{"text": "#include <utt/Configuration.h>\n\n#include <algorithm>\n#include <climits>\n#include <fstream>\n#include <functional>\n#include <random>\n#include <thread>\n#include <vector>\n\n#include <boost/functional/hash.hpp>\n\n#ifdef USE_MULTITHREADING\n# include <omp.h>\n#endif\n\n#include <utt/internal/PicoSha2.h>\n#include <utt/NtlLib.h>\n#include <utt/PolyCrypto.h>\n#include <utt/RangeProof.h>\n\n#include <libff/common/profiling.hpp>\n#include <libff/algebra/field_utils/field_utils.hpp> // get_root_of_unity\n\n#include <xutils/Utils.h>\n\nusing std::endl;\nusing namespace NTL;\n\nnamespace libutt {\n\n    using random_bytes_engine = std::independent_bits_engine<\n        std::default_random_engine, CHAR_BIT, unsigned char>;\n\n    void initialize(unsigned char * randSeed, int size) {\n        (void)randSeed; // TODO: initialize entropy source\n        (void)size;     // TODO: initialize entropy source\n\n        // Apparently, libff logs some extra info when computing pairings\n        libff::inhibit_profiling_info = true;\n\n        // AB: We _info disables printing of information and _counters prevents tracking of profiling information. If we are using the code in parallel, disable both the logs.\n        libff::inhibit_profiling_counters = true;\n\n        // Initializes the default EC curve, so as to avoid \"surprises\"\n        libff::default_ec_pp::init_public_params();\n\n        // Initializes the NTL finite field\n        ZZ p = conv<ZZ> (\"21888242871839275222246405745257275088548364400416034343698204186575808495617\");\n        ZZ_p::init(p);\n\n        NTL::SetSeed(randSeed, size);\n\n#ifdef USE_MULTITHREADING\n        // NOTE: See https://stackoverflow.com/questions/11095309/openmp-set-num-threads-is-not-working\n        loginfo << \"Using \" << getNumCores() << \" threads\" << endl;\n        omp_set_dynamic(0);     // Explicitly disable dynamic teams\n        omp_set_num_threads(static_cast<int>(getNumCores())); // Use 4 threads for all consecutive parallel regions\n#else\n        //loginfo << \"NOT using multithreading\" << endl;\n#endif\n\n        RangeProof::Params::initializeOmegas();\n    }\n\n    GT MultiPairingNaive(const std::vector<G1>& g1, const std::vector<G2>& g2) {\n        assertEqual(g1.size(), g2.size());\n        GT r = GT::one();\n        for(size_t i = 0; i < g1.size(); i++) {\n            r = r * ReducedPairing(g1[i], g2[i]);\n        }\n        return r;\n    }\n    \n    GT MultiPairing(const std::vector<G1>& g1, const std::vector<G2>& g2) {\n        assertEqual(g1.size(), g2.size());\n        using G1_precomp = libff::default_ec_pp::G1_precomp_type;\n        using G2_precomp = libff::default_ec_pp::G2_precomp_type;\n        using Fqk = libff::default_ec_pp::Fqk_type; \n\n        std::vector<G1_precomp> g1p;\n        std::vector<G2_precomp> g2p;\n\n        for(auto el : g1) {\n            g1p.push_back(libff::default_ec_pp::precompute_G1(el));\n        }\n        \n        for(auto el : g2) {\n            g2p.push_back(libff::default_ec_pp::precompute_G2(el));\n        }\n\n        auto numDblMiller = g1.size() / 2;\n        bool singleMiller = (g1.size() % 2 == 1);\n        Fqk r = Fqk::one();\n        for(size_t i = 0; i < numDblMiller; i++) {\n            r = r * libff::default_ec_pp::double_miller_loop(\n                g1p[2*i],\n                g2p[2*i],\n                g1p[2*i + 1],\n                g2p[2*i + 1]\n            );\n        }\n\n        if(singleMiller) {\n            r = r * libff::default_ec_pp::miller_loop(\n                g1p.back(),\n                g2p.back()\n            );\n        }\n\n        return libff::default_ec_pp::final_exponentiation(r);\n    }\n\n    Fr hashToField(const unsigned char * bytes, size_t len) {\n        // hash bytes, but output a hex string not bytes\n        std::string hex;\n        picosha2::hash256_hex_string(bytes, bytes + len, hex);\n        hex.pop_back(); // small enough for BN-P254 field\n\n        // convert hex to mpz_t\n        mpz_t rop;\n        mpz_init(rop);\n        mpz_set_str(rop, hex.c_str(), 16);\n\n        // convert mpz_t to Fr\n        Fr fr = libff::bigint<Fr::num_limbs>(rop);\n        mpz_clear(rop);\n\n        return fr;\n    }\n\n    Fr hashToField(const std::string& message)\n    {\n        return hashToField(reinterpret_cast<const unsigned char*>(message.c_str()), message.size());\n    }\n\n    size_t Fr_num_bytes() {\n        const size_t assumedFieldSize = 32; // bytes\n\n#ifndef NDEBUG\n        // make sure Fr's are actually 32 bytes\n        Fr test = Fr::random_element();\n        std::vector<uint64_t> v = test.to_words();\n        // a byte is 8 bits => 64 bits is 8 bytes => need 4 words in 'v'\n        assertEqual(v.size(), 4);\n#endif\n\n        return assumedFieldSize;\n    }\n\n    void Fr_serialize(const Fr& fr, unsigned char * bytes, size_t capacity) {\n        std::vector<uint64_t> words = fr.to_words();\n        \n        size_t wordSize = sizeof(uint64_t);\n        \n        if (capacity < wordSize * words.size()) {\n            throw std::runtime_error(\"Need larger buffer to serialize Fr\");\n        }\n\n        for(auto& w : words) {\n            std::memcpy(bytes, reinterpret_cast<unsigned char*>(&w), wordSize);         \n            bytes += wordSize;\n        }\n    }\n\n    Fr Fr_deserialize(const unsigned char * bytes, size_t len) {\n        Fr a;\n        size_t wordSize = sizeof(uint64_t);\n        size_t numWords = len / wordSize;\n        std::vector<uint64_t> words(numWords);\n        assertEqual(words.size(), numWords);\n        \n        for(size_t i = 0; i < words.size(); i++) {\n            uint64_t w;\n            std::memcpy(reinterpret_cast<unsigned char*>(&w), bytes, wordSize);\n            bytes += wordSize;\n            words[i] = w;\n        }\n\n        a.from_words(words);\n\n        return a;\n    }\n\n    AutoBuf<unsigned char> frsToBytes(const std::vector<Fr>& frs) {\n        size_t frSize = Fr_num_bytes();\n\n        AutoBuf<unsigned char> buf(frSize * frs.size());\n\n        for(size_t i = 0; i < frs.size(); i++)\n            Fr_serialize(frs[i], buf.getBuf() + i * frSize, frSize);\n\n        return buf;\n    }\n\n    std::vector<Fr> bytesToFrs(const AutoBuf<unsigned char>& buf) {\n        std::vector<Fr> frs;\n\n        size_t frSize = Fr_num_bytes();\n        size_t num = buf.size() / frSize;\n\n        for(size_t i = 0; i < num; i++) {\n            auto val = Fr_deserialize(buf.getBuf() + i*frSize, frSize);\n\n            frs.push_back(val);\n        }\n\n        return frs;\n    }\n\n    void random_bytes(unsigned char * bytes, size_t len)\n    {\n        random_bytes_engine rbe;\n        std::generate(bytes, bytes + len, std::ref(rbe));\n    }\n\n    std::vector<Fr> random_field_elems(size_t num) {\n        std::vector<Fr> p(num);\n        for (size_t i = 0; i < p.size(); i++) {\n            p[i] = Fr::random_element();\n        }\n        return p;\n    }\n\n    size_t getNumCores() {\n        static size_t numCores = std::thread::hardware_concurrency();\n        if(numCores == 0)\n            throw std::runtime_error(\"Could not get number of cores\");\n        return numCores;\n    }\n\n    std::vector<Fr> get_all_roots_of_unity(size_t n) {\n        if(n < 1)\n            throw std::runtime_error(\"Cannot get 0th root-of-unity\");\n\n        size_t N = Utils::smallestPowerOfTwoAbove(n);\n\n        // initialize array of roots of unity\n        Fr omega = libff::get_root_of_unity<Fr>(N);\n        std::vector<Fr> omegas(n);\n        omegas[0] = Fr::one();\n\n        if(n > 1) {\n            omegas[1] = omega;\n            for(size_t i = 2; i < n; i++) {\n                omegas[i] = omega * omegas[i-1];\n            }\n        }\n\n        return omegas;\n    }\n\n    //std::vector<Fr> random_poly(size_t deg) {\n    //    return random_field_elems(deg+1);\n    //}\n\n} // end of namespace libutt\n\nnamespace boost {\n\n    std::size_t hash_value(const libutt::Fr& f)\n    {\n        size_t size;\n        mpz_t rop;\n        mpz_init(rop);\n        f.as_bigint().to_mpz(rop);\n\n        //char *s = mpz_get_str(NULL, 10, rop);\n        //size = strlen(s);\n        //auto h = boost::hash_range<char*>(s, s + size);\n\n        //void (*freefunc)(void *, size_t);\n        //mp_get_memory_functions(NULL, NULL, &freefunc);\n        //freefunc(s, size);\n\n\n        mpz_export(NULL, &size, 1, 1, 1, 0, rop);\n        AutoBuf<unsigned char> buf(static_cast<long>(size));\n\n        mpz_export(buf, &size, 1, 1, 1, 0, rop);\n        auto h = boost::hash_range<unsigned char*>(buf, buf + buf.size());\n\n        mpz_clear(rop);\n        return h;\n    }\n\n} // end of boost namespace\n", "meta": {"hexsha": "79511e65d369fdce6b37edc8ab7c66531359dc42", "size": 8394, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libutt/libutt/src/PolyCrypto.cpp", "max_stars_repo_name": "definitelyNotFBI/utt", "max_stars_repo_head_hexsha": "1695e3a1f81848e19b042cdc4db9cf1d263c26a9", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "libutt/libutt/src/PolyCrypto.cpp", "max_issues_repo_name": "definitelyNotFBI/utt", "max_issues_repo_head_hexsha": "1695e3a1f81848e19b042cdc4db9cf1d263c26a9", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "libutt/libutt/src/PolyCrypto.cpp", "max_forks_repo_name": "definitelyNotFBI/utt", "max_forks_repo_head_hexsha": "1695e3a1f81848e19b042cdc4db9cf1d263c26a9", "max_forks_repo_licenses": ["Apache-2.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.1458333333, "max_line_length": 175, "alphanum_fraction": 0.5773171313, "num_tokens": 2225, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6224593452091672, "lm_q2_score": 0.5621765008857982, "lm_q1q2_score": 0.34993201663335477}}
{"text": "#include \"Weave.h\"\r\n#include \"topology_object.h\"\r\n#include \"face.h\"\r\n#include \"edge.h\"\r\n#include \"vertex.h\"\r\n#include \"logging.h\"\r\n#include \"object_store.h\"\r\n#include \"vector3d.h\"\r\n\r\n#include <map>\r\n#include <ctime>\r\n#include <cmath>\r\n#include <vector>\r\n#include <cstdlib>\r\n#include <utility>\r\n#include <string.h>\r\n#include <iostream>\r\n#include <algorithm>\r\n#include <cinder\\TriMesh.h>\r\n#include <boost\\foreach.hpp>\r\n#include <boost\\tokenizer.hpp>\r\n\r\nusing namespace std;\r\nusing namespace ci;\r\nusing namespace boost;\r\n\r\nTile::Tile(unsigned int num_vertices) {\r\n    n = num_vertices;\r\n    marked = -1;\r\n    knotType=PLUS1;\r\n    //knotType=TWIST1;\r\n    visited=0; isCrv1Used=NO; isCrv2Used = NO;\r\n}\r\n\r\nTile::~Tile() { up.clear(); down.clear(); }\r\n\r\nVector3D Tile::trilinearInterpolation(float u,float v,float t)\r\n{\r\n    Vector3D ret_val(0.0,0.0,0.0);\r\n    ret_val += ( ((1-u)*(1-v)*(1-t))*(*up[0]) );\r\n    ret_val += ( (u*(1-v)*(1-t))*(*up[1]) );\r\n    ret_val += ( (u*v*(1-t))*(*up[2]) );\r\n    ret_val += ( ((1-u)*v*(1-t))*(*up[3]) );\r\n\r\n    ret_val += ( ((1-u)*(1-v)*t)*(*down[0]) );\r\n    ret_val += ( (u*(1-v)*t)*(*down[1]) );\r\n    ret_val += ( (u*v*t)*(*down[2]) );\r\n    ret_val += ( ((1-u)*v*t)*(*down[3]) );\r\n    return ret_val;\r\n}\r\n\r\nvoid Tile::generateCurvePoints()\r\n{\r\n    /* Safety purposes clear both vector of points */\r\n    curve1.clear();\r\n    curve2.clear();\r\n    Vector3D *tmp;\r\n    tmp = new Vector3D(trilinearInterpolation(0.5,0.25,0.5));\r\n    curve1.push_back(tmp);\r\n    tmp = new Vector3D(trilinearInterpolation(0.5,0.5,0.75));\r\n    curve1.push_back(tmp);\r\n    tmp = new Vector3D(trilinearInterpolation(0.5,0.75,0.5));\r\n    curve1.push_back(tmp);\r\n\r\n    tmp = new Vector3D(trilinearInterpolation(0.25,0.5,0.5));\r\n    curve2.push_back(tmp);\r\n    tmp = new Vector3D(trilinearInterpolation(0.5,0.5,0.25));\r\n    curve2.push_back(tmp);\r\n    tmp = new Vector3D(trilinearInterpolation(0.75,0.5,0.5));\r\n    curve2.push_back(tmp);\r\n}\r\n\r\nvoid Tile::generateTwist1Points()\r\n{\r\n    /* A call to this function clears out any curve points\r\n     *generated for PLUS1/PLUS2 with new twisted curves points */\r\n    curve1.clear();\r\n    curve2.clear();\r\n    Vector3D *tmp;\r\n    tmp = new Vector3D(trilinearInterpolation(0.5,0.25,0.75));\r\n    curve1.push_back(tmp);\r\n    tmp = new Vector3D(trilinearInterpolation(0.75,0.5,0.5));\r\n    curve1.push_back(tmp);\r\n    tmp = new Vector3D(trilinearInterpolation(0.25,0.75,0.25));\r\n    curve1.push_back(tmp);\r\n\r\n    tmp = new Vector3D(trilinearInterpolation(0.75,0.25,0.25));\r\n    curve2.push_back(tmp);\r\n    tmp = new Vector3D(trilinearInterpolation(0.25,0.5,0.5));\r\n    curve2.push_back(tmp);\r\n    tmp = new Vector3D(trilinearInterpolation(0.5,0.75,0.75));\r\n    curve2.push_back(tmp);\r\n}\r\n\r\nvoid Tile::generateTwist2Points()\r\n{\r\n    /* A call to this function clears out any curve points\r\n     *generated for PLUS1/PLUS2 with new twisted curves points */\r\n    curve1.clear();\r\n    curve2.clear();\r\n    Vector3D *tmp;\r\n    tmp = new Vector3D(trilinearInterpolation(0.5,0.25,0.75));\r\n    curve1.push_back(tmp);\r\n    tmp = new Vector3D(trilinearInterpolation(0.25,0.5,0.5));\r\n    curve1.push_back(tmp);\r\n    tmp = new Vector3D(trilinearInterpolation(0.75,0.75,0.25));\r\n    curve1.push_back(tmp);\r\n\r\n    tmp = new Vector3D(trilinearInterpolation(0.25,0.25,0.25));\r\n    curve2.push_back(tmp);\r\n    tmp = new Vector3D(trilinearInterpolation(0.75,0.5,0.5));\r\n    curve2.push_back(tmp);\r\n    tmp = new Vector3D(trilinearInterpolation(0.5,0.75,0.75));\r\n    curve2.push_back(tmp);\r\n}\r\n\r\nvoid Tile::swapCurveMidPoints()\r\n{\r\n    int mid         = curve1.size()/2;\r\n    Vector3D *temp  = curve1[mid];\r\n    curve1[mid]     = curve2[mid];\r\n    curve2[mid]     = temp;\r\n}\r\n\r\nvoid Tile::findCurveAndDirection(Vertex *end, Vertex *othEnd, bool &isCurve1, bool &isRev)\r\n{\r\n    if( knotType == PLUS1 || knotType == PLUS2 ) {\r\n        if( (actVerts[0] == end && actVerts[1] == othEnd) ||\r\n                (actVerts[1] == end && actVerts[0] == othEnd) ) {\r\n            isCurve1    = true;\r\n            isRev       = false;\r\n        } else if( (actVerts[1] == end && actVerts[2] == othEnd) ||\r\n                (actVerts[2] == end && actVerts[1] == othEnd) ) {\r\n            isCurve1    = false;\r\n            isRev       = true;\r\n        }else if( (actVerts[2] == end && actVerts[3] == othEnd) ||\r\n                (actVerts[3] == end && actVerts[2] == othEnd) ) {\r\n            isCurve1    = true;\r\n            isRev       = true;\r\n        }else if( (actVerts[3] == end && actVerts[0] == othEnd) ||\r\n                (actVerts[0] == end && actVerts[3] == othEnd) ) {\r\n            isCurve1    = false;\r\n            isRev       = false;\r\n        }\r\n    } else if( knotType == TWIST1 ) {\r\n        if( (actVerts[0] == end && actVerts[1] == othEnd) ||\r\n                (actVerts[1] == end && actVerts[0] == othEnd) ) {\r\n            isCurve1 = true;\r\n            isRev = false;\r\n        } else if( (actVerts[1] == end && actVerts[2] == othEnd) ||\r\n                (actVerts[2] == end && actVerts[1] == othEnd) ) {\r\n            isCurve1 = false;\r\n            isRev = false;\r\n        }else if( (actVerts[2] == end && actVerts[3] == othEnd) ||\r\n                (actVerts[3] == end && actVerts[2] == othEnd) ) {\r\n            isCurve1 = false;\r\n            isRev = true;\r\n        }else if( (actVerts[3] == end && actVerts[0] == othEnd) ||\r\n                (actVerts[0] == end && actVerts[3] == othEnd) ) {\r\n            isCurve1 = true;\r\n            isRev = true;\r\n        }\r\n    } else if( knotType == TWIST2 ) {\r\n        if( (actVerts[0] == end && actVerts[1] == othEnd) ||\r\n                (actVerts[1] == end && actVerts[0] == othEnd) ) {\r\n            isCurve1 = true;\r\n            isRev = false;\r\n        } else if( (actVerts[1] == end && actVerts[2] == othEnd) ||\r\n                (actVerts[2] == end && actVerts[1] == othEnd) ) {\r\n            isCurve1 = true;\r\n            isRev = true;\r\n        }else if( (actVerts[2] == end && actVerts[3] == othEnd) ||\r\n                (actVerts[3] == end && actVerts[2] == othEnd) ) {\r\n            isCurve1 = false;\r\n            isRev = true;\r\n        }else if( (actVerts[3] == end && actVerts[0] == othEnd) ||\r\n                (actVerts[0] == end && actVerts[3] == othEnd) ) {\r\n            isCurve1 = false;\r\n            isRev = false;\r\n        }\r\n    }\r\n}\r\n\r\n\r\n\r\n\r\n\r\nstring Mesh::getOriginalFileName(string filename,string &path)\r\n{\r\n    vector<string> subStrs;\r\n    char_separator<char> sep(\"\\\\\");\r\n    typedef tokenizer< boost::char_separator<char> > Tokenizer;\r\n    Tokenizer tok(filename,sep);\r\n    for(Tokenizer::iterator beg=tok.begin(); beg!=tok.end(); ++beg) subStrs.push_back(*beg);\r\n    filename = subStrs[subStrs.size()-1];\r\n    for( unsigned int k=0; k < subStrs.size()-1; ++k )\r\n        path = path +\"\\\\\"+ subStrs[k];\r\n    path\t+= \"\\\\\";\r\n    sep\t= char_separator<char>(\".\");\r\n    tok\t= Tokenizer(filename,sep);\r\n    subStrs.clear();\r\n    for(Tokenizer::iterator beg=tok.begin(); beg!=tok.end(); ++beg) subStrs.push_back(*beg);\r\n    return subStrs[0];\r\n}\r\n\r\nvoid Mesh::cacheFaceNormals()\r\n{\r\n    std::set<Face*> faces = this->GetFaces();\r\n    for(std::set<Face*>::iterator fIter = faces.begin(); fIter!= faces.end(); fIter++)\r\n    {\r\n        float *temp = GetFaceNormal(*fIter);\r\n        Vector3D *triadInput = new Vector3D(temp[0],temp[1],temp[2]);\r\n        triadInput->normalize();\r\n        fNormals_[*fIter] = triadInput;\r\n    }\r\n}\r\n\r\nvoid Mesh::calculateVertexNormals()\r\n{\r\n    for (std::set<Vertex*>::iterator it = vertices_.begin(); it != vertices_.end(); ++it)\r\n    {\r\n        /* For each vertex find the averaged normal of the Faces */\r\n        Vector3D *vertexNormal = new Vector3D(0.0f,0.0f,0.0f);\r\n        Vertex *currVertex = (*it);\r\n        std::vector<Edge*> currRotEdg = currVertex->GetRotation();\r\n        unsigned int facesDone = currRotEdg.size();\r\n\r\n        for(unsigned int iter=0; iter<facesDone; iter++)\r\n        {\r\n            float *temp = GetFaceNormal(face_map_[currVertex][currRotEdg[iter]->GetOtherEnd(currVertex)]);\r\n            Vector3D vtmp(temp[0],temp[1],temp[2]);\r\n            (*vertexNormal) += vtmp;\r\n        }\r\n        (*vertexNormal) /= facesDone;\r\n        vertexNormal->normalize();\r\n        vNormals_[currVertex] = vertexNormal;\r\n    }\r\n}\r\n\r\nvoid Mesh::prepareTextureSets()\r\n{\r\n    texture_Bcorner.push_back('a');\r\n    texture_Bcorner.push_back('b');\r\n    texture_Bcorner.push_back('c');\r\n    texture_Bcorner.push_back('d');\r\n\r\n    texture_Ycorner.push_back('e');\r\n    texture_Ycorner.push_back('f');\r\n    texture_Ycorner.push_back('g');\r\n    texture_Ycorner.push_back('h');\r\n\r\n    compat_Bcorner.push_back('a');\r\n    compat_Bcorner.push_back('c');\r\n    compat_Bcorner.push_back('f');\r\n    compat_Bcorner.push_back('h');\r\n\r\n    compat_Ycorner.push_back('b');\r\n    compat_Ycorner.push_back('d');\r\n    compat_Ycorner.push_back('e');\r\n    compat_Ycorner.push_back('g');\r\n}\r\n\r\nvoid Mesh::createTileTexCoordList()\r\n{\r\n    add2DCircularList(&_0aHead,'a',0.0,0.0);\r\n    add2DCircularList(&_0aHead,'b',1.0,0.0);\r\n    add2DCircularList(&_0aHead,'c',1.0,1.0);\r\n    add2DCircularList(&_0aHead,'d',0.0,1.0);\r\n\r\n    add2DCircularList(&_0bHead,'e',0.0,0.0);\r\n    add2DCircularList(&_0bHead,'f',1.0,0.0);\r\n    add2DCircularList(&_0bHead,'g',1.0,1.0);\r\n    add2DCircularList(&_0bHead,'h',0.0,1.0);\r\n    showDCircularList(_0aHead);\r\n    showDCircularList(_0bHead);\r\n}\r\n\r\nbool Mesh::anyUnvisitedFaces(Face **retFacePntr,Tile **correspondingTile)\r\n{\r\n    for (std::set<Face*>::iterator fi = faces_.begin(); fi != faces_.end(); ++fi)\r\n    {\r\n        Tile *currTile = tile_map_[(*fi)];\r\n        if( currTile->visited < 2 )\r\n        {\r\n            *retFacePntr = (*fi);\r\n            *correspondingTile = currTile;\r\n            return true;\r\n        }\r\n    }\r\n    return false;\r\n}\r\n\r\nbool Mesh::LoadObjFile(const char *objFileName)\r\n{\r\n    /* clear object */\r\n    if ( !(vertices_.empty()) ) {\r\n        Clear();\r\n    }\r\n    /* save file name */\r\n    fileName_ = objFileName;\r\n\r\n    /* ------------------   load .obj file   ------------------ */\r\n    FILE* inFile = fopen (objFileName, \"r\");\r\n    if ( !inFile ) {\r\n        ci::app::console() << \"Can not open file: \" << fileName_;\r\n    }\r\n    else {\r\n        ci::app::console() << \"Model file: \" << fileName_;\r\n    }\r\n    /* 1st pass - read all the vertices */\r\n    char buffer[512] = {0};\r\n    float* coord;\r\n    Vertex* newVertex;\r\n    std::map<int, Vertex*> id_vertex;\t/* vert ID starts from 1 */\r\n    while ( fscanf( inFile, \"%s\", buffer) != EOF ) {\r\n        if ( 'v' == buffer[0] ) {\r\n            switch ( buffer[1] ) {\r\n                case '\\0':\r\n                    coord = new float[3];\r\n                    if ( fscanf(inFile, \"%f %f %f\", &(coord[0]), &(coord[1]), &(coord[2])) != 3 ) {\r\n                        delete [] coord;\r\n                        std::cout << \"vertex \" << vertices_.size() << \" wrong\" << std::endl;\r\n                        return false;\r\n                    }\r\n                    else {\r\n                        newVertex = AddVertex();\r\n                        SetCoords(newVertex,coord);\r\n                        id_vertex[vertices_.size()] = newVertex;\r\n                        break;\r\n                    }\r\n\r\n                case 'n':\r\n                case 't':\r\n                    break;\r\n            }\r\n        }\r\n    }\r\n    ci::app::console() << \"Number of vertices: \" << vertices_.size() << std::endl;\r\n\r\n    /* 2nd pass - add edges */\r\n    numFacesObjFile_ = 0;\r\n    int tempID, startID, endID;\r\n    Edge* preEdge;\r\n    Edge* newEdge;\r\n    std::pair<int, int> edgeIDpair;\t/* start <= end */\r\n    std::pair<int, int> firstPair;\t/* 1st edge pair */\r\n    std::map<std::pair<int, int>, Edge*> vertex_id_edge;\t/* vert ID starts from 1 */\r\n    std::map<std::pair<int, int>, Edge*>::iterator it_edge;\r\n    rewind(inFile);\r\n    /* process each face */\r\n    while ( fscanf(inFile, \"%s\", buffer) != EOF) {\r\n        if ( 'f' == buffer[0] && '\\0' == buffer[1] )\r\n        {\r\n            std::vector<int> fVertices;\r\n            while ( fscanf(inFile, \"%s\", buffer) != EOF )\r\n            {\r\n                if ( 1 == sscanf(buffer, \"%d\", &tempID) )\r\n                {\r\n                    fVertices.push_back(tempID);\r\n                }\r\n                else\r\n                {\t\t/* finish one face */\r\n                    numFacesObjFile_++;\r\n                    if ( fVertices.size() < 2 )\r\n                    {\r\n                        std::cout << \"Face only has \" << fVertices.size() << \" vertices\" << std::endl;\r\n                        return false;\r\n                    }\r\n                    /* 1st edge */\r\n                    startID = fVertices[0];\r\n                    endID = fVertices[1];\r\n                    if ( startID > endID ) {\r\n                        std::swap(startID, endID);\r\n                    }\r\n                    edgeIDpair.first = startID;\r\n                    edgeIDpair.second = endID;\r\n                    firstPair = edgeIDpair;\r\n                    it_edge = vertex_id_edge.find(edgeIDpair);\r\n                    if ( vertex_id_edge.end() == it_edge ) {\t/* edge not created */\r\n                        newEdge = ObjectStore::GetInstance()->CreateEdge(id_vertex[startID], id_vertex[endID]);\r\n                        edges_.insert(newEdge);\r\n                        vertex_id_edge[edgeIDpair] = newEdge;\r\n                    }\r\n                    else {\r\n                        newEdge = it_edge->second;\r\n                    }\r\n                    preEdge = newEdge;\r\n                    for (unsigned int i = 1; i < fVertices.size(); i++ )\r\n                    {\r\n                        startID = fVertices[i];\r\n                        endID = fVertices[(i+1 == fVertices.size() ? 0 : i+1)];\r\n                        if ( startID > endID ) {\r\n                            std::swap(startID, endID);\r\n                        }\r\n                        edgeIDpair.first = startID;\r\n                        edgeIDpair.second = endID;\r\n                        it_edge = vertex_id_edge.find(edgeIDpair);\r\n                        if ( vertex_id_edge.end() == it_edge) {\t\t// edge not created\r\n                            newEdge = ObjectStore::GetInstance()->CreateEdge(id_vertex[startID], id_vertex[endID]);\r\n                            edges_.insert(newEdge);\r\n                            vertex_id_edge[edgeIDpair] = newEdge;\r\n                        }\r\n                        else {\r\n                            newEdge = it_edge->second;\r\n                        }\r\n                        /* add to rotation */\r\n                        id_vertex[fVertices[i]]->InsertEdgeInRotation_load(newEdge, preEdge);\r\n                        preEdge = newEdge;\r\n                    }\r\n                    // last & 1st edges in rotation\r\n                    newEdge = vertex_id_edge[firstPair];\r\n                    id_vertex[fVertices[0]]->InsertEdgeInRotation_load(newEdge, preEdge);\r\n\r\n                    fVertices.clear();\t// start a new face\r\n\r\n                    if ( 'f' != buffer[0] )\r\n                    {\r\n                        break;\r\n                    }\r\n                }\r\n            }\r\n        }\r\n    }\r\n    fclose(inFile);\r\n    ci::app::console() << \"Number of edges: \" << edges_.size() << std::endl;\r\n    ci::app::console() << \"Number of faces: \" << numFacesObjFile_ << std::endl;\r\n    ReComputeFaces();\r\n    calculateVertexNormals();\r\n    cacheFaceNormals();\r\n\r\n    pumpMesh();\r\n    ci::app::console() << \"Face extrusion completed.\" << std::endl;\r\n    traverseFaces_PLUSES();\r\n    //traverseFaces_TWISTS();\r\n    ci::app::console() << \"Tile traversal completed.\" << std::endl;\r\n    if(baseCrvType==CATMULLROMSPLINE) generateCtrlPnts4InterpolationSpline();\r\n    generateWngTubes();\r\n    return true;\r\n}\r\n\r\nbool Mesh::Clear()\r\n{\r\n    for (std::set<Vertex*>::iterator it = vertices_.begin();\r\n            it != vertices_.end(); ++it) {\r\n        (*it)->ClearRotations();\r\n        ObjectStore::GetInstance()->DeleteVertex(*it);\r\n    }\r\n    vertices_.clear();\r\n\r\n    for (std::set<Edge*>::iterator it = edges_.begin();\r\n            it != edges_.end(); ++it) {\r\n        ObjectStore::GetInstance()->DeleteEdge(*it);\r\n    }\r\n    edges_.clear();\r\n\r\n    for (std::set<Face*>::iterator it = faces_.begin();\r\n            it != faces_.end(); ++it) {\r\n        ObjectStore::GetInstance()->DeleteFace(*it);\r\n    }\r\n    faces_.clear();\r\n    face_map_.clear();\r\n    fNormals_.clear();\r\n    vNormals_.clear();\r\n    tile_map_.clear();\r\n    wngCrvs.clear();\r\n    mWvngTubes.clear();\r\n    numFacesObjFile_ = 0;\r\n    vertex_treeIDMap_.clear();\r\n    treeID_VertexSetMap_.clear();\r\n    return true;\r\n}\r\n\r\nvoid Mesh::drawMesh(bool wireframe, bool lighting, bool drawBaseMesh, bool paintedMesh, bool tiledMesh, bool drawWeaving,\r\n        GLint TURN1_OR_TOUCH, GLint TURN2_OR_CROSS, GLint DOUBLE_CROSS)\r\n{\r\n    if(paintedMesh)\r\n    {\r\n        glPushMatrix();\r\n        for( std::set<Face*>::iterator fi = faces_.begin(); fi != faces_.end(); ++fi )\r\n        {\r\n            Tile* currT = tile_map_[*fi];\r\n            // float *normal = GetFaceNormal(*fi);\r\n            if( currT->tex == OA ) {\r\n                glBindTexture(GL_TEXTURE_2D, TURN1_OR_TOUCH);\r\n            }\r\n            else if( currT->tex == OB ) {\r\n                glBindTexture(GL_TEXTURE_2D, TURN2_OR_CROSS);\r\n            }\r\n\r\n            glBegin(GL_QUADS);\r\n            // glNormal3fv(normal);\r\n            for( vector<Vertex*>::iterator vIt = currT->actVerts.begin(); vIt != currT->actVerts.end(); ++vIt )\r\n            {\r\n                Vector3D *vnormal = vNormals_[*vIt];\r\n                float *currVertex = coords_[*vIt];\r\n                DCircularList *uvmap = currT->texCoords[*vIt];\r\n                glNormal3f(vnormal->DX(), vnormal->DY(), vnormal->DZ());\r\n                glTexCoord2f( uvmap->u, uvmap->v );\r\n                glVertex3fv( currVertex );\r\n            }\r\n            glEnd();\r\n            glBindTexture(GL_TEXTURE_2D, NULL);\r\n        }\r\n        glPopMatrix();\r\n    }\r\n\r\n    if(drawBaseMesh) {\r\n        glPushMatrix();\r\n        if(lighting) glEnable(GL_COLOR_MATERIAL);\r\n        glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);\r\n        glColor4f(0.5f, 0.5f, 0.5f, 1.0f);\r\n        for( std::set<Face*>::iterator fi = faces_.begin(); fi != faces_.end(); ++fi )\r\n        {\r\n            std::vector<Vertex*> cFVertices = (*fi)->GetVertices();\r\n            glColor4f(1.0,1.0,1.0,1.0);\r\n            glBegin(GL_POLYGON);\r\n            glNormal3fv( GetFaceNormal(*fi) );\r\n            for(unsigned int i=0;i<cFVertices.size();i++)\r\n                glVertex3fv(GetVertexCoordinates(cFVertices[i]));\r\n            glEnd();\r\n        }\r\n        glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);\r\n        if(lighting) glDisable(GL_COLOR_MATERIAL);\r\n        glPopMatrix();\r\n    }\r\n\r\n    if(tiledMesh)\r\n    {\r\n        glPushMatrix();\r\n        glDisable(GL_CULL_FACE);\r\n        if(lighting) glEnable(GL_COLOR_MATERIAL);\r\n        glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);\r\n\r\n        for( std::set<Face*>::iterator fi = faces_.begin(); fi != faces_.end(); ++fi )\r\n        {\r\n            Vector3D *vtmp;\r\n            Tile* currT = tile_map_[*fi];\r\n            glBegin(GL_QUADS);\r\n            float *normal = GetFaceNormal(*fi);\r\n            glColor4f(1.0f, 0.0f, 0.0f, 1.0f);\t// RED\r\n            glNormal3fv(normal);\r\n            for( Vec3DPtrIter it = currT->up.begin(); it != currT->up.end(); it++ )\r\n            {\r\n                vtmp = *it;\r\n                glVertex3f( vtmp->DX(), vtmp->DY(), vtmp->DZ() );\r\n            }\r\n\r\n            glColor4f(0.0f, 1.0f, 0.0f, 1.0f);\t// GREEN\r\n            glNormal3f(-normal[0],-normal[1],-normal[2]);\r\n            for( Vec3DPtrIter it = currT->down.begin(); it != currT->down.end(); it++ )\r\n            {\r\n                vtmp = *it;\r\n                glVertex3f( vtmp->DX(), vtmp->DY(), vtmp->DZ() );\r\n            }\r\n            glEnd();\r\n\r\n            glPointSize(4.0f);\r\n            glBegin(GL_POINTS);\r\n            vtmp = currT->curve1[1];\r\n            glColor4f(1.0f, 0.0f, 0.0f, 1.0f);\t// RED\r\n            glVertex3f( vtmp->DX(), vtmp->DY(), vtmp->DZ() );\r\n            vtmp = currT->curve2[1];\r\n            glColor4f(0.0f, 1.0f, 0.0f, 1.0f);\t// GREEN\r\n            glVertex3f( vtmp->DX(), vtmp->DY(), vtmp->DZ() );\r\n            glEnd();\r\n            glPointSize(1.0f);\r\n        }\r\n        glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);\r\n        if(lighting) glDisable(GL_COLOR_MATERIAL);\r\n        glEnable(GL_CULL_FACE);\r\n        glPopMatrix();\r\n    }\r\n\r\n    if(drawWeaving)\r\n    {\r\n        glPushMatrix();\r\n        GLfloat mat_amb[]       = {0.05,0.05,0.05,1.0};\r\n        GLfloat mat_diff[4];\r\n        GLfloat mat_spec[]      = {1.0,1.0,1.0,1.0};\r\n        GLfloat mat_shininess[] = {100.0};\r\n        float r = 0.3f;\r\n        float g = 0.3f;\r\n        float b = 0.3f;\r\n        for (std::vector<WvngTube*>::iterator tube = mWvngTubes.begin(); tube != mWvngTubes.end(); ++tube)\r\n        {\r\n            WvngTube* currTube = *tube;\r\n            if( r < 1.0f )\r\n                r += 0.2f;\r\n            else if( g < 1.0f )\r\n                g += 0.2f;\r\n            else if( b < 1.0f )\r\n                b += 0.2f;\r\n            else {\r\n                r = 0.3f;\r\n                g = 0.3f;\r\n                b = 0.3f;\r\n            }\r\n            mat_diff[0] = r; mat_diff[1] = g; mat_diff[2] = b; mat_diff[3] = 1.0;\r\n            glPushMatrix();\r\n            glMaterialfv(GL_FRONT_AND_BACK,GL_AMBIENT,mat_amb);\r\n            glMaterialfv(GL_FRONT_AND_BACK,GL_DIFFUSE,mat_diff);\r\n            glMaterialfv(GL_FRONT,GL_SPECULAR,mat_spec);\r\n            glMaterialfv(GL_FRONT,GL_SHININESS,mat_shininess);\r\n\r\n            gluBeginSurface(theNurb);\r\n            gluNurbsSurface(theNurb, currTube->uKnotCount, currTube->uKnots,\r\n                    currTube->vKnotCount, currTube->vKnots,\r\n                    currTube->uStride, currTube->vStride, currTube->ctlPoints,\r\n                    currTube->uOrder, currTube->vOrder, GL_MAP2_VERTEX_3);\r\n            gluEndSurface(theNurb);\r\n            glPopMatrix();\r\n        }\r\n        /*glEnable(GL_COLOR_MATERIAL);\r\n          glColor4f(1.0,1.0,1.0,1.0f);\r\n          glPointSize(4.0);\r\n          glBegin(GL_POINTS);\r\n          for(vector<wngCrvCtrlPnts>::iterator it = wngCrvs.begin(); it != wngCrvs.end(); ++it )\r\n          {\r\n          for(Vec3DPtrIter v = (*it).myPnts.begin(); v != (*it).myPnts.end(); ++v )\r\n          {\r\n          Vector3D tmp = *(*v);\r\n          glVertex3f(tmp.DX(),tmp.DY(),tmp.DZ());\r\n          }\r\n          break;\r\n          }\r\n          glEnd();\r\n          glPointSize(1.0);\r\n          glDisable(GL_COLOR_MATERIAL);\r\n          */\r\n        glPopMatrix();\r\n    }\r\n}\r\n\r\nvoid Mesh::pumpMesh()\r\n{\r\n    /* Now move around faces and generate the positions */\r\n    for (std::set<Face*>::iterator it = faces_.begin(); it != faces_.end(); ++it)\r\n    {\r\n        std::vector<Vertex*> faceVertices = (*it)->GetVertices();\r\n        Tile *myTile = new Tile(faceVertices.size());\r\n\r\n        for(unsigned int i=0; i<faceVertices.size(); ++i )\r\n        {\r\n            float *v = GetVertexCoordinates(faceVertices[i]);\r\n            Vector3D base(v[0],v[1],v[2]);\r\n            Vector3D normal = unitVector(*vNormals_[faceVertices[i]]);\r\n            Vector3D *up = new Vector3D(base + TILE_THICKNESS*normal);      /* Move up */\r\n            Vector3D *down = new Vector3D(base - TILE_THICKNESS*normal);    /* Move down */\r\n            myTile->addUpAndDown(faceVertices[i],up,down);\r\n        }\r\n        myTile->generateCurvePoints();\r\n        tile_map_[(*it)] = myTile;\r\n    }\r\n}\r\n\r\nvoid Mesh::resetTexturePaintMarkers()\r\n{\r\n    set<Face*> faces = this->GetFaces();\r\n    for(set<Face*>::iterator fIter = faces.begin(); fIter!= faces.end(); ++fIter) {\r\n        tile_map_[*fIter]->marked\t= -1;\r\n        tile_map_[*fIter]->tex\t\t= OA;\r\n        tile_map_[*fIter]->texCoords.clear();\r\n    }\r\n    this->vertex_treeIDMap_.clear();\r\n    this->treeID_VertexSetMap_.clear();\r\n}\r\n\r\nvoid Mesh::paintTexturesOnMesh()\r\n{\r\n    for( std::set<Vertex*>::iterator vi = vertices_.begin(); vi != vertices_.end(); ++vi )\r\n    {\r\n        char myColor\t\t\t='0';\r\n        std::vector<Edge*> edges= (*vi)->GetRotation();\r\n        Vertex *end1\t\t\t= *vi;\r\n        Face *prevF\t\t\t\t= 0;\r\n        for(vector<Edge*>::iterator eIter = edges.begin(); eIter != edges.end(); ++eIter)\r\n        {\r\n            Vertex *end2= (*eIter)->GetOtherEnd(end1);\r\n            Face* f\t\t= face_map_[end1][end2];\r\n            if( tile_map_[f]->marked != -1 ) {\r\n                Tile* t\t\t= tile_map_[f];\r\n                char mark\t= t->texCoords[end2]->name;\r\n                vector<char>::iterator idx = find(texture_Bcorner.begin(), texture_Bcorner.end(), mark);\r\n                myColor = texture_Bcorner.at(((idx-texture_Bcorner.begin())+1)%FACE_NUM_V);\r\n                break;\r\n            }\r\n            prevF = f;\r\n        }\r\n\r\n        prevF = 0;\r\n        if( myColor=='0' ) myColor = (*texture_Bcorner.begin());\r\n        for( vector<Edge*>::iterator eIter = edges.begin(); eIter != edges.end(); ++eIter )\r\n        {\r\n            Vertex *end2= (*eIter)->GetOtherEnd(end1);\r\n            Face* f\t\t= face_map_[end1][end2];\r\n            if( tile_map_[f]->marked == -1 )\r\n            {\r\n                Tile* t = tile_map_[f];\r\n                vector<char>::iterator clrIndex = find(texture_Bcorner.begin(),texture_Bcorner.end(),myColor);\r\n                int myClrPos\t\t\t\t\t= clrIndex - texture_Bcorner.begin();\r\n\r\n                int idx1,idx2;\r\n                for(vector<Vertex*>::iterator tV = t->actVerts.begin(); tV != t->actVerts.end(); ++tV )\r\n                {\r\n                    if(end1 == *tV)\r\n                        idx1 = tV - t->actVerts.begin();\r\n                    else if(end2 == *tV)\r\n                        idx2 = tV - t->actVerts.begin();\r\n                }\r\n\r\n                DCircularList *vTexPntr = rotateDCircularListFrwd(_0aHead,myClrPos);\r\n                DCircularList *iter\t\t= vTexPntr;\r\n                if(idx1 < idx2)\r\n                {\r\n                    do {\r\n                        t->texCoords[t->actVerts[idx1]]\t= iter;\r\n                        iter = iter->next;\r\n                        if( !(++idx1 < 4) ) idx1 = 0;\r\n                    }while(iter!=vTexPntr);\r\n                } else {\r\n                    do {\r\n                        t->texCoords[t->actVerts[idx1]]\t= iter;\r\n                        iter = iter->prev;\r\n                        if( !(--idx1 >= 0) ) idx1 = 3;\r\n                    }while(iter!=vTexPntr);\r\n                }\r\n                t->marked\t= t->marked + 1;\r\n                t->tex\t\t= OA;\r\n            }\r\n            prevF = f;\r\n        }\r\n    }\r\n}\r\n\r\nbool Mesh::findUnConnectedFace(Face **returnValue, Vertex **returnVertex)\r\n{\r\n    set<Face*> faces = this->GetFaces();\r\n    for(set<Face*>::iterator fIter = faces.begin(); fIter != faces.end(); ++fIter)\r\n    {\r\n        if(tile_map_[*fIter]->marked==0 && tile_map_[*fIter]->tex==OA) {\r\n            *returnValue = *fIter;\r\n            vector<Vertex*> myVertices = (*returnValue)->GetVertices();\r\n            Tile *currT = tile_map_[(*returnValue)];\r\n            for( vector<Vertex*>::iterator vit = myVertices.begin(); vit != myVertices.end(); ++vit) {\r\n                if( currT->texCoords[*vit]->name == 'b' || currT->texCoords[*vit]->name == 'd' ) {\r\n                    *returnVertex = *vit;\r\n                    break;\r\n                }\r\n            }\r\n            return true;\r\n        }\r\n    }\r\n    *returnValue = 0;\r\n    return false;\r\n}\r\n\r\nvoid Mesh::incMarkerOnFacesIncident(Vertex *v)\r\n{\r\n    vector<Edge*> rot\t= v->GetRotation();\r\n    for(vector<Edge*>::iterator eIt = rot.begin(); eIt != rot.end(); ++eIt)\r\n    {\r\n        Tile *t = tile_map_[ face_map_[v][(*eIt)->GetOtherEnd(v)] ];\r\n        t->marked = t->marked + 1;\r\n    }\r\n}\r\n\r\nVertex* Mesh::getNextPivotInFace(Face *f, Vertex *v, char &colorName, int &index1, int &index2)\r\n{\r\n    Tile *t = tile_map_[f];\r\n    vector<char> matchBInOB(2);\r\n    vector<char>::iterator newColorEnd = set_intersection(compat_Ycorner.begin(),compat_Ycorner.end(), texture_Bcorner.begin(), texture_Bcorner.end(), matchBInOB.begin());\r\n    colorName = (*matchBInOB.begin());\r\n    vector<Vertex*>::iterator index = find(t->actVerts.begin(), t->actVerts.end(),v);\r\n    if(index != t->actVerts.end()) {\r\n        index1 = index - t->actVerts.begin();\r\n        index2 = (index1+1)%FACE_NUM_V;\r\n        return t->actVerts.at( ( ( index1+2 )%FACE_NUM_V ) );\r\n    } else {\r\n        app::console()<<\"Vertex not found, something fishy!\"<<endl;\r\n        return 0;\r\n    }\r\n}\r\n\r\nvoid Mesh::connectBlobsPhase1()\r\n{\r\n    int curveID\t\t= 0;\r\n    bool firstRun\t= true;\r\n    Face *prevFace\t= 0;\r\n    Vertex *prevPivot= 0;\r\n    Face *currFace\t= 0;\r\n    Vertex *pivot\t= 0;\r\n    Tile *currT\t\t= 0;\r\n    Colour BLUE(0.0,0.0,1.0);\r\n    Colour CYAN(0.0,1.0,1.0);\r\n\r\n    while(1)\r\n    {\r\n        if( prevPivot!=0 && (currFace==prevFace || currFace==0) ) {\r\n            app::console()<<\"Marking neighbour faces of the last vertex of the current curve\"<<endl;\r\n            incMarkerOnFacesIncident(prevPivot);\r\n            app::console()<<\"Done marking for this curve, proceeding to next curve if eligible.\"<<endl;\r\n            prevPivot = 0;\r\n        }\r\n        if( !firstRun && currFace == prevFace && findUnConnectedFace(&currFace,&prevPivot) ) {\r\n            ++curveID;\r\n            app::console()<<\"New tree started. I think so at least ;)\"<<endl;\r\n        }\r\n        if(firstRun) {\r\n            currFace\t= (*this->GetFaces().begin());\r\n            currT\t\t= tile_map_[currFace];\r\n            vector<Vertex*> myVertices = currFace->GetVertices();\r\n            for( vector<Vertex*>::iterator vit = myVertices.begin(); vit != myVertices.end(); ++vit) {\r\n                if( currT->texCoords[*vit]->name == 'b' || currT->texCoords[*vit]->name == 'd' ) {\r\n                    prevPivot = *vit;\r\n                    break;\r\n                }\r\n            }\r\n            firstRun\t= false;\r\n        }\r\n\r\n        if( currFace!=prevFace && currFace!=0 && prevPivot!= 0 )\r\n        {\r\n            char colorName;\r\n            int idx1,idx2;\r\n            currT\t\t\t\t= tile_map_[currFace];\r\n            incMarkerOnFacesIncident(prevPivot);\r\n            idx1\t\t\t\t= idx2 = -1;\r\n            pivot\t\t\t\t= getNextPivotInFace(currFace,prevPivot,colorName,idx1,idx2);\r\n\r\n            if(! ( idx1>=0 && idx1<4 & idx2>=0 && idx2<4 ) ) app::console()<<\"idx1,idx2 \"<<idx1<<\" \"<<idx2<<endl;\r\n\r\n            vector<char>::iterator findOut\t= find(texture_Ycorner.begin(), texture_Ycorner.end(),colorName);\r\n            DCircularList *vTexPntr\t\t\t= rotateDCircularListFrwd(_0bHead, findOut-texture_Ycorner.begin());\r\n            DCircularList *iter\t\t\t\t= vTexPntr;\r\n            if(idx1 < idx2) {\r\n                do {\r\n                    currT->texCoords[currT->actVerts[idx1]]\t= iter;\r\n                    iter = iter->next;\r\n                    if( !(++idx1 < 4) ) idx1 = 0;\r\n                }while(iter!=vTexPntr);\r\n            } else {\r\n                do {\r\n                    currT->texCoords[currT->actVerts[idx1]]\t= iter;\r\n                    iter = iter->prev;\r\n                    if( !(--idx1 >= 0) ) idx1 = 3;\r\n                }while(iter!=vTexPntr);\r\n            }\r\n            currT->tex\t\t= OB;\r\n            vertex_treeIDMap_[prevPivot] = curveID;\r\n            vertex_treeIDMap_[pivot] = curveID;\r\n            treeID_VertexSetMap_[curveID].insert(prevPivot);\r\n            treeID_VertexSetMap_[curveID].insert(pivot);\r\n            prevPivot\t\t= pivot;\r\n            prevFace\t\t= currFace;\r\n\r\n            vector<Edge*> rot\t= pivot->GetRotation();\r\n            for(vector<Edge*>::iterator eIt = rot.begin(); eIt != rot.end(); ++eIt)\r\n            {\r\n                Face *temp = face_map_[pivot][(*eIt)->GetOtherEnd(pivot)];\r\n                Tile *t = tile_map_[temp];\r\n                if( t->marked == 0 && t->tex == OA && prevFace!=temp ) {\r\n                    currFace = temp;\r\n                    break;\r\n                }\r\n            }\r\n        }else{\r\n            app::console()<<\"No next face assigned => Either all connected or we have disconnected trees.\"<<endl;\r\n            app::console()<<\"Curves extracted : \"<<treeID_VertexSetMap_.size()<<endl;\r\n            break;\r\n        }\r\n    }\r\n}\r\n\r\nvoid Mesh::connectBlobsPhase2()\r\n{\r\n    if( treeID_VertexSetMap_.size() > 1 )\r\n    {\r\n        vector<char> matchBInOB(2);\r\n        vector<char>::iterator newColorEnd = set_intersection(compat_Ycorner.begin(),compat_Ycorner.end(), texture_Bcorner.begin(), texture_Bcorner.end(), matchBInOB.begin());\r\n        vector<char>::iterator findOut\t= find(texture_Ycorner.begin(), texture_Ycorner.end(),(*matchBInOB.begin()));\r\n        DCircularList *vTexPntr\t\t\t= rotateDCircularListFrwd(_0bHead, findOut-texture_Ycorner.begin());\r\n        DCircularList *iter\t\t\t\t= vTexPntr;\r\n\r\n        set<Face*> faces = this->GetFaces();\r\n        for(set<Face*>::iterator fIter = faces.begin(); fIter != faces.end(); ++fIter)\r\n        {\r\n            Tile *t\t\t= tile_map_[*fIter];\r\n            if( t->tex == OA && t->marked >= 2 )\r\n            {\r\n                Vertex *jumpIn = 0;\r\n                vector<Vertex*> myVertices = (*fIter)->GetVertices();\r\n                for( vector<Vertex*>::iterator vit = myVertices.begin(); vit != myVertices.end(); ++vit) {\r\n                    if( t->texCoords[*vit]->name == 'b' || t->texCoords[*vit]->name == 'd' ) {\r\n                        jumpIn = *vit;\r\n                        break;\r\n                    }\r\n                }\r\n                vector<Vertex*>::iterator index = find(t->actVerts.begin(), t->actVerts.end(),jumpIn);\r\n                int idx1 = index - t->actVerts.begin();\r\n                int idx2 = (idx1+2)%FACE_NUM_V;\r\n                Vertex *jumpOtherEnd = t->actVerts.at(idx2);\r\n                int v1CrvId = vertex_treeIDMap_[jumpIn];\r\n                int v2CrvId = vertex_treeIDMap_[jumpOtherEnd];\r\n                if( v1CrvId != v2CrvId )\r\n                {\r\n                    set<Vertex*> c2Vertices = treeID_VertexSetMap_[v2CrvId];\r\n                    for(set<Vertex*>::iterator it = c2Vertices.begin(); it != c2Vertices.end(); ++it ) {\r\n                        treeID_VertexSetMap_[v1CrvId].insert(*it);\r\n                        vertex_treeIDMap_[*it] = v1CrvId;\r\n                    }\r\n                    map<int, std::set<Vertex*>>::iterator eraseCrv = treeID_VertexSetMap_.find(v2CrvId);\r\n                    treeID_VertexSetMap_.erase(eraseCrv);\r\n                    // Now assign tex coords according to new Tile OB for this face using idx1 & idx2\r\n                    if(idx1 < idx2) {\r\n                        do {\r\n                            t->texCoords[t->actVerts[idx1]]\t= iter;\r\n                            iter = iter->next;\r\n                            if( !(++idx1 < 4) ) idx1 = 0;\r\n                        }while(iter!=vTexPntr);\r\n                    } else {\r\n                        do {\r\n                            t->texCoords[t->actVerts[idx1]]\t= iter;\r\n                            iter = iter->prev;\r\n                            if( !(--idx1 >= 0) ) idx1 = 3;\r\n                        }while(iter!=vTexPntr);\r\n                    }\r\n                    t->tex\t\t= OB;\r\n                } else {\r\n                    app::console()<<\"Phase 2: OA Tile with same curve corners\"<<endl;\r\n                }\r\n            }\r\n        }\r\n        app::console()<<\"Number of curves after phase 2 : \"<<treeID_VertexSetMap_.size()<<endl;\r\n    } else\r\n        app::console()<<\"Only one curves extracted, proceed to phase 3 to process isolated vertices\"<<endl;\r\n}\r\n\r\nvoid Mesh::connectBlobsPhase3()\r\n{\r\n    if( vertex_treeIDMap_.size() != vertices_.size() )\r\n    {\r\n        vector<char> matchBInOB(2);\r\n        vector<char>::iterator newColorEnd = set_intersection(compat_Ycorner.begin(),compat_Ycorner.end(), texture_Bcorner.begin(), texture_Bcorner.end(), matchBInOB.begin());\r\n        vector<char>::iterator findOut\t= find(texture_Ycorner.begin(), texture_Ycorner.end(),(*matchBInOB.begin()));\r\n        DCircularList *vTexPntr\t\t\t= rotateDCircularListFrwd(_0bHead, findOut-texture_Ycorner.begin());\r\n        DCircularList *iter\t\t\t\t= vTexPntr;\r\n\r\n        set<Face*> faces = this->GetFaces();\r\n        for(set<Face*>::iterator fIter = faces.begin(); fIter != faces.end(); ++fIter)\r\n        {\r\n            Tile *t\t\t= tile_map_[*fIter];\r\n            if( t->tex == OA && t->marked == 1 ) {\r\n                // Faces incident on isolated vertices will be still with markers set to 1\r\n                Vertex *jumpIn = 0;\r\n                vector<Vertex*> myVertices = (*fIter)->GetVertices();\r\n                for( vector<Vertex*>::iterator vit = myVertices.begin(); vit != myVertices.end(); ++vit) {\r\n                    if( t->texCoords[*vit]->name == 'b' || t->texCoords[*vit]->name == 'd' ) {\r\n                        jumpIn = *vit;\r\n                        break;\r\n                    }\r\n                }\r\n                vector<Vertex*>::iterator index = find(t->actVerts.begin(), t->actVerts.end(),jumpIn);\r\n                int idx1 = index - t->actVerts.begin();\r\n                int idx2 = (idx1+2)%FACE_NUM_V;\r\n                Vertex *jumpOtherEnd = t->actVerts.at(idx2);\r\n                map<Vertex*,int>::iterator treeId = vertex_treeIDMap_.find(jumpIn);\r\n                int v1CrvId = ( treeId != vertex_treeIDMap_.end() ? treeId->second : -1 );\r\n                treeId = vertex_treeIDMap_.find(jumpOtherEnd);\r\n                int v2CrvId = ( treeId != vertex_treeIDMap_.end() ? treeId->second : -1 );\r\n                if( (v1CrvId!=-1 && v2CrvId==-1) || (v2CrvId!=-1 && v1CrvId==-1) ) {\r\n                    if(v1CrvId!=-1 && v2CrvId==-1) {\r\n                        vertex_treeIDMap_[jumpOtherEnd] = v1CrvId;\r\n                        treeID_VertexSetMap_[v1CrvId].insert(jumpOtherEnd);\r\n                        incMarkerOnFacesIncident(jumpOtherEnd);\r\n                    } else {\r\n                        vertex_treeIDMap_[jumpIn] = v2CrvId;\r\n                        treeID_VertexSetMap_[v2CrvId].insert(jumpIn);\r\n                        incMarkerOnFacesIncident(jumpIn);\r\n                    }\r\n                    // Now assign tex coords according to new Tile OB for this face using idx1 & idx2\r\n                    if(idx1 < idx2) {\r\n                        do {\r\n                            t->texCoords[t->actVerts[idx1]]\t= iter;\r\n                            iter = iter->next;\r\n                            if( !(++idx1 < 4) ) idx1 = 0;\r\n                        }while(iter!=vTexPntr);\r\n                    } else {\r\n                        do {\r\n                            t->texCoords[t->actVerts[idx1]]\t= iter;\r\n                            iter = iter->prev;\r\n                            if( !(--idx1 >= 0) ) idx1 = 3;\r\n                        }while(iter!=vTexPntr);\r\n                    }\r\n                    t->tex\t\t= OB;\r\n                }\r\n            }\r\n        }\r\n    } else\r\n        app::console()<<\"No isolated vertices, hence phase 3 complete.\"<<endl;\r\n}\r\n\r\nvoid Mesh::writeWavefrontObj()\r\n{\r\n    // get output file names and paths\r\n    string path;\r\n    vector<string> extns; extns.push_back(\"*.obj,*.OBJ\");\r\n    getOriginalFileName(fileName_,path);\r\n    fs::path newObjFilePath = app::getSaveFilePath(path,extns);\r\n    if( !newObjFilePath.empty() ) {\r\n        string mtlpath;\r\n        string mtlfilename = getOriginalFileName(newObjFilePath.string(),mtlpath) + \".mtl\";\r\n        mtlpath += mtlfilename;\r\n        string bcornerMtl = \"BlueCorner\";\r\n        string ycornerMtl = \"YellowCorner\";\r\n\r\n        //create index for vertices, normals and texture coordinates\r\n        map<Vertex*,int> v2IndexMap;\r\n        map<Vertex*,int> vNormalIndexMap;\r\n        map<DCircularList*,int> texOAIndexMap, texOBIndexMap;\r\n        int vIndex=1;\r\n        for(set<Vertex*>::iterator vit = vertices_.begin(); vit != vertices_.end(); ++vit)\r\n            v2IndexMap[*vit] = vIndex++;\r\n        int vNormalIndex = 1;\r\n        for(map<Vertex*, Vector3D*>::iterator vnit = vNormals_.begin(); vnit != vNormals_.end(); ++vnit)\r\n            vNormalIndexMap[vnit->first] = vNormalIndex++;\r\n        DCircularList *itOA = _0aHead->prev;\r\n        int texOAIndex = 1;\r\n        DCircularList *itOB = _0bHead->prev;\r\n        int texOBIndex = 1;\r\n        for(int k=0; k<4; ++k) {\r\n            texOAIndexMap[itOA] = texOAIndex++; texOBIndexMap[itOB] = texOBIndex++;\r\n            itOA = itOA->prev; itOB = itOB->prev;\r\n        }\r\n\r\n        //Now write the OBJ file and material files\r\n        FILE *objHandle = fopen(newObjFilePath.string().c_str(),\"w\");\r\n        fprintf(objHandle,\"%s\",\"# File format : Wavefront OBJ file \\n\");\r\n        fprintf(objHandle,\"%s\",\"# Author : Pradeep Garigipati\\n\");\r\n        fprintf(objHandle,\"%s\",\"# Date : 03/05/2010\\n\");\r\n        fprintf(objHandle,\"%s\",\"# -----------------------------------\\n\\n\");\r\n\r\n        fprintf(objHandle,\"%s\",\"# Using the below material file \\n\");\r\n        fprintf(objHandle,\"mtllib %s\\n\\n\",mtlfilename.c_str());\r\n\r\n        fprintf(objHandle,\"# Vertices set size = %d\\n\",v2IndexMap.size());\r\n        for(map<Vertex*,int>::iterator v = v2IndexMap.begin(); v!= v2IndexMap.end(); ++v){\r\n            float *coords = coords_[v->first];\r\n            //app::console()<<\"v \"<<coords[0]<<\" \"<<coords[1]<<\" \"<<coords[2];\r\n            fprintf(objHandle,\"v %f %f %f\\n\",coords[0],coords[1],coords[2]);\r\n        }\r\n        fprintf(objHandle,\"%s\",\"\\n\\n\");\r\n\r\n        fprintf(objHandle,\"# Vertex normals set size = %d\\n\",vNormalIndexMap.size());\r\n        for(map<Vertex*,int>::iterator vn = vNormalIndexMap.begin(); vn!= vNormalIndexMap.end(); ++vn){\r\n            Vector3D *normal = vNormals_[vn->first];\r\n            //app::console()<<\"v \"<<normal->DX()<<\" \"<<normal->DY()<<\" \"<<normal->DZ()];\r\n            fprintf(objHandle,\"vn %f %f %f\\n\",normal->DX(),normal->DY(),normal->DZ());\r\n        }\r\n        fprintf(objHandle,\"%s\",\"\\n\\n\");\r\n\r\n        fprintf(objHandle,\"# Texture coordinates set size = %d\\n\",texOAIndexMap.size());\r\n        for(map<DCircularList*,int>::iterator texCrd = texOAIndexMap.begin(); texCrd!= texOAIndexMap.end(); ++texCrd){\r\n            DCircularList *textureCoord = texCrd->first;\r\n            fprintf(objHandle,\"vt %f %f\\n\",textureCoord->u,textureCoord->v);\r\n        }\r\n        fprintf(objHandle,\"%s\",\"\\n\\n\");\r\n\r\n        fprintf(objHandle,\"# Faces set size = %d\\n\",faces_.size());\r\n        fprintf(objHandle,\"usemtl %s\\n\", bcornerMtl.c_str() );\r\n        for(set<Face*>::iterator f = faces_.begin(); f != faces_.end(); ++f) {\r\n            Tile *t = tile_map_[*f];\r\n            if(t->tex == OA) {\r\n                string out=\"f \";\r\n                vector<Vertex*> verts = (*f)->GetVertices();\r\n                for(vector<Vertex*>::iterator vit = verts.begin(); vit != verts.end(); ++vit) {\r\n                    stringstream ss;\r\n                    string hold;\r\n                    ss<<v2IndexMap[*vit]<<\"/\"<<texOAIndexMap[t->texCoords[*vit]]<<\"/\"<<vNormalIndexMap[*vit];\r\n                    ss>>hold;\r\n                    out = out + \" \" + hold;\r\n                }\r\n                fprintf(objHandle,\"%s\\n\",out.c_str());\r\n            }\r\n        }\r\n        fprintf(objHandle,\"usemtl %s\\n\", ycornerMtl.c_str() );\r\n        for(set<Face*>::iterator f = faces_.begin(); f != faces_.end(); ++f) {\r\n            Tile *t = tile_map_[*f];\r\n            if(t->tex == OB) {\r\n                string out=\"f \";\r\n                vector<Vertex*> verts = (*f)->GetVertices();\r\n                for(vector<Vertex*>::iterator vit = verts.begin(); vit != verts.end(); ++vit) {\r\n                    stringstream ss;\r\n                    string hold;\r\n                    ss<<v2IndexMap[*vit]<<\"/\"<< texOBIndexMap[t->texCoords[*vit]]<<\"/\"<<vNormalIndexMap[*vit];\r\n                    ss>>hold;\r\n                    out = out + \" \" + hold;\r\n                }\r\n                fprintf(objHandle,\"%s\\n\",out.c_str());\r\n            }\r\n        }\r\n        fprintf(objHandle,\"%s\",\"\\n\");\r\n        fclose(objHandle);\r\n\r\n        FILE *mtlHandle = fopen(mtlfilename.c_str(),\"w\");\r\n        fprintf(mtlHandle,\"%s\",\"# File format : Material MTL file \\n\");\r\n        fprintf(mtlHandle,\"%s\",\"# Author : Pradeep Garigipati\\n\");\r\n        fprintf(mtlHandle,\"%s\",\"# Date : 03/05/2010\\n\\n\");\r\n\r\n        fprintf(mtlHandle,\"newmtl %s\\n\",bcornerMtl.c_str());\r\n        fprintf(mtlHandle,\"Ka %f %f %f\\n\", 1.0, 1.0, 1.0);\r\n        fprintf(mtlHandle,\"Kd %f %f %f\\n\", 1.0, 1.0, 1.0);\r\n        fprintf(mtlHandle,\"Ks %f %f %f\\n\", 0.0, 0.0, 0.0);\r\n        fprintf(mtlHandle,\"d %f\\n\", 1.0);\r\n        fprintf(mtlHandle,\"illum %d\\n\", 2);\r\n        fprintf(mtlHandle,\"map_Ka -clamp on %s\\n\", \"0a.png\");\r\n        fprintf(mtlHandle,\"map_Kd -clamp on %s\\n\", \"0a.png\");\r\n        fprintf(mtlHandle,\"map_Ks -clamp on %s\\n\", \"0a.png\");\r\n\r\n        fprintf(mtlHandle,\"newmtl %s\\n\", ycornerMtl.c_str());\r\n        fprintf(mtlHandle,\"Ka %f %f %f\\n\", 1.0, 1.0, 1.0);\r\n        fprintf(mtlHandle,\"Kd %f %f %f\\n\", 1.0, 1.0, 1.0);\r\n        fprintf(mtlHandle,\"Ks %f %f %f\\n\", 0.0, 0.0, 0.0);\r\n        fprintf(mtlHandle,\"d %f\\n\", 1.0);\r\n        fprintf(mtlHandle,\"illum %d\\n\", 2);\r\n        fprintf(mtlHandle,\"map_Ka -clamp on %s\\n\", \"0b.png\");\r\n        fprintf(mtlHandle,\"map_Kd -clamp on %s\\n\", \"0b.png\");\r\n        fprintf(mtlHandle,\"map_Ks -clamp on %s\\n\", \"0b.png\");\r\n        fclose(mtlHandle);\r\n    }\r\n}\r\n\r\nvoid Mesh::traverseFaces_PLUSES()\r\n{\r\n    Face* currFace  = 0;\r\n    Tile* currTile  = 0;\r\n\r\n    while(anyUnvisitedFaces(&currFace,&currTile))\r\n    {\r\n        bool currCurve          = true;\r\n        Edge* prevDirectionEdge = 0;\r\n        KNOT prevFaceKnotType   = NOTHING;\r\n        Face* prevFace          = 0;\r\n        Tile* prevTile          = 0;\r\n        Edge* directionEdge     = 0;\r\n        wngCrvCtrlPnts currCrv;\r\n\r\n        while(currCurve)\r\n        {\r\n            if(currTile->visited == 0)\r\n            {\r\n                Edge *edg       = 0;\r\n                bool isCurve1,isReverse;\r\n                Vertex *start   = 0;\r\n                Vertex *end     = 0;\r\n                // Pick the entry/random-entry edge and start,end vertices of the corresponding face\r\n                if(directionEdge==0)\r\n                    edg = (*(currFace->GetEdges().begin()));\r\n                else\r\n                    edg = directionEdge;\r\n                start = edg->GetStart();\r\n                end   = edg->GetEnd();\r\n                if( face_map_[start][end] != currFace ) {\r\n                    Vertex* temp= start;\r\n                    start       = end;\r\n                    end         = temp;\r\n                }\r\n                // Alternate the Tile patterns OR  generate TWIST points in even-face cycle\r\n                if(prevFaceKnotType == currTile->knotType && (prevFaceKnotType == PLUS1 || prevFaceKnotType == PLUS2)) {\r\n                    currTile->swapCurveMidPoints();\r\n                    currTile->knotType = ( prevFaceKnotType == PLUS1 ? PLUS2 : PLUS1 );\r\n                }else if(currTile->knotType == TWIST1)\r\n                    currTile->generateTwist1Points();\r\n                else if(currTile->knotType == TWIST2)\r\n                    currTile->generateTwist2Points();\r\n                // find the curve of entry based on the entry edge\r\n                currTile->findCurveAndDirection(start,end,isCurve1,isReverse);\r\n                // Push the corresponding curve points\r\n                if(isCurve1) {\r\n                    if(isReverse) {\r\n                        /*for( std::vector<Vector3D*>::reverse_iterator iter = currTile->curve1.rbegin(); iter != currTile->curve1.rend(); iter++ )\r\n                          currCrv.myPnts.push_back(*iter);*/\r\n                        for( int crv=currTile->curve1.size()-2; crv>0; crv--)\r\n                            currCrv.myPnts.push_back(currTile->curve1[crv]);\r\n                        currTile->isUsedCrv1Rev = YES;\r\n                        Vector3D *derv = new Vector3D((*(*currTile->curve1.begin()))-(*(*currTile->curve1.rbegin())));\r\n                        derv->normalize();\r\n                        currCrv.derivatives.push_back(derv);\r\n                    } else {\r\n                        /*for( std::vector<Vector3D*>::iterator iter = currTile->curve1.begin(); iter != currTile->curve1.end(); iter++ )\r\n                          currCrv.myPnts.push_back(*iter);*/\r\n                        for( int crv=1; crv<currTile->curve1.size()-1; crv++)\r\n                            currCrv.myPnts.push_back(currTile->curve1[crv]);\r\n                        currTile->isUsedCrv1Rev = NO;\r\n                        Vector3D *derv = new Vector3D((*(*currTile->curve1.rbegin()))-(*(*currTile->curve1.begin())));\r\n                        derv->normalize();\r\n                        currCrv.derivatives.push_back(derv);\r\n                    }\r\n                    currTile->isCrv1Used = YES;\r\n                } else {\r\n                    if(isReverse) {\r\n                        /*for( std::vector<Vector3D*>::reverse_iterator iter = currTile->curve2.rbegin(); iter != currTile->curve2.rend(); iter++ )\r\n                          currCrv.myPnts.push_back(*iter);*/\r\n                        for( int crv=currTile->curve2.size()-2; crv>0; crv--)\r\n                            currCrv.myPnts.push_back(currTile->curve2[crv]);\r\n                        currTile->isUsedCrv2Rev = YES;\r\n                        Vector3D *derv = new Vector3D((*(*currTile->curve2.begin()))-(*(*currTile->curve2.rbegin())));\r\n                        derv->normalize();\r\n                        currCrv.derivatives.push_back(derv);\r\n                    } else {\r\n                        /*for( std::vector<Vector3D*>::iterator iter = currTile->curve2.begin(); iter != currTile->curve2.end(); iter++ )\r\n                          currCrv.myPnts.push_back(*iter);*/\r\n                        for( int crv=1; crv<currTile->curve2.size()-1; crv++)\r\n                            currCrv.myPnts.push_back(currTile->curve2[crv]);\r\n                        currTile->isUsedCrv2Rev = NO;\r\n                        Vector3D *derv = new Vector3D((*(*currTile->curve2.rbegin()))-(*(*currTile->curve2.begin())));\r\n                        derv->normalize();\r\n                        currCrv.derivatives.push_back(derv);\r\n                    }\r\n                    currTile->isCrv2Used = YES;\r\n                }\r\n                // store face normal to help generate thread\r\n                currCrv.triadNorms.push_back(fNormals_[currFace]);\r\n                currTile->visited++;\r\n                // extract the direction edge based on curve used\r\n                if(currTile->knotType == TWIST1) {\r\n                    if(isCurve1)\r\n                        directionEdge = (isReverse==true ? end->GetNextEdgeInRotation(edg) : start->GetPreviousEdgeInRotation(edg));\r\n                    else\r\n                        directionEdge = (isReverse==true ? start->GetPreviousEdgeInRotation(edg) : end->GetNextEdgeInRotation(edg));\r\n                } else if(currTile->knotType == TWIST2) {\r\n                    if(isCurve1)\r\n                        directionEdge = (isReverse==true ? start->GetPreviousEdgeInRotation(edg) : end->GetNextEdgeInRotation(edg));\r\n                    else\r\n                        directionEdge = (isReverse==true ? end->GetNextEdgeInRotation(edg) : start->GetPreviousEdgeInRotation(edg));\r\n                } else {\r\n                    Edge* adjEdge = end->GetNextEdgeInRotation(edg);\r\n                    Vertex *adjEdgOtherEnd = adjEdge->GetOtherEnd(end);\r\n                    directionEdge = adjEdgOtherEnd->GetNextEdgeInRotation(adjEdge);\r\n                }\r\n                // Store the current face details as prev face details for next face\r\n                prevDirectionEdge = edg;\r\n                prevFaceKnotType = currTile->knotType;\r\n                prevFace = currFace;\r\n                prevTile = currTile;\r\n                // Update current Face and corresponding Tile variables\r\n                start = directionEdge->GetStart();\r\n                end = directionEdge->GetEnd();\r\n                if( face_map_[start][end] == currFace ) {\r\n                    Vertex* temp= start;\r\n                    start       = end;\r\n                    end         = temp;\r\n                }\r\n                currFace        = face_map_[start][end];\r\n                currTile        = tile_map_[currFace];\r\n            }\r\n            else if( currTile->visited == 1 )\r\n            {\r\n                Edge *edg       = 0;\r\n                Vertex *start   = 0;\r\n                Vertex *end     = 0;\r\n                bool isCurve1,isReverse;\r\n\r\n                if(directionEdge==0) {\r\n                    // Loop over the edges to find an edge which emits an unvisited curve\r\n                    std::vector<Edge*> currFaceEdges = currFace->GetEdges();\r\n                    for( std::vector<Edge*>::iterator e = currFaceEdges.begin(); e!=currFaceEdges.end(); e++ )\r\n                    {\r\n                        Edge* tmp   = *e;\r\n                        start       = tmp->GetStart();\r\n                        end         = tmp->GetEnd();\r\n                        if( face_map_[start][end] != currFace ) {\r\n                            Vertex* temp= start;\r\n                            start       = end;\r\n                            end         = temp;\r\n                        }\r\n                        currTile->findCurveAndDirection(start,end,isCurve1,isReverse);\r\n                        if((currTile->isCrv1Used == YES && isCurve1) || (currTile->isCrv2Used == YES && !isCurve1))\r\n                            continue;\r\n                        else {\r\n                            edg = tmp;\r\n                            break;\r\n                        }\r\n                    }\r\n                }\r\n                else {// Use the common edge from prev step\r\n                    edg = directionEdge;\r\n                    start = edg->GetStart();\r\n                    end = edg->GetEnd();\r\n                    if( face_map_[start][end] != currFace ) {\r\n                        Vertex* temp = start;\r\n                        start = end;\r\n                        end = temp;\r\n                    }\r\n                    currTile->findCurveAndDirection(start,end,isCurve1,isReverse);\r\n                }\r\n\r\n                if( (prevFaceKnotType == PLUS1 || prevFaceKnotType == PLUS2) &&\r\n                        (currTile->knotType == PLUS1 || currTile->knotType == PLUS2) )\r\n                {\r\n                    if((currTile->isCrv1Used == YES && isCurve1) ||\r\n                            (currTile->isCrv2Used == YES && !isCurve1))\r\n                    {\r\n                        if( prevFaceKnotType==currTile->knotType )\r\n                        {\r\n                            // Remove already pushed curve vertices\r\n                            for(unsigned int rem=0; rem<3; rem++)\r\n                                currCrv.myPnts.pop_back();\r\n                            // Change prev face KNOT type; choose TWIST1\r\n                            prevTile->knotType = TWIST1;\r\n                            prevTile->visited--;\r\n                            // Now reset the state variables to prev state and continue with new KNOT type.\r\n                            // Don't change the visited of the currTile\r\n                            prevFaceKnotType = TWIST1;\r\n                            currFace = prevFace;\r\n                            currTile = prevTile;\r\n                            directionEdge = prevDirectionEdge;\r\n                        } else {\r\n                            // This is one special case where we should close curve\r\n                            // since we entered the face along the edge we started the curve\r\n                            // for(int i=0;i<1;i++) {\r\n                            currCrv.myPnts.push_back(currCrv.myPnts[0]);\r\n                            currCrv.derivatives.push_back(currCrv.derivatives[0]);\r\n                            currCrv.triadNorms.push_back(currCrv.triadNorms[0]);\r\n                            // }\r\n                            currCurve = false;\r\n                            wngCrvs.push_back(currCrv);\r\n                        }\r\n                    }\r\n                    else\r\n                    {\r\n                        // If curve we are gng to use is not used yet; just proceed in normal fashion\r\n                        // Add points and compute next direction and update prev* variables\r\n                        if(isCurve1) {\r\n                            if(isReverse) {\r\n                                /*for( std::vector<Vector3D*>::reverse_iterator iter = currTile->curve1.rbegin(); iter != currTile->curve1.rend(); iter++ )\r\n                                  currCrv.myPnts.push_back(*iter);*/\r\n                                for( int crv=currTile->curve1.size()-2; crv>0; crv--)\r\n                                    currCrv.myPnts.push_back(currTile->curve1[crv]);\r\n                                Vector3D *derv = new Vector3D((*(*currTile->curve1.begin()))-(*(*currTile->curve1.rbegin())));\r\n                                derv->normalize();\r\n                                currCrv.derivatives.push_back(derv);\r\n                            } else {\r\n                                /*for( std::vector<Vector3D*>::iterator iter = currTile->curve1.begin(); iter != currTile->curve1.end(); iter++ )\r\n                                  currCrv.myPnts.push_back(*iter);*/\r\n                                for( int crv=1; crv<currTile->curve1.size()-1; crv++)\r\n                                    currCrv.myPnts.push_back(currTile->curve1[crv]);\r\n                                Vector3D *derv = new Vector3D((*(*currTile->curve1.rbegin()))-(*(*currTile->curve1.begin())));\r\n                                derv->normalize();\r\n                                currCrv.derivatives.push_back(derv);\r\n                            }\r\n                            currTile->isCrv1Used = YES;\r\n                        } else {\r\n                            if(isReverse) {\r\n                                /*for( std::vector<Vector3D*>::reverse_iterator iter = currTile->curve2.rbegin(); iter != currTile->curve2.rend(); iter++ )\r\n                                  currCrv.myPnts.push_back(*iter);*/\r\n                                for( int crv=currTile->curve2.size()-2; crv>0; crv--)\r\n                                    currCrv.myPnts.push_back(currTile->curve2[crv]);\r\n                                Vector3D *derv = new Vector3D((*(*currTile->curve2.begin()))-(*(*currTile->curve2.rbegin())));\r\n                                derv->normalize();\r\n                                currCrv.derivatives.push_back(derv);\r\n                            } else {\r\n                                /*for( std::vector<Vector3D*>::iterator iter = currTile->curve2.begin(); iter != currTile->curve2.end(); iter++ )\r\n                                  currCrv.myPnts.push_back(*iter);*/\r\n                                for( int crv=1; crv<currTile->curve2.size()-1; crv++)\r\n                                    currCrv.myPnts.push_back(currTile->curve2[crv]);\r\n                                Vector3D *derv = new Vector3D((*(*currTile->curve2.rbegin()))-(*(*currTile->curve2.begin())));\r\n                                derv->normalize();\r\n                                currCrv.derivatives.push_back(derv);\r\n                            }\r\n                            currTile->isCrv2Used = YES;\r\n                        }\r\n                        currCrv.triadNorms.push_back(fNormals_[currFace]);\r\n                        currTile->visited++;\r\n                        // Store the current face details as prev face details for next face\r\n                        prevDirectionEdge = edg;\r\n                        prevFaceKnotType = currTile->knotType;\r\n                        prevFace = currFace;\r\n                        prevTile = currTile;\r\n                        // compute next direction\r\n                        Edge* adjEdge = end->GetNextEdgeInRotation(edg);\r\n                        Vertex *adjEdgOtherEnd = adjEdge->GetOtherEnd(end);\r\n                        directionEdge = adjEdgOtherEnd->GetNextEdgeInRotation(adjEdge);\r\n                        // Update current Face and corresponding Tile variables\r\n                        start = directionEdge->GetStart();\r\n                        end = directionEdge->GetEnd();\r\n                        if( face_map_[start][end] == currFace ) {\r\n                            Vertex* temp = start;\r\n                            start = end;\r\n                            end = temp;\r\n                        }\r\n                        currFace = face_map_[start][end];\r\n                        currTile = tile_map_[currFace];\r\n                    }\r\n                }\r\n                else\r\n                {\r\n                    currTile->findCurveAndDirection(start,end,isCurve1,isReverse);\r\n                    if(currTile->knotType == TWIST1)\r\n                        currTile->generateTwist1Points();\r\n                    else if(currTile->knotType == TWIST2)\r\n                        currTile->generateTwist2Points();\r\n\r\n                    if(isCurve1) {\r\n                        if(isReverse) {\r\n                            /*for( std::vector<Vector3D*>::reverse_iterator iter = currTile->curve1.rbegin(); iter != currTile->curve1.rend(); iter++ )\r\n                              currCrv.myPnts.push_back(*iter);*/\r\n                            for( int crv=currTile->curve1.size()-2; crv>0; crv--)\r\n                                currCrv.myPnts.push_back(currTile->curve1[crv]);\r\n                            Vector3D *derv = new Vector3D((*(*currTile->curve1.begin()))-(*(*currTile->curve1.rbegin())));\r\n                            derv->normalize();\r\n                            currCrv.derivatives.push_back(derv);\r\n                        } else {\r\n                            /*for( std::vector<Vector3D*>::iterator iter = currTile->curve1.begin(); iter != currTile->curve1.end(); iter++ )\r\n                              currCrv.myPnts.push_back(*iter);*/\r\n                            for( int crv=1; crv<currTile->curve1.size()-1; crv++)\r\n                                currCrv.myPnts.push_back(currTile->curve1[crv]);\r\n                            Vector3D *derv = new Vector3D((*(*currTile->curve1.rbegin()))-(*(*currTile->curve1.begin())));\r\n                            derv->normalize();\r\n                            currCrv.derivatives.push_back(derv);\r\n                        }\r\n                        currTile->isCrv1Used = YES;\r\n                    } else {\r\n                        if(isReverse) {\r\n                            /*for( std::vector<Vector3D*>::reverse_iterator iter = currTile->curve2.rbegin(); iter != currTile->curve2.rend(); iter++ )\r\n                              currCrv.myPnts.push_back(*iter);*/\r\n                            for( int crv=currTile->curve2.size()-2; crv>0; crv--)\r\n                                currCrv.myPnts.push_back(currTile->curve2[crv]);\r\n                            Vector3D *derv = new Vector3D((*(*currTile->curve2.begin()))-(*(*currTile->curve2.rbegin())));\r\n                            derv->normalize();\r\n                            currCrv.derivatives.push_back(derv);\r\n                        } else {\r\n                            /*for( std::vector<Vector3D*>::iterator iter = currTile->curve2.begin(); iter != currTile->curve2.end(); iter++ )\r\n                              currCrv.myPnts.push_back(*iter);*/\r\n                            for( int crv=1; crv<currTile->curve2.size()-1; crv++)\r\n                                currCrv.myPnts.push_back(currTile->curve2[crv]);\r\n                            Vector3D *derv = new Vector3D((*(*currTile->curve2.rbegin()))-(*(*currTile->curve2.begin())));\r\n                            derv->normalize();\r\n                            currCrv.derivatives.push_back(derv);\r\n                        }\r\n                        currTile->isCrv2Used = YES;\r\n                    }\r\n                    currCrv.triadNorms.push_back(fNormals_[currFace]);\r\n                    currTile->visited++;\r\n                    // Store the current face details as prev face details for next face\r\n                    prevDirectionEdge = edg;\r\n                    prevFaceKnotType = currTile->knotType;\r\n                    prevFace = currFace;\r\n                    prevTile = currTile;\r\n\r\n                    if(currTile->knotType == TWIST1) {\r\n                        if(isCurve1)\r\n                            directionEdge = (isReverse==true ? start->GetPreviousEdgeInRotation(edg) : end->GetNextEdgeInRotation(edg));\r\n                        else\r\n                            directionEdge = (isReverse==true ? end->GetNextEdgeInRotation(edg) : start->GetPreviousEdgeInRotation(edg));\r\n                    } else if(currTile->knotType == TWIST2) {\r\n                        if(isCurve1)\r\n                            directionEdge = (isReverse==true ? end->GetNextEdgeInRotation(edg) : start->GetPreviousEdgeInRotation(edg));\r\n                        else\r\n                            directionEdge = (isReverse==true ? start->GetPreviousEdgeInRotation(edg) : end->GetNextEdgeInRotation(edg));\r\n                    } else {\r\n                        Edge* adjEdge = end->GetNextEdgeInRotation(edg);\r\n                        Vertex *adjEdgOtherEnd = adjEdge->GetOtherEnd(end);\r\n                        directionEdge = adjEdgOtherEnd->GetNextEdgeInRotation(adjEdge);\r\n                    }\r\n                    // Update current Face and corresponding Tile variables\r\n                    start = directionEdge->GetStart();\r\n                    end = directionEdge->GetEnd();\r\n                    if( face_map_[start][end] == currFace ) {\r\n                        Vertex* temp = start;\r\n                        start = end;\r\n                        end = temp;\r\n                    }\r\n                    currFace = face_map_[start][end];\r\n                    currTile = tile_map_[currFace];\r\n                }\r\n            }\r\n            else if( currTile->visited == 2 )\r\n            {\r\n                // for(int i=0;i<1;i++) {\r\n                currCrv.myPnts.push_back(currCrv.myPnts[0]);\r\n                currCrv.derivatives.push_back(currCrv.derivatives[0]);\r\n                currCrv.triadNorms.push_back(currCrv.triadNorms[0]);\r\n                // }\r\n                currCurve = false;\r\n                wngCrvs.push_back(currCrv);\r\n            }\r\n        }\r\n    }\r\n}\r\n\r\nvoid Mesh::traverseFaces_TWISTS()\r\n{\r\n    Face* currFace=0;\r\n    Tile* currTile=0;\r\n\r\n    while(anyUnvisitedFaces(&currFace,&currTile))\r\n    {\r\n        bool currCurve=true;\r\n        Edge* prevDirectionEdge=0;\r\n        KNOT prevFaceKnotType = NOTHING;\r\n        Face* prevFace=0;\r\n        Tile* prevTile=0;\r\n        Edge* directionEdge = 0;\r\n        wngCrvCtrlPnts currCrv;\r\n\r\n        while(currCurve)\r\n        {\r\n            if(currTile->visited == 0)\r\n            {\r\n                Edge *edg;\r\n                if(directionEdge==0)\r\n                    edg = (*(currFace->GetEdges().begin())); // Pick a random edge\r\n                else\r\n                    edg = directionEdge;   // Use the common edge identified in previous iteration\r\n                Vertex *start = edg->GetStart();\r\n                Vertex *end = edg->GetEnd();\r\n                if( face_map_[start][end] != currFace ) {\r\n                    Vertex* temp = start;\r\n                    start = end;\r\n                    end = temp;\r\n                }\r\n                bool isCurve1;\r\n                bool isReverse;\r\n                if(prevFaceKnotType == currTile->knotType) {\r\n                    if(currTile->knotType == PLUS1 ) {\r\n                        currTile->swapCurveMidPoints();\r\n                        currTile->knotType = PLUS2;\r\n                    } else if(currTile->knotType == TWIST1) {\r\n                        currTile->knotType = TWIST2;\r\n                        currTile->generateTwist2Points();\r\n                    } else if(currTile->knotType == TWIST2) {\r\n                        currTile->knotType = TWIST1;\r\n                        currTile->generateTwist1Points();\r\n                    }\r\n                } else if(currTile->knotType == PLUS1)\r\n                    currTile->generateCurvePoints();\r\n                else if(currTile->knotType == PLUS2)\r\n                    currTile->swapCurveMidPoints();\r\n                else if(currTile->knotType == TWIST1)\r\n                    currTile->generateTwist1Points();\r\n                else if(currTile->knotType == TWIST2)\r\n                    currTile->generateTwist2Points();\r\n\r\n                currTile->findCurveAndDirection(start,end,isCurve1,isReverse);\r\n                if(isCurve1) {\r\n                    if(isReverse) {\r\n                        for( std::vector<Vector3D*>::reverse_iterator iter = currTile->curve1.rbegin(); iter != currTile->curve1.rend(); iter++ )\r\n                            currCrv.myPnts.push_back(*iter);\r\n                    } else {\r\n                        for( std::vector<Vector3D*>::iterator iter = currTile->curve1.begin(); iter != currTile->curve1.end(); iter++ )\r\n                            currCrv.myPnts.push_back(*iter);\r\n                    }\r\n                    currTile->isCrv1Used = YES;\r\n                } else {\r\n                    if(isReverse) {\r\n                        for( std::vector<Vector3D*>::reverse_iterator iter = currTile->curve2.rbegin(); iter != currTile->curve2.rend(); iter++ )\r\n                            currCrv.myPnts.push_back(*iter);\r\n                    } else {\r\n                        for( std::vector<Vector3D*>::iterator iter = currTile->curve2.begin(); iter != currTile->curve2.end(); iter++ )\r\n                            currCrv.myPnts.push_back(*iter);\r\n                    }\r\n                    currTile->isCrv2Used = YES;\r\n                }\r\n                currCrv.triadNorms.push_back(fNormals_[currFace]);\r\n                currTile->visited++;\r\n\r\n                if(currTile->knotType == TWIST1) {\r\n                    if(isCurve1)\r\n                        directionEdge = (isReverse==true ? end->GetNextEdgeInRotation(edg) : start->GetPreviousEdgeInRotation(edg));\r\n                    else\r\n                        directionEdge = (isReverse==true ? start->GetPreviousEdgeInRotation(edg) : end->GetNextEdgeInRotation(edg));\r\n                } else if(currTile->knotType == TWIST2) {\r\n                    if(isCurve1)\r\n                        directionEdge = (isReverse==true ? start->GetPreviousEdgeInRotation(edg) : end->GetNextEdgeInRotation(edg));\r\n                    else\r\n                        directionEdge = (isReverse==true ? end->GetNextEdgeInRotation(edg) : start->GetPreviousEdgeInRotation(edg));\r\n                } else {\r\n                    Edge* adjEdge = end->GetNextEdgeInRotation(edg);\r\n                    Vertex *adjEdgOtherEnd = adjEdge->GetOtherEnd(end);\r\n                    directionEdge = adjEdgOtherEnd->GetNextEdgeInRotation(adjEdge);\r\n                }\r\n                // Store the current face details as prev face details for next face\r\n                prevDirectionEdge = edg;\r\n                prevFaceKnotType = currTile->knotType;\r\n                prevFace = currFace;\r\n                prevTile = currTile;\r\n                // Update current Face and corresponding Tile variables\r\n                start = directionEdge->GetStart();\r\n                end = directionEdge->GetEnd();\r\n                if( face_map_[start][end] == currFace ) {\r\n                    Vertex* temp = start;\r\n                    start = end;\r\n                    end = temp;\r\n                }\r\n                currFace = face_map_[start][end];\r\n                currTile = tile_map_[currFace];\r\n            }\r\n            else if( currTile->visited == 1 )\r\n            {\r\n                Edge *edg=0;\r\n                Vertex *start=0;\r\n                Vertex *end=0;\r\n                bool isCurve1;\r\n                bool isReverse;\r\n\r\n                if(directionEdge==0) {\r\n                    std::vector<Edge*> currFaceEdges = currFace->GetEdges();\r\n                    // Loop over the edges until you find an edge from which an unvisited curve is coming out\r\n                    for( std::vector<Edge*>::iterator e = currFaceEdges.begin(); e!=currFaceEdges.end(); e++ )\r\n                    {\r\n                        Edge* tmp = *e;\r\n                        start = tmp->GetStart();\r\n                        end = tmp->GetEnd();\r\n                        if( face_map_[start][end] != currFace ) {\r\n                            Vertex* temp = start;\r\n                            start = end;\r\n                            end = temp;\r\n                        }\r\n                        currTile->findCurveAndDirection(start,end,isCurve1,isReverse);\r\n                        if(!((currTile->isCrv1Used == YES && isCurve1) || (currTile->isCrv2Used == YES && !isCurve1)))\r\n                        {\r\n                            edg = tmp;\r\n                            break;\r\n                        }\r\n                    }\r\n                }\r\n                else {\r\n                    edg = directionEdge;   // Use the common edge identified in previous iteration\r\n                    start = edg->GetStart();\r\n                    end = edg->GetEnd();\r\n                    if( face_map_[start][end] != currFace ) {\r\n                        Vertex* temp = start;\r\n                        start = end;\r\n                        end = temp;\r\n                    }\r\n                    currTile->findCurveAndDirection(start,end,isCurve1,isReverse);\r\n                }\r\n\r\n\r\n                if( ( (prevFaceKnotType == PLUS1 || prevFaceKnotType == PLUS2) && (currTile->knotType == PLUS1 || currTile->knotType == PLUS2) ) ||\r\n                        ( (prevFaceKnotType == TWIST1 || prevFaceKnotType == TWIST2) && (currTile->knotType == TWIST1 || currTile->knotType == TWIST2) ) )\r\n                {\r\n                    if((currTile->isCrv1Used == YES && isCurve1) || (currTile->isCrv2Used == YES && !isCurve1))\r\n                    {\r\n                        if( prevFaceKnotType==currTile->knotType )\r\n                        {\r\n                            // Remove already pushed curve vertices\r\n                            for(unsigned int rem=0; rem<3; rem++)\r\n                                currCrv.myPnts.pop_back();\r\n                            // Change prev face KNOT type; choose TWIST1\r\n                            prevTile->knotType = PLUS1;\r\n                            prevTile->visited--;\r\n                            // Now reset the state variables to prev state and continue with new KNOT type.\r\n                            // Don't change the visited of the currTile\r\n                            prevFaceKnotType = PLUS1;\r\n                            currFace = prevFace;\r\n                            currTile = prevTile;\r\n                            directionEdge = prevDirectionEdge;\r\n                        } else {\r\n                            // This is one special case where we should close curve\r\n                            // since we entered the face along the edge we started the curve\r\n                            if(isCurve1) {\r\n                                if(isReverse) {\r\n                                    for( std::vector<Vector3D*>::reverse_iterator iter = currTile->curve1.rbegin(); iter != currTile->curve1.rend(); iter++ )\r\n                                        currCrv.myPnts.push_back(*iter);\r\n                                } else {\r\n                                    for( std::vector<Vector3D*>::iterator iter = currTile->curve1.begin(); iter != currTile->curve1.end(); iter++ )\r\n                                        currCrv.myPnts.push_back(*iter);\r\n                                }\r\n                            } else {\r\n                                if(isReverse) {\r\n                                    for( std::vector<Vector3D*>::reverse_iterator iter = currTile->curve2.rbegin(); iter != currTile->curve2.rend(); iter++ )\r\n                                        currCrv.myPnts.push_back(*iter);\r\n                                } else {\r\n                                    for( std::vector<Vector3D*>::iterator iter = currTile->curve2.begin(); iter != currTile->curve2.end(); iter++ )\r\n                                        currCrv.myPnts.push_back(*iter);\r\n                                }\r\n                            }\r\n                            currCrv.triadNorms.push_back(fNormals_[currFace]);\r\n                            currCurve = false;\r\n                            wngCrvs.push_back(currCrv);\r\n                        }\r\n                    }\r\n                    else\r\n                    {\r\n                        // If curve we are gng to use is not used yet; just proceed in normal fashion\r\n                        // Add points and compute next direction and update prev* variables\r\n                        if(isCurve1) {\r\n                            if(isReverse) {\r\n                                for( std::vector<Vector3D*>::reverse_iterator iter = currTile->curve1.rbegin(); iter != currTile->curve1.rend(); iter++ )\r\n                                    currCrv.myPnts.push_back(*iter);\r\n                            } else {\r\n                                for( std::vector<Vector3D*>::iterator iter = currTile->curve1.begin(); iter != currTile->curve1.end(); iter++ )\r\n                                    currCrv.myPnts.push_back(*iter);\r\n                            }\r\n                            currTile->isCrv1Used = YES;\r\n                        } else {\r\n                            if(isReverse) {\r\n                                for( std::vector<Vector3D*>::reverse_iterator iter = currTile->curve2.rbegin(); iter != currTile->curve2.rend(); iter++ )\r\n                                    currCrv.myPnts.push_back(*iter);\r\n                            } else {\r\n                                for( std::vector<Vector3D*>::iterator iter = currTile->curve2.begin(); iter != currTile->curve2.end(); iter++ )\r\n                                    currCrv.myPnts.push_back(*iter);\r\n                            }\r\n                            currTile->isCrv2Used = YES;\r\n                        }\r\n                        currCrv.triadNorms.push_back(fNormals_[currFace]);\r\n                        currTile->visited++;\r\n                        // Store the current face details as prev face details for next face\r\n                        prevDirectionEdge = edg;\r\n                        prevFaceKnotType = currTile->knotType;\r\n                        prevFace = currFace;\r\n                        prevTile = currTile;\r\n                        // compute next direction\r\n                        if(currTile->knotType == TWIST1) {\r\n                            if(isCurve1)\r\n                                directionEdge = (isReverse==true ? end->GetNextEdgeInRotation(edg) : start->GetPreviousEdgeInRotation(edg));\r\n                            else\r\n                                directionEdge = (isReverse==true ? start->GetPreviousEdgeInRotation(edg) : end->GetNextEdgeInRotation(edg));\r\n                        } else if(currTile->knotType == TWIST2) {\r\n                            if(isCurve1)\r\n                                directionEdge = (isReverse==true ? start->GetPreviousEdgeInRotation(edg) : end->GetNextEdgeInRotation(edg));\r\n                            else\r\n                                directionEdge = (isReverse==true ? end->GetNextEdgeInRotation(edg) : start->GetPreviousEdgeInRotation(edg));\r\n                        } else {\r\n                            Edge* adjEdge = end->GetNextEdgeInRotation(edg);\r\n                            Vertex *adjEdgOtherEnd = adjEdge->GetOtherEnd(end);\r\n                            directionEdge = adjEdgOtherEnd->GetNextEdgeInRotation(adjEdge);\r\n                        }\r\n                        // Update current Face and corresponding Tile variables\r\n                        start = directionEdge->GetStart();\r\n                        end = directionEdge->GetEnd();\r\n                        if( face_map_[start][end] == currFace ) {\r\n                            Vertex* temp = start;\r\n                            start = end;\r\n                            end = temp;\r\n                        }\r\n                        currFace = face_map_[start][end];\r\n                        currTile = tile_map_[currFace];\r\n                    }\r\n                }\r\n                else\r\n                {\r\n                    currTile->findCurveAndDirection(start,end,isCurve1,isReverse);\r\n                    /*if(currTile->knotType == TWIST1)\r\n                      currTile->generateTwist1Points();\r\n                      else if(currTile->knotType == TWIST2)\r\n                      currTile->generateTwist2Points();*/\r\n\r\n                    if(isCurve1) {\r\n                        if(isReverse) {\r\n                            for( std::vector<Vector3D*>::reverse_iterator iter = currTile->curve1.rbegin(); iter != currTile->curve1.rend(); iter++ )\r\n                                currCrv.myPnts.push_back(*iter);\r\n                        } else {\r\n                            for( std::vector<Vector3D*>::iterator iter = currTile->curve1.begin(); iter != currTile->curve1.end(); iter++ )\r\n                                currCrv.myPnts.push_back(*iter);\r\n                        }\r\n                        currTile->isCrv1Used = YES;\r\n                    } else {\r\n                        if(isReverse) {\r\n                            for( std::vector<Vector3D*>::reverse_iterator iter = currTile->curve2.rbegin(); iter != currTile->curve2.rend(); iter++ )\r\n                                currCrv.myPnts.push_back(*iter);\r\n                        } else {\r\n                            for( std::vector<Vector3D*>::iterator iter = currTile->curve2.begin(); iter != currTile->curve2.end(); iter++ )\r\n                                currCrv.myPnts.push_back(*iter);\r\n                        }\r\n                        currTile->isCrv2Used = YES;\r\n                    }\r\n                    currCrv.triadNorms.push_back(fNormals_[currFace]);\r\n                    currTile->visited++;\r\n                    // Store the current face details as prev face details for next face\r\n                    prevDirectionEdge = edg;\r\n                    prevFaceKnotType = currTile->knotType;\r\n                    prevFace = currFace;\r\n                    prevTile = currTile;\r\n\r\n                    if(currTile->knotType == TWIST1) {\r\n                        if(isCurve1)\r\n                            directionEdge = (isReverse==true ? end->GetNextEdgeInRotation(edg) : start->GetPreviousEdgeInRotation(edg));\r\n                        else\r\n                            directionEdge = (isReverse==true ? start->GetPreviousEdgeInRotation(edg) : end->GetNextEdgeInRotation(edg));\r\n                    } else if(currTile->knotType == TWIST2) {\r\n                        if(isCurve1)\r\n                            directionEdge = (isReverse==true ? start->GetPreviousEdgeInRotation(edg) : end->GetNextEdgeInRotation(edg));\r\n                        else\r\n                            directionEdge = (isReverse==true ? end->GetNextEdgeInRotation(edg) : start->GetPreviousEdgeInRotation(edg));\r\n                    } else {\r\n                        Edge* adjEdge = end->GetNextEdgeInRotation(edg);\r\n                        Vertex *adjEdgOtherEnd = adjEdge->GetOtherEnd(end);\r\n                        directionEdge = adjEdgOtherEnd->GetNextEdgeInRotation(adjEdge);\r\n                    }\r\n                    // Update current Face and corresponding Tile variables\r\n                    start = directionEdge->GetStart();\r\n                    end = directionEdge->GetEnd();\r\n                    if( face_map_[start][end] == currFace ) {\r\n                        Vertex* temp = start;\r\n                        start = end;\r\n                        end = temp;\r\n                    }\r\n                    currFace = face_map_[start][end];\r\n                    currTile = tile_map_[currFace];\r\n                }\r\n            }\r\n            else if( currTile->visited == 2 )\r\n            {\r\n                Edge *edg = directionEdge;   // Use the common edge identified in previous iteration\r\n                Vertex *start = edg->GetStart();\r\n                Vertex *end = edg->GetEnd();\r\n                if( face_map_[start][end] != currFace ) {\r\n                    Vertex* temp = start;\r\n                    start = end;\r\n                    end = temp;\r\n                }\r\n\r\n                bool isCurve1;\r\n                bool isReverse;\r\n                currTile->findCurveAndDirection(start,end,isCurve1,isReverse);\r\n                if(isCurve1) {\r\n                    if(isReverse) {\r\n                        for( std::vector<Vector3D*>::reverse_iterator iter = currTile->curve1.rbegin(); iter != currTile->curve1.rend(); iter++ )\r\n                            currCrv.myPnts.push_back(*iter);\r\n                    } else {\r\n                        for( std::vector<Vector3D*>::iterator iter = currTile->curve1.begin(); iter != currTile->curve1.end(); iter++ )\r\n                            currCrv.myPnts.push_back(*iter);\r\n                    }\r\n                } else {\r\n                    if(isReverse) {\r\n                        for( std::vector<Vector3D*>::reverse_iterator iter = currTile->curve2.rbegin(); iter != currTile->curve2.rend(); iter++ )\r\n                            currCrv.myPnts.push_back(*iter);\r\n                    } else {\r\n                        for( std::vector<Vector3D*>::iterator iter = currTile->curve2.begin(); iter != currTile->curve2.end(); iter++ )\r\n                            currCrv.myPnts.push_back(*iter);\r\n                    }\r\n                }\r\n                currCrv.triadNorms.push_back(fNormals_[currFace]);\r\n                currCurve = false;\r\n                wngCrvs.push_back(currCrv);\r\n            }\r\n        }\r\n    }\r\n}\r\n\r\n\r\nvoid Mesh::generateCtrlPnts4InterpolationSpline()\r\n{\r\n    for (std::vector<wngCrvCtrlPnts>::iterator crv = wngCrvs.begin(); crv != wngCrvs.end(); ++crv)\r\n    {\r\n        Vec3DPtrIter vBegin\t\t\t= (*crv).myPnts.begin();\r\n        Vec3DPtrIter vEnd\t\t\t= (*crv).myPnts.end();\r\n        Vec3DPtrIter dBegin\t\t\t= (*crv).derivatives.begin();\r\n        Vec3DPtrIter dEnd\t\t\t= (*crv).derivatives.end();\r\n        Vec3DPtrIter nBegin\t\t\t= (*crv).triadNorms.begin();\r\n        Vec3DPtrIter nEnd\t\t\t= (*crv).triadNorms.end();\r\n        Vector3D *vFinish\t\t\t= *((*crv).myPnts.rbegin()+1);\r\n        Vec3DPtrIter dIter\t\t\t= dBegin;\r\n        Vec3DPtrIter nIter\t\t\t= nBegin;\r\n\r\n        for( Vec3DPtrIter c = vBegin; c+1 != vEnd; ++c, ++dIter, ++nIter )\r\n        {\r\n            Vector3D P1, P2, P3, P4, b1, b2, derv, norm, binorm;\r\n            Vector3D n1 = *(*nIter);\r\n            Vector3D n2 = ( c+2 == vEnd ? *(*(nBegin+1)) : *(*(nIter+1)) );\r\n\r\n            if( c == vBegin ) {\r\n                P1.set( vFinish->DX(), vFinish->DY(), vFinish->DZ() );\r\n                P2.set( (*c)->DX(), (*c)->DY(), (*c)->DZ() );\r\n                P3.set( (*(c+1))->DX(), (*(c+1))->DY(), (*(c+1))->DZ() );\r\n                P4.set( (*(c+2))->DX(), (*(c+2))->DY(), (*(c+2))->DZ() );\r\n            } else if( c+2 == vEnd ) {\r\n                P1.set( (*(c-3))->DX(), (*(c-3))->DY(), (*(c-3))->DZ() );\r\n                P2.set( (*c)->DX(), (*c)->DY(), (*c)->DZ() );\r\n                P3.set( (*(c+1))->DX(), (*(c+1))->DY(), (*(c+1))->DZ() );\r\n                P4.set( (*(vBegin+3))->DX(), (*(vBegin+3))->DY(), (*(vBegin+3))->DZ() );\r\n            } else {\r\n                P1.set( (*(c-3))->DX(), (*(c-3))->DY(), (*(c-3))->DZ() );\r\n                P2.set( (*c)->DX(), (*c)->DY(), (*c)->DZ() );\r\n                P3.set( (*(c+1))->DX(), (*(c+1))->DY(), (*(c+1))->DZ() );\r\n                P4.set( (*(c+2))->DX(), (*(c+2))->DY(), (*(c+2))->DZ() );\r\n            }\r\n            b1 = P2 + (P3 - P1) / 6.0f;\r\n            b2 = P3 + (P2 - P4) / 6.0f;\r\n\r\n            c++; dIter++; nIter++;\r\n            c = (*crv).myPnts.insert(c,new Vector3D(b1));\r\n            derv = b2 - P2; derv.normalize();\r\n            binorm = cross(derv,n1); binorm.normalize();\r\n            norm = cross(binorm,derv); norm.normalize();\r\n            dIter = (*crv).derivatives.insert(dIter,new Vector3D(derv));\r\n            nIter = (*crv).triadNorms.insert(nIter,new Vector3D(norm));\r\n\r\n            c++; dIter++; nIter++;\r\n            c = (*crv).myPnts.insert(c,new Vector3D(b2));\r\n            derv = P3 - b1; derv.normalize();\r\n            binorm = cross(derv,n2); binorm.normalize();\r\n            norm = cross(binorm,derv); norm.normalize();\r\n            dIter = (*crv).derivatives.insert(dIter,new Vector3D(derv));\r\n            nIter = (*crv).triadNorms.insert(nIter,new Vector3D(norm));\r\n\r\n            /* Begin and End iterators are no longer valid, hence get updated ones */\r\n            vBegin\t= (*crv).myPnts.begin();\r\n            vEnd\t= (*crv).myPnts.end();\r\n            nBegin\t= (*crv).triadNorms.begin();\r\n        }\r\n    }\r\n}\r\n\r\n\r\nvoid Mesh::generateKnotVectors(GLfloat *uKnots, GLint uKnotCount, GLfloat *vKnots, GLint vKnotCount)\r\n{\r\n    GLfloat step    = 1.0;\r\n    GLint ktIter    = 0;\r\n    uKnots[ktIter++]= 0.0f;\r\n    for(GLint k=ktIter; k<uKnotCount; k++ )\r\n        uKnots[k] = uKnots[k-1] + step;\r\n    ktIter          = 0;\r\n    vKnots[ktIter++]= 0.0f;\r\n    for(GLint k=ktIter; k<vKnotCount; k++ )\r\n        vKnots[k] = vKnots[k-1] + step;\r\n}\r\n\r\nvoid Mesh::generateTubeCtrlPnts(const wngCrvCtrlPnts &wvngCrv, float *ctlpoints)\r\n{\r\n    int i;\r\n    int triadIndex = 0;\r\n    int firstRunCount = 0;\r\n    GLfloat dTheta = 45.0f;\r\n    GLfloat theta;\r\n    std::vector<Vector3D*> thisCurvePnts = wvngCrv.myPnts;\r\n    std::vector<Vector3D*> thisCurveTriads = wvngCrv.triadNorms;\r\n    std::vector<Vector3D*> thisDervs = wvngCrv.derivatives;\r\n\r\n    for(std::vector<Vector3D*>::iterator it = thisCurvePnts.begin(); it != thisCurvePnts.end(); it++,triadIndex++)\r\n    {\r\n        Vector3D norm = *thisCurveTriads[triadIndex];\r\n        Vector3D derivative = *thisDervs[triadIndex];\r\n        norm.normalize();\r\n        derivative.normalize();\r\n        Vector3D binorm = cross(norm,derivative);\r\n        binorm.normalize();\r\n\r\n        i = it-thisCurvePnts.begin();\r\n        Vector3D tmp = *(*it);\r\n        theta = 0.0f;\r\n        for(int v=0; v<vNumPnts; v++)\r\n        {\r\n            Vector3D newPnt = tmp + THREAD_HRT*cos(theta*PI/180)*norm + THREAD_VERT*sin(theta*PI/180)*binorm;\r\n            int index = i*vNumPnts*DIMENSION + v*DIMENSION;\r\n            ctlpoints[index+0] = ( fabs(newPnt[0]) < 1.0e-5 ? 0.0f : newPnt[0] );\r\n            ctlpoints[index+1] = ( fabs(newPnt[1]) < 1.0e-5 ? 0.0f : newPnt[1] );\r\n            ctlpoints[index+2] = ( fabs(newPnt[2]) < 1.0e-5 ? 0.0f : newPnt[2] );\r\n            theta += dTheta;\r\n        }\r\n    }\r\n\r\n    firstRunCount = thisCurvePnts.size()-1;\r\n    triadIndex = 1;\r\n    for(int pnt=1; pnt<3; pnt++,triadIndex++)\r\n    {\r\n        Vector3D norm = *thisCurveTriads[triadIndex];\r\n        Vector3D derivative = *thisDervs[triadIndex];\r\n        norm.normalize();\r\n        derivative.normalize();\r\n        Vector3D binorm = cross(norm,derivative);\r\n        binorm.normalize();\r\n\r\n        i = firstRunCount + pnt;\r\n        Vector3D tmp = *(thisCurvePnts[pnt]);\r\n        theta = 0.0f;\r\n        for(int v=0; v<vNumPnts; v++)\r\n        {\r\n            Vector3D newPnt = tmp + THREAD_HRT*cos(theta*PI/180)*norm + THREAD_VERT*sin(theta*PI/180)*binorm;\r\n            int index = i*vNumPnts*DIMENSION + v*DIMENSION;\r\n            ctlpoints[index+0] = ( fabs(newPnt[0]) < 1.0e-5 ? 0.0f : newPnt[0] );\r\n            ctlpoints[index+1] = ( fabs(newPnt[1]) < 1.0e-5 ? 0.0f : newPnt[1] );\r\n            ctlpoints[index+2] = ( fabs(newPnt[2]) < 1.0e-5 ? 0.0f : newPnt[2] );\r\n            theta += dTheta;\r\n        }\r\n    }\r\n}\r\n\r\nvoid Mesh::generateWngTubes()\r\n{\r\n    for (std::vector<wngCrvCtrlPnts>::iterator crv = wngCrvs.begin(); crv != wngCrvs.end(); ++crv)\r\n    {\r\n        WvngTube *currTube = new WvngTube;\r\n        wngCrvCtrlPnts currCurve = (*crv);\r\n        currTube->uOrder = DEGREE+1;\r\n        currTube->vOrder = DEGREE+1;\r\n        currTube->uCtrlNum = currCurve.myPnts.size() + EXTRA_VERTICES;\r\n        currTube->vCtrlNum = vNumPnts;\r\n        currTube->uStride = currTube->vCtrlNum*DIMENSION;\r\n        currTube->vStride = DIMENSION;\r\n        currTube->uKnotCount = currTube->uCtrlNum + currTube->uOrder;\r\n        currTube->vKnotCount = currTube->vCtrlNum + currTube->vOrder;\r\n        currTube->uKnots = new GLfloat[currTube->uKnotCount];\r\n        currTube->vKnots = new GLfloat[currTube->vKnotCount];\r\n        generateKnotVectors(currTube->uKnots,currTube->uKnotCount,currTube->vKnots,currTube->vKnotCount);\r\n        currTube->ctlPoints = new float[currTube->uCtrlNum*currTube->vCtrlNum*DIMENSION];\r\n        generateTubeCtrlPnts(currCurve,currTube->ctlPoints);\r\n        app::console()<<std::endl;\r\n        mWvngTubes.push_back(currTube);\r\n    }\r\n}\r\n\r\nvoid Mesh::regenerateThreads(bool isThicknessModified, CURVE_TYPE curveType)\r\n{\r\n    mWvngTubes.clear();\r\n    baseCrvType = curveType;\r\n    if(isThicknessModified) {\r\n        THREAD_HRT\t= 0.65*(TILE_THICKNESS/2.0);\r\n        tile_map_.clear();\r\n        wngCrvs.clear();\r\n        pumpMesh();\r\n        traverseFaces_PLUSES();\r\n        //traverseFaces_TWISTS();\r\n        if( baseCrvType == CATMULLROMSPLINE ) generateCtrlPnts4InterpolationSpline();\r\n    }\r\n    generateWngTubes();\r\n}\r\n", "meta": {"hexsha": "a3d4f823a0a8049f157041e78e9a7c364893b12b", "size": 93196, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "source/Weave.cpp", "max_stars_repo_name": "9prady9/duotone", "max_stars_repo_head_hexsha": "53d5d8daa9a90ca7ca39698766c267d5b03849cb", "max_stars_repo_licenses": ["BSD-3-Clause"], "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/Weave.cpp", "max_issues_repo_name": "9prady9/duotone", "max_issues_repo_head_hexsha": "53d5d8daa9a90ca7ca39698766c267d5b03849cb", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/Weave.cpp", "max_forks_repo_name": "9prady9/duotone", "max_forks_repo_head_hexsha": "53d5d8daa9a90ca7ca39698766c267d5b03849cb", "max_forks_repo_licenses": ["BSD-3-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.1366336634, "max_line_length": 176, "alphanum_fraction": 0.4749560067, "num_tokens": 22415, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6224593312018546, "lm_q2_score": 0.5621765008857981, "lm_q1q2_score": 0.3499320087587727}}
{"text": "#include \"Pnm.h\"\n\n#include <iostream>\n\n#include <vector>\n#include <string>\n#include <cmath>\n\n#include <Eigen/Sparse>\n\ntypedef Eigen::SparseMatrix<double, Eigen::RowMajor> Matrix;\ntypedef Matrix::InnerIterator MatrixIterator;\ntypedef Eigen::BiCGSTAB <Eigen::SparseMatrix<double>> BiCGSTAB;\ntypedef Eigen::LeastSquaresConjugateGradient <Eigen::SparseMatrix<double>>\n        LeastSqCG;\ntypedef Eigen::SparseLU <Eigen::SparseMatrix<double>> SparseLU;\n\nPnm::Pnm(const std::map <std::string, std::variant<int, double, std::string>> &paramsPnm,\n         std::shared_ptr <Netgrid> netgrid) :\n        _paramsPnm(paramsPnm),\n        _netgrid(netgrid),\n        _dim(netgrid->_poresPores.size()),\n        _matrix(_dim, _dim),\n        _freeVector(new double[_dim], _dim),\n        _pressures(new double[_dim], _dim) {}\n\nvoid Pnm::printParamsPnm() {\n\n    for (auto const &[name, param] : _paramsPnm) {\n        std::cout << name << \": \";\n        if (std::get_if<int>(&param))\n            std::cout << std::get<int>(param) << std::endl;\n        else if (std::get_if<double>(&param))\n            std::cout << std::get<double>(param) << std::endl;\n        else if (std::get_if<std::string>(&param))\n            std::cout << std::get<std::string>(param) << std::endl;\n    }\n\n}\n\nvoid Pnm::calcConductances(const std::vector<double> &densities,\n                           const std::vector<double> &viscosities) {\n\n    for (auto &[throat, pores] : _netgrid->_throatsPores) {\n\n        auto &height = _netgrid->_throatsDepths[throat];\n        auto &width = _netgrid->_throatsWidths[throat];\n        auto &length = _netgrid->_throatsLs[throat];\n        auto &density = densities[throat];\n        auto &viscosity = viscosities[throat];\n        // 3D case\n        // double resistance = 12. * viscosity * length / height / height / height / width;\n        // 2D case\n        auto corrFactor = 1.12;\n        double resistance = corrFactor * 12. * viscosity * length / width / width / width / height;\n\n        // _conductances[throat] = density / resistance;\n        _conductances[throat] = 1. / resistance;\n    }\n\n}\n\nvoid Pnm::processThroats() {\n    for (auto&[throat, pores] : _netgrid->_throatsPores) {\n        auto &normals = _netgrid->_normalsThroatsPores[throat];\n        for (uint32_t i = 0; i < pores.size(); i++)\n            _matrixCoeffs[throat][pores[i]] = normals[i] * _conductances[throat];\n    }\n}\n\nvoid Pnm::processPores() {\n\n    for (auto &pore: _netgrid->_inletPores)\n        _freeCoeffs[pore] = 0;\n    for (auto &pore: _netgrid->_outletPores)\n        _freeCoeffs[pore] = 0;\n    for (auto &pore: _netgrid->_deadendPores)\n        _freeCoeffs[pore] = 0;\n    for (auto &pore: _netgrid->_nonboundPores)\n        _freeCoeffs[pore] = 0;\n}\n\nvoid Pnm::processNewmanPores(std::map<uint32_t, double> &poresFlows) {\n    // ToDo: make sure it is ok with flow sign\n    for (auto &[pore, flow]: poresFlows)\n        _freeCoeffs[pore] = flow;\n}\n\nvoid Pnm::processDirichPores(std::map<uint32_t, double> &poresPressures) {\n    for (auto &[pore, pressure]: poresPressures)\n        _freeCoeffs[pore] = pressure;\n}\n\nvoid Pnm::fillMatrix(std::map<uint32_t, double> &poresFlows,\n                     std::map<uint32_t, double> &poresPressures,\n                     const std::vector<double> &capillaryPressures) {\n\n    for (int i = 0; i < _dim; ++i)\n        for (MatrixIterator it(_matrix, i); it; ++it)\n            it.valueRef() = 0;\n\n    std::set <uint32_t> groupedPores;\n    groupedPores.insert(_netgrid->_nonboundPores.begin(), _netgrid->_nonboundPores.end());\n    groupedPores.insert(_netgrid->_deadendPores.begin(), _netgrid->_deadendPores.end());\n\n    for (auto &pore: groupedPores) {\n        _freeVector[pore] = _freeCoeffs[pore];\n        auto &throats = _netgrid->_poresThroats[pore];\n        auto &normals = _netgrid->_normalsPoresThroats[pore];\n        for (uint32_t i = 0; i < throats.size(); i++) {\n            _freeVector[pore] += normals[i] * _conductances[throats[i]] *\n                                 capillaryPressures[throats[i]];\n            for (auto &poreCurr : _netgrid->_throatsPores[throats[i]])\n                _matrix.coeffRef(pore, poreCurr) +=\n                        normals[i] * _matrixCoeffs[throats[i]][poreCurr];\n        }\n    }\n\n    for (auto &[pore, flow]: poresFlows) {\n        _freeVector[pore] = _freeCoeffs[pore];\n        auto &throats = _netgrid->_poresThroats[pore];\n        auto &normals = _netgrid->_normalsPoresThroats[pore];\n        for (uint32_t i = 0; i < throats.size(); i++) {\n            _freeVector[pore] += normals[i] * _conductances[throats[i]] *\n                                 capillaryPressures[throats[i]];\n            for (auto &poreCurr : _netgrid->_throatsPores[throats[i]])\n                _matrix.coeffRef(pore, poreCurr) +=\n                        normals[i] * _matrixCoeffs[throats[i]][poreCurr];\n        }\n    }\n\n    for (auto &[pore, pressure]: poresPressures) {\n        _freeVector[pore] = _freeCoeffs[pore];\n        _matrix.coeffRef(pore, pore) = 1;\n    }\n\n}\n\nvoid Pnm::calculatePress() {\n\n    auto &itAccuracy = std::get<double>(_paramsPnm[\"it_accuracy\"]);\n    auto &solverMethod = std::get<std::string>(_paramsPnm[\"solver_method\"]);\n\n    if (solverMethod == \"sparseLU\") {\n\n        SparseLU sparseLU;\n        sparseLU.compute(_matrix);\n        _pressures = sparseLU.solve(_freeVector);\n\n    } else if (solverMethod == \"biCGSTAB\") {\n\n        BiCGSTAB biCGSTAB;\n        biCGSTAB.compute(_matrix);\n        biCGSTAB.setTolerance(itAccuracy);\n        _pressures = biCGSTAB.solveWithGuess(_freeVector, _pressures);\n\n    } else if (solverMethod == \"leastSqCG\") {\n\n        LeastSqCG leastSqCG;\n        leastSqCG.compute(_matrix);\n        leastSqCG.setTolerance(itAccuracy);\n        _pressures = leastSqCG.solveWithGuess(_freeVector, _pressures);\n\n    }\n\n}\n\nvoid Pnm::cfdProcedure(const std::vector<double> &densities,\n                       const std::vector<double> &viscosities,\n                       const std::vector<double> &capillaryPressures,\n                       std::map<uint32_t, double> &poresFlows,\n                       std::map<uint32_t, double> &poresPressures) {\n\n    calcConductances(densities, viscosities);\n    processThroats();\n    processPores();\n    processNewmanPores(poresFlows);\n    processDirichPores(poresPressures);\n    fillMatrix(poresFlows, poresPressures, capillaryPressures);\n    // std::cout << _matrix << std::endl;\n\n    calculatePress();\n\n}\n\nvoid Pnm::calcThroatsVolFlows(const std::vector<double> &capillaryPressures) {\n\n    for (auto &[throat, conductance] : _conductances) {\n        auto &pores = _netgrid->_throatsPores[throat];\n        auto &normals = _netgrid->_normalsThroatsPores[throat];\n        _throatsVolFlows[throat] = conductance * capillaryPressures[throat];\n        for (uint32_t i = 0; i < pores.size(); i++)\n            _throatsVolFlows[throat] -= normals[i] * conductance * _pressures[pores[i]];\n    }\n\n}\n\nvoid Pnm::calcPoresFlowRates() {\n\n    std::set <uint32_t> groupedPores;\n    groupedPores.insert(_netgrid->_nonboundPores.begin(), _netgrid->_nonboundPores.end());\n    groupedPores.insert(_netgrid->_deadendPores.begin(), _netgrid->_deadendPores.end());\n\n    for (auto &pore: groupedPores) {\n        auto &poresThroats = _netgrid->_poresThroats[pore];\n        auto &normals = _netgrid->_normalsPoresThroats[pore];\n        for (uint32_t i = 0; i < poresThroats.size(); i++)\n            _poresFlowRates[pore] += normals[i] * _throatsVolFlows[poresThroats[i]];\n    }\n\n    for (auto &pore: _netgrid->_outletPores) {\n        auto &poresThroats = _netgrid->_poresThroats[pore];\n        auto &normals = _netgrid->_normalsPoresThroats[pore];\n        for (uint32_t i = 0; i < poresThroats.size(); i++)\n            _poresFlowRates[pore] += normals[i] * _throatsVolFlows[poresThroats[i]];\n    }\n\n    for (auto &pore: _netgrid->_inletPores) {\n        auto &poresThroats = _netgrid->_poresThroats[pore];\n        auto &normals = _netgrid->_normalsPoresThroats[pore];\n        for (uint32_t i = 0; i < poresThroats.size(); i++)\n            _poresFlowRates[pore] += -normals[i] * _throatsVolFlows[poresThroats[i]];\n    }\n\n}\n\nvoid Pnm::calcTotalFlowRate(const std::set <uint32_t> &pores) {\n\n    _totFlowRate = 0;\n\n    for (auto &pore: pores)\n        _totFlowRate += _poresFlowRates[pore];\n}\n\nvoid Pnm::setPressures(Eigen::Ref <Eigen::VectorXd> pressures) {\n    if (_pressures.data() != pressures.data())\n        delete _pressures.data();\n    new(&_pressures) Eigen::Map<Eigen::VectorXd>(pressures.data(),\n                                                 pressures.size());\n}\n\nEigen::Ref <Eigen::VectorXd> Pnm::getPressures() {\n    return _pressures;\n}", "meta": {"hexsha": "beb742b43a4b2407999cf87d6dd9ef9bd4f3d508", "size": 8623, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "pnm/Pnm.cpp", "max_stars_repo_name": "lanetszb/vofpnm", "max_stars_repo_head_hexsha": "520544db894fb13e44a86e989bd17b4690e996d3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "pnm/Pnm.cpp", "max_issues_repo_name": "lanetszb/vofpnm", "max_issues_repo_head_hexsha": "520544db894fb13e44a86e989bd17b4690e996d3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pnm/Pnm.cpp", "max_forks_repo_name": "lanetszb/vofpnm", "max_forks_repo_head_hexsha": "520544db894fb13e44a86e989bd17b4690e996d3", "max_forks_repo_licenses": ["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.3401639344, "max_line_length": 99, "alphanum_fraction": 0.6218253508, "num_tokens": 2492, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7341195385342971, "lm_q2_score": 0.4765796510636759, "lm_q1q2_score": 0.3498664335137021}}
{"text": "/* This file is part of PyMesh. Copyright (c) 2015 by Qingnan Zhou */\n#include \"SelfIntersection.h\"\n\n#include <Core/Exception.h>\n#include <Math/MatrixUtils.h>\n\n#include <boost/function.hpp>\n#include <boost/bind.hpp>\n\n#include <CGAL/box_intersection_d.h>\n\nusing namespace PyMesh;\n\nnamespace SelfIntersectionHelper {\n    class Box : public CGAL::Box_intersection_d::Box_d<Float,\n          3, CGAL::Box_intersection_d::ID_NONE> {\n        public:\n            typedef CGAL::Box_intersection_d::Box_d<Float, 3,\n                    CGAL::Box_intersection_d::ID_NONE> Base;\n            typedef Float                   NT;\n            typedef std::size_t             ID;\n\n            Box() {}\n            Box(bool complete) : Base(complete) {}\n            Box(NT l[3], NT h[3]) : Base( l, h) {}\n            Box( const CGAL::Bbox_3& b) : Base( b) {}\n            ID  id() const { return m_id; }\n            void set_id(ID id) { m_id = id; }\n        private:\n            ID m_id;\n    };\n\n    void handle_intersection_candidate(\n            SelfIntersection* self, const Box& a, const Box& b) {\n        self->handle_intersection_candidate(a.id(), b.id());\n    }\n\n    Vector2I get_opposite_edge(const Vector3I& f, size_t v) {\n        if (f[0] == v) {\n            return Vector2I(f[1], f[2]);\n        } else if (f[1] == v) {\n            return Vector2I(f[2], f[0]);\n        } else if (f[2] == v) {\n            return Vector2I(f[0], f[1]);\n        } else {\n            std::stringstream err_msg;\n            err_msg << \"Vertex \" << v << \" does not belong to triangle (\"\n                << f.transpose() << \")\";\n            throw RuntimeError(err_msg.str());\n        }\n    }\n\n    size_t get_opposite_vertex(const Vector3I& f, const Vector2I& e) {\n        if (f[0] != e[0] && f[0] != e[1]) return f[0];\n        if (f[1] != e[0] && f[1] != e[1]) return f[1];\n        if (f[2] != e[0] && f[2] != e[1]) return f[2];\n        throw RuntimeError(\"Face must be topologically degnerated!\");\n    }\n\n    std::vector<Box> get_triangle_bboxes(\n            const SelfIntersection::Points& pts, const MatrixIr& faces) {\n        const size_t num_faces = faces.rows();\n        std::vector<Box> boxes;\n        boxes.reserve(num_faces);\n        for (size_t i=0; i<num_faces; i++) {\n            const Vector3I f = faces.row(i);\n            const std::vector<SelfIntersection::Point_3> corners{\n                pts[f[0]], pts[f[1]], pts[f[2]]\n            };\n            if (CGAL::collinear(pts[f[0]], pts[f[1]], pts[f[2]])) {\n                // Triangle is degenerated.\n                continue;\n            }\n            boxes.emplace_back(CGAL::bbox_3(corners.begin(), corners.end()));\n            boxes.back().set_id(i);\n        }\n        return boxes;\n    }\n}\nusing namespace SelfIntersectionHelper;\n\nSelfIntersection::SelfIntersection(\n        const MatrixFr& vertices, const MatrixIr& faces)\n: m_faces(faces) {\n    const size_t num_vertices = vertices.rows();\n    const size_t dim = vertices.cols();\n    const size_t vertex_per_face = faces.cols();\n\n    if (dim != 3) {\n        throw NotImplementedError(\n                \"Self intersection check only support 3D\");\n    }\n    if (vertex_per_face != 3) {\n        throw NotImplementedError(\n                \"Self intersection check only works with triangles\");\n    }\n\n    m_points.resize(num_vertices);\n    for (size_t i=0; i<num_vertices; i++) {\n        m_points[i] = Point_3(\n                vertices(i,0),\n                vertices(i,1),\n                vertices(i,2));\n    }\n}\n\nvoid SelfIntersection::detect_self_intersection() {\n    clear();\n    std::vector<Box> boxes = get_triangle_bboxes(m_points, m_faces);\n    boost::function<void(const Box& a, const Box& b)> cb =\n        boost::bind(SelfIntersectionHelper::handle_intersection_candidate,\n                this, _1, _2);\n    CGAL::box_self_intersection_d(boxes.begin(), boxes.end(), cb);\n}\n\nvoid SelfIntersection::clear() {\n    m_intersecting_pairs.clear();\n}\n\nvoid SelfIntersection::handle_intersection_candidate(\n        size_t f_idx_1, size_t f_idx_2) {\n    auto duplicated_vertices = topological_overlap(f_idx_1, f_idx_2);\n    const Vector3I f1 = m_faces.row(f_idx_1);\n    const Vector3I f2 = m_faces.row(f_idx_2);\n    const Triangle_3 t1(m_points[f1[0]], m_points[f1[1]], m_points[f1[2]]);\n    const Triangle_3 t2(m_points[f2[0]], m_points[f2[1]], m_points[f2[2]]);\n\n    bool is_intersecting = false;\n    const size_t num_duplicated_vertices = duplicated_vertices.size();\n    switch (num_duplicated_vertices) {\n        case 0:\n            // triangles do not touch.\n            {\n                bool t1_degenerate = t1.is_degenerate();\n                bool t2_degenerate = t2.is_degenerate();\n                if (t1_degenerate || t2_degenerate) {\n                    // Degenerated triangles are considered as\n                    // self-intersecting.\n                    is_intersecting = true;\n                } else {\n                    is_intersecting = CGAL::do_intersect(t1, t2);\n                }\n            }\n            break;\n        case 3:\n            // duplicated face\n            is_intersecting = true;\n            break;\n        case 1:\n            {\n                // touch at a vertex.\n                size_t shared_vertex = duplicated_vertices[0];\n                Vector2I opp_edge_1 = get_opposite_edge(f1, shared_vertex);\n                Vector2I opp_edge_2 = get_opposite_edge(f2, shared_vertex);\n                Segment_3 seg_1(m_points[opp_edge_1[0]], m_points[opp_edge_1[1]]);\n                Segment_3 seg_2(m_points[opp_edge_2[0]], m_points[opp_edge_2[1]]);\n                is_intersecting =\n                    CGAL::do_intersect(t1, seg_2) ||\n                    CGAL::do_intersect(t2, seg_1);\n            }\n            break;\n        case 2:\n            {\n                // touch at an edge.\n                Vector2I shared_edge(duplicated_vertices[0],\n                        duplicated_vertices[1]);\n                size_t v1 = get_opposite_vertex(f1, shared_edge);\n                size_t v2 = get_opposite_vertex(f2, shared_edge);\n                const auto& p1 = m_points[v1];\n                const auto& p2 = m_points[v2];\n                const auto& p3 = m_points[shared_edge[0]];\n                const auto& p4 = m_points[shared_edge[1]];\n                if (CGAL::coplanar(p1, p2, p3, p4)) {\n                    if (CGAL::collinear(p3, p4, p1)) {\n                        is_intersecting = true;\n                    } else if (CGAL::collinear(p3, p4, p2)) {\n                        is_intersecting = true;\n                    } else {\n                        switch (CGAL::coplanar_orientation(p3, p4, p1, p2)) {\n                            case CGAL::POSITIVE:\n                                is_intersecting = true;\n                                break;\n                            case CGAL::NEGATIVE:\n                                is_intersecting = false;\n                                break;\n                            case CGAL::COLLINEAR:\n                                throw RuntimeError(\n                                        \"Inconsistent CGAL predicate output\");\n                                break;\n                        }\n                    }\n                } else {\n                    is_intersecting = false;\n                }\n            }\n            break;\n        default:\n            throw RuntimeError(\n                    \"Two triangles sharing more than 3 vertices? Something is very wrong\");\n    }\n\n    if (is_intersecting) {\n        m_intersecting_pairs.emplace_back(f_idx_1, f_idx_2);\n    }\n}\n\nstd::vector<size_t> SelfIntersection::topological_overlap(size_t id1, size_t id2) const {\n    Vector3I f1 = m_faces.row(id1);\n    Vector3I f2 = m_faces.row(id2);\n    std::vector<size_t> duplicated_vertices;\n    duplicated_vertices.reserve(3);\n    for (size_t i=0; i<3; i++) {\n        for (size_t j=0; j<3; j++) {\n            if (f1[i] == f2[j]) {\n                duplicated_vertices.push_back(f1[i]);\n            }\n        }\n    }\n    return duplicated_vertices;\n}\n", "meta": {"hexsha": "8e5ac6e0b42e9f2ca2f9fef7116ed40b75e0bf13", "size": 8023, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "dependencies/PyMesh/tools/CGAL/SelfIntersection.cpp", "max_stars_repo_name": "aprieels/3D-watermarking-spectral-decomposition", "max_stars_repo_head_hexsha": "dcab78857d0bb201563014e58900917545ed4673", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2018-06-04T19:52:02.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-22T09:04:00.000Z", "max_issues_repo_path": "dependencies/PyMesh/tools/CGAL/SelfIntersection.cpp", "max_issues_repo_name": "aprieels/3D-watermarking-spectral-decomposition", "max_issues_repo_head_hexsha": "dcab78857d0bb201563014e58900917545ed4673", "max_issues_repo_licenses": ["MIT"], "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/PyMesh/tools/CGAL/SelfIntersection.cpp", "max_forks_repo_name": "aprieels/3D-watermarking-spectral-decomposition", "max_forks_repo_head_hexsha": "dcab78857d0bb201563014e58900917545ed4673", "max_forks_repo_licenses": ["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.3031674208, "max_line_length": 91, "alphanum_fraction": 0.5232456687, "num_tokens": 1920, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7341195269001831, "lm_q2_score": 0.47657965106367595, "lm_q1q2_score": 0.34986642796912015}}
{"text": "#include <algorithm>\n#include <array>\n#include <cmath>\n\n#include <boost/math/constants/constants.hpp>\n#include <Euclid/BoundingVolume/OBB.h>\n#include <Euclid/MeshUtil/CGALMesh.h>\n#include <Euclid/Geometry/TriMeshGeometry.h>\n#include <Euclid/Math/Vector.h>\n#include <Euclid/Render/RayTracer.h>\n\nnamespace Euclid\n{\n\ntemplate<typename Mesh, typename T>\nvoid proxy_view(const Mesh& mesh,\n                const ViewSphere<Mesh>& view_sphere,\n                std::vector<T>& view_scores,\n                float weight)\n{\n    using Point_3 = typename boost::property_traits<\n        typename boost::property_map<Mesh,\n                                     boost::vertex_point_t>::type>::value_type;\n    using Kernel = typename CGAL::Kernel_traits<Point_3>::Kernel;\n    const int proxies = 6;\n    const int width = 256;\n    const int height = 256;\n    const float least_visible =\n        std::cos(boost::math::float_constants::pi / 3.0f);\n    const float w1 = weight;    // weight for projected areas\n    const float w2 = 1.0f - w1; // weight for visible ratios\n\n    auto [vbeg, vend] = vertices(mesh);\n    auto mesh_vpmap = get(boost::vertex_point, mesh);\n    OBB<Kernel> obb;\n    obb.build(vbeg, vend, mesh_vpmap);\n\n    // Compute projected area\n    std::vector<float> positions;\n    std::vector<unsigned> indices;\n    extract_mesh<3>(mesh, positions, indices);\n    positions.push_back(0.0f); // Embree alignment\n    RayTracer raytracer;\n    raytracer.attach_geometry_buffers(positions, indices);\n\n    std::vector<float> projected_areas(proxies);\n    for (size_t i = 0; i < projected_areas.size(); ++i) {\n        OrthoRayCamera cam;\n        auto view_dir = view_sphere.radius * obb.axis(i % 3);\n        if (i >= 3) {\n            view_dir = -view_dir;\n        }\n        Eigen::Vector3f pos, focus, up;\n        cgal_to_eigen(view_sphere.center + view_dir, pos);\n        cgal_to_eigen(view_sphere.center, focus);\n        cgal_to_eigen(obb.axis((i + 1) % 3), up);\n        cam.lookat(pos, focus, up);\n        cam.set_extent(view_sphere.radius * 2.0f, view_sphere.radius * 2.0f);\n\n        std::vector<uint8_t> pixels(width * height, 0);\n        raytracer.render_silhouette(pixels, cam, width, height);\n        auto proj = 0;\n        for (size_t j = 0; j < pixels.size(); ++j) {\n            if (pixels[j] != 0) {\n                ++proj;\n            }\n        }\n        projected_areas[i] = static_cast<float>(proj) / pixels.size();\n    }\n    auto max_proj_area =\n        *std::max_element(projected_areas.begin(), projected_areas.end());\n    for (auto& proj_area : projected_areas) {\n        proj_area /= max_proj_area;\n    }\n\n    // Compute visible ratio\n    std::vector<float> visible_ratios(proxies);\n    std::vector<int> n_visible_facets(proxies, 0);\n    for (const auto& f : faces(mesh)) {\n        auto normal = face_normal(f, mesh);\n        if (normal * obb.axis(0) > least_visible) {\n            ++n_visible_facets[0];\n        }\n        if (normal * obb.axis(1) > least_visible) {\n            ++n_visible_facets[1];\n        }\n        if (normal * obb.axis(2) > least_visible) {\n            ++n_visible_facets[2];\n        }\n        if (-normal * obb.axis(0) > least_visible) {\n            ++n_visible_facets[3];\n        }\n        if (-normal * obb.axis(1) > least_visible) {\n            ++n_visible_facets[4];\n        }\n        if (-normal * obb.axis(2) > least_visible) {\n            ++n_visible_facets[5];\n        }\n    }\n    float inv_nf = 1.0f / num_faces(mesh);\n    std::transform(n_visible_facets.begin(),\n                   n_visible_facets.end(),\n                   visible_ratios.begin(),\n                   [inv_nf](int nf) { return nf * inv_nf; });\n    auto max_visible_ratio =\n        *std::max_element(visible_ratios.begin(), visible_ratios.end());\n    for (auto& visible_ratio : visible_ratios) {\n        visible_ratio /= max_visible_ratio;\n    }\n\n    // Compute final score\n    view_scores.clear();\n    view_scores.resize(num_vertices(view_sphere.mesh), 0.0f);\n    auto sphere_vpmap = get(boost::vertex_point, view_sphere.mesh);\n    auto sphere_vimap = get(boost::vertex_index, view_sphere.mesh);\n    for (const auto& v : vertices(view_sphere.mesh)) {\n        auto view_dir = normalized(get(sphere_vpmap, v) - obb.center());\n        auto i = get(sphere_vimap, v);\n        view_scores[i] += (w1 * projected_areas[0] + w2 * visible_ratios[0]) *\n                          std::max(view_dir * obb.axis(0), 0.0f);\n        view_scores[i] += (w1 * projected_areas[1] + w2 * visible_ratios[1]) *\n                          std::max(view_dir * obb.axis(1), 0.0f);\n        view_scores[i] += (w1 * projected_areas[2] + w2 * visible_ratios[2]) *\n                          std::max(view_dir * obb.axis(2), 0.0f);\n        view_scores[i] += (w1 * projected_areas[3] + w2 * visible_ratios[3]) *\n                          std::max(-view_dir * obb.axis(0), 0.0f);\n        view_scores[i] += (w1 * projected_areas[4] + w2 * visible_ratios[4]) *\n                          std::max(-view_dir * obb.axis(1), 0.0f);\n        view_scores[i] += (w1 * projected_areas[5] + w2 * visible_ratios[5]) *\n                          std::max(-view_dir * obb.axis(2), 0.0f);\n    }\n}\n\n} // namespace Euclid\n", "meta": {"hexsha": "a6b3dd9f3d2e904137a0b48d26015f222d1e5cd4", "size": 5174, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "include/Euclid/ViewSelection/src/ProxyView.cpp", "max_stars_repo_name": "unclejimbo/euclid", "max_stars_repo_head_hexsha": "e118abdcdf51b6bc05cf5aa056bf228e052cf501", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 31.0, "max_stars_repo_stars_event_min_datetime": "2017-05-02T07:04:40.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-31T10:00:01.000Z", "max_issues_repo_path": "include/Euclid/ViewSelection/src/ProxyView.cpp", "max_issues_repo_name": "unclejimbo/euclid", "max_issues_repo_head_hexsha": "e118abdcdf51b6bc05cf5aa056bf228e052cf501", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/Euclid/ViewSelection/src/ProxyView.cpp", "max_forks_repo_name": "unclejimbo/euclid", "max_forks_repo_head_hexsha": "e118abdcdf51b6bc05cf5aa056bf228e052cf501", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2018-07-02T17:59:35.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-18T07:01:17.000Z", "avg_line_length": 38.3259259259, "max_line_length": 79, "alphanum_fraction": 0.5873598763, "num_tokens": 1379, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7718434978390747, "lm_q2_score": 0.45326184801538616, "lm_q1q2_score": 0.34984721020919873}}
{"text": "#include \"scaled_variance.h\"\n\n#include \"smash/../../scatteractionsfinder.cc\"\n\n#include <Eigen/Dense>\n#include <fstream>\n#include <gsl/gsl_sf_bessel.h>\n\n/// Loads particle table from SMASH\nbool load_particle_types() {\n  std::cout << \"Loading SMASH particle types and decay modes\" << std::endl;\n  std::string smash_dir(std::getenv(\"SMASH_DIR\"));\n  if (smash_dir == \"\") {\n    std::cerr << \"Failed to load SMASH particle types. SMASH_DIR is not set.\"\n              << std::endl;\n    return true;\n  }\n  std::ifstream particles_input_file(smash_dir + \"/input/particles.txt\");\n  std::stringstream buffer;\n  if (particles_input_file) {\n    buffer << particles_input_file.rdbuf();\n    smash::ParticleType::create_type_list(buffer.str());\n  } else {\n    std::cerr << \"File with SMASH particle list not found.\" << std::endl;\n    return true;\n  }\n  std::ifstream decaymodes_input_file(smash_dir + \"/input/decaymodes.txt\");\n  if (decaymodes_input_file) {\n    buffer.clear();\n    buffer.str(std::string());\n    buffer << decaymodes_input_file.rdbuf();\n    smash::DecayModes::load_decaymodes(buffer.str());\n    smash::ParticleType::check_consistency();\n  } else {\n    std::cerr << \"File with SMASH decaymodes not found.\" << std::endl;\n    return true;\n  }\n  return false;\n}\n\n\n\nint ScaledVarianceCalculator::set_eos_solver_equations(\n                             const gsl_vector* x, void* params,\n                             gsl_vector* f) {\n  smash::ParticleTypePtrList* types =\n      reinterpret_cast<struct solver_params *>(params)->types;\n  double e = reinterpret_cast<struct solver_params *>(params)->e;\n  double nb = reinterpret_cast<struct solver_params *>(params)->nb;\n  double ns = reinterpret_cast<struct solver_params *>(params)->ns;\n  double nq = reinterpret_cast<struct solver_params *>(params)->nq;\n\n  const double T = gsl_vector_get(x, 0);\n  const double mub = gsl_vector_get(x, 1);\n  const double mus = gsl_vector_get(x, 2);\n  const double muq = gsl_vector_get(x, 3);\n\n  double e_tot = 0.0, nb_tot = 0.0, ns_tot = 0.0, nq_tot = 0.0;\n  for (const smash::ParticleTypePtr t : (*types)) {\n    const double b = t->baryon_number();\n    const double s = t->strangeness();\n    const double q = t->charge();\n    const double z = t->mass() / T;\n    const double mu = mub * b + mus * s + muq * q;\n    const double mu_m_over_T = (mu - t->mass()) / T;\n    const double factor = t->pdgcode().spin_degeneracy() * 4.0 * M_PI *\n                          std::pow(T / (2.0 * M_PI * smash::hbarc), 3);\n    const double k1 = gsl_sf_bessel_Kn_scaled(1, z);\n    const double k2 = gsl_sf_bessel_Kn_scaled(2, z);\n    const double ex = std::exp(mu_m_over_T);\n    double rho = z * z *  k2 * ex * factor;\n    double edens = z * z * (3 * k2 + z * k1) * ex * T * factor;\n    e_tot += edens;\n    nb_tot += rho * b;\n    ns_tot += rho * s;\n    nq_tot += rho * q;\n  }\n  gsl_vector_set(f, 0, e_tot - e);\n  gsl_vector_set(f, 1, nb_tot - nb);\n  gsl_vector_set(f, 2, ns_tot - ns);\n  gsl_vector_set(f, 3, nq_tot - nq);\n  return GSL_SUCCESS;\n}\n\nstd::string ScaledVarianceCalculator::print_solver_state(size_t iter,\n     gsl_multiroot_fsolver* solver) const {\n  std::stringstream s;\n  // clang-format off\n  s << \"iter = \" << iter << \",\"\n    << \" x = \" << gsl_vector_get(solver->x, 0) << \" \"\n               << gsl_vector_get(solver->x, 1) << \" \"\n               << gsl_vector_get(solver->x, 2) << \" \"\n               << gsl_vector_get(solver->x, 3) << \", \"\n    << \"f(x) = \" << gsl_vector_get(solver->f, 0) << \" \"\n                 << gsl_vector_get(solver->f, 1) << \" \"\n                 << gsl_vector_get(solver->f, 2) << \" \"\n                 << gsl_vector_get(solver->f, 3) << \" \"\n                 << std::endl;\n  // clang-format on\n  return s.str();\n\n}\n\nvoid ScaledVarianceCalculator::setTmu_from_conserved(double Etot, double V,\n                                                double B, double S, double Q) {\n  if (quantum_statistics_) {\n    std::cout << \"WARNING: quantum statistics requested, but not implemented \"\n              << \"for (E, B, S, Q) -> (T, muB, muS, muQ) solver.\" << std::endl;\n    throw std::runtime_error(\"\");\n  }\n  const gsl_multiroot_fsolver_type *solver_type = gsl_multiroot_fsolver_hybrid;\n  gsl_multiroot_fsolver* solver = gsl_multiroot_fsolver_alloc(solver_type, 4);\n  gsl_vector* x = gsl_vector_alloc(4);\n  int residual_status = GSL_SUCCESS;\n  size_t iter = 0;\n  std::cout << print_solver_state(iter, solver);\n\n  struct solver_params p = {&all_types_in_the_box_, Etot/V, B/V, S/V, Q/V};\n  gsl_multiroot_function f = {&set_eos_solver_equations, 4, &p};\n\n  gsl_vector_set(x, 0, 0.15);\n  gsl_vector_set(x, 1, 0.01);\n  gsl_vector_set(x, 2, 0.01);\n  gsl_vector_set(x, 3, 0.01);\n\n  gsl_multiroot_fsolver_set(solver, &f, x);\n  do {\n    iter++;\n    const auto iterate_status = gsl_multiroot_fsolver_iterate(solver);\n    // std::cout << print_solver_state(iter, solver);\n\n    // Avoiding too low temperature\n    if (gsl_vector_get(solver->x, 0) < 0.015) {\n      T_ = 0.0;\n      mub_ = 0.0;\n      mus_ = 0.0;\n      muq_ = 0.0;\n      return;\n    }\n\n    // check if solver is stuck\n    if (iterate_status) {\n      break;\n    }\n    residual_status = gsl_multiroot_test_residual(solver->f, 1.e-9);\n  } while (residual_status == GSL_CONTINUE && iter < 1000);\n\n  if (residual_status != GSL_SUCCESS) {\n    std::stringstream solver_parameters;\n    solver_parameters << \"Solver run with \"\n                      << \"e = \" << Etot/V << \", nb = \" << B/V\n                      << \", ns = \" << S/V << \", nq = \" << Q/V\n                      << std::endl;\n    throw std::runtime_error(gsl_strerror(residual_status) +\n                             solver_parameters.str() +\n                             print_solver_state(iter, solver));\n  }\n  T_ = gsl_vector_get(solver->x, 0);\n  mub_ = gsl_vector_get(solver->x, 1);\n  mus_ = gsl_vector_get(solver->x, 2);\n  muq_ = gsl_vector_get(solver->x, 3);\n  gsl_multiroot_fsolver_free(solver);\n  gsl_vector_free(x);\n}\n\nstd::pair<double, double> ScaledVarianceCalculator::scaled_variance(\n    std::function<bool(const smash::ParticleTypePtr)> type_of_interest) {\n\n  constexpr unsigned int m = 5;\n  Eigen::MatrixXd k2_tilde = Eigen::MatrixXd::Zero(m, m);\n  double kappa1 = 0.0;\n\n  for (const smash::ParticleTypePtr ptype : all_types_in_the_box_) {\n    const double b = B_conservation_ ? ptype->baryon_number() : 0;\n    const double s = S_conservation_ ? ptype->strangeness() : 0;\n    const double q = Q_conservation_ ? ptype->charge() : 0;\n    const double z = ptype->mass() / T_;\n    const double mu = mub_ * b + mus_ * s + muq_ * q;\n    const double mu_m_over_T = (mu - ptype->mass()) / T_;\n    if (mu_m_over_T > 0 and quantum_statistics_) {\n      std::cout << \"Warning: quantum expressions for \" << ptype->name() <<\n                   \" do not converge, m < chemical potential.\" << std::endl;\n    }\n    const double factor = ptype->pdgcode().spin_degeneracy() * 4.0 * M_PI *\n                          std::pow(T_ / (2.0 * M_PI * smash::hbarc), 3);\n    double EE = 0.0, EN = 0.0, NN = 0.0, N1 = 0.0;\n    // std::cout << \"Computing matrix for \" << ptype.name() << std::endl;\n    for (unsigned int k = 1; k < quantum_series_max_terms_; k++) {\n      if (k > 1 and !quantum_statistics_) {\n        break;\n      }\n      const double k1 = gsl_sf_bessel_Kn_scaled(1, z * k);\n      const double k2 = gsl_sf_bessel_Kn_scaled(2, z * k);\n      const double x = std::exp(mu_m_over_T * k);\n      double N1_summand = z * z / k * k2 * x;\n      double NN_summand = z * z * k2 * x;\n      double EN_summand = z * z / k * (3 * k2 + k * z * k1) * x;\n      double EE_summand = z * z / (k * k) *\n                          ((z * z * k * k + 12.0) * k2 + 3.0 * z * k * k1) * x;\n      // std::cout << \"k = \" << k\n      //          << \", N1_summand*factor*1000 = \" << N1_summand*factor*1000\n      //          << \", NN_summand*factor*1000 = \" << NN_summand*factor*1000\n      //          << \", EN_summand = \" << EN_summand\n      //          << \", EE_summand = \" << EE_summand << std::endl;\n      if (k > 1 and\n          EE_summand < EE * quantum_series_rel_precision_ and\n          EN_summand < EN * quantum_series_rel_precision_ and\n          NN_summand < NN * quantum_series_rel_precision_ and\n          N1_summand < N1 * quantum_series_rel_precision_) {\n        break;\n      }\n      if (k % 2 == 0 and ptype->pdgcode().is_baryon()) {\n        NN_summand = -NN_summand;\n        EN_summand = -EN_summand;\n        EE_summand = -EE_summand;\n        N1_summand = -N1_summand;\n      }\n      NN += NN_summand;\n      EN += EN_summand;\n      EE += EE_summand;\n      N1 += N1_summand;\n    }\n    EE *= factor;\n    EN *= factor;\n    NN *= factor;\n    N1 *= factor;\n\n    Eigen::MatrixXd k2_tilde_ptype(m, m);\n    // clang-format off\n    k2_tilde_ptype << NN,     EN,    q*NN,    b*NN,    s*NN,\n                      EN,     EE,    q*EN,    b*EN,    s*EN,\n                      q*NN, q*EN,  q*q*NN,  q*b*NN,  q*s*NN,\n                      b*NN, b*EN,  b*q*NN,  b*b*NN,  b*s*NN,\n                      s*NN, s*EN,  s*q*NN,  s*b*NN,  s*s*NN;\n    // clang-format on\n    if (!type_of_interest(ptype)) {\n      k2_tilde_ptype.row(0).setZero();\n      k2_tilde_ptype.col(0).setZero();\n      N1 = 0.0;\n    }\n    kappa1 += N1;\n    k2_tilde += k2_tilde_ptype;\n  }\n\n  if (!energy_conservation_) {\n    k2_tilde.row(1).setZero();\n    k2_tilde.col(1).setZero();\n  }\n  // Remove zero rows and columns before asking for determinant\n  // This uses the property of k2_tilde matrix being symmetric\n  Eigen::Matrix<bool, 1, Eigen::Dynamic> non_zeros =\n      k2_tilde.cast<bool>().colwise().any();\n  const unsigned int n = non_zeros.count();\n  Eigen::MatrixXd k2_tilde_nz(n, n);\n  int i = 0, j;\n  for (unsigned int i0 = 0; i0 < m; ++i0) {\n    if (!non_zeros(i0)) {\n      continue;\n    }\n    j = 0;\n    for (unsigned int j0 = 0; j0 < m; ++j0) {\n      if (non_zeros(j0)) {\n        k2_tilde_nz(i, j) = k2_tilde(i0, j0);\n        j++;\n      }\n    }\n    i++;\n  }\n\n  const double rho_type_interest = kappa1;\n  // No conservation laws: grand-canonical case\n  if (n < 2) {\n    return std::make_pair(rho_type_interest,\n                          k2_tilde_nz(0,0) / kappa1);\n  }\n\n  const double det_k2_tilde = k2_tilde_nz.determinant();\n  const double det_k2 = k2_tilde_nz.block(1, 1, n - 1, n - 1).determinant();\n  const double expected_scaled_variance = det_k2_tilde / det_k2 /\n                                          rho_type_interest;\n  return std::make_pair(rho_type_interest, expected_scaled_variance);\n}\n\nvoid ScaledVarianceCalculator::prepare_decays() {\n  std::vector<smash::ParticleTypePtr> all_stable_hadrons;\n  for (const smash::ParticleType &ptype : smash::ParticleType::list_all()) {\n    if (ptype.is_stable()) {\n      all_stable_hadrons.push_back(&ptype);\n    }\n  }\n\n  for (const smash::ParticleTypePtr res : all_types_in_the_box_) {\n    smash::decaytree::Node tree(res->name(), 1.0, {res}, {res}, {res}, {});\n    constexpr double sqrts = 5.0;  // This is sufficient to add all possible decays\n    smash::decaytree::add_decays(tree, sqrts);\n    std::vector<smash::FinalStateCrossSection> fs = tree.final_state_cross_sections();\n    smash::deduplicate(fs);\n    double wsum = 0.0;\n    for (const smash::FinalStateCrossSection &xs : fs) {\n      wsum += xs.cross_section_;\n    }\n    assert(std::abs(wsum - 1.0) < 1.e-9);\n    std::cout << res->name() << std::endl;\n    for (const smash::FinalStateCrossSection &xs : fs) {\n      std::map<smash::ParticleTypePtr, int> decay_final_states;\n      // For each stable particle count how many of it one finds in the final state\n      for (const smash::ParticleTypePtr ptype : all_stable_hadrons) {\n        std::string little_str = ptype->name(),\n                    big_str = xs.name_;\n        // How many times little_str occurs in big_str?\n        int nPos = big_str.find(little_str, 0);\n        int count = 0;\n        while (nPos != std::string::npos) {\n          count++;\n          nPos = big_str.find(little_str, nPos + little_str.size());\n        }\n        if (count > 0) {\n          decay_final_states[ptype] = count;\n        }\n      }\n      all_decay_final_states_[res].emplace_back(\n          std::make_pair(xs.cross_section_, decay_final_states));\n      std::cout << \"    \" << xs.name_ << \" \" << xs.cross_section_ << \";   \";\n      for (const auto &hadron_count : decay_final_states) {\n        std::cout << hadron_count.second << hadron_count.first->name() << \" \";\n      }\n      std::cout << std::endl;\n    }\n  }\n}\n\nstd::ostream& operator<< (std::ostream& out,\n                          const ScaledVarianceCalculator &svc) {\n  out << \"Scaled variance calculator\" << std::endl;\n  out << \"T [GeV] = \" << svc.T_\n      << \", muB [GeV] = \" << svc.mub_\n      << \", muS [GeV] = \" << svc.mus_\n      << \", muQ [GeV] = \" << svc.muq_ << std::endl;\n  out << \"Quantum statistics = \" << svc.quantum_statistics_ << std::endl;\n  out << \"Included conservation laws: \";\n  if (svc.energy_conservation_) {\n    out << \" energy;\";\n  }\n  if (svc.B_conservation_) {\n    out << \"  baryon number;\";\n  }\n  if (svc.S_conservation_) {\n    out << \" strangeness;\";\n  }\n  if (svc.Q_conservation_) {\n    out << \" electric charge;\";\n  }\n  out << std::endl;\n  out << \"Species in the box:\" << std::endl;\n  for (const smash::ParticleTypePtr t : svc.all_types_in_the_box_) {\n    out << t->name() << \" \";\n  }\n  out << std::endl;\n  return out;\n}\n\n\nint main() {\n  load_particle_types();\n\n  // Prepare the set of particle species in the box\n  std::vector<smash::ParticleTypePtr> hadrons_in_the_box;\n  for (const smash::ParticleType &t : smash::ParticleType::list_all()) {\n    if (t.is_hadron() && t.mass() < 2.0) {\n      hadrons_in_the_box.push_back(&t);\n    }\n  }\n  std::sort(hadrons_in_the_box.begin(), hadrons_in_the_box.end(),\n            [&](smash::ParticleTypePtr ta, smash::ParticleTypePtr tb) {\n              return ta->mass() < tb->mass();\n            });\n\n  const double Temperature = 0.2;  // [GeV]\n  const double muB = 0.0;  // [GeV]\n  const double muS = 0.0;  // [GeV]\n  const double muQ = 0.0;  // [GeV]\n  const bool E_conservation = true;\n  const bool B_conservation = true;\n  const bool S_conservation = true;\n  const bool Q_conservation = true;\n  const bool quantum_statistics = false;\n  ScaledVarianceCalculator svc(hadrons_in_the_box,\n                               Temperature, muB, muS, muQ,\n                               E_conservation, B_conservation,\n                               S_conservation, Q_conservation,\n                               quantum_statistics);\n  svc.prepare_decays();\n/*\n  const double V = 1762.1897;  // [fm^3]\n  const double E_tot = 972.4227;  // [GeV]\n  const double B_tot = 0.0;\n  const double S_tot = 0.0;\n  const double Q_tot = 0.0;\n  svc.setTmu_from_conserved(E_tot, V, B_tot, S_tot, Q_tot);\n  std::cout << svc;\n\n  // Variance of each specie\n  for (const smash::ParticleTypePtr t : hadrons_in_the_box) {\n    const auto density_and_variance = svc.scaled_variance(\n          [&](const smash::ParticleTypePtr t0) { return t0 == t; });\n    std::cout << t->name() << \" \" << density_and_variance.first * V << \" \"\n              << density_and_variance.second << std::endl;\n  }\n\n  // Variance of total number\n  const auto density_and_variance = svc.scaled_variance(\n      [&](const smash::ParticleTypePtr) { return true; });\n  std::cout << \"Ntot \" << density_and_variance.first * V << \" \"\n            << density_and_variance.second << std::endl;\n*/\n}\n", "meta": {"hexsha": "0f5ae1fed94bbb8fd27595bf136c28b1b38b715d", "size": 15343, "ext": "cc", "lang": "C++", "max_stars_repo_path": "scaled_variance.cc", "max_stars_repo_name": "doliinychenko/scaled_variance_cons_laws", "max_stars_repo_head_hexsha": "eb032fe3901cf4f3a2f9bdddb017da84654be18f", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-07-31T10:36:07.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-31T10:36:07.000Z", "max_issues_repo_path": "scaled_variance.cc", "max_issues_repo_name": "doliinychenko/scaled_variance_cons_laws", "max_issues_repo_head_hexsha": "eb032fe3901cf4f3a2f9bdddb017da84654be18f", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "scaled_variance.cc", "max_forks_repo_name": "doliinychenko/scaled_variance_cons_laws", "max_forks_repo_head_hexsha": "eb032fe3901cf4f3a2f9bdddb017da84654be18f", "max_forks_repo_licenses": ["BSD-3-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.793764988, "max_line_length": 86, "alphanum_fraction": 0.5911490582, "num_tokens": 4540, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7718434978390747, "lm_q2_score": 0.4532618480153861, "lm_q1q2_score": 0.3498472102091987}}
{"text": "/*=========================================================================\n\n  Program:   Visualization Toolkit\n  Module:    vtkBoostBrandesCentrality.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#include \"vtkBoostBrandesCentrality.h\"\n\n#include \"vtkCellArray.h\"\n#include \"vtkCellData.h\"\n#include \"vtkMath.h\"\n#include \"vtkInformation.h\"\n#include \"vtkInformationVector.h\"\n#include \"vtkObjectFactory.h\"\n#include \"vtkPointData.h\"\n#include \"vtkFloatArray.h\"\n#include \"vtkDataArray.h\"\n#include \"vtkSmartPointer.h\"\n#include \"vtkStringArray.h\"\n\n#include \"vtkBoostGraphAdapter.h\"\n#include \"vtkDirectedGraph.h\"\n#include \"vtkUndirectedGraph.h\"\n\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/betweenness_centrality.hpp>\n#include <boost/graph/properties.hpp>\n\nusing namespace boost;\n\nvtkStandardNewMacro(vtkBoostBrandesCentrality);\n\n//-----------------------------------------------------------------------------\nvtkBoostBrandesCentrality::vtkBoostBrandesCentrality() :\n  UseEdgeWeightArray    (false),\n  InvertEdgeWeightArray (false),\n  EdgeWeightArrayName   (NULL)\n{\n}\n\n//-----------------------------------------------------------------------------\nvtkBoostBrandesCentrality::~vtkBoostBrandesCentrality()\n{\n  this->SetEdgeWeightArrayName(0);\n}\n\n//-----------------------------------------------------------------------------\nvoid vtkBoostBrandesCentrality::PrintSelf(ostream& os, vtkIndent indent)\n{\n  this->Superclass::PrintSelf(os, indent);\n\n  os << indent << \"UseEdgeWeightArray: \" << this->UseEdgeWeightArray << endl;\n\n  os << indent << \"InvertEdgeWeightArray: \" << this->InvertEdgeWeightArray\n    << endl;\n\n  os << indent << \"this->EdgeWeightArrayName: \" <<\n    (this->EdgeWeightArrayName ?  this->EdgeWeightArrayName : \"NULL\") << endl;\n}\n\n//-----------------------------------------------------------------------------\nint vtkBoostBrandesCentrality::RequestData(\n  vtkInformation *vtkNotUsed(request),\n  vtkInformationVector **inputVector,\n  vtkInformationVector *outputVector)\n{\n  // get the info objects\n  vtkInformation *inInfo = inputVector[0]->GetInformationObject(0);\n  vtkInformation *outInfo = outputVector->GetInformationObject(0);\n\n  // get the input and output\n  vtkGraph *input = vtkGraph::SafeDownCast(\n    inInfo->Get(vtkDataObject::DATA_OBJECT()));\n  vtkGraph *output = vtkGraph::SafeDownCast(\n    outInfo->Get(vtkDataObject::DATA_OBJECT()));\n\n  // Send the data to output.\n  output->ShallowCopy(input);\n\n  // Compute betweenness centrality\n\n  // Property map for vertices\n  vtkFloatArray* vertexCMap = vtkFloatArray::New();\n  vertexCMap->SetName(\"centrality\");\n  identity_property_map imap;\n\n  // Property map for edges\n  vtkFloatArray* edgeCMap = vtkFloatArray::New();\n  edgeCMap->SetName(\"centrality\");\n  vtkGraphEdgePropertyMapHelper<vtkFloatArray*> helper(edgeCMap);\n\n  vtkSmartPointer<vtkDataArray> edgeWeight (0);\n  if(this->UseEdgeWeightArray && this->EdgeWeightArrayName)\n  {\n    if(!this->InvertEdgeWeightArray)\n    {\n      edgeWeight = input->GetEdgeData()->GetArray(this->EdgeWeightArrayName);\n    }\n    else\n    {\n      vtkDataArray* weights =\n          input->GetEdgeData()->GetArray(this->EdgeWeightArrayName);\n\n      if(!weights)\n      {\n        vtkErrorMacro(<<\"Error: Edge weight array \" << this->EdgeWeightArrayName\n                      << \" is set but not found or not a data array.\\n\");\n        return 0;\n      }\n\n      edgeWeight.TakeReference(\n        vtkDataArray::CreateDataArray(weights->GetDataType()));\n\n      double range[2];\n      weights->GetRange(range);\n\n      if(weights->GetNumberOfComponents() > 1)\n      {\n        return 0;\n      }\n\n      for(int i=0; i < weights->GetDataSize(); ++i)\n      {\n        edgeWeight->InsertNextTuple1(range[1] - weights->GetTuple1(i));\n      }\n    }\n\n    if(!edgeWeight)\n    {\n      vtkErrorMacro(<<\"Error: Edge weight array \" << this->EdgeWeightArrayName\n                    << \" is set but not found or not a data array.\\n\");\n      return 0;\n    }\n  }\n\n  // Is the graph directed or undirected\n  if (vtkDirectedGraph::SafeDownCast(output))\n  {\n    vtkDirectedGraph *g = vtkDirectedGraph::SafeDownCast(output);\n    if(edgeWeight)\n    {\n      vtkGraphEdgePropertyMapHelper<vtkDataArray*> helper2(edgeWeight);\n      brandes_betweenness_centrality(g,\n        centrality_map(vertexCMap).edge_centrality_map(\n          helper).vertex_index_map(imap).weight_map(helper2));\n    }\n    else\n    {\n      brandes_betweenness_centrality(g,\n        centrality_map(vertexCMap).edge_centrality_map(\n          helper).vertex_index_map(imap));\n    }\n  }\n  else\n  {\n    vtkUndirectedGraph *g = vtkUndirectedGraph::SafeDownCast(output);\n    if(edgeWeight)\n    {\n      vtkGraphEdgePropertyMapHelper<vtkDataArray*> helper2(edgeWeight);\n      brandes_betweenness_centrality(g,\n             centrality_map(vertexCMap).edge_centrality_map(\n               helper).vertex_index_map(imap).weight_map(helper2));\n    }\n    else\n    {\n      brandes_betweenness_centrality(g,\n             centrality_map(vertexCMap).edge_centrality_map(\n               helper).vertex_index_map(imap));\n    }\n  }\n\n  // Add the arrays to the output and dereference\n  output->GetVertexData()->AddArray(vertexCMap);\n  vertexCMap->Delete();\n  output->GetEdgeData()->AddArray(edgeCMap);\n  edgeCMap->Delete();\n\n  return 1;\n}\n", "meta": {"hexsha": "78bcfee3d0a230474ee2773ae419310fd05cc5fa", "size": 5994, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "Infovis/BoostGraphAlgorithms/vtkBoostBrandesCentrality.cxx", "max_stars_repo_name": "inviCRO/VTK", "max_stars_repo_head_hexsha": "a2dc2e79d4ecb8f6da900535b32e1a2a702c7f48", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-12-02T07:23:36.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-02T07:23:36.000Z", "max_issues_repo_path": "Infovis/BoostGraphAlgorithms/vtkBoostBrandesCentrality.cxx", "max_issues_repo_name": "inviCRO/VTK", "max_issues_repo_head_hexsha": "a2dc2e79d4ecb8f6da900535b32e1a2a702c7f48", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 14.0, "max_issues_repo_issues_event_min_datetime": "2015-04-25T17:54:13.000Z", "max_issues_repo_issues_event_max_datetime": "2017-01-13T15:30:39.000Z", "max_forks_repo_path": "Infovis/BoostGraphAlgorithms/vtkBoostBrandesCentrality.cxx", "max_forks_repo_name": "inviCRO/VTK", "max_forks_repo_head_hexsha": "a2dc2e79d4ecb8f6da900535b32e1a2a702c7f48", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2015-03-13T17:21:31.000Z", "max_forks_repo_forks_event_max_datetime": "2015-03-13T17:21:31.000Z", "avg_line_length": 31.0569948187, "max_line_length": 80, "alphanum_fraction": 0.6301301301, "num_tokens": 1382, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7461389817407016, "lm_q2_score": 0.46879062662624377, "lm_q1q2_score": 0.3497829608004909}}
{"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 * color.cpp\n */\n\n#include \"color.hpp\"\n\n#include <boost/numeric/ublas/matrix.hpp>\n#include <cmath>\n\n\nnamespace imgproc {\n\n/* class RGBColor */\n\nRGBColor::RGBColor( float r, float g, float b )\n    : ublas::vector<float>(3) {\n    (*this)(0) = r; (*this)(1) = g; (*this)(2) = b;\n}\n\nRGBColor::RGBColor( const ublas::vector<float> & c )\n    : ublas::vector<float>( c ) {}\n\nRGBColor::RGBColor( const YCCColor & c )\n    : ublas::vector<float>(3) {\n\n    //assert( c(0) <= 1.0 && c(0) >= 0.0 );\n\n    ublas::matrix<float> a( 3, 3 );\n    a( 0, 0 ) = 1.f; a( 0, 1 ) = 9.2674E-4f; a( 0, 2 ) = 1.4017f;\n    a( 1, 0 ) = 1.f; a( 1, 1 ) =  -0.34370f; a( 1, 2 ) = -0.7142f;\n    a( 2, 0 ) = 1.f; a( 2, 1 ) = 1.7722f; a( 2, 2 ) = 9.9022E-4f;\n\n    *this = RGBColor( ublas::prod( a, c ) );\n\n    // clip to fit into rgb gamut\n    ublas::vector<float> yccnochroma( 3 );\n    yccnochroma(0) = c(0); yccnochroma(1) = yccnochroma(2) = 0.f;\n    ublas::vector<float> nochroma = ublas::prod( a, yccnochroma );\n\n    if ( (*this)(0) < 0.f ) {\n        ublas::vector<float> diff = *this - nochroma;\n        float u = ( 0.f - nochroma(0) ) / ( (*this)(0) - nochroma(0) );\n        *this = RGBColor( nochroma + u * diff );\n    }\n\n    if ( (*this)(0) > 1.f ) {\n        ublas::vector<float> diff = *this - nochroma;\n        float u = ( 1.f - nochroma(0) ) / ( (*this)(0) - nochroma(0) );\n        *this = RGBColor( nochroma + u * diff );\n    }\n\n    if ( (*this)(1) < 0.f ) {\n        ublas::vector<float> diff = *this - nochroma;\n        float u = ( 0.f - nochroma(1) ) / ( (*this)(1) - nochroma(1) );\n        *this = RGBColor( nochroma + u * diff );\n    }\n\n    if ( (*this)(1) > 1.f ) {\n        ublas::vector<float> diff = *this - nochroma;\n        float u = ( 1.f - nochroma(1) ) / ( (*this)(1) - nochroma(1) );\n        *this = RGBColor( nochroma + u * diff );\n    }\n\n    if ( (*this)(2) < 0.f ) {\n        ublas::vector<float> diff = *this - nochroma;\n        float u = ( 0.f - nochroma(2) ) / ( (*this)(2) - nochroma(2) );\n        *this = RGBColor( nochroma + u * diff );\n    }\n\n    if ( (*this)(2) > 1.f ) {\n        ublas::vector<float> diff = *this - nochroma;\n        float u = ( 1.f - nochroma(2) ) / ( (*this)(2) - nochroma(2) );\n        *this = RGBColor( nochroma + u * diff );\n    }\n}\n\n\ngil::rgb8_pixel_t RGBColor::rgbpixel() const {\n\n    return gil::rgb8_pixel_t(\n        (unsigned char)(round( 0xff * (*this)(0) )),\n        (unsigned char)(round( 0xff * (*this)(1) )),\n        (unsigned char)(round( 0xff * (*this)(2) )));\n}\n\nRGBColor::RGBColor( const gil::rgb8_pixel_t & p )\n    : ublas::vector<float>(3) {\n\n    (*this)(0) = (float) p[0] / 0xff;\n    (*this)(1) = (float) p[1] / 0xff;\n    (*this)(2) = (float) p[2] / 0xff;\n}\n\n/* class YCCColor */\n\nYCCColor::YCCColor( float y, float cb, float cr )\n    : ublas::vector<float>(3) {\n    (*this)(0) = y; (*this)(1) = cb; (*this)(2) = cr;\n}\n\nYCCColor::YCCColor( const ublas::vector<float> & c )\n    : ublas::vector<float>( c ) {}\n\nYCCColor::YCCColor( const RGBColor & c )\n    : ublas::vector<float>(3) {\n\n    /*assert( c(0) <= 1.0 && c(0) >= 0.0 );\n    assert( c(1) <= 1.0 && c(1) >= 0.0 );\n    assert( c(2) <= 1.0 && c(2) >= 0.0 );*/\n\n    ublas::matrix<float> a( 3, 3 );\n    a( 0, 0 ) = 0.299f; a( 0, 1 ) = 0.587f; a( 0, 2 ) = 0.114f;\n    a( 1, 0 ) = -0.169f; a( 1, 1 ) = -0.331f; a( 1, 2 ) = 0.500f;\n    a( 2, 0 ) = 0.500f; a( 2, 1 ) = -0.419f; a( 2, 2 ) = -0.081f;\n\n    //std::cout << ublas::prod( a, c );\n\n    *this = YCCColor( ublas::prod( a, c ) );\n\n    //std::cout << \" =? \" << *this << std::endl;\n}\n\nYCCColor::YCCColor( const gil::rgb8_pixel_t & yccpixel )\n    : ublas::vector<float>(3) {\n\n    (*this)(0) = ( (float) yccpixel[0] / 0xff ) - 0.5f;\n    (*this)(1) = ( (float) yccpixel[1] / 0xff ) - 0.5f;\n    (*this)(2) = ( (float) yccpixel[2] / 0xff ) - 0.5f;\n}\n\nYCCColor::YCCColor( const gil::rgb32f_pixel_t & yccpixel )\n    : ublas::vector<float>(3) {\n\n    (*this)(0) = ( yccpixel[0] / 0xff ) - 0.5f;\n    (*this)(1) = ( yccpixel[1] / 0xff ) - 0.5f;\n    (*this)(2) = ( yccpixel[2] / 0xff ) - 0.5f;\n}\n\n\ngil::rgb8_pixel_t YCCColor::yccpixel() const {\n\n    return gil::rgb8_pixel_t(\n        (int) round( 0xff * (*this)(0) ),\n        (int) round( 0xff * ( (*this)(1) + 0.5f ) ),\n        (int) round( 0xff * ( (*this)(2) + 0.5f ) ) );\n}\n\nfloat ccDiff( const YCCColor & color1, const YCCColor & color2 ) {\n\n    float hue1, hue2;\n\n    hue1 = atan2( color1( 2 ), color1( 1 ) );\n\n    hue2 = atan2( color2( 2 ), color2( 1 ) );\n\n    return std::min( fabs( hue1 - hue2 ), float(2 * M_PI) - fabs( hue1 - hue2 ) );\n\n    //return sqr( color2( 1 ) - color1( 1 ) ) + sqr( color2( 2 ) - color1( 2 ) );\n}\n\n} // namespace imgproc \n", "meta": {"hexsha": "e50e1756eb4b1ff82a03bc2636327efe4d1ecd1d", "size": 5998, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "imgproc/color.cpp", "max_stars_repo_name": "melowntech/libimgproc", "max_stars_repo_head_hexsha": "2dc035d12b0d0128f0f97274d2efa62de924b257", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2017-06-23T19:16:00.000Z", "max_stars_repo_stars_event_max_datetime": "2019-03-11T08:10:56.000Z", "max_issues_repo_path": "externals/browser/externals/browser/externals/libimgproc/imgproc/color.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": 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/libimgproc/imgproc/color.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:22:31.000Z", "max_forks_repo_forks_event_max_datetime": "2019-09-25T05:22:31.000Z", "avg_line_length": 32.0748663102, "max_line_length": 82, "alphanum_fraction": 0.5608536179, "num_tokens": 2163, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7279754489059774, "lm_q2_score": 0.480478678047907, "lm_q1q2_score": 0.3497766813416757}}
{"text": "// Copyright (C) 2015 The Regents of the University of California (Regents).\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are\n// met:\n//\n//     * Redistributions of source code must retain the above copyright\n//       notice, this list of conditions and the following disclaimer.\n//\n//     * Redistributions in binary form must reproduce the above\n//       copyright notice, this list of conditions and the following\n//       disclaimer in the documentation and/or other materials provided\n//       with the distribution.\n//\n//     * Neither the name of The Regents or University of California nor the\n//       names of its contributors may be used to endorse or promote products\n//       derived from this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE\n// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n// POSSIBILITY OF SUCH DAMAGE.\n//\n// Please contact the author of this library if you have any questions.\n// Author: Chris Sweeney (cmsweeney@cs.ucsb.edu)\n\n#include \"theia/sfm/global_pose_estimation/least_unsquared_deviation_position_estimator.h\"\n\n#include <ceres/rotation.h>\n#include <Eigen/Core>\n#include <Eigen/SparseCore>\n\n#include <limits>\n#include <unordered_map>\n#include <vector>\n\n#include \"theia/math/qp_solver.h\"\n#include \"theia/sfm/global_pose_estimation/pairwise_translation_and_scale_error.h\"\n#include \"theia/sfm/types.h\"\n#include \"theia/util/map_util.h\"\n#include \"theia/util/util.h\"\n\nnamespace theia {\nnamespace {\n\nusing Eigen::Matrix3d;\nusing Eigen::Vector3d;\n\nVector3d GetRotatedTranslation(const Vector3d& rotation_angle_axis,\n                               const Vector3d& translation) {\n  Matrix3d rotation;\n  ceres::AngleAxisToRotationMatrix(\n      rotation_angle_axis.data(),\n      ceres::ColumnMajorAdapter3x3(rotation.data()));\n  return rotation.transpose() * translation;\n}\n\n}  // namespace\n\nLeastUnsquaredDeviationPositionEstimator::\n    LeastUnsquaredDeviationPositionEstimator(\n        const LeastUnsquaredDeviationPositionEstimator::Options& options)\n    : options_(options) {\n  CHECK_GT(options_.max_num_iterations, 0);\n  CHECK_GT(options_.max_num_reweighted_iterations, 0);\n}\n\nbool LeastUnsquaredDeviationPositionEstimator::EstimatePositions(\n    const std::unordered_map<ViewIdPair, TwoViewInfo>& view_pairs,\n    const std::unordered_map<ViewId, Vector3d>& orientations,\n    std::unordered_map<ViewId, Vector3d>* positions) {\n  CHECK_NOTNULL(positions)->clear();\n\n  InitializeIndexMapping(view_pairs, orientations);\n\n  // Set up the linear system.\n  SetupConstraintMatrix(view_pairs, orientations);\n  solution_.setZero(constraint_matrix_.cols());\n  weights_.setConstant(constraint_matrix_.rows(), 1.0);\n\n  // Set the lower bounds for the QP. The positions should be unbounded while\n  // the scales havea lower bound of 1.0.\n  Eigen::VectorXd lower_bound(constraint_matrix_.cols());\n  lower_bound.head(3 * orientations.size())\n      .setConstant(-std::numeric_limits<double>::infinity());\n  lower_bound.tail(view_pairs.size()).setConstant(1.0);\n\n  // Solve for the camera positions using an IRLS scheme. The values p and r are\n  // constant at zero.\n  Eigen::SparseMatrix<double> P(constraint_matrix_.rows(),\n                                constraint_matrix_.rows());\n  Eigen::VectorXd q(constraint_matrix_.cols());\n  q.setZero();\n  const double r = 0;\n  QPSolver::Options qp_solver_options;\n  qp_solver_options.max_num_iterations = 10;\n  for (int i = 0; i < options_.max_num_reweighted_iterations; i++) {\n    if (i > 0) {\n      UpdateConstraintWeights();\n    }\n\n    // Compute P = A^t * W * A, the quadratic matrix term for our QP.\n    P = constraint_matrix_.transpose() * weights_.matrix().asDiagonal() *\n        constraint_matrix_;\n\n    // Solve the quadratic program. Increase the number of possible iterations\n    // each time.\n    qp_solver_options.max_num_iterations = std::min(\n        options_.max_num_iterations, 2 * qp_solver_options.max_num_iterations);\n    QPSolver qp_solver(qp_solver_options, P, q, r);\n    const Eigen::VectorXd prev_solution = solution_;\n    qp_solver.SetLowerBound(lower_bound);\n    if (!qp_solver.Solve(&solution_)) {\n      LOG(WARNING) << \"Could not solve the Quadratic Program for the least \"\n                      \"unsquared deviations position solver.\";\n      return false;\n    }\n  }\n\n  // Set the estimated positions.\n  for (const auto& view_id_index : view_id_to_index_) {\n    const int index = view_id_index.second;\n    const ViewId view_id = view_id_index.first;\n    if (index == kConstantViewIndex) {\n      (*positions)[view_id] = Eigen::Vector3d::Zero();\n    } else {\n      (*positions)[view_id] = solution_.segment<3>(index);\n    }\n  }\n\n  return true;\n}\n\nvoid LeastUnsquaredDeviationPositionEstimator::InitializeIndexMapping(\n    const std::unordered_map<ViewIdPair, TwoViewInfo>& view_pairs,\n    const std::unordered_map<ViewId, Vector3d>& orientations) {\n  std::unordered_set<ViewId> views;\n  for (const auto& view_pair : view_pairs) {\n    if (ContainsKey(orientations, view_pair.first.first)) {\n      views.insert(view_pair.first.first);\n    }\n    if (ContainsKey(orientations, view_pair.first.second)) {\n      views.insert(view_pair.first.second);\n    }\n  }\n\n  // Create a mapping from the view id to the index of the linear system.\n  int index = kConstantViewIndex;\n  view_id_to_index_.reserve(orientations.size());\n  for (const ViewId view_id : views) {\n    view_id_to_index_[view_id] = index;\n    index += 3;\n  }\n\n  // Create a mapping from the view id pair to the index of the linear system.\n  view_id_pair_to_index_.reserve(view_pairs.size());\n  for (const auto& view_pair : view_pairs) {\n    view_id_pair_to_index_[view_pair.first] = index;\n    ++index;\n  }\n}\n\nvoid LeastUnsquaredDeviationPositionEstimator::SetupConstraintMatrix(\n    const std::unordered_map<ViewIdPair, TwoViewInfo>& view_pairs,\n    const std::unordered_map<ViewId, Vector3d>& orientations) {\n  constraint_matrix_.resize(3 * view_pairs.size(),\n                            3 * orientations.size() + view_pairs.size());\n\n  // Add the camera to camera constraints.\n  std::vector<Eigen::Triplet<double> > triplet_list;\n  triplet_list.reserve(9 * view_pairs.size());\n  int row = 0;\n  for (const auto& view_pair : view_pairs) {\n    const ViewIdPair view_id_pair = view_pair.first;\n\n    const int view1_index = FindOrDie(view_id_to_index_, view_id_pair.first);\n    const int view2_index = FindOrDie(view_id_to_index_, view_id_pair.second);\n    const int scale_index =\n        FindOrDieNoPrint(view_id_pair_to_index_, view_id_pair);\n\n    // Rotate the relative translation so that it is aligned to the global\n    // orientation frame.\n    const Vector3d translation_direction =\n        GetRotatedTranslation(FindOrDie(orientations, view_id_pair.first),\n                              view_pair.second.position_2);\n\n    // Add the constraint for view 1 in the minimization:\n    //   position2 - position1 - scale_1_2 * translation_direction.\n    if (view1_index != kConstantViewIndex) {\n      triplet_list.emplace_back(row + 0, view1_index + 0, -1.0);\n      triplet_list.emplace_back(row + 1, view1_index + 1, -1.0);\n      triplet_list.emplace_back(row + 2, view1_index + 2, -1.0);\n    }\n\n    // Add the constraint for view 2 in the minimization:\n    //   position2 - position1 - scale_1_2 * translation_direction.\n    if (view2_index != kConstantViewIndex) {\n      triplet_list.emplace_back(row + 0, view2_index + 0, 1.0);\n      triplet_list.emplace_back(row + 1, view2_index + 1, 1.0);\n      triplet_list.emplace_back(row + 2, view2_index + 2, 1.0);\n    }\n\n    // Add the constraint for scale in the minimization:\n    //   position2 - position1 - scale_1_2 * translation_direction.\n    triplet_list.emplace_back(row + 0, scale_index, -translation_direction[0]);\n    triplet_list.emplace_back(row + 1, scale_index, -translation_direction[1]);\n    triplet_list.emplace_back(row + 2, scale_index, -translation_direction[2]);\n\n    row += 3;\n  }\n\n  constraint_matrix_.setFromTriplets(triplet_list.begin(), triplet_list.end());\n\n  VLOG(2) << view_pairs.size() << \" camera to camera constraints were added \"\n                                    \"to the position estimation problem.\";\n}\n\n// Compute the error:\n//     err_i_j = || c_j - c_i - scale_i_j * t_i_j ||^2\n//\n// For each pairwise constraint, set w_i_j = (err_i_j + delta)^(-1/2) to\n// reweight the QP solver for robustness.\nvoid LeastUnsquaredDeviationPositionEstimator::UpdateConstraintWeights() {\n  static const double delta = 1e-12;\n  // Compute the errors with a simple matrix multiplication.\n  const Eigen::VectorXd errors = constraint_matrix_ * solution_;\n  weights_ = (errors.array().square() + delta).sqrt().inverse();\n}\n\n}  // namespace theia\n", "meta": {"hexsha": "803be5c6e88ca15cebdabf5cff9a010015a33e89", "size": 9493, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/theia/sfm/global_pose_estimation/least_unsquared_deviation_position_estimator.cc", "max_stars_repo_name": "LEON-MING/TheiaSfM_Leon", "max_stars_repo_head_hexsha": "8ac187b80100ad7f52fe9af49fa4a0db6db226b9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2019-01-17T17:37:37.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-26T09:21:38.000Z", "max_issues_repo_path": "src/theia/sfm/global_pose_estimation/least_unsquared_deviation_position_estimator.cc", "max_issues_repo_name": "LEON-MING/TheiaSfM_Leon", "max_issues_repo_head_hexsha": "8ac187b80100ad7f52fe9af49fa4a0db6db226b9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/theia/sfm/global_pose_estimation/least_unsquared_deviation_position_estimator.cc", "max_forks_repo_name": "LEON-MING/TheiaSfM_Leon", "max_forks_repo_head_hexsha": "8ac187b80100ad7f52fe9af49fa4a0db6db226b9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2019-09-09T03:34:20.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-21T06:00:50.000Z", "avg_line_length": 39.719665272, "max_line_length": 90, "alphanum_fraction": 0.7182134204, "num_tokens": 2271, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.658417487156366, "lm_q2_score": 0.5312093733737563, "lm_q1q2_score": 0.34975754077065646}}
{"text": "// Copyright (C) 2015 The Regents of the University of California (Regents).\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are\n// met:\n//\n//     * Redistributions of source code must retain the above copyright\n//       notice, this list of conditions and the following disclaimer.\n//\n//     * Redistributions in binary form must reproduce the above\n//       copyright notice, this list of conditions and the following\n//       disclaimer in the documentation and/or other materials provided\n//       with the distribution.\n//\n//     * Neither the name of The Regents or University of California nor the\n//       names of its contributors may be used to endorse or promote products\n//       derived from this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE\n// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n// POSSIBILITY OF SUCH DAMAGE.\n//\n// Please contact the author of this library if you have any questions.\n// Author: Chris Sweeney (cmsweeney@cs.ucsb.edu)\n\n#include \"theia/sfm/global_pose_estimation/least_unsquared_deviation_position_estimator.h\"\n\n#include <Eigen/Core>\n#include <Eigen/SparseCore>\n#include <ceres/rotation.h>\n\n#include <limits>\n#include <unordered_map>\n#include <vector>\n\n#include \"theia/math/constrained_l1_solver.h\"\n#include \"theia/sfm/types.h\"\n#include \"theia/util/map_util.h\"\n#include \"theia/util/util.h\"\n\nnamespace theia {\nnamespace {\n\nusing Eigen::Matrix3d;\nusing Eigen::Vector3d;\n\nVector3d GetRotatedTranslation(const Vector3d& rotation_angle_axis,\n                               const Vector3d& translation) {\n  Matrix3d rotation;\n  ceres::AngleAxisToRotationMatrix(\n      rotation_angle_axis.data(),\n      ceres::ColumnMajorAdapter3x3(rotation.data()));\n  return rotation.transpose() * translation;\n}\n\n}  // namespace\n\nLeastUnsquaredDeviationPositionEstimator::\n    LeastUnsquaredDeviationPositionEstimator(\n        const LeastUnsquaredDeviationPositionEstimator::Options& options)\n    : options_(options) {\n  CHECK_GT(options_.max_num_iterations, 0);\n  CHECK_GT(options_.max_num_reweighted_iterations, 0);\n}\n\nbool LeastUnsquaredDeviationPositionEstimator::EstimatePositions(\n    const std::unordered_map<ViewIdPair, TwoViewInfo>& view_pairs,\n    const std::unordered_map<ViewId, Vector3d>& orientations,\n    std::unordered_map<ViewId, Vector3d>* positions) {\n  CHECK_NOTNULL(positions)->clear();\n\n  InitializeIndexMapping(view_pairs, orientations);\n  const int num_views = view_id_to_index_.size();\n  const int num_view_pairs = view_id_pair_to_index_.size();\n\n  // Set up the linear system.\n  SetupConstraintMatrix(view_pairs, orientations);\n  Eigen::VectorXd solution;\n  solution.setZero(constraint_matrix_.cols());\n\n  // Create the lower bound constraint enforcing that all scales are > 1.\n  Eigen::SparseMatrix<double> geq_mat(num_view_pairs,\n                                      constraint_matrix_.cols());\n  for (int i = 0; i < num_view_pairs; i++) {\n    geq_mat.insert(i, 3 * (num_views - 1) + i) = 1.0;\n  }\n  Eigen::VectorXd geq_vec(num_view_pairs);\n  geq_vec.setConstant(1.0);\n\n  Eigen::VectorXd b(constraint_matrix_.rows());\n  b.setZero();\n\n  // Solve for camera positions by solving a constrained L1 problem to enforce\n  // all relative translations scales > 1.\n  ConstrainedL1Solver::Options l1_options;\n  ConstrainedL1Solver solver(\n      l1_options, constraint_matrix_, b, geq_mat, geq_vec);\n  solver.Solve(&solution);\n\n  // Set the estimated positions.\n  for (const auto& view_id_index : view_id_to_index_) {\n    const int index = view_id_index.second;\n    const ViewId view_id = view_id_index.first;\n    if (index == kConstantViewIndex) {\n      (*positions)[view_id] = Eigen::Vector3d::Zero();\n    } else {\n      (*positions)[view_id] = solution.segment<3>(index);\n    }\n  }\n\n  return true;\n}\n\nvoid LeastUnsquaredDeviationPositionEstimator::InitializeIndexMapping(\n    const std::unordered_map<ViewIdPair, TwoViewInfo>& view_pairs,\n    const std::unordered_map<ViewId, Vector3d>& orientations) {\n  std::unordered_set<ViewId> views;\n  for (const auto& view_pair : view_pairs) {\n    if (ContainsKey(orientations, view_pair.first.first) &&\n        ContainsKey(orientations, view_pair.first.second)) {\n      views.insert(view_pair.first.first);\n      views.insert(view_pair.first.second);\n    }\n  }\n\n  // Create a mapping from the view id to the index of the linear system.\n  int index = kConstantViewIndex;\n  view_id_to_index_.reserve(views.size());\n  for (const ViewId view_id : views) {\n    view_id_to_index_[view_id] = index;\n    index += 3;\n  }\n\n  // Create a mapping from the view id pair to the index of the linear system.\n  view_id_pair_to_index_.reserve(view_pairs.size());\n  for (const auto& view_pair : view_pairs) {\n    if (ContainsKey(view_id_to_index_, view_pair.first.first) &&\n        ContainsKey(view_id_to_index_, view_pair.first.second)) {\n      view_id_pair_to_index_[view_pair.first] = index;\n      ++index;\n    }\n  }\n}\n\nvoid LeastUnsquaredDeviationPositionEstimator::SetupConstraintMatrix(\n    const std::unordered_map<ViewIdPair, TwoViewInfo>& view_pairs,\n    const std::unordered_map<ViewId, Vector3d>& orientations) {\n  constraint_matrix_.resize(\n      3 * view_id_pair_to_index_.size(),\n      3 * (view_id_to_index_.size() - 1) + view_pairs.size());\n\n  // Add the camera to camera constraints.\n  std::vector<Eigen::Triplet<double> > triplet_list;\n  triplet_list.reserve(9 * view_pairs.size());\n  int row = 0;\n  for (const auto& view_pair : view_pairs) {\n    const ViewIdPair view_id_pair = view_pair.first;\n    if (!ContainsKey(view_id_to_index_, view_id_pair.first) ||\n        !ContainsKey(view_id_to_index_, view_id_pair.second)) {\n      continue;\n    }\n\n    const int view1_index = FindOrDie(view_id_to_index_, view_id_pair.first);\n    const int view2_index = FindOrDie(view_id_to_index_, view_id_pair.second);\n    const int scale_index =\n        FindOrDieNoPrint(view_id_pair_to_index_, view_id_pair);\n\n    // Rotate the relative translation so that it is aligned to the global\n    // orientation frame.\n    const Vector3d translation_direction =\n        GetRotatedTranslation(FindOrDie(orientations, view_id_pair.first),\n                              view_pair.second.position_2);\n\n    // Add the constraint for view 1 in the minimization:\n    //   position2 - position1 - scale_1_2 * translation_direction.\n    if (view1_index != kConstantViewIndex) {\n      triplet_list.emplace_back(row + 0, view1_index + 0, -1.0);\n      triplet_list.emplace_back(row + 1, view1_index + 1, -1.0);\n      triplet_list.emplace_back(row + 2, view1_index + 2, -1.0);\n    }\n\n    // Add the constraint for view 2 in the minimization:\n    //   position2 - position1 - scale_1_2 * translation_direction.\n    if (view2_index != kConstantViewIndex) {\n      triplet_list.emplace_back(row + 0, view2_index + 0, 1.0);\n      triplet_list.emplace_back(row + 1, view2_index + 1, 1.0);\n      triplet_list.emplace_back(row + 2, view2_index + 2, 1.0);\n    }\n\n    // Add the constraint for scale in the minimization:\n    //   position2 - position1 - scale_1_2 * translation_direction.\n    triplet_list.emplace_back(row + 0, scale_index, -translation_direction[0]);\n    triplet_list.emplace_back(row + 1, scale_index, -translation_direction[1]);\n    triplet_list.emplace_back(row + 2, scale_index, -translation_direction[2]);\n\n    row += 3;\n  }\n\n  constraint_matrix_.setFromTriplets(triplet_list.begin(), triplet_list.end());\n\n  VLOG(2) << view_pairs.size() << \" camera to camera constraints were added \"\n                                  \"to the position estimation problem.\";\n}\n\nstd::unordered_map<ViewId, Eigen::Vector3d> LeastUnsquaredDeviationPositionEstimator::EstimatePositionsWrapper(\n      const std::unordered_map<ViewIdPair, TwoViewInfo>& view_pairs,\n      const std::unordered_map<ViewId, Eigen::Vector3d>& orientation) {\n  std::unordered_map<ViewId, Eigen::Vector3d> positions;\n  EstimatePositions(view_pairs, orientation, &positions);\n  return positions;\n}\n\n}  // namespace theia\n", "meta": {"hexsha": "d177c76fb596b2023b4edea88e962f3f0509ca2c", "size": 8771, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/theia/sfm/global_pose_estimation/least_unsquared_deviation_position_estimator.cc", "max_stars_repo_name": "Sergej91/TheiaSfM", "max_stars_repo_head_hexsha": "e603e16888456c3e565a2c197fa9f8643c176175", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/theia/sfm/global_pose_estimation/least_unsquared_deviation_position_estimator.cc", "max_issues_repo_name": "Sergej91/TheiaSfM", "max_issues_repo_head_hexsha": "e603e16888456c3e565a2c197fa9f8643c176175", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/theia/sfm/global_pose_estimation/least_unsquared_deviation_position_estimator.cc", "max_forks_repo_name": "Sergej91/TheiaSfM", "max_forks_repo_head_hexsha": "e603e16888456c3e565a2c197fa9f8643c176175", "max_forks_repo_licenses": ["BSD-3-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.331838565, "max_line_length": 111, "alphanum_fraction": 0.724660814, "num_tokens": 2111, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6442251064863697, "lm_q2_score": 0.5428632831725052, "lm_q1q2_score": 0.3497261564093474}}
{"text": "/**\nBSD 3-Clause License\n\nThis file is part of the code accompanying the paper\nFrom Planes to Corners: Multi-Purpose Primitive Detection in Unorganized 3D Point Clouds\nby C. Sommer, Y. Sun, L. Guibas, D. Cremers and T. Birdal,\naccepted for Publication in IEEE Robotics and Automation Letters (RA-L) 2020.\n\nCopyright (c) 2019, Christiane Sommer.\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n\n* Redistributions of source code must retain the above copyright notice, this\n  list of conditions and the following disclaimer.\n\n* Redistributions in binary form must reproduce the above copyright notice,\n  this list of conditions and the following disclaimer in the documentation\n  and/or other materials provided with the distribution.\n\n* Neither the name of the copyright holder nor the names of its\n  contributors may be used to endorse or promote products derived from\n  this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\nDISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\nFOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\nDAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\nSERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\nCAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\nOR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*/\n\n// includes\n#include <iostream>\n#include <fstream>\n#include \"definitions.h\"\n// libraries\n#include <Eigen/Dense>\n#include <opencv2/core/core.hpp>\n#include <sophus/so3.hpp>\n#include <CLI/CLI.hpp>\n// classes\n#include \"Timer.h\"\n#include \"Plane.h\"\n#include \"graph/PlaneGraph.h\"\n#include \"graph/ParallelPlaneGraph.h\"\n#include \"PPF/PairDetector.h\"\n#include \"corners/Corner.h\"\n// function includes\n#include \"io/load_ply_cloud.h\"\n#include \"visualize/pcshow.h\"\n\n/*\n * main\n */\nint main(int argc, char** argv) {\n\n    Timer T;\n    \n    // parse setttings from command line\n    std::string ply_file;\n    int min_votes = 5;\n    double d_min = .1, d_max = 1.;\n    int sampling = 50;\n\n    CLI::App app{\"Detect and refine orthogonal plane configurations\"};\n    app.add_option(\"--img\", ply_file, \"ply file path, from data/\")->required();\n    app.add_option(\"--min-votes\", min_votes, \"minimal number of votes to accept configuration\");\n    app.add_option(\"--dmin\", d_min, \"minimal distance between two points\");\n    app.add_option(\"--dmax\", d_max, \"maximal distance between two points\");\n    app.add_option(\"--sampling\", sampling, \"sampling of points\");\n\n    try {\n        app.parse(argc, argv);\n    } catch (const CLI::ParseError& e) {\n        return app.exit(e);\n    }\n    \n    // load data\n    std::string filepath = \"../data/\";\n    std::vector<Eigen::Vector3f> points;\n    std::vector<Eigen::Vector3f> normals;\n    \n    T.tic();\n    read_ply_file(filepath+ply_file, points, normals);\n    T.toc(\"read data\");\n    std::cout << points.size() << \" points loaded.\" << std::endl;\n    std::cout << normals.size() << \" normals loaded.\" << std::endl;\n    \n    pcshow(points);\n              \n    // pairing\n    ppf::PairDetector pairDet(d_max, d_min, min_votes);\n    PlaneGraph planeMap(pairDet.para_thresh(), pairDet.distance_bin());\n    T.tic();\n    pairDet.detect_ortho_pairs(points, normals, planeMap);\n    T.toc(\"time pairing PPF \");\n    planeMap.print_info();\n    \n    std::cout << std::endl << \"Thresholds:\\tAngle:\\t\" << pairDet.para_thresh() << \"\\tDistance:\\t\" << pairDet.distance_bin() << std::endl << std::endl;\n\n    // clustering & filtering\n    T.tic();\n    planeMap.cluster_graph_vertices();\n    T.toc(\"clustering planes\");\n    planeMap.print_info();\n    planeMap.print_parameters();\n    planeMap.print_edges();\n    \n    // reduce graph to ParallelPlaneGraph\n    T.tic();\n    ParallelPlaneGraph redMap = planeMap.reduce_graph();\n    T.toc(\"graph reduction\");\n    redMap.print_info();\n    redMap.print_edges();\n    T.tic();\n    redMap.triangle_reduce();\n    T.toc(\"triangle reduction\");\n    redMap.print_info();\n    redMap.print_parameters();\n    redMap.print_edges();\n    \n    T.tic();\n    redMap.filter_outliers(points, normals, pairDet.distance_bin(), .5*sampling);\n    T.toc(\"outlier filtering\");\n    redMap.print_info();\n    redMap.print_parameters();\n    redMap.print_edges();\n    \n    // coarse refinement\n    double lambda = .01 * points.size();\n    T.tic();\n    redMap.refine(points, normals, lambda, pairDet.distance_bin(), sampling);\n    redMap.cluster_graph_vertices();\n    T.toc(\"coarse refine and clustering\");\n    redMap.print_info();\n    redMap.print_parameters();\n    redMap.print_edges();     \n\n    T.tic();\n    redMap.filter_outliers(points, normals, pairDet.distance_bin(), .5*sampling);\n    T.toc(\"outlier filtering\");\n    redMap.print_info();\n    redMap.print_parameters();\n    redMap.print_edges();\n      \n    // find triangles\n    std::vector<Graph<ParallelPlaneSet>::Triangle> triangles;\n    T.tic();\n    redMap.find_triangles(triangles);\n    T.toc(\"find triangles in reduced graph\");\n    redMap.print_triangles(triangles);\n    // if no triangles found: stop here\n    if (triangles.size() < 1) {\n        std::cout << \"No corners found, return.\" << std::endl;\n        return 0;\n    }\n    \n    // neighborhood search: Kd-Tree    \n    const PointCloudAdaptor pc2kd(points);\n    KDTree index(3, pc2kd, nanoflann::KDTreeSingleIndexAdaptorParams(10)); // arguments: dimensionality, point cloud adaptor, max leafs\n    index.buildIndex();\n    std::vector<Corner> corners;\n    std::vector<size_t> indices;\n    \n    // find good corners\n    T.tic();\n    for (const auto& t : triangles) {\n        Vec3 n1 = redMap.vertices()[t.first].n();\n        Vec3 n2 = redMap.vertices()[t.second].n();\n        Vec3 n3 = redMap.vertices()[t.third].n();\n        for (const auto d1 : redMap.vertices()[t.first].ds()) for (const auto d2 : redMap.vertices()[t.second].ds()) for (const auto d3 : redMap.vertices()[t.third].ds()) {\n            indices = Corner::eval_candidate(points, normals, n1, d1, n2, d2, n3, d3, index);\n            std::cout << (-d1*n1 - d2*n2 - d3*n3).transpose() << std::endl;\n            if (indices.size() > 0) {\n                Corner c(n1, d1, n2, d2, n3, d3);\n                c.set_indices(indices);\n                if (c.refine(points)) { // only accept if refinement converges\n                    corners.push_back(c);\n                }\n            }\n        }\n    }\n    T.toc(\"evaluated corner candidates\");\n    \n    for (const auto& c : corners) {\n        std::cout << c << std::endl << std::endl;\n    }\n    \n    pcshow_corners(points, corners);\n    \n}\n", "meta": {"hexsha": "71066c48bcbef50ca9ed6aac0efe02fe35d2e700", "size": 6975, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ply_corners/src/main.cpp", "max_stars_repo_name": "OneOneEleven/orthogonal-planes", "max_stars_repo_head_hexsha": "1a0e282897d3852646cdeba37e71999e58906339", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-09-04T15:19:43.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-04T15:19:43.000Z", "max_issues_repo_path": "ply_corners/src/main.cpp", "max_issues_repo_name": "caoccp/orthogonal-planes", "max_issues_repo_head_hexsha": "1a0e282897d3852646cdeba37e71999e58906339", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ply_corners/src/main.cpp", "max_forks_repo_name": "caoccp/orthogonal-planes", "max_forks_repo_head_hexsha": "1a0e282897d3852646cdeba37e71999e58906339", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-03-19T02:43:11.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-19T02:43:11.000Z", "avg_line_length": 35.2272727273, "max_line_length": 172, "alphanum_fraction": 0.6679569892, "num_tokens": 1725, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6442250928250375, "lm_q2_score": 0.5428632831725052, "lm_q1q2_score": 0.3497261489931118}}
{"text": "//=======================================================================\n// Copyright (c) 2013 Piotr Wygocki\n//\n// Distributed under the Boost Software License, Version 1.0. (See\n// accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n//=======================================================================\n/**\n * @file knapsack_unbounded.hpp\n * @brief\n * @author Piotr Wygocki\n * @version 1.0\n * @date 2013-09-20\n */\n#ifndef PAAL_KNAPSACK_UNBOUNDED_HPP\n#define PAAL_KNAPSACK_UNBOUNDED_HPP\n\n#include \"paal/dynamic/knapsack/fill_knapsack_dynamic_table.hpp\"\n#include \"paal/dynamic/knapsack/get_bound.hpp\"\n#include \"paal/dynamic/knapsack/knapsack_common.hpp\"\n#include \"paal/greedy/knapsack_unbounded_two_app.hpp\"\n#include \"paal/utils/functors.hpp\"\n#include \"paal/utils/knapsack_utils.hpp\"\n#include \"paal/utils/less_pointees.hpp\"\n#include \"paal/utils/type_functions.hpp\"\n#include \"paal/utils/irange.hpp\"\n\n#include <boost/range/adaptor/reversed.hpp>\n#include <boost/optional.hpp>\n\n#include <vector>\n\nnamespace paal {\n\nnamespace detail {\n/**\n * @brief For knapsack dynamic algorithm for given element the table has to be\n * traversed from the lowest to highest element\n */\nstruct knapsack_get_position_range {\n    template <typename T>\n    auto operator()(T begin, T end)->decltype(irange(begin, end)) {\n        return irange(begin, end);\n    }\n};\n\ntemplate <typename KnapsackData,\n          typename GetBestElement, typename ValuesComparator,\n          typename ReturnType = typename KnapsackData::return_type>\nReturnType knapsack_unbounded_dynamic(\n    KnapsackData knap_data,\n    GetBestElement getBest, ValuesComparator compareValues) {\n    using Value = typename KnapsackData::value;\n    using Size  = typename KnapsackData::size;\n    using ObjectsIter = typename KnapsackData::object_iter;\n    using ObjIterWithValueOrNull =\n        boost::optional<std::pair<ObjectsIter, Value>>;\n    std::vector<ObjIterWithValueOrNull> objectOnSize(knap_data.get_capacity() + 1);\n\n    auto compare = [ = ](const ObjIterWithValueOrNull & left,\n                         const ObjIterWithValueOrNull & right) {\n        return compareValues(left->second, right->second);\n    };\n\n    auto objectOnSizeBegin = objectOnSize.begin();\n    auto objectOnSizeEnd = objectOnSize.end();\n    fill_knapsack_dynamic_table(objectOnSizeBegin, objectOnSizeEnd, knap_data.get_objects(), knap_data.get_size(),\n                                [&](ObjIterWithValueOrNull val, ObjectsIter obj)\n                                    ->ObjIterWithValueOrNull{\n        return std::make_pair(obj, val->second + knap_data.get_value(*obj));\n    },\n                                compare, [](ObjIterWithValueOrNull & val) {\n        val = std::make_pair(ObjectsIter{}, Value{});\n    },\n                                detail::knapsack_get_position_range());\n\n    // getting position of the max value in the objectOnSize array\n    auto maxPos = getBest(objectOnSizeBegin, objectOnSizeEnd, compare);\n\n    // setting solution\n    auto remainingSpaceInKnapsack = maxPos;\n    while (remainingSpaceInKnapsack != objectOnSizeBegin) {\n        assert(*remainingSpaceInKnapsack);\n        auto && obj = *((*remainingSpaceInKnapsack)->first);\n        knap_data.out(obj);\n        remainingSpaceInKnapsack -= knap_data.get_size(obj);\n    }\n\n    // returning result\n    if (maxPos != objectOnSizeEnd) {\n        assert(*maxPos);\n        return ReturnType((*maxPos)->second, maxPos - objectOnSizeBegin);\n    } else {\n        return ReturnType(Value{}, Size{});\n    }\n}\n\n/**\n * @brief Solution to the knapsack problem\n *\n * @tparam OutputIterator\n * @param objects given objects\n * @param out the result is returned using output iterator\n * @param size functor that for given object returns its size\n * @param value functor that for given object returns its value\n */\ntemplate <typename KnapsackData,\n          typename ReturnType = typename KnapsackData::return_type,\n          typename Size       = typename KnapsackData::size>\nReturnType knapsack(KnapsackData knap_data,\n         unbounded_tag, integral_value_tag, retrieve_solution_tag) {\n    using ValueType = typename KnapsackData::value;\n    using ObjectsIter = typename KnapsackData::object_iter;\n    using TableElementType = boost::optional<std::pair<ObjectsIter, ValueType>>;\n\n    auto && objects = knap_data.get_objects();\n\n    if (boost::empty(objects)) {\n        return ReturnType{};\n    }\n    auto maxSize = get_value_bound(knap_data, unbounded_tag{}, upper_tag{});\n    auto ret = knapsack_unbounded_dynamic(\n            detail::make_knapsack_data(\n        knap_data.get_objects(), maxSize, knap_data.get_value(), knap_data.get_size(), knap_data.get_output_iter()),\n        get_max_element_on_value_indexed_collection<TableElementType, Size>(\n            TableElementType(std::make_pair(ObjectsIter{}, knap_data.get_capacity() + 1))),\n        utils::greater{});\n    return ReturnType(ret.second, ret.first);\n}\n\n/**\n * @brief Solution to the knapsack problem\n *\n * @tparam OutputIterator\n * @param oBegin given objects\n * @param oEnd\n * @param out the result is returned using output iterator\n * @param size functor that for given object returns its size\n * @param value functor that for given object returns its value\n */\ntemplate <typename KnapsackData>\ntypename KnapsackData::return_type\nknapsack(KnapsackData knap_data,\n         unbounded_tag, integral_size_tag, retrieve_solution_tag) {\n    using Value = typename KnapsackData::value;\n    return knapsack_unbounded_dynamic(std::move(knap_data),\n        detail::get_max_element_on_capacity_indexed_collection<Value>(),\n        utils::less{});\n}\n\n} // detail\n\n/**\n * @brief Solution to the knapsack problem\n *\n * @tparam Objects\n * @tparam OutputIterator\n * @tparam ObjectSizeFunctor\n * @tparam ObjectValueFunctor\n * @param oBegin given objects\n * @param oEnd\n * @param out the result is returned using output iterator\n * @param size functor that for given object returns its size\n * @param value functor that for given object returns its value\n */\ntemplate <typename Objects, typename OutputIterator,\n          typename ObjectSizeFunctor,\n          typename ObjectValueFunctor = utils::return_one_functor>\ntypename detail::knapsack_base<Objects, ObjectSizeFunctor,\n                               ObjectValueFunctor>::return_type\nknapsack_unbounded(Objects && objects,\n         detail::FunctorOnRangePValue<ObjectSizeFunctor, Objects>\n             capacity, // capacity is of size type\n         OutputIterator out, ObjectSizeFunctor size,\n         ObjectValueFunctor value = ObjectValueFunctor()) {\n    return detail::knapsack_check_integrality(detail::make_knapsack_data(std::forward<Objects>(objects), capacity, size,\n                                              value, out), detail::unbounded_tag{},\n                                              detail::retrieve_solution_tag());\n}\n\n} // paal\n\n#endif // PAAL_KNAPSACK_UNBOUNDED_HPP\n", "meta": {"hexsha": "9597e8c010b37af43f8bb4dcbea6d75959dad0b6", "size": 6921, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/paal/dynamic/knapsack_unbounded.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/dynamic/knapsack_unbounded.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/dynamic/knapsack_unbounded.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": 37.6141304348, "max_line_length": 120, "alphanum_fraction": 0.6848721283, "num_tokens": 1604, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6442250928250375, "lm_q2_score": 0.5428632831725052, "lm_q1q2_score": 0.3497261489931118}}
{"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/*!\\file NE....cpp\n  \\brief \\ref EMNE_MULTIBODY - C++ input file, Time-Stepping version - O.B.\n\n  A multibody example.\n  Direct description of the model.\n  Simulation with a Time-Stepping scheme.\n*/\n\n#include \"SiconosKernel.hpp\"\n#include \"KneeJointR.hpp\"\n#include \"PrismaticJointR.hpp\"\n#include <boost/math/quaternion.hpp>\nusing namespace std;\n\n/* Given a position of a point in the Inertial Frame and the configuration vector q of a solid\n * returns a position in the spatial frame.\n */\nvoid fromInertialToSpatialFrame(double *positionInInertialFrame, double *positionInSpatialFrame, SP::SiconosVector  q  )\n{\ndouble q0 = q->getValue(3);\ndouble q1 = q->getValue(4);\ndouble q2 = q->getValue(5);\ndouble q3 = q->getValue(6);\n\n::boost::math::quaternion<double>    quatQ(q0, q1, q2, q3);\n::boost::math::quaternion<double>    quatcQ(q0, -q1, -q2, -q3);\n::boost::math::quaternion<double>    quatpos(0, positionInInertialFrame[0], positionInInertialFrame[1], positionInInertialFrame[2]);\n::boost::math::quaternion<double>    quatBuff;\n\n//perform the rotation\nquatBuff = quatQ * quatpos * quatcQ;\n\npositionInSpatialFrame[0] = quatBuff.R_component_2()+q->getValue(0);\npositionInSpatialFrame[1] = quatBuff.R_component_3()+q->getValue(1);\npositionInSpatialFrame[2] = quatBuff.R_component_4()+q->getValue(2);\n\n}\nvoid tipTrajectories(SP::SiconosVector  q, double * traj, double length)\n{\n  double positionInInertialFrame[3];\n  double positionInSpatialFrame[3];\n  // Output the position of the tip of beam1\n  positionInInertialFrame[0]=length/2;\n  positionInInertialFrame[1]=0.0;\n  positionInInertialFrame[2]=0.0;\n  \n  fromInertialToSpatialFrame(positionInInertialFrame, positionInSpatialFrame, q  );\n  traj[0] = positionInSpatialFrame[0];\n  traj[1] = positionInSpatialFrame[1];\n  traj[2] = positionInSpatialFrame[2];\n  \n  \n  // std::cout <<  \"positionInSpatialFrame[0]\" <<  positionInSpatialFrame[0]<<std::endl;\n  // std::cout <<  \"positionInSpatialFrame[1]\" <<  positionInSpatialFrame[1]<<std::endl;\n  // std::cout <<  \"positionInSpatialFrame[2]\" <<  positionInSpatialFrame[2]<<std::endl;\n  \n  positionInInertialFrame[0]=-length/2;\n  fromInertialToSpatialFrame(positionInInertialFrame, positionInSpatialFrame, q  );\n  traj[3]= positionInSpatialFrame[0];\n  traj[4] = positionInSpatialFrame[1];\n  traj[5] = positionInSpatialFrame[2];\n}\n\n\n\n\n\nint main(int argc, char* argv[])\n{\n  try\n  {\n\n\n    // ================= Creation of the model =======================\n\n    // User-defined main parameters\n    unsigned int nDof = 3;\n    unsigned int qDim = 7;\n    unsigned int nDim = 6;\n    double t0 = 0;                   // initial computation time\n    double T = 10.0;                  // final computation time\n    double h = 0.01;                // time step\n    int N = 1000;\n    double L1 = 1.0;\n    double L2 = 1.0;\n    double L3 = 1.0;\n    double theta = 1.0;              // theta for MoreauJeanOSI integrator\n    double g = 9.81; // Gravity\n    double m = 1.;\n\n    // -------------------------\n    // --- Dynamical systems ---\n    // -------------------------\n\n    FILE * pFile;\n    pFile = fopen(\"data.h\", \"w\");\n    if (pFile == NULL)\n    {\n      printf(\"fopen exampleopen filed!\\n\");\n      fclose(pFile);\n    }\n\n\n    cout << \"====> Model loading ...\" << endl << endl;\n    // -- Initial positions and velocities --\n    SP::SiconosVector q03(new SiconosVector(qDim));\n    SP::SiconosVector v03(new SiconosVector(nDim));\n    SP::SimpleMatrix I3(new SimpleMatrix(3, 3));\n    v03->zero();\n    I3->eye();\n    I3->setValue(0, 0, 0.1);\n    q03->zero();\n    (*q03)(2) = -L1 * sqrt(2.0) - L1 / 2;\n\n    double angle = M_PI / 2;\n    SiconosVector V1(3);\n    V1.zero();\n    V1.setValue(0, 0);\n    V1.setValue(1, 1);\n    V1.setValue(2, 0);\n    q03->setValue(3, cos(angle / 2));\n    q03->setValue(4, V1.getValue(0)*sin(angle / 2));\n    q03->setValue(5, V1.getValue(1)*sin(angle / 2));\n    q03->setValue(6, V1.getValue(2)*sin(angle / 2));\n\n    SP::NewtonEulerDS bouncingbeam(new NewtonEulerDS(q03, v03, m, I3));\n    // -- Set external forces (weight) --\n    SP::SiconosVector weight3(new SiconosVector(nDof));\n    (*weight3)(2) = -m * g;\n    bouncingbeam->setFExtPtr(weight3);\n\n    // --------------------\n    // --- Interactions ---\n    // --------------------\n\n    // Interaction with the floor\n    double e = 0.9;\n    SP::SimpleMatrix H(new SimpleMatrix(1, qDim));\n    SP::SiconosVector eR(new SiconosVector(1));\n    eR->setValue(0, 2.3);\n    H->zero();\n    (*H)(0, 2) = 1.0;\n    SP::NonSmoothLaw nslaw0(new NewtonImpactNSL(e));\n    SP::NewtonEulerR relation0(new NewtonEulerR());\n    relation0->setJachq(H);\n    relation0->setE(eR);\n    cout << \"main jacQH\" << endl;\n    relation0->jachq()->display();\n\n\n    // Interactions\n    // Building the prismatic joint for bouncingbeam\n    // input  - the first concerned DS : bouncingbeam\n    //        - an axis in the spatial frame (absolute frame)\n    // SP::SimpleMatrix H4(new SimpleMatrix(PrismaticJointR::numberOfConstraints(), qDim));\n    // H4->zero();\n\n    SP::SiconosVector axe1(new SiconosVector(3));\n    axe1->zero();\n    axe1->setValue(2, 1);\n    SP::PrismaticJointR relation4(new PrismaticJointR(axe1, false, bouncingbeam));\n    SP::NonSmoothLaw nslaw4(new EqualityConditionNSL(relation4->numberOfConstraints()));\n\n    SP::Interaction inter4(new Interaction(nslaw4, relation4));\n    SP::Interaction interFloor(new Interaction(nslaw0, relation0));\n\n    // -------------\n    // --- Model ---\n    // -------------\n    SP::NonSmoothDynamicalSystem myModel(new NonSmoothDynamicalSystem(t0, T));\n    // add the dynamical system in the non smooth dynamical system\n    myModel->insertDynamicalSystem(bouncingbeam);\n    // link the interaction and the dynamical system\n\n    myModel->link(inter4, bouncingbeam);\n    myModel->link(interFloor, bouncingbeam);\n    // ------------------\n    // --- Simulation ---\n    // ------------------\n\n    // -- (1) OneStepIntegrators --\n\n    SP::MoreauJeanOSI OSI3(new MoreauJeanOSI(theta));\n\n    // -- (2) Time discretisation --\n    SP::TimeDiscretisation t(new TimeDiscretisation(t0, h));\n\n    // -- (3) one step non smooth problem\n    SP::OneStepNSProblem osnspb(new MLCP());\n\n    // -- (4) Simulation setup with (1) (2) (3)\n    SP::TimeStepping s(new TimeStepping(myModel, t, OSI3, osnspb));\n    s->setNewtonTolerance(5e-4);\n    s->setNewtonMaxIteration(50);\n\n\n    // =========================== End of model definition ===========================\n\n    // ================================= Computation =================================\n\n    // --- Get the values to be plotted ---\n    // -> saved in a matrix dataPlot\n    unsigned int outputSize = 15 + 7;\n    SimpleMatrix dataPlot(N, outputSize);\n    SimpleMatrix bouncingbeamPlot(2,3*N);\n\n    SP::SiconosVector q3 = bouncingbeam->q();\n    SP::SiconosVector y= interFloor->y(0);\n    SP::SiconosVector ydot= interFloor->y(1);\n\n    // --- Time loop ---\n    cout << \"====> Start computation ... \" << endl << endl;\n    // ==== Simulation loop - Writing without explicit event handling =====\n    int k = 0;\n    boost::progress_display show_progress(N);\n\n    boost::timer time;\n    time.restart();\n    SP::SiconosVector yAux(new SiconosVector(3));\n    yAux->setValue(0, 1);\n    SP::SimpleMatrix Jaux(new SimpleMatrix(3, 3));\n    Index dimIndex(2);\n    Index startIndex(4);\n    fprintf(pFile, \"double T[%d*%d]={\", N + 1, outputSize);\n    double beamTipTrajectories[6];\n    \n    for (k = 0; k < N; k++)\n    {\n      // solve ...\n      s->advanceToEvent();\n\n\n\n      // --- Get values to be plotted ---\n      dataPlot(k, 0) =  s->nextTime();\n      \n      dataPlot(k, 1) = (*q3)(0);\n      dataPlot(k, 2) = (*q3)(1);\n      dataPlot(k, 3) = (*q3)(2);\n      dataPlot(k, 4) = (*q3)(3);\n      dataPlot(k, 5) = (*q3)(4);\n      dataPlot(k, 6) = (*q3)(5);\n      dataPlot(k, 7) = (*q3)(6);\n\n      dataPlot(k, 8) = y->norm2();\n      dataPlot(k, 9) = ydot->norm2();\n\n\n\n      tipTrajectories(q3,beamTipTrajectories,L3);\n      bouncingbeamPlot(0,3*k) = beamTipTrajectories[0];\n      bouncingbeamPlot(0,3*k+1) = beamTipTrajectories[1];\n      bouncingbeamPlot(0,3*k+2) = beamTipTrajectories[2];\n      bouncingbeamPlot(1,3*k) = beamTipTrajectories[3];\n      bouncingbeamPlot(1,3*k+1) = beamTipTrajectories[4];\n      bouncingbeamPlot(1,3*k+2) = beamTipTrajectories[5];\n      \n      //printf(\"reaction1:%lf \\n\", interFloor->lambda(1)->getValue(0));\n\n      for (unsigned int jj = 0; jj < outputSize; jj++)\n      {\n        if ((k || jj))\n          fprintf(pFile, \",\");\n        fprintf(pFile, \"%f\", dataPlot(k, jj));\n      }\n      fprintf(pFile, \"\\n\");\n      s->nextStep();\n      ++show_progress;\n    }\n    fprintf(pFile, \"};\");\n    cout << endl << \"End of computation - Number of iterations done: \" << k - 1 << endl;\n    cout << \"Computation Time \" << time.elapsed()  << endl;\n\n    // --- Output files ---\n    cout << \"====> Output file writing ...\" << endl;\n    ioMatrix::write(\"NE_BouncingBeam.dat\", \"ascii\", dataPlot, \"noDim\");\n    ioMatrix::write(\"NE_BouncingBeam_beam.dat\", \"ascii\", bouncingbeamPlot, \"noDim\");\n\n    double error=0.0, eps=1e-12;\n    if ((error=ioMatrix::compareRefFile(dataPlot, \"NE_BouncingBeam.ref\", eps)) >= 0.0\n        && error > eps)\n      return 1;\n\n\n    fclose(pFile);\n  }\n\n  catch (SiconosException e)\n  {\n    cout << e.report() << endl;\n  }\n  catch (...)\n  {\n    cout << \"Exception caught in NE_...cpp\" << endl;\n  }\n\n}\n", "meta": {"hexsha": "dba64d03fd73b5c2da8652807e6ac9b4094d736e", "size": 10024, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/Mechanics/JointsTests/NE_BouncingBeam.cpp", "max_stars_repo_name": "stpua/siconos", "max_stars_repo_head_hexsha": "01cd4a134746b2b22e6473e7a1d8e5bc892cc2a9", "max_stars_repo_licenses": ["Apache-2.0"], "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/Mechanics/JointsTests/NE_BouncingBeam.cpp", "max_issues_repo_name": "stpua/siconos", "max_issues_repo_head_hexsha": "01cd4a134746b2b22e6473e7a1d8e5bc892cc2a9", "max_issues_repo_licenses": ["Apache-2.0"], "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/Mechanics/JointsTests/NE_BouncingBeam.cpp", "max_forks_repo_name": "stpua/siconos", "max_forks_repo_head_hexsha": "01cd4a134746b2b22e6473e7a1d8e5bc892cc2a9", "max_forks_repo_licenses": ["Apache-2.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.7215189873, "max_line_length": 132, "alphanum_fraction": 0.6122306464, "num_tokens": 2950, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6442250928250375, "lm_q2_score": 0.5428632831725052, "lm_q1q2_score": 0.3497261489931118}}
{"text": "\n#include <dbconnector/dbconnector.hpp>\n#include <boost/math/distributions.hpp>\n#include <modules/prob/student.hpp>\n#include <modules/prob/boost.hpp>\n#include <limits>\n#include <string>\n\n#include \"clustered_errors.hpp\"\n#include \"clustered_errors_state.hpp\"\n\nusing namespace madlib::dbal::eigen_integration;\n\nusing std::string;\n\nnamespace madlib {\nnamespace modules {\nnamespace regress {\n\n// ------------------------------------------------------------------------\n\ntypedef ClusteredState<RootContainer> IClusteredState;\ntypedef ClusteredState<MutableRootContainer> MutableClusteredState;\n\n// ------------------------------------------------------------------------\n\n// function used by linear and logistic transitions\nAnyType __clustered_common_transition (AnyType& args, string regressionType,\n                                       void (*func)(\n                                           MutableClusteredState&,\n                                           const MappedColumnVector&,\n                                           const double& y))\n{\n    // Early return because of an exception has been \"thrown\" \n    // (actually \"warning\") in the previous invocations\n    if (args[0].isNull())\n        return Null();\n    MutableClusteredState state = args[0].getAs<MutableByteString>();\n\n   if (args[1].isNull() || args[2].isNull()) {\n        return args[0];\n    }\n\n    // Get x as a vector of double\n    MappedColumnVector x;\n    try{\n        // an exception is raised in the backend if args[2] contains nulls\n        MappedColumnVector xx = args[2].getAs<MappedColumnVector>();\n        // x is a const reference, we can only rebind to change its pointer\n        x.rebind(xx.memoryHandle(), xx.size());\n    } catch (const ArrayWithNullException &e) {\n        return args[0];\n    }\n\n    double y;\n    if (regressionType == \"log\") //Logistic regression\n        y = args[1].getAs<bool>() ? 1. : -1;\n    else if(regressionType == \"lin\") // Linear regression\n        y = args[1].getAs<double>();\n    else if(regressionType == \"mlog\")//Multi-logistic regression\n    \ty = args[1].getAs<int>();\n\n    // const MappedColumnVector& x = args[2].getAs<MappedColumnVector>();\n\n    if (!std::isfinite(y)) {\n        //throw std::domain_error(\"Dependent variables are not finite.\");\n        warning(\"Dependent variables are not finite.\");\n        return Null();\n    } else if (x.size() > std::numeric_limits<uint16_t>::max()) {\n        //throw std::domain_error(\"Number of independent variables cannot be \"\n        //                        \"larger than 65535.\");\n        warning(\"Number of independent variables cannot be larger than 65535.\");\n        return Null();\n    }\n\n    if (state.numRows == 0) {\n        if(regressionType == \"mlog\")\n        {\n            if (args[4].isNull() || args[5].isNull()) {\n                return args[0];\n            }\n        \tstate.numCategories = static_cast<uint16_t>(args[4].getAs<int>());\n        \tstate.refCategory = static_cast<uint16_t>(args[5].getAs<int>());\n        } else {\n        \tstate.numCategories = 2;\n        \tstate.refCategory = 0;\n        }\n\n        state.widthOfX = static_cast<uint16_t>(x.size() * (state.numCategories-1));\n        state.resize();\n\n        if(regressionType == \"mlog\") {\n\t            MappedMatrix coefMat = args[3].getAs<MappedMatrix>();\n                Matrix mat = coefMat;\n                mat.transposeInPlace();\n                mat.resize(coefMat.size(), 1);\n                state.coef = mat;\n        } else {\n            const MappedColumnVector& coef = args[3].getAs<MappedColumnVector>();\n            state.coef = coef;\n        }\n        state.meat_half.setZero();\n    }\n\n    // dimension check\n    if (state.widthOfX != static_cast<uint16_t>(x.size() * (state.numCategories-1))) {\n        //throw std::runtime_error(\"Inconsistent numbers of independent \"\n        //                         \"variables.\");\n        warning(\"Inconsistent numbers of independent variables.\");\n        return Null();\n    }\n    state.numRows++;\n    (*func)(state, x, y);\n    return state.storage();\n}\n\n// ------------------------------------------------------------------------\n\n// function used by linear and logistic merges\nAnyType __clustered_common_merge (AnyType& args)\n{\n    // In case the aggregator should be terminated because\n    // an exception has been \"thrown\" in the transition function\n    if(args[0].isNull() || args[1].isNull())\n        return Null();\n    MutableClusteredState state1 = args[0].getAs<MutableByteString>();\n    IClusteredState state2 = args[1].getAs<ByteString>();\n\n    if (state1.numRows == 0)\n        return state2.storage();\n    else if (state2.numRows == 0)\n        return state1.storage();\n\n    state1.numRows += state2.numRows;\n    state1.bread += state2.bread;\n    state1.meat_half += state2.meat_half;\n\n    return state1.storage();\n}\n\n// ------------------------------------------------------------------------\n\n// function used by linear and logistic finals\nAnyType __clustered_common_final (AnyType& args)\n{\n    // In case the aggregator should be terminated because\n    // an exception has been \"thrown\" in the transition function\n    if (args[0].isNull())\n        return Null(); \n    IClusteredState state = args[0].getAs<ByteString>();\n    if (state.numRows == 0) return Null();\n\n    Allocator& allocator = defaultAllocator();\n    SymmetricPositiveDefiniteEigenDecomposition<Matrix> decomposition(\n        state.bread, EigenvaluesOnly, ComputePseudoInverse);\n\n    int k = static_cast<int>(state.widthOfX);\n\n    Matrix meat(k, k);\n    meat = trans(state.meat_half) * state.meat_half;\n\n    MutableNativeColumnVector meatvec;\n    MutableNativeColumnVector breadvec;\n    meatvec.rebind(allocator.allocateArray<double>(k*k));\n    breadvec.rebind(allocator.allocateArray<double>(k*k));\n    int count = 0;\n    for (int i = 0; i < k; i++)\n        for (int j = 0; j < k; j++) {\n            meatvec(count) = meat(i,j);\n            breadvec(count) = state.bread(i,j);\n            count++;\n        }\n\n    AnyType tuple;\n\n    tuple << meatvec << breadvec;\n\n    return tuple;\n}\n\n// ------------------------------------------------------------------------\n\n// Compute the stats from coef and errs\nAnyType clustered_compute_stats (AnyType& args,\n                                 void (*func)(\n                                     MutableNativeColumnVector&,\n                                     MutableNativeColumnVector&,\n                                     int, int), bool ismlogr)\n{\n    //const MappedColumnVector& coef = args[0].getAs<MappedColumnVector>();\n    ColumnVector coef;\n    if (ismlogr){\n\t    MappedMatrix coefMat = args[0].getAs<MappedMatrix>();\n        Matrix mat = coefMat;\n        mat.transposeInPlace();\n        mat.resize(coefMat.size(), 1);\n        coef = mat;\n    }else{\n        coef = args[0].getAs<MappedColumnVector>();\n    }\n    const MappedColumnVector& meatvec = args[1].getAs<MappedColumnVector>();\n    const MappedColumnVector& breadvec = args[2].getAs<MappedColumnVector>();\n    int mcluster = args[3].getAs<int>();\n    int numRows = args[4].getAs<int>();\n    int k = static_cast<int>(coef.size());\n    Matrix bread(k,k);\n    Matrix meat(k,k);\n    int count = 0;\n\n    for (int i = 0; i < k; i++)\n        for (int j = 0; j < k; j++)\n        {\n            meat(i,j) = meatvec(count);\n            bread(i,j) = breadvec(count);\n            count++;\n        }\n\n    if (mcluster == 1) {\n        //throw std::domain_error (\"Clustered variance error: Number of clusters cannot be smaller than 2!\");\n        warning(\"Clustered variance error: Number of clusters cannot be smaller than 2!\");\n        return Null();\n    }\n    double dfc = (mcluster / (mcluster - 1.)) * ((numRows - 1.) / (numRows - k));\n\n    SymmetricPositiveDefiniteEigenDecomposition<Matrix> decomposition(\n        bread, EigenvaluesOnly, ComputePseudoInverse);\n    Matrix inverse_of_bread = decomposition.pseudoInverse();\n    Matrix cov(k, k);\n    cov = inverse_of_bread * meat * inverse_of_bread;\n\n    MutableNativeColumnVector errs;\n    MutableNativeColumnVector stats;\n    MutableNativeColumnVector pValues;\n    Allocator& allocator = defaultAllocator();\n\n    errs.rebind(allocator.allocateArray<double>(k));\n    stats.rebind(allocator.allocateArray<double>(k));\n    pValues.rebind(allocator.allocateArray<double>(k));\n    for (int i = 0; i < k; i++)\n    {\n        if (inverse_of_bread(i,i) < 0)\n            errs(i) = 0;\n        else\n            errs(i) = std::sqrt(cov(i,i) * dfc);\n\n        if (coef(i) == 0 && errs(i) == 0)\n            stats(i) = 0;\n        else\n            stats(i) = coef(i) / errs(i);\n    }\n\n    if (numRows > k)\n        (*func)(pValues, stats, numRows, k);\n\n    AnyType tuple;\n\n\ttuple << coef << errs << stats\n\t\t  << (numRows > k\n\t\t\t  ? pValues\n\t\t\t  : Null());\n    return tuple;\n}\n\n// ------------------------------------------------------------------------\n\n// compute t-stats\nvoid __compute_t_stats (MutableNativeColumnVector& pValues,\n                        MutableNativeColumnVector& stats,\n                        int numRows, int k)\n{\n    for (int i = 0; i < k; i++)\n        pValues(i) = 2. * prob::cdf(\n            boost::math::complement(\n                prob::students_t(static_cast<double>(numRows - k)),\n                std::fabs(stats(i))));\n}\n// ------------------------------------------------------------------------\n\n// compute t-stats\nvoid __compute_z_stats (MutableNativeColumnVector& pValues,\n                        MutableNativeColumnVector& stats,\n                        int numRows, int k)\n{\n    (void)numRows;\n    for (int i = 0; i < k; i++)\n        pValues(i) = 2. * prob::cdf(\n            boost::math::complement(prob::normal(), std::fabs(stats(i))));\n}\n\n// ------------------------------------------------------------------------\n// linear clustered\n// ------------------------------------------------------------------------\n\nvoid __linear_trans_compute (MutableClusteredState& state,\n                             const MappedColumnVector& x, const double& y)\n{\n    // On Redhat, I have to use the next a few lines instead of\n    // state.meat_half += (y - trans(state.coef) * x) * x;\n    double sm = 0;\n    for (int i = 0; i < state.widthOfX; i++) sm += state.coef(i) * x(i);\n    sm = y - sm;\n    for (int i = 0; i < state.widthOfX; i++)\n        state.meat_half(0,i) += sm * x(i);\n\n    state.bread += x * trans(x);\n}\n\n// ------------------------------------------------------------------------\n\nAnyType __clustered_err_lin_transition::run (AnyType& args)\n{\n    return __clustered_common_transition(args, \"lin\", __linear_trans_compute);\n}\n\n// ------------------------------------------------------------------------\n\nAnyType __clustered_err_lin_merge::run (AnyType& args)\n{\n    return __clustered_common_merge(args);\n}\n\n// ------------------------------------------------------------------------\n\nAnyType __clustered_err_lin_final::run (AnyType& args)\n{\n    return __clustered_common_final(args);\n}\n\n// ------------------------------------------------------------------------\n\nAnyType clustered_lin_compute_stats::run (AnyType& args)\n{\n    return clustered_compute_stats(args, __compute_t_stats, false);\n}\n\n// ------------------------------------------------------------------------\n// Logistic clustered standard errors\n// ------------------------------------------------------------------------\n\ninline double sigma(double x) {\n\treturn 1. / (1. + std::exp(-x));\n}\n\nvoid __logistic_trans_compute (MutableClusteredState& state,\n                               const MappedColumnVector& x, const double& y)\n{\n    double sm = 0;\n    for (int i = 0; i < state.widthOfX; i++) sm += state.coef(i) * x(i);\n\n    double sgn = y > 0 ? -1 : 1;\n    double t1 = sigma(sgn * sm);\n    double t2 = sigma(-sgn * sm);\n\n    for (int i = 0; i < state.widthOfX; i++)\n        state.meat_half(0,i) += t1 * sgn * x(i);\n\n    state.bread += (t1 * t2) * (x * trans(x));\n}\n\n// ------------------------------------------------------------------------\n\nAnyType __clustered_err_log_transition::run (AnyType& args)\n{\n    return __clustered_common_transition(args, \"log\", __logistic_trans_compute);\n}\n\n// ------------------------------------------------------------------------\n\nAnyType __clustered_err_log_merge::run (AnyType& args)\n{\n    return __clustered_common_merge(args);\n}\n\n// ------------------------------------------------------------------------\n\nAnyType __clustered_err_log_final::run (AnyType& args)\n{\n    return __clustered_common_final(args);\n}\n\n// ------------------------------------------------------------------------\n\nAnyType clustered_log_compute_stats::run (AnyType& args)\n{\n    return clustered_compute_stats(args, __compute_z_stats, false);\n}\n\n\n// ------------------------------------------------------------------------\n// Multi-Logistic clustered standard errors\n// ------------------------------------------------------------------------\n\n\nvoid __mlogistic_trans_compute (MutableClusteredState& state,\n                               const MappedColumnVector& x, const double& y)\n{\n\tint numCategories = state.numCategories -1;\n\tColumnVector yVec(numCategories);\n    yVec.fill(0);\n\n    //Pivot around the reference category\n    if (y > state.refCategory) {\n        yVec((int)y - 1) = 1;\n    } else if (y < state.refCategory) {\n        yVec((int)y) = 1;\n    }\n\n//    if ((int)y != 0) {\n //       yVec(((int)y) - 1) = 1;\n //   }\n\n\t/*\n    Compute the parameter vector (the 'pi' vector in the documentation)\n    for the data point being processed.\n    Casting the coefficients into a matrix makes the calculation simple.\n    */\n    Matrix coef = state.coef;\n    coef.resize(numCategories, state.widthOfX/numCategories);\n\n    //Store the intermediate calculations because we'll reuse them in the LLH\n    ColumnVector t1 = x; //t1 is vector of size state.widthOfX\n    t1 = coef*x;\n    /*\n        Note: The above 2 lines could have been written as:\n        ColumnVector t1 = -coef*x;\n\n        but this creates warnings. These warnings are somehow related to the factor\n        that x is an immutable type.\n    */\n\n    ColumnVector t2 = t1.array().exp();\n    double t3 = 1 + t2.sum();\n    ColumnVector pi = t2/t3;\n    //The gradient matrix has numCatergories rows and widthOfX columns\n    Matrix grad = -yVec * x.transpose() + pi * x.transpose();\n    //We cast the gradient into a vector to make the math easier.\n    grad.resize(state.widthOfX, 1);\n    for (int i = 0; i < state.widthOfX; i++)\n    {\n\t\tstate.meat_half(0,i) += grad(i);\n\t}\n\n\t// Compute the 'a' matrix.\n    Matrix a(numCategories,numCategories);\n    Matrix piDiag = pi.asDiagonal();\n    a = pi * pi.transpose() - piDiag;\n\n    //Start the Hessian calculations\n    //Matrix X_transp_AX(numCategories * state.widthOfX, numCategories * state.widthOfX);\n \tMatrix X_transp_AX( (int)state.widthOfX, (int)state.widthOfX);\n    /*\n        Again: The following 3 lines could have been written as\n        Matrix XXTrans = x * x.transpose();\n        but it creates warnings related to the type of x. Here is an easy fix\n    */\n    Matrix cv_x = x;\n    Matrix XXTrans = trans(cv_x);\n    XXTrans = cv_x * XXTrans;\n\n    //Eigen doesn't supported outer-products for matrices, so we have to do our own.\n    //This operation is also known as a tensor-product.\n    for (int i1 = 0; i1 < (state.widthOfX/numCategories); i1++){\n         for (int i2 = 0; i2 < (state.widthOfX/numCategories); i2++){\n            int rowOffset = numCategories * i1;\n            int colOffset = numCategories * i2;\n\n            X_transp_AX.block(rowOffset, colOffset, numCategories,  numCategories) = XXTrans(i1, i2) * a;\n        }\n    }\n\n    state.bread += -1*X_transp_AX;\n}\n\n// ------------------------------------------------------------------------\n\nAnyType __clustered_err_mlog_transition::run (AnyType& args)\n{\n    return __clustered_common_transition(args, \"mlog\", __mlogistic_trans_compute);\n}\n\n// ------------------------------------------------------------------------\n\nAnyType __clustered_err_mlog_merge::run (AnyType& args)\n{\n    return __clustered_common_merge(args);\n}\n\n// ------------------------------------------------------------------------\n\nAnyType __clustered_err_mlog_final::run (AnyType& args)\n{\n    return __clustered_common_final(args);\n}\n\n// ------------------------------------------------------------------------\n\nAnyType clustered_mlog_compute_stats::run (AnyType& args)\n{\n    return clustered_compute_stats(args,  __compute_z_stats, true);\n}\n\n}\n}\n}\n", "meta": {"hexsha": "84661bd22b30f23085e52bc00e1693511dda7aff", "size": 16406, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/modules/regress/clustered_errors.cpp", "max_stars_repo_name": "fmcquillan99/apache-madlib", "max_stars_repo_head_hexsha": "e2dea62d1eadc7f662f2d926c71f42332f414ca0", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2018-09-18T07:44:22.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-14T19:45:18.000Z", "max_issues_repo_path": "src/modules/regress/clustered_errors.cpp", "max_issues_repo_name": "fmcquillan99/apache-madlib", "max_issues_repo_head_hexsha": "e2dea62d1eadc7f662f2d926c71f42332f414ca0", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-09-06T05:50:17.000Z", "max_issues_repo_issues_event_max_datetime": "2018-09-06T05:50:17.000Z", "max_forks_repo_path": "src/modules/regress/clustered_errors.cpp", "max_forks_repo_name": "fmcquillan99/apache-madlib", "max_forks_repo_head_hexsha": "e2dea62d1eadc7f662f2d926c71f42332f414ca0", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-09-03T20:50:13.000Z", "max_forks_repo_forks_event_max_datetime": "2019-09-03T20:50:13.000Z", "avg_line_length": 32.4871287129, "max_line_length": 109, "alphanum_fraction": 0.5455321224, "num_tokens": 3755, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6992544335934766, "lm_q2_score": 0.5, "lm_q1q2_score": 0.3496272167967383}}
{"text": "/***********************************************************************************************************************\n *  OpenStudio(R), Copyright (c) 2008-2017, Alliance for Sustainable Energy, LLC. All rights reserved.\n *\n *  Redistribution and use in source and binary forms, with or without modification, are permitted provided that the\n *  following conditions are met:\n *\n *  (1) Redistributions of source code must retain the above copyright notice, this list of conditions and the following\n *  disclaimer.\n *\n *  (2) Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the\n *  following disclaimer in the documentation and/or other materials provided with the distribution.\n *\n *  (3) Neither the name of the copyright holder nor the names of any contributors may be used to endorse or promote\n *  products derived from this software without specific prior written permission from the respective party.\n *\n *  (4) Other than as required in clauses (1) and (2), distributions in any form of modifications or other derivative\n *  works may not use the \"OpenStudio\" trademark, \"OS\", \"os\", or any other confusingly similar designation without\n *  specific prior written permission from Alliance for Sustainable Energy, LLC.\n *\n *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES,\n *  INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n *  DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER, THE UNITED STATES GOVERNMENT, OR ANY CONTRIBUTORS BE LIABLE FOR\n *  ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n *  PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED\n *  AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n *  ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n **********************************************************************************************************************/\n\n#include \"CurveExponentialSkewNormal.hpp\"\n#include \"CurveExponentialSkewNormal_Impl.hpp\"\n\n#include <utilities/idd/IddFactory.hxx>\n\n#include <utilities/idd/OS_Curve_ExponentialSkewNormal_FieldEnums.hxx>\n#include <utilities/idd/IddEnums.hxx>\n\n#include \"../utilities/core/Assert.hpp\"\n\n#include <cmath>\n#include <boost/math/special_functions/erf.hpp>\n\nusing namespace std;\n\nnamespace openstudio {\nnamespace model {\n\nnamespace detail {\n\n  CurveExponentialSkewNormal_Impl::CurveExponentialSkewNormal_Impl(const IdfObject& idfObject, Model_Impl* model, bool keepHandle)\n    : Curve_Impl(idfObject,model,keepHandle)\n  {\n    OS_ASSERT(idfObject.iddObject().type() == CurveExponentialSkewNormal::iddObjectType());\n  }\n\n  CurveExponentialSkewNormal_Impl::CurveExponentialSkewNormal_Impl(const openstudio::detail::WorkspaceObject_Impl& other,\n                                                                   Model_Impl* model,\n                                                                   bool keepHandle)\n    : Curve_Impl(other,model,keepHandle)\n  {\n    OS_ASSERT(other.iddObject().type() == CurveExponentialSkewNormal::iddObjectType());\n  }\n\n  CurveExponentialSkewNormal_Impl::CurveExponentialSkewNormal_Impl(const CurveExponentialSkewNormal_Impl& other,\n                                                                   Model_Impl* model,\n                                                                   bool keepHandle)\n    : Curve_Impl(other,model,keepHandle)\n  {}\n\n  const std::vector<std::string>& CurveExponentialSkewNormal_Impl::outputVariableNames() const\n  {\n    static std::vector<std::string> result;\n    if (result.empty()){\n    }\n    return result;\n  }\n\n  IddObjectType CurveExponentialSkewNormal_Impl::iddObjectType() const {\n    return CurveExponentialSkewNormal::iddObjectType();\n  }\n\n  int CurveExponentialSkewNormal_Impl::numVariables() const {\n    return 1;\n  }\n\n  double CurveExponentialSkewNormal_Impl::evaluate(const std::vector<double>& x) const {\n    OS_ASSERT(x.size() == 1u);\n    double z1 = (x[0] - coefficient1C1()) / coefficient2C2();\n    double z2 = (exp(coefficient3C3() * x[0]) * coefficient4C4() * x[0] - coefficient1C1()) / \n                coefficient2C2();\n    double z3 = -coefficient1C1()/coefficient4C4();\n    double numerator = 1.0 + (z2/abs(z2)) * boost::math::erf<double>(abs(z2)/sqrt(2.0));\n    numerator *= exp(-0.5 * pow(z1,2));\n    double denominator = 1.0 + (z3/abs(z3)) * boost::math::erf<double>(abs(z3)/sqrt(2.0));\n    denominator *= exp(-0.5 * pow(z3,2));\n    return numerator/denominator;\n  }\n\n  double CurveExponentialSkewNormal_Impl::coefficient1C1() const {\n    boost::optional<double> value = getDouble(OS_Curve_ExponentialSkewNormalFields::Coefficient1C1,true);\n    OS_ASSERT(value);\n    return value.get();\n  }\n\n  double CurveExponentialSkewNormal_Impl::coefficient2C2() const {\n    boost::optional<double> value = getDouble(OS_Curve_ExponentialSkewNormalFields::Coefficient2C2,true);\n    OS_ASSERT(value);\n    return value.get();\n  }\n\n  double CurveExponentialSkewNormal_Impl::coefficient3C3() const {\n    boost::optional<double> value = getDouble(OS_Curve_ExponentialSkewNormalFields::Coefficient3C3,true);\n    OS_ASSERT(value);\n    return value.get();\n  }\n\n  double CurveExponentialSkewNormal_Impl::coefficient4C4() const {\n    boost::optional<double> value = getDouble(OS_Curve_ExponentialSkewNormalFields::Coefficient4C4,true);\n    OS_ASSERT(value);\n    return value.get();\n  }\n\n  double CurveExponentialSkewNormal_Impl::minimumValueofx() const {\n    boost::optional<double> value = getDouble(OS_Curve_ExponentialSkewNormalFields::MinimumValueofx,true);\n    OS_ASSERT(value);\n    return value.get();\n  }\n\n  double CurveExponentialSkewNormal_Impl::maximumValueofx() const {\n    boost::optional<double> value = getDouble(OS_Curve_ExponentialSkewNormalFields::MaximumValueofx,true);\n    OS_ASSERT(value);\n    return value.get();\n  }\n\n  boost::optional<double> CurveExponentialSkewNormal_Impl::minimumCurveOutput() const {\n    return getDouble(OS_Curve_ExponentialSkewNormalFields::MinimumCurveOutput,true);\n  }\n\n  boost::optional<double> CurveExponentialSkewNormal_Impl::maximumCurveOutput() const {\n    return getDouble(OS_Curve_ExponentialSkewNormalFields::MaximumCurveOutput,true);\n  }\n\n  std::string CurveExponentialSkewNormal_Impl::inputUnitTypeforx() const {\n    boost::optional<std::string> value = getString(OS_Curve_ExponentialSkewNormalFields::InputUnitTypeforx,true);\n    OS_ASSERT(value);\n    return value.get();\n  }\n\n  bool CurveExponentialSkewNormal_Impl::isInputUnitTypeforxDefaulted() const {\n    return isEmpty(OS_Curve_ExponentialSkewNormalFields::InputUnitTypeforx);\n  }\n\n  std::string CurveExponentialSkewNormal_Impl::outputUnitType() const {\n    boost::optional<std::string> value = getString(OS_Curve_ExponentialSkewNormalFields::OutputUnitType,true);\n    OS_ASSERT(value);\n    return value.get();\n  }\n\n  bool CurveExponentialSkewNormal_Impl::isOutputUnitTypeDefaulted() const {\n    return isEmpty(OS_Curve_ExponentialSkewNormalFields::OutputUnitType);\n  }\n\n  void CurveExponentialSkewNormal_Impl::setCoefficient1C1(double coefficient1C1) {\n    bool result = setDouble(OS_Curve_ExponentialSkewNormalFields::Coefficient1C1, coefficient1C1);\n    OS_ASSERT(result);\n  }\n\n  void CurveExponentialSkewNormal_Impl::setCoefficient2C2(double coefficient2C2) {\n    bool result = setDouble(OS_Curve_ExponentialSkewNormalFields::Coefficient2C2, coefficient2C2);\n    OS_ASSERT(result);\n  }\n\n  void CurveExponentialSkewNormal_Impl::setCoefficient3C3(double coefficient3C3) {\n    bool result = setDouble(OS_Curve_ExponentialSkewNormalFields::Coefficient3C3, coefficient3C3);\n    OS_ASSERT(result);\n  }\n\n  void CurveExponentialSkewNormal_Impl::setCoefficient4C4(double coefficient4C4) {\n    bool result = setDouble(OS_Curve_ExponentialSkewNormalFields::Coefficient4C4, coefficient4C4);\n    OS_ASSERT(result);\n  }\n\n  void CurveExponentialSkewNormal_Impl::setMinimumValueofx(double minimumValueofx) {\n    bool result = setDouble(OS_Curve_ExponentialSkewNormalFields::MinimumValueofx, minimumValueofx);\n    OS_ASSERT(result);\n  }\n\n  void CurveExponentialSkewNormal_Impl::setMaximumValueofx(double maximumValueofx) {\n    bool result = setDouble(OS_Curve_ExponentialSkewNormalFields::MaximumValueofx, maximumValueofx);\n    OS_ASSERT(result);\n  }\n\n  void CurveExponentialSkewNormal_Impl::setMinimumCurveOutput(boost::optional<double> minimumCurveOutput) {\n    bool result = false;\n    if (minimumCurveOutput) {\n      result = setDouble(OS_Curve_ExponentialSkewNormalFields::MinimumCurveOutput, minimumCurveOutput.get());\n    } else {\n      result = setString(OS_Curve_ExponentialSkewNormalFields::MinimumCurveOutput, \"\");\n    }\n    OS_ASSERT(result);\n  }\n\n  void CurveExponentialSkewNormal_Impl::resetMinimumCurveOutput() {\n    bool result = setString(OS_Curve_ExponentialSkewNormalFields::MinimumCurveOutput, \"\");\n    OS_ASSERT(result);\n  }\n\n  void CurveExponentialSkewNormal_Impl::setMaximumCurveOutput(boost::optional<double> maximumCurveOutput) {\n    bool result = false;\n    if (maximumCurveOutput) {\n      result = setDouble(OS_Curve_ExponentialSkewNormalFields::MaximumCurveOutput, maximumCurveOutput.get());\n    } else {\n      result = setString(OS_Curve_ExponentialSkewNormalFields::MaximumCurveOutput, \"\");\n    }\n    OS_ASSERT(result);\n  }\n\n  void CurveExponentialSkewNormal_Impl::resetMaximumCurveOutput() {\n    bool result = setString(OS_Curve_ExponentialSkewNormalFields::MaximumCurveOutput, \"\");\n    OS_ASSERT(result);\n  }\n\n  bool CurveExponentialSkewNormal_Impl::setInputUnitTypeforx(std::string inputUnitTypeforx) {\n    bool result = setString(OS_Curve_ExponentialSkewNormalFields::InputUnitTypeforx, inputUnitTypeforx);\n    return result;\n  }\n\n  void CurveExponentialSkewNormal_Impl::resetInputUnitTypeforx() {\n    bool result = setString(OS_Curve_ExponentialSkewNormalFields::InputUnitTypeforx, \"\");\n    OS_ASSERT(result);\n  }\n\n  bool CurveExponentialSkewNormal_Impl::setOutputUnitType(std::string outputUnitType) {\n    bool result = setString(OS_Curve_ExponentialSkewNormalFields::OutputUnitType, outputUnitType);\n    return result;\n  }\n\n  void CurveExponentialSkewNormal_Impl::resetOutputUnitType() {\n    bool result = setString(OS_Curve_ExponentialSkewNormalFields::OutputUnitType, \"\");\n    OS_ASSERT(result);\n  }\n\n} // detail\n\nCurveExponentialSkewNormal::CurveExponentialSkewNormal(const Model& model)\n  : Curve(CurveExponentialSkewNormal::iddObjectType(),model)\n{\n  OS_ASSERT(getImpl<detail::CurveExponentialSkewNormal_Impl>());\n  setDouble(OS_Curve_ExponentialSkewNormalFields::Coefficient1C1,1.0);\n  setDouble(OS_Curve_ExponentialSkewNormalFields::Coefficient2C2,1.0);\n  setDouble(OS_Curve_ExponentialSkewNormalFields::Coefficient3C3,-1.0);\n  setDouble(OS_Curve_ExponentialSkewNormalFields::Coefficient4C4,1.0);\n  setDouble(OS_Curve_ExponentialSkewNormalFields::MinimumValueofx,-1.0);\n  setDouble(OS_Curve_ExponentialSkewNormalFields::MaximumValueofx,1.0);\n}\n\nIddObjectType CurveExponentialSkewNormal::iddObjectType() {\n  IddObjectType result(IddObjectType::OS_Curve_ExponentialSkewNormal);\n  return result;\n}\n\nstd::vector<std::string> CurveExponentialSkewNormal::validInputUnitTypeforxValues() {\n  return getIddKeyNames(IddFactory::instance().getObject(iddObjectType()).get(),\n                        OS_Curve_ExponentialSkewNormalFields::InputUnitTypeforx);\n}\n\nstd::vector<std::string> CurveExponentialSkewNormal::validOutputUnitTypeValues() {\n  return getIddKeyNames(IddFactory::instance().getObject(iddObjectType()).get(),\n                        OS_Curve_ExponentialSkewNormalFields::OutputUnitType);\n}\n\ndouble CurveExponentialSkewNormal::coefficient1C1() const {\n  return getImpl<detail::CurveExponentialSkewNormal_Impl>()->coefficient1C1();\n}\n\ndouble CurveExponentialSkewNormal::coefficient2C2() const {\n  return getImpl<detail::CurveExponentialSkewNormal_Impl>()->coefficient2C2();\n}\n\ndouble CurveExponentialSkewNormal::coefficient3C3() const {\n  return getImpl<detail::CurveExponentialSkewNormal_Impl>()->coefficient3C3();\n}\n\ndouble CurveExponentialSkewNormal::coefficient4C4() const {\n  return getImpl<detail::CurveExponentialSkewNormal_Impl>()->coefficient4C4();\n}\n\ndouble CurveExponentialSkewNormal::minimumValueofx() const {\n  return getImpl<detail::CurveExponentialSkewNormal_Impl>()->minimumValueofx();\n}\n\ndouble CurveExponentialSkewNormal::maximumValueofx() const {\n  return getImpl<detail::CurveExponentialSkewNormal_Impl>()->maximumValueofx();\n}\n\nboost::optional<double> CurveExponentialSkewNormal::minimumCurveOutput() const {\n  return getImpl<detail::CurveExponentialSkewNormal_Impl>()->minimumCurveOutput();\n}\n\nboost::optional<double> CurveExponentialSkewNormal::maximumCurveOutput() const {\n  return getImpl<detail::CurveExponentialSkewNormal_Impl>()->maximumCurveOutput();\n}\n\nstd::string CurveExponentialSkewNormal::inputUnitTypeforx() const {\n  return getImpl<detail::CurveExponentialSkewNormal_Impl>()->inputUnitTypeforx();\n}\n\nbool CurveExponentialSkewNormal::isInputUnitTypeforxDefaulted() const {\n  return getImpl<detail::CurveExponentialSkewNormal_Impl>()->isInputUnitTypeforxDefaulted();\n}\n\nstd::string CurveExponentialSkewNormal::outputUnitType() const {\n  return getImpl<detail::CurveExponentialSkewNormal_Impl>()->outputUnitType();\n}\n\nbool CurveExponentialSkewNormal::isOutputUnitTypeDefaulted() const {\n  return getImpl<detail::CurveExponentialSkewNormal_Impl>()->isOutputUnitTypeDefaulted();\n}\n\nvoid CurveExponentialSkewNormal::setCoefficient1C1(double coefficient1C1) {\n  getImpl<detail::CurveExponentialSkewNormal_Impl>()->setCoefficient1C1(coefficient1C1);\n}\n\nvoid CurveExponentialSkewNormal::setCoefficient2C2(double coefficient2C2) {\n  getImpl<detail::CurveExponentialSkewNormal_Impl>()->setCoefficient2C2(coefficient2C2);\n}\n\nvoid CurveExponentialSkewNormal::setCoefficient3C3(double coefficient3C3) {\n  getImpl<detail::CurveExponentialSkewNormal_Impl>()->setCoefficient3C3(coefficient3C3);\n}\n\nvoid CurveExponentialSkewNormal::setCoefficient4C4(double coefficient4C4) {\n  getImpl<detail::CurveExponentialSkewNormal_Impl>()->setCoefficient4C4(coefficient4C4);\n}\n\nvoid CurveExponentialSkewNormal::setMinimumValueofx(double minimumValueofx) {\n  getImpl<detail::CurveExponentialSkewNormal_Impl>()->setMinimumValueofx(minimumValueofx);\n}\n\nvoid CurveExponentialSkewNormal::setMaximumValueofx(double maximumValueofx) {\n  getImpl<detail::CurveExponentialSkewNormal_Impl>()->setMaximumValueofx(maximumValueofx);\n}\n\nvoid CurveExponentialSkewNormal::setMinimumCurveOutput(double minimumCurveOutput) {\n  getImpl<detail::CurveExponentialSkewNormal_Impl>()->setMinimumCurveOutput(minimumCurveOutput);\n}\n\nvoid CurveExponentialSkewNormal::resetMinimumCurveOutput() {\n  getImpl<detail::CurveExponentialSkewNormal_Impl>()->resetMinimumCurveOutput();\n}\n\nvoid CurveExponentialSkewNormal::setMaximumCurveOutput(double maximumCurveOutput) {\n  getImpl<detail::CurveExponentialSkewNormal_Impl>()->setMaximumCurveOutput(maximumCurveOutput);\n}\n\nvoid CurveExponentialSkewNormal::resetMaximumCurveOutput() {\n  getImpl<detail::CurveExponentialSkewNormal_Impl>()->resetMaximumCurveOutput();\n}\n\nbool CurveExponentialSkewNormal::setInputUnitTypeforx(std::string inputUnitTypeforx) {\n  return getImpl<detail::CurveExponentialSkewNormal_Impl>()->setInputUnitTypeforx(inputUnitTypeforx);\n}\n\nvoid CurveExponentialSkewNormal::resetInputUnitTypeforx() {\n  getImpl<detail::CurveExponentialSkewNormal_Impl>()->resetInputUnitTypeforx();\n}\n\nbool CurveExponentialSkewNormal::setOutputUnitType(std::string outputUnitType) {\n  return getImpl<detail::CurveExponentialSkewNormal_Impl>()->setOutputUnitType(outputUnitType);\n}\n\nvoid CurveExponentialSkewNormal::resetOutputUnitType() {\n  getImpl<detail::CurveExponentialSkewNormal_Impl>()->resetOutputUnitType();\n}\n\n/// @cond\nCurveExponentialSkewNormal::CurveExponentialSkewNormal(std::shared_ptr<detail::CurveExponentialSkewNormal_Impl> impl)\n  : Curve(impl)\n{}\n/// @endcond\n\n} // model\n} // openstudio\n\n", "meta": {"hexsha": "a9b629eb9187dab54e9a5d06f6618875207d8bc1", "size": 16155, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "openstudiocore/src/model/CurveExponentialSkewNormal.cpp", "max_stars_repo_name": "OpenStudioThailand/OpenStudio", "max_stars_repo_head_hexsha": "4e2173955e687ef1b934904acc10939ac0bed52f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2017-10-13T09:23:04.000Z", "max_stars_repo_stars_event_max_datetime": "2017-10-13T09:23:04.000Z", "max_issues_repo_path": "openstudiocore/src/model/CurveExponentialSkewNormal.cpp", "max_issues_repo_name": "OpenStudioThailand/OpenStudio", "max_issues_repo_head_hexsha": "4e2173955e687ef1b934904acc10939ac0bed52f", "max_issues_repo_licenses": ["MIT"], "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/model/CurveExponentialSkewNormal.cpp", "max_forks_repo_name": "OpenStudioThailand/OpenStudio", "max_forks_repo_head_hexsha": "4e2173955e687ef1b934904acc10939ac0bed52f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-03-20T13:19:42.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-20T13:19:42.000Z", "avg_line_length": 42.0703125, "max_line_length": 130, "alphanum_fraction": 0.7636025998, "num_tokens": 3918, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6992544335934765, "lm_q2_score": 0.5, "lm_q1q2_score": 0.34962721679673825}}
{"text": "#ifndef SPARSE_PATCHMAP_H\n#define SPARSE_PATCHMAP_H\n\n#include <algorithm>\n#include <bitset>\n#include <cassert>\n#include <cstdint>\n#include <cstring>\n#include <functional>\n#include <iomanip>\n#include <iostream>\n#include <iterator>\n#include <stdexcept>\n#include <boost/container/allocator.hpp>\n#include <boost/interprocess/allocators/allocator.hpp>\n#include <typeinfo>\n#include <exception>\n#include <memory>\n#include \"wmath_forward.hpp\"\n#include \"wmath_bits.hpp\"\n#include \"wmath_hash.hpp\"\n#include \"wmath_math.hpp\"\n#include \"hashed_array_tree.hpp\"\n#ifdef PATCHMAP_STAT\nsize_t recursion_depth;\nsize_t shift_count;\n#endif\n\nnamespace{\n  template<class T>\n  double frac(const T& n){\n    return n*pow(0.5,std::numeric_limits<T>::digits);\n  }\n}\n\nnamespace wmath{\n  \n  using std::allocator_traits;\n\n  template<typename T>\n  struct dummy_comp{ // dummy comparator for when we don't need a comparator\n    constexpr bool operator()(const T&,const T&) const {return false;}\n  };\n\n  struct empty{\n  };\n  \n  template<class key_type    = int,  // int is the default, why not\n           class mapped_type = int,  // int is the default, why not\n           class hash        = hash_functor<key_type>,\n           class equal       = std::equal_to<key_type>,\n           class comp        = typename conditional<is_injective<hash>::value,\n                                                    dummy_comp<key_type>,\n                                                    std::less<key_type>>::type,\n           class alloc       = typename std::allocator<\n             typename conditional<\n               std::is_same<mapped_type,void>::value,\n               std::pair<key_type,empty>,\n               std::pair<key_type,mapped_type>\n             >::type>,\n           /*class alloc       = typename boost::container::allocator<\n             typename conditional<\n               std::is_same<mapped_type,void>::value,\n               std::pair<key_type,empty>,\n               std::pair<key_type,mapped_type>\n             >::type,2>,*/\n           bool dynamic      = true\n          >\n  class sparse_patchmap{\n    public:\n      typedef alloc allocator_type;\n      typedef typename alloc::value_type value_type;\n      typedef typename alloc::pointer value_pointer;\n      typedef typename alloc::reference reference;\n      typedef typename alloc::const_reference const_reference;\n      typedef typename alloc::difference_type difference_type;\n      typedef typename alloc::size_type size_type;\n      typedef typename std::result_of<hash(key_type)>::type hash_type;\n      typedef typename conditional<is_same<mapped_type,void>::value,\n                                  key_type,\n                                  mapped_type>::type\n                                  _mapped_type;\n    private:\n      size_type num_data = 0;\n      size_type datasize = 0;\n      size_type masksize = 0;\n      allocator_type allocator;\n      boost::container::allocator<size_type,2> maskallocator;\n      hashed_array_tree<value_type,alloc> data;\n      hashed_array_tree< size_type,boost::container::allocator<size_type,2>>\n        mask;\n      comp  comparator;\n      equal equator;\n      hash  hasher;\n      using uphold_iterator_validity = true_type;\n      /* TODO\n      size_type const inline masksize() const {\n        return (datasize+digits<size_type>()-1)/digits<size_type>();\n      }\n      */\n      template<typename T>\n      const key_type& key_of(T&& value) const {\n        if constexpr (is_same<void,mapped_type>::value) return value;\n        else return value.first;\n      }\n      size_type inline map(\n          const hash_type& h,\n          const hash_type& n\n          ) const {\n        return get<0>(long_mul(h,n));\n      }\n      size_type inline map(const hash_type& h) const {\n        return map(h,datasize);\n      }\n      size_type inline map_diff(\n          const hash_type& h0,\n          const hash_type& h1,\n          const hash_type& n\n          ) const {\n        const auto lm = long_mul(h0-h1,n);\n        return get<0>(lm);\n      }\n      size_type inline map_diff(\n          const hash_type& h0,\n          const hash_type& h1\n          ) const {\n        return map_diff(h0,h1,datasize);\n      }\n      size_type inline map_diff_round(\n          const hash_type& h0,\n          const hash_type& h1,\n          const hash_type& n\n          ) const {\n        const auto lm = long_mul(h0-h1,n);\n        return get<0>(lm)+(get<1>(lm)>((~hash_type(0))>>1));\n      }\n      size_type inline map_diff_round(\n          const hash_type& h0,\n          const hash_type& h1\n          ) const {\n        return map_diff_round(h0,h1,datasize);\n      }\n      hash_type inline order(const key_type& k) const {\n        return distribute(hasher(k));\n      }\n      bool inline is_less(\n          const key_type& a,\n          const key_type& b,\n          const hash_type& oa,\n          const hash_type& ob\n          ) const {\n        if constexpr (is_injective<hash>::value){\n          assert(equator(a,b)==(oa==ob));\n          if (oa<ob) return true;\n          else       return false;\n        } else {\n          if (oa<ob) return true;\n          if (oa>ob) return false;\n          return comparator(a,b);\n        }\n      }\n      bool inline is_less(\n          const key_type& a,\n          const key_type& b,\n          const hash_type& oa\n          ) const {\n        return is_less(a,b,oa,order(b));\n      }\n      bool inline is_less(const key_type& a,const key_type& b) const {\n        return is_less(a,b,order(a),order(b));\n      }\n      bool inline is_more(\n          const key_type& a,\n          const key_type& b,\n          const hash_type& oa,\n          const hash_type& ob\n          ) const {\n        if constexpr (is_injective<hash>::value){\n          assert(equator(a,b)==(oa==ob));\n          if (oa>ob) return true;\n          else       return false;\n        } else {\n          if (oa>ob) return true;\n          if (oa<ob) return false;\n          return !((comparator(a,b))||(equator(a,b)));\n        }\n      }\n      bool inline is_more(\n          const key_type& a,\n          const key_type& b,\n          const hash_type& oa\n          ) const {\n        return is_more(a,b,oa,order(b));\n      }\n      bool inline is_more(\n          const key_type& a,\n          const key_type& b\n          ) const {\n        return is_more(a,b,order(a),order(b));\n      }\n      bool inline is_set(const size_type& n) const {\n        const size_type i = n/digits<size_type>();\n        const size_type j = n%digits<size_type>();\n        assert(i<masksize);\n        return (mask[i]&(size_type(1)<<(digits<size_type>()-j-1)));\n      }\n      bool inline is_set_any(\n          const size_type& lo,\n          const size_type& hi) const {\n        const size_type k0 = lo/digits<size_type>();\n        const size_type l0 = lo%digits<size_type>();\n        const size_type m0 = (~size_type(0))>>l0;\n        const size_type k1 = hi/digits<size_type>();\n        const size_type l1 = hi%digits<size_type>();\n        const size_type m1 = (~size_type(0))<<(digits<size_type>()-l1-1);\n        if (k0==k1) return ((m0&m1&mask[k0])!=0);\n        if (((m0&mask[k0])!=0)||((m1&mask[k1])!=0)) return true;\n        for (size_type i = k0+1;i!=k1;++i)\n          if (mask[i]!=0) return true;\n        return false;\n      }\n      void inline set(const size_type& n) {\n        const size_type i = n/digits<size_type>();\n        const size_type j = n%digits<size_type>();\n        mask[i]|=size_type(1)<<(digits<size_type>()-j-1);\n      }\n      void inline unset(const size_type& n) {\n        const size_type i = n/digits<size_type>();\n        const size_type j = n%digits<size_type>();\n        mask[i]&=((~size_type(0))^(size_type(1)<<(digits<size_type>()-j-1)));\n      }\n      void inline swap_set(const size_type& i,const size_type& j){\n        if (is_set(i)==is_set(j)) return;\n        if (is_set(i)){\n          set(j);\n          unset(i);\n        }else{\n          set(i);\n          unset(j);\n        }\n      }\n      bool inline index_key_is_less(const size_type& i,const key_type& k) const{\n        if (is_set(i)) return is_less(data[i].first,k);\n        return i<map(order(k));\n      }\n      bool inline key_index_is_less(const key_type& k,const size_type& i) const{\n        if (is_set(i)) return is_less(k,data[i].first);\n        return map(order(k))<i;\n      }\n      bool inline index_index_is_less(const size_type& i,const size_type& j)\n        const {\n        assert(i<datasize);\n        assert(j<datasize);\n        if (is_set(i)&&is_set(j)) return is_less(data[i].first,data[j].first);\n        if (is_set(i)) return map(order(data[i].first))<j;\n        if (is_set(j)) return i<map(order(data[j].first));\n        return i<j;\n      }\n      bool inline index_index_is_more(const size_type& i,const size_type& j)\n        const {\n        return index_index_is_less(j,i);\n      }\n      size_type inline find_first() const {\n        size_type i=0;\n        if (i>=datasize) return ~size_type(0);\n        while(true){\n          const size_type k = i/digits<size_type>();\n          const size_type l = i%digits<size_type>();\n          const size_type m = (~size_type(0))>>l; \n          assert(k<masksize);\n          size_type p = (mask[k]&m)<<l;\n          if (k+1<masksize)\n            p|=shr(mask[k+1]&(~m),digits<size_type>()-l);\n          const size_type s = clz(p);\n          if (s==0) return i;\n          i+=s;\n          if (i>=datasize) return ~size_type(0);\n        }\n      }\n      // search for free bucket in decreasing order\n      size_type inline search_free_dec(size_type i) const {\n        while(true){\n          const size_type k = i/digits<size_type>();\n          const size_type l = i%digits<size_type>();\n          const size_type m = (~size_type(0))<<(digits<size_type>()-l-1);\n          assert(k<masksize);\n                size_type p = ((~(mask[k]&m))>>(digits<size_type>()-l-1));\n          if (k!=0) p|=shl(~(mask[k-1]&(~m)),l+1);\n          const size_type s = ctz(p);\n          if (s==0){\n            assert(!is_set(i));\n            return i;\n          }\n          i-=s;\n          if (i>=datasize) return ~size_type(0);\n        }\n      }\n      // search for free bucket in increasing order\n      size_type inline search_free_inc(size_type i) const {\n        while(true){\n          const size_type k = i/digits<size_type>();\n          const size_type l = i%digits<size_type>();\n          const size_type m = (~size_type(0))>>l; \n          assert(k<masksize);\n                size_type p = (~(mask[k]&m))<<l;\n          if (k+1<masksize) p|=shr(~(mask[k+1]&(~m)),digits<size_type>()-l);\n          const size_type s = clz(p);\n          if (s==0){\n            assert(!is_set(i));\n            return i;\n          }\n          i+=s;\n          if (i>=datasize) return ~size_type(0);\n        }\n      }\n      // search for free bucket bidirectional\n      size_type inline search_free_bidir_v0(size_type i) const {\n        const size_type k = search_free_inc(i);\n        const size_type l = search_free_dec(i);\n        assert((k<datasize)||(l<datasize));\n        if (k>=datasize) i=l;\n        else if (l>=datasize) i=k;\n        else if (k-i<i-l) i=k;\n        else i=l;\n        return i;\n      }\n      // search for free bucket truly bidirectional\n      // this is optimal vor very high load factors > 0.98\n      size_type inline search_free_bidir(const size_type& n) const {\n        size_type i = n, j = n, si=~size_type(0),sj=~size_type(0);\n        while(true){\n          if ((i!=~size_type(0))&&si){\n            const size_type k = i/digits<size_type>();\n            const size_type l = i%digits<size_type>();\n            const size_type m = (~size_type(0))>>l; \n                  size_type p = (~(mask[k]&m))<<l;\n            if (k+1<masksize) p|=shr(~(mask[k+1]&(~m)),digits<size_type>()-l);\n                            si= clz(p);\n          }\n          if (si==0){\n            if (j==~size_type(0)) return i;\n            if (i-n+digits<size_type>()<=n-j) return i;\n          } else {\n            i+=si;\n            if (i>=datasize) i=~size_type(0);\n            if ((i&j)==~size_type(0)) return ~size_type(0);\n          }\n          if ((j!=~size_type(0))&&sj){\n            const size_type k = j/digits<size_type>();\n            const size_type l = j%digits<size_type>();\n            const size_type m = (~size_type(0))<<(digits<size_type>()-l-1);\n                  size_type p = ((~(mask[k]&m))>>(digits<size_type>()-l-1));\n            if (k!=0)       p|=shl(~(mask[k-1]&(~m)),l+1);\n                            sj= ctz(p);\n          }\n          if (sj==0) {\n            if (i==~size_type(0)) return j;\n            if (n-j+digits<size_type>()<=i-n) return j;\n          } else {\n            j-=sj;\n            if (j>=datasize) j=~size_type(0);\n            if ((i&j)==~size_type(0)) return ~size_type(0);\n          }\n          if ((si==0)&&(sj==0)){\n            if (i-n<=n-j) return i;\n            else          return j;\n          }\n        }\n        return ~size_type(0);\n      }\n      size_type const inline reserve_node(\n          const  key_type& key,\n          const size_type& mok,\n          const hash_type& ok\n          ){\n#ifdef PATCHMAP_STAT\n        shift_count = 0;\n#endif\n        assert(mok<datasize);\n        assert(map(order(key))==mok);\n        if (!is_set(mok)) {\n          set(mok);\n          ++num_data;\n          return mok;\n        }\n        const size_type j = search_free_bidir_v0(mok);\n        assert(j<datasize);\n        assert(!is_set(j));\n        set(j);\n        //data[i].first = key;\n        ++num_data;\n        size_type i = j;\n        while(true){\n          if (i==0) break;\n          if (!is_set(i-1)) break;\n          if (is_less(data[i-1].first,key,order(data[i-1].first),ok)) break; \n          swap(data[i],data[i-1]);\n          --i;\n        }\n#ifdef PATCHMAP_STAT\n        shift_count = j-i;\n#endif\n        if (i!=j) return i;\n        while(true){\n          if (i+1>=datasize) break;\n          if (!is_set(i+1)) break;\n          if (is_less(key,data[i+1].first,ok,order(data[i+1].first))) break; \n          swap(data[i],data[i+1]);\n          ++i;\n        }\n#ifdef PATCHMAP_STAT\n        shift_count = i-j;\n#endif\n        return i;\n      }\n      size_type inline reserve_node(\n          const key_type& key,\n          const size_type& hint){\n        const hash_type ok = order(key);\n        return reserve_node(key,hint,ok);\n      }\n      size_type inline reserve_node(const key_type& key){\n        const hash_type ok = order(key);\n        const size_type hint = map(ok);\n        assert(hint<datasize);\n        return reserve_node(key,hint,ok);\n      }\n      size_type inline find_node_binary(\n          const key_type& key,\n          const hash_type& ok,\n          const size_type& lo, // inclusive bounds\n          const size_type& hi  // inclusive bounds\n          ) const {\n#ifdef PATCHMAP_STAT\n        ++recursion_depth;\n#endif\n        assert(lo<datasize);\n        assert(hi<datasize);\n        assert(lo<=hi);\n        const size_type  mi = (hi+lo)/2;\n        if (is_set(mi)) if (equator(data[mi].first,key)) return mi;\n        if constexpr (is_injective<hash>::value) {\n          if (index_key_is_less(mi,key)){\n            if (mi<hi) return find_node_binary(key,ok,mi+1,hi);\n            else return ~size_type(0);\n          } else {\n            if (mi>lo) return find_node_binary(key,ok,lo,mi-1);\n            else return ~size_type(0);\n          }\n        } else {\n          if (index_key_is_less(mi,key)){\n            if (mi<hi) return find_node_binary(key,ok,mi+1,hi);\n            else return ~size_type(0);\n          }\n          if (key_index_is_less(key,mi)){\n            if (mi>lo) return find_node_binary(key,ok,lo,mi-1);\n            else return ~size_type(0);\n          }\n        }\n      }\n      \n      size_type inline interpol(\n          const hash_type& ok,\n          const hash_type& olo,\n          const hash_type& ohi,\n          const size_type& lo,\n          const size_type& hi\n          ) const {\n        auto lm             = long_mul(size_type(ok-olo),hi-lo);\n        // this is theoretically better but not worth the time\n        //const hash_type tmp = get<1>(lm)+(ohi-olo)/2;\n        //if (tmp<get<1>(lm)) ++get<0>(lm);\n        //get<1>(lm)          = tmp;\n        const size_type n   = clz(get<0>(lm));\n        const size_type m   = digits<hash_type>()-n;\n        const hash_type den = (ohi-olo)>>m;\n        const hash_type nom = (get<0>(lm)<<n)+(get<1>(lm)>>m);\n        return lo+nom/den;\n      }\n\n      size_type inline find_node_linear(\n          const key_type& k,\n          const size_type& lo,\n          const size_type& hi) const {\n        size_type i = lo;\n        while(true){\n          if (is_set(i)) if (equator(data[i].first,k)) return i;\n          if (i==hi) return ~size_type(0);\n          ++i;\n        }\n      }\n      \n      size_type inline find_node_interpol(\n        const  key_type&   k,\n        const hash_type&  ok,\n        const size_type& mok,\n              size_type   lo,\n              hash_type  olo,\n              bool is_set_lo,\n              size_type   hi,\n              size_type  ohi,\n              bool is_set_hi\n          ) const {\n        assert(lo<=hi||datasize==0);\n        size_type mi;\n        while(true) {\n          if (!(lo<hi)) return ~size_type(0);\n#ifdef PATCHMAP_STAT\n          ++recursion_depth;\n#endif\n          if (hi-lo<2) {\n            if (is_set_lo&&is_set_hi) return ~size_type(0);\n            if (is_set(lo)) if (equator(k,data[lo].first)) return lo;\n            if (is_set(hi)) if (equator(k,data[hi].first)) return hi;\n            return ~size_type(0);\n          }\n          if (hi-lo<8) {\n            if (is_set_hi && is_set_lo) {\n              mi = lo + ((hi-lo)>>1);\n            } else if (is_set_lo) {\n              mi = lo + ((hi-lo+2)>>2);\n            } else if (is_set_hi) {\n              mi = hi - ((hi-lo+2)>>2);\n            } else {\n              return ~size_type(0);\n            }\n          } else {\n            if (is_set_hi && is_set_lo) {\n              mi = interpol(ok,olo,ohi,lo,hi);\n            } else if (is_set_lo) {\n              const size_type st = map_diff(ok,olo);\n              mi = lo+st<hi?lo+st:hi;\n            } else if (is_set_hi) {\n              const size_type st = map_diff(ohi,ok);\n              mi = lo+st<hi?hi-st:lo;\n            } else {\n              return ~size_type(0);\n            }\n            mi = clip(mi,lo+1,hi-1);\n          }\n          if (!is_set(mi)) {\n            if (mi<mok) {\n              lo = mi;\n              is_set_lo=false;\n              continue;\n            }\n            if (mi>mok) {\n              hi = mi;\n              is_set_hi=false;\n              continue;\n            }\n            return ~size_type(0);\n          }\n          if (equator(k,data[mi].first)) return mi;\n          const hash_type omi = order(data[mi].first);\n          if (ok<omi) {\n            hi = mi;\n            ohi = omi;\n            is_set_hi = true;\n            continue;\n          }\n          if (ok>omi) {\n            lo = mi;\n            olo = omi;\n            is_set_lo = true;\n            continue;\n          }\n          if constexpr (is_injective<hash>::value) {\n            return ~size_type(0);\n          } else {\n            if (k<data[mi].first) {\n              hi = mi;\n              ohi = omi;\n              is_set_hi = true;\n              continue;\n            }\n            if (k>data[mi].first) {\n              lo = mi;\n              olo = omi;\n              is_set_lo = true;\n              continue;\n            }\n          }\n          return ~size_type(0);\n        }\n        return ~size_t(0);\n      }\n\n      size_type inline find_node(\n          const key_type &  k,\n          const hash_type& ok,\n          const size_type& mok)\n        const {\n#ifdef PATCHMAP_STAT\n        recursion_depth=0;\n#endif\n        assert((mok<datasize)||(datasize==0));\n        if (datasize==0) return ~size_type(0);\n        if (!is_set(mok)) return ~size_type(0);\n        if (equator(data[mok].first,k)) return mok;\n        const hash_type omi = order(data[mok].first);\n        if (omi<ok) {\n          return find_node_interpol(k,ok,mok,\n              mok       ,omi          ,true ,\n              datasize-1,~size_type(0),false);\n        } else {\n          return find_node_interpol(k,ok,mok,\n              0         ,0            ,false,\n              mok       ,          omi,true );\n        }\n      }\n      \n      size_type const inline find_node(\n          const  key_type&  k,\n          const size_type& ok\n          ) const { return find_node(k,ok,map(ok)); }\n      \n      size_type const inline find_node(const key_type& k)\n      const { return find_node(k,order(k)); }\n\n      size_type const inline find_node_bruteforce(const key_type& k) const {\n        for (size_type i = 0; i!=datasize; ++i)\n          if (is_set(i)) if (equator(data[i].first,k)) return i;\n        return ~size_type(0);\n      }\n\n      void inline const restore_order() { // insertion sort\n        for (size_type i=0;i!=datasize;++i){\n          for(size_type j=i;j!=0;--j){\n            if (index_index_is_less(j-1,j)) break;\n            swap_set(j,j-1);\n            swap(data[j],data[j-1]);\n          }\n        }\n      }\n      template<typename map_type>\n      typename conditional<is_const<map_type>::value,\n        const _mapped_type&,\n              _mapped_type&>::type\n      static inline const_noconst_at(map_type& hashmap,const key_type& k) {\n        size_type i = hashmap.find_node(k);\n        if (i<hashmap.datasize){\n          assert(hashmap.is_set(i));\n          if constexpr (is_same<mapped_type,void>::value)\n            return hashmap.data[i].first;\n          else return\n            hashmap.data[i].second;\n        } else throw std::out_of_range(\n            std::string(typeid(hashmap).name())\n            +\".const_noconst_at(\"+typeid(k).name()+\" k)\"\n            +\"key not found, array index \"\n            +to_string(i)+\" out of bounds\"\n           );\n      }\n    public:\n      void print() const {\n        cerr << datasize << \" \" << num_data << endl;\n        for (size_type i=0;i!=datasize;++i) {\n          cout << std::fixed << std::setprecision(16);\n          const size_type  ok = order(data[i].first);\n          const size_type mok = map(ok);\n          if (is_set(i)) cout << setw(6) << i;\n          else           cout << \"      \"    ;\n                         cout << setw(20) << frac(uint32_t(ok))\n                              << setw(20) << frac(uint32_t(data[i].second));\n          if (is_set(i)) cout << setw( 8) << mok\n                              << setw( 8) << int(mok)-int(i);\n          else           cout << setw( 8) << i\n                              << setw( 8) << 0;\n          cout << endl;\n        }\n        cout << endl;\n      }\n      size_type erase(\n          const  key_type&  k,\n          const hash_type& ok,\n          const size_type& hint){\n        size_type i = find_node(k,ok,hint);\n        if (i>=datasize) return 0;\n        //cout << \"erasing \" << wmath::frac(ok) << endl;\n        //cout << \"found at \" << i << endl;\n        const size_type j = i;\n        while(true){\n          if (i+1==datasize) break;\n          if (!is_set(i+1)) break;\n          if (map(order(data[i+1].first))>i) break;\n          swap(data[i],data[i+1]);\n          ++i;\n        }\n        if (i==j){\n          while(true){\n            if (i==0) break;\n            if (!is_set(i-1)) break;\n            if (map(order(data[i-1].first))<i) break;\n            swap(data[i],data[i-1]);\n            --i;\n          }\n        }\n        unset(i);\n        //cout << \"unset position \" << i << endl;\n        //cout << k << \" \" << data[i].first << endl;\n        --num_data;\n        //check_ordering();\n        //cout << num_data << endl;\n        assert(num_data<datasize);\n        return 1;\n      }\n      size_type erase(\n          const  key_type&  k,\n          const size_type& ok\n          ){\n        const hash_type hint = map(ok);\n        return erase(k,ok,hint);\n      }\n      size_type erase(const key_type& k){\n        const size_type ok = order(k);\n        return erase(k,ok);\n      }\n      void inline clear(){\n        for (size_type i=0;i!=masksize;++i) mask[i]=0;\n        num_data=0;\n      }\n      void const resize(const size_type& n){\n        //cout << \"resizing patchmap \" << num_data << endl;\n        if (n <num_data) return resize(num_data);\n        if (n==datasize) return;\n        const size_type new_datasize = n;\n        const size_type new_masksize =\n          (new_datasize+digits<size_type>()-1)/digits<size_type>();\n        if (n>datasize) {\n          data.resize(new_datasize);\n          mask.resize(new_masksize);\n          const size_type old_masksize = masksize;\n          masksize = new_masksize;\n          const size_type old_datasize = datasize;\n          datasize = new_datasize;\n          for (size_type i=old_masksize;i!=new_masksize;++i) mask[i]=0;\n          num_data = 0;\n          for (size_type n=old_datasize;n!=~size_type(0);--n) {\n            const size_type i = n/digits<size_type>();\n            const size_type j = n%digits<size_type>();\n            if (mask[i]&(size_type(1)<<(digits<size_type>()-j-1))) {\n              const value_type tmp = move(data[n]);\n              unset(n);\n              const size_type l = reserve_node(tmp.first);\n              data[l] = move(tmp);\n              set(l);\n            }\n          }\n        } else {\n          const size_type old_datasize = datasize;\n          datasize = new_datasize;\n          masksize = new_masksize;\n          num_data = 0;\n          for (size_type n=0;n!=old_datasize;++n) {\n            const size_type i = n/digits<size_type>();\n            const size_type j = n%digits<size_type>();\n            if (mask[i]&(size_type(1)<<(digits<size_type>()-j-1))) {\n              const value_type tmp = move(data[n]);\n              unset(n);\n              const size_type l = reserve_node(tmp.first);\n              data[l] = move(tmp);\n              set(l);\n            }\n          }\n          data.resize(datasize);\n          mask.resize(masksize);\n        }\n      }\n      size_type inline size() const { return num_data; }\n      size_type const test_size() const {\n        size_type test = 0;\n        for (size_type i=0;i!=datasize;++i) test += is_set(i);\n        return test;\n      }\n      void test_chunks() const {\n        for (size_type i=0;i!=masksize;++i){\n          cout << popcount(mask[i]) << endl;\n        }\n      }\n      bool check_ordering() const {\n        bool ordered = true;\n        for (size_type i=0,j=1;j<datasize;(++i,++j)){\n          if (!index_index_is_less(j,i)) continue;\n          cout << std::fixed << std::setprecision(16)\n               << is_set(i) << \" \" << is_set(j) << \" \"\n               << i << \" \" << j << \" \"\n               << data[i].first << \" \" << data[j].first << \" \"\n               << order(data[i].first) << \" \" << order(data[j].first) << endl;\n          //cout << index(i) << \" \" << index(j) << endl;\n          /*cout << double(index(i))\n            /pow(2.0,double(CHAR_BIT*sizeof(hash_type))) << \" \"\n               << double(index(j))\n            /pow(2.0,double(CHAR_BIT*sizeof(hash_type))) << endl;*/\n          ordered = false;\n        }\n        return ordered;\n      }\n      bool check_ordering(const size_type& i) const {\n        if (  i>0       ) if (!index_index_is_less(i-1,i)) return false;\n        if (i+1<datasize) if (!index_index_is_less(i,i+1)) return false;\n        return true;\n      }\n      void inline ensure_size(){\n        if constexpr (!dynamic) return;\n        if (num_data*32<datasize*31) return;\n        //const size_type l2 = log2(datasize+1);\n        //if ( (128*31+l2*l2*32)*num_data < (128+l2*l2)*31*datasize ) return;\n        //if ( (128*15+l2*l2*16)*num_data < (128+l2*l2)*15*datasize ) return;\n        //if ( (128*7+l2*l2*8)*num_data < (128+l2*l2)*7*datasize ) return;\n        size_type nextsize;\n        if (datasize == 0) {\n          nextsize = digits<size_type>();\n        } else {\n          //nextsize = 50*datasize/31;\n          //nextsize = 48*datasize/31;\n          //nextsize = 47*datasize/31;\n          //nextsize = 47*datasize/37;\n          //nextsize = 53*datasize/41;\n          //nextsize = (113*datasize+44)/89;\n          nextsize = (107*datasize+89)/89;\n          nextsize = (nextsize+digits<size_type>()-1)/digits<size_type>();\n          nextsize = mask.next_size(nextsize);\n          nextsize*= digits<size_type>();\n        }\n        resize(nextsize);\n      }\n      _mapped_type& operator[](const key_type& k){\n        const size_type i = find_node(k);\n        if (i<datasize) {\n          if constexpr (is_same<mapped_type,void>::value) return data[i].first;\n          else return data[i].second;\n        }\n        //assert(find_node_bruteforce(k)==~size_type(0));\n        ensure_size();\n        //assert(check_ordering());\n        const size_type j = reserve_node(k);\n        if constexpr (is_same<void,mapped_type>::value) {\n          allocator_traits<alloc>::construct(\n              allocator,&data[j],k,wmath::empty());\n        } else {\n          allocator_traits<alloc>::construct(\n              allocator,&data[j],k,mapped_type());\n        }\n        //assert(check_ordering());\n        //assert(find_node_bruteforce(k)==j);\n        //assert(find_node(k)==j);\n        assert(check_ordering(j));\n        if constexpr (is_same<mapped_type,void>::value) return data[i].first;\n        else return data[j].second;\n      }\n      const _mapped_type& operator[](const key_type& k) const {\n        const size_type i = find_node(k);\n        assert(i<datasize);\n        if constexpr (is_same<void,mapped_type>::value) return data[i].first;\n        return data[i].second; // this is only valid if key exists!\n      }\n      _mapped_type& at(const key_type& k){\n        return const_noconst_at(*this,k);\n      }\n      const _mapped_type& at(const key_type& k) const {\n        return const_noconst_at(*this,k);\n      }\n      size_type const inline count(const key_type& k) const {\n        //assert(check_ordering());\n        //assert(find_node(k)==find_node_bruteforce(k));\n        return (find_node(k)<datasize);\n      }\n      double average_offset(){\n        double v = 0;\n        for (size_type i=0;i!=datasize;++i){\n          if (is_set(i)){\n            v+=double(map(data[i].first))-double(i);\n            cout << map(order(data[i].first)) << \" \" << i << \" \"\n                 << datasize << endl;\n          }\n        }\n        return v/size()/datasize;\n      }\n      void print_offsets(){\n        for (size_type i=0;i!=datasize;++i){\n          if (is_set(i)) cout << map(order(data[i].first)) << \" \" << i << endl;\n          //else           cout << i                         << \" \" << i << endl;\n        }\n      }\n      void print_offsethist(){\n        sparse_patchmap<int,size_t> hist;\n        for (size_type i=0;i!=datasize;++i)\n          ++hist[int(map(order(data[i].first)))-int(i)];\n        for (auto it=hist.begin();it!=hist.end();++it)\n          cout << it->first << \" \" << it->second << endl;\n      }\n      equal key_eq() const{ // get key equivalence predicate\n        return equal{};\n      }\n      comp key_comp() const{ // get key order predicate\n        return comp{};\n      }\n      alloc get_allocator() const{\n        return allocator;\n      }\n      hash hash_function() const{ // get hash function\n        return hash{};\n      }  \n      template<bool is_const>\n      class const_noconst_iterator {\n        friend class sparse_patchmap;\n        public:\n          size_type hint;\n          key_type key;\n          typename conditional<is_const,\n                               const sparse_patchmap*,\n                               sparse_patchmap*\n                              >::type map;\n        private:\n          void inline update_hint(){\n            if constexpr (!uphold_iterator_validity::value) return;\n            if (hint<map->datasize)\n              if (equal{}(map->data[hint].first,key)) return;\n            hint = map->find_node(key,hint);\n            if (hint>=map->datasize) hint = ~size_type(0);\n          }\n          void inline unsafe_increment(){ // assuming hint is valid\n            //cout << \"unsafe_increment() \" << hint << \" \" << key << endl;\n            if (++hint>=map->datasize){\n              //cout << \"test1\" << endl;\n              //cout << \"becoming an end()\" << endl;\n              hint=~size_type(0);\n              return;\n            }\n            while(true){\n              //cout << \"test2\" << endl;\n              const size_type k = hint/digits<size_type>();\n              const size_type l = hint%digits<size_type>();\n              const size_type m = (~size_type(0))>>l; \n              assert(k<map->masksize);\n              size_type p = (map->mask[k]&m)<<l;\n              if (k+1<map->masksize)\n                p|=shr(map->mask[k+1]&(~m),digits<size_type>()-l);\n              const size_type s = clz(p);\n              if (s==0) break;\n              hint+=s;\n              //cout << hint << \" \" << s << endl;\n              if (hint>=map->datasize){\n                //cout << \"test3\" << endl;\n                //cout << \"becoming an end()\" << endl;\n                hint=~size_type(0);\n                return;\n              }\n            }\n            //cout << \"test4\" << endl;\n            //cout << \"new hint=\" << hint << endl;\n            key = map->data[hint].first;\n            //cout << \"new key=\" << key << endl;\n          }\n          void inline unsafe_decrement(){ // assuming hint is valid\n            if (--hint>=map->datasize){\n              hint=~size_type(0);\n              return;\n            }\n            while(true){\n              const size_type k = hint/digits<size_type>();\n              const size_type l = hint%digits<size_type>();\n              const size_type m = (~size_type(0))<<(digits<size_type>()-l-1);\n              assert(k<map->masksize);\n              size_type p = (map->mask[k]&m)>>(digits<size_type>()-l-1);\n              if (k!=0) p|=shl(map->mask[k-1]&(~m),l+1);\n              const size_type s = ctz(p);\n              if (s==0) break;\n              hint-=s;\n              if (hint>=map->datasize){\n                hint=~size_type(0);\n                return;\n              }\n            }\n            key = map->data[hint].first;\n          }\n          template<bool is_const0,bool is_const1>\n            difference_type inline friend diff(\n                const_noconst_iterator<is_const0>& it0,\n                const_noconst_iterator<is_const1>& it1){\n              if (it1<it0) return -diff(it0,it1);\n              it0.update_hint();\n              it1.update_hint();\n              const size_type k0 = it0->hint/digits<size_type>();\n              const size_type l0 = it0->hint%digits<size_type>();\n              const size_type m0 = (~size_type(0))>>l0;\n              const size_type k1 = it1->hint/digits<size_type>();\n              const size_type l1 = it1->hint%digits<size_type>();\n              const size_type m1 = (~size_type(0))<<(digits<size_type>()-l1-1);\n              if (k0==k1) return popcount(m0&m1&it0.map->mask[k0])-1;\n            size_type d = popcount(m0&it0.map->mask[k0])\n                         +popcount(m1&it1.map->mask[k1]);\n            for (size_type i = k0+1;i!=k1;++i)\n              d+=popcount(it0.map->mask[i]);\n            return d;\n          }\n          void inline add(const size_type& n){\n            update_hint();\n                  size_type k = hint/digits<size_type>();\n            const size_type l = hint%digits<size_type>();\n            const size_type m = (~size_type(0))>>l;\n                  size_type i = 0;\n                  size_type p = popcount(map->mask[k]&m)-1; \n            while (i+p<n){\n              if (++k>=map->mapsize){\n                hint=~size_type(0);\n                return;\n              }\n              hint+=digits<size_type>();\n              p = popcount(map->mask[k]);\n            }\n            for (;i!=n;++i) unsafe_increment();\n            key = map->data[hint].first;\n          }\n          void inline sub(const size_type& n){\n            update_hint();\n                  size_type k = hint/digits<size_type>();\n            const size_type l = hint%digits<size_type>();\n            const size_type m = (~size_type(0))<<(digits<size_type>()-l-1);\n                  size_type i = 0;\n                  size_type p = popcount(map->mask[k]&m)-1;\n            while (i+p<n){\n              if (--k>=map->mapsize){\n                hint=~size_type(0);\n                return;\n              }\n              hint+=digits<size_type>();\n              p = popcount(map->mask[k]);\n            }\n            for (;i!=n;++i) unsafe_decrement();\n            key = map->data[hint].first;\n          }\n        public:\n          typedef typename alloc::difference_type difference_type;\n          typedef typename alloc::value_type value_type;\n          typedef typename\n            conditional<is_const,\n                        const typename alloc::reference,\n                              typename alloc::reference\n                       >::type\n            reference;\n          typedef typename\n            conditional<is_const,\n                        const typename alloc::pointer,\n                              typename alloc::pointer\n                       >::type\n            pointer;\n          typedef std::bidirectional_iterator_tag iterator_category;\n          const_noconst_iterator(){\n            //cout << \"constructor 0\" << endl;\n          }\n          const_noconst_iterator(\n            const size_t& hint,\n            typename conditional<is_const,\n                                 const sparse_patchmap*,\n                                       sparse_patchmap*\n                                >::type map)\n            :hint(hint),key(key_type{}),map(map){\n            //cout << \"constructor 1 \" << hint << endl;\n          }\n          const_noconst_iterator(\n            const size_t& hint,\n            const key_type& key,\n            typename conditional<is_const,\n                                 const sparse_patchmap*,\n                                       sparse_patchmap*\n                                >::type map)\n            :hint(hint),key(key),map(map) {\n              //cout << \"constructor 2 \" << hint << endl;\n          }\n          ~const_noconst_iterator(){\n          //cout << \"destructor of const_noconst_iterator \" << is_const << endl;\n          //cout << hint << endl;\n          }\n          // copy constructor\n          template<bool is_const_other>\n          const_noconst_iterator(const const_noconst_iterator<is_const_other>& o)\n          :hint(o.hint),key(o.key),map(o.map){\n            //cout << \"copy constructor\" << endl;\n          }\n          // move constructor\n          template<bool is_const_other>\n          const_noconst_iterator(\n              const_noconst_iterator<is_const_other>&& o) noexcept{\n            //cout << \"move constructor\" << endl;\n            swap(hint,o.hint);\n            swap(key,o.key);\n            swap(map,o.map);\n          }\n          // copy assignment\n          template<bool is_const_other>\n          const_noconst_iterator<is_const>& operator=(\n              const const_noconst_iterator<is_const_other>& other){\n            //cout << \"copy assignment\" << endl;\n            return  (*this=const_noconst_iterator<is_const>(other));\n          }\n          template<bool is_const_other>\n          bool operator==(\n              const const_noconst_iterator<is_const_other>& o) const {\n            //cout << \"comparing \" << hint << \" \" << key << \" with \"\n            //     << o.hint << \" \" << key << endl;\n            if ((hint>=map->datasize)&&(o.hint>=o.map->datasize)) return true;\n            if ((hint>=map->datasize)||(o.hint>=o.map->datasize)) return false;\n            if (key!=o.key) return false;\n            return true;\n          }\n          template<bool is_const_other>\n          bool operator!=(\n              const const_noconst_iterator<is_const_other>& o) const{\n            return !((*this)==o);\n          }\n          template<bool is_const_other>\n          bool operator< (\n              const const_noconst_iterator<is_const_other>& o) const{\n            if ((o.hint<o.mpa->datasize)){\n              if (hint<map->datasize){\n                return comp(key,o.key);\n              }else{\n                return false;\n              }\n            } else {\n              return false;\n            }\n          }\n          template<bool is_const_other>\n          bool operator> (\n              const const_noconst_iterator<is_const_other>& o) const{\n            if ((o.hint<o.mpa->datasize)){\n              if (hint<map->datasize){\n                return (!comp(key,o.key))&&(!equal(key,o.key));\n              }else{\n                return true;\n              }\n            } else {\n              return false;\n            }\n          }\n          template<bool is_const_other>\n          bool operator<=(\n              const const_noconst_iterator<is_const_other>& o) const{\n            if ((o.hint<o.mpa->datasize)){\n              if (hint<map->datasize){\n                return comp(key,o.key)||equal(key,o.key);\n              }else{\n                return false;\n              }\n            } else {\n              return true;\n            }\n          }\n          template<bool is_const_other>\n          bool operator>=(\n              const const_noconst_iterator<is_const_other>& o) const{\n            if ((o.hint<o.mpa->datasize)){\n              if (hint<map->datasize){\n               return !comp(key,o.key);\n              }else{\n                return true;\n              }\n            } else {\n              return true;\n            }\n          }\n          const_noconst_iterator<is_const>& operator++(){   // prefix\n            //cout << \"operator++()\" << endl;\n            update_hint();\n            unsafe_increment();\n            return *this;\n          }\n          const_noconst_iterator<is_const> operator++(int){ // postfix\n            update_hint();\n            iterator pre(*this);\n            unsafe_increment();\n            return pre;\n          }\n          const_noconst_iterator<is_const>& operator--(){   // prefix\n            update_hint();\n            unsafe_decrement();\n            return *this;\n          }\n          const_noconst_iterator<is_const> operator--(int){ // postfix\n            update_hint();\n            iterator pre(*this);\n            unsafe_decrement();\n            return pre;\n          }\n          // not a random_acces_iterator but we can still do better than default\n          template<bool is_const_other>\n          difference_type operator-(\n              const const_noconst_iterator<is_const_other>& o) const {\n            iterator it0(*this);\n            iterator it1(o);\n            return diff(it0,it1);\n          }\n          const_noconst_iterator<is_const>& operator+=(const size_type& n){\n            add(n);\n            return *this;\n          }\n          const_noconst_iterator<is_const> operator+(const size_type& n) const {\n            return (const_noconst_iterator<is_const>(*this)+=n);\n          }\n          friend const_noconst_iterator<is_const> operator+(\n              const size_type& n,\n              const const_noconst_iterator<is_const>& it){\n            return (const_noconst_iterator<is_const>(it)+=n);\n          }\n          const_noconst_iterator<is_const>& operator-=(const size_type& n){\n            sub(n);\n            return *this;\n          }\n          const_noconst_iterator<is_const> operator-(const size_type& n) const{\n            return (const_noconst_iterator<is_const>(*this)-=n);\n          }\n          reference operator*() {\n            update_hint();\n            return map->data[hint];\n          }\n          pointer operator->() {\n            update_hint();\n            return &(map->data[hint]);\n          }\n          reference operator*() const {\n            size_type i;\n            if (hint>=map->datasize){\n              i = map->find_node(key);\n            } else if (map->data[hint]!=key){\n              i = map->find_node(key,hint);\n            } else {\n              i = hint;\n            }\n            return map->data[i];\n          }\n          pointer operator->() const {\n            size_type i;\n            if (hint>=map->datasize){\n              i = map->find_node(key);\n            } else if (map->data[hint]!=key){\n              i = map->find_node(key,hint);\n            } else {\n              i = hint;\n            }\n            return &(map->data[i]);\n          }\n    };\n    typedef const_noconst_iterator<false> iterator;\n    typedef const_noconst_iterator<true>  const_iterator;    \n    iterator begin(){\n      //cout << \"begin()\" << endl;\n      const size_type i = find_first();\n      //cout << \"this should call constructor 2\" << endl;\n      return iterator(i,data[i].first,this);\n    }\n    const_iterator begin() const {\n      //cout << \"begin()\" << endl;\n      const size_type i = find_first();\n      //cout << \"this should call constructor 2\" << endl;\n      return const_iterator(i,data[i].first,this);\n    }\n    const_iterator cbegin() const {\n      //cout << \"cbegin()\" << endl;\n      const size_type i = find_first();\n      //cout << \"this should call constructor 2\" << endl;\n      return const_iterator(i,data[i].first,this);\n    }\n    iterator end() {\n      //cout << \"end()\" << endl;\n      const size_type i = find_first();\n      //cout << \"this should call constructor 1\" << endl;\n      return iterator(~size_type(0),this);\n    }\n    const_iterator end() const {\n      //cout << \"end()\" << endl;\n      //cout << \"this should call constructor 2\" << endl;\n      return const_iterator(~size_type(0),this);\n    }\n    const_iterator cend() const {\n      //cout << \"cend()\" << endl;\n      //cout << \"this should call constructor 2\" << endl;\n      return const_iterator(~size_type(0),this);\n    }\n    size_type max_size()         const{return numeric_limits<size_type>::max();}\n    bool empty()                 const{return (num_data==0);}\n    size_type bucket_count()     const{return datasize;}\n    size_type max_bucket_count() const{return numeric_limits<size_type>::max();}\n    void rehash(const size_type& n) { if (n>=size()) resize(n); }\n    void reserve(const size_type& n){ if (3*n>=2*(size()+1)) resize(n*3/2); }\n    pair<iterator,bool> insert ( const value_type& val ){\n      const size_type i = find_node(key_of(val));\n      if (i<datasize) return {iterator(i,key_of(val),this),false};\n      ensure_size();\n      const size_type j = reserve_node(key_of(val));\n      allocator_traits<alloc>::construct(allocator,data+j,val);\n      return {{j,key_of(val),this},true};\n    }\n    template <class P>\n    pair<iterator,bool> insert ( P&& val ){\n      const size_type i = find_node(key_of(val));\n      if (i<datasize) return {iterator(i,key_of(val),this),false};\n      ensure_size();\n      const size_type j = reserve_node(key_of(val));\n      if constexpr (is_same<void,mapped_type>::value)\n        allocator_traits<alloc>::construct(allocator,data+j,\n            std::pair(val,wmath::empty{}));\n      else\n        allocator_traits<alloc>::construct(allocator,data+j,val);\n      return {{j,key_of(val),this},true};\n    }\n    iterator insert ( const_iterator hint, const value_type& val ){\n      const size_type i = find_node(key_of(val),hint.hint);\n      if (i<datasize) return {iterator(i,key_of(val),this),false};\n      ensure_size();\n      const size_type j = reserve_node(key_of(val));\n      if constexpr (is_same<void,mapped_type>::value)\n        allocator_traits<alloc>::construct(allocator,data+j,{val,{}});\n      else\n        allocator_traits<alloc>::construct(allocator,data+j,val);\n      return {{j,key_of(val),this},true};\n    }\n    template <class P>\n    iterator insert ( const_iterator hint, P&& val ){\n      const size_type i = find_node(key_of(val),hint.hint);\n      if (i<datasize) return {iterator(i,key_of(val),this),false};\n      ensure_size();\n      const size_type j = reserve_node(key_of(val),hint.hint);\n      if constexpr (is_same<void,mapped_type>::value)\n        allocator_traits<alloc>::construct(allocator,data+j,{val,{}});\n      else\n        allocator_traits<alloc>::construct(allocator,data+j,val);\n      return {{j,key_of(val),this},true};\n    }\n    template <class InputIterator>\n    void insert ( InputIterator first, InputIterator last ){\n      for (auto it(first);it!=last;++it){\n        insert(*it);\n      }\n    }\n    void insert ( initializer_list<value_type> il ){\n      insert(il.begin(),il.end());\n    }\n    template <class... Args>\n    pair<iterator, bool> emplace ( Args&&... args ){\n      insert(value_type(args...));\n    }\n    template <class... Args>\n    iterator emplace_hint(const_iterator position,Args&&... args){\n      insert(position,value_type(args...));\n    }\n    pair<iterator,iterator> equal_range(const key_type& k){\n      const size_type i = find_node(k);\n      if (i>=datasize) return {end(),end()};\n      iterator lo(i,data[i].first,this);\n      iterator hi(lo);\n      ++hi;\n      return {lo,hi};\n    }\n    pair<const_iterator,const_iterator>\n    equal_range ( const key_type& k ) const{\n      const size_type i = find_node(k);\n      if (i>=datasize) return {cend(),cend()};\n      iterator lo(i,data[i].first,this);\n      iterator hi(lo);\n      ++hi;\n      return {lo,hi};\n    }\n    float load_factor() const noexcept{\n      return float(num_data)/float(datasize);\n    }\n    float average_patchsize() const noexcept{\n      double avg = 0;\n      double counter = 0;\n      for (size_type i=0;i<datasize;++i){\n        const size_type j = search_free_inc(i);\n        if (j<datasize) avg += (j-i);\n        else break;\n        i=j;\n        ++counter;\n      }\n      return avg/counter;\n    }\n    void print_patchsizes() const noexcept{\n      for (size_type i=0;i<datasize;++i){\n        const size_type j = search_free_inc(i);\n        if (j<datasize) cout << j-i << endl;\n        else break;\n        i=j;\n      }\n    }\n    float max_load_factor() const noexcept{\n      return 1;\n    }\n    template<bool is_const>\n    iterator erase(const_noconst_iterator<is_const> position){\n      iterator it(position);\n      ++it;\n      erase(position.key);//,position.hint);\n      return it;\n    }\n    template<bool is_const>\n    iterator erase(\n        const_noconst_iterator<is_const> first,\n        const_noconst_iterator<is_const> last){\n      for (auto it=first;it!=last;it=erase(it));\n    }\n  }; \n}\n\n\n\n#endif // SPARSE_PATCHMAP_H\n", "meta": {"hexsha": "b36cad5c5bf6be0fdd741015e31f36a1d55e90f1", "size": 50172, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/common/wflign/deps/patchmap/sparse_patchmap.hpp", "max_stars_repo_name": "AndreaGuarracino/edyeet", "max_stars_repo_head_hexsha": "776a0c82e7ebf9ea7def055d12e19d6bb0aa5383", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 92.0, "max_stars_repo_stars_event_min_datetime": "2019-09-11T05:17:20.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T09:54:06.000Z", "max_issues_repo_path": "deps/patchmap/sparse_patchmap.hpp", "max_issues_repo_name": "AndreaGuarracino/wflign", "max_issues_repo_head_hexsha": "8d991cbb6ba6821e1765cce92338dbacafbe278e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 9.0, "max_issues_repo_issues_event_min_datetime": "2020-09-01T02:33:34.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-13T20:01:26.000Z", "max_forks_repo_path": "deps/patchmap/sparse_patchmap.hpp", "max_forks_repo_name": "AndreaGuarracino/wflign", "max_forks_repo_head_hexsha": "8d991cbb6ba6821e1765cce92338dbacafbe278e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2020-08-18T14:24:55.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-08T13:33:12.000Z", "avg_line_length": 35.5577604536, "max_line_length": 81, "alphanum_fraction": 0.5106234553, "num_tokens": 12240, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6992544210587586, "lm_q2_score": 0.5, "lm_q1q2_score": 0.3496272105293793}}
{"text": "// Copyright 2006. Peter Gottschling, Matthias Troyer, Rolf Bonderer\n// Software License for MTL\n// \n// Copyright (c) 2007 The Trustees of Indiana University.\n//               2008 Dresden University of Technology and the Trustees of Indiana University.\n//               2010 SimuNova UG (haftungsbeschränkt), www.simunova.com.\n// All rights reserved.\n// Authors: Peter Gottschling and Andrew Lumsdaine\n// \n// This file is part of the Matrix Template Library\n// \n// See also license.mtl.txt in the distribution.\n\n#ifndef MATH_IDENTITY_INCLUDE\n#define MATH_IDENTITY_INCLUDE\n\n#include <boost/math/tools/config.hpp>\n#include <limits>\n#include <string>\n#include <functional>\n\n#include <boost/numeric/linear_algebra/operators.hpp>\n\nnamespace math {\n\ntemplate <typename Operation, typename Element>\nstruct identity_t {};\n\n// TBD: Do we the case that the return type is different? Using std::unary_function?\n\n// Additive identity of Element type is by default a converted 0\n// However, for vectors one needs to know the dimension\n// (and in parallel eventually also the distribution).\n// Therefore, an element is passed as reference.\n// It is strongly recommended to specialize this functor\n// for better efficiency.\ntemplate <typename Element>\nstruct identity_t< add<Element>, Element > \n  : public std::binary_function<add<Element>, Element, Element>\n{ \n    Element operator() (const add<Element>&, const Element& ref) const\n    {\n\tElement tmp(ref);\n\ttmp= 0;\n\treturn tmp;\n    }\n};\n\ntemplate <>\nstruct identity_t< add<std::string>, std::string > \n  : public std::binary_function<add<std::string>, std::string, std::string>\n{ \n    std::string operator() (const add<std::string>&, const std::string&) const\n    {\n\treturn std::string();\n    }\n};\n\n// Multiplicative identity of Element type is by default a converted 1\n// Same comments as above.\n// In contrast to additive identity, this default more likely to be wrong (e.g. matrices with all 1s)\ntemplate <typename Element>\nstruct identity_t< mult<Element>, Element > \n  : public std::binary_function<mult<Element>, Element, Element>\n{ \n    Element operator() (const mult<Element>&, const Element& ref) const\n    {\n\tElement tmp(ref);\n\ttmp= 1;\n\treturn tmp;\n    }\n};\n\n\n// Identity of max is minimal representable value, for standard types defined in numeric_limits\ntemplate <typename Element>\nstruct identity_t< max<Element>, Element > \n  : public std::binary_function<max<Element>, Element, Element>\n{ \n    Element operator() (const max<Element>&, const Element& ) const\n    {\n\tusing std::numeric_limits;\n\treturn numeric_limits<Element>::min();\n    }\n};\n\ntemplate <>\nstruct identity_t< max<float>, float > \n  : public std::binary_function<max<float>, float, float>\n{ \n    float operator() (const max<float>&, const float& ) const\n    {\n\tusing std::numeric_limits;\n\treturn -numeric_limits<float>::max();\n    }\n};\n\ntemplate <>\nstruct identity_t< max<double>, double > \n  : public std::binary_function<max<double>, double, double>\n{ \n    double operator() (const max<double>&, const double& ) const\n    {\n\tusing std::numeric_limits;\n\treturn -numeric_limits<double>::max();\n    }\n};\n\n\n#ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS\n   \ntemplate <>\nstruct identity_t< max<long double>, long double > \n  : public std::binary_function<max<long double>, long double, long double>\n{ \n    long double operator() (const max<long double>&, const long double& ) const\n    {\n\tusing std::numeric_limits;\n\treturn -numeric_limits<long double>::max();\n    }\n};\n\n#endif\n\n\n\n// Identity of min is maximal representable value, for standard types defined in numeric_limits\ntemplate <typename Element>\nstruct identity_t< min<Element>, Element > \n  : public std::binary_function<min<Element>, Element, Element>\n{ \n    Element operator() (const min<Element>&, const Element& ) const\n    {\n\tusing std::numeric_limits;\n\treturn numeric_limits<Element>::max();\n    }\n};\n\n// Identity of bit-wise and\ntemplate <typename Element>\nstruct identity_t< bitwise_and<Element>, Element > \n  : public std::binary_function<bitwise_and<Element>, Element, Element>\n{ \n    Element operator() (const bitwise_and<Element>&, const Element&) const\n    {\n\treturn 0;\n    }\n};\n\n// Identity of bit-wise or\ntemplate <typename Element>\nstruct identity_t< bitwise_or<Element>, Element > \n  : public std::binary_function<bitwise_or<Element>, Element, Element>\n{ \n    Element operator() (const bitwise_or<Element>&, const Element&) const\n    {\n\treturn 0 - 1;\n    }\n};\n\n#if 0 // ambiguous specialization\ntemplate <template <typename> class Operation, typename First, typename Second>\nstruct identity_t< Operation<std::pair<First, Second> >, std::pair<First, Second> >\n{\n    typedef std::pair<First, Second> pt;\n\n    pt operator()(const Operation<pt>&, const pt& ref) const\n    {\n\treturn std::make_pair(identity(Operation<First>(), ref.first), identity(Operation<Second>(), ref.second));\n    }\n};\n#endif\n\n// Function is shorter than typetrait-like functor\ntemplate <typename Operation, typename Element>\ninline Element identity(const Operation& op, const Element& v)\n{\n    return identity_t<Operation, Element>() (op, v);\n}\n\n#if 1\n// I shouldn't do this (but as functor I'd need too many specializations)\ntemplate <template <typename> class Operation, typename First, typename Second>\ninline std::pair<First, Second> identity(const Operation<std::pair<First, Second> >&, const std::pair<First, Second>& v)\n{\n    return std::pair<First, Second>(::math::identity(Operation<First>(), v.first), ::math::identity(Operation<Second>(), v.second));\n}\n#endif\n\n// Short-cut for additive identity\ntemplate <typename Element>\ninline Element zero(const Element& v)\n{\n    return identity_t<::math::add<Element>, Element>() (::math::add<Element>(), v);\n}\n\n\n// Short-cut for multiplicative identity\ntemplate <typename Element>\ninline Element one(const Element& v)\n{\n    return identity_t<::math::mult<Element>, Element>() (::math::mult<Element>(), v);\n}\n\n\n} // namespace math\n\n#endif // MATH_IDENTITY_INCLUDE\n", "meta": {"hexsha": "28d3e8911cfe1e964f4097f7d9f520fddf6ed14b", "size": 5976, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "lib/mtl4/boost/numeric/linear_algebra/identity.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/linear_algebra/identity.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/linear_algebra/identity.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.5933014354, "max_line_length": 132, "alphanum_fraction": 0.7128514056, "num_tokens": 1394, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6992544210587585, "lm_q2_score": 0.5, "lm_q1q2_score": 0.34962721052937923}}
{"text": "/////////////////////////////////////////////////////////////////////////////\r\n//\r\n// (C) Copyright Ion Gaztanaga  2014-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\r\n#ifndef BOOST_INTRUSIVE_DETAIL_MATH_HPP\r\n#define BOOST_INTRUSIVE_DETAIL_MATH_HPP\r\n\r\n#ifndef BOOST_CONFIG_HPP\r\n#  include <boost/config.hpp>\r\n#endif\r\n\r\n#if defined(BOOST_HAS_PRAGMA_ONCE)\r\n#  pragma once\r\n#endif\r\n\r\n#include <cstddef>\r\n#include <climits>\r\n#include <boost/intrusive/detail/mpl.hpp>\r\n\r\nnamespace boost {\r\nnamespace intrusive {\r\nnamespace detail {\r\n\r\n///////////////////////////\r\n// floor_log2  Dispatcher\r\n////////////////////////////\r\n\r\n#if defined(_MSC_VER) && (_MSC_VER >= 1300)\r\n\r\n   }}} //namespace boost::intrusive::detail\r\n\r\n   //Use _BitScanReverseXX intrinsics\r\n\r\n   #if defined(_M_X64) || defined(_M_AMD64) || defined(_M_IA64)   //64 bit target\r\n      #define BOOST_INTRUSIVE_BSR_INTRINSIC_64_BIT\r\n   #endif\r\n\r\n   #ifndef __INTRIN_H_   // Avoid including any windows system header\r\n      #ifdef __cplusplus\r\n      extern \"C\" {\r\n      #endif // __cplusplus\r\n\r\n      #if defined(BOOST_INTRUSIVE_BSR_INTRINSIC_64_BIT)   //64 bit target\r\n         unsigned char _BitScanReverse64(unsigned long *index, unsigned __int64 mask);\r\n         #pragma intrinsic(_BitScanReverse64)\r\n      #else //32 bit target\r\n         unsigned char _BitScanReverse(unsigned long *index, unsigned long mask);\r\n         #pragma intrinsic(_BitScanReverse)\r\n      #endif\r\n\r\n      #ifdef __cplusplus\r\n      }\r\n      #endif // __cplusplus\r\n   #endif // __INTRIN_H_\r\n\r\n   #ifdef BOOST_INTRUSIVE_BSR_INTRINSIC_64_BIT\r\n      #define BOOST_INTRUSIVE_BSR_INTRINSIC _BitScanReverse64\r\n      #undef BOOST_INTRUSIVE_BSR_INTRINSIC_64_BIT\r\n   #else\r\n      #define BOOST_INTRUSIVE_BSR_INTRINSIC _BitScanReverse\r\n   #endif\r\n\r\n   namespace boost {\r\n   namespace intrusive {\r\n   namespace detail {\r\n\r\n   inline std::size_t floor_log2 (std::size_t x)\r\n   {\r\n      unsigned long log2;\r\n      BOOST_INTRUSIVE_BSR_INTRINSIC( &log2, (unsigned long)x );\r\n      return log2;\r\n   }\r\n\r\n   #undef BOOST_INTRUSIVE_BSR_INTRINSIC\r\n\r\n#elif defined(__GNUC__) && ((__GNUC__ >= 4) || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4)) //GCC >=3.4\r\n\r\n   //Compile-time error in case of missing specialization\r\n   template<class Uint>\r\n   struct builtin_clz_dispatch;\r\n\r\n   #if defined(BOOST_HAS_LONG_LONG)\r\n   template<>\r\n   struct builtin_clz_dispatch< ::boost::ulong_long_type >\r\n   {\r\n      static ::boost::ulong_long_type call(::boost::ulong_long_type n)\r\n      {  return __builtin_clzll(n); }\r\n   };\r\n   #endif\r\n\r\n   template<>\r\n   struct builtin_clz_dispatch<unsigned long>\r\n   {\r\n      static unsigned long call(unsigned long n)\r\n      {  return __builtin_clzl(n); }\r\n   };\r\n\r\n   template<>\r\n   struct builtin_clz_dispatch<unsigned int>\r\n   {\r\n      static unsigned int call(unsigned int n)\r\n      {  return __builtin_clz(n); }\r\n   };\r\n\r\n   inline std::size_t floor_log2(std::size_t n)\r\n   {\r\n      return sizeof(std::size_t)*CHAR_BIT - std::size_t(1) - builtin_clz_dispatch<std::size_t>::call(n);\r\n   }\r\n\r\n#else //Portable methods\r\n\r\n////////////////////////////\r\n// Generic method\r\n////////////////////////////\r\n\r\n   inline std::size_t floor_log2_get_shift(std::size_t n, true_ )//power of two size_t\r\n   {  return n >> 1;  }\r\n\r\n   inline std::size_t floor_log2_get_shift(std::size_t n, false_ )//non-power of two size_t\r\n   {  return (n >> 1) + ((n & 1u) & (n != 1)); }\r\n\r\n   template<std::size_t N>\r\n   inline std::size_t floor_log2 (std::size_t x, integral_constant<std::size_t, N>)\r\n   {\r\n      const std::size_t Bits = N;\r\n      const bool Size_t_Bits_Power_2= !(Bits & (Bits-1));\r\n\r\n      std::size_t n = x;\r\n      std::size_t log2 = 0;\r\n\r\n      std::size_t remaining_bits = Bits;\r\n      std::size_t shift = floor_log2_get_shift(remaining_bits, bool_<Size_t_Bits_Power_2>());\r\n      while(shift){\r\n         std::size_t tmp = n >> shift;\r\n         if (tmp){\r\n            log2 += shift, n = tmp;\r\n         }\r\n         shift = floor_log2_get_shift(shift, bool_<Size_t_Bits_Power_2>());\r\n      }\r\n\r\n      return log2;\r\n   }\r\n\r\n   ////////////////////////////\r\n   // DeBruijn method\r\n   ////////////////////////////\r\n\r\n   //Taken from:\r\n   //http://stackoverflow.com/questions/11376288/fast-computing-of-log2-for-64-bit-integers\r\n   //Thanks to Desmond Hume\r\n\r\n   inline std::size_t floor_log2 (std::size_t v, integral_constant<std::size_t, 32>)\r\n   {\r\n      static const int MultiplyDeBruijnBitPosition[32] =\r\n      {\r\n         0, 9, 1, 10, 13, 21, 2, 29, 11, 14, 16, 18, 22, 25, 3, 30,\r\n         8, 12, 20, 28, 15, 17, 24, 7, 19, 27, 23, 6, 26, 5, 4, 31\r\n      };\r\n\r\n      v |= v >> 1;\r\n      v |= v >> 2;\r\n      v |= v >> 4;\r\n      v |= v >> 8;\r\n      v |= v >> 16;\r\n\r\n      return MultiplyDeBruijnBitPosition[(std::size_t)(v * 0x07C4ACDDU) >> 27];\r\n   }\r\n\r\n   inline std::size_t floor_log2 (std::size_t v, integral_constant<std::size_t, 64>)\r\n   {\r\n      static const std::size_t MultiplyDeBruijnBitPosition[64] = {\r\n      63,  0, 58,  1, 59, 47, 53,  2,\r\n      60, 39, 48, 27, 54, 33, 42,  3,\r\n      61, 51, 37, 40, 49, 18, 28, 20,\r\n      55, 30, 34, 11, 43, 14, 22,  4,\r\n      62, 57, 46, 52, 38, 26, 32, 41,\r\n      50, 36, 17, 19, 29, 10, 13, 21,\r\n      56, 45, 25, 31, 35, 16,  9, 12,\r\n      44, 24, 15,  8, 23,  7,  6,  5};\r\n\r\n      v |= v >> 1;\r\n      v |= v >> 2;\r\n      v |= v >> 4;\r\n      v |= v >> 8;\r\n      v |= v >> 16;\r\n      v |= v >> 32;\r\n      return MultiplyDeBruijnBitPosition[((std::size_t)((v - (v >> 1))*0x07EDD5E59A4E28C2ULL)) >> 58];\r\n   }\r\n\r\n\r\n   inline std::size_t floor_log2 (std::size_t x)\r\n   {\r\n      const std::size_t Bits = sizeof(std::size_t)*CHAR_BIT;\r\n      return floor_log2(x, integral_constant<std::size_t, Bits>());\r\n   }\r\n\r\n#endif\r\n\r\n//Thanks to Laurent de Soras in\r\n//http://www.flipcode.com/archives/Fast_log_Function.shtml\r\ninline float fast_log2 (float val)\r\n{\r\n   union caster_t\r\n   {\r\n      unsigned x;\r\n      float val;\r\n   } caster;\r\n\r\n   caster.val = val;\r\n   unsigned x = caster.x;\r\n   const int log_2 = int((x >> 23) & 255) - 128;\r\n   x &= ~(unsigned(255u) << 23u);\r\n   x += unsigned(127) << 23u;\r\n   caster.x = x;\r\n   val = caster.val;\r\n   //1+log2(m), m ranging from 1 to 2\r\n   //3rd degree polynomial keeping first derivate continuity.\r\n   //For less precision the line can be commented out\r\n   val = ((-1.f/3.f) * val + 2.f) * val - (2.f/3.f);\r\n   return val + static_cast<float>(log_2);\r\n}\r\n\r\ninline bool is_pow2(std::size_t x)\r\n{  return (x & (x-1)) == 0;  }\r\n\r\ntemplate<std::size_t N>\r\nstruct static_is_pow2\r\n{\r\n   static const bool value = (N & (N-1)) == 0;\r\n};\r\n\r\ninline std::size_t ceil_log2 (std::size_t x)\r\n{\r\n   return static_cast<std::size_t>(!(is_pow2)(x)) + floor_log2(x);\r\n}\r\n\r\ninline std::size_t ceil_pow2 (std::size_t x)\r\n{\r\n   return std::size_t(1u) << (ceil_log2)(x);\r\n}\r\n\r\ninline std::size_t previous_or_equal_pow2(std::size_t x)\r\n{\r\n   return std::size_t(1u) << floor_log2(x);\r\n}\r\n\r\ntemplate<class SizeType, std::size_t N>\r\nstruct numbits_eq\r\n{\r\n   static const bool value = sizeof(SizeType)*CHAR_BIT == N;\r\n};\r\n\r\ntemplate<class SizeType, class Enabler = void >\r\nstruct sqrt2_pow_max;\r\n\r\ntemplate <class SizeType>\r\nstruct sqrt2_pow_max<SizeType, typename voider<typename enable_if< numbits_eq<SizeType, 32> >::type>::type>\r\n{\r\n   static const SizeType value = 0xb504f334;\r\n   static const std::size_t pow   = 31;\r\n};\r\n\r\n#ifndef BOOST_NO_INT64_T\r\n\r\ntemplate <class SizeType>\r\nstruct sqrt2_pow_max<SizeType, typename voider<typename enable_if< numbits_eq<SizeType, 64> >::type>::type>\r\n{\r\n   static const SizeType value = 0xb504f333f9de6484ull;\r\n   static const std::size_t pow   = 63;\r\n};\r\n\r\n#endif   //BOOST_NO_INT64_T\r\n\r\n// Returns floor(pow(sqrt(2), x * 2 + 1)).\r\n// Defined for X from 0 up to the number of bits in size_t minus 1.\r\ninline std::size_t sqrt2_pow_2xplus1 (std::size_t x)\r\n{\r\n   const std::size_t value = (std::size_t)sqrt2_pow_max<std::size_t>::value;\r\n   const std::size_t pow   = (std::size_t)sqrt2_pow_max<std::size_t>::pow;\r\n   return (value >> (pow - x)) + 1;\r\n}\r\n\r\n} //namespace detail\r\n} //namespace intrusive\r\n} //namespace boost\r\n\r\n#endif //BOOST_INTRUSIVE_DETAIL_MATH_HPP\r\n", "meta": {"hexsha": "cb019ef6ee3ff951bd73849e7170b3087a19df5e", "size": 8385, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "dep/win/include/boost/intrusive/detail/math.hpp", "max_stars_repo_name": "Netis/packet-agent", "max_stars_repo_head_hexsha": "70da3479051a07e3c235abe7516990f9fd21a18a", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 995.0, "max_stars_repo_stars_event_min_datetime": "2018-06-22T10:39:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T01:22:14.000Z", "max_issues_repo_path": "dep/win/include/boost/intrusive/detail/math.hpp", "max_issues_repo_name": "Netis/packet-agent", "max_issues_repo_head_hexsha": "70da3479051a07e3c235abe7516990f9fd21a18a", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 32.0, "max_issues_repo_issues_event_min_datetime": "2018-06-23T14:19:37.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-29T10:20:37.000Z", "max_forks_repo_path": "dep/win/include/boost/intrusive/detail/math.hpp", "max_forks_repo_name": "Netis/packet-agent", "max_forks_repo_head_hexsha": "70da3479051a07e3c235abe7516990f9fd21a18a", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 172.0, "max_forks_repo_forks_event_min_datetime": "2018-06-22T11:12:00.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-29T07:44:33.000Z", "avg_line_length": 28.3277027027, "max_line_length": 108, "alphanum_fraction": 0.5954680978, "num_tokens": 2514, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6992544210587585, "lm_q2_score": 0.5, "lm_q1q2_score": 0.34962721052937923}}
{"text": "#include <Eigen/Dense>\n#include \"disc.hpp\"\n#include \"evaluations.hpp\"\n#include \"global_residual.hpp\"\n#include \"local_residual.hpp\"\n#include \"macros.hpp\"\n#include \"nested.hpp\"\n#include \"qoi.hpp\"\n#include \"state.hpp\"\n\nnamespace calibr8 {\n\nvoid eval_forward_jacobian(RCP<State> state, RCP<Disc> disc, int step) {\n\n  // gather discretization information\n  apf::Mesh* mesh = disc->apf_mesh();\n\n  // gather information from the state object\n  RCP<LocalResidual<FADT>> local = state->d_residuals->local;\n  RCP<GlobalResidual<FADT>> global = state->d_residuals->global;\n  Array1D<RCP<VectorT>>& RHS = state->la->b[GHOST];\n  Array2D<RCP<MatrixT>>& LHS = state->la->A[GHOST];\n  Array1D<apf::Field*> x = disc->primal(step).global;\n  Array1D<apf::Field*> xi = disc->primal(step).local;\n  Array1D<apf::Field*> x_prev = disc->primal(step - 1).global;\n  Array1D<apf::Field*> xi_prev = disc->primal(step - 1).local;\n\n  // modify the fields if we are doing a verification\n  RCP<NestedDisc> nested;\n  bool const is_verification = (disc->type() == VERIFICATION);\n  if (is_verification) {\n    nested = Teuchos::rcp_static_cast<NestedDisc>(disc);\n    ALWAYS_ASSERT(nested != Teuchos::null);\n    x = nested->primal_fine(step).global;\n    xi = nested->primal_fine(step).local;\n    x_prev = nested->primal_fine(step - 1).global;\n    xi_prev = nested->primal_fine(step - 1).local;\n  }\n\n  // perform initializations of the residual objects\n  global->before_elems(disc);\n\n  // loop over all element sets in the discretization\n  for (int es = 0; es < disc->num_elem_sets(); ++es) {\n\n    local->before_elems(es, disc);\n\n    // gather the elements in the current element set\n    std::string const& es_name = disc->elem_set_name(es);\n    ElemSet const& elems = disc->elems(es_name);\n\n    // loop over all elements in the element set\n    for (size_t elem = 0; elem < elems.size(); ++elem) {\n\n      // get the current mesh element\n      apf::MeshEntity* e = elems[elem];\n      apf::MeshElement* me = apf::createMeshElement(mesh, e);\n\n      // peform operations on element input\n      global->set_elem(me);\n      local->set_elem(me);\n      global->gather(x, x_prev);\n\n      // loop over domain ip sets\n      // ip_set = 0 -> coupled\n      // ip_set > 0 -> global only\n      Array1D<int> ip_sets = global->ip_sets();\n      int const num_ip_sets = ip_sets.size();\n\n      for (int ip_set = 0; ip_set < num_ip_sets; ++ip_set) {\n\n        // get the quadrature order for the ip set\n        int const q_order = ip_sets[ip_set];\n        // loop over all integration points in the current element\n        int const npts = apf::countIntPoints(me, q_order);\n\n        for (int pt = 0; pt < npts; ++pt) {\n\n          // get integration point specific information\n          apf::Vector3 iota;\n          apf::getIntPoint(me, q_order, pt, iota);\n          double const w = apf::getIntWeight(me, q_order, pt);\n          double const dv = apf::getDV(me, iota);\n\n          if (ip_set == 0) {\n\n            // solve the local constitutive equations at the integration point\n            // and store the resultant local residual and its derivatives (dC_dxi)\n            global->interpolate(iota);\n            local->gather(pt, xi, xi_prev);\n            local->seed_wrt_xi();\n            int path = local->solve_nonlinear(global);\n            if (is_verification) {\n              nested->branch_paths()[step][es][elem] = path;\n            }\n            local->scatter(pt, xi);\n            EMatrix const dC_dxi = local->eigen_jacobian();\n\n            // re-evaluate the constitutive equations to obtain dC_dx\n            local->unseed_wrt_xi();\n            global->seed_wrt_x();\n            global->interpolate(iota);\n            local->evaluate(global);\n            EMatrix const dC_dx = local->eigen_jacobian();\n\n            // solve the forward sensitivty system to obtain dxi_dx\n            EMatrix const dxi_dx = dC_dxi.fullPivLu().solve(-dC_dx);\n\n            // evaluate and scatter point contributions to the global residual\n            local->seed_wrt_x(dxi_dx);\n\n          }\n\n          else {\n\n            global->seed_wrt_x();\n            global->interpolate(iota);\n\n          }\n\n          global->zero_residual();\n          global->evaluate(local, iota, w, dv, ip_set);\n          EMatrix const dtotal = global->eigen_jacobian();\n          EMatrix const elem_resid = global->eigen_residual();\n          global->scatter_lhs(disc, dtotal, LHS);\n          global->scatter_rhs(disc, elem_resid, RHS);\n          global->unseed_wrt_x();\n\n        }\n\n      }\n\n      // perform operations on element output\n      apf::destroyMeshElement(me);\n      global->unset_elem();\n      local->unset_elem();\n\n    }\n\n  }\n\n  // perform clean-ups of the residual objects\n  local->after_elems();\n  global->after_elems();\n\n}\n\ntemplate<typename T>\nvoid preprocess_qoi(RCP<QoI<T>> qoi,\n    RCP<LocalResidual<T>> local,\n    RCP<GlobalResidual<T>> global,\n    RCP<State> state,\n    RCP<Disc> disc,\n    int step) {\n\n  // gather discretization information\n  apf::Mesh* mesh = disc->apf_mesh();\n  int const q_order = disc->lv_shape()->getOrder();\n\n  // gather information from the state object\n  Array1D<apf::Field*> x = disc->primal(step).global;\n  Array1D<apf::Field*> xi = disc->primal(step).local;\n  Array1D<apf::Field*> x_prev = disc->primal(step - 1).global;\n  Array1D<apf::Field*> xi_prev = disc->primal(step - 1).local;\n\n  RCP<NestedDisc> nested;\n  if (disc->type() == VERIFICATION) {\n    nested = Teuchos::rcp_static_cast<NestedDisc>(disc);\n    ALWAYS_ASSERT(nested != Teuchos::null);\n    x = nested->primal_fine(step).global;\n    xi = nested->primal_fine(step).local;\n    x_prev = nested->primal_fine(step - 1).global;\n    xi_prev = nested->primal_fine(step - 1).local;\n  }\n\n  // perform initializations of the residual objects\n  global->before_elems(disc);\n  qoi->before_elems(disc, step);\n\n  // loop over all element sets in the discretization\n  for (int es = 0; es < disc->num_elem_sets(); ++es) {\n\n    local->before_elems(es, disc);\n\n    // gather the elements in the current element set\n    std::string const& es_name = disc->elem_set_name(es);\n    ElemSet const& elems = disc->elems(es_name);\n\n    // loop over all elements in the element set\n    for (size_t elem = 0; elem < elems.size(); ++elem) {\n\n      // get the current mesh element\n      apf::MeshEntity* e = elems[elem];\n      apf::MeshElement* me = apf::createMeshElement(mesh, e);\n\n      // peform operations on element input\n      global->set_elem(me);\n      local->set_elem(me);\n      qoi->set_elem(me);\n      global->gather(x, x_prev);\n\n      // loop over all integration points in the current element\n      int const npts = apf::countIntPoints(me, q_order);\n      for (int pt = 0; pt < npts; ++pt) {\n\n        // get integration point specific information\n        apf::Vector3 iota;\n        apf::getIntPoint(me, q_order, pt, iota);\n        double const w = apf::getIntWeight(me, q_order, pt);\n        double const dv = apf::getDV(me, iota);\n\n        // preprocess the quantities needed for QoI evaluation\n        global->interpolate(iota);\n        local->gather(pt, xi, xi_prev);\n        qoi->preprocess(es, elem, global, local, iota, w, dv);\n\n      }\n\n      // perform operations on element output\n      apf::destroyMeshElement(me);\n      global->unset_elem();\n      local->unset_elem();\n      qoi->unset_elem();\n\n    }\n\n  }\n\n  qoi->preprocess_finalize(step);\n\n  // perform clean-ups of the residual objects\n  local->after_elems();\n  global->after_elems();\n  qoi->after_elems();\n\n}\n\nvoid eval_adjoint_jacobian(\n    RCP<State> state,\n    RCP<Disc> disc,\n    Array3D<EVector>& g,\n    Array3D<EVector>& f,\n    int step) {\n\n  // gather discretization information\n  apf::Mesh* mesh = disc->apf_mesh();\n\n  // preprocess the QoI\n  RCP<LocalResidual<FADT>> local = state->d_residuals->local;\n  RCP<GlobalResidual<FADT>> global = state->d_residuals->global;\n  RCP<QoI<FADT>> qoi = state->d_qoi;\n  preprocess_qoi(qoi, local, global, state, disc, step);\n\n  // gather information from the state object\n  Array2D<RCP<MatrixT>>& LHS = state->la->A[GHOST];\n  Array1D<RCP<VectorT>>& RHS = state->la->b[GHOST];\n  Array1D<apf::Field*> x = disc->primal(step).global;\n  Array1D<apf::Field*> xi = disc->primal(step).local;\n  Array1D<apf::Field*> x_prev = disc->primal(step - 1).global;\n  Array1D<apf::Field*> xi_prev = disc->primal(step - 1).local;\n\n  // determine if we are doing verification\n  RCP<NestedDisc> nested;\n  bool force_path = false;\n  int path = 0;\n  if (disc->type() == VERIFICATION) {\n    nested = Teuchos::rcp_static_cast<NestedDisc>(disc);\n    ALWAYS_ASSERT(nested != Teuchos::null);\n    force_path = true;\n  }\n\n  // perform initializations of the residual objects\n  global->before_elems(disc);\n  qoi->before_elems(disc, step);\n\n  // loop over all element sets in the discretization\n  for (int es = 0; es < disc->num_elem_sets(); ++es) {\n\n    local->before_elems(es, disc);\n\n    // gather the elements in the current element set\n    std::string const& es_name = disc->elem_set_name(es);\n    ElemSet const& elems = disc->elems(es_name);\n\n    // loop over all elements in the element set\n    for (size_t elem = 0; elem < elems.size(); ++elem) {\n\n      // get the current mesh element\n      apf::MeshEntity* e = elems[elem];\n      apf::MeshElement* me = apf::createMeshElement(mesh, e);\n\n      // peform operations on element input\n      global->set_elem(me);\n      local->set_elem(me);\n      qoi->set_elem(me);\n      global->gather(x, x_prev);\n\n      // grab the forced path if required\n      if (force_path) {\n        path = nested->branch_paths()[step][es][elem];\n      }\n\n      // loop over domain ip sets\n      // ip_set = 0 -> coupled\n      // ip_set > 0 -> global only\n      Array1D<int> ip_sets = global->ip_sets();\n      int const num_ip_sets = ip_sets.size();\n\n      for (int ip_set = 0; ip_set < num_ip_sets; ++ip_set) {\n\n        // get the quadrature order for the ip set\n        int const q_order = ip_sets[ip_set];\n        // loop over all integration points in the current element\n        int const npts = apf::countIntPoints(me, q_order);\n\n        for (int pt = 0; pt < npts; ++pt) {\n\n          // get integration point specific information\n          apf::Vector3 iota;\n          apf::getIntPoint(me, q_order, pt, iota);\n          double const w = apf::getIntWeight(me, q_order, pt);\n          double const dv = apf::getDV(me, iota);\n\n          if (ip_set == 0) {\n\n            // solve the local constitutive equations at the integration point\n            // and store the resultant local residual and its derivatives (dC_dxi)\n            global->interpolate(iota);\n            local->gather(pt, xi, xi_prev);\n            local->seed_wrt_xi();\n            local->evaluate(global, force_path, path);\n            EMatrix const dC_dxi = local->eigen_jacobian();\n\n            // re-evaluate the constitutive equations to obtain dC_dx\n            local->unseed_wrt_xi();\n            global->seed_wrt_x();\n            global->interpolate(iota);\n            local->evaluate(global, force_path, path);\n            EMatrix const dC_dx = local->eigen_jacobian();\n\n            // solve the forward sensitivty system to obtain dxi_dx\n            EMatrix const dxi_dx = dC_dxi.fullPivLu().solve(-dC_dx);\n\n            // evaluate and scatter point contributions to the global LHS\n            local->seed_wrt_x(dxi_dx);\n\n            global->zero_residual();\n            global->evaluate(local, iota, w, dv, ip_set);\n            EMatrix const dtotal = global->eigen_jacobian();\n            EMatrix const dtotalT = dtotal.transpose();\n            global->scatter_lhs(disc, dtotalT, LHS);\n            local->unseed_wrt_xi();\n\n            // evaluate the QoI derivatives to obtain dJ_dx\n            qoi->evaluate(es, elem, global, local, iota, w, dv);\n            EVector const dJ_dx = qoi->eigen_dvector();\n            global->unseed_wrt_x();\n\n            // evaluate the QoI derivatives to obtain dJ_dxi\n            local->seed_wrt_xi();\n            global->interpolate(iota);\n            qoi->evaluate(es, elem, global, local, iota, w, dv);\n            EVector const dJ_dxi = qoi->eigen_dvector();\n            local->unseed_wrt_xi();\n\n            // update the local history variable\n            g[es][elem][pt] -= dJ_dxi;\n            EVector const g_pt = g[es][elem][pt];\n            EVector const f_pt = f[es][elem][pt];\n\n            // evaluate and scatter point contributions to the global RHS\n            EMatrix const dxi_dxT = dxi_dx.transpose();\n            EVector const rhs = -dJ_dx + f_pt + dxi_dxT * g_pt;\n            global->scatter_rhs(disc, rhs, RHS);\n\n          }\n\n          else {\n\n            global->seed_wrt_x();\n            global->interpolate(iota);\n            global->zero_residual();\n            global->evaluate(local, iota, w, dv, ip_set);\n            EMatrix const dtotal = global->eigen_jacobian();\n            EMatrix const dtotalT = dtotal.transpose();\n            global->scatter_lhs(disc, dtotalT, LHS);\n\n          }\n\n        }\n\n      }\n\n      // perform operations on element output\n      apf::destroyMeshElement(me);\n      global->unset_elem();\n      local->unset_elem();\n      qoi->unset_elem();\n\n    }\n\n  }\n\n  // perform clean-ups of the residual objects\n  local->after_elems();\n  global->after_elems();\n  qoi->after_elems();\n\n}\n\nvoid solve_adjoint_local(\n    RCP<State> state,\n    RCP<Disc> disc,\n    Array3D<EVector>& g,\n    Array3D<EVector>& f,\n    int step) {\n\n  // gather discretization information\n  apf::Mesh* mesh = disc->apf_mesh();\n  int const q_order = disc->lv_shape()->getOrder();\n\n  // gather information from the state object\n  RCP<LocalResidual<FADT>> local = state->d_residuals->local;\n  RCP<GlobalResidual<FADT>> global = state->d_residuals->global;\n  Array1D<apf::Field*> x = disc->primal(step).global;\n  Array1D<apf::Field*> xi = disc->primal(step).local;\n  Array1D<apf::Field*> x_prev = disc->primal(step - 1).global;\n  Array1D<apf::Field*> xi_prev = disc->primal(step - 1).local;\n  Array1D<apf::Field*> z = disc->adjoint(step).global;\n  Array1D<apf::Field*> phi = disc->adjoint(step).local;\n\n  // determine if we are doing verification\n  RCP<NestedDisc> nested;\n  bool force_path = false;\n  int path = 0;\n  if (disc->type() == VERIFICATION) {\n    nested = Teuchos::rcp_static_cast<NestedDisc>(disc);\n    ALWAYS_ASSERT(nested != Teuchos::null);\n    force_path = true;\n  }\n\n  // perform initializations of the residual objects\n  global->before_elems(disc);\n\n  // loop over all element sets in the discretization\n  for (int es = 0; es < disc->num_elem_sets(); ++es) {\n\n    local->before_elems(es, disc);\n\n    // gather the elements in the current element set\n    std::string const& es_name = disc->elem_set_name(es);\n    ElemSet const& elems = disc->elems(es_name);\n\n    // loop over all elements in the element set\n    for (size_t elem = 0; elem < elems.size(); ++elem) {\n\n      // get the current mesh element\n      apf::MeshEntity* e = elems[elem];\n      apf::MeshElement* me = apf::createMeshElement(mesh, e);\n\n      // peform operations on element input\n      global->set_elem(me);\n      local->set_elem(me);\n      global->gather(x, x_prev);\n\n      // grab the forced path if required\n      if (force_path) {\n        path = nested->branch_paths()[step][es][elem];\n      }\n\n      // grab the adjoint nodal solution at the element\n      EVector const z_nodes = global->gather_adjoint(z);\n\n      // loop over all integration points in the current element\n      int const npts = apf::countIntPoints(me, q_order);\n\n      for (int pt = 0; pt < npts; ++pt) {\n\n        // get integration point specific information\n        apf::Vector3 iota;\n        apf::getIntPoint(me, q_order, pt, iota);\n        double const w = apf::getIntWeight(me, q_order, pt);\n        double const dv = apf::getDV(me, iota);\n\n        // evaluate local/global residuals and their derivatives, store\n        // their transpose Jacobians, and grab g at the integration point\n        global->interpolate(iota);\n        local->gather(pt, xi, xi_prev);\n        local->seed_wrt_xi();\n        global->zero_residual();\n        global->evaluate(local, iota, w, dv, 0);\n        local->evaluate(global, force_path, path);\n        EMatrix const dC_dxiT = local->eigen_jacobian().transpose();\n        EMatrix const dR_dxiT = global->eigen_jacobian().transpose();\n        EVector const g_pt = g[es][elem][pt];\n\n        // Solve for the local adjoint variables and scatter them into fields\n        EVector const phi_pt = dC_dxiT.fullPivLu().solve(g_pt - dR_dxiT * z_nodes);\n        local->scatter_adjoint(pt, phi_pt, phi);\n\n        // Solve for the global history vector\n        local->unseed_wrt_xi();\n        global->seed_wrt_x_prev();\n        global->interpolate(iota);\n        local->evaluate(global, force_path, path);\n        EMatrix const dC_dx_prevT = local->eigen_jacobian().transpose();\n        f[es][elem][pt] = -dC_dx_prevT * phi_pt;\n\n        // Solve for the local history vector\n        global->unseed_wrt_x_prev();\n        global->interpolate(iota);\n        local->seed_wrt_xi_prev();\n        local->evaluate(global, force_path, path);\n        EMatrix const dC_dxi_prevT = local->eigen_jacobian().transpose();\n        g[es][elem][pt] = -dC_dxi_prevT * phi_pt;\n        local->unseed_wrt_xi_prev();\n\n      }\n\n      // perform operations on element output\n      apf::destroyMeshElement(me);\n      global->unset_elem();\n      local->unset_elem();\n\n    }\n\n  }\n\n  // perform clean-ups of the residual objects\n  local->after_elems();\n  global->after_elems();\n\n}\n\n\ndouble eval_qoi(RCP<State> state, RCP<Disc> disc, int step) {\n\n  // gather discretization information\n  apf::Mesh* mesh = disc->apf_mesh();\n  int const q_order = disc->lv_shape()->getOrder();\n\n  // preprocess the QoI\n  RCP<LocalResidual<double>> local = state->residuals->local;\n  RCP<GlobalResidual<double>> global = state->residuals->global;\n  RCP<QoI<double>> qoi = state->qoi;\n  preprocess_qoi(qoi, local, global, state, disc, step);\n\n  // gather information from the state object\n  Array1D<apf::Field*> x = disc->primal(step).global;\n  Array1D<apf::Field*> xi = disc->primal(step).local;\n  Array1D<apf::Field*> x_prev = disc->primal(step - 1).global;\n  Array1D<apf::Field*> xi_prev = disc->primal(step - 1).local;\n\n\n  RCP<NestedDisc> nested;\n  if (disc->type() == VERIFICATION) {\n    nested = Teuchos::rcp_static_cast<NestedDisc>(disc);\n    ALWAYS_ASSERT(nested != Teuchos::null);\n    x = nested->primal_fine(step).global;\n    xi = nested->primal_fine(step).local;\n    x_prev = nested->primal_fine(step - 1).global;\n    xi_prev = nested->primal_fine(step - 1).local;\n  }\n\n  // perform initializations of the residual objects\n  global->before_elems(disc);\n  qoi->before_elems(disc, step);\n\n  // initialize the QoI value at the step\n  double J = 0.;\n\n  // loop over all element sets in the discretization\n  for (int es = 0; es < disc->num_elem_sets(); ++es) {\n\n    local->before_elems(es, disc);\n\n    // gather the elements in the current element set\n    std::string const& es_name = disc->elem_set_name(es);\n    ElemSet const& elems = disc->elems(es_name);\n\n    // loop over all elements in the element set\n    for (size_t elem = 0; elem < elems.size(); ++elem) {\n\n      // get the current mesh element\n      apf::MeshEntity* e = elems[elem];\n      apf::MeshElement* me = apf::createMeshElement(mesh, e);\n\n      // peform operations on element input\n      global->set_elem(me);\n      local->set_elem(me);\n      qoi->set_elem(me);\n      global->gather(x, x_prev);\n\n      // loop over all integration points in the current element\n      int const npts = apf::countIntPoints(me, q_order);\n      for (int pt = 0; pt < npts; ++pt) {\n\n        // get integration point specific information\n        apf::Vector3 iota;\n        apf::getIntPoint(me, q_order, pt, iota);\n        double const w = apf::getIntWeight(me, q_order, pt);\n        double const dv = apf::getDV(me, iota);\n\n        // solve the local constitutive equations at the integration point\n        // and store the resultant local residual and its derivatives (dC_dxi)\n        global->interpolate(iota);\n        local->gather(pt, xi, xi_prev);\n        qoi->evaluate(es, elem, global, local, iota, w, dv);\n        qoi->scatter(J);\n\n      }\n\n      // perform operations on element output\n      apf::destroyMeshElement(me);\n      global->unset_elem();\n      local->unset_elem();\n      qoi->unset_elem();\n\n    }\n\n  }\n\n  qoi->postprocess(J);\n\n  // perform clean-ups of the residual objects\n  local->after_elems();\n  global->after_elems();\n  qoi->after_elems();\n\n  return J;\n\n}\n\nArray1D<double> eval_qoi_gradient(RCP<State> state, int step) {\n\n  int const num_active_params = state->residuals->local->num_active_params();\n  Array1D<double> grad(num_active_params);\n  EVector Egrad = EVector::Zero(num_active_params);\n\n  // gather discretization information\n  RCP<Disc> disc = state->disc;\n  apf::Mesh* mesh = disc->apf_mesh();\n\n  // preprocess the QoI\n  RCP<LocalResidual<FADT>> local = state->d_residuals->local;\n  RCP<GlobalResidual<FADT>> global = state->d_residuals->global;\n  RCP<QoI<FADT>> qoi = state->d_qoi;\n  preprocess_qoi(qoi, local, global, state, disc, step);\n\n  // gather information from the state object\n  Array1D<apf::Field*> x = disc->primal(step).global;\n  Array1D<apf::Field*> xi = disc->primal(step).local;\n  Array1D<apf::Field*> x_prev = disc->primal(step - 1).global;\n  Array1D<apf::Field*> xi_prev = disc->primal(step - 1).local;\n  Array1D<apf::Field*> z = disc->adjoint(step).global;\n  Array1D<apf::Field*> phi = disc->adjoint(step).local;\n\n\n  // perform initializations of the residual objects\n  global->before_elems(disc);\n  qoi->before_elems(disc, step);\n\n  // loop over all element sets in the discretization\n  for (int es = 0; es < disc->num_elem_sets(); ++es) {\n\n    local->before_elems(es, disc);\n\n    // gather the elements in the current element set\n    std::string const& es_name = disc->elem_set_name(es);\n    ElemSet const& elems = disc->elems(es_name);\n\n    // loop over all elements in the element set\n    for (size_t elem = 0; elem < elems.size(); ++elem) {\n\n      // get the current mesh element\n      apf::MeshEntity* e = elems[elem];\n      apf::MeshElement* me = apf::createMeshElement(mesh, e);\n\n      // peform operations on element input\n      global->set_elem(me);\n      local->set_elem(me);\n      qoi->set_elem(me);\n      global->gather(x, x_prev);\n\n      // grab the adjoint nodal solution at the element\n      EVector const z_nodes = global->gather_adjoint(z);\n\n      // loop over domain ip sets\n      // ip_set = 0 -> coupled\n      // ip_set > 0 -> global only\n      Array1D<int> ip_sets = global->ip_sets();\n      int const num_ip_sets = ip_sets.size();\n\n      for (int ip_set = 0; ip_set < num_ip_sets; ++ip_set) {\n\n        // get the quadrature order for the ip set\n        int const q_order = ip_sets[ip_set];\n        // loop over all integration points in the current element\n        int const npts = apf::countIntPoints(me, q_order);\n\n        for (int pt = 0; pt < npts; ++pt) {\n          // get integration point specific information\n          apf::Vector3 iota;\n          apf::getIntPoint(me, q_order, pt, iota);\n          double const w = apf::getIntWeight(me, q_order, pt);\n          double const dv = apf::getDV(me, iota);\n\n          // evaluate local/global residuals and their derivatives\n          // and dot with the corresponding adjoint solutions to\n          // compute gradient contributions\n          global->interpolate(iota);\n          global->zero_residual();\n          local->seed_wrt_params(es);\n\n          if (ip_set == 0) {\n            local->gather(pt, xi, xi_prev);\n            local->evaluate(global);\n            EMatrix const dC_dpT = local->eigen_jacobian().transpose();\n            EVector const phi_pt = local->gather_adjoint(pt, phi);\n            Egrad += dC_dpT * phi_pt;\n\n            // evaluate the QoI derivatives to obtain dJ_dp\n            qoi->evaluate(es, elem, global, local, iota, w, dv);\n            EVector const dJ_dp = qoi->eigen_dvector();\n            Egrad += dJ_dp;\n\n          }\n\n          global->evaluate(local, iota, w, dv, ip_set);\n          EMatrix const dR_dpT = global->eigen_jacobian().transpose();\n          Egrad += dR_dpT * z_nodes;\n          local->unseed_wrt_params(es);\n\n        }\n\n      }\n\n      // perform operations on element output\n      apf::destroyMeshElement(me);\n      global->unset_elem();\n      local->unset_elem();\n      qoi->unset_elem();\n\n    }\n\n  }\n\n  // perform clean-ups of the residual objects\n  local->after_elems();\n  global->after_elems();\n  qoi->after_elems();\n\n  EVector::Map(&grad[0], num_active_params) = Egrad;\n\n  return grad;\n}\n\n// TODO: write this using global->interpolate_error\n//void eval_error_contributions_nodal();\n\nvoid eval_error_contributions(\n    RCP<State> state,\n    RCP<Disc> disc,\n    apf::Field* R_error_field,\n    apf::Field* C_error_field,\n    int step) {\n\n  // gather the residuals from the state object\n  RCP<LocalResidual<double>> local = state->residuals->local;\n  RCP<GlobalResidual<double>> global = state->residuals->global;\n  Array1D<RCP<VectorT>>& resid_vec = state->la->b[GHOST];\n  Array1D<RCP<VectorT>>& z_vec = state->la->x[GHOST];\n\n  // gather discretization information\n  apf::Mesh* mesh = disc->apf_mesh();\n\n  // gather the prolonged forward state variables\n  Array1D<apf::Field*> x = disc->primal(step).global;\n  Array1D<apf::Field*> xi = disc->primal(step).local;\n  Array1D<apf::Field*> x_prev = disc->primal(step - 1).global;\n  Array1D<apf::Field*> xi_prev = disc->primal(step - 1).local;\n\n  // gather the enriched adjoint state variables\n  Array1D<apf::Field*> z = disc->adjoint(step).global;\n  Array1D<apf::Field*> phi = disc->adjoint(step).local;\n\n  // determine if we are doing verification\n  RCP<NestedDisc> nested;\n  bool force_path = false;\n  int path = 0;\n  if (disc->type() == VERIFICATION) {\n    nested = Teuchos::rcp_static_cast<NestedDisc>(disc);\n    ALWAYS_ASSERT(nested != Teuchos::null);\n    force_path = true;\n  }\n\n  // perform initializations of the residual objects\n  global->before_elems(disc);\n\n  // loop over all element sets in the discretization\n  for (int es = 0; es < disc->num_elem_sets(); ++es) {\n\n    local->before_elems(es, disc);\n\n    // gather the elements in the current element set\n    std::string const& es_name = disc->elem_set_name(es);\n    ElemSet const& elems = disc->elems(es_name);\n\n    // loop over all elements in the element set\n    for (size_t elem = 0; elem < elems.size(); ++elem) {\n\n      // get the current mesh element\n      apf::MeshEntity* e = elems[elem];\n      apf::MeshElement* me = apf::createMeshElement(mesh, e);\n\n      // peform operations on element input\n      global->set_elem(me);\n      local->set_elem(me);\n      global->gather(x, x_prev);\n\n      // grab the adjoint nodal solution at the element\n      EVector const z_nodes = global->gather_adjoint(z);\n      global->assign_rhs(disc, z_nodes, z_vec);\n\n      // grab the forced path if required\n      if (force_path) {\n        path = nested->branch_paths()[step][es][elem];\n      }\n\n      // loop over domain ip sets\n      // ip_set = 0 -> coupled\n      // ip_set > 0 -> global only\n      Array1D<int> ip_sets = global->ip_sets();\n      int const num_ip_sets = ip_sets.size();\n\n      for (int ip_set = 0; ip_set < num_ip_sets; ++ip_set) {\n\n        // get the quadrature order for the ip set\n        int const q_order = ip_sets[ip_set];\n        // loop over all integration points in the current element\n        int const npts = apf::countIntPoints(me, q_order);\n\n        for (int pt = 0; pt < npts; ++pt) {\n\n          // get integration point specific information\n          apf::Vector3 iota;\n          apf::getIntPoint(me, q_order, pt, iota);\n          double const w = apf::getIntWeight(me, q_order, pt);\n          double const dv = apf::getDV(me, iota);\n\n          if (ip_set == 0) {\n\n            // evaluate the global residual error contributions\n            local->gather(pt, xi, xi_prev);\n            global->zero_residual();\n            global->interpolate(iota);\n            global->evaluate(local, iota, w, dv, ip_set);\n            EVector const R = global->eigen_residual();\n            double const E_R_elem = z_nodes.dot(R);\n            double E_R = apf::getScalar(R_error_field, e, 0);\n            apf::setScalar(R_error_field, e, 0, E_R + E_R_elem);\n            global->scatter_rhs(disc, R, resid_vec);\n\n            // evaluate the local residual error contributions\n            local->evaluate(global, force_path, path);\n            EVector const C = local->eigen_residual();\n            EVector const phi_pt = local->gather_adjoint(pt, phi);\n            double const E_C_elem = phi_pt.dot(C);\n            double E_C = apf::getScalar(C_error_field, e, 0);\n            apf::setScalar(C_error_field, e, 0, E_C + E_C_elem);\n\n          }\n\n          else {\n\n            // evaluate the global residual error contributions\n            global->zero_residual();\n            global->interpolate(iota);\n            global->evaluate(local, iota, w, dv, ip_set);\n            EVector const R = global->eigen_residual();\n            double const E_R_elem = z_nodes.dot(R);\n            double E_R = apf::getScalar(R_error_field, e, 0);\n            apf::setScalar(R_error_field, e, 0, E_R + E_R_elem);\n            global->scatter_rhs(disc, R, resid_vec);\n\n          }\n\n        }\n\n      }\n\n      // perform operations on element output\n      apf::destroyMeshElement(me);\n      global->unset_elem();\n      local->unset_elem();\n\n    }\n\n  }\n\n  // perform clean-ups of the residual objects\n  local->after_elems();\n  global->after_elems();\n\n}\n\nvoid eval_linearization_errors(\n    RCP<State> state,\n    RCP<Disc> disc,\n    int step,\n    double& E_lin_R,\n    double& E_lin_C) {\n\n  // we must be a verification mesh to do this evaluation\n  ALWAYS_ASSERT(disc->type() == VERIFICATION);\n  RCP<NestedDisc> nested = Teuchos::rcp_static_cast<NestedDisc>(disc);\n  bool force_path = true;\n\n  // gather the residuals from the state object\n  RCP<LocalResidual<FADT>> local = state->d_residuals->local;\n  RCP<GlobalResidual<FADT>> global = state->d_residuals->global;\n\n  // gather discretization information\n  apf::Mesh* mesh = disc->apf_mesh();\n\n  // gather the prolonged forward state variables\n  Array1D<apf::Field*> x = disc->primal(step).global;\n  Array1D<apf::Field*> xi = disc->primal(step).local;\n  Array1D<apf::Field*> x_prev = disc->primal(step - 1).global;\n  Array1D<apf::Field*> xi_prev = disc->primal(step - 1).local;\n\n  // gather the enriched forward state variables\n  Array1D<apf::Field*> x_fine = nested->primal_fine(step).global;\n  Array1D<apf::Field*> xi_fine = nested->primal_fine(step).local;\n  Array1D<apf::Field*> x_prev_fine = nested->primal_fine(step - 1).global;\n  Array1D<apf::Field*> xi_prev_fine = nested->primal_fine(step - 1).local;\n\n  // gather the enriched adjoint state variables\n  Array1D<apf::Field*> z = disc->adjoint(step).global;\n  Array1D<apf::Field*> phi = disc->adjoint(step).local;\n\n  // perform initializations of the residual objects\n  global->before_elems(disc);\n\n  // loop over all element sets in the discretization\n  for (int es = 0; es < disc->num_elem_sets(); ++es) {\n\n    local->before_elems(es, disc);\n\n    // gather the elements in the current element set\n    std::string const& es_name = disc->elem_set_name(es);\n    ElemSet const& elems = disc->elems(es_name);\n\n    // loop over all elements in the element set\n    for (size_t elem = 0; elem < elems.size(); ++elem) {\n\n      // get the current mesh element\n      apf::MeshEntity* e = elems[elem];\n      apf::MeshElement* me = apf::createMeshElement(mesh, e);\n\n      // peform operations on element input\n      global->set_elem(me);\n      local->set_elem(me);\n      global->gather(x, x_prev);\n\n      // grab some nodal solution information at the element\n      EVector const z_nodes = global->gather_adjoint(z);\n      EVector const x_diff = global->gather_difference(x_fine, x);\n      EVector const x_prev_diff =\n          global->gather_difference(x_prev_fine, x_prev);\n\n      // initialize the element level global linearization error\n      EVector ELR_e = EVector::Zero(x_diff.size());\n\n      // grab the forced path\n      int const path = nested->branch_paths()[step][es][elem];\n\n      // loop over domain ip sets\n      // ip_set = 0 -> coupled\n      // ip_set > 0 -> global only\n      Array1D<int> ip_sets = global->ip_sets();\n      int const num_ip_sets = ip_sets.size();\n\n      for (int ip_set = 0; ip_set < num_ip_sets; ++ip_set) {\n\n        // get the quadrature order for the ip set\n        int const q_order = ip_sets[ip_set];\n        // loop over all integration points in the current element\n        int const npts = apf::countIntPoints(me, q_order);\n\n        for (int pt = 0; pt < npts; ++pt) {\n\n          // get integration point specific information\n          apf::Vector3 iota;\n          apf::getIntPoint(me, q_order, pt, iota);\n          double const w = apf::getIntWeight(me, q_order, pt);\n          double const dv = apf::getDV(me, iota);\n\n          if (ip_set == 0) {\n\n            // grab local state variable data at the point\n            EVector const phi_pt = local->gather_adjoint(pt, phi);\n            EVector const xi_diff = local->gather_difference(pt, xi_fine, xi);\n            EVector const xi_prev_diff =\n                local->gather_difference(pt, xi_prev_fine, xi_prev);\n\n            // evaluate derivatives wrt x\n            global->zero_residual();\n            global->seed_wrt_x();\n            global->interpolate(iota);\n            local->gather(pt, xi, xi_prev);\n            global->evaluate(local, iota, w, dv, ip_set);\n            local->evaluate(global, force_path, path);\n            EVector const R = global->eigen_residual();\n            EVector const C = local->eigen_residual();\n            EMatrix const dR_dx = global->eigen_jacobian();\n            EMatrix const dC_dx = local->eigen_jacobian();\n\n            // evaluate derivatives wrt xi\n            global->unseed_wrt_x();\n            global->zero_residual();\n            local->seed_wrt_xi();\n            global->interpolate(iota);\n            global->evaluate(local, iota, w, dv, ip_set);\n            local->evaluate(global, force_path, path);\n            EMatrix const dR_dxi = global->eigen_jacobian();\n            EMatrix const dC_dxi = local->eigen_jacobian();\n\n            // evaluate derivatives wrt x_prev\n            local->unseed_wrt_xi();\n            global->seed_wrt_x_prev();\n            global->interpolate(iota);\n            local->evaluate(global, force_path, path);\n            EMatrix const dC_dx_prev = local->eigen_jacobian();\n\n            // evaluate derivatives wrt xi_prev\n            global->unseed_wrt_x_prev();\n            global->interpolate(iota);\n            local->seed_wrt_xi_prev();\n            local->evaluate(global, force_path, path);\n            EMatrix const dC_dxi_prev = local->eigen_jacobian();\n\n            // evaluate the point level local linearization error\n            EVector const ELC_e =\n              -C - (dC_dx * x_diff) - (dC_dxi * xi_diff) -\n              (dC_dx_prev * x_prev_diff) - (dC_dxi_prev * xi_prev_diff);\n            E_lin_C += phi_pt.dot(ELC_e);\n\n            // evaluate point contribs to the global linearization error\n            EVector const ELR_e = -R - (dR_dx * x_diff) - (dR_dxi * xi_diff);\n            E_lin_R += z_nodes.dot(ELR_e);\n\n            // unseed on output\n            local->unseed_wrt_xi_prev();\n\n          }\n\n          else {\n\n            // evaluate the global residual linearization error contributions\n            global->zero_residual();\n            global->seed_wrt_x();\n            global->interpolate(iota);\n            global->evaluate(local, iota, w, dv, ip_set);\n            EVector const R = global->eigen_residual();\n            EMatrix const dR_dx = global->eigen_jacobian();\n\n            // evaluate point contribs to the global linearization error\n            EVector const ELR_e = -R - (dR_dx * x_diff);\n            E_lin_R += z_nodes.dot(ELR_e);\n\n            // unseed on output\n            global->unseed_wrt_x();\n\n          }\n\n        }\n\n      }\n\n      // perform operations on element output\n      apf::destroyMeshElement(me);\n      global->unset_elem();\n      local->unset_elem();\n\n    }\n\n  }\n\n  // perform clean-ups of the residual objects\n  local->after_elems();\n  global->after_elems();\n\n}\n\n// TODO: Cauchy stress can have contributions from fields\n// with different polynomials orders (e.g. constant + linear).\n// Generalize to handle such cases.\napf::Field* eval_cauchy(RCP<State> state, int step) {\n\n  // an assumption about the pressure index\n  int const pressure_idx = 1;\n\n  // gather discretization information\n  RCP<Disc> disc = state->disc;\n  apf::Mesh* mesh = disc->apf_mesh();\n  int const ndims = mesh->getDimension();\n  int const q_order = disc->lv_shape()->getOrder();\n\n  // gather information from the state object\n  RCP<LocalResidual<double>> local = state->residuals->local;\n  RCP<GlobalResidual<double>> global = state->residuals->global;\n  Array1D<apf::Field*> x = disc->primal(step).global;\n  Array1D<apf::Field*> xi = disc->primal(step).local;\n  Array1D<apf::Field*> x_prev = disc->primal(step - 1).global;\n  Array1D<apf::Field*> xi_prev = disc->primal(step - 1).local;\n\n  // create the field to fill in\n  apf::FieldShape* shape = state->disc->lv_shape();\n  apf::Field* field = apf::createField(mesh, \"sigma\", apf::MATRIX, shape);\n  apf::zeroField(field);\n  if (step == 0) return field;\n\n  // perform initializations of the residual objects\n  global->before_elems(disc);\n\n  // loop over all element sets in the discretization\n  for (int es = 0; es < disc->num_elem_sets(); ++es) {\n\n    local->before_elems(es, disc);\n\n    // gather the elements in the current element set\n    std::string const& es_name = disc->elem_set_name(es);\n    ElemSet const& elems = disc->elems(es_name);\n\n    // loop over all elements in the element set\n    for (size_t elem = 0; elem < elems.size(); ++elem) {\n\n      // get the current mesh element\n      apf::MeshEntity* e = elems[elem];\n      apf::MeshElement* me = apf::createMeshElement(mesh, e);\n\n      // peform operations on element input\n      global->set_elem(me);\n      local->set_elem(me);\n      global->gather(x, x_prev);\n\n      // loop over all integration points in the current element\n      int const npts = apf::countIntPoints(me, q_order);\n      for (int pt = 0; pt < npts; ++pt) {\n\n        // get integration point specific information\n        apf::Vector3 iota;\n        apf::getIntPoint(me, q_order, pt, iota);\n\n        // evaluate the cauchy stress tensor at the point\n        global->interpolate(iota);\n        local->gather(pt, xi, xi_prev);\n        double const p = global->scalar_x(pressure_idx);\n        Tensor<double> const sigma = local->cauchy(global, p);\n\n        // set the cauchy stress tensor to a field\n        apf::Matrix3x3 apf_sigma(0, 0, 0, 0, 0, 0, 0, 0, 0);\n        for (int i = 0; i < ndims; ++i) {\n          for (int j = 0; j < ndims; ++j) {\n            apf_sigma[i][j] = sigma(i, j);\n          }\n        }\n        apf::setMatrix(field, e, pt, apf_sigma);\n\n      }\n\n      // perform operations on element output\n      apf::destroyMeshElement(me);\n      global->unset_elem();\n      local->unset_elem();\n\n    }\n  }\n\n  // perform clean-ups of the residual objects\n  local->after_elems();\n  global->after_elems();\n\n  return field;\n\n}\n\n}\n", "meta": {"hexsha": "bcf8772eebafa13ff5ec8e828256d0f8a246d346", "size": 39337, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/evaluations.cpp", "max_stars_repo_name": "sandialabs/calibr8", "max_stars_repo_head_hexsha": "a7be9213a49eb2b56f58041a2a88b0184382de4d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2021-08-31T00:33:36.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T17:10:28.000Z", "max_issues_repo_path": "src/evaluations.cpp", "max_issues_repo_name": "sandialabs/calibr8", "max_issues_repo_head_hexsha": "a7be9213a49eb2b56f58041a2a88b0184382de4d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/evaluations.cpp", "max_forks_repo_name": "sandialabs/calibr8", "max_forks_repo_head_hexsha": "a7be9213a49eb2b56f58041a2a88b0184382de4d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.056302521, "max_line_length": 83, "alphanum_fraction": 0.6252383252, "num_tokens": 10527, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7520125737597972, "lm_q2_score": 0.4649015713733885, "lm_q1q2_score": 0.34961182723347595}}
{"text": "//---------------------------------------------------------------------------//\n// Copyright (c) 2018-2021 Mikhail Komarov <nemo@nil.foundation>\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//    http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//---------------------------------------------------------------------------//\n\n#include <iostream>\n\n\n#include <boost/filesystem.hpp>\n#include <boost/program_options.hpp>\n#include <boost/random.hpp>\n#include <boost/algorithm/hex.hpp>\n\n#include \"circuit.hpp\"\n#include \"list_contains_component.hpp\"\n\n#include <nil/crypto3/algebra/curves/bls12.hpp>\n#include <nil/crypto3/algebra/fields/bls12/base_field.hpp>\n#include <nil/crypto3/algebra/fields/bls12/scalar_field.hpp>\n#include <nil/crypto3/algebra/fields/arithmetic_params/bls12.hpp>\n#include <nil/crypto3/algebra/curves/params/multiexp/bls12.hpp>\n#include <nil/crypto3/algebra/curves/params/wnaf/bls12.hpp>\n\n#include <nil/crypto3/zk/components/blueprint.hpp>\n#include <nil/crypto3/zk/components/blueprint_variable.hpp>\n\n#include <nil/crypto3/zk/components/hashes/knapsack/knapsack_component.hpp>\n#include <nil/crypto3/zk/components/hashes/hmac_component.hpp>\n#include <nil/crypto3/zk/components/disjunction.hpp>\n\n#include <nil/crypto3/zk/snark/schemes/ppzksnark/r1cs_gg_ppzksnark.hpp>\n#include <nil/crypto3/zk/snark/schemes/ppzksnark/r1cs_gg_ppzksnark/marshalling.hpp>\n\n#include <nil/crypto3/zk/snark/algorithms/generate.hpp>\n#include <nil/crypto3/zk/snark/algorithms/verify.hpp>\n#include <nil/crypto3/zk/snark/algorithms/prove.hpp>\n\nusing namespace nil::crypto3;\nusing namespace zk::components;\n\ntypedef algebra::curves::bls12<381> curve_type;\ntypedef typename curve_type::scalar_field_type field_type;\n\ntypedef zk::snark::r1cs_gg_ppzksnark<curve_type> scheme_type;\ntypedef nil::marshalling::verifier_input_serializer_tvm<scheme_type> serializer_tvm;\ntypedef nil::marshalling::verifier_input_deserializer_tvm<scheme_type> deserializer_tvm;\ntypedef hmac_component<field_type,\n                       knapsack_crh_with_bit_out_component<field_type>,\n                       knapsack_crh_with_field_out_component<field_type>>\n    Hmac;\n\nconstexpr const std::size_t modulus_bits = field_type::modulus_bits;\nconstexpr const std::size_t modulus_chunks = modulus_bits / 8 + (modulus_bits % 8 ? 1 : 0);\n\n\nstd::string field_element_to_hex(field_type::value_type element) {\n    std::string hex;\n    std::vector<std::uint8_t> byteblob(modulus_chunks);\n    std::vector<std::uint8_t>::iterator write_iter = byteblob.begin();\n    serializer_tvm::field_type_process<field_type>(element, write_iter);\n    boost::algorithm::hex(byteblob.begin(), byteblob.end(), std::back_inserter(hex));\n    return hex;\n}\n\ninline std::vector<uint8_t> read_vector_from_disk(boost::filesystem::path file_path) {\n    boost::filesystem::ifstream instream(file_path, std::ios::in | std::ios::binary);\n    std::vector<uint8_t> data((std::istreambuf_iterator<char>(instream)), std::istreambuf_iterator<char>());\n    return data;\n}\n\ninline void write_vector_to_disk(boost::filesystem::path file_path, const std::vector<uint8_t> &data) {\n    boost::filesystem::ofstream ostream(file_path, std::ios::out | std::ios::binary);\n    for(auto byte : data) {\n        ostream << byte;\n    }\n}\n\nvoid generate_vote_secret() {\n    boost::random::random_device rd;\n    std::vector<std::uint8_t> secret_byteblob(circuit::SECRET_BITS_SIZE / 8);\n    rd.generate(secret_byteblob.begin(), secret_byteblob.end());\n    std::vector<bool> secret_bitblob(256);\n    nil::crypto3::detail::pack<stream_endian::big_octet_big_bit, stream_endian::big_octet_big_bit, 8, 1>(\n        secret_byteblob.begin(), secret_byteblob.end(), secret_bitblob.begin());\n\n    field_type::value_type hash = Hmac::get_hmac(secret_bitblob, std::vector<bool>(circuit::HASH_MSG_LEN, 1)) [0];\n\n    std::string hash_hex = field_element_to_hex(hash);\n\n    boost::filesystem::path secret_path(hash_hex);\n    write_vector_to_disk(secret_path, secret_byteblob);\n    std::cout << \"Voting secret has been saved to \" << hash_hex << std::endl;\n    std::cout << \"Voting secret hash is: \" << hash_hex << std::endl;\n}\n\nint main(int argc, char *argv[]) {\n    boost::filesystem::path pout, pkout, vkout, pkin, sin, hlin;\n    std::uint32_t vote_choice;\n    boost::program_options::options_description options(\n        \"R1CS Generic Group PreProcessing Zero-Knowledge Succinct Non-interactive ARgument of Knowledge \"\n        \"(https://eprint.iacr.org/2016/260.pdf) CLI Proof Generator\");\n    // clang-format off\n    options.add_options()(\"help,h\", \"Display help message\")\n    (\"version,v\", \"Display version\")\n    (\"generate-vote-secret\", \"Generate vote secret\")\n    (\"generate-keypair\", \"Generate keys\")\n    (\"prove\", \"Generate proof\")\n    (\"proof-output,po\", boost::program_options::value<boost::filesystem::path>(&pout)->default_value(\"proof\"))\n    (\"proving-key,pk\", boost::program_options::value<boost::filesystem::path>(&pkin)->default_value(\"pkey\"))\n    (\"proving-key-output,pko\", boost::program_options::value<boost::filesystem::path>(&pkout))\n    (\"verifying-key-output,vko\", boost::program_options::value<boost::filesystem::path>(&vkout))\n    (\"secret,s\", boost::program_options::value<boost::filesystem::path>(&sin))\n    (\"hash-list,hl\", boost::program_options::value<boost::filesystem::path>(&hlin))\n    (\"vote\", boost::program_options::value<std::uint32_t>(&vote_choice));\n\n    // clang-format on\n\n    boost::program_options::variables_map vm;\n    boost::program_options::store(boost::program_options::command_line_parser(argc, argv).options(options).run(), vm);\n    boost::program_options::notify(vm);\n\n    if (vm.count(\"help\") || argc < 2) {\n        std::cout << options << std::endl;\n        return 0;\n    }\n\n    if (vm.count(\"prove\")) {\n        if (!(vm.count(\"secret\") && vm.count(\"hash-list\") && vm.count(\"vote\"))) {\n            std::cerr << \"--secret, --hash-list and --vote are required.\" << std::endl;\n            return 1;\n        } else if (!boost::filesystem::exists(sin)) {\n            std::cerr << \"file not found: \" << sin << std::endl;\n            return 1;\n        } else if (!boost::filesystem::exists(hlin)) {\n            std::cerr << \"file not found: \" << hlin << std::endl;\n            return 1;\n        }\n    }\n\n    if (vm.count(\"generate-vote-secret\")) {\n        generate_vote_secret();\n        return 0;\n    }\n\n    blueprint<field_type> bp;\n    if(!vm.count(\"prove\")) {\n        bp = circuit::generate_circuit<field_type>();\n    } else {\n        std::vector<std::uint8_t> secret_byteblob = read_vector_from_disk(sin);\n        assert(secret_byteblob.size() == circuit::SECRET_BITS_SIZE / 8);\n        std::vector<bool> secret_bv(circuit::SECRET_BITS_SIZE);\n        nil::crypto3::detail::pack<stream_endian::big_octet_big_bit, stream_endian::big_octet_big_bit, 8, 1>(\n            secret_byteblob.begin(), secret_byteblob.end(), secret_bv.begin());\n\n        boost::filesystem::ifstream hlinf(hlin);\n\n        std::vector<std::string> hashes_hex;\n\n        std::size_t i = 0;\n        while (!hlinf.eof()) {\n            std::string line;\n            std::getline(hlinf, line);\n            if (!line.empty()) {\n                hashes_hex.insert(hashes_hex.end(), line);\n            }\n        }\n\n        std::vector<std::vector<std::uint8_t>> hashes_bytes(hashes_hex.size());\n        for (std::size_t i = 0; i < hashes_hex.size(); ++i) {\n            if (hashes_hex[i].size() != modulus_chunks * 2) {\n                std::cout << \"Hash number \" << i + 1 << \" is not \" << modulus_chunks * 2 << \"character long but \"\n                          << hashes_hex.size() << std::endl;\n                return 1;\n            }\n            hashes_bytes[i].resize(modulus_chunks);\n            boost::algorithm::unhex(hashes_hex[i].begin(), hashes_hex[i].end(), hashes_bytes[i].begin());\n        }\n\n        std::vector<field_type::value_type> hashes_field_elements(circuit::MAX_VOTERS);\n\n        for (size_t i = 0; i < hashes_bytes.size(); ++i) {\n            nil::marshalling::status_type status;\n            hashes_field_elements[i] =\n                deserializer_tvm::field_type_process<field_type>(\n                    hashes_bytes[i].cbegin(), hashes_bytes[i].cend(), status);\n        }\n\n        for (size_t i = hashes_bytes.size(); i < hashes_field_elements.size(); ++i) {\n            hashes_field_elements[i] = field_type::value_type::zero();\n        }\n\n        field_type::value_type hash =\n            Hmac::get_hmac(secret_bv, std::vector<bool>(circuit::HASH_MSG_LEN, 1)) [0];\n        field_type::value_type anonymous_id =\n            Hmac::get_hmac(secret_bv, std::vector<bool>(circuit::ANONYMOUS_ID_MSG_LEN, 1)) [0];\n        \n        std::vector<bool> vote_choice_bv(circuit::VOTE_MSG_LEN);\n\n        for(std::size_t i = 0, temp = vote_choice; i < circuit::VOTE_MSG_LEN; ++i) {\n            vote_choice_bv[i] = temp&1;\n            temp >>= 1;\n        }\n\n        field_type::value_type vote_choice_hmac =\n            Hmac::get_hmac(secret_bv, vote_choice_bv) [0];\n\n        std::size_t index = \n            std::find(hashes_field_elements.begin(),\n                      hashes_field_elements.end(),\n                      hash) - hashes_field_elements.begin();\n\n        if(index < 0 ) {\n            std::cout << \"The voting secret's hash is not in the voters hashes list\" << std::endl;\n            return 1;\n        }\n        \n\n        bp = circuit::generate_circuit_with_witness<field_type>(\n            hashes_field_elements,\n            secret_bv,\n            vote_choice,\n            index,\n            vote_choice_hmac,\n            anonymous_id\n        );\n        std::cout << \"is blueprint satisfied:\" << (bp.is_satisfied() ? \"true\" : \"false\") << std::endl;\n\n        std::cout << \"Your vote hmac is: \" << field_element_to_hex(vote_choice_hmac) << std::endl;        \n        std::cout << \"Your anonymous voter id is: \" << field_element_to_hex(anonymous_id) << std::endl;\n\n    }\n    \n    typename scheme_type::proving_key_type proving_key;\n    if (vm.count(\"generate-keypair\")) {\n        std::cout << \"Starting generator\" << std::endl;\n        zk::snark::r1cs_constraint_system<field_type> constraint_system =\n            bp.get_constraint_system();\n        std::cout << constraint_system.num_constraints() << std::endl;\n        std::cout << constraint_system.num_variables() << std::endl;\n        typename scheme_type::keypair_type keypair =\n             zk::snark::generate<scheme_type>(constraint_system);\n        std::vector<std::uint8_t> verification_key_byteblob =\n            serializer_tvm::process(keypair.second);\n        write_vector_to_disk(vkout, verification_key_byteblob);\n        \n        std::vector<std::uint8_t> proving_key_byteblob =\n            serializer_tvm::process(keypair.first);\n        write_vector_to_disk(pkout, proving_key_byteblob);\n\n        proving_key=keypair.first;\n    } else {\n        std::cout << \"Loading proving key\" << std::endl;\n        std::vector<uint8_t> proving_key_byteblob = read_vector_from_disk(pkin);\n        nil::marshalling::status_type pk_desrialize_status;\n        proving_key =\n             deserializer_tvm::proving_key_process(proving_key_byteblob.begin(),\n                                                   proving_key_byteblob.end(),\n                                                   pk_desrialize_status);\n\n        if(pk_desrialize_status != nil::marshalling::status_type::success) {\n            std::cerr << \"Error: Could not deserialize proving key\" << std::endl;\n            std::cerr << \"Status is:\" << static_cast<int>(pk_desrialize_status) << std::endl;\n            return 1;\n        }\n    }\n\n    if (vm.count(\"prove\")) {\n        std::cout << \"is blueprint satisfied:\" << (bp.is_satisfied() ? \"true\" : \"false\") << std::endl;\n\n        std::cout << \"Starting prover\" << std::endl;\n\n        const typename scheme_type::proof_type proof =\n            zk::snark::prove<scheme_type>(proving_key, bp.primary_input(), bp.auxiliary_input());\n        std::vector<std::uint8_t> proof_byteblob =\n            serializer_tvm::process(proof);\n        boost::filesystem::ofstream poutf(pout);\n        for (const auto &v : proof_byteblob) {\n            poutf << v;\n        }\n        poutf.close();\n    }\n\n    return 0;\n}\n", "meta": {"hexsha": "dd8d69e9fd0edea5b6ada2733824f5b6f85ffc89", "size": 12634, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "proposal-18/submission-2/anonymous-vote/bin/cli/src/main.cpp", "max_stars_repo_name": "Tonium-io/devex", "max_stars_repo_head_hexsha": "e031f74b0d08958a3c6e56d9c2b8c386acc96f8e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-05-09T14:40:45.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-09T14:40:45.000Z", "max_issues_repo_path": "proposal-18/submission-2/anonymous-vote/bin/cli/src/main.cpp", "max_issues_repo_name": "Tonium-io/devex", "max_issues_repo_head_hexsha": "e031f74b0d08958a3c6e56d9c2b8c386acc96f8e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-12-09T04:33:41.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-09T04:35:09.000Z", "max_forks_repo_path": "proposal-18/submission-2/anonymous-vote/bin/cli/src/main.cpp", "max_forks_repo_name": "Tonium-io/devex", "max_forks_repo_head_hexsha": "e031f74b0d08958a3c6e56d9c2b8c386acc96f8e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 13.0, "max_forks_repo_forks_event_min_datetime": "2021-05-05T20:58:32.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-17T08:18:07.000Z", "avg_line_length": 42.6824324324, "max_line_length": 118, "alphanum_fraction": 0.6416020263, "num_tokens": 3091, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.8577681049901037, "lm_q2_score": 0.4073334000459302, "lm_q1q2_score": 0.3493975986565734}}
{"text": "/*\n * L2ProductRightHandSide.cc\n *\n *  Created on: 29.06.2017\n *      Author: thies\n */\n\n#include <deal.II/base/quadrature.h>\n#include <deal.II/dofs/dof_handler.h>\n#include <deal.II/lac/vector.h>\n\n#include <forward/L2ProductRightHandSide.h>\n\nnamespace wavepi {\nnamespace forward {\nusing namespace dealii;\nusing namespace wavepi::base;\n\ntemplate <int dim>\nL2ProductRightHandSide<dim>::L2ProductRightHandSide(std::shared_ptr<DiscretizedFunction<dim>> f1,\n                                                    std::shared_ptr<DiscretizedFunction<dim>> f2)\n    : func1(f1), func2(f2) {}\n\ntemplate <int dim>\nL2ProductRightHandSide<dim>::AssemblyScratchData::AssemblyScratchData(const FiniteElement<dim> &fe,\n                                                                      const Quadrature<dim> &quad)\n    : fe_values(fe, quad, update_values | update_quadrature_points | update_JxW_values) {}\n\ntemplate <int dim>\nL2ProductRightHandSide<dim>::AssemblyScratchData::AssemblyScratchData(const AssemblyScratchData &scratch_data)\n    : fe_values(scratch_data.fe_values.get_fe(), scratch_data.fe_values.get_quadrature(),\n                update_values | update_quadrature_points | update_JxW_values) {}\n\ntemplate <int dim>\nvoid L2ProductRightHandSide<dim>::copy_local_to_global(Vector<double> &result, const AssemblyCopyData &copy_data) {\n  for (unsigned int i = 0; i < copy_data.local_dof_indices.size(); ++i)\n    result(copy_data.local_dof_indices[i]) += copy_data.cell_rhs(i);\n}\n\ntemplate <int dim>\nvoid L2ProductRightHandSide<dim>::local_assemble(const Vector<double> &f1, const Vector<double> &f2,\n                                                 const typename DoFHandler<dim>::active_cell_iterator &cell,\n                                                 AssemblyScratchData &scratch_data, AssemblyCopyData &copy_data) {\n  const unsigned int dofs_per_cell = scratch_data.fe_values.get_fe().dofs_per_cell;\n  const unsigned int n_q_points    = scratch_data.fe_values.get_quadrature().size();\n\n  copy_data.cell_rhs.reinit(dofs_per_cell);\n  copy_data.local_dof_indices.resize(dofs_per_cell);\n  scratch_data.fe_values.reinit(cell);\n\n  cell->get_dof_indices(copy_data.local_dof_indices);\n\n  for (unsigned int q_point = 0; q_point < n_q_points; ++q_point)\n    for (unsigned int i = 0; i < dofs_per_cell; ++i)\n      for (unsigned int k1 = 0; k1 < dofs_per_cell; ++k1)\n        for (unsigned int k2 = 0; k2 < dofs_per_cell; ++k2)\n          copy_data.cell_rhs(i) -=\n              f1[copy_data.local_dof_indices[k1]] * scratch_data.fe_values.shape_value(k1, q_point) *\n              f2[copy_data.local_dof_indices[k2]] * scratch_data.fe_values.shape_value(k2, q_point) *\n              scratch_data.fe_values.shape_value(i, q_point) * scratch_data.fe_values.JxW(q_point);\n}\n\ntemplate <int dim>\nvoid L2ProductRightHandSide<dim>::create_right_hand_side(const DoFHandler<dim> &dof, const Quadrature<dim> &quad,\n                                                         Vector<double> &rhs) const {\n  func1->set_time(this->get_time());\n  func2->set_time(this->get_time());\n\n  Vector<double> coeffs1 = func1->get_function_coefficients(func1->get_time_index());\n  Assert(coeffs1.size() == dof.n_dofs(), ExcDimensionMismatch(coeffs1.size(), dof.n_dofs()));\n\n  Vector<double> coeffs2 = func2->get_function_coefficients(func2->get_time_index());\n  Assert(coeffs2.size() == dof.n_dofs(), ExcDimensionMismatch(coeffs2.size(), dof.n_dofs()));\n\n  WorkStream::run(\n      dof.begin_active(), dof.end(),\n      std::bind(&L2ProductRightHandSide<dim>::local_assemble, *this, std::ref(coeffs1), std::ref(coeffs2),\n                std::placeholders::_1, std::placeholders::_2, std::placeholders::_3),\n      std::bind(&L2ProductRightHandSide<dim>::copy_local_to_global, *this, std::ref(rhs), std::placeholders::_1),\n      AssemblyScratchData(dof.get_fe(), quad), AssemblyCopyData());\n}\n\ntemplate <int dim>\nstd::shared_ptr<DiscretizedFunction<dim>> L2ProductRightHandSide<dim>::get_func1() const {\n  return func1;\n}\n\ntemplate <int dim>\nvoid L2ProductRightHandSide<dim>::set_func1(std::shared_ptr<DiscretizedFunction<dim>> func1) {\n  this->func1 = func1;\n}\n\ntemplate <int dim>\nstd::shared_ptr<DiscretizedFunction<dim>> L2ProductRightHandSide<dim>::get_func2() const {\n  return func2;\n}\n\ntemplate <int dim>\nvoid L2ProductRightHandSide<dim>::set_func2(std::shared_ptr<DiscretizedFunction<dim>> func2) {\n  this->func2 = func2;\n}\n\ntemplate class L2ProductRightHandSide<1>;\ntemplate class L2ProductRightHandSide<2>;\ntemplate class L2ProductRightHandSide<3>;\n\n} /* namespace forward */\n} /* namespace wavepi */\n", "meta": {"hexsha": "ba3271fcb8669059bfc8b644154823cc95854869", "size": 4564, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lib/forward/L2ProductRightHandSide.cpp", "max_stars_repo_name": "thiesgerken/wavepi", "max_stars_repo_head_hexsha": "5af37946dcc1910ad1cccdc76d2e2f546eeafec4", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "lib/forward/L2ProductRightHandSide.cpp", "max_issues_repo_name": "thiesgerken/wavepi", "max_issues_repo_head_hexsha": "5af37946dcc1910ad1cccdc76d2e2f546eeafec4", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lib/forward/L2ProductRightHandSide.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": 41.871559633, "max_line_length": 115, "alphanum_fraction": 0.6980718668, "num_tokens": 1161, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7577943712746406, "lm_q2_score": 0.4610167793123159, "lm_q1q2_score": 0.34935592042603614}}
{"text": "/*\n Copyright (C) 2018 Quaternion Risk Management Ltd\n All rights reserved.\n\n This file is part of ORE, a free-software/open-source library\n for transparent pricing and risk analysis - http://opensourcerisk.org\n\n ORE is free software: you can redistribute it and/or modify it\n under the terms of the Modified BSD License.  You should have received a\n copy of the license along with this program.\n The license is also available online at <http://opensourcerisk.org>\n\n This program is distributed on the basis that it will form a useful\n contribution to risk analytics and model standardisation, but WITHOUT\n ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n FITNESS FOR A PARTICULAR PURPOSE. See the license for more details.\n*/\n\n/*! \\file qle/termstructures/pricecurve.hpp\n    \\brief Interpolated price curve\n*/\n\n#ifndef quantext_price_curve_hpp\n#define quantext_price_curve_hpp\n\n#include <boost/algorithm/cxx11/is_sorted.hpp>\n\n#include <qle/termstructures/pricetermstructure.hpp>\n\n#include <ql/currency.hpp>\n#include <ql/math/comparison.hpp>\n#include <ql/patterns/lazyobject.hpp>\n#include <ql/quote.hpp>\n#include <ql/termstructures/interpolatedcurve.hpp>\n#include <ql/time/calendars/nullcalendar.hpp>\n\nnamespace QuantExt {\n\n//! Interpolated price curve\n/*! Class representing a curve of projected prices in the future.\n\n    \\warning for consistency, if curve is constructed by inferring times from dates\n             using a given day counter, pass the same day counter to the constructor\n\n    \\ingroup termstructures\n*/\ntemplate <class Interpolator>\nclass InterpolatedPriceCurve : public PriceTermStructure,\n                               public QuantLib::LazyObject,\n                               protected QuantLib::InterpolatedCurve<Interpolator> {\npublic:\n    //! \\name Constructors\n    //@{\n    //! Curve constructed from periods and prices. No conventions are applied in getting to a date from a period.\n    InterpolatedPriceCurve(const std::vector<QuantLib::Period>& tenors, const std::vector<QuantLib::Real>& prices,\n                           const QuantLib::DayCounter& dc, const QuantLib::Currency& currency,\n                           const Interpolator& interpolator = Interpolator());\n\n    //! Curve constructed from periods and quotes. No conventions are applied in getting to a date from a period.\n    InterpolatedPriceCurve(const std::vector<QuantLib::Period>& tenors,\n                           const std::vector<QuantLib::Handle<QuantLib::Quote> >& quotes,\n                           const QuantLib::DayCounter& dc, const QuantLib::Currency& currency,\n                           const Interpolator& interpolator = Interpolator());\n\n    //! Curve constructed from dates and prices\n    InterpolatedPriceCurve(const QuantLib::Date& referenceDate, const std::vector<QuantLib::Date>& dates,\n                           const std::vector<QuantLib::Real>& prices, const QuantLib::DayCounter& dc,\n                           const QuantLib::Currency& currency, const Interpolator& interpolator = Interpolator());\n\n    //! Curve constructed from dates and quotes\n    InterpolatedPriceCurve(const QuantLib::Date& referenceDate, const std::vector<QuantLib::Date>& dates,\n                           const std::vector<QuantLib::Handle<QuantLib::Quote> >& quotes,\n                           const QuantLib::DayCounter& dc, const QuantLib::Currency& currency,\n                           const Interpolator& interpolator = Interpolator());\n    //@}\n\n    //! \\name Observer interface\n    //@{\n    void update();\n    //@}\n\n    //! \\name LazyObject interface\n    //@{\n    void performCalculations() const;\n    //@}\n\n    //! \\name TermStructure interface\n    //@{\n    QuantLib::Date maxDate() const;\n    QuantLib::Time maxTime() const;\n    //@}\n\n    //! \\name PriceTermStructure interface\n    //@{\n    QuantLib::Time minTime() const;\n    std::vector<QuantLib::Date> pillarDates() const;\n    const QuantLib::Currency& currency() const { return currency_; }\n    //@}\n\n    //! \\name Inspectors\n    //@{\n    const std::vector<QuantLib::Time>& times() const { return this->times_; }\n    const std::vector<QuantLib::Real>& prices() const { return this->data_; }\n    //@}\n\nprotected:\n    //! \\name PriceTermStructure implementation\n    //@{\n    QuantLib::Real priceImpl(QuantLib::Time t) const;\n    //@}\n\nprivate:\n    const QuantLib::Currency currency_;\n    std::vector<QuantLib::Handle<QuantLib::Quote> > quotes_;\n    std::vector<QuantLib::Period> tenors_;\n    mutable std::vector<QuantLib::Date> dates_;\n\n    void initialise();\n    void populateDatesFromTenors() const;\n    void convertDatesToTimes();\n    void getPricesFromQuotes() const;\n};\n\ntemplate <class Interpolator>\nInterpolatedPriceCurve<Interpolator>::InterpolatedPriceCurve(const std::vector<QuantLib::Period>& tenors,\n                                                             const std::vector<QuantLib::Real>& prices,\n                                                             const QuantLib::DayCounter& dc,\n                                                             const QuantLib::Currency& currency,\n                                                             const Interpolator& interpolator)\n    : PriceTermStructure(0, QuantLib::NullCalendar(), dc), QuantLib::InterpolatedCurve<Interpolator>(\n                                                               std::vector<QuantLib::Time>(tenors.size()), prices,\n                                                               interpolator),\n      currency_(currency), tenors_(tenors), dates_(tenors.size()) {\n\n    QL_REQUIRE(boost::algorithm::is_sorted(tenors_.begin(), tenors_.end()), \"Tenors must be sorted\");\n    populateDatesFromTenors();\n    initialise();\n}\n\ntemplate <class Interpolator>\nInterpolatedPriceCurve<Interpolator>::InterpolatedPriceCurve(\n    const std::vector<QuantLib::Period>& tenors, const std::vector<QuantLib::Handle<QuantLib::Quote> >& quotes,\n    const QuantLib::DayCounter& dc, const QuantLib::Currency& currency, const Interpolator& interpolator)\n    : PriceTermStructure(0, QuantLib::NullCalendar(), dc), QuantLib::InterpolatedCurve<Interpolator>(\n                                                               std::vector<QuantLib::Time>(tenors.size()),\n                                                               std::vector<QuantLib::Real>(quotes.size()),\n                                                               interpolator),\n      currency_(currency), quotes_(quotes), tenors_(tenors), dates_(tenors.size()) {\n\n    QL_REQUIRE(boost::algorithm::is_sorted(tenors_.begin(), tenors_.end()), \"Tenors must be sorted\");\n    populateDatesFromTenors();\n    initialise();\n\n    // Observe the quotes\n    for (QuantLib::Size i = 0; i < quotes_.size(); ++i) {\n        registerWith(quotes[i]);\n    }\n}\n\ntemplate <class Interpolator>\nInterpolatedPriceCurve<Interpolator>::InterpolatedPriceCurve(const QuantLib::Date& referenceDate,\n                                                             const std::vector<QuantLib::Date>& dates,\n                                                             const std::vector<QuantLib::Real>& prices,\n                                                             const QuantLib::DayCounter& dc,\n                                                             const QuantLib::Currency& currency,\n                                                             const Interpolator& interpolator)\n    : PriceTermStructure(referenceDate, QuantLib::NullCalendar(), dc), QuantLib::InterpolatedCurve<Interpolator>(\n                                                                           std::vector<QuantLib::Time>(dates.size()),\n                                                                           prices, interpolator),\n      currency_(currency), dates_(dates) {\n\n    convertDatesToTimes();\n    initialise();\n}\n\ntemplate <class Interpolator>\nInterpolatedPriceCurve<Interpolator>::InterpolatedPriceCurve(\n    const QuantLib::Date& referenceDate, const std::vector<QuantLib::Date>& dates,\n    const std::vector<QuantLib::Handle<QuantLib::Quote> >& quotes, const QuantLib::DayCounter& dc,\n    const QuantLib::Currency& currency, const Interpolator& interpolator)\n    : PriceTermStructure(referenceDate, QuantLib::NullCalendar(), dc), QuantLib::InterpolatedCurve<Interpolator>(\n                                                                           std::vector<QuantLib::Time>(dates.size()),\n                                                                           std::vector<QuantLib::Real>(quotes.size()),\n                                                                           interpolator),\n      currency_(currency), quotes_(quotes), dates_(dates) {\n\n    convertDatesToTimes();\n    initialise();\n\n    // Observe the quotes\n    for (QuantLib::Size i = 0; i < quotes_.size(); ++i) {\n        registerWith(quotes[i]);\n    }\n}\n\ntemplate <class Interpolator> void InterpolatedPriceCurve<Interpolator>::update() {\n\n    QuantLib::LazyObject::update();\n\n    // TermStructure::update() update part\n    if (moving_) {\n        updated_ = false;\n    }\n}\n\ntemplate <class Interpolator> void InterpolatedPriceCurve<Interpolator>::performCalculations() const {\n    // Calculations need to be performed if the curve is tenor based\n    if (!tenors_.empty()) {\n        populateDatesFromTenors();\n        this->interpolation_.update();\n    }\n\n    // Calculations need to be performed if the curve depends on quotes\n    if (!quotes_.empty()) {\n        getPricesFromQuotes();\n        this->interpolation_.update();\n    }\n}\n\ntemplate <class Interpolator> QuantLib::Date InterpolatedPriceCurve<Interpolator>::maxDate() const {\n    calculate();\n    return dates_.back();\n}\n\ntemplate <class Interpolator> QuantLib::Time InterpolatedPriceCurve<Interpolator>::maxTime() const {\n    calculate();\n    return this->times_.back();\n}\n\ntemplate <class Interpolator> QuantLib::Time InterpolatedPriceCurve<Interpolator>::minTime() const {\n    calculate();\n    return this->times_.front();\n}\n\ntemplate <class Interpolator> std::vector<QuantLib::Date> InterpolatedPriceCurve<Interpolator>::pillarDates() const {\n    calculate();\n    return dates_;\n}\n\ntemplate <class Interpolator> QuantLib::Real InterpolatedPriceCurve<Interpolator>::priceImpl(QuantLib::Time t) const {\n    // Return interpolated/extrapolated price\n    calculate();\n    return this->interpolation_(t, true);\n}\n\ntemplate <class Interpolator> void InterpolatedPriceCurve<Interpolator>::initialise() {\n\n    QL_REQUIRE(this->data_.size() >= Interpolator::requiredPoints, \"not enough times for the interpolation method\");\n\n    // If we are quotes based, get prices from quotes\n    if (!quotes_.empty()) {\n        getPricesFromQuotes();\n    }\n\n    QL_REQUIRE(this->data_.size() == this->times_.size(), \"Number of times must equal number of prices\");\n\n    QuantLib::InterpolatedCurve<Interpolator>::setupInterpolation();\n    this->interpolation_.update();\n}\n\ntemplate <class Interpolator> void InterpolatedPriceCurve<Interpolator>::populateDatesFromTenors() const {\n    QuantLib::Date asof = QuantLib::Settings::instance().evaluationDate();\n    for (QuantLib::Size i = 0; i < dates_.size(); ++i) {\n        dates_[i] = asof + tenors_[i];\n        this->times_[i] = timeFromReference(dates_[i]);\n    }\n}\n\ntemplate <class Interpolator> void InterpolatedPriceCurve<Interpolator>::convertDatesToTimes() {\n\n    QL_REQUIRE(!dates_.empty(), \"Dates cannot be empty for InterpolatedPriceCurve\");\n    this->times_[0] = timeFromReference(dates_[0]);\n    for (QuantLib::Size i = 1; i < dates_.size(); ++i) {\n        QL_REQUIRE(dates_[i] > dates_[i - 1], \"invalid date (\" << dates_[i] << \", vs \" << dates_[i - 1] << \")\");\n        this->times_[i] = timeFromReference(dates_[i]);\n        QL_REQUIRE(!QuantLib::close(this->times_[i], this->times_[i - 1]), \"two dates correspond to the same time \"\n                                                                           \"under this curve's day count convention\");\n    }\n}\n\ntemplate <class Interpolator> void InterpolatedPriceCurve<Interpolator>::getPricesFromQuotes() const {\n\n    for (QuantLib::Size i = 0; i < quotes_.size(); ++i) {\n        QL_REQUIRE(!this->quotes_[i].empty(), \"price quote at index \" << i << \" is empty\");\n        this->data_[i] = quotes_[i]->value();\n    }\n}\n\n} // namespace QuantExt\n\n#endif\n", "meta": {"hexsha": "4ba773af025c2a49a11e450239ca1a682be370ae", "size": 12282, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "QuantExt/qle/termstructures/pricecurve.hpp", "max_stars_repo_name": "nvolfango/Engine", "max_stars_repo_head_hexsha": "a5ee0fc09d5a50ab36e50d55893b6e484d6e7004", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-03-30T17:24:17.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-30T17:24:17.000Z", "max_issues_repo_path": "QuantExt/qle/termstructures/pricecurve.hpp", "max_issues_repo_name": "zhangjiayin/Engine", "max_issues_repo_head_hexsha": "a5ee0fc09d5a50ab36e50d55893b6e484d6e7004", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "QuantExt/qle/termstructures/pricecurve.hpp", "max_forks_repo_name": "zhangjiayin/Engine", "max_forks_repo_head_hexsha": "a5ee0fc09d5a50ab36e50d55893b6e484d6e7004", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 42.0616438356, "max_line_length": 118, "alphanum_fraction": 0.6214785865, "num_tokens": 2629, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6723317123102956, "lm_q2_score": 0.519521321952093, "lm_q1q2_score": 0.34929065996975905}}
{"text": "/*\n * Copyright (c) 2012 Jonathan Perry\n * This code is released under the MIT license (see LICENSE file).\n */\n#include \"codes/strider/LayerManipulator.h\"\n\n#include <stdexcept>\n#include <stdint.h>\n#include <assert.h>\n#include <math.h>\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/matrix_proxy.hpp>\n#include <boost/numeric/ublas/matrix_expression.hpp>\n#include <boost/numeric/ublas/vector.hpp>\n#include <boost/numeric/ublas/vector_proxy.hpp>\n#include <boost/numeric/ublas/vector_expression.hpp>\n\nusing namespace boost::numeric::ublas;\n\nLayerManipulator::LayerManipulator(\n\t\tunsigned int layerLength,\n\t\tstd::complex<double> *matrixG,\n\t\tint rowsG,\n\t\tint colsG)\n:\tm_G(rowsG, colsG),\n \tm_symbols(rowsG, layerLength),\n \tm_fading(scalar_matrix<FadingMagnitude>(rowsG, layerLength, 1.0)),\n \tm_numFullPasses(0),\n \tm_nonFullPassLength(0)\n{\n\tfor(int row = 0; row < rowsG; row++) {\n\t\tfor(int col = 0; col < colsG; col++) {\n\t\t\tm_G(row, col) = *(matrixG++);\n\t\t}\n\t}\n}\n\n\nvoid LayerManipulator::setSymbols(\n\t\tunsigned int numFullPasses,\n\t\tunsigned int nonFullPassLength,\n\t\tconst boost_col_cmat & symbols)\n{\n\tconst unsigned int passLength = m_symbols.size2();\n\tm_numFullPasses = numFullPasses;\n\tm_nonFullPassLength = nonFullPassLength;\n\n\t// Copy short columns\n\tsubrange(m_symbols, 0, m_numFullPasses,\n\t\t\t\t\t\tm_nonFullPassLength, passLength) =\n\t\tsubrange(symbols, 0, m_numFullPasses,\n\t\t\t\t\t\t  m_nonFullPassLength, passLength);\n\n\tif(m_nonFullPassLength > 0) {\n\t\t// Copy long columns\n\t\tsubrange(m_symbols, 0, m_numFullPasses+1, 0, m_nonFullPassLength) =\n\t\t\tsubrange(symbols, 0, m_numFullPasses+1, 0, m_nonFullPassLength);\n\t}\n}\n\n\nvoid LayerManipulator::setSymbols(\n\t\tunsigned int numFullPasses,\n\t\tunsigned int nonFullPassLength,\n\t\tconst boost_col_cmat & symbols,\n\t\tconst boost_col_mat & fading)\n{\n\t// Set the symbols\n\tsetSymbols(numFullPasses, nonFullPassLength, symbols);\n\n\t// Set the fading coefficients\n\t// Copy short columns\n\tconst unsigned int passLength = m_symbols.size2();\n\tsubrange(m_fading, 0, m_numFullPasses,\n\t\t\t\t\t\tm_nonFullPassLength, passLength) =\n\t\tsubrange(fading, 0, m_numFullPasses,\n\t\t\t\t\t\t  m_nonFullPassLength, passLength);\n\n\tif(m_nonFullPassLength > 0) {\n\t\t// Copy long columns\n\t\tsubrange(m_fading, 0, m_numFullPasses+1, 0, m_nonFullPassLength) =\n\t\t\tsubrange(fading, 0, m_numFullPasses+1, 0, m_nonFullPassLength);\n\t}\n}\n\n\n\nvoid LayerManipulator::maximalRatioCombining(\n\t\tunsigned int layerInd,\n\t\tfloat externalSnr,\n\t\tboost_cvec & combined,\n\t\tboost_vec & combinedScale)\n{\n\tconst unsigned int passLength = m_symbols.size2();\n\n\tmaximalRatioCombiningPartial(layerInd,\n\t                             externalSnr,\n\t                             combined,\n\t                             combinedScale,\n\t                             m_nonFullPassLength,\n\t                             passLength,\n\t                             m_numFullPasses);\n\n\tif(m_nonFullPassLength > 0) {\n\t\t// We have symbols in a non-full pass, need to combine them as well\n\t\tmaximalRatioCombiningPartial(layerInd,\n\t\t                             externalSnr,\n\t\t                             combined,\n\t\t                             combinedScale,\n\t\t                             0,\n\t\t                             m_nonFullPassLength,\n\t\t                             m_numFullPasses + 1);\n\t}\n}\n\nvoid LayerManipulator::subtractLayer(\n\t\tunsigned int layerInd,\n\t\tconst std::vector<ComplexSymbol> & symbols)\n{\n\tif(symbols.size() != m_symbols.size2()) {\n\t\tthrow(std::runtime_error(\"Number of symbols to subtract should be equal to a layer's length\"));\n\t}\n\n\t// full passes\n\tfor(unsigned int i = m_nonFullPassLength; i < m_symbols.size2(); i++) {\n\t\tComplexNumber sym = symbols[i];\n\t\tfor(unsigned int pass = 0; pass < m_numFullPasses; pass++) {\n\t\t\tm_symbols(pass,i) -= sym * m_G(pass, layerInd) * m_fading(pass,i);\n\t\t}\n\t}\n\n\t// non full passes\n\tfor(unsigned int i = 0; i < m_nonFullPassLength; i++) {\n\t\tComplexNumber sym = symbols[i];\n\t\tfor(unsigned int pass = 0; pass < m_numFullPasses + 1; pass++) {\n\t\t\tm_symbols(pass,i) -= sym * m_G(pass, layerInd) * m_fading(pass,i);\n\t\t}\n\t}\n}\n\nvoid LayerManipulator::maximalRatioCombiningPartial(unsigned int layerInd,\n\t\t\t\t\t\t\t\t\t\t\t\t\tfloat externalSnr,\n\t\t\t\t\t\t\t\t\t\t\t\t\tboost_cvec & combined,\n\t\t\t\t\t\t\t\t\t\t\t\t\tboost_vec & combinedScale,\n\t\t\t\t\t\t\t\t\t\t\t\t\tunsigned int beginIndex,\n\t\t\t\t\t\t\t\t\t\t\t\t\tunsigned int endIndex,\n\t\t\t\t\t\t\t\t\t\t\t\t\tunsigned int numPasses)\n{\n\tboost_double_vec fading(\n\t\t\tmatrix_vector_slice<boost_col_mat> (m_fading,\n\t\t\t\t\t\t\t\t\t\t\t\tslice(0,1,numPasses),\n\t\t\t\t\t\t\t\t\t\t\t\tslice(beginIndex,0,numPasses)));\n\tuint32_t fadingIndex = beginIndex;\n\n\tfor(uint32_t i = beginIndex + 1; i < endIndex; i++) {\n\t\tmatrix_vector_slice<boost_col_mat> thisFading(\n\t\t\t\t\t\t\t\t\t\t\t\tm_fading,\n\t\t\t\t\t\t\t\t\t\t\t\tslice(0,1,numPasses),\n\t\t\t\t\t\t\t\t\t\t\t\tslice(i,0,numPasses));\n\t\tfor(uint32_t j = 0; j < numPasses; j++) {\n\t\t\tif(thisFading[j] != fading[j]) {\n\t\t\t\t// Run maximal ratio combining on previous sequence of indices,\n\t\t\t\t//  fadingIndex, fadingIndex+1, .., i-1\n\t\t\t\tmaximalRatioCombiningSameFading(layerInd,\n\t\t\t\t\t\t\t\t\t\t\t\texternalSnr,\n\t\t\t\t\t\t\t\t\t\t\t\tfading,\n\t\t\t\t\t\t\t\t\t\t\t\tcombined,\n\t\t\t\t\t\t\t\t\t\t\t\tcombinedScale,\n\t\t\t\t\t\t\t\t\t\t\t\tfadingIndex,\n\t\t\t\t\t\t\t\t\t\t\t\ti,\n\t\t\t\t\t\t\t\t\t\t\t\tnumPasses);\n\t\t\t\t// Update state so the fading information for index i will be cached\n\t\t\t\tfading = thisFading;\n\t\t\t\tfadingIndex = i;\n\n\t\t\t\t// no need to check more indices\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\n\t// We finished the for loop, there is still another combining to do\n\tmaximalRatioCombiningSameFading(layerInd,\n\t\t\t\t\t\t\t\t    externalSnr,\n\t\t\t\t\t\t\t\t    fading,\n\t\t\t\t\t\t\t\t    combined,\n\t\t\t\t\t\t\t\t    combinedScale,\n\t\t\t\t\t\t\t\t    fadingIndex,\n\t\t\t\t\t\t\t\t    endIndex,\n\t\t\t\t\t\t\t\t    numPasses);\n}\n\nvoid LayerManipulator::maximalRatioCombiningSameFading(\n\t\tunsigned int layerInd,\n\t\tfloat externalSnr,\n\t\tconst boost_double_vec & fading,\n\t\tboost_cvec & combined,\n\t\tboost_vec & combinedScale,\n\t\tunsigned int beginIndex,\n\t\tunsigned int endIndex,\n\t\tunsigned int numPasses)\n{\n\t// debug print\n//\tcout << \"MRC indices [\" << beginIndex << \", \" << endIndex << \")\"\n//\t\t\t<< \" num passes=\" << numPasses << endl;\n\n\t// Stores the interference from other layers\n\tboost_vec interference;\n\n\t// Weights to combine the passes coherently\n\tboost_cvec weights;\n\n\t// Get the internal interference power for each of the layers\n\tgetInterference(layerInd, numPasses, interference);\n\n\t// Calculate normalized weights\n\tfloat signalPower = getWeights(layerInd,\n\t\t\t\t\t\t\t\t\texternalSnr,\n\t\t\t\t\t\t\t\t\tinterference,\n\t\t\t\t\t\t\t\t\tfading,\n\t\t\t\t\t\t\t\t\tweights);\n\n\tif (signalPower == 0) {\n\t\tsubrange(combined, beginIndex, endIndex) =\n\t\t\t\tscalar_vector<float>(endIndex - beginIndex, 0);\n\t\tsubrange(combinedScale, beginIndex, endIndex) =\n\t\t\t\tscalar_vector<float>(endIndex - beginIndex, 0);\n\t} else {\n\t\t// Calculate SNRs of combined signal after coherent combining of\n\t\t// interference\n\t\tfloat interferencePower = getCoherentInterference(layerInd, weights, fading);\n\n\t\t// Calculate normalized noise power\n\t\tfloat noisePower = externalSnr * real(inner_prod(weights, conj(weights)));\n\n\t\t// Scaling factor makes the noise+interference be of power externalSnr\n\t\tfloat noiseNormalizationFactor =\n\t\t\t\tsqrt(externalSnr / (noisePower + interferencePower));\n\t\tassert(isfinite(noiseNormalizationFactor));\n\n\t\t// combinedScale is the total scaling from combinedScalingFactor and\n\t\t// the weights\n\t\tfloat scale = sqrt(signalPower) * noiseNormalizationFactor;\n\t\tassert(isfinite(scale));\n\t\tsubrange(combinedScale, beginIndex, endIndex) =\n\t\t\t\tscalar_vector<float>(endIndex - beginIndex, scale);\n\n\n\t\t// Combine the different passes into one coherent reception\n\t\tsubrange(combined, beginIndex, endIndex) =\n\t\t\t\t   double(noiseNormalizationFactor) *\n\t\t\t\t   prod(weights,\n\t\t\t\t\t\tsubrange(m_symbols, 0, numPasses,\n\t\t\t\t\t\t\t\t\t\t\tbeginIndex, endIndex));\n\t\t// debug print\n//\t\tcout << \"combined_scale=\" << scale\n//\t\t\t << \" signal_power=\" << signalPower\n//\t\t\t << \" interference_power=\" << interferencePower\n//\t\t\t << \" noise_norm=\" << noiseNormalizationFactor\n//\t\t\t\t<< endl;\n\n\t}\n}\n\nvoid LayerManipulator::getInterference(\tunsigned int layerInd,\n\t\t\t\t\t\t\t\t\t\tunsigned int numPasses,\n\t\t\t\t\t\t\t\t\t\tboost_vec & interference)\n{\n\tmatrix_range<boost_col_cmat> coeffs(\n\t\t\tsubrange(m_G, 0, numPasses, layerInd+1, m_G.size2()));\n\n\tif(layerInd != m_G.size2() - 1) {\n\t\tinterference =\n\t\t\treal(\n\t\t\t\tprod(element_prod(coeffs, conj(coeffs)),\n\t\t\t\t\t scalar_vector<ComplexBaseType>(m_G.size2() - (layerInd + 1), 1.0f)));\n\t} else {\n\t\tinterference = scalar_vector<float>(numPasses, 0);\n\t}\n}\n\n\nfloat LayerManipulator::getWeights(\n\t\tunsigned int layerInd,\n\t\tfloat noise,\n\t\tconst boost_vec & interference,\n\t\tconst boost_double_vec & fading,\n\t\tboost_cvec & weights)\n{\n\tconst unsigned int num_passes = interference.size();\n\n\tmatrix_vector_slice<boost_col_cmat> layerCoeff(m_G,\n\t\t\t\t\t\t\t\t\t\t\t\t   slice(0,1,num_passes),\n\t\t\t\t\t\t\t\t\t\t\t\t   slice(layerInd,0,num_passes));\n\t// Calculate un-normalized weights\n\tweights = element_div(element_prod(conj(layerCoeff), fading),\n\t\t\t\t\t\t  ( element_prod(interference, element_prod(fading,fading))\n\t\t\t\t\t\t   + scalar_vector<ComplexBaseType>(num_passes,noise)));\n\n\tfloat scale = real(inner_prod(weights, element_prod(layerCoeff, fading)));\n\treturn scale*scale;\n}\n\nfloat LayerManipulator::getCoherentInterference(\n\t\tunsigned int layerInd,\n\t\tconst boost_cvec & weights,\n\t\tconst boost_double_vec & fading)\n{\n\tconst unsigned int num_passes = weights.size();\n\n\t// Get interference power if not on the last layer\n\tfloat interferencePower = 0;\n\tif(layerInd != m_G.size2() - 1) {\n\t\tboost_cvec layerInterference =\n\t\t\tprod(element_prod(weights,fading),\n\t\t\t\t subrange(m_G, 0, num_passes, layerInd+1, m_G.size2()));\n\n\t\tinterferencePower = real(inner_prod(layerInterference,\n\t\t\t\t\t\t\t\t\t\t\tconj(layerInterference)));\n\t}\n\n\treturn interferencePower;\n}\n\n\n\n", "meta": {"hexsha": "8ab3de195f08522e429d8f023928f133fe0d35d6", "size": 9636, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/codes/strider/LayerManipulator.cpp", "max_stars_repo_name": "yonch/wireless", "max_stars_repo_head_hexsha": "5e5a081fcf3cd49d901f25db6c4c1fabbfc921d5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 29.0, "max_stars_repo_stars_event_min_datetime": "2015-03-11T04:54:01.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-20T06:07:59.000Z", "max_issues_repo_path": "src/codes/strider/LayerManipulator.cpp", "max_issues_repo_name": "darksidelemm/wireless", "max_issues_repo_head_hexsha": "5e5a081fcf3cd49d901f25db6c4c1fabbfc921d5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/codes/strider/LayerManipulator.cpp", "max_forks_repo_name": "darksidelemm/wireless", "max_forks_repo_head_hexsha": "5e5a081fcf3cd49d901f25db6c4c1fabbfc921d5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 16.0, "max_forks_repo_forks_event_min_datetime": "2015-01-28T18:58:33.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-29T02:00:24.000Z", "avg_line_length": 29.4678899083, "max_line_length": 97, "alphanum_fraction": 0.6745537567, "num_tokens": 2470, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6825737344123242, "lm_q2_score": 0.5117166047041654, "lm_q1q2_score": 0.3492843138337172}}
{"text": "#ifndef _LDAPLUSPLUS_OPTIMIZATION_GRADIENT_DESCENT_HPP_\n#define _LDAPLUSPLUS_OPTIMIZATION_GRADIENT_DESCENT_HPP_\n\n#include <functional>\n#include <memory>\n\n#include <Eigen/Core>\n\nnamespace ldaplusplus {\nnamespace optimization {\n\n\n/**\n * LineSearch is an interface that is meant to be used to update the parameter\n * x0 in the direction 'direction' by (probably) performing a line search for\n * the best value.\n */\ntemplate <typename ProblemType, typename ParameterType>\nclass LineSearch\n{\n    public:\n        typedef typename ParameterType::Scalar Scalar;\n\n        /**\n         * Search for a good enough function value in the direction given and\n         * the function given.\n         *\n         * This function changes its parameter x0 which is passed by reference.\n         *\n         * @param  problem   The function to be minimized\n         * @param  x0        The improved position (passed by reference)\n         * @param  grad_x0   The gradient at the initial x0\n         * @param  direction The direction of search which can be different than\n         *                  the gradient to account for Newton methods\n         * @return The function value at the final x0\n         */\n        virtual Scalar search(\n            const ProblemType &problem,\n            Eigen::Ref<ParameterType> x0,\n            const ParameterType &grad_x0,\n            const ParameterType &direction\n        ) = 0;\n\n        virtual ~LineSearch(){};\n};\n\n\n/**\n * ConstantLineSearch simply updates the parameter by a costant factor of the\n * direction performing no line search actually.\n */\ntemplate <typename ProblemType, typename ParameterType>\nclass ConstantLineSearch : public LineSearch<ProblemType, ParameterType>\n{\n    public:\n        typedef typename ParameterType::Scalar Scalar;\n\n        /**\n         * @param alpha The amount to move towards the search direction\n         */\n        ConstantLineSearch(Scalar alpha) : alpha_(alpha) {}\n\n        Scalar search(\n            const ProblemType &problem,\n            Eigen::Ref<ParameterType> x0,\n            const ParameterType &grad_x0,\n            const ParameterType &direction\n        ) {\n            x0 -= alpha_ * direction;\n\n            return problem.value(x0);\n        }\n\n    private:\n        Scalar alpha_;\n};\n\n/**\n * Armijo line search is a simple backtracking line search where the Armijo\n * condition is required.\n *\n * The Armijo condition is the following if \\f$p_k\\f$ is the negative direction and\n * \\f$g_k\\f$ the gradient. In Armijo line search we search the largest \\f$a_k\n * \\in \\{\\tau^n \\mid n \\in \\{0\\} \\cup \\mathbb{N}\\}\\f$ for which the Armijo\n * condition stands.\n *\n *  \\f[\n *      f(x_k - a_k p_k) \\leq f(x_k) - a_k b g_k^T p_k\n *  \\f]\n *\n *  \\f$f(x_k) - a_k b g_k^T p_k\\f$ is a linear approximation of the function at\n *  \\f$x_k\\f$ (scaled by \\f$b\\f$) that we assume to be the upper bound for the\n *  decrease.\n *\n *  In all the above \\f$p_k\\f$ is assumed to be of **unit length**.\n *\n *  See [Wolfe Conditions](https://en.wikipedia.org/wiki/Wolfe_conditions).\n */\ntemplate <typename ProblemType, typename ParameterType>\nclass ArmijoLineSearch : public LineSearch<ProblemType, ParameterType>\n{\n    public:\n        typedef typename ParameterType::Scalar Scalar;\n\n        /**\n         * @param beta The amount of scaling to do the linear decrease\n         * @param tau  Defines the set of \\f$a_k\\f$ to try in the line search\n         */\n        ArmijoLineSearch(Scalar beta=0.001, Scalar tau=0.5) : beta_(beta),\n                                                              tau_(tau)\n        {}\n\n        Scalar search(\n            const ProblemType &problem,\n            Eigen::Ref<ParameterType> x0,\n            const ParameterType &grad_x0,\n            const ParameterType &direction\n        ) {\n            ParameterType x_copy(x0.rows(), x0.cols());\n            Scalar value_x0 = problem.value(x0);\n            Scalar decrease = beta_ * (grad_x0.array() * direction.array()).sum();\n            Scalar value = value_x0;\n            Scalar a = 1.0/tau_;\n\n            while (value > value_x0 - a * decrease) {\n                a *= tau_;\n                x_copy = x0 - a * direction;\n                value = problem.value(x_copy);\n            }\n\n            x0 -= a * direction;\n\n            return value;\n        }\n\n    private:\n        Scalar beta_;\n        Scalar tau_;\n};\n\n\n/**\n * A very simple implementation of batch gradient descent.\n *\n * Given a problem, a line search and a starting point it performs the\n * following simple iteration.\n *\n * 1. Repeat the following until convergence\n * 2. Compute the gradient\n * 3. Search in the direction of the gradient for sufficient decrease\n *\n * Convergence is decided by another part of the program through injection of a\n * callback.\n *\n * TODO: Maybe bind the problem type through an interface\n */\ntemplate <typename ProblemType, typename ParameterType>\nclass GradientDescent\n{\n    public:\n        typedef typename ParameterType::Scalar Scalar;\n\n        /**\n         * @param line_search A line search method\n         * @param progress    A callback that decides when the optimization has\n         *                    ended; it can also be used to get informed about\n         *                    the progress of the optimization\n         */\n        GradientDescent(\n            std::shared_ptr<LineSearch<ProblemType, ParameterType> > line_search,\n            std::function<bool(Scalar, Scalar, size_t)> progress\n        ) : line_search_(line_search),\n            progress_(progress)\n        {}\n\n        /**\n         * Minimize the function defined in the 'problem' argument.\n         *\n         * The 'problem' argument should implement the functions value() and\n         * gradient() in order to be used with the GradientDescent class.\n         *\n         * @param problem The function being minimized\n         * @param x0      The initial position during our minimization (it will\n         *                be overwritten with the optimal position)\n         */\n        void minimize(const ProblemType &problem, Eigen::Ref<ParameterType> x0) {\n            // allocate memory for the gradient\n            ParameterType grad(x0.rows(), x0.cols());\n\n            // Keep the value in this variable\n            Scalar value = problem.value(x0);\n\n            // And the iterations in this one\n            size_t iterations = 0;\n\n            // Whether we stop or not is decided by someone else\n            while (progress_(value, grad.template lpNorm<Eigen::Infinity>(), iterations++)) {\n                problem.gradient(x0, grad);\n                value = line_search_->search(problem, x0, grad, grad);\n            }\n        }\n\n    private:\n        std::shared_ptr<LineSearch<ProblemType, ParameterType> > line_search_;\n        std::function<bool(Scalar, Scalar, size_t)> progress_;\n};\n\n\n}  // namespace optimization\n}  // namespace ldaplusplus\n\n#endif // _LDAPLUSPLUS_OPTIMIZATION_GRADIENT_DESCENT_HPP_\n", "meta": {"hexsha": "e4a810761d7b7874a0784d212d48b83faeefb722", "size": 6919, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/ldaplusplus/optimization/GradientDescent.hpp", "max_stars_repo_name": "angeloskath/supervised-lda", "max_stars_repo_head_hexsha": "fe3a39bb0d6c7d0c2a33f069440869ad70774da8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 22.0, "max_stars_repo_stars_event_min_datetime": "2017-05-25T11:59:02.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-30T08:51:41.000Z", "max_issues_repo_path": "include/ldaplusplus/optimization/GradientDescent.hpp", "max_issues_repo_name": "angeloskath/supervised-lda", "max_issues_repo_head_hexsha": "fe3a39bb0d6c7d0c2a33f069440869ad70774da8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 22.0, "max_issues_repo_issues_event_min_datetime": "2016-06-30T15:51:18.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-06T10:43:16.000Z", "max_forks_repo_path": "include/ldaplusplus/optimization/GradientDescent.hpp", "max_forks_repo_name": "angeloskath/supervised-lda", "max_forks_repo_head_hexsha": "fe3a39bb0d6c7d0c2a33f069440869ad70774da8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2017-09-28T14:58:01.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-21T14:22:38.000Z", "avg_line_length": 32.4835680751, "max_line_length": 93, "alphanum_fraction": 0.6146842029, "num_tokens": 1540, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6297746074044134, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.34919141938779563}}
{"text": "/*\n * Copyright (c) 2013, Christian Gehring, Hannes Sommer, Paul Furgale, Remo Diethelm\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *     * Redistributions of source code must retain the above copyright\n *       notice, this list of conditions and the following disclaimer.\n *     * Redistributions in binary form must reproduce the above copyright\n *       notice, this list of conditions and the following disclaimer in the\n *       documentation and/or other materials provided with the distribution.\n *     * Neither the name of the Autonomous Systems Lab, ETH Zurich nor the\n *       names of its contributors may be used to endorse or promote products\n *       derived from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL Christian Gehring, Hannes Sommer, Paul Furgale,\n * Remo Diethelm BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,\n * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE\n * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n*/\n\n#pragma once\n\n#include <Eigen/Core>\n\n#include \"kindr/math/LinearAlgebra.hpp\"\n#include \"kindr/common/common.hpp\"\n#include \"kindr/common/assert_macros.hpp\"\n#include \"kindr/common/assert_macros_eigen.hpp\"\n#include \"kindr/rotations/RotationDiffBase.hpp\"\n#include \"kindr/rotations/Rotation.hpp\"\n\nnamespace kindr {\n\n/*! \\class EulerAnglesZyxDiff\n * \\brief Implementation of time derivatives of Euler angles (Z,Y',X'' / yaw,pitch,roll) based on Eigen::Matrix<Scalar, 3, 1>\n *\n * The following two typedefs are provided for convenience:\n *   - EulerAnglesZyxDiffAD for primitive type double\n *   - EulerAnglesZyxDoffAF for primitive type float\n * \\tparam PrimType_ the primitive type of the data (double or float)\n * \\ingroup rotations\n */\ntemplate<typename PrimType_>\nclass EulerAnglesZyxDiff : public RotationDiffBase<EulerAnglesZyxDiff<PrimType_>> {\n private:\n  /*! \\brief The base type.\n   */\n  typedef Eigen::Matrix<PrimType_, 3, 1> Base;\n\n  /*! \\brief data container [yaw; pitch; roll]\n   */\n  Base zyxDiff_;\n\n public:\n  /*! \\brief The implementation type.\n   *  The implementation type is always an Eigen object.\n   */\n  typedef Base Implementation;\n\n  /*! \\brief The primitive type.\n   *  Float/Double\n   */\n  typedef PrimType_ Scalar;\n\n  /*! \\brief Default constructor.\n   */\n  EulerAnglesZyxDiff()\n    : zyxDiff_(Base::Zero()) {\n  }\n\n  /*! \\brief Constructor using three scalars.\n   *  \\param yaw      time derivative of first rotation angle around Z axis\n   *  \\param pitch    time derivative of second rotation angle around Y' axis\n   *  \\param roll     time derivative of third rotation angle around X'' axis\n   */\n  EulerAnglesZyxDiff(Scalar yaw, Scalar pitch, Scalar roll)\n    : zyxDiff_(yaw,pitch,roll) {\n  }\n\n  /*! \\brief Constructor using a time derivative with a different parameterization\n   *\n   * \\param rotation  rotation\n   * \\param other     other time derivative\n   */\n  template<typename RotationDerived_, typename OtherDerived_>\n  inline explicit EulerAnglesZyxDiff(const RotationBase<RotationDerived_>& rotation, const RotationDiffBase<OtherDerived_>& other)\n    : zyxDiff_(internal::RotationDiffConversionTraits<EulerAnglesZyxDiff, OtherDerived_, RotationDerived_>::convert(rotation.derived(), other.derived()).toImplementation()){\n  }\n\n  /*! \\brief Cast to another representation of the time derivative of a rotation\n   *  \\param other   other rotation\n   *  \\returns reference\n   */\n  template<typename OtherDerived_, typename RotationDerived_>\n  OtherDerived_ cast(const RotationBase<RotationDerived_>& rotation) const {\n    return internal::RotationDiffConversionTraits<OtherDerived_, EulerAnglesZyxDiff, RotationDerived_>::convert(rotation.derived(), *this);\n  }\n\n  /*! \\brief Constructor using Eigen::Matrix.\n   *  \\param other   Eigen::Matrix<Scalar, 3, 1> [yaw; pitch; roll]\n   */\n  explicit EulerAnglesZyxDiff(const Base& other)\n    : zyxDiff_(other) {\n  }\n\n  /*! \\brief Cast to the implementation type.\n   *  \\returns the implementation for direct manipulation (recommended only for advanced users)\n   */\n  inline Base& toImplementation() {\n    return static_cast<Base&>(zyxDiff_);\n  }\n\n  /*! \\brief Cast to the implementation type.\n   *  \\returns the implementation for direct manipulation (recommended only for advanced users)\n   */\n  inline const Base& toImplementation() const {\n    return static_cast<const Base&>(zyxDiff_);\n  }\n\n\n  inline Base& vector() {\n    return toImplementation();\n  }\n\n  inline const Base& vector() const {\n    return toImplementation();\n  }\n\n\n  /*! \\brief Reading access to time derivative of yaw (Z) angle.\n    *  \\returns time derivative of yaw angle (scalar) with reading access\n    */\n   inline Scalar yaw() const {\n     return toImplementation()(0);\n   }\n\n   /*! \\brief Reading access to time derivative of pitch (Y') angle.\n    *  \\returns time derivative of pitch angle (scalar) with reading access\n    */\n   inline Scalar pitch() const {\n     return toImplementation()(1);\n   }\n\n   /*! \\brief Reading access to time derivative of roll (X'') angle.\n    *  \\returns time derivative of roll angle (scalar) with reading access\n    */\n   inline Scalar roll() const {\n     return toImplementation()(2);\n   }\n\n   /*! \\brief Writing access to time derivative of yaw (Z) angle.\n    *  \\returns time derivative of yaw angle (scalar) with writing access\n    */\n   inline Scalar& yaw() {\n     return toImplementation()(0);\n   }\n\n   /*! \\brief Writing access to time derivative of pitch (Y') angle.\n    *  \\returns time derivative of pitch angle (scalar) with writing access\n    */\n   inline Scalar& pitch() {\n     return toImplementation()(1);\n   }\n\n   /*! \\brief Writing access to time derivative of roll (X'') angle.\n    *  \\returns time derivative of roll angle (scalar) with writing access\n    */\n   inline Scalar& roll() {\n     return toImplementation()(2);\n   }\n\n   /*! \\brief Reading access to time derivative of yaw (Z) angle.\n    *  \\returns time derivative of yaw angle (scalar) with reading access\n    */\n   inline Scalar z() const {\n     return toImplementation()(0);\n   }\n\n   /*! \\brief Reading access to time derivative of pitch (Y') angle.\n    *  \\returns time derivative of pitch angle (scalar) with reading access\n    */\n   inline Scalar y() const {\n     return toImplementation()(1);\n   }\n\n   /*! \\brief Reading access to time derivative of roll (X'') angle.\n    *  \\returns time derivative of roll angle (scalar) with reading access\n    */\n   inline Scalar x() const {\n     return toImplementation()(2);\n   }\n\n   /*! \\brief Writing access to time derivative of yaw (Z) angle.\n    *  \\returns time derivative of yaw angle (scalar) with writing access\n    */\n   inline Scalar& z() {\n     return toImplementation()(0);\n   }\n\n   /*! \\brief Writing access to time derivative of pitch (Y') angle.\n    *  \\returns time derivative of pitch angle (scalar) with writing access\n    */\n   inline Scalar& y() {\n     return toImplementation()(1);\n   }\n\n   /*! \\brief Writing access to time derivative of roll (X'') angle.\n    *  \\returns time derivative of roll angle (scalar) with writing access\n    */\n   inline Scalar& x() {\n     return toImplementation()(2);\n   }\n\n   /*! \\brief Sets all time derivatives to zero.\n    *  \\returns reference\n    */\n   EulerAnglesZyxDiff& setZero() {\n     this->toImplementation().setZero();\n     return *this;\n   }\n\n   /*! \\brief Get zero element.\n    *  \\returns zero element\n    */\n   static EulerAnglesZyxDiff Zero() {\n     return EulerAnglesZyxDiff(Base::Zero());\n   }\n\n   /*! \\brief Addition of two angular velocities.\n    */\n   using RotationDiffBase<EulerAnglesZyxDiff<PrimType_>>::operator+; // otherwise ambiguous EulerAnglesDiffBase and Eigen\n\n   /*! \\brief Subtraction of two angular velocities.\n    */\n   using RotationDiffBase<EulerAnglesZyxDiff<PrimType_>>::operator-; // otherwise ambiguous EulerAnglesDiffBase and Eigen\n\n\n   /*! \\brief Used for printing the object with std::cout.\n    *\n    *   Prints: yaw pitch roll\n    *  \\returns std::stream object\n    */\n   friend std::ostream& operator << (std::ostream& out, const EulerAnglesZyxDiff& diff) {\n     out << diff.toImplementation().transpose();\n     return out;\n   }\n};\n\n//! \\brief Time derivative of Euler angles with z-y-x convention and primitive type double\ntypedef EulerAnglesZyxDiff<double> EulerAnglesZyxDiffPD;\n//! \\brief Time derivative of Euler angles with z-y-x convention and primitive type float\ntypedef EulerAnglesZyxDiff<float> EulerAnglesZyxDiffPF;\n//! \\brief Time derivative of Euler angles with z-y-x convention and primitive type double\ntypedef EulerAnglesZyxDiff<double> EulerAnglesZyxDiffD;\n//! \\brief Time derivative of Euler angles with z-y-x convention and primitive type float\ntypedef EulerAnglesZyxDiff<float> EulerAnglesZyxDiffF;\n\n\n\nnamespace internal {\n\n\ntemplate<typename PrimType_>\nclass RotationDiffConversionTraits<EulerAnglesZyxDiff<PrimType_>, LocalAngularVelocity<PrimType_>, EulerAnglesZyx<PrimType_>> {\n public:\n  inline static EulerAnglesZyxDiff<PrimType_> convert(const EulerAnglesZyx<PrimType_>& eulerAngles, const LocalAngularVelocity<PrimType_>& angularVelocity) {\n    return EulerAnglesZyxDiff<PrimType_>(eulerAngles.getMappingFromLocalAngularVelocityToDiff()*angularVelocity.vector());\n  }\n};\n\n\n} // namespace internal\n} // namespace kindr\n\n", "meta": {"hexsha": "f3e1cb98d5bf07369782e885a918388c3704febe", "size": 9945, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/kindr/rotations/EulerAnglesZyxDiff.hpp", "max_stars_repo_name": "mcx/kindr", "max_stars_repo_head_hexsha": "761303a6d82780b3e476473ba66a0c2abc623179", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 289.0, "max_stars_repo_stars_event_min_datetime": "2018-08-06T15:57:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T06:52:43.000Z", "max_issues_repo_path": "include/kindr/rotations/EulerAnglesZyxDiff.hpp", "max_issues_repo_name": "mcx/kindr", "max_issues_repo_head_hexsha": "761303a6d82780b3e476473ba66a0c2abc623179", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 15.0, "max_issues_repo_issues_event_min_datetime": "2018-08-22T09:58:25.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-26T06:32:14.000Z", "max_forks_repo_path": "include/kindr/rotations/EulerAnglesZyxDiff.hpp", "max_forks_repo_name": "mcx/kindr", "max_forks_repo_head_hexsha": "761303a6d82780b3e476473ba66a0c2abc623179", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 106.0, "max_forks_repo_forks_event_min_datetime": "2018-08-24T08:39:49.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-28T15:17:37.000Z", "avg_line_length": 35.1413427562, "max_line_length": 173, "alphanum_fraction": 0.7127199598, "num_tokens": 2340, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6297746074044134, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.34919141938779563}}
{"text": "\n#include <algorithm>\n#include <boost/foreach.hpp>\n\n#include \"constants.hpp\"\n#include \"fragment_model.hpp\"\n#include \"fragbias.hpp\"\n\n\nFragBias::FragBias(FragmentModel* fm)\n{\n    // lengths used for interpolation\n    const pos_t lengths[] = {\n        25, 50, 75, 100, 125, 150, 175, 200, 225, 250, 275, 300,\n        325, 350, 375, 400, 425, 450, 475, 500, 550, 600, 650, 700,\n        750, 800, 850, 900, 950, 1000, 1100, 1200, 1300, 1500, 1600,\n        1700, 1800, 1900, 2000, 2500, 3000, 3500, 4000, 4500, 5000\n    };\n\n    this->lengths.resize(sizeof(lengths) / sizeof(pos_t));\n    std::copy(lengths, lengths + this->lengths.size(), this->lengths.begin());\n\n    // assumed fragmentation probability\n    this->fm = fm;\n    p = (1.0 / fm->frag_len_med()) / 2.0;\n    double omp = 1.0 - p;\n    max_non_frag_run = std::max<pos_t>(1, lround(log(1e-5) / log(omp)));\n\n    non_frag_run_pr_sum.resize(max_non_frag_run);\n    non_frag_run_pr.resize(max_non_frag_run);\n\n    non_frag_run_pr[0] = 1.0;\n    non_frag_run_pr_sum[0] = 1.0;\n    for (pos_t m = 1; m < max_non_frag_run; ++m) {\n        non_frag_run_pr_sum[m] = non_frag_run_pr_sum[m - 1] + pow(omp, m - 1) / (double) m;\n        non_frag_run_pr[m] = pow(omp, m - 1);\n    }\n\n    BOOST_FOREACH (pos_t l, this->lengths) {\n        std::vector<float> fb(l);\n        compute(&fb.at(0), 0, l, l);\n        bias.push_back(fb);\n    }\n}\n\n\nvoid FragBias::compute(float* out, pos_t from, pos_t to, pos_t l)\n{\n        // Four cases:\n        for (pos_t u = from; u < to; ++u) out[u] = 0.0;\n\n#if 0\n        // enrichment of end positions assuming the end position is\n        // primed first\n        // Case 1: no fragmentation\n        double c = (1.0 / l) * (l - 1 < max_non_frag_run ? non_frag_run_pr[l - 1] : 0.0);\n        for (pos_t v = from; v < to; ++v) {\n            double select_pr = fm->frag_len_c(v) / v;\n            out[v] = c * select_pr;\n        }\n\n        // Case 2: read contained in a fragment at the left end of the\n        //         transcript\n        for (pos_t v = from; v < to; ++v) {\n            for (pos_t j = v; j < std::min<pos_t>(l, v + max_non_frag_run); ++j) {\n                double select_pr = fm->frag_len_c(v) / v;\n                double run_pr = j - 1 < max_non_frag_run ? non_frag_run_pr[j - 1] : 0.0;\n                out[v] += p * run_pr * (1.0 / j) * select_pr;\n            }\n        }\n\n        // Case 3: read contained a fragment at the right end\n        for (pos_t v = from; v < to; ++v) {\n            for (pos_t i = std::max<pos_t>(0, v - max_non_frag_run); i < v; ++i) {\n                double select_pr = fm->frag_len_c(v - i) / (v - i);\n                double run_pr = l - i - 1 < max_non_frag_run ? non_frag_run_pr[l - i - 1] : 0.0;\n                out[v] += p * run_pr * (1.0 / ((l - i))) * select_pr;\n            }\n        }\n\n        // Case 4: read flanked by fragmentation breakpoints\n        for (pos_t v = from; v < to; ++v) {\n            for (pos_t h = 1; h < std::min<pos_t>(max_non_frag_run, v); ++h) {\n                double run_pr1 = non_frag_run_pr_sum[\n                    std::min<pos_t>((l - v)+ h, max_non_frag_run - 1)];\n                double run_pr2 = non_frag_run_pr_sum[\n                    std::min<pos_t>(h, max_non_frag_run - 1)];\n\n                out[v] += p * p * (fm->frag_len_c(h) / h) *\n                    (run_pr1 - run_pr2);\n            }\n        }\n#endif\n\n        // enrichment of start positions assuming the start position\n        // is primed first.\n        // Case 1: no fragmentation\n        double c = (1.0 / l) * (l - 1 < max_non_frag_run ? non_frag_run_pr[l - 1] : 0.0);\n        for (pos_t u = from; u < to; ++u) {\n            double select_pr = fm->frag_len_c(l - u + 1) / (l - u + 1);\n            out[u] = c * select_pr;\n        }\n\n        // Case 2: read contained in a fragment at the left end of the\n        //         transcript\n        for (pos_t u = from; u < to; ++u) {\n            for (pos_t j = u + 1; j < std::min<pos_t>(l, u + max_non_frag_run); ++j) {\n                double select_pr = fm->frag_len_c(j - u) / (j - u);\n                double run_pr = j - 1 < max_non_frag_run ? non_frag_run_pr[j - 1] : 0.0;\n                out[u] += p * run_pr * (1.0 / j) * select_pr;\n            }\n        }\n\n        // Case 3: read contained a fragment at the right end\n        for (pos_t u = from; u < to; ++u) {\n            for (pos_t i = std::max<pos_t>(0, u - max_non_frag_run); i < u; ++i) {\n                double select_pr = fm->frag_len_c(l - u + 1) / (l - u + 1);\n                double run_pr = l - i - 1 < max_non_frag_run ? non_frag_run_pr[l - i - 1] : 0.0;\n                out[u] += p * run_pr * (1.0 / ((l - i))) * select_pr;\n            }\n        }\n\n        // Case 4: read flanked by fragmentation breakpoints\n        for (pos_t u = from; u < to; ++u) {\n            for (pos_t h = 1; h < std::min<pos_t>(max_non_frag_run, l - u); ++h) {\n                double run_pr1 = non_frag_run_pr_sum[\n                    std::min<pos_t>(u + h, max_non_frag_run - 1)];\n                double run_pr2 = non_frag_run_pr_sum[\n                    std::min<pos_t>(h, max_non_frag_run - 1)];\n\n                out[u] += p * p * (fm->frag_len_c(h) / h) *\n                    (run_pr1 - run_pr2);\n            }\n        }\n\n        for (pos_t u = from; u < to; ++u) {\n            out[u] *= constants::fragbias_scale;\n        }\n}\n\n\nvoid FragBias::get_bias(float* out, pos_t l)\n{\n    unsigned int a;\n    // extrapolate downwards\n    if (l < lengths.front()) {\n        a = 0;\n    }\n    // extrapolate upwards\n    else if (l >= lengths.back()) {\n        a = lengths.size() - 2;\n    }\n    // interpolate\n    else {\n        std::vector<pos_t>::iterator a_it =\n            std::upper_bound(lengths.begin(), lengths.end(), l);\n        a = a_it - lengths.begin() - 1;\n    }\n\n    unsigned int b = a + 1;\n\n    pos_t al = lengths[a];\n    pos_t bl = lengths[b];\n\n    double z = (double) (l - al) / (double) (bl - al);\n\n    // extrapolation can be very very wrong, so we just explicitly compute the\n    // ends and copy the middles.\n    pos_t endlen = 0;\n    if (b == lengths.size() - 1) {\n        z = 0.0;\n        endlen = constants::fragbias_endlen;\n    }\n    pos_t to = std::min<pos_t>(l, endlen);\n    compute(out, 0, to, l);\n    compute(out, std::max<pos_t>(to, l - endlen), l, l);\n\n    for (pos_t u = endlen; u < l - endlen; ++u) {\n        double r = (double) u / (double) (l - 1);\n        pos_t au = lround(r * (al - 1));\n        pos_t bu = lround(r * (bl - 1));\n        double slope = bias[b][bu] - bias[a][au];\n\n        out[u] = bias[a][au] + z * slope;\n    }\n}\n\n\n", "meta": {"hexsha": "9a2ab26805671eec1e2b477dbf63019c90fd38e6", "size": 6565, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/fragbias.cpp", "max_stars_repo_name": "dcjones/isolator", "max_stars_repo_head_hexsha": "24bafc0a102dce213bfc2b5b9744136ceadaba03", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 33.0, "max_stars_repo_stars_event_min_datetime": "2015-07-13T03:00:01.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-20T08:49:07.000Z", "max_issues_repo_path": "src/fragbias.cpp", "max_issues_repo_name": "dcjones/isolator", "max_issues_repo_head_hexsha": "24bafc0a102dce213bfc2b5b9744136ceadaba03", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 9.0, "max_issues_repo_issues_event_min_datetime": "2016-11-29T00:04:30.000Z", "max_issues_repo_issues_event_max_datetime": "2020-02-10T17:46:01.000Z", "max_forks_repo_path": "src/fragbias.cpp", "max_forks_repo_name": "dcjones/isolator", "max_forks_repo_head_hexsha": "24bafc0a102dce213bfc2b5b9744136ceadaba03", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2015-09-10T15:49:34.000Z", "max_forks_repo_forks_event_max_datetime": "2017-03-09T05:14:06.000Z", "avg_line_length": 34.7354497354, "max_line_length": 96, "alphanum_fraction": 0.5079969535, "num_tokens": 2107, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6477982179521103, "lm_q2_score": 0.5389832206876841, "lm_q1q2_score": 0.3491523698675708}}
{"text": "#include <cstdlib>\n#include <sstream>\n#include <iostream>\n#include <fstream>\n#include <vector>\n\n#include <boost/program_options.hpp>\n#include <boost/program_options/variables_map.hpp>\n\n#include \"filelib.h\"\n#include \"weights.h\"\n#include \"sparse_vector.h\"\n#include \"optimize.h\"\n#include \"liblbfgs/lbfgs++.h\"\n\nusing namespace std;\nnamespace po = boost::program_options;\n\n// since this is a ranking model, there should be equal numbers of\n// positive and negative examples, so the bias should be 0\n\nvoid InitCommandLine(int argc, char** argv, po::variables_map* conf) {\n  po::options_description opts(\"Configuration options\");\n  opts.add_options()\n        (\"weights,w\", po::value<string>(), \"Weights from previous iteration (used as initialization and interpolation\")\n        (\"regularization_strength,C\",po::value<double>()->default_value(500.0), \"l2 regularization strength\")\n        (\"l1\",po::value<double>()->default_value(0.0), \"l1 regularization strength\")\n        (\"regularize_to_weights,y\",po::value<double>()->default_value(5000.0), \"Differences in learned weights to previous weights are penalized with an l2 penalty with this strength; 0.0 = no effect\")\n        (\"memory_buffers,m\",po::value<unsigned>()->default_value(100), \"Number of memory buffers (LBFGS)\")\n        (\"min_reg,r\",po::value<double>()->default_value(0.01), \"When tuning (-T) regularization strength, minimum regularization strenght\")\n        (\"max_reg,R\",po::value<double>()->default_value(1e6), \"When tuning (-T) regularization strength, maximum regularization strenght\")\n        (\"testset,t\",po::value<string>(), \"Optional held-out test set\")\n        (\"tune_regularizer,T\", \"Use the held out test set (-t) to tune the regularization strength\")\n        (\"interpolate_with_weights,p\",po::value<double>()->default_value(1.0), \"[deprecated] Output weights are p*w + (1-p)*w_prev; 1.0 = no effect\")\n        (\"help,h\", \"Help\");\n  po::options_description dcmdline_options;\n  dcmdline_options.add(opts);\n  po::store(parse_command_line(argc, argv, dcmdline_options), *conf);\n  if (conf->count(\"help\")) {\n    cerr << dcmdline_options << endl;\n    exit(1);\n  }\n}\n\nvoid ParseSparseVector(string& line, size_t cur, SparseVector<weight_t>* out) {\n  SparseVector<weight_t>& x = *out;\n  size_t last_start = cur;\n  size_t last_comma = string::npos;\n  while(cur <= line.size()) {\n    if (line[cur] == ' ' || cur == line.size()) {\n      if (!(cur > last_start && last_comma != string::npos && cur > last_comma)) {\n        cerr << \"[ERROR] \" << line << endl << \"  position = \" << cur << endl;\n        exit(1);\n      }\n      const int fid = FD::Convert(line.substr(last_start, last_comma - last_start));\n      if (cur < line.size()) line[cur] = 0;\n      const weight_t val = strtod(&line[last_comma + 1], NULL);\n      x.set_value(fid, val);\n\n      last_comma = string::npos;\n      last_start = cur+1;\n    } else {\n      if (line[cur] == '=')\n        last_comma = cur;\n    }\n    ++cur;\n  }\n}\n\nvoid ReadCorpus(istream* pin, vector<pair<bool, SparseVector<weight_t> > >* corpus) {\n  istream& in = *pin;\n  corpus->clear();\n  bool flag = false;\n  int lc = 0;\n  string line;\n  SparseVector<weight_t> x;\n  while(getline(in, line)) {\n    ++lc;\n    if (lc % 1000 == 0) { cerr << '.'; flag = true; }\n    if (lc % 40000 == 0) { cerr << \" [\" << lc << \"]\\n\"; flag = false; }\n    if (line.empty()) continue;\n    const size_t ks = line.find(\"\\t\");\n    assert(string::npos != ks);\n    assert(ks == 1);\n    const bool y = line[0] == '1';\n    x.clear();\n    ParseSparseVector(line, ks + 1, &x);\n    corpus->push_back(make_pair(y, x));\n  }\n  if (flag) cerr << endl;\n}\n\nvoid GradAdd(const SparseVector<weight_t>& v, const double scale, weight_t* acc) {\n  for (SparseVector<weight_t>::const_iterator it = v.begin();\n       it != v.end(); ++it) {\n    acc[it->first] += it->second * scale;\n  }\n}\n\ndouble ApplyRegularizationTerms(const double C,\n                                const double T,\n                                const vector<weight_t>& weights,\n                                const vector<weight_t>& prev_weights,\n                                weight_t* g) {\n  double reg = 0;\n  for (size_t i = 0; i < weights.size(); ++i) {\n    const double prev_w_i = (i < prev_weights.size() ? prev_weights[i] : 0.0);\n    const double& w_i = weights[i];\n    reg += C * w_i * w_i;\n    g[i] += 2 * C * w_i;\n\n    const double diff_i = w_i - prev_w_i;\n    reg += T * diff_i * diff_i;\n    g[i] += 2 * T * diff_i;\n  }\n  return reg;\n}\n\ndouble TrainingInference(const vector<weight_t>& x,\n                         const vector<pair<bool, SparseVector<weight_t> > >& corpus,\n                         weight_t* g = NULL) {\n  double cll = 0;\n  for (int i = 0; i < corpus.size(); ++i) {\n    const double dotprod = corpus[i].second.dot(x) + (x.size() ? x[0] : weight_t()); // x[0] is bias\n    double lp_false = dotprod;\n    double lp_true = -dotprod;\n    if (0 < lp_true) {\n      lp_true += log1p(exp(-lp_true));\n      lp_false = log1p(exp(lp_false));\n    } else {\n      lp_true = log1p(exp(lp_true));\n      lp_false += log1p(exp(-lp_false));\n    }\n    lp_true*=-1;\n    lp_false*=-1;\n    if (corpus[i].first) {  // true label\n      cll -= lp_true;\n      if (g) {\n        // g -= corpus[i].second * exp(lp_false);\n        GradAdd(corpus[i].second, -exp(lp_false), g);\n        g[0] -= exp(lp_false); // bias\n      }\n    } else {                  // false label\n      cll -= lp_false;\n      if (g) {\n        // g += corpus[i].second * exp(lp_true);\n        GradAdd(corpus[i].second, exp(lp_true), g);\n        g[0] += exp(lp_true); // bias\n      }\n    }\n  }\n  return cll;\n}\n\nstruct ProLoss {\n  ProLoss(const vector<pair<bool, SparseVector<weight_t> > >& tr,\n          const vector<pair<bool, SparseVector<weight_t> > >& te,\n          const double c,\n          const double t,\n          const vector<weight_t>& px) : training(tr), testing(te), C(c), T(t), prev_x(px){}\n  double operator()(const vector<double>& x, double* g) const {\n    fill(g, g + x.size(), 0.0);\n    double cll = TrainingInference(x, training, g);\n    tppl = 0;\n    if (testing.size())\n      tppl = pow(2.0, TrainingInference(x, testing, g) / (log(2) * testing.size()));\n    double ppl = cll / log(2);\n    ppl /= training.size();\n    ppl = pow(2.0, ppl);\n    double reg = ApplyRegularizationTerms(C, T, x, prev_x, g);\n    return cll + reg;\n  }\n  const vector<pair<bool, SparseVector<weight_t> > >& training, testing;\n  const double C, T;\n  const vector<double>& prev_x;\n  mutable double tppl;\n};\n\n// return held-out log likelihood\ndouble LearnParameters(const vector<pair<bool, SparseVector<weight_t> > >& training,\n                       const vector<pair<bool, SparseVector<weight_t> > >& testing,\n                       const double C,\n                       const double C1,\n                       const double T,\n                       const unsigned memory_buffers,\n                       const vector<weight_t>& prev_x,\n                       vector<weight_t>* px) {\n  assert(px->size() == prev_x.size());\n  ProLoss loss(training, testing, C, T, prev_x);\n  LBFGS<ProLoss> lbfgs(px, loss, memory_buffers, C1);\n  lbfgs.MinimizeFunction();\n  return loss.tppl;\n}\n\nint main(int argc, char** argv) {\n  po::variables_map conf;\n  InitCommandLine(argc, argv, &conf);\n  string line;\n  vector<pair<bool, SparseVector<weight_t> > > training, testing;\n  const bool tune_regularizer = conf.count(\"tune_regularizer\");\n  if (tune_regularizer && !conf.count(\"testset\")) {\n    cerr << \"--tune_regularizer requires --testset to be set\\n\";\n    return 1;\n  }\n  const double min_reg = conf[\"min_reg\"].as<double>();\n  const double max_reg = conf[\"max_reg\"].as<double>();\n  double C = conf[\"regularization_strength\"].as<double>(); // will be overridden if parameter is tuned\n  double C1 = conf[\"l1\"].as<double>(); // will be overridden if parameter is tuned\n  const double T = conf[\"regularize_to_weights\"].as<double>();\n  assert(C >= 0.0);\n  assert(min_reg >= 0.0);\n  assert(max_reg >= 0.0);\n  assert(max_reg > min_reg);\n  const double psi = conf[\"interpolate_with_weights\"].as<double>();\n  if (psi < 0.0 || psi > 1.0) { cerr << \"Invalid interpolation weight: \" << psi << endl; return 1; }\n  ReadCorpus(&cin, &training);\n  if (conf.count(\"testset\")) {\n    ReadFile rf(conf[\"testset\"].as<string>());\n    ReadCorpus(rf.stream(), &testing);\n  }\n  cerr << \"Number of features: \" << FD::NumFeats() << endl;\n\n  vector<weight_t> x, prev_x;  // x[0] is bias\n  if (conf.count(\"weights\")) {\n    Weights::InitFromFile(conf[\"weights\"].as<string>(), &x);\n    x.resize(FD::NumFeats());\n    prev_x = x;\n  } else {\n    x.resize(FD::NumFeats());\n    prev_x = x;\n  }\n  cerr << \"         Number of features: \" << x.size() << endl;\n  cerr << \"Number of training examples: \" << training.size() << endl;\n  cerr << \"Number of  testing examples: \" << testing.size() << endl;\n  double tppl = 0.0;\n  vector<pair<double,double> > sp;\n  vector<double> smoothed;\n  if (tune_regularizer) {\n    C = min_reg;\n    const double steps = 18;\n    double sweep_factor = exp((log(max_reg) - log(min_reg)) / steps);\n    cerr << \"SWEEP FACTOR: \" << sweep_factor << endl;\n    while(C < max_reg) {\n      cerr << \"C=\" << C << \"\\tT=\" <<T << endl;\n      tppl = LearnParameters(training, testing, C, C1, T, conf[\"memory_buffers\"].as<unsigned>(), prev_x, &x);\n      sp.push_back(make_pair(C, tppl));\n      C *= sweep_factor;\n    }\n    smoothed.resize(sp.size(), 0);\n    smoothed[0] = sp[0].second;\n    smoothed.back() = sp.back().second; \n    for (int i = 1; i < sp.size()-1; ++i) {\n      double prev = sp[i-1].second;\n      double next = sp[i+1].second;\n      double cur = sp[i].second;\n      smoothed[i] = (prev*0.2) + cur * 0.6 + (0.2*next);\n    }\n    double best_ppl = 9999999;\n    unsigned best_i = 0;\n    for (unsigned i = 0; i < sp.size(); ++i) {\n      if (smoothed[i] < best_ppl) {\n        best_ppl = smoothed[i];\n        best_i = i;\n      }\n    }\n    C = sp[best_i].first;\n  }  // tune regularizer\n  tppl = LearnParameters(training, testing, C, C1, T, conf[\"memory_buffers\"].as<unsigned>(), prev_x, &x);\n  if (conf.count(\"weights\")) {\n    for (int i = 1; i < x.size(); ++i) {\n      x[i] = (x[i] * psi) + prev_x[i] * (1.0 - psi);\n    }\n  }\n  cout.precision(15);\n  cout << \"# C=\" << C << \"\\theld out perplexity=\";\n  if (tppl) { cout << tppl << endl; } else { cout << \"N/A\\n\"; }\n  if (sp.size()) {\n    cout << \"# Parameter sweep:\\n\";\n    for (int i = 0; i < sp.size(); ++i) {\n      cout << \"# \" << sp[i].first << \"\\t\" << sp[i].second << \"\\t\" << smoothed[i] << endl;\n    }\n  }\n  Weights::WriteToFile(\"-\", x);\n  return 0;\n}\n", "meta": {"hexsha": "a61a3a5f09c29e40a80da559805cf03df1230521", "size": 10549, "ext": "cc", "lang": "C++", "max_stars_repo_path": "training/pro/mr_pro_reduce.cc", "max_stars_repo_name": "veer66/cdec", "max_stars_repo_head_hexsha": "abc8ba62232c158ad5c4ee1bb4256bc2ace07b61", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 114.0, "max_stars_repo_stars_event_min_datetime": "2015-01-11T05:41:03.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-31T03:47:12.000Z", "max_issues_repo_path": "training/pro/mr_pro_reduce.cc", "max_issues_repo_name": "veer66/cdec", "max_issues_repo_head_hexsha": "abc8ba62232c158ad5c4ee1bb4256bc2ace07b61", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 29.0, "max_issues_repo_issues_event_min_datetime": "2015-01-09T01:00:09.000Z", "max_issues_repo_issues_event_max_datetime": "2019-09-25T06:04:02.000Z", "max_forks_repo_path": "training/pro/mr_pro_reduce.cc", "max_forks_repo_name": "veer66/cdec", "max_forks_repo_head_hexsha": "abc8ba62232c158ad5c4ee1bb4256bc2ace07b61", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 50.0, "max_forks_repo_forks_event_min_datetime": "2015-02-13T13:48:39.000Z", "max_forks_repo_forks_event_max_datetime": "2019-08-07T09:45:11.000Z", "avg_line_length": 36.8846153846, "max_line_length": 201, "alphanum_fraction": 0.5889657787, "num_tokens": 2988, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6619228758499942, "lm_q2_score": 0.5273165233795671, "lm_q1q2_score": 0.3490428696386238}}
{"text": "/*!\n  \\file gpp_knowledge_gradient_optimization.cpp\n  \\rst\n\\endrst*/\n\n\n#include \"gpp_knowledge_gradient_optimization.hpp\"\n\n#include <cmath>\n\n#include <algorithm>\n#include <memory>\n#include <vector>\n\n#include <boost/math/distributions/normal.hpp>  // NOLINT(build/include_order)\n\n#include \"gpp_common.hpp\"\n#include \"gpp_domain.hpp\"\n#include \"gpp_logging.hpp\"\n#include \"gpp_math.hpp\"\n#include \"gpp_optimizer_parameters.hpp\"\n\nnamespace optimal_learning {\n\ntemplate <typename DomainType>\nKnowledgeGradientEvaluator<DomainType>::KnowledgeGradientEvaluator(const GaussianProcess& gaussian_process_in, const int num_fidelity,\n                                                                   double const * discrete_pts,\n                                                                   int num_pts,\n                                                                   int num_mc_iterations,\n                                                                   const DomainType& domain,\n                                                                   const GradientDescentParameters& optimizer_parameters,\n                                                                   double best_so_far)\n  : dim_(gaussian_process_in.dim()),\n    num_fidelity_(num_fidelity),\n    num_mc_iterations_(num_mc_iterations),\n    best_so_far_(best_so_far),\n    optimizer_parameters_(optimizer_parameters.num_multistarts, optimizer_parameters.max_num_steps,\n                          optimizer_parameters.max_num_restarts, optimizer_parameters.num_steps_averaged,\n                          optimizer_parameters.gamma, optimizer_parameters.pre_mult,\n                          optimizer_parameters.max_relative_change, optimizer_parameters.tolerance),\n    domain_(domain),\n    gaussian_process_(&gaussian_process_in),\n    discrete_pts_(discrete_points(discrete_pts, num_pts)),\n    num_pts_(num_pts){\n}\n\ntemplate <typename DomainType>\nKnowledgeGradientEvaluator<DomainType>::KnowledgeGradientEvaluator(KnowledgeGradientEvaluator&& other)\n  : dim_(other.dim()),\n    num_fidelity_(other.num_fidelity()),\n    num_mc_iterations_(other.num_mc_iterations()),\n    best_so_far_(other.best_so_far()),\n    optimizer_parameters_(other.gradient_descent_params().num_multistarts, other.gradient_descent_params().max_num_steps,\n                          other.gradient_descent_params().max_num_restarts, other.gradient_descent_params().num_steps_averaged,\n                          other.gradient_descent_params().gamma, other.gradient_descent_params().pre_mult,\n                          other.gradient_descent_params().max_relative_change, other.gradient_descent_params().tolerance),\n    domain_(other.domain()),\n    gaussian_process_(other.gaussian_process()),\n    discrete_pts_(other.discrete_pts_copy()),\n    num_pts_(other.number_discrete_pts()){\n}\n\n/*!\\rst\n  Compute Knowledge Gradient\n  This version requires the discretization of A (the feasibe domain).\n  The discretization usually is: some set + points previous sampled + points being sampled + points to sample\n\\endrst*/\ntemplate <typename DomainType>\ndouble KnowledgeGradientEvaluator<DomainType>::ComputeKnowledgeGradient(StateType * kg_state) const {\n  int num_union = kg_state->num_union;\n  int num_gradients_to_sample = kg_state->num_gradients_to_sample;\n\n  double best_posterior = best_so_far_;\n  for (int j = 0; j < num_union; ++j) {\n    if (kg_state->to_sample_mean_[j*(1+kg_state->num_gradients_to_sample)] < best_posterior){\n      best_posterior = kg_state->to_sample_mean_[j*(1+kg_state->num_gradients_to_sample)];\n    }\n  }\n\n  double aggregate = 0.0;\n  kg_state->normal_rng->ResetToMostRecentSeed();\n\n  GaussianProcess gaussian_process_after(*gaussian_process_);\n  std::vector<double> make_up_function_value(num_union*(1+num_gradients_to_sample));\n  gaussian_process_after.AddSampledPointsToGP(kg_state->union_of_points.data(), make_up_function_value.data(), num_union);\n\n  for (int i = 0; i < num_mc_iterations_; ++i) {\n    if (i % 2 == 1){\n      for (int j = 0; j < num_union*(1+num_gradients_to_sample); ++j) {\n        kg_state->normals[j + i*num_union*(1+num_gradients_to_sample)] = -kg_state->normals[j + (i-1)*num_union*(1+num_gradients_to_sample)];\n      }\n    }\n    else {\n      for (int j = 0; j < num_union*(1+num_gradients_to_sample); ++j) {\n        kg_state->normals[j + i*num_union*(1+num_gradients_to_sample)] = (*(kg_state->normal_rng))();\n      }\n    }\n\n    double best_function_value = 0.0;\n    bool found_flag;\n\n    std::copy(kg_state->to_sample_mean_.begin(), kg_state->to_sample_mean_.end(), make_up_function_value.begin());\n    GeneralMatrixVectorMultiply(kg_state->cholesky_to_sample_var.data(), 'N', kg_state->normals.data() + i*num_union*(1+num_gradients_to_sample),\n                                1.0, 1.0, num_union*(1+num_gradients_to_sample), num_union*(1+num_gradients_to_sample), num_union*(1+num_gradients_to_sample),\n                                make_up_function_value.data());\n\n    gaussian_process_after.NewSampledValue(make_up_function_value.data(), num_union, gaussian_process_->num_sampled(), false);\n\n    ComputeOptimalPosteriorMean(gaussian_process_after, num_fidelity_, optimizer_parameters_,\n                                domain_, kg_state->discretized_set.data(), num_union + num_pts_,\n                                &found_flag, kg_state->best_point.data() + i*dim_, &best_function_value);\n    aggregate += best_posterior + best_function_value;\n  }\n  return aggregate/static_cast<double>(num_mc_iterations_);\n}\n\n/*!\\rst\n  Computes gradient of KG (see KnowledgeGradientEvaluator::ComputeGradKnowledgeGradient) wrt points_to_sample (stored in\n  ``union_of_points[0:num_to_sample]``).\n  Mechanism is similar to the computation of KG, where points' contributions to the gradient are thrown out of their\n  corresponding ``improvement <= 0.0``.\n  Thus ``\\nabla(\\mu)`` only contributes when the ``winner`` (point w/best improvement this iteration) is the current point.\n  That is, the gradient of ``\\mu`` at ``x_i`` wrt ``x_j`` is 0 unless ``i == j`` (and only this result is stored in\n  ``kg_state->grad_mu``).  The interaction with ``kg_state->grad_chol_decomp`` is harder to know a priori (like with\n  ``grad_mu``) and has a more complex structure (rank 3 tensor), so the derivative wrt ``x_j`` is computed fully, and\n  the relevant submatrix (indexed by the current ``winner``) is accessed each iteration.\n  .. Note:: comments here are copied to _compute_grad_knowledge_gradient_monte_carlo() in python_version/knowledge_gradient.py\n\\endrst*/\ntemplate <typename DomainType>\ndouble KnowledgeGradientEvaluator<DomainType>::ComputeGradKnowledgeGradient(StateType * kg_state, double * restrict grad_KG) const {\n  const int num_union = kg_state->num_union;\n  int num_gradients_to_sample = kg_state->num_gradients_to_sample;\n\n  std::vector<double> grad_mu_temp(dim_*(kg_state->num_to_sample)*(1+num_gradients_to_sample), 0.0);\n  gaussian_process_->ComputeGradMeanOfPoints(kg_state->points_to_sample_state, grad_mu_temp.data());\n  for (int i = 0; i < kg_state->num_to_sample; ++i){\n    for (int d = 0; d < dim_; ++d){\n      kg_state->grad_mu[d + i*dim_] = grad_mu_temp[d + i*(1+num_gradients_to_sample)*dim_];\n    }\n  }\n\n  // compute the grad of chol among points to sample.\n  gaussian_process_->ComputeGradCholeskyVarianceOfPoints(&(kg_state->points_to_sample_state),\n                                                         kg_state->cholesky_to_sample_var.data(),\n                                                         kg_state->grad_chol_decomp.data());\n  int winner_so_far = -1;\n  double best_posterior = best_so_far_;\n  for (int j = 0; j < num_union; ++j){\n    if (kg_state->to_sample_mean_[j*(1+kg_state->num_gradients_to_sample)] < best_posterior){\n      winner_so_far = j;\n      best_posterior = kg_state->to_sample_mean_[j*(1+kg_state->num_gradients_to_sample)];\n    }\n  }\n\n  std::fill(kg_state->aggregate.begin(), kg_state->aggregate.end(), 0.0);\n\n  if (winner_so_far >= 0 && winner_so_far < kg_state->num_to_sample){\n    for (int k = 0; k < dim_; ++k) {\n      kg_state->aggregate[winner_so_far*dim_ + k] += num_mc_iterations_ * kg_state->grad_mu[winner_so_far*dim_ + k];\n    }\n  }\n  std::fill(kg_state->best_point.begin(), kg_state->best_point.end(), 1.0);\n  double aggregate = 0.0;\n  kg_state->normal_rng->ResetToMostRecentSeed();\n\n  GaussianProcess gaussian_process_after(*gaussian_process_);\n  std::vector<double> make_up_function_value(num_union*(1+num_gradients_to_sample));\n  gaussian_process_after.AddSampledPointsToGP(kg_state->union_of_points.data(), make_up_function_value.data(), num_union);\n\n  for (int i = 0; i < num_mc_iterations_; ++i) {\n    if (i % 2 == 1){\n      for (int j = 0; j < num_union*(1+num_gradients_to_sample); ++j) {\n        kg_state->normals[j + i*num_union*(1+num_gradients_to_sample)] = -kg_state->normals[j + (i-1)*num_union*(1+num_gradients_to_sample)];\n      }\n    }\n    else {\n      for (int j = 0; j < num_union*(1+num_gradients_to_sample); ++j) {\n        kg_state->normals[j + i*num_union*(1+num_gradients_to_sample)] = (*(kg_state->normal_rng))();// - 1.0;\n      }\n    }\n\n    double best_function_value = 0.0;\n    bool found_flag;\n\n    std::copy(kg_state->to_sample_mean_.begin(), kg_state->to_sample_mean_.end(), make_up_function_value.begin());\n    GeneralMatrixVectorMultiply(kg_state->cholesky_to_sample_var.data(), 'N', kg_state->normals.data() + i*num_union*(1+num_gradients_to_sample),\n                                1.0, 1.0, num_union*(1+num_gradients_to_sample), num_union*(1+num_gradients_to_sample), num_union*(1+num_gradients_to_sample),\n                                make_up_function_value.data());\n\n    gaussian_process_after.NewSampledValue(make_up_function_value.data(), num_union, gaussian_process_->num_sampled(), false);\n\n    ComputeOptimalPosteriorMean(gaussian_process_after, num_fidelity_, optimizer_parameters_,\n                                domain_, kg_state->discretized_set.data(), num_union + num_pts_,\n                                &found_flag, kg_state->best_point.data() + i*dim_, &best_function_value);\n    aggregate += best_posterior + best_function_value;\n  }  // end for i: num_mc_iterations_\n  double KG =aggregate/static_cast<double>(num_mc_iterations_);\n\n  gaussian_process_->ComputeCovarianceOfPoints(&(kg_state->points_to_sample_state), kg_state->best_point.data(), num_mc_iterations_,\n                                               nullptr, 0, false, nullptr, kg_state->chol_inverse_cov.data());\n  TriangularMatrixMatrixSolve(kg_state->cholesky_to_sample_var.data(), 'N', num_union*(1+num_gradients_to_sample), num_mc_iterations_,\n                              num_union*(1+num_gradients_to_sample), kg_state->chol_inverse_cov.data());\n\n  gaussian_process_->ComputeGradInverseCholeskyCovarianceOfPoints(&(kg_state->points_to_sample_state),\n                                                                  kg_state->cholesky_to_sample_var.data(),\n                                                                  kg_state->grad_chol_decomp.data(),\n                                                                  kg_state->chol_inverse_cov.data(),\n                                                                  kg_state->best_point.data(), num_mc_iterations_, false, nullptr,\n                                                                  kg_state->grad_chol_inverse_cov.data());\n\n  // let L_{d,i,j,k} = grad_chol_decomp, d over dim_, i, j over num_union, k over num_to_sample\n  // we want to compute: agg_dx_{d,k} = L_{d,i,j=winner,k} * normals_i\n  // TODO(GH-92): Form this as one GeneralMatrixVectorMultiply() call by storing data as L_{d,i,k,j} if it's faster.\n  double const * restrict grad_chol_decomp_winner_block = kg_state->grad_chol_inverse_cov.data();\n  for (int k = 0; k < kg_state->num_to_sample; ++k) {\n    for (int i = 0; i < num_mc_iterations_; ++i){\n      GeneralMatrixVectorMultiply(grad_chol_decomp_winner_block, 'N', kg_state->normals.data() + i*num_union*(1+num_gradients_to_sample), -1.0, 1.0,\n                                  dim_, num_union*(1+num_gradients_to_sample), dim_, kg_state->aggregate.data() + k*dim_);\n      grad_chol_decomp_winner_block += dim_*num_union*(1+num_gradients_to_sample);\n    }\n  }\n\n  for (int k = 0; k < kg_state->num_to_sample*dim_; ++k) {\n    grad_KG[k] = kg_state->aggregate[k]/static_cast<double>(num_mc_iterations_);\n  }\n  return KG;\n}\n\ntemplate class KnowledgeGradientEvaluator<TensorProductDomain>;\ntemplate class KnowledgeGradientEvaluator<SimplexIntersectTensorProductDomain>;\n\ntemplate <typename DomainType>\nvoid KnowledgeGradientState<DomainType>::SetCurrentPoint(const EvaluatorType& kg_evaluator,\n                                                         double const * restrict points_to_sample) {\n  // update points_to_sample in union_of_points\n  std::copy(points_to_sample, points_to_sample + num_to_sample*dim, union_of_points.data());\n\n  // evaluate derived quantities for the GP\n  points_to_sample_state.SetupState(*kg_evaluator.gaussian_process(), union_of_points.data(),\n                                    num_union, num_gradients_to_sample, num_derivatives, true, (num_derivatives>0));\n\n  PreCompute(kg_evaluator, points_to_sample);\n}\n\ntemplate <typename DomainType>\nKnowledgeGradientState<DomainType>::KnowledgeGradientState(const EvaluatorType& kg_evaluator, double const * restrict points_to_sample,\n                                                           double const * restrict points_being_sampled, int num_to_sample_in, int num_being_sampled_in, int num_pts_in,\n                                                           int const * restrict gradients_in, int num_gradients_in, bool configure_for_gradients, NormalRNGInterface * normal_rng_in)\n  : dim(kg_evaluator.dim()),\n    num_to_sample(num_to_sample_in),\n    num_being_sampled(num_being_sampled_in),\n    num_derivatives(configure_for_gradients ? num_to_sample : 0),\n    num_union(num_to_sample + num_being_sampled),\n    num_iterations(kg_evaluator.num_mc_iterations()),\n    gradients(gradients_in, gradients_in+num_gradients_in),\n    num_gradients_to_sample(num_gradients_in),\n    union_of_points(BuildUnionOfPoints(points_to_sample, points_being_sampled,\n                                       num_to_sample, num_being_sampled, dim)),\n    subset_union_of_points(SubsetData(union_of_points.data(), num_union, kg_evaluator.num_fidelity())),\n    discretized_set(BuildUnionOfPoints(subset_union_of_points.data(), kg_evaluator.discrete_pts_copy().data(),\n                                       num_union, kg_evaluator.number_discrete_pts(), dim - kg_evaluator.num_fidelity())),\n    points_to_sample_state(*kg_evaluator.gaussian_process(), union_of_points.data(), num_union,\n                           gradients_in, num_gradients_in, num_derivatives, true, configure_for_gradients),\n    normal_rng(normal_rng_in),\n    cholesky_to_sample_var(Square(num_union*(1+num_gradients_to_sample))),\n    grad_chol_decomp(dim*Square(num_union*(1+num_gradients_to_sample))*num_derivatives),\n    to_sample_mean_(num_union*(1+num_gradients_to_sample)),\n    grad_mu(dim*num_derivatives),\n    aggregate(dim*num_derivatives),\n    normals(num_union*(1+num_gradients_to_sample)*num_iterations),\n    best_point(dim*num_iterations),\n    chol_inverse_cov(num_iterations*num_union*(1+num_gradients_to_sample)),\n    grad_chol_inverse_cov(dim*num_iterations*num_union*(1+num_gradients_to_sample)*num_derivatives) {\n  PreCompute(kg_evaluator, points_to_sample);\n}\n\ntemplate <typename DomainType>\nKnowledgeGradientState<DomainType>::KnowledgeGradientState(KnowledgeGradientState&& OL_UNUSED(other)) = default;\n\ntemplate <typename DomainType>\nvoid KnowledgeGradientState<DomainType>::SetupState(const EvaluatorType& kg_evaluator,\n                                                    double const * restrict points_to_sample) {\n  if (unlikely(dim != kg_evaluator.dim())) {\n    OL_THROW_EXCEPTION(InvalidValueException<int>, \"Evaluator's and State's dim do not match!\", dim, kg_evaluator.dim());\n  }\n\n  // update quantities derived from points_to_sample\n  SetCurrentPoint(kg_evaluator, points_to_sample);\n}\n\ntemplate <typename DomainType>\nvoid KnowledgeGradientState<DomainType>::PreCompute(const EvaluatorType& kg_evaluator,\n                                                    double const * restrict points_to_sample) {\n  if (unlikely(dim != kg_evaluator.dim())) {\n    OL_THROW_EXCEPTION(InvalidValueException<int>, \"Evaluator's and State's dim do not match!\", dim, kg_evaluator.dim());\n  }\n\n  kg_evaluator.gaussian_process()->ComputeMeanOfAdditionalPoints(union_of_points.data(), num_union, gradients.data(), num_gradients_to_sample,\n                                                                 to_sample_mean_.data());\n\n  kg_evaluator.gaussian_process()->ComputeVarianceOfPoints(&(points_to_sample_state), gradients.data(),\n                                                          num_gradients_to_sample, cholesky_to_sample_var.data());\n  //Adding the variance of measurement noise to the covariance matrix\n  for (int i = 0;i < num_union; i++){\n    for (int j = 0; j < 1+num_gradients_to_sample; ++j){\n      int row = i*(1+num_gradients_to_sample)+j;\n      cholesky_to_sample_var[row+row*num_union*(1+num_gradients_to_sample)] += kg_evaluator.gaussian_process()->noise_variance()[j];// + 1.e-6;\n    }\n  }\n  int leading_minor_index = ComputeCholeskyFactorL(num_union*(1+num_gradients_to_sample), cholesky_to_sample_var.data());\n  if (unlikely(leading_minor_index != 0)) {\n    OL_THROW_EXCEPTION(SingularMatrixException,\n    \"GP-Variance matrix singular. Check for duplicate points_to_sample/being_sampled or points_to_sample/being_sampled duplicating points_sampled with 0 noise.\",\n    cholesky_to_sample_var.data(), num_union*(1+num_gradients_to_sample), leading_minor_index);\n  }\n  ZeroUpperTriangle(num_union*(1+num_gradients_to_sample), cholesky_to_sample_var.data());\n}\n\ntemplate struct KnowledgeGradientState<TensorProductDomain>;\ntemplate struct KnowledgeGradientState<SimplexIntersectTensorProductDomain>;\n\nPosteriorMeanEvaluator::PosteriorMeanEvaluator(\n  const GaussianProcess& gaussian_process_in)\n  : dim_(gaussian_process_in.dim()),\n    gaussian_process_(&gaussian_process_in) {\n}\n\n/*!\\rst\n  Uses analytic formulas to compute EI when ``num_to_sample = 1`` and ``num_being_sampled = 0`` (occurs only in 1,0-EI).\n  In this case, the single-parameter (posterior) GP is just a Gaussian.  So the integral in EI (previously eval'd with MC)\n  can be computed 'exactly' using high-accuracy routines for the pdf & cdf of a Gaussian random variable.\n  See Ginsbourger, Le Riche, and Carraro.\n\\endrst*/\ndouble PosteriorMeanEvaluator::ComputePosteriorMean(StateType * ps_state) const {\n  double to_sample_mean;\n  gaussian_process_->ComputeMeanOfAdditionalPoints(ps_state->point_to_sample.data(),\n                                                   1, nullptr, 0,\n                                                   &to_sample_mean);\n  return -to_sample_mean;\n}\n\n/*!\\rst\n  Differentiates OnePotentialSampleExpectedImprovementEvaluator::ComputeExpectedImprovement wrt\n  ``points_to_sample`` (which is just ONE point; i.e., 1,0-EI).\n  Again, this uses analytic formulas in terms of the pdf & cdf of a Gaussian since the integral in EI (and grad EI)\n  can be evaluated exactly for this low dimensional case.\n  See Ginsbourger, Le Riche, and Carraro.\n\\endrst*/\nvoid PosteriorMeanEvaluator::ComputeGradPosteriorMean(\n    StateType * ps_state,\n    double * restrict grad_PS) const {\n  double * restrict grad_mu = ps_state->grad_mu.data();\n  gaussian_process_->ComputeGradMeanOfAdditionalPoints(ps_state->point_to_sample.data(),\n                                                       1, nullptr, 0,\n                                                       grad_mu);\n  for (int i = 0; i < dim_-ps_state->num_fidelity; ++i) {\n    grad_PS[i] = -grad_mu[i];\n  }\n}\n\nvoid PosteriorMeanState::SetCurrentPoint(const EvaluatorType& ps_evaluator,\n                                         double const * restrict point_to_sample_in) {\n  // update current point in union_of_points\n  std::copy(point_to_sample_in, point_to_sample_in + dim - num_fidelity, point_to_sample.data());\n  std::fill(point_to_sample.data() + dim - num_fidelity, point_to_sample.data() + dim, 1.0);\n}\n\nPosteriorMeanState::PosteriorMeanState(\n  const EvaluatorType& ps_evaluator,\n  const int num_fidelity_in,\n  double const * restrict point_to_sample_in,\n  bool configure_for_gradients)\n  : dim(ps_evaluator.dim()),\n    num_fidelity(num_fidelity_in),\n    num_derivatives(configure_for_gradients ? num_to_sample : 0),\n    point_to_sample(BuildUnionOfPoints(point_to_sample_in)),\n    grad_mu(dim*num_derivatives) {\n}\nPosteriorMeanState::PosteriorMeanState(PosteriorMeanState&& OL_UNUSED(other)) = default;\n\n//void PosteriorMeanState::SetupState(const EvaluatorType& ps_evaluator,\n//                                    double const * restrict point_to_sample_in) {\n//  if (unlikely(dim != ps_evaluator.dim())) {\n//    OL_THROW_EXCEPTION(InvalidValueException<int>, \"Evaluator's and State's dim do not match!\", dim, ps_evaluator.dim());\n//  }\n//\n//  SetCurrentPoint(ps_evaluator, point_to_sample_in);\n//}\n\n/*!\\rst\n  Perform multistart gradient descent (MGD) to solve the q,p-EI problem (see ComputeOptimalPointsToSample and/or\n  header docs), starting from ``num_multistarts`` points selected randomly from the within th domain.\n  This function is a simple wrapper around ComputeOptimalPointsToSampleViaMultistartGradientDescent(). It additionally\n  generates a set of random starting points and is just here for convenience when better initial guesses are not\n  available.\n  See ComputeOptimalPointsToSampleViaMultistartGradientDescent() for more details.\n  \\param\n    :gaussian_process: GaussianProcess object (holds ``points_sampled``, ``values``, ``noise_variance``, derived quantities)\n      that describes the underlying GP\n    :optimizer_parameters: GradientDescentParameters object that describes the parameters controlling EI optimization\n      (e.g., number of iterations, tolerances, learning rate)\n    :domain: object specifying the domain to optimize over (see ``gpp_domain.hpp``)\n    :thread_schedule: struct instructing OpenMP on how to schedule threads; i.e., (suggestions in parens)\n      max_num_threads (num cpu cores), schedule type (omp_sched_dynamic), chunk_size (0).\n    :points_being_sampled[dim][num_being_sampled]: points that are being sampled in concurrent experiments\n    :num_to_sample: number of potential future samples; gradients are evaluated wrt these points (i.e., the \"q\" in q,p-EI)\n    :num_being_sampled: number of points being sampled concurrently (i.e., the \"p\" in q,p-EI)\n    :best_so_far: value of the best sample so far (must be ``min(points_sampled_value)``)\n    :max_int_steps: maximum number of MC iterations\n    :uniform_generator[1]: a UniformRandomGenerator object providing the random engine for uniform random numbers\n    :normal_rng[thread_schedule.max_num_threads]: a vector of NormalRNG objects that provide\n      the (pesudo)random source for MC integration\n  \\output\n    :found_flag[1]: true if best_next_point corresponds to a nonzero EI\n    :uniform_generator[1]: UniformRandomGenerator object will have its state changed due to random draws\n    :normal_rng[thread_schedule.max_num_threads]: NormalRNG objects will have their state changed due to random draws\n    :best_next_point[dim][num_to_sample]: points yielding the best EI according to MGD\n\\endrst*/\ntemplate <typename DomainType>\nvoid ComputeOptimalPosteriorMean(const GaussianProcess& gaussian_process, const int num_fidelity,\n                                 const GradientDescentParameters& optimizer_parameters,\n                                 const DomainType& domain, double const * restrict initial_guess, const int num_starts,\n                                 bool * restrict found_flag, double * restrict best_next_point, double * best_function_value) {\n  if (unlikely(optimizer_parameters.max_num_restarts <= 0)) {\n    return;\n  }\n  bool configure_for_gradients = true;\n  OL_VERBOSE_PRINTF(\"Posterior Mean Optimization via %s:\\n\", OL_CURRENT_FUNCTION_NAME);\n\n  // special analytic case when we are not using (or not accounting for) multiple, simultaneous experiments\n  PosteriorMeanEvaluator ps_evaluator(gaussian_process);\n  typename PosteriorMeanEvaluator::StateType ps_state(ps_evaluator, num_fidelity, initial_guess, configure_for_gradients);\n\n  std::priority_queue<std::pair<double, int>> q;\n  double val;\n  int k = std::min(1, num_starts); // number of indices we need\n  for (int i = 0; i < num_starts; ++i) {\n    ps_state.SetCurrentPoint(ps_evaluator, initial_guess + i*(gaussian_process.dim()-num_fidelity));\n    val = ps_evaluator.ComputePosteriorMean(&ps_state);\n    if (i < k){\n      q.push(std::pair<double, int>(-val, i));\n    }\n    else{\n      if (q.top().first > -val){\n        q.pop();\n        q.push(std::pair<double, int>(-val, i));\n      }\n    }\n  }\n\n  std::vector<double> top_k_starting(k*(gaussian_process.dim()-num_fidelity));\n  for (int i = 0; i < k; ++i) {\n    int ki = q.top().second;\n    for (int d = 0; d<gaussian_process.dim()-num_fidelity; ++d){\n      top_k_starting[i*(gaussian_process.dim()-num_fidelity) + d] = initial_guess[ki*(gaussian_process.dim()-num_fidelity) + d];\n    }\n    q.pop();\n  }\n\n  GradientDescentOptimizerLineSearch<PosteriorMeanEvaluator, DomainType> gd_opt;\n  double function_value_temp = -INFINITY;\n  *best_function_value = -INFINITY;\n  for (int i = 0; i < k; ++i){\n    ps_state.SetCurrentPoint(ps_evaluator, top_k_starting.data() + i*(gaussian_process.dim()-num_fidelity));\n    gd_opt.Optimize(ps_evaluator, optimizer_parameters, domain, &ps_state);\n    function_value_temp = ps_evaluator.ComputePosteriorMean(&ps_state);\n    if (function_value_temp > *best_function_value){\n      *best_function_value = function_value_temp;\n      ps_state.GetCurrentPoint(best_next_point);\n    }\n  }\n}\n\n// template explicit instantiation definitions, see gpp_common.hpp header comments, item 6\ntemplate void ComputeOptimalPosteriorMean(const GaussianProcess& gaussian_process, const int num_fidelity,\n                                          const GradientDescentParameters& optimizer_parameters,\n                                          const TensorProductDomain& domain, double const * restrict initial_guess, const int num_starts,\n                                          bool * restrict found_flag, double * restrict best_next_point, double * best_function_value);\ntemplate void ComputeOptimalPosteriorMean(const GaussianProcess& gaussian_process, const int num_fidelity,\n                                          const GradientDescentParameters& optimizer_parameters,\n                                          const SimplexIntersectTensorProductDomain& domain, double const * restrict initial_guess, const int num_starts,\n                                          bool * restrict found_flag, double * restrict best_next_point, double * best_function_value);\n\n/*!\\rst\n  This is a simple wrapper around ComputeKGOptimalPointsToSampleWithRandomStarts() and\n  ComputeKGOptimalPointsToSampleViaLatinHypercubeSearch(). That is, this method attempts multistart gradient descent\n  and falls back to latin hypercube search if gradient descent fails (or is not desired).\n\\endrst*/\ntemplate <typename DomainType>\nvoid ComputeKGOptimalPointsToSample(const GaussianProcess& gaussian_process, const int num_fidelity,\n                                    const GradientDescentParameters& optimizer_parameters,\n                                    const GradientDescentParameters& optimizer_parameters_inner,\n                                    const DomainType& domain, const DomainType& inner_domain, const ThreadSchedule& thread_schedule,\n                                    double const * restrict points_being_sampled,\n                                    double const * discrete_pts,\n                                    int num_to_sample, int num_being_sampled,\n                                    int num_pts, double best_so_far,\n                                    int max_int_steps, bool lhc_search_only,\n                                    int num_lhc_samples, bool * restrict found_flag,\n                                    UniformRandomGenerator * uniform_generator,\n                                    NormalRNG * normal_rng, double * restrict best_points_to_sample) {\n  if (unlikely(num_to_sample <= 0)) {\n    return;\n  }\n\n  std::vector<double> next_points_to_sample(gaussian_process.dim()*num_to_sample);\n  bool found_flag_local = false;\n  if (lhc_search_only == false) {\n    ComputeKGOptimalPointsToSampleWithRandomStarts(gaussian_process, num_fidelity, optimizer_parameters, optimizer_parameters_inner,\n                                                   domain, inner_domain, thread_schedule, points_being_sampled, discrete_pts,\n                                                   num_to_sample, num_being_sampled, num_pts,\n                                                   best_so_far, max_int_steps,\n                                                   &found_flag_local, uniform_generator, normal_rng,\n                                                   next_points_to_sample.data());\n  }\n\n  // if gradient descent EI optimization failed OR we're only doing latin hypercube searches\n  if (found_flag_local == false || lhc_search_only == true) {\n    if (unlikely(lhc_search_only == false)) {\n      OL_WARNING_PRINTF(\"WARNING: %d,%d-KG opt DID NOT CONVERGE\\n\", num_to_sample, num_being_sampled);\n      OL_WARNING_PRINTF(\"Attempting latin hypercube search\\n\");\n    }\n\n    if (num_lhc_samples > 0) {\n      // Note: using a schedule different than \"static\" may lead to flakiness in monte-carlo KG optimization tests.\n      // Besides, this is the fastest setting.\n      ThreadSchedule thread_schedule_naive_search(thread_schedule);\n      thread_schedule_naive_search.schedule = omp_sched_static;\n      ComputeKGOptimalPointsToSampleViaLatinHypercubeSearch(gaussian_process, num_fidelity, optimizer_parameters_inner, domain, inner_domain,\n                                                            thread_schedule_naive_search,\n                                                            points_being_sampled, discrete_pts,\n                                                            num_lhc_samples, num_to_sample,\n                                                            num_being_sampled, num_pts, best_so_far,\n                                                            max_int_steps,\n                                                            &found_flag_local, uniform_generator,\n                                                            normal_rng, next_points_to_sample.data());\n\n      // if latin hypercube 'dumb' search failed\n      if (unlikely(found_flag_local == false)) {\n        OL_ERROR_PRINTF(\"ERROR: %d,%d-KG latin hypercube search FAILED on\\n\", num_to_sample, num_being_sampled);\n      }\n    } else {\n      OL_WARNING_PRINTF(\"num_lhc_samples <= 0. Skipping latin hypercube search\\n\");\n    }\n  }\n\n  // set outputs\n  *found_flag = found_flag_local;\n  std::copy(next_points_to_sample.begin(), next_points_to_sample.end(), best_points_to_sample);\n}\n\n// template explicit instantiation definitions, see gpp_common.hpp header comments, item 6\ntemplate void ComputeKGOptimalPointsToSample(\n    const GaussianProcess& gaussian_process, const int num_fidelity, const GradientDescentParameters& optimizer_parameters,\n    const GradientDescentParameters& optimizer_parameters_inner,\n    const TensorProductDomain& domain, const TensorProductDomain& inner_domain, const ThreadSchedule& thread_schedule,\n    double const * restrict points_being_sampled, double const * discrete_pts,\n    int num_to_sample, int num_being_sampled,\n    int num_pts, double best_so_far, int max_int_steps, bool lhc_search_only,\n    int num_lhc_samples, bool * restrict found_flag, UniformRandomGenerator * uniform_generator,\n    NormalRNG * normal_rng, double * restrict best_points_to_sample);\ntemplate void ComputeKGOptimalPointsToSample(\n    const GaussianProcess& gaussian_process, const int num_fidelity, const GradientDescentParameters& optimizer_parameters,\n    const GradientDescentParameters& optimizer_parameters_inner,\n    const SimplexIntersectTensorProductDomain& domain, const SimplexIntersectTensorProductDomain& inner_domain, const ThreadSchedule& thread_schedule,\n    double const * restrict points_being_sampled,double const * discrete_pts,\n    int num_to_sample, int num_being_sampled, int num_pts, double best_so_far, int max_int_steps, bool lhc_search_only, int num_lhc_samples, bool * restrict found_flag,\n    UniformRandomGenerator * uniform_generator, NormalRNG * normal_rng, double * restrict best_points_to_sample);\n}  // end namespace optimal_learning\n", "meta": {"hexsha": "814a0f8a7b32e03e25dfc852d830a746c00d36ca", "size": 32769, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "moe/optimal_learning/cpp/gpp_knowledge_gradient_optimization.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_knowledge_gradient_optimization.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_knowledge_gradient_optimization.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": 57.4894736842, "max_line_length": 181, "alphanum_fraction": 0.690225518, "num_tokens": 7218, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6619228758499942, "lm_q2_score": 0.5273165233795671, "lm_q1q2_score": 0.3490428696386238}}
{"text": "/****************************************************************\n\n  jjjt_operator.cpp\n\n  Mark A. Caprio, University of Notre Dame.\n\n****************************************************************/\n\n#include <cassert>\n#include <cmath>\n#include <cstddef>\n#include <cstdlib>\n#include <iomanip>\n#include <ostream>\n#include <tuple>\n#include <vector>\n\n#include \"jjjt_operator.h\"\n\n#include \"am/halfint.h\"\n#include <Eigen/Core>\n#include \"basis.h\"\n#include \"many_body.h\"\n#include \"jjjt_scheme.h\"\n#include \"jt_operator.h\"\n#include \"operator.h\"\n\nnamespace basis {\n\n  ////////////////////////////////////////////////////////////////\n  // two-body JJJT operator -- gather N blocks\n  ////////////////////////////////////////////////////////////////\n\n  inline\n  void RecastLabelsTwoBodyJJJTToTwoBodyJJJTN(\n      const TwoBodySubspaceJJJTLabels& two_body_jjjt_subspace_labels,\n      const TwoBodyStateJJJTLabels& two_body_jjjt_state_labels,\n      TwoBodySubspaceJJJTNLabels& two_body_jjjtn_subspace_labels,\n      TwoBodyStateJJJTNLabels& two_body_jjjtn_state_labels\n    )\n  // Recast labels for (subspace,state) from TwoBodyJJJT scheme to\n  // TwoBodyJJJTN scheme.\n  //\n  // This direction of conversion (from target labels to source\n  // labels) is as needed for looking up the source matrix element.\n  //\n  // This switches N from being the most-significant state label (that\n  // is, least-rapidly-varying in the lexicographic ordering scheme),\n  // to being the least-significant subspace label (that is,\n  // most-rapidly-varying):\n  //\n  //   (L,S,J,T,g) : ([N],N1,l1,N2,l2) -> (L,S,J,T,g,N) : (N1,l1,N2,l2)\n  //\n  // As a state label, N is actually an implicit label, not stored,\n  // but effectively the first label for ordering purposes.  Its value\n  // may be recovered as N1+N2.\n  //\n  // Arguments:\n  //   two_body_jjjt_subspace_labels (...) : source subspace labels\n  //   two_body_jjjt_state_labels (...) : source state labels\n  //   two_body_jjjtn_subspace_labels (...,output) : target subspace labels\n  //   two_body_jjjtn_state_labels (...,output) : target state labels\n  {\n    // extract labels\n    int J, T, g;\n    std::tie(J,T,g) = two_body_jjjt_subspace_labels;\n    int N1, l1, N2, l2;\n    HalfInt j1, j2;\n    std::tie(N1,j1,N2,j2) = two_body_jjjt_state_labels;\n\n    // repackage labels\n    int N = N1+N2;\n    two_body_jjjtn_subspace_labels = TwoBodySubspaceJJJTNLabels(J,T,g,N);\n    two_body_jjjtn_state_labels = two_body_jjjt_state_labels;\n  }\n\n  void GatherOperatorTwoBodyJJJTNToTwoBodyJJJT(\n      const basis::OperatorLabelsJT& operator_labels,\n      const basis::TwoBodySpaceJJJTN& two_body_jjjtn_space,\n      const std::array<basis::TwoBodySectorsJJJTN,3>& two_body_jjjtn_component_sectors,\n      const std::array<basis::OperatorBlocks<double>,3>& two_body_jjjtn_component_matrices,\n      const basis::TwoBodySpaceJJJT& two_body_jjjt_space,\n      std::array<basis::TwoBodySectorsJJJT,3>& two_body_jjjt_component_sectors,\n      std::array<basis::OperatorBlocks<double>,3>& two_body_jjjt_component_matrices\n    )\n  {\n  for (int T0=operator_labels.T0_min; T0<=operator_labels.T0_max; ++T0)\n    // for each isospin component\n    {\n\n      // enumerate sectors\n      two_body_jjjt_component_sectors[T0]\n        = basis::TwoBodySectorsJJJT(two_body_jjjt_space,operator_labels.J0,T0,operator_labels.g0);\n\n      // populate matrices\n      two_body_jjjt_component_matrices[T0].resize(two_body_jjjt_component_sectors[T0].size());\n      for (std::size_t sector_index=0; sector_index<two_body_jjjt_component_sectors[T0].size(); ++sector_index)\n        {\n          // retrieve target sector\n          const basis::TwoBodySectorsJJJT::SectorType& two_body_jjjt_sector\n            = two_body_jjjt_component_sectors[T0].GetSector(sector_index);\n\n          // initialize matrix\n          Eigen::MatrixXd& two_body_jjjt_matrix = two_body_jjjt_component_matrices[T0][sector_index];\n          two_body_jjjt_matrix = Eigen::MatrixXd::Zero(\n              two_body_jjjt_sector.bra_subspace().size(),\n              two_body_jjjt_sector.ket_subspace().size()\n            );\n\n          // populate matrix elements\n          for (std::size_t bra_index = 0; bra_index < two_body_jjjt_sector.bra_subspace().size(); ++bra_index)\n            for (std::size_t ket_index = 0; ket_index < two_body_jjjt_sector.ket_subspace().size(); ++ket_index)\n              // for each target matrix element\n              {\n\n                // ensure canonical matrix element if diagonal sector\n                if (two_body_jjjt_sector.IsDiagonal())\n                  if (!(bra_index<=ket_index))\n                    continue;\n\n                // retrieve target states\n                basis::TwoBodyStateJJJT two_body_jjjt_bra(two_body_jjjt_sector.bra_subspace(),bra_index);\n                basis::TwoBodyStateJJJT two_body_jjjt_ket(two_body_jjjt_sector.ket_subspace(),ket_index);\n\n                // extract source bra labels\n                TwoBodySubspaceJJJTLabels two_body_jjjt_subspace_labels_bra\n                  = two_body_jjjt_bra.subspace().labels();\n                TwoBodyStateJJJTLabels two_body_jjjt_state_labels_bra\n                  = two_body_jjjt_bra.labels();\n                TwoBodySubspaceJJJTNLabels two_body_jjjtn_subspace_labels_bra;\n                TwoBodyStateJJJTNLabels two_body_jjjtn_state_labels_bra;\n                RecastLabelsTwoBodyJJJTToTwoBodyJJJTN(\n                    two_body_jjjt_subspace_labels_bra,\n                    two_body_jjjt_state_labels_bra,\n                    two_body_jjjtn_subspace_labels_bra,\n                    two_body_jjjtn_state_labels_bra\n                  );\n\n                // extract source bra indices\n                std::size_t two_body_jjjtn_subspace_index_bra\n                  = two_body_jjjtn_space.LookUpSubspaceIndex(\n                      two_body_jjjtn_subspace_labels_bra\n                    );\n                std::size_t two_body_jjjtn_state_index_bra\n                  = two_body_jjjtn_space.GetSubspace(two_body_jjjtn_subspace_index_bra).LookUpStateIndex(\n                      two_body_jjjtn_state_labels_bra\n                    );\n\n                // extract source ket labels\n                TwoBodySubspaceJJJTLabels two_body_jjjt_subspace_labels_ket\n                  = two_body_jjjt_ket.subspace().labels();\n                TwoBodyStateJJJTLabels two_body_jjjt_state_labels_ket\n                  = two_body_jjjt_ket.labels();\n                TwoBodySubspaceJJJTNLabels two_body_jjjtn_subspace_labels_ket;\n                TwoBodyStateJJJTNLabels two_body_jjjtn_state_labels_ket;\n                RecastLabelsTwoBodyJJJTToTwoBodyJJJTN(\n                    two_body_jjjt_subspace_labels_ket,\n                    two_body_jjjt_state_labels_ket,\n                    two_body_jjjtn_subspace_labels_ket,\n                    two_body_jjjtn_state_labels_ket\n                  );\n\n                // extract source ket indices\n                std::size_t two_body_jjjtn_subspace_index_ket\n                  = two_body_jjjtn_space.LookUpSubspaceIndex(\n                      two_body_jjjtn_subspace_labels_ket\n                    );\n                std::size_t two_body_jjjtn_state_index_ket\n                  = two_body_jjjtn_space.GetSubspace(two_body_jjjtn_subspace_index_ket).LookUpStateIndex(\n                      two_body_jjjtn_state_labels_ket\n                    );\n\n                // look up matrix element\n                std::size_t two_body_jjjtn_sector_index\n                  = two_body_jjjtn_component_sectors[T0].LookUpSectorIndex(\n                      two_body_jjjtn_subspace_index_bra,\n                      two_body_jjjtn_subspace_index_ket\n                    );\n\n                const Eigen::MatrixXd& two_body_jjjtn_matrix\n                  = two_body_jjjtn_component_matrices[T0][two_body_jjjtn_sector_index];\n                double two_body_jjjtn_matrix_element = two_body_jjjtn_matrix(\n                    two_body_jjjtn_state_index_bra,two_body_jjjtn_state_index_ket\n                  );\n\n                two_body_jjjt_matrix(bra_index,ket_index) = two_body_jjjtn_matrix_element;\n\n              }\n        }\n    }\n\n  }\n\n  ////////////////////////////////////////////////////////////////\n  // two-body JJJT operator output\n  ////////////////////////////////////////////////////////////////\n\n  void WriteTwoBodyOperatorComponentJJJT(\n      std::ostream& os,\n      int T0,\n      const TwoBodySectorsJJJT& sectors,\n      const OperatorBlocks<double>& matrices,\n      basis::NormalizationConversion conversion_mode\n    )\n  {\n\n    // iterate over sectors\n    for (std::size_t sector_index = 0; sector_index < sectors.size(); ++sector_index)\n      {\n\n        // extract sector\n        const typename TwoBodySectorsJJJT::SectorType& sector = sectors.GetSector(sector_index);\n        const typename TwoBodySectorsJJJT::SubspaceType& bra_subspace = sector.bra_subspace();\n        const typename TwoBodySectorsJJJT::SubspaceType& ket_subspace = sector.ket_subspace();\n\n        // verify that sector is canonical\n        //\n        // This is a check that the caller's sector construction\n        // followed the specification that only \"upper triangle\"\n        // sectors are stored.\n        assert(sector.bra_subspace_index()<=sector.ket_subspace_index());\n\n        // iterate over matrix elements\n        for (std::size_t bra_index=0; bra_index<bra_subspace.size(); ++bra_index)\n          for (std::size_t ket_index=0; ket_index<ket_subspace.size(); ++ket_index)\n            {\n\n              // diagonal sector: restrict to upper triangle\n              if (sector.IsDiagonal())\n                if (!(bra_index<=ket_index))\n                  continue;\n\n              // define states\n              const basis::TwoBodyStateJJJT bra(bra_subspace,bra_index);\n              const basis::TwoBodyStateJJJT ket(ket_subspace,ket_index);\n\n              // determine matrix element normalization factor\n              double conversion_factor = 1.;\n              if (conversion_mode == basis::NormalizationConversion::kASToNAS)\n                {\n                  if ((bra.N1()==bra.N2())&&(bra.l1()==bra.l2())&&(bra.j1()==bra.j2()))\n                    conversion_factor *= (1/sqrt(2.));\n                  if ((ket.N1()==ket.N2())&&(ket.l1()==ket.l2())&&(ket.j1()==ket.j2()))\n                    conversion_factor *= (1/sqrt(2.));\n                }\n              else if (conversion_mode == basis::NormalizationConversion::kNASToAS)\n                {\n                  if ((bra.N1()==bra.N2())&&(bra.l1()==bra.l2())&&(bra.j1()==bra.j2()))\n                    conversion_factor *= sqrt(2.);\n                  if ((ket.N1()==ket.N2())&&(ket.l1()==ket.l2())&&(ket.j1()==ket.j2()))\n                    conversion_factor *= sqrt(2.);\n                }\n\n              // extract matrix element\n              const double matrix_element = conversion_factor*matrices[sector_index](bra_index,ket_index);\n\n              // generate output line\n              const int width = 3;\n              const int precision = 8;  // for approximately single precision output\n              os << std::setprecision(precision);\n              os\n                << \" \" << std::setw(width) << T0\n                << \" \" << \"  \"\n                << \" \" << std::setw(width) << bra.N1()\n                << \" \" << std::setw(width) << bra.l1()\n                << \" \" << std::showpoint << std::fixed << std::setprecision(1) << std::setw(4) << float(bra.j1())\n                << \" \" << std::setw(width) << bra.N2()\n                << \" \" << std::setw(width) << bra.l2()\n                << \" \" << std::showpoint << std::fixed << std::setprecision(1) << std::setw(4) << float(bra.j2())\n                << \" \" << std::setw(width) << bra.J()\n                << \" \" << std::setw(width) << bra.T()\n                << \" \" << std::setw(width) << bra.g()\n                << \" \" << \"    \"\n                << \" \" << std::setw(width) << ket.N1()\n                << \" \" << std::setw(width) << ket.l1()\n                << \" \" << std::showpoint << std::fixed << std::setprecision(1) << std::setw(4) << float(ket.j1())\n                << \" \" << std::setw(width) << ket.N2()\n                << \" \" << std::setw(width) << ket.l2()\n                << \" \" << std::showpoint << std::fixed << std::setprecision(1) << std::setw(4) << float(ket.j2())\n                << \" \" << std::setw(width) << ket.J()\n                << \" \" << std::setw(width) << ket.T()\n                << \" \" << std::setw(width) << ket.g()\n                << \" \" << \"    \"\n                << \" \" << std::showpoint << std::scientific << std::setprecision(precision) << matrix_element\n                << std::endl;\n\n            }\n\n      }\n  }\n\n  ////////////////////////////////////////////////////////////////\n  ////////////////////////////////////////////////////////////////\n} // namespace\n", "meta": {"hexsha": "0f61bc64e6cfefc4893a063fba217ac2e3ac7243", "size": 12755, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "jjjt_operator.cpp", "max_stars_repo_name": "nd-nuclear-theory/basis", "max_stars_repo_head_hexsha": "11a743a8aedd7354347ddb8b300ad14ac018ee98", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "jjjt_operator.cpp", "max_issues_repo_name": "nd-nuclear-theory/basis", "max_issues_repo_head_hexsha": "11a743a8aedd7354347ddb8b300ad14ac018ee98", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "jjjt_operator.cpp", "max_forks_repo_name": "nd-nuclear-theory/basis", "max_forks_repo_head_hexsha": "11a743a8aedd7354347ddb8b300ad14ac018ee98", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-02-24T20:10:47.000Z", "max_forks_repo_forks_event_max_datetime": "2019-07-10T23:34:01.000Z", "avg_line_length": 43.2372881356, "max_line_length": 113, "alphanum_fraction": 0.5745197962, "num_tokens": 3056, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6619228758499942, "lm_q2_score": 0.5273165233795671, "lm_q1q2_score": 0.3490428696386238}}
{"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 gaussian.hpp\n * \\date October 2014\n * \\author Jan Issac (jan.issac@gmail.com)\n * \\author Manuel Wuthrich (manuel.wuthrich@gmail.com)\n */\n\n#pragma once\n\n\n#include <Eigen/Dense>\n\n#include <array>\n#include <string>\n#include <cstddef>\n#include <type_traits>\n\n#include <fl/util/traits.hpp>\n#include <fl/exception/exception.hpp>\n#include <fl/distribution/interface/moments.hpp>\n#include <fl/distribution/interface/evaluation.hpp>\n#include <fl/distribution/interface/standard_gaussian_mapping.hpp>\n\nnamespace fl\n{\n\n/**\n * \\ingroup exceptions\n *\n * Exception used in case of accessing dynamic-size distribution attributes\n * without initializing the Gaussian using a dimension greater 0.\n */\nclass GaussianUninitializedException\n    : public Exception\n{\npublic:\n    /**\n     * Creates a GaussianUninitializedException\n     */\n    GaussianUninitializedException()\n        : Exception(\"Accessing uninitialized dynamic-size distribution. \"\n                    \"Gaussian dimension is 0. \"\n                    \"Use ::dimension(dimension) to initialize the \"\n                    \"distribution!\") { }\n\n    /**\n     * \\return Exception name\n     */\n    virtual std::string name() const noexcept\n    {\n        return \"fl::GaussianUninitializedException\";\n    }\n};\n\n/**\n * \\ingroup exceptions\n *\n * Exception representing a unsupported representation ID\n */\nclass InvalidGaussianRepresentationException\n    : public Exception\n{\npublic:\n    /**\n     * Creates an InvalidGaussianRepresentationException\n     */\n    InvalidGaussianRepresentationException()\n        : Exception(\"Invalid Gaussian covariance representation\") { }\n\n    /**\n     * \\return Exception name\n     */\n    virtual std::string name() const noexcept\n    {\n        return \"fl::InvalidGaussianRepresentationException\";\n    }\n};\n\n\n/**\n * \\class Gaussian\n *\n * \\brief General Gaussian Distribution\n * \\ingroup distributions\n * \\{\n *\n * The Gaussian is a general purpose distribution representing a multi-variate\n * \\f${\\cal N}(x; \\mu, \\Sigma)\\f$. It can be used in various\n * ways while maintaining efficienty at the same time. This is due to it's\n * multi-representation structure. The distribution can be represented either by\n *\n *  - the covariance matrix \\f$\\Sigma\\f$,\n *  - the precision matrix \\f$\\Sigma^{-1} = \\Lambda\\f$,\n *  - the covariance square root matrix (Cholesky decomposition or LDLT)\n *    \\f$\\sqrt{\\Sigma} = L\\sqrt{D}\\f$,\n *  - or the diagonal form of the previous three options\n *    \\f$diag(\\sigma_1, \\ldots, \\sigma_n)\\f$.\n *\n * A change in one representation results in change of all other\n * representations.\n *\n * Two key features of the distribution are its aibility to evaluation the\n * probability of a given sample and to map a noise sample into the distribution\n * sample space.\n *\n * \\cond internal\n * The Gaussian internal structure uses lazy assignments or write on read\n * technique. Due to the multi-representation of the Gaussian, modifying one\n * representation affects all remaining ones. If one of the representation is\n * modified, the other representations are only then updated when needed. This\n * minimizes redundant computation and increases efficienty.\n * \\endcond\n */\ntemplate <typename Variate>\nclass Gaussian\n    : public Moments<Variate>,\n      public Evaluation<Variate>,\n      public StandardGaussianMapping<Variate, SizeOf<Variate>::Value>\n{\nprivate:\n    typedef StandardGaussianMapping<\n                Variate,\n                SizeOf<Variate>::Value\n            > StdGaussianMappingBase;\n\npublic:\n    /**\n     * \\brief Second moment matrix type, i.e covariance matrix, precision\n     *        matrix, and their diagonal and square root representations\n     */\n    typedef typename Moments<Variate>::SecondMoment SecondMoment;\n\n    /**\n     * \\brief Represents the StandardGaussianMapping standard variate type which\n     *        is of the same dimension as the Gaussian Variate. The\n     *        StandardVariate type is used to sample from a standard normal\n     *        Gaussian and map it to this Gaussian\n     */\n    typedef typename StdGaussianMappingBase::StandardVariate StandardVariate;\n\nprotected:\n    /** \\cond internal */\n    /**\n     * \\enum Attribute\n     * Implementation attributes. The enumeration lists the different\n     * representations along with other properties such as the rank of the\n     * second moment and the log normalizer.\n     */\n    enum Attribute\n    {\n        CovarianceMatrix = 0,     /**< Covariance mat. */\n        PrecisionMatrix,          /**< Inverse of the cov. mat. */\n        SquareRootMatrix,         /**< Cholesky decomp. of the cov. mat. */\n        DiagonalCovarianceMatrix, /**< Diagonal form of the of cov. mat. */\n        DiagonalPrecisionMatrix,  /**< Diagonal form of the inv cov. mat. */\n        DiagonalSquareRootMatrix, /**< Diagonal form of the Cholesky decomp. */\n        Rank,                     /**< Covariance Rank */\n        Normalizer,               /**< Log probability normalizer */\n        Determinant,              /**< Determinant of covariance */\n\n        Attributes                /**< Total number of attribute */\n    };\n\n    /**\n     * \\brief Flags array type which contains the content status if different\n     *        distribution representation\n     */\n    typedef std::array<bool, Attributes> FlagArray;\n    /** \\endcond */\n\npublic:\n    /**\n     * Creates a dynamic or fixed size Gaussian.\n     *\n     * \\param dimension Dimension of the Gaussian. The default is defined by the\n     *                  dimension of the variable type \\em Vector. If the size\n     *                  of the Variate at compile time is fixed, this will be\n     *                  adapted. For dynamic-sized Variable the dimension is\n     *                  initialized to 0.\n     */\n    explicit Gaussian(int dim = DimensionOf<Variate>()):\n        StdGaussianMappingBase(dim)\n    {\n        static_assert(Variate::SizeAtCompileTime != 0,\n                      \"Illegal static dimension\");\n\n        std::fill(dirty_.begin(), dirty_.end(), true);\n        set_standard();\n    }\n\n    /**\n     * \\brief Overridable default destructor\n     */\n    virtual ~Gaussian() noexcept { }\n\n    /**\n     * \\return Gaussian dimension\n     */\n    virtual int dimension() const\n    {\n        return StdGaussianMappingBase::standard_variate_dimension();\n    }\n\n    /**\n     * \\return Gaussian first moment\n     */\n    virtual const Variate& mean() const\n    {\n        return mean_;\n    }\n\n    /**\n     * \\return Gaussian second centered moment\n     *\n     * Computes the covariance from other representation of not available\n     *\n     * \\throws GaussianUninitializedException if the Gaussian is of dynamic-size\n     *         and has not been initialized using SetStandard(dimension).\n     * \\throws InvalidGaussianRepresentationException if non-of theember function)\n     *         representation can be used as a source\n     */\n    virtual const SecondMoment& covariance() const\n    {\n        if (dimension() == 0)\n        {\n            fl_throw(GaussianUninitializedException());\n        }\n\n        if (is_dirty(CovarianceMatrix) && is_dirty(DiagonalCovarianceMatrix))\n        {\n            switch (select_first_representation<4>({{DiagonalSquareRootMatrix,\n                                                    DiagonalPrecisionMatrix,\n                                                    SquareRootMatrix,\n                                                    PrecisionMatrix}}))\n            {\n            case SquareRootMatrix:\n                covariance_ = square_root_ * square_root_.transpose();\n                break;\n\n            case PrecisionMatrix:\n                covariance_ = precision_.inverse();\n                break;\n\n            case DiagonalSquareRootMatrix:\n                covariance_.setZero(dimension(), dimension());\n                for (int i = 0; i < square_root_.diagonalSize(); ++i)\n                {\n                    covariance_(i, i) = square_root_(i, i) * square_root_(i, i);\n                }\n                break;\n\n            case DiagonalPrecisionMatrix:\n                covariance_.setZero(dimension(), dimension());\n                for (int i = 0; i < precision_.diagonalSize(); ++i)\n                {\n                    covariance_(i, i) = 1./precision_(i, i);\n                }\n                break;\n\n            default:\n                fl_throw(InvalidGaussianRepresentationException());\n                break;\n            }\n\n            updated_internally(CovarianceMatrix);\n        }\n\n        return covariance_;\n    }\n\n    /**\n     * \\return Gaussian second centered moment in the precision form (inverse\n     * of the covariance)\n     *\n     * Computes the precision from other representation of not available\n     *\n     * \\throws GaussianUninitializedException if the Gaussian is of dynamic-size\n     *         and has not been initialized using SetStandard(dimension).\n     * \\throws InvalidGaussianRepresentationException if non-of the\n     *         representation can be used as a source\n     */\n    virtual const SecondMoment& precision() const\n    {\n        if (dimension() == 0)\n        {\n            fl_throw(GaussianUninitializedException());\n        }\n\n        if (is_dirty(PrecisionMatrix) && is_dirty(DiagonalPrecisionMatrix))\n        {\n            const SecondMoment& cov = covariance();\n\n            switch (select_first_representation<4>({{DiagonalCovarianceMatrix,\n                                                    DiagonalSquareRootMatrix,\n                                                    CovarianceMatrix,\n                                                    SquareRootMatrix}}))\n            {\n            case CovarianceMatrix:\n            case SquareRootMatrix:\n                precision_ = covariance().inverse();\n                break;\n\n            case DiagonalCovarianceMatrix:\n            case DiagonalSquareRootMatrix:\n                precision_.setZero(dimension(), dimension());\n                for (int i = 0; i < cov.rows(); ++i)\n                {\n                    precision_(i, i) = 1./cov(i, i);\n                }\n                break;\n\n            default:\n                fl_throw(InvalidGaussianRepresentationException());\n                break;\n            }\n\n            updated_internally(PrecisionMatrix);\n        }\n\n        return precision_;\n    }\n\n\n    /**\n     * \\return Gaussian second centered moment in the square root form (\n     * Cholesky decomposition)\n     *\n     * Computes the square root from other representation of not available\n     *\n     * \\throws GaussianUninitializedException if the Gaussian is of dynamic-size\n     *         and has not been initialized using SetStandard(dimension).\n     * \\throws InvalidGaussianRepresentationException if non-of the\n     *         representation can be used as a source\n     */\n    virtual const SecondMoment& square_root() const\n    {\n        if (dimension() == 0)\n        {\n            fl_throw(GaussianUninitializedException());\n        }\n\n        if (is_dirty(SquareRootMatrix) && is_dirty(DiagonalSquareRootMatrix))\n        {\n            const SecondMoment& cov = covariance();\n\n            switch (select_first_representation<4>({{DiagonalCovarianceMatrix,\n                                                    DiagonalPrecisionMatrix,\n                                                    CovarianceMatrix,\n                                                    PrecisionMatrix}}))\n            {\n            case CovarianceMatrix:\n            case PrecisionMatrix:\n                fl::square_root(cov, square_root_);\n                break;\n\n            case DiagonalCovarianceMatrix:\n            case DiagonalPrecisionMatrix:\n                square_root_.setZero(dimension(), dimension());\n                for (int i = 0; i < square_root_.rows(); ++i)\n                {\n                    square_root_(i, i) = std::sqrt(cov(i, i));\n                }\n                break;\n\n            default:\n                fl_throw(InvalidGaussianRepresentationException());\n                break;\n            }\n\n            updated_internally(SquareRootMatrix);\n        }\n\n        return square_root_;\n    }\n\n    /**\n     * \\return True if the covariance matrix has a full rank\n     *\n     * \\throws see covariance()\n     */\n    virtual bool has_full_rank() const\n    {\n        if (is_dirty(Rank))\n        {\n            full_rank_ =\n               covariance().colPivHouseholderQr().rank() == covariance().rows();\n\n            updated_internally(Rank);\n        }\n\n        return full_rank_;\n    }\n\n    /**\n     * \\return Log normalizing constant\n     *\n     * \\throws see has_full_rank()\n     */\n    virtual Real log_normalizer() const\n    {\n        if (is_dirty(Normalizer))\n        {\n            if (has_full_rank())\n            {\n                log_norm_ =\n                    -0.5\n                    * (std::log(covariance_determinant())\n                       + Real(dimension()) * std::log(2.0 * M_PI));\n            }\n            else\n            {\n                log_norm_ = 0.0; // FIXME\n            }\n\n            updated_internally(Normalizer);\n        }\n\n        return log_norm_;\n    }\n\n    /**\n     * \\return Covariance determinant\n     *\n     * \\throws see covariance\n     */\n    virtual Real covariance_determinant() const\n    {\n        if (is_dirty(Determinant))\n        {\n            determinant_ = covariance().determinant();\n\n            updated_internally(Determinant);\n        }\n\n        return determinant_;\n    }\n\n    /**\n     * \\return Log of the probability of the given sample \\c vector\n     *\n     * \\param vector sample which should be evaluated\n     *\n     * \\throws see has_full_rank()\n     */\n    Real log_probability(const Variate& vector) const override\n    {\n        // assert(has_full_rank());\n\n        if(has_full_rank())\n        {\n            return log_normalizer() - 0.5\n                    * (vector - mean()).transpose()\n                    * precision()\n                    * (vector - mean());\n        }\n\n        return -std::numeric_limits<Real>::infinity();\n    }\n\n    /**\n     * \\return a Gaussian sample of the type \\c Variate determined by mapping a\n     * noise sample into the Gaussian sample space\n     *\n     * \\param sample    Noise Sample\n     *\n     * \\throws see square_root()\n     */\n    Variate map_standard_normal(const StandardVariate& sample) const override\n    {\n        return mean() + square_root() * sample;\n    }\n\n    /**\n     * Sets the Gaussian to a standard distribution with zero mean and identity\n     * covariance.\n     */\n    virtual void set_standard()\n    {\n        mean_.resize(dimension());\n        covariance_.resize(dimension(), dimension());\n        precision_.resize(dimension(), dimension());\n        square_root_.resize(dimension(), dimension());\n\n        mean(Variate::Zero(dimension()));\n        covariance(SecondMoment::Identity(dimension(), dimension()));\n\n        full_rank_ = true;\n        updated_internally(Rank);\n    }\n\n    /**\n     * Changes the dimension of the dynamic-size Gaussian and sets it to a\n     * standard distribution with zero mean and identity covariance.\n     *\n     * \\param new_dimension New dimension of the Gaussian\n     *\n     * \\throws ResizingFixedSizeEntityException\n     *         see GaussianMap::standard_variate_dimension(int)\n     */\n    virtual void dimension(int new_dimension)\n    {\n        StdGaussianMappingBase::standard_variate_dimension(new_dimension);\n        set_standard();\n    }\n\n    /**\n     * Sets the mean\n     *\n     * \\param mean New Gaussian mean\n     *\n     * \\throws WrongSizeException\n     */\n    virtual void mean(const Variate& mean) noexcept\n    {\n        if (mean_.size() != mean.size())\n        {\n            fl_throw(fl::WrongSizeException(mean.size(), mean_.size()));\n        }\n\n        mean_ = mean;\n    }\n\n    /**\n     * Sets the covariance matrix\n     * \\param covariance New covariance matrix\n     *\n     * \\throws WrongSizeException\n     */\n\n    virtual void covariance(const SecondMoment& covariance)\n    {\n        if (covariance_.size() != covariance.size())\n        {\n            fl_throw(fl::WrongSizeException(\n                         covariance.size(), covariance_.size()));\n        }\n\n        covariance_ = covariance;\n        updated_externally(CovarianceMatrix);\n    }\n\n    /**\n     * Sets the covariance matrix in the form of its square root (Cholesky f\n     * actor)\n     *\n     * \\param square_root New covariance square root\n     *\n     * \\throws WrongSizeException\n     */\n    virtual void square_root(const SecondMoment& square_root)\n    {\n        if (square_root_.size() != square_root.size())\n        {\n            fl_throw(fl::WrongSizeException(\n                         square_root.size(), square_root_.size()));\n        }\n\n        square_root_ = square_root;\n        updated_externally(SquareRootMatrix);\n    }\n\n    /**\n     * Sets the covariance matrix in the precision form (inverse of covariance)\n     *\n     * \\param precision New precision matrix\n     *\n     * \\throws WrongSizeException\n     */\n    virtual void precision(const SecondMoment& precision) noexcept\n    {\n        if (precision_.size() != precision.size())\n        {\n            fl_throw(fl::WrongSizeException(\n                         precision.size(), precision_.size()));\n        }\n\n        precision_ = precision;\n        updated_externally(PrecisionMatrix);\n    }\n\n    /**\n     * Sets the covariance matrix as a diagonal matrix\n     *\n     * \\param diag_covariance New diagonal covariance matrix\n     *\n     * \\throws WrongSizeException\n     */\n    virtual void diagonal_covariance(const SecondMoment& diag_covariance)\n    {\n        if (diag_covariance.size() != covariance_.size())\n        {\n            fl_throw(\n                fl::WrongSizeException(\n                    diag_covariance.size(), covariance_.size()));\n        }\n\n        covariance_ = diag_covariance.diagonal().asDiagonal();\n        updated_externally(DiagonalCovarianceMatrix);\n    }\n\n    /**\n     * Sets the covariance matrix in its diagonal square root form\n     *\n     * \\param diag_square_root New diagonal square root of the covariance\n     *\n     * \\throws WrongSizeException\n     */\n    virtual void diagonal_square_root(const SecondMoment& diag_square_root)\n    {\n        if (diag_square_root.size() != square_root_.size())\n        {\n            fl_throw(\n                fl::WrongSizeException(\n                    diag_square_root.size(), square_root_.size()));\n        }\n\n        square_root_ = diag_square_root.diagonal().asDiagonal();\n        updated_externally(DiagonalSquareRootMatrix);\n    }\n\n    /**\n     * Sets the covariance matrix in its diagonal precision form\n     *\n     * \\param diag_precision New diagonal precision matrix\n     *\n     * \\throws WrongSizeException\n     */\n    virtual void diagonal_precision(const SecondMoment& diag_precision)\n    {\n        if (diag_precision.size() != precision_.size())\n        {\n            fl_throw(\n                fl::WrongSizeException(\n                    diag_precision.size(), precision_.size()));\n        }\n\n        precision_ = diag_precision.diagonal().asDiagonal();\n        updated_externally(DiagonalPrecisionMatrix);\n    }\n\n    /**\n     * \\brief Returns true if the specified Gaussian is close to this one w.r.t.\n     *        \\a an epsilon.\n     *\n     * \\throws See covariance() and mean()\n     */\n    template <typename OtherVariate>\n    bool is_approx(const Gaussian<OtherVariate>& other)\n    {\n\n\n        return fl::are_similar(mean(), other.mean()) &&\n               fl::are_similar(covariance(), other.covariance());\n    }\n\n    /**\n     * \\brief Returns true if the specified Gaussian is close to this one w.r.t.\n     *        \\a an epsilon.\n     *\n     * \\throws See covariance() and mean()\n     */\n    template <typename OtherVariate>\n    bool is_approx(const Gaussian<OtherVariate>& other,\n                   Real eps = 1.e-9,\n                   bool scale_with_size = false)\n    {\n        Real eps_mean = eps;\n        Real eps_cov = eps;\n\n        if (scale_with_size)\n        {\n            eps_mean *= mean().size();\n            eps_cov *= covariance().size();\n        }\n\n        return fl::are_similar(mean(), other.mean(), eps_mean) &&\n               fl::are_similar(covariance(), other.covariance(), eps_cov);\n    }\n\nprotected:\n    /** \\cond internal */\n    /**\n     * Flags the specified attribute as valid and the rest of attributes as\n     * dirty.\n     *\n     * \\param attribute Modified attribute\n     */\n    void updated_externally(Attribute attribute) const noexcept\n    {\n        std::fill(dirty_.begin(), dirty_.end(), true);\n        updated_internally(attribute);\n    }\n\n    /**\n     * Flags the specified attribute as valid.\n     *\n     * \\param attribute Modified attribute\n     */\n    void updated_internally(Attribute attribute) const noexcept\n    {\n        dirty_[attribute] = false;\n    }\n\n    /**\n     * \\return True if any of the other representation was modified.\n     * \\param attribute     Attribute in question\n     */\n    bool is_dirty(Attribute attribute) const noexcept\n    {\n        return dirty_[int(attribute)];\n    }\n\n    /**\n     * \\return First representation ID that is available\n     *\n     * \\param representations   Representation list\n     *\n     * Example:\n     * If the last invoked functions were\n     *\n     * \\code\n     * diagonal_covariance(my_diagonal);\n     * my_covariance = covariance();\n     * \\endcode\n     *\n     * Now, the representation is set to \\c DiagonalCovarianceMatrix and\n     * \\c CovarianceMatrix since \\c diagonal_covariance() was used to set the\n     * covariance matrix followed by requesting \\c covariance().\n     * The following subsequent call\n     *\n     * \\code\n     * Attribute att = SelectRepresentation({SquareRoot,\n     *                                       DiagonalCovarianceMatrix,\n     *                                       CovarianceMatrix});\n     * \\endcode\n     *\n     * will assign att to DiagonalCovarianceMatrix since that is the first\n     * available representation within the initializer-list\n     * <tt>{#SquareRoot, #DiagonalCovarianceMatrix, #CovarianceMatrix}</tt>.\n     *\n     * This method is used to determine the best suitable representation\n     * for conversion. It is recommanded to put the diagonal forms at the\n     * beginning of the initialization-list. Diagonal forms can be converted\n     * most efficiently other  representations.\n     */\n    template <int AttributeCount>\n    Attribute select_first_representation(\n        const std::array<Attribute, AttributeCount>& representations\n    ) const noexcept\n    {\n        for (auto& rep: representations)  if (!is_dirty(rep)) return rep;\n        return Attributes;\n    }\n    /** \\endcond */\n\nprotected:\n    /** \\cond internal */\n    Variate mean_;                     /**< \\brief first moment vector */\n    mutable SecondMoment covariance_;  /**< \\brief cov. form */\n    mutable SecondMoment precision_;   /**< \\brief cov. inverse form */\n    mutable SecondMoment square_root_; /**< \\brief cov. square root form */\n    mutable bool full_rank_;           /**< \\brief full rank flag */\n    mutable Real log_norm_;            /**< \\brief log normalizing constant */\n    mutable Real determinant_;         /**< \\brief determinant of covariance */\n    mutable FlagArray dirty_;          /**< \\brief data validity flags */\n    /** \\endcond */\n};\n\n/** \\} */\n\n}\n", "meta": {"hexsha": "d1503ea803d1b355c1b9c93821d9e273d14caa3d", "size": 23742, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/fl/distribution/gaussian.hpp", "max_stars_repo_name": "catree/fl", "max_stars_repo_head_hexsha": "de28c2eef13105b820332b99cef1941cbc6d96a3", "max_stars_repo_licenses": ["MIT"], "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/fl/distribution/gaussian.hpp", "max_issues_repo_name": "catree/fl", "max_issues_repo_head_hexsha": "de28c2eef13105b820332b99cef1941cbc6d96a3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/fl/distribution/gaussian.hpp", "max_forks_repo_name": "catree/fl", "max_forks_repo_head_hexsha": "de28c2eef13105b820332b99cef1941cbc6d96a3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-11-20T14:05:50.000Z", "max_forks_repo_forks_event_max_datetime": "2018-11-20T14:05:50.000Z", "avg_line_length": 30.2445859873, "max_line_length": 82, "alphanum_fraction": 0.5862185157, "num_tokens": 4894, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6619228758499941, "lm_q2_score": 0.5273165233795671, "lm_q1q2_score": 0.34904286963862374}}
{"text": "#include <math.h>\n#include <stdio.h>\n\n#include <boost/math/quaternion.hpp>\n\nextern \"C\" void externalForces(double t, double *f, unsigned int size_z, double *z)\n{\n  f[0]=0;\n  f[1]=0;\n  f[2]=0;\n\n}\n\nextern \"C\" void externalMoment(double t,double *m, unsigned int size_z, double *z)\n{\n  m[0]=0;\n  m[1]=0;\n  m[2]=0;\n}\n\nextern \"C\" void fInt_beam1(double t, double *q, double *v, double *f, unsigned int size_z, double *z)\n{\n  // printf(\"fInt_beam1\\n\");\n  // printf(\"q[0] = %e\\t q[1] = %e\\t, q[2]=%e\\n\",q[0],q[1],q[2]);\n  f[0]=1e4*q[0];\n  f[1]=0.0;\n  f[2]=1e4*q[2];\n  // printf(\"f[0] = %e\\t f[1] = %e\\t, f[2]=%e\\n\",f[0],f[1],f[2]);\n\n}\nextern \"C\" void jacobianFIntq_beam1(double t, double *q, double *v, double *jac, unsigned int size_z, double *z)\n{\n  for(int i =0; i < 3; i++)\n  {\n    for(int j=0; j<7; j++)\n      jac[i+j*3]=0.0;\n  }\n  jac[0+0*3]=1e4;\n  jac[2+2*3]=1e4;\n}\n\nextern \"C\" void jacobianFIntv_beam1(double t, double *q, double *v, double *jac, unsigned int size_z, double *z)\n{\n  for(int i =0; i < 3; i++)\n  {\n    for(int j=0; j< 6; j++)\n      jac[i+j*3]=0.0;\n  }\n}\n\n\nextern \"C\" void mInt_beam1(double t, double *q, double *v, double *m, unsigned int size_z, double *z)\n{\n  // printf(\"mInt_beam1 :\\n\");\n\n  // Simple torsional spring around y axis\n  // printf(\"q[0] = %e\\n\", q[0]);\n  // printf(\"q[1] = %e\\n\", q[1]);\n  // printf(\"q[2] = %e\\n\", q[2]);\n  // printf(\"q[3] = %e\\n\", q[3]);\n  // printf(\"q[4] = %e\\n\", q[4]);\n  // printf(\"q[5] = %e\\n\", q[5]);\n  // printf(\"q[6] = %e\\n\", q[6]);\n\n  double angle = 2*asin(q[5]);\n  // printf(\"angle = %e\\n\", angle);\n  m[0]=0.0;\n  m[1]=1e3*(angle-1.0);\n  m[2]=0.0;\n  // printf(\"m[0] = %e\\t m[1] = %e\\t, m[2]=%e\\n\",m[0],m[1],m[2]);\n}\n\nextern \"C\" void jacobianMIntq_beam1(double t, double *q, double *v, double *jac, unsigned int size_z, double *z)\n{\n  // printf(\"jacobianMIntq_beam1:\\n \");\n  for(int i =0; i < 3; i++)\n  {\n    for(int j=0; j<7; j++)\n      jac[i+j*3]=0.0;\n  }\n  // printf(\"q[0] = %e\\n\", q[0]);\n  // printf(\"q[1] = %e\\n\", q[1]);\n  // printf(\"q[2] = %e\\n\", q[2]);\n  // printf(\"q[3] = %e\\n\", q[3]);\n  // printf(\"q[4] = %e\\n\", q[4]);\n  // printf(\"q[5] = %e\\n\", q[5]);\n  // printf(\"q[6] = %e\\n\", q[6]);\n\n  // double angle = 2*asin(q[5]);\n\n  // printf(\"angle = %e\\n\", angle);\n  jac[1+5*3]=1e3 * 2.0 / sqrt(1 - q[5]*q[5]) ;\n  //printf(\"jac[3+3*3] = %e\\n\", jac[3+3*3]);\n  // printf(\"[(\");\n  // for (int i =0; i < 3; i++)\n  // {\n  //   for (int j=0; j<7; j++) printf(\"%e,\\t\",jac[i+j*3]);\n  //   printf(\"\\n\");\n  // }\n  // printf(\")]\\n\");\n  // // Computation by finite difference\n  // double epsilon = 1e-8;\n  // double vector[7];\n  // double m1[3],m2[3];\n\n  // for (int j =0; j < 7; j++)\n  // {\n  //   for (int k =0; k < 7; k++) vector[k] =q[k];\n  //   vector[j] += epsilon;\n  //   mInt_beam1(t, q, v, m1,  size_z, z);\n  //   mInt_beam1(t, vector, v, m2,  size_z, z);\n  //   jac[0+j*3]=(m2[0]-m1[0])/epsilon ;\n  //   jac[1+j*3]=(m2[1]-m1[1])/epsilon ;\n  //   jac[2+j*3]=(m2[2]-m1[2])/epsilon ;\n  // }\n\n  // for (int i =0; i < 3; i++)\n  // {\n  //   for (int j=0; j<7; j++) printf(\"%e\\t\",jac[i+j*3]);\n  //   printf(\"\\n\");\n  // }\n\n}\n\n\n\n\nextern \"C\" void jacobianMIntv_beam1(double t, double *q, double *v, double *jac, unsigned int size_z, double *z)\n{\n  for(int i =0; i < 3; i++)\n  {\n    for(int j=0; j< 6; j++)\n      jac[i+j*3]=0.0;\n  }\n}\n", "meta": {"hexsha": "e8221cd5e4508cd09462e4d9a8180fb0ab7fa043", "size": 3281, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/mechanics/JointsTestsWithInternalForces/SimplePlugin/SimplePlugin.cpp", "max_stars_repo_name": "vacary/siconos-tutorials", "max_stars_repo_head_hexsha": "93c0158321077a313692ed52fed69ff3c256ae32", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2017-01-12T23:09:28.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-20T17:03:58.000Z", "max_issues_repo_path": "examples/mechanics/JointsTestsWithInternalForces/SimplePlugin/SimplePlugin.cpp", "max_issues_repo_name": "vacary/siconos-tutorials", "max_issues_repo_head_hexsha": "93c0158321077a313692ed52fed69ff3c256ae32", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2019-01-14T13:44:51.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-17T13:57:27.000Z", "max_forks_repo_path": "examples/mechanics/JointsTestsWithInternalForces/SimplePlugin/SimplePlugin.cpp", "max_forks_repo_name": "vacary/siconos-tutorials", "max_forks_repo_head_hexsha": "93c0158321077a313692ed52fed69ff3c256ae32", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-10-22T13:30:39.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-06T10:19:57.000Z", "avg_line_length": 24.125, "max_line_length": 112, "alphanum_fraction": 0.4937519049, "num_tokens": 1437, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6926419958239131, "lm_q2_score": 0.5039061705290805, "lm_q1q2_score": 0.3490265756632474}}
{"text": "#include <iostream>\n#include <memory>\n#include <string>\n#include <chrono>\n\n#include <boost/program_options.hpp>\n#include <algorithms/Grover.hpp>\n#include <algorithms/QFT.hpp>\n#include <algorithms/Entanglement.hpp>\n\n\n#include \"Simulator.hpp\"\n#include \"QFRSimulator.hpp\"\n#include \"GroverSimulator.hpp\"\n#include \"ShorFastSimulator.hpp\"\n#include \"ShorSimulator.hpp\"\n\n\nint main(int argc, char** argv) {\n    namespace po = boost::program_options;\n    unsigned long long seed;\n\n    po::options_description description(\"JKQ DDSIM by https://iic.jku.at/eda/ -- Allowed options\");\n    description.add_options()\n            (\"help,h\", \"produce help message\")\n            (\"seed\", po::value<unsigned long long>(&seed)->default_value(0), \"seed for random number generator (default zero is possibly directly used as seed!)\")\n            (\"shots\", po::value<unsigned int>()->default_value(0), \"number of measurements (if the algorithm does not contain non-unitary gates, weak simulation is used)\")\n            (\"display_vector\", \"display the state vector\")\n            (\"ps\", \"print simulation stats (applied gates, sim. time, and maximal size of the DD)\")\n            (\"verbose\", \"Causes some simulators to print additional information to STDERR\")\n            (\"benchmark\", \"print simulation stats in a single CSV style line (overrides --ps and suppresses most other output, please don't rely on the format across versions)\")\n\n            (\"simulate_file\", po::value<std::string>(), \"simulate a quantum circuit given by file (detection by the file extension)\")\n            (\"simulate_qft\", po::value<unsigned int>(), \"simulate Quantum Fourier Transform for given number of qubits\")\n            (\"simulate_ghz\", po::value<unsigned int>(), \"simulate state preparation of GHZ state for given number of qubits\")\n            (\"step_fidelity\", po::value<double>()->default_value(1.0), \"target fidelity for each approximation run (>=1 = disable approximation)\")\n            (\"steps\", po::value<unsigned int>()->default_value(1), \"number of approximation steps\")\n            (\"initial_reorder\", po::value<int>()->default_value(0), \"Try to find a good initial variable order (0=None, 1=Most affected qubits to the top, 2=Most affected targets to the top)\")\n            (\"dynamic_reorder\", po::value<int>()->default_value(0), \"Apply reordering strategy during simulation (0=None, 1=Sifting, 2=Move2Top)\")\n            (\"post_reorder\", po::value<int>()->default_value(0), \"Apply a reordering strategy after simulation (0=None, 1=Sifting)\")\n\n            (\"simulate_grover\", po::value<unsigned int>(), \"simulate Grover's search for given number of qubits with random oracle\")\n            (\"simulate_grover_emulated\", po::value<unsigned int>(), \"simulate Grover's search for given number of qubits with random oracle and emulation\")\n            (\"simulate_grover_oracle_emulated\", po::value<std::string>(), \"simulate Grover's search for given number of qubits with given oracle and emulation\")\n\n            (\"simulate_shor\", po::value<unsigned int>(), \"simulate Shor's algorithm factoring this number\")\n            (\"simulate_shor_coprime\", po::value<unsigned int>()->default_value(0), \"coprime number to use with Shor's algorithm (zero randomly generates a coprime)\")\n            (\"simulate_shor_no_emulation\", \"Force Shor simulator to do modular exponentiation instead of using emulation (you'll usually want emulation)\")\n\n            (\"simulate_fast_shor\", po::value<unsigned int>(), \"simulate Shor's algorithm factoring this number with intermediate measurements\")\n            (\"simulate_fast_shor_coprime\", po::value<unsigned int>()->default_value(0), \"coprime number to use with Shor's algorithm (zero randomly generates a coprime)\")\n            ;\n    po::variables_map vm;\n    try {\n        po::store(po::parse_command_line(argc, argv, description), vm);\n\n        if (vm.count(\"help\")) {\n            std::cout << description;\n            return 0;\n        }\n        po::notify(vm);\n    } catch (const po::error &e) {\n        std::cerr << \"[ERROR] \" << e.what() << \"! Try option '--help' for available commandline options.\\n\";\n        std::exit(1);\n    }\n\n    std::unique_ptr<qc::QuantumComputation> quantumComputation;\n    std::unique_ptr<Simulator> ddsim{nullptr};\n\n    if (vm.count(\"simulate_file\")) {\n        const std::string fname = vm[\"simulate_file\"].as<std::string>();\n    \tquantumComputation = std::make_unique<qc::QuantumComputation>(fname);\n        ddsim = std::make_unique<QFRSimulator>(quantumComputation,\n                                               vm[\"steps\"].as<unsigned int>(), vm[\"step_fidelity\"].as<double>(),\n                                               vm[\"initial_reorder\"].as<int>(), vm[\"dynamic_reorder\"].as<int>(), vm[\"post_reorder\"].as<int>(),\n                                               seed);\n    } else if (vm.count(\"simulate_qft\")) {\n\t    const unsigned int n_qubits = vm[\"simulate_qft\"].as<unsigned int>();\n\t    quantumComputation = std::make_unique<qc::QFT>(n_qubits);\n        ddsim = std::make_unique<QFRSimulator>(quantumComputation,\n                                               vm[\"steps\"].as<unsigned int>(), vm[\"step_fidelity\"].as<double>(),\n                                               vm[\"initial_reorder\"].as<int>(), vm[\"dynamic_reorder\"].as<int>(), vm[\"post_reorder\"].as<int>(),\n                                               seed);\n    } else 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, vm.count(\"verbose\") > 0);\n        } else {\n            ddsim = std::make_unique<ShorFastSimulator>(composite_number, coprime, seed, vm.count(\"verbose\") > 0);\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        if (seed == 0) {\n            ddsim = std::make_unique<ShorSimulator>(composite_number, coprime, vm.count(\"verbose\") > 0);\n        } else {\n            ddsim = std::make_unique<ShorSimulator>(composite_number, coprime, seed, vm.count(\"verbose\") > 0);\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<QFRSimulator>(quantumComputation,\n                                               vm[\"steps\"].as<unsigned int>(), vm[\"step_fidelity\"].as<double>(),\n                                               vm[\"initial_reorder\"].as<int>(), vm[\"dynamic_reorder\"].as<int>(), vm[\"post_reorder\"].as<int>(),\n                                               seed);\n    } else 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\t    const unsigned int n_qubits = vm[\"simulate_ghz\"].as<unsigned int>();\n\t    quantumComputation = std::make_unique<qc::Entanglement>(n_qubits);\n        ddsim = std::make_unique<QFRSimulator>(quantumComputation,\n                                               vm[\"steps\"].as<unsigned int>(), vm[\"step_fidelity\"].as<double>(),\n                                               vm[\"initial_reorder\"].as<int>(), vm[\"dynamic_reorder\"].as<int>(), vm[\"post_reorder\"].as<int>(),\n                                               seed);\n    } else {\n        std::cerr << \"Did not find anything to simulate. See help below.\\n\"\n                  << description << \"\\n\";\n        return 1;\n    }\n\n    if (quantumComputation && quantumComputation->getNqubits() > dd::MAXN) {\n        std::cerr << \"Quantum computation contains to many qubits (limit is set to \" << dd::MAXN << \"). See documentation for details.\\n\";\n        std::exit(1);\n    }\n\n    auto t1 = std::chrono::high_resolution_clock::now();\n    auto m = ddsim->Simulate(vm[\"shots\"].as<unsigned int>());\n    auto t2 = std::chrono::high_resolution_clock::now();\n\n    std::chrono::duration<float> duration_simulation = t2-t1;\n\n    if (vm.count(\"benchmark\")) {\n        auto more_info = ddsim->AdditionalStatistics();\n        std::cout << ddsim->getName() << \", \"\n                  << ddsim->getNumberOfQubits() << \", \"\n                  //<< vm[\"approximate\"].as<float>() << \", \"\n                  << std::fixed << duration_simulation.count() << std::defaultfloat << \", \"\n                  //<< more_info[\"approximation_runs\"] << \",\"\n                  //<< more_info[\"final_fidelity\"] << \", \"\n                  << more_info[\"coprime_a\"] << \", \"\n                  << more_info[\"sim_result\"] << \", \"\n                  << more_info[\"polr_result\"] << \", \"\n                  << ddsim->getSeed() << \", \"\n                  << ddsim->getNumberOfOps() << \", \"\n                  << ddsim->getMaxNodeCount()\n                  << \"\\n\";\n        return 0;\n    }\n\n    std::cout << \"{\\n\";\n\n    if (!m.empty()) {\n        std::cout << \"  \\\"measurements\\\": {\";\n        bool first_element = true;\n        for(const auto& element : m)\n        {\n            std::cout << (first_element ? \"\" : \",\") << \"\\n    \\\"\" << element.first << \"\\\": \" << element.second;\n            first_element = false;\n        }\n        std::cout << \"\\n  },\\n\";\n    }\n    if (vm.count(\"display_vector\")) {\n        std::cout << \"  \\\"state_vector\\\": [\";\n\n        bool first_element = true;\n        unsigned long long non_zero_entries = 0;\n        for(const auto& element : ddsim->getVector()) {\n            if (element.r != 0 || element.i != 0) {\n                non_zero_entries++;\n                std::cout << (first_element ? \"\" : \",\") << \"\\n    \" << std::showpos << element.r << element.i << \"i\" << std::noshowpos;\n            } else {\n                std::cout << (first_element ? \"\" : \",\") << \"\\n    0\";\n            }\n            first_element = false;\n        }\n        std::cout << \"\\n  ],\\n\";\n        std::cout << \"  \\\"non_zero_entries\\\": \" << non_zero_entries << \",\\n\";\n    }\n\n    if (vm.count(\"ps\")) {\n        std::cout << \"  \\\"statistics\\\": {\\n\"\n                  << \"    \\\"simulation_time\\\": \" << std::fixed << duration_simulation.count() << std::defaultfloat << \",\\n\"\n                  << \"    \\\"benchmark\\\": \\\"\" << ddsim->getName() << \"\\\",\\n\"\n                  << \"    \\\"shots\\\": \" << vm[\"shots\"].as<unsigned int>() << \",\\n\"\n                  << \"    \\\"distinct_results\\\": \" << m.size() << \",\\n\"\n                  << \"    \\\"n_qubits\\\": \" << ddsim->getNumberOfQubits() << \",\\n\"\n                  << \"    \\\"applied_gates\\\": \" << ddsim->getNumberOfOps() << \",\\n\"\n                  << \"    \\\"max_nodes\\\": \" << ddsim->getMaxNodeCount() << \",\\n\"\n                  ;\n        for(const auto& item : ddsim->AdditionalStatistics()) {\n            std::cout << \"    \\\"\" << item.first << \"\\\": \\\"\" << item.second << \"\\\",\\n\";\n        }\n        std::cout << \"    \\\"seed\\\": \" << ddsim->getSeed() << \"\\n\"\n                  << \"  },\\n\";\n    }\n    std::cout << \"  \\\"dummy\\\": 0\\n}\\n\"; // trailing element to make json printout easier\n}\n", "meta": {"hexsha": "4d3e5fe8f33a3a656d8e6493c11f367e5d53fb94", "size": 11429, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "apps/simple.cpp", "max_stars_repo_name": "Tonanguyxiro/ddsim", "max_stars_repo_head_hexsha": "ff6d8afba6e72f4795394688872a9081f871d320", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-03-05T09:17:39.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-05T09:17:39.000Z", "max_issues_repo_path": "apps/simple.cpp", "max_issues_repo_name": "Tonanguyxiro/ddsim", "max_issues_repo_head_hexsha": "ff6d8afba6e72f4795394688872a9081f871d320", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "apps/simple.cpp", "max_forks_repo_name": "Tonanguyxiro/ddsim", "max_forks_repo_head_hexsha": "ff6d8afba6e72f4795394688872a9081f871d320", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 56.8606965174, "max_line_length": 192, "alphanum_fraction": 0.5661037711, "num_tokens": 2737, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5964331462646254, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.3489737222844969}}
{"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 * Matrix.hpp\n *\n *  @date 26.08.2008\n *  @author Thomas Wiemann (twiemann@uos.de)\n */\n\n#ifndef LVR2_MATRIX_H_\n#define LVR2_MATRIX_H_\n\n#include <iostream>\n#include <fstream>\n#include <iomanip>\n#include <vector>\n\n#include <lvr2/geometry/Normal.hpp>\n#include <lvr2/io/DataStruct.hpp>\n\n#define _USE_MATH_DEFINES\n#include <cmath>\n\n#include <Eigen/Dense>\n\n#ifndef M_PI\n#define M_PI 3.141592654\n#endif\nusing namespace std;\n\nnamespace lvr2\n{\n\n/**\n * @brief\tA 4x4 matrix class implementation for use with the provided\n * \t\t\tvertex types.\n */\ntemplate<typename BaseVecT>\nclass Matrix4 {\npublic:\n\n    using ValueType = typename BaseVecT::CoordType;\n\n\t/**\n\t * @brief \tDefault constructor. Initializes a identity matrix.\n\t */\n\tMatrix4()\n\t{\n\t\tfor(int i = 0; i < 16; i++) m[i] = 0;\n\t\tm[0] = m[5] = m[10] = m[15] = 1;\n\t}\n\n\t/**\n\t * @brief\tInitializes a matrix wit the given data array. Ensure\n\t * \t\t\tthat the array has exactly 16 fields.\n\t */\n\ttemplate<typename T>\n\tMatrix4(T* matrix)\n\t{\n\t\tfor(int i = 0; i < 16; i++) m[i] = matrix[i];\n\t}\n\n\t/**\n\t * @brief \tCopy constructor.\n\t */\n\ttemplate<typename T>\n\tMatrix4(const Matrix4<T>& other)\n\t{\n\t\tfor(int i = 0; i < 16; i++) m[i] = other[i];\n\t}\n\n\t/**\n\t * @brief\tConstructs a matrix from given axis and angle. Trys to\n\t * \t\t\tavoid a gimbal lock.\n\t */\n\ttemplate<typename T>\n\tMatrix4(T axis, ValueType angle)\n\t{\n\t\t// Check for gimbal lock\n\t\tif(fabs(angle) < 0.0001){\n\n\t\t\tbool invert_z = axis.z < 0;\n\n\t\t\t//Angle to yz-plane\n\t\t\tfloat pitch = atan2(axis.z, axis.x) - M_PI_2;\n\t\t\tif(pitch < 0.0f) pitch += 2.0f * M_PI;\n\n\t\t\tif(axis.x == 0.0f && axis.z == 0.0) pitch = 0.0f;\n\n\t\t\t//Transform axis into yz-plane\n\t\t\taxis.x =  axis.x * cos(pitch) + axis.z * sin(pitch);\n\t\t\taxis.z = -axis.x * sin(pitch) + axis.z * cos(pitch);\n\n\t\t\t//Angle to y-Axis\n\t\t\tfloat yaw = atan2(axis.y, axis.z);\n\t\t\tif(yaw < 0) yaw += 2 * M_PI;\n\n\t\t\tMatrix4<BaseVecT> m1, m2, m3;\n\n\t\t\tif(invert_z) yaw = -yaw;\n\n\t\t\tcout << \"YAW: \" << yaw << \" PITCH: \" << pitch << endl;\n\n\t\t\tif(fabs(yaw)   > 0.0001){\n\t\t\t\tm2 = Matrix4(T(1.0, 0.0, 0.0), yaw);\n\t\t\t\tm3 = m3 * m2;\n\t\t\t}\n\n\t\t\tif(fabs(pitch) > 0.0001){\n\t\t\t\tm1 = Matrix4(T(0.0, 1.0, 0.0), pitch);\n\t\t\t\tm3 = m3 * m1;\n\t\t\t}\n\n\t\t\tfor(int i = 0; i < 16; i++) m[i] = m3[i];\n\n\t\t} else {\n\t\t\tfloat c = cos(angle);\n\t\t\tfloat s = sin(angle);\n\t\t\tfloat t = 1.0f - c;\n\t\t\tfloat tmp1, tmp2;\n\n\t\t\t// Normalize axis\n\t\t\tNormal<ValueType> a(axis);\n\n\t\t\tm[ 0] = c + a.x * a.x * t;\n\t\t\tm[ 5] = c + a.y * a.y * t;\n\t\t\tm[10] = c + a.z * a.z * t;\n\n\t\t\ttmp1 = a.x * a.y * t;\n\t\t\ttmp2 = a.z * s;\n\t\t\tm[ 4] = tmp1 + tmp2;\n\t\t\tm[ 1] = tmp1 - tmp2;\n\n\t\t\ttmp1 = a.x * a.z * t;\n\t\t\ttmp2 = a.y * s;\n\t\t\tm[ 8] = tmp1 - tmp2;\n\t\t\tm[ 2] = tmp1 + tmp2;\n\n\t\t\ttmp1 = a.y * a.z * t;\n\t\t\ttmp2 = a.x * s;\n\t\t\tm[ 9] = tmp1 + tmp2;\n\t\t\tm[ 6] = tmp1 - tmp2;\n\n\t\t\tm[ 3] = m[ 7] = m[11] = 0.0;\n\t\t\tm[12] = m[13] = m[14] = 0.0;\n\t\t\tm[15] = 1.0;\n\t\t}\n\t}\n\n\ttemplate<typename T>\n\tMatrix4(const T &position, const T &angles)\n\t{\n\t\tfloat sx = sin(angles[0]);\n\t\tfloat cx = cos(angles[0]);\n\t\tfloat sy = sin(angles[1]);\n\t\tfloat cy = cos(angles[1]);\n\t\tfloat sz = sin(angles[2]);\n\t\tfloat cz = cos(angles[2]);\n\n\t\tm[0]  = cy*cz;\n\t\tm[1]  = sx*sy*cz + cx*sz;\n\t\tm[2]  = -cx*sy*cz + sx*sz;\n\t\tm[3]  = 0.0;\n\t\tm[4]  = -cy*sz;\n\t\tm[5]  = -sx*sy*sz + cx*cz;\n\t\tm[6]  = cx*sy*sz + sx*cz;\n\t\tm[7]  = 0.0;\n\t\tm[8]  = sy;\n\t\tm[9]  = -sx*cy;\n\t\tm[10] = cx*cy;\n\n\t\tm[11] = 0.0;\n\n\t\tm[12] = position[0];\n\t\tm[13] = position[1];\n\t\tm[14] = position[2];\n\t\tm[15] = 1;\n\t}\n\n\tMatrix4(string filename);\n\n\t~Matrix4()\n\t{\n\n\t}\n\n    Matrix4& operator=(const Eigen::Matrix4d& mat)\n    {\n        m[0]  = mat(0, 0);\n        m[1]  = mat(0, 1);\n        m[2]  = mat(0, 2);\n        m[3]  = mat(0, 3);\n\n        m[4]  = mat(1, 0);\n        m[5]  = mat(1, 1);\n        m[6]  = mat(1, 2);\n        m[7]  = mat(1, 3);\n\n        m[8]  = mat(2, 0);\n        m[9]  = mat(2, 1);\n        m[10] = mat(2, 2);\n        m[11] = mat(2, 3);\n\n        m[12] = mat(3, 0);\n        m[13] = mat(3, 1);\n        m[14] = mat(3, 2);\n        m[15] = mat(3, 3);\n\n        return *this;\n    }\n\n\t/**\n\t * @brief\tScales the matrix elemnts by the given factor\n\t */\n\tMatrix4<BaseVecT> operator*(const ValueType &scale) const\n\t{\n\t\tValueType new_matrix[16];\n\t\tfor(int i = 0; i < 16; i++){\n\t\t\tnew_matrix[i] = m[i] * scale;\n\t\t}\n\t\treturn Matrix4<BaseVecT>(new_matrix);\n\t}\n\n\t/**\n\t * @brief\tMatrix-Matrix multiplication. Returns the new\n\t * \t\t\tmatrix\n\t */\n\ttemplate<typename T>\n\tMatrix4<BaseVecT> operator*(const Matrix4<T> &other) const\n\t{\n\t\tValueType new_matrix[16];\n\t\tnew_matrix[ 0] = m[ 0] * other[ 0] + m[ 4] * other[ 1] + m[ 8] * other[ 2] + m[12] * other[ 3];\n\t\tnew_matrix[ 1] = m[ 1] * other[ 0] + m[ 5] * other[ 1] + m[ 9] * other[ 2] + m[13] * other[ 3];\n\t\tnew_matrix[ 2] = m[ 2] * other[ 0] + m[ 6] * other[ 1] + m[10] * other[ 2] + m[14] * other[ 3];\n\t\tnew_matrix[ 3] = m[ 3] * other[ 0] + m[ 7] * other[ 1] + m[11] * other[ 2] + m[15] * other[ 3];\n\t\tnew_matrix[ 4] = m[ 0] * other[ 4] + m[ 4] * other[ 5] + m[ 8] * other[ 6] + m[12] * other[ 7];\n\t\tnew_matrix[ 5] = m[ 1] * other[ 4] + m[ 5] * other[ 5] + m[ 9] * other[ 6] + m[13] * other[ 7];\n\t\tnew_matrix[ 6] = m[ 2] * other[ 4] + m[ 6] * other[ 5] + m[10] * other[ 6] + m[14] * other[ 7];\n\t\tnew_matrix[ 7] = m[ 3] * other[ 4] + m[ 7] * other[ 5] + m[11] * other[ 6] + m[15] * other[ 7];\n\t\tnew_matrix[ 8] = m[ 0] * other[ 8] + m[ 4] * other[ 9] + m[ 8] * other[10] + m[12] * other[11];\n\t\tnew_matrix[ 9] = m[ 1] * other[ 8] + m[ 5] * other[ 9] + m[ 9] * other[10] + m[13] * other[11];\n\t\tnew_matrix[10] = m[ 2] * other[ 8] + m[ 6] * other[ 9] + m[10] * other[10] + m[14] * other[11];\n\t\tnew_matrix[11] = m[ 3] * other[ 8] + m[ 7] * other[ 9] + m[11] * other[10] + m[15] * other[11];\n\t\tnew_matrix[12] = m[ 0] * other[12] + m[ 4] * other[13] + m[ 8] * other[14] + m[12] * other[15];\n\t\tnew_matrix[13] = m[ 1] * other[12] + m[ 5] * other[13] + m[ 9] * other[14] + m[13] * other[15];\n\t\tnew_matrix[14] = m[ 2] * other[12] + m[ 6] * other[13] + m[10] * other[14] + m[14] * other[15];\n\t\tnew_matrix[15] = m[ 3] * other[12] + m[ 7] * other[13] + m[11] * other[14] + m[15] * other[15];\n\t\treturn Matrix4<BaseVecT>(new_matrix);\n\t}\n\n\t/**\n\t * @brief \tMatrix addition operator. Returns a new matrix\n\t *\n\t */\n\ttemplate<typename T>\n\tMatrix4<BaseVecT> operator+(const Matrix4<T> &other) const\n\t{\n\t\tValueType new_matrix[16];\n\t\tfor(int i = 0; i < 16; i++)\n\t\t{\n\t\t\tnew_matrix[i] = m[i] + other[i];\n\t\t}\n\t\treturn Matrix4<BaseVecT>(new_matrix);\n\t}\n\n\t/**\n\t * @brief \tMatrix addition operator\n\t */\n\ttemplate<typename T>\n\tMatrix4<BaseVecT> operator+=(const Matrix4<T> &other)\n\t{\n\t\t//if(other != *this)\n\t\t//{\n\t\t\treturn *this + other;\n\t\t//}\n\t\t//else\n\t\t//{\n\t\t\t//return *this;\n\t\t//}\n\t}\n\n\t/**\n\t * @brief\tMatrix-Matrix multiplication (array based). Mainly\n\t * \t\t\timplemented for compatibility with other math libs.\n\t * \t\t\tensure that the used array has at least 16 elements\n\t * \t\t\tto avoid memory access violations.\n\t */\n\ttemplate<typename T>\n\tMatrix4<BaseVecT> operator*(const T* &other) const\n\t{\n\t\tValueType new_matrix[16];\n\t\tnew_matrix[ 0] = m[ 0] * other[ 0] + m[ 4] * other[ 1] + m[ 8] * other[ 2] + m[12] * other[ 3];\n\t\tnew_matrix[ 1] = m[ 1] * other[ 0] + m[ 5] * other[ 1] + m[ 9] * other[ 2] + m[13] * other[ 3];\n\t\tnew_matrix[ 2] = m[ 2] * other[ 0] + m[ 6] * other[ 1] + m[10] * other[ 2] + m[14] * other[ 3];\n\t\tnew_matrix[ 3] = m[ 3] * other[ 0] + m[ 7] * other[ 1] + m[11] * other[ 2] + m[15] * other[ 3];\n\t\tnew_matrix[ 4] = m[ 0] * other[ 4] + m[ 4] * other[ 5] + m[ 8] * other[ 6] + m[12] * other[ 7];\n\t\tnew_matrix[ 5] = m[ 1] * other[ 4] + m[ 5] * other[ 5] + m[ 9] * other[ 6] + m[13] * other[ 7];\n\t\tnew_matrix[ 6] = m[ 2] * other[ 4] + m[ 6] * other[ 5] + m[10] * other[ 6] + m[14] * other[ 7];\n\t\tnew_matrix[ 7] = m[ 3] * other[ 4] + m[ 7] * other[ 5] + m[11] * other[ 6] + m[15] * other[ 7];\n\t\tnew_matrix[ 8] = m[ 0] * other[ 8] + m[ 4] * other[ 9] + m[ 8] * other[10] + m[12] * other[11];\n\t\tnew_matrix[ 9] = m[ 1] * other[ 8] + m[ 5] * other[ 9] + m[ 9] * other[10] + m[13] * other[11];\n\t\tnew_matrix[10] = m[ 2] * other[ 8] + m[ 6] * other[ 9] + m[10] * other[10] + m[14] * other[11];\n\t\tnew_matrix[11] = m[ 3] * other[ 8] + m[ 7] * other[ 9] + m[11] * other[10] + m[15] * other[11];\n\t\tnew_matrix[12] = m[ 0] * other[12] + m[ 4] * other[13] + m[ 8] * other[14] + m[12] * other[15];\n\t\tnew_matrix[13] = m[ 1] * other[12] + m[ 5] * other[13] + m[ 9] * other[14] + m[13] * other[15];\n\t\tnew_matrix[14] = m[ 2] * other[12] + m[ 6] * other[13] + m[10] * other[14] + m[14] * other[15];\n\t\tnew_matrix[15] = m[ 3] * other[12] + m[ 7] * other[13] + m[11] * other[14] + m[15] * other[15];\n\t\treturn Matrix4<BaseVecT>(new_matrix);\n\t}\n\n\t/**\n\t * @brief\tMultiplication of Matrix and Vertex types\n\t */\n\ttemplate<typename T>\n\tT operator*(const T &v) const\n\t{\n        using ValType = typename T::CoordType;\n\t\tValType x = m[ 0] * v.x + m[ 4] * v.y + m[8 ] * v.z;\n\t\tValType y = m[ 1] * v.x + m[ 5] * v.y + m[9 ] * v.z;\n\t\tValType z = m[ 2] * v.x + m[ 6] * v.y + m[10] * v.z;\n\n\t\tx = x + m[12];\n\t\ty = y + m[13];\n\t\tz = z + m[14];\n\n\t\treturn T(x, y, z);\n\t}\n\n    /**\n     * @brief   Multiplication of Matrix and Vertex types\n     */\n    template<typename T>\n    Normal<T> operator*(const Normal<T> &v) const\n    {\n        T x = m[ 0] * v.x + m[ 4] * v.y + m[8 ] * v.z;\n        T y = m[ 1] * v.x + m[ 5] * v.y + m[9 ] * v.z;\n        T z = m[ 2] * v.x + m[ 6] * v.y + m[10] * v.z;\n\n        return Normal<T>(x, y, z);\n    }\n\n\t/**\n\t * @brief\tSets the given index of the Matrix's data field\n\t * \t\t\tto the provided value.\n\t *\n\t * @param\ti\t\tField index of the matrix\n\t * @param\tvalue\tnew value\n\t */\n\tvoid set(int i, ValueType value){m[i] = value;};\n\n\t/**\n\t * @brief\tTransposes the current matrix\n\t */\n\tvoid transpose()\n\t{\n\t\tValueType m_tmp[16];\n\t\tm_tmp[0]  = m[0];\n\t\tm_tmp[4]  = m[1];\n\t\tm_tmp[8]  = m[2];\n\t\tm_tmp[12] = m[3];\n\t\tm_tmp[1]  = m[4];\n\t\tm_tmp[5]  = m[5];\n\t\tm_tmp[9]  = m[6];\n\t\tm_tmp[13] = m[7];\n\t\tm_tmp[2]  = m[8];\n\t\tm_tmp[6]  = m[9];\n\t\tm_tmp[10] = m[10];\n\t\tm_tmp[14] = m[11];\n\t\tm_tmp[3]  = m[12];\n\t\tm_tmp[7]  = m[13];\n\t\tm_tmp[11] = m[14];\n\t\tm_tmp[15] = m[15];\n\t\tfor(int i = 0; i < 16; i++) m[i] = m_tmp[i];\n\t}\n\n\t/**\n\t * @brief\tComputes an Euler representation (x, y, z) plus three\n\t * \t\t\trotation values in rad. Rotations are with respect to\n\t * \t\t\tthe x, y, z axes.\n\t */\n\tvoid toPostionAngle(ValueType pose[6])\n\t{\n\t\tif(pose != 0){\n\t\t\tfloat _trX, _trY;\n\t\t\tif(m[0] > 0.0) {\n\t\t\t\tpose[4] = asin(m[8]);\n\t\t\t} else {\n\t\t\t\tpose[4] = (float)M_PI - asin(m[8]);\n\t\t\t}\n\t\t\t// rPosTheta[1] =  asin( m[8]);      // Calculate Y-axis angle\n\n\t\t\tfloat  C    =  cos( pose[4] );\n\t\t\tif ( fabs( C ) > 0.005 )  {          // Gimball lock?\n\t\t\t\t_trX      =  m[10] / C;          // No, so get X-axis angle\n\t\t\t\t_trY      =  -m[9] / C;\n\t\t\t\tpose[3]  = atan2( _trY, _trX );\n\t\t\t\t_trX      =  m[0] / C;           // Get Z-axis angle\n\t\t\t\t_trY      = -m[4] / C;\n\t\t\t\tpose[5]  = atan2( _trY, _trX );\n\t\t\t} else {                             // Gimball lock has occurred\n\t\t\t\tpose[3] = 0.0;                   // Set X-axis angle to zero\n\t\t\t\t_trX      =  m[5];  //1          // And calculate Z-axis angle\n\t\t\t\t_trY      =  m[1];  //2\n\t\t\t\tpose[5]  = atan2( _trY, _trX );\n\t\t\t}\n\n\t\t\t// cout << pose[3] << \" \" << pose[4] << \" \" << pose[5] << endl;\n\n\t\t\tpose[0] = m[12];\n\t\t\tpose[1] = m[13];\n\t\t\tpose[2] = m[14];\n\t\t}\n\t}\n\n\t/**\n\t * @brief\tLoads matrix values from a given file.\n\t */\n\tvoid loadFromFile(string filename)\n\t{\n\t\tifstream in(filename.c_str());\n\t\tfor(int i = 0; i < 16; i++){\n\t\t\tif(!in.good()){\n                cout << \"Warning: Matrix::loadFromFile: File not found or corrupted: \" << filename << endl;\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tin >> m[i];\n\t\t}\n\t}\n\n\t/**\n\t * @brief\tMatrix scaling with self assignment.\n\t */\n\ttemplate<typename T>\n\tvoid operator*=(const T scale)\n\t{\n\t\t*this = *this * scale;\n\t}\n\n\t/**\n\t * @brief \tMatrix-Matrix multiplication with self assigment.\n\t */\n\ttemplate<typename T>\n\tvoid operator*=(const Matrix4<T>& other)\n\t{\n\t\t*this = *this * other;\n\t}\n\n\t/**\n\t * @brief\tMatrix-Matrix multiplication (array based). See \\ref{operator*}.\n\t */\n\ttemplate<typename T>\n\tvoid operator*=(const T* other)\n\t{\n\t\t*this = *this * other;\n\t}\n\n\t/**\n\t * @brief\tReturns the internal data array. Unsafe. Will probably\n\t * \t\t\tremoved in one of the next versions.\n\t */\n\tValueType* getData(){ return m;}\n\n    floatArr toFloatArray()\n    {\n        floatArr a(new float[16]);\n        for(int i = 0; i < 16; i++)\n        {\n            a[i] = m[i];\n        }\n        return a;\n    }\n\n    std::vector<ValueType> getVector()\n    {\n        std::vector<ValueType> tmp(16);\n        for(int i = 0; i < 16; i++)\n        {\n            tmp.push_back(m[i]);\n        }\n        return tmp;\n    }\n\n\t/**\n\t * @brief\tReturns the element at the given index.\n\t */\n\tValueType at(const int i) const;\n\n\t/**\n\t * @brief\tIndexed element (reading) access.\n\t */\n\tValueType operator[](const int index) const\n\t{\n\t    /// TODO: Boundary check\n\t    return m[index];\n\t}\n\n\n\t/**\n\t * @brief  \tWriteable index access\n\t */\n\tValueType& operator[](const int index)\n\t{\n\t\treturn m[index];\n\t}\n\n\t/**\n\t * @brief   Returns the matrix's determinant\n\t */\n\tValueType det()\n\t{\n\t    ValueType det, result = 0, i = 1.0;\n\t    ValueType Msub3[9];\n\t    int    n;\n\t    for ( n = 0; n < 4; n++, i *= -1.0 ) {\n\t        submat( Msub3, 0, n );\n\t        det     = det3( Msub3 );\n\t        result += m[n] * det * i;\n\t    }\n\t    return( result );\n\t}\n\n\tMatrix4<BaseVecT> inv(bool& success)\n\t{\n\t    Matrix4<BaseVecT> Mout;\n\t    ValueType  mdet = det();\n\t    if ( fabs( mdet ) < 0.00000000000005 ) {\n\t        cout << \"Error matrix inverting! \" << mdet << endl;\n\t        return Mout;\n\t    }\n\t    ValueType  mtemp[9];\n\t    int     i, j, sign;\n\t    for ( i = 0; i < 4; i++ ) {\n\t        for ( j = 0; j < 4; j++ ) {\n\t            sign = 1 - ( (i +j) % 2 ) * 2;\n\t            submat( mtemp, i, j );\n\t            Mout[i+j*4] = ( det3( mtemp ) * sign ) / mdet;\n\t        }\n\t    }\n\t    return Mout;\n\t}\n\n\tValueType m[16];\n\nprivate:\n\n    /**\n     * @brief   Returns a sub matrix without row \\ref i and column \\ref j.\n     */\n\tvoid submat(ValueType* submat, int i, int j)\n\t{\n\t    int di, dj, si, sj;\n\t    // loop through 3x3 submatrix\n\t    for( di = 0; di < 3; di ++ ) {\n\t        for( dj = 0; dj < 3; dj ++ ) {\n\t            // map 3x3 element (destination) to 4x4 element (source)\n\t            si = di + ( ( di >= i ) ? 1 : 0 );\n\t            sj = dj + ( ( dj >= j ) ? 1 : 0 );\n\t            // copy element\n\t            submat[di * 3 + dj] = m[si * 4 + sj];\n\t        }\n\t    }\n\t}\n\n\t/**\n\t * @brief    Calculates the determinant of a 3x3 matrix\n\t *\n\t * @param    M  input 3x3 matrix\n\t * @return   determinant of input matrix\n\t */\n\tValueType det3(const ValueType *M )\n\t{\n\t  ValueType det;\n\t  det = (double)(  M[0] * ( M[4]*M[8] - M[7]*M[5] )\n\t                 - M[1] * ( M[3]*M[8] - M[6]*M[5] )\n\t                 + M[2] * ( M[3]*M[7] - M[6]*M[4] ));\n\t  return ( det );\n\t}\n\n\t\n};\n\n/**\n * @brief Output operator for matrices.\n */\ntemplate<typename T>\ninline ostream& operator<<(ostream& os, const Matrix4<T> matrix){\n\tos << \"Matrix:\" << endl;\n\tos << fixed;\n\tfor(int i = 0; i < 16; i++){\n\t\tos << setprecision(4) << matrix[i] << \" \";\n\t\tif(i % 4 == 3) os << \" \" <<  endl;\n\t}\n\tos << endl;\n\treturn os;\n}\n\n} // namespace lvr2\n\n#endif /* MATRIX_H_ */\n", "meta": {"hexsha": "7126e5cc7880e1437306e0d02671b2a911b025c9", "size": 16649, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/lvr2/geometry/Matrix4.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/geometry/Matrix4.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/geometry/Matrix4.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": 26.6384, "max_line_length": 107, "alphanum_fraction": 0.5296414199, "num_tokens": 6349, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7090191460821871, "lm_q2_score": 0.49218813572079556, "lm_q1q2_score": 0.34897081170054206}}
{"text": "#include \"scan_material.hpp\"\n#include <cstdlib>\n#include <algorithm>\n#include <boost/lexical_cast.hpp>\n#include <complex>\n#include <memory>\n#include <fftw3.h>\n\n#include <vector>\n#include <random>\n#include <chrono>\n\n#include <DebugOps.hpp>\n#include <ScanParams.hpp>\n\n#include <cstddef> // for nullptr\n#include <cstdint> // for writing as an int32_t and int16_t\n\nusing namespace Constants;\n\n/* Here's main */\nint main(int argc, char* argv[])\n{\n\tstd::time_t tstart = std::time(nullptr);\n\tstd::cout << \"\\t\\t======================================\\n\"\n\t\t<< \"\\t\\t======= scan_material started ========\\n\"\n\t\t<< \"\\t\\t===== \" << std::asctime(std::localtime(&tstart)) \n\t\t<< \"\\t\\t===== on host \" << getenv(\"HOSTNAME\") << \"\\n\"\n\t\t<< \"\\t\\t===== for \" << getenv(\"nimages\") << \" images\\n\"\n\t\t<< \"\\t\\t===== with \" << getenv(\"nfibers\") << \" fibers\\n\"\n\t\t<< \"\\t\\t======================================\\n\" << std::flush;\n\n\tunsigned nthreads = (unsigned)atoi( getenv(\"nthreads\") );\n\tstd::cout << \"Scaling fibers =\\t\";\n\tif (getenv(\"scale_fibers\")){\n\t\tstd::cout << \"yes\\n\";\n\t} else {\n\t\tstd::cout << \"no\\n\";\n\t}\n\tstd::cout << std::flush;\n\n\tScanParams scanparams;\n\tscanparams.nimages(size_t(atoi(getenv(\"nimages\"))));\n\tscanparams.filebase(std::string(getenv(\"filebase\")));\n\tscanparams.calfilebase(std::string(getenv(\"calfilebase\")));\n\n\tstd::vector<float> imagetimes(scanparams.nimages(),0); // for benchmarking the processors\n\n\tscanparams.dalpha((atof(getenv(\"drifting_alpha\")))*pi<double>()/scanparams.nimages());\n\n\tif (scanparams.doublepulse(atoi(getenv(\"doublepulse\")) > 0 )){\n\t\tscanparams.doublepulsedelay(atof( getenv(\"doublepulsedelay\") ) ) ; // this one gets used directly in atomic units\n\t}\n\tscanparams.lambda_0(atof( getenv(\"lambda0\") ));\n\tscanparams.lambda_width( atof( getenv(\"lambda_width\") ));\n\tscanparams.lambda_onoff( atof( getenv(\"lambda_onoff\") ));\n\tscanparams.tspan((atof( getenv(\"tspan\") ) )/fsPau<double>());\n\n\tscanparams.ngroupsteps(atoi( getenv(\"ngroupsteps\") ));\n\tscanparams.groupdelay(atof(getenv(\"groupdelay\")));\n\tscanparams.backdelay(atof(getenv(\"backdelay\")));\n\tscanparams.netalon(atoi(getenv(\"netalon\")));\n\n\n\tscanparams.etalonreflectance(atof(getenv(\"etalon\")));\n\tscanparams.etalondelay(atof(getenv(\"etalondelay\")));\n\tscanparams.interferedelay((double)atof(getenv(\"interferedelay\")));\n\n\tscanparams.chirp(\n\t\t\t( atof( getenv(\"chirp\") ) ) / std::pow(fsPau<float>(),int(2)), // the difference in slopes at omega_low versus omega_high must equal tspan\n\t\t\t( atof( getenv(\"TOD\") ) ) / std::pow(fsPau<float>(),int(3)),\n\t\t\t( atof( getenv(\"FOD\") ) ) / std::pow(fsPau<float>(),int(4)),\n\t\t\t( atof( getenv(\"fifthOD\") ) ) / std::pow(fsPau<float>(),int(5))\n\t\t\t);\n\n\n\tif (scanparams.addchirpnoise(atoi(getenv(\"usechirpnoise\"))>0)){\n\t\tscanparams.initchirpnoise( \n\t\t\t\t( atof( getenv(\"chirpnoise\") ) ) / std::pow(fsPau<float>(),int(2)), \n\t\t\t\t( atof( getenv(\"TODnoise\") ) ) / std::pow(fsPau<float>(),int(3)),\n\t\t\t\t( atof( getenv(\"FODnoise\") ) ) / std::pow(fsPau<float>(),int(4)),\n\t\t\t\t( atof( getenv(\"fifthODnoise\") ) ) / std::pow(fsPau<float>(),int(5))\n\t\t\t\t);\n\t}\n\n\n\n\n\tFiberBundle masterbundle(boost::lexical_cast<size_t>(atoi(getenv(\"nfibers\"))));\n\tmasterbundle.fiberdiameter(boost::lexical_cast<float>(atof(getenv(\"fiberdiam\"))));\n\tmasterbundle.laserdiameter(boost::lexical_cast<float>(atof(getenv(\"laserdiam\"))));\n\tmasterbundle.xraydiameter(boost::lexical_cast<float>(atof(getenv(\"xraydiam\"))));\n\tmasterbundle.set_fsPmm(boost::lexical_cast<float>(atof(getenv(\"bundle_fsPmm\"))));\n\tmasterbundle.scalePolarCoords();\n\n\tstd::cout << \"\\t\\tshuffle fibers?\\t\";\n\tif (getenv(\"shuffle_fibers\"))\n\t{\n\t\tstd::cout << \"yes\\n\";masterbundle.shuffle_output();\n\t} else {\n\t\tstd::cout << \"no\\n\";\n\t}\n\n\tmasterbundle.Ixray(float(1.));\n\tmasterbundle.Ilaser(float(1.));\n\tstd::string filename = scanparams.filebase() + \"fibermap.out\";\n\tstd::cout << \"fibermap file = \" << filename << std::endl << std::flush;\n\tstd::ofstream mapfile(filename.c_str(),std::ios::out);\n\t//masterbundle.print_mapping(mapfile,double(0.0));\n\tmapfile.close();\n\n\t// file for delay bins\n\tofstream outbins(std::string(scanparams.filebase() + \"delaybins.out\").c_str(),ios::out); \n\tfor (size_t f=0;f<masterbundle.get_nfibers();++f){\n\t\toutbins << masterbundle.delay(f) << \"\\n\";\n\t}\n\toutbins.close();\n\n\tMatResponse masterresponse(\n\t\t\t0,\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// stepdelay\n\t\t\t(double)( atof( getenv(\"stepwidth\") ) ),\t\t\t\t\t\t\t\t// stepwidth\n\t\t\t((double)( atof( getenv(\"attenuation\") ) ) - 1.0) * masterbundle.Ixray() / scanparams.ngroupsteps() + 1.0,\t// attenuation\n\t\t\t(double)( atof( getenv(\"phase\") ) ) * masterbundle.Ixray() / scanparams.ngroupsteps()\t\t\t\t// phase\n\t\t\t);\n\tmasterresponse.aalphabbeta(\n\t\t\t(double)( atof( getenv(\"a\") ) ),\t\t// a\n\t\t\t(double)( atof( getenv(\"alpha\" ) ) ),\t\t// alpha\n\t\t\t(double)( atof( getenv(\"b\") ) ),\t\t// b\n\t\t\t(double)( atof( getenv(\"beta\") ) )\t\t// beta\n\t\t\t);\n\n\tmasterresponse.setreflectance(scanparams.etalonreflectance());\n\tmasterresponse.setetalondelay(scanparams.etalondelay());\n\n\tstd::cout << \"initializing masterpulse and masterplans\" << std::endl << std::flush;\n\tPulseFreq masterpulse(scanparams.omega0(),scanparams.omega_width(),scanparams.omega_onoff(),scanparams.tspan());\n\tfftw_plan forward;\n\tfftw_plan backward;\n\tfftw_plan plan_r2hc;\n\tfftw_plan plan_hc2r;\n\tfftw_plan plan_r2hc_2x;\n\tfftw_plan plan_hc2r_2x;\n\tmasterpulse.setmasterplans(&forward,&backward);\n\tmasterpulse.setancillaryplans(& plan_r2hc,& plan_hc2r,& plan_r2hc_2x,& plan_hc2r_2x);\n\tmasterpulse.addchirp(scanparams.getchirp());\t\t\t\t\t\t\t// chirp that ref pulse\n\n\tdouble xrayphoton_energy = double(atof(getenv(\"xrayphoton_energy\")));\n\tmasterresponse.bandgap(double(atof(getenv(\"bandgap_eV\")))); //\n\n\tif (masterresponse.fill_carriersvec(masterpulse,xrayphoton_energy)){\n\t\tstd::cout << \"\\t OK, masterresponse.fill_carriersvec(masterpulse,9.5); filled with xrayphoton_energy = \" << xrayphoton_energy << \"\\n\" << std::flush;\n\t} else {\n\t\tstd::cout << \"\\t FAILED, masterresponse.fill_carriersvec(masterpulse,9.5); did not fill\\n\" << std::flush;\n\t}\n\n\n\tstd::time_t tstop = std::time(nullptr);\n\tstd::cout << \"\\tIt has taken \" << (tstop-tstart) << \" s so far for initializing masterpulse and building fftw plans\\n\" << std::flush;\n\n\tCalibMat calibration(boost::lexical_cast<size_t>(atoi(getenv(\"ncalibdelays\")))\n\t\t\t, boost::lexical_cast<double>(atof(getenv(\"fsWindow\"))));\n\tif (!getenv(\"skipcalibration\"))\n\t{\n\t\tstd::cout << \"\\t\\t############ entering calibration ###########\\n\" << std::flush;\n\t\tcalibration.set_center(boost::lexical_cast<double>(atof(getenv(\"delays_mean\"))));\n\t\tstd::cout << \"\\t\\t====== delays =======\\n\";\n\t\tfor (size_t i = 0 ; i< calibration.get_ndelays(); ++i){\n\t\t\tstd::cout << calibration.get_delay(i) << \" \";\n\t\t}\n\t\tstd::cout << std::endl << std::flush;\n\t}\n\n\n\n\tif (!getenv(\"skipcalibration\"))\n\t{\n\t\t// Setup the shared pulse arrays\n\t\tstd::vector< PulseFreq > calpulsearray(calibration.get_ndelays(),masterpulse);\n\n#pragma omp parallel num_threads(nthreads) default(shared) shared(masterpulse)\n\t\t{ // begin parallel region 1\n\t\t\tsize_t tid = omp_get_thread_num();\n\n\t\t\t// all non-shared objects must be created inside the parallel section for default is shared if defined outside\n\t\t\t// http://pages.tacc.utexas.edu/~eijkhout/pcse/html/omp-data.html\n\t\t\tPulseFreq etalonpulse(masterpulse);\n\t\t\tPulseFreq crossetalonpulse(masterpulse);\n\t\t\tPulseFreq calpulse(masterpulse);\n\t\t\tPulseFreq calcrosspulse(masterpulse);\n\n\t\t\t// initialize with masterpulse/masterresponse\n\t\t\tMatResponse calibresponse(masterresponse);\n\n\n\n#pragma omp for schedule(dynamic) \n\t\t\tfor (size_t d=0;d<calpulsearray.size();++d)\n\t\t\t{ // outermost loop for calibration.get_ndelays() to produce //\n\t\t\t\t//std::cout << \"\\tinside parallel region for actual loop d = \" \n\t\t\t\t//<< d << \"\\twith tid = \" << tid << \"\\n\" << std::flush;\n\t\t\t\tstd::cout << '+' << std::flush;\n\t\t\t\t//before each delay, reset to masterpulse\n\t\t\t\t//std::cerr << \"\\tmasterpulse.domain() = \" << masterpulse.domain() << \"\\n\" << std::flush;\n\t\t\t\tcalpulse = masterpulse;\n\t\t\t\tcalcrosspulse = masterpulse;\n\t\t\t\t//std::cerr << \"\\tcalpulse.domain() = \" << calpulse.domain() << \"\\n\" << std::flush;\n\t\t\t\t//std::cerr << \"\\tcalcrosspulse.domain() = \" << calcrosspulse.domain() << \"\\n\" << std::flush;\n\t\t\t\t//std::cerr << \"\\n\\n\\t\\t###### Made it here HERE HERE HERE debugging seg fault ######\\n\\n\" << std::flush;\n\n\t\t\t\tdouble startdelay(calibration.get_delay(d));\n\n\t\t\t\tcalcrosspulse.delay(scanparams.interferedelay()); // delay in the frequency domain\n\n\t\t\t\tcalpulse.fft_totime();\n\t\t\t\tcalcrosspulse.fft_totime();\n\n\t\t\t\t//std::cerr << \"\\tafter fft_totime() calpulse.domain() = \" << calpulse.domain() << \"\\n\" << std::flush;\n\t\t\t\t//std::cerr << \"\\tafter fft_totime() calcrosspulse.domain() = \" << calcrosspulse.domain() << \"\\n\" << std::flush;\n\n\t\t\t\tfor(size_t g=0;g<scanparams.ngroupsteps();g++){ // begin groupsteps loop\n\t\t\t\t\tcalibresponse.setdelay(startdelay - g*scanparams.groupstep()); // forward propagating, x-rays advance on the optical\n\t\t\t\t\tcalibresponse.setstepvec_amp(calpulse);\n\t\t\t\t\tcalibresponse.setstepvec_phase(calpulse);\n\t\t\t\t\tcalibresponse.setstepvec_amp(calcrosspulse);\n\t\t\t\t\tcalibresponse.setstepvec_phase(calcrosspulse);\n\t\t\t\t\tif (scanparams.doublepulse()){\n\t\t\t\t\t\tcalibresponse.addstepvec_amp(calpulse,scanparams.doublepulsedelay());\n\t\t\t\t\t\tcalibresponse.addstepvec_phase(calpulse,scanparams.doublepulsedelay());\n\t\t\t\t\t\tcalibresponse.addstepvec_amp(calcrosspulse,scanparams.doublepulsedelay());\n\t\t\t\t\t\tcalibresponse.addstepvec_phase(calcrosspulse,scanparams.doublepulsedelay());\n\t\t\t\t\t}\n\t\t\t\t\t// this pulls down the tail of the response so vector is periodic on nsamples\t\n\t\t\t\t\tcalibresponse.buffervectors(calpulse); \n\t\t\t\t\tcalibresponse.buffervectors(calcrosspulse); \n\t\t\t\t\tcalpulse.modulateamp_time();\n\t\t\t\t\tcalpulse.modulatephase_time();\n\t\t\t\t\tcalcrosspulse.modulateamp_time();\n\t\t\t\t\tcalcrosspulse.modulatephase_time();\n\t\t\t\t}// end groupsteps loop\n\n\n\n\t\t\t\tfor (size_t e=0;e<scanparams.netalon();e++){ // begin etalon loop\n\t\t\t\t\t// back propagation step //\n\t\t\t\t\tdouble etalondelay = startdelay - double(e+1) * (calibresponse.getetalondelay()); \n\t\t\t\t\t// at front surface, x-rays see counter-propagating light from one full etalon delay\n\n\t\t\t\t\t// reset back to calpulse for each round\n\t\t\t\t\tetalonpulse = calpulse;\n\t\t\t\t\tcrossetalonpulse = calcrosspulse;\n\t\t\t\t\t//std::cerr << \"\\t\\t\\t -- inside etalon: etalonpulse.domain() = \" << etalonpulse.domain() << \"\\n\" << std::flush;\n\t\t\t\t\t//std::cerr << \"\\t\\t\\t -- inside etalon: crossetalonpulse.domain() = \" << crossetalonpulse.domain() << \"\\n\" << std::flush;\n\n\t\t\t\t\tfor(size_t g=0;g<scanparams.ngroupsteps();g++){\n\t\t\t\t\t\tcalibresponse.setdelay(etalondelay + g*scanparams.backstep()); \n\t\t\t\t\t\t// counterpropagating, x-rays work backwards through the optical\n\n\t\t\t\t\t\tcalibresponse.setstepvec_amp(etalonpulse);\n\t\t\t\t\t\tcalibresponse.setstepvec_phase(etalonpulse);\n\t\t\t\t\t\tcalibresponse.setstepvec_amp(crossetalonpulse);\n\t\t\t\t\t\tcalibresponse.setstepvec_phase(crossetalonpulse);\n\t\t\t\t\t\tif (scanparams.doublepulse()){\n\t\t\t\t\t\t\tcalibresponse.addstepvec_amp(etalonpulse,scanparams.doublepulsedelay());\n\t\t\t\t\t\t\tcalibresponse.addstepvec_phase(etalonpulse,scanparams.doublepulsedelay());\n\t\t\t\t\t\t\tcalibresponse.addstepvec_amp(crossetalonpulse,scanparams.doublepulsedelay());\n\t\t\t\t\t\t\tcalibresponse.addstepvec_phase(crossetalonpulse,scanparams.doublepulsedelay());\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcalibresponse.buffervectors(etalonpulse); // this pulls down the tail of the response so vector is periodic on nsamples\n\t\t\t\t\t\tcalibresponse.buffervectors(crossetalonpulse); // this pulls down the tail of the response so vector is periodic on nsamples\n\t\t\t\t\t\t//std::cerr << \"\\t\\t\\t -- inside etalon groupsteps: before: etalonpulse.domain() = \" << etalonpulse.domain() << \"\\n\" << std::flush;\n\t\t\t\t\t\t//std::cerr << \"\\t\\t\\t -- inside etalon groupsteps: before: crossetalonpulse.domain() = \" << crossetalonpulse.domain() << \"\\n\" << std::flush;\n\t\t\t\t\t\tetalonpulse.modulateamp_time();\n\t\t\t\t\t\tetalonpulse.modulatephase_time();\n\t\t\t\t\t\tcrossetalonpulse.modulateamp_time();\n\t\t\t\t\t\tcrossetalonpulse.modulatephase_time();\n\t\t\t\t\t\t//std::cerr << \"\\t\\t\\t -- inside etalon groupsteps: after: etalonpulse.domain() = \" << etalonpulse.domain() << \"\\n\" << std::flush;\n\t\t\t\t\t\t//std::cerr << \"\\t\\t\\t -- inside etalon groupsteps: after: crossetalonpulse.domain() = \" << crossetalonpulse.domain() << \"\\n\" << std::flush;\n\t\t\t\t\t}\n\t\t\t\t\t// forward propagation //\n\t\t\t\t\tfor(size_t g=0;g<scanparams.ngroupsteps();g++){\n\t\t\t\t\t\tcalibresponse.setdelay(startdelay - g*scanparams.groupstep()); // forward propagating, x-rays advance on the optical\n\t\t\t\t\t\tcalibresponse.setstepvec_amp(etalonpulse);\n\t\t\t\t\t\tcalibresponse.setstepvec_phase(etalonpulse);\n\t\t\t\t\t\tcalibresponse.setstepvec_amp(crossetalonpulse);\n\t\t\t\t\t\tcalibresponse.setstepvec_phase(crossetalonpulse);\n\t\t\t\t\t\tif (scanparams.doublepulse()){\n\t\t\t\t\t\t\tcalibresponse.addstepvec_amp(etalonpulse,scanparams.doublepulsedelay());\n\t\t\t\t\t\t\tcalibresponse.addstepvec_phase(etalonpulse,scanparams.doublepulsedelay());\n\t\t\t\t\t\t\tcalibresponse.addstepvec_amp(crossetalonpulse,scanparams.doublepulsedelay());\n\t\t\t\t\t\t\tcalibresponse.addstepvec_phase(crossetalonpulse,scanparams.doublepulsedelay());\n\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcalibresponse.buffervectors(etalonpulse); // this pulls down the tail of the response so vector is periodic on nsamples\n\t\t\t\t\t\tcalibresponse.buffervectors(crossetalonpulse); // this pulls down the tail of the response so vector is periodic on nsamples\n\t\t\t\t\t\t//std::cerr << \"\\t\\t\\t -- inside etalon groupsteps forward prop: before: etalonpulse.domain() = \" << etalonpulse.domain() << \"\\n\" << std::flush;\n\t\t\t\t\t\t//std::cerr << \"\\t\\t\\t -- inside etalon groupsteps forward prop: before: crossetalonpulse.domain() = \" << crossetalonpulse.domain() << \"\\n\" << std::flush;\n\t\t\t\t\t\tetalonpulse.modulateamp_time();\n\t\t\t\t\t\tetalonpulse.modulatephase_time();\n\t\t\t\t\t\tcrossetalonpulse.modulateamp_time();\n\t\t\t\t\t\tcrossetalonpulse.modulatephase_time();\n\t\t\t\t\t\t//std::cerr << \"\\t\\t\\t -- inside etalon groupsteps forward prop: after: etalonpulse.domain() = \" << etalonpulse.domain() << \"\\n\" << std::flush;\n\t\t\t\t\t\t//std::cerr << \"\\t\\t\\t -- inside etalon groupsteps forward prop: after: crossetalonpulse.domain() = \" << crossetalonpulse.domain() << \"\\n\" << std::flush;\n\t\t\t\t\t}\n\t\t\t\t\t//std::cerr << \"\\t\\t\\t -- inside etalon finished groupsteps: etalonpulse.domain() = \" << etalonpulse.domain() << \"\\ttid = \"<< tid << \"\\n\" << std::flush;\n\t\t\t\t\t//std::cerr << \"\\t\\t\\t -- inside etalon finished groupsteps: crossetalonpulse.domain() = \" << crossetalonpulse.domain() << \"\\n\" << std::flush;\n\t\t\t\t\tetalonpulse.fft_tofreq();\n\t\t\t\t\tcrossetalonpulse.fft_tofreq();\n\t\t\t\t\tetalonpulse.delay(calibresponse.getetalondelay()); // delay and attenuate in frequency domain\n\t\t\t\t\tetalonpulse.attenuate(pow(calibresponse.getreflectance(),(int)2));\n\t\t\t\t\tcrossetalonpulse.delay(calibresponse.getetalondelay()); // delay and attenuate in frequency domain\n\t\t\t\t\tcrossetalonpulse.attenuate(pow(calibresponse.getreflectance(),(int)2));\n\t\t\t\t\tetalonpulse.fft_totime();\n\t\t\t\t\tcrossetalonpulse.fft_totime();\n\t\t\t\t\t//std::cerr << \"\\t\\t\\t -- end etalon: etalonpulse.domain() = \" << etalonpulse.domain() << \"\\n\" << std::flush;\n\t\t\t\t\t//std::cerr << \"\\t\\t\\t -- end etalon: crossetalonpulse.domain() = \" << crossetalonpulse.domain() << \"\\n\" << std::flush;\n\t\t\t\t\t//std::cerr << \"\\t\\t\\t -- end etalon: calpulse.domain() = \" << calpulse.domain() << \"\\n\" << std::flush;\n\t\t\t\t\t//std::cerr << \"\\t\\t\\t -- end etalon: calcrosspulse.domain() = \" << calcrosspulse.domain() << \"\\n\" << std::flush;\n\t\t\t\t\tcalpulse += etalonpulse;\n\t\t\t\t\tcalcrosspulse += crossetalonpulse;\n\t\t\t\t} // end etalon loop\n\n\n\t\t\t\t//std::cerr << \"\\t\\tbefore fft_tofreq(): calpulse.domain() = \" << calpulse.domain() << \"\\n\" << std::flush;\n\t\t\t\t//std::cerr << \"\\t\\tbefore fft_tofreq(): calcrosspulse.domain() = \" << calcrosspulse.domain() << \"\\n\" << std::flush;\n\t\t\t\tcalpulse.fft_tofreq();\n\t\t\t\tcalcrosspulse.fft_tofreq();\n\t\t\t\tcalpulse.delay(scanparams.interferedelay()); // expects this in fs // time this back up to the crosspulse\n\n\t\t\t\tcalpulse -= calcrosspulse;\n\t\t\t\t// reversing order for sake of chirp calib matrix\n\t\t\t\tcalpulsearray[calpulsearray.size()-d-1] = calpulse;\n\n\t\t\t\t/*\n\t\t\t\t   std::cerr << \"\\t\\tcalpulse.domain() = \" << calpulse.domain() << \"\\n\" << std::flush;\n\t\t\t\t   std::cerr << \"\\t\\tcalcrosspulse.domain() = \" << calcrosspulse.domain() << \"\\n\" << std::flush;\n\t\t\t\t   std::cerr << \"\\t\\tcalpulsearray[ \" << (calpulsearray.size()-d-1) << \" ].domain() = \" \n\t\t\t\t   << calpulsearray[calpulsearray.size()-d-1].domain() << \"\\n\" << std::flush;\n\t\t\t\t   */\n\t\t\t} // end of loop calibration.get_ndelays() to produce //\n\n\n#pragma omp barrier\n\n#pragma omp master\n\t\t\t{\n\t\t\t\tstd::cout << \"|\\t done with calibration delays\\n\" << std::flush;\n\t\t\t\t//std::cerr << \"\\t\\t###### Made it here too #####\\n\\t\\t##### should call only once in master #######\\n\" << std::flush;\n\t\t\t\t// print out the calibration as ascii for now //\n\t\t\t\t// print rows in order, eventually in tf_record or matrix or so. //\n\t\t\t\tstd::string calfilename = scanparams.calfilebase() + \"interference.calibration\";\n\t\t\t\tstd::string calfilename_delays = scanparams.calfilebase() + \"interference.calibration.delays\";\n\t\t\t\tstd::string calfilename_wavelengths = scanparams.calfilebase() + \"interference.calibration.wavelengths\";\n\t\t\t\tofstream calibrationstream(calfilename.c_str(),ios::out); \n\t\t\t\tofstream calibrationstream_delays(calfilename_delays.c_str(),ios::out); \n\t\t\t\tofstream calibrationstream_wavelengths(calfilename_wavelengths.c_str(),ios::out); \n\t\t\t\t/*\n\t\t\t\tstd::string bin_calfilename = scanparams.filebase() + \"interference.calibration.bin\";\n\t\t\t\tofstream bin_calibrationstream(bin_calfilename.c_str(),ios::out | ios::binary); \n\t\t\t\tstd::cout << \"\\tcalibration filename out = \" << calfilename << \"\\n\\t and \\t\" << bin_calfilename << std::endl;\n\t\t\t\t*/\n\t\t\t\tcalibrationstream << \"# wavelengths\\n#\";\n\t\t\t\tcalpulsearray[0].printwavelengthbins(&calibrationstream);\n\t\t\t\tcalpulsearray[0].printwavelengthbins(&calibrationstream_wavelengths);\n\t\t\t\tcalibrationstream << \"# delays\\n#\";\n\t\t\t\tcalibrationstream_delays << \"# delays\\n\";\n\t\t\t\tfor (size_t i = 0 ; i< calibration.get_ndelays(); ++i){\n\t\t\t\t\tcalibrationstream << calibration.get_delay(i) << \"\\t\";\n\t\t\t\t\tcalibrationstream_delays << calibration.get_delay(i) << \"\\t\";\n\t\t\t\t}\n\t\t\t\tcalibrationstream << \"\\n\";\n\t\t\t\tcalibrationstream_delays << \"\\n\";\n\n\t\t\t\tfor (size_t n=0;n<calpulsearray.size();++n){\n\t\t\t\t\tcalpulsearray[n].appendwavelength(&calibrationstream);\n\t\t\t\t\t//\tcalpulsearray[n].appendwavelength_bin(&bin_calibrationstream);\n\t\t\t\t}\n\n\t\t\t\tcalibrationstream.close();\n\t\t\t\tcalibrationstream_delays.close();\n\t\t\t\tcalibrationstream_wavelengths.close();\n\t\t\t\t//bin_calibrationstream.close();\n\t\t\t\tstd::cout << \"Finished with the calibration image/matrix\\n\" << std::flush;\n\n\n\t\t\t}\n\n#pragma omp master\n\t\t\t{\n\t\t\t\tstd::cout << \"\\t\\t############ ending parallel region 1 ###########\\n\" << std::flush;\n\t\t\t}\n\t\t} // end parallel region 1\n\n\t} // end if (!getenv(\"skipcalibration\"))\n\n\n\t//############## Images section ##############\n\n#pragma omp parallel num_threads(nthreads) default(shared) shared(masterpulse)\n\t\t{\n\tif (!getenv(\"skipimages\"))\n\t{\n\t\tstd::cout << \"\\t\\t############ entering parallel/images ###########\\n\" << std::flush;\n\t\t\tsize_t tid = omp_get_thread_num();\n\t\t\tsize_t nfibers = masterbundle.get_nfibers();\n\n\t\t\tFiberBundle parabundle(masterbundle);\n\t\t\tMatResponse pararesponse(masterresponse);\n\n\t\t\tPulseFreq pulse(masterpulse);\n\t\t\tPulseFreq crosspulse(masterpulse);\n\t\t\tPulseFreq etalonpulse(masterpulse);\n\t\t\tPulseFreq crossetalonpulse(masterpulse);\n\t\t\tstd::vector< PulseFreq > pulsearray(nfibers,PulseFreq(masterpulse));\n#pragma omp barrier\n\n\t\t\tif (scanparams.addrandomphase(atoi(getenv(\"addrandomphase\"))>0))\n\t\t\t{\n\t\t\t\tmasterpulse.addrandomphase();\n\t\t\t\tstd::string filename = scanparams.filebase() + \"spectralphaseFTpower.dat\";\n\t\t\t\tstd::ofstream outfile(filename.c_str(),std::ios::out);\n\t\t\t\tmasterpulse.print_phase_powerspectrum(outfile);\n\t\t\t\toutfile.close();\n\t\t\t\tfilename = scanparams.filebase() + \"spectralphase.dat\";\n\t\t\t\toutfile.open(filename.c_str(),std::ios::out);\n\t\t\t\tmasterpulse.print_phase(outfile);\n\t\t\t\toutfile.close();\n\t\t\t\tfilename = scanparams.filebase() + \"spectralamp.dat\";\n\t\t\t\toutfile.open(filename.c_str(),std::ios::out);\n\t\t\t\tmasterpulse.print_amp(outfile);\n\t\t\t\toutfile.close();\n\t\t\t}\n\n\n#pragma omp for schedule(dynamic)\n\t\t\tfor (size_t n=0;n<scanparams.nimages();++n)\n\t\t\t{ // outermost loop for nimages to produce //\n\t\t\t\t//std::cerr << \"\\tinside the parallel region 2 for images loop n = \" << n << \" in thread \" << tid << \"\\n\" << std::flush;\n\t\t\t\tif (n==0 & tid==0) {\n\t\t\t\t\tstd::cout << \"=========================================================================\"\n\t\t\t\t\t\t<<   \"\\n\\t\\t ==== http://www.fftw.org/fftw3_doc/Advanced-Complex-DFTs.html ====\"\n\t\t\t\t\t\t<<   \"\\n\\t\\t ====         use this for defining multiple fibers as         ====\"\n\t\t\t\t\t\t<<   \"\\n\\t\\t ====         contiguous blocks for row-wise FFT as 2D         ====\"\n\t\t\t\t\t\t<<   \"\\n\\t\\t ==================================================================\\n\" << std::flush;\n\t\t\t\t}\n\n\t\t\t\tstd::time_t imgstart = std::time(nullptr);\n\n\t\t\t\tdouble t0 = scanparams.delays_uniform();\n\t\t\t\tdouble startdelay(0);\n\n\t\t\t\tparabundle = masterbundle;\n\n\n\t\t\t\tparabundle.Ixray(scanparams.xray_inten_rand());\n\t\t\t\tparabundle.Ilaser(scanparams.laser_inten_rand());\n\t\t\t\tparabundle.delay_angle(scanparams.dalpha()*double(n));\n\t\t\t\tparabundle.center_Ixray(scanparams.xray_pos_rand(),scanparams.xray_pos_rand());\n\t\t\t\tparabundle.center_Ilaser(scanparams.laser_pos_rand(),scanparams.laser_pos_rand());\n\n\n\n\t\t\t\t//DebugOps::pushout(std::string(\"Running image \" + std::to_string(n) + \" for t0 = \" + std::to_string(t0) + \" in threaded for loop, thread \" + std::to_string(tid)));\n\t\t\t\tstd::string mapfilename = scanparams.filebase() + \"fibermap.out.\" + std::to_string(n);\n\t\t\t\t//std::cout << \"fibermap file = \" << mapfilename << std::endl << std::flush;\n\t\t\t\tstd::ofstream mapfile(mapfilename.c_str(),std::ios::out);\n\t\t\t\tparabundle.print_mapping(mapfile,t0);\n\t\t\t\tmapfile.close();\n\n\n\t\t\t\tfor(size_t f = 0; f < parabundle.get_nfibers(); f++)\n\t\t\t\t{ // begin fibers loop\n\t\t\t\t\tpulse = masterpulse;\n\t\t\t\t\tcrosspulse = masterpulse;\n\t\t\t\t\tstartdelay = t0 + parabundle.delay(f);\n\t\t\t\t\tpulse.scale(parabundle.Ilaser(f));\n\t\t\t\t\tcrosspulse.scale(parabundle.Ilaser(f));\n\n\t\t\t\t\tpararesponse = masterresponse;\n\n\t\t\t\t\tif (getenv(\"scale_fibers\")){\n\t\t\t\t\t\tpararesponse.setscale(parabundle.Ixray(f));\n\t\t\t\t\t\t//std::cerr << \"parabundle.Ixray(\" << f << \") = \" << parabundle.Ixray(f) << \"\\n\" << std::flush;\n\t\t\t\t\t}\n\n\t\t\t\t\tif (scanparams.addchirpnoise()){\n\t\t\t\t\t\tstd::vector<double> noise(scanparams.getchirpnoise());\n\t\t\t\t\t\tpulse.addchirp(noise); \n\t\t\t\t\t\tcrosspulse.addchirp(noise); \n\t\t\t\t\t}\n\n\t\t\t\t\tcrosspulse.delay(scanparams.interferedelay()); // delay in the frequency domain\n\t\t\t\t\tpulse.fft_totime();\n\t\t\t\t\tcrosspulse.fft_totime();\n\n\t\t\t\t\tfor(size_t g=0;g<scanparams.ngroupsteps();g++){ // begin groupsteps loop\n\t\t\t\t\t\tpararesponse.setdelay(startdelay - g*scanparams.groupstep()); // forward propagating, x-rays advance on the optical\n\t\t\t\t\t\tpararesponse.setstepvec_amp(pulse);\n\t\t\t\t\t\tpararesponse.setstepvec_phase(pulse);\n\t\t\t\t\t\tpararesponse.setstepvec_amp(crosspulse);\n\t\t\t\t\t\tpararesponse.setstepvec_phase(crosspulse);\n\t\t\t\t\t\tif (scanparams.doublepulse()){\n\t\t\t\t\t\t\tpararesponse.addstepvec_amp(pulse,scanparams.doublepulsedelay());\n\t\t\t\t\t\t\tpararesponse.addstepvec_phase(pulse,scanparams.doublepulsedelay());\n\t\t\t\t\t\t\tpararesponse.addstepvec_amp(crosspulse,scanparams.doublepulsedelay());\n\t\t\t\t\t\t\tpararesponse.addstepvec_phase(crosspulse,scanparams.doublepulsedelay());\n\t\t\t\t\t\t}\n\t\t\t\t\t\t// this pulls down the tail of the response so vector is periodic on nsamples\t\n\t\t\t\t\t\tpararesponse.buffervectors(pulse); \n\t\t\t\t\t\tpararesponse.buffervectors(crosspulse); \n\t\t\t\t\t\tpulse.modulateamp_time();\n\t\t\t\t\t\tpulse.modulatephase_time();\n\t\t\t\t\t\tcrosspulse.modulateamp_time();\n\t\t\t\t\t\tcrosspulse.modulatephase_time();\n\t\t\t\t\t}// end groupsteps loop\n\t\t\t\t\t//std::cerr << \"tid = \" << tid << \"\\tpulse/crosspulse.domain() = \" << pulse.domain() << \"/\" << crosspulse.domain() << \"\\n\" << std::flush;\n\n\n\t\t\t\t\tfor (size_t e=0;e<scanparams.netalon();e++){ // begin etalon loop\n\t\t\t\t\t\t//std::cerr << \"tid = \" << tid << \"\\tpulse/crosspulse.domain() = \" << pulse.domain() << \"/\" << crosspulse.domain() << \"\\n\" << std::flush;\n\t\t\t\t\t\t//std::cerr << \"\\n\\t\\t ---- starting etalon at \" << e << \" ----\\n\" << std::flush;\n\t\t\t\t\t\t// back propagation step //\n\t\t\t\t\t\tdouble etalondelay = startdelay - double(e+1) * (pararesponse.getetalondelay()); \n\t\t\t\t\t\t// at front surface, x-rays see counter-propagating light from one full etalon delay\n\n\t\t\t\t\t\tetalonpulse = pulse;\n\t\t\t\t\t\tcrossetalonpulse = crosspulse;\n\t\t\t\t\t\t//std::cerr << \"etalonpulse/crossetalonpulse.domain() = \" << etalonpulse.domain() << \"/\" << crossetalonpulse.domain() << \"\\n\" << std::flush;\n\n\t\t\t\t\t\tfor(size_t g=0;g<scanparams.ngroupsteps();g++){\n\t\t\t\t\t\t\tpararesponse.setdelay(etalondelay + g*scanparams.backstep()); \n\t\t\t\t\t\t\t// counterpropagating, x-rays work backwards through the optical\n\n\t\t\t\t\t\t\tpararesponse.setstepvec_amp(etalonpulse);\n\t\t\t\t\t\t\tpararesponse.setstepvec_phase(etalonpulse);\n\t\t\t\t\t\t\tpararesponse.setstepvec_amp(crossetalonpulse);\n\t\t\t\t\t\t\tpararesponse.setstepvec_phase(crossetalonpulse);\n\t\t\t\t\t\t\tif (scanparams.doublepulse()){\n\t\t\t\t\t\t\t\tpararesponse.addstepvec_amp(etalonpulse,scanparams.doublepulsedelay());\n\t\t\t\t\t\t\t\tpararesponse.addstepvec_phase(etalonpulse,scanparams.doublepulsedelay());\n\t\t\t\t\t\t\t\tpararesponse.addstepvec_amp(crossetalonpulse,scanparams.doublepulsedelay());\n\t\t\t\t\t\t\t\tpararesponse.addstepvec_phase(crossetalonpulse,scanparams.doublepulsedelay());\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tpararesponse.buffervectors(etalonpulse); // this pulls down the tail of the response so vector is periodic on nsamples\n\t\t\t\t\t\t\tpararesponse.buffervectors(crossetalonpulse); // this pulls down the tail of the response so vector is periodic on nsamples\n\t\t\t\t\t\t\tetalonpulse.modulateamp_time();\n\t\t\t\t\t\t\tetalonpulse.modulatephase_time();\n\t\t\t\t\t\t\tcrossetalonpulse.modulateamp_time();\n\t\t\t\t\t\t\tcrossetalonpulse.modulatephase_time();\n\t\t\t\t\t\t}\n\t\t\t\t\t\t// forward propagation //\n\t\t\t\t\t\t//std::cerr << \"\\t\\t\\t ########### // forward propagation // #############\\n\" << std::flush;\n\t\t\t\t\t\tfor(size_t g=0;g<scanparams.ngroupsteps();g++){\n\t\t\t\t\t\t\tpararesponse.setdelay(startdelay - g*scanparams.groupstep()); // forward propagating, x-rays advance on the optical\n\t\t\t\t\t\t\tpararesponse.setstepvec_amp(etalonpulse);\n\t\t\t\t\t\t\tpararesponse.setstepvec_phase(etalonpulse);\n\t\t\t\t\t\t\tpararesponse.setstepvec_amp(crossetalonpulse);\n\t\t\t\t\t\t\tpararesponse.setstepvec_phase(crossetalonpulse);\n\t\t\t\t\t\t\tif (scanparams.doublepulse()){\n\t\t\t\t\t\t\t\tpararesponse.addstepvec_amp(etalonpulse,scanparams.doublepulsedelay());\n\t\t\t\t\t\t\t\tpararesponse.addstepvec_phase(etalonpulse,scanparams.doublepulsedelay());\n\t\t\t\t\t\t\t\tpararesponse.addstepvec_amp(crossetalonpulse,scanparams.doublepulsedelay());\n\t\t\t\t\t\t\t\tpararesponse.addstepvec_phase(crossetalonpulse,scanparams.doublepulsedelay());\n\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tpararesponse.buffervectors(etalonpulse); // this pulls down the tail of the response so vector is periodic on nsamples\n\t\t\t\t\t\t\tpararesponse.buffervectors(crossetalonpulse); // this pulls down the tail of the response so vector is periodic on nsamples\n\t\t\t\t\t\t\tetalonpulse.modulateamp_time();\n\t\t\t\t\t\t\tetalonpulse.modulatephase_time();\n\t\t\t\t\t\t\tcrossetalonpulse.modulateamp_time();\n\t\t\t\t\t\t\tcrossetalonpulse.modulatephase_time();\n\t\t\t\t\t\t}\n\t\t\t\t\t\t//std::cerr << \"etalonpulse/crossetalonpulse.domain() = \" << etalonpulse.domain() << \"/\" << crossetalonpulse.domain() << \"\\n\" << std::flush;\n\t\t\t\t\t\tetalonpulse.fft_tofreq();\n\t\t\t\t\t\tcrossetalonpulse.fft_tofreq();\n\t\t\t\t\t\tetalonpulse.delay(pararesponse.getetalondelay()); // delay and attenuate in frequency domain\n\t\t\t\t\t\tetalonpulse.attenuate(pow(pararesponse.getreflectance(),(int)2));\n\t\t\t\t\t\tcrossetalonpulse.delay(pararesponse.getetalondelay()); // delay and attenuate in frequency domain\n\t\t\t\t\t\tcrossetalonpulse.attenuate(pow(pararesponse.getreflectance(),(int)2));\n\t\t\t\t\t\tetalonpulse.fft_totime();\n\t\t\t\t\t\tcrossetalonpulse.fft_totime();\n\t\t\t\t\t\tpulse += etalonpulse;\n\t\t\t\t\t\tcrosspulse += crossetalonpulse;\n\t\t\t\t\t} // end etalon loop\n\n\n\t\t\t\t\tpulse.fft_tofreq();\n\t\t\t\t\tcrosspulse.fft_tofreq();\n\t\t\t\t\tpulse.delay(scanparams.interferedelay()); // expects this in fs // time this back up to the crosspulse\n\t\t\t\t\tpulse -= crosspulse;\n\t\t\t\t\t// std::cerr << \"\\n\\n\\t\\t\\t\\t============== testing... just before the push_back() ==============\\n\\n\" << std::flush;\n\t\t\t\t\tpulsearray[f] = pulse;\n\t\t\t\t} // end nfibers loop\n\n\n\t\t\t\tstd::string filename = scanparams.filebase() + \"interference.out.\" + std::to_string(n);// + \".tid\" + std::to_string(tid);\n\t\t\t\t//std::cerr << \"testing: filename = \" << filename << \"\\n\" << std::flush;\n\t\t\t\tofstream interferestream(filename.c_str(),ios::out); // use app to append delays to same file.\n\n\t\t\t\t//std::cout << \"tid = \" << tid << \": interfere filename out = \" << filename << std::endl;\n\t\t\t\tstd::complex<double> z_laser = parabundle.center_Ilaser();\n\t\t\t\tstd::complex<double> z_xray = parabundle.center_Ixray();\n\t\t\t\tinterferestream << \"#delay for image = \\t\" << t0 \n\t\t\t\t\t<< \"\\n#Ilaser = \\t\" << parabundle.Ilaser()\n\t\t\t\t\t<< \"\\n#Ixray = \\t\" << parabundle.Ixray()\n\t\t\t\t\t<< \"\\n#center laser = \\t\" << z_laser.real() << \"\\t\" << z_laser.imag() \n\t\t\t\t\t<< \"\\n#center xray = \\t\" << z_xray.real() << \"\\t\" << z_xray.imag()\n\t\t\t\t\t<< \"\\n#alpha = \\t\" << parabundle.delay_angle() \n\t\t\t\t\t<< std::endl;\n\t\t\t\tinterferestream << \"#\";\n\t\t\t\tpulsearray[0].printwavelengthbins(&interferestream);\n\t\t\t\tfor (size_t f=0;f<pulsearray.size();f++){\n\t\t\t\t\tpulsearray[f].scale(parabundle.Ilaser(f)); \n\t\t\t\t\tpulsearray[f].appendwavelength(&interferestream);\n\t\t\t\t}\n\t\t\t\tif (tid % 10 < 2){\n\t\t\t\t\tfor (size_t f=0;f<parabundle.get_nfibers();f++){\n\t\t\t\t\t\tint max = boost::lexical_cast<double>(getenv(\"gain\")) * pulsearray[f].maxsignal();\n\t\t\t\t\t\tfor (size_t i=0;i<std::log(max);++i){\n\t\t\t\t\t\t\tstd::cout << '.';\n\t\t\t\t\t\t}\n\t\t\t\t\t\tstd::cout << \"|\";\n\t\t\t\t\t}\n\t\t\t\t\tstd::cout << \"\\timg = \" << n << \" in tid = \" << tid << \"\\n\" << std::flush;\n\t\t\t\t}\n\t\t\t\tinterferestream.close();\n\n\t\t\t\tstd::time_t imgstop = std::time(nullptr);\n\t\t\t\timagetimes[n] = float(imgstop - imgstart);\n\n\t\t\t} // outermost loop for nimages to produce //\n\n#pragma omp master\n\t\t\t{\n\t\t\t\tstd::cout << \"\\t\\t############ ending parallel region 2 ###########\\n\" << std::flush;\n\t\t\t}\n\n#pragma omp barrier\n\n\t\t\t//std::cerr << \"\\n\\t... trying to leave parallel region 2\" << std::endl;\n\t} // end if (!getenv(\"skipimages\")\n\t\t} // end parallel region\n\n\t//std::cout << \"\\n ---- just left parallel region ----\" << std::endl;\n\tstd::cout << \"masterresponse reflectance: \" << masterresponse.getreflectance() << std::endl;\n\tstd::cout << \"masterbundle fiberdiameter: \" << masterbundle.fiberdiameter() << std::endl;\n\tstd::cout << \"scanparams lambda_0: \" << scanparams.lambda_0() << std::endl;\n\tfftw_destroy_plan(forward);\n\tfftw_destroy_plan(backward);\n\n\ttstop = std::time(nullptr);\n\ttstop -= tstart;\n\tstd::cout << \"\\t\\t======================================\\n\"\n\t\t<< \"\\t\\t======== scan_material stopped =======\\n\"\n\t\t<< \"\\t\\t===== \" << std::asctime(std::localtime(&tstop)) \n\t\t<< \"\\t\\t===== in \" << tstop << \" s \\n\"\n\t\t<< \"\\t\\t======================================\\n\" << std::flush;\n\tstd::string timesfilename = scanparams.filebase() + \"runtimes.log\";\n\tstd::ofstream timesout(timesfilename.c_str(),std::ios::app);\n\ttimesout << \"#########################################\\n\" << std::flush;\n\ttimesout << \"# HOSTNAME:\\t\" << getenv(\"HOSTNAME\") << \"\\n\" << std::flush;\n\ttimesout << \"# total time (seconds):\\t\" << tstop << \"\\n\" << std::flush;\n\ttimesout << \"# nfibers :\\t\" << masterbundle.get_nfibers() << \"\\n\" << std::flush;\n\ttimesout << \"# nthreads :\\t\" << nthreads << \"\\n\" << std::flush;\n\ttimesout << \"# mean time / image:\\t\" << DataOps::mean(imagetimes) \n\t\t<< \"\\t/ fiber\\t\" << DataOps::mean(imagetimes)/float(masterbundle.get_nfibers()) << \"\\n\" << std::flush;\n\tfor (size_t i=0 ;i< imagetimes.size();++i){\n\t\ttimesout << imagetimes[i] << \"\\t\";\n\t}\n\ttimesout << \"\\n\" << std::flush;\n\ttimesout.close();\n\n\treturn 0;\n}\n\n\n", "meta": {"hexsha": "eb4535c300945f20e2fd0914d1f1f17b5c4325cf", "size": 31666, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/scan_material.cpp", "max_stars_repo_name": "ryancoffee/2dtimetool_simulation", "max_stars_repo_head_hexsha": "4ca4b585f35a04e81111a67c5bf6aaef931ee03c", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/scan_material.cpp", "max_issues_repo_name": "ryancoffee/2dtimetool_simulation", "max_issues_repo_head_hexsha": "4ca4b585f35a04e81111a67c5bf6aaef931ee03c", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/scan_material.cpp", "max_forks_repo_name": "ryancoffee/2dtimetool_simulation", "max_forks_repo_head_hexsha": "4ca4b585f35a04e81111a67c5bf6aaef931ee03c", "max_forks_repo_licenses": ["BSD-3-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.8431952663, "max_line_length": 168, "alphanum_fraction": 0.6575191057, "num_tokens": 8866, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7090191337850932, "lm_q2_score": 0.49218813572079556, "lm_q1q2_score": 0.3489708056480583}}
{"text": "#include \"HashTableHandler.h\"\n#include <stdio.h>\n#include <string>\n#include <map>\n#include <fstream>\n#include \"llvm/Support/raw_ostream.h\"\n#include <cstdio>\n#include <iostream>\n#include <memory>\n#include <stdexcept>\n#include <array>\n#include <regex>\n#include \"helper.h\"\n#include \"klee/ExecutionState.h\"\n#include \"klee/Internal/ADT/RNG.h\"\n#include <boost/math/distributions/binomial.hpp>\n#include \"Executor.h\"\n#include <cmath>\n#include \"klee/klee.h\"\n\n// TODO: use macros in klee.h instead of hard-coded return values.\n\nusing namespace klee;\nusing namespace std;\nusing namespace llvm;\nusing boost::math::binomial;\n\nnamespace klee {\n  extern RNG theRNG;\n}\n\nHashTableHandler::HashTableHandler(Executor &_executor)\n: executor(_executor)\n{\n   printf(\"new ht handler created!\\n\");\n}\n\nHashTableHandler::HashTableHandler(HashTableHandler &_handler)\n: executor(_handler.executor)\n{\n\n}\n\nHashTableHandler::~HashTableHandler()\n{\n\n}\n\nHashTable::HashTable()\n{\n}\n\nHashTable::HashTable(int _size):\n   status(-1),\n   size(_size),\n   cur_size(0)\n{\n   // create an empty table\n   LOG(LOG_MASK_HT, \"creating an empty hash table, size=%d\", _size);\n}\n\nHashTable::HashTable(const HashTable &_table):\n   status(_table.status),\n   size(_table.size),\n   cur_size(_table.cur_size),\n   dist(_table.dist)\n{\n}\n\nHashTable::~HashTable()\n{\n}\n\nint HashTableHandler::ht_init(ExecutionState &cur, size_t sz)\n{\n   LOG(LOG_MASK_HT, \"allocating table size=%ld\", sz);\n   cur.table = new HashTable(sz);\n\n   // TODO: add deletion of the hash table\n   return 0;\n}\n\nint HashTableHandler::ht_get_max(ExecutionState &cur)\n{\n   HashTable *t = cur.table;\n   int max = 0;\n   for (auto x : t->dist) {\n      if (x.first > max) {\n         max = x.first;\n      }\n   }\n   LOG(LOG_MASK_HT, \"returning max val in ht = %d\", max);\n   return max;\n}\n\nint HashTableHandler::ht_access(ExecutionState &cur,\n                                vector<ExecutionState*> &states,\n                                vector<int> &rets)\n{\n   HashTable *t = cur.table;\n   assert(t);\n\n   LOG(LOG_MASK_HT, \"accessing table, cur size=%d\", t->cur_size);\n\n   // processing the first access\n   if (t->cur_size == 0) {\n      LOG(LOG_MASK_HT, \"table is empty, can only insert entry, pathprob=%f\",\n          cur.getPathProb());\n      t->status = GREYBOX_MISS;\n      states.push_back(&cur);\n      rets.push_back(GREYBOX_MISS);\n      return 0;\n   }\n\n   // TODO: cannot insert to empty if table is full\n   assert(t->cur_size < t->size);\n\n   // Obtain per-path probabilities\n   double probEmpty = 1 - ((double) t->cur_size) / ((double) t->size);\n   double probNonEmpty = 1 - probEmpty;\n   double probCollision = probNonEmpty * (1.0 / (double) t->size);\n   double probHit = probNonEmpty - probCollision;\n   assert(probEmpty + probCollision + probHit > 0.99);\n\n   LOG(LOG_MASK_HT, \"table not empty, pathprob=%g, empty=%g,hit=%g,col=%g\",\n       cur.getPathProb(), probEmpty, probHit, probCollision);\n\n   // if we are doing Monte Carlo sampling, just pick up one state\n   if (cur.isSample == true) {\n      assert(cur.isSampleDone == false);\n\n      double r = theRNG.getDouble();\n\n      LOG(LOG_MASK_HT, \"r=%f\", r);\n\n      // pick up a branch according to per-path prob\n      states.push_back(&cur);\n      t = states[0]->table;\n      if (r < probEmpty) {\n         cur.updatePathProb(probEmpty);\n         t->status = GREYBOX_MISS;\n         rets.push_back(GREYBOX_MISS);\n         LOG(LOG_MASK_HT, \"access=empty, pathprob=%f\", cur.getPathProb());\n      } else if (probEmpty <= r && r < probEmpty + probCollision) {\n         cur.updatePathProb(probCollision);\n         t->status = GREYBOX_COL;\n         rets.push_back(GREYBOX_COL);\n         LOG(LOG_MASK_HT, \"access=col, pathprob=%f\", cur.getPathProb());\n      } else {\n         cur.updatePathProb(probHit);\n         t->status = GREYBOX_HIT;\n         rets.push_back(GREYBOX_HIT);\n         LOG(LOG_MASK_HT, \"access=hit, pathprob=%f\", cur.getPathProb());\n      }\n\n      return 0;\n   }\n\n   // fork three states\n   executor.branchTableAccessNoCond(cur, 3, states);\n   rets.push_back(GREYBOX_MISS);\n   rets.push_back(GREYBOX_HIT);\n   rets.push_back(GREYBOX_COL);\n   assert(states.size() == 3);\n   assert(rets.size() == 3);\n\n   // empty prob\n   states[0]->updatePathProb(probEmpty);\n   // hit prob\n   states[1]->updatePathProb(probHit);\n   // collision prob\n   states[2]->updatePathProb(probCollision);\n\n   // empty\n   t = states[0]->table;\n   t->status = GREYBOX_MISS;\n\n   // hit\n   t = states[1]->table;\n   t->status = GREYBOX_HIT;\n\n   // collision\n   t = states[2]->table;\n   t->status = GREYBOX_COL;\n\n   return 0;\n}\n\nint HashTableHandler::ht_check(ExecutionState &cur, int &status)\n{\n   ERR(\"not implemented\");\n   assert(0);\n   return 0;\n}\n\n// Based the previous access result, return a branch for each possible\n// value in the table\nint HashTableHandler::ht_read(ExecutionState &cur,\n                              vector<ExecutionState*> &states,\n                              vector<int> &rets)\n{\n   HashTable *t = cur.table;\n\n   LOG(LOG_MASK_HT, \"reading HT, status=%d, cur_size=%d\", t->status,\n       t->cur_size);\n\n   // the access misses the table, have to return 0\n   if (t->status == GREYBOX_MISS) {\n      rets.push_back(HT_READ_FALSE);\n      states.push_back(&cur);\n      return 0;\n   }\n\n   // hit or collision\n   assert(t->dist.size() > 0);\n   executor.branchTableAccessNoCond(cur, t->dist.size(), states);\n\n   int i = 0;\n   for (auto x : t->dist) {\n      rets.push_back(x.first);\n      states[i]->updatePathProb(x.second);\n      LOG(LOG_MASK_HT, \"read value=%d, prob=%g, pathProb=%g\", x.first,\n          x.second, states[i]->getPathProb());\n      i ++;\n   }\n\n   return 0;\n}\n\n// Write val to the table, based on previous access result\n// This API doesn't fork states\nint HashTableHandler::ht_write(ExecutionState &cur, int val)\n{\n   HashTable *t = cur.table;\n   int num = t->cur_size;\n   double p0 = t->dist[0];\n   double p1 = t->dist[1];\n\n   // empty table, and we just missed the table\n   if (num == 0) {\n      assert(t->status == GREYBOX_MISS);\n      LOG(LOG_MASK_HT, \"writing %d to an empty table\", val);\n      if (val == 0) {\n         t->dist[0] = 1;\n         t->dist[1] = 0;\n      } else if (val == 1) {\n         t->dist[0] = 0;\n         t->dist[1] = 1;\n      }\n      t->cur_size += 1;\n      return 0;\n   }\n\n   // Table not empty, but we just missed the table\n   if (t->status == GREYBOX_MISS) {\n      for (auto d: t->dist) {\n         if (d.first == val) {\n            d.second = (d.second * num + 1) / (num + 1);\n         } else {\n            d.second = (d.second * num) / (num + 1);\n         }\n      }\n      t->cur_size += 1;\n      return 0;\n   }\n\n      // write 1 to an empty entry\n      /*\n      if (val == 1) {\n         t->dist[0] = (p0 * num) / (num + 1);\n         t->dist[1] = 1 - t->dist[0];\n      } else if (val == 0) {\n         t->dist[0] = (p0 * num + 1) / (num + 1);\n         t->dist[1] = 1 - t->dist[0];\n      }\n      */\n\n\n   // Table not empty, and we just hit or collide on an existing entry\n   // TODO: only support binary HT\n   if (t->dist.size() > 2) {\n      t->dump();\n   }\n   assert(t->dist.size() <= 2);\n   if (val == 1) {\n      t->dist[0] = p0 * ((p0 * num - 1) / num) + (p0 * p1);\n      t->dist[1] = 1 - t->dist[0];\n   } else if (val == 0) {\n      t->dist[0] = p0 * p0 +\n                   p1 * (p0 * num + 1) / num;\n      t->dist[1] = 1 - t->dist[0];\n   }\n\n   return 0;\n}\n\nlong long factorial(long number)\n{\n   long long ret;\n   if (number <= 1)\n\t\tret = 1;\n\telse\n\t\tret = number * factorial(number - 1);\n\n   assert(ret > 0);\n\n   return ret;\n}\n\nlong long combinator(int n,int m)\n{\n   // LOG(LOG_MASK_HT, \"computing C %d %d\", n, m);\n\n   int temp;\n\tif (n < m) {\n      temp = n;\n\t\tn = m;\n\t\tm = temp;\n   }\n\n\tlong long ret = factorial(n) / (factorial(m) * factorial(n - m));\n\n   // LOG(LOG_MASK_HT, \"C %d %d = %lld\", n, m, ret);\n\n   return ret;\n}\n\n// This API only supports binary HT, e.g., the value must be 0 or 1\ndouble HashTable::test_sum_prob(int sum)\n{\n   double p0, p1, ret = 0;\n   p0 = dist[0];\n   p1 = dist[1];\n\n   if (cur_size < sum) {\n      return 0;\n   }\n\n   const double success_fraction = p1;\n   int flips = cur_size;\n\n   binomial flip(flips, success_fraction);\n\n   ret = 1 - cdf(flip, sum - 1);\n\n   assert(ret >= 0);\n   assert(ret <= 1);\n\n   /*\n   for (int i=sum; i <= cur_size; i ++) {\n      long long c = combinator(i, cur_size);\n   }\n   */\n\n   LOG(LOG_MASK_HT, \"test sum prob=%f for sum>=%d, size=%d, curSize=%d, p0=%f, p1=%f\",\n       ret, sum, size, cur_size, p0, p1);\n\n   return ret;\n}\n\nint HashTableHandler::ht_test_sum(ExecutionState &cur, int sum,\n                                  vector<ExecutionState*> &states,\n                                  vector<int> &rets)\n{\n   // Compute and update outgoing path probabilities.\n   double cur_prob = cur.getPathProb();\n\n   // Using the CDF of binomial distribution to compute p\n   double p = cur.table->test_sum_prob(sum);\n   assert(p >= 0 && p <= 1);\n\n   // if larger than sum is 0% or 100%\n   if (p < 0.0001 || p > 0.9999) {\n      LOG(LOG_MASK_HT, \"p=%f, test_sum is determinsitic\", p);\n      states.push_back(&cur);\n      rets.push_back(p < 0.0001 ? 0 : 1);\n      LOG(LOG_MASK_HT, \"continue pcur=%f, test_sum is %s\", cur_prob,\n          p > 0.9999 ? \"100%\" : \"0%\");\n      return 0;\n   }\n\n   // if we are doing Monte Carlo sampling, just pick up one state\n   if (cur.isSample == true) {\n      assert(cur.isSampleDone == false);\n\n      double r = theRNG.getDouble();\n\n      states.push_back(&cur);\n\n      // 10% return 1 (>= sum)\n      if (r < p) {\n         cur.updatePathProb(p);\n         rets.push_back(1);\n      }\n      // 90% return 0 (<= sum)\n      else {\n         cur.updatePathProb(1-p);\n         rets.push_back(0);\n      }\n\n      LOG(LOG_MASK_HT, \"test sum returning, path prob=%f\", cur.getPathProb());\n      return 0;\n   }\n\n   // if both possible, need to fork two branches\n   executor.branchTableAccessNoCond(cur, 2, states);\n   assert(states.size() == 2);\n\n   states[0]->updatePathProb(p);\n   rets.push_back(1);\n   states[1]->updatePathProb(1 - p);\n   rets.push_back(0);\n\n   LOG(LOG_MASK_HT, \"pcur=%f, p1=%f, p2=%f\", cur.getPathProb(),\n       states[0]->getPathProb(), states[1]->getPathProb());\n\n   return 0;\n}\n\nint HashTableHandler::ht_add_handler(ExecutionState &state)\n{\n   int status = state.table->status;\n   // ht_add returns the prob of hitting/missing the hash table,\n   // in this handler we don't need that.\n   state.table->ht_add(status);\n   return 0;\n}\n\n// Add by 1 to each possible entry of HT, based the previous access result\n// previous result is provided by flag, so that this API can be used by\n// cmin_add_to_ht\ndouble HashTable::ht_add(int flag)\n{\n   LOG(LOG_MASK_CMIN, \"adding one to hash table, cur_size=%d, flag=%d\",\n       cur_size, flag);\n\n   double ret;\n   // hit\n   if (flag) {\n      assert(cur_size > 0);\n      int largest = 0;\n      for (auto const x : dist) {\n         if (x.second > 0 && x.first > largest) {\n            largest = x.first;\n         }\n      }\n      int v = largest;\n\n      if (dist[v] * cur_size > 1) {\n         dist[v] = (double)(dist[v] * cur_size - 1) / (double)cur_size;\n      } else {\n         dist[v] = 0;\n      }\n\n      dist[v+1] = (double)(dist[v+1] * cur_size + 1) / (double)cur_size;\n\n      ret = (double)cur_size / (double)size;\n      return ret;\n   }\n\n   // miss\n   ret = ((double)size - (double)cur_size) / (double)size;\n\n   if (dist.size() == 0) {\n      dist[1] = 1.0;\n   } else {\n      for (auto x : dist) {\n         if (x.first == 1) {\n            x.second = (x.second * cur_size + 1) / (cur_size + 1);\n         } else {\n            x.second = (x.second * cur_size) / (cur_size + 1);\n         }\n      }\n   }\n\n   cur_size += 1;\n   return ret;\n}\n\nvoid HashTable::dump()\n{\n   LOG(LOG_MASK_HT, \"hash table size=%d, cur_size=%d\", size, cur_size);\n   for (auto x : dist) {\n      LOG(LOG_MASK_HT, \"[v=%d, p=%f]\", x.first, x.second);\n   }\n}\n\nint HashTableHandler::ht_read_larger_than(ExecutionState &cur,\n                                          int val,\n                                          vector<ExecutionState*> &states,\n                                          vector<int> &rets)\n{\n   HashTable *t = cur.table;\n   double larger = t->ht_get_prob_larger_than_after_hit(val);\n   if (larger == 0.0) {\n      states.push_back(&cur);\n      rets.push_back(0);\n      LOG(LOG_MASK_HT, \"cannot greater than %d, returning one branch\", val);\n      return 0;\n   } else if (larger == 1.0) {\n      states.push_back(&cur);\n      rets.push_back(1);\n      LOG(LOG_MASK_HT, \"always greater than %d, returning one branch\", val);\n      return 0;\n   }\n\n   executor.branchTableAccessNoCond(cur, 2, states);\n\n   // branch 1: greater than val\n   rets.push_back(1);\n   states[0]->updatePathProb(larger);\n   // branch 2: cmin is not greater than val\n   rets.push_back(0);\n   states[1]->updatePathProb(1 - larger);\n\n   LOG(LOG_MASK_HT, \"greater than %d prob=%g, elseprob=%g\", val,\n       larger, 1-larger);\n   return 0;\n}\n\n// Get the probability that ht value is greater than val\n// This API assumes that the previous access has hit HT\ndouble HashTable::ht_get_prob_larger_than_after_hit(int val)\n{\n   double ret = 0.0;\n\n   for (auto x : dist) {\n      if (x.first >= val) {\n         ret += x.second;\n      }\n   }\n   return ret;\n}\n\n// Get the probability that ht value is greater than val\n// This API doesn't assume that the previous access has hit HT\n// Should be used by CminHandler::cmin_larger_than\ndouble HashTable::ht_get_prob_larger_than(int val)\n{\n   double ret = 0.0;\n\n   for (auto x : dist) {\n      if (x.first >= val) {\n         ret += (x.second * (double)cur_size / (double)size);\n      }\n   }\n   return ret;\n}\n\nint HashTable::getMaxValue()\n{\n   int ret = 0;\n   for (auto e: dist) {\n      if (e.second > 0) {\n         ret = ret > e.first ? ret : e.first;\n      }\n   }\n   return ret;\n}\n", "meta": {"hexsha": "143a68142be5fc88ea3bb385eaaa22b7c4357249", "size": 13795, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lib/Core/HashTableHandler.cpp", "max_stars_repo_name": "qiaokang92/P4wn", "max_stars_repo_head_hexsha": "cd2418de2dff238f67508898e3bfdf2aae1889a4", "max_stars_repo_licenses": ["NCSA"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2020-12-26T07:18:14.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-11T23:46:13.000Z", "max_issues_repo_path": "lib/Core/HashTableHandler.cpp", "max_issues_repo_name": "qiaokang92/P4wn", "max_issues_repo_head_hexsha": "cd2418de2dff238f67508898e3bfdf2aae1889a4", "max_issues_repo_licenses": ["NCSA"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-05-25T03:54:19.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-25T04:22:29.000Z", "max_forks_repo_path": "lib/Core/HashTableHandler.cpp", "max_forks_repo_name": "qiaokang92/P4wn", "max_forks_repo_head_hexsha": "cd2418de2dff238f67508898e3bfdf2aae1889a4", "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": 24.6339285714, "max_line_length": 86, "alphanum_fraction": 0.5809351214, "num_tokens": 4030, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7090191337850932, "lm_q2_score": 0.49218813572079556, "lm_q1q2_score": 0.3489708056480583}}
{"text": "//==============================================================================\n//         Copyright 2003 - 2011 LASMEA UMR 6602 CNRS/Univ. Clermont II\n//         Copyright 2009 - 2011 LRI    UMR 8623 CNRS/Univ Paris Sud XI\n//\n//          Distributed under the Boost Software License, Version 1.0.\n//                 See accompanying file LICENSE.txt or copy at\n//                     http://www.boost.org/LICENSE_1_0.txt\n//==============================================================================\n#ifndef NT2_TOOLBOX_POLYNOMIALS_FUNCTIONS_SCALAR_IMPL_HORNER_HPP_INCLUDED\n#define NT2_TOOLBOX_POLYNOMIALS_FUNCTIONS_SCALAR_IMPL_HORNER_HPP_INCLUDED\n\n#include <boost/mpl/at.hpp>\n#include <boost/mpl/size.hpp>\n#include <boost/mpl/vector.hpp>\n#include <boost/mpl/pop_back.hpp>\n#include <nt2/sdk/meta/strip.hpp>\n#include <nt2/sdk/meta/as_integer.hpp>\n#include <nt2/include/functions/scalar/fma.hpp>\n#include <nt2/include/constants/real.hpp>\n#include <nt2/include/constants/digits.hpp>\n#include <boost/preprocessor/seq/for_each.hpp>\n#include <boost/preprocessor/tuple/to_seq.hpp>\n#include <boost/dispatch/preprocessor/strip.hpp>\n\nnamespace nt2\n{\n  //////////////////////////////////////////////////////////////////////////////\n  // static unrollign of horner scheme\n  // Coefficients are given in decreasing powers and hexadecimal form\n  // horner< NT2_HORNER_COEFF(float,3,(0x3f800000,0x40000000,0x40400000))>(2.0f)\n  // means ((1*x+2)*x+3) or x^2+2x+3\n  //////////////////////////////////////////////////////////////////////////////\n  namespace details\n    {\n    template<int N, class Seq> struct static_horner_\n    {\n      template<class Sig> struct result;\n      template<class This,class T> struct result<This(T)> : meta::strip<T> {};\n\n      template<class T> inline\n      T operator()(T const& x) const\n      {\n        static_horner_<N-1,typename boost::mpl::pop_back<Seq>::type> callee;\n        return fma( x\n                  , callee(x)\n                  , Const<T,boost::mpl::at_c<Seq,N-1>::type::value>()\n                  );\n      }\n    };\n\n    template<class Seq> struct static_horner_<1,Seq>\n    {\n      template<class Sig> struct result;\n      template<class This,class T> struct result<This(T)> : meta::strip<T> {};\n\n      template<class T> inline\n      T operator()(T const& ) const\n      {\n        return Const<T, boost::mpl::at_c<Seq,0>::type::value >();\n      }\n    };\n  }\n\n  //////////////////////////////////////////////////////////////////////////////\n  /// @brief Static Horner scheme\n  //////////////////////////////////////////////////////////////////////////////\n  template<class Coeff,class Type>\n  static inline Type horner( Type const& x )\n  {\n    details::static_horner_<boost::mpl::size<Coeff>::value,Coeff> callee;\n    return callee(x);\n  }\n}\n\n#define NT2_COEFF_GEN(z,n,text)                                           \\\nboost::mpl::integral_c< BOOST_DISPATCH_PP_STRIP(BOOST_PP_TUPLE_ELEM(3,0,text))       \\\n                      , BOOST_PP_TUPLE_ELEM(BOOST_PP_TUPLE_ELEM(3,1,text) \\\n                                           ,n                             \\\n                                           ,BOOST_PP_TUPLE_ELEM(3,2,text) \\\n                                           )                              \\\n                      >                                                   \\\n/**/\n\n////////////////////////////////////////////////////////////////////////////////\n// Horner coefficient building macro\n////////////////////////////////////////////////////////////////////////////////\n#define NT2_HORNER_COEFF(Type, Size, Seq)                                     \\\nboost::mpl::vector< BOOST_PP_ENUM(Size                                        \\\n                                 ,NT2_COEFF_GEN                               \\\n                                 ,((nt2::meta::as_integer<Type, unsigned>::type),Size,Seq)\\\n                                 ) >                                          \\\n/**/\n\n////////////////////////////////////////////////////////////////////////////////\n// Horner coefficient building macro for template dependant Type\n////////////////////////////////////////////////////////////////////////////////\n#define NT2_HORNER_COEFF_T(Type, Size, Seq)                                   \\\nboost::mpl::vector< BOOST_PP_ENUM(Size                                        \\\n                                 ,NT2_COEFF_GEN                               \\\n                                 ,((typename nt2::meta::as_integer<Type, unsigned>::type)\\\n                                  ,Size                                       \\\n                                  ,Seq)                                       \\\n                                 ) >                                          \\\n/**/\n\n\n\n\n\n#endif\n", "meta": {"hexsha": "605ae22242b146eb7d08c980e293790e84e6028e", "size": 4756, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/core/polynomials/include/nt2/toolbox/polynomials/functions/scalar/impl/horner.hpp", "max_stars_repo_name": "timblechmann/nt2", "max_stars_repo_head_hexsha": "6c71f7063ca4e5975c9c019877e6b2fe07c9e4ce", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2016-09-14T00:23:53.000Z", "max_stars_repo_stars_event_max_datetime": "2018-01-14T12:51:18.000Z", "max_issues_repo_path": "modules/core/polynomials/include/nt2/toolbox/polynomials/functions/scalar/impl/horner.hpp", "max_issues_repo_name": "timblechmann/nt2", "max_issues_repo_head_hexsha": "6c71f7063ca4e5975c9c019877e6b2fe07c9e4ce", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "modules/core/polynomials/include/nt2/toolbox/polynomials/functions/scalar/impl/horner.hpp", "max_forks_repo_name": "timblechmann/nt2", "max_forks_repo_head_hexsha": "6c71f7063ca4e5975c9c019877e6b2fe07c9e4ce", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 42.8468468468, "max_line_length": 91, "alphanum_fraction": 0.4222035324, "num_tokens": 894, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6001883735630721, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.34889135652099745}}
{"text": "/**\n * \\file NearestNeighbor.hpp\n * \\brief Header for GeographicLib::NearestNeighbor class\n *\n * Copyright (c) Charles Karney (2016-2019) <charles@karney.com> and licensed\n * under the MIT/X11 License.  For more information, see\n * https://geographiclib.sourceforge.io/\n **********************************************************************/\n\n#if !defined(GEOGRAPHICLIB_NEARESTNEIGHBOR_HPP)\n#define GEOGRAPHICLIB_NEARESTNEIGHBOR_HPP 1\n\n#include <algorithm>            // for nth_element, max_element, etc.\n#include <vector>\n#include <queue>                // for priority_queue\n#include <utility>              // for swap + pair\n#include <cstring>\n#include <limits>\n#include <cmath>\n#include <iostream>\n#include <sstream>\n// Only for GeographicLib::GeographicErr\n#include <GeographicLib/Constants.hpp>\n\n#if defined(GEOGRAPHICLIB_HAVE_BOOST_SERIALIZATION) && \\\n  GEOGRAPHICLIB_HAVE_BOOST_SERIALIZATION\n#include <boost/serialization/nvp.hpp>\n#include <boost/serialization/split_member.hpp>\n#include <boost/serialization/array.hpp>\n#include <boost/serialization/vector.hpp>\n#endif\n\n#if defined(_MSC_VER)\n// Squelch warnings about constant conditional expressions\n#  pragma warning (push)\n#  pragma warning (disable: 4127)\n#endif\n\nnamespace GeographicLib {\n\n  /**\n   * \\brief Nearest-neighbor calculations\n   *\n   * This class solves the nearest-neighbor problm using a vantage-point tree\n   * as described in \\ref nearest.\n   *\n   * This class is templated so that it can handle arbitrary metric spaces as\n   * follows:\n   *\n   * @tparam dist_t the type used for measuring distances; it can be a real or\n   *   signed integer type; in typical geodetic applications, \\e dist_t might\n   *   be <code>double</code>.\n   * @tparam pos_t the type for specifying the positions of points; geodetic\n   *   application might bundled the latitude and longitude into a\n   *   <code>std::pair<dist_t, dist_t></code>.\n   * @tparam distfun_t the type of a function object which takes takes two\n   *   positions (of type \\e pos_t) and returns the distance (of type \\e\n   *   dist_t); in geodetic applications, this might be a class which is\n   *   constructed with a Geodesic object and which implements a member\n   *   function with a signature <code>dist_t operator() (const pos_t&, const\n   *   pos_t&) const</code>, which returns the geodesic distance between two\n   *   points.\n   *\n   * \\note The distance measure must satisfy the triangle inequality, \\f$\n   * d(a,c) \\le d(a,b) + d(b,c) \\f$ for all points \\e a, \\e b, \\e c.  The\n   * geodesic distance (given by Geodesic::Inverse) does, while the great\n   * ellipse distance and the rhumb line distance <i>do not</i>.  If you use\n   * the ordinary Euclidean distance, i.e., \\f$ \\sqrt{(x_a-x_b)^2 +\n   * (y_a-y_b)^2} \\f$ for two dimensions, don't be tempted to leave out the\n   * square root in the interests of \"efficiency\"; the squared distance does\n   * not satisfy the triangle inequality!\n   *\n   * \\note This is a \"header-only\" implementation and, as such, depends in a\n   * minimal way on the rest of GeographicLib (the only dependency is through\n   * the use of GeographicLib::GeographicErr for handling compile-time and\n   * run-time exceptions).  Therefore, it is easy to extract this class from\n   * the rest of GeographicLib and use it as a stand-alone facility.\n   *\n   * The \\e dist_t type must support numeric_limits queries (specifically:\n   * is_signed, is_integer, max(), digits).\n   *\n   * The NearestNeighbor object is constructed with a vector of points (type \\e\n   * pos_t) and a distance function (type \\e distfun_t).  However the object\n   * does \\e not store the points.  When querying the object with Search(),\n   * it's necessary to supply the same vector of points and the same distance\n   * function.\n   *\n   * There's no capability in this implementation to add or remove points from\n   * the set.  Instead Initialize() should be called to re-initialize the\n   * object with the modified vector of points.\n   *\n   * Because of the overhead in constructing a NearestNeighbor object for a\n   * large set of points, functions Save() and Load() are provided to save the\n   * object to an external file.  operator<<(), operator>>() and <a\n   * href=\"https://www.boost.org/libs/serialization/doc\"> Boost\n   * serialization</a> can also be used to save and restore a NearestNeighbor\n   * object.  This is illustrated in the example.\n   *\n   * Example of use:\n   * \\include example-NearestNeighbor.cpp\n   **********************************************************************/\n  template <typename dist_t, typename pos_t, class distfun_t>\n  class NearestNeighbor {\n    // For tracking changes to the I/O format\n    static const int version = 1;\n    // This is what we get \"free\"; but if sizeof(dist_t) = 1 (unlikely), allow\n    // 4 slots (and this accommodates the default value bucket = 4).\n    static const int maxbucket =\n      (2 + ((4 * sizeof(dist_t)) / sizeof(int) >= 2 ?\n            (4 * sizeof(dist_t)) / sizeof(int) : 2));\n  public:\n\n    /**\n     * Default constructor for NearestNeighbor.\n     *\n     * This is equivalent to specifying an empty set of points.\n     **********************************************************************/\n    NearestNeighbor() : _numpoints(0), _bucket(0), _cost(0) {}\n\n    /**\n     * Constructor for NearestNeighbor.\n     *\n     * @param[in] pts a vector of points to include in the set.\n     * @param[in] dist the distance function object.\n     * @param[in] bucket the size of the buckets at the leaf nodes; this must\n     *   lie in [0, 2 + 4*sizeof(dist_t)/sizeof(int)] (default 4).\n     * @exception GeographicErr if the value of \\e bucket is out of bounds or\n     *   the size of \\e pts is too big for an int.\n     * @exception std::bad_alloc if memory for the tree can't be allocated.\n     *\n     * \\e pts may contain coincident points (i.e., the distance between them\n     * vanishes); these are treated as distinct.\n     *\n     * The choice of \\e bucket is a tradeoff between space and efficiency.  A\n     * larger \\e bucket decreases the size of the NearestNeighbor object which\n     * scales as pts.size() / max(1, bucket) and reduces the number of distance\n     * calculations to construct the object by log2(bucket) * pts.size().\n     * However each search then requires about bucket additional distance\n     * calculations.\n     *\n     * \\warning The distances computed by \\e dist must satisfy the standard\n     * metric conditions.  If not, the results are undefined.  Neither the data\n     * in \\e pts nor the query points should contain NaNs or infinities because\n     * such data violates the metric conditions.\n     *\n     * \\warning The same arguments \\e pts and \\e dist must be provided\n     * to the Search() function.\n     **********************************************************************/\n    NearestNeighbor(const std::vector<pos_t>& pts, const distfun_t& dist,\n                    int bucket = 4) {\n      Initialize(pts, dist, bucket);\n    }\n\n    /**\n     * Initialize or re-initialize NearestNeighbor.\n     *\n     * @param[in] pts a vector of points to include in the tree.\n     * @param[in] dist the distance function object.\n     * @param[in] bucket the size of the buckets at the leaf nodes; this must\n     *   lie in [0, 2 + 4*sizeof(dist_t)/sizeof(int)] (default 4).\n     * @exception GeographicErr if the value of \\e bucket is out of bounds or\n     *   the size of \\e pts is too big for an int.\n     * @exception std::bad_alloc if memory for the tree can't be allocated.\n     *\n     * See also the documentation on the constructor.\n     *\n     * If an exception is thrown, the state of the NearestNeighbor is\n     * unchanged.\n     **********************************************************************/\n    void Initialize(const std::vector<pos_t>& pts, const distfun_t& dist,\n                    int bucket = 4) {\n      static_assert(std::numeric_limits<dist_t>::is_signed,\n                    \"dist_t must be a signed type\");\n      if (!( 0 <= bucket && bucket <= maxbucket ))\n        throw GeographicLib::GeographicErr\n          (\"bucket must lie in [0, 2 + 4*sizeof(dist_t)/sizeof(int)]\");\n      if (pts.size() > size_t(std::numeric_limits<int>::max()))\n        throw GeographicLib::GeographicErr(\"pts array too big\");\n      // the pair contains distance+id\n      std::vector<item> ids(pts.size());\n      for (int k = int(ids.size()); k--;)\n        ids[k] = std::make_pair(dist_t(0), k);\n      int cost = 0;\n      std::vector<Node> tree;\n      init(pts, dist, bucket, tree, ids, cost,\n           0, int(ids.size()), int(ids.size()/2));\n      _tree.swap(tree);\n      _numpoints = int(pts.size());\n      _bucket = bucket;\n      _mc = _sc = 0;\n      _cost = cost; _c1 = _k = _cmax = 0;\n      _cmin = std::numeric_limits<int>::max();\n    }\n\n    /**\n     * Search the NearestNeighbor.\n     *\n     * @param[in] pts the vector of points used for initialization.\n     * @param[in] dist the distance function object used for initialization.\n     * @param[in] query the query point.\n     * @param[out] ind a vector of indices to the closest points found.\n     * @param[in] k the number of points to search for (default = 1).\n     * @param[in] maxdist only return points with distances of \\e maxdist or\n     *   less from \\e query (default is the maximum \\e dist_t).\n     * @param[in] mindist only return points with distances of more than\n     *   \\e mindist from \\e query (default = &minus;1).\n     * @param[in] exhaustive whether to do an exhaustive search (default true).\n     * @param[in] tol the tolerance on the results (default 0).\n     * @return the distance to the closest point found (&minus;1 if no points\n     *   are found).\n     * @exception GeographicErr if \\e pts has a different size from that used\n     *   to construct the object.\n     *\n     * The indices returned in \\e ind are sorted by distance from \\e query\n     * (closest first).\n     *\n     * The simplest invocation is with just the 4 non-optional arguments.  This\n     * returns the closest distance and the index to the closest point in\n     * <i>ind</i><sub>0</sub>.  If there are several points equally close, then\n     * <i>ind</i><sub>0</sub> gives the index of an arbirary one of them.  If\n     * there's no closest point (because the set of points is empty), then \\e\n     * ind is empty and &minus;1 is returned.\n     *\n     * With \\e exhaustive = true and \\e tol = 0 (their default values), this\n     * finds the indices of \\e k closest neighbors to \\e query whose distances\n     * to \\e query are in (\\e mindist, \\e maxdist].  If \\e mindist and \\e\n     * maxdist have their default values, then these bounds have no effect.  If\n     * \\e query is one of the points in the tree, then set \\e mindist = 0 to\n     * prevent this point (and other coincident points) from being returned.\n     *\n     * If \\e exhaustive = false, exit as soon as \\e k results satisfying the\n     * distance criteria are found.  If less than \\e k results are returned\n     * then the search was exhaustive even if \\e exhaustive = false.\n     *\n     * If \\e tol is positive, do an approximate search; in this case the\n     * results are to be interpreted as follows: if the <i>k</i>'th distance is\n     * \\e dk, then all results with distances less than or equal \\e dk &minus;\n     * \\e tol are correct; all others are suspect &mdash; there may be other\n     * closer results with distances greater or equal to \\e dk &minus; \\e tol.\n     * If less than \\e k results are found, then the search is exact.\n     *\n     * \\e mindist should be used to exclude a \"small\" neighborhood of the query\n     * point (relative to the average spacing of the data).  If \\e mindist is\n     * large, the efficiency of the search deteriorates.\n     *\n     * \\note Only the shortest distance is returned (as as the function value).\n     * The distances to other points (indexed by <i>ind</i><sub><i>j</i></sub>\n     * for \\e j > 0) can be found by invoking \\e dist again.\n     *\n     * \\warning The arguments \\e pts and \\e dist must be identical to those\n     * used to initialize the NearestNeighbor; if not, this function will\n     * return some meaningless result (however, if the size of \\e pts is wrong,\n     * this function throw an exception).\n     *\n     * \\warning The query point cannot be a NaN or infinite because then the\n     * metric conditions are violated.\n     **********************************************************************/\n    dist_t Search(const std::vector<pos_t>& pts, const distfun_t& dist,\n                  const pos_t& query,\n                  std::vector<int>& ind,\n                  int k = 1,\n                  dist_t maxdist = std::numeric_limits<dist_t>::max(),\n                  dist_t mindist = -1,\n                  bool exhaustive = true,\n                  dist_t tol = 0) const {\n      if (_numpoints != int(pts.size()))\n          throw GeographicLib::GeographicErr(\"pts array has wrong size\");\n      std::priority_queue<item> results;\n      if (_numpoints > 0 && k > 0 && maxdist > mindist) {\n        // distance to the kth closest point so far\n        dist_t tau = maxdist;\n        // first is negative of how far query is outside boundary of node\n        // +1 if on boundary or inside\n        // second is node index\n        std::priority_queue<item> todo;\n        todo.push(std::make_pair(dist_t(1), int(_tree.size()) - 1));\n        int c = 0;\n        while (!todo.empty()) {\n          int n = todo.top().second;\n          dist_t d = -todo.top().first;\n          todo.pop();\n          dist_t tau1 = tau - tol;\n          // compare tau and d again since tau may have become smaller.\n          if (!( n >= 0 && tau1 >= d )) continue;\n          const Node& current = _tree[n];\n          dist_t dst = 0;   // to suppress warning about uninitialized variable\n          bool exitflag = false, leaf = current.index < 0;\n          for (int i = 0; i < (leaf ? _bucket : 1); ++i) {\n            int index = leaf ? current.leaves[i] : current.index;\n            if (index < 0) break;\n            dst = dist(pts[index], query);\n            ++c;\n\n            if (dst > mindist && dst <= tau) {\n              if (int(results.size()) == k) results.pop();\n              results.push(std::make_pair(dst, index));\n              if (int(results.size()) == k) {\n                if (exhaustive)\n                  tau = results.top().first;\n                else {\n                  exitflag = true;\n                  break;\n                }\n                if (tau <= tol) {\n                  exitflag = true;\n                  break;\n                }\n              }\n            }\n          }\n          if (exitflag) break;\n\n          if (current.index < 0) continue;\n          tau1 = tau - tol;\n          for (int l = 0; l < 2; ++l) {\n            if (current.data.child[l] >= 0 &&\n                dst + current.data.upper[l] >= mindist) {\n              if (dst < current.data.lower[l]) {\n                d = current.data.lower[l] - dst;\n                if (tau1 >= d)\n                  todo.push(std::make_pair(-d, current.data.child[l]));\n              } else if (dst > current.data.upper[l]) {\n                d = dst - current.data.upper[l];\n                if (tau1 >= d)\n                  todo.push(std::make_pair(-d, current.data.child[l]));\n              } else\n                todo.push(std::make_pair(dist_t(1), current.data.child[l]));\n            }\n          }\n        }\n        ++_k;\n        _c1 += c;\n        double omc = _mc;\n        _mc += (c - omc) / _k;\n        _sc += (c - omc) * (c - _mc);\n        if (c > _cmax) _cmax = c;\n        if (c < _cmin) _cmin = c;\n      }\n\n      dist_t d = -1;\n      ind.resize(results.size());\n\n      for (int i = int(ind.size()); i--;) {\n        ind[i] = int(results.top().second);\n        if (i == 0) d = results.top().first;\n        results.pop();\n      }\n      return d;\n\n    }\n\n    /**\n     * @return the total number of points in the set.\n     **********************************************************************/\n    int NumPoints() const { return _numpoints; }\n\n    /**\n     * Write the object to an I/O stream.\n     *\n     * @param[in,out] os the stream to write to.\n     * @param[in] bin if true (the default) save in binary mode.\n     * @exception std::bad_alloc if memory for the string representation of the\n     *   object can't be allocated.\n     *\n     * The counters tracking the statistics of searches are not saved; however\n     * the initializtion cost is saved.  The format of the binary saves is \\e\n     * not portable.\n     *\n     * \\note <a href=\"https://www.boost.org/libs/serialization/doc\">\n     * Boost serialization</a> can also be used to save and restore a\n     * NearestNeighbor object.  This requires that the\n     * GEOGRAPHICLIB_HAVE_BOOST_SERIALIZATION macro be defined.\n     **********************************************************************/\n    void Save(std::ostream& os, bool bin = true) const {\n      int realspec = std::numeric_limits<dist_t>::digits *\n        (std::numeric_limits<dist_t>::is_integer ? -1 : 1);\n      if (bin) {\n        char id[] = \"NearestNeighbor_\";\n        os.write(id, 16);\n        int buf[6];\n        buf[0] = version;\n        buf[1] = realspec;\n        buf[2] = _bucket;\n        buf[3] = _numpoints;\n        buf[4] = int(_tree.size());\n        buf[5] = _cost;\n        os.write(reinterpret_cast<const char *>(buf), 6 * sizeof(int));\n        for (int i = 0; i < int(_tree.size()); ++i) {\n          const Node& node = _tree[i];\n          os.write(reinterpret_cast<const char *>(&node.index), sizeof(int));\n          if (node.index >= 0) {\n            os.write(reinterpret_cast<const char *>(node.data.lower),\n                     2 * sizeof(dist_t));\n            os.write(reinterpret_cast<const char *>(node.data.upper),\n                     2 * sizeof(dist_t));\n            os.write(reinterpret_cast<const char *>(node.data.child),\n                     2 * sizeof(int));\n          } else {\n            os.write(reinterpret_cast<const char *>(node.leaves),\n                     _bucket * sizeof(int));\n          }\n        }\n      } else {\n        std::stringstream ostring;\n          // Ensure enough precision for type dist_t.  With C++11, max_digits10\n          // can be used instead.\n        if (!std::numeric_limits<dist_t>::is_integer) {\n          static const int prec\n            = int(std::ceil(std::numeric_limits<dist_t>::digits *\n                            std::log10(2.0) + 1));\n          ostring.precision(prec);\n        }\n        ostring << version << \" \" << realspec << \" \" << _bucket << \" \"\n                << _numpoints << \" \" << _tree.size() << \" \" << _cost;\n        for (int i = 0; i < int(_tree.size()); ++i) {\n          const Node& node = _tree[i];\n          ostring << \"\\n\" << node.index;\n          if (node.index >= 0) {\n            for (int l = 0; l < 2; ++l)\n              ostring << \" \" << node.data.lower[l] << \" \" << node.data.upper[l]\n                      << \" \" << node.data.child[l];\n          } else {\n            for (int l = 0; l < _bucket; ++l)\n              ostring << \" \" << node.leaves[l];\n          }\n        }\n        os << ostring.str();\n      }\n    }\n\n    /**\n     * Read the object from an I/O stream.\n     *\n     * @param[in,out] is the stream to read from\n     * @param[in] bin if true (the default) load in binary mode.\n     * @exception GeographicErr if the state read from \\e is is illegal.\n     * @exception std::bad_alloc if memory for the tree can't be allocated.\n     *\n     * The counters tracking the statistics of searches are reset by this\n     * operation.  Binary data must have been saved on a machine with the same\n     * architecture.  If an exception is thrown, the state of the\n     * NearestNeighbor is unchanged.\n     *\n     * \\note <a href=\"https://www.boost.org/libs/serialization/doc\">\n     * Boost serialization</a> can also be used to save and restore a\n     * NearestNeighbor object.  This requires that the\n     * GEOGRAPHICLIB_HAVE_BOOST_SERIALIZATION macro be defined.\n     *\n     * \\warning The same arguments \\e pts and \\e dist used for\n     * initialization must be provided to the Search() function.\n     **********************************************************************/\n    void Load(std::istream& is, bool bin = true) {\n      int version1, realspec, bucket, numpoints, treesize, cost;\n      if (bin) {\n        char id[17];\n        is.read(id, 16);\n        id[16] = '\\0';\n        if (!(std::strcmp(id, \"NearestNeighbor_\") == 0))\n          throw GeographicLib::GeographicErr(\"Bad ID\");\n        is.read(reinterpret_cast<char *>(&version1), sizeof(int));\n        is.read(reinterpret_cast<char *>(&realspec), sizeof(int));\n        is.read(reinterpret_cast<char *>(&bucket), sizeof(int));\n        is.read(reinterpret_cast<char *>(&numpoints), sizeof(int));\n        is.read(reinterpret_cast<char *>(&treesize), sizeof(int));\n        is.read(reinterpret_cast<char *>(&cost), sizeof(int));\n      } else {\n        if (!( is >> version1 >> realspec >> bucket >> numpoints >> treesize\n               >> cost ))\n          throw GeographicLib::GeographicErr(\"Bad header\");\n      }\n      if (!( version1 == version ))\n        throw GeographicLib::GeographicErr(\"Incompatible version\");\n      if (!( realspec == std::numeric_limits<dist_t>::digits *\n             (std::numeric_limits<dist_t>::is_integer ? -1 : 1) ))\n        throw GeographicLib::GeographicErr(\"Different dist_t types\");\n      if (!( 0 <= bucket && bucket <= maxbucket ))\n        throw GeographicLib::GeographicErr(\"Bad bucket size\");\n      if (!( 0 <= treesize && treesize <= numpoints ))\n        throw\n          GeographicLib::GeographicErr(\"Bad number of points or tree size\");\n      if (!( 0 <= cost ))\n        throw GeographicLib::GeographicErr(\"Bad value for cost\");\n      std::vector<Node> tree;\n      tree.reserve(treesize);\n      for (int i = 0; i < treesize; ++i) {\n        Node node;\n        if (bin) {\n          is.read(reinterpret_cast<char *>(&node.index), sizeof(int));\n          if (node.index >= 0) {\n            is.read(reinterpret_cast<char *>(node.data.lower),\n                    2 * sizeof(dist_t));\n            is.read(reinterpret_cast<char *>(node.data.upper),\n                    2 * sizeof(dist_t));\n            is.read(reinterpret_cast<char *>(node.data.child),\n                    2 * sizeof(int));\n          } else {\n            is.read(reinterpret_cast<char *>(node.leaves),\n                    bucket * sizeof(int));\n            for (int l = bucket; l < maxbucket; ++l)\n              node.leaves[l] = 0;\n          }\n        } else {\n          if (!( is >> node.index ))\n            throw GeographicLib::GeographicErr(\"Bad index\");\n          if (node.index >= 0) {\n            for (int l = 0; l < 2; ++l) {\n              if (!( is >> node.data.lower[l] >> node.data.upper[l]\n                     >> node.data.child[l] ))\n                throw GeographicLib::GeographicErr(\"Bad node data\");\n            }\n          } else {\n            // Must be at least one valid leaf followed by a sequence end\n            // markers (-1).\n            for (int l = 0; l < bucket; ++l) {\n              if (!( is >> node.leaves[l] ))\n                throw GeographicLib::GeographicErr(\"Bad leaf data\");\n            }\n            for (int l = bucket; l < maxbucket; ++l)\n              node.leaves[l] = 0;\n          }\n        }\n        node.Check(numpoints, treesize, bucket);\n        tree.push_back(node);\n      }\n      _tree.swap(tree);\n      _numpoints = numpoints;\n      _bucket = bucket;\n      _mc = _sc = 0;\n      _cost = cost; _c1 = _k = _cmax = 0;\n      _cmin = std::numeric_limits<int>::max();\n    }\n\n    /**\n     * Write the object to stream \\e os as text.\n     *\n     * @param[in,out] os the output stream.\n     * @param[in] t the NearestNeighbor object to be saved.\n     * @exception std::bad_alloc if memory for the string representation of the\n     *   object can't be allocated.\n     **********************************************************************/\n    friend std::ostream& operator<<(std::ostream& os, const NearestNeighbor& t)\n    { t.Save(os, false); return os; }\n\n    /**\n     * Read the object from stream \\e is as text.\n     *\n     * @param[in,out] is the input stream.\n     * @param[out] t the NearestNeighbor object to be loaded.\n     * @exception GeographicErr if the state read from \\e is is illegal.\n     * @exception std::bad_alloc if memory for the tree can't be allocated.\n     **********************************************************************/\n    friend std::istream& operator>>(std::istream& is, NearestNeighbor& t)\n    { t.Load(is, false); return is; }\n\n    /**\n     * Swap with another NearestNeighbor object.\n     *\n     * @param[in,out] t the NearestNeighbor object to swap with.\n     **********************************************************************/\n    void swap(NearestNeighbor& t) {\n      std::swap(_numpoints, t._numpoints);\n      std::swap(_bucket, t._bucket);\n      std::swap(_cost, t._cost);\n      _tree.swap(t._tree);\n      std::swap(_mc, t._mc);\n      std::swap(_sc, t._sc);\n      std::swap(_c1, t._c1);\n      std::swap(_k, t._k);\n      std::swap(_cmin, t._cmin);\n      std::swap(_cmax, t._cmax);\n    }\n\n    /**\n     * The accumulated statistics on the searches so far.\n     *\n     * @param[out] setupcost the cost of initializing the NearestNeighbor.\n     * @param[out] numsearches the number of calls to Search().\n     * @param[out] searchcost the total cost of the calls to Search().\n     * @param[out] mincost the minimum cost of a Search().\n     * @param[out] maxcost the maximum cost of a Search().\n     * @param[out] mean the mean cost of a Search().\n     * @param[out] sd the standard deviation in the cost of a Search().\n     *\n     * Here \"cost\" measures the number of distance calculations needed.  Note\n     * that the accumulation of statistics is \\e not thread safe.\n     **********************************************************************/\n    void Statistics(int& setupcost, int& numsearches, int& searchcost,\n                    int& mincost, int& maxcost,\n                    double& mean, double& sd) const {\n      setupcost = _cost; numsearches = _k; searchcost = _c1;\n      mincost = _cmin; maxcost = _cmax;\n      mean = _mc; sd = std::sqrt(_sc / (_k - 1));\n    }\n\n    /**\n     * Reset the counters for the accumulated statistics on the searches so\n     * far.\n     **********************************************************************/\n    void ResetStatistics() const {\n      _mc = _sc = 0;\n      _c1 = _k = _cmax = 0;\n      _cmin = std::numeric_limits<int>::max();\n    }\n\n  private:\n    // Package up a dist_t and an int.  We will want to sort on the dist_t so\n    // put it first.\n    typedef std::pair<dist_t, int> item;\n    // \\cond SKIP\n    class Node {\n    public:\n      struct bounds {\n        dist_t lower[2], upper[2]; // bounds on inner/outer distances\n        int child[2];\n      };\n      union {\n        bounds data;\n        int leaves[maxbucket];\n      };\n      int index;\n\n      Node()\n        : index(-1)\n      {\n        for (int i = 0; i < 2; ++i) {\n          data.lower[i] = data.upper[i] = 0;\n          data.child[i] = -1;\n        }\n      }\n\n      // Sanity check on a Node\n      void Check(int numpoints, int treesize, int bucket) const {\n        if (!( -1 <= index && index < numpoints ))\n          throw GeographicLib::GeographicErr(\"Bad index\");\n        if (index >= 0) {\n          if (!( -1 <= data.child[0] && data.child[0] < treesize &&\n                 -1 <= data.child[1] && data.child[1] < treesize ))\n            throw GeographicLib::GeographicErr(\"Bad child pointers\");\n          if (!( 0 <= data.lower[0] && data.lower[0] <= data.upper[0] &&\n                 data.upper[0] <= data.lower[1] &&\n                 data.lower[1] <= data.upper[1] ))\n            throw GeographicLib::GeographicErr(\"Bad bounds\");\n        } else {\n          // Must be at least one valid leaf followed by a sequence end markers\n          // (-1).\n          bool start = true;\n          for (int l = 0; l < bucket; ++l) {\n            if (!( (start ?\n                    ((l == 0 ? 0 : -1) <= leaves[l] && leaves[l] < numpoints) :\n                    leaves[l] == -1) ))\n              throw GeographicLib::GeographicErr(\"Bad leaf data\");\n            start = leaves[l] >= 0;\n          }\n          for (int l = bucket; l < maxbucket; ++l) {\n            if (leaves[l] != 0)\n              throw GeographicLib::GeographicErr(\"Bad leaf data\");\n          }\n        }\n      }\n\n#if defined(GEOGRAPHICLIB_HAVE_BOOST_SERIALIZATION) && \\\n  GEOGRAPHICLIB_HAVE_BOOST_SERIALIZATION\n      friend class boost::serialization::access;\n      template<class Archive>\n      void save(Archive& ar, const unsigned int) const {\n        ar & boost::serialization::make_nvp(\"index\", index);\n        if (index < 0)\n          ar & boost::serialization::make_nvp(\"leaves\", leaves);\n        else\n          ar & boost::serialization::make_nvp(\"lower\", data.lower)\n            & boost::serialization::make_nvp(\"upper\", data.upper)\n            & boost::serialization::make_nvp(\"child\", data.child);\n      }\n      template<class Archive>\n      void load(Archive& ar, const unsigned int) {\n        ar & boost::serialization::make_nvp(\"index\", index);\n        if (index < 0)\n          ar & boost::serialization::make_nvp(\"leaves\", leaves);\n        else\n          ar & boost::serialization::make_nvp(\"lower\", data.lower)\n            & boost::serialization::make_nvp(\"upper\", data.upper)\n            & boost::serialization::make_nvp(\"child\", data.child);\n      }\n      template<class Archive>\n      void serialize(Archive& ar, const unsigned int file_version)\n      { boost::serialization::split_member(ar, *this, file_version); }\n#endif\n    };\n    // \\endcond\n#if defined(GEOGRAPHICLIB_HAVE_BOOST_SERIALIZATION) && \\\n  GEOGRAPHICLIB_HAVE_BOOST_SERIALIZATION\n    friend class boost::serialization::access;\n    template<class Archive> void save(Archive& ar, const unsigned) const {\n      int realspec = std::numeric_limits<dist_t>::digits *\n        (std::numeric_limits<dist_t>::is_integer ? -1 : 1);\n      // Need to use version1, otherwise load error in debug mode on Linux:\n      // undefined reference to GeographicLib::NearestNeighbor<...>::version.\n      int version1 = version;\n      ar & boost::serialization::make_nvp(\"version\", version1)\n        & boost::serialization::make_nvp(\"realspec\", realspec)\n        & boost::serialization::make_nvp(\"bucket\", _bucket)\n        & boost::serialization::make_nvp(\"numpoints\", _numpoints)\n        & boost::serialization::make_nvp(\"cost\", _cost)\n        & boost::serialization::make_nvp(\"tree\", _tree);\n    }\n    template<class Archive> void load(Archive& ar, const unsigned) {\n      int version1, realspec, bucket, numpoints, cost;\n      ar & boost::serialization::make_nvp(\"version\", version1);\n      if (version1 != version)\n        throw GeographicLib::GeographicErr(\"Incompatible version\");\n      std::vector<Node> tree;\n      ar & boost::serialization::make_nvp(\"realspec\", realspec);\n      if (!( realspec == std::numeric_limits<dist_t>::digits *\n             (std::numeric_limits<dist_t>::is_integer ? -1 : 1) ))\n        throw GeographicLib::GeographicErr(\"Different dist_t types\");\n      ar & boost::serialization::make_nvp(\"bucket\", bucket);\n      if (!( 0 <= bucket && bucket <= maxbucket ))\n        throw GeographicLib::GeographicErr(\"Bad bucket size\");\n      ar & boost::serialization::make_nvp(\"numpoints\", numpoints)\n        & boost::serialization::make_nvp(\"cost\", cost)\n        & boost::serialization::make_nvp(\"tree\", tree);\n      if (!( 0 <= int(tree.size()) && int(tree.size()) <= numpoints ))\n        throw\n          GeographicLib::GeographicErr(\"Bad number of points or tree size\");\n      for (int i = 0; i < int(tree.size()); ++i)\n        tree[i].Check(numpoints, int(tree.size()), bucket);\n      _tree.swap(tree);\n      _numpoints = numpoints;\n      _bucket = bucket;\n      _mc = _sc = 0;\n      _cost = cost; _c1 = _k = _cmax = 0;\n      _cmin = std::numeric_limits<int>::max();\n    }\n    template<class Archive>\n    void serialize(Archive& ar, const unsigned int file_version)\n    { boost::serialization::split_member(ar, *this, file_version); }\n#endif\n\n    int _numpoints, _bucket, _cost;\n    std::vector<Node> _tree;\n    // Counters to track stastistics on the cost of searches\n    mutable double _mc, _sc;\n    mutable int _c1, _k, _cmin, _cmax;\n\n    int init(const std::vector<pos_t>& pts, const distfun_t& dist, int bucket,\n             std::vector<Node>& tree, std::vector<item>& ids, int& cost,\n             int l, int u, int vp) {\n\n      if (u == l)\n        return -1;\n      Node node;\n\n      if (u - l > (bucket == 0 ? 1 : bucket)) {\n\n        // choose a vantage point and move it to the start\n        int i = vp;\n        std::swap(ids[l], ids[i]);\n\n        int m = (u + l + 1) / 2;\n\n        for (int k = l + 1; k < u; ++k) {\n          ids[k].first = dist(pts[ids[l].second], pts[ids[k].second]);\n          ++cost;\n        }\n        // partition around the median distance\n        std::nth_element(ids.begin() + l + 1,\n                         ids.begin() + m,\n                         ids.begin() + u);\n        node.index = ids[l].second;\n        if (m > l + 1) {        // node.child[0] is possibly empty\n          typename std::vector<item>::iterator\n            t = std::min_element(ids.begin() + l + 1, ids.begin() + m);\n          node.data.lower[0] = t->first;\n          t = std::max_element(ids.begin() + l + 1, ids.begin() + m);\n          node.data.upper[0] = t->first;\n          // Use point with max distance as vantage point; this point act as a\n          // \"corner\" point and leads to a good partition.\n          node.data.child[0] = init(pts, dist, bucket, tree, ids, cost,\n                                    l + 1, m, int(t - ids.begin()));\n        }\n        typename std::vector<item>::iterator\n          t = std::max_element(ids.begin() + m, ids.begin() + u);\n        node.data.lower[1] = ids[m].first;\n        node.data.upper[1] = t->first;\n        // Use point with max distance as vantage point here too\n        node.data.child[1] = init(pts, dist, bucket, tree, ids, cost,\n                                  m, u, int(t - ids.begin()));\n      } else {\n        if (bucket == 0)\n          node.index = ids[l].second;\n        else {\n          node.index = -1;\n          // Sort the bucket entries so that the tree is independent of the\n          // implementation of nth_element.\n          std::sort(ids.begin() + l, ids.begin() + u);\n          for (int i = l; i < u; ++i)\n            node.leaves[i-l] = ids[i].second;\n          for (int i = u - l; i < bucket; ++i)\n            node.leaves[i] = -1;\n          for (int i = bucket; i < maxbucket; ++i)\n            node.leaves[i] = 0;\n        }\n      }\n\n      tree.push_back(node);\n      return int(tree.size()) - 1;\n    }\n\n  };\n\n} // namespace GeographicLib\n\nnamespace std {\n\n  /**\n   * Swap two GeographicLib::NearestNeighbor objects.\n   *\n   * @tparam dist_t the type used for measuring distances.\n   * @tparam pos_t the type for specifying the positions of points.\n   * @tparam distfun_t the type for a function object which calculates\n   *   distances between points.\n   * @param[in,out] a the first GeographicLib::NearestNeighbor to swap.\n   * @param[in,out] b the second GeographicLib::NearestNeighbor to swap.\n   **********************************************************************/\n  template <typename dist_t, typename pos_t, class distfun_t>\n  void swap(GeographicLib::NearestNeighbor<dist_t, pos_t, distfun_t>& a,\n            GeographicLib::NearestNeighbor<dist_t, pos_t, distfun_t>& b) {\n    a.swap(b);\n  }\n\n} // namespace std\n\n#if defined(_MSC_VER)\n#  pragma warning (pop)\n#endif\n\n#endif  // GEOGRAPHICLIB_NEARESTNEIGHBOR_HPP\n", "meta": {"hexsha": "70cdcd68f4306275347e6fb6dce2eb5e463b47be", "size": 35717, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/GeographicLib/NearestNeighbor.hpp", "max_stars_repo_name": "TheNicker/geographiclib", "max_stars_repo_head_hexsha": "5e9b898734643954a9f6aafae3e9b8de429252bb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/GeographicLib/NearestNeighbor.hpp", "max_issues_repo_name": "TheNicker/geographiclib", "max_issues_repo_head_hexsha": "5e9b898734643954a9f6aafae3e9b8de429252bb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/GeographicLib/NearestNeighbor.hpp", "max_forks_repo_name": "TheNicker/geographiclib", "max_forks_repo_head_hexsha": "5e9b898734643954a9f6aafae3e9b8de429252bb", "max_forks_repo_licenses": ["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.6217183771, "max_line_length": 79, "alphanum_fraction": 0.5697287006, "num_tokens": 8913, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.600188359260205, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.3488913482066966}}
{"text": "//****************************************************************************\n// (c) 2008, 2009 by the openOR Team\n//****************************************************************************\n// The contents of this file are available under the GPL v2.0 license\n// or under the openOR comercial license. see\n//   /Doc/openOR_free_license.txt or\n//   /Doc/openOR_comercial_license.txt\n// for Details.\n//****************************************************************************\n/**\n* @file\n* @author Christian Winne\n* @ingroup openOR_core\n*/\n\n#ifndef openOR_core_math_create_hpp\n#define openOR_core_math_create_hpp\n\n#include <openOR/Math/vector.hpp>\n#include <openOR/Math/matrix.hpp>\n#include <openOR/Math/matrixsetaxis.hpp>\n\n#include <boost/mpl/assert.hpp>\n\nnamespace openOR {\n\tnamespace Math {\n\n\t\tnamespace Impl {\n\t\t\t/**\n\t\t\t* Functor for Impl::VectorCompileIterator in order to copy the content of source vector into destination vector\n\t\t\t* \\internal\n\t\t\t*/\n\t\t\ttemplate <class Vec, class VecSrc, int I>\n\t\t\tstruct VectorCopy {\n\t\t\t\tvoid operator()(Vec& vec, const VecSrc& vecSrc) {\n\t\t\t\t\tget<I>(vec) = get<I>(vecSrc);\n\t\t\t\t}\n\t\t\t};\n\n\t\t\ttemplate <class Mat, class MatSrc, int I, int J>\n\t\t\tstruct MatrixCopy {\n\t\t\t\tvoid operator()(Mat& mat, const MatSrc& matSrc) {\n\t\t\t\t\tget<I, J>(mat) = get<I, J>(matSrc);\n\t\t\t\t}\n\t\t\t};\n\n\n\t\t\t/**\n\t\t\t* v0 is an vector because the destination vector is larger than Dimension 2.\n\t\t\t* \\internal\n\t\t\t*/\n\t\t\ttemplate<class Vec_type, class Type2, int Dim>\n\t\t\tstruct CreateVec2 {\n\t\t\t\tstatic Vec_type create(const Type2& v0,\n\t\t\t\t\ttypename VectorTraits<Vec_type>::ValueType v1) \n\t\t\t\t{\n\t\t\t\t\tBOOST_MPL_ASSERT((typename VectorTraits<Vec_type>::IsVector));\n\t\t\t\t\tVec_type t;\n\t\t\t\t\tImpl::VectorCompileTimeIterator < Vec_type, 0, VectorTraits<Vec_type>::Dimension::value - 1 > ()\n\t\t\t\t\t\t.template apply<Impl::VectorCopy, Type2>(t, v0);\n\t\t\t\t\tget < VectorTraits<Vec_type>::Dimension::value - 1 > (t) = v1;\n\t\t\t\t\treturn t;\n\t\t\t\t}\n\t\t\t};\n\n\t\t\t/**\n\t\t\t* v0 is a ValueType because the vector to create has dimension 2.\n\t\t\t* \\internal\n\t\t\t*/\n\t\t\ttemplate<class Type, class Type2>\n\t\t\tstruct CreateVec2<Type, Type2, 2> {\n\t\t\t\tstatic Type create(const Type2& v0,\n\t\t\t\t\ttypename VectorTraits<Type>::ValueType v1) {\n\t\t\t\t\t\tType t;\n\t\t\t\t\t\tget<0>(t) = static_cast<typename VectorTraits<Type>::ValueType>(v0);\n\t\t\t\t\t\tget<1>(t) = static_cast<typename VectorTraits<Type>::ValueType>(v1);\n\t\t\t\t\t\treturn t;\n\t\t\t\t}\n\t\t\t};\n\n\t\t\ttemplate<class Mat, class MatSrc, class Vec>\n\t\t\tstruct CreateMat2 {\n\t\t\t\tstatic Mat create(\n\t\t\t\t\tconst MatSrc& matSrc,\n\t\t\t\t\tconst Vec& v) \n\t\t\t\t{\n\t\t\t\t\tBOOST_MPL_ASSERT((typename MatrixTraits<Mat>::IsMatrix));\n\t\t\t\t\tBOOST_MPL_ASSERT((typename VectorTraits<Vec>::IsVector));\n\t\t\t\t\tMat mat = MatrixTraits<Mat>::IDENTITY;\n\t\t\t\t\tImpl::MatrixCompileTimeIterator <Mat, 0, MatrixTraits<Mat>::RowDimension::value - 1, 0, MatrixTraits<Mat>::ColDimension::value - 1> ()\n\t\t\t\t\t\t.template apply<Impl::MatrixCopy, MatSrc>(mat, matSrc);\n\n\t\t\t\t\tfor (int i = 0; i < VectorTraits<Vec>::Dimension::value; ++i)\n\t\t\t\t\t{\n\t\t\t\t\t\tmat(i, MatrixTraits<Mat>::ColDimension::value - 1) = v(i);\n\t\t\t\t\t}\n\t\t\t\t\treturn mat;\n\t\t\t\t}\n\t\t\t};\n\n\t\t\t/**\n\t\t\t* \n\t\t\t* \\internal\n\t\t\t*/\n\t\t\ttemplate<class Type, class Type2, class Type3, class IsVector>\n\t\t\tstruct Create2 {\n\t\t\t\tstatic Type create(const Type2& v0, const Type3& v1) \n\t\t\t\t{\n\t\t\t\t\treturn CreateVec2<Type, Type2, VectorTraits<Type>::Dimension::value>::create(v0, v1);\n\t\t\t\t}\n\t\t\t};\n\n\n\t\t\t/**\n\t\t\t* \n\t\t\t* \\internal\n\t\t\t*/\n\t\t\ttemplate<class Type, class Type2, class Type3>\n\t\t\tstruct Create2<Type, Type2, Type3, boost::mpl::false_> {\n\t\t\t\tstatic Type create(const Type2& v0, const Type3& v1) \n\t\t\t\t{\n\t\t\t\t\treturn CreateMat2<Type, Type2, Type3>::create(v0, v1);\n\t\t\t\t}\n\t\t\t};\n\n\n\t\t\t/**\n\t\t\t* Type is a vector\n\t\t\t* \\internal\n\t\t\t*/\n\t\t\ttemplate<class Type, class Type2, class Type3, class Type4, class IsVector>\n\t\t\tstruct Create3 {\n\t\t\t\tstatic Type create(const Type2& v0, \n\t\t\t\t\tconst Type3& v1, \n\t\t\t\t\tconst Type4& v2) {\n\t\t\t\t\t\tBOOST_MPL_ASSERT((typename VectorTraits<Type>::IsVector));\n\t\t\t\t\t\tType t;\n\t\t\t\t\t\tget<0>(t) = static_cast<typename VectorTraits<Type>::ValueType>(v0);\n\t\t\t\t\t\tget<1>(t) = static_cast<typename VectorTraits<Type>::ValueType>(v1);\n\t\t\t\t\t\tget<2>(t) = static_cast<typename VectorTraits<Type>::ValueType>(v2);\n\t\t\t\t\t\treturn t;\n\t\t\t\t}\n\t\t\t};\n\n\n\t\t\t/**\n\t\t\t* Type is matrix\n\t\t\t* \\internal\n\t\t\t*/\n\t\t\ttemplate<class Type, class Type2, class Type3, class Type4>\n\t\t\tstruct Create3<Type, Type2, Type3, Type4, boost::mpl::false_> {\n\t\t\t\tstatic Type create(const Type2& v0, const Type3& v1, const Type4& v2) {\n\t\t\t\t\tBOOST_MPL_ASSERT((typename MatrixTraits<Type>::IsMatrix));\n\t\t\t\t\tType t = MatrixTraits<Type>::IDENTITY;\n\t\t\t\t\tsetXAxis(t, v0);\n\t\t\t\t\tsetYAxis(t, v1);\n\t\t\t\t\tsetZAxis(t, v2);\n\t\t\t\t\treturn t;\n\t\t\t\t}\n\t\t\t};\n\n\n\t\t\t/**\n\t\t\t* Type is a vector\n\t\t\t* \\internal\n\t\t\t*/\n\t\t\ttemplate<class Type, class Type2, class Type3, class Type4, class Type5, class IsVector>\n\t\t\tstruct Create4 {\n\t\t\t\tstatic Type create(const Type2& v0, const Type3& v1, const Type4& v2, const Type5& v3) {\n\t\t\t\t\tBOOST_MPL_ASSERT((typename VectorTraits<Type>::IsVector));\n\t\t\t\t\tType t;\n\t\t\t\t\tget<0>(t) = static_cast<typename VectorTraits<Type>::ValueType>(v0);\n\t\t\t\t\tget<1>(t) = static_cast<typename VectorTraits<Type>::ValueType>(v1);\n\t\t\t\t\tget<2>(t) = static_cast<typename VectorTraits<Type>::ValueType>(v2);\n\t\t\t\t\tget<3>(t) = static_cast<typename VectorTraits<Type>::ValueType>(v3);\n\t\t\t\t\treturn t;\n\t\t\t\t}\n\t\t\t};\n\n\n\t\t\t/** \n\t\t\t* Type is matrix\n\t\t\t* \\internal\n\t\t\t*/\n\t\t\ttemplate<class Type, class Type2, class Type3, class Type4, class Type5>\n\t\t\tstruct Create4<Type, Type2, Type3, Type4, Type5, boost::mpl::false_> {\n\t\t\t\tstatic Type create(const Type2& v0, const Type3& v1, const Type4& v2, const Type5& v3) {\n\t\t\t\t\tType t = MatrixTraits<Type>::IDENTITY;\n\t\t\t\t\tsetXAxis(t, v0);\n\t\t\t\t\tsetYAxis(t, v1);\n\t\t\t\t\tsetZAxis(t, v2);\n\t\t\t\t\tsetTranslation(t, v3);\n\t\t\t\t\treturn t;\n\t\t\t\t}\n\t\t\t};\n\n\n\t\t\ttemplate<class Type, class Type2, class Type3, class Type4, class Type5, class Type6, class Type7, class IsVector>\n\t\t\tstruct Create6 {\n\t\t\t\tstatic Type create(const Type2& v0, const Type3& v1, const Type4& v2, const Type5& v3, const Type6& v4, const Type7& v5) {\n\t\t\t\t\tBOOST_MPL_ASSERT((typename VectorTraits<Type>::IsVector));\n\t\t\t\t\tType t;\n\t\t\t\t\tget<0>(t) = static_cast<typename VectorTraits<Type>::ValueType>(v0);\n\t\t\t\t\tget<1>(t) = static_cast<typename VectorTraits<Type>::ValueType>(v1);\n\t\t\t\t\tget<2>(t) = static_cast<typename VectorTraits<Type>::ValueType>(v2);\n\t\t\t\t\tget<3>(t) = static_cast<typename VectorTraits<Type>::ValueType>(v3);\n\t\t\t\t\tget<4>(t) = static_cast<typename VectorTraits<Type>::ValueType>(v4);\n\t\t\t\t\tget<5>(t) = static_cast<typename VectorTraits<Type>::ValueType>(v5);\n\t\t\t\t\treturn t;\n\t\t\t\t}\n\t\t\t};\n\t\t}\n\n\n\n\t\t/** \n\t\t* \\brief create\n\t\t* \\ingroup openOR_core\n\t\t*/\n\t\ttemplate <class Type, class Vec>\n\t\tinline\n\t\t\tOPENOR_CONCEPT_REQUIRES(\n\t\t\t((Concept::Matrix<Type>))\n\t\t\t((Concept::ConstVector<Vec>)),\n\t\t\t(Type))\n\t\t\tcreate(const Vec& vec) {\n\t\t\t\tType mat = MatrixTraits<Type>::IDENTITY;\n\t\t\t\tsetTranslation(mat, vec);\n\t\t\t\treturn mat;\n\t\t}\n\n\n\t\t/**\n\t\t* @brief Creation of a vector with two parameters.\n\t\t* @ingroup openOR_core\n\t\t*/\n\t\ttemplate<class Type, class Type2, class Type3>\n\t\tinline Type create(const Type2& v0,\n\t\t\tconst Type3& v1) {\n\t\t\t\treturn Impl::Create2<Type, Type2, Type3, typename VectorTraits<Type>::IsVector>::create(v0, v1);\n\t\t}\n\n\t\t/**\n\t\t* @brief Creation of a vector with three parameters.\n\t\t* @ingroup openOR_core\n\t\t*/\n\t\ttemplate<class Type, class Type2, class Type3, class Type4>\n\t\tinline Type create(const Type2& v0,\n\t\t\tconst Type3& v1,\n\t\t\tconst Type4& v2) {\n\t\t\t\treturn Impl::Create3<Type, Type2, Type3, Type4, typename VectorTraits<Type>::IsVector>::create(v0, v1, v2);\n\t\t}\n\n\n\t\t/**\n\t\t* @brief Creation of a vector with four parameters.\n\t\t* @ingroup openOR_core\n\t\t*/\n\t\ttemplate<class Type, class Type2, class Type3, class Type4, class Type5>\n\t\tinline Type create(const Type2& v0, const Type3& v1, const Type4& v2, const Type5& v3) {\n\t\t\treturn Impl::Create4<Type, Type2, Type3, Type4, Type5, typename VectorTraits<Type>::IsVector>::create(v0, v1, v2, v3);\n\t\t}\n\n\n\t\t/**\n\t\t* @brief Creation of a vector with six parameters.\n\t\t* @ingroup openOR_core\n\t\t*/\n\t\ttemplate<class Type, class Type2, class Type3, class Type4, class Type5, class Type6, class Type7>\n\t\tinline Type create(const Type2& v0, const Type3& v1, const Type4& v2, const Type5& v3, const Type6& v4, const Type7& v5) {\n\t\t\treturn Impl::Create6<Type, Type2, Type3, Type4, Type5, Type6, Type7, typename VectorTraits<Type>::IsVector>::create(v0, v1, v2, v3, v4, v5);\n\t\t}\n\n\n\n\t}\n}\n\n\n#endif\n", "meta": {"hexsha": "9f381bd0c0559e0f823bd6da184d4f82e56d5c45", "size": 8471, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/core/include/openOR/Math/create.hpp", "max_stars_repo_name": "avinfinity/UnmanagedCodeSnippets", "max_stars_repo_head_hexsha": "2bd848db88d7b271209ad30017c8f62307319be3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/core/include/openOR/Math/create.hpp", "max_issues_repo_name": "avinfinity/UnmanagedCodeSnippets", "max_issues_repo_head_hexsha": "2bd848db88d7b271209ad30017c8f62307319be3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/core/include/openOR/Math/create.hpp", "max_forks_repo_name": "avinfinity/UnmanagedCodeSnippets", "max_forks_repo_head_hexsha": "2bd848db88d7b271209ad30017c8f62307319be3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.1459074733, "max_line_length": 143, "alphanum_fraction": 0.6347538661, "num_tokens": 2491, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6039318337259584, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.3487678348649093}}
{"text": "// Copyright 2004, 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: Nick Edmonds\n//           Andrew Lumsdaine\n#ifndef BOOST_GRAPH_RMAT_GENERATOR_HPP\n#define BOOST_GRAPH_RMAT_GENERATOR_HPP\n\n#include <math.h>\n#include <iterator>\n#include <utility>\n#include <vector>\n#include <queue>\n#include <map>\n#include <boost/shared_ptr.hpp>\n#include <boost/assert.hpp>\n#include <boost/random/uniform_int.hpp>\n#include <boost/random/uniform_01.hpp>\n#include <boost/graph/graph_traits.hpp>\n#include <boost/graph/detail/mpi_include.hpp>\n#include <boost/type_traits/is_base_and_derived.hpp>\n#include <boost/type_traits/is_same.hpp>\n// #include <boost/test/floating_point_comparison.hpp>\n\nusing boost::shared_ptr;\nusing boost::uniform_01;\n\n// Returns floor(log_2(n)), and -1 when n is 0\ntemplate <typename IntegerType>\ninline int int_log2(IntegerType n) {\n  int l = 0;\n  while (n > 0) {++l; n >>= 1;}\n  return l - 1;\n}\n\nstruct keep_all_edges {\n  template <typename T>\n  bool operator()(const T&, const T&) { return true; }\n};\n\ntemplate <typename Distribution, typename ProcessId>\nstruct keep_local_edges {\n\n  keep_local_edges(const Distribution& distrib, const ProcessId& id)\n    : distrib(distrib), id(id)\n  { }\n\n  template <typename T>\n  bool operator()(const T& x, const T& y)\n  { return distrib(x) == id || distrib(y) == id; }\n\nprivate:\n  const Distribution& distrib;\n  const ProcessId&    id;\n};\n\ntemplate <typename RandomGenerator, typename T>\nvoid\ngenerate_permutation_vector(RandomGenerator& gen, std::vector<T>& vertexPermutation, T n)\n{\n  using boost::uniform_int;\n\n  vertexPermutation.resize(n);\n\n  // Generate permutation map of vertex numbers\n  uniform_int<T> rand_vertex(0, n-1);\n  for (T i = 0; i < n; ++i)\n    vertexPermutation[i] = i;\n\n  // Can't use std::random_shuffle unless we create another (synchronized) PRNG\n  for (T i = 0; i < n; ++i)\n    std::swap(vertexPermutation[i], vertexPermutation[rand_vertex(gen)]);\n}\n\ntemplate <typename RandomGenerator, typename T>\nstd::pair<T,T>\ngenerate_edge(shared_ptr<uniform_01<RandomGenerator> > prob, T n,\n              unsigned int SCALE, double a, double b, double c, double d)\n{\n  T u = 0, v = 0;\n  T step = n/2;\n  for (unsigned int j = 0; j < SCALE; ++j) {\n    double p = (*prob)();\n\n    if (p < a)\n      ;\n    else if (p >= a && p < a + b)\n      v += step;\n    else if (p >= a + b && p < a + b + c)\n      u += step;\n    else { // p > a + b + c && p < a + b + c + d\n      u += step;\n      v += step;\n    }\n\n    step /= 2;\n\n    // 0.2 and 0.9 are hardcoded in the reference SSCA implementation.\n    // The maximum change in any given value should be less than 10%\n    a *= 0.9 + 0.2 * (*prob)();\n    b *= 0.9 + 0.2 * (*prob)();\n    c *= 0.9 + 0.2 * (*prob)();\n    d *= 0.9 + 0.2 * (*prob)();\n\n    double S = a + b + c + d;\n\n    a /= S; b /= S; c /= S;\n    // d /= S;\n    // Ensure all values add up to 1, regardless of floating point errors\n    d = 1. - a - b - c;\n  }\n\n  return std::make_pair(u, v);\n}\n\nnamespace boost {\n\n  /*\n    Chakrabarti's R-MAT scale free generator.\n\n    For all flavors of the R-MAT iterator a+b+c+d must equal 1 and for the\n    unique_rmat_iterator 'm' << 'n^2'.  If 'm' is too close to 'n^2' the\n    generator may be unable to generate sufficient unique edges\n\n    To get a true scale free distribution {a, b, c, d : a > b, a > c, a > d}\n  */\n\n  template<typename RandomGenerator, typename Graph>\n  class rmat_iterator\n  {\n    typedef typename graph_traits<Graph>::directed_category directed_category;\n    typedef typename graph_traits<Graph>::vertices_size_type vertices_size_type;\n    typedef typename graph_traits<Graph>::edges_size_type edges_size_type;\n\n  public:\n    typedef std::input_iterator_tag iterator_category;\n    typedef std::pair<vertices_size_type, vertices_size_type> value_type;\n    typedef const value_type& reference;\n    typedef const value_type* pointer;\n    typedef std::ptrdiff_t difference_type; // Not used\n\n    // No argument constructor, set to terminating condition\n    rmat_iterator()\n      : gen(), edge(0) { }\n\n    // Initialize for edge generation\n    rmat_iterator(RandomGenerator& gen, vertices_size_type n,\n                  edges_size_type m, double a, double b, double c,\n                  double d, bool permute_vertices = true)\n      : gen(), n(n), a(a), b(b), c(c), d(d), edge(m),\n        permute_vertices(permute_vertices),\n        SCALE(int_log2(n))\n\n    {\n      this->gen.reset(new uniform_01<RandomGenerator>(gen));\n\n      // BOOST_ASSERT(boost::test_tools::check_is_close(a + b + c + d, 1., 1.e-5));\n\n      if (permute_vertices)\n        generate_permutation_vector(gen, vertexPermutation, n);\n\n      // TODO: Generate the entire adjacency matrix then \"Clip and flip\" if undirected graph\n\n      // Generate the first edge\n      vertices_size_type u, v;\n      boost::tie(u, v) = generate_edge(this->gen, n, SCALE, a, b, c, d);\n\n      if (permute_vertices)\n        current = std::make_pair(vertexPermutation[u],\n                                 vertexPermutation[v]);\n      else\n        current = std::make_pair(u, v);\n\n      --edge;\n    }\n\n    reference operator*() const { return current; }\n    pointer operator->() const { return &current; }\n\n    rmat_iterator& operator++()\n    {\n      vertices_size_type u, v;\n      boost::tie(u, v) = generate_edge(this->gen, n, SCALE, a, b, c, d);\n\n      if (permute_vertices)\n        current = std::make_pair(vertexPermutation[u],\n                                 vertexPermutation[v]);\n      else\n        current = std::make_pair(u, v);\n\n      --edge;\n\n      return *this;\n    }\n\n    rmat_iterator operator++(int)\n    {\n      rmat_iterator temp(*this);\n      ++(*this);\n      return temp;\n    }\n\n    bool operator==(const rmat_iterator& other) const\n    {\n      return edge == other.edge;\n    }\n\n    bool operator!=(const rmat_iterator& other) const\n    { return !(*this == other); }\n\n  private:\n\n    // Parameters\n    shared_ptr<uniform_01<RandomGenerator> > gen;\n    vertices_size_type n;\n    double a, b, c, d;\n    int edge;\n    bool permute_vertices;\n    int SCALE;\n\n    // Internal data structures\n    std::vector<vertices_size_type> vertexPermutation;\n    value_type current;\n  };\n\n  // Sorted version for CSR\n  template <typename T>\n  struct sort_pair {\n    bool operator() (const std::pair<T,T>& x, const std::pair<T,T>& y)\n    {\n      if (x.first == y.first)\n        return x.second > y.second;\n      else\n        return x.first > y.first;\n    }\n  };\n\n  template<typename RandomGenerator, typename Graph,\n           typename EdgePredicate = keep_all_edges>\n  class sorted_rmat_iterator\n  {\n    typedef typename graph_traits<Graph>::directed_category directed_category;\n    typedef typename graph_traits<Graph>::vertices_size_type vertices_size_type;\n    typedef typename graph_traits<Graph>::edges_size_type edges_size_type;\n\n  public:\n    typedef std::input_iterator_tag iterator_category;\n    typedef std::pair<vertices_size_type, vertices_size_type> value_type;\n    typedef const value_type& reference;\n    typedef const value_type* pointer;\n    typedef std::ptrdiff_t difference_type; // Not used\n\n    // No argument constructor, set to terminating condition\n    sorted_rmat_iterator()\n      : gen(), values(sort_pair<vertices_size_type>()), done(true)\n    { }\n\n    // Initialize for edge generation\n    sorted_rmat_iterator(RandomGenerator& gen, vertices_size_type n,\n                         edges_size_type m, double a, double b, double c,\n                         double d, bool permute_vertices = true,\n                         EdgePredicate ep = keep_all_edges())\n      : gen(), permute_vertices(permute_vertices),\n        values(sort_pair<vertices_size_type>()), done(false)\n\n    {\n      // BOOST_ASSERT(boost::test_tools::check_is_close(a + b + c + d, 1., 1.e-5));\n\n      this->gen.reset(new uniform_01<RandomGenerator>(gen));\n\n      std::vector<vertices_size_type> vertexPermutation;\n      if (permute_vertices)\n        generate_permutation_vector(gen, vertexPermutation, n);\n\n      // TODO: \"Clip and flip\" if undirected graph\n      int SCALE = int_log2(n);\n\n      for (edges_size_type i = 0; i < m; ++i) {\n\n        vertices_size_type u, v;\n        boost::tie(u, v) = generate_edge(this->gen, n, SCALE, a, b, c, d);\n\n        if (permute_vertices) {\n          if (ep(vertexPermutation[u], vertexPermutation[v]))\n            values.push(std::make_pair(vertexPermutation[u], vertexPermutation[v]));\n        } else {\n          if (ep(u, v))\n            values.push(std::make_pair(u, v));\n        }\n\n      }\n\n      current = values.top();\n      values.pop();\n    }\n\n    reference operator*() const { return current; }\n    pointer operator->() const { return &current; }\n\n    sorted_rmat_iterator& operator++()\n    {\n      if (!values.empty()) {\n        current = values.top();\n        values.pop();\n      } else\n        done = true;\n\n      return *this;\n    }\n\n    sorted_rmat_iterator operator++(int)\n    {\n      sorted_rmat_iterator temp(*this);\n      ++(*this);\n      return temp;\n    }\n\n    bool operator==(const sorted_rmat_iterator& other) const\n    {\n      return values.empty() && other.values.empty() && done && other.done;\n    }\n\n    bool operator!=(const sorted_rmat_iterator& other) const\n    { return !(*this == other); }\n\n  private:\n\n    // Parameters\n    shared_ptr<uniform_01<RandomGenerator> > gen;\n    bool permute_vertices;\n\n    // Internal data structures\n    std::priority_queue<value_type, std::vector<value_type>, sort_pair<vertices_size_type> > values;\n    value_type current;\n    bool       done;\n  };\n\n\n  // This version is slow but guarantees unique edges\n  template<typename RandomGenerator, typename Graph,\n           typename EdgePredicate = keep_all_edges>\n  class unique_rmat_iterator\n  {\n    typedef typename graph_traits<Graph>::directed_category directed_category;\n    typedef typename graph_traits<Graph>::vertices_size_type vertices_size_type;\n    typedef typename graph_traits<Graph>::edges_size_type edges_size_type;\n\n  public:\n    typedef std::input_iterator_tag iterator_category;\n    typedef std::pair<vertices_size_type, vertices_size_type> value_type;\n    typedef const value_type& reference;\n    typedef const value_type* pointer;\n    typedef std::ptrdiff_t difference_type; // Not used\n\n    // No argument constructor, set to terminating condition\n    unique_rmat_iterator()\n        : gen(), done(true)\n    { }\n\n    // Initialize for edge generation\n    unique_rmat_iterator(RandomGenerator& gen, vertices_size_type n,\n                         edges_size_type m, double a, double b, double c,\n                         double d, bool permute_vertices = true,\n                         EdgePredicate ep = keep_all_edges())\n      : gen(), done(false)\n\n    {\n      // BOOST_ASSERT(boost::test_tools::check_is_close(a + b + c + d, 1., 1.e-5));\n\n      this->gen.reset(new uniform_01<RandomGenerator>(gen));\n\n      std::vector<vertices_size_type> vertexPermutation;\n      if (permute_vertices)\n        generate_permutation_vector(gen, vertexPermutation, n);\n\n      int SCALE = int_log2(n);\n\n      std::map<value_type, bool> edge_map;\n\n      edges_size_type edges = 0;\n      do {\n        vertices_size_type u, v;\n        boost::tie(u, v) = generate_edge(this->gen, n, SCALE, a, b, c, d);\n\n        // Lowest vertex number always comes first\n        // (this means we don't have to worry about i->j and j->i being in the edge list)\n        if (u > v && is_same<directed_category, undirected_tag>::value)\n          std::swap(u, v);\n\n        if (edge_map.find(std::make_pair(u, v)) == edge_map.end()) {\n          edge_map[std::make_pair(u, v)] = true;\n\n          if (permute_vertices) {\n            if (ep(vertexPermutation[u], vertexPermutation[v]))\n              values.push_back(std::make_pair(vertexPermutation[u], vertexPermutation[v]));\n          } else {\n            if (ep(u, v))\n              values.push_back(std::make_pair(u, v));\n          }\n\n          edges++;\n        }\n      } while (edges < m);\n      // NGE - Asking for more than n^2 edges will result in an infinite loop here\n      //       Asking for a value too close to n^2 edges may as well\n\n      current = values.back();\n      values.pop_back();\n    }\n\n    reference operator*() const { return current; }\n    pointer operator->() const { return &current; }\n\n    unique_rmat_iterator& operator++()\n    {\n      if (!values.empty()) {\n        current = values.back();\n        values.pop_back();\n      } else\n        done = true;\n\n      return *this;\n    }\n\n    unique_rmat_iterator operator++(int)\n    {\n      unique_rmat_iterator temp(*this);\n      ++(*this);\n      return temp;\n    }\n\n    bool operator==(const unique_rmat_iterator& other) const\n    {\n      return values.empty() && other.values.empty() && done && other.done;\n    }\n\n    bool operator!=(const unique_rmat_iterator& other) const\n    { return !(*this == other); }\n\n  private:\n\n    // Parameters\n    shared_ptr<uniform_01<RandomGenerator> > gen;\n\n    // Internal data structures\n    std::vector<value_type> values;\n    value_type              current;\n    bool                    done;\n  };\n\n  // This version is slow but guarantees unique edges\n  template<typename RandomGenerator, typename Graph,\n           typename EdgePredicate = keep_all_edges>\n  class sorted_unique_rmat_iterator\n  {\n    typedef typename graph_traits<Graph>::directed_category directed_category;\n    typedef typename graph_traits<Graph>::vertices_size_type vertices_size_type;\n    typedef typename graph_traits<Graph>::edges_size_type edges_size_type;\n\n  public:\n    typedef std::input_iterator_tag iterator_category;\n    typedef std::pair<vertices_size_type, vertices_size_type> value_type;\n    typedef const value_type& reference;\n    typedef const value_type* pointer;\n    typedef std::ptrdiff_t difference_type; // Not used\n\n    // No argument constructor, set to terminating condition\n    sorted_unique_rmat_iterator()\n      : gen(), values(sort_pair<vertices_size_type>()), done(true) { }\n\n    // Initialize for edge generation\n    sorted_unique_rmat_iterator(RandomGenerator& gen, vertices_size_type n,\n                                edges_size_type m, double a, double b, double c,\n                                double d, bool bidirectional = false,\n                                bool permute_vertices = true,\n                                EdgePredicate ep = keep_all_edges())\n      : gen(), bidirectional(bidirectional),\n        values(sort_pair<vertices_size_type>()), done(false)\n\n    {\n      // BOOST_ASSERT(boost::test_tools::check_is_close(a + b + c + d, 1., 1.e-5));\n\n      this->gen.reset(new uniform_01<RandomGenerator>(gen));\n\n      std::vector<vertices_size_type> vertexPermutation;\n      if (permute_vertices)\n        generate_permutation_vector(gen, vertexPermutation, n);\n\n      int SCALE = int_log2(n);\n\n      std::map<value_type, bool> edge_map;\n\n      edges_size_type edges = 0;\n      do {\n\n        vertices_size_type u, v;\n        boost::tie(u, v) = generate_edge(this->gen, n, SCALE, a, b, c, d);\n\n        if (bidirectional) {\n          if (edge_map.find(std::make_pair(u, v)) == edge_map.end()) {\n            edge_map[std::make_pair(u, v)] = true;\n            edge_map[std::make_pair(v, u)] = true;\n\n            if (ep(u, v)) {\n              if (permute_vertices) {\n                values.push(std::make_pair(vertexPermutation[u], vertexPermutation[v]));\n                values.push(std::make_pair(vertexPermutation[v], vertexPermutation[u]));\n              } else {\n                values.push(std::make_pair(u, v));\n                values.push(std::make_pair(v, u));\n              }\n           }\n\n            ++edges;\n          }\n        } else {\n          // Lowest vertex number always comes first\n          // (this means we don't have to worry about i->j and j->i being in the edge list)\n          if (u > v && is_same<directed_category, undirected_tag>::value)\n            std::swap(u, v);\n\n          if (edge_map.find(std::make_pair(u, v)) == edge_map.end()) {\n            edge_map[std::make_pair(u, v)] = true;\n\n            if (permute_vertices) {\n              if (ep(vertexPermutation[u], vertexPermutation[v]))\n                values.push(std::make_pair(vertexPermutation[u], vertexPermutation[v]));\n            } else {\n              if (ep(u, v))\n                values.push(std::make_pair(u, v));\n            }\n\n            ++edges;\n          }\n        }\n\n      } while (edges < m);\n      // NGE - Asking for more than n^2 edges will result in an infinite loop here\n      //       Asking for a value too close to n^2 edges may as well\n\n      current = values.top();\n      values.pop();\n    }\n\n    reference operator*() const { return current; }\n    pointer operator->() const { return &current; }\n\n    sorted_unique_rmat_iterator& operator++()\n    {\n      if (!values.empty()) {\n        current = values.top();\n        values.pop();\n      } else\n        done = true;\n\n      return *this;\n    }\n\n    sorted_unique_rmat_iterator operator++(int)\n    {\n      sorted_unique_rmat_iterator temp(*this);\n      ++(*this);\n      return temp;\n    }\n\n    bool operator==(const sorted_unique_rmat_iterator& other) const\n    {\n      return values.empty() && other.values.empty() && done && other.done;\n    }\n\n    bool operator!=(const sorted_unique_rmat_iterator& other) const\n    { return !(*this == other); }\n\n  private:\n\n    // Parameters\n    shared_ptr<uniform_01<RandomGenerator> > gen;\n    bool             bidirectional;\n\n    // Internal data structures\n    std::priority_queue<value_type, std::vector<value_type>,\n                        sort_pair<vertices_size_type> > values;\n    value_type current;\n    bool       done;\n  };\n\n} // end namespace boost\n\n#include BOOST_GRAPH_MPI_INCLUDE(<boost/graph/distributed/rmat_graph_generator.hpp>)\n\n#endif // BOOST_GRAPH_RMAT_GENERATOR_HPP\n", "meta": {"hexsha": "a96887fbd6cafc2fefb65ff5ebc39ef599831c37", "size": 17942, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/graph/rmat_graph_generator.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/rmat_graph_generator.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/rmat_graph_generator.hpp", "max_forks_repo_name": "cpp-pm/boost", "max_forks_repo_head_hexsha": "38c6c8c07f2fcc42d573b10807fef27ec14930f8", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 892.0, "max_forks_repo_forks_event_min_datetime": "2015-01-29T16:26:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-20T07:44:30.000Z", "avg_line_length": 30.1546218487, "max_line_length": 100, "alphanum_fraction": 0.6238992309, "num_tokens": 4362, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6039318337259584, "lm_q2_score": 0.5774953651858117, "lm_q1q2_score": 0.34876783486490925}}
{"text": "\r\n\r\n#include <NTL/ZZ_p.h>\r\n#include <NTL/FFT.h>\r\n\r\n#include <NTL/new.h>\r\n\r\n\r\nNTL_START_IMPL\r\n\r\n\r\n\r\nNTL_THREAD_LOCAL SmartPtr<ZZ_pInfoT> ZZ_pInfo = 0;\r\nNTL_THREAD_LOCAL SmartPtr<ZZ_pTmpSpaceT> ZZ_pTmpSpace = 0;\r\nNTL_THREAD_LOCAL bool ZZ_pInstalled = false;\r\n\r\n\r\n\r\nZZ_pInfoT::ZZ_pInfoT(const ZZ& NewP)\r\n{\r\n   if (NewP <= 1) LogicError(\"ZZ_pContext: p must be > 1\");\r\n\r\n   p = NewP;\r\n   size = p.size();\r\n\r\n   ExtendedModulusSize = 2*size + \r\n                 (NTL_BITS_PER_LONG + NTL_ZZ_NBITS - 1)/NTL_ZZ_NBITS;\r\n\r\n}\r\n\r\n\r\n\r\n// we use a lazy strategy for initializing and installing\r\n// FFTInfo and TmpSpace related to a ZZ_p modulus.  \r\n// The routines GetFFTInfo and GetTmpSpace make sure this process \r\n// is complete.\r\n\r\nvoid ZZ_p::DoInstall()\r\n{\r\n   SmartPtr<ZZ_pTmpSpaceT> tmps = 0;\r\n\r\n   do { // NOTE: thread safe lazy init \r\n      Lazy<ZZ_pFFTInfoT>::Builder builder(ZZ_pInfo->FFTInfo);\r\n      if (!builder()) break;\r\n\r\n      UniquePtr<ZZ_pFFTInfoT> FFTInfo;\r\n      FFTInfo.make();\r\n\r\n      ZZ B, M, M1, M2, M3;\r\n      long n, i;\r\n      long q, t;\r\n\r\n      sqr(B, ZZ_pInfo->p);\r\n\r\n      LeftShift(B, B, NTL_FFTMaxRoot+NTL_FFTFudge);\r\n\r\n      // FIXME: the following is quadratic time...would\r\n      // be nice to get a faster solution...\r\n      // One could estimate the # of primes by summing logs,\r\n      // then multiply using a tree-based multiply, then \r\n      // adjust up or down...\r\n\r\n      // Assuming IEEE floating point, the worst case estimate\r\n      // for error guarantees a correct answer +/- 1 for\r\n      // numprimes up to 2^25...for sure we won't be\r\n      // using that many primes...we can certainly put in \r\n      // a sanity check, though. \r\n\r\n      // If I want a more accuaruate summation (with using Kahan,\r\n      // which has some portability issues), I could represent \r\n      // numbers as x = a + f, where a is integer and f is the fractional\r\n      // part.  Summing in this representation introduces an *absolute*\r\n      // error of 2 epsilon n, which is just as good as Kahan \r\n      // for this application.\r\n\r\n      // same strategy could also be used in the ZZX HomMul routine,\r\n      // if we ever want to make that subquadratic\r\n\r\n      set(M);\r\n      n = 0;\r\n      while (M <= B) {\r\n         UseFFTPrime(n);\r\n         q = GetFFTPrime(n);\r\n         n++;\r\n         mul(M, M, q);\r\n      }\r\n\r\n      FFTInfo->NumPrimes = n;\r\n      FFTInfo->MaxRoot = CalcMaxRoot(q);\r\n\r\n\r\n      double fn = double(n);\r\n\r\n      if (8.0*fn*(fn+32) > NTL_FDOUBLE_PRECISION)\r\n         ResourceError(\"modulus too big\");\r\n\r\n\r\n      if (8.0*fn*(fn+32) > NTL_FDOUBLE_PRECISION/double(NTL_SP_BOUND))\r\n         FFTInfo->QuickCRT = false;\r\n      else\r\n         FFTInfo->QuickCRT = true;\r\n\r\n\r\n      FFTInfo->x.SetLength(n);\r\n      FFTInfo->u.SetLength(n);\r\n\r\n      FFTInfo->rem_struct.init(n, ZZ_pInfo->p, GetFFTPrime);\r\n\r\n      FFTInfo->crt_struct.init(n, ZZ_pInfo->p, GetFFTPrime);\r\n\r\n      if (!FFTInfo->crt_struct.special()) {\r\n         ZZ qq, rr;\r\n\r\n         DivRem(qq, rr, M, ZZ_pInfo->p);\r\n\r\n         NegateMod(FFTInfo->MinusMModP, rr, ZZ_pInfo->p);\r\n\r\n         for (i = 0; i < n; i++) {\r\n            q = GetFFTPrime(i);\r\n\r\n            long tt = rem(qq, q);\r\n\r\n            mul(M2, ZZ_pInfo->p, tt);\r\n            add(M2, M2, rr); \r\n            div(M2, M2, q);  // = (M/q) rem p\r\n            \r\n\r\n            div(M1, M, q);\r\n            t = rem(M1, q);\r\n            t = InvMod(t, q);\r\n\r\n            mul(M3, M2, t);\r\n            rem(M3, M3, ZZ_pInfo->p);\r\n\r\n            FFTInfo->crt_struct.insert(i, M3);\r\n\r\n\r\n            FFTInfo->x[i] = ((double) t)/((double) q);\r\n            FFTInfo->u[i] = t;\r\n         }\r\n      }\r\n\r\n      tmps = MakeSmart<ZZ_pTmpSpaceT>();\r\n      tmps->crt_tmp_vec.fetch(FFTInfo->crt_struct);\r\n      tmps->rem_tmp_vec.fetch(FFTInfo->rem_struct);\r\n\r\n      builder.move(FFTInfo);\r\n   } while (0);\r\n\r\n   if (!tmps) {\r\n      const ZZ_pFFTInfoT *FFTInfo = ZZ_pInfo->FFTInfo.get();\r\n      tmps = MakeSmart<ZZ_pTmpSpaceT>();\r\n      tmps->crt_tmp_vec.fetch(FFTInfo->crt_struct);\r\n      tmps->rem_tmp_vec.fetch(FFTInfo->rem_struct);\r\n   }\r\n\r\n   ZZ_pTmpSpace = tmps;\r\n}\r\n\r\n\r\n\r\n\r\nvoid ZZ_p::init(const ZZ& p)\r\n{\r\n   ZZ_pContext c(p);\r\n   c.restore();\r\n}\r\n\r\n\r\n\r\nvoid ZZ_pContext::restore() const\r\n{\r\n   ZZ_pInfo = ptr;\r\n   ZZ_pTmpSpace = 0;\r\n   ZZ_pInstalled = false;\r\n}\r\n\r\n\r\n\r\nZZ_pBak::~ZZ_pBak()\r\n{\r\n   if (MustRestore) c.restore();\r\n}\r\n\r\nvoid ZZ_pBak::save()\r\n{\r\n   c.save();\r\n   MustRestore = true;\r\n}\r\n\r\n\r\nvoid ZZ_pBak::restore()\r\n{\r\n   c.restore();\r\n   MustRestore = false;\r\n}\r\n\r\n\r\nconst ZZ_p& ZZ_p::zero()\r\n{\r\n   NTL_THREAD_LOCAL static ZZ_p z(INIT_NO_ALLOC);\r\n   return z;\r\n}\r\n\r\nNTL_THREAD_LOCAL\r\nZZ_p::DivHandlerPtr ZZ_p::DivHandler = 0;\r\n\r\n   \r\n\r\nZZ_p::ZZ_p(INIT_VAL_TYPE, const ZZ& a)  // NO_ALLOC\r\n{\r\n   conv(*this, a);\r\n} \r\n\r\nZZ_p::ZZ_p(INIT_VAL_TYPE, long a) // NO_ALLOC\r\n{\r\n   conv(*this, a);\r\n}\r\n\r\n\r\nvoid conv(ZZ_p& x, long a)\r\n{\r\n   if (a == 0)\r\n      clear(x);\r\n   else if (a == 1)\r\n      set(x);\r\n   else {\r\n      NTL_ZZRegister(y);\r\n\r\n      conv(y, a);\r\n      conv(x, y);\r\n   }\r\n}\r\n\r\nistream& operator>>(istream& s, ZZ_p& x)\r\n{\r\n   NTL_ZZRegister(y);\r\n\r\n   NTL_INPUT_CHECK_RET(s, s >> y);\r\n   conv(x, y);\r\n\r\n   return s;\r\n}\r\n\r\nvoid div(ZZ_p& x, const ZZ_p& a, const ZZ_p& b)\r\n{\r\n   NTL_ZZ_pRegister(T);\r\n\r\n   inv(T, b);\r\n   mul(x, a, T);\r\n}\r\n\r\nvoid inv(ZZ_p& x, const ZZ_p& a)\r\n{\r\n   NTL_ZZRegister(T);\r\n\r\n   if (InvModStatus(T, a._ZZ_p__rep, ZZ_p::modulus())) {\r\n      if (!IsZero(a._ZZ_p__rep) && ZZ_p::DivHandler)\r\n         (*ZZ_p::DivHandler)(a);\r\n\r\n      InvModError(\"ZZ_p: division by non-invertible element\",\r\n                   a._ZZ_p__rep, ZZ_p::modulus());\r\n   }\r\n\r\n   x._ZZ_p__rep = T;\r\n}\r\n\r\nlong operator==(const ZZ_p& a, long b)\r\n{\r\n   if (b == 0)\r\n      return IsZero(a);\r\n\r\n   if (b == 1)\r\n      return IsOne(a);\r\n\r\n   NTL_ZZ_pRegister(T);\r\n   conv(T, b);\r\n   return a == T;\r\n}\r\n\r\n\r\n\r\nvoid add(ZZ_p& x, const ZZ_p& a, long b)\r\n{\r\n   NTL_ZZ_pRegister(T);\r\n   conv(T, b);\r\n   add(x, a, T);\r\n}\r\n\r\nvoid sub(ZZ_p& x, const ZZ_p& a, long b)\r\n{\r\n   NTL_ZZ_pRegister(T);\r\n   conv(T, b);\r\n   sub(x, a, T);\r\n}\r\n\r\nvoid sub(ZZ_p& x, long a, const ZZ_p& b)\r\n{\r\n   NTL_ZZ_pRegister(T);\r\n   conv(T, a);\r\n   sub(x, T, b);\r\n}\r\n\r\nvoid mul(ZZ_p& x, const ZZ_p& a, long b)\r\n{\r\n   NTL_ZZ_pRegister(T);\r\n   conv(T, b);\r\n   mul(x, a, T);\r\n}\r\n\r\nvoid div(ZZ_p& x, const ZZ_p& a, long b)\r\n{\r\n   NTL_ZZ_pRegister(T);\r\n   conv(T, b);\r\n   div(x, a, T);\r\n}\r\n\r\nvoid div(ZZ_p& x, long a, const ZZ_p& b)\r\n{\r\n   if (a == 1) {\r\n      inv(x, b);\r\n   }\r\n   else {\r\n      NTL_ZZ_pRegister(T);\r\n      conv(T, a);\r\n      div(x, T, b);\r\n   }\r\n}\r\n\r\nNTL_END_IMPL\r\n", "meta": {"hexsha": "3a20a886cbda43f771061d4bd4270e4567ad4f7c", "size": 6578, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "WinNTL-8_1_2/src/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/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/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": 19.8731117825, "max_line_length": 74, "alphanum_fraction": 0.5442383703, "num_tokens": 2012, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5774953651858118, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.34876783486490925}}
{"text": "/**\n * @file SimPolygon2D.cpp\n * @author Alex Cunningham\n */\n\n#include <iostream>\n#include <boost/random/linear_congruential.hpp>\n#include <boost/random/uniform_real.hpp>\n#include <boost/random/normal_distribution.hpp>\n#include <boost/random/variate_generator.hpp>\n\n#include <gtsam_unstable/geometry/SimPolygon2D.h>\n\nnamespace gtsam {\n\nusing namespace std;\n\nconst size_t max_it = 100000;\nboost::minstd_rand SimPolygon2D::rng(42u);\n\n/* ************************************************************************* */\nvoid SimPolygon2D::seedGenerator(unsigned long seed) {\n  rng = boost::minstd_rand(seed);\n}\n\n/* ************************************************************************* */\nSimPolygon2D SimPolygon2D::createTriangle(const Point2& pA, const Point2& pB, const Point2& pC) {\n  SimPolygon2D result;\n  result.landmarks_.push_back(pA);\n  result.landmarks_.push_back(pB);\n  result.landmarks_.push_back(pC);\n  return result;\n}\n\n/* ************************************************************************* */\nSimPolygon2D SimPolygon2D::createRectangle(const Point2& p, double height, double width) {\n  SimPolygon2D result;\n  result.landmarks_.push_back(p);\n  result.landmarks_.push_back(p + Point2(width, 0.0));\n  result.landmarks_.push_back(p + Point2(width, height));\n  result.landmarks_.push_back(p + Point2(0.0, height));\n  return result;\n}\n\n/* ************************************************************************* */\nbool SimPolygon2D::equals(const SimPolygon2D& p, double tol) const {\n  if (p.size() != size()) return false;\n  for (size_t i=0; i<size(); ++i)\n    if (!traits<Point2>::Equals(landmarks_[i], p.landmarks_[i], tol))\n      return false;\n  return true;\n}\n\n/* ************************************************************************* */\nvoid SimPolygon2D::print(const string& s) const {\n  cout << \"SimPolygon \" << s << \": \" << endl;\n  for(const Point2& p: landmarks_)\n    traits<Point2>::Print(p, \"   \");\n}\n\n/* ************************************************************************* */\nvector<SimWall2D> SimPolygon2D::walls() const {\n  vector<SimWall2D> result;\n  for (size_t i=0; i<size()-1; ++i)\n    result.push_back(SimWall2D(landmarks_[i], landmarks_[i+1]));\n  result.push_back(SimWall2D(landmarks_[size()-1], landmarks_[0]));\n  return result;\n}\n\n/* ************************************************************************* */\nbool SimPolygon2D::contains(const Point2& c) const {\n  vector<SimWall2D> edges = walls();\n  bool initialized = false;\n  bool lastSide = false;\n  for(const SimWall2D& ab: edges) {\n    // compute cross product of ab and ac\n    Point2 dab = ab.b() - ab.a();\n    Point2 dac = c - ab.a();\n    double cross = dab.x() * dac.y() - dab.y() * dac.x();\n    if (fabs(cross) < 1e-6) // check for on one of the edges\n      return true;\n    bool side = cross > 0;\n    // save the first side found\n    if (!initialized) {\n      lastSide = side;\n      initialized = true;\n      continue;\n    }\n\n    // to be inside the polygon, point must be on the same side of all lines\n    if (lastSide != side)\n      return false;\n  }\n  return true;\n}\n\n/* ************************************************************************* */\nbool SimPolygon2D::overlaps(const SimPolygon2D& p) const {\n  for(const Point2& a: landmarks_)\n    if (p.contains(a))\n      return true;\n  for(const Point2& a: p.landmarks_)\n    if (contains(a))\n      return true;\n  return false;\n}\n\n/* ***************************************************************** */\nbool SimPolygon2D::anyContains(const Point2& p, const vector<SimPolygon2D>& obstacles) {\n  for(const SimPolygon2D& poly: obstacles)\n    if (poly.contains(p))\n      return true;\n  return false;\n}\n\n/* ************************************************************************* */\nbool SimPolygon2D::anyOverlaps(const SimPolygon2D& p, const vector<SimPolygon2D>& obstacles) {\n  for(const SimPolygon2D& poly: obstacles)\n    if (poly.overlaps(p))\n      return true;\n  return false;\n}\n\n/* ************************************************************************* */\nSimPolygon2D SimPolygon2D::randomTriangle(\n    double side_len, double mean_side_len, double sigma_side_len,\n    double min_vertex_dist, double min_side_len, const vector<SimPolygon2D>& existing_polys) {\n  // get the current set of landmarks\n  std::vector<Point2> lms;\n  double d2 = side_len/2.0;\n  lms.push_back(Point2( d2, d2));\n  lms.push_back(Point2(-d2, d2));\n  lms.push_back(Point2(-d2,-d2));\n  lms.push_back(Point2( d2,-d2));\n\n  for(const SimPolygon2D& poly: existing_polys)\n    lms.insert(lms.begin(), poly.vertices().begin(), poly.vertices().end());\n\n  for (size_t i=0; i<max_it; ++i) {\n\n    // find a random pose for line AB\n    Pose2 xA(randomAngle(), randomBoundedPoint2(side_len, lms, existing_polys, min_vertex_dist));\n\n    // extend line by random dist and angle to get BC\n    double dAB = randomDistance(mean_side_len, sigma_side_len, min_side_len);\n    double tABC = randomAngle().theta();\n    Pose2 xB = xA.retract((Vector(3) << dAB, 0.0, tABC).finished());\n\n    // extend from B to find C\n    double dBC = randomDistance(mean_side_len, sigma_side_len, min_side_len);\n    Pose2 xC = xB.retract(Vector::Unit(3,0)*dBC);\n\n    // use triangle equality to verify non-degenerate triangle\n    double dAC = distance2(xA.t(), xC.t());\n\n    // form a triangle and test if it meets requirements\n    SimPolygon2D test_tri = SimPolygon2D::createTriangle(xA.t(), xB.t(), xC.t());\n\n    // check inside walls, long enough edges, far away from landmarks\n    const double thresh = mean_side_len / 2.0;\n    if ((dAB + dBC + thresh > dAC) &&  // triangle inequality\n        (dAB + dAC + thresh > dBC) &&\n        (dAC + dBC + thresh > dAB) &&\n        insideBox(side_len, test_tri.landmark(0)) &&\n        insideBox(side_len, test_tri.landmark(1)) &&\n        insideBox(side_len, test_tri.landmark(2)) &&\n        distance2(test_tri.landmark(1), test_tri.landmark(2)) > min_side_len &&\n        !nearExisting(lms, test_tri.landmark(0), min_vertex_dist) &&\n        !nearExisting(lms, test_tri.landmark(1), min_vertex_dist) &&\n        !nearExisting(lms, test_tri.landmark(2), min_vertex_dist) &&\n        !anyOverlaps(test_tri, existing_polys)) {\n      return test_tri;\n    }\n  }\n  throw runtime_error(\"Could not find space for a triangle\");\n  return SimPolygon2D::createTriangle(Point2(99,99), Point2(99,99), Point2(99,99));\n}\n\n/* ************************************************************************* */\nSimPolygon2D SimPolygon2D::randomRectangle(\n    double side_len, double mean_side_len, double sigma_side_len,\n    double min_vertex_dist, double min_side_len, const vector<SimPolygon2D>& existing_polys) {\n  // get the current set of landmarks\n  std::vector<Point2> lms;\n  double d2 = side_len/2.0;\n  lms.push_back(Point2( d2, d2));\n  lms.push_back(Point2(-d2, d2));\n  lms.push_back(Point2(-d2,-d2));\n  lms.push_back(Point2( d2,-d2));\n  for(const SimPolygon2D& poly: existing_polys)\n    lms.insert(lms.begin(), poly.vertices().begin(), poly.vertices().end());\n\n  const Point2 lower_corner(-side_len,-side_len);\n  const Point2 upper_corner( side_len, side_len);\n\n  for (size_t i=0; i<max_it; ++i) {\n\n    // pick height and width to be viable distances\n    double height = randomDistance(mean_side_len, sigma_side_len, min_side_len);\n    double width = randomDistance(mean_side_len, sigma_side_len, min_side_len);\n\n    // find a starting point - limited to region viable for this height/width\n    Point2 pA = randomBoundedPoint2(lower_corner, upper_corner - Point2(width, height),\n        lms, existing_polys, min_vertex_dist);\n\n    // verify\n    SimPolygon2D rect = SimPolygon2D::createRectangle(pA, height, width);\n\n    // check inside walls, long enough edges, far away from landmarks\n    if (insideBox(side_len, rect.landmark(0)) &&\n        insideBox(side_len, rect.landmark(1)) &&\n        insideBox(side_len, rect.landmark(2)) &&\n        insideBox(side_len, rect.landmark(3)) &&\n        !nearExisting(lms, rect.landmark(0), min_vertex_dist) &&\n        !nearExisting(lms, rect.landmark(1), min_vertex_dist) &&\n        !nearExisting(lms, rect.landmark(2), min_vertex_dist) &&\n        !nearExisting(lms, rect.landmark(3), min_vertex_dist) &&\n        !anyOverlaps(rect, existing_polys)) {\n      return rect;\n    }\n  }\n  throw runtime_error(\"Could not find space for a rectangle\");\n  return SimPolygon2D::createRectangle(Point2(99,99), 100, 100);\n}\n\n/* ***************************************************************** */\nPoint2 SimPolygon2D::randomPoint2(double s) {\n  boost::uniform_real<>  gen_t(-s/2.0, s/2.0);\n  return Point2(gen_t(rng), gen_t(rng));\n}\n\n/* ***************************************************************** */\nRot2 SimPolygon2D::randomAngle() {\n  boost::uniform_real<>  gen_r(-M_PI, M_PI); // modified range to avoid degenerate cases in triangles\n  return Rot2::fromAngle(gen_r(rng));\n}\n\n/* ***************************************************************** */\ndouble SimPolygon2D::randomDistance(double mu, double sigma, double min_dist) {\n  boost::normal_distribution<double> norm_dist(mu, sigma);\n  boost::variate_generator<boost::minstd_rand&, boost::normal_distribution<double> > gen_d(rng, norm_dist);\n  double d = -10.0;\n  for (size_t i=0; i<max_it; ++i) {\n    d = fabs(gen_d());\n    if (d > min_dist)\n      return d;\n  }\n  cout << \"Non viable distance: \" << d << \" with mu = \" << mu << \" sigma = \" << sigma\n       << \" min_dist = \" << min_dist << endl;\n  throw runtime_error(\"Failed to find a viable distance\");\n  return fabs(norm_dist(rng));\n}\n\n/* ***************************************************************** */\nPoint2 SimPolygon2D::randomBoundedPoint2(double boundary_size,\n      const vector<SimPolygon2D>& obstacles) {\n  for (size_t i=0; i<max_it; ++i) {\n    Point2 p = randomPoint2(boundary_size);\n    if (!anyContains(p, obstacles))\n      return p;\n  }\n  throw runtime_error(\"Failed to find a place for a landmark!\");\n  return Point2(0,0);\n}\n\n/* ***************************************************************** */\nPoint2 SimPolygon2D::randomBoundedPoint2(double boundary_size,\n    const std::vector<Point2>& landmarks, double min_landmark_dist) {\n  for (size_t i=0; i<max_it; ++i) {\n    Point2 p = randomPoint2(boundary_size);\n    if (!nearExisting(landmarks, p, min_landmark_dist))\n      return p;\n  }\n  throw runtime_error(\"Failed to find a place for a landmark!\");\n  return Point2(0,0);\n}\n\n/* ***************************************************************** */\nPoint2 SimPolygon2D::randomBoundedPoint2(double boundary_size,\n    const std::vector<Point2>& landmarks,\n    const vector<SimPolygon2D>& obstacles, double min_landmark_dist) {\n  for (size_t i=0; i<max_it; ++i) {\n    Point2 p = randomPoint2(boundary_size);\n    if (!nearExisting(landmarks, p, min_landmark_dist) && !anyContains(p, obstacles))\n      return p;\n  }\n  throw runtime_error(\"Failed to find a place for a landmark!\");\n  return Point2(0,0);\n}\n\n/* ***************************************************************** */\nPoint2 SimPolygon2D::randomBoundedPoint2(\n    const Point2& LL_corner, const Point2& UR_corner,\n    const std::vector<Point2>& landmarks,\n    const std::vector<SimPolygon2D>& obstacles, double min_landmark_dist) {\n\n  boost::uniform_real<>  gen_x(0.0, UR_corner.x() - LL_corner.x());\n  boost::uniform_real<>  gen_y(0.0, UR_corner.y() - LL_corner.y());\n\n  for (size_t i=0; i<max_it; ++i) {\n    Point2 p = Point2(gen_x(rng), gen_y(rng)) + LL_corner;\n    if (!nearExisting(landmarks, p, min_landmark_dist) && !anyContains(p, obstacles))\n      return p;\n  }\n  throw runtime_error(\"Failed to find a place for a landmark!\");\n  return Point2(0,0);\n}\n\n/* ***************************************************************** */\nPose2 SimPolygon2D::randomFreePose(double boundary_size, const vector<SimPolygon2D>& obstacles) {\n  return Pose2(randomAngle(), randomBoundedPoint2(boundary_size, obstacles));\n}\n\n/* ***************************************************************** */\nbool SimPolygon2D::insideBox(double s, const Point2& p) {\n  return fabs(p.x()) < s/2.0 && fabs(p.y()) < s/2.0;\n}\n\n/* ***************************************************************** */\nbool SimPolygon2D::nearExisting(const std::vector<Point2>& S,\n    const Point2& p, double threshold) {\n  for(const Point2& Sp: S)\n    if (distance2(Sp, p) < threshold)\n      return true;\n  return false;\n}\n\n} //\\namespace gtsam\n\n", "meta": {"hexsha": "ba1445b207d00deecc1378d7434655b9e70e69f3", "size": 12323, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "gtsam_unstable/geometry/SimPolygon2D.cpp", "max_stars_repo_name": "alexhagiopol/GTSAM", "max_stars_repo_head_hexsha": "c397fac199d0202c7abb1cd8e6005731658f56e8", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2018-12-19T08:19:37.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-16T05:22:05.000Z", "max_issues_repo_path": "gtsam_unstable/geometry/SimPolygon2D.cpp", "max_issues_repo_name": "luhongquan66/gtsam", "max_issues_repo_head_hexsha": "c21186c6212798e665da6b5015296713ddfe8c1d", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-11-09T06:39:02.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-09T06:39:02.000Z", "max_forks_repo_path": "gtsam_unstable/geometry/SimPolygon2D.cpp", "max_forks_repo_name": "luhongquan66/gtsam", "max_forks_repo_head_hexsha": "c21186c6212798e665da6b5015296713ddfe8c1d", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 11.0, "max_forks_repo_forks_event_min_datetime": "2016-08-30T13:14:48.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-12T18:49:58.000Z", "avg_line_length": 37.3424242424, "max_line_length": 107, "alphanum_fraction": 0.5943357949, "num_tokens": 3155, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.603931819468636, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.34876782663137174}}
{"text": "/**\n\n\\file\n\\author Datta Ramadasan\n//==============================================================================\n//         Copyright 2015 INSTITUT PASCAL UMR 6602 CNRS/Univ. Clermont II\n//\n//          Distributed under the Boost Software License, Version 1.0.\n//                 See accompanying file LICENSE.txt or copy at\n//                     http://www.boost.org/LICENSE_1_0.txt\n//==============================================================================\n\n*/\n\n#ifndef __OPTIMISATION2_FUNCTION_DERIVATIVE_NUMERICAL_DERIVATIVE_HPP__\n#define __OPTIMISATION2_FUNCTION_DERIVATIVE_NUMERICAL_DERIVATIVE_HPP__\n\n#include \"detail_derivative.hpp\"\n#include <libv/lma/ttt/traits/unroll1.hpp>\n#include <boost/fusion/include/vector_tie.hpp>\n#include <libv/lma/lm/trait/accessor.hpp>\n\ntemplate<class T >\nstruct Container;\n\nnamespace lma\n{\n  //! calcul de dérivée numérique avec déroulage static sur les blocks, puis sur les paramètres de chaque block, puis sur chaque résidu\n\n    \n  namespace detail\n  {\n    template<class Float, std::size_t I, std::size_t Fin> struct TupleDerivator;\n    template<class Float, std::size_t Fin> struct TupleDerivator<Float,Fin,Fin>\n    {\n      template<class A, class B, class C, class D> static void compute(const A&, const B&, const C&, const D&){}\n      template<class A, class B, class C> static void compute(const A&, const B&, const C&){}\n    };\n\n    template<class Float, std::size_t K, size_t I, std::size_t F> struct TupleDerivatorInternal;\n    template<class Float, std::size_t K, size_t F> struct TupleDerivatorInternal<Float,K,F,F>\n    {\n      template<class Fonction, class Result, class Tuple, class R1> static void compute(const Fonction&, Result&, Tuple&, const R1&){}\n      template<class Fonction, class Result, class Tuple> static void compute(const Fonction&, Result&, Tuple&){}\n    };\n\n    template<class Float, size_t I, class TIE> struct FinalUnroll\n    {\n      TIE& tie;\n      FinalUnroll(TIE& tie_):tie(tie_){}\n      \n      template<size_t K, class A, class D> inline void compute(A& a, const Float& b, const Float& c, const D& d) const\n      {\n      \tstatic_assert( K==0, \"K==0\" );\n      \tstd::get<K,I>(a) = ( b - c ) * d;\n        //a(K,I) = ( b - c ) * d;\n      }\n\n      template<size_t K, class A, class B, class C, class D> inline void compute(A& a, const B& b, const C& c, const D& d) const\n      {\n\t       //a(K,I) = ( std::get<K>(b) - std::get<K>(c) ) * d;\n         std::get<K,I>(a) = ( std::get<K>(b) - std::get<K>(c) ) * d;\n      }\n      \n      template<size_t K> inline void operator()(Int<K> const &) const\n      {\n\t       compute<K>(bf::at_c<0>(tie),bf::at_c<1>(tie),bf::at_c<2>(tie),bf::at_c<3>(tie));\n      }\n    };\n\n    template<class Float, std::size_t K, size_t I, std::size_t Fin> struct TupleDerivatorInternal\n    {\n      // forward derivative\n      template<class Fonction, class Result, class Tuple, class R> static void compute(const Fonction& fonction, Result& result, Tuple& tuple, const R& r1)\n      {\n        static const Float h = Float(2.0)*std::sqrt( std::numeric_limits<Float>::epsilon() );\n        static const Float _h = Float(1.0) / h ;\n        //! to_ref : on crée une référence vers l'objet contenu dans le tuple (uniquement pour simplifier l'écriture)\n        //! -> to_ref renvoie T& que l'objet contenu soit T ou T*\n        //! at -> renvoie at_c<I>(tuple) ou at_c<I>(map).second\n\n        auto& ref_objet = ttt::to_ref(bf::at_c<K>(tuple));\n        auto& jacob = bf::at_c<K>(result).second;\n\n        BOOST_MPL_ASSERT((boost::is_reference<decltype(ref_objet)>));\n        assert( (&ref_objet == &ttt::to_ref(bf::at_c<K>(tuple))) );\n\n        auto backup = back_up<I>(ref_objet);\n        detail::internal_apply_small_increment(ref_objet,h,v::numeric_tag<I>());\n        typedef typename Fonction::ErreurType Residu;\n        Residu r2;\n        bool b2 = fonction(tuple,r2);\n        backup.restore();\n\n        if(b2) // functor evaluation didn't failed\n        {\n          auto tie = bf::vector_tie(jacob,r2,r1,_h);\n          ttt::unroll<0,Size<R>::value>(FinalUnroll<Float,I,decltype(tie)>(tie));\n          TupleDerivatorInternal<Float,K,I+1,Fin>::template compute(fonction,result,tuple,r1);\n          return;\n        }\n\n        set_zero(jacob);\n      }\n      \n      // central derivative\n      template<class Fonction, class Result, class Tuple> static void compute(const Fonction& fonction, Result& result, Tuple& tuple)\n      {\n        static const Float h = Float(2.0)*std::sqrt( std::numeric_limits<Float>::epsilon() );\n        static const Float _h = Float(1.0) / (2.0*h) ;\n        //! to_ref : on crée une référence vers l'objet contenu dans le tuple (uniquement pour simplifier l'écriture)\n        //! -> to_ref renvoie T& que l'objet contenu soit T ou T*\n        //! at -> renvoie at_c<I>(tuple) ou at_c<I>(map).second\n\n        auto& ref_objet = ttt::to_ref(bf::at_c<K>(tuple));\n        auto& jacob = bf::at_c<K>(result).second;\n\n        BOOST_MPL_ASSERT((boost::is_reference<decltype(ref_objet)>));\n        assert( (&ref_objet == &ttt::to_ref(bf::at_c<K>(tuple))) );\n\n        typedef typename Fonction::ErreurType Residu;\n        Residu r2;\n        \n        auto backup = back_up<I>(ref_objet);\n        detail::internal_apply_small_increment(ref_objet,h,v::numeric_tag<I>());\n        bool b2 = fonction(tuple,r2);\n        backup.restore();\n        if (b2)\n        {\n          detail::internal_apply_small_increment(ref_objet,-h,v::numeric_tag<I>());\n          Residu r1;\n          bool b1 = fonction(tuple,r1);\n          backup.restore();\n          \n          if(b1)\n          {\n            auto tie = bf::vector_tie(jacob,r2,r1,_h);\n            ttt::unroll<0,Size<Residu>::value>(FinalUnroll<Float,I,decltype(tie)>(tie));\n            TupleDerivatorInternal<Float,K,I+1,Fin>::template compute(fonction,result,tuple);\n            return;\n          }\n        }\n        set_zero(jacob);\n      }\n    };\n\n    template<class Float, std::size_t I, std::size_t Fin> struct TupleDerivator\n    {\n      // numerical central derivative\n      template<class Fonction, class Result, class Tuple> static void compute(const Fonction& fonction, Result& result, Tuple& tuple)\n      {\n        static const size_t F = Size<decltype(ttt::to_ref(bf::at_c<I>(tuple)))>::value;\n        TupleDerivatorInternal<Float,I,0,F>::template compute(fonction,result,tuple);\n        TupleDerivator<Float,I+1,Fin>::template compute(fonction,result,tuple);\n      }\n\n      // numerical foward derivative\n      template<class Fonction, class Result, class Tuple, class R1> static void compute(const Fonction& fonction, Result& result, Tuple& tuple, const R1& r1)\n      {\n        static const size_t F = Size<decltype(ttt::to_ref(bf::at_c<I>(tuple)))>::value;\n        TupleDerivatorInternal<Float,I,0,F>::template compute(fonction,result,tuple,r1);\n        TupleDerivator<Float,I+1,Fin>::template compute(fonction,result,tuple,r1);\n      }\n    };\n  }// eon detail\n\n\n  template<class Tag> struct NumericalDerivator\n  {\n    //! le tuple en entrée ne doit pas être constant car il sera modifié, et remis à l'état d'origine\n    template<class Fonctor, class Tuple, class Jacob>\n    static void derive(const Function<Fonctor>& fonctor, Tuple tuple, Jacob& result)\n    {\n      detail::TupleDerivator<typename Tag::second_type, 0,br::size<Jacob>::value>::template compute(fonctor,result,tuple);\n    }\n\n    template<class Fonctor, class Tuple, class Jacob, class Residual>\n    static void derive(const Function<Fonctor>& fonctor, Tuple tuple, Jacob& result, const Residual& residual)\n    {\n      detail::TupleDerivator<typename Tag::second_type, 0,br::size<Jacob>::value>::template compute(fonctor,result,tuple,residual);\n    }\n  };\n\n}// eon\n\nnamespace ttt\n{\n  template<class T> struct Name<lma::NumericalDerivator<T>> { static std::string name(){ return \"NumericalDerivator<\" + ttt::name<T>() + \">\"; } };\n}\n\n#endif\n\n", "meta": {"hexsha": "22f29ccfc4b2a50a610bd70b9358538bd0d86041", "size": 7866, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/libv/lma/lm/function/derivative/numerical_derivative.hpp", "max_stars_repo_name": "bezout/LMA", "max_stars_repo_head_hexsha": "9555e41eed5f44690c5f6e3ea2d22d520ff1a9d2", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 29.0, "max_stars_repo_stars_event_min_datetime": "2015-12-08T12:07:30.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-08T21:23:01.000Z", "max_issues_repo_path": "src/libv/lma/lm/function/derivative/numerical_derivative.hpp", "max_issues_repo_name": "ayumizll/LMA", "max_issues_repo_head_hexsha": "e945452e12a8b05bd17400b46a20a5322aeda01d", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2016-07-11T16:23:48.000Z", "max_issues_repo_issues_event_max_datetime": "2017-04-05T13:33:00.000Z", "max_forks_repo_path": "src/libv/lma/lm/function/derivative/numerical_derivative.hpp", "max_forks_repo_name": "bezout/LMA", "max_forks_repo_head_hexsha": "9555e41eed5f44690c5f6e3ea2d22d520ff1a9d2", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2015-12-21T01:52:27.000Z", "max_forks_repo_forks_event_max_datetime": "2017-12-26T02:26:55.000Z", "avg_line_length": 40.7564766839, "max_line_length": 157, "alphanum_fraction": 0.6244597, "num_tokens": 2110, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6334102775181399, "lm_q2_score": 0.5506073655352404, "lm_q1q2_score": 0.3487603642072085}}
{"text": "/* Author: Luca Heltai, Cataldo Manigrasso, 2009                  */\n\n/*    $Id: step-34.cc 28376 2013-02-13 15:19:38Z heister $       */\n/*                                                                */\n/*    Copyright (C) 2009-2012 by deal.II authors */\n/*                                                                */\n/*    This file is subject to QPL and may not be  distributed     */\n/*    without copyright and license information. Please refer     */\n/*    to the file deal.II/doc/license.html for the  text  and     */\n/*    further information on this license.                        */\n\n// @sect3{Include files}\n\n// The program starts with including a bunch of include files that we will use\n// in the various parts of the program. Most of them have been discussed in\n// previous tutorials already:\n#include <deal.II/base/smartpointer.h>\n#include <deal.II/base/convergence_table.h>\n#include <deal.II/base/quadrature_lib.h>\n#include <deal.II/base/quadrature_selector.h>\n#include <deal.II/base/parsed_function.h>\n#include <deal.II/base/utilities.h>\n\n#include <deal.II/lac/full_matrix.h>\n#include <deal.II/lac/vector.h>\n#include <deal.II/lac/solver_control.h>\n#include <deal.II/lac/solver_gmres.h>\n#include <deal.II/lac/precondition.h>\n\n#include <deal.II/grid/tria.h>\n#include <deal.II/grid/tria_iterator.h>\n#include <deal.II/grid/tria_accessor.h>\n#include <deal.II/grid/grid_generator.h>\n#include <deal.II/grid/grid_in.h>\n#include <deal.II/grid/grid_out.h>\n#include <deal.II/grid/tria_boundary_lib.h>\n\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\n#include <deal.II/fe/fe_q.h>\n#include <deal.II/fe/fe_values.h>\n#include <deal.II/fe/mapping_q.h>\n\n#include <deal.II/numerics/data_out.h>\n#include <deal.II/numerics/vector_tools.h>\n\n// And here are a few C++ standard header files that we will need:\n#include <cmath>\n#include <iostream>\n#include <fstream>\n#include <string>\n\n// The last part of this preamble is to import everything in the dealii\n// namespace into the one into which everything in this program will go:\nnamespace Step34\n{\n  using namespace dealii;\n\n\n  // @sect3{Single and double layer operator kernels}\n\n  // First, let us define a bit of the boundary integral equation machinery.\n\n  // The following two functions are the actual calculations of the single and\n  // double layer potential kernels, that is $G$ and $\\nabla G$. They are well\n  // defined only if the vector $R = \\mathbf{y}-\\mathbf{x}$ is different from\n  // zero.\n  namespace LaplaceKernel\n  {\n    template <int dim>\n    double single_layer(const Point<dim> &R)\n    {\n      switch (dim)\n        {\n        case 2:\n          return (-std::log(R.norm()) / (2*numbers::PI) );\n\n        case 3:\n          return (1./( R.norm()*4*numbers::PI ) );\n\n        default:\n          Assert(false, ExcInternalError());\n          return 0.;\n        }\n    }\n\n\n\n    template <int dim>\n    Point<dim> double_layer(const Point<dim> &R)\n    {\n      switch (dim)\n        {\n        case 2:\n          return R / ( -2*numbers::PI * R.square());\n        case 3:\n          return R / ( -4*numbers::PI * R.square() * R.norm() );\n\n        default:\n          Assert(false, ExcInternalError());\n          return Point<dim>();\n        }\n    }\n  }\n\n\n  // @sect3{The BEMProblem class}\n\n  // The structure of a boundary element method code is very similar to the\n  // structure of a finite element code, and so the member functions of this\n  // class are like those of most of the other tutorial programs. In\n  // particular, by now you should be familiar with reading parameters from an\n  // external file, and with the splitting of the different tasks into\n  // different modules. The same applies to boundary element methods, and we\n  // won't comment too much on them, except on the differences.\n  template <int dim>\n  class BEMProblem\n  {\n  public:\n    BEMProblem(const unsigned int fe_degree = 1,\n               const unsigned int mapping_degree = 1);\n\n    void run();\n\n  private:\n\n    void read_parameters (const std::string &filename);\n\n    void read_domain();\n\n    void refine_and_resize();\n\n    // The only really different function that we find here is the assembly\n    // routine. We wrote this function in the most possible general way, in\n    // order to allow for easy generalization to higher order methods and to\n    // different fundamental solutions (e.g., Stokes or Maxwell).\n    //\n    // The most noticeable difference is the fact that the final matrix is\n    // full, and that we have a nested loop inside the usual loop on cells\n    // that visits all support points of the degrees of freedom.  Moreover,\n    // when the support point lies inside the cell which we are visiting, then\n    // the integral we perform becomes singular.\n    //\n    // The practical consequence is that we have two sets of quadrature\n    // formulas, finite element values and temporary storage, one for standard\n    // integration and one for the singular integration, which are used where\n    // necessary.\n    void assemble_system();\n\n    // There are two options for the solution of this problem. The first is to\n    // use a direct solver, and the second is to use an iterative solver. We\n    // opt for the second option.\n    //\n    // The matrix that we assemble is not symmetric, and we opt to use the\n    // GMRES method; however the construction of an efficient preconditioner\n    // for boundary element methods is not a trivial issue. Here we use a non\n    // preconditioned GMRES solver. The options for the iterative solver, such\n    // as the tolerance, the maximum number of iterations, are selected\n    // through the parameter file.\n    void solve_system();\n\n    // Once we obtained the solution, we compute the $L^2$ error of the\n    // computed potential as well as the $L^\\infty$ error of the approximation\n    // of the solid angle. The mesh we are using is an approximation of a\n    // smooth curve, therefore the computed diagonal matrix of fraction of\n    // angles or solid angles $\\alpha(\\mathbf{x})$ should be constantly equal\n    // to $\\frac 12$. In this routine we output the error on the potential and\n    // the error in the approximation of the computed angle. Notice that the\n    // latter error is actually not the error in the computation of the angle,\n    // but a measure of how well we are approximating the sphere and the\n    // circle.\n    //\n    // Experimenting a little with the computation of the angles gives very\n    // accurate results for simpler geometries. To verify this you can comment\n    // out, in the read_domain() method, the tria.set_boundary(1, boundary)\n    // line, and check the alpha that is generated by the program. By removing\n    // this call, whenever the mesh is refined new nodes will be placed along\n    // the straight lines that made up the coarse mesh, rather than be pulled\n    // onto the surface that we really want to approximate. In the three\n    // dimensional case, the coarse grid of the sphere is obtained starting\n    // from a cube, and the obtained values of alphas are exactly $\\frac 12$\n    // on the nodes of the faces, $\\frac 34$ on the nodes of the edges and\n    // $\\frac 78$ on the 8 nodes of the vertices.\n    void compute_errors(const unsigned int cycle);\n\n    // Once we obtained a solution on the codimension one domain, we want to\n    // interpolate it to the rest of the space. This is done by performing\n    // again the convolution of the solution with the kernel in the\n    // compute_exterior_solution() function.\n    //\n    // We would like to plot the velocity variable which is the gradient of\n    // the potential solution. The potential solution is only known on the\n    // boundary, but we use the convolution with the fundamental solution to\n    // interpolate it on a standard dim dimensional continuous finite element\n    // space. The plot of the gradient of the extrapolated solution will give\n    // us the velocity we want.\n    //\n    // In addition to the solution on the exterior domain, we also output the\n    // solution on the domain's boundary in the output_results() function, of\n    // course.\n    void compute_exterior_solution();\n\n    void output_results(const unsigned int cycle);\n\n    // To allow for dimension independent programming, we specialize this\n    // single function to extract the singular quadrature formula needed to\n    // integrate the singular kernels in the interior of the cells.\n    const Quadrature<dim-1> & get_singular_quadrature(\n      const typename DoFHandler<dim-1, dim>::active_cell_iterator &cell,\n      const unsigned int index) const;\n\n\n    // The usual deal.II classes can be used for boundary element methods by\n    // specifying the \"codimension\" of the problem. This is done by setting\n    // the optional second template arguments to Triangulation, FiniteElement\n    // and DoFHandler to the dimension of the embedding space. In our case we\n    // generate either 1 or 2 dimensional meshes embedded in 2 or 3\n    // dimensional spaces.\n    //\n    // The optional argument by default is equal to the first argument, and\n    // produces the usual finite element classes that we saw in all previous\n    // examples.\n    //\n    // The class is constructed in a way to allow for arbitrary order of\n    // approximation of both the domain (through high order mapping) and the\n    // finite element space. The order of the finite element space and of the\n    // mapping can be selected in the constructor of the class.\n\n    Triangulation<dim-1, dim>   tria;\n    FE_Q<dim-1,dim>             fe;\n    DoFHandler<dim-1,dim>       dh;\n    MappingQ<dim-1, dim>      mapping;\n\n    // In BEM methods, the matrix that is generated is dense. Depending on the\n    // size of the problem, the final system might be solved by direct LU\n    // decomposition, or by iterative methods. In this example we use an\n    // unpreconditioned GMRES method. Building a preconditioner for BEM method\n    // is non trivial, and we don't treat this subject here.\n\n    FullMatrix<double>    system_matrix;\n    Vector<double>        system_rhs;\n\n    // The next two variables will denote the solution $\\phi$ as well as a\n    // vector that will hold the values of $\\alpha(\\mathbf x)$ (the fraction\n    // of $\\Omega$ visible from a point $\\mathbf x$) at the support points of\n    // our shape functions.\n\n    Vector<double>              phi;\n    Vector<double>              alpha;\n\n    // The convergence table is used to output errors in the exact solution\n    // and in the computed alphas.\n\n    ConvergenceTable  convergence_table;\n\n    // The following variables are the ones that we fill through a parameter\n    // file.  The new objects that we use in this example are the\n    // Functions::ParsedFunction object and the QuadratureSelector object.\n    //\n    // The Functions::ParsedFunction class allows us to easily and quickly\n    // define new function objects via parameter files, with custom\n    // definitions which can be very complex (see the documentation of that\n    // class for all the available options).\n    //\n    // We will allocate the quadrature object using the QuadratureSelector\n    // class that allows us to generate quadrature formulas based on an\n    // identifying string and on the possible degree of the formula itself. We\n    // used this to allow custom selection of the quadrature formulas for the\n    // standard integration, and to define the order of the singular\n    // quadrature rule.\n    //\n    // We also define a couple of parameters which are used in case we wanted\n    // to extend the solution to the entire domain.\n\n    Functions::ParsedFunction<dim> wind;\n    Functions::ParsedFunction<dim> exact_solution;\n\n    unsigned int singular_quadrature_order;\n    std_cxx1x::shared_ptr<Quadrature<dim-1> > quadrature;\n\n    SolverControl solver_control;\n\n    unsigned int n_cycles;\n    unsigned int external_refinement;\n\n    bool run_in_this_dimension;\n    bool extend_solution;\n  };\n\n\n  // @sect4{BEMProblem::BEMProblem and BEMProblem::read_parameters}\n\n  // The constructor initializes the variuous object in much the same way as\n  // done in the finite element programs such as step-4 or step-6. The only\n  // new ingredient here is the ParsedFunction object, which needs, at\n  // construction time, the specification of the number of components.\n  //\n  // For the exact solution the number of vector components is one, and no\n  // action is required since one is the default value for a ParsedFunction\n  // object. The wind, however, requires dim components to be\n  // specified. Notice that when declaring entries in a parameter file for the\n  // expression of the Functions::ParsedFunction, we need to specify the\n  // number of components explicitly, since the function\n  // Functions::ParsedFunction::declare_parameters is static, and has no\n  // knowledge of the number of components.\n  template <int dim>\n  BEMProblem<dim>::BEMProblem(const unsigned int fe_degree,\n                              const unsigned int mapping_degree)\n    :\n    fe(fe_degree),\n    dh(tria),\n    mapping(mapping_degree, true),\n    wind(dim)\n  {}\n\n\n  template <int dim>\n  void BEMProblem<dim>::read_parameters (const std::string &filename)\n  {\n    deallog << std::endl << \"Parsing parameter file \" << filename << std::endl\n            << \"for a \" << dim << \" dimensional simulation. \" << std::endl;\n\n    ParameterHandler prm;\n\n    prm.declare_entry(\"Number of cycles\", \"4\",\n                      Patterns::Integer());\n    prm.declare_entry(\"External refinement\", \"5\",\n                      Patterns::Integer());\n    prm.declare_entry(\"Extend solution on the -2,2 box\", \"true\",\n                      Patterns::Bool());\n    prm.declare_entry(\"Run 2d simulation\", \"true\",\n                      Patterns::Bool());\n    prm.declare_entry(\"Run 3d simulation\", \"true\",\n                      Patterns::Bool());\n\n    prm.enter_subsection(\"Quadrature rules\");\n    {\n      prm.declare_entry(\"Quadrature type\", \"gauss\",\n                        Patterns::Selection(QuadratureSelector<(dim-1)>::get_quadrature_names()));\n      prm.declare_entry(\"Quadrature order\", \"4\", Patterns::Integer());\n      prm.declare_entry(\"Singular quadrature order\", \"5\", Patterns::Integer());\n    }\n    prm.leave_subsection();\n\n    // For both two and three dimensions, we set the default input data to be\n    // such that the solution is $x+y$ or $x+y+z$. The actually computed\n    // solution will have value zero at infinity. In this case, this coincide\n    // with the exact solution, and no additional corrections are needed, but\n    // you should be aware of the fact that we arbitrarily set $\\phi_\\infty$,\n    // and the exact solution we pass to the program needs to have the same\n    // value at infinity for the error to be computed correctly.\n    //\n    // The use of the Functions::ParsedFunction object is pretty straight\n    // forward. The Functions::ParsedFunction::declare_parameters function\n    // takes an additional integer argument that specifies the number of\n    // components of the given function. Its default value is one. When the\n    // corresponding Functions::ParsedFunction::parse_parameters method is\n    // called, the calling object has to have the same number of components\n    // defined here, otherwise an exception is thrown.\n    //\n    // When declaring entries, we declare both 2 and three dimensional\n    // functions. However only the dim-dimensional one is ultimately\n    // parsed. This allows us to have only one parameter file for both 2 and 3\n    // dimensional problems.\n    //\n    // Notice that from a mathematical point of view, the wind function on the\n    // boundary should satisfy the condition $\\int_{\\partial\\Omega}\n    // \\mathbf{v}\\cdot \\mathbf{n} d \\Gamma = 0$, for the problem to have a\n    // solution. If this condition is not satisfied, then no solution can be\n    // found, and the solver will not converge.\n    prm.enter_subsection(\"Wind function 2d\");\n    {\n      Functions::ParsedFunction<2>::declare_parameters(prm, 2);\n      prm.set(\"Function expression\", \"1; 1\");\n    }\n    prm.leave_subsection();\n\n    prm.enter_subsection(\"Wind function 3d\");\n    {\n      Functions::ParsedFunction<3>::declare_parameters(prm, 3);\n      prm.set(\"Function expression\", \"1; 1; 1\");\n    }\n    prm.leave_subsection();\n\n    prm.enter_subsection(\"Exact solution 2d\");\n    {\n      Functions::ParsedFunction<2>::declare_parameters(prm);\n      prm.set(\"Function expression\", \"x+y\");\n    }\n    prm.leave_subsection();\n\n    prm.enter_subsection(\"Exact solution 3d\");\n    {\n      Functions::ParsedFunction<3>::declare_parameters(prm);\n      prm.set(\"Function expression\", \"x+y+z\");\n    }\n    prm.leave_subsection();\n\n\n    // In the solver section, we set all SolverControl parameters. The object\n    // will then be fed to the GMRES solver in the solve_system() function.\n    prm.enter_subsection(\"Solver\");\n    SolverControl::declare_parameters(prm);\n    prm.leave_subsection();\n\n    // After declaring all these parameters to the ParameterHandler object,\n    // let's read an input file that will give the parameters their values. We\n    // then proceed to extract these values from the ParameterHandler object:\n    prm.read_input(filename);\n\n    n_cycles = prm.get_integer(\"Number of cycles\");\n    external_refinement = prm.get_integer(\"External refinement\");\n    extend_solution = prm.get_bool(\"Extend solution on the -2,2 box\");\n\n    prm.enter_subsection(\"Quadrature rules\");\n    {\n      quadrature =\n        std_cxx1x::shared_ptr<Quadrature<dim-1> >\n        (new QuadratureSelector<dim-1> (prm.get(\"Quadrature type\"),\n                                        prm.get_integer(\"Quadrature order\")));\n      singular_quadrature_order = prm.get_integer(\"Singular quadrature order\");\n    }\n    prm.leave_subsection();\n\n    prm.enter_subsection(std::string(\"Wind function \")+\n                         Utilities::int_to_string(dim)+std::string(\"d\"));\n    {\n      wind.parse_parameters(prm);\n    }\n    prm.leave_subsection();\n\n    prm.enter_subsection(std::string(\"Exact solution \")+\n                         Utilities::int_to_string(dim)+std::string(\"d\"));\n    {\n      exact_solution.parse_parameters(prm);\n    }\n    prm.leave_subsection();\n\n    prm.enter_subsection(\"Solver\");\n    solver_control.parse_parameters(prm);\n    prm.leave_subsection();\n\n\n    // Finally, here's another example of how to use parameter files in\n    // dimension independent programming.  If we wanted to switch off one of\n    // the two simulations, we could do this by setting the corresponding \"Run\n    // 2d simulation\" or \"Run 3d simulation\" flag to false:\n    run_in_this_dimension = prm.get_bool(\"Run \" +\n                                         Utilities::int_to_string(dim) +\n                                         \"d simulation\");\n  }\n\n\n  // @sect4{BEMProblem::read_domain}\n\n  // A boundary element method triangulation is basically the same as a\n  // (dim-1) dimensional triangulation, with the difference that the vertices\n  // belong to a (dim) dimensional space.\n  //\n  // Some of the mesh formats supported in deal.II use by default three\n  // dimensional points to describe meshes. These are the formats which are\n  // compatible with the boundary element method capabilities of deal.II. In\n  // particular we can use either UCD or GMSH formats. In both cases, we have\n  // to be particularly careful with the orientation of the mesh, because,\n  // unlike in the standard finite element case, no reordering or\n  // compatibility check is performed here.  All meshes are considered as\n  // oriented, because they are embedded in a higher dimensional space. (See\n  // the documentation of the GridIn and of the Triangulation for further\n  // details on orientation of cells in a triangulation.) In our case, the\n  // normals to the mesh are external to both the circle in 2d or the sphere\n  // in 3d.\n  //\n  // The other detail that is required for appropriate refinement of the\n  // boundary element mesh, is an accurate description of the manifold that\n  // the mesh is approximating. We already saw this several times for the\n  // boundary of standard finite element meshes (for example in step-5 and\n  // step-6), and here the principle and usage is the same, except that the\n  // HyperBallBoundary class takes an additional template parameter that\n  // specifies the embedding space dimension. The function object still has to\n  // be static to live at least as long as the triangulation object to which\n  // it is attached.\n\n  template <int dim>\n  void BEMProblem<dim>::read_domain()\n  {\n    static const Point<dim> center = Point<dim>();\n    static const HyperBallBoundary<dim-1, dim> boundary(center,1.);\n\n    std::ifstream in;\n    switch (dim)\n      {\n      case 2:\n        in.open (\"coarse_circle.inp\");\n        break;\n\n      case 3:\n        in.open (\"coarse_sphere.inp\");\n        break;\n\n      default:\n        Assert (false, ExcNotImplemented());\n      }\n\n    GridIn<dim-1, dim> gi;\n    gi.attach_triangulation (tria);\n    gi.read_ucd (in);\n\n    tria.set_boundary(1, boundary);\n  }\n\n\n  // @sect4{BEMProblem::refine_and_resize}\n\n  // This function globally refines the mesh, distributes degrees of freedom,\n  // and resizes matrices and vectors.\n\n  template <int dim>\n  void BEMProblem<dim>::refine_and_resize()\n  {\n    tria.refine_global(1);\n\n    dh.distribute_dofs(fe);\n\n    const unsigned int n_dofs =  dh.n_dofs();\n\n    system_matrix.reinit(n_dofs, n_dofs);\n\n    system_rhs.reinit(n_dofs);\n    phi.reinit(n_dofs);\n    alpha.reinit(n_dofs);\n  }\n\n\n  // @sect4{BEMProblem::assemble_system}\n\n  // The following is the main function of this program, assembling the matrix\n  // that corresponds to the boundary integral equation.\n  template <int dim>\n  void BEMProblem<dim>::assemble_system()\n  {\n\n    // First we initialize an FEValues object with the quadrature formula for\n    // the integration of the kernel in non singular cells. This quadrature is\n    // selected with the parameter file, and needs to be quite precise, since\n    // the functions we are integrating are not polynomial functions.\n    FEValues<dim-1,dim> fe_v(mapping, fe, *quadrature,\n                             update_values |\n                             update_cell_normal_vectors |\n                             update_quadrature_points |\n                             update_JxW_values);\n\n    const unsigned int n_q_points = fe_v.n_quadrature_points;\n\n    std::vector<unsigned int> local_dof_indices(fe.dofs_per_cell);\n\n    std::vector<Vector<double> > cell_wind(n_q_points, Vector<double>(dim) );\n    double normal_wind;\n\n    // Unlike in finite element methods, if we use a collocation boundary\n    // element method, then in each assembly loop we only assemble the\n    // information that refers to the coupling between one degree of freedom\n    // (the degree associated with support point $i$) and the current\n    // cell. This is done using a vector of fe.dofs_per_cell elements, which\n    // will then be distributed to the matrix in the global row $i$. The\n    // following object will hold this information:\n    Vector<double>      local_matrix_row_i(fe.dofs_per_cell);\n\n    // The index $i$ runs on the collocation points, which are the support\n    // points of the $i$th basis function, while $j$ runs on inner integration\n    // points.\n\n    // We construct a vector of support points which will be used in the local\n    // integrations:\n    std::vector<Point<dim> > support_points(dh.n_dofs());\n    DoFTools::map_dofs_to_support_points<dim-1, dim>( mapping, dh, support_points);\n\n\n    // After doing so, we can start the integration loop over all cells, where\n    // we first initialize the FEValues object and get the values of\n    // $\\mathbf{\\tilde v}$ at the quadrature points (this vector field should\n    // be constant, but it doesn't hurt to be more general):\n    typename DoFHandler<dim-1,dim>::active_cell_iterator\n    cell = dh.begin_active(),\n    endc = dh.end();\n\n    for (cell = dh.begin_active(); cell != endc; ++cell)\n      {\n        fe_v.reinit(cell);\n        cell->get_dof_indices(local_dof_indices);\n\n        const std::vector<Point<dim> > &q_points = fe_v.get_quadrature_points();\n        const std::vector<Point<dim> > &normals = fe_v.get_normal_vectors();\n        wind.vector_value_list(q_points, cell_wind);\n\n        // We then form the integral over the current cell for all degrees of\n        // freedom (note that this includes degrees of freedom not located on\n        // the current cell, a deviation from the usual finite element\n        // integrals). The integral that we need to perform is singular if one\n        // of the local degrees of freedom is the same as the support point\n        // $i$. A the beginning of the loop we therefore check wether this is\n        // the case, and we store which one is the singular index:\n        for (unsigned int i=0; i<dh.n_dofs() ; ++i)\n          {\n\n            local_matrix_row_i = 0;\n\n            bool is_singular = false;\n            unsigned int singular_index = numbers::invalid_unsigned_int;\n\n            for (unsigned int j=0; j<fe.dofs_per_cell; ++j)\n              if (local_dof_indices[j] == i)\n                {\n                  singular_index = j;\n                  is_singular = true;\n                  break;\n                }\n\n            // We then perform the integral. If the index $i$ is not one of\n            // the local degrees of freedom, we simply have to add the single\n            // layer terms to the right hand side, and the double layer terms\n            // to the matrix:\n            if (is_singular == false)\n              {\n                for (unsigned int q=0; q<n_q_points; ++q)\n                  {\n                    normal_wind = 0;\n                    for (unsigned int d=0; d<dim; ++d)\n                      normal_wind += normals[q][d]*cell_wind[q](d);\n\n                    const Point<dim> R = q_points[q] - support_points[i];\n\n                    system_rhs(i) += ( LaplaceKernel::single_layer(R)   *\n                                       normal_wind                      *\n                                       fe_v.JxW(q) );\n\n                    for (unsigned int j=0; j<fe.dofs_per_cell; ++j)\n\n                      local_matrix_row_i(j) -= ( ( LaplaceKernel::double_layer(R)     *\n                                                   normals[q] )            *\n                                                 fe_v.shape_value(j,q)     *\n                                                 fe_v.JxW(q)       );\n                  }\n              }\n            else\n              {\n                // Now we treat the more delicate case. If we are here, this\n                // means that the cell that runs on the $j$ index contains\n                // support_point[i]. In this case both the single and the\n                // double layer potential are singular, and they require\n                // special treatment.\n                //\n                // Whenever the integration is performed with the singularity\n                // inside the given cell, then a special quadrature formula is\n                // used that allows one to integrate arbitrary functions\n                // against a singular weight on the reference cell.\n                //\n                // The correct quadrature formula is selected by the\n                // get_singular_quadrature function, which is explained in\n                // detail below.\n                Assert(singular_index != numbers::invalid_unsigned_int,\n                       ExcInternalError());\n\n                const Quadrature<dim-1> & singular_quadrature =\n                  get_singular_quadrature(cell, singular_index);\n\n                FEValues<dim-1,dim> fe_v_singular (mapping, fe, singular_quadrature,\n                                                   update_jacobians |\n                                                   update_values |\n                                                   update_cell_normal_vectors |\n                                                   update_quadrature_points );\n\n                fe_v_singular.reinit(cell);\n\n                std::vector<Vector<double> > singular_cell_wind( singular_quadrature.size(),\n                                                                 Vector<double>(dim) );\n\n                const std::vector<Point<dim> > &singular_normals = fe_v_singular.get_normal_vectors();\n                const std::vector<Point<dim> > &singular_q_points = fe_v_singular.get_quadrature_points();\n\n                wind.vector_value_list(singular_q_points, singular_cell_wind);\n\n                for (unsigned int q=0; q<singular_quadrature.size(); ++q)\n                  {\n                    const Point<dim> R = singular_q_points[q] - support_points[i];\n                    double normal_wind = 0;\n                    for (unsigned int d=0; d<dim; ++d)\n                      normal_wind += (singular_cell_wind[q](d)*\n                                      singular_normals[q][d]);\n\n                    system_rhs(i) += ( LaplaceKernel::single_layer(R) *\n                                       normal_wind                         *\n                                       fe_v_singular.JxW(q) );\n\n                    for (unsigned int j=0; j<fe.dofs_per_cell; ++j)\n                      {\n                        local_matrix_row_i(j) -= (( LaplaceKernel::double_layer(R) *\n                                                    singular_normals[q])                *\n                                                  fe_v_singular.shape_value(j,q)        *\n                                                  fe_v_singular.JxW(q)       );\n                      }\n                  }\n              }\n\n            // Finally, we need to add the contributions of the current cell\n            // to the global matrix.\n            for (unsigned int j=0; j<fe.dofs_per_cell; ++j)\n              system_matrix(i,local_dof_indices[j])\n              += local_matrix_row_i(j);\n          }\n      }\n\n    // The second part of the integral operator is the term\n    // $\\alpha(\\mathbf{x}_i) \\phi_j(\\mathbf{x}_i)$. Since we use a collocation\n    // scheme, $\\phi_j(\\mathbf{x}_i)=\\delta_{ij}$ and the corresponding matrix\n    // is a diagonal one with entries equal to $\\alpha(\\mathbf{x}_i)$.\n\n    // One quick way to compute this diagonal matrix of the solid angles, is\n    // to use the Neumann matrix itself. It is enough to multiply the matrix\n    // with a vector of elements all equal to -1, to get the diagonal matrix\n    // of the alpha angles, or solid angles (see the formula in the\n    // introduction for this). The result is then added back onto the system\n    // matrix object to yield the final form of the matrix:\n    Vector<double> ones(dh.n_dofs());\n    ones.add(-1.);\n\n    system_matrix.vmult(alpha, ones);\n    alpha.add(1);\n    for (unsigned int i = 0; i<dh.n_dofs(); ++i)\n      system_matrix(i,i) +=  alpha(i);\n  }\n\n\n  // @sect4{BEMProblem::solve_system}\n\n  // The next function simply solves the linear system.\n  template <int dim>\n  void BEMProblem<dim>::solve_system()\n  {\n    SolverGMRES<Vector<double> > solver (solver_control);\n    solver.solve (system_matrix, phi, system_rhs, PreconditionIdentity());\n  }\n\n\n  // @sect4{BEMProblem::compute_errors}\n\n  // The computation of the errors is exactly the same in all other example\n  // programs, and we won't comment too much. Notice how the same methods that\n  // are used in the finite element methods can be used here.\n  template <int dim>\n  void BEMProblem<dim>::compute_errors(const unsigned int cycle)\n  {\n    Vector<float> difference_per_cell (tria.n_active_cells());\n    VectorTools::integrate_difference (mapping, dh, phi,\n                                       exact_solution,\n                                       difference_per_cell,\n                                       QGauss<(dim-1)>(2*fe.degree+1),\n                                       VectorTools::L2_norm);\n    const double L2_error = difference_per_cell.l2_norm();\n\n\n    // The error in the alpha vector can be computed directly using the\n    // Vector::linfty_norm() function, since on each node, the value should be\n    // $\\frac 12$. All errors are then output and appended to our\n    // ConvergenceTable object for later computation of convergence rates:\n    Vector<double> difference_per_node(alpha);\n    difference_per_node.add(-.5);\n\n    const double alpha_error = difference_per_node.linfty_norm();\n    const unsigned int n_active_cells=tria.n_active_cells();\n    const unsigned int n_dofs=dh.n_dofs();\n\n    deallog << \"Cycle \" << cycle << ':'\n            << std::endl\n            << \"   Number of active cells:       \"\n            << n_active_cells\n            << std::endl\n            << \"   Number of degrees of freedom: \"\n            << n_dofs\n            << std::endl;\n\n    convergence_table.add_value(\"cycle\", cycle);\n    convergence_table.add_value(\"cells\", n_active_cells);\n    convergence_table.add_value(\"dofs\", n_dofs);\n    convergence_table.add_value(\"L2(phi)\", L2_error);\n    convergence_table.add_value(\"Linfty(alpha)\", alpha_error);\n  }\n\n\n  // Singular integration requires a careful selection of the quadrature\n  // rules. In particular the deal.II library provides quadrature rules which\n  // are taylored for logarithmic singularities (QGaussLog, QGaussLogR), as\n  // well as for 1/R singularities (QGaussOneOverR).\n  //\n  // Singular integration is typically obtained by constructing weighted\n  // quadrature formulas with singular weights, so that it is possible to\n  // write\n  //\n  // \\f[ \\int_K f(x) s(x) dx = \\sum_{i=1}^N w_i f(q_i) \\f]\n  //\n  // where $s(x)$ is a given singularity, and the weights and quadrature\n  // points $w_i,q_i$ are carefully selected to make the formula above an\n  // equality for a certain class of functions $f(x)$.\n  //\n  // In all the finite element examples we have seen so far, the weight of the\n  // quadrature itself (namely, the function $s(x)$), was always constantly\n  // equal to 1.  For singular integration, we have two choices: we can use\n  // the definition above, factoring out the singularity from the integrand\n  // (i.e., integrating $f(x)$ with the special quadrature rule), or we can\n  // ask the quadrature rule to \"normalize\" the weights $w_i$ with $s(q_i)$:\n  //\n  // \\f[ \\int_K f(x) s(x) dx = \\int_K g(x) dx = \\sum_{i=1}^N\n  //   \\frac{w_i}{s(q_i)} g(q_i) \\f]\n  //\n  // We use this second option, through the @p factor_out_singularity\n  // parameter of both QGaussLogR and QGaussOneOverR.\n  //\n  // These integrals are somewhat delicate, especially in two dimensions, due\n  // to the transformation from the real to the reference cell, where the\n  // variable of integration is scaled with the determinant of the\n  // transformation.\n  //\n  // In two dimensions this process does not result only in a factor appearing\n  // as a constant factor on the entire integral, but also on an additional\n  // integral altogether that needs to be evaluated:\n  //\n  // \\f[ \\int_0^1 f(x)\\ln(x/\\alpha) dx = \\int_0^1 f(x)\\ln(x) dx - \\int_0^1\n  //  f(x) \\ln(\\alpha) dx.  \\f]\n  //\n  // This process is taken care of by the constructor of the QGaussLogR class,\n  // which adds additional quadrature points and weights to take into\n  // consideration also the second part of the integral.\n  //\n  // A similar reasoning should be done in the three dimensional case, since\n  // the singular quadrature is taylored on the inverse of the radius $r$ in\n  // the reference cell, while our singular function lives in real space,\n  // however in the three dimensional case everything is simpler because the\n  // singularity scales linearly with the determinant of the\n  // transformation. This allows us to build the singular two dimensional\n  // quadrature rules only once and, reuse them over all cells.\n  //\n  // In the one dimensional singular integration this is not possible, since\n  // we need to know the scaling parameter for the quadrature, which is not\n  // known a priori. Here, the quadrature rule itself depends also on the size\n  // of the current cell. For this reason, it is necessary to create a new\n  // quadrature for each singular integration.\n  //\n  // The different quadrature rules are built inside the\n  // get_singular_quadrature, which is specialized for dim=2 and dim=3, and\n  // they are retrieved inside the assemble_system function. The index given\n  // as an argument is the index of the unit support point where the\n  // singularity is located.\n\n  template<>\n  const Quadrature<2> &BEMProblem<3>::get_singular_quadrature(\n    const DoFHandler<2,3>::active_cell_iterator &,\n    const unsigned int index) const\n  {\n    Assert(index < fe.dofs_per_cell,\n           ExcIndexRange(0, fe.dofs_per_cell, index));\n\n    static std::vector<QGaussOneOverR<2> > quadratures;\n    if (quadratures.size() == 0)\n      for (unsigned int i=0; i<fe.dofs_per_cell; ++i)\n        quadratures.push_back(QGaussOneOverR<2>(singular_quadrature_order,\n                                                fe.get_unit_support_points()[i],\n                                                true));\n    return quadratures[index];\n  }\n\n\n  template<>\n  const Quadrature<1> &BEMProblem<2>::get_singular_quadrature(\n    const DoFHandler<1,2>::active_cell_iterator &cell,\n    const unsigned int index) const\n  {\n    Assert(index < fe.dofs_per_cell,\n           ExcIndexRange(0, fe.dofs_per_cell, index));\n\n    static Quadrature<1> *q_pointer = NULL;\n    if (q_pointer) delete q_pointer;\n\n    q_pointer = new QGaussLogR<1>(singular_quadrature_order,\n                                  fe.get_unit_support_points()[index],\n                                  1./cell->measure(), true);\n    return (*q_pointer);\n  }\n\n\n\n  // @sect4{BEMProblem::compute_exterior_solution}\n\n  // We'd like to also know something about the value of the potential $\\phi$\n  // in the exterior domain: after all our motivation to consider the boundary\n  // integral problem was that we wanted to know the velocity in the exterior\n  // domain!\n  //\n  // To this end, let us assume here that the boundary element domain is\n  // contained in the box $[-2,2]^{\\text{dim}}$, and we extrapolate the actual\n  // solution inside this box using the convolution with the fundamental\n  // solution. The formula for this is given in the introduction.\n  //\n  // The reconstruction of the solution in the entire space is done on a\n  // continuous finite element grid of dimension dim. These are the usual\n  // ones, and we don't comment any further on them. At the end of the\n  // function, we output this exterior solution in, again, much the usual way.\n  template <int dim>\n  void BEMProblem<dim>::compute_exterior_solution()\n  {\n    Triangulation<dim>  external_tria;\n    GridGenerator::hyper_cube(external_tria, -2, 2);\n\n    FE_Q<dim>           external_fe(1);\n    DoFHandler<dim>     external_dh (external_tria);\n    Vector<double>      external_phi;\n\n    external_tria.refine_global(external_refinement);\n    external_dh.distribute_dofs(external_fe);\n    external_phi.reinit(external_dh.n_dofs());\n\n    typename DoFHandler<dim-1,dim>::active_cell_iterator\n    cell = dh.begin_active(),\n    endc = dh.end();\n\n\n    FEValues<dim-1,dim> fe_v(mapping, fe, *quadrature,\n                             update_values |\n                             update_cell_normal_vectors |\n                             update_quadrature_points |\n                             update_JxW_values);\n\n    const unsigned int n_q_points = fe_v.n_quadrature_points;\n\n    std::vector<unsigned int> dofs(fe.dofs_per_cell);\n\n    std::vector<double> local_phi(n_q_points);\n    std::vector<double> normal_wind(n_q_points);\n    std::vector<Vector<double> > local_wind(n_q_points, Vector<double>(dim) );\n\n    std::vector<Point<dim> > external_support_points(external_dh.n_dofs());\n    DoFTools::map_dofs_to_support_points<dim>(StaticMappingQ1<dim>::mapping,\n                                              external_dh, external_support_points);\n\n    for (cell = dh.begin_active(); cell != endc; ++cell)\n      {\n        fe_v.reinit(cell);\n\n        const std::vector<Point<dim> > &q_points = fe_v.get_quadrature_points();\n        const std::vector<Point<dim> > &normals = fe_v.get_normal_vectors();\n\n        cell->get_dof_indices(dofs);\n        fe_v.get_function_values(phi, local_phi);\n\n        wind.vector_value_list(q_points, local_wind);\n\n        for (unsigned int q=0; q<n_q_points; ++q)\n          {\n            normal_wind[q] = 0;\n            for (unsigned int d=0; d<dim; ++d)\n              normal_wind[q] += normals[q][d]*local_wind[q](d);\n          }\n\n        for (unsigned int i=0; i<external_dh.n_dofs(); ++i)\n          for (unsigned int q=0; q<n_q_points; ++q)\n            {\n\n              const Point<dim> R =  q_points[q] - external_support_points[i];\n\n              external_phi(i) += ( ( LaplaceKernel::single_layer(R) *\n                                     normal_wind[q]\n                                     +\n                                     (LaplaceKernel::double_layer(R) *\n                                      normals[q] )            *\n                                     local_phi[q] )           *\n                                   fe_v.JxW(q) );\n            }\n      }\n\n    DataOut<dim> data_out;\n\n    data_out.attach_dof_handler(external_dh);\n    data_out.add_data_vector(external_phi, \"external_phi\");\n    data_out.build_patches();\n\n    const std::string\n    filename = Utilities::int_to_string(dim) + \"d_external.vtk\";\n    std::ofstream file(filename.c_str());\n\n    data_out.write_vtk(file);\n  }\n\n\n  // @sect4{BEMProblem::output_results}\n\n  // Outputting the results of our computations is a rather mechanical\n  // tasks. All the components of this function have been discussed before.\n  template <int dim>\n  void BEMProblem<dim>::output_results(const unsigned int cycle)\n  {\n    DataOut<dim-1, DoFHandler<dim-1, dim> > dataout;\n\n    dataout.attach_dof_handler(dh);\n    dataout.add_data_vector(phi, \"phi\");\n    dataout.add_data_vector(alpha, \"alpha\");\n    dataout.build_patches(mapping,\n                          mapping.get_degree(),\n                          DataOut<dim-1, DoFHandler<dim-1, dim> >::curved_inner_cells);\n\n    std::string filename = ( Utilities::int_to_string(dim) +\n                             \"d_boundary_solution_\" +\n                             Utilities::int_to_string(cycle) +\n                             \".vtk\" );\n    std::ofstream file(filename.c_str());\n\n    dataout.write_vtk(file);\n\n    if (cycle == n_cycles-1)\n      {\n        convergence_table.set_precision(\"L2(phi)\", 3);\n        convergence_table.set_precision(\"Linfty(alpha)\", 3);\n\n        convergence_table.set_scientific(\"L2(phi)\", true);\n        convergence_table.set_scientific(\"Linfty(alpha)\", true);\n\n        convergence_table\n        .evaluate_convergence_rates(\"L2(phi)\", ConvergenceTable::reduction_rate_log2);\n        convergence_table\n        .evaluate_convergence_rates(\"Linfty(alpha)\", ConvergenceTable::reduction_rate_log2);\n        deallog << std::endl;\n        convergence_table.write_text(std::cout);\n      }\n  }\n\n\n  // @sect4{BEMProblem::run}\n\n  // This is the main function. It should be self explanatory in its\n  // briefness:\n  template <int dim>\n  void BEMProblem<dim>::run()\n  {\n\n    read_parameters(\"parameters.prm\");\n\n    if (run_in_this_dimension == false)\n      {\n        deallog << \"Run in dimension \" << dim\n                << \" explicitly disabled in parameter file. \"\n                << std::endl;\n        return;\n      }\n\n    read_domain();\n\n    for (unsigned int cycle=0; cycle<n_cycles; ++cycle)\n      {\n        refine_and_resize();\n        assemble_system();\n        solve_system();\n        compute_errors(cycle);\n        output_results(cycle);\n      }\n\n    if (extend_solution == true)\n      compute_exterior_solution();\n  }\n}\n\n\n// @sect3{The main() function}\n\n// This is the main function of this program. It is exactly like all previous\n// tutorial programs:\nint main ()\n{\n  try\n    {\n      using namespace dealii;\n      using namespace Step34;\n\n      const unsigned int degree = 1;\n      const unsigned int mapping_degree = 1;\n\n      deallog.depth_console (3);\n      BEMProblem<2> laplace_problem_2d(degree, mapping_degree);\n      laplace_problem_2d.run();\n\n      BEMProblem<3> laplace_problem_3d(degree, mapping_degree);\n      laplace_problem_3d.run();\n    }\n  catch (std::exception &exc)\n    {\n      std::cerr << std::endl << std::endl\n                << \"----------------------------------------------------\"\n                << std::endl;\n      std::cerr << \"Exception on processing: \" << std::endl\n                << exc.what() << std::endl\n                << \"Aborting!\" << std::endl\n                << \"----------------------------------------------------\"\n                << std::endl;\n\n      return 1;\n    }\n  catch (...)\n    {\n      std::cerr << std::endl << std::endl\n                << \"----------------------------------------------------\"\n                << std::endl;\n      std::cerr << \"Unknown exception!\" << std::endl\n                << \"Aborting!\" << std::endl\n                << \"----------------------------------------------------\"\n                << std::endl;\n      return 1;\n    }\n\n  return 0;\n}\n", "meta": {"hexsha": "424be3057e700628fe21a6488e93fd122263e099", "size": 45169, "ext": "cc", "lang": "C++", "max_stars_repo_path": "MHD/examples/step-34/step-34.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-34/step-34.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-34/step-34.cc", "max_forks_repo_name": "wathen/PhD", "max_forks_repo_head_hexsha": "35524f40028541a4d611d8c78574e4cf9ddc3278", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2019-10-28T16:12:13.000Z", "max_forks_repo_forks_event_max_datetime": "2020-01-13T13:59:44.000Z", "avg_line_length": 40.3655049151, "max_line_length": 106, "alphanum_fraction": 0.6337089597, "num_tokens": 10286, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.607663184043154, "lm_q2_score": 0.5736784074525096, "lm_q1q2_score": 0.3486032476893979}}
{"text": "\n/******************************************************************************\n\n  Triangulation algorithms for surface reconstruction problems.\n\n  Copyright (c) 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 TRIANGULATION_HPP_40CA4CA1_3752_4080_9BDE_D13393E21902\n#define TRIANGULATION_HPP_40CA4CA1_3752_4080_9BDE_D13393E21902\n\n#include <vector>\n#include <boost/foreach.hpp>\n#include <boost/noncopyable.hpp>\n\n#include \"bo/core/mesh.hpp\"\n#include \"bo/surfaces/detail/indexed_tstrip.hpp\"\n#include \"bo/surfaces/christiansen_tiling.hpp\"\n\nnamespace bo {\nnamespace surfaces {\n\n// This class contain various triangulation algorithms.\ntemplate <typename RealType>\nclass Triangulation\n{\npublic:\n    typedef bo::Mesh<RealType> RealMesh;\n    typedef ChristiansenTiling<RealType> Christiansen;\n\npublic:\n    // Performs modified Christiansen triangulation for two contours.\n    template <typename ContourDescrPtr>\n    static RealMesh christiansen(const ContourDescrPtr& contour1,\n                                 const ContourDescrPtr& contour2)\n    {\n\n        detail::IndexedTStrip tstrip = Christiansen(0, contour1->contour(), contour1->is_closed(),\n                                                    1, contour2->contour(), contour2->is_closed())\n                .run();\n\n        // Calculate the total number of vertices to create mesh efficiently.\n        std::size_t total_vertices = contour1->contour()->size() + contour2->contour()->size();\n\n        // Populate the result mesh with vertices and store vertices shift for the\n        // second contour (it should be 0 for the first).\n        RealMesh mesh(total_vertices);\n        std::vector<std::size_t> lookup_table(2);\n        lookup_table[0] = mesh.add_vertices(*(contour1->contour()));\n        lookup_table[1] = mesh.add_vertices(*(contour2->contour()));\n\n        // Populate the result mesh with faces. Transform old <contour_id, vertex_ix>\n        // keys into new <mesh_vertex_id> keys using lookup table.\n        BOOST_FOREACH (const detail::IndexedTStrip::Face& face, tstrip.get_faces())\n        {\n            std::size_t new_a = lookup_table[face.A().first] + face.A().second;\n            std::size_t new_b = lookup_table[face.B().first] + face.B().second;\n            std::size_t new_c = lookup_table[face.C().first] + face.C().second;\n            mesh.add_face(typename RealMesh::Face(new_a, new_b, new_c));\n        }\n\n        return mesh;\n    }\n\n    // Performs modified Christiansen triangulation for a collection of contours.\n    // Note that the collection must be sorted, because the algorithm connects adjacent\n    // contours.\n    template <typename ContourDescrPtr>\n    static RealMesh christiansen(const std::vector<ContourDescrPtr>& contours)\n    {\n        std::size_t total_contours = contours.size();\n        detail::IndexedTStrip::TStrips tstrips_;\n\n        for (std::size_t idx = 1; idx < total_contours; ++idx)\n        {\n            ContourDescrPtr cur_contour = contours[idx];\n            ContourDescrPtr prev_contour = contours[idx - 1];\n\n            Christiansen triang(\n                    idx - 1, prev_contour->contour(), prev_contour->is_closed(),\n                    idx, cur_contour->contour(), cur_contour->is_closed());\n\n            detail::IndexedTStrip tstrip = triang.run();\n            tstrips_.push_back(tstrip);\n        }\n\n        // Union all tstrips into one mesh.\n        detail::IndexedTStrip joined_tstrips = detail::IndexedTStrip::join(tstrips_);\n\n        // Calculate the total number of vertices to create mesh efficiently.\n        std::size_t total_vertices = 0;\n        BOOST_FOREACH (const ContourDescrPtr& c, contours)\n        { total_vertices += c->contour()->size(); }\n\n        // Populate the result mesh with vertices and create lookup tables.\n        RealMesh mesh(total_vertices);\n        std::vector<std::size_t> lookup_table(total_contours);\n        for (std::size_t idx = 0; idx < total_contours; ++idx)\n        {\n            std::size_t current_offset = mesh.add_vertices(*(contours[idx]->contour()));\n            lookup_table[idx] = current_offset;\n        }\n\n        // Populate the result mesh with faces. Transform old <contour_id, vertex_ix>\n        // keys into new <mesh_vertex_id> keys using lookup table.\n        BOOST_FOREACH (const detail::IndexedTStrip::Face& face, joined_tstrips.get_faces())\n        {\n            std::size_t new_a = lookup_table[face.A().first] + face.A().second;\n            std::size_t new_b = lookup_table[face.B().first] + face.B().second;\n            std::size_t new_c = lookup_table[face.C().first] + face.C().second;\n            mesh.add_face(typename RealMesh::Face(new_a, new_b, new_c));\n        }\n\n        return mesh;\n    }\n};\n\n} // namespace surfaces\n} // namespace bo\n\n#endif // TRIANGULATION_HPP_40CA4CA1_3752_4080_9BDE_D13393E21902\n", "meta": {"hexsha": "2f6d40ab30b043187adfc7cec90a95d07789f67c", "size": 6175, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Bo/surfaces/triangulation.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/triangulation.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/triangulation.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": 42.2945205479, "max_line_length": 98, "alphanum_fraction": 0.6655870445, "num_tokens": 1407, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6076631698328917, "lm_q2_score": 0.5736784074525098, "lm_q1q2_score": 0.3486032395372773}}
{"text": "//\n// $Id: ParameterEstimator.cpp 2051 2010-06-15 18:39:13Z chambm $\n//\n//\n// Original author: Darren Kessner <darren@proteowizard.org>\n//\n// Copyright 2006 Louis Warschaw Prostate Cancer Center\n//   Cedars Sinai Medical Center, Los Angeles, California  90048\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\"); \n// you may not use this file except in compliance with the License. \n// You may obtain a copy of the License at \n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software \n// distributed under the License is distributed on an \"AS IS\" BASIS, \n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. \n// See the License for the specific language governing permissions and \n// limitations under the License.\n//\n\n\n#include \"ParameterEstimator.hpp\"\n//#include \"DerivativeTest.hpp\" // for testing numerical derivatives only\n\n#include \"pwiz/utility/misc/Std.hpp\"\n#include <boost/numeric/ublas/vector.hpp>\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/lu.hpp>\n#include <boost/numeric/ublas/triangular.hpp>\n#include <boost/numeric/ublas/vector_proxy.hpp>\n#include <boost/numeric/ublas/io.hpp>\nnamespace ublas = boost::numeric::ublas;\n\n\nnamespace pwiz {\nnamespace frequency {\n\n\nclass ParameterEstimatorImpl : public ParameterEstimator\n{\n    public:\n\n    ParameterEstimatorImpl(const Function& function,\n                               const Data& data,\n                               const Parameters& initialEstimate);\n\n    virtual const Parameters& estimate() const {return p_;}\n    virtual void estimate(const Parameters& p) {p_ = p;}\n    virtual double error() const {return e_(p_);}\n    virtual double iterate(ostream* log);\n\n    private:\n\n    const Function& f_;\n    const Data& data_;\n    Parameters p_;\n    Function::ErrorFunction e_;\n\n    Parameters solve(const ublas::matrix<double>& A , const ublas::vector<double>& y) const;\n};\n\n\nauto_ptr<ParameterEstimator> ParameterEstimator::create(const Function& function,\n                                                                const Data& data,\n                                                                const Parameters& initialEstimate)\n{\n    return auto_ptr<ParameterEstimator>(new ParameterEstimatorImpl(function, data, initialEstimate));\n}\n\n\nParameterEstimatorImpl::ParameterEstimatorImpl(const Function& function,\n                                                       const Data& data,\n                                                       const Parameters& initialEstimate)\n:   f_(function),\n    data_(data),\n    p_(initialEstimate),\n    e_(f_, data_)\n{\n    if (function.parameterCount() != initialEstimate.size())\n        throw logic_error(\"[ParameterEstimator::ParameterEstimatorImpl()] Wrong number of parameters.\");\n}\n\n\ndouble ParameterEstimatorImpl::iterate(ostream* log)\n{\n    // DerivativeTest::testDerivatives< complex<double> >(e_, p_); // testing only\n\n    double error_old = error();\n\n    ublas::vector<double> d = e_.dp(p_);\n    ublas::matrix<double> d2 = e_.dp2(p_);\n\n    // calculate new estimate:\n    //   correction == inverse(d2) * d\n    //   p_new = p_old - correction\n\n    Parameters correction = solve(d2, d);\n\n    // compare error change to prediction from parabolic approximation\n    ublas::vector<double> dp = -correction;\n    double error_change_predicted = inner_prod(d, dp) + .5*inner_prod(dp, prod(d2,dp));\n    double error_change_actual = e_(p_-correction) - error_old;\n\n\n    if (log) *log << \"d: \" << d << endl;\n    if (log) *log << \"d2: \" << d2 << endl;\n    if (log) *log << \"correction: \" << correction << endl;\n    if (log) *log << \"error_change_predicted: \" << error_change_predicted << endl;\n    if (log) *log << \"error_change_actual: \" << error_change_actual << endl;\n\n\n    // if we can decrease error -- go for it!\n    if (error_change_actual < 0)\n    {\n        p_ -= correction;\n        return error_change_actual;\n    }\n\n    // error is going to increase if we make the full correction;\n    // backtrack along correction gradient to find decreasing error\n\n    Parameters correction_backtrack = correction;\n    int zeroCount = 0;\n\n    for (int i=0; i<10; i++)\n    {\n        correction_backtrack /= 2;\n        double error_change_backtrack = e_(p_ - correction_backtrack) - error_old;\n        if (log) *log << \"error_change_backtrack: \" << error_change_backtrack << endl;\n        if (error_change_backtrack < 0)\n        {\n            // found negative error change -- go for it!\n            p_ -= correction_backtrack;\n            return error_change_backtrack;\n        }\n        else if (error_change_backtrack == 0)\n        {\n            zeroCount++;\n            if (zeroCount >= 3) // stuck on zero -- we're outta here\n                break;\n        }\n    }\n\n    // don't correct\n    if (log) *log << \"No correction.\\n\";\n    return 0;\n}\n\n\nParameterEstimatorImpl::Parameters ParameterEstimatorImpl::solve(const ublas::matrix<double>& A , const ublas::vector<double>& y) const\n{\n    // solve Ax = y\n\n    ublas::matrix<double> A_factorized = A;\n\n    ublas::permutation_matrix<size_t> pm(e_.parameterCount());\n    int singular = lu_factorize(A_factorized, pm);\n    if (singular)\n        throw runtime_error(\"[ParameterEstimatorImpl::solve()] A is singular.\");\n\n    ublas::vector<double> result(y);\n    lu_substitute(A_factorized, pm, result);\n    return result;\n}\n\n\n} // namespace frequency\n} // namespace pwiz\n\n", "meta": {"hexsha": "51e739593646b519f895c7e3a8e529e3d3d8c87b", "size": 5453, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "pwiz/analysis/frequency/ParameterEstimator.cpp", "max_stars_repo_name": "edyp-lab/pwiz-mzdb", "max_stars_repo_head_hexsha": "d13ce17f4061596c7e3daf9cf5671167b5996831", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 11.0, "max_stars_repo_stars_event_min_datetime": "2015-01-08T08:33:44.000Z", "max_stars_repo_stars_event_max_datetime": "2019-07-12T06:14:54.000Z", "max_issues_repo_path": "pwiz/analysis/frequency/ParameterEstimator.cpp", "max_issues_repo_name": "shze/pwizard-deb", "max_issues_repo_head_hexsha": "4822829196e915525029a808470f02d24b8b8043", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 61.0, "max_issues_repo_issues_event_min_datetime": "2015-05-27T11:20:11.000Z", "max_issues_repo_issues_event_max_datetime": "2019-12-20T15:06:21.000Z", "max_forks_repo_path": "pwiz/analysis/frequency/ParameterEstimator.cpp", "max_forks_repo_name": "shze/pwizard-deb", "max_forks_repo_head_hexsha": "4822829196e915525029a808470f02d24b8b8043", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2016-02-03T09:41:16.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-01T18:42:36.000Z", "avg_line_length": 31.7034883721, "max_line_length": 135, "alphanum_fraction": 0.6444159178, "num_tokens": 1284, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6076631556226292, "lm_q2_score": 0.5736784074525096, "lm_q1q2_score": 0.3486032313851564}}
{"text": "#ifndef STAN_MATH_PRIM_SCAL_FUN_LOCSCALE_FREE_HPP\n#define STAN_MATH_PRIM_SCAL_FUN_LOCSCALE_FREE_HPP\n\n#include <stan/math/prim/scal/fun/identity_free.hpp>\n#include <stan/math/prim/scal/err/check_positive_finite.hpp>\n#include <stan/math/prim/scal/err/check_finite.hpp>\n#include <boost/math/tools/promotion.hpp>\n#include <cmath>\n#include <limits>\n\nnamespace stan {\nnamespace math {\n\n/**\n * Return the unconstrained scalar that transforms to the\n * specified location and scale constrained scalar given the specified\n * location and scale.\n *\n * <p>The transfrom in <code>locscale_constrain(T, double, double)</code>,\n * is reversed by the reverse affine transformation,\n *\n * <p>\\f$f^{-1}(y) = \\frac{y - L}{S}\\f$\n *\n * where \\f$L\\f$ and \\f$S\\f$ are the location and scale.\n *\n * <p>If the location is zero and scale is one,\n * this function reduces to  <code>identity_free(y)</code>.\n *\n * @tparam T type of scalar\n * @tparam L type of location\n * @tparam S type of scale\n * @param y constrained value\n * @param[in] mu location of constrained output\n * @param[in] sigma scale of constrained output\n * @return the free scalar that transforms to the input scalar\n *   given the location and scale\n * @throw std::domain_error if sigma <= 0\n * @throw std::domain_error if mu is not finite\n */\ntemplate <typename T, typename L, typename S>\ninline typename boost::math::tools::promote_args<T, L, S>::type locscale_free(\n    const T& y, const L& mu, const S& sigma) {\n  check_finite(\"locscale_free\", \"location\", mu);\n  if (sigma == 1) {\n    if (mu == 0)\n      return identity_free(y);\n    return y - mu;\n  }\n  check_positive_finite(\"locscale_free\", \"scale\", sigma);\n  return (y - mu) / sigma;\n}\n\n}  // namespace math\n}  // namespace stan\n#endif\n", "meta": {"hexsha": "6ac928aa0fbf43eb62530b50e148c6241cffd9bb", "size": 1735, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "stan/math/prim/scal/fun/locscale_free.hpp", "max_stars_repo_name": "jrmie/math", "max_stars_repo_head_hexsha": "2850ec262181075a5843968e805dc9ad1654e069", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "stan/math/prim/scal/fun/locscale_free.hpp", "max_issues_repo_name": "jrmie/math", "max_issues_repo_head_hexsha": "2850ec262181075a5843968e805dc9ad1654e069", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "stan/math/prim/scal/fun/locscale_free.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.9821428571, "max_line_length": 78, "alphanum_fraction": 0.7083573487, "num_tokens": 468, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6513548782017745, "lm_q2_score": 0.5350984286266115, "lm_q1q2_score": 0.34853897180404747}}
{"text": "/**\n * cartesian_pose_control.cc\n *\n * Copyright 2019. All Rights Reserved.\n * Stanford IPRL\n *\n * Created: January 16, 2019\n * Authors: Mengyuan Yan\n */\n\n#include \"control_thread.h\"\n\n#include <algorithm>  // std::all_of\n#include <array>      // std::array\n#include <cmath>      // std::abs, std::acos, std::cos, std::pow, std::sin, std::sqrt\n\n#include <Eigen/Eigen>\n#include <franka/exception.h>\n#include <franka/control_types.h>\n#include <franka/duration.h>\n#include <franka/robot.h>\n#include <franka/robot_state.h>\n\n#include \"shared_memory.h\"\n\nnamespace franka_driver {\n\n/**\n * Sets a default collision behavior, joint impedance, Cartesian impedance, and filter frequency.\n *\n * @param[in] robot Robot instance to set behavior on.\n */\nvoid setDefaultBehavior(franka::Robot& robot);\n\n/**\n * Generate a joint pose motion to a goal position. Adapted from:\n * Wisama Khalil and Etienne Dombre. 2002. Modeling, Identification and Control of Robots\n * (Kogan Page Science Paper edition).\n */\nclass MotionGenerator {\n  public:\n\n  /**\n   * Creates a new MotionGenerator instance.\n   */\n  MotionGenerator();\n\n  /**\n   * reset MotionGenerator for a target q.\n   *\n   * @param[in] speed_factor General speed factor in range [0, 1].\n   * @param[in] pose_goal Target end-effector pose.\n   */\n  void reset(double speed_factor, const std::array<double, 16> pose_goal);\n\n  /**\n   * Sends next pose command\n   *\n   * @param[in] robot_state Current state of the robot.\n   * @param[in] period Duration of execution.\n   *\n   * @return end-effector pose for use inside a control loop.\n   */\n  franka::CartesianPose operator()(const franka::RobotState& robot_state, franka::Duration period);\n\n  private:\n  using Vector3d = Eigen::Matrix<double, 3, 1, Eigen::ColMajor>;\n  using Vector2d = Eigen::Matrix<double, 2, 1, Eigen::ColMajor>;\n  using Matrix4x4d = Eigen::Matrix<double, 4, 4, Eigen::ColMajor>;\n  using Matrix3x3d = Eigen::Matrix<double, 3, 3, Eigen::ColMajor>;\n\n  bool calculateDesiredValues(double t, Vector2d* delta_pose_d) const;\n  void calculateSynchronizedValues();\n  void preCalculateRotationMatrices();\n\n  // tranlational and rotation angle residual threshold\n  static constexpr std::array<double, 2> kDeltaMotionFinished = {1e-4, 0.01};\n  Matrix4x4d pose_goal_;\n  Matrix4x4d pose_start_;\n  Vector3d unit_T_;\n  Vector3d axis_R_;\n  Vector2d delta_q_; // delta_trans_, delta_angle_\n\n  Matrix3x3d precompute_pose_eye_;\n  Matrix3x3d precompute_pose_dot_;\n  Matrix3x3d precompute_pose_cross_;\n\n  Vector2d dq_max_sync_;\n  Vector2d t_1_sync_;\n  Vector2d t_2_sync_;\n  Vector2d t_f_sync_;\n  Vector2d q_1_;\n\n  double time_ = 0.0;\n\n  const Vector2d default_dq_max_ = (Vector2d() << 0.1, 0.4).finished(); // 0.2m/s, 1.0rad/s\n  const Vector2d default_ddq_max_start_ = (Vector2d() << 0.2, 0.5).finished();\n  const Vector2d default_ddq_max_goal_ = (Vector2d() << 0.2, 0.5).finished();\n  Vector2d dq_max_;\n  Vector2d ddq_max_start_;\n  Vector2d ddq_max_goal_;\n\n};\n\nvoid setDefaultBehavior(franka::Robot& robot) {\n  robot.setCollisionBehavior(\n      {{20.0, 20.0, 20.0, 20.0, 20.0, 20.0, 20.0}}, {{20.0, 20.0, 20.0, 20.0, 20.0, 20.0, 20.0}},\n      {{10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0}}, {{10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0}},\n      {{20.0, 20.0, 20.0, 20.0, 20.0, 20.0}}, {{20.0, 20.0, 20.0, 20.0, 20.0, 20.0}},\n      {{10.0, 10.0, 10.0, 10.0, 10.0, 10.0}}, {{10.0, 10.0, 10.0, 10.0, 10.0, 10.0}});\n  robot.setJointImpedance({{3000, 3000, 3000, 2500, 2500, 2000, 2000}});\n  robot.setCartesianImpedance({{3000, 3000, 3000, 300, 300, 300}});\n}\n\n// This is for gcc 5.4, does not need this line with gcc6.4\n// Refer to https://stackoverflow.com/questions/8016780/undefined-reference-to-static-constexpr-char\nconstexpr std::array<double, 2> MotionGenerator::kDeltaMotionFinished;\n\nMotionGenerator::MotionGenerator() {\n  dq_max_sync_.setZero();\n  pose_start_.setZero();\n  pose_goal_.setZero();\n  unit_T_.setZero();\n  axis_R_.setZero();\n  delta_q_.setZero();\n  t_1_sync_.setZero();\n  t_2_sync_.setZero();\n  t_f_sync_.setZero();\n  q_1_.setZero();\n}\n\nvoid MotionGenerator::reset(double speed_factor, const std::array<double, 16> pose_goal)\n{\n  dq_max_ = default_dq_max_ * speed_factor;\n  ddq_max_start_ = default_ddq_max_start_ * speed_factor;\n  ddq_max_goal_ = default_ddq_max_goal_ * speed_factor;\n  dq_max_sync_.setZero();\n  pose_start_.setZero();\n  pose_goal_ = Matrix4x4d(pose_goal.data());\n  unit_T_.setZero();\n  axis_R_.setZero();\n  delta_q_.setZero();\n  t_1_sync_.setZero();\n  t_2_sync_.setZero();\n  t_f_sync_.setZero();\n  q_1_.setZero();\n  time_ = 0;\n}\n\nbool MotionGenerator::calculateDesiredValues(double t, Vector2d* delta_q_d) const {\n  // Vector2d t_d = t_2_sync_ - t_1_sync_;\n  Vector2d delta_t_2_sync = t_f_sync_ - t_2_sync_;\n  std::array<bool, 2> motion_finished{};\n\n  for (size_t i = 0; i < 2; i++) {\n    if (std::abs(delta_q_[i]) < kDeltaMotionFinished[i]) {\n      (*delta_q_d)[i] = 0;\n      motion_finished[i] = true;\n    } else {\n      if (t < t_1_sync_[i]) {\n        (*delta_q_d)[i] = -1.0 / (t_1_sync_[i]*t_1_sync_[i]*t_1_sync_[i]) * dq_max_sync_[i] *\n                          (0.5 * t - t_1_sync_[i]) * (t*t*t);\n      } else if (t >= t_1_sync_[i] && t < t_2_sync_[i]) {\n        (*delta_q_d)[i] = q_1_[i] + (t - t_1_sync_[i]) * dq_max_sync_[i];\n      } else if (t >= t_2_sync_[i] && t < t_f_sync_[i]) {\n        double tt = t - t_2_sync_[i];\n        (*delta_q_d)[i] =\n            delta_q_[i] + 0.5 * (1.0 / (delta_t_2_sync[i]*delta_t_2_sync[i]*delta_t_2_sync[i]) *\n                                   (tt - 2.0 * delta_t_2_sync[i]) * (tt*tt*tt) +\n                                (2.0 * tt - delta_t_2_sync[i])) * dq_max_sync_[i];\n      } else {\n        (*delta_q_d)[i] = delta_q_[i];\n        motion_finished[i] = true;\n      }\n    }\n  }\n  return std::all_of(motion_finished.cbegin(), motion_finished.cend(),\n                     [](bool x) { return x; });\n}\n\nvoid MotionGenerator::calculateSynchronizedValues() {\n  Vector2d dq_max_reach(dq_max_);\n  Vector2d t_f = Vector2d::Zero();\n  Vector2d delta_t_2 = Vector2d::Zero();\n  Vector2d t_1 = Vector2d::Zero();\n  Vector2d delta_t_2_sync = Vector2d::Zero();\n\n  unit_T_ = pose_goal_.block<3,1>(0,3) - pose_start_.block<3,1>(0,3);\n  delta_q_[0] = unit_T_.norm();\n  if (delta_q_[0] > 0) unit_T_ = unit_T_ / delta_q_[0];\n\n  Matrix3x3d delta_R_;\n  delta_R_ = pose_goal_.block<3,3>(0,0) * pose_start_.block<3,3>(0,0).transpose();\n  // matrix to axis-angle\n  double cos_angle = (delta_R_.trace()-1)/2;\n  delta_q_[1] = std::acos(cos_angle);\n  if (cos_angle < 0) {\n    // more stable way of calculating axis when angle close to pi.\n    axis_R_(0) = std::sqrt((delta_R_(0,0)-cos_angle)/2);\n    axis_R_(1) = std::sqrt((delta_R_(1,1)-cos_angle)/2);\n    axis_R_(2) = std::sqrt((delta_R_(2,2)-cos_angle)/2);\n    if (delta_R_(0,1)-delta_R_(1,0) > 0) axis_R_(2) = -axis_R_(2);\n    if (delta_R_(2,0)-delta_R_(0,2) > 0) axis_R_(1) = -axis_R_(1);\n    if (delta_R_(1,2)-delta_R_(2,1) > 0) axis_R_(0) = -axis_R_(0);\n    axis_R_.normalize();\n  } else {\n    // more stable way of calculating axis when angle close to 0.\n    axis_R_(0) = delta_R_(2,1) - delta_R_(1,2);\n    axis_R_(1) = delta_R_(0,2) - delta_R_(2,0);\n    axis_R_(2) = delta_R_(1,0) - delta_R_(0,1);\n    if (axis_R_.norm() > 0) axis_R_.normalize();\n  }\n\n  for (size_t i = 0; i < 2; i++) {\n    if (std::abs(delta_q_[i]) > kDeltaMotionFinished[i]) {\n      if (std::abs(delta_q_[i]) < (3.0 / 4.0 * (std::pow(dq_max_[i], 2.0) / ddq_max_start_[i]) +\n                                   3.0 / 4.0 * (std::pow(dq_max_[i], 2.0) / ddq_max_goal_[i]))) {\n        dq_max_reach[i] = std::sqrt(4.0 / 3.0 * delta_q_[i] *\n                                    (ddq_max_start_[i] * ddq_max_goal_[i]) /\n                                    (ddq_max_start_[i] + ddq_max_goal_[i]));\n      }\n      t_1[i] = 1.5 * dq_max_reach[i] / ddq_max_start_[i];\n      delta_t_2[i] = 1.5 * dq_max_reach[i] / ddq_max_goal_[i];\n      t_f[i] = t_1[i] / 2.0 + delta_t_2[i] / 2.0 + std::abs(delta_q_[i]) / dq_max_reach[i];\n    }\n  }\n  double max_t_f = t_f.maxCoeff();\n  for (size_t i = 0; i < 2; i++) {\n    if (std::abs(delta_q_[i]) > kDeltaMotionFinished[i]) {\n      double a = 1.5 / 2.0 * (ddq_max_goal_[i] + ddq_max_start_[i]);\n      double b = -1.0 * max_t_f * ddq_max_goal_[i] * ddq_max_start_[i];\n      double c = std::abs(delta_q_[i]) * ddq_max_goal_[i] * ddq_max_start_[i];\n      double delta = b * b - 4.0 * a * c;\n      if (delta < 0.0) {\n        delta = 0.0;\n      }\n      dq_max_sync_[i] = (-1.0 * b - std::sqrt(delta)) / (2.0 * a);\n      t_1_sync_[i] = 1.5 * dq_max_sync_[i] / ddq_max_start_[i];\n      delta_t_2_sync[i] = 1.5 * dq_max_sync_[i] / ddq_max_goal_[i];\n      t_f_sync_[i] =\n          (t_1_sync_)[i] / 2.0 + delta_t_2_sync[i] / 2.0 + std::abs(delta_q_[i] / dq_max_sync_[i]);\n      t_2_sync_[i] = t_f_sync_[i] - delta_t_2_sync[i];\n      q_1_[i] = dq_max_sync_[i] * 0.5 * t_1_sync_[i];\n    }\n  }\n}\n\nvoid MotionGenerator::preCalculateRotationMatrices() {\n  precompute_pose_eye_ = pose_start_.block<3,3>(0,0);\n  precompute_pose_dot_ = axis_R_*axis_R_.transpose()*precompute_pose_eye_;\n  precompute_pose_cross_ = Eigen::MatrixXd::Zero(3,3);\n  precompute_pose_cross_(0,1) = -axis_R_(2);\n  precompute_pose_cross_(1,0) = axis_R_(2);\n  precompute_pose_cross_(0,2) = axis_R_(1);\n  precompute_pose_cross_(2,0) = -axis_R_(1);\n  precompute_pose_cross_(1,2) = -axis_R_(0);\n  precompute_pose_cross_(2,1) = axis_R_(0);\n  precompute_pose_cross_ = precompute_pose_cross_ * precompute_pose_eye_;\n}\n\nfranka::CartesianPose MotionGenerator::operator()(const franka::RobotState& robot_state,\n                                                   franka::Duration period) {\n  time_ += period.toSec();\n\n  if (time_ == 0.0) {\n    pose_start_ = Matrix4x4d(robot_state.O_T_EE_c.data());\n    calculateSynchronizedValues();\n    preCalculateRotationMatrices();\n  }\n\n  Vector2d delta_q_d;\n  bool motion_finished = calculateDesiredValues(time_, &delta_q_d);\n\n  std::array<double, 16> command_pose;\n  Eigen::Map<Matrix4x4d> command_pose_e(&command_pose[0]);\n  command_pose_e = pose_start_;\n\n  if (delta_q_d[0] > 0) {\n    command_pose_e.block<3,1>(0,3) += delta_q_d[0] * unit_T_;\n  }\n  if (delta_q_d[1] > 0) {\n    command_pose_e.block<3,3>(0,0) = std::cos(delta_q_d[1]) * precompute_pose_eye_ +\n                                     (1 - std::cos(delta_q_d[1])) * precompute_pose_dot_ +\n                                     std::sin(delta_q_d[1]) * precompute_pose_cross_;\n  }\n//  std::cout << command_pose_e << std::endl;\n//  std::cout << command_pose_e.transpose()*command_pose_e << std::endl;\n  franka::CartesianPose output(command_pose);\n  output.motion_finished = motion_finished;\n  return output;\n}\n\nstd::function<franka::CartesianPose(const franka::RobotState&, franka::Duration)>\nCreateCartesianPoseController(const Args& args, const std::shared_ptr<SharedMemory>& globals,\n                              franka::Robot& robot, const franka::Model& model) {\n  std::shared_ptr<MotionGenerator> motion_generator = std::make_shared<MotionGenerator>();\n  \n  franka::RobotState state = robot.readOnce();\n  std::array<double, 16> pose_command = globals->pose_command;\n  if (globals->control_mode == ControlMode::DELTA_CARTESIAN_POSE) {\n    Eigen::Map<Eigen::Matrix4d> start_pose_e(state.O_T_EE.data());\n    Eigen::Map<Eigen::Matrix4d> command_pose_e(pose_command.data());\n    command_pose_e.topRightCorner<3,1>() += start_pose_e.topRightCorner<3,1>();\n    command_pose_e.topLeftCorner<3,3>() = command_pose_e.topLeftCorner<3,3>() * start_pose_e.topLeftCorner<3,3>();\n  }\n  motion_generator->reset(1., pose_command);\n\n  return [globals, motion_generator](const franka::RobotState& state, franka::Duration dt) -> franka::CartesianPose {\n    static const auto t_start = std::chrono::steady_clock::now();\n    if (!*globals->runloop) {\n      throw std::runtime_error(\"TorqueController(): SIGINT.\");\n    }\n\n    // Set sensor values\n    globals->q    = state.q;\n    globals->dq   = state.dq;\n    globals->tau  = state.tau_J;\n    globals->dtau = state.dtau_J;\n\n    // Set time\n    const auto ms_now = std::chrono::duration_cast<std::chrono::duration<double>>(std::chrono::steady_clock::now() - t_start);\n    globals->time = globals->time + ms_now.count();\n\n    // Get command torques\n    if (globals->control_mode != ControlMode::CARTESIAN_POSE) {\n      throw SwitchControllerException(\"cartesian_pose\");\n    }\n\n    return (*motion_generator)(state, dt);\n  };\n}\n\n}  // namespace franka_driver\n", "meta": {"hexsha": "e96b09f01041a1ed830395c0d3d0b8a84c0b22e6", "size": 12416, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/cartesian_pose_control.cc", "max_stars_repo_name": "stanford-iprl-lab/franka-panda-public", "max_stars_repo_head_hexsha": "13b8e7d7400001e1c96c78fef5ecf34c179529f9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-01-15T00:15:06.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-15T09:33:47.000Z", "max_issues_repo_path": "src/cartesian_pose_control.cc", "max_issues_repo_name": "stanford-iprl-lab/franka-panda-public", "max_issues_repo_head_hexsha": "13b8e7d7400001e1c96c78fef5ecf34c179529f9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/cartesian_pose_control.cc", "max_forks_repo_name": "stanford-iprl-lab/franka-panda-public", "max_forks_repo_head_hexsha": "13b8e7d7400001e1c96c78fef5ecf34c179529f9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-01-21T22:32:24.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-21T22:32:24.000Z", "avg_line_length": 37.1736526946, "max_line_length": 126, "alphanum_fraction": 0.6461823454, "num_tokens": 4134, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6513548646660543, "lm_q2_score": 0.5350984286266115, "lm_q1q2_score": 0.34853896456110484}}
{"text": "// Functions for computing scores that assess the significance of TCR clusters\n// Z_CO and S_size in the terminology of the original manuscript\n//\n\n#ifndef INCLUDED_pubtcrs_cluster_scores_HH\n#define INCLUDED_pubtcrs_cluster_scores_HH\n\n#include <boost/math/distributions/binomial.hpp>\n\n#include \"misc.hh\"\n#include \"randutil.hh\"\n\n\n////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n//\n// both lists should sum to the same thing: the sum of the subject counts for all the tcrs in the cluster\n//\n//\nReal // return the best score\nscore_l1_versus_l2(\n\tReals const & l1,  // should be sorted\n\tReals const & l2,  // -- ditto --\n\tSize & min_switchpoint // for i <= min_switchpoint, score += l1[i] - l2[i];\n) //                            i >  min_switchpoint, score += l2[i] - l2[i];\n{\n\tReal const epsilon( 1e-4 );\n\n\truntime_assert( l1.front() >= l1.back()-epsilon ); // silly check for sorted\n\truntime_assert( l2.front() >= l2.back()-epsilon ); // ditto\n\n\tSize const nsubjects( l2.size() );\n\n\truntime_assert( l1.size() == nsubjects );\n\n\tReals total_l1_minus_l2;\n\n\tReal total(0);\n\tfor ( Size i=0; i< nsubjects; ++i ) {\n\t\ttotal += l1[i] - l2[i];\n\t\ttotal_l1_minus_l2.push_back( total );\n\t}\n\n\truntime_assert( fabs( total_l1_minus_l2[ nsubjects-1 ] - 0.0 )<epsilon );\n\n\tReal best_score( 0.0 ), score;\n\tmin_switchpoint = nsubjects-1; // this should give a score of 0.0\n\n\ttotal=0.;\n\n\tfor ( Size i=nsubjects-1; i > 0; --i ) {\n\t\ttotal += l2[i] - l1[i];\n\t\t// this is the score if min_switchpoint were i-1:\n\t\tscore = total_l1_minus_l2[ i-1 ] + total;\n\t\tif ( score >= best_score - epsilon ) { // choose smaller switchpoints with equal scores\n\t\t\tbest_score = score;\n\t\t\tmin_switchpoint = i-1;\n\t\t}\n\t}\n\n\treturn best_score;\n\n}\n\n////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\nReal // return diff_Zscore\nanalyze_cluster_occurrences(\n\tSizes const & tcrs,\n\tvector< bools > const & all_occs, // could be just intra-HLA occs\n\tSizes const & subject_indices, // for output, eg might be: ( hla_positive_subjects.find(hla)->second ) );\n\tReals const & subject_sampling_bias,\n\tSize const nrep,\n\tstring const tag, // empty for classic output\n\tSize & upper_tcr_count,\n\tSize & lower_tcr_count,\n\tostream & out\n)\n{\n\tSize const total_subjects( all_occs.front().size() );\n\truntime_assert( subject_sampling_bias.size() == total_subjects );\n\truntime_assert( subject_indices.size() == total_subjects );\n\n\tReals avg_counts( total_subjects, 0. );\n\tReal diff_score_mean, diff_score_sdev;\n\n\tbools chosen( total_subjects ); // re-use this array\n\tSizes counts( total_subjects );\n\tReals realcounts( total_subjects );\n\n\n\tReals rand_diff_scores;\n\n\t// go through this loop 2*nrep times, building up the average the first time, then comparing the counts\n\t// \tto the average the second time, so we can get a Z-score for the observed counts\n\tfor ( Size rep=1; rep<= 2*nrep; ++rep ) {\n\t\tstd::fill( counts.begin(), counts.end(), Size(0) );\n\n\t\t// randomly choose tcr occurrences\n\t\tforeach_( Size t, tcrs ) {\n\t\t\tSize num_subjects_this_tcr(0);\n\t\t\tforeach_( bool occ, all_occs[t] ) { if ( occ ) ++num_subjects_this_tcr; }\n\t\t\tif ( num_subjects_this_tcr ) {\n\t\t\t\tchoose_random_subjects_with_bias( num_subjects_this_tcr, subject_sampling_bias, chosen );\n\t\t\t\tfor ( Size i=0; i< total_subjects; ++i ) {\n\t\t\t\t\tif ( chosen[i] ) ++counts[i];\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tsort( counts.begin(), counts.end() ); // increasing order\n\t\tstd::reverse( counts.begin(), counts.end() ); // now decreasing order\n\n\t\tif ( rep <= nrep ) {\n\t\t\tfor ( Size i=0; i< total_subjects; ++i ) avg_counts[i] += counts[i];\n\n\t\t\tif ( rep == nrep ) { // normalize avg scores, write them out\n\t\t\t\tfor ( Size i=0; i< total_subjects; ++i ) avg_counts[i] /= nrep;\n\t\t\t\tout << \"avg_subject_tcr_counts\" << tag << \": total_subjects= \" << total_subjects;\n\t\t\t\tfor ( Size i=0; i< total_subjects; ++i ) out << ' ' << F(9,3,avg_counts[i]);\n\t\t\t\tout << '\\n';\n\t\t\t}\n\t\t} else {\n\t\t\t/// score our counts against avg_counts\n\t\t\tfor ( Size i=0; i< total_subjects; ++i ) realcounts[i] = Real(counts[i]);\n\n\t\t\tSize tmp_switchpoint;\n\t\t\tReal pos_score( score_l1_versus_l2( realcounts, avg_counts, tmp_switchpoint ) ),\n\t\t\t\tneg_score( score_l1_versus_l2( avg_counts, realcounts, tmp_switchpoint ) );\n\n\t\t\tif ( pos_score > neg_score ) {\n\t\t\t\trand_diff_scores.push_back( pos_score );\n\t\t\t} else {\n\t\t\t\trand_diff_scores.push_back( -1 * neg_score );\n\t\t\t}\n\t\t\truntime_assert( rand_diff_scores.size() == rep-nrep );\n\t\t}\n\t} // rep=1, 2*nrep\n\truntime_assert( rand_diff_scores.size() == nrep );\n\tget_mean_sdev( rand_diff_scores, diff_score_mean, diff_score_sdev );\n\n\n\tSizes subject_tcr_counts( total_subjects, 0 );\n\tfor ( Size i=0; i< tcrs.size(); ++i ) {\n\t\tbools const & i_occs( all_occs[ tcrs[i] ] );\n\t\tfor ( Size k=0; k< total_subjects; ++k ) {\n\t\t\tif ( i_occs[k] ) ++subject_tcr_counts[k];\n\t\t}\n\t}\n\tSizePairs countslist;\n\tSize num_nonzero(0);\n\tfor ( Size k=0; k< total_subjects; ++k ) {\n\t\tif ( subject_tcr_counts[k]>0 ) ++num_nonzero;\n\t\tcountslist.push_back( make_pair( subject_tcr_counts[k], k ) );\n\t}\n\tsort( countslist.begin(), countslist.end () );\n\treverse( countslist.begin(), countslist.end () );\n\n\t//Reals realcounts( total_subjects, 0.0 );\n\tfor ( Size i=0; i< total_subjects; ++i ) {\n\t\trealcounts[i] = countslist[i].first;\n\t}\n\n\tSize pos_switchpoint, neg_switchpoint;\n\tReal pos_score( score_l1_versus_l2( realcounts, avg_counts, pos_switchpoint ) ),\n\t\tneg_score( score_l1_versus_l2( avg_counts, realcounts, neg_switchpoint ) ),\n\t\tdiff_score( pos_score>neg_score ? pos_score : -1*neg_score ),\n\t\tdiff_Zscore( ( diff_score - diff_score_mean )/ diff_score_sdev );\n\n\tupper_tcr_count = countslist[ pos_switchpoint ].first;\n\tlower_tcr_count = ( pos_switchpoint < total_subjects ? countslist[ pos_switchpoint+1 ].first : 0 );\n\n\n\tout << \"subject_tcr_counts\" << tag << \": total_subjects= \" << total_subjects <<\n\t\t\" num_nonzero_tcr_counts: \" << num_nonzero <<\n\t\t\" D_CO: \" << F(9,3,diff_score) <<\n\t\t\" Z_CO: \" << F(9,3,diff_Zscore) <<\n\t\t\" D_CO_rand_mean: \" << F(9,3,diff_score_mean) <<\n\t\t\" D_CO_rand_sdev: \" << F(9,3,diff_score_sdev) <<\n\t\t\" pos_switchpoint: \" << pos_switchpoint <<\n\t\t\" upper_tcr_count: \" << upper_tcr_count <<\n\t\t\" lower_tcr_count: \" << lower_tcr_count;\n\t// Sizes const & hla_subs( hla_positive_subjects.find(hla)->second );\n\t// runtime_assert( hla_subs.size() == total_subjects );\n\tfor ( Size k=0; k< total_subjects; ++k ) {\n\t\tif ( countslist[k].first == 0 ) break; // don't show the zeros\n\t\tSize const subject( subject_indices[ countslist[k].second ] );\n\t\tout << ' ' << subject << ':' << countslist[k].first;\n\t\t\t//<< ':' << subject_sampling_bias[ countslist[k].second ]; // now show the bias...\n\t}\n\tout << '\\n';\n\n\treturn diff_Zscore;\n}\n\n////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n//\n// returns 1 if we don't have info for this (similarity_mode,nbr_pval_threshold)\n//\n//\n// probability of seeing an equal or greater number of neighbors for a random TCR, given num_clustered_tcrs\n//\nReal\ncompute_cluster_size_score(\n\tSize const num_center_nbrs, // max nbr number for cluster member\n\tSize const num_clustered_tcrs,\n\tSize const similarity_mode,\n\tReal const nbr_pval_threshold\n)\n{\n\tusing namespace boost::math;\n\tstatic bool init( false );\n\tstatic map< pair<Size,Real>, Reals > precomputed_nbr_rates;\n\n\tif ( !init ) {\n\t\tinit = true;\n\t\tstring const filename( misc::dbdir + \"nbr_rates_for_P_size_calc.txt\" );\n\t\tstrings lines;\n\t\tread_lines_from_file( filename, lines );\n\t\tforeach_( string line, lines ) {\n\t\t\tistringstream l(line);\n\t\t\tstring tmp;\n\t\t\tSize l_sim_mode;\n\t\t\tReal l_nbr_pval_threshold;\n\t\t\tl >> tmp >> l_sim_mode >> tmp >> l_nbr_pval_threshold >> tmp;\n\t\t\tReals nbr_rates;\n\t\t\twhile ( !l.fail() ) {\n\t\t\t\tReal rate;\n\t\t\t\tl >> rate;\n\t\t\t\tif ( !l.fail() ) nbr_rates.push_back( rate );\n\t\t\t}\n\t\t\tcout << \"Read \" << nbr_rates.size() << \" precomputed_nbr_rates for similarity_mode: \" << l_sim_mode <<\n\t\t\t\t\" and nbr_pval_threshold: \" << l_nbr_pval_threshold << endl;\n\t\t\tprecomputed_nbr_rates[ make_pair( l_sim_mode, l_nbr_pval_threshold ) ] = nbr_rates;\n\t\t}\n\t}\n\n\tReals nbr_rates;\n\n\tif ( similarity_mode == 1 ) {\n\t\tnbr_rates.push_back( nbr_pval_threshold );\n\t} else { // look for info in the file\n\t\tfor ( map< pair<Size,Real>, Reals >::const_iterator it= precomputed_nbr_rates.begin();\n\t\t\t\t\tit!= precomputed_nbr_rates.end(); ++it ) {\n\t\t\tif ( it->first.first == similarity_mode && fabs( log( it->first.second ) - log( nbr_pval_threshold ) )<.1 ) {\n\t\t\t\t// match\n\t\t\t\tnbr_rates = it->second;\n\t\t\t}\n\t\t}\n\t}\n\n\tif ( nbr_rates.empty() ) {\n\t\tcerr << \"Failed to find precomputed information for computing cluster size score:: \" <<\n\t\t\t\" similarity_mode: \" << similarity_mode << \" nbr_pval_threshold: \" << nbr_pval_threshold << endl;\n\t\treturn 1.0;\n\t}\n\n\t//\n\tReal P_size(0); // odds of seeing an equal or greater neighbor number, given the total number of tcrs clustered\n\n\tReal const wt( 1.0/ nbr_rates.size() );\n\tforeach_( Real rate, nbr_rates ) {\n\t\tP_size += wt * cdf( complement( binomial( num_clustered_tcrs-1, rate ), num_center_nbrs-1 ) );\n\t}\n\n\treturn P_size;\n}\n\n#endif\n", "meta": {"hexsha": "6994a3d0d8961ef2faca5681ef9be08c7b9129b9", "size": 9119, "ext": "hh", "lang": "C++", "max_stars_repo_path": "src/cluster_scores.hh", "max_stars_repo_name": "wangshun1121/pubtcrs", "max_stars_repo_head_hexsha": "779ceca2e19c03d5172010527da8d7bf9c8d5923", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/cluster_scores.hh", "max_issues_repo_name": "wangshun1121/pubtcrs", "max_issues_repo_head_hexsha": "779ceca2e19c03d5172010527da8d7bf9c8d5923", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/cluster_scores.hh", "max_forks_repo_name": "wangshun1121/pubtcrs", "max_forks_repo_head_hexsha": "779ceca2e19c03d5172010527da8d7bf9c8d5923", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.026119403, "max_line_length": 120, "alphanum_fraction": 0.6504002632, "num_tokens": 2610, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6513548511303338, "lm_q2_score": 0.5350984286266115, "lm_q1q2_score": 0.34853895731816203}}
{"text": "#include <iostream>\n#include <fstream>\n#include <cmath>\n#include \"CftData.h\"\n#include \"common.h\"\n#include <boost/math/special_functions/gamma.hpp>\n\nstd::ostream& operator<< (std::ostream& out, const CftConfig& config)\n{\n    out << \"{D=\" << config.D << \", OperatorNumbers=\" << config.OperatorNumbers << '}';\n    return out;\n}\n\nCftData::CftData(CftConfig config)\n{\n    this->D = config.D;\n    this->opsNumbers = config.OperatorNumbers;\n    GenerateRandomData();\n}\n\nvoid CftData::GenerateRandomData()\n{\n    // clear the data.\n    ops.clear();\n    opeCoefs.clear();\n\n    // add Identity operator.\n    ops.push_back(PrimaryInfo(0, 0, 0));\n\n    int id = 0;\n    for (uint i = 0; i < this->opsNumbers.size(); i++) {\n        float_type lastDim = .0;\n        float_type gap;\n\n        // the unitary bound.\n        if (i == 0) {\n            gap = this->D / 2.0 - 1;\n        } else {\n            gap = i + this->D - 2.0;\n        }\n\n        for (int j = 0; j < this->opsNumbers[i]; j++) {\n            double dim;\n            id++;\n            // for stress tensor\n            if (i == 2 && j == 0) {\n                dim = (double)this->D;\n            } else {\n                // randomly set scaling dimsion for primaries except for that\n                // scaling dimesions increase with id.\n                dim = lastDim + gap + random(0, .2);\n            }\n\n            gap = .8;\n\n            ops.push_back(PrimaryInfo(id, dim, i));\n            lastDim = dim;\n        }\n    }\n\n    // randomly generate OPE coefficients for three scalars operators and two scalars and one spinning operators..\n    for (int i = 1; i <= this->opsNumbers[0]; i++) {\n        for (int j = i; j <= this->opsNumbers[0]; j++) {\n            for (uint k = j; k <= this->ops.size(); k++) {\n                SetOpeCoefficient(this->ops[i].Id, this->ops[j].Id, this->ops[k].Id, random(-5.0, 5.0));\n            }\n        }\n    }\n\n    SetFixedCftData();\n}\n\nvoid CftData::SetFixedCftData()\n{\n    maxPrimaryId = Sum(opsNumbers);\n    this->StressTensorId = opsNumbers[0] + opsNumbers[1] + 1;\n\n    // normalize OPE coefficients of two identitical scalars to identity operator or stress tensor.\n    // for identity operator the OPE coefficients are 1.\n    // for stress tensor, it is -d * Dim/(d-1)  * 1/S_d, where S_d is is the volumn of the unit sphere S^(d-1).\n    float_type Pi = acos(-1.0);\n    for (int i = 0; i <= opsNumbers[0]; i++) {\n        SetOpeCoefficient(i, i, 0, 1.0);\n        if (i > 0) {\n            double coef = -D * GetPrimaryDim(i) / (D - 1);\n            double sd = 2 * pow(Pi, D/2.0) / boost::math::tgamma<float_type>(D/2.0);\n            SetOpeCoefficient(i, i, StressTensorId, coef / sd);\n        }\n\n        for (int j = i + 1; j <= opsNumbers[0]; j++) {\n            SetOpeCoefficient(i, j, 0, 0.0);\n            SetOpeCoefficient(i, j, StressTensorId, 0.0);\n        }\n    }\n}\n\nPrimaryInfo CftData::GetPrimaryInfo(int id) const\n{\n    return this->ops[id];\n}\n\nvoid CftData::SetPrimaryDim(int id, double dim)\n{\n    this->ops[id].Dim = dim;\n}\n\nint CftData::PrimaryNumber(int spin) const\n{\n    return this->opsNumbers[spin];\n}\n\nfloat_type CftData::GetOpeCoefficient(int id1, int id2, int id3)\n{\n    return this->opeCoefs[OpeCoefficientKey(id1, id2, id3)];\n}\n\nfloat_type CftData::GetOpeCoefficient(OpeCoefficientKey& key)\n{\n    return this->opeCoefs[key];\n}\n\nvoid CftData::SetOpeCoefficient(int id1, int id2, int id3, float_type coef)\n{\n    this->opeCoefs[OpeCoefficientKey(id1, id2, id3)] = coef;\n}\n\nvoid CftData::SetOpeCoefficient(OpeCoefficientKey& key, float_type coef)\n{\n    this->opeCoefs[key] = coef;\n}\n\nvoid CftData::Output(vector<int> ops)\n{\n    std::cout << \"Dimensions of operators\" << std::endl;\n    for (uint i = 0; i < ops.size(); i++) {\n        std::cout << ops[i] << \":\\t\" << GetPrimaryDim(ops[i]) << std::endl;\n    }\n\n    std::cout << std::endl << \"OPE coefficients: \" << std::endl;\n\n    int count = 0;\n\n    for (uint i = 0; i < ops.size(); i++) {\n        for (uint j = i; j < ops.size(); j++) {\n            for (uint k = j; k < ops.size(); k++) {\n                std::cout << '(' << ops[i] << ',' << ops[j] << ',' << ops[k] << \"): \";\n                std::cout << GetOpeCoefficient(ops[i], ops[j], ops[k]) << \"\\t\";\n                count++;\n                if (count % 5 == 0) std::cout << endl;\n            }\n        }\n    }\n    std::cout << std::endl;\n}\n\nvoid CftData::Save(string file)\n{\n    ofstream out(file);\n    out << this->D << ' ' << this->opsNumbers.size() << std::endl;\n\n    out << \"OperatorNubmers:\" << std::endl;\n    for (uint i = 0; i < this->opsNumbers.size(); i++) {\n        if (i > 0) out << ' ';\n        out << opsNumbers[i];\n    }\n    out << std::endl;\n    \n    out << \"ScalingDimensions:\" << std::endl;\n    for (uint i = 1; i < ops.size(); i++) {\n        if (i > 1) out << ' ';\n        out << setprecision(15) << ops[i].Dim;\n    }\n    out << std::endl;\n\n    out << \"OpeCoefficients:\" << std::endl;\n    for (int i = 1; i <= this->opsNumbers[0]; i++) {\n        for (int j = i; j <= this->opsNumbers[0]; j++) {\n            for (uint k = j; k < this->ops.size(); k++) {\n                if (k == StressTensorId) continue;\n                out << i << ' ' << j << ' ' << k << ' ' << setprecision(15) << GetOpeCoefficient(i, j, k) << std::endl;\n            }\n        }\n    }\n\n    out.close();\n}\n\nvoid CftData::LoadFromFile(string file)\n{\n    ifstream in(file);\n    int spinNumber;\n    string buf;\n    in >> this->D >> spinNumber;\n    this->opsNumbers.resize(spinNumber, 0);\n\n    in >> buf;\n    for (int i = 0; i < spinNumber; i++) {\n        in >> opsNumbers[i];\n    }\n    \n    in >> buf;\n\n    int id = 0;\n    float_type dim;\n    ops.clear();\n    ops.push_back(PrimaryInfo(id, 0.0, 0));\n    for (int spin = 0; spin < spinNumber; spin++) {\n        for (int i = 0; i < opsNumbers[spin]; i++) {\n            in >> dim;\n            ops.push_back(PrimaryInfo(++id, dim, spin));\n        }\n    }\n\n    in >> buf;\n\n    int op1, op2, op3;\n    float_type coef;\n    while(!in.eof()) {\n        in >> op1 >> op2 >> op3 >> coef;\n        if (!in.good()) break;\n        SetOpeCoefficient(op1, op2, op3, coef);\n    }\n\n    in.close();\n\n    SetFixedCftData();\n}\n\n", "meta": {"hexsha": "2c1574ca26761ec4e9093bbf33e91e3d67fdff62", "size": 6139, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/CftData.cpp", "max_stars_repo_name": "gaolichen/cftbtsp", "max_stars_repo_head_hexsha": "e764b6ca339d6d68a5c6b6acd9f58ef64c628d47", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/CftData.cpp", "max_issues_repo_name": "gaolichen/cftbtsp", "max_issues_repo_head_hexsha": "e764b6ca339d6d68a5c6b6acd9f58ef64c628d47", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/CftData.cpp", "max_forks_repo_name": "gaolichen/cftbtsp", "max_forks_repo_head_hexsha": "e764b6ca339d6d68a5c6b6acd9f58ef64c628d47", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.807860262, "max_line_length": 119, "alphanum_fraction": 0.5214204268, "num_tokens": 1841, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7025300573952054, "lm_q2_score": 0.49609382947091946, "lm_q1q2_score": 0.34852082649161226}}
{"text": "/*********************************************************************************\n *  OKVIS - Open Keyframe-based Visual-Inertial SLAM\n *  Copyright (c) 2015, Autonomous Systems Lab / ETH Zurich\n *\n *  Redistribution and use in source and binary forms, with or without\n *  modification, are permitted provided that the following conditions are met:\n *\n *   * Redistributions of source code must retain the above copyright notice,\n *     this list of conditions and the following disclaimer.\n *   * Redistributions in binary form must reproduce the above copyright notice,\n *     this list of conditions and the following disclaimer in the documentation\n *     and/or other materials provided with the distribution.\n *   * Neither the name of Autonomous Systems Lab / ETH Zurich nor the names of\n *     its contributors may be used to endorse or promote products derived from\n *     this software without specific prior written permission.\n *\n *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n *  AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n *  IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n *  ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\n *  LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n *  CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n *  SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n *  INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n *  CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n *  ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n *  POSSIBILITY OF SUCH DAMAGE.\n *\n *  Created on: Feb 3, 2015\n *      Author: Stefan Leutenegger (s.leutenegger@imperial.ac.uk)\n *********************************************************************************/\n\n/**\n * @file implementation/EquidistantDistortion.hpp\n * @brief Header implementation file for the EquidistantDistortion class.\n * @author Stefan Leutenegger\n */\n\n\n#include <Eigen/LU>\n#include <iostream>\n\n/// \\brief okvis Main namespace of this package.\nnamespace vio {\n/// \\brief cameras Namespace for camera-related functionality.\nnamespace cameras {\n    int FTR_UNDIST_DL_MAX_ITERATIONS              = 10;\n    float FTR_UNDIST_DL_RADIUS_INITIAL              = 1.0f;      // 1.0^2\n    float FTR_UNDIST_DL_RADIUS_MIN                  = 1.0e-10f;  // 0.00001^2\n    float FTR_UNDIST_DL_RADIUS_MAX                  = 1.0e4f;    // 100.0^2\n    float FTR_UNDIST_DL_RADIUS_FACTOR_INCREASE      = 9.0f;      // 3.0^2\n    float FTR_UNDIST_DL_RADIUS_FACTOR_DECREASE      = 0.25f;     // 0.5^2\n    float FTR_UNDIST_DL_GAIN_RATIO_MIN              = 0.25f;\n    float FTR_UNDIST_DL_GAIN_RATIO_MAX              = 0.75f;\n// The default constructor with all zero ki\nEquidistantDistortion::EquidistantDistortion()\n        : k1_(0.0),\n          k2_(0.0),\n          k3_(0.0),\n          k4_(0.0)\n{\n    parameters_.setZero();\n}\n\n// Constructor initialising ki\nEquidistantDistortion::EquidistantDistortion(float k1, float k2, float k3,\n                                             float k4)\n{\n    parameters_[0] = k1;\n    parameters_[1] = k2;\n    parameters_[2] = k3;\n    parameters_[3] = k4;\n    k1_ = k1;\n    k2_ = k2;\n    k3_ = k3;\n    k4_ = k4;\n}\n\nbool EquidistantDistortion::setParameters(const Eigen::VectorXd & parameters)\n{\n    if (parameters.cols() != NumDistortionIntrinsics) {\n        return false;\n    }\n    parameters_ = parameters.cast<float>();;\n    k1_ = parameters[0];\n    k2_ = parameters[1];\n    k3_ = parameters[2];\n    k4_ = parameters[3];\n    return true;\n}\n\nbool EquidistantDistortion::distort(const Eigen::Vector2d & pointUndistorted,\n                                    Eigen::Vector2d * pointDistorted) const\n{\n    // distortion only:\n    const float u0 = pointUndistorted[0];\n    const float u1 = pointUndistorted[1];\n    const float r = sqrt(u0 * u0 + u1 * u1);\n    const float theta = atan(r);\n    const float theta2 = theta * theta;\n    const float theta4 = theta2 * theta2;\n    const float theta6 = theta4 * theta2;\n    const float theta8 = theta4 * theta4;\n    const float thetad = theta\n                          * (1 + k1_ * theta2 + k2_ * theta4 + k3_ * theta6 + k4_ * theta8);\n\n    const float scaling = (r > 1e-8) ? thetad / r : 1.0;\n    (*pointDistorted)[0] = scaling * u0;\n    (*pointDistorted)[1] = scaling * u1;\n    return true;\n}\n\nbool EquidistantDistortion::distort(const Eigen::Vector2f & pointUndistorted,\n                                    Eigen::Vector2f * pointDistorted) const\n{\n    // distortion only:\n    const float u0 = pointUndistorted[0];\n    const float u1 = pointUndistorted[1];\n    const float r = sqrt(u0 * u0 + u1 * u1);\n    const float theta = atan(r);\n    const float theta2 = theta * theta;\n    const float theta4 = theta2 * theta2;\n    const float theta6 = theta4 * theta2;\n    const float theta8 = theta4 * theta4;\n    const float thetad = theta\n                         * (1 + k1_ * theta2 + k2_ * theta4 + k3_ * theta6 + k4_ * theta8);\n\n    const float scaling = (r > 1e-8) ? thetad / r : 1.0;\n    (*pointDistorted)[0] = scaling * u0;\n    (*pointDistorted)[1] = scaling * u1;\n    return true;\n}\n\nbool EquidistantDistortion::distort(const Eigen::Vector2d & pointUndistorted,\n                                    Eigen::Vector2d * pointDistorted,\n                                    Eigen::Matrix2d * pointJacobian,\n                                    Eigen::Matrix2Xd * parameterJacobian) const\n{\n    // distortion first:\n    const float u0 = pointUndistorted[0];\n    const float u1 = pointUndistorted[1];\n    const float r = sqrt(u0 * u0 + u1 * u1);\n    const float theta = atan(r);\n    const float theta2 = theta * theta;\n    const float theta4 = theta2 * theta2;\n    const float theta6 = theta4 * theta2;\n    const float theta8 = theta4 * theta4;\n    const float thetad = theta\n                          * (1 + k1_ * theta2 + k2_ * theta4 + k3_ * theta6 + k4_ * theta8);\n\n    const float scaling = (r > 1e-8) ? thetad / r : 1.0;\n    (*pointDistorted)[0] = scaling * u0;\n    (*pointDistorted)[1] = scaling * u1;\n\n    Eigen::Matrix2d & J = *pointJacobian;\n    if (r > 1e-8) {\n        // mostly matlab generated...\n        float t2;\n        float t3;\n        float t4;\n        float t6;\n        float t7;\n        float t8;\n        float t9;\n        float t11;\n        float t17;\n        float t18;\n        float t19;\n        float t20;\n        float t25;\n\n        t2 = u0 * u0;\n        t3 = u1 * u1;\n        t4 = t2 + t3;\n        t6 = atan(sqrt(t4));\n        t7 = t6 * t6;\n        t8 = 1.0 / sqrt(t4);\n        t9 = t7 * t7;\n        t11 = 1.0 / ((t2 + t3) + 1.0);\n        t17 = (((k1_ * t7 + k2_ * t9) + k3_ * t7 * t9) + k4_ * (t9 * t9)) + 1.0;\n        t18 = 1.0 / t4;\n        t19 = 1.0 / sqrt(t4 * t4 * t4);\n        t20 = t6 * t8 * t17;\n        t25 = ((k2_ * t6 * t7 * t8 * t11 * u1 * 4.0\n                + k3_ * t6 * t8 * t9 * t11 * u1 * 6.0)\n               + k4_ * t6 * t7 * t8 * t9 * t11 * u1 * 8.0)\n              + k1_ * t6 * t8 * t11 * u1 * 2.0;\n        t4 = ((k2_ * t6 * t7 * t8 * t11 * u0 * 4.0\n               + k3_ * t6 * t8 * t9 * t11 * u0 * 6.0)\n              + k4_ * t6 * t7 * t8 * t9 * t11 * u0 * 8.0)\n             + k1_ * t6 * t8 * t11 * u0 * 2.0;\n        t7 = t11 * t17 * t18 * u0 * u1;\n        J(0, 1) = (t7 + t6 * t8 * t25 * u0) - t6 * t17 * t19 * u0 * u1;\n        J(1, 1) = ((t20 - t3 * t6 * t17 * t19) + t3 * t11 * t17 * t18)\n                  + t6 * t8 * t25 * u1;\n        J(0, 0) = ((t20 - t2 * t6 * t17 * t19) + t2 * t11 * t17 * t18)\n                  + t6 * t8 * t4 * u0;\n        J(1, 0) = (t7 + t6 * t8 * t4 * u1) - t6 * t17 * t19 * u0 * u1;\n\n        if (parameterJacobian) {\n            Eigen::Matrix2Xd & Ji = *parameterJacobian;\n            Ji.resize(2,NumDistortionIntrinsics);\n            // mostly matlab generated...\n            float t6;\n            float t2;\n            float t3;\n            float t8;\n            float t10;\n\n            t6 = u0 * u0 + u1 * u1;\n            t2 = atan(sqrt(t6));\n            t3 = t2 * t2;\n            t8 = t3 * t3;\n            t6 = 1.0 / sqrt(t6);\n            t10 = t8 * t8;\n            Ji(0, 0) = t2 * t3 * t6 * u0;\n            Ji(1, 0) = t2 * t3 * t6 * u1;\n            Ji(0, 1) = t2 * t8 * t6 * u0;\n            Ji(1, 1) = t2 * t8 * t6 * u1;\n            Ji(0, 2) = t2 * t3 * t8 * t6 * u0;\n            Ji(1, 2) = t2 * t3 * t8 * t6 * u1;\n            Ji(0, 3) = t2 * t6 * t10 * u0;\n            Ji(1, 3) = t2 * t6 * t10 * u1;\n\n        }\n    } else {\n        // handle limit case for [u0,u1]->0\n        if (parameterJacobian) {\n            parameterJacobian->resize(2,NumDistortionIntrinsics);\n            parameterJacobian->setZero();\n        }\n        J.setIdentity();\n    }\n\n    return true;\n}\n\n\nbool EquidistantDistortion::distort(const Eigen::Vector2f & pointUndistorted,\n                                    Eigen::Vector2f* pointDistorted,\n                                    Eigen::Matrix2f * pointJacobian,\n                                    Eigen::Matrix2Xf * parameterJacobian) const\n{\n\n\n    ////针对k1,k2,k2,k3的等距投影模型, r^2 = x^2 + y^2\n    ////残差2*1 归一化坐标的2维： min F(x,y) = 0.5*r(x,y)^2 约束： x^2+y^2 <=\n    ///      r.x = x*(theta*(1 + k1*theta^2 + k2*theta^4 + k3 *theta^6 + k4*theta^8)/r) - x0\n    ////     r.x = y*(theta*(1 + k1*theta^2 + k2*theta^4 + k3 *theta^6 + k4*theta^8)/r) - y0\n    // distortion first:\n    const float u0 = pointUndistorted[0];//x\n    const float u1 = pointUndistorted[1];//y\n    const float r = sqrt(u0 * u0 + u1 * u1);//r = sqrt(x^2 + y^2)\n    const float theta = atan(r);\n    const float theta2 = theta * theta;\n    const float theta4 = theta2 * theta2;\n    const float theta6 = theta4 * theta2;\n    const float theta8 = theta4 * theta4;\n    const float thetad = theta\n                         * (1 + k1_ * theta2 + k2_ * theta4 + k3_ * theta6 + k4_ * theta8);\n\n    const float scaling = (r > 1e-8) ? thetad / r : 1.0;\n    (*pointDistorted)[0] = scaling * u0;\n    (*pointDistorted)[1] = scaling * u1;\n\n    Eigen::Matrix2f & J = *pointJacobian;\n    if (r > 1e-8) {\n        // mostly matlab generated...\n        float t2;//x^2\n        float t3;//y^2\n        float t4;//r^2 = x^2+y^2\n        float t6;//theta\n        float t7;//theta^2\n        float t8;// 1/r\n        float t9;//theta^4\n        float t11;// 1 / ((x^2+y^2) + 1.0);\n        float t17;// (((k1_ * theta^2 + k2_ * theta^4) + k3_ * t7 * t9) + k4_ * (t9 * t9)) + 1.0\n        float t18;\n        float t19;\n        float t20;\n        float t25;\n\n        t2 = u0 * u0;\n        t3 = u1 * u1;\n        t4 = t2 + t3;\n        t6 = atan(sqrt(t4));\n        t7 = t6 * t6;\n        t8 = 1.0 / sqrt(t4);\n        t9 = t7 * t7;\n        t11 = 1.0 / ((t2 + t3) + 1.0);\n        t17 = (((k1_ * t7 + k2_ * t9) + k3_ * t7 * t9) + k4_ * (t9 * t9)) + 1.0;\n        t18 = 1.0 / t4;\n        t19 = 1.0 / sqrt(t4 * t4 * t4);\n        t20 = t6 * t8 * t17;\n        t25 = ((k2_ * t6 * t7 * t8 * t11 * u1 * 4.0\n                + k3_ * t6 * t8 * t9 * t11 * u1 * 6.0)\n               + k4_ * t6 * t7 * t8 * t9 * t11 * u1 * 8.0)\n              + k1_ * t6 * t8 * t11 * u1 * 2.0;\n        t4 = ((k2_ * t6 * t7 * t8 * t11 * u0 * 4.0\n               + k3_ * t6 * t8 * t9 * t11 * u0 * 6.0)\n              + k4_ * t6 * t7 * t8 * t9 * t11 * u0 * 8.0)\n             + k1_ * t6 * t8 * t11 * u0 * 2.0;\n        t7 = t11 * t17 * t18 * u0 * u1;\n        J(0, 1) = (t7 + t6 * t8 * t25 * u0) - t6 * t17 * t19 * u0 * u1;\n        J(1, 1) = ((t20 - t3 * t6 * t17 * t19) + t3 * t11 * t17 * t18)\n                  + t6 * t8 * t25 * u1;\n        J(0, 0) = ((t20 - t2 * t6 * t17 * t19) + t2 * t11 * t17 * t18)\n                  + t6 * t8 * t4 * u0;\n        J(1, 0) = (t7 + t6 * t8 * t4 * u1) - t6 * t17 * t19 * u0 * u1;\n\n        if (parameterJacobian) {\n            Eigen::Matrix2Xf & Ji = *parameterJacobian;\n            Ji.resize(2,NumDistortionIntrinsics);\n            // mostly matlab generated...\n            float t6;\n            float t2;\n            float t3;\n            float t8;\n            float t10;\n\n            t6 = u0 * u0 + u1 * u1;\n            t2 = atan(sqrt(t6));\n            t3 = t2 * t2;\n            t8 = t3 * t3;\n            t6 = 1.0 / sqrt(t6);\n            t10 = t8 * t8;\n            Ji(0, 0) = t2 * t3 * t6 * u0;\n            Ji(1, 0) = t2 * t3 * t6 * u1;\n            Ji(0, 1) = t2 * t8 * t6 * u0;\n            Ji(1, 1) = t2 * t8 * t6 * u1;\n            Ji(0, 2) = t2 * t3 * t8 * t6 * u0;\n            Ji(1, 2) = t2 * t3 * t8 * t6 * u1;\n            Ji(0, 3) = t2 * t6 * t10 * u0;\n            Ji(1, 3) = t2 * t6 * t10 * u1;\n\n        }\n    } else {\n        // handle limit case for [u0,u1]->0\n        if (parameterJacobian) {\n            parameterJacobian->resize(2,NumDistortionIntrinsics);\n            parameterJacobian->setZero();\n        }\n        J.setIdentity();\n    }\n\n    return true;\n}\n\n\nbool EquidistantDistortion::distortWithExternalParameters(\n        const Eigen::Vector2d & pointUndistorted,\n        const Eigen::VectorXd & parameters, Eigen::Vector2d * pointDistorted,\n        Eigen::Matrix2d * pointJacobian, Eigen::Matrix2Xd * parameterJacobian) const\n{\n    // decompose parameters\n\n    const float k1 = parameters[0];\n    const float k2 = parameters[1];\n    const float k3 = parameters[2];\n    const float k4 = parameters[3];\n    // distortion first:\n    const float u0 = pointUndistorted[0];\n    const float u1 = pointUndistorted[1];\n    const float r = sqrt(u0 * u0 + u1 * u1);\n    const float theta = atan(r);\n    const float theta2 = theta * theta;\n    const float theta4 = theta2 * theta2;\n    const float theta6 = theta4 * theta2;\n    const float theta8 = theta4 * theta4;\n    const float thetad = theta\n                          * (1 + k1 * theta2 + k2 * theta4 + k3 * theta6 + k4 * theta8);\n\n    const float scaling = (r > 1e-8) ? thetad / r : 1.0;\n    (*pointDistorted)[0] = scaling * u0;\n    (*pointDistorted)[1] = scaling * u1;\n\n    Eigen::Matrix2d & J = *pointJacobian;\n    if (r > 1e-8) {\n        // mostly matlab generated...\n        float t2;\n        float t3;\n        float t4;\n        float t6;\n        float t7;\n        float t8;\n        float t9;\n        float t11;\n        float t17;\n        float t18;\n        float t19;\n        float t20;\n        float t25;\n\n        t2 = u0 * u0;\n        t3 = u1 * u1;\n        t4 = t2 + t3;\n        t6 = atan(sqrt(t4));\n        t7 = t6 * t6;\n        t8 = 1.0 / sqrt(t4);\n        t9 = t7 * t7;\n        t11 = 1.0 / ((t2 + t3) + 1.0);\n        t17 = (((k1 * t7 + k2 * t9) + k3 * t7 * t9) + k4 * (t9 * t9)) + 1.0;\n        t18 = 1.0 / t4;\n        t19 = 1.0 / sqrt(t4 * t4 * t4);\n        t20 = t6 * t8 * t17;\n        t25 = ((k2 * t6 * t7 * t8 * t11 * u1 * 4.0\n                + k3 * t6 * t8 * t9 * t11 * u1 * 6.0)\n               + k4 * t6 * t7 * t8 * t9 * t11 * u1 * 8.0)\n              + k1 * t6 * t8 * t11 * u1 * 2.0;\n        t4 = ((k2 * t6 * t7 * t8 * t11 * u0 * 4.0\n               + k3 * t6 * t8 * t9 * t11 * u0 * 6.0)\n              + k4 * t6 * t7 * t8 * t9 * t11 * u0 * 8.0)\n             + k1 * t6 * t8 * t11 * u0 * 2.0;\n        t7 = t11 * t17 * t18 * u0 * u1;\n        J(0, 0) = (t7 + t6 * t8 * t25 * u0) - t6 * t17 * t19 * u0 * u1;\n        J(1, 0) = ((t20 - t3 * t6 * t17 * t19) + t3 * t11 * t17 * t18)\n                  + t6 * t8 * t25 * u1;\n        J(0, 1) = ((t20 - t2 * t6 * t17 * t19) + t2 * t11 * t17 * t18)\n                  + t6 * t8 * t4 * u0;\n        J(1, 1) = (t7 + t6 * t8 * t4 * u1) - t6 * t17 * t19 * u0 * u1;\n        if (parameterJacobian) {\n            Eigen::Matrix2Xd & Ji = *parameterJacobian;\n            Ji.resize(2,NumDistortionIntrinsics);\n            // mostly matlab generated...\n            float t6;\n            float t2;\n            float t3;\n            float t8;\n            float t10;\n\n            t6 = u0 * u0 + u1 * u1;\n            t2 = atan(sqrt(t6));\n            t3 = t2 * t2;\n            t8 = t3 * t3;\n            t6 = 1.0 / sqrt(t6);\n            t10 = t8 * t8;\n            Ji(0, 0) = t2 * t3 * t6 * u0;\n            Ji(1, 0) = t2 * t3 * t6 * u1;\n            Ji(0, 1) = t2 * t8 * t6 * u0;\n            Ji(1, 1) = t2 * t8 * t6 * u1;\n            Ji(0, 2) = t2 * t3 * t8 * t6 * u0;\n            Ji(1, 2) = t2 * t3 * t8 * t6 * u1;\n            Ji(0, 3) = t2 * t6 * t10 * u0;\n            Ji(1, 3) = t2 * t6 * t10 * u1;\n\n        }\n    } else {\n        // handle limit case for [u0,u1]->0\n        if (parameterJacobian) {\n            parameterJacobian->resize(2,NumDistortionIntrinsics);\n            parameterJacobian->setZero();\n        }\n        J.setIdentity();\n    }\n\n    return true;\n}\nbool EquidistantDistortion::undistort(const Eigen::Vector2d & pointDistorted,\n                                      Eigen::Vector2d * pointUndistorted) const\n{\n    // this is expensive: we solve with Gauss-Newton...\n    Eigen::Vector2d x_bar = pointDistorted;  // initialise at distorted point\n    const int n = 5;  // just 5 iterations max.\n    Eigen::Matrix2d E;  // error Jacobian\n\n    bool success = false;\n    for (int i = 0; i < n; i++) {\n\n        Eigen::Vector2d x_tmp;\n\n        distort(x_bar, &x_tmp, &E);\n\n        Eigen::Vector2d e(pointDistorted - x_tmp);//Hx = b=>\n        Eigen::Vector2d du = (E.transpose() * E).inverse() * E.transpose() * e;\n\n        x_bar += du;\n\n\n        const double chi2 = e.dot(e);\n        if (chi2 < 1e-2) {\n            success = true;\n        }\n        //std::cout<<\"chi2\"<<chi2<<std::endl;\n        if (chi2 < 1e-15) {\n            success = true;\n            break;\n        }\n\n    }\n    *pointUndistorted = x_bar;\n\n    return success;\n}\n\n\nbool EquidistantDistortion::undistort(const Eigen::Vector2f & pointDistorted,\n                                      Eigen::Vector2f * pointUndistorted) const\n{\n\n    float dx2GN/*G-N解出的步长的欧式距离*/, dx2GD/*pU点的欧式距离*/, delta2/*信赖域半径*/, beta;\n    Eigen::Vector2f dxGN/*G-N解出的增量*/, dxGD/*pU点*/;\n    bool update, converge;\n    float dr, j, dx2;\n\n    delta2 = 1.0;\n    // this is expensive: we solve with Gauss-Newton...\n    Eigen::Vector2f x_bar = pointDistorted;  // initialise at distorted point\n    const int n = 30;  // just 5 iterations max.\n    const int UNDIST_DL_MAX_ITERATIONS = 4;\n    Eigen::Matrix2f E;  // error Jacobian\n\n    bool success = false;\n    for (int i = 0; i < n; i++)\n    {\n\n        Eigen::Vector2f x_tmp;\n\n        distort(x_bar, &x_tmp, &E);\n\n        Eigen::Vector2f e(x_tmp -pointDistorted);\n        Eigen::Vector2f dx = -(E.transpose() * E).inverse() * E.transpose() * e;\n        Eigen::Vector2f b = -E.transpose() * e;\n        Eigen::Matrix2f A = -E.transpose() * E;\n\n        x_bar += dx;\n\n//\n//        dx2 = dx.squaredNorm();//x的欧式距离\n//        //by wya\n//       dxGN = dx;//G-N法求出的增量\n//        dx2GN = dx2;//G-N法求出的增量的欧式距离\n//        dx2GD = 0.0f;//dogleg\n//        const float F = e.squaredNorm();//dogleg迭代开始前残差的欧式距离\n//        const Eigen::Vector2f xnBkp = x_bar;//待优化变量\n//        update = true;\n//        converge = false;//狗腿迭代次数\n//        for (int iIterDL = 0; iIterDL < UNDIST_DL_MAX_ITERATIONS; ++iIterDL)\n//        {\n//            if (dx2GN > delta2 && dx2GD == 0.0f) {//如果G-N增量在信赖域外且dx2GD还没有初始化\n//                const float bl = sqrtf(b.squaredNorm());//模长\n//                const Eigen::Vector2f g = b * (1.0f / bl);//梯度方向\n//                const Eigen::Vector2f Ag = A * g;\n//                const float xl = bl / g.dot(Ag);//计算pU点的步长\n//                dxGD = g * -xl;//负梯度*步长,pU点\n//                dx2GD = xl * xl;//pU点的半径\n//\n//            }\n//            //三种情况,1：GN极值点在域内直接变成无约束条件 2:GN和pU点都在域外,那么就在给pU点的步长一个比例因子(域半径/自己的步长^2（因为用的是最小2乘）),让它刚好落在域半径上\n//            //3:GN在域外,pU点在域内,那么增量就是GN极值点和pU点的连线与信赖域的交点\n//            if (dx2GN <= delta2) {//如果G-N的极值在信赖域内,那么就是一个无约束问题,就直接用GN法求出的增量就可以\n//                dx = dxGN;\n//                dx2 = dx2GN;\n//                beta = 1.0f;\n//            } else if (dx2GD >= delta2) {//如果G-N和pU点求的最优点都在信赖域外\n//                if (delta2 == 0.0f) {//信赖域为0,直接用pU点求得最优值\n//                    dx = dxGD;\n//                    dx2 = dx2GD;\n//                } else {\n//                    dx =  dxGD * sqrtf(delta2 / dx2GD);//乘比例因子\n//                    dx2 = delta2;\n//                }\n//                beta = 0.0f;\n//            } else {//GN在域外,pU点在域内,那么增量就是GN极值点和pU点的连线与信赖域的交点\n//                const Eigen::Vector2f v = dxGN - dxGD;//方向\n//                const float d = dxGD.dot(v), v2 = v.squaredNorm();\n//                //beta = float((-d + sqrt(double(d) * d + (delta2 - dx2GD) * double(v2))) / v2);\n//                beta = (-d + sqrtf(d * d + (delta2 - dx2GD) * v2)) / v2;//算得是在域外那段连线的长度\n//                dx = dxGD;\n//                dx += v * beta;\n//                dx2 = delta2;\n//            }\n//            x_bar += dx;//加上这一次的增量\n//            Eigen::Vector2f x_d_temp;\n//            distort(x_bar, &x_d_temp);\n//            const float dFa = F - (x_d_temp - pointDistorted).squaredNorm();//实际下降的\n//            const float dFp = F - (e + ( E.transpose()) * dx).squaredNorm();//理论下降值,直接用J*dx近似下降值了\n//            const float rho = dFa > 0.0f && dFp > 0.0f ? dFa / dFp : -1.0f;//求实际/理论的比值,理论不可能为负,实际为负的时候拒绝这次更新\n//            //信赖域： Numerical Optimization 第二版 p69\n//\n//            //rho < 0.25 如果大于0说明近似的不好,需要减小信赖域,减小近似的范围。如果<0就说明是错误的近似,那么就拒绝这次的增量\n//            if (rho < FTR_UNDIST_DL_GAIN_RATIO_MIN) {\n//                delta2 *= FTR_UNDIST_DL_RADIUS_FACTOR_DECREASE;\n//                if (delta2 < FTR_UNDIST_DL_RADIUS_MIN) {\n//                    delta2 = FTR_UNDIST_DL_RADIUS_MIN;\n//                }\n//                x_bar = xnBkp;//取消这次增量\n//                update = false;//不更新\n//                converge = false;\n//                continue;\n//            } else if (rho > FTR_UNDIST_DL_GAIN_RATIO_MAX) //rho > 0.75,可以扩大信赖域半径\n//            {\n//                delta2 = std::max(delta2, FTR_UNDIST_DL_RADIUS_FACTOR_INCREASE * dx2);\n//                if (delta2 > FTR_UNDIST_DL_RADIUS_MAX) {//信赖域半径最大值\n//                    delta2 = FTR_UNDIST_DL_RADIUS_MAX;\n//                }\n//            }\n//            update = true;//\n//\n//            converge = dx2 < 1e-12;//增量小于阈值,认为收敛\n//            break;\n//        }\n//        if (!update || converge) {\n//            break;\n//        }\n//\n//        const double chi2 = e.dot(e);\n//        if (chi2 < 1e-5) {\n//            success = true;\n//        }\n        const double chi2 = e.dot(e);\n\n        if (chi2 < 1e-8) {\n            success = true;\n            break;\n        }\n\n\n    }\n    *pointUndistorted = x_bar;\n    if(converge)\n        success = true;\n\n\n    return success;\n}\n\nbool EquidistantDistortion::undistort(const Eigen::Vector2d & pointDistorted,\n                                      Eigen::Vector2d * pointUndistorted,\n                                      Eigen::Matrix2d * pointJacobian) const\n{\n    // this is expensive: we solve with Gauss-Newton...\n    Eigen::Vector2d x_bar = pointDistorted;  // initialise at distorted point\n    const int n = 5;  // just 5 iterations max.\n    Eigen::Matrix2d E;  // error Jacobian\n\n    bool success = false;\n    for (int i = 0; i < n; i++) {\n\n        Eigen::Vector2d x_tmp;\n\n        distort(x_bar, &x_tmp, &E);\n\n        Eigen::Vector2d e(pointDistorted - x_tmp);\n        Eigen::Vector2d dx = (E.transpose() * E).inverse() * E.transpose() * e;\n\n        x_bar += dx;\n\n        const double chi2 = e.dot(e);\n        if (chi2 < 1e-2) {\n            success = true;\n        }\n        if (chi2 < 1e-15) {\n            success = true;\n            break;\n        }\n\n    }\n    *pointUndistorted = x_bar;\n\n    // the Jacobian of the inverse map is simply the inverse Jacobian.\n    *pointJacobian = E.inverse();\n\n    return success;\n}\n\nbool EquidistantDistortion::undistort(const Eigen::Vector2f & pointDistorted,\n                                      Eigen::Vector2f * pointUndistorted,\n                                      Eigen::Matrix2f * pointJacobian) const\n{\n    // this is expensive: we solve with Gauss-Newton...\n    Eigen::Vector2f x_bar = pointDistorted;  // initialise at distorted point\n    const int n = 5;  // just 5 iterations max.\n    Eigen::Matrix2f E;  // error Jacobian\n\n    bool success = false;\n    for (int i = 0; i < n; i++) {\n\n        Eigen::Vector2f x_tmp;\n\n        distort(x_bar, &x_tmp, &E);\n\n        Eigen::Vector2f e(pointDistorted - x_tmp);\n        Eigen::Vector2f dx = (E.transpose() * E).inverse() * E.transpose() * e;\n\n        x_bar += dx;\n\n        const double chi2 = e.dot(e);\n        if (chi2 < 1e-2) {\n            success = true;\n        }\n        if (chi2 < 1e-15) {\n            success = true;\n            break;\n        }\n\n    }\n    *pointUndistorted = x_bar;\n\n    // the Jacobian of the inverse map is simply the inverse Jacobian.\n    *pointJacobian = E.inverse();\n\n    return success;\n}\n\n}  // namespace cameras\n}  // namespace okvis\n", "meta": {"hexsha": "dce8d870d0184eca3cdbcfe1b57b3fd4839d0f58", "size": 24689, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Frontend/cameras/implementation/EquidistantDistortion.hpp", "max_stars_repo_name": "wangyuanbiubiubiu/ICE-BA-ros", "max_stars_repo_head_hexsha": "9a3582a2dd1d5ae24115425bdf072864094cfb8e", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 47.0, "max_stars_repo_stars_event_min_datetime": "2020-03-06T10:19:36.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T10:06:37.000Z", "max_issues_repo_path": "Frontend/cameras/implementation/EquidistantDistortion.hpp", "max_issues_repo_name": "wangyuanbiubiubiu/ICE-BA-Annotation", "max_issues_repo_head_hexsha": "9a3582a2dd1d5ae24115425bdf072864094cfb8e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2020-03-06T11:57:05.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-19T01:47:22.000Z", "max_forks_repo_path": "Frontend/cameras/implementation/EquidistantDistortion.hpp", "max_forks_repo_name": "wangyuanbiubiubiu/ICE-BA-Annotation", "max_forks_repo_head_hexsha": "9a3582a2dd1d5ae24115425bdf072864094cfb8e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2020-03-06T10:19:55.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-31T13:23:22.000Z", "avg_line_length": 34.9207920792, "max_line_length": 110, "alphanum_fraction": 0.5004252906, "num_tokens": 8463, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7025300573952052, "lm_q2_score": 0.49609382947091946, "lm_q1q2_score": 0.3485208264916122}}
{"text": "/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */\n\n/*\n Copyright (C) 2008 Andreas Gaida\n Copyright (C) 2008 Ralph Schreyer\n Copyright (C) 2008 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 ninepointlinearop.hpp\n    \\brief nine point linear operator\n*/\n\n#ifndef quantlib_nine_point_linear_op_hpp\n#define quantlib_nine_point_linear_op_hpp\n\n#include <ql/math/matrixutilities/sparsematrix.hpp>\n#include <ql/methods/finitedifferences/operators/fdmlinearop.hpp>\n#if !defined(QL_USE_STD_UNIQUE_PTR)\n#include <boost/shared_array.hpp>\n#endif\n#include <memory>\n\nnamespace QuantLib {\n\n    class FdmMesher;\n\n    class NinePointLinearOp : public FdmLinearOp {\n      public:\n        NinePointLinearOp(Size d0, Size d1,\n                const ext::shared_ptr<FdmMesher>& mesher);\n        NinePointLinearOp(const NinePointLinearOp& m);\n        NinePointLinearOp(NinePointLinearOp&& m) QL_NOEXCEPT;\n        #ifdef QL_USE_DISPOSABLE\n        NinePointLinearOp(const Disposable<NinePointLinearOp>& m);\n        #endif\n        NinePointLinearOp& operator=(const NinePointLinearOp& m);\n        NinePointLinearOp& operator=(NinePointLinearOp&& m) QL_NOEXCEPT;\n        #ifdef QL_USE_DISPOSABLE\n        NinePointLinearOp& operator=(const Disposable<NinePointLinearOp>& m);\n        #endif\n\n        Disposable<Array> apply(const Array& r) const override;\n        Disposable<NinePointLinearOp> mult(const Array& u) const;\n\n        void swap(NinePointLinearOp& m);\n\n        Disposable<SparseMatrix> toMatrix() const override;\n\n      protected:\n        NinePointLinearOp() = default;\n\n        Size d0_, d1_;\n        #if !defined(QL_USE_STD_UNIQUE_PTR)\n        boost::shared_array<Size> i00_, i10_, i20_;\n        boost::shared_array<Size> i01_, i21_;\n        boost::shared_array<Size> i02_, i12_, i22_;\n        boost::shared_array<Real> a00_, a10_, a20_;\n        boost::shared_array<Real> a01_, a11_, a21_;\n        boost::shared_array<Real> a02_, a12_, a22_;\n        #else\n        std::unique_ptr<Size[]> i00_, i10_, i20_;\n        std::unique_ptr<Size[]> i01_, i21_;\n        std::unique_ptr<Size[]> i02_, i12_, i22_;\n        std::unique_ptr<Real[]> a00_, a10_, a20_;\n        std::unique_ptr<Real[]> a01_, a11_, a21_;\n        std::unique_ptr<Real[]> a02_, a12_, a22_;\n        #endif\n\n        ext::shared_ptr<FdmMesher> mesher_;\n    };\n\n\n    inline NinePointLinearOp::NinePointLinearOp(NinePointLinearOp&& m) QL_NOEXCEPT {\n        swap(m);\n    }\n\n    inline NinePointLinearOp& NinePointLinearOp::operator=(const NinePointLinearOp& m) {\n        NinePointLinearOp temp(m);\n        swap(temp);\n        return *this;\n    }\n\n    inline NinePointLinearOp& NinePointLinearOp::operator=(NinePointLinearOp&& m) QL_NOEXCEPT {\n        swap(m);\n        return *this;\n    }\n\n}\n\n#endif\n", "meta": {"hexsha": "f3402f36289fd23d15379fbb9caae095ff1ffd89", "size": 3429, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ql/methods/finitedifferences/operators/ninepointlinearop.hpp", "max_stars_repo_name": "jiangjiali/QuantLib", "max_stars_repo_head_hexsha": "37c98eccfa18a95acb1e98b276831641be92b38e", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 3358.0, "max_stars_repo_stars_event_min_datetime": "2015-12-18T02:56:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T02:42:47.000Z", "max_issues_repo_path": "ql/methods/finitedifferences/operators/ninepointlinearop.hpp", "max_issues_repo_name": "jiangjiali/QuantLib", "max_issues_repo_head_hexsha": "37c98eccfa18a95acb1e98b276831641be92b38e", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 965.0, "max_issues_repo_issues_event_min_datetime": "2015-12-21T10:35:28.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T02:47:00.000Z", "max_forks_repo_path": "ql/methods/finitedifferences/operators/ninepointlinearop.hpp", "max_forks_repo_name": "jiangjiali/QuantLib", "max_forks_repo_head_hexsha": "37c98eccfa18a95acb1e98b276831641be92b38e", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1663.0, "max_forks_repo_forks_event_min_datetime": "2015-12-17T17:45:38.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T07:58:29.000Z", "avg_line_length": 32.9711538462, "max_line_length": 95, "alphanum_fraction": 0.6899970837, "num_tokens": 891, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6757646010190476, "lm_q2_score": 0.5156199157230157, "lm_q1q2_score": 0.34843768662603863}}
{"text": "#include <boost/bind.hpp>\n#include <gazebo/gazebo.hh>\n#include <gazebo/physics/Model.hh>\n#include <gazebo/physics/physics.hh>\n\n/* A simple drag plugin. Usage:\n *\n *    <gazebo>\n *      <plugin name=\"OrcaDragPlugin\" filename=\"libOrcaDragPlugin.so\">\n *        <link name=\"base_link\">\n *          <center_of_mass>0 0 -0.2</center_of_mass>\n *          <tether_attach>-0.5, -0.4, 0</tether_attach>\n *          <linear_drag>10 20 30</linear_drag>\n *          <angular_drag>5 10 15</angular_drag>\n *          <tether_drag>4</tether_drag>\n *          <surface>10</surface>\n *        </link>\n *      </plugin>\n *    </gazebo>\n *\n *    <center_of_mass> Drag force is applied to the center of mass.\n *    <tether_attach> Relative position of tether attachment.\n *    <linear_drag> Linear drag constants. See default calculation.\n *    <angular_drag> Angular drag constants. See defaut calculation.\n *    <tether_drag> Tether drag constant. See default calculation.\n *    <surface> How far above z=0 the surface of the water is; used to calculate depth.\n *\n * Limitations:\n *    Tether drag is modeled only in x\n */\n\nnamespace gazebo {\n\n/* drag = 0.5 * density * area * velocity^2 * coefficient\n *\n * The drag coefficient for a box is 1.0, so we'll use 0.9 for the ROV.\n * The drag coefficient for an unfaired tether is 1.2.\n *\n * The ROV constants below capture all but velocity:\n * constant = 0.5 * density * area * coefficient\n *\n * The tether constant below captures all but depth and velocity:\n * constant = 0.5 * density * width * coefficient\n */\n\nconstexpr double FLUID_DENSITY = 1029;    // Fluid density of seawater\nconstexpr double ROV_DIM_X = 0.457;       // Length\nconstexpr double ROV_DIM_Y = 0.338;       // Width\nconstexpr double ROV_DIM_Z = 0.254;       // Height\nconstexpr double ROV_AREA_X = ROV_DIM_Y * ROV_DIM_Z;  // Fore, aft area\nconstexpr double ROV_AREA_Y = ROV_DIM_X * ROV_DIM_Z;  // Top, bottom area\nconstexpr double ROV_AREA_Z = ROV_DIM_X * ROV_DIM_Y;  // Port, starboard area\nconstexpr double ROV_DRAG_COEFFICIENT_X = 0.8;\nconstexpr double ROV_DRAG_COEFFICIENT_Y = 0.95;\nconstexpr double ROV_DRAG_COEFFICIENT_Z = 0.95;\nconstexpr double ROV_LINEAR_DRAG_X = 0.5 * FLUID_DENSITY * ROV_AREA_X * ROV_DRAG_COEFFICIENT_X;\nconstexpr double ROV_LINEAR_DRAG_Y = 0.5 * FLUID_DENSITY * ROV_AREA_Y * ROV_DRAG_COEFFICIENT_Y;\nconstexpr double ROV_LINEAR_DRAG_Z = 0.5 * FLUID_DENSITY * ROV_AREA_Z * ROV_DRAG_COEFFICIENT_Z;\nconstexpr double ANGULAR_DRAG_X = ROV_LINEAR_DRAG_X / 2; // A hack\nconstexpr double ANGULAR_DRAG_Y = ROV_LINEAR_DRAG_Y / 2;\nconstexpr double ANGULAR_DRAG_Z = ROV_LINEAR_DRAG_Z / 2; // TODO these are wrong, see revised cals in orca_mission.cpp\nconstexpr double TETHER_DIAM = 0.008;\nconstexpr double TETHER_DRAG_COEFFICIENT = 1.1;\nconstexpr double TETHER_DRAG = 0.5 * FLUID_DENSITY * TETHER_DIAM * TETHER_DRAG_COEFFICIENT;\n\nclass OrcaDragPlugin : public ModelPlugin\n{\nprivate:\n\n  physics::LinkPtr base_link_;\n\n  // Drag force will be applied to the center_of_mass_ (body frame)\n  ignition::math::Vector3d center_of_mass_ {0, 0, 0};\n\n  // Tether drag will be applied to the tether attachment point (body frame)\n  ignition::math::Vector3d tether_attach_ {0, 0, 0};\n\n  // Drag constants (body frame)\n  ignition::math::Vector3d linear_drag_ {ROV_LINEAR_DRAG_X, ROV_LINEAR_DRAG_Y, ROV_LINEAR_DRAG_Z};\n  ignition::math::Vector3d angular_drag_ {ANGULAR_DRAG_X, ANGULAR_DRAG_Y, ANGULAR_DRAG_Z};\n  double tether_drag_ {TETHER_DRAG};\n\n  // Distance to surface\n  double surface_ {10};\n\n  event::ConnectionPtr update_connection_;\n\npublic:\n\n  // Called once when the plugin is loaded.\n  void Load(physics::ModelPtr model, sdf::ElementPtr sdf)\n  {\n    std::string link_name {\"base_link\"};\n\n    std::cout << std::endl;\n    std::cout << \"ORCA DRAG PLUGIN PARAMETERS\" << std::endl;\n    std::cout << \"-----------------------------------------\" << std::endl;\n    std::cout << \"Default link name: \" << link_name << std::endl;\n    std::cout << \"Default center of mass: \" << center_of_mass_ << std::endl;\n    std::cout << \"Default tether attachment point: \" << tether_attach_ << std::endl;\n    std::cout << \"Default linear drag: \" << linear_drag_ << std::endl;\n    std::cout << \"Default angular drag: \" << angular_drag_ << std::endl;\n    std::cout << \"Default tether drag: \" << tether_drag_ << std::endl;\n    std::cout << \"Default surface: \" << surface_ << std::endl;\n\n    GZ_ASSERT(model != nullptr, \"Model is null\");\n    GZ_ASSERT(sdf != nullptr, \"SDF is null\");\n\n    if (sdf->HasElement(\"link\"))\n    {\n      sdf::ElementPtr linkElem = sdf->GetElement(\"link\"); // Only one link is supported\n\n      if (linkElem->HasAttribute(\"name\"))\n      {\n        linkElem->GetAttribute(\"name\")->Get(link_name);\n        std::cout << \"Link name: \" << link_name << std::endl;\n      }\n\n      if (linkElem->HasElement(\"center_of_mass\"))\n      {\n        center_of_mass_ = linkElem->GetElement(\"center_of_mass\")->Get<ignition::math::Vector3d>();\n        std::cout << \"Center of mass: \" << center_of_mass_ << std::endl;\n      }\n\n      if (linkElem->HasElement(\"tether_attach\"))\n      {\n        tether_attach_ = linkElem->GetElement(\"tether_attach\")->Get<ignition::math::Vector3d>();\n        std::cout << \"Tether attachment point: \" << tether_attach_ << std::endl;\n      }\n\n      if (linkElem->HasElement(\"linear_drag\"))\n      {\n        linear_drag_ = linkElem->GetElement(\"linear_drag\")->Get<ignition::math::Vector3d>();\n        std::cout << \"Linear drag: \" << linear_drag_ << std::endl;\n      }\n\n      if (linkElem->HasElement(\"angular_drag\"))\n      {\n        angular_drag_ = linkElem->GetElement(\"angular_drag\")->Get<ignition::math::Vector3d>();\n        std::cout << \"Angular drag: \" << angular_drag_ << std::endl;\n      }\n\n      if (linkElem->HasElement(\"tether_drag\")) // TODO should be child of gazebo element, not link element\n      {\n        tether_drag_ = linkElem->GetElement(\"tether_drag\")->Get<double>();\n        std::cout << \"Tether drag: \" << tether_drag_ << std::endl;\n      }\n\n      if (linkElem->HasElement(\"surface\")) // TODO should be child of gazebo element, not link element\n      {\n        surface_ = linkElem->GetElement(\"surface\")->Get<double>();\n        std::cout << \"Surface: \" << surface_ << std::endl;\n      }\n    }\n\n    base_link_ = model->GetLink(link_name);\n    GZ_ASSERT(base_link_ != nullptr, \"Missing link\");\n\n    // Listen for the update event. This event is broadcast every simulation iteration.\n    update_connection_ = event::Events::ConnectWorldUpdateBegin(boost::bind(&OrcaDragPlugin::OnUpdate, this, _1));\n\n    std::cout << \"-----------------------------------------\" << std::endl;\n    std::cout << std::endl;\n  }\n\n  // Called by the world update start event, up to 1000 times per second.\n  void OnUpdate(const common::UpdateInfo& /*info*/)\n  {\n    ignition::math::Vector3d linear_velocity = base_link_->RelativeLinearVel();\n    ignition::math::Vector3d angular_velocity = base_link_->RelativeAngularVel();\n\n    ignition::math::Vector3d drag_force;\n    drag_force.X() = linear_velocity.X() * fabs(linear_velocity.X()) * -linear_drag_.X();\n    drag_force.Y() = linear_velocity.Y() * fabs(linear_velocity.Y()) * -linear_drag_.Y();\n    drag_force.Z() = linear_velocity.Z() * fabs(linear_velocity.Z()) * -linear_drag_.Z();\n    base_link_->AddLinkForce(drag_force, center_of_mass_);\n\n    ignition::math::Vector3d drag_torque;\n    drag_torque.X() = angular_velocity.X() * fabs(angular_velocity.X()) * -angular_drag_.X();\n    drag_torque.Y() = angular_velocity.Y() * fabs(angular_velocity.Y()) * -angular_drag_.Y();\n    drag_torque.Z() = angular_velocity.Z() * fabs(angular_velocity.Z()) * -angular_drag_.Z();\n    base_link_->AddRelativeTorque(drag_torque); // ODE adds torque at the center of mass\n\n    // Tether drag only accounts for motion in x (forward/reverse)\n    ignition::math::Vector3d tether_force;\n    double depth = surface_ - base_link_->WorldPose().Pos().Z();\n    tether_force.X() = linear_velocity.X() * fabs(linear_velocity.X()) * depth * -tether_drag_;\n    tether_force.Y() = 0;\n    tether_force.Z() = 0;\n    base_link_->AddLinkForce(tether_force, tether_attach_);\n  }\n};\n\nGZ_REGISTER_MODEL_PLUGIN(OrcaDragPlugin)\n\n}\n", "meta": {"hexsha": "3491f0f00b89566eaf7b0970b98dccdfc8e2aaa5", "size": 8148, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "orca_gazebo/src/drag_plugin.cpp", "max_stars_repo_name": "clydemcqueen/orca", "max_stars_repo_head_hexsha": "364a4771383360df609ebe93cf8c8aedac9f5844", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 29.0, "max_stars_repo_stars_event_min_datetime": "2017-10-04T14:25:37.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-19T10:40:02.000Z", "max_issues_repo_path": "orca_gazebo/src/drag_plugin.cpp", "max_issues_repo_name": "clydemcqueen/orca", "max_issues_repo_head_hexsha": "364a4771383360df609ebe93cf8c8aedac9f5844", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2017-11-07T21:24:33.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-20T15:53:25.000Z", "max_forks_repo_path": "orca_gazebo/src/drag_plugin.cpp", "max_forks_repo_name": "clydemcqueen/orca", "max_forks_repo_head_hexsha": "364a4771383360df609ebe93cf8c8aedac9f5844", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2017-10-04T14:25:42.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-10T11:16:32.000Z", "avg_line_length": 41.3604060914, "max_line_length": 118, "alphanum_fraction": 0.6709621993, "num_tokens": 2255, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6757645879592642, "lm_q2_score": 0.5156199157230157, "lm_q1q2_score": 0.34843767989215424}}
{"text": "#ifndef CANNON_PHYSICS_LAGRANGIAN_MECHANICS\n#define CANNON_PHYSICS_LAGRANGIAN_MECHANICS \n\n/*!\n * \\file cannon/physics/lagrangian_mechanics.hpp\n * \\brief File containing class and free function definitions for working with\n * Lagrangian dynamics, as in Structure and Interpretation of Classical\n * Mechanics.\n */\n\n#include <functional>\n\n#include <Eigen/Dense>\n\n#include <cannon/log/registry.hpp>\n\nusing namespace Eigen;\n\nusing namespace cannon::log;\n\nnamespace cannon {\n  namespace physics {\n\n    /*!\n     * \\brief Struct representing a local tuple consisting of a coordinate\n     * vector, velocity vector, and time. \n     */\n    struct LocalTuple {\n\n      LocalTuple() = delete;\n\n      /*!\n       * \\brief Constructor taking generalized coordinate dimension and\n       * initializing coordinates and time to zero.\n       */\n      LocalTuple(unsigned int dim) : dim(dim), time(0.0) {\n        coordinates = VectorXd::Zero(dim);\n        velocities = VectorXd::Zero(dim);\n      }\n\n      /*!\n       * \\brief Copy constructor.\n       */\n      LocalTuple(const LocalTuple &l) : dim(l.dim), time(l.time),\n      coordinates(l.coordinates), velocities(l.velocities) {}\n\n      /*!\n       * \\brief Move constructor.\n       */\n      LocalTuple(LocalTuple &&l) : dim(l.dim), time(l.time),\n      coordinates(std::move(l.coordinates)),\n      velocities(std::move(l.velocities)) {}\n\n      /*!\n       * \\brief Copy assignment operator.\n       */\n      LocalTuple& operator=(const LocalTuple& o) {\n        dim = o.dim;\n        time = o.time;\n        coordinates = o.coordinates;\n        velocities = o.velocities;   \n\n        return *this;\n      }\n\n      /*!\n       * \\brief Get a vector representation of this local tuple.\n       *\n       * \\returns A vector containing the time, generalized coordinates, and\n       * generalized velocity for this local tuple, in that order.\n       */\n      VectorXd to_vec();\n\n      /*!\n       * \\brief Initialize this local tuple with the input vector, which should\n       * have the time, generalized coordinates, and generalized velocities, in\n       * that order.\n       *\n       * \\param vec The vector to use for initialization.\n       */\n      void from_vec(const VectorXd& vec);\n\n      unsigned int dim; //!< Dimension of generalized coordinates\n      double time; //!< Time for this local tuple\n      VectorXd coordinates; //!< Generalized coordinates for this local tuple.\n      VectorXd velocities; //!< Generalized velocities for this local tuple\n\n    };\n\n    /*!\n     * \\brief Struct representing a path as a series of waypoints in\n     * generalized coordinates for doing Lagrangian mechanics.\n     */\n    struct Path {\n      Path() = delete;\n\n      /*!\n       * \\brief Straight-line constructor taking a start, and end time and\n       * start and end coordinates, as well as the number of waypoints to\n       * construct.\n       */\n      Path(double t0, double t1, VectorXd start, VectorXd end, \n          unsigned int length) : t0(t0), t1(t1) {\n        assert(0 <= t0);\n        assert(t0 < t1);\n        assert(start.size() == end.size());\n        assert(length >= 2);\n\n        VectorXd delta = (end - start) / (double)(length-1);\n        \n        for (unsigned int i = 0; i < length; i++) {\n          waypoints.push_back(start + i * delta); \n        }\n      }\n\n      /*!\n       * \\brief Constructor taking generalized coordinate dimension and a\n       * vector of appended waypoints.\n       */\n      Path(unsigned int dim, const VectorXd& vec) {\n        from_vec(dim, vec);\n      }\n\n      /*!\n       * \\brief Get a vector representation of this path by appending all\n       * waypoints.\n       *\n       * \\returns The vector representation.\n       */\n      VectorXd to_vec();\n\n      /*!\n       * \\brief Load a path with waypoints of the input dimension from the\n       * input vector.\n       *\n       * \\param vec The vector to load.\n       */\n      void from_vec(unsigned int dim, const VectorXd& vec);\n\n      /*!\n       * \\brief Get the local tuple at time t from this path. \n       *\n       * Just doing linear interpolation for now.\n       *\n       * \\param t The time to get local tuple for.\n       *\n       * \\returns Local tuple at the input time along this path.\n       */\n      LocalTuple get_local_tuple(double t) const;\n\n      double t0; //!< Start time for this path\n      double t1; //!< End time for this path\n      std::vector<VectorXd> waypoints; //!< Waypoints making up this path\n    };\n\n    using Lagrangian = std::function<double(const LocalTuple&)>;\n\n    /*!\n     * \\brief Compute path action of the input Lagrangian on the input path.\n     *\n     * \\param L The Lagrangian to use\n     * \\param q The path to evaluate path action on\n     * \n     * \\returns The path action\n     */\n    double compute_path_action(Lagrangian L, const Path& q);\n\n  } // namespace physics\n} // namespace cannon\n\n#endif /* ifndef CANNON_PHYSICS_LAGRANGIAN_MECHANICS */\n", "meta": {"hexsha": "722d7ecfbba03cdf1f0b625238969324688b74bc", "size": 4902, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "cannon/physics/lagrangian_mechanics.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/physics/lagrangian_mechanics.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/physics/lagrangian_mechanics.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": 28.5, "max_line_length": 79, "alphanum_fraction": 0.6087311302, "num_tokens": 1099, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5698526514141571, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.34839763850849137}}
{"text": "/*\n * H.cpp\n *\n *  Created on: Apr 11, 2014\n *      Author: wilfeli\n *\n *\n *\n *\n *\n *\n *\n *\n *\n */\n\n\n#include <Eigen/Dense>\n#include <math.h>\n\n#include \"H.h\"\n#include \"Asset.h\"\n#include \"W.h\"\n#include \"Contract.h\"\n#include \"Market.h\"\n#include \"Tools.h\"\n\n\nusing Eigen::MatrixXd;\n\n\n\nH::H(W &w_, int id_):w(w_),\nl_ask(0.0, 0.0),\nc_bid(0.0, 0.0),\nid(id_),\ntheta_x(1,3),\ns0(1,18){\n\t// create reference to the world\n\tw.AddH(this);\n    \n\t//create storage for goods\n\tass_asGC.push_back(new GoodC(this, 0.0));\n    \n\t//create HK\n\tass_asHK.push_back(new HK(1.0));\n    \n    \n\ttype = \"H\";\n    \n\tc_bid.issuer = this;\n\tl_ask.issuer = this;\n    \n\t//create wm\n\tExpectationBackward* exp = new ExpectationBackward(1.0, 10, 0.5);\n\twm[\"MasCHK\"] = exp;\n    \n\t//create wm\n\texp = new ExpectationBackward(1.0, 10, 0.5);\n\twm[\"MasGC\"] = exp;\n    \n\t//create wm\n\texp = new ExpectationBackward(1.0, 0, 0.0);\n\twm[\"api\"] = exp;\n    \n    \n\t//create wm\n\texp = new ExpectationBackward(0.0, 0, 0.01);\n\twm[\"fi_ti\"] = exp;\n    \n\t//parameters\n\tparam = new Parameters();\n\tparam->init();\n    \n\t//accounting\n\taccount = new AccountH();\n    \n    \n};\n\nvoid\nH::init(){\n    //ADP setup\n    theta_V = Eigen::MatrixXd::Constant(1, 1, param->ADP_BF_N);\n    B_n_1_RLS = Eigen::MatrixXd::Zero(param->ADP_BF_N, param->ADP_BF_N);\n    \n    //QL setup\n    _set_QL();\n    \n    \n    //mRe setup\n    _set_mRE();\n\n    \n};\n\nvoid\nH::ac_W(MessageMakeDec* mes){\n    \n\t//calls opt choice\n\t_s0();\n\t//calls opt choice\n    if (param->opt_TYPE == \"EO_CS\"){\n        opt_CS(&s0,&theta_x, param->opt_CS_N);\n    };\n    \n    if (param->opt_TYPE == \"EO_ADP\"){\n        theta_V = _API_LM(&s0, param->ADP_API_LM_N, param->ADP_API_LM_M);\n\n        Eigen::Block<Eigen::MatrixXd> s = s0.block(0,0,s0.rows(),s0.cols());\n        _opt_CS_s_V(s,theta_x, theta_V, param->opt_CS_N);\n    };\n    \n    if (param->opt_TYPE == \"QL\"){\n        opt_QL();\n    };\n    \n    if (param->opt_TYPE == \"mRE\"){\n        opt_mRE();\n        \n    };\n    \n    \n\t//transforms it into ask and bid\n\tl_ask.q = theta_x(0,0) * s0(0,1);\n\tl_ask.p = theta_x(0,1) * s0(0,4);\n    \n\tc_bid.pq_share = theta_x(0,2);\n    \n    \n    \n};\n\n\nAsk*\nH::ac_L(){\n\t//update numbers in bid\n\tl_ask.supply_curve = Eigen::MatrixXd::Zero(1,2);\n\tl_ask.supply_curve << l_ask.p , l_ask.q;\n    \n\tl_ask.p_t_0 = l_ask.p;\n\tl_ask.q_t_0 = l_ask.q;\n    \n    \n    \n\t//return reference to the ask\n\treturn &l_ask;\n};\n\nBid*\nH::ac_C(){\n\t//update numbers in bid\n\tc_bid.pq = _s0()(0,0) * c_bid.pq_share;\n    \n\tc_bid.pq_t_0 = c_bid.pq;\n\tc_bid.pq_share_t_0 = c_bid.pq_share;\n    \n    \n\t//update numbers in bid\n    \n    \n//    if (param->GRID == \"test\"){\n//        c_bid.demand_curve = Eigen::MatrixXd::Zero(1,2);\n//        c_bid.demand_curve.row(0) << wm[\"MasGC\"]->mu , c_bid.pq/wm[\"MasGC\"]->mu ;\n//        return &c_bid;\n//    };\n    \n    \n\t//number of steps\n\tint N_STEPS_dc = 30;\n\tdouble P_MAX_dc = wm[\"MasGC\"]->mu * 10;\n\tdouble P_MIN_dc = wm[\"MasGC\"]->mu * 0.01;\n\tdouble STEP_SIZE = (P_MAX_dc - P_MIN_dc)/N_STEPS_dc;\n    \n\tc_bid.demand_curve = Eigen::MatrixXd::Zero(N_STEPS_dc,2);\n\tfor (int i = 0; i < N_STEPS_dc; i++){\n        \n\t\tc_bid.demand_curve.row(i) << P_MIN_dc + i * STEP_SIZE, c_bid.pq/(P_MIN_dc + i * STEP_SIZE);\n        \n\t};\n    \n    \n    \n    \n\t//return reference to the bid\n\treturn &c_bid;\n};\n\n\n\n\ndouble\nH::_mas_q_sell(MessageMarketLCheckAsk* inf){\n\t//checks how much to sell\n\t//return q from ask\n    \n\tdouble q_sell;\n    \n\tif (inf->p_eq >= l_ask.p){\n\t\tq_sell = l_ask.q;\n\t};\n    \n\treturn q_sell;\n};\n\ndouble\nH::_mas_q_buy(MessageMarketCCheckBid* inf){\n\t//checks how much to sell\n\t//return q from ask\n    \n    \n\tdouble q_buy;\n    \n\tint i=0;\n    \n\twhile ((c_bid.demand_curve(i,0) < inf->p_eq) && (i<c_bid.demand_curve.rows())){\n\t\ti++;\n\t};\n    \n\tif (i<c_bid.demand_curve.rows()){\n\t\tq_buy = c_bid.demand_curve(i,1);\n\t}else{\n\t\t//buys zero\n\t\tq_buy = 0.0;\n\t};\n    \n    \n    \n\treturn q_buy;\n};\n\n\nvoid\nH::_sell_asCHK(MessageMarketLSellC* inf){\n\t//new contract\n\tContractHK* cHK = new ContractHK(this,\n                                     inf->buyer,\n                                     inf->p,\n                                     inf->q,\n                                     w.t,\n                                     w.t);\n    \n\ttype = \"H_EO\";\n    \n\tass_asCHK.push_back(cHK);\n    \n\t//?update ask\n\tl_ask.q -= cHK->q;\n    \n\t//tell market about the contract\n\tinf->sender->_clear_C(cHK);\n    \n\t//call accounting\n\t//create accounting message\n    //\tMessageSellC* mes = new MessageSellC(inf, cHK);\n\taccount->ac_get_inf(inf, cHK);\n    \n    //\tdelete mes;\n    \n    \n};\n\ndouble\nH::_goal_t(Eigen::MatrixXd* s){\n    \n\tdouble l;\n\tdouble c;\n    \n\tif ((*s)(0,3) <= 0.0){\n\t\tc = -0.5;\n//        c = 0.0;\n\t}else{\n        c = (*s)(0,3);\n    };\n    \n\tl = (*s)(0,2);\n    \n\treturn (param->GOAL_T_theta(0,0) * log(1+c) + param->GOAL_T_theta(0,1) * (1-l));\n//    return (param->GOAL_T_theta(0,0) * log(0.5+c) + param->GOAL_T_theta(0,1) * (1-l));\n};\n\n\n\nvoid\nH::_buy_asGC(MessageGoodC* mes){\n    \n\tass_asGC.back()->q += mes->q;\n\taccount->ac_get_inf(mes);\n    \n};\n\n\nvoid\nH::_PS_receive_payment(MessagePSSendPayment* mes){\n    \n\taccount->ac_get_inf(mes);\n    \n};\n\n\nbool\nH::_PS_send_payment(MessagePSSendPayment* inf){\n    \n\tinf->sender = this; //static_cast<IHolderPS*>(const_cast<H*>(this));\n    \n\tbool FLAG_CLEARED = ass_asCBDt0.front()->issuer->_PS_accept_PO(inf);\n    \n    \n    \n\tif(FLAG_CLEARED){\n\t\taccount->ac_get_inf(inf);\n        \n\t};\n    \n\treturn FLAG_CLEARED;\n    \n    \n};\n\nvoid\nH::ac_W_begin_step(){\n    \n\t//update accounting\n\taccount->ac_W_initialize_step();\n    \n\t//\n\tfor (auto c:ass_asCHK){\n\t\tif (c->t_end <= w.t){\n\t\t\tdelete c;\n\t\t\tc = NULL;\n\t\t};\n\t};\n    \n    \n\t//clear contracts\n\tass_asCHK.erase(std::remove_if(ass_asCHK.begin(), ass_asCHK.end(),\n                                   [&](ContractHK* x) -> bool { return (x); }),\n                    ass_asCHK.end());\n    \n    \n    \n};\n\nvoid\nH::ac_W_begin_step(MessageStatus* mes){\n\tif (mes->status <= 0.0){\n\t\taccount->ac_W_initialize_step(mes);\n\t};\n};\n\nvoid\nH::ac_W_end_step(){\n\t//updates state\n\t_s0();\n\tdouble ut = _goal_t(&s0);\n\taccount->ac_W_end_step(&s0, ut);\n    \n\t//eats good\n\tass_asGC.front()->q = 0.0;\n    \n};\n\nvoid\nH::ac_W_end_step(MessageStatus* mes){\n    if (mes->status <= 0.0){\n        ac_W_end_step();\n    };\n};\n\n\n\nvoid\nH::wm_update_k_s(){\n\tif (w.t > 0.0){\n        \n\t\tMatrixXd w0 = wm_w0_tbeg();\n\t\tExpectationBackward* exp_i;\n\t\tstd::vector<double> s_t_i;\n        \n\t\t//update k_s if conditions are met\n//\t\tif ((w0(0,1) > 0.0) || ((w0(0,1) == 0.0) && (w0(0,0) != 0.0)) || ((w0(0,4) > 0.0) && (w0(0,0) == 0.0))){\n\t\t\ts_t_i.push_back(w0(0,0));\n\t\t\ts_t_i.push_back((w0(0,1) > 0.0)? w0(0,1):w0(0,7));\n            \n\t\t\texp_i = wm[\"MasCHK\"];\n            \n\t\t\texp_i->s_t.push_back(s_t_i);\n            \n\t\t\twm_update_expectation_backward(exp_i, 1, true);\n//\t\t};\n        \n\t\ts_t_i.clear();\n        \n\t\ts_t_i.push_back(w0(0,2));\n\t\ts_t_i.push_back((w0(0,2) > 0.0)? w0(0,3)/w0(0,2):w0(0,8));\n        \n        \n\t\texp_i = wm[\"MasGC\"];\n        \n\t\texp_i->s_t.push_back(s_t_i);\n        \n\t\twm_update_expectation_backward(exp_i, 1, true);\n        \n\t\ts_t_i.clear();\n        \n        \n\t\tif (w.t > 0.0){\n\t\t\texp_i = wm[\"api\"];\n            \n\t\t\ts_t_i.push_back(w0(0,5));\n\t\t\texp_i->s_t.push_back(s_t_i);\n            \n\t\t\twm_update_expectation_backward(exp_i, 0, false);\n            \n            \n\t\t\ts_t_i.clear();\n            \n\t\t\texp_i = wm[\"fi_ti\"];\n            \n\t\t\ts_t_i.push_back(w0(0,6));\n\t\t\texp_i->s_t.push_back(s_t_i);\n            \n//\t\t\twm_update_expectation_backward(exp_i, 0, false);\n            wm_update_expectation_backward(exp_i, 0, true);\n            \n\t\t};\n        \n        \n        if (param->opt_TYPE == \"QL\"){\n            wm_update_Q();\n            \n        };\n        \n        if (param->opt_TYPE == \"mRE\"){\n            wm_update_mRE();\n            \n        };\n    \n        \n\t};\n    \n    \n    \n};\n\n\nvoid\nH::wm_update_expectation_backward(ExpectationBackward* exp_i, int p_position, bool FLAG_UPDATE_V){\n    \n\tstd::vector<double> p;\n    \n\tint i_s_t_1_max = 0;\n\tlong i_s_t_max = 0;\n    \n\t//depending on the length of the wm and accumulated number of prices\n\tif (std::isinf(param->WM_LENGTH)){\n\t\ti_s_t_1_max = exp_i->s_t_1[\"n\"];\n\t\ti_s_t_max = exp_i->s_t.size();\n\t}else{\n\t\ti_s_t_1_max = std::min(std::max(param->WM_LENGTH - exp_i->s_t.size(), 0.0), exp_i->s_t_1[\"n\"]);\n\t\ti_s_t_max = std::min(param->WM_LENGTH, (double)exp_i->s_t.size());\n\t};\n    \n\tfor (int i = 0; i < i_s_t_1_max; i++){\n\t\tp.push_back(exp_i->s_t_1[\"mu\"]);\n\t};\n    \n\t//push other prices\n\tfor (std::size_t i = (exp_i->s_t.size() - i_s_t_max);i < exp_i->s_t.size();i++){\n\t\tp.push_back(exp_i->s_t[i][p_position]);\n\t};\n    \n\tMatrixXd mean_variance = wm_mean_variance(p);\n    \n\texp_i->mu = mean_variance(0,0);\n\texp_i->n += 1.0;\n    \n    if (FLAG_UPDATE_V){\n        exp_i->v = mean_variance(1,0);\n        \n        if (exp_i->v <= 0.0){\n            exp_i->v = exp_i->mu * 0.01;\n        };\n        \n        \n    };\n    \n    \n    \n};\n\n\n\nEigen::MatrixXd\nH::wm_mean_variance(std::vector<double> &x){\n\tMatrixXd mean_variance(2,1);\n    \n\t//gets mean and variance\n\tdouble sum = std::accumulate(x.begin(), x.end(), 0.0);\n\tdouble mean = sum / x.size();\n\tstd::vector<double> diff(x.size());\n\tstd::transform(x.begin(), x.end(), diff.begin(),\n\t               std::bind2nd(std::minus<double>(), mean));\n\tdouble sq_sum = std::inner_product(diff.begin(), diff.end(), diff.begin(), 0.0);\n    //\tdouble stdev = std::sqrt(sq_sum / x.size());\n\tdouble variance = sq_sum/x.size();\n    \n\tmean_variance(0,0) = mean;\n\tmean_variance(1,0) = variance;\n    \n\treturn mean_variance;\n};\n\n\nEigen::MatrixXd\nH::wm_w0_tbeg(){\n\tMatrixXd w0(1,9);\n    \n\tlong life_length = account->asCHK_q.size();\n    \n\tw0(0,0) = account->asCHK_q.at(life_length - 2);\n\tw0(0,1) = account->asCHK_p.at(life_length - 2);\n\tw0(0,2) = account->asGC_q.at(life_length - 2);\n\tw0(0,3) = account->asGC_pq.at(life_length - 2);\n    \n\tw0(0,4) = l_ask.q_t_0;\n\tw0(0,5) = account->FI_div_t.at(life_length - 2) + account->asCHK_p_t.at(life_length - 2);\n\tw0(0,6) = account->FI_div_t.at(life_length - 2);\n    \n\tw0(0,7) = w.ml->market_price.at(w.t - 1)->p;\n\tw0(0,8) = w.mc->market_price.at(w.t - 1)->p;\n    \n    //\tstd::cout << w0 << std::endl;\n    \n    \n    \n\treturn w0;\n};\n\n\nEigen::MatrixXd\nH::_s0(){\n\t//money holdings\n\ts0(0,0) = ass_asCBDt0.front()->q;\n    \n\ts0(0,1) = ass_asHK.front()->q;\n    \n\ts0(0,2) = 0.0;\n\t//labor to be supplied\n\tfor (auto c:ass_asCHK){\n\t\ts0(0,2) += c->q;\n\t};\n    \n    \n\t//amount of good c\n\ts0(0,3) = ass_asGC.front()->q;\n    \n\t//expected price on labor market\n\ts0(0,4) = wm[\"MasCHK\"]->mu;\n    \n\t//number of observations\n\ts0(0,5) = wm[\"MasCHK\"]->n;\n    \n\t//expected price on goods market\n\ts0(0,6) = wm[\"MasGC\"]->mu;\n    \n\t//number of observations\n\ts0(0,7) = wm[\"MasGC\"]->n;\n    \n    \n    \n    \n\t//average past income\n\ts0(0,8) = wm[\"api\"]->mu;\n    \n\ts0(0,9) = wm[\"api\"]->n;\n    \n\t//current income\n\ts0(0,10) = account->FI_div_t.back() + account->asCHK_p_t.back();\n    \n\t//to be used in max routinue\n\t//current signed labor contracts - q\n\ts0(0,11) = 0.0;\n    \n\t//current signed labor contracts - p\n\ts0(0,12) = 0.0;\n    \n\t//financial income\n\ts0(0,13) = wm[\"fi_ti\"]->mu;\n    \n\ts0(0,14) = wm[\"fi_ti\"]->n;\n    \n    \n\t//variance of labor market\n\ts0(0,15) = wm[\"MasCHK\"]->v;\n    \n\t//variance of goods market\n\ts0(0,16) = wm[\"MasGC\"]->v;\n    \n\t//variance of financial income\n\ts0(0,17) = wm[\"fi_ti\"]->v;\n    \n    \n\t//\n    \n    \n\treturn s0;\n};\n\n\n\n\nvoid\nH::opt_CS(MatrixXd* s0,  MatrixXd* theta_x, int N){\n    \n//\tN = 1;\n    \n\t//gets matrix of thetas\n\t//prepare initial matrix\n\tMatrixXd m_s0 = MatrixXd::Zero(N, s0->cols());\n    \n\tm_s0.rowwise() += s0->row(0);\n    \n    \n\t//allocate space to the matrix\n\tMatrixXd n_w;\n\tMatrixXd n_x;\n\tMatrixXd n_s = MatrixXd::Zero(N, s0->cols());\n\tMatrixXd n_c;\n    \n    \n\t//create matrix for the grid - small size here\n\tMatrixXd grid(3,3);\n    \n    create_decision_grid(grid,0);\n\n    \n    \n    if (w.param->SIMULATION_MODE == \"test\"){\n        Tools::mgrid_test(grid, &theta_x_all);\n        \n    } else{\n        \n        Tools::mgrid(grid, &theta_x_all);\n    };\n    \n    //\tstd::cout << theta_x_all.transpose() << \"\\n\";\n    \n    \n\t//create random number generators for the implementation\n    \n\tboost::normal_distribution<> nd_w1((*s0)(0,4), pow((*s0)(0,15),0.5));\n\tboost::normal_distribution<> nd_w2((*s0)(0,6), pow((*s0)(0,16),0.5));\n\tboost::normal_distribution<> nd_w3((*s0)(0,13), pow((*s0)(0,17),0.5));\n    \n\tboost::variate_generator<boost::mt19937&,\n    boost::normal_distribution<>> rng_w1(w.rng, nd_w1);\n    \n\tboost::variate_generator<boost::mt19937&,\n    boost::normal_distribution<>> rng_w2(w.rng, nd_w2);\n    \n\tboost::variate_generator<boost::mt19937&,\n    boost::normal_distribution<>> rng_w3(w.rng, nd_w3);\n    \n\n    \n    if (w.param->SIMULATION_MODE != \"test\"){\n\n        //draw random variables\n        //fast realization\n        n_w = MatrixXd::Zero(N, 3 * param->T_MAX);\n        for (int i = 0; i < N; i++){\n            for(int j=0; j< n_w.cols(); j++){\n                if (j%3 == 0){\n                    n_w(i,j) = rng_w1();\n                } else {\n                    if (j%3 == 1){\n                        n_w(i,j) = rng_w2();\n                    }else{\n                        n_w(i,j) = rng_w3();\n                    };\n                    \n                };\n                n_w(i,j) = std::max(0.0, (double)n_w(i,j));\n            };\n        };\n    };\n    \n\n    \n    \n    \n    \n    \n\t//matrix of all\n\tMatrixXd c_all(theta_x_all.cols(),1);\n    \n\tfor (int i = 0 ; i < theta_x_all.cols(); i++){\n        if (w.param->SIMULATION_MODE == \"test\"){\n            n_w = MatrixXd::Zero(N, 3 * param->T_MAX);\n            for (int i = 0; i < N; i++){\n                for(int j=0; j< n_w.cols(); j++){\n                    if (j%3 == 0){\n                        n_w(i,j) = Tools::get_normal((*s0)(0,4), pow((*s0)(0,15),0.5), w.myrng);\n                    } else {\n                        if (j%3 == 1){\n                            n_w(i,j) = Tools::get_normal((*s0)(0,6), pow((*s0)(0,16),0.5), w.myrng);\n                        }else{\n                            n_w(i,j) = Tools::get_normal((*s0)(0,13), pow((*s0)(0,17),0.5), w.myrng);\n                        };\n                        \n                    };\n                    n_w(i,j) = std::max(0.0, (double)n_w(i,j));\n                };\n            };\n        };\n\n\t\t//call estimator of results of steps, given theta_x\n        theta_x->row(0) = theta_x_all.col(i).transpose();\n\t\tn_x = MatrixXd::Zero(N, 3);\n\t\tn_s = m_s0;\n\t\tn_c = MatrixXd::Zero(N, param->T_MAX);\n\t\t_step_opt_CS(theta_x, &n_w, &n_x, &n_s, &n_c, param->T_MAX);\n        \n\t\t//after n_c\n\t\t//average over n runs\n//        std::cout << n_w << std::endl;\n//        std::cout << n_c << std::endl;\n\t\tc_all(i,0) = (n_c * param->BETA_T).mean();\n        \n\t};\n\n    \n    \n    \n    //\tstd::cout << c_all << \"\\n\";\n    \n\t//find all max elements\n\tdouble max = c_all(0,0);\n\tstd::list<int> i_max;\n\tfor (int i=0; i<c_all.rows(); i++){\n\t\tif (c_all(i,0) == max){\n\t\t\ti_max.push_back(i);\n\t\t}else{\n\t\t\tif (c_all(i,0) > max){\n\t\t\t\tmax = c_all(i,0);\n\t\t\t\ti_max.clear();\n\t\t\t\ti_max.push_back(i);\n\t\t\t};\n\t\t}\n\t};\n    \n\t//if more than 1 max - randomly pick\n\tlong theta_max_i;\n\tif (i_max.size()>1){\n\t\tboost::random::uniform_int_distribution<> i_max_dist(0, i_max.size()-1);\n\t\ttheta_max_i = i_max_dist(w.rng);\n\t}else{\n\t\ttheta_max_i = i_max.front();\n\t};\n    \n    \n\ttheta_x->row(0) = theta_x_all.col(theta_max_i).transpose();\n    \n    //\tstd::cout << \"theta\" << *theta_x << \"\\n\";\n};\n\n\ndouble\nH::get_status(){\n\treturn status;\n};\n\n\nvoid\nH::_step_opt_CS(MatrixXd *theta_x,\n                MatrixXd *w,\n                MatrixXd *x,\n                MatrixXd *s,\n                MatrixXd *c,\n                int T){\n    \n\tdouble l_t;\n\tdouble c_t;\n    \n    //\tstd::cout <<\"w\" << *w << \"\\n\";\n    \n\tfor (int i=0; i< T; i++){\n        \n\t\tx->col(0) = (*theta_x)(0,0) * s->col(1).array();\n\t\tx->col(1) = (*theta_x)(0,1) * s->col(4).array();\n        \n\t\t//labor market results\n\t\t//if wage is less than realized wage - get hired, otherwise zero\n\t\ts->col(11) = (w->col(i*3).array() >= x->col(1).array()).cast<double>().array() *x->col(0).array();\n\t\ts->col(12) = w->col(i*3);\n        \n        //\t\tauto FLAG_UPDATE = ((s->col(12) > 0.0).array() ||\n        //\t\t\t\t\t\t\t((s->col(12) == 0.0).array() &&\n        //\t\t\t\t\t\t\t(s->col(11) != 0.0).array()) ||\n        //\t\t\t\t\t\t\t((x->col(0) > 0.0).array() &&\n        //\t\t\t\t\t\t\t(s->col(11) == 0.0).array()));\n        \n\t\t//TODO update inside , not coded for now\n        //\t\tif (param->wm_INSIDE_UPDATE){\n        //\t\t};\n        \n\t\t//made consumption good decision\n\t\tx->col(2) = (*theta_x)(0,2) * s->col(0).array();\n        \n        \n\t\t//buy consumption goods , assume all goods are consumed in the previous\n\t\t//period, so no addition here\n\t\tfor (int j=0; j<s->rows(); j++){\n\t\t\tif ((*w)(j,i*3 + 1) > 0.0){\n\t\t\t\t(*s)(j,3) = (*x)(j,2) / (*w)(j,i*3 + 1);\n                \n                \n                \n\t\t\t\t//for speed calculate goal in this cycle\n\t\t\t\t//stores realization of a goal\n\t\t\t\t//as couldn't pass block need to calculate in place?\n                \n                //\t\t\t\t(*c)(j,i) = _goal_t(&(s->block(1,s->cols(),j,0)));\n\t\t\t}else{\n\t\t\t\t(*s)(j,3) = 0.0;\n\t\t\t};\n            \n\t\t\tif ((*s)(j,3) <= 0.0){\n\t\t\t\tc_t = -0.5;\n//                c_t = 0.0;\n\t\t\t} else {\n\t\t\t\tc_t = (*s)(j,3);\n\t\t\t};\n            \n\t\t\tl_t = (*s)(j,11);\n            \n            \n\t\t\t(*c)(j,i) = param->GOAL_T_theta(0,0) * log(1+c_t) + param->GOAL_T_theta(0,1) * (1-l_t);\n//            (*c)(j,i) = param->GOAL_T_theta(0,0) * log(0.5+c_t) + param->GOAL_T_theta(0,1) * (1-l_t);\n\n            \n\t\t};\n        \n\t\t//account for money being spent\n\t\ts->col(0) = s->col(0).array() - w->col(i*3 + 1).array() * s->col(3).array();\n        \n        \n\t\t//labor payments\n\t\ts->col(0) = s->col(0).array() + s->col(11).array() * s->col(12).array();\n        \n\t\t//dividend payment\n\t\ts->col(0) += w->col(i*3 + 2);\n        \n        //\t\tstd::cout << s->col(0) << \"\\n\";\n//        std::cout << *s << \"\\n\";\n        //\t\tstd::cout << *c << \"\\n\";\n        //\t\tstd::cout << *x << \"\\n\";\n        \n\t\t//skipped, because they are assigned, not added in a cycle\n\t\t//zero labor contracts\n\t\t//zero consumption good\n        \n\t};\n    \n};\n\n\n    \n    \nvoid\nH::_bf(Eigen::MatrixXd* s, Eigen::MatrixXd* ret){\n    (*ret)(0,0) = (*s)(0,0);\n};\n\nvoid\nH::_bf(Eigen::Block<Eigen::MatrixXd>& s, Eigen::MatrixXd* ret){\n    (*ret)(0,0) = s(0,0);\n};\n\n\ndouble\nH::_V(Eigen::MatrixXd* s, Eigen::MatrixXd* phi_f, Eigen::MatrixXd& theta_V){\n    _bf(s, phi_f);\n    \n    return (theta_V*(*phi_f).transpose()).sum();\n    \n};\n\n\ndouble\nH::_V(Eigen::Block<Eigen::MatrixXd>& s, Eigen::MatrixXd* phi_f, Eigen::MatrixXd& theta_V){\n    _bf(s, phi_f);\n    \n    return (theta_V*(*phi_f).transpose()).sum();\n    \n};\n\nEigen::MatrixXd\nH::_API_LM(Eigen::MatrixXd* s0, int N, int M){\n    //Approximate policy iteration using linear models.\n    //\n    //p.407 ADP\n    //\n    \n    //fix basis functions\n    long n_theta_t = param->ADP_BF_N;\n    \n    //inner theta\n    //theta for now and future\n    Eigen::MatrixXd theta_V_n = Eigen::MatrixXd::Constant(1, n_theta_t, 1);\n    \n    //policy theta\n    Eigen::MatrixXd theta_V_pi = theta_V;\n    \n    \n    Eigen::MatrixXd s_n_m;\n    Eigen::MatrixXd v_n_m;\n    Eigen::MatrixXd x_n_m(1,3);\n    Eigen::MatrixXd phi(1, param->ADP_BF_N);\n    Eigen::MatrixXd phi1(1, param->ADP_BF_N);\n    \n    \n    \n    for (int n=0; n<N; n++){\n        theta_V_n = theta_V_pi;\n        \n        s_n_m = MatrixXd::Zero(M+1, s0->cols());\n        s_n_m.row(0) += s0->row(0);\n        //v_n_m_T1 = 0\n        v_n_m = Eigen::MatrixXd::Constant(M, n_theta_t, 0.0);\n        \n        \n        for (int m=0; m<M; m++){\n            \n            Eigen::Block<Eigen::MatrixXd> s = s_n_m.block(m,0,1,(*s0).cols());\n            \n            \n            //choose action, takes reference to s\n            _opt_CS_s_V(s, x_n_m, theta_V_pi, param->opt_CS_N);\n            \n            s_n_m.block(m+1,0,1,(*s0).cols()) = s;\n            \n            Eigen::Block<Eigen::MatrixXd> s1 = s_n_m.block(m+1,0,1,(*s0).cols());\n            s = s_n_m.block(m,0,1,(*s0).cols());\n            \n            \n            //make step given action, to update state and return value function\n            double _c = _c_theta_x(x_n_m, s1, theta_V_pi);\n            \n            double c_n_m = _c - _V(s1,&phi,theta_V_pi);\n            \n            _bf(s,&phi);\n            _bf(s1,&phi1);\n            Eigen::MatrixXd v_n_m = phi - param->BETA*phi1;\n            \n            //            std::cout << s_n_m.row(m) << std::endl;\n            //            std::cout << s << std::endl;\n            //\n            //            std::cout << s_n_m.row(m+1) << std::endl;\n            //            std::cout << theta_V_pi << std::endl;\n            //            std::cout << theta_V_n << std::endl;\n            \n            \n            //update theta_V_n\n            theta_V_n = _RLS(theta_V_n,\n                             v_n_m,\n                             s,\n                             m,\n                             c_n_m);\n            //assume that only 1 element in v and restrict it\n            if (theta_V_n(0,0) > 1000){\n                theta_V_n(0,0) = 1000;\n            };\n            if (theta_V_n(0,0) < 0.0){\n                theta_V_n(0,0) = 0.01;\n            };\n            \n        };\n        \n        theta_V_pi = theta_V_n;\n    };\n    \n    //std::cout << theta_V_pi << std::endl;\n    return theta_V_pi;\n};\n\nEigen::MatrixXd\nH::_RLS(Eigen::MatrixXd& theta, Eigen::MatrixXd& v, Eigen::Block<Eigen::MatrixXd>& s, int i, double c){\n    \n    //i - iteration if i = 0 - initialize B\n    //for each theta_t:\n    Eigen::MatrixXd B_n_1;\n    \n    if (i == 0){\n        //identity matrix\n        double e_B_0 = 0.0005;\n        \n        //B(n-1)\n        B_n_1 = e_B_0 * Eigen::MatrixXd::Identity(param->ADP_BF_N, param->ADP_BF_N);\n        \n    }else{\n        B_n_1 = B_n_1_RLS;\n    };\n    \n    //container for basis functions\n    Eigen::MatrixXd phi(1, param->ADP_BF_N);\n    _bf(s,&phi);\n    \n    double e_n = c - (v.transpose()*theta)(0,0);\n    \n    double gamma_n = 1 + ((v.transpose()*B_n_1)*phi)(0,0);\n    \n    \n    Eigen::MatrixXd B_n = B_n_1 - 1/gamma_n *((B_n_1*(phi*v.transpose()))*B_n_1);\n    \n    Eigen::MatrixXd theta_n = theta + 1/gamma_n * ((e_n*B_n_1)*phi);\n    \n    //    std::cout << 1/gamma_n * ((e_n*B_n_1)*phi) << std::endl;\n    \n    //    std::cout << theta_n << std::endl;\n    \n    B_n_1_RLS = B_n;\n    \n    \n    \n    return theta_n;\n    \n    \n};\n\n\n\n\nvoid\nH::_opt_CS_s_V(Eigen::Block<Eigen::MatrixXd>& s0,  Eigen::MatrixXd& theta_x, Eigen::MatrixXd& theta_V, int N){\n    \n    //\tN = 1;\n    \n\t//gets matrix of thetas\n\t//prepare initial matrix\n\tMatrixXd m_s0 = MatrixXd::Zero(N, s0.cols());\n    \n\tm_s0.rowwise() += s0.row(0);\n    \n    \n\t//allocate space to the matrix\n\tMatrixXd n_w;\n\tMatrixXd n_x;\n\tMatrixXd n_s = MatrixXd::Zero(N, s0.cols());\n\tMatrixXd n_c;\n    MatrixXd v_bf_ret = MatrixXd::Zero(1, param->ADP_BF_N);\n    MatrixXd n_v;\n    \n    \n\t//create matrix for the grid - small size here\n\tMatrixXd grid(3,3);\n    \n    create_decision_grid(grid,0);\n    \n    if (w.param->SIMULATION_MODE == \"test\"){\n        Tools::mgrid_test(grid, &theta_x_all);\n        \n    } else{\n        \n        Tools::mgrid(grid, &theta_x_all);\n    };\n    \n\t//create random number generators for the implementation\n    \n\tboost::normal_distribution<> nd_w1(s0(0,4), pow(s0(0,15),0.5));\n\tboost::normal_distribution<> nd_w2(s0(0,6), pow(s0(0,16),0.5));\n\tboost::normal_distribution<> nd_w3(s0(0,13), pow(s0(0,17),0.5));\n    \n\tboost::variate_generator<boost::mt19937&,\n    boost::normal_distribution<>> rng_w1(w.rng, nd_w1);\n    \n\tboost::variate_generator<boost::mt19937&,\n    boost::normal_distribution<>> rng_w2(w.rng, nd_w2);\n    \n\tboost::variate_generator<boost::mt19937&,\n    boost::normal_distribution<>> rng_w3(w.rng, nd_w3);\n    \n    \n    \n    if (w.param->SIMULATION_MODE != \"test\"){\n        \n        //draw random variables\n        //fast realization\n        n_w = MatrixXd::Zero(N, 3 * param->T_MAX);\n        for (int i = 0; i < N; i++){\n            for(int j=0; j< n_w.cols(); j++){\n                if (j%3 == 0){\n                    n_w(i,j) = rng_w1();\n                } else {\n                    if (j%3 == 1){\n                        n_w(i,j) = rng_w2();\n                    }else{\n                        n_w(i,j) = rng_w3();\n                    };\n                    \n                };\n                n_w(i,j) = std::max(0.0, (double)n_w(i,j));\n            };\n        };\n    };\n    \n\t//matrix of all\n\tMatrixXd c_all(theta_x_all.cols(),1);\n    \n\tfor (int i = 0 ; i < theta_x_all.cols(); i++){\n        if (w.param->SIMULATION_MODE == \"test\"){\n            n_w = MatrixXd::Zero(N, 3 * param->T_MAX);\n            for (int i = 0; i < N; i++){\n                for(int j=0; j< n_w.cols(); j++){\n                    if (j%3 == 0){\n                        n_w(i,j) = Tools::get_normal(s0(0,4), pow(s0(0,15),0.5), w.myrng);\n                    } else {\n                        if (j%3 == 1){\n                            n_w(i,j) = Tools::get_normal(s0(0,6), pow(s0(0,16),0.5), w.myrng);\n                        }else{\n                            n_w(i,j) = Tools::get_normal(s0(0,13), pow(s0(0,17),0.5), w.myrng);\n                        };\n                        \n                    };\n                    n_w(i,j) = std::max(0.0, (double)n_w(i,j));\n                };\n            };\n        };\n        \n\t\t//call estimator of results of steps, given theta_x\n\t\ttheta_x.row(0) = theta_x_all.col(i).transpose();\n\t\tn_x = MatrixXd::Zero(N, 3);\n\t\tn_s = m_s0;\n\t\tn_c = MatrixXd::Zero(N, 1);\n        n_v = MatrixXd::Zero(N, 1);\n\t\t_step_opt_CS(theta_x, &n_w, &n_x, &n_s, &n_c, &n_v, theta_V, &v_bf_ret, 1);\n        \n\t\t//after n_c\n\t\t//average over n runs\n        c_all(i,0) = (n_c + param->BETA*n_v).mean();\n        \n\t};\n    \n    //    std::cout << (n_c + param->BETA*n_v).mean() << std::endl;\n    \n    \n\t//find all max elements\n\tdouble max = c_all(0,0);\n\tstd::list<int> i_max;\n\tfor (int i=0; i<c_all.rows(); i++){\n\t\tif (c_all(i,0) == max){\n\t\t\ti_max.push_back(i);\n\t\t}else{\n\t\t\tif (c_all(i,0) > max){\n\t\t\t\tmax = c_all(i,0);\n\t\t\t\ti_max.clear();\n\t\t\t\ti_max.push_back(i);\n\t\t\t};\n\t\t}\n\t};\n    \n\t//if more than 1 max - randomly pick\n\tlong theta_max_i;\n\tif (i_max.size()>1){\n\t\tboost::random::uniform_int_distribution<> i_max_dist(0, i_max.size()-1);\n\t\ttheta_max_i = i_max_dist(w.rng);\n\t}else{\n\t\ttheta_max_i = i_max.front();\n\t};\n    \n    \n\ttheta_x.row(0) = theta_x_all.col(theta_max_i).transpose();\n    \n    //    std::cout << theta_x << std::endl;\n};\n\nvoid\nH::_step_opt_CS(MatrixXd& theta_x,\n                MatrixXd *w,\n                MatrixXd *x,\n                MatrixXd *s,\n                MatrixXd *c,\n                MatrixXd* v,\n                MatrixXd& theta_v,\n                MatrixXd* ret,\n                int T){\n    \n\tdouble l_t;\n\tdouble c_t;\n\n\t//zero vector\n\tauto s_zero = MatrixXd::Zero(s->rows(),1);\n    Eigen::Block<Eigen::MatrixXd> s_block = s->block(0,0,1,s->cols());;\n\n    \n    \n    //\tstd::cout <<\"w\" << *w << \"\\n\";\n    \n\tfor (int i=0; i< T; i++){\n        \n\t\tx->col(0) = theta_x(0,0) * s->col(1).array();\n\t\tx->col(1) = theta_x(0,1) * s->col(4).array();\n        \n\t\t//labor market results\n\t\t//if wage is less than realized wage - get hired, otherwise zero\n\t\ts->col(11) = (w->col(i*3).array() >= x->col(1).array()).cast<double>().array() *x->col(0).array();\n\t\ts->col(12) = w->col(i*3);\n        \n\t\t//made consumption good decision\n\t\tx->col(2) = theta_x(0,2) * s->col(0).array();\n        \n        \n\t\t//buy consumption goods , assume all goods are consumed in the previous\n\t\t//period, so no addition here\n\t\tfor (int j=0; j<s->rows(); j++){\n\t\t\tif ((*w)(j,i*3 + 1) > 0.0){\n\t\t\t\t(*s)(j,3) = (*x)(j,2) / (*w)(j,i*3 + 1);\n                \n                \n                \n\t\t\t\t//for speed calculate goal in this cycle\n\t\t\t\t//stores realization of a goal\n\t\t\t\t//as couldn't pass block need to calculate in place?\n                \n                //\t\t\t\t(*c)(j,i) = _goal_t(&(s->block(1,s->cols(),j,0)));\n\t\t\t}else{\n\t\t\t\t(*s)(j,3) = 0.0;\n\t\t\t};\n            \n\t\t\tif ((*s)(j,3) <= 0.0){\n\t\t\t\tc_t = -0.5;\n//                c_t = 0.0;\n\t\t\t} else {\n\t\t\t\tc_t = (*s)(j,3);\n\t\t\t};\n            \n\t\t\tl_t = (*s)(j,11);\n            \n            \n\t\t\t(*c)(j,i) = param->GOAL_T_theta(0,0) * log(1+c_t) + param->GOAL_T_theta(0,1) * (1-l_t);\n//            (*c)(j,i) = param->GOAL_T_theta(0,0) * log(0.5+c_t) + param->GOAL_T_theta(0,1) * (1-l_t);\n\n            \n\t\t};\n        \n\t\t//account for money being spent\n\t\ts->col(0) = s->col(0).array() - w->col(i*3 + 1).array() * s->col(3).array();\n        \n        \n\t\t//labor payments\n\t\ts->col(0) = s->col(0).array() + s->col(11).array() * s->col(12).array();\n\n    \n\t\t//dividend payment\n\t\ts->col(0) += w->col(i*3 + 2);\n        \n        \n        //zero out labor contracts\n        s->col(11) = s_zero;\n        s->col(12) = s_zero;\n        //zero out consumption goods\n        s->col(3) = s_zero;\n        \n        //add value function estimation\n        for (int j=0; j < s->rows(); j++){\n            s_block  = s->block(j,0,1,s->cols());\n            \n            (*v)(j,i) = _V(s_block,ret, theta_V);\n        };\n        \n\n\n        \n\t};\n    \n};\n\n\ndouble\nH::_c_theta_x(Eigen::MatrixXd& theta_x, Eigen::Block<Eigen::MatrixXd>& s0, Eigen::MatrixXd& theta_V){\n    \n    int N = 1;\n    double _c = 0.0;\n    \n    //    std::cout << s0 << std::endl;\n    \n\t//gets matrix of thetas\n\t//prepare initial matrix\n\tMatrixXd m_s0 = MatrixXd::Zero(N, s0.cols());\n    \n\tm_s0.rowwise() += s0.row(0);\n    \n    \n\t//allocate space to the matrix\n\tMatrixXd n_w;\n\tMatrixXd n_x = MatrixXd::Zero(N, 3);\n\tMatrixXd n_s = MatrixXd::Zero(N, s0.cols());\n    MatrixXd v_bf_ret = MatrixXd::Zero(1, param->ADP_BF_N);\n\tMatrixXd n_c = MatrixXd::Zero(N, 1);;\n    MatrixXd n_v = MatrixXd::Zero(N, 1);;\n    \n    \n\t//create random number generators for the implementation\n    \n\tboost::normal_distribution<> nd_w1(s0(0,4), pow(s0(0,15),0.5));\n\tboost::normal_distribution<> nd_w2(s0(0,6), pow(s0(0,16),0.5));\n\tboost::normal_distribution<> nd_w3(s0(0,13), pow(s0(0,17),0.5));\n    \n\tboost::variate_generator<boost::mt19937&,\n    boost::normal_distribution<>> rng_w1(w.rng, nd_w1);\n    \n\tboost::variate_generator<boost::mt19937&,\n    boost::normal_distribution<>> rng_w2(w.rng, nd_w2);\n    \n\tboost::variate_generator<boost::mt19937&,\n    boost::normal_distribution<>> rng_w3(w.rng, nd_w3);\n    \n    \n    \n    if (w.param->SIMULATION_MODE != \"test\"){\n        \n        //draw random variables\n        //fast realization\n        n_w = MatrixXd::Zero(N, 3 * param->T_MAX);\n        for (int i = 0; i < N; i++){\n            for(int j=0; j< n_w.cols(); j++){\n                if (j%3 == 0){\n                    n_w(i,j) = rng_w1();\n                } else {\n                    if (j%3 == 1){\n                        n_w(i,j) = rng_w2();\n                    }else{\n                        n_w(i,j) = rng_w3();\n                    };\n                    \n                };\n                n_w(i,j) = std::max(0.0, (double)n_w(i,j));\n            };\n        };\n    };\n\n    \n    \n    \n    //redraw random in comparative with Python mode\n    if (w.param->SIMULATION_MODE == \"test\"){\n        n_w = MatrixXd::Zero(N, 3 * param->T_MAX);\n        for (int i = 0; i < N; i++){\n            for(int j=0; j< n_w.cols(); j++){\n                if (j%3 == 0){\n                    n_w(i,j) = Tools::get_normal(s0(0,4), pow(s0(0,15),0.5), w.myrng);\n                } else {\n                    if (j%3 == 1){\n                        n_w(i,j) = Tools::get_normal(s0(0,6), pow(s0(0,16),0.5), w.myrng);\n                    }else{\n                        n_w(i,j) = Tools::get_normal(s0(0,13), pow(s0(0,17),0.5), w.myrng);\n                    };\n                    \n                };\n                n_w(i,j) = std::max(0.0, (double)n_w(i,j));\n            };\n        };\n    };\n    \n    //call estimator of results of steps, given theta_x\n    n_s = m_s0;\n    _step_opt_CS(theta_x, &n_w, &n_x, &n_s, &n_c, &n_v, theta_V, &v_bf_ret, 1);\n    _c = (n_c + param->BETA*n_v).mean();\n    \n    s0.row(0) = n_s.row(0);\n    \n    \n    //    std::cout << s0 << std::endl;\n    \n    return _c;\n    \n};\n\n\nvoid\nH::opt_QL(){\n    //find best action for the state\n    \n    //find current bin for the state\n    _s0();\n    std::vector<double> s_bin = _place_state_QL(s0);\n    s_t_bin = s_bin;\n    std::vector<int> Q_s;\n    \n    \n    //create list of all indexes that correspond to current state\n    for (int i = 0; i < s_bin.size(); i++){\n        for (int j = 0; j< Q.cols(); j++){\n            if (_is_bin(j, i, s_bin)){\n                Q_s.push_back(j);\n            };\n            \n        };\n    };\n    \n    //find index with max Q\n    std::vector<int> Q_max;\n    double max = Q(4,Q_s.at(0));\n    \n    for (auto j:Q_s){\n        if (Q(4,j) > max){\n            max = Q(4,j);\n            Q_max.clear();\n            Q_max.push_back(j);\n            \n        }else{\n            if (Q(4,j) == max){\n                Q_max.push_back(j);\n            };\n        };\n        \n    };\n    \n    \n    \n    \n    boost::random::uniform_01<> _exp_dist;\n    double exp_rate = _exp_dist(w.rng);\n    \n    boost::random::uniform_int_distribution<> Q_dist(0, Q.cols()-1);\n    long theta_max_i;\n    \n    \n    if (exp_rate < param->QL_experimental_rate){\n        theta_max_i = Q_dist(w.rng);\n    }else{\n        //pick randomly best action\n        if (Q_max.size()>1){\n            boost::random::uniform_int_distribution<> Q_max_dist(0, Q_max.size()-1);\n            theta_max_i = Q_max.at(Q_max_dist(w.rng));\n            \n        }else{\n            theta_max_i = Q_max.front();\n        };\n    };\n    \n    theta_x_t_bin.push_back(theta_max_i);\n    \n    //transform from index to decision\n    theta_x.row(0) = Q.block(s_bin.size(),theta_max_i,3,1).transpose();\n    \n};\n\nbool\nH::_is_bin(int j, int i, std::vector<double>& s_bin){\n    bool is_bin = false;\n    \n    if (i < s_bin.size()){\n        is_bin = (Q(i,j) == Q_bin.at(i).at(s_bin.at(i))) && _is_bin(j, i+1, s_bin);\n        //        std::cout << (Q(i,j) == s_bin.at(i)) << std::endl;\n        //        std::cout << _is_bin(j, i+1, s_bin) << std::endl;\n    }else{\n        is_bin = true;\n    };\n    \n    return is_bin;\n};\n\n\n\nvoid\nH::wm_update_Q(){\n    //updates Q matrix\n    //reward\n    double R_t1 = account->g_t.at(account->g_t.size()-2);\n    \n    //new state\n    _s0();\n    std::vector<double> s_bin = _place_state_QL(s0);\n    std::vector<int> Q_s;\n    \n    \n    //create list of all indexes that correspond to current state\n    for (int i = 0; i < s_bin.size(); i++){\n        for (int j = 0; j< Q.cols(); j++){\n            if (_is_bin(j, i+1, s_bin)){\n                Q_s.push_back(j);\n            };\n            \n        };\n    };\n    \n    //find index with max Q\n    std::vector<int> Q_max;\n    double max = Q(4,Q_s.at(0));\n    \n    for (auto j:Q_s){\n        if (Q(4,j) > max){\n            max = Q(4,j);\n            Q_max.clear();\n            Q_max.push_back(j);\n            \n        }else{\n            if (Q(4,j) == max){\n                Q_max.push_back(j);\n            };\n        };\n        \n    };\n    \n    //pick best action\n    long theta_max_i;\n    long max_i;\n    if (Q_max.size()>1){\n        boost::random::uniform_int_distribution<> Q_max_dist(0, Q_max.size()-1);\n        max_i = Q_max_dist(w.rng);\n        theta_max_i = Q_max.at(max_i);\n    }else{\n        theta_max_i = Q_max.front();\n    };\n    \n    \n    //update Q value\n    Q(4,theta_x_t_bin.back()) = Q(4,theta_x_t_bin.back())\n    + Q(5,theta_x_t_bin.back())\n    * (R_t1 + param->BETA*Q(4,theta_max_i) - Q(4,theta_x_t_bin.back()));\n    //    std::cout << Q << std::endl;\n    \n};\n\n\n\nvoid\nH::_set_QL(){\n    //setup QL matrix\n    //create matrix for the grid - small size here\n\tQ_grid = Eigen::MatrixXd::Zero(6,3);\n    \n    //money and stock of goods on hand\n    Q_grid(0,0) = 0.0;\n    Q_grid(0,1) = 10.0;\n    Q_grid(0,2) = ((Q_grid(0,1) - Q_grid(0,0))/2);\n    \n    create_decision_grid(Q_grid, 1);\n\n    //Q factors\n    Q_grid(4,0) = 0.0;\n    Q_grid(4,1) = 0.1;\n    Q_grid(4,2) = 1.0;\n    \n    Q_grid(5,0) = param->QL_L; //speed of learning\n    Q_grid(5,1) = Q_grid(5,0) + 0.1;\n    Q_grid(5,2) = Q_grid(5,0) + 1.0;\n    \n    if (w.param->SIMULATION_MODE == \"test\"){\n        Tools::mgrid_test(Q_grid, &Q);\n        \n    } else{\n        \n        Tools::mgrid(Q_grid, &Q);\n    };\n    \n    create_bin_values(Q_grid, Q_bin);\n    \n    //update Q to push to hiring all of them\n    for (int j = 0; j < Q.cols(); j++){\n        if (Q(1,j) == Q_bin.at(1).back()){\n            Q(4,j) = 0.05;\n        };\n    };\n    \n    \n    //    std::cout << Q << std::endl;\n    \n    //    Tools::print_vector(Q_bin);\n    \n};\n\n\nvoid\nH::create_bin_values(Eigen::MatrixXd& _grid, std::vector<std::vector<double>>& _bin){\n    long N_rows = _grid.rows();\n\tint n_steps_i;\n\tdouble n_steps_i_int;\n    \n\tdouble val;\n    std::vector<double> values_temp;\n    \n    //create matrix of bin values\n    //create list of values\n\tfor (int i=0; i < N_rows; i++){\n\t\t//n_steps\n\t\tn_steps_i_int = (_grid(i,1) - _grid(i,0))/_grid(i,2);\n        \n\t\tn_steps_i = static_cast<int>(floor(n_steps_i_int)) + 1;\n        \n        \n\t\tfor (int j=0; j<n_steps_i; j++){\n\t\t\tval = _grid(i,0) + _grid(i,2)*j;\n\t\t\tvalues_temp.push_back(val);\n\t\t};\n        \n\t\t_bin.push_back(values_temp);\n\t\tvalues_temp.clear();\n\t};\n    \n};\n\n\nstd::vector<double>\nH::_place_state_QL(Eigen::MatrixXd& s){\n    std::vector<double> s_bin;\n    \n    //pick first and compare\n    //push values for bins ina  vector\n    \n    bool FLAG_PLACED = false;\n    \n    int j = Q_bin.at(0).size()-1;\n    while ((j>=0) && !FLAG_PLACED){\n        \n        if (s(0,0) >= Q_bin.at(0).at(j)){\n            s_bin.push_back(j);\n            FLAG_PLACED = true;\n        };\n        j -= 1;\n    };\n    \n    return s_bin;\n};\n\nvoid\nH::create_decision_grid(Eigen::MatrixXd& grid, int begin_index){\n    int i = begin_index;\n    \n    if (param->GRID == \"small\"){\n\t\tgrid(i,0) = 0.0;\n\t\tgrid(i,1) = 1.1;\n\t\tgrid(i,2) = 1.0;\n\t\tgrid(i+1,0) = 0.8;\n\t\tgrid(i+1,1) = 1.25;\n\t\tgrid(i+1,2) = 0.2;\n\t\tgrid(i+2,0) = 0.0;\n\t\tgrid(i+2,1) = 1.0;\n\t\tgrid(i+2,2) = 0.5;\n\t};\n    \n    if (param->GRID == \"big\"){\n\t\tgrid(i,0) = 0.0;\n\t\tgrid(i,1) = 1.1;\n\t\tgrid(i,2) = 1.0;\n\t\tgrid(i+1,0) = 0.1;\n\t\tgrid(i+1,1) = 2.1;\n\t\tgrid(i+1,2) = 0.45;\n\t\tgrid(i+2,0) = 0.0;\n\t\tgrid(i+2,1) = 1.0;\n\t\tgrid(i+2,2) = 0.5;\n        \n\t};\n    if (param->GRID == \"test\"){\n        \n        grid(i,0) = 1.0;\n        grid(i,1) = 1.1;\n        grid(i,2) = 1.0;\n        \n        grid(i+1,0) = 0.8;\n        grid(i+1,1) = 1.2;\n        grid(i+1,2) = 1.0;\n        \n        grid(i+2,0) = 0.5;\n        grid(i+2,1) = 1.1;\n        grid(i+2,2) = 1.0;\n        \n    };\n    \n    \n};\n\nvoid\nH::_set_mRE(){\n    //\n    mRE_grid = Eigen::MatrixXd::Zero(4,3);\n    create_decision_grid(mRE_grid, 0);\n    mRE_grid(3,0) = 1.0;\n    mRE_grid(3,1) = 1.1;\n    mRE_grid(3,2) = 1.0;\n    \n    if (w.param->SIMULATION_MODE == \"test\"){\n        Tools::mgrid_test(mRE_grid, &mRE);\n        \n    } else{\n        \n        Tools::mgrid(mRE_grid, &mRE);\n    };\n    \n    \n    \n    create_bin_values(mRE_grid, mRE_bin);\n    \n    //update mRE to push to hiring all of them\n    for (int j = 0; j < mRE.cols(); j++){\n        if (mRE(0,j) == mRE_bin.at(0).back()){\n            mRE(3,j) = 1.05;\n        };\n    };\n    \n};\n\n\n\nvoid\nH::opt_mRE(){\n    //form matrix of probabilities\n    double sum_prob = 0.0;\n    \n    for (int j=0; j<mRE.cols();j++){\n        sum_prob += exp(mRE(3,j)/param->mRE_T);\n    };\n    \n    std::vector<double> probs;\n    \n    for (int j=0; j<mRE.cols();j++){\n        probs.push_back(exp(mRE(3,j)/param->mRE_T)/sum_prob);\n    };\n    \n    \n    //roll weighted dice\n    boost::random::discrete_distribution<> dist(probs.begin(), probs.end());\n    \n    \n    int theta_i = dist(w.rng);\n    \n    theta_x_t_bin.push_back(theta_i);\n    \n    //transform from index to decision\n    theta_x.row(0) = mRE.block(0,theta_i,3,1).transpose();\n    \n};\n\n\n\nvoid\nH::wm_update_mRE(){\n    //adjustment matrix\n    Eigen::MatrixXd _E_re  = Eigen::MatrixXd::Zero(1, mRE.cols());\n    \n    //reward\n    double R_t1 = account->g_t.at(account->g_t.size()-2);\n    \n    //adjustment\n    _E_re = mRE.row(3) * (param->mRE_EPSILON/(mRE.cols()-1));\n    \n    //include reward\n    _E_re(0,theta_x_t_bin.back()) = R_t1 * (1 - param->mRE_EPSILON);\n    \n    //update whole matrix\n    mRE.row(3) = mRE.row(3) * (1 - param->mRE_PHI) + _E_re;\n    \n\n};\n\n\n\n\n\n\n\n\n\nbool\nH::_PS_accept_PO(MessagePSSendPayment* mes){\n\treturn true;\n};\n\n\n\nContractBDt0*\nH::_PS_contract(){\n\treturn ass_asCBDt0.front();\n};\n\n\n\n", "meta": {"hexsha": "2933e99c158b8d8823b4e4d22e56111eb4216203", "size": 40303, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/H.cpp", "max_stars_repo_name": "wilfeli/DMGameBasic", "max_stars_repo_head_hexsha": "ccc5e7ba08ee4e1959c60421692540cafb1faeed", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2017-08-11T23:12:44.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-04T08:54:19.000Z", "max_issues_repo_path": "src/H.cpp", "max_issues_repo_name": "wilfeli/DMGameBasic", "max_issues_repo_head_hexsha": "ccc5e7ba08ee4e1959c60421692540cafb1faeed", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/H.cpp", "max_forks_repo_name": "wilfeli/DMGameBasic", "max_forks_repo_head_hexsha": "ccc5e7ba08ee4e1959c60421692540cafb1faeed", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-08-02T20:23:21.000Z", "max_forks_repo_forks_event_max_datetime": "2020-08-02T20:23:21.000Z", "avg_line_length": 22.6421348315, "max_line_length": 110, "alphanum_fraction": 0.4968860879, "num_tokens": 13008, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7431680086124811, "lm_q2_score": 0.46879062662624377, "lm_q1q2_score": 0.34839019644602276}}
{"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#ifdef NUKLEI_HAS_PARTIAL_VIEW\n\n#define CGAL_EIGEN3_ENABLED\n\n#include <CGAL/Simple_cartesian.h>\n#include <CGAL/AABB_tree.h>\n#include <CGAL/AABB_traits.h>\n#include <CGAL/Polyhedron_3.h>\n#include <CGAL/AABB_polyhedron_triangle_primitive.h>\n#include <CGAL/property_map.h>\n#include <CGAL/IO/read_off_points.h>\n#include <CGAL/IO/read_xyz_points.h>\n#include <CGAL/IO/write_xyz_points.h>\n#include <CGAL/IO/Polyhedron_iostream.h>\n\n#include <CGAL/squared_distance_3.h>\n#include <CGAL/Point_with_normal_3.h>\n\n#endif\n\n#include <nuklei/KernelCollection.h>\n#include <nuklei/ObservationIO.h>\n\n#include <boost/shared_ptr.hpp>\n\n#include <nuklei/KernelCollection.h>\n\n#ifdef NUKLEI_HAS_PARTIAL_VIEW\n\ntypedef CGAL::Simple_cartesian<double> K;\ntypedef K::Point_3 Point;\ntypedef K::Plane_3 Plane;\ntypedef K::Vector_3 Vector;\ntypedef K::Segment_3 Segment;\ntypedef K::Line_3 Line;\ntypedef CGAL::Polyhedron_3<K> Polyhedron;\ntypedef CGAL::AABB_polyhedron_triangle_primitive<K,Polyhedron> Primitive;\ntypedef CGAL::AABB_traits<K, Primitive> Traits;\ntypedef CGAL::AABB_tree<Traits> Tree;\ntypedef Tree::Object_and_primitive_id Object_and_primitive_id;\ntypedef Tree::Primitive_id Primitive_id;\n\ntypedef CGAL::Point_with_normal_3<K> Point_with_normal;\ntypedef std::vector<Point_with_normal> PointList;\n\n#endif\n\nnamespace nuklei {\n\n  typedef std::vector< std::pair< Vector3, std::vector<int> > > viewcache_t;\n\n#ifdef NUKLEI_HAS_PARTIAL_VIEW\n  \n  \n  inline bool isVisible(const Vector3& wtarget,\n                        const Vector3& wnormal,\n                        const Vector3& wcamera,\n                        const Polyhedron& poly,\n                        const Tree& tree,\n                        const coord_t& tolerance)\n  {\n    if (std::fabs(wnormal.SquaredLength()-1) < FLOATTOL)\n    {\n      Vector3 ctot = la::normalized(wtarget-wcamera);\n      double dot = wnormal.Dot(ctot);\n      if (std::acos(std::fabs(dot)) > (80./180*M_PI))\n      {\n        return false;\n      }\n    }\n    \n    Point camera(wcamera.X(), wcamera.Y(), wcamera.Z());\n    Point target(wtarget.X(), wtarget.Y(), wtarget.Z());\n    \n    //double d = dot();\n    Segment segment_query(camera,target);\n    bool visible = true;\n    \n    std::list<Object_and_primitive_id> intersections;\n    tree.all_intersections(segment_query, std::back_inserter(intersections));\n    \n    int self_intersect = 0;\n    for (std::list<Object_and_primitive_id>::const_iterator intersection = intersections.begin();\n         intersection != intersections.end(); ++intersection)\n    {\n      Object_and_primitive_id op = *intersection;\n      CGAL::Object object = op.first;\n      Point intersectionPoint;\n      if(CGAL::assign(intersectionPoint,object))\n      {\n        double sq2 = squared_distance(intersectionPoint, target);\n        if (sq2 < tolerance*tolerance) self_intersect++;\n      }\n      else\n      {\n        // This is very unlikely (p<<0.001)\n        //NUKLEI_THROW(\"intersection is not a point!\");\n      }\n    }\n    \n    int num_inter = intersections.size();\n    if (self_intersect > 1)\n      NUKLEI_LOG(\"Number of self-intersections (\" << self_intersect << \") greater than 1\");\n    \n    if (num_inter == 0)\n      visible = true;\n    else\n    {\n      if (num_inter - self_intersect > 0)\n        visible = false;\n      else\n        visible = true;\n    }\n    if (num_inter > 1 && visible)\n      NUKLEI_INFO(\"Strange visibility at\" << target);\n    \n    return visible;\n    \n  }\n  \n  inline bool isVisible(const Vector3& wtarget,\n                        const Vector3& wcamera,\n                        const Polyhedron& poly,\n                        const Tree& tree,\n                        const coord_t& tolerance)\n  {\n    return isVisible(wtarget,\n                     Vector3::ZERO,\n                     wcamera,\n                     poly,\n                     tree,\n                     tolerance);\n  }\n\n#endif\n  \n  bool KernelCollection::isVisibleFrom(const Vector3& p, const Vector3& viewpoint,\n                                       const coord_t& tolerance) const\n  {\n    NUKLEI_TRACE_BEGIN();\n#ifdef NUKLEI_HAS_PARTIAL_VIEW\n    if (!deco_.has_key(MESH_KEY))\n      NUKLEI_THROW(\"Undefined mesh. Call buildMesh() first.\");\n    if (!deco_.has_key(AABBTREE_KEY))\n      NUKLEI_THROW(\"Undefined AABB tree. Call buildMesh() first.\");\n    \n    return isVisible(p, viewpoint,\n                     *deco_.get< boost::shared_ptr<Polyhedron> >(MESH_KEY),\n                     *deco_.get< boost::shared_ptr<Tree> >(AABBTREE_KEY),\n                     tolerance);\n#else\n    NUKLEI_THROW(\"This function requires the partial view build of Nuklei. See http://nuklei.sourceforge.net/doxygen/group__install.html\");\n#endif\n    NUKLEI_TRACE_END();\n  }\n  \n  bool KernelCollection::isVisibleFrom(const kernel::r3xs2p& p, const Vector3& viewpoint,\n                                       const coord_t& tolerance) const\n  {\n    NUKLEI_TRACE_BEGIN();\n#ifdef NUKLEI_HAS_PARTIAL_VIEW\n    if (!deco_.has_key(MESH_KEY))\n      NUKLEI_THROW(\"Undefined mesh. Call buildMesh() first.\");\n    if (!deco_.has_key(AABBTREE_KEY))\n      NUKLEI_THROW(\"Undefined AABB tree. Call buildMesh() first.\");\n\n    return isVisible(p.loc_, p.dir_, viewpoint,\n                     *deco_.get< boost::shared_ptr<Polyhedron> >(MESH_KEY),\n                     *deco_.get< boost::shared_ptr<Tree> >(AABBTREE_KEY),\n                     tolerance);\n#else\n    NUKLEI_THROW(\"This function requires the partial view build of Nuklei. See http://nuklei.sourceforge.net/doxygen/group__install.html\");\n#endif\n    NUKLEI_TRACE_END();\n  }\n\n  template<typename C>\n  C KernelCollection::partialView(const Vector3& viewpoint,\n                                  const coord_t& tolerance,\n                                  const bool useViewcache,\n                                  const bool useRayToSurfacenormalAngle) const\n  {\n    NUKLEI_TRACE_BEGIN();\n\n    C index_collection;\n\n    if (!useViewcache)\n    {\n#ifdef NUKLEI_HAS_PARTIAL_VIEW\n      if (!deco_.has_key(MESH_KEY))\n        NUKLEI_THROW(\"Undefined mesh. Call buildMesh() first.\");\n      if (!deco_.has_key(AABBTREE_KEY))\n        NUKLEI_THROW(\"Undefined AABB tree. Call buildMesh() first.\");\n      \n      const Polyhedron& poly = *deco_.get< boost::shared_ptr<Polyhedron> >(MESH_KEY);\n      const Tree& tree = *deco_.get< boost::shared_ptr<Tree> >(AABBTREE_KEY);\n      \n      for (const_iterator v = begin(); v != end(); ++v)\n      {\n        Vector3 p = v->getLoc();\n        Vector3 normal = Vector3::ZERO;\n        if (useRayToSurfacenormalAngle)\n          normal = kernel::r3xs2p(*v).dir_;\n        if (isVisible(p, normal, viewpoint, poly, tree, tolerance))\n          index_collection.push_back(std::distance(begin(), v));\n      }\n#else\n      NUKLEI_THROW(\"This function requires the partial view build of Nuklei. See http://nuklei.sourceforge.net/doxygen/group__install.html\");\n#endif\n    }\n    else\n    {\n      if (!deco_.has_key(VIEWCACHE_KEY))\n        NUKLEI_THROW(\"Undefined view cache. Call buildPartialViewCache() first.\");\n\n      const viewcache_t &viewIndex = *deco_.get< boost::shared_ptr<viewcache_t> >(VIEWCACHE_KEY);\n      \n      double minDist = 1e6;\n      viewcache_t::const_iterator closest = as_const(viewIndex).begin();\n      for (viewcache_t::const_iterator oo = as_const(viewIndex).begin(); oo != viewIndex.end(); ++oo)\n      {\n        double tmp = (viewpoint-oo->first).SquaredLength();\n        if (tmp < minDist*minDist)\n        {\n          minDist = tmp;\n          closest = oo;\n        }\n      }\n      for (std::vector<int>::const_iterator i = closest->second.begin(); i != closest->second.end(); ++i)\n        index_collection.push_back(*i);\n    }\n    return index_collection;\n    NUKLEI_TRACE_END();\n  }\n  \n  \n  std::vector<int> KernelCollection::partialView(const Vector3& viewpoint,\n                                                 const coord_t& tolerance,\n                                                 const bool useViewcache,\n                                                 const bool useRayToSurfacenormalAngle) const\n  {\n    NUKLEI_TRACE_BEGIN();\n#ifdef NUKLEI_HAS_PARTIAL_VIEW\n    return partialView< std::vector<int> >(viewpoint, tolerance, useViewcache, useRayToSurfacenormalAngle);\n#else\n    NUKLEI_THROW(\"This function requires the partial view build of Nuklei. See http://nuklei.sourceforge.net/doxygen/group__install.html\");\n#endif\n    NUKLEI_TRACE_END();\n  }\n  \n  \n  KernelCollection::const_partialview_iterator KernelCollection::partialViewBegin(const Vector3& viewpoint,\n                                                                                  const coord_t& tolerance,\n                                                                                  const bool useViewcache,\n                                                                                  const bool useRayToSurfacenormalAngle) const\n  {\n    NUKLEI_TRACE_BEGIN();\n#ifdef NUKLEI_HAS_PARTIAL_VIEW\n    \n    typedef const_partialview_iterator::index_container\n    index_container;\n    typedef const_partialview_iterator::index_container_ptr\n    index_container_ptr;\n    typedef const_partialview_iterator::index_t\n    index_t;\n    \n    index_container_ptr index_collection(new index_container);\n    *index_collection = partialView< index_container >(viewpoint, tolerance, useViewcache, useRayToSurfacenormalAngle);\n    \n    return const_partialview_iterator(begin(), index_collection);\n#else\n    NUKLEI_THROW(\"This function requires the partial view build of Nuklei. See http://nuklei.sourceforge.net/doxygen/group__install.html\");\n#endif\n    NUKLEI_TRACE_END();\n  }\n  \n  void KernelCollection::buildPartialViewCache(const double meshTol, const bool useRayToSurfacenormalAngle)\n  {\n    NUKLEI_TRACE_BEGIN();\n#ifdef NUKLEI_HAS_PARTIAL_VIEW\n    Vector3 mean = as_const(*this).moments()->getLoc();\n    double stdev = as_const(*this).moments()->getLocH();\n    \n    std::vector< Vector3 > keys;\n    for (int o = 0; o < 10000; ++o)\n    {\n      Vector3 key = Random::uniformDirection3d();\n      keys.push_back(key);\n    }\n    \n    {\n      double minDist2 = .15;\n      std::vector< Vector3 > tmp = keys;\n      keys.clear();\n      for (std::vector<Vector3>::const_iterator\n           i = tmp.begin();\n           i != tmp.end(); ++i)\n      {\n        bool cnt = false;\n        Vector3 iLoc = (*i);\n        for (std::vector<Vector3>::const_iterator\n             j = keys.begin();\n             j != keys.end(); ++j)\n        {\n          if ( (iLoc - *j).SquaredLength() < minDist2*minDist2 )\n          {\n            cnt = true;\n            break;\n          }\n        }\n        if (!cnt)\n        {\n          keys.push_back(iLoc);\n        }\n      }\n    }\n    \n    boost::shared_ptr<viewcache_t> viewIndex(new viewcache_t());\n    \n    for (unsigned int o = 0; o < keys.size(); ++o)\n    {\n      Vector3 key = keys.at(o);\n      Vector3 vp = mean + key*stdev*20;\n      std::vector<int> vi = as_const(*this).partialView(vp, meshTol, false, useRayToSurfacenormalAngle);\n#if 0\n      // debug - delete when code is considered stable\n      KernelCollection v;\n      for (std::vector<int>::iterator i = vi.begin(); i != vi.end(); ++i)\n        v.add(as_const(*this).at(*i));\n      v.computeKernelStatistics();\n      kernel::base::ptr k = v.randomKernel().create();\n      k->setLoc(vp);\n      v.add(*k);\n      v.computeKernelStatistics();\n#endif\n      viewIndex->push_back(std::make_pair(key, vi));\n    }\n    \n    if (deco_.has_key(VIEWCACHE_KEY)) deco_.erase(VIEWCACHE_KEY);\n    deco_.insert(VIEWCACHE_KEY, viewIndex);\n    \n#if 0\n    // debug - delete when code is considered stable\n    \n      for (viewcache_t::iterator o = viewIndex->begin(); o != viewIndex->end(); ++o)\n      {\n        double d = 1e6;\n        KernelCollection near;\n        \n        for (viewcache_t::iterator oo = viewIndex->begin(); oo != viewIndex->end(); ++oo)\n        {\n          if (oo == o) continue;\n          double dd = (o->first-oo->first).Length();\n          if (dd < d) {\n            d = dd;\n            near.clear();\n            for (std::vector<int>::iterator j = oo->second.begin(); j != oo->second.end(); ++j)\n              near.add(as_const(*this).at(*j));\n            near.computeKernelStatistics();\n            if (near.size() == 0) continue;\n            kernel::base::ptr k = near.randomKernel().create();\n            k->setLoc(mean + oo->first*stdev*20);\n            near.add(*k);\n            near.computeKernelStatistics();\n          }\n        }\n        for (KernelCollection::iterator i = near.begin(); i != near.end(); ++i)\n        {\n          ColorDescriptor cd;\n          cd.setColor(RGBColor(1, 0, 0));\n          i->setDescriptor(cd);\n        }\n        for (std::vector<int>::iterator j = o->second.begin(); j != o->second.end(); ++j)\n        {\n          near.add(as_const(*this).at(*j));\n          near.back().setLoc(near.back().getLoc()+Vector3(0.001, 0, 0));\n        }\n        near.computeKernelStatistics();\n        if (near.size() == 0) continue;\n        kernel::base::ptr k = near.randomKernel().create();\n        k->setLoc(mean + o->first*stdev*20);\n        near.add(*k);\n        near.computeKernelStatistics();\n        writeObservations(\"/tmp/v/\" + stringify(std::distance(viewIndex->begin(), o)), near, Observation::SERIAL);\n      }\n#endif\n    \n#else\n    NUKLEI_THROW(\"This function requires the partial view build of Nuklei. See http://nuklei.sourceforge.net/doxygen/group__install.html\");\n#endif\n    NUKLEI_TRACE_END();\n\n  }\n\n}\n\n", "meta": {"hexsha": "c06735c3dc9009f45fdf036d93ceef84651ef969", "size": 13549, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libnuklei/kernel/KernelCollectionPartialView.cpp", "max_stars_repo_name": "chungying/nuklei", "max_stars_repo_head_hexsha": "23db2a55a1b3260cf913d0ac10b3b27c000ae1a6", "max_stars_repo_licenses": ["BSD-3-Clause"], "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/kernel/KernelCollectionPartialView.cpp", "max_issues_repo_name": "chungying/nuklei", "max_issues_repo_head_hexsha": "23db2a55a1b3260cf913d0ac10b3b27c000ae1a6", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/kernel/KernelCollectionPartialView.cpp", "max_forks_repo_name": "chungying/nuklei", "max_forks_repo_head_hexsha": "23db2a55a1b3260cf913d0ac10b3b27c000ae1a6", "max_forks_repo_licenses": ["BSD-3-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.6203473945, "max_line_length": 141, "alphanum_fraction": 0.6052107167, "num_tokens": 3326, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7956581000631541, "lm_q2_score": 0.4378234991142019, "lm_q1q2_score": 0.3483578134682079}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\n\n// Copyright (c) 2019 Barend Gehrels, Amsterdam, the Netherlands.\n\n// Use, modification and distribution is subject to the Boost Software License,\n// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n\n#ifndef BOOST_GEOMETRY_ALGORITHMS_DETAIL_OVERLAY_GET_DISTANCE_MEASURE_HPP\n#define BOOST_GEOMETRY_ALGORITHMS_DETAIL_OVERLAY_GET_DISTANCE_MEASURE_HPP\n\n#include <boost/geometry/core/access.hpp>\n#include <boost/geometry/core/coordinate_system.hpp>\n#include <boost/geometry/core/coordinate_type.hpp>\n#include <boost/geometry/util/select_coordinate_type.hpp>\n\n#include <cmath>\n\nnamespace boost { namespace geometry\n{\n\n#ifndef DOXYGEN_NO_DETAIL\nnamespace detail\n{\n\ntemplate <typename T>\nstruct distance_measure\n{\n    T measure;\n\n    distance_measure()\n        : measure(T())\n    {}\n\n    bool is_small() const { return true; }\n    bool is_zero() const { return true; }\n    bool is_positive() const { return false; }\n    bool is_negative() const { return false; }\n};\n\ntemplate <typename T>\nstruct distance_measure_floating\n{\n    T measure;\n\n    distance_measure_floating()\n        : measure(T())\n    {}\n\n    // Returns true if the distance measure is small.\n    // This is an arbitrary boundary, to enable some behaviour\n    // (for example include or exclude turns), which are checked later\n    // with other conditions.\n    bool is_small() const { return std::abs(measure) < 1.0e-3; }\n\n    // Returns true if the distance measure is absolutely zero\n    bool is_zero() const { return measure == 0.0; }\n\n    // Returns true if the distance measure is positive. Distance measure\n    // algorithm returns positive value if it is located on the left side.\n    bool is_positive() const { return measure > 0.0; }\n\n    // Returns true if the distance measure is negative. Distance measure\n    // algorithm returns negative value if it is located on the right side.\n    bool is_negative() const { return measure < 0.0; }\n};\n\ntemplate <>\nstruct distance_measure<long double>\n    : public distance_measure_floating<long double> {};\n\ntemplate <>\nstruct distance_measure<double>\n    : public distance_measure_floating<double> {};\n\ntemplate <>\nstruct distance_measure<float>\n    : public distance_measure_floating<float> {};\n\n} // detail\n\n\nnamespace detail_dispatch\n{\n\n// TODO: this is effectively a strategy, but for internal usage.\n// It might be moved to the strategies folder.\n\ntemplate <typename CalculationType, typename CsTag>\nstruct get_distance_measure\n        : not_implemented<CsTag>\n{};\n\ntemplate <typename CalculationType>\nstruct get_distance_measure<CalculationType, cartesian_tag>\n{\n    typedef detail::distance_measure<CalculationType> result_type;\n\n    template <typename SegmentPoint, typename Point>\n    static result_type apply(SegmentPoint const& p1, SegmentPoint const& p2,\n                             Point const& p)\n    {\n        typedef CalculationType ct;\n\n        // Construct a line in general form (ax + by + c = 0),\n        // (will be replaced by a general_form structure in next PR)\n        ct const x1 = geometry::get<0>(p1);\n        ct const y1 = geometry::get<1>(p1);\n        ct const x2 = geometry::get<0>(p2);\n        ct const y2 = geometry::get<1>(p2);\n        ct const a = y1 - y2;\n        ct const b = x2 - x1;\n        ct const c = -a * x1 - b * y1;\n\n        // Returns a distance measure\n        // https://en.wikipedia.org/wiki/Distance_from_a_point_to_a_line#Line_defined_by_an_equation\n        // dividing by sqrt(a*a+b*b) is not necessary for this distance measure,\n        // it is not a real distance and purpose is to detect small differences\n        // in collinearity\n        result_type result;\n        result.measure = a * geometry::get<0>(p) + b * geometry::get<1>(p) + c;\n\n        return result;\n    }\n};\n\ntemplate <typename CalculationType>\nstruct get_distance_measure<CalculationType, spherical_tag>\n{\n    typedef detail::distance_measure<CalculationType> result_type;\n\n    template <typename SegmentPoint, typename Point>\n    static result_type apply(SegmentPoint const& , SegmentPoint const& ,\n                             Point const& )\n    {\n        // TODO, optional\n        result_type result;\n        return result;\n    }\n};\n\ntemplate <typename CalculationType>\nstruct get_distance_measure<CalculationType, geographic_tag>\n        : get_distance_measure<CalculationType, spherical_tag> {};\n\n\n} // namespace detail_dispatch\n\nnamespace detail\n{\n\n// Returns a (often very tiny) value to indicate its side, and distance,\n// 0 (absolutely 0, not even an epsilon) means collinear. Like side,\n// a negative means that p is to the right of p1-p2. And a positive value\n// means that p is to the left of p1-p2.\n\ntemplate <typename cs_tag, typename SegmentPoint, typename Point>\nstatic distance_measure<typename select_coordinate_type<SegmentPoint, Point>::type>\nget_distance_measure(SegmentPoint const& p1, SegmentPoint const& p2, Point const& p)\n{\n    return detail_dispatch::get_distance_measure\n            <\n                typename select_coordinate_type<SegmentPoint, Point>::type,\n                cs_tag\n            >::apply(p1, p2, p);\n\n}\n\n} // namespace detail\n#endif // DOXYGEN_NO_DETAIL\n\n}} // namespace boost::geometry\n\n#endif // BOOST_GEOMETRY_ALGORITHMS_DETAIL_OVERLAY_GET_DISTANCE_MEASURE_HPP\n", "meta": {"hexsha": "a306cb442168d4271541de52ce482e54f749fbf2", "size": 5351, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "3rdParty/boost/1.71.0/boost/geometry/algorithms/detail/overlay/get_distance_measure.hpp", "max_stars_repo_name": "rajeev02101987/arangodb", "max_stars_repo_head_hexsha": "817e6c04cb82777d266f3b444494140676da98e2", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 12278.0, "max_stars_repo_stars_event_min_datetime": "2015-01-29T17:11:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T21:12:00.000Z", "max_issues_repo_path": "3rdParty/boost/1.71.0/boost/geometry/algorithms/detail/overlay/get_distance_measure.hpp", "max_issues_repo_name": "rajeev02101987/arangodb", "max_issues_repo_head_hexsha": "817e6c04cb82777d266f3b444494140676da98e2", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 9469.0, "max_issues_repo_issues_event_min_datetime": "2015-01-30T05:33:07.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T16:17:21.000Z", "max_forks_repo_path": "3rdParty/boost/1.71.0/boost/geometry/algorithms/detail/overlay/get_distance_measure.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": 30.5771428571, "max_line_length": 100, "alphanum_fraction": 0.7022986358, "num_tokens": 1222, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6859494678483918, "lm_q2_score": 0.5078118642792044, "lm_q1q2_score": 0.34833327806942005}}
{"text": "#include <scitbx/array_family/boost_python/flex_fwd.h>\n\n#include <boost/python/class.hpp>\n#include <boost/python/args.hpp>\n#include <boost/python/return_value_policy.hpp>\n#include <boost/python/return_by_value.hpp>\n#include <boost/python/copy_const_reference.hpp>\n\n#include <scitbx/math/chebyshev.h>\n\nnamespace scitbx { namespace math {\n\nnamespace {\n\n\n  struct chebyshev_base_wrappers\n  {\n    typedef chebyshev::chebyshev_base<> w_t;\n\n    static void\n    wrap()\n    {\n      using namespace boost::python;\n\n      class_<w_t>(\"chebyshev_base\", no_init)\n        .def(init<std::size_t const&,\n                  double const&,\n                  double const&>((arg(\"n_terms\"),\n                                  arg(\"low_limit\"),\n                                  arg(\"high_limit\") )))\n        .def(init<std::size_t const& ,\n                  double const&,\n                  double const&,\n                  scitbx::af::const_ref<double> const&>\n             ((arg(\"n_terms\"),\n               arg(\"low_limit\"),\n               arg(\"high_limit\"),\n               arg(\"cheb_coefs\") )))\n        .def(\"f\", (double(w_t::*)(double const&)) &w_t::f)\n        .def(\"f\", (scitbx::af::shared<double>(w_t::*)\n                   (scitbx::af::const_ref<double> const&))\n                    &w_t::f )\n        .def(\"coefs\", &w_t::coefs )\n        .def(\"replace\", &w_t::replace )\n        ;\n\n    }\n\n\n  };\n\n\n  struct chebyshev_polynome_wrappers\n  {\n    typedef chebyshev::chebyshev_polynome<> w_t;\n\n    static void\n    wrap()\n    {\n      using namespace boost::python;\n\n      class_<w_t>(\"chebyshev_polynome\", no_init)\n        .def(init<std::size_t const& ,\n                  double const&,\n                  double const&,\n                  scitbx::af::const_ref<double> const&>\n             ((arg(\"n_terms\"),\n               arg(\"low_limit\"),\n               arg(\"high_limit\"),\n               arg(\"cheb_coefs\") )))\n        .def(\"f\", (double(w_t::*)(double const&)) &w_t::f)\n        .def(\"f\", (scitbx::af::shared<double>(w_t::*)\n                   (scitbx::af::const_ref<double> const&))\n                    &w_t::f )\n        .def(\"coefs\", &w_t::coefs )\n\n        .def(\"dfdx\", (double(w_t::*)(double const&)) &w_t::dfdx)\n        .def(\"dfdx\", (scitbx::af::shared<double>(w_t::*)\n                      (scitbx::af::const_ref<double> const&))\n             &w_t::dfdx )\n        .def(\"dfdx_coefs\", &w_t::dfdx_coefs)\n        ;\n\n    }\n\n\n  };\n\n\n  struct chebyshev_fitter_wrappers\n  {\n    typedef chebyshev::chebyshev_fitter<> w_t;\n\n    static void\n    wrap()\n    {\n      using namespace boost::python;\n\n      class_<w_t>(\"chebyshev_fitter\", no_init)\n        .def(init<std::size_t const& ,\n                  double const&,\n                  double const& >\n             ((arg(\"n_terms\"),\n               arg(\"low_limit\"),\n               arg(\"high_limit\") )))\n        .def(init<std::size_t const& ,\n                  double const&,\n                  double const&,\n                  scitbx::af::const_ref<double> const&>\n             ((arg(\"n_terms\"),\n               arg(\"low_limit\"),\n               arg(\"high_limit\"),\n               arg(\"cheb_coefs\") )))\n\n\n        .def(\"f\", (double(w_t::*)(double const&)) &w_t::f)\n        .def(\"f\", (scitbx::af::shared<double>(w_t::*)\n                   (scitbx::af::const_ref<double> const&))\n                    &w_t::f )\n        .def(\"coefs\", &w_t::coefs )\n        .def(\"replace\", &w_t::replace)\n        .def(\"dfdcoefs\", &w_t::dfdcoefs)\n        ;\n\n    }\n\n\n  };\n\n\n\n\n\n  struct chebyshev_smooth_wrappers\n  {\n    typedef chebyshev::chebyshev_smooth<> w_t;\n\n    static void\n    wrap()\n    {\n      using namespace boost::python;\n\n      class_<w_t>(\"chebyshev_smooth\", no_init)\n        .def(init<std::size_t const&,\n                  double const&,\n                  double const&>((arg(\"n_terms\"),\n                                  arg(\"low_limit\"),\n                                  arg(\"high_limit\") )))\n        .def(init<std::size_t const& ,\n                  double const&,\n                  double const&,\n                  scitbx::af::const_ref<double> const&>\n             ((arg(\"n_terms\"),\n               arg(\"low_limit\"),\n               arg(\"high_limit\"),\n               arg(\"cheb_coefs\") )))\n        .def(\"f\", (double(w_t::*)(double const&)) &w_t::f)\n        .def(\"f\", (scitbx::af::shared<double>(w_t::*)\n                   (scitbx::af::const_ref<double> const&))\n                    &w_t::f )\n        .def(\"coefs\", &w_t::smooth_coefs )\n        .def(\"replace\", &w_t::replace_and_smooth )\n        ;\n\n    }\n\n\n  };\n\n\n\n  struct chebyshev_smooth_fitter_wrappers\n  {\n    typedef chebyshev::chebyshev_smooth_fitter<> w_t;\n\n    static void\n    wrap()\n    {\n      using namespace boost::python;\n\n      class_<w_t>(\"chebyshev_smooth_fitter\", no_init)\n        .def(init<std::size_t const&,\n                  double const&,\n                  double const&>((arg(\"n_terms\"),\n                                  arg(\"low_limit\"),\n                                  arg(\"high_limit\") )))\n        .def(init<std::size_t const& ,\n                  double const&,\n                  double const&,\n                  scitbx::af::const_ref<double> const&>\n             ((arg(\"n_terms\"),\n               arg(\"low_limit\"),\n               arg(\"high_limit\"),\n               arg(\"cheb_coefs\") )))\n        .def(\"f\", (double(w_t::*)(double const&)) &w_t::f)\n        .def(\"f\", (scitbx::af::shared<double>(w_t::*)\n                   (scitbx::af::const_ref<double> const&))\n                    &w_t::f )\n        .def(\"coefs\", &w_t::smooth_coefs )\n        .def(\"replace\", &w_t::replace_and_smooth )\n        .def(\"dfdcoefs\", &w_t::dfdcoefs)\n        ;\n\n    }\n\n\n  };\n\n\n\n\n  struct chebyshev_lsq_wrappers\n  {\n    typedef chebyshev::chebyshev_lsq<> w_t;\n\n    static void\n    wrap()\n    {\n      using namespace boost::python;\n\n      class_<w_t>(\"chebyshev_lsq\", no_init)\n        .def(init<std::size_t const&,\n                  double const&,\n                  double const&,\n                  scitbx::af::const_ref<double> const&,\n                  scitbx::af::const_ref<double> const&,\n                  scitbx::af::const_ref<double> const&,\n                  scitbx::af::const_ref<bool> const&\n                  >((arg(\"n_terms\"),\n                     arg(\"low_limit\"),\n                     arg(\"high_limit\"),\n                     arg(\"x_obs\"),\n                     arg(\"y_obs\"),\n                     arg(\"w_obs\"),\n                     arg(\"free_flags\") )))\n\n        .def(\"residual\", &w_t::residual)\n        .def(\"free_residual\", &w_t::free_residual)\n        .def(\"gradient\", &w_t::gradient )\n        .def(\"replace\", &w_t::replace )\n        .def(\"coefs\", &w_t::coefs)\n        ;\n\n    }\n\n\n  };\n\n\n\n\n\n\n\n\n} // namespace <anonymous>\n\nnamespace boost_python {\n\n\n  void wrap_chebyshev_base()\n  {\n    chebyshev_base_wrappers::wrap();\n  }\n  void wrap_chebyshev_polynome()\n  {\n    chebyshev_polynome_wrappers::wrap();\n  }\n  void wrap_chebyshev_fitter()\n  {\n    chebyshev_fitter_wrappers::wrap();\n  }\n\n  void wrap_chebyshev_smooth()\n  {\n    chebyshev_smooth_wrappers::wrap();\n  }\n  void wrap_chebyshev_smooth_fitter()\n  {\n    chebyshev_smooth_fitter_wrappers::wrap();\n  }\n\n  void wrap_chebyshev_lsq()\n  {\n    chebyshev_lsq_wrappers::wrap();\n  }\n\n\n\n}}} // namespace scitbx::math::boost_python\n", "meta": {"hexsha": "a442b3fe0141da2946f86c9aca73598745dacd1b", "size": 7240, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "scitbx/math/boost_python/chebyshev.cpp", "max_stars_repo_name": "rimmartin/cctbx_project", "max_stars_repo_head_hexsha": "644090f9432d9afc22cfb542fc3ab78ca8e15e5d", "max_stars_repo_licenses": ["BSD-3-Clause-LBNL"], "max_stars_count": 155.0, "max_stars_repo_stars_event_min_datetime": "2016-11-23T12:52:16.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T15:35:44.000Z", "max_issues_repo_path": "scitbx/math/boost_python/chebyshev.cpp", "max_issues_repo_name": "rimmartin/cctbx_project", "max_issues_repo_head_hexsha": "644090f9432d9afc22cfb542fc3ab78ca8e15e5d", "max_issues_repo_licenses": ["BSD-3-Clause-LBNL"], "max_issues_count": 590.0, "max_issues_repo_issues_event_min_datetime": "2016-12-10T11:31:18.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T23:10:09.000Z", "max_forks_repo_path": "scitbx/math/boost_python/chebyshev.cpp", "max_forks_repo_name": "rimmartin/cctbx_project", "max_forks_repo_head_hexsha": "644090f9432d9afc22cfb542fc3ab78ca8e15e5d", "max_forks_repo_licenses": ["BSD-3-Clause-LBNL"], "max_forks_count": 115.0, "max_forks_repo_forks_event_min_datetime": "2016-11-15T08:17:28.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-09T15:30:14.000Z", "avg_line_length": 24.8797250859, "max_line_length": 64, "alphanum_fraction": 0.4914364641, "num_tokens": 1905, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6859494550081926, "lm_q2_score": 0.5078118642792044, "lm_q1q2_score": 0.34833327154901456}}
{"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 <cstddef>\n#include <cassert>\n#include <cstring>\n#include <cstdlib>\n#include <cstdio>\n#include <cfloat>\n#include <vector>\n\n#include <boost/random/mersenne_twister.hpp>\n#include <boost/random/uniform_real.hpp>\n#include <boost/random/variate_generator.hpp>\n\n#include \"NPY.hpp\"\n#include \"NPlanck.hpp\"\n#include \"NCIE.hpp\"\n\n#include \"GAry.hh\"\n#include \"GDomain.hh\"\n\n#include \"PLOG.hh\"\n\n\n\ntemplate <typename T>\nT GAry<T>::np_interp(const T z, GAry<T>* xp, GAry<T>* fp )\n{\n    // input domain and values\n    //   \n    //  :param z:   \"x\" domain value for which the interpolated \"y\" value is to be obtained\n    //  :param xp : domain x-coordinates of the data points, must be increasing.\n    //  :param fp : value  y-coordinates of the data points, same length as `xp`.\n    //  \n    //  :return:   y value (ie linear interpolation of fp values) corresponding to the ordinate supplied \n    //   \n\n    T* dx = xp->getValues();   \n\n    T* dy = fp->getValues();   \n    T left = fp->getLeft();\n    T right = fp->getRight();\n\n    int len = xp->getLength();\n \n    assert( len > 0 );\n \n    if(dy[len-1] != right )\n    {\n        LOG(warning) << \"GAry<T>::np_interp \"\n                     << \" len \" << len\n                     << \" dy[len-1] \" << dy[len-1]\n                     << \" right \" << right\n                     << \" left \" << left\n                     ;\n    }\n\n    assert(dy[len-1] == right );\n\n\n/*\n   This assert is firing occasionally... but unreproducibly \n\n[2015-Jul-22 15:28:16.828602]: GProperty::save 2d array of length 275 to : /tmp/reemissionCDF.npy\ncreateZeroTrimmed ifr 0 ito 273 \nnp_sliced ifr 0 ito 273  alen 275 blen 273 \nnp_sliced ifr 0 ito 273  alen 275 blen 273 \nGBoundaryLib::createReemissionBuffer icdf  : 570b234e132f398d4213400cc88f427b : 4096 \nd       0.000      0.063      0.125      0.188      0.250      0.313      0.375      0.438      0.500      0.563      0.625      0.688      0.750      0.813      0.875      0.938\nv     799.898    463.793    450.234    441.314    434.113    428.762    424.561    420.824    417.127    413.177    408.946    404.907    401.409    398.164    394.649    389.214\n[2015-Jul-22 15:28:16.834756]: GProperty::save 2d array of length 4096 to : /tmp/invertedReemissionCDF.npy\nAssertion failed: (dy[len-1] == right), function np_interp, file /Users/blyth/env/optix/ggeo/GAry.cc, line 39.\nAbort trap: 6\n\n[2015-Jul-24 10:30:36.403821]: GProperty::save 2d array of length 4096 to : /tmp/invertedReemissionCDF.npy\n[2015-Jul-24 10:30:36.443812]: GAry<T>::np_interp  len 4096 dy[len-1] nan right nan left 799.898\nAssertion failed: (dy[len-1] == right), function np_interp, file /Users/blyth/env/optix/ggeo/GAry.cc, line 50.\n/Users/blyth/env/graphics/ggeoview/ggeoview.bash: line 550:  2369 Abort trap: 6           $bin $*\n\n*/\n\n    T ival ;\n    int j = xp->binary_search(z);  // find low side domain index corresponding to domain value z\n    if(j == -1)\n    {\n        ival = left;\n    }\n    else if(j == len - 1)\n    {\n        ival = dy[j]; // right \n    }\n    else if(j == len )\n    {\n        ival = right;\n    }\n    else\n    {\n        const T slope  = (dy[j + 1] - dy[j])/(dx[j + 1] - dx[j]);\n        ival = slope*(z - dx[j]) + dy[j];\n    }\n    return ival ; \n}\n\n\ntemplate <typename T>\nGAry<T>* GAry<T>::np_interp(GAry<T>* xi, GAry<T>* xp, GAry<T>* fp )\n{\n    //\n    // Loosely follow np.interp signature and implementation from \n    //    https://github.com/numpy/numpy/blob/v1.9.1/numpy/lib/src/_compiled_base.c#L599\n    //\n\n    assert(xp->getLength() == fp->getLength());  // input domain and values must be of same length\n\n    GAry<T>* res = new GAry<T>(xi->getLength()); // Ary to be filled with interpolated values\n    T* dres = res->getValues();\n\n    for (unsigned int i = 0; i < res->getLength() ; i++) \n    {\n        dres[i] = np_interp( xi->getValue(i), xp, fp ) ;\n    }\n    return res ;\n}\n\ntemplate <typename T>\nGAry<T>* np_product(GAry<T>* a, GAry<T>* b)\n{\n    assert(a->getLength() == b->getLength()); \n    GAry<T>* prod = new GAry<T>(a->getLength()); // Ary to be filled with interpolated values\n    for (unsigned int i = 0; i < prod->getLength() ; i++) \n    {\n       T ab = a->getValue(i) * b->getValue(i);\n       prod->setValue(i, ab );\n    }\n    return prod ;\n}\n\ntemplate <typename T>\nGAry<T>* np_subtract(GAry<T>* a, GAry<T>* b)\n{\n    assert(a->getLength() == b->getLength()); \n    GAry<T>* result = new GAry<T>(a->getLength()); \n    for (unsigned int i = 0; i < result->getLength() ; i++) \n    {\n       T ab = b->getValue(i) - a->getValue(i);\n       result->setValue(i, ab );\n    }\n    return result ;\n}\n\n\ntemplate <typename T>\nGAry<T>* np_add(GAry<T>* a, GAry<T>* b)\n{\n    assert(a->getLength() == b->getLength()); \n    GAry<T>* result = new GAry<T>(a->getLength()); \n    for (unsigned int i = 0; i < result->getLength() ; i++) \n    {\n       T ab = b->getValue(i) + a->getValue(i);\n       result->setValue(i, ab );\n    }\n    return result ;\n}\n\n\ntemplate <typename T>\nGAry<T>* np_clip(GAry<T>* a, GAry<T>* low, GAry<T>* high, GAry<T>* low_fallback, GAry<T>* high_fallback )\n{\n    assert(a->getLength() == low->getLength()); \n    assert(a->getLength() == high->getLength()); \n    if(low_fallback) assert(a->getLength() == low_fallback->getLength()); \n    if(high_fallback) assert(a->getLength() == high_fallback->getLength()); \n\n    GAry<T>* cc = new GAry<T>(a->getLength()); \n    for (unsigned int i = 0; i < cc->getLength() ; i++) \n    {\n        T aa = a->getValue(i);\n        T lo = low->getValue(i);\n        T hi = high->getValue(i);\n\n        if( aa < lo )\n        {\n            cc->setValue(i, low_fallback ? low_fallback->getValue(i) : lo );\n        }\n        else if(aa > hi )\n        {\n            cc->setValue(i, high_fallback ? high_fallback->getValue(i) : hi );\n        }\n        else\n        {\n            cc->setValue(i, aa );\n\n        }\n    }\n    return cc ;\n}\n\n\n\n\n\ntemplate <typename T>\nT np_maxdiff(GAry<T>* a, GAry<T>* b, bool dump)\n{\n\n    unsigned alen = a->getLength() ;\n    unsigned blen = b->getLength() ;\n \n    if(dump) LOG(info) << \" np_maxdiff \" \n                       << \" a \" << std::setw(5) << alen\n                       << \" b \" << std::setw(5) << blen\n                       ;\n\n    assert(alen == blen); \n    T max(0);\n    for (unsigned int i = 0; i < a->getLength() ; i++) \n    {\n       T av = a->getValue(i);\n       T bv = b->getValue(i);\n       T ab = bv - av ;\n\n       max = std::max( max, ab );\n\n       if(dump) LOG(info) \n                    <<  \" i \" << std::setw(4) << i\n                    <<  \" av \" << std::setw(10) << av \n                    <<  \" bv \" << std::setw(10) << bv \n                    <<  \" ab \" << std::setw(10) << ab \n                    ; \n\n    }\n\n    if(dump) LOG(info) << \" maxdiff \" << max ; \n\n    return max ;\n}\n\n\n\n\n\n\ntemplate <typename T>\nGAry<T>* np_cumsum(GAry<T>* y, unsigned int offzero)\n{\n    unsigned int len = y->getLength();\n    GAry<T>* cy = new GAry<T>(len+offzero); // Ary to be filled with cumsum values\n    T sum(0);\n    for (unsigned int j = 0; j < offzero ; j++) \n    {\n        cy->setValue(j, 0);\n    }\n    for (unsigned int i = 0; i < len ; i++) \n    {\n        sum += y->getValue(i);\n        cy->setValue(offzero+i, sum);\n    }\n    return cy ;\n}\n\ntemplate <typename T>\nGAry<T>* np_reversed(GAry<T>* y, bool reciprocal, T scale)\n{\n    unsigned int len = y->getLength();\n    GAry<T>* ry = new GAry<T>(len); \n\n    for (unsigned int i = 0; i < len ; i++)\n    {\n        T val = y->getValue(i) ; \n        ry->setValue(len-1-i, reciprocal ? scale/val : scale*val );\n    }\n    return ry ;\n}\n\n\ntemplate <typename T>\nGAry<T>* GAry<T>::reciprocal(GAry<T>* y, T scale)\n{\n    unsigned int len = y->getLength();\n    GAry<T>* ry = new GAry<T>(len); \n    for (unsigned int i = 0; i < len ; i++)\n    {\n        T val = y->getValue(i) ; \n        ry->setValue(i, scale/val );\n    }\n    return ry ;\n}\n\n\n\n\ntemplate <typename T>\nGAry<T>* g4_groupvel_bintrick(GAry<T>* y)\n{\n   /*\n    This curious bin shifting is used by G4 GROUPVEL calc\n\n    In order not to loose a bin\n    a tricky manoever of using the 1st and last bin and \n    the average of the body bins\n    which means the first bin is half width, and last is 1.5 width\n    \n    ::\n\n            0  +  1  +  2  +  3  +  4  +  5        <--- 6 original values\n            |    /     /     /     /      |\n            |   /     /     /     /       |\n            0  1     2     3     4        5        <--- still 6 \n\n\n    bb = np.zeros_like(aa)\n    bb[0] = aa[0]\n    bb[1:-1] = (aa[1:-1] + aa[:-2])/2.\n    bb[-1] = aa[-1]\n    return bb\n\n   */\n\n    GAry<T>& Y = *y ;\n    unsigned int len = y->getLength();\n    GAry<T>* ry = new GAry<T>(len); \n\n    ry->setValue(0    , Y[0]);\n    ry->setValue(len-1, Y[-1]);\n\n    T two(2);\n\n    for (unsigned i = 1; i < len - 1 ; i++)\n    {\n        T val = (Y[i-1] + Y[i])/two ; \n        ry->setValue(i, val );\n    }\n    return ry ;\n}\n\ntemplate <typename T>\nGAry<T>* np_gradient(GAry<T>* y)\n{\n    /*\n    Take a look at np.gradient??\n\n    The gradient is computed using second order accurate central differences\n    in the interior and either first differences or second order accurate \n    one-sides (forward or backwards) differences at the boundaries. The\n    returned gradient hence has the same shape as the input array.\n\n          0    <--- (0,1)  \n  \n          1    <--- (0,2)/2\n          2    <--- (1,3)/2\n          3    <--  (2,4)/2\n          4    <--  (3,5)/2\n          5    <--  (4,6)/2\n          6    <--  (5,7)/2\n          7    <--  (6,8)/2\n          8    <--  (7,9)/2\n\n          9    <--  (8,9) \n\n    ::\n\n        out = np.zeros_like(y)\n        out[0] = y[1] - y[0]\n        out[1:-1] = (y[2:]-y[:-2])/2.0\n        out[-1] = y[-1] - y[-2]\n        return o\n    */\n\n    GAry<T>& Y = *y ;\n    unsigned int len = y->getLength();\n    assert(len >= 2 );\n    T two(2);\n\n    GAry<T>* g = new GAry<T>(len); \n    g->setValue(0    , Y[1] - Y[0] );\n    for (unsigned i = 1; i < len - 1 ; i++) g->setValue(i, (Y[i+1] - Y[i-1])/two );\n    g->setValue(len-1, Y[-1] - Y[-2]);\n\n    return g ;\n}\n\n\ntemplate <typename T>\nGAry<T>* np_sliced(GAry<T>* a, int ifr, int ito)\n{\n   /*\n\nIn [13]: a = np.linspace(0,1,11)\n\nIn [14]: a\nOut[14]: array([ 0. ,  0.1,  0.2,  0.3,  0.4,  0.5,  0.6,  0.7,  0.8,  0.9,  1. ])\n\nIn [16]: a[0:-1]\nOut[16]: array([ 0. ,  0.1,  0.2,  0.3,  0.4,  0.5,  0.6,  0.7,  0.8,  0.9])\n\nIn [17]: a[0:11]\nOut[17]: array([ 0. ,  0.1,  0.2,  0.3,  0.4,  0.5,  0.6,  0.7,  0.8,  0.9,  1. ])\n\n   */\n    int alen = a->getLength();\n    if(ifr < 0 ) ifr += alen ;   \n    if(ito < 0 ) ito += alen ;   \n    assert(ifr >=0 && ifr <  alen);\n    assert(ito >=0 && ito <= alen);\n\n    int blen = ito - ifr ;   // py style 0-based one-beyond \"ito\"\n    assert( ito >= ifr );\n\n    //printf(\"Gary.cc:np_sliced ifr %d ito %d  alen %u blen %u \\n\", ifr, ito, alen, blen );  \n\n    GAry<T>* b = new GAry<T>(blen); \n\n    for (int ia = 0; ia < alen ; ia++)\n    {\n        if( ia >= ifr && ia < ito )\n        {\n            unsigned int ib = ia - ifr ;\n            T val = a->getValue(ia) ; \n            b->setValue( ib, val );\n        }\n    }     \n    return b ;\n}\n\n\n\n\n\ntemplate <typename T>\nGAry<T>* np_diff(GAry<T>* y)\n{\n    unsigned int len = y->getLength() ;\n    GAry<T>* dy = new GAry<T>(len - 1); \n    for (unsigned int i = 0; i < len - 1 ; i++)\n    {\n        T diff = y->getValue(i+1) - y->getValue(i) ; \n        dy->setValue(i, diff );\n    }\n    return dy ;\n}\n\ntemplate <typename T>\nGAry<T>* np_mid(GAry<T>* y)\n{\n    unsigned int len = y->getLength() ;\n    GAry<T>* my = new GAry<T>(len - 1); \n    T two(2);\n    for (unsigned int i = 0; i < len - 1 ; i++)\n    {\n        T mid = (y->getValue(i) + y->getValue(i+1))/two ; \n        my->setValue(i, mid );\n    }\n    return my ;\n}\n\n\ntemplate <typename T>\nGAry<T>* GAry<T>::urandom(unsigned int length)\n{\n    GAry<T>* u = new GAry<T>(length); \n    T* vals = u->getValues();\n\n    typedef boost::mt19937          RNG_t;\n    typedef boost::uniform_real<>   Distrib_t;\n    typedef boost::variate_generator< RNG_t, Distrib_t > Generator_t ;\n\n    RNG_t rng;\n    Distrib_t distrib(0,1);\n    Generator_t gen(rng, distrib);    \n\n    for (unsigned int i = 0; i < length ; i++) vals[i] = gen();\n    return u ;\n}\n\n\ntemplate <typename T>\nGAry<T>* GAry<T>::from_domain(GDomain<T>* domain)\n{\n    GAry<T>* ary = new GAry<T>( domain->getLength(), domain->getValues() );\n    return ary ; \n}\n\n\ntemplate <typename T>\nGAry<T>* GAry<T>::planck_spectral_radiance(GAry<T>* nm, T blackbody_temp_kelvin)\n{\n    T* nmv = nm->getValues();\n    GAry<T>* ary = new GAry<T>( nm->getLength(), NULL );\n    T* vals = ary->getValues();\n    for(unsigned int i=0 ; i < ary->getLength(); i++) vals[i] = ::planck_spectral_radiance(nmv[i], blackbody_temp_kelvin) ;  \n    return ary ;\n}\n\ntemplate <typename T>\nGAry<T>* GAry<T>::cie_weight(GAry<T>* nm, unsigned int component)\n{\n    T* nmv = nm->getValues();\n    GAry<T>* ary = new GAry<T>( nm->getLength(), NULL );\n    T* vals = ary->getValues();\n    for(unsigned int i=0 ; i < ary->getLength(); i++) \n    {\n        switch(component)\n        {\n            case 0:vals[i] = NCIE::X(nmv[i]) ;break;  \n            case 1:vals[i] = NCIE::Y(nmv[i]) ;break;  \n            case 2:vals[i] = NCIE::Z(nmv[i]) ;break;  \n        }\n    }\n    return ary ;\n}\n\n\ntemplate <typename T>\nGAry<T>* GAry<T>::cie_X(GAry<T>* nm)\n{\n    return cie_weight(nm, 0);\n}\ntemplate <typename T>\nGAry<T>* GAry<T>::cie_Y(GAry<T>* nm)\n{\n    return cie_weight(nm, 1);\n}\ntemplate <typename T>\nGAry<T>* GAry<T>::cie_Z(GAry<T>* nm)\n{\n    return cie_weight(nm, 2);\n}\n\n\n\n\n\n\n\n\n\ntemplate <typename T>\nGAry<T>* GAry<T>::create_from_floats(unsigned int length, float* values)\n{\n    // promoting floats to doubles\n    T* tvalues = new T[length];\n    for(unsigned int i=0 ; i < length ; i++) tvalues[i] = values[i];\n    GAry<T>* ary = new GAry<T>(length, tvalues);\n    delete[] tvalues ;       \n    return ary ;\n}\n\ntemplate <typename T>\nGAry<T>* GAry<T>::product(GAry<T>* a, GAry<T>* b)\n{\n    return np_product(a, b);\n}\n\ntemplate <typename T>\nGAry<T>* GAry<T>::subtract(GAry<T>* a, GAry<T>* b)\n{\n    return np_subtract(a, b);\n}\ntemplate <typename T>\nGAry<T>* GAry<T>::add(GAry<T>* a, GAry<T>* b)\n{\n    return np_add(a, b);\n}\n\n\ntemplate <typename T>\nGAry<T>* GAry<T>::clip(GAry<T>* low, GAry<T>* high, GAry<T>* low_fallback, GAry<T>* high_fallback )\n{\n    return np_clip(this, low, high, low_fallback, high_fallback );\n}\n\n\ntemplate <typename T>\nT GAry<T>::maxdiff(GAry<T>* a, GAry<T>* b, bool dump)\n{\n    return np_maxdiff(a, b, dump);\n}\n\ntemplate <typename T>\nGAry<T>* GAry<T>::reciprocal(T scale_)\n{\n    return reciprocal(this, scale_);\n}\n\n\n\n\n\n\ntemplate <typename T>\nGAry<T>* GAry<T>::from_constant(unsigned int length, T value )\n{\n    GAry<T>* ary = new GAry<T>( length, NULL );\n    T* vals = ary->getValues();\n    for(unsigned int i=0 ; i < length; i++) vals[i] = value ;\n    return ary ;\n} \n\n\ntemplate <typename T>\nGAry<T>* GAry<T>::zeros(unsigned int length)\n{\n    return GAry<T>::from_constant(length, 0);\n} \n\ntemplate <typename T>\nGAry<T>* GAry<T>::ones(unsigned int length)\n{\n    return GAry<T>::from_constant(length, 1);\n} \n\n\n\n\n\ntemplate <typename T>\nGAry<T>* GAry<T>::ramp(unsigned int length, T low, T step )\n{\n    GAry<T>* ary = new GAry<T>( length, NULL );\n    T* vals = ary->getValues();\n    for(unsigned int i=0 ; i < length; i++) vals[i] = low + step*i ;  \n    return ary ;\n} \n\n\ntemplate <typename T>\nT GAry<T>::step(T num, T start, T stop)\n{\n    return (stop - start)/(num - 1) ; \n}\n\ntemplate <typename T>\nGAry<T>* GAry<T>::linspace(T num, T start, T stop)\n{\n   /*\nIn [11]: np.linspace(0,1,10)\nOut[11]: \narray([ 0.   ,  0.111,  0.222,  0.333,  0.444,  0.556,  0.667,  0.778,\n        0.889,  1.   ])\n\nIn [12]: np.linspace(0,1,11)\nOut[12]: array([ 0. ,  0.1,  0.2,  0.3,  0.4,  0.5,  0.6,  0.7,  0.8,  0.9,  1. ])\n\n   */\n    T step_ = step(num, start, stop);\n    GAry<T>* ary = new GAry<T>( num, NULL );\n    T* vals = ary->getValues();\n    for(unsigned int i=0 ; i < num ; i++) vals[i] = start + step_*i ;  \n    return ary ;\n} \n\n\ntemplate <typename T>\nGAry<T>* GAry<T>::copy() \n{\n    return new GAry<T>(this);\n}\n\ntemplate <typename T>\nGAry<T>::GAry(GAry<T>* other) : m_length(other->getLength())\n{\n    m_values = new T[m_length];\n    for(unsigned int i=0 ; i < m_length; i++) m_values[i] = other->getValue(i) ;\n}\n\ntemplate <typename T>\nGAry<T>::GAry(unsigned int length, T* values) : m_length(length)\n{\n    m_values = new T[m_length];\n    if(values)\n    {\n        for(unsigned int i=0 ; i < length; i++) m_values[i] = values[i] ;\n    }\n} \n\ntemplate <typename T>\nGAry<T>::~GAry() \n{\n    delete m_values ;\n}\n\n\n\ntemplate <typename T>\nvoid GAry<T>::setValues(T val)\n{\n    for(unsigned int i=0 ; i < m_length; i++) m_values[i] = val ;\n}\n\n\ntemplate <typename T>\nGAry<T>* GAry<T>::cumsum(unsigned int offzero)\n{  \n    return np_cumsum(this, offzero) ; \n}\n\ntemplate <typename T>\nGAry<T>* GAry<T>::g4_groupvel_bintrick()\n{  \n    return ::g4_groupvel_bintrick(this) ; \n}\n\ntemplate <typename T>\nGAry<T>* GAry<T>::gradient()\n{  \n    return ::np_gradient(this) ; \n}\n\n\n\n\n\n\n\ntemplate <typename T>\nGAry<T>* GAry<T>::diff()\n{ \n    return np_diff(this) ; \n}     // domain bin widths\n\ntemplate <typename T>\nGAry<T>* GAry<T>::mid()\n{ \n    return np_mid(this) ; \n}  // average of values at bin edges, ie linear approximation of mid bin \"y\" value \n\ntemplate <typename T>\nGAry<T>* GAry<T>::reversed(bool reciprocal_, T scale_)\n{ \n     return np_reversed(this, reciprocal_, scale_) ; \n}\n\ntemplate <typename T>\nGAry<T>* GAry<T>::sliced(int ifr_, int ito_)\n{ \n     return np_sliced(this, ifr_, ito_) ; \n}\n\n\n\ntemplate <typename T>\nvoid GAry<T>::Summary(const char* msg, unsigned int imod, T presentation_scale)\n{\n    printf(\"%s length %u  leftzero %u rightzero %u \\n\", msg, m_length, getLeftZero(), getRightZero() );\n\n    if(m_length < 100)\n    {\n        for(unsigned int i=0 ; i < m_length ; i++ ) if(i%imod == 0) printf(\" %10.3f \", getValue(i)*presentation_scale);\n        printf(\"\\n\");\n    }\n    else\n    {\n        for(unsigned int i=0 ; i < m_length ; i++ ) \n        {\n            if( i < 10 || i > m_length - 10 )\n            {\n                printf(\" %10.3f \", getValue(i)*presentation_scale);\n            } \n            else if ( i == 10 )\n            {\n                printf(\" ... \");\n            }\n        }\n        printf(\"\\n\");\n   }\n\n    T rng[2] ;\n    unsigned int idx[2] ;\n    rng[0] = min(idx[0]);\n    rng[1] = max(idx[1]);\n\n    printf(\"mi/mx idx %u %u  range %15.5f %15.5f  1/range %15.5f %15.5f \\n\", idx[0], idx[1], rng[0], rng[1], 1./rng[0], 1./rng[1] );\n\n} \n\n\ntemplate <typename T>\nT GAry<T>::getValueFractional(T findex)\n{\n    unsigned int idx(findex);\n    T dva ; \n\n    if(idx + 1 < m_length )\n    {\n       T frac(findex - T(idx));\n       dva = m_values[idx]*(1.-frac) + m_values[idx+1]*frac ;\n    }\n    else\n    {\n       dva = m_values[m_length-1]; \n    } \n    return dva ; \n}\n\ntemplate <typename T>\nT GAry<T>::getValueLookup(T u)\n{\n    // convert u (0:1) into fractional bin, and use that to lookup values\n    assert( u <= 1. && u >= 0. );\n    T findex = u * (m_length - 1) ; \n    return getValueFractional(findex);\n}\n\ntemplate <typename T>\nunsigned int GAry<T>::getLeftZero()\n{\n    // when the values start with a string of zeros, \n    // return the index of rightmost such zero minus 1, \n    // otherwise return 0\n\n    T zero(0);\n    int ifr(0);\n    for(unsigned int i=0 ; i < m_length ; i++)\n    {\n        if( m_values[i] == zero ) ifr = i  ;\n        else\n            break ; \n    }\n\n    return ifr > 0 ? ifr - 1 : 0 ; \n}\n\n\ntemplate <typename T>\nunsigned int GAry<T>::getRightZero()\n{\n    // when the values end with a string of zeros, \n    // return the lowest index + 1, \n    // otherwise return m_length\n\n    T zero(0);\n    unsigned int ito(m_length);\n    for(unsigned int i=0 ; i < m_length ; i++)\n    {\n        unsigned int j = m_length - 1 - i ;   // looks at bins from the right \n        if( m_values[j] == zero ) ito = j  ;\n        else\n            break ; \n    }\n    return ito < m_length ? ito + 1 : m_length ; \n}\n\n\n\ntemplate <typename T>\nvoid GAry<T>::add(GAry<T>* other)\n{  \n    assert(other->getLength() == m_length);\n    for(unsigned int i=0 ; i < m_length ; i++ ) m_values[i] += other->getValue(i) ; \n}\n\ntemplate <typename T>\nvoid GAry<T>::subtract(GAry<T>* other)\n{  \n    assert(other->getLength() == m_length);\n    for(unsigned int i=0 ; i < m_length ; i++ ) m_values[i] -= other->getValue(i) ; \n}\n\n\n\n\ntemplate <typename T>\nvoid GAry<T>::scale(T sc)\n{\n    for(unsigned int i=0 ; i < m_length ; i++ ) m_values[i] *= sc ; \n}  \n\ntemplate <typename T>\nvoid GAry<T>::reciprocate()\n{\n    T one(1);\n    for(unsigned int i=0 ; i < m_length ; i++ ) m_values[i] = one/m_values[i] ; \n}  \n\ntemplate <typename T>\nint GAry<T>::linear_search(T key)\n{\n    // for checking edge case behaviour of binary_search\n    // expected to return same values as binary_search more slowly\n\n    if(key < m_values[0])          \n    {\n        return -1 ;        // indicates \"below-lower-bound\"\n    }\n    else if(key > m_values[m_length-1]) \n    {\n        return m_length ;   // indicates \"above-upper-bound\"\n    }\n    else if(key == m_values[m_length-1])\n    {\n        return m_length - 1 ;   //  at upper bound   \n    }\n    else\n    {\n        for(unsigned int i=0 ; i < m_length - 1 ; ++i )\n        {\n            //   m_values[0] : m_values[1]\n            //   ...\n            //   m_values[m_length-2] : m_values[m_length-1]   \n            //\n            if(key >= m_values[i] && key < m_values[i+1]) return i ;\n        }\n    }  \n    assert(0); // not expected here\n    return -2 ; \n}\n \n\n\ntemplate <typename T>\nint GAry<T>::binary_search(T key)\n{\n   // Find bin index containing the key   \n   //\n   // :param key: value to be \"placed\" within the sequence of ascending values\n   // :return: index of the low side value  \n   //\n   //      * normally index is range 0:m_length-1\n   //      * if the key exceeds m_values[m_length-1] m_length is returned, meaning \"to the right\" \n   //\n   // NB this is used by np_interp \n\n    if(key > m_values[m_length-1])\n    {\n        return m_length ;\n    }\n    unsigned int imin = 0 ; \n    unsigned int imax = m_length ; \n    unsigned int imid ;   \n\n    while(imin < imax)\n    {\n        imid = imin + ((imax - imin) >> 1);\n        if (key >= m_values[imid]) \n        {\n            imin = imid + 1;\n        }\n        else \n        {\n            imax = imid;\n        }\n    }\n\n    assert( imin == imax );\n    //if(imin != imax ) printf(\"GAry<T>::binary_search key %10.5f  imin %u imax %u len %u \\n\", key, imin, imax, m_length );\n\n    return imin - 1; \n} \n\n\ntemplate <typename T>\nT GAry<T>::fractional_binary_search(T u)\n{\n    // the advantage in dealing in fractional indices\n    // is can delay resorting to using domain information for a bit longer\n\n    int idx = binary_search(u);\n    T frac  = (u - m_values[idx])/(m_values[idx+1]-m_values[idx]);  // fraction of bin \n    return T(idx) + frac ; \n}\n\n\n\ntemplate <typename T>\nunsigned int GAry<T>::sample_cdf(T u)\n{\n    // other than edge cases, this gives same results as binary_search\n\n    int lower = 0;\n    int upper = m_length - 1;\n\n    while(lower < upper-1)\n    {   \n        int half = (lower + upper) / 2;\n        if (u < m_values[half])\n        {\n            upper = half;\n        }\n        else \n        {\n            lower = half;\n        }\n    }   \n\n    assert( lower == upper - 1 );\n    return lower ; \n}\n\n\ntemplate <typename T>\nT GAry<T>::min(unsigned& idx) const \n{\n   T mi(FLT_MAX);\n   for(unsigned int i=0 ; i < m_length ; i++ )\n   {\n       T v = m_values[i];\n       if(v < mi)\n       {\n           mi = v ; \n           idx = i ;\n       }\n   }\n   return mi ; \n}\n\ntemplate <typename T>\nT GAry<T>::max(unsigned& idx) const \n{\n   T mx(-FLT_MAX);\n   for(unsigned int i=0 ; i < m_length ; i++ )\n   {\n       T v = m_values[i];\n       if(v > mx)\n       {\n           mx = v ; \n           idx = i ;\n       }\n   }\n   return mx ; \n}\n\n\ntemplate <typename T>\nvoid GAry<T>::save(const char* path)\n{\n    std::vector<int> shape ; \n    shape.push_back(m_length);\n\n    std::string metadata = \"{}\" ; \n\n    std::vector<T> data ; \n    for(unsigned int i=0 ; i < m_length ; i++ ) data.push_back(m_values[i]) ;\n\n    LOG(info) << \"GAry::save 1d array of length \" << m_length << \" to : \" << path ;  \n    NPY<T> npy(shape, data, metadata);\n    npy.save(path);\n}\n\n\n\n\n/*\n* :google:`move templated class implementation out of header`\n* http://www.drdobbs.com/moving-templates-out-of-header-files/184403420\n\nA compiler warning \"declaration does not declare anything\" was avoided\nby putting the explicit template instantiation at the tail rather than the \nhead of the implementation.\n*/\n\ntemplate class GAry<float>;\ntemplate class GAry<double>;   // needs work on NPY for this\n\n\n\n", "meta": {"hexsha": "6f9f44bfe9f2e9b5847e64b5c0f816e0de87cbad", "size": 25366, "ext": "cc", "lang": "C++", "max_stars_repo_path": "ggeo/GAry.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": "ggeo/GAry.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": "ggeo/GAry.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": 23.6182495345, "max_line_length": 178, "alphanum_fraction": 0.5446660885, "num_tokens": 8140, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.6654105653819836, "lm_q1q2_score": 0.3482894303181545}}
{"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#include \"read_pla_to_cirkit_bdd.hpp\"\n\n#include <core/io/pla_processor.hpp>\n#include <core/io/pla_parser.hpp>\n\n#include <classical/dd/bdd.hpp>\n\n#include <boost/format.hpp>\n#include <boost/filesystem/fstream.hpp>\n#include <boost/timer.hpp>\n\nnamespace cirkit\n{\n\nnamespace\n{\n\nclass from_bdd_pla_processor : public pla_processor\n{\npublic:\n  explicit from_bdd_pla_processor( unsigned log_max_objs, bool verbose )\n    : m_log_max_objs( log_max_objs  ),\n      m_verbose( verbose )\n    {}\n\n    void on_comment(const std::string &comment)\n    {\n    }\n\n    void on_num_inputs(unsigned num_inputs)\n    {\n      m_inputs = num_inputs;\n      m_timer.restart();\n    }\n\n    void on_num_outputs(unsigned num_outputs) final\n    {\n      m_outputs = num_outputs;\n    }\n\n    void on_num_products(unsigned num_products) final\n    {\n    }\n\n    void on_input_labels(const std::vector<std::string> &input_labels) final\n    {\n      m_inputNames = input_labels;\n    }\n\n    void on_output_labels(const std::vector<std::string> &output_labels) final\n    {\n      m_outputNames = output_labels;\n    }\n\n    void on_end() final\n    {\n      if ( true /* m_verbose */ )\n      {\n        std::cout\n          << boost::format (\"[i] took %.2f seconds to reading pla-file into BDD.\") % m_timer.elapsed()\n          << std::endl;\n      }\n    }\n\n    void on_type(const std::string &type)\n    {\n    }\n\n    void setPortNames()\n    {\n      assert( m_inputNames.size() <= m_inputs );\n      assert( m_outputNames.size() <= m_outputs );\n\n      for ( auto i = 0u; i < m_inputNames.size(); ++i )\n      {\n        m_function->setInputName ( i, m_inputNames.at ( i ) );\n      }\n\n      for ( auto i = 0u; i < m_outputNames.size(); ++i )\n      {\n        m_function->setOutputName ( i, m_outputNames.at ( i ) );\n      }\n    }\n\n    void initializeInputPorts()\n    {\n      for ( auto i = 0u; i < m_inputs; ++i )\n      {\n        m_function->pushInput ( i );\n      }\n    }\n\n    void initializeOutputPorts(bdd_manager_ptr manager)\n    {\n      auto falseNode = manager->bdd_bot ();\n      std::cout << falseNode << std::endl;\n      for ( auto i = 0u; i < m_outputs; ++i )\n      {\n        m_function->setOutputVar ( i, falseNode );\n      }\n    }\n\n    void initializeFunction () {\n      assert ( m_inputs != 0 );\n      assert ( m_outputs != 0 );\n\n      try {\n        auto function = new bdd_function (\n          m_inputs, m_log_max_objs, m_verbose\n        );\n        m_function.reset ( function );\n\n        initializeInputPorts();\n        initializeOutputPorts( m_function->manager() );\n        setPortNames();\n      }\n      catch ( std::exception const& e )\n      {\n        std::cerr << \"[e] unable to create bdd_function: \" << e.what() << std::endl;\n        throw;\n      }\n    }\n\n    void on_cube(const std::string &in, const std::string &out) final\n    {\n      if ( !m_function ) {\n        initializeFunction ();\n      }\n\n      auto term = getBddCube ( in );\n\n      addToOutputBdds ( term, out );\n    }\n\n    bdd_function_cptr function() const {\n      return m_function;\n    }\n\n  private:\n    void addToOutputBdds ( const bdd& term, const std::string& out ) {\n\n      auto relevantValue = [] ( const char& val )\n      {\n        return val == '1';\n      };\n\n      for ( auto i = 0u; i < out.size(); ++i )\n      {\n        auto const& value = out.at( i );\n        if ( relevantValue ( value ) ) {\n          auto output = m_function->lookupOutput ( i );\n//          std::cout << \"Output: \" << i  << \" is relevant: \" << output << std::endl;\n\n          m_function->setOutputVar ( i, output || term );\n        }\n      }\n    }\n\n\n    bdd getBddCube ( const std::string& cube )\n    {\n      auto manager = m_function->manager ();\n\n      assert ( cube.size() == m_inputs );\n      bdd term = manager->bdd_top ();\n\n      for ( auto i = 0u; i < cube.size(); ++i ) {\n        auto const& val = cube.at( i );\n\n        if ( val != '-') {\n          auto input = m_function->lookupInput( i );\n\n          if ( val == '0')\n          {\n            term = !input && term;\n          }\n          else\n          {\n            term = input && term;\n          }\n        }\n      }\n\n      if ( m_verbose )\n      {\n        std::cout << \"[i] term result:\" << term << std::endl;\n      }\n      return term;\n    }\n\nprivate:\n  unsigned         m_log_max_objs;\n  bool             m_verbose;\n  bdd_function_ptr m_function;\n  unsigned         m_inputs;\n  unsigned         m_outputs;\n\n  boost::timer     m_timer;\n\n  std::vector<std::string> m_inputNames;\n  std::vector<std::string> m_outputNames;\n};\n\n} // anonymous namespace\n\n\nbdd_function::bdd_function(\n      unsigned nvars\n    , unsigned log_max_objs\n    , bool verbose\n) : m_manager ( bdd_manager::create ( nvars, log_max_objs, verbose ) )\n{\n}\n\nbdd_function::bdd_function(bdd_manager_ptr manager)\n  : m_manager ( manager )\n{\n}\n\nbdd_function::~bdd_function()\n{\n}\n\nvoid bdd_function::pushInput ( unsigned index ) {\n  assert ( m_outputs.empty() );\n  auto bdd = m_manager->bdd_var( index );\n  m_inputs.emplace ( index, bdd );\n}\n\nbdd::const_param_ref bdd_function::lookupInput(unsigned index) const\n{\n  auto iter = m_inputs.find ( index );\n  assert ( iter != m_inputs.end() );\n  return iter->second;\n}\n\nbdd::const_param_ref bdd_function::lookupOutput(unsigned index) const\n{\n  auto iter = m_outputs.find ( index );\n  assert ( iter != m_outputs.end() );\n  return iter->second;\n}\n\nvoid bdd_function::setOutputVar(unsigned index, const bdd &var)\n{\n  auto iter = m_outputs.find ( index );\n  if ( iter != m_outputs.end() ) {\n    iter->second = var;\n  }\n  else {\n    m_outputs.emplace ( index, var );\n  }\n}\n\nbdd_manager_ptr bdd_function::manager() const\n{\n  return m_manager;\n}\n\nvoid bdd_function::setInputName(unsigned index, const std::string &name)\n{\n  m_inputNames.emplace ( index, name );\n}\n\nvoid bdd_function::setOutputName(unsigned index, const std::string &name)\n{\n  m_outputNames.emplace ( index, name );\n}\n\nbdd_function_cptr read_pla_into_cirkit_bdd_job( boost::filesystem::ifstream& stream, unsigned log_max_objs, bool verbose )\n{\n  assert ( stream );\n\n  from_bdd_pla_processor processor ( log_max_objs, verbose );\n  try {\n    pla_parser ( stream, processor );\n  } catch ( std::exception const& e ) {\n    std::cerr << \"[e] unable to parse PLA file: \" << e.what() << std::endl;\n    return bdd_function_ptr ();\n  }\n\n  return processor.function();\n}\n\nbdd_function_cptr read_pla_into_cirkit_bdd( const boost::filesystem::path &filename,\n                                            const properties::ptr& settings )\n{\n  assert ( !filename.empty() );\n\n  auto log_max_objs = get( settings, \"log_max_objs\", 24u );\n  auto verbose      = get( settings, \"verbose\",      false );\n\n  boost::filesystem::ifstream stream( filename );\n  if ( !stream ) {\n    std::cerr << \"[e] unable to open file \" << filename << std::endl;\n    return bdd_function_ptr();\n  }\n\n  return read_pla_into_cirkit_bdd_job( stream, log_max_objs, verbose );\n}\n\nstd::vector<std::string> bdd_function::input_labels() const { \n  std::vector<std::string> input_vars;\n  for (auto const &itr: m_inputNames)\n    input_vars.push_back(itr.second);\n  return input_vars; \n}\nstd::vector<std::string> bdd_function::output_labels() const{ \n  std::vector<std::string> output_vars;\n  for (auto const &itr: m_outputNames)\n    output_vars.push_back(itr.second);\n  return output_vars; \n}\n\n} // namespace cirkit\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": "9ac81324acbf3bb27bb9a14ad81a168a4e5267c8", "size": 8631, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/classical/io/read_pla_to_cirkit_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/io/read_pla_to_cirkit_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/io/read_pla_to_cirkit_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": 24.8731988473, "max_line_length": 122, "alphanum_fraction": 0.6207855405, "num_tokens": 2183, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.665410558746814, "lm_q2_score": 0.523420348936324, "lm_q1q2_score": 0.3482894268451717}}
{"text": "/*\n * Copyright (c) 2016 Abhishek Agrawal (abhishek.agrawal@protonmail.com)\n * Distributed under the MIT License.\n * See accompanying file LICENSE.md or copy at http://opensource.org/licenses/MIT\n */\n\n#ifndef PARTICLE_AROUND_SPHEROID_AND_ELLIPSOID_GRAVITATIONAL_POTENTIAL_HPP\n#define PARTICLE_AROUND_SPHEROID_AND_ELLIPSOID_GRAVITATIONAL_POTENTIAL_HPP\n\n#include <cstdlib>\n#include <iostream>\n#include <sstream>\n#include <fstream>\n#include <string>\n#include <cmath>\n#include <limits>\n#include <vector>\n\n#include <boost/numeric/odeint.hpp>\n\n#include \"NAOS/constants.hpp\"\n#include \"NAOS/basicMath.hpp\"\n#include \"NAOS/basicAstro.hpp\"\n#include \"NAOS/misc.hpp\"\n#include \"NAOS/ellipsoidGravitationalAcceleration.hpp\"\n\nnamespace naos\n{\n//! particle around spheroid integration\n/*!\n * integrate the equations of motion for a particle around a spheroid. The gravitational accelerations\n * calculated using the ellipsoid gravitational potential model.\n */\nvoid executeParticleAroundSpheroid( const double alpha,\n                                    const double gravParameter,\n                                    std::vector< double > asteroidRotationVector,\n                                    std::vector< double > &initialOrbitalElements,\n                                    const double initialStepSize,\n                                    const double startTime,\n                                    const double endTime,\n                                    std::ostringstream &outputFilePath,\n                                    const int dataSaveIntervals );\n} // namespace naos\n\n#endif // PARTICLE_AROUND_SPHEROID_AND_ELLIPSOID_GRAVITATIONAL_POTENTIAL_HPP\n", "meta": {"hexsha": "5572fe6feb097473dfc3ed3902f2fbc54da951d3", "size": 1650, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/NAOS/particleAroundSpheroidAndElllipsoidGravitationalPotential.hpp", "max_stars_repo_name": "agrawalabhishek/NAOS", "max_stars_repo_head_hexsha": "25ae383d2c3f9a52ecd2e06f34661e52e239478b", "max_stars_repo_licenses": ["MIT"], "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/NAOS/particleAroundSpheroidAndElllipsoidGravitationalPotential.hpp", "max_issues_repo_name": "agrawalabhishek/NAOS", "max_issues_repo_head_hexsha": "25ae383d2c3f9a52ecd2e06f34661e52e239478b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/NAOS/particleAroundSpheroidAndElllipsoidGravitationalPotential.hpp", "max_forks_repo_name": "agrawalabhishek/NAOS", "max_forks_repo_head_hexsha": "25ae383d2c3f9a52ecd2e06f34661e52e239478b", "max_forks_repo_licenses": ["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.8695652174, "max_line_length": 102, "alphanum_fraction": 0.6672727273, "num_tokens": 335, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.665410558746814, "lm_q2_score": 0.5234203489363239, "lm_q1q2_score": 0.34828942684517167}}
{"text": "/*\n * Flowlessly\n * Copyright (c) Ionel Gog <ionel.gog@cl.cam.ac.uk>\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 * THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR\n * CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT\n * LIMITATION ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR\n * A PARTICULAR PURPOSE, MERCHANTABLITY OR NON-INFRINGEMENT.\n *\n * See the Apache Version 2.0 License for specific language governing\n * permissions and limitations under the License.\n */\n\n#include \"misc/utils.h\"\n\n#include <boost/heap/binomial_heap.hpp>\n#include <algorithm>\n#include <functional>\n#include <limits>\n#include <queue>\n#include <utility>\n\nnamespace flowlessly {\n\nvoid BellmanFord(AdjacencyMapGraph* graph, const set<uint32_t>& active_node_ids,\n                 vector<uint32_t>* predecessor) {\n  const uint32_t max_node_id = graph->get_max_node_id();\n  const auto& arcs = graph->get_arcs();\n  auto& nodes = graph->get_nodes();\n  vector<uint32_t> old_active_ids;\n  for (auto& active_node : active_node_ids) {\n    nodes[active_node].distance = 0;\n    old_active_ids.push_back(active_node);\n  }\n  for (uint32_t iter = 1;\n       iter <= max_node_id && old_active_ids.size();\n       ++iter) {\n    vector<uint32_t> new_active_ids;\n    for (auto& node_id : old_active_ids) {\n      if (nodes[node_id].distance < numeric_limits<int32_t>::max()) {\n        int64_t src_distance = nodes[node_id].distance;\n        for (auto& arc : arcs[node_id]) {\n          int64_t arc_cost = arc.second->cost -\n            nodes[node_id].potential + nodes[arc.first].potential;\n          if (arc.second->residual_cap > 0 &&\n              src_distance + arc_cost < nodes[arc.first].distance) {\n            new_active_ids.push_back(arc.first);\n            nodes[arc.first].distance = src_distance + arc_cost;\n            (*predecessor)[arc.first] = node_id;\n          }\n        }\n      }\n    }\n    old_active_ids = new_active_ids;\n  }\n}\n\nvoid BellmanFordWithoutPotentials(AdjacencyMapGraph* graph,\n                                  const set<uint32_t>& active_node_ids,\n                                  vector<uint32_t>* predecessor) {\n  const uint32_t max_node_id = graph->get_max_node_id();\n  const auto& arcs = graph->get_arcs();\n  auto& nodes = graph->get_nodes();\n  vector<uint32_t> old_active_ids;\n  for (auto& active_node : active_node_ids) {\n    nodes[active_node].distance = 0;\n    old_active_ids.push_back(active_node);\n  }\n  for (uint32_t iter = 1;\n       iter <= max_node_id && old_active_ids.size();\n       ++iter) {\n    vector<uint32_t> new_active_ids;\n    for (auto& node_id : old_active_ids) {\n      if (nodes[node_id].distance < numeric_limits<int32_t>::max()) {\n        int64_t src_distance = nodes[node_id].distance;\n        for (auto& arc : arcs[node_id]) {\n          if (arc.second->residual_cap > 0 &&\n              src_distance + arc.second->cost < nodes[arc.first].distance) {\n            new_active_ids.push_back(arc.first);\n            nodes[arc.first].distance = src_distance + arc.second->cost;\n            (*predecessor)[arc.first] = node_id;\n          }\n        }\n      }\n    }\n    old_active_ids = new_active_ids;\n  }\n}\n\nuint32_t DijkstraOptimized(AdjacencyMapGraph* graph,\n                           const set<uint32_t>& active_node_ids,\n                           vector<uint32_t>* predecessor) {\n  const uint32_t max_node_id = graph->get_max_node_id();\n  const auto& arcs = graph->get_arcs();\n  auto& nodes = graph->get_nodes();\n  boost::heap::binomial_heap<pair<int64_t, uint32_t>,\n                boost::heap::compare<greater<\n                  pair<int64_t, uint32_t> > > > dist_heap;\n  // Handles to the heap elements.\n  boost::heap::binomial_heap<pair<int64_t, uint32_t>,\n                boost::heap::compare<greater<\n                  pair<int64_t, uint32_t> > > >::handle_type\n    *handles =\n    new boost::heap::binomial_heap<pair<int64_t, uint32_t>,\n             boost::heap::compare<greater<\n               pair<int64_t, uint32_t> > > >::handle_type[max_node_id + 1];\n  // ASSUMPTION: Works with the assumption that all the elements of distance are\n  // already set to INF.\n  for (auto& active_node : active_node_ids) {\n    nodes[active_node].distance = 0;\n    nodes[active_node].status = VISITING;\n    handles[active_node] = dist_heap.push(make_pair(0, active_node));\n  }\n  while (dist_heap.size() > 0) {\n    uint32_t min_node_id = dist_heap.top().second;\n    //    CHECK_LE(min_node_id, max_node_id);\n    dist_heap.pop();\n    nodes[min_node_id].status = VISITED;\n    // We've finished visiting a node with negative supply. We can stop the\n    // shortest path algorithm because we want to route flow to this node.\n    if (nodes[min_node_id].supply < 0) {\n      delete [] handles;\n      return min_node_id;\n    }\n    int64_t src_distance = nodes[min_node_id].distance;\n    for (auto& arc : arcs[min_node_id]) {\n      int64_t arc_cost = arc.second->cost - nodes[min_node_id].potential +\n        nodes[arc.first].potential;\n      if (arc.second->residual_cap > 0 &&\n          src_distance + arc_cost < nodes[arc.first].distance) {\n        nodes[arc.first].distance = src_distance + arc_cost;\n        if (nodes[arc.first].status == NOT_VISITED) {\n          // The node's status is set to VISITING the first time we've computed\n          // its distance. On this ocassion we also get a handle to the node's\n          // entry in the binomial heap.\n          nodes[arc.first].status = VISITING;\n          (*predecessor)[arc.first] = min_node_id;\n          handles[arc.first] =\n            dist_heap.push(make_pair(nodes[arc.first].distance, arc.first));\n        } else {\n          (*predecessor)[arc.first] = min_node_id;\n          dist_heap.update(handles[arc.first],\n                           make_pair(nodes[arc.first].distance, arc.first));\n        }\n      }\n    }\n  }\n  delete [] handles;\n  // 0 means that no node has been found.\n  return 0;\n}\n\nvoid DijkstraSimple(AdjacencyMapGraph* graph,\n                    const set<uint32_t>& active_node_ids,\n                    vector<uint32_t>* predecessor) {\n  const uint32_t max_node_id = graph->get_max_node_id();\n  const auto& arcs = graph->get_arcs();\n  auto& nodes = graph->get_nodes();\n  vector<bool> node_used(max_node_id + 1, false);\n  // ASSUMPTION: Works with the assumption that all the elements of distance are\n  // already set to INF.\n  for (auto& active_node : active_node_ids) {\n    nodes[active_node].distance = 0;\n  }\n  for (uint32_t iter = 1; iter <= max_node_id; ++iter) {\n    int64_t min_node_distance = numeric_limits<int32_t>::max();\n    uint32_t min_node_id = 0;\n    // Get the closest unused vertex.\n    for (uint32_t node_id = 1; node_id <= max_node_id; ++node_id) {\n      if (!node_used[node_id] && nodes[node_id].distance < min_node_distance) {\n        min_node_distance = nodes[node_id].distance;\n        min_node_id = node_id;\n      }\n    }\n    node_used[min_node_id] = true;\n    for (auto& arc : arcs[min_node_id]) {\n      int64_t arc_cost = arc.second->cost -\n        nodes[min_node_id].potential + nodes[arc.first].potential;\n      if (arc.second->residual_cap > 0 && nodes[min_node_id].distance +\n          arc_cost < nodes[arc.first].distance) {\n        nodes[arc.first].distance = nodes[min_node_id].distance + arc_cost;\n        (*predecessor)[arc.first] = min_node_id;\n      }\n    }\n  }\n}\n\n// Computes max flow over the graph using the Ford-Fulkerson algorithm.\n// The Complexity of the algorithm is O(E * F). Where F is the max flow value.\n// NOTE: This method changes the graph.\nvoid MaxFlow(AdjacencyMapGraph* graph) {\n  const uint32_t max_node_id = graph->get_max_node_id();\n  vector<unordered_map<uint32_t, Arc*> >& arcs = graph->get_arcs();\n  vector<Node>& nodes = graph->get_nodes();\n  vector<int32_t> visited(max_node_id + 1, 0);\n  vector<uint32_t> predecessor(max_node_id + 1, 0);\n  set<uint32_t>& active_node_ids = graph->get_active_node_ids();\n  uint32_t sink_node = graph->get_sink_node();\n  bool has_path = true;\n  while (has_path) {\n    has_path = false;\n    queue<uint32_t> to_visit;\n    fill(visited.begin(), visited.end(), 0);\n    fill(predecessor.begin(), predecessor.end(), 0);\n    for (const auto& active_node : active_node_ids) {\n      if (nodes[active_node].supply > 0) {\n        to_visit.push(active_node);\n        visited[active_node] = nodes[active_node].supply;\n        break;\n      }\n    }\n    while (!to_visit.empty() && !has_path) {\n      uint32_t cur_node = to_visit.front();\n      to_visit.pop();\n      for (auto& arc : arcs[cur_node]) {\n        if (!visited[arc.first] && arc.second->residual_cap > 0) {\n          visited[arc.first] = min(arc.second->residual_cap, visited[cur_node]);\n          to_visit.push(arc.first);\n          predecessor[arc.first] = cur_node;\n          if (arc.first == sink_node) {\n            has_path = true;\n            int32_t min_aux_flow = visited[arc.first];\n            for (uint32_t cur_node = arc.first; predecessor[cur_node] > 0;\n                 cur_node = predecessor[cur_node]) {\n              Arc* cur_arc = arcs[predecessor[cur_node]][cur_node];\n              cur_arc->residual_cap -= min_aux_flow;\n              cur_arc->reverse_arc->residual_cap += min_aux_flow;\n              nodes[predecessor[cur_node]].supply -= min_aux_flow;\n              nodes[cur_node].supply += min_aux_flow;\n            }\n            break;\n          }\n        }\n      }\n    }\n  }\n  // Check that all the supply has been drained.\n  for (auto& active_node : active_node_ids) {\n    CHECK_EQ(nodes[active_node].supply, 0);\n  }\n  // NOTE: The method does not update the set of active nodes because\n  // the nodes are used in the CycleCancelling algorithm as starting\n  // nodes for the BellmanFord algorithm. However, the active_node_ids\n  // are cleared at the end of the of CycleCancelling.\n}\n\nvoid ReverseMaxFlow(AdjacencyMapGraph* graph) {\n  const uint32_t max_node_id = graph->get_max_node_id();\n  auto& admissible_arcs = graph->get_admissible_arcs();\n  auto& arcs = graph->get_arcs();\n  vector<Node>& nodes = graph->get_nodes();\n  vector<int32_t> visited(max_node_id + 1, 0);\n  vector<uint32_t> predecessor(max_node_id + 1, 0);\n  uint32_t sink_node = graph->get_sink_node();\n  set<uint32_t> demand_node_ids;\n  for (uint32_t node_id = 1; node_id <= max_node_id; ++node_id) {\n    if (nodes[node_id].supply < 0 && node_id != sink_node) {\n      demand_node_ids.insert(node_id);\n    }\n  }\n  bool has_path = true;\n  while (has_path) {\n    has_path = false;\n    queue<uint32_t> to_visit;\n    fill(visited.begin(), visited.end(), 0);\n    fill(predecessor.begin(), predecessor.end(), 0);\n    for (const auto& demand_node : demand_node_ids) {\n      if (nodes[demand_node].supply < 0 && demand_node != sink_node) {\n        to_visit.push(demand_node);\n        visited[demand_node] = -nodes[demand_node].supply;\n        break;\n      }\n    }\n    while (!to_visit.empty() && !has_path) {\n      uint32_t cur_node = to_visit.front();\n      to_visit.pop();\n      for (auto& arc : arcs[cur_node]) {\n        if (!visited[arc.first] && arc.second->reverse_arc->residual_cap > 0) {\n          visited[arc.first] = min(arc.second->reverse_arc->residual_cap,\n                                   visited[cur_node]);\n          to_visit.push(arc.first);\n          predecessor[arc.first] = cur_node;\n          if (arc.first == sink_node) {\n            has_path = true;\n            int32_t min_aux_flow = visited[arc.first];\n            for (uint32_t cur_node = arc.first; predecessor[cur_node] > 0;\n                 cur_node = predecessor[cur_node]) {\n              Arc* cur_arc = arcs[predecessor[cur_node]][cur_node];\n              cur_arc->residual_cap += min_aux_flow;\n              // Add the arc back to the admissible graph.\n              admissible_arcs[cur_arc->src_node_id][cur_arc->dst_node_id] =\n                cur_arc;\n              cur_arc->reverse_arc->residual_cap -= min_aux_flow;\n              nodes[predecessor[cur_node]].supply += min_aux_flow;\n              nodes[cur_node].supply -= min_aux_flow;\n            }\n            break;\n          }\n        }\n      }\n    }\n  }\n}\n\n} // namespace flowlessly\n", "meta": {"hexsha": "16b6dcf161fbf2cc2a3b386ffadfceffe3945be5", "size": 12298, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/misc/utils.cc", "max_stars_repo_name": "mitake/Flowlessly", "max_stars_repo_head_hexsha": "fc130276ae9ceb2550f8885ba89f2edeccfddb94", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2016-06-11T23:54:57.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-10T01:59:47.000Z", "max_issues_repo_path": "src/misc/utils.cc", "max_issues_repo_name": "mitake/Flowlessly", "max_issues_repo_head_hexsha": "fc130276ae9ceb2550f8885ba89f2edeccfddb94", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-06-05T16:40:16.000Z", "max_issues_repo_issues_event_max_datetime": "2018-08-30T07:04:37.000Z", "max_forks_repo_path": "src/misc/utils.cc", "max_forks_repo_name": "mitake/Flowlessly", "max_forks_repo_head_hexsha": "fc130276ae9ceb2550f8885ba89f2edeccfddb94", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2016-07-30T23:51:11.000Z", "max_forks_repo_forks_event_max_datetime": "2020-08-16T04:52:52.000Z", "avg_line_length": 39.2907348243, "max_line_length": 80, "alphanum_fraction": 0.6333550171, "num_tokens": 3110, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6370307806984444, "lm_q2_score": 0.5467381519846138, "lm_q1q2_score": 0.3482890317963833}}
{"text": "// This file is part of LatNet Builder.\n//\n// Copyright (C) 2012-2021  The LatNet Builder author's, supervised by Pierre L'Ecuyer, Universite de Montreal.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//     http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\n#include \"latbuilder/Norm/IAAlpha.h\"\n#include \"latbuilder/WeightsDispatcher.h\"\n#include \"latbuilder/Util.h\"\n\n#include <vector>\n#include <cmath>\n#include <boost/math/tools/polynomial.hpp>\n\nnamespace LatBuilder { namespace Norm {\n      \n typedef boost::math::tools::polynomial<double> RealPolynomial;\n\nnamespace SumHelperIAAlpha{\n\n\n   template <typename WEIGHTS>\n   struct SumHelper {\n      Real operator()(\n            const WEIGHTS& weights,\n            Real lambda,\n            Dimension dimension,\n            unsigned int alpha\n            ) const\n      {\n         throw std::runtime_error(\"IAAlpha normalization not implemented for these weights.\");\n         return 1.;\n      }\n   };\n\n\n#define DECLARE_IAALPHA_SUM(weight_type) \\\n      template <> \\\n      class SumHelper<weight_type> { \\\n      public: \\\n         Real operator()( \\\n               const weight_type& weights, \\\n               Real lambda, \\\n               Dimension dimension, \\\n               unsigned int alpha \\\n               ) const; \\\n      }\\\n\n   DECLARE_IAALPHA_SUM(LatBuilder::CombinedWeights);\n   DECLARE_IAALPHA_SUM(LatBuilder::Interlaced::IPODWeights<LatBuilder::Kernel::IAAlpha>);\n   DECLARE_IAALPHA_SUM(LatBuilder::Interlaced::IPDWeights<LatBuilder::Kernel::IAAlpha>);\n\n#undef DECLARE_IAALPHA_SUM\n\n   //===========================================================================\n   // combined weights\n   //===========================================================================\n\n   // Separating sumCombined() from\n   // SumHelper<LatBuilder::CombinedWeights>::operator() is a workaround for\n   // LLVM/clang++.\n   Real sumCombined(\n         const CombinedWeights& weights,\n         Real lambda,\n         Dimension dimension,\n         unsigned int alpha\n         )\n   {\n      Real val = 0.0;\n      for (const auto& w : weights.list())\n         val += WeightsDispatcher::dispatch<SumHelper>(*w, lambda, dimension, alpha);\n      return val;\n   }\n\n   Real SumHelper<LatBuilder::CombinedWeights>::operator()(\n         const CombinedWeights& weights,\n         Real lambda,\n         Dimension dimension,\n         unsigned int alpha\n         ) const\n   {\n      return sumCombined(weights, lambda, dimension, alpha);\n   }\n\n\n   //===========================================================================\n   // interlaced projection-dependent weights\n   //===========================================================================\n\n   Real SumHelper<LatBuilder::Interlaced::IPDWeights<LatBuilder::Kernel::IAAlpha>>::operator()(\n         const LatBuilder::Interlaced::IPDWeights<LatBuilder::Kernel::IAAlpha>& weights,\n         Real lambda,\n         Dimension dimension,\n         unsigned int alpha\n         ) const\n   { \n      unsigned int interlacingFactor = weights.interlacingFactor();\n      Dimension j0 = (Dimension) std::ceil( (double) dimension / interlacingFactor);\n      Dimension d0 = dimension - (j0 - 1) * interlacingFactor;\n      Real gTilde = 1 / (pow(2.0, alpha*lambda/2)) * std::max(pow(intPow(2.0,std::min(alpha, interlacingFactor))-2,-lambda), 1 / (pow(2.0, lambda * std::min(alpha, interlacingFactor)) - 2));\n      Real g = - 1.0 + intPow(1 + gTilde, interlacingFactor);\n      Real g0 = - 1.0 + intPow(1 + gTilde, d0);\n      Real val = 0.0;\n      for (Dimension largestIndex = 0; largestIndex < j0; largestIndex++) {\n         // iterate only through projections that have a weight\n         for (const auto& pw : weights.getBaseWeights().getWeightsForLargestIndex(largestIndex)) {\n            const auto& proj = pw.first;\n            const auto& weight = pw.second;\n            if (weight)\n            {\n                  if (largestIndex < j0 - 1)\n                  {\n                        val += pow(weight, lambda) * intPow(g, proj.size());\n                  }\n                  else\n                  {\n                        val += pow(weight, lambda) * g0 * intPow(g, proj.size() - 1);\n                  }\n            }\n         }\n      }\n\n      return val;\n   }\n\n   //===========================================================================\n   // IPOD weights\n   //===========================================================================\n   \n   Real SumHelper<LatBuilder::Interlaced::IPODWeights<LatBuilder::Kernel::IAAlpha>>::operator()(\n         const LatBuilder::Interlaced::IPODWeights<LatBuilder::Kernel::IAAlpha>& weights,\n         Real lambda,\n         Dimension dimension,\n         unsigned int alpha\n         ) const\n   {\n      unsigned int interlacingFactor = weights.interlacingFactor();\n      Dimension j0 = (Dimension) std::ceil( (double) dimension / interlacingFactor);\n      Dimension d0 = dimension - (j0 - 1) * interlacingFactor;\n      Real gTilde = 1 / (pow(2.0, alpha*lambda/2)) * std::max(pow(intPow(2.0,std::min(alpha, interlacingFactor))-2,-lambda), 1 / (pow(2.0, lambda * std::min(alpha, interlacingFactor)) - 2));\n      Real g = - 1.0 + intPow(1 + gTilde, interlacingFactor);\n      Real g0 = - 1.0 + intPow(1 + gTilde, d0);\n\n      Real val = g0 * pow(weights.getWeightForCoordinate(j0 - 1) * weights.getWeightForOrder(1), lambda);\n      RealPolynomial acc{1.0};\n      for(Dimension coord = 0; coord < j0 - 1; ++coord)\n      {\n            acc *= RealPolynomial{{pow(weights.getWeightForCoordinate(coord), lambda) * g, 1.0}};\n      }\n      for(Dimension degree = 0; degree < j0 - 1; ++degree)\n      {\n            val += acc[degree] * (pow(weights.getWeightForOrder(j0 - 1 - degree),lambda) + g0 * pow(weights.getWeightForCoordinate(j0 - 1) * weights.getWeightForOrder(j0 - degree), lambda)) ;\n      }\n      return val;\n  }\n\n}\n\nIAAlpha::IAAlpha(unsigned int alpha, const LatticeTester::Weights& weights, Real normType):\n   NormAlphaBase<IAAlpha>(alpha, normType),\n   m_weights(weights)\n{}\n\ntemplate <LatticeType LR, EmbeddingType L>\nReal IAAlpha::value(\n      Real lambda,\n      const SizeParam<LR, L>& sizeParam,\n      Dimension dimension,\n      Real norm\n      ) const\n{\n   norm = 1.0 / (norm * (sizeParam.numPoints() - 1.0));\n   Real val = WeightsDispatcher::dispatch<SumHelperIAAlpha::SumHelper>(\n         m_weights,\n         lambda,\n         dimension,\n         alpha()\n         );\n\n   return pow(val * norm, 1.0 / lambda);\n}\n\ntemplate Real IAAlpha::value<LatticeType::ORDINARY, EmbeddingType::UNILEVEL>(Real, const SizeParam<LatticeType::ORDINARY, EmbeddingType::UNILEVEL>&, Dimension, Real) const;\ntemplate Real IAAlpha::value<LatticeType::ORDINARY, EmbeddingType::MULTILEVEL>(Real, const SizeParam<LatticeType::ORDINARY, EmbeddingType::MULTILEVEL>&, Dimension, Real) const;\n\ntemplate Real IAAlpha::value<LatticeType::POLYNOMIAL, EmbeddingType::UNILEVEL>(Real, const SizeParam<LatticeType::POLYNOMIAL, EmbeddingType::UNILEVEL>&, Dimension, Real) const;\ntemplate Real IAAlpha::value<LatticeType::POLYNOMIAL, EmbeddingType::MULTILEVEL>(Real, const SizeParam<LatticeType::POLYNOMIAL, EmbeddingType::MULTILEVEL>&, Dimension, Real) const;\n\n}}\n", "meta": {"hexsha": "05d902b583dd174e70d25cfa66e5b17ef30fbf82", "size": 7595, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/LatBuilder/Norm/IAAlpha.cc", "max_stars_repo_name": "YochevedDarmon/latnetbuilder", "max_stars_repo_head_hexsha": "7df3a7ba89e10ca51d4af347b75cdb0987e5151c", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2020-01-21T06:08:51.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-24T16:11:31.000Z", "max_issues_repo_path": "src/LatBuilder/Norm/IAAlpha.cc", "max_issues_repo_name": "YochevedDarmon/latnetbuilder", "max_issues_repo_head_hexsha": "7df3a7ba89e10ca51d4af347b75cdb0987e5151c", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2019-10-31T07:49:28.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-03T12:07:49.000Z", "max_forks_repo_path": "src/LatBuilder/Norm/IAAlpha.cc", "max_forks_repo_name": "YochevedDarmon/latnetbuilder", "max_forks_repo_head_hexsha": "7df3a7ba89e10ca51d4af347b75cdb0987e5151c", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2016-07-27T19:25:26.000Z", "max_forks_repo_forks_event_max_datetime": "2018-05-22T20:00:47.000Z", "avg_line_length": 37.975, "max_line_length": 191, "alphanum_fraction": 0.5980250165, "num_tokens": 1840, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7248702761768248, "lm_q2_score": 0.48047867804790706, "lm_q1q2_score": 0.34828471205366207}}
{"text": "/**\n * Creates needed tables\n * @author Tobias Weber <tobias.weber@tum.de>\n * @date nov-2015\n * @license GPLv2\n */\n\n#include <iostream>\n#include <sstream>\n#include <set>\n#include <limits>\n#include <unordered_map>\n\n#include \"tlibs/string/string.h\"\n#include \"tlibs/file/prop.h\"\n#include \"tlibs/log/log.h\"\n#include \"tlibs/math/linalg.h\"\n#include \"libs/spacegroups/sghelper.h\"\n#ifndef NO_CLP\n\t#include \"libs/spacegroups/spacegroup_clp.h\"\n#endif\n\n#ifndef USE_BOOST_REX\n\t#include <regex>\n\tnamespace rex = ::std;\n#else\n\t#include <boost/tr1/regex.hpp>\n\tnamespace rex = ::boost;\n#endif\n\n#include <boost/numeric/ublas/io.hpp>\n#include <boost/version.hpp>\n\nnamespace prop = boost::property_tree;\nnamespace algo = boost::algorithm;\nnamespace ublas = boost::numeric::ublas;\n\nusing t_real = double;\nusing t_cplx = std::complex<t_real>;\nusing t_mat = ublas::matrix<t_real>;\n\n\nunsigned g_iPrec = std::numeric_limits<t_real>::max_digits10-1;\n\n// ============================================================================\n\n#include \"gentab_web.cpp\"\n#ifndef NO_CLP\n\t#include \"gentab_clp.cpp\"\n#endif\n\n// ============================================================================\n\n\nstatic std::unordered_map<std::string, int> g_mapElems;\n\n/**\n * periodic table of elements\n */\nbool gen_elements()\n{\n\tg_mapElems.clear();\n\n\tusing t_propval = tl::Prop<std::string>::t_propval;\n\n\ttl::Prop<std::string> propIn, propOut;\n\tpropIn.SetSeparator('/');\n\tpropOut.SetSeparator('.');\n\n\tif(!propIn.Load(\"tmp/elements.xml\", tl::PropType::XML))\n\t{\n\t\ttl::log_err(\"Cannot load periodic table of elements \\\"tmp/elements.xml\\\".\");\n\t\treturn false;\n\t}\n\n\n\t// iterate over all elements\n\tstd::vector<t_propval> vecElems = propIn.GetFullChildNodes(\"/list\");\n\tstd::size_t iElem = 0;\n\tfor(const t_propval& elem : vecElems)\n\t{\n\t\tif(elem.first != \"atom\") continue;\n\n\t\ttry\n\t\t{\n\t\t\ttl::Prop<std::string> propelem(elem.second, '/');\n\n\t\t\tstd::string strName = propelem.Query<std::string>(\"<xmlattr>/id\", \"\");\n\t\t\tif(strName == \"\" || strName == \"Xx\") continue;\n\n\t\t\tt_real dMass = t_real(-1);\n\t\t\tt_real dRadCov=t_real(-1), dRadVdW=t_real(-1);\n\t\t\tt_real dEIon=t_real(-1), dEAffin(-1);\n\t\t\tt_real dTMelt=t_real(-1), dTBoil=t_real(-1);\n\t\t\tint iNr=-1, iPeriod=-1, iGroup=-1;\n\t\t\tstd::string strConfig, strBlock;\n\n\t\t\t// iterate over all properties\n\t\t\tfor(auto iterVal=propelem.GetProp().begin(); iterVal!=propelem.GetProp().end(); ++iterVal)\n\t\t\t{\n\t\t\t\ttl::Prop<std::string> propVal(iterVal->second, '/');\n\t\t\t\tstd::string strKey = propVal.Query<std::string>(\"<xmlattr>/dictRef\", \"\");\n\t\t\t\tstd::string strVal = propVal.Query<std::string>(\"/\", \"\");\n\t\t\t\t//std::cout << strKey << \" = \" << strVal << std::endl;\n\n\t\t\t\tif(strKey.find(\"atomicNumber\") != std::string::npos)\n\t\t\t\t\tiNr = tl::str_to_var<int>(strVal);\n\t\t\t\telse if(strKey.find(\"electronicConfiguration\") != std::string::npos)\n\t\t\t\t\tstrConfig = strVal;\n\t\t\t\telse if(strKey.find(\"periodTableBlock\") != std::string::npos)\n\t\t\t\t\tstrBlock = strVal;\n\t\t\t\telse if(strKey.find(\"period\") != std::string::npos)\n\t\t\t\t\tiPeriod = tl::str_to_var<int>(strVal);\n\t\t\t\telse if(strKey.find(\"group\") != std::string::npos)\n\t\t\t\t\tiGroup = tl::str_to_var<int>(strVal);\n\t\t\t\telse if(strKey.find(\"exactMass\") != std::string::npos)\n\t\t\t\t\tdMass = tl::str_to_var<t_real>(strVal);\n\t\t\t\telse if(strKey.find(\"radiusCovalent\") != std::string::npos)\n\t\t\t\t\tdRadCov = tl::str_to_var<t_real>(strVal);\n\t\t\t\telse if(strKey.find(\"radiusVDW\") != std::string::npos)\n\t\t\t\t\tdRadVdW = tl::str_to_var<t_real>(strVal);\n\t\t\t\telse if(strKey.find(\"ionization\") != std::string::npos)\n\t\t\t\t\tdEIon = tl::str_to_var<t_real>(strVal);\n\t\t\t\telse if(strKey.find(\"electronAffinity\") != std::string::npos)\n\t\t\t\t\tdEAffin = tl::str_to_var<t_real>(strVal);\n\t\t\t\telse if(strKey.find(\"melting\") != std::string::npos)\n\t\t\t\t\tdTMelt = tl::str_to_var<t_real>(strVal);\n\t\t\t\telse if(strKey.find(\"boiling\") != std::string::npos)\n\t\t\t\t\tdTBoil = tl::str_to_var<t_real>(strVal);\n\t\t\t}\n\n\t\t\tstd::ostringstream ostr;\n\t\t\tostr << \"pte.elem_\" << iElem;\n\t\t\tstd::string strElem = ostr.str();\n\n\t\t\tpropOut.Add(strElem + \".name\", strName);\n\t\t\tpropOut.Add(strElem + \".num\", tl::var_to_str(iNr, g_iPrec));\n\t\t\tpropOut.Add(strElem + \".period\", tl::var_to_str(iPeriod, g_iPrec));\n\t\t\tpropOut.Add(strElem + \".group\", tl::var_to_str(iGroup, g_iPrec));\n\t\t\tpropOut.Add(strElem + \".orbitals\", strConfig);\n\t\t\tpropOut.Add(strElem + \".block\", strBlock);\n\t\t\tpropOut.Add(strElem + \".m\", tl::var_to_str(dMass, g_iPrec));\n\t\t\tpropOut.Add(strElem + \".r_cov\", tl::var_to_str(dRadCov, g_iPrec));\n\t\t\tpropOut.Add(strElem + \".r_vdW\", tl::var_to_str(dRadVdW, g_iPrec));\n\t\t\tpropOut.Add(strElem + \".E_ion\", tl::var_to_str(dEIon, g_iPrec));\n\t\t\tpropOut.Add(strElem + \".E_affin\", tl::var_to_str(dEAffin, g_iPrec));\n\t\t\tpropOut.Add(strElem + \".T_melt\", tl::var_to_str(dTMelt, g_iPrec));\n\t\t\tpropOut.Add(strElem + \".T_boil\", tl::var_to_str(dTBoil, g_iPrec));\n\n\t\t\tg_mapElems[strName] = iNr;\n\t\t}\n\t\tcatch(const std::exception& ex)\n\t\t{\n\t\t\ttl::log_err(\"Element \", iElem, \": \", ex.what());\n\t\t}\n\n\t\t++iElem;\n\t}\n\n\n\tpropOut.Add(\"pte.num_elems\", iElem);\n\n\tpropOut.Add(\"pte.source\", \"Periodic table of the elements obtained from the \"\n\t\t\"<a href=\\\"http://dx.doi.org/10.1021/ci050400b\\\">Blue Obelisk Data Repository</a>.\");\n\tpropOut.Add(\"pte.source_url\", \"https://github.com/egonw/bodr/blob/master/bodr/elements/elements.xml\");\n\n\tif(!propOut.Save(\"res/data/elements.xml.gz\"))\n\t{\n\t\ttl::log_err(\"Cannot write \\\"res/data/elements.xml.gz\\\".\");\n\t\treturn false;\n\t}\n\n\treturn true;\n}\n\n\n\n// ============================================================================\n\n\n/**\n * space groups (alternative)\n */\nbool gen_spacegroups()\n{\n\tusing t_propval = tl::Prop<std::string>::t_propval;\n\n\ttl::Prop<std::string> propIn, propOut;\n\tpropIn.SetSeparator('/');\n\tpropOut.SetSeparator('.');\n\n\tif(!propIn.Load(\"tmp/space-groups.xml\", tl::PropType::XML))\n\t{\n\t\ttl::log_err(\"Cannot load space group table \\\"tmp/space-groups.xml\\\".\");\n\t\treturn false;\n\t}\n\n\n\t// iterate over all groups\n\tstd::vector<t_propval> vecGroups = propIn.GetFullChildNodes(\"/list\");\n\tstd::size_t iGroup = 0;\n\tstd::set<std::string> setNames;\n\tfor(const t_propval& grp : vecGroups)\n\t{\n\t\tif(grp.first != \"group\") continue;\n\n\t\ttry\n\t\t{\n\t\t\ttl::Prop<std::string> propgrp(grp.second, '/');\n\n\t\t\tstd::string strId = propgrp.Query<std::string>(\"<xmlattr>/id\", \"\");\n\t\t\tif(strId == \"\") continue;\n\t\t\tint iNr = tl::str_to_var<int>(strId);\n\n\t\t\tstd::string strName = propgrp.Query<std::string>(\"<xmlattr>/HM\", \"\");\n\t\t\tif(strName == \"\") continue;\n\t\t\ttl::find_all_and_replace<std::string>(strName, \":1\", \"\");\n\t\t\ttl::find_all_and_replace<std::string>(strName, \":2\", \"\");\n\t\t\ttl::find_all_and_replace<std::string>(strName, \":3\", \"\");\n\t\t\txtl::convert_hm_symbol(strName);\n\n\t\t\t// find an unique name\n\t\t\tstd::size_t iNameCtr = 1;\n\t\t\twhile(1)\n\t\t\t{\n\t\t\t\tstd::ostringstream ostrNewName;\n\t\t\t\tostrNewName << strName;\n\t\t\t\tif(iNameCtr >= 2)\n\t\t\t\t\tostrNewName << \" [\" << iNameCtr << \"]\";\n\t\t\t\tif(setNames.find(ostrNewName.str()) == setNames.end())\n\t\t\t\t{\n\t\t\t\t\tstrName = ostrNewName.str();\n\t\t\t\t\tsetNames.insert(strName);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\t\t++iNameCtr;\n\t\t\t}\n\n\t\t\tstd::ostringstream ostr;\n\t\t\tostr << \"sgroups.group_\" << iGroup;\n\t\t\tstd::string strGroup = ostr.str();\n\n\t\t\tstd::vector<t_propval> vecTrafos = propgrp.GetFullChildNodes(\"/\");\n\t\t\tstd::size_t iTrafo = 0;\n\t\t\tfor(const t_propval& trafo : vecTrafos)\n\t\t\t{\n\t\t\t\tif(trafo.first != \"transform\") continue;\n\n\t\t\t\ttl::Prop<std::string> proptrafo(trafo.second, '/');\n\t\t\t\tstd::string strTrafo = proptrafo.Query<std::string>(\"/\", \"\");\n\n\t\t\t\tstd::ostringstream ostrTrafo;\n\t\t\t\tostrTrafo << strGroup << \".trafo_\" << iTrafo;\n\t\t\t\tstd::string strTrafoKey = ostrTrafo.str();\n\n\t\t\t\tt_mat matTrafo = xtl::get_desc_trafo<t_real>(strTrafo);\n\t\t\t\tstd::string strAttribs = \"; \";\n\t\t\t\tif(tl::is_identity_matrix(matTrafo) ||\n\t\t\t\t\ttl::is_inverting_matrix<t_mat>(tl::submatrix(matTrafo,3,3)))\n\t\t\t\t\tstrAttribs += \"i\";\n\t\t\t\tif(tl::is_identity_matrix(matTrafo) ||\n\t\t\t\t\ttl::is_centering_matrix<t_mat>(matTrafo))\n\t\t\t\t\tstrAttribs += \"c\";\n\t\t\t\t/*if(tl::is_identity_matrix(matTrafo) ||\n\t\t\t\t\t(tl::has_translation_components<t_mat>(matTrafo) &&\n\t\t\t\t\t\t!tl::is_centering_matrix<t_mat>(matTrafo) &&\n\t\t\t\t\t\t!tl::is_inverting_matrix<t_mat>(tl::submatrix(matTrafo,3,3))))\n\t\t\t\t\tstrAttribs += \"s\";*/\n\t\t\t\tif(tl::is_identity_matrix(matTrafo) ||\n\t\t\t\t\ttl::has_translation_components<t_mat>(matTrafo))\n\t\t\t\t\tstrAttribs += \"t\";\n\n\t\t\t\tpropOut.Add(strTrafoKey, tl::var_to_str(matTrafo, g_iPrec) + strAttribs);\n\t\t\t\t++iTrafo;\n\t\t\t}\n\n\t\t\tpropOut.Add(strGroup + \".number\", tl::var_to_str(iNr, g_iPrec));\n\t\t\tpropOut.Add(strGroup + \".name\", strName);\n\t\t\tpropOut.Add(strGroup + \".num_trafos\", tl::var_to_str(iTrafo, g_iPrec));\n\t\t}\n\t\tcatch(const std::exception& ex)\n\t\t{\n\t\t\ttl::log_err(\"Space group \", iGroup, \": \", ex.what());\n\t\t}\n\n\t\t++iGroup;\n\t}\n\n\n\tpropOut.Add(\"sgroups.num_groups\", iGroup);\n\n\tpropOut.Add(\"sgroups.source\", \"Space groups obtained from the \"\n\t\t\"<a href=\\\"http://dx.doi.org/10.1021/ci050400b\\\">Blue Obelisk Data Repository</a>.\");\n\tpropOut.Add(\"sgroups.source_url\", \"https://github.com/egonw/bodr/blob/master/bodr/crystal/space-groups.xml\");\n\n\tif(!propOut.Save(\"res/data/sgroups.xml.gz\"))\n\t{\n\t\ttl::log_err(\"Cannot write \\\"res/data/sgroups.xml.gz\\\".\");\n\t\treturn false;\n\t}\n\n\treturn true;\n}\n\n\n\n// ============================================================================\n\n\nstruct ffact\n{\n\tstd::string strName;\n\n\tt_cplx cCohb, cIncb;\n\n\tt_real dScatXs, dAbsXs;\n\tt_real dCohXs, dIncXs;\n\n\tbool bIncCohXs = 0;\n\tbool bIncIncXs = 0;\n\tbool bIncScatXs = 0;\n\n\tstd::string strAbund;\n\tt_real dAbOrHL;\n\tbool bAb;\n};\n\nbool gen_scatlens_npy()\n{\n\ttl::Prop<std::string> propIn, propOut;\n\tpropIn.SetSeparator('/');\n\tpropOut.SetSeparator('.');\n\n\tif(!propIn.Load(\"tmp/scattering_lengths.json\", tl::PropType::JSON))\n\t{\n\t\ttl::log_err(\"Cannot load scattering length table \\\"tmp/scattering_lengths.json\\\".\");\n\t\treturn false;\n\t}\n\n\tstd::vector<std::string> vecNuclei = propIn.GetChildNodes(\"/\");\n\tstd::vector<ffact> vecFfacts;\n\n\tfor(const std::string& strNucl : vecNuclei)\n\t{\n\t\tffact ff;\n\n\t\tff.strName = strNucl;\n\t\tff.cCohb = propIn.Query<t_real>(\"/\" + strNucl + \"/Coh b\");\n\t\tff.cIncb = propIn.Query<t_real>(\"/\" + strNucl + \"/Inc b\");\n\t\tff.dAbsXs = propIn.Query<t_real>(\"/\" + strNucl + \"/Abs xs\") * t_real(100); // in fm^2\n\t\tff.dCohXs = propIn.Query<t_real>(\"/\" + strNucl + \"/Coh xs\") * t_real(100);\n\t\tff.dIncXs = propIn.Query<t_real>(\"/\" + strNucl + \"/Inc xs\") * t_real(100);\n\t\tff.dScatXs = propIn.Query<t_real>(\"/\" + strNucl + \"/Scatt xs\");\n\t\tff.strAbund = propIn.Query<std::string>(\"/\" + strNucl + \"/conc\");\n\n\t\t// include total scattering cross-section only if it is not the sum\n\t\t// of the coherent and incoherent cross-sections\n\t\tif(!tl::float_equal(ff.dScatXs, ff.dCohXs + ff.dIncXs, 1.))\n\t\t{\n\t\t\tff.bIncScatXs = 1;\n\t\t\t//tl::log_warn(\"Mismatch in scattering cross-section for \", ff.strName, \": \",\n\t\t\t//\tff.dCohXs + ff.dIncXs, \" != \", ff.dScatXs, \".\");\n\t\t}\n\n\t\tif(!tl::float_equal(ff.dCohXs, (ff.cCohb*std::conj(ff.cCohb)).real()*t_real(4)*tl::get_pi<t_real>(), 1.))\n\t\t{\n\t\t\tff.bIncCohXs = 1;\n\t\t\t//tl::log_warn(\"Mismatch in coherent cross-section for \", ff.strName, \": \",\n\t\t\t//\t(ff.cCohb*std::conj(ff.cCohb)).real()*t_real(4)*tl::get_pi<t_real>(),\n\t\t\t//\t\" != \", ff.dCohXs, \".\");\n\t\t}\n\n\t\tif(!tl::float_equal(ff.dIncXs, (ff.cIncb*std::conj(ff.cIncb)).real()*t_real(4)*tl::get_pi<t_real>(), 1.))\n\t\t{\n\t\t\tff.bIncIncXs = 1;\n\t\t\t//tl::log_warn(\"Mismatch in incoherent cross-section for \", ff.strName, \": \",\n\t\t\t//\t(ff.cIncb*std::conj(ff.cIncb)).real()*t_real(4)*tl::get_pi<t_real>(),\n\t\t\t//\t\" != \", ff.dIncXs, \".\");\n\t\t}\n\n\n\t\t// complex?\n\t\tauto vecValsCohb = propIn.GetChildValues<t_real>(\"/\" + strNucl + \"/Coh b\");\n\t\tauto vecValsIncb = propIn.GetChildValues<t_real>(\"/\" + strNucl + \"/Inc b\");\n\n\t\tif(vecValsCohb.size() >= 2)\n\t\t{\n\t\t\tff.cCohb.real(vecValsCohb[0]);\n\t\t\tff.cCohb.imag(vecValsCohb[1]);\n\t\t}\n\t\tif(vecValsIncb.size() >= 2)\n\t\t{\n\t\t\tff.cIncb.real(vecValsIncb[0]);\n\t\t\tff.cIncb.imag(vecValsIncb[1]);\n\t\t}\n\n\t\tff.dAbOrHL = t_real(0);\n\t\tff.bAb = get_abundance_or_hl(ff.strAbund, ff.dAbOrHL);\n\n\t\tvecFfacts.emplace_back(std::move(ff));\n\t}\n\n\n\t// sort elements if elements map is not empty\n\tif(g_mapElems.size())\n\t{\n\t\tstd::stable_sort(vecFfacts.begin(), vecFfacts.end(),\n\t\t\t[](const ffact& ff1, const ffact& ff2) -> bool\n\t\t\t{\n\t\t\t\tstd::string strName1 = tl::remove_chars(ff1.strName, std::string(\"+-0123456789\"));\n\t\t\t\tstd::string strName2 = tl::remove_chars(ff2.strName, std::string(\"+-0123456789\"));\n\n\t\t\t\tauto iter1 = g_mapElems.find(strName1);\n\t\t\t\tauto iter2 = g_mapElems.find(strName2);\n\n\t\t\t\tif(iter1 == g_mapElems.end())\n\t\t\t\t{\n\t\t\t\t\ttl::log_err(\"Element \", strName1, \" not in table!\");\n\t\t\t\t\treturn 0;\n\t\t\t\t}\n\t\t\t\tif(iter2 == g_mapElems.end())\n\t\t\t\t{\n\t\t\t\t\ttl::log_err(\"Element \", strName2, \" not in table!\");\n\t\t\t\t\treturn 0;\n\t\t\t\t}\n\n\t\t\t\treturn iter1->second < iter2->second;\n\t\t\t});\n\t}\n\n\n\t// write database\n\tstd::size_t iNucl = 0;\n\tfor(const ffact& ff : vecFfacts)\n\t{\n\t\tstd::ostringstream ostr;\n\t\tostr << \"scatlens.atom_\" << iNucl;\n\t\tstd::string strAtom = ostr.str();\n\n\t\tpropOut.Add(strAtom + \".name\", ff.strName);\n\n\t\t// scattering lengths\n\t\tpropOut.Add(strAtom + \".coh\", tl::var_to_str(ff.cCohb, g_iPrec));\n\t\tpropOut.Add(strAtom + \".incoh\", tl::var_to_str(ff.cIncb, g_iPrec));\n\n\t\t// cross-sections\n\t\tif(ff.bIncCohXs)\n\t\t\tpropOut.Add(strAtom + \".xsec_coh\", tl::var_to_str(ff.dCohXs, g_iPrec));\n\t\tif(ff.bIncIncXs)\n\t\t\tpropOut.Add(strAtom + \".xsec_incoh\", tl::var_to_str(ff.dIncXs, g_iPrec));\n\t\tif(ff.bIncScatXs)\n\t\t\tpropOut.Add(strAtom + \".xsec_scat\", tl::var_to_str(ff.dScatXs, g_iPrec));\n\t\tpropOut.Add(strAtom + \".xsec_absorp\", tl::var_to_str(ff.dAbsXs, g_iPrec));\n\n\t\t// abundances\n\t\tif(ff.bAb)\n\t\t\tpropOut.Add(strAtom + \".abund\", tl::var_to_str(ff.dAbOrHL, g_iPrec));\n\t\telse\n\t\t\tpropOut.Add(strAtom + \".hl\", tl::var_to_str(ff.dAbOrHL, g_iPrec));\n\n\t\t++iNucl;\n\t}\n\n\tpropOut.Add(\"scatlens.num_atoms\", tl::var_to_str(vecNuclei.size()));\n\n\tpropOut.Add(\"scatlens.source\", \"Scattering lengths and cross-sections extracted from NeutronPy (by D. Fobes)\"\n\t\t\" (which itself is based on <a href=\\\"http://dx.doi.org/10.1080/10448639208218770\\\">this paper</a>).\");\n\tpropOut.Add(\"scatlens.source_url\", \"https://github.com/neutronpy/neutronpy/blob/master/neutronpy/database/scattering_lengths.json\");\n\n\tif(!propOut.Save(\"res/data/scatlens.xml.gz\"))\n\t{\n\t\ttl::log_err(\"Cannot write \\\"res/data/scatlens.xml.gz\\\".\");\n\t\treturn false;\n\t}\n\n\treturn true;\n}\n\n\n\n// ============================================================================\n\n\nstruct mag_ffact\n{\n\tstd::string strName;\n\tstd::string strJ0_A, strJ0_a;\n\tstd::string strJ2_A, strJ2_a;\n\tstd::string strJ4_A, strJ4_a;\n};\n\nbool gen_magformfacts_npy()\n{\n\ttl::Prop<std::string> propIn, propOut;\n\tpropIn.SetSeparator('/');\n\tpropOut.SetSeparator('.');\n\n\tif(!propIn.Load(\"tmp/magnetic_form_factors.json\", tl::PropType::JSON))\n\t{\n\t\ttl::log_err(\"Cannot load scattering length table \\\"tmp/magnetic_form_factors.json\\\".\");\n\t\treturn false;\n\t}\n\n\tstd::vector<std::string> vecNuclei = propIn.GetChildNodes(\"/\");\n\tstd::vector<mag_ffact> vecFfacts;\n\n\tfor(const std::string& strNucl : vecNuclei)\n\t{\n\t\tauto vecJ0 = propIn.GetChildValues<t_real>(\"/\" + strNucl + \"/j0\");\n\t\tauto vecJ2 = propIn.GetChildValues<t_real>(\"/\" + strNucl + \"/j2\");\n\t\tauto vecJ4 = propIn.GetChildValues<t_real>(\"/\" + strNucl + \"/j4\");\n\n\t\tmag_ffact ffact;\n\t\tffact.strName = strNucl;\n\t\tstd::string& strJ0A = ffact.strJ0_A;\n\t\tstd::string& strJ2A = ffact.strJ2_A;\n\t\tstd::string& strJ4A = ffact.strJ4_A;\n\t\tstd::string& strJ0a = ffact.strJ0_a;\n\t\tstd::string& strJ2a = ffact.strJ2_a;\n\t\tstd::string& strJ4a = ffact.strJ4_a;\n\n\t\tfor(std::size_t iJ=0; iJ<vecJ0.size(); ++iJ)\n\t\t{\n\t\t\tt_real dVal = vecJ0[iJ];\n\t\t\tbool bEven = tl::is_even(iJ);\n\t\t\tif(bEven)\n\t\t\t{\n\t\t\t\tif(strJ0A != \"\") strJ0A += \"; \";\n\t\t\t\tstrJ0A += tl::var_to_str(dVal, g_iPrec);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tif(strJ0a != \"\") strJ0a += \"; \";\n\t\t\t\tstrJ0a += tl::var_to_str(dVal, g_iPrec);\n\t\t\t}\n\t\t}\n\t\tfor(std::size_t iJ=0; iJ<vecJ2.size(); ++iJ)\n\t\t{\n\t\t\tt_real dVal = vecJ2[iJ];\n\t\t\tbool bEven = tl::is_even(iJ);\n\t\t\tif(bEven)\n\t\t\t{\n\t\t\t\tif(strJ2A != \"\") strJ2A += \"; \";\n\t\t\t\tstrJ2A += tl::var_to_str(dVal, g_iPrec);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tif(strJ2a != \"\") strJ2a += \"; \";\n\t\t\t\tstrJ2a += tl::var_to_str(dVal, g_iPrec);\n\t\t\t}\n\t\t}\n\t\tfor(std::size_t iJ=0; iJ<vecJ4.size(); ++iJ)\n\t\t{\n\t\t\tt_real dVal = vecJ4[iJ];\n\t\t\tbool bEven = tl::is_even(iJ);\n\t\t\tif(bEven)\n\t\t\t{\n\t\t\t\tif(strJ4A != \"\") strJ4A += \"; \";\n\t\t\t\tstrJ4A += tl::var_to_str(dVal, g_iPrec);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tif(strJ4a != \"\") strJ4a += \"; \";\n\t\t\t\tstrJ4a += tl::var_to_str(dVal, g_iPrec);\n\t\t\t}\n\t\t}\n\n\t\tvecFfacts.emplace_back(std::move(ffact));\n\t}\n\n\n\t// sort elements\n\tstd::stable_sort(vecFfacts.begin(), vecFfacts.end(),\n\t\t[](const mag_ffact& ff1, const mag_ffact& ff2) -> bool\n\t\t{\n\t\t\tstd::string strName1 = tl::remove_chars(ff1.strName, std::string(\"+-0123456789\"));\n\t\t\tstd::string strName2 = tl::remove_chars(ff2.strName, std::string(\"+-0123456789\"));\n\n\t\t\tauto iter1 = g_mapElems.find(strName1);\n\t\t\tauto iter2 = g_mapElems.find(strName2);\n\n\t\t\tif(iter1 == g_mapElems.end())\n\t\t\t\ttl::log_err(\"Element \", strName1, \" not in table!\");\n\t\t\tif(iter2 == g_mapElems.end())\n\t\t\t\ttl::log_err(\"Element \", strName2, \" not in table!\");\n\n\t\t\treturn iter1->second < iter2->second;\n\t\t});\n\n\n\t// write database\n\tstd::size_t iNucl = 0;\n\tfor(const mag_ffact& ffact : vecFfacts)\n\t{\n\t\tstd::ostringstream ostr;\n\t\tostr << \"atom_\" << iNucl;\n\t\tstd::string strAtom = ostr.str();\n\n\t\tpropOut.Add(\"magffacts.j0.\" + strAtom + \".name\", ffact.strName);\n\t\tpropOut.Add(\"magffacts.j2.\" + strAtom + \".name\", ffact.strName);\n\t\tpropOut.Add(\"magffacts.j4.\" + strAtom + \".name\", ffact.strName);\n\n\t\tpropOut.Add(\"magffacts.j0.\" + strAtom + \".A\", ffact.strJ0_A);\n\t\tpropOut.Add(\"magffacts.j0.\" + strAtom + \".a\", ffact.strJ0_a);\n\n\t\tpropOut.Add(\"magffacts.j2.\" + strAtom + \".A\", ffact.strJ2_A);\n\t\tpropOut.Add(\"magffacts.j2.\" + strAtom + \".a\", ffact.strJ2_a);\n\n\t\tpropOut.Add(\"magffacts.j4.\" + strAtom + \".A\", ffact.strJ4_A);\n\t\tpropOut.Add(\"magffacts.j4.\" + strAtom + \".a\", ffact.strJ4_a);\n\n\t\t++iNucl;\n\t}\n\n\tpropOut.Add(\"magffacts.num_atoms\", tl::var_to_str(vecNuclei.size()));\n\n\tpropOut.Add(\"magffacts.source\", \"Magnetic form factor coefficients extracted from NeutronPy (by D. Fobes).\");\n\tpropOut.Add(\"magffacts.source_url\", \"https://github.com/neutronpy/neutronpy/blob/master/neutronpy/database/magnetic_form_factors.json\");\n\n\tif(!propOut.Save(\"res/data/magffacts.xml.gz\"))\n\t{\n\t\ttl::log_err(\"Cannot write \\\"res/data/magffacts.xml.gz\\\".\");\n\t\treturn false;\n\t}\n\n\treturn true;\n}\n\n\n// ============================================================================\n\n\nint main()\n{\n#ifdef NO_TERM_CMDS\n\ttl::Log::SetUseTermCmds(0);\n#endif\n\n\tstd::cout << \"Generating periodic table of elements ... \";\n\tbool bHasElems = gen_elements();\n\tif(bHasElems) std::cout << \"OK\" << std::endl;\n\n#ifndef NO_CLP\n\tstd::cout << \"Generating atomic form factor coefficient table ... \";\n\tif(gen_formfacts_clp()) std::cout << \"OK\" << std::endl;\n#endif\n\n\tstd::cout << \"Generating scattering length table ... \";\n\tif(gen_scatlens_npy())\n\t{\n\t\tstd::cout << \"OK\" << std::endl;\n\t}\n\telse\n\t{\n\t\tstd::cout << \"FAILED.\\nGenerating scattering length table (alternative) ... \";\n\t\tif(gen_scatlens()) std::cout << \"OK\" << std::endl;\n\t}\n\n\tstd::cout << \"Generating space group table ... \";\n\tif(gen_spacegroups())\n\t{\n\t\tstd::cout << \"OK\" << std::endl;\n\t}\n\telse\n\t{\n\t\tstd::cout << \"FAILED.\\n\";\n#ifndef NO_CLP\n\t\tstd::cout << \"Generating space group type table (alternative) ... \";\n\t\tif(gen_spacegroups_clp()) std::cout << \"OK\" << std::endl;\n#endif\n\t}\n\n\t//std::cout << \"Generating magnetic form factor coefficient table ... \";\n\t//if(gen_magformfacts()) std::cout << \"OK\" << std::endl;\n\n\tif(bHasElems)\n\t{\n\t\tstd::cout << \"Generating magnetic form factor coefficient table ... \";\n\t\tif(gen_magformfacts_npy()) std::cout << \"OK\" << std::endl;\n\t}\n\telse\n\t{\n\t\ttl::log_err(\"Cannot create magnetic form factor coefficient table, because required periodic table is invalid.\");\n\t}\n\n\treturn 0;\n}\n", "meta": {"hexsha": "88bd2f84c9617d97b3513f84f184841fa7fd9efa", "size": 19736, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tools/gentab/gentab.cpp", "max_stars_repo_name": "t-weber/libcrystal", "max_stars_repo_head_hexsha": "2611288014047fe60010ee1b963a9e686b6ea77a", "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/gentab/gentab.cpp", "max_issues_repo_name": "t-weber/libcrystal", "max_issues_repo_head_hexsha": "2611288014047fe60010ee1b963a9e686b6ea77a", "max_issues_repo_licenses": ["BSL-1.0"], "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/gentab/gentab.cpp", "max_forks_repo_name": "t-weber/libcrystal", "max_forks_repo_head_hexsha": "2611288014047fe60010ee1b963a9e686b6ea77a", "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.6444121916, "max_line_length": 137, "alphanum_fraction": 0.6324483178, "num_tokens": 6363, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6150878555160665, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.3481511269961152}}
{"text": "#ifndef STAN_MATH_REV_MAT_FUN_MATRIX_EXP_MULTIPLY_HPP\n#define STAN_MATH_REV_MAT_FUN_MATRIX_EXP_MULTIPLY_HPP\n\n#include <stan/math/rev/mat.hpp>\n#include <stan/math/rev/core.hpp>\n#include <stan/math/prim/mat/fun/matrix_exp_action_handler.hpp>\n#include <stan/math/prim/mat/fun/Eigen.hpp>\n#include <stan/math/rev/mat/fun/to_var.hpp>\n#include <stan/math/prim/mat/fun/matrix_exp.hpp>\n#include <stan/math/prim/mat/err/check_multiplicable.hpp>\n#include <stan/math/prim/scal/err/check_not_nan.hpp>\n#include <boost/math/tools/promotion.hpp>\n#include <boost/utility/enable_if.hpp>\n#include <boost/type_traits.hpp>\n#include <vector>\n\nnamespace stan {\nnamespace math {\n\n/**\n * Calculate adjoint of matrix exponential action\n * exp(At)*B when A is data and B is var, used for chaining action.\n *\n * @param Ad double array pointer to the data of matrix A\n * @param n dim of square matrix A\n * @param adjexpAB MatrixXd adjoint of exp(At)*B\n * @param t double time data\n * @return MatrixXd The adjoint of B.\n */\ninline Eigen::MatrixXd exp_action_chain_dv(double* Ad, const int& n,\n                                           const Eigen::MatrixXd& adjexpAB,\n                                           const double t) {\n  using Eigen::Map;\n  matrix_exp_action_handler handle;\n  return handle.action(Map<Eigen::MatrixXd>(Ad, n, n).transpose(), adjexpAB, t);\n}\n\n/**\n * Calculate adjoint of matrix exponential action\n * exp(At)*B when A is var and B is data, used for chaining action.\n *\n * @param Ad double array pointer to the data of matrix A\n * @param Bd double array pointer to the data of matrix B\n * @param n dim(nb. of rows) of square matrix A\n * @param m nb. of cols of matrix B\n * @param adjexpAB MatrixXd adjoint of exp(At)*B\n * @param t double time data\n * @return MatrixXd The adjoint of A.\n */\ninline Eigen::MatrixXd exp_action_chain_vd(double* Ad, double* Bd, const int& n,\n                                           const int& m,\n                                           const Eigen::MatrixXd& adjexpAB,\n                                           const double t) {\n  using Eigen::Map;\n  using Eigen::Matrix;\n  using Eigen::MatrixXd;\n  Eigen::MatrixXd adjexpA = Eigen::MatrixXd::Zero(n, n);\n  Eigen::MatrixXd adjA = Eigen::MatrixXd::Zero(n, n);\n\n  // TODO(yizhang): a better way such as complex step approximation\n  try {\n    start_nested();\n\n    adjexpA = adjexpAB * Map<MatrixXd>(Bd, n, m).transpose();\n    Eigen::Matrix<stan::math::var, Eigen::Dynamic, Eigen::Dynamic> Av(n, n);\n    for (int i = 0; i < Av.size(); ++i) {\n      Av(i) = to_var(Ad[i]);\n    }\n    std::vector<stan::math::var> Avec(Av.data(), Av.data() + Av.size());\n    Eigen::Matrix<stan::math::var, Eigen::Dynamic, Eigen::Dynamic> expA\n        = matrix_exp(Av);\n    std::vector<double> g;\n    for (size_type i = 0; i < expA.size(); ++i) {\n      stan::math::set_zero_all_adjoints_nested();\n      expA.coeffRef(i).grad(Avec, g);\n      for (size_type j = 0; j < adjA.size(); ++j) {\n        adjA(j) += adjexpA(i) * g[j];\n      }\n    }\n  } catch (const std::exception& e) {\n    recover_memory_nested();\n    throw;\n  }\n  recover_memory_nested();\n  return adjA;\n}\n\n/**\n * This is a subclass of the vari class for matrix\n * exponential action exp(At) * B where A is a double\n * NxN matrix and B is a NxCb matrix.\n *\n * The class stores the structure of each matrix,\n * the double values of A and B, and pointers to\n * the varis for A and B if A or B is a var. It\n * also instantiates and stores pointers to\n * varis for all elements of A * B.\n *\n * @tparam Ta Scalar type of matrix A\n * @tparam N rows and cols of A\n * @tparam Tb Scalar type for matrix B\n * @tparam Cb cols for matrix B\n */\ntemplate <typename Ta, int N, typename Tb, int Cb>\nclass matrix_exp_action_vari : public vari {\n public:\n  int n_;\n  int B_cols_;\n  int A_size_;\n  int B_size_;\n  double t_;\n  double* Ad_;\n  double* Bd_;\n  vari** variRefA_;\n  vari** variRefB_;\n  vari** variRefexpAB_;\n\n  /**\n   * Constructor: vari child-class of matrix_exp_action_vari.\n   * @param A statically-sized matirx\n   * @param B statically-sized matirx\n   * @param t double scalar time.\n   */\n  matrix_exp_action_vari(const Eigen::Matrix<Ta, N, N>& A,\n                         const Eigen::Matrix<Tb, N, Cb>& B, const double& t)\n      : vari(0.0),\n        n_(A.rows()),\n        B_cols_(B.cols()),\n        A_size_(A.size()),\n        B_size_(B.size()),\n        t_(t),\n        Ad_(ChainableStack::instance().memalloc_.alloc_array<double>(A_size_)),\n        Bd_(ChainableStack::instance().memalloc_.alloc_array<double>(B_size_)),\n        variRefA_(\n            ChainableStack::instance().memalloc_.alloc_array<vari*>(A_size_)),\n        variRefB_(\n            ChainableStack::instance().memalloc_.alloc_array<vari*>(B_size_)),\n        variRefexpAB_(\n            ChainableStack::instance().memalloc_.alloc_array<vari*>(B_size_)) {\n    using Eigen::Map;\n    using Eigen::MatrixXd;\n    for (size_type i = 0; i < A.size(); ++i) {\n      variRefA_[i] = A.coeffRef(i).vi_;\n      Ad_[i] = A.coeffRef(i).val();\n    }\n    for (size_type i = 0; i < B.size(); ++i) {\n      variRefB_[i] = B.coeffRef(i).vi_;\n      Bd_[i] = B.coeffRef(i).val();\n    }\n    matrix_exp_action_handler handle;\n    MatrixXd expAB = handle.action(Map<MatrixXd>(Ad_, n_, n_),\n                                   Map<MatrixXd>(Bd_, n_, B_cols_), t_);\n    for (size_type i = 0; i < expAB.size(); ++i)\n      variRefexpAB_[i] = new vari(expAB.coeffRef(i), false);\n  }\n\n  /**\n   * Chain command for the adjoint of matrix exp action.\n   */\n  virtual void chain() {\n    using Eigen::Map;\n    using Eigen::MatrixXd;\n    MatrixXd adjexpAB(n_, B_cols_);\n\n    for (size_type i = 0; i < adjexpAB.size(); ++i)\n      adjexpAB(i) = variRefexpAB_[i]->adj_;\n\n    MatrixXd adjA = exp_action_chain_vd(Ad_, Bd_, n_, B_cols_, adjexpAB, t_);\n    MatrixXd adjB = exp_action_chain_dv(Ad_, n_, adjexpAB, t_);\n\n    for (size_type i = 0; i < A_size_; ++i) {\n      variRefA_[i]->adj_ += adjA(i);\n    }\n    for (size_type i = 0; i < B_size_; ++i) {\n      variRefB_[i]->adj_ += adjB(i);\n    }\n  }\n};\n\n/**\n * This is a subclass of the vari class for matrix\n * exponential action exp(At) * B where A is an N by N\n * matrix of double, B is N by Cb, and t is data(time)\n *\n * The class stores the structure of each matrix,\n * the double values of A and B, and pointers to\n * the varis for A and B if B is a var. It\n * also instantiates and stores pointers to\n * varis for all elements of exp(At) * B.\n *\n * @tparam N Rows and cols for matrix A, also rows for B\n * @tparam Tb Scalar type for matrix B\n * @tparam Cb Columns for matrix B\n */\ntemplate <int N, typename Tb, int Cb>\nclass matrix_exp_action_vari<double, N, Tb, Cb> : public vari {\n public:\n  int n_;\n  int B_cols_;\n  int A_size_;\n  int B_size_;\n  double t_;\n  double* Ad_;\n  double* Bd_;\n  vari** variRefB_;\n  vari** variRefexpAB_;\n\n  /**\n   * Constructor for matrix_exp_action_vari.\n   *\n   * All memory allocated in\n   * ChainableStack's stack_alloc arena.\n   *\n   * It is critical for the efficiency of this object\n   * that the constructor create new varis that aren't\n   * popped onto the var_stack_, but rather are\n   * popped onto the var_nochain_stack_. This is\n   * controlled to the second argument to\n   * vari's constructor.\n   *\n   * @param A matrix\n   * @param B matrix\n   * @param t double\n   */\n  matrix_exp_action_vari(const Eigen::Matrix<double, N, N>& A,\n                         const Eigen::Matrix<Tb, N, Cb>& B, const double& t)\n      : vari(0.0),\n        n_(A.rows()),\n        B_cols_(B.cols()),\n        A_size_(A.size()),\n        B_size_(B.size()),\n        t_(t),\n        Ad_(ChainableStack::instance().memalloc_.alloc_array<double>(A_size_)),\n        Bd_(ChainableStack::instance().memalloc_.alloc_array<double>(B_size_)),\n        variRefB_(\n            ChainableStack::instance().memalloc_.alloc_array<vari*>(B_size_)),\n        variRefexpAB_(\n            ChainableStack::instance().memalloc_.alloc_array<vari*>(B_size_)) {\n    using Eigen::Map;\n    using Eigen::MatrixXd;\n    for (size_type i = 0; i < A.size(); ++i)\n      Ad_[i] = A.coeffRef(i);\n    for (size_type i = 0; i < B.size(); ++i) {\n      variRefB_[i] = B.coeffRef(i).vi_;\n      Bd_[i] = B.coeffRef(i).val();\n    }\n    matrix_exp_action_handler handle;\n    MatrixXd expAB = handle.action(Map<MatrixXd>(Ad_, n_, n_),\n                                   Map<MatrixXd>(Bd_, n_, B_cols_), t_);\n    for (size_type i = 0; i < expAB.size(); ++i)\n      variRefexpAB_[i] = new vari(expAB.coeffRef(i), false);\n  }\n\n  /**\n   * Chain for matrix_exp_action_vari.\n   */\n  virtual void chain() {\n    using Eigen::Map;\n    using Eigen::MatrixXd;\n    MatrixXd adjexpAB(n_, B_cols_);\n    // MatrixXd adjB(n_, B_cols_);\n\n    for (size_type i = 0; i < adjexpAB.size(); ++i)\n      adjexpAB(i) = variRefexpAB_[i]->adj_;\n\n    MatrixXd adjB = exp_action_chain_dv(Ad_, n_, adjexpAB, t_);\n\n    for (size_type i = 0; i < B_size_; ++i) {\n      variRefB_[i]->adj_ += adjB(i);\n    }\n  }\n};\n\n/**\n * This is a subclass of the vari class for matrix\n * exponential action exp(At) * B where A is an N by N\n * matrix of var, B is N by Cb matrix of double, and t is data(time)\n *\n * The class stores the structure of each matrix,\n * the double values of A and B, and pointers to\n * the varis for A and B if B is a var. It\n * also instantiates and stores pointers to\n * varis for all elements of exp(At) * B.\n *\n * @tparam Ta Scalar type for matrix A\n * @tparam N Rows and cols for matrix A, also rows for B\n * @tparam Cb Columns for matrix B\n */\ntemplate <typename Ta, int N, int Cb>\nclass matrix_exp_action_vari<Ta, N, double, Cb> : public vari {\n public:\n  int n_;\n  int B_cols_;\n  int A_size_;\n  int B_size_;\n  double t_;\n  double* Ad_;\n  double* Bd_;\n  vari** variRefA_;\n  vari** variRefexpAB_;\n\n  /**\n   * Constructor for matrix_exp_action_vari.\n   *\n   * All memory allocated in\n   * ChainableStack's stack_alloc arena.\n   *\n   * It is critical for the efficiency of this object\n   * that the constructor create new varis that aren't\n   * popped onto the var_stack_, but rather are\n   * popped onto the var_nochain_stack_. This is\n   * controlled to the second argument to\n   * vari's constructor.\n   *\n   * @param A matrix\n   * @param B matrix\n   * @param t double\n   */\n  matrix_exp_action_vari(const Eigen::Matrix<Ta, N, N>& A,\n                         const Eigen::Matrix<double, N, Cb>& B, const double& t)\n      : vari(0.0),\n        n_(A.rows()),\n        B_cols_(B.cols()),\n        A_size_(A.size()),\n        B_size_(B.size()),\n        t_(t),\n        Ad_(ChainableStack::instance().memalloc_.alloc_array<double>(A_size_)),\n        Bd_(ChainableStack::instance().memalloc_.alloc_array<double>(B_size_)),\n        variRefA_(\n            ChainableStack::instance().memalloc_.alloc_array<vari*>(A_size_)),\n        variRefexpAB_(\n            ChainableStack::instance().memalloc_.alloc_array<vari*>(B_size_)) {\n    using Eigen::Map;\n    using Eigen::MatrixXd;\n    for (size_type i = 0; i < A.size(); ++i) {\n      variRefA_[i] = A.coeffRef(i).vi_;\n      Ad_[i] = A.coeffRef(i).val();\n    }\n    for (size_type i = 0; i < B.size(); ++i) {\n      Bd_[i] = B.coeffRef(i);\n    }\n    matrix_exp_action_handler handle;\n    MatrixXd expAB = handle.action(Map<MatrixXd>(Ad_, n_, n_),\n                                   Map<MatrixXd>(Bd_, n_, B_cols_), t_);\n    for (size_type i = 0; i < expAB.size(); ++i)\n      variRefexpAB_[i] = new vari(expAB.coeffRef(i), false);\n  }\n\n  virtual void chain() {\n    using Eigen::Map;\n    using Eigen::MatrixXd;\n    MatrixXd adjexpAB(n_, B_cols_);\n\n    for (size_type i = 0; i < adjexpAB.size(); ++i)\n      adjexpAB(i) = variRefexpAB_[i]->adj_;\n\n    MatrixXd adjA = exp_action_chain_vd(Ad_, Bd_, n_, B_cols_, adjexpAB, t_);\n\n    for (size_type i = 0; i < A_size_; ++i) {\n      variRefA_[i]->adj_ += adjA(i);\n    }\n  }\n};\n\n/**\n * Return product of exp(At) and B, where A is a NxN matrix,\n * B is a NxCb matrix, and t is a double\n * @tparam Ta scalar type matrix A\n * @tparam N Rows and cols matrix A, also rows of matrix B\n * @tparam Tb scalar type matrix B\n * @tparam Cb Columns matrix B\n * @param[in] A Matrix\n * @param[in] B Matrix\n * @param[in] t double\n * @return exponential of At multiplies B\n */\ntemplate <typename Ta, int N, typename Tb, int Cb>\ninline typename boost::enable_if_c<boost::is_same<Ta, var>::value\n                                       || boost::is_same<Tb, var>::value,\n                                   Eigen::Matrix<var, N, Cb> >::type\nmatrix_exp_action(const Eigen::Matrix<Ta, N, N>& A,\n                  const Eigen::Matrix<Tb, N, Cb>& B, const double& t = 1.0) {\n  matrix_exp_action_vari<Ta, N, Tb, Cb>* baseVari\n      = new matrix_exp_action_vari<Ta, N, Tb, Cb>(A, B, t);\n  Eigen::Matrix<var, N, Cb> expAB_v(A.rows(), B.cols());\n  for (size_type i = 0; i < expAB_v.size(); ++i) {\n    expAB_v.coeffRef(i).vi_ = baseVari->variRefexpAB_[i];\n  }\n  return expAB_v;\n}\n\n/**\n * Wrapper of matrix_exp_action function for a more literal name\n * @tparam Ta scalar type matrix A\n * @tparam Tb scalar type matrix B\n * @tparam Cb Columns matrix B\n * @param[in] A Matrix\n * @param[in] B Matrix\n * @return exponential of A multiplies B\n */\ntemplate <typename Ta, typename Tb, int Cb>\ninline Eigen::Matrix<typename stan::return_type<Ta, Tb>::type, -1, Cb>\nmatrix_exp_multiply(const Eigen::Matrix<Ta, -1, -1>& A,\n                    const Eigen::Matrix<Tb, -1, Cb>& B) {\n  check_nonzero_size(\"matrix_exp_multiply\", \"input matrix\", A);\n  check_nonzero_size(\"matrix_exp_multiply\", \"input matrix\", B);\n  check_multiplicable(\"matrix_exp_multiply\", \"A\", A, \"B\", B);\n  check_square(\"matrix_exp_multiply\", \"input matrix\", A);\n  return matrix_exp_action(A, B);\n}\n\n}  // namespace math\n}  // namespace stan\n\n#endif\n", "meta": {"hexsha": "afde7b2c8600b9c5b04a3efd1a05d5074ca79a29", "size": 13682, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "stan/math/rev/mat/fun/matrix_exp_multiply.hpp", "max_stars_repo_name": "cqfd/math", "max_stars_repo_head_hexsha": "68b8f7e2effb1a23abe8524ff429a212653b53a3", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "stan/math/rev/mat/fun/matrix_exp_multiply.hpp", "max_issues_repo_name": "cqfd/math", "max_issues_repo_head_hexsha": "68b8f7e2effb1a23abe8524ff429a212653b53a3", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "stan/math/rev/mat/fun/matrix_exp_multiply.hpp", "max_forks_repo_name": "cqfd/math", "max_forks_repo_head_hexsha": "68b8f7e2effb1a23abe8524ff429a212653b53a3", "max_forks_repo_licenses": ["BSD-3-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.8894230769, "max_line_length": 80, "alphanum_fraction": 0.6257126151, "num_tokens": 3924, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7185943925708562, "lm_q2_score": 0.48438008427698437, "lm_q1q2_score": 0.3480728124344397}}
{"text": "/**\n * @file\n * @copyright This code is licensed under the 3-clause BSD license.\\n\n *            Copyright ETH Zurich, Laboratory of Physical Chemistry, Reiher Group.\\n\n *            See LICENSE.txt for details.\n */\n\n#include \"DihedralTerm.h\"\n#include \"../MMExceptions.h\"\n#include <Utils/Math/AtomicSecondDerivativeCollection.h>\n#include <Utils/Math/Tensor33.h>\n#include <Eigen/Dense>\n\nnamespace Scine {\nnamespace MolecularMechanics {\n\nDihedralTerm::DihedralTerm(AtomIndex firstAtom, AtomIndex secondAtom, AtomIndex thirdAtom, AtomIndex fourthAtom,\n                           const Dihedral& dihedral, const DihedralType& typeOfDihedral)\n  : firstAtom_(firstAtom),\n    secondAtom_(secondAtom),\n    thirdAtom_(thirdAtom),\n    fourthAtom_(fourthAtom),\n    dihedral_(dihedral),\n    typeOfDihedral_(typeOfDihedral) {\n}\n\nDihedralTerm::~DihedralTerm() = default;\n\ndouble DihedralTerm::evaluateDihedralTerm(const Utils::PositionCollection& positions,\n                                          Utils::AtomicSecondDerivativeCollection& derivatives) const {\n  if (this->disabled_)\n    return 0.0;\n  if (!dihedral_.hasParameters()) // Check this only if this term is not disabled\n    throw MMDihedralParametersNotAvailableException(typeOfDihedral_.a1, typeOfDihedral_.a2, typeOfDihedral_.a3,\n                                                    typeOfDihedral_.a4);\n\n  // Calculating the dihedral energy and its derivatives according to\n  // A. Blondel, M. Karplus, New Formulation for Derivatives of Torsion Angles and Improper Torsion Angles in Molecular\n  // Mechanics: Elimination of Singularities, JCC, 17, 1996, 1132-1141.\n  Eigen::Vector3d F(positions.row(firstAtom_) - positions.row(secondAtom_));\n  Eigen::Vector3d G(positions.row(secondAtom_) - positions.row(thirdAtom_));\n  Eigen::Vector3d H(positions.row(fourthAtom_) - positions.row(thirdAtom_));\n\n  auto A = F.cross(G);\n  auto B = H.cross(G);\n\n  double A2 = A.squaredNorm();\n  double B2 = B.squaredNorm();\n  //  double A4 = A2 * A2;\n  //  double B4 = B2 * B2;\n  double G1 = G.norm();\n  //  double G2 = G1 * G1;\n  //  double G3 = G1 * G2;\n\n  // Values needed for first derivatives\n  auto gba2a = G1 / A2 * A;\n  auto fgba2ga = F.dot(G) / (A2 * G1) * A;\n  auto hgbb2gb = H.dot(G) / (B2 * G1) * B;\n  auto gbb2b = G1 / B2 * B;\n\n  // First derivatives:\n  Eigen::Vector3d firstDer1 = -gba2a;\n  Eigen::Vector3d firstDer2 = gba2a + fgba2ga - hgbb2gb;\n  Eigen::Vector3d firstDer3 = hgbb2gb - fgba2ga - gbb2b;\n  Eigen::Vector3d firstDer4 = gbb2b;\n\n  //  // Values needed for second derivatives // TODO\n  //  auto gca = G.cross(A);\n  //  auto gcb = G.cross(B);\n  //  auto fca = F.cross(A);\n  //  auto hcb = H.cross(B);\n  //  auto d2df2 = (Utils::tensor(A, gca) + Utils::tensor(gca, A)) * (G.norm() / A4);\n  //  auto d2dh2 = (Utils::tensor(B, gcb) + Utils::tensor(gcb, B)) * (-G.norm() / B4);\n  //  auto d2dg2 = (Utils::tensor(gca, A) + Utils::tensor(A, gca)) * (1.0 / (2 * G3 * A2)) +\n  //               (Utils::tensor(A, fca) + Utils::tensor(fca, A)) * (F.dot(G) / (G.norm() * A4)) +\n  //               (Utils::tensor(gcb, B) + Utils::tensor(B, gcb)) * (-1.0 / (2 * G3 * B2)) +\n  //               (Utils::tensor(B, hcb) + Utils::tensor(hcb, B)) * (-H.dot(G) / (G.norm() * B4));\n  //  auto d2dfdg = (Utils::tensor(-fca, A) * G.squaredNorm() + Utils::tensor(A, -gca) * F.dot(G)) * (1.0 / (G.norm() *\n  //  A4)); auto d2dhdg = (Utils::tensor(-hcb, B) * G.squaredNorm() + Utils::tensor(B, -gcb) * H.dot(G)) * (-1.0 /\n  //  (G.norm() * B4));\n\n  // Derivative objects for theta\n  Utils::AutomaticDifferentiation::Second3D h1, h2, h3, h4;\n\n  //  // Add contributions to second derivatives // TODO\n  //  setSecondDerivative(h1, d2df2, 1.0, 1.0);\n  //  setSecondDerivative(h2, d2df2, -1.0, -1.0);\n  //  setSecondDerivative(h2, d2dg2, 1.0, 1.0);\n  //  setSecondDerivative(h2, d2dfdg, -1.0, 1.0);\n  //  setSecondDerivative(h3, d2dh2, -1.0, -1.0);\n  //  setSecondDerivative(h3, d2dg2, -1.0, -1.0);\n  //  setSecondDerivative(h3, d2dhdg, -1.0, -1.0);\n  //  setSecondDerivative(h4, d2dh2, 1.0, 1.0);\n\n  // Add first derivatives contributions\n  h1.setFirst3D(firstDer1);\n  h2.setFirst3D(firstDer2);\n  h3.setFirst3D(firstDer3);\n  h4.setFirst3D(firstDer4);\n\n  double theta = getTheta(A, B, G);\n  auto result = dihedral_.getInteraction(theta);\n\n  // Apply chain rule to get derivatives with respect to the energy\n  derivatives[firstAtom_] += threeDimDer(result, h1);\n  derivatives[secondAtom_] += threeDimDer(result, h2);\n  derivatives[thirdAtom_] += threeDimDer(result, h3);\n  derivatives[fourthAtom_] += threeDimDer(result, h4);\n\n  return result.value();\n}\n\nUtils::AutomaticDifferentiation::Second3D DihedralTerm::threeDimDer(const Utils::AutomaticDifferentiation::Second1D& energy,\n                                                                    const Utils::AutomaticDifferentiation::Second3D& alpha) const {\n  return {energy.value(),\n          energy.first() * alpha.dx(),\n          energy.first() * alpha.dy(),\n          energy.first() * alpha.dz(),\n          energy.second() * alpha.dx() * alpha.dx() + energy.first() * alpha.XX(),\n          energy.second() * alpha.dy() * alpha.dy() + energy.first() * alpha.YY(),\n          energy.second() * alpha.dz() * alpha.dz() + energy.first() * alpha.ZZ(),\n          energy.second() * alpha.dx() * alpha.dy() + energy.first() * alpha.XY(),\n          energy.second() * alpha.dx() * alpha.dz() + energy.first() * alpha.XZ(),\n          energy.second() * alpha.dy() * alpha.dz() + energy.first() * alpha.YZ()};\n}\n\nvoid DihedralTerm::setSecondDerivative(Utils::AutomaticDifferentiation::Second3D& h, const Utils::Tensor33& tensor,\n                                       double derFirst, double derSecond) const {\n  double f = derFirst * derSecond;\n  h.setXX(h.XX() + f * tensor.x().x());\n  h.setYY(h.YY() + f * tensor.y().y());\n  h.setZZ(h.ZZ() + f * tensor.z().z());\n  h.setXY(h.XY() + f * tensor.x().y() + f * tensor.y().x()); // TODO: DO I need 1/2 ?\n  h.setXZ(h.XZ() + f * tensor.x().z() + f * tensor.z().x());\n  h.setYZ(h.YZ() + f * tensor.y().z() + f * tensor.z().y());\n}\n\ndouble DihedralTerm::getTheta(const Eigen::Vector3d& A, const Eigen::Vector3d& B, const Eigen::Vector3d& G) {\n  double acosArg = A.dot(B) / (A.norm() * B.norm());\n  //  acosArg *= -1;\n  double theta = acos(acosArg);\n  // Needed because of numerical instabilities provoking theta = nan\n  if (acosArg >= 1)\n    theta = 0;\n  else if (acosArg <= -1)\n    theta = 4.0 * atan(1);\n\n  // Invert sign of theta if it should be negative (NB: acos delivers only values between 0 and pi)\n  double asinArg = B.cross(A).dot(G) / (A.norm() * B.norm() * G.norm());\n  if (asinArg < 0) {\n    theta *= -1;\n  }\n\n  return theta;\n}\n\nDihedralType DihedralTerm::getTypeOfDihedral() const {\n  return typeOfDihedral_;\n}\n\nint DihedralTerm::getFirstAtom() const {\n  return firstAtom_;\n}\n\nint DihedralTerm::getSecondAtom() const {\n  return secondAtom_;\n}\n\nint DihedralTerm::getThirdAtom() const {\n  return thirdAtom_;\n}\n\nint DihedralTerm::getFourthAtom() const {\n  return fourthAtom_;\n}\n\n} // namespace MolecularMechanics\n} // namespace Scine", "meta": {"hexsha": "a3b4a799bc97fd06b7f900ae191f17596218bb33", "size": 7059, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Swoose/Swoose/MolecularMechanics/Interactions/DihedralTerm.cpp", "max_stars_repo_name": "qcscine/swoose", "max_stars_repo_head_hexsha": "55a74259153845ade607784f26455fd96dddce07", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-12-15T09:31:36.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-15T09:35:36.000Z", "max_issues_repo_path": "src/Swoose/Swoose/MolecularMechanics/Interactions/DihedralTerm.cpp", "max_issues_repo_name": "qcscine/swoose", "max_issues_repo_head_hexsha": "55a74259153845ade607784f26455fd96dddce07", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Swoose/Swoose/MolecularMechanics/Interactions/DihedralTerm.cpp", "max_forks_repo_name": "qcscine/swoose", "max_forks_repo_head_hexsha": "55a74259153845ade607784f26455fd96dddce07", "max_forks_repo_licenses": ["BSD-3-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.6573033708, "max_line_length": 131, "alphanum_fraction": 0.6261510129, "num_tokens": 2224, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7185943925708561, "lm_q2_score": 0.48438008427698437, "lm_q1q2_score": 0.34807281243443966}}
{"text": "#include <cstdio>\n\n#if defined(USE_OPENGL)\n    #include <GL/glut.h>\n#endif\n\n#include <iostream>\n\n#include <Eigen/Dense>\n\n#include <argparser.h>\n#include <easyppm.h>\n\n#include <Color.h>\n#include <Material.h>\n#include <Light.h>\n#include <Sphere.h>\n#include <Util.h>\n\nenum class SHADEMODE {\n    NONE,\n    FLAT,\n    GOURAUD,\n    PHONG,\n};\n\nconstexpr int NX = 512;\nconstexpr int NY = 512;\n\nColor* buffer;\nfloat zbuf[NX][NY];\n\nPPM ppm;\n\nchar shade_str[20];\nSHADEMODE shade_mode;\nvoid assign_shade_mode() {\n    if (strcmp(shade_str, \"NONE\") == 0)\n        shade_mode = SHADEMODE::NONE;\n    else if (strcmp(shade_str, \"FLAT\") == 0)\n        shade_mode = SHADEMODE::FLAT;\n    else if (strcmp(shade_str, \"GOURAUD\") == 0)\n        shade_mode = SHADEMODE::GOURAUD;\n    else\n        shade_mode = SHADEMODE::PHONG;\n}\n\nvoid cleanup() {\n    delete[] buffer;\n}\n\n#if defined(USE_OPENGL)\nvoid gl_display() {\n    glClearColor(0,0,0,1);\n    glClear(GL_COLOR_BUFFER_BIT);\n\n    float* float_buffer = new float[3*NX*NY];\n\n    int k = 0;\n    for (int i = 0; i < NX; i++) {\n        for (int j = 0; j < NY; j++) {\n            float_buffer[k++] = buffer[j*NY + i].r;\n            float_buffer[k++] = buffer[j*NY + i].g;\n            float_buffer[k++] = buffer[j*NY + i].b;\n        }\n    }\n\n    glDrawPixels(NX, NY, GL_RGB, GL_FLOAT, float_buffer);\n\n    glutSwapBuffers();\n\n    delete[] float_buffer;\n}\n\nvoid gl_keyboard(unsigned char key, int x, int y) {\n    switch (key) {\n        // ESC\n        case 27:\n            cleanup();\n            exit(EXIT_SUCCESS);\n    }\n}\n#endif\n\nint clamp(int x, int min, int max) {\n    return std::max(min, std::min(x, max));\n}\n\nvoid draw(int x, int y, const Color& color) {\n#if defined(USE_OPENGL)\n    buffer[x*NY + y] = color.correct(2.2f);\n#else\n    auto c = color.correct(2.2f);\n\n    auto r = clamp(c.r * 255, 0, 255);\n    auto g = clamp(c.g * 255, 0, 255);\n    auto b = clamp(c.b * 255, 0, 255);\n    easyppm_set(&ppm, x, y, easyppm_rgb(r,g,b));\n#endif\n}\n\ntemplate <typename T>\nT lerp(T a, T b, T c, float alpha, float beta) {\n    return (a-c)*alpha + (b-c)*beta + c;\n}\n\nvoid rasterize(const Triangle& tri, const Light& light, const Material& mat, const Eigen::Matrix4f& M) {\n    // Backface culling\n    auto v = tri.centroid().normalized();\n    if (v.dot(tri.n) > 0)\n        return;\n\n    // Convert triangle coordinates from world to viewport\n    auto a_vp = vec4to3(M * Eigen::Vector4f(tri.a[0], tri.a[1], tri.a[2], 1.0f));\n    auto b_vp = vec4to3(M * Eigen::Vector4f(tri.b[0], tri.b[1], tri.b[2], 1.0f));\n    auto c_vp = vec4to3(M * Eigen::Vector4f(tri.c[0], tri.c[1], tri.c[2], 1.0f));\n\n    // Viewport triangle bounds\n    auto bounds = Triangle(a_vp, b_vp, c_vp).bounds();\n\n    // Viewport triangle vertex values\n    float ax = a_vp[0], ay = a_vp[1], az = a_vp[2];\n    float bx = b_vp[0], by = b_vp[1], bz = b_vp[2];\n    float cx = c_vp[0], cy = c_vp[1], cz = c_vp[2];\n\n    Eigen::Matrix2f A;\n    A << (ax-cx), (bx-cx),\n         (ay-cy), (by-cy);\n\n    // Step through viewport bounding box and check whether pixel is in triangle\n    for (int y = bounds.ymin; y <= bounds.ymax; y++) {\n        for (int x = bounds.xmin; x <= bounds.xmax; x++) {\n            // Solve Ax=b for barycentric coordinates\n            Eigen::Vector2f bary = A.lu().solve(Eigen::Vector2f(x-cx, y-cy));\n\n            float alpha = bary[0];\n            float beta  = bary[1];\n\n            float z = lerp(az, bz, cz, alpha, beta);\n\n            if (alpha >= 0 && beta >= 0 && alpha + beta <= 1 && z > zbuf[x][y]) {\n                zbuf[x][y] = z;\n                if (shade_mode == SHADEMODE::NONE) {\n                    // White\n                    draw(x, y, Color::white());\n                } else if (shade_mode == SHADEMODE::FLAT) {\n                    // Centroid color\n                    draw(x, y, tri.shade(tri.centroid(), tri.n, light, mat));\n                } else if (shade_mode == SHADEMODE::GOURAUD) {\n                    // Vertex colors\n                    auto ac = tri.shade(tri.a, tri.an, light, mat);\n                    auto bc = tri.shade(tri.b, tri.bn, light, mat);\n                    auto cc = tri.shade(tri.c, tri.cn, light, mat);\n\n                    draw(x, y, lerp(ac, bc, cc, alpha, beta));\n                } else {\n                    // Interpolate position and normal\n                    auto p = lerp(tri.a,  tri.b,  tri.c,  alpha, beta);\n                    auto n = lerp(tri.an, tri.bn, tri.cn, alpha, beta);\n\n                    draw(x, y, tri.shade(p, n, light, mat));\n                }\n            }\n        }\n    }\n}\n\nint main(int argc, char* argv[]) {\n    // Parse system arguments\n    argparser ap = argparser_create(argc, argv, PARSEMODE_LENIENT);\n    argparser_add(&ap, \"-s\", \"--shading\", ARGTYPE_STRING, &shade_str, \"Shade mode\");\n    argparser_parse(&ap);\n\n    assign_shade_mode();\n\n#ifndef USE_OPENGL\n    ppm = easyppm_create(NX, NY, IMAGETYPE_PPM);\n#endif\n\n    constexpr float l = -0.1f;\n    constexpr float r =  0.1f;\n    constexpr float b = -0.1f;\n    constexpr float t =  0.1f;\n    constexpr float n = -0.1f;\n    constexpr float f = -1000.0f;\n\n    Eigen::Matrix4f M, M_world, M_m, M_cam, P, M_orth, M_vp;\n\n    // Modeling transform\n    M_m <<     2.0f,            0.0f,           0.0f,           0.0f,\n               0.0f,            2.0f,           0.0f,           0.0f,\n               0.0f,            0.0f,           2.0f,          -7.0f,\n               0.0f,            0.0f,           0.0f,           1.0f;\n\n    // Camera transform\n    M_cam <<   1.0f,            0.0f,           0.0f,           0.0f,\n               0.0f,            1.0f,           0.0f,           0.0f,\n               0.0f,            0.0f,           1.0f,           0.0f,\n               0.0f,            0.0f,           0.0f,           1.0f;\n\n    // Perspective transform\n    P <<       n,               0.0f,           0.0f,           0.0f,\n               0.0f,            n,              0.0f,           0.0f,\n               0.0f,            0.0f,           n+f,            -f*n,\n               0.0f,            0.0f,           1.0f,           0.0f;\n\n    // Orthographic transform\n    M_orth <<  2.0f/(r-l),      0.0f,           0.0f,           -(r+l)/(r-l),\n               0.0f,            2.0f/(t-b),     0.0f,           -(t+b)/(t-b),\n               0.0f,            0.0f,           2.0f/(n-f),     -(n+f)/(n-f),\n               0.0f,            0.0f,           0.0f,           1.0f;\n\n    // Viewport transform\n    M_vp <<    NX/2.0f,         0.0f,           0.0f,           (NX-1)/2.0f,\n               0.0f,            NY/2.0f,        0.0f,           (NY-1)/2.0f,\n               0.0f,            0.0f,           1.0f,           0.0f,\n               0.0f,            0.0f,           0.0f,           1.0f;\n\n    // World transform\n    M_world = M_cam * M_m;\n\n    // \"Viewport\" transform\n    M = M_vp * M_orth * P;\n\n    // Sphere\n    Color ka(0.0f, 1.0f, 0.0f);\n    Color kd(0.0f, 0.5f, 0.0f);\n    Color ks(0.5f, 0.5f, 0.5f);\n    Material mat(ka, kd, ks, 32);\n    Sphere sphere(mat, M_world);\n\n    // Light\n    Light light(Eigen::Vector3f(-4, 4, -3), 1);\n\n    // Black buffer\n    buffer = new Color[NX*NY];\n    for (int x = 0; x < NX; x++)\n        for (int y = 0; y < NY; y++)\n            draw(x, y, Color::black());\n\n    // Z buffer starts at max depth\n    for (int x = 0; x < NX; x++)\n        for (int y = 0; y < NY; y++)\n            zbuf[x][y] = f;\n\n    // Rasterize sphere\n    for (const auto& tri : sphere.triangles)\n        rasterize(tri, light, mat, M);\n\n#if defined(USE_OPENGL)\n    // Write buffer to OpenGL window\n    char window_name[50];\n    if      (shade_mode == SHADEMODE::NONE)    strcpy(window_name, \"Part 1 (Unshaded)\");\n    else if (shade_mode == SHADEMODE::FLAT)    strcpy(window_name, \"Part 2 (Flat Shading)\");\n    else if (shade_mode == SHADEMODE::GOURAUD) strcpy(window_name, \"Part 3 (Gouraud Shading)\");\n    else                                       strcpy(window_name, \"Part 4 (Phong Shading)\");\n    glutInit(&argc, argv);\n    glutInitDisplayMode(GLUT_RGB | GLUT_DEPTH | GLUT_DOUBLE);\n    glutInitWindowSize(NX, NY);\n    glutCreateWindow(window_name);\n    glutDisplayFunc(gl_display);\n    glutKeyboardFunc(gl_keyboard);\n    glutMainLoop();\n#else\n    // Write buffer to image file\n    char ppmpath[50];\n    if      (shade_mode == SHADEMODE::NONE)    strcpy(ppmpath, \"images/part1-unshaded.ppm\");\n    else if (shade_mode == SHADEMODE::FLAT)    strcpy(ppmpath, \"images/part2-flat.ppm\");\n    else if (shade_mode == SHADEMODE::GOURAUD) strcpy(ppmpath, \"images/part3-gouraud.ppm\");\n    else                                       strcpy(ppmpath, \"images/part4-phong.ppm\");\n\n    easyppm_invert_y(&ppm);\n    easyppm_write(&ppm, ppmpath);\n    easyppm_destroy(&ppm);\n#endif\n\n    cleanup();\n\n    return EXIT_SUCCESS;\n}\n", "meta": {"hexsha": "a33258b8d15d25801f4002af54873b1097c99518", "size": 8734, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "main.cpp", "max_stars_repo_name": "zanzo420/rasterizer", "max_stars_repo_head_hexsha": "afc974e6289c84982e0f42070aa0b8d96bcb6cf9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-06-12T20:31:46.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-12T20:31:46.000Z", "max_issues_repo_path": "main.cpp", "max_issues_repo_name": "zanzo420/rasterizer", "max_issues_repo_head_hexsha": "afc974e6289c84982e0f42070aa0b8d96bcb6cf9", "max_issues_repo_licenses": ["MIT"], "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": "zanzo420/rasterizer", "max_forks_repo_head_hexsha": "afc974e6289c84982e0f42070aa0b8d96bcb6cf9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-09-22T06:03:16.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-04T13:10:48.000Z", "avg_line_length": 31.0818505338, "max_line_length": 104, "alphanum_fraction": 0.4993130295, "num_tokens": 2817, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7185943925708561, "lm_q2_score": 0.48438008427698437, "lm_q1q2_score": 0.34807281243443966}}
{"text": "#include <Eigen/Dense>\n#include <vector>\n#include <fstream>\n#include <iostream>\n#include <cmath>\n\n#include \"../include/KF.h\"\n#include \"../include/dsho.h\"\n#include \"../include/matern32.h\"\n#include \"../include/ndsho.h\"\n\n\nusing namespace Eigen;\nusing namespace std;\n\n#define TWOPI 6.283185307179586\n\n// function to read a space separated file\n\nstd::vector<double> load_csv (const std::string & path) {\n    std::ifstream indata;\n    indata.open(path);\n    std::string line;\n    std::vector<double> values;\n    uint rows = 0;\n    while (std::getline(indata, line)) {\n        std::stringstream lineStream(line);\n        std::string cell;\n        while (std::getline(lineStream, cell, ' ')) {\n            //cout << std::stod(cell) << endl;\n            values.push_back(std::stod(cell));\n        }\n        ++rows;\n    }\n    return values;\n}\n\nint main() {\n\n\t// read file with two component damped simple harmonic oscillator simulated data\n\t//std::vector<double> values = load_csv(\"two_comp_dsho.txt\");\n\t//cout << values.size() << endl;\n\n\t// map data to VectorXds\n\t//VectorXd times = Map<VectorXd, 0, InnerStride<2> > (values.data(), 10000);\n\t//VectorXd yi = Map<VectorXd, 0, InnerStride<2> > (values.data()+1, 10000);\n\n\n  int vecsize = 10000;\n\t// map data to VectorXds\n\tVectorXd yi(vecsize);\n  VectorXd times = Eigen::VectorXd::Random(vecsize);\n  times.array() += 1.0;\n  times.array() *= (100*0.5);\n  std::sort(times.data(), times.data() + times.size());\n\n\n\t// this is the observational error vector\n\tVectorXd yerr = VectorXd::Ones(yi.size());\n\tyerr.array() *= 0.05;\n\n\tVectorXd y_sim, y_sim_one;\n\n\tfor(int j=0; j < 24; j++) {\n\t\t//auto const seed = std::random_device()();\n\t\tint seed = 123;\n\t\tstd::mt19937 rng(seed);\n\t\tcout << seed << endl;\n\t\t// set parameters for a 2 component DSHO model\n\t\tEigen::Vector2d omegas,Qpars,varfs;\n\t\tEigen::Matrix<double,1,1> omega_one, Qpar_one, varf_one;\n\t\tdouble omega0 = 8; // this component stays fixed\n\t\tdouble period_list[6] = {1.0, 2.0, 4.0, 8.0, 16.0, 32.0};\n\t\tstd::cout << j/6 << j%6 << std::endl;\n\t\tdouble omega1 = TWOPI / period_list[j%6];\n\t\tdouble Q0 = 10.0;\n\t\tdouble Q1 = 10.0;\n\t\tdouble varf0 = 1.0;\n\t\tdouble varf1 = 1.0;\n\t\tif ((j/6 == 1) || (j/6 ==3))\n\t\t{\n\t\t\tvarf0 = 0.01;\n\t\t\tvarf1 = 0.01;\n\t\t}\n\t\tif (j/6 > 1)\n\t\t{\n\t\t\tQ1 = 1.0;\n\t\t}\n\t\tomegas << omega0, omega1;\n\t\tQpars << Q0, Q1;\n\t\tvarfs << varf0, varf1;\n\n\t\tomega_one << omega1;\n\t\tQpar_one << Q1;\n\t\tvarf_one << varf1;\n\n\t\t// Simulate a 2 component DSHO model\n\t\tgpstate::n_dsho::N_DSHOSolver ndsho(times,yi,yerr,omegas, Qpars, varfs);\n\t\tndsho.simulate_N_DSHO(y_sim, rng);\n\n\t\t// For efficiency, just output one of the components as well (the varying one)\n\t\tgpstate::n_dsho::N_DSHOSolver ndsho_one(times,yi,yerr,omega_one, Qpar_one, varf_one);\n\t\tndsho_one.simulate_N_DSHO(y_sim_one, rng);\n\n\t\t// write simulated vector to file GPtest.txt\n\t\tstd::ofstream file(\"GPtest\" + std::to_string(j+1) + \"_ndsho.txt\");\n\t\tassert(file.is_open());\n\t\tfile << \"# N_DSHO simulated light curve\" << endl;\n\t\tfile << \"# input parameters: \" << endl;\n\t\tfile << \"# omega: \" << omega0 << \", \" << omega1 << endl;\n\t\tfile << \"# Q: \" << Q0 << \", \" << Q1 << endl;\n\t\tfile << \"# varf: \" << varf0 << \", \" << varf1 << endl;\n\t\tfile << \"# time y_sim\" << endl;\n\t\tfor(int i=0; i<times.rows(); i++)\n\t\t\tfile <<  times(i) <<\" \"<< y_sim(i) << endl;\n\n\t\tstd::ofstream file_one(\"GPtest\" + std::to_string(j+1) + \"_dsho.txt\");\n\t\tfile_one << \"# DSHO simulated light curve\" << endl;\n\t\tfile_one << \"# input parameters: \" << endl;\n\t\tfile_one << \"# omega: \" << omega_one << endl;\n\t\tfile_one << \"# Q: \" << Qpar_one << endl;\n\t\tfile_one << \"# varf: \" << varf_one << endl;\n\t\tfile_one << \"# time y_sim\" << endl;\n\t\tfor(int i=0; i<times.rows(); i++)\n\t\t\tfile_one <<  times(i) <<\" \"<< y_sim_one(i) << endl;\n\n\n\t}\n}\n", "meta": {"hexsha": "8b870580a0b14d8aac0bd4597930d3ccd99417b9", "size": 3729, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/simulate_ndsho.cpp", "max_stars_repo_name": "andres-jordan/gpstate", "max_stars_repo_head_hexsha": "4daabcd0b851318c581995836ebd81e6ecde6f54", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-11-13T23:27:32.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-13T23:27:32.000Z", "max_issues_repo_path": "src/simulate_ndsho.cpp", "max_issues_repo_name": "andres-jordan/gpstate", "max_issues_repo_head_hexsha": "4daabcd0b851318c581995836ebd81e6ecde6f54", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/simulate_ndsho.cpp", "max_forks_repo_name": "andres-jordan/gpstate", "max_forks_repo_head_hexsha": "4daabcd0b851318c581995836ebd81e6ecde6f54", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.6846153846, "max_line_length": 87, "alphanum_fraction": 0.6122284795, "num_tokens": 1240, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6959583250334526, "lm_q2_score": 0.5, "lm_q1q2_score": 0.3479791625167263}}
{"text": "/* -*- c++ -*- */\n/*\n * Copyright 2013 Free Software Foundation, Inc.\n *\n * This file is part of GNU Radio\n *\n * GNU Radio is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 3, or (at your option)\n * any later version.\n *\n * GNU Radio is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with GNU Radio; see the file COPYING.  If not, write to\n * the Free Software Foundation, Inc., 51 Franklin Street,\n * Boston, MA 02110-1301, USA.\n */\n\n#include \"selective_fading_model_impl.h\"\n#include <gnuradio/io_signature.h>\n#include <iostream>\n\n#include <boost/format.hpp>\n#include <boost/random.hpp>\n\n#include <gnuradio/fxpt.h>\n#include <sincostable.h>\n\n\n// FASTSINCOS:  0 = slow native,  1 = gr::fxpt impl,  2 = sincostable.h\n#define FASTSINCOS  2\n\n\nnamespace gr {\n  namespace channels {\n\n    selective_fading_model::sptr\n    selective_fading_model::make( unsigned int N, float fDTs, bool LOS, float K, int seed, std::vector<float> delays, std::vector<float> mags, int ntaps)\n    {\n      return gnuradio::get_initial_sptr\n\t(new selective_fading_model_impl( N, fDTs, LOS, K, seed, delays, mags, ntaps));\n    }\n\n    // Block constructor\n    selective_fading_model_impl::selective_fading_model_impl( unsigned int N, float fDTs, bool LOS, float K, int seed, std::vector<float> delays, std::vector<float> mags, int ntaps )\n      : sync_block(\"selective_fading_model\",\n\t\t       io_signature::make(1, 1, sizeof(gr_complex)),\n\t\t       io_signature::make(1, 1, sizeof(gr_complex))),\n        d_delays(delays),\n        d_mags(mags),\n        d_sintable(1024)\n    {\n        if(mags.size() != delays.size())\n            throw std::runtime_error(\"magnitude and delay vectors must be the same length!\");\n\n        for(size_t i=0; i<mags.size(); i++){\n            d_faders.push_back(new gr::channels::flat_fader_impl(N, fDTs, (i==0)&&(LOS), K, seed+i));\n        }\n\n        // set up tap history\n        if(ntaps < 1){ throw std::runtime_error(\"ntaps must be >= 1\"); }\n        set_history(1+ntaps);\n        d_taps.resize(ntaps, gr_complex(0,0));\n    }\n\n    selective_fading_model_impl::~selective_fading_model_impl()\n    {\n        for(size_t i=0; i<d_faders.size(); i++){\n            delete d_faders[i];\n        }\n    }\n\n    int\n    selective_fading_model_impl::work (int noutput_items,\n        gr_vector_const_void_star &input_items,\n        gr_vector_void_star &output_items)\n    {\n        const gr_complex* in = (const gr_complex*) input_items[0];\n        gr_complex* out = (gr_complex*) output_items[0];\n\n        // loop over each output sample\n        for(int i=0; i<noutput_items; i++){\n\n            // clear the current values in each tap\n            for(size_t j=0; j<d_taps.size(); j++){\n                d_taps[j] = gr_complex(0,0);\n            }\n\n            // add each flat fading component to the taps\n            for(size_t j=0; j<d_faders.size(); j++){\n                gr_complex ff_H(d_faders[j]->next_sample());\n                for(size_t k=0; k<d_taps.size(); k++){\n                    float dist = k-d_delays[j];\n                    float interpmag = d_sintable.sinc(M_PI*dist);\n                    d_taps[k] += ff_H * interpmag * d_mags[j];\n                }\n            }\n\n            // apply the taps and generate output\n            gr_complex sum(0,0);\n            for(size_t j=0; j<d_taps.size(); j++){\n                sum += in[i+j] * d_taps[d_taps.size()-j-1];\n            }\n\n            // assign output\n            out[i] = sum;\n        }\n\n        // return all outputs\n        return noutput_items;\n    }\n\n    void\n    selective_fading_model_impl::setup_rpc()\n    {\n#ifdef GR_CTRLPORT\n    add_rpc_variable(\n        rpcbasic_sptr(new rpcbasic_register_get<selective_fading_model, float >(\n            alias(), \"fDTs\",\n            &selective_fading_model::fDTs,\n            pmt::mp(0), pmt::mp(1), pmt::mp(0.01),\n            \"Hz*Sec\", \"normalized maximum doppler frequency (fD*Ts)\",\n            RPC_PRIVLVL_MIN, DISPTIME | DISPOPTSTRIP)));\n    add_rpc_variable(\n        rpcbasic_sptr(new rpcbasic_register_set<selective_fading_model, float >(\n            alias(), \"fDTs\",\n            &selective_fading_model::set_fDTs,\n            pmt::mp(0), pmt::mp(1), pmt::mp(0.01),\n            \"Hz*Sec\", \"normalized maximum doppler frequency (fD*Ts)\",\n            RPC_PRIVLVL_MIN, DISPTIME | DISPOPTSTRIP)));\n\n    add_rpc_variable(\n        rpcbasic_sptr(new rpcbasic_register_get<selective_fading_model, float >(\n            alias(), \"K\",\n            &selective_fading_model::K,\n            pmt::mp(0), pmt::mp(8), pmt::mp(4),\n            \"Ratio\", \"Rician factor (ratio of the specular power to the scattered power)\",\n            RPC_PRIVLVL_MIN, DISPTIME | DISPOPTSTRIP)));\n    add_rpc_variable(\n        rpcbasic_sptr(new rpcbasic_register_set<selective_fading_model, float >(\n            alias(), \"K\",\n            &selective_fading_model::set_K,\n            pmt::mp(0), pmt::mp(8), pmt::mp(4),\n            \"Ratio\", \"Rician factor (ratio of the specular power to the scattered power)\",\n            RPC_PRIVLVL_MIN, DISPTIME | DISPOPTSTRIP)));\n\n    add_rpc_variable(\n        rpcbasic_sptr(new rpcbasic_register_get<selective_fading_model, float >(\n            alias(), \"step\",\n            &selective_fading_model::step,\n            pmt::mp(0), pmt::mp(8), pmt::mp(4),\n            \"radians\", \"Maximum step size for random walk angle per sample\",\n            RPC_PRIVLVL_MIN, DISPTIME | DISPOPTSTRIP)));\n    add_rpc_variable(\n        rpcbasic_sptr(new rpcbasic_register_set<selective_fading_model, float >(\n            alias(), \"step\",\n            &selective_fading_model::set_step,\n            pmt::mp(0), pmt::mp(1), pmt::mp(0.00001),\n            \"radians\", \"Maximum step size for random walk angle per sample\",\n            RPC_PRIVLVL_MIN, DISPTIME | DISPOPTSTRIP)));\n#endif /* GR_CTRLPORT */\n    }\n\n  } /* namespace channels */\n} /* namespace gr */\n", "meta": {"hexsha": "3594ec4aa0c8d50792d951e0e0a72aecb2ac516f", "size": 6224, "ext": "cc", "lang": "C++", "max_stars_repo_path": "gnuradio-3.7.13.4/gr-channels/lib/selective_fading_model_impl.cc", "max_stars_repo_name": "v1259397/cosmic-gnuradio", "max_stars_repo_head_hexsha": "64c149520ac6a7d44179c3f4a38f38add45dd5dc", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-03-09T07:32:37.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-09T07:32:37.000Z", "max_issues_repo_path": "gnuradio-3.7.13.4/gr-channels/lib/selective_fading_model_impl.cc", "max_issues_repo_name": "v1259397/cosmic-gnuradio", "max_issues_repo_head_hexsha": "64c149520ac6a7d44179c3f4a38f38add45dd5dc", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "gnuradio-3.7.13.4/gr-channels/lib/selective_fading_model_impl.cc", "max_forks_repo_name": "v1259397/cosmic-gnuradio", "max_forks_repo_head_hexsha": "64c149520ac6a7d44179c3f4a38f38add45dd5dc", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.6117647059, "max_line_length": 182, "alphanum_fraction": 0.6110218509, "num_tokens": 1648, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6959583250334526, "lm_q2_score": 0.5, "lm_q1q2_score": 0.3479791625167263}}
{"text": "#include \"CALPHADFreeEnergyFunctionsBinary.h\"\n#include \"CALPHADConcSolverBinary.h\"\n#include \"CALPHADEqConcSolverBinary.h\"\n#include \"CALPHADFunctions.h\"\n#include \"PhysicalConstants.h\"\n#include \"functions.h\"\n#include \"well_functions.h\"\n\n#include <boost/property_tree/json_parser.hpp>\n\n#include <iomanip>\n#include <string>\n\nnamespace pt = boost::property_tree;\n\nnamespace Thermo4PFM\n{\n\nCALPHADFreeEnergyFunctionsBinary::CALPHADFreeEnergyFunctionsBinary(\n    pt::ptree& calphad_db, boost::optional<pt::ptree&> newton_db,\n    const EnergyInterpolationType energy_interp_func_type,\n    const ConcInterpolationType conc_interp_func_type)\n    : energy_interp_func_type_(energy_interp_func_type),\n      conc_interp_func_type_(conc_interp_func_type),\n      newton_tol_(1.e-8),\n      newton_alpha_(1.),\n      newton_maxits_(20),\n      newton_verbose_(false)\n{\n    std::string fenergy_diag_filename(\"energy.vtk\");\n    fenergy_diag_filename_ = new char[fenergy_diag_filename.length() + 1];\n    strcpy(fenergy_diag_filename_, fenergy_diag_filename.c_str());\n\n    readParameters(calphad_db);\n\n    if (newton_db) readNewtonparameters(newton_db.get());\n}\n\n//=======================================================================\n\nvoid CALPHADFreeEnergyFunctionsBinary::readNewtonparameters(\n    pt::ptree& newton_db)\n{\n    newton_tol_     = newton_db.get<double>(\"tol\", newton_tol_);\n    newton_alpha_   = newton_db.get<double>(\"alpha\", newton_alpha_);\n    newton_maxits_  = newton_db.get<int>(\"max_its\", newton_maxits_);\n    newton_verbose_ = newton_db.get<bool>(\"verbose\", newton_verbose_);\n}\n\n//=======================================================================\n\nvoid CALPHADFreeEnergyFunctionsBinary::readParameters(pt::ptree& calphad_db)\n{\n    pt::ptree& species0_db = calphad_db.get_child(\"SpeciesA\");\n    std::string dbnameL(\"PhaseL\");\n    g_species_phaseL_[0].initialize(\"L0\", species0_db.get_child(dbnameL));\n    std::string dbnameA(\"PhaseA\");\n    g_species_phaseA_[0].initialize(\"A0\", species0_db.get_child(dbnameA));\n\n    pt::ptree& speciesB_db = calphad_db.get_child(\"SpeciesB\");\n    g_species_phaseL_[1].initialize(\"L1\", speciesB_db.get_child(dbnameL));\n    g_species_phaseA_[1].initialize(\"A1\", speciesB_db.get_child(dbnameA));\n\n    // read Lmix coefficients\n    std::string dbnamemixL(\"LmixPhaseL\");\n    pt::ptree Lmix0_db = calphad_db.get_child(dbnamemixL);\n    readLmixBinary(Lmix0_db, LmixPhaseL_);\n\n    std::string dbnamemixA(\"LmixPhaseA\");\n    pt::ptree Lmix1_db = calphad_db.get_child(dbnamemixA);\n    readLmixBinary(Lmix1_db, LmixPhaseA_);\n\n    // print database just read\n    // std::clog << \"CALPHAD database...\" << std::endl;\n    // pt::write_json(std::clog, calphad_db);\n}\n\n//-----------------------------------------------------------------------\n#ifdef HAVE_OPENMP_OFFLOAD\n#pragma omp declare target\n#endif\n\ndouble CALPHADFreeEnergyFunctionsBinary::computeFreeEnergy(\n    const double temperature, const double* const conc, const PhaseIndex pi,\n    const bool gp)\n{\n    const CalphadDataType l0 = lmixPhase(0, pi, temperature);\n    const CalphadDataType l1 = lmixPhase(1, pi, temperature);\n    const CalphadDataType l2 = lmixPhase(2, pi, temperature);\n    const CalphadDataType l3 = lmixPhase(3, pi, temperature);\n\n    CALPHADSpeciesPhaseGibbsEnergy* g_species;\n\n    switch (pi)\n    {\n        case PhaseIndex::phaseL:\n            g_species = &g_species_phaseL_[0];\n            break;\n        case PhaseIndex::phaseA:\n            g_species = &g_species_phaseA_[0];\n            break;\n        default:\n            //            std::cerr << \"CALPHADFreeEnergyFunctionsBinary::\"\n            //                         \"computeFreeEnergy(), undefined phase\"\n            //                      << \"!!!\" << std::endl;\n            // abort();\n            return 0.;\n    }\n\n    double fe = conc[0] * g_species[0].fenergy(temperature)\n                + (1. - conc[0]) * g_species[1].fenergy(temperature)\n                + CALPHADcomputeFMixBinary(l0, l1, l2, l3, conc[0])\n                + CALPHADcomputeFIdealMixBinary(\n                      gas_constant_R_JpKpmol * temperature, conc[0]);\n\n    // subtract -mu*c to get grand potential\n    if (gp)\n    {\n        double deriv;\n        computeDerivFreeEnergy(temperature, conc, pi, &deriv);\n        fe -= deriv * conc[0];\n    }\n\n    return fe;\n}\n\n//=======================================================================\n\nvoid CALPHADFreeEnergyFunctionsBinary::computeDerivFreeEnergy(\n    const double temperature, const double* const conc, const PhaseIndex pi,\n    double* deriv)\n{\n    const CalphadDataType l0 = lmixPhase(0, pi, temperature);\n    const CalphadDataType l1 = lmixPhase(1, pi, temperature);\n    const CalphadDataType l2 = lmixPhase(2, pi, temperature);\n    const CalphadDataType l3 = lmixPhase(3, pi, temperature);\n\n    CALPHADSpeciesPhaseGibbsEnergy* g_species;\n\n    switch (pi)\n    {\n        case PhaseIndex::phaseL:\n            g_species = &g_species_phaseL_[0];\n            break;\n        case PhaseIndex::phaseA:\n            g_species = &g_species_phaseA_[0];\n            break;\n        default:\n            //            std::cerr << \"CALPHADFreeEnergyFunctionsBinary::\"\n            //                         \"computeFreeEnergy(), undefined phase!!!\"\n            //                      << std::endl;\n            // abort();\n            return;\n    }\n\n    double mu = (g_species[0].fenergy(temperature)\n                    - g_species[1].fenergy(temperature))\n                + CALPHADcomputeFMix_derivBinary(l0, l1, l2, l3, conc[0])\n                + CALPHADcomputeFIdealMix_derivBinary(\n                      gas_constant_R_JpKpmol * temperature, conc[0]);\n\n    deriv[0] = mu;\n}\n\n//=======================================================================\n\nvoid CALPHADFreeEnergyFunctionsBinary::computeSecondDerivativeFreeEnergy(\n    const double temp, const double* const conc, const PhaseIndex pi,\n    double* d2fdc2)\n{\n    // assert(conc[0] >= 0.);\n    // assert(conc[0] <= 1.);\n\n    const CalphadDataType l0 = lmixPhase(0, pi, temp);\n    const CalphadDataType l1 = lmixPhase(1, pi, temp);\n    const CalphadDataType l2 = lmixPhase(2, pi, temp);\n    const CalphadDataType l3 = lmixPhase(3, pi, temp);\n    const double rt          = gas_constant_R_JpKpmol * temp;\n\n    d2fdc2[0] = (CALPHADcomputeFMix_deriv2Binary(l0, l1, l2, l3, conc[0])\n                 + CALPHADcomputeFIdealMix_deriv2Binary(rt, conc[0]));\n}\n\n//=======================================================================\n\nvoid CALPHADFreeEnergyFunctionsBinary::computeTdependentParameters(\n    const double temperature, CalphadDataType* Lmix_L, CalphadDataType* Lmix_A,\n    CalphadDataType* fA, CalphadDataType* fB)\n{\n    fA[0]     = g_species_phaseL_[0].fenergy(temperature);\n    fB[0]     = g_species_phaseL_[1].fenergy(temperature);\n    Lmix_L[0] = lmixPhase(0, PhaseIndex::phaseL, temperature);\n    Lmix_L[1] = lmixPhase(1, PhaseIndex::phaseL, temperature);\n    Lmix_L[2] = lmixPhase(2, PhaseIndex::phaseL, temperature);\n    Lmix_L[3] = lmixPhase(3, PhaseIndex::phaseL, temperature);\n\n    fA[1]     = g_species_phaseA_[0].fenergy(temperature);\n    fB[1]     = g_species_phaseA_[1].fenergy(temperature);\n    Lmix_A[0] = lmixPhase(0, PhaseIndex::phaseA, temperature);\n    Lmix_A[1] = lmixPhase(1, PhaseIndex::phaseA, temperature);\n    Lmix_A[2] = lmixPhase(2, PhaseIndex::phaseA, temperature);\n    Lmix_A[3] = lmixPhase(3, PhaseIndex::phaseA, temperature);\n}\n\n//=======================================================================\n\n// compute equilibrium concentrations in various phases for given temperature\nbool CALPHADFreeEnergyFunctionsBinary::computeCeqT(\n    const double temperature, double* ceq, const int maxits, const bool verbose)\n{\n#ifndef HAVE_OPENMP_OFFLOAD\n    if (verbose)\n        std::cout << \"CALPHADFreeEnergyFunctionsBinary::computeCeqT()\"\n                  << std::endl;\n#endif\n    // assert(temperature > 0.);\n\n    // evaluate temperature dependent parameters\n    CalphadDataType fA[3];\n    CalphadDataType fB[3];\n\n    CalphadDataType Lmix_L[4];\n    CalphadDataType Lmix_A[4];\n\n    computeTdependentParameters(temperature, Lmix_L, Lmix_A, fA, fB);\n\n    double RTinv = 1.0 / (gas_constant_R_JpKpmol * temperature);\n\n    CALPHADEqConcSolverBinary eq_solver;\n\n    eq_solver.setup(RTinv, Lmix_L, Lmix_A, fA, fB);\n    int ret = eq_solver.ComputeConcentration(ceq, newton_tol_, maxits);\n\n#ifndef HAVE_OPENMP_OFFLOAD\n    if (ret >= 0)\n    {\n        if (verbose)\n        {\n            std::cout << \"CALPHAD, c_eq phase0=\" << ceq[0] << std::endl;\n            std::cout << \"CALPHAD, c_eq phase1=\" << ceq[1] << std::endl;\n        }\n    }\n    else\n    {\n        std::cout << \"CALPHADFreeEnergyFunctionsBinary, WARNING: ceq \"\n                     \"computation did not converge\"\n                  << std::endl;\n    }\n#endif\n\n    return (ret >= 0);\n}\n\n//=======================================================================\n\nvoid CALPHADFreeEnergyFunctionsBinary::computePhasesFreeEnergies(\n    const double temperature, const double* const hphi, const double conc,\n    double& fl, double& fa)\n{\n    // std::cout<<\"CALPHADFreeEnergyFunctionsBinary::computePhasesFreeEnergies()\"<<endl;\n\n    double c[2] = { conc, conc };\n\n    // evaluate temperature dependent parameters\n    CalphadDataType fA[2];\n    CalphadDataType fB[2];\n\n    CalphadDataType Lmix_L[4];\n    CalphadDataType Lmix_A[4];\n    computeTdependentParameters(temperature, Lmix_L, Lmix_A, fA, fB);\n\n    double RTinv = 1.0 / (gas_constant_R_JpKpmol * temperature);\n\n    CALPHADConcSolverBinary solver;\n    solver.setup(conc, hphi[0], RTinv, Lmix_L, Lmix_A, fA, fB);\n    int ret = solver.ComputeConcentration(\n        c, newton_tol_, newton_maxits_, newton_alpha_);\n    if (ret < 0)\n    {\n#if 0\n        std::cerr << \"ERROR in \"\n                     \"CALPHADFreeEnergyFunctionsBinary::\"\n                     \"computePhasesFreeEnergies()\"\n                     \" ---\"\n                  << \"conc=\" << conc << \", hphi=\" << hphi << std::endl;\n        abort();\n#endif\n    }\n\n    // assert(c[0] >= 0.);\n    fl = computeFreeEnergy(temperature, &c[0], PhaseIndex::phaseL, false);\n\n    // assert(c[1] >= 0.);\n    fa = computeFreeEnergy(temperature, &c[1], PhaseIndex::phaseA, false);\n}\n\n//-----------------------------------------------------------------------\n\nint CALPHADFreeEnergyFunctionsBinary::computePhaseConcentrations(\n    const double temperature, const double* const conc, const double* const phi,\n    double* x)\n{\n    // assert(x[0] >= 0.);\n    // assert(x[1] >= 0.);\n    // assert(x[0] <= 1.);\n    // assert(x[1] <= 1.);\n\n    const double RTinv = 1.0 / (gas_constant_R_JpKpmol * temperature);\n\n    CalphadDataType fA[2];\n    CalphadDataType fB[2];\n    CalphadDataType Lmix_L[4];\n    CalphadDataType Lmix_A[4];\n\n    computeTdependentParameters(temperature, Lmix_L, Lmix_A, fA, fB);\n\n    const double hphi = interp_func(conc_interp_func_type_, phi[0]);\n\n    // conc could be outside of [0.,1.] in a trial step\n    double c0 = conc[0] >= 0. ? conc[0] : 0.;\n    c0        = c0 <= 1. ? c0 : 1.;\n    // solve system of equations to find (cl,cs) given c0 and hphi\n    // x: initial guess and solution\n    CALPHADConcSolverBinary solver;\n    solver.setup(c0, hphi, RTinv, Lmix_L, Lmix_A, fA, fB);\n    int ret = solver.ComputeConcentration(\n        x, newton_tol_, newton_maxits_, newton_alpha_);\n#if 0\n    if (ret == -1)\n    {\n        std::cerr << \"ERROR, \"\n                     \"CALPHADFreeEnergyFunctionsBinary::\"\n                     \"computePhaseConcentrations() \"\n                     \"failed for conc=\"\n                  << conc[0] << \", hphi=\" << hphi[0] << std::endl;\n        abort();\n    }\n#endif\n\n    return ret;\n}\n#ifdef HAVE_OPENMP_OFFLOAD\n#pragma omp end declare target\n#endif\n\n//-----------------------------------------------------------------------\n\nvoid CALPHADFreeEnergyFunctionsBinary::energyVsPhiAndC(const double temperature,\n    const double* const ceq, const bool found_ceq, const double phi_well_scale,\n    const int npts_phi, const int npts_c)\n{\n    std::cout << \"CALPHADFreeEnergyFunctionsBinary::energyVsPhiAndC()...\"\n              << std::endl;\n\n    double slopec = 0.;\n    double fc0    = 0.;\n    double fc1    = 0.;\n    if (found_ceq)\n    {\n        // compute slope of f between equilibrium concentrations\n        // to add slopec*conc to energy later on\n\n        fc0    = computeFreeEnergy(temperature, &ceq[0], PhaseIndex::phaseL);\n        fc1    = computeFreeEnergy(temperature, &ceq[1], PhaseIndex::phaseA);\n        slopec = -(fc1 - fc0) / (ceq[1] - ceq[0]);\n    }\n    std::cout << std::setprecision(8) << \"fc0: \" << fc0 << \"...\"\n              << \", fc1: \" << fc1 << \"...\" << std::endl;\n    std::cout << \"CALPHADFreeEnergyFunctionsBinary: Use slope: \" << slopec\n              << \"...\" << std::endl;\n\n    // reset cmin, cmax, deltac\n    double cmin   = std::min(ceq[0], ceq[1]);\n    double cmax   = std::max(ceq[0], ceq[1]);\n    double dc     = cmax - cmin;\n    cmin          = std::max(0.25 * cmin, cmin - 0.25 * dc);\n    cmax          = std::min(1. - 0.25 * (1. - cmax), cmax + 0.25 * dc);\n    cmax          = std::max(cmax, cmin + dc);\n    double deltac = (cmax - cmin) / (npts_c - 1);\n\n    std::ofstream tfile(fenergy_diag_filename_, std::ios::out);\n\n    printEnergyVsPhiHeader(\n        temperature, npts_phi, npts_c, cmin, cmax, slopec, tfile);\n\n    for (int i = 0; i < npts_c; i++)\n    {\n        double conc = cmin + deltac * i;\n        printEnergyVsPhi(\n            &conc, temperature, phi_well_scale, npts_phi, slopec, tfile);\n    }\n}\n\n// Print out free energy as a function of phase\n// for given composition and temperature\n// File format: ASCII VTK, readble with Visit\nvoid CALPHADFreeEnergyFunctionsBinary::printEnergyVsPhiHeader(\n    const double temperature, const int nphi, const int nc, const double cmin,\n    const double cmax, const double slopec, std::ostream& os) const\n{\n    os << \"# vtk DataFile Version 2.0\" << std::endl;\n    os << \"Free energy + \" << slopec << \"*c [J/mol] at T=\" << temperature\n       << std::endl;\n    os << \"ASCII\" << std::endl;\n    os << \"DATASET STRUCTURED_POINTS\" << std::endl;\n\n    os << \"DIMENSIONS   \" << nphi << \" \" << nc << \" 1\" << std::endl;\n    double asp_ratio_c = (nc > 1) ? (cmax - cmin) / (nc - 1) : 1.;\n    os << \"ASPECT_RATIO \" << 1. / (nphi - 1) << \" \" << asp_ratio_c << \" 1.\"\n       << std::endl;\n    os << \"ORIGIN        0. \" << cmin << \" 0.\" << std::endl;\n    os << \"POINT_DATA   \" << nphi * nc << std::endl;\n    os << \"SCALARS energy float 1\" << std::endl;\n    os << \"LOOKUP_TABLE default\" << std::endl;\n}\n\n//=======================================================================\n\nvoid CALPHADFreeEnergyFunctionsBinary::printEnergyVsPhi(\n    const double* const conc, const double temperature,\n    const double phi_well_scale, const int npts, const double slopec,\n    std::ostream& os)\n{\n    // std::cout << \"CALPHADFreeEnergyFunctionsBinary::printEnergyVsPhi()...\" <<\n    // std::endl;\n    const double dphi = 1.0 / (double)(npts - 1);\n\n    // os << \"# phi     f(phi)     for c=\" << conc\n    //           << \" and T=\" << temperature << std::endl;\n    for (int i = 0; i < npts; i++)\n    {\n        const double phi = i * dphi;\n\n        double e       = fchem(&phi, conc, temperature);\n        const double w = phi_well_scale * well_func(phi);\n\n        os << e + w + slopec * conc[0] << std::endl;\n    }\n    // os << std::endl;\n}\n\n//=======================================================================\n// compute free energy in [J/mol]\ndouble CALPHADFreeEnergyFunctionsBinary::fchem(\n    const double* const phi, const double* const conc, const double temperature)\n{\n    const double hcphi = interp_func(conc_interp_func_type_, phi[0]);\n\n    const double tol = 1.e-8;\n    double fl        = 0.;\n    double fa        = 0.;\n    double fb        = 0.;\n    if ((phi[0] > tol) & (phi[0] < (1. - tol)))\n    {\n        computePhasesFreeEnergies(temperature, &hcphi, conc[0], fl, fa);\n    }\n    else\n    {\n        if (phi[0] <= tol)\n        {\n            fl = computeFreeEnergy(temperature, conc, PhaseIndex::phaseL);\n        }\n        else\n        {\n            fa = computeFreeEnergy(temperature, conc, PhaseIndex::phaseA);\n        }\n    }\n\n    const double hfphi = interp_func(energy_interp_func_type_, phi[0]);\n\n    double e = (1.0 - hfphi) * fl + hfphi * fa;\n\n    return e;\n}\n\n//=======================================================================\n\nvoid CALPHADFreeEnergyFunctionsBinary::printEnergyVsComposition(\n    const double temperature, std::ostream& os, const int npts)\n{\n    const double dc = 1.0 / (double)(npts - 1);\n\n    os << \"#phi=0\" << std::endl;\n    for (int i = 0; i < npts; i++)\n    {\n        const double conc = i * dc;\n\n        const double phi = 0.0;\n\n        double e = fchem(&phi, &conc, temperature);\n        os << conc << \"\\t\" << e << std::endl;\n    }\n    os << std::endl << std::endl;\n\n    os << \"#phi=1\" << std::endl;\n    for (int i = 0; i < npts; i++)\n    {\n        const double conc = i * dc;\n\n        const double phi = 1.0;\n\n        double e = fchem(&phi, &conc, temperature);\n        os << conc << \"\\t\" << e << std::endl;\n    }\n}\n\n//=======================================================================\n\nvoid CALPHADFreeEnergyFunctionsBinary::preRunDiagnostics(\n    const double T0, const double T1)\n{\n    std::ofstream os1(\"FlC0vsT.dat\", std::ios::out);\n    os1 << \"#Species 0, Phase L\" << std::endl;\n    g_species_phaseL_[0].plotFofT(os1, T0, T1);\n\n    std::ofstream os2(\"FlC1vsT.dat\", std::ios::out);\n    os2 << \"#Species 1, Phase L\" << std::endl;\n    g_species_phaseL_[1].plotFofT(os2, T0, T1);\n\n    std::ofstream os3(\"FsC0vsT.dat\", std::ios::out);\n    os3 << \"#Species 0, Phase A\" << std::endl;\n    g_species_phaseA_[0].plotFofT(os3, T0, T1);\n\n    std::ofstream os4(\"FsC1vsT.dat\", std::ios::out);\n    os4 << \"#Species 1, Phase A\" << std::endl;\n    g_species_phaseA_[1].plotFofT(os4, T0, T1);\n}\n}\n", "meta": {"hexsha": "6e7bfd1cc410982412f200c52cbe7ab207b41559", "size": 17847, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/CALPHADFreeEnergyFunctionsBinary.cc", "max_stars_repo_name": "stvdwtt/Thermo4PFM", "max_stars_repo_head_hexsha": "5308b7c58c4b67ed98d2bd50469226b7d89da2b8", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/CALPHADFreeEnergyFunctionsBinary.cc", "max_issues_repo_name": "stvdwtt/Thermo4PFM", "max_issues_repo_head_hexsha": "5308b7c58c4b67ed98d2bd50469226b7d89da2b8", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/CALPHADFreeEnergyFunctionsBinary.cc", "max_forks_repo_name": "stvdwtt/Thermo4PFM", "max_forks_repo_head_hexsha": "5308b7c58c4b67ed98d2bd50469226b7d89da2b8", "max_forks_repo_licenses": ["BSD-3-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.7372400756, "max_line_length": 88, "alphanum_fraction": 0.5837395641, "num_tokens": 4998, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6959583250334526, "lm_q2_score": 0.5, "lm_q1q2_score": 0.3479791625167263}}
{"text": "/* ----------------------------------------------------------------------- *//**\n *\n * @file boost.hpp\n *\n *//* ----------------------------------------------------------------------- */\n\n#define LIST_CONTINUOUS_PROB_DISTR \\\n    MADLIB_ITEM(beta) \\\n    MADLIB_ITEM(cauchy) \\\n    MADLIB_ITEM(chi_squared) \\\n    MADLIB_ITEM(fisher_f) \\\n    MADLIB_ITEM(exponential) \\\n    MADLIB_ITEM(extreme_value) \\\n    MADLIB_ITEM(gamma) \\\n    MADLIB_ITEM(inverse_chi_squared) \\\n    MADLIB_ITEM(inverse_gamma) \\\n    MADLIB_ITEM(laplace) \\\n    MADLIB_ITEM(logistic) \\\n    MADLIB_ITEM(lognormal) \\\n    MADLIB_ITEM(non_central_beta) \\\n    MADLIB_ITEM(non_central_chi_squared) \\\n    MADLIB_ITEM(non_central_f) \\\n    MADLIB_ITEM(non_central_t) \\\n    MADLIB_ITEM(normal) \\\n    MADLIB_ITEM(pareto) \\\n    MADLIB_ITEM(rayleigh) \\\n    MADLIB_ITEM(triangular) \\\n    MADLIB_ITEM(uniform) \\\n    MADLIB_ITEM(weibull)\n// FIXME: MADLIB-513: Pending Boost bug 6934, we currently do not support the\n// inverse Gaussian distribution. https://svn.boost.org/trac/boost/ticket/6934\n//    MADLIB_ITEM(inverse_gaussian)\n// For Student's t distribution, see student.hpp\n\n\n#define LIST_DISCRETE_PROB_DISTR \\\n    MADLIB_ITEM(bernoulli) \\\n    MADLIB_ITEM(binomial) \\\n    MADLIB_ITEM(geometric) \\\n    MADLIB_ITEM(hypergeometric) \\\n    MADLIB_ITEM(negative_binomial) \\\n    MADLIB_ITEM(poisson)\n\n\n#define MADLIB_ITEM(dist) \\\n    DECLARE_UDF(prob, dist ## _cdf) \\\n    DECLARE_UDF(prob, dist ## _pdf) \\\n    DECLARE_UDF(prob, dist ## _quantile)\n\nLIST_CONTINUOUS_PROB_DISTR\n\n#undef MADLIB_ITEM\n\n#define MADLIB_ITEM(dist) \\\n    DECLARE_UDF(prob, dist ## _cdf) \\\n    DECLARE_UDF(prob, dist ## _pmf) \\\n    DECLARE_UDF(prob, dist ## _quantile)\n\nLIST_DISCRETE_PROB_DISTR\n\n#undef MADLIB_ITEM\n\n\n#ifndef MADLIB_MODULES_PROB_BOOST_HPP\n#define MADLIB_MODULES_PROB_BOOST_HPP\n\n#include <boost/math/distributions.hpp>\n\nnamespace madlib {\n\nnamespace modules {\n\nnamespace prob {\n\nnamespace {\n// No need to make this visable beyond this translation unit.\n\nenum ProbFnOverride {\n    kResultIsReady = 0,\n    kLetBoostCalculate,\n    kLetBoostCalculateUsingValue\n};\n\n/**\n * @brief Via (partial) specialization, this class offers a way to override\n *     boost's domain checks\n *\n * Some boost functions have domain checks we would like to override. E.g.,\n * boost's CDF and PDF for the Fisher F-distribution raise a domain error if the\n * input argument is <0 or infinity. By using madlib::modules::prob::cdf() (and\n * pdf/quantile, respectively), these domain checks can be overridden.\n * In MADlib, we always prefer returning correct values as opposed to raising\n * errors. E.g., for the CDF, it is the correct mathematical behavior to simply\n * return 0 if the input argument for the Fisher F-distribution is < 0.\n *\n * The following functions return \\c true if boost's implementation should be\n * called, and they return \\c false if the function result has alrady been\n * stored in \\c outResult and boost's implementation should not be called any\n * more.\n *\n * Note that C++03 does not support partial specialization of functions. We\n * therefore must partially specialize the whole \\c DomainCheck class.\n */\ntemplate <class Distribution>\nstruct DomainCheck {\n    typedef typename Distribution::value_type RealType;\n\n    template <bool Complement>\n    static ProbFnOverride cdf(const Distribution&, const RealType&, RealType&) {\n        return kLetBoostCalculate;\n    }\n\n    static ProbFnOverride pdf(const Distribution&, const RealType&, RealType&) {\n        return kLetBoostCalculate;\n    }\n\n    template <bool Complement>\n    static ProbFnOverride quantile(const Distribution&, const RealType&,\n        RealType&) {\n\n        return kLetBoostCalculate;\n    }\n};\n\n/**\n * @brief Domain-check overrides for distribution functions with support in\n *     \\f$ \\mathbb R \\f$\n *\n * We override the domain check by treating -infinity and infinity as part of\n * the domain. Some, but not all, boost functions would raise a domain_error\n * instead. See:\n * http://www.boost.org/doc/libs/1_49_0/libs/math/doc/sf_and_dist/html/math_toolkit/backgrounders/implementation.html#math_toolkit.backgrounders.implementation.handling_of_floating_point_infinity\n */\ntemplate <class Distribution>\nstruct RealDomainCheck {\n    typedef typename Distribution::value_type RealType;\n\n    template <bool Complement>\n    static ProbFnOverride cdf(const Distribution&, const RealType& inX,\n        RealType& outResult) {\n\n        if (boost::math::isinf(inX)) {\n            if (inX < 0)\n                outResult = Complement ? 1 : 0;\n            else\n                outResult = Complement ? 0 : 1;\n            return kResultIsReady;\n        }\n        return kLetBoostCalculate;\n    }\n\n    static ProbFnOverride pdf(const Distribution&, const RealType& inX,\n        RealType& outResult) {\n\n        if (boost::math::isinf(inX)) {\n            outResult = 0;\n            return kResultIsReady;\n        }\n        return kLetBoostCalculate;\n    }\n\n    template <bool Complement>\n    static ProbFnOverride quantile(const Distribution&, const RealType&, RealType&) {\n        return kLetBoostCalculate;\n    }\n};\n\n/**\n * @brief Domain-check overrides for distribution functions with support in\n *     \\f$ [0, \\infty) \\f$\n */\ntemplate <class Distribution>\nstruct PositiveDomainCheck : public RealDomainCheck<Distribution> {\n    typedef RealDomainCheck<Distribution> Base;\n    typedef typename Base::RealType RealType;\n\n    template <bool Complement>\n    static ProbFnOverride cdf(const Distribution& inDist, const RealType& inX,\n        RealType& outResult) {\n\n        if (inX < 0) {\n            outResult = Complement ? 1 : 0;\n            return kResultIsReady;\n        }\n        return Base::template cdf<Complement>(inDist, inX, outResult);\n    }\n\n    static ProbFnOverride pdf(const Distribution& inDist, const RealType& inX,\n        RealType& outResult) {\n\n        if (inX < 0) {\n            outResult = 0;\n            return kResultIsReady;\n        }\n        return Base::pdf(inDist, inX, outResult);\n    }\n};\n\n/**\n * @brief Domain-check overrides for distribution functions with support in\n *     \\f$ [0, 1] \\f$\n */\ntemplate <class Distribution>\nstruct ZeroOneDomainCheck : public PositiveDomainCheck<Distribution> {\n    typedef PositiveDomainCheck<Distribution> Base;\n    typedef typename Base::RealType RealType;\n\n    template <bool Complement>\n    static ProbFnOverride cdf(const Distribution&, const RealType& inX,\n        RealType& outResult) {\n\n        if (inX < 0)\n            outResult = Complement ? 1 : 0;\n        else if (inX > 1)\n            outResult = Complement ? 0 : 1;\n        else\n            return kLetBoostCalculate;\n\n        return kResultIsReady;\n    }\n\n    static ProbFnOverride pdf(const Distribution&, const RealType& inX,\n        RealType& outResult) {\n\n        if (inX < 0 || inX > 1) {\n            outResult = 0;\n            return kResultIsReady;\n        }\n        return kLetBoostCalculate;\n    }\n};\n\n/**\n * @brief Domain-check overrides for distribution functions with support in\n *     \\f$ \\mathbb Z \\f$\n */\ntemplate <class Distribution>\nstruct IntegerDomainCheck : public RealDomainCheck<Distribution> {\n    typedef RealDomainCheck<Distribution> Base;\n    typedef typename Base::RealType RealType;\n\n    static ProbFnOverride internalMakeIntegral(ProbFnOverride inAction,\n        const RealType& inX, RealType& outResult) {\n\n        static const char* function = \"madlib::modules::prob::<unnamed>::\"\n            \"IntegerDomainCheck::internalMakeIntegral(...)\";\n\n        if (inAction != kResultIsReady) {\n            if (std::isnan(inX)) {\n                outResult = boost::math::policies::raise_domain_error<RealType>(\n                    function,\n                    \"Random variate must be integral but was: %1%.\",\n                    inX,\n                    typename Distribution::policy_type());\n                inAction = kResultIsReady;\n            } else {\n                outResult = std::floor(inX);\n                inAction = kLetBoostCalculateUsingValue;\n            }\n        }\n        return inAction;\n    }\n\n    template <bool Complement>\n    static ProbFnOverride cdf(const Distribution& inDist, const RealType& inX,\n        RealType& outResult) {\n\n        return internalMakeIntegral(\n            Base::template cdf<Complement>(inDist, inX, outResult), inX,\n                outResult);\n    }\n\n    static ProbFnOverride pdf(const Distribution& inDist, const RealType& inX,\n        RealType& outResult) {\n\n        return internalMakeIntegral(\n            Base::pdf(inDist, inX, outResult), inX, outResult);\n    }\n};\n\n/**\n * @brief Domain-check overrides for distribution functions with support in\n *     \\f$ \\mathbb N_0 \\f$\n */\ntemplate <class Distribution>\nstruct NonNegativeIntegerDomainCheck : public IntegerDomainCheck<Distribution> {\n    typedef IntegerDomainCheck<Distribution> Base;\n    typedef typename Base::RealType RealType;\n\n    template <bool Complement>\n    static ProbFnOverride cdf(const Distribution& inDist, const RealType& inX,\n        RealType& outResult) {\n\n        if (inX < 0) {\n            outResult = Complement ? 1 : 0;\n            return kResultIsReady;\n        }\n        return Base::template cdf<Complement>(inDist, inX, outResult);\n    }\n\n    static ProbFnOverride pdf(const Distribution& inDist, const RealType& inX,\n        RealType& outResult) {\n\n        if (inX < 0) {\n            outResult = 0;\n            return kResultIsReady;\n        }\n        return Base::pdf(inDist, inX, outResult);\n    }\n};\n\n\n/**\n * @brief Boost only accepts 0 or 1 for random variate\n *\n * Due to boost bug 6937, we also need to override the domain check for quantile\n *\n * https://svn.boost.org/trac/boost/ticket/6937\n */\ntemplate <class RealType, class Policy>\nstruct DomainCheck<boost::math::bernoulli_distribution<RealType, Policy> >\n  : public IntegerDomainCheck<\n        boost::math::bernoulli_distribution<RealType, Policy>\n    > {\n    typedef boost::math::bernoulli_distribution<RealType, Policy> Distribution;\n    typedef IntegerDomainCheck<Distribution> Base;\n\n    template <bool Complement>\n    static ProbFnOverride cdf(const Distribution& inDist, const RealType& inX,\n        RealType& outResult) {\n\n        if (inX < 0)\n            outResult = Complement ? 1 : 0;\n        else if (inX > 1)\n            outResult = Complement ? 0 : 1;\n        else\n            return Base::template cdf<Complement>(inDist, inX, outResult);\n\n        return kResultIsReady;\n    }\n\n    static ProbFnOverride pdf(const Distribution& inDist, const RealType& inX,\n        RealType& outResult) {\n\n        if (inX < 0 || inX > 1) {\n            outResult = 0;\n            return kResultIsReady;\n        } else\n            return Base::pdf(inDist, inX, outResult);\n    }\n\n    template <bool Complement>\n    static ProbFnOverride quantile(const Distribution& inDist,\n        const RealType& inP, RealType& outResult) {\n\n        static const char* function = \"madlib::modules::prob::<unnamed>::\"\n            \"DomainCheck<bernoulli_distribution<%1%> >::quantile(...)\";\n\n        if (!boost::math::detail::check_probability(function,\n            inDist.success_fraction(), &outResult, Policy())) {\n            return kResultIsReady;\n        } else if (inP == 1 || inP == 0){\n            outResult = inP;\n            return kResultIsReady;\n        } else {\n            return Base::template quantile<Complement>(inDist, inP, outResult);\n        }\n    }\n};\n\n/**\n * @brief Boost only accepts a limited range for random variates\n *\n * Due to boost bug 6937, we also need to override the domain check for quantile\n *\n * https://svn.boost.org/trac/boost/ticket/6937\n */\ntemplate <class RealType, class Policy>\nstruct DomainCheck<boost::math::binomial_distribution<RealType, Policy> >\n  : public IntegerDomainCheck<\n        boost::math::binomial_distribution<RealType, Policy>\n    > {\n    typedef boost::math::binomial_distribution<RealType, Policy> Distribution;\n    typedef IntegerDomainCheck<Distribution> Base;\n\n    template <bool Complement>\n    static ProbFnOverride cdf(const Distribution& inDist, const RealType& inX,\n        RealType& outResult) {\n\n        static const char* function = \"madlib::modules::prob::<unnamed>::\"\n            \"DomainCheck<binomial_distribution<%1%> >::cdf(...)\";\n\n        if (!boost::math::binomial_detail::check_dist(function, inDist.trials(),\n            inDist.success_fraction(), &outResult, Policy())) {\n            return kResultIsReady;\n        } else if (inX < 0) {\n            outResult = Complement ? 1 : 0;\n            return kResultIsReady;\n        } else if (inX > inDist.trials()) {\n            outResult = Complement ? 0 : 1;\n            return kResultIsReady;\n        }\n        return Base::template cdf<Complement>(inDist, inX, outResult);\n    }\n\n    static ProbFnOverride pdf(const Distribution& inDist, const RealType& inX,\n        RealType& outResult) {\n\n        static const char* function = \"madlib::modules::prob::<unnamed>::\"\n            \"DomainCheck<binomial_distribution<%1%> >::pdf(...)\";\n\n        if (!boost::math::binomial_detail::check_dist(function, inDist.trials(),\n            inDist.success_fraction(), &outResult, Policy())) {\n            return kResultIsReady;\n        } else if (inX < 0 || inX > inDist.trials()) {\n            outResult = 0;\n            return kResultIsReady;\n        }\n        return Base::pdf(inDist, inX, outResult);\n    }\n\n    template <bool Complement>\n    static ProbFnOverride quantile(const Distribution& inDist,\n        const RealType& inP, RealType& outResult) {\n\n        static const char* function = \"madlib::modules::prob::<unnamed>::\"\n            \"DomainCheck<binomial_distribution<%1%> >::quantile(...)\";\n\n        if (!boost::math::binomial_detail::check_dist(function, inDist.trials(),\n                inDist.success_fraction(), &outResult, Policy())\n            || !boost::math::detail::check_probability(function, inP,\n                &outResult, Policy())) {\n            return kResultIsReady;\n        } else if (inP == 1) {\n            outResult = inDist.trials();\n            return kResultIsReady;\n        } else if (inP == 0) {\n            outResult = 0;\n            return kResultIsReady;\n        } else if (inDist.success_fraction() == 1) {\n            outResult = inDist.trials();\n            return kResultIsReady;\n        } else if (inDist.success_fraction() == 0) {\n            outResult = 0;\n            return kResultIsReady;\n        }\n        return Base::template quantile<Complement>(inDist, inP, outResult);\n    }\n};\n\n/**\n * @brief Due to boost bug XXX, we need to override the domain checks\n *\n * FIXME: No boost bug filed so far\n * Boost does not catch the case where lambda is non-finite.\n */\ntemplate <class RealType, class Policy>\nstruct DomainCheck<boost::math::exponential_distribution<RealType, Policy> >\n  : public PositiveDomainCheck<\n        boost::math::exponential_distribution<RealType, Policy>\n    > {\n    typedef boost::math::exponential_distribution<RealType, Policy> Distribution;\n    typedef PositiveDomainCheck<Distribution> Base;\n\n    static bool check_dist(const char* function, RealType lambda,\n        RealType* result, const Policy& pol) {\n\n        if (!boost::math::isfinite(lambda)) {\n            *result = boost::math::policies::raise_domain_error<RealType>(\n                function,\n                \"The scale parameter \\\"lambda\\\" must be finite, but was: %1%.\",\n                lambda, pol);\n            return false;\n        }\n        return true;\n    }\n\n    template <bool Complement>\n    static ProbFnOverride cdf(const Distribution& inDist,\n        const RealType& inX, RealType& outResult) {\n\n        static const char* function = \"madlib::modules::prob::<unnamed>::\"\n            \"DomainCheck<exponential_distribution<%1%> >::cdf(...)\";\n\n        if (!check_dist(function, inDist.lambda(), &outResult, Policy()))\n            return kResultIsReady;\n        return Base::template cdf<Complement>(inDist, inX, outResult);\n    }\n\n    static ProbFnOverride pdf(const Distribution& inDist,\n        const RealType& inX, RealType& outResult) {\n\n        static const char* function = \"madlib::modules::prob::<unnamed>::\"\n            \"DomainCheck<exponential_distribution<%1%> >::pdf(...)\";\n\n        if (!check_dist(function, inDist.lambda(), &outResult, Policy()))\n            return kResultIsReady;\n        return Base::pdf(inDist, inX, outResult);\n    }\n\n    template <bool Complement>\n    static ProbFnOverride quantile(const Distribution& inDist,\n        const RealType& inP, RealType& outResult) {\n\n        static const char* function = \"madlib::modules::prob::<unnamed>::\"\n            \"DomainCheck<exponential_distribution<%1%> >::quantile(...)\";\n\n        if (!check_dist(function, inDist.lambda(), &outResult, Policy()))\n            return kResultIsReady;\n        return Base::template quantile<Complement>(inDist, inP, outResult);\n    }\n};\n\n/**\n * @brief Due to boost bug XXX, we need to override the domain check for\n *     quantile\n *\n * FIXME: No boost bug filed so far\n * Boost does not catch the case where the location or scale parameters are\n * non-finite.\n */\ntemplate <class RealType, class Policy>\nstruct DomainCheck<boost::math::extreme_value_distribution<RealType, Policy> >\n  : public RealDomainCheck<\n        boost::math::extreme_value_distribution<RealType, Policy>\n    > {\n    typedef boost::math::extreme_value_distribution<RealType, Policy> Distribution;\n    typedef RealDomainCheck<Distribution> Base;\n\n    static bool check_dist(const char* function, RealType location,\n        RealType scale, RealType* result, const Policy& pol) {\n\n        return\n            boost::math::detail::check_location(function, location, result, pol)\n            && boost::math::detail::check_scale(function, scale, result, pol);\n    }\n\n    template <bool Complement>\n    static ProbFnOverride cdf(const Distribution& inDist,\n        const RealType& inX, RealType& outResult) {\n\n        static const char* function = \"madlib::modules::prob::<unnamed>::\"\n            \"DomainCheck<extreme_value_distribution<%1%> >::cdf(...)\";\n\n        if (!check_dist(function, inDist.location(), inDist.scale(), &outResult,\n            Policy()))\n            return kResultIsReady;\n        return Base::template cdf<Complement>(inDist, inX, outResult);\n    }\n\n    static ProbFnOverride pdf(const Distribution& inDist,\n        const RealType& inX, RealType& outResult) {\n\n        static const char* function = \"madlib::modules::prob::<unnamed>::\"\n            \"DomainCheck<extreme_value_distribution<%1%> >::pdf(...)\";\n\n        if (!check_dist(function, inDist.location(), inDist.scale(), &outResult,\n            Policy()))\n            return kResultIsReady;\n        return Base::pdf(inDist, inX, outResult);\n    }\n\n    template <bool Complement>\n    static ProbFnOverride quantile(const Distribution& inDist,\n        const RealType& inP, RealType& outResult) {\n\n        static const char* function = \"madlib::modules::prob::<unnamed>::\"\n            \"DomainCheck<extreme_value_distribution<%1%> >::quantile(...)\";\n\n        if (!check_dist(function, inDist.location(), inDist.scale(), &outResult,\n            Policy()))\n            return kResultIsReady;\n        return Base::template quantile<Complement>(inDist, inP, outResult);\n    }\n};\n\n/**\n * @brief Due to boost bug 6937, we need to override the domain check for\n *     quantile\n *\n * https://svn.boost.org/trac/boost/ticket/6937\n */\ntemplate <class RealType, class Policy>\nstruct DomainCheck<boost::math::fisher_f_distribution<RealType, Policy> >\n  : public PositiveDomainCheck<\n        boost::math::fisher_f_distribution<RealType, Policy>\n    > {\n    typedef boost::math::fisher_f_distribution<RealType, Policy> Distribution;\n    typedef PositiveDomainCheck<Distribution> Base;\n\n    template <bool Complement>\n    static ProbFnOverride quantile(const Distribution& inDist,\n        const RealType& inP, RealType& outResult) {\n\n        static const char* function = \"madlib::modules::prob::<unnamed>::\"\n            \"DomainCheck<fisher_f_distribution<%1%> >::quantile(...)\";\n\n        if (!boost::math::detail::check_df(function,\n            inDist.degrees_of_freedom1(), &outResult, Policy())\n            || !boost::math::detail::check_df(function,\n                inDist.degrees_of_freedom2(), &outResult, Policy()))\n            return kResultIsReady;\n\n        if (std::isnan(inP)) {\n            outResult = boost::math::policies::raise_domain_error<RealType>(\n                function,\n                \"Probability argument is %1%, but must be >= 0 and <= 1!\", inP,\n                Policy());\n            return kResultIsReady;\n        }\n        return Base::template quantile<Complement>(inDist, inP, outResult);\n    }\n};\n\n/**\n * @brief Due to boost bug XXXX, we override the domain check for gamma: pdf\n *\n * For the gamma distribution, boost's pdf always returns 0 for x = 0. That is\n * wrong.\n */\ntemplate <class RealType, class Policy>\nstruct DomainCheck<boost::math::gamma_distribution<RealType, Policy> >\n  : public PositiveDomainCheck<\n        boost::math::gamma_distribution<RealType, Policy>\n    > {\n    typedef boost::math::gamma_distribution<RealType, Policy> Distribution;\n    typedef PositiveDomainCheck<Distribution> Base;\n\n    static ProbFnOverride pdf(const Distribution& inDist, const RealType& inX,\n        RealType& outResult) {\n\n        static const char* function = \"madlib::modules::prob::<unnamed>::\"\n            \"DomainCheck<gamma_distribution<%1%> >::pdf(...)\";\n        RealType shape = inDist.shape();\n        RealType scale = inDist.scale();\n        if (!boost::math::detail::check_gamma(function, scale, shape,\n            &outResult, Policy()))\n            return kResultIsReady;\n\n        if (inX == 0) {\n            if (shape == 1)\n                outResult = 1. / scale;\n            else if (shape < 1)\n                outResult\n                    = boost::math::policies::raise_overflow_error<RealType>(\n                        function, 0, Policy());\n            else\n                return kLetBoostCalculate;\n\n            return kResultIsReady;\n        }\n        return Base::pdf(inDist, inX, outResult);\n    }\n};\n\n/**\n * @brief Due to boost bug 6937, we need to override the domain check for\n *     quantile\n *\n * https://svn.boost.org/trac/boost/ticket/6937\n */\ntemplate <class RealType, class Policy>\nstruct DomainCheck<boost::math::geometric_distribution<RealType, Policy> >\n  : public NonNegativeIntegerDomainCheck<\n        boost::math::geometric_distribution<RealType, Policy>\n    > {\n    typedef boost::math::geometric_distribution<RealType, Policy> Distribution;\n    typedef NonNegativeIntegerDomainCheck<Distribution> Base;\n\n    template <bool Complement>\n    static ProbFnOverride cdf(const Distribution& inDist, const RealType& inX,\n        RealType& outResult) {\n\n        if (inDist.success_fraction() == 1 && !std::isnan(inX)) {\n            if (inX < 0)\n                outResult = Complement ? 1 : 0;\n            else if (inX > 0)\n                outResult = Complement ? 0 : 1;\n            else /* if (inX == 0) */\n                outResult = 1;\n            return kResultIsReady;\n        }\n        return Base::template cdf<Complement>(inDist, inX, outResult);\n    }\n\n    template <bool Complement>\n    static ProbFnOverride quantile(const Distribution& inDist,\n        const RealType& inP, RealType& outResult) {\n\n        static const char* function = \"madlib::modules::prob::<unnamed>::\"\n            \"DomainCheck<geometric_distribution<%1%> >::quantile(...)\";\n\n        if (!boost::math::detail::check_probability(function,\n            inDist.success_fraction(), &outResult, Policy()))\n            return kResultIsReady;\n\n        return Base::template quantile<Complement>(inDist, inP, outResult);\n    }\n};\n\n\n/**\n * @brief Boost only accepts a limited range for random variates\n */\ntemplate <class RealType, class Policy>\nstruct DomainCheck<boost::math::hypergeometric_distribution<RealType, Policy> >\n  : public NonNegativeIntegerDomainCheck<\n        boost::math::hypergeometric_distribution<RealType, Policy>\n    > {\n    typedef boost::math::hypergeometric_distribution<RealType, Policy> Distribution;\n    typedef NonNegativeIntegerDomainCheck<Distribution> Base;\n\n    template <bool Complement>\n    static ProbFnOverride cdf(const Distribution& inDist, const RealType& inX,\n        RealType& outResult) {\n\n        // inDist's parameters are all unsigned, so we need to be careful in the\n        // comparison!\n        if (inX + inDist.total() < inDist.defective() + inDist.sample_count())\n            outResult = Complement ? 1 : 0;\n        else if (inX > inDist.sample_count() || inX > inDist.defective())\n            outResult = Complement ? 0 : 1;\n        else\n            return Base::template cdf<Complement>(inDist, inX, outResult);\n\n        return kResultIsReady;\n    }\n\n    static ProbFnOverride pdf(const Distribution& inDist, const RealType& inX,\n        RealType& outResult) {\n\n        // inDist's parameters are all unsigned, so we need to be careful in the\n        // comparison!\n        if (inX + inDist.total() < inDist.defective() + inDist.sample_count()\n            || inX > inDist.sample_count() || inX > inDist.defective()) {\n            outResult = 0;\n            return kResultIsReady;\n        } else\n            return Base::pdf(inDist, inX, outResult);\n    }\n};\n\n\n/**\n * @brief Boost returns a small non-zero value for quantile(0) instead of 0\n */\ntemplate <class RealType, class Policy>\nstruct DomainCheck<boost::math::inverse_gamma_distribution<RealType, Policy> >\n  : public PositiveDomainCheck<\n        boost::math::inverse_gamma_distribution<RealType, Policy>\n    > {\n    typedef boost::math::inverse_gamma_distribution<RealType, Policy> Distribution;\n    typedef PositiveDomainCheck<Distribution> Base;\n\n    template <bool Complement>\n    static ProbFnOverride quantile(const Distribution& inDist,\n        const RealType& inP, RealType& outResult) {\n\n        static const char* function = \"madlib::modules::prob::<unnamed>::\"\n            \"DomainCheck<inverse_gamma_distribution<%1%> >::quantile(...)\";\n\n        if(!boost::math::detail::check_inverse_gamma(function, inDist.scale(),\n            inDist.shape(), &outResult, Policy()))\n            return kResultIsReady;\n        else if (inP == 0) {\n            outResult = 0;\n            return kResultIsReady;\n        }\n        return Base::template quantile<Complement>(inDist, inP, outResult);\n    }\n};\n\n/**\n * @brief Due to boost bug XXX, we need to override the domain check for\n *     quantile\n *\n * FIXME: No boost bug filed so far\n * Boost does not catch the case where location or scale are not finite.\n */\ntemplate <class RealType, class Policy>\nstruct DomainCheck<boost::math::lognormal_distribution<RealType, Policy> >\n  : public PositiveDomainCheck<\n        boost::math::lognormal_distribution<RealType, Policy>\n    > {\n    typedef boost::math::lognormal_distribution<RealType, Policy> Distribution;\n    typedef PositiveDomainCheck<Distribution> Base;\n\n    static bool check_dist(const char* function, RealType location,\n        RealType scale, RealType* result, const Policy& pol) {\n\n        if (!boost::math::detail::check_location(function, location, result,\n                pol)\n            || !boost::math::detail::check_scale(function, scale, result, pol))\n            return false;\n        return true;\n    }\n\n    static ProbFnOverride pdf(const Distribution& inDist,\n        const RealType& inX, RealType& outResult) {\n\n        static const char* function = \"madlib::modules::prob::<unnamed>::\"\n            \"DomainCheck<lognormal_distribution<%1%> >::pdf(...)\";\n\n        if (!check_dist(function, inDist.location(), inDist.scale(), &outResult,\n            Policy()))\n            return kResultIsReady;\n        return Base::pdf(inDist, inX, outResult);\n    }\n\n    template <bool Complement>\n    static ProbFnOverride quantile(const Distribution& inDist,\n        const RealType& inP, RealType& outResult) {\n\n        static const char* function = \"madlib::modules::prob::<unnamed>::\"\n            \"DomainCheck<lognormal_distribution<%1%> >::quantile(...)\";\n\n        if (!check_dist(function, inDist.location(), inDist.scale(), &outResult,\n            Policy()))\n            return kResultIsReady;\n        return Base::template quantile<Complement>(inDist, inP, outResult);\n    }\n};\n\n/**\n * @brief Due to boost bug 6937, we need to override the domain check for\n *     quantile.\n *\n * https://svn.boost.org/trac/boost/ticket/6937\n *\n * Also, we want to raise an error if the success probability is 0, because the\n * distribution is not well-defined in that case.\n */\ntemplate <class RealType, class Policy>\nstruct DomainCheck<boost::math::negative_binomial_distribution<RealType, Policy> >\n  : public NonNegativeIntegerDomainCheck<\n        boost::math::negative_binomial_distribution<RealType, Policy>\n    > {\n    typedef boost::math::negative_binomial_distribution<RealType, Policy> Distribution;\n    typedef NonNegativeIntegerDomainCheck<Distribution> Base;\n\n    static bool check_dist(const char* function, const RealType& r,\n        const RealType& p, RealType* result, const Policy& pol) {\n\n        if (!boost::math::negative_binomial_detail::check_dist(function, r, p,\n                result, pol)) {\n            return false;\n        } else if (p == 0) {\n            *result = boost::math::policies::raise_domain_error<RealType>(\n                function,\n                \"Probability argument is %1%, but must be > 0 and <= 1!\",\n                p, pol);\n            return false;\n        }\n        return true;\n    }\n\n    template <bool Complement>\n    static ProbFnOverride cdf(const Distribution& inDist,\n        const RealType& inX, RealType& outResult) {\n\n        static const char* function = \"madlib::modules::prob::<unnamed>::\"\n            \"DomainCheck<negative_binomial_distribution<%1%> >::cdf(...)\";\n\n        if (!check_dist(function, inDist.successes(), inDist.success_fraction(),\n            &outResult, Policy()))\n            return kResultIsReady;\n        return Base::template cdf<Complement>(inDist, inX, outResult);\n    }\n\n    static ProbFnOverride pdf(const Distribution& inDist,\n        const RealType& inX, RealType& outResult) {\n\n        static const char* function = \"madlib::modules::prob::<unnamed>::\"\n            \"DomainCheck<negative_binomial_distribution<%1%> >::pdf(...)\";\n\n        if (!check_dist(function, inDist.successes(), inDist.success_fraction(),\n            &outResult, Policy()))\n            return kResultIsReady;\n        return Base::pdf(inDist, inX, outResult);\n    }\n\n    template <bool Complement>\n    static ProbFnOverride quantile(const Distribution& inDist,\n        const RealType& inP, RealType& outResult) {\n\n        static const char* function = \"madlib::modules::prob::<unnamed>::\"\n            \"DomainCheck<negative_binomial_distribution<%1%> >::quantile(...)\";\n\n        if (!check_dist(function, inDist.successes(), inDist.success_fraction(),\n            &outResult, Policy())) {\n            return kResultIsReady;\n        } else if (inDist.success_fraction() == 1) {\n            // distribution is single-point measure, i.e., same for complement\n            outResult = 0;\n            return kResultIsReady;\n        }\n        return Base::template quantile<Complement>(inDist, inP, outResult);\n    }\n};\n\n/**\n * @brief Due to boost bug XXX, we need to check the corner cases for the pdf\n *\n * FIXME: No boost bug filed so far\n */\ntemplate <class RealType, class Policy>\nstruct DomainCheck<boost::math::non_central_beta_distribution<RealType, Policy> >\n  : public ZeroOneDomainCheck<\n        boost::math::non_central_beta_distribution<RealType, Policy>\n    > {\n    typedef boost::math::non_central_beta_distribution<RealType, Policy> Distribution;\n    typedef ZeroOneDomainCheck<Distribution> Base;\n\n    static ProbFnOverride pdf(const Distribution& inDist,\n        const RealType& inX, RealType& outResult) {\n\n        static const char* function = \"madlib::modules::prob::<unnamed>::\"\n            \"DomainCheck<non_central_beta_distribution<%1%> >::quantile(...)\";\n\n        if (inX == 0 || inX == 1) {\n            if(!boost::math::beta_detail::check_alpha(function, inDist.alpha(),\n                    &outResult, Policy())\n                || !boost::math::beta_detail::check_beta(function,\n                    inDist.beta(), &outResult, Policy())\n                || !boost::math::detail::check_non_centrality(function,\n                    inDist.non_centrality(), &outResult, Policy()))\n                return kResultIsReady;\n\n            if (inX == 0) {\n                if (inDist.alpha() < 1)\n                    outResult = boost::math::policies\n                        ::raise_overflow_error<RealType>(function, 0, Policy());\n                else if (inDist.alpha() == 1)\n                    outResult = inDist.beta()\n                              * std::exp(-inDist.non_centrality()/2.);\n                else /* if (inDist.alpha() > 1) */\n                    outResult = 0;\n                return kResultIsReady;\n            } else /* if (inX == 1) */ {\n                if (inDist.beta() < 1)\n                    outResult = boost::math::policies\n                        ::raise_overflow_error<RealType>(function, 0, Policy());\n                else if (inDist.beta() == 1)\n                    outResult = inDist.alpha() + inDist.non_centrality()/2.;\n                else /* if (inDist.beta() > 1) */\n                    outResult = 0;\n                return kResultIsReady;\n            }\n        }\n        return Base::pdf(inDist, inX, outResult);\n    }\n};\n\n/**\n * @brief Due to boost bug XXX, we need to check the corner cases for the pdf\n *\n * FIXME: No boost bug filed so far\n */\ntemplate <class RealType, class Policy>\nstruct DomainCheck<boost::math::non_central_chi_squared_distribution<RealType, Policy> >\n  : public PositiveDomainCheck<\n        boost::math::non_central_chi_squared_distribution<RealType, Policy>\n    > {\n    typedef boost::math::non_central_chi_squared_distribution<RealType, Policy> Distribution;\n    typedef PositiveDomainCheck<Distribution> Base;\n\n    static ProbFnOverride pdf(const Distribution& inDist,\n        const RealType& inX, RealType& outResult) {\n\n        static const char* function = \"madlib::modules::prob::<unnamed>::\"\n            \"DomainCheck<non_central_chi_squared_distribution<%1%> >::quantile(...)\";\n\n        if (inX == 0) {\n            if(!boost::math::detail::check_df(function,\n                    inDist.degrees_of_freedom(), &outResult, Policy())\n                || !boost::math::detail::check_non_centrality(function,\n                    inDist.non_centrality(), &outResult, Policy()))\n                return kResultIsReady;\n\n            if (inDist.degrees_of_freedom() < 2)\n                outResult = boost::math::policies\n                    ::raise_overflow_error<RealType>(function, 0, Policy());\n            else if (inDist.degrees_of_freedom() == 2)\n                // In this case, f(x) = exp(-lambda/2) * g(x), where g(x)\n                // is the densitiy of a chi-squared distributed RV with 2\n                // degrees of freedom, i.e., f(x) = exp(-lambda/2) / 2\n                outResult = std::exp(-inDist.non_centrality()/2.) / 2.;\n            else /* if (inDist.degrees_of_freedom() > 2) */\n                outResult = 0;\n            return kResultIsReady;\n        }\n        return Base::pdf(inDist, inX, outResult);\n    }\n};\n\n/**\n * @brief Due to boost bug XXX, we need to check the corner cases for the pdf\n *\n * FIXME: No boost bug filed so far\n */\ntemplate <class RealType, class Policy>\nstruct DomainCheck<boost::math::non_central_f_distribution<RealType, Policy> >\n  : public PositiveDomainCheck<\n        boost::math::non_central_f_distribution<RealType, Policy>\n    > {\n    typedef boost::math::non_central_f_distribution<RealType, Policy> Distribution;\n    typedef PositiveDomainCheck<Distribution> Base;\n\n    static ProbFnOverride pdf(const Distribution& inDist,\n        const RealType& inX, RealType& outResult) {\n\n        static const char* function = \"madlib::modules::prob::<unnamed>::\"\n            \"DomainCheck<non_central_f_distribution<%1%> >::quantile(...)\";\n\n        if (inX == 0) {\n            if(!boost::math::detail::check_df(function,\n                    inDist.degrees_of_freedom1(), &outResult, Policy())\n                || !boost::math::detail::check_df(function,\n                    inDist.degrees_of_freedom2(), &outResult, Policy())\n                || !boost::math::detail::check_non_centrality(function,\n                    inDist.non_centrality(), &outResult, Policy()))\n                return kResultIsReady;\n\n            if (inDist.degrees_of_freedom1() < 2)\n                outResult = boost::math::policies\n                    ::raise_overflow_error<RealType>(function, 0, Policy());\n            else if (inDist.degrees_of_freedom1() == 2)\n                // In this case, f(x) = exp(-lambda/2)\n                outResult = std::exp(-inDist.non_centrality()/2.);\n            else /* if (inDist.degrees_of_freedom1() > 2) */\n                outResult = 0;\n            return kResultIsReady;\n        }\n        return Base::pdf(inDist, inX, outResult);\n    }\n};\n\n/**\n * @brief Override the domain check for Pareto: quantile\n *\n * For the Pareto distribution, boost sometimes returns max_value instead\n * of infinity. We override that.\n */\ntemplate <class RealType, class Policy>\nstruct DomainCheck<boost::math::pareto_distribution<RealType, Policy> >\n  : public PositiveDomainCheck<\n        boost::math::pareto_distribution<RealType, Policy>\n    > {\n    typedef boost::math::pareto_distribution<RealType, Policy> Distribution;\n    typedef PositiveDomainCheck<Distribution> Base;\n\n    template <bool Complement>\n    static ProbFnOverride cdf(const Distribution& inDist,\n        const RealType& inX, RealType& outResult) {\n\n        static const char* function = \"madlib::modules::prob::<unnamed>::\"\n            \"DomainCheck<pareto_distribution<%1%> >::cdf(...)\";\n\n        if (inX <= inDist.scale()) {\n            if (boost::math::detail::check_pareto(function, inDist.scale(),\n                inDist.shape(), &outResult, Policy()))\n                outResult = 0;\n            return kResultIsReady;\n        }\n        return Base::template cdf<Complement>(inDist, inX, outResult);\n    }\n\n    static ProbFnOverride pdf(const Distribution& inDist,\n        const RealType& inX, RealType& outResult) {\n\n        static const char* function = \"madlib::modules::prob::<unnamed>::\"\n            \"DomainCheck<pareto_distribution<%1%> >::pdf(...)\";\n\n        if (inX < inDist.scale()) {\n            if (boost::math::detail::check_pareto(function, inDist.scale(),\n                inDist.shape(), &outResult, Policy()))\n                outResult = 0;\n            return kResultIsReady;\n        }\n        return Base::pdf(inDist, inX, outResult);\n    }\n\n    template <bool Complement>\n    static ProbFnOverride quantile(const Distribution& inDist,\n        const RealType& inP, RealType& outResult) {\n\n        static const char* function = \"madlib::modules::prob::<unnamed>::\"\n            \"DomainCheck<pareto_distribution<%1%> >::quantile(...)\";\n\n        if (!boost::math::detail::check_pareto(function, inDist.scale(),\n            inDist.shape(), &outResult, Policy()))\n            return kResultIsReady;\n        else if (inP == 1) {\n            outResult = boost::math::policies::raise_overflow_error<RealType>(\n                function, 0, Policy());\n            return kResultIsReady;\n        }\n        return Base::template quantile<Complement>(inDist, inP, outResult);\n    }\n};\n\n/**\n * @brief Due to boost bug 6937, we need to override the domain check for\n *     quantile\n *\n * https://svn.boost.org/trac/boost/ticket/6937\n */\ntemplate <class RealType, class Policy>\nstruct DomainCheck<boost::math::poisson_distribution<RealType, Policy> >\n  : public NonNegativeIntegerDomainCheck<\n        boost::math::poisson_distribution<RealType, Policy>\n    > {\n    typedef boost::math::poisson_distribution<RealType, Policy> Distribution;\n    typedef NonNegativeIntegerDomainCheck<Distribution> Base;\n\n    template <bool Complement>\n    static ProbFnOverride quantile(const Distribution& inDist,\n        const RealType& inP, RealType& outResult) {\n\n        static const char* function = \"madlib::modules::prob::<unnamed>::\"\n            \"DomainCheck<poisson_distribution<%1%> >::quantile(...)\";\n\n        if (!boost::math::poisson_detail::check_dist(function,\n            inDist.mean(), &outResult, Policy()))\n            return kResultIsReady;\n        else if (inP == 1) {\n            outResult = boost::math::policies::raise_overflow_error<RealType>(\n                function, 0, Policy());\n            return kResultIsReady;\n        }\n\n        return Base::template quantile<Complement>(inDist, inP, outResult);\n    }\n};\n\n/**\n * @brief Due to boost bug XXX, we need to override the domain check for\n *     quantile\n *\n * FIXME: No boost bug filed so far\n * Boost does not catch the case where sigma is NaN.\n */\ntemplate <class RealType, class Policy>\nstruct DomainCheck<boost::math::rayleigh_distribution<RealType, Policy> >\n  : public PositiveDomainCheck<\n        boost::math::rayleigh_distribution<RealType, Policy>\n    > {\n    typedef boost::math::rayleigh_distribution<RealType, Policy> Distribution;\n    typedef PositiveDomainCheck<Distribution> Base;\n\n    static bool check_sigma_finite(const char* function, RealType sigma,\n        RealType* result, const Policy& pol) {\n\n        if (!boost::math::isfinite(sigma)) {\n            *result = boost::math::policies::raise_domain_error<RealType>(\n                function,\n                \"The scale parameter \\\"sigma\\\" must be finite, but was: %1%.\",\n                sigma, pol);\n            return false;\n        }\n        return true;\n    }\n\n    template <bool Complement>\n    static ProbFnOverride cdf(const Distribution& inDist,\n        const RealType& inX, RealType& outResult) {\n\n        static const char* function = \"madlib::modules::prob::<unnamed>::\"\n            \"DomainCheck<rayleigh_distribution<%1%> >::cdf(...)\";\n\n        if (!check_sigma_finite(function, inDist.sigma(), &outResult, Policy()))\n            return kResultIsReady;\n\n        return Base::template cdf<Complement>(inDist, inX, outResult);\n    }\n\n    static ProbFnOverride pdf(const Distribution& inDist,\n        const RealType& inX, RealType& outResult) {\n\n        static const char* function = \"madlib::modules::prob::<unnamed>::\"\n            \"DomainCheck<rayleigh_distribution<%1%> >::pdf(...)\";\n\n        if (!check_sigma_finite(function, inDist.sigma(), &outResult, Policy()))\n            return kResultIsReady;\n\n        return Base::pdf(inDist, inX, outResult);\n    }\n\n    template <bool Complement>\n    static ProbFnOverride quantile(const Distribution& inDist,\n        const RealType& inP, RealType& outResult) {\n\n        static const char* function = \"madlib::modules::prob::<unnamed>::\"\n            \"DomainCheck<rayleigh_distribution<%1%> >::quantile(...)\";\n\n        if (!check_sigma_finite(function, inDist.sigma(), &outResult, Policy()))\n            return kResultIsReady;\n\n        return Base::template quantile<Complement>(inDist, inP, outResult);\n    }\n};\n\n/**\n * @brief Due to boost bugs 6938 and 6939, we need to override the domain checks\n *\n * https://svn.boost.org/trac/boost/ticket/6938\n * https://svn.boost.org/trac/boost/ticket/6939\n */\ntemplate <class RealType, class Policy>\nstruct DomainCheck<boost::math::weibull_distribution<RealType, Policy> >\n  : public PositiveDomainCheck<\n        boost::math::weibull_distribution<RealType, Policy>\n    > {\n    typedef boost::math::weibull_distribution<RealType, Policy> Distribution;\n    typedef PositiveDomainCheck<Distribution> Base;\n\n    // BEGIN Copied from boost/math/distributions/weibull.hpp (v1.49), but replaced\n    // \"<\" check by \"<=\".\n    static bool check_weibull_shape(\n        const char* function,\n        RealType shape,\n        RealType* result, const Policy& pol) {\n\n        if((shape <= 0) || !(boost::math::isfinite)(shape)) {\n            *result = boost::math::policies::raise_domain_error<RealType>(\n                function,\n                \"Shape parameter is %1%, but must be > 0 !\", shape, pol);\n            return false;\n        }\n        return true;\n    }\n    // END Copied from boost/math/distributions/weibull.hpp (v1.49)\n\n    template <bool Complement>\n    static ProbFnOverride cdf(const Distribution& inDist, const RealType& inX,\n        RealType& outResult) {\n\n        static const char* function = \"madlib::modules::prob::<unnamed>::\"\n            \"DomainCheck<weibull_distribution<%1%> >::cdf(...)\";\n        RealType shape = inDist.shape();\n        if (!check_weibull_shape(function, shape, &outResult, Policy()))\n            return kResultIsReady;\n\n        return Base::template cdf<Complement>(inDist, inX, outResult);\n    }\n\n    static ProbFnOverride pdf(const Distribution& inDist, const RealType& inX,\n        RealType& outResult) {\n\n        static const char* function = \"madlib::modules::prob::<unnamed>::\"\n            \"DomainCheck<weibull_distribution<%1%> >::pdf(...)\";\n        RealType shape = inDist.shape();\n        if (!check_weibull_shape(function, shape, &outResult, Policy()))\n            return kResultIsReady;\n\n        if (inX == 0) {\n            if (shape == 1)\n                outResult = 1;\n            else if (shape < 1)\n                outResult = boost::math::policies::raise_overflow_error<RealType>(\n                    function, 0, Policy());\n            else\n                return kLetBoostCalculate;\n\n            return kResultIsReady;\n        }\n        return Base::pdf(inDist, inX, outResult);\n    }\n\n    template <bool Complement>\n    static ProbFnOverride quantile(const Distribution& inDist,\n        const RealType& inP, RealType& outResult) {\n\n        static const char* function = \"madlib::modules::prob::<unnamed>::\"\n            \"DomainCheck<weibull_distribution<%1%> >::quantile(...)\";\n        RealType shape = inDist.shape();\n        if (!check_weibull_shape(function, shape, &outResult, Policy()))\n            return kResultIsReady;\n\n        return Base::template quantile<Complement>(inDist, inP, outResult);\n    }\n};\n\n\n\n#define DOMAIN_CHECK_OVERRIDE(dist, check) \\\n    template <class RealType, class Policy> \\\n    struct DomainCheck<boost::math::dist ## _distribution<RealType, Policy> > \\\n      : public check<boost::math::dist ## _distribution<RealType, Policy> > { };\n\nDOMAIN_CHECK_OVERRIDE(beta, ZeroOneDomainCheck)\nDOMAIN_CHECK_OVERRIDE(chi_squared, PositiveDomainCheck)\nDOMAIN_CHECK_OVERRIDE(laplace, RealDomainCheck)\nDOMAIN_CHECK_OVERRIDE(non_central_t, RealDomainCheck)\nDOMAIN_CHECK_OVERRIDE(triangular, RealDomainCheck)\nDOMAIN_CHECK_OVERRIDE(uniform, RealDomainCheck)\n// The following lines are currently commented out. Each of these is a boost\n// deficiency unfortunately. See above.\n// DOMAIN_CHECK_OVERRIDE(exponential, PositiveDomainCheck)\n// DOMAIN_CHECK_OVERRIDE(extreme_value, RealDomainCheck)\n// DOMAIN_CHECK_OVERRIDE(fisher_f, PositiveDomainCheck)\n// DOMAIN_CHECK_OVERRIDE(gamma, PositiveDomainCheck)\n// DOMAIN_CHECK_OVERRIDE(geometric, NonNegativeIntegerDomainCheck)\n// DOMAIN_CHECK_OVERRIDE(lognormal, PositiveDomainCheck)\n// DOMAIN_CHECK_OVERRIDE(hypergeometric, NonNegativeIntegerDomainCheck)\n// DOMAIN_CHECK_OVERRIDE(inverse_gamma, PositiveDomainCheck)\n// DOMAIN_CHECK_OVERRIDE(negative_binomial, NonNegativeIntegerDomainCheck)\n// DOMAIN_CHECK_OVERRIDE(non_central_beta, ZeroOneDomainCheck)\n// DOMAIN_CHECK_OVERRIDE(non_central_chi_squared, PositiveDomainCheck)\n// DOMAIN_CHECK_OVERRIDE(non_central_f, PositiveDomainCheck)\n// DOMAIN_CHECK_OVERRIDE(pareto, PositiveDomainCheck)\n// DOMAIN_CHECK_OVERRIDE(poisson, NonNegativeIntegerDomainCheck)\n// DOMAIN_CHECK_OVERRIDE(rayleigh, PositiveDomainCheck)\n// DOMAIN_CHECK_OVERRIDE(weibull, PositiveDomainCheck)\n\n#undef DOMAIN_CHECK_OVERRIDE\n\n} // anonymous namespace\n\n#define DEFINE_BOOST_WRAPPER(_dist, _what, _domain_check_what) \\\n    template <class RealType, class Policy> \\\n    inline \\\n    RealType \\\n    _what(const boost::math::_dist ## _distribution<RealType, Policy>& dist, \\\n        const RealType& x) { \\\n        \\\n        typedef boost::math::_dist ## _distribution<RealType, Policy> Dist; \\\n        RealType result; \\\n        switch (DomainCheck<Dist>::_domain_check_what(dist, x, result)) { \\\n            case kResultIsReady: return result; \\\n            case kLetBoostCalculate: return boost::math::_what(dist, x); \\\n            case kLetBoostCalculateUsingValue: \\\n                return boost::math::_what(dist, result); \\\n            default: throw std::logic_error(\"Unexpected case detected in \" \\\n                \"domain-check override for a boost probability function.\"); \\\n        } \\\n    }\n\n#define DEFINE_BOOST_COMPLEMENT_WRAPPER(_dist, _what) \\\n    template <class RealType, class Policy> \\\n    inline \\\n    RealType \\\n    _what(const boost::math::complemented2_type< \\\n        boost::math::_dist ## _distribution<RealType, Policy>, \\\n        RealType \\\n    >& c) { \\\n        typedef boost::math::_dist ## _distribution<RealType, Policy> Dist; \\\n        typedef boost::math::complemented2_type<Dist, RealType> Complement; \\\n        RealType result; \\\n        switch (DomainCheck<Dist>::template _what<true>(c.dist, c.param, result)) { \\\n            case kResultIsReady: return result; \\\n            case kLetBoostCalculate: return boost::math::_what(c); \\\n            case kLetBoostCalculateUsingValue: \\\n                return boost::math::_what(Complement(c.dist, result)); \\\n            default: throw std::logic_error(\"Unexpected case detected in \" \\\n                \"domain-check override for a boost probability function.\"); \\\n        } \\\n    }\n\n#define DEFINE_BOOST_PROBABILITY_DISTR(_dist) \\\n    typedef boost::math::_dist ## _distribution< \\\n        double, boost_mathkit_policy> _dist; \\\n    \\\n    DEFINE_BOOST_WRAPPER(_dist, cdf, template cdf<false>) \\\n    DEFINE_BOOST_COMPLEMENT_WRAPPER(_dist, cdf) \\\n    DEFINE_BOOST_WRAPPER(_dist, pdf, pdf) \\\n    DEFINE_BOOST_WRAPPER(_dist, quantile, template quantile<false>) \\\n    DEFINE_BOOST_COMPLEMENT_WRAPPER(_dist, quantile)\n\n\n#define MADLIB_ITEM(_dist) \\\n    DEFINE_BOOST_PROBABILITY_DISTR(_dist)\n\n// Note that boost also uses the pdf() if actually a probability mass function\n// is meant\nLIST_CONTINUOUS_PROB_DISTR\nLIST_DISCRETE_PROB_DISTR\n\n#undef MADLIB_ITEM\n#undef DEFINE_PROBABILITY_DISTR\n#undef DEFINE_BOOST_WRAPPER\n#undef LIST_CONTINUOUS_PROB_DISTR\n\n} // namespace prob\n\n} // namespace modules\n\n} // namespace regress\n\n#endif // defined(MADLIB_MODULES_PROB_BOOST_HPP)\n", "meta": {"hexsha": "cd70fd518f02afab8328dc859b04df2123cfc221", "size": 50520, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/modules/prob/boost.hpp", "max_stars_repo_name": "fmcquillan99/apache-madlib", "max_stars_repo_head_hexsha": "e2dea62d1eadc7f662f2d926c71f42332f414ca0", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2018-09-18T07:44:22.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-14T19:45:18.000Z", "max_issues_repo_path": "src/modules/prob/boost.hpp", "max_issues_repo_name": "fmcquillan99/apache-madlib", "max_issues_repo_head_hexsha": "e2dea62d1eadc7f662f2d926c71f42332f414ca0", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-09-06T05:50:17.000Z", "max_issues_repo_issues_event_max_datetime": "2018-09-06T05:50:17.000Z", "max_forks_repo_path": "src/modules/prob/boost.hpp", "max_forks_repo_name": "fmcquillan99/apache-madlib", "max_forks_repo_head_hexsha": "e2dea62d1eadc7f662f2d926c71f42332f414ca0", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-09-03T20:50:13.000Z", "max_forks_repo_forks_event_max_datetime": "2019-09-03T20:50:13.000Z", "avg_line_length": 36.3191948239, "max_line_length": 195, "alphanum_fraction": 0.6403602534, "num_tokens": 12077, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6548947290421276, "lm_q2_score": 0.5312093733737563, "lm_q1q2_score": 0.34788621864024455}}
{"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_ADADELTA_HPP\n#define NETKET_ADADELTA_HPP\n\n#include <Eigen/Core>\n#include <Eigen/Dense>\n#include <cassert>\n#include <cmath>\n#include <complex>\n#include <iostream>\n#include \"abstract_stepper.hpp\"\n\nnamespace netket {\n\nclass AdaDelta : public AbstractStepper {\n  int npar_;\n\n  double rho_;\n  double epscut_;\n\n  Eigen::VectorXd Eg2_;\n  Eigen::VectorXd Edx2_;\n\n  int mynode_;\n\n  const std::complex<double> I_;\n\n public:\n  // Json constructor\n  explicit AdaDelta(const json &pars)\n      : rho_(FieldOrDefaultVal(pars[\"Learning\"], \"Rho\", 0.95)),\n        epscut_(FieldOrDefaultVal(pars[\"Learning\"], \"Epscut\", 1.0e-7)),\n        I_(0, 1) {\n    npar_ = -1;\n\n    PrintParameters();\n  }\n\n  void PrintParameters() {\n    MPI_Comm_rank(MPI_COMM_WORLD, &mynode_);\n    if (mynode_ == 0) {\n      std::cout << \"# Adadelta stepper initialized with these parameters : \"\n                << std::endl;\n      std::cout << \"# Rho = \" << rho_ << std::endl;\n      std::cout << \"# Epscut = \" << epscut_ << std::endl;\n    }\n  }\n\n  void Init(const Eigen::VectorXd &pars) override {\n    npar_ = pars.size();\n    Eg2_.setZero(npar_);\n    Edx2_.setZero(npar_);\n\n  }\n\n  void Init(const Eigen::VectorXcd &pars) override {\n    npar_ = 2 * pars.size();\n    Eg2_.setZero(npar_);\n    Edx2_.setZero(npar_);\n\n  }\n\n  void Update(const Eigen::VectorXd &grad, Eigen::VectorXd &pars) override {\n    assert(npar_ > 0);\n\n    Eg2_=rho_*Eg2_+(1.-rho_)*grad.cwiseAbs2();\n\n    Eigen::VectorXd Dx(npar_);\n\n    for(int i=0;i<npar_;i++){\n      Dx(i)=-std::sqrt(Edx2_(i)+epscut_)*grad(i);\n      Dx(i)/=std::sqrt(Eg2_(i)+epscut_);\n      pars(i)+=Dx(i);\n    }\n\n    Edx2_=rho_*Edx2_+(1.-rho_)*Dx.cwiseAbs2();\n\n  }\n\n  void Update(const Eigen::VectorXcd &grad, Eigen::VectorXd &pars) override {\n    Update(Eigen::VectorXd(grad.real()), pars);\n  }\n\n  void Update(const Eigen::VectorXcd &grad, Eigen::VectorXcd &pars) override {\n    assert(npar_==2*pars.size());\n\n    Eigen::VectorXd Dx(npar_);\n\n    for(int i=0;i<pars.size();i++){\n      Eg2_(2*i)=rho_*Eg2_(2*i)+(1.-rho_)*std::pow(grad(i).real(),2);\n      Eg2_(2*i+1)=rho_*Eg2_(2*i+1)+(1.-rho_)*std::pow(grad(i).imag(),2);\n\n      Dx(2*i)=-std::sqrt(Edx2_(2*i)+epscut_)*grad(i).real();\n      Dx(2*i+1)=-std::sqrt(Edx2_(2*i+1)+epscut_)*grad(i).imag();\n      Dx(2*i)/=std::sqrt(Eg2_(2*i)+epscut_);\n      Dx(2*i+1)/=std::sqrt(Eg2_(2*i+1)+epscut_);\n\n      pars(i)+=Dx(2*i);\n      pars(i)+=I_*Dx(2*i+1);\n\n      Edx2_(2*i)=rho_*Edx2_(2*i)+(1.-rho_)*std::pow(Dx(2*i),2);\n      Edx2_(2*i+1)=rho_*Edx2_(2*i+1)+(1.-rho_)*std::pow(Dx(2*i+1),2);\n    }\n  }\n\n  void Reset() override {\n    Eg2_= Eigen::VectorXd::Zero(npar_);\n    Edx2_= Eigen::VectorXd::Zero(npar_);\n  }\n\n};\n\n}  // namespace netket\n\n#endif\n", "meta": {"hexsha": "fc9a0a7a9393f6e2cfa587ec2b543dd93c1a2dc7", "size": 3320, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "NetKet/Learning/ada_delta.hpp", "max_stars_repo_name": "artemborin/netket", "max_stars_repo_head_hexsha": "c7f26d52fdb66d2a8f9f94f2e2cfdc8b4ab41334", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "NetKet/Learning/ada_delta.hpp", "max_issues_repo_name": "artemborin/netket", "max_issues_repo_head_hexsha": "c7f26d52fdb66d2a8f9f94f2e2cfdc8b4ab41334", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "NetKet/Learning/ada_delta.hpp", "max_forks_repo_name": "artemborin/netket", "max_forks_repo_head_hexsha": "c7f26d52fdb66d2a8f9f94f2e2cfdc8b4ab41334", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.7364341085, "max_line_length": 78, "alphanum_fraction": 0.628313253, "num_tokens": 1065, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6548947290421275, "lm_q2_score": 0.5312093733737562, "lm_q1q2_score": 0.3478862186402444}}
{"text": "/*===================================================================\r\n\r\nThe Medical Imaging Interaction Toolkit (MITK)\r\n\r\nCopyright (c) German Cancer Research Center,\r\nDivision of Medical and Biological Informatics.\r\nAll rights reserved.\r\n\r\nThis software is distributed WITHOUT ANY WARRANTY; without\r\neven the implied warranty of MERCHANTABILITY or FITNESS FOR\r\nA PARTICULAR PURPOSE.\r\n\r\nSee LICENSE.txt or http://www.mitk.org for details.\r\n\r\n===================================================================*/\r\n\r\n#include \"mitkDiffusionFunctionCollection.h\"\r\n#include <math.h>\r\n#include \"mitkNumericTypes.h\"\r\n\r\n// for Windows\r\n#ifndef M_PI\r\n#define M_PI  3.14159265358979323846\r\n#endif\r\n\r\n// Namespace ::SH\r\n#include <boost/math/special_functions/legendre.hpp>\r\n#include <boost/math/special_functions/spherical_harmonic.hpp>\r\n#include <boost/version.hpp>\r\n\r\n\r\n// Namespace ::Gradients\r\n#include \"itkVectorContainer.h\"\r\n#include \"vnl/vnl_vector.h\"\r\n\r\n//------------------------- SH-function ------------------------------------\r\n\r\ndouble mitk::sh::factorial(int number) {\r\n  if(number <= 1) return 1;\r\n  double result = 1.0;\r\n  for(int i=1; i<=number; i++)\r\n    result *= i;\r\n  return result;\r\n}\r\n\r\nvoid mitk::sh::Cart2Sph(double x, double y, double z, double *cart)\r\n{\r\n  double phi, th, rad;\r\n  rad = sqrt(x*x+y*y+z*z);\r\n  if( rad < mitk::eps )\r\n  {\r\n    th = M_PI/2;\r\n    phi = M_PI/2;\r\n  }\r\n  else\r\n  {\r\n    th = acos(z/rad);\r\n    phi = atan2(y, x);\r\n  }\r\n  cart[0] = phi;\r\n  cart[1] = th;\r\n  cart[2] = rad;\r\n}\r\n\r\ndouble mitk::sh::legendre0(int l)\r\n{\r\n  if( l%2 != 0 )\r\n  {\r\n    return 0;\r\n  }\r\n  else\r\n  {\r\n    double prod1 = 1.0;\r\n    for(int i=1;i<l;i+=2) prod1 *= i;\r\n    double prod2 = 1.0;\r\n    for(int i=2;i<=l;i+=2) prod2 *= i;\r\n    return pow(-1.0,l/2.0)*(prod1/prod2);\r\n  }\r\n}\r\n\r\n\r\ndouble mitk::sh::Yj(int m, int l, double theta, double phi)\r\n{\r\n  if (m<0)\r\n    return sqrt(2.0)*::boost::math::spherical_harmonic_r(l, -m, theta, phi);\r\n  else if (m==0)\r\n    return ::boost::math::spherical_harmonic_r(l, m, theta, phi);\r\n  else\r\n    return pow(-1.0,m)*sqrt(2.0)*::boost::math::spherical_harmonic_i(l, m, theta, phi);\r\n\r\n  return 0;\r\n}\r\n\r\n\r\n\r\n//------------------------- gradients-function ------------------------------------\r\n\r\nstd::vector<unsigned int> mitk::gradients::GetAllUniqueDirections(const BValueMap & refBValueMap, GradientDirectionContainerType *refGradientsContainer )\r\n{\r\n\r\n  IndiciesVector directioncontainer;\r\n  auto mapIterator = refBValueMap.begin();\r\n\r\n  if(refBValueMap.find(0) != refBValueMap.end() && refBValueMap.size() > 1)\r\n    mapIterator++; //skip bzero Values\r\n\r\n  for( ; mapIterator != refBValueMap.end(); mapIterator++){\r\n\r\n    IndiciesVector currentShell = mapIterator->second;\r\n\r\n    while(currentShell.size()>0)\r\n    {\r\n      unsigned int wntIndex = currentShell.back();\r\n      currentShell.pop_back();\r\n\r\n      auto containerIt = directioncontainer.begin();\r\n      bool directionExist = false;\r\n      while(containerIt != directioncontainer.end())\r\n      {\r\n        if (fabs(dot(refGradientsContainer->ElementAt(*containerIt), refGradientsContainer->ElementAt(wntIndex)))  > 0.9998)\r\n        {\r\n          directionExist = true;\r\n          break;\r\n        }\r\n        containerIt++;\r\n      }\r\n      if(!directionExist)\r\n      {\r\n        directioncontainer.push_back(wntIndex);\r\n      }\r\n    }\r\n  }\r\n\r\n  return directioncontainer;\r\n}\r\n\r\n\r\nbool mitk::gradients::CheckForDifferingShellDirections(const BValueMap & refBValueMap, GradientDirectionContainerType::ConstPointer refGradientsContainer)\r\n{\r\n  auto mapIterator = refBValueMap.begin();\r\n\r\n  if(refBValueMap.find(0) != refBValueMap.end() && refBValueMap.size() > 1)\r\n    mapIterator++; //skip bzero Values\r\n\r\n  for( ; mapIterator != refBValueMap.end(); mapIterator++){\r\n\r\n    auto mapIterator_2 = refBValueMap.begin();\r\n    if(refBValueMap.find(0) != refBValueMap.end() && refBValueMap.size() > 1)\r\n      mapIterator_2++; //skip bzero Values\r\n\r\n    for( ; mapIterator_2 != refBValueMap.end(); mapIterator_2++){\r\n\r\n      if(mapIterator_2 == mapIterator) continue;\r\n\r\n      IndiciesVector currentShell = mapIterator->second;\r\n      IndiciesVector testShell = mapIterator_2->second;\r\n      for (unsigned int i = 0; i< currentShell.size(); i++)\r\n        if (fabs(dot(refGradientsContainer->ElementAt(currentShell[i]), refGradientsContainer->ElementAt(testShell[i])))  <= 0.9998) { return true; }\r\n\r\n    }\r\n  }\r\n  return false;\r\n}\r\n\r\n\r\ntemplate<typename type>\r\ndouble mitk::gradients::dot (vnl_vector_fixed< type ,3> const& v1, vnl_vector_fixed< type ,3 > const& v2 )\r\n{\r\n  double result = (v1[0] * v2[0] + v1[1] * v2[1] + v1[2] * v2[2]) / (v1.two_norm() * v2.two_norm());\r\n  return result ;\r\n}\r\n\r\nvnl_matrix<double> mitk::gradients::ComputeSphericalFromCartesian(const IndiciesVector & refShell, const GradientDirectionContainerType * refGradientsContainer)\r\n{\r\n\r\n  vnl_matrix<double> Q(3, refShell.size());\r\n  Q.fill(0.0);\r\n\r\n  for(unsigned int i = 0; i < refShell.size(); i++)\r\n  {\r\n    GradientDirectionType dir = refGradientsContainer->ElementAt(refShell[i]);\r\n    double x = dir.normalize().get(0);\r\n    double y = dir.normalize().get(1);\r\n    double z = dir.normalize().get(2);\r\n    double cart[3];\r\n    mitk::sh::Cart2Sph(x,y,z,cart);\r\n    Q(0,i) = cart[0];\r\n    Q(1,i) = cart[1];\r\n    Q(2,i) = cart[2];\r\n  }\r\n  return Q;\r\n}\r\n\r\nvnl_matrix<double> mitk::gradients::ComputeSphericalHarmonicsBasis(const vnl_matrix<double> & QBallReference, const unsigned int & LOrder)\r\n{\r\n  vnl_matrix<double> SHBasisOutput(QBallReference.cols(), (LOrder+1)*(LOrder+2)*0.5);\r\n  SHBasisOutput.fill(0.0);\r\n  for(int i=0; i< (int)SHBasisOutput.rows(); i++)\r\n    for(int k = 0; k <= (int)LOrder; k += 2)\r\n      for(int m =- k; m <= k; m++)\r\n      {\r\n        int j = ( k * k + k + 2 ) / 2.0 + m - 1;\r\n        double phi = QBallReference(0,i);\r\n        double th = QBallReference(1,i);\r\n        double val = mitk::sh::Yj(m,k,th,phi);\r\n        SHBasisOutput(i,j) = val;\r\n      }\r\n  return SHBasisOutput;\r\n}\r\n\r\nmitk::gradients::GradientDirectionContainerType::Pointer mitk::gradients::CreateNormalizedUniqueGradientDirectionContainer(const mitk::gradients::BValueMap & bValueMap,\r\n    const GradientDirectionContainerType *origninalGradentcontainer)\r\n{\r\n  mitk::gradients::GradientDirectionContainerType::Pointer directioncontainer = mitk::gradients::GradientDirectionContainerType::New();\r\n  auto mapIterator = bValueMap.begin();\r\n\r\n  if(bValueMap.find(0) != bValueMap.end() && bValueMap.size() > 1){\r\n    mapIterator++; //skip bzero Values\r\n    vnl_vector_fixed<double, 3> vec;\r\n    vec.fill(0.0);\r\n    directioncontainer->push_back(vec);\r\n  }\r\n\r\n  for( ; mapIterator != bValueMap.end(); mapIterator++){\r\n\r\n    IndiciesVector currentShell = mapIterator->second;\r\n\r\n    while(currentShell.size()>0)\r\n    {\r\n      unsigned int wntIndex = currentShell.back();\r\n      currentShell.pop_back();\r\n\r\n      mitk::gradients::GradientDirectionContainerType::Iterator containerIt = directioncontainer->Begin();\r\n      bool directionExist = false;\r\n      while(containerIt != directioncontainer->End())\r\n      {\r\n        if (fabs(dot(containerIt.Value(), origninalGradentcontainer->ElementAt(wntIndex)))  > 0.9998)\r\n        {\r\n          directionExist = true;\r\n          break;\r\n        }\r\n        containerIt++;\r\n      }\r\n      if(!directionExist)\r\n      {\r\n        GradientDirectionType dir(origninalGradentcontainer->ElementAt(wntIndex));\r\n        directioncontainer->push_back(dir.normalize());\r\n      }\r\n    }\r\n  }\r\n\r\n  return directioncontainer;\r\n}\r\n", "meta": {"hexsha": "5d880023721c72033cc2ae3ed709ba8261e7251d", "size": 7524, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Modules/DiffusionImaging/DiffusionCore/src/mitkDiffusionFunctionCollection.cpp", "max_stars_repo_name": "liu3xing3long/MITK-2016.11", "max_stars_repo_head_hexsha": "385c506f9792414f40337e106e13d5fd61aa3ccc", "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": "Modules/DiffusionImaging/DiffusionCore/src/mitkDiffusionFunctionCollection.cpp", "max_issues_repo_name": "liu3xing3long/MITK-2016.11", "max_issues_repo_head_hexsha": "385c506f9792414f40337e106e13d5fd61aa3ccc", "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": "Modules/DiffusionImaging/DiffusionCore/src/mitkDiffusionFunctionCollection.cpp", "max_forks_repo_name": "liu3xing3long/MITK-2016.11", "max_forks_repo_head_hexsha": "385c506f9792414f40337e106e13d5fd61aa3ccc", "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": 29.6220472441, "max_line_length": 169, "alphanum_fraction": 0.6197501329, "num_tokens": 2019, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6548947155710234, "lm_q2_score": 0.5312093733737563, "lm_q1q2_score": 0.3478862114842677}}
{"text": "#include \"utils.h\"\n\n#include <fstream>\n#include <iostream>\n#include <ctime>\n\n\n#include <boost/algorithm/string.hpp>\n#include <boost/format.hpp>\n\n\nauto random_engine = std::mt19937(std::time(0));\n\nvoid train_with_features(std::string data_file_path,\n                         std::string features_file_path,\n                         std::string noise_file_path,\n                         int n_steps, double eta_0, double iter_power,\n                         size_t l_dimensions, size_t k_dimensions,\n                         std::string output_file_path,\n                         std::string objective_output_file_path) {\n    // Data loading\n    std::fstream data_file_input;\n    data_file_input.open(data_file_path, std::ios::in);\n    std::string line;\n    std::vector<std::string> tokens;\n    getline(data_file_input, line);\n    boost::split(tokens, line, boost::is_any_of(\",\"));\n    size_t data_size = stoul(tokens[0]);\n    size_t n_samples = stoul(tokens[1]);\n\n    std::vector<size_t> start_indexes(n_samples);\n    std::vector<size_t> permutation(n_samples);\n    std::vector<int> data(data_size + n_samples);\n    long n_data = 0;\n    long n_noise = 0;\n    for (size_t i = 0, data_index = 0; i < n_samples; ++i) {\n        getline(data_file_input, line);\n        boost::split(tokens, line, boost::is_any_of(\",\"));\n        start_indexes[i] = data_index;\n        permutation[i] = i;\n        for (size_t j = 0; j < tokens.size(); ++j) {\n            data[data_index + j] = stoi(tokens[j]);\n        }\n        if (data[data_index] == 0) {\n            ++n_noise;\n        } else {\n            ++n_data;\n        }\n        data[data_index + tokens.size()] = -1;\n        data_index += tokens.size() + 1;\n    }\n\n    size_t n_items;\n    size_t m_features;\n    std::vector<double> features;\n    auto index_features = [&m_features](size_t i, size_t j) -> size_t {\n        return (i * m_features) + j;\n    };\n    masterthesis::readFeatureFile(\n            features_file_path, &n_items, &m_features, &features);\n\n    std::fstream noise_file_input;\n    noise_file_input.open(noise_file_path, std::ios::in);\n    getline(noise_file_input, line);\n    boost::split(tokens, line, boost::is_any_of(\",\"));\n    std::vector<double> a_weights(m_features);\n    for (size_t i = 0; i < m_features; ++i) {\n        a_weights[i] = stod(tokens[i]);\n    }\n    getline(noise_file_input, line);\n    boost::split(tokens, line, boost::is_any_of(\",\"));\n    std::vector<double> noise_utilities(n_items);\n    for (size_t i = 0; i < n_items; ++i) {\n        noise_utilities[i] = stod(tokens[i]);\n    }\n\n\n    // Calculate constant quantities.\n    double nu = n_noise / n_data;\n    double log_nu = log(nu);\n    double logz_noise = 0;\n    for (size_t i = 0; i < n_items; ++i) {\n        logz_noise += masterthesis::log1exp(noise_utilities[i]);\n    }\n\n    // Initialize parameters.\n    std::uniform_real_distribution<double_t> udouble_dist(0, 1e-3);\n    std::vector<double> b_weights(m_features * l_dimensions);\n    std::vector<double> c_weights(m_features * k_dimensions);\n    double n_logz = 0;\n\n    auto index_b_weights = [&l_dimensions](size_t i, size_t j) -> size_t {\n        return (i * l_dimensions) + j;\n    };\n\n    auto index_c_weights = [&k_dimensions](size_t i, size_t j) -> size_t {\n        return (i * k_dimensions) + j;\n    };\n\n    for (size_t i = 0; i < m_features; ++i) {\n        for (size_t j = 0; j < l_dimensions; ++j) {\n            b_weights[index_b_weights(i, j)] = udouble_dist(random_engine);\n        }\n        for (size_t j = 0; j < k_dimensions; ++j) {\n            c_weights[index_c_weights(i, j)] = udouble_dist(random_engine);\n        }\n    }\n    for (size_t i = 0; i < n_items; ++i) {\n        double item_util = 0;\n        for (size_t j = 0; j < m_features; ++j) {\n            item_util += a_weights[j] * features[index_features(i, j)];\n        }\n        n_logz -= masterthesis::log1exp(item_util);\n    }\n    std::cout << logz_noise << \" \" << n_logz << std::endl;\n\n    std::vector<double> a_gradient(m_features);\n    std::vector<double> objectives(n_steps);\n    for (size_t iter = 0; iter < n_steps; ++iter) {\n        double objective = 0;\n        for (size_t sub_iter = 0; sub_iter < n_samples; ++sub_iter) {\n            size_t start_idx = start_indexes[sub_iter];\n            size_t end_idx;\n            if (sub_iter == n_samples - 1) {\n                end_idx = data_size + n_samples - 1;\n            } else {\n                end_idx = start_indexes[sub_iter + 1] - 1;\n            }\n            int label = data[start_idx];\n            double p_model = n_logz;\n            double p_noise = -logz_noise;\n            for (size_t j = 0; j < m_features; ++j) {\n                for (size_t i = start_idx + 1; i < end_idx; ++i) {\n                    p_model += features[index_features(data[i], j)] *\n                               a_weights[j];\n                }\n            }\n            for (size_t i = start_idx + 1; i < end_idx; ++i) {\n                p_noise += noise_utilities[data[i]];\n            }\n            for (size_t j = 0; j < l_dimensions; ++j) {\n                double max_b_weight = -1;\n                for (size_t i = start_idx + 1; i < end_idx; ++i) {\n                    double weight = 0;\n                    for (size_t k = 0; k < m_features; ++k) {\n                        weight += features[index_features(data[i], k)] *\n                                  b_weights[index_b_weights(k, j)];\n                    }\n                    if (weight > max_b_weight) {\n                        max_b_weight = weight;\n                    }\n                    p_model -= weight;\n                }\n                if (max_b_weight >= 0) {\n                    p_model += max_b_weight;\n                }\n            }\n            for (size_t j = 0; j < k_dimensions; ++j) {\n                double max_c_weight = -1;\n                for (size_t i = start_idx + 1; i < end_idx; ++i) {\n                    double weight = 0;\n                    for (size_t k = 0; k < m_features; ++k) {\n                        weight += features[index_features(data[i], k)] *\n                                  c_weights[index_c_weights(k, j)];\n                    }\n                    if (weight > max_c_weight) {\n                        max_c_weight = weight;\n                    }\n                    p_model += weight;\n                }\n                if (max_c_weight >= 0) {\n                    p_model -= max_c_weight;\n                }\n            }\n            if (label == 1) {\n                objective -= masterthesis::log1exp(log_nu + p_noise - p_model);\n            } else {\n                objective -= masterthesis::log1exp(p_model - log_nu - p_noise);\n            }\n        }\n        std::cout << objective << std::endl;\n        objectives[iter] = objective;\n        shuffle(begin(permutation), end(permutation), random_engine);\n        for (size_t sub_iter = 0; sub_iter < n_samples; ++sub_iter) {\n            size_t start_idx = start_indexes[permutation[sub_iter]];\n            size_t end_idx;\n            if (permutation[sub_iter] == n_samples - 1) {\n                end_idx = data_size + n_samples - 1;\n            } else {\n                end_idx = start_indexes[permutation[sub_iter] + 1] - 1;\n            }\n            bool isEmpty = (start_idx == end_idx - 1);\n            int label = data[start_idx];\n            double p_model = n_logz;\n            double p_noise = -logz_noise;\n            for (size_t j = 0; j < m_features; ++j) {\n                a_gradient[j] = 0;\n                for (size_t i = start_idx + 1; i < end_idx; ++i) {\n                    a_gradient[j] += features[index_features(data[i], j)];\n                    p_model += features[index_features(data[i], j)] *\n                               a_weights[j];\n                }\n            }\n            for (size_t i = start_idx + 1; i < end_idx; ++i) {\n                p_noise += noise_utilities[data[i]];\n            }\n\n\n            std::vector<double> max_b_weights(l_dimensions);\n            std::vector<int> max_weight_b_indexes(l_dimensions);\n            std::vector<double> max_c_weights(k_dimensions);\n            std::vector<int> max_weight_c_indexes(k_dimensions);\n            if (!isEmpty) {\n                for (size_t j = 0; j < l_dimensions; ++j) {\n                    max_b_weights[j] = -1;\n                    max_weight_b_indexes[j] = -1;\n                    for (size_t i = start_idx + 1; i < end_idx; ++i) {\n                        double weight = 0;\n                        for (size_t k = 0; k < m_features; ++k) {\n                            weight += features[index_features(data[i], k)] *\n                                      b_weights[index_b_weights(k, j)];\n                        }\n                        if (weight > max_b_weights[j]) {\n                            max_b_weights[j] = weight;\n                            max_weight_b_indexes[j] = data[i];\n                        }\n                        p_model -= weight;\n                    }\n                    p_model += max_b_weights[j];\n                }\n\n                for (size_t j = 0; j < k_dimensions; ++j) {\n                    max_c_weights[j] = -1;\n                    max_weight_c_indexes[j] = -1;\n                    for (size_t i = start_idx + 1; i < end_idx; ++i) {\n                        double weight = 0;\n                        for (size_t k = 0; k < m_features; ++k) {\n                            weight += features[index_features(data[i], k)] *\n                                      c_weights[index_c_weights(k, j)];\n                        }\n                        if (weight > max_c_weights[j]) {\n                            max_c_weights[j] = weight;\n                            max_weight_c_indexes[j] = data[i];\n                        }\n                        p_model += weight;\n                    }\n                    p_model -= max_c_weights[j];\n                }\n            }\n\n            double learning_rate = eta_0 *\n                                   pow((iter * n_samples) + sub_iter + 1, -iter_power);\n            double factor = learning_rate *\n                            (label - masterthesis::expit(p_model - p_noise - log_nu));\n            if (!isEmpty) {\n                for (size_t i = 0; i < m_features; ++i) {\n                    a_weights[i] += factor * a_gradient[i];\n                    for (size_t j = 0; j < l_dimensions; ++j) {\n                        b_weights[index_b_weights(i, j)] += factor *\n                                                            (features[index_features(\n                                                                    max_weight_b_indexes[j],\n                                                                    i)] -\n                                                             a_gradient[i]);\n                        if (b_weights[index_b_weights(i, j)] <= 0) {\n                            b_weights[index_b_weights(i, j)] = udouble_dist(random_engine);\n                        }\n                    }\n                    for (size_t j = 0; j < k_dimensions; ++j) {\n                        c_weights[index_c_weights(i, j)] += factor *\n                                                            (a_gradient[i] -\n                                                             features[index_features(\n                                                                     max_weight_c_indexes[j],\n                                                                     i)]);\n                        if (c_weights[index_c_weights(i, j)] <= 0) {\n                            c_weights[index_c_weights(i, j)] = udouble_dist(random_engine);\n                        }\n                    }\n                }\n            }\n            n_logz += factor;\n        }\n    }\n\n    std::fstream output_file(output_file_path, std::ios::out);\n\n    output_file << n_logz << std::endl;\n    for (size_t i = 0; i < m_features - 1; ++i) {\n        output_file << a_weights[i] << \",\";\n    }\n    output_file << a_weights[m_features - 1] << std::endl;\n\n    for (size_t i = 0; i < m_features; ++i) {\n        if (l_dimensions > 0) {\n            for (size_t j = 0; j < l_dimensions - 1; ++j) {\n                output_file << b_weights[index_b_weights(i, j)] << \",\";\n            }\n            output_file << b_weights[index_b_weights(i, l_dimensions - 1)] << std::endl;\n        }\n    }\n\n    for (size_t i = 0; i < m_features; ++i) {\n        if (k_dimensions > 0) {\n            for (size_t j = 0; j < k_dimensions - 1; ++j) {\n                output_file << c_weights[index_c_weights(i, j)] << \",\";\n            }\n            output_file << c_weights[index_c_weights(i, k_dimensions - 1)] << std::endl;\n        }\n    }\n\n    output_file.close();\n\n    std::fstream objective_output_file(\n            objective_output_file_path, std::ios::out);\n\n    for (size_t i = 0; i < n_steps; ++i) {\n        objective_output_file << objectives[i] << std::endl;\n    }\n\n    objective_output_file.close();\n}\n\nint main(int argc, char* argv[]) {\n    int fold_number = std::stoi(argv[1]);\n    int l_dimensions = std::stoi(argv[2]);\n    int k_dimensions = std::stoi(argv[3]);\n    char* feature_set = argv[4];\n    char* dataset_name = argv[5];\n    int iterations = std::stoi(argv[6]);\n    std::vector<double> times(fold_number);\n    for (int i = 1; i <= fold_number; ++i) {\n        time_t start = time(0);\n        train_with_features(\n                (boost::format(\n                        \"/home/diegob/workspace/master-thesis-2015/data/path_set_%1%_nce_data_features_%2%_fold_%3%.csv\") %\n                 dataset_name % feature_set % i).str(),\n                (boost::format(\n                        \"/home/diegob/workspace/master-thesis-2015/data/path_set_%1%_nce_features_%2%.csv\") %\n                 dataset_name % feature_set).str(),\n                (boost::format(\n                        \"/home/diegob/workspace/master-thesis-2015/data/path_set_%1%_nce_noise_features_%2%_fold_%3%.csv\") %\n                 dataset_name % feature_set % i).str(),\n                iterations, 0.00005, 0.1,\n                static_cast<size_t>(l_dimensions),\n                static_cast<size_t>(k_dimensions),\n                (boost::format(\n                        \"/home/diegob/workspace/master-thesis-2015/data/models/path_set_%1%_nce_out_features_%2%_l_dim_%3%_k_dim_%4%_fold_%5%.csv\") %\n                 dataset_name % feature_set % l_dimensions % k_dimensions % i).str(),\n                (boost::format(\n                        \"/home/diegob/workspace/master-thesis-2015/data/models/path_set_%1%_nce_objective_features_%2%_l_dim_%3%_k_dim_%4%_fold_%5%.csv\") %\n                 dataset_name % feature_set % l_dimensions % k_dimensions % i).str()\n        );\n        time_t end = time(0);\n        double time = std::difftime(end, start);\n        times[i-1] = time;\n        std::cout << \"Fold finished.\" << std::endl;\n        std::cout << \"Fold took: \" << times[i-1] << \"s\" << std::endl;\n    }\n    std::fstream times_output_file(\n            (boost::format(\n                    \"/home/diegob/workspace/master-thesis-2015/data/models/path_set_%1%_nce_timing_features_%2%_l_dim_%3%_k_dim_%4%.csv\") %\n             dataset_name % feature_set % l_dimensions % k_dimensions).str(),\n            std::ios::out);\n\n    for (size_t i = 0; i < fold_number; ++i) {\n        times_output_file << times[i] << std::endl;\n    }\n    times_output_file.close();\n}\n", "meta": {"hexsha": "c640f0acbc9703e533f4f40921b30c5b1f3eee77", "size": 15310, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cppsrc/train_general.cpp", "max_stars_repo_name": "dballesteros7/master-thesis-2015", "max_stars_repo_head_hexsha": "8c0bf9a6eef172fc8167a30780ae0666f8ea2d88", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cppsrc/train_general.cpp", "max_issues_repo_name": "dballesteros7/master-thesis-2015", "max_issues_repo_head_hexsha": "8c0bf9a6eef172fc8167a30780ae0666f8ea2d88", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cppsrc/train_general.cpp", "max_forks_repo_name": "dballesteros7/master-thesis-2015", "max_forks_repo_head_hexsha": "8c0bf9a6eef172fc8167a30780ae0666f8ea2d88", "max_forks_repo_licenses": ["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.4905149051, "max_line_length": 155, "alphanum_fraction": 0.4830176355, "num_tokens": 3587, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6548947155710234, "lm_q2_score": 0.5312093733737563, "lm_q1q2_score": 0.3478862114842677}}
{"text": "/*\n * lorenz_multi.cpp\n * Date: 2016-02-26\n * Author: Karsten Ahnert (karsten.ahnert@gmx.de)\n * Copyright: Karsten Ahnert\n *\n * Distributed under the Boost Software License, Version 1.0.\n * (See accompanying file LICENSE_1_0.txt or\n * copy at http://www.boost.org/LICENSE_1_0.txt)\n */\n\n#include \"generate_data.hpp\"\n#include \"tree_types.hpp\"\n#include \"program_options.hpp\"\n#include \"serialize.hpp\"\n\n#include <gpcxx/app.hpp>\n#include <gpcxx/eval.hpp>\n#include <gpcxx/evolve.hpp>\n#include <gpcxx/tree.hpp>\n#include <gpcxx/intrusive_nodes.hpp>\n#include <gpcxx/operator.hpp>\n#include <gpcxx/stat.hpp>\n#include <gpcxx/generate.hpp>\n#include <gpcxx/io.hpp>\n\n#include <boost/program_options.hpp>\n\n#include <iostream>\n\nnamespace po = boost::program_options;\n\n\nint main( int argc , char** argv )\n{\n    auto options = dynsys::get_options();\n    auto positional_options = dynsys::get_positional_options();\n    \n    po::options_description cmdline_options;\n    cmdline_options.add( options ).add( positional_options.second );\n    \n    po::variables_map vm;\n    try\n    {\n        po::store( po::command_line_parser( argc , argv ).options( cmdline_options ).positional( positional_options.first ).run() , vm );\n        po::notify( vm );\n    }\n    catch( std::exception& e )\n    {\n        std::cerr << \"Error \" << e.what() << \"\\n\\n\";\n        std::cerr << cmdline_options << \"\\n\";\n        return -1;\n    }\n    \n    dynsys::rng_type rng;\n    \n    \n    //[ create_lorenz_data\n    auto training_data = dynsys::generate_data();\n    \n    std::array< std::pair< double , double > , dynsys::dim > xstat , ystat;\n    for( size_t i=0 ; i<dynsys::dim ; ++i )\n    {\n        xstat[i].first = ystat[i].first = 0.0;\n        xstat[i].second = ystat[i].second = 1.0;\n    }\n    if( vm.count( \"normalize\" ) )\n    {\n        xstat = dynsys::normalize_data( training_data.first );\n        ystat = dynsys::normalize_data( training_data.second );\n    }\n    // plot_data( training_data );\n    //]\n    \n    //[ lorenz_define_node_generator\n    auto node_generator = dynsys::create_node_generator();\n    //]\n    \n    \n    //[ define_gp_parameters\n//     size_t population_size = 256 ;\n//     size_t generation_size = 20;\n    size_t population_size = 512 * 32;\n    size_t generation_size = 2000;\n    \n    size_t number_elite = 1;\n    double mutation_rate = 0.2;\n    double crossover_rate = 0.6;\n    double reproduction_rate = 0.3;\n    size_t min_tree_height = 1 , max_tree_height = 8;\n    size_t tournament_size = 15;\n    //]\n    \n    \n    //[ define_population_and_fitness\n    using population_type = std::vector< dynsys::individual_type >;\n    using fitness_type = std::vector< double >;\n    \n    fitness_type fitness ( population_size , 0.0 );\n    population_type population ( population_size );\n    //]\n    \n    \n    //[ define_evolution\n    using evolver_type = gpcxx::dynamic_pipeline< population_type , fitness_type , dynsys::rng_type >;\n    evolver_type evolver( rng , number_elite );\n    //]\n    \n    //[define_evaluator\n    \n    auto evaluator = []( auto const& individual , auto const& context ) {\n        return dynsys::state_type {{\n            individual[0].root()->eval( context ) ,\n            individual[1].root()->eval( context ) ,\n            individual[2].root()->eval( context ) }}; };\n    \n    auto distance = []( auto const& y , auto const& ytrain ) {\n        const double weight_x = 1.0;\n        const double weight_y = 1.0;\n        const double weight_z = 1.0;\n        dynsys::state_type diff {{ y[0] - ytrain[0] , y[1] - ytrain[1] , y[2] - ytrain[2] }};\n        return weight_x * diff[0] * diff[0] + weight_y * diff[1] * diff[1] + weight_z * diff[2] * diff[2]; };\n    //]\n                \n    //[define_genetic_operators\n    auto tree_generator = gpcxx::make_ramp( rng , node_generator , min_tree_height , max_tree_height , 0.5 );\n    auto fitness_f1 = gpcxx::make_multi_regression_fitness( evaluator , distance );\n    auto fitness_f = [ fitness_f1 ]( auto const& individual , auto const& x , auto const& y ) {\n        return fitness_f1.get_chi2( individual , x , y ); };\n    evolver.add_operator(\n        gpcxx::make_multi_mutation(\n            rng , \n            gpcxx::make_point_mutation( rng , tree_generator , max_tree_height , 20 ) ,\n            gpcxx::make_tournament_selector( rng , tournament_size )\n        ) , mutation_rate );\n    evolver.add_operator(\n        gpcxx::make_multi_crossover(\n            rng ,\n            gpcxx::make_one_point_crossover_strategy( rng , 10 ) ,\n            gpcxx::make_tournament_selector( rng , tournament_size )\n        ) , crossover_rate );\n    evolver.add_operator(\n        gpcxx::make_reproduce(\n            gpcxx::make_tournament_selector( rng , tournament_size )\n        ) , reproduction_rate );\n    //]\n                    \n                    \n                    \n    //[init_population\n    std::ofstream fout { vm[ \"evolution\" ].as< std::string >() };\n    for( size_t i=0 ; i<population.size() ; )\n    {\n        for( size_t j=0 ; j<dynsys::dim ; ++j )\n        {\n            population[i][j].clear();\n            tree_generator( population[i][j] );\n        }\n        fitness[i] = fitness_f( population[i] , training_data.first , training_data.second );\n        if( ! dynsys::is_number( fitness[i] ) )\n        {\n            continue;\n        }\n        ++i;\n    }\n    \n    std::cout << \"Initial population\" << std::endl;\n    dynsys::write_best_individuals( std::cout , population , fitness , 10 );\n    dynsys::write_best_individuals( fout , population , fitness , 10 , true );\n    //]\n    \n    //[main_loop\n    for( size_t i=0 ; i<generation_size ; ++i )\n    {\n        evolver.next_generation( population , fitness );\n        for( size_t i=0 ; i<population.size() ; ++i )\n            fitness[i] = fitness_f( population[i] , training_data.first , training_data.second );\n        \n        std::cout << \"Iteration \" << i << std::endl;\n        dynsys::write_best_individuals( std::cout , population , fitness , 10 );\n        dynsys::write_best_individuals( fout , population , fitness , 10 , true );\n        \n        auto min_fitness = * ( std::min_element( fitness.begin() , fitness.end() ) );\n        if( std::abs( min_fitness ) < 1.0e-7 )\n        {\n            std::cout << \"Minimal fitness is small then 1.0e-7. Stopping now.\" << std::endl << std::endl << std::endl << std::endl;\n            fout << \"Minimal fitness is small then 1.0e-7. Stopping now.\" << std::endl << std::endl << std::endl << std::endl;\n            break;\n        }\n    }\n    //]\n\n    std::ofstream fout2 { vm[ \"result\" ].as< std::string >() };\n    fout2.precision( 14 );\n    for( size_t j=0 ; j<dynsys::dim ; ++j )\n        fout2 << xstat[j].first << \" \" << xstat[j].second << \" \" << ystat[j].first << \" \" << ystat[j].second << \"\\n\";\n    fout2 << std::endl << std::endl;\n    dynsys::write_best_individuals( fout2 , population , fitness , 10 , true );\n    \n    \n    std::vector< size_t > idx;\n    gpcxx::sort_indices( fitness , idx );\n    std::ofstream winner_out { vm[ \"winner\" ].as< std::string >() };\n    winner_out << dynsys::serialize_winner( population[ idx[0] ] , xstat , ystat ) << \"\\n\";\n    \n\n    return 0;\n}", "meta": {"hexsha": "f7afff937755f699e77c198fdc07bcc48a6130b4", "size": 7118, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/dynamical_system/lorenz_multi.cpp", "max_stars_repo_name": "gchoinka/gpcxx", "max_stars_repo_head_hexsha": "143398d8a12cdc39735e6ef50c3f8a44a6e6360f", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 21.0, "max_stars_repo_stars_event_min_datetime": "2015-05-15T08:01:37.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-12T07:28:54.000Z", "max_issues_repo_path": "examples/dynamical_system/lorenz_multi.cpp", "max_issues_repo_name": "gchoinka/gpcxx", "max_issues_repo_head_hexsha": "143398d8a12cdc39735e6ef50c3f8a44a6e6360f", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2015-03-26T23:48:04.000Z", "max_issues_repo_issues_event_max_datetime": "2016-02-29T14:16:37.000Z", "max_forks_repo_path": "examples/dynamical_system/lorenz_multi.cpp", "max_forks_repo_name": "gchoinka/gpcxx", "max_forks_repo_head_hexsha": "143398d8a12cdc39735e6ef50c3f8a44a6e6360f", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2015-02-12T21:39:01.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-01T05:14:08.000Z", "avg_line_length": 34.2211538462, "max_line_length": 137, "alphanum_fraction": 0.5931441416, "num_tokens": 1910, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6548947155710233, "lm_q2_score": 0.5312093733737563, "lm_q1q2_score": 0.3478862114842676}}
{"text": "// smooth_feedback: Control theory on Lie groups\n// https://github.com/pettni/smooth_feedback\n//\n// Licensed under the MIT License <http://opensource.org/licenses/MIT>.\n//\n// Copyright (c) 2021 Petter Nilsson, John B. Mains\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in all\n// copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n// SOFTWARE.\n\n#ifndef BENCHMARK__BENCH_TYPES_HPP_\n#define BENCHMARK__BENCH_TYPES_HPP_\n\n#include <Eigen/Core>\n#include <Eigen/Sparse>\n\n#include <smooth/feedback/qp.hpp>\n\n#include <chrono>\n#include <fstream>\n#include <iostream>\n#include <random>\n\n/**\n * @brief Create a random quadratic program of dimension m x n.\n * @param m number on inequalities\n * @param n number of variables\n * @param density approximate proportion of nonzeros in P and A\n * @param RNG random number generator\n */\ntemplate<typename RNG>\nsmooth::feedback::QuadraticProgram<-1, -1> random_qp(int m, int n, double density, RNG & rng)\n{\n  std::bernoulli_distribution bdist(density);\n  std::uniform_real_distribution<double> udist(-1, 1);\n\n  Eigen::MatrixXd A =\n    Eigen::MatrixXd::NullaryExpr(m, n, [&](int, int) { return bdist(rng) ? udist(rng) : 0.; });\n  Eigen::MatrixXd Lrand =\n    Eigen::MatrixXd::NullaryExpr(n, n, [&](int, int) { return bdist(rng) ? udist(rng) : 0.; });\n  Eigen::MatrixXd L                         = Eigen::MatrixXd::Zero(n, n);\n  L.template triangularView<Eigen::Lower>() = Lrand.template triangularView<Eigen::Lower>();\n  for (int i = 0; i < n; ++i) { L(i, i) = std::max({L(i, i), -L(i, i), 0.05}); }\n\n  Eigen::VectorXd v     = Eigen::VectorXd::NullaryExpr(n, [&](int) { return udist(rng); });\n  Eigen::VectorXd delta = Eigen::VectorXd::NullaryExpr(m, [&](int) { return udist(rng); });\n\n  return smooth::feedback::QuadraticProgram<-1, -1>{\n    .P = L * L.transpose(),\n    .q = Eigen::VectorXd::NullaryExpr(n, [&](int) { return udist(rng); }),\n    .A = A,\n    .l = Eigen::VectorXd::Constant(m, -std::numeric_limits<double>::infinity()),\n    .u = A * v + delta,\n  };\n}\n\n/**\n * @brief Create a random sparse quadratic program of dimension m x n.\n */\ninline smooth::feedback::QuadraticProgramSparse<double>\nqp_dense_to_sparse(const smooth::feedback::QuadraticProgram<-1, -1, double> & qp)\n{\n  smooth::feedback::QuadraticProgramSparse<double> qps;\n\n  qps.P = qp.P.sparseView();\n  qps.P.prune(1e-6);\n  qps.P.makeCompressed();\n  qps.q = qp.q;\n  qps.A = qp.A.sparseView();\n  qps.A.prune(1e-6);\n  qps.A.makeCompressed();\n  qps.l = qp.l;\n  qps.u = qp.u;\n\n  return qps;\n}\n\nstruct BenchResult\n{\n  smooth::feedback::QPSolutionStatus status;\n  std::chrono::high_resolution_clock::duration dt;\n  uint64_t iter;\n  Eigen::VectorXd solution;\n  double objective;\n};\n\nstruct BatchResult\n{\n  std::vector<BenchResult> results{};\n\n  std::size_t num_optimal{0};\n\n  double total_duration_success{0};\n  double total_duration_fail{0};\n\n  double avg_duration_success{0};\n  double avg_duration_fail{0};\n};\n\ntemplate<typename SolverWrapper, std::ranges::range R>\nBatchResult solve_batch(const R & qps, const smooth::feedback::QPSolverParams & prm)\n{\n  auto work_range =\n    std::views::transform(qps, [&prm](const auto & qp) { return SolverWrapper(qp, prm); });\n\n  BatchResult ret{};\n\n  for (const auto & work : work_range) { ret.results.push_back(work()); }\n\n  // calculate accuracies\n  for (const auto & result : ret.results) {\n    if (result.status == smooth::feedback::QPSolutionStatus::Optimal) {\n      ++ret.num_optimal;\n      ret.total_duration_success += std::chrono::duration<double>(result.dt).count();\n    } else {\n      ret.total_duration_fail += std::chrono::duration<double>(result.dt).count();\n    }\n  }\n\n  std::size_t num_fail = ret.results.size() - ret.num_optimal;\n\n  ret.avg_duration_success =\n    ret.num_optimal > 0 ? ret.total_duration_success / ret.num_optimal : -1;\n  ret.avg_duration_fail = num_fail > 0 ? ret.total_duration_fail / num_fail : -1;\n\n  return ret;\n}\n\n#endif  // BENCHMARK__BENCH_TYPES_HPP_\n", "meta": {"hexsha": "c45da2f65796fc13aac4dfea29ccdb1163da99b1", "size": 4880, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "benchmarks/bench_types.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": "benchmarks/bench_types.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": "benchmarks/bench_types.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": 33.6551724138, "max_line_length": 95, "alphanum_fraction": 0.6989754098, "num_tokens": 1270, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6187804478040616, "lm_q2_score": 0.5621765008857981, "lm_q1q2_score": 0.3478638269630346}}
{"text": "///////////////////////////////////////////////////////////////////////////////\n// BSD 3-Clause License\n//\n// Copyright (C) 2019-2021, 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_ACTUATION_BASE_HPP_\n#define CROCODDYL_CORE_ACTUATION_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/mathbase.hpp\"\n#include \"crocoddyl/core/state-base.hpp\"\n#include \"crocoddyl/core/utils/exception.hpp\"\n\nnamespace crocoddyl {\n\n/**\n * @brief Abstract class for the actuation-mapping model\n *\n * The generalized torques \\f$\\boldsymbol{\\tau}\\in\\mathbb{R}^{nv}\\f$ can by any nonlinear function of the\n * control inputs \\f$\\mathbf{u}\\in\\mathbb{R}^{nu}\\f$, and state point \\f$\\mathbf{x}\\in\\mathbb{R}^{nx}\\f$, where\n * `nv`, `nu`, and `ndx` are the number of joints, dimension of the control input and state manifold,\n * respectively. Additionally, the generalized torques are also named as the actuation signals of our system.\n *\n * The main computations are carrying out in `calc()`, and `calcDiff()`, where the former computes actuation signal,\n * and the latter computes the Jacobians of the actuation-mapping function, i.e.,\n * \\f$\\frac{\\partial\\boldsymbol{\\tau}}{\\partial\\mathbf{x}}\\f$ and\n * \\f$\\frac{\\partial\\boldsymbol{\\tau}}{\\partial\\mathbf{u}}\\f$. Note that `calcDiff()` requires to run `calc()` first.\n *\n * \\sa `calc()`, `calcDiff()`, `createData()`\n */\ntemplate <typename _Scalar>\nclass ActuationModelAbstractTpl {\n public:\n  EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n\n  typedef _Scalar Scalar;\n  typedef MathBaseTpl<Scalar> MathBase;\n  typedef StateAbstractTpl<Scalar> StateAbstract;\n  typedef ActuationDataAbstractTpl<Scalar> ActuationDataAbstract;\n  typedef typename MathBase::VectorXs VectorXs;\n  typedef typename MathBase::MatrixXs MatrixXs;\n\n  /**\n   * @brief Initialize the actuation model\n   *\n   * @param[in] state  State description\n   * @param[in] nu     Dimension of control vector\n   */\n  ActuationModelAbstractTpl(boost::shared_ptr<StateAbstract> state, const std::size_t nu);\n  virtual ~ActuationModelAbstractTpl();\n\n  /**\n   * @brief Compute the actuation signal from the state point \\f$\\mathbf{x}\\in\\mathbb{R}^{ndx}\\f$ and control input\n   * \\f$\\mathbf{u}\\in\\mathbb{R}^{nu}\\f$\n   *\n   * @param[in] data  Actuation data\n   * @param[in] x     State point \\f$\\mathbf{x}\\in\\mathbb{R}^{ndx}\\f$\n   * @param[in] u     Control input \\f$\\mathbf{u}\\in\\mathbb{R}^{nu}\\f$\n   */\n  virtual void calc(const boost::shared_ptr<ActuationDataAbstract>& data, const Eigen::Ref<const VectorXs>& x,\n                    const Eigen::Ref<const VectorXs>& u) = 0;\n\n  /**\n   * @brief Ignore the computation of the actuation signal\n   *\n   * It does not update the actuation signal as this function is used in the terminal nodes of an optimal\n   * control problem.\n   *\n   * @param[in] data  Actuation data\n   * @param[in] x     State point \\f$\\mathbf{x}\\in\\mathbb{R}^{ndx}\\f$\n   */\n  void calc(const boost::shared_ptr<ActuationDataAbstract>& data, const Eigen::Ref<const VectorXs>& x);\n\n  /**\n   * @brief Compute the Jacobians of the actuation function\n   *\n   * @param[in] data  Actuation data\n   * @param[in] x     State point \\f$\\mathbf{x}\\in\\mathbb{R}^{ndx}\\f$\n   * @param[in] u     Control input \\f$\\mathbf{u}\\in\\mathbb{R}^{nu}\\f$\n   */\n  virtual void calcDiff(const boost::shared_ptr<ActuationDataAbstract>& data, const Eigen::Ref<const VectorXs>& x,\n                        const Eigen::Ref<const VectorXs>& u) = 0;\n\n  /**\n   * @brief Ignore the computation of the Jacobians of the actuation function\n   *\n   * It does not update the Jacobians of the actuation function as this function is used in the terminal\n   * nodes of an optimal control problem.\n   *\n   * @param[in] data  Actuation data\n   * @param[in] x     State point \\f$\\mathbf{x}\\in\\mathbb{R}^{ndx}\\f$\n   */\n  void calcDiff(const boost::shared_ptr<ActuationDataAbstract>& data, const Eigen::Ref<const VectorXs>& x);\n\n  /**\n   * @brief Create the actuation data\n   *\n   * @return the actuation data\n   */\n  virtual boost::shared_ptr<ActuationDataAbstract> createData();\n\n  /**\n   * @brief Return the dimension of the control input\n   */\n  std::size_t get_nu() const;\n\n  /**\n   * @brief Return the state\n   */\n  const boost::shared_ptr<StateAbstract>& get_state() const;\n\n  /**\n   * @brief Print information on the residual model\n   */\n  template <class Scalar>\n  friend std::ostream& operator<<(std::ostream& os, const ResidualModelAbstractTpl<Scalar>& model);\n\n  /**\n   * @brief Print relevant information of the residual model\n   *\n   * @param[out] os  Output stream object\n   */\n  virtual void print(std::ostream& os) const;\n\n protected:\n  std::size_t nu_;                          //!< Control dimension\n  boost::shared_ptr<StateAbstract> state_;  //!< Model of the state\n};\n\ntemplate <typename _Scalar>\nstruct ActuationDataAbstractTpl {\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 ActuationDataAbstractTpl(Model<Scalar>* const model)\n      : tau(model->get_state()->get_nv()),\n        dtau_dx(model->get_state()->get_nv(), model->get_state()->get_ndx()),\n        dtau_du(model->get_state()->get_nv(), model->get_nu()) {\n    tau.setZero();\n    dtau_dx.setZero();\n    dtau_du.setZero();\n  }\n  virtual ~ActuationDataAbstractTpl() {}\n\n  VectorXs tau;      //!< Actuation (generalized force) signal\n  MatrixXs dtau_dx;  //!< Partial derivatives of the actuation model w.r.t. the state point\n  MatrixXs dtau_du;  //!< Partial derivatives of the actuation model w.r.t. the control input\n};\n\n}  // namespace crocoddyl\n\n/* --- Details -------------------------------------------------------------- */\n/* --- Details -------------------------------------------------------------- */\n/* --- Details -------------------------------------------------------------- */\n#include \"crocoddyl/core/actuation-base.hxx\"\n\n#endif  // CROCODDYL_CORE_ACTUATION_BASE_HPP_\n", "meta": {"hexsha": "e7290b98a50ba4088c3ee1b95747f9218d8042a8", "size": 6300, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/crocoddyl/core/actuation-base.hpp", "max_stars_repo_name": "spykspeigel/crocoddyl", "max_stars_repo_head_hexsha": "0500e398861564b6986d99206a1e0ccec0d66a33", "max_stars_repo_licenses": ["BSD-3-Clause"], "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/actuation-base.hpp", "max_issues_repo_name": "spykspeigel/crocoddyl", "max_issues_repo_head_hexsha": "0500e398861564b6986d99206a1e0ccec0d66a33", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_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/actuation-base.hpp", "max_forks_repo_name": "spykspeigel/crocoddyl", "max_forks_repo_head_hexsha": "0500e398861564b6986d99206a1e0ccec0d66a33", "max_forks_repo_licenses": ["BSD-3-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.0588235294, "max_line_length": 117, "alphanum_fraction": 0.6546031746, "num_tokens": 1643, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6187804478040616, "lm_q2_score": 0.5621765008857981, "lm_q1q2_score": 0.3478638269630346}}
{"text": "/*  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 in the LICENSE file.\n */\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\n\nnamespace dai {\n\n\nusing namespace std;\n\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(), 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\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\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(); 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(); 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\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,\"Variable with label \" + boost::lexical_cast<string>(labels[mi]) + \" 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( 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 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\n\nVarSet FactorGraph::Delta( size_t i ) const {\n    // calculate Markov Blanket\n    VarSet Del;\n    for( const Neighbor &I : nbV(i) ) // for all neighboring factors I of i\n        for( const Neighbor &j : nbF(I) ) // for all neighboring variables j of I\n            Del |= var(j);\n\n    return Del;\n}\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\n\nSmallSet<size_t> FactorGraph::Deltai( size_t i ) const {\n    // calculate Markov Blanket\n    SmallSet<size_t> Del;\n    for( const Neighbor &I : nbV(i) ) // for all neighboring factors I of i\n        for( const Neighbor &j : nbF(I) ) // for all neighboring variables j of I\n            Del |= j;\n\n    return Del;\n}\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    for( 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\n\nvoid FactorGraph::makeRegionCavity( std::vector<size_t> facInds, bool backup ) {\n    map<size_t,Factor> newFacs;\n    for( size_t I = 0; I < facInds.size(); I++ )\n        newFacs[facInds[I]] = Factor(factor(facInds[I]).vars(), (Real)1);\n    setFactors( newFacs, backup );\n}\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,\"Cannot read from file \" + std::string(filename));\n}\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,\"Cannot write to file \" + std::string(filename));\n}\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        for( const Neighbor &I : nbV(i) )  // for all neighboring factors I of i\n            os << \"\\tv\" << var(i).label() << \" -- f\" << I << \";\" << endl;\n    os << \"}\" << endl;\n}\n\n\nGraphAL FactorGraph::MarkovGraph() const {\n    GraphAL G( nrVars() );\n    for( size_t i = 0; i < nrVars(); i++ )\n        for( const Neighbor &I : nbV(i) )\n            for( const Neighbor &j : nbF(I) )\n                if( i < j )\n                    G.addEdge( i, j, true );\n    return G;\n}\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        for( const Neighbor& i : nbF(I) ) {\n            for( const Neighbor& J : nbV(i) ) {\n                if( J != I )\n                    if( (factor(J).vars() >> I_vars) && (factor(J).vars().size() != I_size) )\n                        return false;\n            }\n        }\n        return true;\n    }\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        for( const Neighbor& i : nbF(I) ) {\n            for( const Neighbor& J : nbV(i) ) {\n                if( J != I )\n                    if( (factor(J).vars() >> I_vars) && (factor(J).vars().size() != I_size) )\n                        return maximalFactor( J );\n            }\n        }\n        return I;\n    }\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\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 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 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\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    for( const Neighbor &I : nbV(i) )\n        newFacs[I] = factor(I) * mask;\n    setFactors( newFacs, backup );\n\n    return;\n}\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    for( 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    for( const Neighbor &I : nbV(i) )\n        newFacs[I] = factor(I) * mask_n;\n    setFactors( newFacs, backup );\n}\n\n\nvoid FactorGraph::clampFactor( size_t I, const vector<size_t> &is, bool backup ) {\n#ifndef DAI_PERF\n    size_t st = factor(I).nrStates();\n#endif\n    Factor newF( factor(I).vars(), (Real)0 );\n\n    for( 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\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\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\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\n\nvoid FactorGraph::restoreFactors( const VarSet &ns ) {\n    map<size_t,Factor> facs;\n    for( map<size_t,Factor>::iterator uI = _backup.begin(); 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\n\nvoid FactorGraph::restoreFactors() {\n    setFactors( _backup );\n    _backup.clear();\n}\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(); fac++ )\n        backupFactor( *fac );\n}\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\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\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\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(), facs.size(), nrVars() );\n}\n\n\n} // end of namespace dai\n", "meta": {"hexsha": "abf7b672f605d3e967895777b13b36af13eaa48c", "size": 16370, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/factorgraph.cpp", "max_stars_repo_name": "flurischt/libDAI", "max_stars_repo_head_hexsha": "20683a222e2ef307209290f79081fe428d9c5050", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2015-05-03T00:17:48.000Z", "max_stars_repo_stars_event_max_datetime": "2015-05-03T00:17:48.000Z", "max_issues_repo_path": "src/factorgraph.cpp", "max_issues_repo_name": "flurischt/libDAI", "max_issues_repo_head_hexsha": "20683a222e2ef307209290f79081fe428d9c5050", "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/factorgraph.cpp", "max_forks_repo_name": "flurischt/libDAI", "max_forks_repo_head_hexsha": "20683a222e2ef307209290f79081fe428d9c5050", "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.9268738574, "max_line_length": 156, "alphanum_fraction": 0.537690898, "num_tokens": 4550, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.640635854839898, "lm_q2_score": 0.5428632831725052, "lm_q1q2_score": 0.3477776834764115}}
{"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.hpp\n * @author Ondrej Prochazka <ondrej.prochazka@citationtech.net>\n *\n * Analytical geometry functions\n */\n\n#ifndef MATH_GEOMETRY_HPP\n#define MATH_GEOMETRY_HPP\n\n#include \"geometry_core.hpp\"\n\n#include <algorithm>\n#include <array>\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\nnamespace math {\n\nnamespace ublas = boost::numeric::ublas;\n\n\ntypedef std::array<math::Point2d, 3> Triangle2d;\ntypedef std::array<math::Point3d, 3> Triangle3d;\n\ntypedef std::vector<Triangle2d> Triangles2d;\ntypedef std::vector<Triangle3d> Triangles3d;\n\ntypedef Points2d Polygon; // single CCW ring, not closed\ntypedef std::vector<Polygon> MultiPolygon; // multiple rings, holes CW\n\n/**\n * Find the point where two lines get closest in 3D space.\n * The lines are defined parametrically in euclidian coordinates.\n * Return value is the euclidian metrics of the line distance, plus\n * the two parameter values for each of the lines.\n */\n\nfloat lineDistance(\n    const ublas::vector<float> & p1, const ublas::vector<float> & u1,\n    const ublas::vector<float> & p2, const ublas::vector<float> & u2,\n    float & r1, float & r2 );\n\n\n/** normalize vector */\ntemplate <class T>\ninline ublas::vector<typename T::value_type> normalize( const T & v ) {\n    return v / ublas::norm_2( v );\n}\n\n/** normalize vector */\ntemplate <class T>\ninline Point2_<T> normalize( const Point2_<T> & v ) {\n    return v / ublas::norm_2( v );\n}\n\n/** normalize vector */\ntemplate <class T>\ninline Point3_<T> normalize( const Point3_<T> & v ) {\n    return v / ublas::norm_2( v );\n}\n\n/** length of the vector */\ntemplate <typename T>\ninline double length( const T & v ) {\n    return ublas::norm_2(v);\n}\n\n/** angle between two 3D vectors (in radians)\n * See Kahan W.: How Futile are Mindless Assessments of Roundoff in\n * Floating-Point Computation?, page 46\n * (https://people.eecs.berkeley.edu/~wkahan/Mindless.pdf)\n *  **/\ntemplate <class T>\ninline T angle(const Point3_<T>& v1, const Point3_<T>& v2)\n{\n    return 2\n           * std::atan2(length(v1 * length(v2) - length(v1) * v2),\n                        length(v1 * length(v2) + length(v1) * v2));\n}\n\n/** homogeneous coordinates (from euclidian) */\ntemplate <class T>\ninline ublas::vector<T, ublas::bounded_array<T, 4> >\nhomogeneous( const Point3_<T> & src )\n{\n    ublas::vector<T, ublas::bounded_array<T, 4> > dst(4);\n    dst(0) = src(0); dst(1) = src(1); dst(2) = src(2);\n    dst(3) = T(1);\n    return dst;\n}\n\n/** homogeneous coordinates (from euclidian) */\ntemplate <class T>\ninline ublas::vector<typename T::value_type> homogeneous( const T & src ) {\n\n    ublas::vector<typename T::value_type> ret(\n        ublas::unit_vector<typename T::value_type>(\n            src.size() + 1, src.size() ) );\n    ublas::subrange( ret, 0, src.size() ) = src;\n    return ret;\n}\n\n/** euclidian coordinates (from homogenous) */\ntemplate <class T>\ninline Point3_<T>\neuclidian( const ublas::vector<T, ublas::bounded_array<T, 4> > & src )\n{\n    auto div(src(3));\n    return Point3_<T>(src(0) / div, src(1) / div, src(2) / div);\n}\n\n/** euclidian coordinates (from homogenous) */\ntemplate <class T>\ninline ublas::vector<typename T::value_type> euclidian( const T & src ) {\n    return ublas::subrange( src, 0, src.size() - 1 ) / src( src.size() - 1 );\n}\n\n/** cross product, in euclidian 3D */\n\ntemplate<typename T, typename U>\ninline ublas::vector<typename T::value_type> crossProduct(\n    const T & u,\n    const U & v ) {\n\n    assert( u.size() == 3 && v.size() == 3 );\n    ublas::vector<typename T::value_type> retval( 3 );\n    retval(0) = u(1) * v(2) - v(1) * u(2);\n    retval(1) = -u(0) * v(2) + v(0) * u(2);\n    retval(2) = u(0) * v(1) - v(0) * u(1);\n    return retval;\n}\n\ntemplate <typename T>\ninline Point3_<T> crossProduct(const Point3_<T> & u, const Point3_<T> & v )\n{\n    return Point3_<T>(u(1) * v(2) - v(1) * u(2)\n                     , -u(0) * v(2) + v(0) * u(2)\n                     , u(0) * v(1) - v(0) * u(1));\n}\n\ntemplate<typename T>\ninline Point3_<T> crossProduct(const Point3_<T> & u, const ublas::vector<T> & v )\n{\n    assert(v.size() == 3);\n    return Point3_<T>(u(1) * v(2) - v(1) * u(2)\n                     , -u(0) * v(2) + v(0) * u(2)\n                     , u(0) * v(1) - v(0) * u(1));\n}\n\ntemplate<typename T>\ninline Point3_<T> crossProduct(const ublas::vector<T> & u, const Point3_<T> & v )\n{\n    assert(u.size() == 3);\n    return Point3_<T>(u(1) * v(2) - v(1) * u(2)\n                     , -u(0) * v(2) + v(0) * u(2)\n                     , u(0) * v(1) - v(0) * u(1));\n}\n\n/** 2D version of cross product; result is not an vector but crossproduct's\n *  z-component.\n */\ntemplate <typename T>\ninline T crossProduct(const Point2_<T> & u, const Point2_<T> & v )\n{\n    return u(0) * v(1) - v(0) * u(1);\n}\n\n//! return area of a triangle in 2D plane\ntemplate <typename T>\ninline double triangleArea(const Point2_<T>& a, const Point2_<T>& b,\n                           const Point2_<T>& c)\n{\n    return std::abs(crossProduct(Point2(b - a), Point2(c - a))) * 0.5;\n}\n\n//! return area of a triangle in 3D space\ntemplate <typename T>\ninline double triangleArea(const Point3_<T>& a, const Point3_<T>& b,\n                           const Point3_<T>& c)\n{\n    return norm_2(crossProduct(b - a, c - a)) * 0.5;\n}\n\n#ifdef MATH_HAS_OPENCV\n    //! return area of a triangle in 2D plane\n    template <typename T>\n    inline double triangleArea(const cv::Point_<T>& a, const cv::Point_<T>& b,\n                               const cv::Point_<T>& c)\n    {\n        return triangleArea(Point2_<T>(a), Point2_<T>(b), Point2_<T>(c));\n    }\n\n    //! return area of a triangle in 3D space\n    template <typename T>\n    inline double triangleArea(const cv::Point3_<T>& a, const cv::Point3_<T>& b,\n                               const cv::Point3_<T>& c)\n    {\n        return triangleArea(Point3_<T>(a), Point3_<T>(b), Point3_<T>(c));\n    }\n#endif // MATH_HAS_OPENCV\n\n/** Returns a positive number if the sequence of points {a, b, c} turns\n *  counter-clockwise in the XY plane (negative number otherwise).\n *  Zero (within numerical tolerance) means collinear.\n */\ntemplate <typename T>\ninline T ccw(const Point2_<T> &a, const Point2_<T> &b, const Point2_<T> &c)\n{\n    return (b(0) - a(0))*(c(1) - a(1)) - (b(1) - a(1))*(c(0) - a(0));\n}\n\n\n/** Parametric line, in euclidian 2D\n */\n\ntemplate <typename T>\nstruct Line2_\n{\n    T p, u;\n\n    Line2_(const T p, const T u) : p(p), u(u) {};\n};\n\ntypedef Line2_<Point2> Line2;\n\n/** Returns a point where two lines `l1` and `l2` intersect.\n */\ntemplate <typename T>\ninline T lineIntersection(const Line2_<T>& l1, const Line2_<T>& l2)\n{\n    T pd = l2.p - l1.p; // diff of origins\n    auto num = -l2.u(1) * pd(0) + l2.u(0) * pd(1);\n    auto den = l2.u(0) * l1.u(1) - l1.u(0) * l2.u(1);\n    return l1.p + (num / den) * l1.u;\n}\n\n/**\n * Line segment represented by start and end points\n */\ntemplate <typename T>\nstruct Segment2_\n{\n    T p1, p2;\n\n    Segment2_(const T p1, const T p2) : p1(p1), p2(p2) {};\n};\n\ntypedef Segment2_<Point2> Segment2;\n\n/**\n * Parametric line, in euclidian 3D\n */\n\nstruct Line3 {\n    Point3 p, u;\n\n    Line3(const Point3 p = Point3(), const Point3 u = Point3() )\n        : p( p ), u( u ) {}\n\n    /** Returns line's point at given parameter (t)\n     */\n    Point3 point(double t) const { return p + u * t; }\n};\n\ntemplate <typename E, typename T>\ninline std::basic_ostream<E, T> & operator << (\n        std::basic_ostream<E,T> & os,\n        const Line3 & line ) {\n\n    os << line.p << \" + t * \" << line.u;\n    return os;\n}\n\nPoint3 midpoint( const Line3 & line1, const Line3 & line2\n               , double minAngleCos = 0.9962 );\n\ndouble pointLineDistance(const Point3 &p, const Line3 &line);\n\n\n/**\n * Parametric plane, in euclidian 3D\n * Legacy representation of plane by 3 points.\n */\nnamespace legacy {\nstruct Plane3 {\n\n    Point3 p, u, v;\n\n    Plane3(\n        const ublas::vector<double> p = ublas::zero_vector<double>( 3 ),\n        const ublas::vector<double> u = ublas::zero_vector<double>( 3 ),\n        const ublas::vector<double> v = ublas::zero_vector<double>( 3 ) )\n        : p( p ), u( u ), v( v ) {}\n\n\n    template <class Matrix>\n    Plane3 transform( const Matrix & trafo ) const {\n\n        Plane3 tplane;\n\n        tplane.p = euclidian( prod( trafo, homogeneous( p ) ) );\n        tplane.u = euclidian( prod( trafo, homogeneous( p + u ) ) ) - tplane.p;\n        tplane.v = euclidian( prod( trafo, homogeneous( p + v ) ) ) - tplane.p;\n\n        return tplane;\n\n    }\n};\n\ntemplate <typename E, typename T>\ninline std::basic_ostream<E, T> & operator << (\n        std::basic_ostream<E,T> & os,\n        const Plane3 & plane ) {\n\n    os << plane.p << \" + t * \" << plane.u << \" + s * \" << plane.v;\n    return os;\n}\n}  // namespace legacy\n\n\n/** line and plane intersection */\n\nPoint3 intersection( const Line3 & line, const legacy::Plane3 & plane );\n\n/** line and plane intersection\n *  instead of point returns 3 coefficients:\n *      * lines t-parameter\n *      * planes t-parameter\n *      * planes s-parameter\n */\nPoint3 intersectionParams(const Line3 &line, const legacy::Plane3 &plane);\n\n\n/**\n* Plane represented in general form\n* Representation as (a,b,c,d) in equation: ax+by+cz+d=0\n*/\nstruct Plane3\n{\n    math::Point3 n_;  // vector with (a,b,c) i.e. normal vector\n    double d_;\n\n    // Plane from parameters\n    Plane3(double a, double b, double c, double d) : n_(a, b, c), d_(d) { }\n\n    // Plane from point and normal\n    Plane3(const math::Point3d& pt, const math::Point3d& n)\n        : n_(n),\n          d_(-ublas::inner_prod(pt, n)) {};\n\n    // Plane from three points\n    Plane3(const math::Point3d& p1,\n           const math::Point3d& p2,\n           const math::Point3d& p3)\n        : Plane3(p1, crossProduct(p2 - p1, p3 - p1)) {};\n\n    // Plane from legacy representation (point-normal packed as Line3)\n    Plane3(const math::Line3& l) : Plane3(l.p, l.u) {};\n\n    // Returns a plane with opposite orientation\n    Plane3 opposite() const {\n        Plane3 pl2(*this);\n        pl2.n_ *= -1;\n        pl2.d_ *= -1;\n        return pl2;\n    }\n};\n\n/**\n * Returns a distance of point to a plane (perpendicular)\n*/\ndouble pointPlaneDistance(const Point3 &p, const Plane3 &plane);\n\n/**\n * Returns an orthogonal projection of a point to a plane\n */\nPoint3 pointPlaneProjection(const Point3 &p, const Plane3 &plane);\n\n/**\n * Returns a point of intersection between plane and line\n */\nPoint3 linePlaneIntersection(const Line3 &l, const Plane3 &plane);\n\n/**\n * Returns a line of intersection between two planes\n */\nLine3 planeIntersection(const Plane3 &p1, const Plane3 &p2);\n\n/**\n * Returns a point of intersection between three planes\n */\nPoint3 planeIntersection(const Plane3 &p1, const Plane3 &p2, const Plane3 &p3);\n\n/**\n * Returns a measure of triangular polyface regularity. Value of 1.0\n * indicates an equilateral triangle, value of 0.0 indicates a triangle\n * with at least one degenerate edge.\n */\ndouble polygonRegularity(\n    const Point3 & v0, const Point3 & v1, const Point3 & v2  );\n\n/**\n * Returns a measure of quad polyface regularity. Value of 1.0\n * indicates a square, value of 0.0 indicates a triangle\n * with at least one degenerate edge.\n */\ndouble polygonRegularity(\n    const Point3 & v0, const Point3 & v1, const Point3 & v2, const Point3 & v3 );\n\n/**\n * Returns whether the triangle and rectagle collide.\n */\nbool triangleRectangleCollision( math::Point2 triangle[3]\n                               , math::Point2 ll, math::Point2 ur);\n\n/**\n * Convert cartesian coordinates (r) to barycentric with respect to the (a,b,c)\n * triangle. See http://en.wikipedia.org/wiki/Barycentric_coordinate_system\n */\nmath::Point3 barycentricCoords(const math::Point2 &r, const math::Point2 &a\n                               , const math::Point2 &b, const math::Point2 &c);\ninline\nmath::Point3 barycentricCoords(const math::Point2 &r, const Triangle2d &tri) {\n    return barycentricCoords(r, tri[0], tri[1], tri[2]);\n}\n\nnamespace detail {\n    template <typename T, typename Q> struct ExtentsTypeTraits;\n\n    template <typename T> struct ExtentsTypeTraits<T, Point2_<T>> {\n        typedef Extents2_<T> type;\n    };\n\n    template <typename T> struct ExtentsTypeTraits<T, Point3_<T>> {\n        typedef Extents3_<T> type;\n    };\n\n#ifdef MATH_HAS_OPENCV\n    template <typename T> struct ExtentsTypeTraits<T, cv::Point_<T>> {\n        typedef Extents2_<T> type;\n    };\n\n    template <typename T> struct ExtentsTypeTraits<T, cv::Point3_<T>> {\n        typedef Extents3_<T> type;\n    };\n#endif\n} // namespace detail\n\ntemplate <typename Iterator>\ninline auto computeExtents(Iterator begin, Iterator end)\n    -> typename detail::ExtentsTypeTraits\n    <typename std::iterator_traits<Iterator>::value_type::value_type\n    , typename std::iterator_traits<Iterator>::value_type>::type\n{\n    typedef typename detail::ExtentsTypeTraits\n        <typename std::iterator_traits<Iterator>::value_type::value_type\n         , typename std::iterator_traits<Iterator>::value_type>::type Extents;\n    typedef typename Extents::point_type point_type;\n\n    if (begin == end) {\n        return Extents(InvalidExtents{});\n    }\n\n    Extents extents(*begin++);\n    std::for_each(begin, end\n                  , [&extents](const point_type &p) {\n                      update(extents, p);\n                  });\n    return extents;\n}\n\n/** Simplified version for STL container.\n */\ntemplate <typename Container>\ninline auto computeExtents(const Container &c)\n    -> typename detail::ExtentsTypeTraits\n    <typename Container::value_type::value_type\n     , typename Container::value_type>::type\n{\n    return computeExtents(c.begin(), c.end());\n}\n\n// prefered natural aliases for above\n\ntemplate <typename Iterator>\ninline auto extents(Iterator begin, Iterator end)\n    -> typename detail::ExtentsTypeTraits\n    <typename std::iterator_traits<Iterator>::value_type::value_type\n    , typename std::iterator_traits<Iterator>::value_type>::type\n{\n    return computeExtents<Iterator>(begin,end);\n}\n\ntemplate <typename Container>\ninline auto extents(const Container &c)\n    -> typename detail::ExtentsTypeTraits\n    <typename Container::value_type::value_type\n     , typename Container::value_type>::type\n{\n    return computeExtents<Container>(c);\n}\n\n} // namespace math\n\n#endif // MATH_GEOMETRY_HPP\n", "meta": {"hexsha": "acb4115c8f5f9d82f5937461d83c905821924ff2", "size": 15789, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "math/geometry.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.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.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": 29.4022346369, "max_line_length": 81, "alphanum_fraction": 0.6436126417, "num_tokens": 4481, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.640635854839898, "lm_q2_score": 0.5428632831725052, "lm_q1q2_score": 0.3477776834764115}}
{"text": "/**\n * @file\n * @copyright This code is licensed under the 3-clause BSD license.\\n\n *            Copyright ETH Zurich, Laboratory for Physical Chemistry, Reiher Group.\\n\n *            See LICENSE.txt for details.\n */\n\n#include \"MDIntegrator.h\"\n#include <Utils/Geometry/GeometryUtilities.h>\n#include <Eigen/Geometry>\n#include <random>\n\nnamespace Scine {\nnamespace Utils {\n\nstatic constexpr double femtosecondsToAtomicUnits = 41.3413746; // 1 fs in atomic time units\nstatic constexpr double massConversionFactor = 1822.88848619;   // 1 u in electron masses\nstatic constexpr double atomicUnitsToKelvin = 3.1577464e5;\nstatic constexpr double kelvinToAtomicUnits = 1.0 / atomicUnitsToKelvin;\nstatic constexpr double boltzmannConstant = 3.1668114e-6; // E_h / K\n\nMDIntegrator::MDIntegrator() : targetTemperature_(298.15 * kelvinToAtomicUnits) {\n  setTimeStepInFemtoseconds(1.0);\n  setRelaxationTimeFactor(10.0);\n}\n\nvoid MDIntegrator::setElementTypes(const Utils::ElementTypeCollection& elements) {\n  nAtoms_ = static_cast<int>(elements.size());\n  masses_ = Utils::Geometry::getMasses(elements);\n  resetVelocities();\n  resetAccelerations();\n}\n\nvoid MDIntegrator::calculateAccelerationsFromGradients(const Utils::GradientCollection& gradients) {\n  assert(gradients.size() == accelerations_.size());\n  for (int i = 0; i < nAtoms_; ++i)\n    accelerations_.row(i) = (-1.0 / masses_[i]) * gradients.row(i);\n}\n\nvoid MDIntegrator::rescaleVelocitiesForTemperatureBath() {\n  if (!temperatureBath_)\n    return;\n  double currentTemperature = getCurrentTemperature();\n  double factor = std::sqrt(1. + timeStep_ / temperatureRelaxationTime_ * (targetTemperature_ / currentTemperature - 1));\n  velocities_ *= factor;\n}\n\nvoid MDIntegrator::resetVelocities() {\n  velocities_.resize(nAtoms_, 3);\n  velocities_.setZero();\n  sampleVelocitiesFromBoltzmannDistribution();\n}\n\nvoid MDIntegrator::resetAccelerations() {\n  accelerations_.resize(nAtoms_, 3);\n  accelerations_.setZero();\n}\n\nvoid MDIntegrator::setVelocities(const Utils::DisplacementCollection& velocities) {\n  velocities_ = velocities;\n}\n\nUtils::DisplacementCollection MDIntegrator::getVelocities() const {\n  return velocities_;\n}\n\nvoid MDIntegrator::setTimeStepInFemtoseconds(double fs) {\n  timeStep_ = fs * femtosecondsToAtomicUnits / massConversionFactor;\n  temperatureRelaxationTime_ = timeStep_ * relaxationTimeFactor_;\n}\n\nvoid MDIntegrator::setRelaxationTimeFactor(double factor) {\n  relaxationTimeFactor_ = factor;\n  temperatureRelaxationTime_ = timeStep_ * relaxationTimeFactor_;\n}\n\nvoid MDIntegrator::setTargetTemperatureInKelvin(double T) {\n  targetTemperature_ = T * kelvinToAtomicUnits;\n  temperatureBath_ = true;\n}\n\ndouble MDIntegrator::getCurrentTemperature() {\n  int numberDegreesOfFreedom = 3 * nAtoms_; // TODO: Subtract translation and remove center of mass motion\n  double currentTemperature =\n      (velocities_.rowwise().squaredNorm().array() * Eigen::Map<const Eigen::ArrayXd>(masses_.data(), masses_.size())).sum() /\n      numberDegreesOfFreedom;\n  return currentTemperature;\n}\n\nvoid MDIntegrator::sampleVelocitiesFromBoltzmannDistribution() {\n  std::mt19937 gen(seed_);\n  double numerator = std::sqrt(targetTemperature_ * boltzmannConstant * atomicUnitsToKelvin);\n  int index = 0;\n  for (double mass : masses_) {\n    std::normal_distribution<> d(0., numerator * std::sqrt(1. / mass));\n    velocities_.row(index) = Position{d(gen), d(gen), d(gen)};\n    ++index;\n  }\n}\n\nvoid MDIntegrator::setSeed(int seed) {\n  seed_ = seed;\n}\n\nvoid MDIntegrator::removeCenterOfMassLinearMomentum(const Eigen::MatrixX3d& positions) {\n  const Eigen::VectorXd& masses = Eigen::Map<const Eigen::VectorXd>(masses_.data(), masses_.size());\n  double totalMass = masses.sum();\n  auto centerOfMass = Utils::Geometry::getCenterOfMass(positions, masses_);\n\n  // Remove total linear momentum\n  Eigen::MatrixX3d linearMomentumVector = velocities_.array().colwise() * masses.array();\n  Eigen::RowVector3d centerOfMassVelocity = linearMomentumVector.colwise().sum() / totalMass;\n\n  velocities_.rowwise() -= centerOfMassVelocity;\n}\n\nvoid MDIntegrator::removeCenterOfMassAngularMomentum(const Eigen::MatrixX3d& positions) {\n  const Eigen::VectorXd& masses = Eigen::Map<const Eigen::VectorXd>(masses_.data(), masses_.size());\n  double totalMass = masses.sum();\n  auto centerOfMass = Utils::Geometry::getCenterOfMass(positions, masses_);\n  auto inertiaTensor = Utils::Geometry::calculateInertiaTensor(positions, masses_, centerOfMass);\n  Eigen::MatrixX3d positionsRelativeToCOM = positions.rowwise() - centerOfMass;\n\n  // Remove total angular momentum\n  Eigen::MatrixX3d linearMomentumVector = velocities_.array().colwise() * masses.array();\n  Eigen::RowVector3d totalAngularMomentum = Eigen::RowVector3d::Zero(1, 3);\n  for (int i = 0; i < linearMomentumVector.rows(); ++i) {\n    Eigen::RowVector3d particleAngularMomentum = positionsRelativeToCOM.row(i).cross(linearMomentumVector.row(i));\n    totalAngularMomentum += particleAngularMomentum;\n  }\n\n  Eigen::RowVector3d angularVelocityVector =\n      inertiaTensor.jacobiSvd(Eigen::ComputeFullU | Eigen::ComputeFullV).solve(totalAngularMomentum.transpose());\n\n  for (int i = 0; i < positionsRelativeToCOM.rows(); ++i) {\n    velocities_.row(i) -= angularVelocityVector.cross(positionsRelativeToCOM.row(i));\n  }\n}\n} // namespace Utils\n} // namespace Scine", "meta": {"hexsha": "f6ee6bafa1878e520b341b03f62c258548950a4c", "size": 5322, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Utils/Utils/MolecularDynamics/MDIntegrator.cpp", "max_stars_repo_name": "DockBio/utilities", "max_stars_repo_head_hexsha": "213ed5ac2a64886b16d0fee1fcecb34d36eea9e9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Utils/Utils/MolecularDynamics/MDIntegrator.cpp", "max_issues_repo_name": "DockBio/utilities", "max_issues_repo_head_hexsha": "213ed5ac2a64886b16d0fee1fcecb34d36eea9e9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Utils/Utils/MolecularDynamics/MDIntegrator.cpp", "max_forks_repo_name": "DockBio/utilities", "max_forks_repo_head_hexsha": "213ed5ac2a64886b16d0fee1fcecb34d36eea9e9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.0142857143, "max_line_length": 126, "alphanum_fraction": 0.7553551297, "num_tokens": 1364, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.712232184238947, "lm_q2_score": 0.48828339529583464, "lm_q1q2_score": 0.34777114915916146}}
{"text": "#include \"GRU.hpp\"\n#include \"ActFunc.hpp\"\n#include \"Utils.hpp\"\n#include <Eigen/SVD>\n\nGRU::GRU(const int inputDim, const int hiddenDim){\n  this->Wxr = MatD(hiddenDim, inputDim);\n  this->Whr = MatD(hiddenDim, hiddenDim);\n  this->br = VecD::Zero(hiddenDim);\n\n  this->Wxz = MatD(hiddenDim, inputDim);\n  this->Whz = MatD(hiddenDim, hiddenDim);\n  this->bz = VecD::Zero(hiddenDim);\n\n  this->Wxu = MatD(hiddenDim, inputDim);\n  this->Whu = MatD(hiddenDim, hiddenDim);\n  this->bu = VecD::Zero(hiddenDim);\n}\n\nvoid GRU::init(Rand& rnd, const Real scale){\n  rnd.uniform(this->Wxr, scale);\n  rnd.uniform(this->Whr, scale);\n\n  rnd.uniform(this->Wxz, scale);\n  rnd.uniform(this->Whz, scale);\n  \n  rnd.uniform(this->Wxu, scale);\n  rnd.uniform(this->Whu, scale);\n\n  this->Whr = Eigen::JacobiSVD<MatD>(this->Whr, Eigen::ComputeFullV|Eigen::ComputeFullU).matrixU();\n  this->Whz = Eigen::JacobiSVD<MatD>(this->Whz, Eigen::ComputeFullV|Eigen::ComputeFullU).matrixU();\n  this->Whu = Eigen::JacobiSVD<MatD>(this->Whu, Eigen::ComputeFullV|Eigen::ComputeFullU).matrixU();\n}\n\nvoid GRU::forward(const VecD& xt, const GRU::State* prev, GRU::State* cur){\n  cur->r = this->br + this->Wxr*xt + this->Whr*prev->h;\n  cur->z = this->bz + this->Wxz*xt + this->Whz*prev->h;\n\n  ActFunc::logistic(cur->r);\n  ActFunc::logistic(cur->z);\n\n  cur->rh = cur->r.array()*prev->h.array();\n  cur->u = this->bu + this->Wxu*xt + this->Whu*cur->rh;\n  ActFunc::tanh(cur->u);\n  cur->h = (1.0-cur->z.array())*prev->h.array() + cur->z.array()*cur->u.array();\n}\n\nvoid GRU::backward(GRU::State* prev, GRU::State* cur, GRU::Grad& grad, const VecD& xt){\n  VecD delr, delz, delu, delrh;\n\n  delz = ActFunc::logisticPrime(cur->z).array()*cur->delh.array()*(cur->u-prev->h).array();\n  delu = ActFunc::tanhPrime(cur->u).array()*cur->delh.array()*cur->z.array();\n  delrh = this->Whu.transpose()*delu;\n  delr = ActFunc::logisticPrime(cur->r).array()*delrh.array()*prev->h.array();\n\n  cur->delx =\n    this->Wxr.transpose()*delr+\n    this->Wxz.transpose()*delz+\n    this->Wxu.transpose()*delu;\n\n  prev->delh.noalias() +=\n    this->Whr.transpose()*delr+\n    this->Whz.transpose()*delz;\n  prev->delh.array() +=\n    delrh.array()*cur->r.array()+\n    cur->delh.array()*(1.0-cur->z.array());\n\n  grad.Wxr.noalias() += delr*xt.transpose();\n  grad.Whr.noalias() += delr*prev->h.transpose();\n\n  grad.Wxz.noalias() += delz*xt.transpose();\n  grad.Whz.noalias() += delz*prev->h.transpose();\n\n  grad.Wxu.noalias() += delu*xt.transpose();\n  grad.Whu.noalias() += delu*cur->rh.transpose();\n\n  grad.br += delr;\n  grad.bz += delz;\n  grad.bu += delu;\n}\n\nvoid GRU::sgd(const GRU::Grad& grad, const Real learningRate){\n  this->Wxr -= learningRate*grad.Wxr;\n  this->Whr -= learningRate*grad.Whr;\n  this->br -= learningRate*grad.br;\n\n  this->Wxz -= learningRate*grad.Wxz;\n  this->Whz -= learningRate*grad.Whz;\n  this->bz -= learningRate*grad.bz;\n\n  this->Wxu -= learningRate*grad.Wxu;\n  this->Whu -= learningRate*grad.Whu;\n  this->bu -= learningRate*grad.bu;\n}\n\nvoid GRU::save(std::ofstream& ofs){\n  Utils::save(ofs, this->Wxr); Utils::save(ofs, this->Whr); Utils::save(ofs, this->br);\n  Utils::save(ofs, this->Wxz); Utils::save(ofs, this->Whz); Utils::save(ofs, this->bz);\n  Utils::save(ofs, this->Wxu); Utils::save(ofs, this->Whu); Utils::save(ofs, this->bu);\n}\n\nvoid GRU::load(std::ifstream& ifs){\n  Utils::load(ifs, this->Wxr); Utils::load(ifs, this->Whr); Utils::load(ifs, this->br);\n  Utils::load(ifs, this->Wxz); Utils::load(ifs, this->Whz); Utils::load(ifs, this->bz);\n  Utils::load(ifs, this->Wxu); Utils::load(ifs, this->Whu); Utils::load(ifs, this->bu);\n}\n\nvoid GRU::State::clear(){\n  this->h = VecD();\n  this->u = VecD();\n  this->r = VecD();\n  this->z = VecD();\n  this->rh = VecD();\n  this->delh = VecD();\n  this->delx = VecD();\n}\n\nGRU::Grad::Grad(const GRU& gru){\n  this->Wxr = MatD::Zero(gru.Wxr.rows(), gru.Wxr.cols());\n  this->Whr = MatD::Zero(gru.Whr.rows(), gru.Whr.cols());\n  this->br = VecD::Zero(gru.br.rows());\n\n  this->Wxz = MatD::Zero(gru.Wxz.rows(), gru.Wxz.cols());\n  this->Whz = MatD::Zero(gru.Whz.rows(), gru.Whz.cols());\n  this->bz = VecD::Zero(gru.bz.rows());\n\n  this->Wxu = MatD::Zero(gru.Wxu.rows(), gru.Wxu.cols());\n  this->Whu = MatD::Zero(gru.Whu.rows(), gru.Whu.cols());\n  this->bu = VecD::Zero(gru.bu.rows());\n};\n\nvoid GRU::Grad::init(){\n  this->Wxr.setZero(); this->Whr.setZero(); this->br.setZero();\n  this->Wxz.setZero(); this->Whz.setZero(); this->bz.setZero();\n  this->Wxu.setZero(); this->Whu.setZero(); this->bu.setZero();\n}\n\nReal GRU::Grad::norm(){\n  return\n    this->Wxr.squaredNorm()+this->Whr.squaredNorm()+this->br.squaredNorm()+\n    this->Wxz.squaredNorm()+this->Whz.squaredNorm()+this->bz.squaredNorm()+\n    this->Wxu.squaredNorm()+this->Whu.squaredNorm()+this->bu.squaredNorm();\n}\n\nvoid GRU::Grad::operator += (const GRU::Grad& grad){\n  this->Wxr += grad.Wxr; this->Whr += grad.Whr; this->br += grad.br;\n  this->Wxz += grad.Wxz; this->Whz += grad.Whz; this->bz += grad.bz;\n  this->Wxu += grad.Wxu; this->Whu += grad.Whu; this->bu += grad.bu;\n}\n", "meta": {"hexsha": "1622d1e42cf77769981793b120ec0f7ba48e9ae4", "size": 5005, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "GRU.cpp", "max_stars_repo_name": "Sanaxen/N3LP", "max_stars_repo_head_hexsha": "06526ba558231c5973d26a5f2b876a9379dc4502", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 93.0, "max_stars_repo_stars_event_min_datetime": "2015-12-16T13:17:23.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-01T17:02:51.000Z", "max_issues_repo_path": "GRU.cpp", "max_issues_repo_name": "Sanaxen/N3LP", "max_issues_repo_head_hexsha": "06526ba558231c5973d26a5f2b876a9379dc4502", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2016-01-03T23:48:17.000Z", "max_issues_repo_issues_event_max_datetime": "2017-10-17T05:29:08.000Z", "max_forks_repo_path": "GRU.cpp", "max_forks_repo_name": "Sanaxen/N3LP", "max_forks_repo_head_hexsha": "06526ba558231c5973d26a5f2b876a9379dc4502", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 32.0, "max_forks_repo_forks_event_min_datetime": "2016-01-07T15:52:50.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-08T00:55:26.000Z", "avg_line_length": 33.3666666667, "max_line_length": 99, "alphanum_fraction": 0.632967033, "num_tokens": 1759, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7606506635289836, "lm_q2_score": 0.4571367168274948, "lm_q1q2_score": 0.347721346978295}}
{"text": "#include \"ReconstructionImpl.h\"\r\n#include \"omp.h\"\r\n#include \"cgls.hpp\"\r\n#include \"sirt.hpp\"\r\n#include \"mlem.hpp\"\r\n#include \"ui_calls.hpp\"\r\n#include \"utils.hpp\"\r\n#include \"voxels.hpp\"\r\n#include \"blas.hpp\"\r\n#include <boost/filesystem.hpp>\r\n\r\nCCPi::ReconstructionImpl::ReconstructionImpl(void)\r\n{\r\n\tdeviceId = CCPi::dev_Nikon_XTek;\r\n\tnumberOfProcessors = omp_get_max_threads();\r\n\talgorithmId = CCPi::alg_CGLS;\r\n\tbHyperThreads = true;\r\n\tnumberOfIterations = 20;\r\n\tresolution = 1;\r\n\tregularise = 0.01;\r\n}\r\n\r\n\r\nCCPi::ReconstructionImpl::~ReconstructionImpl(void)\r\n{\r\n\tif(voxels!=NULL)\r\n\t\tdelete voxels;\r\n}\r\n\r\nvoid CCPi::ReconstructionImpl::setDeviceId(devices id)\r\n{\r\n\tdeviceId = id;\r\n}\r\n\r\nvoid CCPi::ReconstructionImpl::setAlgorithmId(algorithms id)\r\n{\r\n\talgorithmId = id;\r\n}\r\n\r\nvoid CCPi::ReconstructionImpl::setNumberOfProcessors(int noProcs)\r\n{\r\n\tnumberOfProcessors = noProcs;\r\n}\r\n\r\nvoid CCPi::ReconstructionImpl::enableHyperThreads()\r\n{\r\n\tbHyperThreads = true;\r\n}\r\nvoid CCPi::ReconstructionImpl::disableHyperThreads()\r\n{\r\n\tbHyperThreads = false;\r\n}\r\n\r\nvoid CCPi::ReconstructionImpl::setResolution(int resolution)\r\n{\r\n\tthis->resolution = resolution;\r\n}\r\nvoid CCPi::ReconstructionImpl::setNumberOfIterations(int iterations)\r\n{\r\n\tnumberOfIterations = iterations;\r\n}\r\n\r\nvoid CCPi::ReconstructionImpl::setRegularisation(double value)\r\n{\r\n\tregularise = value;\r\n}\r\n\r\nvoid CCPi::ReconstructionImpl::enableBeamHardening()\r\n{\r\n\tbBeamHardening = true;\r\n}\r\n\r\nvoid CCPi::ReconstructionImpl::disableBeamHardening()\r\n{\r\n\tbBeamHardening = false;\r\n}\r\n\r\nvoid CCPi::ReconstructionImpl::setBeamHardening(bool value)\r\n{\r\n\tbBeamHardening = value;\r\n}\r\n\r\nvoid CCPi::ReconstructionImpl::setFilename(std::string name)\r\n{\r\n\tfilename = name;\r\n}\r\n\r\nbool CCPi::ReconstructionImpl::run()\r\n{\r\n\tif (!bHyperThreads) {\r\n\t\tint num_processors = numberOfProcessors / 2;\r\n\t\tomp_set_num_threads(num_processors);\r\n\t}else{\r\n\t\tomp_set_num_threads(numberOfProcessors);\r\n\t}\r\n\tbool noerror = true;\r\n\t\r\n\tCCPi::instrument *device = 0;\r\n\t\r\n\tswitch (deviceId) {\r\n\tcase CCPi::dev_Nikon_XTek:\r\n\t\tdevice = new CCPi::Nikon_XTek;\r\n\t\tbreak;\r\n\tdefault:\r\n\t\tnoerror = false;\r\n\t\tbreak;\r\n\t}\r\n\r\n\tCCPi::reconstruction_alg *recon_algorithm = 0;\r\n\tswitch (algorithmId) {\r\n\tcase CCPi::alg_CGLS:\r\n\t  recon_algorithm = new CCPi::cgls_3d(numberOfIterations);\r\n\t  break;\r\n\tcase CCPi::alg_SIRT:\r\n\t  recon_algorithm = new CCPi::sirt(numberOfIterations);\r\n\t  break;\r\n\tcase CCPi::alg_MLEM:\r\n\t  recon_algorithm = new CCPi::mlem(numberOfIterations);\r\n\t  break;\r\n\tcase CCPi::alg_CGLS_Tikhonov:\r\n\t  recon_algorithm = new CCPi::cgls_tikhonov(numberOfIterations, regularise);\r\n\t  break;\r\n\tcase CCPi::alg_CGLS_TVreg:\r\n\t  recon_algorithm = new CCPi::cgls_tv_reg(numberOfIterations, regularise);\r\n\t  break;\r\n\tdefault:\r\n\t\tnoerror = false;\r\n\t}\r\n\r\n\tif (noerror) {\r\n\t\tnoerror = false;\r\n\t\tbool phantom = false;\r\n\t\treal rotation_centre = -1.0;\r\n\t\tboost::filesystem::path p(filename);\r\n\t\tif (device->setup_experimental_geometry(p.parent_path().generic_string(), p.filename().generic_string(), rotation_centre, resolution, phantom)) {\r\n\t\t  int nx_voxels = 0;\r\n\t\t  int ny_voxels = 0;\r\n\t\t  int maxz_voxels = 0;\r\n\t\t  int nz_voxels = 0;\r\n\t\t  int block_size = 0;\r\n\t\t  int block_step = 0;\r\n\t\t  calculate_block_sizes(nx_voxels, ny_voxels, nz_voxels, maxz_voxels, block_size, block_step, 1,\r\n\t\t    0, resolution, device, recon_algorithm->supports_blocks());\r\n\t\t  int z_data_size = block_size * resolution;\r\n\t\t  int z_data_step = block_step * resolution;\r\n\t\t  device->set_v_block(z_data_size);\r\n\t\t  int block_offset = 0;\r\n\t\t  int z_data_offset = block_offset * resolution;\r\n\t\t\t\tif (device->finish_voxel_geometry(voxel_origin, voxel_size, nx_voxels, ny_voxels, nz_voxels)) {\r\n\t\t\t\t\tif (device->read_scans(p.parent_path().generic_string(), 0, z_data_size, true, phantom)) {\r\n\t\t\t\t\t\tvoxels = new voxel_data(boost::extents[nx_voxels][ny_voxels][nz_voxels], boost::c_storage_order());\r\n\t\t\t\t\t\tinit_data(*voxels, nx_voxels, ny_voxels, nz_voxels);\r\n\t\t\t\t\t\tif (bBeamHardening)\r\n\t\t\t\t\t\t\tdevice->apply_beam_hardening();\r\n\t\t\t\t\t\tnoerror = recon_algorithm->reconstruct(device, *voxels, voxel_origin, voxel_size);\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t}\r\n\t}\r\n\tif (!noerror)\r\n\t\tdelete voxels;\r\n\treturn noerror;\r\n}\r\n\r\nbool CCPi::ReconstructionImpl::saveResults(std::string outputFilename, CCPi::output_format outputFormat)\r\n{\r\n\tbool clamp_output = true;\r\n\tconst voxel_data::size_type *s = voxels->shape();\r\n\tclamp_min(*voxels, 0.0, s[0], s[1], s[2]);\r\n\tCCPi::write_results(outputFilename, *voxels, voxel_origin, voxel_size, 0, (int)s[2], outputFormat, clamp_output);\r\n\treturn true;\r\n}", "meta": {"hexsha": "0296c19d894fe0a677130a3ad5ebc87d4f0d0d78", "size": 4542, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Wrappers/Qt/src/ReconstructionImpl.cpp", "max_stars_repo_name": "vais-ral/CCPi-Reconstruction", "max_stars_repo_head_hexsha": "6c9f5eb9af308981b6d1c910dc1a38e8f6e83acd", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-11-09T11:58:32.000Z", "max_stars_repo_stars_event_max_datetime": "2018-11-09T11:58:32.000Z", "max_issues_repo_path": "Wrappers/Qt/src/ReconstructionImpl.cpp", "max_issues_repo_name": "vais-ral/CCPi-Reconstruction", "max_issues_repo_head_hexsha": "6c9f5eb9af308981b6d1c910dc1a38e8f6e83acd", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 8.0, "max_issues_repo_issues_event_min_datetime": "2018-05-22T12:58:27.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-15T14:54:04.000Z", "max_forks_repo_path": "Wrappers/Qt/src/ReconstructionImpl.cpp", "max_forks_repo_name": "vais-ral/CCPi-Reconstruction", "max_forks_repo_head_hexsha": "6c9f5eb9af308981b6d1c910dc1a38e8f6e83acd", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-01-11T12:04:53.000Z", "max_forks_repo_forks_event_max_datetime": "2019-01-11T12:04:53.000Z", "avg_line_length": 26.4069767442, "max_line_length": 148, "alphanum_fraction": 0.7073976222, "num_tokens": 1233, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7606506635289835, "lm_q2_score": 0.4571367168274948, "lm_q1q2_score": 0.34772134697829493}}
{"text": "/*\n * Copyright (c) 2012, Daniel Claes, Maastricht University\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n *     * Redistributions of source code must retain the above copyright\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 Maastricht University 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\n\n#include \"collvoid_local_planner/clearpath.h\"\n#include <ros/ros.h>\n#include <float.h>\n#include <boost/foreach.hpp>\n\nnamespace collvoid {\n\n\n    // VO createObstacleVO(Vector2& position1, const std::vector<Vector2>& footprint1,Vector2& vel1,  Vector2& position2, const std::vector<Vector2>& footprint2){\n    //   VO result;\n    //   std::vector<Vector2> mink_sum = minkowskiSum(footprint1, footprint2);\n\n    //   Vector2 rel_position = position2 - position1;\n\n    //   Vector2 rel_position_normal = normal(rel_position);\n    //   double min_dist = abs(rel_position);\n\n    //   for (int i = 0; i< (int) mink_sum.size(); i++){\n    //     Vector2 project_on_rel_position = intersectTwoLines(Vector2(0.0, 0.0), rel_position, rel_position + mink_sum[i], rel_position_normal);\n    //     double dist = abs(project_on_rel_position);\n    //     if (project_on_rel_position * rel_position < EPSILON){\n    // \t//\tROS_ERROR(\"Collision?\");\n    // \tdist = -dist;\n\n    //     }\n\n    //     if (dist < min_dist) {\n    // \tmin_dist = dist;\n    //     }\n    //   }\n    //   result.left_leg_dir = - normalize(rel_position_normal);\n    //   result.right_leg_dir = - result.left_leg_dir;\n    //   result.relative_position = rel_position;\n    //   result.combined_radius = abs(rel_position) - min_dist;\n\n    //   result.point = normalize(rel_position) * min_dist; // * std::max(1 - abs(vel1), 0.0);\n    //   result.trunc_left = result.point;\n    //   result.trunc_right = result.point;\n    //   result.trunc_line_center = result.point;\n\n    //   return result;\n\n    // }\n\n\n\n\n    VO createObstacleVO(Vector2 &position1, double radius1, const std::vector<Vector2> &footprint1, Vector2 &obst1,\n                        Vector2 &obst2) {\n        VO result;\n\n        Vector2 position_obst = 0.5 * (obst1 + obst2);\n\n        std::vector<Vector2> obst;\n        obst.push_back(obst1 - position_obst);\n        obst.push_back(obst2 - position_obst);\n\n        std::vector<Vector2> mink_sum = minkowskiSum(footprint1, obst);\n\n        Vector2 min_left, min_right;\n        double min_ang = 0.0;\n        double max_ang = 0.0;\n        Vector2 rel_position = position_obst - position1;\n\n        Vector2 rel_position_normal = normal(rel_position);\n        double min_dist = abs(rel_position);\n\n        for (int i = 0; i < (int) mink_sum.size(); i++) {\n            double angle = angleBetween(rel_position, rel_position + mink_sum[i]);\n            if (rightOf(Vector2(0.0, 0.0), rel_position, rel_position + mink_sum[i])) {\n                if (-angle < min_ang) {\n                    min_right = rel_position + mink_sum[i];\n                    min_ang = -angle;\n                }\n            }\n            else {\n                if (angle > max_ang) {\n                    min_left = rel_position + mink_sum[i];\n                    max_ang = angle;\n                }\n            }\n            Vector2 project_on_rel_position = intersectTwoLines(Vector2(0.0, 0.0), rel_position,\n                                                                rel_position + mink_sum[i], rel_position_normal);\n            double dist = abs(project_on_rel_position);\n            if (project_on_rel_position * rel_position < -EPSILON) {\n                //\tROS_ERROR(\"Collision?\");\n                dist = -dist;\n\n            }\n\n            if (dist < min_dist) {\n                min_dist = dist;\n            }\n        }\n        if (min_dist < 0) {\n            result.left_leg_dir = -normalize(obst1 - obst2);\n            result.right_leg_dir = -result.left_leg_dir;\n\n            result.point = rel_position - 1.5 * radius1 * normal(result.left_leg_dir);\n            result.trunc_left = result.point;\n            result.trunc_right = result.point;\n            return result;\n\n        }\n\n        double ang_rel = atan2(rel_position.y(), rel_position.x());\n        result.left_leg_dir = Vector2(cos(ang_rel + max_ang), sin(ang_rel + max_ang));\n        result.right_leg_dir = Vector2(cos(ang_rel + min_ang), sin(ang_rel + min_ang));\n\n        result.left_leg_dir = rotateVectorByAngle(result.left_leg_dir, 0.15);\n        result.right_leg_dir = rotateVectorByAngle(result.right_leg_dir, -0.05);\n\n\n        //double ang_between = angleBetween(result.right_leg_dir, result.left_leg_dir);\n        //double opening_ang = ang_rel + min_ang + (ang_between) / 2.0;\n\n        // Vector2 dir_center = Vector2(cos(opening_ang), sin(opening_ang));\n        // min_dist = abs(rel_position);\n        // Vector2 min_point = rel_position;\n        // for(int i = 0; i< (int)mink_sum.size(); i++) {\n        //   Vector2 proj_on_center = intersectTwoLines(Vector2(0.0,0.0), dir_center, rel_position+mink_sum[i], normal(dir_center));\n        //   if (abs(proj_on_center) < min_dist) {\n        // \tmin_dist = abs(proj_on_center);\n        // \tmin_point = rel_position+mink_sum[i];\n        //   }\n\n        // }\n\n        //result.left_leg_dir = rotateVectorByAngle(normalize(min), 0.1);\n        //result.right_leg_dir = rotateVectorByAngle(normalize(max), -0.1);\n\n        result.relative_position = rel_position;\n        result.combined_radius = abs(rel_position) - min_dist;\n        result.point = Vector2(0, 0);\n\n        result.trunc_left = intersectTwoLines(result.point, result.left_leg_dir,\n                                              result.combined_radius / 2.0 * normalize(rel_position), obst2 - obst1);\n        result.trunc_right = intersectTwoLines(result.point, result.right_leg_dir,\n                                               result.combined_radius / 2.0 * normalize(rel_position), obst2 - obst1);\n\n        //result = createTruncVO(result, 6.0);\n        return result;\n\n    }\n\n    // VO createObstacleVO(Vector2& position1, double radius1,Vector2& vel1,  Vector2& position2, double radius2){\n    //   VO result;\n\n    //   Vector2 rel_position = position2 - position1;\n\n    //   Vector2 rel_position_normal = normal(rel_position);\n\n    //   result.left_leg_dir = - normalize(rel_position_normal);\n    //   result.right_leg_dir = - result.left_leg_dir;\n    //   result.relative_position = rel_position;\n    //   result.combined_radius = radius1 + radius2;\n\n    //   result.point = normalize(rel_position) * (abs(rel_position) - result.combined_radius); // * std::max(1 - abs(vel1), 0.0);\n    //   result.trunc_left = result.point;\n    //   result.trunc_right = result.point;\n    //   result.trunc_line_center = result.point;\n\n    //   return result;\n\n    // }\n\n\n    VO createVO(Vector2 &position1, const std::vector<Vector2> &footprint1, Vector2 &position2,\n                const std::vector<Vector2> &footprint2, Vector2 &vel2) {\n        VO result;\n        std::vector<Vector2> mink_sum = minkowskiSum(footprint1, footprint2);\n\n        Vector2 min_left, min_right;\n        double min_ang = 0.0;\n        double max_ang = 0.0;\n        Vector2 rel_position = position2 - position1;\n\n        Vector2 rel_position_normal = normal(rel_position);\n        double min_dist = abs(rel_position);\n\n        for (int i = 0; i < (int) mink_sum.size(); i++) {\n            double angle = angleBetween(rel_position, rel_position + mink_sum[i]);\n            if (rightOf(Vector2(0.0, 0.0), rel_position, rel_position + mink_sum[i])) {\n                if (-angle < min_ang) {\n                    min_right = rel_position + mink_sum[i];\n                    min_ang = -angle;\n                }\n            }\n            else {\n                if (angle > max_ang) {\n                    min_left = rel_position + mink_sum[i];\n                    max_ang = angle;\n                }\n            }\n            Vector2 project_on_rel_position = intersectTwoLines(Vector2(0.0, 0.0), rel_position,\n                                                                rel_position + mink_sum[i], rel_position_normal);\n            double dist = abs(project_on_rel_position);\n            if (project_on_rel_position * rel_position < -EPSILON) {\n                //\tROS_ERROR(\"Collision?\");\n                dist = -dist;\n\n            }\n\n            if (dist < min_dist) {\n                min_dist = dist;\n            }\n        }\n        if (min_dist < 0) {\n            result.left_leg_dir = -normalize(rel_position_normal);\n            result.right_leg_dir = -result.left_leg_dir;\n            result.relative_position = rel_position;\n            result.combined_radius = abs(rel_position) - min_dist;\n            result.point = vel2;\n            return result;\n        }\n\n        double ang_rel = atan2(rel_position.y(), rel_position.x());\n        result.left_leg_dir = Vector2(cos(ang_rel + max_ang), sin(ang_rel + max_ang));\n        result.right_leg_dir = Vector2(cos(ang_rel + min_ang), sin(ang_rel + min_ang));\n\n        result.left_leg_dir = rotateVectorByAngle(result.left_leg_dir, 0.15);\n        result.right_leg_dir = rotateVectorByAngle(result.right_leg_dir, -0.05);\n\n\n        double ang_between = angleBetween(result.right_leg_dir, result.left_leg_dir);\n        double opening_ang = ang_rel + min_ang + (ang_between) / 2.0;\n\n        Vector2 dir_center = Vector2(cos(opening_ang), sin(opening_ang));\n        min_dist = abs(rel_position);\n        Vector2 min_point = rel_position;\n        for (int i = 0; i < (int) mink_sum.size(); i++) {\n            Vector2 proj_on_center = intersectTwoLines(Vector2(0.0, 0.0), dir_center, rel_position + mink_sum[i],\n                                                       normal(dir_center));\n            if (abs(proj_on_center) < min_dist) {\n                min_dist = abs(proj_on_center);\n                min_point = rel_position + mink_sum[i];\n            }\n\n        }\n\n        //ROS_ERROR(\"min_right %f, %f, min_left %f,%f,\", min_right.x(), min_right.y(), min_left.x(), min_left.y());\n        double center_p, radius;\n        Vector2 center_r;\n        //test left/right\n        if (abs(min_left) < abs(min_right)) {\n            center_p = abs(min_left) / cos(ang_between / 2.0);\n            radius = tan(ang_between / 2.0) * abs(min_left);\n            center_r = center_p * dir_center;\n        }\n        else {\n            center_p = abs(min_right) / cos(ang_between / 2.0);\n            center_r = center_p * dir_center;\n            radius = tan(ang_between / 2.0) * abs(min_right);\n        }\n        //check min_point, if failed stupid calc for new radius and point;\n        if (abs(min_point - center_r) > radius) {\n            double gamma = min_point.x() * dir_center.x() + min_point.y() * dir_center.y();\n            double sqrt_exp = absSqr(min_point) / (sqr(sin(ang_between / 2.0)) - 1) +\n                              sqr(gamma / (sqr(sin(ang_between / 2.0)) - 1));\n            if (fabs(sqrt_exp) < EPSILON) {\n                sqrt_exp = 0;\n            }\n            if (sqrt_exp >= 0) {\n                center_p = -gamma / (sqr(sin(ang_between / 2.0)) - 1) + std::sqrt(sqrt_exp);\n                center_r = center_p * dir_center;\n                radius = abs(min_point - center_r);\n            }\n            else {\n                ROS_ERROR(\"ang = %f, sqrt_ext = %f\", ang_between, sqrt_exp);\n                ROS_ERROR(\"rel position %f, %f, radius %f, center_p %f\", rel_position.x(), rel_position.y(), radius,\n                          center_p);\n            }\n        }\n        //result.relative_position = rel_position;\n        //result.combined_radius = abs(rel_position) - min_dist;\n\n        result.relative_position = center_r;\n        result.combined_radius = radius;\n        result.point = vel2;\n        return result;\n\n    }\n\n\n    VO createRVO(Vector2 &position1, const std::vector<Vector2> &footprint1, Vector2 &vel1, Vector2 &position2,\n                 const std::vector<Vector2> &footprint2, Vector2 &vel2) {\n        VO result = createVO(position1, footprint1, position2, footprint2, vel2);\n        result.point = 0.5 * (vel1 + vel2); //TODO add uncertainty\n        return result;\n\n\n    }\n\n    VO createHRVO(Vector2 &position1, const std::vector<Vector2> &footprint1, Vector2 &vel1, Vector2 &position2,\n                  const std::vector<Vector2> &footprint2, Vector2 &vel2) {\n        //std::vector<Vector2> mink_sum = minkowskiSum(footprint1, footprint2);\n        //std::vector<Vector2> empty;\n        VO result = createRVO(position1, footprint1, vel1, position2, footprint2, vel2);\n\n\n        Vector2 rel_velocity = vel1 - vel2;\n        // Vector2 rel_position = position2 - position1;\n\n        // //Test if origin is inside mink_sum (Then we are in collision)!!!)\n        // bool inside = true;\n        // for (int i = 0; i<(int)mink_sum.size(); i++){\n        //   int j = i+1;\n        //   if (j == (int) mink_sum.size())\n        // \tj = 0;\n        //   if (leftOf(rel_position + mink_sum[i], mink_sum[j]-mink_sum[i], Vector2(0.0,0.0))) {\n        // \tinside = false;\n\n        // \tbreak;\n        //   }\n        // }\n        // Vector2 new_position = position1;\n        // int max_tries = 0;\n        // while (result.combined_radius > abs(result.relative_position) && max_tries > 0) {\n        //   //      ROS_ERROR(\"inside minkowskiSum!!\");\n        //   new_position = new_position - normalize(result.relative_position) * 0.1;\n        //   //result = createRVO(new_position, footprint1,vel1, position2, footprint2, vel2);\n        //   max_tries--;\n        // }\n        if (result.combined_radius > abs(result.relative_position)) {\n            //ROS_ERROR(\"comb.rad. %f, relPos %f, %f (abs = %f)\", result.combined_radius, result.relative_position.x(), result.relative_position.y(), abs(result.relative_position));\n            //result.point = 0.5 * (vel2 + vel1) -  ((result.combined_radius - abs(result.relative_position)) / (2.0f * 0.1)) * normalize(result.relative_position);\n            return result;\n\n        }\n\n        if (leftOf(Vector2(0.0, 0.0), result.relative_position, rel_velocity)) { //left of centerline\n            result.point = intersectTwoLines(result.point, result.left_leg_dir, vel2,\n                                             result.right_leg_dir); // TODO add uncertainty\n\n        }\n        else { //right of centerline\n            result.point = intersectTwoLines(vel2, result.left_leg_dir, result.point,\n                                             result.right_leg_dir); // TODO add uncertainty\n        }\n\n        return result;\n\n\n    }\n\n\n    VO createVO(Vector2 &position1, const std::vector<Vector2> &footprint1, Vector2 &vel1, Vector2 &position2,\n                const std::vector<Vector2> &footprint2, Vector2 &vel2, int TYPE) {\n        if (TYPE == HRVOS) {\n            return createHRVO(position1, footprint1, vel1, position2, footprint2, vel2);\n        }\n        else if (TYPE == RVOS) {\n            return createRVO(position1, footprint1, vel1, position2, footprint2, vel2);\n        }\n        else {\n            return createVO(position1, footprint1, position2, footprint2, vel2);\n        }\n    }\n\n\n    VO createVO(Vector2 &position1, double radius1, Vector2 &vel1, Vector2 &position2, double radius2, Vector2 &vel2,\n                int TYPE) {\n        if (TYPE == HRVOS) {\n            return createHRVO(position1, radius1, vel1, position2, radius2, vel2);\n        }\n        else if (TYPE == RVOS) {\n            return createRVO(position1, radius1, vel1, position2, radius2, vel2);\n        }\n        else {\n            return createVO(position1, radius1, position2, radius2, vel2);\n        }\n    }\n\n\n    VO createVO(Vector2 &position1, double radius1, Vector2 &position2, double radius2, Vector2 &vel2) {\n        VO result;\n        Vector2 rel_position = position2 - position1;\n        double ang_to_other = atan(rel_position);\n        double combined_radius = radius2 + radius1;\n        double angle_of_opening;\n        if (abs(rel_position) < combined_radius) {\n            // angle_of_opening = M_PI/2.0-EPSILON;\n            result.left_leg_dir = -normalize(normal(rel_position));\n            result.right_leg_dir = -result.left_leg_dir;\n            // result.right_leg_dir = Vector2(std::cos(ang_to_other - angle_of_opening), std::sin(ang_to_other - angle_of_opening));\n            // result.left_leg_dir = Vector2(std::cos(ang_to_other + angle_of_opening), std::sin(ang_to_other + angle_of_opening));\n        }\n        else {\n            angle_of_opening = std::asin(combined_radius / abs(rel_position));\n            result.right_leg_dir = Vector2(std::cos(ang_to_other - angle_of_opening),\n                                           std::sin(ang_to_other - angle_of_opening));\n            result.left_leg_dir = Vector2(std::cos(ang_to_other + angle_of_opening),\n                                          std::sin(ang_to_other + angle_of_opening));\n        }\n        //    ROS_ERROR(\"angle_of_opening %f, combined_radius %f, rel_position %f\", angle_of_opening, combined_radius, abs(rel_position));\n        result.point = vel2;\n        result.relative_position = rel_position;\n        result.combined_radius = radius1 + radius2;\n\n        return result;\n    }\n\n    VO createRVO(Vector2 &position1, double radius1, Vector2 &vel1, Vector2 &position2, double radius2, Vector2 &vel2) {\n        VO result = createVO(position1, radius1, position2, radius2, vel2);\n        result.point = 0.5 * (vel1 + vel2); //TODO add uncertainty\n        return result;\n    }\n\n    VO createHRVO(Vector2 &position1, double radius1, Vector2 &vel1, Vector2 &position2, double radius2,\n                  Vector2 &vel2) {\n\n        VO result = createRVO(position1, radius1, vel1, position2, radius2, vel2);\n\n        Vector2 rel_velocity = vel1 - vel2;\n        Vector2 rel_position = position2 - position1;\n        if (abs(rel_position) < radius1 + radius2) {\n            result.point = 0.5 * (vel2 + vel1);\n            return result;\n        }\n\n        if (leftOf(Vector2(0.0, 0.0), rel_position, rel_velocity)) { //left of centerline\n            result.point = intersectTwoLines(result.point, result.left_leg_dir, vel2,\n                                             result.right_leg_dir); // TODO add uncertainty\n        }\n        else { //right of centerline\n            result.point = intersectTwoLines(vel2, result.left_leg_dir, result.point,\n                                             result.right_leg_dir); // TODO add uncertainty\n        }\n        return result;\n\n    }\n\n    VO createTruncVO(VO &vo, double time) {\n        VO result;\n        result.point = vo.point;\n        result.left_leg_dir = vo.left_leg_dir;\n        result.right_leg_dir = vo.right_leg_dir;\n        result.relative_position = vo.relative_position;\n        result.combined_radius = vo.combined_radius;\n        double trunc_radius = vo.combined_radius / time;\n        double angle_of_opening;\n\n        if (abs(vo.relative_position) < vo.combined_radius) {\n            result.trunc_left = result.point;\n            result.trunc_right = result.point;\n            result.trunc_line_center = result.point;\n            return result;\n        }\n        else {\n            angle_of_opening = std::asin(vo.combined_radius / abs(vo.relative_position));\n            double trunc_dist = trunc_radius / std::sin(angle_of_opening) - trunc_radius;\n            result.trunc_line_center = normalize(vo.relative_position) * trunc_dist;\n            Vector2 intersectLeft = intersectTwoLines(result.point + result.trunc_line_center,\n                                                      Vector2(result.trunc_line_center.y(),\n                                                              -result.trunc_line_center.x()), result.point,\n                                                      result.left_leg_dir);\n            result.trunc_left = intersectLeft;\n            result.trunc_right = intersectTwoLines(result.point + result.trunc_line_center,\n                                                   Vector2(result.trunc_line_center.y(), -result.trunc_line_center.x()),\n                                                   result.point, result.right_leg_dir);\n\n            return result;\n        }\n    }\n\n    bool isInsideVO(VO vo, Vector2 point, bool use_truncation) {\n        bool trunc = leftOf(vo.trunc_left, vo.trunc_right - vo.trunc_left, point);\n        if (abs(vo.trunc_left - vo.trunc_right) < EPSILON)\n            trunc = true;\n        return rightOf(vo.point, vo.left_leg_dir, point) && leftOf(vo.point, vo.right_leg_dir, point) &&\n               (!use_truncation || trunc);\n    }\n\n    bool isWithinAdditionalConstraints(const std::vector<Line> &additional_constraints, const Vector2 &point) {\n        BOOST_FOREACH(Line line, additional_constraints) {\n                        if (rightOf(line.point, line.dir, point)) {\n                            return false;\n                        }\n                    }\n        return true;\n    }\n\n\n    void addCircleLineIntersections(std::vector<VelocitySample> &samples, const Vector2 &pref_vel, double maxSpeed,\n                                    bool use_truncation, const Vector2 &point, const Vector2 &dir) {\n\n        double discriminant = sqr(maxSpeed) - sqr(det(point,\n                                                      dir)); // http://stackoverflow.com/questions/1073336/circle-line-collision-detection\n        if (discriminant > 0.0f) //intersection with line\n        {\n            double t1 = -(point * dir) + std::sqrt(discriminant); //first solution\n            double t2 = -(point * dir) - std::sqrt(discriminant); //second solution\n            //ROS_ERROR(\"Adding circle line dist %f, %f\", t1, t2);\n            Vector2 point1 = point + t1 * dir;\n            Vector2 point2 = point + t2 * dir;\n\n            if (t1 >= 0.0f) {\n                VelocitySample intersection_point;\n                intersection_point.velocity = point1;\n                intersection_point.dist_to_pref_vel = absSqr(pref_vel - intersection_point.velocity);\n                samples.push_back(intersection_point);\n            }\n            if (t2 >= 0.0f) {\n                VelocitySample intersection_point;\n                intersection_point.velocity = point2;\n                intersection_point.dist_to_pref_vel = absSqr(pref_vel - intersection_point.velocity);\n                samples.push_back(intersection_point);\n            }\n        }\n    }\n\n\n    void addRayVelocitySamples(std::vector<VelocitySample> &samples, const Vector2 &pref_vel, Vector2 point1,\n                               Vector2 dir1, Vector2 point2, Vector2 dir2, double max_speed, int TYPE) {\n        double r, s;\n\n        double x1, x2, x3, x4, y1, y2, y3, y4;\n        x1 = point1.x();\n        y1 = point1.y();\n        x2 = x1 + dir1.x();\n        y2 = y1 + dir1.y();\n        x3 = point2.x();\n        y3 = point2.y();\n        x4 = x3 + dir2.x();\n        y4 = y3 + dir2.y();\n\n        double det = (((x2 - x1) * (y4 - y3)) - (y2 - y1) * (x4 - x3));\n\n        if (det == 0.0) {\n            //ROS_WARN(\"No Intersection found\");\n            return;\n        }\n        if (det != 0) {\n            r = (((y1 - y3) * (x4 - x3)) - (x1 - x3) * (y4 - y3)) / det;\n            s = (((y1 - y3) * (x2 - x1)) - (x1 - x3) * (y2 - y1)) / det;\n\n            if ((TYPE == LINELINE) || (TYPE == RAYLINE && r >= 0) || (TYPE == SEGMENTLINE && r >= 0 && r <= 1) ||\n                (TYPE == RAYRAY && r >= 0 && s >= 0) ||\n                (TYPE == RAYSEGMENT && r >= 0 && s >= 0 && s <= 1) ||\n                (TYPE == SEGMENTSEGMENT && r >= 0 && s >= 0 && r <= 1 && s <= 1)) {\n\n\n                VelocitySample intersection_point;\n                intersection_point.velocity = Vector2(x1 + r * (x2 - x1), y1 + r * (y2 - y1));\n                intersection_point.dist_to_pref_vel = absSqr(pref_vel - intersection_point.velocity);\n                if (absSqr(intersection_point.velocity) < sqr(1.2 * max_speed)) {\n                    //ROS_ERROR(\"adding VelocitySample\");\n                    samples.push_back(intersection_point);\n                    //ROS_ERROR(\"size of VelocitySamples %d\", (int) samples->size());\n\n                }\n            }\n        }\n    }\n\n\n    void createSamplesWithinMovementConstraints(std::vector<VelocitySample> &samples, double cur_vel_x,\n                                                double cur_vel_y, double cur_vel_theta, double acc_lim_x,\n                                                double acc_lim_y, double acc_lim_theta, double min_vel_x,\n                                                double max_vel_x, double min_vel_y, double max_vel_y,\n                                                double min_vel_theta, double max_vel_theta, double heading,\n                                                Vector2 pref_vel, double sim_period, int num_samples, bool holo_robot) {\n\n        if (holo_robot) {//holonomic drive\n            double min_x, max_x, min_y, max_y;\n\n            min_x = std::max(-max_vel_x, cur_vel_x - acc_lim_x * sim_period);\n            max_x = std::min(max_vel_x, cur_vel_x + acc_lim_x * sim_period);\n\n            min_y = std::max(-max_vel_y, cur_vel_y - acc_lim_y * sim_period);\n            max_y = std::min(max_vel_y, cur_vel_y + acc_lim_y * sim_period);\n\n            double step_x, step_y;\n\n            int num_samples_per_dir = (int) std::sqrt(num_samples);\n\n            step_x = (max_x - min_x) / num_samples_per_dir;\n            step_y = (max_y - min_y) / num_samples_per_dir;\n\n            for (int i = 0; i < num_samples_per_dir; i++) {\n                for (int j = 0; j < num_samples_per_dir; j++) {\n                    VelocitySample p;\n                    Vector2 vel = Vector2(min_x + i * step_x, min_y + j * step_y);\n                    p.dist_to_pref_vel = absSqr(vel - Vector2(cur_vel_x, cur_vel_y));\n                    p.velocity = rotateVectorByAngle(Vector2(min_x + i * step_x, min_y + j * step_y), heading);\n                    samples.push_back(p);\n                }\n\n            }\n\n        }\n        else {\n            double min_x, max_x, min_theta, max_theta;\n\n            min_x = -0.3;//std::max(-0.2, cur_vel_x - acc_lim_x * sim_period);\n            max_x = std::min(max_vel_x, cur_vel_x + acc_lim_x * sim_period);\n\n            //cur_vel_theta = 0.0; //HACK\n\n            min_theta = -2 * max_vel_theta;//std::max(-max_vel_theta, cur_vel_theta - acc_lim_theta * sim_period);\n            max_theta = 2 * max_vel_theta;//std::min(max_vel_theta, cur_vel_theta + acc_lim_theta * sim_period);\n\n            double step_x, step_theta;\n\n            int num_samples_per_dir = (int) std::sqrt(num_samples);\n\n            step_x = (max_x - min_x) / num_samples_per_dir;\n            step_theta = (max_theta - min_theta) / num_samples_per_dir;\n\n            // ROS_ERROR(\"heading %f, min_theta %f, %f cur_vel_theta %f\", heading, min_theta, max_theta, cur_vel_theta);\n\n            for (int i = 0; i < num_samples_per_dir; i++) {\n                for (int j = 0; j < num_samples_per_dir; j++) {\n                    VelocitySample p;\n                    double th_dif = min_theta + j * step_theta;\n                    double x_dif = (min_x + i * step_x) * cos(heading + th_dif / 2.0);\n                    double y_dif = (min_x + i * step_x) * sin(heading + th_dif / 2.0);\n                    p.dist_to_pref_vel = absSqr(Vector2(cur_vel_x, cur_vel_y));\n\n                    p.velocity = Vector2(x_dif, y_dif);\n                    //p.velocity = rotateVectorByAngle(Vector2(min_x + i* step_x, 0), heading + min_theta + j * step_theta);\n\n                    samples.push_back(p);\n                }\n\n            }\n        }\n\n    }\n\n    Vector2 calculateNewVelocitySampled(std::vector<VelocitySample> &samples, const std::vector<VO> &truncated_vos,\n                                        const Vector2 &pref_vel, double max_speed, bool use_truncation) {\n\n        // VelocitySample pref_vel_sample;\n        // pref_vel_sample.velocity = pref_vel;\n        // samples.push_back(pref_vel_sample);\n\n\n        // VelocitySample null_vel;\n        // null_vel.velocity = Vector2(0,0);\n        // null_vel.dist_to_pref_vel = absSqr(pref_vel);\n        // samples.push_back(null_vel);\n\n        double min_cost = DBL_MAX;\n        Vector2 best_vel;\n\n        for (int i = 0; i < (int) samples.size(); i++) {\n            VelocitySample cur = samples[i];\n            double cost = calculateVelCosts(cur.velocity, truncated_vos, pref_vel, max_speed, use_truncation);\n            cost += cur.dist_to_pref_vel;\n            if (cost < min_cost) {\n                min_cost = cost;\n                best_vel = cur.velocity;\n            }\n        }\n        //ROS_ERROR(\"min_cost %f\", min_cost);\n        return best_vel;\n    }\n\n    double calculateVelCosts(const Vector2 &test_vel, const std::vector<VO> &truncated_vos, const Vector2 &pref_vel,\n                             double max_speed, bool use_truncation) {\n        double cost = 0.0;\n        double COST_IN_VO = 1000.0;\n        for (int j = 0; j < (int) truncated_vos.size(); j++) {\n            if (isInsideVO(truncated_vos[j], test_vel, use_truncation)) {\n                cost += (truncated_vos.size() - j) * COST_IN_VO;\n            }\n        }\n        cost += absSqr(pref_vel - test_vel);\n        return cost;\n    }\n\n\n    Vector2 calculateClearpathVelocity(std::vector<VelocitySample> &samples, const std::vector<VO> &truncated_vos,\n                                       const std::vector<Line> &additional_constraints, const Vector2 &pref_vel,\n                                       double max_speed, bool use_truncation) {\n\n        if (!isWithinAdditionalConstraints(additional_constraints, pref_vel)) {\n            BOOST_FOREACH (Line line, additional_constraints) {\n                            VelocitySample pref_vel_sample;\n                            pref_vel_sample.velocity = intersectTwoLines(line.point, line.dir, pref_vel,\n                                                                         Vector2(line.dir.y(), -line.dir.x()));\n                            pref_vel_sample.dist_to_pref_vel = absSqr(pref_vel - pref_vel_sample.velocity);\n                            samples.push_back(pref_vel_sample);\n                        }\n        }\n        else {\n            VelocitySample pref_vel_sample;\n            pref_vel_sample.velocity = pref_vel;\n            pref_vel_sample.dist_to_pref_vel = 0;\n            samples.push_back(pref_vel_sample);\n        }\n        VelocitySample null_vel_sample;\n        null_vel_sample.velocity = Vector2(0, 0);\n        null_vel_sample.dist_to_pref_vel = absSqr(pref_vel);\n        samples.push_back(null_vel_sample);\n\n        BOOST_FOREACH(Line line, additional_constraints) {\n                        BOOST_FOREACH(Line line2, additional_constraints) {\n                                        addRayVelocitySamples(samples, pref_vel, line.point, line.dir, line2.point,\n                                                              line2.dir, max_speed, LINELINE);\n                                    }\n                    }\n\n        for (int i = 0; i < (int) truncated_vos.size(); i++) {\n            if (isInsideVO(truncated_vos[i], pref_vel, use_truncation)) {\n\n                VelocitySample leg_projection;\n                if (leftOf(truncated_vos[i].point, truncated_vos[i].relative_position,\n                           pref_vel)) { //left of centerline, project on left leg\n                    leg_projection.velocity = intersectTwoLines(truncated_vos[i].point, truncated_vos[i].left_leg_dir,\n                                                                pref_vel, Vector2(truncated_vos[i].left_leg_dir.y(),\n                                                                                  -truncated_vos[i].left_leg_dir.x()));\n                }\n                else { //project on right leg\n                    leg_projection.velocity = intersectTwoLines(truncated_vos[i].point, truncated_vos[i].right_leg_dir,\n                                                                pref_vel, Vector2(truncated_vos[i].right_leg_dir.y(),\n                                                                                  -truncated_vos[i].right_leg_dir.x()));\n                }\n\n                //if(absSqr(leg_projection.velocity) < max_speed) { //only add if below max_speed\n                leg_projection.dist_to_pref_vel = absSqr(pref_vel - leg_projection.velocity);\n                samples.push_back(leg_projection);\n                //}\n\n                if (use_truncation) {\n                    addRayVelocitySamples(samples, pref_vel, pref_vel, -truncated_vos[i].relative_position,\n                                          truncated_vos[i].trunc_left,\n                                          truncated_vos[i].trunc_right - truncated_vos[i].trunc_left, max_speed,\n                                          RAYSEGMENT);\n                }\n            }\n        }\n\n        // for (int i= 0 ; i< (int) truncated_vos.size(); i++){ //intersect with max_speed circle\n        //   if (!use_truncation) {\n        // \taddCircleLineIntersections(samples, pref_vel, max_speed, use_truncation, truncated_vos[i].point, truncated_vos[i].left_leg_dir); //intersect with left leg_dir\n        // \taddCircleLineIntersections(samples, pref_vel, max_speed, use_truncation, truncated_vos[i].point, truncated_vos[i].right_leg_dir); //intersect with right_leg_dir\n        //   }\n        //   else {\n        // \taddCircleLineIntersections(samples, pref_vel, max_speed, use_truncation, truncated_vos[i].trunc_left, truncated_vos[i].left_leg_dir); //intersect with left leg_dir\n        // \taddCircleLineIntersections(samples, pref_vel, max_speed, use_truncation, truncated_vos[i].trunc_right, truncated_vos[i].right_leg_dir); //intersect with right_leg_dir\n\n        //  \t//addCircleLineIntersections(samples, pref_vel, max_speed, use_truncation, truncated_vos[i].trunc_left, truncated_vos[i].trunc_right - truncated_vos[i].trunc_left, i, truncated_vos[i]); //intersect with truncation line\n        //   }\n        // }\n\n        for (int i = 0; i < (int) truncated_vos.size(); i++) {\n            for (int j = 0; j < (int) additional_constraints.size(); j++) {\n                if (!use_truncation) {\n                    addRayVelocitySamples(samples, pref_vel, truncated_vos[i].point, truncated_vos[i].left_leg_dir,\n                                          additional_constraints[j].point, additional_constraints[j].dir, max_speed,\n                                          RAYLINE);\n                    addRayVelocitySamples(samples, pref_vel, truncated_vos[i].point, truncated_vos[i].right_leg_dir,\n                                          additional_constraints[j].point, additional_constraints[j].dir, max_speed,\n                                          RAYLINE);\n                }\n                else {\n                    addRayVelocitySamples(samples, pref_vel, truncated_vos[i].trunc_left, truncated_vos[i].left_leg_dir,\n                                          additional_constraints[j].point, additional_constraints[j].dir, max_speed,\n                                          RAYLINE);\n                    addRayVelocitySamples(samples, pref_vel, truncated_vos[i].trunc_right,\n                                          truncated_vos[i].right_leg_dir, additional_constraints[j].point,\n                                          additional_constraints[j].dir, max_speed, RAYLINE);\n                    addRayVelocitySamples(samples, pref_vel, truncated_vos[i].trunc_left,\n                                          truncated_vos[i].trunc_right - truncated_vos[i].trunc_left,\n                                          additional_constraints[j].point, additional_constraints[j].dir, max_speed,\n                                          SEGMENTLINE);\n                }\n            }\n\n            for (int j = i + 1; j < (int) truncated_vos.size(); j++) {\n\n                if (!use_truncation) {\n                    addRayVelocitySamples(samples, pref_vel, truncated_vos[i].point, truncated_vos[i].left_leg_dir,\n                                          truncated_vos[j].point, truncated_vos[j].left_leg_dir, max_speed, RAYRAY);\n                    addRayVelocitySamples(samples, pref_vel, truncated_vos[i].point, truncated_vos[i].left_leg_dir,\n                                          truncated_vos[j].point, truncated_vos[j].right_leg_dir, max_speed, RAYRAY);\n                    addRayVelocitySamples(samples, pref_vel, truncated_vos[i].point, truncated_vos[i].right_leg_dir,\n                                          truncated_vos[j].point, truncated_vos[j].left_leg_dir, max_speed, RAYRAY);\n                    addRayVelocitySamples(samples, pref_vel, truncated_vos[i].point, truncated_vos[i].right_leg_dir,\n                                          truncated_vos[j].point, truncated_vos[j].right_leg_dir, max_speed, RAYRAY);\n\n                }\n                else {\n                    addRayVelocitySamples(samples, pref_vel, truncated_vos[i].trunc_left, truncated_vos[i].left_leg_dir,\n                                          truncated_vos[j].trunc_left, truncated_vos[j].left_leg_dir, max_speed,\n                                          RAYRAY);\n                    addRayVelocitySamples(samples, pref_vel, truncated_vos[i].trunc_left, truncated_vos[i].left_leg_dir,\n                                          truncated_vos[j].trunc_right, truncated_vos[j].right_leg_dir, max_speed,\n                                          RAYRAY);\n                    addRayVelocitySamples(samples, pref_vel, truncated_vos[i].trunc_right,\n                                          truncated_vos[i].right_leg_dir, truncated_vos[j].trunc_left,\n                                          truncated_vos[j].left_leg_dir, max_speed, RAYRAY);\n                    addRayVelocitySamples(samples, pref_vel, truncated_vos[i].trunc_right,\n                                          truncated_vos[i].right_leg_dir, truncated_vos[j].trunc_left,\n                                          truncated_vos[j].right_leg_dir, max_speed, RAYRAY);\n\n\n                    addRayVelocitySamples(samples, pref_vel, truncated_vos[i].trunc_left, truncated_vos[i].left_leg_dir,\n                                          truncated_vos[j].trunc_left,\n                                          truncated_vos[j].trunc_right - truncated_vos[j].trunc_left, max_speed,\n                                          RAYSEGMENT); //left trunc\n                    addRayVelocitySamples(samples, pref_vel, truncated_vos[j].trunc_left, truncated_vos[j].left_leg_dir,\n                                          truncated_vos[i].trunc_left,\n                                          truncated_vos[i].trunc_right - truncated_vos[i].trunc_left, max_speed,\n                                          RAYSEGMENT); //trunc left\n\n                    addRayVelocitySamples(samples, pref_vel, truncated_vos[i].trunc_right,\n                                          truncated_vos[i].right_leg_dir, truncated_vos[j].trunc_left,\n                                          truncated_vos[j].trunc_right - truncated_vos[j].trunc_left, max_speed,\n                                          RAYSEGMENT); //right trunc\n                    addRayVelocitySamples(samples, pref_vel, truncated_vos[j].trunc_right,\n                                          truncated_vos[j].right_leg_dir, truncated_vos[i].trunc_left,\n                                          truncated_vos[i].trunc_right - truncated_vos[i].trunc_left, max_speed,\n                                          RAYSEGMENT); //trunc right\n\n                    addRayVelocitySamples(samples, pref_vel, truncated_vos[i].trunc_left,\n                                          truncated_vos[i].trunc_right - truncated_vos[i].trunc_left,\n                                          truncated_vos[j].trunc_left,\n                                          truncated_vos[j].trunc_right - truncated_vos[j].trunc_left, max_speed,\n                                          SEGMENTSEGMENT); //trunc trunc\n\n\n                }\n\n            }\n        }\n\n\n        //    ROS_ERROR(\"projection list length  = %d\", samples.size());\n\n        std::sort(samples.begin(), samples.end(), compareVelocitySamples);\n\n        Vector2 new_vel; // = pref_vel;\n\n        bool valid = false;\n        bool foundOutside = false;\n        bool outside = true;\n        int optimal = -1;\n\n        for (int i = 0; i < (int) samples.size(); i++) {\n            outside = true;\n            valid = true;\n            if (!isWithinAdditionalConstraints(additional_constraints, samples[i].velocity)) {\n                outside = false;\n            }\n\n\n            for (int j = 0; j < (int) truncated_vos.size(); j++) {\n                if (isInsideVO(truncated_vos[j], samples[i].velocity, use_truncation)) {\n                    valid = false;\n                    if (j > optimal) {\n                        optimal = j;\n                        new_vel = samples[i].velocity;\n                    }\n                    break;\n                }\n            }\n            if (valid && outside) {\n                return samples[i].velocity;\n            }\n            if (valid && !outside && !foundOutside) {\n                optimal = truncated_vos.size();\n                new_vel = samples[i].velocity;\n                foundOutside = true;\n            }\n\n        }\n        //    ROS_INFO(\"selected j %d, of size %d\", optimal, (int) truncated_vos.size());\n\n\n        return new_vel;\n    }\n\n\n    std::vector<Vector2> minkowskiSum(const std::vector<Vector2> polygon1, const std::vector<Vector2> polygon2) {\n        std::vector<Vector2> result;\n        std::vector<ConvexHullPoint> convex_hull;\n\n\n        for (int i = 0; i < (int) polygon1.size(); i++) {\n            for (int j = 0; j < (int) polygon2.size(); j++) {\n                ConvexHullPoint p;\n                p.point = polygon1[i] + polygon2[j];\n                convex_hull.push_back(p);\n            }\n\n        }\n        convex_hull = convexHull(convex_hull, false);\n        for (int i = 0; i < (int) convex_hull.size(); i++) {\n            result.push_back(convex_hull[i].point);\n        }\n        return result;\n\n    }\n\n\n    bool compareVectorsLexigraphically(const ConvexHullPoint &v1, const ConvexHullPoint &v2) {\n        return v1.point.x() < v2.point.x() || (v1.point.x() == v2.point.x() && v1.point.y() < v2.point.y());\n    }\n\n    double cross(const ConvexHullPoint &O, const ConvexHullPoint &A, const ConvexHullPoint &B) {\n        return (A.point.x() - O.point.x()) * (B.point.y() - O.point.y()) -\n               (A.point.y() - O.point.y()) * (B.point.x() - O.point.x());\n    }\n\n    // Returns a list of points on the convex hull in counter-clockwise order.\n    // Note: the last point in the returned list is the same as the first one.\n    //Wikipedia Monotone chain...\n    std::vector<ConvexHullPoint> convexHull(std::vector<ConvexHullPoint> P, bool sorted) {\n        int n = P.size(), k = 0;\n        std::vector<ConvexHullPoint> result(2 * n);\n\n        // Sort points lexicographically\n        if (!sorted)\n            sort(P.begin(), P.end(), compareVectorsLexigraphically);\n\n        //    ROS_WARN(\"points length %d\", (int)P.size());\n\n        // Build lower hull\n        for (int i = 0; i < n; i++) {\n            while (k >= 2 && cross(result[k - 2], result[k - 1], P[i]) <= 0) k--;\n            result[k++] = P[i];\n        }\n\n        // Build upper hull\n        for (int i = n - 2, t = k + 1; i >= 0; i--) {\n            while (k >= t && cross(result[k - 2], result[k - 1], P[i]) <= 0) k--;\n            result[k++] = P[i];\n        }\n        result.resize(k);\n\n        return result;\n    }\n\n\n    bool compareVelocitySamples(const VelocitySample &p1, const VelocitySample &p2) {\n        return p1.dist_to_pref_vel < p2.dist_to_pref_vel;\n    }\n\n    Vector2 intersectTwoLines(Vector2 point1, Vector2 dir1, Vector2 point2, Vector2 dir2) {\n        double x1, x2, x3, x4, y1, y2, y3, y4;\n        x1 = point1.x();\n        y1 = point1.y();\n        x2 = x1 + dir1.x();\n        y2 = y1 + dir1.y();\n        x3 = point2.x();\n        y3 = point2.y();\n        x4 = x3 + dir2.x();\n        y4 = y3 + dir2.y();\n\n        double det = (x1 - x2) * (y3 - y4) - (y1 - y2) * (x3 - x4);\n\n        if (det == 0) {\n            return Vector2(0, 0); //TODO fix return NULL\n\n        }\n        double x_i = ((x3 - x4) * (x1 * y2 - y1 * x2) - (x1 - x2) * (x3 * y4 - y3 * x4)) / det;\n        double y_i = ((y3 - y4) * (x1 * y2 - y1 * x2) - (y1 - y2) * (x3 * y4 - y3 * x4)) / det;\n\n        return Vector2(x_i, y_i);\n    }\n\n    Vector2 intersectTwoLines(Line line1, Line line2) {\n        return intersectTwoLines(line1.point, line1.dir, line2.point, line2.dir);\n    }\n\n\n}\n", "meta": {"hexsha": "f95bd8a47c7974d0d2c01ef21843698713147549", "size": 45689, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "data/collvoid/collvoid_local_planner/src/clearpath.cpp", "max_stars_repo_name": "khairulislam/phys", "max_stars_repo_head_hexsha": "fc702520fcd3b23022b9253e7d94f878978b4500", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "data/collvoid/collvoid_local_planner/src/clearpath.cpp", "max_issues_repo_name": "khairulislam/phys", "max_issues_repo_head_hexsha": "fc702520fcd3b23022b9253e7d94f878978b4500", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "data/collvoid/collvoid_local_planner/src/clearpath.cpp", "max_forks_repo_name": "khairulislam/phys", "max_forks_repo_head_hexsha": "fc702520fcd3b23022b9253e7d94f878978b4500", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 45.5978043912, "max_line_length": 231, "alphanum_fraction": 0.5578366784, "num_tokens": 10690, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6791787121629466, "lm_q2_score": 0.5117166047041654, "lm_q1q2_score": 0.3475470245753706}}
{"text": "#pragma once\n\n#include <polyfem/Common.hpp>\n#include <polyfem/ElasticityUtils.hpp>\n\n#include <polyfem/ElementAssemblyValues.hpp>\n#include <polyfem/ElementBases.hpp>\n#include <polyfem/AutodiffTypes.hpp>\n#include <polyfem/Types.hpp>\n\n#include <Eigen/Dense>\n#include <array>\n\nnamespace polyfem\n{\n\t// Similar to HookeLinear but with non-linear stress strain: C:½(F+Fᵀ+FᵀF)\n\tclass SaintVenantElasticity\n\t{\n\tpublic:\n\t\tSaintVenantElasticity();\n\n\t\tEigen::MatrixXd assemble_hessian(const ElementAssemblyValues &vals, const Eigen::MatrixXd &displacement, const QuadratureVector &da) const;\n\t\tEigen::VectorXd assemble_grad(const ElementAssemblyValues &vals, const Eigen::MatrixXd &displacement, const QuadratureVector &da) const;\n\t\tdouble compute_energy(const ElementAssemblyValues &vals, const Eigen::MatrixXd &displacement, const QuadratureVector &da) const;\n\n\t\tEigen::Matrix<double, Eigen::Dynamic, 1, 0, 3, 1>\n\t\tcompute_rhs(const AutodiffHessianPt &pt) const;\n\n\t\tinline int size() const { return size_; }\n\t\tvoid set_size(const int size);\n\n\t\tvoid set_stiffness_tensor(int i, int j, const double val);\n\t\tdouble stifness_tensor(int i, int j) const;\n\n\t\tvoid compute_von_mises_stresses(const int el_id, const ElementBases &bs, const ElementBases &gbs, const Eigen::MatrixXd &local_pts, const Eigen::MatrixXd &displacement, Eigen::MatrixXd &stresses) const;\n\t\tvoid compute_stress_tensor(const int el_id, const ElementBases &bs, const ElementBases &gbs, const Eigen::MatrixXd &local_pts, const Eigen::MatrixXd &displacement, Eigen::MatrixXd &tensor) const;\n\n\t\tvoid set_parameters(const json &params);\n\n\tprivate:\n\t\tint size_ = 2;\n\n\t\tElasticityTensor elasticity_tensor_;\n\n\t\ttemplate <typename T, unsigned long N>\n\t\tT stress(const std::array<T, N> &strain, const int j) const;\n\n\t\ttemplate <typename T>\n\t\tT compute_energy_aux(const ElementAssemblyValues &vals, const Eigen::MatrixXd &displacement, const QuadratureVector &da) const;\n\n\t\tvoid assign_stress_tensor(const int el_id, const ElementBases &bs, const ElementBases &gbs, const Eigen::MatrixXd &local_pts, const Eigen::MatrixXd &displacement, const int all_size, Eigen::MatrixXd &all, const std::function<Eigen::MatrixXd(const Eigen::MatrixXd &)> &fun) const;\n\t};\n} // namespace polyfem\n", "meta": {"hexsha": "fd5f47379a624d2aaae3970ea977539c823f2140", "size": 2225, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/assembler/SaintVenantElasticity.hpp", "max_stars_repo_name": "danielepanozzo/polyfem", "max_stars_repo_head_hexsha": "34a7719c2a3874b7ecc865c28d8b3d9bbdf7d0ba", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 228.0, "max_stars_repo_stars_event_min_datetime": "2018-11-23T19:32:42.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T10:30:51.000Z", "max_issues_repo_path": "src/assembler/SaintVenantElasticity.hpp", "max_issues_repo_name": "danielepanozzo/polyfem", "max_issues_repo_head_hexsha": "34a7719c2a3874b7ecc865c28d8b3d9bbdf7d0ba", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 14.0, "max_issues_repo_issues_event_min_datetime": "2019-03-11T22:44:14.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-16T14:50:35.000Z", "max_forks_repo_path": "src/assembler/SaintVenantElasticity.hpp", "max_forks_repo_name": "danielepanozzo/polyfem", "max_forks_repo_head_hexsha": "34a7719c2a3874b7ecc865c28d8b3d9bbdf7d0ba", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 45.0, "max_forks_repo_forks_event_min_datetime": "2018-12-31T02:04:57.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-08T02:42:01.000Z", "avg_line_length": 41.2037037037, "max_line_length": 281, "alphanum_fraction": 0.7734831461, "num_tokens": 586, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6791787121629466, "lm_q2_score": 0.5117166047041654, "lm_q1q2_score": 0.3475470245753706}}
{"text": "/* Author: Abner Salgado, Texas A&M University 2009               */\n\n/*    $Id: step-35.cc 28376 2013-02-13 15:19:38Z heister $       */\n/*                                                                */\n/*    Copyright (C) 2009-2012 by 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// We start by including all the necessary deal.II header files and some C++\n// related ones. Each one of them has been discussed in previous tutorial\n// programs, so we will not get into details here.\n#include <deal.II/base/parameter_handler.h>\n#include <deal.II/base/point.h>\n#include <deal.II/base/function.h>\n#include <deal.II/base/quadrature_lib.h>\n#include <deal.II/base/multithread_info.h>\n#include <deal.II/base/thread_management.h>\n#include <deal.II/base/work_stream.h>\n#include <deal.II/base/parallel.h>\n#include <deal.II/base/utilities.h>\n#include <deal.II/base/conditional_ostream.h>\n\n#include <deal.II/lac/vector.h>\n#include <deal.II/lac/sparse_matrix.h>\n#include <deal.II/lac/solver_cg.h>\n#include <deal.II/lac/precondition.h>\n#include <deal.II/lac/solver_gmres.h>\n#include <deal.II/lac/sparse_ilu.h>\n#include <deal.II/lac/sparse_direct.h>\n#include <deal.II/lac/constraint_matrix.h>\n\n#include <deal.II/grid/tria.h>\n#include <deal.II/grid/grid_generator.h>\n#include <deal.II/grid/grid_refinement.h>\n#include <deal.II/grid/tria_accessor.h>\n#include <deal.II/grid/tria_iterator.h>\n#include <deal.II/grid/tria_boundary_lib.h>\n#include <deal.II/grid/grid_in.h>\n\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/dofs/dof_renumbering.h>\n\n#include <deal.II/fe/fe_q.h>\n#include <deal.II/fe/fe_values.h>\n#include <deal.II/fe/fe_tools.h>\n#include <deal.II/fe/fe_system.h>\n\n#include <deal.II/numerics/matrix_tools.h>\n#include <deal.II/numerics/vector_tools.h>\n#include <deal.II/numerics/data_out.h>\n\n#include <fstream>\n#include <cmath>\n#include <iostream>\n\n// Finally this is as in all previous programs:\nnamespace Step35\n{\n  using namespace dealii;\n\n\n\n  // @sect3{Run time parameters}\n  //\n  // Since our method has several parameters that can be fine-tuned we put\n  // them into an external file, so that they can be determined at run-time.\n  //\n  // This includes, in particular, the formulation of the equation for the\n  // auxiliary variable $\\phi$, for which we declare an <code>enum</code>.\n  // Next, we declare a class that is going to read and store all the\n  // parameters that our program needs to run.\n  namespace RunTimeParameters\n  {\n    enum MethodFormulation\n    {\n      METHOD_STANDARD,\n      METHOD_ROTATIONAL\n    };\n\n    class Data_Storage\n    {\n    public:\n      Data_Storage();\n      ~Data_Storage();\n      void read_data (const char *filename);\n      MethodFormulation form;\n      double initial_time,\n             final_time,\n             Reynolds;\n      double dt;\n      unsigned int n_global_refines,\n               pressure_degree;\n      unsigned int vel_max_iterations,\n               vel_Krylov_size,\n               vel_off_diagonals,\n               vel_update_prec;\n      double vel_eps,\n             vel_diag_strength;\n      bool verbose;\n      unsigned int output_interval;\n    protected:\n      ParameterHandler prm;\n    };\n\n    // In the constructor of this class we declare all the parameters. The\n    // details of how this works have been discussed elsewhere, for example in\n    // step-19 and step-29.\n    Data_Storage::Data_Storage()\n    {\n      prm.declare_entry (\"Method_Form\", \"rotational\",\n                         Patterns::Selection (\"rotational|standard\"),\n                         \" Used to select the type of method that we are going \"\n                         \"to use. \");\n      prm.enter_subsection (\"Physical data\");\n      {\n        prm.declare_entry (\"initial_time\", \"0.\",\n                           Patterns::Double (0.),\n                           \" The initial time of the simulation. \");\n        prm.declare_entry (\"final_time\", \"1.\",\n                           Patterns::Double (0.),\n                           \" The final time of the simulation. \");\n        prm.declare_entry (\"Reynolds\", \"1.\",\n                           Patterns::Double (0.),\n                           \" The Reynolds number. \");\n      }\n      prm.leave_subsection();\n\n      prm.enter_subsection (\"Time step data\");\n      {\n        prm.declare_entry (\"dt\", \"5e-4\",\n                           Patterns::Double (0.),\n                           \" The time step size. \");\n      }\n      prm.leave_subsection();\n\n      prm.enter_subsection (\"Space discretization\");\n      {\n        prm.declare_entry (\"n_of_refines\", \"0\",\n                           Patterns::Integer (0, 15),\n                           \" The number of global refines we do on the mesh. \");\n        prm.declare_entry (\"pressure_fe_degree\", \"1\",\n                           Patterns::Integer (1, 5),\n                           \" The polynomial degree for the pressure space. \");\n      }\n      prm.leave_subsection();\n\n      prm.enter_subsection (\"Data solve velocity\");\n      {\n        prm.declare_entry (\"max_iterations\", \"1000\",\n                           Patterns::Integer (1, 1000),\n                           \" The maximal number of iterations GMRES must make. \");\n        prm.declare_entry (\"eps\", \"1e-12\",\n                           Patterns::Double (0.),\n                           \" The stopping criterion. \");\n        prm.declare_entry (\"Krylov_size\", \"30\",\n                           Patterns::Integer(1),\n                           \" The size of the Krylov subspace to be used. \");\n        prm.declare_entry (\"off_diagonals\", \"60\",\n                           Patterns::Integer(0),\n                           \" The number of off-diagonal elements ILU must \"\n                           \"compute. \");\n        prm.declare_entry (\"diag_strength\", \"0.01\",\n                           Patterns::Double (0.),\n                           \" Diagonal strengthening coefficient. \");\n        prm.declare_entry (\"update_prec\", \"15\",\n                           Patterns::Integer(1),\n                           \" This number indicates how often we need to \"\n                           \"update the preconditioner\");\n      }\n      prm.leave_subsection();\n\n      prm.declare_entry (\"verbose\", \"true\",\n                         Patterns::Bool(),\n                         \" This indicates whether the output of the solution \"\n                         \"process should be verbose. \");\n\n      prm.declare_entry (\"output_interval\", \"1\",\n                         Patterns::Integer(1),\n                         \" This indicates between how many time steps we print \"\n                         \"the solution. \");\n    }\n\n\n\n    Data_Storage::~Data_Storage()\n    {}\n\n\n\n    void Data_Storage::read_data (const char *filename)\n    {\n      std::ifstream file (filename);\n      AssertThrow (file, ExcFileNotOpen (filename));\n\n      prm.read_input (file);\n\n      if (prm.get (\"Method_Form\") == std::string (\"rotational\"))\n        form = METHOD_ROTATIONAL;\n      else\n        form = METHOD_STANDARD;\n\n      prm.enter_subsection (\"Physical data\");\n      {\n        initial_time = prm.get_double (\"initial_time\");\n        final_time   = prm.get_double (\"final_time\");\n        Reynolds     = prm.get_double (\"Reynolds\");\n      }\n      prm.leave_subsection();\n\n      prm.enter_subsection (\"Time step data\");\n      {\n        dt = prm.get_double (\"dt\");\n      }\n      prm.leave_subsection();\n\n      prm.enter_subsection (\"Space discretization\");\n      {\n        n_global_refines = prm.get_integer (\"n_of_refines\");\n        pressure_degree     = prm.get_integer (\"pressure_fe_degree\");\n      }\n      prm.leave_subsection();\n\n      prm.enter_subsection (\"Data solve velocity\");\n      {\n        vel_max_iterations = prm.get_integer (\"max_iterations\");\n        vel_eps            = prm.get_double (\"eps\");\n        vel_Krylov_size    = prm.get_integer (\"Krylov_size\");\n        vel_off_diagonals  = prm.get_integer (\"off_diagonals\");\n        vel_diag_strength  = prm.get_double (\"diag_strength\");\n        vel_update_prec    = prm.get_integer (\"update_prec\");\n      }\n      prm.leave_subsection();\n\n      verbose = prm.get_bool (\"verbose\");\n\n      output_interval = prm.get_integer (\"output_interval\");\n    }\n  }\n\n\n\n  // @sect3{Equation data}\n\n  // In the next namespace, we declare the initial and boundary conditions:\n  namespace EquationData\n  {\n    // As we have chosen a completely decoupled formulation, we will not take\n    // advantage of deal.II's capabilities to handle vector valued\n    // problems. We do, however, want to use an interface for the equation\n    // data that is somehow dimension independent. To be able to do that, our\n    // functions should be able to know on which spatial component we are\n    // currently working, and we should be able to have a common interface to\n    // do that. The following class is an attempt in that direction.\n    template <int dim>\n    class MultiComponentFunction: public Function<dim>\n    {\n    public:\n      MultiComponentFunction (const double initial_time = 0.);\n      void set_component (const unsigned int d);\n    protected:\n      unsigned int comp;\n    };\n\n    template <int dim>\n    MultiComponentFunction<dim>::\n    MultiComponentFunction (const double initial_time)\n      :\n      Function<dim> (1, initial_time), comp(0)\n    {}\n\n\n    template <int dim>\n    void MultiComponentFunction<dim>::set_component(const unsigned int d)\n    {\n      Assert (d<dim, ExcIndexRange (d, 0, dim));\n      comp = d;\n    }\n\n\n    // With this class defined, we declare classes that describe the boundary\n    // conditions for velocity and pressure:\n    template <int dim>\n    class Velocity : public MultiComponentFunction<dim>\n    {\n    public:\n      Velocity (const double initial_time = 0.0);\n\n      virtual double value (const Point<dim> &p,\n                            const unsigned int component = 0) const;\n\n      virtual void value_list (const std::vector< Point<dim> > &points,\n                               std::vector<double> &values,\n                               const unsigned int component = 0) const;\n    };\n\n\n    template <int dim>\n    Velocity<dim>::Velocity (const double initial_time)\n      :\n      MultiComponentFunction<dim> (initial_time)\n    {}\n\n\n    template <int dim>\n    void Velocity<dim>::value_list (const std::vector<Point<dim> > &points,\n                                    std::vector<double> &values,\n                                    const unsigned int) const\n    {\n      const unsigned int n_points = points.size();\n      Assert (values.size() == n_points,\n              ExcDimensionMismatch (values.size(), n_points));\n      for (unsigned int i=0; i<n_points; ++i)\n        values[i] = Velocity<dim>::value (points[i]);\n    }\n\n\n    template <int dim>\n    double Velocity<dim>::value (const Point<dim> &p,\n                                 const unsigned int) const\n    {\n      if (this->comp == 0)\n        {\n          const double Um = 1.5;\n          const double H  = 4.1;\n          return 4.*Um*p(1)*(H - p(1))/(H*H);\n        }\n      else\n        return 0.;\n    }\n\n\n\n    template <int dim>\n    class Pressure: public Function<dim>\n    {\n    public:\n      Pressure (const double initial_time = 0.0);\n\n      virtual double value (const Point<dim> &p,\n                            const unsigned int component = 0) const;\n\n      virtual void value_list (const std::vector< Point<dim> > &points,\n                               std::vector<double> &values,\n                               const unsigned int component = 0) const;\n    };\n\n    template <int dim>\n    Pressure<dim>::Pressure (const double initial_time)\n      :\n      Function<dim> (1, initial_time)\n    {}\n\n\n    template <int dim>\n    double Pressure<dim>::value (const Point<dim> &p,\n                                 const unsigned int) const\n    {\n      return 25.-p(0);\n    }\n\n    template <int dim>\n    void Pressure<dim>::value_list (const std::vector<Point<dim> > &points,\n                                    std::vector<double> &values,\n                                    const unsigned int) const\n    {\n      const unsigned int n_points = points.size();\n      Assert (values.size() == n_points, ExcDimensionMismatch (values.size(), n_points));\n      for (unsigned int i=0; i<n_points; ++i)\n        values[i] = Pressure<dim>::value (points[i]);\n    }\n  }\n\n\n\n  // @sect3{The <code>NavierStokesProjection</code> class}\n\n  // Now for the main class of the program. It implements the various versions\n  // of the projection method for Navier-Stokes equations.  The names for all\n  // the methods and member variables should be self-explanatory, taking into\n  // account the implementation details given in the introduction.\n  template <int dim>\n  class NavierStokesProjection\n  {\n  public:\n    NavierStokesProjection (const RunTimeParameters::Data_Storage &data);\n\n    void run (const bool         verbose    = false,\n              const unsigned int n_plots = 10);\n  protected:\n    RunTimeParameters::MethodFormulation type;\n\n    const unsigned int deg;\n    const double       dt;\n    const double       t_0, T, Re;\n\n    EquationData::Velocity<dim>       vel_exact;\n    std::map<unsigned int, double>    boundary_values;\n    std::vector<types::boundary_id> boundary_indicators;\n\n    Triangulation<dim> triangulation;\n\n    FE_Q<dim>          fe_velocity;\n    FE_Q<dim>          fe_pressure;\n\n    DoFHandler<dim>    dof_handler_velocity;\n    DoFHandler<dim>    dof_handler_pressure;\n\n    QGauss<dim>        quadrature_pressure;\n    QGauss<dim>        quadrature_velocity;\n\n    SparsityPattern    sparsity_pattern_velocity;\n    SparsityPattern    sparsity_pattern_pressure;\n    SparsityPattern    sparsity_pattern_pres_vel;\n\n    SparseMatrix<double> vel_Laplace_plus_Mass;\n    SparseMatrix<double> vel_it_matrix[dim];\n    SparseMatrix<double> vel_Mass;\n    SparseMatrix<double> vel_Laplace;\n    SparseMatrix<double> vel_Advection;\n    SparseMatrix<double> pres_Laplace;\n    SparseMatrix<double> pres_Mass;\n    SparseMatrix<double> pres_Diff[dim];\n    SparseMatrix<double> pres_iterative;\n\n    Vector<double> pres_n;\n    Vector<double> pres_n_minus_1;\n    Vector<double> phi_n;\n    Vector<double> phi_n_minus_1;\n    Vector<double> u_n[dim];\n    Vector<double> u_n_minus_1[dim];\n    Vector<double> u_star[dim];\n    Vector<double> force[dim];\n    Vector<double> v_tmp;\n    Vector<double> pres_tmp;\n    Vector<double> rot_u;\n\n    SparseILU<double> prec_velocity[dim];\n    SparseILU<double> prec_pres_Laplace;\n    SparseDirectUMFPACK prec_mass;\n    SparseDirectUMFPACK prec_vel_mass;\n\n    DeclException2 (ExcInvalidTimeStep,\n                    double, double,\n                    << \" The time step \" << arg1 << \" is out of range.\"\n                    << std::endl\n                    << \" The permitted range is (0,\" << arg2 << \"]\");\n\n    void create_triangulation_and_dofs (const unsigned int n_refines);\n\n    void initialize();\n\n    void interpolate_velocity ();\n\n    void diffusion_step (const bool reinit_prec);\n\n    void projection_step (const bool reinit_prec);\n\n    void update_pressure (const bool reinit_prec);\n\n  private:\n    unsigned int vel_max_its;\n    unsigned int vel_Krylov_size;\n    unsigned int vel_off_diagonals;\n    unsigned int vel_update_prec;\n    double       vel_eps;\n    double       vel_diag_strength;\n\n    void initialize_velocity_matrices();\n\n    void initialize_pressure_matrices();\n\n    // The next few structures and functions are for doing various things in\n    // parallel. They follow the scheme laid out in @ref threads, using the\n    // WorkStream class. As explained there, this requires us to declare two\n    // structures for each of the assemblers, a per-task data and a scratch\n    // data structure. These are then handed over to functions that assemble\n    // local contributions and that copy these local contributions to the\n    // global objects.\n    //\n    // One of the things that are specific to this program is that we don't\n    // just have a single DoFHandler object that represents both the\n    // velocities and the pressure, but we use individual DoFHandler objects\n    // for these two kinds of variables. We pay for this optimization when we\n    // want to assemble terms that involve both variables, such as the\n    // divergence of the velocity and the gradient of the pressure, times the\n    // respective test functions. When doing so, we can't just anymore use a\n    // single FEValues object, but rather we need two, and they need to be\n    // initialized with cell iterators that point to the same cell in the\n    // triangulation but different DoFHandlers.\n    //\n    // To do this in practice, we declare a \"synchronous\" iterator -- an\n    // object that internally consists of several (in our case two) iterators,\n    // and each time the synchronous iteration is moved up one step, each of\n    // the iterators stored internally is moved up one step as well, thereby\n    // always staying in sync. As it so happens, there is a deal.II class that\n    // facilitates this sort of thing.\n    typedef std_cxx1x::tuple< typename DoFHandler<dim>::active_cell_iterator,\n            typename DoFHandler<dim>::active_cell_iterator\n            > IteratorTuple;\n\n    typedef SynchronousIterators<IteratorTuple> IteratorPair;\n\n    void initialize_gradient_operator();\n\n    struct InitGradPerTaskData\n    {\n      unsigned int              d;\n      unsigned int              vel_dpc;\n      unsigned int              pres_dpc;\n      FullMatrix<double>        local_grad;\n      std::vector<unsigned int> vel_local_dof_indices;\n      std::vector<unsigned int> pres_local_dof_indices;\n\n      InitGradPerTaskData (const unsigned int dd,\n                           const unsigned int vdpc,\n                           const unsigned int pdpc)\n        :\n        d(dd),\n        vel_dpc (vdpc),\n        pres_dpc (pdpc),\n        local_grad (vdpc, pdpc),\n        vel_local_dof_indices (vdpc),\n        pres_local_dof_indices (pdpc)\n      {}\n    };\n\n    struct InitGradScratchData\n    {\n      unsigned int  nqp;\n      FEValues<dim> fe_val_vel;\n      FEValues<dim> fe_val_pres;\n      InitGradScratchData (const FE_Q<dim> &fe_v,\n                           const FE_Q<dim> &fe_p,\n                           const QGauss<dim> &quad,\n                           const UpdateFlags flags_v,\n                           const UpdateFlags flags_p)\n        :\n        nqp (quad.size()),\n        fe_val_vel (fe_v, quad, flags_v),\n        fe_val_pres (fe_p, quad, flags_p)\n      {}\n      InitGradScratchData (const InitGradScratchData &data)\n        :\n        nqp (data.nqp),\n        fe_val_vel (data.fe_val_vel.get_fe(),\n                    data.fe_val_vel.get_quadrature(),\n                    data.fe_val_vel.get_update_flags()),\n        fe_val_pres (data.fe_val_pres.get_fe(),\n                     data.fe_val_pres.get_quadrature(),\n                     data.fe_val_pres.get_update_flags())\n      {}\n    };\n\n    void assemble_one_cell_of_gradient (const IteratorPair &SI,\n                                        InitGradScratchData &scratch,\n                                        InitGradPerTaskData &data);\n\n    void copy_gradient_local_to_global (const InitGradPerTaskData &data);\n\n    // The same general layout also applies to the following classes and\n    // functions implementing the assembly of the advection term:\n    void assemble_advection_term();\n\n    struct AdvectionPerTaskData\n    {\n      FullMatrix<double>        local_advection;\n      std::vector<unsigned int> local_dof_indices;\n      AdvectionPerTaskData (const unsigned int dpc)\n        :\n        local_advection (dpc, dpc),\n        local_dof_indices (dpc)\n      {}\n    };\n\n    struct AdvectionScratchData\n    {\n      unsigned int                 nqp;\n      unsigned int                 dpc;\n      std::vector< Point<dim> >    u_star_local;\n      std::vector< Tensor<1,dim> > grad_u_star;\n      std::vector<double>          u_star_tmp;\n      FEValues<dim>                fe_val;\n      AdvectionScratchData (const FE_Q<dim> &fe,\n                            const QGauss<dim> &quad,\n                            const UpdateFlags flags)\n        :\n        nqp (quad.size()),\n        dpc (fe.dofs_per_cell),\n        u_star_local (nqp),\n        grad_u_star (nqp),\n        u_star_tmp (nqp),\n        fe_val (fe, quad, flags)\n      {}\n\n      AdvectionScratchData (const AdvectionScratchData &data)\n        :\n        nqp (data.nqp),\n        dpc (data.dpc),\n        u_star_local (nqp),\n        grad_u_star (nqp),\n        u_star_tmp (nqp),\n        fe_val (data.fe_val.get_fe(),\n                data.fe_val.get_quadrature(),\n                data.fe_val.get_update_flags())\n      {}\n    };\n\n    void assemble_one_cell_of_advection (const typename DoFHandler<dim>::active_cell_iterator &cell,\n                                         AdvectionScratchData &scratch,\n                                         AdvectionPerTaskData &data);\n\n    void copy_advection_local_to_global (const AdvectionPerTaskData &data);\n\n    // The final few functions implement the diffusion solve as well as\n    // postprocessing the output, including computing the curl of the\n    // velocity:\n    void diffusion_component_solve (const unsigned int d);\n\n    void output_results (const unsigned int step);\n\n    void assemble_vorticity (const bool reinit_prec);\n  };\n\n\n\n  // @sect4{ <code>NavierStokesProjection::NavierStokesProjection</code> }\n\n  // In the constructor, we just read all the data from the\n  // <code>Data_Storage</code> object that is passed as an argument, verify\n  // that the data we read is reasonable and, finally, create the\n  // triangulation and load the initial data.\n  template <int dim>\n  NavierStokesProjection<dim>::NavierStokesProjection(const RunTimeParameters::Data_Storage &data)\n    :\n    type (data.form),\n    deg (data.pressure_degree),\n    dt (data.dt),\n    t_0 (data.initial_time),\n    T (data.final_time),\n    Re (data.Reynolds),\n    vel_exact (data.initial_time),\n    fe_velocity (deg+1),\n    fe_pressure (deg),\n    dof_handler_velocity (triangulation),\n    dof_handler_pressure (triangulation),\n    quadrature_pressure (deg+1),\n    quadrature_velocity (deg+2),\n    vel_max_its (data.vel_max_iterations),\n    vel_Krylov_size (data.vel_Krylov_size),\n    vel_off_diagonals (data.vel_off_diagonals),\n    vel_update_prec (data.vel_update_prec),\n    vel_eps (data.vel_eps),\n    vel_diag_strength (data.vel_diag_strength)\n  {\n    if (deg < 1)\n      std::cout << \" WARNING: The chosen pair of finite element spaces is not stable.\"\n                << std::endl\n                << \" The obtained results will be nonsense\"\n                << std::endl;\n\n    AssertThrow (!  ( (dt <= 0.) || (dt > .5*T)), ExcInvalidTimeStep (dt, .5*T));\n\n    create_triangulation_and_dofs (data.n_global_refines);\n    initialize();\n  }\n\n\n  // @sect4{ <code>NavierStokesProjection::create_triangulation_and_dofs</code> }\n\n  // The method that creates the triangulation and refines it the needed\n  // number of times.  After creating the triangulation, it creates the mesh\n  // dependent data, i.e. it distributes degrees of freedom and renumbers\n  // them, and initializes the matrices and vectors that we will use.\n  template <int dim>\n  void\n  NavierStokesProjection<dim>::\n  create_triangulation_and_dofs (const unsigned int n_refines)\n  {\n    GridIn<dim> grid_in;\n    grid_in.attach_triangulation (triangulation);\n\n    {\n      std::string filename = \"nsbench2.inp\";\n      std::ifstream file (filename.c_str());\n      Assert (file, ExcFileNotOpen (filename.c_str()));\n      grid_in.read_ucd (file);\n    }\n\n    std::cout << \"Number of refines = \" << n_refines\n              << std::endl;\n    triangulation.refine_global (n_refines);\n    std::cout << \"Number of active cells: \" << triangulation.n_active_cells()\n              << std::endl;\n\n    boundary_indicators = triangulation.get_boundary_indicators();\n\n    dof_handler_velocity.distribute_dofs (fe_velocity);\n    DoFRenumbering::boost::Cuthill_McKee (dof_handler_velocity);\n    dof_handler_pressure.distribute_dofs (fe_pressure);\n    DoFRenumbering::boost::Cuthill_McKee (dof_handler_pressure);\n\n    initialize_velocity_matrices();\n    initialize_pressure_matrices();\n    initialize_gradient_operator();\n\n    pres_n.reinit (dof_handler_pressure.n_dofs());\n    pres_n_minus_1.reinit (dof_handler_pressure.n_dofs());\n    phi_n.reinit (dof_handler_pressure.n_dofs());\n    phi_n_minus_1.reinit (dof_handler_pressure.n_dofs());\n    pres_tmp.reinit (dof_handler_pressure.n_dofs());\n    for (unsigned int d=0; d<dim; ++d)\n      {\n        u_n[d].reinit (dof_handler_velocity.n_dofs());\n        u_n_minus_1[d].reinit (dof_handler_velocity.n_dofs());\n        u_star[d].reinit (dof_handler_velocity.n_dofs());\n        force[d].reinit (dof_handler_velocity.n_dofs());\n      }\n    v_tmp.reinit (dof_handler_velocity.n_dofs());\n    rot_u.reinit (dof_handler_velocity.n_dofs());\n\n    std::cout << \"dim (X_h) = \" << (dof_handler_velocity.n_dofs()*dim)\n              << std::endl\n              << \"dim (M_h) = \" << dof_handler_pressure.n_dofs()\n              << std::endl\n              << \"Re        = \" << Re\n              << std::endl\n              << std::endl;\n  }\n\n\n  // @sect4{ <code>NavierStokesProjection::initialize</code> }\n\n  // This method creates the constant matrices and loads the initial data\n  template <int dim>\n  void\n  NavierStokesProjection<dim>::initialize()\n  {\n    vel_Laplace_plus_Mass = 0.;\n    vel_Laplace_plus_Mass.add (1./Re, vel_Laplace);\n    vel_Laplace_plus_Mass.add (1.5/dt, vel_Mass);\n\n    EquationData::Pressure<dim> pres (t_0);\n    VectorTools::interpolate (dof_handler_pressure, pres, pres_n_minus_1);\n    pres.advance_time (dt);\n    VectorTools::interpolate (dof_handler_pressure, pres, pres_n);\n    phi_n = 0.;\n    phi_n_minus_1 = 0.;\n    for (unsigned int d=0; d<dim; ++d)\n      {\n        vel_exact.set_time (t_0);\n        vel_exact.set_component(d);\n        VectorTools::interpolate (dof_handler_velocity, ZeroFunction<dim>(), u_n_minus_1[d]);\n        vel_exact.advance_time (dt);\n        VectorTools::interpolate (dof_handler_velocity, ZeroFunction<dim>(), u_n[d]);\n      }\n  }\n\n\n  // @sect4{ The <code>NavierStokesProjection::initialize_*_matrices</code> methods }\n\n  // In this set of methods we initialize the sparsity patterns, the\n  // constraints (if any) and assemble the matrices that do not depend on the\n  // timestep <code>dt</code>. Note that for the Laplace and mass matrices, we\n  // can use functions in the library that do this. Because the expensive\n  // operations of this function -- creating the two matrices -- are entirely\n  // independent, we could in principle mark them as tasks that can be worked\n  // on in %parallel using the Threads::new_task functions. We won't do that\n  // here since these functions internally already are parallelized, and in\n  // particular because the current function is only called once per program\n  // run and so does not incur a cost in each time step. The necessary\n  // modifications would be quite straightforward, however.\n  template <int dim>\n  void\n  NavierStokesProjection<dim>::initialize_velocity_matrices()\n  {\n    sparsity_pattern_velocity.reinit (dof_handler_velocity.n_dofs(),\n                                      dof_handler_velocity.n_dofs(),\n                                      dof_handler_velocity.max_couplings_between_dofs());\n    DoFTools::make_sparsity_pattern (dof_handler_velocity,\n                                     sparsity_pattern_velocity);\n    sparsity_pattern_velocity.compress();\n\n    vel_Laplace_plus_Mass.reinit (sparsity_pattern_velocity);\n    for (unsigned int d=0; d<dim; ++d)\n      vel_it_matrix[d].reinit (sparsity_pattern_velocity);\n    vel_Mass.reinit (sparsity_pattern_velocity);\n    vel_Laplace.reinit (sparsity_pattern_velocity);\n    vel_Advection.reinit (sparsity_pattern_velocity);\n\n    MatrixCreator::create_mass_matrix (dof_handler_velocity,\n                                       quadrature_velocity,\n                                       vel_Mass);\n    MatrixCreator::create_laplace_matrix (dof_handler_velocity,\n                                          quadrature_velocity,\n                                          vel_Laplace);\n  }\n\n  // The initialization of the matrices that act on the pressure space is\n  // similar to the ones that act on the velocity space.\n  template <int dim>\n  void\n  NavierStokesProjection<dim>::initialize_pressure_matrices()\n  {\n    sparsity_pattern_pressure.reinit (dof_handler_pressure.n_dofs(), dof_handler_pressure.n_dofs(),\n                                      dof_handler_pressure.max_couplings_between_dofs());\n    DoFTools::make_sparsity_pattern (dof_handler_pressure, sparsity_pattern_pressure);\n\n    sparsity_pattern_pressure.compress();\n\n    pres_Laplace.reinit (sparsity_pattern_pressure);\n    pres_iterative.reinit (sparsity_pattern_pressure);\n    pres_Mass.reinit (sparsity_pattern_pressure);\n\n    MatrixCreator::create_laplace_matrix (dof_handler_pressure,\n                                          quadrature_pressure,\n                                          pres_Laplace);\n    MatrixCreator::create_mass_matrix (dof_handler_pressure,\n                                       quadrature_pressure,\n                                       pres_Mass);\n  }\n\n\n  // For the gradient operator, we start by initializing the sparsity pattern\n  // and compressing it.  It is important to notice here that the gradient\n  // operator acts from the pressure space into the velocity space, so we have\n  // to deal with two different finite element spaces. To keep the loops\n  // synchronized, we use the <code>typedef</code>'s that we have defined\n  // before, namely <code>PairedIterators</code> and\n  // <code>IteratorPair</code>.\n  template <int dim>\n  void\n  NavierStokesProjection<dim>::initialize_gradient_operator()\n  {\n    sparsity_pattern_pres_vel.reinit (dof_handler_velocity.n_dofs(),\n                                      dof_handler_pressure.n_dofs(),\n                                      dof_handler_velocity.max_couplings_between_dofs());\n    DoFTools::make_sparsity_pattern (dof_handler_velocity,\n                                     dof_handler_pressure,\n                                     sparsity_pattern_pres_vel);\n    sparsity_pattern_pres_vel.compress();\n\n    InitGradPerTaskData per_task_data (0, fe_velocity.dofs_per_cell,\n                                       fe_pressure.dofs_per_cell);\n    InitGradScratchData scratch_data (fe_velocity,\n                                      fe_pressure,\n                                      quadrature_velocity,\n                                      update_gradients | update_JxW_values,\n                                      update_values);\n\n    for (unsigned int d=0; d<dim; ++d)\n      {\n        pres_Diff[d].reinit (sparsity_pattern_pres_vel);\n        per_task_data.d = d;\n        WorkStream::run (IteratorPair (IteratorTuple (dof_handler_velocity.begin_active(),\n                                                      dof_handler_pressure.begin_active()\n                                                     )\n                                      ),\n                         IteratorPair (IteratorTuple (dof_handler_velocity.end(),\n                                                      dof_handler_pressure.end()\n                                                     )\n                                      ),\n                         *this,\n                         &NavierStokesProjection<dim>::assemble_one_cell_of_gradient,\n                         &NavierStokesProjection<dim>::copy_gradient_local_to_global,\n                         scratch_data,\n                         per_task_data\n                        );\n      }\n  }\n\n  template <int dim>\n  void\n  NavierStokesProjection<dim>::\n  assemble_one_cell_of_gradient (const IteratorPair &SI,\n                                 InitGradScratchData &scratch,\n                                 InitGradPerTaskData &data)\n  {\n    scratch.fe_val_vel.reinit (std_cxx1x::get<0> (SI.iterators));\n    scratch.fe_val_pres.reinit (std_cxx1x::get<1> (SI.iterators));\n\n    std_cxx1x::get<0> (SI.iterators)->get_dof_indices (data.vel_local_dof_indices);\n    std_cxx1x::get<1> (SI.iterators)->get_dof_indices (data.pres_local_dof_indices);\n\n    data.local_grad = 0.;\n    for (unsigned int q=0; q<scratch.nqp; ++q)\n      {\n        for (unsigned int i=0; i<data.vel_dpc; ++i)\n          for (unsigned int j=0; j<data.pres_dpc; ++j)\n            data.local_grad (i, j) += -scratch.fe_val_vel.JxW(q) *\n                                      scratch.fe_val_vel.shape_grad (i, q)[data.d] *\n                                      scratch.fe_val_pres.shape_value (j, q);\n      }\n  }\n\n\n  template <int dim>\n  void\n  NavierStokesProjection<dim>::\n  copy_gradient_local_to_global(const InitGradPerTaskData &data)\n  {\n    for (unsigned int i=0; i<data.vel_dpc; ++i)\n      for (unsigned int j=0; j<data.pres_dpc; ++j)\n        pres_Diff[data.d].add (data.vel_local_dof_indices[i], data.pres_local_dof_indices[j],\n                               data.local_grad (i, j) );\n  }\n\n\n  // @sect4{ <code>NavierStokesProjection::run</code> }\n\n  // This is the time marching function, which starting at <code>t_0</code>\n  // advances in time using the projection method with time step\n  // <code>dt</code> until <code>T</code>.\n  //\n  // Its second parameter, <code>verbose</code> indicates whether the function\n  // should output information what it is doing at any given moment: for\n  // example, it will say whether we are working on the diffusion, projection\n  // substep; updating preconditioners etc. Rather than implementing this\n  // output using code like\n  // @code\n  //   if (verbose) std::cout << \"something\";\n  // @endcode\n  // we use the ConditionalOStream class to do that for us. That\n  // class takes an output stream and a condition that indicates whether the\n  // things you pass to it should be passed through to the given output\n  // stream, or should just be ignored. This way, above code simply becomes\n  // @code\n  //   verbose_cout << \"something\";\n  // @endcode\n  // and does the right thing in either case.\n  template <int dim>\n  void\n  NavierStokesProjection<dim>::run (const bool verbose,\n                                    const unsigned int output_interval)\n  {\n    ConditionalOStream verbose_cout (std::cout, verbose);\n\n    const unsigned int n_steps =  static_cast<unsigned int>((T - t_0)/dt);\n    vel_exact.set_time (2.*dt);\n    output_results(1);\n    for (unsigned int n = 2; n<=n_steps; ++n)\n      {\n        if (n % output_interval == 0)\n          {\n            verbose_cout << \"Plotting Solution\" << std::endl;\n            output_results(n);\n          }\n        std::cout << \"Step = \" << n << \" Time = \" << (n*dt) << std::endl;\n        verbose_cout << \"  Interpolating the velocity \" << std::endl;\n\n        interpolate_velocity();\n        verbose_cout << \"  Diffusion Step\" << std::endl;\n        if (n % vel_update_prec == 0)\n          verbose_cout << \"    With reinitialization of the preconditioner\"\n                       << std::endl;\n        diffusion_step ((n%vel_update_prec == 0) || (n == 2));\n        verbose_cout << \"  Projection Step\" << std::endl;\n        projection_step ( (n == 2));\n        verbose_cout << \"  Updating the Pressure\" << std::endl;\n        update_pressure ( (n == 2));\n        vel_exact.advance_time(dt);\n      }\n    output_results (n_steps);\n  }\n\n\n\n  template <int dim>\n  void\n  NavierStokesProjection<dim>::interpolate_velocity()\n  {\n    for (unsigned int d=0; d<dim; ++d)\n      u_star[d].equ (2., u_n[d], -1, u_n_minus_1[d]);\n  }\n\n\n  // @sect4{<code>NavierStokesProjection::diffusion_step</code>}\n\n  // The implementation of a diffusion step. Note that the expensive operation\n  // is the diffusion solve at the end of the function, which we have to do\n  // once for each velocity component. To accellerate things a bit, we allow\n  // to do this in %parallel, using the Threads::new_task function which makes\n  // sure that the <code>dim</code> solves are all taken care of and are\n  // scheduled to available processors: if your machine has more than one\n  // processor core and no other parts of this program are using resources\n  // currently, then the diffusion solves will run in %parallel. On the other\n  // hand, if your system has only one processor core then running things in\n  // %parallel would be inefficient (since it leads, for example, to cache\n  // congestion) and things will be executed sequentially.\n  template <int dim>\n  void\n  NavierStokesProjection<dim>::diffusion_step (const bool reinit_prec)\n  {\n    pres_tmp.equ (-1., pres_n, -4./3., phi_n, 1./3., phi_n_minus_1);\n\n    assemble_advection_term();\n\n    for (unsigned int d=0; d<dim; ++d)\n      {\n        force[d] = 0.;\n        v_tmp.equ (2./dt,u_n[d],-.5/dt,u_n_minus_1[d]);\n        vel_Mass.vmult_add (force[d], v_tmp);\n\n        pres_Diff[d].vmult_add (force[d], pres_tmp);\n        u_n_minus_1[d] = u_n[d];\n\n        vel_it_matrix[d].copy_from (vel_Laplace_plus_Mass);\n        vel_it_matrix[d].add (1., vel_Advection);\n\n        vel_exact.set_component(d);\n        boundary_values.clear();\n        for (std::vector<types::boundary_id>::const_iterator\n             boundaries = boundary_indicators.begin();\n             boundaries != boundary_indicators.end();\n             ++boundaries)\n          {\n            switch (*boundaries)\n              {\n              case 1:\n                VectorTools::\n                interpolate_boundary_values (dof_handler_velocity,\n                                             *boundaries,\n                                             ZeroFunction<dim>(),\n                                             boundary_values);\n                break;\n              case 2:\n                VectorTools::\n                interpolate_boundary_values (dof_handler_velocity,\n                                             *boundaries,\n                                             vel_exact,\n                                             boundary_values);\n                break;\n              case 3:\n                if (d != 0)\n                  VectorTools::\n                  interpolate_boundary_values (dof_handler_velocity,\n                                               *boundaries,\n                                               ZeroFunction<dim>(),\n                                               boundary_values);\n                break;\n              case 4:\n                VectorTools::\n                interpolate_boundary_values (dof_handler_velocity,\n                                             *boundaries,\n                                             ZeroFunction<dim>(),\n                                             boundary_values);\n                break;\n              default:\n                Assert (false, ExcNotImplemented());\n              }\n          }\n        MatrixTools::apply_boundary_values (boundary_values,\n                                            vel_it_matrix[d],\n                                            u_n[d],\n                                            force[d]);\n      }\n\n\n    Threads::TaskGroup<void> tasks;\n    for (unsigned int d=0; d<dim; ++d)\n      {\n        if (reinit_prec)\n          prec_velocity[d].initialize (vel_it_matrix[d],\n                                       SparseILU<double>::\n                                       AdditionalData (vel_diag_strength,\n                                                       vel_off_diagonals));\n        tasks += Threads::new_task (&NavierStokesProjection<dim>::\n                                    diffusion_component_solve,\n                                    *this, d);\n      }\n    tasks.join_all();\n  }\n\n\n\n  template <int dim>\n  void\n  NavierStokesProjection<dim>::diffusion_component_solve (const unsigned int d)\n  {\n    SolverControl solver_control (vel_max_its, vel_eps*force[d].l2_norm());\n    SolverGMRES<> gmres (solver_control,\n                         SolverGMRES<>::AdditionalData (vel_Krylov_size));\n    gmres.solve (vel_it_matrix[d], u_n[d], force[d], prec_velocity[d]);\n  }\n\n\n  // @sect4{ The <code>NavierStokesProjection::assemble_advection_term</code> method and related}\n\n  // The following few functions deal with assembling the advection terms,\n  // which is the part of the system matrix for the diffusion step that\n  // changes at every time step. As mentioned above, we will run the assembly\n  // loop over all cells in %parallel, using the WorkStream class and other\n  // facilities as described in the documentation module on @ref threads.\n  template <int dim>\n  void\n  NavierStokesProjection<dim>::assemble_advection_term()\n  {\n    vel_Advection = 0.;\n    AdvectionPerTaskData data (fe_velocity.dofs_per_cell);\n    AdvectionScratchData scratch (fe_velocity, quadrature_velocity,\n                                  update_values |\n                                  update_JxW_values |\n                                  update_gradients);\n    WorkStream::run (dof_handler_velocity.begin_active(),\n                     dof_handler_velocity.end(), *this,\n                     &NavierStokesProjection<dim>::assemble_one_cell_of_advection,\n                     &NavierStokesProjection<dim>::copy_advection_local_to_global,\n                     scratch,\n                     data);\n  }\n\n\n\n  template <int dim>\n  void\n  NavierStokesProjection<dim>::\n  assemble_one_cell_of_advection(const typename DoFHandler<dim>::active_cell_iterator &cell,\n                                 AdvectionScratchData &scratch,\n                                 AdvectionPerTaskData &data)\n  {\n    scratch.fe_val.reinit(cell);\n    cell->get_dof_indices (data.local_dof_indices);\n    for (unsigned int d=0; d<dim; ++d)\n      {\n        scratch.fe_val.get_function_values (u_star[d], scratch.u_star_tmp);\n        for (unsigned int q=0; q<scratch.nqp; ++q)\n          scratch.u_star_local[q](d) = scratch.u_star_tmp[q];\n      }\n\n    for (unsigned int d=0; d<dim; ++d)\n      {\n        scratch.fe_val.get_function_gradients (u_star[d], scratch.grad_u_star);\n        for (unsigned int q=0; q<scratch.nqp; ++q)\n          {\n            if (d==0)\n              scratch.u_star_tmp[q] = 0.;\n            scratch.u_star_tmp[q] += scratch.grad_u_star[q][d];\n          }\n      }\n\n    data.local_advection = 0.;\n    for (unsigned int q=0; q<scratch.nqp; ++q)\n      for (unsigned int i=0; i<scratch.dpc; ++i)\n        for (unsigned int j=0; j<scratch.dpc; ++j)\n          data.local_advection(i,j) += (scratch.u_star_local[q] *\n                                        scratch.fe_val.shape_grad (j, q) *\n                                        scratch.fe_val.shape_value (i, q)\n                                        +\n                                        0.5 *\n                                        scratch.u_star_tmp[q] *\n                                        scratch.fe_val.shape_value (i, q) *\n                                        scratch.fe_val.shape_value (j, q))\n                                       *\n                                       scratch.fe_val.JxW(q) ;\n  }\n\n\n\n  template <int dim>\n  void\n  NavierStokesProjection<dim>::\n  copy_advection_local_to_global(const AdvectionPerTaskData &data)\n  {\n    for (unsigned int i=0; i<fe_velocity.dofs_per_cell; ++i)\n      for (unsigned int j=0; j<fe_velocity.dofs_per_cell; ++j)\n        vel_Advection.add (data.local_dof_indices[i],\n                           data.local_dof_indices[j],\n                           data.local_advection(i,j));\n  }\n\n\n\n  // @sect4{<code>NavierStokesProjection::projection_step</code>}\n\n  // This implements the projection step:\n  template <int dim>\n  void\n  NavierStokesProjection<dim>::projection_step (const bool reinit_prec)\n  {\n    pres_iterative.copy_from (pres_Laplace);\n\n    pres_tmp = 0.;\n    for (unsigned d=0; d<dim; ++d)\n      pres_Diff[d].Tvmult_add (pres_tmp, u_n[d]);\n\n    phi_n_minus_1 = phi_n;\n\n    static std::map<unsigned int, double> bval;\n    if (reinit_prec)\n      VectorTools::interpolate_boundary_values (dof_handler_pressure, 3,\n                                                ZeroFunction<dim>(), bval);\n\n    MatrixTools::apply_boundary_values (bval, pres_iterative, phi_n, pres_tmp);\n\n    if (reinit_prec)\n      prec_pres_Laplace.initialize(pres_iterative,\n                                   SparseILU<double>::AdditionalData (vel_diag_strength,\n                                       vel_off_diagonals) );\n\n    SolverControl solvercontrol (vel_max_its, vel_eps*pres_tmp.l2_norm());\n    SolverCG<> cg (solvercontrol);\n    cg.solve (pres_iterative, phi_n, pres_tmp, prec_pres_Laplace);\n\n    phi_n *= 1.5/dt;\n  }\n\n\n  // @sect4{ <code>NavierStokesProjection::update_pressure</code> }\n\n  // This is the pressure update step of the projection method. It implements\n  // the standard formulation of the method, that is @f[ p^{n+1} = p^n +\n  // \\phi^{n+1}, @f] or the rotational form, which is @f[ p^{n+1} = p^n +\n  // \\phi^{n+1} - \\frac{1}{Re} \\nabla\\cdot u^{n+1}.  @f]\n  template <int dim>\n  void\n  NavierStokesProjection<dim>::update_pressure (const bool reinit_prec)\n  {\n    pres_n_minus_1 = pres_n;\n    switch (type)\n      {\n      case RunTimeParameters::METHOD_STANDARD:\n        pres_n += phi_n;\n        break;\n      case RunTimeParameters::METHOD_ROTATIONAL:\n        if (reinit_prec)\n          prec_mass.initialize (pres_Mass);\n        pres_n = pres_tmp;\n        prec_mass.solve (pres_n);\n        pres_n.sadd(1./Re, 1., pres_n_minus_1, 1., phi_n);\n        break;\n      default:\n        Assert (false, ExcNotImplemented());\n      };\n  }\n\n\n  // @sect4{ <code>NavierStokesProjection::output_results</code> }\n\n  // This method plots the current solution. The main difficulty is that we\n  // want to create a single output file that contains the data for all\n  // velocity components, the pressure, and also the vorticity of the flow. On\n  // the other hand, velocities and the pressure live on separate DoFHandler\n  // objects, and so can't be written to the same file using a single DataOut\n  // object. As a consequence, we have to work a bit harder to get the various\n  // pieces of data into a single DoFHandler object, and then use that to\n  // drive graphical output.\n  //\n  // We will not elaborate on this process here, but rather refer to step-31\n  // and step-32, where a similar procedure is used (and is documented) to\n  // create a joint DoFHandler object for all variables.\n  //\n  // Let us also note that we here compute the vorticity as a scalar quantity\n  // in a separate function, using the $L^2$ projection of the quantity\n  // $\\text{curl} u$ onto the finite element space used for the components of\n  // the velocity. In principle, however, we could also have computed as a\n  // pointwise quantity from the velocity, and do so through the\n  // DataPostprocessor mechanism discussed in step-29 and step-33.\n  template <int dim>\n  void NavierStokesProjection<dim>::output_results (const unsigned int step)\n  {\n    assemble_vorticity ( (step == 1));\n    const FESystem<dim> joint_fe (fe_velocity, dim,\n                                  fe_pressure, 1,\n                                  fe_velocity, 1);\n    DoFHandler<dim> joint_dof_handler (triangulation);\n    joint_dof_handler.distribute_dofs (joint_fe);\n    Assert (joint_dof_handler.n_dofs() ==\n            ((dim + 1)*dof_handler_velocity.n_dofs() +\n             dof_handler_pressure.n_dofs()),\n            ExcInternalError());\n    static Vector<double> joint_solution (joint_dof_handler.n_dofs());\n    std::vector<unsigned int> loc_joint_dof_indices (joint_fe.dofs_per_cell),\n        loc_vel_dof_indices (fe_velocity.dofs_per_cell),\n        loc_pres_dof_indices (fe_pressure.dofs_per_cell);\n    typename DoFHandler<dim>::active_cell_iterator\n    joint_cell = joint_dof_handler.begin_active(),\n    joint_endc = joint_dof_handler.end(),\n    vel_cell   = dof_handler_velocity.begin_active(),\n    pres_cell  = dof_handler_pressure.begin_active();\n    for (; joint_cell != joint_endc; ++joint_cell, ++vel_cell, ++pres_cell)\n      {\n        joint_cell->get_dof_indices (loc_joint_dof_indices);\n        vel_cell->get_dof_indices (loc_vel_dof_indices),\n                 pres_cell->get_dof_indices (loc_pres_dof_indices);\n        for (unsigned int i=0; i<joint_fe.dofs_per_cell; ++i)\n          switch (joint_fe.system_to_base_index(i).first.first)\n            {\n            case 0:\n              Assert (joint_fe.system_to_base_index(i).first.second < dim,\n                      ExcInternalError());\n              joint_solution (loc_joint_dof_indices[i]) =\n                u_n[ joint_fe.system_to_base_index(i).first.second ]\n                (loc_vel_dof_indices[ joint_fe.system_to_base_index(i).second ]);\n              break;\n            case 1:\n              Assert (joint_fe.system_to_base_index(i).first.second == 0,\n                      ExcInternalError());\n              joint_solution (loc_joint_dof_indices[i]) =\n                pres_n (loc_pres_dof_indices[ joint_fe.system_to_base_index(i).second ]);\n              break;\n            case 2:\n              Assert (joint_fe.system_to_base_index(i).first.second == 0,\n                      ExcInternalError());\n              joint_solution (loc_joint_dof_indices[i]) =\n                rot_u (loc_vel_dof_indices[ joint_fe.system_to_base_index(i).second ]);\n              break;\n            default:\n              Assert (false, ExcInternalError());\n            }\n      }\n    std::vector<std::string> joint_solution_names (dim, \"v\");\n    joint_solution_names.push_back (\"p\");\n    joint_solution_names.push_back (\"rot_u\");\n    DataOut<dim> data_out;\n    data_out.attach_dof_handler (joint_dof_handler);\n    std::vector< DataComponentInterpretation::DataComponentInterpretation >\n    component_interpretation (dim+2,\n                              DataComponentInterpretation::component_is_part_of_vector);\n    component_interpretation[dim]\n      = DataComponentInterpretation::component_is_scalar;\n    component_interpretation[dim+1]\n      = DataComponentInterpretation::component_is_scalar;\n    data_out.add_data_vector (joint_solution,\n                              joint_solution_names,\n                              DataOut<dim>::type_dof_data,\n                              component_interpretation);\n    data_out.build_patches (deg + 1);\n    std::ofstream output ((\"solution-\" +\n                           Utilities::int_to_string (step, 5) +\n                           \".vtk\").c_str());\n    data_out.write_vtk (output);\n  }\n\n\n\n  // Following is the helper function that computes the vorticity by\n  // projecting the term $\\text{curl} u$ onto the finite element space used\n  // for the components of the velocity. The function is only called whenever\n  // we generate graphical output, so not very often, and as a consequence we\n  // didn't bother parallelizing it using the WorkStream concept as we do for\n  // the other assembly functions. That should not be overly complicated,\n  // however, if needed. Moreover, the implementation that we have here only\n  // works for 2d, so we bail if that is not the case.\n  template <int dim>\n  void NavierStokesProjection<dim>::assemble_vorticity (const bool reinit_prec)\n  {\n    Assert (dim == 2, ExcNotImplemented());\n    if (reinit_prec)\n      prec_vel_mass.initialize (vel_Mass);\n\n    FEValues<dim> fe_val_vel (fe_velocity, quadrature_velocity,\n                              update_gradients |\n                              update_JxW_values |\n                              update_values);\n    const unsigned int dpc = fe_velocity.dofs_per_cell,\n                       nqp = quadrature_velocity.size();\n    std::vector<unsigned int> ldi (dpc);\n    Vector<double> loc_rot (dpc);\n\n    std::vector< Tensor<1,dim> > grad_u1 (nqp), grad_u2 (nqp);\n    rot_u = 0.;\n\n    typename DoFHandler<dim>::active_cell_iterator\n    cell = dof_handler_velocity.begin_active(),\n    end  = dof_handler_velocity.end();\n    for (; cell != end; ++cell)\n      {\n        fe_val_vel.reinit (cell);\n        cell->get_dof_indices (ldi);\n        fe_val_vel.get_function_gradients (u_n[0], grad_u1);\n        fe_val_vel.get_function_gradients (u_n[1], grad_u2);\n        loc_rot = 0.;\n        for (unsigned int q=0; q<nqp; ++q)\n          for (unsigned int i=0; i<dpc; ++i)\n            loc_rot(i) += (grad_u2[q][0] - grad_u1[q][1]) *\n                          fe_val_vel.shape_value (i, q) *\n                          fe_val_vel.JxW(q);\n\n        for (unsigned int i=0; i<dpc; ++i)\n          rot_u (ldi[i]) += loc_rot(i);\n      }\n\n    prec_vel_mass.solve (rot_u);\n  }\n}\n\n\n// @sect3{ The main function }\n\n// The main function looks very much like in all the other tutorial programs,\n// so there is little to comment on here:\nint main()\n{\n  try\n    {\n      using namespace dealii;\n      using namespace Step35;\n\n      RunTimeParameters::Data_Storage data;\n      data.read_data (\"parameter-file.prm\");\n\n      deallog.depth_console (data.verbose ? 2 : 0);\n\n      NavierStokesProjection<2> test (data);\n      test.run (data.verbose, data.output_interval);\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      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  std::cout << \"----------------------------------------------------\"\n            << std::endl\n            << \"Apparently everything went fine!\"\n            << std::endl\n            << \"Don't forget to brush your teeth :-)\"\n            << std::endl << std::endl;\n  return 0;\n}\n", "meta": {"hexsha": "305ac07f6021b5cf3b507989992612eb2cc401f7", "size": 54359, "ext": "cc", "lang": "C++", "max_stars_repo_path": "MHD/examples/step-35/step-35.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-35/step-35.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-35/step-35.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": 37.6186851211, "max_line_length": 100, "alphanum_fraction": 0.5978954727, "num_tokens": 12300, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5583269943353744, "lm_q2_score": 0.6224593312018545, "lm_q1q2_score": 0.34753584748593874}}
{"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 \"spectral_canonization.hpp\"\n\n#include <iostream>\n#include <numeric>\n\n#include <boost/format.hpp>\n\n#include <core/utils/range_utils.hpp>\n#include <core/utils/timer.hpp>\n\nnamespace cirkit\n{\n\n/******************************************************************************\n * Types                                                                      *\n ******************************************************************************/\n\n/******************************************************************************\n * Private functions                                                          *\n ******************************************************************************/\n\ntt make_sum( const boost::dynamic_bitset<>& mask )\n{\n  boost::dynamic_bitset<> sum( std::max<unsigned>( 1 << mask.size(), 64u ) );\n  foreach_bit( mask, [&sum]( unsigned pos ) {\n      sum ^= tt_nth_var( pos );\n    } );\n  if ( mask.size() < 6u )\n  {\n    tt_shrink( sum, mask.size() );\n  }\n\n  return sum;\n}\n\nstd::vector<int> rademacher_walsh_spectrum( const tt& func )\n{\n  const auto n = tt_num_vars( func );\n  std::vector<int> spectrum;\n\n  foreach_bitset( n, [n, &func, &spectrum]( const boost::dynamic_bitset<>& bs ) {\n      const auto row = make_sum( bs );\n      spectrum.push_back( ( 1 << n ) - 2 * ( row ^ func ).count() );\n    } );\n\n  return spectrum;\n}\n\nstd::vector<int> autocorrelation_spectrum( const tt& func )\n{\n  const auto n = tt_num_vars( func );\n  std::vector<int> spectrum;\n\n  foreach_bitset( n, [n, &func, &spectrum]( const boost::dynamic_bitset<>& bs ) {\n      if ( bs.none() )\n      {\n        spectrum.push_back( 1 << n );\n      }\n      else\n      {\n        boost::dynamic_bitset<> fs( func.size() );\n        foreach_bitset( n, [&bs, &fs, &func]( const boost::dynamic_bitset<>& bs2 ) {\n            fs.set( bs2.to_ulong(), func.test( ( bs2 ^ bs ).to_ulong() ) );\n          } );\n        spectrum.push_back( ( 1 << n ) - 2 * ( fs ^ func ).count() );\n      }\n    } );\n  return spectrum;\n}\n\nvoid print_spectrum( const std::vector<int>& spectrum, unsigned nvars )\n{\n  for ( auto i = 0u; i < spectrum.size(); ++i )\n  {\n    std::cout << boost::dynamic_bitset<>( nvars, i ) << boost::format( \" %5d\" ) % spectrum[i] << std::endl;\n  }\n}\n\nvoid print_spectrum_ordered( const std::vector<int>& spectrum, unsigned nvars )\n{\n  if ( nvars == 4u )\n  {\n    for ( auto i : {0u,16u,1u,2u,4u,8u,16u,3u,5u,9u,6u,10u,12u,16u,7u,11u,13u,14u,16u,15u} )\n    {\n      if ( i == 16u )\n      {\n        std::cout << \" |\";\n      }\n      else\n      {\n        std::cout << \" \" << spectrum[i];\n      }\n    }\n    std::cout << std::endl;\n  }\n  else\n  {\n    std::cout << any_join( spectrum, \" \" ) << std::endl;\n  }\n}\n\nint compare_abs( int a, int b )\n{\n  if ( abs( a ) < abs( b ) )\n  {\n    return -1;\n  }\n  else if ( abs( a ) > abs( b ) )\n  {\n    return 1;\n  }\n  else if ( a < b )\n  {\n    return -1;\n  }\n  else if ( a > b )\n  {\n    return 1;\n  }\n  else\n  {\n    return 0;\n  }\n}\n\n/******************************************************************************\n * Spectral operations                                                        *\n ******************************************************************************/\n\nvoid operation1( std::vector<int>& spectrum, tt& func, const std::vector<unsigned>& perm )\n{\n  std::vector<int> spectrum_p( spectrum.size() );\n  tt func_p = func;\n\n  for ( auto row = 0u; row < spectrum.size(); ++row )\n  {\n    boost::dynamic_bitset<> idx( perm.size(), row ), idx_p( perm.size() );\n    for ( auto i = 0u; i < perm.size(); ++i )\n    {\n      idx_p[i] = idx[perm[i]];\n    }\n\n    spectrum_p[idx_p.to_ulong()] = spectrum[row];\n    func_p.set( idx_p.to_ulong(), func.test( row ) );\n  }\n\n  spectrum = spectrum_p;\n  func = func_p;\n}\n\nvoid operation2( std::vector<int>& spectrum, tt& func, unsigned var )\n{\n  func = tt_flip( func, var );\n\n  for ( auto row = 1u; row < spectrum.size(); ++row )\n  {\n    if ( ( row >> var ) & 1 )\n    {\n      spectrum[row] = -spectrum[row];\n    }\n  }\n}\n\nvoid operation3( std::vector<int>& spectrum, tt& func )\n{\n  func.flip();\n\n  std::transform( spectrum.begin(), spectrum.end(), spectrum.begin(), std::negate<int>() );\n}\n\nvoid operation4( std::vector<int>& spectrum, tt& func, unsigned var, unsigned diff )\n{\n  for ( auto row = 0u; row < spectrum.size(); ++row )\n  {\n    if ( ( row >> var ) & 1 )\n    {\n      auto row2 = row ^ diff;\n      if ( row < row2 )\n      {\n        std::swap( spectrum[row], spectrum[row2] );\n      }\n    }\n  }\n\n  const auto nvars = tt_num_vars( func );\n  boost::dynamic_bitset<> mask( nvars, diff );\n  const auto varbs = onehot_bitset( nvars, var );\n  const auto inc_mask = ~( varbs | mask );\n\n  //std::cout << \"var = \" << var << \", mask = \" << mask << \", diff = \" << diff << std::endl;\n  //std::cout << \"func b \" << func << \" \" << func[15] << \" \" << func[14] << std::endl;\n\n  auto start = varbs;\n  do {\n    //std::cout << start << std::endl;\n\n    auto pattern = start;\n    do {\n      //std::cout << \" \" << pattern;\n      if ( ( pattern & mask ).count() % 2 )\n      {\n        const auto r1 = pattern.to_ulong();\n        const auto r2 = ( pattern ^ varbs ).to_ulong();\n\n        const auto tmp = func.test( r1 );\n        func.set( r1, func.test( r2 ) );\n        func.set( r2, tmp );\n        //std::cout << \" *, swap with \" << ( pattern ^ varbs ) << \" (\" << r1 << \" with \" << r2 << \")\";\n      }\n      //std::cout << std::endl;\n      inc_pos( pattern, mask );\n    } while ( ( pattern & mask ).any() );\n\n    inc_pos( start, inc_mask );\n  } while ( ( start & inc_mask ).any() );\n\n  //std::cout << \"func a \" << func << std::endl;\n}\n\nvoid operation5( std::vector<int>& spectrum, tt& func, unsigned row )\n{\n  const auto nvars = tt_num_vars( func );\n  boost::dynamic_bitset<> mask( nvars, row );\n\n  func ^= make_sum( mask );\n\n  for ( auto i = 0u; i < spectrum.size(); ++i )\n  {\n    const auto j = i ^ row;\n    if ( i < j )\n    {\n      std::swap( spectrum[i], spectrum[j] );\n    }\n  }\n}\n\n/******************************************************************************\n * Canonization operations                                                    *\n ******************************************************************************/\n\nvoid maximize_zero_coefficient( std::vector<int>& spectrum, tt& func )\n{\n  const auto max_coeff = std::max_element( spectrum.begin(), spectrum.end(), []( int a, int b ) { return compare_abs( a, b ) == -1; } );\n\n  if ( *max_coeff < 0 )\n  {\n    operation3( spectrum, func );\n  }\n\n  const auto pos = std::distance( spectrum.begin(), max_coeff );\n\n  if ( pos != 0 )\n  {\n    operation5( spectrum, func, pos );\n  }\n}\n\nvoid minimize_order( std::vector<int>& spectrum, tt& func )\n{\n  const auto n = tt_num_vars( func );\n\n  for ( auto var = 0u; var < n; ++var )\n  {\n    const auto row = 1u << var;\n    /* sweep through the other ones */\n    auto best_row = row;\n    auto best_val = spectrum[row];\n    for ( auto row2 = row + 1u; row2 < spectrum.size(); ++row2 )\n    {\n      if ( ( row & row2 ) != row ) continue;\n\n      if ( compare_abs( spectrum[row2], best_val ) == 1 )\n      {\n        best_val = spectrum[row2];\n        best_row = row2;\n      }\n    }\n\n    /* update values */\n    const auto diff = row ^ best_row;\n    if ( diff )\n    {\n      operation4( spectrum, func, var, diff );\n    }\n  }\n}\n\nvoid sort_inputs( std::vector<int>& spectrum, tt& func )\n{\n  auto cmp = [&spectrum]( unsigned i1, unsigned i2 ) {\n    switch ( compare_abs( spectrum[1 << i1], spectrum[1 << i2] ) )\n    {\n    case -1: return false;\n    case 1: return true;\n    default:\n    return false;\n    }\n  };\n\n  auto cmp4 = [&spectrum]( unsigned i1, unsigned i2 ) {\n    switch ( compare_abs( spectrum[1 << i1], spectrum[1 << i2] ) )\n    {\n    case -1: return false;\n    case 1: return true;\n    default:\n    {\n      for ( auto row : {3, 5, 9, 6, 10, 12} )\n      {\n        if ( ( ( row >> i1 ) & 1 ) && !( ( row >> i2 ) & 1 ) )\n        {\n          auto row2 = ( row ^ ( 1 << i1 ) ) | ( 1 << i2 );\n          switch ( compare_abs( spectrum[row], spectrum[row2] ) )\n          {\n          case -1: return true;\n          case 1: return false;\n          }\n        }\n        else if ( !( ( row >> i1 ) & 1 ) && ( ( row >> i2 ) & 1 ) )\n        {\n          auto row2 = ( row ^ ( 1 << i2 ) ) | ( 1 << i1 );\n          switch ( compare_abs( spectrum[row], spectrum[row2] ) )\n          {\n          case -1: return true;\n          case 1: return false;\n          }\n        }\n      }\n      return false;\n    }\n    }\n  };\n\n  const auto nvars = tt_num_vars( func );\n  std::vector<unsigned> proj( nvars );\n  std::iota( proj.begin(), proj.end(), 0u );\n\n  if ( nvars <= 3 )\n  {\n    std::sort( proj.begin(), proj.end(), cmp );\n  }\n  else\n  {\n    std::sort( proj.begin(), proj.end(), cmp4 );\n  }\n\n  operation1( spectrum, func, proj );\n}\n\nvoid invert_inputs( std::vector<int>& spectrum, tt& func )\n{\n  const auto nvars = tt_num_vars( func );\n\n  for ( auto i = 0u; i < nvars; ++i )\n  {\n    if ( spectrum[1 << i] < 0 )\n    {\n      operation2( spectrum, func, i );\n    }\n  }\n}\n\n/******************************************************************************\n * Public functions                                                           *\n ******************************************************************************/\n\ntt spectral_canonization( const tt& func, const properties::ptr& settings, const properties::ptr& statistics )\n{\n  const auto verbose = get( settings, \"verbose\", false );\n  const auto very_verbose = get( settings, \"very_verbose\", false );\n\n  properties_timer t( statistics );\n\n  const auto nvars = tt_num_vars( func );\n  auto spectrum = rademacher_walsh_spectrum( func );\n  set( statistics, \"spectrum_init\", spectrum );\n  auto cfunc = func;\n\n  if ( verbose )\n  {\n    std::cout << \"AC \" << any_join( autocorrelation_spectrum( func ), \" \" ) << std::endl;\n    std::cout << \"before\" << std::endl;\n    if ( very_verbose ) print_spectrum( spectrum, nvars );\n    print_spectrum_ordered( spectrum, nvars );\n  }\n\n  maximize_zero_coefficient( spectrum, cfunc );\n\n  if ( verbose )\n  {\n    std::cout << \"after step 1\" << std::endl;\n    if ( very_verbose ) print_spectrum( spectrum, nvars );\n    print_spectrum_ordered( spectrum, nvars );\n    std::cout << cfunc << std::endl;\n  }\n\n  minimize_order( spectrum, cfunc );\n\n  if ( verbose )\n  {\n    std::cout << \"after step 2\" << std::endl;\n    if ( very_verbose ) print_spectrum( spectrum, nvars );\n    print_spectrum_ordered( spectrum, nvars );\n    std::cout << cfunc << std::endl;\n  }\n\n  invert_inputs( spectrum, cfunc );\n\n  if ( verbose )\n  {\n    std::cout << \"after step 3\" << std::endl;\n    if ( very_verbose ) print_spectrum( spectrum, nvars );\n    print_spectrum_ordered( spectrum, nvars );\n    std::cout << cfunc << std::endl;\n  }\n\n  sort_inputs( spectrum, cfunc );\n\n  if ( verbose )\n  {\n    std::cout << \"after step 4\" << std::endl;\n    if ( very_verbose ) print_spectrum( spectrum, nvars );\n    print_spectrum_ordered( spectrum, nvars );\n    std::cout << cfunc << std::endl;\n  }\n\n  set( statistics, \"spectrum_final\", spectrum );\n  set( statistics, \"class\", get_spectral_class( func ) );\n\n  // if ( !( ( spectrum == std::vector<int>( {16, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0} ) ) ||\n  //         ( spectrum == std::vector<int>( {14, 2, 2, -2, 2, -2, -2, 2, 2, -2, -2, 2, -2, 2, 2, -2} ) ) ||\n  //         ( spectrum == std::vector<int>( {12, 4, 4, -4, 4, -4, -4, 4, 0, 0, 0, 0, 0, 0, 0, 0} ) ) ||\n  //         ( spectrum == std::vector<int>( {10, 6, 6, -6, 2, -2, -2, 2, 2, -2, -2, 2, 2, -2, -2, 2} ) ) ||\n  //         ( spectrum == std::vector<int>( {8, 8, 8, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0} ) ) ||\n  //         ( spectrum == std::vector<int>( {8, 8, 4, -4, 4, -4, 0, 0, 4, -4, 0, 0, 0, 0, -4, 4} ) ) ||\n  //         ( spectrum == std::vector<int>( {6, 6, 6, -2, 6, -2, -2, -2, 6, -2, -2, -2, -2, -2, -2, 6} ) ) ||\n  //         ( spectrum == std::vector<int>( {4, 4, 4, 4, 4, 4, -4, -4, 4, -4, 4, -4, -4, 4, 4, -4} ) ) ) )\n  // {\n  //   std::cout << \"[w] wrongly classified \" << func << std::endl;\n  //   print_spectrum_ordered( spectrum );\n  //   print_spectrum( spectrum, nvars );\n  // }\n\n  return cfunc;\n}\n\nunsigned get_spectral_class( const tt& func )\n{\n  const auto nvars = tt_num_vars( func );\n\n  assert( nvars >= 2u && nvars <= 5u );\n\n  auto spectrum = rademacher_walsh_spectrum( func );\n  std::transform( spectrum.begin(), spectrum.end(), spectrum.begin(), []( int i ) { return abs( i ); } );\n  std::stable_sort( spectrum.begin(), spectrum.end(), std::not2( std::less<int>() ) );\n\n  switch ( nvars )\n  {\n  case 2u:\n    return spectrum.front() == 4 ? 0u : 1u;\n  case 3u:\n    switch ( spectrum.front() )\n    {\n    case 8: return 0u;\n    case 6: return 1u;\n    case 4: return 2u;\n    } break;\n  case 4u:\n    switch ( spectrum.front() )\n    {\n    case 16: return 0u;\n    case 14: return 1u;\n    case 12: return 2u;\n    case 10: return 3u;\n    case 8: return spectrum[2u] == 8 ? 4u : 5u;\n    case 6: return 6u;\n    case 4: return 7u;\n    } break;\n  case 5u:\n    switch ( spectrum.front() )\n    {\n    case 32: return 0u;\n    case 30: return 1u;\n    case 28: return 2u;\n    case 26: return 3u;\n    case 24: return spectrum[4u] == 8 ? 4u : 5u;\n    case 22: return spectrum[2u] == 6 ? 6u : 7u;\n    case 20:\n      if ( spectrum[1u] == 12 && spectrum[2u] == 4 ) return 8u;\n      else if ( spectrum[1u] == 8 ) return 9u;\n      else if ( spectrum[1u] == 12 && spectrum[2u] == 8 ) return 10u;\n      else if ( spectrum[1u] == 12 && spectrum[2u] == 12 ) return 11u;\n      else assert( false ); break;\n    case 18:\n      if ( spectrum[1u] == 10 && spectrum[2u] == 6 ) return 12u;\n      else if ( spectrum[1u] == 14 && spectrum[2u] == 6 ) return 13u;\n      else if ( spectrum[1u] == 10 && spectrum[2u] == 10 ) return 14u;\n      else if ( spectrum[1u] == 14 && spectrum[2u] == 10 ) return 15u;\n      else if ( spectrum[1u] == 14 && spectrum[2u] == 14 ) return 16u;\n      else assert( false ); break;\n    case 16:\n      if ( spectrum[1u] == 16 && spectrum[2u] == 16 ) return 17u;\n      else if ( spectrum[1u] == 8 && spectrum[9u] == 8 ) return 18u;\n      else if ( spectrum[1u] == 16 && spectrum[2u] == 8 && spectrum[6] == 8) return 19u;\n      else if ( spectrum[1u] == 8 && spectrum[9u] == 4 ) return 20u;\n      else if ( spectrum[1u] == 12 && spectrum[2u] == 8 ) return 21u;\n      else if ( spectrum[1u] == 16 && spectrum[2u] == 8 && spectrum[6] == 4 ) return 22u;\n      else if ( spectrum[1u] == 12 && spectrum[2u] == 12 ) return 23u;\n      else if ( spectrum[1u] == 16 && spectrum[2u] == 12 ) return 24u;\n      else assert( false ); break;\n    case 14:\n      if ( spectrum[1u] == 10 && spectrum[2u] == 10 && spectrum[5u] == 6 )\n      {\n        auto ac = autocorrelation_spectrum( func );\n        std::transform( ac.begin(), ac.end(), ac.begin(), []( int i ) { return abs( i ); } );\n        std::stable_sort( ac.begin(), ac.end(), std::not2( std::less<int>() ) );\n        return ac[1u] == 12 ? 25u : 26u;\n      }\n      else if ( spectrum[1u] == 14 && spectrum[2u] == 10 && spectrum[4u] == 6 ) return 27u;\n      else if ( spectrum[1u] == 10 && spectrum[2u] == 10 && spectrum[5u] == 10 ) return 28u;\n      else if ( spectrum[1u] == 14 && spectrum[2u] == 14 ) return 29u;\n      else if ( spectrum[1u] == 14 && spectrum[2u] == 10 && spectrum[4u] == 10 ) return 30;\n      else assert( false ); break;\n    case 12:\n      if ( spectrum[1u] == 8 ) return 33u;\n      else if ( spectrum[1u] == 12 && spectrum[2u] == 8 )\n      {\n        auto ac = autocorrelation_spectrum( func );\n        std::transform( ac.begin(), ac.end(), ac.begin(), []( int i ) { return abs( i ); } );\n        std::stable_sort( ac.begin(), ac.end(), std::not2( std::less<int>() ) );\n        return ac[1u] == 16 ? 34u : 35u;\n      }\n      else if ( spectrum[1u] == 12 && spectrum[2u] == 12 && spectrum[3u] == 8 ) return 36;\n      else if ( spectrum[4u] == 4 )\n      {\n        auto ac = autocorrelation_spectrum( func );\n        std::transform( ac.begin(), ac.end(), ac.begin(), []( int i ) { return abs( i ); } );\n        std::stable_sort( ac.begin(), ac.end(), std::not2( std::less<int>() ) );\n        return ac[4u] == 8 ? 31u : 32u;\n      }\n      else if ( spectrum[4u] == 8 )\n      {\n        auto ac = autocorrelation_spectrum( func );\n        std::transform( ac.begin(), ac.end(), ac.begin(), []( int i ) { return abs( i ); } );\n        std::stable_sort( ac.begin(), ac.end(), std::not2( std::less<int>() ) );\n        return ac[1u] == 16 ? 37u : 38u;\n      }\n      else if ( spectrum[4u] == 12 ) return 39u;\n      else assert( false ); break;\n    case 10:\n      if ( spectrum[4u] == 6 ) return 40u;\n      else if ( spectrum[4u] == 10 )\n      {\n        auto ac = autocorrelation_spectrum( func );\n        std::transform( ac.begin(), ac.end(), ac.begin(), []( int i ) { return abs( i ); } );\n        std::stable_sort( ac.begin(), ac.end(), std::not2( std::less<int>() ) );\n        return ac[1u] == 12 ? 41u : ( ac[1u] == 20 ? 42u : 43u );\n      }\n      else assert( false ); break;\n    case 8:\n      if ( spectrum[12u] == 8 )\n      {\n        auto ac = autocorrelation_spectrum( func );\n        std::transform( ac.begin(), ac.end(), ac.begin(), []( int i ) { return abs( i ); } );\n        std::stable_sort( ac.begin(), ac.end(), std::not2( std::less<int>() ) );\n        return ac[1u] == 32 ? 44u : ( ac[1u] == 8 ? 45u : 46u );\n      }\n      else if ( spectrum[12u] == 4 ) return 47u;\n      else assert( false ); break;\n    } break;\n  }\n\n  return 0u;\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": "a1c31a0cba569a4314b9f0adab5f3d5994ee8121", "size": 18716, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/classical/functions/spectral_canonization.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/functions/spectral_canonization.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/functions/spectral_canonization.cpp", "max_forks_repo_name": "eletesta/cirkit", "max_forks_repo_head_hexsha": "6d0939798ea25cecf92306ce796be154139b94f5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.7828947368, "max_line_length": 136, "alphanum_fraction": 0.5145330199, "num_tokens": 5688, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6224593312018545, "lm_q2_score": 0.5583269943353744, "lm_q1q2_score": 0.34753584748593874}}
{"text": "// Distributed under the MIT License.\n// See LICENSE.txt for details.\n\n#pragma once\n\n#include <boost/none.hpp>\n#include <boost/optional.hpp>\n#include <vector>\n\n#include \"DataStructures/DataVector.hpp\"\n#include \"ErrorHandling/Error.hpp\"\n#include \"Utilities/Gsl.hpp\"\n\nnamespace RootFinder {\nnamespace bracketing_detail {\n// Brackets a root, given a functor f(x) that returns a\n// boost::optional<double> and given two arrays x and y (with y=f(x))\n// containing points that have already been tried for bracketing.\n//\n// Returns a std::array<double,4> containing {{x1,x2,y1,y2}} where\n// x1 and x2 bracket the root, and y1=f(x1) and y2=f(x2).\n//\n// Note that y might be undefined (i.e. an invalid boost::optional)\n// for values of x at or near the endpoints of the interval.  We\n// assume that if f(x1) and f(x2) are valid for some x1 and x2, then\n// f(x) is valid for all x between x1 and x2.\n//\n// Assumes that there is a root between the first and last points of\n// the array.\n// We also assume that there is only one root.\n//\n// So this means we have only 2 possibilities for the validity of the\n// points in the input x,y arrays:\n// 1) All points are invalid, e.g. \"X X X X X X X X\".\n//    (here X represents an invalid point)\n// 2) All valid points are adjacent, with the same sign, e.g. \"X X o o X X\"\n//    or \"o o X X X\" or \"X X X o o\".\n//    (here o represents a valid point)\n// Note that we assume that all valid points have the same sign; otherwise\n// the caller would have known that the root was bracketed and the caller would\n// not have called bracket_by_contracting.\n//\n// Also note that we exclude the case \"o o o o o\" (no roots), since the\n// caller would have known that too.  If such a case is found, an error is\n// thrown.  An error is also thrown if the size of the region where the\n// sign changes is so small that the number of iterations is exceeded.\n//\n// For case 1) above, we bisect each pair of points, and call\n// bracket_by_contracting recursively until we find a valid point.\n// For case 2) above, it is sufficent to check for a bracket only\n// between valid and invalid points.  That is, for \"X X + + X X\" we\n// check only between points 1 and 2 and between points 3 and 4 (where\n// points are numbered starting from zero).  For \"+ + X X X\" we check\n// only between points 1 and 2.\ntemplate <typename Functor>\nstd::array<double, 4> bracket_by_contracting(\n    const std::vector<double>& x, const std::vector<boost::optional<double>>& y,\n    const Functor& f, const size_t level = 0) noexcept {\n  constexpr size_t max_level = 6;\n  if (level > max_level) {\n    ERROR(\"Too many iterations in bracket_by_contracting. Either refine the \"\n          \"initial range/guess or increase max_level.\");\n  }\n\n  // First check if we have any valid points.\n  size_t last_valid_index = y.size();\n  for (size_t i = y.size(); i >= 1; --i) {\n    if (y[i - 1]) {\n      last_valid_index = i - 1;\n      break;\n    }\n  }\n\n  if (last_valid_index == y.size()) {\n    // No valid points!\n\n    // Create larger arrays with one point between each of the already\n    // computed points.\n    std::vector<double> bisected_x(x.size() * 2 - 1);\n    std::vector<boost::optional<double>> bisected_y(y.size() * 2 - 1);\n\n    // Copy all even-numbered points in the range.\n    for (size_t i = 0; i < x.size(); ++i) {\n      bisected_x[2 * i] = x[i];\n      bisected_y[2 * i] = y[i];\n    }\n\n    // Fill midpoints and check for bracket on each one.\n    for (size_t i = 0; i < x.size() - 1; ++i) {\n      bisected_x[2 * i + 1] = x[i] + 0.5 * (x[i + 1] - x[i]);\n      bisected_y[2 * i + 1] = f(bisected_x[2 * i + 1]);\n      if (bisected_y[2 * i + 1]) {\n        // Valid point! We know that all the other points are\n        // invalid, so we need to check only 3 points in the next\n        // iteration: the new valid point and its neighbors.\n        return bracket_by_contracting({{x[i], bisected_x[2 * i + 1], x[i + 1]}},\n                                      {{y[i], bisected_y[2 * i + 1], y[i + 1]}},\n                                      f, level + 1);\n      }\n    }\n    // We still have no valid points. So recurse, using all points.\n    // The next iteration will bisect all the points.\n    return bracket_by_contracting(bisected_x, bisected_y, f, level + 1);\n  }\n\n  // If we get here, we have found a valid point; in particular we have\n  // found the last valid point in the array.\n\n  // Find the first valid point in the array.\n  size_t first_valid_index = 0;\n  for (size_t i = 0; i < y.size(); ++i) {\n    if (y[i]) {\n      first_valid_index = i;\n      break;\n    }\n  }\n\n  // Make a new set of points that includes only the points that\n  // neighbor the boundary between valid and invalid points.\n  std::vector<double> x_near_valid_point;\n  std::vector<boost::optional<double>> y_near_valid_point;\n\n  if (first_valid_index == 0 and last_valid_index == y.size() - 1) {\n    ERROR(\n        \"bracket_while_contracting: found a case where all points are valid,\"\n        \"which should not happen under our assumptions.\");\n  }\n\n  if (first_valid_index > 0) {\n    // Check for a root between first_valid_index-1 and first_valid_index.\n    const double x_test =\n        x[first_valid_index - 1] +\n        0.5 * (x[first_valid_index] - x[first_valid_index - 1]);\n    const auto y_test = f(x_test);\n    if (y_test and y[first_valid_index].get() * y_test.get() <= 0.0) {\n      // Bracketed!\n      return std::array<double, 4>{{x_test, x[first_valid_index], y_test.get(),\n                                    y[first_valid_index].get()}};\n    } else {\n      x_near_valid_point.push_back(x[first_valid_index - 1]);\n      y_near_valid_point.push_back(y[first_valid_index - 1]);\n      x_near_valid_point.push_back(x_test);\n      y_near_valid_point.push_back(y_test);\n      x_near_valid_point.push_back(x[first_valid_index]);\n      y_near_valid_point.push_back(y[first_valid_index]);\n    }\n  }\n  if (last_valid_index < y.size() - 1) {\n    // Check for a root between last_valid_index and last_valid_index+1.\n    const double x_test = x[last_valid_index] +\n                          0.5 * (x[last_valid_index + 1] - x[last_valid_index]);\n    const auto y_test = f(x_test);\n    if (y_test and y[last_valid_index].get() * y_test.get() <= 0.0) {\n      // Bracketed!\n      return std::array<double, 4>{{x[last_valid_index], x_test,\n                                    y[last_valid_index].get(), y_test.get()}};\n    } else {\n      if (first_valid_index != last_valid_index or first_valid_index == 0) {\n        x_near_valid_point.push_back(x[last_valid_index]);\n        y_near_valid_point.push_back(y[last_valid_index]);\n      }  // else we already pushed back last_valid_index (==first_valid_index).\n      x_near_valid_point.push_back(x_test);\n      y_near_valid_point.push_back(y_test);\n      x_near_valid_point.push_back(x[last_valid_index + 1]);\n      y_near_valid_point.push_back(y[last_valid_index + 1]);\n    }\n  }\n\n  // We have one or more valid points but we didn't find a bracket.\n  // That is, we have something like \"X X o o X X\" or \"X X o o\" or \"o o X X\".\n  // So recurse, zooming in to the boundary (either one boundary or two\n  // boundaries) between valid and invalid points.\n  // Note that \"o o o o\" is prohibited by our assumptions, and checked for\n  // above just in case it occurs by mistake.\n  return bracket_by_contracting(x_near_valid_point, y_near_valid_point, f,\n                                level + 1);\n}\n}  // namespace bracketing_detail\n\n/*!\n * \\ingroup NumericalAlgorithmsGroup\n * \\brief Brackets the root of the function `f`, assuming a single\n * root in a given interval \\f$f[x_\\mathrm{lo},x_\\mathrm{up}]\\f$\n * and assuming that `f` is defined only in an unknown smaller\n * interval \\f$f[x_a,x_b]\\f$ where\n * \\f$x_\\mathrm{lo} \\leq x_a \\leq x_b \\leq x_\\mathrm{hi}\\f$.\n *\n * `f` is a unary invokable that takes a `double` which is the current value at\n * which to evaluate `f`.  `f` returns a `boost::optional<double>` which\n * evaluates to false if the function is undefined at the supplied point.\n *\n * Assumes that there is only one root in the interval.\n *\n * Assumes that if \\f$f(x_1)\\f$ and \\f$f(x_2)\\f$ are both defined for\n * some \\f$(x_1,x_2)\\f$, then \\f$f(x)\\f$ is defined for all \\f$x\\f$\n * between \\f$x_1\\f$ and \\f$x_2\\f$.\n *\n * On input, assumes that the root lies in the interval\n * [`lower_bound`,`upper_bound`].  Optionally takes a `guess` for the\n * location of the root.  If `guess` is supplied, then evaluates the\n * function first at `guess` and `upper_bound` before trying\n * `lower_bound`: this means that it would be optimal if `guess`\n * underestimates the actual root and if `upper_bound` was less likely\n * to be undefined than `lower_bound`.\n *\n * On return, `lower_bound` and `upper_bound` are replaced with values that\n * bracket the root and for which the function is defined, and\n * `f_at_lower_bound` and `f_at_upper_bound` are replaced with\n * `f` evaluated at those bracketing points.\n *\n * `bracket_possibly_undefined_function_in_interval` throws an error if\n *  all points are valid but of the same sign (because that would indicate\n *  multiple roots but we assume only one root), if no root exists, or\n *  if the range of a sign change is sufficently small relative to the\n *  given interval that the number of iterations to find the root is exceeded.\n *\n */\ntemplate <typename Functor>\nvoid bracket_possibly_undefined_function_in_interval(\n    const gsl::not_null<double*> lower_bound,\n    const gsl::not_null<double*> upper_bound,\n    const gsl::not_null<double*> f_at_lower_bound,\n    const gsl::not_null<double*> f_at_upper_bound, const Functor& f,\n    const double guess) noexcept {\n  // Initial values of x1,x2,y1,y2.  Use `guess` and `upper_bound`,\n  // because in typical usage `guess` underestimates the actual\n  // root, and `lower_bound` is more likely than `upper_bound` to be\n  // invalid.\n  double x1 = guess;\n  double x2 = *upper_bound;\n  auto y1 = f(x1);\n  auto y2 = f(x2);\n  const bool y1_defined = static_cast<bool>(y1);\n  const bool y2_defined = static_cast<bool>(y2);\n  if (not(y1_defined and y2_defined and y1.get() * y2.get() <= 0.0)) {\n    // Root is not bracketed.\n    // Before moving to the general algorithm, try the remaining\n    // input point that was supplied.\n    const double x3 = *lower_bound;\n    const auto y3 = f(x3);\n    const bool y3_defined = static_cast<bool>(y3);\n    if (y1_defined and y3_defined and y1.get() * y3.get() <= 0.0) {\n      // Bracketed! Throw out x2,y2.  Rename variables to keep x1 < x2.\n      x2 = x1;\n      y2 = y1;\n      x1 = x3;\n      y1 = y3;\n    } else {\n      // Our simple checks didn't work, so call the more general method.\n      // There are 8 cases:\n      //\n      // y3 y1 y2\n      // --------\n      // X  X  X\n      // o  X  X\n      // X  o  X\n      // o  o  X\n      // X  o  o\n      // o  o  o\n      // X  X  o\n      // o  X  o\n      //\n      // where X means an invalid point, o means a valid point.\n      // All valid points have the same sign, or we would have found a\n      // bracket already.\n      //\n      // Before calling the general case, error on \"o o o\" and \"o X o\".\n      // Both of these are prohibited by our assumptions (we\n      // assume the root is in the interval so no \"o o o\", and we\n      // assume that all invalid points are at the end of interval, so no\n      // \"o X o\").\n      if (y2_defined and y3_defined) {\n        ERROR(\n            \"bracket_possibly_undefined_function_in_interval: found \"\n            \"case that should not happen under our assumptions.\");\n      }\n      std::array<double, 4> tmp = bracketing_detail::bracket_by_contracting(\n          {{x3, x1, x2}}, {{y3, y1, y2}}, f);\n      x1 = tmp[0];\n      x2 = tmp[1];\n      y1 = tmp[2];\n      y2 = tmp[3];\n    }\n  }\n  *f_at_lower_bound = y1.get();\n  *f_at_upper_bound = y2.get();\n  *lower_bound = x1;\n  *upper_bound = x2;\n}\n\n/*!\n * \\ingroup NumericalAlgorithmsGroup\n * \\brief Brackets the single root of the\n * function `f` for each element in a `DataVector`, assuming the root\n * lies in the given interval and that `f` may be undefined at some\n * points in the interval.\n *\n * `f` is a binary invokable that takes a `double` and a `size_t` as\n * arguments.  The `double` is the current value at which to evaluate\n * `f`, and the `size_t` is the index into the `DataVector`s.  `f`\n * returns a `boost::optional<double>` which evaluates to false if the\n * function is undefined at the supplied point.\n *\n * Assumes that there is only one root in the interval.\n *\n * Assumes that if \\f$f(x_1)\\f$ and \\f$f(x_2)\\f$ are both defined for\n * some \\f$(x_1,x_2)\\f$, then \\f$f(x)\\f$ is defined for all \\f$x\\f$\n * between \\f$x_1\\f$ and \\f$x_2\\f$.\n *\n * On input, assumes that the root lies in the interval\n * [`lower_bound`,`upper_bound`].  Optionally takes a `guess` for the\n * location of the root.\n *\n * On return, `lower_bound` and `upper_bound` are replaced with values that\n * bracket the root and for which the function is defined, and\n * `f_at_lower_bound` and `f_at_upper_bound` are replaced with\n * `f` evaluated at those bracketing points.\n *\n */\ntemplate <typename Functor>\nvoid bracket_possibly_undefined_function_in_interval(\n    const gsl::not_null<DataVector*> lower_bound,\n    const gsl::not_null<DataVector*> upper_bound,\n    const gsl::not_null<DataVector*> f_at_lower_bound,\n    const gsl::not_null<DataVector*> f_at_upper_bound, const Functor& f,\n    const DataVector& guess) noexcept {\n  for (size_t s = 0; s < lower_bound->size(); ++s) {\n    bracket_possibly_undefined_function_in_interval(\n        &((*lower_bound)[s]), &((*upper_bound)[s]), &((*f_at_lower_bound)[s]),\n        &((*f_at_upper_bound)[s]),\n        [&f, &s ](const double x) noexcept { return f(x, s); }, guess[s]);\n  }\n}\n\n/*\n * Version of `bracket_possibly_undefined_function_in_interval`\n * without a supplied initial guess; uses the mean of `lower_bound` and\n * `upper_bound` as the guess.\n */\ntemplate <typename Functor>\nvoid bracket_possibly_undefined_function_in_interval(\n    const gsl::not_null<double*> lower_bound,\n    const gsl::not_null<double*> upper_bound,\n    const gsl::not_null<double*> f_at_lower_bound,\n    const gsl::not_null<double*> f_at_upper_bound, const Functor& f) noexcept {\n  bracket_possibly_undefined_function_in_interval(\n      lower_bound, upper_bound, f_at_lower_bound, f_at_upper_bound, f,\n      *lower_bound + 0.5 * (*upper_bound - *lower_bound));\n}\n\n/*\n * Version of `bracket_possibly_undefined_function_in_interval`\n * without a supplied initial guess; uses the mean of `lower_bound` and\n * `upper_bound` as the guess.\n */\ntemplate <typename Functor>\nvoid bracket_possibly_undefined_function_in_interval(\n    const gsl::not_null<DataVector*> lower_bound,\n    const gsl::not_null<DataVector*> upper_bound,\n    const gsl::not_null<DataVector*> f_at_lower_bound,\n    const gsl::not_null<DataVector*> f_at_upper_bound,\n    const Functor& f) noexcept {\n  bracket_possibly_undefined_function_in_interval(\n      lower_bound, upper_bound, f_at_lower_bound, f_at_upper_bound, f,\n      *lower_bound + 0.5 * (*upper_bound - *lower_bound));\n}\n}  // namespace RootFinder\n", "meta": {"hexsha": "4fcd5aa0862ee1c20a19304763576a534e62ecc1", "size": 15070, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/NumericalAlgorithms/RootFinding/RootBracketing.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/NumericalAlgorithms/RootFinding/RootBracketing.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/NumericalAlgorithms/RootFinding/RootBracketing.hpp", "max_forks_repo_name": "tomwlodarczyk/spectre", "max_forks_repo_head_hexsha": "086aaee002f2f07eb812cf17b8e1ba54052feb71", "max_forks_repo_licenses": ["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.9510869565, "max_line_length": 80, "alphanum_fraction": 0.6642335766, "num_tokens": 4143, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6688802603710086, "lm_q2_score": 0.519521321952093, "lm_q1q2_score": 0.34749755709560654}}
{"text": "/*\n * Copyright (c) 2021 The Foundation for Research on Information Technologies in Society (IT'IS).\n *\n * This file is part of iSEG\n * (see https://github.com/ITISFoundation/osparc-iseg).\n *\n * This software is released under the MIT License.\n *  https://opensource.org/licenses/MIT\n */\n#include \"AutoTubeWidget.h\"\n\n#include \"Data/ItkUtils.h\"\n#include \"Data/Logger.h\"\n#include \"Data/SlicesHandlerITKInterface.h\"\n\n#include \"Thirdparty/IJ/BinaryThinningImageFilter3D/itkBinaryThinningImageFilter3D.h\"\n#include \"Thirdparty/IJ/NonMaxSuppression/itkNonMaxSuppressionImageFilter.h\"\n\n#include <itkBinaryThinningImageFilter.h>\n#include <itkBinaryThresholdImageFilter.h>\n#include <itkConnectedComponentImageFilter.h>\n#include <itkCurvesLevelSetImageFilter.h>\n#include <itkFastMarchingImageFilter.h>\n#include <itkGradientMagnitudeRecursiveGaussianImageFilter.h>\n#include <itkHessianToObjectnessMeasureImageFilter.h>\n#include <itkImage.h>\n#include <itkMinimumMaximumImageCalculator.h>\n#include <itkMultiScaleHessianBasedMeasureImageFilter.h>\n#include <itkRelabelComponentImageFilter.h>\n#include <itkRescaleIntensityImageFilter.h>\n#include <itkSigmoidImageFilter.h>\n#include <itkSliceBySliceImageFilter.h>\n#include <itkThresholdImageFilter.h>\n\n#include <accumulators/percentile.hpp>\n#include <boost/accumulators/accumulators.hpp>\n#include <boost/accumulators/statistics/max.hpp>\n#include <boost/accumulators/statistics/mean.hpp>\n#include <boost/accumulators/statistics/min.hpp>\n#include <boost/accumulators/statistics/stats.hpp>\n#include <boost/accumulators/statistics/variance.hpp>\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/range/adaptor/transformed.hpp>\n\n#include <QFormLayout>\n#include <QMessageBox>\n#include <QScrollArea>\n\n#include <algorithm>\n#include <sstream>\n\nnamespace acc = boost::accumulators;\nusing boost::adaptors::transformed;\nusing boost::algorithm::join;\n\ntemplate<typename TInputImage, typename TOutputImage, unsigned int Dimension>\nclass BinaryThinningImageFilter : public itk::BinaryThinningImageFilter<TInputImage, TOutputImage>\n{\n};\n\ntemplate<typename TInputImage, typename TOutputImage>\nclass BinaryThinningImageFilter<TInputImage, TOutputImage, 3> : public itk::BinaryThinningImageFilter3D<TInputImage, TOutputImage>\n{\n};\n\nAutoTubeWidget::AutoTubeWidget(iseg::SlicesHandlerInterface* hand3D)\n\t\t: m_Handler3D(hand3D)\n{\n\tsetToolTip(Format(\"Sandbox Tool\"));\n\n\tm_Metric2d = new QCheckBox;\n\tm_Metric2d->setChecked(false);\n\tm_Metric2d->setToolTip(Format(\"Use 2D pseudo vesselness (blob feature per slice), or use full 3D vesselness.\"));\n\n\tm_NonMaxSuppression = new QCheckBox;\n\tm_NonMaxSuppression->setChecked(true);\n\tm_NonMaxSuppression->setToolTip(Format(\"Extract approx. one pixel wide paths based on non-maximum suppression.\"));\n\n\tm_Skeletonize = new QCheckBox;\n\tm_Skeletonize->setChecked(true);\n\tm_Skeletonize->setToolTip(Format(\"Compute 1-pixel wide centerlines (skeleton).\"));\n\n\tm_SigmaLow = new QLineEdit(QString::number(0.3));\n\tm_SigmaLow->setValidator(new QDoubleValidator);\n\n\tm_SigmaHi = new QLineEdit(QString::number(0.6));\n\tm_SigmaHi->setValidator(new QDoubleValidator);\n\n\tm_NumberSigmaLevels = new QLineEdit(QString::number(2));\n\tm_NumberSigmaLevels->setValidator(new QIntValidator);\n\n\tm_Threshold = new QLineEdit;\n\tm_Threshold->setValidator(new QDoubleValidator);\n\n\tm_MaxRadius = new QLineEdit(QString::number(1));\n\tm_MaxRadius->setValidator(new QDoubleValidator);\n\n\tm_MinObjectSize = new QLineEdit(QString::number(10));\n\tm_MinObjectSize->setValidator(new QIntValidator);\n\n\tm_SelectObjectsButton = new QPushButton(\"Select Mask\");\n\tm_SelectedObjects = new QLineEdit;\n\tm_SelectedObjects->setReadOnly(true);\n\n\tm_ExecuteButton = new QPushButton(\"Execute\");\n\n\tauto layout = new QFormLayout;\n\tlayout->addRow(\"Sigma Min\", m_SigmaLow);\n\tlayout->addRow(\"Sigma Max\", m_SigmaHi);\n\tlayout->addRow(\"Number of Sigmas\", m_NumberSigmaLevels);\n\tlayout->addRow(\"2D Vesselness\", m_Metric2d);\n\tlayout->addRow(\"Feature Threshold\", m_Threshold);\n\tlayout->addRow(\"Non-maximum Suppression\", m_NonMaxSuppression);\n\tlayout->addRow(\"Centerlines\", m_Skeletonize);\n\t//layout->addRow(\"Maximum radius\", _max_radius);\n\tlayout->addRow(\"Minimum object size\", m_MinObjectSize);\n\tlayout->addRow(m_SelectObjectsButton, m_SelectedObjects);\n\tlayout->addRow(m_ExecuteButton);\n\n\tauto big_view = new QWidget;\n\tbig_view->setLayout(layout);\n\n\tauto scroll_area = new QScrollArea(this);\n\tscroll_area->setWidget(big_view);\n\n\tauto top_layout = new QGridLayout(1, 1);\n\ttop_layout->addWidget(scroll_area, 0, 0);\n\tsetLayout(top_layout);\n\n\tQObject_connect(m_SelectObjectsButton, SIGNAL(clicked()), this, SLOT(SelectObjects()));\n\tQObject_connect(m_ExecuteButton, SIGNAL(clicked()), this, SLOT(DoWork()));\n}\n\nvoid AutoTubeWidget::Init()\n{\n\tOnSlicenrChanged();\n\tHideParamsChanged();\n}\n\nvoid AutoTubeWidget::NewLoaded()\n{\n\tOnSlicenrChanged();\n}\n\nvoid AutoTubeWidget::OnSlicenrChanged()\n{\n}\n\nvoid AutoTubeWidget::Cleanup()\n{\n\tm_SelectedObjects->setText(\"\");\n\tm_CachedFeatureImage.img = nullptr;\n}\n\nvoid AutoTubeWidget::OnMouseClicked(iseg::Point p)\n{\n}\n\nvoid AutoTubeWidget::SelectObjects()\n{\n\tauto sel = m_Handler3D->TissueSelection();\n\tstd::cout << \"sel \" << sel[0] << std::endl;\n\tstd::string text = join(sel | transformed([](int d) { return std::to_string(d); }), \", \");\n\tm_SelectedObjects->setText(QString::fromStdString(text));\n}\n\nvoid AutoTubeWidget::DoWork()\n{\n\tiseg::SlicesHandlerITKInterface itk_handler(m_Handler3D);\n\ttry\n\t{\n\t\tif ((true)) //(all_slices->isChecked())\n\t\t{\n\t\t\tusing input_type = itk::SliceContiguousImage<float>;\n\t\t\tusing tissues_type = itk::SliceContiguousImage<iseg::tissues_size_t>;\n\t\t\tauto source = itk_handler.GetSource(true); // active_slices -> correct seed z-position\n\t\t\tauto target = itk_handler.GetTarget(true);\n\t\t\tauto tissues = itk_handler.GetTissues(true);\n\t\t\tDoWorkNd<input_type, tissues_type, input_type>(source, tissues, target);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tusing input_type = itk::Image<float, 2>;\n\t\t\tusing tissues_type = itk::Image<iseg::tissues_size_t, 2>;\n\t\t\tauto source = itk_handler.GetSourceSlice();\n\t\t\tauto target = itk_handler.GetTargetSlice();\n\t\t\tauto tissues = itk_handler.GetTissuesSlice();\n\t\t\tDoWorkNd<input_type, tissues_type, input_type>(source, tissues, target);\n\t\t}\n\t}\n\tcatch (const std::exception& e)\n\t{\n\t\tQMessageBox::warning(this, \"iSeg\", QString(\"Error: \") + e.what(), QMessageBox::Ok | QMessageBox::Default);\n\t}\n}\n\ntemplate<class TInput, class TImage>\ntypename TImage::Pointer AutoTubeWidget::ComputeFeatureImage(TInput* source) const\n{\n\titkStaticConstMacro(ImageDimension, size_t, TInput::ImageDimension);\n\tusing hessian_pixel_type = itk::SymmetricSecondRankTensor<float, ImageDimension>;\n\tusing hessian_image_type = itk::Image<hessian_pixel_type, ImageDimension>;\n\tusing feature_filter_type = itk::HessianToObjectnessMeasureImageFilter<hessian_image_type, TImage>;\n\tusing multiscale_hessian_filter_type = itk::MultiScaleHessianBasedMeasureImageFilter<TInput, hessian_image_type, TImage>;\n\n\tdouble sigm_min = m_SigmaLow->text().toDouble();\n\tdouble sigm_max = m_SigmaHi->text().toDouble();\n\tint num_levels = m_NumberSigmaLevels->text().toInt();\n\n\tauto objectness_filter = feature_filter_type::New();\n\tobjectness_filter->SetBrightObject(false);\n\tobjectness_filter->SetObjectDimension(1);\n\tobjectness_filter->SetScaleObjectnessMeasure(true);\n\tobjectness_filter->SetAlpha(0.5);\n\tobjectness_filter->SetBeta(0.5);\n\tobjectness_filter->SetGamma(5.0);\n\n\tauto multi_scale_enhancement_filter = multiscale_hessian_filter_type::New();\n\tmulti_scale_enhancement_filter->SetInput(source);\n\tmulti_scale_enhancement_filter->SetHessianToMeasureFilter(objectness_filter);\n\tmulti_scale_enhancement_filter->SetSigmaStepMethodToEquispaced();\n\tmulti_scale_enhancement_filter->SetSigmaMinimum(std::min(sigm_min, sigm_max));\n\tmulti_scale_enhancement_filter->SetSigmaMaximum(std::max(sigm_min, sigm_max));\n\tmulti_scale_enhancement_filter->SetNumberOfSigmaSteps(std::min(1, num_levels));\n\tmulti_scale_enhancement_filter->Update();\n\treturn multi_scale_enhancement_filter->GetOutput();\n}\n\ntemplate<class TInput, class TImage>\ntypename TImage::Pointer AutoTubeWidget::ComputeFeatureImage2d(TInput* source) const\n{\n\titkStaticConstMacro(ImageDimension, size_t, TInput::ImageDimension);\n\tusing input_type = TInput;\n\tusing output_type = TImage;\n\tusing image_type = itk::Image<float, 2>;\n\n\tusing hessian_filter_type = itk::HessianRecursiveGaussianImageFilter<image_type>;\n\tusing hessian_pixel_type = itk::SymmetricSecondRankTensor<double, 2>;\n\tusing hessian_image_type = itk::Image<hessian_pixel_type, 2>;\n\n\tusing feature_filter_type = itk::HessianToObjectnessMeasureImageFilter<hessian_image_type, image_type>;\n\tusing multiscale_hessian_filter_type = itk::MultiScaleHessianBasedMeasureImageFilter<image_type, hessian_image_type, image_type>;\n\tusing slice_by_slice_filter_type = itk::SliceBySliceImageFilter<input_type, output_type, multiscale_hessian_filter_type>;\n\n\tdouble sigm_min = m_SigmaLow->text().toDouble();\n\tdouble sigm_max = m_SigmaHi->text().toDouble();\n\tint num_levels = m_NumberSigmaLevels->text().toInt();\n\n\tauto objectness_filter = feature_filter_type::New();\n\tobjectness_filter->SetBrightObject(false);\n\tobjectness_filter->SetObjectDimension(ImageDimension == 2 ? 1 : 0); // for 2D analysis we are looking for lines in a single slice\n\tobjectness_filter->SetScaleObjectnessMeasure(true);\n\tobjectness_filter->SetAlpha(0.5);\n\tobjectness_filter->SetBeta(0.5);\n\tobjectness_filter->SetGamma(5.0);\n\n\tauto multi_scale_enhancement_filter = multiscale_hessian_filter_type::New();\n\tmulti_scale_enhancement_filter->SetHessianToMeasureFilter(objectness_filter);\n\tmulti_scale_enhancement_filter->SetSigmaStepMethodToEquispaced();\n\tmulti_scale_enhancement_filter->SetSigmaMinimum(std::min(sigm_min, sigm_max));\n\tmulti_scale_enhancement_filter->SetSigmaMaximum(std::max(sigm_min, sigm_max));\n\tmulti_scale_enhancement_filter->SetNumberOfSigmaSteps(std::min(1, num_levels));\n\n\tauto slice_filter = slice_by_slice_filter_type::New();\n\tslice_filter->SetInput(source);\n\tslice_filter->SetFilter(multi_scale_enhancement_filter);\n\tslice_filter->Update();\n\n\treturn slice_filter->GetOutput();\n}\n\ntemplate<class TInput, class TTissue, class TTarget>\nvoid AutoTubeWidget::DoWorkNd(TInput* source, TTissue* tissues, TTarget* target)\n{\n\titkStaticConstMacro(ImageDimension, size_t, TInput::ImageDimension);\n\tusing input_type = TInput;\n\tusing real_type = itk::Image<float, ImageDimension>;\n\tusing mask_type = itk::Image<unsigned char, ImageDimension>;\n\tusing labelfield_type = itk::Image<unsigned short, ImageDimension>;\n\n\tusing threshold_filter_type = itk::BinaryThresholdImageFilter<real_type, mask_type>;\n\tusing nonmax_filter_type = itk::NonMaxSuppressionImageFilter<real_type>;\n\tusing thinnning_filter_type = BinaryThinningImageFilter<mask_type, mask_type, ImageDimension>;\n\n\ttypename real_type::Pointer feature_image;\n\tstd::vector<double> feature_params;\n\tfeature_params.push_back(m_SigmaLow->text().toDouble());\n\tfeature_params.push_back(m_SigmaHi->text().toDouble());\n\tfeature_params.push_back(m_NumberSigmaLevels->text().toInt());\n\tfeature_params.push_back(m_Metric2d->isChecked());\n\tif (!m_CachedFeatureImage.Get(feature_image, feature_params))\n\t{\n\t\tfeature_image = m_Metric2d->isChecked()\n\t\t\t\t\t\t\t\t\t\t\t\t? ComputeFeatureImage2d<input_type, real_type>(source)\n\t\t\t\t\t\t\t\t\t\t\t\t: ComputeFeatureImage<input_type, real_type>(source);\n\t\tm_CachedFeatureImage.Store(feature_image, feature_params);\n\t\tm_CachedSkeleton.img = nullptr;\n\t}\n\n\t// initialize threshold to reasonable value\n\tbool ok = false;\n\tfloat lower = m_Threshold->text().toFloat(&ok);\n\tif (!ok)\n\t{\n\t\tauto calculator = itk::MinimumMaximumImageCalculator<real_type>::New();\n\t\tcalculator->SetImage(feature_image);\n\t\tcalculator->Compute();\n\n\t\tauto min_gm = calculator->GetMinimum();\n\t\tauto max_gm = calculator->GetMaximum();\n\n\t\tlower = min_gm + 0.8 * (max_gm - min_gm); // stupid way to guess threshold\n\t\tm_Threshold->setText(QString::number(lower));\n\t}\n\n\t// extract IDs if any were set\n\tstd::vector<int> object_ids;\n\tif (!m_SelectedObjects->text().isEmpty())\n\t{\n\t\tstd::vector<std::string> tokens;\n\t\tstd::string selected_objects_text = m_SelectedObjects->text().toStdString();\n\t\tboost::algorithm::split(tokens, selected_objects_text, boost::algorithm::is_any_of(\",\"));\n\t\tstd::transform(tokens.begin(), tokens.end(), std::back_inserter(object_ids), [](std::string s) {\n\t\t\tboost::algorithm::trim(s);\n\t\t\treturn stoi(s);\n\t\t});\n\t}\n\n\t// mask feature image before skeletonization\n\tif (!object_ids.empty())\n\t{\n\t\tusing map_functor_type = iseg::Functor::MapLabels<unsigned short, unsigned char>;\n\t\tmap_functor_type map;\n\t\tmap.m_Map.assign(m_Handler3D->TissueNames().size() + 1, 0);\n\t\tfor (size_t i = 0; i < object_ids.size(); i++)\n\t\t{\n\t\t\tmap.m_Map.at(object_ids[i]) = 1;\n\t\t}\n\n\t\tauto map_filter = itk::UnaryFunctorImageFilter<TTissue, mask_type, map_functor_type>::New();\n\t\tmap_filter->SetFunctor(map);\n\t\tmap_filter->SetInput(tissues);\n\n\t\tauto masker = itk::MaskImageFilter<real_type, mask_type>::New();\n\t\tmasker->SetInput(feature_image);\n\t\tmasker->SetMaskImage(map_filter->GetOutput());\n\t\tSAFE_UPDATE(masker, return );\n\t\tfeature_image = masker->GetOutput();\n\t}\n\n\ttypename mask_type::Pointer skeleton;\n\tstd::vector<double> skeleton_params(object_ids.begin(), object_ids.end());\n\tskeleton_params.push_back(lower);\n\tskeleton_params.push_back(m_NonMaxSuppression->isChecked());\n\tskeleton_params.push_back(m_Skeletonize->isChecked());\n\tskeleton_params.push_back(m_MinObjectSize->text().toInt());\n\tif (!m_CachedSkeleton.Get(skeleton, skeleton_params))\n\t{\n\t\t// disconnect bright tubes via non-maxi suppression\n\t\tif (m_NonMaxSuppression->isChecked())\n\t\t{\n\t\t\tauto masking = itk::ThresholdImageFilter<real_type>::New();\n\t\t\tmasking->SetInput(feature_image);\n\t\t\tmasking->ThresholdBelow(lower);\n\t\t\tmasking->SetOutsideValue(std::min(lower, 0.f));\n\n\t\t\t// do thinning to get brightest pixels (\"one\" pixel wide)\n\t\t\tauto nonmax_filter = nonmax_filter_type::New();\n\t\t\tnonmax_filter->SetInput(masking->GetOutput());\n\n\t\t\tauto threshold = threshold_filter_type::New();\n\t\t\tthreshold->SetInput(nonmax_filter->GetOutput());\n\t\t\tthreshold->SetLowerThreshold(std::nextafter(std::min(lower, 0.f), 1.f));\n\t\t\tSAFE_UPDATE(threshold, return );\n\t\t\tskeleton = threshold->GetOutput();\n\t\t}\n\t\telse\n\t\t{\n\t\t\tauto threshold = threshold_filter_type::New();\n\t\t\tthreshold->SetInput(feature_image);\n\t\t\tthreshold->SetLowerThreshold(lower);\n\t\t\tSAFE_UPDATE(threshold, return );\n\t\t\tskeleton = threshold->GetOutput();\n\t\t}\n\n\t\tif (m_Skeletonize->isChecked())\n\t\t{\n\t\t\t// get centerline: either thresholding or non-max suppression must be done before this\n\t\t\tauto thinning = thinnning_filter_type::New();\n\t\t\tthinning->SetInput(skeleton);\n\n\t\t\tauto rescale = itk::RescaleIntensityImageFilter<mask_type>::New();\n\t\t\trescale->SetInput(thinning->GetOutput());\n\t\t\trescale->SetOutputMinimum(0);\n\t\t\trescale->SetOutputMaximum(255);\n\t\t\trescale->InPlaceOn();\n\n\t\t\tSAFE_UPDATE(rescale, return );\n\t\t\tskeleton = rescale->GetOutput();\n\t\t}\n\t\tm_CachedSkeleton.Store(skeleton, skeleton_params);\n\t}\n\n\ttypename mask_type::Pointer output;\n\tif (skeleton && m_MinObjectSize->text().toInt() > 1)\n\t{\n\t\tauto connectivity = itk::ConnectedComponentImageFilter<mask_type, labelfield_type>::New();\n\t\tconnectivity->SetInput(skeleton);\n\t\tconnectivity->FullyConnectedOn();\n\n\t\tauto relabel = itk::RelabelComponentImageFilter<labelfield_type, labelfield_type>::New();\n\t\trelabel->SetInput(connectivity->GetOutput());\n\t\trelabel->SetMinimumObjectSize(m_MinObjectSize->text().toInt());\n\n\t\tauto threshold = itk::BinaryThresholdImageFilter<labelfield_type, mask_type>::New();\n\t\tthreshold->SetInput(relabel->GetOutput());\n\t\tthreshold->SetLowerThreshold(1);\n\t\tSAFE_UPDATE(threshold, return );\n\t\toutput = threshold->GetOutput();\n\t}\n\n\tiseg::DataSelection data_selection;\n\tdata_selection.allSlices = true; // all_slices->isChecked();\n\tdata_selection.sliceNr = m_Handler3D->ActiveSlice();\n\tdata_selection.work = true;\n\temit BeginDatachange(data_selection, this);\n\n\tif (output && iseg::Paste<mask_type, input_type>(output, target))\n\t{\n\t\t// good, else maybe output is not defined\n\t}\n\telse if (!iseg::Paste<mask_type, input_type>(skeleton, target))\n\t{\n\t\tstd::cerr << \"Error: could not set output because image regions don't match.\\n\";\n\t}\n\n\temit EndDatachange(this);\n}\n", "meta": {"hexsha": "1e52f702afc160756b2982b8299ea734bb76e8ca", "size": 16325, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Plugins/TracingTubularStructures/AutoTubeWidget.cpp", "max_stars_repo_name": "ITISFoundation/osparc-iseg", "max_stars_repo_head_hexsha": "6f38924120b3a3e7a0292914d2c17f24c735309b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 32.0, "max_stars_repo_stars_event_min_datetime": "2018-03-26T12:39:19.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T20:54:22.000Z", "max_issues_repo_path": "Plugins/TracingTubularStructures/AutoTubeWidget.cpp", "max_issues_repo_name": "dyollb/osparc-iseg", "max_issues_repo_head_hexsha": "6f38924120b3a3e7a0292914d2c17f24c735309b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 10.0, "max_issues_repo_issues_event_min_datetime": "2018-04-03T15:54:22.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-01T14:32:36.000Z", "max_forks_repo_path": "Plugins/TracingTubularStructures/AutoTubeWidget.cpp", "max_forks_repo_name": "dyollb/osparc-iseg", "max_forks_repo_head_hexsha": "6f38924120b3a3e7a0292914d2c17f24c735309b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 11.0, "max_forks_repo_forks_event_min_datetime": "2018-03-08T13:11:28.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-01T10:43:39.000Z", "avg_line_length": 36.9343891403, "max_line_length": 130, "alphanum_fraction": 0.7734150077, "num_tokens": 4119, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6688802603710086, "lm_q2_score": 0.5195213219520929, "lm_q1q2_score": 0.3474975570956065}}
{"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 ILUPRECOND_HH\n#define ILUPRECOND_HH\n\n#include \"globheads.h\"\n#include \"protospp.h\" \n#include \"ios.h\"\nextern \"C\" void set_arms_pars(io_t* io,  int Dscale, int *ipar, double *tolcoef, int *lfil);\n\n#include <boost/timer/timer.hpp>\n#include \"dune/istl/preconditioners.hh\"\n#include \"linalg/triplet.hh\"\n\n//---------------------------------------------------------------------\n//---------------------------------------------------------------------\n\nnamespace Kaskade\n{\n/**\n * \\ingroup linalg\n * \n * PrecondType::ILUT Preconditioner from Saads ITSOL library\n */\ntemplate <class Op>\nclass ILUTPreconditioner: public Dune::Preconditioner<typename Op::Range, typename Op::Range>\n{\n  typedef typename Op::Range Range;\n  typedef Range               Domain;\n  typedef typename Op::field_type field_type;\n\npublic:\n  static int const category = Dune::SolverCategory::sequential;\n\n  ILUTPreconditioner(Op& op, int lfil=240, double tol=1.0e-2, int verbosity=2) {\n    boost::timer::cpu_timer iluTimer;\n    std::cout << \"ilut constructor: \";\n    MatrixAsTriplet<field_type> A = op.template get<MatrixAsTriplet<field_type> >();\n    int n = A.nrows(), nnz = A.nnz(), ierr;\n    FILE *flog = stdout;\n\n    csmat = (csptr)Malloc( sizeof(SparMat), \"main\" );\n    ierr = COOcs(n, nnz,  &A.data[0], &A.cidx[0],  &A.ridx[0], csmat);\n    if( ierr != 0 )\n      {\n        printf(\" *** ILU error - COOcs code %d csmat=%p\\n\", ierr, csmat);\n        throw ierr;\n      }\n\n    lu = (iluptr)Malloc(sizeof(ILUSpar), \"main\");\n    ierr = ilut(csmat, lu, lfil, tol, flog);\n    if( ierr != 0 )\n      {\n        printf(\" *** PrecondType::ILUT error - ilut code %d lu=%p\\n\", ierr, lu);\n        throw ierr;\n      }\n    \n    xx   = (double *)Malloc(n*sizeof(double), \"main\");\n    yy   = (double *)Malloc(n*sizeof(double), \"main\");\n    \n    if ( verbosity>=2 )\n    {\n\tstd::cout << \"PrecondType::ILUT: n=\" << n << \", nnz=\" << nnz << \" dropTol=\" << tol << \", fillfac=\" \n\t          << 1.0*nnz_ilu(lu)/(nnz+1.0) << \", lfil=\" << lfil << \", time=\" << (double)(iluTimer.elapsed().user)/1e9 << \"s\\n\";\n\t}\n  }\n  ~ILUTPreconditioner()\n    {\n      cleanILU(lu);\n      cleanCS(csmat);\n      free(xx);\n      free(yy);\n    }\n\n  virtual void pre (Domain&, Range&) {}\n  virtual void post (Domain&) {}\n  \n  virtual void apply (Domain& x, Range const& y) {\n    y.write(yy);\n    lusolC(yy, xx, lu);\n    x.read(xx);\n  }\n\nprivate:\n  csptr csmat;\n  iluptr lu;\n  double *xx, *yy;\n};\n\n//---------------------------------------------------------------------\n\n/**\n * \\ingroup linalg\n * \n * PrecondType::ILUT Preconditioner from Saads ITSOL library\n */\ntemplate <class Op>\nclass ILUKPreconditioner: public Dune::Preconditioner<typename Op::Range, typename Op::Range>\n{\n  typedef typename Op::Range Range;\n  typedef Range               Domain;\n  typedef typename Op::field_type field_type;\n\npublic:\n  static int const category = Dune::SolverCategory::sequential;\n\n  ILUKPreconditioner(Op& op, int fill_lev=3, int verbosity=2) {\n    boost::timer::cpu_timer iluTimer;\n    MatrixAsTriplet<field_type> A = op.template get<MatrixAsTriplet<field_type> >();\n    int n = A.nrows(), nnz = A.nnz(), ierr;\n    FILE *flog = stdout;\n\n    csmat = (csptr)Malloc( sizeof(SparMat), \"main\" );\n    ierr = COOcs(n, nnz,  &A.data[0], &A.cidx[0],  &A.ridx[0], csmat);\n    if( ierr != 0 )\n      {\n        printf(\" *** ILU error - COOcs code %d csmat=%p\\n\", ierr, csmat);\n        throw ierr;\n      }\n\n    lu = (iluptr)Malloc(sizeof(ILUSpar), \"main\");\n    ierr = ilukC(fill_lev, csmat, lu, flog);\n    if( ierr != 0 )\n      {\n        printf(\" *** PrecondType::ILUK error - ilut code %d lu=%p\\n\", ierr, lu);\n        throw ierr;\n      }\n\n    xx   = (double *)Malloc(n*sizeof(double), \"main\");\n    yy   = (double *)Malloc(n*sizeof(double), \"main\");\n\n    if ( verbosity>=2 )\n    {\n\tstd::cout << \"PrecondType::ILUK: n=\" << n << \", nnz=\" << nnz << \", fillfac=\"\n\t          << 1.0*nnz_ilu(lu)/(nnz+1.0) << \", fill_lev=\" \n\t          << fill_lev << \", time=\" << (double)(iluTimer.elapsed().user)/1e9 << \"s\\n\";\n    }\n  }\n  ~ILUKPreconditioner()\n    {\n      cleanILU(lu);\n      cleanCS(csmat);\n      free(xx);\n      free(yy);\n    }\n\n  virtual void pre (Domain&, Range&) {}\n  virtual void post (Domain&) {}\n  \n  virtual void apply (Domain& x, Range const& y) {\n    y.write(yy);\n    lusolC(yy, xx, lu);\n    x.read(xx);\n  }\n\nprivate:\n  csptr csmat;\n  iluptr lu;\n  double *xx, *yy;\n};\n//---------------------------------------------------------------------\n\n/**\n * \\ingroup linalg\n * \n * PrecondType::ILUT Preconidoner from Saads ITSOL library\n */\ntemplate <class Op>\nclass ARMSPreconditioner: public Dune::Preconditioner<typename Op::Range, typename Op::Range>\n{\n  typedef typename Op::Range Range;\n  typedef Range               Domain;\n  typedef typename Op::field_type field_type;\n\npublic:\n  static int const category = Dune::SolverCategory::sequential;\n\n  ARMSPreconditioner(Op& op, int lfil=4, double tol=1.0e-2, int lev_reord=1, double tolind = 0.2, int verbosity=2) {\n    boost::timer::cpu_timer iluTimer;\n    MatrixAsTriplet<field_type> A = op.template get<MatrixAsTriplet<field_type> >();\n    int n = A.nrows(), nnz = A.nnz(), ierr, diagscal = 1;\n\n    int lfil_arr[7]; \n    double droptol[7], dropcoef[7];\n    int ipar[18];\n    io_t io;\n    FILE *flog = stdout;\n\n    csmat = (csptr)Malloc( sizeof(SparMat), \"main\" );\n    ierr = COOcs(n, nnz,  &A.data[0], &A.cidx[0],  &A.ridx[0], csmat);\n    if( ierr != 0 )\n      {\n        printf(\" *** PrecondType::ARMS error - COOcs code %d csmat=%p\\n\", ierr, csmat);\n        throw ierr;\n      }\n\n    memset(&io, 0, sizeof(io) );\n    io.perm_type = 0;\n    io.Bsize = 400;\n    set_arms_pars(&io, diagscal, ipar, dropcoef, lfil_arr);\n    for (int j=0; j<7; j++)\n      {\n         lfil_arr[j] = lfil*((int) nnz/n); \n         droptol[j] =  tol*dropcoef[j];\n      }\n    ipar[1] = lev_reord; \n    ArmsSt = (arms) Malloc(sizeof(armsMat),\"main:ArmsSt\");\n    setup_arms(ArmsSt);\n\n    ierr = arms2(csmat, ipar, droptol, lfil_arr, tolind, ArmsSt, flog);\n    if( ierr != 0 )\n      {\n        printf(\" *** PrecondType::ARMS error - arms2 code %d ArmsSt=%p\\n\", ierr, ArmsSt);\n        throw ierr;\n      }\n\n    yy   = (double *)Malloc(n*sizeof(double), \"main\");\n\n    if ( verbosity>=2 )\n    {\n\tstd::cout << \"PrecondType::ARMS: n=\" << n << \", nnz=\" << nnz << \", dropTol=\" << tol\n\t          << \", lev_reord=\" << lev_reord\n\t          << \", lfil=\" << lfil << \", time=\" << (double)(iluTimer.elapsed().user)/1e9 << \"s\\n\";\n    }\n  }\n  ~ARMSPreconditioner()\n    {\n      cleanARMS(ArmsSt); \n      cleanCS(csmat);\n      free(yy);\n    }\n\n  virtual void pre (Domain&, Range&) {}\n  virtual void post (Domain&) {}\n  \n  virtual void apply (Domain& x, Range const& y) {\n    y.write(yy);\n    armsol2(yy, ArmsSt);\n    x.read(yy);\n  }\n\nprivate:\n  csptr csmat;\n  arms ArmsSt;\n  double *yy;\n};\n\n}  // namespace Kaskade\n#endif\n", "meta": {"hexsha": "e47e8fb5d7cc40daeab6d823b9c54611a8089787", "size": 7698, "ext": "hh", "lang": "C++", "max_stars_repo_path": "Kaskade/linalg/iluprecond.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/iluprecond.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/iluprecond.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": 29.6076923077, "max_line_length": 124, "alphanum_fraction": 0.5218238504, "num_tokens": 2314, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6688802603710086, "lm_q2_score": 0.5195213219520929, "lm_q1q2_score": 0.3474975570956065}}
{"text": "\n// ************************  Prize-collecting Steiner Forest (PCSF) *********************//\n// This is a C++ implementation of our heuristic algorithm for the PCSF (Akhmedov et al 2017).\n// The heuristic is developed for functional analyses of large biological networks in a reasonable time.\n\n\n// Loading the required libraries\n#include <Rcpp.h>\n#include <boost/config.hpp>\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/breadth_first_search.hpp>\n#include <boost/graph/visitors.hpp>\n#include <boost/graph/graph_utility.hpp>\n#include <boost/random.hpp>\n#include <boost/random/linear_congruential.hpp>\n#include <boost/property_map/property_map.hpp>\n#include <boost/graph/erdos_renyi_generator.hpp>\n#include <boost/program_options.hpp>\n#include <boost/format.hpp>\n#include <boost/lexical_cast.hpp>\n#include <boost/graph/connected_components.hpp>\n#include <boost/graph/dijkstra_shortest_paths.hpp>\n#include <boost/graph/prim_minimum_spanning_tree.hpp>\n#include <time.h>\n#include <stdio.h>\n#include <boost/graph/graphviz.hpp>\n#include <fstream>\n#include <vector>\n#include <utility>\n#include <string>\n#include <math.h>\n#include <iomanip>\n#include <boost/limits.hpp>\n#include <queue>\n\nusing namespace boost;\nusing namespace Rcpp;\nusing namespace std;\n\n\n// Node class\nclass Node\n{  public:\n  vector <int> children;\n  int father;\n  int size;\n  double price;\n  Node(){};\n  Node(const Node & other){\n    father=other.father;\n    children= other.children;}\n\n  Node & operator= (const Node & other){\n    father=other.father;\n    children= other.children;\n    return *this;\n  }\n\n};\n\n// Properties of Vertices in the network\nstruct VertexProperties  {\n  VertexProperties() :c(0) {}\n  VertexProperties(string const & name) : name(name),c(0){}\n  string name;\n  double c;\n};\n\n// Properties of the graph that is used within the BOOST\ntypedef adjacency_list<vecS, vecS, undirectedS, VertexProperties, property < edge_weight_t, double > > GraphBase;\ntypedef graph_traits<GraphBase>::vertex_iterator vertex_iterator;\ntypedef graph_traits<GraphBase>::out_edge_iterator edge_iterator;\ntypedef graph_traits<GraphBase>::edge_iterator graph_edge_iterator;\ntypedef graph_traits<GraphBase>::edge_descriptor Edge;\ntypedef graph_traits<GraphBase>::vertex_descriptor Vertex;\n\n\nGraphBase g, g_adjusted; GraphBase G; GraphBase G_pruned;\nproperty_map<GraphBase, edge_weight_t>::type weight_g;\nproperty_map<GraphBase, edge_weight_t>::type weight_g_adjusted;\nproperty_map<GraphBase, edge_weight_t>::type weight_G;\nproperty_map<GraphBase, edge_weight_t>::type weight_G_pruned;\n\nint Root = -1;\nstatic map <string, int> g_map;\nstatic map <string, int> G_map;\nstatic map <string, int> G_pruned_map;\n\nvoid clear_variables(){\n  g.clear();\n  g_adjusted.clear();\n  G.clear();\n  G_pruned.clear();\n  g_map.clear();\n  G_map.clear();\n  G_pruned_map.clear();\n}\n\n// Map\nint idx_g(String const & id)\n{\n  map<string, int>::iterator mit = g_map.find(id);\n  if (mit == g_map.end())\n    return g_map[id] = add_vertex(VertexProperties(id), g);\n  return mit->second;\n}\nint idx_G(string const & id)\n{\n  map<string, int>::iterator mit = G_map.find(id);\n  if (mit == G_map.end())\n    return G_map[id] = add_vertex(VertexProperties(id), G);\n  return mit->second;\n}\nint idx_G_pruned(string const & id)\n{\n  map<string, int>::iterator mit = G_pruned_map.find(id);\n  if (mit == G_pruned_map.end())\n    return G_pruned_map[id] = add_vertex(VertexProperties(id), G_pruned);\n  return mit->second;\n}\n\n\n// Reading the input network\nvoid read_input_graph(CharacterVector from, CharacterVector to,  NumericVector cost, CharacterVector prize, NumericVector prize_v)\n{\n  for(int i=0; i < from.size(); i++){\n    add_edge(vertex(idx_g(from[i]), g), vertex(idx_g(to[i]), g), cost[i], g);\n  }\n  for(int i=0; i<prize.size(); i++){\n    g[idx_g(prize[i])].c = prize_v[i];\n  }\n\n  // cerr << num_edges(g) << \" edges, \" << num_vertices(g) << \" vertices\" << endl;\n\n  g_adjusted = g;\n  weight_g_adjusted = get(edge_weight, g_adjusted);\n  graph_edge_iterator ei, ei_end; double penalty; Vertex sour, tar;\n  for(tie(ei, ei_end) = edges(g_adjusted); ei != ei_end; ++ei){\n    sour = source(*ei,g_adjusted); tar = target(*ei,g_adjusted); penalty = 0;\n    if(g_adjusted[sour].c < 0 && g_adjusted[tar].c < 0){\n      penalty = g_adjusted[sour].c + g_adjusted[tar].c;\n    } else if( g_adjusted[sour].c < 0 ){\n      penalty = g_adjusted[sour].c;\n    } else if( g_adjusted[tar].c < 0 ){\n      penalty = g_adjusted[tar].c;\n    }\n    weight_g_adjusted[*ei] = weight_g_adjusted[*ei] + abs(penalty);\n  }\n}\n\n\n// A function to dynamically remove the leaf node if its prize smaller than connection cost.\n// It is used called within the process_leafs() function.\nvoid clear(vector <Node> & predecessor, int & current_node){\n  int node=current_node;\n  for(unsigned int j=0; j<predecessor[node].children.size(); j++){\n    clear(predecessor, predecessor[node].children[j]);\n  }\n  predecessor[node].father=-1;\n}\n\n// A function to dynamically remove the leaf node if its prize smaller than connection cost.\nvoid process_leafs(vector <Node> & predecessor, int & current_node, Edge &e, bool &found){\n  for(unsigned int i=0; i<predecessor[current_node].children.size(); i++){\n    process_leafs(predecessor, predecessor[current_node].children[i], e, found);\n  }\n  int node = current_node;\n  if(node != predecessor[node].father){\n    boost::tuples::tie(e,found) = edge( vertex(predecessor[node].father, G_pruned),vertex(node, G_pruned) , G_pruned);\n    if(predecessor[node].price - weight_G_pruned[e] <= 0) {\n      clear(predecessor, node);\n    }\n  }\n\n}\n\n// A function to dynamically sum up the prizes of vertices.\nvoid price_collect(vector <Node> & predecessor, int & current_node, Edge &e, bool &found){\n  for(unsigned int i=0; i<predecessor[current_node].children.size(); i++){\n    price_collect(predecessor, predecessor[current_node].children[i], e, found);\n  }\n  int node = current_node;\n  if(node != predecessor[node].father){\n    boost::tuples::tie(e,found) = edge(vertex(predecessor[node].father, G_pruned),vertex(node, G_pruned) , G_pruned);\n    if(predecessor[node].price - weight_G_pruned[e] > 0)\n      predecessor[predecessor[node].father].price = predecessor[predecessor[node].father].price + predecessor[node].price - weight_G_pruned[e];\n  }\n}\n\n\n\n\n// After reading the input network information from the input file, the algorithm constructs a\nvector< Vertex > constructG(vector<int> & terminals, int &Root){\n\n  // Distance: all-pairs-shortest-path distance matrix\n  // perPath: List of arcs in all-pairs-shortest-path distance matrix\n  vector <vector <vector<int> > > perPath;\n  vector <vector<double> > Distance;\n  perPath.resize (terminals.size());\n  Distance.resize (terminals.size());\n  for (unsigned int i = 0; i < terminals.size(); ++i) {\n    perPath [i].resize(terminals.size());\n    Distance [i].resize(terminals.size());\n  }\n\n  // Computing all-pairs-shortest-path distance matrix\n  Vertex from; int current, pred, outer = 0, inner;\n  std::vector<Vertex> p = vector<Vertex> (num_vertices(g));\n  std::vector<double> d = vector<double> (num_vertices(g));\n\n  for (std::vector<int>::iterator first=terminals.begin(); first!=terminals.end(); ++first){\n\n    from = vertex(*first, g_adjusted);\n    dijkstra_shortest_paths(g_adjusted, from,\n                            predecessor_map(boost::make_iterator_property_map(p.begin(), get(boost::vertex_index, g_adjusted))).\n                              distance_map(boost::make_iterator_property_map(d.begin(), get(boost::vertex_index, g_adjusted))));\n\n    inner = outer + 1;\n    for (std::vector<int>::iterator second = first+1; second!=terminals.end(); ++second) {\n      current=*second; pred=p[current];\n      Distance[outer][inner] = d[current];\n      Distance[inner][outer] = d[current];\n      while(pred!=current){perPath[outer][inner].push_back(current); current=pred; pred=p[current]; } perPath[outer][inner].push_back(current);\n      inner++;\n    }\n    outer++;\n  }\n\n\n\n\n  // Heuristic Clustering, given large input network, the algorithm clusters input network into\n  // smaller clusters, and solves the MST afterwards\n  set<int> V;\n  set<int> D;\n  unsigned int root_index = -1;\n  vector<int> node_labels;\n  node_labels.resize(terminals.size());\n  for(unsigned int i=0; i< node_labels.size(); i++){\n    node_labels[i] = 0;}\n  for(unsigned int i=0; i<terminals.size(); i++){\n    if(terminals[i] == Root){\n      root_index = i;}\n    else{\n      V.insert(i);}\n  }\n  node_labels[root_index] = INT_MAX;\n  int clusterID=0; int targ;\n\n  while(!V.empty()){\n    clusterID++;  current = *V.begin();\n    node_labels[current] =clusterID;\n    V.erase(current);\n\n    D.clear();\n    for (unsigned int i=0; i < terminals.size(); i++) {\n      targ = i;\n      if(node_labels[targ] == 0 && current != targ && i != root_index){\n        if(g[terminals[current]].c >= Distance[current][targ] && g[terminals[targ]].c >= Distance[current][targ]){\n          if(g[terminals[targ]].c > 0){\n            D.insert(targ); V.erase(targ);\n          }\n          node_labels[targ]=clusterID;\n        }\n      }\n    }\n\n    while(!D.empty()){\n      current = *D.begin();  D.erase(current);\n      for (unsigned int i=0; i < terminals.size(); i++) {\n        targ = i;\n        if(node_labels[targ] == 0 && current != targ && i != root_index){\n          if(g[terminals[current]].c >= Distance[current][targ] && g[terminals[targ]].c >= Distance[current][targ]){\n            if(g[terminals[targ]].c > 0){ D.insert(targ); V.erase(targ);}\n            node_labels[targ]=clusterID;\n          }\n        }\n      }\n    }\n\n  }\n\n  // Identfying the vertex membership with respect to clusters\n  vector<vector <int> > clusters(clusterID+1);\n  for(unsigned int i=0; i< node_labels.size(); i++){\n    for(int j=0; j<=clusterID; j++){\n      if(node_labels[i] == j){\n        clusters[j].push_back(i);\n      }\n    }\n  }\n\n  std::vector<int>::iterator it, itt; int num_clusters=0;\n  for(unsigned int i=1; i<clusters.size(); i++){\n    if(clusters[i].size() > 1) num_clusters++;\n  }\n\n  if(num_clusters == 0){\n    //cout<<\"There is no tree in construct G ()\"<<endl;\n    //return 0;\n  }\n\n\n  // Regrouping the singletone and dobletone clusters after clustering\n  unsigned int threshold_num = 2; int min_index; double min_distance;\n  for(unsigned int i=1; i<clusters.size(); i++){\n    if( clusters[i].size() <= threshold_num){\n      for (it=clusters[i].begin(); it!=clusters[i].end(); ++it){\n        min_index = -1; min_distance = DBL_MAX;\n        for(unsigned int j=1; j<clusters.size(); j++){\n          if( clusters[j].size() > threshold_num){\n            for (itt=clusters[j].begin(); itt!=clusters[j].end(); ++itt){\n              if(min_distance > Distance[*it][*itt] -g[terminals[*it]].c - g[terminals[*itt]].c ){\n                min_distance = Distance[*it][*itt] -g[terminals[*it]].c - g[terminals[*itt]].c; min_index = j;\n              }\n            }\n          }\n        }\n\n\n        if (min_index != -1){\n          clusters[min_index].push_back(*it);\n          *it = -1;\n        }\n      }\n    }\n\n  }\n\n\n\n  // Construct an artificial graph G, which is composed of all clusters determined\n  // from Heuristic Clustering phase\n\n  string str; unsigned int index1=-1, index2=-1;\n\n  for (unsigned int l = 0; l<terminals.size(); l++){\n    str=to_string(l);\n    index1=idx_G(str);\n    G[index1].c = g[terminals[l]].c;\n    G[index1].name = g[terminals[l]].name;\n  }\n\n\n  for (unsigned int l = 0; l<terminals.size(); l++){\n    if(l != root_index){\n      str=to_string(l);\n      index1=idx_G(str);\n      add_edge(root_index, index1, Distance[root_index][index1], G);\n    }\n  }\n\n  for(unsigned int i = 1; i < clusters.size(); i++){\n    for (it=clusters[i].begin(); it!=clusters[i].end(); ++it){\n      if(*it != -1){\n        str=to_string(*it); index1=idx_G(str);\n        for (itt=it+1; itt!=clusters[i].end(); ++itt){\n          if(*itt != -1){\n            str=to_string(*itt); index2=idx_G(str);\n            add_edge(index1, index2, Distance[*it][*itt], G);\n          }\n        }\n      }\n    }\n  }\n\n\n\n  weight_G = get(edge_weight, G);\n  vector < Vertex > spanning_tree_G(num_vertices(G));\n  prim_minimum_spanning_tree(G, & spanning_tree_G[0]);\n\n\n  Edge beg; Vertex sour, tar; double cost;\n  Edge e; bool found;\n\n  weight_g = get(edge_weight, g);\n\n  vector<int> path; index1=0; index2=0;\n  edge_iterator out_i, out_end; int add=0;\n\n  // Solving the Minimum Spanning Tree on G\n  for(unsigned int i = 0; i < spanning_tree_G.size(); ++i ){\n\n    if(spanning_tree_G[i]!=i ){\n\n      if(i> spanning_tree_G[i]) path=perPath[spanning_tree_G[i]][i];\n      else path=perPath[i][spanning_tree_G[i]];\n\n      for(unsigned int j=0; j<path.size()-1; j++){\n\n        sour=vertex(path[j], g); tar= vertex(path[j+1], g);\n        boost::tuples::tie(beg, found) = edge(sour, tar,g);\n        cost=get(weight_g, beg);\n\n        index1=idx_G_pruned(to_string(path[j])); index2=idx_G_pruned(to_string(path[j+1]));\n        add=0;\n        for (boost::tuples::tie(out_i, out_end) = out_edges(vertex(index1,G_pruned), G_pruned); out_i != out_end; ++out_i) {\n          if(target(*out_i, G_pruned)==index2) add++;\n        }\n        if(!add) add_edge(index1, index2, cost, G_pruned);\n      }\n  }\n  }\n\n  weight_G_pruned = get(edge_weight, G_pruned);\n\n  vector< Vertex >spanning_tree_G_pruned(num_vertices(G_pruned));\n  prim_minimum_spanning_tree(G_pruned, &spanning_tree_G_pruned[0]);\n\n\n  double total1=0;\n  for(unsigned int i = 0; i < spanning_tree_G_pruned.size(); ++i ){\n    if(spanning_tree_G_pruned[i] != i){\n      sour= vertex(i,G_pruned); tar=vertex(spanning_tree_G_pruned[i], G_pruned);\n      boost::tuples::tie(beg, found) = edge(sour, tar,G_pruned);\n      total1+=get(weight_G_pruned, beg);\n    }\n  }\n\n\n  return spanning_tree_G_pruned;\n\n  }\n\n\n// After obtaining MST tree, the algorithm prunes the leaf nodes\n// which have prizes smaller than connection cost\ndouble cut(int &Root, vector< Vertex > &spanning_tree_G_pruned,  vector< string > &tree_from,  vector< string > &tree_to,  vector< double > &tree_cost, map < string, double > &tree_terminals){\n\n  weight_G_pruned = get(edge_weight, G_pruned);\n\n  Edge e; bool found;\n\n  Edge beg; Vertex sour, tar; int ancestor=-1; bool select=false;\n\n\n  int root= -1;\n  if(Root == -1){\n    double max=0;\n    vertex_iterator ei, ef;\n    for(tie(ei, ef)= vertices(G_pruned); ei!=ef; ei++){\n      if(g[boost::lexical_cast<int>(G_pruned[*ei].name)].c > max){\n        root = *ei;\n        max = g[boost::lexical_cast<int>(G_pruned[*ei].name)].c;\n      }\n    }\n  } else {root = idx_G_pruned(to_string(Root));}\n\n\n\n  select = true;\n\n  bool ancestor_changed=true; unsigned int father, temp; ancestor = root;\n  if (select){\n    father=spanning_tree_G_pruned[ancestor];\n    spanning_tree_G_pruned[ancestor]=ancestor;\n    while(ancestor_changed){\n      if(spanning_tree_G_pruned[father]==father){\n        ancestor_changed=false;\n        spanning_tree_G_pruned[father]=ancestor;\n      }else{\n        temp=spanning_tree_G_pruned[father];\n        spanning_tree_G_pruned[father]=ancestor;\n        ancestor=father; father=temp;\n      }\n\n    }\n\n  }else{\n    //cout <<\"There is no tree\"<<endl;\n    return 0;\n  }\n\n\n\n  vector<Node> predecessor(num_vertices(G_pruned));\n  if(select){\n    for(unsigned int i = 0; i < spanning_tree_G_pruned.size(); ++i ){\n      if(spanning_tree_G_pruned[i]!=i){\n        predecessor[i].father=spanning_tree_G_pruned[i];\n        predecessor[spanning_tree_G_pruned[i]].children.push_back(i);\n      }else{predecessor[i].father=i;}\n    }\n  }\n\n\n  for(unsigned int i = 0; i < predecessor.size(); ++i ){\n    predecessor[i].size=predecessor[i].children.size();\n    predecessor[i].price=g[boost::lexical_cast<int>(G_pruned[i].name)].c;\n\n  }\n\n\n  price_collect(predecessor, root, e, found);\n\n  process_leafs(predecessor, root, e, found);\n\n  weight_g = get(edge_weight, g);\n\n  // Tree\n  for(unsigned int i = 0; i < predecessor.size(); ++i ){\n    if(predecessor[i].father != -1 &&  predecessor[i].father != (int) i ){\n      sour= vertex(boost::lexical_cast<int>(G_pruned[i].name),g); tar = vertex(boost::lexical_cast<int>(G_pruned[predecessor[i].father].name),g);\n      boost::tuples::tie(beg, found) = edge(sour, tar,g);\n      tree_from.push_back(g[boost::lexical_cast<int>(G_pruned[i].name)].name);\n      tree_to.push_back(g[boost::lexical_cast<int>(G_pruned[predecessor[i].father].name)].name);\n      tree_cost.push_back(weight_g[beg]);\n      tree_terminals[g[boost::lexical_cast<int>(G_pruned[i].name)].name] = g[boost::lexical_cast<int>(G_pruned[i].name)].c;\n      tree_terminals[g[boost::lexical_cast<int>(G_pruned[predecessor[i].father].name)].name] = g[boost::lexical_cast<int>(G_pruned[predecessor[i].father].name)].c;\n    }\n  }\n\n\n\n  double total = 0, lostPrice =0;\n  int uncovered_nodes = 0;\n  for(unsigned int i = 0; i < predecessor.size(); ++i ){\n    if(predecessor[i].father != -1){\n      if(predecessor[i].father != (int) i){\n        sour= vertex(i,G_pruned); tar = vertex(predecessor[i].father,G_pruned);\n        boost::tuples::tie(beg, found) = edge(sour, tar,G_pruned);\n        total+=get(weight_G_pruned, beg);\n      }\n    }\n  }\n\n\n  // Lsit of nodes that are outside of final tree\n  vector<int> calculatecost(num_vertices(g));\n  for(unsigned int i = 0; i < predecessor.size(); ++i ){\n    if(predecessor[i].father != -1 && predecessor[i].father != (int) i){\n      sour= vertex(boost::lexical_cast<int>(G_pruned[i].name),g); tar = vertex(boost::lexical_cast<int>(G_pruned[predecessor[i].father].name),g);\n      calculatecost[sour]=1; calculatecost[tar]=1;\n    }\n  }\n\n  // Uncovered nodes\n  for(unsigned int i = 0; i < num_vertices(g); ++i ){\n    if(calculatecost[i] == 0 && (int) i != root ){\n      lostPrice += g[i].c;\n      uncovered_nodes++;\n    }\n  }\n\n  // The list of Nodes in the final Tree\n  for(unsigned int i = 0; i < num_vertices(g); ++i ){\n    if(calculatecost[i] == 1){\n    }\n  }\n\n  // Objective value\n  return total + lostPrice;\n\n}\n\n\n//' Internal function \\code{call_sr}\n//'\n//' This function is internally used to solve the PCST.\n//'\n//' @keywords internal\n//'\n//' @param from  A \\code{CharacterVector} that corresponds to \\code{head} nodes of the edges.\n//' @param to A \\code{CharacterVector} that corresponds the \\code{tail} nodes of the edges.\n//' @param cost A \\code{NumericVector} which represents the edge weights.\n//' @param node_names A \\code{CharacterVector} demonstrates the names of the nodes.\n//' @param node_prizes A \\code{NumericVector} which corresponds to the node prizes.\n//' @author Murodzhon Akhmedov\n//'\n// [[Rcpp::export]]\nList call_sr(CharacterVector from, CharacterVector to,  NumericVector cost, CharacterVector node_names, NumericVector node_prizes)\n{\n  clear_variables();\n\n  vector <int> terminals;\n\n  read_input_graph(from, to, cost, node_names, node_prizes);\n\n  Root = idx_g(\"DUMMY\");\n\n  double max_price=0; int max_price_index = -1;\n  for(unsigned int i=0; i<num_vertices(g); i++){\n    if (g[i].c > max_price){\n      max_price = g[i].c;\n      max_price_index = i;\n    }\n  }\n\n  if(Root != -1){\n    for(unsigned int i=0; i<num_vertices(g); i++){\n      if( (int) i != Root && g[i].c >0){\n        terminals.push_back(i);\n      }\n    }\n  }else{\n    Root = max_price_index;\n    for(unsigned int i=0; i<num_vertices(g); i++){\n      if( (int) i != Root && g[i].c >0){\n        terminals.push_back(i);\n      }\n    }\n  }\n\n  terminals.push_back(Root);\n\n\n  if(terminals.size() <=1){\n    // There is no tree\n    //return 0;\n  }\n\n\n  vector< Vertex > spanning_tree;\n  spanning_tree = constructG(terminals, Root);\n\n  vector< string > tree_from;\n  vector< string > tree_to;\n  vector< double > tree_cost;\n  map < string, double > tree_terminals;\n  double obj = cut(Root, spanning_tree, tree_from, tree_to, tree_cost, tree_terminals); if (obj == 0) return 0;\n\n  CharacterVector tree_f(tree_from.size());\n  CharacterVector tree_t(tree_to.size());\n  NumericVector tree_c(tree_cost.size());\n  CharacterVector tree_ter(tree_terminals.size());\n  NumericVector tree_ter_p(tree_terminals.size());\n\n  for(unsigned int i=0; i<tree_from.size(); i++){\n    tree_f[i]=tree_from[i];\n    tree_t[i]=tree_to[i];\n    tree_c[i]=tree_cost[i];\n  }\n\n  int counter = 0;\n  for (std::map<string, double>::iterator it=tree_terminals.begin(); it!=tree_terminals.end(); ++it){\n    tree_ter[counter] = it->first;\n    tree_ter_p[counter] = it->second;\n    counter++;\n  }\n\n  List tree = List::create(tree_from, tree_to, tree_cost, tree_ter, tree_ter_p);\n\n\n  return tree;\n}\n\n\n\n\n\n\n", "meta": {"hexsha": "5b70857542cb1c770eaa8a5cb2d3fc70a0ddc154", "size": 20395, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/PCSF.cpp", "max_stars_repo_name": "murodzhon/PCSF", "max_stars_repo_head_hexsha": "7df1520259d222b8a72533b3f2b1f22f57bd5382", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2017-08-04T19:12:49.000Z", "max_stars_repo_stars_event_max_datetime": "2019-05-08T08:29:16.000Z", "max_issues_repo_path": "src/PCSF.cpp", "max_issues_repo_name": "murodzhon/PCSF", "max_issues_repo_head_hexsha": "7df1520259d222b8a72533b3f2b1f22f57bd5382", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2017-08-15T12:26:50.000Z", "max_issues_repo_issues_event_max_datetime": "2021-02-15T01:04:56.000Z", "max_forks_repo_path": "src/PCSF.cpp", "max_forks_repo_name": "murodzhon/PCSF", "max_forks_repo_head_hexsha": "7df1520259d222b8a72533b3f2b1f22f57bd5382", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2017-08-14T03:19:04.000Z", "max_forks_repo_forks_event_max_datetime": "2020-01-17T16:02:00.000Z", "avg_line_length": 31.1850152905, "max_line_length": 192, "alphanum_fraction": 0.6526599657, "num_tokens": 5593, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7057850402140659, "lm_q2_score": 0.49218813572079556, "lm_q1q2_score": 0.3473790231625878}}
{"text": "/*    Copyright (c) 2010-2019, Delft University of Technology\n*    All rigths reserved\n*\n*    This file is part of the Tudat. Redistribution and use in source and\n*    binary forms, with or without modification, are permitted exclusively\n*    under the terms of the Modified BSD license. You should have received\n*    a copy of the license with this file. If not, please or visit:\n*    http://tudat.tudelft.nl/LICENSE.\n*/\n\n#include <iostream>\n#include <fstream>\n\n#include <boost/filesystem.hpp>\n\n#include \"pagmo/island.hpp\"\n#include \"pagmo/io.hpp\"\n#include \"pagmo/problem.hpp\"\n#include <pagmo/rng.hpp>\n#include \"pagmo/algorithms/sade.hpp\"\n#include \"problems/multipleGravityAssist.h\"\n#include \"tudat/astro/ephemerides/approximatePlanetPositions.h\"\n#include \"tudat/astro/ephemerides/constantEphemeris.h\"\n#include \"tudat/astro/gravitation/gravityFieldModel.h\"\n#include \"tudat/astro/mission_segments/createTransferTrajectory.h\"\n#include \"tudat/simulation/environment/body.h\"\n\nusing namespace pagmo;\nusing namespace tudat;\nusing namespace ephemerides;\nusing namespace gravitation;\nusing namespace simulation_setup;\n\nsimulation_setup::NamedBodyMap getApproximatePlanetBodyMap( )\n{\n\n\n    NamedBodyMap bodyMap;\n    bodyMap[ \"Sun\" ] = std::make_shared< Body >( );\n    bodyMap[ \"Mercury\" ] = std::make_shared< Body >( );\n    bodyMap[ \"Venus\" ] = std::make_shared< Body >( );\n    bodyMap[ \"Earth\" ] = std::make_shared< Body >( );\n    bodyMap[ \"Mars\" ] = std::make_shared< Body >( );\n    bodyMap[ \"Jupiter\" ] = std::make_shared< Body >( );\n    bodyMap[ \"Saturn\" ] = std::make_shared< Body >( );\n\n    bodyMap[ \"Sun\" ]->setEphemeris( std::make_shared< ConstantEphemeris >( Eigen::Vector6d::Zero( ) ) );\n    bodyMap[ \"Mercury\" ]->setEphemeris( std::make_shared< ApproximatePlanetPositions >(\n                                            ApproximatePlanetPositionsBase::BodiesWithEphemerisData::mercury ) );\n    bodyMap[ \"Venus\" ]->setEphemeris( std::make_shared< ApproximatePlanetPositions >(\n                                          ApproximatePlanetPositionsBase::BodiesWithEphemerisData::venus ) );\n    bodyMap[ \"Earth\" ]->setEphemeris( std::make_shared< ApproximatePlanetPositions >(\n                                          ApproximatePlanetPositionsBase::BodiesWithEphemerisData::earthMoonBarycenter ) );\n    bodyMap[ \"Mars\" ]->setEphemeris( std::make_shared< ApproximatePlanetPositions >(\n                                          ApproximatePlanetPositionsBase::BodiesWithEphemerisData::earthMoonBarycenter ) );\n    bodyMap[ \"Jupiter\" ]->setEphemeris( std::make_shared< ApproximatePlanetPositions >(\n                                            ApproximatePlanetPositionsBase::BodiesWithEphemerisData::jupiter ) );\n    bodyMap[ \"Saturn\" ]->setEphemeris( std::make_shared< ApproximatePlanetPositions >(\n                                           ApproximatePlanetPositionsBase::BodiesWithEphemerisData::saturn ) );\n\n    bodyMap[ \"Sun\" ]->setGravityFieldModel( std::make_shared< GravityFieldModel >( 1.32712428e20 ) );\n    bodyMap[ \"Mercury\" ]->setGravityFieldModel( std::make_shared< GravityFieldModel >( 2.2321e13 ) );\n    bodyMap[ \"Venus\" ]->setGravityFieldModel( std::make_shared< GravityFieldModel >( 3.24860e14 ) );\n    bodyMap[ \"Earth\" ]->setGravityFieldModel( std::make_shared< GravityFieldModel >( 3.9860119e14 ) );\n    bodyMap[ \"Mars\" ]->setGravityFieldModel( std::make_shared< GravityFieldModel >( 4.282837e13 ) );\n    bodyMap[ \"Jupiter\" ]->setGravityFieldModel( std::make_shared< GravityFieldModel >( 1.267e17 ) );\n    bodyMap[ \"Saturn\" ]->setGravityFieldModel( std::make_shared< GravityFieldModel >( 3.79e16 ) );\n\n    return bodyMap;\n}\n\nnamespace std\n{\ntemplate <typename T>\nostream& operator<<(ostream& output, std::vector<T> const& values)\n{\n    std::cout<<\"[ \";\n    for (auto const& value : values)\n    {\n        output << value <<\", \";\n    }\n    std::cout<<\" ]\"<<std::endl;\n    return output;\n}\n}\n//! Execute  main\nint main( )\n{\n    //Set seed for reproducible results\n    pagmo::random_device::set_seed( 123456789 );\n\n    // Set transfer order\n    std::vector< std::string > bodyOrder = {\n        \"Earth\", \"Venus\", \"Venus\", \"Earth\", \"Jupiter\", \"Saturn\" };\n    int numberOfNodes = bodyOrder.size( );\n\n    // Create leg settings (all unpowered)\n    std::vector< std::shared_ptr< TransferLegSettings > > transferLegSettings;\n    transferLegSettings.resize( numberOfNodes - 1 );\n    transferLegSettings[ 0 ] = unpoweredLeg( );\n    transferLegSettings[ 1 ] = dsmVelocityBasedLeg( );\n    transferLegSettings[ 2 ] = dsmVelocityBasedLeg( );\n    transferLegSettings[ 3 ] = unpoweredLeg( );\n    transferLegSettings[ 4 ] = unpoweredLeg( );\n\n    // Define minimum periapsis altitudes for flybys;\n    std::map< std::string, double >minimumPeriapses;\n    minimumPeriapses[ \"Venus\" ] = 6351800.0;\n    minimumPeriapses[ \"Earth\" ] = 6778000.0;\n    minimumPeriapses[ \"Mars\" ] = 3696200.0;\n    minimumPeriapses[ \"Jupiter\" ] =  600000000;\n\n    std::vector< std::shared_ptr< TransferNodeSettings > > transferNodeSettings;\n    transferNodeSettings.resize( numberOfNodes );\n    transferNodeSettings[ 0 ] = escapeAndCaptureNode( std::numeric_limits< double >::infinity( ), 0.0 );\n    transferNodeSettings[ 1 ] = swingbyNode( minimumPeriapses.at( bodyOrder.at( 1 ) ) );\n    transferNodeSettings[ 2 ] = swingbyNode( minimumPeriapses.at( bodyOrder.at( 2 ) ) );\n    transferNodeSettings[ 3 ] = swingbyNode( minimumPeriapses.at( bodyOrder.at( 3 ) ) );\n    transferNodeSettings[ 4 ] = swingbyNode( minimumPeriapses.at( bodyOrder.at( 4 ) ) );\n    transferNodeSettings[ 5 ] = captureAndInsertionNode( 1.0895e8 / 0.02, 0.98 );\n\n    printTransferParameterDefinition( transferLegSettings, transferNodeSettings );\n    simulation_setup::NamedBodyMap bodyMap = getApproximatePlanetBodyMap( );\n\n    // Define search bounds: first parameter is start date, following parameters are leg durations\n    std::vector< std::vector< double > > bounds( 2, std::vector< double >( 14, 0.0 ) );\n    bounds[ 0 ][ 0 ] = -2000.0; //MJD2000\n    bounds[ 1 ][ 0 ] = 0.0; //MJD2000\n    bounds[ 0 ][ 1 ] = 50.0;\n    bounds[ 1 ][ 1 ] = 500.0;\n    bounds[ 0 ][ 2 ] = 100.0;\n    bounds[ 1 ][ 2 ] = 500.0;\n    bounds[ 0 ][ 3 ] = 50.0;\n    bounds[ 1 ][ 3 ] = 500.0;\n    bounds[ 0 ][ 4 ] = 500.0;\n    bounds[ 1 ][ 4 ] = 2000.0;\n    bounds[ 0 ][ 5 ] = 1000.0;\n    bounds[ 1 ][ 5 ] = 10000.0;\n//    bounds[ 0 ][ 6 ] = 0.0;\n//    bounds[ 1 ][ 6 ] = 2.0E3;;\n//    bounds[ 0 ][ 7 ] = 0.0;\n//    bounds[ 1 ][ 7 ] = 2.0 * mathematical_constants::PI;\n\n//    bounds[ 0 ][ 8 ] = 0.0;\n//    bounds[ 1 ][ 8 ] = 2.0 * mathematical_constants::PI;\n\n//    bounds[ 0 ][ 9 ] = 0.05;\n//    bounds[ 1 ][ 9 ] = 0.95;\n    int currentIndex = 5;\n    for( int i = 1; i < 3; i++ )\n    {\n        // periapsis bounds\n        bounds[ 0 ][ currentIndex + ( i - 1 ) * 4 + 1 ] = minimumPeriapses.at( bodyOrder.at( i ) );\n        bounds[ 1 ][ currentIndex + ( i - 1 ) * 4 + 1 ] = 1.5 * minimumPeriapses.at( bodyOrder.at( i ) );\n\n        // orbit orientation bounds\n        bounds[ 0 ][ currentIndex + ( i - 1 ) * 4 + 2 ] = 0.0;\n        bounds[ 1 ][ currentIndex + ( i - 1 ) * 4 + 2 ] = 2.0 * mathematical_constants::PI;\n\n        // Swingby Delta V bounds\n        bounds[ 0 ][ currentIndex + ( i - 1 ) * 4 + 3 ] = 0;\n        bounds[ 1 ][ currentIndex + ( i - 1 ) * 4 + 3 ] = 2500.0;\n\n        // DSM TOF fraction\n        bounds[ 0 ][ currentIndex + ( i - 1 ) * 4 + 4 ] = 0.05;\n        bounds[ 1 ][ currentIndex + ( i - 1 ) * 4 + 4 ] = 0.95;\n    }\n\n    // Create object to compute the problem fitness\n    problem prob{ MultipleGravityAssist(\n                    bodyMap, transferLegSettings, transferNodeSettings, bodyOrder, \"Sun\", bounds ) };\n\n\n    // Select NSGA2 algorithm for priblem\n    algorithm algo{sade( )};\n\n    // Create an island with 1000 individuals\n    island isl{algo, prob, 500 };\n\n    // Evolve for 512 generations\n    for( int i = 0 ; i < 10000; i++ )\n    {\n\n        isl.evolve( );\n        while( isl.status( ) != pagmo::evolve_status::idle &&\n               isl.status( ) != pagmo::evolve_status::idle_error )\n        {\n            isl.wait( );\n        }\n\n        isl.wait_check( ); // Raises errors\n\n        if( i% 100 == 0 )\n        {\n            std::cout<<i<<\" \"<<isl.get_population().champion_f()[0]<<\"***  \"<<\n                       isl.get_population().champion_x()<<std::endl;        // Write current iteration results to file\n        }\n//        printPopulationToFile( isl.get_population( ).get_x( ), \"mo_mga_EVEEJ_\" + std::to_string( i ), false );\n//        printPopulationToFile( isl.get_population( ).get_f( ), \"mo_mga_EVEEJ_\" + std::to_string( i ), true );\n    }\n\n    return 0;\n\n}\n", "meta": {"hexsha": "663cab4b0a9a89ace26db4d3b177c07a8db10b4e", "size": 8621, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/pagmo/mgaTransferExample.cpp", "max_stars_repo_name": "kimonito98/tudat", "max_stars_repo_head_hexsha": "c28f2a3e78b8492e2e054ad5e0d1f9ad785cd092", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/pagmo/mgaTransferExample.cpp", "max_issues_repo_name": "kimonito98/tudat", "max_issues_repo_head_hexsha": "c28f2a3e78b8492e2e054ad5e0d1f9ad785cd092", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/pagmo/mgaTransferExample.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": 42.0536585366, "max_line_length": 123, "alphanum_fraction": 0.6266094421, "num_tokens": 2584, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.7057850278370111, "lm_q2_score": 0.4921881357207956, "lm_q1q2_score": 0.34737901707074836}}
{"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 AMGE_HOST_TEMPLATES_HPP\n#define AMGE_HOST_TEMPLATES_HPP\n\n#include <mfmg/common/lanczos.templates.hpp>\n#include <mfmg/common/utils.hpp>\n#include <mfmg/dealii/amge_host.hpp>\n#include <mfmg/dealii/anasazi.templates.hpp>\n#include <mfmg/dealii/dealii_matrix_free_mesh_evaluator.hpp>\n\n#include <deal.II/base/work_stream.h>\n#include <deal.II/dofs/dof_accessor.h>\n#include <deal.II/lac/arpack_solver.h>\n#include <deal.II/lac/la_parallel_vector.h>\n#include <deal.II/lac/lapack_full_matrix.h>\n#include <deal.II/lac/precondition.h>\n#include <deal.II/lac/solver_cg.h>\n#include <deal.II/lac/sparse_direct.h>\n\n#include <EpetraExt_MatrixMatrix.h>\n\nnamespace mfmg\n{\n\nstruct Identity\n{\n  template <typename VectorType>\n  void vmult(VectorType &dst, const VectorType &src) const\n  {\n    dst = src;\n  }\n};\n\n/**\n * A class representing the operator on a given agglomerate\n * wrapping a MeshEvaluator object to restrict the interface\n * to the operations required on an agglomerate.\n */\ntemplate <typename MeshEvaluator>\nstruct MatrixFreeAgglomerateOperator\n{\n  using size_type = typename MeshEvaluator::size_type;\n\n  /**\n   * This constructor expects @p mesh_evaluator to be an object that performs\n   * the actual operator evaluation. @p dof_handler is used to initialize the\n   * appropriate data structures in the MeshEvaluator and is expected to be\n   * initialized itself with respect to a given dealii::FiniteElement object\n   * in that call.\n   */\n  template <typename DoFHandler>\n  MatrixFreeAgglomerateOperator(MeshEvaluator const &mesh_evaluator,\n                                DoFHandler &dof_handler,\n                                dealii::AffineConstraints<double> &constraints)\n      : _mesh_evaluator(mesh_evaluator.clone()), _dof_handler(dof_handler),\n        _constraints(constraints)\n  {\n    _mesh_evaluator->matrix_free_initialize_agglomerate(dof_handler);\n  }\n\n  /**\n   * Perform the operator evaluation on the agglomerate.\n   */\n  void vmult(dealii::Vector<double> &dst,\n             dealii::Vector<double> const &src) const\n  {\n    _mesh_evaluator->matrix_free_evaluate_agglomerate(src, dst);\n  }\n\n  /**\n   * Return the diagonal entries the matrix corresponding to the operator would\n   * have. This data is necessary for certain smoothers to work.\n   * @p _constraints is used to restrict the diagonal to the correct\n   * (constrained) finite element subspace.\n   */\n  std::vector<double> get_diag_elements() const\n  {\n    return _mesh_evaluator->matrix_free_get_agglomerate_diagonal(_constraints);\n  }\n\n  /**\n   * Return the dimension of the range of the agglomerate operator.\n   */\n  size_type m() const { return _dof_handler.n_dofs(); }\n\n  /**\n   * Return the dimension of the domain of the agglomerate operator.\n   */\n  size_type n() const { return _dof_handler.n_dofs(); }\n\nprivate:\n  /**\n   * The actual operator wrapped.\n   */\n  std::unique_ptr<MeshEvaluator const> const _mesh_evaluator;\n\n  /**\n   * The dimension for the underlying mesh.\n   */\n  static int constexpr dim = MeshEvaluator::_dim;\n\n  /**\n   * The DoFHandler containing information about the degrees of freedom on the\n   * agglomerate.\n   */\n  dealii::DoFHandler<dim> const &_dof_handler;\n\n  /**\n   * The constraints needed for restricting the vector returned by\n   * get_diag_elements() to the correct subspace.\n   */\n  dealii::AffineConstraints<double> &_constraints;\n};\n\ntemplate <int dim, typename MeshEvaluator, typename VectorType>\nAMGe_host<dim, MeshEvaluator, VectorType>::AMGe_host(\n    MPI_Comm comm, dealii::DoFHandler<dim> const &dof_handler,\n    boost::property_tree::ptree const &eigensolver_params)\n    : AMGe<dim, VectorType>(comm, dof_handler),\n      _eigensolver_params(eigensolver_params)\n{\n}\n} // namespace mfmg\n\nnamespace Anasazi\n{\ntemplate <typename VectorType, typename MeshEvaluator>\nclass OperatorTraits<double, mfmg::MultiVector<VectorType>,\n                     mfmg::MatrixFreeAgglomerateOperator<MeshEvaluator>>\n{\n  using MultiVectorType = mfmg::MultiVector<VectorType>;\n  using OperatorType = mfmg::MatrixFreeAgglomerateOperator<MeshEvaluator>;\n\npublic:\n  static void Apply(OperatorType const &op, MultiVectorType const &x,\n                    MultiVectorType &y)\n  {\n    auto n_vectors = x.n_vectors();\n\n    ASSERT(x.size() == y.size(), \"\");\n    ASSERT(y.n_vectors() == n_vectors, \"\");\n\n    for (int i = 0; i < n_vectors; i++)\n      op.vmult(*y[i], *x[i]);\n  }\n};\n\n} // namespace Anasazi\n\nnamespace mfmg\n{\nnamespace\n{\ntemplate <typename AgglomerateOperator>\nvoid lanczos_compute_eigenvalues_and_eigenvectors(\n    unsigned int n_eigenvectors, double tolerance,\n    boost::property_tree::ptree const &eigensolver_params,\n    AgglomerateOperator const &agglomerate_operator,\n    dealii::Vector<double> const &initial_guess,\n    std::vector<std::complex<double>> &eigenvalues,\n    std::vector<dealii::Vector<double>> &eigenvectors)\n{\n  boost::property_tree::ptree lanczos_params;\n  lanczos_params.put(\"num_eigenpairs\", n_eigenvectors);\n  // We are having trouble with Lanczos when tolerance is too tight.\n  // Typically, it results in spurious eigenvalues (so far, only noticed 0).\n  // This seems to be the result of producing too many Lanczos vectors. For\n  // hierarchy_3d tests, any tolerance below 1e-5 (e.g., 1e-6) produces this\n  // problem. Thus, we try to work around it here. It is still unclear how\n  // robust this is.\n  lanczos_params.put(\"tolerance\", std::max(tolerance, 1e-4));\n  lanczos_params.put(\"max_iterations\",\n                     eigensolver_params.get(\"max_iterations\", 200));\n  lanczos_params.put(\"percent_overshoot\",\n                     eigensolver_params.get(\"percent_overshoot\", 5));\n  bool is_deflated = eigensolver_params.get(\"is_deflated\", false);\n  if (is_deflated)\n  {\n    lanczos_params.put(\"is_deflated\", true);\n    lanczos_params.put(\"num_cycles\", eigensolver_params.get<int>(\"num_cycles\"));\n    lanczos_params.put(\"num_eigenpairs_per_cycle\",\n                       eigensolver_params.get<int>(\"num_eigenpairs_per_cycle\"));\n  }\n\n  Lanczos<AgglomerateOperator, dealii::Vector<double>> solver(\n      agglomerate_operator);\n\n  std::vector<double> real_eigenvalues;\n  std::tie(real_eigenvalues, eigenvectors) =\n      solver.solve(lanczos_params, initial_guess);\n  ASSERT(n_eigenvectors == eigenvectors.size(),\n         \"Wrong number of computed eigenpairs\");\n\n  // Copy real eigenvalues to complex\n  std::copy(real_eigenvalues.begin(), real_eigenvalues.end(),\n            eigenvalues.begin());\n}\n\ntemplate <typename AgglomerateOperator>\nvoid anasazi_compute_eigenvalues_and_eigenvectors(\n    unsigned int n_eigenvectors,\n    boost::property_tree::ptree const &eigensolver_params,\n    AgglomerateOperator const &agglomerate_operator,\n    dealii::Vector<double> const &initial_guess,\n    std::vector<dealii::Vector<double>> const &lobpcg_vectors,\n    std::vector<std::complex<double>> &eigenvalues,\n    std::vector<dealii::Vector<double>> &eigenvectors)\n{\n  AnasaziSolver<AgglomerateOperator, dealii::Vector<double>> solver(\n      agglomerate_operator);\n\n  std::vector<double> real_eigenvalues;\n  std::vector<std::shared_ptr<dealii::Vector<double>>> lobpcg_initial_guess;\n  // If the vectors in scratch_data do not exist or if the size of agglomerate\n  // has changed, the initial guess for LOBPCG is the initial provided by the\n  // user.\n  if ((lobpcg_vectors.size() == 0) ||\n      (lobpcg_vectors[0].size() != initial_guess.size()))\n  {\n    lobpcg_initial_guess.resize(1);\n    lobpcg_initial_guess[0] =\n        std::make_shared<dealii::Vector<double>>(initial_guess);\n  }\n  else\n  {\n    lobpcg_initial_guess.resize(n_eigenvectors);\n    for (unsigned int i = 0; i < n_eigenvectors; ++i)\n      lobpcg_initial_guess[i] =\n          std::make_shared<dealii::Vector<double>>(lobpcg_vectors[i]);\n\n    // If the initial vector has zero entries due to the constraints, we need\n    // to modify the LOPBCG initial guess. Conversely if the LOBPCG initial\n    // guess does have zero entries but the initial vector does not, we set\n    // the entries in the LOPBCG initial guess.\n    unsigned int const eigenvector_size = initial_guess.size();\n    for (unsigned int i = 0; i < eigenvector_size; ++i)\n    {\n      if (initial_guess[i] == 0.)\n      {\n        for (unsigned int j = 0; j < n_eigenvectors; ++j)\n        {\n          (*lobpcg_initial_guess[j])[i] = 0.;\n        }\n      }\n      else\n      {\n        for (unsigned int j = 0; j < n_eigenvectors; ++j)\n        {\n          if ((*lobpcg_initial_guess[j])[i] == 0.)\n          {\n            (*lobpcg_initial_guess[j])[i] = initial_guess[i];\n          }\n        }\n      }\n    }\n  }\n  std::tie(real_eigenvalues, eigenvectors) =\n      solver.solve(eigensolver_params, lobpcg_initial_guess);\n  ASSERT(n_eigenvectors == eigenvectors.size(),\n         \"Wrong number of computed eigenpairs\");\n\n  // Copy real eigenvalues to complex\n  std::copy(real_eigenvalues.begin(), real_eigenvalues.end(),\n            eigenvalues.begin());\n}\n} // namespace\n\ntemplate <int dim, typename MeshEvaluator, typename VectorType>\ntemplate <typename Triangulation>\nstd::tuple<std::vector<std::complex<double>>,\n           std::vector<dealii::Vector<double>>,\n           std::vector<typename VectorType::value_type>,\n           std::vector<dealii::types::global_dof_index>>\nAMGe_host<dim, MeshEvaluator, VectorType>::compute_local_eigenvectors(\n    unsigned int n_eigenvectors, double tolerance,\n    Triangulation const &agglomerate_triangulation,\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    MeshEvaluator const &evaluator, LobpcgScratchData const &scratch_data,\n    typename std::enable_if_t<is_matrix_free<MeshEvaluator>::value &&\n                                  std::is_class<Triangulation>::value,\n                              int>) const\n{\n  dealii::DoFHandler<dim> agglomerate_dof_handler(agglomerate_triangulation);\n  dealii::AffineConstraints<double> agglomerate_constraints;\n\n  using AgglomerateOperator = MatrixFreeAgglomerateOperator<MeshEvaluator>;\n  AgglomerateOperator agglomerate_operator(evaluator, agglomerate_dof_handler,\n                                           agglomerate_constraints);\n\n  auto const diag_elements = agglomerate_operator.get_diag_elements();\n\n  // Compute the eigenvalues and the eigenvectors\n  unsigned int const n_dofs_agglomerate = agglomerate_operator.m();\n  std::vector<std::complex<double>> eigenvalues(n_eigenvectors);\n  std::vector<dealii::Vector<double>> eigenvectors(\n      n_eigenvectors, dealii::Vector<double>(n_dofs_agglomerate));\n\n  auto const eigensolver_type =\n      _eigensolver_params.get<std::string>(\"type\", \"lanczos\");\n  dealii::Vector<double> initial_vector(n_dofs_agglomerate);\n  evaluator.set_initial_guess(agglomerate_constraints, initial_vector);\n  if (eigensolver_type == \"lanczos\")\n  {\n    lanczos_compute_eigenvalues_and_eigenvectors(\n        n_eigenvectors, tolerance, _eigensolver_params, agglomerate_operator,\n        initial_vector, eigenvalues, eigenvectors);\n  }\n  else if (eigensolver_type == \"anasazi\")\n  {\n    anasazi_compute_eigenvalues_and_eigenvectors(\n        n_eigenvectors, _eigensolver_params, agglomerate_operator,\n        initial_vector, scratch_data.lobpcg_init_guess, eigenvalues,\n        eigenvectors);\n  }\n  else if (eigensolver_type == \"arpack\")\n  {\n    throw std::runtime_error(\n        \"ARPACK not available as eigensolver in matrix-free mode\");\n  }\n  else if (eigensolver_type == \"lapack\")\n  {\n    throw std::runtime_error(\n        \"LAPACK not available as eigensolver in matrix-free mode\");\n  }\n  else\n  {\n    ASSERT(false, \"Unknown eigensolver type '\" + eigensolver_type + \"'\");\n  }\n\n  // Compute the map between the local and the global dof indices.\n  std::vector<dealii::types::global_dof_index> dof_indices_map =\n      this->compute_dof_index_map(patch_to_global_map, agglomerate_dof_handler);\n\n  return std::make_tuple(eigenvalues, eigenvectors, diag_elements,\n                         dof_indices_map);\n}\n\ntemplate <int dim, typename MeshEvaluator, typename VectorType>\ntemplate <typename Triangulation>\nstd::tuple<std::vector<std::complex<double>>,\n           std::vector<dealii::Vector<double>>,\n           std::vector<typename VectorType::value_type>,\n           std::vector<dealii::types::global_dof_index>>\nAMGe_host<dim, MeshEvaluator, VectorType>::compute_local_eigenvectors(\n    unsigned int n_eigenvectors, double tolerance,\n    Triangulation const &agglomerate_triangulation,\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    MeshEvaluator const &evaluator, LobpcgScratchData const &scratch_data,\n    typename std::enable_if_t<!is_matrix_free<MeshEvaluator>::value &&\n                                  std::is_class<Triangulation>::value,\n                              int>) const\n{\n  dealii::DoFHandler<dim> agglomerate_dof_handler(agglomerate_triangulation);\n  dealii::AffineConstraints<double> agglomerate_constraints;\n  using value_type = typename VectorType::value_type;\n  dealii::SparsityPattern agglomerate_sparsity_pattern;\n  dealii::SparseMatrix<value_type> agglomerate_system_matrix;\n\n  // Call user function to build the system matrix\n  evaluator.evaluate_agglomerate(\n      agglomerate_dof_handler, agglomerate_constraints,\n      agglomerate_sparsity_pattern, agglomerate_system_matrix);\n\n  // Get the diagonal elements\n  unsigned int const size = agglomerate_system_matrix.m();\n  std::vector<ScalarType> diag_elements(size);\n  for (unsigned int i = 0; i < size; ++i)\n    diag_elements[i] = agglomerate_system_matrix.diag_element(i);\n\n  // Shift eigenvalues away from zero\n  double const average_diagonal =\n      std::accumulate(diag_elements.begin(), diag_elements.end(), 0.) / size;\n  for (unsigned int i = 0; i < size; ++i)\n    agglomerate_system_matrix.diag_element(i) += average_diagonal;\n  // Shift diagonal entries for constrained degrees of freedom, to avoid\n  // using the corresponding eigenvectors\n  for (auto const constraint : agglomerate_constraints.get_lines())\n  {\n    agglomerate_system_matrix.diag_element(constraint.index) = 200;\n  }\n\n  // Compute the eigenvalues and the eigenvectors\n  unsigned int const n_dofs_agglomerate = agglomerate_system_matrix.m();\n  std::vector<std::complex<double>> eigenvalues(n_eigenvectors);\n  // Arpack only works with double not float\n  std::vector<dealii::Vector<double>> eigenvectors(\n      n_eigenvectors, dealii::Vector<double>(n_dofs_agglomerate));\n\n  dealii::Vector<double> initial_vector(n_dofs_agglomerate);\n  evaluator.set_initial_guess(agglomerate_constraints, initial_vector);\n  auto const eigensolver_type =\n      _eigensolver_params.get<std::string>(\"type\", \"arpack\");\n  if (eigensolver_type == \"arpack\")\n  {\n    // Make Identity mass matrix\n    Identity agglomerate_mass_matrix;\n\n    dealii::SparseDirectUMFPACK inv_system_matrix;\n    inv_system_matrix.initialize(agglomerate_system_matrix);\n\n    dealii::SolverControl solver_control(n_dofs_agglomerate, tolerance);\n    unsigned int const n_arnoldi_vectors = 2 * n_eigenvectors + 2;\n    bool const symmetric = true;\n    // We want the eigenvalues of the smallest magnitudes but we need to ask\n    // for the ones with the largest magnitudes because they are computed for\n    // the inverse of the matrix we care about.\n    auto const which_eigenvalues =\n        dealii::ArpackSolver::WhichEigenvalues::largest_magnitude;\n    dealii::ArpackSolver::AdditionalData additional_data(\n        n_arnoldi_vectors, which_eigenvalues, symmetric);\n    dealii::ArpackSolver solver(solver_control, additional_data);\n\n    // Compute the eigenvectors. Arpack outputs eigenvectors with a L2 norm of\n    // one.\n    solver.set_initial_vector(initial_vector);\n    solver.solve(agglomerate_system_matrix, agglomerate_mass_matrix,\n                 inv_system_matrix, eigenvalues, eigenvectors);\n  }\n  else if (eigensolver_type == \"lanczos\")\n  {\n    lanczos_compute_eigenvalues_and_eigenvectors(\n        n_eigenvectors, tolerance, _eigensolver_params,\n        agglomerate_system_matrix, initial_vector, eigenvalues, eigenvectors);\n  }\n  else if (eigensolver_type == \"anasazi\")\n  {\n    anasazi_compute_eigenvalues_and_eigenvectors(\n        n_eigenvectors, _eigensolver_params, agglomerate_system_matrix,\n        initial_vector, scratch_data.lobpcg_init_guess, eigenvalues,\n        eigenvectors);\n  }\n  else if (eigensolver_type == \"lapack\")\n  {\n    // Use Lapack to compute the eigenvalues\n    dealii::LAPACKFullMatrix<double> full_matrix;\n    full_matrix.copy_from(agglomerate_system_matrix);\n\n    double const lower_bound = -0.5;\n    double const upper_bound = 100.;\n    double const tol = 1e-12;\n    dealii::Vector<double> lapack_eigenvalues(size);\n    dealii::FullMatrix<double> lapack_eigenvectors;\n    full_matrix.compute_eigenvalues_symmetric(\n        lower_bound, upper_bound, tol, lapack_eigenvalues, lapack_eigenvectors);\n\n    // Copy the eigenvalues and the eigenvectors in the right format\n    for (unsigned int i = 0; i < n_eigenvectors; ++i)\n      eigenvalues[i] = lapack_eigenvalues[i];\n\n    for (unsigned int i = 0; i < n_eigenvectors; ++i)\n      for (unsigned int j = 0; j < n_dofs_agglomerate; ++j)\n        eigenvectors[i][j] = lapack_eigenvectors[j][i];\n  }\n  else\n  {\n    ASSERT(false, \"Unknown eigensolver type '\" + eigensolver_type + \"'\");\n  }\n\n  // Shift eigenvalues back\n  for (unsigned int i = 0; i < n_eigenvectors; ++i)\n    eigenvalues[i] -= average_diagonal;\n\n  // Compute the map between the local and the global dof indices.\n  std::vector<dealii::types::global_dof_index> dof_indices_map =\n      this->compute_dof_index_map(patch_to_global_map, agglomerate_dof_handler);\n\n  return std::make_tuple(eigenvalues, eigenvectors, diag_elements,\n                         dof_indices_map);\n}\n\ntemplate <int dim, typename MeshEvaluator, typename VectorType>\nvoid AMGe_host<dim, MeshEvaluator, VectorType>::setup_restrictor(\n    boost::property_tree::ptree const &agglomerate_ptree,\n    unsigned int const n_eigenvectors, double const tolerance,\n    MeshEvaluator const &evaluator,\n    dealii::LinearAlgebra::distributed::Vector<\n        typename VectorType::value_type> const &locally_relevant_global_diag,\n    dealii::TrilinosWrappers::SparseMatrix &restriction_sparse_matrix)\n{\n  // Flag the cells to build agglomerates.\n  unsigned int const n_agglomerates =\n      this->build_agglomerates(agglomerate_ptree);\n\n  // Parallel part of the setup.\n  std::vector<unsigned int> agglomerate_ids(n_agglomerates);\n  std::iota(agglomerate_ids.begin(), agglomerate_ids.end(), 1);\n  std::vector<dealii::Vector<double>> eigenvectors;\n  std::vector<std::vector<ScalarType>> diag_elements;\n  std::vector<std::vector<dealii::types::global_dof_index>> dof_indices_maps;\n  std::vector<unsigned int> n_local_eigenvectors;\n  LobpcgScratchData scratch_data;\n  CopyData copy_data;\n\n  dealii::WorkStream::run(\n      agglomerate_ids.begin(), agglomerate_ids.end(),\n      [&](std::vector<unsigned int>::iterator const &agg_id,\n          LobpcgScratchData &local_scratch_data, CopyData &local_copy_data) {\n        this->local_worker(n_eigenvectors, tolerance, evaluator, agg_id,\n                           local_scratch_data, local_copy_data);\n      },\n      [&](CopyData const &local_copy_data) {\n        this->copy_local_to_global(local_copy_data, eigenvectors, diag_elements,\n                                   dof_indices_maps, n_local_eigenvectors);\n      },\n      scratch_data, copy_data);\n\n  AMGe<dim, VectorType>::compute_restriction_sparse_matrix(\n      eigenvectors, diag_elements, dof_indices_maps, n_local_eigenvectors,\n      locally_relevant_global_diag, restriction_sparse_matrix);\n\n  // When checking the restriction matrix, we check that the sum of the local\n  // diagonals is the global diagonals. This is not true for matrix-free because\n  // the constraints values are set arbitrarily.\n  if (std::is_base_of<DealIIMatrixFreeMeshEvaluator<dim>,\n                      MeshEvaluator>::value == false)\n  {\n    check_restriction_matrix(this->_comm, eigenvectors, dof_indices_maps,\n                             locally_relevant_global_diag, diag_elements,\n                             n_local_eigenvectors);\n  }\n}\n\ntemplate <int dim, typename MeshEvaluator, typename VectorType>\nvoid AMGe_host<dim, MeshEvaluator, VectorType>::setup_restrictor(\n    boost::property_tree::ptree const &agglomerate_ptree,\n    unsigned int const n_eigenvectors, double const tolerance,\n    MeshEvaluator const &evaluator,\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,\n    std::vector<double> &eigenvalues)\n{\n  // Flag the cells to build agglomerates.\n  unsigned int const n_agglomerates =\n      this->build_agglomerates(agglomerate_ptree);\n\n  // Parallel part of the setup.\n  std::vector<unsigned int> agglomerate_ids(n_agglomerates);\n  std::iota(agglomerate_ids.begin(), agglomerate_ids.end(), 1);\n  std::vector<dealii::Vector<double>> eigenvectors;\n  std::vector<std::vector<ScalarType>> diag_elements;\n  std::vector<std::vector<dealii::types::global_dof_index>> dof_indices_maps;\n  std::vector<unsigned int> n_local_eigenvectors;\n  LobpcgScratchData scratch_data;\n  CopyData copy_data;\n\n  dealii::WorkStream::run(\n      agglomerate_ids.begin(), agglomerate_ids.end(),\n      [&](std::vector<unsigned int>::iterator const &agg_id,\n          LobpcgScratchData &local_scratch_data, CopyData &local_copy_data) {\n        this->local_worker(n_eigenvectors, tolerance, evaluator, agg_id,\n                           local_scratch_data, local_copy_data);\n      },\n      [&](CopyData const &local_copy_data) {\n        this->copy_local_to_global_eig(local_copy_data, eigenvalues,\n                                       eigenvectors, diag_elements,\n                                       dof_indices_maps, n_local_eigenvectors);\n      },\n      scratch_data, copy_data);\n\n  AMGe<dim, VectorType>::compute_restriction_sparse_matrix(\n      eigenvectors, diag_elements, dof_indices_maps, n_local_eigenvectors,\n      locally_relevant_global_diag, restriction_sparse_matrix,\n      eigenvector_sparse_matrix, delta_eigenvector_matrix);\n}\n\ntemplate <int dim, typename MeshEvaluator, typename VectorType>\nvoid AMGe_host<dim, MeshEvaluator, VectorType>::local_worker(\n    unsigned int const n_eigenvectors, double const tolerance,\n    MeshEvaluator const &evaluator,\n    std::vector<unsigned int>::iterator const &agg_id,\n    LobpcgScratchData &scratch_data, CopyData &copy_data)\n{\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;\n\n  this->build_agglomerate_triangulation(*agg_id, agglomerate_triangulation,\n                                        agglomerate_to_global_tria_map);\n\n  std::tie(copy_data.local_eigenvalues, copy_data.local_eigenvectors,\n           copy_data.diag_elements, copy_data.local_dof_indices_map) =\n      compute_local_eigenvectors(\n          n_eigenvectors, tolerance, agglomerate_triangulation,\n          agglomerate_to_global_tria_map, evaluator, scratch_data);\n\n  if (_eigensolver_params.get(\"type\", \"lanczos\") == \"anasazi\")\n  {\n    if (_eigensolver_params.get(\"use_initial_guess\", false))\n    {\n      // Copy the eigenvectors to be used as initial guess for LOBPCG\n      scratch_data.lobpcg_init_guess = copy_data.local_eigenvectors;\n    }\n  }\n}\n\ntemplate <int dim, typename MeshEvaluator, typename VectorType>\nvoid AMGe_host<dim, MeshEvaluator, VectorType>::copy_local_to_global(\n    CopyData const &copy_data,\n    std::vector<dealii::Vector<double>> &eigenvectors,\n    std::vector<std::vector<typename VectorType::value_type>> &diag_elements,\n    std::vector<std::vector<dealii::types::global_dof_index>> &dof_indices_maps,\n    std::vector<unsigned int> &n_local_eigenvectors)\n{\n  eigenvectors.insert(eigenvectors.end(), copy_data.local_eigenvectors.begin(),\n                      copy_data.local_eigenvectors.end());\n\n  diag_elements.push_back(copy_data.diag_elements);\n\n  dof_indices_maps.push_back(copy_data.local_dof_indices_map);\n\n  n_local_eigenvectors.push_back(copy_data.local_eigenvectors.size());\n}\n\ntemplate <int dim, typename MeshEvaluator, typename VectorType>\nvoid AMGe_host<dim, MeshEvaluator, VectorType>::copy_local_to_global_eig(\n    CopyData const &copy_data, std::vector<double> &eigenvalues,\n    std::vector<dealii::Vector<double>> &eigenvectors,\n    std::vector<std::vector<typename VectorType::value_type>> &diag_elements,\n    std::vector<std::vector<dealii::types::global_dof_index>> &dof_indices_maps,\n    std::vector<unsigned int> &n_local_eigenvectors)\n{\n  copy_local_to_global(copy_data, eigenvectors, diag_elements, dof_indices_maps,\n                       n_local_eigenvectors);\n\n  std::transform(copy_data.local_eigenvalues.begin(),\n                 copy_data.local_eigenvalues.end(),\n                 std::back_inserter(eigenvalues),\n                 [](std::complex<double> const &z) { return z.real(); });\n}\n} // namespace mfmg\n\n#endif\n", "meta": {"hexsha": "214e99905dfa92f768f78c498f7185e9a81769d4", "size": 26223, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/mfmg/dealii/amge_host.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/dealii/amge_host.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/dealii/amge_host.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": 40.0963302752, "max_line_length": 80, "alphanum_fraction": 0.7075468101, "num_tokens": 6424, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7057850154599563, "lm_q2_score": 0.49218813572079556, "lm_q1q2_score": 0.3473790109789088}}
{"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#include \"Coulomb.h\"\n\n#include <boost/math/constants/constants.hpp>\n\n#include \"BaseLib/Error.h\"\n#include \"LogPenalty.h\"\n#include \"MathLib/MathTools.h\"\n#include \"NumLib/Exceptions.h\"\n\nnamespace MaterialLib\n{\nnamespace Fracture\n{\nnamespace Coulomb\n{\nstruct MaterialPropertyValues\n{\n    double Kn = 0.0;\n    double Ks = 0.0;\n    double phi = 0.0;  // friction angle\n    double psi = 0.0;  // dilation angle\n    double c = 0.0;\n\n    template <typename MaterialProperties>\n    MaterialPropertyValues(MaterialProperties const& mp,\n                           double const t,\n                           ParameterLib::SpatialPosition const& x)\n    {\n        Kn = mp.normal_stiffness(t, x)[0];\n        Ks = mp.shear_stiffness(t, x)[0];\n        auto constexpr degree =\n            boost::math::constants::degree<double>();  // pi/180\n        phi = mp.friction_angle(t, x)[0] * degree;\n        psi = mp.dilatancy_angle(t, x)[0] * degree;\n        c = mp.cohesion(t, x)[0];\n    }\n};\n\ntemplate <int DisplacementDim>\nvoid Coulomb<DisplacementDim>::computeConstitutiveRelation(\n    double const t,\n    ParameterLib::SpatialPosition const& x,\n    double const aperture0,\n    Eigen::Ref<Eigen::VectorXd const>\n    /*sigma0*/,\n    Eigen::Ref<Eigen::VectorXd const>\n        w_prev,\n    Eigen::Ref<Eigen::VectorXd const>\n        w,\n    Eigen::Ref<Eigen::VectorXd const>\n        sigma_prev,\n    Eigen::Ref<Eigen::VectorXd>\n        sigma,\n    Eigen::Ref<Eigen::MatrixXd>\n        Kep,\n    typename FractureModelBase<DisplacementDim>::MaterialStateVariables&\n        material_state_variables)\n{\n    assert(dynamic_cast<StateVariables<DisplacementDim> const*>(\n               &material_state_variables) != nullptr);\n\n    StateVariables<DisplacementDim>& state =\n        static_cast<StateVariables<DisplacementDim>&>(material_state_variables);\n\n    MaterialPropertyValues const mat(_mp, t, x);\n\n    const int index_ns = DisplacementDim - 1;\n    double const aperture = w[index_ns] + aperture0;\n\n    Eigen::MatrixXd Ke;\n    {  // Elastic tangent stiffness\n        Ke = Eigen::MatrixXd::Zero(DisplacementDim, DisplacementDim);\n        for (int i = 0; i < index_ns; i++)\n        {\n            Ke(i, i) = mat.Ks;\n        }\n\n        Ke(index_ns, index_ns) = mat.Kn;\n    }\n\n    // Total plastic aperture compression\n    // NOTE: Initial condition sigma0 seems to be associated with an initial\n    // condition of the w0 = 0. Therefore the initial state is not associated\n    // with a plastic aperture change.\n    {  // Exact elastic predictor\n        sigma.noalias() = Ke * (w - w_prev);\n\n        sigma.coeffRef(index_ns) *=\n            logPenaltyDerivative(aperture0, aperture, _penalty_aperture_cutoff);\n        sigma.noalias() += sigma_prev;\n    }\n\n    // correction for an opening fracture\n    if (_tension_cutoff && sigma[DisplacementDim - 1] >= 0)\n    {\n        Kep.setZero();\n        sigma.setZero();\n        state.w_p = w;\n        material_state_variables.setTensileStress(true);\n        return;\n    }\n\n    auto yield_function = [&mat](Eigen::VectorXd const& s)\n    {\n        double const sigma_n = s[DisplacementDim - 1];\n        Eigen::VectorXd const sigma_s = s.head(DisplacementDim - 1);\n        double const mag_tau = sigma_s.norm();  // magnitude\n        return mag_tau + sigma_n * std::tan(mat.phi) - mat.c;\n    };\n\n    {  // Exit if still in elastic range by checking the shear yield function.\n        double const Fs = yield_function(sigma);\n        material_state_variables.setShearYieldFunctionValue(Fs);\n        if (Fs < .0)\n        {\n            Kep = Ke;\n            Kep(index_ns, index_ns) *= logPenaltyDerivative(\n                aperture0, aperture, _penalty_aperture_cutoff);\n            return;\n        }\n    }\n\n    auto yield_function_derivative = [&mat](Eigen::VectorXd const& s)\n    {\n        Eigen::Matrix<double, DisplacementDim, 1> dFs_dS;\n        dFs_dS.template head<DisplacementDim - 1>().noalias() =\n            s.template head<DisplacementDim - 1>().normalized();\n        dFs_dS.coeffRef(DisplacementDim - 1) = std::tan(mat.phi);\n        return dFs_dS;\n    };\n\n    // plastic potential function: Qs = |tau| + Sn * tan da\n    auto plastic_potential_derivative = [&mat](Eigen::VectorXd const& s)\n    {\n        Eigen::Matrix<double, DisplacementDim, 1> dQs_dS;\n        dQs_dS.template head<DisplacementDim - 1>().noalias() =\n            s.template head<DisplacementDim - 1>().normalized();\n        dQs_dS.coeffRef(DisplacementDim - 1) = std::tan(mat.psi);\n        return dQs_dS;\n    };\n\n    {  // Newton\n\n        Eigen::FullPivLU<Eigen::Matrix<double, 1, 1, Eigen::RowMajor>>\n            linear_solver;\n        using ResidualVectorType = Eigen::Matrix<double, 1, 1, Eigen::RowMajor>;\n        using JacobianMatrix = Eigen::Matrix<double, 1, 1, Eigen::RowMajor>;\n\n        JacobianMatrix jacobian;\n        ResidualVectorType solution;\n        solution << 0;\n\n        auto const update_residual = [&](ResidualVectorType& residual)\n        { residual[0] = yield_function(sigma); };\n\n        auto const update_jacobian = [&](JacobianMatrix& jacobian)\n        {\n            jacobian(0, 0) = -yield_function_derivative(sigma).transpose() *\n                             Ke * plastic_potential_derivative(sigma);\n        };\n\n        auto const update_solution = [&](ResidualVectorType const& increment)\n        {\n            solution += increment;\n            /*DBUG(\"analytical = {:g}\",\n                 Fs / (mat.Ks + mat.Kn * std::tan(mat.psi) * std::tan(mat.phi)))\n                 */\n            state.w_p = state.w_p_prev +\n                        solution[0] * plastic_potential_derivative(sigma);\n\n            sigma.noalias() = Ke * (w - w_prev - state.w_p + state.w_p_prev);\n\n            sigma.coeffRef(index_ns) *= logPenaltyDerivative(\n                aperture0, aperture, _penalty_aperture_cutoff);\n            sigma.noalias() += sigma_prev;\n        };\n\n        auto newton_solver =\n            NumLib::NewtonRaphson<decltype(linear_solver), JacobianMatrix,\n                                  decltype(update_jacobian), ResidualVectorType,\n                                  decltype(update_residual),\n                                  decltype(update_solution)>(\n                linear_solver, update_jacobian, update_residual,\n                update_solution, _nonlinear_solver_parameters);\n\n        auto const success_iterations = newton_solver.solve(jacobian);\n\n        if (!success_iterations)\n        {\n            throw NumLib::AssemblyException(\n                \"FractureModel/Coulomb local nonlinear solver didn't \"\n                \"converge.\");\n        }\n\n        // Solution containing lambda is not needed; w_p and sigma already\n        // up to date.\n    }\n\n    {  // Update material state shear yield function value.\n        double const Fs = yield_function(sigma);\n        material_state_variables.setShearYieldFunctionValue(Fs);\n    }\n\n    Ke(index_ns, index_ns) *=\n        logPenaltyDerivative(aperture0, aperture, _penalty_aperture_cutoff);\n    Eigen::RowVectorXd const A = yield_function_derivative(sigma).transpose() *\n                                 Ke /\n                                 (yield_function_derivative(sigma).transpose() *\n                                  Ke * plastic_potential_derivative(sigma));\n    Kep = Ke - Ke * plastic_potential_derivative(sigma) * A;\n}\n\ntemplate class Coulomb<2>;\ntemplate class Coulomb<3>;\n\n}  // namespace Coulomb\n}  // namespace Fracture\n}  // namespace MaterialLib\n", "meta": {"hexsha": "3a74a2d9e249d1334e8f29343627c026272d1f43", "size": 7709, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "MaterialLib/FractureModels/Coulomb.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": "MaterialLib/FractureModels/Coulomb.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": "MaterialLib/FractureModels/Coulomb.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": 33.8114035088, "max_line_length": 80, "alphanum_fraction": 0.6073420677, "num_tokens": 1823, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6893056040203135, "lm_q2_score": 0.5039061705290805, "lm_q1q2_score": 0.34734534724611094}}
{"text": "/*****************************************************************************\n*\n* Rokko: Integrated Interface for libraries of eigenvalue decomposition\n*\n* Copyright (C) 2017 by Rokko Developers https://github.com/t-sakashita/rokko\n*\n* Distributed under the Boost Software License, Version 1.0. (See accompanying\n* file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n*\n*****************************************************************************/\n\n#ifndef ROKKO_LAPACK_UNGQR_HPP\n#define ROKKO_LAPACK_UNGQR_HPP\n\n#include <complex>\n#ifdef I\n# undef I\n#endif\n#include <stdexcept>\n#include <boost/type_traits/is_same.hpp>\n#include <lapacke.h>\n#include <rokko/traits/value_t.hpp>\n#include \"complex_cast.hpp\"\n\nnamespace rokko {\nnamespace lapack {\n\nnamespace {\n\ntemplate<typename T> struct ungqr_dispatch;\n  \ntemplate<>\nstruct ungqr_dispatch<float> {\n  template<typename MATRIX, typename VECTOR>\n  static lapack_int ungqr(int matrix_layout, lapack_int m, lapack_int n, lapack_int k,\n                          MATRIX& a, VECTOR& tau) {\n    return LAPACKE_sorgqr(matrix_layout, m, n, k, storage(a), ld(a), storage(tau));\n  }\n  template<typename MATRIX, typename VECTOR>\n  static lapack_int ungqr(int matrix_layout, lapack_int m, lapack_int n, lapack_int k,\n                          MATRIX& a, VECTOR& tau, VECTOR& work) {\n    return LAPACKE_sorgqr(matrix_layout, m, n, k, storage(a), ld(a), storage(tau),\n                          storage(work), size(work));\n  }\n};\n\ntemplate<>\nstruct ungqr_dispatch<double> {\n  template<typename MATRIX, typename VECTOR>\n  static lapack_int ungqr(int matrix_layout, lapack_int m, lapack_int n, lapack_int k,\n                          MATRIX& a, VECTOR& tau) {\n    return LAPACKE_dorgqr(matrix_layout, m, n, k, storage(a), ld(a), storage(tau));\n  }\n  template<typename MATRIX, typename VECTOR>\n  static lapack_int ungqr(int matrix_layout, lapack_int m, lapack_int n, lapack_int k,\n                          MATRIX& a, VECTOR& tau, VECTOR& work) {\n    return LAPACKE_dorgqr(matrix_layout, m, n, k, storage(a), ld(a), storage(tau),\n                          storage(work), size(work));\n  }\n};\n\ntemplate<>\nstruct ungqr_dispatch<std::complex<float>> {\n  template<typename MATRIX, typename VECTOR>\n  static lapack_int ungqr(int matrix_layout, lapack_int m, lapack_int n, lapack_int k,\n                          MATRIX& a, VECTOR& tau) {\n    return LAPACKE_cungqr(matrix_layout, m, n, k, complex_cast(storage(a)), ld(a),\n                          complex_cast(storage(tau)));\n  }\n  template<typename MATRIX, typename VECTOR>\n  static lapack_int ungqr(int matrix_layout, lapack_int m, lapack_int n, lapack_int k,\n                          MATRIX& a, VECTOR& tau, VECTOR& work) {\n    return LAPACKE_cungqr(matrix_layout, m, n, k, complex_cast(storage(a)), ld(a),\n                          complex_cast(storage(tau)), complex_cast(storage(work)),\n                          size(work));\n  }\n};\n\ntemplate<>\nstruct ungqr_dispatch<std::complex<double>> {\n  template<typename MATRIX, typename VECTOR>\n  static lapack_int ungqr(int matrix_layout, lapack_int m, lapack_int n, lapack_int k,\n                          MATRIX& a, VECTOR& tau) {\n    return LAPACKE_zungqr(matrix_layout, m, n, k, complex_cast(storage(a)), ld(a),\n                          complex_cast(storage(tau)));\n  }\n  template<typename MATRIX, typename VECTOR>\n  static lapack_int ungqr(int matrix_layout, lapack_int m, lapack_int n, lapack_int k,\n                          MATRIX& a, VECTOR& tau, VECTOR& work) {\n    return LAPACKE_zungqr(matrix_layout, m, n, k, complex_cast(storage(a)), ld(a),\n                          complex_cast(storage(tau)), complex_cast(storage(work)),\n                          size(work));\n  }\n};\n\n}\n  \ntemplate<typename MATRIX, typename VECTOR>\nlapack_int ungqr(lapack_int k, MATRIX& a, VECTOR const& tau) {\n  static_assert(std::is_same<value_t<MATRIX>, value_t<VECTOR>>::value, \"\");\n  lapack_int m = rows(a);\n  lapack_int n = cols(a);\n  if (size(tau) != k)\n    throw std::invalid_argument(\"vector tau size mismatch\");\n  return ungqr_dispatch<value_t<MATRIX>>\n    ::ungqr((is_col_major(a) ? LAPACK_COL_MAJOR : LAPACK_ROW_MAJOR), m, n, k, a, tau);\n}\n\ntemplate<typename MATRIX, typename VECTOR>\nlapack_int ungqr(lapack_int k, MATRIX& a, VECTOR const& tau, VECTOR& work) {\n  static_assert(std::is_same<value_t<MATRIX>, value_t<VECTOR>>::value, \"\");\n  lapack_int m = rows(a);\n  lapack_int n = cols(a);\n  if (size(tau) != k)\n    throw std::invalid_argument(\"vector tau size mismatch\");\n  if (size(work) < std::max(1, n))\n    throw std::invalid_argument(\"vector work size mismatch\");\n  return ungqr_dispatch<value_t<MATRIX>>\n    ::ungqr((is_col_major(a) ? LAPACK_COL_MAJOR : LAPACK_ROW_MAJOR), m, n, k, a, tau, work);\n}\n\ntemplate<typename MATRIX, typename VECTOR>\nlapack_int orgqr(lapack_int k, MATRIX& a, VECTOR const& tau) {\n  return ungqr(k, a, tau);\n}\n  \ntemplate<typename MATRIX, typename VECTOR>\nlapack_int orgqr(lapack_int k, MATRIX& a, VECTOR const& tau, VECTOR& work) {\n  return ungqr(k, a, tau, work);\n};\n  \n} // end namespace lapack\n} // end namespace rokko\n\n#endif // ROKKO_LAPACK_UNGQR_HPP\n", "meta": {"hexsha": "4a55e9a21dd1768d575b5cbf11ac05b0e951abda", "size": 5124, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "rokko/lapack/ungqr.hpp", "max_stars_repo_name": "t-sakashita/rokko", "max_stars_repo_head_hexsha": "ebd49e1198c4ec9e7612ad4a9806d16a4ff0bdc9", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 16.0, "max_stars_repo_stars_event_min_datetime": "2015-01-31T18:57:48.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-18T19:04:49.000Z", "max_issues_repo_path": "rokko/lapack/ungqr.hpp", "max_issues_repo_name": "t-sakashita/rokko", "max_issues_repo_head_hexsha": "ebd49e1198c4ec9e7612ad4a9806d16a4ff0bdc9", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 514.0, "max_issues_repo_issues_event_min_datetime": "2015-02-05T14:56:54.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-25T09:29:52.000Z", "max_forks_repo_path": "rokko/lapack/ungqr.hpp", "max_forks_repo_name": "t-sakashita/rokko", "max_forks_repo_head_hexsha": "ebd49e1198c4ec9e7612ad4a9806d16a4ff0bdc9", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2015-06-16T04:22:23.000Z", "max_forks_repo_forks_event_max_datetime": "2019-06-01T07:10:01.000Z", "avg_line_length": 37.6764705882, "max_line_length": 92, "alphanum_fraction": 0.6473458236, "num_tokens": 1292, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6442251201477016, "lm_q2_score": 0.5389832206876841, "lm_q1q2_score": 0.34722653010511845}}
{"text": "#include <algorithm>\n#include <cstdint>\n#include <iostream>\n#include <stdexcept>\n#include <string>\n\n\n#ifndef CPPDEBUG /* Ubuntu's Boost does not provide binaries compatible with libstdc++'s debug mode so we just reduce functionality here */\n#include <boost/program_options.hpp>\n#endif\n\n#include \"boost_profile.cpp\"\n#include <libff/algebra/curves/edwards/edwards_pp.hpp>\n#include <libff/algebra/curves/alt_bn128/alt_bn128_pp.hpp>\n\n#include \"libiop/algebra/fields/gf64.hpp\"\n#include \"libiop/algebra/fields/gf128.hpp\"\n#include \"libiop/algebra/fields/gf192.hpp\"\n#include \"libiop/algebra/fields/gf256.hpp\"\n\n#include \"libiop/snark/ligero_snark.hpp\"\n#include \"libiop/bcs/bcs_common.hpp\"\n#include \"libiop/bcs/common_bcs_parameters.hpp\"\n#include \"libiop/relations/examples/r1cs_examples.hpp\"\n\n#ifndef CPPDEBUG\nbool process_prover_command_line(const int argc, const char** argv,\n                                 options &options, \n                                 float &height_width_ratio,\n                                 std::size_t &RS_extra_dimensions)\n{\n    namespace po = boost::program_options;\n\n    try\n    {\n        po::options_description desc = gen_options(options);\n        desc.add_options()\n             (\"height_width_ratio\", po::value<float>(&height_width_ratio)->default_value(0.1))\n             (\"RS_extra_dimensions\", po::value<std::size_t>(&RS_extra_dimensions)->default_value(2));\n\n        po::variables_map vm;\n        po::store(po::parse_command_line(argc, argv, desc), vm);\n\n        if (vm.count(\"help\"))\n        {\n            std::cout << desc << \"\\n\";\n            return false;\n        }\n\n        po::notify(vm);\n        options.hash_enum = static_cast<libiop::bcs_hash_type>(options.hash_enum_val);\n    }\n    catch(std::exception& e)\n    {\n        std::cerr << \"Error: \" << e.what() << \"\\n\";\n        return false;\n    }\n\n    return true;\n}\n#endif\n\nusing namespace libiop;\n\ntemplate<typename FieldT, typename hash_type>\nvoid instrument_ligero_snark(options &options,\n                             LDT_reducer_soundness_type ldt_reducer_soundness_type,\n                             const field_subset_type domain_type,\n                             float height_width_ratio, \n                             std::size_t RS_extra_dimensions)\n{\n    ligero_snark_parameters<FieldT, hash_type> parameters;\n    parameters.security_level_ = options.security_level;\n    parameters.LDT_reducer_soundness_type_ = ldt_reducer_soundness_type;\n    parameters.height_width_ratio_ = height_width_ratio;\n    parameters.RS_extra_dimensions_ = RS_extra_dimensions;\n    parameters.make_zk_ = options.make_zk;\n    parameters.domain_type_ = domain_type;\n    parameters.bcs_params_ = default_bcs_params<FieldT, hash_type>(options.hash_enum, options.security_level, options.log_n_min);\n    parameters.describe();\n\n    for (std::size_t log_n = options.log_n_min; log_n <= options.log_n_max; ++log_n)\n    {\n        print_separator();\n        const std::size_t n = 1ul << log_n;\n        /* k+1 needs to be a power of 2 (proof system artifact) and k <= n+2 (example generation artifact) so we just fix it to 15 here */\n        const std::size_t k = 15;\n        const std::size_t m = n - 1;\n        r1cs_example<FieldT> example = generate_r1cs_example<FieldT>(n, k, m);\n        parameters.bcs_params_ = default_bcs_params<FieldT, hash_type>(options.hash_enum, options.security_level, log_n);\n\n        enter_block(\"Check satisfiability of R1CS example\");\n        const bool is_satisfied = example.constraint_system_.is_satisfied(\n            example.primary_input_, example.auxiliary_input_);\n        assert(is_satisfied);\n        leave_block(\"Check satisfiability of R1CS example\");\n        printf(\"\\n\");\n        print_indent(); printf(\"* R1CS number of constraints: %zu\\n\", example.constraint_system_.num_constraints());\n        print_indent(); printf(\"* R1CS number of variables: %zu\\n\", example.constraint_system_.num_variables());\n        print_indent(); printf(\"* R1CS number of variables for primary input: %zu\\n\", example.primary_input_.size());\n        print_indent(); printf(\"* R1CS number of variables for auxiliary input: %zu\\n\", example.auxiliary_input_.size());\n        print_indent(); printf(\"* R1CS size of constraint system (bytes): %zu\\n\", example.constraint_system_.size_in_bytes());\n        print_indent(); printf(\"* R1CS size of primary input (bytes): %zu\\n\", example.primary_input_.size() * sizeof(FieldT));\n        print_indent(); printf(\"* R1CS size of auxiliary input (bytes): %zu\\n\", example.auxiliary_input_.size() * sizeof(FieldT));\n        printf(\"\\n\");\n        const ligero_snark_argument<FieldT, hash_type> proof = ligero_snark_prover<FieldT, hash_type>(\n            example.constraint_system_,\n            example.primary_input_,\n            example.auxiliary_input_,\n            parameters);\n\n        printf(\"\\n\");\n\n        print_indent(); printf(\"* Argument size in bytes (IOP): %zu\\n\", proof.IOP_size_in_bytes());\n        print_indent(); printf(\"* Argument size in bytes (BCS): %zu\\n\", proof.BCS_size_in_bytes());\n        print_indent(); printf(\"* Argument size in bytes (total): %zu\\n\", proof.size_in_bytes());\n\n        printf(\"\\nIf we were to remove pruning of authentication paths in BCS,\\n\"\n               \"the argument would have the following sizes:\\n\");\n        print_indent(); printf(\"* Argument size in bytes (BCS, no pruning): %zu\\n\", proof.BCS_size_in_bytes_without_pruning());\n        print_indent(); printf(\"* Argument size in bytes (total, no pruning): %zu\\n\", proof.size_in_bytes_without_pruning());\n\n        printf(\"\\n\");\n\n        const bool bit = ligero_snark_verifier<FieldT, hash_type>(\n            example.constraint_system_,\n            example.primary_input_,\n            proof,\n            parameters);\n\n        printf(\"\\n\\n\");\n\n        print_indent(); printf(\"* Verifier satisfied: %s\\n\", bit ? \"true\" : \"false\");\n    }\n}\n\nint main(int argc, const char * argv[])\n{\n\n    options default_vals;\n\n    float height_width_ratio = 0.1;\n    std::size_t RS_extra_dimensions = 2;\n\n#ifdef CPPDEBUG\n    /* set reasonable defaults */\n\n#else\n    if (!process_prover_command_line(argc, argv, default_vals, height_width_ratio, RS_extra_dimensions))\n    {\n        return 1;\n    }\n#endif\n\n    /** TODO: eventually get a string from program options, and then have a from string method in LDT reducer */\n    LDT_reducer_soundness_type ldt_reducer_soundness_type = LDT_reducer_soundness_type::proven;\n    if (default_vals.heuristic_ldt_reducer_soundness)\n    {\n        ldt_reducer_soundness_type = LDT_reducer_soundness_type::optimistic_heuristic;\n    }\n    start_profiling();\n\n    printf(\"Selected parameters:\\n\");\n    printf(\"- log_n_min = %zu\\n\", default_vals.log_n_min);\n    printf(\"- log_n_max = %zu\\n\", default_vals.log_n_max);\n    printf(\"- height_width_ratio = %f\\n\", height_width_ratio);\n    printf(\"- RS_extra_dimensions = %zu\\n\", RS_extra_dimensions);\n    printf(\"- security_level = %zu\\n\", default_vals.security_level);\n    printf(\"- LDT_reducer_soundness_type = %s\\n\", LDT_reducer_soundness_type_to_string(ldt_reducer_soundness_type));\n    printf(\"- field_size = %zu\\n\", default_vals.field_size);\n    printf(\"- make_zk = %d\\n\", default_vals.make_zk);\n    printf(\"- hash_enum = %s\\n\", bcs_hash_type_names[default_vals.hash_enum]);\n\n    if (default_vals.is_multiplicative)\n    {\n        switch (default_vals.field_size) {\n            case 181:\n                edwards_pp::init_public_params();\n                instrument_ligero_snark<edwards_Fr, binary_hash_digest>(\n                                        default_vals, ldt_reducer_soundness_type, multiplicative_coset_type,\n                                        height_width_ratio, RS_extra_dimensions);\n                break;\n            case 256:\n                libff::alt_bn128_pp::init_public_params();\n                if (default_vals.hash_enum == blake2b_type)\n                {\n                    instrument_ligero_snark<libff::alt_bn128_Fr, binary_hash_digest>(\n                                            default_vals, ldt_reducer_soundness_type, multiplicative_coset_type,\n                                            height_width_ratio, RS_extra_dimensions);\n                } \n                else\n                {\n                    instrument_ligero_snark<libff::alt_bn128_Fr, libff::alt_bn128_Fr>(\n                                            default_vals, ldt_reducer_soundness_type, multiplicative_coset_type,\n                                            height_width_ratio, RS_extra_dimensions);\n                }\n                break;\n            default:\n                throw std::invalid_argument(\"Field size not supported.\");\n        }\n    }\n    else\n    {\n        switch (default_vals.field_size)\n        {\n            case 64:\n                instrument_ligero_snark<gf64, binary_hash_digest>(\n                                        default_vals, ldt_reducer_soundness_type, affine_subspace_type,\n                                        height_width_ratio, RS_extra_dimensions);\n                break;\n            case 128:\n                instrument_ligero_snark<gf128, binary_hash_digest>(\n                                        default_vals, ldt_reducer_soundness_type, affine_subspace_type,\n                                        height_width_ratio, RS_extra_dimensions);\n                break;\n            case 192:\n                instrument_ligero_snark<gf192, binary_hash_digest>(\n                                        default_vals, ldt_reducer_soundness_type, affine_subspace_type,\n                                        height_width_ratio, RS_extra_dimensions);\n                break;\n            case 256:\n                instrument_ligero_snark<gf256, binary_hash_digest>(\n                                        default_vals, ldt_reducer_soundness_type, affine_subspace_type,\n                                        height_width_ratio, RS_extra_dimensions);\n                break;\n            default:\n                throw std::invalid_argument(\"Field size not supported.\");\n        }\n    }\n}\n", "meta": {"hexsha": "4ac601af14398a1aebf0f6761f5a659ef28a4065", "size": 10026, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libiop/profiling/instrument_ligero_snark.cpp", "max_stars_repo_name": "pwang00/libiop", "max_stars_repo_head_hexsha": "640a627f0e844caf88ac66cc2ab16f1ef3ea3283", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "libiop/profiling/instrument_ligero_snark.cpp", "max_issues_repo_name": "pwang00/libiop", "max_issues_repo_head_hexsha": "640a627f0e844caf88ac66cc2ab16f1ef3ea3283", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "libiop/profiling/instrument_ligero_snark.cpp", "max_forks_repo_name": "pwang00/libiop", "max_forks_repo_head_hexsha": "640a627f0e844caf88ac66cc2ab16f1ef3ea3283", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 43.4025974026, "max_line_length": 139, "alphanum_fraction": 0.626770397, "num_tokens": 2178, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6442251064863697, "lm_q2_score": 0.5389832206876841, "lm_q1q2_score": 0.34722652274188975}}
{"text": "#include <limits>\n#include <fstream>\n#include <vector>\n#include <Eigen/Core>\n#include \"pcl/point_types.h\"\n#include \"pcl/point_cloud.h\"\n#include \"pcl/io/pcd_io.h\"\n#include \"pcl/kdtree/kdtree_flann.h\"\n#include \"pcl/filters/passthrough.h\"\n#include \"pcl/filters/voxel_grid.h\"\n#include \"pcl/features/normal_3d.h\"\n#include \"pcl/features/fpfh.h\"\n#include \"pcl/registration/ia_ransac.h\"\n#include \"pcl/registration/icp.h\"\n#include <pcl/surface/mls.h>\n\n#include <NDTMatcherF2F.hh>\n#include <PointCloudUtils.hh>\n\nclass FeatureCloud\n{\npublic:\n    // A bit of shorthand\n    typedef pcl::PointCloud<pcl::PointXYZ> PointCloud;\n    typedef pcl::PointCloud<pcl::Normal> SurfaceNormals;\n    typedef pcl::PointCloud<pcl::FPFHSignature33> LocalFeatures;\n    //typedef pcl::KdTreeFLANN<pcl::PointXYZ> SearchMethod;\n\n\n    FeatureCloud () :\n        //search_method_xyz_ (new SearchMethod),\n        normal_radius_ (0.05),\n        feature_radius_ (0.05)\n    {\n    }\n\n    ~FeatureCloud () {}\n\n    // Process the given cloud\n    void\n    setInputCloud (PointCloud::Ptr xyz)\n    {\n        xyz_ = xyz;\n        processInput ();\n    }\n\n    // Load and process the cloud in the given PCD file\n    void\n    loadInputCloud (const std::string &pcd_file)\n    {\n        xyz_ = PointCloud::Ptr (new PointCloud);\n        pcl::io::loadPCDFile (pcd_file, *xyz_);\n        processInput ();\n    }\n\n    // Get a pointer to the cloud 3D points\n    PointCloud::Ptr\n    getPointCloud () const\n    {\n        return (xyz_);\n    }\n\n    // Get a pointer to the cloud of 3D surface normals\n    SurfaceNormals::Ptr\n    getSurfaceNormals () const\n    {\n        return (normals_);\n    }\n\n    // Get a pointer to the cloud of feature descriptors\n    LocalFeatures::Ptr\n    getLocalFeatures () const\n    {\n        return (features_);\n    }\n\nprotected:\n    // Compute the surface normals and local features\n    void\n    processInput ()\n    {\n        computeSurfaceNormals ();\n        computeLocalFeatures ();\n    }\n\n    // Compute the surface normals\n    void\n    computeSurfaceNormals ()\n    {\n        normals_ = SurfaceNormals::Ptr (new SurfaceNormals);\n\n        pcl::NormalEstimation<pcl::PointXYZ, pcl::Normal> norm_est;\n        norm_est.setInputCloud (xyz_);\n        norm_est.setSearchMethod (search_method_xyz_);\n        norm_est.setRadiusSearch (normal_radius_);\n        norm_est.compute (*normals_);\n    }\n\n    // Compute the local feature descriptors\n    void\n    computeLocalFeatures ()\n    {\n        features_ = LocalFeatures::Ptr (new LocalFeatures);\n\n        pcl::FPFHEstimation<pcl::PointXYZ, pcl::Normal, pcl::FPFHSignature33> fpfh_est;\n        fpfh_est.setInputCloud (xyz_);\n        fpfh_est.setInputNormals (normals_);\n        fpfh_est.setSearchMethod (search_method_xyz_);\n        fpfh_est.setRadiusSearch (feature_radius_);\n        fpfh_est.compute (*features_);\n    }\n\nprivate:\n    // Point cloud data\n    PointCloud::Ptr xyz_;\n    SurfaceNormals::Ptr normals_;\n    LocalFeatures::Ptr features_;\n    //SearchMethod::Ptr search_method_xyz_;\n    pcl::Feature<pcl::PointXYZ, pcl::Normal>::KdTreePtr search_method_xyz_;\n\n    // Parameters\n    float normal_radius_;\n    float feature_radius_;\n};\n\nclass TemplateRegistration\n{\npublic:\n\n    // A struct for storing alignment results\n\n    typedef Eigen::Transform<double,3,Eigen::Affine,Eigen::ColMajor> Result;\n\n    TemplateRegistration () :\n        min_sample_distance_ (0.05),\n        max_correspondence_distance_ (0.01*0.01),\n        nr_iterations_ (500)\n    {\n        // Intialize the parameters in the Sample Consensus Intial Alignment (SAC-IA) algorithm\n        sac_ia_.setMinSampleDistance (min_sample_distance_);\n        sac_ia_.setMaxCorrespondenceDistance (max_correspondence_distance_);\n        sac_ia_.setMaximumIterations (nr_iterations_);\n        sac_ia_.setNumberOfSamples (10);\n    }\n\n    ~TemplateRegistration () {}\n\n    // Set the given cloud as the target to which the templates will be aligned\n    void\n    setTargetCloud (FeatureCloud &target_cloud)\n    {\n        target_ = target_cloud;\n        sac_ia_.setInputTarget (target_cloud.getPointCloud ());\n        sac_ia_.setTargetFeatures (target_cloud.getLocalFeatures ());\n    }\n\n    // Align the moving cloud to the target specified by setTargetCloud ()\n    void\n    align (FeatureCloud &moving_cloud, TemplateRegistration::Result &result)\n    {\n        sac_ia_.setInputCloud (moving_cloud.getPointCloud ());\n        sac_ia_.setSourceFeatures (moving_cloud.getLocalFeatures ());\n\n        pcl::PointCloud<pcl::PointXYZ> registration_output;\n        sac_ia_.align (registration_output);\n\n        result = sac_ia_.getFinalTransformation ().cast<double>();\n    }\n\nprivate:\n    // A list of template clouds and the target to which they will be aligned\n    FeatureCloud target_;\n\n    // The Sample Consensus Initial Alignment (SAC-IA) registration routine and its parameters\n    pcl::SampleConsensusInitialAlignment<pcl::PointXYZ, pcl::PointXYZ, pcl::FPFHSignature33> sac_ia_;\n    float min_sample_distance_;\n    float max_correspondence_distance_;\n    float nr_iterations_;\n};\n\nbool matchICP(pcl::PointCloud<pcl::PointXYZ> &fixed,  pcl::PointCloud<pcl::PointXYZ> &moving,\n              Eigen::Transform<double,3,Eigen::Affine,Eigen::ColMajor> &Tout)\n{\n\n    pcl::PointCloud<pcl::PointXYZ>::Ptr cloud_in (new pcl::PointCloud<pcl::PointXYZ>);\n    pcl::PointCloud<pcl::PointXYZ>::Ptr cloud_out (new pcl::PointCloud<pcl::PointXYZ>);\n    pcl::PointCloud<pcl::PointXYZ>::ConstPtr f (new pcl::PointCloud<pcl::PointXYZ>(fixed) );\n    pcl::PointCloud<pcl::PointXYZ>::ConstPtr m (new pcl::PointCloud<pcl::PointXYZ>(moving) );\n\n    pcl::VoxelGrid<pcl::PointXYZ> gr1,gr2;\n    gr1.setLeafSize(0.1,0.1,0.1);\n    gr2.setLeafSize(0.1,0.1,0.1);\n\n    gr1.setInputCloud(m);\n    gr2.setInputCloud(f);\n\n    cloud_in->height = 1;\n    cloud_in->width = cloud_in->points.size();\n    cloud_out->height = 1;\n    cloud_out->width = cloud_out->points.size();\n    cloud_in->is_dense = false;\n    cloud_out->is_dense = false;\n\n    gr1.filter(*cloud_in);\n    gr2.filter(*cloud_out);\n    //*cloud_in = moving;\n    //*cloud_out= fixed;\n\n\n    pcl::IterativeClosestPoint<pcl::PointXYZ, pcl::PointXYZ> icp;\n\n    icp.setMaximumIterations(10000);\n    std::cout<<\"max itr are \"<<icp.getMaximumIterations()<<std::endl;\n    icp.setInputCloud(cloud_in);\n    icp.setInputTarget(cloud_out);\n\n    icp.setRANSACOutlierRejectionThreshold (2);\n    icp.setMaxCorrespondenceDistance(10);\n    icp.setTransformationEpsilon(0.00001);\n//    cout<<\"ransac outlier thersh   : \"<<icp.getRANSACOutlierRejectionThreshold ()<<endl;\n//    cout<<\"correspondance max dist : \"<<icp.getMaxCorrespondenceDistance() << endl;\n//    cout<<\"epsilon : \"<<icp.getTransformationEpsilon() << endl;\n    pcl::PointCloud<pcl::PointXYZ> Final;\n    icp.align(Final);\n\n\n//    std::cout << \"has converged:\" << icp.hasConverged() << \" score: \" <<\n//\ticp.getFitnessScore() << std::endl;\n//    std::cout << icp.getFinalTransformation() << std::endl;\n\n    //Eigen::Transform<float,3,Eigen::Affine,Eigen::ColMajor> tTemp;\n    Tout = (icp.getFinalTransformation()).cast<double>();\n\n    /*    char fname[50];\n        snprintf(fname,49,\"/home/tsv/ndt_tmp/c2_offset.wrl\");\n        FILE *fout = fopen(fname,\"w\");\n        fprintf(fout,\"#VRML V2.0 utf8\\n\");\n        lslgeneric::writeToVRML(fout,*cloud_out,Eigen::Vector3d(0,1,0));\n        lslgeneric::writeToVRML(fout,Final,Eigen::Vector3d(1,0,0));\n        lslgeneric::writeToVRML(fout,*cloud_in,Eigen::Vector3d(1,1,1));\n        fclose(fout);\n    */\n    return icp.hasConverged();\n\n}\n\n// Align two point clouds based on the features\nint\nmain (int argc, char **argv)\n{\n    if (argc < 3)\n    {\n        printf (\"No targets given!\\n\");\n        return (-1);\n    }\n\n    struct timeval tv_start, tv_end1, tv_end2;\n    TemplateRegistration::Result ToutFPFH, ToutICP, ToutNDT, Tout;\n\n    // Load the target cloud PCD file\n    pcl::PointCloud<pcl::PointXYZ>::Ptr cloudM (new pcl::PointCloud<pcl::PointXYZ>);\n    pcl::PointCloud<pcl::PointXYZ>::Ptr cloudF (new pcl::PointCloud<pcl::PointXYZ>);\n    pcl::PointCloud<pcl::PointXYZ> Final, Final0, Final1;\n\n    *cloudM = lslgeneric::readVRML(argv[1]);\n    *cloudF = lslgeneric::readVRML(argv[2]);\n\n    double __res[] = {0.2, 0.4, 1, 2};\n    std::vector<double> resolutions (__res, __res+sizeof(__res)/sizeof(double));\n    lslgeneric::NDTMatcherF2F matcherF2F(false, false, false, resolutions);\n    bool ret = matcherF2F.match(*cloudF,*cloudM,ToutNDT);\n    Final1 = lslgeneric::transformPointCloud(ToutNDT,*cloudM);\n\n    /* char f[50];\n     snprintf(f,49,\"/home/tsv/ndt_tmp/c2_offset.wrl\");\n     FILE *fo = fopen(f,\"w\");\n     fprintf(fo,\"#VRML V2.0 utf8\\n\");\n     lslgeneric::writeToVRML(fo,*cloudM,Eigen::Vector3d(1,0,0));\n     lslgeneric::writeToVRML(fo,Final1,Eigen::Vector3d(0,1,1));\n     lslgeneric::writeToVRML(fo,*cloudF,Eigen::Vector3d(1,1,1));\n     fclose(fo);\n     return (0);\n     */\n    //start timing\n    gettimeofday(&tv_start,NULL);\n\n    pcl::VoxelGrid<pcl::PointXYZ> gr1,gr2;\n    gr1.setLeafSize(0.05,0.05,0.05);\n    gr2.setLeafSize(0.05,0.05,0.05);\n\n    gr1.setInputCloud(cloudM);\n    gr2.setInputCloud(cloudF);\n\n    gr1.filter(*cloudM);\n    gr2.filter(*cloudF);\n\n    cloudM->height = 1;\n    cloudM->width = cloudM->points.size();\n    cloudF->height = 1;\n    cloudF->width = cloudF->points.size();\n    cloudM->is_dense = false;\n    cloudF->is_dense = false;\n\n    // Assign to the target FeatureCloud\n    FeatureCloud target_cloud, moving_cloud;\n    target_cloud.setInputCloud (cloudF);\n    moving_cloud.setInputCloud (cloudM);\n\n    TemplateRegistration templateReg;\n    templateReg.setTargetCloud (target_cloud);\n\n    // Find the best template alignment\n    templateReg.align(moving_cloud,ToutFPFH);\n    //stop timing1\n    gettimeofday(&tv_end1,NULL);\n\n    std::cout<<\"ToutFPFH: \"<<ToutFPFH.translation().transpose()<<\"\\n\"<<ToutFPFH.rotation()<<std::endl;\n    Final0 = lslgeneric::transformPointCloud(ToutFPFH,*cloudM);\n\n    bool converged = matchICP(*cloudF,Final0,ToutICP);\n    Final = lslgeneric::transformPointCloud(ToutICP,Final0);\n    //stop timing2\n    gettimeofday(&tv_end2,NULL);\n\n\n    Tout = ToutFPFH*(ToutNDT.inverse());\n    std::cout<<\"FPFH\\n\";\n    std::cout<<\"E translation \"<<Tout.translation().transpose()\n             <<\" (norm) \"<<Tout.translation().norm()<<std::endl;\n    std::cout<<\"E rotation \"<<Tout.rotation().eulerAngles(0,1,2).transpose()\n             <<\" (norm) \"<<Tout.rotation().eulerAngles(0,1,2).norm()<<std::endl;\n    std::cout<<\" TIME: \"<<\n             (tv_end1.tv_sec-tv_start.tv_sec)*1000.+(tv_end1.tv_usec-tv_start.tv_usec)/1000.<<std::endl;\n\n    Tout = ToutICP*ToutFPFH*(ToutNDT.inverse());\n    std::cout<<\"FPFH+ICP\\n\";\n    std::cout<<\"E translation \"<<Tout.translation().transpose()\n             <<\" (norm) \"<<Tout.translation().norm()<<std::endl;\n    std::cout<<\"E rotation \"<<Tout.rotation().eulerAngles(0,1,2).transpose()\n             <<\" (norm) \"<<Tout.rotation().eulerAngles(0,1,2).norm()<<std::endl;\n    std::cout<<\" TIME: \"<<\n             (tv_end2.tv_sec-tv_start.tv_sec)*1000.+(tv_end2.tv_usec-tv_start.tv_usec)/1000.<<std::endl;\n\n    char fname[50];\n    snprintf(fname,49,\"/home/tsv/ndt_tmp/c2_offset.wrl\");\n    FILE *fout = fopen(fname,\"w\");\n    fprintf(fout,\"#VRML V2.0 utf8\\n\");\n    lslgeneric::writeToVRML(fout,*cloudM,Eigen::Vector3d(1,0,0));\n    lslgeneric::writeToVRML(fout,Final0,Eigen::Vector3d(0,0,1));\n    lslgeneric::writeToVRML(fout,Final1,Eigen::Vector3d(0,1,1));\n    lslgeneric::writeToVRML(fout,Final,Eigen::Vector3d(0,1,0));\n    lslgeneric::writeToVRML(fout,*cloudF,Eigen::Vector3d(1,1,1));\n    fclose(fout);\n\n\n\n    return (0);\n}\n", "meta": {"hexsha": "72ef9b626119449f15f38c015866bcc1cf12aab6", "size": 11569, "ext": "cc", "lang": "C++", "max_stars_repo_path": "perception_oru-port-kinetic/ndt_registration/test/feature_registration.cc", "max_stars_repo_name": "lllray/ndt-loam", "max_stars_repo_head_hexsha": "331867941e0764b40e1a980dd85d2174f861e9c8", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-11-14T08:21:13.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-14T08:21:13.000Z", "max_issues_repo_path": "perception_oru-port-kinetic/ndt_registration/test/feature_registration.cc", "max_issues_repo_name": "lllray/ndt-loam", "max_issues_repo_head_hexsha": "331867941e0764b40e1a980dd85d2174f861e9c8", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-07-28T04:47:56.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-28T04:47:56.000Z", "max_forks_repo_path": "perception_oru-port-kinetic/ndt_registration/test/feature_registration.cc", "max_forks_repo_name": "lllray/ndt-loam", "max_forks_repo_head_hexsha": "331867941e0764b40e1a980dd85d2174f861e9c8", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-12-18T11:25:53.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-19T12:59:59.000Z", "avg_line_length": 32.2256267409, "max_line_length": 104, "alphanum_fraction": 0.665312473, "num_tokens": 3167, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.658417500561683, "lm_q2_score": 0.5273165233795672, "lm_q1q2_score": 0.34719442732845096}}
{"text": "#ifndef UTILITY_H\n#define UTILITY_H\n\n// system information\n#include <unistd.h>\n#include <pwd.h>\n\n//! Eigen\n#include <Eigen/Dense>\n\n//! ROS\n#include <tf/tf.h>\n#include <tf/transform_broadcaster.h>\n#include <tf/transform_listener.h>\n#include <tf2_ros/transform_listener.h>\n#include <tf2_geometry_msgs/tf2_geometry_msgs.h>\n#include <tf2_ros/static_transform_broadcaster.h>\n#include <visualization_msgs/Marker.h>\n#include <std_msgs/ColorRGBA.h>\n#include <geometry_msgs/Point.h>\n\n\nnamespace bluerov_detection_tracking\n{\nclass Utility\n{\npublic:\n    inline std::string getUserName(){\n        struct passwd* pwd;\n        uid_t userid;\n        userid = getuid();\n        pwd = getpwuid(userid);\n        // cout<<pwd->pw_name<<endl;\n        return pwd->pw_name;\n    }\n\n    /*\n    # Intrinsic camera matrix for the raw (distorted) images.\n    #     [fx  0 cx]\n    # K = [ 0 fy cy]\n    #     [ 0  0  1]\n    # Projects 3D points in the camera coordinate frame to 2D pixel\n    # coordinates using the focal lengths (fx, fy) and principal point\n    # (cx, cy).\n    float64[9]  K # 3x3 row-major matrix\n    */\n    inline Eigen::Vector3f project3dTo2d(Eigen::Vector3f p3, Eigen::Matrix3f K){\n        // 2dpoint = K*3dpoint\n        Eigen::Vector3f p2;\n        p2 = K*p3;\n        // p2(0) = p2(0) - p3(2)*K(0,2);\n        // p2(1) = p2(1) - p3(2)*K(1,2);\n        p2(0) = p2(0)/(p3(2)-1);\n        p2(1) = p2(1)/(p3(2)-1);\n\n        return p2;\n    }\n\n    /*\n    # Projection/camera matrix\n    #     [fx'  0  cx' Tx]\n    # P = [ 0  fy' cy' Ty]\n    #     [ 0   0   1   0]\n    # By convention, this matrix specifies the intrinsic (camera) matrix\n    #  of the processed (rectified) image. That is, the left 3x3 portion\n    #  is the normal camera intrinsic matrix for the rectified image.\n    # It projects 3D points in the camera coordinate frame to 2D pixel\n    #  coordinates using the focal lengths (fx', fy') and principal point\n    #  (cx', cy') - these may differ from the values in K.\n    # For monocular cameras, Tx = Ty = 0. Normally, monocular cameras will\n    #  also have R = the identity and P[1:3,1:3] = K.\n    # For a stereo pair, the fourth column [Tx Ty 0]' is related to the\n    #  position of the optical center of the second camera in the first\n    #  camera's frame. We assume Tz = 0 so both cameras are in the same\n    #  stereo image plane. The first camera always has Tx = Ty = 0. For\n    #  the right (second) camera of a horizontal stereo pair, Ty = 0 and\n    #  Tx = -fx' * B, where B is the baseline between the cameras.\n    # Given a 3D point [X Y Z]', the projection (x, y) of the point onto\n    #  the rectified image is given by:\n    #  [u v w]' = P * [X Y Z 1]'\n    #         x = u / w\n    #         y = v / w\n    #  This holds for both images of a stereo pair.\n    float64[12] P # 3x4 row-major matrix\n    */\n    inline Eigen::Vector3f project3dTo2d(Eigen::Vector3f p3, Eigen::MatrixXf P){\n        Eigen::Vector4f p4;\n        p4(0) = p3(0);\n        p4(1) = p3(1);\n        p4(2) = p3(2);\n        p4(3) = 1;\n\n        Eigen::Vector3f p2;\n        p2 = P*p4;\n\n        p2(0) = p2(0)/p2(2);\n        p2(1) = p2(1)/p2(2);\n        // p2(0) = p2(0)/(p2(2)-0.9);\n        // p2(1) = p2(1)/(p2(2)-0.9);\n\n        return p2;\n    }    \n\n\n    /*\n        说明：此方法存在计算误差，暂时停用！\n        图像坐标投影到相机坐标，通过深度值计算，适合RGBD相机\n        输入：图像坐标\n             3*3内参矩阵\n             深度归一化scale\n             归一化后的深度值\n        输出：三维空间坐标\n\n        依据小孔投影模型原理：\n        # u = fx*x/z + cx;\n        # v = fy*y/z + cy;\n    */\n    inline Eigen::Vector3f project2dTo3d(Eigen::Vector2f p2, Eigen::Matrix3f k, float depthScale, float depth){\n       Eigen::Vector3f p3;\n       p3(0) = (p2(0) - k(0,2))/k(0,0);\n       p3(1) = (p2(1) - k(1,2))/k(1,1);\n       p3(2) = depth/depthScale;\n\n       return p3;\n   }\n\n\n    /*\n        说明：只要知道准确的相机内参和准确的点距离，那么此方法计算无误差，已经经过验证了\n        图像坐标投影到相机坐标，通过实际距离计算（没有归一化尺度）\n        输入：图像坐标\n             3*3内参矩阵\n             空间点在相机坐标系下到相机坐标原点的距离（实际深度值，非归一化深度值！）\n        输出：三维空间坐标\n\n        原理：\n        p_camera = p_pixel * range * K_inverse\n    */\n    inline Eigen::Vector3f project2dTo3d(Eigen::Vector2f p2, Eigen::Matrix3f k, float range){\n       Eigen::Vector3f p3;\n       Eigen::Vector3f p2_normalized;\n       p2_normalized(0) = p2(0);\n       p2_normalized(1) = p2(1);\n       p2_normalized(2) = 1.0;\n\n       p3 = k.inverse() * range * p2_normalized;\n\n       return p3;\n   }\n\n\n    /*\n        发布两个坐标系之间的变换关系TF\n        输入：父坐标系名称\n             子坐标系名称\n             变换位姿\n        输出：无\n    */\n    void sendTF(std::string fatherFrame, \n                std::string childFrame,\n                geometry_msgs::PoseStamped pose);\n\n\n    /*\n        目标位置转换到NED坐标系\n        输入：当前位置\n             目标初始化位置\n        输出：NED位置坐标\n    */\n    void toNED( geometry_msgs::PoseStamped poseIn,\n                Eigen::Vector3f initialPose,\n                geometry_msgs::PoseStamped& poseOut); // 输出必须以引用传递，函数内部修改变量值才能保存到全局变量中！\n\n\n\n    /*\n        目标位置转换到locked_pose坐标系\n        输入：当前位置\n             目标初始化位置\n        输出：locked_pose位置坐标\n    */\n    void toLockedPoseFrame( geometry_msgs::PoseStamped poseIn,\n                            Eigen::Vector3f initialPose,\n                            geometry_msgs::PoseStamped& poseOut); // 输出必须以引用传递，函数内部修改变量值才能保存到全局变量中！\n\n\n\n    // void publish3DConvexHullMarkers(   std::string frame,\n    //                                             std::vector<geometry_msgs::Point> vertex,\n    //                                             ros::Publisher publisher);\n\n\n    /*\n        发布三维凸包markers到rviz显示\n        输入：markers的坐标系\n             颜色\n             线条粗细\n             保存了构成三维凸包的所有边的vector\n             ROS发布器\n        输出：\n    */\n    void publish3DConvexHullMarkers(std::string frame,\n                                    std_msgs::ColorRGBA color,\n                                    double width,    \n                                    std::vector<std::vector<geometry_msgs::Point>> vertex,\n                                    ros::Publisher publisher);\n\n\n\n    /*\n        获取球型marker\n        输入：marker所属坐标系\n             marker颜色、透明度、尺寸\n             marker位置\n        输出：球型marker\n    */\n    void sphereMarker(  std_msgs::Header &header,\n                        Eigen::VectorXf &CAS,\n                        Eigen::VectorXd position,\n                        visualization_msgs::Marker &marker);\n\n\n    // void Utility::sphereMarkerArray(bool &isCenter,\n    //                                 std_msgs::Header &header, \n    //                                 VectorXd &c_a_s, \n    //                                 std::vector<DetectedObject> &objList,\n    //                                 visualization_msgs::MarkerArray &markerArray);\n\n\n\n    /*\n        发布轨迹到RVIZ中显示\n        输入：轨迹所属坐标系\n             轨迹颜色\n             轨迹点\n             轨迹发布器\n        输出：轨迹，类型为visualization_msgs::Marker\n    */\n    void publishPath(   std::string frameId, \n                        std_msgs::ColorRGBA colorRGBA,\n                        geometry_msgs::Point point,\n                        ros::Publisher publisher,\n                        visualization_msgs::Marker& path); // path必须以引用方式传入，在压入位置点时才能保存到全局path变量中！\n\n\n\n};\n\n}\n#endif", "meta": {"hexsha": "9479f3eb544fe8a83329a42e49083af01de6849a", "size": 7090, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "pcl/include/Utility.hpp", "max_stars_repo_name": "lukechencqu/bluerov_zed_tracking", "max_stars_repo_head_hexsha": "75d87cfc183839615fada0731724cf0a230a0970", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-07-21T12:21:26.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-02T00:57:02.000Z", "max_issues_repo_path": "pcl/include/Utility.hpp", "max_issues_repo_name": "lukechencqu/bluerov_zed_tracking", "max_issues_repo_head_hexsha": "75d87cfc183839615fada0731724cf0a230a0970", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pcl/include/Utility.hpp", "max_forks_repo_name": "lukechencqu/bluerov_zed_tracking", "max_forks_repo_head_hexsha": "75d87cfc183839615fada0731724cf0a230a0970", "max_forks_repo_licenses": ["Apache-2.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.36, "max_line_length": 111, "alphanum_fraction": 0.5339915374, "num_tokens": 2375, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.658417500561683, "lm_q2_score": 0.5273165233795671, "lm_q1q2_score": 0.3471944273284509}}
{"text": "/* Authors: Joerg Frohne, Texas A&M University and                */\n/*                        University of Siegen, 2011, 2012        */\n/*          Wolfgang Bangerth, Texas A&M University, 2012         */\n\n/*    $Id: step-41.cc 27657 2012-11-21 13:19:08Z bangerth $        */\n/*                                                                */\n/*    Copyright (C) 2011-2012 by the deal.II authors */\n/*                                                                */\n/*    This file is subject to QPL and may not be  distributed     */\n/*    without copyright and license information. Please refer     */\n/*    to the file deal.II/doc/license.html for the  text  and     */\n/*    further information on this license.                        */\n\n// @sect3{Include files}\n\n// As usual, at the beginning we include all the header files we need in\n// here. With the exception of the various files that provide interfaces to\n// the Trilinos library, there are no surprises:\n#include <deal.II/base/quadrature_lib.h>\n#include <deal.II/base/function.h>\n#include <deal.II/base/index_set.h>\n\n#include <deal.II/lac/vector.h>\n#include <deal.II/lac/full_matrix.h>\n#include <deal.II/lac/compressed_sparsity_pattern.h>\n#include <deal.II/lac/solver_cg.h>\n#include <deal.II/lac/trilinos_sparse_matrix.h>\n#include <deal.II/lac/trilinos_vector.h>\n#include <deal.II/lac/trilinos_precondition.h>\n\n#include <deal.II/grid/tria.h>\n#include <deal.II/grid/grid_generator.h>\n#include <deal.II/grid/tria_accessor.h>\n#include <deal.II/grid/tria_iterator.h>\n\n#include <deal.II/fe/fe_q.h>\n#include <deal.II/fe/fe_values.h>\n\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\n#include <deal.II/numerics/vector_tools.h>\n#include <deal.II/numerics/data_out.h>\n\n#include <fstream>\n#include <iostream>\n#include <list>\n\n\nnamespace Step41\n{\n  using namespace dealii;\n\n  // @sect3{The <code>ObstacleProblem</code> class template}\n\n  // This class supplies all function and variables needed to describe the\n  // obstacle problem. It is close to what we had to do in step-4, and so\n  // relatively simple. The only real new components are the\n  // update_solution_and_constraints function that computes the active set and\n  // a number of variables that are necessary to describe the original\n  // (unconstrained) form of the linear system\n  // (<code>complete_system_matrix</code> and\n  // <code>complete_system_rhs</code>) as well as the active set itself and\n  // the diagonal of the mass matrix $B$ used in scaling Lagrange multipliers\n  // in the active set formulation. The rest is as in step-4:\n  template <int dim>\n  class ObstacleProblem\n  {\n  public:\n    ObstacleProblem ();\n    void run ();\n\n  private:\n    void make_grid ();\n    void setup_system();\n    void assemble_system ();\n    void assemble_mass_matrix_diagonal (TrilinosWrappers::SparseMatrix &mass_matrix);\n    void update_solution_and_constraints ();\n    void solve ();\n    void output_results (const unsigned int iteration) const;\n\n    Triangulation<dim>   triangulation;\n    FE_Q<dim>            fe;\n    DoFHandler<dim>      dof_handler;\n    ConstraintMatrix     constraints;\n    IndexSet             active_set;\n\n    TrilinosWrappers::SparseMatrix system_matrix;\n    TrilinosWrappers::SparseMatrix complete_system_matrix;\n\n    TrilinosWrappers::Vector       solution;\n    TrilinosWrappers::Vector       system_rhs;\n    TrilinosWrappers::Vector       complete_system_rhs;\n    TrilinosWrappers::Vector       diagonal_of_mass_matrix;\n    TrilinosWrappers::Vector       contact_force;\n  };\n\n\n  // @sect3{Right hand side, boundary values, and the obstacle}\n\n  // In the following, we define classes that describe the right hand side\n  // function, the Dirichlet boundary values, and the height of the obstacle\n  // as a function of $\\mathbf x$. In all three cases, we derive these classes\n  // from Function@<dim@>, although in the case of <code>RightHandSide</code>\n  // and <code>Obstacle</code> this is more out of convention than necessity\n  // since we never pass such objects to the library. In any case, the\n  // definition of the right hand side and boundary values classes is obvious\n  // given our choice of $f=-10$, $u|_{\\partial\\Omega}=0$:\n  template <int dim>\n  class RightHandSide : public Function<dim>\n  {\n  public:\n    RightHandSide () : Function<dim>() {}\n\n    virtual double value (const Point<dim>   &p,\n                          const unsigned int  component = 0) const;\n  };\n\n  template <int dim>\n  double RightHandSide<dim>::value (const Point<dim> &p,\n                                    const unsigned int component) const\n  {\n    Assert (component == 0, ExcNotImplemented());\n\n    return -10;\n  }\n\n\n\n  template <int dim>\n  class BoundaryValues : public Function<dim>\n  {\n  public:\n    BoundaryValues () : Function<dim>() {}\n\n    virtual double value (const Point<dim>   &p,\n                          const unsigned int  component = 0) const;\n  };\n\n  template <int dim>\n  double BoundaryValues<dim>::value (const Point<dim> &p,\n                                     const unsigned int component) const\n  {\n    Assert (component == 0, ExcNotImplemented());\n\n    return 0;\n  }\n\n\n\n  // We describe the obstacle function by a cascaded barrier (think: stair\n  // steps):\n  template <int dim>\n  class Obstacle : public Function<dim>\n  {\n  public:\n    Obstacle () : Function<dim>() {}\n\n    virtual double value (const Point<dim>   &p,\n                          const unsigned int  component = 0) const;\n  };\n\n  template <int dim>\n  double Obstacle<dim>::value (const Point<dim> &p,\n                               const unsigned int component) const\n  {\n    Assert (component == 0, ExcNotImplemented());\n\n    if (p (0) < -0.5)\n      return -0.2;\n    else if (p (0) >= -0.5 && p (0) < 0.0)\n      return -0.4;\n    else if (p (0) >= 0.0 && p (0) < 0.5)\n      return -0.6;\n    else\n      return -0.8;\n  }\n\n\n\n  // @sect3{Implementation of the <code>ObstacleProblem</code> class}\n\n\n  // @sect4{ObstacleProblem::ObstacleProblem}\n\n  // To everyone who has taken a look at the first few tutorial programs, the\n  // constructor is completely obvious:\n  template <int dim>\n  ObstacleProblem<dim>::ObstacleProblem ()\n    :\n    fe (1),\n    dof_handler (triangulation)\n  {}\n\n\n  // @sect4{ObstacleProblem::make_grid}\n\n  // We solve our obstacle problem on the square $[-1,1]\\times [-1,1]$ in\n  // 2D. This function therefore just sets up one of the simplest possible\n  // meshes.\n  template <int dim>\n  void ObstacleProblem<dim>::make_grid ()\n  {\n    GridGenerator::hyper_cube (triangulation, -1, 1);\n    triangulation.refine_global (7);\n\n    std::cout << \"Number of active cells: \"\n              << triangulation.n_active_cells()\n              << std::endl\n              << \"Total number of cells: \"\n              << triangulation.n_cells()\n              << std::endl;\n  }\n\n\n  // @sect4{ObstacleProblem::setup_system}\n\n  // In this first function of note, we set up the degrees of freedom handler,\n  // resize vectors and matrices, and deal with the constraints. Initially,\n  // the constraints are, of course, only given by boundary values, so we\n  // interpolate them towards the top of the function.\n  template <int dim>\n  void ObstacleProblem<dim>::setup_system ()\n  {\n    dof_handler.distribute_dofs (fe);\n    active_set.set_size (dof_handler.n_dofs());\n\n    std::cout << \"Number of degrees of freedom: \"\n              << dof_handler.n_dofs()\n              << std::endl\n              << std::endl;\n\n    VectorTools::interpolate_boundary_values (dof_handler,\n                                              0,\n                                              BoundaryValues<dim>(),\n                                              constraints);\n    constraints.close ();\n\n    CompressedSparsityPattern c_sparsity(dof_handler.n_dofs());\n    DoFTools::make_sparsity_pattern (dof_handler,\n                                     c_sparsity,\n                                     constraints,\n                                     false);\n\n    system_matrix.reinit (c_sparsity);\n    complete_system_matrix.reinit (c_sparsity);\n\n    solution.reinit (dof_handler.n_dofs());\n    system_rhs.reinit (dof_handler.n_dofs());\n    complete_system_rhs.reinit (dof_handler.n_dofs());\n    contact_force.reinit (dof_handler.n_dofs());\n\n    // The only other thing to do here is to compute the factors in the $B$\n    // matrix which is used to scale the residual. As discussed in the\n    // introduction, we'll use a little trick to make this mass matrix\n    // diagonal, and in the following then first compute all of this as a\n    // matrix and then extract the diagonal elements for later use:\n    TrilinosWrappers::SparseMatrix mass_matrix;\n    mass_matrix.reinit (c_sparsity);\n    assemble_mass_matrix_diagonal (mass_matrix);\n    diagonal_of_mass_matrix.reinit (dof_handler.n_dofs());\n    for (unsigned int j=0; j<solution.size (); j++)\n      diagonal_of_mass_matrix (j) = mass_matrix.diag_element (j);\n  }\n\n\n  // @sect4{ObstacleProblem::assemble_system}\n\n  // This function at once assembles the system matrix and right-hand-side and\n  // applied the constraints (both due to the active set as well as from\n  // boundary values) to our system. Otherwise, it is functionally equivalent\n  // to the corresponding function in, for example, step-4.\n  template <int dim>\n  void ObstacleProblem<dim>::assemble_system ()\n  {\n    std::cout << \"   Assembling system...\" << std::endl;\n\n    system_matrix = 0;\n    system_rhs    = 0;\n\n    const QGauss<dim>         quadrature_formula(fe.degree+1);\n    const RightHandSide<dim>  right_hand_side;\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    TrilinosWrappers::Vector  cell_rhs (dofs_per_cell);\n\n    std::vector<unsigned int> local_dof_indices (dofs_per_cell);\n\n    typename DoFHandler<dim>::active_cell_iterator\n    cell = dof_handler.begin_active(),\n    endc = dof_handler.end();\n\n    for (; cell!=endc; ++cell)\n      {\n        fe_values.reinit (cell);\n        cell_matrix = 0;\n        cell_rhs = 0;\n\n        for (unsigned int q_point=0; q_point<n_q_points; ++q_point)\n          for (unsigned int i=0; i<dofs_per_cell; ++i)\n            {\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) += (fe_values.shape_value (i, q_point) *\n                              right_hand_side.value (fe_values.quadrature_point (q_point)) *\n                              fe_values.JxW (q_point));\n            }\n\n        cell->get_dof_indices (local_dof_indices);\n\n        constraints.distribute_local_to_global (cell_matrix,\n                                                cell_rhs,\n                                                local_dof_indices,\n                                                system_matrix,\n                                                system_rhs,\n                                                true);\n      }\n  }\n\n\n\n  // @sect4{ObstacleProblem::assemble_mass_matrix_diagonal}\n\n  // The next function is used in the computation of the diagonal mass matrix\n  // $B$ used to scale variables in the active set method. As discussed in the\n  // introduction, we get the mass matrix to be diagonal by choosing the\n  // trapezoidal rule for quadrature. Doing so we don't really need the triple\n  // loop over quadrature points, indices $i$ and indices $j$ any more and\n  // can, instead, just use a double loop. The rest of the function is obvious\n  // given what we have discussed in many of the previous tutorial programs.\n  //\n  // Note that at the time this function is called, the constraints object\n  // only contains boundary value constraints; we therefore do not have to pay\n  // attention in the last copy-local-to-global step to preserve the values of\n  // matrix entries that may later on be constrained by the active set.\n  //\n  // Note also that the trick with the trapezoidal rule only works if we have\n  // in fact $Q_1$ elements. For higher order elements, one would need to use\n  // a quadrature formula that has quadrature points at all the support points\n  // of the finite element. Constructing such a quadrature formula isn't\n  // really difficult, but not the point here, and so we simply assert at the\n  // top of the function that our implicit assumption about the finite element\n  // is in fact satisfied.\n  template <int dim>\n  void\n  ObstacleProblem<dim>::\n  assemble_mass_matrix_diagonal (TrilinosWrappers::SparseMatrix &mass_matrix)\n  {\n    Assert (fe.degree == 1, ExcNotImplemented());\n\n    const QTrapez<dim>        quadrature_formula;\n    FEValues<dim>             fe_values (fe,\n                                         quadrature_formula,\n                                         update_values   |\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    std::vector<unsigned int> local_dof_indices (dofs_per_cell);\n\n    typename DoFHandler<dim>::active_cell_iterator\n    cell = dof_handler.begin_active(),\n    endc = dof_handler.end();\n\n    for (; cell!=endc; ++cell)\n      {\n        fe_values.reinit (cell);\n        cell_matrix = 0;\n\n        for (unsigned int q_point=0; q_point<n_q_points; ++q_point)\n          for (unsigned int i=0; i<dofs_per_cell; ++i)\n            cell_matrix(i,i) += (fe_values.shape_value (i, q_point) *\n                                 fe_values.shape_value (i, q_point) *\n                                 fe_values.JxW (q_point));\n\n        cell->get_dof_indices (local_dof_indices);\n\n        constraints.distribute_local_to_global (cell_matrix,\n                                                local_dof_indices,\n                                                mass_matrix);\n      }\n  }\n\n\n  // @sect4{ObstacleProblem::update_solution_and_constraints}\n\n  // In a sense, this is the central function of this program.  It updates the\n  // active set of constrained degrees of freedom as discussed in the\n  // introduction and computes a ConstraintMatrix object from it that can then\n  // be used to eliminate constrained degrees of freedom from the solution of\n  // the next iteration. At the same time we set the constrained degrees of\n  // freedom of the solution to the correct value, namely the height of the\n  // obstacle.\n  //\n  // Fundamentally, the function is rather simple: We have to loop over all\n  // degrees of freedom and check the sign of the function $\\Lambda^k_i +\n  // c([BU^k]_i - G_i) = \\Lambda^k_i + cB_i(U^k_i - [g_h]_i)$ because in our\n  // case $G_i = B_i[g_h]_i$. To this end, we use the formula given in the\n  // introduction by which we can compute the Lagrange multiplier as the\n  // residual of the original linear system (given via the variables\n  // <code>complete_system_matrix</code> and <code>complete_system_rhs</code>.\n  // At the top of this function, we compute this residual using a function\n  // that is part of the matrix classes.\n  template <int dim>\n  void\n  ObstacleProblem<dim>::update_solution_and_constraints ()\n  {\n    std::cout << \"   Updating active set...\" << std::endl;\n\n    const double penalty_parameter = 100.0;\n\n    TrilinosWrappers::Vector lambda (dof_handler.n_dofs());\n    complete_system_matrix.residual (lambda,\n                                     solution, complete_system_rhs);\n    contact_force.ratio (lambda, diagonal_of_mass_matrix);\n    contact_force *= -1;\n\n    // The next step is to reset the active set and constraints objects and to\n    // start the loop over all degrees of freedom. This is made slightly more\n    // complicated by the fact that we can't just loop over all elements of\n    // the solution vector since there is no way for us then to find out what\n    // location a DoF is associated with; however, we need this location to\n    // test whether the displacement of a DoF is larger or smaller than the\n    // height of the obstacle at this location.\n    //\n    // We work around this by looping over all cells and DoFs defined on each\n    // of these cells. We use here that the displacement is described using a\n    // $Q_1$ function for which degrees of freedom are always located on the\n    // vertices of the cell; thus, we can get the index of each degree of\n    // freedom and its location by asking the vertex for this information. On\n    // the other hand, this clearly wouldn't work for higher order elements,\n    // and so we add an assertion that makes sure that we only deal with\n    // elements for which all degrees of freedom are located in vertices to\n    // avoid tripping ourselves with non-functional code in case someone wants\n    // to play with increasing the polynomial degree of the solution.\n    //\n    // The price to pay for having to loop over cells rather than DoFs is that\n    // we may encounter some degrees of freedom more than once, namely each\n    // time we visit one of the cells adjacent to a given vertex. We will\n    // therefore have to keep track which vertices we have already touched and\n    // which we haven't so far. We do so by using an array of flags\n    // <code>dof_touched</code>:\n    constraints.clear();\n    active_set.clear ();\n\n    const Obstacle<dim> obstacle;\n    std::vector<bool>   dof_touched (dof_handler.n_dofs(), false);\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      for (unsigned int v=0; v<GeometryInfo<dim>::vertices_per_cell; ++v)\n        {\n          Assert (dof_handler.get_fe().dofs_per_cell ==\n                  GeometryInfo<dim>::vertices_per_cell,\n                  ExcNotImplemented());\n\n          const unsigned int dof_index = cell->vertex_dof_index (v,0);\n\n          if (dof_touched[dof_index] == false)\n            dof_touched[dof_index] = true;\n          else\n            continue;\n\n          // Now that we know that we haven't touched this DoF yet, let's get\n          // the value of the displacement function there as well as the value\n          // of the obstacle function and use this to decide whether the\n          // current DoF belongs to the active set. For that we use the\n          // function given above and in the introduction.\n          //\n          // If we decide that the DoF should be part of the active set, we\n          // add its index to the active set, introduce a nonhomogeneous\n          // equality constraint in the ConstraintMatrix object, and reset the\n          // solution value to the height of the obstacle. Finally, the\n          // residual of the non-contact part of the system serves as an\n          // additional control (the residual equals the remaining,\n          // unaccounted forces, and should be zero outside the contact zone),\n          // so we zero out the components of the residual vector (i.e., the\n          // Lagrange multiplier lambda) that correspond to the area where the\n          // body is in contact; at the end of the loop over all cells, the\n          // residual will therefore only consist of the residual in the\n          // non-contact zone. We output the norm of this residual along with\n          // the size of the active set after the loop.\n          const double obstacle_value = obstacle.value (cell->vertex(v));\n          const double solution_value = solution (dof_index);\n\n          if (lambda (dof_index) +\n              penalty_parameter *\n              diagonal_of_mass_matrix(dof_index) *\n              (solution_value - obstacle_value)\n              <\n              0)\n            {\n              active_set.add_index (dof_index);\n              constraints.add_line (dof_index);\n              constraints.set_inhomogeneity (dof_index, obstacle_value);\n\n              solution (dof_index) = obstacle_value;\n\n              lambda (dof_index) = 0;\n            }\n        }\n    std::cout << \"      Size of active set: \" << active_set.n_elements()\n              << std::endl;\n\n    std::cout << \"   Residual of the non-contact part of the system: \"\n              << lambda.l2_norm()\n              << std::endl;\n\n    // In a final step, we add to the set of constraints on DoFs we have so\n    // far from the active set those that result from Dirichlet boundary\n    // values, and close the constraints object:\n    VectorTools::interpolate_boundary_values (dof_handler,\n                                              0,\n                                              BoundaryValues<dim>(),\n                                              constraints);\n    constraints.close ();\n  }\n\n  // @sect4{ObstacleProblem::solve}\n\n  // There is nothing to say really about the solve function. In the context\n  // of a Newton method, we are not typically interested in very high accuracy\n  // (why ask for a highly accurate solution of a linear problem that we know\n  // only gives us an approximation of the solution of the nonlinear problem),\n  // and so we use the ReductionControl class that stops iterations when\n  // either an absolute tolerance is reached (for which we choose $10^{-12}$)\n  // or when the residual is reduced by a certain factor (here, $10^{-3}$).\n  template <int dim>\n  void ObstacleProblem<dim>::solve ()\n  {\n    std::cout << \"   Solving system...\" << std::endl;\n\n    ReductionControl                    reduction_control (100, 1e-12, 1e-3);\n    SolverCG<TrilinosWrappers::Vector>  solver (reduction_control);\n    TrilinosWrappers::PreconditionAMG   precondition;\n    precondition.initialize (system_matrix);\n\n    solver.solve (system_matrix, solution, system_rhs, precondition);\n    constraints.distribute (solution);\n\n    std::cout << \"      Error: \" << reduction_control.initial_value()\n              << \" -> \" << reduction_control.last_value()\n              << \" in \"\n              <<  reduction_control.last_step()\n              << \" CG iterations.\"\n              << std::endl;\n  }\n\n\n  // @sect4{ObstacleProblem::output_results}\n\n  // We use the vtk-format for the output.  The file contains the displacement\n  // and a numerical represenation of the active set. The function looks\n  // standard but note that we can add an IndexSet object to the DataOut\n  // object in exactly the same way as a regular solution vector: it is simply\n  // interpreted as a function that is either zero (when a degree of freedom\n  // is not part of the IndexSet) or one (if it is).\n  template <int dim>\n  void ObstacleProblem<dim>::output_results (const unsigned int iteration) const\n  {\n    std::cout << \"   Writing graphical output...\" << std::endl;\n\n    DataOut<dim> data_out;\n\n    data_out.attach_dof_handler (dof_handler);\n    data_out.add_data_vector (solution, \"displacement\");\n    data_out.add_data_vector (active_set, \"active_set\");\n    data_out.add_data_vector (contact_force, \"lambda\");\n\n    data_out.build_patches ();\n\n    std::ofstream output_vtk ((std::string(\"output_\") +\n                               Utilities::int_to_string (iteration, 3) +\n                               \".vtk\").c_str ());\n    data_out.write_vtk (output_vtk);\n  }\n\n\n\n  // @sect4{ObstacleProblem::run}\n\n  // This is the function which has the top-level control over everything.  It\n  // is not very long, and in fact rather straightforward: in every iteration\n  // of the active set method, we assemble the linear system, solve it, update\n  // the active set and project the solution back to the feasible set, and\n  // then output the results. The iteration is terminated whenever the active\n  // set has not changed in the previous iteration.\n  //\n  // The only trickier part is that we have to save the linear system (i.e.,\n  // the matrix and right hand side) after assembling it in the first\n  // iteration. The reason is that this is the only step where we can access\n  // the linear system as built without any of the contact constraints\n  // active. We need this to compute the residual of the solution at other\n  // iterations, but in other iterations that linear system we form has the\n  // rows and columns that correspond to constrained degrees of freedom\n  // eliminated, and so we can no longer access the full residual of the\n  // original equation.\n  template <int dim>\n  void ObstacleProblem<dim>::run ()\n  {\n    make_grid();\n    setup_system ();\n\n    IndexSet active_set_old (active_set);\n    for (unsigned int iteration=0; iteration<=solution.size (); ++iteration)\n      {\n        std::cout << \"Newton iteration \" << iteration << std::endl;\n\n        assemble_system ();\n\n        if (iteration == 0)\n          {\n            complete_system_matrix.copy_from (system_matrix);\n            complete_system_rhs = system_rhs;\n          }\n\n        solve ();\n        update_solution_and_constraints ();\n        output_results (iteration);\n\n        if (active_set == active_set_old)\n          break;\n\n        active_set_old = active_set;\n\n        std::cout << std::endl;\n      }\n  }\n}\n\n\n// @sect3{The <code>main</code> function}\n\n// And this is the main function. It follows the pattern of all other main\n// functions. The call to initialize MPI exists because the Trilinos library\n// upon which we build our linear solvers in this program requires it.\nint main (int argc, char *argv[])\n{\n  try\n    {\n      using namespace dealii;\n      using namespace Step41;\n\n      deallog.depth_console (0);\n\n      Utilities::MPI::MPI_InitFinalize mpi_initialization (argc, argv);\n\n      ObstacleProblem<2> obstacle_problem;\n      obstacle_problem.run ();\n    }\n  catch (std::exception &exc)\n    {\n      std::cerr << std::endl << std::endl\n                << \"----------------------------------------------------\"\n                << std::endl;\n      std::cerr << \"Exception on processing: \" << std::endl\n                << exc.what() << std::endl\n                << \"Aborting!\" << std::endl\n                << \"----------------------------------------------------\"\n                << std::endl;\n\n      return 1;\n    }\n  catch (...)\n    {\n      std::cerr << std::endl << std::endl\n                << \"----------------------------------------------------\"\n                << std::endl;\n      std::cerr << \"Unknown exception!\" << std::endl\n                << \"Aborting!\" << std::endl\n                << \"----------------------------------------------------\"\n                << std::endl;\n      return 1;\n    }\n\n  return 0;\n}\n", "meta": {"hexsha": "d911fc3ff9b4636e96e1373dfd866ba053e65500", "size": 26939, "ext": "cc", "lang": "C++", "max_stars_repo_path": "MHD/examples/step-41/step-41.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-41/step-41.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-41/step-41.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": 38.8170028818, "max_line_length": 92, "alphanum_fraction": 0.6258213, "num_tokens": 6153, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5273165233795672, "lm_q2_score": 0.6584174938590245, "lm_q1q2_score": 0.3471944237940284}}
{"text": "/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */\n\n/*\n Copyright (C) 2015 Peter Caspers\n Copyright (C) 2015 Roland Lichters\n\n This file is part of QuantLib, a free-software/open-source library\n for financial quantitative analysts and developers - http://quantlib.org/\n\n QuantLib is free software: you can redistribute it and/or modify it\n under the terms of the QuantLib license.  You should have received a\n copy of the license along with this program; if not, please email\n <quantlib-dev@lists.sf.net>. The license is also available online at\n <http://quantlib.org/license.shtml>.\n\n This program is distributed in the hope that it will be useful, but WITHOUT\n ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n FOR A PARTICULAR PURPOSE.  See the license for more details.\n*/\n\n#include <ql/experimental/models/betaeta.hpp>\n#include <ql/quotes/simplequote.hpp>\n#include <ql/time/schedule.hpp>\n#include <ql/math/integrals/gausslobattointegral.hpp>\n#include <ql/math/integrals/segmentintegral.hpp>\n#include <ql/math/interpolations/linearinterpolation.hpp>\n\n#include <boost/make_shared.hpp>\n\nnamespace QuantLib {\n\nBetaEta::BetaEta(const Handle<YieldTermStructure> &termStructure,\n                 const std::vector<Date> &volstepdates,\n                 const std::vector<Real> &volatilities, const Real reversion,\n                 const Real beta, const Real eta)\n    : TermStructureConsistentModel(termStructure), CalibratedModel(4),\n      reversion_(arguments_[0]), sigma_(arguments_[1]), pBeta_(arguments_[2]),\n      pEta_(arguments_[3]), volstepdates_(volstepdates) {\n    QL_REQUIRE(!termStructure.empty(),\n               \"no yield term structure given (empty handle)\");\n    // integrator and fall back\n    integrator_ = boost::make_shared<GaussLobattoIntegral>(100000, 1E-8, 1E-8);\n    integrator2_ = boost::make_shared<SegmentIntegral>(1000);\n    volatilities_.resize(volatilities.size());\n    for (Size i = 0; i < volatilities.size(); ++i)\n        volatilities_[i] =\n            Handle<Quote>(boost::make_shared<SimpleQuote>(volatilities[i]));\n    reversions_.resize(1);\n    reversions_[0] = Handle<Quote>(boost::make_shared<SimpleQuote>(reversion));\n    beta_ = Handle<Quote>(boost::make_shared<SimpleQuote>(beta));\n    eta_ = Handle<Quote>(boost::make_shared<SimpleQuote>(eta));\n    initialize();\n}\n\nBetaEta::BetaEta(const Handle<YieldTermStructure> &termStructure,\n                 const std::vector<Date> &volstepdates,\n                 const std::vector<Real> &volatilities,\n                 const std::vector<Real> &reversions, const Real beta,\n                 const Real eta)\n    : TermStructureConsistentModel(termStructure), CalibratedModel(4),\n      reversion_(arguments_[0]), sigma_(arguments_[1]), pBeta_(arguments_[2]),\n      pEta_(arguments_[3]), volstepdates_(volstepdates) {\n    QL_REQUIRE(!termStructure.empty(),\n               \"no yield term structure given (empty handle)\");\n    volatilities_.resize(volatilities.size());\n    for (Size i = 0; i < volatilities.size(); ++i)\n        volatilities_[i] =\n            Handle<Quote>(boost::make_shared<SimpleQuote>(volatilities[i]));\n    reversions_.resize(reversions.size());\n    for (Size i = 0; i < reversions_.size(); ++i)\n        reversions_[i] =\n            Handle<Quote>(boost::make_shared<SimpleQuote>(reversions[i]));\n    beta_ = Handle<Quote>(boost::make_shared<SimpleQuote>(beta));\n    eta_ = Handle<Quote>(boost::make_shared<SimpleQuote>(eta));\n    initialize();\n}\n\nBetaEta::BetaEta(const Handle<YieldTermStructure> &termStructure,\n                 const std::vector<Date> &volstepdates,\n                 const std::vector<Handle<Quote> > &volatilities,\n                 const Handle<Quote> reversion, const Handle<Quote> beta,\n                 const Handle<Quote> eta)\n    : TermStructureConsistentModel(termStructure), CalibratedModel(4),\n      reversion_(arguments_[0]), sigma_(arguments_[1]), pBeta_(arguments_[2]),\n      pEta_(arguments_[3]), volatilities_(volatilities),\n      reversions_(std::vector<Handle<Quote> >(1, reversion)),\n      volstepdates_(volstepdates) {\n\n    QL_REQUIRE(!termStructure.empty(),\n               \"no yield term structure given (empty handle)\");\n    initialize();\n}\n\nBetaEta::BetaEta(const Handle<YieldTermStructure> &termStructure,\n                 const std::vector<Date> &volstepdates,\n                 const std::vector<Handle<Quote> > &volatilities,\n                 const std::vector<Handle<Quote> > &reversions,\n                 const Handle<Quote> beta, const Handle<Quote> eta)\n    : TermStructureConsistentModel(termStructure), CalibratedModel(4),\n      reversion_(arguments_[0]), sigma_(arguments_[1]), pBeta_(arguments_[2]),\n      pEta_(arguments_[3]), volatilities_(volatilities),\n      reversions_(reversions), volstepdates_(volstepdates) {\n\n    QL_REQUIRE(!termStructure.empty(),\n               \"no yield term structure given (empty handle)\");\n    initialize();\n}\n\nvoid BetaEta::updateTimes() const {\n    volsteptimes_.clear();\n    int j = 0;\n    for (std::vector<Date>::const_iterator i = volstepdates_.begin();\n         i != volstepdates_.end(); ++i, ++j) {\n        volsteptimes_.push_back(termStructure()->timeFromReference(*i));\n        volsteptimesArray_[j] = volsteptimes_[j];\n        if (j == 0)\n            QL_REQUIRE(volsteptimes_[0] > 0.0, \"volsteptimes must be positive (\"\n                                                   << volsteptimes_[0] << \")\");\n        else\n            QL_REQUIRE(volsteptimes_[j] > volsteptimes_[j - 1],\n                       \"volsteptimes must be strictly increasing (\"\n                           << volsteptimes_[j - 1] << \"@\" << (j - 1) << \", \"\n                           << volsteptimes_[j] << \"@\" << j << \")\");\n    }\n}\n\nvoid BetaEta::updateReversion() {\n    for (Size i = 0; i < reversion_.size(); i++) {\n        reversion_.setParam(i, reversions_[i]->value());\n    }\n    update();\n}\n\nvoid BetaEta::updateVolatility() {\n    for (Size i = 0; i < sigma_.size(); i++) {\n        sigma_.setParam(i, volatilities_[i]->value());\n    }\n    update();\n}\n\nvoid BetaEta::updateBeta() {\n    pBeta_.setParam(0, beta_->value());\n    betaLink_ = beta_->value();\n    update();\n}\n\nvoid BetaEta::updateEta() {\n    pEta_.setParam(0, eta_->value());\n    etaLink_ = eta_->value();\n    update();\n}\n\nvoid BetaEta::initialize() {\n    useTabulation(true);\n    volsteptimesArray_ = Array(volstepdates_.size());\n    updateTimes();\n    QL_REQUIRE(volatilities_.size() == volsteptimes_.size() + 1,\n               \"there must be n+1 volatilities (\"\n                   << volatilities_.size() << \") for n volatility step times (\"\n                   << volsteptimes_.size() << \")\");\n    sigma_ = PiecewiseConstantParameter(volsteptimes_, NoConstraint());\n\n    QL_REQUIRE(reversions_.size() == 1 ||\n                   reversions_.size() == volsteptimes_.size() + 1,\n               \"there must be 1 or n+1 reversions (\"\n                   << reversions_.size() << \") for n volatility step times (\"\n                   << volsteptimes_.size() << \")\");\n    if (reversions_.size() == 1) {\n        reversion_ = ConstantParameter(reversions_[0]->value(), NoConstraint());\n    } else {\n        reversion_ = PiecewiseConstantParameter(volsteptimes_, NoConstraint());\n    }\n\n    pBeta_ = ConstantParameter(beta_->value(), NoConstraint());\n    pEta_ = ConstantParameter(eta_->value(), NoConstraint());\n    betaLink_ = beta_->value();\n    etaLink_ = eta_->value();\n\n    for (Size i = 0; i < sigma_.size(); i++) {\n        sigma_.setParam(i, volatilities_[i]->value());\n    }\n    for (Size i = 0; i < reversion_.size(); i++) {\n        reversion_.setParam(i, reversions_[i]->value());\n    }\n\n    registerWith(termStructure());\n\n    volatilityObserver_ = boost::make_shared<VolatilityObserver>(this);\n    reversionObserver_ = boost::make_shared<ReversionObserver>(this);\n    betaObserver_ = boost::make_shared<BetaObserver>(this);\n    etaObserver_ = boost::make_shared<EtaObserver>(this);\n\n    for (Size i = 0; i < reversions_.size(); ++i)\n        reversionObserver_->registerWith(reversions_[i]);\n    for (Size i = 0; i < volatilities_.size(); ++i)\n        volatilityObserver_->registerWith(volatilities_[i]);\n\n    betaObserver_->registerWith(beta_);\n    etaObserver_->registerWith(eta_);\n\n    core_ = boost::make_shared<BetaEtaCore>(volsteptimesArray_, sigma_.params(),\n                                            reversion_.params(), betaLink_,\n                                            etaLink_);\n}\n\nconst Real BetaEta::numeraire(const Time t, const Real x,\n                              const Handle<YieldTermStructure> &yts) const {\n    Real d =\n        yts.empty() ? this->termStructure()->discount(t) : yts->discount(t);\n    Real result =\n        std::exp(core_->lambda(t) * x + core_->M(0, 0, t, useTabulation_)) / d;\n    return result;\n}\n\nconst Real BetaEta::zerobond(const Time T, const Time t, const Real x,\n                             const Handle<YieldTermStructure> &yts) const {\n    Real d = yts.empty()\n                 ? this->termStructure()->discount(T) /\n                       this->termStructure()->discount(t)\n                 : yts->discount(T) / yts->discount(t);\n\n    Real result = d * std::exp(-(core_->lambda(T) - core_->lambda(t)) * x -\n                               (core_->M(0, 0, T, useTabulation_) -\n                                core_->M(0, 0, t, useTabulation_)) +\n                               core_->M(t, x, T, useTabulation_));\n    return result;\n}\n\nconst Real BetaEta::forwardRate(const Date &fixing, const Date &referenceDate,\n                                const Real x,\n                                boost::shared_ptr<IborIndex> iborIdx) const {\n\n    QL_REQUIRE(iborIdx != NULL, \"no ibor index given\");\n\n    calculate();\n\n    if (fixing <= (evaluationDate_ + (enforcesTodaysHistoricFixings_ ? 0 : -1)))\n        return iborIdx->fixing(fixing);\n\n    Handle<YieldTermStructure> yts =\n        iborIdx->forwardingTermStructure(); // might be empty, then use\n                                            // model curve\n\n    Date valueDate = iborIdx->valueDate(fixing);\n    Date endDate = iborIdx->fixingCalendar().advance(\n        valueDate, iborIdx->tenor(), iborIdx->businessDayConvention(),\n        iborIdx->endOfMonth());\n    // FIXME Here we should use the calculation date calendar ?\n    Real dcf = iborIdx->dayCounter().yearFraction(valueDate, endDate);\n\n    return (zerobond(valueDate, referenceDate, x, yts) -\n            zerobond(endDate, referenceDate, x, yts)) /\n           (dcf * zerobond(endDate, referenceDate, x, yts));\n}\n\nconst Real BetaEta::swapRate(const Date &fixing, const Period &tenor,\n                             const Date &referenceDate, const Real x,\n                             boost::shared_ptr<SwapIndex> swapIdx) const {\n\n    QL_REQUIRE(swapIdx != NULL, \"no swap index given\");\n\n    calculate();\n\n    if (fixing <= (evaluationDate_ + (enforcesTodaysHistoricFixings_ ? 0 : -1)))\n        return swapIdx->fixing(fixing);\n\n    Handle<YieldTermStructure> ytsf =\n        swapIdx->iborIndex()->forwardingTermStructure();\n    Handle<YieldTermStructure> ytsd =\n        swapIdx->discountingTermStructure(); // either might be empty, then\n                                             // use model curve\n\n    Schedule sched, floatSched;\n\n    boost::shared_ptr<VanillaSwap> underlying =\n        underlyingSwap(swapIdx, fixing, tenor);\n\n    sched = underlying->fixedSchedule();\n\n    boost::shared_ptr<OvernightIndexedSwapIndex> oisIdx =\n        boost::dynamic_pointer_cast<OvernightIndexedSwapIndex>(swapIdx);\n    if (oisIdx != NULL) {\n        floatSched = sched;\n    } else {\n        floatSched = underlying->floatingSchedule();\n    }\n\n    // should be fine for overnightindexed swap indices as well\n    Real annuity = swapAnnuity(fixing, tenor, referenceDate, x, swapIdx);\n    Rate floatleg = 0.0;\n    if (ytsf.empty() && ytsd.empty()) { // simple 100-formula can be used\n                                        // only in one curve setup\n        floatleg =\n            (zerobond(sched.dates().front(), referenceDate, x,\n                      Handle<YieldTermStructure>()) -\n             zerobond(sched.calendar().adjust(sched.dates().back(),\n                                              underlying->paymentConvention()),\n                      referenceDate, x, Handle<YieldTermStructure>()));\n    } else {\n        for (Size i = 1; i < floatSched.size(); i++) {\n            floatleg +=\n                (zerobond(floatSched[i - 1], referenceDate, x, ytsf) /\n                     zerobond(floatSched[i], referenceDate, x, ytsf) -\n                 1.0) *\n                zerobond(floatSched.calendar().adjust(\n                             floatSched[i], underlying->paymentConvention()),\n                         referenceDate, x, ytsd);\n        }\n    }\n    return floatleg / annuity;\n}\n\nconst Real BetaEta::swapAnnuity(const Date &fixing, const Period &tenor,\n                                const Date &referenceDate, const Real x,\n                                boost::shared_ptr<SwapIndex> swapIdx) const {\n\n    QL_REQUIRE(swapIdx != NULL, \"no swap index given\");\n\n    calculate();\n\n    Handle<YieldTermStructure> ytsd =\n        swapIdx->discountingTermStructure(); // might be empty, then use\n                                             // model curve\n\n    boost::shared_ptr<VanillaSwap> underlying =\n        underlyingSwap(swapIdx, fixing, tenor);\n\n    Schedule sched = underlying->fixedSchedule();\n\n    Real annuity = 0.0;\n    for (unsigned int j = 1; j < sched.size(); j++) {\n        annuity += zerobond(sched.calendar().adjust(\n                                sched.date(j), underlying->paymentConvention()),\n                            referenceDate, x, ytsd) *\n                   swapIdx->dayCounter().yearFraction(sched.date(j - 1),\n                                                      sched.date(j));\n    }\n    return annuity;\n}\n\nconst Disposable<Array> BetaEta::xGrid(const Real stdDevs, const int gridPoints,\n                                       const Real T, const Real t,\n                                       const Real x) const {\n\n    Array result(2 * gridPoints + 1, 0.0);\n\n    // approximate standard deviation for x\n    Real s = std::sqrt(core_->tau(t, T));\n\n    Real h = stdDevs * s / (static_cast<Real>(gridPoints));\n\n    // ensure that only grid points greater or equal the barrier are generated\n    // do this by scaling the points left from x linearly\n    std::vector<Real> hx, hy;\n    Real leftX = x - h * static_cast<Real>(gridPoints);\n    hx.push_back(leftX);\n    hx.push_back(x);\n    hy.push_back(std::max(leftX, -1.0 / beta_->value()));\n    hy.push_back(x);\n\n    LinearInterpolation l(hx.begin(), hx.end(), hy.begin());\n\n    for (int j = -gridPoints; j <= gridPoints; ++j) {\n        Real tmp = x + h * (static_cast<Real>(j));\n        result[j + gridPoints] =\n            (j < 0 && gridPoints > 0 && h > 0.0) ? l(tmp) : tmp;\n    }\n\n    return result;\n}\n\n} // namespace QuantLib\n", "meta": {"hexsha": "46005ad3fb1bf5b57c75859beb94f82e6bd528ce", "size": 14958, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ql/experimental/models/betaeta.cpp", "max_stars_repo_name": "universe1987/QuantLib", "max_stars_repo_head_hexsha": "bbb0145aff285853755b9f6ed013f53a41163acb", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2016-03-28T15:05:23.000Z", "max_stars_repo_stars_event_max_datetime": "2020-02-17T23:05:57.000Z", "max_issues_repo_path": "ql/experimental/models/betaeta.cpp", "max_issues_repo_name": "universe1987/QuantLib", "max_issues_repo_head_hexsha": "bbb0145aff285853755b9f6ed013f53a41163acb", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2015-02-02T20:32:43.000Z", "max_issues_repo_issues_event_max_datetime": "2015-02-02T20:32:43.000Z", "max_forks_repo_path": "ql/experimental/models/betaeta.cpp", "max_forks_repo_name": "pcaspers/quantlib", "max_forks_repo_head_hexsha": "bbb0145aff285853755b9f6ed013f53a41163acb", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2015-01-26T14:50:24.000Z", "max_forks_repo_forks_event_max_datetime": "2015-10-23T07:41:30.000Z", "avg_line_length": 40.1018766756, "max_line_length": 80, "alphanum_fraction": 0.6024869635, "num_tokens": 3702, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7279754607093178, "lm_q2_score": 0.476579651063676, "lm_q1q2_score": 0.34693829104776547}}
{"text": "/// \\file   nuslam.cpp\n/// \\brief  A package for Extended Kalman Filter Slam implementation.\n\n#include \"nuslam/nuslam.hpp\"\n#include \"rigid2d/diff_drive.hpp\"\n#include \"rigid2d/rigid2d.hpp\"\n\n#include <armadillo>\n#include <cmath>\n#include <iostream>\n#include <sstream>\n#include <utility>\n#include <vector>\n\nnamespace nuslam\n{\n  /********** Measurement struct member functions **********/\n\n  /// Create zero-measurement\n  Measurement::Measurement()\n  {\n    r = 0.0;\n    phi = 0.0;\n  }\n\n  /// Create a measurement with r,phi inputs\n  Measurement::Measurement(double x_, double y_, int id_)\n  {\n    r = std::sqrt(pow(x_, 2) + pow(y_, 2));\n    phi = rigid2d::normalize_angle(atan2(y_, x_));\n    id = id_;\n  }\n\n  /// Create a measurement vector\n  arma::mat Measurement::compute_z()\n  {\n    arma::mat z = arma::mat(2, 1);\n    z(0, 0) = r;\n    z(1, 0) = rigid2d::normalize_angle(phi);\n\n    return z;\n  }\n\n  /********** EKF class member functions **********/\n\n  /// Initialize the combined state vector.\n  /// Start with a guess for the robot state (0, 0, 0) and zero e map state.\n  EKF::EKF()\n  {\n    q_t.fill(0.0);\n\n    xi_predict.fill(0.0);\n    cov_predict.fill(0.0);\n\n    Q_mat.fill(0.0);\n    Q_mat(0, 0) = 1e-3;\n    Q_mat(1, 1) = 1e-3;\n    Q_mat(2, 2) = 1e-3;\n\n    R_mat.fill(0.0);\n    R_mat(0, 0) = 1e-2;\n    R_mat(1, 1) = 1e-2;\n  }\n\n  /// Check if the measured landmark exists in the landmark dictionary.\n  bool EKF::check_landmarks(const int landmark_id)\n  {\n    if (id2landmark.count(landmark_id) == 1)\n    {\n      return false;\n    }\n    return true;\n  }\n\n  /// Update the landmarks matrix and landmark covariance.\n  void EKF::add_new_measurement(const Measurement &meas)\n  {\n    if (check_landmarks(meas.id))\n    {\n      update_landmark(meas);\n    }\n  }\n\n  /// Update the landmarks matrix and landmark covariance.\n  void EKF::update_landmark(const Measurement &meas)\n  {\n\n    // Update id2landmark dictionary with new measurement\n    id2landmark.insert(std::make_pair(meas.id, xi_predict.n_rows - 3));\n\n    // Update covariance matrix\n    cov_predict = update_matrix_size(cov_predict);\n    cov_predict(cov_predict.n_rows - 1, cov_predict.n_cols - 1) =\n        10000.0; // Infinity\n    cov_predict(cov_predict.n_rows - 2, cov_predict.n_cols - 2) =\n        10000.0; // Infinity\n\n    // Update process noise for the robot motion model Q (expanding to fill the\n    // whole state)\n    Q_mat = update_matrix_size(Q_mat);\n\n    // Update map state matrix\n    double m_x =\n        xi_predict(1, 0) +\n        meas.r * cos(rigid2d::normalize_angle(meas.phi + xi_predict(0, 0)));\n    double m_y =\n        xi_predict(2, 0) +\n        meas.r * sin(rigid2d::normalize_angle(meas.phi + xi_predict(0, 0)));\n\n    arma::mat m_addition = arma::mat(2, 1);\n    m_addition(0, 0) = m_x;\n    m_addition(1, 0) = m_y;\n\n    xi_predict = std::move(arma::join_cols(xi_predict, m_addition));\n    // m_t = std::move(arma::join_cols(m_t, m_addition));\n  }\n\n  /// Get the state transition ξ_t (q_t, m_t) and the map’s movement with respect\n  /// to the state ξ.\n  arma::mat EKF::get_new_state(const Twist2D &twist)\n  {\n    arma::mat T_wbp = arma::mat(3, 1);\n    arma::mat w_t = (arma::mat(3, 1)).fill(0.0);\n\n    // If the rotational velocity is zero (twist.thetadot = 0)\n    if (rigid2d::almost_equal(twist.thetadot, 0.0, 1.0e-6))\n    {\n      T_wbp(0, 0) = 0.0;\n      T_wbp(1, 0) = twist.xdot * cos(xi_predict(0, 0));\n      T_wbp(2, 0) = twist.xdot * sin(xi_predict(0, 0));\n    }\n\n    // If the rotational velocity is not zero (twist.thetadot != 0)\n    else\n    {\n      double dx_dtheta = twist.xdot / twist.thetadot;\n      T_wbp(0, 0) = twist.thetadot;\n      T_wbp(1, 0) = -dx_dtheta * sin(xi_predict(0, 0)) +\n                    dx_dtheta * sin(xi_predict(0, 0) + twist.thetadot);\n      T_wbp(2, 0) = dx_dtheta * cos(xi_predict(0, 0)) -\n                    dx_dtheta * cos(xi_predict(0, 0) + twist.thetadot);\n    }\n\n    // Return the current state\n    xi_predict(0, 0) =\n        rigid2d::normalize_angle(xi_predict(0, 0) + T_wbp(0, 0) + w_t(0, 0));\n    xi_predict(1, 0) = xi_predict(1, 0) + T_wbp(1, 0) + w_t(1, 0);\n    xi_predict(2, 0) = xi_predict(2, 0) + T_wbp(2, 0) + w_t(2, 0);\n\n    // arma::mat q_t_new = q_t + T_wbp + w_t;\n    // q_t_new(0, 0) = rigid2d::normalize_angle(q_t_new(0, 0));\n    return xi_predict;\n  }\n\n  /// Get derivative of g with respect to the state ξ.\n  arma::mat EKF::get_transition(const Twist2D &twist)\n  {\n    arma::mat g = (arma::mat(xi_predict.n_rows, xi_predict.n_rows)).fill(0.0);\n    arma::mat A_t = (arma::mat(xi_predict.n_rows, xi_predict.n_rows)).fill(0.0);\n    arma::mat I = eye(size(g));\n\n    // If the rotational velocity is zero (twist.thetadot = 0)\n    if (rigid2d::almost_equal(twist.thetadot, 0.0, 1.0e-6))\n    {\n      g(0, 0) = 0.0;\n      g(1, 0) = -twist.xdot * sin(xi_predict(0, 0));\n      g(2, 0) = twist.xdot * cos(xi_predict(0, 0));\n    }\n\n    // If the rotational velocity is not zero (twist.thetadot != 0)\n    else\n    {\n      double dx_dtheta = twist.xdot / twist.thetadot;\n      g(0, 0) = 0.0;\n      g(1, 0) = -dx_dtheta * cos(xi_predict(0, 0)) +\n                dx_dtheta * cos(xi_predict(0, 0) + twist.thetadot);\n      g(2, 0) = -dx_dtheta * sin(xi_predict(0, 0)) +\n                dx_dtheta * sin(xi_predict(0, 0) + twist.thetadot);\n    }\n\n    // Return the current state\n    return (I + g);\n  }\n\n  /// Predict the next step - finds the estimated state and covariance.\n  void EKF::predict(const Twist2D &twist)\n  {\n    xi_predict = get_new_state(twist);\n    arma::mat A_t = get_transition(twist);\n    cov_predict = A_t * cov_predict * A_t.t() + Q_mat;\n  }\n\n  /// Compute the measurement h for range and bearing to landmark.\n  arma::mat EKF::get_h(int index)\n  {\n    arma::mat h = arma::mat(2, 1);\n    h(0, 0) = std::sqrt(pow(xi_predict(index + 3, 0) - xi_predict(1, 0), 2) +\n                        pow(xi_predict(index + 4, 0) - xi_predict(2, 0), 2));\n    h(1, 0) = rigid2d::normalize_angle(\n        atan2(xi_predict(index + 4, 0) - xi_predict(2, 0),\n              xi_predict(index + 3, 0) - xi_predict(1, 0)) -\n        xi_predict(0, 0));\n\n    return h;\n  }\n\n  /// Compute the derivative of h with respect to the state.\n  arma::mat EKF::get_H(int index)\n  {\n    int i = index + 3;\n    double del_x = xi_predict(i, 0) - xi_predict(1, 0);\n    double del_y = xi_predict(i + 1, 0) - xi_predict(2, 0);\n    double d = pow(del_x, 2) + pow(del_y, 2);\n\n    arma::mat H = arma::mat(2, cov_predict.n_rows).fill(0.0);\n    H(0, 1) = -del_x / sqrt(d);\n    H(0, 2) = -del_y / sqrt(d);\n    H(1, 0) = -1;\n    H(1, 1) = del_y / d;\n    H(1, 2) = -del_x / d;\n\n    H(0, i) = del_x / sqrt(d);\n    H(0, i + 1) = del_y / sqrt(d);\n    H(1, i) = -del_y / d;\n    H(1, i + 1) = del_x / d;\n\n    return H;\n  }\n\n  /// Update the next step.\n  void EKF::update(std::vector<Measurement> meas)\n  {\n    arma::mat I = eye(size(cov_predict));\n    arma::mat z = arma::mat(2, 1);\n    arma::mat z_del = arma::mat(2, 1);\n\n    for (auto &m : meas)\n    {\n      int m_row = id2landmark.find(m.id)->second;\n\n      // Compute the theoretical measurement, given the current state estimate\n      auto z_theory = get_h(m_row);\n\n      // Compute the Kalman gain from the linearized measurement model\n      auto H_i = get_H(m_row);\n      arma::mat H_i_t = H_i.t();\n      arma::mat inv_mat = arma::inv(H_i * cov_predict * H_i_t + R_mat);\n      arma::mat K = cov_predict * H_i_t * inv_mat;\n\n      // Compute the posterior state update\n      // arma::mat z = m.compute_z();\n      z(0, 0) = m.r;\n      z(1, 0) = rigid2d::normalize_angle(m.phi);\n      // z_del = z - z_theory;\n      z_del = z - z_theory;\n      z_del(1, 0) = rigid2d::normalize_angle(z_del(1, 0));\n\n      xi_predict = xi_predict + K * z_del;\n      xi_predict(0, 0) = rigid2d::normalize_angle(xi_predict(0, 0));\n\n      // Compute the posterior covariance\n      cov_predict = (I - K * H_i) * cov_predict;\n    }\n  }\n\n  /// Add a new zero row and column to a matrix (used when adding new landmark).\n  arma::mat EKF::update_matrix_size(arma::mat mat)\n  {\n    arma::mat mat_addition_col = (arma::mat(mat.n_rows, 2)).fill(0.0);\n    arma::mat mat_addition_row = (arma::mat(2, mat.n_cols + 2)).fill(0.0);\n\n    arma::mat mat_update = std::move(arma::join_rows(mat, mat_addition_col));\n    mat_update = std::move(arma::join_cols(mat_update, mat_addition_row));\n\n    return mat_update;\n  }\n\n  /// Run the Extended Kalman Filter algorithm.\n  void EKF::run_ekf(const Twist2D &twist, const std::vector<Measurement> &meas)\n  {\n    // For every measurement\n    for (auto &m : meas)\n    {\n      add_new_measurement(m);\n    }\n\n    // Predict and update\n    predict(twist);\n    update(meas);\n\n    // Update the combined state vector and the covariance\n    // xi = xi_predict;\n    // cov = cov_predict;\n\n    // Update robot state and map state\n    q_t = xi_predict.submat(0, 0, 2, 0);\n    q_t(0, 0) = rigid2d::normalize_angle(q_t(0, 0));\n    m_t = xi_predict.submat(3, 0, xi_predict.n_rows - 1, 0);\n  }\n\n  /// Output the robot state\n  arma::mat EKF::output_state()\n  {\n    q_t(0, 0) = rigid2d::normalize_angle(q_t(0, 0));\n    return q_t;\n  }\n\n  /// Output the map state\n  arma::mat EKF::output_map_state() { return m_t; }\n} // namespace nuslam", "meta": {"hexsha": "0bad0b058c520d136d11202336206ada765d8382", "size": 9157, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "nuslam/src/nuslam.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/nuslam.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/nuslam.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": 29.5387096774, "max_line_length": 81, "alphanum_fraction": 0.6001965709, "num_tokens": 3079, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7279754489059774, "lm_q2_score": 0.476579651063676, "lm_q1q2_score": 0.34693828542253363}}
{"text": "// Volumetric3D_cylinder.cpp\n// created by Kuangdai on 19-Oct-2016 \n// a cylinder-shaped heterogeneity\n\n#include \"Volumetric3D_cylinder.h\"\n#include \"Parameters.h\"\n#include \"Geodesy.h\"\n#include <boost/algorithm/string.hpp>\n#include <sstream>\n\nvoid Volumetric3D_cylinder::initialize(const std::vector<std::string> &params) {\n    // need at least 10 parameters to make a cylinder\n    if (params.size() < 10) {\n        throw std::runtime_error(\"Volumetric3D_cylinder::initialize || \"\n            \"Not enough parameters for a cylinder-shaped heterogeneity. Need 10 at least.\");\n    }\n        \n    const std::string source = \"Volumetric3D_cylinder::initialize\";\n    \n    // property name\n    bool found = false;\n    for (int i = 0; i < Volumetric3D::MaterialPropertyString.size(); i++) {\n        if (boost::iequals(params[0], Volumetric3D::MaterialPropertyString[i])) {\n            mMaterialProp = Volumetric3D::MaterialProperty(i);\n            found = true;\n            break;\n        }\n    }\n    if (!found) {\n        throw std::runtime_error(\"Volumetric3D_cylinder::initialize || \"\n            \"Unknown material property, name = \" + params[0]);\n    }\n    \n    // reference type\n    found = false;\n    for (int i = 0; i < Volumetric3D::MaterialRefTypeString.size(); i++) {\n        if (boost::iequals(params[1], Volumetric3D::MaterialRefTypeString[i]) ||\n            boost::iequals(params[1], Volumetric3D::MaterialRefTypeStringShort[i])) {\n            mReferenceType = Volumetric3D::MaterialRefType(i);\n            found = true;\n            break;\n        }\n    }\n    if (!found) {\n        throw std::runtime_error(\"Volumetric3D_cylinder::initialize || \"\n            \"Unknown material reference type, type = \" + params[1]);\n    }\n    \n    // value inside\n    Parameters::castValue(mValueInside, params[2], source);\n    \n    // radius\n    Parameters::castValue(mRadius, params[3], source); mRadius *= 1e3;\n    \n    // location    \n    Parameters::castValue(mD1, params[4], source); mD1 *= 1e3;\n    Parameters::castValue(mLat1, params[5], source);\n    Parameters::castValue(mLon1, params[6], source);\n    \n    Parameters::castValue(mD2, params[7], source); mD2 *= 1e3;\n    Parameters::castValue(mLat2, params[8], source);\n    Parameters::castValue(mLon2, params[9], source);\n    \n    // optional\n    try {\n        int ipar = 10;\n        Parameters::castValue(mSourceCentered, params.at(ipar++), source);\n        Parameters::castValue(mFluid, params.at(ipar++), source);\n        Parameters::castValue(mHWHM_lateral, params.at(ipar++), source); mHWHM_lateral *= 1e3;\n        Parameters::castValue(mHWHM_top_bot, params.at(ipar++), source); mHWHM_top_bot *= 1e3;\n    } catch (std::out_of_range) {\n        // nothing\n    }    \n    \n    // compute xyz of endpoints and length\n    RDCol3 rtpPoint1, rtpPoint2;\n    if (mSourceCentered) {\n        RDCol3 rtpPoint1Src, rtpPoint2Src;\n        rtpPoint1Src(0) = Geodesy::getROuter() - mD1;\n        rtpPoint1Src(1) = mLat1 * degree;\n        rtpPoint1Src(2) = mLon1 * degree;\n        rtpPoint1 = Geodesy::rotateSrc2Glob(rtpPoint1Src, mSrcLat, mSrcLon, mSrcDep);\n        rtpPoint2Src(0) = Geodesy::getROuter() - mD2;\n        rtpPoint2Src(1) = mLat2 * degree;\n        rtpPoint2Src(2) = mLon2 * degree;\n        rtpPoint2 = Geodesy::rotateSrc2Glob(rtpPoint2Src, mSrcLat, mSrcLon, mSrcDep);\n    } else {\n        rtpPoint1(0) = Geodesy::getROuter() - mD1;\n        rtpPoint1(1) = Geodesy::lat2Theta_d(mLat1, mD1);\n        rtpPoint1(2) = Geodesy::lon2Phi(mLon1);\n        rtpPoint2(0) = Geodesy::getROuter() - mD2;\n        rtpPoint2(1) = Geodesy::lat2Theta_d(mLat2, mD2);\n        rtpPoint2(2) = Geodesy::lon2Phi(mLon2);\n    }\n    mXyzPoint1 = Geodesy::toCartesian(rtpPoint1);\n    mXyzPoint2 = Geodesy::toCartesian(rtpPoint2);\n    mLength = (mXyzPoint1 - mXyzPoint2).norm();\n    \n    // use 20% of radius for lateral HWHM if not specified\n    if (mHWHM_lateral < 0.) {\n        mHWHM_lateral = mRadius * .2;\n    }\n    \n    // use 10% of cylinder length for top-bot HWHM if not specified\n    if (mHWHM_top_bot < 0.) {\n        mHWHM_top_bot = mLength * .1;\n    }\n    \n    // for Absolute models\n    if (mReferenceType == Volumetric3D::MaterialRefType::Absolute) {\n        // decay is not allowed\n        mHWHM_lateral = mHWHM_top_bot = 0.;\n        // convert to SI\n        mValueInside *= MaterialPropertyAbsSI[mMaterialProp];\n    }\n}\n\nbool Volumetric3D_cylinder::get3dProperties(double r, double theta, double phi, double rElemCenter,\n    std::vector<MaterialProperty> &properties, \n    std::vector<MaterialRefType> &refTypes,\n    std::vector<double> &values) const {\n    \n    // header\n    properties = std::vector<MaterialProperty>(1, mMaterialProp);\n    refTypes = std::vector<MaterialRefType>(1, mReferenceType);\n    values = std::vector<double>(1, 0.);\n    \n    // distance from point to axis\n    RDCol3 rtpTarget;\n    rtpTarget(0) = r;\n    rtpTarget(1) = theta;\n    rtpTarget(2) = phi;\n    const RDCol3 &xyzTarget = Geodesy::toCartesian(rtpTarget);\n    const RDCol3 &xyzDiff1 = xyzTarget - mXyzPoint1;\n    const RDCol3 &xyzDiff2 = xyzTarget - mXyzPoint2; \n    double distToLine = xyzDiff1.cross(xyzDiff2).norm() / mLength;\n    \n    // outside range\n    if (distToLine > mRadius + 4. * mHWHM_lateral) {\n        return false;\n    }\n    \n    // compute Gaussian lateral\n    double distToSurf = distToLine - mRadius;\n    if (distToSurf < 0.) {\n        distToSurf = 0.;\n    }\n    double stddev = mHWHM_lateral / sqrt(2. * log(2.));\n    double gaussian_lateral = mValueInside * exp(-distToSurf * distToSurf / (stddev * stddev * 2.));\n    \n    // distance from point to ends\n    double d1 = xyzDiff1.norm();\n    double d2 = xyzDiff2.norm();\n    double dmax = std::max(d1, d2);\n    double distToTopBot = sqrt(dmax * dmax - distToLine * distToLine) - mLength;\n    \n    // outside range\n    if (distToTopBot > 4. * mHWHM_top_bot) {\n        return false;\n    }\n    \n    double gaussian_topbot = gaussian_lateral;\n    if (distToTopBot > 0.) {\n        // compute Gaussian top-bottom\n        stddev = mHWHM_top_bot / sqrt(2. * log(2.));\n        gaussian_topbot = gaussian_lateral * exp(-distToTopBot * distToTopBot / (stddev * stddev * 2.)); \n    }\n    \n    // set perturbations    \n    values[0] = gaussian_topbot;\n    return true;    \n}\n\nstd::string Volumetric3D_cylinder::verbose() const {\n    std::stringstream ss;\n    ss << \"\\n======================= 3D Volumetric ======================\" << std::endl;\n    ss << \"  Model Name               =   cylinder\" << std::endl;\n    ss << \"  Material Property        =   \" << MaterialPropertyString[mMaterialProp] << std::endl;\n    ss << \"  Reference Type           =   \" << MaterialRefTypeString[mReferenceType] << std::endl;\n    if (mReferenceType == Volumetric3D::MaterialRefType::Absolute) {\n        ss << \"  Value Inside             =   \" << mValueInside / MaterialPropertyAbsSI[mMaterialProp] << std::endl;\n    } else {\n        ss << \"  Value Inside             =   \" << mValueInside << std::endl;\n    }\n    ss << \"  Cylinder Radius / km     =   \" << mRadius / 1e3 << std::endl;\n    ss << \"  Depth_1 / km             =   \" << mD1 / 1e3 << std::endl;\n    ss << \"  Lat_1 or Theta_1 / deg   =   \" << mLat1 << std::endl;\n    ss << \"  Lon_1 or Phi_1 / deg     =   \" << mLon1 << std::endl;\n    ss << \"  Depth_2 / km             =   \" << mD2 / 1e3 << std::endl;\n    ss << \"  Lat_2 or Theta_2 / deg   =   \" << mLat2 << std::endl;\n    ss << \"  Lon_2 or Phi_2 / deg     =   \" << mLon2 << std::endl;\n    ss << \"  Source-centered          =   \" << (mSourceCentered ? \"YES\" : \"NO\") << std::endl;\n    ss << \"  HWHM lateral / km        =   \" << mHWHM_lateral / 1e3 << std::endl;\n    ss << \"  HWHM top-bot / km        =   \" << mHWHM_top_bot / 1e3 << std::endl;\n    ss << \"======================= 3D Volumetric ======================\\n\" << std::endl;\n    return ss.str();\n}\n\n", "meta": {"hexsha": "66b5d6c18d809e245d01bbcd52b139a74329cb6a", "size": 7819, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "SOLVER/src/3d_model/3d_volumetric/simple_shapes/Volumetric3D_cylinder.cpp", "max_stars_repo_name": "kuangdai/AxiSEM3D", "max_stars_repo_head_hexsha": "fd9da14e9107783e3b07b936c67af2412146e099", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 17.0, "max_stars_repo_stars_event_min_datetime": "2016-12-16T03:13:57.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-15T01:56:45.000Z", "max_issues_repo_path": "SOLVER/src/3d_model/3d_volumetric/simple_shapes/Volumetric3D_cylinder.cpp", "max_issues_repo_name": "syzeng-duduxi/AxiSEM3D", "max_issues_repo_head_hexsha": "fd9da14e9107783e3b07b936c67af2412146e099", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2018-01-15T17:17:20.000Z", "max_issues_repo_issues_event_max_datetime": "2020-03-18T09:53:58.000Z", "max_forks_repo_path": "SOLVER/src/3d_model/3d_volumetric/simple_shapes/Volumetric3D_cylinder.cpp", "max_forks_repo_name": "syzeng-duduxi/AxiSEM3D", "max_forks_repo_head_hexsha": "fd9da14e9107783e3b07b936c67af2412146e099", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 19.0, "max_forks_repo_forks_event_min_datetime": "2016-12-28T16:55:00.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-23T01:02:16.000Z", "avg_line_length": 39.2914572864, "max_line_length": 116, "alphanum_fraction": 0.5954725668, "num_tokens": 2421, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6992544210587585, "lm_q2_score": 0.49609382947091946, "lm_q1q2_score": 0.3468958035175102}}
{"text": "#include <GL/freeglut.h>\n#include <vector>\n#include <Eigen/Eigen>\n#include <iostream>\n\n#include \"equirectangular_camera_colinearity_tait_bryan_wc_jacobian.h\"\n#include \"equirectangular_camera_coplanarity_tait_bryan_wc_jacobian.h\"\n#include \"equirectangular_camera_coplanarity_rodrigues_wc_jacobian.h\"\n#include \"equirectangular_camera_coplanarity_quaternion_wc_jacobian.h\"\n#include \"quaternion_constraint_jacobian.h\"\n#include \"structures.h\"\n#include \"transformations.h\"\n#include \"cauchy.h\"\n\nstruct KeyPoint{\n\tdouble u;\n\tdouble v;\n\tint index_to_tie_point;\n};\n\nstruct Camera{\n\tEigen::Affine3d pose;\n\tstd::vector<KeyPoint> key_points;\n};\n\nstd::vector<Eigen::Vector3d> tie_points;\nstd::vector<Camera> cameras;\nint cols = 4096;\nint rows = 2048;\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 = -215, rotate_y = 273;\nfloat translate_z = -68.0;\nfloat translate_x = 4, translate_y = 30.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\nint main(int argc, char *argv[]){\n\n\tif (false == initGL(&argc, argv)) {\n\t\treturn 4;\n\t}\n\n\tfor(size_t i = 0 ; i < 100; i++){\n\t\tEigen::Vector3d p;\n\t\tp.x() = ((rand()%1000000)/1000000.0 - 0.5) * 2.0 * 100.0;\n\t\tp.y() = ((rand()%1000000)/1000000.0 - 0.5) * 2.0 * 200.0;\n\t\tp.z() = ((rand()%1000000)/1000000.0 - 0.5) * 2.0 * 100.0;\n\t\ttie_points.push_back(p);\n\t}\n\n\tfor(int i = -50 ; i < 50; i+=20){\n\t\tCamera c;\n\t\tc.pose = Eigen::Affine3d::Identity();\n\t\tc.pose(0,3) = (float(rand()%1000000)/1000000.0 - 0.5) * 2.0 * 1.0;\n\t\tc.pose(1,3) = i;\n\t\tc.pose(2,3) = (float(rand()%1000000)/1000000.0 - 0.5) * 2.0 * 1.0;\n\t\tcameras.push_back(c);\n\t}\n\n\n\tfor(size_t i = 0 ; i < cameras.size(); i++){\n\t\tfor(size_t j = 0; j < tie_points.size(); j++){\n\t\t\tKeyPoint kp;\n\t\t\tkp.index_to_tie_point = j;\n\n\t\t\tTaitBryanPose pose = pose_tait_bryan_from_affine_matrix(cameras[i].pose);\n\t\t\tequrectangular_camera_colinearity_tait_bryan_wc(kp.u, kp.v, rows, cols, M_PI, pose.px, pose.py, pose.pz, pose.om, pose.fi, pose.ka, tie_points[j].x(), tie_points[j].y(), tie_points[j].z());\n\n\t\t\tcameras[i].key_points.push_back(kp);\n\t\t}\n\t}\n\n\tprintHelp();\n\tglutDisplayFunc(display);\n\tglutKeyboardFunc(keyboard);\n\tglutMouseFunc(mouse);\n\tglutMotionFunc(motion);\n\tglutMainLoop();\n\n\treturn 0;\n}\n\nbool initGL(int *argc, char **argv) {\n\tglutInit(argc, argv);\n\tglutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE);\n\tglutInitWindowSize(window_width, window_height);\n\tglutCreateWindow(\"equirectangular_camera_coplanarity_ba\");\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\tglColor3f(1,0,0);\n\tglPointSize(5);\n\tglBegin(GL_POINTS);\n\tfor(size_t i = 0 ; i < tie_points.size(); i++){\n\t\tglVertex3f(tie_points[i].x(), tie_points[i].y(), tie_points[i].z());\n\t}\n\tglEnd();\n\n\tfor(size_t i = 0 ; i < cameras.size(); i++){\n\t\tEigen::Affine3d m = cameras[i].pose;\n\n\t\tglBegin(GL_LINES);\n\t\t\tglColor3f(1.0f, 0.0f, 0.0f);\n\t\t\tglVertex3f(m(0,3), m(1,3), m(2,3));\n\t\t\tglVertex3f(m(0,3) + m(0,0), m(1,3) + m(1,0), m(2,3) + m(2,0));\n\n\t\t\tglColor3f(0.0f, 1.0f, 0.0f);\n\t\t\tglVertex3f(m(0,3), m(1,3), m(2,3));\n\t\t\tglVertex3f(m(0,3) + m(0,1), m(1,3) + m(1,1), m(2,3) + m(2,1));\n\n\t\t\tglColor3f(0.0f, 0.0f, 1.0f);\n\t\t\tglVertex3f(m(0,3), m(1,3), m(2,3));\n\t\t\tglVertex3f(m(0,3) + m(0,2), m(1,3) + m(1,2), m(2,3) + m(2,2));\n\t\tglEnd();\n\t}\n\n\tglColor3f(0.8,0.8,0.8);\n\tglBegin(GL_LINE_STRIP);\n\tfor(size_t i = 0 ; i < cameras.size(); i++){\n\t\tEigen::Affine3d m = cameras[i].pose;\n\t\tglVertex3f(m(0,3), m(1,3), m(2,3));\n\t}\n\tglEnd();\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 'c':{\n\t\t\tfor(size_t i = 0; i < cameras.size(); i++){\n\t\t\t\tTaitBryanPose pose;\n\t\t\t\tpose.om = (float(rand()%1000000)/1000000.0 - 0.5) * 2.0 * 0.1;\n\t\t\t\tpose.fi = (float(rand()%1000000)/1000000.0 - 0.5) * 2.0 * 0.1;\n\t\t\t\tpose.ka = (float(rand()%1000000)/1000000.0 - 0.5) * 2.0 * 0.1;\n\n\t\t\t\tEigen::Affine3d m = affine_matrix_from_pose_tait_bryan(pose);\n\t\t\t\tcameras[i].pose = cameras[i].pose * m;\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t\tcase 'p':{\n\t\t\tfor(size_t i = 0; i < tie_points.size(); i++){\n\t\t\t\ttie_points[i].x() += (float(rand()%1000000)/1000000.0 - 0.5) * 2.0 * 1.0;\n\t\t\t\ttie_points[i].y() += (float(rand()%1000000)/1000000.0 - 0.5) * 2.0 * 1.0;\n\t\t\t\ttie_points[i].z() += (float(rand()%1000000)/1000000.0 - 0.5) * 2.0 * 1.0;\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\tfor(size_t i = 0; i < cameras.size(); i++){\n\t\t\t\tfor(size_t j = 0; j < cameras.size(); j++){\n\t\t\t\t\tfor(size_t k = 0; k < cameras[i].key_points.size(); k++){\n\t\t\t\t\t\tif(i != j){\n\t\t\t\t\t\t\tTaitBryanPose pose_1 = pose_tait_bryan_from_affine_matrix(cameras[i].pose);\n\t\t\t\t\t\t\tTaitBryanPose pose_2 = pose_tait_bryan_from_affine_matrix(cameras[j].pose);\n\n\t\t\t\t\t\t\tdouble px_1 = pose_1.px;\n\t\t\t\t\t\t\tdouble py_1 = pose_1.py;\n\t\t\t\t\t\t\tdouble pz_1 = pose_1.pz;\n\t\t\t\t\t\t\tdouble om_1 = pose_1.om;\n\t\t\t\t\t\t\tdouble fi_1 = pose_1.fi;\n\t\t\t\t\t\t\tdouble ka_1 = pose_1.ka;\n\n\t\t\t\t\t\t\tdouble px_2 = pose_2.px;\n\t\t\t\t\t\t\tdouble py_2 = pose_2.py;\n\t\t\t\t\t\t\tdouble pz_2 = pose_2.pz;\n\t\t\t\t\t\t\tdouble om_2 = pose_2.om;\n\t\t\t\t\t\t\tdouble fi_2 = pose_2.fi;\n\t\t\t\t\t\t\tdouble ka_2 = pose_2.ka;\n\n\t\t\t\t\t\t\tdouble u_1 = (cameras[i].key_points[k].u);\n\t\t\t\t\t\t\tdouble v_1 = (cameras[i].key_points[k].v);\n\t\t\t\t\t\t\tdouble u_2 = (cameras[j].key_points[k].u);\n\t\t\t\t\t\t\tdouble v_2 = (cameras[j].key_points[k].v);\n\n\n\t\t\t\t\t\t\tdouble delta;\n\t\t\t\t\t\t\tobservation_equation_equirectangular_camera_coplanarity_tait_bryan_wc(delta, rows, cols, M_PI, u_1, v_1, px_1, py_1, pz_1, om_1, fi_1, ka_1, rows, cols, u_2, v_2, px_2, py_2, pz_2, om_2, fi_2, ka_2);\n\n\t\t\t\t\t\t\tEigen::Matrix<double, 1, 12, Eigen::RowMajor> jacobian;\n\t\t\t\t\t\t\tobservation_equation_equirectangular_camera_coplanarity_tait_bryan_wc_jacobian(jacobian, rows, cols, M_PI, u_1, v_1, px_1, py_1, pz_1, om_1, fi_1, ka_1, rows, cols, u_2, v_2, px_2, py_2, pz_2, om_2, fi_2, ka_2);\n\n\t\t\t\t\t\t\tint ir = tripletListB.size();\n\t\t\t\t\t\t\tint ic_1 = i * 3;\n\t\t\t\t\t\t\tint ic_2 = j * 3;\n\n\t\t\t\t\t\t\ttripletListA.emplace_back(ir     , ic_1 + 0, -jacobian(0,3));\n\t\t\t\t\t\t\ttripletListA.emplace_back(ir     , ic_1 + 1, -jacobian(0,4));\n\t\t\t\t\t\t\ttripletListA.emplace_back(ir     , ic_1 + 2, -jacobian(0,5));\n\n\t\t\t\t\t\t\ttripletListA.emplace_back(ir     , ic_2 + 0, -jacobian(0,9));\n\t\t\t\t\t\t\ttripletListA.emplace_back(ir     , ic_2 + 1, -jacobian(0,10));\n\t\t\t\t\t\t\ttripletListA.emplace_back(ir     , ic_2 + 2, -jacobian(0,11));\n\n\t\t\t\t\t\t\ttripletListP.emplace_back(ir    , ir    ,  cauchy(delta, 1));\n\n\t\t\t\t\t\t\ttripletListB.emplace_back(ir    , 0,  delta);\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\tEigen::SparseMatrix<double> matA(tripletListB.size(), cameras.size() * 3);\n\t\t\tEigen::SparseMatrix<double> matP(tripletListB.size(), tripletListB.size());\n\t\t\tEigen::SparseMatrix<double> matB(tripletListB.size(), 1);\n\n\t\t\tmatA.setFromTriplets(tripletListA.begin(), tripletListA.end());\n\t\t\tmatP.setFromTriplets(tripletListP.begin(), tripletListP.end());\n\t\t\tmatB.setFromTriplets(tripletListB.begin(), tripletListB.end());\n\n\t\t\tEigen::SparseMatrix<double> AtPA(cameras.size() * 3, cameras.size() * 3);\n\t\t\tEigen::SparseMatrix<double> AtPB(cameras.size() * 3, 1);\n\n\t\t\t{\n\t\t\tEigen::SparseMatrix<double> AtP = matA.transpose() * matP;\n\t\t\tAtPA = (AtP) * matA;\n\t\t\tAtPB = (AtP) * matB;\n\t\t\t}\n\n\t\t\ttripletListA.clear();\n\t\t\ttripletListP.clear();\n\t\t\ttripletListB.clear();\n\n\t\t\tstd::cout << \"AtPA.size: \" << AtPA.size() << std::endl;\n\t\t\tstd::cout << \"AtPB.size: \" << AtPB.size() << std::endl;\n\n\t\t\tstd::cout << \"start solving AtPA=AtPB\" << std::endl;\n\t\t\tEigen::SimplicialCholesky<Eigen::SparseMatrix<double>> solver(AtPA);\n\n\t\t\tstd::cout << \"x = solver.solve(AtPB)\" << std::endl;\n\t\t\tEigen::SparseMatrix<double> x = solver.solve(AtPB);\n\n\t\t\tstd::vector<double> h_x;\n\n\t\t\tfor (int k=0; k<x.outerSize(); ++k){\n\t\t\t\tfor (Eigen::SparseMatrix<double>::InnerIterator it(x,k); it; ++it){\n\t\t\t\t\th_x.push_back(it.value());\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif(h_x.size() == cameras.size() * 3){\n\t\t\t\tfor(size_t i = 0 ; i < h_x.size(); i++){\n\t\t\t\t\tstd::cout << h_x[i] << std::endl;\n\t\t\t\t}\n\t\t\t\tstd::cout << \"AtPA=AtPB SOLVED\" << std::endl;\n\t\t\t\tstd::cout << \"update\" << std::endl;\n\n\t\t\t\tint counter = 0;\n\n\t\t\t\tfor(size_t i = 0; i < cameras.size(); i++){\n\t\t\t\t\tTaitBryanPose pose = pose_tait_bryan_from_affine_matrix(cameras[i].pose);\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\n\t\t\t\t\tcameras[i].pose = affine_matrix_from_pose_tait_bryan(pose);\n\t\t\t\t}\n\t\t\t}else{\n\t\t\t\tstd::cout << \"AtPA=AtPB FAILED\" << std::endl;\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t\tcase 'r':{\n\t\t\tfor(size_t i = 0; i < cameras.size(); i++){\n\t\t\t\tTaitBryanPose posetb = pose_tait_bryan_from_affine_matrix(cameras[i].pose);\n\t\t\t\tposetb.om += (float(rand()%1000000)/1000000.0 - 0.5) * 2.0 * 0.00001;\n\t\t\t\tposetb.fi += (float(rand()%1000000)/1000000.0 - 0.5) * 2.0 * 0.00001;\n\t\t\t\tposetb.ka += (float(rand()%1000000)/1000000.0 - 0.5) * 2.0 * 0.00001;\n\t\t\t\tcameras[i].pose = affine_matrix_from_pose_tait_bryan(posetb);\n\t\t\t}\n\n\t\t\tstd::vector<Eigen::Triplet<double>> tripletListA;\n\t\t\tstd::vector<Eigen::Triplet<double>> tripletListP;\n\t\t\tstd::vector<Eigen::Triplet<double>> tripletListB;\n\n\t\t\tfor(size_t i = 0; i < cameras.size(); i++){\n\t\t\t\tfor(size_t j = 0; j < cameras.size(); j++){\n\t\t\t\t\tfor(size_t k = 0; k < cameras[i].key_points.size(); k++){\n\t\t\t\t\t\tif(i != j){\n\t\t\t\t\t\t\tRodriguesPose pose_1 = pose_rodrigues_from_affine_matrix(cameras[i].pose);\n\t\t\t\t\t\t\tRodriguesPose pose_2 = pose_rodrigues_from_affine_matrix(cameras[j].pose);\n\n\t\t\t\t\t\t\tdouble px_1 = pose_1.px;\n\t\t\t\t\t\t\tdouble py_1 = pose_1.py;\n\t\t\t\t\t\t\tdouble pz_1 = pose_1.pz;\n\t\t\t\t\t\t\tdouble sx_1 = pose_1.sx;\n\t\t\t\t\t\t\tdouble sy_1 = pose_1.sy;\n\t\t\t\t\t\t\tdouble sz_1 = pose_1.sz;\n\n\t\t\t\t\t\t\tdouble px_2 = pose_2.px;\n\t\t\t\t\t\t\tdouble py_2 = pose_2.py;\n\t\t\t\t\t\t\tdouble pz_2 = pose_2.pz;\n\t\t\t\t\t\t\tdouble sx_2 = pose_2.sx;\n\t\t\t\t\t\t\tdouble sy_2 = pose_2.sy;\n\t\t\t\t\t\t\tdouble sz_2 = pose_2.sz;\n\n\t\t\t\t\t\t\tdouble u_1 = (cameras[i].key_points[k].u);\n\t\t\t\t\t\t\tdouble v_1 = (cameras[i].key_points[k].v);\n\t\t\t\t\t\t\tdouble u_2 = (cameras[j].key_points[k].u);\n\t\t\t\t\t\t\tdouble v_2 = (cameras[j].key_points[k].v);\n\n\n\t\t\t\t\t\t\tdouble delta;\n\t\t\t\t\t\t\tobservation_equation_equirectangular_camera_coplanarity_rodrigues_wc(delta, rows, cols, M_PI, u_1, v_1, px_1, py_1, pz_1, sx_1, sy_1, sz_1, rows, cols, u_2, v_2, px_2, py_2, pz_2, sx_2, sy_2, sz_2);\n\n\t\t\t\t\t\t\tEigen::Matrix<double, 1, 12, Eigen::RowMajor> jacobian;\n\t\t\t\t\t\t\tobservation_equation_equirectangular_camera_coplanarity_rodrigues_wc_jacobian(jacobian, rows, cols, M_PI, u_1, v_1, px_1, py_1, pz_1, sx_1, sy_1, sz_1, rows, cols, u_2, v_2, px_2, py_2, pz_2, sx_2, sy_2, sz_2);\n\n\t\t\t\t\t\t\tint ir = tripletListB.size();\n\t\t\t\t\t\t\tint ic_1 = i * 3;\n\t\t\t\t\t\t\tint ic_2 = j * 3;\n\n\t\t\t\t\t\t\ttripletListA.emplace_back(ir, ic_1 + 0, -jacobian(0,3));\n\t\t\t\t\t\t\ttripletListA.emplace_back(ir, ic_1 + 1, -jacobian(0,4));\n\t\t\t\t\t\t\ttripletListA.emplace_back(ir, ic_1 + 2, -jacobian(0,5));\n\n\t\t\t\t\t\t\ttripletListA.emplace_back(ir, ic_2 + 0, -jacobian(0,9));\n\t\t\t\t\t\t\ttripletListA.emplace_back(ir, ic_2 + 1, -jacobian(0,10));\n\t\t\t\t\t\t\ttripletListA.emplace_back(ir, ic_2 + 2, -jacobian(0,11));\n\n\t\t\t\t\t\t\ttripletListP.emplace_back(ir, ir,  cauchy(delta, 1));\n\n\t\t\t\t\t\t\ttripletListB.emplace_back(ir, 0, delta);\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\tEigen::SparseMatrix<double> matA(tripletListB.size(), cameras.size() * 3);\n\t\t\tEigen::SparseMatrix<double> matP(tripletListB.size(), tripletListB.size());\n\t\t\tEigen::SparseMatrix<double> matB(tripletListB.size(), 1);\n\n\t\t\tmatA.setFromTriplets(tripletListA.begin(), tripletListA.end());\n\t\t\tmatP.setFromTriplets(tripletListP.begin(), tripletListP.end());\n\t\t\tmatB.setFromTriplets(tripletListB.begin(), tripletListB.end());\n\n\t\t\tEigen::SparseMatrix<double> AtPA(cameras.size() * 3, cameras.size() * 3);\n\t\t\tEigen::SparseMatrix<double> AtPB(cameras.size() * 3, 1);\n\n\t\t\t{\n\t\t\tEigen::SparseMatrix<double> AtP = matA.transpose() * matP;\n\t\t\tAtPA = (AtP) * matA;\n\t\t\tAtPB = (AtP) * matB;\n\t\t\t}\n\n\t\t\ttripletListA.clear();\n\t\t\ttripletListP.clear();\n\t\t\ttripletListB.clear();\n\n\t\t\tstd::cout << \"AtPA.size: \" << AtPA.size() << std::endl;\n\t\t\tstd::cout << \"AtPB.size: \" << AtPB.size() << std::endl;\n\n\t\t\tstd::cout << \"start solving AtPA=AtPB\" << std::endl;\n\t\t\tEigen::SimplicialCholesky<Eigen::SparseMatrix<double>> solver(AtPA);\n\n\t\t\tstd::cout << \"x = solver.solve(AtPB)\" << std::endl;\n\t\t\tEigen::SparseMatrix<double> x = solver.solve(AtPB);\n\n\t\t\tstd::vector<double> h_x;\n\n\t\t\tfor (int k=0; k<x.outerSize(); ++k){\n\t\t\t\tfor (Eigen::SparseMatrix<double>::InnerIterator it(x,k); it; ++it){\n\t\t\t\t\th_x.push_back(it.value());\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif(h_x.size() == cameras.size() * 3){\n\t\t\t\tfor(size_t i = 0 ; i < h_x.size(); i++){\n\t\t\t\t\tstd::cout << h_x[i] << std::endl;\n\t\t\t\t}\n\t\t\t\tstd::cout << \"AtPA=AtPB SOLVED\" << std::endl;\n\t\t\t\tstd::cout << \"update\" << std::endl;\n\n\t\t\t\tint counter = 0;\n\n\t\t\t\tfor(size_t i = 0; i < cameras.size(); i++){\n\t\t\t\t\tRodriguesPose pose = pose_rodrigues_from_affine_matrix(cameras[i].pose);\n\t\t\t\t\tpose.sx += h_x[counter++];\n\t\t\t\t\tpose.sy += h_x[counter++];\n\t\t\t\t\tpose.sz += h_x[counter++];\n\n\t\t\t\t\tcameras[i].pose = affine_matrix_from_pose_rodrigues(pose);\n\t\t\t\t}\n\t\t\t}else{\n\t\t\t\tstd::cout << \"AtPA=AtPB FAILED\" << std::endl;\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t\tcase 'q':{\n\t\t\tfor(size_t i = 0; i < cameras.size(); i++){\n\t\t\t\tTaitBryanPose posetb = pose_tait_bryan_from_affine_matrix(cameras[i].pose);\n\t\t\t\tposetb.om += (float(rand()%1000000)/1000000.0 - 0.5) * 2.0 * 0.00001;\n\t\t\t\tposetb.fi += (float(rand()%1000000)/1000000.0 - 0.5) * 2.0 * 0.00001;\n\t\t\t\tposetb.ka += (float(rand()%1000000)/1000000.0 - 0.5) * 2.0 * 0.00001;\n\t\t\t\tcameras[i].pose = affine_matrix_from_pose_tait_bryan(posetb);\n\t\t\t}\n\n\t\t\tstd::vector<Eigen::Triplet<double>> tripletListA;\n\t\t\tstd::vector<Eigen::Triplet<double>> tripletListP;\n\t\t\tstd::vector<Eigen::Triplet<double>> tripletListB;\n\n\t\t\tfor(size_t i = 0; i < cameras.size(); i++){\n\t\t\t\tfor(size_t j = 0; j < cameras.size(); j++){\n\t\t\t\t\tfor(size_t k = 0; k < cameras[i].key_points.size(); k++){\n\t\t\t\t\t\tif(i != j){\n\t\t\t\t\t\t\tQuaternionPose pose_1 = pose_quaternion_from_affine_matrix(cameras[i].pose);\n\t\t\t\t\t\t\tQuaternionPose pose_2 = pose_quaternion_from_affine_matrix(cameras[j].pose);\n\n\t\t\t\t\t\t\tdouble px_1 = pose_1.px;\n\t\t\t\t\t\t\tdouble py_1 = pose_1.py;\n\t\t\t\t\t\t\tdouble pz_1 = pose_1.pz;\n\t\t\t\t\t\t\tdouble q0_1 = pose_1.q0;\n\t\t\t\t\t\t\tdouble q1_1 = pose_1.q1;\n\t\t\t\t\t\t\tdouble q2_1 = pose_1.q2;\n\t\t\t\t\t\t\tdouble q3_1 = pose_1.q3;\n\n\t\t\t\t\t\t\tdouble px_2 = pose_2.px;\n\t\t\t\t\t\t\tdouble py_2 = pose_2.py;\n\t\t\t\t\t\t\tdouble pz_2 = pose_2.pz;\n\t\t\t\t\t\t\tdouble q0_2 = pose_2.q0;\n\t\t\t\t\t\t\tdouble q1_2 = pose_2.q1;\n\t\t\t\t\t\t\tdouble q2_2 = pose_2.q2;\n\t\t\t\t\t\t\tdouble q3_2 = pose_2.q3;\n\n\t\t\t\t\t\t\tdouble u_1 = (cameras[i].key_points[k].u);\n\t\t\t\t\t\t\tdouble v_1 = (cameras[i].key_points[k].v);\n\t\t\t\t\t\t\tdouble u_2 = (cameras[j].key_points[k].u);\n\t\t\t\t\t\t\tdouble v_2 = (cameras[j].key_points[k].v);\n\n\n\t\t\t\t\t\t\tdouble delta;\n\t\t\t\t\t\t\tobservation_equation_equirectangular_camera_coplanarity_quaternion_wc(delta, rows, cols, M_PI, u_1, v_1, px_1, py_1, pz_1, q0_1, q1_1, q2_1, q3_1, rows, cols, u_2, v_2, px_2, py_2, pz_2, q0_2, q1_2, q2_2, q3_2);\n\n\t\t\t\t\t\t\tEigen::Matrix<double, 1, 14, Eigen::RowMajor> jacobian;\n\t\t\t\t\t\t\tobservation_equation_equirectangular_camera_coplanarity_quaternion_wc_jacobian(jacobian, rows, cols, M_PI, u_1, v_1, px_1, py_1, pz_1, q0_1, q1_1, q2_1, q3_1, rows, cols, u_2, v_2, px_2, py_2, pz_2, q0_2, q1_2, q2_2, q3_2);\n\n\t\t\t\t\t\t\tint ir = tripletListB.size();\n\t\t\t\t\t\t\tint ic_1 = i * 4;\n\t\t\t\t\t\t\tint ic_2 = j * 4;\n\n\t\t\t\t\t\t\ttripletListA.emplace_back(ir, ic_1 + 0, -jacobian(0,3));\n\t\t\t\t\t\t\ttripletListA.emplace_back(ir, ic_1 + 1, -jacobian(0,4));\n\t\t\t\t\t\t\ttripletListA.emplace_back(ir, ic_1 + 2, -jacobian(0,5));\n\t\t\t\t\t\t\ttripletListA.emplace_back(ir, ic_1 + 3, -jacobian(0,6));\n\n\t\t\t\t\t\t\ttripletListA.emplace_back(ir, ic_2 + 0, -jacobian(0,10));\n\t\t\t\t\t\t\ttripletListA.emplace_back(ir, ic_2 + 1, -jacobian(0,11));\n\t\t\t\t\t\t\ttripletListA.emplace_back(ir, ic_2 + 2, -jacobian(0,12));\n\t\t\t\t\t\t\ttripletListA.emplace_back(ir, ic_2 + 3, -jacobian(0,13));\n\n\t\t\t\t\t\t\ttripletListP.emplace_back(ir, ir, cauchy(delta, 1));\n\n\t\t\t\t\t\t\ttripletListB.emplace_back(ir, 0,  delta);\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\tfor(size_t i = 0 ; i < cameras.size(); i++){\n\t\t\t\tint ic = i * 4;\n\t\t\t\tint ir = tripletListB.size();\n\t\t\t\tQuaternionPose pose = pose_quaternion_from_affine_matrix(cameras[i].pose);\n\n\t\t\t\tdouble delta;\n\t\t\t\tquaternion_constraint(delta, pose.q0, pose.q1, pose.q2, pose.q3);\n\n\t\t\t\tEigen::Matrix<double, 1, 4> jacobian;\n\t\t\t\tquaternion_constraint_jacobian(jacobian, pose.q0, pose.q1, pose.q2, pose.q3);\n\n\t\t\t\ttripletListA.emplace_back(ir, ic + 0 , -jacobian(0,0));\n\t\t\t\ttripletListA.emplace_back(ir, ic + 1 , -jacobian(0,1));\n\t\t\t\ttripletListA.emplace_back(ir, ic + 2 , -jacobian(0,2));\n\t\t\t\ttripletListA.emplace_back(ir, ic + 3 , -jacobian(0,3));\n\n\t\t\t\ttripletListP.emplace_back(ir, ir, 1000000.0);\n\n\t\t\t\ttripletListB.emplace_back(ir, 0, delta);\n\t\t\t}\n\n\t\t\tEigen::SparseMatrix<double> matA(tripletListB.size(), cameras.size() * 4);\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(cameras.size() * 4, cameras.size() * 4);\n\t\t\tEigen::SparseMatrix<double> AtPB(cameras.size() * 4, 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\tif(h_x.size() == cameras.size() * 4){\n\t\t\t\tfor(size_t i = 0 ; i < h_x.size(); i++){\n\t\t\t\t\tstd::cout << h_x[i] << std::endl;\n\t\t\t\t}\n\t\t\t\tstd::cout << \"AtPA=AtPB SOLVED\" << std::endl;\n\t\t\t\tstd::cout << \"update\" << std::endl;\n\n\t\t\t\tint counter = 0;\n\n\t\t\t\tfor(size_t i = 0; i < cameras.size(); i++){\n\t\t\t\t\tQuaternionPose pose = pose_quaternion_from_affine_matrix(cameras[i].pose);\n\t\t\t\t\tpose.q0 += h_x[counter++];\n\t\t\t\t\tpose.q1 += h_x[counter++];\n\t\t\t\t\tpose.q2 += h_x[counter++];\n\t\t\t\t\tpose.q3 += h_x[counter++];\n\n\t\t\t\t\tcameras[i].pose = affine_matrix_from_pose_quaternion(pose);\n\t\t\t\t}\n\t\t\t}else{\n\t\t\t\tstd::cout << \"AtPA=AtPB FAILED\" << std::endl;\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t}\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 << \"t: optimize (Tait-Bryan)\" << std::endl;\n\tstd::cout << \"r: optimize (Rodriguez)\" << std::endl;\n\tstd::cout << \"q: optimize (Quaternion)\" << std::endl;\n\tstd::cout << \"c: add noise to cameras\" << std::endl;\n\tstd::cout << \"p: add noise to tie points\" << std::endl;\n}\n\n\n\n\n", "meta": {"hexsha": "b1c70a0371667f85745a03d5c0ced7d9004cb8af", "size": 20706, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "codes/c++Examples/src/equirectangular_camera_coplanarity_ba.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/equirectangular_camera_coplanarity_ba.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/equirectangular_camera_coplanarity_ba.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": 32.0030911901, "max_line_length": 230, "alphanum_fraction": 0.6296242635, "num_tokens": 7361, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6992544085240401, "lm_q2_score": 0.4960938294709195, "lm_q1q2_score": 0.34689579729911385}}
{"text": "/*\nSoftware License Agreement (BSD License)\n\nCopyright (c) 2016--, Liana Bertoni (liana.bertoni@gmail.com)\n  All rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n\n* Redistributions of source code must retain the above copyright notice, this\n  list of conditions and the following disclaimer.\n\n* Redistributions in binary form must reproduce the above copyright notice,\n  this list of conditions and the following disclaimer in the documentation\n  and/or other materials provided with the distribution.\n\n* Neither the name of the copyright holder(s) nor the names of its\n  contributors may be used to endorse or promote products derived from\n  this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\nDISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\nFOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\nDAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\nSERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\nCAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\nOR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\nContact GitHub API Training Shop Blog About\n*/\n\n\n#include <ros/ros.h>\n#include <ros/package.h>\n#include <tf/transform_broadcaster.h>\n#include <geometry_msgs/PoseStamped.h>\n#include <geometry_msgs/Pose.h>\n\n\n#include <eigen3/Eigen/Core>\n#include <eigen3/Eigen/Dense>\n#include <eigen3/Eigen/Geometry>\n\n\n#include <kdl/chain.hpp>\n#include <kdl/chainfksolver.hpp>\n#include <kdl/chainfksolverpos_recursive.hpp>\n#include <kdl/frames_io.hpp>\n\n#include <boost/scoped_ptr.hpp>\n#include <kdl/chainjnttojacsolver.hpp>\n#include <kdl/chainfksolverpos_recursive.hpp>\n\n#include <kdl_parser/kdl_parser.hpp>\n#include <urdf/model.h>\n\n\n\n#include <iostream>\n#include <fstream>\n#include <sstream>\n#include <cstdlib>\n#include <string>\n\n\n#include <math.h>\n#include <stdio.h>\n#include <ctime>\n#include <time.h>\n\n\nusing namespace std;\nusing namespace Eigen;\nusing namespace KDL;\n\n\n\n\nint main (int argc, char **argv)\n{\n\n\tros::init(argc, argv, \"Grasp_quality\");\t// ROS node\n\tros::NodeHandle nh;\n\n\n\tint n_c = 1; //number of contacts\n\tint n_q = 19; //number of joints\n\tint n_z = 1; // number of synergie\n\tint synergy = 1;\n\n\n\tdouble Kx = 1;\n\tdouble Ky = 1;\n\tdouble Kz = 1;\n\n\n\tdouble f_i_max = 20;\n\tdouble mu_friction = 1;\n\tdouble PCR;\n\n\n\n\n\n\tEigen::VectorXd f(6*n_c); // contact force\n\tEigen::VectorXd H_f(3*n_c); // contact force with type model of contact\n\tEigen::VectorXd f_y(3*n_c); // controllable contact force\n\n\tEigen::VectorXd w(6);\n\n\tEigen::MatrixXd G(6, 6*n_c);\n\tEigen::MatrixXd G_H_t(6,3*n_c); // Grasp Matrix\n\tEigen::MatrixXd J(6*n_c, n_q); \n\tEigen::MatrixXd H_J(3*n_c,n_q); // Hand Jacobian\n\tEigen::MatrixXd G_r_k(3*n_c,6); // weighted right pseudoinverse of G\n\n\n\tEigen::MatrixXd K(3*n_c,3*n_c); // grasp stiffness matrix\n\tEigen::MatrixXd Kis(3,3);\n\tEigen::MatrixXd Ks(3*n_c,3*n_c); // contact stiffness matrix\n\tEigen::MatrixXd Kp(n_q,n_q); // joint stiffness matrix\n\n\tEigen::MatrixXd S(n_q,n_z); // Synergie matriz for underactuacted hand\n\n\n\tEigen::VectorXd d_f(3*n_c);\n\n\n\t// calculation Ks(Cj)\n\tint s = 0; // step for component\n\tfor( int i = 0 ; i < n_c ; i++ )\n\t{\n\t\tKis(0,0) = 0;\n\t\tKis(1,1) = 0;\n\t\tKis(2,2) = 0;\n\n\t\tif( H_f(i+s+3) >= 0 )\n\t\t\tif(  sqrt( H_f(i+s+0)*H_f(i+s+0) + H_f(i+s+1)*H_f(i+s+1)) <= mu_friction * H_f(i+s+2) )\n\t\t\t{\n\t\t\t\tKis(0,0) =  Kx;\n\t\t\t\tKis(1,1) =  Ky;\n\t\t\t\tKis(2,2) =  Kz;\n\t\t\t}\n\t\t\telse\n\t\t\t\tKs(2,2) = Kz;\n\t\t\n\t\tKs.block<3,3>(s,s) = Kis;\n\t\ts += 3;\n\t}\t\n\n\t// calculation the grasp stiffness matrix K(Cj)\n\tEigen::MatrixXd K_(3*n_c,3*n_c);\n\tK_ = Ks.inverse() + H_J * Kp.inverse() * H_J.transpose() ;\n\tK  = K_.inverse();\n\n\n\n\t// evaluation the constraint N(K(Cj)*Gt) = 0 \n\t// it must be satisfied to immobilize the object\n\tEigen::MatrixXd Kcj_Gt = K * G_H_t.transpose();\n\tFullPivLU<MatrixXd> lu_(Kcj_Gt);\n\tEigen::MatrixXd Null_Kcj_Gt = lu_.kernel();\n\n\n\tbool Matrix_is_Zero = true;\n\n\tfor (int i = 0 ; i < Null_Kcj_Gt.rows() ; i++ )\n\t\tfor ( int j = 0 ; j < Null_Kcj_Gt.cols() ; j++)\n\t\t\tif( Null_Kcj_Gt(i,j) != 0 )\n\t\t\t{\tMatrix_is_Zero = false; break; }\n\n\n\tif( !Matrix_is_Zero ) // condition-constrain of PGR is not satisfy\n\t\treturn 0;\n\n\n\n\tEigen::MatrixXd H_(3,6);\n\n\tH_ << 1, 0, 0, 0, 0, 0,\n\t\t  0, 1, 0, 0, 0, 0,\n\t\t  0, 0, 1, 0, 0, 0;\n\n\n\tEigen::MatrixXd H(3*n_c,6*n_c);\n\n\n\n\tint i = 0;\n\tint j = 0;\n\tfor(int n = 0 ;  n < n_c ; n++)\n\t{\n\t\tH.block<3,6>(i,j) = H_;\n\t\ti += 3;\n\t\tj += 6;\n\t}\n\n\n\n\n\t//define the sinergie matrix \n\tfor(int j = 0 ; j < n_q ; j++)\n\t\tfor(int i = 0; i < n_z ; i++)\n\t\t\tS(j,i) = 1;\n\n\n\n\t\n\t// apply the kind of the point id contact model\n\tG_H_t = G * H.transpose();\n\tH_J = H * J ;\n\tH_f = H * f ;\n\n\n\t// calculatin of external wrench\n\tw = - G_H_t * H_f;\n\n\n\n\t//calculation weighted right pseudoinverse\n\tEigen::MatrixXd G_inv;\n\tEigen::MatrixXd G_;\n\tG_ = G_H_t * K * G_H_t.transpose();\n\tG_inv = G_.inverse();\n\tG_r_k = K * G.transpose() * G_inv; \n\n\n///////////////////////////////////////////////////////////////////////////////////////////////////////////////\n\t/////////////////////////////////////////////////////////////////////////////////////////\n\t///////////////////////////////////////////////////////////////////////////////////////////////\n\n\n\t//calculation of a basis for the subspace of the controllable internal forces\n\t// with null of GHt\n\tFullPivLU<MatrixXd> lu(G_H_t);\n\tEigen::MatrixXd E_ = lu.kernel();\n\tEigen::VectorXd y_(E_.cols());\n\n\tfor(int i = 0; i < y_.size(); i++)\n\t\ty_(i)=1;\n\n\n\tf_y = - G_r_k * w + E_* y_ ; //calculation of the controllable contact forces\n\n\n\t\n\n//////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n\t//////////////////////////////////////////////////////777777777777777777777777777777777777\n\t///////////////////////////////////////////////////////////////////////////////////////\n\n\n\t//calculation of a basis for the subspace of the controllable internal force\n\t// with synergy\n\tEigen::MatrixXd I = MatrixXd::Identity(3*n_c, 3*n_c);\n\tEigen::MatrixXd F(3*n_c,n_q);\n\tEigen::MatrixXd E;\n\tEigen::VectorXd y(1);\n\n\ty(0) = synergy;\n\n\n\n\tF = ( I - G_r_k * G ) * K * H_J; // and maps independently controlled joint reference displacements δqr’s into active internal forces\n\n\tE = F * S ;\n\t\n\tf_y = - G_r_k * w + E * y ; // calculation of the controllable contact forces\n\n\n\n\n\t// search the minimum value of d(f_y) vector\n\tEigen::VectorXd f_i(3);\n\tEigen::VectorXd n_i(3);\n\tEigen::VectorXd f_i_n(1);\n\tint step = 0;\n\tdouble f_i_ ;\n\t\n\n\t\n\n\tfor(int i = 0 ; i < (f_y.size()/3)  ; i++)\n\t{\n\t\tf_i(0) = f_y(step+0);\n\t\tf_i(1) = f_y(step+1);\n\t\tf_i(2) = f_y(step+2);\n\n\t\t\n\t\tf_i_ = f_i(0)+f_i(1)+f_i(2);\n\t\tf_i_n = f_i * n_i.transpose();\n\n\n\t\td_f(step+0)  =  f_i_n(0);\t\n\t\td_f(step+1)  =  mu_friction*f_i_n(0) - (sin(acos(f_i_n(0)/f_i_)));\t\t\n\t\td_f(step+2)  =  f_i_max - f_i.norm();\n\n\t\tstep += 3;\n\t}\n\n\n\n\tdouble d_min = d_f(0);\n\t\n\tfor(int i = 0 ; i < d_f.size() ; i++)\n\t\tif( d_min > d_f(i) ) \n\t\t\td_min = d_f(i);\n\n\n\n\tEigen::VectorXd Singular ;\n\tJacobiSVD<MatrixXd> svd(G_r_k, ComputeThinU | ComputeThinV);  \n    Singular = svd.singularValues();\n\n    double sigma_max = Singular[0];\n\n    PCR = d_min / sigma_max;\n\t\t\t\n\n\n\n\tcout << \" YEAH ENJOY \" << endl;\n\tcout << \"   fine   \" << endl;\n\n\n\tros::spin();\n\treturn 0;\n}", "meta": {"hexsha": "2cdfb1edc9567579a7eca4e694dd538f86da1be6", "size": 7640, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/index_quality_PCR_PGR.cpp", "max_stars_repo_name": "lia2790/grasp-learning", "max_stars_repo_head_hexsha": "e32c58eff37c1a951e914705a916452044c1d019", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2017-11-08T12:51:50.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-26T12:17:22.000Z", "max_issues_repo_path": "src/index_quality_PCR_PGR.cpp", "max_issues_repo_name": "lia2790/grasp-learning", "max_issues_repo_head_hexsha": "e32c58eff37c1a951e914705a916452044c1d019", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/index_quality_PCR_PGR.cpp", "max_forks_repo_name": "lia2790/grasp-learning", "max_forks_repo_head_hexsha": "e32c58eff37c1a951e914705a916452044c1d019", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2017-05-30T14:59:28.000Z", "max_forks_repo_forks_event_max_datetime": "2019-12-11T13:34:27.000Z", "avg_line_length": 23.1515151515, "max_line_length": 134, "alphanum_fraction": 0.6184554974, "num_tokens": 2285, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7718434978390747, "lm_q2_score": 0.44939263446475963, "lm_q1q2_score": 0.3468607828883968}}
{"text": "#pragma once\n\n\n#include <iostream>\n\n#include <boost/container/flat_map.hpp>\n\n#include <xtensor/xoperation.hpp>\n#include <xtensor/xmath.hpp>\n#include <xtensor/xtensor.hpp>\n#include <xtensor/xexpression.hpp>\n#include <xtensor/xview.hpp>\n\n#include \"nifty/ufd/ufd.hxx\"\n#include \"nifty/graph/undirected_list_graph.hxx\"\n#include \"nifty/graph/opt/lifted_multicut/lifted_multicut_objective.hxx\"\nnamespace nifty{\nnamespace graph{\nnamespace opt{\nnamespace lifted_multicut{\n\n\n    ///\\cond\n    namespace detail_plmc{\n        template<std::size_t DIM>\n        struct EvalHelper;\n\n        template<>\n        struct EvalHelper<2>{\n\n            template<class OBJ, class D_LABELS>\n            static auto evaluate(\n                const OBJ & obj,\n                const xt::xexpression<D_LABELS> & e_labels\n            ){\n                const auto & labels = e_labels.derived_cast();\n                const auto & weights = obj.weights();\n                const auto & offsets = obj.offsets();\n                const auto & shape = obj.shape();\n                const auto & n_offsets = obj.n_offsets();\n\n                auto e = 0.0;\n\n                for(int p0=0; p0<shape[0]; ++p0)\n                for(int p1=0; p1<shape[1]; ++p1){\n                    const auto label_p = labels(p0, p1);\n                    for(int offset_index=0; offset_index<n_offsets; ++offset_index){\n                        const int q0 = p0 + offsets(offset_index, 0);\n                        const int q1 = p1 + offsets(offset_index, 1);\n                        if(q0 >= 0 && q0 < shape[0]  && q1 >= 0 && q1 < shape[1]){\n                            const auto label_q = labels(q0, q1);\n                            if(label_p != label_q){\n                                e += weights(p0, p1, offset_index);\n                            }\n                        }\n                    }\n                }\n                return e;\n            }\n        };\n    }\n    ///\\endcond\n\n\n\n\n\n\n\n\n\n\n\n\n    template<std::size_t DIM>\n    class PixelWiseLmcObjective{\n    public:\n\n        PixelWiseLmcObjective(\n        ) {\n\n        }\n        template<class D_WEIGHTS, class D_OFFSETS>\n        PixelWiseLmcObjective(\n            const xt::xexpression<D_WEIGHTS> & e_weights,\n            const xt::xexpression<D_OFFSETS> & e_offsets\n        )   \n        :   weights_(e_weights),\n            offsets_(e_offsets),\n            shape_(),\n            n_offsets_(),\n            n_variables_()\n        {\n            // shape and n_offset\n            const auto & wshape = weights_.shape();\n            std::copy(wshape.begin(), wshape.end(), shape_.begin());\n            n_offsets_ = wshape[DIM];\n\n            // n_var \n            n_variables_ = shape_[0];\n            for(auto d=1; d<DIM; ++d){\n                n_variables_ *= shape_[d];\n            }\n\n        }\n\n        template<class D_LABELS>\n        auto evaluate(\n            const xt::xexpression<D_LABELS> & e_labels\n        )const{\n            return detail_plmc::EvalHelper<DIM>::evaluate(*this, e_labels);\n        }\n        const auto & weights()const{\n            return weights_;\n        }\n        const auto & offsets()const{\n            return offsets_;\n        }\n        const auto & shape()const{\n            return shape_;\n        }\n        auto n_offsets()const{\n            return n_offsets_;\n        }\n        auto n_variables() const {\n            return n_variables_;\n        }\n    private:\n\n        xt::xtensor<int,       2, xt::layout_type::row_major> offsets_;\n        xt::xtensor<float, DIM+1, xt::layout_type::row_major> weights_;\n\n        std::array<int, DIM> shape_;\n        std::size_t n_offsets_;\n        uint64_t n_variables_;\n    };\n\n\n\n\n\n\n    template<std::size_t DIM>\n    class PixelWiseLmcConnetedComponentsFusion;\n\n    template<>\n    class PixelWiseLmcConnetedComponentsFusion<2>\n    {\n    public:\n        static const std::size_t DIM = 2;\n\n\n\n        typedef nifty::graph::UndirectedGraph<>                 CCGraphType;\n        typedef LiftedMulticutObjective<CCGraphType, double >   CCObjectiveType;\n        typedef LiftedMulticutBase<CCObjectiveType>             CCBaseType;\n        typedef typename CCBaseType::VisitorBaseType            CVisitorBaseType;\n        typedef typename CCBaseType::NodeLabelsType             CCNodeLabels;\n        // factory for the lifted primal rounder\n        typedef nifty::graph::opt::common::SolverFactoryBase<CCBaseType> CCLmcFactoryBase;\n\n\n\n\n\n\n\n\n        PixelWiseLmcConnetedComponentsFusion(\n            const PixelWiseLmcObjective<DIM> & objective,\n            std::shared_ptr<CCLmcFactoryBase> solver_fatory\n        )\n        :   objective_(objective),\n            ufd_(objective.n_variables()),\n            solver_fatory_(solver_fatory)\n        {\n\n        }\n\n\n        struct  Settings\n        {\n            \n        };\n\n\n        \n\n        template<class D_LABELS_A, class D_LABELS_B>\n        auto fuse(\n            const xt::xexpression<D_LABELS_A>  & e_labels_a,\n            const xt::xexpression<D_LABELS_B>  & e_labels_b\n        ){\n\n            ufd_.reset();\n\n            const auto & shape = objective_.shape();\n            const auto & labels_a = e_labels_a.derived_cast();\n            const auto & labels_b = e_labels_b.derived_cast();\n\n            typename xt::xtensor<int, DIM>::shape_type reshape{size_t(shape[0]), size_t(shape[1])};\n            auto res = xt::xtensor<int, DIM, xt::layout_type::row_major>(reshape);\n\n\n            this->merge_ufd(e_labels_a, e_labels_b);\n\n            // \n            auto e_a = objective_.evaluate(labels_a);\n            auto e_b = objective_.evaluate(labels_b);\n            this->do_it(res, [&](\n                const auto & cc_node_labels,\n                const auto & cc_energy\n            ){\n                if(cc_energy < std::min(e_a, e_b)){\n\n                    auto res_iter = res.begin();\n                    for(auto var=0; var<objective_.n_variables(); ++var){\n                        const auto dense_var = *res_iter;\n                        *res_iter = cc_node_labels[dense_var];\n                        //*res_iter = cc_node_labels[to_dense[ufd_.find(var)]];\n                        ++res_iter;\n                    }   \n\n                }\n                else if(e_a < cc_energy){\n                    std::copy(labels_a.begin(), labels_a.end(), res.begin());\n                }\n                else{\n                    std::copy(labels_b.begin(), labels_b.end(), res.begin());\n                }\n            });\n\n            return res;\n\n        }\n\n\n        template<class D_LABELS>\n        auto fuse(\n            const xt::xexpression<D_LABELS>  & e_labels\n        ){\n\n\n\n            ufd_.reset();\n\n            const auto & shape = objective_.shape();\n\n\n\n\n\n            typename xt::xtensor<int, DIM>::shape_type reshape{size_t(shape[0]), size_t(shape[1])};\n            auto res = xt::xtensor<int, DIM, xt::layout_type::row_major>(reshape);\n\n\n            this->merge_ufd2(e_labels);\n\n\n            // \n           \n            this->do_it(res, [&](\n                const auto & cc_node_labels,\n                const auto & cc_energy\n            ){\n                if(1){//cc_energy < std::min(e_a, e_b)){\n                    \n                    auto res_iter = res.begin();\n                    for(auto var=0; var<objective_.n_variables(); ++var){\n                        const auto dense_var = *res_iter;\n                        *res_iter = cc_node_labels[dense_var];\n                        //*res_iter = cc_node_labels[to_dense[ufd_.find(var)]];\n                        ++res_iter;\n                    }   \n\n                }\n                //else if(e_a < cc_energy){\n                //    std::copy(labels_a.begin(), labels_a.end(), res.begin());\n                //}\n                //else{\n                //    std::copy(labels_b.begin(), labels_b.end(), res.begin());\n                //}\n            });\n\n            return res;\n\n        }\n\n\n    private:\n\n\n        template<class D_LABELS_A, class D_LABELS_B>\n        auto merge_ufd(\n            const xt::xexpression<D_LABELS_A>  & e_labels_a,\n            const xt::xexpression<D_LABELS_B>  & e_labels_b\n        ){\n            const auto & shape = objective_.shape();\n            const auto & labels_a = e_labels_a.derived_cast();\n            const auto & labels_b = e_labels_b.derived_cast();\n\n            uint64_t node_p = 0;\n            for(int p0=0; p0<shape[0]; ++p0)\n            for(int p1=0; p1<shape[1]; ++p1){\n\n                const auto p_label_a = labels_a(p0, p1);\n                const auto p_label_b = labels_b(p0, p1);\n\n                if(p0 + 1 < shape[0]){\n                    const auto q_label_a = labels_a(p0+1, p1);\n                    const auto q_label_b = labels_b(p0+1, p1);\n                    if(p_label_a == q_label_a && p_label_b == q_label_b){\n                        const auto node_q = node_p + shape[1];\n                        ufd_.merge(node_p, node_q);\n                    }\n                }\n                if(p1 + 1 < shape[1]){\n                    const auto q_label_a = labels_a(p0, p1+1);\n                    const auto q_label_b = labels_b(p0, p1+1);\n                    if(p_label_a == q_label_a && p_label_b == q_label_b){\n                        const auto node_q = node_p + 1;\n                        ufd_.merge(node_p, node_q);\n                    }\n                }\n                ++node_p;\n            }\n        }\n\n\n\n\n        template<class D_LABELS>\n        auto merge_ufd2(\n            const xt::xexpression<D_LABELS>  & e_labels\n        ){\n            const auto & shape = objective_.shape();\n            const auto & labels = e_labels.derived_cast();\n            const auto n_offsets = labels.shape()[DIM];\n\n            const auto pview = xt::view(labels,0,0,xt::all());\n            const auto bla = pview(0);\n\n            //uint64_t node_p = 0;\n            //for(int p0=0; p0<shape[0]; ++p0)\n            //for(int p1=0; p1<shape[1]; ++p1){\n            //    if(p0 + 1 < shape[0]){\n            //        bool do_merge = true;\n            //        for(auto o=0; o<n_offsets; ++o){\n            //            const auto p_label = labels(p0,  p1,o);\n            //            const auto q_label = labels(p0+1,p1,o);\n            //            if(p_label != q_label ){ \n            //                do_merge = false;\n            //                break;\n            //            }\n            //        }\n            //        if(do_merge){\n            //            const auto node_q = node_p + shape[1];\n            //            ufd_.merge(node_p, node_q);\n            //        }\n            //    }\n            //    if(p1 + 1 < shape[1]){\n            //        bool do_merge = true;\n            //        for(auto o=0; o<n_offsets; ++o){\n            //            const auto p_label = labels(p0, p1,  o);\n            //            const auto q_label = labels(p0, p1+1,o);\n            //            if(p_label != q_label ){ \n            //                do_merge = false;\n            //                break;\n            //            }\n            //        }\n            //        if(do_merge){\n            //            const auto node_q = node_p + 1;\n            //            ufd_.merge(node_p, node_q);\n            //        }\n            //    }\n            //    ++node_p;\n            //}\n        }\n\n\n\n        template<class F>\n        auto do_it(\n            xt::xtensor<int, DIM, xt::layout_type::row_major> & res,\n            F && f\n        ){\n\n\n            const auto & shape = objective_.shape();\n            const auto & offsets = objective_.offsets();\n            const auto & weights = objective_.weights();\n            const auto & n_offsets = objective_.n_offsets();\n            // const auto & labels_a = e_labels_a.derived_cast();\n            // const auto & labels_b = e_labels_b.derived_cast();\n\n\n            // make map dense   \n            const auto cc_n_variables = ufd_.numberOfSets();\n            boost::container::flat_map<uint64_t, uint64_t> to_dense;\n            ufd_.representativeLabeling(to_dense);\n            {\n                auto res_iter = res.begin();\n                for(auto var=0; var<objective_.n_variables(); ++var){\n                    *res_iter = to_dense[ufd_.find(var)];\n                    ++res_iter;\n                }   \n            }\n\n\n\n            \n            // build the normal graph\n            CCGraphType cc_graph(cc_n_variables);\n\n            uint64_t node_p = 0 ;\n            for(int p0=0; p0<shape[0]; ++p0)\n            for(int p1=0; p1<shape[1]; ++p1){\n\n                const auto p_label = ufd_.find(node_p);\n\n                if(p0 + 1 < shape[0]){\n                    const auto node_q = node_p + shape[1];\n                    const auto q_label = ufd_.find(node_q);\n                    if(p_label != q_label){\n                        cc_graph.insertEdge(to_dense[p_label],to_dense[q_label]);\n                    }\n                }\n                if(p1 + 1 < shape[1]){\n                    const auto node_q = node_p + 1;\n                    const auto q_label = ufd_.find(node_q);\n                    if(p_label != q_label){\n                        cc_graph.insertEdge(to_dense[p_label],to_dense[q_label]);\n                    }\n                }\n                ++node_p;\n            }\n\n            CCObjectiveType cc_obj(cc_graph);\n\n            node_p = 0 ;\n\n            // fill the lifted obj\n            for(int p0=0; p0<shape[0]; ++p0)\n            for(int p1=0; p1<shape[1]; ++p1){\n\n                const auto p_label = ufd_.find(node_p);\n\n                for(int offset_index=0; offset_index<n_offsets; ++offset_index){\n                    const int q0 = p0 + offsets(offset_index, 0);\n                    const int q1 = p1 + offsets(offset_index, 1);\n                    if(q0 >= 0 && q0 < shape[0]  && q1 >= 0 && q1 < shape[1]){\n\n                        const auto node_q = q0*shape[1] + q1;\n                        const auto q_label = ufd_.find(node_q);\n                        if(p_label != q_label){\n\n                            cc_obj.setCost(to_dense[p_label], to_dense[q_label], \n                                weights(p0,p1,offset_index));\n                        }\n                    }\n                }\n                ++node_p;\n            }\n\n\n            auto solver = solver_fatory_->create(cc_obj);\n            CCNodeLabels cc_node_labels(cc_graph);\n\n\n            nifty::graph::opt::common::VerboseVisitor<CCBaseType> visitor;\n            solver->optimize(cc_node_labels, nullptr);\n            auto e_res = cc_obj.evalNodeLabels(cc_node_labels);\n            delete solver;  \n            f(cc_node_labels, e_res);\n        }\n\n\n        const PixelWiseLmcObjective<DIM> & objective_;\n        nifty::ufd::Ufd<uint64_t> ufd_;\n        std::shared_ptr<CCLmcFactoryBase>  solver_fatory_;\n    };\n\n\n\n\n} // namespace nifty::graph::opt::lifted_multicut\n} // namespace nifty::graph::opt\n} // namespace nifty::graph\n} // namespace nifty\n\n", "meta": {"hexsha": "046f6eb3f793a08f391cc8cdca9f326cbf9d7aa5", "size": 14854, "ext": "hxx", "lang": "C++", "max_stars_repo_path": "include/nifty/graph/opt/lifted_multicut/pixel_wise_q.hxx", "max_stars_repo_name": "k-dominik/nifty", "max_stars_repo_head_hexsha": "067e137e9c1f33cccb22052b53ff0d75c288d667", "max_stars_repo_licenses": ["MIT"], "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/nifty/graph/opt/lifted_multicut/pixel_wise_q.hxx", "max_issues_repo_name": "k-dominik/nifty", "max_issues_repo_head_hexsha": "067e137e9c1f33cccb22052b53ff0d75c288d667", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/nifty/graph/opt/lifted_multicut/pixel_wise_q.hxx", "max_forks_repo_name": "k-dominik/nifty", "max_forks_repo_head_hexsha": "067e137e9c1f33cccb22052b53ff0d75c288d667", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-02-07T09:29:26.000Z", "max_forks_repo_forks_event_max_datetime": "2018-02-07T09:29:26.000Z", "avg_line_length": 30.2525458248, "max_line_length": 99, "alphanum_fraction": 0.4714555002, "num_tokens": 3380, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7718434978390747, "lm_q2_score": 0.44939263446475963, "lm_q1q2_score": 0.3468607828883968}}
{"text": "// Copyright (C) 2014 The Regents of the University of California (Regents)\n// and Google, Inc. All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are\n// met:\n//\n//     * Redistributions of source code must retain the above 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, Google,\n//       nor the names of its contributors may be used to endorse or promote\n//       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\"\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), John Flynn (jflynn@google.com)\n\n#include \"theia/sfm/pose/four_point_relative_pose_partial_rotation.h\"\n\n#include <Eigen/Core>\n#include <Eigen/Eigenvalues>\n#include <Eigen/Geometry>\n#include <Eigen/SVD>\n#include <glog/logging.h>\n#include <limits>\n#include <math.h>\n\n#include \"theia/alignment/alignment.h\"\n\nnamespace theia {\n\nusing Eigen::AngleAxisd;\nusing Eigen::EigenSolver;\nusing Eigen::JacobiSVD;\nusing Eigen::Map;\nusing Eigen::Matrix;\nusing Eigen::Matrix3d;\nusing Eigen::Matrix4d;\nusing Eigen::Quaterniond;\nusing Eigen::Vector3d;\nusing Eigen::Vector4d;\n\nnamespace {\n\nbool SolveQEP(const Matrix4d& M,\n              const Matrix4d& C,\n              const Matrix4d& K,\n              std::vector<double>* eigenvalues,\n              std::vector<Vector4d>* eigenvectors) {\n  // Solves the quadratic eigenvalue problem:\n  //\n  //   Q(s)x = 0\n  //\n  // where:\n  //\n  //   Q(s) = s^2*M + s*C + K\n  //\n  // Returns true if the problem could be solved, false otherwise.\n  //\n  // This is converted to a generalized eigenvalue as described in:\n  //   http://en.wikipedia.org/wiki/Quadratic_eigenvalue_problem\n  //\n  // The generalized eigenvalue problem is in this form:\n  //\n  // [ C  K ]z = s[ -M  0  ]z\n  // [-I  0 ]     [ 0   -I ]\n  //\n  // With eigenvector z = [ sx ] and s is the eigenvalue.\n  //                      [  x ]\n  //\n  // The eigenvector of the quadratic eigenvalue problem can be extracted from\n  // z.\n  //\n  // Where z is the eigenvector, s is the eigenvalue.\n  // This generalized eigenvalue can be converted to a standard eigenvalue\n  // problem by multiplying by the inverse of the RHS matrix. The inverse of\n  // the RHS matrix is particularly simple:\n  //\n  // [ -inv(M)  0 ]\n  // [ 0       -I ]\n  //\n  // So the generalized eigenvalue problem reduces to a standard eigenvalue\n  // problem on the constraint matrix:\n  //\n  // [ -inv(M)C  -inv(M)K ]z = sz\n  // [ I         0        ]\n\n  Matrix4d inv_M;\n  static const double kDeterminantThreshold = 1e-7;\n  bool invert_success;\n  // Check that determinant of M is larger than threshold. This threshold only\n  // seems to be reached when there is no rotation. TODO(jflynn): verify.\n  M.computeInverseWithCheck(inv_M, invert_success, kDeterminantThreshold);\n  if (!invert_success) {\n    return false;\n  }\n\n  // Negate inverse of M.\n  inv_M = -1.0 * inv_M;\n\n  // Set up constraint matrix.\n  Matrix<double, 8, 8> constraint = Matrix<double, 8, 8>::Zero();\n  // Set upper-left to - inv(M) * C.\n  constraint.block<4, 4>(0, 0) = inv_M * C;\n  // Set upper-right to -inv(M) * K.\n  constraint.block<4, 4>(0, 4) = inv_M * K;\n  // Set lower-left to identity.\n  constraint.block<4, 4>(4, 0) = Matrix4d::Identity();\n\n  // Extract the left eigenvectors and values from the constraint matrix.\n  static const double kImagEigenValueTolerance = 1e-9;\n  EigenSolver<Matrix<double, 8, 8> > eig_solver(constraint);\n\n  for (int i = 0; i < 8; i++) {\n    // Only consider the real eigenvalues and corresponding eigenvectors.\n    if (fabs(eig_solver.eigenvalues()[i].imag()) < kImagEigenValueTolerance) {\n      eigenvalues->push_back(eig_solver.eigenvalues()[i].real());\n      eigenvectors->push_back(\n          Vector4d(eig_solver.eigenvectors().col(i).tail(4).real()));\n    }\n  }\n  return true;\n}\n\n}  // namespace\n\nvoid FourPointRelativePosePartialRotation(\n    const Vector3d& axis,\n    const Vector3d image_one_ray_directions[4],\n    const Vector3d image_one_ray_origins[4],\n    const Vector3d image_two_ray_directions[4],\n    const Vector3d image_two_ray_origins[4],\n    std::vector<Quaterniond>* soln_rotations,\n    std::vector<Vector3d>* soln_translations) {\n  CHECK_DOUBLE_EQ(axis.squaredNorm(), 1.0);\n  CHECK_NOTNULL(soln_rotations)->clear();\n  CHECK_NOTNULL(soln_translations)->clear();\n\n  // The generalized epipolar constraint between two sets of rays in different\n  // coordinate systems (two generalized cameras).\n  //\n  // The rays are converted to plucker coordinates:\n  //   L = [ q  ]\n  //       [ p  ]\n  //\n  // Assuming the first coordinate system has zero rotation and translation,\n  // the constraint is:\n  //\n  //   q2' * [t]x R * q1 + q2' * R * p1 + q1' * R * p2 = 0\n  //\n  // v' means transpose v, t is unknown translation, [t]x is the matrix\n  // cross product form.\n  //\n  // Re-arranging to isolate t:\n  //\n  //   -(q2 x (R * q1))' * t + q2' * R * p1 + q1' * R' * p2 = 0\n  //\n  // In vector form:\n  //\n  //  [-(q2 x (R * q1))', q2' * R * p1 + q1' * R' * p2 ] * [ t ] = 0\n  //                                                       [ 1 ]\n  //\n  // Each correspondence gives another constraint and the constraints can\n  // be stacked to create a constraint matrix.\n  //\n  // The rotation matrix R can be parameterized, up to scale factor, as:\n  //\n  //   R ~ 2 * (v * v' + s[v]x) + (s^2 - 1)I\n  //\n  //   I = Identity matrix.\n  //\n  // where is v is the known (unit length) axis and s is related to the\n  // unknown angle of rotation.\n  //\n  // The epipolar constraint holds if the rotation matrix is scaled, so the\n  // rotation matrix parameterization above can be used. Each row of the\n  // constraint matrix is thus a function of s^2 and s, so the constraint can be\n  // written as:\n  //\n  //   [ M * s^2 + C *s + k ] * [ t ] = 0\n  //                            [ 1 ]\n  //\n  // This is standard quadratic eigenvalue problem (QEP) and is solved using\n  // standard methods.\n\n  // Creates the matrices for the QEP problem.\n  Matrix4d M;\n  Matrix4d C;\n  Matrix4d K;\n  for (int i = 0; i < 4; ++i) {\n    const Vector3d& q1(image_one_ray_directions[i]);\n    const Vector3d p1(image_one_ray_origins[i].cross(q1));\n    const Vector3d& q2(image_two_ray_directions[i]);\n    const Vector3d p2(image_two_ray_origins[i].cross(q2));\n\n    M.row(i).head(3) = -q2.cross(q1);\n    M.row(i)[3] = q2.dot(p1) + q1.dot(p2);\n\n    C.row(i).head(3) = -2.0 * q2.cross(axis.cross(q1));\n    C.row(i)[3] = -2.0 * (q1.dot(axis.cross(p2)) - q2.dot(axis.cross(p1)));\n\n    K.row(i).head(3) = -(2.0 * q1.dot(axis) * q2.cross(axis) - q2.cross(q1));\n    K.row(i)[3] =\n        -q2.dot(p1) - q1.dot(p2) +\n        2.0 * (q2.dot(axis) * p1.dot(axis) + q1.dot(axis) * p2.dot(axis));\n  }\n\n  std::vector<double> eigenvalues;\n  std::vector<Vector4d> eigenvectors;\n  static const double kWTolerance = 1e-7;\n  if (SolveQEP(M, C, K, &eigenvalues, &eigenvectors)) {\n    // Extracts the translations and rotations from the eigenvalues and\n    // eigenvectors of the QEP problem.\n    for (int i = 0; i < eigenvalues.size(); ++i) {\n      if (fabs(eigenvectors[i].w()) > kWTolerance) {\n        Quaterniond quat(eigenvalues[i], axis[0], axis[1], axis[2]);\n        quat.normalize();\n        soln_rotations->push_back(quat);\n        soln_translations->push_back(\n            Vector3d(eigenvectors[i].x() / eigenvectors[i].w(),\n                     eigenvectors[i].y() / eigenvectors[i].w(),\n                     eigenvectors[i].z() / eigenvectors[i].w()));\n      }\n    }\n  } else {\n    // When there is zero rotation the vector part of the quaternion disappears\n    // and it becomes ([0], 1) (where [0] is the zero vector) and the SolveQEP\n    // method cannot be used.\n    // However from the equations for M, C, and K above we can see that the\n    // C and K matrices contain the axis, which is 0 assuming zero rotation,\n    // so to solve for the translation we can directly extract the null space\n    // of M.\n    // Alternatively this can be derived directly from the generalized epipolar\n    // constraint, after substituting identity for the rotation matrix.\n    eigenvectors.clear();\n\n    JacobiSVD<Matrix4d> svd = M.jacobiSvd(Eigen::ComputeFullV);\n    const Vector4d eigenvector(svd.matrixV().col(3));\n\n    if (fabs(eigenvector[3]) > kWTolerance) {\n      soln_rotations->push_back(Quaterniond(AngleAxisd(0.0, axis)));\n      soln_translations->push_back(Vector3d(eigenvector[0] / eigenvector[3],\n                                            eigenvector[1] / eigenvector[3],\n                                            eigenvector[2] / eigenvector[3]));\n    }\n  }\n}\n\n}  // namespace theia\n", "meta": {"hexsha": "36d7ba9efa098356ec36fa3bc8033829b4fbeaf4", "size": 9842, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/theia/sfm/pose/four_point_relative_pose_partial_rotation.cc", "max_stars_repo_name": "urbste/pyTheiaSfM", "max_stars_repo_head_hexsha": "814034c96b602fef1dc76ae6692278d61179ebcc", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2021-11-10T19:50:36.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-03T08:16:54.000Z", "max_issues_repo_path": "src/theia/sfm/pose/four_point_relative_pose_partial_rotation.cc", "max_issues_repo_name": "urbste/TheiaSfM", "max_issues_repo_head_hexsha": "a92fa27e90b6182e2a2511a46d24283afad1a995", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/theia/sfm/pose/four_point_relative_pose_partial_rotation.cc", "max_forks_repo_name": "urbste/TheiaSfM", "max_forks_repo_head_hexsha": "a92fa27e90b6182e2a2511a46d24283afad1a995", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-03-20T03:06:55.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-04T08:08:52.000Z", "avg_line_length": 36.723880597, "max_line_length": 80, "alphanum_fraction": 0.6474293843, "num_tokens": 2738, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7217432182679956, "lm_q2_score": 0.48047867804790706, "lm_q1q2_score": 0.34678222740344855}}
{"text": "/*\n [auto_generated]\n boost/numeric/odeint/stepper/adams_moulton.hpp\n\n [begin_description]\n Implementation of the Adams-Moulton method. This is method is not a real stepper, it is more a helper class\n which computes the corrector step in the Adams-Bashforth-Moulton method.\n [end_description]\n\n Copyright 2011-2012 Karsten Ahnert\n Copyright 2011-2013 Mario Mulansky\n Copyright 2012 Christoph Koke\n\n Distributed under the Boost Software License, Version 1.0.\n (See accompanying file LICENSE_1_0.txt or\n copy at http://www.boost.org/LICENSE_1_0.txt)\n */\n\n\n#ifndef BOOST_NUMERIC_ODEINT_STEPPER_ADAMS_MOULTON_HPP_INCLUDED\n#define BOOST_NUMERIC_ODEINT_STEPPER_ADAMS_MOULTON_HPP_INCLUDED\n\n\n#include <boost/numeric/odeint/util/bind.hpp>\n\n#include <boost/numeric/odeint/algebra/range_algebra.hpp>\n#include <boost/numeric/odeint/algebra/default_operations.hpp>\n#include <boost/numeric/odeint/algebra/algebra_dispatcher.hpp>\n#include <boost/numeric/odeint/algebra/operations_dispatcher.hpp>\n\n#include <boost/numeric/odeint/util/state_wrapper.hpp>\n#include <boost/numeric/odeint/util/is_resizeable.hpp>\n#include <boost/numeric/odeint/util/resizer.hpp>\n\n#include <boost/numeric/odeint/stepper/stepper_categories.hpp>\n#include <boost/numeric/odeint/stepper/runge_kutta4_classic.hpp>\n\n#include <boost/numeric/odeint/stepper/detail/adams_moulton_call_algebra.hpp>\n#include <boost/numeric/odeint/stepper/detail/adams_moulton_coefficients.hpp>\n#include <boost/numeric/odeint/stepper/detail/rotating_buffer.hpp>\n\n\n\n\nnamespace boost {\nnamespace numeric {\nnamespace odeint {\n\n\n/*\n * Static implicit Adams-Moulton multistep-solver without step size control and without dense output.\n */\ntemplate<\nsize_t Steps ,\nclass State ,\nclass Value = double ,\nclass Deriv = State ,\nclass Time = Value ,\nclass Algebra = typename algebra_dispatcher< State >::algebra_type ,\nclass Operations = typename operations_dispatcher< State >::operations_type ,\nclass Resizer = initially_resizer\n>\nclass adams_moulton\n{\nprivate:\n\n\npublic :\n\n    typedef State state_type;\n    typedef state_wrapper< state_type > wrapped_state_type;\n    typedef Value value_type;\n    typedef Deriv deriv_type;\n    typedef state_wrapper< deriv_type > wrapped_deriv_type;\n    typedef Time time_type;\n    typedef Algebra algebra_type;\n    typedef Operations operations_type;\n    typedef Resizer resizer_type;\n    typedef stepper_tag stepper_category;\n\n    typedef adams_moulton< Steps , State , Value , Deriv , Time , Algebra , Operations , Resizer > stepper_type;\n\n    static const size_t steps = Steps;\n\n    typedef unsigned short order_type;\n    static const order_type order_value = steps + 1;\n\n    typedef detail::rotating_buffer< wrapped_deriv_type , steps > step_storage_type;\n\n    adams_moulton( )\n    : m_coefficients() , m_dxdt() , m_resizer() ,\n      m_algebra_instance() , m_algebra( m_algebra_instance )\n    { }\n\n    adams_moulton( algebra_type &algebra )\n    : m_coefficients() , m_dxdt() , m_resizer() ,\n      m_algebra_instance() , m_algebra( algebra )\n    { }\n\n    adams_moulton& operator=( const adams_moulton &stepper )\n    {\n        m_dxdt = stepper.m_dxdt;\n        m_resizer = stepper.m_resizer;\n        m_algebra = stepper.m_algebra;\n        return *this;\n    }\n\n    order_type order( void ) const { return order_value; }\n\n\n    /*\n     * Version 1 : do_step( system , x , t , dt , buf );\n     *\n     * solves the forwarding problem\n     */\n    template< class System , class StateInOut , class StateIn , class ABBuf >\n    void do_step( System system , StateInOut &x , StateIn const & pred , time_type t , time_type dt , const ABBuf &buf )\n    {\n        do_step( system , x , pred , t , x , dt , buf );\n    }\n\n    template< class System , class StateInOut , class StateIn , class ABBuf >\n    void do_step( System system , const StateInOut &x , StateIn const & pred , time_type t , time_type dt , const ABBuf &buf )\n    {\n        do_step( system , x , pred , t , x , dt , buf );\n    }\n\n\n\n    /*\n     * Version 2 : do_step( system , in , t , out , dt , buf );\n     *\n     * solves the forwarding problem\n     */\n    template< class System , class StateIn , class PredIn , class StateOut , class ABBuf >\n    void do_step( System system , const StateIn &in , const PredIn &pred , time_type t , StateOut &out , time_type dt , const ABBuf &buf )\n    {\n        do_step_impl( system , in , pred , t , out , dt , buf );\n    }\n\n    template< class System , class StateIn , class PredIn , class StateOut , class ABBuf >\n    void do_step( System system , const StateIn &in , const PredIn &pred , time_type t , const StateOut &out , time_type dt , const ABBuf &buf )\n    {\n        do_step_impl( system , in , pred , t , out , dt , buf );\n    }\n\n\n\n    template< class StateType >\n    void adjust_size( const StateType &x )\n    {\n        resize_impl( x );\n    }\n\n    algebra_type& algebra()\n    {   return m_algebra; }\n\n    const algebra_type& algebra() const\n    {   return m_algebra; }\n\n\nprivate:\n\n\n    template< class System , class StateIn , class PredIn , class StateOut , class ABBuf >\n    void do_step_impl( System system , const StateIn &in , const PredIn &pred , time_type t , StateOut &out , time_type dt , const ABBuf &buf )\n    {\n        typename odeint::unwrap_reference< System >::type &sys = system;\n        m_resizer.adjust_size( in , detail::bind( &stepper_type::template resize_impl<StateIn> , detail::ref( *this ) , detail::_1 ) );\n        sys( pred , m_dxdt.m_v , t );\n        detail::adams_moulton_call_algebra< steps , algebra_type , operations_type >()( m_algebra , in , out , m_dxdt.m_v , buf , m_coefficients , dt );\n    }\n\n\n    template< class StateIn >\n    bool resize_impl( const StateIn &x )\n    {\n        return adjust_size_by_resizeability( m_dxdt , x , typename is_resizeable<deriv_type>::type() );\n    }\n\n\n    const detail::adams_moulton_coefficients< value_type , steps > m_coefficients;\n    wrapped_deriv_type m_dxdt;\n    resizer_type m_resizer;\n\nprotected:\n\n    algebra_type m_algebra_instance;\n    algebra_type &m_algebra;\n};\n\n\n\n\n} // odeint\n} // numeric\n} // boost\n\n\n\n#endif // BOOST_NUMERIC_ODEINT_STEPPER_ADAMS_MOULTON_HPP_INCLUDED\n", "meta": {"hexsha": "05b42777355be822ecb34a300207fb2c8c254c79", "size": 6112, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "contrib/libboost/boost_1_62_0/boost/numeric/odeint/stepper/adams_moulton.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/odeint/stepper/adams_moulton.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/odeint/stepper/adams_moulton.hpp", "max_forks_repo_name": "189569400/ClickHouse", "max_forks_repo_head_hexsha": "0b8683c8c9f0e17446bef5498403c39e9cb483b8", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1343.0, "max_forks_repo_forks_event_min_datetime": "2017-12-08T19:47:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-26T11:31:36.000Z", "avg_line_length": 30.2574257426, "max_line_length": 152, "alphanum_fraction": 0.7035340314, "num_tokens": 1572, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6297746074044134, "lm_q2_score": 0.5506073655352404, "lm_q1q2_score": 0.3467585374639343}}
{"text": "#ifndef _CELERITE2_REVERSE_HPP_DEFINED_\n#define _CELERITE2_REVERSE_HPP_DEFINED_\n\n#include <Eigen/Core>\n#include \"internal.hpp\"\n\nnamespace celerite2 {\nnamespace core {\n\ntemplate <typename Input, typename Coeffs, typename Diag, typename LowRank, typename Work, typename InputOut, typename CoeffsOut, typename DiagOut,\n          typename LowRankOut>\nvoid factor_rev(const Eigen::MatrixBase<Input> &t,           // (N,)\n                const Eigen::MatrixBase<Coeffs> &c,          // (J,)\n                const Eigen::MatrixBase<Diag> &a,            // (N,)\n                const Eigen::MatrixBase<LowRank> &U,         // (N, J)\n                const Eigen::MatrixBase<LowRank> &V,         // (N, J)\n                const Eigen::MatrixBase<Diag> &d,            // (N,)\n                const Eigen::MatrixBase<LowRank> &W,         // (N, J)\n                const Eigen::MatrixBase<Work> &S,            // (N, J*J)\n                const Eigen::MatrixBase<Diag> &bd,           // (N,)\n                const Eigen::MatrixBase<LowRank> &bW,        // (N, J)\n                Eigen::MatrixBase<InputOut> const &bt_out,   // (N,)\n                Eigen::MatrixBase<CoeffsOut> const &bc_out,  // (J,)\n                Eigen::MatrixBase<DiagOut> const &ba_out,    // (N,)\n                Eigen::MatrixBase<LowRankOut> const &bU_out, // (N, J)\n                Eigen::MatrixBase<LowRankOut> const &bV_out  // (N, J)\n\n) {\n  UNUSED(a);\n  UNUSED(V);\n\n  ASSERT_ROW_MAJOR(Work);\n\n  typedef typename Diag::Scalar Scalar;\n  typedef typename Eigen::Matrix<Scalar, LowRank::ColsAtCompileTime, LowRank::ColsAtCompileTime> Inner;\n  typedef typename Eigen::internal::plain_col_type<Coeffs>::type CoeffVector;\n\n  Eigen::Index N = U.rows(), J = U.cols();\n  CAST_VEC(InputOut, bt, N);\n  CAST_VEC(CoeffsOut, bc, J);\n  CAST_VEC(DiagOut, ba, N);\n  CAST_MAT(LowRankOut, bU, N, J);\n  CAST_MAT(LowRankOut, bV, N, J);\n\n  // Make local copies of the gradients that we need\n  Inner Sn(J, J), bS(J, J);\n  Eigen::Map<typename Eigen::internal::plain_row_type<Work>::type> ptr(Sn.data(), 1, J * J);\n  Eigen::Matrix<Scalar, LowRank::ColsAtCompileTime, 1> bSWT;\n  CoeffVector p(J), bp(J);\n\n  Scalar dt, factor;\n  bS.setZero();\n  bt.setZero();\n  bc.setZero();\n  ba.noalias() = bd;\n  bV.noalias() = bW;\n  bV.array().colwise() /= d.array();\n  for (Eigen::Index n = N - 1; n > 0; --n) {\n    dt = t(n - 1) - t(n);\n    p  = exp(c.array() * dt);\n\n    ptr = S.row(n);\n\n    // Step 6\n    ba(n) -= W.row(n) * bV.row(n).transpose();\n    bU.row(n).noalias() = -(bV.row(n) + 2.0 * ba(n) * U.row(n)) * Sn * p.asDiagonal();\n    bS.noalias() -= U.row(n).transpose() * (bV.row(n) + ba(n) * U.row(n));\n\n    // Step 4\n    bp.array() = (bS * Sn + Sn.transpose() * bS).diagonal().array() * p.array();\n    bc.noalias() += dt * bp;\n    factor = (c.array() * bp.array()).sum();\n    bt(n) -= factor;\n    bt(n - 1) += factor;\n\n    // Step 3\n    bS   = p.asDiagonal() * bS * p.asDiagonal();\n    bSWT = bS * W.row(n - 1).transpose();\n    ba(n - 1) += W.row(n - 1) * bSWT;\n    bV.row(n - 1).noalias() += W.row(n - 1) * (bS + bS.transpose());\n  }\n\n  bU.row(0).setZero();\n  ba(0) -= bV.row(0) * W.row(0).transpose();\n}\n\ntemplate <typename Input, typename Coeffs, typename LowRank, typename RightHandSide, typename Work, typename InputOut, typename CoeffsOut,\n          typename LowRankOut, typename RightHandSideOut>\nvoid solve_lower_rev(const Eigen::MatrixBase<Input> &t,                // (N,)\n                     const Eigen::MatrixBase<Coeffs> &c,               // (J,)\n                     const Eigen::MatrixBase<LowRank> &U,              // (N, J)\n                     const Eigen::MatrixBase<LowRank> &W,              // (N, J)\n                     const Eigen::MatrixBase<RightHandSide> &Y,        // (N, nrhs)\n                     const Eigen::MatrixBase<RightHandSide> &Z,        // (N, nrhs)\n                     const Eigen::MatrixBase<Work> &F,                 // (N, J*nrhs)\n                     const Eigen::MatrixBase<RightHandSide> &bZ,       // (N, nrhs)\n                     Eigen::MatrixBase<InputOut> const &bt_out,        // (N,)\n                     Eigen::MatrixBase<CoeffsOut> const &bc_out,       // (J,)\n                     Eigen::MatrixBase<LowRankOut> const &bU_out,      // (N, J)\n                     Eigen::MatrixBase<LowRankOut> const &bW_out,      // (N, J)\n                     Eigen::MatrixBase<RightHandSideOut> const &bY_out // (N, nrhs)\n) {\n  ASSERT_ROW_MAJOR(Work);\n\n  Eigen::Index N = t.rows(), J = c.rows();\n  CAST_VEC(InputOut, bt, N);\n  CAST_VEC(CoeffsOut, bc, J);\n  CAST_MAT(LowRankOut, bU, N, J);\n  CAST_MAT(LowRankOut, bW, N, J);\n  CAST_BASE(RightHandSideOut, bY);\n\n  bt.setZero();\n  bc.setZero();\n  bU.setZero();\n  bW.setZero();\n  bY = bZ;\n  internal::forward_rev<true>(t, c, U, W, Y, Z, F, bY, bt, bc, bU, bW, bY);\n}\n\ntemplate <typename Input, typename Coeffs, typename LowRank, typename RightHandSide, typename Work, typename InputOut, typename CoeffsOut,\n          typename LowRankOut, typename RightHandSideOut>\nvoid solve_upper_rev(const Eigen::MatrixBase<Input> &t,                // (N,)\n                     const Eigen::MatrixBase<Coeffs> &c,               // (J,)\n                     const Eigen::MatrixBase<LowRank> &U,              // (N, J)\n                     const Eigen::MatrixBase<LowRank> &W,              // (N, J)\n                     const Eigen::MatrixBase<RightHandSide> &Y,        // (N, nrhs)\n                     const Eigen::MatrixBase<RightHandSide> &Z,        // (N, nrhs)\n                     const Eigen::MatrixBase<Work> &F,                 // (N, J*nrhs)\n                     const Eigen::MatrixBase<RightHandSide> &bZ,       // (N, nrhs)\n                     Eigen::MatrixBase<InputOut> const &bt_out,        // (N,)\n                     Eigen::MatrixBase<CoeffsOut> const &bc_out,       // (J,)\n                     Eigen::MatrixBase<LowRankOut> const &bU_out,      // (N, J)\n                     Eigen::MatrixBase<LowRankOut> const &bW_out,      // (N, J)\n                     Eigen::MatrixBase<RightHandSideOut> const &bY_out // (N, nrhs)\n) {\n  ASSERT_ROW_MAJOR(Work);\n\n  Eigen::Index N = t.rows(), J = c.rows();\n  CAST_VEC(InputOut, bt, N);\n  CAST_VEC(CoeffsOut, bc, J);\n  CAST_MAT(LowRankOut, bU, N, J);\n  CAST_MAT(LowRankOut, bW, N, J);\n  CAST_BASE(RightHandSideOut, bY);\n\n  bt.setZero();\n  bc.setZero();\n  bU.setZero();\n  bW.setZero();\n  bY = bZ;\n  internal::backward_rev<true>(t, c, U, W, Y, Z, F, bY, bt, bc, bU, bW, bY);\n}\n\ntemplate <typename Input, typename Coeffs, typename LowRank, typename RightHandSide, typename Work, typename InputOut, typename CoeffsOut,\n          typename LowRankOut, typename RightHandSideOut>\nvoid matmul_lower_rev(const Eigen::MatrixBase<Input> &t,                // (N,)\n                      const Eigen::MatrixBase<Coeffs> &c,               // (J,)\n                      const Eigen::MatrixBase<LowRank> &U,              // (N, J)\n                      const Eigen::MatrixBase<LowRank> &V,              // (N, J)\n                      const Eigen::MatrixBase<RightHandSide> &Y,        // (N, nrhs)\n                      const Eigen::MatrixBase<RightHandSide> &Z,        // (N, nrhs)\n                      const Eigen::MatrixBase<Work> &F,                 // (N, J*nrhs)\n                      const Eigen::MatrixBase<RightHandSide> &bZ,       // (N, nrhs)\n                      Eigen::MatrixBase<InputOut> const &bt_out,        // (N,)\n                      Eigen::MatrixBase<CoeffsOut> const &bc_out,       // (J,)\n                      Eigen::MatrixBase<LowRankOut> const &bU_out,      // (N, J)\n                      Eigen::MatrixBase<LowRankOut> const &bV_out,      // (N, J)\n                      Eigen::MatrixBase<RightHandSideOut> const &bY_out // (N, nrhs)\n) {\n  ASSERT_ROW_MAJOR(Work);\n\n  Eigen::Index N = t.rows(), J = c.rows();\n  CAST_VEC(InputOut, bt, N);\n  CAST_VEC(CoeffsOut, bc, J);\n  CAST_MAT(LowRankOut, bU, N, J);\n  CAST_MAT(LowRankOut, bV, N, J);\n  CAST_MAT(RightHandSideOut, bY, N, Y.cols());\n\n  bt.setZero();\n  bc.setZero();\n  bU.setZero();\n  bV.setZero();\n  bY.setZero();\n  internal::forward_rev<false>(t, c, U, V, Y, Z, F, bZ, bt, bc, bU, bV, bY);\n}\n\ntemplate <typename Input, typename Coeffs, typename LowRank, typename RightHandSide, typename Work, typename InputOut, typename CoeffsOut,\n          typename LowRankOut, typename RightHandSideOut>\nvoid matmul_upper_rev(const Eigen::MatrixBase<Input> &t,                // (N,)\n                      const Eigen::MatrixBase<Coeffs> &c,               // (J,)\n                      const Eigen::MatrixBase<LowRank> &U,              // (N, J)\n                      const Eigen::MatrixBase<LowRank> &V,              // (N, J)\n                      const Eigen::MatrixBase<RightHandSide> &Y,        // (N, nrhs)\n                      const Eigen::MatrixBase<RightHandSide> &Z,        // (N, nrhs)\n                      const Eigen::MatrixBase<Work> &F,                 // (N, J*nrhs)\n                      const Eigen::MatrixBase<RightHandSide> &bZ,       // (N, nrhs)\n                      Eigen::MatrixBase<InputOut> const &bt_out,        // (N,)\n                      Eigen::MatrixBase<CoeffsOut> const &bc_out,       // (J,)\n                      Eigen::MatrixBase<LowRankOut> const &bU_out,      // (N, J)\n                      Eigen::MatrixBase<LowRankOut> const &bV_out,      // (N, J)\n                      Eigen::MatrixBase<RightHandSideOut> const &bY_out // (N, nrhs)\n) {\n  ASSERT_ROW_MAJOR(Work);\n\n  Eigen::Index N = t.rows(), J = c.rows();\n  CAST_VEC(InputOut, bt, N);\n  CAST_VEC(CoeffsOut, bc, J);\n  CAST_MAT(LowRankOut, bU, N, J);\n  CAST_MAT(LowRankOut, bV, N, J);\n  CAST_MAT(RightHandSideOut, bY, N, Y.cols());\n\n  bt.setZero();\n  bc.setZero();\n  bU.setZero();\n  bV.setZero();\n  bY.setZero();\n  internal::backward_rev<false>(t, c, U, V, Y, Z, F, bZ, bt, bc, bU, bV, bY);\n}\n\n} // namespace core\n} // namespace celerite2\n\n#endif // _CELERITE2_REVERSE_HPP_DEFINED_\n", "meta": {"hexsha": "c69a9bf848d3c311b073ddd6ce4eebd0b4a45270", "size": 9893, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "c++/include/celerite2/reverse.hpp", "max_stars_repo_name": "jacksonloper/celerite2", "max_stars_repo_head_hexsha": "e413e28dc43ba33e67960b51a9cbbac43c2f58df", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 38.0, "max_stars_repo_stars_event_min_datetime": "2020-10-10T02:43:53.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T09:59:21.000Z", "max_issues_repo_path": "c++/include/celerite2/reverse.hpp", "max_issues_repo_name": "jacksonloper/celerite2", "max_issues_repo_head_hexsha": "e413e28dc43ba33e67960b51a9cbbac43c2f58df", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 34.0, "max_issues_repo_issues_event_min_datetime": "2020-10-06T18:50:47.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-28T10:33:04.000Z", "max_forks_repo_path": "c++/include/celerite2/reverse.hpp", "max_forks_repo_name": "jacksonloper/celerite2", "max_forks_repo_head_hexsha": "e413e28dc43ba33e67960b51a9cbbac43c2f58df", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2020-11-09T18:12:54.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-03T20:20:59.000Z", "avg_line_length": 44.3632286996, "max_line_length": 147, "alphanum_fraction": 0.5369453149, "num_tokens": 2923, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7520125737597972, "lm_q2_score": 0.46101677931231594, "lm_q1q2_score": 0.34669041475710716}}
{"text": "//==================================================================================================\n/*!\n  @file\n  @copyright 2016 NumScale SAS\n  @copyright 2016 J.T. Lapreste\n\n  Distributed under the Boost Software License, Version 1.0.\n  (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\n*/\n//==================================================================================================\n#ifndef BOOST_SIMD_ARCH_COMMON_SIMD_FUNCTION_GAMMALN_HPP_INCLUDED\n#define BOOST_SIMD_ARCH_COMMON_SIMD_FUNCTION_GAMMALN_HPP_INCLUDED\n\n#include <boost/simd/function/std.hpp>\n#include <boost/simd/arch/common/detail/generic/gammaln_kernel.hpp>\n\n#include <boost/simd/constant/half.hpp>\n#include <boost/simd/constant/inf.hpp>\n#include <boost/simd/constant/invpi.hpp>\n#include <boost/simd/constant/logpi.hpp>\n#include <boost/simd/constant/logsqrt2pi.hpp>\n#include <boost/simd/constant/minf.hpp>\n#include <boost/simd/constant/mone.hpp>\n#include <boost/simd/constant/nan.hpp>\n#include <boost/simd/constant/one.hpp>\n#include <boost/simd/constant/two.hpp>\n#include <boost/simd/constant/three.hpp>\n#include <boost/simd/constant/zero.hpp>\n\n\n#include <boost/simd/constant/pi.hpp>\n#include <boost/simd/constant/two.hpp>\n\n#include <boost/simd/function/abs.hpp>\n#include <boost/simd/function/any.hpp>\n#include <boost/simd/function/dec.hpp>\n#include <boost/simd/function/floor.hpp>\n#include <boost/simd/function/fma.hpp>\n#include <boost/simd/function/if_dec.hpp>\n#include <boost/simd/function/if_else.hpp>\n#include <boost/simd/function/if_inc.hpp>\n#include <boost/simd/function/if_minus.hpp>\n#include <boost/simd/function/if_nan_else.hpp>\n#include <boost/simd/function/if_plus.hpp>\n#include <boost/simd/function/is_equal.hpp>\n#include <boost/simd/function/is_flint.hpp>\n#include <boost/simd/function/is_less.hpp>\n#include <boost/simd/function/is_lez.hpp>\n#include <boost/simd/function/log.hpp>\n#include <boost/simd/function/logical_and.hpp>\n#include <boost/simd/function/logical_andnot.hpp>\n#include <boost/simd/function/logical_or.hpp>\n#include <boost/simd/function/nbtrue.hpp>\n#include <boost/simd/function/sinpi.hpp>\n#include <boost/simd/function/sqr.hpp>\n\n\n#include <boost/simd/meta/as_logical.hpp>\n#include <boost/simd/detail/dispatch/function/overload.hpp>\n#include <boost/simd/detail/dispatch/meta/scalar_of.hpp>\n#include <boost/config.hpp>\n#include <cmath>\n\nnamespace boost { namespace simd { namespace ext\n{\n  namespace bd = boost::dispatch;\n  namespace bs = boost::simd;\n  BOOST_DISPATCH_OVERLOAD_IF ( gammaln_\n                             , (typename A0, typename X)\n                             , (detail::is_native<X>)\n                             , bd::cpu_\n                             , bs::pack_< bd::single_<A0>, X>\n                             )\n  {\n    using sA0 = bd::scalar_of_t<A0>;\n    A0 operator() (const A0& a0) const BOOST_NOEXCEPT\n    {\n      auto inf_result = logical_and(is_lez(a0), is_flint(a0));\n      A0 x = if_nan_else(inf_result, a0);\n      A0 q = bs::abs(x);\n      #ifndef BOOST_SIMD_NO_INFINITES\n      inf_result = logical_or(is_equal(x, Inf<A0>()), inf_result);\n      #endif\n      auto ltza0 = is_ltz(a0);\n      size_t nb = bs::nbtrue(ltza0);\n      A0 r;\n      A0 r1 =  other(q);\n      if(nb > 0)\n      {\n        //treat negative\n        r = bs::if_else(inf_result, Inf<A0>(), negative(q, r1));\n        if (nb >= A0::static_size) return r;\n      }\n      A0 r2 = if_else(ltza0, r, r1);\n      return bs::if_else(is_equal(a0, Minf<A0>()),\n                          Nan<A0>(),\n                          bs::if_else(inf_result, Inf<A0>(), r2)\n                         );\n    }\n  private :\n    using lA0 = bs::as_logical_t<A0>;\n    static inline A0 negative(const A0& q,  const A0& w)\n    {\n      A0 p = bs::floor(q);\n      A0 z = q - p;\n      auto test2 = is_less(z, bs::Half<A0>() );\n      z = bs::if_minus(test2, z, bs::One<A0>());\n      z = q*bs::sinpi(z);\n      z =  bs::abs(z);\n      return -log(Invpi<A0>()*bs::abs(z))-w;\n    }\n    static inline A0 other(const A0& x)\n    {\n      auto xlt650 = is_less(x,A0(6.50) );\n      size_t nb = nbtrue(xlt650);\n      A0 r0x = x;\n      A0 r0z = x;\n      A0 r0s = One<A0>();\n      A0 r1 = Zero<A0>();\n      A0 p =  Nan<A0>();\n      if (nb > 0)\n      {\n        auto kernelC = False<lA0>();\n        A0 z = One<A0>();\n        A0 tx = if_else_zero(xlt650, x);\n        A0 nx = Zero<A0>();\n\n        const A0 _075 = A0(0.75);\n        const A0 _150 = A0(1.50);\n        const A0 _125 = A0(1.25);\n        const A0 _250 = A0(2.50);\n        auto xge150 = is_greater_equal(x, _150);\n        auto txgt250= is_greater(tx,_250);\n\n        // x >= 1.5\n        while (bs::any(logical_and(xge150, txgt250)))\n        {\n          nx = if_dec(txgt250, nx);\n          tx = if_else(txgt250, x + nx, tx);\n          z = if_else(txgt250, z*tx, z);\n          txgt250= is_greater(tx,_250);\n        }\n        r0x = if_plus(xge150, x, nx - Two<A0>());\n        r0z = if_else(xge150, z, r0z);\n        r0s = if_else(xge150,One<A0>(), r0s);\n\n        // x >= 1.25 && x < 1.5\n        auto xge125 = is_greater_equal(x, _125);\n        auto xge125t = logical_andnot(xge125, xge150);\n        if (bs::any(xge125))\n        {\n          r0x =  if_else(xge125t, dec(x)    , r0x);\n          r0z =  if_else(xge125t, z*x       , r0z);\n          r0s =  if_else(xge125t, Mone<A0>(), r0s);\n        }\n        // x >= 0.75&& x < 1.5\n        auto xge075  = is_greater_equal(x, _075);\n        auto xge075t = logical_andnot(xge075, xge125);\n        if (bs::any(xge075t))\n        {\n          kernelC =  xge075t;\n          r0x =  if_else(xge075t, dec(x)    , r0x);\n          r0z =  if_else(xge075t, One<A0>() , r0z);\n          r0s =  if_else(xge075t, Mone<A0>(), r0s);\n          p = detail::gammaln_kernel<A0>::gammalnC(r0x);\n        }\n        // tx < 1.5 && x < 0.75\n        auto txlt150 = logical_andnot(is_less(tx,_150), xge075);\n        if (bs::any(txlt150))\n        {\n          auto orig = txlt150;\n          while( bs::any(txlt150) )\n          {\n            z  = if_else(txlt150, z*tx, z);\n            nx = if_inc(txlt150, nx);\n            tx = if_else(txlt150, x + nx, tx);\n            txlt150= logical_andnot(is_less(tx,_150), xge075);\n          }\n          r0x =  if_plus(orig, r0x, nx - Two<A0>());\n          r0z =  if_else(orig,z         , r0z);\n          r0s =  if_else(orig,Mone<A0>(), r0s);\n        }\n        p =  if_else(kernelC, p, detail::gammaln_kernel<A0>::gammalnB(r0x));\n        if (nb >= A0::static_size)\n          return fma(r0x, p, r0s*bs::log(bs::abs(r0z)));\n      }\n      r0z = if_else(xlt650, bs::abs(r0z), x);\n      A0 m = bs::log(r0z);\n      r1 = fma(r0x, p, r0s*m);\n      A0 r2 = fma(x-Half<A0>(),m,Logsqrt2pi<A0>()-x);\n      r2 += detail::gammaln_kernel<A0>::gammaln2(rec(sqr(x)))/x;\n      return if_else(xlt650, r1, r2);\n    }\n  };\n  BOOST_DISPATCH_OVERLOAD_IF ( gammaln_\n                             , (typename A0, typename X)\n                             , (detail::is_native<X>)\n                             , bd::cpu_\n                             , bs::pack_< bd::double_<A0>, X >\n                             )\n  {\n    BOOST_FORCEINLINE A0 operator() (const A0& a0) const BOOST_NOEXCEPT\n    {\n      auto inf_result = logical_and(is_lez(a0), is_flint(a0));\n      A0 x = if_nan_else(inf_result, a0);\n      A0 q = bs::abs(x);\n      #ifndef BOOST_SIMD_NO_INFINITES\n      inf_result = is_equal(q, Inf<A0>());\n      #endif\n      auto test = is_less(a0, A0(-34.0));\n      size_t nb = bs::nbtrue(test);\n      A0 r =  Nan<A0>();\n      if(nb > 0)\n      {\n        //treat negative large with reflection\n        r = large_negative(q);\n        if (nb >= A0::static_size)\n          return bs::if_else(inf_result, Nan<A0>(), r);\n      }\n      A0 r1 = other(a0);\n      A0 r2 = if_else(test, r, r1);\n      return bs::if_else(is_equal(a0, Minf<A0>()),\n                          Nan<A0>(),\n                          bs::if_else(inf_result, Inf<A0>(), r2)\n                         );\n    }\n  private :\n    static inline A0 large_negative(const A0& q)\n    {\n      A0 w = gammaln(q);\n      A0 p = bs::floor(q);\n      A0 z = q - p;\n      auto test2 = is_less(z, bs::Half<A0>() );\n      z = bs::if_minus(test2, z, bs::One<A0>());\n      z = q*bs::sinpi(z);\n      z =  bs::abs(z);\n      return Logpi<A0>()-log(z)-w;\n    }\n    static inline A0 other(const A0& xx)\n    {\n      A0 x =  xx;\n      auto test = is_less(x, A0(13.0) );\n      size_t nb = nbtrue(test);\n      A0 r1 = Zero<A0>();\n      if (nb > 0)\n      {\n        A0 z = One<A0>();\n        A0 p = Zero<A0>();\n        A0 u = if_else_zero(test, x);\n        auto test1 = is_greater_equal(u,Three<A0>());\n        while(bs::any(test1))\n        {\n          p = if_dec(test1, p);\n          u = if_else(test1, x+p, u);\n          z = if_else(test1, z*u, z);\n          test1 = is_greater_equal(u,Three<A0>());\n        }\n        //all u are less than 3\n        auto test2 = is_less(u,Two<A0>());\n\n        while(bs::any(test2))\n        {\n          z = if_else(test2, z/u, z);\n          p = if_inc(test2, p);\n          u = if_else(test2, x+p, u);\n          test2 = is_less(u,Two<A0>());\n        }\n        z = bs::abs(z);\n        x +=  p-Two<A0>();\n        r1 = x * detail::gammaln_kernel<A0>::gammaln1(x)+bs::log(z);\n        if (nb >= A0::static_size) return r1;\n      }\n      A0 r2 = fma(xx-Half<A0>(),bs::log(xx), Logsqrt2pi<A0>()-xx);\n      A0 p = rec(sqr(xx));\n      r2 += detail::gammaln_kernel<A0>::gammalnA(p)/xx;\n      return if_else(test, r1, r2);\n    }\n  };\n\n} } }\n\n\n#endif\n", "meta": {"hexsha": "2cdda438add67b25908881f3da4332346f31f0c2", "size": 9461, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/arch/common/simd/function/gammaln.hpp", "max_stars_repo_name": "xmar/pythran", "max_stars_repo_head_hexsha": "dbf2e8b70ed1e4d4ac6b5f26ead4add940a72592", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2018-02-20T11:21:12.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-12T13:45:09.000Z", "max_issues_repo_path": "third_party/boost/simd/arch/common/simd/function/gammaln.hpp", "max_issues_repo_name": "xmar/pythran", "max_issues_repo_head_hexsha": "dbf2e8b70ed1e4d4ac6b5f26ead4add940a72592", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "third_party/boost/simd/arch/common/simd/function/gammaln.hpp", "max_forks_repo_name": "xmar/pythran", "max_forks_repo_head_hexsha": "dbf2e8b70ed1e4d4ac6b5f26ead4add940a72592", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2017-12-12T12:29:52.000Z", "max_forks_repo_forks_event_max_datetime": "2019-04-08T15:55:25.000Z", "avg_line_length": 33.3133802817, "max_line_length": 100, "alphanum_fraction": 0.5352499736, "num_tokens": 2885, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7520125737597972, "lm_q2_score": 0.46101677931231594, "lm_q1q2_score": 0.34669041475710716}}
{"text": "/*\n * Copyright (c) 2013-2020 Masahide Kashiwagi (kashi@waseda.jp)\n */\n\n#ifndef OPTIMIZE_HPP\n#define OPTIMIZE_HPP\n\n#include <iostream>\n#include <list>\n#include <limits>\n#include <kv/interval.hpp>\n#include <kv/rdouble.hpp>\n#include <kv/interval-vector.hpp>\n#include <boost/numeric/ublas/vector.hpp>\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/io.hpp>\n#include <kv/autodif.hpp>\n\n\n// 0: Do not use TRIM\n// 1: use TRIM and use slow trim algorithm\n// 2: use TRIM and use fast bat slightly inefficient trim algorithm\n// 3: use TRIM and use new trim algorithm\n\n#ifndef OPTIMIZE_TRIM\n#define OPTIMIZE_TRIM 0\n#endif\n\n#ifndef OPTIMIZE_ZERODIVIDE\n#define OPTIMIZE_ZERODIVIDE 2\n#endif\n\n\nnamespace kv {\n\nnamespace ub = boost::numeric::ublas;\n\n\n// change scalar function f to -f\ntemplate <class F> struct Opt_MakeMinus {\n\tF f;\n\tOpt_MakeMinus(F f) : f(f) {}\n\ttemplate <class T> T operator()(const ub::vector<T>& x) {\n\t\treturn -f(x);\n\t}\n};\n\n// change scalar function T -> T\n// to 1-dimentional vector function T^1 -> T\ntemplate <class F> struct Opt_MakeVec {\n\tF f;\n\tOpt_MakeVec(F f) : f(f) {}\n\ttemplate <class T> T operator()(const ub::vector<T>& x) {\n\t\treturn f(x(0));\n\t}\n};\n\n\ntemplate <class T, class F>\nstd::list< ub::vector< interval<T> > >\noptimize(const ub::vector< interval<T> >& init, F f, T limit, bool unify = true, int verbose = 0)\n{\n\tstd::list< ub::vector< interval<T> > > targets;\n\ttargets.push_back(init);\n\treturn optimize_list(targets, f, limit, unify, verbose);\n}\n\ntemplate <class T, class F>\nstd::list< ub::vector< interval<T> > >\noptimize_list(std::list< ub::vector< interval<T> > > targets, F f, T limit, bool unify = true, int verbose = 0)\n{\n\tint s = (targets.front()).size();\n\tub::vector< interval<T> > I, C, I1, I2, IR, fdi, C2;\n\tinterval<T> fc, fi, mvf, fc2; \n\tT tmp, tmp2;\n\tstd::list< ub::vector< interval<T> > > solutions;\n\ttypename std::list< ub::vector< interval<T> > >::iterator p;\n\tint i, j, k, mi;\n\tbool flag, errflag;\n\tinterval<T> A, B, J, J2, Itmp; \n#if OPTIMIZE_TRIM == 3\n\tub::vector< interval<T> > A0, A1, A2; // for new trim algorithm\n#endif // OPTIMIZE_TRIM == 3\n\n\tC2.resize(s);\n\n\tT delta = std::numeric_limits<T>::max();\n\n\twhile (!targets.empty()) {\n\t\tI = targets.front();\n\t\ttargets.pop_front();\n\t\terrflag = false; // evaluation error occurs or not\n\n\t\ttry {\n\t\t\tfi = f(I);\n\t\t}\n\t\tcatch (std::domain_error& e) {\n\t\t\terrflag = true;\n\t\t\tgoto label;\n\t\t}\n\n\t\tif (fi.lower() > delta) {\n\t\t\tcontinue;\n\t\t}\n\n\t\tC = mid(I);\n\t\ttry {\n\t\t\tfc = f(C);\n\t\t\tautodif< interval<T> >::split(f(autodif< interval<T> >::init(I)), fi, fdi);\n\t\t}\n\t\tcatch (std::domain_error& e) {\n\t\t\t// errflag = true;\n\t\t\tgoto label;\n\t\t}\n\n\t\tfdi.resize(s); // prepare for constant f\n\t\tmvf = fc + inner_prod(fdi, I - C);\n\t\tif (mvf.lower() > delta) {\n\t\t\tcontinue;\n\t\t}\n\n\t\t// update delta at C\n\t\ttmp = fc.upper();\n\t\tif (tmp < delta) delta = tmp;\n\n\t\t// C2 is likely to give small value\n\t\tfor (i=0; i<s; i++) {\n\t\t\ttmp = mid(fdi(i));\n\t\t\tif (tmp > 0.) tmp2 = I(i).lower();\n\t\t\telse if (tmp < 0.) tmp2 = I(i).upper();\n\t\t\telse tmp2 = mid(I(i));\n\t\t\tC2(i).assign(tmp2, tmp2);\n\t\t}\n\n\t\t// update delta at C2\n\t\ttry {\n\t\t\tfc2 = f(C2);\n\t\t}\n\t\tcatch (std::domain_error& e) {\n\t\t\t// errflag = true;\n\t\t\tgoto label;\n\t\t}\n\t\ttmp = fc2.upper();\n\t\tif (tmp < delta) delta = tmp;\n\n#if OPTIMIZE_TRIM >= 1\n\t\t// interval shrinking\n\n#if OPTIMIZE_TRIM == 3\n\t\t// prepare for new trim algorithm\n\t\tA0.resize(s);\n\t\tA1.resize(s);\n\t\tA2.resize(s);\n\t\tfor (j=0; j<s; j++) {\n\t\t\tA0(j) = fdi(j) * (I(j)-C(j));\n\t\t}\n\t\tItmp = 0.;\n\t\tfor (j=0; j<s; j++) {\n\t\t\tA1(j) = Itmp;\n\t\t\tItmp += A0(j);\n\t\t}\n\t\tItmp = 0.;\n\t\tfor (j=s-1; j>=0; j--) {\n\t\t\tA2(j) = Itmp;\n\t\t\tItmp += A0(j);\n\t\t}\n#endif // OPTIMIZE_TRIM == 3\n\n\t\tIR = I;\n\t\tflag = false; // non-existence in I turns out or not\n\t\tfor (j=0; j<s; j++) {\n\t\t\tB = fdi(j);\n\n#if OPTIMIZE_TRIM == 1\n\t\t\t// calculate A simply\n\t\t\t// simple but slow\n\t\t\tA = 0.;\n\t\t\tfor (k=0; k<s; k++) {\n\t\t\t\tif (k == j) continue;\n\t\t\t\tA += fdi(k) * (I(k)-C(k));\n\t\t\t}\n\t\t\tA += fc;\n#endif // OPTIMIZE_TRIM == 1\n#if OPTIMIZE_TRIM == 2\n\t\t\t// old trim algorithm\n\t\t\t// calculate back A from mvf\n\t\t\tA = mvf;\n\t\t\tItmp = B * (I(j)-C(j));\n\t\t\trop<T>::begin();\n\t\t\ttmp = rop<T>::sub_down(A.lower(), Itmp.lower());\n\t\t\ttmp2 = rop<T>::sub_up(A.upper(), Itmp.upper());\n\t\t\trop<T>::end();\n\t\t\tA.assign(tmp, tmp2);\n#endif // OPTIMIZE_TRIM == 2\n#if OPTIMIZE_TRIM == 3\n\t\t\t// new trim algorithm\n\t\t\tA = fc + A1(j) + A2(j);\n#endif // OPTIMIZE_TRIM == 3\n\n\t\t\t// A -= delta;\n\t\t\tA -= interval<T>(-std::numeric_limits<T>::infinity(), delta);\n\n\t\t\tif (zero_in(B)) {\n#if OPTIMIZE_ZERODIVIDE >= 1\n\t\t\t\tbool bdummy;\n\t\t\t\tif (rad(B) <= 0) continue;\n\t\t\t\tJ = C(j) - division_part1(A, B, bdummy);\n\t\t\t\tJ2 = C(j) - division_part2(A, B);\n\t\t\t\tif (overlap(IR(j), J)) {\n\t\t\t\t\tif (overlap(IR(j), J2)) {\n#if OPTIMIZE_ZERODIVIDE == 2\n\t\t\t\t\t\tif (overlap(J, J2)) continue;\n\t\t\t\t\t\t// interval division\n\t\t\t\t\t\tI1 = IR;\n\t\t\t\t\t\tI2 = IR;\n\t\t\t\t\t\tI1(j) = intersect(IR(j), J);\n\t\t\t\t\t\tI2(j) = intersect(IR(j), J2);\n\t\t\t\t\t\ttargets.push_back(I1);\n\t\t\t\t\t\ttargets.push_back(I2);\n\t\t\t\t\t\tflag = true;\n\t\t\t\t\t\tbreak;\n#else\n\t\t\t\t\t\tcontinue;\n#endif\n\t\t\t\t\t} else {\n\t\t\t\t\t\tIR(j) = intersect(IR(j), J);\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tif (overlap(IR(j), J2)) {\n\t\t\t\t\t\tIR(j) = intersect(IR(j), J2);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tflag = true;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n#else\n\t\t\t\tcontinue;\n#endif\n\t\t\t} else {\n\t\t\t\tJ = C(j) - A/B;\n\t\t\t\tif (overlap(IR(j), J)) {\n\t\t\t\t\tIR(j) = intersect(IR(j), J);\n\t\t\t\t} else {\n\t\t\t\t\tflag = true;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// non-existence in I turns out\n\t\tif (flag == true) {\n\t\t\tcontinue;\n\t\t}\n\n\t\tI = IR;\n\n#endif // OPTIMIZE_TRIM >= 1\n\n\t\tlabel:;\n\n\t\ttmp2 = 0.;\n\t\tfor (i=0; i<s; i++) {\n\t\t\ttmp = width(I(i));\n\t\t\tif (tmp > tmp2) {\n\t\t\t\ttmp2 = tmp; mi = i;\n\t\t\t}\n\t\t}\n\n\t\tif (tmp2 < limit && errflag == false) {\n\t\t\tif (verbose >= 1) {\n\t\t\t\tstd::cout << I << \"\\n\";\n\t\t\t}\n\t\t\tif (unify) {\n\t\t\t\twhile (true) {\n\t\t\t\t\tflag = false;\n                                        p = solutions.begin();\n\t\t\t\t\twhile (p != solutions.end()) {\n\t\t\t\t\t\tif (overlap(*p, I)) {\n\t\t\t\t\t\t\tI = hull(I, *p);\n\t\t\t\t\t\t\tp = solutions.erase(p);\n\t\t\t\t\t\t\tflag = true;\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tp++;\n\t\t\t\t\t}\n\t\t\t\t\tif (flag == false) break;\n\t\t\t\t}\n\t\t\t}\n\t\t\tsolutions.push_back(I);\n\t\t\tcontinue;\n\t\t}\n\n\t\ttmp = mid(I(mi));\n\t\tI1 = I; I2 = I;\n\t\tI1(mi).assign(I1(mi).lower(), tmp);\n\t\tI2(mi).assign(tmp, I2(mi).upper());\n\t\ttargets.push_back(I1);\n\t\ttargets.push_back(I2);\n\t}\n\n\tif (verbose >= 1) {\n\t\tstd::cout << delta << \"\\n\";\n\t}\n\n\treturn solutions;\n}\n\n// rename of optimize\ntemplate <class T, class F>\nstd::list< ub::vector< interval<T> > >\nminimize(const ub::vector< interval<T> >& x, F f, T limit, bool unify = true, int verbose = 0)\n{\n        return optimize(x, f, limit, unify, verbose);\n}\n\n// specify maximum number of subdivision instead of width limit\ntemplate <class T, class F>\nstd::list< ub::vector< interval<T> > >\nminimize(const ub::vector< interval<T> >& x, F f, int n = 1000, bool unify = true, int verbose = 0)\n{\n\tint i;\n\tT tmp;\n\ttmp = 1.;\n\tfor (i=0; i<x.size(); i++) {\n\t\ttmp *= width(x(i));\n\t}\n\tT limit = (T)std::pow(tmp / n, 1.0/x.size());\n        return minimize(x, f, limit, unify, verbose);\n}\n\n// return only mininum value\ntemplate <class T, class F>\ninterval<T>\nminimize_value(const ub::vector< interval<T> >& x, F f, T limit, int verbose = 0) {\n\tstd::list< ub::vector< interval<T> > > result;\n\ttypename std::list< ub::vector< interval<T> > >::iterator p;\n\tT ret_l, ret_u;\n\tinterval<T> tmp;\n\n\tret_l = std::numeric_limits<T>::infinity();\n\tret_u = std::numeric_limits<T>::infinity();\n\n\tresult = minimize(x, f, limit, false, verbose); // disable unify\n\tp = result.begin();\n\twhile (p != result.end()) {\n\t\ttmp = f(*p);\n\t\tret_u = std::min(ret_u, tmp.upper());\n\t\tret_l = std::min(ret_l, tmp.lower());\n\t\tp++;\n\t}\n\n\treturn kv::interval<T>(ret_l, ret_u);\n}\n\n// return only mininum value\n// specify maximum number of subdivision instead of width limit\ntemplate <class T, class F>\ninterval<T>\nminimize_value(const ub::vector< interval<T> >& x, F f, int n = 1000, int verbose = 0) {\n\tstd::list< ub::vector< interval<T> > > result;\n\ttypename std::list< ub::vector< interval<T> > >::iterator p;\n\tT ret_l, ret_u;\n\tinterval<T> tmp;\n\n\tret_l = std::numeric_limits<T>::infinity();\n\tret_u = std::numeric_limits<T>::infinity();\n\n\tresult = minimize(x, f, n, false, verbose); // disable unify\n\tp = result.begin();\n\twhile (p != result.end()) {\n\t\ttmp = f(*p);\n\t\tret_u = std::min(ret_u, tmp.upper());\n\t\tret_l = std::min(ret_l, tmp.lower());\n\t\tp++;\n\t}\n\n\treturn kv::interval<T>(ret_l, ret_u);\n}\n\n// maximize/maximize_value\n\ntemplate <class T, class F>\nstd::list< ub::vector< interval<T> > >\nmaximize(const ub::vector< interval<T> >& x, F f, T limit, bool unify = true, int verbose = 0)\n{\n        return minimize(x, Opt_MakeMinus<F>(f), limit, unify, verbose);\n}\n\ntemplate <class T, class F>\nstd::list< ub::vector< interval<T> > >\nmaximize(const ub::vector< interval<T> >& x, F f, int n = 1000, bool unify = true, int verbose = 0)\n{\n        return minimize(x, Opt_MakeMinus<F>(f), n, unify, verbose);\n}\n\ntemplate <class T, class F>\ninterval<T>\nmaximize_value(const ub::vector< interval<T> >& x, F f, T limit, int verbose = 0) {\n\treturn -minimize_value(x, Opt_MakeMinus<F>(f), limit, verbose);\n}\n\ntemplate <class T, class F>\ninterval<T>\nmaximize_value(const ub::vector< interval<T> >& x, F f, int n = 1000, int verbose = 0) {\n\treturn -minimize_value(x, Opt_MakeMinus<F>(f), n, verbose);\n}\n\n// one dimensional version of minimize/minimize_value\n\ntemplate <class T, class F>\nstd::list< interval<T> >\nminimize(const interval<T>& x, F f, T limit, bool unify = true, int verbose = 0)\n{\n\tOpt_MakeVec<F> g(f);\n\tub::vector< interval<T> > v(1);\n\tstd::list< ub::vector< interval<T> > > result;\n\ttypename std::list< ub::vector< interval<T> > >::iterator p;\n\tstd::list< interval<T> > result2;\n\tv(0) = x;\n        result = minimize(v, g, limit, unify, verbose);\n\tp = result.begin();\n\twhile (p != result.end()) {\n\t\tresult2.push_back((*(p++))(0));\n\t}\n\treturn result2;\n}\n\ntemplate <class T, class F>\nstd::list< interval<T> >\nminimize(const interval<T>& x, F f, int n = 1000, bool unify = true, int verbose = 0)\n{\n\tOpt_MakeVec<F> g(f);\n\tub::vector< interval<T> > v(1);\n\tstd::list< ub::vector< interval<T> > > result;\n\ttypename std::list< ub::vector< interval<T> > >::iterator p;\n\tstd::list< interval<T> > result2;\n\tv(0) = x;\n        result = minimize(v, g, n, unify, verbose);\n\tp = result.begin();\n\twhile (p != result.end()) {\n\t\tresult2.push_back((*(p++))(0));\n\t}\n\treturn result2;\n}\n\ntemplate <class T, class F>\ninterval<T>\nminimize_value(const interval<T>& x, F f, T limit, int verbose = 0) {\n\tOpt_MakeVec<F> g(f);\n\tub::vector< interval<T> > v(1);\n\tv(0) = x;\n\treturn minimize_value(v, g, limit, verbose);\n}\n\ntemplate <class T, class F>\ninterval<T>\nminimize_value(const interval<T>& x, F f, int n = 1000, int verbose = 0) {\n\tOpt_MakeVec<F> g(f);\n\tub::vector< interval<T> > v(1);\n\tv(0) = x;\n\treturn minimize_value(v, g, n, verbose);\n}\n\n// one dimensional version of maximize/maximize_value\n\ntemplate <class T, class F>\nstd::list< interval<T> >\nmaximize(const interval<T>& x, F f, T limit, bool unify = true, int verbose = 0)\n{\n\tOpt_MakeVec<F> g(f);\n\tub::vector< interval<T> > v(1);\n\tstd::list< ub::vector< interval<T> > > result;\n\ttypename std::list< ub::vector< interval<T> > >::iterator p;\n\tstd::list< interval<T> > result2;\n\tv(0) = x;\n        result = maximize(v, g, limit, unify, verbose);\n\tp = result.begin();\n\twhile (p != result.end()) {\n\t\tresult2.push_back((*(p++))(0));\n\t}\n\treturn result2;\n}\n\ntemplate <class T, class F>\nstd::list< interval<T> >\nmaximize(const interval<T>& x, F f, int n = 1000, bool unify = true, int verbose = 0)\n{\n\tOpt_MakeVec<F> g(f);\n\tub::vector< interval<T> > v(1);\n\tstd::list< ub::vector< interval<T> > > result;\n\ttypename std::list< ub::vector< interval<T> > >::iterator p;\n\tstd::list< interval<T> > result2;\n\tv(0) = x;\n        result = maximize(v, g, n, unify, verbose);\n\tp = result.begin();\n\twhile (p != result.end()) {\n\t\tresult2.push_back((*(p++))(0));\n\t}\n\treturn result2;\n}\n\ntemplate <class T, class F>\ninterval<T>\nmaximize_value(const interval<T>& x, F f, T limit, int verbose = 0) {\n\tOpt_MakeVec<F> g(f);\n\tub::vector< interval<T> > v(1);\n\tv(0) = x;\n\treturn maximize_value(v, g, limit, verbose);\n}\n\ntemplate <class T, class F>\ninterval<T>\nmaximize_value(const interval<T>& x, F f, int n = 1000, int verbose = 0) {\n\tOpt_MakeVec<F> g(f);\n\tub::vector< interval<T> > v(1);\n\tv(0) = x;\n\treturn maximize_value(v, g, n, verbose);\n}\n\n} // namespace kv\n\n#endif // OPTIMIZE_HPP\n", "meta": {"hexsha": "1719895c58c8d3a7d610e61b4d32fbc437cb11a1", "size": 12383, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "kv/optimize.hpp", "max_stars_repo_name": "soonho-tri/kv", "max_stars_repo_head_hexsha": "4963be6560d8600cdc9ff22d004b2b965ae7b1df", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "kv/optimize.hpp", "max_issues_repo_name": "soonho-tri/kv", "max_issues_repo_head_hexsha": "4963be6560d8600cdc9ff22d004b2b965ae7b1df", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "kv/optimize.hpp", "max_forks_repo_name": "soonho-tri/kv", "max_forks_repo_head_hexsha": "4963be6560d8600cdc9ff22d004b2b965ae7b1df", "max_forks_repo_licenses": ["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.6768642447, "max_line_length": 111, "alphanum_fraction": 0.5954130663, "num_tokens": 4065, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.6477982043529716, "lm_q1q2_score": 0.3466358012164157}}
{"text": "//   Copyright 2015 Patrick Putnam\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 ASSORTATIVE_SELECTOR_HPP_\n#define ASSORTATIVE_SELECTOR_HPP_\n\n#include <boost/random/discrete_distribution.hpp>\n#include <boost/random/uniform_real_distribution.hpp>\n#include <boost/math/constants/constants.hpp>\n#include <cmath>\n\n#include <iterator>\n#include <cmath>\n#include <cassert>\n#include <iostream>\n\ntemplate < class URNG >\nstruct assortative_selector {\n    typedef URNG rng_type;\n    typedef unsigned int result_type;\n\n    typedef boost::random::discrete_distribution< result_type, double > dist_type;\n\n    typedef std::vector< std::pair< double, unsigned int > > population_fitness_type;\n    typedef typename population_fitness_type::iterator      fitness_iterator;\n\n    static const unsigned int BIN_SIZE = 100;\n    static const unsigned int BIN_COUNT = 100;\n\n    rng_type * m_rng;\n    dist_type m_dist;\n    boost::random::uniform_real_distribution< double > m_uniform;\n\n    unsigned int m_next_bin;\n\n    population_fitness_type m_pop_fit;\n    std::vector< size_t >   m_bin_sizes;\n\n    struct simple_comp {\n        bool operator()( const std::pair< double, unsigned int > & lhs, const std::pair< double, unsigned int > & rhs ) {\n            return (lhs.first < rhs.first);\n        }\n    };\n\n    assortative_selector( const assortative_selector< URNG > & other ) :\n        m_rng( other.m_rng)\n        , m_dist( other.m_dist )\n        , m_uniform()\n        , m_next_bin( other.m_next_bin )\n        , m_pop_fit( other.m_pop_fit )\n        , m_bin_sizes( other.m_bin_sizes )\n    {}\n\n\n    template < class Iter >\n    assortative_selector( rng_type & rng, Iter first, Iter last ) :\n        m_rng( &rng )\n        , m_dist()\n        , m_uniform()\n        , m_next_bin( -1 )\n        , m_pop_fit()\n    {\n        init_method2( first, last );\n    }\n\n    /// allows selfing\n    unsigned int operator()() {\n        unsigned int bstart = 0, bsize = 0;\n        if( m_next_bin == -1 ) {\n            unsigned int bin_idx = m_dist( *m_rng );\n            unsigned int bin_y = (int) ((sqrt( 8 * bin_idx + 1) - 1) / 2);\n            m_next_bin = bin_idx - (( bin_y + 1 ) * (bin_y) / 2);\n\n            bstart = (( bin_y == 0 ) ? 0 : m_bin_sizes[ bin_y - 1] );\n            bsize  = m_bin_sizes[ bin_y ] - bstart;\n//            if( bsize == 0 ) {\n//                std::cerr << bin_y << \", \" << m_bin_sizes[bin_y] << std::endl;\n//                std::cerr << \"Bin Start: \" << bstart << \"; Bin Size: \" << bsize << std::endl;\n//                std::cerr << m_bin_sizes[bin_y] << std::endl;\n//                std::cerr << m_dist.probabilities()[ bin_y ] << std::endl;\n//                assert( false );\n//            }\n        } else {\n            bstart = (( m_next_bin == 0 ) ? 0 : m_bin_sizes[ m_next_bin - 1] );\n            bsize =  m_bin_sizes[m_next_bin] - bstart;\n            m_next_bin = -1;\n        }\n\n        if( bsize == 0 ) {\n            std::cerr << \"Bin Start: \" << bstart << \"; Bin Size: \" << bsize << std::endl;\n            assert( false );\n        }\n\n        double r = m_uniform( *m_rng );\n        return m_pop_fit[ bstart + r * bsize ].second;\n    }\n\n    virtual ~assortative_selector() {}\nprotected:\n\n    template < class Iter >\n    void init_method1( Iter first, Iter last ) {\n        unsigned int N = 0;\n        while( first != last ) {\n            m_pop_fit.push_back( std::make_pair( *first, N++ ) );\n            ++first;\n        }\n\n        simple_comp comp;\n\n        std::sort( m_pop_fit.begin(), m_pop_fit.end(), comp );\n\n        std::vector< double > bin_mean;\n        if( m_pop_fit.size() % BIN_SIZE ) {\n            bin_mean.reserve( m_pop_fit.size() / BIN_SIZE + 1 );\n        } else {\n            bin_mean.reserve( m_pop_fit.size() / BIN_SIZE );\n        }\n\n        fitness_iterator pit = m_pop_fit.begin();\n        double accum = 0.0;\n        unsigned int b = BIN_SIZE;\n\n        unsigned int bin_size_accum = 0;\n        while( pit != m_pop_fit.end() ) {\n            accum += pit->first;\n            if( ! --b ) {\n                bin_mean.push_back( accum / (double) BIN_SIZE );\n                bin_size_accum += BIN_SIZE;\n                m_bin_sizes.push_back( bin_size_accum );\n                accum = 0.0;\n                b = BIN_SIZE;\n            }\n            ++pit;\n        }\n\n        if( b != BIN_SIZE ) {\n            bin_mean.push_back( accum / (BIN_SIZE - b) );\n            bin_size_accum += (BIN_SIZE - b);\n            m_bin_sizes.push_back( bin_size_accum );\n        }\n        assert(m_bin_sizes.back() == N );\n\n        init_discrete_distribution( bin_mean );\n    }\n\n    template < class Iter >\n    void init_method2( Iter first, Iter last ) {\n//        std::cerr << \"Init method 2 \" << std::endl;\n        unsigned int N = 0;\n        double min_fit = 2.0, max_fit = 0.0;\n        while( first != last ) {\n            m_pop_fit.push_back( std::make_pair( *first, N++ ) );\n\n            if( *first > max_fit ) {\n                max_fit = *first;\n            }\n\n            if( *first < min_fit ) {\n                min_fit = *first;\n            }\n            ++first;\n        }\n\n        simple_comp comp;\n        std::sort( m_pop_fit.begin(), m_pop_fit.end(), comp );\n\n        std::vector< double > bin_mean;\n        bin_mean.reserve( BIN_COUNT );\n        m_bin_sizes.reserve( BIN_COUNT );\n\n//        double bin_size = (max_fit - min_fit) / (double) BIN_COUNT;\n        if( max_fit == min_fit) { \n            // all individuals have the same fitness\n            // therefore all bins have same average fitness\n            // divide population into BIN_COUNT bins\n                                                            // if N = 101 && BIN_COUNT = 100 then\n            unsigned int ind_per_bin = (N / BIN_COUNT);     // ind_per_bin = 1\n            unsigned int b = BIN_COUNT;                     // b = 100\n            unsigned int n = N % BIN_COUNT;                 // n = 1\n            unsigned int baccum = 0;\n\n            while( n-- ) {                                  // single round\n                // N - (BIN_COUNT - 1) * ind_per_bin \n                bin_mean.push_back( max_fit );\n                baccum += (ind_per_bin + 1);\n                m_bin_sizes.push_back( baccum ); // push_back(1 + 1)\n                --b;                                        // b = 99\n            }\n\n            while( b-- ) {                                  // 99 rounds\n                bin_mean.push_back( max_fit );              //\n                baccum += (ind_per_bin);                    //\n                m_bin_sizes.push_back( baccum );            // push_back( )\n            }\n                                                            // | m_bin_sizes | = | < 2, 3, 4, 5, ..., 100, 101 > | = 100\n        } else {\n            double bin_step = (1.0000001 * max_fit - min_fit) / (double)(BIN_COUNT);\n            fitness_iterator pit = m_pop_fit.begin();\n            double accum = 0.0, bin_max = min_fit + bin_step;\n\n//            std::cerr << \"Bin Range: <\" << min_fit << \", \" << max_fit << \", \"  << bin_step << \" >\" << std::endl;\n\n            unsigned int count = 0, bin_size_accum = 0;\n            while( pit != m_pop_fit.end() ) {\n                if( pit->first >= bin_max ) {\n                \n                    bin_mean.push_back( accum / (double) count );\n                    bin_size_accum += count;\n                    m_bin_sizes.push_back( bin_size_accum );\n\n                    accum = 0.0;\n                    count = 0;\n                    bin_max += bin_step;\n\n                    // advance to next containing bin\n                    while( pit->first >= bin_max ) {\n                        bin_mean.push_back( 0.0 );\n                        m_bin_sizes.push_back( bin_size_accum );\n                        bin_max += bin_step;\n                    }\n                }\n                accum += pit->first;\n                ++count;\n\n                ++pit;\n            }\n            if( bin_size_accum < (double) N ) {\n                bin_mean.push_back( accum / (double) count );\n                bin_size_accum += count;\n                assert( bin_size_accum == (double) N );\n\n                m_bin_sizes.push_back( bin_size_accum );\n            }\n        }\n\n//        std::cerr << \"Last two bin sizes: \" << m_bin_sizes[ m_bin_sizes.size() - 2] << \", \" << m_bin_sizes.back() << std::endl;\n        assert( m_bin_sizes.back() == N);\n//        std::cerr << \"bin count: \" << bin_mean.size() << std::endl;\n        assert( bin_mean.size() == BIN_COUNT );\n\n        init_discrete_distribution( bin_mean );\n    }\n\n    void init_discrete_distribution( std::vector< double > & bin_mean ) {\n        // N * (N + 1) / 2\n//        std::cerr << \"Bin Mean Size: \" << bin_mean.size() << std::endl;\n        unsigned int bin_pairs = bin_mean.size() * (bin_mean.size() + 1)  / 2;\n        assert( bin_pairs != -1 );\n\n        std::vector< double > pairs( bin_pairs, 0.0);\n        std::vector< double >::iterator it = pairs.begin();\n        std::vector< double >::iterator y = bin_mean.begin();\n        while( y != bin_mean.end() ) {\n            double fit = *y;\n            ++y;\n            std::vector<double>::iterator x = bin_mean.begin();\n            while( x != y ) {\n                (*it) = prob2( fit, (*x) );\n                ++it;\n                ++x;\n            }\n        }\n\n        assert( it == pairs.end() );\n\n        typename dist_type::param_type p(pairs.begin(), pairs.end());\n        m_dist.param(p);\n    }\n\n    double prob1( double x, double y ) {\n        return x * y;\n    }\n\n    double prob2( double x, double y, double mu = 0.0, double sigma = 1.0 ) {\n        double res = x * y;\n        if( res == 0.0 ) return 0.0;\n\n        double coeff = (1.0/sigma) * boost::math::double_constants::one_div_root_two_pi;\n        double var = sigma * sigma;\n\n        res = ( (1.0 - res) - mu); // (1 - xy) - mu\n        res *= res;\n        res /= (2.0 * var);\n\n        return coeff * exp(-res);\n    }\n};\n\n#endif  // ASSORTATIVE_SELECTOR_HPP_\n", "meta": {"hexsha": "0335e5507b3a49a7ac2ca898eb89dd4f7db45111", "size": 10477, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/clotho/genetics/assortative_selector.hpp", "max_stars_repo_name": "putnampp/clotho", "max_stars_repo_head_hexsha": "6dbfd82ef37b4265381cd78888cd6da8c61c68c2", "max_stars_repo_licenses": ["ECL-2.0", "Apache-2.0"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2015-06-16T21:27:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-25T23:26:54.000Z", "max_issues_repo_path": "include/clotho/genetics/assortative_selector.hpp", "max_issues_repo_name": "putnampp/clotho", "max_issues_repo_head_hexsha": "6dbfd82ef37b4265381cd78888cd6da8c61c68c2", "max_issues_repo_licenses": ["ECL-2.0", "Apache-2.0"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2015-06-16T21:12:42.000Z", "max_issues_repo_issues_event_max_datetime": "2015-06-23T12:41:00.000Z", "max_forks_repo_path": "include/clotho/genetics/assortative_selector.hpp", "max_forks_repo_name": "putnampp/clotho", "max_forks_repo_head_hexsha": "6dbfd82ef37b4265381cd78888cd6da8c61c68c2", "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": 34.6920529801, "max_line_length": 129, "alphanum_fraction": 0.5047246349, "num_tokens": 2562, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6825737473266735, "lm_q2_score": 0.5078118642792044, "lm_q1q2_score": 0.34661904713800074}}
{"text": "///////////////////////////////////////////////////////////////////////////////\n// lost_df_accumulator.hpp                                                   //\n//                                                                           //\n//  Copyright 2010 Erwann Rogard. Distributed under the Boost                //\n//  Software License, Version 1.0. (See accompanying file                    //\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)         //\n///////////////////////////////////////////////////////////////////////////////\n#ifndef BOOST_STATISTICS_DETAIL_NON_PARAMETRIC_CONTINGENCY_TABLE_PEARSON_CHISQ_INDEPENDENCE_AUX_LOST_DF_ACCUMULATOR_HPP_ER_2010\n#define BOOST_STATISTICS_DETAIL_NON_PARAMETRIC_CONTINGENCY_TABLE_PEARSON_CHISQ_INDEPENDENCE_AUX_LOST_DF_ACCUMULATOR_HPP_ER_2010\n#include <boost/mpl/detail/wrapper.hpp>\n#include <boost/statistics/detail/non_parametric/contingency_table/factor/levels.hpp>\n\nnamespace boost { \nnamespace statistics{\nnamespace detail{\nnamespace contingency_table{\nnamespace pearson_chi_square_statistic{\nnamespace independence_between_aux{\n\n    template<typename A,typename N>\n    struct lost_df_accumulator{\n\n        lost_df_accumulator(const A& acc, N& df) : acc_(acc), df_(df){}\n\n        template<typename Key>\n        void operator()(const boost::mpl::detail::wrapper<Key>& wrapper)const\n        {\n            namespace ct = contingency_table;\n            this->df_ += (ct::extract::levels<Key>( this->acc_ ).size() - 1);\n        }\n\n        private:\n        const A& acc_;\n        mutable N& df_;\n    };\n\n    template<typename A,typename N>\n    independence_between_aux::lost_df_accumulator<A,N> \n    make_lost_df_accumulator(const A& acc, N& df)\n    {\n        namespace aux = independence_between_aux;\n        return aux::lost_df_accumulator<A,N>(acc, df);\n    }\n\n}// independence_between_aux\n}// pearson_chi_square_statistic\n}// contingency_table\n}// detail\n}// statistics\n}// boost\n\n#endif\n", "meta": {"hexsha": "458e549a2a0efdfcb0f28402b4b87330d5431ef3", "size": 1964, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "non_parametric/boost/statistics/detail/non_parametric/contingency_table/pearson_chisq/independence/aux_/lost_df_accumulator.hpp", "max_stars_repo_name": "rogard/boost_sandbox_statistics", "max_stars_repo_head_hexsha": "16aacbc716a31a9f7bb6c535b1c90dc343282a23", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "non_parametric/boost/statistics/detail/non_parametric/contingency_table/pearson_chisq/independence/aux_/lost_df_accumulator.hpp", "max_issues_repo_name": "rogard/boost_sandbox_statistics", "max_issues_repo_head_hexsha": "16aacbc716a31a9f7bb6c535b1c90dc343282a23", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "non_parametric/boost/statistics/detail/non_parametric/contingency_table/pearson_chisq/independence/aux_/lost_df_accumulator.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": 37.0566037736, "max_line_length": 127, "alphanum_fraction": 0.6094704684, "num_tokens": 405, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6825737214979745, "lm_q2_score": 0.5078118642792044, "lm_q1q2_score": 0.3466190340218809}}
{"text": "\n\n#ifndef __HMM_HPP__\n#define __HMM_HPP__\n\n#include \"utility.hpp\"\n#include <iostream>\n#include <string>\n#include <unordered_map>\n#include <vector>\n#include <fstream>\n#include <boost/functional/hash.hpp>\n#include <boost/bimap.hpp>\n#include <math.h>\n\n\n\tauto total = std::chrono::duration<double, std::milli>{0};\n\n\ntemplate <typename viterbi_T>\nclass HMM {\npublic:\n\tusing Viterbi_type = viterbi_T;\n\tusing Model_type = typename Viterbi_type::Model;\n\npublic:\n\tHMM() = delete;\n\tHMM(const std::string& filename) : m_viterbi(mlTrain(filename)) {}\n\n\tHMM(const HMM& other) = default;\n\tHMM& operator=(const HMM& rhs) = default;\n\tstd::vector<std::string> infer(const std::vector<std::string>& ws) {\n\t\tauto is =\n\t\t\tstd::vector<typename Viterbi_type::Emission_type>(ws.size(), 0);\n\n\t\tstd::transform(ws.cbegin(), ws.cend(), is.begin(),\n\t\t\t\t\t   [this](const std::string& w) {\n\t\t\t\t\t\t   auto i = emissionBijection.left.find(w);\n\t\t\t\t\t\t   if (i == emissionBijection.left.end()) {\n\t\t\t\t\t\t\t   std::cerr << w << \" not covered.\\n\";\n\t\t\t\t\t\t\t   return 0;\n\t\t\t\t\t\t   }\n\t\t\t\t\t\t   return i->second;\n\t\t\t\t\t   });\n\n\t\tauto before = std::chrono::high_resolution_clock::now();\n\n\t\tauto iouts = m_viterbi.infer(is);\n\n\t\ttotal += std::chrono::high_resolution_clock::now() - before;\n\n\t\tauto outs = std::vector<std::string>(ws.size(), \"\");\n\n\t\tstd::transform(iouts.cbegin(), iouts.cend(), outs.begin(),\n\t\t\t\t\t   [this](const typename Viterbi_type::Label_type& l) {\n\t\t\t\t\t\t   return labelBijection.right.find(l)->second;\n\t\t\t\t\t   });\n\n\t\treturn outs;\n\t}  // end infer\n\nprivate:\n\tusing stringmap = std::unordered_map<std::string, int>;\n\tusing stringpair = std::pair<std::string, std::string>;\n\tusing pairmap =\n\t\tstd::unordered_map<stringpair, int, boost::hash<stringpair>>;\n\tusing bijection = boost::bimap<std::string, int>;\n\tusing bijectionPair = bijection::value_type;\n\nprivate:\n\tModel_type mlTrain(const std::string& filename) {\n\t\tauto file = std::ifstream{filename};\n\n\t\tbool isNewSent = true;\n\t\tstringmap initialLabelCount;\n\t\tstringmap labelCount;\n\t\tpairmap transitionCount;\n\t\tpairmap emissionCount;\n\t\tstd::string prevLabel;\n\t\tint nextLabel = 0;\n\t\tint nextEmission = 0;\n\t\tint numSents = 0;\n\n\t\tfor (std::string label, emission = \"\";\n\t\t\t std::getline(file, emission) && std::getline(file, label);) {\n\t\t\t// if its two new lines in the file emission will be empty\n\t\t\t// note: we require two newlines at end of file (or numSents is\n\t\t\t// wrong)\n\t\t\tif (emission == \"\") {\n\t\t\t\tisNewSent = true;\n\t\t\t\tnumSents += 1;\n\t\t\t\temission = label;\n\t\t\t\tif (!std::getline(file, label)) break;\n//\t\t\t} else {\n\t\t\t}\n\n\t\t\t\t// bijections\n\t\t\t\tif (labelBijection.left.find(label) ==\n\t\t\t\t\tlabelBijection.left.end()) {\n\t\t\t\t\tlabelBijection.insert(bijectionPair(label, nextLabel++));\n\t\t\t\t}\n\n\t\t\t\tif (emissionBijection.left.find(emission) ==\n\t\t\t\t\temissionBijection.left.end()) {\n\t\t\t\t\temissionBijection.insert(\n\t\t\t\t\t\tbijectionPair(emission, nextEmission++));\n\t\t\t\t}\n\n\t\t\t\tif (isNewSent) {\n\t\t\t\t\tisNewSent = false;\n\t\t\t\t\tinitialLabelCount[label] += 1;\n\t\t\t\t\tlabelCount[label] += 1;\n\t\t\t\t\tprevLabel = label;\n\t\t\t\t} else {\n\t\t\t\t\t// it is not a new sentence, so prevLabel is valid\n\t\t\t\t\ttransitionCount[std::make_pair(prevLabel, label)] += 1;\n\t\t\t\t\tlabelCount[label] += 1;\n\t\t\t\t}\n\n\t\t\t\t// we can always count emissions\n\t\t\t\temissionCount[std::make_pair(label, emission)] += 1;\n\t\t\t\tprevLabel = label;\n\t\t}  // end for\n\n\t\t// now comes the ml-estimate step\n\t\tauto maxLabel = nextLabel;\n\t\tauto maxEmission = nextEmission;\n/*\t\tstd::cout << \"Labels: \" << maxLabel << \"\\nEmissions: \" << maxEmission\n\t\t\t\t  << \"\\nSentences: \" << numSents << std::endl;\n*/\n\t\tauto m = Model_type{maxLabel, maxEmission, std::log(0.0f)};\n\n/*\t\tfor (auto i = 0; i < maxLabel; ++i) {\n\t\t\tm.start[i] =\n\t\t\t\tlog(initialLabelCount[labelBijection.right.find(i)->second]) -\n\t\t\t\tlog(numSents);\n\t\t}\n*/\n\n\t\tfor(const auto& l : initialLabelCount) {\n\t\t\tm.setStart(labelBijection.left.find(l.first)->second, log(l.second) - log(numSents));\n\t\t}\n\n\n\t\t// transitions\n\t\tfor(const auto& t : transitionCount) {\n\t\t\tauto i = labelBijection.left.find(t.first.first)->second;\n\t\t\tauto j = labelBijection.left.find(t.first.second)->second;\n\t\t\tm.setTransition(i, j, log(t.second) - log(labelCount[t.first.first]));\n\t\t}\n\n/*\n\t\tfor (auto i = 0; i < maxLabel; ++i) {\n\t\t\tfor (auto j = 0; j < maxLabel; ++j) {\n\t\t\t\tm.setTransition(i, j, \n\t\t\t\t\tlog(transitionCount[std::make_pair(\n\t\t\t\t\t\tlabelBijection.right.find(i)->second,\n\t\t\t\t\t\tlabelBijection.right.find(j)->second)]) -\n\t\t\t\t\tlog(labelCount[labelBijection.right.find(i)->second]));\n\t\t\t}\n\t\t}\n*/\n\t\t// emissions\n/*\n\t\tfor(auto i = 0; i < maxLabel; ++i) {\n\t\tfor(auto j = 0; j < nextEmission-1; ++j) {\n\t\t\tm.emissions(i, j) = log(emissionCount[std::make_pair(labelBijection.right.find(i)->second, emissionBijection.right.find(j)->second)]) - log(labelCount[labelBijection.right.find(i)->second]);\n\t\t}\n\t\t}\n*/\n\t\tfor ( auto e = emissionCount.begin(); e != emissionCount.end(); ++e) {\n\t\t\tm.setEmission(labelBijection.left.find(e->first.first)->second,\n\t\t\t\t\t\temissionBijection.left.find(e->first.second)->second,\n\t\t\t\t\t\tlog(e->second) - log(labelCount[e->first.first]));\n\t\t}\n\n\t\treturn std::move(m);\n\t}\n\nprivate:\n\tbijection labelBijection;\n\tbijection emissionBijection;\n\tViterbi_type m_viterbi;\n};  // end class HMM\n\n#endif\n", "meta": {"hexsha": "da0af38495abe54090e02520bac30b09f4ff6b89", "size": 5187, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/HMM.hpp", "max_stars_repo_name": "mjgerdes/paraterbi", "max_stars_repo_head_hexsha": "914c5430fc053788812cc5da7465b637de22458e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/HMM.hpp", "max_issues_repo_name": "mjgerdes/paraterbi", "max_issues_repo_head_hexsha": "914c5430fc053788812cc5da7465b637de22458e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/HMM.hpp", "max_forks_repo_name": "mjgerdes/paraterbi", "max_forks_repo_head_hexsha": "914c5430fc053788812cc5da7465b637de22458e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-12-05T03:31:49.000Z", "max_forks_repo_forks_event_max_datetime": "2018-12-05T03:31:49.000Z", "avg_line_length": 27.7379679144, "max_line_length": 193, "alphanum_fraction": 0.648544438, "num_tokens": 1495, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6825737214979745, "lm_q2_score": 0.5078118642792044, "lm_q1q2_score": 0.3466190340218809}}
{"text": "/*\n * Copyright 2020 Ryan Levy, Xiongjie Yu, and Bryan K. Clark\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 \"../util/types_and_headers.h\"\n#include \"../linalg/lapack_wrapper.h\"\n#include \"../dtensor/dtensor_all.h\"\n#include \"../qtensor/qtensor_all.h\"\n#include \"../mps/mps_all.h\"\n\n#include \"../models/sites/spinhalf.h\"\n#include \"../models/sites/electron.h\"\n#include \"../models/hams/Heisenberg.h\"\n\n#include \"../algos/dmrg/dmrg.h\"\n\n#include \"../util/timer.h\"\n\n#include \"../models/hams/AutoMPO.h\"\n\n#include \"../models/lattice/square.h\"\n#include \"../models/lattice/triangular.h\"\n\n#include <ctf.hpp>\n#include <sys/stat.h>\nusing namespace std;\ninline bool check_existence(const string& name);\n\n//#include <Eigen/Dense>\n#include \"hdf5.h\"\n\nfilebuf fbuf;\nostream perr(&fbuf);\nfilebuf fbufo;\nostream pout(&fbufo);\n\ntemplate <typename T, template <typename,unsigned> class TensorType>\nvoid fixTensors(TensorType<T,1>& psi,TensorType<T,2>& H){\n  uint_vec perm;\n  string Link_name_pref = \"ID\"+to_string(psi._id)+\"Link\";\n  string Site_name_pref = \"Site\";\n  for(unsigned l=0;l<psi.length;l++){\n    string left_link_name  = Link_name_pref+to_string(l);\n    string right_link_name = Link_name_pref+to_string(l+1);\n    string site_name       = Site_name_pref+to_string(l);\n    vector<qtensor_index> inds(3);\n    for(auto& ix : psi.A[l].idx_set){\n      if(ix.name()==left_link_name) inds[0] = ix;\n      else if(ix.name()==site_name) inds[1] = ix;\n      else if(ix.name()==right_link_name) inds[2] = ix;\n    }\n    find_index_permutation(psi.A[l].idx_set,inds, perm);\n    psi.A[l].permute(perm);\n  }\n  //check if we need to dagger H\n  string site_name = Site_name_pref+to_string(0);\n  auto& psiSet = psi.A[0].idx_set;\n  auto& HSet   = H.A[0].idx_set;\n  auto it  = find_if(psiSet.begin(), psiSet.end(), [&](qtensor_index& qi){ return qi.name()==site_name;});\n  auto itH = find_if(HSet.begin(),   HSet.end(),   [&](qtensor_index& qi){ return (qi.name()==site_name) && (qi.level()==0);});\n  assert(it!=psiSet.end() && itH != HSet.end());\n  if( it->arrow() == itH->arrow()){\n    for(auto& Ai: H.A) Ai.dag();\n  }\n\n}\n\nint main(int argc, char **argv)\n{\n  MPI_Init(&argc, &argv);\n  {\n    CTF::World world(argc,argv);\n    if (world.rank == 0){\n      perr.rdbuf(cerr.rdbuf());\n      pout.rdbuf(cout.rdbuf());\n      perr.precision(12);\n      pout.precision(12);\n    }\n    if(argc==1) {\n      perr<<\"Error: Need filename!\"<<endl;\n      assert(1==2);\n    }\n    string inputName = string(argv[1]);\n    ifstream in;\n    in.open(inputName);\n    assert(in);\n    string line; stringstream linest;\n\n    /*\n     *              input file format\n     * type\n     * Nx Ny\n     * J1 J2\n     * fname\n     * prefix\n     * nsweeps\n     * maxm maxm maxm\n     * cutoff cutoff cutoff\n     * restart restart restart\n     *\n     */\n\n    string type; getline(in,type);\n    getline(in,line); linest.clear(); linest.str(line);\n    int Nx,Ny;\n    linest >> Nx >> Ny;\n    auto N = Nx*Ny;\n    double J1,J2;\n    getline(in,line); linest.clear(); linest.str(line); \n    perr << \"J1 line=\" << line << endl;\n    linest >> J1 >> J2;\n    string fname=\"\";  \n    getline(in,line); if(!line.empty()) fname=line;\n    string pref=\"\"; \n    getline(in,line); if(!line.empty()) pref=line; \n    int nsweeps = 0; \n    getline(in,line); linest.clear(); linest.str(line);\n    linest >> nsweeps; \n\n    vector<int> maxm;\n    vector<double> cutoff;\n    vector<int> max_restart;\n    getline(in,line); linest.clear(); linest.str(line);\n    while(getline(linest,line,' ')){\n      maxm.push_back(std::stoi(line));\n    }\n    getline(in,line); linest.clear(); linest.str(line);\n    while(getline(linest,line,' ')){\n      cutoff.push_back(std::stof(line));\n    }\n    getline(in,line); linest.clear(); linest.str(line);\n    while(getline(linest,line,' ')){\n      max_restart.push_back(std::stoi(line));\n    }\n    in.close();\n\n    if(world.rank==0)\n      printf(\"type=%s N=(%i,%i) J1=%f J2=%f\\nfile=%s prefix=%s\\nnsweeps=%i \\n\",\n          type.c_str(),Nx,Ny,J1,J2,fname.c_str(),pref.c_str(),nsweeps);\n    perr<<\"maxm:\";        for(auto m: maxm)        perr<<m<<\" \"; perr<<\"\\n\";\n    perr<<\"cutoff:\";      for(auto c: cutoff)      perr<<c<<\" \"; perr<<\"\\n\";\n    perr<<\"max_restart:\"; for(auto r: max_restart) perr<<r<<\" \"; perr<<\"\\n\";\n    //spinhalf sites(N);\n    electron sites(N);\n    str_vec ps;\n    for (size_t i = 0; i < sites.N(); i++) {\n      if(i%2==0)\n        ps.push_back(\"Dn\");\n      else\n        ps.push_back(\"Up\");\n    }\n\n    AutoMPO ampo(sites);\n    bool yperiodic = true;\n    auto lattice = triangularLattice(Nx,Ny,yperiodic);\n    auto t = 1.0;\n    auto U = J2;\n\n    for(auto bnd : lattice){\n      //hopping terms in the 1DEG\n      ampo+=-t,\"Cdagup\",bnd.s1-1,\"Cup\",bnd.s2-1;\n      ampo+=-t,\"Cdagdn\",bnd.s1-1,\"Cdn\",bnd.s2-1;\n      ampo+=-t,\"Cdagup\",bnd.s2-1,\"Cup\",bnd.s1-1;\n      ampo+=-t,\"Cdagdn\",bnd.s2-1,\"Cdn\",bnd.s1-1;\n    }\n    //-------------------------\n    for(int i=0;i<N;i++)\n      ampo+=U,\"Nupdn\",i;\n\n    if(type==\"d\"){\n      pout << \"\\n\" << \"Dense MPS DMRG (Linear Heisenberg)\" << '\\n';\n      \n      MPS<double> psi(&sites,ps);\n      //psi.load(fname); //TODO: fix pref\n      psi.print();\n      MPO< double > H;\n      Heisenberg< double > HB(&sites);\n      HB.buildHam(H);\n      dmrg(psi, H, nsweeps, maxm, cutoff, max_restart);\n      psi.print();\n\n    }\n    if(type==\"q\"){\n      pout << \"\\n\" << \"qMPS Fermionic DMRG\" << '\\n';\n      \n      qMPS< double > psi(&sites,ps);\n      bool yperiodic=true;\n      auto lattice = triangularLattice(Nx,Ny,yperiodic);\n\n      auto t = 1.0;\n      auto U = J2;\n\n      AutoMPO ampo(sites);\n      for(auto bnd : lattice){\n        //hopping terms in the 1DEG\n        ampo+=-t,\"Cdagup\",bnd.s1-1,\"Cup\",bnd.s2-1;\n        ampo+=-t,\"Cdagdn\",bnd.s1-1,\"Cdn\",bnd.s2-1;\n        ampo+=-t,\"Cdagup\",bnd.s2-1,\"Cup\",bnd.s1-1;\n        ampo+=-t,\"Cdagdn\",bnd.s2-1,\"Cdn\",bnd.s1-1;\n      }\n      //-------------------------\n      for(int i=0;i<N;i++)\n        ampo+=U,\"Nupdn\",i;\n\n      string postfix = to_string(Nx)+\"x\"+to_string(Ny)+\"_U\"+to_string(U);\n      auto sp = \"psi_\"+postfix;\n      qMPO< double > H;\n      Heisenberg< double > HB(&sites);\n      perr<<\"making H\"<<endl;\n      HB.buildHam(ampo,H);\n\n      psi.load(fname,pref);\n      psi.print();\n\n      assert(H._id != psi._id);\n      fixTensors(psi,H);\n\n      dmrg(psi, H, nsweeps, maxm, cutoff, max_restart);\n\n    }\n    if(type==\"qs\"){\n      pout << \"\\n\" << \"qsMPS Fermionic DMRG\" << '\\n';\n      \n      qsMPS<double> psi(&sites,ps);\n      psi.load(fname,pref);\n      psi.print();\n      qMPO< double > H;\n      Heisenberg< double > HB(&sites);\n      HB.buildHam(ampo,H);\n      qsMPO< double > Hq = H;\n\n      assert(H._id != psi._id);\n      fixTensors(psi,Hq);\n\n      dmrg(psi, Hq, nsweeps, maxm, cutoff, max_restart);\n\n      psi.print();\n      for(int l=0;l<N;l++){\n        auto& Al = psi.A[l];\n        perr<<Al._T.nnz_tot<<\",\"<<(double)Al._T.nnz_tot/(Al._T.get_tot_size(false))<<endl;\n        for(size_t i=0;i<Al.block_index_qd.size();i++)\n          perr<<\"   (\"<<Al.block_index_qd[i][0]<<\",\"\n              << Al.block_index_qd[i][1]<<\",\"<<Al.block_index_qd[i][2]<<\")\\n\";\n      }\n    }\n    if(type==\"qToqs\"){\n      pout << \"\\n\" << \"q to qsMPS Fermionic DMRG\" << '\\n';\n      \n      qMPO< double > H;\n      Heisenberg< double > HB(&sites);\n      HB.buildHam(ampo,H);\n      H.load(\"H_36_1.h5\");\n      H.print();\n      qsMPO< double > Hq = H;\n\n      qMPS<double> psi(&sites);\n      psi.load(fname,pref);\n      psi.print();\n      qsMPS<double> psiq = psi;\n      psiq.print();\n\n     \n      assert(H._id != psi._id);\n      fixTensors(psiq,Hq);\n      \n      dmrg(psiq, Hq, nsweeps, maxm, cutoff, max_restart);\n\n      psiq.print();\n      /*for(int l=0;l<N;l++){\n        auto& Al = psiq.A[l];\n        perr<<Al._T.nnz_tot<<\",\"<<(double)Al._T.nnz_tot/(Al._T.get_tot_size(false))<<endl;\n        perr<<\"   \";\n        for(size_t i=0;i<Al.block_index_qd.size();i++)\n          perr<<\"(\"<<Al.block_index_qd[i][0]<<\",\"\n              << Al.block_index_qd[i][1]<<\",\"<<Al.block_index_qd[i][2]<<\") \";\n        perr<<'\\n';\n      }*/\n    }\n  }\n  MPI_Finalize();\n  return 0;\n  exit(1);\n  //------------------------------------\n  return 0;\n}\n\ninline bool check_existence(const std::string& name){\n  struct stat buffer;\n  return (stat (name.c_str(),&buffer) == 0);\n}\n", "meta": {"hexsha": "f209f0423f60b3111158f843ac569e285399ff33", "size": 8772, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "project/main.cpp", "max_stars_repo_name": "ClarkResearchGroup/tensor-tools", "max_stars_repo_head_hexsha": "25fe4553991d2680b43301aef1960e4c20f1e146", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2020-07-14T01:55:51.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-12T14:06:59.000Z", "max_issues_repo_path": "project/main.cpp", "max_issues_repo_name": "ClarkResearchGroup/tensor-tools", "max_issues_repo_head_hexsha": "25fe4553991d2680b43301aef1960e4c20f1e146", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-07-31T02:43:25.000Z", "max_issues_repo_issues_event_max_datetime": "2020-08-08T16:18:36.000Z", "max_forks_repo_path": "project/main.cpp", "max_forks_repo_name": "ClarkResearchGroup/tensor-tools", "max_forks_repo_head_hexsha": "25fe4553991d2680b43301aef1960e4c20f1e146", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-12-01T03:40:26.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-01T03:40:26.000Z", "avg_line_length": 28.8552631579, "max_line_length": 127, "alphanum_fraction": 0.5664614683, "num_tokens": 2744, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6825737214979745, "lm_q2_score": 0.5078118642792044, "lm_q1q2_score": 0.3466190340218809}}
{"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 *      100902    K. Kumar          File header and footer added.\n *      100916    D. Dirkx          Added minor comments during checking.\n *      100928    K. Kumar          Small comment modifications.\n *      100929    K. Kumar          Small comment modifications.\n *      110202    K. Kumar          Added overload for map with State* for\n *                                  computeNearestLeftNeighborUsingBinarySearch( ).\n *      110803    J. Leloux         Added convertStringToTemplate.\n *      110805    J. Leloux         Added outputCurrentRunningTime( ).\n *      110807    K. Kumar          Minor comment modifications.\n *      110810    J. Leloux         Minor comment modifications.\n *      110913    K. Kumar          Implemented automatic root-path functions based on\n *                                  suggestions by M. Persson.\n *      111117    K. Kumar          Added listAllFilesInDirectory( ) function.\n *\n *    References\n *      Press W.H., et al. Numerical Recipes in C++: The Art of Scientific Computing. Cambridge\n *          University Press, February 2002.\n *\n *    Notes\n *      Need to add bounds checking with respect to targetValue for\n *      computeNearestLeftNeighborUsingBinarySearch( ).\n */\n\n#include <map>\n#include <iterator>\n#include <Eigen/Core>\n\nnamespace tudat\n{\nnamespace basic_mathematics\n{\n\n//! Nearest left neighbor binary search.\nint computeNearestLeftNeighborUsingBinarySearch(\n        const Eigen::VectorXd& vectorOfSortedData,\n        const double targetValueInVectorOfSortedData )\n{\n    // Declare local variables.\n    // Declare bounds of vector of sorted data and current position.\n    int leftLimitOfVectorOfSortedData = 0;\n    int rightLimitOfVectorOfSortedData = vectorOfSortedData.rows( ) - 1;\n    int currentPositionInVectorOfSortedData;\n\n    // Check if data is sorted in ascending order.\n    // ( true if ascending, else false ).\n    bool isVectorOfSortedDataAscending\n            = ( vectorOfSortedData[ rightLimitOfVectorOfSortedData ]\n                >= vectorOfSortedData[ leftLimitOfVectorOfSortedData ] );\n\n    // Loop through vector of sorted data until left and right limits\n    // are neighbours.\n    while ( rightLimitOfVectorOfSortedData\n            - leftLimitOfVectorOfSortedData > 1 )\n    {\n        // Compute midpoint ( bitshift is same as division by 2.0 ).\n        currentPositionInVectorOfSortedData\n                = ( rightLimitOfVectorOfSortedData\n                    + leftLimitOfVectorOfSortedData ) >> 1;\n\n        // Check which limit to replace ( if ascending and target datum\n        // is in right half, replace left limit ).\n        if ( targetValueInVectorOfSortedData\n             >= vectorOfSortedData[ currentPositionInVectorOfSortedData ]\n             && isVectorOfSortedDataAscending )\n        {\n            // Set left limit to current position in vector of sorted data.\n            leftLimitOfVectorOfSortedData = currentPositionInVectorOfSortedData;\n        }\n\n        else\n        {\n            // Set right limit to current position in vector of sorted data.\n            rightLimitOfVectorOfSortedData = currentPositionInVectorOfSortedData;\n        }\n    }\n\n    // Set current position to left limit.\n    currentPositionInVectorOfSortedData = leftLimitOfVectorOfSortedData;\n\n    // Return current position in vector.\n    return currentPositionInVectorOfSortedData;\n}\n\n//! Nearest left neighbor binary search.\nint computeNearestLeftNeighborUsingBinarySearch(\n        const std::map < double, Eigen::VectorXd >& sortedIndepedentAndDependentVariables,\n        const double targetValueInMapOfData )\n{\n    // Declare local variables.\n    // Declare bounds of key of map of data and current position.\n    int leftLimitOfKeyOfMapOfData = 0;\n    int rightLimitOfKeyOfMapOfData = sortedIndepedentAndDependentVariables\n                                     .size( ) - 1;\n    int currentPositionInKeyOfMapOfData;\n\n    // Declare map iterator\n    std::map < double, Eigen::VectorXd >::const_iterator mapIterator;\n\n    // Loop through vector of sorted data until left and right limits\n    // are neighbours\n    while ( rightLimitOfKeyOfMapOfData - leftLimitOfKeyOfMapOfData > 1 )\n    {\n        // Compute midpoint ( bitshift is same as division by 2.0 ).\n        currentPositionInKeyOfMapOfData\n                = ( rightLimitOfKeyOfMapOfData\n                   + leftLimitOfKeyOfMapOfData ) >> 1;\n\n        // Set map iterator to begin begin of map of sorted independent and\n        // dependent variables.\n        mapIterator = sortedIndepedentAndDependentVariables.begin( );\n\n        // Advance iterator to location of current position in key of map of\n        // data.\n        advance( mapIterator, currentPositionInKeyOfMapOfData );\n\n        // Check that target value lies to the right of lower bound.\n        if ( targetValueInMapOfData\n             >= mapIterator->first )\n        {\n            // Set left limit to current position in map of data.\n            leftLimitOfKeyOfMapOfData = currentPositionInKeyOfMapOfData;\n        }\n\n        else\n        {\n            // Set right limit to current position in map of data.\n            rightLimitOfKeyOfMapOfData = currentPositionInKeyOfMapOfData;\n        }\n    }\n\n    // Set current position to left limit.\n    currentPositionInKeyOfMapOfData = leftLimitOfKeyOfMapOfData;\n\n    // Return current position in map of data.\n    return currentPositionInKeyOfMapOfData;\n}\n\n} // namespace basic_mathematics\n} // namespace tudat\n", "meta": {"hexsha": "b057ddc2631aaea45b8c4b3826dd4290068a830f", "size": 7197, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Tudat/Mathematics/BasicMathematics/nearestNeighbourSearch.cpp", "max_stars_repo_name": "JPelamatti/ThesisTUDAT", "max_stars_repo_head_hexsha": "b94ce35fb7c8fa44ae83238e296a979dfa3adfe8", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Tudat/Mathematics/BasicMathematics/nearestNeighbourSearch.cpp", "max_issues_repo_name": "JPelamatti/ThesisTUDAT", "max_issues_repo_head_hexsha": "b94ce35fb7c8fa44ae83238e296a979dfa3adfe8", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Tudat/Mathematics/BasicMathematics/nearestNeighbourSearch.cpp", "max_forks_repo_name": "JPelamatti/ThesisTUDAT", "max_forks_repo_head_hexsha": "b94ce35fb7c8fa44ae83238e296a979dfa3adfe8", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-05-30T03:42:22.000Z", "max_forks_repo_forks_event_max_datetime": "2019-05-30T03:42:22.000Z", "avg_line_length": 43.3554216867, "max_line_length": 99, "alphanum_fraction": 0.677365569, "num_tokens": 1567, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.600188359260205, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.3466059957112453}}
{"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 \"permutation.hpp\"\n\n#include <numeric>\n\n#include <boost/algorithm/string/join.hpp>\n#include <boost/assign/std/vector.hpp>\n#include <boost/dynamic_bitset.hpp>\n#include <boost/lexical_cast.hpp>\n#include <boost/range/adaptors.hpp>\n#include <boost/range/algorithm.hpp>\n#include <boost/range/algorithm_ext/push_back.hpp>\n\n#include <core/utils/range_utils.hpp>\n#include <reversible/functions/circuit_to_truth_table.hpp>\n#include <reversible/simulation/simple_simulation.hpp>\n\nusing namespace boost::assign;\nusing boost::adaptors::transformed;\n\nnamespace cirkit\n{\n\npermutation_t identity_permutation( unsigned size )\n{\n  permutation_t perm( size );\n  std::iota( perm.begin(), perm.end(), 0u );\n  return perm;\n}\n\npermutation_t truth_table_to_permutation( const binary_truth_table& spec )\n{\n  permutation_t perm;\n\n  for ( const auto& row : index( spec ) )\n  {\n    auto from = row.value.first;\n    auto to   = row.value.second;\n\n    assert( truth_table_cube_to_number( binary_truth_table::cube_type( from.first, from.second ) ) == row.index );\n    perm += truth_table_cube_to_number( binary_truth_table::cube_type( to.first, to.second ) );\n  }\n\n  return perm;\n}\n\npermutation_t circuit_to_permutation( const circuit& circ )\n{\n  binary_truth_table spec;\n  circuit_to_truth_table( circ, spec, simple_simulation_func() );\n  return truth_table_to_permutation( spec );\n}\n\ncycles_t permutation_to_cycles( const permutation_t& perm, bool sort )\n{\n  cycles_t cycles;\n\n  boost::dynamic_bitset<> vismask = ~boost::dynamic_bitset<>( perm.size() );\n  unsigned start, current;\n\n  while ( vismask.any() )\n  {\n    start = vismask.find_first();\n    permutation_t cycle;\n    cycle += start;\n    current = perm[start];\n    vismask.reset( current );\n\n    while ( current != start ) {\n      cycle += current;\n      current = perm[current];\n      vismask.reset( current );\n    }\n\n    cycles += cycle;\n  }\n\n  assert( vismask.none() );\n\n  if ( sort )\n  {\n    boost::sort( cycles, []( const std::vector<unsigned>& x1, const std::vector<unsigned>& x2 ) { return x1.size() > x2.size(); } );\n  }\n\n  return cycles;\n}\n\nstd::vector<std::pair<unsigned, unsigned>> permutation_to_transpositions( const permutation_t& perm )\n{\n  auto perm_copy = perm;\n  std::vector<std::pair<unsigned, unsigned>> transpositions;\n\n  for ( int i = perm_copy.size() - 1; i > 0; --i )\n  {\n    if ( static_cast<int>( perm_copy[i] ) == i ) { continue; }\n\n    /* where is i? */\n    auto other = std::distance( perm_copy.begin(), std::find( perm_copy.begin(), perm_copy.begin() + i, i ) );\n    transpositions.push_back( {i, other} );\n\n    std::swap( perm_copy[i], perm_copy[other] );\n  }\n\n  return transpositions;\n}\n\nunsigned permutation_inv( const permutation_t& perm )\n{\n  unsigned inv = 0u;\n\n  for ( unsigned i = 0u; i < perm.size() - 1u; ++i )\n  {\n    for ( unsigned j = i + 1u; j < perm.size(); ++j )\n    {\n      if ( perm[i] > perm[j] )\n      {\n        ++inv;\n      }\n    }\n  }\n\n  return inv;\n}\n\nint permutation_sign( const permutation_t& perm )\n{\n  return ( permutation_inv( perm ) % 2 == 0u ) ? 1 : -1;\n}\n\npermutation_t permutation_multiply( const permutation_t& a, const permutation_t& b )\n{\n  assert( a.size() == b.size() );\n  permutation_t result( a.size() );\n\n  for ( auto i = 0u; i < a.size(); ++i )\n  {\n    result[i] = b[a[i]];\n  }\n\n  return result;\n}\n\npermutation_t permutation_invert( const permutation_t& perm )\n{\n  permutation_t result( perm.size() );\n\n  for ( auto i = 0u; i < perm.size(); ++i )\n  {\n    result[perm[i]] = i;\n  }\n\n  return result;\n}\n\nstd::vector<unsigned> cycles_type( const cycles_t& cycles )\n{\n  std::vector<unsigned> type( cycles.size() );\n  boost::transform( cycles, type.begin(), []( const permutation_t& cycle ) { return cycle.size(); } );\n  boost::sort( type );\n  return type;\n}\n\nbool is_involution( const permutation_t& perm )\n{\n  auto c = permutation_to_cycles( perm );\n  return boost::find_if( c, []( const std::vector<unsigned>& cycle ) { return cycle.size() > 2u; } ) == c.end();\n}\n\ninline unsigned pos( unsigned i, unsigned j, unsigned n )\n{\n  return i * n + ( i * ( i + 1 ) ) / 2 + j;\n}\n\n/* dynamic programming algorithm to check whether a permutation is\n   simple.\n\n   [M.H. Albert, M.D. Atkinson, M. Klazar, Journal of Integer Sequences 6 (2003), 03.4.4]\n*/\nbool is_simple( const permutation_t& perm )\n{\n  const unsigned n = perm.size();\n  const auto sumn  = ( n * ( n + 1 ) ) / 2;\n\n  std::vector<unsigned> m_min( sumn );\n  std::vector<unsigned> m_max( sumn );\n\n  auto p = 0u;\n  for ( auto i = 0u; i < n; ++i )\n  {\n    m_min[p] = m_max[p] = perm.at( i );\n\n    for ( auto j = ( i + 1u ); j < n; ++j )\n    {\n      m_min[p + 1u] = std::min( m_min[p], perm.at( j ) );\n      m_max[p + 1u] = std::max( m_max[p], perm.at( j ) );\n      ++p;\n    }\n\n    ++p;\n  }\n\n  p = 0u;\n  for ( auto i = 0u; i < ( n - 1u ); ++i )\n  {\n    ++p;\n    for ( auto j = ( i + 1u ); j < n; ++j )\n    {\n      if ( ( m_max[p] - m_min[p] ) == ( j - i ) && !( ( i == 0u ) && ( j == ( n - 1u ) ) ) )\n      {\n        return false;\n      }\n      ++p;\n    }\n  }\n\n  return true;\n}\n\nstd::string permutation_to_string( const permutation_t& perm )\n{\n  return \"[\" + any_join( perm, \" \" ) + \"]\";\n}\n\nstd::string cycles_to_string( const cycles_t& cycles, bool print_fixpoints )\n{\n  return boost::join( cycles | transformed( [&print_fixpoints]( const permutation_t& cycle ) {\n        return ( cycle.size() > 1u || print_fixpoints ) ? ( \"(\" + any_join( cycle, \" \" ) + \")\" ) : std::string();\n      } ), \"\" );\n}\n\nstd::string cycles_to_string( const permutation_t& perm, bool print_fixpoints )\n{\n  return cycles_to_string( permutation_to_cycles( perm ), print_fixpoints );\n}\n\nstd::string type_to_string( const std::vector<unsigned>& type )\n{\n  return \"(\" + any_join( type, \", \" ) + \")\";\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": "54b586605f0d159601debf8ff3b905a91e3d0de0", "size": 7064, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "addons/cirkit-addon-reversible/src/reversible/utils/permutation.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/utils/permutation.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/utils/permutation.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.8754578755, "max_line_length": 132, "alphanum_fraction": 0.6438278596, "num_tokens": 1935, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.600188359260205, "lm_q2_score": 0.5774953651858117, "lm_q1q2_score": 0.34660599571124523}}
{"text": "//  Copyright (c) 2019 National Technology & Engineering Solutions of Sandia,\n//                     LLC (NTESS).\n//  Copyright (c) 2014 Hartmut Kaiser\n//  Copyright (c) 2014 Patricia Grubel\n//  Copyright (c) 2019 Nikunj Gupta\n//\n//  SPDX-License-Identifier: BSL-1.0\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 is the fourth in a series of examples demonstrating the development of\n// a fully distributed solver for a simple 1D heat distribution problem.\n//\n// This example builds on example three. It futurizes the code from that\n// example. Compared to example two this code runs much more efficiently. It\n// allows for changing the amount of work executed in one HPX thread which\n// enables tuning the performance for the optimal grain size of the\n// computation. This example is still fully local but demonstrates nice\n// scalability on SMP machines.\n\n#include <hpx/local/algorithm.hpp>\n#include <hpx/local/init.hpp>\n#include <hpx/modules/resiliency.hpp>\n#include <hpx/modules/synchronization.hpp>\n#include <boost/range/irange.hpp>\n\n#include <atomic>\n#include <cstddef>\n#include <cstdint>\n#include <exception>\n#include <iostream>\n#include <memory>\n#include <random>\n#include <utility>\n#include <vector>\n\nstruct validate_exception : std::exception\n{\n};\n\n///////////////////////////////////////////////////////////////////////////////\ndouble const pi = std::acos(-1.0);\n\n// Variable to count the number of failed attempts\nstd::atomic<int> counter(0);\n\n// Variables to generate errors\nstd::random_device rd;\nstd::mt19937 gen(rd());\n\n///////////////////////////////////////////////////////////////////////////////\n// Our partition data type\nstruct partition_data\n{\npublic:\n    partition_data(std::size_t size)\n      : data_(size)\n      , size_(size)\n    {\n    }\n\n    partition_data(std::size_t subdomain_width, double subdomain_index,\n        std::size_t subdomains)\n      : data_(subdomain_width + 1)\n      , size_(subdomain_width + 1)\n    {\n        for (std::size_t k = 0; k != subdomain_width + 1; ++k)\n        {\n            data_[k] = std::sin(2 * pi *\n                ((0.0 + subdomain_width * subdomain_index + k) /\n                    static_cast<double>(subdomain_width * subdomains)));\n        }\n    }\n\n    partition_data(partition_data&& other)\n      : data_(std::move(other.data_))\n      , size_(other.size_)\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    friend std::vector<double>::const_iterator begin(const partition_data& v)\n    {\n        return begin(v.data_);\n    }\n    friend std::vector<double>::const_iterator end(const partition_data& v)\n    {\n        return end(v.data_);\n    }\n\n    std::size_t size() const\n    {\n        return size_;\n    }\n\n    void resize(std::size_t size)\n    {\n        data_.resize(size);\n        size_ = size;\n    }\n\nprivate:\n    std::vector<double> data_;\n    std::size_t size_;\n};\n\nstd::ostream& operator<<(std::ostream& os, partition_data const& c)\n{\n    os << \"{\";\n    for (std::size_t i = 0; i != c.size() - 1; ++i)\n    {\n        if (i != 0)\n            os << \", \";\n        os << c[i];\n    }\n    os << \"}\";\n    return os;\n}\n\n///////////////////////////////////////////////////////////////////////////////\nstruct stepper\n{\n    // Our data for one time step\n    typedef hpx::shared_future<partition_data> partition;\n    typedef std::vector<partition> space;\n\n    // Our operator\n    static double stencil(double left, double center, double right)\n    {\n        return 0.5 * (0.75) * left + (0.75) * center - 0.5 * (0.25) * right;\n    }\n\n    static double left_flux(double left, double center)\n    {\n        return (0.625) * left - (0.125) * center;\n    }\n\n    static double right_flux(double center, double right)\n    {\n        return 0.5 * (0.75) * center + (1.125) * right;\n    }\n\n    // The partitioned operator, it invokes the heat operator above on all\n    // elements of a partition.\n    static partition_data heat_part(std::size_t sti, double error,\n        partition_data const& left_input, partition_data const& center_input,\n        partition_data const& right_input)\n    {\n        static thread_local std::exponential_distribution<> dist_(error);\n\n        double num = dist_(gen);\n        bool error_flag = false;\n\n        // Probability of error occurrence is proportional to exp(-error_rate)\n        if (num > 1.0)\n        {\n            error_flag = true;\n            ++counter;\n        }\n\n        std::size_t const size = center_input.size() - 1;\n        partition_data workspace(size + 2 * sti + 1);\n\n        std::copy(\n            end(left_input) - sti - 1, end(left_input) - 1, &workspace[0]);\n        std::copy(begin(center_input), end(center_input) - 1, &workspace[sti]);\n        std::copy(begin(right_input), begin(right_input) + sti + 1,\n            &workspace[size + sti]);\n\n        for (std::size_t t = 0; t != sti; ++t)\n        {\n            for (std::size_t k = 0; k != size + 2 * sti - 1 - 2 * t; ++k)\n                workspace[k] =\n                    stencil(workspace[k], workspace[k + 1], workspace[k + 2]);\n        }\n\n        workspace.resize(size + 1);\n\n        // Artificial error injection to get replay in action\n        if (error_flag)\n            throw validate_exception();\n\n        return workspace;\n    }\n\n    hpx::future<space> do_work(std::size_t subdomains,\n        std::size_t subdomain_width, std::size_t iterations, std::size_t sti,\n        std::uint64_t nd, std::uint64_t n_value, double error,\n        hpx::lcos::local::sliding_semaphore& sem)\n    {\n        using hpx::resiliency::experimental::dataflow_replicate;\n        using hpx::util::unwrapping;\n\n        // U[t][i] is the state of position i at time t.\n        std::vector<space> U(2);\n        for (space& s : U)\n            s.resize(subdomains);\n\n        std::size_t b = 0;\n        auto range = boost::irange(b, subdomains);\n        hpx::ranges::for_each(hpx::execution::par, range,\n            [&U, subdomain_width, subdomains](std::size_t i) {\n                U[0][i] = hpx::make_ready_future(\n                    partition_data(subdomain_width, double(i), subdomains));\n            });\n\n        auto Op = unwrapping(&stepper::heat_part);\n\n        // Actual time step loop\n        for (std::size_t t = 0; t != iterations; ++t)\n        {\n            space const& current = U[t % 2];\n            space& next = U[(t + 1) % 2];\n\n            for (std::size_t i = 0; i != subdomains; ++i)\n            {\n                next[i] = dataflow_replicate(n_value, Op, sti, error,\n                    current[(i - 1 + subdomains) % subdomains], current[i],\n                    current[(i + 1) % subdomains]);\n            }\n\n            // every nd time steps, attach additional continuation which will\n            // trigger the semaphore once computation has reached this point\n            if ((t % nd) == 0)\n            {\n                next[0].then([&sem, t](partition&&) {\n                    // inform semaphore about new lower limit\n                    sem.signal(t);\n                });\n            }\n\n            // suspend if the tree has become too deep, the continuation above\n            // will resume this thread once the computation has caught up\n            sem.wait(t);\n        }\n\n        // Return the solution at time-step 'iterations'.\n        return hpx::when_all(U[iterations % 2]);\n    }\n};\n\n///////////////////////////////////////////////////////////////////////////////\nint hpx_main(hpx::program_options::variables_map& vm)\n{\n    std::uint64_t n_value =\n        vm[\"n-value\"].as<std::uint64_t>();    // Number of partitions.\n    std::uint64_t subdomains =\n        vm[\"subdomains\"].as<std::uint64_t>();    // Number of partitions.\n    std::uint64_t subdomain_width =\n        vm[\"subdomain-width\"].as<std::uint64_t>();    // Number of grid points.\n    std::uint64_t iterations =\n        vm[\"iterations\"].as<std::uint64_t>();    // Number of steps.\n    std::uint64_t nd =\n        vm[\"nd\"].as<std::uint64_t>();    // Max depth of dep tree.\n    std::uint64_t sti =\n        vm[\"steps-per-iteration\"]\n            .as<std::uint64_t>();    // Number of time steps per iteration\n    double error = vm[\"error-rate\"].as<double>();\n\n    // Create the stepper object\n    stepper step;\n\n    std::cout << \"Starting 1d stencil with dataflow replicate\" << std::endl;\n\n    // Measure execution time.\n    std::uint64_t t = hpx::chrono::high_resolution_clock::now();\n\n    {\n        // limit depth of dependency tree\n        hpx::lcos::local::sliding_semaphore sem(nd);\n\n        hpx::future<stepper::space> result = step.do_work(subdomains,\n            subdomain_width, iterations, sti, nd, n_value, error, sem);\n\n        stepper::space solution = result.get();\n        hpx::wait_all(solution);\n    }\n\n    std::cout << \"Time elapsed: \"\n              << static_cast<double>(\n                     hpx::chrono::high_resolution_clock::now() - t) /\n            1e9\n              << std::endl;\n    std::cout << \"Errors occurred: \" << counter << std::endl;\n\n    // for (std::size_t i = 0; i != subdomains; ++i)\n    //     std::cout << solution[i].get() << \" \";\n    // std::cout << std::endl;\n\n    return hpx::local::finalize();\n}\n\nint main(int argc, char* argv[])\n{\n    using namespace hpx::program_options;\n\n    // Configure application-specific options.\n    options_description desc_commandline;\n\n    desc_commandline.add_options()(\n        \"results\", \"print generated results (default: false)\");\n\n    desc_commandline.add_options()(\"n-value\",\n        value<std::uint64_t>()->default_value(5), \"Number of allowed replays\");\n\n    desc_commandline.add_options()(\"error-rate\",\n        value<double>()->default_value(5), \"Error rate for injecting errors\");\n\n    desc_commandline.add_options()(\"subdomain-width\",\n        value<std::uint64_t>()->default_value(128),\n        \"Local x dimension (of each partition)\");\n\n    desc_commandline.add_options()(\"iterations\",\n        value<std::uint64_t>()->default_value(10), \"Number of time steps\");\n\n    desc_commandline.add_options()(\"steps-per-iteration\",\n        value<std::uint64_t>()->default_value(16),\n        \"Number of time steps per iterations\");\n\n    desc_commandline.add_options()(\"nd\",\n        value<std::uint64_t>()->default_value(10),\n        \"Number of time steps to allow the dependency tree to grow to\");\n\n    desc_commandline.add_options()(\"subdomains\",\n        value<std::uint64_t>()->default_value(10), \"Number of partitions\");\n\n    // Initialize and run HPX\n    hpx::local::init_params init_args;\n    init_args.desc_cmdline = desc_commandline;\n\n    return hpx::local::init(hpx_main, argc, argv, init_args);\n}\n", "meta": {"hexsha": "4f5b781e692098c749b7e236c79a43a8e2941f42", "size": 10764, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/parallelism/resiliency/tests/performance/replicate/1d_stencil_replicate.cpp", "max_stars_repo_name": "toktarev/hpx", "max_stars_repo_head_hexsha": "6faba191fdf382ca7d3053c3ea3092a4be505e14", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "libs/parallelism/resiliency/tests/performance/replicate/1d_stencil_replicate.cpp", "max_issues_repo_name": "toktarev/hpx", "max_issues_repo_head_hexsha": "6faba191fdf382ca7d3053c3ea3092a4be505e14", "max_issues_repo_licenses": ["BSL-1.0"], "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/parallelism/resiliency/tests/performance/replicate/1d_stencil_replicate.cpp", "max_forks_repo_name": "toktarev/hpx", "max_forks_repo_head_hexsha": "6faba191fdf382ca7d3053c3ea3092a4be505e14", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.5659824047, "max_line_length": 80, "alphanum_fraction": 0.5798959495, "num_tokens": 2626, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6001883592602049, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.34660599571124523}}
{"text": "\n#include <iostream>\n//#include <iomanip>\n//#include <fstream>\n\n//#include <boost/numeric/ublas/matrix.hpp>\n//#include <boost/numeric/ublas/vector.hpp>\n//#include <boost/numeric/ublas/io.hpp>\n\n#include <boost/timer.hpp>\n\n#include <vector>\n#include <cmath>\n#include <cstring>\n\n#include \"NRGclasses.hpp\"\n#include \"NRGfunctions.hpp\"\n#include \"SpecFuncClass.hpp\"\n#include \"DM_NRG.hpp\"\n#include \"NRGOpMatRules.hpp\"\n\n\n#ifndef pi\n#define pi 3.141592653589793238462643383279502884197169\n#endif\n\n\nint main (int argc, char* argv[]){\n\n\n  CNRGCodeHandler ThisCode;\n\n  //CNRGbasisarray AcutN;\n  CNRGbasisarray* AcutN;\n  CNRGbasisarray AbasisN;\n\n  //CNRGbasisarray AcutNp1;\n  CNRGbasisarray AbasisNp1;\n\n  CNRGbasisarray SingleSite;\n\n  CNRGmatrix** OpArrayN;\n\n  CNRGmatrix* RhoN;\n  vector<double> ParamsTemp;\n  double betabar=0.727;\n    double DM,TM;\n  // 0 - betabar; 1 - TM; 2 - DM ?\n  double Temp; // In units of the bandwidth (fixed!)\n               // Temp/DN = TempBar = 1/betabar \n  int Mtemp=1001;\n\n  double twindow=2.0;\n\n  double broadtemp=0.8; // Good for CFS\n\n  char CNsites[8];\n  char CNmat[8];\n  char arqname[32];\n  char ext[32];\n\n  int NshellMax=3;\n  int NFermiOps=2;\n\n  // Check time\n  boost::timer MyTime;\n  double time_elapsed;\n\n\n  int UseCFS=0;\n  int Nw=0; // No of omegas in each shell\n\n  // FDM calculations\n  bool UseFDM=false;\n  double auxwN=0.0;\n  double ZN=0.0;\n  double ZTot=0.0;\n  double ZNdisc=0.0;\n  double TempBar;\n  vector<double> wN;\n\n  // Read code parameters, including z_twist\n  ThisCode.ReadGenPars(true); \n\n  double bbroad=0.5*log(ThisCode.Lambda);\n\n  // New (2016)\n  bool UseGap=false;\n\n  // Command-line: Set Temp\n  DM_NRG_CommandLineRead(argc,argv,Mtemp,betabar,twindow,broadtemp,bbroad,UseCFS,UseFDM,UseGap,Nw);\n\n  // Set Temp\n  cout << \" Mtemp = \" << Mtemp \n       << \" betabar = \" << betabar \n       << \" twindow = \" << twindow \n       << \" dBroad = \" << bbroad \n       << \" dBroadTemp = \" << broadtemp << endl\n       << \" NomegasEachShell = \" << Nw << \" (if =0 then use standard interpolation) \"\n       << endl; \n  //betabar=0.727;\n  Temp=0.0;  // Real Temperature\n  //ParamsTemp.push_back(betabar); // Need to fix this today...\n  if (Mtemp<ThisCode.Nsitesmax-1) {\n    if (!UseFDM) ThisCode.Nsitesmax=Mtemp+1;\n    DM=CalcDN(ThisCode.Lambda,Mtemp);\n    Temp=DM/betabar;\n  }\n  else{ // OK, Let me try this. Instead of 0.0, \"Temp\" will be DM(Nsites+200)/betabar.\n    //Temp=0.0;\n    Temp=CalcDN(ThisCode.Lambda,ThisCode.Nsitesmax+199)/betabar;\n    DM=CalcDN(ThisCode.Lambda,ThisCode.Nsitesmax-1);\n  }\n  cout << \" Temp = \"<<Temp\n       << \" DMtemp = \" << DM\n       << endl;\n  //DM=CalcDN(ThisCode.Lambda,NshellMax);\n  ParamsTemp.push_back(Temp/DM);\n  // Save in Temp_Mtemp.dat\n  ofstream OutFile;\n  strcpy(arqname,\"Temp_Mtemp.dat\");\n  OutFile.open(arqname);\n  OutFile << Temp << \" \" << Mtemp << endl;\n  OutFile.close();\n\n\n  cout << \"Lambda    = \" << ThisCode.Lambda << endl;\n  cout << \"Nsites0   = \" << ThisCode.Nsites0 << endl;\n  cout << \"Nsitesmax = \" << ThisCode.Nsitesmax << endl;\n  cout << \"NFermiOps = \" << ThisCode.NopsSaved << endl;\n  cout << \"Ext arq   = \" << ThisCode.SaveArraysFileName << endl;\n  cout << \"Symmetry  = \" << ThisCode.SymNo << endl;\n  if ( (ThisCode.SymNo != 2)&&(ThisCode.SymNo != 3) ){\n    cout << \" DM-NRG: Only 1chQSz and 1chQ symmetries supported at this point. Testing QS symmetry now...\" << endl;\n  }\n  if (ThisCode.totalS){cout << \" SU(2) symmetry detected. \" << endl;}\n  cout << \"Oliveira z = \" << ThisCode.code_z_twist << endl;\n\n  if (UseGap){ThisCode.ReadParams((char *)\"input_nrg.dat\",1);} // Need the gap\n\n  NshellMax=ThisCode.Nsitesmax-1;\n  NFermiOps= ThisCode.NopsSaved;\n\n  // April 2010\n  // TotS QNs in ThisCode\n  ThisCode.SetTotS();\n  // Setting SingleSite (depends only on SymNo)\n  ThisCode.SetSingleSite(&SingleSite);\n\n  // Allocate matrices: Tricky\n\n  OpArrayN=new CNRGmatrix* [NFermiOps];\n  for (int iop=0;iop<NFermiOps;iop++){\n    OpArrayN[iop]=new CNRGmatrix [NshellMax+1];\n  }\n\n  AcutN = new CNRGbasisarray [NshellMax+1];\n  RhoN = new CNRGmatrix [NshellMax+1];\n\n\n  // Read last Nshell\n\n  cout << \" Reading bin Files for NshellMax = \" << NshellMax << endl;\n  AcutN[NshellMax].Nshell=NshellMax;\n  AbasisNp1.Nshell=NshellMax;\n  //ThisCode.ReadArrays(\"test\"); // ReadsInto pAcutN\n  // Not too handy...\n\n  sprintf(CNsites,\"%d\",NshellMax);\n  //strcpy(ext,\"test_N\");\n  strcpy(ext,ThisCode.SaveArraysFileName);\n  strcat(ext,\"_N\");\n  strcat(ext,CNsites);\n  strcat(ext,\".bin\");\n\n  // Read Abasis\n  strcpy(arqname,\"Abasis_\");\n  strcat(arqname,ext);\n  AbasisNp1.ReadBin(arqname);\n\n  // Read Acut\n  strcpy(arqname,\"Acut_\");\n  strcat(arqname,ext);\n  AcutN[NshellMax].ReadBin(arqname);\n\n  // Read Operators at NshellMax \n  for (int iop=0;iop<NFermiOps;iop++){\n    sprintf(CNmat,\"%d\",iop);\n    strcpy(arqname,\"Mat\");\n    strcat(arqname,CNmat);\n    strcat(arqname,\"_\");\n    strcat(arqname,ext);\n    OpArrayN[iop][NshellMax].ReadBin(arqname);\n    // Need a better way to do this but for now it will do:\n    // Actually, from Mat block it works!\n    //OpArrayN[iop][NshellMax].CheckForMatEl=OneChQSz_cd_check;\n\n  }\n  // end read operators\n\n  cout << \" NshellMax Files read \"<< endl;\n\n  // FDM-NRG: Setting temperature\n  DM=CalcDN(ThisCode.Lambda,NshellMax-1); // Why????\n  TempBar=Temp/DM;\n  ZN=AcutN[NshellMax].PartitionFunc(1.0/TempBar);\n  if (!UseFDM)\n    ParamsTemp.push_back(ZN); // for NshellMax\n\n  wN.push_back(ZN);\n  ZTot=ZN;\n  cout << \" Temp = \" << Temp << \" at N= \" << NshellMax \n       << \" TempBar = \" << TempBar \n       << \" DN = \" << DM\n       << \" ZNdisc = ZN = \" << ZN \n       << \" ZwNN = \" << ZN*pow(4.0,NshellMax-NshellMax)\n       << endl;\n  /////////\n\n  // Read AcutN \n  for (int Nshell=NshellMax-1;Nshell>=ThisCode.Nsites0;Nshell--){\n\n    cout << \" Reading AcutN in Nshell = \" << Nshell << endl;\n\n    //AcutN[Nshell].ClearAll();\n    //AcutN[Nshell].Nshell=Nshell;\n\n    sprintf(CNsites,\"%d\",Nshell);\n    strcpy(ext,ThisCode.SaveArraysFileName);\n    strcat(ext,\"_N\");\n    strcat(ext,CNsites);\n    strcat(ext,\".bin\");\n\n    // Read Acut\n    strcpy(arqname,\"Acut_\");\n    strcat(arqname,ext);\n    AcutN[Nshell].ReadBin(arqname);\n\n    // FDM-NRG: Setting temperature\n    DM=CalcDN(ThisCode.Lambda,Nshell-1);\n    TempBar=Temp/DM;\n    // Partition function \n    ZN=AcutN[Nshell].PartitionFunc(1.0/TempBar);\n    // Partition function for discarded states\n    ZNdisc=AcutN[Nshell].PartitionFuncDisc(1.0/TempBar);\n    wN.push_back(ZNdisc*pow(4.0,NshellMax-Nshell));\n    ZTot+=ZNdisc*pow(4.0,NshellMax-Nshell);\n    cout << \" Temp = \" << Temp << \" at N= \" << Nshell \n  \t << \" TempBar = \" << TempBar \n  \t << \" DM = \" << DM\n  \t << \" ZN = \" << ZN \n  \t << \" ZNdisc = \" << ZNdisc \n  \t << \" ZwNN = \" << ZNdisc*pow(4.0,NshellMax-Nshell)\n  \t << endl;\n    /////////\n  }\n  //end loop in Nshell\n\n  cout << \"Ztot = \" << ZTot << endl;\n\n  // Calculate wN\n  double NormwN=0.0;\n  for (int ii=0; ii<wN.size(); ii++){\n    wN[ii]/=ZTot;\n    cout << \" wN[\" << NshellMax-ii << \"] = \" << wN[ii] << endl;\n    NormwN+=wN[ii];\n  }\n  cout << \" Sum_N wN = \" << NormwN << endl;\n\n  // end calculate wn\n    \n  \n  if (UseFDM)\n    ParamsTemp.push_back(ZTot); // for NshellMax\n    \n  // For 1-channel only!! d=4\n \n\n  // Set density matrix at the LAST NRG iteration\n\n  // Either CalcRhoN AND save it OR read it from file\n  // Read RhoNmax\n  sprintf(CNsites,\"%d\",NshellMax);\n  strcpy(ext,ThisCode.SaveArraysFileName);\n  strcat(ext,\"_N\");\n  strcat(ext,CNsites);\n  strcat(ext,\".bin\");\n\n  strcpy(arqname,\"rhoDM_\");\n  strcat(arqname,ext);\n\n  if (ThisCode.CheckFileExists(arqname)){\n    cout << \" DM_NRG: Found file \" << arqname << endl;\n    RhoN[NshellMax].ReadBin(arqname);\n  }else{\n    DM_NRG_SetRhoNmax(ParamsTemp,&AcutN[NshellMax],&RhoN[NshellMax]);\n    RhoN[NshellMax].SaveBin(arqname);\n  }\n\n  cout << \" trace(Rho[Nshell= \" << NshellMax << \" ]) = \" << RhoN[NshellMax].CalcTrace() << endl;\n\n\n  //if (NshellMax==48){\n  //cout << \" Rho Nshell = \" << NshellMax << endl;\n  //RhoN[NshellMax].PrintAllBlocks();}\n  // Debugging\n  double qnums[2];\n  int iBl=0;\n  \n  // Calculate reduced density matrices\n\n  for (int Nshell=NshellMax-1;Nshell>=ThisCode.Nsites0;Nshell--){\n\n    cout << \"DM-NRG: working on Nshell = \" << Nshell << endl;\n\n    AbasisN.ClearAll();\n    AbasisN.Nshell=Nshell;\n    \n    // AcutN[Nshell].ClearAll();\n    // AcutN[Nshell].Nshell=Nshell;\n\n    sprintf(CNsites,\"%d\",Nshell);\n    //strcpy(ext,\"test_N\");\n    strcpy(ext,ThisCode.SaveArraysFileName);\n    strcat(ext,\"_N\");\n    strcat(ext,CNsites);\n    strcat(ext,\".bin\");\n\n    // Read Abasis\n    strcpy(arqname,\"Abasis_\");\n    strcat(arqname,ext);\n    AbasisN.ReadBin(arqname);\n\n    // Read Acut (read already)\n    // strcpy(arqname,\"Acut_\");\n    // strcat(arqname,ext);\n    // AcutN[Nshell].ReadBin(arqname);\n\n\n    // Set ChildStates in AcutN\n \n    DM_NRG_SetChildSt(&AcutN[Nshell],&AbasisNp1);\n\n    // Set RhoN from RhoNp1\n\n    MyTime.restart();\n\n    // FDM-NRG: Setting temperature\n    DM=CalcDN(ThisCode.Lambda,Nshell-1);\n    TempBar=Temp/DM;\n    // Partition function \n    ZN=AcutN[Nshell].PartitionFunc(1.0/TempBar);\n    // Partition function for discarded states\n    ZNdisc=AcutN[Nshell].PartitionFuncDisc(1.0/TempBar);\n    cout << \" Temp = \" << Temp << \" at N= \" << Nshell \n  \t << \" TempBar = \" << TempBar \n  \t << \" DN = \" << DM\n  \t << \" ZN = \" << ZN \n  \t << \" ZNdisc = \" << ZNdisc \n  \t << endl;\n\n    ParamsTemp.clear();\n    ParamsTemp.push_back(TempBar);\n    //ParamsTemp.push_back(ZN); // NOT ZNdisc!!\n    ParamsTemp.push_back(ZTot/pow(4.0,NshellMax-Nshell)); // =ZNdisc/wN !!\n    // For 1-channel only!! d=4\n    //wN.push_back(ZNdisc*pow(4.0,NshellMax-Nshell));\n    /////////\n\n    // Either CalcRhoN AND save it OR read it from file\n\n    // Read RhoN\n    strcpy(arqname,\"rhoDM_\");\n    strcat(arqname,ext);\n\n    if (ThisCode.CheckFileExists(arqname)){\n      cout << \" DM_NRG: Found file \" << arqname << endl;\n      RhoN[Nshell].ReadBin(arqname);\n    }else{\n      if (ThisCode.totalS){\n\tDM_NRG_CalcRhoN_withSU2(ParamsTemp,UseFDM,\n\t\t\t\t&AcutN[Nshell],&AcutN[Nshell+1],\n\t\t\t\t&AbasisNp1,&SingleSite,\n\t\t\t\t&RhoN[Nshell],&RhoN[Nshell+1]);\n\n      }\n      else{\n\tDM_NRG_CalcRhoN(ParamsTemp,UseFDM,\n\t\t\t&AcutN[Nshell],&AcutN[Nshell+1],&AbasisNp1,\n\t\t\t&RhoN[Nshell],&RhoN[Nshell+1]);\n      }\n      // if SU(2) symmetry\n      RhoN[Nshell].SaveBin(arqname);\n    }\n\n    time_elapsed=MyTime.elapsed();\n    cout << \" Rho Nshell = \" << Nshell \n\t << \" completed in \" << time_elapsed << \" secs \" << endl;\n\n    cout << \" trace(Rho[Nshell= \" << Nshell << \" ]) = \" << RhoN[Nshell].CalcTrace() << endl;\n    // Debugging\n//      if (Nshell==1){\n//        RhoN[Nshell].PrintAllBlocks();\n//     qnums[0]=-2.000;\n//     qnums[1]=1.000;\n//     iBl=RhoN[Nshell].GetBlockFromQNumbers(qnums);\n//     RhoN[Nshell].PrintMatBlock(iBl,iBl);\n//     qnums[0]=2.000;\n//     qnums[1]=1.000;\n//     iBl=RhoN[Nshell].GetBlockFromQNumbers(qnums);\n//     RhoN[Nshell].PrintMatBlock(iBl,iBl);\n//      }\n\n    // Update AbasisNp1\n    AbasisNp1.ClearAll();\n    AbasisNp1=AbasisN;\n\n    // Read Operators \n    for (int iop=0;iop<NFermiOps;iop++){\n      sprintf(CNmat,\"%d\",iop); // Get all SavedMatrices\n      strcpy(arqname,\"Mat\");\n      strcat(arqname,CNmat);\n      strcat(arqname,\"_\");\n      strcat(arqname,ext);\n      OpArrayN[iop][Nshell].ReadBin(arqname);\n      // Need a better way to do this but for now it will do:\n      // Not needed!\n      //OpArrayN[iop][Nshell].CheckForMatEl=OneChQSz_cd_check;\n\n    }\n    // end read operators\n    \n    // Debug\n//     if ((Nshell==0)||(Nshell==1)){\n//       cout << \" Op1 : \" << endl;\n//       OpArrayN[0][Nshell].PrintAllBlocks();\n//       cout << \" Op2 : \" << endl;\n//       OpArrayN[1][Nshell].PrintAllBlocks();\n//       cout << \" DM-NRG: Abasis(Nshell=\"<<Nshell<<\"): \" << endl;\n//       AbasisN.PrintBasisAll();\n//       cout << \" Op1 (Nshell=\"<< Nshell<<\"): \" << endl;\n//       OpArrayN[0][Nshell].PrintAllBlocks();\n//     }\n    // end debug\n\n\n  }\n  // end loop in Nshell\n\n\n  // Save RhoN matrices\n\n  // Read RhoN matrices\n\n  // Given AcutN, rhoN and the Operators, calculate the spectral density\n\n  // Calculate rho_0_0 and rho_Costi. Good for debugging\n//   DM_NRG_CalcSpecFuncs(&ThisCode,AcutN,RhoN,OpArrayN,0,0);\n//   DM_NRG_CalcSpecFuncs(&ThisCode,AcutN,RhoN,OpArrayN,1,1);\n//   DM_NRG_CalcSpecFuncs(&ThisCode,AcutN,RhoN,OpArrayN,2,2);\n\n\n   CSpecFunction spec1;\n\n   spec1.Lambda=ThisCode.Lambda;\n   spec1.z_twist=ThisCode.code_z_twist;\n   spec1.NshellMax=ThisCode.Nsitesmax;\n   spec1.NshellMin=ThisCode.Nsites0;\n   spec1.AcutN=AcutN;\n   spec1.RhoN=RhoN;\n   spec1.UseCFS=UseCFS;\n\n   // Spec Dens\n   if (UseCFS==2) spec1.BDelta=LogGaussDelta; // FDM calculation\n   else spec1.BDelta=BroadDelta;\n   //spec1.dBroad=0.5*log(ThisCode.Lambda);\n   spec1.dBroad=bbroad;\n\n   // Finite Temp stuff (need to test this!)\n   if (UseCFS==1) spec1.BDeltaTemp=LorentzDeltaAnders;\n   else if (UseCFS==2) spec1.BDeltaTemp=GaussDelta;\n   else spec1.BDeltaTemp=LorentzDelta;\n\n   //spec1.Temp=0.0;\n   //spec1.Mtemp=1000;\n   spec1.Temp=Temp;\n   spec1.Mtemp=Mtemp;\n   spec1.Betabar=betabar;\n\n   spec1.TwindowFac=twindow;\n   spec1.dBroadTemp=broadtemp;\n\n\n   if (UseGap){\n     spec1.Gap=ThisCode.dInitParams[3];\n     cout << \" Using gap = \" << spec1.Gap << endl;\n   }\n   // end setting up the gap]\n\n   // Debug (Mar 2016)\n   //DM_NRG_CalcSpecFunc_ij(&spec1,OpArrayN,1,1,UseCFS,UseGap,Nw);\n\n   // Calculate ALL spectral functions!!\n   // Jun 2015: Only diagonal functions for now...\n   for (int iop=0; iop<NFermiOps; iop++){\n     DM_NRG_CalcSpecFunc_ij(&spec1,OpArrayN,iop,iop,UseGap,Nw);\n//     if (UseCFS!=0){\n//       DM_NRG_CalcSpecFunc_ij(&spec1,OpArrayN,iop,iop,UseCFS,Nw);\n//     } else {\n//       for (int jop=0; jop<NFermiOps; jop++){\n//\t DM_NRG_CalcSpecFunc_ij(&spec1,OpArrayN,iop,jop,UseCFS,Nw);\n//       }\n//     }\n//     // end if CFS\n   }\n   // end loop in Fermi Ops\n\n   //int iop=0;\n   //int jop=0;\n   //CFS_CalcSpecFunc_ij(&spec1,OpArrayN,iop,jop);\n   \n\n\n  delete[] RhoN;\n  delete[] AcutN;\n  for (int iop=NFermiOps-1;iop>=0;iop--){\n    delete[] OpArrayN[iop];\n  }\n  delete[] OpArrayN;\n\n}\n// end MAIN\n", "meta": {"hexsha": "3e23db7cf192b49a75f6520e3467eb4811419726", "size": 13987, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/DM_NRG/DM_NRG.cpp", "max_stars_repo_name": "lgds/NRG_USP", "max_stars_repo_head_hexsha": "ff66846e92498aa429cce6fc5793bec23ad03eb4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2015-09-21T20:58:45.000Z", "max_stars_repo_stars_event_max_datetime": "2019-03-20T01:21:41.000Z", "max_issues_repo_path": "src/DM_NRG/DM_NRG.cpp", "max_issues_repo_name": "lgds/NRG_USP", "max_issues_repo_head_hexsha": "ff66846e92498aa429cce6fc5793bec23ad03eb4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/DM_NRG/DM_NRG.cpp", "max_forks_repo_name": "lgds/NRG_USP", "max_forks_repo_head_hexsha": "ff66846e92498aa429cce6fc5793bec23ad03eb4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.2420262664, "max_line_length": 115, "alphanum_fraction": 0.6224351183, "num_tokens": 4758, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.8128672997041659, "lm_q2_score": 0.4263215925474903, "lm_q1q2_score": 0.34654288173965814}}
{"text": "#include \"manip.h\"\r\n#include <iostream>\r\n#include <cmath>\r\n#include <cassert>\r\n#include <vector>\r\n#include <utility>\r\n#include <algorithm>\r\n#include <boost/multi_array.hpp>\r\n#include <boost/bind.hpp>\r\n#include \"gd.h\"\r\n#include \"../image/image.h\"\r\n\r\n#define GOSA_KAKUSAN_YCBCR(dx, dy, rate, rate_total) do { \\\r\n        const int tx = x + d * dx; \\\r\n        const int ty = y + dy; \\\r\n        if(0 <= tx && tx < width && 0 <= ty && ty < height) { \\\r\n            gosa[tx][ty][0] += gosa_y  * rate / rate_total; \\\r\n            gosa[tx][ty][1] += gosa_cb * rate / rate_total; \\\r\n            gosa[tx][ty][2] += gosa_cr * rate / rate_total; \\\r\n        } \\\r\n    } while(0)\r\n\r\n#define GOSA_KAKUSAN_RGB(dx, dy, rate, rate_total) do { \\\r\n        const int tx = x + d * dx; \\\r\n        const int ty = y + dy; \\\r\n        if(0 <= tx && tx < width && 0 <= ty && ty < height) { \\\r\n            gosa[tx][ty][0] += gosa_r * rate / rate_total; \\\r\n            gosa[tx][ty][1] += gosa_g * rate / rate_total; \\\r\n            gosa[tx][ty][2] += gosa_b * rate / rate_total; \\\r\n        } \\\r\n    } while(0)\r\n\r\nnamespace manip {\r\n    namespace {\r\n        // 大津の手法による閾値の計算\r\n        int otsu_threshold(const double average, const int histgram[256]) {\r\n            double max = 0.;\r\n            int max_no = 0;\r\n            for(int i = 0; i < 256; ++i) {\r\n                long count1 = 0, count2 = 0;\r\n                long long data = 0;\r\n                double breakup1 = 0., breakup2 = 0.;\r\n                double average1 = 0., average2 = 0.;\r\n                for(int j = 0; j < i; ++j) {\r\n                    count1 += histgram[j];\r\n                    data += histgram[j] * j;\r\n                }\r\n                if(count1 > 0) {\r\n                    average1 = (double)data / (double)count1;\r\n                    for(int j = 0; j < i; ++j) {\r\n                        breakup1 += pow(j - average1, 2) * histgram[j];\r\n                    }\r\n                    breakup1 /= (double)count1;\r\n                }\r\n\r\n                data = 0;\r\n                for(int j = i; j < 256; ++j) {\r\n                    count2 += histgram[j];\r\n                    data += histgram[j] * j;\r\n                }\r\n                if(count2 > 0) {\r\n                    average2 = (double)data / (double)count2;\r\n                    for(int j = i; j < 256; ++j) {\r\n                        breakup2 += pow(j - average2, 2) * histgram[j];\r\n                    }\r\n                    breakup2 /= (double)count2;\r\n                }\r\n                const double class1 = (double)count1 * breakup1 + (double)count2 * breakup2;\r\n                const double class2 = (double)count1 * pow(average1 - average, 2) + (double)count2 * pow(average2 - average, 2);\r\n                const double tmp = class2 / class1;\r\n                if(max < tmp) {\r\n                    max = tmp;\r\n                    max_no = i;\r\n                }\r\n            }\r\n            return max_no;\r\n        }\r\n\r\n        // 3x3 微分オペレータを適用する\r\n        bool apply_operator_3x3(gd &img, const double op[3][3], double filter_div, double offset) {\r\n            const int width = img.width();\r\n            const int height = img.height();\r\n            gd dst(width, height);\r\n            dst.alpha_blending(false);\r\n\r\n            for(int y = 0; y < height; ++y) {\r\n                for(int x = 0; x < width; ++x) {\r\n                    double sum_r = 0., sum_g = 0., sum_b = 0., sum_a = 0.;\r\n                    for(int j = -1; j <= 1; ++j) {\r\n                        const int ref_y = std::min(std::max(0, y + j), height - 1);\r\n                        for(int i = -1; i <= 1; ++i) {\r\n                            const int ref_x = std::min(std::max(0, x + i), width - 1);\r\n                            const double ref_op = op[i + 1][j + 1];\r\n                            const gd::color color = img.pixel_fast(ref_x, ref_y);\r\n                            const int a = (color & 0x7f000000) >> 24;\r\n                            if(a == 0x7f) {\r\n                                sum_a += a * ref_op;\r\n                            } else if(std::abs(ref_op) > 0) {\r\n                                const int r = (color & 0xff0000) >> 16;\r\n                                const int g = (color & 0x00ff00) >> 8;\r\n                                const int b = (color & 0x0000ff);\r\n                                sum_r += r * ref_op;\r\n                                sum_g += g * ref_op;\r\n                                sum_b += b * ref_op;\r\n                                sum_a += a * ref_op;\r\n                            }\r\n                        }\r\n                    }\r\n\r\n                    const int r = std::max(0, std::min(255, static_cast<int>(sum_r / filter_div + offset + 0.5)));\r\n                    const int g = std::max(0, std::min(255, static_cast<int>(sum_g / filter_div + offset + 0.5)));\r\n                    const int b = std::max(0, std::min(255, static_cast<int>(sum_b / filter_div + offset + 0.5)));\r\n                    const int a = std::max(0, std::min(127, static_cast<int>(sum_a + 0.5)));\r\n                    dst.pixel_fast(x, y, (a << 24) | (r << 16) | (g << 8) | b);\r\n                }\r\n            }\r\n            img.swap(dst);\r\n            return true;\r\n        }\r\n\r\n        bool do_grayscale(gd &img, int black = 0, int white = 255, gd::color background = 0x7fffffff) {\r\n            img.convert_to_true_color();\r\n            img.alpha_blending(false);\r\n            if((background & 0x7f000000) != 0x7f000000) {\r\n                if(!fill_background(img, background)) {\r\n                    return false;\r\n                }\r\n            }\r\n            const int width = img.width();\r\n            const int height = img.height();\r\n            const double range = white - black;\r\n            for(int y = 0; y < height; ++y) {\r\n                for(int x = 0; x < width; ++x) {\r\n                    const gd::color color = img.pixel_fast(x, y);\r\n                    const int r = (color & 0xff0000) >> 16;\r\n                    const int g = (color & 0x00ff00) >>  8;\r\n                    const int b = (color & 0x0000ff);\r\n                    const int a = (color & 0x7f000000); // そのまま使うのでビットシフトしない\r\n                    const double gray = (r * 0.298912) + (g * 0.586611) + (b * 0.114478);\r\n                    const int put =\r\n                        (gray <= black)\r\n                            ? 0\r\n                            : (gray >= white)\r\n                                ? 255\r\n                                : std::min(255, std::max(0, static_cast<int>((gray - black) * 255. / range + 0.5)));\r\n                    img.pixel_fast(x, y, a | (put * 0x010101));\r\n                }\r\n            }\r\n            return true;\r\n        }\r\n\r\n        inline int convert_to_websafe_color(int c) {\r\n            return c < 0 ? 0 : c > 255 ? 255 : ((int)round(c / 51.)) * 51;\r\n        }\r\n\r\n        inline double rgb_to_y(int r, int g, int b) {\r\n            return (0.29900 * r) + (0.58700 * g) + (0.11400 * b);\r\n        }\r\n\r\n        inline double rgb_to_cb(int r, int g, int b) {\r\n            return (-0.16874 * r) - (0.33126 * g) + (0.50000 * b) + 128.;\r\n        }\r\n\r\n        inline double rgb_to_cr(int r, int g, int b) {\r\n            return (0.50000 * r) - (0.41869 * g) - (0.08131 * b) + 128.;\r\n        }\r\n\r\n        inline int ycbcr_to_rgb(double y, double cb, double cr) {\r\n            cb -= 128.;\r\n            cr -= 128.;\r\n            const double r_ = y                  + (1.40200 * cr);\r\n            const double g_ = y - (0.34414 * cb) - (0.71414 * cr);\r\n            const double b_ = y + (1.77200 * cb);\r\n            const int r = static_cast<int>(r_ < 0.5 ? 0 : r_ >= 254.5 ? 255.0 : (r_ + 0.5));\r\n            const int g = static_cast<int>(g_ < 0.5 ? 0 : g_ >= 254.5 ? 255.0 : (g_ + 0.5));\r\n            const int b = static_cast<int>(b_ < 0.5 ? 0 : b_ >= 254.5 ? 255.0 : (b_ + 0.5));\r\n            return (r << 16) | (g << 8) | b;\r\n        }\r\n\r\n        inline size_t find_nearest_color_y_cb_cr(double y, double cb, double cr, const int palette[], const size_t palette_size) {\r\n            y  = y  < 0.0 ? 0.0 : y  > 255.0 ? 255.0 : y;\r\n            cb = cb < 0.0 ? 0.0 : cb > 255.0 ? 255.0 : cb;\r\n            cr = cr < 0.0 ? 0.0 : cr > 255.0 ? 255.0 : cr;\r\n            size_t min_index = 0;\r\n            double min_score = INFINITY;\r\n            for(size_t i = 0; i < palette_size; ++i) {\r\n                const int p_color = palette[i];\r\n                const double p_y  = (double)((p_color & 0xff0000) >> 16);\r\n                const double p_cb = (double)((p_color & 0x00ff00) >>  8);\r\n                const double p_cr = (double)((p_color & 0x0000ff)      );\r\n                const double d_cbcr = sqrt(pow(cb - p_cb, 2.) + pow(cr - p_cr, 2.));\r\n                const double score = sqrt(pow(y - p_y, 2.) + pow(d_cbcr, 2));\r\n                if(score < min_score) {\r\n                    min_index = i;\r\n                    min_score = score;\r\n                }\r\n            }\r\n            return min_index;\r\n        }\r\n\r\n        int famicom_convert(gd &img, DITHERING_METHOD dither, const int palette[], const size_t palette_size, int used_count[]) {\r\n            img.alpha_blending(false);\r\n            const int width = img.width();\r\n            const int height = img.height();\r\n            boost::multi_array<double, 3> gosa(boost::extents[width][height][3]);\r\n            std::fill(gosa.origin(), gosa.origin() + gosa.size(), 0);\r\n\r\n            for(int y = 0; y < height; ++y) {\r\n                const int d = (y % 2 == 0) ? 1 : -1;\r\n                const int x_begin = (y % 2 == 0) ? 0 : width - 1;\r\n                const int x_end   = (y % 2 == 0) ? width : -1;\r\n                for(int x = x_begin; x != x_end; x += d) {\r\n                    const gd::color color = img.pixel_fast(x, y);\r\n                    const int r = (color & 0x00ff0000) >> 16;\r\n                    const int g = (color & 0x0000ff00) >> 8;\r\n                    const int b = (color & 0x000000ff);\r\n                    const double cy = rgb_to_y(r, g, b)  + gosa[x][y][0];\r\n                    const double cb = rgb_to_cb(r, g, b) + gosa[x][y][1];\r\n                    const double cr = rgb_to_cr(r, g, b) + gosa[x][y][2];\r\n                    const size_t index = find_nearest_color_y_cb_cr(cy, cb, cr, palette, palette_size);\r\n                    ++used_count[index];\r\n                    const int p_y  = (palette[index] & 0xff0000) >> 16;\r\n                    const int p_cb = (palette[index] & 0x00ff00) >>  8;\r\n                    const int p_cr = (palette[index] & 0x0000ff);\r\n                    img.pixel_fast(x, y, ycbcr_to_rgb(p_y, p_cb, p_cr));\r\n                    const double gosa_y  = cy - p_y;\r\n                    const double gosa_cb = cb - p_cb;\r\n                    const double gosa_cr = cr - p_cr;\r\n\r\n                    switch(dither) {\r\n                    case DITHERING_NONE:\r\n                    default:\r\n                        break;\r\n                    case DITHERING_FLOYD_STEINBERG:\r\n                        // - X 7\r\n                        // 3 5 1\r\n                        GOSA_KAKUSAN_YCBCR( 1, 0, 7., 16.);\r\n                        GOSA_KAKUSAN_YCBCR(-1, 0, 3., 16.);\r\n                        GOSA_KAKUSAN_YCBCR( 0, 0, 5., 16.);\r\n                        GOSA_KAKUSAN_YCBCR( 1, 0, 1., 16.);\r\n                        break;\r\n                    case DITHERING_SIERRA_3LINE:\r\n                        // - - X 5 3\r\n                        // 2 4 5 4 2\r\n                        // 0 2 3 2 0\r\n                        GOSA_KAKUSAN_YCBCR( 1, 0, 5., 32.);\r\n                        GOSA_KAKUSAN_YCBCR( 2, 0, 3., 32.);\r\n                        GOSA_KAKUSAN_YCBCR(-2, 1, 2., 32.);\r\n                        GOSA_KAKUSAN_YCBCR(-1, 1, 4., 32.);\r\n                        GOSA_KAKUSAN_YCBCR( 0, 1, 5., 32.);\r\n                        GOSA_KAKUSAN_YCBCR( 1, 1, 4., 32.);\r\n                        GOSA_KAKUSAN_YCBCR( 2, 1, 2., 32.);\r\n                        GOSA_KAKUSAN_YCBCR(-1, 2, 2., 32.);\r\n                        GOSA_KAKUSAN_YCBCR( 0, 2, 3., 32.);\r\n                        GOSA_KAKUSAN_YCBCR( 1, 2, 2., 32.);\r\n                        break;\r\n                    case DITHERING_SIERRA_2LINE:\r\n                        // - - X 4 3\r\n                        // 1 2 3 2 1\r\n                        GOSA_KAKUSAN_YCBCR( 1, 0, 4., 16.);\r\n                        GOSA_KAKUSAN_YCBCR( 2, 0, 3., 16.);\r\n                        GOSA_KAKUSAN_YCBCR(-2, 1, 1., 16.);\r\n                        GOSA_KAKUSAN_YCBCR(-1, 1, 2., 16.);\r\n                        GOSA_KAKUSAN_YCBCR( 0, 1, 3., 16.);\r\n                        GOSA_KAKUSAN_YCBCR( 1, 1, 2., 16.);\r\n                        GOSA_KAKUSAN_YCBCR( 2, 1, 1., 16.);\r\n                        break;\r\n                    case DITHERING_SIERRA_LITE:\r\n                        // - X 2\r\n                        // 1 1 0\r\n                        GOSA_KAKUSAN_YCBCR( 1, 0, 2., 4.);\r\n                        GOSA_KAKUSAN_YCBCR(-1, 1, 1., 4.);\r\n                        GOSA_KAKUSAN_YCBCR( 0, 1, 1., 4.);\r\n                        break;\r\n                    case DITHERING_ATKINSON:\r\n                        // - - X 1 1\r\n                        // 0 1 1 1 0\r\n                        // 0 0 1 0 0 ※合計6だが8で割る(75%拡散)\r\n                        GOSA_KAKUSAN_YCBCR( 1, 0, 1., 8.);\r\n                        GOSA_KAKUSAN_YCBCR( 2, 0, 1., 8.);\r\n                        GOSA_KAKUSAN_YCBCR(-1, 1, 1., 8.);\r\n                        GOSA_KAKUSAN_YCBCR( 0, 1, 1., 8.);\r\n                        GOSA_KAKUSAN_YCBCR( 1, 1, 1., 8.);\r\n                        GOSA_KAKUSAN_YCBCR( 0, 2, 1., 8.);\r\n                        break;\r\n                    }\r\n                }\r\n            }\r\n            int count = 0;\r\n            for(size_t i = 0; i < palette_size; ++i) {\r\n                if(used_count[i] > 0) {\r\n                    ++count;\r\n                }\r\n            }\r\n            return count;\r\n        }\r\n    }\r\n\r\n    bool grayscale(gd &img) {\r\n        return do_grayscale(img, 0x00, 0xff, (0x7f << 24));\r\n    }\r\n\r\n    bool colorize(gd &img, int red, int green, int blue, int alpha) {\r\n        img.convert_to_true_color();\r\n        img.alpha_blending(false);\r\n        const int width = img.width();\r\n        const int height = img.height();\r\n        for(int y = 0; y < height; ++y) {\r\n            for(int x = 0; x < width; ++x) {\r\n                const gd::color color = img.pixel_fast(x, y);\r\n                const int r = ((color & 0xff0000) >> 16) + red;\r\n                const int g = ((color & 0x00ff00) >>  8) + green;\r\n                const int b = (color & 0x0000ff) + blue;\r\n                const int a = ((color & 0x7f000000) >> 24) + alpha;\r\n                const int new_color = \r\n                    ((a < 0 ? 0 : a > 127 ? 127 : a) << 24) |\r\n                    ((r < 0 ? 0 : r > 255 ? 255 : r) << 16) |\r\n                    ((g < 0 ? 0 : g > 255 ? 255 : g) <<  8) |\r\n                     (b < 0 ? 0 : b > 255 ? 255 : b);\r\n                img.pixel_fast(x, y, new_color);\r\n            }\r\n        }\r\n        return true;\r\n    }\r\n\r\n    bool binarize(gd &img, bool is_grayscaled, THRESHOLDING thresholding, DITHERING_METHOD dithering) {\r\n        img.convert_to_true_color();\r\n        img.alpha_blending(false);\r\n        int hist_r[256] = {};\r\n        int hist_g[256] = {};\r\n        int hist_b[256] = {};\r\n        long total_r = 0;\r\n        long total_g = 0;\r\n        long total_b = 0;\r\n        int pixel_count = 0;\r\n        const int width = img.width();\r\n        const int height = img.height();\r\n\r\n        // ヒストグラムを取得\r\n        for(int y = 0; y < height; ++y) {\r\n            for(int x = 0; x < width; ++x) {\r\n                const gd::color color = img.pixel_fast(x, y);\r\n                const int a = (color & 0x7f000000) >> 24;\r\n                if(a == 0x7f) {\r\n                    // 完全透明なのでスキップ\r\n                    continue;\r\n                }\r\n                ++pixel_count;\r\n                const int r = (color & 0xff0000) >> 16;\r\n                ++hist_r[r];\r\n                total_r += r;\r\n                if(!is_grayscaled) {\r\n                    const int g = (color & 0x00ff00) >> 8;\r\n                    ++hist_g[g];\r\n                    total_g += g;\r\n                    const int b = (color & 0x0000ff);\r\n                    ++hist_b[b];\r\n                    total_b += b;\r\n                }\r\n            }\r\n        }\r\n\r\n        // 完全に透明な画像だったわ\r\n        if(pixel_count < 1) {\r\n            return true;\r\n        }\r\n\r\n        boost::multi_array<double, 3> gosa(boost::extents[width][height][3]);\r\n        std::fill(gosa.origin(), gosa.origin() + gosa.size(), 0);\r\n\r\n        // 閾値を計算\r\n        const int threshold_r = (thresholding == THRESHOLD_HALF) ? 128 : otsu_threshold((double)total_r / (double)pixel_count, hist_r);\r\n        const int threshold_g = is_grayscaled ? threshold_r : (thresholding == THRESHOLD_HALF) ? 128 : otsu_threshold((double)total_g / (double)pixel_count, hist_g);\r\n        const int threshold_b = is_grayscaled ? threshold_r : (thresholding == THRESHOLD_HALF) ? 128 : otsu_threshold((double)total_b / (double)pixel_count, hist_b);\r\n        for(int y = 0; y < height; ++y) {\r\n            const int d = (y % 2 == 0) ? 1 : -1;\r\n            const int x_begin = (y % 2 == 0) ? 0 : width - 1;\r\n            const int x_end   = (y % 2 == 0) ? width : -1;\r\n            for(int x = x_begin; x != x_end; x += d) {\r\n                const gd::color color = img.pixel_fast(x, y);\r\n                const int a = (color & 0x7f000000);\r\n                const double r = static_cast<double>((color & 0xff0000) >> 16) + gosa[x][y][0];\r\n                const double g = static_cast<double>((color & 0x00ff00) >>  8) + gosa[x][y][1];\r\n                const double b = static_cast<double>((color & 0x0000ff)      ) + gosa[x][y][2];\r\n                const int put_r = (r < threshold_r) ? 0x00 : 0xff;\r\n                const int put_g = (g < threshold_g) ? 0x00 : 0xff;\r\n                const int put_b = (b < threshold_b) ? 0x00 : 0xff;\r\n                img.pixel_fast(x, y, a | (put_r << 16) | (put_g << 8) | put_b);\r\n                if(a < 0x7f000000) {\r\n                    const double gosa_r = r - static_cast<double>(put_r);\r\n                    const double gosa_g = g - static_cast<double>(put_g);\r\n                    const double gosa_b = b - static_cast<double>(put_b);\r\n                    switch(dithering) {\r\n                    case DITHERING_NONE:\r\n                    default:\r\n                        break;\r\n                    case DITHERING_FLOYD_STEINBERG:\r\n                        // - X 7\r\n                        // 3 5 1\r\n                        GOSA_KAKUSAN_RGB( 1, 0, 7., 16.);\r\n                        GOSA_KAKUSAN_RGB(-1, 0, 3., 16.);\r\n                        GOSA_KAKUSAN_RGB( 0, 0, 5., 16.);\r\n                        GOSA_KAKUSAN_RGB( 1, 0, 1., 16.);\r\n                        break;\r\n                    case DITHERING_SIERRA_3LINE:\r\n                        // - - X 5 3\r\n                        // 2 4 5 4 2\r\n                        // 0 2 3 2 0\r\n                        GOSA_KAKUSAN_RGB( 1, 0, 5., 32.);\r\n                        GOSA_KAKUSAN_RGB( 2, 0, 3., 32.);\r\n                        GOSA_KAKUSAN_RGB(-2, 1, 2., 32.);\r\n                        GOSA_KAKUSAN_RGB(-1, 1, 4., 32.);\r\n                        GOSA_KAKUSAN_RGB( 0, 1, 5., 32.);\r\n                        GOSA_KAKUSAN_RGB( 1, 1, 4., 32.);\r\n                        GOSA_KAKUSAN_RGB( 2, 1, 2., 32.);\r\n                        GOSA_KAKUSAN_RGB(-1, 2, 2., 32.);\r\n                        GOSA_KAKUSAN_RGB( 0, 2, 3., 32.);\r\n                        GOSA_KAKUSAN_RGB( 1, 2, 2., 32.);\r\n                        break;\r\n                    case DITHERING_SIERRA_2LINE:\r\n                        // - - X 4 3\r\n                        // 1 2 3 2 1\r\n                        GOSA_KAKUSAN_RGB( 1, 0, 4., 16.);\r\n                        GOSA_KAKUSAN_RGB( 2, 0, 3., 16.);\r\n                        GOSA_KAKUSAN_RGB(-2, 1, 1., 16.);\r\n                        GOSA_KAKUSAN_RGB(-1, 1, 2., 16.);\r\n                        GOSA_KAKUSAN_RGB( 0, 1, 3., 16.);\r\n                        GOSA_KAKUSAN_RGB( 1, 1, 2., 16.);\r\n                        GOSA_KAKUSAN_RGB( 2, 1, 1., 16.);\r\n                        break;\r\n                    case DITHERING_SIERRA_LITE:\r\n                        // - X 2\r\n                        // 1 1 0\r\n                        GOSA_KAKUSAN_RGB( 1, 0, 2., 4.);\r\n                        GOSA_KAKUSAN_RGB(-1, 1, 1., 4.);\r\n                        GOSA_KAKUSAN_RGB( 0, 1, 1., 4.);\r\n                        break;\r\n                    case DITHERING_ATKINSON:\r\n                        // - - X 1 1\r\n                        // 0 1 1 1 0\r\n                        // 0 0 1 0 0 ※合計6だが8で割る(75%拡散)\r\n                        GOSA_KAKUSAN_RGB( 1, 0, 1., 8.);\r\n                        GOSA_KAKUSAN_RGB( 2, 0, 1., 8.);\r\n                        GOSA_KAKUSAN_RGB(-1, 1, 1., 8.);\r\n                        GOSA_KAKUSAN_RGB( 0, 1, 1., 8.);\r\n                        GOSA_KAKUSAN_RGB( 1, 1, 1., 8.);\r\n                        GOSA_KAKUSAN_RGB( 0, 2, 1., 8.);\r\n                        break;\r\n                    }\r\n                }\r\n            }\r\n        }\r\n        return true;\r\n    }\r\n\r\n    bool websafe(gd &img, DITHERING_METHOD dither) {\r\n        img.convert_to_true_color();\r\n        img.alpha_blending(false);\r\n        const int width = img.width();\r\n        const int height = img.height();\r\n        boost::multi_array<double, 3> gosa(boost::extents[width][height][3]);\r\n        std::fill(gosa.origin(), gosa.origin() + gosa.size(), 0); // 要らない？\r\n\r\n        for(int y = 0; y < height; ++y) {\r\n            const int d = (y % 2 == 0) ? 1 : -1;\r\n            const int x_begin = (y % 2 == 0) ? 0 : width - 1;\r\n            const int x_end   = (y % 2 == 0) ? width : -1;\r\n            for(int x = x_begin; x != x_end; x += d) {\r\n                const gd::color color = img.pixel_fast(x, y);\r\n                const int a = (color & 0x7f000000);\r\n                const double r = static_cast<double>((color & 0x00ff0000) >> 16) + gosa[x][y][0];\r\n                const double g = static_cast<double>((color & 0x0000ff00) >>  8) + gosa[x][y][1];\r\n                const double b = static_cast<double>((color & 0x000000ff)      ) + gosa[x][y][2];\r\n                const int web_r = convert_to_websafe_color(static_cast<int>(round(r)));\r\n                const int web_g = convert_to_websafe_color(static_cast<int>(round(g)));\r\n                const int web_b = convert_to_websafe_color(static_cast<int>(round(b)));\r\n                if(a < 0x7f000000) {\r\n                    const double gosa_r = r - static_cast<double>(web_r);\r\n                    const double gosa_g = g - static_cast<double>(web_g);\r\n                    const double gosa_b = b - static_cast<double>(web_b);\r\n                    switch(dither) {\r\n                    case DITHERING_NONE:\r\n                    default:\r\n                        break;\r\n                    case DITHERING_FLOYD_STEINBERG:\r\n                        // - X 7\r\n                        // 3 5 1\r\n                        GOSA_KAKUSAN_RGB( 1, 0, 7., 16.);\r\n                        GOSA_KAKUSAN_RGB(-1, 0, 3., 16.);\r\n                        GOSA_KAKUSAN_RGB( 0, 0, 5., 16.);\r\n                        GOSA_KAKUSAN_RGB( 1, 0, 1., 16.);\r\n                        break;\r\n                    case DITHERING_SIERRA_3LINE:\r\n                        // - - X 5 3\r\n                        // 2 4 5 4 2\r\n                        // 0 2 3 2 0\r\n                        GOSA_KAKUSAN_RGB( 1, 0, 5., 32.);\r\n                        GOSA_KAKUSAN_RGB( 2, 0, 3., 32.);\r\n                        GOSA_KAKUSAN_RGB(-2, 1, 2., 32.);\r\n                        GOSA_KAKUSAN_RGB(-1, 1, 4., 32.);\r\n                        GOSA_KAKUSAN_RGB( 0, 1, 5., 32.);\r\n                        GOSA_KAKUSAN_RGB( 1, 1, 4., 32.);\r\n                        GOSA_KAKUSAN_RGB( 2, 1, 2., 32.);\r\n                        GOSA_KAKUSAN_RGB(-1, 2, 2., 32.);\r\n                        GOSA_KAKUSAN_RGB( 0, 2, 3., 32.);\r\n                        GOSA_KAKUSAN_RGB( 1, 2, 2., 32.);\r\n                        break;\r\n                    case DITHERING_SIERRA_2LINE:\r\n                        // - - X 4 3\r\n                        // 1 2 3 2 1\r\n                        GOSA_KAKUSAN_RGB( 1, 0, 4., 16.);\r\n                        GOSA_KAKUSAN_RGB( 2, 0, 3., 16.);\r\n                        GOSA_KAKUSAN_RGB(-2, 1, 1., 16.);\r\n                        GOSA_KAKUSAN_RGB(-1, 1, 2., 16.);\r\n                        GOSA_KAKUSAN_RGB( 0, 1, 3., 16.);\r\n                        GOSA_KAKUSAN_RGB( 1, 1, 2., 16.);\r\n                        GOSA_KAKUSAN_RGB( 2, 1, 1., 16.);\r\n                        break;\r\n                    case DITHERING_SIERRA_LITE:\r\n                        // - X 2\r\n                        // 1 1 0\r\n                        GOSA_KAKUSAN_RGB( 1, 0, 2., 4.);\r\n                        GOSA_KAKUSAN_RGB(-1, 1, 1., 4.);\r\n                        GOSA_KAKUSAN_RGB( 0, 1, 1., 4.);\r\n                        break;\r\n                    case DITHERING_ATKINSON:\r\n                        // - - X 1 1\r\n                        // 0 1 1 1 0\r\n                        // 0 0 1 0 0 ※合計6だが8で割る(75%拡散)\r\n                        GOSA_KAKUSAN_RGB( 1, 0, 1., 8.);\r\n                        GOSA_KAKUSAN_RGB( 2, 0, 1., 8.);\r\n                        GOSA_KAKUSAN_RGB(-1, 1, 1., 8.);\r\n                        GOSA_KAKUSAN_RGB( 0, 1, 1., 8.);\r\n                        GOSA_KAKUSAN_RGB( 1, 1, 1., 8.);\r\n                        GOSA_KAKUSAN_RGB( 0, 2, 1., 8.);\r\n                        break;\r\n                    }\r\n                }\r\n                img.pixel_fast(x, y, a | (web_r << 16) | (web_g << 8) | web_b);\r\n            }\r\n        }\r\n        return true;\r\n    }\r\n\r\n    bool famicom(gd &img, DITHERING_METHOD dither) {\r\n        const int fixed_palette_y_cb_cr[] = {\r\n            0x008080, 0x1bde71, 0x24fe6c, 0x32975e, 0x3462bc, 0x34635b, 0x346394, 0x3774d1,\r\n            0x3c5ecd, 0x3d5d54, 0x3fa9bf, 0x46584e, 0x47c582, 0x5185eb, 0x57df47, 0x5ec1db,\r\n            0x63483a, 0x63973c, 0x6ad43a, 0x6b43e5, 0x6bd683, 0x6c4333, 0x6c6a34, 0x7c3aa2,\r\n            0x7c43ca, 0x7c8080, 0x808080, 0x93bf67, 0x9485cb, 0x98ba86, 0x9d5ac3, 0xa5534b,\r\n            0xa5b53b, 0xa79f0d, 0xb342b5, 0xb4aab6, 0xb619af, 0xb8aa02, 0xc26b38, 0xc28080,\r\n            0xc680a8, 0xc7a07b, 0xcc1b72, 0xd09a8b, 0xda4a98, 0xda959b, 0xdb6a93, 0xdb975e,\r\n            0xe3457a, 0xe36b65, 0xe75f93, 0xe87b63, 0xed8a8d, 0xff8080, \r\n        };\r\n        const size_t fixed_palette_count = sizeof(fixed_palette_y_cb_cr) / sizeof(fixed_palette_y_cb_cr[0]);\r\n\r\n        if(!fill_background(img, 0xffffff)) {\r\n            return false;\r\n        }\r\n        // それっぽさを出すために解像度を落とす\r\n        img.resize_fit((img.width() + 1) / 2, (img.height() + 1) / 2);\r\n\r\n        // 画像を破壊しないためにコピーを作る\r\n        gd img_tmp(img.width(), img.height());\r\n        img_tmp.alpha(false, true);\r\n        img_tmp.copy(img, 0, 0, 0, 0, img.width(), img.height());\r\n\r\n        // 1 パス目: とりあえず変換する\r\n        std::vector<int> palette_use_count(fixed_palette_count);\r\n        const int color_count = famicom_convert(img_tmp, dither, fixed_palette_y_cb_cr, fixed_palette_count, &palette_use_count[0]);\r\n        if(color_count <= 25) {\r\n            // 1 パスで同時発色可能数に収まった\r\n            img.swap(img_tmp);\r\n        } else {\r\n            // 2 パス目: 25 色以内に抑える\r\n            \r\n            // 使われた回数が多い順に並び替える\r\n            std::vector<std::pair<size_t, int> > counts;\r\n            for(size_t i = 0; i < fixed_palette_count; ++i) {\r\n                counts.push_back(std::pair<size_t, int>(i, palette_use_count[i]));\r\n            }\r\n            std::sort(counts.begin(), counts.end(), boost::bind(&std::pair<size_t, int>::second, _1) > boost::bind(&std::pair<size_t, int>::second, _2));\r\n\r\n            // 多い方から 25 色取得する\r\n            int palette[25] = {};\r\n            {\r\n                size_t i;\r\n                std::vector<std::pair<size_t, int> >::iterator it;\r\n                for(i = 0, it = counts.begin(); i < 25; ++i, ++it) {\r\n                    palette[i] = fixed_palette_y_cb_cr[it->first];\r\n                }\r\n            }\r\n\r\n            palette_use_count.resize(25);\r\n            famicom_convert(img, dither, palette, 25, &palette_use_count[0]);\r\n        }\r\n\r\n        // 解像度を下げたので元（とほとんど同じ）サイズに変更する\r\n        // GD の拡大が nearest neighbor なことに依存している\r\n        img.resize_fit(img.width() * 2, img.height() * 2);\r\n        return true;\r\n    }\r\n\r\n    bool gameboy(gd &img, bool scale, DITHERING_METHOD dither) {\r\n        const int    palette_y_cb_cr[4] = { 0x3a8080, 0x6b8080, 0xb08080, 0xde8080 };\r\n        const size_t palette_size = 4;\r\n        int palette_use_count[4] = {};\r\n        \r\n        // 出力色が完全な白や黒でないので調整する\r\n        if(!do_grayscale(img, 28, 236, 0xffffff)) {\r\n            return false;\r\n        }\r\n\r\n        if(scale) {\r\n            img.resize_fit(160, 144);\r\n        }\r\n\r\n        // ファミコンパレットへの変換を流用して変換する\r\n        famicom_convert(img, dither, palette_y_cb_cr, palette_size, palette_use_count);\r\n\r\n        // パレット置換\r\n        const int width = img.width();\r\n        const int height = img.height();\r\n        for(int y = 0; y < height; ++y) {\r\n            for(int x = 0; x < width; ++x) {\r\n                const gd::color color = img.pixel_fast(x, y);\r\n                const int c1 = (color & 0x0000ff);\r\n                const int c2 = (c1 < 0x52) ? 0x204631 : (c1 < 0x8d) ? 0x527f39 : (c1 < 0xc7) ? 0xaec440 : 0xd7e894;\r\n                img.pixel_fast(x, y, c2);\r\n            }\r\n        }\r\n\r\n        if(scale) {\r\n            img.resize_fit(480, 432);\r\n        }\r\n\r\n        return true;\r\n    }\r\n\r\n    bool virtualboy(gd &img, bool scale, DITHERING_METHOD dither) {\r\n        const int    palette_y_cb_cr[4] = { 0x008080, 0x558080, 0xaa8080, 0xff8080 };\r\n        const size_t palette_size = 4;\r\n        int palette_use_count[4] = {};\r\n        \r\n        if(!do_grayscale(img, 0, 255, 0xffffff)) {\r\n            return false;\r\n        }\r\n        if(scale) {\r\n            img.resize_fit(384, 288);   // 4:3 で切り出す\r\n            img.resize_force(384, 224); // ピクセル数を整合する\r\n        }\r\n        // ファミコンパレットへの変換を流用して変換する\r\n        famicom_convert(img, dither, palette_y_cb_cr, palette_size, palette_use_count);\r\n\r\n        // パレット置換\r\n        const int palette_red[4] = { 0x170515, 0x5c020a, 0xa20000, 0xe70000 };\r\n        const int width = img.width();\r\n        const int height = img.height();\r\n        for(int y = 0; y < height; ++y) {\r\n            for(int x = 0; x < width; ++x) {\r\n                const gd::color color = img.pixel_fast(x, y);\r\n                const int c1 = (color & 0x0000ff);\r\n                const int c2 = palette_red[c1 / 85];\r\n                img.pixel_fast(x, y, c2);\r\n            }\r\n        }\r\n\r\n        if(scale) {\r\n            img.resize_force(384, 288); // 歪ませたので戻す\r\n        }\r\n\r\n        gaussian_blur(img);\r\n\r\n        return true;\r\n    }\r\n\r\n    bool negate(gd &img) {\r\n        img.convert_to_true_color();\r\n        img.alpha_blending(false);\r\n        const int width = img.width();\r\n        const int height = img.height();\r\n        for(int y = 0; y < height; ++y) {\r\n            for(int x = 0; x < width; ++x) {\r\n                const gd::color color = img.pixel_fast(x, y);\r\n                const int a = (color & 0x7f000000);\r\n                const int r = 255 - ((color & 0x00ff0000) >> 16);\r\n                const int g = 255 - ((color & 0x0000ff00) >> 8);\r\n                const int b = 255 - ((color & 0x000000ff));\r\n                img.pixel_fast(x, y, a | (r << 16) | (g << 8) | b);\r\n            }\r\n        }\r\n        return true;\r\n    }\r\n\r\n    bool pixelate(gd &img, int size) {\r\n        if(size < 1) {\r\n            std::cerr << \"モザイクのサイズは 1 以上である必要があります\" << std::endl;\r\n            return false;\r\n        }\r\n        img.convert_to_true_color();\r\n        const int width = img.width();\r\n        const int height = img.height();\r\n        const int blocks_x = (width + size - 1) / size;\r\n        const int blocks_y = (height + size - 1) / size;\r\n        gd out(width, height);\r\n        out.alpha_blending(false);\r\n        for(int block_y = 0; block_y < blocks_y; ++block_y) {\r\n            const int min_y = block_y * size;\r\n            const int max_y = std::min((block_y + 1) * size, height);\r\n            for(int block_x = 0; block_x < blocks_x; ++block_x) {\r\n                const int min_x = block_x * size;\r\n                const int max_x = std::min((block_x + 1) * size, width);\r\n                int total_r = 0, total_g = 0, total_b = 0, total_a = 0;\r\n                int pixel_count = 0;\r\n                for(int y = min_y; y < max_y; ++y) {\r\n                    for(int x = min_x; x < max_x; ++x) {\r\n                        const gd::color color = img.pixel_fast(x, y);\r\n                        const int a = (color & 0x7f000000) >> 24;\r\n                        if(a == 0x7f) {\r\n                            // 完全透明\r\n                            continue;\r\n                        }\r\n                        const int r = (color & 0xff0000) >> 16;\r\n                        const int g = (color & 0x00ff00) >> 8;\r\n                        const int b = (color & 0x0000ff);\r\n                        total_r += r;\r\n                        total_g += g;\r\n                        total_b += b;\r\n                        total_a += a;\r\n                        ++pixel_count;\r\n                    }\r\n                }\r\n                const int fill_color =\r\n                    (pixel_count < 1)\r\n                        ? 0x7fffffff\r\n                        : ((static_cast<int>((double)total_a / (double)pixel_count + 0.5) << 24) |\r\n                           (static_cast<int>((double)total_r / (double)pixel_count + 0.5) << 16) |\r\n                           (static_cast<int>((double)total_g / (double)pixel_count + 0.5) <<  8) |\r\n                           (static_cast<int>((double)total_b / (double)pixel_count + 0.5)));\r\n                out.fill_rect(min_x, min_y, max_x, max_y, fill_color);\r\n            }\r\n        }\r\n        img.swap(out);\r\n        return true;\r\n    }\r\n\r\n    bool emboss(gd &img) {\r\n        const double filter[3][3] = {\r\n            { 1.5, 0.0, 0.0},\r\n            { 0.0, 0.0, 0.0},\r\n            { 0.0, 0.0,-1.5}\r\n        };\r\n        return fill_background(img, 0xffffff) && grayscale(img) && apply_operator_3x3(img, filter, 1, 127);\r\n    }\r\n\r\n    bool gaussian_blur(gd &img) {\r\n        const double filter[3][3] = {\r\n            { 1./16., 2./16., 1./16. },\r\n            { 2./16., 4./16., 2./16. },\r\n            { 1./16., 2./16., 1./16. }\r\n        };\r\n        return apply_operator_3x3(img, filter, 1, 0);\r\n    }\r\n\r\n    bool sharpen(gd &img) {\r\n        const double filter[3][3] = {\r\n            { -1., -1., -1. },\r\n            { -1.,  9., -1. },\r\n            { -1., -1., -1. }\r\n        };\r\n        return apply_operator_3x3(img, filter, 1, 0);\r\n    }\r\n\r\n    bool edge(gd &img) {\r\n        const double sobel_h[3][3] = {\r\n            { 1, 0, -1 },\r\n            { 2, 0, -2 },\r\n            { 1, 0, -1 }\r\n        };\r\n        const double sobel_v[3][3] = {\r\n            {  1,  2,  1 },\r\n            {  0,  0,  0 },\r\n            { -1, -2, -1 }\r\n        };\r\n\r\n        if(!fill_background(img, 0xffffff) || !grayscale(img)) {\r\n            return false;\r\n        }\r\n\r\n        // ぼかす\r\n        if(!gaussian_blur(img) || !gaussian_blur(img) || !gaussian_blur(img)) {\r\n            return false;\r\n        }\r\n        const int width = img.width();\r\n        const int height = img.height();\r\n\r\n        // 勾配検出\r\n        {\r\n            gd horizontal(width, height);\r\n            horizontal.alpha(false, false);\r\n            horizontal.copy(img, 0, 0, 0, 0, width, height);\r\n            if(!apply_operator_3x3(horizontal, sobel_h, 1, 127)) {\r\n                return false;\r\n            }\r\n            gd vertical(width, height);\r\n            vertical.alpha(false, false);\r\n            vertical.copy(img, 0, 0, 0, 0, width, height);\r\n            if(!apply_operator_3x3(vertical, sobel_v, 1, 127)) {\r\n                return false;\r\n            }\r\n            for(int y = 0; y < height; ++y) {\r\n                for(int x = 0; x < width; ++x) {\r\n                    const double h = std::min(1.0, static_cast<double>((horizontal.pixel(x, y) & 0xff) - 127) / 127.0);\r\n                    const double v = std::min(1.0, static_cast<double>((vertical.pixel(x, y) & 0xff) - 127) / 127.0);\r\n                    const int edge = std::max(0, std::min(255, static_cast<int>(sqrt(h * h + v * v) * 255.0 + 0.5)));\r\n                    const double theta = atan2(h, v) * 180.0 / M_PI;\r\n                    const int direction_code = \r\n                        (theta < 22.5) ? 1 :                // 右\r\n                        (theta < 22.5 + 45.0 * 1) ? 2 :     // 右上\r\n                        (theta < 22.5 + 45.0 * 2) ? 3 :     // 上\r\n                        (theta < 22.5 + 45.0 * 3) ? 4 : 5;  // 左上・左 180°を超えることはない…はず\r\n                    img.pixel(x, y, (direction_code << 8) | edge);\r\n                }\r\n            }\r\n        }\r\n\r\n        // 細線化（と後の処理のためにヒストグラム作成）\r\n        int hist[256] = {};\r\n        long long sum = 0;\r\n        for(int y = 0; y < height; ++y) {\r\n            for(int x = 0; x < width; ++x) {\r\n                const int direction_code = (img.pixel(x, y) & 0xff00) >> 8;\r\n                const int c0 = img.pixel(x, y) & 0xff;\r\n                int c1, c2;\r\n                switch(direction_code) {\r\n                case 1: case 5: // 左右\r\n                    c1 = img.pixel_safe(x + 1, y) & 0xff;\r\n                    c2 = img.pixel_safe(x - 1, y) & 0xff;\r\n                    break;\r\n                case 2: // 右上\r\n                    c1 = img.pixel_safe(x + 1, y - 1) & 0xff;\r\n                    c2 = img.pixel_safe(x - 1, y + 1) & 0xff;\r\n                    break;\r\n                case 3: // 上\r\n                    c1 = img.pixel_safe(x, y - 1) & 0xff;\r\n                    c2 = img.pixel_safe(x, y + 1) & 0xff;\r\n                    break;\r\n                case 4: // 左上\r\n                    c1 = img.pixel_safe(x - 1, y - 1) & 0xff;\r\n                    c2 = img.pixel_safe(x + 1, y + 1) & 0xff;\r\n                    break;\r\n                default:\r\n                    assert(false);\r\n                    return false;\r\n                }\r\n                if(c0 < c1 || c0 < c2) {\r\n                    img.pixel(x, y, 0x000000);\r\n                    ++hist[0];\r\n                } else {\r\n                    img.pixel(x, y, 0x010101 * c0);\r\n                    ++hist[c0];\r\n                    sum += c0;\r\n                }\r\n            }\r\n        }\r\n\r\n        // 閾値(HI)を計算\r\n        const int hi_threshold = otsu_threshold((double)sum / ((double)width * (double)height), hist);\r\n\r\n        // 閾値(LO)を計算\r\n        sum = 0;\r\n        for(int i = 0; i < 256; ++i) {\r\n            if(i < hi_threshold) {\r\n                sum += hist[i] * i;\r\n            } else if(i == hi_threshold) {\r\n                // nothing to do.\r\n            } else {\r\n                // 閾値(HI)以上の画素は全部閾値(HI)と見なす\r\n                sum += hist[i] * hi_threshold;\r\n                hist[hi_threshold] += hist[i];\r\n                hist[i] = 0;\r\n            }\r\n        }\r\n        const int lo_threshold = otsu_threshold((double)sum / ((double)width * (double)height), hist);\r\n\r\n        gd dst(width, height);\r\n        dst.alpha(false, true);\r\n        // 閾値HI以上の画素を描画\r\n        for(int y = 0; y < height; ++y) {\r\n            for(int x = 0; x < width; ++x) {\r\n                dst.pixel_fast(x, y, (img.pixel_fast(x, y) & 0xff) >= hi_threshold ? 0xffffff : 0x000000);\r\n            }\r\n        }\r\n        // 閾値LO以上HI未満の画素をそれなりに描画\r\n        for(int y = 0; y < height; ++y) {\r\n            for(int x = 0; x < width; ++x) {\r\n                const int c = img.pixel_fast(x, y) & 0xff;\r\n                if(lo_threshold <= c && c < hi_threshold) {\r\n                    bool found = false;\r\n                    for(int j = -1; j <= 1; ++j) {\r\n                        for(int i = -1; i <= 1; ++i) {\r\n                            if(i == 0 && j == 0) {\r\n                                // 自分の画素を見ても仕方ない\r\n                                continue;\r\n                            }\r\n                            // 近所にエッジは居る？\r\n                            if((img.pixel_safe(x + i, y + j) & 0xff) >= hi_threshold) {\r\n                                found = true;\r\n                                break;\r\n                            }\r\n                        }\r\n                        if(found) {\r\n                            break;\r\n                        }\r\n                    }\r\n                    if(found) {\r\n                        dst.pixel_fast(x, y, 0xffffff);\r\n                    }\r\n                }\r\n            }\r\n        }\r\n\r\n        img.swap(dst);\r\n\r\n        return true;\r\n    }\r\n\r\n    bool rotate_fast(gd &img, int degree) {\r\n        degree %= 360;\r\n        assert(degree % 90 == 0);\r\n        if(degree == 0) {\r\n            return true;\r\n        }\r\n        const int src_width  = img.width();\r\n        const int src_height = img.height();\r\n        const int dst_width  = degree % 180 == 0 ? src_width : src_height;\r\n        const int dst_height = degree % 180 == 0 ? src_height : src_width;\r\n        gd dst(dst_width, dst_height);\r\n        dst.alpha(false, true);\r\n        dst.copy_rotated(img, dst_width / 2.0, dst_height / 2.0, 0, 0, src_width, src_height, degree);\r\n        img.swap(dst);\r\n        return true;\r\n    }\r\n\r\n    bool flip_horizontal(gd &img) {\r\n        const int width = img.width();\r\n        const int height = img.height();\r\n        gd dst(width, height);\r\n        dst.alpha(false, true);\r\n        for(int x = 0; x < width; ++x) {\r\n            const int x2 = width - x - 1;\r\n            dst.copy(img, x2, 0, x, 0, 1, height);\r\n        }\r\n        img.swap(dst);\r\n        return true;\r\n    }\r\n\r\n    bool flip_vertical(gd &img) {\r\n        const int width = img.width();\r\n        const int height = img.height();\r\n        gd dst(width, height);\r\n        dst.alpha(false, true);\r\n        for(int y = 0; y < height; ++y) {\r\n            const int y2 = height - y - 1;\r\n            dst.copy(img, 0, y2, 0, y, width, 1);\r\n        }\r\n        img.swap(dst);\r\n        return true;\r\n    }\r\n\r\n    bool fill_background(gd &img, gd::color bg) {\r\n        const int bg_r = (bg & 0xff0000) >> 16;\r\n        const int bg_g = (bg & 0x00ff00) >>  8;\r\n        const int bg_b = (bg & 0x0000ff);\r\n        img.convert_to_true_color();\r\n        img.alpha_blending(false);\r\n        const int width = img.width();\r\n        const int height = img.height();\r\n        for(int y = 0; y < height; ++y) {\r\n            for(int x = 0; x < width; ++x) {\r\n                const gd::color color = img.pixel_fast(x, y);\r\n                const int a = (color & 0x7f000000) >> 24;\r\n                if(a == 0) {\r\n                    continue;\r\n                }\r\n                const double alpha = static_cast<double>(127 - a) / 127.0;\r\n                const int org_r = (color & 0xff0000) >> 16;\r\n                const int org_g = (color & 0x00ff00) >>  8;\r\n                const int org_b = (color & 0x0000ff);\r\n                const int r = static_cast<int>(org_r * alpha + bg_r * (1.0 - alpha) + 0.5);\r\n                const int g = static_cast<int>(org_g * alpha + bg_g * (1.0 - alpha) + 0.5);\r\n                const int b = static_cast<int>(org_b * alpha + bg_b * (1.0 - alpha) + 0.5);\r\n                img.pixel_fast(x, y, (r << 16) | (g << 8) | b);\r\n            }\r\n        }\r\n        return true;\r\n    }\r\n}\r\n", "meta": {"hexsha": "24ad10e81904e94c07907adc48ee752735f26205", "size": 43324, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "source/manip.cpp", "max_stars_repo_name": "fetus-hina/wakuflow", "max_stars_repo_head_hexsha": "a49152ae8eb35f5090b0280f879571b5f14e7fa7", "max_stars_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-02-17T15:12:14.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-17T15:12:14.000Z", "max_issues_repo_path": "source/manip.cpp", "max_issues_repo_name": "fetus-hina/wakuflow", "max_issues_repo_head_hexsha": "a49152ae8eb35f5090b0280f879571b5f14e7fa7", "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": "source/manip.cpp", "max_forks_repo_name": "fetus-hina/wakuflow", "max_forks_repo_head_hexsha": "a49152ae8eb35f5090b0280f879571b5f14e7fa7", "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": 43.3673673674, "max_line_length": 166, "alphanum_fraction": 0.4124965377, "num_tokens": 12961, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7154239836484143, "lm_q2_score": 0.48438008427698437, "lm_q1q2_score": 0.3465371294933948}}
{"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_MODEL_GP_HPP\n#define LIMBO_MODEL_GP_HPP\n\n#include <cassert>\n#include <iostream>\n#include <limits>\n#include <vector>\n\n#include <Eigen/Cholesky>\n#include <Eigen/Core>\n#include <Eigen/LU>\n\n// Quick hack for definition of 'I' in <complex.h>\n#undef I\n\n#include <limbo/kernel/matern_five_halves.hpp>\n#include <limbo/kernel/squared_exp_ard.hpp>\n#include <limbo/mean/constant.hpp>\n#include <limbo/mean/data.hpp>\n#include <limbo/model/gp/kernel_lf_opt.hpp>\n#include <limbo/model/gp/no_lf_opt.hpp>\n#include <limbo/tools.hpp>\n\nnamespace limbo {\n    namespace model {\n        /// @ingroup model\n        /// A classic Gaussian process.\n        /// It is parametrized by:\n        /// - a kernel function\n        /// - a mean function\n        /// - [optional] an optimizer for the hyper-parameters\n        template <typename Params, typename KernelFunction = kernel::MaternFiveHalves<Params>, typename MeanFunction = mean::Data<Params>, typename HyperParamsOptimizer = gp::NoLFOpt<Params>>\n        class GP {\n        public:\n            /// useful because the model might be created before knowing anything about the process\n            GP() : _dim_in(-1), _dim_out(-1), _inv_kernel_updated(false) {}\n\n            /// useful because the model might be created before having samples\n            GP(int dim_in, int dim_out)\n                : _dim_in(dim_in), _dim_out(dim_out), _kernel_function(dim_in), _mean_function(dim_out), _inv_kernel_updated(false) {}\n\n            /// Compute the GP from samples and observations. This call needs to be explicit!\n            void compute(const std::vector<Eigen::VectorXd>& samples,\n                const std::vector<Eigen::VectorXd>& observations, bool compute_kernel = true)\n            {\n                assert(samples.size() != 0);\n                assert(observations.size() != 0);\n                assert(samples.size() == observations.size());\n\n                if (_dim_in != samples[0].size()) {\n                    _dim_in = samples[0].size();\n                    _kernel_function = KernelFunction(_dim_in); // the cost of building a functor should be relatively low\n                }\n\n                if (_dim_out != observations[0].size()) {\n                    _dim_out = observations[0].size();\n                    _mean_function = MeanFunction(_dim_out); // the cost of building a functor should be relatively low\n                }\n\n                _samples = samples;\n\n                _observations.resize(observations.size(), _dim_out);\n                for (int i = 0; i < _observations.rows(); ++i)\n                    _observations.row(i) = observations[i];\n\n                _mean_observation = _observations.colwise().mean();\n\n                this->_compute_obs_mean();\n                if (compute_kernel)\n                    this->_compute_full_kernel();\n            }\n\n            /// Do not forget to call this if you use hyper-parameters optimization!!\n            void optimize_hyperparams()\n            {\n                _hp_optimize(*this);\n            }\n\n            /// add sample and update the GP. This code uses an incremental implementation of the Cholesky\n            /// decomposition. It is therefore much faster than a call to compute()\n            void add_sample(const Eigen::VectorXd& sample, const Eigen::VectorXd& observation)\n            {\n                if (_samples.empty()) {\n                    if (_dim_in != sample.size()) {\n                        _dim_in = sample.size();\n                        _kernel_function = KernelFunction(_dim_in); // the cost of building a functor should be relatively low\n                    }\n                    if (_dim_out != observation.size()) {\n                        _dim_out = observation.size();\n                        _mean_function = MeanFunction(_dim_out); // the cost of building a functor should be relatively low\n                    }\n                }\n                else {\n                    assert(sample.size() == _dim_in);\n                    assert(observation.size() == _dim_out);\n                }\n\n                _samples.push_back(sample);\n\n                _observations.conservativeResize(_observations.rows() + 1, _dim_out);\n                _observations.bottomRows<1>() = observation.transpose();\n\n                _mean_observation = _observations.colwise().mean();\n\n                this->_compute_obs_mean();\n                this->_compute_incremental_kernel();\n            }\n\n            /**\n             \\\\rst\n             return :math:`\\mu`, :math:`\\sigma^2` (un-normalized). If there is no sample, return the value according to the mean function. Using this method instead of separate calls to mu() and sigma() is more efficient because some computations are shared between mu() and sigma().\n             \\\\endrst\n            */\n            std::tuple<Eigen::VectorXd, double> query(const Eigen::VectorXd& v) const\n            {\n                if (_samples.size() == 0)\n                    return std::make_tuple(_mean_function(v, *this),\n                        _kernel_function(v, v) + _kernel_function.noise());\n\n                Eigen::VectorXd k = _compute_k(v);\n                return std::make_tuple(_mu(v, k), _sigma(v, k) + _kernel_function.noise());\n            }\n\n            /**\n             \\\\rst\n             return :math:`\\mu` (un-normalized). If there is no sample, return the value according to the mean function.\n             \\\\endrst\n            */\n            Eigen::VectorXd mu(const Eigen::VectorXd& v) const\n            {\n                if (_samples.size() == 0)\n                    return _mean_function(v, *this);\n                return _mu(v, _compute_k(v));\n            }\n\n            /**\n             \\\\rst\n             return :math:`\\sigma^2` (un-normalized). If there is no sample, return the max :math:`\\sigma^2`.\n             \\\\endrst\n            */\n            double sigma(const Eigen::VectorXd& v) const\n            {\n                if (_samples.size() == 0)\n                    return _kernel_function(v, v) + _kernel_function.noise();\n                return _sigma(v, _compute_k(v)) + _kernel_function.noise();\n            }\n\n            /// return the number of dimensions of the input\n            int dim_in() const\n            {\n                assert(_dim_in != -1); // need to compute first!\n                return _dim_in;\n            }\n\n            /// return the number of dimensions of the output\n            int dim_out() const\n            {\n                assert(_dim_out != -1); // need to compute first!\n                return _dim_out;\n            }\n\n            const KernelFunction& kernel_function() const { return _kernel_function; }\n\n            KernelFunction& kernel_function() { return _kernel_function; }\n\n            const MeanFunction& mean_function() const { return _mean_function; }\n\n            MeanFunction& mean_function() { return _mean_function; }\n\n            /// return the maximum observation (only call this if the output of the GP is of dimension 1)\n            Eigen::VectorXd max_observation() const\n            {\n                if (_observations.cols() > 1)\n                    std::cout << \"WARNING max_observation with multi dimensional \"\n                                 \"observations doesn't make sense\"\n                              << std::endl;\n                return tools::make_vector(_observations.maxCoeff());\n            }\n\n            /// return the mean observation (only call this if the output of the GP is of dimension 1)\n            Eigen::VectorXd mean_observation() const\n            {\n                assert(_dim_out > 0);\n                return _samples.size() > 0 ? _mean_observation\n                                           : Eigen::VectorXd::Zero(_dim_out);\n            }\n\n            const Eigen::MatrixXd& mean_vector() const { return _mean_vector; }\n\n            const Eigen::MatrixXd& obs_mean() const { return _obs_mean; }\n\n            /// return the number of samples used to compute the GP\n            int nb_samples() const { return _samples.size(); }\n\n            ///  recomputes the GP\n            void recompute(bool update_obs_mean = true, bool update_full_kernel = true)\n            {\n                assert(!_samples.empty());\n\n                if (update_obs_mean)\n                    this->_compute_obs_mean();\n\n                if (update_full_kernel)\n                    this->_compute_full_kernel();\n                else\n                    this->_compute_alpha();\n            }\n\n            void compute_inv_kernel()\n            {\n                size_t n = _obs_mean.rows();\n                // K^{-1} using Cholesky decomposition\n                _inv_kernel = Eigen::MatrixXd::Identity(n, n);\n\n                _matrixL.template triangularView<Eigen::Lower>().solveInPlace(_inv_kernel);\n                _matrixL.template triangularView<Eigen::Lower>().transpose().solveInPlace(_inv_kernel);\n\n                _inv_kernel_updated = true;\n            }\n\n            /// compute and return the log likelihood\n            double compute_log_lik()\n            {\n                size_t n = _obs_mean.rows();\n\n                // --- cholesky ---\n                // see:\n                // http://xcorr.net/2008/06/11/log-determinant-of-positive-definite-matrices-in-matlab/\n                long double logdet = 2 * _matrixL.diagonal().array().log().sum();\n\n                double a = (_obs_mean.transpose() * _alpha)\n                               .trace(); // generalization for multi dimensional observation\n\n                _log_lik = -0.5 * a - 0.5 * logdet - 0.5 * n * std::log(2 * M_PI);\n\n                return _log_lik;\n            }\n\n            /// compute and return the gradient of the log likelihood wrt to the kernel parameters\n            Eigen::VectorXd compute_kernel_grad_log_lik()\n            {\n                size_t n = _obs_mean.rows();\n\n                // compute K^{-1} only if needed\n                if (!_inv_kernel_updated) {\n                    compute_inv_kernel();\n                }\n                Eigen::MatrixXd w = _inv_kernel;\n\n                // alpha * alpha.transpose() - K^{-1}\n                w = _alpha * _alpha.transpose() - w;\n\n                // only compute half of the matrix (symmetrical matrix)\n                Eigen::VectorXd grad = Eigen::VectorXd::Zero(_kernel_function.h_params_size());\n                for (size_t i = 0; i < n; ++i) {\n                    for (size_t j = 0; j <= i; ++j) {\n                        Eigen::VectorXd g = _kernel_function.grad(_samples[i], _samples[j], i, j);\n                        if (i == j)\n                            grad += w(i, j) * g * 0.5;\n                        else\n                            grad += w(i, j) * g;\n                    }\n                }\n\n                return grad;\n            }\n\n            /// compute and return the gradient of the log likelihood wrt to the mean parameters\n            Eigen::VectorXd compute_mean_grad_log_lik()\n            {\n                size_t n = _obs_mean.rows();\n\n                // compute K^{-1} only if needed\n                if (!_inv_kernel_updated) {\n                    compute_inv_kernel();\n                }\n\n                Eigen::VectorXd grad = Eigen::VectorXd::Zero(_mean_function.h_params_size());\n                for (int i_obs = 0; i_obs < _dim_out; ++i_obs)\n                    for (size_t n_obs = 0; n_obs < n; n_obs++) {\n                        grad += _obs_mean.col(i_obs).transpose() * _inv_kernel.col(n_obs) * _mean_function.grad(_samples[n_obs], *this).row(i_obs);\n                    }\n\n                return grad;\n            }\n\n            /// return the likelihood (do not compute it -- return last computed)\n            double get_log_lik() const { return _log_lik; }\n\n            /// set the log likelihood (e.g. computed from outside)\n            void set_log_lik(double log_lik) { _log_lik = log_lik; }\n\n            /// compute and return the log probability of LOO CV\n            double compute_log_loo_cv()\n            {\n                // compute K^{-1} only if needed\n                if (!_inv_kernel_updated) {\n                    compute_inv_kernel();\n                }\n\n                Eigen::VectorXd inv_diag = _inv_kernel.diagonal().array().inverse();\n\n                _log_loo_cv = (((-0.5 * (_alpha.array().square().array().colwise() * inv_diag.array())).array().colwise() - 0.5 * inv_diag.array().log().array()) - 0.5 * std::log(2 * M_PI)).colwise().sum().sum();\n\n                return _log_loo_cv;\n            }\n\n            /// compute and return the gradient of the log probability of LOO CV wrt to the kernel parameters\n            Eigen::VectorXd compute_kernel_grad_log_loo_cv()\n            {\n                size_t n = _obs_mean.rows();\n                size_t n_params = _kernel_function.h_params_size();\n\n                // compute K^{-1} only if needed\n                if (!_inv_kernel_updated) {\n                    compute_inv_kernel();\n                }\n\n                Eigen::VectorXd grad = Eigen::VectorXd::Zero(n_params);\n                Eigen::MatrixXd grads = Eigen::MatrixXd::Zero(n_params, _dim_out);\n\n                // only compute half of the matrix (symmetrical matrix)\n                // TO-DO: Make it better\n                std::vector<std::vector<Eigen::VectorXd>> full_dk;\n                for (size_t i = 0; i < n; i++) {\n                    full_dk.push_back(std::vector<Eigen::VectorXd>());\n                    for (size_t j = 0; j <= i; j++)\n                        full_dk[i].push_back(_kernel_function.grad(_samples[i], _samples[j], i, j));\n                    for (size_t j = i + 1; j < n; j++)\n                        full_dk[i].push_back(Eigen::VectorXd::Zero(n_params));\n                }\n                for (size_t i = 0; i < n; i++)\n                    for (size_t j = 0; j < i; ++j)\n                        full_dk[j][i] = full_dk[i][j];\n\n                Eigen::VectorXd inv_diag = _inv_kernel.diagonal().array().inverse();\n\n                for (int j = 0; j < grad.size(); j++) {\n                    Eigen::MatrixXd dKdTheta_j = Eigen::MatrixXd::Zero(n, n);\n                    for (size_t i = 0; i < n; i++) {\n                        for (size_t k = 0; k < n; k++)\n                            dKdTheta_j(i, k) = full_dk[i][k](j);\n                    }\n                    Eigen::MatrixXd Zeta_j = _inv_kernel * dKdTheta_j;\n                    Eigen::MatrixXd Zeta_j_alpha = Zeta_j * _alpha;\n                    Eigen::MatrixXd Zeta_j_K = Zeta_j * _inv_kernel;\n\n                    grads.row(j) = ((_alpha.array() * Zeta_j_alpha.array() - 0.5 * ((1. + _alpha.array().square().array().colwise() * inv_diag.array()).array().colwise() * Zeta_j_K.diagonal().array())).array().colwise() * inv_diag.array()).colwise().sum();\n\n                    // for (size_t i = 0; i < n; i++)\n                    //     grads.row(j).array() += (_alpha.row(i).array() * Zeta_j_alpha.row(i).array() - 0.5 * (1. + _alpha.row(i).array().square() / _inv_kernel.diagonal()(i)) * Zeta_j_K.diagonal()(i)) / _inv_kernel.diagonal()(i);\n                }\n\n                grad = grads.rowwise().sum();\n\n                return grad;\n            }\n\n            /// return the LOO-CV log probability (do not compute it -- return last computed)\n            double get_log_loo_cv() const { return _log_loo_cv; }\n\n            /// set the LOO-CV log probability (e.g. computed from outside)\n            void set_log_loo_cv(double log_loo_cv) { _log_loo_cv = log_loo_cv; }\n\n            /// LLT matrix (from Cholesky decomposition)\n            const Eigen::MatrixXd& matrixL() const { return _matrixL; }\n\n            const Eigen::MatrixXd& alpha() const { return _alpha; }\n\n            /// return the list of samples\n            const std::vector<Eigen::VectorXd>& samples() const { return _samples; }\n\n            /// return the list of observations\n            std::vector<Eigen::VectorXd> observations() const\n            {\n                std::vector<Eigen::VectorXd> observations;\n                for (int i = 0; i < _observations.rows(); i++) {\n                    observations.push_back(_observations.row(i));\n                }\n\n                return observations;\n            }\n\n            /// return the observations (in matrix form)\n            /// (NxD), where N is the number of points and D is the dimension output\n            const Eigen::MatrixXd& observations_matrix() const\n            {\n                return _observations;\n            }\n\n            bool inv_kernel_computed() { return _inv_kernel_updated; }\n\n            /// save the parameters and the data for the GP to the archive (text or binary)\n            template <typename A>\n            void save(const std::string& directory) const\n            {\n                A archive(directory);\n                save(archive);\n            }\n\n            /// save the parameters and the data for the GP to the archive (text or binary)\n            template <typename A>\n            void save(const A& archive) const\n            {\n                if (_kernel_function.h_params_size() > 0) {\n                    archive.save(_kernel_function.h_params(), \"kernel_params\");\n                }\n                if (_mean_function.h_params_size() > 0) {\n                    archive.save(_mean_function.h_params(), \"mean_params\");\n                }\n                archive.save(_samples, \"samples\");\n                archive.save(_observations, \"observations\");\n                archive.save(_matrixL, \"matrixL\");\n                archive.save(_alpha, \"alpha\");\n            }\n\n            /// load the parameters and the data for the GP from the archive (text or binary)\n            /// if recompute is true, we do not read the kernel matrix\n            /// but we recompute it given the data and the hyperparameters\n            template <typename A>\n            void load(const std::string& directory, bool recompute = true)\n            {\n                A archive(directory);\n                load(archive, recompute);\n            }\n\n            /// load the parameters and the data for the GP from the archive (text or binary)\n            /// if recompute is true, we do not read the kernel matrix\n            /// but we recompute it given the data and the hyperparameters\n            template <typename A>\n            void load(const A& archive, bool recompute = true)\n            {\n                _samples.clear();\n                archive.load(_samples, \"samples\");\n\n                archive.load(_observations, \"observations\");\n\n                _dim_in = _samples[0].size();\n                _kernel_function = KernelFunction(_dim_in);\n\n                if (_kernel_function.h_params_size() > 0) {\n                    Eigen::VectorXd h_params;\n                    archive.load(h_params, \"kernel_params\");\n                    assert(h_params.size() == (int)_kernel_function.h_params_size());\n                    _kernel_function.set_h_params(h_params);\n                }\n\n                _dim_out = _observations.cols();\n                _mean_function = MeanFunction(_dim_out);\n\n                if (_mean_function.h_params_size() > 0) {\n                    Eigen::VectorXd h_params;\n                    archive.load(h_params, \"mean_params\");\n                    assert(h_params.size() == (int)_mean_function.h_params_size());\n                    _mean_function.set_h_params(h_params);\n                }\n\n                _mean_observation = _observations.colwise().mean();\n\n                if (recompute)\n                    this->recompute(true, true);\n                else {\n                    archive.load(_matrixL, \"matrixL\");\n                    archive.load(_alpha, \"alpha\");\n                }\n            }\n\n        protected:\n            int _dim_in;\n            int _dim_out;\n\n            KernelFunction _kernel_function;\n            MeanFunction _mean_function;\n\n            std::vector<Eigen::VectorXd> _samples;\n            Eigen::MatrixXd _observations;\n            Eigen::MatrixXd _mean_vector;\n            Eigen::MatrixXd _obs_mean;\n\n            Eigen::MatrixXd _alpha;\n            Eigen::VectorXd _mean_observation;\n\n            Eigen::MatrixXd _kernel, _inv_kernel;\n\n            Eigen::MatrixXd _matrixL;\n\n            double _log_lik, _log_loo_cv;\n            bool _inv_kernel_updated;\n\n            HyperParamsOptimizer _hp_optimize;\n\n            void _compute_obs_mean()\n            {\n                assert(!_samples.empty());\n                _mean_vector.resize(_samples.size(), _dim_out);\n                for (int i = 0; i < _mean_vector.rows(); i++) {\n                    assert(_samples[i].cols() == 1);\n                    assert(_samples[i].rows() != 0);\n                    assert(_samples[i].rows() == _dim_in);\n                    _mean_vector.row(i) = _mean_function(_samples[i], *this);\n                }\n                _obs_mean = _observations - _mean_vector;\n            }\n\n            void _compute_full_kernel()\n            {\n                size_t n = _samples.size();\n                _kernel.resize(n, n);\n\n                // O(n^2) [should be negligible]\n                for (size_t i = 0; i < n; i++)\n                    for (size_t j = 0; j <= i; ++j)\n                        _kernel(i, j) = _kernel_function(_samples[i], _samples[j], i, j);\n\n                for (size_t i = 0; i < n; i++)\n                    for (size_t j = 0; j < i; ++j)\n                        _kernel(j, i) = _kernel(i, j);\n\n                // O(n^3)\n                _matrixL = Eigen::LLT<Eigen::MatrixXd>(_kernel).matrixL();\n\n                this->_compute_alpha();\n\n                // notify change of kernel\n                _inv_kernel_updated = false;\n            }\n\n            void _compute_incremental_kernel()\n            {\n                // Incremental LLT\n                // This part of the code is inspired from the Bayesopt Library (cholesky_add_row function).\n                // However, the mathematical foundations can be easily retrieved by detailing the equations of the\n                // extended L matrix that produces the desired kernel.\n\n                size_t n = _samples.size();\n                _kernel.conservativeResize(n, n);\n\n                for (size_t i = 0; i < n; ++i) {\n                    _kernel(i, n - 1) = _kernel_function(_samples[i], _samples[n - 1], i, n - 1);\n                    _kernel(n - 1, i) = _kernel(i, n - 1);\n                }\n\n                _matrixL.conservativeResizeLike(Eigen::MatrixXd::Zero(n, n));\n\n                double L_j;\n                for (size_t j = 0; j < n - 1; ++j) {\n                    L_j = _kernel(n - 1, j) - (_matrixL.block(j, 0, 1, j) * _matrixL.block(n - 1, 0, 1, j).transpose())(0, 0);\n                    _matrixL(n - 1, j) = (L_j) / _matrixL(j, j);\n                }\n\n                L_j = _kernel(n - 1, n - 1) - (_matrixL.block(n - 1, 0, 1, n - 1) * _matrixL.block(n - 1, 0, 1, n - 1).transpose())(0, 0);\n                _matrixL(n - 1, n - 1) = sqrt(L_j);\n\n                this->_compute_alpha();\n\n                // notify change of kernel\n                _inv_kernel_updated = false;\n            }\n\n            void _compute_alpha()\n            {\n                // alpha = K^{-1} * this->_obs_mean;\n                Eigen::TriangularView<Eigen::MatrixXd, Eigen::Lower> triang = _matrixL.template triangularView<Eigen::Lower>();\n                _alpha = triang.solve(_obs_mean);\n                triang.adjoint().solveInPlace(_alpha);\n            }\n\n            Eigen::VectorXd _mu(const Eigen::VectorXd& v, const Eigen::VectorXd& k) const\n            {\n                return (k.transpose() * _alpha) + _mean_function(v, *this).transpose();\n            }\n\n            double _sigma(const Eigen::VectorXd& v, const Eigen::VectorXd& k) const\n            {\n                Eigen::VectorXd z = _matrixL.triangularView<Eigen::Lower>().solve(k);\n                double res = _kernel_function(v, v) - z.dot(z);\n\n                return (res <= std::numeric_limits<double>::epsilon()) ? 0 : res;\n            }\n\n            Eigen::VectorXd _compute_k(const Eigen::VectorXd& v) const\n            {\n                Eigen::VectorXd k(_samples.size());\n                for (int i = 0; i < k.size(); i++)\n                    k[i] = _kernel_function(_samples[i], v);\n                return k;\n            }\n        };\n        /// GPBasic is a GP with a \"mean data\" mean function, Exponential kernel,\n        /// and NO hyper-parameter optimization\n        template <typename Params>\n        using GPBasic = GP<Params, kernel::MaternFiveHalves<Params>, mean::Data<Params>, gp::NoLFOpt<Params>>;\n\n        /// GPOpt is a GP with a \"mean data\" mean function, Exponential kernel with Automatic Relevance\n        /// Determination (ARD), and hyper-parameter optimization based on Rprop\n        template <typename Params>\n        using GPOpt = GP<Params, kernel::SquaredExpARD<Params>, mean::Data<Params>, gp::KernelLFOpt<Params>>;\n    } // namespace model\n} // namespace limbo\n\n#endif\n", "meta": {"hexsha": "3bfa4db5df90cd13e9c9ead24de2a7ffdc060524", "size": 27290, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "limbo/src/limbo/model/gp.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/model/gp.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/model/gp.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": 42.1792890263, "max_line_length": 283, "alphanum_fraction": 0.5355075119, "num_tokens": 5963, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6619228625116081, "lm_q2_score": 0.523420348936324, "lm_q1q2_score": 0.3464638956647564}}
{"text": "// Copyright John Maddock 2010.\r\n// Copyright Paul A. Bristow 2010.\r\n\r\n// Use, modification and distribution are subject to the\r\n// Boost Software License, Version 1.0.\r\n// (See accompanying file LICENSE_1_0.txt\r\n// or copy at http://www.boost.org/LICENSE_1_0.txt)\r\n\r\n#ifndef BOOST_MATH_DISTRIBUTIONS_INVERSE_CHI_SQUARED_HPP\r\n#define BOOST_MATH_DISTRIBUTIONS_INVERSE_CHI_SQUARED_HPP\r\n\r\n#include <boost/math/distributions/fwd.hpp>\r\n#include <boost/math/special_functions/gamma.hpp> // for incomplete beta.\r\n#include <boost/math/distributions/complement.hpp> // for complements.\r\n#include <boost/math/distributions/detail/common_error_handling.hpp> // for error checks.\r\n#include <boost/math/special_functions/fpclassify.hpp> // for isfinite\r\n\r\n// See http://en.wikipedia.org/wiki/Scaled-inverse-chi-square_distribution\r\n// for definitions of this scaled version.\r\n// See http://en.wikipedia.org/wiki/Inverse-chi-square_distribution\r\n// for unscaled version.\r\n\r\n// http://reference.wolfram.com/mathematica/ref/InverseChiSquareDistribution.html\r\n// Weisstein, Eric W. \"Inverse Chi-Squared Distribution.\" From MathWorld--A Wolfram Web Resource.\r\n// http://mathworld.wolfram.com/InverseChi-SquaredDistribution.html\r\n\r\n#include <utility>\r\n\r\nnamespace boost{ namespace math{\r\n\r\nnamespace detail\r\n{\r\n  template <class RealType, class Policy>\r\n  inline bool check_inverse_chi_squared( // Check both distribution parameters.\r\n        const char* function,\r\n        RealType degrees_of_freedom, // degrees_of_freedom (aka nu).\r\n        RealType scale,  // scale (aka sigma^2)\r\n        RealType* result,\r\n        const Policy& pol)\r\n  {\r\n     return check_scale(function, scale, result, pol)\r\n       && check_df(function, degrees_of_freedom,\r\n       result, pol);\r\n  } // bool check_inverse_chi_squared\r\n} // namespace detail\r\n\r\ntemplate <class RealType = double, class Policy = policies::policy<> >\r\nclass inverse_chi_squared_distribution\r\n{\r\npublic:\r\n   typedef RealType value_type;\r\n   typedef Policy policy_type;\r\n\r\n   inverse_chi_squared_distribution(RealType df, RealType l_scale) : m_df(df), m_scale (l_scale)\r\n   {\r\n      RealType result;\r\n      detail::check_df(\r\n         \"boost::math::inverse_chi_squared_distribution<%1%>::inverse_chi_squared_distribution\",\r\n         m_df, &result, Policy())\r\n         && detail::check_scale(\r\n\"boost::math::inverse_chi_squared_distribution<%1%>::inverse_chi_squared_distribution\",\r\n         m_scale, &result,  Policy());\r\n   } // inverse_chi_squared_distribution constructor \r\n\r\n   inverse_chi_squared_distribution(RealType df = 1) : m_df(df)\r\n   {\r\n      RealType result;\r\n      m_scale = 1 / m_df ; // Default scale = 1 / degrees of freedom (Wikipedia definition 1).\r\n      detail::check_df(\r\n         \"boost::math::inverse_chi_squared_distribution<%1%>::inverse_chi_squared_distribution\",\r\n         m_df, &result, Policy());\r\n   } // inverse_chi_squared_distribution\r\n\r\n   RealType degrees_of_freedom()const\r\n   {\r\n      return m_df; // aka nu\r\n   }\r\n   RealType scale()const\r\n   {\r\n      return m_scale;  // aka xi\r\n   }\r\n\r\n   // Parameter estimation:  NOT implemented yet.\r\n   //static RealType find_degrees_of_freedom(\r\n   //   RealType difference_from_variance,\r\n   //   RealType alpha,\r\n   //   RealType beta,\r\n   //   RealType variance,\r\n   //   RealType hint = 100);\r\n\r\nprivate:\r\n   // Data members:\r\n   RealType m_df;  // degrees of freedom are treated as a real number.\r\n   RealType m_scale;  // distribution scale.\r\n\r\n}; // class chi_squared_distribution\r\n\r\ntypedef inverse_chi_squared_distribution<double> inverse_chi_squared;\r\n\r\ntemplate <class RealType, class Policy>\r\ninline const std::pair<RealType, RealType> range(const inverse_chi_squared_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>(static_cast<RealType>(0), max_value<RealType>()); // 0 to + infinity.\r\n}\r\n\r\ntemplate <class RealType, class Policy>\r\ninline const std::pair<RealType, RealType> support(const inverse_chi_squared_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   return std::pair<RealType, RealType>(static_cast<RealType>(0), tools::max_value<RealType>()); // 0 to + infinity.\r\n}\r\n\r\ntemplate <class RealType, class Policy>\r\nRealType pdf(const inverse_chi_squared_distribution<RealType, Policy>& dist, const RealType& x)\r\n{\r\n   BOOST_MATH_STD_USING  // for ADL of std functions.\r\n   RealType df = dist.degrees_of_freedom();\r\n   RealType scale = dist.scale();\r\n   RealType error_result;\r\n\r\n   static const char* function = \"boost::math::pdf(const inverse_chi_squared_distribution<%1%>&, %1%)\";\r\n\r\n   if(false == detail::check_inverse_chi_squared\r\n     (function, df, scale, &error_result, Policy())\r\n     )\r\n   { // Bad distribution.\r\n      return error_result;\r\n   }\r\n   if((x < 0) || !(boost::math::isfinite)(x))\r\n   { // Bad x.\r\n      return policies::raise_domain_error<RealType>(\r\n         function, \"inverse Chi Square parameter was %1%, but must be >= 0 !\", x, Policy());\r\n   }\r\n\r\n   if(x == 0)\r\n   { // Treat as special case.\r\n     return 0;\r\n   }\r\n   // Wikipedia scaled inverse chi sq (df, scale) related to inv gamma (df/2, df * scale /2) \r\n   // so use inverse gamma pdf with shape = df/2, scale df * scale /2 \r\n   // RealType shape = df /2; // inv_gamma shape\r\n   // RealType scale = df * scale/2; // inv_gamma scale\r\n   // RealType result = gamma_p_derivative(shape, scale / x, Policy()) * scale / (x * x);\r\n   RealType result = df * scale/2 / x;\r\n   if(result < tools::min_value<RealType>())\r\n      return 0; // Random variable is near enough infinite.\r\n   result = gamma_p_derivative(df/2, result, Policy()) * df * scale/2;\r\n   if(result != 0) // prevent 0 / 0,  gamma_p_derivative -> 0 faster than x^2\r\n      result /= (x * x);\r\n   return result;\r\n} // pdf\r\n\r\ntemplate <class RealType, class Policy>\r\ninline RealType cdf(const inverse_chi_squared_distribution<RealType, Policy>& dist, const RealType& x)\r\n{\r\n   static const char* function = \"boost::math::cdf(const inverse_chi_squared_distribution<%1%>&, %1%)\";\r\n   RealType df = dist.degrees_of_freedom();\r\n   RealType scale = dist.scale();\r\n   RealType error_result;\r\n\r\n   if(false ==\r\n       detail::check_inverse_chi_squared(function, df, scale, &error_result, Policy())\r\n     )\r\n   { // Bad distribution.\r\n      return error_result;\r\n   }\r\n   if((x < 0) || !(boost::math::isfinite)(x))\r\n   { // Bad x.\r\n      return policies::raise_domain_error<RealType>(\r\n         function, \"inverse Chi Square parameter was %1%, but must be >= 0 !\", x, Policy());\r\n   }\r\n   if (x == 0)\r\n   { // Treat zero as a special case.\r\n     return 0;\r\n   }\r\n   // RealType shape = df /2; // inv_gamma shape,\r\n   // RealType scale = df * scale/2; // inv_gamma scale,\r\n   // result = boost::math::gamma_q(shape, scale / x, Policy()); // inverse_gamma code.\r\n   return boost::math::gamma_q(df / 2, (df * (scale / 2)) / x, Policy());\r\n} // cdf\r\n\r\ntemplate <class RealType, class Policy>\r\ninline RealType quantile(const inverse_chi_squared_distribution<RealType, Policy>& dist, const RealType& p)\r\n{\r\n   using boost::math::gamma_q_inv;\r\n   RealType df = dist.degrees_of_freedom();\r\n   RealType scale = dist.scale();\r\n\r\n   static const char* function = \"boost::math::quantile(const inverse_chi_squared_distribution<%1%>&, %1%)\";\r\n   // Error check:\r\n   RealType error_result;\r\n   if(false == detail::check_df(\r\n         function, df, &error_result, Policy())\r\n         && detail::check_probability(\r\n            function, p, &error_result, Policy()))\r\n   {\r\n      return error_result;\r\n   }\r\n   if(false == detail::check_probability(\r\n            function, p, &error_result, Policy()))\r\n   {\r\n      return error_result;\r\n   }\r\n   // RealType shape = df /2; // inv_gamma shape,\r\n   // RealType scale = df * scale/2; // inv_gamma scale,\r\n   // result = scale / gamma_q_inv(shape, p, Policy());\r\n      RealType result = gamma_q_inv(df /2, p, Policy());\r\n      if(result == 0)\r\n         return policies::raise_overflow_error<RealType, Policy>(function, \"Random variable is infinite.\", Policy());\r\n      result = df * (scale / 2) / result;\r\n      return result;\r\n} // quantile\r\n\r\ntemplate <class RealType, class Policy>\r\ninline RealType cdf(const complemented2_type<inverse_chi_squared_distribution<RealType, Policy>, RealType>& c)\r\n{\r\n   using boost::math::gamma_q_inv;\r\n   RealType const& df = c.dist.degrees_of_freedom();\r\n   RealType const& scale = c.dist.scale();\r\n   RealType const& x = c.param;\r\n   static const char* function = \"boost::math::cdf(const inverse_chi_squared_distribution<%1%>&, %1%)\";\r\n   // Error check:\r\n   RealType error_result;\r\n   if(false == detail::check_df(\r\n         function, df, &error_result, Policy()))\r\n   {\r\n      return error_result;\r\n   }\r\n   if (x == 0)\r\n   { // Treat zero as a special case.\r\n     return 1;\r\n   }\r\n   if((x < 0) || !(boost::math::isfinite)(x))\r\n   {\r\n      return policies::raise_domain_error<RealType>(\r\n         function, \"inverse Chi Square parameter was %1%, but must be > 0 !\", x, Policy());\r\n   }\r\n   // RealType shape = df /2; // inv_gamma shape,\r\n   // RealType scale = df * scale/2; // inv_gamma scale,\r\n   // result = gamma_p(shape, scale/c.param, Policy()); use inv_gamma.\r\n\r\n   return gamma_p(df / 2, (df * scale/2) / x, Policy()); // OK\r\n} // cdf(complemented\r\n\r\ntemplate <class RealType, class Policy>\r\ninline RealType quantile(const complemented2_type<inverse_chi_squared_distribution<RealType, Policy>, RealType>& c)\r\n{\r\n   using boost::math::gamma_q_inv;\r\n\r\n   RealType const& df = c.dist.degrees_of_freedom();\r\n   RealType const& scale = c.dist.scale();\r\n   RealType const& q = c.param;\r\n   static const char* function = \"boost::math::quantile(const inverse_chi_squared_distribution<%1%>&, %1%)\";\r\n   // Error check:\r\n   RealType error_result;\r\n   if(false == detail::check_df(function, df, &error_result, Policy()))\r\n   {\r\n      return error_result;\r\n   }\r\n   if(false == detail::check_probability(function, q, &error_result, Policy()))\r\n   {\r\n      return error_result;\r\n   }\r\n   // RealType shape = df /2; // inv_gamma shape,\r\n   // RealType scale = df * scale/2; // inv_gamma scale,\r\n   // result = scale / gamma_p_inv(shape, q, Policy());  // using inv_gamma.\r\n   RealType result = gamma_p_inv(df/2, q, Policy());\r\n   if(result == 0)\r\n      return policies::raise_overflow_error<RealType, Policy>(function, \"Random variable is infinite.\", Policy());\r\n   result = (df * scale / 2) / result;\r\n   return result;\r\n} // quantile(const complement\r\n\r\ntemplate <class RealType, class Policy>\r\ninline RealType mean(const inverse_chi_squared_distribution<RealType, Policy>& dist)\r\n{ // Mean of inverse Chi-Squared distribution.\r\n   RealType df = dist.degrees_of_freedom();\r\n   RealType scale = dist.scale();\r\n\r\n   static const char* function = \"boost::math::mean(const inverse_chi_squared_distribution<%1%>&)\";\r\n   if(df <= 2)\r\n      return policies::raise_domain_error<RealType>(\r\n         function,\r\n         \"inverse Chi-Squared distribution only has a mode for degrees of freedom > 2, but got degrees of freedom = %1%.\",\r\n         df, Policy());\r\n  return (df * scale) / (df - 2);\r\n} // mean\r\n\r\ntemplate <class RealType, class Policy>\r\ninline RealType variance(const inverse_chi_squared_distribution<RealType, Policy>& dist)\r\n{ // Variance of inverse Chi-Squared distribution.\r\n   RealType df = dist.degrees_of_freedom();\r\n   RealType scale = dist.scale();\r\n   static const char* function = \"boost::math::variance(const inverse_chi_squared_distribution<%1%>&)\";\r\n   if(df <= 4)\r\n   {\r\n      return policies::raise_domain_error<RealType>(\r\n         function,\r\n         \"inverse Chi-Squared distribution only has a variance for degrees of freedom > 4, but got degrees of freedom = %1%.\",\r\n         df, Policy());\r\n   }\r\n   return 2 * df * df * scale * scale / ((df - 2)*(df - 2) * (df - 4));\r\n} // variance\r\n\r\ntemplate <class RealType, class Policy>\r\ninline RealType mode(const inverse_chi_squared_distribution<RealType, Policy>& dist)\r\n{ // mode is not defined in Mathematica.\r\n  // See Discussion section http://en.wikipedia.org/wiki/Talk:Scaled-inverse-chi-square_distribution\r\n  // for origin of the formula used below.\r\n\r\n   RealType df = dist.degrees_of_freedom();\r\n   RealType scale = dist.scale();\r\n   static const char* function = \"boost::math::mode(const inverse_chi_squared_distribution<%1%>&)\";\r\n   if(df < 0)\r\n      return policies::raise_domain_error<RealType>(\r\n         function,\r\n         \"inverse Chi-Squared distribution only has a mode for degrees of freedom >= 0, but got degrees of freedom = %1%.\",\r\n         df, Policy());\r\n   return (df * scale) / (df + 2);\r\n}\r\n\r\n//template <class RealType, class Policy>\r\n//inline RealType median(const inverse_chi_squared_distribution<RealType, Policy>& dist)\r\n//{ // Median is given by Quantile[dist, 1/2]\r\n//   RealType df = dist.degrees_of_freedom();\r\n//   if(df <= 1)\r\n//      return tools::domain_error<RealType>(\r\n//         BOOST_CURRENT_FUNCTION,\r\n//         \"The inverse_Chi-Squared distribution only has a median for degrees of freedom >= 0, but got degrees of freedom = %1%.\",\r\n//         df);\r\n//   return df;\r\n//}\r\n// Now implemented via quantile(half) in derived accessors.\r\n\r\ntemplate <class RealType, class Policy>\r\ninline RealType skewness(const inverse_chi_squared_distribution<RealType, Policy>& dist)\r\n{\r\n   BOOST_MATH_STD_USING // For ADL\r\n   RealType df = dist.degrees_of_freedom();\r\n   static const char* function = \"boost::math::skewness(const inverse_chi_squared_distribution<%1%>&)\";\r\n   if(df <= 6)\r\n      return policies::raise_domain_error<RealType>(\r\n         function,\r\n         \"inverse Chi-Squared distribution only has a skewness for degrees of freedom > 6, but got degrees of freedom = %1%.\",\r\n         df, Policy());\r\n\r\n   return 4 * sqrt (2 * (df - 4)) / (df - 6);  // Not a function of scale.\r\n}\r\n\r\ntemplate <class RealType, class Policy>\r\ninline RealType kurtosis(const inverse_chi_squared_distribution<RealType, Policy>& dist)\r\n{\r\n   RealType df = dist.degrees_of_freedom();\r\n   static const char* function = \"boost::math::kurtosis(const inverse_chi_squared_distribution<%1%>&)\";\r\n   if(df <= 8)\r\n      return policies::raise_domain_error<RealType>(\r\n         function,\r\n         \"inverse Chi-Squared distribution only has a kurtosis for degrees of freedom > 8, but got degrees of freedom = %1%.\",\r\n         df, Policy());\r\n\r\n   return kurtosis_excess(dist) + 3;\r\n}\r\n\r\ntemplate <class RealType, class Policy>\r\ninline RealType kurtosis_excess(const inverse_chi_squared_distribution<RealType, Policy>& dist)\r\n{\r\n   RealType df = dist.degrees_of_freedom();\r\n   static const char* function = \"boost::math::kurtosis(const inverse_chi_squared_distribution<%1%>&)\";\r\n   if(df <= 8)\r\n      return policies::raise_domain_error<RealType>(\r\n         function,\r\n         \"inverse Chi-Squared distribution only has a kurtosis excess for degrees of freedom > 8, but got degrees of freedom = %1%.\",\r\n         df, Policy());\r\n\r\n   return 12 * (5 * df - 22) / ((df - 6 )*(df - 8));  // Not a function of scale.\r\n}\r\n\r\n//\r\n// Parameter estimation comes last:\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_MATH_DISTRIBUTIONS_INVERSE_CHI_SQUARED_HPP\r\n", "meta": {"hexsha": "a7565c19c79c75662046e1dfe45331cf2f34715d", "size": 15593, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ios/Pods/boost-for-react-native/boost/math/distributions/inverse_chi_squared.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/inverse_chi_squared.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/inverse_chi_squared.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.7780612245, "max_line_length": 134, "alphanum_fraction": 0.6683127044, "num_tokens": 3846, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6039318337259584, "lm_q2_score": 0.5736784074525096, "lm_q1q2_score": 0.34646265258178166}}
{"text": "/******************************************************************************\n *\n * AMDiS - Adaptive multidimensional simulations\n *\n * Copyright (C) 2013 Dresden University of Technology. All Rights Reserved.\n * Web: https://fusionforge.zih.tu-dresden.de/projects/amdis\n *\n * Authors:\n * Simon Vey, Thomas Witkowski, Andreas Naumann, Simon Praetorius, et al.\n *\n * This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE\n * WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.\n *\n *\n * This file is part of AMDiS\n *\n * See also license.opensource.txt in the distribution.\n *\n ******************************************************************************/\n\n\n#include <boost/numeric/mtl/mtl.hpp>\n#include \"CompositeFEMOperator.h\"\n#include \"SubElementAssembler.h\"\n#include \"SubElInfo.h\"\n#include \"SubPolytope.h\"\n\nnamespace compositeFEM\n{\n\n  using namespace std;\n  using namespace AMDiS;\n\n  void CompositeFEMOperator::getElementMatrix(const ElInfo* elInfo,\n      ElementMatrix& userMat,\n      double factor)\n  {\n    FUNCNAME(\"CompositeFEMOperator::getElementMatrix\");\n\n    VectorOfFixVecs<DimVec<double>>* intersecPoints = NULL;\n    SubPolytope* subPolytope = NULL;\n    double levelSetSubPolytope;\n    DimVec<double> subElVertexBarCoords(elInfo->getMesh()->getDim());\n\n    /**\n     * Get element status. Does element lie completely inside the integration\n     * domain, completely outside of the integration domain or is it\n     * intersected by the boundary ?\n     */\n    elStatus = elLS->createElementLevelSet(elInfo);\n\n    /**\n     * element status == completely inside or outside\n     *                                       --->  take the \"normal\"\n     *                                             integration routine\n     *                                             Operator::getElementMatrix\n     * element status == lies on boundary  ---> integration on subpolytopes and\n     *                                          subelements\n     */\n    if (elStatus == ElementLevelSet::LEVEL_SET_INTERIOR  ||\n        elStatus == ElementLevelSet::LEVEL_SET_EXTERIOR)\n    {\n\n      elLS->setLevelSetDomain(elStatus);\n      Operator::getElementMatrix(elInfo, userMat, factor);\n      return;\n    }\n\n    /***************************************************************************\n     * Integration on intersected element.\n     *\n     * The integral is calculated as the sum of integrals on the two\n     * subpolytopes given by the intersection.\n     * We only calculate the integral on one of the subpolytopes. The\n     * integral on the second subpolytope then is the difference between the\n     * integral on the complete element and the integral on the first\n     * subpolytope.\n     */\n\n    if(!subElementAssembler)\n    {\n      subElementAssembler = new SubElementAssembler(this,\n          rowFeSpace,\n          colFeSpace);\n    }\n\n    // Get intersection points.\n    intersecPoints = elLS->getElIntersecPoints();\n    subPolytope = new SubPolytope(elInfo,\n                                  intersecPoints,\n                                  elLS->getNumElIntersecPoints());\n\n    /**\n     * Calculate integral on element.\n     *\n     * Whether a subpolytope lies inside or outside the integration domain is\n     * decided using the level set of the first vertex in the first subelement\n     * of the subpolytope. (The subelements of a subpolytope are created in\n     * such a way that this vertex always is a vertex of the element\n     * and not an intersection point. Thus the level set of this vertex really\n     * is unequal to zero.)\n     */\n\n    /**\n     * Integration on subPolytope.\n     */\n    subElVertexBarCoords = subPolytope->getSubElement(0)->getLambda(0);\n    levelSetSubPolytope = elLS->getVertexPos(\n                            (const DimVec<double>) subElVertexBarCoords);\n\n    if (levelSetSubPolytope < 0)\n    {\n      elLS->setLevelSetDomain(ElementLevelSet::LEVEL_SET_INTERIOR);\n    }\n    else if (levelSetSubPolytope > 0)\n    {\n      elLS->setLevelSetDomain(ElementLevelSet::LEVEL_SET_EXTERIOR);\n    }\n    else\n    {\n      ERROR_EXIT(\"cannot get position of subpolytope\\n\");\n    }\n\n    ElementMatrix subPolMat1(subElementAssembler->getNRow(),\n                             subElementAssembler->getNCol());\n    set_to_zero(subPolMat1);\n    subElementAssembler->getSubPolytopeMatrix(subPolytope,\n        subElementAssembler,\n        elInfo,\n        subPolMat1);\n\n    /**\n     * Integration on second subpolytope produced by the intersection.\n     */\n    ElementMatrix elMat(subElementAssembler->getNRow(),\n                        subElementAssembler->getNCol());\n    set_to_zero(elMat);\n    ElementMatrix subPolMat2(subElementAssembler->getNRow(),\n                             subElementAssembler->getNCol());\n    set_to_zero(subPolMat2);\n\n    if (!assembler.get())\n    {\n      Assembler* aptr = new StandardAssembler(this, NULL, NULL, NULL, NULL, rowFeSpace, colFeSpace);\n      assembler.set(aptr);\n    }\n\n    if (elLS->getLevelSetDomain() ==\n        ElementLevelSet::LEVEL_SET_INTERIOR)\n    {\n      elLS->setLevelSetDomain(ElementLevelSet::LEVEL_SET_EXTERIOR);\n    }\n    else\n    {\n      elLS->setLevelSetDomain(ElementLevelSet::LEVEL_SET_INTERIOR);\n    }\n\n    assembler.get()->calculateElementMatrix(elInfo, elMat, 1.0);\n    subElementAssembler->getSubPolytopeMatrix(subPolytope,\n        subElementAssembler,\n        elInfo,\n        subPolMat2);\n\n    elMat -= subPolMat2;\n\n    // Get integral on element as sum of the two integrals on subpolytopes.\n    elMat += subPolMat1;\n\n    // Add integral to userMat.\n    userMat += factor * elMat;\n\n    // Free data\n    delete subPolytope;\n  }\n\n\n  void CompositeFEMOperator::getElementVector(const ElInfo* elInfo,\n      DenseVector<double>& userVec,\n      double factor)\n  {\n    FUNCNAME(\"CompositeFEMOperator::getElementVector\");\n\n    VectorOfFixVecs<DimVec<double>>* intersecPoints = NULL;\n    SubPolytope* subPolytope = NULL;\n    double levelSetSubPolytope;\n    DimVec<double> subElVertexBarCoords(elInfo->getMesh()->getDim());\n\n    /**\n     * Get element status. Does element lie completely inside the integration\n     * domain, completely outside of the integration domain or is it\n     * intersected by the boundary ?\n     */\n    elStatus = elLS->createElementLevelSet(elInfo);\n\n    /**\n     * element status == completely inside or outside\n     *                                        --->  take the \"normal\"\n     *                                              integration routine\n     *                                              Operator::getElementVector\n     * element status == lies on boundary  ---> integration on subpolytopes and\n     *                                          subelements\n     */\n    if (elStatus == ElementLevelSet::LEVEL_SET_INTERIOR  ||\n        elStatus == ElementLevelSet::LEVEL_SET_EXTERIOR)\n    {\n\n      elLS->setLevelSetDomain(elStatus);\n      Operator::getElementVector(elInfo, userVec, factor);\n      return;\n    }\n\n    /*********************************************************************************\n     * Integration on intersected element.\n     *\n     * The integral is calculated as the sum of integrals on the two\n     * subpolytopes given by the intersection.\n     * We only calculate the integral on one of the subpolytopes. The integral\n     * on the second subpolytope then is the difference between the integral on\n     * the complete element and the integral on the first subpolytope.\n     */\n\n    if(!subElementAssembler)\n    {\n      subElementAssembler = new SubElementAssembler(this,\n          rowFeSpace,\n          colFeSpace);\n    }\n\n    /**\n     * Get intersection points.\n     */\n    intersecPoints = elLS->getElIntersecPoints();\n    subPolytope = new SubPolytope(elInfo,\n                                  intersecPoints,\n                                  elLS->getNumElIntersecPoints());\n\n    /**\n     * Calculate integral on element.\n     *\n     * Whether a subpolytope lies inside or outside the integration domain is\n     * decided using the level set of the first vertex in the first subelement\n     * of the subpolytope. (The subelements of a subpolytope are created in\n     * such a way that this vertex is always a vertex of the element and not\n     * an intersection point. Thus the level set of this vertex really is\n     * unequal to zero.)\n     */\n\n    /**\n     * Integration on ubPolytope.\n     */\n    subElVertexBarCoords = subPolytope->getSubElement(0)->getLambda(0);\n    levelSetSubPolytope = elLS->getVertexPos(\n                            (const DimVec<double>) subElVertexBarCoords);\n\n    if (levelSetSubPolytope < 0)\n    {\n      elLS->setLevelSetDomain(ElementLevelSet::LEVEL_SET_INTERIOR);\n    }\n    else if (levelSetSubPolytope > 0)\n    {\n      elLS->setLevelSetDomain(ElementLevelSet::LEVEL_SET_EXTERIOR);\n    }\n    else\n    {\n      ERROR_EXIT(\"cannot get position of subpolytope\\n\");\n    }\n\n    DenseVector<double> subPolVec1(subElementAssembler->getNRow());\n    set_to_zero(subPolVec1);\n    subElementAssembler->getSubPolytopeVector(subPolytope,\n        subElementAssembler,\n        elInfo,\n        subPolVec1);\n\n    // Integration on second subpolytope produced by the intersection.\n    DenseVector<double> elVec(subElementAssembler->getNRow());\n    set_to_zero(elVec);\n    DenseVector<double> subPolVec2(subElementAssembler->getNRow());\n    set_to_zero(subPolVec2);\n\n    if (!assembler.get())\n    {\n      Assembler* aptr = new StandardAssembler(this, NULL, NULL, NULL, NULL, rowFeSpace, colFeSpace);\n      assembler.set(aptr);\n    }\n\n    if (elLS->getLevelSetDomain() ==\n        ElementLevelSet::LEVEL_SET_INTERIOR)\n    {\n      elLS->setLevelSetDomain(ElementLevelSet::LEVEL_SET_EXTERIOR);\n    }\n    else\n    {\n      elLS->setLevelSetDomain(ElementLevelSet::LEVEL_SET_INTERIOR);\n    }\n\n    assembler.get()->calculateElementVector(elInfo, elVec, 1.0);\n    subElementAssembler->getSubPolytopeVector(subPolytope,\n        subElementAssembler,\n        elInfo,\n        subPolVec2);\n\n    elVec -= subPolVec2;\n\n    // Get integral on element as sum of the two integrals on subpolytopes.\n    elVec += subPolVec1;\n\n    // Add integral to userVec.\n    userVec += factor * elVec;\n\n    // Free data\n    delete subPolytope;\n  }\n\n}\n", "meta": {"hexsha": "9e9e27226fa5f86924e47e96a23bae7d6d7da8a5", "size": 10206, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/compositeFEM/CompositeFEMOperator.cpp", "max_stars_repo_name": "spraetor/amdis2", "max_stars_repo_head_hexsha": "53c45c81a65752a8fafbb54f9ae6724a86639dcd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2018-07-04T16:44:04.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-03T07:26:27.000Z", "max_issues_repo_path": "src/compositeFEM/CompositeFEMOperator.cpp", "max_issues_repo_name": "spraetor/amdis2", "max_issues_repo_head_hexsha": "53c45c81a65752a8fafbb54f9ae6724a86639dcd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/compositeFEM/CompositeFEMOperator.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": 32.2974683544, "max_line_length": 100, "alphanum_fraction": 0.6223789927, "num_tokens": 2360, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6926419831347362, "lm_q2_score": 0.5, "lm_q1q2_score": 0.3463209915673681}}
{"text": "// Copyright Nick Thompson, 2021\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#ifndef BOOST_MATH_INTERPOLATORS_BEZIER_POLYNOMIAL_HPP\n#define BOOST_MATH_INTERPOLATORS_BEZIER_POLYNOMIAL_HPP\n#include <memory>\n#include <boost/math/interpolators/detail/bezier_polynomial_detail.hpp>\n\n#ifdef BOOST_MATH_NO_THREAD_LOCAL_WITH_NON_TRIVIAL_TYPES\n#warning \"Thread local storage support is necessary for the Bezier polynomial class to work.\"\n#endif\n\nnamespace boost::math::interpolators {\n\ntemplate <class RandomAccessContainer>\nclass bezier_polynomial\n{\npublic:\n    using Point = typename RandomAccessContainer::value_type;\n    using Real = typename Point::value_type;\n    using Z = typename RandomAccessContainer::size_type;\n\n    bezier_polynomial(RandomAccessContainer && control_points)\n    : m_imp(std::make_shared<detail::bezier_polynomial_imp<RandomAccessContainer>>(std::move(control_points)))\n    {\n    }\n\n    inline Point operator()(Real t) const\n    {\n        return (*m_imp)(t);\n    }\n\n    inline Point prime(Real t) const\n    {\n        return m_imp->prime(t);\n    }\n\n    void edit_control_point(Point const & p, Z index)\n    {\n        m_imp->edit_control_point(p, index);\n    }\n\n    RandomAccessContainer const & control_points() const\n    {\n        return m_imp->control_points();\n    }\n\n    friend std::ostream& operator<<(std::ostream& out, bezier_polynomial<RandomAccessContainer> const & bp) {\n        out << *bp.m_imp;\n        return out;\n    }\n\nprivate:\n    std::shared_ptr<detail::bezier_polynomial_imp<RandomAccessContainer>> m_imp;\n};\n\n}\n#endif\n", "meta": {"hexsha": "022d205c094f1648796d380fa6c6cd93a58ff3c7", "size": 1702, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/math/interpolators/bezier_polynomial.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/interpolators/bezier_polynomial.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/interpolators/bezier_polynomial.hpp", "max_forks_repo_name": "oleg-alexandrov/math", "max_forks_repo_head_hexsha": "2137c31eb8e52129d997a76b893f71c1da0ccc5f", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 243.0, "max_forks_repo_forks_event_min_datetime": "2015-01-17T17:46:32.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-07T12:56:26.000Z", "avg_line_length": 27.9016393443, "max_line_length": 110, "alphanum_fraction": 0.7297297297, "num_tokens": 405, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6926419704455589, "lm_q2_score": 0.5, "lm_q1q2_score": 0.34632098522277943}}
{"text": "//==================================================================================================\n/*!\n  @file\n\n  @copyright 2016 NumScale SAS\n\n  Distributed under the Boost Software License, Version 1.0.\n  (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\n*/\n//==================================================================================================\n#ifndef BOOST_SIMD_ARCH_COMMON_SIMD_FUNCTION_SINH_HPP_INCLUDED\n#define BOOST_SIMD_ARCH_COMMON_SIMD_FUNCTION_SINH_HPP_INCLUDED\n\n#include <boost/simd/detail/overload.hpp>\n#include <boost/simd/arch/common/detail/generic/sinh_kernel.hpp>\n#include <boost/simd/meta/as_logical.hpp>\n#include <boost/simd/constant/half.hpp>\n#include <boost/simd/constant/log_2.hpp>\n#include <boost/simd/detail/constant/maxlog.hpp>\n#include <boost/simd/constant/one.hpp>\n#include <boost/simd/constant/zero.hpp>\n#include <boost/simd/function/abs.hpp>\n#include <boost/simd/function/bitofsign.hpp>\n#include <boost/simd/function/bitwise_xor.hpp>\n#include <boost/simd/function/exp.hpp>\n#include <boost/simd/function/if_else.hpp>\n#include <boost/simd/function/nbtrue.hpp>\n#include <boost/simd/function/is_greater.hpp>\n#include <boost/simd/function/is_less.hpp>\n#include <boost/simd/function/minus.hpp>\n#include <boost/simd/function/multiplies.hpp>\n#include <boost/simd/function/rec.hpp>\n#include <boost/simd/function/sqr.hpp>\n\nnamespace boost { namespace simd { namespace ext\n{\n   namespace bd = boost::dispatch;\n   namespace bs = boost::simd;\n   BOOST_DISPATCH_OVERLOAD_IF( sinh_\n                          , (typename A0, typename X)\n                          , (detail::is_native<X>)\n                          , bd::cpu_\n                          , bs::pack_<bd::floating_<A0>, X>\n                          )\n   {\n      BOOST_FORCEINLINE A0 operator()( const A0& a0) const BOOST_NOEXCEPT\n      {\n        A0 x = bs::abs(a0);\n        auto lt1= is_less(x, One<A0>());\n        A0 bts = bitofsign(a0);\n        std::size_t nb = nbtrue(lt1);\n        A0 z = Zero<A0>();\n        if(nb > 0)\n        {\n          A0 x2 = sqr(x);\n          z = detail::sinh_kernel<A0>::compute(x, x2);\n          if(nb >= A0::static_size) return bitwise_xor(z, bts);\n        }\n        auto test1 = is_greater(x, Maxlog<A0>()-Log_2<A0>());\n        A0 fac = if_else(test1, Half<A0>(), One<A0>());\n        A0 tmp = exp(x*fac);\n        A0 tmp1 = Half<A0>()*tmp;\n        A0 r =  if_else(test1, tmp1*tmp, tmp1-Half<A0>()*rec(tmp));\n        return bitwise_xor(if_else(lt1, z, r), bts);\n      }\n   };\n\n} } }\n\n#endif\n", "meta": {"hexsha": "a7fb512ef7730a783488464a4bce8a83f3c4abb2", "size": 2539, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/arch/common/simd/function/sinh.hpp", "max_stars_repo_name": "SylvainCorlay/pythran", "max_stars_repo_head_hexsha": "908ec070d837baf77d828d01c3e35e2f4bfa2bfa", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2018-02-25T22:23:33.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-15T15:13:12.000Z", "max_issues_repo_path": "third_party/boost/simd/arch/common/simd/function/sinh.hpp", "max_issues_repo_name": "SylvainCorlay/pythran", "max_issues_repo_head_hexsha": "908ec070d837baf77d828d01c3e35e2f4bfa2bfa", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "third_party/boost/simd/arch/common/simd/function/sinh.hpp", "max_forks_repo_name": "SylvainCorlay/pythran", "max_forks_repo_head_hexsha": "908ec070d837baf77d828d01c3e35e2f4bfa2bfa", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2017-12-12T12:36:31.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-10T14:27:07.000Z", "avg_line_length": 35.7605633803, "max_line_length": 100, "alphanum_fraction": 0.5880267822, "num_tokens": 632, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7772998611746912, "lm_q2_score": 0.4455295350395727, "lm_q1q2_score": 0.3463100457354846}}
{"text": "/*\n [auto_generated]\n boost/numeric/odeint/stepper/runge_kutta4_classic.hpp\n\n [begin_description]\n Implementation for the classical Runge Kutta stepper.\n [end_description]\n\n Copyright 2010-2013 Karsten Ahnert\n Copyright 2010-2013 Mario Mulansky\n Copyright 2012 Christoph Koke\n\n Distributed under the Boost Software License, Version 1.0.\n (See accompanying file LICENSE_1_0.txt or\n copy at http://www.boost.org/LICENSE_1_0.txt)\n */\n\n\n#ifndef BOOST_NUMERIC_ODEINT_STEPPER_RUNGE_KUTTA4_CLASSIC_HPP_INCLUDED\n#define BOOST_NUMERIC_ODEINT_STEPPER_RUNGE_KUTTA4_CLASSIC_HPP_INCLUDED\n\n\n\n#include <boost/numeric/odeint/stepper/base/explicit_stepper_base.hpp>\n#include <boost/numeric/odeint/algebra/range_algebra.hpp>\n#include <boost/numeric/odeint/algebra/default_operations.hpp>\n#include <boost/numeric/odeint/algebra/algebra_dispatcher.hpp>\n#include <boost/numeric/odeint/algebra/operations_dispatcher.hpp>\n\n#include <boost/numeric/odeint/util/state_wrapper.hpp>\n#include <boost/numeric/odeint/util/is_resizeable.hpp>\n#include <boost/numeric/odeint/util/resizer.hpp>\n\nnamespace boost {\nnamespace numeric {\nnamespace odeint {\n\ntemplate<\nclass State ,\nclass Value = double ,\nclass Deriv = State ,\nclass Time = Value ,\nclass Algebra = typename algebra_dispatcher< State >::algebra_type ,\nclass Operations = typename operations_dispatcher< State >::operations_type ,\nclass Resizer = initially_resizer\n>\n#ifndef DOXYGEN_SKIP\nclass runge_kutta4_classic\n: public explicit_stepper_base<\n  runge_kutta4_classic< State , Value , Deriv , Time , Algebra , Operations , Resizer > ,\n  4 , State , Value , Deriv , Time , Algebra , Operations , Resizer >\n#else\nclass runge_kutta4_classic : public explicit_stepper_base\n#endif\n{\n\npublic :\n\n    #ifndef DOXYGEN_SKIP\n    typedef explicit_stepper_base<\n    runge_kutta4_classic< State , Value , Deriv , Time , Algebra , Operations , Resizer > ,\n    4 , State , Value , Deriv , Time , Algebra , Operations , Resizer > stepper_base_type;\n    #else\n    typedef explicit_stepper_base< runge_kutta4_classic< ... > , ... > stepper_base_type;\n    #endif\n\n    typedef typename stepper_base_type::state_type state_type;\n    typedef typename stepper_base_type::value_type value_type;\n    typedef typename stepper_base_type::deriv_type deriv_type;\n    typedef typename stepper_base_type::time_type time_type;\n    typedef typename stepper_base_type::algebra_type algebra_type;\n    typedef typename stepper_base_type::operations_type operations_type;\n    typedef typename stepper_base_type::resizer_type resizer_type;\n\n    #ifndef DOXYGEN_SKIP\n    typedef typename stepper_base_type::stepper_type stepper_type;\n    typedef typename stepper_base_type::wrapped_state_type wrapped_state_type;\n    typedef typename stepper_base_type::wrapped_deriv_type wrapped_deriv_type;\n    #endif // DOXYGEN_SKIP\n\n\n\n    runge_kutta4_classic( const algebra_type &algebra = algebra_type() ) : stepper_base_type( algebra )\n    { }\n\n\n    template< class System , class StateIn , class DerivIn , class StateOut >\n    void do_step_impl( System system , const StateIn &in , const DerivIn &dxdt , time_type t , StateOut &out , time_type dt )\n    {\n        // ToDo : check if size of in,dxdt,out are equal?\n\n        static const value_type val1 = static_cast< value_type >( 1 );\n\n        m_resizer.adjust_size( in , detail::bind( &stepper_type::template resize_impl< StateIn > , detail::ref( *this ) , detail::_1 ) );\n\n        typename odeint::unwrap_reference< System >::type &sys = system;\n\n        const time_type dh = dt / static_cast< value_type >( 2 );\n        const time_type th = t + dh;\n\n        // dt * dxdt = k1\n        // m_x_tmp = x + dh*dxdt\n        stepper_base_type::m_algebra.for_each3( m_x_tmp.m_v , in , dxdt ,\n                typename operations_type::template scale_sum2< value_type , time_type >( val1 , dh ) );\n\n\n        // dt * m_dxt = k2\n        sys( m_x_tmp.m_v , m_dxt.m_v , th );\n\n        // m_x_tmp = x + dh*m_dxt\n        stepper_base_type::m_algebra.for_each3( m_x_tmp.m_v , in , m_dxt.m_v ,\n                typename operations_type::template scale_sum2< value_type , time_type >( val1 , dh ) );\n\n\n        // dt * m_dxm = k3\n        sys( m_x_tmp.m_v , m_dxm.m_v , th );\n        //m_x_tmp = x + dt*m_dxm\n        stepper_base_type::m_algebra.for_each3( m_x_tmp.m_v , in , m_dxm.m_v ,\n                typename operations_type::template scale_sum2< value_type , time_type >( val1 , dt ) );\n\n\n        // dt * m_dxh = k4\n        sys( m_x_tmp.m_v , m_dxh.m_v , t + dt );\n\n        //x += dt/6 * ( m_dxdt + m_dxt + val2*m_dxm )\n        time_type dt6 = dt / static_cast< value_type >( 6 );\n        time_type dt3 = dt / static_cast< value_type >( 3 );\n        stepper_base_type::m_algebra.for_each6( out , in , dxdt , m_dxt.m_v , m_dxm.m_v , m_dxh.m_v ,\n                                             typename operations_type::template scale_sum5< value_type , time_type , time_type , time_type , time_type >( 1.0 , dt6 , dt3 , dt3 , dt6 ) );\n\n        // x += dt/6 * m_dxdt + dt/3 * m_dxt )\n        // stepper_base_type::m_algebra.for_each4( out , in , dxdt , m_dxt.m_v ,\n        //                                         typename operations_type::template scale_sum3< value_type , time_type , time_type >( 1.0 , dt6 , dt3 ) );\n        // // x += dt/3 * m_dxm + dt/6 * m_dxh )\n        // stepper_base_type::m_algebra.for_each4( out , out , m_dxm.m_v , m_dxh.m_v ,\n        //                                         typename operations_type::template scale_sum3< value_type , time_type , time_type >( 1.0 , dt3 , dt6 ) );\n\n    }\n\n    template< class StateType >\n    void adjust_size( const StateType &x )\n    {\n        resize_impl( x );\n        stepper_base_type::adjust_size( x );\n    }\n\nprivate:\n\n    template< class StateIn >\n    bool resize_impl( const StateIn &x )\n    {\n        bool resized = false;\n        resized |= adjust_size_by_resizeability( m_x_tmp , x , typename is_resizeable<state_type>::type() );\n        resized |= adjust_size_by_resizeability( m_dxm , x , typename is_resizeable<deriv_type>::type() );\n        resized |= adjust_size_by_resizeability( m_dxt , x , typename is_resizeable<deriv_type>::type() );\n        resized |= adjust_size_by_resizeability( m_dxh , x , typename is_resizeable<deriv_type>::type() );\n        return resized;\n    }\n\n\n    resizer_type m_resizer;\n\n    wrapped_deriv_type m_dxt;\n    wrapped_deriv_type m_dxm;\n    wrapped_deriv_type m_dxh;\n    wrapped_state_type m_x_tmp;\n\n};\n\n\n/********* DOXYGEN *********/\n\n/**\n * \\class runge_kutta4_classic\n * \\brief The classical Runge-Kutta stepper of fourth order.\n *\n * The Runge-Kutta method of fourth order is one standard method for\n * solving ordinary differential equations and is widely used, see also\n * <a href=\"http://en.wikipedia.org/wiki/Runge%E2%80%93Kutta_methods\">en.wikipedia.org/wiki/Runge-Kutta_methods</a>\n * The method is explicit and fulfills the Stepper concept. Step size control\n * or continuous output are not provided.  This class implements the method directly, hence the \n * generic Runge-Kutta algorithm is not used.\n * \n * This class derives from explicit_stepper_base and inherits its interface via\n * CRTP (current recurring template pattern). For more details see\n * explicit_stepper_base.\n *\n * \\tparam State The state type.\n * \\tparam Value The value type.\n * \\tparam Deriv The type representing the time derivative of the state.\n * \\tparam Time The time representing the independent variable - the time.\n * \\tparam Algebra The algebra type.\n * \\tparam Operations The operations type.\n * \\tparam Resizer The resizer policy type.\n */\n\n    /**\n     * \\fn runge_kutta4_classic::runge_kutta4_classic( const algebra_type &algebra )\n     * \\brief Constructs the runge_kutta4_classic class. This constructor can be used as a default\n     * constructor if the algebra has a default constructor. \n     * \\param algebra A copy of algebra is made and stored inside explicit_stepper_base.\n     */\n\n\n    /**\n     * \\fn runge_kutta4_classic::do_step_impl( System system , const StateIn &in , const DerivIn &dxdt , time_type t , StateOut &out , time_type dt )\n     * \\brief This method performs one step. The derivative `dxdt` of `in` at the time `t` is passed to the method.\n     * The result is updated out of place, hence the input is in `in` and the output in `out`.\n     * Access to this step functionality is provided by explicit_stepper_base and \n     * `do_step_impl` should not be called directly.\n     *\n     * \\param system The system function to solve, hence the r.h.s. of the ODE. It must fulfill the\n     *               Simple System concept.\n     * \\param in The state of the ODE which should be solved. in is not modified in this method\n     * \\param dxdt The derivative of x at t.\n     * \\param t The value of the time, at which the step should be performed.\n     * \\param out The result of the step is written in out.\n     * \\param dt The step size.\n     */\n\n    /**\n     * \\fn runge_kutta4_classic::adjust_size( const StateType &x )\n     * \\brief Adjust the size of all temporaries in the stepper manually.\n     * \\param x A state from which the size of the temporaries to be resized is deduced.\n     */\n\n} // odeint\n} // numeric\n} // boost\n\n\n#endif // BOOST_NUMERIC_ODEINT_STEPPER_RUNGE_KUTTA4_CLASSIC_HPP_INCLUDED\n", "meta": {"hexsha": "4463a53ebdc5ef763fcf4799fd30abff13a12e84", "size": 9243, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "3party/boost/boost/numeric/odeint/stepper/runge_kutta4_classic.hpp", "max_stars_repo_name": "marceldallagnol/omim", "max_stars_repo_head_hexsha": "774de15a3b8c369acbf412f15a1db61717358262", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-01-24T15:36:20.000Z", "max_stars_repo_stars_event_max_datetime": "2019-12-26T10:03:48.000Z", "max_issues_repo_path": "3party/boost/boost/numeric/odeint/stepper/runge_kutta4_classic.hpp", "max_issues_repo_name": "marceldallagnol/omim", "max_issues_repo_head_hexsha": "774de15a3b8c369acbf412f15a1db61717358262", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 13.0, "max_issues_repo_issues_event_min_datetime": "2015-09-28T13:59:23.000Z", "max_issues_repo_issues_event_max_datetime": "2015-10-08T20:12:45.000Z", "max_forks_repo_path": "3party/boost/boost/numeric/odeint/stepper/runge_kutta4_classic.hpp", "max_forks_repo_name": "marceldallagnol/omim", "max_forks_repo_head_hexsha": "774de15a3b8c369acbf412f15a1db61717358262", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-08-09T21:31:29.000Z", "max_forks_repo_forks_event_max_datetime": "2019-08-09T21:31:29.000Z", "avg_line_length": 39.669527897, "max_line_length": 186, "alphanum_fraction": 0.6934977821, "num_tokens": 2358, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6076631698328916, "lm_q2_score": 0.5698526514141572, "lm_q1q2_score": 0.3462784684960046}}
{"text": "/******************************************************************************\n * Author:   Laurent Kneip                                                    *\n * Contact:  kneip.laurent@gmail.com                                          *\n * License:  Copyright (c) 2013 Laurent Kneip, ANU. All rights reserved.      *\n *                                                                            *\n * Redistribution and use in source and binary forms, with or without         *\n * modification, are permitted provided that the following conditions         *\n * are met:                                                                   *\n * * Redistributions of source code must retain the above copyright           *\n *   notice, this list of conditions and the following disclaimer.            *\n * * Redistributions in binary form must reproduce the above copyright        *\n *   notice, this list of conditions and the following disclaimer in the      *\n *   documentation and/or other materials provided with the distribution.     *\n * * Neither the name of ANU nor the names of its contributors may be         *\n *   used to endorse or promote products derived from this software without   *\n *   specific prior written permission.                                       *\n *                                                                            *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"*\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE  *\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE *\n * ARE DISCLAIMED. IN NO EVENT SHALL ANU OR THE CONTRIBUTORS BE LIABLE        *\n * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL *\n * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR *\n * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER *\n * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT         *\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY  *\n * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF     *\n * SUCH DAMAGE.                                                               *\n ******************************************************************************/\n\n#include <stdlib.h>\n#include <stdio.h>\n#include <iostream>\n#include <iomanip>\n#include <limits.h>\n#include <Eigen/Eigen>\n#include <opengv/absolute_pose/methods.hpp>\n#include <opengv/absolute_pose/NoncentralAbsoluteMultiAdapter.hpp>\n#include <opengv/sac/MultiRansac.hpp>\n#include <opengv/sac_problems/absolute_pose/MultiNoncentralAbsolutePoseSacProblem.hpp>\n#include <sstream>\n#include <fstream>\n\n#include \"random_generators.hpp\"\n#include \"experiment_helpers.hpp\"\n#include \"time_measurement.hpp\"\n\n\nusing namespace std;\nusing namespace Eigen;\nusing namespace opengv;\n\nint main( int argc, char** argv )\n{\n  //initialize random seed\n  initializeRandomSeed();\n\n  //set experiment parameters\n  double noise = 0.5;\n  double outlierFraction = 0.1;\n  size_t pointsPerCam = 25;\n  int numberCameras = 4;\n\n  //create a random viewpoint pose\n  translation_t position = generateRandomTranslation(2.0);\n  rotation_t rotation = generateRandomRotation(0.5);\n\n  //create a random camera-system\n  translations_t camOffsets;\n  rotations_t camRotations;\n  generateRandomCameraSystem( numberCameras, camOffsets, camRotations );\n\n  //derive correspondences based on random point-cloud\n  std::vector<std::shared_ptr<points_t> > multiPoints;\n  std::vector<std::shared_ptr<bearingVectors_t> > multiBearingVectors;\n  std::vector< std::shared_ptr<Eigen::MatrixXd> > gt;\n  generateMulti2D3DCorrespondences(\n      position, rotation, camOffsets, camRotations,\n      pointsPerCam, noise, outlierFraction,\n      multiPoints, multiBearingVectors, gt );\n\n  //print the experiment characteristics\n  printExperimentCharacteristics(\n      position, rotation, noise, outlierFraction );\n\n  //create a non-central absolute adapter\n  absolute_pose::NoncentralAbsoluteMultiAdapter adapter(\n      multiBearingVectors,\n      multiPoints,\n      camOffsets,\n      camRotations );\n\n  //Create a AbsolutePoseSacProblem and Ransac\n  //The method is set to GP3P\n  sac::MultiRansac<\n      sac_problems::absolute_pose::MultiNoncentralAbsolutePoseSacProblem> ransac;\n  std::shared_ptr<\n      sac_problems::absolute_pose::MultiNoncentralAbsolutePoseSacProblem> absposeproblem_ptr(\n      new sac_problems::absolute_pose::MultiNoncentralAbsolutePoseSacProblem(\n      adapter ));\n\n  ransac.sac_model_ = absposeproblem_ptr;\n  ransac.threshold_ = 1.0 - cos(atan(sqrt(2.0)*0.5/800.0));\n  ransac.max_iterations_ = 50;\n\n  //Run the experiment\n  struct timeval tic;\n  struct timeval toc;\n  gettimeofday( &tic, 0 );\n  ransac.computeModel();\n  gettimeofday( &toc, 0 );\n  double ransac_time = TIMETODOUBLE(timeval_minus(toc,tic));\n\n  //print the results\n  std::cout << \"the ransac results is: \" << std::endl;\n  std::cout << ransac.model_coefficients_ << std::endl << std::endl;\n  std::cout << \"Ransac needed \" << ransac.iterations_ << \" iterations and \";\n  std::cout << ransac_time << \" seconds\" << std::endl << std::endl;\n  size_t numberInliers = 0;\n  for(size_t i = 0; i < ransac.inliers_.size(); i++)\n    numberInliers += ransac.inliers_[i].size();\n  std::cout << \"the number of inliers is: \" << numberInliers;\n  std::cout << std::endl << std::endl;\n  std::cout << \"the found inliers are: \" << std::endl;\n  for(size_t i = 0; i < ransac.inliers_.size(); i++)\n  {\n    for(size_t j = 0; j < ransac.inliers_[i].size(); j++)\n      std::cout << ransac.inliers_[i][j] << \" \";\n  }\n  std::cout << std::endl << std::endl;\n}\n", "meta": {"hexsha": "107ff1eb653958749933f0156474ecca724d05ce", "size": 5673, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/test_multi_noncentral_absolute_pose_sac.cpp", "max_stars_repo_name": "skn123/opengv", "max_stars_repo_head_hexsha": "91f4b19c73450833a40e463ad3648aae80b3a7f3", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 794.0, "max_stars_repo_stars_event_min_datetime": "2015-01-16T22:25:41.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-27T23:59:20.000Z", "max_issues_repo_path": "test/test_multi_noncentral_absolute_pose_sac.cpp", "max_issues_repo_name": "skn123/opengv", "max_issues_repo_head_hexsha": "91f4b19c73450833a40e463ad3648aae80b3a7f3", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 77.0, "max_issues_repo_issues_event_min_datetime": "2015-01-14T11:09:25.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-19T13:31:39.000Z", "max_forks_repo_path": "test/test_multi_noncentral_absolute_pose_sac.cpp", "max_forks_repo_name": "skn123/opengv", "max_forks_repo_head_hexsha": "91f4b19c73450833a40e463ad3648aae80b3a7f3", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 276.0, "max_forks_repo_forks_event_min_datetime": "2015-01-15T04:18:56.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-15T09:05:06.000Z", "avg_line_length": 42.9772727273, "max_line_length": 93, "alphanum_fraction": 0.6442799224, "num_tokens": 1295, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6076631698328916, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.3462784684960045}}
{"text": "/*\n * function.cpp\n *\n */\n\n#include <list>\n#include <map>\n#include <random>\n#include <iostream>\n#include <chrono>\n#include <math.h>\n#include <boost/pool/object_pool.hpp>\n#include <sstream>\n\n#include \"function.h\"\n\n\nusing namespace std;\n\nint func_id = 0;\n\nPVariable variable_construct_for_function(Function *f, int rows, int cols) {\n    PVariable r = PVariable(variable_construct(rows, cols), variable_destroy);\n    r->creator = f;\n\n    return r;\n}\n\n\n// Function class //////////////////////////////////////////////////////////////\nFunction::Function(){\n    name = \"Function\";\n    this->id = func_id;\n    func_id += 1;\n    count_function += 1;\n}\n\nFunction::~Function(){\n    init();\n    count_function--;\n\n}\n\nvoid Function::init() {\n    inputs.clear();\n    outputs.clear();\n}\n\n\n\nPVariable Function::forward(vector<PVariable> &inputs, vector<PVariable > &outputs) {\n    return NULL;\n}\n\nvoid Function::backward(cuMat &p_grad, vector<PVariable > &inputs, vector<PVariable > &outputs) {\n    //TODO\n}\n\n\nPVariable Function::forward(PVariable v){\n\n    v->forward_count++;\n\n    inputs.push_back(v);\n    PVariable r = forward(inputs, outputs);\n\n    return r;\n}\n\n\nPVariable Function::forward(PVariable v1, PVariable v2){\n\n    v1->forward_count++;\n    v2->forward_count++;\n\n    inputs.push_back(v1);\n    inputs.push_back(v2);\n    PVariable r = forward(inputs, outputs);\n\n    return r;\n}\n\nPVariable Function::forward(PVariable v1, PVariable v2, PVariable v3){\n\n    v1->forward_count++;\n    v2->forward_count++;\n    v3->forward_count++;\n\n    inputs.push_back(v1);\n    inputs.push_back(v2);\n    inputs.push_back(v3);\n    PVariable r = forward(inputs, outputs);\n\n    return r;\n}\n\nPVariable Function::forward(PVariable v1, PVariable v2, PVariable v3, PVariable v4){\n    v1->forward_count++;\n    v2->forward_count++;\n\n    inputs.push_back(v1);\n    inputs.push_back(v2);\n    inputs.push_back(v3);\n    inputs.push_back(v4);\n    PVariable r = forward(inputs, outputs);\n\n    return r;\n}\n\nPVariable Function::forward(PVariable v1, PVariable v2, PVariable v3, PVariable v4,\n                            PVariable v5, PVariable v6, PVariable v7, PVariable v8,\n                            PVariable v9, PVariable v10, PVariable v11, PVariable v12\n){\n    v1->forward_count++;\n    v2->forward_count++;\n\n\n    inputs.push_back(v1);\n    inputs.push_back(v2);\n    inputs.push_back(v3);\n    inputs.push_back(v4);\n    inputs.push_back(v5);\n    inputs.push_back(v6);\n    inputs.push_back(v7);\n    inputs.push_back(v8);\n    inputs.push_back(v9);\n    inputs.push_back(v10);\n    inputs.push_back(v11);\n    inputs.push_back(v12);\n    PVariable r = forward(inputs, outputs);\n\n    return r;\n}\n\n\n\nvoid Function::backward(cuMat &p_grad){\n    backward(p_grad, inputs, outputs);\n}\n\n\n\nvoid Function::clip_grad(Variable *v){\n    float clip_grad_threshold = 5.0;\n    float sq = v->grad.l2();\n    float rate = clip_grad_threshold/sq;\n    if (rate < 1.){\n        v->grad.mul(rate, v->grad);\n    }\n}\n\nvoid Function::reset_state(){}\n\n\n\nFunctionPlus::FunctionPlus() : Function() {\n    name = \"FunctionPlus\";\n}\n\n\n\nPVariable FunctionPlus::forward(vector<PVariable > &inputs, vector<PVariable > &outputs){\n\n    PVariable v1 = inputs.at(0);\n    PVariable v2 = inputs.at(1);\n\n    PVariable r = variable_construct_for_function(this, v1->data.rows, v1->data.cols);\n\n    v1->data.plus(v2->data, r->data);\n\n    return r;\n}\nvoid FunctionPlus::backward(cuMat &p_grad, vector<PVariable > &inputs, vector<PVariable > &outputs){\n\n    PVariable v1 = inputs.at(0);\n    PVariable v2 = inputs.at(1);\n    //v1->grad += p_grad*1.0;\n    //v2->grad += p_grad*1.0;\n    if (v1->isGetGrad) p_grad.mul_plus(1.0, v1->grad);\n    if (v2->isGetGrad) p_grad.mul_plus(1.0, v2->grad);\n}\n\nFunctionMinus::FunctionMinus() : Function() {\n    name = \"FunctionMinus\";\n}\nPVariable FunctionMinus::forward(vector<PVariable > &inputs, vector<PVariable > &outputs){\n\n\n    PVariable v1 = inputs.at(0);\n    PVariable v2 = inputs.at(1);\n\n    PVariable r = variable_construct_for_function(this, v1->data.rows, v1->data.cols);\n\n    outputs.push_back(r);\n\n    v1->data.minus(v2->data, r->data);\n\n    return r;\n\n}\nvoid FunctionMinus::backward(cuMat &p_grad, vector<PVariable > &inputs, vector<PVariable > &outputs){\n    PVariable v1 = inputs.at(0);\n    PVariable v2 = inputs.at(1);\n    //v1->grad += p_grad*1.0;\n    //v2->grad += p_grad*(-1.0);\n    if (v1->isGetGrad) p_grad.mul_plus(1.0, v1->grad);\n    if (v2->isGetGrad) p_grad.mul_plus(-1.0, v2->grad);\n}\n\n\nFunctionMul::FunctionMul() : Function() {\n    name = \"FunctionMul\";\n}\nPVariable FunctionMul::forward(vector<PVariable > &inputs, vector<PVariable > &outputs){\n\n    PVariable v1 = inputs.at(0);\n    PVariable v2 = inputs.at(1);\n\n    PVariable r = variable_construct_for_function(this, v1->data.rows, v1->data.cols);\n\n\n    outputs.push_back(r);\n    v1->data.mul(v2->data, r->data);\n\n    return r;\n\n}\nvoid FunctionMul::backward(cuMat &p_grad, vector<PVariable > &inputs, vector<PVariable > &outputs){\n\n    PVariable v1 = inputs.at(0);\n    PVariable v2 = inputs.at(1);\n\n    //v1->grad += p_grad * v2->data;\n    //v2->grad += p_grad * v1->data;\n    if (v1->isGetGrad) p_grad.mul_plus(v2->data, v1->grad, 1.0, 1.0);\n    if (v2->isGetGrad) p_grad.mul_plus(v1->data, v2->grad, 1.0, 1.0);\n}\n\n\nFunctionInverse::FunctionInverse() : Function() {\n    name = \"FunctionInverse\";\n}\nPVariable FunctionInverse::forward(vector<PVariable > &inputs, vector<PVariable > &outputs){\n\n    PVariable v = inputs.at(0);\n\n    PVariable r = variable_construct_for_function(this, v->data.rows, v->data.cols);\n\n\n    outputs.push_back(r);\n    v->data.inverse(r->data);\n\n    return r;\n\n}\nvoid FunctionInverse::backward(cuMat &p_grad, vector<PVariable > &inputs, vector<PVariable > &outputs){\n\n    PVariable v = inputs.at(0);\n\n    if (v->isGetGrad) v->grad += p_grad * v->data.inverse_d();\n}\n\nFunctionSqrt::FunctionSqrt() : Function() {\n    name = \"FunctionSqrt\";\n}\nPVariable FunctionSqrt::forward(vector<PVariable > &inputs, vector<PVariable > &outputs){\n\n    PVariable v = inputs.at(0);\n\n    PVariable r = variable_construct_for_function(this, v->data.rows, v->data.cols);\n\n\n    outputs.push_back(r);\n    v->data.sqrt(r->data, 1e-8);\n\n    return r;\n\n}\nvoid FunctionSqrt::backward(cuMat &p_grad, vector<PVariable > &inputs, vector<PVariable > &outputs){\n\n    PVariable v = inputs.at(0);\n\n    if (v->isGetGrad) v->grad += p_grad * v->data.sqrt_d();\n}\n\n\nFunctionSin::FunctionSin() : Function() { }\nPVariable FunctionSin::forward(vector<PVariable > &inputs, vector<PVariable > &outputs){\n\n    PVariable v1 = inputs.at(0);\n\n    PVariable r;\n    r = PVariable(new Variable(this, v1->data.rows, v1->data.cols));\n    outputs.push_back(r);\n\n    v1->data.sin(r->data);\n    return r;\n}\nvoid FunctionSin::backward(cuMat &p_grad, vector<PVariable > &inputs, vector<PVariable > &outputs){\n    PVariable v1 = inputs.at(0);\n\n    if (rr.get() == NULL) rr = PVariable(new Variable(this, v1->data.rows, v1->data.cols));\n    v1->data.cos(rr->data);\n    if (v1->isGetGrad) v1->grad += p_grad * rr->data;\n}\n\nFunctionCos::FunctionCos() : Function() { }\nPVariable FunctionCos::forward(vector<PVariable > &inputs, vector<PVariable > &outputs){\n\n    PVariable v1 = inputs.at(0);\n\n    PVariable r;\n    r = PVariable(new Variable(this, v1->data.rows, v1->data.cols));\n    outputs.push_back(r);\n    v1->data.cos(r->data);\n    return r;\n\n}\nvoid FunctionCos::backward(cuMat &p_grad, vector<PVariable > &inputs, vector<PVariable > &outputs){\n    PVariable v1 = inputs.at(0);\n\n    if (rr.get() == NULL) rr = PVariable(new Variable(this, v1->data.rows, v1->data.cols));\n    v1->data.sin(rr->data);\n    if (v1->isGetGrad) v1->grad += p_grad * rr->data * (-1.0);\n}\n\nFunctionLog::FunctionLog() : Function() {}\nPVariable FunctionLog::forward(vector<PVariable > &inputs, vector<PVariable > &outputs){\n\n    PVariable v1 = inputs.at(0);\n\n    PVariable r;\n    r = PVariable(new Variable(this, v1->data.rows, v1->data.cols));\n    outputs.push_back(r);\n    v1->data.log(r->data, 0);\n    return r;\n\n}\nvoid FunctionLog::backward(cuMat &p_grad, vector<PVariable > &inputs, vector<PVariable > &outputs){\n    PVariable v1 = inputs.at(0);\n\n    if (v1->isGetGrad) v1->grad += p_grad * 1.0/v1->data;\n}\n\n\n\n\n\n\nFunctionLinear::FunctionLinear() : Function() {\n    name = \"FunctionLinear\";\n}\nFunctionLinear::FunctionLinear(Variable *w, Variable *b,  bool isTranspose) : Function() {\n    name = \"FunctionLinear\";\n    this->w  = w;\n    this->b = b;\n    this->isTranspose = isTranspose;\n}\nFunctionLinear::FunctionLinear(Variable *w,  bool isTranspose) : Function() {\n    name = \"FunctionLinear\";\n    noBias = true;\n    this->w  = w;\n    this->isTranspose = isTranspose;\n\n}\nFunctionLinear::FunctionLinear(int output_size, int input_size) : Function() {\n    name = \"FunctionLinear\";\n\n    this->w = new Variable(output_size, input_size);\n    this->b = new Variable(output_size, 1);\n    this->w->randoms(0., sqrt((1./(float)input_size)));\n\n}\n\nFunctionLinear::FunctionLinear(int output_size, int input_size, bool no_bias) : Function() {\n    name = \"FunctionLinear\";\n\n    noBias = no_bias;\n\n    this->w = new Variable(output_size, input_size);\n    this->w->randoms(0., sqrt((1./(float)input_size)));\n\n    if (!noBias){\n        this->b = new Variable(output_size, 1);\n    }\n}\n\n\nvoid FunctionLinear::toHostArray(){\n    i1.toHostArray();\n    w->data.toHostArray();\n    w->grad.toHostArray();\n    if (!noBias){\n        b->data.toHostArray();\n        b->grad.toHostArray();\n    }\n}\nvoid FunctionLinear::fromHostArray(){\n    i1.fromHostArray();\n    w->data.fromHostArray();\n    w->grad.fromHostArray();\n    if (!noBias){\n        b->data.fromHostArray();\n        b->grad.fromHostArray();\n    }\n}\n\n\nPVariable FunctionLinear::forward(vector<PVariable > &inputs, vector<PVariable > &outputs){\n\n\n    PVariable x = inputs.at(0);\n\n    int w_size = w->data.rows;\n    if (isTranspose) w_size = w->data.cols;\n\n    PVariable r = PVariable(new Variable(this, w_size, x->data.cols));\n\n\n\n    if (i1.cols == 0 || i1.cols != x->data.cols){\n        i1 = cuMat(1, x->data.cols);\n        i1.ones();\n    }\n\n\n\n    if (!noBias) b->data.dot(i1, r->data);\n    if (!isTranspose) w->data.dot_plus(x->data, r->data);\n    else w->data.transpose().dot_plus(x->data, r->data);\n    //r->data = w->data.dot(x->data) + b->data.dot(i1);\n\n    return r;\n}\nvoid FunctionLinear::backward(cuMat &p_grad, vector<PVariable > &inputs, vector<PVariable > &outputs){\n\n    PVariable x = inputs.at(0);\n\n    if (x->isGetGrad){\n        if (!isTranspose) w->data.transpose_dot_plus(p_grad, x->grad);\n        else w->data.transpose().transpose_dot_plus(p_grad, x->grad);\n    }\n    //x->grad += w->data.transpose().dot(p_grad);\n\n    if (!isTranspose) p_grad.dot_transpose_plus(x->data, w->grad);\n    else {\n        cuMat tmpwg = w->grad.transpose();\n        tmpwg *= 0;\n        p_grad.dot_transpose_plus(x->data, tmpwg);\n        w->grad += tmpwg.transpose();\n    }\n    //w->grad += p_grad.dot(x->data.transpose());\n\n\n    if (!noBias){\n        p_grad.dot_transpose_plus(i1, b->grad);\n    }\n    //b->grad += p_grad.dot(i1.transpose());\n}\n\n\n\nFunctionSparseLinear::FunctionSparseLinear() : Function() {\n    name = \"FunctionSparseLinear\";\n}\n\nFunctionSparseLinear::FunctionSparseLinear(Variable *w, Variable *b, float beta, float p, Variable *ph) : Function() {\n    name = \"FunctionSparseLinear\";\n    this->w  = w;\n    this->b = b;\n\n    this->beta = beta;\n    this->p = p;\n    this->ph = ph;\n}\n\nFunctionSparseLinear::FunctionSparseLinear(Variable *w, float beta, float p, Variable *ph) : Function() {\n    name = \"FunctionSparseLinear\";\n    noBias = true;\n    this->w  = w;\n\n    this->beta = beta;\n    this->p = p;\n    this->ph = ph;\n}\n\nvoid FunctionSparseLinear::toHostArray(){\n    i1.toHostArray();\n    w->data.toHostArray();\n    w->grad.toHostArray();\n    if (!noBias){\n        b->data.toHostArray();\n        b->grad.toHostArray();\n    }\n}\n\nvoid FunctionSparseLinear::fromHostArray(){\n    i1.fromHostArray();\n    w->data.fromHostArray();\n    w->grad.fromHostArray();\n    if (!noBias){\n        b->data.fromHostArray();\n        b->grad.fromHostArray();\n    }\n}\n\n\nPVariable FunctionSparseLinear::forward(vector<PVariable > &inputs, vector<PVariable > &outputs){\n\n    PVariable x = inputs.at(0);\n    PVariable r = PVariable(new Variable(this, w->data.rows, x->data.cols));\n\n    if (i1.cols == 0 || i1.cols != x->data.cols){\n        i1 = cuMat(1, x->data.cols);\n        i1.ones();\n    }\n\n    if (!noBias) b->data.dot(i1, r->data);\n    w->data.dot_plus(x->data, r->data);\n\n    outputs.push_back(r);\n\n    PVariable r2 = PVariable(new Variable(this, w->data.rows, x->data.cols));\n    r->data.relu(r2->data);\n    //r->data.sigmoid(r2->data);\n\n    return r2;\n}\n\nvoid FunctionSparseLinear::backward(cuMat &p_grad, vector<PVariable > &inputs, vector<PVariable > &outputs){\n\n\n    PVariable o = outputs.at(0);\n    cuMat sg = o->data.relu_d();\n    //cuMat sg = o->data.sigmoid_d();\n\n\n    PVariable x = inputs.at(0);\n\n    if (x->isGetGrad){\n        w->data.transpose_dot_plus(p_grad, x->grad);\n    }\n\n    // KL\n    cuMat ones(ph->data.rows, ph->data.cols);\n    ones.ones();\n    cuMat p_tmp(ph->data.rows, ph->data.cols);\n    p_tmp.ones();\n    p_tmp *= p;\n\n    cuMat kl = beta * (-1.0 * p_tmp / ph->data + (ones - p_tmp) / (ones - ph->data));\n\n    p_grad += kl;\n    p_grad *= sg;\n\n    p_grad.dot_transpose_plus(x->data, w->grad);\n\n    if (!noBias){\n        p_grad.dot_transpose_plus(i1, b->grad);\n    }\n\n\n}\n\n\n\nFunctionEmbed::FunctionEmbed() : Function() {\n    name = \"FunctionEmbed\";\n}\nFunctionEmbed::FunctionEmbed(int output_size, int input_size, bool no_bias){\n    name = \"FunctionEmbed\";\n\n    noBias = no_bias;\n\n    Variable w(output_size, input_size);\n    this->w = w;\n    this->w.randoms(0., sqrt((1./(float)input_size)));\n\n    if (!noBias){\n        Variable b(output_size, 1);\n        this->b = b;\n    }\n\n}\nPVariable FunctionEmbed::forward(vector<PVariable > &inputs, vector<PVariable > &outputs){\n\n    PVariable x = inputs.at(0);\n\n    int x_cols = 0;\n    if (!x->isSparse) x_cols = x->data.cols;\n    else x_cols = x->data_sparse.rows;\n\n    PVariable r = variable_construct_for_function(this, w.data.rows, x_cols);\n\n    outputs.push_back(r);\n\n\n    if (i1.cols == 0 || i1.cols != x_cols){\n        i1 = cuMat(1, x_cols);\n        i1.ones();\n    }\n\n    if (!noBias) b.data.dot(i1, r->data);\n\n    if (!x->isSparse){\n        w.data.dot_plus(x->data, r->data);\n    }\n    else{\n        if (wt.rows == 0) wt = cuMat(w.data.cols, w.data.rows);\n        w.data.transpose(wt);\n        if (rt.rows == 0) rt = cuMat(r->data.cols, r->data.rows);\n        x->data_sparse.s_d_dot(wt, rt);\n        if (rtmp.rows == 0) rtmp = cuMat(r->data.rows, r->data.cols);\n        rt.transpose(rtmp);\n        r->data.plus(rtmp, r->data);\n    }\n\n    return r;\n}\nvoid FunctionEmbed::backward(cuMat &p_grad, vector<PVariable > &inputs, vector<PVariable > &outputs){\n\n\n    PVariable x = inputs.at(0);\n\n    float batchSizeNorm = 1.0/((float)x->data.cols);\n\n    if (x->isGetGrad) w.data.transpose_dot_plus(p_grad, x->grad);\n\n    if (!x->isSparse){\n        p_grad.dot_transpose_plus(x->data, w.grad);\n    }\n    else{\n        cuMat xd = x->data_sparse.toDense();\n        p_grad.dot_plus(xd, w.grad);\n    }\n    w.grad.mul(batchSizeNorm, w.grad);\n\n    if (!noBias){\n        p_grad.dot_transpose_plus(i1, b.grad);\n        b.grad.mul(batchSizeNorm, b.grad);\n    }\n\n\n}\nvoid FunctionEmbed::toHostArray(){\n    i1.toHostArray();\n    w.data.toHostArray();\n    w.grad.toHostArray();\n    if (!noBias){\n        b.data.toHostArray();\n        b.grad.toHostArray();\n    }\n}\nvoid FunctionEmbed::fromHostArray(){\n    i1.fromHostArray();\n    w.data.fromHostArray();\n    w.grad.fromHostArray();\n    if (!noBias){\n        b.data.fromHostArray();\n        b.grad.fromHostArray();\n    }\n}\n\n\n\nFunctionReLU::FunctionReLU() : Function() {\n    name = \"FunctionReLU\";\n}\n\nPVariable FunctionReLU::forward(vector<PVariable > &inputs, vector<PVariable > &outputs){\n\n\n    PVariable x = inputs.at(0);\n\n    PVariable r = PVariable(new Variable(this, x->data.rows, x->data.cols));\n\n    x->data.relu(r->data);\n\n    return r;\n}\n\nvoid FunctionReLU::backward(cuMat &p_grad, vector<PVariable > &inputs, vector<PVariable > &outputs){\n\n    PVariable x = inputs.at(0);\n\n\n    if (rr.get() == NULL || rr->data.cols != x->data.cols){\n        rr = PVariable(new Variable(x->data.rows, x->data.cols));\n    }\n\n    x->data.relu_d(rr->data);\n\n    if (x->isGetGrad) rr->data.mul_plus(p_grad, x->grad, 1.0, 1.0);\n}\n\nFunctionPReLU::FunctionPReLU() : Function() {\n    name = \"FunctionPReLU\";\n}\nFunctionPReLU::FunctionPReLU(Variable *a) {\n    name = \"FunctionPReLU\";\n    this->a = a;\n}\n\nPVariable FunctionPReLU::forward(vector<PVariable > &inputs, vector<PVariable > &outputs){\n\n    PVariable x = inputs.at(0);\n\n    PVariable r = variable_construct_for_function(this, x->data.rows, x->data.cols);\n\n    outputs.push_back(r);\n\n    x->data.prelu(a->data, r->data);\n\n    return r;\n}\nvoid FunctionPReLU::backward(cuMat &p_grad, vector<PVariable > &inputs, vector<PVariable > &outputs){\n    PVariable x = inputs.at(0);\n\n\n    if (xd.get() == NULL || xd->data.cols != x->data.cols){\n        xd = PVariable(new Variable(x->data.rows, x->data.cols));\n        ad = PVariable(new Variable(x->data.rows, x->data.cols));\n    }\n\n    x->data.prelu_d(a->data, xd->data, ad->data);\n\n    ad->data.mul_plus(p_grad, a->grad, 1.0, 1.0);\n    if (x->isGetGrad) xd->data.mul_plus(p_grad, x->grad, 1.0, 1.0);\n\n}\n\n\nFunctionSigmoid::FunctionSigmoid() : Function() {\n    name = \"FunctionSigmoid\";\n}\nPVariable FunctionSigmoid::forward(vector<PVariable > &inputs, vector<PVariable > &outputs){\n\n    PVariable x = inputs.at(0);\n\n    PVariable r = variable_construct_for_function(this, x->data.rows, x->data.cols);\n\n\n    outputs.push_back(r);\n    x->data.sigmoid(r->data);\n\n    return r;\n}\nvoid FunctionSigmoid::backward(cuMat &p_grad, vector<PVariable > &inputs, vector<PVariable > &outputs){\n    PVariable x = inputs.at(0);\n\n\n    if (rr.get() == NULL || rr->data.cols != x->data.cols){\n        rr = PVariable(new Variable(x->data.rows, x->data.cols));\n    }\n    x->data.sigmoid_d(rr->data);\n\n    if (x->isGetGrad) rr->data.mul_plus(p_grad, x->grad, 1.0, 1.0);\n}\n\nFunctionTanh::FunctionTanh() : Function() {\n    name = \"FunctionTanh\";\n}\nPVariable FunctionTanh::forward(vector<PVariable > &inputs, vector<PVariable > &outputs){\n\n    PVariable x = inputs.at(0);\n\n    PVariable r = variable_construct_for_function(this, x->data.rows, x->data.cols);\n\n    outputs.push_back(r);\n\n    x->data.tanh(r->data);\n\n    return r;\n}\nvoid FunctionTanh::backward(cuMat &p_grad, vector<PVariable > &inputs, vector<PVariable > &outputs){\n    PVariable x = inputs.at(0);\n\n\n    if (rr.get() == NULL || rr->data.cols != x->data.cols){\n        rr = PVariable(new Variable(x->data.rows, x->data.cols));\n    }\n    x->data.tanh_d(rr->data);\n\n    if (x->isGetGrad) rr->data.mul_plus(p_grad, x->grad, 1.0, 1.0);\n}\n\nFunctionSoftmax::FunctionSoftmax() : Function() {\n    name = \"FunctionSoftmax\";\n}\nPVariable FunctionSoftmax::forward(vector<PVariable > &inputs, vector<PVariable > &outputs){\n\n    PVariable x = inputs.at(0);\n\n    PVariable r = PVariable(new Variable(x->data.rows, x->data.cols));\n\n    outputs.push_back(r);\n\n    x->data.softmax(r->data);\n\n    return r;\n}\n\nFunctionSoftmaxCrossEntropy::FunctionSoftmaxCrossEntropy() : Function() {\n    name = \"FunctionSoftmaxCrossEntropy\";\n    loss = cuMat(1,1);\n    loss.ones();\n\n}\nPVariable FunctionSoftmaxCrossEntropy::forward(vector<PVariable > &inputs, vector<PVariable > &outputs){\n\n    PVariable x = inputs.at(0);\n    PVariable t = inputs.at(1);\n\n    if (rr3.get() == NULL || rr3->data.cols != x->data.cols){\n        rr3 = PVariable(new Variable(x->data.rows, x->data.cols));\n    }\n\n    x->data.softmax(rr3->data);\n\n    if (rr.get() == NULL || rr->data.cols != rr3->data.cols){\n        rr = PVariable(new Variable(rr3->data));\n    }\n    else rr->data = rr3->data;\n\n    rr3->data.softmax_cross_entropy(t->data, rr3->data);\n    float sum = rr3->data.sum();\n\n    sum /= rr3->data.cols;\n\n    PVariable r = PVariable(new Variable(this, loss.rows, loss.cols));\n\n    outputs.push_back(r);\n\n    r->data = loss * sum;\n\n    return r;\n}\nvoid FunctionSoftmaxCrossEntropy::backward(cuMat &p_grad, vector<PVariable > &inputs, vector<PVariable > &outputs){\n\n    PVariable x = inputs.at(0);\n    PVariable t = inputs.at(1);\n    PVariable y = rr;\n\n    if (x->isGetGrad) x->grad += y->data - t->data;\n}\n\n\nFunctionMeanSquaredError::FunctionMeanSquaredError() : Function() {\n    name = \"FunctionMeanSquaredError\";\n    loss = cuMat(1,1);\n    loss.ones();\n}\n\nPVariable FunctionMeanSquaredError::forward(vector<PVariable > &inputs, vector<PVariable > &outputs){\n\n    PVariable x = inputs.at(0);\n    PVariable t = inputs.at(1);\n\n    if (rr.get() == NULL || rr->data.cols != x->data.cols){\n        rr = PVariable(new Variable(x->data));\n    }\n\n    x->data.minus(t->data, rr->data);\n\n    rr->data.mul(rr->data, rr->data);\n\n    float sum = rr->data.sum();\n    sum /= (2*rr->data.cols);\n\n    PVariable r = variable_construct_for_function(this, loss.rows, loss.cols);\n\n    outputs.push_back(r);\n\n    loss.mul(sum, r->data);\n\n    return r;\n}\nvoid FunctionMeanSquaredError::backward(cuMat &p_grad, vector<PVariable > &inputs, vector<PVariable > &outputs){\n    PVariable x = inputs.at(0);\n    PVariable t = inputs.at(1);\n\n    if (rr.get() == NULL || rr->data.cols != x->data.cols){\n\n        rr = PVariable(new Variable(x->data));\n    }\n\n    x->data.minus(t->data, rr->data);\n    float batch_size = rr->data.cols;\n    if (x->isGetGrad) x->grad.plus(rr->data, x->grad);\n}\n\n\n\nFunctionDropout::FunctionDropout(float p) : Function() {\n    name = \"FunctionDropout\";\n    this->p = p;\n}\nPVariable FunctionDropout::forward(vector<PVariable > &inputs, vector<PVariable > &outputs){\n\n    PVariable x = inputs.at(0);\n\n    PVariable r = PVariable(new Variable(this, x->data.rows, x->data.cols));\n\n    outputs.push_back(r);\n\n    if (rr.get() == NULL || rr->data.cols != x->data.cols){\n        rr = PVariable(new Variable(x->data.rows, x->data.cols));\n    }\n\n    x->data.dropout(r->data, rr->data, p);\n\n    return r;\n}\nvoid FunctionDropout::backward(cuMat &p_grad, vector<PVariable > &inputs, vector<PVariable > &outputs){\n    PVariable x = inputs.at(0);\n    PVariable idx = rr;\n\n    if (x->isGetGrad) idx->data.mul_plus(p_grad, x->grad, 1.0, 1.0);\n}\n\n\nFunctionIdentity::FunctionIdentity() : Function() {\n    name = \"FunctionIdentity\";\n}\n\nPVariable FunctionIdentity::forward(vector<PVariable> &inputs, vector<PVariable> &outputs){\n\n    PVariable x = inputs.at(0);\n\n    PVariable r = variable_construct_for_function(this, x->data.rows, x->data.cols);\n\n    r->data = x->data;\n\n    return r;\n}\n\nvoid FunctionIdentity::backward(cuMat &p_grad, vector<PVariable> &inputs, vector<PVariable> &outputs){\n    PVariable x = inputs.at(0);\n\n    if (x->isGetGrad) p_grad.mul_plus(1.0, x->grad);\n}\n\n\n\n// LSTM ----------------------------------\nFunctionLSTM::FunctionLSTM() : Function() {\n    name = \"FunctionLSTM\";\n}\n\nPVariable FunctionLSTM::forward(vector<PVariable> &inputs, vector<PVariable> &outputs){\n\n    PVariable x = inputs.at(0);\n    PVariable c = inputs.at(1);\n    PVariable c_next = inputs.at(2);\n\n    int offset = x->data.rows/4;\n\n    this->i = x->data.sliceRows(0, offset);\n    this->f = x->data.sliceRows(offset, offset);\n    this->g = x->data.sliceRows(offset*2, offset);\n    this->o = x->data.sliceRows(offset*3, offset);\n\n    cuMat _i = this->i;\n    cuMat _f = this->f;\n    cuMat _g = this->g;\n    cuMat _o = this->o;\n\n    this->i.sigmoid(_i);\n    this->f.sigmoid(_f);\n    this->g.tanh(_g);\n    this->o.sigmoid(_o);\n\n    c_next->data = _g * _i + _f * c->data;\n\n    cuMat tmp = c_next->data;\n    c_next->data.tanh(tmp);\n\n    PVariable r = variable_construct_for_function(this, x->data.rows, x->data.cols);\n\n\n    r->data = _o * tmp;\n\n    return r;\n}\n\n\nvoid FunctionLSTM::backward(cuMat &gh, vector<PVariable> &inputs, vector<PVariable> &outputs){\n\n    PVariable x = inputs.at(0);\n    PVariable c = inputs.at(1);\n    PVariable c_next = inputs.at(2);\n\n    int offset = x->data.rows/4;\n\n    cuMat co = c_next->data.tanh();\n\n    c->grad = gh * this->o * co.tanh_d() + c_next->grad;\n\n    cuMat gg = c->grad * this->i * this->g.tanh_d();\n\n    cuMat gi = c->grad * this->g * this->i.sigmoid_d();\n\n    cuMat gf = c->grad * c->data * this->f.sigmoid_d();\n\n    cuMat go = gh * co * this->o.sigmoid_d();\n\n    c->grad *= this->f;\n\n    cuMat tmp = x->grad;\n    tmp.joinRows(gi, 0, offset);\n    tmp.joinRows(gf, offset, offset);\n    tmp.joinRows(gg, offset*2, offset);\n    tmp.joinRows(go, offset*3, offset);\n    if (x->isGetGrad) x->grad += tmp;\n}\n\n\n//FullLSTM\nFunctionFullLSTM::FunctionFullLSTM(\n        Variable *f_c_w, Variable *f_h_w, Variable *f_x_w, Variable *f_x_b,\n        Variable *i_c_w, Variable *i_h_w, Variable *i_x_w, Variable *i_x_b,\n        Variable *o_c_w, Variable *o_h_w, Variable *o_x_w, Variable *o_x_b,\n        Variable *g_h_w, Variable *g_x_w, Variable *g_x_b) : Function(){\n\n    name = \"FunctionFullLSTM\";\n\n    this->f_c_w = f_c_w; this->f_h_w = f_h_w; this->f_x_w = f_x_w; this->f_x_b = f_x_b;\n    this->i_c_w = i_c_w; this->i_h_w = i_h_w; this->i_x_w = i_x_w; this->i_x_b = i_x_b;\n    this->o_c_w = o_c_w; this->o_h_w = o_h_w; this->o_x_w = o_x_w; this->o_x_b = o_x_b;\n    this->g_h_w = g_h_w; this->g_x_w = g_x_w; this->g_x_b = g_x_b;\n}\n\n\n\nPVariable FunctionFullLSTM::forward(vector<PVariable> &inputs, vector<PVariable> &outputs) {\n\n    PVariable x = inputs.at(0);\n    PVariable h = inputs.at(1);\n    PVariable c = inputs.at(2);\n    PVariable c_next = inputs.at(3);\n\n    cuMat ones(1, x->data.cols);\n    ones.ones();\n\n    f_hat = f_c_w->data.dot(c->data) + f_h_w->data.dot(h->data) + f_x_w->data.dot(x->data) + f_x_b->data.dot(ones);\n    f = f_hat.sigmoid();\n    i_hat = i_c_w->data.dot(c->data) + i_h_w->data.dot(h->data) + i_x_w->data.dot(x->data) + i_x_b->data.dot(ones);\n    i = i_hat.sigmoid();\n    g_hat = g_h_w->data.dot(h->data) + g_x_w->data.dot(x->data) + g_x_b->data.dot(ones);\n    g = g_hat.tanh();\n\n    c_next->data = c->data * f + i * g;\n\n    o_hat = o_c_w->data.dot(c_next->data) + o_h_w->data.dot(h->data) + o_x_w->data.dot(x->data) + o_x_b->data.dot(ones);\n    o = o_hat.sigmoid();\n\n    PVariable h_next = variable_construct_for_function(this, f_x_w->data.rows, x->data.cols);\n\n\n    h_next->data = c_next->data.tanh() * o;\n\n    return h_next;\n}\n\nvoid FunctionFullLSTM::backward(cuMat &delta_h, vector<PVariable> &inputs, vector<PVariable> &outputs) {\n\n    PVariable x = inputs.at(0);\n    PVariable h = inputs.at(1);\n    PVariable c = inputs.at(2);\n    PVariable c_next = inputs.at(3);\n    PVariable f_for_grad = inputs.at(4);\n    PVariable f_next_for_grad = inputs.at(5);\n    PVariable i_for_grad = inputs.at(6);\n    PVariable i_next_for_grad = inputs.at(7);\n    PVariable o_for_grad = inputs.at(8);\n    PVariable o_next_for_grad = inputs.at(9);\n    PVariable g_for_grad = inputs.at(10);\n    PVariable g_next_for_grad = inputs.at(11);\n\n    cuMat ones(1, x->data.cols);\n    ones.ones();\n\n    cuMat delta_o = delta_h *  c_next->data.tanh() * o_hat.sigmoid_d();\n    c_next->grad += delta_h * o * c_next->data.tanh_d() + o_c_w->data.transpose().dot(delta_o);\n\n    cuMat delta_i = c_next->grad * g * i_hat.sigmoid_d();\n    cuMat delta_f = c_next->grad * c->data * f_hat.sigmoid_d();\n    cuMat delta_g = c_next->grad * i * g_hat.tanh_d();\n\n\n    i_for_grad->grad = delta_i;\n    f_for_grad->grad = delta_f;\n    o_for_grad->grad = delta_o;\n    g_for_grad->grad = delta_g;\n\n\n    c->grad = c_next->grad * f + i_c_w->data.transpose().dot(delta_i) + f_c_w->data.transpose().dot(delta_f);\n\n\n    o_c_w->grad += delta_o.dot(c_next->grad.transpose());\n    i_c_w->grad += i_next_for_grad->grad.dot(c_next->grad.transpose());\n    f_c_w->grad += f_next_for_grad->grad.dot(c_next->grad.transpose());\n\n\n    x->grad += g_x_w->data.transpose().dot(delta_g)\n               + i_x_w->data.transpose().dot(delta_i)\n               + f_x_w->data.transpose().dot(delta_f)\n               + o_x_w->data.transpose().dot(delta_o);\n\n\n    h->grad += g_h_w->data.transpose().dot(delta_g)\n               + i_h_w->data.transpose().dot(delta_i)\n               + f_h_w->data.transpose().dot(delta_f)\n               + o_h_w->data.transpose().dot(delta_o);\n\n\n    g_x_w->grad += delta_g.dot(x->data.transpose());\n    g_h_w->grad += g_next_for_grad->grad.dot(h->data.transpose());\n    i_x_w->grad += delta_i.dot(x->data.transpose());\n    i_h_w->grad += i_next_for_grad->grad.dot(h->data.transpose());\n    f_x_w->grad += delta_f.dot(x->data.transpose());\n    f_h_w->grad += f_next_for_grad->grad.dot(h->data.transpose());\n    o_x_w->grad += delta_o.dot(x->data.transpose());\n    o_h_w->grad += o_next_for_grad->grad.dot(h->data.transpose());\n\n\n    g_x_b->grad += delta_g.dot(ones.transpose());\n    i_x_b->grad += delta_i.dot(ones.transpose());\n    f_x_b->grad += delta_f.dot(ones.transpose());\n    o_x_b->grad += delta_o.dot(ones.transpose());\n}\n\n\n\nFunctionGRU::FunctionGRU(Variable *w_r, Variable *u_r, Variable *b_r,\n                         Variable *w_z, Variable *u_z, Variable *b_z,\n                         Variable *w_g, Variable *u_g, Variable *b_g){\n    this->w_r = w_r;\n    this->u_r = u_r;\n    this->b_r = b_r;\n    this->w_z = w_z;\n    this->u_z = u_z;\n    this->b_z = b_z;\n    this->w_g = w_g;\n    this->u_g = u_g;\n    this->b_g = b_g;\n\n    name = \"FunctionGRU\";\n}\n\nPVariable FunctionGRU::forward(vector<PVariable> &inputs, vector<PVariable> &outputs) {\n    PVariable x = inputs[0];\n    PVariable h = inputs[1];\n\n    cuMat ones(w_z->data.rows, x->data.cols);\n    ones.ones();\n    cuMat ones_b(1, x->data.cols);\n    ones_b.ones();\n\n\n    r_hat = w_r->data.dot(h->data) + u_r->data.dot(x->data) + b_r->data.dot(ones_b);\n    r = r_hat.sigmoid();\n    z_hat = w_z->data.dot(h->data) + u_z->data.dot(x->data) + b_z->data.dot(ones_b);\n    z = z_hat.sigmoid();\n    g_hat = w_g->data.dot(h->data * r) + u_g->data.dot(x->data) + b_g->data.dot(ones_b);\n    g = g_hat.tanh();\n\n    PVariable h_new = variable_construct_for_function(this, w_r->data.rows, x->data.cols);\n\n\n    h_new->data = h->data * (ones - z) + z * g;\n\n    return h_new;\n}\n\nvoid FunctionGRU::backward(cuMat &delta_h, vector<PVariable> &inputs, vector<PVariable> &outputs) {\n    PVariable x = inputs[0];\n    PVariable h = inputs[1];\n\n    cuMat zeros(w_z->data.rows, x->data.cols);\n    //ones.ones();\n    cuMat ones_b(1, x->data.cols);\n    ones_b.ones();\n\n    cuMat delta4 = (zeros - z) * delta_h;\n    cuMat delta5 = delta_h * h->data;\n    cuMat delta6 = zeros - delta5;\n    cuMat delta7 = delta_h * g;\n    cuMat delta8 = delta_h * z;\n\n    cuMat delta9 = delta6 + delta7;\n\n    cuMat delta10 = delta8 * g_hat.tanh_d();\n    cuMat delta11 = delta9 * z_hat.sigmoid_d();\n\n\n    cuMat delta12 = u_g->data.transpose().dot(delta10);\n    cuMat delta13 = w_g->data.transpose().dot(delta10);\n    cuMat delta14 = u_z->data.transpose().dot(delta11);\n    cuMat delta15 = w_z->data.transpose().dot(delta11);\n\n    cuMat delta16 = delta13 * h->data;\n    cuMat delta17 = delta13 * r;\n    cuMat delta18 = delta16 * r_hat.sigmoid_d();\n    cuMat delta19 = delta17 + delta4;\n    cuMat delta20 = u_r->data.transpose().dot(delta18);\n    cuMat delta21 = w_r->data.transpose().dot(delta18);\n    cuMat delta22 = delta21 + delta15;\n    h->grad += delta19 + delta22;\n    x->grad += delta12 + delta14 + delta20;\n\n    w_r->grad += delta18.dot(h->data.transpose());\n    u_r->grad += delta18.dot(x->data.transpose());\n    w_z->grad += delta11.dot(h->data.transpose());\n    u_z->grad += delta11.dot(x->data.transpose());\n\n    w_g->grad += delta10.dot((h->data * r).transpose());\n    u_g->grad += delta10.dot(x->data.transpose());\n\n    b_r->grad += delta18.dot(ones_b.transpose());\n    b_z->grad += delta11.dot(ones_b.transpose());\n    b_g->grad += delta10.dot(ones_b.transpose());\n\n}\n\n\nFunctionBatchNorm::FunctionBatchNorm(int element_size, int channel_num, Variable *gamma, Variable *beta, Variable *x_mean, Variable *x_var) {\n    this->gamma = gamma;\n    this->beta = beta;\n\n    this->x_mean = x_mean;\n    this->x_var = x_var;\n\n    this->element_size = element_size;\n    this->channel_num = channel_num;\n\n    xhat.resize(channel_num);\n    rmu.resize(channel_num);\n    xmu.resize(channel_num);\n    ivar.resize(channel_num);\n    sqrtvar.resize(channel_num);\n    var.resize(channel_num);\n\n}\n\n\nPVariable FunctionBatchNorm::forward(vector<PVariable> &inputs, vector<PVariable> &outputs) {\n\n    PVariable x_org = inputs[0];\n\n    PVariable r = variable_construct_for_function(this, x_org->data.rows, x_org->data.cols);\n\n    for(int i=0; i<channel_num; i++) {\n\n        int idx = i*element_size;\n        cuMat x_data = x_org->data.sliceRows(idx, element_size);\n\n        int N = x_data.cols;\n        int D = x_data.rows;\n\n        cuMat ones(D, N);\n        ones.ones();\n\n\n        //step 1\n        if (is_train) rmu[i] = 1.0 / N * x_data.batch_sum();\n        else{\n            rmu[i] = cuMat(element_size, 1);\n            rmu[i].memSetDevice(this->x_mean->data.mDevice + idx);\n        }\n        cuMat mu = rmu[i].vec_to_mat(N);\n\n        //step 2\n        xmu[i] = x_data - mu;\n\n        //step 3\n        cuMat sq = xmu[i] * xmu[i];\n\n        //step 4\n        if (is_train) var[i] = 1.0 / N * sq.batch_sum();\n        else {\n            var[i] = cuMat(element_size, 1);\n            var[i].memSetDevice(x_var->data.mDevice + idx);\n            var[i] = ((float) N) / (((float) N) - 1.0) * var[i];\n        } //use unbiased variance\n\n        //step 5\n        sqrtvar[i] = var[i].sqrt();\n\n        //step 6\n        ivar[i] = sqrtvar[i].inverse();\n        cuMat tmp = ivar[i].vec_to_mat(N);\n\n        //step 7\n        xhat[i] = xmu[i] * tmp;\n\n        //step 8\n        cuMat gamma_tmp(element_size, 1);\n        gamma_tmp.memSetDevice(gamma->data.mDevice + idx);\n        cuMat gammax = xhat[i].mat_vec_mul(gamma_tmp, 0);\n\n        //step 9\n        cuMat beta_tmp(element_size, 1);\n        beta_tmp.memSetDevice(beta->data.mDevice + idx);\n        cuMat r_c = gammax + ones.mat_vec_mul(beta_tmp, 0);\n        r->data.joinRows(r_c, idx, element_size);\n\n    }\n\n    return r;\n}\n\nvoid FunctionBatchNorm::backward(cuMat &dout_org, vector<PVariable> &inputs, vector<PVariable> &outputs) {\n\n    PVariable x = inputs[0];\n\n    for(int i=0; i<channel_num; i++) {\n\n        int idx = i*element_size;\n        cuMat dout = dout_org.sliceRows(idx, element_size);\n\n        int N = dout.cols;\n        int D = dout.rows;\n\n\n        //step 9\n        beta->grad.memSetDeviceRow(dout.batch_sum().mDevice, i);\n        cuMat dgammax = dout;\n\n        //step 8\n        cuMat tmp = dgammax * xhat[i];\n        gamma->grad.memSetDeviceRow(tmp.batch_sum().mDevice, i);\n        cuMat gamma_tmp(element_size, 1);\n        gamma_tmp.memSetDevice(gamma->data.mDevice + idx);\n        cuMat dxhat = dgammax.mat_vec_mul(gamma_tmp, 0);\n\n        //step 7\n        tmp = dxhat * xmu[i];\n        cuMat divar = tmp.batch_sum();\n        cuMat dxmu1 = dxhat.mat_vec_mul(ivar[i], 0);\n\n        //step 6\n        //tmp = sqrtvar.inverse_d();\n        tmp = -1.0 * sqrtvar[i].inverse() * sqrtvar[i].inverse();\n        cuMat dsqrtvar = tmp * divar;\n\n        //step 5\n        cuMat dvar = var[i].sqrt_d() * dsqrtvar;\n\n        //step 4\n        cuMat dsq = 1.0 / N * dvar.vec_to_mat(N);\n\n        //step 3\n        cuMat dxmu2 = 2.0 * xmu[i] * dsq;\n\n        //step 2\n        cuMat dx1 = dxmu1 + dxmu2;\n        cuMat dmu = -1.0 * dx1.batch_sum();\n\n        //step 1\n        cuMat dx2 = 1.0 / N * dmu.vec_to_mat(N);\n\n        //step0\n        cuMat dx3 = dx1 + dx2;\n        x->grad.joinRows(dx3, idx, element_size);\n    }\n}\n\n\nFunctionConv2D::FunctionConv2D(Variable *w, Variable *b, int batch_num, int channel_num, int w_size, int h_size, int filter_size, int filter_num, int stride, int padding){\n\n    this->batch_num = batch_num;\n    this->channel_num = channel_num;\n    this->w_size = w_size;\n    this->h_size = h_size;\n    this->filter_size = filter_size;\n    this->filter_num = filter_num;\n    this->stride = stride;\n    this->padding = padding;\n\n    this->w = w;\n    this->b = b;\n\n    this->name = \"FunctionConv2D\";\n\n    /**\n    * Each dimension h and w of the output images is computed as followed:\n    * outputDim = 1 + (inputDim + 2*pad - filterDim)/convolutionStride\n    */\n    this->outputDim_w = 1 + (w_size + (padding+padding) - filter_size) / stride;\n    this->outputDim_h = 1 + (h_size + (padding+padding) - filter_size) / stride;\n\n    ones = new Variable(this->outputDim_w * this->outputDim_h, 1);\n    ones->ones();\n}\n\nFunctionConv2D::~FunctionConv2D(){\n    delete ones;\n}\n\ncuMat FunctionConv2D::forward_one(cuMat &data){\n\n    int output_dim_w, output_dim_h;\n\n    cuMat stacked = data.im2col(w_size, h_size, channel_num, filter_size, filter_size, stride, stride, padding, padding, padding, padding, output_dim_w, output_dim_h);\n\n    cols.push_back(stacked);\n\n    cuMat r = stacked.dot(w->data.transpose()) + ones->data.dot(b->data.transpose());\n\n    return r;\n}\n\n\ncuMat FunctionConv2D::backward_one(cuMat &col, cuMat &p_grad) {\n\n    cuMat p_grad_t = p_grad.transpose();\n\n    w->grad += p_grad_t.dot(col);\n\n    b->grad += p_grad_t.dot(ones->data);\n\n    cuMat dcol = p_grad.dot(w->data);\n\n    cuMat dx = dcol.col2im(w_size, h_size, channel_num, filter_size, filter_size, stride, stride, padding, padding, padding, padding);\n\n    return dx;\n}\n\n\n\nPVariable FunctionConv2D::forward(vector<PVariable> &inputs, vector<PVariable> &outputs){\n\n    PVariable x = inputs[0];\n\n    PVariable r = PVariable(new Variable(this, filter_num * outputDim_w * outputDim_h, batch_num));\n\n\n    for(int i=0; i<batch_num; i++) {\n        int data_index = i*(channel_num * w_size * h_size);\n        float *one_m = x->data.mDevice + data_index;\n        cuMat one_m_dev(w_size * h_size, channel_num);\n        one_m_dev.memSetDevice(one_m);\n        cuMat r_array = forward_one(one_m_dev);\n        r->data.memSetDeviceCol(r_array.mDevice, i);\n    }\n    return r;\n}\n\nvoid FunctionConv2D::backward(cuMat &p_grad, vector<PVariable> &inputs, vector<PVariable> &outputs) {\n\n    PVariable x = inputs[0];\n\n    cuMat dx(channel_num * w_size * h_size, batch_num);\n\n    for(int i=0; i<batch_num; i++) {\n\n        int data_index = i*(filter_num * outputDim_w * outputDim_h);\n\n        float *p_grad_one = p_grad.mDevice + data_index;\n\n        cuMat p_grad_one_dev(outputDim_w * outputDim_h, filter_num);\n        p_grad_one_dev.memSetDevice(p_grad_one);\n\n        cuMat r_array = backward_one(cols[i], p_grad_one_dev);\n\n        dx.memSetDeviceCol(r_array.mDevice, i);\n    }\n\n    x->grad += dx;\n}\n\n\nFunctionPooling::FunctionPooling(int width, int height, int depth, int windowWidth, int windowHeight, int stride, int padding){\n\n    name = \"FunctionPooling\";\n\n    this->width = width;\n    this->height = height;\n    this->depth = depth;\n    this->windowWidth = windowWidth;\n    this->windowHeight = windowHeight;\n    this->stride = stride;\n    this->padding = padding;\n}\n\nPVariable FunctionPooling::forward(vector<PVariable> &inputs, vector<PVariable> &outputs){\n    PVariable x = inputs[0];\n\n    int batch_num = x->data.cols;\n\n    //* Pooling size as followed:\n    //* outputDim = 1 + (inputDim + 2*padding - windowDim)/poolingStride;\n\n    int pooled_w = 1 + (width + (padding+padding) - windowWidth)/stride;\n    int pooled_h = 1 + (height + (padding+padding) - windowHeight)/stride;\n\n    PVariable r = PVariable(new Variable(this, depth * pooled_w * pooled_h, batch_num));\n\n    r->data = x->data.pooling(batch_num, width, height, depth, windowWidth, windowHeight, stride, stride, padding, padding, padding, padding);\n    return r;\n}\n\nvoid FunctionPooling::backward(cuMat &p_grad, vector<PVariable> &inputs, vector<PVariable> &outputs){\n\n    PVariable x = inputs[0];\n\n    int batch_num = x->data.cols;\n\n    int pooled_w = 1 + (width + (padding+padding) - windowWidth)/stride;\n    int pooled_h = 1 + (height + (padding+padding) - windowHeight)/stride;\n\n    x->grad = x->data.pooling_backward(batch_num, p_grad.mDevice, width, height, depth, windowWidth, windowHeight, stride, stride, padding, padding, padding, padding);\n}\n", "meta": {"hexsha": "60be453707277bd2a6212dec477c8a7ecbaeccd0", "size": 39941, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "core/function.cpp", "max_stars_repo_name": "YeonwooSung/DNN_Builder", "max_stars_repo_head_hexsha": "b009aaca55665f581276b024b570744db7f72358", "max_stars_repo_licenses": ["MIT"], "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/function.cpp", "max_issues_repo_name": "YeonwooSung/DNN_Builder", "max_issues_repo_head_hexsha": "b009aaca55665f581276b024b570744db7f72358", "max_issues_repo_licenses": ["MIT"], "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/function.cpp", "max_forks_repo_name": "YeonwooSung/DNN_Builder", "max_forks_repo_head_hexsha": "b009aaca55665f581276b024b570744db7f72358", "max_forks_repo_licenses": ["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.3636963696, "max_line_length": 171, "alphanum_fraction": 0.6255226459, "num_tokens": 11635, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6113819874558603, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.3460535369850473}}
{"text": "#include <iostream>\n#include <string>\n#include <algorithm>\n#include <vector>\n#include <chrono>\n#include <sys/stat.h>\n#include <sys/types.h>\n#include <dirent.h>\n#include <memory>\n\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n#include <opencv2/opencv.hpp>\n#include <opencv2/core/eigen.hpp>\n#include <yaml-cpp/yaml.h>\n#include <Open3D/Open3D.h>\n#include <glog/logging.h>\n\n#include \"teche_calibration.h\"\n#include \"FileSystemTools.h\"\n#include \"YamlFileIO.h\"\n#ifdef VISUALIZE_TRAJECTORY\n#include \"viewer.h\"\n#endif\n\n\n/**\n  * @brief save monocular camera pose in w2c form.\n  * @param folder_name is name of file folder.\n  * @param cam_id is the id of each camera.\n  * @param cam_pose is the camera pose in w2c.\n  * @return .\n  */\nbool saveCamPoseTxt(const std::string &filepath, const Eigen::Matrix4d &cam_pose)\n{\n    std::ofstream output_file(filepath);\n    if (!output_file.is_open())\n    {\n        LOG(FATAL) << \" Fail to open \" << filepath << \"\\n\";\n        return false;\n    }\n    LOG(INFO) << \" Write \" << filepath << \"\\n\";\n    for (size_t i = 0; i < 4; ++i)\n    {\n        for (size_t j = 0; j < 4; ++j)\n\n        {\n            if (j != 3)\n                output_file << cam_pose(i, j) << \", \";\n            else\n                output_file << cam_pose(i, j) << \"\\n\";\n        }\n    }\n    output_file.close();\n\n    return true;\n}\n\nstd::shared_ptr<open3d::geometry::PointCloud> convertPointClouds(const std::vector<Eigen::Vector3d> &v_pointclouds)\n{\n    assert(v_pointclouds.size());\n\n    int pts_num = v_pointclouds.size();\n    std::shared_ptr<open3d::geometry::PointCloud> pcl_ptr(new open3d::geometry::PointCloud);\n    for(int i = 0; i < pts_num; ++i)\n    {\n        pcl_ptr->points_.push_back(v_pointclouds[i]);\n    }\n\n    return pcl_ptr;\n}\n\nint main(int argc, char **argv)\n{\n    if (argc < 8)\n    {\n        std::cerr << \"Usage : test_techecalibrator [global_map.yaml] [cctag_result.yaml]\\n \\\n        [cam0_intrin_file] [cam1_intrin_file] [cam2_intrin_file] [cam3_intrin_file]\\n \\\n        [output_folder] \\n\";\n        return -1;\n    }\n    // start timer\n    // const auto tp_1 = std::chrono::steady_clock::now();\n\n    // save w2c camera pose\n    bool b_save_camera_pose_w_c = true;\n    // save c2r camera pose\n    bool b_save_camera_pose_c_r = true;\n\n    std::string gt_map_file_name(argv[1]);\n    std::string cctag_file_name(argv[2]);\n    std::string cam0_calibration_file_name(argv[3]);\n    std::string cam1_calibration_file_name(argv[4]);\n    std::string cam2_calibration_file_name(argv[5]);\n    std::string cam3_calibration_file_name(argv[6]);\n    std::string output_folder(argv[7]);\n\n    if (!common::fileExists(gt_map_file_name))\n    {\n        LOG(ERROR) << \" FIle \" << gt_map_file_name << \" doesnot exist!\";\n        return -1;\n    }\n    if (!common::pathExists(output_folder))\n    {\n        if (!common::createPath(output_folder))\n        {\n            LOG(ERROR) << \" Fail to create \" << output_folder;\n            return -1;\n        }\n    }\n\n    std::vector<std::string> v_intrinsic_fns = {cam0_calibration_file_name, cam1_calibration_file_name,\n                                                cam2_calibration_file_name, cam3_calibration_file_name};\n    std::vector<std::string> v_calib_img_paths;\n    std::vector<std::vector<cv::Point2d>> v_cctag_centers;\n    bool sts = common::loadCCTagResultFile(cctag_file_name, v_calib_img_paths, v_cctag_centers);\n    if (!sts)\n    {\n        LOG(ERROR) << \" Failed to parse \" << cctag_file_name;\n        return -1;\n    }\n\n    TecheCalibrator teche_calibrator(camera::model_type_t::Fisheye, target::target_type_t::CCTAG, v_intrinsic_fns, gt_map_file_name, 4);\n    sts = teche_calibrator.addCctagData(v_calib_img_paths, v_cctag_centers);\n    if (!sts)\n    {\n        LOG(ERROR) << \" Feail to add cctag data!\";\n        return -1;\n    }\n\n    sts = teche_calibrator.calibrate();\n    if (!sts)\n    {\n        LOG(ERROR) << \" Fail to calibrate teche 360 anywhere camera\";\n        return -1;\n    }\n    // const auto tp_2 = std::chrono::steady_clock::now();\n    // const auto calib_time = std::chrono::duration_cast<std::chrono::duration<double>>(tp_2 - tp_1).count();\n    // TIMER_STREAM(\"[test_techecalibrator] caliration time is \" << calib_time << \" s\");\n\n    std::vector<Eigen::Matrix4d> v_cam_poses_w2c = teche_calibrator.validCameraPoses();\n    // rotation axis 2 camera\n    std::vector<Eigen::Matrix4d> v_cam_poses_r2c = teche_calibrator.validCameraPosesInRotationAxisFrame();\n\n    // save camera pose and relative pose\n    for (size_t i = 0; i < v_cam_poses_w2c.size(); ++i)\n    {\n        if (b_save_camera_pose_w_c)\n        {\n            std::string txt_filepath = output_folder + \"/cam\" + std::to_string(i) + \"_w2c.txt\";\n            saveCamPoseTxt(txt_filepath, v_cam_poses_w2c[i]);\n        }\n        if (i == 0)\n            continue;\n\n        Eigen::Matrix4d T_cam0_cami = v_cam_poses_w2c[0].inverse() * v_cam_poses_w2c[i];\n        std::string yml_filepath = output_folder + \"/camera0\"+\"_to_camera\"+ std::to_string(i) +\".yml\";\n        common::saveExtFileOpencv(yml_filepath, T_cam0_cami);\n    }\n\n    // for (size_t i = 0; i < v_cam_poses_r2c.size(); ++i)\n    // {\n    //     if (b_save_camera_pose_c_r)\n    //     {\n    //         sts = writeCameraPosesInYml(output_folder, i, v_cam_poses_r2c[i]);\n    //         if (!sts)\n    //         {\n    //             ERROR_STREAM(\"[test_techecalibrator] Fail to write frame \" << i);\n    //             return -1;\n    //         }\n    //     }\n    // }\n\n#ifdef VISUALIZE_TRAJECTORY\n    Viewer viewer(v_visual_frames);\n    std::vector<Eigen::Vector3d> v_map_points = teche_calibrator.objectPoints();\n    // std::shared_ptr<open3d::geometry::PointCloud> targtboard_pcl_ptr = convertPointClouds(v_map_points);\n    // open3d::io::WritePointCloudToPLY(output_folder + \"/calibration_room.ply\", *targtboard_pcl_ptr, true);\n    viewer.setCurrentMapPoints(v_map_points);\n    viewer.run();\n#endif\n\n    return 0;\n}\n", "meta": {"hexsha": "6fc40e4053e4339bc5fb2fc0edce45d3321decee", "size": 5894, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/test_techecalibrator.cpp", "max_stars_repo_name": "alibaba/multiple-cameras-and-3D-LiDARs-extrinsic-calibration", "max_stars_repo_head_hexsha": "349bc8b954506721583b3571568fb8e23c2f1e83", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 47.0, "max_stars_repo_stars_event_min_datetime": "2021-09-06T02:25:28.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-17T12:03:13.000Z", "max_issues_repo_path": "test/test_techecalibrator.cpp", "max_issues_repo_name": "alibaba/multiple-cameras-and-3D-LiDARs-extrinsic-calibration", "max_issues_repo_head_hexsha": "349bc8b954506721583b3571568fb8e23c2f1e83", "max_issues_repo_licenses": ["MIT"], "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_techecalibrator.cpp", "max_forks_repo_name": "alibaba/multiple-cameras-and-3D-LiDARs-extrinsic-calibration", "max_forks_repo_head_hexsha": "349bc8b954506721583b3571568fb8e23c2f1e83", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 11.0, "max_forks_repo_forks_event_min_datetime": "2021-09-15T22:30:04.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-11T07:43:24.000Z", "avg_line_length": 31.8594594595, "max_line_length": 136, "alphanum_fraction": 0.6282660333, "num_tokens": 1652, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6113819732941511, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.34605352896925745}}
{"text": "// sdf: Triangle mesh to signed-distance function (SDF) library\n// Copyright Alex Yu 2020\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// 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#pragma once\n#ifndef SDF_SDF_F15B6437_01FD_4DBE_AB0D_BC1EE8ACC4C4\n#define SDF_SDF_F15B6437_01FD_4DBE_AB0D_BC1EE8ACC4C4\n\n#include <Eigen/Core>\n#include <cstdint>\n\n#include <memory>\n#include <vector>\n#ifdef __GNUC__\n#include <experimental/propagate_const>\n#endif\n#include <Eigen/Geometry>\n\nnamespace sdf {\n\nusing Index = uint32_t;\nusing Points = Eigen::Matrix<float, Eigen::Dynamic, 3, Eigen::RowMajor>;\nusing Points2D = Eigen::Matrix<float, Eigen::Dynamic, 2, Eigen::RowMajor>;\nusing Triangles = Eigen::Matrix<Index, Eigen::Dynamic, 3, Eigen::RowMajor>;\nusing Matrix =\n    Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>;\nusing Vector = Eigen::Matrix<float, Eigen::Dynamic, 1>;\n\nnamespace util {\n\ntemplate <class T>\n// 3D point to line shortest distance SQUARED\nT dist_point2line(\n    const Eigen::Ref<const Eigen::Matrix<T, 1, 3, Eigen::RowMajor>>& p,\n    const Eigen::Ref<const Eigen::Matrix<T, 1, 3, Eigen::RowMajor>>& a,\n    const Eigen::Ref<const Eigen::Matrix<T, 1, 3, Eigen::RowMajor>>& b) {\n    Eigen::Matrix<T, 1, 3> ap = p - a, ab = b - a;\n    return (ap - (ap.dot(ab) / ab.squaredNorm()) * ab).squaredNorm();\n}\n\n// 3D point to line segment shortest distance SQUARED\ntemplate <class T>\nT dist_point2lineseg(\n    const Eigen::Ref<const Eigen::Matrix<T, 1, 3, Eigen::RowMajor>>& p,\n    const Eigen::Ref<const Eigen::Matrix<T, 1, 3, Eigen::RowMajor>>& a,\n    const Eigen::Ref<const Eigen::Matrix<T, 1, 3, Eigen::RowMajor>>& b) {\n    Eigen::Matrix<T, 1, 3> ap = p - a, ab = b - a;\n    T t = ap.dot(ab) / ab.squaredNorm();\n    t = std::max(T(0.0), std::min(T(1.0), t));\n    return (ap - t * ab).squaredNorm();\n}\n\ntemplate <class T>\nconst Eigen::Matrix<T, 1, 3, Eigen::RowMajor> normal(\n    const Eigen::Ref<const Eigen::Matrix<T, 1, 3, Eigen::RowMajor>>& a,\n    const Eigen::Ref<const Eigen::Matrix<T, 1, 3, Eigen::RowMajor>>& b,\n    const Eigen::Ref<const Eigen::Matrix<T, 1, 3, Eigen::RowMajor>>& c) {\n    return (b - a).cross(c - a);\n}\n\ntemplate <class T>\n// Find barycentric coords of p in triangle (a,b,c) in 3D\n// (p does NOT have to be projected to plane beforehand)\n// normal, area_abc to be computed using util::normal,\n// where normal is normalized vector, area is magnitude\nEigen::Matrix<T, 1, 3, Eigen::RowMajor> bary(\n    const Eigen::Ref<const Eigen::Matrix<T, 1, 3, Eigen::RowMajor>>& p,\n    const Eigen::Ref<const Eigen::Matrix<T, 1, 3, Eigen::RowMajor>>& a,\n    const Eigen::Ref<const Eigen::Matrix<T, 1, 3, Eigen::RowMajor>>& b,\n    const Eigen::Ref<const Eigen::Matrix<T, 1, 3, Eigen::RowMajor>>& c,\n    const Eigen::Ref<const Eigen::Matrix<T, 1, 3, Eigen::RowMajor>>& normal,\n    float area_abc) {\n    float area_pbc = normal.dot((b - p).cross(c - p));\n    float area_pca = normal.dot((c - p).cross(a - p));\n\n    Eigen::Matrix<T, 1, 3> uvw;\n    uvw.x() = area_pbc / area_abc;\n    uvw.y() = area_pca / area_abc;\n    uvw.z() = T(1.0) - uvw.x() - uvw.y();\n\n    return uvw;\n}\n\ntemplate <class T>\n// 3D point to triangle shortest distance SQUARED\n// normal, area_abc to be computed using util::normal,\n// where normal is normalized vector, area is magnitude\nT dist_point2tri(\n    const Eigen::Ref<const Eigen::Matrix<T, 1, 3, Eigen::RowMajor>>& p,\n    const Eigen::Ref<const Eigen::Matrix<T, 1, 3, Eigen::RowMajor>>& a,\n    const Eigen::Ref<const Eigen::Matrix<T, 1, 3, Eigen::RowMajor>>& b,\n    const Eigen::Ref<const Eigen::Matrix<T, 1, 3, Eigen::RowMajor>>& c,\n    const Eigen::Ref<const Eigen::Matrix<T, 1, 3, Eigen::RowMajor>>& normal,\n    float area) {\n    const Eigen::Matrix<T, 1, 3> uvw = bary<T>(p, a, b, c, normal, area);\n    if (uvw[0] < 0) {\n        return dist_point2lineseg<T>(p, b, c);\n    } else if (uvw[1] < 0) {\n        return dist_point2lineseg<T>(p, a, c);\n    } else if (uvw[2] < 0) {\n        return dist_point2lineseg<T>(p, a, b);\n    } else {\n        return (uvw[0] * a + uvw[1] * b + uvw[2] * c - p).squaredNorm();\n    }\n}\n\ntemplate <class T>\nEigen::Matrix<T, 1, 3, Eigen::RowMajor> bary2d(\n    const Eigen::Ref<const Eigen::Matrix<T, 1, 2, Eigen::RowMajor>>& p,\n    const Eigen::Ref<const Eigen::Matrix<T, 1, 2, Eigen::RowMajor>>& a,\n    const Eigen::Ref<const Eigen::Matrix<T, 1, 2, Eigen::RowMajor>>& b,\n    const Eigen::Ref<const Eigen::Matrix<T, 1, 2, Eigen::RowMajor>>& c) {\n    Eigen::Matrix<T, 1, 2, Eigen::RowMajor> v0 = b - a, v1 = c - a, v2 = p - a;\n    Eigen::Matrix<T, 1, 3> result;\n    const float invden = 1.f / (v0.x() * v1.y() - v1.x() * v0.y());\n    result[1] = (v2.x() * v1.y() - v1.x() * v2.y()) * invden;\n    result[2] = (v0.x() * v2.y() - v2.x() * v0.y()) * invden;\n    result[0] = 1.0f - result.template tail<2>().sum();\n    return result;\n}\n}  // namespace util\n\n// Signed distance function utility for watertight meshes.\n//\n// Basic usage: SDF sdf(verts, faces); Vector sdf_vals = sdf(query_points);\n// Get nearest neighbor (verts) indices: sdf.nn(query_points);\n// Check containment (returns bool): sdf.contains(query_points);\nstruct SDF {\n    // Construct SDF instance from triangle mesh with given vertices and faces\n    // Note: Mesh is assumed to be watertight and all vertex positions are\n    // expected to be free of nans/infs\n    //\n    // Basic usage: SDF sdf(verts, faces); Vector sdf_vals = sdf(query_points);\n    // Get nearest neighbor (verts) indices: sdf.nn(query_points);\n    // Check containment (returns bool): sdf.contains(query_points);\n    //\n    // @param verts mesh vertices. If the contents of this matrix are modified,\n    // please call SDF::update() to update the internal representation.\n    // Else the results will be incorrect.\n    // @param faces mesh faces. The contents of this matrix should not be\n    // modified for the lifetime of this instance.\n    // @param robust whether to use robust mode. In robust mode,\n    // @param copy whether to make a copy of the data instead of referencing it\n    // SDF/containment computation is robust to mesh self-intersections and\n    // facewinding but is slower.\n    SDF(Eigen::Ref<const Points> verts, Eigen::Ref<const Triangles> faces,\n        bool robust = true, bool copy = false);\n    ~SDF();\n\n    /*** PRIMARY INTERFACE ***/\n    // Fast approximate signed-distance function.\n    // Points inside the mesh have positive sign and outside have negative sign.\n    //\n    // Method: computes minimum distance to a triangular face incident to\n    // the nearest vertex for each point.\n    //\n    // @param points input points\n    // @param trunc_aabb if true, returns -FLT_MAX for all points outside mesh's\n    // bounding box\n    // @return approx SDF values at input points\n    //\n    // WARNING: if robust=false (from constructor), this WILL FAIL if the mesh\n    // has self-intersections. In particular, the signs of points inside the\n    // mesh may be flipped.\n    Vector operator()(Eigen::Ref<const Points> points,\n                      bool trunc_aabb = false) const;\n\n    // Return exact nearest neighbor vertex index for each point (index as in\n    // input verts)\n    Eigen::VectorXi nn(Eigen::Ref<const Points> points) const;\n\n    // Return 1 for each point inside/on surface of the mesh and 0 for outside.\n    //\n    // @param points input points\n    // @return indicator of whether each point is in OR on surface of mesh\n    //\n    // WARNING: if robust=false (from constructor), this WILL FAIL if the mesh\n    // has self-intersections.\n    Eigen::Matrix<bool, Eigen::Dynamic, 1> contains(\n        Eigen::Ref<const Points> points) const;\n\n    // Call if vertex positions have been updated to rebuild the KD tree\n    // and update face normals+areas\n    void update();\n\n    /*** MISC UTILITIES ***/\n    // Sample 'num_points' points uniformly on surface, output (num_points, 3).\n    // Note: this takes O(num_points * log(num_faces)) time.\n    Points sample_surface(int num_points) const;\n\n    /*** DATA ACCESSORS ***/\n    // Get adjacent faces of point at verts[pointid]\n    const std::vector<int>& adj_faces(int pointid) const;\n\n    // Get total surface area of mesh\n    const float surface_area() const;\n\n    // Get vector of face areas, shape (num_faces)\n    const Vector& face_areas() const;\n\n    // Get matrix of face normals, shape (num_faces, 3).\n    // normal of face i (from faces passed to constructor) is in row i\n    const Points& face_normals() const;\n\n    // Get AABB of entire mesh, shape (6).\n    // (minx, miny, minz, maxx, maxy, maxz)\n    Eigen::Ref<const Eigen::Matrix<float, 6, 1>> aabb() const;\n\n    // Get faces\n    Eigen::Ref<const Triangles> faces() const;\n    Eigen::Ref<Triangles> faces_mutable();\n\n    // Get verts\n    Eigen::Ref<const Points> verts() const;\n    Eigen::Ref<Points> verts_mutable();\n\n    // Whether SDF is in robust mode\n    const bool robust;\n\n    // Whether we own data\n    const bool own_data;\n\n   private:\n    // Optional owned data\n    Points owned_verts;\n    Triangles owned_faces;\n\n    struct Impl;\n#ifdef __GNUC__\n    std::experimental::propagate_const<std::unique_ptr<Impl>> p_impl;\n#else\n    std::unique_ptr<Impl> p_impl;\n#endif\n};\n\n// Image-space raycast renderer utility for watertight meshes.\n//\n// Renders depth maps (render_depth), object mask (render_mask), and\n// vertex ids (render_nn)\n// using raycasting in image space. Also supports querying these for\n// arbitrary continuous points (x, y) in image space\n// (operator(), contains, nn).\n//\n// By image space we mean the space of (x,y,z)\n// where a pinhole camera perspective projection was applied to x,y.\n// This class is somehow similar to sdf::SDF but in\n// image space and only available on the image plane.\n//\n// NOTE: We assume no objects are present where z <= 0. This allows\n// us to use 2D data structures and skip a check.\n//\n// This is not a very efficient method.\n// If object has relatively few points compared to image size,\n// painter's algorithm (implemented in sxyu/avatar) probably performs better.\n//\n// Assumes camera is at origin facing +z, where up is -y and right is +x.\n// Note the coordinate system is right-handed.\nstruct Renderer {\n    // Construct software renderer\n    // @param verts mesh vertices. If the contents of this matrix are modified,\n    // please call Renderer::update() to update the internal representation.\n    // Else the results will be incorrect.\n    // @param faces mesh faces. The contents of this matrix should not be\n    // modified for the lifetime of this instance.\n    // @param width image width\n    // @param height image height\n    // @param fx focal length x\n    // @param fy focal length y\n    // @param cx principal point x\n    // @param cy principal point y\n    // @param copy whether to make a copy of the data instead of referencing it\n    // SDF/containment computation is robust to mesh self-intersections and\n    // facewinding but is slower.\n    Renderer(Eigen::Ref<const Points> verts, Eigen::Ref<const Triangles> faces,\n             int width = 1080, int height = 1080, float fx = 2600.f,\n             float fy = 2600.f, float cx = 540.f, float cy = 540.f,\n             bool copy = false);\n\n    // Destructor, pImpl pattern needs this\n    ~Renderer();\n\n    // *** PRIMARY INTERFACE ***\n    // Render (height, width) depth map of the mesh.\n    // @return Each pixel will be distance from z=0 plane and 0 if no object is\n    // present.\n    Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>\n    render_depth() const;\n\n    // Render (height, width) mask.\n    // @return Each pixel is 1 where object is present, 0 else.\n    Eigen::Matrix<bool, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>\n    render_mask() const;\n\n    // Render (height, width) vertex map, i.e. vertex id nearest to raycast hit\n    // at each pixel. Each pixel is -1 if empty space, index of vertex in verts\n    // else\n    // @param fill_outside if true, instead of returning -1 for empty space,\n    // finds nearest-neighbor vertex in 2d and uses its index\n    Eigen::Matrix<int, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>\n    render_nn(bool fill_outside = false) const;\n\n    // Compute depth at 2D points\n    // (render_depth for continuous points)\n    Vector operator()(Eigen::Ref<const Points2D> points) const;\n\n    // Compute mask at 2D points (1 means inside)\n    // (render_mask for continuous points)\n    Eigen::Matrix<bool, Eigen::Dynamic, 1> contains(\n        Eigen::Ref<const Points2D> points) const;\n\n    // Compute vertex id hit by raycast at 2D points\n    // (render_vertex for continuous points)\n    // @param fill_outside if true, instead of returning -1 for empty space,\n    // finds nearest-neighbor vertex in 2d and uses its index\n    Eigen::VectorXi nn(Eigen::Ref<const Points2D> points,\n                       bool fill_outside = false) const;\n\n    // Call if vertex positions have been updated to rebuild the KD tree\n    // and update face normals+areas\n    void update();\n\n    /*** DATA ACCESSORS ***/\n    // Get faces\n    Eigen::Ref<const Triangles> faces() const;\n    Eigen::Ref<Triangles> faces_mutable();\n\n    // Get verts\n    Eigen::Ref<const Points> verts() const;\n    Eigen::Ref<Points> verts_mutable();\n\n    // Whether we own data\n    const bool own_data;\n\n   private:\n    // Optional owned data\n    Points owned_verts;\n    Triangles owned_faces;\n\n    struct Impl;\n#ifdef __GNUC__\n    std::experimental::propagate_const<std::unique_ptr<Impl>> p_impl;\n#else\n    std::unique_ptr<Impl> p_impl;\n#endif\n};\n\n}  // namespace sdf\n\n#endif  // ifndef SDF_SDF_F15B6437_01FD_4DBE_AB0D_BC1EE8ACC4C4\n", "meta": {"hexsha": "00ef9c357f0ae3264af3d653c9abaea0c7f0a290", "size": 14766, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/sdf/sdf.hpp", "max_stars_repo_name": "ganthern/sdf", "max_stars_repo_head_hexsha": "9e69c9d8a2ce83513faaa1912e72b4aeadcf5fbd", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 47.0, "max_stars_repo_stars_event_min_datetime": "2020-12-10T09:34:27.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T08:26:26.000Z", "max_issues_repo_path": "include/sdf/sdf.hpp", "max_issues_repo_name": "ganthern/sdf", "max_issues_repo_head_hexsha": "9e69c9d8a2ce83513faaa1912e72b4aeadcf5fbd", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-02-11T15:07:38.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-17T06:23:05.000Z", "max_forks_repo_path": "include/sdf/sdf.hpp", "max_forks_repo_name": "ganthern/sdf", "max_forks_repo_head_hexsha": "9e69c9d8a2ce83513faaa1912e72b4aeadcf5fbd", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2020-12-03T02:32:11.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-21T21:12:31.000Z", "avg_line_length": 39.8005390836, "max_line_length": 80, "alphanum_fraction": 0.6741162129, "num_tokens": 3989, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6513548646660543, "lm_q2_score": 0.5312093733737563, "lm_q1q2_score": 0.34600580950320253}}
{"text": "/*\n *  Copyright (c) 2009, Rene Wagner\n *  All rights reserved.\n *\n *  Author: Rene Wagner <rw@nelianur.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\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 Rene Wagner nor the names of any\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 __UKFOM_LAPACK_INVERT_HPP__\n#define __UKFOM_LAPACK_INVERT_HPP__\n\n#include \"lapack.h\"\n\n#include <Eigen/Core>\n\nnamespace ukf {\nnamespace lapack {\n\n// import most common Eigen types \nUSING_PART_OF_NAMESPACE_EIGEN\n\ntemplate<size_t P>\nMatrix<double, P, P> invert(const Matrix<double, P, P> &m)\n{\n\tMatrix<double, P, P> tmp = m;\n\n\t/* first call DGETRF */\n\tint M = tmp.rows();\n\tint N = tmp.cols();\n\tint LDA = tmp.stride();\n\tint IPIV[M];\n\n\tint INFO;\n\n\tdgetrf_(&M, &N, tmp.data(), &LDA, IPIV, &INFO);\n\n\tif(INFO != 0)\n\t\tthrow \"dgetrf failed\";\n\n\t/* now call DGETRI */\n\tint LWORK = 64 * N; // FIXME: retrieve block size from ILAENV\n\tdouble WORK[LWORK];\n  \n\tdgetri_(&N, tmp.data(), &LDA, IPIV, WORK, &LWORK, &INFO);\n\n\tif(INFO != 0)\n\t\tthrow \"dgetri failed\";\n\n\treturn tmp;\n}\n\n} // namespace lapack\n} // namespace ukf\n\n#endif // __UKFOM_LAPACK_INVERT_HPP__\n", "meta": {"hexsha": "0ed1d34f14ee97ce183ffe45ebd1e855cb4f6a22", "size": 2499, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "examples/slam_and_orientation/ukfom/lapack/invert.hpp", "max_stars_repo_name": "mfkiwl/ADEKF", "max_stars_repo_head_hexsha": "178092b7585b0f311ed7889820704e74dab12bd1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 90.0, "max_stars_repo_stars_event_min_datetime": "2021-01-04T11:04:59.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-23T01:43:07.000Z", "max_issues_repo_path": "examples/slam_and_orientation/ukfom/lapack/invert.hpp", "max_issues_repo_name": "mfkiwl/ADEKF", "max_issues_repo_head_hexsha": "178092b7585b0f311ed7889820704e74dab12bd1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/slam_and_orientation/ukfom/lapack/invert.hpp", "max_forks_repo_name": "mfkiwl/ADEKF", "max_forks_repo_head_hexsha": "178092b7585b0f311ed7889820704e74dab12bd1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 11.0, "max_forks_repo_forks_event_min_datetime": "2021-04-26T09:18:07.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-23T01:43:10.000Z", "avg_line_length": 30.4756097561, "max_line_length": 72, "alphanum_fraction": 0.7182873149, "num_tokens": 626, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6513548646660543, "lm_q2_score": 0.5312093733737563, "lm_q1q2_score": 0.34600580950320253}}
{"text": "/*\n * Copyright (c) 2013, Christian Gehring, Hannes Sommer, Paul Furgale, Remo Diethelm\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *     * Redistributions of source code must retain the above copyright\n *       notice, this list of conditions and the following disclaimer.\n *     * Redistributions in binary form must reproduce the above copyright\n *       notice, this list of conditions and the following disclaimer in the\n *       documentation and/or other materials provided with the distribution.\n *     * Neither the name of the Autonomous Systems Lab, ETH Zurich nor the\n *       names of its contributors may be used to endorse or promote products\n *       derived from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL Christian Gehring, Hannes Sommer, Paul Furgale,\n * Remo Diethelm BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,\n * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE\n * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n*/\n\n#ifndef KINDR_ROTATIONS_EIGEN_ROTATIONQUATERNION_HPP_\n#define KINDR_ROTATIONS_EIGEN_ROTATIONQUATERNION_HPP_\n\n#include <cmath>\n\n#include <Eigen/Geometry>\n\n#include \"kindr/common/common.hpp\"\n#include \"kindr/common/assert_macros_eigen.hpp\"\n#include \"kindr/quaternions/QuaternionEigen.hpp\"\n#include \"kindr/rotations/RotationBase.hpp\"\n#include \"kindr/rotations/eigen/RotationEigenFunctions.hpp\"\n\nnamespace kindr {\nnamespace rotations {\nnamespace eigen_impl {\n\n\n\n/*!  \\class RotationQuaternion\n *  \\brief Implementation of quaternion rotation based on Eigen::Quaternion\n *\n *  The following four typedefs are provided for convenience:\n *   - \\ref eigen_impl::RotationQuaternionAD \"RotationQuaternionAD\" for active rotation and primitive type double\n *   - \\ref eigen_impl::RotationQuaternionAF \"RotationQuaternionAF\" for active rotation and primitive type float\n *   - \\ref eigen_impl::RotationQuaternionPD \"RotationQuaternionPD\" for passive rotation and primitive type double\n *   - \\ref eigen_impl::RotationQuaternionPF \"RotationQuaternionPF\" for passive rotation and primitive type float\n *\n *  \\tparam PrimType_ the primitive type of the data (double or float)\n *  \\tparam Usage_ the rotation usage which is either active or passive\n *\n *  \\ingroup rotations\n */\ntemplate<typename PrimType_, enum RotationUsage Usage_>\nclass RotationQuaternion : public RotationQuaternionBase<RotationQuaternion<PrimType_, Usage_>, Usage_> {\n private:\n  /*! \\brief The base type.\n   */\n  typedef quaternions::eigen_impl::UnitQuaternion<PrimType_> Base;\n\n  /*! \\brief The data container\n   */\n  Base rotationQuaternion_;\n public:\n  /*! \\brief The implementation type.\n   *  The implementation type is always an Eigen object.\n   */\n  typedef typename Base::Implementation Implementation;\n\n  /*! \\brief The primitive type.\n   *  Float/Double\n   */\n  typedef PrimType_ Scalar;\n\n  //! the imaginary type, i.e., Eigen::Quaternion<>\n  typedef Eigen::Matrix<PrimType_,3,1> Imaginary;\n\n  //! quaternion as 4x1 matrix: [w; x; y; z]\n  typedef Eigen::Matrix<PrimType_,4,1> Vector4;\n\n  /*! \\brief Default constructor using identity rotation.\n   */\n  RotationQuaternion()\n    : rotationQuaternion_(Implementation::Identity()) {\n  }\n\n  /*! \\brief Constructor using four scalars.\n   *  In debug mode, an assertion is thrown if the quaternion has not unit length.\n   *  \\param w     first entry of the quaternion = cos(phi/2)\n   *  \\param x     second entry of the quaternion = n1*sin(phi/2)\n   *  \\param y     third entry of the quaternion = n2*sin(phi/2)\n   *  \\param z     fourth entry of the quaternion = n3*sin(phi/2)\n   */\n  RotationQuaternion(Scalar w, Scalar x, Scalar y, Scalar z)\n    : rotationQuaternion_(w,x,y,z) {\n    KINDR_ASSERT_SCALAR_NEAR_DBG(std::runtime_error, rotationQuaternion_.norm(), static_cast<Scalar>(1), static_cast<Scalar>(1e-4), \"Input quaternion has not unit length.\");\n  }\n\n  /*! \\brief Constructor using real and imaginary part.\n   *  In debug mode, an assertion is thrown if the quaternion has not unit length.\n   *  \\param real   real part (PrimType_)\n   *  \\param imag   imaginary part (Eigen::Matrix<PrimType_,3,1>)\n   */\n  RotationQuaternion(Scalar real, const Imaginary& imag)\n    : rotationQuaternion_(real,imag(0),imag(1),imag(2)) {\n    KINDR_ASSERT_SCALAR_NEAR_DBG(std::runtime_error, rotationQuaternion_.norm(), static_cast<Scalar>(1), static_cast<Scalar>(1e-4), \"Input quaternion has not unit length.\");\n  }\n\n  /*! \\brief Constructor using Eigen::Matrix<PrimType_,4,1>.\n   *  In debug mode, an assertion is thrown if the quaternion has not unit length.\n   *  \\param other   Eigen::Matrix<PrimType_,4,1>\n   */\n  RotationQuaternion(const Vector4 & vec)\n    : rotationQuaternion_(vec(0),vec(1),vec(2),vec(3)) {\n    KINDR_ASSERT_SCALAR_NEAR_DBG(std::runtime_error, rotationQuaternion_.norm(), static_cast<Scalar>(1), 1e-4, \"Input quaternion has not unit length.\");\n  }\n\n  /*! \\brief Constructor using Eigen::Quaternion<PrimType_>.\n   *  In debug mode, an assertion is thrown if the quaternion has not unit length.\n   *  \\param other   Eigen::Quaternion<PrimType_>\n   */\n  explicit RotationQuaternion(const Implementation& other)\n    : rotationQuaternion_(other.w(), other.x(), other.y(), other.z()) {\n    KINDR_ASSERT_SCALAR_NEAR_DBG(std::runtime_error, rotationQuaternion_.norm(), static_cast<Scalar>(1), 1e-4, \"Input quaternion has not unit length.\");\n  }\n\n  /*! \\brief Constructor using quaternions::UnitQuaternion.\n   *  In debug mode, an assertion is thrown if the quaternion has not unit length.\n   *  \\param other   quaternions::UnitQuaternion\n   */\n  explicit RotationQuaternion(const Base& other)\n    : rotationQuaternion_(other.w(), other.x(), other.y(), other.z()) {\n    KINDR_ASSERT_SCALAR_NEAR_DBG(std::runtime_error, rotationQuaternion_.norm(), static_cast<Scalar>(1), 1e-4, \"Input quaternion has not unit length.\");\n  }\n\n  /*! \\brief Constructor using another rotation.\n   *  \\param other   other rotation\n   */\n  template<typename OtherDerived_>\n  inline explicit RotationQuaternion(const RotationBase<OtherDerived_, Usage_>& other)\n    : rotationQuaternion_(internal::ConversionTraits<RotationQuaternion, OtherDerived_>::convert(other.derived()).toImplementation()) {\n  }\n\n  inline Scalar w() const {\n    return rotationQuaternion_.w();\n  }\n\n  inline Scalar x() const {\n    return rotationQuaternion_.x();\n  }\n\n  inline Scalar y() const {\n    return rotationQuaternion_.y();\n  }\n\n  inline Scalar z() const {\n    return rotationQuaternion_.z();\n  }\n\n\n  inline Scalar real() const {\n    return this->toUnitQuaternion().real();\n  }\n\n  inline Imaginary imaginary() const {\n    return this->toUnitQuaternion().imaginary();\n  }\n\n  inline Vector4 vector() const {\n    Vector4 vector4;\n    vector4 << w(), x(), y(), z();\n    return vector4;\n  }\n\n  inline void setValues(Scalar w, Scalar x, Scalar y, Scalar z) {\n    rotationQuaternion_.w() = w;\n    rotationQuaternion_.x() = x;\n    rotationQuaternion_.y() = y;\n    rotationQuaternion_.z() = z;\n  }\n\n  inline void setParts(Scalar real, const Imaginary& imag) {\n    rotationQuaternion_.w() = real;\n    rotationQuaternion_.x() = imag(0);\n    rotationQuaternion_.y() = imag(1);\n    rotationQuaternion_.z() = imag(2);\n  }\n\n  /*! \\brief Cast to the implementation type.\n   *  \\returns the implementation for direct manipulation (recommended only for advanced users)\n   */\n  inline Implementation& toImplementation() {\n    return toUnitQuaternion().toImplementation();\n  }\n\n  /*! \\brief Cast to the implementation type.\n   *  \\returns the implementation for direct manipulation (recommended only for advanced users)\n   */\n  inline const Implementation& toImplementation() const {\n    return toUnitQuaternion().toImplementation();\n  }\n\n//  Implementation toImplementation() const {\n//    return Implementation(this->w(),this->x(),this->y(),this->z());\n//  }\n\n  Base& toUnitQuaternion() {\n     return static_cast<Base&>(rotationQuaternion_);\n   }\n\n  const Base& toUnitQuaternion() const {\n     return static_cast<const Base&>(rotationQuaternion_);\n   }\n\n  /*! \\brief Assignment operator using a UnitQuaternion.\n   *  \\param quat   UnitQuaternion\n   *  \\returns reference\n   */\n  template<typename PrimTypeIn_>\n  RotationQuaternion& operator =(const quaternions::eigen_impl::UnitQuaternion<PrimTypeIn_>& quat) {\n    this->toImplementation() = Implementation(quat.w(),quat.x(),quat.y(),quat.z());\n    return *this;\n  }\n\n  /*! \\brief Assignment operator using another rotation.\n   *  \\param other   other rotation\n   *  \\returns reference\n   */\n  template<typename OtherDerived_>\n  RotationQuaternion& operator =(const RotationBase<OtherDerived_, Usage_>& other) {\n    this->toImplementation() = internal::ConversionTraits<RotationQuaternion, OtherDerived_>::convert(other.derived()).toImplementation();\n    return *this;\n  }\n\n  /*! \\brief Assignment operator using another rotation.\n   *  \\param other   other rotation\n   *  \\returns reference\n   */\n  template<typename PrimTypeIn_>\n  RotationQuaternion& operator =(const RotationQuaternion<PrimTypeIn_, Usage_>& other) {\n    this->toImplementation() = other.toImplementation().template cast<PrimType_>();\n    return *this;\n  }\n\n  /*! \\brief Bracket operator which assigns a UnitQuaternion to the RotationQuaternion.\n   *  \\param quat   UnitQuaternion\n   *  \\returns reference\n   */\n  template<typename PrimTypeIn_>\n  RotationQuaternion& operator ()(const quaternions::eigen_impl::UnitQuaternion<PrimTypeIn_>& quat) {\n    this->toImplementation() = Implementation(quat.w(),quat.x(),quat.y(),quat.z());\n    return *this;\n  }\n\n  /*! \\brief Bracket operator which assigns a Quaternion to the RotationQuaternion.\n   *  In debug mode, an assertion is thrown if the quaternion has not unit length.\n   *  \\param quat   Quaternion\n   *  \\returns reference\n   */\n  template<typename PrimTypeIn_>\n  RotationQuaternion& operator ()(const quaternions::eigen_impl::Quaternion<PrimTypeIn_>& quat) {\n    this->toImplementation() = Implementation(quat.w(),quat.x(),quat.y(),quat.z());\n    KINDR_ASSERT_SCALAR_NEAR_DBG(std::runtime_error, norm(), static_cast<Scalar>(1), static_cast<Scalar>(1e-4), \"Input quaternion has not unit length.\");\n    return *this;\n  }\n\n  /*! \\brief Parenthesis operator to convert from another rotation.\n   *  \\param other   other rotation\n   *  \\returns reference\n   */\n  template<typename OtherDerived_>\n  RotationQuaternion& operator ()(const RotationBase<OtherDerived_, Usage_>& other) {\n    this->toImplementation() = internal::ConversionTraits<RotationQuaternion, OtherDerived_>::convert(other.derived()).toImplementation();\n    return *this;\n  }\n\n  /*! \\brief Returns the inverse of the rotation.\n   *  \\returns the inverse of the rotation\n   */\n  RotationQuaternion inverted() const {\n    return RotationQuaternion(this->toUnitQuaternion().inverted());\n  }\n\n  /*! \\brief Inverts the rotation.\n   *  \\returns reference\n   */\n  RotationQuaternion& invert() {\n    *this = inverted();\n    return *this;\n  }\n\n  /*! \\brief Returns the conjugated of the quaternion.\n   *  \\returns conjugated of the quaternion\n   */\n  RotationQuaternion conjugated() const {\n    return RotationQuaternion(this->toUnitQuaternion().conjugated());\n  }\n\n  /*! \\brief Conjugates of the quaternion.\n   *  \\returns reference\n   */\n  RotationQuaternion& conjugate() {\n    *this = conjugated();\n    return *this;\n  }\n\n  /*! \\brief Sets the rotation to identity.\n   *  \\returns reference\n   */\n  RotationQuaternion& setIdentity() {\n    rotationQuaternion_.w() = static_cast<Scalar>(1);\n    rotationQuaternion_.x() = static_cast<Scalar>(0);\n    rotationQuaternion_.y() = static_cast<Scalar>(0);\n    rotationQuaternion_.z() = static_cast<Scalar>(0);\n    return *this;\n  }\n\n  /*! \\brief Returns a unique quaternion rotation with w > 0.\n   *  This function is used to compare different rotations.\n   *  \\returns copy of the quaternion rotation which is unique\n   */\n  RotationQuaternion getUnique() const {\n    if(this->w() > 0) {\n      return *this;\n    } else if (this->w() < 0){\n      return RotationQuaternion(-this->w(),-this->x(),-this->y(),-this->z());\n    } else { // w == 0\n\n      if(this->x() > 0) {\n        return *this;\n      } else if (this->x() < 0){\n        return RotationQuaternion(-this->w(),-this->x(),-this->y(),-this->z());\n      } else { // x == 0\n\n        if(this->y() > 0) {\n          return *this;\n        } else if (this->y() < 0){\n          return RotationQuaternion(-this->w(),-this->x(),-this->y(),-this->z());\n        } else { // y == 0\n\n          if(this->z() > 0) { // z must be either -1 or 1 in this case\n            return *this;\n          } else {\n            return RotationQuaternion(-this->w(),-this->x(),-this->y(),-this->z());\n          }\n        }\n      }\n    }\n  }\n\n  /*! \\brief Returns the quaternion matrix Qleft: q*p = Qleft(q)*p\n   *  This function can be used to get the derivative of the concatenation with respect to the right quaternion.\n   *  \\returns the quaternion matrix Qleft\n   */\n  Eigen::Matrix<PrimType_,4,4> getQuaternionMatrix() {\n    Eigen::Matrix<PrimType_,4,4> Qleft;\n    if(Usage_ == rotations::RotationUsage::ACTIVE)\n    {\n      Qleft(0,0) =  w();      Qleft(0,1) = -x();      Qleft(0,2) = -y();      Qleft(0,3) = -z();\n      Qleft(1,0) =  x();      Qleft(1,1) =  w();      Qleft(1,2) = -z();      Qleft(1,3) =  y();\n      Qleft(2,0) =  y();      Qleft(2,1) =  z();      Qleft(2,2) =  w();      Qleft(2,3) = -x();\n      Qleft(3,0) =  z();      Qleft(3,1) = -y();      Qleft(3,2) =  x();      Qleft(3,3) =  w();\n    }\n    if(Usage_ == rotations::RotationUsage::PASSIVE)\n    {\n      Qleft(0,0) =  w();      Qleft(0,1) = -x();      Qleft(0,2) = -y();      Qleft(0,3) = -z();\n      Qleft(1,0) =  x();      Qleft(1,1) =  w();      Qleft(1,2) =  z();      Qleft(1,3) = -y();\n      Qleft(2,0) =  y();      Qleft(2,1) = -z();      Qleft(2,2) =  w();      Qleft(2,3) =  x();\n      Qleft(3,0) =  z();      Qleft(3,1) =  y();      Qleft(3,2) = -x();      Qleft(3,3) =  w();\n    }\n    return Qleft;\n  }\n\n  /*! \\brief Returns the quaternion matrix Qright: q*p = Qright(p)*q\n   *  This function can be used to get the derivative of the concatenation with respect to the left quaternion.\n   *  \\returns the quaternion matrix Qright\n   */\n  Eigen::Matrix<PrimType_,4,4> getConjugateQuaternionMatrix() {\n    Eigen::Matrix<PrimType_,4,4> Qright;\n    if(Usage_ == rotations::RotationUsage::ACTIVE)\n    {\n      Qright(0,0) =  w();      Qright(0,1) = -x();      Qright(0,2) = -y();      Qright(0,3) = -z();\n      Qright(1,0) =  x();      Qright(1,1) =  w();      Qright(1,2) =  z();      Qright(1,3) = -y();\n      Qright(2,0) =  y();      Qright(2,1) = -z();      Qright(2,2) =  w();      Qright(2,3) =  x();\n      Qright(3,0) =  z();      Qright(3,1) =  y();      Qright(3,2) = -x();      Qright(3,3) =  w();\n    }\n    if(Usage_ == rotations::RotationUsage::PASSIVE)\n    {\n      Qright(0,0) =  w();      Qright(0,1) = -x();      Qright(0,2) = -y();      Qright(0,3) = -z();\n      Qright(1,0) =  x();      Qright(1,1) =  w();      Qright(1,2) = -z();      Qright(1,3) =  y();\n      Qright(2,0) =  y();      Qright(2,1) =  z();      Qright(2,2) =  w();      Qright(2,3) = -x();\n      Qright(3,0) =  z();      Qright(3,1) = -y();      Qright(3,2) =  x();      Qright(3,3) =  w();\n    }\n    return Qright;\n  }\n\n  /*! \\brief Returns the global quaternion diff matrix H: GlobalAngularVelocity = 2*H*qdiff, qdiff = 0.5*H^T*GlobalAngularVelocity\n   *  \\returns the global quaternion diff matrix H\n   */\n  Eigen::Matrix<PrimType_,3,4> getGlobalQuaternionDiffMatrix() {\n    Eigen::Matrix<PrimType_,3,4> H;\n    if(Usage_ == rotations::RotationUsage::ACTIVE) // x, y, z * -1\n    {\n      H(0,0) =  -x();      H(0,1) =  w();      H(0,2) =  z();      H(0,3) = -y();\n      H(1,0) =  -y();      H(1,1) = -z();      H(1,2) =  w();      H(1,3) =  x();\n      H(2,0) =  -z();      H(2,1) =  y();      H(2,2) = -x();      H(2,3) =  w();\n    }\n    if(Usage_ == rotations::RotationUsage::PASSIVE)\n    {\n      H(0,0) = -x();      H(0,1) =  w();      H(0,2) = -z();      H(0,3) =  y();\n      H(1,0) = -y();      H(1,1) =  z();      H(1,2) =  w();      H(1,3) = -x();\n      H(2,0) = -z();      H(2,1) = -y();      H(2,2) =  x();      H(2,3) =  w();\n    }\n    return H;\n  }\n\n  /*! \\brief Returns the local quaternion diff matrix HBar: LocalAngularVelocity = 2*HBar*qdiff, qdiff = 0.5*HBar^T*LocalAngularVelocity\n   *  \\returns the local quaternion diff matrix HBar\n   */\n  Eigen::Matrix<PrimType_,3,4> getLocalQuaternionDiffMatrix() const {\n    Eigen::Matrix<PrimType_,3,4> HBar;\n    if(Usage_ == rotations::RotationUsage::ACTIVE) // x, y, z * -1\n    {\n      HBar(0,0) =  -x();      HBar(0,1) =  w();      HBar(0,2) = -z();      HBar(0,3) =  y();\n      HBar(1,0) =  -y();      HBar(1,1) =  z();      HBar(1,2) =  w();      HBar(1,3) = -x();\n      HBar(2,0) =  -z();      HBar(2,1) = -y();      HBar(2,2) =  x();      HBar(2,3) =  w();\n    }\n    if(Usage_ == rotations::RotationUsage::PASSIVE)\n    {\n      HBar(0,0) = -x();      HBar(0,1) =  w();      HBar(0,2) =  z();      HBar(0,3) = -y();\n      HBar(1,0) = -y();      HBar(1,1) = -z();      HBar(1,2) =  w();      HBar(1,3) =  x();\n      HBar(2,0) = -z();      HBar(2,1) =  y();      HBar(2,2) = -x();      HBar(2,3) =  w();\n    }\n    return HBar;\n  }\n\n  /*! \\brief Modifies the quaternion rotation such that w >= 0.\n   *  \\returns reference\n   */\n  RotationQuaternion& setUnique() {\n    *this = getUnique();\n    return *this;\n  }\n\n  /*! \\brief Returns the norm of the quaternion.\n   *  The RotationQuaternion should always have unit length.\n   *  \\returns norm of the quaternion\n   */\n  Scalar norm() {\n    return rotationQuaternion_.norm();\n  }\n\n  /*! \\brief Concenation operator.\n   *  This is explicitly specified, because QuaternionBase provides also an operator*.\n   *  \\returns the concenation of two rotations\n   */\n  using RotationQuaternionBase<RotationQuaternion<PrimType_, Usage_>, Usage_> ::operator*;\n\n  /*! \\brief Equivalence operator.\n   *  This is explicitly specified, because QuaternionBase provides also an operator==.\n   *  \\returns true if two rotations are similar.\n   */\n  using RotationQuaternionBase<RotationQuaternion<PrimType_, Usage_>, Usage_> ::operator==;\n\n\n  /*! \\brief Used for printing the object with std::cout.\n   *  \\returns std::stream object\n   */\n  friend std::ostream& operator << (std::ostream& out, const RotationQuaternion& rquat) {\n    out << rquat.toUnitQuaternion();\n    return out;\n  }\n};\n\n//! \\brief Active quaternion rotation with double primitive type\ntypedef RotationQuaternion<double, RotationUsage::ACTIVE>  RotationQuaternionAD;\n//! \\brief Active quaternion rotation with float primitive type\ntypedef RotationQuaternion<float,  RotationUsage::ACTIVE>  RotationQuaternionAF;\n//! \\brief Passive quaternion rotation with double primitive type\ntypedef RotationQuaternion<double, RotationUsage::PASSIVE> RotationQuaternionPD;\n//! \\brief Passive quaternion rotation with float primitive type\ntypedef RotationQuaternion<float,  RotationUsage::PASSIVE> RotationQuaternionPF;\n\n\n\n\n\n\n} // namespace eigen_impl\n\n\nnamespace internal {\n\ntemplate<typename PrimType_, enum RotationUsage Usage_>\nclass get_scalar<eigen_impl::RotationQuaternion<PrimType_, Usage_>> {\n public:\n  typedef PrimType_ Scalar;\n};\n\ntemplate<typename PrimType_, enum RotationUsage Usage_>\nclass get_matrix3X<eigen_impl::RotationQuaternion<PrimType_, Usage_>>{\n public:\n  typedef int IndexType;\n\n  template <IndexType Cols>\n  using Matrix3X = Eigen::Matrix<PrimType_, 3, Cols>;\n};\n\ntemplate<typename PrimType_>\nclass get_other_usage<eigen_impl::RotationQuaternion<PrimType_, RotationUsage::ACTIVE>> {\n public:\n  typedef eigen_impl::RotationQuaternion<PrimType_, RotationUsage::PASSIVE> OtherUsage;\n};\n\ntemplate<typename PrimType_>\nclass get_other_usage<eigen_impl::RotationQuaternion<PrimType_, RotationUsage::PASSIVE>> {\n public:\n  typedef eigen_impl::RotationQuaternion<PrimType_, RotationUsage::ACTIVE> OtherUsage;\n};\n\n/* -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------\n * Conversion Traits\n * ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- */\ntemplate<typename DestPrimType_, typename SourcePrimType_, enum RotationUsage Usage_>\nclass ConversionTraits<eigen_impl::RotationQuaternion<DestPrimType_, Usage_>, eigen_impl::AngleAxis<SourcePrimType_, Usage_>> {\n public:\n  inline static eigen_impl::RotationQuaternion<DestPrimType_, Usage_> convert(const eigen_impl::AngleAxis<SourcePrimType_, Usage_>& aa) {\n    return eigen_impl::RotationQuaternion<DestPrimType_, Usage_>(eigen_impl::eigen_internal::getQuaternionFromAngleAxis<SourcePrimType_, DestPrimType_>(aa.toImplementation()));\n  }\n};\n\n\ntemplate <typename Scalar_ = double>\ninline bool isLessThenEpsilons4thRoot(Scalar_ x){\n  static const Scalar_ epsilon4thRoot = pow(std::numeric_limits<Scalar_>::epsilon(), 1.0/4.0);\n  return x < epsilon4thRoot;\n}\n\ntemplate<typename DestPrimType_, typename SourcePrimType_, enum RotationUsage Usage_>\nclass ConversionTraits<eigen_impl::RotationQuaternion<DestPrimType_, Usage_>, eigen_impl::RotationVector<SourcePrimType_, Usage_>> {\n public:\n  inline static eigen_impl::RotationQuaternion<DestPrimType_, Usage_> convert(const eigen_impl::RotationVector<SourcePrimType_, Usage_>& rotationVector) {\n    typedef typename eigen_impl::RotationQuaternion<DestPrimType_, Usage_>::Scalar Scalar;\n    typedef typename eigen_impl::RotationQuaternion<DestPrimType_, Usage_>::Imaginary Imaginary;\n//    const Scalar v = rotationVector.toImplementation().norm();\n//    Scalar real;\n//    Imaginary imaginary;\n//    if (v < common::internal::NumTraits<Scalar>::dummy_precision()) {\n//      real = 1.0;\n//      imaginary= 0.5*rotationVector.toImplementation().template cast<DestPrimType_>();\n//    }\n//    else {\n//      real = cos(v/2);\n//      imaginary = sin(v/2)/v*rotationVector.toImplementation().template cast<DestPrimType_>();\n//    }\n//    return eigen_impl::RotationQuaternion<DestPrimType_, Usage_>(real, imaginary);\n\n\n    Scalar theta = (Scalar)rotationVector.toImplementation().norm();\n\n    // na is 1/theta sin(theta/2)\n    double na;\n    if(isLessThenEpsilons4thRoot(theta))\n    {\n        const Scalar one_over_48 = 1.0/48.0;\n        na = 0.5 + (theta * theta) * one_over_48;\n    }\n    else\n    {\n        na = sin(theta*0.5) / theta;\n    }\n    Imaginary axis = rotationVector.toImplementation().template cast<Scalar>()*na;\n    Scalar ct = cos(theta*0.5);\n    return eigen_impl::RotationQuaternion<DestPrimType_, Usage_>(ct, axis[0],axis[1],axis[2]);\n//    return Eigen::Vector4d(axis[0],axis[1],axis[2],ct);\n\n  }\n};\n\ntemplate<typename DestPrimType_, typename SourcePrimType_, enum RotationUsage Usage_>\nclass ConversionTraits<eigen_impl::RotationQuaternion<DestPrimType_, Usage_>, eigen_impl::RotationQuaternion<SourcePrimType_, Usage_>> {\n public:\n  inline static eigen_impl::RotationQuaternion<DestPrimType_, Usage_> convert(const eigen_impl::RotationQuaternion<SourcePrimType_, Usage_>& q) {\n    return eigen_impl::RotationQuaternion<DestPrimType_, Usage_>(q.toImplementation().template cast<DestPrimType_>());\n  }\n};\n\ntemplate<typename DestPrimType_, typename SourcePrimType_, enum RotationUsage Usage_>\nclass ConversionTraits<eigen_impl::RotationQuaternion<DestPrimType_, Usage_>, eigen_impl::RotationMatrix<SourcePrimType_, Usage_>> {\n public:\n  inline static eigen_impl::RotationQuaternion<DestPrimType_, Usage_> convert(const eigen_impl::RotationMatrix<SourcePrimType_, Usage_>& rotationMatrix) {\n    return eigen_impl::RotationQuaternion<DestPrimType_, Usage_>(eigen_impl::eigen_internal::getQuaternionFromRotationMatrix<SourcePrimType_, DestPrimType_>(rotationMatrix.toImplementation()));\n  }\n};\n\ntemplate<typename DestPrimType_, typename SourcePrimType_, enum RotationUsage Usage_>\nclass ConversionTraits<eigen_impl::RotationQuaternion<DestPrimType_, Usage_>, eigen_impl::EulerAnglesXyz<SourcePrimType_, Usage_>> {\n public:\n  inline static eigen_impl::RotationQuaternion<DestPrimType_, Usage_> convert(const eigen_impl::EulerAnglesXyz<SourcePrimType_, Usage_>& xyz) {\n    return eigen_impl::RotationQuaternion<DestPrimType_, Usage_>(eigen_impl::eigen_internal::getQuaternionFromRpy<SourcePrimType_, DestPrimType_>(xyz.toImplementation()));\n  }\n};\n\ntemplate<typename DestPrimType_, typename SourcePrimType_, enum RotationUsage Usage_>\nclass ConversionTraits<eigen_impl::RotationQuaternion<DestPrimType_, Usage_>, eigen_impl::EulerAnglesZyx<SourcePrimType_, Usage_>> {\n public:\n  inline static eigen_impl::RotationQuaternion<DestPrimType_, Usage_> convert(const eigen_impl::EulerAnglesZyx<SourcePrimType_, Usage_>& zyx) {\n    return eigen_impl::RotationQuaternion<DestPrimType_, Usage_>(eigen_impl::eigen_internal::getQuaternionFromYpr<SourcePrimType_, DestPrimType_>(zyx.toImplementation()));\n  }\n};\n\n/* -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------\n * Multiplication Traits\n * ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- */\n\n/* -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------\n * Rotation Traits\n * ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- */\n\n/* -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------\n * Comparison Traits\n * ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- */\ntemplate<typename PrimType_, enum RotationUsage Usage_>\nclass ComparisonTraits<eigen_impl::RotationQuaternion<PrimType_, Usage_>, eigen_impl::RotationQuaternion<PrimType_, Usage_>> {\n public:\n   inline static bool isEqual(const eigen_impl::RotationQuaternion<PrimType_, Usage_>& a, const eigen_impl::RotationQuaternion<PrimType_, Usage_>& b){\n     return a.toImplementation().w() ==  b.toImplementation().w() &&\n            a.toImplementation().x() ==  b.toImplementation().x() &&\n            a.toImplementation().y() ==  b.toImplementation().y() &&\n            a.toImplementation().z() ==  b.toImplementation().z();\n   }\n};\n\n/* -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------\n * Fixing Traits\n * ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- */\ntemplate<typename PrimType_, enum RotationUsage Usage_>\nclass FixingTraits<eigen_impl::RotationQuaternion<PrimType_, Usage_>> {\n public:\n  inline static void fix(eigen_impl::RotationQuaternion<PrimType_, Usage_>& q) {\n    q.toImplementation().normalize();\n  }\n};\n\n} // namespace internal\n} // namespace rotations\n} // namespace kindr\n\n\n#endif /* KINDR_ROTATIONS_EIGEN_ROTATIONQUATERNION_HPP_ */\n\n", "meta": {"hexsha": "d7be0b20528ef5373e0a1200111dd93020244446", "size": 28528, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "IHMCPerception/third-party/kindr/include/kindr/rotations/eigen/RotationQuaternion.hpp", "max_stars_repo_name": "wxmerkt/ihmc-open-robotics-software", "max_stars_repo_head_hexsha": "2c47c9a9bd999e7811038e99c3888683f9973a2a", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 170.0, "max_stars_repo_stars_event_min_datetime": "2016-02-01T18:58:50.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-17T05:28:01.000Z", "max_issues_repo_path": "IHMCPerception/third-party/kindr/include/kindr/rotations/eigen/RotationQuaternion.hpp", "max_issues_repo_name": "wxmerkt/ihmc-open-robotics-software", "max_issues_repo_head_hexsha": "2c47c9a9bd999e7811038e99c3888683f9973a2a", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 162.0, "max_issues_repo_issues_event_min_datetime": "2016-01-29T17:04:29.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-10T16:25:37.000Z", "max_forks_repo_path": "IHMCPerception/third-party/kindr/include/kindr/rotations/eigen/RotationQuaternion.hpp", "max_forks_repo_name": "wxmerkt/ihmc-open-robotics-software", "max_forks_repo_head_hexsha": "2c47c9a9bd999e7811038e99c3888683f9973a2a", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 83.0, "max_forks_repo_forks_event_min_datetime": "2016-01-28T22:49:01.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T03:11:24.000Z", "avg_line_length": 43.2242424242, "max_line_length": 217, "alphanum_fraction": 0.6274537297, "num_tokens": 7157, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6370308082623217, "lm_q2_score": 0.5428632831725052, "lm_q1q2_score": 0.34582063605531865}}
{"text": "#ifndef CONTRACTOR_TERMS_PERMUTATIONGROUP_HPP_\n#define CONTRACTOR_TERMS_PERMUTATIONGROUP_HPP_\n\n#include \"terms/Index.hpp\"\n#include \"terms/IndexSubstitution.hpp\"\n\n#include <ostream>\n#include <vector>\n\n#include <boost/range/join.hpp>\n\nnamespace Contractor::Terms {\n\n/*\n * NOTE: For a more performant solution (especially for larger groups) the\n * Schreier-Sims-Algorithm for generating a base and a strong generating set\n * (used as a representation for the group) should be used instead.\n * However as we are only expecting to treat small-ish groups with this class\n * and given that the Schreier-Sims-Algorithm involves heavy group theory\n * that I don't understand yet, we'll settle on the brute-force method here.\n */\n\n/**\n * A class representing a permutation group (A group in the mathematical sense that consists of\n * permutation operations).\n */\nclass PermutationGroup {\npublic:\n\t/**\n\t * An element consists of a specific index sequence along with a factor that results from converting\n\t * the initial sequence into the stored one using only the allowed permutation operations.\n\t */\n\tstruct Element {\n\t\tstd::vector< Index > indexSequence;\n\t\tint factor = 1.0f;\n\n\t\tElement(const std::vector< Index > &seq = {}, int factor = 1.0f) : indexSequence(seq), factor(factor) {}\n\t\tElement(const Element &other) = default;\n\t\tElement(Element &&other)      = default;\n\n\t\tElement &operator=(const Element &other) = default;\n\t\tElement &operator=(Element &&other) = default;\n\n\t\tfriend bool operator==(const Element &lhs, const Element &rhs) {\n\t\t\treturn lhs.indexSequence == rhs.indexSequence;\n\t\t};\n\n\t\tfriend bool operator!=(const Element &lhs, const Element &rhs) { return lhs != rhs; }\n\n\t\tfriend bool operator<(const Element &lhs, const Element &rhs) { return lhs.indexSequence < rhs.indexSequence; }\n\t};\n\n\tPermutationGroup() = default;\n\tPermutationGroup(const Element &startConfiguration);\n\tPermutationGroup(Element &&startConfiguration);\n\tPermutationGroup(const PermutationGroup &other) = default;\n\tPermutationGroup(PermutationGroup &&other)      = default;\n\tPermutationGroup &operator=(const PermutationGroup &other) = default;\n\tPermutationGroup &operator=(PermutationGroup &&other) = default;\n\n\tfriend bool operator==(const PermutationGroup &lhs, const PermutationGroup &rhs);\n\tfriend bool operator!=(const PermutationGroup &lhs, const PermutationGroup &rhs);\n\tfriend std::ostream &operator<<(std::ostream &stream, const PermutationGroup &group);\n\n\t/**\n\t * Add a generator for this group\n\t *\n\t * @param generator The generator operation to add\n\t * @param regenerate Whether to regenerate the group after having added the generator\n\t */\n\tvoid addGenerator(const IndexSubstitution &generator, bool regenerate = true);\n\t/**\n\t * Add a generator for this group\n\t *\n\t * @param generator The generator operation to add\n\t * @param regenerate Whether to regenerate the group after having added the generator\n\t */\n\tvoid addGenerator(IndexSubstitution &&generator, bool regenerate = true);\n\n\t/**\n\t * @returns A list of generator operations of this group\n\t */\n\tconst std::vector< IndexSubstitution > &getGenerators() const;\n\t/**\n\t * @returns A list of operations of this group that are not the generators but that result\n\t * by chainging and combining the generators.\n\t */\n\tconst std::vector< IndexSubstitution > &getAdditionalSymmetryOperations() const;\n\n\t/**\n\t * @returns The list of permutations of the index sequence that can be reached by applying the\n\t * permutation operations contained in this group.\n\t */\n\tconst std::vector< Element > &getIndexPermutations() const;\n\n\t/**\n\t * Set the initial index sequence this group shall act on\n\t *\n\t * @param rootSequence The sequence to permute\n\t */\n\tvoid setRootSequence(const Element &rootSequence);\n\n\t/**\n\t * @returns Whether the given permutation operation is contained in this group\n\t */\n\tbool contains(const IndexSubstitution &permutation) const;\n\t/**\n\t * @returns Whether the given index sequence can be reached from the root sequence set on this group\n\t * by only using the permutation operations contained in this group.\n\t */\n\tbool contains(const std::vector< Index > &indexSequence) const;\n\n\t/**\n\t * @returns The size of this group (amount of permutation operations contained in it)\n\t */\n\tstd::size_t size() const;\n\n\t/**\n\t * @returns A \"canonical\" index sequence. This sequence will be the same no matter which root sequence\n\t * has been chosen for this group, provided that the different root sequences can be converted into one another\n\t * using only the allowed permutation operations on them.\n\t */\n\tconst std::vector< Index > &getCanonicalRepresentation() const;\n\t/**\n\t * The factor that is associated with turning the set root sequence into the \"canonical\" one\n\t */\n\tint getCanonicalRepresentationFactor() const;\n\n\t/**\n\t * Given the generators of this group, this function will generate all permutation operations.\n\t */\n\tvoid regenerateGroup();\n\nprotected:\n\tstd::vector< Element > m_permutations;\n\tstd::vector< IndexSubstitution > m_generators = { IndexSubstitution::identity() };\n\tstd::vector< IndexSubstitution > m_additionalElements;\n\n\tvoid generateSymmetryOperations(const IndexSubstitution &preceidingOperation = IndexSubstitution::identity());\n};\n\n}; // namespace Contractor::Terms\n\n// Provide template specialization of std::hash for the PermutationGroup class\nnamespace std {\ntemplate<> struct hash< Contractor::Terms::PermutationGroup > {\n\tstd::size_t operator()(const Contractor::Terms::PermutationGroup &group) const {\n\t\tstd::size_t hash = 0;\n\n\t\tauto it = boost::join(group.getGenerators(), group.getAdditionalSymmetryOperations());\n\t\tfor (auto i = it.begin(); i != it.end(); ++i) {\n\t\t\thash += std::hash< Contractor::Terms::IndexSubstitution >{}(*i);\n\t\t}\n\n\t\treturn hash;\n\t}\n};\n}; // namespace std\n\n#endif // CONTRACTOR_TERMS_PERMUTATIONGROUP_HPP_\n", "meta": {"hexsha": "6cf30f457414d7d8130a6ef1d6821f07c36d1ec4", "size": 5803, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/terms/PermutationGroup.hpp", "max_stars_repo_name": "Krzmbrzl/contractor", "max_stars_repo_head_hexsha": "7d2d7f08054ba22b12c6e473757f963d5a61a912", "max_stars_repo_licenses": ["BSD-3-Clause"], "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/terms/PermutationGroup.hpp", "max_issues_repo_name": "Krzmbrzl/contractor", "max_issues_repo_head_hexsha": "7d2d7f08054ba22b12c6e473757f963d5a61a912", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/terms/PermutationGroup.hpp", "max_forks_repo_name": "Krzmbrzl/contractor", "max_forks_repo_head_hexsha": "7d2d7f08054ba22b12c6e473757f963d5a61a912", "max_forks_repo_licenses": ["BSD-3-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.0434782609, "max_line_length": 113, "alphanum_fraction": 0.7437532311, "num_tokens": 1305, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6370307944803832, "lm_q2_score": 0.5428632831725052, "lm_q1q2_score": 0.34582062857361023}}
{"text": "/*\n * Copyright (C) 2012 Open Source Robotics Foundation\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n*/\n#ifndef _GAZEBO_MATH_FUNCTIONS_HH_\n#define _GAZEBO_MATH_FUNCTIONS_HH_\n\n#include <boost/math/special_functions/fpclassify.hpp>\n#include <boost/math/special_functions/round.hpp>\n#include <algorithm>\n#include <cmath>\n#include <limits>\n#include <string>\n#include <iostream>\n#include <vector>\n#include \"gazebo/util/system.hh\"\n\n/// \\brief Double maximum value\n#define GZ_DBL_MAX gazebo::math::MAX_D\n\n/// \\brief Double min value\n#define GZ_DBL_MIN gazebo::math::MIN_D\n\n/// \\brief Double positive infinite value\n#define GZ_DBL_INF gazebo::math::INF_D\n\n/// \\brief Float maximum value\n#define GZ_FLT_MAX gazebo::math::MAX_F\n\n/// \\brief Float minimum value\n#define GZ_FLT_MIN gazebo::math::MIN_F\n\n/// \\brief 32bit unsigned integer maximum value\n#define GZ_UINT32_MAX gazebo::math::MAX_UI32\n\n/// \\brief 32bit unsigned integer minimum value\n#define GZ_UINT32_MIN gazebo::math::MIN_UI32\n\n/// \\brief 32bit integer maximum value\n#define GZ_INT32_MAX gazebo::math::MAX_I32\n\n/// \\brief 32bit integer minimum value\n#define GZ_INT32_MIN gazebo::math::MIN_I32\n\n\nnamespace gazebo\n{\n  namespace math\n  {\n    /// \\addtogroup gazebo_math\n    /// \\brief A set of classes that encapsulate math related properties and\n    ///        functions.\n    /// \\{\n\n    /// \\brief Double maximum value. This value will be similar to 1.79769e+308\n    static const double\n    GAZEBO_DEPRECATED(8.0)\n    MAX_D = std::numeric_limits<double>::max();\n\n    /// \\brief Double min value. This value will be similar to 2.22507e-308\n    static const double\n    GAZEBO_DEPRECATED(8.0)\n    MIN_D = std::numeric_limits<double>::min();\n\n    /// \\brief Double positive infinite value\n    static const double\n    GAZEBO_DEPRECATED(8.0)\n    INF_D = std::numeric_limits<double>::infinity();\n\n    /// \\brief Returns the representation of a quiet not a number (NAN)\n    static const double\n    GAZEBO_DEPRECATED(8.0)\n    NAN_D = std::numeric_limits<double>::quiet_NaN();\n\n    /// \\brief Float maximum value. This value will be similar to 3.40282e+38\n    static const float\n    GAZEBO_DEPRECATED(8.0)\n    MAX_F = std::numeric_limits<float>::max();\n\n    /// \\brief Float minimum value. This value will be similar to 1.17549e-38\n    static const float\n    GAZEBO_DEPRECATED(8.0)\n    MIN_F = std::numeric_limits<float>::min();\n\n    /// \\brief 32bit unsigned integer maximum value\n    static const uint32_t\n    GAZEBO_DEPRECATED(8.0)\n    MAX_UI32 = std::numeric_limits<uint32_t>::max();\n\n    /// \\brief 32bit unsigned integer minimum value\n    static const uint32_t\n    GAZEBO_DEPRECATED(8.0)\n    MIN_UI32 = std::numeric_limits<uint32_t>::min();\n\n    /// \\brief 32bit unsigned integer maximum value\n    static const int32_t\n    GAZEBO_DEPRECATED(8.0)\n    MAX_I32 = std::numeric_limits<int32_t>::max();\n\n    /// \\brief 32bit unsigned integer minimum value\n    static const int32_t\n    GAZEBO_DEPRECATED(8.0)\n    MIN_I32 = std::numeric_limits<int32_t>::min();\n\n    /// \\brief Returns the representation of a quiet not a number (NAN)\n    static const int\n    GAZEBO_DEPRECATED(8.0)\n    NAN_I = std::numeric_limits<int>::quiet_NaN();\n\n    /// \\brief Simple clamping function\n    /// \\param[in] _v value\n    /// \\param[in] _min minimum\n    /// \\param[in] _max maximum\n    /// \\deprecated See ignition::math::clamp\n    template<typename T>\n    inline T\n    GAZEBO_DEPRECATED(8.0)\n    clamp(T _v, T _min, T _max)\n    {\n      return std::max(std::min(_v, _max), _min);\n    }\n\n    /// \\brief check if a float is NaN\n    /// \\param[in] _v the value\n    /// \\return true if _v is not a number, false otherwise\n    /// \\deprecated See ignition::math::isnan\n    inline bool\n    GAZEBO_DEPRECATED(8.0)\n    isnan(float _v)\n    {\n      return (boost::math::isnan)(_v);\n    }\n\n    /// \\brief check if a double is NaN\n    /// \\param[in] _v the value\n    /// \\return true if _v is not a number, false otherwise\n    /// \\deprecated See ignition::math::isnan\n    inline bool\n    GAZEBO_DEPRECATED(8.0)\n    isnan(double _v)\n    {\n      return (boost::math::isnan)(_v);\n    }\n\n#ifndef _WIN32\n#pragma GCC diagnostic push\n#pragma GCC diagnostic ignored \"-Wdeprecated-declarations\"\n#endif\n    /// \\brief Fix a nan value.\n    /// \\param[in] _v Value to correct.\n    /// \\return 0 if _v is NaN, _v otherwise.\n    /// \\deprecated See ignition::math::fixnan\n    inline float\n    GAZEBO_DEPRECATED(8.0)\n    fixnan(float _v)\n    {\n      return isnan(_v) || std::isinf(_v) ? 0.0f : _v;\n    }\n\n    /// \\brief Fix a nan value.\n    /// \\param[in] _v Value to correct.\n    /// \\return 0 if _v is NaN, _v otherwise.\n    /// \\deprecated See ignition::math::fixnan\n    inline double\n    GAZEBO_DEPRECATED(8.0)\n    fixnan(double _v)\n    {\n      return isnan(_v) || std::isinf(_v) ? 0.0 : _v;\n    }\n#ifndef _WIN32\n#pragma GCC diagnostic pop\n#endif\n\n    /// \\brief get mean of vector of values\n    /// \\param[in] _values the vector of values\n    /// \\return the mean\n    /// \\deprecated See ignition::math::mean\n    template<typename T>\n    inline T\n    GAZEBO_DEPRECATED(8.0)\n    mean(const std::vector<T> &_values)\n    {\n      T sum = 0;\n      for (unsigned int i = 0; i < _values.size(); ++i)\n        sum += _values[i];\n      return sum / _values.size();\n    }\n\n    /// \\brief get variance of vector of values\n    /// \\param[in] _values the vector of values\n    /// \\return the squared deviation\n    /// \\deprecated See ignition::math::variance\n    template<typename T>\n    inline T\n    GAZEBO_DEPRECATED(8.0)\n    variance(const std::vector<T> &_values)\n    {\n      T avg = mean<T>(_values);\n\n      T sum = 0;\n      for (unsigned int i = 0; i < _values.size(); ++i)\n        sum += (_values[i] - avg) * (_values[i] - avg);\n      return sum / _values.size();\n    }\n\n    /// \\brief get the maximum value of vector of values\n    /// \\param[in] _values the vector of values\n    /// \\return maximum\n    /// \\deprecated See ignition::math::max\n    template<typename T>\n    inline T\n    GAZEBO_DEPRECATED(8.0)\n    max(const std::vector<T> &_values)\n    {\n      T max = std::numeric_limits<T>::min();\n      for (unsigned int i = 0; i < _values.size(); ++i)\n        if (_values[i] > max)\n          max = _values[i];\n      return max;\n    }\n\n    /// \\brief get the minimum value of vector of values\n    /// \\param[in] _values the vector of values\n    /// \\return minimum\n    /// \\deprecated See ignition::math::min\n    template<typename T>\n    inline T\n    GAZEBO_DEPRECATED(8.0)\n    min(const std::vector<T> &_values)\n    {\n      T min = std::numeric_limits<T>::max();\n      for (unsigned int i = 0; i < _values.size(); ++i)\n        if (_values[i] < min)\n          min = _values[i];\n      return min;\n    }\n\n    /// \\brief check if two values are equal, within a tolerance\n    /// \\param[in] _a the first value\n    /// \\param[in] _b the second value\n    /// \\param[in] _epsilon the tolerance\n    /// \\deprecated See ignition::math::equal\n    template<typename T>\n    inline bool\n    GAZEBO_DEPRECATED(8.0)\n    equal(const T &_a, const T &_b, const T &_epsilon = 1e-6)\n    {\n      return std::fabs(_a - _b) <= _epsilon;\n    }\n\n    /// \\brief get value at a specified precision\n    /// \\param[in] _a the number\n    /// \\param[in] _precision the precision\n    /// \\return the value for the specified precision\n    /// \\deprecated See ignition::math::precision\n    template<typename T>\n    inline T\n    GAZEBO_DEPRECATED(8.0)\n    precision(const T &_a, const unsigned int &_precision)\n    {\n      if (!std::isinf(_a))\n      {\n        return boost::math::round(\n          _a * pow(10, _precision)) / pow(10, _precision);\n      }\n      else\n      {\n        return _a;\n      }\n    }\n\n    /// \\brief is this a power of 2?\n    /// \\param[in] _x the number\n    /// \\return true if _x is a power of 2, false otherwise\n    /// \\deprecated See ignition::math::isPowerOfTwo\n    inline bool\n    GAZEBO_DEPRECATED(8.0)\n    isPowerOfTwo(unsigned int _x)\n    {\n      return ((_x != 0) && ((_x & (~_x + 1)) == _x));\n    }\n\n    /// \\brief Get the smallest power of two that is greater or equal to a given\n    /// value\n    /// \\param[in] _x the number\n    /// \\return the same value if _x is already a power of two. Otherwise,\n    /// it returns the smallest power of two that is greater than _x\n    /// \\deprecated See ignition::math::roundUpPowerOfTwo\n    inline unsigned int\n    GAZEBO_DEPRECATED(8.0)\n    roundUpPowerOfTwo(unsigned int _x)\n    {\n      if (_x == 0)\n        return 1;\n\n#ifndef _WIN32\n#pragma GCC diagnostic push\n#pragma GCC diagnostic ignored \"-Wdeprecated-declarations\"\n#endif\n      if (isPowerOfTwo(_x))\n        return _x;\n#ifndef _WIN32\n#pragma GCC diagnostic pop\n#endif\n\n      while (_x & (_x - 1))\n        _x = _x & (_x - 1);\n\n      _x = _x << 1;\n\n      return _x;\n    }\n\n    /// \\brief parse string into an integer\n    /// \\param[in] _input the string\n    /// \\return an integer, 0 or 0 and a message in the error stream\n    /// \\deprecated See ignition::math::parseInt\n    inline int\n    GAZEBO_DEPRECATED(8.0)\n    parseInt(const std::string& _input)\n    {\n      const char *p = _input.c_str();\n#ifndef _WIN32\n#pragma GCC diagnostic push\n#pragma GCC diagnostic ignored \"-Wdeprecated-declarations\"\n#endif\n      if (!*p || *p == '?')\n        return NAN_I;\n#ifndef _WIN32\n#pragma GCC diagnostic pop\n#endif\n\n      int s = 1;\n      while (*p == ' ')\n        p++;\n\n      if (*p == '-')\n      {\n        s = -1;\n        p++;\n      }\n\n      int acc = 0;\n      while (*p >= '0' && *p <= '9')\n        acc = acc * 10 + *p++ - '0';\n\n      if (*p)\n      {\n        std::cerr << \"Invalid int numeric format[\" << _input << \"]\\n\";\n        return 0.0;\n      }\n\n      return s * acc;\n    }\n\n    /// \\brief parse string into float\n    /// \\param _input the string\n    /// \\return a floating point number (can be NaN) or 0 with a message in the\n    /// error stream\n    /// \\deprecated See ignition::math::parseFloat\n    inline double\n    GAZEBO_DEPRECATED(8.0)\n    parseFloat(const std::string& _input)\n    {\n      const char *p = _input.c_str();\n#ifndef _WIN32\n#pragma GCC diagnostic push\n#pragma GCC diagnostic ignored \"-Wdeprecated-declarations\"\n#endif\n      if (!*p || *p == '?')\n        return NAN_D;\n#ifndef _WIN32\n#pragma GCC diagnostic pop\n#endif\n      int s = 1;\n      while (*p == ' ')\n        p++;\n\n      if (*p == '-')\n      {\n        s = -1;\n        p++;\n      }\n\n      double acc = 0;\n      while (*p >= '0' && *p <= '9')\n        acc = acc * 10 + *p++ - '0';\n\n      if (*p == '.')\n      {\n        double k = 0.1;\n        p++;\n        while (*p >= '0' && *p <= '9')\n        {\n          acc += (*p++ - '0') * k;\n          k *= 0.1;\n        }\n      }\n      if (*p == 'e')\n      {\n        int es = 1;\n        int f = 0;\n        p++;\n        if (*p == '-')\n        {\n          es = -1;\n          p++;\n        }\n        else if (*p == '+')\n        {\n          es = 1;\n          p++;\n        }\n        while (*p >= '0' && *p <= '9')\n          f = f * 10 + *p++ - '0';\n\n        acc *= pow(10, f*es);\n      }\n\n      if (*p)\n      {\n        std::cerr << \"Invalid double numeric format[\" << _input << \"]\\n\";\n        return 0.0;\n      }\n      return s * acc;\n    }\n    /// \\}\n  }\n}\n#endif\n", "meta": {"hexsha": "34c8dd3220237e47c7dd1c89489d353663fd067f", "size": 11683, "ext": "hh", "lang": "C++", "max_stars_repo_path": "gazebo/math/Helpers.hh", "max_stars_repo_name": "tommy91/Gazebo-Ardupilot", "max_stars_repo_head_hexsha": "03ff6d3e6787eddaf650a681adb56dc06cf82294", "max_stars_repo_licenses": ["ECL-2.0", "Apache-2.0"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2018-07-17T00:17:13.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-26T08:39:25.000Z", "max_issues_repo_path": "gazebo/math/Helpers.hh", "max_issues_repo_name": "tommy91/Gazebo-Ardupilot", "max_issues_repo_head_hexsha": "03ff6d3e6787eddaf650a681adb56dc06cf82294", "max_issues_repo_licenses": ["ECL-2.0", "Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2022-02-03T18:32:35.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-03T18:32:35.000Z", "max_forks_repo_path": "gazebo/math/Helpers.hh", "max_forks_repo_name": "mingfeisun/gazebo", "max_forks_repo_head_hexsha": "f3eae789c738f040b8fb27c2dc16dc4c06f2495c", "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": 26.3724604966, "max_line_length": 80, "alphanum_fraction": 0.5971069075, "num_tokens": 3268, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6757646140788307, "lm_q2_score": 0.5117166047041654, "lm_q1q2_score": 0.3457999738956399}}
{"text": "#include <signal.h>\n#include <iostream>\n#include <iomanip>\n#include <string>\n#include <fstream>\n#include <sstream>\n#include <algorithm>\n#include <cassert>\n#include <sstream>\n#include \"g2o/apps/g2o_cli/dl_wrapper.h\"\n#include \"g2o/apps/g2o_cli/output_helper.h\"\n#include \"g2o/apps/g2o_cli/g2o_common.h\"\n\n#include \"g2o/core/estimate_propagator.h\"\n#include \"g2o/core/sparse_optimizer.h\"\n#include \"g2o/core/factory.h\"\n#include \"g2o/core/optimization_algorithm_factory.h\"\n#include \"g2o/core/hyper_dijkstra.h\"\n\n#include \"g2o/stuff/macros.h\"\n#include \"g2o/stuff/color_macros.h\"\n#include \"g2o/stuff/command_args.h\"\n#include \"g2o/stuff/filesys_tools.h\"\n#include \"g2o/stuff/string_tools.h\"\n#include \"g2o/stuff/timeutil.h\"\n\n#include \"edge_labeler.h\"\n#include \"edge_creator.h\"\n#include \"star.h\"\n\n#include \"g2o/stuff/unscented.h\"\n#include <Eigen/Core>\n#include <Eigen/Dense>\n\n\nusing namespace std;\nusing namespace g2o;\nusing namespace Eigen;\n\ntypedef SigmaPoint<VectorXd> MySigmaPoint;\n\nvoid testMarginals(SparseOptimizer& optimizer){\n  cerr << \"Projecting marginals\" << endl;\n  std::vector<std::pair<int, int> > blockIndices;\n  for (size_t i=0; i<optimizer.activeVertices().size(); i++) {\n    OptimizableGraph::Vertex* v=optimizer.activeVertices()[i];\n    if (v->hessianIndex()>=0){\n      blockIndices.push_back(make_pair(v->hessianIndex(), v->hessianIndex()));\n    }\n    // if (v->hessianIndex()>0){\n    //   blockIndices.push_back(make_pair(v->hessianIndex()-1, v->hessianIndex()));\n    // }\n  }\n  SparseBlockMatrix<MatrixXd> spinv;\n  if (optimizer.computeMarginals(spinv, blockIndices)) {\n    for (size_t i=0; i<optimizer.activeVertices().size(); i++) {\n      OptimizableGraph::Vertex* v=optimizer.activeVertices()[i];\n      cerr << \"Vertex id:\" << v->id() << endl;\n      if (v->hessianIndex()>=0){\n        cerr << \"increments block :\" << v->hessianIndex() << \", \" << v->hessianIndex()<< \" covariance:\" <<  endl;\n        VectorXd mean(v->minimalEstimateDimension()); //HACK: need to set identity\n        mean.fill(0);\n        VectorXd oldMean(v->minimalEstimateDimension()); //HACK: need to set identity\n        v->getMinimalEstimateData(&oldMean[0]);\n        MatrixXd& cov= *(spinv.block(v->hessianIndex(), v->hessianIndex()));\n        std::vector<MySigmaPoint, Eigen::aligned_allocator<MySigmaPoint> > spts;\n        cerr << cov << endl;\n        if (! sampleUnscented(spts,mean,cov) )\n          continue;\n\n        // now apply the oplus operator to the sigma points,\n        // and get the points in the global space\n        std::vector<MySigmaPoint, Eigen::aligned_allocator<MySigmaPoint> > tspts = spts;\n\n        for (size_t j=0; j<spts.size(); j++) {\n          v->push();\n          // cerr << \"v_before [\" << j << \"]\" << endl;\n          v->getMinimalEstimateData(&mean[0]);\n          // cerr << mean << endl;\n          // cerr << \"sigma [\" << j << \"]\" << endl;\n          // cerr << spts[j]._sample << endl;\n          v->oplus(&(spts[j]._sample[0]));\n          v->getMinimalEstimateData(&mean[0]);\n          tspts[j]._sample=mean;\n          // cerr << \"oplus [\" << j << \"]\" << endl;\n          // cerr << tspts[j]._sample << endl;\n          v->pop();\n        }\n        MatrixXd cov2=cov;\n        reconstructGaussian(mean, cov2, tspts);\n        cerr << \"global block :\" << v->hessianIndex() << \", \" << v->hessianIndex()<< endl;\n        cerr << \"mean: \" << endl;\n        cerr <<  mean << endl;\n        cerr << \"oldMean: \" << endl;\n        cerr <<  oldMean << endl;\n        cerr << \"cov: \" << endl;\n        cerr << cov2 << endl;\n\n      }\n      // if (v->hessianIndex()>0){\n      //   cerr << \"inv block :\" << v->hessianIndex()-1 << \", \" << v->hessianIndex()<< endl;\n      //   cerr << *(spinv.block(v->hessianIndex()-1, v->hessianIndex()));\n      //   cerr << endl;\n      // }\n    }\n  }\n}\n\nint unscentedTest(){\n  MatrixXd m=MatrixXd(6,6);\n  for (int i=0; i<6; i++){\n    for (int j=i; j<6; j++){\n      m(i,j)=m(j,i)=i*j+1;\n    }\n  }\n  m+=MatrixXd::Identity(6,6);\n  cerr << m;\n  VectorXd mean(6);\n  mean.fill(1);\n\n  std::vector<MySigmaPoint, Eigen::aligned_allocator<MySigmaPoint> > spts;\n  sampleUnscented(spts,mean,m);\n  for (size_t i =0; i<spts.size(); i++){\n    cerr << \"Point \" << i << \" \" << endl << \"wi=\" << spts[i]._wi << \" wp=\" << spts[i]._wp << \" \" << endl;\n    cerr << spts[i]._sample << endl;\n  }\n\n  VectorXd recMean(6);\n  MatrixXd recCov(6,6);\n\n  reconstructGaussian(recMean, recCov, spts);\n\n  cerr << \"recMean\" << endl;\n  cerr << recMean << endl;\n\n  cerr << \"recCov\" << endl;\n  cerr << recCov << endl;\n\n  return 0;\n}\n", "meta": {"hexsha": "f2865ea9336a35719a574e8a6efe04b8b373d4fb", "size": 4517, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Thirdparty/g2o/g2o/apps/g2o_hierarchical/g2o_hierarchical_test_functions.cpp", "max_stars_repo_name": "liyi2017/StructSLAM", "max_stars_repo_head_hexsha": "7eb205489d7bde30ee74b08e72d01deaa42741fa", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 57.0, "max_stars_repo_stars_event_min_datetime": "2018-03-11T03:35:46.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-14T07:39:26.000Z", "max_issues_repo_path": "Thirdparty/g2o/g2o/apps/g2o_hierarchical/g2o_hierarchical_test_functions.cpp", "max_issues_repo_name": "jyakaranda/StructSLAM", "max_issues_repo_head_hexsha": "7eb205489d7bde30ee74b08e72d01deaa42741fa", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2019-03-06T02:16:42.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-07T08:45:52.000Z", "max_forks_repo_path": "Thirdparty/g2o/g2o/apps/g2o_hierarchical/g2o_hierarchical_test_functions.cpp", "max_forks_repo_name": "jyakaranda/StructSLAM", "max_forks_repo_head_hexsha": "7eb205489d7bde30ee74b08e72d01deaa42741fa", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 30.0, "max_forks_repo_forks_event_min_datetime": "2017-07-23T11:33:26.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-21T05:35:53.000Z", "avg_line_length": 32.0354609929, "max_line_length": 113, "alphanum_fraction": 0.5948638477, "num_tokens": 1318, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6757646010190476, "lm_q2_score": 0.5117166047041654, "lm_q1q2_score": 0.345799967212732}}
{"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_MAPFUNCS_LINEARIZATION_HPP\n#define STAPL_MAPFUNCS_LINEARIZATION_HPP\n\n#include <stapl/algorithms/functional.hpp>\n#include <stapl/views/mapping_functions/mapping_functions.hpp>\n#include <stapl/utility/tuple.hpp>\n#include <stapl/utility/tuple/to_index.hpp>\n#include <stapl/utility/tuple/ensure_tuple.hpp>\n#include <stapl/utility/tuple/rearrange.hpp>\n#include <stapl/utility/integer_sequence.hpp>\n\n#include <boost/mpl/find_if.hpp>\n#include <boost/mpl/vector.hpp>\n#include <boost/mpl/distance.hpp>\n\nnamespace stapl {\n\ntemplate<typename GID, typename Traversal>\nstruct nd_reverse_linearize;\n\n\ntemplate<typename GID, typename Traversal>\nstruct nd_linearize;\n\n\nnamespace detail {\n\n//////////////////////////////////////////////////////////////////////\n/// @brief Rearrange the contents of a tuple to be in the correct\n///        traversal order.\n///\n/// For example, given the tuple (x, y, z) and the traversal <1, 2, 0>,\n/// output the tuple (z, x, y).\n///\n/// @tparam Tuple Type of the run-time tuple of std::size_ts\n/// @tparam Traversal Traversal ordering.\n//////////////////////////////////////////////////////////////////////\ntemplate<typename Tuple, typename Traversal,\n         typename Indices = make_index_sequence<tuple_size<Traversal>::value>>\nstruct traversal_order;\n\n\ntemplate<typename Tuple, typename... IntTypes, std::size_t... Indices>\nstruct traversal_order<Tuple, tuple<IntTypes...>, index_sequence<Indices...>>\n{\n  typedef boost::mpl::vector<IntTypes...>                  vector_t;\n\nprivate:\n  typedef tuple<\n    typename boost::mpl::distance<\n      typename boost::mpl::begin<vector_t>::type,\n      typename boost::mpl::find_if<\n        vector_t, type_constant_equal<Indices>>::type\n    >::type...>                                            indices_t;\n\npublic:\n  static Tuple apply(Tuple const& src)\n  {\n    return Tuple(get<tuple_element<Indices, indices_t>::type::value>(src)...);\n  }\n};\n\n\n//////////////////////////////////////////////////////////////////////\n/// @brief Specialization for size_t\n//////////////////////////////////////////////////////////////////////\ntemplate<typename... IntTypes, std::size_t... Indices>\nstruct traversal_order<std::size_t, tuple<IntTypes...>,\n                       index_sequence<Indices...>>\n{\n  static std::size_t apply(std::size_t src)\n  {\n    return src;\n  }\n};\n\n//////////////////////////////////////////////////////////////////////\n/// @brief Rearrange the contents of a tuple to be in the reverse\n///        traversal order.\n/// @tparam Tuple Type of tuple to rearrange.\n/// @tparam Travesal Traversal ordering.\n///\n/// For example, given the tuple (x, y, z) and the traversal <1, 2, 0>,\n/// output the tuple (y, z, x).\n//////////////////////////////////////////////////////////////////////\ntemplate<typename Tuple, typename Traversal,\n         typename Indices = make_index_sequence<tuple_size<Tuple>::value>>\nstruct reverse_traversal_order;\n\n\ntemplate<typename Tuple, typename Traversal, std::size_t... Indices>\nstruct reverse_traversal_order<Tuple, Traversal, index_sequence<Indices...>>\n{\n  static Tuple apply(Tuple const& src)\n  {\n    return Tuple(get<tuple_element<Indices, Traversal>::type::value>(src)...);\n  }\n};\n\n\n//////////////////////////////////////////////////////////////////////\n/// @brief Computes the modulus of a 1-dimensional number with the\n///        linear size of all of the dimensions before the current\n///        dimension @p N.\n//////////////////////////////////////////////////////////////////////\ntemplate<int N>\nstruct apply_modulo\n{\n  template<class Tuple>\n  static size_t apply(Tuple const& sizes, size_t result)\n  {\n    return apply_modulo<N-1>::apply(\n      tuple_ops::pop_back(sizes),\n      result % tuple_ops::fold(sizes, 1, stapl::multiplies<size_t>()));\n  }\n};\n\n\n//////////////////////////////////////////////////////////////////////\n/// @brief Base case @ref apply_modulo.\n//////////////////////////////////////////////////////////////////////\ntemplate<>\nstruct apply_modulo<0>\n{\n  template<class Tuple>\n  static size_t apply(Tuple const&, size_t result)\n  { return result; }\n};\n\n\n//////////////////////////////////////////////////////////////////////\n/// @brief Divides a given number by all of the elements of a tuple.\n///\n/// Start with N = N-1 and sizes in traversal order\n//////////////////////////////////////////////////////////////////////\ntemplate<int N>\nstruct apply_divide\n{\n  template<class Tuple>\n  static size_t apply(Tuple const& sizes, size_t result)\n  {\n    return apply_divide<N-1>::apply(sizes, result / get<N>(sizes));\n  }\n};\n\n\n//////////////////////////////////////////////////////////////////////\n/// @brief Base case @ref apply_divide.\n//////////////////////////////////////////////////////////////////////\ntemplate<>\nstruct apply_divide<-1>\n{\n  template<class Tuple>\n  static size_t apply(Tuple const&, size_t result)\n  { return result; }\n};\n\n\n//////////////////////////////////////////////////////////////////////\n/// @brief Translates a 1-dimensional linearization back to its\n///        n-dimensional form.\n///\n/// This functor assumes that the sizes are in the correct traversal\n/// order.\n//////////////////////////////////////////////////////////////////////\ntemplate<int I, typename GID>\nstruct reverse_linearize\n{\n  static GID apply(GID const& m_size, size_t linear, GID gid)\n  {\n    size_t result =\n      apply_modulo<tuple_size<GID>::value-1-I>::apply(\n        tuple_ops::pop_back(m_size), linear);\n\n    result = apply_divide<I-1>::apply(m_size, result);\n\n    get<I>(gid) = result;\n\n    return reverse_linearize<I-1, GID>::apply(m_size, linear, gid);\n  }\n};\n\n\n//////////////////////////////////////////////////////////////////////\n/// @brief Base case of recursion for @ref reverse_linearize.\n/// @note Intel fails if function operator takes @p gid by reference.\n//////////////////////////////////////////////////////////////////////\ntemplate<typename GID>\nstruct reverse_linearize<-1, GID>\n{\n  static GID apply(GID const&, size_t, GID gid)\n  { return gid; }\n};\n\n\n//////////////////////////////////////////////////////////////////////\n/// @brief Small function to optimize index linearization by not\n/// performing multiplication on the first element.\n//////////////////////////////////////////////////////////////////////\ntemplate<int Idx>\nstruct conditional_multiply\n{\n  template<typename Tuple>\n  static size_t apply(Tuple const& plane_sizes, size_t lhs)\n  {\n    return lhs * get<Idx>(plane_sizes);\n  }\n};\n\n\n//////////////////////////////////////////////////////////////////////\n/// @brief Specialization for first element of tuple.  Do not perform\n/// multiplication and assert the first element in plane_sizes is 1.\n//////////////////////////////////////////////////////////////////////\ntemplate<>\nstruct conditional_multiply<0>\n{\n  template<typename Tuple>\n  static size_t apply(Tuple const& plane_sizes, size_t lhs)\n  {\n    stapl_assert(get<0>(plane_sizes) == 1, \"found last idx != 1\");\n    return lhs;\n  }\n};\n\n\n//////////////////////////////////////////////////////////////////////\n/// @brief Reorders input Indices according to provided traversal order,\n/// decrements each by corresponding value in @p first and then multiplies\n/// by corresponding value in @p plane_sizes, accumulating the results into\n/// a linearized index.\n//////////////////////////////////////////////////////////////////////\ntemplate <int Iterate, int LastIdx, typename Traversal>\nstruct reorder_localize_linearize\n{\n  template<typename Tuple, typename Index, typename... Indices>\n  static size_t apply(Tuple const& first, Tuple const& plane_sizes,\n                    Index&& i, Indices&&... is)\n\n {\n   constexpr size_t idx = std::tuple_element<Iterate, Traversal>::type::value;\n\n   return conditional_multiply<idx>::apply(\n     plane_sizes, i - std::get<idx>(first))\n     + reorder_localize_linearize<Iterate + 1, LastIdx, Traversal>::apply(\n         first, plane_sizes, std::forward<Indices>(is)...);\n  }\n};\n\n\n//////////////////////////////////////////////////////////////////////\n/// @brief Base case of the recursion.\n/// @note Traversal of the tuple occurs from 0 to tuple_size-1 for performance\n/// reasons.\n//////////////////////////////////////////////////////////////////////\ntemplate<int LastIdx, typename Traversal>\nstruct reorder_localize_linearize<LastIdx, LastIdx, Traversal>\n{\n  template<typename Tuple, typename Index>\n  static size_t apply(Tuple const& first, Tuple const& plane_sizes, Index&& i)\n  {\n    constexpr size_t idx = std::tuple_element<LastIdx, Traversal>::type::value;\n\n    return conditional_multiply<idx>::apply(\n      plane_sizes, i - std::get<idx>(first));\n  }\n};\n\n\n//////////////////////////////////////////////////////////////////////\n/// @brief Computes the factor by which a component of an n-dimensional GID\n/// should be multiplied when linearizing the GID.\n//////////////////////////////////////////////////////////////////////\ntemplate<int Iterate, int LastIdx>\nstruct compute_plane_sizes\n{\n  template <typename Tuple>\n  static void apply(Tuple const& size, Tuple& plane_size)\n  {\n    // Other indices multiplied by size of all inner dimensions.\n    std::get<Iterate>(plane_size) =\n      std::get<Iterate-1>(size)*std::get<Iterate-1>(plane_size);\n    compute_plane_sizes<Iterate+1, LastIdx>::apply(size, plane_size);\n  }\n};\n\n\n//////////////////////////////////////////////////////////////////////\n/// @brief Specialization for first iteration of @ref compute_plane_sizes.\n///\n/// The first element represents the innermost dimension of the traversal,\n/// and thus isn't multiplied by any of the other dimensions.\n/// @note Traversal of the tuple occurs from 0 to tuple_size-1 for performance\n/// reasons.\n//////////////////////////////////////////////////////////////////////\ntemplate<int LastIdx>\nstruct compute_plane_sizes<0, LastIdx>\n{\n  template <typename Tuple>\n  static void apply(Tuple const& size, Tuple& plane_size)\n  {\n    // Innermost dimension is multiplied by 1 when linearizing.\n    std::get<0>(plane_size) = 1;\n    compute_plane_sizes<1, LastIdx>::apply(size, plane_size);\n  }\n};\n\n\n//////////////////////////////////////////////////////////////////////\n/// @brief Specialization for final iteration of @ref compute_plane_sizes.\n///\n/// The last element represents the outermost dimension of the traversal,\n/// and thus is multiplied by the size of all inner dimensions when linearized.\n/// @note Traversal of the tuple occurs from 0 to tuple_size-1 for performance\n/// reasons.\n//////////////////////////////////////////////////////////////////////\ntemplate<int LastIdx>\nstruct compute_plane_sizes<LastIdx, LastIdx>\n{\n  template <typename Tuple>\n  static void apply(Tuple const& size, Tuple& plane_size)\n  {\n    // Plane size is size multiplied by size of all inner dimensions.\n    std::get<LastIdx>(plane_size) =\n      std::get<LastIdx-1>(size)*std::get<LastIdx-1>(plane_size);\n  }\n};\n\n\n//////////////////////////////////////////////////////////////////////\n/// @brief Specialization for the 1-D case.\n//////////////////////////////////////////////////////////////////////\ntemplate<>\nstruct compute_plane_sizes<0, 0>\n{\n  template <typename Tuple>\n  static void apply(Tuple const& size, Tuple& plane_size)\n  {\n    // Innermost dimension is multiplied by 1 when linearizing.\n    std::get<0>(plane_size) = 1;\n  }\n};\n\n\n//////////////////////////////////////////////////////////////////////\n/// @brief Type metafunction reflecting the reduced rank linearizer\n/// that a slice operation returns.\n//////////////////////////////////////////////////////////////////////\ntemplate<std::size_t SliceIndex, typename Traversal, typename GID>\nstruct slice_result\n{\n  using slices_tuple_t =\n    typename tuple_ops::from_index_sequence<index_sequence<SliceIndex>>::type;\n\n  using new_gid_t =\n    typename tuple_ops::result_of::heterogeneous_discard<\n      slices_tuple_t, GID>::type;\n\n  using new_traversal_t =\n    typename tuple_ops::result_of::heterogeneous_discard<\n      slices_tuple_t, Traversal>::type;\n\n  using type = nd_linearize<new_gid_t, new_traversal_t>;\n};\n\ntemplate<typename Slices, typename Traversal,\n         typename = make_index_sequence<tuple_size<Slices>::value>>\nstruct indices_of_most_significant;\n\n\n//////////////////////////////////////////////////////////////////////\n/// @brief Metafunction to compute the reordering of a Slices tuple (as a tuple\n///        of indices) in descending order of Traversal's most significant\n///        (slowest moving) dimensions.\n///\n///        When given multiple dimensions to slice at a time, we need to slice\n///        them in the order of the largest to smallest (where largest and\n///        smallest refers to their positions in the real traversal ordering).\n///\n///        For example, if Slices is <1,2,3> and Traversal is <0,2,4,3,1> then\n///        the output would be <2,0,1>.\n///\n///        This is because we compute:\n///          <4-Tr<Sl<0>>, 4-Tr<Sl<1>>, 4-Tr<Sl<2>>> =\n///          <4-Tr<1>, 4-Tr<2>, 4-Tr<3>> =\n///          <4-2, 4-4, 4-3> =\n///          <2,0,1>\n///\n///        The meaning of <2,0,1> in this case means we need to slice position\n///        1 first, then position 2, and then position 0. This boils down to\n///        calling slice<2> and then slice<3> and then slice<1>. This is\n///        necessary because in actuality, we are slicing the real dimensions of\n///        4 then 3 then 2 of the traversal, which are the most significant\n///        dimensions descending in order.\n///\n/// @note  The result of this metafunction only has meaning if the input slices\n///        indeed refer to the last |Slices| dimensions of the linearizer and\n///        it is only the order that is unknown.\n//////////////////////////////////////////////////////////////////////\ntemplate<typename Slices, typename Traversal, std::size_t... Indices>\nstruct indices_of_most_significant<Slices, Traversal,\n                                   index_sequence<Indices...>>\n{\n  static constexpr std::size_t traversal_size = tuple_size<Traversal>::value-1;\n\n  using type = tuple<std::integral_constant<std::size_t,\n    traversal_size - tuple_element<\n      tuple_element<Indices, Slices>::type::value, Traversal>::type::value\n  >...>;\n};\n\n//////////////////////////////////////////////////////////////////////\n/// @brief Compute what the rest of the slices should be based on the current\n///        slice. For example, if the incoming slices for slice() are\n///        <0,1,2>, we would need to recursively call slice<0>.slice<0>.slice<0>\n///        because we are now referring to the dimensions which are one less.\n///        However, if the incoming slices are <2,1,0>, we would instead call\n///        slice<2>.slice<1>.slice<0>.\n//////////////////////////////////////////////////////////////////////\nconstexpr std::size_t adjusted_slice(std::size_t FirstSlice,\n                                     std::size_t SecondSlice)\n{\n  return SecondSlice > FirstSlice ? SecondSlice-1 : SecondSlice;\n}\n\n} // namespace detail\n\n\n//////////////////////////////////////////////////////////////////////\n/// @brief Translates an n-dimensional @p gid to a 1-dimensional\n///        linearization, based on the given @p Traversal order.\n//////////////////////////////////////////////////////////////////////\ntemplate<typename GID, typename Traversal>\nstruct nd_linearize\n{\npublic:\n  using traversal_type = Traversal;\n  using index_type     = GID;\n  using gid_type       = size_t;\n  using size_type      = index_type;\n  using inverse        = nd_reverse_linearize<GID, Traversal>;\n  using is_bijective   = std::true_type;\n\n  static constexpr size_t last_idx = tuple_size<size_type>::value - 1;\n\n  size_type         m_size;\n\n  size_type         m_plane_sizes;\n  size_type         m_first;\n\n  /// @brief Original unreordered size kept to make slicing logic easier.\n  size_type         m_original_size;\n\n  /// @brief Original unreordered first index kept to make slicing logic easier.\n  size_type         m_original_first;\n\npublic:\n  nd_linearize(void) = default;\n\n  explicit\n  nd_linearize(size_type size)\n    : m_size(detail::traversal_order<GID, Traversal>::apply(size)), m_first(),\n      m_original_size(size), m_original_first()\n  {\n    detail::compute_plane_sizes<0, last_idx>::apply(m_size, m_plane_sizes);\n  }\n\n  explicit\n  nd_linearize(size_type size, size_type first)\n    : m_size(detail::traversal_order<GID, Traversal>::apply(size)),\n      m_first(detail::traversal_order<GID, Traversal>::apply(first)),\n      m_original_size(size), m_original_first(first)\n  {\n    detail::compute_plane_sizes<0, last_idx>::apply(m_size, m_plane_sizes);\n  }\n\n  explicit\n  nd_linearize(nd_reverse_linearize<GID, Traversal> const& other)\n    : m_size(other.m_size), m_first()\n  {\n    detail::compute_plane_sizes<0, last_idx>::apply(m_size, m_plane_sizes);\n  }\n\n\n  //////////////////////////////////////////////////////////////////////\n  /// @brief Slice a single index of the multidimensional space, fixing\n  /// its value to that of the passed @p idx parameters. Return an offset\n  /// representing the effect of the slicing operation and a reduced rank\n  /// linearizer for the remaining indices.\n  ///\n  /// @todo Consider storing offset internally in @ref nd_linearize to\n  /// better abstract behavior.\n  //////////////////////////////////////////////////////////////////////\n  template<std::size_t SliceIndex>\n  std::pair<\n    std::size_t, typename detail::slice_result<SliceIndex,Traversal,GID>::type\n  >\n  slice(size_t const& idx)\n  {\n    constexpr size_t mapped_index =\n      tuple_element<SliceIndex, Traversal>::type::value;\n\n    static_assert(mapped_index == last_idx,\n                  \"Slicing limited to last in traversal order\");\n\n    const size_t multiplier  = get<mapped_index>(m_plane_sizes);\n    const std::size_t offset = (idx - get<mapped_index>(m_first)) * multiplier;\n\n    using slice_result_t = detail::slice_result<SliceIndex,Traversal,GID>;\n    using SlicesTuple    = typename slice_result_t::slices_tuple_t;\n    using NewGID         = typename slice_result_t::new_gid_t;\n    using NewTraversal   = typename slice_result_t::new_traversal_t;\n\n    return std::make_pair(\n      offset,\n      nd_linearize<NewGID, NewTraversal>(\n        tuple_ops::heterogeneous_discard<SlicesTuple>(m_original_size),\n        tuple_ops::heterogeneous_discard<SlicesTuple>(m_original_first)));\n  }\n\n\n  //////////////////////////////////////////////////////////////////////\n  /// @brief Slice multiple indices of the multidimensional space.\n  /// Recursively called with single @p slice signature above as base case.\n  //////////////////////////////////////////////////////////////////////\n  template<std::size_t FirstSlice, std::size_t SecondSlice,\n           std::size_t... Slices, typename Fixed>\n    std::pair<std::size_t,\n              decltype(\n                std::declval<\n                  typename detail::slice_result<\n                    FirstSlice, Traversal, GID>::type\n                >().template slice<\n                    detail::adjusted_slice(FirstSlice, SecondSlice),\n                    detail::adjusted_slice(FirstSlice, Slices)...\n                  >(\n                  tuple_ops::heterogeneous_discard<\n                    tuple<std::integral_constant<size_t, 0>>\n                  >(std::declval<Fixed>())).second)>\n  slice(Fixed const& fixed)\n  {\n    using discard_tuple_t = tuple<std::integral_constant<size_t, 0>>;\n\n    auto p = slice<FirstSlice>(get<0>(fixed));\n\n    auto q = (p.second).template slice<\n      detail::adjusted_slice(FirstSlice, SecondSlice),\n      detail::adjusted_slice(FirstSlice, Slices)...>(\n        tuple_ops::heterogeneous_discard<discard_tuple_t>(fixed)\n      );\n\n    return std::make_pair(p.first + q.first, q.second);\n  }\n\nprivate:\n  //////////////////////////////////////////////////////////////////////\n  /// @brief Slice multiple indices of the multidimensional space.\n  ///    Specialization when Slices is an index_sequence\n  //////////////////////////////////////////////////////////////////////\n  template<std::size_t... Slices, typename Fixed>\n  auto slice_impl(index_sequence<Slices...>, Fixed const& fixed)\n    -> decltype(this->template slice<Slices...>(fixed))\n  {\n    return this->template slice<Slices...>(fixed);\n  }\n\npublic:\n\n  //////////////////////////////////////////////////////////////////////\n  /// @brief Slice multiple indices of the multidimensional space.\n  ///        Specialization when Slices is a tuple of integral constants\n  ///\n  ///        When slicing multiple indices at a time, we first need to rearrange\n  ///        the slice dimensions to match the most significant dimensions of\n  ///        the traversal.\n  ///\n  /// @tparam Slices Tuple of integral constants\n  /// @param fixed The indices to fix in the slice\n  //////////////////////////////////////////////////////////////////////\n  template<typename Slices, typename Fixed>\n  auto slice(Fixed const& fixed) ->\n    decltype(this->slice_impl(typename tuple_ops::to_index_sequence<\n      typename tuple_ops::result_of::rearrange<Slices,\n        typename detail::indices_of_most_significant<Slices, Traversal>::type\n      >::type\n    >::type(), fixed))\n  {\n    // Rearrange the tuple of fixed values\n    auto reordered_fixed = detail::traversal_order<Fixed,\n      typename detail::indices_of_most_significant<Slices, Traversal>::type\n    >::apply(fixed);\n\n    // Rearrange the compile-time tuple of slices\n    using reordered_slices = typename tuple_ops::to_index_sequence<\n      typename tuple_ops::result_of::rearrange<\n        Slices,\n        typename detail::indices_of_most_significant<Slices, Traversal>::type\n      >::type\n    >::type;\n\n    return this->slice_impl(reordered_slices(), reordered_fixed);\n  }\n\npublic:\n  //////////////////////////////////////////////////////////////////////\n  /// @brief Localize and then linearize the indices that are the components\n  /// of an n-dimensional GID.\n  //////////////////////////////////////////////////////////////////////\n  template <typename... Indices>\n  gid_type operator()(Indices const&... is) const\n  {\n    return detail::reorder_localize_linearize<0, last_idx, Traversal>::apply(\n      m_first, m_plane_sizes, is...);\n  }\n\nprivate:\n  template<std::size_t... I>\n  gid_type\n  linearize_impl(index_type const& gid, index_sequence<I...> const&) const\n  {\n    return detail::reorder_localize_linearize<0, last_idx, Traversal>::apply(\n      m_first, m_plane_sizes, std::get<I>(gid)...);\n  }\n\npublic:\n  //////////////////////////////////////////////////////////////////////\n  /// Localize and then linearize the n-dimensional GID provided.\n  //////////////////////////////////////////////////////////////////////\n  template<typename Indices =\n             make_index_sequence<tuple_size<index_type>::value>>\n  gid_type operator()(index_type const& gid) const\n  {\n    return linearize_impl(gid, Indices());\n  }\n\n  void define_type(typer& t)\n  {\n    t.member(m_size);\n    t.member(m_plane_sizes);\n    t.member(m_first);\n    t.member(m_original_size);\n    t.member(m_original_first);\n  }\n}; // struct nd_linearize\n\n\n//////////////////////////////////////////////////////////////////////\n/// @brief Base case for @ref nd_linearize for 1-dimensional GID.\n///\n/// @todo Possibly use of the f_ident mapping function for this.\n//////////////////////////////////////////////////////////////////////\ntemplate<typename Traversal>\nstruct nd_linearize<size_t, Traversal>\n{\n  using index_type = std::size_t;\n  using traversal_type = Traversal;\n\n  size_t m_size;\n  size_t m_original_size;\n  size_t m_original_first;\n  size_t m_first;\n\n  nd_linearize(void)\n    : m_first(0)\n  { }\n\n  explicit\n  nd_linearize(size_t)\n    : m_first(0)\n  { }\n\n  explicit\n  nd_linearize(size_t size, size_t first)\n    : m_size(size), m_original_size(size), m_original_first(first),\n      m_first(first)\n  { }\n\n  size_t operator()(size_t gid) const\n  { return gid - m_first; }\n\n  void define_type(typer& t)\n  {\n    t.member(m_size);\n    t.member(m_original_size);\n    t.member(m_original_first);\n    t.member(m_first);\n  }\n};\n\n\n//////////////////////////////////////////////////////////////////////\n/// @brief Translates a 1-dimensional linearized GID to its\n///        n-dimensional GID, based on the given @p Traversal order.\n//////////////////////////////////////////////////////////////////////\ntemplate<typename GID, typename Traversal>\nstruct nd_reverse_linearize\n{\n  typedef GID                               gid_type;\n  typedef gid_type                          result_type;\n  typedef std::size_t                       index_type;\n  typedef gid_type                          size_type;\n  typedef nd_linearize<GID, Traversal>      inverse;\n  typedef std::true_type is_bijective;\n\n  enum { last_idx = tuple_size<size_type>::value - 1 };\n\n  size_type m_size;\n\n  //////////////////////////////////////////////////////////////////////\n  /// @todo Is the default constructor needed? if it is size should be\n  ///       correctly initialized (default constructed in domain.hpp).\n  //////////////////////////////////////////////////////////////////////\n  nd_reverse_linearize(void) = default;\n\n  explicit\n  nd_reverse_linearize(size_type const& size)\n    : m_size(detail::traversal_order<gid_type, Traversal>::apply(size))\n  { }\n\n  explicit\n  nd_reverse_linearize(nd_linearize<GID, Traversal> const& other)\n    : m_size(other.m_size)\n  { }\n\n  //////////////////////////////////////////////////////////////////////\n  /// @todo merge calls to inverse_linearizer_t::operator() and\n  /// inverse_index_order_t::operator() into a single call\n  /// to minimize the number of traversals of the tuple.\n  //////////////////////////////////////////////////////////////////////\n  gid_type operator()(index_type linear) const\n  {\n    return detail::reverse_traversal_order<gid_type, Traversal>::apply(\n      detail::reverse_linearize<last_idx, gid_type>::apply(\n        m_size, linear, gid_type())\n    );\n  }\n\n  void define_type(typer& t)\n  {\n    t.member(m_size);\n  }\n}; // struct nd_reverse_linearize\n\n\n//////////////////////////////////////////////////////////////////////\n/// @brief Base case for @ref nd_reverse_linearize for 1-dimensional GID.\n///\n/// @todo Possible use of the f_ident mapping function for this.\n//////////////////////////////////////////////////////////////////////\ntemplate<typename Traversal>\nstruct nd_reverse_linearize<size_t, Traversal>\n{\n  nd_reverse_linearize(void) = default;\n\n  explicit\n  nd_reverse_linearize(size_t)\n  { }\n\n  size_t operator()(size_t linear) const\n  { return linear; }\n};\n\n} // namespace stapl\n\n#endif // STAPL_MAPFUNCS_LINEARIZATION_HPP\n", "meta": {"hexsha": "acbebf633cc1d03a483ed9817260db2be912f726", "size": 26937, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "stapl_release/stapl/views/mapping_functions/linearization.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/views/mapping_functions/linearization.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/views/mapping_functions/linearization.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": 34.667953668, "max_line_length": 80, "alphanum_fraction": 0.5749712292, "num_tokens": 5602, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6757646010190476, "lm_q2_score": 0.5117166047041654, "lm_q1q2_score": 0.345799967212732}}
{"text": "#ifndef SKYLARK_GEMM_HPP\n#define SKYLARK_GEMM_HPP\n\n#include <boost/mpi.hpp>\n#include \"exception.hpp\"\n#include \"sparse_matrix.hpp\"\n#include \"computed_matrix.hpp\"\n#include \"../utility/typer.hpp\"\n\n#include \"Gemm_detail.hpp\"\n\n// Defines a generic Gemm function that receives both dense and sparse matrices.\n\nnamespace skylark { namespace base {\n\n/**\n * Rename the elemental Gemm function, so that we have unified access.\n */\n\ntemplate<typename T>\ninline void Gemm(elem::Orientation oA, elem::Orientation oB,\n    T alpha, const elem::Matrix<T>& A, const elem::Matrix<T>& B,\n    T beta, elem::Matrix<T>& C) {\n    elem::Gemm(oA, oB, alpha, A, B, beta, C);\n}\n\ntemplate<typename T>\ninline void Gemm(elem::Orientation oA, elem::Orientation oB,\n    T alpha, const elem::Matrix<T>& A, const elem::Matrix<T>& B,\n    elem::Matrix<T>& C) {\n    elem::Gemm(oA, oB, alpha, A, B, C);\n}\n\ntemplate<typename T>\ninline void Gemm(elem::Orientation oA, elem::Orientation oB,\n    T alpha, const elem::DistMatrix<T, elem::STAR, elem::STAR>& A,\n    const elem::DistMatrix<T, elem::STAR, elem::STAR>& B,\n    T beta, elem::DistMatrix<T, elem::STAR, elem::STAR>& C) {\n    elem::Gemm(oA, oB, alpha, A.LockedMatrix(), B.LockedMatrix(), beta, C.Matrix());\n}\n\ntemplate<typename T>\ninline void Gemm(elem::Orientation oA, elem::Orientation oB,\n    T alpha, const elem::DistMatrix<T, elem::STAR, elem::STAR>& A,\n    const elem::DistMatrix<T, elem::STAR, elem::STAR>& B,\n    elem::DistMatrix<T, elem::STAR, elem::STAR>& C) {\n    elem::Gemm(oA, oB, alpha, A.LockedMatrix(), B.LockedMatrix(), C.Matrix());\n}\n\ntemplate<typename T>\ninline void Gemm(elem::Orientation oA, elem::Orientation oB,\n    T alpha, const elem::DistMatrix<T>& A, const elem::DistMatrix<T>& B,\n    T beta, elem::DistMatrix<T>& C) {\n    elem::Gemm(oA, oB, alpha, A, B, beta, C);\n}\n\ntemplate<typename T>\ninline void Gemm(elem::Orientation oA, elem::Orientation oB,\n    T alpha, const elem::DistMatrix<T>& A, const elem::DistMatrix<T>& B,\n    elem::DistMatrix<T>& C) {\n    elem::Gemm(oA, oB, alpha, A, B, C);\n}\n\n/**\n * The following combinations is not offered by Elemental, but is useful for us.\n * We implement it partially.\n */\n\ntemplate<typename T>\ninline void Gemm(elem::Orientation oA, elem::Orientation oB,\n    T alpha, const elem::DistMatrix<T, elem::VC, elem::STAR>& A,\n    const elem::DistMatrix<T, elem::VC, elem::STAR>& B,\n    T beta, elem::DistMatrix<T, elem::STAR, elem::STAR>& C) {\n    // TODO verify sizes etc.\n\n    if ((oA == elem::TRANSPOSE || oA == elem::ADJOINT) && oB == elem::NORMAL) {\n        boost::mpi::communicator comm(C.Grid().Comm(), boost::mpi::comm_attach);\n        elem::Matrix<T> Clocal(C.Matrix());\n        elem::Gemm(oA, elem::NORMAL,\n            alpha, A.LockedMatrix(), B.LockedMatrix(),\n            beta / T(comm.size()), Clocal);\n        boost::mpi::all_reduce(comm,\n            Clocal.Buffer(), Clocal.MemorySize(), C.Matrix().Buffer(),\n            std::plus<T>());\n    } else {\n        SKYLARK_THROW_EXCEPTION(base::unsupported_base_operation());\n    }\n}\n\ntemplate<typename T>\ninline void Gemm(elem::Orientation oA, elem::Orientation oB,\n    T alpha, const elem::DistMatrix<T, elem::VC, elem::STAR>& A,\n    const elem::DistMatrix<T, elem::VC, elem::STAR>& B,\n    elem::DistMatrix<T, elem::STAR, elem::STAR>& C) {\n\n    int C_height = (oA == elem::NORMAL ? A.Height() : A.Width());\n    int C_width = (oB == elem::NORMAL ? B.Width() : B.Height());\n    elem::Zeros(C, C_height, C_width);\n    base::Gemm(oA, oB, alpha, A, B, T(0), C);\n}\n\ntemplate<typename T>\ninline void Gemm(elem::Orientation oA, elem::Orientation oB,\n    T alpha, const elem::DistMatrix<T, elem::VC, elem::STAR>& A,\n    const elem::DistMatrix<T, elem::STAR, elem::STAR>& B,\n    T beta, elem::DistMatrix<T, elem::VC, elem::STAR>& C) {\n    // TODO verify sizes etc.\n\n    if (oA == elem::NORMAL && oB == elem::NORMAL) {\n        elem::Gemm(elem::NORMAL, elem::NORMAL,\n            alpha, A.LockedMatrix(), B.LockedMatrix(),\n            beta, C.Matrix());\n    } else {\n        SKYLARK_THROW_EXCEPTION(base::unsupported_base_operation());\n    }\n}\n\ntemplate<typename T>\ninline void Gemm(elem::Orientation oA, elem::Orientation oB,\n    T alpha, const elem::DistMatrix<T, elem::VC, elem::STAR>& A,\n    const elem::DistMatrix<T, elem::STAR, elem::STAR>& B,\n    elem::DistMatrix<T, elem::VC, elem::STAR>& C) {\n\n    int C_height = (oA == elem::NORMAL ? A.Height() : A.Width());\n    int C_width = (oB == elem::NORMAL ? B.Width() : B.Height());\n    elem::Zeros(C, C_height, C_width);\n    base::Gemm(oA, oB, alpha, A, B, T(0), C);\n}\n\n\ntemplate<typename T>\ninline void Gemm(elem::Orientation oA, elem::Orientation oB,\n    T alpha, const elem::DistMatrix<T, elem::VR, elem::STAR>& A,\n    const elem::DistMatrix<T, elem::VR, elem::STAR>& B,\n    T beta, elem::DistMatrix<T, elem::STAR, elem::STAR>& C) {\n    // TODO verify sizes etc.\n\n    if ((oA == elem::TRANSPOSE || oA == elem::ADJOINT) && oB == elem::NORMAL) {\n        boost::mpi::communicator comm(C.Grid().Comm(), boost::mpi::comm_attach);\n        elem::Matrix<T> Clocal(C.Matrix());\n        elem::Gemm(oA, elem::NORMAL,\n            alpha, A.LockedMatrix(), B.LockedMatrix(),\n            beta / T(comm.size()), Clocal);\n        boost::mpi::all_reduce(comm,\n            Clocal.Buffer(), Clocal.MemorySize(), C.Matrix().Buffer(),\n            std::plus<T>());\n    } else {\n        SKYLARK_THROW_EXCEPTION(base::unsupported_base_operation());\n    }\n}\n\ntemplate<typename T>\ninline void Gemm(elem::Orientation oA, elem::Orientation oB,\n    T alpha, const elem::DistMatrix<T, elem::VR, elem::STAR>& A,\n    const elem::DistMatrix<T, elem::VR, elem::STAR>& B,\n    elem::DistMatrix<T, elem::STAR, elem::STAR>& C) {\n\n    int C_height = (oA == elem::NORMAL ? A.Height() : A.Width());\n    int C_width = (oB == elem::NORMAL ? B.Width() : B.Height());\n    elem::Zeros(C, C_height, C_width);\n    base::Gemm(oA, oB, alpha, A, B, T(0), C);\n}\n\ntemplate<typename T>\ninline void Gemm(elem::Orientation oA, elem::Orientation oB,\n    T alpha, const elem::DistMatrix<T, elem::VR, elem::STAR>& A,\n    const elem::DistMatrix<T, elem::STAR, elem::STAR>& B,\n    T beta, elem::DistMatrix<T, elem::VR, elem::STAR>& C) {\n    // TODO verify sizes etc.\n\n    if (oA == elem::NORMAL && oB == elem::NORMAL) {\n        elem::Gemm(elem::NORMAL, elem::NORMAL,\n            alpha, A.LockedMatrix(), B.LockedMatrix(),\n            beta, C.Matrix());\n    } else {\n        SKYLARK_THROW_EXCEPTION(base::unsupported_base_operation());\n    }\n}\n\ntemplate<typename T>\ninline void Gemm(elem::Orientation oA, elem::Orientation oB,\n    T alpha, const elem::DistMatrix<T, elem::VR, elem::STAR>& A,\n    const elem::DistMatrix<T, elem::STAR, elem::STAR>& B,\n    elem::DistMatrix<T, elem::VR, elem::STAR>& C) {\n\n    int C_height = (oA == elem::NORMAL ? A.Height() : A.Width());\n    int C_width = (oB == elem::NORMAL ? B.Width() : B.Height());\n    elem::Zeros(C, C_height, C_width);\n    base::Gemm(oA, oB, alpha, A, B, T(0), C);\n}\n\n/**\n * Gemm between mixed elemental, sparse input. Output is dense elemental.\n */\n\ntemplate<typename T>\ninline void Gemm(elem::Orientation oA, elem::Orientation oB,\n    T alpha, const elem::Matrix<T>& A, const sparse_matrix_t<T>& B,\n    T beta, elem::Matrix<T>& C) {\n    // TODO verify sizes etc.\n\n    const int* indptr = B.indptr();\n    const int* indices = B.indices();\n    const T *values = B.locked_values();\n\n    int k = A.Width();\n    int n = B.width();\n    int m = A.Height();\n\n    if (oA == elem::ADJOINT && std::is_same<T, elem::Base<T> >::value)\n        oA = elem::TRANSPOSE;\n\n    if (oB == elem::ADJOINT && std::is_same<T, elem::Base<T> >::value)\n        oB = elem::TRANSPOSE;\n\n    if (oA == elem::ADJOINT || oB == elem::ADJOINT)\n        SKYLARK_THROW_EXCEPTION(base::unsupported_base_operation());\n\n    // NN\n    if (oA == elem::NORMAL && oB == elem::NORMAL) {\n\n        elem::Scal(beta, C);\n\n        elem::Matrix<T> Ac;\n        elem::Matrix<T> Cc;\n\n#       if SKYLARK_HAVE_OPENMP\n#       pragma omp parallel for private(Cc, Ac)\n#       endif\n        for(int col = 0; col < n; col++) {\n            elem::View(Cc, C, 0, col, m, 1);\n            for (int j = indptr[col]; j < indptr[col + 1]; j++) {\n                int row = indices[j];\n                T val = values[j];\n                elem::LockedView(Ac, A, 0, row, m, 1);\n                elem::Axpy(alpha * val, Ac, Cc);\n            }\n        }\n    }\n\n    // NT\n    if (oA == elem::NORMAL && oB == elem::TRANSPOSE) {\n\n        elem::Scal(beta, C);\n\n        elem::Matrix<T> Ac;\n        elem::Matrix<T> Cc;\n\n        // Now, we simply think of B has being in CSR mode...\n        int row = 0;\n        for(int row = 0; row < n; row++) {\n            elem::LockedView(Ac, A, 0, row, m, 1);\n#           if SKYLARK_HAVE_OPENMP\n#           pragma omp parallel for private(Cc)\n#           endif\n            for (int j = indptr[row]; j < indptr[row + 1]; j++) {\n                int col = indices[j];\n                T val = values[j];\n                elem::View(Cc, C, 0, col, m, 1);\n                elem::Axpy(alpha * val, Ac, Cc);\n            }\n        }\n    }\n\n\n    // TN - TODO: Not tested!\n    if (oA == elem::TRANSPOSE && oB == elem::NORMAL) {\n        double *c = C.Buffer();\n        int ldc = C.LDim();\n\n        const double *a = A.LockedBuffer();\n        int lda = A.LDim();\n\n#       if SKYLARK_HAVE_OPENMP\n#       pragma omp parallel for collapse(2)\n#       endif\n        for (int j = 0; j < n; j++)\n            for(int row = 0; row < k; row++) {\n                c[j * ldc + row] *= beta;\n                 for (int l = indptr[j]; l < indptr[j + 1]; l++) {\n                     int rr = indices[l];\n                     T val = values[l];\n                     c[j * ldc + row] += val * a[j * lda + rr];\n                 }\n            }\n    }\n\n    // TT - TODO: Not tested!\n    if (oA == elem::TRANSPOSE && oB == elem::TRANSPOSE) {\n        elem::Scal(beta, C);\n\n        double *c = C.Buffer();\n        int ldc = C.LDim();\n\n        const double *a = A.LockedBuffer();\n        int lda = A.LDim();\n\n#       if SKYLARK_HAVE_OPENMP\n#       pragma omp parallel for\n#       endif\n        for(int row = 0; row < k; row++)\n            for(int rb = 0; rb < n; rb++)\n                for (int l = indptr[rb]; l < indptr[rb + 1]; l++) {\n                    int col = indices[l];\n                    c[col * ldc + row] += values[l] * a[row * lda + rb];\n                }\n    }\n}\n\ntemplate<typename T>\ninline void Gemm(elem::Orientation oA, elem::Orientation oB,\n    T alpha, const sparse_matrix_t<T>& A, const elem::Matrix<T>& B,\n    T beta, elem::Matrix<T>& C) {\n    // TODO verify sizes etc.\n\n    const int* indptr = A.indptr();\n    const int* indices = A.indices();\n    const double *values = A.locked_values();\n\n    int k = A.width();\n    int n = B.Width();\n    int m = B.Height();\n\n    if (oA == elem::ADJOINT && std::is_same<T, elem::Base<T> >::value)\n        oA = elem::TRANSPOSE;\n\n    if (oB == elem::ADJOINT && std::is_same<T, elem::Base<T> >::value)\n        oB = elem::TRANSPOSE;\n\n    // NN\n    if (oA == elem::NORMAL && oB == elem::NORMAL) {\n\n        elem::Scal(beta, C);\n\n        double *c = C.Buffer();\n        int ldc = C.LDim();\n\n        const double *b = B.LockedBuffer();\n        int ldb = B.LDim();\n\n#       if SKYLARK_HAVE_OPENMP\n#       pragma omp parallel for\n#       endif\n        for(int i = 0; i < n; i++)\n            for(int col = 0; col < k; col++)\n                 for (int j = indptr[col]; j < indptr[col + 1]; j++) {\n                     int row = indices[j];\n                     T val = values[j];\n                     c[i * ldc + row] += alpha * val * b[i * ldb + col];\n                 }\n    }\n\n    // NT\n    if (oA == elem::NORMAL && (oB == elem::TRANSPOSE || oB == elem::ADJOINT)) {\n\n        elem::Scal(beta, C);\n\n        elem::Matrix<T> Bc;\n        elem::Matrix<T> BTr;\n        elem::Matrix<T> Cr;\n\n        for(int col = 0; col < k; col++) {\n            elem::LockedView(Bc, B, 0, col, m, 1);\n            elem::Transpose(Bc, BTr, oB == elem::ADJOINT);\n#           if SKYLARK_HAVE_OPENMP\n#           pragma omp parallel for private(Cr)\n#           endif\n            for (int j = indptr[col]; j < indptr[col + 1]; j++) {\n                int row = indices[j];\n                T val = values[j];\n                elem::View(Cr, C, row, 0, 1, m);\n                elem::Axpy(alpha * val, BTr, Cr);\n            }\n        }\n    }\n\n    // TN - TODO: Not tested!\n    if (oA == elem::TRANSPOSE && oB == elem::NORMAL) {\n        double *c = C.Buffer();\n        int ldc = C.LDim();\n\n        const double *b = B.LockedBuffer();\n        int ldb = B.LDim();\n\n#       if SKYLARK_HAVE_OPENMP\n#       pragma omp parallel for collapse(2)\n#       endif\n        for (int j = 0; j < n; j++)\n            for(int row = 0; row < k; row++) {\n                c[j * ldc + row] *= beta;\n                 for (int l = indptr[row]; l < indptr[row + 1]; l++) {\n                     int col = indices[l];\n                     T val = values[l];\n                     c[j * ldc + row] += val * b[j * ldb + col];\n                 }\n            }\n    }\n\n    // AN - TODO: Not tested!\n    if (oA == elem::ADJOINT && oB == elem::NORMAL) {\n        double *c = C.Buffer();\n        int ldc = C.LDim();\n\n        const double *b = B.LockedBuffer();\n        int ldb = B.LDim();\n\n#       if SKYLARK_HAVE_OPENMP\n#       pragma omp parallel for collapse(2)\n#       endif\n        for (int j = 0; j < n; j++)\n            for(int row = 0; row < k; row++) {\n                c[j * ldc + row] *= beta;\n                 for (int l = indptr[row]; l < indptr[row + 1]; l++) {\n                     int col = indices[l];\n                     T val = elem::Conj(values[l]);\n                     c[j * ldc + row] += val * b[j * ldb + col];\n                 }\n            }\n    }\n\n\n    // TT - TODO: Not tested!\n    if (oA == elem::TRANSPOSE && (oB == elem::TRANSPOSE || oB == elem::ADJOINT)) {\n\n        elem::Scal(beta, C);\n\n        elem::Matrix<T> Bc;\n        elem::Matrix<T> BTr;\n        elem::Matrix<T> Cr;\n\n#       if SKYLARK_HAVE_OPENMP\n#       pragma omp parallel for private(Cr, Bc, BTr)\n#       endif\n        for(int row = 0; row < k; row++) {\n            elem::View(Cr, C, row, 0, 1, m);\n            for (int l = indptr[row]; l < indptr[row + 1]; l++) {\n                int col = indices[l];\n                T val = values[l];\n                elem::LockedView(Bc, B, 0, col, m, 1);\n                elem::Transpose(Bc, BTr, oB == elem::ADJOINT);\n                elem::Axpy(alpha * val, BTr, Cr);\n            }\n        }\n    }\n\n    // AT - TODO: Not tested!\n    if (oA == elem::ADJOINT && (oB == elem::TRANSPOSE || oB == elem::ADJOINT)) {\n\n        elem::Scal(beta, C);\n\n        elem::Matrix<T> Bc;\n        elem::Matrix<T> BTr;\n        elem::Matrix<T> Cr;\n\n#       if SKYLARK_HAVE_OPENMP\n#       pragma omp parallel for private(Cr, Bc, BTr)\n#       endif\n        for(int row = 0; row < k; row++) {\n            elem::View(Cr, C, row, 0, 1, m);\n            for (int l = indptr[row]; l < indptr[row + 1]; l++) {\n                int col = indices[l];\n                T val = elem::Conj(values[l]);\n                elem::LockedView(Bc, B, 0, col, m, 1);\n                elem::Transpose(Bc, BTr, oB == elem::ADJOINT);\n                elem::Axpy(alpha * val, BTr, Cr);\n            }\n        }\n    }\n}\n\ntemplate<typename T>\ninline void Gemm(elem::Orientation oA, elem::Orientation oB,\n    T alpha, const sparse_matrix_t<T>& A, const elem::Matrix<T>& B,\n    elem::Matrix<T>& C) {\n    int C_height = (oA == elem::NORMAL ? A.height() : A.width());\n    int C_width = (oB == elem::NORMAL ? B.Width() : B.Height());\n    elem::Zeros(C, C_height, C_width);\n    base::Gemm(oA, oB, alpha, A, B, T(0), C);\n}\n\n#if SKYLARK_HAVE_COMBBLAS\n/**\n * Mixed GEMM for Elemental and CombBLAS matrices. For a distributed Elemental\n * input matrix, the output has the same distribution.\n */\n\n/// Gemm for distCombBLAS x distElemental(* / *) -> distElemental (SOMETHING / *)\ntemplate<typename index_type, typename value_type, elem::Distribution col_d>\nvoid Gemm(elem::Orientation oA, elem::Orientation oB, double alpha,\n          const SpParMat<index_type, value_type, SpDCCols<index_type, value_type> > &A,\n          const elem::DistMatrix<value_type, elem::STAR, elem::STAR> &B,\n          double beta,\n          elem::DistMatrix<value_type, col_d, elem::STAR> &C) {\n\n    if(oA == elem::NORMAL && oB == elem::NORMAL) {\n\n        if(A.getnol() != B.Height())\n            SKYLARK_THROW_EXCEPTION (\n                base::combblas_exception()\n                    << base::error_msg(\"Gemm: Dimensions do not agree\"));\n\n        if(A.getnrow() != C.Height())\n            SKYLARK_THROW_EXCEPTION (\n                base::combblas_exception()\n                    << base::error_msg(\"Gemm: Dimensions do not agree\"));\n\n        if(B.Width() != C.Width())\n            SKYLARK_THROW_EXCEPTION (\n                base::combblas_exception()\n                    << base::error_msg(\"Gemm: Dimensions do not agree\"));\n\n        //XXX: simple heuristic to decide what to communicate (improve!)\n        //     or just if A.getncol() < B.Width..\n        if(A.getnnz() < B.Height() * B.Width())\n            detail::outer_panel_mixed_gemm_impl_nn(alpha, A, B, beta, C);\n        else\n            detail::inner_panel_mixed_gemm_impl_nn(alpha, A, B, beta, C);\n    }\n}\n\n/// Gemm for distCombBLAS x distElemental(SOMETHING / *) -> distElemental (* / *)\ntemplate<typename index_type, typename value_type, elem::Distribution col_d>\nvoid Gemm(elem::Orientation oA, elem::Orientation oB, double alpha,\n          const SpParMat<index_type, value_type, SpDCCols<index_type, value_type> > &A,\n          const elem::DistMatrix<value_type, col_d, elem::STAR> &B,\n          double beta,\n          elem::DistMatrix<value_type, elem::STAR, elem::STAR> &C) {\n\n    if(oA == elem::TRANSPOSE && oB == elem::NORMAL) {\n\n        if(A.getrow() != B.Height())\n            SKYLARK_THROW_EXCEPTION (\n                base::combblas_exception()\n                    << base::error_msg(\"Gemm: Dimensions do not agree\"));\n\n        if(A.getncol() != C.Height())\n            SKYLARK_THROW_EXCEPTION (\n                    base::combblas_exception()\n                    << base::error_msg(\"Gemm: Dimensions do not agree\"));\n\n        if(B.Width() != C.Width())\n            SKYLARK_THROW_EXCEPTION (\n                base::combblas_exception()\n                    << base::error_msg(\"Gemm: Dimensions do not agree\"));\n\n        detail::outer_panel_mixed_gemm_impl_tn(alpha, A, B, beta, C);\n    }\n\n}\n\n#endif // SKYLARK_HAVE_COMBBLAS\n\n/* All combinations with computed matrix */\n\ntemplate<typename CT, typename RT, typename OT>\ninline void Gemm(elem::Orientation oA, elem::Orientation oB,\n    typename utility::typer_t<OT>::value_type alpha, const computed_matrix_t<CT>& A,\n    const RT& B, typename utility::typer_t<OT>::value_type beta, OT& C) {\n    base::Gemm(oA, oB, alpha, A.materialize(), B, beta, C);\n}\n\ntemplate<typename CT, typename RT, typename OT>\ninline void Gemm(elem::Orientation oA, elem::Orientation oB,\n    typename utility::typer_t<OT>::value_type alpha, const computed_matrix_t<CT>& A,\n    const RT& B, OT& C) {\n    base::Gemm(oA, oB, alpha, A.materialize(), B, C);\n}\n\ntemplate<typename CT, typename RT, typename OT>\ninline void Gemm(elem::Orientation oA, elem::Orientation oB,\n    typename utility::typer_t<OT>::value_type alpha, const RT& A,\n    const computed_matrix_t<CT>& B,\n    typename utility::typer_t<OT>::value_type beta, OT& C) {\n    base::Gemm(oA, oB, alpha, A, B.materialize(), beta, C);\n}\n\ntemplate<typename CT, typename RT, typename OT>\ninline void Gemm(elem::Orientation oA, elem::Orientation oB,\n    typename utility::typer_t<OT>::value_type alpha, const RT& A,\n    const computed_matrix_t<CT>& B, OT& C) {\n    base::Gemm(oA, oB, alpha, A, B.materialize(), C);\n}\n\ntemplate<typename CT1, typename CT2, typename OT>\ninline void Gemm(elem::Orientation oA, elem::Orientation oB,\n    typename utility::typer_t<OT>::value_type alpha, const computed_matrix_t<CT1>& A,\n    const computed_matrix_t<CT2>& B, typename utility::typer_t<OT>::value_type beta,\n    OT& C) {\n    base::Gemm(oA, oB, alpha, A.materialize(), B.materialize(), beta, C);\n}\n\ntemplate<typename CT1, typename CT2, typename OT>\ninline void Gemm(elem::Orientation oA, elem::Orientation oB,\n    typename utility::typer_t<OT>::value_type alpha, const computed_matrix_t<CT1>& A,\n    const computed_matrix_t<CT2>& B, OT& C) {\n    base::Gemm(oA, oB, alpha, A.materialize(), B.materialize(), C);\n}\n\n\n} } // namespace skylark::base\n#endif // SKYLARK_GEMM_HPP\n", "meta": {"hexsha": "a4bf5d72a97517a438bdacbf7f3980a912003f88", "size": 20505, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "base/Gemm.hpp", "max_stars_repo_name": "wangg12/libskylark", "max_stars_repo_head_hexsha": "e8836190be854d0284d38772c48e110b3c6d5e51", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-06-12T07:26:43.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-12T07:26:47.000Z", "max_issues_repo_path": "base/Gemm.hpp", "max_issues_repo_name": "cjiyer/libskylark", "max_issues_repo_head_hexsha": "e8836190be854d0284d38772c48e110b3c6d5e51", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "base/Gemm.hpp", "max_forks_repo_name": "cjiyer/libskylark", "max_forks_repo_head_hexsha": "e8836190be854d0284d38772c48e110b3c6d5e51", "max_forks_repo_licenses": ["Apache-2.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.061461794, "max_line_length": 87, "alphanum_fraction": 0.5573274811, "num_tokens": 5845, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6757646010190476, "lm_q2_score": 0.5117166047041652, "lm_q1q2_score": 0.34579996721273193}}
{"text": "#include <algorithm>\n#include <iostream>\n#include <queue>\n#include <vector>\n#include <set>\n#include <map>\n#include <random>\n#include <boost/pending/disjoint_sets.hpp>\n\nnamespace sublevel {\ntypedef std::vector<std::vector<int>> Graph;\n\nstruct Ans {\n    Ans(int e, int d, int es, int ds) \n        : eat(e), death(d), eat_size(es), death_size(ds), \n        total_height(0.0) {\n    }\n    int eat;\n    int death;\n    int eat_size;\n    int death_size;\n    float total_height;\n};\n\nclass RootedForest {\npublic:\n    Graph tree_;\n    std::vector<int> pred_;\n    std::vector<int> height_;\n\n    explicit RootedForest(Graph tree) : tree_(tree) {\n    }\n\n    void Initilize() {\n        pred_.resize(tree_.size(), -1);\n        height_.resize(tree_.size(), -1);\n        std::queue<int> que;\n        size_t counter = 0;\n        while (counter < tree_.size()) {\n            if (que.empty()) {\n                int next_start = 0;\n                while (height_[next_start] != -1) {\n                    ++next_start;\n                }\n                que.push(next_start);\n                ++counter;\n                height_[next_start] = 0;\n            }\n            while (!que.empty()) {\n                int current = que.front();\n                que.pop();\n                for (auto neu : tree_[current]) {\n                    if (height_[neu] == -1) {\n                        height_[neu] = height_[current] + 1;\n                        pred_[neu] = current;\n                        que.push(neu);\n                        ++counter;\n                    }\n                }\n            }\n        }\n    }\n\n    bool GetWay (int lhs, int rhs, std::vector<int>& answer) {\n        std::vector<int> left_way;\n        std::vector<int> right_way;\n        while (height_[lhs] > height_[rhs]) {\n            left_way.push_back(lhs);\n            lhs = pred_[lhs];\n        }\n        while (height_[lhs] < height_[rhs]) {\n            right_way.push_back(rhs);\n            rhs = pred_[rhs];\n        }\n        while ((lhs != -1 && rhs != -1) && lhs != rhs) {\n            left_way.push_back(lhs);\n            lhs = pred_[lhs];\n            right_way.push_back(rhs);\n            rhs = pred_[rhs];                        \n        }\n        if (lhs != -1 && rhs != -1) {\n            for (size_t step = 0; step < left_way.size(); ++step) {\n                answer.push_back(left_way[step]);\n            }\n            answer.push_back(lhs);\n            for (size_t step = right_way.size(); step > 0; --step) {\n                answer.push_back(right_way[step - 1]);\n            }\n            return true;\n        }\n        return false;\n    }\n};\n\nclass VirtualCloud { \npublic:\n    float* values_;\n    size_t cloud_size_;\n    std::vector<int> order_;\n    std::set<int> trash_;\n    Graph graph_;\n    Graph minima_graph_;\n    VirtualCloud(float* val, size_t size) : values_(val), cloud_size_(size) {\n    }\n    virtual ~VirtualCloud() = default;\n    void GetOrder() {\n        order_.reserve(cloud_size_);\n        for (int index = 0; index < static_cast<int>(cloud_size_); ++index) {\n            order_.push_back(index);\n        }\n        std::sort(order_.begin(), order_.end(), \n                  [&](int lhs, int rhs) { return (*(values_ + lhs) < *(values_ + rhs) ||\n                                                  (*(values_ + lhs) == *(values_ + rhs) && lhs < rhs)); } );\n    }\n\n    virtual void GetGraph() {\n    }\n\n    virtual void SetGraph(Graph&& gr) {\n        graph_ = gr;\n    }\n\n    std::map<int, Ans> SublevelHomology() {\n        GetGraph();\n        minima_graph_.resize(cloud_size_);\n        std::map<int, Ans> answer;\n        int lenght = graph_.size();\n        std::vector<int> back_ord(lenght, 0);\n        for (int id = 0; id < lenght; ++id) {\n            back_ord[order_[id]] = id;\n        }\n        std::vector<int> siz(lenght + 1, 0);\n        std::vector<int> ord(lenght + 1, 0);\n        boost::disjoint_sets<int*,int*> ds(&ord[0], &siz[0]);\n        auto comp = [&](int lhs, int rhs){ return back_ord[lhs - 1] < back_ord[rhs - 1]; };\n        for (int ind = 0; ind < lenght; ++ind) {\n            int vertex = order_[ind];\n            if (trash_.find(vertex) != trash_.end()) {\n                continue;\n            }\n            std::map<int, int, decltype(comp)> clusters(comp);\n            for (auto neubour : graph_[vertex]) {\n                if (trash_.find(neubour) == trash_.end()) {\n                    int next_cluster = ds.find_set(neubour + 1);\n                    if (clusters.find(next_cluster) == clusters.end()) {\n                        clusters.emplace(next_cluster, neubour);\n                    } else if (back_ord[neubour] < back_ord[clusters[next_cluster]]) { \n                        clusters[next_cluster] = neubour;\n                    }\n                }        \n            }\n            for (auto& item : clusters) {\n                minima_graph_[vertex].push_back(item.second);\n                minima_graph_[item.second].push_back(vertex);\n            }\n            if (clusters.empty()) {\n                ds.make_set(vertex + 1);\n                answer.emplace(vertex, Ans(-1, -1, -1, 1));\n                continue;\n            }\n            int start = clusters.begin()->first;\n            ds.make_set(vertex + 1);\n            ds.link(vertex + 1, start);\n            ++answer.at(start - 1).death_size;\n            answer.at(start - 1).total_height += *(values_ + vertex) - *(values_ + start - 1);\n            for (auto it = next(clusters.begin()); it != clusters.end(); ++it) {\n                ord[start] = std::max(ord[start], ord[it->first]);\n                ds.link(it->first, start);\n                answer.at(it->first - 1).eat = start - 1;\n                answer.at(it->first - 1).death = vertex;\n                answer.at(it->first - 1).eat_size = answer.at(start - 1).death_size;\n                answer.at(start - 1).death_size += answer.at(it->first - 1).death_size;\n                answer.at(start - 1).total_height += answer.at(it->first - 1).total_height + \n                                                     (*(values_ + it->first - 1) - *(values_ + start - 1)) * \n                                                     answer.at(it->first - 1).death_size;\n            }\n        }\n        return answer;\n    }\n};\n\nclass GridCloud : public VirtualCloud {\nprivate:\n    std::vector<size_t> shape_;\n    std::vector<size_t> shift_;\n\n    int GetIndex(int point, int dim) {\n        return (point % shift_[dim + 1]) / shift_[dim];\n    }\n\npublic:\n    GridCloud(float* val, size_t size, std::vector<size_t> sh) \n        : VirtualCloud(val, size), shape_(sh) {\n        shift_.resize(shape_.size() + 1, 1);\n        for (size_t id = 1; id < shape_.size() + 1; ++id) {\n            shift_[id] = shift_[id - 1] * shape_[id - 1];\n        }\n    }\n\n    void GetGraph() {\n        graph_.resize(cloud_size_);\n        for (size_t index = 0; index < cloud_size_; ++index) {\n            for (size_t dim = 0; dim < shape_.size(); ++dim) {\n                size_t down = index - shift_[dim];\n                if (GetIndex(index, dim) != 0 && *(values_ + index) >= *(values_ + down)) {\n                    graph_[index].push_back(down);\n                }\n                size_t up = index + shift_[dim];\n                if (GetIndex(up, dim) != 0 && *(values_ + index) > *(values_ + up)) {\n                    graph_[index].push_back(up);\n                }\n            }            \n        }\n    }\n};\n\n}\n\n", "meta": {"hexsha": "37b2797f32dc04d4589057d8d7f70c6f60176ba8", "size": 7389, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/sublevel_v6.hpp", "max_stars_repo_name": "daniil-777/BarCode", "max_stars_repo_head_hexsha": "1f0c39287f757da4293d07fa3a2d68703e66da37", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/sublevel_v6.hpp", "max_issues_repo_name": "daniil-777/BarCode", "max_issues_repo_head_hexsha": "1f0c39287f757da4293d07fa3a2d68703e66da37", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/sublevel_v6.hpp", "max_forks_repo_name": "daniil-777/BarCode", "max_forks_repo_head_hexsha": "1f0c39287f757da4293d07fa3a2d68703e66da37", "max_forks_repo_licenses": ["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.7397260274, "max_line_length": 109, "alphanum_fraction": 0.4736770876, "num_tokens": 1808, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7025300573952054, "lm_q2_score": 0.49218813572079556, "lm_q1q2_score": 0.3457769592371696}}
{"text": "// ---------------------------------------------------------------------\n//\n// Copyright (c) 2019 - 2021 by the IBAMR developers\n// All rights reserved.\n//\n// This file is part of IBAMR.\n//\n// IBAMR is free software and is distributed under the 3-clause BSD\n// license. The full text of the license can be found in the file\n// COPYRIGHT at the top level directory of IBAMR.\n//\n// ---------------------------------------------------------------------\n\n#include <ibtk/config.h>\n\n#include \"InterpolationUtilities.h\"\n#include \"tbox/MathUtilities.h\"\n#include \"tbox/Pointer.h\"\n\nIBTK_DISABLE_EXTRA_WARNINGS\n#include <Eigen/Core>\n#include <Eigen/QR>\nIBTK_ENABLE_EXTRA_WARNINGS\n\n#include <HierarchyCellDataOpsReal.h>\n#include <Patch.h>\n#include <PatchLevel.h>\n\n#include <algorithm>\n\nusing Eigen::Matrix3d;\nusing Eigen::Vector3d;\n\nnamespace IBTK\n{\ndouble\nInterpolationUtilities::interpolate(const vector<double>& X,\n                                    const int data_idx,\n                                    Pointer<CellVariable<NDIM, double> > Q_var,\n                                    Pointer<PatchHierarchy<NDIM> > patch_hierarchy,\n                                    const std::vector<RobinBcCoefStrategy<NDIM>*>& bc_coefs,\n                                    const double data_time,\n                                    const int depth)\n{\n    double q_val = 0.0;\n    VariableDatabase<NDIM>* var_db = VariableDatabase<NDIM>::getDatabase();\n    const int data_idx_temp =\n        var_db->registerVariableAndContext(Q_var, var_db->getContext(\"Interpolation\"), IntVector<NDIM>(3));\n    for (int ln = 0; ln <= patch_hierarchy->getFinestLevelNumber(); ++ln)\n    {\n        Pointer<PatchLevel<NDIM> > level = patch_hierarchy->getPatchLevel(ln);\n        level->allocatePatchData(data_idx_temp);\n    }\n    HierarchyCellDataOpsReal<NDIM, double> hier_cc_data_ops(patch_hierarchy);\n    hier_cc_data_ops.copyData(data_idx_temp, data_idx);\n    typedef HierarchyGhostCellInterpolation::InterpolationTransactionComponent InterpolationTransactionComponent;\n    std::vector<InterpolationTransactionComponent> ghost_cell_components(1);\n    ghost_cell_components[0] = InterpolationTransactionComponent(\n        data_idx_temp, \"CONSERVATIVE_LINEAR_REFINE\", false, \"CONSERVATIVE_COARSEN\", \"LINEAR\", false, bc_coefs, NULL);\n    HierarchyGhostCellInterpolation ghost_fill_op;\n    ghost_fill_op.initializeOperatorState(ghost_cell_components, patch_hierarchy);\n    ghost_fill_op.fillData(data_time);\n    bool done = false;\n    for (int ln = patch_hierarchy->getFinestLevelNumber(); ln >= 0 && !done; --ln)\n    {\n        // Start at the finest level...\n        Pointer<PatchLevel<NDIM> > level = patch_hierarchy->getPatchLevel(ln);\n        CellIndex<NDIM> idx = IndexUtilities::getCellIndex(X, level->getGridGeometry(), level->getRatio());\n        for (PatchLevel<NDIM>::Iterator p(level); p && !done; p++)\n        {\n            Pointer<Patch<NDIM> > patch = level->getPatch(p());\n            const Pointer<CartesianPatchGeometry<NDIM> > p_geom = patch->getPatchGeometry();\n            const double* const dx = p_geom->getDx();\n            const double* const x_lower = p_geom->getXLower();\n            const Box<NDIM>& patch_box = patch->getBox();\n            Pointer<CellData<NDIM, double> > S_data = patch->getPatchData(data_idx_temp);\n            if (patch_box.contains(idx))\n            {\n                // Great. The patch is currently on this level\n                // Let's create a box that contains this data\n                Box<NDIM> box(idx, idx);\n                // Grow it by some number of grid cells\n                box.grow(IntVector<NDIM>(3));\n                // Loop through the box, make sure the point is located\n                // OUTSIDE the disk\n                std::vector<double> x(NDIM);\n                CellData<NDIM, int> i_data(box, 1, IntVector<NDIM>(0));\n                CellData<NDIM, double> si_data(box, NDIM + 1, IntVector<NDIM>(0));\n                si_data.fillAll(std::numeric_limits<double>::signaling_NaN());\n                const CellIndex<NDIM> ci_l = patch_box.lower();\n                int num = 0;\n                for (CellIterator<NDIM> i(box); i; i++)\n                {\n                    CellIndex<NDIM> ci = i();\n                    for (int d = 0; d < NDIM; ++d) x[d] = x_lower[d] + dx[d] * (ci(d) - ci_l(d) + 0.5);\n                    double r = sqrt(x[0] * x[0] + x[1] * x[1]);\n                    if (r > 1.0)\n                    {\n                        i_data(ci) = 1;\n                        si_data(ci, NDIM) = (*S_data)(ci, depth);\n                        num++;\n                    }\n                    else\n                    {\n                        i_data(ci) = -1;\n                    }\n                }\n                // We have a box containing the point and data the says if we are inside or outside disk.\n                // Find directions and interpolate. First in x, then in y.\n                std::vector<int> completed_dims;\n                q_val = InterpolationUtilities::interpolate_in_boxes(\n                    idx, X, i_data, si_data, p_geom, patch_box, 0, 0, completed_dims);\n                done = true;\n            }\n        }\n    }\n    for (int ln = 0; ln <= patch_hierarchy->getFinestLevelNumber(); ++ln)\n    {\n        Pointer<PatchLevel<NDIM> > level = patch_hierarchy->getPatchLevel(ln);\n        level->deallocatePatchData(data_idx_temp);\n    }\n    q_val = IBTK_MPI::sumReduction(q_val);\n    return q_val;\n}\n\ndouble\nInterpolationUtilities::interpolateL2(const std::vector<double>& X,\n                                      const int data_idx,\n                                      Pointer<CellVariable<NDIM, double> > Q_var,\n                                      SAMRAI::tbox::Pointer<SAMRAI::hier::PatchHierarchy<NDIM> > patch_hierarchy,\n                                      const std::vector<SAMRAI::solv::RobinBcCoefStrategy<NDIM>*>& bc_coefs,\n                                      const double data_time,\n                                      const int depth)\n{\n    double q_val = 0.0;\n    VariableDatabase<NDIM>* var_db = VariableDatabase<NDIM>::getDatabase();\n    const int data_idx_temp =\n        var_db->registerVariableAndContext(Q_var, var_db->getContext(\"Interpolation\"), IntVector<NDIM>(3));\n    for (int ln = 0; ln <= patch_hierarchy->getFinestLevelNumber(); ++ln)\n    {\n        Pointer<PatchLevel<NDIM> > level = patch_hierarchy->getPatchLevel(ln);\n        level->allocatePatchData(data_idx_temp);\n    }\n    HierarchyCellDataOpsReal<NDIM, double> hier_cc_data_ops(patch_hierarchy);\n    hier_cc_data_ops.copyData(data_idx_temp, data_idx);\n    typedef HierarchyGhostCellInterpolation::InterpolationTransactionComponent InterpolationTransactionComponent;\n    std::vector<InterpolationTransactionComponent> ghost_cell_components(1);\n    ghost_cell_components[0] = InterpolationTransactionComponent(\n        data_idx_temp, \"CONSERVATIVE_LINEAR_REFINE\", false, \"CONSERVATIVE_COARSEN\", \"LINEAR\", false, bc_coefs, NULL);\n    HierarchyGhostCellInterpolation ghost_fill_op;\n    ghost_fill_op.initializeOperatorState(ghost_cell_components, patch_hierarchy);\n    ghost_fill_op.fillData(data_time);\n    bool done = false;\n    for (int ln = patch_hierarchy->getFinestLevelNumber(); ln >= 0 && !done; --ln)\n    {\n        // Start at the finest level...\n        Pointer<PatchLevel<NDIM> > level = patch_hierarchy->getPatchLevel(ln);\n        CellIndex<NDIM> idx = IndexUtilities::getCellIndex(X, level->getGridGeometry(), level->getRatio());\n        for (PatchLevel<NDIM>::Iterator p(level); p && !done; p++)\n        {\n            Pointer<Patch<NDIM> > patch = level->getPatch(p());\n            const Pointer<CartesianPatchGeometry<NDIM> > p_geom = patch->getPatchGeometry();\n            const double* const dx = p_geom->getDx();\n            const double* const x_lower = p_geom->getXLower();\n            const Box<NDIM>& patch_box = patch->getBox();\n            Pointer<CellData<NDIM, double> > S_data = patch->getPatchData(data_idx_temp);\n            if (patch_box.contains(idx))\n            {\n                // Great. The patch is currently on this level\n                // Let's create a box that contains this data\n                Box<NDIM> box(idx, idx);\n                // Grow it by some number of grid cells\n                box.grow(2);\n                // Loop through the box, make sure the point is located\n                // OUTSIDE the disk\n                std::vector<double> x(NDIM);\n                CellData<NDIM, int> i_data(box, 1, IntVector<NDIM>(0));\n                const CellIndex<NDIM> ci_l = patch_box.lower();\n                int num = 0;\n                for (CellIterator<NDIM> i(box); i; i++)\n                {\n                    CellIndex<NDIM> ci = i();\n                    for (int d = 0; d < NDIM; ++d) x[d] = x_lower[d] + dx[d] * (ci(d) - ci_l(d) + 0.5);\n                    double r = sqrt(x[0] * x[0] + x[1] * x[1]);\n                    if (r > 1.0)\n                    {\n                        i_data(ci) = 1;\n                        num++;\n                    }\n                }\n                // Moving least squares\n                VectorXd rhs = VectorXd::Zero(6);\n                VectorXd soln = VectorXd::Zero(6);\n                MatrixXd mat = MatrixXd::Zero(6, 6);\n                for (CellIterator<NDIM> i(box); i; i++)\n                {\n                    CellIndex<NDIM> ci = i();\n                    if (i_data(ci) == 1)\n                    {\n                        for (int d = 0; d < NDIM; ++d) x[d] = x_lower[d] + dx[d] * (ci(d) - ci_l(d) + 0.5);\n                        // Fill in RHS and MATRIX values\n                        double w = weight_fcn(X, x);\n                        double f = (*S_data)(ci, depth);\n                        rhs(0) += w * f;\n                        rhs(1) += w * f * x[0];\n                        rhs(2) += w * f * x[1];\n                        rhs(3) += w * f * x[0] * x[0];\n                        rhs(4) += w * f * x[1] * x[1];\n                        rhs(5) += w * f * x[0] * x[1];\n                        mat(0, 0) += w; /*mat(0,1) += x[0]*w; mat(0,2) += x[1]*w; mat(0,3) += x[0]*x[0]*w; mat(0,4) +=\n                                           x[1]*x[1]*w; mat(0,5) += x[0]*x[1]*w;*/\n                        mat(1, 0) += x[0] * w;\n                        mat(1, 1) += x[0] * x[0] * w; /* mat(1,2) += x[0]*x[1]*w; mat(2,3) += x[0]*x[0]*x[0]*w; mat(2,4)\n                                                         += x[0]*x[1]*x[1]*w; mat(3,5) += x[0]*x[0]*x[1]*w;*/\n                        mat(2, 0) += x[1] * w;\n                        mat(2, 1) += x[1] * x[0] * w;\n                        mat(2, 2) += x[1] * x[1] * w;\n                        mat(3, 0) += x[0] * x[0] * w;\n                        mat(3, 1) += x[0] * x[0] * x[0] * w;\n                        mat(3, 2) += x[0] * x[0] * x[1] * w;\n                        mat(3, 3) += x[0] * x[0] * x[0] * x[0] * w;\n                        mat(4, 0) += x[1] * x[1] * w;\n                        mat(4, 1) += x[1] * x[1] * x[0] * w;\n                        mat(4, 2) += x[1] * x[1] * x[1] * w;\n                        mat(4, 3) += x[1] * x[1] * x[0] * x[0] * w;\n                        mat(4, 4) += x[1] * x[1] * x[1] * x[1] * w;\n                        mat(5, 0) += x[0] * x[1] * w;\n                        mat(5, 1) += x[0] * x[1] * x[0] * w;\n                        mat(5, 2) += x[0] * x[1] * x[1] * w;\n                        mat(5, 3) += x[0] * x[1] * x[0] * x[0] * w;\n                        mat(5, 4) += x[0] * x[1] * x[1] * x[1] * w;\n                        mat(5, 5) += x[0] * x[1] * x[0] * x[1] * w;\n                    }\n                }\n                //                mat(0,1) = mat(1,0); mat(0,2) = mat(2,0); mat(0,3) = mat(3,0); mat(0,4) = mat(4,0);\n                //                mat(0,5) = mat(5,0); mat(1,2) = mat(2,1); mat(1,3) = mat(3,1); mat(1,4) = mat(4,1);\n                //                mat(1,5) = mat(5,1); mat(2,3) = mat(3,2); mat(2,4) = mat(4,2); mat(2,5) = mat(5,2);\n                //                mat(3,4) = mat(4,3); mat(3,5) = mat(5,3);\n                //                mat(4,5) = mat(5,4);\n                soln = mat.ldlt().solve(rhs);\n                q_val = soln(0) + soln(1) * X[0] + soln(2) * X[1] + soln(3) * X[0] * X[0] + soln(4) * X[1] * X[1] +\n                        soln(5) * X[0] * X[1];\n                done = true;\n            }\n        }\n    }\n    q_val = IBTK_MPI::sumReduction(q_val);\n\n    for (int ln = 0; ln <= patch_hierarchy->getFinestLevelNumber(); ++ln)\n    {\n        Pointer<PatchLevel<NDIM> > level = patch_hierarchy->getPatchLevel(ln);\n        level->deallocatePatchData(data_idx_temp);\n    }\n    return q_val;\n}\n\ndouble\nInterpolationUtilities::weight_fcn(const std::vector<double>& x, const std::vector<double>& x_j)\n{\n    double r = sqrt((x[0] - x_j[0]) * (x[0] - x_j[0]) + (x[1] - x_j[1]) * (x[1] - x_j[1]));\n    double w = exp(-10.0 * r * r);\n    w = 1.0;\n    return w;\n}\n\ndouble\nInterpolationUtilities::interpolate(const double& l, const std::vector<int>& i, const std::vector<double>& y)\n{\n    double val = 0.0;\n    TBOX_ASSERT(i.size() == 3);\n    TBOX_ASSERT(y.size() == i.size());\n    val = y[0] + (y[1] - y[0]) * l / static_cast<double>(i[1] - i[0]) +\n          (y[2] * static_cast<double>(i[0] - i[1]) + y[0] * static_cast<double>(i[1] - i[2]) +\n           y[1] * static_cast<double>(i[2] - i[0])) *\n              l * (l - 1.0) / (static_cast<double>((i[0] - i[1]) * (i[0] - i[2]) * (i[1] - i[2])));\n    return val;\n}\n\ndouble\nInterpolationUtilities::interpolate_in_boxes(const CellIndex<NDIM>& idx,\n                                             const std::vector<double>& X,\n                                             CellData<NDIM, int>& r_data,\n                                             CellData<NDIM, double>& q_data,\n                                             Pointer<CartesianPatchGeometry<NDIM> > pgeom,\n                                             const Box<NDIM>& pbox,\n                                             int dim,\n                                             int cycle,\n                                             std::vector<int>& completed_dims)\n{\n    double q_val = 0.0;\n    // form list of indices.\n    std::vector<CellIndex<NDIM> > idx_list;\n    std::vector<int> i_list;\n    bool done = false;\n    while (!done)\n    {\n        idx_list.clear();\n        i_list.clear();\n        dim = dim % NDIM;\n        if (r_data(idx) == 1)\n        {\n            idx_list.push_back(idx);\n            i_list.push_back(0);\n        }\n        int s = 1;\n        while (idx_list.size() < 3)\n        {\n            IntVector<NDIM> si(0);\n            si(dim) = s;\n            if (r_data(idx + si) == 1)\n            {\n                idx_list.push_back(idx + si);\n                i_list.push_back(s);\n            }\n            if (r_data(idx - si) == 1)\n            {\n                idx_list.push_back(idx - si);\n                i_list.push_back(-s);\n            }\n            s++;\n        }\n        int min_val = *std::min_element(i_list.begin(), i_list.end());\n        int max_val = *std::max_element(i_list.begin(), i_list.end());\n        if (std::max(std::abs(min_val), std::abs(max_val)) > 3)\n        {\n            dim++;\n            if (std::find(completed_dims.begin(), completed_dims.end(), dim) != completed_dims.end() || dim > NDIM)\n            {\n                TBOX_ERROR(\"already completed dimension, or dimension too high\");\n            }\n        }\n        else\n        {\n            done = true;\n        }\n    }\n    while (idx_list.size() > 3)\n    {\n        idx_list.pop_back();\n    }\n    completed_dims.push_back(dim);\n    // We start at dim = 0. Each call generates a new box to interpolate inside of, and increases the dim by 1.\n    if (cycle < NDIM - 1)\n    {\n        std::vector<int> i_list;\n        std::vector<double> y_data;\n        for (std::vector<CellIndex<NDIM> >::const_iterator cit = idx_list.begin(); cit != idx_list.end(); ++cit)\n        {\n            const CellIndex<NDIM>& cidx = *cit;\n            q_data(cidx, cycle + 1) = InterpolationUtilities::interpolate_in_boxes(\n                cidx, X, r_data, q_data, pgeom, pbox, dim + 1, cycle + 1, completed_dims);\n            i_list.push_back(cidx(dim));\n            y_data.push_back(q_data(cidx, cycle + 1));\n        }\n        const double* dx = pgeom->getDx();\n        const double* xlow = pgeom->getXLower();\n        const CellIndex<NDIM>& idxl = pbox.lower();\n        double xx = xlow[dim] + dx[dim] * (idx_list[0](dim) - idxl(dim) + 0.5);\n        q_val = InterpolationUtilities::interpolate((X[dim] - xx) / dx[dim], i_list, y_data);\n    }\n    else if (cycle == NDIM - 1)\n    {\n        std::vector<int> i_list;\n        std::vector<double> y_data;\n        for (std::vector<CellIndex<NDIM> >::const_iterator cit = idx_list.begin(); cit != idx_list.end(); ++cit)\n        {\n            const CellIndex<NDIM>& cidx = *cit;\n            i_list.push_back(cidx(dim));\n            y_data.push_back(q_data(cidx, cycle + 1));\n        }\n        const double* dx = pgeom->getDx();\n        const double* xlow = pgeom->getXLower();\n        const CellIndex<NDIM>& idxl = pbox.lower();\n        double xx = xlow[dim] + dx[dim] * (idx_list[0](dim) - idxl(dim) + 0.5);\n        q_val = InterpolationUtilities::interpolate((X[dim] - xx) / dx[dim], i_list, y_data);\n    }\n    else\n    {\n        // Shouldn't get here.\n        TBOX_ERROR(\"Invalid dimension.\\n\");\n    }\n    return q_val;\n}\n} // namespace IBTK\n", "meta": {"hexsha": "c23f4ee7dc9f3ee0120fe1b8e6711cc5f672b444", "size": 17440, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/complex_fluids/ex2/InterpolationUtilities.cpp", "max_stars_repo_name": "akashdhruv/IBAMR", "max_stars_repo_head_hexsha": "a2b47946d795fb5a40c181b43e44a6ec387585a9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 264.0, "max_stars_repo_stars_event_min_datetime": "2015-01-04T12:11:02.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T13:10:37.000Z", "max_issues_repo_path": "examples/complex_fluids/ex2/InterpolationUtilities.cpp", "max_issues_repo_name": "akashdhruv/IBAMR", "max_issues_repo_head_hexsha": "a2b47946d795fb5a40c181b43e44a6ec387585a9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1057.0, "max_issues_repo_issues_event_min_datetime": "2015-04-27T04:27:57.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T13:14:59.000Z", "max_forks_repo_path": "examples/complex_fluids/ex2/InterpolationUtilities.cpp", "max_forks_repo_name": "drwells/IBAMR", "max_forks_repo_head_hexsha": "0ceda3873405a35da4888c99e7d2b24d132f9071", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 126.0, "max_forks_repo_forks_event_min_datetime": "2015-02-13T15:36:02.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-27T21:59:50.000Z", "avg_line_length": 45.2987012987, "max_line_length": 120, "alphanum_fraction": 0.4911123853, "num_tokens": 4766, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.665410572017153, "lm_q2_score": 0.519521321952093, "lm_q1q2_score": 0.34569498001524973}}
{"text": "#include <boost/version.hpp>\n#if BOOST_VERSION < 106300 && BOOST_VERSION >= 106200\n// Boost 1.62 is missing an iostream include...\n#include <iostream>\n#endif\n#include <boost/geometry/geometries/box.hpp>\n#include <boost/geometry/geometries/pointing_segment.hpp>\n#include <boost/geometry/index/rtree.hpp>\n\n#include \"lanelet2_core/geometry/LineString.h\"\n#include \"lanelet2_core/geometry/Polygon.h\"\n\nnamespace lanelet {\nnamespace geometry {\nnamespace {\nusing V3d = BasicPoint3d;\n\nstruct LineParams {\n  double sN;\n  double sD;\n  double tN;\n  double tD;\n};\n\nconstexpr double SmallNum = 1.e-10;\n\ninline LineParams calculateLineParams(double a, double b, double c, double d, double e, double den) {\n  // compute the line parameters of the two closest points\n  if (den < SmallNum) {  // the lines are almost parallel\n    // force using point P0 on segment S1\n    // to prevent possible division by 0.0 later\n    return {0.0, 1.0, e, c};\n  }\n  LineParams lp{};\n  lp.sD = den;\n  lp.tD = den;\n  // get the closest points on the infinite lines\n  lp.sN = (b * e - c * d);\n  lp.tN = (a * e - b * d);\n  if (lp.sN < 0.0) {  // sc < 0 => the s=0 edge is visible\n    lp.sN = 0.0;\n    lp.tN = e;\n    lp.tD = c;\n  } else if (lp.sN > lp.sD) {  // sc > 1  => the s=1 edge is visible\n    lp.sN = lp.sD;\n    lp.tN = e + b;\n    lp.tD = c;\n  }\n\n  return lp;\n}\n\nstd::pair<BasicPoint3d, BasicPoint3d> projectedPoint3d(const BasicPoint3d& p1, const BasicPoint3d& p2,\n                                                       const BasicPoint3d& q1, const BasicPoint3d& q2) {\n  // see http://geomalgorithms.com/a07-_distance.html\n  V3d w = p1 - q1;\n  V3d u = p2 - p1;\n  V3d v = q2 - q1;\n  double a = u.dot(u);\n  double b = u.dot(v);\n  double c = v.dot(v);\n  double d = u.dot(w);\n  double e = v.dot(w);\n  auto den = a * c - b * b;\n\n  auto lp = calculateLineParams(a, b, c, d, e, den);\n\n  if (lp.tN < 0.0) {  // tc < 0 => the t=0 edge is visible\n    lp.tN = 0.0;\n    // recompute sc for this edge\n    if (-d < 0.0) {\n      lp.sN = 0.0;\n    } else if (-d > a) {\n      lp.sN = lp.sD;\n    } else {\n      lp.sN = -d;\n      lp.sD = a;\n    }\n  } else if (lp.tN > lp.tD) {  // tc > 1  => the t=1 edge is visible\n    lp.tN = lp.tD;\n    // recompute sc for this edge\n    if ((-d + b) < 0.0) {\n      lp.sN = 0;\n    } else if ((-d + b) > a) {\n      lp.sN = lp.sD;\n    } else {\n      lp.sN = (-d + b);\n      lp.sD = a;\n    }\n  }\n  // finally do the division to get sc and tc\n  double sc = (std::abs(lp.sN) < SmallNum ? 0.0 : lp.sN / lp.sD);\n  double tc = (std::abs(lp.tN) < SmallNum ? 0.0 : lp.tN / lp.tD);\n\n  return {p1 + (sc * u), q1 + (tc * v)};  // return the closest distance\n}\n\nnamespace bg = boost::geometry;\nnamespace bgi = bg::index;\nnamespace bgm = boost::geometry::model;\nusing BasicSegment = bgm::pointing_segment<const BasicPoint3d>;\nusing Box = bgm::box<bgm::point<double, 3, boost::geometry::cs::cartesian>>;\nusing Node = std::pair<Box, BasicSegment>;\nusing RTree = bgi::rtree<Node, bgi::linear<8>>;\n\ntemplate <typename LineString1T, typename LineString2T>\nstd::pair<BasicPoint3d, BasicPoint3d> projectedPoint3dOrdered(const LineString1T& smallerRange,\n                                                              const LineString2T& greaterRange) {\n  // catch some degerated cases\n  ConstHybridLineString3d duplicate;\n  if (smallerRange.size() == 1 && greaterRange.size() == 1) {\n    std::pair<BasicPoint3d, BasicPoint3d> ret(greaterRange.front(), smallerRange.front());\n    return ret;\n  }\n  auto values =\n      utils::transform(bg::segments_begin(greaterRange), bg::segments_end(greaterRange), [](const auto& segm) {\n        Box box;\n        boost::geometry::envelope(segm, box);\n        return Node(box, segm);\n      });\n  RTree tree(values.begin(), values.end());\n\n  bool first = true;\n  double dMin{};\n  std::pair<BasicPoint3d, BasicPoint3d> closestPair;\n  for (auto it = bg::segments_begin(smallerRange); it != bg::segments_end(smallerRange); ++it) {\n    Box queryBox;\n    bg::envelope(*it, queryBox);\n    for (auto qIt = tree.qbegin(bgi::nearest(queryBox, unsigned(greaterRange.size()))); qIt != tree.qend();\n         ++qIt, first = false) {\n      const auto& nearest = *qIt;\n      auto dBox = boost::geometry::distance(nearest.first, queryBox);\n      if (!first && dBox > dMin) {\n        break;\n      }\n      auto projPair = projectedPoint3d(*nearest.second.first, *nearest.second.second, *it->first, *it->second);\n      auto d = (projPair.first - projPair.second).norm();\n      if (first || d < dMin) {\n        closestPair = projPair;\n        dMin = d;\n      }\n    }\n  }\n  return closestPair;\n}\n\ntemplate <typename LineString1T, typename LineString2T>\nstd::pair<BasicPoint3d, BasicPoint3d> projectedPoint3dImpl(const LineString1T& l1, const LineString2T& l2) {\n  if (l1.size() < l2.size()) {\n    return projectedPoint3dOrdered(l1, l2);\n  }\n  auto res = projectedPoint3dOrdered(l2, l1);\n  return {res.second, res.first};\n}\n}  // namespace\n\nnamespace internal {\nstd::pair<BasicPoint3d, BasicPoint3d> projectedPoint3d(const CompoundHybridLineString3d& l1,\n                                                       const CompoundHybridLineString3d& l2) {\n  return projectedPoint3dImpl(l1, l2);\n}\n\nstd::pair<BasicPoint3d, BasicPoint3d> projectedPoint3d(const ConstHybridLineString3d& l1,\n                                                       const CompoundHybridLineString3d& l2) {\n  return projectedPoint3dImpl(l1, l2);\n}\n\nstd::pair<BasicPoint3d, BasicPoint3d> projectedPoint3d(const CompoundHybridLineString3d& l1,\n                                                       const ConstHybridLineString3d& l2) {\n  return projectedPoint3dImpl(l1, l2);\n}\n\nstd::pair<BasicPoint3d, BasicPoint3d> projectedPoint3d(const ConstHybridLineString3d& l1,\n                                                       const ConstHybridLineString3d& l2) {\n  return projectedPoint3dImpl(l1, l2);\n}\n\nstd::pair<BasicPoint3d, BasicPoint3d> projectedPoint3d(const ConstHybridLineString3d& l1, const BasicLineString3d& l2) {\n  return projectedPoint3dImpl(l1, l2);\n}\n\nstd::pair<BasicPoint3d, BasicPoint3d> projectedPoint3d(const BasicLineString3d& l1, const ConstHybridLineString3d& l2) {\n  return projectedPoint3dImpl(l1, l2);\n}\n\nstd::pair<BasicPoint3d, BasicPoint3d> projectedPoint3d(const BasicLineString3d& l1, const BasicLineString3d& l2) {\n  return projectedPoint3dImpl(l1, l2);\n}\n\nstd::pair<BasicPoint3d, BasicPoint3d> projectedBorderPoint3d(const ConstHybridPolygon3d& l1,\n                                                             const ConstHybridPolygon3d& l2) {\n  return projectedPoint3dImpl(l1, l2);\n}\n\nstd::pair<BasicPoint3d, BasicPoint3d> projectedBorderPoint3d(const CompoundHybridPolygon3d& l1,\n                                                             const CompoundHybridPolygon3d& l2) {\n  return projectedPoint3dImpl(l1, l2);  // NOLINT\n}\n\n}  // namespace internal\n\nSegment<BasicPoint2d> closestSegment(const BasicLineString2d& lineString, const BasicPoint2d& pointToProject) {\n  helper::ProjectedPoint<BasicPoint2d> projectedPoint;\n  distance(lineString, pointToProject, projectedPoint);\n  return Segment<BasicPoint2d>(projectedPoint.result->segmentPoint1, projectedPoint.result->segmentPoint2);\n}\nSegment<BasicPoint3d> closestSegment(const BasicLineString3d& lineString, const BasicPoint3d& pointToProject) {\n  helper::ProjectedPoint<BasicPoint3d> projectedPoint;\n  distance(lineString, pointToProject, projectedPoint);\n  return Segment<BasicPoint3d>(projectedPoint.result->segmentPoint1, projectedPoint.result->segmentPoint2);\n}\n}  // namespace geometry\n}  // namespace lanelet\n", "meta": {"hexsha": "1da26b95a91793aba1e47a5bba5b363873d1cfc9", "size": 7547, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lanelet2/lanelet2_core/src/LineStringGeometry.cpp", "max_stars_repo_name": "alanjclark/autoware.ai", "max_stars_repo_head_hexsha": "ba97edbbffb6f22e78912bf96400a59ef6a13daf", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 465.0, "max_stars_repo_stars_event_min_datetime": "2018-10-26T14:10:49.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T09:34:38.000Z", "max_issues_repo_path": "lanelet2/lanelet2_core/src/LineStringGeometry.cpp", "max_issues_repo_name": "alanjclark/autoware.ai", "max_issues_repo_head_hexsha": "ba97edbbffb6f22e78912bf96400a59ef6a13daf", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 236.0, "max_issues_repo_issues_event_min_datetime": "2018-11-06T06:02:09.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-29T06:10:22.000Z", "max_forks_repo_path": "lanelet2/lanelet2_core/src/LineStringGeometry.cpp", "max_forks_repo_name": "alanjclark/autoware.ai", "max_forks_repo_head_hexsha": "ba97edbbffb6f22e78912bf96400a59ef6a13daf", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 252.0, "max_forks_repo_forks_event_min_datetime": "2018-11-01T19:52:29.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-27T08:21:44.000Z", "avg_line_length": 35.2663551402, "max_line_length": 120, "alphanum_fraction": 0.6444945011, "num_tokens": 2269, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.665410558746814, "lm_q2_score": 0.5195213219520929, "lm_q1q2_score": 0.34569497312102554}}
{"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// Parts of Boost.Geometry are redesigned from Geodan's Geographic Library\n// (geolib/GGL), copyright (c) 1995-2010 Geodan, Amsterdam, the Netherlands.\n\n// Use, modification and distribution is subject to the Boost Software License,\n// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n\n#ifndef BOOST_GEOMETRY_EXTENSIONS_ALGEBRA_GEOMETRIES_QUATERNION_HPP\n#define BOOST_GEOMETRY_EXTENSIONS_ALGEBRA_GEOMETRIES_QUATERNION_HPP\n\n#include <cstddef>\n\n#include <boost/geometry/extensions/algebra/core/tags.hpp>\n#include <boost/geometry/extensions/algebra/geometries/concepts/quaternion_concept.hpp>\n\n// WARNING!\n// It is probable that the sequence of coordinate will change in the future\n// at the beginning there would be xyz, w would become the last coordinate\n\nnamespace boost { namespace geometry\n{\n\nnamespace model\n{\n\ntemplate <typename T>\nclass quaternion\n{\n    BOOST_CONCEPT_ASSERT( (concepts::Quaternion<quaternion>) );\n\npublic:\n\n    /// @brief Default constructor, no initialization\n    inline quaternion()\n    {}\n\n    /// @brief Constructor to set components\n    inline quaternion(T const& w, T const& x, T const& y, T const& z)\n    {\n        m_values[0] = w;\n        m_values[1] = x;\n        m_values[2] = y;\n        m_values[3] = z;\n    }\n\n    /// @brief Get a coordinate\n    /// @tparam K coordinate to get\n    /// @return the coordinate\n    template <std::size_t K>\n    inline T const& get() const\n    {\n        BOOST_STATIC_ASSERT(K < 4);\n        return m_values[K];\n    }\n\n    /// @brief Set a coordinate\n    /// @tparam K coordinate to set\n    /// @param value value to set\n    template <std::size_t K>\n    inline void set(T const& value)\n    {\n        BOOST_STATIC_ASSERT(K < 4);\n        m_values[K] = value;\n    }\n\nprivate:\n\n    T m_values[4];\n};\n\n\n} // namespace model\n\n#ifndef DOXYGEN_NO_TRAITS_SPECIALIZATIONS\nnamespace traits\n{\n\ntemplate <typename CoordinateType>\nstruct tag<model::quaternion<CoordinateType> >\n{\n    typedef quaternion_tag type;\n};\n\ntemplate <typename CoordinateType>\nstruct coordinate_type<model::quaternion<CoordinateType> >\n{\n    typedef CoordinateType type;\n};\n\n//template <typename CoordinateType>\n//struct coordinate_system<model::quaternion<CoordinateType> >\n//{\n//    typedef cs::cartesian type;\n//};\n\ntemplate <typename CoordinateType>\nstruct dimension<model::quaternion<CoordinateType> >\n    : boost::integral_constant<std::size_t, 4>\n{};\n\ntemplate<typename CoordinateType, std::size_t Dimension>\nstruct access<model::quaternion<CoordinateType>, Dimension>\n{\n    static inline CoordinateType get(\n        model::quaternion<CoordinateType> const& v)\n    {\n        return v.template get<Dimension>();\n    }\n\n    static inline void set(\n        model::quaternion<CoordinateType> & v,\n        CoordinateType const& value)\n    {\n        v.template set<Dimension>(value);\n    }\n};\n\n} // namespace traits\n#endif // DOXYGEN_NO_TRAITS_SPECIALIZATIONS\n\n}} // namespace boost::geometry\n\n#endif // BOOST_GEOMETRY_EXTENSIONS_ALGEBRA_GEOMETRIES_QUATERNION_HPP\n", "meta": {"hexsha": "d41569f66fadb15e4d61d62ed9e4f6c409b0756a", "size": 3334, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Siv3D/src/ThirdParty/boost/geometry/extensions/algebra/geometries/quaternion.hpp", "max_stars_repo_name": "yumetodo/OpenSiv3D", "max_stars_repo_head_hexsha": "ea191438ecbc64185f5df3d9f79dffc6757e4192", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2020-04-26T11:06:02.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-05T16:42:31.000Z", "max_issues_repo_path": "Siv3D/src/ThirdParty/boost/geometry/extensions/algebra/geometries/quaternion.hpp", "max_issues_repo_name": "yumetodo/OpenSiv3D", "max_issues_repo_head_hexsha": "ea191438ecbc64185f5df3d9f79dffc6757e4192", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 10.0, "max_issues_repo_issues_event_min_datetime": "2020-04-26T13:25:36.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-01T12:34:44.000Z", "max_forks_repo_path": "Siv3D/src/ThirdParty/boost/geometry/extensions/algebra/geometries/quaternion.hpp", "max_forks_repo_name": "yumetodo/OpenSiv3D", "max_forks_repo_head_hexsha": "ea191438ecbc64185f5df3d9f79dffc6757e4192", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2020-12-03T13:22:49.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T10:43:59.000Z", "avg_line_length": 25.4503816794, "max_line_length": 87, "alphanum_fraction": 0.7075584883, "num_tokens": 829, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6654105454764747, "lm_q2_score": 0.519521321952093, "lm_q1q2_score": 0.34569496622680146}}
{"text": "#include <iostream>\n#include <vector>\n#include <cassert>\n#include <cstring>\n#include <limits>\n#include <mpi.h>\n//#include <Eigen/Eigenvalues>\n\nenum KernelType {CubicSpline = 0, WendlandC2 = 1, WendlandC4 = 2};\n\n#include \"particle_simulator.hpp\"\n#include \"hdr_time.hpp\"\n#include \"hdr_run.hpp\"\n#ifdef USE_INTRINSICS\n#include \"vector_x86.hpp\"\n#endif\n#include \"hdr_dimension.hpp\"\n#include \"hdr_kernel.hpp\"\n#include \"hdr_sph.hpp\"\n#include \"hdr_hgas.hpp\"\n#include \"hdr_bhns.hpp\"\n\nclass SPHAnalysis : public HelmholtzGas {\npublic:\n    SPHAnalysis() {\n        this->id    = 0;\n        this->istar = 0;\n        this->mass  = 0.;\n        this->pos   = 0.;\n        this->vel   = 0.;\n        this->uene  = 0.;\n        this->alph  = 0.;\n        this->alphu = 0.;\n        this->ksr   = 0.;\n        for(PS::S32 k = 0; k < NR::NumberOfNucleon; k++) {\n            this->cmps[k] = 0.;\n        }        \n    }\n\n    PS::F64 calcRadialVelocity() {\n        PS::F64 r2 = this->pos * this->pos;\n        PS::F64 rv = this->pos * this->vel;\n        return (rv / sqrt(r2));\n    }\n\n    void readAscii(FILE * fp) {\n        fscanf(fp, \"%lld%lld%lf\", &this->id, &this->istar, &this->mass);      //  3\n        fscanf(fp, \"%lf%lf%lf\", &this->pos[0], &this->pos[1], &this->pos[2]); //  6\n        fscanf(fp, \"%lf%lf%lf\", &this->vel[0], &this->vel[1], &this->vel[2]); //  9\n        fscanf(fp, \"%lf%lf%lf\", &this->acc[0], &this->acc[1], &this->acc[2]); // 12\n        fscanf(fp, \"%lf%lf%lf\", &this->uene, &this->alph, &this->alphu);      // 15\n        fscanf(fp, \"%lf%lf%6d\", &this->dens, &this->ksr,  &this->np);         // 18\n        fscanf(fp, \"%lf%lf%lf\", &this->vsnd, &this->pres, &this->temp);       // 21\n        fscanf(fp, \"%lf%lf%lf\", &this->divv, &this->rotv, &this->bswt);       // 24\n        fscanf(fp, \"%lf%lf%lf\", &this->pot,  &this->abar, &this->zbar);       // 27\n        fscanf(fp, \"%lf\",       &this->enuc);                                 // 28\n        fscanf(fp, \"%lf%lf%lf\", &this->vsmx, &this->udot, &this->dnuc);       // 31\n        for(PS::S32 k = 0; k < NuclearReaction::NumberOfNucleon; k++) {       // 32 -- 44\n            fscanf(fp, \"%lf\", &this->cmps[k]);\n        }\n        fscanf(fp, \"%lf\", &this->pot3);\n        fscanf(fp, \"%lf%lf%lf\", &this->tempmax[0], &this->tempmax[1], &this->tempmax[2]);\n        fscanf(fp, \"%lf\", &this->entr);\n    }\n\n};\n\nclass Shell {\npublic:\n    PS::S64 nump; // The number of particles in the shell\n    PS::F64 mass; // The total mass in the shell\n    PS::F64 ener; // The total internal energy in the shell\n    PS::F64 rvel; // Radial velocity in the shell\n    NR::Nucleon mele;\n\n    Shell() {\n        this->nump = 0;\n        this->mass = 0.;\n        this->ener = 0.;\n        this->rvel = 0.;\n        for(PS::S64 k = 0; k < NR::NumberOfNucleon; k++) {\n            this->mele[k] = 0.;\n        }\n    }\n\n    void increment(SPHAnalysis & sph) {\n        this->nump += 1;\n        this->mass += sph.mass;\n        this->ener += sph.mass * sph.uene;\n        this->rvel += sph.calcRadialVelocity();\n        for(PS::S64 k = 0; k < NR::NumberOfNucleon; k++) {\n            this->mele[k] += sph.mass * sph.cmps[k];\n        }\n    }\n\n    void reduceAddition(Shell sloc) {\n        this->nump = PS::Comm::getSum(sloc.nump);\n        this->mass = PS::Comm::getSum(sloc.mass);\n        this->ener = PS::Comm::getSum(sloc.ener);\n        this->rvel = PS::Comm::getSum(sloc.rvel);\n        for(PS::S64 k = 0; k < NR::NumberOfNucleon; k++) {\n            this->mele[k] = PS::Comm::getSum(sloc.mele[k]);\n        }\n    }\n\n};\n\ntemplate <class Tsph>\nvoid sphericalizeWhiteDwarf(PS::F64 rmax,\n                            PS::F64 drad,\n                            char * ofile,\n                            Tsph & sph) {\n\n    PS::F64vec cntr_loc = 0.;\n    PS::F64vec cvel_loc = 0.;\n    PS::F64    dens_loc = 0.;\n    for(PS::S64 i = 0; i < sph.getNumberOfParticleLocal(); i++) {\n        dens_loc += sph[i].dens;\n        cntr_loc += sph[i].dens * sph[i].pos;\n        cvel_loc += sph[i].dens * sph[i].vel;\n    }\n    PS::F64vec cntr_glb = PS::Comm::getSum(cntr_loc);\n    PS::F64vec cvel_glb = PS::Comm::getSum(cvel_loc);\n    PS::F64    dens_glb = PS::Comm::getSum(dens_loc);\n    cntr_glb = (1. / dens_glb) * cntr_glb;\n    cvel_glb = (1. / dens_glb) * cvel_glb;\n    \n    PS::S64 nbin = (PS::S64)(rmax / drad) + 1;\n    Shell * sloc = (Shell *)malloc(sizeof(Shell) * nbin);\n    \n    for(PS::S64 i = 0; i < sph.getNumberOfParticleLocal(); i++) {\n        sph[i].pos = sph[i].pos - cntr_glb;\n        sph[i].vel = sph[i].vel - cvel_glb;\n        PS::F64 rad1  = sqrt(sph[i].pos * sph[i].pos);\n        PS::S64 ibin = (PS::S64)(rad1 / drad);\n        if(ibin >= nbin) {\n            continue;\n        }\n        ///////////// Ad hoc method //////////////\n        if(sph[i].istar == 0 && sph[i].cmps[1] > 0.2 && rad1 < 3e10) {\n            for(PS::S64 k = 0; k < NR::NumberOfNucleon; k++) {\n                if(k != 12) {\n                    sph[i].cmps[k] = 0.;\n                } else {\n                    sph[i].cmps[k] = 1.;\n                }\n            }\n            //continue;\n        }\n        //////////////////////////////////////////\n        sloc[ibin].increment(sph[i]);\n    }\n\n    Shell * sglb = (Shell *)malloc(sizeof(Shell) * nbin);\n    for(PS::S64 ibin = 0; ibin < nbin; ibin++) {\n        sglb[ibin].reduceAddition(sloc[ibin]);\n    }\n    \n    if(PS::Comm::getRank() == 0) {\n        PS::S64 nshl = 0;\n        PS::F64 mass = 0.;\n        PS::F64 ener = 0.;\n        PS::F64 rvel = 0.;\n        PS::F64 rad0 = 0.;\n        PS::F64 menc = 0.;\n        NR::Nucleon mele;\n        FILE * fp = fopen(ofile, \"w\");\n        for(PS::S64 ibin = 0; ibin < nbin; ibin++) {\n            nshl += sglb[ibin].nump;\n            mass += sglb[ibin].mass;\n            ener += sglb[ibin].ener;\n            rvel += sglb[ibin].rvel;\n            for(PS::S64 k = 0; k < NR::NumberOfNucleon; k++) {\n                mele[k] += sglb[ibin].mele[k];\n            }\n            if(nshl < 10000 && ibin != nbin - 1) {\n            //if(nshl < 1000 && ibin != nbin - 1) {\n                continue;\n            }\n\n            PS::F64 rad1   = drad * (ibin + 1);\n            PS::F64 radius = ((rad0 != 0.) ? sqrt(rad0 * rad1) : 0.5 * rad1);\n            PS::F64 volume = 4. * M_PI / 3. * (rad1 * rad1 * rad1 - rad0 * rad0 * rad0);\n            PS::F64 dens   = mass / volume;\n            PS::F64 uene   = ener / mass;\n            rvel  = rvel / (PS::S64)nshl;\n            NR::Nucleon cmps;\n            for(PS::S64 k = 0; k < NR::NumberOfNucleon; k++) {\n                cmps[k] = mele[k] / mass;\n            }\n            menc += mass;\n\n            PS::F64 tin = 1e9;\n            PS::F64 pout, cout, tout, sout, uout;\n            flash_helmholtz_(&dens, &uene, &tin, cmps.getPointer(), &pout, &cout, &tout, &sout);\n            tout = (tout < 1e7) ? 1e7 : tout;\n            flash_helmholtz_e_(&dens, &tout, cmps.getPointer(), &uout);\n            flash_helmholtz_(&dens, &uout, &tout, cmps.getPointer(), &pout, &cout, &tout, &sout);\n            fprintf(fp, \"%+e %+e %+e %+e %+e %+e %+e\", \n                    rad1, dens, pout, tout, uout, menc/CodeUnit::SolarMass, rvel);\n            for(PS::S64 k = 0; k < NR::NumberOfNucleon; k++) {\n                fprintf(fp, \" %+e\", cmps[k]);\n            }\n            fprintf(fp, \" %+e\", sout);\n            fprintf(fp, \"\\n\");\n            \n            nshl = 0;\n            mass = 0.;\n            ener = 0.;\n            rvel = 0.;\n            for(PS::S64 k = 0; k < NR::NumberOfNucleon; k++) {\n                mele[k] = 0.;\n            }\n            rad0 = rad1;\n        }\n        fclose(fp);\n    }\n\n    free(sloc);\n    free(sglb);\n                \n}\n\nint main(int argc, char ** argv) {\n    PS::Initialize(argc, argv);\n\n    PS::ParticleSystem<SPHAnalysis> sph;\n    sph.initialize();\n    sph.createParticle(0);\n    sph.setNumberOfParticleLocal(0);\n\n    char idir[1024], odir[1024];\n    PS::F64 rmax, drad;\n    PS::S64 ibgn, iend;\n    FILE * fp = fopen(argv[1], \"r\");\n    fscanf(fp, \"%s\", idir);\n    fscanf(fp, \"%s\", odir);\n    fscanf(fp, \"%lf%lf\", &rmax, &drad);\n    fscanf(fp, \"%lld%lld\", &ibgn, &iend);\n    fclose(fp);\n\n    init_flash_helmholtz_(&CodeUnit::FractionOfCoulombCorrection);\n\n    for(PS::S64 itime = ibgn; itime <= iend; itime++) {        \n        char tfile[1024];\n        FILE *fp = NULL;\n        PS::S64 tdir = 0;\n        for(PS::S64 iidir = 0; iidir < 100; iidir++) {\n            sprintf(tfile, \"%s/t%02d/sph_t%04d_p%06d_i%06d.dat\", idir, iidir, itime,\n                    PS::Comm::getNumberOfProc(), 0);\n            fp = fopen(tfile, \"r\");\n            if(fp != NULL) {\n                tdir = iidir;\n                break;\n            }\n        }\n        if(fp == NULL) {\n            fprintf(stderr, \"%s is not found.\\n\", tfile);\n            continue;\n        }\n        fclose(fp);\n        \n        char sfile[1024];\n        sprintf(sfile, \"%s/t%02d/sph_t%04d\", idir, tdir, itime);\n        sph.readParticleAscii(sfile, \"%s_p%06d_i%06d.dat\");\n\n        char ofile[1024];\n        sprintf(ofile, \"%s/poly.dat\", odir);\n        sphericalizeWhiteDwarf(rmax, drad, ofile, sph);\n\n    }\n\n    PS::Finalize();\n\n    return 0;\n}\n", "meta": {"hexsha": "47592481bf9d3d9cee6de2115fdf7e4174c8df5b", "size": 9102, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tool.hgas/sphericalize/main.cpp", "max_stars_repo_name": "atrtnkw/sph", "max_stars_repo_head_hexsha": "c6bb3d7fd18f57c51fe60197706741e5a26e6ce4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2018-07-11T00:43:01.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-11T13:41:50.000Z", "max_issues_repo_path": "tool.hgas/sphericalize/main.cpp", "max_issues_repo_name": "atrtnkw/sph", "max_issues_repo_head_hexsha": "c6bb3d7fd18f57c51fe60197706741e5a26e6ce4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tool.hgas/sphericalize/main.cpp", "max_forks_repo_name": "atrtnkw/sph", "max_forks_repo_head_hexsha": "c6bb3d7fd18f57c51fe60197706741e5a26e6ce4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-01-06T14:22:25.000Z", "max_forks_repo_forks_event_max_datetime": "2020-01-06T14:22:25.000Z", "avg_line_length": 32.8592057762, "max_line_length": 97, "alphanum_fraction": 0.4713249835, "num_tokens": 3026, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6859494550081926, "lm_q2_score": 0.5039061705290805, "lm_q1q2_score": 0.3456541630496881}}
{"text": "/* \n// Copyright 2018 University of Liege\n// \n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n// \n//     http://www.apache.org/licenses/LICENSE-2.0\n// \n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//\n// Authors:\n// - Adrien Crovato\n*/\n\n//// Field derivatives mapping\n// Identify cells for which spatial derivatives should be prevented so that surface panel crossing does not occur\n// Results are stored in boolean matrices: row(f) = [dx-, dx+, dy-, dy+, dz-, dz+]\n//\n// I/O:\n// - sGrid: temporary dynamic array containing body panel vertices\n// - numC: list of numerical parameters (structure)\n// - bPan: body panels (structure)\n// - bPan: wake panels (structure)\n// - fPan: field panels (structure)\n\n#include <iostream>\n#include <Eigen/Dense>\n#include \"map_derivatives.h\"\n#include \"cast_ray_pip.h\"\n\nusing namespace std;\nusing namespace Eigen;\n\nvoid map_derivatives(MatrixX3d &sGrid, Numerical_CST &numC, Network &bPan, Network &wPan, Field &fPan) {\n\n    //// Begin\n    // Variable definition\n    int allow = 0;\n    double minX, minY, maxY, minZ, maxZ; // minimal bounding box holding the geometry\n    Vector3d u, w;\n    // Display check\n    cout << \"Mapping field derivatives... \" << flush;\n    // Resize field and network matrices\n    fPan.fbdMap.resize(fPan.nF,6);\n    fPan.fwdMap.resize(fPan.nF,6);\n    // Define box enclosing the body\n    minX = sGrid.col(0).minCoeff() - numC.TOLB;\n    minY = sGrid.col(1).minCoeff() - numC.TOLB;\n    maxY = sGrid.col(1).maxCoeff() + numC.TOLB;\n    minZ = sGrid.col(2).minCoeff() - numC.TOLB;\n    maxZ = sGrid.col(2).maxCoeff() + numC.TOLB;\n\n    //// Map field derivatives\n    int f = 0;\n    for (int j = 0; j < fPan.nY; j++) {\n        for (int k = 0; k < fPan.nZ; k++) {\n            for (int i = 0; i < fPan.nX; i++) {\n\n                // If cell is inside the body, derivatives are prevented\n                if (!fPan.fMap(f)) {\n                    fPan.fbdMap(f, 0) = 0;\n                    fPan.fbdMap(f, 1) = 0;\n                    fPan.fbdMap(f, 2) = 0;\n                    fPan.fbdMap(f, 3) = 0;\n                    fPan.fbdMap(f, 4) = 0;\n                    fPan.fbdMap(f, 5) = 0;\n                    fPan.fwdMap(f, 0) = 0;\n                    fPan.fwdMap(f, 1) = 0;\n                    fPan.fwdMap(f, 2) = 0;\n                    fPan.fwdMap(f, 3) = 0;\n                    fPan.fwdMap(f, 4) = 0;\n                    fPan.fwdMap(f, 5) = 0;\n                }\n                else {\n                    /// 1. X-backward\n                    // Check if cell is not on the domain border\n                    if (i == 0) {\n                        fPan.fbdMap(f, 0) = 0;\n                        fPan.fwdMap(f, 0) = 0;\n                    }\n                    // Create a box enclosing the geometry, based on cell dimensions to restrict the algorithm complexity\n                    else if ((fPan.CG(f,0) < minX)\n                             || (fPan.CG(f,1) < minY || fPan.CG(f,1) > maxY)\n                             || (fPan.CG(f,2) < minZ || fPan.CG(f,2) > maxZ)) {\n                        fPan.fbdMap(f, 0) = 1;\n                        fPan.fwdMap(f, 0) = 1;\n                    }\n                    // Check if previous cell is not an internal cell\n                    else if (!fPan.fMap(f-1)) {\n                        fPan.fbdMap(f, 0) = 0;\n                        fPan.fwdMap(f, 0) = 0;\n                    }\n                    // Create a vector joining the center of two adjacent cells and check if that vector crosses a panel\n                    else {\n                        u = fPan.CG.row(f-1).transpose() - fPan.CG.row(f).transpose();\n                        // Body panel\n                        for (int p = 0; p < bPan.nP; p++) {\n                            w = fPan.CG.row(f).transpose() - bPan.CG.row(p).transpose();\n\n                            allow = cast_ray_pip(u(0),u(1),u(2),w(0),w(1),w(2),fPan.CG(f,0),fPan.CG(f,1),fPan.CG(f,2),\n                                                 bPan.n(p,0),bPan.n(p,1),bPan.n(p,2),bPan.v0(p,0),bPan.v0(p,1),bPan.v0(p,2),\n                                                 bPan.v1(p,0),bPan.v1(p,1),bPan.v1(p,2),bPan.v2(p,0),bPan.v2(p,1),bPan.v2(p,2),\n                                                 bPan.v3(p,0),bPan.v3(p,1),bPan.v3(p,2));\n                            if (!allow)\n                                break;\n                        }\n                        fPan.fbdMap(f, 0) = allow; // Store the result in a boolean matrix\n                        // Wake panel\n                        for (int p = 0; p < wPan.nP; p++) {\n                            w = fPan.CG.row(f).transpose() - wPan.CG.row(p).transpose();\n\n                            allow = cast_ray_pip(u(0),u(1),u(2),w(0),w(1),w(2),fPan.CG(f,0),fPan.CG(f,1),fPan.CG(f,2),\n                                                 wPan.n(p,0),wPan.n(p,1),wPan.n(p,2),wPan.v0(p,0),wPan.v0(p,1),wPan.v0(p,2),\n                                                 wPan.v1(p,0),wPan.v1(p,1),wPan.v1(p,2),wPan.v2(p,0),wPan.v2(p,1),wPan.v2(p,2),\n                                                 wPan.v3(p,0),wPan.v3(p,1),wPan.v3(p,2));\n                            if (!allow)\n                                break;\n                        }\n                        fPan.fwdMap(f, 0) = allow; // Store the result in a boolean matrix\n                    }\n\n                    /// 2. X-forward\n                    // Check if cell is not on the domain border\n                    if (i == fPan.nX - 1) {\n                        fPan.fbdMap(f, 1) = 0;\n                        fPan.fwdMap(f, 1) = 0;\n                    }\n                    // Create a box enclosing the geometry, based on cell dimensions to restrict the algorithm complexity\n                    else if (((fPan.CG(f,0)+fPan.deltaX) < minX)\n                             || (fPan.CG(f,1) < minY || fPan.CG(f,1) > maxY)\n                             || (fPan.CG(f,2) < minZ || fPan.CG(f,2) > maxZ)) {\n                        fPan.fbdMap(f, 1) = 1;\n                        fPan.fwdMap(f, 1) = 1;\n                    }\n                    // Check if next cell is not an internal cell\n                    else if (!fPan.fMap(f+1)) {\n                        fPan.fbdMap(f, 1) = 0;\n                        fPan.fwdMap(f, 1) = 0;\n                    }\n                    // Create a vector joining the center of two adjacent cells and check if that vector crosses a panel\n                    else {\n                        u = fPan.CG.row(f+1).transpose() - fPan.CG.row(f).transpose();\n                        // Body panel\n                        for (int p = 0; p < bPan.nP; p++) {\n                            w = fPan.CG.row(f).transpose() - bPan.CG.row(p).transpose();\n\n                            allow = cast_ray_pip(u(0),u(1),u(2),w(0),w(1),w(2),fPan.CG(f,0),fPan.CG(f,1),fPan.CG(f,2),\n                                                 bPan.n(p,0),bPan.n(p,1),bPan.n(p,2),bPan.v0(p,0),bPan.v0(p,1),bPan.v0(p,2),\n                                                 bPan.v1(p,0),bPan.v1(p,1),bPan.v1(p,2),bPan.v2(p,0),bPan.v2(p,1),bPan.v2(p,2),\n                                                 bPan.v3(p,0),bPan.v3(p,1),bPan.v3(p,2));\n                            if (!allow)\n                                break;\n                        }\n                        fPan.fbdMap(f, 1) = allow; // Store the result in a boolean matrix\n                        // Wake panel\n                        for (int p = 0; p < wPan.nP; p++) {\n                            w = fPan.CG.row(f).transpose() - wPan.CG.row(p).transpose();\n\n                            allow = cast_ray_pip(u(0),u(1),u(2),w(0),w(1),w(2),fPan.CG(f,0),fPan.CG(f,1),fPan.CG(f,2),\n                                                 wPan.n(p,0),wPan.n(p,1),wPan.n(p,2),wPan.v0(p,0),wPan.v0(p,1),wPan.v0(p,2),\n                                                 wPan.v1(p,0),wPan.v1(p,1),wPan.v1(p,2),wPan.v2(p,0),wPan.v2(p,1),wPan.v2(p,2),\n                                                 wPan.v3(p,0),wPan.v3(p,1),wPan.v3(p,2));\n                            if (!allow)\n                                break;\n                        }\n                        fPan.fwdMap(f, 1) = allow; // Store the result in a boolean matrix\n                    }\n\n                    /// 3. Y-backward\n                    // Check if cell is not on the domain border\n                    if (j == 0) {\n                        fPan.fbdMap(f, 2) = 0;\n                        fPan.fwdMap(f, 2) = 0;\n                    }\n                    // Create a box enclosing the geometry, based on cell dimensions to restrict the algorithm complexity\n                    else if ((fPan.CG(f,0) < minX)\n                             || (fPan.CG(f,1) < minY || (fPan.CG(f,1)-fPan.deltaY) > maxY)\n                             || (fPan.CG(f,2) < minZ || fPan.CG(f,2) > maxZ)) {\n                        fPan.fbdMap(f, 2) = 1;\n                        fPan.fwdMap(f, 2) = 1;\n                    }\n                    // Check if previous cell is not an internal cell\n                    else if (!fPan.fMap(f-fPan.nX*fPan.nZ)) {\n                        fPan.fbdMap(f, 2) = 0;\n                        fPan.fwdMap(f, 2) = 0;\n                    }\n                    // Create a vector joining the center of two adjacent cells and check if that vector crosses a panel\n                    else {\n                        u = fPan.CG.row(f-fPan.nX*fPan.nZ).transpose() - fPan.CG.row(f).transpose();\n                        // Body panel\n                        for (int p = 0; p < bPan.nP; p++) {\n                            w = fPan.CG.row(f).transpose() - bPan.CG.row(p).transpose();\n\n                            allow = cast_ray_pip(u(0),u(1),u(2),w(0),w(1),w(2),fPan.CG(f,0),fPan.CG(f,1),fPan.CG(f,2),\n                                                 bPan.n(p,0),bPan.n(p,1),bPan.n(p,2),bPan.v0(p,0),bPan.v0(p,1),bPan.v0(p,2),\n                                                 bPan.v1(p,0),bPan.v1(p,1),bPan.v1(p,2),bPan.v2(p,0),bPan.v2(p,1),bPan.v2(p,2),\n                                                 bPan.v3(p,0),bPan.v3(p,1),bPan.v3(p,2));\n                            if (!allow)\n                                break;\n                        }\n                        fPan.fbdMap(f, 2) = allow; // Store the result in a boolean matrix\n                        // Wake panel\n                        for (int p = 0; p < wPan.nP; p++) {\n                            w = fPan.CG.row(f).transpose() - wPan.CG.row(p).transpose();\n\n                            allow = cast_ray_pip(u(0),u(1),u(2),w(0),w(1),w(2),fPan.CG(f,0),fPan.CG(f,1),fPan.CG(f,2),\n                                                 wPan.n(p,0),wPan.n(p,1),wPan.n(p,2),wPan.v0(p,0),wPan.v0(p,1),wPan.v0(p,2),\n                                                 wPan.v1(p,0),wPan.v1(p,1),wPan.v1(p,2),wPan.v2(p,0),wPan.v2(p,1),wPan.v2(p,2),\n                                                 wPan.v3(p,0),wPan.v3(p,1),wPan.v3(p,2));\n                            if (!allow)\n                                break;\n                        }\n                        fPan.fwdMap(f, 2) = allow; // Store the result in a boolean matrix\n                    }\n\n                    /// 4. Y-forward\n                    // Check if cell is not on the domain border\n                    if (j == fPan.nY - 1) {\n                        fPan.fbdMap(f, 3) = 0;\n                        fPan.fwdMap(f, 3) = 0;\n                    }\n                    // Create a box enclosing the geometry, based on cell dimensions to restrict the algorithm complexity\n                    else if ((fPan.CG(f,0) < minX)\n                             || ((fPan.CG(f,1)+fPan.deltaY) < minY || fPan.CG(f,1) > maxY)\n                             || (fPan.CG(f,2) < minZ || fPan.CG(f,2) > maxZ)) {\n                        fPan.fbdMap(f, 3) = 1;\n                        fPan.fwdMap(f, 3) = 1;\n                    }\n                    // Check if next cell is not an internal cell\n                    else if (!fPan.fMap(f+fPan.nX*fPan.nZ)) {\n                        fPan.fbdMap(f, 3) = 0;\n                        fPan.fwdMap(f, 3) = 0;\n                    }\n                    // Create a vector joining the center of two adjacent cells and check if that vector crosses a panel\n                    else {\n                        u = fPan.CG.row(f+fPan.nX*fPan.nZ).transpose() - fPan.CG.row(f).transpose();\n                        // Body panel\n                        for (int p = 0; p < bPan.nP; p++) {\n                            w = fPan.CG.row(f).transpose() - bPan.CG.row(p).transpose();\n\n                            allow = cast_ray_pip(u(0),u(1),u(2),w(0),w(1),w(2),fPan.CG(f,0),fPan.CG(f,1),fPan.CG(f,2),\n                                                 bPan.n(p,0),bPan.n(p,1),bPan.n(p,2),bPan.v0(p,0),bPan.v0(p,1),bPan.v0(p,2),\n                                                 bPan.v1(p,0),bPan.v1(p,1),bPan.v1(p,2),bPan.v2(p,0),bPan.v2(p,1),bPan.v2(p,2),\n                                                 bPan.v3(p,0),bPan.v3(p,1),bPan.v3(p,2));\n                            if (!allow)\n                                break;\n                        }\n                        fPan.fbdMap(f, 3) = allow; // Store the result in a boolean matrix\n                        // Wake panel\n                        for (int p = 0; p < wPan.nP; p++) {\n                            w = fPan.CG.row(f).transpose() - wPan.CG.row(p).transpose();\n\n                            allow = cast_ray_pip(u(0),u(1),u(2),w(0),w(1),w(2),fPan.CG(f,0),fPan.CG(f,1),fPan.CG(f,2),\n                                                 wPan.n(p,0),wPan.n(p,1),wPan.n(p,2),wPan.v0(p,0),wPan.v0(p,1),wPan.v0(p,2),\n                                                 wPan.v1(p,0),wPan.v1(p,1),wPan.v1(p,2),wPan.v2(p,0),wPan.v2(p,1),wPan.v2(p,2),\n                                                 wPan.v3(p,0),wPan.v3(p,1),wPan.v3(p,2));\n                            if (!allow)\n                                break;\n                        }\n                        fPan.fwdMap(f, 3) = allow; // Store the result in a boolean matrix\n                    }\n\n                    /// 5. Z-backward\n                    // Check if cell is not on the domain border\n                    if (k == 0) {\n                        fPan.fbdMap(f, 4) = 0;\n                        fPan.fwdMap(f, 4) = 0;\n                    }\n                    // Create a box enclosing the geometry, based on cell dimensions to restrict the algorithm complexity\n                    else if ((fPan.CG(f,0) < minX)\n                             || (fPan.CG(f,1) < minY || fPan.CG(f,1) > maxY)\n                             || (fPan.CG(f,2) < minZ || (fPan.CG(f,2)-fPan.deltaZ) > maxZ)) {\n                        fPan.fbdMap(f, 4) = 1;\n                        fPan.fwdMap(f, 4) = 1;\n                    }\n                    // Check if previous cell is not an internal cell\n                    else if (!fPan.fMap(f-fPan.nX)) {\n                        fPan.fbdMap(f, 4) = 0;\n                        fPan.fwdMap(f, 4) = 0;\n                    }\n                    // Create a vector joining the center of two adjacent cells and check if that vector crosses a panel\n                    else {\n                        u = fPan.CG.row(f-fPan.nX).transpose() - fPan.CG.row(f).transpose();\n                        // Body panel\n                        for (int p = 0; p < bPan.nP; p++) {\n                            w = fPan.CG.row(f).transpose() - bPan.CG.row(p).transpose();\n\n                            allow = cast_ray_pip(u(0),u(1),u(2),w(0),w(1),w(2),fPan.CG(f,0),fPan.CG(f,1),fPan.CG(f,2),\n                                                 bPan.n(p,0),bPan.n(p,1),bPan.n(p,2),bPan.v0(p,0),bPan.v0(p,1),bPan.v0(p,2),\n                                                 bPan.v1(p,0),bPan.v1(p,1),bPan.v1(p,2),bPan.v2(p,0),bPan.v2(p,1),bPan.v2(p,2),\n                                                 bPan.v3(p,0),bPan.v3(p,1),bPan.v3(p,2));\n                            if (!allow)\n                                break;\n                        }\n                        fPan.fbdMap(f, 4) = allow; // Store the result in a boolean matrix\n                        // Wake panel\n                        for (int p = 0; p < wPan.nP; p++) {\n                            w = fPan.CG.row(f).transpose() - wPan.CG.row(p).transpose();\n\n                            allow = cast_ray_pip(u(0),u(1),u(2),w(0),w(1),w(2),fPan.CG(f,0),fPan.CG(f,1),fPan.CG(f,2),\n                                                 wPan.n(p,0),wPan.n(p,1),wPan.n(p,2),wPan.v0(p,0),wPan.v0(p,1),wPan.v0(p,2),\n                                                 wPan.v1(p,0),wPan.v1(p,1),wPan.v1(p,2),wPan.v2(p,0),wPan.v2(p,1),wPan.v2(p,2),\n                                                 wPan.v3(p,0),wPan.v3(p,1),wPan.v3(p,2));\n                            if (!allow)\n                                break;\n                        }\n                        fPan.fwdMap(f, 4) = allow; // Store the result in a boolean matrix\n                    }\n\n                    /// 6. Z-forward\n                    // Check if cell is not on the domain border\n                    if (k == fPan.nZ - 1) {\n                        fPan.fbdMap(f, 5) = 0;\n                        fPan.fwdMap(f, 5) = 0;\n                    }\n                    // Create a box enclosing the geometry, based on cell dimensions to restrict the algorithm complexity\n                    else if ((fPan.CG(f,0) < minX)\n                             || (fPan.CG(f,1) < minY || fPan.CG(f,1) > maxY)\n                             || ((fPan.CG(f,2)+fPan.deltaZ) < minZ || fPan.CG(f,2) > maxZ)) {\n                        fPan.fbdMap(f, 5) = 1;\n                        fPan.fwdMap(f, 5) = 1;\n                    }\n                    // Check if next cell is not an internal cell\n                    else if (!fPan.fMap(f+fPan.nX)) {\n                        fPan.fbdMap(f, 5) = 0;\n                        fPan.fwdMap(f, 5) = 0;\n                    }\n                    // Create a vector joining the center of two adjacent cells and check if that vector crosses a panel\n                    else {\n                        u = fPan.CG.row(f+fPan.nX).transpose() - fPan.CG.row(f).transpose();\n                        // Body panel\n                        for (int p = 0; p < bPan.nP; p++) {\n                            w = fPan.CG.row(f).transpose() - bPan.CG.row(p).transpose();\n\n                            allow = cast_ray_pip(u(0),u(1),u(2),w(0),w(1),w(2),fPan.CG(f,0),fPan.CG(f,1),fPan.CG(f,2),\n                                                 bPan.n(p,0),bPan.n(p,1),bPan.n(p,2),bPan.v0(p,0),bPan.v0(p,1),bPan.v0(p,2),\n                                                 bPan.v1(p,0),bPan.v1(p,1),bPan.v1(p,2),bPan.v2(p,0),bPan.v2(p,1),bPan.v2(p,2),\n                                                 bPan.v3(p,0),bPan.v3(p,1),bPan.v3(p,2));\n                            if (!allow)\n                                break;\n                        }\n                        fPan.fbdMap(f, 5) = allow; // Store the result in a boolean matrix\n                        // Wake panel\n                        for (int p = 0; p < wPan.nP; p++) {\n                            w = fPan.CG.row(f).transpose() - wPan.CG.row(p).transpose();\n\n                            allow = cast_ray_pip(u(0),u(1),u(2),w(0),w(1),w(2),fPan.CG(f,0),fPan.CG(f,1),fPan.CG(f,2),\n                                                 wPan.n(p,0),wPan.n(p,1),wPan.n(p,2),wPan.v0(p,0),wPan.v0(p,1),wPan.v0(p,2),\n                                                 wPan.v1(p,0),wPan.v1(p,1),wPan.v1(p,2),wPan.v2(p,0),wPan.v2(p,1),wPan.v2(p,2),\n                                                 wPan.v3(p,0),wPan.v3(p,1),wPan.v3(p,2));\n                            if (!allow)\n                                break;\n                        }\n                        fPan.fwdMap(f, 5) = allow; // Store the result in a boolean matrix\n                    }\n                }\n                f++;\n            }\n        }\n    }\n\n    //// Control display\n    cout << \"Done!\" << endl;\n    #ifdef VERBOSE\n        cout << \"Allowed derivatives (body) map: \" << fPan.fbdMap.rows() << 'X' << fPan.fbdMap.cols() << endl;\n        for (int i = 0; i < fPan.nF; i++)\n            cout << fPan.fbdMap.row(i) << endl;\n        cout << endl;\n        cout << \"Allowed derivatives (wake) map: \" << fPan.fwdMap.rows() << 'X' << fPan.fwdMap.cols() << endl;\n        for (int i = 0; i < fPan.nF; i++)\n            cout << fPan.fwdMap.row(i) << endl;\n    #endif\n    cout << endl;\n}", "meta": {"hexsha": "576d22199e20ab37e6f953a98ff2732f4cdceb41", "size": 20892, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/map_derivatives.cpp", "max_stars_repo_name": "acrovato/aero", "max_stars_repo_head_hexsha": "310e6840670f5a39ca015c61c9090f123da8cfd6", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2020-11-16T15:24:12.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-15T09:36:09.000Z", "max_issues_repo_path": "src/map_derivatives.cpp", "max_issues_repo_name": "acrovato/aero", "max_issues_repo_head_hexsha": "310e6840670f5a39ca015c61c9090f123da8cfd6", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/map_derivatives.cpp", "max_forks_repo_name": "acrovato/aero", "max_forks_repo_head_hexsha": "310e6840670f5a39ca015c61c9090f123da8cfd6", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 55.1240105541, "max_line_length": 127, "alphanum_fraction": 0.3959410301, "num_tokens": 5733, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6859494550081925, "lm_q2_score": 0.5039061705290805, "lm_q1q2_score": 0.34565416304968805}}
{"text": "//  (C) Copyright Nick Thompson 2020.\n//  Use, modification and distribution are subject to the\n//  Boost Software License, Version 1.0. (See accompanying file\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n#ifndef BOOST_MATH_TOOLS_ULP_PLOT_HPP\n#define BOOST_MATH_TOOLS_ULP_PLOT_HPP\n#include <algorithm>\n#include <iostream>\n#include <iomanip>\n#include <cassert>\n#include <vector>\n#include <utility>\n#include <fstream>\n#include <string>\n#include <list>\n#include <random>\n#include <stdexcept>\n#include <boost/math/tools/condition_numbers.hpp>\n#include <boost/random/uniform_real_distribution.hpp>\n#include <boost/algorithm/string/predicate.hpp>\n\n\n// Design of this function comes from:\n// https://blogs.mathworks.com/cleve/2017/01/23/ulps-plots-reveal-math-function-accurary/\n\n// The envelope is the maximum of 1/2 and half the condition number of function evaluation.\n\nnamespace boost::math::tools {\n\nnamespace detail {\ntemplate<class F1, class F2, class CoarseReal, class PreciseReal>\nvoid write_gridlines(std::ostream& fs, int horizontal_lines, int vertical_lines,\n                     F1 x_scale, F2 y_scale, CoarseReal min_x, CoarseReal max_x, PreciseReal min_y, PreciseReal max_y,\n                     int graph_width, int graph_height, int margin_left, std::string const & font_color)\n{\n  // Make a grid:\n  for (int i = 1; i <= horizontal_lines; ++i) {\n      PreciseReal y_cord_dataspace = min_y +  ((max_y - min_y)*i)/horizontal_lines;\n      auto y = y_scale(y_cord_dataspace);\n      fs << \"<line x1='0' y1='\" << y << \"' x2='\" << graph_width\n         << \"' y2='\" << y\n         << \"' stroke='gray' stroke-width='1' opacity='0.5' stroke-dasharray='4' />\\n\";\n\n      fs << \"<text x='\" <<  -margin_left/4 + 5 << \"' y='\" << y - 3\n         << \"' font-family='times' font-size='10' fill='\" << font_color << \"' transform='rotate(-90 \"\n         << -margin_left/4 + 8 << \" \" << y + 5 << \")'>\"\n         << std::setprecision(4) << y_cord_dataspace << \"</text>\\n\";\n   }\n\n    for (int i = 1; i <= vertical_lines; ++i) {\n        CoarseReal x_cord_dataspace = min_x +  ((max_x - min_x)*i)/vertical_lines;\n        CoarseReal x = x_scale(x_cord_dataspace);\n        fs << \"<line x1='\" << x << \"' y1='0' x2='\" << x\n           << \"' y2='\" << graph_height\n           << \"' stroke='gray' stroke-width='1' opacity='0.5' stroke-dasharray='4' />\\n\";\n\n        fs << \"<text x='\" <<  x - 10  << \"' y='\" << graph_height + 10\n           << \"' font-family='times' font-size='10' fill='\" << font_color << \"'>\"\n           << std::setprecision(4) << x_cord_dataspace << \"</text>\\n\";\n    }\n}\n}\n\ntemplate<class F, typename PreciseReal, typename CoarseReal>\nclass ulps_plot {\npublic:\n    ulps_plot(F hi_acc_impl, CoarseReal a, CoarseReal b,\n             size_t samples = 1000, bool perturb_abscissas = false, int random_seed = -1);\n\n    ulps_plot& clip(PreciseReal clip);\n\n    ulps_plot& width(int width);\n\n    ulps_plot& envelope_color(std::string const & color);\n\n    ulps_plot& title(std::string const & title);\n\n    ulps_plot& background_color(std::string const & background_color);\n\n    ulps_plot& font_color(std::string const & font_color);\n\n    ulps_plot& crop_color(std::string const & color);\n\n    ulps_plot& nan_color(std::string const & color);\n\n    ulps_plot& ulp_envelope(bool write_ulp);\n\n    template<class G>\n    ulps_plot& add_fn(G g, std::string const & color = \"steelblue\");\n\n    ulps_plot& horizontal_lines(int horizontal_lines);\n\n    ulps_plot& vertical_lines(int vertical_lines);\n\n    void write(std::string const & filename) const;\n\n    friend std::ostream& operator<<(std::ostream& fs, ulps_plot const & plot)\n    {\n        using std::abs;\n        using std::floor;\n        using std::isnan;\n        if (plot.ulp_list_.size() == 0)\n        {\n            throw std::domain_error(\"No functions added for comparison.\");\n        }\n        if (plot.width_ <= 1)\n        {\n            throw std::domain_error(\"Width = \" + std::to_string(plot.width_) + \", which is too small.\");\n        }\n\n        PreciseReal worst_ulp_distance = 0;\n        PreciseReal min_y = std::numeric_limits<PreciseReal>::max();\n        PreciseReal max_y = std::numeric_limits<PreciseReal>::lowest();\n        for (auto const & ulp_vec : plot.ulp_list_)\n        {\n            for (auto const & ulp : ulp_vec)\n            {\n                if (static_cast<PreciseReal>(abs(ulp)) > worst_ulp_distance)\n                {\n                    worst_ulp_distance = static_cast<PreciseReal>(abs(ulp));\n                }\n                if (static_cast<PreciseReal>(ulp) < min_y)\n                {\n                    min_y = static_cast<PreciseReal>(ulp);\n                }\n                if (static_cast<PreciseReal>(ulp) > max_y)\n                {\n                    max_y = static_cast<PreciseReal>(ulp);\n                }\n            }\n        }\n\n        // half-ulp accuracy is the best that can be expected; sometimes we can get less, but barely less.\n        // then the axes don't show up; painful!\n        if (max_y < 0.5) {\n            max_y = 0.5;\n        }\n        if (min_y > -0.5) {\n            min_y = -0.5;\n        }\n\n        if (plot.clip_ > 0)\n        {\n            if (max_y > plot.clip_)\n            {\n                max_y = plot.clip_;\n            }\n            if (min_y < -plot.clip_)\n            {\n                min_y = -plot.clip_;\n            }\n        }\n\n        int height = static_cast<int>(floor(double(plot.width_)/1.61803));\n        int margin_top = 40;\n        int margin_left = 25;\n        if (plot.title_.size() == 0)\n        {\n            margin_top = 10;\n            margin_left = 15;\n        }\n        int margin_bottom = 20;\n        int margin_right = 20;\n        int graph_height = height - margin_bottom - margin_top;\n        int graph_width = plot.width_ - margin_left - margin_right;\n\n        // Maps [a,b] to [0, graph_width]\n        auto x_scale = [&](CoarseReal x)->CoarseReal\n        {\n            return ((x-plot.a_)/(plot.b_ - plot.a_))*static_cast<CoarseReal>(graph_width);\n        };\n\n        auto y_scale = [&](PreciseReal y)->PreciseReal\n        {\n            return ((max_y - y)/(max_y - min_y) )*static_cast<PreciseReal>(graph_height);\n        };\n\n        fs << \"<?xml version=\\\"1.0\\\" encoding='UTF-8' ?>\\n\"\n           << \"<svg xmlns='http://www.w3.org/2000/svg' width='\"\n           << plot.width_ << \"' height='\"\n           << height << \"'>\\n\"\n           << \"<style>\\nsvg { background-color:\" << plot.background_color_ << \"; }\\n\"\n           << \"</style>\\n\";\n        if (plot.title_.size() > 0)\n        {\n            fs << \"<text x='\" << floor(plot.width_/2)\n               << \"' y='\" << floor(margin_top/2)\n               << \"' font-family='Palatino' font-size='25' fill='\"\n               << plot.font_color_  << \"'  alignment-baseline='middle' text-anchor='middle'>\"\n               << plot.title_\n               << \"</text>\\n\";\n        }\n\n        // Construct SVG group to simplify the calculations slightly:\n        fs << \"<g transform='translate(\" << margin_left << \", \" << margin_top << \")'>\\n\";\n            // y-axis:\n        fs  << \"<line x1='0' y1='0' x2='0' y2='\" << graph_height\n            << \"' stroke='gray' stroke-width='1'/>\\n\";\n        PreciseReal x_axis_loc = y_scale(static_cast<PreciseReal>(0));\n        fs << \"<line x1='0' y1='\" << x_axis_loc\n            << \"' x2='\" << graph_width << \"' y2='\" << x_axis_loc\n            << \"' stroke='gray' stroke-width='1'/>\\n\";\n\n        if (worst_ulp_distance > 3)\n        {\n            detail::write_gridlines(fs, plot.horizontal_lines_, plot.vertical_lines_, x_scale, y_scale, plot.a_, plot.b_,\n                                    min_y, max_y, graph_width, graph_height, margin_left, plot.font_color_);\n        }\n        else\n        {\n            std::vector<double> ys{-3.0, -2.5, -2.0, -1.5, -1.0, -0.5, 0.5, 1.0, 1.5, 2.0, 2.5, 3.0};\n            for (size_t i = 0; i < ys.size(); ++i)\n            {\n                if (min_y <= ys[i] && ys[i] <= max_y)\n                {\n                    PreciseReal y_cord_dataspace = ys[i];\n                    PreciseReal y = y_scale(y_cord_dataspace);\n                    fs << \"<line x1='0' y1='\" << y << \"' x2='\" << graph_width\n                       << \"' y2='\" << y\n                       << \"' stroke='gray' stroke-width='1' opacity='0.5' stroke-dasharray='4' />\\n\";\n\n                    fs << \"<text x='\" <<  -margin_left/2 << \"' y='\" << y - 3\n                       << \"' font-family='times' font-size='10' fill='\" << plot.font_color_ << \"' transform='rotate(-90 \"\n                       << -margin_left/2 + 7 << \" \" << y << \")'>\"\n                       <<  std::setprecision(4) << y_cord_dataspace << \"</text>\\n\";\n                }\n            }\n            for (int i = 1; i <= plot.vertical_lines_; ++i)\n            {\n                CoarseReal x_cord_dataspace = plot.a_ +  ((plot.b_ - plot.a_)*i)/plot.vertical_lines_;\n                CoarseReal x = x_scale(x_cord_dataspace);\n                fs << \"<line x1='\" << x << \"' y1='0' x2='\" << x\n                   << \"' y2='\" << graph_height\n                   << \"' stroke='gray' stroke-width='1' opacity='0.5' stroke-dasharray='4' />\\n\";\n\n                fs << \"<text x='\" <<  x - 10  << \"' y='\" << graph_height + 10\n                   << \"' font-family='times' font-size='10' fill='\" << plot.font_color_ << \"'>\"\n                   << std::setprecision(4) << x_cord_dataspace << \"</text>\\n\";\n            }\n        }\n\n        int color_idx = 0;\n        for (auto const & ulp : plot.ulp_list_)\n        {\n            std::string color = plot.colors_[color_idx++];\n            for (size_t j = 0; j < ulp.size(); ++j)\n            {\n                if (isnan(ulp[j]))\n                {\n                    if(plot.nan_color_ == \"\")\n                        continue;\n                    CoarseReal x = x_scale(plot.coarse_abscissas_[j]);\n                    PreciseReal y = y_scale(static_cast<PreciseReal>(plot.clip_));\n                    fs << \"<circle cx='\" << x << \"' cy='\" << y << \"' r='1' fill='\" << plot.nan_color_ << \"'/>\\n\";\n                    y = y_scale(static_cast<PreciseReal>(-plot.clip_));\n                    fs << \"<circle cx='\" << x << \"' cy='\" << y << \"' r='1' fill='\" << plot.nan_color_ << \"'/>\\n\";\n                }\n                if (plot.clip_ > 0 && static_cast<PreciseReal>(abs(ulp[j])) > plot.clip_)\n                {\n                   if (plot.crop_color_ == \"\")\n                      continue;\n                   CoarseReal x = x_scale(plot.coarse_abscissas_[j]);\n                   PreciseReal y = y_scale(static_cast<PreciseReal>(ulp[j] < 0 ? -plot.clip_ : plot.clip_));\n                   fs << \"<circle cx='\" << x << \"' cy='\" << y << \"' r='1' fill='\" << plot.crop_color_ << \"'/>\\n\";\n                }\n                else\n                {\n                   CoarseReal x = x_scale(plot.coarse_abscissas_[j]);\n                   PreciseReal y = y_scale(static_cast<PreciseReal>(ulp[j]));\n                   fs << \"<circle cx='\" << x << \"' cy='\" << y << \"' r='1' fill='\" << color << \"'/>\\n\";\n                }\n            }\n        }\n\n        if (plot.ulp_envelope_)\n        {\n            std::string close_path = \"' stroke='\"  + plot.envelope_color_ + \"' stroke-width='1' fill='none'></path>\\n\";\n            size_t jstart = 0;\n            while (plot.cond_[jstart] > max_y)\n            {\n                ++jstart;\n                if (jstart >= plot.cond_.size())\n                {\n                    goto done;\n                }\n            }\n\n            size_t jmin = jstart;\n        new_top_path:\n            if (jmin >= plot.cond_.size())\n            {\n                goto start_bottom_paths;\n            }\n            fs << \"<path d='M\" << x_scale(plot.coarse_abscissas_[jmin]) << \" \" << y_scale(plot.cond_[jmin]);\n\n            for (size_t j = jmin + 1; j < plot.coarse_abscissas_.size(); ++j)\n            {\n                bool bad = isnan(plot.cond_[j]) || (plot.cond_[j] > max_y);\n                if (bad)\n                {\n                    ++j;\n                    while ( (j < plot.coarse_abscissas_.size() - 2) && bad)\n                    {\n                        bad = isnan(plot.cond_[j]) || (plot.cond_[j] > max_y);\n                        ++j;\n                    }\n                    jmin = j;\n                    fs << close_path;\n                    goto new_top_path;\n                }\n\n                CoarseReal t = x_scale(plot.coarse_abscissas_[j]);\n                PreciseReal y = y_scale(plot.cond_[j]);\n                fs << \" L\" << t << \" \" << y;\n            }\n            fs << close_path;\n        start_bottom_paths:\n            jmin = jstart;\n        new_bottom_path:\n            if (jmin >= plot.cond_.size())\n            {\n                goto done;\n            }\n            fs << \"<path d='M\" << x_scale(plot.coarse_abscissas_[jmin]) << \" \" << y_scale(-plot.cond_[jmin]);\n\n            for (size_t j = jmin + 1; j < plot.coarse_abscissas_.size(); ++j)\n            {\n                bool bad = isnan(plot.cond_[j]) || (-plot.cond_[j] < min_y);\n                if (bad)\n                {\n                    ++j;\n                    while ( (j < plot.coarse_abscissas_.size() - 2) && bad)\n                    {\n                        bad = isnan(plot.cond_[j]) || (-plot.cond_[j] < min_y);\n                        ++j;\n                    }\n                    jmin = j;\n                    fs << close_path;\n                    goto new_bottom_path;\n                }\n                CoarseReal t = x_scale(plot.coarse_abscissas_[j]);\n                PreciseReal y = y_scale(-plot.cond_[j]);\n                fs << \" L\" << t << \" \" << y;\n            }\n            fs << close_path;\n        }\n    done:\n        fs << \"</g>\\n\"\n           << \"</svg>\\n\";\n        return fs;\n    }\n\nprivate:\n    std::vector<PreciseReal> precise_abscissas_;\n    std::vector<CoarseReal> coarse_abscissas_;\n    std::vector<PreciseReal> precise_ordinates_;\n    std::vector<PreciseReal> cond_;\n    std::list<std::vector<CoarseReal>> ulp_list_;\n    std::vector<std::string> colors_;\n    CoarseReal a_;\n    CoarseReal b_;\n    PreciseReal clip_;\n    int width_;\n    std::string envelope_color_;\n    bool ulp_envelope_;\n    int horizontal_lines_;\n    int vertical_lines_;\n    std::string title_;\n    std::string background_color_;\n    std::string font_color_;\n    std::string crop_color_;\n    std::string nan_color_;\n};\n\ntemplate<class F, typename PreciseReal, typename CoarseReal>\nulps_plot<F, PreciseReal, CoarseReal>& ulps_plot<F, PreciseReal, CoarseReal>::envelope_color(std::string const & color)\n{\n    envelope_color_ = color;\n    return *this;\n}\n\ntemplate<class F, typename PreciseReal, typename CoarseReal>\nulps_plot<F, PreciseReal, CoarseReal>& ulps_plot<F, PreciseReal, CoarseReal>::clip(PreciseReal clip)\n{\n    clip_ = clip;\n    return *this;\n}\n\ntemplate<class F, typename PreciseReal, typename CoarseReal>\nulps_plot<F, PreciseReal, CoarseReal>& ulps_plot<F, PreciseReal, CoarseReal>::width(int width)\n{\n    width_ = width;\n    return *this;\n}\n\ntemplate<class F, typename PreciseReal, typename CoarseReal>\nulps_plot<F, PreciseReal, CoarseReal>& ulps_plot<F, PreciseReal, CoarseReal>::horizontal_lines(int horizontal_lines)\n{\n    horizontal_lines_ = horizontal_lines;\n    return *this;\n}\n\ntemplate<class F, typename PreciseReal, typename CoarseReal>\nulps_plot<F, PreciseReal, CoarseReal>& ulps_plot<F, PreciseReal, CoarseReal>::vertical_lines(int vertical_lines)\n{\n    vertical_lines_ = vertical_lines;\n    return *this;\n}\n\ntemplate<class F, typename PreciseReal, typename CoarseReal>\nulps_plot<F, PreciseReal, CoarseReal>& ulps_plot<F, PreciseReal, CoarseReal>::title(std::string const & title)\n{\n    title_ = title;\n    return *this;\n}\n\ntemplate<class F, typename PreciseReal, typename CoarseReal>\nulps_plot<F, PreciseReal, CoarseReal>& ulps_plot<F, PreciseReal, CoarseReal>::background_color(std::string const & background_color)\n{\n    background_color_ = background_color;\n    return *this;\n}\n\ntemplate<class F, typename PreciseReal, typename CoarseReal>\nulps_plot<F, PreciseReal, CoarseReal>& ulps_plot<F, PreciseReal, CoarseReal>::font_color(std::string const & font_color)\n{\n    font_color_ = font_color;\n    return *this;\n}\n\ntemplate<class F, typename PreciseReal, typename CoarseReal>\nulps_plot<F, PreciseReal, CoarseReal>& ulps_plot<F, PreciseReal, CoarseReal>::crop_color(std::string const & color)\n{\n    crop_color_ = color;\n    return *this;\n}\n\ntemplate<class F, typename PreciseReal, typename CoarseReal>\nulps_plot<F, PreciseReal, CoarseReal>& ulps_plot<F, PreciseReal, CoarseReal>::nan_color(std::string const & color)\n{\n    nan_color_ = color;\n    return *this;\n}\n\ntemplate<class F, typename PreciseReal, typename CoarseReal>\nulps_plot<F, PreciseReal, CoarseReal>& ulps_plot<F, PreciseReal, CoarseReal>::ulp_envelope(bool write_ulp_envelope)\n{\n    ulp_envelope_ = write_ulp_envelope;\n    return *this;\n}\n\ntemplate<class F, typename PreciseReal, typename CoarseReal>\nvoid ulps_plot<F, PreciseReal, CoarseReal>::write(std::string const & filename) const\n{\n    if (!boost::algorithm::ends_with(filename, \".svg\"))\n    {\n        throw std::logic_error(\"Only svg files are supported at this time.\");\n    }\n    std::ofstream fs(filename);\n    fs << *this;\n    fs.close();\n}\n\n\ntemplate<class F, typename PreciseReal, typename CoarseReal>\nulps_plot<F, PreciseReal, CoarseReal>::ulps_plot(F hi_acc_impl, CoarseReal a, CoarseReal b,\n             size_t samples, bool perturb_abscissas, int random_seed) : crop_color_(\"red\")\n{\n    // Use digits10 for this comparison in case the two types have differeing radixes:\n    static_assert(std::numeric_limits<PreciseReal>::digits10 >= std::numeric_limits<CoarseReal>::digits10, \"PreciseReal must have higher precision that CoarseReal\");\n    if (samples < 10)\n    {\n        throw std::domain_error(\"Must have at least 10 samples, samples = \" + std::to_string(samples));\n    }\n    if (b <= a)\n    {\n        throw std::domain_error(\"On interval [a,b], b > a is required.\");\n    }\n    a_ = a;\n    b_ = b;\n\n    std::mt19937_64 gen;\n    if (random_seed == -1)\n    {\n        std::random_device rd;\n        gen.seed(rd());\n    }\n    // Boost's uniform_real_distribution can generate quad and multiprecision random numbers; std's cannot:\n    boost::random::uniform_real_distribution<PreciseReal> dis(static_cast<PreciseReal>(a), static_cast<PreciseReal>(b));\n    precise_abscissas_.resize(samples);\n    coarse_abscissas_.resize(samples);\n\n    if (perturb_abscissas)\n    {\n        for(size_t i = 0; i < samples; ++i)\n        {\n            precise_abscissas_[i] = dis(gen);\n        }\n        std::sort(precise_abscissas_.begin(), precise_abscissas_.end());\n        for (size_t i = 0; i < samples; ++i)\n        {\n            coarse_abscissas_[i] = static_cast<CoarseReal>(precise_abscissas_[i]);\n        }\n    }\n    else\n    {\n        for(size_t i = 0; i < samples; ++i)\n        {\n            coarse_abscissas_[i] = static_cast<CoarseReal>(dis(gen));\n        }\n        std::sort(coarse_abscissas_.begin(), coarse_abscissas_.end());\n        for (size_t i = 0; i < samples; ++i)\n        {\n            precise_abscissas_[i] = static_cast<PreciseReal>(coarse_abscissas_[i]);\n        }\n    }\n\n    precise_ordinates_.resize(samples);\n    for (size_t i = 0; i < samples; ++i)\n    {\n        precise_ordinates_[i] = hi_acc_impl(precise_abscissas_[i]);\n    }\n\n    cond_.resize(samples, std::numeric_limits<PreciseReal>::quiet_NaN());\n    for (size_t i = 0 ; i < samples; ++i)\n    {\n        PreciseReal y = precise_ordinates_[i];\n        if (y != 0)\n        {\n            // Maybe cond_ is badly names; should it be half_cond_?\n            cond_[i] = boost::math::tools::evaluation_condition_number(hi_acc_impl, precise_abscissas_[i])/2;\n            // Half-ULP accuracy is the correctly rounded result, so make sure the envelop doesn't go below this:\n            if (cond_[i] < 0.5)\n            {\n                cond_[i] = 0.5;\n            }\n        }\n        // else leave it as nan.\n    }\n    clip_ = -1;\n    width_ = 1100;\n    envelope_color_ = \"chartreuse\";\n    ulp_envelope_ = true;\n    horizontal_lines_ = 8;\n    vertical_lines_ = 10;\n    title_ = \"\";\n    background_color_ = \"black\";\n    font_color_ = \"white\";\n}\n\ntemplate<class F, typename PreciseReal, typename CoarseReal>\ntemplate<class G>\nulps_plot<F, PreciseReal, CoarseReal>& ulps_plot<F, PreciseReal, CoarseReal>::add_fn(G g, std::string const & color)\n{\n    using std::abs;\n    size_t samples = precise_abscissas_.size();\n    std::vector<CoarseReal> ulps(samples);\n    for (size_t i = 0; i < samples; ++i)\n    {\n        PreciseReal y_hi_acc = precise_ordinates_[i];\n        PreciseReal y_lo_acc = static_cast<PreciseReal>(g(coarse_abscissas_[i]));\n        PreciseReal absy = abs(y_hi_acc);\n        PreciseReal dist = static_cast<PreciseReal>(nextafter(static_cast<CoarseReal>(absy), std::numeric_limits<CoarseReal>::max()) - static_cast<CoarseReal>(absy));\n        ulps[i] = static_cast<CoarseReal>((y_lo_acc - y_hi_acc)/dist);\n    }\n    ulp_list_.emplace_back(ulps);\n    colors_.emplace_back(color);\n    return *this;\n}\n\n\n\n\n} // namespace boost::math::tools\n#endif\n", "meta": {"hexsha": "3d941f44452f6941f0e5cfa32414c2d70ac2dd9d", "size": 21098, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ReactNativeFrontend/ios/Pods/boost/boost/math/tools/ulps_plot.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/tools/ulps_plot.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/tools/ulps_plot.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": 36.6284722222, "max_line_length": 166, "alphanum_fraction": 0.5516162669, "num_tokens": 5613, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.6859494485880928, "lm_q1q2_score": 0.3456541598145602}}
{"text": "/////////////////////////////////////////////////////////////\n// Copyright (C) 2003-2006 Bryan Clark and Kenneth Esler   //\n//                                                         //\n// This program is free software; you can redistribute it  //\n// and/or modify it under the terms of the GNU General     //\n// Public License as published by the Free Software        //\n// Foundation; either version 2 of the License, or         //\n// (at your option) any later version.  This program is    //\n// distributed in the hope that it will be useful, but     //\n// WITHOUT ANY WARRANTY; without even the implied warranty //\n// of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. //  \n// See the GNU General Public License for more details.    //\n// For more information, please see the PIMC++ Home Page:  //\n//           http://pathintegrals.info                     //\n/////////////////////////////////////////////////////////////\n\n#include \"MatrixOps.h\"\n#include <blitz/mstruct.h>\n#include \"../config.h\"\n\n//#ifdef NOUNDERSCORE \n//#define FORT(name) name\n//#else\n#define FORT(name) name ## _\n//#endif \n\n#define F77_DGELS  F77_FUNC(dgels,DGELS)\n#define F77_ZGESVD F77_FUNC(zgesvd,ZGESVD)\n#define F77_DGESVD F77_FUNC(dgesvd,DGESVD)\n#define F77_DGETRF F77_FUNC(dgetrf,DGETRF)\n#define F77_ZGETRF F77_FUNC(zgetrf,ZGETRF)\n#define F77_DGETRI F77_FUNC(dgetri,DGETRI)\n#define F77_ZGETRI F77_FUNC(zgetri,ZGETRI)\n#define F77_DGEMM  F77_FUNC(dgemm,DGEMM)\n#define F77_ZGEMM  F77_FUNC(zgemm,ZGEMM)\n#define F77_DSYEVR F77_FUNC(dsyevr,DSYEVR)\n#define F77_ZHEEVR F77_FUNC(zheevr,ZHEEVR)\n#define F77_DGEMV  F77_FUNC(dgemv,DGEMV)\n#define F77_DPOTRF  F77_FUNC(dpotrf,DPOTRF)\n\n\nextern \"C\" void \nF77_DGELS (char *transa, int *m, int *n, int *nrhs, \n\t   double *A, int *LDA, double *B,int *LDB,\n\t   double *work, int *LDWORK,int *INFO);\n\nextern \"C\" void \nF77_DGESVD (char *JOBU, char* JOBVT, int *M, int *N,\n\t    double *A, int *LDA, double *S, double *U,\n\t    int *LDU, double *VT, int *LDVT, double *work,\n\t    int *LWORK, int *INFO);\n\nextern \"C\" void \nF77_ZGESVD (char *JOBU, char* JOBVT, int *M, int *N,\n\t    complex<double> *A, int *LDA, double *S, complex<double> *U,\n\t    int *LDU, complex<double> *VT, int *LDVT, complex<double> *work,\n\t    int *LWORK, double *work2, int *INFO);\n\n\nextern \"C\" void \nF77_DGETRF(int *m, int *n, double A[], int *lda, int ipiv[], int *info);\n\nextern \"C\" void \nF77_DPOTRF(char *UPLO, int *n, double A[], int *lda, int *info);\n\n\nextern \"C\" void \nF77_ZGETRF(int *m, int *n, complex<double> A[], \n\t   int *lda, int ipiv[], int *info);\n\nextern \"C\" void \nF77_DGETRI (int *N, double A[], int *lda, int ipiv[], double work[], \n\t    int *lwork, int *info);\n\nextern \"C\" void \nF77_ZGETRI (int *N, complex<double> A[], int *lda, int ipiv[], \n\t    complex<double> work[], int *lwork, int *info);\n\nextern \"C\" void \nF77_DGEMM (char *transA, char *transB, int *m, int *n, int *k,\n\t   double *alpha, const double *A, int *lda, const double *B, int *ldb,\n\t   double *beta,  double *C, int *ldc);\n\nextern \"C\" void \nF77_ZGEMM (char *transA, char *transB, int *m, int *n, int *k,\n\t   complex<double> *alpha, const complex<double> *A, int *lda, const complex<double> *B, \n\t   int *ldb, complex<double> *beta,  complex<double> *C, int *ldc);\n\nextern \"C\" void \nF77_DSYEVR (char *JobType, char *Range, char *UpperLower, \n\t    int *N, double *Amat, int *LDA,\n\t    double *VL, double *VU,\n\t    int *IL, int *IU, \n\t    double *AbsTolerance, int *M,\n\t    double *EigVals, \n\t    double *EigVecs, int *LDEigVecs, int *ISuppZ,\n\t    double *Work, int *Lwork, \n\t    int *IWorkSpace, int *LIwork,\n\t    int *Info);\n\nextern \"C\" void \nF77_ZHEEVR (char *JobType, char *Range, char *UpperLower, \n\t    int *N, complex<double> *Amat, int *LDA,\n\t    double *VL, double *VU,\n\t    int *IL, int *IU, \n\t    double *AbsTolerance, int *M,\n\t    double *EigVals, \n\t    complex<double> *EigVecs, int *LDEigVecs, \n\t    int *ISuppZ,\n\t    complex<double> *Work, int *Lwork, \n\t    double *Rwork, int *LRwork,\n\t    int *IWorkSpace, int *LIwork,\n\t    int *Info);\n\n\nconst Array<double,2> operator*(const Array<double,2> &A,\n\t\t\t\tconst Array<double,2> &B)\n{\n  int m = A.rows();\n  int n = B.cols();\n  int k = A.cols();\n  assert (B.rows() == k);\n  // We use \"transpose\" operation because we have C ordering, which fortran\n  // thinks is transposed.\n  char transA = 'T';\n  char transB = 'T';\n  double alpha = 1.0;\n  double beta = 0.0;\n  GeneralArrayStorage<2> colMajor;\n  colMajor.ordering() = firstDim, secondDim;\n  Array<double,2> C(m,n,colMajor);\n  F77_DGEMM (&transA, &transB, &m, &n, &k, &alpha, A.data(), &k, \n\t     B.data(), &n, &beta, C.data(), &m);\n  return C;\n}\n\nconst Array<complex<double>,2> operator*(const Array<complex<double>,2> &A,\n\t\t\t\t\t const Array<complex<double>,2> &B)\n{\n  int m = A.rows();\n  int n = B.cols();\n  int k = A.cols();\n  assert (B.rows() == k);\n  // We use \"transpose\" operation because we have C ordering, which fortran\n  // thinks is transposed.\n  char transA = 'T';\n  char transB = 'T';\n  complex<double> alpha(1.0, 0.0);\n  complex<double> beta(0.0, 0.0);\n  GeneralArrayStorage<2> colMajor;\n  colMajor.ordering() = firstDim, secondDim;\n  Array<complex<double>,2> C(m,n,colMajor);\n  F77_ZGEMM (&transA, &transB, &m, &n, &k, &alpha, A.data(), &k, \n\t     B.data(), &n, &beta, C.data(), &m);\n  return C;\n}\n\n\nvoid MatMult (const Array<double,2> &A, const Array<double,2> &B,\n\t      Array<double,2> &C)\n{\n  int m = A.rows();\n  int n = B.cols();\n  int k = A.cols();\n  assert (B.rows() == k);\n  // We use \"transpose\" operation because we have C ordering, which fortran\n  // thinks is transposed.\n  char transA = 'T';\n  char transB = 'T';\n  double alpha = 1.0;\n  double beta = 0.0;\n  GeneralArrayStorage<2> colMajor;\n  colMajor.ordering() = firstDim, secondDim;\n  F77_DGEMM (&transA, &transB, &m, &n, &k, &alpha, A.data(), &k, \n\t     B.data(), &n, &beta, C.data(), &m);\n}\n\ndouble \nInnerProduct(const Array<double,1> &A,\n\t     const Array<double,1> &B)\n{\n  assert(A.size()==B.size());\n  double total=0.0;\n  for (int counter=0;counter<A.size();counter++)\n    total+=A(counter)*B(counter);\n  return total;\n\n}\n\n\nvoid\nOuterProduct(const Array<double,1> &A,\n\t     const Array<double,1> &B,\n\t     Array<double,2> &AB)\n{\n  double total=0.0;\n  AB.resize(A.size(),B.size());\n  for (int i=0;i<A.size();i++)\n    for (int j=0;j<B.size();j++)\n      AB(i,j)=A(i)*B(j);\n}\n\n//Note that A gets corrupted in this process and b gets returned\n//as the answer\nvoid\nLinearLeastSquares(Array<double,2> &A, Array<double,1> &x,\n\t\t   Array<double,1> &b)\n{\n  char trans;\n  trans='T';\n  ///These n and m are \"transposed\" because of Fortran ordering\n  int n=A.rows();\n  int m=A.cols();\n  ///\n\n  int ldb=b.size();\n  //  cerr<<\"The value of ldb is \"<<ldb<<endl;\n  Array<double,1> work(1);\n  int ldwork=-1;\n  int info=0;\n  int nrhs=1;\n  F77_DGELS(&trans,&m,&n,&nrhs,A.data(),&m,b.data(),&ldb,work.data(),\n\t    &ldwork,&info);\n  work.resize((int)work(0));\n  ldwork=work.size();\n  F77_DGELS(&trans,&m,&n,&nrhs,A.data(),&m,b.data(),&ldb,work.data(),\n\t    &ldwork,&info);\n\n}\nvoid MatMult (const Array<complex<double>,2> &A, const Array<complex<double>,2> &B,\n\t      Array<complex<double>,2> &C)\n{\n  int m = A.rows();\n  int n = B.cols();\n  int k = A.cols();\n  assert (B.rows() == k);\n  // We use \"transpose\" operation because we have C ordering, which fortran\n  // thinks is transposed.\n  char transA = 'T';\n  char transB = 'T';\n  complex<double> alpha = 1.0;\n  complex<double> beta = 0.0;\n  GeneralArrayStorage<2> colMajor;\n  colMajor.ordering() = firstDim, secondDim;\n  F77_ZGEMM (&transA, &transB, &m, &n, &k, &alpha, A.data(), &k, \n\t     B.data(), &n, &beta, C.data(), &m);\n  Transpose(C);\n}\n\n\ndouble Determinant (const Array<double,2> &A)\n{\n  int m = A.rows();\n  int n = A.cols();\n  assert (m == n);  // Cannot take a determinant of a non-square\n\t\t    // matrix\n  if (A.rows() == 1)\n    return (A(0,0));\n  if (A.rows() == 2) \n    return (A(0,0)*A(1,1)-A(0,1)*A(1,0));\n  else {\n    Array<double,2> LU(m,m);\n    Array<int,1> ipiv(m);\n    int info;\n    LU = A;\n    // Do LU factorization\n    F77_DGETRF (&m, &n, LU.data(), &m, ipiv.data(), &info);\n    double det = 1.0;\n    int numPerm = 0;\n    for (int i=0; i<m; i++) {\n      det *= LU(i,i);\n      numPerm += (ipiv(i) != (i+1));\n    }\n    if (numPerm & 1)\n      det *= -1.0;\n    \n    return det;\n  }\n}\n\ncomplex<double> \nDeterminant (const Array<complex<double>,2> &A)\n{\n  int m = A.rows();\n  int n = A.cols();\n  assert (m == n);  // Cannot take a determinant of a non-square\n\t\t    // matrix\n  if (A.rows() == 1)\n    return (A(0,0));\n  if (A.rows() == 2) \n    return (A(0,0)*A(1,1)-A(0,1)*A(1,0));\n  else {\n    Array<complex<double>,2> LU(m,m);\n    Array<int,1> ipiv(m);\n    int info;\n    LU = A;\n    // Do LU factorization\n    F77_ZGETRF (&m, &n, LU.data(), &m, ipiv.data(), &info);\n    complex<double> det = 1.0;\n    int numPerm = 0;\n    for (int i=0; i<m; i++) {\n      det *= LU(i,i);\n      numPerm += (ipiv(i) != (i+1));\n    }\n    if (numPerm & 1)\n      det *= -1.0;\n    \n    return det;\n  }\n}\n\n// Replaces A with its inverse by gauss-jordan elimination with full pivoting\n// Adapted from Numerical Recipes in C\ndouble GJInverse (Array<double,2> &A)\n{\n  \n  const int maxSize = 2000;\n  assert (A.cols() == A.rows());\n  assert (A.cols() <= maxSize);\n  int n = A.rows();\n\n  if (n == 2) { // Special case for 2x2\n    double a=A(0,0); double b=A(0,1);\n    double c=A(1,0); double d=A(1,1);\n    double detInv = 1.0/(a*d-b*c);\n    A(0,0) = d*detInv;\n    A(0,1) = -b*detInv;\n    A(1,0) = -c*detInv;\n    A(1,1) = a*detInv;\n    return 1.0/detInv;\n  }\n  double det = 1.0;\n\n\n  int colIndex[maxSize], rowIndex[maxSize], ipiv[maxSize];\n  double big, dum, pivInv, temp;\n  int icol, irow;\n  \n  for (int j=0; j<n; j++)\n    ipiv[j] = -1;\n\n  for (int i=0; i<n; i++) {\n    big = 0.0;\n    for (int j=0; j<n; j++) \n      if (ipiv[j] != 0)\n\tfor (int k=0; k<n; k++) {\n\t  if (ipiv[k] == -1) {\n\t    if (fabs(A(j,k)) >= big) {\n\t      big = fabs(A(j,k));\n\t      irow = j; \n\t      icol = k;\n\t    }\n\t  }\n\t  else if (ipiv[k] > 0) {\n\t    cerr << \"GJInverse: Singular matrix!\\n\";\n\t    cerr << \"A = \" << A << endl;\n\t    abort();\n\t  }\n\t}\n    ++(ipiv[icol]); \n    \n    if (irow != icol) \n      for (int l=0; l<n; l++) \n\tswap (A(irow,l), A(icol,l));\n    \n    rowIndex[i] = irow;\n    colIndex[i] = icol;\n    if (A(icol,icol) == 0.0) { \n      cerr << \"GJInverse: Singular matrix!\\n\";\n      cerr << \"A = \" << A << endl;\n      abort();\n    }\n    det *= A(icol,icol);\n    pivInv = 1.0/A(icol,icol);\n    A(icol,icol) = 1.0;\n    for (int l=0; l<n; l++)\n      A(icol,l) *= pivInv;\n    for (int ll=0; ll<n; ll++)\n      if (ll != icol) {\n\tdouble dum = A(ll,icol);\n\tA(ll,icol) = 0.0;\n\tfor (int l=0; l<n; l++)\n\t  A(ll,l) -= A(icol,l)*dum;\n      }\n  }\n  // Now unscramble the permutations\n  for (int l=n-1; l>=0; l--) {\n    if (rowIndex[l] != colIndex[l]) {\n      for (int k=0; k<n ; k++)\n\tswap (A(k,rowIndex[l]),A(k, colIndex[l]));\n      det *= -1.0;\n    }\n  }\n  return det; \n}\n\n\ndouble GJInversePartial (Array<double,2> &A)\n{\n  const int maxSize = 2000;\n  assert (A.cols() == A.rows());\n  assert (A.cols() <= maxSize);\n  int n = A.rows();\n\n  double det = 1.0;\n\n\n  int colIndex[maxSize], rowIndex[maxSize], ipiv[maxSize];\n  double big, dum, pivInv, temp;\n  int icol, irow;\n  \n  for (int i=0; i<n; i++) {\n    big = 0.0;\n    int ipiv = 0;\n    for (int j=i; j<n; j++) \n      if (fabs(A(j,i)) < big) {\n\tbig = fabs(A(j,i));\n\tipiv = j;\n      }\n    // HACK \n    // for (int j=0; j<n; j++)\n    //   swap (A(i,j), A(ipiv,j));\n\n    //ipiv = i;\n\n    det *= A(ipiv,i);\n    double pivInv = 1.0/A(ipiv,i);\n\n    A(ipiv,i) = 1.0;\n    for (int j=0; j<n; j++) \n      A(ipiv,j) *= pivInv;\n    for (int j=0; j<n; j++)\n      if (j != ipiv) {\n\tdouble tmp = A(j,i);\n\tA(j,i) = 0.0;\n\tfor (int k=0; k<n; k++)\n\t  A(j,k) -= A(ipiv,k)*tmp;\n      }\n  }\n  return det;\n}\n\n\n\n\ninline void SwapRow (Array<double,2> A, int row1, int row2)\n{\n  int m = A.cols();\n  for (int col=0; col<m; col++) {\n    double temp = A(row1,col);\n    A(row1,col) = A(row2,col);\n    A(row2,col) = temp;\n  }\n}\n\n\n// The cofactors of A are given by \n// cof(A) = det(A) transpose(A^{-1})\nvoid Cofactors (const Array<double,2> &A, \n\t\tArray<double,2> &cof,\n\t\tArray<double,2> &scratch)\n{\n  const int maxSize = 2000;\n  int m = A.rows();\n  int n = A.cols();\n  assert (m == n);  // Cannot take cofactors of a non-square matrix\n  assert (A.cols() < maxSize);\n  int  ipiv[maxSize];\n  int info;\n  // Copy and transpose for FORTRAN ordering\n  for (int i=0; i<m; i++)\n    for (int j=0; j<m; j++)\n      scratch(i,j) = A(j,i);\n  // Do LU decomposition\n  F77_DGETRF (&m, &n, scratch.data(), &m, ipiv, &info);\n  // Now scratch contains LU matrix in fortran ordering with pivots in ipiv\n  // Put identity matrix in cof\n  cof = 0.0;\n  for (int i=0; i<m; i++)\n    cof(i,i) = 1.0;\n  int numPerm = 0;\n  // Now apply permutation matrix to cof\n  for (int row=0; row<m; row++) {\n    int ip = ipiv[row]-1;\n    if (ip != row) { \n      SwapRow(cof, row, ip);\n      numPerm++;\n    }\n  }\n}\n\n\nvoid SVdecomp (Array<double,2> &A,\n\t       Array<double,2> &U, Array<double,1> &S,\n\t       Array<double,2> &V)\n{\n  int M = A.rows();\n  int N = A.cols();\n  Array<double,2> Atrans(M,N);\n  // U will be Utrans after lapack call\n  U.resize(min(M,N),M);\n  V.resize(N,min(M,N));\n  \n  S.resize(min(N,M));\n  Atrans = A;\n\n  // Transpose U for FORTRAN ordering\n  Transpose(Atrans);\n  char JOBU  = 'S'; // return min (M,N) columns of U\n  char JOBVT = 'S'; // return min (M,N) columns of V\n  int LDA = M;\n  int LDU = M;\n  int LDVT = min(M,N);\n  int LWORK = 10 * max(3*min(M,N)+max(M,N),5*min(M,N));\n  Array<double,1> WORK(LWORK);\n  int INFO;\n\n  F77_DGESVD (&JOBU, &JOBVT, &M, &N, Atrans.data(), &LDA,\n\t      S.data(), U.data(), &LDU, V.data(), &LDVT,\n\t      WORK.data(), &LWORK, &INFO);\n  assert (INFO == 0);\n  // Transpose U to get back to C ordering\n  // V was really Vtrans so we don't need to transpose\n  Transpose(U);\n}\n\n\nvoid SVdecomp (Array<complex<double>,2> &A, Array<complex<double>,2> &U, \n\t       Array<double,1> &S, Array<complex<double>,2> &V)\n{\n  int M = A.rows();\n  int N = A.cols();\n  Array<complex<double>,2> Atrans(M,N);\n  // U will be Utrans after lapack call\n  U.resize(min(M,N),M);\n  V.resize(N,min(M,N));\n  \n  S.resize(min(N,M));\n  Atrans = A;\n\n  // Transpose U for FORTRAN ordering\n  Transpose(Atrans);\n  char JOBU  = 'S'; // return min (M,N) columns of U\n  char JOBVT = 'S'; // return min (M,N) columns of V\n  int LDA = M;\n  int LDU = M;\n  int LDVT = min(M,N);\n  int LWORK = 10 * max(3*min(M,N)+max(M,N),5*min(M,N));\n  Array<complex<double>,1> WORK(LWORK);\n  Array<double,1> WORK2(5*min(M,N));\n  int INFO;\n\n  F77_ZGESVD (&JOBU, &JOBVT, &M, &N, Atrans.data(), &LDA,\n\t      S.data(), U.data(), &LDU, V.data(), &LDVT,\n\t      WORK.data(), &LWORK, WORK2.data(), &INFO);\n  assert (INFO == 0);\n  // Transpose U to get back to C ordering\n  // V was really Vtrans so we don't need to transpose\n  Transpose(U);\n}\n\n\nvoid PolarOrthogonalize (Array<complex<double>,2> &A)\n{\n  int M = A.rows();\n  int N = A.cols();\n  if (M != N) {\n    cerr << \"Error:  nonsquare matrix in PolarOrthogonalize. Aborting.\\n\";\n    abort();\n  }\n  Array<complex<double>,2> U, V;\n  Array<double,1> S;\n\n  SVdecomp (A, U, S, V);\n  Transpose(V);\n  for (int i=0; i<V.rows(); i++)\n    for (int j=0; j<V.cols(); j++)\n      V(i,j) = conj(V(i,j));\n  A = U * V;\n}\n\t       \n\n      // Adapted from Numerical Recipes in C\nvoid LUdecomp (Array<double,2> &A, Array<int,1> &perm, \n\t       double &sign)\n{\n  int i, imax, j, k;\n  int n = A.rows();\n  double big, dum, sum, temp;\n  Array<double,1> vv(n);\n  sign = 1.0;\n\n  perm.resize(n);\n\n  for (i=0; i<n; i++) {\n    big = 0.0;\n    for (int j=0; j<n; j++)\n      if (fabs(A(i,j)) > big) big = fabs(A(i,j));\n    if (big == 0.0) {\n      cerr << \"Singularity in LUdecomp.\\n\";\n      abort();\n    }\n    vv(i) = 1.0/big;\n  }\n  for (j=0; j<n; j++) {\n    for (i=0; i<j; i++) {\n      sum=A(i,j);\n      for(k=0; k<i; k++) \n\tsum -= A(i,k)*A(k,j);\n      A(i,j) = sum;\n    }\n    big=0.0;\n    for (i=j; i<n; i++) {\n      sum = A(i,j);\n      for (k=0; k<j; k++)\n\tsum-=A(i,k)*A(k,j);\n      A(i,j) = sum;\n      if ((dum=vv(i)*fabs(sum)) >= big) {\n\tbig = dum;\n\timax = i;\n      }\n    }\n    if (j != imax) {\n      for (k=0; k<n; k++) {\n\tdum=A(imax,k);\n\tA(imax,k) = A(j,k);\n\tA(j,k) = dum;\n      }\n      sign = -sign;\n      vv(imax) = vv(j);\n    }\n    perm(j)=imax;\n    if (A(j,j) == 0.0)\n      A(j,j) = 1.0e-200;\n    if (j != (n-1)) {\n      dum=1.0/A(j,j);\n      for (i=j+1; i<n; i++)\n\tA(i,j) *= dum;\n    }\n  }  \n}\n\n\nvoid LUsolve (Array<double,2> &LU, Array<int,1> &perm,\n\t      Array<double,1> &b)\n{\n  int i, ii=-1,ip,j;\n  double sum;\n  int n = LU.rows();\n  \n  for (i=0; i<n; i++) {\n    ip = perm(i);\n    sum = b(ip);\n    b(ip) = b(i);\n    if (ii>=0)\n      for (j=ii; j<i; j++)\n\tsum -= LU(i,j)*b(j);\n    else if (sum) \n      ii = i;\n    b(i) = sum;\n  }\n  for (i=n-1; i>=0; i--) {\n    sum = b(i);\n    for (j=i+1; j<n; j++)\n      sum -= LU(i,j)*b(j);\n    b(i) = sum/LU(i,i);\n  }\n}\n\n\nArray<double,2> Inverse (Array<double,2> &A)\n{\n  Array<double,2> LU(A.rows(), A.cols()), Ainv(A.rows(), A.cols());\n  Array<double,1> col(A.rows());\n  Array<int,1> perm;\n  double sign;\n\n  LU = A;\n  LUdecomp (LU, perm, sign);\n  for (int j=0; j<A.rows(); j++) {\n    for (int i=0; i<A.rows(); i++)\n      col(i) = 0.0;\n    col(j) = 1.0;\n    LUsolve (LU, perm, col);\n    for (int i=0; i<A.rows(); i++)\n      Ainv(i,j) = col(i);\n  }\n  return (Ainv);\n}\n\n  \nvoid SymmEigenPairs (const Array<scalar,2> &A, int NumPairs,\n\t\t     Array<scalar,1> &Vals,\n\t\t     Array<scalar,2> &Vectors)\n{\n  char JobType = 'V';    // Find eigenvectors and eignevalues\n  char Range   = 'I';    // Find eigenpairs in a range of indices\n  char UpperLower = 'U'; // Use upper triagle of A\n\n  int N   = A.rows();\n  double *Amat = new double[N*N];\n  int LDA = N;\n  double VL = 0.0;\n  double VU = 0.0;\n  int IL = 1;\n  int IU = NumPairs;\n  double AbsTolerance = -1.0;\n  int NumComputed;\n  double *EigVals = new double[N];\n  double *EigVecs = new double[N*NumPairs];\n  int LDEigVecs = N;\n  int *ISuppZ = new int[2*NumPairs];\n  int Info;\n\n  // First do workspace query\n  int Lwork = -1;\n  int LIwork = -1;\n  double WorkSize;\n  int IWorkSize;\n  \n  \n   F77_DSYEVR (&JobType, &Range, &UpperLower, &N, Amat, &LDA, &VL, &VU,\n\t       &IL, &IU, &AbsTolerance, &NumComputed, EigVals, EigVecs,\n\t       &LDEigVecs, ISuppZ, &WorkSize, &Lwork, &IWorkSize, &LIwork, \n\t       &Info);\n\n   // Now allocate WorkSpace;\n   Lwork = (int) floor(WorkSize+0.5);\n   LIwork = IWorkSize;\n   double *WorkSpace = new double[Lwork];\n   int *IWorkSpace = new int[LIwork];\n   \n   // Copy A int Amat\n   for (int row=0; row<N; row++)\n     for (int col=0; col<N; col++)\n       *(Amat+(col*N)+row) = A(row,col);\n  \n   F77_DSYEVR (&JobType, &Range, &UpperLower, &N, Amat, &LDA, &VL, &VU,\n\t       &IL, &IU, &AbsTolerance, &NumComputed, EigVals, EigVecs,\n\t       &LDEigVecs, ISuppZ, WorkSpace, &Lwork, IWorkSpace, &LIwork, \n\t       &Info);\n\n   if (Info !=0) \n     cerr << \"Lapack error in DSYEVR: \" << Info << endl;\n\n   // Now copy over output of Vectors and Vals\n   Vals.resize(NumPairs);\n   Vectors.resize(NumPairs,N);\n   \n   for (int i=0; i<NumPairs; i++)\n     {\n       Vals(i) = *(EigVals+i);\n       for (int j=0; j<N; j++)\n\t Vectors(i,j) = *(EigVecs+(i*N)+j);\n     }\n\n   // Now free allocate memory\n   delete[] Amat;\n   delete[] EigVals;\n   delete[] EigVecs; \n   delete[] WorkSpace; \n   delete[] IWorkSpace; \n   delete[] ISuppZ;\n}\n\n\n\n\nvoid SymmEigenPairs (const Array<complex<double>,2> &A, int NumPairs,\n\t\t     Array<scalar,1> &Vals,\n\t\t     Array<complex<double>,2> &Vectors)\n{\n  char JobType = 'V';    // Find eigenvectors and eignevalues\n  char Range   = 'I';    // Find eigenpairs in a range of indices\n  char UpperLower = 'U'; // Use upper triagle of A\n\n  int N   = A.rows();\n  complex<double> *Amat = new complex<double>[N*N];\n  int LDA = N;\n  double VL = 0.0;\n  double VU = 0.0;\n  int IL = 1;\n  int IU = NumPairs;\n  double AbsTolerance = 0.0;\n  int NumComputed;\n  double *EigVals = new double[N];\n  complex<double> *EigVecs = new complex<double>[N*NumPairs];\n  int LDEigVecs = N;\n  int *ISuppZ = new int[2*NumPairs];\n  int Info;\n\n  // First do workspace query\n  int Lwork = -1;\n  int LIwork = -1;\n  int LRwork = -1;\n  complex<double> WorkSize;\n  double RWorkSize;\n  int IWorkSize;\n  \n  \n   F77_ZHEEVR(&JobType, &Range, &UpperLower, &N, Amat, &LDA, &VL, &VU,\n\t      &IL, &IU, &AbsTolerance, &NumComputed, EigVals, EigVecs,\n\t      &LDEigVecs, ISuppZ, &WorkSize, &Lwork, &RWorkSize, &LRwork, \n\t      &IWorkSize, &LIwork, &Info);\n//    fprintf (stderr, \"WorkSize  = %1.8f\\n\", WorkSize.real());\n//    fprintf (stderr, \"RWorkSize = %1.8f\\n\", RWorkSize);\n//    fprintf (stderr, \"IWorkSize = %d\\n\", IWorkSize);\n\n   // Now allocate WorkSpace;\n   Lwork = (int) floor(WorkSize.real()+0.5);\n   LIwork = IWorkSize;\n   LRwork = (int) floor (RWorkSize+0.5);\n   complex<double> *WorkSpace = new complex<double>[Lwork];\n   double * RWorkSpace = new double[LRwork];\n   int *IWorkSpace = new int[LIwork];\n   \n   // Copy A int Amat\n   for (int row=0; row<N; row++)\n     for (int col=0; col<N; col++)\n       *(Amat+(col*N)+row) = A(row,col);\n   \n   F77_ZHEEVR(&JobType, &Range, &UpperLower, &N, Amat, &LDA, &VL, &VU,\n\t      &IL, &IU, &AbsTolerance, &NumComputed, EigVals, EigVecs,\n\t      &LDEigVecs, ISuppZ, WorkSpace, &Lwork, RWorkSpace, &LRwork, \n\t      IWorkSpace, &LIwork, &Info);\n\n   if (Info !=0) {\n     fprintf (stderr, \"Lapack error in zheevr.  Exitting.\\n\");\n     exit(-1);\n   }\n\n   // Now copy over output of Vectors and Vals\n   Vals.resize(NumPairs);\n   Vectors.resize(NumPairs,N);\n   \n   for (int i=0; i<NumPairs; i++) {\n     Vals(i) = *(EigVals+i);\n     for (int j=0; j<N; j++)\n       Vectors(i,j) = *(EigVecs+(i*N)+j);\n   }\n\n   // Now free allocate memory\n   delete[] Amat;\n   delete[] EigVals;\n   delete[] EigVecs;\n   delete[] WorkSpace;\n   delete[] IWorkSpace;\n   delete[] ISuppZ;\n   \n\n}\n\n\n/// This function returns the determinant of A and replaces A with its\n/// cofactors.\ndouble \nDetCofactors (Array<double,2> &A, Array<double,1> &work)\n{\n  const int maxN = 2000;\n  int ipiv[maxN];\n  int N = A.rows();\n  int M = A.cols();\n  assert (N == M);\n  assert (N <= maxN);\n  // First, transpose A for fortran ordering\n//   for (int i=0; i<N; i++)\n//     for (int j=0; j<i; j++) {\n//       double tmp = A(i,j);\n//       A(i,j) = A(j,i);\n//       A(j,i) = tmp;\n//     }\n  Transpose(A);\n  \n  int info;\n  // Do LU factorization\n  F77_DGETRF (&N, &M, A.data(), &N, ipiv, &info);\n  double det = 1.0;\n  int numPerm = 0;\n  for (int i=0; i<N; i++) {\n    det *= A(i,i);\n    numPerm += (ipiv[i] != (i+1));\n  }\n  if (numPerm & 1)\n    det *= -1.0;\n  \n  int lwork = work.size();\n  // Now, do inverse\n  F77_DGETRI (&N, A.data(), &N, ipiv, work.data(), &lwork, &info);\n\n  // Now, we have the transpose of Ainv.  Now, just multiply by det:\n  A = det * A;\n  // And we're done!\n  return det;\n}\n\nint \nDetCofactorsWorksize(int N)\n{\n  double work;\n  double dummy;\n  int info;\n  int ipiv;\n  int lwork = -1;\n  \n  F77_DGETRI(&N, &dummy, &N, &ipiv, &work, &lwork, &info);\n\n  return ((int)ceil(work));\n}\n\n\n\n/// This function returns the determinant of A and replaces A with its\n/// cofactors.\ncomplex<double>\nComplexDetCofactors (Array<complex<double>,2> &A, \n\t\t     Array<complex<double>,1> &work)\n{\n  const int maxN = 2000;\n  int ipiv[maxN];\n  int N = A.rows();\n  int M = A.cols();\n  assert (N == M);\n  assert (N <= maxN);\n  // First, transpose A for fortran ordering\n//   for (int i=0; i<N; i++)\n//     for (int j=0; j<i; j++) {\n//       double tmp = A(i,j);\n//       A(i,j) = A(j,i);\n//       A(j,i) = tmp;\n//     }\n  Transpose(A);\n  \n  int info;\n  // Do LU factorization\n  F77_ZGETRF (&N, &M, A.data(), &N, ipiv, &info);\n  complex<double> det = 1.0;\n  int numPerm = 0;\n  for (int i=0; i<N; i++) {\n    det *= A(i,i);\n    numPerm += (ipiv[i] != (i+1));\n  }\n  if (numPerm & 1)\n    det = -det;\n  \n  int lwork = work.size();\n  // Now, do inverse\n  F77_ZGETRI (&N, A.data(), &N, ipiv, work.data(), &lwork, &info);\n\n  // Now, we have the transpose of Ainv.  Now, just multiply by det:\n  A = det * A;\n  // And we're done!\n  return det;\n}\n\nint \nComplexDetCofactorsWorksize(int N)\n{\n  complex<double> work;\n  complex<double> dummy;\n  int info;\n  int ipiv;\n  int lwork = -1;\n  \n  F77_ZGETRI(&N, &dummy, &N, &ipiv, &work, &lwork, &info);\n\n  return ((int)ceil(work.real()));\n}\n\nextern \"C\" void   F77_DGEMV (char *TRANS, const int *M, const int *N, \n\t\t\t     double *alpha, const void *A, \n\t\t\t     const int *LDA, const void *X, \n\t\t\t     const int *INCX, double *beta, \n\t\t\t     const void *Y, const int *INCY);\n\n\nvoid\nMatVecProd (Array<double,2> &A, Array<double,1> &x, Array<double,1> &Ax)\n{\n  assert (A.cols() == x.size());\n  assert (A.rows() == Ax.size());\n\n  double zero(0.0);\n  double one(1.0);\n  char trans = 'T';\n\n  int n = A.rows();\n  int m = A.cols();\n  int inc = 1;\n\n  F77_DGEMV(&trans, &m, &n, &one, A.data(), &m,\n\t    x.data(), &inc, &zero, Ax.data(), &inc);\n}\n\n\n\nvoid CholeskyBig (Array<double,2> &A)\n{\n  int n=A.extent(0);\n  int lda=A.extent(1);\n  int info;\n  char upper='L';\n  F77_DPOTRF(&upper,&n,A.data(),&lda,&info);\n  for (int i=0;i<A.extent(0);i++)\n    for (int j=0;j<i;j++)\n      A(i,j)=0.0;\n  \n}\n", "meta": {"hexsha": "ab6adef18764ed58210a8a96b83530e9dc135923", "size": 25118, "ext": "cc", "lang": "C++", "max_stars_repo_path": "test/performance-regression/full-apps/qmcpack/src/QMCTools/ppconvert/src/common/MatrixOps.cc", "max_stars_repo_name": "JKChenFZ/hclib", "max_stars_repo_head_hexsha": "50970656ac133477c0fbe80bb674fe88a19d7177", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 55.0, "max_stars_repo_stars_event_min_datetime": "2015-07-28T01:32:58.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-27T16:27:46.000Z", "max_issues_repo_path": "test/performance-regression/full-apps/qmcpack/src/QMCTools/ppconvert/src/common/MatrixOps.cc", "max_issues_repo_name": "JKChenFZ/hclib", "max_issues_repo_head_hexsha": "50970656ac133477c0fbe80bb674fe88a19d7177", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 66.0, "max_issues_repo_issues_event_min_datetime": "2015-06-15T20:38:19.000Z", "max_issues_repo_issues_event_max_datetime": "2020-08-26T00:11:43.000Z", "max_forks_repo_path": "test/performance-regression/full-apps/qmcpack/src/QMCTools/ppconvert/src/common/MatrixOps.cc", "max_forks_repo_name": "JKChenFZ/hclib", "max_forks_repo_head_hexsha": "50970656ac133477c0fbe80bb674fe88a19d7177", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 26.0, "max_forks_repo_forks_event_min_datetime": "2015-10-26T22:11:51.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-02T22:09:15.000Z", "avg_line_length": 24.9186507937, "max_line_length": 90, "alphanum_fraction": 0.5595986942, "num_tokens": 8975, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6859494421679929, "lm_q2_score": 0.5039061705290805, "lm_q1q2_score": 0.34565415657943227}}
{"text": "//==============================================================================\n//         Copyright 2003 - 2011 LASMEA UMR 6602 CNRS/Univ. Clermont II\n//         Copyright 2009 - 2011 LRI    UMR 8623 CNRS/Univ Paris Sud XI\n//\n//          Distributed under the Boost Software License, Version 1.0.\n//                 See accompanying file LICENSE.txt or copy at\n//                     http://www.boost.org/LICENSE_1_0.txt\n//==============================================================================\n#ifndef NT2_TRIGONOMETRIC_FUNCTIONS_SIMD_COMMON_ATAN2_HPP_INCLUDED\n#define NT2_TRIGONOMETRIC_FUNCTIONS_SIMD_COMMON_ATAN2_HPP_INCLUDED\n\n#include <nt2/trigonometric/functions/atan2.hpp>\n#include <nt2/trigonometric/functions/simd/common/impl/invtrig.hpp>\n#include <nt2/include/functions/simd/if_else.hpp>\n#include <nt2/include/functions/simd/is_gtz.hpp>\n#include <nt2/include/functions/simd/is_eqz.hpp>\n#include <nt2/include/functions/simd/divides.hpp>\n#include <nt2/include/functions/simd/minus.hpp>\n#include <nt2/include/functions/simd/negatenz.hpp>\n#include <nt2/include/functions/simd/is_ltz.hpp>\n#include <nt2/include/constants/pi.hpp>\n#include <boost/simd/sdk/meta/as_logical.hpp>\n#include <boost/simd/sdk/config.hpp>\n\n#ifndef BOOST_SIMD_NO_INFINITIES\n#include <nt2/include/functions/simd/logical_and.hpp>\n#include <nt2/include/functions/simd/is_inf.hpp>\n#include <nt2/include/functions/simd/copysign.hpp>\n#include <nt2/include/constants/one.hpp>\n#endif\n#ifndef BOOST_SIMD_NO_NANS\n#include <nt2/include/functions/simd/if_allbits_else.hpp>\n#include <nt2/include/functions/simd/logical_or.hpp>\n#include <nt2/include/functions/simd/is_nan.hpp>\n#endif\n\n\nnamespace nt2 { namespace ext\n{\n  BOOST_DISPATCH_IMPLEMENT  ( atan2_, boost::simd::tag::simd_\n                            , (A0)(X)\n                            , ((simd_<floating_<A0>,X>))\n                              ((simd_<floating_<A0>,X>))\n                            )\n  {\n    typedef A0 result_type;\n    inline result_type operator()(const typename A0::native_type a0_n,\n                                  const typename A0::native_type a1_n) const\n    {\n      A0 a0 = a0_n;\n      A0 a1 = a1_n;\n      typedef typename meta::as_logical<A0>::type lA0;\n#ifndef BOOST_SIMD_NO_INFINITIES\n      lA0 test =  nt2::logical_and(nt2::is_inf(a0),  nt2::is_inf(a1));\n      a0 =  nt2::if_else(test, nt2::copysign(One<A0>(), a0), a0);\n      a1 =  nt2::if_else(test, nt2::copysign(One<A0>(), a1), a1);\n#endif\n      A0 z = details::invtrig_base<result_type,radian_tag, tag::simd_type>::kernel_atan(a0/a1);\n      //A0 z = atan(abs(a0/a1));  // case a1 > 0,  a0 > 0\n      z = nt2::negatenz(nt2::if_else(nt2::is_gtz(a1), z, nt2::Pi<A0>()-z), a0);\n      z =  nt2::if_else( nt2::is_eqz(a0),\n                         nt2::if_else_zero( nt2::is_ltz(a1),  nt2::Pi<A0>()),\n                         z);\n#ifdef BOOST_SIMD_NO_NANS\n      return z;\n#else\n      return  nt2::if_nan_else( nt2::logical_or( nt2::is_nan(a0),  nt2::is_nan(a1)), z);\n#endif\n    }\n  };\n} }\n\n\n#endif\n", "meta": {"hexsha": "0f37b6ca301f7e3b29263c13d0cfcea78419f489", "size": 3008, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/core/trigonometric/include/nt2/trigonometric/functions/simd/common/atan2.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/trigonometric/include/nt2/trigonometric/functions/simd/common/atan2.hpp", "max_issues_repo_name": "psiha/nt2", "max_issues_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "modules/core/trigonometric/include/nt2/trigonometric/functions/simd/common/atan2.hpp", "max_forks_repo_name": "psiha/nt2", "max_forks_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2017-12-02T12:59:17.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-31T12:46:14.000Z", "avg_line_length": 40.1066666667, "max_line_length": 95, "alphanum_fraction": 0.6210106383, "num_tokens": 833, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.7690802264851919, "lm_q2_score": 0.44939263446475963, "lm_q1q2_score": 0.3456189890949344}}
{"text": "#include <iostream>\n#include <iomanip>\n#include <fstream>\n\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/vector.hpp>\n#include <boost/numeric/ublas/io.hpp>\n\n#include <vector>\n#include <cmath>\n#include <cstring>\n\n#include <unistd.h>\n\n#include \"NRGclasses.hpp\"\n#include \"NRGfunctions.hpp\"\n#include \"NRGOpMatRules.hpp\"\n#include \"NRG_main.hpp\"\n#include \"TwoChQS.hpp\"\n\n\n#ifndef pi\n#define pi 3.141592653589793238462643383279502884197169\n#endif\n\n#ifndef _CHIN_\n#define _CHIN_\n\n\ndouble chiN(int Nsites, double Lambda)\n{\n\n  double daux[3];\n  daux[0]=1.0-pow( Lambda,-((double)(Nsites)+1.0) );\n  daux[1]=sqrt( 1.0-pow(Lambda,-(2.0*(double)(Nsites)+1.0)) );\n  daux[2]=sqrt( 1.0-pow(Lambda,-(2.0*(double)(Nsites)+3.0)) );  \n\n  return(daux[0]/(daux[1]*daux[2]));\n\n}\n\n#endif\n\n\nint main (int argc, char* argv[]){\n\n\n// Parameters for command-line passing (GetOpt)\n  \n  CNRGCodeHandler ThisCode;\n  CNRGarray Aeig;\n\n#include\"ModelOptMain.cpp\"\n\n  ThisCode.SaveData=false;\n\n  // NRG objects\n  \n  CNRGbasisarray AeigCut;\n  CNRGbasisarray Abasis;\n  CNRGbasisarray SingleSite;\n\n  // STL vector\n\n  CNRGmatrix HN;\n  CNRGmatrix Qm1fNQ;\n\n  //CNRGmatrix MQQp1;\n\n  CNRGmatrix* MatArray;\n  int NumNRGarrays=4;\n  // Jul 09: Will this work???\n  vector<CNRGmatrix> STLMatArray;\n  CNRGmatrix auxNRGMat;\n  // MatArray 0 is f_ch1\n  // MatArray 1 is f_ch2\n  // MatArray 2 is Sz\n  // MatArray 3 is Sz2\n\n\n\n  // STL vectors\n  vector <double> Params;\n  vector <double> ParamsHN;\n  vector <double> ParamsBetabar;\n  vector<int> CommonQNs; \n  vector<int> totSpos;\n\n  // Thermodynamics\n\n  CNRGthermo Suscep;\n  CNRGthermo Entropy;\n\n  CNRGthermo *ThermoArray;\n  int NumThermoArrays=2;\n\n  double TM=0.0;\n  //double DN=0.0;\n  //double betabar=0.727;\n  ThisCode.Nsites=0;\n  ThisCode.betabar=0.727;\n  // Add more than one betabar in the code... Done!\n  //ThisCode.betabar=0.6; \n\n  // instream\n  ifstream InFile;\n  // outstream\n  ofstream OutFile;\n\n\n  // Allows for several channels\n  vector <double> chi_m1;\n\n  ////////////////////////////////////////////////////\n  ////////////////////////////////////////////////////\n  ////////////////////////////////////////////////////\n  ///                                              ///\n  ///                Main code                     ///\n  ///                                              ///\n  ////////////////////////////////////////////////////\n  ////////////////////////////////////////////////////\n  ////////////////////////////////////////////////////\n\n\n  // Read stuff (separate routine)\n\n// Allocate MatArray (hope this works!)\n// Yes, but, for some reason, needs to be BEFORE everything!\n\n\n   MatArray = new CNRGmatrix [NumNRGarrays];\n   ThermoArray = new CNRGthermo [NumThermoArrays];\n\n   for (int imat=0;imat<NumNRGarrays;imat++){STLMatArray.push_back(auxNRGMat);}\n\n   ThisCode.Nsites0=0;\n   ThisCode.NumChannels=1;\n   ThisCode.NumNRGmats=NumNRGarrays;\n   ThisCode.NumThermoMats=NumThermoArrays;\n   ThisCode.InitialSetUp(); \n   //InFile.open(\"input_nrg.dat\"); // Needs this here \n                                   // new MatArray after!! Why????\n\n   ThisCode.SetSingleSite(&SingleSite);\n\n   // Copy pointers for saving/reading.\n   ThisCode.pAbasis=&Abasis;\n   //ThisCode.MatArray=MatArray;\n   ThisCode.MatArray=&STLMatArray[0];\n   ThisCode.pAcut=&AeigCut;\n\n  // Set H0\n  // Set initial Aeig and matrices (such as Qm1fNQ[])/Operators\n  //  - Model dependent functions (hardest part)\n  //  - Set quantum numbers, etc,etc,\n  //  - HN. will \n\n\n  // Thermobasics\n\n   strcpy(ThermoArray[0].ArqName,\"SuscepImp_Main.dat\");\n   strcpy(ThermoArray[0].ChainArqName,\"SuscepChain2Ch.dat\");\n   ThermoArray[0].Calc=CalcSuscep;\n  \n   strcpy(ThermoArray[1].ArqName,\"EntropyImp_Main.dat\");\n   strcpy(ThermoArray[1].ChainArqName,\"EntropyChain2Ch.dat\");\n   ThermoArray[1].Calc=CalcEntropy;\n\n   for (int ithermo=0;ithermo<NumThermoArrays;ithermo++){\n     if (ThisCode.calcdens==3)\n       ThermoArray[ithermo].CalcChain=true;\n     else\n       ThermoArray[ithermo].CalcChain=false;\n   }\n   // HN basics\n   HN.NeedOld=false;\n   HN.UpperTriangular=true;\n   HN.CheckForMatEl=Diag_check;\n\n\n   // To do: send ALL THIS to codeHandler!!\n   /// For all codes\n   double Gamma=0.0282691;\n   double Lambda=2.5;\n   if (ThisCode.dInitParams.size()>1)\n     Gamma=ThisCode.dInitParams[1];\n   if (ThisCode.Lambda>0.0)\n     Lambda=ThisCode.Lambda;\n   //double HalfLambdaFactor=0.5*(1.0+(1.0/Lambda)); // also defined in CNRGcodehandler\n   double HalfLambdaFactor=ThisCode.HalfLambdaFactor; // fix this double counting later\n\n//    double chi_m1=sqrt(2.0*Gamma/pi)/(sqrt(Lambda)*HalfLambdaFactor);\n   // NumChannels was set in ThisCode.InitialSetUp(). Set\n   chi_m1.insert(chi_m1.begin(),ThisCode.NumChannels,0.0);\n   chi_m1[0]=sqrt(2.0*Gamma/pi)/(sqrt(Lambda)*HalfLambdaFactor);\n\n   // added: eN for chains away from phs (getting en for N=0)\n   double eN=ThisCode.Chains[0].GetEn(0);\n\n   cout << \" Fsq = \" << ThisCode.Chains[0].Fsq \n\t<< \" chi_m1 = \" << chi_m1[0] \n\t<< \" eN(0) = \" << eN << endl;\n\n   // Adding A_Lambda factor (except if using Campo-Oliveira)\n   if (ThisCode.Chains[0].DiscScheme!=1){\n     chi_m1[0]*=sqrt(0.5*log(Lambda)*(Lambda+1)/(Lambda-1));\n   }\n\n   cout  << \" sqrt(ALambda)*chi_m1 = \" << chi_m1[0]  << endl;\n\n\n   // Sep 08: 1ChQ chain calculations diverted to Anderson (ModelNo=0)\n   // Aug 09: Why?? Is this correct?\n\n   if ( (ThisCode.ModelNo==3)&&(ThisCode.SymNo==3) ){\n     ThisCode.ZeroParams();\n     ThisCode.ModelNo=0;\n   }\n\n   double DeltaSC=0.0;\n   // Set 2015: added SC leads\n   if ( (ThisCode.SymNo==7)||(ThisCode.SymNo==8) ){\n     if (ThisCode.ModelNo==0){\n       DeltaSC=ThisCode.dInitParams[3];\n       cout << \" DeltaSC = \" << DeltaSC << endl;\n       }\n   }\n   // end add DeltaSC\n\n   /***************/\n   // Model specific hamiltonians //\n   /***************/\t\n\n   // to do: models for which Nsites0=1 need eN as input here\n\n   ThisCode.ModelSwitch(CommonQNs,totSpos,&Aeig,&SingleSite,\n\t\t\t&HN,STLMatArray,ThermoArray,chi_m1);\n\n   CutStates(Aeig, AeigCut, ThisCode.Ncutoff);\n\n \n   // watch out for the \"Nsites0-2\"\n   ThisCode.DN=HalfLambdaFactor*pow(Lambda,(-(ThisCode.Nsites0-2)/2.0) );\n   // Aug 2010: Z-trick factor added into HalfLambdaFactor\n   TM=ThisCode.DN/ThisCode.betabar;\n   cout << \"DN = \" << ThisCode.DN << \"  TM = \" << TM << endl;\n\n   // \n   for (int ithermo=0;ithermo<NumThermoArrays;ithermo++){\n     ThisCode.ThermoSTLArray.push_back(ThermoArray[ithermo]);\n   }\n\n   if (ThisCode.Nsites0==1) // Calculates Thermo from N=0 on (not N=-1)\n     ThisCode.CalcThermo(ThermoArray,&Aeig);\n\n   ThisCode.CalcStuff(&Aeig,&AeigCut);\n\n\n   // Save Params?\n   if (ThisCode.SaveData){ThisCode.SaveGenPars();}\n\n   // Ok, with that we can go into the main loop\n\n   // Parameters for HN (always the same?)\n   ParamsHN.push_back(Lambda);\n   for (int ich=0;ich<ThisCode.NumChannels;ich++)\n     ParamsHN.push_back(chi_m1[ich]);\n   // This is not good. Depends on setting chi_m1 at ModelSwitch!!\n   // Also: if Nsites0 is NOT -1, we need something like this\n   //        ParamsHN[ich+1]=ThisCode.chain.GetChin(ThisCode.Nsites);\n   // What if the chains are not equivalent?\n\n   // added: chains away from phs\n   ParamsHN.push_back(eN);\n   // added: superconducting leads\n   ParamsHN.push_back(DeltaSC);\n\n\n   // Entering calculation of H_Nsites0\n   ThisCode.Nsites=ThisCode.Nsites0;\n\n   while (ThisCode.Nsites<ThisCode.Nsitesmax){\n     ThisCode.DN=HalfLambdaFactor*pow(Lambda,(-(ThisCode.Nsites-1)/2.0) );\n     // Aug 2010: Z-trick factor added into HalfLambdaFactor\n     TM=ThisCode.DN/ThisCode.betabar;\n     cout << \"DN = \" << ThisCode.DN << \" TM = \" << TM << endl;\n     // Debugging...\n     //bool disp=(ThisCode.Nsites==1?true:false);\n     //bool disp=true;\n     bool disp=false;\n\n     // Build Basis\n\n     //SingleSite.PrintQNumbers();\n     //Aeig.PrintQNumbers();\n\n\n     // If UpdateBefCut=1, StCameFrom is the \"old\" (Before Cutting) one! \n     // Matrices will be in sync with Aeig, not AeigCut \n\n     BuildBasis(CommonQNs, totSpos,&AeigCut,&Abasis, \n\t\t&SingleSite,ThisCode.UpdateBefCut);\n\n\n     // Diagonalize HN\n\n     cout << \"Diagonalizing H(N=\"<<ThisCode.Nsites<<\")... \" << endl;\n     cout << \" chi_N = \" << ParamsHN[1] << endl;\n\n     // Need to adapt ALL models to use STLMatArray... \n     // in the meantime, this will work.\n     if ( (ThisCode.ModelNo==4) ){\n       HN.DiagHN(ParamsHN,&Abasis,&SingleSite,MatArray,&Aeig);\n     }else{\n       HN.DiagHN(ParamsHN,&Abasis,&SingleSite,&STLMatArray[0],&Aeig,disp);\n     }\n\n     cout << \"... done diagonalizing HN. \" << endl;\n    \n\n     Aeig.SetKept(ThisCode.Ncutoff);\n     Aeig.PrintEn();\n\n     //       for (int ibl=0;ibl<Aeig.NumBlocks();ibl++)\n     // \tAeig.PrintBlock(ibl);\n\n     // Calculate Susceptibility/Entropy (does not need update)\n\n     ThisCode.CalcThermo(ThermoArray,&Aeig);\n\n\n     // NEW (updates after cutting)\n\n     if (ThisCode.UpdateBefCut==0){\n       // Update AFTER CUTTING (faster)\n       CutStates(Aeig, AeigCut, ThisCode.Ncutoff);\n     }else{\n       // Update BEFORE CUTTING\n       //Aeig.SetKept(ThisCode.Ncutoff);\n       CutStates(Aeig, AeigCut, 2*Aeig.Nstates());\n       // AeigCut is essentially a copy of Aeig\n     }\n     // end if UpdateBefCut\n\n\n     // Update matrices (in either case)\n\n     if (ThisCode.Nsites<ThisCode.Nsitesmax){\n       // Need to adapt ALL models to use STLMatArray... \n       // in the meantime, this will work.\n       if ( (ThisCode.ModelNo==4) ){\n\t UpdateMatrices(&SingleSite,&AeigCut, \n\t\t\t&Abasis,MatArray, ThisCode.NumNRGmats);\n\n       }else{\n\t //disp=(ThisCode.Nsites==1?true:false);\n\t // UpdateMatrices_uBLAS(&SingleSite,&AeigCut, \n\t // \t\t&Abasis,&STLMatArray[0],STLMatArray.size(),disp);\n\t // Testing...\n\t UpdateMatrices(&SingleSite,&AeigCut, \n\t \t\t&Abasis,&STLMatArray[0],STLMatArray.size(),disp);\n\t // Lightning FAST!!\n\t //disp=false;\n       }\n     }\n     // end update matrices\n\n     // Save stuff to files\n\n\n     if (ThisCode.SaveData){ThisCode.SaveArrays();}\n\n \n     // Calculate Other things that need updated matrices\n     //\n     // The idea is to eliminate this and put into CalcStuff\n     // (need to test with OneChQ!!\n     if (ThisCode.SymNo==3){\n       ParamsBetabar.clear();\n       ParamsBetabar.push_back(ThisCode.betabar);\n       double dSz=CalcOpAvg(ParamsBetabar,&AeigCut,&STLMatArray[2],false,0);\n       double dSz2=CalcOpAvg(ParamsBetabar,&AeigCut,&STLMatArray[3],false,0);\n       //double dSz=CalcOpAvg(ParamsBetabar,&AeigCut,MatArray,false,0);\n       //double dSz2=CalcOpAvg(ParamsBetabar,&AeigCut,MatArray,false,0);\n       \n       cout << \" T = \" << TM << \" Sz = \" << dSz << \" Sz2 = \" << dSz2 \n\t    << \"  T_M chi = \" << dSz2-dSz*dSz << endl;\n     }\n\n     ThisCode.CalcStuff(&Aeig,&AeigCut);\n\n\n     if (ThisCode.UpdateBefCut==1){\n       // Now we cut for real\n       CutStates(Aeig, AeigCut, ThisCode.Ncutoff);\n     }\n\n     cout << \" N = \" << ThisCode.Nsites << endl;\n\n     // Update ParamsHN\n     //ParamsHN[1]=chiN(ThisCode.Nsites,Lambda); // Old\n     for (int ich=0;ich<ThisCode.NumChannels;ich++)\n       //ParamsHN[ich+1]=chiN(ThisCode.Nsites,Lambda);\n       // Try this...\n       ParamsHN[ich+1]=ThisCode.Chains[0].GetChin(ThisCode.Nsites);\n\n     \n     // Update sites\n     ThisCode.Nsites++;\n\n     // Adding eN: is this before or after Nsites is updated? After!\n     if (ParamsHN.size()>ThisCode.NumChannels+2){\n       eN=ThisCode.Chains[0].GetEn(ThisCode.Nsites);\n       ParamsHN[ThisCode.NumChannels+1]=eN;\n       cout << \" eN_\" << ThisCode.Nsites << \" = \" << eN << endl;\n       // Adding DeltaSC RENORMALIZED\n       double ScaleFactorNm1=ThisCode.Chains[0].ScaleFactor(ThisCode.Nsites-1);\n       ParamsHN[ThisCode.NumChannels+2]=ScaleFactorNm1*DeltaSC;\n       cout << \" ScaleFactorN_\" << ThisCode.Nsites-1 << \" = \" << ScaleFactorNm1\n\t    << \" DeltaSC_scaled = \" << \" DeltaSC_scaled = \" << ScaleFactorNm1*DeltaSC\n\t    << endl;\n\n     }\n     // apparently this is ALWAYS true!\n\n     \n   }\n   // end Nsites loop\n\n   // De-allocate MatArray \n   delete[] ThermoArray;\n   delete[] MatArray;\n\n   ThisCode.WrapUp();\n\n}\n// end main\n\n\n//\n// Trash\n//\n//////////////////////////\n\n\n", "meta": {"hexsha": "a773c4f477dbbc7f486d0b6b06c8c09b17e01ccf", "size": 12032, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Main/NRG_main.cpp", "max_stars_repo_name": "lgds/NRG_USP", "max_stars_repo_head_hexsha": "ff66846e92498aa429cce6fc5793bec23ad03eb4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2015-09-21T20:58:45.000Z", "max_stars_repo_stars_event_max_datetime": "2019-03-20T01:21:41.000Z", "max_issues_repo_path": "src/Main/NRG_main.cpp", "max_issues_repo_name": "lgds/NRG_USP", "max_issues_repo_head_hexsha": "ff66846e92498aa429cce6fc5793bec23ad03eb4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Main/NRG_main.cpp", "max_forks_repo_name": "lgds/NRG_USP", "max_forks_repo_head_hexsha": "ff66846e92498aa429cce6fc5793bec23ad03eb4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.9775784753, "max_line_length": 87, "alphanum_fraction": 0.6197639628, "num_tokens": 3700, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.8175744673038222, "lm_q2_score": 0.42250463481418826, "lm_q1q2_score": 0.3454290017416059}}
{"text": "/*! \\file Peridigm_CorrespondenceMaterial.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_CorrespondenceMaterial.hpp\"\n#include \"Peridigm_Field.hpp\"\n#include \"elastic.h\"\n#include \"correspondence.h\"\n#include \"Peridigm_DegreesOfFreedomManager.hpp\"\n#include \"elastic_correspondence.h\"\n#include <Teuchos_Assert.hpp>\n#include <Epetra_SerialComm.h>\n#include <Sacado.hpp>\n#include <boost/math/special_functions/fpclassify.hpp>\nusing namespace std;\n\nPeridigmNS::CorrespondenceMaterial::CorrespondenceMaterial(const Teuchos::ParameterList& params)\n  : Material(params),\n    m_density(0.0), m_hourglassCoefficient(0.0),\n        m_OMEGA(PeridigmNS::InfluenceFunction::self().getInfluenceFunction()),\n    m_horizonFieldId(-1), m_volumeFieldId(-1),\n    m_modelCoordinatesFieldId(-1), m_coordinatesFieldId(-1), m_velocitiesFieldId(-1), \n    m_hourglassForceDensityFieldId(-1), m_forceDensityFieldId(-1), m_bondDamageFieldId(-1),\n    m_deformationGradientFieldId(-1),\n    m_shapeTensorInverseFieldId(-1),\n    m_leftStretchTensorFieldId(-1),\n    m_rotationTensorFieldId(-1), \n    m_unrotatedCauchyStressFieldId(-1),\n    m_cauchyStressFieldId(-1), \n    m_unrotatedRateOfDeformationFieldId(-1),\n    m_partialStressFieldId(-1),\n    m_hourglassStiffId(-1)\n    \n{\n     \n  //! \\todo Add meaningful asserts on material properties.\n  m_bulkModulus = calculateBulkModulus(params);\n  m_shearModulus = calculateShearModulus(params);\n  m_density = params.get<double>(\"Density\");\n  \n  m_stabilizationType = 3;\n\n  m_plane = false;\n\n  //************************************\n  // wie komme ich an den Namen??\n  //************************************\n  //if (params.isParameter(\"Linear Elastic Correspondence\")){\n    nonLin = false;\n  \n    bool m_planeStrain = false, m_planeStress = false;\n    if (params.isParameter(\"Plane Strain\"))\n        m_planeStrain = params.get<bool>(\"Plane Strain\");\n        \n    if (params.isParameter(\"Plane Stress\"))\n        m_planeStress = params.get<bool>(\"Plane Stress\");\n\n    if (m_planeStrain==true){\n        m_plane=true;\n        \n    }\n    if (m_planeStress==true){\n        m_plane=true;\n       \n    }\n  m_tension = true;\n  if (params.isParameter(\"Tension pressure separation for damage model\")){\n      m_tension = params.get<bool>(\"Tension pressure separation for damage model\");\n      \n  }\n  m_applyAutomaticDifferentiationJacobian = true;\n  if(params.isParameter(\"Apply Automatic Differentiation Jacobian\"))\n    m_applyAutomaticDifferentiationJacobian = params.get<bool>(\"Apply Automatic Differentiation Jacobian\");\n  if (params.isParameter(\"Stabilizaton Type\")){\n      \n    if (params.get<string>(\"Stabilizaton Type\")==\"Bond Based\"){\n        m_stabilizationType = 1;\n        m_hourglassCoefficient = params.get<double>(\"Hourglass Coefficient\");\n    }\n    if (params.get<string>(\"Stabilizaton Type\")==\"State Based\"){\n        m_stabilizationType = 2;\n        m_hourglassCoefficient = params.get<double>(\"Hourglass Coefficient\");\n    }\n    //if (params.get<string>(\"Stabilizaton Type\")==\"Sub Horizon\"){\n    //    m_stabilizationType = 4;\n    //    // works only for linear elastic correspondence first\n    //    // based on: Shubhankar Roy Chowdhury, Pranesh Roy, Debasish Roy and J N Reddy, \n    //    // \"A simple alteration of the peridynamics correspondence principle to eliminate zero-energy deformation\"\n    //}\n    if (params.get<string>(\"Stabilizaton Type\")==\"Global Stiffness\"){\n        \n        m_stabilizationType = 3;\n        m_hourglassCoefficient = params.get<double>(\"Hourglass Coefficient\");\n\n        double C11 = 0.0, C12 = 0.0, C13 = 0.0, C14 = 0.0, C15 = 0.0, C16 = 0.0;\n        double            C22 = 0.0, C23 = 0.0, C24 = 0.0, C25 = 0.0, C26 = 0.0;\n        double                       C33 = 0.0, C34 = 0.0, C35 = 0.0, C36 = 0.0;\n        double                                  C44 = 0.0, C45 = 0.0, C46 = 0.0;\n        double                                             C55 = 0.0, C56 = 0.0;\n        double                                                        C66 = 0.0;\n       \n        bool iso = false;\n        if (params.isParameter(\"Material Symmetry\")){\n            if (params.get<string>(\"Material Symmetry\")==\"Isotropic\"){\n                C11 = params.get<double>(\"C11\");\n                C44 = params.get<double>(\"C44\");\n                C55 = params.get<double>(\"C44\");\n                C66 = params.get<double>(\"C44\");\n                C12 = C11 - 2*C55;\n                C13 = C12;\n                C14 = 0.0;\n                C15 = 0.0;\n                C16 = 0.0;\n                C22 = params.get<double>(\"C11\");\n                C33 = params.get<double>(\"C11\");\n                C23 = C12;\n                C24 = 0.0;\n                C25 = 0.0;\n                C26 = 0.0;\n                C34 = 0.0;\n                C35 = 0.0;\n                C36 = 0.0;\n                C45 = 0.0;\n                C46 = 0.0;\n                C56 = 0.0; \n                iso  = true;\n            }\n            if (params.get<string>(\"Material Symmetry\")==\"Anisotropic\"){\n                C11 = params.get<double>(\"C11\");\n                C12 = params.get<double>(\"C12\");\n                C13 = params.get<double>(\"C13\");\n                C14 = params.get<double>(\"C14\");\n                C15 = params.get<double>(\"C15\");\n                C16 = params.get<double>(\"C16\");\n                C22 = params.get<double>(\"C22\");\n                C23 = params.get<double>(\"C23\");\n                C24 = params.get<double>(\"C24\");\n                C25 = params.get<double>(\"C25\");\n                C26 = params.get<double>(\"C26\");\n                C33 = params.get<double>(\"C33\");\n                C34 = params.get<double>(\"C34\");\n                C35 = params.get<double>(\"C35\");\n                C36 = params.get<double>(\"C36\");\n                C44 = params.get<double>(\"C44\");\n                C45 = params.get<double>(\"C45\");\n                C46 = params.get<double>(\"C46\");\n                C55 = params.get<double>(\"C55\");\n                C56 = params.get<double>(\"C56\");\n                C66 = params.get<double>(\"C66\");\n                \n            }\n        \n        }\n        else{\n            m_bulkModulus = calculateBulkModulus(params);\n            m_shearModulus = calculateShearModulus(params);\n        \n            C11 = (4*m_shearModulus*(3*m_bulkModulus + m_shearModulus))/(3*m_bulkModulus + 4*m_shearModulus);\n            C44 = m_shearModulus;\n            C55 = m_shearModulus;\n            C66 = m_shearModulus;\n            C12 = (2*(3*m_bulkModulus - 2*m_shearModulus)*m_shearModulus)/(3*m_bulkModulus + 4*m_shearModulus);\n            C13 = C12;\n            C14 = 0.0;\n            C15 = 0.0;\n            C16 = 0.0;\n            C22 = C11;\n            C33 = C11;\n            C23 = C12;\n            C24 = 0.0;\n            C25 = 0.0;\n            C26 = 0.0;\n            C34 = 0.0;\n            C35 = 0.0;\n            C36 = 0.0;\n            C45 = 0.0;\n            C46 = 0.0;\n            C56 = 0.0;\n        }\n        // Equation (8) Dipasquale, D., Sarego, G., Zaccariotto, M., Galvanetto, U., A discussion on failure criteria\n          // for ordinary state-based Peridynamics, Engineering Fracture Mechanics (2017), doi: https://doi.org/10.1016/\n          // j.engfracmech.2017.10.011\n        if (m_planeStrain==true)m_plane=true;\n        if (m_planeStress==true)m_plane=true;\n        // have to be done after rotation if angles exist\n        if (m_plane==false){\n         C[0][0] = C11;C[0][1] = C12;C[0][2]= C13; C[0][3] = C14; C[0][4] = C15; C[0][5]= C16;\n         C[1][0] = C12;C[1][1] = C22;C[1][2]= C23; C[1][3] = C24; C[1][4] = C25; C[1][5]= C26;\n         C[2][0] = C13;C[2][1] = C23;C[2][2]= C33; C[2][3] = C34; C[2][4] = C35; C[2][5]= C36;\n         C[3][0] = C14;C[3][1] = C24;C[3][2]= C34; C[3][3] = C44; C[3][4] = C45; C[3][5]= C46;\n         C[4][0] = C15;C[4][1] = C25;C[4][2]= C35; C[4][3] = C45; C[4][4] = C55; C[4][5]= C56;\n         C[5][0] = C16;C[5][1] = C26;C[5][2]= C36; C[5][3] = C46; C[5][4] = C56; C[5][5]= C66;\n        }\n        // tbd in future\n        if (m_planeStress==true && iso == true){\n            //only transversal isotropic in the moment --> definition of iso missing\n         C[0][0] = C11-C13*C13/C22;C[0][1] = C12-C13*C23/C22;C[0][2] = 0.0; C[0][3] = 0.0; C[0][4] = 0.0; C[0][5] = 0.0;\n         C[1][0] = C12-C13*C23/C22;C[1][1] = C22-C13*C23/C22;C[1][2] = 0.0; C[1][3] = 0.0; C[1][4] = 0.0; C[1][5] = 0.0;\n         C[2][0] = 0.0;            C[2][1] = 0.0;            C[2][2] = 0.0; C[2][3] = 0.0; C[2][4] = 0.0; C[2][5] = 0.0;\n         C[3][0] = 0.0;            C[3][1] = 0.0;            C[3][2] = 0.0; C[3][3] = 0.0; C[3][4] = 0.0; C[3][5] = 0.0;\n         C[4][0] = 0.0;            C[4][1] = 0.0;            C[4][2] = 0.0; C[4][3] = 0.0; C[4][4] = 0.0; C[4][5] = 0.0;\n         C[5][0] = 0.0;            C[5][1] = 0.0;            C[5][2] = 0.0; C[5][3] = 0.0; C[5][4] = 0.0; C[5][5] = C66;\n        }\n        // not correct for plane stress!!!\n        if (m_plane==true && iso == false){\n         C[0][0] = C11;C[0][1] = C12;C[0][2] = 0.0;C[0][3] = 0.0;C[0][4] = 0.0;C[0][5] = C16;\n         C[1][0] = C12;C[1][1] = C22;C[1][2] = 0.0;C[1][3] = 0.0;C[1][4] = 0.0;C[1][5] = C26;\n         C[2][0] = 0.0;C[2][1] = 0.0;C[2][2] = 0.0;C[2][3] = 0.0;C[2][4] = 0.0;C[2][5] = 0.0;\n         C[3][0] = 0.0;C[3][1] = 0.0;C[3][2] = 0.0;C[3][3] = 0.0;C[3][4] = 0.0;C[3][5] = 0.0;\n         C[4][0] = 0.0;C[4][1] = 0.0;C[4][2] = 0.0;C[4][3] = 0.0;C[4][4] = 0.0;C[4][5] = 0.0;\n         C[5][0] = C16;C[5][1] = C26;C[5][2] = 0.0;C[5][3] = 0.0;C[5][4] = 0.0;C[5][5] = C66;\n        \n        }\n        \n    }\n  }\n  nonLin = false;\n  lin = true;\n\n  if (params.isParameter(\"Elastic Correspondence\")){\n     \n      nonLin = true;\n      lin = false;\n\n    }\n\n\n\n\n  //TEUCHOS_TEST_FOR_EXCEPT_MSG(params.isParameter(\"Apply Automatic Differentiation Jacobian\"), \"**** Error:  Automatic Differentiation is not supported for the ElasticCorrespondence material model.\\n\");\n  TEUCHOS_TEST_FOR_EXCEPT_MSG(params.isParameter(\"Apply Shear Correction Factor\"), \"**** Error:  Shear Correction Factor is not supported for the ElasticCorrespondence material model.\\n\");\n  TEUCHOS_TEST_FOR_EXCEPT_MSG(params.isParameter(\"Thermal Expansion Coefficient\"), \"**** Error:  Thermal expansion is not currently supported for the ElasticCorrespondence material model.\\n\");\n\n  PeridigmNS::FieldManager& fieldManager = PeridigmNS::FieldManager::self();\n  m_horizonFieldId                    = fieldManager.getFieldId(PeridigmField::ELEMENT, PeridigmField::SCALAR, PeridigmField::CONSTANT, \"Horizon\");\n  m_volumeFieldId                     = fieldManager.getFieldId(PeridigmField::ELEMENT, PeridigmField::SCALAR, PeridigmField::CONSTANT, \"Volume\");\n  m_modelCoordinatesFieldId           = fieldManager.getFieldId(PeridigmField::NODE,    PeridigmField::VECTOR, PeridigmField::CONSTANT, \"Model_Coordinates\");\n  m_modelAnglesId                     = fieldManager.getFieldId(PeridigmField::NODE,    PeridigmField::VECTOR, PeridigmField::CONSTANT, \"Local_Angles\");\n  m_coordinatesFieldId                = fieldManager.getFieldId(PeridigmField::NODE,    PeridigmField::VECTOR, PeridigmField::TWO_STEP, \"Coordinates\");\n  m_velocitiesFieldId                 = fieldManager.getFieldId(PeridigmField::NODE,    PeridigmField::VECTOR, PeridigmField::TWO_STEP, \"Velocity\");\n  m_forceDensityFieldId               = fieldManager.getFieldId(PeridigmField::NODE,    PeridigmField::VECTOR, PeridigmField::TWO_STEP, \"Force_Density\");\n  m_hourglassForceDensityFieldId      = fieldManager.getFieldId(PeridigmField::NODE,    PeridigmField::VECTOR, PeridigmField::TWO_STEP, \"Hourglass_Force_Density\");\n  m_bondDamageFieldId                 = fieldManager.getFieldId(PeridigmField::BOND,    PeridigmField::SCALAR, PeridigmField::TWO_STEP, \"Bond_Damage\");\n  m_deformationGradientFieldId        = fieldManager.getFieldId(PeridigmField::ELEMENT, PeridigmField::FULL_TENSOR, PeridigmField::CONSTANT, \"Deformation_Gradient\");\n  m_leftStretchTensorFieldId          = fieldManager.getFieldId(PeridigmField::ELEMENT, PeridigmField::FULL_TENSOR, PeridigmField::TWO_STEP, \"Left_Stretch_Tensor\");\n  m_rotationTensorFieldId             = fieldManager.getFieldId(PeridigmField::ELEMENT, PeridigmField::FULL_TENSOR, PeridigmField::TWO_STEP, \"Rotation_Tensor\");\n  m_shapeTensorInverseFieldId         = fieldManager.getFieldId(PeridigmField::ELEMENT, PeridigmField::FULL_TENSOR, PeridigmField::CONSTANT, \"Shape_Tensor_Inverse\");\n  m_unrotatedCauchyStressFieldId      = fieldManager.getFieldId(PeridigmField::ELEMENT, PeridigmField::FULL_TENSOR, PeridigmField::TWO_STEP, \"Unrotated_Cauchy_Stress\");\n  m_cauchyStressFieldId               = fieldManager.getFieldId(PeridigmField::ELEMENT, PeridigmField::FULL_TENSOR, PeridigmField::TWO_STEP, \"Cauchy_Stress\");\n  m_piolaStressTimesInvShapeTensorXId = fieldManager.getFieldId(PeridigmField::ELEMENT, PeridigmField::VECTOR, PeridigmField::TWO_STEP, \"PiolaStressTimesInvShapeTensorX\");\n  m_piolaStressTimesInvShapeTensorYId = fieldManager.getFieldId(PeridigmField::ELEMENT, PeridigmField::VECTOR, PeridigmField::TWO_STEP, \"PiolaStressTimesInvShapeTensorY\");\n  m_piolaStressTimesInvShapeTensorZId = fieldManager.getFieldId(PeridigmField::ELEMENT, PeridigmField::VECTOR, PeridigmField::TWO_STEP, \"PiolaStressTimesInvShapeTensorZ\");\n  m_unrotatedRateOfDeformationFieldId = fieldManager.getFieldId(PeridigmField::ELEMENT, PeridigmField::FULL_TENSOR, PeridigmField::CONSTANT, \"Unrotated_Rate_Of_Deformation\");\n  m_partialStressFieldId              = fieldManager.getFieldId(PeridigmField::ELEMENT, PeridigmField::FULL_TENSOR, PeridigmField::TWO_STEP, \"Partial_Stress\");\n  m_detachedNodesFieldId              = fieldManager.getFieldId(PeridigmField::NODE,    PeridigmField::SCALAR, PeridigmField::TWO_STEP, \"Detached_Nodes\");\n  m_hourglassStiffId                  = fieldManager.getFieldId(PeridigmField::ELEMENT, PeridigmField::FULL_TENSOR, PeridigmField::CONSTANT, \"Hourglass_Stiffness\");\n  \n  m_fieldIds.push_back(m_horizonFieldId);\n  m_fieldIds.push_back(m_volumeFieldId);\n  m_fieldIds.push_back(m_modelCoordinatesFieldId);\n  m_fieldIds.push_back(m_coordinatesFieldId);\n  m_fieldIds.push_back(m_velocitiesFieldId);\n  m_fieldIds.push_back(m_hourglassForceDensityFieldId);\n  m_fieldIds.push_back(m_forceDensityFieldId);\n  m_fieldIds.push_back(m_bondDamageFieldId);\n  m_fieldIds.push_back(m_deformationGradientFieldId);\n  \n  m_fieldIds.push_back(m_leftStretchTensorFieldId);\n  m_fieldIds.push_back(m_rotationTensorFieldId);\n  m_fieldIds.push_back(m_shapeTensorInverseFieldId);\n  m_fieldIds.push_back(m_unrotatedCauchyStressFieldId);\n  m_fieldIds.push_back(m_cauchyStressFieldId);\n  m_fieldIds.push_back(m_piolaStressTimesInvShapeTensorXId);\n  m_fieldIds.push_back(m_piolaStressTimesInvShapeTensorYId);\n  m_fieldIds.push_back(m_piolaStressTimesInvShapeTensorZId);\n  m_fieldIds.push_back(m_unrotatedRateOfDeformationFieldId);\n  m_fieldIds.push_back(m_partialStressFieldId);\n  m_fieldIds.push_back(m_detachedNodesFieldId);\n  m_fieldIds.push_back(m_hourglassStiffId);\n  m_fieldIds.push_back(m_modelAnglesId);\n\n  }\n\nPeridigmNS::CorrespondenceMaterial::~CorrespondenceMaterial()\n{\n}\n\nvoid\nPeridigmNS::CorrespondenceMaterial::initialize(const double dt,\n                                               const int numOwnedPoints,\n                                               const int* ownedIDs,\n                                               const int* neighborhoodList,\n                                               PeridigmNS::DataManager& dataManager)\n{\n  \n  dataManager.getData(m_unrotatedRateOfDeformationFieldId, PeridigmField::STEP_NONE)->PutScalar(0.0);\n  dataManager.getData(m_hourglassStiffId, PeridigmField::STEP_NONE)->PutScalar(0.0);\n  dataManager.getData(m_leftStretchTensorFieldId, PeridigmField::STEP_N)->PutScalar(0.0);\n  dataManager.getData(m_leftStretchTensorFieldId, PeridigmField::STEP_NP1)->PutScalar(0.0);\n  dataManager.getData(m_rotationTensorFieldId, PeridigmField::STEP_N)->PutScalar(0.0);\n  dataManager.getData(m_rotationTensorFieldId, PeridigmField::STEP_NP1)->PutScalar(0.0);\n  dataManager.getData(m_unrotatedCauchyStressFieldId, PeridigmField::STEP_N)->PutScalar(0.0);\n  dataManager.getData(m_unrotatedCauchyStressFieldId, PeridigmField::STEP_NP1)->PutScalar(0.0);\n  dataManager.getData(m_cauchyStressFieldId, PeridigmField::STEP_N)->PutScalar(0.0);\n  dataManager.getData(m_cauchyStressFieldId, PeridigmField::STEP_NP1)->PutScalar(0.0);\n  dataManager.getData(m_detachedNodesFieldId, PeridigmField::STEP_NP1)->PutScalar(0.0);\n  \n  \n  dataManager.getData(m_partialStressFieldId, PeridigmField::STEP_N)->PutScalar(0.0);\n  dataManager.getData(m_partialStressFieldId, PeridigmField::STEP_NP1)->PutScalar(0.0);\n  \n  dataManager.getData(m_piolaStressTimesInvShapeTensorXId, PeridigmField::STEP_NP1)->PutScalar(0.0);\n  dataManager.getData(m_piolaStressTimesInvShapeTensorYId, PeridigmField::STEP_NP1)->PutScalar(0.0);\n  dataManager.getData(m_piolaStressTimesInvShapeTensorZId, PeridigmField::STEP_NP1)->PutScalar(0.0);\n\n\n  double *leftStretchTensorN;\n  double *leftStretchTensorNP1;\n  double *rotationTensorN;\n  double *rotationTensorNP1;\n  double *detachedNodes;\n  dataManager.getData(m_leftStretchTensorFieldId, PeridigmField::STEP_N)->ExtractView(&leftStretchTensorN);\n  dataManager.getData(m_leftStretchTensorFieldId, PeridigmField::STEP_NP1)->ExtractView(&leftStretchTensorNP1);\n  dataManager.getData(m_rotationTensorFieldId, PeridigmField::STEP_N)->ExtractView(&rotationTensorN);\n  dataManager.getData(m_rotationTensorFieldId, PeridigmField::STEP_NP1)->ExtractView(&rotationTensorNP1);\n  dataManager.getData(m_detachedNodesFieldId, PeridigmField::STEP_NP1)->ExtractView(&detachedNodes);\n  //Initialize the left stretch and rotation tenor to the identity matrix\n  CORRESPONDENCE::setOnesOnDiagonalFullTensor(leftStretchTensorN, numOwnedPoints);\n  CORRESPONDENCE::setOnesOnDiagonalFullTensor(leftStretchTensorNP1, numOwnedPoints);\n  CORRESPONDENCE::setOnesOnDiagonalFullTensor(rotationTensorN, numOwnedPoints);\n  CORRESPONDENCE::setOnesOnDiagonalFullTensor(rotationTensorNP1, numOwnedPoints);\n\n  //Initialize the inverse of the shape tensor and the deformation gradient\n  double *volume;\n  double *horizon;\n  double *modelCoordinates;\n  double *coordinates;\n  double *coordinatesNP1;\n  double *shapeTensorInverse;\n  double *deformationGradient;\n  double *bondDamage;\n\n\n  dataManager.getData(m_volumeFieldId, PeridigmField::STEP_NONE)->ExtractView(&volume);\n  dataManager.getData(m_horizonFieldId, PeridigmField::STEP_NONE)->ExtractView(&horizon);\n\n  dataManager.getData(m_modelCoordinatesFieldId, PeridigmField::STEP_NONE)->ExtractView(&modelCoordinates);\n  dataManager.getData(m_coordinatesFieldId, PeridigmField::STEP_N)->ExtractView(&coordinates);\n  dataManager.getData(m_coordinatesFieldId, PeridigmField::STEP_NP1)->ExtractView(&coordinatesNP1);\n  dataManager.getData(m_shapeTensorInverseFieldId, PeridigmField::STEP_NONE)->ExtractView(&shapeTensorInverse);\n  dataManager.getData(m_deformationGradientFieldId, PeridigmField::STEP_NONE)->ExtractView(&deformationGradient);\n  dataManager.getData(m_unrotatedRateOfDeformationFieldId, PeridigmField::STEP_NONE)->PutScalar(0.0);\n  dataManager.getData(m_bondDamageFieldId, PeridigmField::STEP_NP1)->ExtractView(&bondDamage);\n\n int shapeTensorReturnCode = 0;\n  shapeTensorReturnCode = \n            CORRESPONDENCE::computeShapeTensorInverseAndApproximateDeformationGradient(volume,\n                                                                                   horizon,\n                                                                                   modelCoordinates,\n                                                                                   coordinates,\n                                                                                   coordinatesNP1,\n                                                                                   shapeTensorInverse,\n                                                                                   deformationGradient,\n                                                                                   bondDamage,\n                                                                                   neighborhoodList,\n                                                                                   numOwnedPoints,\n                                                                                   m_plane,\n                                                                                   detachedNodes);\n\n  string shapeTensorErrorMessage =\n    \"**** Error:  CorrespondenceMaterial::initialize() failed to compute shape tensor.\\n\";\n  shapeTensorErrorMessage +=\n    \"****         Note that all nodes must have a minimum of three neighbors.  Is the horizon too small?\\n\";\n  TEUCHOS_TEST_FOR_EXCEPT_MSG(shapeTensorReturnCode != 0, shapeTensorErrorMessage);\n\n}\n\nvoid\nPeridigmNS::CorrespondenceMaterial::computeForce(const double dt,\n                                                 const int numOwnedPoints,\n                                                 const int* ownedIDs,\n                                                 const int* neighborhoodList,\n                                                 PeridigmNS::DataManager& dataManager) const\n{\n  // Zero out the forces and partial stress\n\n  dataManager.getData(m_forceDensityFieldId, PeridigmField::STEP_NP1)->PutScalar(0.0);\n  dataManager.getData(m_partialStressFieldId, PeridigmField::STEP_NP1)->PutScalar(0.0);\n  dataManager.getData(m_unrotatedRateOfDeformationFieldId, PeridigmField::STEP_NONE)->PutScalar(0.0);\n  double *horizon, *volume, *modelCoordinates, *coordinates, *coordinatesNP1, *shapeTensorInverse, *deformationGradient, *bondDamage, *pointAngles, *detachedNodes;\n  //double *deformationGradientNonInc;\n\n  dataManager.getData(m_horizonFieldId, PeridigmField::STEP_NONE)->ExtractView(&horizon);\n  dataManager.getData(m_volumeFieldId, PeridigmField::STEP_NONE)->ExtractView(&volume);\n  dataManager.getData(m_modelCoordinatesFieldId, PeridigmField::STEP_NONE)->ExtractView(&modelCoordinates);\n  dataManager.getData(m_modelAnglesId,           PeridigmField::STEP_NONE)->ExtractView(&pointAngles);\n  dataManager.getData(m_coordinatesFieldId, PeridigmField::STEP_N)->ExtractView(&coordinates);\n  dataManager.getData(m_coordinatesFieldId, PeridigmField::STEP_NP1)->ExtractView(&coordinatesNP1);\n  dataManager.getData(m_shapeTensorInverseFieldId, PeridigmField::STEP_NONE)->ExtractView(&shapeTensorInverse);\n  dataManager.getData(m_deformationGradientFieldId, PeridigmField::STEP_NONE)->ExtractView(&deformationGradient);\n\n          \n          \n  dataManager.getData(m_bondDamageFieldId, PeridigmField::STEP_NP1)->ExtractView(&bondDamage);\n\n  \n  dataManager.getData(m_detachedNodesFieldId, PeridigmField::STEP_NP1)->ExtractView(&detachedNodes);\n  // Compute the inverse of the shape tensor and the approximate deformation gradient\n  // The approximate deformation gradient will be used by the derived class (specific correspondence material model)\n  // to compute the Cauchy stress.\n  // The inverse of the shape tensor is stored for later use after the Cauchy stress calculation\n\n   // vier szenarien\n   int shapeTensorReturnCode = 0;\n  // if (lin == true){\n    \n    \n    shapeTensorReturnCode = \n        CORRESPONDENCE::computeShapeTensorInverseAndApproximateDeformationGradient(volume,\n                                                                                horizon,\n                                                                                modelCoordinates,\n                                                                                coordinates,\n                                                                                coordinatesNP1,\n                                                                                shapeTensorInverse,\n                                                                                deformationGradient,\n                                                                                bondDamage,\n                                                                                neighborhoodList,\n                                                                                numOwnedPoints,\n                                                                                m_plane,\n                                                                                detachedNodes);\n\n    \n   //}\n\n  string shapeTensorErrorMessage =\n    \"**** Error:  CorrespondenceMaterial::computeForce() failed to compute shape tensor.\\n\";\n  shapeTensorErrorMessage +=\n    \"****         Note that all nodes must have a minimum of three neighbors.  Is the horizon too small?\\n\";\n  TEUCHOS_TEST_FOR_EXCEPT_MSG(shapeTensorReturnCode != 0, shapeTensorErrorMessage);\n\n  \n  double *velocities, *leftStretchTensorN, *leftStretchTensorNP1, *rotationTensorN, *rotationTensorNP1, *unrotatedRateOfDeformation;\n  if (nonLin==true){  \n      dataManager.getData(m_leftStretchTensorFieldId, PeridigmField::STEP_N)->ExtractView(&leftStretchTensorN);\n      dataManager.getData(m_leftStretchTensorFieldId, PeridigmField::STEP_NP1)->ExtractView(&leftStretchTensorNP1);\n      dataManager.getData(m_rotationTensorFieldId, PeridigmField::STEP_N)->ExtractView(&rotationTensorN);\n      dataManager.getData(m_rotationTensorFieldId, PeridigmField::STEP_NP1)->ExtractView(&rotationTensorNP1);\n      dataManager.getData(m_unrotatedRateOfDeformationFieldId, PeridigmField::STEP_NONE)->ExtractView(&unrotatedRateOfDeformation);\n      dataManager.getData(m_velocitiesFieldId, PeridigmField::STEP_NP1)->ExtractView(&velocities);\n      // Compute left stretch tensor, rotation tensor, and unrotated rate-of-deformation.\n      // Performs a polar decomposition via Flanagan & Taylor (1987) algorithm.\n      //\"A non-ordinary state-based peridynamic method to model solid material deformation and fracture\"\n      // Thomas L. Warren, Stewart A. Silling, Abe Askari, Olaf Weckner, Michael A. Epton, Jifeng Xu\n      \n      int rotationTensorReturnCode = 0;\n\n      rotationTensorReturnCode = CORRESPONDENCE::computeUnrotatedRateOfDeformationAndRotationTensor(volume,\n                                                                                                   horizon,\n                                                                                                   modelCoordinates, \n                                                                                                   velocities, \n                                                                                                   deformationGradient,\n                                                                                                   shapeTensorInverse,\n                                                                                                   leftStretchTensorN,\n                                                                                                   rotationTensorN,\n                                                                                                   leftStretchTensorNP1,\n                                                                                                   rotationTensorNP1,\n                                                                                                   unrotatedRateOfDeformation,\n                                                                                                   neighborhoodList, \n                                                                                                   numOwnedPoints, \n                                                                                                   dt,\n                                                                                                   bondDamage,\n                                                                                                   m_plane,\n                                                                                                   detachedNodes);\n\n      string rotationTensorErrorMessage =\n        \"**** Error:  CorrespondenceMaterial::computeForce() failed to compute rotation tensor.\\n\";\n      rotationTensorErrorMessage +=\n        \"****         Note that all nodes must have a minimum of three neighbors.  Is the horizon too small?\\n\";\n      string rotationTensorErrorMessage2 =\n        \"**** Error:  CorrespondenceMaterial::computeForce() failed to invert deformation gradient tensor.\\n\";\n        \n      string rotationTensorErrorMessage3 =\n        \"**** Error:  CorrespondenceMaterial::computeForce() failed to invert temp.\\n\";\n\n      TEUCHOS_TEST_FOR_EXCEPT_MSG(rotationTensorReturnCode == 1, rotationTensorErrorMessage);\n      TEUCHOS_TEST_FOR_EXCEPT_MSG(rotationTensorReturnCode == 2, rotationTensorErrorMessage2);\n      TEUCHOS_TEST_FOR_EXCEPT_MSG(rotationTensorReturnCode == 3, rotationTensorErrorMessage3);\n                                    \n     }  \n    \n  // Evaluate the Cauchy stress using the routine implemented in the derived class (specific correspondence material model)\n  // The general idea is to compute the stress based on:\n  //   1) The unrotated rate-of-deformation tensor\n  //   2) The time step\n  //   3) Whatever state variables are managed by the derived class\n  //\n  // computeCauchyStress() typically uses the following fields which are accessed via the DataManager:\n  //   Input:  unrotated rate-of-deformation tensor\n  //   Input:  unrotated Cauchy stress at step N\n  //   Input:  internal state data (managed in the derived class)\n  //   Output: unrotated Cauchy stress at step N+1\n  \n  // multiple Cauchy stresses will be provided over the datamanager --> Peridigm_ElasticLinearCorrespondence\n\n                \n  computeCauchyStress(dt, numOwnedPoints, dataManager);\n\n  // rotate back to the Eulerian frame\n  double *unrotatedCauchyStressNP1, *cauchyStressNP1;\n\n\n  if (nonLin == true) {\n      dataManager.getData(m_unrotatedCauchyStressFieldId, PeridigmField::STEP_NP1)->ExtractView(&unrotatedCauchyStressNP1);\n      dataManager.getData(m_cauchyStressFieldId, PeridigmField::STEP_NP1)->ExtractView(&cauchyStressNP1);\n      \n      CORRESPONDENCE::rotateCauchyStress(rotationTensorNP1,\n                                         unrotatedCauchyStressNP1,\n                                         cauchyStressNP1,\n                                         numOwnedPoints);\n                                         // Cauchy stress is now updated and in the rotated state. \n  }\n  else\n  {\n    dataManager.getData(m_cauchyStressFieldId, PeridigmField::STEP_NP1)->ExtractView(&cauchyStressNP1);\n    \n  }\n\n   \n  // Proceed with conversion to Piola-Kirchoff and force-vector states.\n//--------------------------------------------------------------------------\n double *forceDensity;\n dataManager.getData(m_forceDensityFieldId, PeridigmField::STEP_NP1)->ExtractView(&forceDensity);\n dataManager.getData(m_forceDensityFieldId, PeridigmField::STEP_NP1)->PutScalar(0.0);\n double *partialStress;\n dataManager.getData(m_partialStressFieldId, PeridigmField::STEP_NP1)->ExtractView(&partialStress);\n dataManager.getData(m_partialStressFieldId, PeridigmField::STEP_NP1)->PutScalar(0.0);\n \n double *tempStressX, *tempStressY, *tempStressZ;\n dataManager.getData(m_piolaStressTimesInvShapeTensorXId, PeridigmField::STEP_NP1)->ExtractView(&tempStressX);\n dataManager.getData(m_piolaStressTimesInvShapeTensorYId, PeridigmField::STEP_NP1)->ExtractView(&tempStressY);\n dataManager.getData(m_piolaStressTimesInvShapeTensorZId, PeridigmField::STEP_NP1)->ExtractView(&tempStressZ);\n dataManager.getData(m_piolaStressTimesInvShapeTensorXId, PeridigmField::STEP_NP1)->PutScalar(0.0);\n dataManager.getData(m_piolaStressTimesInvShapeTensorYId, PeridigmField::STEP_NP1)->PutScalar(0.0);\n dataManager.getData(m_piolaStressTimesInvShapeTensorZId, PeridigmField::STEP_NP1)->PutScalar(0.0);\n\n double *hourglassStiff;\n\n dataManager.getData(m_hourglassStiffId, PeridigmField::STEP_NONE)->ExtractView(&hourglassStiff);\n\n\n\n CORRESPONDENCE::computeForcesAndStresses(\n                                       numOwnedPoints,\n                                       neighborhoodList,\n                                       volume,\n                                       horizon,\n                                       modelCoordinates,\n                                       coordinatesNP1,\n                                       deformationGradient,\n                                       cauchyStressNP1,\n                                       shapeTensorInverse,\n                                       bondDamage,\n                                       C,\n                                       pointAngles,\n                                       forceDensity,\n                                       partialStress,\n                                       tempStressX,\n                                       tempStressY,\n                                       tempStressZ,\n                                       hourglassStiff,\n                                       m_hourglassCoefficient,\n                                       m_stabilizationType,\n                                       m_plane,\n                                       m_tension,\n                                       detachedNodes);\n                                          \n //     std::cout<<numOwnedPoints<< \" \"<< *(deformationGradient)<<\" \"<<*(partialStress)<<std::endl;\n    \n\n  if (m_incremental == false){\n      if (m_stabilizationType == 1){\n      CORRESPONDENCE::computeHourglassForce(volume,\n                                            horizon,\n                                            modelCoordinates,\n                                            coordinates,\n                                            deformationGradient,\n                                            forceDensity,\n                                            neighborhoodList,\n                                            numOwnedPoints,\n                                            m_bulkModulus,\n                                            m_hourglassCoefficient,\n                                            bondDamage\n                                            );\n      }\n      \n      if (m_stabilizationType == 2){\n      \n      CORRESPONDENCE::computeCorrespondenceStabilityForce(volume,\n                                            horizon,\n                                            modelCoordinates,\n                                            coordinates,\n                                            deformationGradient,\n                                            forceDensity,\n                                            neighborhoodList,\n                                            numOwnedPoints,\n                                            m_bulkModulus,\n                                            m_hourglassCoefficient,\n                                            bondDamage\n                                            );\n      }\n  }\n}\n\nvoid\nPeridigmNS::CorrespondenceMaterial::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\n  if(m_applyAutomaticDifferentiationJacobian){\n    // Compute the Jacobian via automatic differentiation\n    computeAutomaticDifferentiationJacobian(dt, numOwnedPoints, ownedIDs, neighborhoodList, dataManager, jacobian, jacobianType);  \n  }\n  else{\n  //  // Call the base class function, which computes the Jacobian by finite difference\n    computeJacobianFiniteDifference(dt, numOwnedPoints, ownedIDs, neighborhoodList, dataManager, jacobian, CENTRAL_DIFFERENCE, jacobianType);\n  }\n}\n\n\nvoid\nPeridigmNS::CorrespondenceMaterial::computeAutomaticDifferentiationJacobian(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 contributions to the tangent matrix on an element-by-element basis\n\n  // To reduce memory re-allocation, use static variable to store Fad types for\n  // current coordinates (independent variables).\n\n  static vector<Sacado::Fad::DFad<double> > coordinatesNP1_AD;\n  static vector<Sacado::Fad::DFad<double> > coordinates_AD;\n\n  static Sacado::Fad::DFad<double> C_AD[6][6];\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    int numEntries = numNeighbors+1;\n    int numDof = 3*numEntries;\n    vector<int> tempMyGlobalIDs(numEntries);\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(numEntries); \n    tempNeighborhoodList[0] = numNeighbors;\n\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(numEntries, numEntries, &tempMyGlobalIDs[0], 1, 0, serialComm));\n    Teuchos::RCP<Epetra_BlockMap> tempThreeDimensionalMap = Teuchos::rcp(new Epetra_BlockMap(numEntries, numEntries, &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 field specs 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(tempNumOwnedPoints);\n    tempOwnedIDs[0] = 0;\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() < numDof)\n      scratchMatrix.Resize(numDof);\n\n    // Create a list of global indices for the rows/columns in the scratch matrix.\n    vector<int> globalIndices(numDof);\n    for(int i=0 ; i<numEntries ; ++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    // Extract pointers to the underlying data in the constitutive data array.\n\n    double *modelCoordinates, *coordinates, *volume, *coordinatesNP1, *angles, *detachedNodes;\n    tempDataManager.getData(m_modelAnglesId,           PeridigmField::STEP_NONE)->ExtractView(&angles);\n    tempDataManager.getData(m_volumeFieldId, PeridigmField::STEP_NONE)->ExtractView(&volume);\n    tempDataManager.getData(m_modelCoordinatesFieldId, PeridigmField::STEP_NONE)->ExtractView(&modelCoordinates);\n    tempDataManager.getData(m_coordinatesFieldId, PeridigmField::STEP_N)->ExtractView(&coordinates);\n    tempDataManager.getData(m_coordinatesFieldId, PeridigmField::STEP_NP1)->ExtractView(&coordinatesNP1);\n    dataManager.getData(m_detachedNodesFieldId, PeridigmField::STEP_NP1)->ExtractView(&detachedNodes);\n    double *horizon, *bondDamage;\n    tempDataManager.getData(m_horizonFieldId, PeridigmField::STEP_NONE)->ExtractView(&horizon);\n    tempDataManager.getData(m_bondDamageFieldId, PeridigmField::STEP_NP1)->ExtractView(&bondDamage);\n \n    // Create arrays of Fad objects for the current coordinates, dilatation, and force density\n    // Modify the existing vector of Fad objects for the current coordinates\n    if((int)coordinatesNP1_AD.size() < numDof) {\n      coordinates_AD.resize(numDof);\n      coordinatesNP1_AD.resize(numDof);\n    }\n    for(int i=0 ; i<numDof ; ++i){\n      coordinates_AD[i].diff(i, numDof);\n      coordinates_AD[i].val() = coordinates[i];\n      coordinatesNP1_AD[i].diff(i, numDof);\n      coordinatesNP1_AD[i].val() = coordinatesNP1[i];\n    }\n    \n    vector<Sacado::Fad::DFad<double> > shapeTensorInverse_AD;\n    vector<Sacado::Fad::DFad<double> > deformationGradient_AD;\n    vector<Sacado::Fad::DFad<double> > cauchyStress_AD;\n    vector<Sacado::Fad::DFad<double> > cauchyStressNP1_AD;\n    vector<Sacado::Fad::DFad<double> > partialStress_AD;\n    vector<Sacado::Fad::DFad<double> > tempStressX_AD;\n    vector<Sacado::Fad::DFad<double> > tempStressY_AD;\n    vector<Sacado::Fad::DFad<double> > tempStressZ_AD;\n    vector<Sacado::Fad::DFad<double> > hourglassStiff_AD;\n    \n    partialStress_AD.resize(numDof*numDof);\n    shapeTensorInverse_AD.resize(numDof*numDof);\n    deformationGradient_AD.resize(numDof*numDof);\n    cauchyStress_AD.resize(numDof*numDof);\n    cauchyStressNP1_AD.resize(numDof*numDof);\n    tempStressX_AD.resize(numDof*numDof);\n    tempStressY_AD.resize(numDof*numDof);\n    tempStressZ_AD.resize(numDof*numDof);\n    hourglassStiff_AD.resize(numDof*numDof);\n\n    for(int i=0 ; i<6 ; ++i){\n        for(int j=0 ; j<6 ; ++j){\n            C_AD[i][j].val() = C[i][j];\n    }}\n\n    int shapeTensorReturnCode = 0;\n      shapeTensorReturnCode = \n                CORRESPONDENCE::computeShapeTensorInverseAndApproximateDeformationGradient(volume,\n                                                                                       horizon,\n                                                                                       modelCoordinates,\n                                                                                       &coordinates_AD[0],\n                                                                                       &coordinatesNP1_AD[0],\n                                                                                       &shapeTensorInverse_AD[0],\n                                                                                       &deformationGradient_AD[0],\n                                                                                       bondDamage,\n                                                                                       &tempNeighborhoodList[0],\n                                                                                       tempNumOwnedPoints,\n                                                                                       m_plane,\n                                                                                       detachedNodes);\n    double *cauchyStress;\n    double *cauchyStressNP1;\n\n    tempDataManager.getData(m_cauchyStressFieldId, PeridigmField::STEP_N)->ExtractView(&cauchyStress);\n    tempDataManager.getData(m_cauchyStressFieldId, PeridigmField::STEP_N)->ExtractView(&cauchyStressNP1);\n    CORRESPONDENCE::updateElasticCauchyStressSmallDef(&deformationGradient_AD[0], \n                                          &cauchyStress_AD[0],\n                                          &cauchyStressNP1_AD[0],\n                                          tempNumOwnedPoints,\n                                          &C_AD[0],\n                                          angles,\n                                          m_type,\n                                          dt,\n                                          m_incremental);\n    \n    // define the sacadoFAD force vector\n    vector<Sacado::Fad::DFad<double> > force_AD(numDof);\n    //std::cout<<m_stabilizationType<<std::endl;\n    CORRESPONDENCE::computeForcesAndStresses(\n                                        tempNumOwnedPoints,\n                                        &tempNeighborhoodList[0],\n                                        volume,\n                                        horizon,\n                                        modelCoordinates,\n                                        &coordinatesNP1_AD[0],\n                                        &deformationGradient_AD[0],\n                                        &cauchyStressNP1_AD[0],\n                                        &shapeTensorInverse_AD[0],\n                                        bondDamage,\n                                        &C_AD[0],\n                                        angles,\n                                        &force_AD[0],\n                                        &partialStress_AD[0],\n                                        &tempStressX_AD[0],\n                                        &tempStressY_AD[0],\n                                        &tempStressZ_AD[0],\n                                        &hourglassStiff_AD[0],\n                                        m_hourglassCoefficient,\n                                        m_stabilizationType,\n                                        m_plane,\n                                        m_tension,\n                                        detachedNodes);\n\n    // Load derivative values into scratch matrix\n    // Multiply by volume along the way to convert force density to force\n    double value;\n    for(int row=0 ; row<numDof ; ++row){\n      for(int col=0 ; col<numDof ; ++col){\n\tvalue = force_AD[row].dx(col) ; //--> I think this must be it, because forces are already provided\n    //value = force_AD[row].dx(col) * volume[row/3]; // given by peridigm org\n\tTEUCHOS_TEST_FOR_EXCEPT_MSG(!boost::math::isfinite(value), \"**** NaN detected in correspondence::computeAutomaticDifferentiationJacobian().\\n\");\n        scratchMatrix(row, col) = value;\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\nvoid\nPeridigmNS::CorrespondenceMaterial::computeJacobianFiniteDifference(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\n  \n  // The mechanics 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  PeridigmNS::DegreesOfFreedomManager& dofManager = PeridigmNS::DegreesOfFreedomManager::self();\n  bool solveForDisplacement = dofManager.displacementTreatedAsUnknown();\n  //bool solveForTemperature = dofManager.temperatureTreatedAsUnknown();\n  int numDof = dofManager.totalNumberOfDegreesOfFreedom();\n  int numDisplacementDof = dofManager.numberOfDisplacementDegreesOfFreedom();\n  //int numTemperatureDof = dofManager.numberOfTemperatureDegreesOfFreedom();\n  int displacementDofOffset = dofManager.displacementDofOffset();\n  //int temperatureDofOffset = dofManager.temperatureDofOffset();\n\n  // Get field ids for all relevant data\n  PeridigmNS::FieldManager& fieldManager = PeridigmNS::FieldManager::self();\n  int volumeFId(-1), coordinatesFId(-1), velocityFId(-1), forceDensityFId(-1); //, temperatureFId(-1), fluxDivergenceFId(-1);\n  volumeFId = fieldManager.getFieldId(\"Volume\");\n  if (solveForDisplacement) {\n    coordinatesFId = fieldManager.getFieldId(\"Coordinates\");\n    velocityFId = fieldManager.getFieldId(\"Velocity\");\n    forceDensityFId = fieldManager.getFieldId(\"Force_Density\");\n  }\n  //if (solveForTemperature) {\n  //  temperatureFId = fieldManager.getFieldId(\"Temperature\");\n  //  fluxDivergenceFId = fieldManager.getFieldId(\"Flux_Divergence\");\n  //}\n\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.\n    double *volume, *y, *v, *force;//, *temperature, *fluxDivergence;\n    tempDataManager.getData(volumeFId, PeridigmField::STEP_NONE)->ExtractView(&volume);\n    if (solveForDisplacement) {\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    //if (solveForTemperature) {\n    //  tempDataManager.getData(temperatureFId, PeridigmField::STEP_NP1)->ExtractView(&temperature);\n    //  tempDataManager.getData(fluxDivergenceFId, PeridigmField::STEP_NP1)->ExtractView(&fluxDivergence);\n    //}\n\n    // Create a temporary vector for storing force and/or flux divergence.\n    Teuchos::RCP<Epetra_Vector> forceVector, tempForceVector, fluxDivergenceVector, tempFluxDivergenceVector;\n    double *tempForce, *tempFluxDivergence;\n    if (solveForDisplacement) {\n      forceVector = tempDataManager.getData(forceDensityFId, PeridigmField::STEP_NP1);\n      tempForceVector = Teuchos::rcp(new Epetra_Vector(*forceVector));\n      tempForceVector->ExtractView(&tempForce);\n    }\n    //if (solveForTemperature) {\n    //  fluxDivergenceVector = tempDataManager.getData(fluxDivergenceFId, PeridigmField::STEP_NP1);\n    //  tempFluxDivergenceVector = Teuchos::rcp(new Epetra_Vector(*fluxDivergenceVector));\n    //  tempFluxDivergenceVector->ExtractView(&tempFluxDivergence);\n    //}\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() < numDof*(numNeighbors+1))\n      scratchMatrix.Resize(numDof*(numNeighbors+1));\n\n    // Create a list of global indices for the rows/columns in the scratch matrix.\n    vector<int> globalIndices(numDof*(numNeighbors+1));\n    for(int i=0 ; i<numNeighbors+1 ; ++i){\n      int globalID = tempOneDimensionalMap->GID(i);\n      for(int j=0 ; j<numDof ; ++j){\n        globalIndices[numDof*i+j] = numDof*globalID+j;\n      }\n    }\n\n    if(finiteDifferenceScheme == FORWARD_DIFFERENCE){\n      if (solveForDisplacement) {\n        // Compute and store the unperturbed force.\n        computeForce(dt, tempNumOwnedPoints, &tempOwnedIDs[0], &tempNeighborhoodList[0], tempDataManager);\n        \n        \n        \n        for(int i=0 ; i<forceVector->MyLength() ; ++i)\n          tempForce[i] = force[i];\n      }\n      //if (solveForTemperature) {\n      //  // Compute and store the unperturbed flux divergence.\n      //  computeFluxDivergence(dt, tempNumOwnedPoints, &tempOwnedIDs[0], &tempNeighborhoodList[0], tempDataManager);\n      //  for(int i=0 ; i<fluxDivergenceVector->MyLength() ; ++i)\n      //    tempFluxDivergence[i] = fluxDivergence[i];\n      //}\n    }\n\n    // Perturb one dof in the neighborhood at a time and compute the force and/or flux divergence.\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      // Displacement degrees of freedom\n      for(int dof=0 ; dof<numDisplacementDof ; ++dof){\n\n        // Perturb a dof and compute the forces.\n        double oldY = y[numDof*perturbID+dof];\n        double oldV = v[numDof*perturbID+dof];\n\n        if(finiteDifferenceScheme == CENTRAL_DIFFERENCE){\n          // Compute and store the negatively perturbed force.\n          y[numDof*perturbID+dof] -= epsilon;\n          v[numDof*perturbID+dof] -= epsilon/dt;\n          computeForce(dt, tempNumOwnedPoints, &tempOwnedIDs[0], &tempNeighborhoodList[0], tempDataManager);\n          y[numDof*perturbID+dof] = oldY;\n          v[numDof*perturbID+dof] = oldV;\n          for(int i=0 ; i<forceVector->MyLength() ; ++i)\n            tempForce[i] = force[i];\n        }\n\n        // Compute the purturbed force.\n        y[numDof*perturbID+dof] += epsilon;\n        v[numDof*perturbID+dof] += epsilon/dt;\n        computeForce(dt, tempNumOwnedPoints, &tempOwnedIDs[0], &tempNeighborhoodList[0], tempDataManager);\n        y[numDof*perturbID+dof] = oldY;\n        v[numDof*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<numDof ; ++d){\n            double value = ( force[numDof*forceID+d] - tempForce[numDof*forceID+d] ) / epsilon;\n            if(finiteDifferenceScheme == CENTRAL_DIFFERENCE)\n              value *= 0.5;\n            scratchMatrix(numDof*forceID + displacementDofOffset + d, numDof*perturbID + displacementDofOffset + dof) = value;\n          }\n        }\n      }\n\n      // Temperature degrees of freedom\n    //if(solveForTemperature){\n    //\n    //  // Perturb a temperature value and compute the flux divergence.\n    //  double oldTemperature = temperature[perturbID];\n    //\n    //  if(finiteDifferenceScheme == CENTRAL_DIFFERENCE){\n    //    // Compute and store the negatively perturbed flux divergence.\n    //    temperature[perturbID] -= epsilon;\n    //    computeFluxDivergence(dt, tempNumOwnedPoints, &tempOwnedIDs[0], &tempNeighborhoodList[0], tempDataManager);\n    //    temperature[perturbID] = oldTemperature;\n    //    for(int i=0 ; i<fluxDivergenceVector->MyLength() ; ++i)\n    //      tempFluxDivergence[i] = fluxDivergence[i];\n    //  }\n    //\n    //// Compute the purturbed flux divergence.\n    //  temperature[perturbID] += epsilon;\n    //  computeFluxDivergence(dt, tempNumOwnedPoints, &tempOwnedIDs[0], &tempNeighborhoodList[0], tempDataManager);\n    //  temperature[perturbID] = oldTemperature;\n    //\n    //  for(int i=0 ; i<numNeighbors+1 ; ++i){\n    //    int fluxDivergenceID;\n    //    if(i < numNeighbors)\n    //      fluxDivergenceID = tempNeighborhoodList[i+1];\n    //    else\n    //      fluxDivergenceID = 0;\n    //\n    //    double value = ( fluxDivergence[fluxDivergenceID] - tempFluxDivergence[fluxDivergenceID] ) / epsilon;\n    //    if(finiteDifferenceScheme == CENTRAL_DIFFERENCE)\n    //      value *= 0.5;\n    //    scratchMatrix(numDof*fluxDivergenceID + temperatureDofOffset, numDof*perturbID + temperatureDofOffset) = value;\n    //}\n    //}\n    }\n\n    // Multiply by nodal volume\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/numDof];\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(!std::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", "meta": {"hexsha": "9458630da2b11d19fc1d798bf78211c5bd23bc21", "size": 62916, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Peridigm/Code/Anisotropic_Material/materials/Peridigm_CorrespondenceMaterial.cpp", "max_stars_repo_name": "oldninja/PeriDoX", "max_stars_repo_head_hexsha": "f31bccc7b8ea60cd814d00732aebdbbe876a2ac7", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Peridigm/Code/Anisotropic_Material/materials/Peridigm_CorrespondenceMaterial.cpp", "max_issues_repo_name": "oldninja/PeriDoX", "max_issues_repo_head_hexsha": "f31bccc7b8ea60cd814d00732aebdbbe876a2ac7", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Peridigm/Code/Anisotropic_Material/materials/Peridigm_CorrespondenceMaterial.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": 54.4727272727, "max_line_length": 203, "alphanum_fraction": 0.5947453748, "num_tokens": 15580, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7490872243177518, "lm_q2_score": 0.46101677931231594, "lm_q1q2_score": 0.3453417795789723}}
{"text": "#include <iostream>\n#include <boost/python.hpp>\n#include <map>\n#include <string>\n#include <exception>\n#include <stdexcept>\n#include \"pyutil.hpp\"\n\nusing namespace std;\nusing namespace boost::python;\n\nstruct Vec4d\n{\n  double values[4];\n\n  Vec4d()\n  {\n    for(int iter = 0; iter < 4; ++iter)\n      values[iter] = 0;\n  }\n\n  double dist(const Vec4d&o) const\n  {\n    double ssd = 0;\n    for(int iter = 0; iter < 4; ++iter)\n    {\n      double diff = (values[iter] - o.values[iter]);\n      ssd += diff * diff;\n    }\n    return ssd;\n  }\n};\n\nstd::ostream& operator<<(ostream&os, const Vec4d&o) \n{\n  os << \"[\" << o.values[0] << \", \" << o.values[1] << \", \" << o.values[2] << \", \" << o.values[3] << \"] \";\n  return os;\n}\n\n#include \"eval_ik.cpp\"\n\nbool strhas(const string&str,const string&has)\n{\n  return str.find(has) != std::string::npos;\n}\n\nclass IK\n{\npublic:\n  map<string,double> null_solution;\n  map<string,double> regularizers;\n  float step_size;\n  \n  IK()\n  {\n  }\n  \n  double objective_cost(map<string,Vec4d>&target_positions,map<string,double>&solution)\n  {\n    // compute target component\n    double ssd = 0;\n    for(auto && targ : target_positions)\n    {\n      Vec4d cur = joint_position(targ.first,solution);\n      ssd += cur.dist(targ.second);\n    }\n\n    // compute the reguarizer cost.\n    for(auto && param : solution)\n    {\n      auto null_value = null_solution.find(param.first);\n      if(null_value != null_solution.end())\n      {\n\tdouble C = regularizers[param.first];\n\tdouble diff = null_value->second - param.second;\n\tssd += C * diff * diff;\n      }\n    }\n    \n    return ssd;\n  }\n\n  map<string,double> perturb_solution_random(const map<string,double>&solution)\n  {\n    map<string,double> sol_prime = solution;\n    static std::default_random_engine generator;\n    static std::normal_distribution<double> distribution(0,1.0);\n\n    int param_id = rand() % sol_prime.size();\n    int iter =0;\n    for(auto && param : sol_prime)\n    {\n      if(iter == param_id)\n\tparam.second += distribution(generator);\n      ++iter;\n    }\n    \n    return sol_prime;\n  }\n\n  map<string,double> perturb_solution_gradient(map<string,Vec4d>&targets,map<string,double>&solution)\n  {\n    map<string,double> sp;\n    \n    for(auto && param : solution)\n    {        \n      // data gradient\n      double grad = 0;\n      for(auto && target : targets)\n      {\n\tVec4d cur_pos = joint_position(target.first,solution);\n\tfor(int i = 0; i < 4; ++i)\n\t{\n\t  grad += 2 * (cur_pos.values[i] - target.second.values[i]) * diff(target.first,param.first,i,solution);\n\t}\n      }\n      \n      // regularizer gradient\n      auto null_value = null_solution.at(param.first);\t\n      double C = regularizers.at(param.first);\n      double diff = null_value - param.second;\n      grad += C * -2 * diff;\n\n      // update\n      sp[param.first] = param.second - step_size*grad;\n    }\n\n    return sp;\n  }\n\n  map<string,double> perturb_solution(map<string,Vec4d>&target,map<string,double>&solution)\n  {\n    static long ctr = 0;\n    ctr++;\n    if(ctr % 500 == 0)\n      return perturb_solution_gradient(target,solution);\n    else\n      return perturb_solution_random(solution);\n  }  \n\n  void print_match(map<string,Vec4d>&target_positions,map<string,double>&solution)\n  {\n    for(auto && targ : target_positions)\n    {\n      Vec4d cur = joint_position(targ.first,solution);\n      cout << targ.first << targ.second << \" vs \" << cur << endl;\n    }\n  }\n\n  map<string,double> extract_solution(boost::python::dict pySol)\n  {\n    boost::python::list sol_keys = pySol.keys();\n    map<string,double> sol;\n    for(int iter = 0; iter < len(sol_keys); ++iter)\n    {\n      boost::python::extract<std::string> key(sol_keys[iter]);\n      boost::python::extract<double> value(pySol[sol_keys[iter]]);\n      sol[key] = value;\n    }\n    return sol;\n  }\n\n  map<string,Vec4d> extract_targets(boost::python::dict target_positions)\n  {\n    boost::python::list target_keys = target_positions.keys();\n    map<string,Vec4d> target;\n    for( int iter = 0; iter < len(target_keys); ++iter)\n    {\n      boost::python::extract<std::string> key(target_keys[iter]);\n      boost::python::list value = boost::python::extract<boost::python::list>(target_positions[target_keys[iter]]);\n      Vec4d v;\n      assert(len(value) == 4);\n      for(int jter = 0; jter < len(value); ++jter)\n\tv.values[jter] = boost::python::extract<double>(value[jter]);\n      target[key] = v;\n    }\n    return target;\n  }\n  \n  void set_null_solution(boost::python::dict null_solution)\n  {\n    // convert init solution\n    this->null_solution = extract_solution(null_solution);\n  }\n\n  void set_regularizers(boost::python::dict py_reguarizers)\n  {\n    // convert init solution\n    this->regularizers = extract_solution(py_reguarizers);\n  }  \n\n  void optimize(map<string,Vec4d>&target,map<string,double>&sol)\n  {\n    ScopedGILRelease unlock;\n    \n    double start_cost = objective_cost(target,sol);\n    double best_cost = start_cost;\n    cout << \"init cost = \" << best_cost << endl;\n    int max_iter = 1000;\n    for(int iter = 0; iter < max_iter; ++iter)\n    {\n      auto sol_prime = perturb_solution(target,sol);\n      double cost_prime = objective_cost(target,sol_prime);\n      if(cost_prime < best_cost)\n      {\n\tcout << \"ACCEPT: \" << best_cost << \" => \" << cost_prime << endl;\n\tsol = sol_prime;\n\tbest_cost = cost_prime;\n      }\n      else if(iter % 100 == 0)\n      {\n\tcout << \"REJECT: \" << best_cost << \" => \" << cost_prime << endl;\n      }\n\n      if(iter % 1000 == 0)\n      {\n\tcout << \"iter \" << iter << \" of \" << 50000 << endl;\n      }\n    }\n    \n    print_match(target,sol);\n    cout << \"init cost = \" << start_cost << endl;    \n    cout << \"final cost = \" << objective_cost(target,sol) << endl;\n  }\n  \n  boost::python::dict solve(boost::python::dict target_positions,boost::python::dict init_solution)\n  {   \n    // convert arguments\n    map<string,Vec4d> target = extract_targets(target_positions);\n\n    // convert init solution\n    map<string,double> sol = extract_solution(init_solution);\n\n    // OPTIMIZE THE DAMN THING!!!\n    {      \n      optimize(target,sol);\n    }\n    \n    // convert to output\n    boost::python::dict dictionary;\n    for(auto && param : sol)\n    {\n      dictionary[param.first] = param.second;\n    }\n    return dictionary;\n  }\n\n  void set_grad_step_size(float s)\n  {\n    step_size = s;\n  }\n};\n\nBOOST_PYTHON_MODULE(iksolver)\n{\n  class_<IK>(\"iksolver\", init<>())\n    .def(init<>())\n    .def(\"solve\", &IK::solve)\n    .def(\"set_null_solution\",&IK::set_null_solution)\n    .def(\"set_regularizers\",&IK::set_regularizers)\n    .def(\"set_grad_step_size\",&IK::set_grad_step_size);\n}\n", "meta": {"hexsha": "2eae4dc011c66fc0de42106c07961c078f8a99ef", "size": 6586, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "pyhand/iksolver.cpp", "max_stars_repo_name": "LuciaXu/libhand_generate", "max_stars_repo_head_hexsha": "ed3eda62c91e4eafbac09c4d78a298d6a764140a", "max_stars_repo_licenses": ["CC-BY-3.0"], "max_stars_count": 19.0, "max_stars_repo_stars_event_min_datetime": "2015-11-28T03:49:10.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-12T13:19:26.000Z", "max_issues_repo_path": "pyhand/iksolver.cpp", "max_issues_repo_name": "LuciaXu/libhand_generate", "max_issues_repo_head_hexsha": "ed3eda62c91e4eafbac09c4d78a298d6a764140a", "max_issues_repo_licenses": ["CC-BY-3.0"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2015-12-24T08:53:10.000Z", "max_issues_repo_issues_event_max_datetime": "2017-11-08T10:58:16.000Z", "max_forks_repo_path": "pyhand/iksolver.cpp", "max_forks_repo_name": "jsupancic/libhand-public", "max_forks_repo_head_hexsha": "da9b92fa5440d06fdd4ba72c2327c50c88a1d469", "max_forks_repo_licenses": ["CC-BY-3.0"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2015-12-16T05:27:22.000Z", "max_forks_repo_forks_event_max_datetime": "2020-08-24T07:59:29.000Z", "avg_line_length": 25.0418250951, "max_line_length": 115, "alphanum_fraction": 0.6178256909, "num_tokens": 1741, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6548947425132315, "lm_q2_score": 0.5273165233795671, "lm_q1q2_score": 0.3453368188016341}}
{"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: ructest.cc,v $\n//       Version: $Revision: 1.1 $  Dated: $Date: 2010-05-20 21:21:04 $\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 = 45.2931;\n  double ruclo1 = -97.588;\n  double ruclatin1 = 25.0;\n  double ruclatin2 = 25.0;\n  double rucdx = 13545.087;\n  double rucdy = 13545.087;\n  int rucnx = 5;\n  int rucny = 4;\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\n  double la2 = 45.6415;\n  double lo2 = -96.9482;\n\n  rucLambertProj.ll2xy(lo2, la2, &xc, &yc);\n  printf(\"xc, yc for lo2, la2: %g %g\\n\", xc, yc);\n  rucLambertProj.xy2ll(0, 0, &lon, &lat);\n  printf(\"lon, lat for origin: %g %g\\n\", lon, lat);\n\n  rucLambertProj.xy2ll(4, 3, &lon, &lat);\n  printf(\"lon, lat for 4,3: %g %g\\n\", lon, lat);\n\n  double la3 = 45.5245;\n  double lo3 = -97.27;\n  rucLambertProj.ll2xy(lo3, la3, &xc, &yc);\n  printf(\"xc, yc for lo3, la3: %g %g\\n\", xc, yc);\n}\n\n\n", "meta": {"hexsha": "e8dadfe38db75ab45083af548e4dbf70c5915b07", "size": 2165, "ext": "cc", "lang": "C++", "max_stars_repo_path": "libs/Proj4Wrap/src/Proj4Wrap/ructest.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/ructest.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/ructest.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": 26.7283950617, "max_line_length": 151, "alphanum_fraction": 0.6023094688, "num_tokens": 753, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6548947290421275, "lm_q2_score": 0.5273165233795671, "lm_q1q2_score": 0.3453368116980983}}
{"text": "/*\n * Copyright (c) 2010-2013 Steffen Kieß\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 MATH_VECTOR2_HPP_INCLUDED\n#define MATH_VECTOR2_HPP_INCLUDED\n\n#include <Core/Util.hpp>\n#include <Core/Assert.hpp>\n\n#include <Math/Forward.hpp>\n#include <Math/Abs.hpp>\n\n#include <complex>\n\n#include <boost/type_traits/is_convertible.hpp>\n#include <boost/type_traits/alignment_of.hpp>\n#include <boost/utility/enable_if.hpp>\n\n//#define VECTOR2_USE_ARRAY\n\nnamespace Math {\n  template <typename T> class\n  Vector2 {\n#ifdef VECTOR2_USE_ARRAY\n    T data_[2];\n#else\n    T x_, y_;\n#endif\n\n    class PrivateType {\n      friend class Vector2;\n      NVCC_HOST_DEVICE PrivateType () {}\n    };\n\n  public:\n    NVCC_HOST_DEVICE Vector2 () {}\n#if !defined (__CUDACC__)\n#if defined (__clang__) || GCC_VERSION_IS_ATLEAST(4, 6)\n#pragma GCC diagnostic push\n#endif\n#pragma GCC diagnostic ignored \"-Wconversion\"\n#pragma GCC diagnostic ignored \"-Wfloat-conversion\"\n#endif\n#ifdef VECTOR2_USE_ARRAY\n    //NVCC_HOST_DEVICE explicit Vector2 (T v) { data_[0] = v; data_[1] = v }\n    NVCC_HOST_DEVICE Vector2 (T x, T y) { data_[0] = x; data_[1] = y; }\n    template <typename U> NVCC_HOST_DEVICE Vector2 (Vector2<U> v, UNUSED typename boost::enable_if<boost::is_convertible<U, T>, PrivateType>::type dummy = PrivateType ()) { data_[0] = v.x (); data_[1] = v.y (); }\n    template <typename U> NVCC_HOST_DEVICE explicit Vector2 (Vector2<U> v, UNUSED typename boost::disable_if<boost::is_convertible<U, T>, PrivateType>::type dummy = PrivateType ()) { data_[0] = (T) v.x (); data_[1] = (T) v.y (); }\n#else\n    //NVCC_HOST_DEVICE explicit Vector2 (T v) : x_ (v), y_ (v) {}\n    NVCC_HOST_DEVICE Vector2 (T x, T y) : x_ (x), y_ (y) {}\n    template <typename U> NVCC_HOST_DEVICE Vector2 (Vector2<U> v, UNUSED typename boost::enable_if<boost::is_convertible<U, T>, PrivateType>::type dummy = PrivateType ()) : x_ (v.x ()), y_ (v.y ()) {}\n    template <typename U> NVCC_HOST_DEVICE explicit Vector2 (Vector2<U> v, UNUSED typename boost::disable_if<boost::is_convertible<U, T>, PrivateType>::type dummy = PrivateType ()) : x_ (v.x ()), y_ (v.y ()) {}\n#endif\n#if !defined (__CUDACC__)\n#if defined (__clang__) || GCC_VERSION_IS_ATLEAST(4, 6)\n#pragma GCC diagnostic pop\n#endif\n#endif\n\n    NVCC_HOST_DEVICE const T& x () const {\n#ifdef VECTOR2_USE_ARRAY\n      return data_[0];\n#else\n      return x_;\n#endif\n    }\n\n    NVCC_HOST_DEVICE const T& y () const {\n#ifdef VECTOR2_USE_ARRAY\n      return data_[1];\n#else\n      return y_;\n#endif\n    }\n\n    NVCC_HOST_DEVICE T& x () {\n#ifdef VECTOR2_USE_ARRAY\n      return data_[0];\n#else\n      return x_;\n#endif\n    }\n\n    NVCC_HOST_DEVICE T& y () {\n#ifdef VECTOR2_USE_ARRAY\n      return data_[1];\n#else\n      return y_;\n#endif\n    }\n\n    NVCC_HOST_DEVICE const T& operator[] (size_t i) const {\n#ifdef VECTOR2_USE_ARRAY\n      ASSERT (i >= 0 && i < 2);\n      return data_[i];\n#else\n      if (i == 0)\n        return x_;\n      else if (i == 1)\n        return y_;\n      else\n        ABORT ();\n#endif\n    }\n\n    NVCC_HOST_DEVICE T& operator[] (size_t i) {\n#ifdef VECTOR2_USE_ARRAY\n      ASSERT (i >= 0 && i < 2);\n      return data_[i];\n#else\n      if (i == 0)\n        return x_;\n      else if (i == 1)\n        return y_;\n      else\n        ABORT ();\n#endif\n    }\n  };\n\n  // Operations on Vector2\n\n#define RTS(op) DECLTYPE ((*(T*)NULL) op (*(U*)NULL))\n#define RT(op) Vector2<RTS(op)>\n#ifdef __CUDACC__ // Workaround BugPlayground/nvcc-5.0-templates-1.cu\n  template <typename T> static ERROR_ATTRIBUTE (\"should not be called\") Vector2<T> helperGetVector2Type (T t);\n#define RT2(op) DECLTYPE (helperGetVector2Type ((*(T*)NULL) op (*(U*)NULL)))\n#define RETURN_RT(op) typedef RT2(op) Ty; return Ty\n#else\n#define RETURN_RT(op) return RT(op)\n#endif\n  template <typename T, typename U> NVCC_HOST_DEVICE inline RT(+) operator+ (Vector2<T> v1, Vector2<U> v2) {\n    RETURN_RT(+) (v1.x () + v2.x (), v1.y () + v2.y ());\n  }\n\n  template <typename T, typename U> NVCC_HOST_DEVICE inline Vector2<T>& operator+= (Vector2<T>& v1, Vector2<U> v2) {\n    v1.x () += v2.x (); v1.y () += v2.y ();\n    return v1;\n  }\n\n\n  template <typename T, typename U> NVCC_HOST_DEVICE inline RT(-) operator- (Vector2<T> v1, Vector2<U> v2) {\n    RETURN_RT(-) (v1.x () - v2.x (), v1.y () - v2.y ());\n  }\n\n  template <typename T, typename U> NVCC_HOST_DEVICE inline Vector2<T>& operator-= (Vector2<T>& v1, Vector2<U> v2) {\n    v1.x () -= v2.x (); v1.y () -= v2.y ();\n    return v1;\n  }\n\n\n  template <typename T, typename U> NVCC_HOST_DEVICE inline RT(*) operator* (Vector2<T> v, U scalar) {\n    RETURN_RT(*) (v.x () * scalar, v.y () * scalar);\n  }\n\n  template <typename T, typename U> NVCC_HOST_DEVICE inline RT(*) operator* (T scalar, Vector2<U> v) {\n    RETURN_RT(*) (scalar * v.x (), scalar * v.y ());\n  }\n\n  template <typename T, typename U> NVCC_HOST_DEVICE inline Vector2<T>& operator*= (Vector2<T>& v, U scalar) {\n    v.x () *= scalar; v.y () *= scalar;\n    return v;\n  }\n\n  template <typename T, typename U> NVCC_HOST_DEVICE inline RT(/) operator/ (Vector2<T> v, U scalar) {\n    RETURN_RT(/) (v.x () / scalar, v.y () / scalar);\n  }\n\n  template <typename T, typename U> NVCC_HOST_DEVICE inline Vector2<T>& operator/= (Vector2<T>& v, U scalar) {\n    v.x () /= scalar; v.y () /= scalar;\n    return v;\n  }\n\n  template <typename T> NVCC_HOST_DEVICE inline bool operator== (Vector2<T> v1, Vector2<T> v2) {\n    return v1.x () == v2.x () && v1.y () == v2.y ();\n  }\n  template <typename T> NVCC_HOST_DEVICE inline bool operator!= (Vector2<T> v1, Vector2<T> v2) {\n    return !(v1 == v2);\n  }\n\n  template <typename T> struct Abs2Impl<Vector2<T> > {\n    static DECLTYPE(Math::abs2 (*(T*)0)) apply (Vector2<T> v) {\n      return Math::abs2 (v.x ()) + Math::abs2 (v.y ());\n    }\n  };\n\n  // dot product\n  template <typename T, typename U> NVCC_HOST_DEVICE inline RTS(*) operator* (Vector2<T> v1, Vector2<U> v2) {\n    return v1.x () * v2.x () + v1.y () * v2.y ();\n  }\n\n#undef RTS\n#undef RT\n#ifdef __CUDACC__ // Workaround BugPlayground/nvcc-5.0-templates-1.cu\n#undef RT2\n#undef RETURN_RT\n#endif\n\n  // Unary +/-\n  template <typename T> NVCC_HOST_DEVICE inline Vector2<T> operator+ (Vector2<T> v) {\n    return Vector2<T> (+v.x (), +v.y ());\n  }\n  template <typename T> NVCC_HOST_DEVICE inline Vector2<T> operator- (Vector2<T> v) {\n    return Vector2<T> (-v.x (), -v.y ());\n  }\n\n  template <typename F> Vector2<F> inline real (Vector2<std::complex<F> > v) {\n    return Vector2<F> (real (v.x ()), real (v.y ()));\n  }\n\n  template <typename F> Vector2<F> inline imag (Vector2<std::complex<F> > v) {\n    return Vector2<F> (imag (v.x ()), imag (v.y ()));\n  }\n\n  template <typename F> Vector2<std::complex<F> > inline conj (Vector2<std::complex<F> > v) {\n    return Vector2<std::complex<F> > (conj (v.x ()), conj (v.y ()));\n  }\n}\n\n#endif // !MATH_VECTOR2_HPP_INCLUDED\n", "meta": {"hexsha": "4c961b62f439262c4b18aac67e7eb39f7aea9333", "size": 7831, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/PluginHDF5/Math/Vector2.hpp", "max_stars_repo_name": "voxie-viewer/voxie", "max_stars_repo_head_hexsha": "d2b5e6760519782e9ef2e51f5322a3baa0cb1198", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2016-06-03T18:41:43.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-17T20:28:58.000Z", "max_issues_repo_path": "src/PluginHDF5/Math/Vector2.hpp", "max_issues_repo_name": "voxie-viewer/voxie", "max_issues_repo_head_hexsha": "d2b5e6760519782e9ef2e51f5322a3baa0cb1198", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/PluginHDF5/Math/Vector2.hpp", "max_forks_repo_name": "voxie-viewer/voxie", "max_forks_repo_head_hexsha": "d2b5e6760519782e9ef2e51f5322a3baa0cb1198", "max_forks_repo_licenses": ["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.4937759336, "max_line_length": 230, "alphanum_fraction": 0.6499808454, "num_tokens": 2276, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.640635854839898, "lm_q2_score": 0.5389832206876841, "lm_q1q2_score": 0.34529197632961595}}
{"text": "#include \"VelocityFilter.h\"\n#include <iostream>\n#include <fstream>\n#include <vector>\n#include \"Distance.h\"\n#include <Eigen/Core>\n#include \"CTCD.h\"\n\nusing namespace std;\nusing namespace Eigen;\n\nstatic void writeMesh(const char *filename, const VectorXd &verts, const Matrix3Xi &faces)\n{\n\tofstream ofs(filename);\n\n\tfor(int i=0; i<verts.size()/3; i++)\n\t{\n\t\tofs << \"v \";\n\t\tfor(int j=0; j<3; j++)\n\t\t\tofs << verts[3*i+j] << \" \";\n\t\tofs << endl;\n\t}\n\n\tfor(int i=0; i<faces.cols(); i++)\n\t{\n\t\tofs << \"f \";\n\t\tfor(int j=0; j<3; j++)\n\t\t\tofs << faces.coeff(j, i)+1 << \" \";\n\t\tofs << endl;\n\t}\n}\n\nvoid loadMesh(const char *filename, VectorXd &verts, Matrix3Xi &faces)\n{\n\tifstream ifs(filename);\n\tif(!ifs)\n\t\treturn;\n\n\tvector<double> pos;\n\tvector<int> faceidx;\n\n\twhile(true)\n\t{\n\t\tchar c;\n\t\tifs >> c;\n\t\tif(!ifs)\n\t\t\tbreak;\n\t\tif(c == 'v')\n\t\t{\n\t\t\tfor(int i=0; i<3; i++)\n\t\t\t{\n\t\t\t\tdouble p;\n\t\t\t\tifs >> p;\n\t\t\t\tpos.push_back(p);\n\t\t\t}\n\t\t}\n\t\tif(c == 'f')\n\t\t{\n\t\t\tfor(int i=0; i<3; i++)\n\t\t\t{\n\t\t\t\tint vert;\n\t\t\t\tifs >> vert;\n\t\t\t\tfaceidx.push_back(vert);\n\t\t\t}\n\t\t}\n\t}\n\n\tint nverts = pos.size()/3;\n\tint nfaces = faceidx.size()/3;\n\n\tverts.resize(3*nverts);\n\tfor(int i=0; i<3*nverts; i++)\n\t\tverts[i] = pos[i];\n\t\n\tfaces.resize(3, nfaces);\n\tfor(int i=0; i<nfaces; i++)\n\t\tfor(int j=0; j<3; j++)\n\t\t\tfaces.coeffRef(j, i) = faceidx[3*i+j]-1;\n}\n\ndouble displaceInward(const VectorXd &q, const Matrix3Xi &f, const Matrix3Xd &vertNormals, double maxDisplacement, VectorXd &displacedq)\n{\n\tint nverts = q.size()/3;\n\tint nfaces = f.cols();\n\tdisplacedq = q;\n\tdouble displacement = maxDisplacement;\n\n\tfor(int i=0; i<nverts; i++)\n\t{\n\t\tVector3d pos = q.segment<3>(3*i);\n\t\tVector3d normal = vertNormals.col(i);\n\t\tVector3d endpos = pos - maxDisplacement*normal;\n\n\t\t// vertex-face\n\n\t\tfor(int j=0; j<nfaces; j++)\n\t\t{\n\t\t\tbool skip = false;\n\t\t\tfor(int k=0; k<3; k++)\n\t\t\t\tif(f.col(j)[k] == i)\n\t\t\t\t\tskip = true;\n\n\t\t\tif(skip)\n\t\t\t\tcontinue;\n\n\t\t\tdouble t;\n\t\t\tif(CTCD::vertexFaceCTCD(pos, \n\t\t\t\t\tq.segment<3>(3*f.col(j)[0]), \n\t\t\t\t\tq.segment<3>(3*f.col(j)[1]), \n\t\t\t\t\tq.segment<3>(3*f.col(j)[2]),\n\t\t\t\t\tendpos,\t\t\t\t\t\n\t\t\t\t\tq.segment<3>(3*f.col(j)[0]), \n\t\t\t\t\tq.segment<3>(3*f.col(j)[1]), \n\t\t\t\t\tq.segment<3>(3*f.col(j)[2]),\n\t\t\t\t\t1e-8, t))\n\t\t\t{\n\t\t\t\tdisplacement = min(displacement, maxDisplacement*t/2);\n\t\t\t}\n\t\t}\n\t\t// edge-edge\n\n\t\tfor(int j=0; j<nfaces; j++)\n\t\t{\n\t\t\tfor(int k=0; k<3; k++)\n\t\t\t{\n\t\t\t\tif(f.col(j)[k] == i)\n\t\t\t\t{\n\t\t\t\t\tint vert2 = f.col(j)[(k+1)%3];\n\t\t\t\t\tVector3d pos2 = q.segment<3>(3*vert2);\n\t\t\t\t\tVector3d endpos2 = pos2 - maxDisplacement*vertNormals.col(vert2);\n\t\t\t\t\tfor(int j2=0; j2<nfaces; j2++)\n\t\t\t\t\t{\n\t\t\t\t\t\tfor(int k2=0; k2<3; k2++)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tif(f.col(j2)[k2] == i || f.col(j2)[(k2+1)%3] == i)\n\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\tif(f.col(j2)[k2] == vert2 || f.col(j2)[(k2+1)%3] == vert2)\n\t\t\t\t\t\t\t\tcontinue;\n\n\t\t\t\t\t\t\tdouble t;\n\t\t\t\t\t\t\tif(CTCD::edgeEdgeCTCD(pos, pos2,\n\t\t\t\t\t\t\t\tq.segment<3>(3*f.col(j2)[k2]),\n\t\t\t\t\t\t\t\tq.segment<3>(3*f.col(j2)[(k2+1)%3]),\n\t\t\t\t\t\t\t\tendpos, endpos2,\n\t\t\t\t\t\t\t\tq.segment<3>(3*f.col(j2)[k2]),\n\t\t\t\t\t\t\t\tq.segment<3>(3*f.col(j2)[(k2+1)%3]),\n\t\t\t\t\t\t\t\t1e-8, t))\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tdisplacement = min(displacement, maxDisplacement*t/2);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\t\n\tfor(int i=0; i<nverts; i++)\n\t{\n\t\tdisplacedq.segment<3>(3*i) -= displacement*vertNormals.col(i);\n\t}\n\n\treturn displacement;\n}\n\nint main(int argc, char *argv[])\n{\n\tif(argc != 4)\n\t{\n\t\tstd::cerr << \"Usage: displaceInward (inputMesh) (outputMesh) (maxDisplacement)\" << std::endl;\n\t\treturn -1;\n\t}\n\tVectorXd q;\n\tMatrix3Xi f;\n\tloadMesh(argv[1], q, f);\n\tint numverts = q.size()/3;\n\tstd::cout << \"Loaded mesh with \" << numverts << \" vertices and \" << f.cols() << \" faces\" << std::endl;\n\n\tdouble maxdisp = strtod(argv[3], NULL);\n\n\tMatrix3Xd normals(3, numverts);\n\tnormals.setZero();\n\tfor(int face=0; face<f.cols(); face++)\n\t{\n\t\tVector3i verts = f.col(face);\n\t\tVector3d n = ( q.segment<3>(3*verts[1]) - q.segment<3>(3*verts[0]) ).cross( q.segment<3>(3*verts[2]) - q.segment<3>(3*verts[0]) );\n\t\tn /= n.norm();\n\n\t\tfor(int i=0; i<3; i++)\n\t\t{\n\t\t\tdouble sinangle = ( q.segment<3>(3*verts[(i+1)%3]) - q.segment<3>(3*verts[i]) ).cross( q.segment<3>(3*verts[(i+2)%3]) - q.segment<3>(3*verts[i]) ).norm();\n\t\t\tdouble cosangle = ( q.segment<3>(3*verts[(i+1)%3]) - q.segment<3>(3*verts[i]) ).dot( q.segment<3>(3*verts[(i+2)%3]) - q.segment<3>(3*verts[i]) );\n\t\t\tdouble angle = atan2(sinangle, cosangle);\n\t\t\tnormals.col(verts[i]) += angle*n;\n\t\t}\n\t}\t\n\tfor(int i=0; i<numverts; i++)\n\t\tnormals.col(i) /= normals.col(i).norm();\n\n\tVectorXd newq;\n\tdouble mindisp = displaceInward(q, f, normals, maxdisp, newq);\t\n\tstd::cout << \"Actual displacement was \" << mindisp << std::endl;\n\twriteMesh(argv[2], newq, f);\n}\n", "meta": {"hexsha": "4990b8420d15eb43518caa3437a3b805522faa74", "size": 4606, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "3rdparty/Floating-Point-Root-Finder/example/displaceInward.cpp", "max_stars_repo_name": "LamWS/ClothSimulation", "max_stars_repo_head_hexsha": "008b24fa96005cbe7ccae27a765d19e5f68a3ef2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2021-11-10T08:39:34.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-06T10:21:49.000Z", "max_issues_repo_path": "3rdparty/Floating-Point-Root-Finder/example/displaceInward.cpp", "max_issues_repo_name": "LamWS/ClothSimulation", "max_issues_repo_head_hexsha": "008b24fa96005cbe7ccae27a765d19e5f68a3ef2", "max_issues_repo_licenses": ["MIT"], "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/Floating-Point-Root-Finder/example/displaceInward.cpp", "max_forks_repo_name": "LamWS/ClothSimulation", "max_forks_repo_head_hexsha": "008b24fa96005cbe7ccae27a765d19e5f68a3ef2", "max_forks_repo_licenses": ["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.4682926829, "max_line_length": 157, "alphanum_fraction": 0.5618758142, "num_tokens": 1659, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6406358411176238, "lm_q2_score": 0.5389832206876841, "lm_q1q2_score": 0.34529196893354036}}
{"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 <iomanip>\n#include <boost/math/distributions/binomial.hpp>\n#include <boost/function.hpp>\n#include <Eigen/Core>\n#include \"genfile/Error.hpp\"\n#include \"components/HaplotypeFrequencyComponent/HaplotypeFrequencyComponent.hpp\"\n\n// #define DEBUG_HAPLOTYPE_FREQUENCY_LL 1\nHaplotypeFrequencyLogLikelihood::HaplotypeFrequencyLogLikelihood(\n\tMatrix const& genotype_table,\n\tMatrix const& haplotype_table\n):\n\tm_genotype_table( genotype_table ),\n\tm_haplotype_table( haplotype_table ),\n\tm_D_ll( 3 ),\n\tm_DDt_ll( 3, 3 )\n{\n\tif( m_genotype_table.array().maxCoeff() == 0 && m_haplotype_table.array().maxCoeff() == 0 ) {\n\t\tthrow genfile::BadArgumentError( \"HaplotypeFrequencyLogLikelihood::HaplotypeFrequencyLogLikelihood()\", \"genotype_table, haplotype_table\" ) ;\n\t}\n\t// store derivatives of elements of the parameters pi with respect to pi.\n\tm_dpi.push_back( std::vector< RowVector >( 2, RowVector::Zero( 3 ) )) ;\n\tm_dpi.push_back( std::vector< RowVector >( 2, RowVector::Zero( 3 ) )) ;\n\tm_dpi[0][0] = RowVector::Constant( 3, -1 ) ;\n\tm_dpi[0][1]( 0 ) = 1 ;\n\tm_dpi[1][0]( 1 ) = 1 ;\n\tm_dpi[1][1]( 2 ) = 1 ;\n}\n\nHaplotypeFrequencyLogLikelihood::Vector HaplotypeFrequencyLogLikelihood::get_MLE_by_EM() const {\n\t//\n\t// This method treats the number of individuals X in the G(1,1) cell\n\t// that have AB/ab genotypes as binomially distributed with some unknown\n\t// parameter p that must be estimated.  We pick a value of p and sum over\n\t// possible values of X to get a new estimate of the four parameters\n\t// pi00, pi01, pi10, pi11.  Then p is re-computed from the parameter values.\n\t//\n\t// We stop when the parameter estimate does not change, up to some tolerance.\n\t//\n\tMatrix const& G = m_genotype_table ;\n\tVector pi = estimate_parameters( 0.5 ) ;\n#if DEBUG_HAPLOTYPE_FREQUENCY_LL \n\tstd::cerr << std::resetiosflags( std::ios::floatfield ) << \"Maximising likelihood for genotypes:\\n\"\n\t\t<< m_genotype_table\n\t\t<< \"\\nand haplotypes:\\n\"\n\t\t<< m_haplotype_table\n\t\t<< \"\\n\" ;\n\tstd::cerr << \"pi = \" << pi(0) << \" \" << pi(1) << \" \" << pi(2) << \" \" << pi(3) << \" \" << \", p = 0.5.\\n\" ;\n#endif\n\tif( G(1,1) != 0.0 ) {\n\t\tVector old_pi ;\n\t\tstd::size_t count = 0 ;\n\t\tstd::size_t const max_count = 100000 ;\n\t\tdouble const tolerance = 0.0000001 ;\n\t\tdo {\n\t\t\told_pi = pi ;\n\n\t\t\tdouble p = ( pi(0) * pi( 3 ) ) ;\n\t\t\tif( p != 0 ) {\n\t\t\t\tp = p / ( p + ( pi( 1 ) * pi( 2 )) ) ;\n\t\t\t}\n\n\t\t\tpi = estimate_parameters( p ) ;\n#if DEBUG_HAPLOTYPE_FREQUENCY_LL \n\t\t\tstd::cerr << \"pi = \" << pi(0) << \" \" << pi(1) << \" \" << pi(2) << \" \" << pi(3) << \" \" << \", p = \" << p << \".\\n\" ;\n#endif\n\t\t}\n\t\twhile( ( pi - old_pi ).array().abs().maxCoeff() > tolerance && ++count < max_count ) ;\n\t\tif( count == max_count ) {\n\t\t\tthrow genfile::OperationFailedError(\n\t\t\t\t\"HaplotypeFrequencyLogLikelihood::maximise_by_EM()\",\n\t\t\t\t\"object of type HaplotypeFrequencyLogLikelihood\",\n\t\t\t\t\"convergence\"\n\t\t\t) ;\n\t\t}\n\t}\n\treturn pi.tail( 3 ) ;\n}\n\nHaplotypeFrequencyLogLikelihood::Vector HaplotypeFrequencyLogLikelihood::estimate_parameters(\n\tdouble const p\n) const {\n\tMatrix const& G = m_genotype_table ;\n\tMatrix const& H = m_haplotype_table ;\n\t\n\t// p is proportion of het / het genotypes\n\t// that are due to 00+11 haplotype combinations.\n\tdouble expected_00_11 = G( 1, 1 ) * p ;\n\tdouble expected_01_10 = G( 1, 1 ) - expected_00_11;\n\t\n\t// params are pi00 pi01 pi10 pi11\n\tVector result( 4 ) ;\n\tresult <<\n\t\tH(0,0) + G( 0, 1 ) + 2 * G( 0, 0 ) + G( 1, 0 ) + expected_00_11,\n\t\tH(0,1) + G( 0, 1 ) + 2 * G( 0, 2 ) + G( 1, 2 ) + expected_01_10,\n\t\tH(1,0) + G( 2, 1 ) + 2 * G( 2, 0 ) + G( 1, 0 ) + expected_01_10,\n\t\tH(1,1) + G( 1, 2 ) + 2 * G( 2, 2 ) + G( 2, 1 ) + expected_00_11\n\t;\n\tresult /= result.sum() ;\n\treturn result ;\n}\n\nvoid HaplotypeFrequencyLogLikelihood::evaluate_at( Vector const& pi ) {\n\tdouble const pi00 = 1.0 - pi.sum() ;\n\tdouble const& pi01 = pi(0) ;\n\tdouble const& pi10 = pi(1) ;\n\tdouble const& pi11 = pi(2) ;\n\t\n\tusing std::log ;\n\tdouble const lpi00 = log( pi00 ) ;\n\tdouble const lpi01 = log( pi01 ) ;\n\tdouble const lpi10 = log( pi10 ) ;\n\tdouble const lpi11 = log( pi11 ) ;\n\t\n\tdouble het_probability = pi00 * pi11 + pi01 * pi10 ;\n\n\tMatrix const& G = m_genotype_table ;\n\tMatrix const& H = m_haplotype_table ;\n\tMatrix VG( 3, 3 ) ;\n\tVG <<\n\t\t2.0 * lpi00,\t\tlpi00 + lpi01,\t\t\t\t2.0 * lpi01,\n\t\tlpi00 + lpi10,\t\tlog( het_probability ),\t\tlpi01 + lpi11,\n\t\t2.0 * lpi10,\t\tlpi10 + lpi11,\t\t\t\t2.0 * lpi11\n\t;\n\n\tMatrix VH( 2, 2 ) ;\n\tVG <<\n\t\tlpi00,\t\tlpi01,\n\t\tlpi10,\t\tlpi11\n\t;\n\n\t// cells with count 0 contribute 0 to the loglikelihood/\n\t// Since log(0) = -inf we have to handle this specially.\n\t// We do this by replacing these parameter entries with 0.\n\tVG = VG.array() * ( G.array() > 0.0 ).cast< double >() ;\n\tVH = VH.array() * ( H.array() > 0.0 ).cast< double >() ;\n\n\tm_ll = (\n\t\t(G.array() * VG.array())\n\t\t+ (H.array() * VH.array())\n\t).sum() ;\n}\ndouble HaplotypeFrequencyLogLikelihood::get_value_of_function() const {\n\treturn m_ll ;\n}\n\nHaplotypeFrequencyLogLikelihood::Vector HaplotypeFrequencyLogLikelihood::get_value_of_first_derivative() {\n\tassert(0) ;\n\treturn m_D_ll ;\n}\n\nHaplotypeFrequencyLogLikelihood::Matrix HaplotypeFrequencyLogLikelihood::get_value_of_second_derivative() {\n\tassert(0) ;\n\treturn m_DDt_ll ;\n}\n\n", "meta": {"hexsha": "07ed6d47fa75b287530691b4fe0e9b3c5a5f0a75", "size": 5360, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "components/HaplotypeFrequencyComponent/src/HaplotypeFrequencyLogLikelihood.cpp", "max_stars_repo_name": "CreRecombinase/qctool", "max_stars_repo_head_hexsha": "6dad3a15c461177bf6940ba7b991337402ca5c41", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2021-04-21T05:42:24.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-26T14:59:43.000Z", "max_issues_repo_path": "components/HaplotypeFrequencyComponent/src/HaplotypeFrequencyLogLikelihood.cpp", "max_issues_repo_name": "CreRecombinase/qctool", "max_issues_repo_head_hexsha": "6dad3a15c461177bf6940ba7b991337402ca5c41", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-04-09T16:11:04.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-10T11:18:56.000Z", "max_forks_repo_path": "components/HaplotypeFrequencyComponent/src/HaplotypeFrequencyLogLikelihood.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": 32.6829268293, "max_line_length": 142, "alphanum_fraction": 0.6509328358, "num_tokens": 1815, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7185943925708562, "lm_q2_score": 0.48047867804790706, "lm_q1q2_score": 0.34526928379508376}}
{"text": "/* Copyright 2017 The sfcpp Authors. All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n==============================================================================*/\n\n\n\n#pragma once\n\n#include <Eigen/Dense>\n\n#include <geo/ConvexPolytope.hpp>\n#include <math/AffineSubspace.hpp>\n#include <math/NatSet.hpp>\n\n#include <forward_list>\n#include <iostream>\n#include <queue>\n#include <stdexcept>\n#include <unordered_map>\n#include <unordered_set>\n#include <vector>\n\nnamespace sfcpp {\nnamespace geo {\n\ntemplate <typename... Args>\nstd::function<void(Args...)> getDummyFunction() {\n  return std::function<void(Args...)>([](Args...) {});\n}\n\nenum class FaceStatus { REMOVE, EXTEND, CONNECT, KEEP };\n\nstruct FaceInfo;\n\ntypedef FaceInfo *FaceInfoPtr;\n\nstatic const double QH_EPSILON =\n    1e-9;  // TODO: make relative instead of absolute\n\nstruct FaceInfo {\n  math::NatSet vertexSet;\n\n  std::unordered_set<FaceInfoPtr> parents;\n  std::unordered_set<FaceInfoPtr> children;\n  std::unordered_set<FaceInfoPtr> facesToConnect;\n\n  // number of facets this face is belonging to\n  uint32_t numAncestorFacets = 0;\n\n  // number of ancestor facets where the currently processed point is on the\n  // other side of the facet's hyperplane compared to the current polytope\n  uint32_t p = 0;\n\n  // number of ancestor facets where the currently processed point is inside the\n  // facet's hyperplane\n  uint32_t z = 0;\n\n  bool shouldRemove = false;\n\n  // for generation of Polytope\n  size_t polytopeIndex = 0;  // corresponding index in polytope.faces[d] vector\n\n  bool visited = false;\n\n  virtual ~FaceInfo() {}\n\n  FaceStatus getStatus() const {\n    uint32_t n = numAncestorFacets - p - z;\n    if (n > 0) {\n      if (p > 0) {\n        return FaceStatus::CONNECT;\n      } else {\n        return FaceStatus::KEEP;\n      }\n    } else {\n      if (p > 0) {\n        return FaceStatus::REMOVE;\n      } else {\n        return FaceStatus::EXTEND;\n      }\n    }\n  }\n\n  static std::function<void(FaceInfoPtr)> dummyFunction;\n\n  bool isVertex() const { return vertexSet.size() == 1; }\n};\n\nstruct FacetInfo : public FaceInfo {\n  Eigen::VectorXd outerNormalVector;\n\n  // dot product of any point of the face with outerNormalVector\n  double offset = 0.0;\n\n  std::vector<uint32_t> outsideSet;\n\n  virtual ~FacetInfo() {}\n\n  double signedDistance(Eigen::VectorXd v) const {\n    return v.dot(outerNormalVector) - offset;\n  }\n\n  int distanceSign(Eigen::VectorXd v) {\n    double signedDist = signedDistance(v);\n    return signedDist > QH_EPSILON ? 1 : (signedDist < -QH_EPSILON ? -1 : 0);\n  }\n};\n\ntemplate <typename Set, typename T>\nvoid removeFromSet(Set &set, T t) {\n  auto it = set.find(t);\n  if (it != set.end()) {\n    set.erase(it);\n  }\n}\n\ntypedef FacetInfo *FacetInfoPtr;\n\n/**\n * A custom implementation of the QuickHull algorithm that computes all faces of\n * the given polytope and also works if the facets are non-simplicial (which is\n * important for cube-based SFC, for example). This algorithm works in arbitrary\n * dimensions >= 2.\n */\nclass QuickHullAlgorithm {\n  std::vector<Eigen::VectorXd> vertices;\n\n  // an inner point of the polytope used compute the direction of facet normal\n  // vectors\n  Eigen::VectorXd innerPoint;\n  size_t dim;\n\n  std::unordered_set<FaceInfoPtr> vertexFaces;\n  std::unordered_set<FacetInfoPtr> facets;\n  std::vector<FacetInfoPtr> aboveFacets, insideFacets, newFacets;\n\n  std::queue<FacetInfoPtr> unprocessedFacets;\n  std::unordered_set<FaceInfoPtr> connectFaces;\n  std::unordered_set<FaceInfoPtr> newConnectFaces;\n\n  std::shared_ptr<ConvexPolytope> polytope;\n\n  void visitChildrenWithFlag(\n      FaceInfoPtr face, bool visitedValue,\n      std::function<void(FaceInfoPtr)> const &func = FaceInfo::dummyFunction);\n  void visitChildren(FaceInfoPtr face,\n                     std::function<void(FaceInfoPtr)> const &func);\n\n  void visitParentsWithFlag(\n      FaceInfoPtr face, bool visitedValue,\n      std::function<void(FaceInfoPtr)> const &func = FaceInfo::dummyFunction);\n\n  template <typename Collection>\n  void visitChildrenForEach(Collection const &collection,\n                            std::function<void(FaceInfoPtr)> const &func) {\n    for (auto elem : collection) {\n      visitChildrenWithFlag(elem, true, func);\n      visitChildrenWithFlag(elem, false);\n    }\n  }\n\n  template <typename Collection>\n  void visitChildrenOnce(Collection const &collection,\n                         std::function<void(FaceInfoPtr)> const &func) {\n    for (auto elem : collection) {\n      visitChildrenWithFlag(elem, true, func);\n    }\n    for (auto elem : collection) {\n      visitChildrenWithFlag(elem, false);\n    }\n  }\n\n  void initializeSimplex();\n\n  void computeNeighbors(uint32_t pointIndex, FacetInfoPtr facet);\n\n  void prepareConnect(FaceInfoPtr face,\n                      std::unordered_set<FaceInfoPtr> const &otherFaces);\n\n  void deleteFaceRecursively(FaceInfoPtr face);\n  void deleteChildrenRecursively(FaceInfoPtr face);\n\n  void addPoint(uint32_t pointIndex, FacetInfoPtr facet);\n\n  void compute();\n\n  void addToPolytopeRecursively(FaceInfoPtr face, size_t d = 0);\n\n  template <typename T>\n  void setFacetNormal(FacetInfoPtr facet, T const &vertexIndices) {\n    if (vertexIndices.size() == 0) {\n      throw std::runtime_error(\n          \"QuickHullAlgorithm::setFacetNormal(): vertexIndices.size() == 0\");\n    }\n    auto it = vertexIndices.begin();\n    auto firstPoint = this->vertices[*it];\n    math::AffineSubspace affSpace(firstPoint);\n\n    ++it;\n    for (; it != vertexIndices.end(); ++it) {\n      affSpace.addVector(this->vertices[*it]);\n    }\n\n    auto vec = affSpace.orthogonalVector().normalized();\n\n    if (vec.dot(firstPoint - innerPoint) < 0) {\n      vec *= -1;\n    }\n\n    facet->outerNormalVector = vec;\n    facet->offset = vec.dot(firstPoint);\n  }\n\n public:\n  QuickHullAlgorithm(Eigen::MatrixXd points);\n\n  ~QuickHullAlgorithm();\n\n  std::shared_ptr<ConvexPolytope> createPolytope();\n};\n\n} /* namespace geo */\n} /* namespace sfcpp */\n", "meta": {"hexsha": "d1f51fcd2a96a7d04a3905ebcd40d437020de1d7", "size": 6427, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/geo/QuickHullAlgorithm.hpp", "max_stars_repo_name": "dholzmueller/sfcpp", "max_stars_repo_head_hexsha": "b929419b13c35fff199c6c65e87ecffae9963cfc", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 15.0, "max_stars_repo_stars_event_min_datetime": "2017-10-20T07:53:03.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-23T15:54:54.000Z", "max_issues_repo_path": "src/geo/QuickHullAlgorithm.hpp", "max_issues_repo_name": "dholzmueller/sfcpp", "max_issues_repo_head_hexsha": "b929419b13c35fff199c6c65e87ecffae9963cfc", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/geo/QuickHullAlgorithm.hpp", "max_forks_repo_name": "dholzmueller/sfcpp", "max_forks_repo_head_hexsha": "b929419b13c35fff199c6c65e87ecffae9963cfc", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2017-10-20T20:02:29.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-02T12:47:53.000Z", "avg_line_length": 27.3489361702, "max_line_length": 80, "alphanum_fraction": 0.6892796017, "num_tokens": 1616, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7185943925708562, "lm_q2_score": 0.480478678047907, "lm_q1q2_score": 0.3452692837950837}}
{"text": "//==============================================================================\n//         Copyright 2003 - 2011 LASMEA UMR 6602 CNRS/Univ. Clermont II\n//         Copyright 2009 - 2011 LRI    UMR 8623 CNRS/Univ Paris Sud XI\n//\n//          Distributed under the Boost Software License, Version 1.0.\n//                 See accompanying file LICENSE.txt or copy at\n//                     http://www.boost.org/LICENSE_1_0.txt\n//==============================================================================\n#ifndef BOOST_SIMD_ARITHMETIC_FUNCTIONS_SIMD_COMMON_DIVROUND_HPP_INCLUDED\n#define BOOST_SIMD_ARITHMETIC_FUNCTIONS_SIMD_COMMON_DIVROUND_HPP_INCLUDED\n\n#include <boost/simd/arithmetic/functions/divround.hpp>\n#include <boost/simd/include/functions/simd/iround.hpp>\n#include <boost/simd/include/functions/simd/iround.hpp>\n#include <boost/simd/include/functions/simd/tofloat.hpp>\n#include <boost/simd/include/functions/simd/divides.hpp>\n#include <boost/simd/include/functions/rdivide.hpp>\n#include <boost/simd/include/functions/simd/plus.hpp>\n#include <boost/simd/include/functions/simd/group.hpp>\n#include <boost/simd/include/functions/simd/split.hpp>\n#include <boost/simd/include/functions/simd/bitwise_cast.hpp>\n#include <boost/simd/include/constants/two.hpp>\n#include <boost/simd/sdk/meta/scalar_of.hpp>\n#include <boost/dispatch/meta/upgrade.hpp>\n\nnamespace boost { namespace simd { namespace ext\n{\n  BOOST_SIMD_FUNCTOR_IMPLEMENTATION( boost::simd::tag::divround_, tag::cpu_\n                                   , (A0)(X)\n                                   , ((simd_<arithmetic_<A0>,X>))((simd_<arithmetic_<A0>,X>))\n                                   )\n  {\n    typedef A0 result_type;\n    BOOST_SIMD_FUNCTOR_CALL_REPEAT(2)\n    { return boost::simd::iround(boost::simd::tofloat(a0)/boost::simd::tofloat(a1)); }\n  };\n\n  BOOST_SIMD_FUNCTOR_IMPLEMENTATION( boost::simd::tag::divround_, tag::cpu_\n                                   , (A0)(X)\n                                   , ((simd_<unsigned_<A0>,X>))((simd_<unsigned_<A0>,X>))\n                                   )\n  {\n    typedef A0 result_type;\n    BOOST_SIMD_FUNCTOR_CALL_REPEAT(2)\n    { return boost::simd::rdivide(a0+a1/boost::simd::Two<A0>(), a1); }\n  };\n\n  BOOST_SIMD_FUNCTOR_IMPLEMENTATION( boost::simd::tag::divround_, tag::cpu_\n                                   , (A0)(X)\n                                   , ((simd_<int16_<A0>,X>))((simd_<int16_<A0>,X>))\n                                   )\n  {\n    typedef A0 result_type;\n    BOOST_SIMD_FUNCTOR_CALL_REPEAT(2)\n    {\n      typedef typename meta::scalar_of<A0>::type           stype;\n      typedef typename dispatch::meta::upgrade<stype>::type itype;\n      typedef simd::native<itype,X>                 ivtype;\n      ivtype a0l, a0h, a1l, a1h;\n      boost::simd::split(a0, a0l, a0h);\n      boost::simd::split(a1, a1l, a1h);\n      return simd::bitwise_cast<A0>(boost::simd::group(boost::simd::divround(a0l, a1l),\n                                               boost::simd::divround(a0h, a1h)));\n    }\n  };\n\n  BOOST_SIMD_FUNCTOR_IMPLEMENTATION( boost::simd::tag::divround_, tag::cpu_\n                                   , (A0)(X)\n                                   , ((simd_<int8_<A0>,X>))((simd_<int8_<A0>,X>))\n                                   )\n  {\n    typedef A0 result_type;\n    BOOST_SIMD_FUNCTOR_CALL_REPEAT(2)\n    {\n      typedef typename meta::scalar_of<A0>::type           stype;\n      typedef typename dispatch::meta::upgrade<stype>::type itype;\n      typedef simd::native<itype, X>                 ivtype;\n      ivtype a0l, a0h, a1l, a1h;\n      boost::simd::split(a0, a0l, a0h);\n      boost::simd::split(a1, a1l, a1h);\n      return simd::bitwise_cast<A0>(group(divround(a0l, a1l),\n                                          divround(a0h, a1h) ));\n    }\n  };\n\n  BOOST_SIMD_FUNCTOR_IMPLEMENTATION( boost::simd::tag::divround_, tag::cpu_\n                                   , (A0)(X)\n                                   , ((simd_<floating_<A0>,X>))((simd_<floating_<A0>,X>))\n                                   )\n  {\n    typedef A0 result_type;\n    BOOST_SIMD_FUNCTOR_CALL_REPEAT(2)\n    { return boost::simd::round(a0/a1); }\n  };\n} } }\n\n\n#endif\n", "meta": {"hexsha": "51ff29d7af8c9f2f7a69c65e3497f65de379566f", "size": 4159, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/boost/simd/arithmetic/include/boost/simd/arithmetic/functions/simd/common/divround.hpp", "max_stars_repo_name": "pbrunet/nt2", "max_stars_repo_head_hexsha": "2aeca0f6a315725b335efd5d9dc95d72e10a7fb7", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "modules/boost/simd/arithmetic/include/boost/simd/arithmetic/functions/simd/common/divround.hpp", "max_issues_repo_name": "pbrunet/nt2", "max_issues_repo_head_hexsha": "2aeca0f6a315725b335efd5d9dc95d72e10a7fb7", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "modules/boost/simd/arithmetic/include/boost/simd/arithmetic/functions/simd/common/divround.hpp", "max_forks_repo_name": "pbrunet/nt2", "max_forks_repo_head_hexsha": "2aeca0f6a315725b335efd5d9dc95d72e10a7fb7", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 42.0101010101, "max_line_length": 93, "alphanum_fraction": 0.5547006492, "num_tokens": 1054, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6959583124210896, "lm_q2_score": 0.4960938294709195, "lm_q1q2_score": 0.34526062436109695}}
{"text": "#include \"Curvilinear.h\"\n#include \"Affine.h\"\n#include \"Vector.h\"\n#include \"mesh/LocalSimplexMesh.h\"\n#include \"mesh/MeshData.h\"\n#include \"tensor/EigenMap.h\"\n#include \"tensor/Managed.h\"\n#include \"tensor/Reshape.h\"\n#include \"util/Math.h\"\n\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n#include <Eigen/LU>\n\n#include <algorithm>\n#include <cassert>\n#include <cmath>\n#include <cstddef>\n#include <cstdint>\n#include <iterator>\n#include <memory>\n#include <stdexcept>\n\nnamespace tndm {\n\ntemplate <std::size_t D>\nCurvilinear<D>::Curvilinear(LocalSimplexMesh<D> const& mesh, transform_t transform, unsigned degree,\n                            NodesFactory<D> const& nodesFactory)\n    : N(degree), refElement_(degree, nodesFactory) {\n    // Get vertices\n    std::size_t vertsPerElement = refElement_.refNodes().size();\n\n    auto storage =\n        std::make_shared<mneme::SingleStorage<Verts>>(mesh.numElements() * vertsPerElement);\n    vertices.setStorage(storage, 0, mesh.numElements(), vertsPerElement);\n\n    auto vertexData = dynamic_cast<VertexData<D> const*>(mesh.vertices().data());\n    if (!vertexData) {\n        throw std::runtime_error(\"Expected vertex data\");\n    }\n\n    std::size_t vertexNo = 0;\n    local_mesh_size_ = 0.0;\n    for (auto const& element : mesh.elements()) {\n        auto vlids = mesh.template downward<0>(element);\n        std::array<std::array<double, D>, D + 1> verts;\n        std::size_t localVertexNo = 0;\n        for (auto const& vlid : vlids) {\n            verts[localVertexNo++] = vertexData->getVertices()[vlid];\n        }\n        RefPlexToGeneralPlex<D> map(verts);\n        for (auto& refNode : refElement_.refNodes()) {\n            (*storage)[vertexNo] = transform(map(refNode));\n            ++vertexNo;\n        }\n\n        for (auto& x : verts) {\n            x = transform(x);\n        }\n        for (auto const& x : verts) {\n            for (auto const& y : verts) {\n                auto h = norm(x - y);\n                local_mesh_size_ = std::max(local_mesh_size_, h);\n            }\n        }\n    }\n\n    Simplex<D> refPlex = Simplex<D>::referenceSimplex();\n    f2v = refPlex.downward();\n\n    // Compute reference normals\n    std::size_t fsNo = 0;\n    for (auto const& f : f2v) {\n        std::array<double, D> normal;\n        if constexpr (D == 1u) {\n            normal[0] = 1.0;\n        } else if constexpr (D == 2u) {\n            // Compute normal by rotating edge\n            normal = refVertices[f[1]] - refVertices[f[0]];\n            std::swap(normal[0], normal[1]);\n            normal[0] *= -1.0;\n        } else {\n            // Compute normal by cross product\n            auto e1 = refVertices[f[1]] - refVertices[f[0]];\n            auto e2 = refVertices[f[2]] - refVertices[f[0]];\n            normal = cross(e1, e2);\n        }\n\n        refNormals[fsNo] = Eigen::Map<Eigen::Matrix<double, D, 1>>(normal.data());\n\n        std::vector<uint64_t> missingVertex;\n        std::set_difference(refPlex.begin(), refPlex.end(), f.begin(), f.end(),\n                            std::inserter(missingVertex, missingVertex.begin()));\n        assert(missingVertex.size() == 1);\n\n        auto edge = refVertices[missingVertex[0]] - refVertices[f[0]];\n        if (dot(normal, edge) > 0) {\n            refNormals[fsNo] *= -1.0;\n        }\n        ++fsNo;\n    }\n}\n\ntemplate <std::size_t D>\nTensorBase<Matrix<double>> Curvilinear<D>::mapResultInfo(std::size_t numPoints) const {\n    return TensorBase<Matrix<double>>(D, numPoints);\n}\n\ntemplate <std::size_t D>\nvoid Curvilinear<D>::map(std::size_t eleNo, Matrix<double> const& E,\n                         Tensor<double, 2u>& result) const {\n    assert(eleNo < vertices.size());\n    assert(result.shape(0) == D);\n    assert(result.shape(1) == E.shape(1));\n    assert(E.shape(0) == refElement_.numBasisFunctions());\n\n    auto vertexSpan = vertices[eleNo];\n    assert(vertexSpan.size() == refElement_.numBasisFunctions());\n    Eigen::Map<Eigen::Matrix<double, D, Eigen::Dynamic>> vertMap(vertexSpan.data()->data(), D,\n                                                                 refElement_.numBasisFunctions());\n    EigenMap(result) = vertMap * EigenMap(E);\n}\n\ntemplate <std::size_t D>\nTensorBase<Tensor<double, 3u>> Curvilinear<D>::jacobianResultInfo(std::size_t numPoints) const {\n    return TensorBase<Tensor<double, 3u>>(D, D, numPoints);\n}\n\ntemplate <std::size_t D>\nvoid Curvilinear<D>::jacobian(std::size_t eleNo, Tensor<double, 3u> const& gradE,\n                              Tensor<double, 3u>& result) const {\n    assert(eleNo < vertices.size());\n\n    auto vertexSpan = vertices[eleNo];\n    assert(vertexSpan.size() == refElement_.numBasisFunctions());\n    Eigen::Map<Eigen::Matrix<double, D, Eigen::Dynamic>> vertMap(vertexSpan.data()->data(), D,\n                                                                 refElement_.numBasisFunctions());\n\n    assert(gradE.shape(0) == refElement_.numBasisFunctions());\n    assert(gradE.shape(1) == D);\n    auto gradEMat = reshape(gradE, refElement_.numBasisFunctions(), D * gradE.shape(2));\n\n    assert(result.shape(0) == D);\n    assert(result.shape(1) == D);\n    assert(result.shape(2) == gradE.shape(2));\n    auto resultMat = reshape(result, D, D * gradE.shape(2));\n\n    EigenMap(resultMat) = vertMap * EigenMap(gradEMat);\n}\n\ntemplate <std::size_t D>\nvoid Curvilinear<D>::jacobianInv(Tensor<double, 3u> const& jacobian,\n                                 Tensor<double, 3u>& result) const {\n    for (std::ptrdiff_t i = 0; i < result.shape(2); ++i) {\n        auto jAtP = jacobian.subtensor(slice{}, slice{}, i);\n        auto resAtP = result.subtensor(slice{}, slice{}, i);\n        EigenMap<Matrix<double>, D, D>(resAtP) =\n            EigenMap<const Matrix<double>, D, D>(jAtP).inverse();\n    }\n}\n\ntemplate <std::size_t D>\nTensorBase<Vector<double>> Curvilinear<D>::detJResultInfo(std::size_t numPoints) const {\n    return TensorBase<Vector<double>>(numPoints);\n}\n\ntemplate <std::size_t D>\nvoid Curvilinear<D>::detJ(std::size_t eleNo, Tensor<double, 3u> const& jacobian,\n                          Tensor<double, 1u>& result) const {\n    for (std::ptrdiff_t i = 0; i < result.shape(0); ++i) {\n        auto jAtP = jacobian.subtensor(slice{}, slice{}, i);\n        result(i) = EigenMap<const Matrix<double>, D, D>(jAtP).determinant();\n    }\n}\n\ntemplate <std::size_t D>\nvoid Curvilinear<D>::absDetJ(std::size_t eleNo, Tensor<double, 3u> const& jacobian,\n                             Tensor<double, 1u>& result) const {\n    for (std::ptrdiff_t i = 0; i < result.shape(0); ++i) {\n        auto jAtP = jacobian.subtensor(slice{}, slice{}, i);\n        result(i) = std::fabs(EigenMap<const Matrix<double>, D, D>(jAtP).determinant());\n    }\n}\n\ntemplate <std::size_t D>\nTensorBase<Matrix<double>> Curvilinear<D>::normalResultInfo(std::size_t numPoints) const {\n    return TensorBase<Matrix<double>>(D, numPoints);\n}\n\ntemplate <std::size_t D>\nvoid Curvilinear<D>::normal(std::size_t faceNo, Tensor<double, 1u> const& detJ,\n                            Tensor<double, 3u> const& jInv, Tensor<double, 2u>& result) const {\n    assert(faceNo < D + 1u);\n    // n_{iq} = |J|_q J^{-T}_{ijq} N_j\n    for (std::ptrdiff_t i = 0; i < detJ.shape(0); ++i) {\n        auto jInvAtP = jInv.subtensor(slice{}, slice{}, i);\n        auto res = result.subtensor(slice{}, i);\n        EigenMap<Vector<double>, D>(res) =\n            std::fabs(detJ(i)) * EigenMap<const Matrix<double>, D, D>(jInvAtP).transpose() *\n            refNormals[faceNo];\n    }\n}\n\ntemplate <std::size_t D> void Curvilinear<D>::normalize(Tensor<double, 2u>& normal) const {\n    for (std::ptrdiff_t i = 0; i < normal.shape(1); ++i) {\n        auto n = normal.subtensor(slice{}, i);\n        EigenMap<Vector<double>, D>(n).normalize();\n    }\n}\n\ntemplate <std::size_t D>\nTensorBase<Tensor<double, 3u>> Curvilinear<D>::facetBasisResultInfo(std::size_t numPoints) const {\n    return TensorBase<Tensor<double, 3u>>(D, D, numPoints);\n}\n\ntemplate <std::size_t D>\nvoid Curvilinear<D>::facetBasis(std::array<double, D> const& up, Matrix<double> const& normal,\n                                Tensor<double, 3u>& result) const {\n    assert(result.shape(2) == normal.shape(1));\n\n    constexpr double colinear_tol = 10000.0 * std::numeric_limits<double>::epsilon();\n\n    for (std::ptrdiff_t i = 0; i < result.shape(2); ++i) {\n        auto n_in = normal.subtensor(slice{}, i);\n        auto n_in_eigen = EigenMap<Vector<double>, D>(n_in);\n        auto n = result.subtensor(slice{}, 0, i);\n        auto n_eigen = EigenMap<Vector<double>, D>(n);\n        n_eigen = n_in_eigen.normalized();\n\n        if constexpr (D == 2u) {\n            double s = sgn(up[0] * n(1) - up[1] * n(0));\n            if (std::fabs(s) < colinear_tol) {\n                throw std::logic_error(\"Up vector and normal are almost colinear.\");\n            }\n            auto d = result.subtensor(slice{}, 1, i);\n            d(0) = -s * n(1);\n            d(1) = s * n(0);\n        } else if constexpr (D == 3u) {\n            auto u = Eigen::Vector3d(up.data());\n            auto d = result.subtensor(slice{}, 1, i);\n            auto d_eigen = EigenMap<Vector<double>, D>(d);\n            auto s = result.subtensor(slice{}, 2, i);\n            auto s_eigen = EigenMap<Vector<double>, D>(s);\n            s_eigen = u.cross(n_eigen).normalized();\n            if (s_eigen.norm() < colinear_tol) {\n                throw std::logic_error(\"Up vector and normal are almost colinear.\");\n            }\n            d_eigen = s_eigen.cross(n_eigen).normalized();\n        }\n    }\n}\n\ntemplate <std::size_t D>\nvoid Curvilinear<D>::facetBasisFromPlexTangents(std::size_t faceNo,\n                                                Tensor<double, 3u> const& jacobian,\n                                                Matrix<double> const& normal,\n                                                Tensor<double, 3u>& result) const {\n    assert(result.shape(2) == normal.shape(1));\n    assert(result.shape(2) == jacobian.shape(2));\n\n    auto& f = f2v[faceNo];\n    auto refTangent = refVertices[f[1]] - refVertices[f[0]];\n    for (std::ptrdiff_t i = 0; i < result.shape(2); ++i) {\n        auto n = normal.subtensor(slice{}, i);\n        auto n_eigen = EigenMap<Vector<double>, D>(n);\n        auto n_res = result.subtensor(slice{}, 0, i);\n        auto n_res_eigen = EigenMap<Vector<double>, D>(n_res);\n        n_res_eigen = n_eigen.normalized();\n\n        if constexpr (D >= 2u) {\n            auto jAtP = jacobian.subtensor(slice{}, slice{}, i);\n            auto t1_res = result.subtensor(slice{}, 1, i);\n            auto t1_res_eigen = EigenMap<Vector<double>, D>(t1_res);\n            // first tangent = J * refTangent\n            t1_res_eigen = EigenMap<const Matrix<double>, D, D>(jAtP) *\n                           Eigen::Map<Eigen::Matrix<double, D, 1>>(refTangent.data());\n            t1_res_eigen.normalize();\n\n            if constexpr (D == 3u) {\n                auto t2_res = result.subtensor(slice{}, 2, i);\n                auto t2_res_eigen = EigenMap<Vector<double>, D>(t2_res);\n                t2_res_eigen = n_res_eigen.cross(t1_res_eigen);\n                t2_res_eigen.normalize();\n            }\n        }\n    }\n}\n\ntemplate <std::size_t D>\nstd::array<double, D> Curvilinear<D>::facetParam(std::size_t faceNo,\n                                                 std::array<double, D - 1> const& chi) const {\n    auto& f = f2v[faceNo];\n    std::array<double, D> xi;\n    double chiSum = 0.0;\n    for (std::size_t d = 0; d < chi.size(); ++d) {\n        chiSum += chi[d];\n    }\n    xi = (1.0 - chiSum) * refVertices[f[0]];\n    for (std::size_t d = 0; d < chi.size(); ++d) {\n        xi = xi + chi[d] * refVertices[f[d + 1]];\n    }\n    return xi;\n}\n\ntemplate <std::size_t D>\nstd::vector<std::array<double, D>>\nCurvilinear<D>::facetParam(std::size_t faceNo,\n                           std::vector<std::array<double, D - 1>> const& chis) const {\n    std::vector<std::array<double, D>> xis;\n    xis.reserve(chis.size());\n    for (auto const& chi : chis) {\n        xis.emplace_back(facetParam(faceNo, chi));\n    }\n    return xis;\n}\n\ntemplate class Curvilinear<1ul>;\ntemplate class Curvilinear<2ul>;\ntemplate class Curvilinear<3ul>;\n\n} // namespace tndm\n", "meta": {"hexsha": "d43e9e00ebeb218a33f74dab86365556795769d3", "size": 12114, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/geometry/Curvilinear.cpp", "max_stars_repo_name": "NicoSchlw/tandem", "max_stars_repo_head_hexsha": "3a08b5a7ae391c1675c5cbfdad77260d4a0115cc", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/geometry/Curvilinear.cpp", "max_issues_repo_name": "NicoSchlw/tandem", "max_issues_repo_head_hexsha": "3a08b5a7ae391c1675c5cbfdad77260d4a0115cc", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/geometry/Curvilinear.cpp", "max_forks_repo_name": "NicoSchlw/tandem", "max_forks_repo_head_hexsha": "3a08b5a7ae391c1675c5cbfdad77260d4a0115cc", "max_forks_repo_licenses": ["BSD-3-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.6211180124, "max_line_length": 100, "alphanum_fraction": 0.5793297012, "num_tokens": 3285, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.712232184238947, "lm_q2_score": 0.48438008427698437, "lm_q1q2_score": 0.3449910854264418}}
{"text": "#include \"plugins/snake/algo.h\"\n#include <float.h>\n#include <vector>\n#include <memory>\n#include <utilities/cv.h>\n#include <Eigen/Dense>\n\n/*F///////////////////////////////////////////////////////////////////////////////////////\n//    Name:      icvSnake8uC1R\n//    Purpose:\n//    Context:\n//    Parameters:\n//               img - source image,\n//               imgStep - its step in bytes,\n//               roi - size of ROI,\n//               points - pointer to snake points array\n//               n - size of points array,\n//               alpha - pointer to coefficient of continuity energy,\n//               beta - pointer to coefficient of curvature energy,\n//               gamma - pointer to coefficient of image energy,\n//               coeffUsage - if CV_VALUE - alpha, beta, gamma point to single value\n//                            if CV_MATAY - point to arrays\n//               criteria - termination criteria.\n//               scheme - image energy scheme\n//                         if _CV_SNAKE_IMAGE - image intensity is energy\n//                         if _CV_SNAKE_GRAD  - magnitude of gradient is energy\n//    Returns:\n//F*/\n\n\ntemplate <class T>\nT _max(T a, T b) {\n    return (a>b?a:b);\n}\n\ntemplate <class T>\nT _min(T a, T b) {\n    return (a<b?a:b);\n}\n\nbool snake_iteration(boost::shared_ptr<std::vector<float> > img,\n               int w,\n               int h,\n               std::vector<Eigen::Vector2i> & points,\n               int win_w,\n               int win_h,\n               float alpha,\n               float beta,\n               float gamma,\n               float delta) {\n    int n = points.size();\n    int neighbors = win_h * win_w;\n\n    int centerx = win_w >> 1;\n    int centery = win_h >> 1;\n\n    int iteration = 0;\n    bool converged = false;\n\n    /* check bad arguments */\n    assert(points.size() > 2);\n    assert((h > 0) && (w > 0));\n    assert((win_h > 0) && (win_h & 1));\n    assert((win_w > 0) && (win_w & 1));\n\n    //float invn = 1 / ((float) points.size());\n\n    std::vector<float> Econt(neighbors);\n    std::vector<float> Ecurv(neighbors);\n    std::vector<float> Eimg(neighbors);\n    std::vector<float> Esize(neighbors);\n    std::vector<float> E(neighbors);\n\n    while( !converged ) {\n        float ave_d = 0;\n        int moved = 0;\n\n        converged = false;\n        iteration++;\n        /* compute average distance */\n        for(int i = 1; i < n; i++ )\n        {\n            int diffx = points[i - 1].x() - points[i].x();\n            int diffy = points[i - 1].y() - points[i].y();\n\n            ave_d += sqrt( (float) (diffx * diffx + diffy * diffy) );\n        }\n        ave_d += sqrt( (float) ((points[0].x() - points[n - 1].x()) *\n                                  (points[0].x() - points[n - 1].x()) +\n                                  (points[0].y() - points[n - 1].y()) * (points[0].y() - points[n - 1].y())));\n\n        ave_d /= n;\n        /* average distance computed */\n        for(int i = 0; i < n; i++ )\n        {\n            /* Calculate Econt */\n            float maxEcont = 0;\n            float maxEcurv = 0;\n            float maxEimg = 0;\n            float maxEsize = 0;\n            float minEcont = FLT_MAX;\n            float minEcurv = FLT_MAX;\n            float minEimg = FLT_MAX;\n            float minEsize = FLT_MAX;\n            float Emin = FLT_MAX;\n\n            int offsetx = 0;\n            int offsety = 0;\n            float tmp;\n\n            /* compute bounds */\n            int left = _min( points[i].x(), win_w >> 1 );\n            int right = _min( w - 1 - points[i].x(), win_w >> 1 );\n            int upper = _min( points[i].y(), win_h >> 1 );\n            int bottom = _min( h - 1 - points[i].y(), win_h >> 1 );\n\n            maxEcont = 0;\n            minEcont = FLT_MAX;\n            for(int j = -upper; j <= bottom; j++ )\n            {\n                for(int k = -left; k <= right; k++ )\n                {\n                    int diffx, diffy;\n\n                    if( i == 0 )\n                    {\n                        diffx = points[n - 1].x() - (points[i].x() + k);\n                        diffy = points[n - 1].y() - (points[i].y() + j);\n                    }\n                    else\n                    {\n                        diffx = points[i - 1].x() - (points[i].x() + k);\n                        diffy = points[i - 1].y() - (points[i].y() + j);\n                    }\n\n                    float energy = (float) fabs(ave_d - sqrt( (float) (diffx * diffx + diffy * diffy) ));\n\n                    int idx = (j + centery) * win_w + k + centerx;\n                    Econt[idx] = energy;\n\n                    maxEcont = _max( maxEcont, energy );\n                    minEcont = _min( minEcont, energy );\n                }\n            }\n            tmp = maxEcont - minEcont;\n            tmp = (tmp == 0) ? 0 : (1 / tmp);\n            for(int k = 0; k < neighbors; k++ )\n            {\n                Econt[k] = (Econt[k] - minEcont) * tmp;\n            }\n\n            /*  Calculate Ecurv */\n            maxEcurv = 0;\n            minEcurv = FLT_MAX;\n            for(int j = -upper; j <= bottom; j++ )\n            {\n                for(int k = -left; k <= right; k++ )\n                {\n                    int tx, ty;\n                    float energy;\n\n                    if(i == 0 )\n                    {\n                        tx = points[n - 1].x() - 2 * (points[i].x() + k) + points[i + 1].x();\n                        ty = points[n - 1].y() - 2 * (points[i].y() + j) + points[i + 1].y();\n                    }\n                    else if( i == n - 1 )\n                    {\n                        tx = points[i - 1].x() - 2 * (points[i].x() + k) + points[0].x();\n                        ty = points[i - 1].y() - 2 * (points[i].y() + j) + points[0].y();\n                    }\n                    else\n                    {\n                        tx = points[i - 1].x() - 2 * (points[i].x() + k) + points[i + 1].x();\n                        ty = points[i - 1].y() - 2 * (points[i].y() + j) + points[i + 1].y();\n                    }\n                    Ecurv[(j + centery) * win_w + k + centerx] = energy =\n                        (float) (tx * tx + ty * ty);\n                    maxEcurv = _max( maxEcurv, energy );\n                    minEcurv = _min( minEcurv, energy );\n                }\n            }\n            tmp = maxEcurv - minEcurv;\n            tmp = (tmp == 0) ? 0 : (1 / tmp);\n            for(int k = 0; k < neighbors; k++ )\n            {\n                Ecurv[k] = (Ecurv[k] - minEcurv) * tmp;\n            }\n\n            /* Calculate Eimg */\n            for(int j = -upper; j <= bottom; j++ )\n            {\n                for(int k = -left; k <= right; k++ )\n                {\n                    int y = points[i].y();\n                    int x = points[i].x();\n                    //int idx = (y + j) * w + x + k;\n                    int idx = (x + k) * h + h-1 - (y + j);\n                    float energy = -(*img)[idx];\n\n                    Eimg[(j + centery) * win_w + k + centerx] = energy;\n\n                    maxEimg = _max( maxEimg, energy );\n                    minEimg = _min( minEimg, energy );\n                }\n            }\n\n            // Test purposes\n            /*int y = points[i].y();\n            int x = points[i].x();\n            int k = 0;\n            int j = 0;\n            int idx = (x + k) * h + h-1 - (y + j);\n            (*img)[idx] = 400;\n            */\n\n            tmp = (maxEimg - minEimg);\n            tmp = (tmp == 0) ? 0 : (1 / tmp);\n\n            for(int k = 0; k < neighbors; k++ )\n            {\n                Eimg[k] = (minEimg - Eimg[k]) * tmp;\n            }\n\n            /*  Calculate Esize */\n            maxEsize = 0;\n            minEsize = FLT_MAX;\n            for(int j = -upper; j <= bottom; j++ )\n            {\n                for(int k = -left; k <= right; k++ )\n                {\n                    Eigen::Vector2i prev;\n                    Eigen::Vector2i next;\n                    Eigen::Vector2i & curr = points[i];\n\n                    if(i == 0 )\n                    {\n                        prev = points[n - 1];\n                        next = points[i + 1];\n                    }\n                    else if( i == n - 1 )\n                    {\n                        prev = points[i - 1];\n                        next = points[0];\n                    }\n                    else\n                    {\n                        prev = points[i - 1];\n                        next = points[i + 1];\n                    }\n\n                    float dist1 = pow(curr.x() + k - prev.x(), 2) + pow(curr.y() + j - prev.y(), 2);\n                    float dist2 = pow(curr.x() + k - next.x(), 2) + pow(curr.y() + j - next.y(), 2);\n\n                    float energy = (dist1 + dist2) * 0.5f;\n\n                    Esize[(j + centery) * win_w + k + centerx] = energy;\n                    maxEsize = _max( maxEsize, energy );\n                    minEsize = _min( minEsize, energy );\n                }\n            }\n            tmp = maxEsize - minEsize;\n            tmp = (tmp == 0) ? 0 : (1 / tmp);\n            for(int k = 0; k < neighbors; k++ )\n            {\n                Esize[k] = (Esize[k] - minEsize) * tmp;\n            }\n\n            /* Find Minimize point in the neighbors */\n            for(int k = 0; k < neighbors; k++ )\n            {\n                E[k] = alpha * Econt[k] + beta * Ecurv[k] + gamma * Eimg[k] + delta * Esize[k];\n            }\n            Emin = FLT_MAX;\n            for(int j = -upper; j <= bottom; j++ )\n            {\n                for(int k = -left; k <= right; k++ )\n                {\n\n                    if( E[(j + centery) * win_w + k + centerx] < Emin )\n                    {\n                        Emin = E[(j + centery) * win_w + k + centerx];\n                        offsetx = k;\n                        offsety = j;\n                    }\n                }\n            }\n\n            if( offsetx || offsety )\n            {\n                //qDebug() << \"(\" << points[i].x() << points[i].y() << \") + (\" << offsetx << offsety << \")\" ;\n                points[i] = points[i] + Eigen::Vector2i(offsetx, offsety);\n                //qDebug() << \" = (\" << points[i].x() << points[i].y() << \")\";\n                moved++;\n            }\n        }\n        converged = (moved == 0);\n        break;\n    }\n\n\n    return converged;\n}\n", "meta": {"hexsha": "8108a0e57b3720a1361e08c57ab0c568f804565f", "size": 10307, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/plugins/snake/algo.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/snake/algo.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/snake/algo.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": 33.9046052632, "max_line_length": 110, "alphanum_fraction": 0.3655767925, "num_tokens": 2651, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7122321842389469, "lm_q2_score": 0.48438008427698437, "lm_q1q2_score": 0.34499108542644175}}
{"text": "#pragma once\n#include <iostream> \n#include <vector>\n#include <string>\n#include <thread>\n#include <atomic>\n#include <chrono>\n#include <time.h>\n#include <math.h>\n#include <unordered_map>\n#include <unordered_set>\n\n#include <opencv2/opencv.hpp>\n\n#include <pcl/kdtree/kdtree_flann.h>\n#include <Eigen/Core>\n#include <Eigen/Dense>\n#include <Eigen/Geometry>\n\n#include <octomap/octomap.h>\n#include <octomap/ColorOcTree.h>\n\n\nusing namespace std;\n\nclass Ray\n{\npublic:\n\toctomap::OcTreeKey origin;\n\toctomap::OcTreeKey end;\n\toctomap::KeyRay* ray_set;\n\toctomap::KeyRay::iterator start;\n\toctomap::KeyRay::iterator stop;\n\n\tRay(octomap::OcTreeKey _origin, octomap::OcTreeKey _end, octomap::KeyRay* _ray_set, octomap::KeyRay::iterator _start,octomap::KeyRay::iterator _stop){\n\t\torigin = _origin;\n\t\tend = _end;\n\t\tray_set = _ray_set;\n\t\tstart = _start;\n\t\tstop = _stop;\n\t}\n\n\tbool operator ==(const Ray& other) const {//用于查询 \t\t\n\t\treturn (origin == other.origin) && (end == other.end); \t\n\t}\n};\n\nclass Ray_Hash\n{\npublic:\n\tsize_t operator() (const Ray& ray) const {//利用6个点的double来hash\n\t\treturn octomap::OcTreeKey::KeyHash()(ray.origin) ^ octomap::OcTreeKey::KeyHash()(ray.end);\n\t}\n};\n\nclass Ray_Information\n{\npublic:\n\tRay* ray;\n\tdouble information_gain;\n\tdouble visible;\n\tdouble object_visible;\n\tint voxel_num;\n\tbool previous_voxel_unknown;\n\n\tRay_Information(Ray* _ray) {\n\t\tray = _ray;\n\t\tinformation_gain = 0;\n\t\tvisible = 1;\n\t\tobject_visible = 1;\n\t\tprevious_voxel_unknown = false;\n\t\tvoxel_num = 0;\n\t}\n\n\t~Ray_Information() {\n\t\tdelete ray;\n\t}\n\n\tvoid clear() {\n\t\tinformation_gain = 0;\n\t\tvisible = 1;\n\t\tobject_visible = 1;\n\t\tprevious_voxel_unknown = false;\n\t\tvoxel_num = 0;\n\t}\n};\n\n//void ray_graph_thread_process(int ray_id,Ray_Information** rays_info, unordered_map<int, vector<int>>* rays_to_viwes_map, unordered_map<octomap::OcTreeKey, unordered_set<int>, octomap::OcTreeKey::KeyHash>* end_id_map, Voxel_Information* voxel_information);\nvoid information_gain_thread_process(Ray_Information** rays_info, unordered_map<int, vector<int>>* views_to_rays_map, View_Space* view_space, int pos);\nvoid ray_expand_thread_process(int* ray_num, Ray_Information** rays_info, unordered_map<Ray, int, Ray_Hash>* rays_map, unordered_map<int, vector<int>>* views_to_rays_map, unordered_map<int, vector<int>>* rays_to_viwes_map, octomap::ColorOcTree* octo_model, Voxel_Information* voxel_information, View_Space* view_space, rs2_intrinsics* color_intrinsics, pcl::PointCloud<pcl::PointXYZ>::Ptr frontier,int pos);\nvoid ray_cast_thread_process(int* ray_num, Ray_Information** rays_info, unordered_map<Ray, int, Ray_Hash>* rays_map, unordered_map<int, vector<int>>* views_to_rays_map, unordered_map<int, vector<int>>* rays_to_viwes_map, octomap::ColorOcTree* octo_model, Voxel_Information* voxel_information, View_Space* view_space, rs2_intrinsics* color_intrinsics,int pos);\nvector<int> get_xmax_xmin_ymax_ymin_in_hull(vector<cv::Point2f>& hull, rs2_intrinsics& color_intrinsics);\nbool is_pixel_in_convex(vector<cv::Point2f>& hull, cv::Point2f& pixel);\nvector<cv::Point2f> get_convex_on_image(vector<Eigen::Vector4d>& convex_3d, Eigen::Matrix4d& now_camera_pose_world, rs2_intrinsics& color_intrinsics, int& pixel_interval, double& max_range, double& octomap_resolution);\noctomap::point3d project_pixel_to_ray_end(int x,int y, rs2_intrinsics& color_intrinsics, Eigen::Matrix4d& now_camera_pose_world, float max_range = 1.0);\ndouble information_function(short& method, double& ray_informaiton, double voxel_information, double& visible, bool& is_unknown, bool& previous_voxel_unknown, bool& is_endpoint, bool& is_occupied, double& object, double& object_visible);\nvoid ray_information_thread_process(int ray_id, Ray_Information** rays_info, unordered_map<Ray, int, Ray_Hash>* rays_map, unordered_map<octomap::OcTreeKey, double, octomap::OcTreeKey::KeyHash>* occupancy_map, unordered_map<octomap::OcTreeKey, double, octomap::OcTreeKey::KeyHash>* object_weight, octomap::ColorOcTree* octo_model, Voxel_Information* voxel_information, View_Space* view_space, short method);\nint frontier_check(octomap::point3d node, octomap::ColorOcTree* octo_model, Voxel_Information* voxel_information, double octomap_resolution);\ndouble distance_function(double distance, double alpha);\n\nclass Views_Information\n{\npublic:\n\tdouble cost_weight;\n\tRay_Information** rays_info;\n\tunordered_map<int, vector<int>>* views_to_rays_map;\n\tunordered_map<int, vector<int>>* rays_to_viwes_map;\n\tunordered_map<Ray,int, Ray_Hash>* rays_map;\n\tunordered_map<octomap::OcTreeKey,double, octomap::OcTreeKey::KeyHash>* occupancy_map;\n\tunordered_map<octomap::OcTreeKey, double, octomap::OcTreeKey::KeyHash>* object_weight;\n\tlong long max_num_of_rays;\n\tint ray_num;\n\tdouble alpha;\n\tint K = 6;\n\trs2_intrinsics color_intrinsics;\n\tVoxel_Information* voxel_information;\n\toctomap::ColorOcTree* octo_model;\n\tdouble octomap_resolution;\n\tint method;\n\tint pre_edge_cnt;\n\tint edge_cnt;\n\n\tViews_Information(Share_Data* share_data, Voxel_Information* _voxel_information , View_Space* view_space,int iterations)\n\t{\n\t\t//更新内部数据\n\t\tvoxel_information = _voxel_information;\n\t\tcost_weight = share_data->cost_weight;\n\t\tcolor_intrinsics = share_data->color_intrinsics;\n\t\tmethod = share_data->method_of_IG;\n\t\tocto_model = share_data->octo_model;\n\t\toctomap_resolution = share_data->octomap_resolution;\n\t\tvoxel_information->octomap_resolution = octomap_resolution;\n\t\talpha = 0.1 / octomap_resolution;\n\t\tvoxel_information->skip_coefficient = share_data->skip_coefficient;\n\t\t//注意视点需要按照id排序来建立映射\n\t\tsort(view_space->views.begin(), view_space->views.end(), view_id_compare);\n\t\tdouble now_time = clock();\n\t\tviews_to_rays_map = new unordered_map<int, vector<int>>();\n\t\trays_to_viwes_map = new unordered_map<int, vector<int>>();\n\t\trays_map = new unordered_map<Ray, int, Ray_Hash>();\n\t\tobject_weight = new unordered_map<octomap::OcTreeKey, double, octomap::OcTreeKey::KeyHash>();\n\t\toccupancy_map = new unordered_map<octomap::OcTreeKey, double, octomap::OcTreeKey::KeyHash>();\n\t\t//定义frontier\n\t\tvector<octomap::point3d> points;\n\t\tpcl::PointCloud<pcl::PointXYZ>::Ptr edge(new pcl::PointCloud<pcl::PointXYZ>);\n\t\tdouble map_size = view_space->predicted_size;\n\t\t//查找地图中的edge\n\t\tfor (octomap::ColorOcTree::leaf_iterator it = octo_model->begin_leafs(), end = octo_model->end_leafs(); it != end; ++it)\n\t\t{\n\t\t\tdouble occupancy = (*it).getOccupancy();\n\t\t\t//记录bbx中key到occ率的映射，用于重复查询\n\t\t\t(*occupancy_map)[it.getKey()] = occupancy;\n\t\t\tif (voxel_information->is_unknown(occupancy)) {\n\t\t\t\tauto coordinate = it.getCoordinate();\n\t\t\t\tif (coordinate.x() >= view_space->object_center_world(0) - map_size && coordinate.x() <= view_space->object_center_world(0) + map_size\n\t\t\t\t\t&& coordinate.y() >= view_space->object_center_world(1) - map_size && coordinate.y() <= view_space->object_center_world(1) + map_size\n\t\t\t\t\t&& coordinate.z() >= view_space->object_center_world(2) - map_size && coordinate.z() <= view_space->object_center_world(2) + map_size)\n\t\t\t\t{\n\t\t\t\t\tpoints.push_back(coordinate);\n\t\t\t\t\tif (frontier_check(coordinate, octo_model, voxel_information, octomap_resolution)==2) edge->points.push_back(pcl::PointXYZ(coordinate.x(), coordinate.y(), coordinate.z()));\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tpre_edge_cnt = 0x3f3f3f3f;\n\t\tedge_cnt = edge->points.size();\n\t\t//根据最邻近frontier，计算地图中该点的是物体表面的可能性\n\t\tif (edge->points.size() != 0) {\n\t\t\tpcl::KdTreeFLANN<pcl::PointXYZ> kdtree;\n\t\t\tkdtree.setInputCloud(edge);\n\t\t\tstd::vector<int> pointIdxNKNSearch(K);\n\t\t\tstd::vector<float> pointNKNSquaredDistance(K);\n\t\t\tfor (int i = 0; i < points.size(); i++)\n\t\t\t{\n\t\t\t\toctomap::OcTreeKey key;   bool key_have = octo_model->coordToKeyChecked(points[i], key);\n\t\t\t\tif (key_have) {\n\t\t\t\t\tpcl::PointXYZ searchPoint(points[i].x(), points[i].y(), points[i].z());\n\t\t\t\t\tint num = kdtree.nearestKSearch(searchPoint, K, pointIdxNKNSearch, pointNKNSquaredDistance);\n\t\t\t\t\tif (num > 0) {\n\t\t\t\t\t\tdouble p_obj = 1;\n\t\t\t\t\t\tfor (int j = 0; j < pointIdxNKNSearch.size(); j++) {\n\t\t\t\t\t\t\tp_obj *= distance_function(pointNKNSquaredDistance[j], alpha);\n\t\t\t\t\t\t}\n\t\t\t\t\t\t(*object_weight)[key] = p_obj;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tcout << \"occupancy_map is \" << occupancy_map->size() << endl;\n\t\tcout << \"edge is \" << edge->points.size() << endl;\n\t\tcout << \"object_map is \" << object_weight->size() << endl;\n\t\t//根据BBX计算最多有多少射线，射线个数最多为表面积大小*体积，用于分配指针内存\n\t\tdouble pre_line_point = 2.0 * map_size / octomap_resolution;\n\t\tlong long superficial = ceil(5.0 * pre_line_point * pre_line_point);\n\t\tlong long volume = ceil(pre_line_point * pre_line_point * pre_line_point);\n\t\tmax_num_of_rays = superficial* volume;\n\t\trays_info = new Ray_Information * [max_num_of_rays];\n\t\tcout << \"full rays num is \" << max_num_of_rays << endl;\n\t\t//计算BBX的八个顶点，用于划定射线范围\n\t\tvector<Eigen::Vector4d> convex_3d;\n\t\tdouble x1 = view_space->object_center_world(0) - map_size;\n\t\tdouble x2 = view_space->object_center_world(0) + map_size;\n\t\tdouble y1 = view_space->object_center_world(1) - map_size;\n\t\tdouble y2 = view_space->object_center_world(1) + map_size;\n\t\tdouble z1 = view_space->object_center_world(2) - map_size;\n\t\tdouble z2 = view_space->object_center_world(2) + map_size;\n\t\tconvex_3d.push_back(Eigen::Vector4d(x1, y1, z1, 1));\n\t\tconvex_3d.push_back(Eigen::Vector4d(x1, y2, z1, 1));\n\t\tconvex_3d.push_back(Eigen::Vector4d(x2, y1, z1, 1));\n\t\tconvex_3d.push_back(Eigen::Vector4d(x2, y2, z1, 1));\n\t\tconvex_3d.push_back(Eigen::Vector4d(x1, y1, z2, 1));\n\t\tconvex_3d.push_back(Eigen::Vector4d(x1, y2, z2, 1));\n\t\tconvex_3d.push_back(Eigen::Vector4d(x2, y1, z2, 1));\n\t\tconvex_3d.push_back(Eigen::Vector4d(x2, y2, z2, 1));\n\t\tvoxel_information->convex = convex_3d;\n\t\t//分配视点的射线生成器\n\t\tthread** ray_caster = new thread *[view_space->views.size()];\n\t\t//射线初始下标从0开始\n\t\tray_num = 0;\n\t\tfor (int i = 0; i < view_space->views.size(); i++) {\n\t\t\t//对该视点分发生成射线的线程\n\t\t\tray_caster[i] = new thread(ray_cast_thread_process, &ray_num, rays_info, rays_map, views_to_rays_map, rays_to_viwes_map, octo_model, voxel_information, view_space, &color_intrinsics, i);\n\t\t}\n\t\t//等待每个视点射线生成器计算完成\n\t\tfor (int i = 0; i < view_space->views.size(); i++) {\n\t\t\t(*ray_caster[i]).join();\n\t\t}\n\t\tcout << \"ray_num is \" << ray_num << endl;\n\t\tcout << \"All views' rays generated with executed time \" << clock() - now_time << \" ms. Startring compution.\" << endl;\n\t\t//为每条射线分配一个线程\n\t\tnow_time = clock();\n\t\tthread** rays_process = new thread* [ray_num];\n\t\tfor (int i = 0; i < ray_num; i++) {\n\t\t\trays_process[i] = new thread(ray_information_thread_process, i, rays_info, rays_map, occupancy_map, object_weight, octo_model, voxel_information, view_space, method);\n\t\t}\n\t\t//等待射线计算完成\n\t\tfor (int i = 0; i < ray_num; i++) {\n\t\t\t(*rays_process[i]).join();\t\n\t\t}\n\t\tdouble cost_time = clock() - now_time;\n\t\tcout << \"All rays' threads over with executed time \" << cost_time << \" ms.\" << endl;\n\t\tshare_data->access_directory(share_data->save_path + \"/run_time\");\n\t\tofstream fout(share_data->save_path + \"/run_time/IG\" + to_string(view_space->id) + \".txt\");\n\t\tfout << cost_time << endl;\n\t\t//分配视点的信息统计器\n\t\tnow_time = clock();\n\t\tthread** view_gain = new thread * [view_space->views.size()];\n\t\tfor (int i = 0; i < view_space->views.size(); i++) {\n\t\t\t//对该视点分发信息统计的线程\n\t\t\tview_gain[i] = new thread(information_gain_thread_process, rays_info, views_to_rays_map, view_space, i);\n\t\t}\n\t\t//等待每个视点信息统计完成\n\t\tfor (int i = 0; i < view_space->views.size(); i++) {\n\t\t\t(*view_gain[i]).join();\n\t\t}\n\t\tcout << \"All views' gain threads over with executed time \" << clock() - now_time << \" ms.\" << endl;\n\t}\n\t\n\tvoid update(Share_Data* share_data, View_Space* view_space,int iterations) {\n\t\t//更新内部数据\n\t\tdouble now_time = clock();\n\t\tdouble map_size = view_space->predicted_size;\n\t\t//注意视点需要按照id排序来建立映射\n\t\tsort(view_space->views.begin(), view_space->views.end(), view_id_compare);\n\t\t//重新记录八叉树\n\t\tocto_model = share_data->octo_model;\n\t\toctomap_resolution = share_data->octomap_resolution;\n\t\talpha = 0.1 / octomap_resolution;\n\t\tvoxel_information->octomap_resolution = octomap_resolution;\n\t\tvoxel_information->skip_coefficient = share_data->skip_coefficient;\n\t\t//清空视点信息\n\t\tfor (int i = 0; i < view_space->views.size(); i++) {\n\t\t\tview_space->views[i].information_gain = 0;\n\t\t\tview_space->views[i].voxel_num = 0;\n\t\t}\n\t\t//避免重复search\n\t\tdelete occupancy_map;\n\t\toccupancy_map = new unordered_map<octomap::OcTreeKey, double, octomap::OcTreeKey::KeyHash>();\n\t\tdelete object_weight;\n\t\tobject_weight = new unordered_map<octomap::OcTreeKey, double, octomap::OcTreeKey::KeyHash>();\n\t\t//更新frontier\n\t\tvector<octomap::point3d> points;\n\t\tpcl::PointCloud<pcl::PointXYZ>::Ptr edge(new pcl::PointCloud<pcl::PointXYZ>);\n\t\tfor (octomap::ColorOcTree::leaf_iterator it = octo_model->begin_leafs(), end = octo_model->end_leafs(); it != end; ++it)\n\t\t{\n\t\t\tdouble occupancy = (*it).getOccupancy();\n\t\t\t(*occupancy_map)[it.getKey()] = occupancy;\n\t\t\tif (voxel_information->is_unknown(occupancy)) {\n\t\t\t\tauto coordinate = it.getCoordinate();\n\t\t\t\tif (coordinate.x() >= view_space->object_center_world(0) - map_size && coordinate.x() <= view_space->object_center_world(0) + map_size\n\t\t\t\t\t&& coordinate.y() >= view_space->object_center_world(1) - map_size && coordinate.y() <= view_space->object_center_world(1) + map_size\n\t\t\t\t\t&& coordinate.z() >= view_space->object_center_world(2) - map_size && coordinate.z() <= view_space->object_center_world(2) + map_size)\n\t\t\t\t{\n\t\t\t\t\tpoints.push_back(coordinate);\n\t\t\t\t\tif (frontier_check(coordinate, octo_model, voxel_information, octomap_resolution)==2) edge->points.push_back(pcl::PointXYZ(coordinate.x(), coordinate.y(), coordinate.z()));\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tedge_cnt = edge->points.size();\n\t\tif (edge_cnt > pre_edge_cnt) pre_edge_cnt = 0x3f3f3f3f;\n\t\tif (edge->points.size() != 0) {\n\t\t\t//计算frontier\n\t\t\tpcl::KdTreeFLANN<pcl::PointXYZ> kdtree;\n\t\t\tkdtree.setInputCloud(edge);\n\t\t\tstd::vector<int> pointIdxNKNSearch(K);\n\t\t\tstd::vector<float> pointNKNSquaredDistance(K);\n\t\t\tfor (int i = 0; i < points.size(); i++)\n\t\t\t{\n\t\t\t\toctomap::OcTreeKey key;   bool key_have = octo_model->coordToKeyChecked(points[i], key);\n\t\t\t\tif (key_have) {\n\t\t\t\t\tpcl::PointXYZ searchPoint(points[i].x(), points[i].y(), points[i].z());\n\t\t\t\t\tint num = kdtree.nearestKSearch(searchPoint, K, pointIdxNKNSearch, pointNKNSquaredDistance);\n\t\t\t\t\tif (num > 0) {\n\t\t\t\t\t\tdouble p_obj = 1;\n\t\t\t\t\t\tfor (int j = 0; j < pointIdxNKNSearch.size(); j++) {\n\t\t\t\t\t\t\tp_obj *= distance_function(pointNKNSquaredDistance[j], alpha);\n\t\t\t\t\t\t}\n\t\t\t\t\t\t(*object_weight)[key] = p_obj;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tcout << \"edge is \" << edge->points.size() << endl;\n\t\tcout << \"object_map is \" << object_weight->size() << endl;\n\t\tcout << \"occupancy_map is \" << occupancy_map->size() << endl;\n\t\tcout << \"frontier updated with executed time \" << clock() - now_time << \" ms.\" << endl;\n\t\t//检测是否重生成\n\t\tnow_time = clock();\n\t\tbool regenerate = false;\n\t\tif (view_space->object_changed) {\n\t\t\tregenerate = true;\n\t\t}\n\t\t//如果重生成，则更新数据结构\n\t\tif (regenerate) {\n\t\t\t//重计算最大射线数量，从0开始\n\t\t\tdouble pre_line_point = 2.0 * map_size / octomap_resolution;\n\t\t\tlong long superficial = ceil(5.0 * pre_line_point * pre_line_point);\n\t\t\tlong long volume = ceil(pre_line_point * pre_line_point * pre_line_point);\n\t\t\tmax_num_of_rays = superficial * volume;\n\t\t\tdelete[] rays_info;\n\t\t\trays_info = new Ray_Information * [max_num_of_rays];\n\t\t\tcout << \"full rays num is \" << max_num_of_rays << endl;\n\t\t\tray_num = 0;\n\t\t\tdelete views_to_rays_map;\n\t\t\tviews_to_rays_map = new unordered_map<int, vector<int>>();\n\t\t\tdelete rays_to_viwes_map;\n\t\t\trays_to_viwes_map = new unordered_map<int, vector<int>>();\n\t\t\tdelete rays_map;\n\t\t\trays_map = new unordered_map<Ray, int, Ray_Hash>();\n\n\t\t\t//计算BBX的八个顶点，用于划定射线范围\n\t\t\tvector<Eigen::Vector4d> convex_3d;\n\t\t\tdouble x1 = view_space->object_center_world(0) - map_size;\n\t\t\tdouble x2 = view_space->object_center_world(0) + map_size;\n\t\t\tdouble y1 = view_space->object_center_world(1) - map_size;\n\t\t\tdouble y2 = view_space->object_center_world(1) + map_size;\n\t\t\tdouble z1 = view_space->object_center_world(2) - map_size;\n\t\t\tdouble z2 = view_space->object_center_world(2) + map_size;\n\t\t\tconvex_3d.push_back(Eigen::Vector4d(x1, y1, z1, 1));\n\t\t\tconvex_3d.push_back(Eigen::Vector4d(x1, y2, z1, 1));\n\t\t\tconvex_3d.push_back(Eigen::Vector4d(x2, y1, z1, 1));\n\t\t\tconvex_3d.push_back(Eigen::Vector4d(x2, y2, z1, 1));\n\t\t\tconvex_3d.push_back(Eigen::Vector4d(x1, y1, z2, 1));\n\t\t\tconvex_3d.push_back(Eigen::Vector4d(x1, y2, z2, 1));\n\t\t\tconvex_3d.push_back(Eigen::Vector4d(x2, y1, z2, 1));\n\t\t\tconvex_3d.push_back(Eigen::Vector4d(x2, y2, z2, 1));\n\t\t\tvoxel_information->convex = convex_3d;\n\t\t\t//分配视点的射线生成器\n\t\t\tthread** ray_caster = new thread * [view_space->views.size()];\n\t\t\tfor (int i = 0; i < view_space->views.size(); i++) {\n\t\t\t\t//对该视点分发生成射线的线程\n\t\t\t\tray_caster[i] = new thread(ray_cast_thread_process, &ray_num, rays_info, rays_map, views_to_rays_map, rays_to_viwes_map, octo_model, voxel_information, view_space, &color_intrinsics, i);\n\t\t\t}\n\t\t\t//等待每个视点射线生成器计算完成\n\t\t\tfor (int i = 0; i < view_space->views.size(); i++) {\n\t\t\t\t(*ray_caster[i]).join();\n\t\t\t}\n\t\t\tcout << \"ray_num is \" << ray_num << endl;\n\t\t\tcout << \"All views' rays generated with executed time \" << clock() - now_time << \" ms. Startring compution.\" << endl;\n\t\t}\n\t\t//为每条射线分配一个线程\n\t\tnow_time = clock();\n\t\tthread** rays_process = new thread * [ray_num];\n\t\tfor (int i = 0; i < ray_num; i++) {\n\t\t\trays_info[i]->clear();\n\t\t\trays_process[i] = new thread(ray_information_thread_process, i, rays_info, rays_map, occupancy_map, object_weight, octo_model, voxel_information, view_space, method);\n\t\t}\n\t\t//等待射线计算完成\n\t\tfor (int i = 0; i < ray_num; i++) {\n\t\t\t(*rays_process[i]).join();\n\t\t}\n\t\tdouble cost_time = clock() - now_time;\n\t\tcout << \"All rays' threads over with executed time \" << cost_time << \" ms.\" << endl;\n\t\tshare_data->access_directory(share_data->save_path + \"/run_time\");\n\t\tofstream fout(share_data->save_path + \"/run_time/IG\" + to_string(view_space->id) + \".txt\");\n\t\tfout << cost_time << endl;\n\t\tnow_time = clock();\n\t\tthread** view_gain = new thread * [view_space->views.size()];\n\t\tfor (int i = 0; i < view_space->views.size(); i++) {\n\t\t\t//对该视点分发信息统计的线程\n\t\t\tview_gain[i] = new thread(information_gain_thread_process, rays_info, views_to_rays_map, view_space, i);\n\t\t}\n\t\t//等待每个视点信息统计完成\n\t\tfor (int i = 0; i < view_space->views.size(); i++) {\n\t\t\t(*view_gain[i]).join();\n\t\t}\n\t\tcout << \"All views' gain threads over with executed time \" << clock() - now_time << \" ms.\" << endl;\n\t}\n};\n\nvoid information_gain_thread_process(Ray_Information** rays_info, unordered_map<int, vector<int>>* views_to_rays_map, View_Space* view_space, int pos) {\n\t//视点的每个相关射线信息加入视点\n\tfor (vector<int>::iterator it = (*views_to_rays_map)[pos].begin(); it != (*views_to_rays_map)[pos].end(); it++) {\n\t\tview_space->views[pos].information_gain += rays_info[*it]->information_gain;\n\t\tview_space->views[pos].voxel_num += rays_info[*it]->voxel_num;\n\t}\n}\n\nvoid ray_cast_thread_process(int* ray_num, Ray_Information** rays_info, unordered_map<Ray, int, Ray_Hash>* rays_map, unordered_map<int, vector<int>>* views_to_rays_map, unordered_map<int, vector<int>>* rays_to_viwes_map, octomap::ColorOcTree* octo_model, Voxel_Information* voxel_information, View_Space* view_space, rs2_intrinsics* color_intrinsics, int pos) {\n\t//获取视点位姿\n\tview_space->views[pos].get_next_camera_pos(view_space->now_camera_pose_world, view_space->object_center_world);\n\tEigen::Matrix4d view_pose_world = (view_space->now_camera_pose_world * view_space->views[pos].pose.inverse()).eval();\n\t//将三维物体BBX根据视点位姿，投影至图片凸包区域\n\tdouble skip_coefficient = voxel_information->skip_coefficient;\n\t//根据能访问的体素来控制射线遍历，注意间隔跳跃参数\n\tint pixel_interval = color_intrinsics->width;\n\tdouble max_range = 6.0 * view_space->predicted_size;\n\tvector<cv::Point2f> hull;\n\thull = get_convex_on_image(voxel_information->convex, view_pose_world, *color_intrinsics, pixel_interval, max_range, voxel_information->octomap_resolution);\n\t//if (hull.size() != 4 && hull.size() != 5 && hull.size() != 6) cout << \"hull wrong with size \" << hull.size() << endl;\n\t//计算凸包的包围盒\n\tvector<int> boundary;\n\tboundary = get_xmax_xmin_ymax_ymin_in_hull(hull, *color_intrinsics);\n\tint xmax = boundary[0];\n\tint xmin = boundary[1];\n\tint ymax = boundary[2];\n\tint ymin = boundary[3];\n\t//cout << xmax << \" \" << xmin << \" \" << ymax << \" \" << ymin << \" ,\" << pixel_interval <<endl;\n\t//中间数据结构\n\tvector<Ray*> rays;\n\t//int num = 0;\n\t//检查视点的key\n\toctomap::OcTreeKey key_origin;\n\tbool key_origin_have = octo_model->coordToKeyChecked(view_space->views[pos].init_pos(0), view_space->views[pos].init_pos(1), view_space->views[pos].init_pos(2), key_origin);\n\tif (key_origin_have) {\n\t\toctomap::point3d origin = octo_model->keyToCoord(key_origin);\n\t\t//遍历包围盒\n\t\t//srand(pos);\n\t\t//int rr = rand() % 256, gg = rand() % 256, bb = rand() % 256;\n\t\tfor (int x = xmin; x <= xmax; x += (int)(pixel_interval * skip_coefficient))\n\t\t\tfor (int y = ymin; y <= ymax; y += (int)(pixel_interval * skip_coefficient))\n\t\t\t{\n\t\t\t\t//num++;\n\t\t\t\tcv::Point2f pixel(x, y);\n\t\t\t\t//检查是否在凸包区域内部\n\t\t\t\tif (!is_pixel_in_convex(hull, pixel)) continue;\n\t\t\t\t//反向投影找到终点\n\t\t\t\toctomap::point3d end = project_pixel_to_ray_end(x, y, *color_intrinsics, view_pose_world, max_range);\n\t\t\t\t//显示一下\n\t\t\t\t//view_space->viewer->addLine<pcl::PointXYZ>(pcl::PointXYZ(origin(0), origin(1), origin(2)), pcl::PointXYZ(end(0), end(1), end(2)), rr, gg, bb, \"line\" + to_string(pos) + \"-\" + to_string(x) + \"-\" + to_string(y));\n\t\t\t\toctomap::OcTreeKey key_end;\n\t\t\t\toctomap::point3d direction = end - origin;\n\t\t\t\toctomap::point3d end_point;\n\t\t\t\t//越过未知区域，找到终点\n\t\t\t\tbool found_end_point = octo_model->castRay(origin, direction, end_point, true, max_range);\n\t\t\t\tif (!found_end_point) {//未找到终点，设置终点为最大距离\n\t\t\t\t\tend_point = origin + direction.normalized() * max_range; // use max range instead of stopping at the unknown       found_endpoint = true;     \n\t\t\t\t}\n\t\t\t\t//检查一下末端是否在地图限制范围内，且命中BBX\n\t\t\t\tbool key_end_have = octo_model->coordToKeyChecked(end_point, key_end);\n\t\t\t\tif (key_end_have) {\n\t\t\t\t\t//生成射线\n\t\t\t\t\toctomap::KeyRay* ray_set = new octomap::KeyRay();\n\t\t\t\t\t//获取射线数组，不包含末节点\n\t\t\t\t\tbool point_on_ray_getted = octo_model->computeRayKeys(origin, end_point, *ray_set);\n\t\t\t\t\tif (!point_on_ray_getted) cout << \"Warning. ray cast with wrong max_range.\" << endl;\n\t\t\t\t\tif (ray_set->size() > 950) cout << ray_set->size() << \" rewrite the vector size in octreekey.h.\" << endl;\n\t\t\t\t\t//把终点放入射线组\n\t\t\t\t\tray_set->addKey(key_end);\n\t\t\t\t\t//第一个非空节点作为射线起点，尾巴开始最后一个非空元素作为射线终点\n\t\t\t\t\toctomap::KeyRay::iterator last = ray_set->end();\n\t\t\t\t\tlast--;\n\t\t\t\t\twhile (last != ray_set->begin() && (octo_model->search(*last) == NULL)) last--;\n\t\t\t\t\t//二分第一个非空元素\n\t\t\t\t\toctomap::KeyRay::iterator l = ray_set->begin();\n\t\t\t\t\toctomap::KeyRay::iterator r = last;\n\t\t\t\t\toctomap::KeyRay::iterator mid = l + (r - l) / 2;\n\t\t\t\t\twhile (mid != r) {\n\t\t\t\t\t\tif (octo_model->search(*mid) != NULL)\n\t\t\t\t\t\t\tr = mid;\n\t\t\t\t\t\telse\n\t\t\t\t\t\t\tl = mid + 1;\n\t\t\t\t\t\tmid = l + (r - l) / 2;\n\t\t\t\t\t}\n\t\t\t\t\toctomap::KeyRay::iterator first = mid;\n\t\t\t\t\twhile (first  != ray_set->end() && (octo_model->keyToCoord(*first).x() < view_space->object_center_world(0) - view_space->predicted_size || octo_model->keyToCoord(*first).x() > view_space->object_center_world(0) + view_space->predicted_size\n\t\t\t\t\t\t|| octo_model->keyToCoord(*first).y() < view_space->object_center_world(1) - view_space->predicted_size || octo_model->keyToCoord(*first).y() > view_space->object_center_world(1) + view_space->predicted_size\n\t\t\t\t\t\t|| octo_model->keyToCoord(*first).z() < view_space->object_center_world(2) - view_space->predicted_size || octo_model->keyToCoord(*first).z() > view_space->object_center_world(2) + view_space->predicted_size)) first++;\n\t\t\t\t\t//如果没有非空元素，直接丢弃射线\n\t\t\t\t\tif (last - first < 0) {\n\t\t\t\t\t\tdelete ray_set;\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\toctomap::KeyRay::iterator stop = last;\n\t\t\t\t\tstop++;\n\t\t\t\t\t//显示一下\n\t\t\t\t\t//while (octo_model->keyToCoord(*first).x() < view_space->object_center_world(0) - view_space->predicted_size || octo_model->keyToCoord(*first).x() > view_space->object_center_world(0) + view_space->predicted_size\n\t\t\t\t\t//\t|| octo_model->keyToCoord(*first).y() < view_space->object_center_world(1) - view_space->predicted_size || octo_model->keyToCoord(*first).y() > view_space->object_center_world(1) + view_space->predicted_size\n\t\t\t\t\t//\t|| octo_model->keyToCoord(*first).z() < min(view_space->height_of_ground, view_space->object_center_world(2) - view_space->predicted_size) || octo_model->keyToCoord(*first).z() > view_space->object_center_world(2) + view_space->predicted_size) first++;\n\t\t\t\t\t//octomap::point3d ss = octo_model->keyToCoord(*first);\n\t\t\t\t\t//octomap::point3d ee = octo_model->keyToCoord(*last);\n\t\t\t\t\t//view_space->viewer->addLine<pcl::PointXYZ>(pcl::PointXYZ(ss(0), ss(1), ss(2)), pcl::PointXYZ(ee(0), ee(1), ee(2)), rr, gg, bb, \"line\" + to_string(pos) + \"-\" + to_string(x) + \"-\" + to_string(y));\n\t\t\t\t\t//将射线加入视点的集合，第一个元素与最后一个元素key+数组+头+尾\n\t\t\t\t\tRay* ray = new Ray(*first, *last, ray_set, first, stop);\n\t\t\t\t\trays.push_back(ray);\n\t\t\t\t}\n\t\t\t}\n\t}\n\telse {\n\t\tcout << pos << \"th view out of map.check.\" << endl;\n\t}\n\t//cout << \"rays \" << rays.size() <<\" num \"<<num<< endl;\n\t//该视点射线下标的数组\n\tvector<int> ray_ids;\n\tray_ids.resize(rays.size());\n\t//注意公用的数据结构要加锁\n\tvoxel_information->mutex_rays.lock();\n\t//获取当前射线的位置\n\tint ray_id = (*ray_num);\n\tfor (int i = 0; i < rays.size(); i++) {\n\t\t//对于这些射线，hash查询一下是否有重复的\n\t\tauto hash_this_ray = rays_map->find(*rays[i]);\n\t\t//如果没有重复的，就保存该射线\n\t\tif (hash_this_ray == rays_map->end()) {\n\t\t\t(*rays_map)[*rays[i]] = ray_id;\n\t\t\tray_ids[i] = ray_id;\n\t\t\t//创造射线计算类\n\t\t\trays_info[ray_id] = new Ray_Information(rays[i]);\n\t\t\tvector<int> view_ids;\n\t\t\tview_ids.push_back(pos);\n\t\t\t(*rays_to_viwes_map)[ray_id] = view_ids;\n\t\t\tray_id++;\n\t\t}\n\t\t//如果有重复的，说明其他视点也算到了该射线，就把相应的id放入下标数组\n\t\telse {\n\t\t\tray_ids[i] = hash_this_ray->second;\n\t\t\tdelete rays[i]->ray_set;\n\t\t\t//其他视点已经记录的射线，把本视点的记录放进去\n\t\t\tvector<int> view_ids = (*rays_to_viwes_map)[ray_ids[i]];\n\t\t\tview_ids.push_back(pos);\n\t\t\t(*rays_to_viwes_map)[ray_ids[i]] = view_ids;\n\t\t}\n\t}\n\t//更新射线数目\n\t(*ray_num) = ray_id;\n\t//更新视点映射的射线数组\n\t(*views_to_rays_map)[pos] = ray_ids;\n\t//释放锁\n\tvoxel_information->mutex_rays.unlock();\n}\n\ninline vector<int> get_xmax_xmin_ymax_ymin_in_hull(vector<cv::Point2f>& hull, rs2_intrinsics& color_intrinsics) {\n\tfloat xmax = 0, xmin = color_intrinsics.width - 1, ymax = 0, ymin = color_intrinsics.height - 1;\n\tfor(int i = 0;i< hull.size();i++){\n\t\txmax = max(xmax, hull[i].x);\n\t\txmin = min(xmin, hull[i].x);\n\t\tymax = max(ymax, hull[i].y);\n\t\tymin = min(ymin, hull[i].y);\n\t}\n\tvector<int> boundary;\n\tboundary.push_back((int)floor(xmax));\n\tboundary.push_back((int)floor(xmin));\n\tboundary.push_back((int)floor(ymax));\n\tboundary.push_back((int)floor(ymin));\n\treturn boundary;\n}\n\ninline bool is_pixel_in_convex(vector<cv::Point2f>& hull, cv::Point2f& pixel) {\n\tdouble hull_value = pointPolygonTest(hull, pixel, false);\n\treturn hull_value >= 0;\n}\n\ninline vector<cv::Point2f> get_convex_on_image(vector<Eigen::Vector4d>& convex_3d, Eigen::Matrix4d& now_camera_pose_world, rs2_intrinsics& color_intrinsics,int& pixel_interval,double& max_range,double& octomap_resolution) {\n\t//投影立方体顶点至图像坐标系\n\tdouble now_range = 0;\n\tvector<cv::Point2f> contours;\n\tfor (int i = 0; i < convex_3d.size(); i++) {\n\t\tEigen::Vector4d vertex = now_camera_pose_world.inverse() * convex_3d[i];\n\t\tfloat point[3] = { vertex(0), vertex(1),vertex(2) };\n\t\tfloat pixel[2];\n\t\trs2_project_point_to_pixel(pixel, &color_intrinsics, point);\n\t\tcontours.push_back(cv::Point2f(pixel[0], pixel[1]));\n\t\t//cout << pixel[0] << \" \" << pixel[1] << endl;\n\t\t//计算一下最远点离开视点距离\n\t\tEigen::Vector4d view_pos(now_camera_pose_world(0, 3), now_camera_pose_world(1, 3), now_camera_pose_world(2, 3), 1);\n\t\tnow_range = max(now_range, (view_pos - convex_3d[i]).norm());\n\t}\n\tmax_range = min(max_range, now_range);\n\t//计算凸包\n\tvector<cv::Point2f> hull;\n\tconvexHull(contours, hull, false, true);\n\tif (!cv::isContourConvex(hull)) {\n\t\tcout << \"no convex. check BBX.\" << endl;\n\t\treturn contours;\n\t}\n\t//计算空间最远两点距离，计算像素最远两点距离，根据地图分辨率得到像素偏移\n\tdouble pixel_dis = 0;\n\tdouble space_dis = 0;\n\tfor (int i = 0; i < hull.size(); i++)\n\t\tfor (int j = 0; j < hull.size(); j++) if(i!=j){\n\t\t\tEigen::Vector2d pixel_start(hull[i].x, hull[i].y);\n\t\t\tEigen::Vector2d pixel_end(hull[j].x, hull[j].y);\n\t\t\tpixel_dis = max(pixel_dis,(pixel_start - pixel_end).norm());\n\t\t\tspace_dis = max(space_dis, (convex_3d[i] - convex_3d[j]).norm());\n\t\t}\n\tpixel_interval = (int)(pixel_dis / space_dis * octomap_resolution);\n\treturn hull;\n}\n\ninline octomap::point3d project_pixel_to_ray_end(int x,int y, rs2_intrinsics& color_intrinsics, Eigen::Matrix4d& now_camera_pose_world,float max_range) {\n\tfloat pixel[2] = { x ,y };\n\tfloat point[3];\n\trs2_deproject_pixel_to_point(point, &color_intrinsics, pixel, max_range);\n\tEigen::Vector4d point_world(point[0], point[1], point[2],1);\n\tpoint_world = now_camera_pose_world * point_world;\n\treturn octomap::point3d(point_world(0), point_world(1), point_world(2));\n}\n\nvoid ray_information_thread_process(int ray_id, Ray_Information** rays_info, unordered_map<Ray, int, Ray_Hash>* rays_map, unordered_map<octomap::OcTreeKey, double, octomap::OcTreeKey::KeyHash>* occupancy_map, unordered_map<octomap::OcTreeKey, double, octomap::OcTreeKey::KeyHash>* object_weight, octomap::ColorOcTree* octo_model, Voxel_Information* voxel_information, View_Space* view_space, short method )\n{\n\t//由于检查过，所以第一个节点就是非空节点\n\toctomap::KeyRay::iterator first = rays_info[ray_id]->ray->start;\n\toctomap::KeyRay::iterator last = rays_info[ray_id]->ray->stop;\n\tlast--;\n\tfor (octomap::KeyRay::iterator it = rays_info[ray_id]->ray->start; it != rays_info[ray_id]->ray->stop; ++it) {\n\t\t//从hash表里查询该key\n\t\tauto hash_this_key = (*occupancy_map).find(*it);\n\t\t//找不到节点就下一个\n\t\tif (hash_this_key== (*occupancy_map).end()) {\n\t\t\tif (method == RSE && it == last) rays_info[ray_id]->information_gain = 0;\n\t\t\tcontinue;\n\t\t}\n\t\t//读取节点概率值\n\t\tdouble occupancy = hash_this_key->second;\n\t\t//检查一下当前节点是否被占据\n\t\tbool voxel_occupied = voxel_information->is_occupied(occupancy);\n\t\t//检查一下节点是否未知\n\t\tbool voxel_unknown = voxel_information->is_unknown(occupancy);\n\t\t//读取一下节点为物体表面率\n\t\tdouble on_object = voxel_information->voxel_object(*it, object_weight);\n\t\t//如果被占据，那就是最后一个节点了\n\t\tif (voxel_occupied) last = it;\n\t\t//如果free，则初始节点要更新\n\t\tif (it==first && (!voxel_unknown&&!voxel_occupied)) first = it;\n\t\t//判断是否最后一个节点\n\t\tbool is_end = (it == last);\n\t\t//统计信息熵\n\t\trays_info[ray_id]->information_gain = information_function(method, rays_info[ray_id]->information_gain, voxel_information->entropy(occupancy), rays_info[ray_id]->visible, voxel_unknown, rays_info[ray_id]->previous_voxel_unknown, is_end, voxel_occupied, on_object, rays_info[ray_id]->object_visible);\n\t\trays_info[ray_id]->object_visible *= (1 - on_object);\n\t\tif(method == OursIG) rays_info[ray_id]->visible *= voxel_information->get_voxel_visible(occupancy);\n\t\telse rays_info[ray_id]->visible *= occupancy;\n\t\trays_info[ray_id]->voxel_num++;\n\t\t//如果是最后了就退出\n\t\tif (is_end) break;\n\t}\n\twhile (last - first < -1) first--;\n\tlast++;\n\t//更新stop为最后一个节点后一个迭代器\n\trays_info[ray_id]->ray->stop = last;\n\t//更新start为第一个迭代器\n\trays_info[ray_id]->ray->start = first;\n}\n\ninline double information_function(short& method,double& ray_informaiton,double voxel_information,double& visible,bool& is_unknown, bool& previous_voxel_unknown,bool& is_endpoint,bool& is_occupied,double& object,double& object_visible) {\n\tdouble final_information = 0;\n\tswitch (method) {\n\tcase OursIG:\n\t\tif (is_unknown) {\n\t\t\tfinal_information = ray_informaiton + object * visible * voxel_information;\n\t\t}\n\t\telse {\n\t\t\tfinal_information = ray_informaiton;\n\t\t}\n\t\tbreak;\n\tcase OA:\n\t\tfinal_information = ray_informaiton + visible * voxel_information;\n\t\tbreak;\n\tcase UV:\n\t\tif(is_unknown) final_information = ray_informaiton + visible * voxel_information;\n\t\telse final_information = ray_informaiton;\n\t\tbreak;\n\tcase RSE:\n\t\tif (is_endpoint) {\n\t\t\tif (previous_voxel_unknown) {\n\t\t\t\tif (is_occupied) final_information = ray_informaiton + visible * voxel_information;\n\t\t\t\telse final_information = 0;\n\t\t\t}\n\t\t\telse final_information = 0;\n\t\t}\n\t\telse {\n\t\t\tif (is_unknown) {\n\t\t\t\tprevious_voxel_unknown = true;\n\t\t\t\tfinal_information = ray_informaiton + visible * voxel_information;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tprevious_voxel_unknown = false;\n\t\t\t\tfinal_information = 0;\n\t\t\t}\n\t\t}\n\t\tbreak;\n\tcase APORA:\n\t\tif (is_unknown) {\n\t\t\tfinal_information = ray_informaiton + object * object_visible * voxel_information;\n\t\t}\n\t\telse {\n\t\t\tfinal_information = ray_informaiton;\n\t\t}\n\t\tbreak;\n\tcase Kr:\n\t\tif (is_endpoint) {\n\t\t\tif (is_occupied) final_information = ray_informaiton + voxel_information;\n\t\t\telse final_information = 0;\n\t\t}\n\t\telse final_information = ray_informaiton + voxel_information;\n\t\tbreak;\n\t}\n\treturn final_information;\n}\n\ninline int frontier_check(octomap::point3d node, octomap::ColorOcTree* octo_model, Voxel_Information* voxel_information, double octomap_resolution) {\n\tint free_cnt = 0;\n\tint occupied_cnt = 0;\n\tfor (int i = -1; i <= 1; i++)\n\t\tfor (int j = -1; j <= 1; j++)\n\t\t\tfor (int k = -1; k <= 1; k++) \n\t\t\t{\n\t\t\t\tif (i == 0 && j == 0 && k == 0) continue;\n\t\t\t\tdouble x = node.x() + i * octomap_resolution;\n\t\t\t\tdouble y = node.y() + j * octomap_resolution;\n\t\t\t\tdouble z = node.z() + k * octomap_resolution;\n\t\t\t\toctomap::point3d neighbour(x, y, z);\n\t\t\t\toctomap::OcTreeKey neighbour_key;  bool neighbour_key_have = octo_model->coordToKeyChecked(neighbour, neighbour_key);\n\t\t\t\tif (neighbour_key_have) {\n\t\t\t\t\toctomap::ColorOcTreeNode* neighbour_voxel = octo_model->search(neighbour_key);\n\t\t\t\t\tif (neighbour_voxel != NULL) {\n\t\t\t\t\t\tfree_cnt += voxel_information->voxel_free(neighbour_voxel) == true ? 1 : 0;\n\t\t\t\t\t\toccupied_cnt += voxel_information->voxel_occupied(neighbour_voxel) == true ? 1 : 0;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t//edge\n\tif (free_cnt >= 1 && occupied_cnt >= 1) return 2;\n\t//边界\n\tif (free_cnt >= 1) return 1;\n\t//啥也不是\n\treturn 0;\n}\n\ninline double distance_function(double distance,double alpha) {\n\treturn exp(-pow2(alpha)*distance);\n}\n\n//Max Flow\nclass MCMF {\npublic:\n\tstruct Edge {\n\t\tint from, to, cap, flow;\n\t\tdouble cost;\n\t\tEdge(int u, int v, int c, int f, double w)\n\t\t\t: from(u), to(v), cap(c), flow(f), cost(w) {}\n\t};\n\n\tconst int INF = 0x3f3f3f3f;\n\tint n, m;\n\tvector<Edge> edges;\n\tvector<vector<int>> G;\n\tvector<int> inq, p, a;\n\tvector<double> d;\n\tdouble eps = 1e-3;\n\tbool isZero(const double& val) { return abs(val) < eps; }\n\n\tvoid init(int n) {\n\t\tthis->n = n;\n\t\tG.resize(n);\n\t\td.resize(n);\n\t\ta.resize(n);\n\t\tp.resize(n);\n\t\tinq.resize(n);\n\n\t\tfor (int i = 0; i < n; i++) {\n\t\t\tG[i].clear();\n\t\t\td[i] = a[i] = p[i] = inq[i] = 0;\n\t\t}\n\t\tedges.clear();\n\t}\n\n\tvoid AddEdge(int from, int to, int cap, double cost) {\n\t\t//cerr << from << ' ' << to << ' ' << cap << ' ' << cost << endl;\n\t\tedges.push_back(Edge(from, to, cap, 0, cost));\n\t\tedges.push_back(Edge(to, from, 0, 0, -cost));\n\t\tm = edges.size();\n\t\tG[from].push_back(m - 2);\n\t\tG[to].push_back(m - 1);\n\t}\n\n\tbool BellmanFord(int s, int t, int& flow, double& cost) {\n\t\tfor (int i = 0; i < n; i++) d[i] = INF;\n\t\tfor (int i = 0; i < n; i++) inq[i] = 0;\n\t\td[s] = 0;\n\t\tinq[s] = 1;\n\t\tp[s] = 0;\n\t\ta[s] = INF;\n\t\tqueue<int> Q;\n\t\tQ.push(s);\n\t\twhile (!Q.empty()) {\n\t\t\tint u = Q.front();\n\t\t\tQ.pop();\n\t\t\tinq[u] = 0;\n\t\t\tfor (int i = 0; i < G[u].size(); i++) {\n\t\t\t\tEdge& e = edges[G[u][i]];\n\t\t\t\tif (e.cap > e.flow && d[e.to] > d[u] + e.cost) {\n\t\t\t\t\td[e.to] = d[u] + e.cost;\n\t\t\t\t\tp[e.to] = G[u][i];\n\t\t\t\t\ta[e.to] = min(a[u], e.cap - e.flow);\n\t\t\t\t\tif (!inq[e.to]) {\n\t\t\t\t\t\tQ.push(e.to);\n\t\t\t\t\t\tinq[e.to] = 1;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif (d[t] == INF) return false;  // 当没有可增广的路时退出\n\t\tflow += a[t];\n\t\tcost += d[t] * a[t];\n\t\tfor (int u = t; u != s; u = edges[p[u]].from) {\n\t\t\tedges[p[u]].flow += a[t];\n\t\t\tedges[p[u] ^ 1].flow -= a[t];\n\t\t}\n\t\treturn true;\n\t}\n\n\tvector<int> work(const vector<vector<pair<int, double>>>& vec) {\n\t\tint nn = vec.size();\n\t\tint S = nn, T = nn + 1;\n\t\tinit(T + 2);\n\n\t\tvector<bool> vis(nn);\n\t\tfor (int u = 0; u < nn; u++) {\n\t\t\tfor (auto& e : vec[u]) {\n\t\t\t\tint v = e.first;\n\t\t\t\tdouble w = e.second;\n\t\t\t\tif (!isZero(w)) {\n\t\t\t\t\tif (!vis[u]) {\n\t\t\t\t\t\tAddEdge(S, u, 1, 0);\n\t\t\t\t\t\tvis[u] = true;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tif (!vis[v]) {\n\t\t\t\t\t\tAddEdge(v, T, INF, 0);\n\t\t\t\t\t\tvis[v] = true;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tAddEdge(u, v, INF, -w);\n\t\t\t}\n\t\t}\n\t\tint flow = 0;\n\t\tdouble cost = 0;\n\t\twhile (BellmanFord(S, T, flow, cost))\n\t\t\t;\n\n\t\t//cerr << \"flow = \" << flow << endl;\n\t\t//cerr << \"cost = \" << cost << endl;\n\n\t\tvector<int> ret;\n\t\t//cerr << \"ret: \";\n\t\tfor (auto& e : edges)\n\t\t\tif (e.to == T)\n\t\t\t\tif (e.flow > 0) {\n\t\t\t\t\tret.push_back(e.from);\n\t\t\t\t\t//cerr << \"(\" << e.from << \", \" << e.flow << \") \";\n\t\t\t\t}\n\t\t//cerr << endl;\n\n\t\treturn ret;\n\t}\n};\n\n/*\nsolving by Max Flow\n*/\n\nvoid adjacency_list_thread_process(int ray_id, int* ny, int ray_index_shift, int voxel_index_shift, unordered_map<octomap::OcTreeKey, int, octomap::OcTreeKey::KeyHash>* voxel_id_map, vector<vector<pair<int, double>>>* bipartite_list, View_Space* view_space, Views_Information* views_information, Voxel_Information* voxel_information, Share_Data* share_data);\n\nclass views_voxels_MF {\npublic:\n\tint nx, ny, nz;\t\t\t\t\t\t\t\t\t\t//三边的点数，视点数nx，射线数ny,体素数nz\n\tvector<vector<pair<int, double>>>* bipartite_list;\t//邻接表\n\tView_Space* view_space;\n\tViews_Information* views_information;\n\tVoxel_Information* voxel_information;\n\tShare_Data* share_data;\n\tunordered_map<octomap::OcTreeKey, int, octomap::OcTreeKey::KeyHash>* voxel_id_map;\t//体素下标\n\tMCMF* mcmf;\n\tvector<int> view_id_set;\n\n\tvoid solve() {\n\t\tdouble now_time = clock();\n\t\tview_id_set = mcmf->work(*bipartite_list);\n\t\tdouble cost_time = clock() - now_time;\n\t\tcout << \"flow network solved with executed time \" << cost_time << \" ms.\" << endl;\n\t\tcout << view_id_set.size() << \" views getted by max flow.\" << endl;\n\t\tshare_data->access_directory(share_data->save_path + \"/run_time\");\n\t\tofstream fout(share_data->save_path + \"/run_time/MF\" + to_string(view_space->id) + \".txt\");\n\t\tfout << cost_time << '\\t' << view_id_set.size() << endl;\n\t}\n\n\tvector<int> get_view_id_set() {\n\t\treturn view_id_set;\n\t}\n\n\tviews_voxels_MF(int _nx, View_Space* _view_space, Views_Information* _views_information, Voxel_Information* _voxel_information, Share_Data* _share_data) {\n\t\tdouble now_time = clock();\n\t\tview_space = _view_space;\n\t\tviews_information = _views_information;\n\t\tvoxel_information = _voxel_information;\n\t\tshare_data = _share_data;\n\t\t//视点按照id排序，并建立三分图邻接表\n\t\tsort(view_space->views.begin(), view_space->views.end(), view_id_compare);\n\t\tnx = _nx;\n\t\tny = views_information->ray_num;\n\t\tbipartite_list = new vector<vector<pair<int, double>>>;\n\t\tbipartite_list->resize(nx + ny + share_data->voxels_in_BBX);\n\t\t//建立体素的id表\n\t\tvoxel_id_map = new unordered_map<octomap::OcTreeKey, int, octomap::OcTreeKey::KeyHash>;\n\t\t//并行遍历每条射线上的体素累加至对应视点\n\t\tnz = 0;\n\t\tthread** adjacency_list_process = new thread * [views_information->ray_num];\n\t\tfor (int i = 0; i < views_information->ray_num; i++) {\n\t\t\tadjacency_list_process[i] = new thread(adjacency_list_thread_process, i, &nz, nx, nx + ny, voxel_id_map, bipartite_list, view_space, views_information, voxel_information, share_data);\n\t\t}\n\t\tfor (int i = 0; i < views_information->ray_num; i++) {\n\t\t\t(*adjacency_list_process[i]).join();\n\t\t}\n\t\t//输出一下具体的图大小\n\t\tif (nz != voxel_id_map->size()) cout << \"node_z wrong.\" << endl;\n\t\tint num_of_all_edge = 0;\n\t\tint num_of_view_edge = 0;\n\t\tfor (int i = 0; i < bipartite_list->size(); i++) {\n\t\t\tnum_of_all_edge += (*bipartite_list)[i].size();\n\t\t\tif (i > nx && i < nx + ny) num_of_view_edge += (*bipartite_list)[i].size();\n\t\t}\n\t\tcout << \"Full edge is \" << num_of_all_edge << \". View edge(in) is \" << num_of_view_edge << \". Voexl edge(out) is \"<< num_of_all_edge - num_of_view_edge<< \".\"<< endl;\n\t\tcout << \"adjacency list with interested voxels num \" << ny << \" getted with executed time \" << clock() - now_time << \" ms.\" << endl;\n\t\tmcmf = new MCMF();\n\t}\n\n\t~views_voxels_MF() {\n\t\tdelete bipartite_list;\n\t\tdelete voxel_id_map;\n\t\tdelete mcmf;\n\t}\n};\n\nvoid adjacency_list_thread_process(int ray_id, int* nz, int ray_index_shift, int voxel_index_shift, unordered_map<octomap::OcTreeKey, int, octomap::OcTreeKey::KeyHash>* voxel_id_map, vector<vector<pair<int, double>>>* bipartite_list, View_Space* view_space, Views_Information* views_information, Voxel_Information* voxel_information, Share_Data* share_data) {\n\t//该射线被哪些视点看到，加入图中\n\tvector<int> views_id = (*views_information->rays_to_viwes_map)[ray_id];\n\tfor (int i = 0; i < views_id.size(); i++)\n\t\t(*bipartite_list)[ray_id + ray_index_shift].push_back(make_pair(views_id[i], 0.0));\n\t//仅保留感兴趣体素\n\tdouble visible = 1.0;\n\toctomap::KeyRay::iterator first = views_information->rays_info[ray_id]->ray->start;\n\toctomap::KeyRay::iterator last = views_information->rays_info[ray_id]->ray->stop;\n\tfor (octomap::KeyRay::iterator it = views_information->rays_info[ray_id]->ray->start; it != views_information->rays_info[ray_id]->ray->stop; ++it) {\n\t\t//从hash表里查询该key\n\t\tauto hash_this_key = (*views_information->occupancy_map).find(*it);\n\t\t//找不到节点就下一个\n\t\tif (hash_this_key == (*views_information->occupancy_map).end()) continue;\n\t\t//读取节点概率值\n\t\tdouble occupancy = hash_this_key->second;\n\t\t//读取一下节点为物体表面率\n\t\tdouble on_object = voxel_information->voxel_object(*it, views_information->object_weight);\n\t\t//统计信息熵\n\t\tdouble information_gain = on_object * visible * voxel_information->entropy(occupancy);\n\t\tvisible *= voxel_information->get_voxel_visible(occupancy);\n\t\tif (information_gain > share_data->interesting_threshold) {\n\t\t\toctomap::OcTreeKey node_y = *it;\n\t\t\tint voxel_id;\n\t\t\tvoxel_information->mutex_rays.lock();\n\t\t\tauto hash_this_node = voxel_id_map->find(node_y);\n\t\t\t//如果没有记录，就视为新的体素\n\t\t\tif (hash_this_node == voxel_id_map->end()) {\n\t\t\t\tvoxel_id = (*nz) + voxel_index_shift;\n\t\t\t\t(*voxel_id_map)[node_y] = voxel_id;\n\t\t\t\t(*nz)++;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tvoxel_id = hash_this_node->second;\n\t\t\t}\n\t\t\tvoxel_information->mutex_rays.unlock();\n\t\t\t//对于每个视点，统计该体素的id与价值\n\t\t\tfor (int i = 0; i < views_id.size(); i++)\n\t\t\t{\n\t\t\t\t(*voxel_information->mutex_voxels[voxel_id - voxel_index_shift]).lock();\n\t\t\t\t(*bipartite_list)[voxel_id].push_back(make_pair(ray_id + ray_index_shift, information_gain));\n\t\t\t\t(*voxel_information->mutex_voxels[voxel_id - voxel_index_shift]).unlock();\n\t\t\t}\n\t\t}\n\t}\n}\n", "meta": {"hexsha": "d3a5b055312418ed78be98b7c73c274a5089c115", "size": 41678, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "nbv_simulation/Information.hpp", "max_stars_repo_name": "psc0628/NBV-Simulation", "max_stars_repo_head_hexsha": "9eaa208ac63218b2d3cc1c32b3d061fb7df2a62b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-12-22T17:55:33.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-22T17:55:33.000Z", "max_issues_repo_path": "nbv_simulation/Information.hpp", "max_issues_repo_name": "psc0628/NBV-Simulation", "max_issues_repo_head_hexsha": "9eaa208ac63218b2d3cc1c32b3d061fb7df2a62b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "nbv_simulation/Information.hpp", "max_forks_repo_name": "psc0628/NBV-Simulation", "max_forks_repo_head_hexsha": "9eaa208ac63218b2d3cc1c32b3d061fb7df2a62b", "max_forks_repo_licenses": ["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.2653465347, "max_line_length": 407, "alphanum_fraction": 0.6934833725, "num_tokens": 13711, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7879312056025699, "lm_q2_score": 0.43782349911420193, "lm_q1q2_score": 0.3449747974981888}}
{"text": "//==================================================================================================\n/*!\n  @file\n\n  @copyright 2016 NumScale SAS\n\n  Distributed under the Boost Software License, Version 1.0.\n  (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\n*/\n//==================================================================================================\n#ifndef BOOST_SIMD_ARCH_COMMON_SCALAR_FUNCTION_LOG_HPP_INCLUDED\n#define BOOST_SIMD_ARCH_COMMON_SCALAR_FUNCTION_LOG_HPP_INCLUDED\n#include <boost/simd/function/std.hpp>\n\n#include <boost/simd/detail/dispatch/function/overload.hpp>\n#include <boost/simd/function/musl.hpp>\n#include <boost/simd/function/std.hpp>\n#include <boost/assert.hpp>\n#include <boost/config.hpp>\n#include <cmath>\n#include <boost/simd/function/bitwise_and.hpp>\n#include <boost/simd/function/dec.hpp>\n#include <boost/simd/function/fma.hpp>\n#include <boost/simd/function/frexp.hpp>\n#include <boost/simd/function/horn.hpp>\n#include <boost/simd/function/musl.hpp>\n#include <boost/simd/function/plain.hpp>\n#include <boost/simd/function/sqr.hpp>\n#include <boost/simd/function/std.hpp>\n\n#include <boost/simd/constant/inf.hpp>\n#include <boost/simd/constant/nan.hpp>\n#include <boost/simd/constant/minf.hpp>\n#include <boost/simd/constant/smallestposval.hpp>\n#include <boost/simd/constant/sqrt_2o_2.hpp>\n\n#include <boost/simd/detail/constant/log_2hi.hpp>\n#include <boost/simd/detail/constant/log_2lo.hpp>\n\n#include <boost/simd/detail/dispatch/meta/as_integer.hpp>\n\nnamespace boost { namespace simd { namespace ext\n{\n  namespace bd = boost::dispatch;\n  namespace bs = boost::simd;\n\n  BOOST_DISPATCH_OVERLOAD ( log_\n                          , (typename A0)\n                          , bd::cpu_\n                          , bs::std_tag\n                          , bd::scalar_< bd::floating_<A0> >\n                          )\n  {\n    BOOST_FORCEINLINE A0 operator() (const std_tag &, A0 a0) const BOOST_NOEXCEPT\n    {\n      return std::log(a0);\n    }\n  };\n\n  BOOST_DISPATCH_OVERLOAD ( log_\n                          , (typename A0)\n                          , bd::cpu_\n                          , bd::scalar_< bd::floating_<A0> >\n                          )\n  {\n    BOOST_FORCEINLINE A0 operator() (A0 a0) const BOOST_NOEXCEPT\n    {\n      return musl_(log)(a0);\n    }\n  };\n\n  BOOST_DISPATCH_OVERLOAD ( log_\n                          , (typename A0)\n                          , bd::cpu_\n                          , bs::musl_tag\n                          , bd::scalar_< bd::single_<A0> >\n                          )\n  {\n  /* origin: FreeBSD /usr/src/lib/msun/src/e_log2f.c */\n  /*\n   * ====================================================\n   * Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved.\n   *\n   * Developed at SunPro, a Sun Microsystems, Inc. business.\n   * Permission to use, copy, modify, and distribute this\n   * software is freely granted, provided that this notice\n   * is preserved.\n   * ====================================================\n   */\n     BOOST_FORCEINLINE A0 operator() (const musl_tag &, A0 x) const BOOST_NOEXCEPT\n    {\n      using uiA0 = bd::as_integer_t<A0, unsigned>;\n      using iA0 = bd::as_integer_t<A0,   signed>;\n      uiA0 ix = bitwise_cast<uiA0>(x);\n      iA0 k = 0;\n      if (ix < 0x00800000 || ix>>31)         /* x < 2**-126  */\n      {\n        if (ix<<1 == 0) return Minf<A0>();  /* log(+-0)=-inf */\n        if (ix>>31) return Nan<A0>();       /* log(-#) = NaN */\n#ifndef BOOST_SIMD_NO_DENORMALS\n        /* subnormal number, scale up x */\n        k -= 25;\n        x *= 33554432.0f;\n        ix = bitwise_cast<iA0>(x);\n#endif\n      }\n      else if (ix >= 0x7f800000)\n      {\n        return x;\n      }\n      else if (ix == 0x3f800000)\n        return 0;\n\n      /* reduce x into [sqrt(2)/2, sqrt(2)] */\n      ix += 0x3f800000 - 0x3f3504f3;\n      k += bitwise_cast<iA0>(ix>>23) - 0x7f;\n      ix = (ix&0x007fffff) + 0x3f3504f3;\n      x =  bitwise_cast<A0>(ix);\n      A0 f = dec(x);\n      A0 s = f/(2.0f + f);\n      A0 z = sqr(s);\n      A0 w = sqr(z);\n      A0 t1= w*horn<A0, 0x3eccce13, 0x3e789e26>(w);\n      A0 t2= z*horn<A0, 0x3f2aaaaa, 0x3e91e9ee>(w);\n      A0 R = t2 + t1;\n      A0 hfsq = 0.5f*sqr(f);\n      A0 dk = k;\n      return  fma(dk, Log_2hi<A0>(), ((fma(s, (hfsq+R), dk*Log_2lo<A0>()) - hfsq) + f));\n    }\n  };\n\n  BOOST_DISPATCH_OVERLOAD ( log_\n                          , (typename A0)\n                          , bd::cpu_\n                          , bs::musl_tag\n                          , bd::scalar_< bd::double_<A0> >\n                          )\n  {\n    BOOST_FORCEINLINE A0 operator() (const musl_tag &, A0 x) const BOOST_NOEXCEPT\n    {\n      using uiA0 = bd::as_integer_t<A0, unsigned>;\n      using iA0 = bd::as_integer_t<A0,   signed>;\n      uiA0 hx = bitwise_cast<uiA0>(x) >> 32;\n      iA0 k = 0;\n      if (hx < 0x00100000 || hx>>31)\n      {\n        if(is_eqz(x)) return Minf<A0>();  /* log(+-0)=-inf */\n        if (hx>>31)   return Nan<A0>();   /* log(-#) = NaN */\n#ifndef BOOST_SIMD_NO_DENORMALS\n        /* subnormal number, scale x up */\n        k -= 54;\n        x *= 18014398509481984.0;\n        hx = bitwise_cast<uiA0>(x) >> 32;\n#endif\n      }\n      else if (hx >= 0x7ff00000)\n      {\n        return x;\n      }\n      else if (x == One<A0>())\n        return Zero<A0>();\n\n      /* reduce x into [sqrt(2)/2, sqrt(2)] */\n      hx += 0x3ff00000 - 0x3fe6a09e;\n      k += bitwise_cast<iA0>(hx>>20) - 0x3ff;\n      hx = (hx&0x000fffff) + 0x3fe6a09e;\n      x = bitwise_cast<A0>( (uint64_t)hx<<32 | (bitwise_and(0xffffffffull, bitwise_cast<uiA0>(x))));\n\n      A0 f = dec(x);\n      A0 hfsq = 0.5*sqr(f);\n      A0 s = f/(2.0f + f);\n      A0 z = sqr(s);\n      A0 w = sqr(z);\n      A0 t1= w*horn<A0, 0x3fd999999997fa04ll, 0x3fcc71c51d8e78afll, 0x3fc39a09d078c69fll > (w);\n      A0 t2= z*horn<A0, 0x3fe5555555555593ll, 0x3fd2492494229359ll\n                      , 0x3fc7466496cb03dell, 0x3fc2f112df3e5244ll> (w);\n      A0 R = t2 + t1;\n      A0 dk = k;\n      return  fma(dk, Log_2hi<A0>(), ((fma(s, (hfsq+R), dk*Log_2lo<A0>()) - hfsq) + f));\n    }\n  };\n\n  BOOST_DISPATCH_OVERLOAD ( log_\n                          , (typename A0)\n                          , bd::cpu_\n                          , bs::plain_tag\n                          , bd::scalar_< bd::floating_<A0> >\n                          )\n  {\n    BOOST_FORCEINLINE A0 operator() (const plain_tag &, A0 x) const BOOST_NOEXCEPT\n    {\n      return musl_(log)(x); //the \"plain\" version of the algorithm is never speedier than the \"musl\" version.\n      // the call is here to allow a scalar fallback to simd calls\n    }\n  };\n\n\n  }\n} }\n\n\n#endif\n", "meta": {"hexsha": "1e424a8e7c1401d93238578ec6cf840c86201042", "size": 6599, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/arch/common/scalar/function/log.hpp", "max_stars_repo_name": "SylvainCorlay/pythran", "max_stars_repo_head_hexsha": "908ec070d837baf77d828d01c3e35e2f4bfa2bfa", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2018-02-25T22:23:33.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-15T15:13:12.000Z", "max_issues_repo_path": "third_party/boost/simd/arch/common/scalar/function/log.hpp", "max_issues_repo_name": "SylvainCorlay/pythran", "max_issues_repo_head_hexsha": "908ec070d837baf77d828d01c3e35e2f4bfa2bfa", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "third_party/boost/simd/arch/common/scalar/function/log.hpp", "max_forks_repo_name": "SylvainCorlay/pythran", "max_forks_repo_head_hexsha": "908ec070d837baf77d828d01c3e35e2f4bfa2bfa", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2017-12-12T12:36:31.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-10T14:27:07.000Z", "avg_line_length": 32.5073891626, "max_line_length": 109, "alphanum_fraction": 0.5259887862, "num_tokens": 1973, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.679178699175393, "lm_q2_score": 0.5078118642792044, "lm_q1q2_score": 0.34489500140698126}}
{"text": "//\n// Created by cc on 2020/8/5.\n//\n\n#include <ros/ros.h>\n#include <trajectory_msgs/JointTrajectoryPoint.h>\n#include <geometry_msgs/PoseStamped.h>\n#include <math.h>\n#include <Eigen/Eigen>\n#include <mavros_msgs/State.h>\n#include <mavros_msgs/CommandBool.h>\n#include <mavros_msgs/SetMode.h>\n\nusing namespace Eigen;\n\nVector3d current_p;\nmavros_msgs::State current_state;\nros::Publisher pva_pub;\n\nvoid positionCallback(const geometry_msgs::PoseStamped::ConstPtr &msg)\n{\n    /// ENU frame to NWU\n    current_p << msg->pose.position.y, -msg->pose.position.x, msg->pose.position.z;\n}\n\nvoid stateCallback(const mavros_msgs::State::ConstPtr &msg)\n{\n    current_state = *msg;\n}\n\n\nvoid setPVA(Eigen::Vector3d p, Eigen::Vector3d v, Eigen::Vector3d a, double yaw=0.0)\n{\n    trajectory_msgs::JointTrajectoryPoint pva_setpoint;\n\n    pva_setpoint.positions.push_back(p(0)); //x\n    pva_setpoint.positions.push_back(p(1)); //y\n    pva_setpoint.positions.push_back(p(2)); //z\n    pva_setpoint.positions.push_back(yaw);\n\n    pva_setpoint.velocities.push_back(v(0));\n    pva_setpoint.velocities.push_back(v(1));\n    pva_setpoint.velocities.push_back(v(2));\n\n    pva_setpoint.accelerations.push_back(a(0));\n    pva_setpoint.accelerations.push_back(a(1));\n    pva_setpoint.accelerations.push_back(a(2));\n\n    pva_pub.publish(pva_setpoint);\n\n//    ROS_INFO_THROTTLE(1.0, \"P x=%f, y=%f, z=%f\", pva_setpoint.positions[0], pva_setpoint.positions[1], pva_setpoint.positions[2]);\n//    ROS_INFO_THROTTLE(1.0, \"V x=%f, y=%f, z=%f\", pva_setpoint.velocities[0], pva_setpoint.velocities[1], pva_setpoint.velocities[2]);\n//    ROS_INFO_THROTTLE(1.0, \"A x=%f, y=%f, z=%f\", pva_setpoint.accelerations[0], pva_setpoint.accelerations[1], pva_setpoint.accelerations[2]);\n\n    ROS_INFO(\"P x=%f, y=%f, z=%f\", pva_setpoint.positions[0], pva_setpoint.positions[1], pva_setpoint.positions[2]);\n    ROS_INFO(\"V x=%f, y=%f, z=%f\", pva_setpoint.velocities[0], pva_setpoint.velocities[1], pva_setpoint.velocities[2]);\n    ROS_INFO(\"A x=%f, y=%f, z=%f\", pva_setpoint.accelerations[0], pva_setpoint.accelerations[1], pva_setpoint.accelerations[2]);\n}\n\n/** This function is to generate state to state trajectory **/\nvoid motion_primitives(Eigen::Vector3d p0, Eigen::Vector3d v0, Eigen::Vector3d a0,\n                       Eigen::Vector3d pf, Eigen::Vector3d vf, Eigen::Vector3d af, double v_max, double delt_t,\n                       Eigen::MatrixXd &p, Eigen::MatrixXd &v, Eigen::MatrixXd &a, Eigen::VectorXd &t)\n{\n    // % Choose the time as running in average velocity\n    // double decay_parameter = 0.5;\n    // double T = 0.2;\n\n    double j_limit = 5;\n    double a_limit = 3;\n    double v_limit = v_max;\n\n//    double T1 = fabs(af(0)-a0(0))/j_limit > fabs(af(1)-a0(1))/j_limit ? fabs(af(0)-a0(0))/j_limit : fabs(af(1)-a0(1))/j_limit;\n//    T1 = T1 > fabs(af(2)-a0(2))/j_limit ? T1 : fabs(af(2)-a0(2))/j_limit;\n    double T2 = fabs(vf(0)-v0(0))/a_limit > fabs(vf(1)-v0(1))/a_limit ? fabs(vf(0)-v0(0))/a_limit : fabs(vf(1)-v0(1))/a_limit;\n    T2 = T2 > fabs(vf(2)-v0(2))/a_limit ? T2 : fabs(vf(2)-v0(2))/a_limit;\n    double T3 = fabs(pf(0)-p0(0))/v_limit > fabs(pf(1)-p0(1))/v_limit ? fabs(pf(0)-p0(0))/v_limit : fabs(pf(1)-p0(1))/v_limit;\n    T3 = T3 > fabs(pf(2)-p0(2))/v_limit ? T3 : fabs(pf(2)-p0(2))/v_limit;\n\n//    double T = T1 > T2 ? T1 : T2;\n//    T = T > T3 ? T : T3;\n    double T = T2;\n    T = T > T3 ? T : T3;\n    T = T < 0.3 ? 0.3 : T;\n\n//    ROS_INFO_THROTTLE(2, \"T=%lf\", T);\n\n    int times = T / delt_t;\n\n    p = Eigen::MatrixXd::Zero(times, 3);\n    v = Eigen::MatrixXd::Zero(times, 3);\n    a = Eigen::MatrixXd::Zero(times, 3);\n    t = Eigen::VectorXd::Zero(times);\n\n    // % calculate optimal jerk controls by Mark W. Miller\n    for(int ii=0; ii<3; ii++)\n    {\n        double delt_a = af(ii) - a0(ii);\n        double delt_v = vf(ii) - v0(ii) - a0(ii)*T;\n        double delt_p = pf(ii) - p0(ii) - v0(ii)*T - 0.5*a0(ii)*T*T;\n\n        //%  if vf is not free\n        double alpha = delt_a*60/pow(T,3) - delt_v*360/pow(T,4) + delt_p*720/pow(T,5);\n        double beta = -delt_a*24/pow(T,2) + delt_v*168/pow(T,3) - delt_p*360/pow(T,4);\n        double gamma = delt_a*3/T - delt_v*24/pow(T,2) + delt_p*60/pow(T,3);\n\n        for(int jj=0; jj<times; jj++)\n        {\n            double tt = (jj + 1)*delt_t;\n            t(jj) = tt;\n            p(jj,ii) = alpha/120*pow(tt,5) + beta/24*pow(tt,4) + gamma/6*pow(tt,3) + a0(ii)/2*pow(tt,2) + v0(ii)*tt + p0(ii);\n            v(jj,ii) = alpha/24*pow(tt,4) + beta/6*pow(tt,3) + gamma/2*pow(tt,2) + a0(ii)*tt + v0(ii);\n            a(jj,ii) = alpha/6*pow(tt,3) + beta/2*pow(tt,2) + gamma*tt + a0(ii);\n        }\n    }\n}\n\nvoid compute_circular_traj(const double r, const double vel, const Eigen::Vector3d p0, const double t,\n                           Eigen::Vector3d &p, Eigen::Vector3d &v, Eigen::Vector3d &a)\n//@requires r > 0 && vel > 0 && t >= 0;\n{\n    const double theta = vel*t/r;\n\n    p(0) = r*cos(theta) + p0(0) - r;\n    p(1) = r*sin(theta) + p0(1);\n    p(2) = p0(2);\n\n    v(0) = -vel*sin(theta);\n    v(1) = vel*cos(theta);\n    v(2) = 0;\n\n    a(0) = -vel*vel/r*cos(theta);\n    a(1) = -vel*vel/r*sin(theta);\n    a(2) = 0;\n}\n\n\nint main(int argc, char** argv) {\n    ros::init(argc, argv, \"control\");\n    ros::NodeHandle nh;\n\n    ros::Subscriber state_sub = nh.subscribe<mavros_msgs::State>(\"/mavros/state\", 1, stateCallback);\n    ros::Subscriber pose_sub = nh.subscribe<geometry_msgs::PoseStamped>(\"/mavros/local_position/pose\", 1, positionCallback);\n\n    pva_pub = nh.advertise<trajectory_msgs::JointTrajectoryPoint>(\"/pva_setpoint\", 1);\n\n    ros::ServiceClient arming_client = nh.serviceClient<mavros_msgs::CommandBool>\n            (\"mavros/cmd/arming\");\n    ros::ServiceClient set_mode_client = nh.serviceClient<mavros_msgs::SetMode>\n            (\"mavros/set_mode\");\n\n    const int LOOPRATE = 40;\n    ros::Rate loop_rate(LOOPRATE);\n\n    // wait for FCU connection\n    while(ros::ok() && !current_state.connected){\n        ros::spinOnce();\n        loop_rate.sleep();\n    }\n\n    mavros_msgs::SetMode offb_set_mode;\n    offb_set_mode.request.custom_mode = \"OFFBOARD\";\n\n    mavros_msgs::CommandBool arm_cmd;\n    arm_cmd.request.value = true;\n    ros::Time last_request = ros::Time::now();\n\n    /// Take off with constant acceleration\n    double delt_t = 1.0 / LOOPRATE;\n    double yaw_target = M_PI / 2.0;\n\n\n    // Vector3d recorded_position = current_p;\n    // while(ros::ok()){\n    //     if(current_state.mode != \"OFFBOARD\" || !current_state.armed){\n    //         setPVA(current_p, Vector3d::Zero(), Vector3d::Zero(), yaw_target);\n    //         recorded_position = current_p;\n    //     }else{\n    //         setPVA(recorded_position, Vector3d::Zero(), Vector3d::Zero(), yaw_target);\n    //     }\n\n    //     loop_rate.sleep();\n    //     ros::spinOnce();\n    // }\n\n    Vector3d circle_p0 = current_p;\n    while(ros::ok()){\n        if(current_state.mode != \"OFFBOARD\" || !current_state.armed){\n            setPVA(current_p, Vector3d::Zero(), Vector3d::Zero(), yaw_target);\n            circle_p0 = current_p;\n        }else{\n            /** Accelerate period **/\n            double circle_speed = 0.8;\n            double circle_radius = 0.6;\n            double acc_t_total = 2 * circle_radius / circle_speed;\n            int acc_times = acc_t_total / delt_t;\n            double acc_a_value = circle_speed * circle_speed / 2 / circle_radius;\n            circle_p0 = current_p;\n            \n            for(int i=0; i<acc_times; i++){\n                Eigen::Vector3d p, v ,a;\n\n                p << circle_p0(0), circle_p0(1) + 0.5 * acc_a_value * (i * delt_t) * (i * delt_t), circle_p0(2);\n                v << 0.0, acc_a_value * i * delt_t, 0.0;\n                a << 0.0, acc_a_value, 0.0;\n                setPVA(p, v, a, yaw_target);\n\n                loop_rate.sleep();\n                ros::spinOnce();\n            }\n            ROS_WARN(\"Accelerate Complete!\");\n\n            /** Now draw circle **/\n            double init_t = 0.0;\n            Vector3d circle_start_point = circle_p0;\n            circle_start_point(1) += circle_radius;\n\n            while(ros::ok()){\n                \n                Eigen::Vector3d p, v ,a;\n                compute_circular_traj(circle_radius, circle_speed, circle_start_point, init_t, p, v, a);\n                setPVA(p, v, a, yaw_target);//a_t.row(last_index));\n                init_t += delt_t;\n\n                if(current_state.mode != \"OFFBOARD\" || !current_state.armed){\n                    break;\n                }\n\n                loop_rate.sleep();\n                ros::spinOnce();\n            }\n\n        }\n        loop_rate.sleep();\n        ros::spinOnce();\n    }\n\n    \n\n    // ROS_INFO(\"Arm and takeoff\");\n    // while(ros::ok()){\n    //     if( current_state.mode != \"OFFBOARD\" &&\n    //         (ros::Time::now() - last_request > ros::Duration(5.0))){\n    //         if( set_mode_client.call(offb_set_mode) &&\n    //             offb_set_mode.response.mode_sent){\n    //             ROS_INFO(\"Offboard enabled\");\n    //         }\n    //         last_request = ros::Time::now();\n    //     } else {\n    //         if( !current_state.armed &&\n    //             (ros::Time::now() - last_request > ros::Duration(5.0))){\n    //             if( arming_client.call(arm_cmd) &&\n    //                 arm_cmd.response.success){\n    //                 ROS_INFO(\"Vehicle armed\");\n    //             }\n    //             last_request = ros::Time::now();\n    //         }\n    //     }\n\n    //     trajectory_msgs::JointTrajectoryPoint pva_setpoint;\n\n    //     if(current_state.mode != \"OFFBOARD\" || !current_state.armed){\n    //         setPVA(current_p, Vector3d::Zero(), Vector3d::Zero(), M_PI);\n    //     }else{\n    //         counter ++;\n    //         double z_sp, vz_sp;\n    //         if(counter < take_off_send_times / 2){\n    //             z_sp = 0.5*take_off_acc*counter*delt_t*counter*delt_t;\n    //             vz_sp = counter*delt_t*take_off_acc;\n    //             Vector3d p_sp(recorded_takeoff_position(0), recorded_takeoff_position(1), z_sp);\n    //             Vector3d v_sp(0, 0, vz_sp);\n    //             setPVA(p_sp, v_sp, Vector3d::Zero(), M_PI);\n\n    //         }else if(counter < take_off_send_times){\n    //             double t_this = (counter-take_off_send_times/2)*delt_t;\n    //             z_sp = take_off_send_times/2*delt_t*take_off_acc*t_this - 0.5*take_off_acc*t_this*t_this;\n    //             vz_sp = take_off_send_times/2*delt_t*take_off_acc - take_off_acc*t_this;\n\n    //             Vector3d p_sp(recorded_takeoff_position(0), recorded_takeoff_position(1), z_sp);\n    //             Vector3d v_sp(0, 0, vz_sp);\n    //             setPVA(p_sp, v_sp, Vector3d::Zero(), M_PI);\n\n    //         }else{\n    //             Vector3d p_sp(recorded_takeoff_position(0), recorded_takeoff_position(1), take_off_height);\n    //             setPVA(p_sp, Vector3d::Zero(), Vector3d::Zero(), M_PI);\n    //             counter --;\n    //         }\n    //     }\n\n    //     if(current_p(2) > take_off_height-0.05){\n    //         ROS_WARN(\"Takeoff Complete!\");\n    //         break;\n    //     }\n\n    //     loop_rate.sleep();\n    //     ros::spinOnce();\n    // }\n\n\n    // /** Take off complete. Go to a point with minimum jerk trajectory **/\n    // double circle_radius = 2;\n\n    // MatrixXd p_t, v_t, a_t;\n    // Eigen::VectorXd t_vector;\n    // Vector3d v0(0.0, 0.0, 0.0);\n    // Vector3d a0(0.0, 0.0, 0.0);\n\n    // Vector3d pf(circle_radius, 0, take_off_height);\n    // Vector3d vf(0, 0, 0);\n    // Vector3d af(0, 0, 0);\n\n    // motion_primitives(current_p, v0, a0, pf, vf, af, 3.0, delt_t, p_t, v_t, a_t, t_vector);\n\n    // for(int i=0; i<t_vector.size(); i++)\n    // {\n    //     setPVA(p_t.row(i), v_t.row(i), Vector3d::Zero());// a_t.row(i));\n    //     loop_rate.sleep();\n    //     ros::spinOnce();\n    // }\n\n    // while(ros::ok())\n    // {\n    //     setPVA(p_t.row(t_vector.size()-1), v_t.row(t_vector.size()-1), Vector3d::Zero());// a_t.row(i));\n    //     Vector3d last_sp_p = p_t.row(t_vector.size()-1);\n    //     Vector3d delt_p = last_sp_p - current_p;\n    //     if(delt_p.norm() < 0.2){\n    //         ROS_WARN(\"Align Complete!\");\n    //         break;\n    //     }\n\n    //     loop_rate.sleep();\n    //     ros::spinOnce();\n    // }\n\n    // /** Now draw circle **/\n    // Vector3d circle_p0 = current_p;\n    // double init_t = 0.0;\n    // while(ros::ok()){\n    //     Eigen::Vector3d p, v ,a;\n    //     compute_circular_traj(circle_radius, 5.0, circle_p0, init_t, p, v, a);\n    //     setPVA(p, v, a);//a_t.row(last_index));\n\n    //     init_t += delt_t;\n    //     loop_rate.sleep();\n    //     ros::spinOnce();\n    // }\n\n    return 0;\n}\n", "meta": {"hexsha": "11b3cf194cf6888ba1791353f0ac3dd87dbaf8b9", "size": 12629, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/real_control_test.cpp", "max_stars_repo_name": "ycpengpeng/pva_tracker", "max_stars_repo_head_hexsha": "7c1f188dc641ed2d29e0605dd201811e20ef629f", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/real_control_test.cpp", "max_issues_repo_name": "ycpengpeng/pva_tracker", "max_issues_repo_head_hexsha": "7c1f188dc641ed2d29e0605dd201811e20ef629f", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/real_control_test.cpp", "max_forks_repo_name": "ycpengpeng/pva_tracker", "max_forks_repo_head_hexsha": "7c1f188dc641ed2d29e0605dd201811e20ef629f", "max_forks_repo_licenses": ["BSD-3-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.0828571429, "max_line_length": 144, "alphanum_fraction": 0.5642568691, "num_tokens": 3906, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6688802603710086, "lm_q2_score": 0.5156199157230157, "lm_q1q2_score": 0.34488798348128824}}
{"text": "//  Copyright John Maddock 2007.\n//  Copyright Paul A. Bristow 2010\n//  Use, modification and distribution are subject to the\n//  Boost Software License, Version 1.0. (See accompanying file\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n// Note that this file contains quickbook mark-up as well as code\n// and comments, don't change any of the special comment mark-ups!\n\n#include <iostream>\nusing std::cout; using std::endl; using std::cerr;\n\n//[policy_eg_9\n\n/*`\nThe previous example was all well and good, but the custom error handlers\ndidn't really do much of any use.  In this example we'll implement all\nthe custom handlers and show how the information provided to them can be\nused to generate nice formatted error messages.\n\nEach error handler has the general form:\n\n   template <class T>\n   T user_``['error_type]``(\n      const char* function,\n      const char* message,\n      const T& val);\n\nand accepts three arguments:\n\n[variablelist\n[[const char* function]\n   [The name of the function that raised the error, this string\n   contains one or more %1% format specifiers that should be\n   replaced by the name of real type T, like float or double.]]\n[[const char* message]\n   [A message associated with the error, normally this\n   contains a %1% format specifier that should be replaced with\n   the value of ['value]: however note that overflow and underflow messages\n   do not contain this %1% specifier (since the value of ['value] is\n   immaterial in these cases).]]\n[[const T& value]\n   [The value that caused the error: either an argument to the function\n   if this is a domain or pole error, the tentative result\n   if this is a denorm or evaluation error, or zero or infinity for\n   underflow or overflow errors.]]\n]\n\nAs before we'll include the headers we need first:\n\n*/\n\n#include <boost/math/special_functions.hpp>\n\n/*`\nNext we'll implement our own error handlers for each type of error,\nstarting with domain errors:\n*/\n\nnamespace boost{ namespace math{\nnamespace policies\n{\n\ntemplate <class T>\nT user_domain_error(const char* function, const char* message, const T& val)\n{\n   /*`\n   We'll begin with a bit of defensive programming in case function or message are empty:\n   */\n   if(function == 0)\n       function = \"Unknown function with arguments of type %1%\";\n   if(message == 0)\n       message = \"Cause unknown with bad argument %1%\";\n   /*`\n   Next we'll format the name of the function with the name of type T, perhaps double:\n   */\n   std::string msg(\"Error in function \");\n   msg += (boost::format(function) % typeid(T).name()).str();\n   /*`\n   Then likewise format the error message with the value of parameter /val/,\n   making sure we output all the potentially significant digits of /val/:\n   */\n   msg += \": \\n\";\n   int prec = 2 + (std::numeric_limits<T>::digits * 30103UL) / 100000UL;\n   // int prec = std::numeric_limits<T>::max_digits10; //  For C++0X Standard Library\n   msg += (boost::format(message) % boost::io::group(std::setprecision(prec), val)).str();\n   /*`\n   Now we just have to do something with the message, we could throw an\n   exception, but for the purposes of this example we'll just dump the message\n   to std::cerr:\n   */\n   std::cerr << msg << std::endl;\n   /*`\n   Finally the only sensible value we can return from a domain error is a NaN:\n   */\n   return std::numeric_limits<T>::quiet_NaN();\n}\n\n/*`\nPole errors are essentially a special case of domain errors,\nso in this example we'll just return the result of a domain error:\n*/\n\ntemplate <class T>\nT user_pole_error(const char* function, const char* message, const T& val)\n{\n   return user_domain_error(function, message, val);\n}\n\n/*`\nOverflow errors are very similar to domain errors, except that there's\nno %1% format specifier in the /message/ parameter:\n*/\ntemplate <class T>\nT user_overflow_error(const char* function, const char* message, const T& val)\n{\n   if(function == 0)\n       function = \"Unknown function with arguments of type %1%\";\n   if(message == 0)\n       message = \"Result of function is too large to represent\";\n\n   std::string msg(\"Error in function \");\n   msg += (boost::format(function) % typeid(T).name()).str();\n\n   msg += \": \\n\";\n   msg += message;\n\n   std::cerr << msg << std::endl;\n\n   // Value passed to the function is an infinity, just return it:\n   return val;\n}\n\n/*`\nUnderflow errors are much the same as overflow:\n*/\n\ntemplate <class T>\nT user_underflow_error(const char* function, const char* message, const T& val)\n{\n   if(function == 0)\n       function = \"Unknown function with arguments of type %1%\";\n   if(message == 0)\n       message = \"Result of function is too small to represent\";\n\n   std::string msg(\"Error in function \");\n   msg += (boost::format(function) % typeid(T).name()).str();\n\n   msg += \": \\n\";\n   msg += message;\n\n   std::cerr << msg << std::endl;\n\n   // Value passed to the function is zero, just return it:\n   return val;\n}\n\n/*`\nDenormalised results are much the same as underflow:\n*/\n\ntemplate <class T>\nT user_denorm_error(const char* function, const char* message, const T& val)\n{\n   if(function == 0)\n       function = \"Unknown function with arguments of type %1%\";\n   if(message == 0)\n       message = \"Result of function is denormalised\";\n\n   std::string msg(\"Error in function \");\n   msg += (boost::format(function) % typeid(T).name()).str();\n\n   msg += \": \\n\";\n   msg += message;\n\n   std::cerr << msg << std::endl;\n\n   // Value passed to the function is denormalised, just return it:\n   return val;\n}\n\n/*`\nWhich leaves us with evaluation errors: these occur when an internal\nerror occurs that prevents the function being fully evaluated.\nThe parameter /val/ contains the closest approximation to the result\nfound so far:\n*/\n\ntemplate <class T>\nT user_evaluation_error(const char* function, const char* message, const T& val)\n{\n   if(function == 0)\n       function = \"Unknown function with arguments of type %1%\";\n   if(message == 0)\n       message = \"An internal evaluation error occurred with \"\n                  \"the best value calculated so far of %1%\";\n\n   std::string msg(\"Error in function \");\n   msg += (boost::format(function) % typeid(T).name()).str();\n\n   msg += \": \\n\";\n   int prec = 2 + (std::numeric_limits<T>::digits * 30103UL) / 100000UL;\n   // int prec = std::numeric_limits<T>::max_digits10; // For C++0X Standard Library\n   msg += (boost::format(message) % boost::io::group(std::setprecision(prec), val)).str();\n\n   std::cerr << msg << std::endl;\n\n   // What do we return here?  This is generally a fatal error, that should never occur,\n   // so we just return a NaN for the purposes of the example:\n   return std::numeric_limits<T>::quiet_NaN();\n}\n\n} // policies\n}} // boost::math\n\n\n/*`\nNow we'll need to define a suitable policy that will call these handlers,\nand define some forwarding functions that make use of the policy:\n*/\n\nnamespace mymath\n{ // unnamed.\n\nusing namespace boost::math::policies;\n\ntypedef policy<\n   domain_error<user_error>,\n   pole_error<user_error>,\n   overflow_error<user_error>,\n   underflow_error<user_error>,\n   denorm_error<user_error>,\n   evaluation_error<user_error>\n> user_error_policy;\n\nBOOST_MATH_DECLARE_SPECIAL_FUNCTIONS(user_error_policy)\n\n} // unnamed namespace\n\n/*`\nWe now have a set of forwarding functions, defined in namespace mymath,\nthat all look something like this:\n\n``\ntemplate <class RealType>\ninline typename boost::math::tools::promote_args<RT>::type\n   tgamma(RT z)\n{\n   return boost::math::tgamma(z, user_error_policy());\n}\n``\n\nSo that when we call `mymath::tgamma(z)` we really end up calling\n`boost::math::tgamma(z, user_error_policy())`, and any\nerrors will get directed to our own error handlers:\n*/\n\nint main()\n{\n   // Raise a domain error:\n   cout << \"Result of erf_inv(-10) is: \"\n      << mymath::erf_inv(-10) << std::endl << endl;\n   // Raise a pole error:\n   cout << \"Result of tgamma(-10) is: \"\n      << mymath::tgamma(-10) << std::endl << endl;\n   // Raise an overflow error:\n   cout << \"Result of tgamma(3000) is: \"\n      << mymath::tgamma(3000) << std::endl << endl;\n   // Raise an underflow error:\n   cout << \"Result of tgamma(-190.5) is: \"\n      << mymath::tgamma(-190.5) << std::endl << endl;\n   // Unfortunately we can't predicably raise a denormalised\n   // result, nor can we raise an evaluation error in this example\n   // since these should never really occur!\n} // int main()\n\n/*`\n\nWhich outputs:\n\n[pre\nError in function boost::math::erf_inv<double>(double, double):\nArgument outside range \\[-1, 1\\] in inverse erf function (got p=-10).\nResult of erf_inv(-10) is: 1.#QNAN\n\nError in function boost::math::tgamma<long double>(long double):\nEvaluation of tgamma at a negative integer -10.\nResult of tgamma(-10) is: 1.#QNAN\n\nError in function boost::math::tgamma<long double>(long double):\nResult of tgamma is too large to represent.\nError in function boost::math::tgamma<double>(double):\nResult of function is too large to represent\nResult of tgamma(3000) is: 1.#INF\n\nError in function boost::math::tgamma<long double>(long double):\nResult of tgamma is too large to represent.\nError in function boost::math::tgamma<long double>(long double):\nResult of tgamma is too small to represent.\nResult of tgamma(-190.5) is: 0\n]\n\nNotice how some of the calls result in an error handler being called more\nthan once, or for more than one handler to be called: this is an artefact\nof the fact that many functions are implemented in terms of one or more\nsub-routines each of which may have it's own error handling.  For example\n`tgamma(-190.5)` is implemented in terms of `tgamma(190.5)` - which overflows -\nthe reflection formula for `tgamma` then notices that it is dividing by\ninfinity and so underflows.\n*/\n\n//] //[/policy_eg_9]\n", "meta": {"hexsha": "d5335caba369363127ec3141f9e75beb295493a6", "size": 9703, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "boost/boost_1_56_0/libs/math/example/policy_eg_9.cpp", "max_stars_repo_name": "cooparation/caffe-android", "max_stars_repo_head_hexsha": "cd91078d1f298c74fca4c242531989d64a32ba03", "max_stars_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_stars_count": 9.0, "max_stars_repo_stars_event_min_datetime": "2016-03-01T02:19:06.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-07T08:48:51.000Z", "max_issues_repo_path": "libs/math/example/policy_eg_9.cpp", "max_issues_repo_name": "crystax/android-vendor-boost-1-61-0", "max_issues_repo_head_hexsha": "a1f467d25d815dc7613fbee06c632cae423f52ca", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2016-01-05T06:36:48.000Z", "max_issues_repo_issues_event_max_datetime": "2017-07-13T16:16:30.000Z", "max_forks_repo_path": "libs/math/example/policy_eg_9.cpp", "max_forks_repo_name": "crystax/android-vendor-boost-1-61-0", "max_forks_repo_head_hexsha": "a1f467d25d815dc7613fbee06c632cae423f52ca", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2017-03-20T01:55:03.000Z", "max_forks_repo_forks_event_max_datetime": "2018-07-29T12:35:29.000Z", "avg_line_length": 31.0, "max_line_length": 90, "alphanum_fraction": 0.6920540039, "num_tokens": 2455, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.6688802603710086, "lm_q1q2_score": 0.34488798348128824}}
{"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 \"../../relative_pose_rodrigues_wc_jacobian.h\"\n#include \"../../relative_pose_quaternion_wc_jacobian.h\"\n#include \"../../quaternion_constraint_jacobian.h\"\n#include \"../../point_to_point_source_to_target_tait_bryan_wc_jacobian.h\"\n#include \"../../point_to_point_source_to_target_rodrigues_wc_jacobian.h\"\n#include \"../../point_to_point_source_to_target_quaternion_wc_jacobian.h\"\n#include \"../../constraints_jacobian.h\"\n#include \"../include/cauchy.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\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-case1\");\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\tint ir = tripletListB.size();\n\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::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\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 = georeference_data[i].second * 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    ,  cauchy(delta_x, 1));\n\t\t\t\ttripletListP.emplace_back(ir + 1, ir + 1,  cauchy(delta_y, 1));\n\t\t\t\ttripletListP.emplace_back(ir + 2, ir + 2,  cauchy(delta_z, 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\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\tint ir = tripletListB.size();\n\n\t\t\t\tint ic = georeference_data[i].second * 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, m_poses[georeference_data[i].second](0,3), georeference_data[i].first(0,3));\n\t\t\t\tobservation_equation_constraint_jacobian(jacobian, a, m_poses[georeference_data[i].second](0,3), georeference_data[i].first(0,3));\n\n\t\t\t\ttripletListA.emplace_back(ir, ic,  -jacobian(0,0));\n\t\t\t\ttripletListP.emplace_back(ir, ir,  cauchy(delta, 1));\n\t\t\t\ttripletListB.emplace_back(ir, 0,  delta);\n\n\t\t\t\tobservation_equation_constraint(delta, a, m_poses[georeference_data[i].second](1,3), georeference_data[i].first(1,3));\n\t\t\t\tobservation_equation_constraint_jacobian(jacobian, a, m_poses[georeference_data[i].second](1,3), georeference_data[i].first(1,3));\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,  cauchy(delta, 1));\n\t\t\t\ttripletListB.emplace_back(ir + 1, 0,  delta);\n\n\t\t\t\tobservation_equation_constraint(delta, a, m_poses[georeference_data[i].second](2,3), georeference_data[i].first(2,3));\n\t\t\t\tobservation_equation_constraint_jacobian(jacobian, a, m_poses[georeference_data[i].second](2,3), georeference_data[i].first(2,3));\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,  cauchy(delta, 1));\n\t\t\t\ttripletListB.emplace_back(ir + 2, 0,  delta);\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\n\t\tcase 'r':{\n\t\t\tstd::vector<Eigen::Triplet<double>> tripletListA;\n\t\t\tstd::vector<Eigen::Triplet<double>> tripletListP;\n\t\t\tstd::vector<Eigen::Triplet<double>> tripletListB;\n\n\t\t\tstd::vector<RodriguesPose> poses;\n\t\t\tstd::vector<RodriguesPose> poses_desired;\n\n\t\t\tfor(size_t i = 0 ; i < m_poses.size(); i++){\n\t\t\t\tposes.push_back(pose_rodrigues_from_affine_matrix(m_poses[i]));\n\t\t\t}\n\t\t\tfor(size_t i = 0 ; i < m_poses_desired.size(); i++){\n\t\t\t\tposes_desired.push_back(pose_rodrigues_from_affine_matrix(m_poses_desired[i]));\n\t\t\t}\n\n\t\t\tfor(size_t i = 0 ; i < odo_edges.size(); i++){\n\t\t\t\tEigen::Matrix<double, 6, 1> relative_pose_measurement_odo;\n\t\t\t\trelative_pose_rodrigues_wc(relative_pose_measurement_odo,\n\t\t\t\t\t\tposes_desired[odo_edges[i].first].px,\n\t\t\t\t\t\tposes_desired[odo_edges[i].first].py,\n\t\t\t\t\t\tposes_desired[odo_edges[i].first].pz,\n\t\t\t\t\t\tposes_desired[odo_edges[i].first].sx,\n\t\t\t\t\t\tposes_desired[odo_edges[i].first].sy,\n\t\t\t\t\t\tposes_desired[odo_edges[i].first].sz,\n\t\t\t\t\t\tposes_desired[odo_edges[i].second].px,\n\t\t\t\t\t\tposes_desired[odo_edges[i].second].py,\n\t\t\t\t\t\tposes_desired[odo_edges[i].second].pz,\n\t\t\t\t\t\tposes_desired[odo_edges[i].second].sx,\n\t\t\t\t\t\tposes_desired[odo_edges[i].second].sy,\n\t\t\t\t\t\tposes_desired[odo_edges[i].second].sz);\n\n\t\t\t\tEigen::Matrix<double, 6, 1> delta;\n\t\t\t\trelative_pose_obs_eq_rodrigues_wc(\n\t\t\t\t\t\tdelta,\n\t\t\t\t\t\tposes[odo_edges[i].first].px,\n\t\t\t\t\t\tposes[odo_edges[i].first].py,\n\t\t\t\t\t\tposes[odo_edges[i].first].pz,\n\t\t\t\t\t\tposes[odo_edges[i].first].sx,\n\t\t\t\t\t\tposes[odo_edges[i].first].sy,\n\t\t\t\t\t\tposes[odo_edges[i].first].sz,\n\t\t\t\t\t\tposes[odo_edges[i].second].px,\n\t\t\t\t\t\tposes[odo_edges[i].second].py,\n\t\t\t\t\t\tposes[odo_edges[i].second].pz,\n\t\t\t\t\t\tposes[odo_edges[i].second].sx,\n\t\t\t\t\t\tposes[odo_edges[i].second].sy,\n\t\t\t\t\t\tposes[odo_edges[i].second].sz,\n\t\t\t\t\t\trelative_pose_measurement_odo(0,0),\n\t\t\t\t\t\trelative_pose_measurement_odo(1,0),\n\t\t\t\t\t\trelative_pose_measurement_odo(2,0),\n\t\t\t\t\t\trelative_pose_measurement_odo(3,0),\n\t\t\t\t\t\trelative_pose_measurement_odo(4,0),\n\t\t\t\t\t\trelative_pose_measurement_odo(5,0));\n\n\t\t\t\tEigen::Matrix<double, 6, 12, Eigen::RowMajor> jacobian;\n\t\t\t\trelative_pose_obs_eq_rodrigues_wc_jacobian(jacobian,\n\t\t\t\t\t\tposes[odo_edges[i].first].px,\n\t\t\t\t\t\tposes[odo_edges[i].first].py,\n\t\t\t\t\t\tposes[odo_edges[i].first].pz,\n\t\t\t\t\t\tposes[odo_edges[i].first].sx,\n\t\t\t\t\t\tposes[odo_edges[i].first].sy,\n\t\t\t\t\t\tposes[odo_edges[i].first].sz,\n\t\t\t\t\t\tposes[odo_edges[i].second].px,\n\t\t\t\t\t\tposes[odo_edges[i].second].py,\n\t\t\t\t\t\tposes[odo_edges[i].second].pz,\n\t\t\t\t\t\tposes[odo_edges[i].second].sx,\n\t\t\t\t\t\tposes[odo_edges[i].second].sy,\n\t\t\t\t\t\tposes[odo_edges[i].second].sz);\n\n\t\t\t\tint ir = tripletListB.size();\n\n\t\t\t\tint ic_1 = odo_edges[i].first * 6;\n\t\t\t\tint ic_2 = odo_edges[i].second * 6;\n\n\t\t\t\tfor(size_t row = 0 ; row < 6; row ++){\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_1    , -jacobian(row,0));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_1 + 1, -jacobian(row,1));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_1 + 2, -jacobian(row,2));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_1 + 3, -jacobian(row,3));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_1 + 4, -jacobian(row,4));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_1 + 5, -jacobian(row,5));\n\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_2    , -jacobian(row,6));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_2 + 1, -jacobian(row,7));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_2 + 2, -jacobian(row,8));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_2 + 3, -jacobian(row,9));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_2 + 4, -jacobian(row,10));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_2 + 5, -jacobian(row,11));\n\t\t\t\t}\n\n\t\t\t\ttripletListB.emplace_back(ir,     0, delta(0,0));\n\t\t\t\ttripletListB.emplace_back(ir + 1, 0, delta(1,0));\n\t\t\t\ttripletListB.emplace_back(ir + 2, 0, delta(2,0));\n\t\t\t\ttripletListB.emplace_back(ir + 3, 0, delta(3,0));\n\t\t\t\ttripletListB.emplace_back(ir + 4, 0, delta(4,0));\n\t\t\t\ttripletListB.emplace_back(ir + 5, 0, delta(5,0));\n\n\t\t\t\ttripletListP.emplace_back(ir ,    ir,     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_rodrigues_wc(relative_pose_measurement_loop,\n\t\t\t\t\t\tposes_desired[loop_edges[i].first].px,\n\t\t\t\t\t\tposes_desired[loop_edges[i].first].py,\n\t\t\t\t\t\tposes_desired[loop_edges[i].first].pz,\n\t\t\t\t\t\tposes_desired[loop_edges[i].first].sx,\n\t\t\t\t\t\tposes_desired[loop_edges[i].first].sy,\n\t\t\t\t\t\tposes_desired[loop_edges[i].first].sz,\n\t\t\t\t\t\tposes_desired[loop_edges[i].second].px,\n\t\t\t\t\t\tposes_desired[loop_edges[i].second].py,\n\t\t\t\t\t\tposes_desired[loop_edges[i].second].pz,\n\t\t\t\t\t\tposes_desired[loop_edges[i].second].sx,\n\t\t\t\t\t\tposes_desired[loop_edges[i].second].sy,\n\t\t\t\t\t\tposes_desired[loop_edges[i].second].sz);\n\n\t\t\t\tEigen::Matrix<double, 6, 1> delta;\n\t\t\t\trelative_pose_obs_eq_rodrigues_wc(\n\t\t\t\t\t\tdelta,\n\t\t\t\t\t\tposes[loop_edges[i].first].px,\n\t\t\t\t\t\tposes[loop_edges[i].first].py,\n\t\t\t\t\t\tposes[loop_edges[i].first].pz,\n\t\t\t\t\t\tposes[loop_edges[i].first].sx,\n\t\t\t\t\t\tposes[loop_edges[i].first].sy,\n\t\t\t\t\t\tposes[loop_edges[i].first].sz,\n\t\t\t\t\t\tposes[loop_edges[i].second].px,\n\t\t\t\t\t\tposes[loop_edges[i].second].py,\n\t\t\t\t\t\tposes[loop_edges[i].second].pz,\n\t\t\t\t\t\tposes[loop_edges[i].second].sx,\n\t\t\t\t\t\tposes[loop_edges[i].second].sy,\n\t\t\t\t\t\tposes[loop_edges[i].second].sz,\n\t\t\t\t\t\trelative_pose_measurement_loop(0,0),\n\t\t\t\t\t\trelative_pose_measurement_loop(1,0),\n\t\t\t\t\t\trelative_pose_measurement_loop(2,0),\n\t\t\t\t\t\trelative_pose_measurement_loop(3,0),\n\t\t\t\t\t\trelative_pose_measurement_loop(4,0),\n\t\t\t\t\t\trelative_pose_measurement_loop(5,0));\n\n\t\t\t\tEigen::Matrix<double, 6, 12, Eigen::RowMajor> jacobian;\n\t\t\t\trelative_pose_obs_eq_rodrigues_wc_jacobian(jacobian,\n\t\t\t\t\t\tposes[loop_edges[i].first].px,\n\t\t\t\t\t\tposes[loop_edges[i].first].py,\n\t\t\t\t\t\tposes[loop_edges[i].first].pz,\n\t\t\t\t\t\tposes[loop_edges[i].first].sx,\n\t\t\t\t\t\tposes[loop_edges[i].first].sy,\n\t\t\t\t\t\tposes[loop_edges[i].first].sz,\n\t\t\t\t\t\tposes[loop_edges[i].second].px,\n\t\t\t\t\t\tposes[loop_edges[i].second].py,\n\t\t\t\t\t\tposes[loop_edges[i].second].pz,\n\t\t\t\t\t\tposes[loop_edges[i].second].sx,\n\t\t\t\t\t\tposes[loop_edges[i].second].sy,\n\t\t\t\t\t\tposes[loop_edges[i].second].sz);\n\n\t\t\t\tint ir = tripletListB.size();\n\n\t\t\t\tint ic_1 = loop_edges[i].first * 6;\n\t\t\t\tint ic_2 = loop_edges[i].second * 6;\n\n\t\t\t\tfor(size_t row = 0 ; row < 6; row ++){\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_1    , -jacobian(row,0));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_1 + 1, -jacobian(row,1));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_1 + 2, -jacobian(row,2));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_1 + 3, -jacobian(row,3));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_1 + 4, -jacobian(row,4));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_1 + 5, -jacobian(row,5));\n\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_2    , -jacobian(row,6));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_2 + 1, -jacobian(row,7));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_2 + 2, -jacobian(row,8));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_2 + 3, -jacobian(row,9));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_2 + 4, -jacobian(row,10));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_2 + 5, -jacobian(row,11));\n\t\t\t\t}\n\n\t\t\t\ttripletListB.emplace_back(ir,     0, delta(0,0));\n\t\t\t\ttripletListB.emplace_back(ir + 1, 0, delta(1,0));\n\t\t\t\ttripletListB.emplace_back(ir + 2, 0, delta(2,0));\n\t\t\t\ttripletListB.emplace_back(ir + 3, 0, delta(3,0));\n\t\t\t\ttripletListB.emplace_back(ir + 4, 0, delta(4,0));\n\t\t\t\ttripletListB.emplace_back(ir + 5, 0, delta(5,0));\n\n\t\t\t\ttripletListP.emplace_back(ir ,    ir,     1);\n\t\t\t\ttripletListP.emplace_back(ir + 1, ir + 1, 1);\n\t\t\t\ttripletListP.emplace_back(ir + 2, ir + 2, 1);\n\t\t\t\ttripletListP.emplace_back(ir + 3, ir + 3, 1);\n\t\t\t\ttripletListP.emplace_back(ir + 4, ir + 4, 1);\n\t\t\t\ttripletListP.emplace_back(ir + 5, ir + 5, 1);\n\t\t\t}\n\n\t\t\tfor(size_t i = 0; i < georeference_data.size(); i++){\n\t\t\t\tint ir = tripletListB.size();\n\n\t\t\t\tRodriguesPose pose_s = pose_rodrigues_from_affine_matrix(m_poses[georeference_data[i].second]);\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\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_rodrigues_wc(delta_x, delta_y, delta_z, pose_s.px, pose_s.py, pose_s.pz, pose_s.sx, pose_s.sy, pose_s.sz, 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_rodrigues_wc_jacobian(jacobian, pose_s.px, pose_s.py, pose_s.pz, pose_s.sx, pose_s.sy, pose_s.sz, p_s.x(), p_s.y(), p_s.z());\n\n\t\t\t\tint ic = georeference_data[i].second * 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    ,  cauchy(delta_x, 1));\n\t\t\t\ttripletListP.emplace_back(ir + 1, ir + 1,  cauchy(delta_y, 1));\n\t\t\t\ttripletListP.emplace_back(ir + 2, ir + 2,  cauchy(delta_z, 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(), m_poses.size() * 6);\n\t\t\tEigen::SparseMatrix<double> matP(tripletListB.size(), tripletListB.size());\n\t\t\tEigen::SparseMatrix<double> matB(tripletListB.size(), 1);\n\n\t\t\tmatA.setFromTriplets(tripletListA.begin(), tripletListA.end());\n\t\t\tmatP.setFromTriplets(tripletListP.begin(), tripletListP.end());\n\t\t\tmatB.setFromTriplets(tripletListB.begin(), tripletListB.end());\n\n\n\t\t\tEigen::SparseMatrix<double> AtPA(m_poses.size() * 6 , m_poses.size() * 6);\n\t\t\tEigen::SparseMatrix<double> AtPB(m_poses.size() * 6 , 1);\n\n\t\t\t{\n\t\t\tEigen::SparseMatrix<double> AtP = matA.transpose() * matP;\n\t\t\tAtPA = (AtP) * matA;\n\t\t\tAtPB = (AtP) * matB;\n\t\t\t}\n\n\t\t\ttripletListA.clear();\n\t\t\ttripletListP.clear();\n\t\t\ttripletListB.clear();\n\n\t\t\tstd::cout << \"AtPA.size: \" << AtPA.size() << std::endl;\n\t\t\tstd::cout << \"AtPB.size: \" << AtPB.size() << std::endl;\n\n\t\t\tstd::cout << \"start solving AtPA=AtPB\" << std::endl;\n\t\t\tEigen::SimplicialCholesky<Eigen::SparseMatrix<double>> solver(AtPA);\n\n\t\t\tstd::cout << \"x = solver.solve(AtPB)\" << std::endl;\n\t\t\tEigen::SparseMatrix<double> x = solver.solve(AtPB);\n\n\t\t\tstd::vector<double> h_x;\n\n\t\t\tfor (int k=0; k<x.outerSize(); ++k){\n\t\t\t\tfor (Eigen::SparseMatrix<double>::InnerIterator it(x,k); it; ++it){\n\t\t\t\t\th_x.push_back(it.value());\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tstd::cout << \"h_x.size(): \" << h_x.size() << std::endl;\n\n\t\t\tstd::cout << \"AtPA=AtPB SOLVED\" << std::endl;\n\n\t\t\tfor(size_t i = 0 ; i < h_x.size(); i++){\n\t\t\t\tstd::cout << h_x[i] << std::endl;\n\t\t\t}\n\n\t\t\tif(h_x.size() == 6 * m_poses.size()){\n\t\t\t\tint counter = 0;\n\n\t\t\t\tfor(size_t i = 0; i < m_poses.size(); i++){\n\t\t\t\t\tRodriguesPose pose = pose_rodrigues_from_affine_matrix(m_poses[i]);\n\t\t\t\t\tpose.px += h_x[counter++];\n\t\t\t\t\tpose.py += h_x[counter++];\n\t\t\t\t\tpose.pz += h_x[counter++];\n\t\t\t\t\tpose.sx += h_x[counter++];\n\t\t\t\t\tpose.sy += h_x[counter++];\n\t\t\t\t\tpose.sz += h_x[counter++];\n\n\t\t\t\t\tm_poses[i] = affine_matrix_from_pose_rodrigues(pose);\n\t\t\t\t}\n\t\t\t}\n\t\t\tstd::cout << \"optimizing with rodrigues finished\" << std::endl;\n\t\t\tbreak;\n\t\t}\n\t\tcase 'e':{\n\t\t\tstd::vector<Eigen::Triplet<double>> tripletListA;\n\t\t\tstd::vector<Eigen::Triplet<double>> tripletListP;\n\t\t\tstd::vector<Eigen::Triplet<double>> tripletListB;\n\n\t\t\tstd::vector<RodriguesPose> poses;\n\t\t\tstd::vector<RodriguesPose> poses_desired;\n\n\t\t\tfor(size_t i = 0 ; i < m_poses.size(); i++){\n\t\t\t\tposes.push_back(pose_rodrigues_from_affine_matrix(m_poses[i]));\n\t\t\t}\n\t\t\tfor(size_t i = 0 ; i < m_poses_desired.size(); i++){\n\t\t\t\tposes_desired.push_back(pose_rodrigues_from_affine_matrix(m_poses_desired[i]));\n\t\t\t}\n\n\t\t\tfor(size_t i = 0 ; i < odo_edges.size(); i++){\n\t\t\t\tEigen::Matrix<double, 6, 1> relative_pose_measurement_odo;\n\t\t\t\trelative_pose_rodrigues_wc(relative_pose_measurement_odo,\n\t\t\t\t\t\tposes_desired[odo_edges[i].first].px,\n\t\t\t\t\t\tposes_desired[odo_edges[i].first].py,\n\t\t\t\t\t\tposes_desired[odo_edges[i].first].pz,\n\t\t\t\t\t\tposes_desired[odo_edges[i].first].sx,\n\t\t\t\t\t\tposes_desired[odo_edges[i].first].sy,\n\t\t\t\t\t\tposes_desired[odo_edges[i].first].sz,\n\t\t\t\t\t\tposes_desired[odo_edges[i].second].px,\n\t\t\t\t\t\tposes_desired[odo_edges[i].second].py,\n\t\t\t\t\t\tposes_desired[odo_edges[i].second].pz,\n\t\t\t\t\t\tposes_desired[odo_edges[i].second].sx,\n\t\t\t\t\t\tposes_desired[odo_edges[i].second].sy,\n\t\t\t\t\t\tposes_desired[odo_edges[i].second].sz);\n\n\t\t\t\tEigen::Matrix<double, 6, 1> delta;\n\t\t\t\trelative_pose_obs_eq_rodrigues_wc(\n\t\t\t\t\t\tdelta,\n\t\t\t\t\t\tposes[odo_edges[i].first].px,\n\t\t\t\t\t\tposes[odo_edges[i].first].py,\n\t\t\t\t\t\tposes[odo_edges[i].first].pz,\n\t\t\t\t\t\tposes[odo_edges[i].first].sx,\n\t\t\t\t\t\tposes[odo_edges[i].first].sy,\n\t\t\t\t\t\tposes[odo_edges[i].first].sz,\n\t\t\t\t\t\tposes[odo_edges[i].second].px,\n\t\t\t\t\t\tposes[odo_edges[i].second].py,\n\t\t\t\t\t\tposes[odo_edges[i].second].pz,\n\t\t\t\t\t\tposes[odo_edges[i].second].sx,\n\t\t\t\t\t\tposes[odo_edges[i].second].sy,\n\t\t\t\t\t\tposes[odo_edges[i].second].sz,\n\t\t\t\t\t\trelative_pose_measurement_odo(0,0),\n\t\t\t\t\t\trelative_pose_measurement_odo(1,0),\n\t\t\t\t\t\trelative_pose_measurement_odo(2,0),\n\t\t\t\t\t\trelative_pose_measurement_odo(3,0),\n\t\t\t\t\t\trelative_pose_measurement_odo(4,0),\n\t\t\t\t\t\trelative_pose_measurement_odo(5,0));\n\n\t\t\t\tEigen::Matrix<double, 6, 12, Eigen::RowMajor> jacobian;\n\t\t\t\trelative_pose_obs_eq_rodrigues_wc_jacobian(jacobian,\n\t\t\t\t\t\tposes[odo_edges[i].first].px,\n\t\t\t\t\t\tposes[odo_edges[i].first].py,\n\t\t\t\t\t\tposes[odo_edges[i].first].pz,\n\t\t\t\t\t\tposes[odo_edges[i].first].sx,\n\t\t\t\t\t\tposes[odo_edges[i].first].sy,\n\t\t\t\t\t\tposes[odo_edges[i].first].sz,\n\t\t\t\t\t\tposes[odo_edges[i].second].px,\n\t\t\t\t\t\tposes[odo_edges[i].second].py,\n\t\t\t\t\t\tposes[odo_edges[i].second].pz,\n\t\t\t\t\t\tposes[odo_edges[i].second].sx,\n\t\t\t\t\t\tposes[odo_edges[i].second].sy,\n\t\t\t\t\t\tposes[odo_edges[i].second].sz);\n\n\t\t\t\tint ir = tripletListB.size();\n\n\t\t\t\tint ic_1 = odo_edges[i].first * 6;\n\t\t\t\tint ic_2 = odo_edges[i].second * 6;\n\n\t\t\t\tfor(size_t row = 0 ; row < 6; row ++){\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_1    , -jacobian(row,0));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_1 + 1, -jacobian(row,1));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_1 + 2, -jacobian(row,2));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_1 + 3, -jacobian(row,3));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_1 + 4, -jacobian(row,4));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_1 + 5, -jacobian(row,5));\n\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_2    , -jacobian(row,6));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_2 + 1, -jacobian(row,7));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_2 + 2, -jacobian(row,8));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_2 + 3, -jacobian(row,9));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_2 + 4, -jacobian(row,10));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_2 + 5, -jacobian(row,11));\n\t\t\t\t}\n\n\t\t\t\ttripletListB.emplace_back(ir,     0, delta(0,0));\n\t\t\t\ttripletListB.emplace_back(ir + 1, 0, delta(1,0));\n\t\t\t\ttripletListB.emplace_back(ir + 2, 0, delta(2,0));\n\t\t\t\ttripletListB.emplace_back(ir + 3, 0, delta(3,0));\n\t\t\t\ttripletListB.emplace_back(ir + 4, 0, delta(4,0));\n\t\t\t\ttripletListB.emplace_back(ir + 5, 0, delta(5,0));\n\n\t\t\t\ttripletListP.emplace_back(ir ,    ir,     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_rodrigues_wc(relative_pose_measurement_loop,\n\t\t\t\t\t\tposes_desired[loop_edges[i].first].px,\n\t\t\t\t\t\tposes_desired[loop_edges[i].first].py,\n\t\t\t\t\t\tposes_desired[loop_edges[i].first].pz,\n\t\t\t\t\t\tposes_desired[loop_edges[i].first].sx,\n\t\t\t\t\t\tposes_desired[loop_edges[i].first].sy,\n\t\t\t\t\t\tposes_desired[loop_edges[i].first].sz,\n\t\t\t\t\t\tposes_desired[loop_edges[i].second].px,\n\t\t\t\t\t\tposes_desired[loop_edges[i].second].py,\n\t\t\t\t\t\tposes_desired[loop_edges[i].second].pz,\n\t\t\t\t\t\tposes_desired[loop_edges[i].second].sx,\n\t\t\t\t\t\tposes_desired[loop_edges[i].second].sy,\n\t\t\t\t\t\tposes_desired[loop_edges[i].second].sz);\n\n\t\t\t\tEigen::Matrix<double, 6, 1> delta;\n\t\t\t\trelative_pose_obs_eq_rodrigues_wc(\n\t\t\t\t\t\tdelta,\n\t\t\t\t\t\tposes[loop_edges[i].first].px,\n\t\t\t\t\t\tposes[loop_edges[i].first].py,\n\t\t\t\t\t\tposes[loop_edges[i].first].pz,\n\t\t\t\t\t\tposes[loop_edges[i].first].sx,\n\t\t\t\t\t\tposes[loop_edges[i].first].sy,\n\t\t\t\t\t\tposes[loop_edges[i].first].sz,\n\t\t\t\t\t\tposes[loop_edges[i].second].px,\n\t\t\t\t\t\tposes[loop_edges[i].second].py,\n\t\t\t\t\t\tposes[loop_edges[i].second].pz,\n\t\t\t\t\t\tposes[loop_edges[i].second].sx,\n\t\t\t\t\t\tposes[loop_edges[i].second].sy,\n\t\t\t\t\t\tposes[loop_edges[i].second].sz,\n\t\t\t\t\t\trelative_pose_measurement_loop(0,0),\n\t\t\t\t\t\trelative_pose_measurement_loop(1,0),\n\t\t\t\t\t\trelative_pose_measurement_loop(2,0),\n\t\t\t\t\t\trelative_pose_measurement_loop(3,0),\n\t\t\t\t\t\trelative_pose_measurement_loop(4,0),\n\t\t\t\t\t\trelative_pose_measurement_loop(5,0));\n\n\t\t\t\tEigen::Matrix<double, 6, 12, Eigen::RowMajor> jacobian;\n\t\t\t\trelative_pose_obs_eq_rodrigues_wc_jacobian(jacobian,\n\t\t\t\t\t\tposes[loop_edges[i].first].px,\n\t\t\t\t\t\tposes[loop_edges[i].first].py,\n\t\t\t\t\t\tposes[loop_edges[i].first].pz,\n\t\t\t\t\t\tposes[loop_edges[i].first].sx,\n\t\t\t\t\t\tposes[loop_edges[i].first].sy,\n\t\t\t\t\t\tposes[loop_edges[i].first].sz,\n\t\t\t\t\t\tposes[loop_edges[i].second].px,\n\t\t\t\t\t\tposes[loop_edges[i].second].py,\n\t\t\t\t\t\tposes[loop_edges[i].second].pz,\n\t\t\t\t\t\tposes[loop_edges[i].second].sx,\n\t\t\t\t\t\tposes[loop_edges[i].second].sy,\n\t\t\t\t\t\tposes[loop_edges[i].second].sz);\n\n\t\t\t\tint ir = tripletListB.size();\n\n\t\t\t\tint ic_1 = loop_edges[i].first * 6;\n\t\t\t\tint ic_2 = loop_edges[i].second * 6;\n\n\t\t\t\tfor(size_t row = 0 ; row < 6; row ++){\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_1    , -jacobian(row,0));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_1 + 1, -jacobian(row,1));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_1 + 2, -jacobian(row,2));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_1 + 3, -jacobian(row,3));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_1 + 4, -jacobian(row,4));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_1 + 5, -jacobian(row,5));\n\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_2    , -jacobian(row,6));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_2 + 1, -jacobian(row,7));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_2 + 2, -jacobian(row,8));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_2 + 3, -jacobian(row,9));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_2 + 4, -jacobian(row,10));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_2 + 5, -jacobian(row,11));\n\t\t\t\t}\n\n\t\t\t\ttripletListB.emplace_back(ir,     0, delta(0,0));\n\t\t\t\ttripletListB.emplace_back(ir + 1, 0, delta(1,0));\n\t\t\t\ttripletListB.emplace_back(ir + 2, 0, delta(2,0));\n\t\t\t\ttripletListB.emplace_back(ir + 3, 0, delta(3,0));\n\t\t\t\ttripletListB.emplace_back(ir + 4, 0, delta(4,0));\n\t\t\t\ttripletListB.emplace_back(ir + 5, 0, delta(5,0));\n\n\t\t\t\ttripletListP.emplace_back(ir ,    ir,     1);\n\t\t\t\ttripletListP.emplace_back(ir + 1, ir + 1, 1);\n\t\t\t\ttripletListP.emplace_back(ir + 2, ir + 2, 1);\n\t\t\t\ttripletListP.emplace_back(ir + 3, ir + 3, 1);\n\t\t\t\ttripletListP.emplace_back(ir + 4, ir + 4, 1);\n\t\t\t\ttripletListP.emplace_back(ir + 5, ir + 5, 1);\n\t\t\t}\n\n\t\t\tfor(size_t i = 0; i < georeference_data.size(); i++){\n\t\t\t\tint ir = tripletListB.size();\n\n\t\t\t\tint ic = georeference_data[i].second * 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, m_poses[georeference_data[i].second](0,3), georeference_data[i].first(0,3));\n\t\t\t\tobservation_equation_constraint_jacobian(jacobian, a, m_poses[georeference_data[i].second](0,3), georeference_data[i].first(0,3));\n\n\t\t\t\ttripletListA.emplace_back(ir, ic,  -jacobian(0,0));\n\t\t\t\ttripletListP.emplace_back(ir, ir,  cauchy(delta, 1));\n\t\t\t\ttripletListB.emplace_back(ir, 0,  delta);\n\n\t\t\t\tobservation_equation_constraint(delta, a, m_poses[georeference_data[i].second](1,3), georeference_data[i].first(1,3));\n\t\t\t\tobservation_equation_constraint_jacobian(jacobian, a, m_poses[georeference_data[i].second](1,3), georeference_data[i].first(1,3));\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,  cauchy(delta, 1));\n\t\t\t\ttripletListB.emplace_back(ir + 1, 0,  delta);\n\n\t\t\t\tobservation_equation_constraint(delta, a, m_poses[georeference_data[i].second](2,3), georeference_data[i].first(2,3));\n\t\t\t\tobservation_equation_constraint_jacobian(jacobian, a, m_poses[georeference_data[i].second](2,3), georeference_data[i].first(2,3));\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,  cauchy(delta, 1));\n\t\t\t\ttripletListB.emplace_back(ir + 2, 0,  delta);\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\tRodriguesPose pose = pose_rodrigues_from_affine_matrix(m_poses[i]);\n\t\t\t\t\tpose.px += h_x[counter++];\n\t\t\t\t\tpose.py += h_x[counter++];\n\t\t\t\t\tpose.pz += h_x[counter++];\n\t\t\t\t\tpose.sx += h_x[counter++];\n\t\t\t\t\tpose.sy += h_x[counter++];\n\t\t\t\t\tpose.sz += h_x[counter++];\n\n\t\t\t\t\tm_poses[i] = affine_matrix_from_pose_rodrigues(pose);\n\t\t\t\t}\n\t\t\t}\n\t\t\tstd::cout << \"optimizing with rodrigues finished\" << std::endl;\n\t\t\tbreak;\n\t\t}\n\t\tcase 'q':{\n\t\t\tstd::vector<Eigen::Triplet<double>> tripletListA;\n\t\t\tstd::vector<Eigen::Triplet<double>> tripletListP;\n\t\t\tstd::vector<Eigen::Triplet<double>> tripletListB;\n\n\t\t\tstd::vector<QuaternionPose> poses;\n\t\t\tstd::vector<QuaternionPose> poses_desired;\n\n\t\t\tfor(size_t i = 0 ; i < m_poses.size(); i++){\n\t\t\t\tposes.push_back(pose_quaternion_from_affine_matrix(m_poses[i]));\n\t\t\t}\n\t\t\tfor(size_t i = 0 ; i < m_poses_desired.size(); i++){\n\t\t\t\tposes_desired.push_back(pose_quaternion_from_affine_matrix(m_poses_desired[i]));\n\t\t\t}\n\n\t\t\tfor(size_t i = 0 ; i < odo_edges.size(); i++){\n\t\t\t\tEigen::Matrix<double, 7, 1> relative_pose_measurement_odo;\n\t\t\t\trelative_pose_quaternion_wc(relative_pose_measurement_odo,\n\t\t\t\t\t\tposes_desired[odo_edges[i].first].px,\n\t\t\t\t\t\tposes_desired[odo_edges[i].first].py,\n\t\t\t\t\t\tposes_desired[odo_edges[i].first].pz,\n\t\t\t\t\t\tposes_desired[odo_edges[i].first].q0,\n\t\t\t\t\t\tposes_desired[odo_edges[i].first].q1,\n\t\t\t\t\t\tposes_desired[odo_edges[i].first].q2,\n\t\t\t\t\t\tposes_desired[odo_edges[i].first].q3,\n\t\t\t\t\t\tposes_desired[odo_edges[i].second].px,\n\t\t\t\t\t\tposes_desired[odo_edges[i].second].py,\n\t\t\t\t\t\tposes_desired[odo_edges[i].second].pz,\n\t\t\t\t\t\tposes_desired[odo_edges[i].second].q0,\n\t\t\t\t\t\tposes_desired[odo_edges[i].second].q1,\n\t\t\t\t\t\tposes_desired[odo_edges[i].second].q2,\n\t\t\t\t\t\tposes_desired[odo_edges[i].second].q3);\n\n\t\t\t\tEigen::Matrix<double, 7, 1> delta;\n\t\t\t\trelative_pose_obs_eq_quaternion_wc(\n\t\t\t\t\t\tdelta,\n\t\t\t\t\t\tposes[odo_edges[i].first].px,\n\t\t\t\t\t\tposes[odo_edges[i].first].py,\n\t\t\t\t\t\tposes[odo_edges[i].first].pz,\n\t\t\t\t\t\tposes[odo_edges[i].first].q0,\n\t\t\t\t\t\tposes[odo_edges[i].first].q1,\n\t\t\t\t\t\tposes[odo_edges[i].first].q2,\n\t\t\t\t\t\tposes[odo_edges[i].first].q3,\n\t\t\t\t\t\tposes[odo_edges[i].second].px,\n\t\t\t\t\t\tposes[odo_edges[i].second].py,\n\t\t\t\t\t\tposes[odo_edges[i].second].pz,\n\t\t\t\t\t\tposes[odo_edges[i].second].q0,\n\t\t\t\t\t\tposes[odo_edges[i].second].q1,\n\t\t\t\t\t\tposes[odo_edges[i].second].q2,\n\t\t\t\t\t\tposes[odo_edges[i].second].q3,\n\t\t\t\t\t\trelative_pose_measurement_odo(0,0),\n\t\t\t\t\t\trelative_pose_measurement_odo(1,0),\n\t\t\t\t\t\trelative_pose_measurement_odo(2,0),\n\t\t\t\t\t\trelative_pose_measurement_odo(3,0),\n\t\t\t\t\t\trelative_pose_measurement_odo(4,0),\n\t\t\t\t\t\trelative_pose_measurement_odo(5,0),\n\t\t\t\t\t\trelative_pose_measurement_odo(6,0));\n\n\t\t\t\tEigen::Matrix<double, 7, 14, Eigen::RowMajor> jacobian;\n\t\t\t\trelative_pose_obs_eq_quaternion_wc_jacobian(jacobian,\n\t\t\t\t\t\tposes[odo_edges[i].first].px,\n\t\t\t\t\t\tposes[odo_edges[i].first].py,\n\t\t\t\t\t\tposes[odo_edges[i].first].pz,\n\t\t\t\t\t\tposes[odo_edges[i].first].q0,\n\t\t\t\t\t\tposes[odo_edges[i].first].q1,\n\t\t\t\t\t\tposes[odo_edges[i].first].q2,\n\t\t\t\t\t\tposes[odo_edges[i].first].q3,\n\t\t\t\t\t\tposes[odo_edges[i].second].px,\n\t\t\t\t\t\tposes[odo_edges[i].second].py,\n\t\t\t\t\t\tposes[odo_edges[i].second].pz,\n\t\t\t\t\t\tposes[odo_edges[i].second].q0,\n\t\t\t\t\t\tposes[odo_edges[i].second].q1,\n\t\t\t\t\t\tposes[odo_edges[i].second].q2,\n\t\t\t\t\t\tposes[odo_edges[i].second].q3);\n\n\t\t\t\tint ir = tripletListB.size();\n\n\t\t\t\tint ic_1 = odo_edges[i].first * 7;\n\t\t\t\tint ic_2 = odo_edges[i].second * 7;\n\n\t\t\t\tfor(size_t row = 0 ; row < 7; row ++){\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_1    , -jacobian(row,0));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_1 + 1, -jacobian(row,1));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_1 + 2, -jacobian(row,2));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_1 + 3, -jacobian(row,3));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_1 + 4, -jacobian(row,4));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_1 + 5, -jacobian(row,5));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_1 + 6, -jacobian(row,6));\n\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_2    , -jacobian(row,7));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_2 + 1, -jacobian(row,8));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_2 + 2, -jacobian(row,9));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_2 + 3, -jacobian(row,10));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_2 + 4, -jacobian(row,11));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_2 + 5, -jacobian(row,12));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_2 + 6, -jacobian(row,13));\n\t\t\t\t}\n\n\t\t\t\ttripletListB.emplace_back(ir,     0, delta(0,0));\n\t\t\t\ttripletListB.emplace_back(ir + 1, 0, delta(1,0));\n\t\t\t\ttripletListB.emplace_back(ir + 2, 0, delta(2,0));\n\t\t\t\ttripletListB.emplace_back(ir + 3, 0, delta(3,0));\n\t\t\t\ttripletListB.emplace_back(ir + 4, 0, delta(4,0));\n\t\t\t\ttripletListB.emplace_back(ir + 5, 0, delta(5,0));\n\t\t\t\ttripletListB.emplace_back(ir + 6, 0, delta(6,0));\n\n\t\t\t\ttripletListP.emplace_back(ir ,    ir,     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\ttripletListP.emplace_back(ir + 6, ir + 6, 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, 7, 1> relative_pose_measurement_loop;\n\t\t\t\trelative_pose_quaternion_wc(relative_pose_measurement_loop,\n\t\t\t\t\t\tposes_desired[loop_edges[i].first].px,\n\t\t\t\t\t\tposes_desired[loop_edges[i].first].py,\n\t\t\t\t\t\tposes_desired[loop_edges[i].first].pz,\n\t\t\t\t\t\tposes_desired[loop_edges[i].first].q0,\n\t\t\t\t\t\tposes_desired[loop_edges[i].first].q1,\n\t\t\t\t\t\tposes_desired[loop_edges[i].first].q2,\n\t\t\t\t\t\tposes_desired[loop_edges[i].first].q3,\n\t\t\t\t\t\tposes_desired[loop_edges[i].second].px,\n\t\t\t\t\t\tposes_desired[loop_edges[i].second].py,\n\t\t\t\t\t\tposes_desired[loop_edges[i].second].pz,\n\t\t\t\t\t\tposes_desired[loop_edges[i].second].q0,\n\t\t\t\t\t\tposes_desired[loop_edges[i].second].q1,\n\t\t\t\t\t\tposes_desired[loop_edges[i].second].q2,\n\t\t\t\t\t\tposes_desired[loop_edges[i].second].q3);\n\n\t\t\t\tEigen::Matrix<double, 7, 1> delta;\n\t\t\t\trelative_pose_obs_eq_quaternion_wc(\n\t\t\t\t\t\tdelta,\n\t\t\t\t\t\tposes[loop_edges[i].first].px,\n\t\t\t\t\t\tposes[loop_edges[i].first].py,\n\t\t\t\t\t\tposes[loop_edges[i].first].pz,\n\t\t\t\t\t\tposes[loop_edges[i].first].q0,\n\t\t\t\t\t\tposes[loop_edges[i].first].q1,\n\t\t\t\t\t\tposes[loop_edges[i].first].q2,\n\t\t\t\t\t\tposes[loop_edges[i].first].q3,\n\t\t\t\t\t\tposes[loop_edges[i].second].px,\n\t\t\t\t\t\tposes[loop_edges[i].second].py,\n\t\t\t\t\t\tposes[loop_edges[i].second].pz,\n\t\t\t\t\t\tposes[loop_edges[i].second].q0,\n\t\t\t\t\t\tposes[loop_edges[i].second].q1,\n\t\t\t\t\t\tposes[loop_edges[i].second].q2,\n\t\t\t\t\t\tposes[loop_edges[i].second].q3,\n\t\t\t\t\t\trelative_pose_measurement_loop(0,0),\n\t\t\t\t\t\trelative_pose_measurement_loop(1,0),\n\t\t\t\t\t\trelative_pose_measurement_loop(2,0),\n\t\t\t\t\t\trelative_pose_measurement_loop(3,0),\n\t\t\t\t\t\trelative_pose_measurement_loop(4,0),\n\t\t\t\t\t\trelative_pose_measurement_loop(5,0),\n\t\t\t\t\t\trelative_pose_measurement_loop(6,0));\n\n\t\t\t\tEigen::Matrix<double, 7, 14, Eigen::RowMajor> jacobian;\n\t\t\t\trelative_pose_obs_eq_quaternion_wc_jacobian(jacobian,\n\t\t\t\t\t\tposes[loop_edges[i].first].px,\n\t\t\t\t\t\tposes[loop_edges[i].first].py,\n\t\t\t\t\t\tposes[loop_edges[i].first].pz,\n\t\t\t\t\t\tposes[loop_edges[i].first].q0,\n\t\t\t\t\t\tposes[loop_edges[i].first].q1,\n\t\t\t\t\t\tposes[loop_edges[i].first].q2,\n\t\t\t\t\t\tposes[loop_edges[i].first].q3,\n\t\t\t\t\t\tposes[loop_edges[i].second].px,\n\t\t\t\t\t\tposes[loop_edges[i].second].py,\n\t\t\t\t\t\tposes[loop_edges[i].second].pz,\n\t\t\t\t\t\tposes[loop_edges[i].second].q0,\n\t\t\t\t\t\tposes[loop_edges[i].second].q1,\n\t\t\t\t\t\tposes[loop_edges[i].second].q2,\n\t\t\t\t\t\tposes[loop_edges[i].second].q3);\n\n\t\t\t\tint ir = tripletListB.size();\n\n\t\t\t\tint ic_1 = loop_edges[i].first * 7;\n\t\t\t\tint ic_2 = loop_edges[i].second * 7;\n\n\t\t\t\tfor(size_t row = 0 ; row < 7; row ++){\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_1    , -jacobian(row,0));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_1 + 1, -jacobian(row,1));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_1 + 2, -jacobian(row,2));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_1 + 3, -jacobian(row,3));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_1 + 4, -jacobian(row,4));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_1 + 5, -jacobian(row,5));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_1 + 6, -jacobian(row,6));\n\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_2    , -jacobian(row,7));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_2 + 1, -jacobian(row,8));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_2 + 2, -jacobian(row,9));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_2 + 3, -jacobian(row,10));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_2 + 4, -jacobian(row,11));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_2 + 5, -jacobian(row,12));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_2 + 6, -jacobian(row,13));\n\t\t\t\t}\n\n\t\t\t\ttripletListB.emplace_back(ir,     0, delta(0,0));\n\t\t\t\ttripletListB.emplace_back(ir + 1, 0, delta(1,0));\n\t\t\t\ttripletListB.emplace_back(ir + 2, 0, delta(2,0));\n\t\t\t\ttripletListB.emplace_back(ir + 3, 0, delta(3,0));\n\t\t\t\ttripletListB.emplace_back(ir + 4, 0, delta(4,0));\n\t\t\t\ttripletListB.emplace_back(ir + 5, 0, delta(5,0));\n\t\t\t\ttripletListB.emplace_back(ir + 6, 0, delta(6,0));\n\n\t\t\t\ttripletListP.emplace_back(ir ,    ir,     1);\n\t\t\t\ttripletListP.emplace_back(ir + 1, ir + 1, 1);\n\t\t\t\ttripletListP.emplace_back(ir + 2, ir + 2, 1);\n\t\t\t\ttripletListP.emplace_back(ir + 3, ir + 3, 1);\n\t\t\t\ttripletListP.emplace_back(ir + 4, ir + 4, 1);\n\t\t\t\ttripletListP.emplace_back(ir + 5, ir + 5, 1);\n\t\t\t\ttripletListP.emplace_back(ir + 6, ir + 6, 1);\n\t\t\t}\n\n\t\t\tfor(size_t i = 0; i < georeference_data.size(); i++){\n\t\t\t\tint ir = tripletListB.size();\n\t\t\t\tint ic = georeference_data[i].second * 7;\n\n\t\t\t\tQuaternionPose pose_s = pose_quaternion_from_affine_matrix(m_poses[georeference_data[i].second]);\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\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_quaternion_wc(delta_x, delta_y, delta_z, pose_s.px, pose_s.py, pose_s.pz, pose_s.q0, pose_s.q1, pose_s.q2, pose_s.q3, 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, 7, Eigen::RowMajor> jacobian;\n\t\t\t\tpoint_to_point_source_to_target_quaternion_wc_jacobian(jacobian, pose_s.px, pose_s.py, pose_s.pz, pose_s.q0, pose_s.q1, pose_s.q2, pose_s.q3, p_s.x(), p_s.y(), p_s.z());\n\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    ,  cauchy(delta_x, 1));\n\t\t\t\ttripletListP.emplace_back(ir + 1, ir + 1,  cauchy(delta_y, 1));\n\t\t\t\ttripletListP.emplace_back(ir + 2, ir + 2,  cauchy(delta_z, 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\t\t\tfor(size_t i = 0 ; i < m_poses.size(); i++){\n\t\t\t\tint ic = i * 7;\n\t\t\t\tint ir = tripletListB.size();\n\t\t\t\tQuaternionPose pose = pose_quaternion_from_affine_matrix(m_poses[i]);\n\n\t\t\t\tdouble delta;\n\t\t\t\tquaternion_constraint(delta, pose.q0, pose.q1, pose.q2, pose.q3);\n\n\t\t\t\tEigen::Matrix<double, 1, 4> jacobian;\n\t\t\t\tquaternion_constraint_jacobian(jacobian, pose.q0, pose.q1, pose.q2, pose.q3);\n\n\t\t\t\ttripletListA.emplace_back(ir, ic + 3 , -jacobian(0,0));\n\t\t\t\ttripletListA.emplace_back(ir, ic + 4 , -jacobian(0,1));\n\t\t\t\ttripletListA.emplace_back(ir, ic + 5 , -jacobian(0,2));\n\t\t\t\ttripletListA.emplace_back(ir, ic + 6 , -jacobian(0,3));\n\n\t\t\t\ttripletListP.emplace_back(ir, ir, 1000000.0);\n\n\t\t\t\ttripletListB.emplace_back(ir, 0, delta);\n\t\t\t}\n\n\n\t\t\tEigen::SparseMatrix<double> matA(tripletListB.size(), m_poses.size() * 7);\n\t\t\tEigen::SparseMatrix<double> matP(tripletListB.size(), tripletListB.size());\n\t\t\tEigen::SparseMatrix<double> matB(tripletListB.size(), 1);\n\n\t\t\tmatA.setFromTriplets(tripletListA.begin(), tripletListA.end());\n\t\t\tmatP.setFromTriplets(tripletListP.begin(), tripletListP.end());\n\t\t\tmatB.setFromTriplets(tripletListB.begin(), tripletListB.end());\n\n\n\t\t\tEigen::SparseMatrix<double> AtPA(m_poses.size() * 7 , m_poses.size() * 7);\n\t\t\tEigen::SparseMatrix<double> AtPB(m_poses.size() * 7 , 1);\n\n\t\t\t{\n\t\t\tEigen::SparseMatrix<double> AtP = matA.transpose() * matP;\n\t\t\tAtPA = (AtP) * matA;\n\t\t\tAtPB = (AtP) * matB;\n\t\t\t}\n\n\t\t\ttripletListA.clear();\n\t\t\ttripletListP.clear();\n\t\t\ttripletListB.clear();\n\n\t\t\tstd::cout << \"AtPA.size: \" << AtPA.size() << std::endl;\n\t\t\tstd::cout << \"AtPB.size: \" << AtPB.size() << std::endl;\n\n\t\t\tstd::cout << \"start solving AtPA=AtPB\" << std::endl;\n\t\t\tEigen::SimplicialCholesky<Eigen::SparseMatrix<double>> solver(AtPA);\n\n\t\t\tstd::cout << \"x = solver.solve(AtPB)\" << std::endl;\n\t\t\tEigen::SparseMatrix<double> x = solver.solve(AtPB);\n\n\t\t\tstd::vector<double> h_x;\n\n\t\t\tfor (int k=0; k<x.outerSize(); ++k){\n\t\t\t\tfor (Eigen::SparseMatrix<double>::InnerIterator it(x,k); it; ++it){\n\t\t\t\t\th_x.push_back(it.value());\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tstd::cout << \"h_x.size(): \" << h_x.size() << std::endl;\n\n\t\t\tstd::cout << \"AtPA=AtPB SOLVED\" << std::endl;\n\n\t\t\tfor(size_t i = 0 ; i < h_x.size(); i++){\n\t\t\t\tstd::cout << h_x[i] << std::endl;\n\t\t\t}\n\n\t\t\tif(h_x.size() == 7 * m_poses.size()){\n\t\t\t\tint counter = 0;\n\n\t\t\t\tfor(size_t i = 0; i < m_poses.size(); i++){\n\t\t\t\t\tQuaternionPose pose = pose_quaternion_from_affine_matrix(m_poses[i]);\n\t\t\t\t\tpose.px += h_x[counter++];\n\t\t\t\t\tpose.py += h_x[counter++];\n\t\t\t\t\tpose.pz += h_x[counter++];\n\t\t\t\t\tpose.q0 += h_x[counter++];\n\t\t\t\t\tpose.q1 += h_x[counter++];\n\t\t\t\t\tpose.q2 += h_x[counter++];\n\t\t\t\t\tpose.q3 += h_x[counter++];\n\t\t\t\t\tm_poses[i] = affine_matrix_from_pose_quaternion(pose);\n\t\t\t\t}\n\t\t\t}\n\t\t\tstd::cout << \"optimizing with quaternions finished\" << std::endl;\n\t\t\tbreak;\n\t\t}\n\t\tcase 'w':{\n\t\t\tstd::vector<Eigen::Triplet<double>> tripletListA;\n\t\t\tstd::vector<Eigen::Triplet<double>> tripletListP;\n\t\t\tstd::vector<Eigen::Triplet<double>> tripletListB;\n\n\t\t\tstd::vector<QuaternionPose> poses;\n\t\t\tstd::vector<QuaternionPose> poses_desired;\n\n\t\t\tfor(size_t i = 0 ; i < m_poses.size(); i++){\n\t\t\t\tposes.push_back(pose_quaternion_from_affine_matrix(m_poses[i]));\n\t\t\t}\n\t\t\tfor(size_t i = 0 ; i < m_poses_desired.size(); i++){\n\t\t\t\tposes_desired.push_back(pose_quaternion_from_affine_matrix(m_poses_desired[i]));\n\t\t\t}\n\n\t\t\tfor(size_t i = 0 ; i < odo_edges.size(); i++){\n\t\t\t\tEigen::Matrix<double, 7, 1> relative_pose_measurement_odo;\n\t\t\t\trelative_pose_quaternion_wc(relative_pose_measurement_odo,\n\t\t\t\t\t\tposes_desired[odo_edges[i].first].px,\n\t\t\t\t\t\tposes_desired[odo_edges[i].first].py,\n\t\t\t\t\t\tposes_desired[odo_edges[i].first].pz,\n\t\t\t\t\t\tposes_desired[odo_edges[i].first].q0,\n\t\t\t\t\t\tposes_desired[odo_edges[i].first].q1,\n\t\t\t\t\t\tposes_desired[odo_edges[i].first].q2,\n\t\t\t\t\t\tposes_desired[odo_edges[i].first].q3,\n\t\t\t\t\t\tposes_desired[odo_edges[i].second].px,\n\t\t\t\t\t\tposes_desired[odo_edges[i].second].py,\n\t\t\t\t\t\tposes_desired[odo_edges[i].second].pz,\n\t\t\t\t\t\tposes_desired[odo_edges[i].second].q0,\n\t\t\t\t\t\tposes_desired[odo_edges[i].second].q1,\n\t\t\t\t\t\tposes_desired[odo_edges[i].second].q2,\n\t\t\t\t\t\tposes_desired[odo_edges[i].second].q3);\n\n\t\t\t\tEigen::Matrix<double, 7, 1> delta;\n\t\t\t\trelative_pose_obs_eq_quaternion_wc(\n\t\t\t\t\t\tdelta,\n\t\t\t\t\t\tposes[odo_edges[i].first].px,\n\t\t\t\t\t\tposes[odo_edges[i].first].py,\n\t\t\t\t\t\tposes[odo_edges[i].first].pz,\n\t\t\t\t\t\tposes[odo_edges[i].first].q0,\n\t\t\t\t\t\tposes[odo_edges[i].first].q1,\n\t\t\t\t\t\tposes[odo_edges[i].first].q2,\n\t\t\t\t\t\tposes[odo_edges[i].first].q3,\n\t\t\t\t\t\tposes[odo_edges[i].second].px,\n\t\t\t\t\t\tposes[odo_edges[i].second].py,\n\t\t\t\t\t\tposes[odo_edges[i].second].pz,\n\t\t\t\t\t\tposes[odo_edges[i].second].q0,\n\t\t\t\t\t\tposes[odo_edges[i].second].q1,\n\t\t\t\t\t\tposes[odo_edges[i].second].q2,\n\t\t\t\t\t\tposes[odo_edges[i].second].q3,\n\t\t\t\t\t\trelative_pose_measurement_odo(0,0),\n\t\t\t\t\t\trelative_pose_measurement_odo(1,0),\n\t\t\t\t\t\trelative_pose_measurement_odo(2,0),\n\t\t\t\t\t\trelative_pose_measurement_odo(3,0),\n\t\t\t\t\t\trelative_pose_measurement_odo(4,0),\n\t\t\t\t\t\trelative_pose_measurement_odo(5,0),\n\t\t\t\t\t\trelative_pose_measurement_odo(6,0));\n\n\t\t\t\tEigen::Matrix<double, 7, 14, Eigen::RowMajor> jacobian;\n\t\t\t\trelative_pose_obs_eq_quaternion_wc_jacobian(jacobian,\n\t\t\t\t\t\tposes[odo_edges[i].first].px,\n\t\t\t\t\t\tposes[odo_edges[i].first].py,\n\t\t\t\t\t\tposes[odo_edges[i].first].pz,\n\t\t\t\t\t\tposes[odo_edges[i].first].q0,\n\t\t\t\t\t\tposes[odo_edges[i].first].q1,\n\t\t\t\t\t\tposes[odo_edges[i].first].q2,\n\t\t\t\t\t\tposes[odo_edges[i].first].q3,\n\t\t\t\t\t\tposes[odo_edges[i].second].px,\n\t\t\t\t\t\tposes[odo_edges[i].second].py,\n\t\t\t\t\t\tposes[odo_edges[i].second].pz,\n\t\t\t\t\t\tposes[odo_edges[i].second].q0,\n\t\t\t\t\t\tposes[odo_edges[i].second].q1,\n\t\t\t\t\t\tposes[odo_edges[i].second].q2,\n\t\t\t\t\t\tposes[odo_edges[i].second].q3);\n\n\t\t\t\tint ir = tripletListB.size();\n\n\t\t\t\tint ic_1 = odo_edges[i].first * 7;\n\t\t\t\tint ic_2 = odo_edges[i].second * 7;\n\n\t\t\t\tfor(size_t row = 0 ; row < 7; row ++){\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_1    , -jacobian(row,0));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_1 + 1, -jacobian(row,1));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_1 + 2, -jacobian(row,2));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_1 + 3, -jacobian(row,3));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_1 + 4, -jacobian(row,4));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_1 + 5, -jacobian(row,5));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_1 + 6, -jacobian(row,6));\n\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_2    , -jacobian(row,7));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_2 + 1, -jacobian(row,8));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_2 + 2, -jacobian(row,9));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_2 + 3, -jacobian(row,10));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_2 + 4, -jacobian(row,11));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_2 + 5, -jacobian(row,12));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_2 + 6, -jacobian(row,13));\n\t\t\t\t}\n\n\t\t\t\ttripletListB.emplace_back(ir,     0, delta(0,0));\n\t\t\t\ttripletListB.emplace_back(ir + 1, 0, delta(1,0));\n\t\t\t\ttripletListB.emplace_back(ir + 2, 0, delta(2,0));\n\t\t\t\ttripletListB.emplace_back(ir + 3, 0, delta(3,0));\n\t\t\t\ttripletListB.emplace_back(ir + 4, 0, delta(4,0));\n\t\t\t\ttripletListB.emplace_back(ir + 5, 0, delta(5,0));\n\t\t\t\ttripletListB.emplace_back(ir + 6, 0, delta(6,0));\n\n\t\t\t\ttripletListP.emplace_back(ir ,    ir,     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\ttripletListP.emplace_back(ir + 6, ir + 6, 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, 7, 1> relative_pose_measurement_loop;\n\t\t\t\trelative_pose_quaternion_wc(relative_pose_measurement_loop,\n\t\t\t\t\t\tposes_desired[loop_edges[i].first].px,\n\t\t\t\t\t\tposes_desired[loop_edges[i].first].py,\n\t\t\t\t\t\tposes_desired[loop_edges[i].first].pz,\n\t\t\t\t\t\tposes_desired[loop_edges[i].first].q0,\n\t\t\t\t\t\tposes_desired[loop_edges[i].first].q1,\n\t\t\t\t\t\tposes_desired[loop_edges[i].first].q2,\n\t\t\t\t\t\tposes_desired[loop_edges[i].first].q3,\n\t\t\t\t\t\tposes_desired[loop_edges[i].second].px,\n\t\t\t\t\t\tposes_desired[loop_edges[i].second].py,\n\t\t\t\t\t\tposes_desired[loop_edges[i].second].pz,\n\t\t\t\t\t\tposes_desired[loop_edges[i].second].q0,\n\t\t\t\t\t\tposes_desired[loop_edges[i].second].q1,\n\t\t\t\t\t\tposes_desired[loop_edges[i].second].q2,\n\t\t\t\t\t\tposes_desired[loop_edges[i].second].q3);\n\n\t\t\t\tEigen::Matrix<double, 7, 1> delta;\n\t\t\t\trelative_pose_obs_eq_quaternion_wc(\n\t\t\t\t\t\tdelta,\n\t\t\t\t\t\tposes[loop_edges[i].first].px,\n\t\t\t\t\t\tposes[loop_edges[i].first].py,\n\t\t\t\t\t\tposes[loop_edges[i].first].pz,\n\t\t\t\t\t\tposes[loop_edges[i].first].q0,\n\t\t\t\t\t\tposes[loop_edges[i].first].q1,\n\t\t\t\t\t\tposes[loop_edges[i].first].q2,\n\t\t\t\t\t\tposes[loop_edges[i].first].q3,\n\t\t\t\t\t\tposes[loop_edges[i].second].px,\n\t\t\t\t\t\tposes[loop_edges[i].second].py,\n\t\t\t\t\t\tposes[loop_edges[i].second].pz,\n\t\t\t\t\t\tposes[loop_edges[i].second].q0,\n\t\t\t\t\t\tposes[loop_edges[i].second].q1,\n\t\t\t\t\t\tposes[loop_edges[i].second].q2,\n\t\t\t\t\t\tposes[loop_edges[i].second].q3,\n\t\t\t\t\t\trelative_pose_measurement_loop(0,0),\n\t\t\t\t\t\trelative_pose_measurement_loop(1,0),\n\t\t\t\t\t\trelative_pose_measurement_loop(2,0),\n\t\t\t\t\t\trelative_pose_measurement_loop(3,0),\n\t\t\t\t\t\trelative_pose_measurement_loop(4,0),\n\t\t\t\t\t\trelative_pose_measurement_loop(5,0),\n\t\t\t\t\t\trelative_pose_measurement_loop(6,0));\n\n\t\t\t\tEigen::Matrix<double, 7, 14, Eigen::RowMajor> jacobian;\n\t\t\t\trelative_pose_obs_eq_quaternion_wc_jacobian(jacobian,\n\t\t\t\t\t\tposes[loop_edges[i].first].px,\n\t\t\t\t\t\tposes[loop_edges[i].first].py,\n\t\t\t\t\t\tposes[loop_edges[i].first].pz,\n\t\t\t\t\t\tposes[loop_edges[i].first].q0,\n\t\t\t\t\t\tposes[loop_edges[i].first].q1,\n\t\t\t\t\t\tposes[loop_edges[i].first].q2,\n\t\t\t\t\t\tposes[loop_edges[i].first].q3,\n\t\t\t\t\t\tposes[loop_edges[i].second].px,\n\t\t\t\t\t\tposes[loop_edges[i].second].py,\n\t\t\t\t\t\tposes[loop_edges[i].second].pz,\n\t\t\t\t\t\tposes[loop_edges[i].second].q0,\n\t\t\t\t\t\tposes[loop_edges[i].second].q1,\n\t\t\t\t\t\tposes[loop_edges[i].second].q2,\n\t\t\t\t\t\tposes[loop_edges[i].second].q3);\n\n\t\t\t\tint ir = tripletListB.size();\n\n\t\t\t\tint ic_1 = loop_edges[i].first * 7;\n\t\t\t\tint ic_2 = loop_edges[i].second * 7;\n\n\t\t\t\tfor(size_t row = 0 ; row < 7; row ++){\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_1    , -jacobian(row,0));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_1 + 1, -jacobian(row,1));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_1 + 2, -jacobian(row,2));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_1 + 3, -jacobian(row,3));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_1 + 4, -jacobian(row,4));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_1 + 5, -jacobian(row,5));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_1 + 6, -jacobian(row,6));\n\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_2    , -jacobian(row,7));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_2 + 1, -jacobian(row,8));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_2 + 2, -jacobian(row,9));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_2 + 3, -jacobian(row,10));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_2 + 4, -jacobian(row,11));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_2 + 5, -jacobian(row,12));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_2 + 6, -jacobian(row,13));\n\t\t\t\t}\n\n\t\t\t\ttripletListB.emplace_back(ir,     0, delta(0,0));\n\t\t\t\ttripletListB.emplace_back(ir + 1, 0, delta(1,0));\n\t\t\t\ttripletListB.emplace_back(ir + 2, 0, delta(2,0));\n\t\t\t\ttripletListB.emplace_back(ir + 3, 0, delta(3,0));\n\t\t\t\ttripletListB.emplace_back(ir + 4, 0, delta(4,0));\n\t\t\t\ttripletListB.emplace_back(ir + 5, 0, delta(5,0));\n\t\t\t\ttripletListB.emplace_back(ir + 6, 0, delta(6,0));\n\n\t\t\t\ttripletListP.emplace_back(ir ,    ir,     1);\n\t\t\t\ttripletListP.emplace_back(ir + 1, ir + 1, 1);\n\t\t\t\ttripletListP.emplace_back(ir + 2, ir + 2, 1);\n\t\t\t\ttripletListP.emplace_back(ir + 3, ir + 3, 1);\n\t\t\t\ttripletListP.emplace_back(ir + 4, ir + 4, 1);\n\t\t\t\ttripletListP.emplace_back(ir + 5, ir + 5, 1);\n\t\t\t\ttripletListP.emplace_back(ir + 6, ir + 6, 1);\n\t\t\t}\n\n\t\t\tfor(size_t i = 0; i < georeference_data.size(); i++){\n\t\t\t\tint ir = tripletListB.size();\n\t\t\t\tint ic = georeference_data[i].second * 7;\n\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, m_poses[georeference_data[i].second](0,3), georeference_data[i].first(0,3));\n\t\t\t\tobservation_equation_constraint_jacobian(jacobian, a, m_poses[georeference_data[i].second](0,3), georeference_data[i].first(0,3));\n\n\t\t\t\ttripletListA.emplace_back(ir, ic,  -jacobian(0,0));\n\t\t\t\ttripletListP.emplace_back(ir, ir,  cauchy(delta, 1));\n\t\t\t\ttripletListB.emplace_back(ir, 0,  delta);\n\n\t\t\t\tobservation_equation_constraint(delta, a, m_poses[georeference_data[i].second](1,3), georeference_data[i].first(1,3));\n\t\t\t\tobservation_equation_constraint_jacobian(jacobian, a, m_poses[georeference_data[i].second](1,3), georeference_data[i].first(1,3));\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,  cauchy(delta, 1));\n\t\t\t\ttripletListB.emplace_back(ir + 1, 0,  delta);\n\n\t\t\t\tobservation_equation_constraint(delta, a, m_poses[georeference_data[i].second](2,3), georeference_data[i].first(2,3));\n\t\t\t\tobservation_equation_constraint_jacobian(jacobian, a, m_poses[georeference_data[i].second](2,3), georeference_data[i].first(2,3));\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,  cauchy(delta, 1));\n\t\t\t\ttripletListB.emplace_back(ir + 2, 0,  delta);\n\t\t\t}\n\n\t\t\tfor(size_t i = 0 ; i < m_poses.size(); i++){\n\t\t\t\tint ic = i * 7;\n\t\t\t\tint ir = tripletListB.size();\n\t\t\t\tQuaternionPose pose = pose_quaternion_from_affine_matrix(m_poses[i]);\n\n\t\t\t\tdouble delta;\n\t\t\t\tquaternion_constraint(delta, pose.q0, pose.q1, pose.q2, pose.q3);\n\n\t\t\t\tEigen::Matrix<double, 1, 4> jacobian;\n\t\t\t\tquaternion_constraint_jacobian(jacobian, pose.q0, pose.q1, pose.q2, pose.q3);\n\n\t\t\t\ttripletListA.emplace_back(ir, ic + 3 , -jacobian(0,0));\n\t\t\t\ttripletListA.emplace_back(ir, ic + 4 , -jacobian(0,1));\n\t\t\t\ttripletListA.emplace_back(ir, ic + 5 , -jacobian(0,2));\n\t\t\t\ttripletListA.emplace_back(ir, ic + 6 , -jacobian(0,3));\n\n\t\t\t\ttripletListP.emplace_back(ir, ir, 1000000.0);\n\n\t\t\t\ttripletListB.emplace_back(ir, 0, delta);\n\t\t\t}\n\n\n\t\t\tEigen::SparseMatrix<double> matA(tripletListB.size(), m_poses.size() * 7);\n\t\t\tEigen::SparseMatrix<double> matP(tripletListB.size(), tripletListB.size());\n\t\t\tEigen::SparseMatrix<double> matB(tripletListB.size(), 1);\n\n\t\t\tmatA.setFromTriplets(tripletListA.begin(), tripletListA.end());\n\t\t\tmatP.setFromTriplets(tripletListP.begin(), tripletListP.end());\n\t\t\tmatB.setFromTriplets(tripletListB.begin(), tripletListB.end());\n\n\n\t\t\tEigen::SparseMatrix<double> AtPA(m_poses.size() * 7 , m_poses.size() * 7);\n\t\t\tEigen::SparseMatrix<double> AtPB(m_poses.size() * 7 , 1);\n\n\t\t\t{\n\t\t\tEigen::SparseMatrix<double> AtP = matA.transpose() * matP;\n\t\t\tAtPA = (AtP) * matA;\n\t\t\tAtPB = (AtP) * matB;\n\t\t\t}\n\n\t\t\ttripletListA.clear();\n\t\t\ttripletListP.clear();\n\t\t\ttripletListB.clear();\n\n\t\t\tstd::cout << \"AtPA.size: \" << AtPA.size() << std::endl;\n\t\t\tstd::cout << \"AtPB.size: \" << AtPB.size() << std::endl;\n\n\t\t\tstd::cout << \"start solving AtPA=AtPB\" << std::endl;\n\t\t\tEigen::SimplicialCholesky<Eigen::SparseMatrix<double>> solver(AtPA);\n\n\t\t\tstd::cout << \"x = solver.solve(AtPB)\" << std::endl;\n\t\t\tEigen::SparseMatrix<double> x = solver.solve(AtPB);\n\n\t\t\tstd::vector<double> h_x;\n\n\t\t\tfor (int k=0; k<x.outerSize(); ++k){\n\t\t\t\tfor (Eigen::SparseMatrix<double>::InnerIterator it(x,k); it; ++it){\n\t\t\t\t\th_x.push_back(it.value());\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tstd::cout << \"h_x.size(): \" << h_x.size() << std::endl;\n\n\t\t\tstd::cout << \"AtPA=AtPB SOLVED\" << std::endl;\n\n\t\t\tfor(size_t i = 0 ; i < h_x.size(); i++){\n\t\t\t\tstd::cout << h_x[i] << std::endl;\n\t\t\t}\n\n\t\t\tif(h_x.size() == 7 * m_poses.size()){\n\t\t\t\tint counter = 0;\n\n\t\t\t\tfor(size_t i = 0; i < m_poses.size(); i++){\n\t\t\t\t\tQuaternionPose pose = pose_quaternion_from_affine_matrix(m_poses[i]);\n\t\t\t\t\tpose.px += h_x[counter++];\n\t\t\t\t\tpose.py += h_x[counter++];\n\t\t\t\t\tpose.pz += h_x[counter++];\n\t\t\t\t\tpose.q0 += h_x[counter++];\n\t\t\t\t\tpose.q1 += h_x[counter++];\n\t\t\t\t\tpose.q2 += h_x[counter++];\n\t\t\t\t\tpose.q3 += h_x[counter++];\n\t\t\t\t\tm_poses[i] = affine_matrix_from_pose_quaternion(pose);\n\t\t\t\t}\n\t\t\t}\n\t\t\tstd::cout << \"optimizing with quaternions finished\" << std::endl;\n\t\t\tbreak;\n\t\t}\n\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 gps as point source to target)\" << std::endl;\n\tstd::cout << \"r: optimize (Rodriguez and gps as point source to target)\" << std::endl;\n\tstd::cout << \"q: optimize (Quaternion and gps as point source to target)\" << std::endl;\n\tstd::cout << \"y: optimize (Tait-Bryan and gps using linear function constraint)\" << std::endl;\n\tstd::cout << \"e: optimize (Rodriguez and gps using linear function constraint)\" << std::endl;\n\tstd::cout << \"w: optimize (Quaternion and gps using linear function constraint)\" << std::endl;\n}\n\n\n\n\n\n\n\n", "meta": {"hexsha": "fa9e6ac71eabd6a84b493f4dd4b332edec956604", "size": 81559, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "codes/c++Examples/src/georeference-case1.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-case1.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-case1.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": 38.5804162725, "max_line_length": 214, "alphanum_fraction": 0.6570090364, "num_tokens": 27826, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.626124191181315, "lm_q2_score": 0.5506073655352404, "lm_q1q2_score": 0.34474859140422703}}
{"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_SFUNCTOR_INCLUDE\n#define MTL_SFUNCTOR_INCLUDE\n\n#include <cmath>\n#include <boost/numeric/mtl/concept/std_concept.hpp>\n#include <boost/numeric/mtl/concept/magnitude.hpp>\n#include <boost/numeric/mtl/concept/static_functor.hpp>\n#include <boost/numeric/mtl/interface/vpt.hpp>\n\nnamespace mtl { namespace sfunctor {\n\ntemplate <typename Value1, typename Value2>\nstruct plus\n{\n    typedef const Value1&                                 first_argument_type;\n    typedef const Value2&                                 second_argument_type;\n    typedef typename Addable<Value1, Value2>::result_type result_type;\n\n    static inline result_type apply(const Value1& v1, const Value2& v2)\n    {\n\treturn v1 + v2;\n    }\n\n    result_type operator() (const Value1& v1, const Value2& v2) const\n    {\n\tvampir_trace<23> tracer;\n\treturn v1 + v2;\n    }\n};\n    \ntemplate <typename Value1, typename Value2>\nstruct minus\n{\n    typedef const Value1&                                 first_argument_type;\n    typedef const Value2&                                 second_argument_type;\n    typedef typename Subtractable<Value1, Value2>::result_type result_type;\n\n    static inline result_type apply(const Value1& v1, const Value2& v2)\n    {\n\treturn v1 - v2;\n    }\n\n    result_type operator() (const Value1& v1, const Value2& v2) const\n    {\n\tvampir_trace<24> tracer;\n\treturn v1 - v2;\n    }\n};\n\ntemplate <typename Value1, typename Value2>\nstruct times\n{\n    typedef const Value1&                                 first_argument_type;\n    typedef const Value2&                                 second_argument_type;\n    typedef typename Multiplicable<Value1, Value2>::result_type result_type;\n\n    static inline result_type apply(const Value1& v1, const Value2& v2)\n    {\n\treturn v1 * v2;\n    }\n\n    result_type operator() (const Value1& v1, const Value2& v2) const\n    {\n\tvampir_trace<25> tracer;\n\treturn v1 * v2;\n    }\n};\n\ntemplate <typename Value1, typename Value2>\nstruct divide\n{\n    typedef const Value1&                                 first_argument_type;\n    typedef const Value2&                                 second_argument_type;\n    typedef typename Divisible<Value1, Value2>::result_type result_type;\n\n    static inline result_type apply(const Value1& v1, const Value2& v2)\n    {\n\treturn v1 / v2;\n    }\n\n    result_type operator() (const Value1& v1, const Value2& v2) const\n    {\n\tvampir_trace<26> tracer;\n\treturn v1 / v2;\n    }\n};\n\ntemplate <typename Value1, typename Value2>\nstruct assign\n{\n    typedef Value1&                                       first_argument_type;\n    typedef const Value2&                                 second_argument_type;\n    typedef Value1&                                       result_type;\n\n    static inline result_type apply(Value1& v1, const Value2& v2)\n    {\n\treturn v1= v2;\n    }\n\n    result_type operator() (Value1& v1, const Value2& v2) const\n    {\n\tvampir_trace<27> tracer;\n\treturn v1= v2;\n    }\n};\n    \ntemplate <typename Value1, typename Value2>\nstruct plus_assign\n{\n    typedef Value1&                                       first_argument_type;\n    typedef const Value2&                                 second_argument_type;\n    typedef Value1&                                       result_type;\n\n    static inline result_type apply(Value1& v1, const Value2& v2)\n    {\n\treturn v1+= v2;\n    }\n\n    result_type operator() (Value1& v1, const Value2& v2) const\n    {\n\tvampir_trace<28> tracer;\n\treturn v1+= v2;\n    }\n};\n    \ntemplate <typename Value1, typename Value2>\nstruct minus_assign\n{\n    typedef Value1&                                       first_argument_type;\n    typedef const Value2&                                 second_argument_type;\n    typedef Value1&                                       result_type;\n\n    static inline result_type apply(Value1& v1, const Value2& v2)\n    {\n\treturn v1-= v2;\n    }\n\n    result_type operator() (Value1& v1, const Value2& v2) const\n    {\n\tvampir_trace<29> tracer;\n\treturn v1-= v2;\n    }\n};\n\ntemplate <typename Value1, typename Value2>\nstruct times_assign\n{\n    typedef Value1&                                       first_argument_type;\n    typedef const Value2&                                 second_argument_type;\n    typedef Value1&                                       result_type;\n\n    static inline result_type apply(Value1& v1, const Value2& v2)\n    {\n\treturn v1*= v2;\n    }\n\n    result_type operator() (Value1& v1, const Value2& v2) const\n    {\n\tvampir_trace<30> tracer;\n\treturn v1*= v2;\n    }\n};\n\ntemplate <typename Value1, typename Value2>\nstruct divide_assign\n{\n    typedef Value1&                                       first_argument_type;\n    typedef const Value2&                                 second_argument_type;\n    typedef Value1&                                       result_type;\n\n    static inline result_type apply(Value1& v1, const Value2& v2)\n    {\n\treturn v1/= v2;\n    }\n\n    result_type operator() (Value1& v1, const Value2& v2) const\n    {\n\tvampir_trace<31> tracer;\n\treturn v1/= v2;\n    }\n};\n\n\n// Might be helpful for surplus functor arguments\ntemplate <typename Value>\nstruct identity\n{\n    typedef const Value&                                  argument_type;\n    typedef Value                                         result_type;\n\n    static inline result_type apply(const Value& v)\n    {\n\treturn v;\n    }\n\n    result_type operator() (const Value& v) const\n    {\n\tvampir_trace<32> tracer;\n\treturn v;\n    }\n};\n\n\ntemplate <typename Value>\nstruct abs\n{\n    typedef const Value&                                  argument_type;\n    typedef typename Magnitude<Value>::type               result_type;\n\n    static inline result_type apply(const Value& v)\n    {\t\t\t\t\t\t\n\tusing std::abs;\n\treturn abs(v);\n    }\n\n    result_type operator() (const Value& v) \n    {\n\tvampir_trace<33> tracer; \n\treturn apply(v); \n    }\n};\n\ntemplate <typename Value>\nstruct sqrt\n{\n    typedef const Value&                                  argument_type;\n    typedef Value                                         result_type;\n\n    static inline result_type apply(const Value& v)\n    {\t\t\t\t\t\t\n\tusing std::sqrt;\n\treturn sqrt(v);\n    }\n\n    result_type operator() (const Value& v) \n    {\n\tvampir_trace<34> tracer;\n\treturn apply(v); \n    }\n};\n\ntemplate <typename Value>\nstruct square\n{\n    typedef const Value&                                  argument_type;\n    typedef Value                                         result_type;\n\n    static inline result_type apply(const Value& v)\n    {\t\t\t\t\t\t\n\treturn v * v;\n    }\n\n    result_type operator() (const Value& v) \n    {\n\tvampir_trace<35> tracer;\n\treturn apply(v);\n    }\n};\n\n\ntemplate <typename Value>\nstruct negate\n{\n    typedef const Value&                                  argument_type;\n    typedef Value                                         result_type;\n\n    static inline result_type apply(const Value& v) { return -v;  }\n    result_type operator() (const Value& v) const \n    {\n\tvampir_trace<36> tracer;\n\treturn -v;\n    }\n};\n\n\n/// Compose functors \\p F and \\p G, i.e. compute f(g(x)).\n/** Functors must be models of StaticUnaryFunctor,\n    StaticUnaryFunctor<G>::result_type must be convertible to\n    StaticUnaryFunctor<F>::argument_type.\n    Under these conditions compose<F, G> will be a model of StaticUnaryFunctor.\n**/\ntemplate <typename F, typename G>\nstruct compose\n{\n    typedef typename StaticUnaryFunctor<G>::argument_type argument_type;\n    typedef typename StaticUnaryFunctor<F>::result_type   result_type;\n    \n    static inline result_type apply(argument_type x)\n    {\n\treturn F::apply(G::apply(x));\n    }\n\n    result_type operator()(argument_type x) \n    {\n\tvampir_trace<37> tracer;\n\treturn apply(x);\n    }\n};\n\n\n/// Compose functors \\p F and \\p G with G in F's first argument, i.e. compute f(g(x), y).\n/** F/G must be models of StaticBinaryFunctor/StaticUnaryFunctor,\n    StaticUnaryFunctor<G>::result_type must be convertible to\n    StaticBinaryFunctor<F>::first_argument_type.\n    Under these conditions compose_first<F, G> will be a model of StaticBinaryFunctor.\n**/\ntemplate <typename F, typename G>\nstruct compose_first\n{\n    typedef typename StaticUnaryFunctor<G>::argument_type         first_argument_type;\n    typedef typename StaticBinaryFunctor<F>::second_argument_type second_argument_type;\n    typedef typename StaticBinaryFunctor<F>::result_type          result_type;\n    \n    static inline result_type apply(first_argument_type x, second_argument_type y)\n    {\n\treturn F::apply(G::apply(x), y);\n    }\n\n    result_type operator()(first_argument_type x, second_argument_type y)\n    {\n\tvampir_trace<38> tracer;\n\treturn apply(x, y);\n    }\n};\n\n\n/// Compose functors \\p F and \\p G with G in F's second argument, i.e. compute f(x, g(y)).\n/** F/G must be models of StaticBinaryFunctor/StaticUnaryFunctor,\n    StaticUnaryFunctor<G>::result_type must be convertible to\n    StaticBinaryFunctor<F>::second_argument_type.\n    Under these conditions compose_second<F, G> will be a model of StaticBinaryFunctor.\n**/\ntemplate <typename F, typename G>\nstruct compose_second\n{\n    typedef typename StaticBinaryFunctor<F>::first_argument_type  first_argument_type;\n    typedef typename StaticUnaryFunctor<G>::argument_type         second_argument_type;\n    typedef typename StaticBinaryFunctor<F>::result_type          result_type;\n    \n    static inline result_type apply(first_argument_type x, second_argument_type y)\n    {\n\treturn F::apply(x, G::apply(y));\n    }\n\n    result_type operator()(first_argument_type x, second_argument_type y)\n    {\n\tvampir_trace<39> tracer;\n\treturn apply(x, y);\n    }\n};\n\n/// Compose functors \\p F, \\p G, and \\p H with G/H in F's first/second argument, i.e. compute f(g(x), h(y)).\n/** F/G must be models of StaticBinaryFunctor/StaticUnaryFunctor,\n    StaticUnaryFunctor<G>::result_type must be convertible to\n    StaticBinaryFunctor<F>::first_argument_type and\n    StaticUnaryFunctor<H>::result_type must be convertible to\n    StaticBinaryFunctor<F>::second_argument_type.\n    Under these conditions compose_both<F, G, H> will be a model of StaticBinaryFunctor.\n**/\ntemplate <typename F, typename G, typename H>\nstruct compose_both\n{\n    typedef typename StaticUnaryFunctor<G>::argument_type         first_argument_type;\n    typedef typename StaticUnaryFunctor<H>::argument_type         second_argument_type;\n    typedef typename StaticBinaryFunctor<F>::result_type          result_type;\n    \n    static inline result_type apply(first_argument_type x, second_argument_type y)\n    {\n\treturn F::apply(G::apply(x), H::apply(y));\n    }\n\n    result_type operator()(first_argument_type x, second_argument_type y)\n    {\n\tvampir_trace<40> tracer;\n\treturn apply(x, y);\n    }\n};\n\n/// Compose unary functor \\p F with binary functor \\p G, i.e. compute f(g(x, y)).\n/** F/G must be models of StaticUnaryFunctor/StaticBinaryFunctor,\n    StaticBinaryFunctor<G>::result_type must be convertible to\n    StaticUnaryFunctor<F>::argument_type.\n    Under these conditions compose_binary<F, G> will be a model of StaticBinaryFunctor.\n**/\ntemplate <typename F, typename G>\nstruct compose_binary\n{\n    typedef typename StaticBinaryFunctor<G>::first_argument_type  first_argument_type;\n    typedef typename StaticBinaryFunctor<G>::second_argument_type second_argument_type;\n    typedef typename StaticUnaryFunctor<F>::result_type           result_type;\n    \n    static inline result_type apply(first_argument_type x, second_argument_type y)\n    {\n\treturn F::apply(G::apply(x, y));\n    }\n\n    result_type operator()(first_argument_type x, second_argument_type y)\n    {\n\tvampir_trace<41> tracer;\n\treturn apply(x, y);\n    }\n};\n\n\n/// Templatized example of composition, computes l_2 norm in 2D, i.e. sqrt(abs(x*x + y*y))\ntemplate <typename T>\nstruct l_2_2D\n  : public compose_binary<sqrt<typename abs<T>::result_type>, \n\t\t\t  compose_binary<abs<T>, \n\t\t\t\t\t compose_both<plus<T, T>, \n\t\t\t\t\t\t      square<T>, \n\t\t\t\t\t\t      square<T>  > \n                                        > \n                         >\n{};\n\n}} // namespace mtl::sfunctor\n\n#endif // MTL_SFUNCTOR_INCLUDE\n", "meta": {"hexsha": "9d01d352c913b280c9cd0669eb45bc8123e3bb59", "size": 12452, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "lib/mtl4/boost/numeric/mtl/operation/sfunctor.hpp", "max_stars_repo_name": "spraetor/amdis2", "max_stars_repo_head_hexsha": "53c45c81a65752a8fafbb54f9ae6724a86639dcd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2018-07-04T16:44:04.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-03T07:26:27.000Z", "max_issues_repo_path": "lib/mtl4/boost/numeric/mtl/operation/sfunctor.hpp", "max_issues_repo_name": "spraetor/amdis2", "max_issues_repo_head_hexsha": "53c45c81a65752a8fafbb54f9ae6724a86639dcd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lib/mtl4/boost/numeric/mtl/operation/sfunctor.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.8240740741, "max_line_length": 108, "alphanum_fraction": 0.6376485705, "num_tokens": 2889, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6261241772283035, "lm_q2_score": 0.5506073655352404, "lm_q1q2_score": 0.3447485837215961}}
{"text": "#pragma once\n\n#include <assert.h>\n\n#include <algorithm>\n#include <boost/property_tree/ptree.hpp>\n#include <boost/property_tree/xml_parser.hpp>\n#include <cmath>\n#include <exception>\n#include <functional>\n#include <iostream>\n#include <iterator>\n#include <map>\n#include <memory>\n#include <opencv2/core/types.hpp>\n#include <opencv2/opencv.hpp>\n#include <regex>\n#include <string>\n#include <utility>\n#include <vector>\n\n#define print_line                                                  \\\n    {                                                               \\\n        std::cout << __FILE__ << \"  ---  \" << __func__ << \"  ---  \" \\\n                  << __LINE__ << std::endl;                         \\\n    }\n\nnamespace utils {\n\ninline int round(float v) {\n    return int(std::round(v));\n}\n\ninline cv::Point2f __add__(const cv::Point2f& a, const std::vector<float>& b) {\n    return cv::Point2f{a.x + b.at(0), a.y + b.at(1)};\n}\n\ninline cv::Point2i pntf2pnti(const cv::Point2f& pnt) {\n    return cv::Point2i{round(pnt.x), round(pnt.y)};\n}\n\ninline void setpntf(cv::Point2f& pntf, std::vector<float>& pt) {\n    assert(pt.size() >= 2);\n    pntf.x = pt.at(0);\n    pntf.y = pt.at(1);\n}\n\nstd::shared_ptr<std::vector<float>> arange(float b, float e, float t) {\n    assert(b < e && t > 0);\n    std::shared_ptr<std::vector<float>> res{new std::vector<float>{}};\n    for (; b < e; b += t) {\n        res->push_back(b);\n    }\n    return res;\n}\nstd::shared_ptr<std::vector<float>> linspace(float b, float e, int cnt = 2) {\n    float c = std::max(2, cnt);\n    assert(b < e && c >= 2.0f);\n    std::shared_ptr<std::vector<float>> res{new std::vector<float>{}};\n    float it = b;\n    float sp = e - b;\n    res->push_back(it);\n    while (c > 2) {\n        float delta = sp / (c - 1.0f);\n        it += delta;\n        sp -= delta;\n        c -= 1.0f;\n        res->push_back(it);\n    }\n    res->push_back(e);\n    return res;\n}\n\ninline float eular_distance(const cv::Point2f& a, const cv::Point2f& b) {\n    cv::Point2f c = a - b;\n    return std::sqrt(c.x * c.x + c.y * c.y);\n}\n\ninline cv::Point2f _get_quadratic_bezier_pnt(const cv::Point2f& b,\n                                             const cv::Point2f& c1,\n                                             const cv::Point2f& c2,\n                                             const cv::Point2f& e,\n                                             float t) {\n    return std::pow((1.0f - t), 3) * b + 3 * std::pow((1.0f - t), 2) * t * c1 +\n           3 * std::pow(t, 2) * (1.0f - t) * c2 + std::pow(t, 3) * e;\n}\nstd::shared_ptr<std::vector<cv::Point2i>> quadratic_bezier(\n    const cv::Point2f& b,\n    const cv::Point2f& c1,\n    const cv::Point2f& c2,\n    const cv::Point2f& e,\n    int cnt = -1) {\n    std::shared_ptr<std::vector<cv::Point2i>> res{\n        new std::vector<cv::Point2i>{}};\n\n    cnt = cnt <= 0 ? int(eular_distance(b, c1) + eular_distance(c1, c2) +\n                         eular_distance(c2, e))\n                   : cnt;\n    auto ts = linspace(0, 1, cnt);\n    for (auto& t : *ts) {\n        res->push_back(pntf2pnti(_get_quadratic_bezier_pnt(b, c1, c2, e, t)));\n    }\n\n    return res;\n}\n\nvoid _get_paths_from_g(boost::property_tree::ptree& pt,\n                       std::vector<boost::property_tree::ptree>& paths) {\n    for (auto& el : pt) {\n        if (el.first == \"g\") {\n            _get_paths_from_g(el.second, paths);\n        } else if (el.first == \"path\") {\n            paths.push_back(el.second);\n        }\n    }\n}\n\nstd::pair<int, int> get_size_from_svg(boost::property_tree::ptree& svg) {\n    auto res = std::make_pair(0, 0);\n    try {\n        res.first  = svg.get<int>(\"<xmlattr>.width\");\n        res.second = svg.get<int>(\"<xmlattr>.height\");\n\n    } catch (std::exception& e) {\n        std::cerr << e.what() << std::endl;\n    }\n\n    return res;\n}\n\nstd::pair<int, int> get_size_from_doc(boost::property_tree::ptree& doc) {\n    auto svg = doc.get_child(\"svg\");\n    return get_size_from_svg(svg);\n}\n\nstd::shared_ptr<std::vector<boost::property_tree::ptree>> get_paths_from_svg(\n    boost::property_tree::ptree& doc) {\n    std::shared_ptr<std::vector<boost::property_tree::ptree>> res{\n        new std::vector<boost::property_tree::ptree>{}};\n    auto root = doc.get_child(\"svg\");\n    auto g    = root.get_child(\"g\");\n    _get_paths_from_g(g, *res);\n    return res;\n}\n\nstd::shared_ptr<std::vector<boost::property_tree::ptree>> get_paths_from_svg(\n    const std::string& svg_filepath) {\n    boost::property_tree::ptree pt;\n    boost::property_tree::read_xml(svg_filepath, pt);\n    return get_paths_from_svg(pt);\n}\n\nstd::shared_ptr<std::vector<std::string>> get_pathd_from_doc(\n    boost::property_tree::ptree& doc) {\n    auto paths = get_paths_from_svg(doc);\n    std::shared_ptr<std::vector<std::string>> res{\n        new std::vector<std::string>{}};\n\n    for (auto& path : *paths) {\n        res->push_back(path.get<std::string>(\"<xmlattr>.d\"));\n    }\n    return res;\n}\n\ninline std::shared_ptr<std::vector<std::string>> split(\n    const std::string& s,\n    const std::string& p = \"[\\\\s]+\") {\n    std::regex reg{p};\n    std::shared_ptr<std::vector<std::string>> res{new std::vector<std::string>{\n        std::sregex_token_iterator{s.begin(), s.end(), reg, -1},\n        std::sregex_token_iterator{}}};\n    return res;\n}\n\ninline std::shared_ptr<std::vector<float>> split_to_floats(\n    const std::string& s,\n    const std::string& p = \",\") {\n    print_line;\n    std::cout << \"split s:\" << s << \" ;; by:\" << p << std::endl;\n    std::regex reg{p};\n    std::shared_ptr<std::vector<float>> res{new std::vector<float>{}};\n    std::vector<std::string> strs{\n        std::sregex_token_iterator{s.begin(), s.end(), reg, -1},\n        std::sregex_token_iterator{}};\n    std::transform(\n        strs.begin(), strs.end(), std::back_inserter(*res), [](std::string& s) {\n            float res = 0;\n            try {\n                res = std::stof(s);\n            } catch (std::exception& e) {\n                std::cerr << e.what() << std::endl;\n            }\n            return res;\n        });\n    return res;\n}\n\nstatic std::map<std::string,\n                std::function<bool(cv::Point2f&,\n                                   std::vector<std::vector<cv::Point2i>>&,\n                                   const std::vector<std::string>&,\n                                   int&)>>\n    __handle_mapper__{\n        {\"m\",\n         [](cv::Point2f& prev_pt,\n            std::vector<std::vector<cv::Point2i>>& ways,\n            const std::vector<std::string>& pathd,\n            int& i) -> bool {\n             ways.push_back(std::vector<cv::Point2i>{});\n             ++i;\n             if (i >= pathd.size()) {\n                 return false;\n             }\n             auto pts = split_to_floats(pathd.at(i));\n             prev_pt.x += pts->at(0);\n             prev_pt.y += pts->at(1);\n             ways.back().push_back(prev_pt);\n             ++i;\n             return true;\n         }},\n        {\"M\",\n         [](cv::Point2f& prev_pt,\n            std::vector<std::vector<cv::Point2i>>& ways,\n            const std::vector<std::string>& pathd,\n            int& i) -> bool {\n             ways.push_back(std::vector<cv::Point2i>{});\n             ++i;\n\n             if (i >= pathd.size()) {\n                 return false;\n             }\n             auto pts = split_to_floats(pathd.at(i));\n             setpntf(prev_pt, *pts);\n             ways.back().push_back(prev_pt);\n             ++i;\n             return true;\n         }},\n        {\"l\",\n         [](cv::Point2f& prev_pt,\n            std::vector<std::vector<cv::Point2i>>& ways,\n            const std::vector<std::string>& pathd,\n            int& i) -> bool {\n             ++i;\n             if (i >= pathd.size()) {\n                 return false;\n             }\n             auto pts = split_to_floats(pathd.at(i));\n             prev_pt.x += pts->at(0);\n             prev_pt.y += pts->at(1);\n             ways.back().push_back(prev_pt);\n             ++i;\n             return true;\n         }},\n        {\"L\",\n         [](cv::Point2f& prev_pt,\n            std::vector<std::vector<cv::Point2i>>& ways,\n            const std::vector<std::string>& pathd,\n            int& i) -> bool {\n             ++i;\n             if (i >= pathd.size()) {\n                 return false;\n             }\n             auto pts = split_to_floats(pathd.at(i));\n             setpntf(prev_pt, *pts);\n             ways.back().push_back(prev_pt);\n             ++i;\n             return true;\n         }},\n        {\"h\",\n         [](cv::Point2f& prev_pt,\n            std::vector<std::vector<cv::Point2i>>& ways,\n            const std::vector<std::string>& pathd,\n            int& i) -> bool {\n             ++i;\n             if (i >= pathd.size()) {\n                 return false;\n             }\n             auto pts = split_to_floats(pathd.at(i));\n             prev_pt.x += pts->at(0);\n             ways.back().push_back(prev_pt);\n             ++i;\n             return true;\n         }},\n        {\"H\",\n         [](cv::Point2f& prev_pt,\n            std::vector<std::vector<cv::Point2i>>& ways,\n            const std::vector<std::string>& pathd,\n            int& i) -> bool {\n             ++i;\n             if (i >= pathd.size()) {\n                 return false;\n             }\n             auto pts  = split_to_floats(pathd.at(i));\n             prev_pt.x = pts->at(0);\n             ways.back().push_back(prev_pt);\n             ++i;\n             return true;\n         }},\n        {\"v\",\n         [](cv::Point2f& prev_pt,\n            std::vector<std::vector<cv::Point2i>>& ways,\n            const std::vector<std::string>& pathd,\n            int& i) -> bool {\n             ++i;\n             if (i >= pathd.size()) {\n                 return false;\n             }\n             auto pts = split_to_floats(pathd.at(i));\n             prev_pt.y += pts->at(0);\n             ways.back().push_back(prev_pt);\n             ++i;\n             return true;\n         }},\n        {\"V\",\n         [](cv::Point2f& prev_pt,\n            std::vector<std::vector<cv::Point2i>>& ways,\n            const std::vector<std::string>& pathd,\n            int& i) -> bool {\n             ++i;\n             if (i >= pathd.size()) {\n                 return false;\n             }\n             auto pts  = split_to_floats(pathd.at(i));\n             prev_pt.y = pts->at(0);\n             ways.back().push_back(prev_pt);\n             ++i;\n             return true;\n         }},\n        {\"c\",\n         [](cv::Point2f& prev_pt,\n            std::vector<std::vector<cv::Point2i>>& ways,\n            const std::vector<std::string>& pathd,\n            int& i) -> bool {\n             cv::Point2f b = prev_pt;\n\n             if (++i >= pathd.size()) {\n                 return false;\n             }\n             cv::Point2f c1 = __add__(prev_pt, *split_to_floats(pathd.at(i)));\n\n             if (++i >= pathd.size()) {\n                 return false;\n             }\n             cv::Point2f c2 = __add__(prev_pt, *split_to_floats(pathd.at(i)));\n\n             if (++i >= pathd.size()) {\n                 return false;\n             }\n             cv::Point2f e = __add__(prev_pt, *split_to_floats(pathd.at(i)));\n\n             auto pts = quadratic_bezier(b, c1, c2, e);\n             prev_pt  = pts->back();\n             std::copy(\n                 pts->begin(), pts->end(), std::back_inserter(ways.back()));\n\n             ++i;\n             return true;\n         }},\n        {\"C\",\n         [](cv::Point2f& prev_pt,\n            std::vector<std::vector<cv::Point2i>>& ways,\n            const std::vector<std::string>& pathd,\n            int& i) -> bool {\n             cv::Point2f b = prev_pt;\n\n             if (++i >= pathd.size()) {\n                 return false;\n             }\n             cv::Point2f c1;\n             setpntf(c1, *split_to_floats(pathd.at(i)));\n\n             if (++i >= pathd.size()) {\n                 return false;\n             }\n             cv::Point2f c2;\n             setpntf(c2, *split_to_floats(pathd.at(i)));\n\n             if (++i >= pathd.size()) {\n                 return false;\n             }\n             cv::Point2f e;\n             setpntf(e, *split_to_floats(pathd.at(i)));\n\n             auto pts = quadratic_bezier(b, c1, c2, e);\n             prev_pt  = pts->back();\n             std::copy(\n                 pts->begin(), pts->end(), std::back_inserter(ways.back()));\n\n             ++i;\n             return true;\n         }},\n        {\"z\",\n         [](cv::Point2f& prev_pt,\n            std::vector<std::vector<cv::Point2i>>& ways,\n            const std::vector<std::string>& pathd,\n            int& i) -> bool {\n             ways.back().push_back(ways.back().front());\n             prev_pt = ways.back().back();\n             ++i;\n             return true;\n         }},\n        {\"Z\",\n         [](cv::Point2f& prev_pt,\n            std::vector<std::vector<cv::Point2i>>& ways,\n            const std::vector<std::string>& pathd,\n            int& i) -> bool {\n             ways.back().push_back(ways.back().front());\n             prev_pt = ways.back().back();\n             ++i;\n             return true;\n         }}};\n\nvoid get_way_from_pathd(std::vector<std::string>& pathd,\n                        std::vector<std::vector<cv::Point2i>>& ways) {\n    print_line;\n\n    auto prev_func_it = __handle_mapper__.begin();\n    int i             = 0;\n    cv::Point2f prev_pt{0, 0};\n    while (i < pathd.size()) {\n        auto key = pathd.at(i);\n        auto fit = __handle_mapper__.find(key);\n        if (fit == __handle_mapper__.end()) {\n            --i;\n            fit = prev_func_it;\n        }\n        std::cout << \"handle in \" << fit->first << std::endl;\n        if (false == fit->second(prev_pt, ways, pathd, i)) {\n            return;\n        }\n        std::cout << \"this i is \" << i << std::endl;\n        prev_func_it = fit;\n    }\n}\n\nstd::shared_ptr<std::vector<std::vector<cv::Point2i>>> get_ways_form_paths(\n    std::vector<boost::property_tree::ptree>& paths) {\n    //\n    print_line;\n    std::shared_ptr<std::vector<std::vector<cv::Point2i>>> res{\n        new std::vector<std::vector<cv::Point2i>>{}};\n    for (auto& pt : paths) {\n        auto d     = pt.get<std::string>(\"<xmlattr>.d\");\n        auto pathd = split(d);\n        for (auto& s : *pathd) {\n            std::cout << s << \" ; \";\n        }\n        std::cout << \"%%\" << std::endl;\n        get_way_from_pathd(*pathd, *res);\n    }\n    return res;\n}\n\nstd::shared_ptr<std::vector<std::vector<cv::Point2i>>> get_ways_form_svg(\n    boost::property_tree::ptree& doc) {\n    auto paths = get_paths_from_svg(doc);\n    return get_ways_form_paths(*paths);\n}\n\nstd::shared_ptr<std::vector<std::vector<cv::Point2i>>> get_ways_form_svg(\n    const std::string& svg_filepath) {\n    boost::property_tree::ptree pt;\n    boost::property_tree::read_xml(svg_filepath, pt);\n    return get_ways_form_svg(pt);\n}\n\n}  // namespace utils\n", "meta": {"hexsha": "9e051679c421901227789ab7c6c5ec6d91dda4d4", "size": 14767, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ros_sp/src/image_service_node/src/about_svg_utils.hpp", "max_stars_repo_name": "KanKanTAD/ur_robot_paintor", "max_stars_repo_head_hexsha": "8b448e537c2276e9003de48f11b8860d148452bb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-12-27T06:48:09.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-27T06:48:09.000Z", "max_issues_repo_path": "ros_sp/src/image_service_node/src/about_svg_utils.hpp", "max_issues_repo_name": "KanKanTAD/ur_robot_paintor", "max_issues_repo_head_hexsha": "8b448e537c2276e9003de48f11b8860d148452bb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ros_sp/src/image_service_node/src/about_svg_utils.hpp", "max_forks_repo_name": "KanKanTAD/ur_robot_paintor", "max_forks_repo_head_hexsha": "8b448e537c2276e9003de48f11b8860d148452bb", "max_forks_repo_licenses": ["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.5534188034, "max_line_length": 80, "alphanum_fraction": 0.4814112548, "num_tokens": 3887, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.6261241772283034, "lm_q1q2_score": 0.34474858372159606}}
{"text": "#include \"trajopt/collision_avoidance.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\"\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, DblVec& weights) {\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  weights.clear();\n  dists.reserve(collisions.size());\n  weights.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      weights.push_back(col.weight);\n    }\n  }\n}\n\nvoid CollisionsToDistanceExpressions(const vector<Collision>& collisions, RobotAndDOF& rad,\n    const Link2Int& link2ind, const VarVector& vars, const DblVec& dofvals, vector<AffExpr>& exprs, DblVec& weights) {\n\n  exprs.clear();\n  weights.clear();\n  exprs.reserve(collisions.size());\n  weights.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, 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      weights.push_back(col.weight);\n    }\n  }\n  RAVELOG_DEBUG(\"%i distance expressions\\n\", exprs.size());\n}\n\nvoid CollisionsToDistanceExpressions(const vector<Collision>& collisions, RobotAndDOF& rad, const Link2Int& link2ind,\n    const VarVector& vars0, const VarVector& vars1, const DblVec& vals0, const DblVec& vals1,\n    vector<AffExpr>& exprs, DblVec& weights) {\n  vector<AffExpr> exprs0, exprs1;\n  DblVec weights0, weights1;\n  CollisionsToDistanceExpressions(collisions, rad, link2ind, vars0, vals0, exprs0, weights0);\n  CollisionsToDistanceExpressions(collisions, rad, link2ind, vars1, vals1, exprs1, weights1);\n\n  exprs.resize(exprs0.size());\n  weights.resize(exprs0.size());\n\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    weights[i] = (weights0[i] + weights1[i])/2;\n  }\n}\n\nvoid BeliefCollisionsToDistanceExpressions(const vector<Collision>& collisions, BeliefRobotAndDOF& brad,\n    const Link2Int& link2ind, const VarVector& theta_vars, const DblVec& theta_vals, vector<AffExpr>& exprs, DblVec& weights) {\n  exprs.clear();\n  weights.clear();\n  exprs.reserve(collisions.size());\n  weights.reserve(collisions.size());\n  brad.SetBeliefValues(theta_vals); // since we'll be calculating jacobians\n  BOOST_FOREACH(const Collision& col, collisions) {\n  \tLink2Int::const_iterator itA = link2ind.find(col.linkA);\n\t\tLink2Int::const_iterator itB = link2ind.find(col.linkB);\n\t\tAffExpr dist;\n\t\tfor (int i=0; i<col.mi.alpha.size(); i++) {\n\t\t\t//cout << \"ALPHA \" << col.mi.alpha[i] << endl;\n  \t\tAffExpr dist_a(col.distance);\n\t\t\tif (itA != link2ind.end()) {\n\t\t\t\tVectorXd dist_grad = toVector3d(col.normalB2A).transpose()*brad.BeliefJacobian(itA->second, col.mi.instance_ind[i], col.ptA);\n\t\t\t\texprInc(dist_a, varDot(dist_grad, theta_vars));\n\t\t\t\texprInc(dist_a, -dist_grad.dot(toVectorXd(theta_vals)));\n\t\t\t}\n\t\t\tif (itB != link2ind.end()) {\n\t\t\t\tVectorXd dist_grad = -toVector3d(col.normalB2A).transpose()*brad.BeliefJacobian(itB->second, col.mi.instance_ind[i], col.ptB);\n\t\t\t\texprInc(dist_a, varDot(dist_grad, theta_vars));\n\t\t\t\texprInc(dist_a, -dist_grad.dot(toVectorXd(theta_vals)));\n\t\t\t}\n\t\t\tif (itA != link2ind.end() || itB != link2ind.end()) {\n\t\t    exprScale(dist_a, col.mi.alpha[i]);\n\t\t    exprInc(dist, dist_a);\n\t\t\t}\n\t\t}\n\t\tif (dist.constant!=0 || dist.coeffs.size()!=0 || dist.vars.size()!=0) {\n\t\t\texprs.push_back(dist);\n\t\t\tweights.push_back(col.weight);\n\t\t}\n  }\n  RAVELOG_DEBUG(\"%i distance expressions\\n\", exprs.size());\n}\n\nvoid CollisionEvaluator::GetCollisionsCached(const DblVec& x, vector<Collision>& collisions) {\n  double key = vecSum(x);\n  vector<Collision>* it = m_cache.get(key);\n  if (it != NULL) {\n    RAVELOG_DEBUG(\"using cached collision check\\n\");\n    collisions = *it;\n  }\n  else {\n    RAVELOG_DEBUG(\"not using cached collision check\\n\");\n    CalcCollisions(x, collisions);\n    m_cache.put(key, collisions);\n  }\n}\n\nSingleTimestepCollisionEvaluator::SingleTimestepCollisionEvaluator(RobotAndDOFPtr rad, const VarVector& vars) :\n  m_env(rad->GetRobot()->GetEnv()),\n  m_cc(CollisionChecker::GetOrCreate(*m_env)),\n  m_rad(rad),\n  m_vars(vars),\n  m_link2ind(),\n  m_links() {\n  RobotBasePtr robot = rad->GetRobot();\n  const vector<KinBody::LinkPtr>& robot_links = robot->GetLinks();\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\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);\n}\n\nvoid SingleTimestepCollisionEvaluator::CalcDists(const DblVec& x, DblVec& dists, DblVec& weights) {\n  vector<Collision> collisions;\n  GetCollisionsCached(x, collisions);\n  CollisionsToDistances(collisions, m_link2ind, dists, weights);\n}\n\n\nvoid SingleTimestepCollisionEvaluator::CalcDistExpressions(const DblVec& x, vector<AffExpr>& exprs, DblVec& weights) {\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, weights);\n}\n\n////////////////////////////////////////\n\nCastCollisionEvaluator::CastCollisionEvaluator(RobotAndDOFPtr rad, const VarVector& vars0, const VarVector& vars1) :\n  m_env(rad->GetRobot()->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  RobotBasePtr robot = rad->GetRobot();\n  const vector<KinBody::LinkPtr>& robot_links = robot->GetLinks();\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, DblVec& weights) {\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, weights);\n}\nvoid CastCollisionEvaluator::CalcDists(const DblVec& x, DblVec& dists, DblVec& weights) {\n  vector<Collision> collisions;\n  GetCollisionsCached(x, collisions);\n  CollisionsToDistances(collisions, m_link2ind, dists, weights);\n}\n\n\n//////////////////////////////////////////\nSigmaPtsCollisionEvaluator::SigmaPtsCollisionEvaluator(BeliefRobotAndDOFPtr rad, const VarVector& theta_vars) :\n  m_env(rad->GetRobot()->GetEnv()),\n  m_cc(CollisionChecker::GetOrCreate(*m_env)),\n  m_rad(rad),\n  m_theta_vars(theta_vars),\n  m_link2ind(),\n  m_links() {\n  RobotBasePtr robot = rad->GetRobot();\n  const vector<KinBody::LinkPtr>& robot_links = robot->GetLinks();\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}\nvoid SigmaPtsCollisionEvaluator::CalcCollisions(const DblVec& x, vector<Collision>& collisions) {\n  DblVec theta = getDblVec(x, m_theta_vars);\n  MatrixXd sigma_pts = m_rad->sigmaPoints(toVectorXd(theta));\n\n  vector<DblVec> dofvals(sigma_pts.cols());\n  for (int i=0; i<sigma_pts.cols(); i++) {\n  \tdofvals[i] = toDblVec(sigma_pts.col(i));\n  }\n  m_cc->MultiCastVsAll(*m_rad, m_links, dofvals, collisions);\n}\nvoid SigmaPtsCollisionEvaluator::CalcDistExpressions(const DblVec& x, vector<AffExpr>& exprs, DblVec& weights) {\n  vector<Collision> collisions;\n  GetCollisionsCached(x, collisions);\n  DblVec theta = getDblVec(x, m_theta_vars);\n  // MatrixXd sigma_pts = m_rad->sigmaPoints(toVectorXd(theta));\n  // is sigma_pts not being used ??\n  BeliefCollisionsToDistanceExpressions(collisions, *m_rad, m_link2ind, m_theta_vars, theta, exprs, weights);\n}\nvoid SigmaPtsCollisionEvaluator::CalcDists(const DblVec& x, DblVec& dists, DblVec& weights) {\n  vector<Collision> collisions;\n  GetCollisionsCached(x, collisions);\n\tCollisionsToDistances(collisions, m_link2ind, dists, weights);\n}\n// for numerical linearization (for debugging, not being used)\nVectorXd SigmaPtsCollisionEvaluator::CalcDists(const VectorXd& theta, DblVec& weights) {\n  MatrixXd sigma_pts = m_rad->sigmaPoints(theta);\n\n  vector<DblVec> dofvals(sigma_pts.cols());\n  for (int i=0; i<sigma_pts.cols(); i++) {\n  \tdofvals[i] = toDblVec(sigma_pts.col(i));\n  }\n\tm_cc->SetContactDistance(100);\n  vector<Collision> collisions;\n  m_cc->MultiCastVsAll(*m_rad, m_links, dofvals, collisions);\n\n  VectorXd distances(collisions.size());\n  weights.resize(collisions.size());\n  for (int i=0; i<m_links.size(); i++) {\n\t\tint j;\n\t\tfor (j=0; j<collisions.size(); j++) {\n\t\t\tif (collisions[j].linkA == m_links[i].get() || collisions[j].linkB == m_links[i].get())\n\t\t\t\tbreak;\n\t\t}\n\t\tassert(j!=collisions.size());\n\t\tdistances(i) = collisions[j].distance;\n\t\tweights[i] = collisions[j].weight;\n  }\n  return distances;\n}\n//// for numerical linearization\n//void SigmaPtsCollisionEvaluator::CalcDistExpressions(const DblVec& x, vector<AffExpr>& exprs, DblVec& weights) {\n//  VectorXd theta = toVectorXd(getDblVec(x, m_theta_vars));\n//\n//  MatrixXd A = calcNumJac(boost::bind(&SigmaPtsCollisionEvaluator::CalcDists, this, _1, weights), theta);\n//  VectorXd c = CalcDists(theta, weights);\n//  //-coeff * (A * (m_theta_vars - theta) + c);\n//\tassert(A.rows() == c.rows());\n//\tfor (int i=0; i < A.rows(); ++i) {\n//\t\tAffExpr aff;\n//\t\taff.constant = c(i) - A.row(i).dot(theta);\n//\t\taff.coeffs = toDblVec(A.row(i));\n//\t\taff.vars = m_theta_vars;\n//\t\texprs.push_back(aff);\n//\t}\n//}\nvoid SigmaPtsCollisionEvaluator::CustomPlot(const DblVec& x, std::vector<OR::GraphHandlePtr>& handles) {\n\tDblVec theta = getDblVec(x, m_theta_vars);\n\tMatrixXd sigma_pts = m_rad->sigmaPoints(toVectorXd(theta));\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}\n\tm_cc->PlotCastHull(*m_rad, m_links, dofvals, handles);\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    handles.push_back(env.drawarrow(col.ptA, col.ptB, .0025, color));\n  }\n}\n\nCollisionCost::CollisionCost(double dist_pen, double coeff, RobotAndDOFPtr rad, const VarVector& vars) :\n    Cost(\"collision\"),\n    m_dist_pen(dist_pen),\n    m_coeff(coeff)\n{\n\tif (vars.size() == rad->GetDOF()) {\n\t\tm_calc = CollisionEvaluatorPtr(new SingleTimestepCollisionEvaluator(rad, vars));\n\t} else {\n\t\tBeliefRobotAndDOFPtr brad = boost::static_pointer_cast<BeliefRobotAndDOF>(rad);\n\t\tm_calc = CollisionEvaluatorPtr(new SigmaPtsCollisionEvaluator(brad, vars));\n\t}\n}\n\nCollisionCost::CollisionCost(double dist_pen, double coeff, RobotAndDOFPtr 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{}\n\nConvexObjectivePtr CollisionCost::convex(const vector<double>& x, Model* model) {\n  ConvexObjectivePtr out(new ConvexObjective(model));\n  vector<AffExpr> exprs;\n  DblVec weights;\n  m_calc->CalcDistExpressions(x, exprs, weights);\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*weights[i]);\n  }\n  return out;\n}\ndouble CollisionCost::value(const vector<double>& x) {\n  DblVec dists, weights;\n  m_calc->CalcDists(x, dists, weights);\n  double out = 0;\n  for (int i=0; i < dists.size(); ++i) {\n    out += pospart(m_dist_pen - dists[i]) * m_coeff * weights[i];\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  m_calc->CustomPlot(x, handles);\n}\n\n\nCollisionConstraint::CollisionConstraint(double dist_pen, double coeff, RobotAndDOFPtr rad, const VarVector& vars) :\n    Constraint(\"collision\"), m_dist_pen(dist_pen), m_coeff(coeff), type_(INEQ)\n{\n\tif (vars.size() == rad->GetDOF()) {\n\t\tm_calc = CollisionEvaluatorPtr(new SingleTimestepCollisionEvaluator(rad, vars));\n\t} else {\n\t\tBeliefRobotAndDOFPtr brad = boost::static_pointer_cast<BeliefRobotAndDOF>(rad);\n\t\tm_calc = CollisionEvaluatorPtr(new SigmaPtsCollisionEvaluator(brad, vars));\n\t}\n}\nCollisionConstraint::CollisionConstraint(double dist_pen, double coeff, RobotAndDOFPtr rad, const VarVector& vars0, const VarVector& vars1) :\n\t\tConstraint(\"cast_collision\"), m_calc(new CastCollisionEvaluator(rad, vars0, vars1)), m_dist_pen(dist_pen), m_coeff(coeff), type_(INEQ)\n{}\nConvexConstraintsPtr CollisionConstraint::convex(const vector<double>& x, Model* model) {\n\tConvexConstraintsPtr out(new ConvexConstraints(model));\n  vector<AffExpr> exprs;\n  DblVec weights;\n  m_calc->CalcDistExpressions(x, exprs, weights);\n  for (int i=0; i < exprs.size(); ++i) {\n    AffExpr aff = exprMult(exprSub(AffExpr(m_dist_pen), exprs[i]), m_coeff * weights[i]);\n\t\tout->addIneqCnt(aff);\n  }\n  return out;\n}\nvector<double> CollisionConstraint::value(const vector<double>& x) {\n  DblVec dists, weights;\n  m_calc->CalcDists(x, dists, weights);\n  vector<double> out(dists.size());\n  for (int i=0; i < dists.size(); ++i) {\n    out[i] = (m_dist_pen - dists[i]) * m_coeff * weights[i];\n  }\n  return out;\n}\nvoid CollisionConstraint::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  m_calc->CustomPlot(x, handles);\n}\n\n}\n", "meta": {"hexsha": "5ad28fd8e439f44074d2be6fd87d22599c5fc15c", "size": 15835, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/trajopt/collision_avoidance.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/collision_avoidance.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/collision_avoidance.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.5279805353, "max_line_length": 144, "alphanum_fraction": 0.7127881276, "num_tokens": 4569, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6442250928250375, "lm_q2_score": 0.5350984286266115, "lm_q1q2_score": 0.3447238348525105}}
{"text": "#ifndef STAN_MATH_REV_MAT_FUN_TRACE_GEN_INV_QUAD_FORM_LDLT_HPP\n#define STAN_MATH_REV_MAT_FUN_TRACE_GEN_INV_QUAD_FORM_LDLT_HPP\n\n#include <stan/math/prim/mat/fun/Eigen.hpp>\n#include <stan/math/rev/core.hpp>\n#include <stan/math/prim/scal/meta/is_var.hpp>\n#include <stan/math/rev/scal/meta/is_var.hpp>\n#include <boost/utility/enable_if.hpp>\n#include <stan/math/prim/mat/err/check_multiplicable.hpp>\n#include <stan/math/prim/mat/err/check_square.hpp>\n#include <stan/math/rev/mat/fun/trace_inv_quad_form_ldlt.hpp>\n\nnamespace stan {\n  namespace math {\n\n    /**\n     * Compute the trace of an inverse quadratic form.  I.E., this computes\n     *       trace(D B^T A^-1 B)\n     * where D is a square matrix and the LDLT_factor of A is provided.\n     **/\n    template <typename T1, int R1, int C1, typename T2, int R2, int C2,\n              typename T3, int R3, int C3>\n    inline typename\n    boost::enable_if_c<stan::is_var<T1>::value ||\n    stan::is_var<T2>::value ||\n    stan::is_var<T3>::value, var>::type\n      trace_gen_inv_quad_form_ldlt(const Eigen::Matrix<T1, R1, C1> &D,\n                                   const LDLT_factor<T2, R2, C2> &A,\n                                   const Eigen::Matrix<T3, R3, C3> &B) {\n      check_square(\"trace_gen_inv_quad_form_ldlt\", \"D\", D);\n      check_multiplicable(\"trace_gen_inv_quad_form_ldlt\",\n                          \"A\", A,\n                          \"B\", B);\n      check_multiplicable(\"trace_gen_inv_quad_form_ldlt\",\n                          \"B\", B,\n                          \"D\", D);\n\n      trace_inv_quad_form_ldlt_impl<T2, R2, C2, T3, R3, C3> *_impl\n        = new trace_inv_quad_form_ldlt_impl<T2, R2, C2, T3, R3, C3>(D, A, B);\n\n      return var(new trace_inv_quad_form_ldlt_vari<T2, R2, C2, T3, R3, C3>\n                 (_impl));\n    }\n\n  }\n}\n#endif\n", "meta": {"hexsha": "967c62deb2d430b0204e6f57c640b3ad8bab0d1c", "size": 1796, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "cmdstan/stan/lib/stan_math/stan/math/rev/mat/fun/trace_gen_inv_quad_form_ldlt.hpp", "max_stars_repo_name": "yizhang-cae/torsten", "max_stars_repo_head_hexsha": "dc82080ca032325040844cbabe81c9a2b5e046f9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cmdstan/stan/lib/stan_math/stan/math/rev/mat/fun/trace_gen_inv_quad_form_ldlt.hpp", "max_issues_repo_name": "yizhang-cae/torsten", "max_issues_repo_head_hexsha": "dc82080ca032325040844cbabe81c9a2b5e046f9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cmdstan/stan/lib/stan_math/stan/math/rev/mat/fun/trace_gen_inv_quad_form_ldlt.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": 37.4166666667, "max_line_length": 77, "alphanum_fraction": 0.6191536748, "num_tokens": 512, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6893056295505783, "lm_q2_score": 0.5, "lm_q1q2_score": 0.34465281477528914}}
{"text": "//\n// Copyright Jesse Manning 2007\n//\n// Distributed under the Boost Software License, Version 1.0.\n// (See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n//\n\n#ifndef BOOST_NUMERIC_BINDINGS_LAPACK_GELSD_HPP\n#define BOOST_NUMERIC_BINDINGS_LAPACK_GELSD_HPP\n\n#include <algorithm>\n\n#include <boost/numeric/bindings/traits/type.hpp>\n#include <boost/numeric/bindings/traits/traits.hpp>\n#include <boost/numeric/bindings/traits/type_traits.hpp>\n#include <boost/numeric/bindings/lapack/lapack.h>\n#include <boost/numeric/bindings/lapack/workspace.hpp>\n#include <boost/numeric/bindings/traits/detail/array.hpp>\n#include <boost/numeric/bindings/traits/detail/utils.hpp>\n#include <boost/numeric/bindings/lapack/ilaenv.hpp>\n\n// included to implicitly convert a vector to an nx1 matrix\n// so that it is compatible with lapack binding\n#include <boost/numeric/bindings/traits/ublas_vector2.hpp> \n\n\n#ifndef BOOST_NUMERIC_BINDINGS_NO_STRUCTURE_CHECK \n#  include <boost/static_assert.hpp>\n#  include <boost/type_traits.hpp>\n#endif\n\nnamespace boost { namespace numeric { namespace bindings {\n\n\tnamespace lapack {\n\n\t\tnamespace detail {\n\n\t\t\tinline void gelsd(const int m, const int n, const int nrhs, \n\t\t\t\t\t\t\t  float *a, const int lda, float *b, const int ldb, \n\t\t\t\t\t\t\t  float *s, const float rcond, int *rank, float *work,\n\t\t\t\t\t\t\t  const int lwork, int *iwork, int *info)\n\t\t\t{\n\t\t\t\tLAPACK_SGELSD(&m, &n, &nrhs, a, &lda, b, &ldb, s, \n\t\t\t\t\t\t\t  &rcond, rank, work, &lwork, iwork, info);\n\t\t\t}\n\n\t\t\tinline void gelsd(const int m, const int n, const int nrhs, \n\t\t\t\t\t\t\t  double *a, const int lda, double *b, const int ldb, \n\t\t\t\t\t\t\t  double *s, const double rcond, int *rank, double *work,\n\t\t\t\t\t\t\t  const int lwork, int *iwork, int *info)\n\t\t\t{\n\t\t\t\tLAPACK_DGELSD(&m, &n, &nrhs, a, &lda, b, &ldb, s, \n\t\t\t\t\t\t\t  &rcond, rank, work, &lwork, iwork, info);\n\t\t\t}\n\n\t\t\tinline void gelsd(const int m, const int n, const int nrhs, \n\t\t\t\t\t\t\t  traits::complex_f *a, const int lda, traits::complex_f *b, \n\t\t\t\t\t\t\t  const int ldb, float *s, const float rcond, int *rank, \n\t\t\t\t\t\t\t  traits::complex_f *work, const int lwork, float *rwork, \n\t\t\t\t\t\t\t  int *iwork, int *info)\n\t\t\t{\n\t\t\t\tLAPACK_CGELSD(&m, &n, &nrhs, traits::complex_ptr(a), \n\t\t\t\t\t\t\t  &lda, traits::complex_ptr(b), &ldb, s, \n\t\t\t\t\t\t\t  &rcond, rank, traits::complex_ptr(work), \n\t\t\t\t\t\t\t  &lwork, rwork, iwork, info);\n\t\t\t}\n\n\t\t\tinline void gelsd(const int m, const int n, const int nrhs, \n\t\t\t\t\t\t\t  traits::complex_d *a, const int lda, traits::complex_d *b, \n\t\t\t\t\t\t\t  const int ldb, double *s, const double rcond, int *rank, \n\t\t\t\t\t\t\t  traits::complex_d *work, const int lwork, double *rwork, \n\t\t\t\t\t\t\t  int *iwork, int *info)\n\t\t\t{\n\t\t\t\tLAPACK_ZGELSD(&m, &n, &nrhs, traits::complex_ptr(a), \n\t\t\t\t\t\t\t  &lda, traits::complex_ptr(b), &ldb, s, \n\t\t\t\t\t\t\t  &rcond, rank, traits::complex_ptr(work), \n\t\t\t\t\t\t\t  &lwork, rwork, iwork, info);\n\t\t\t}\n\n\t\t\t// gelsd for real type\n\t\t\ttemplate <typename MatrA, typename MatrB, typename VecS, typename Work>\n\t\t\tinline int gelsd(MatrA& A, MatrB& B, VecS& s, Work& work)\n\t\t\t{\n\t\t\t\ttypedef typename MatrA::value_type val_t;\n\t\t\t\ttypedef typename traits::type_traits<val_t>::real_type real_t;\n\n\t\t\t\tconst int m = traits::matrix_size1(A);\n\t\t\t\tconst int n = traits::matrix_size2(A);\n\t\t\t\tconst int nrhs = traits::matrix_size2(B);\n\t\t\t\tconst int maxmn = std::max(m, n);\n\t\t\t\tconst int minmn = std::min(m, n);\n\n\t\t\t\t// sanity checks\n\t\t\t\tassert(m >= 0 && n >= 0);\n\t\t\t\tassert(nrhs >= 0);\n\t\t\t\tassert(traits::leading_dimension(A) >= std::max(1, m));\n\t\t\t\tassert(traits::leading_dimension(B) >= std::max(1, maxmn));\n\t\t\t\tassert(traits::vector_size(work) >= 1);\n\t\t\t\tassert(traits::vector_size(s) >= std::max(1, minmn));\n\n\t\t\t\tint info;\n\t\t\t\tconst real_t rcond = -1;\t// use machine precision\n\t\t\t\tint rank;\n\n\t\t\t\t// query for maximum size of subproblems\n\t\t\t\tconst int smlsiz = ilaenv(9, \"GELSD\", \"\");\n\t\t\t\tconst int nlvl = static_cast<int>(((std::log(static_cast<float>(minmn))/std::log(2.f))/ (smlsiz+1)) + 1);\n\n\t\t\t\ttraits::detail::array<int> iwork(3*minmn*nlvl + 11*minmn);\n\n\t\t\t\tdetail::gelsd(traits::matrix_size1(A),\n\t\t\t\t\t\t\t  traits::matrix_size2(A),\n\t\t\t\t\t\t\t  traits::matrix_size2(B),\n\t\t\t\t\t\t\t  traits::matrix_storage(A),\n\t\t\t\t\t\t\t  traits::leading_dimension(A),\n\t\t\t\t\t\t\t  traits::matrix_storage(B),\n\t\t\t\t\t\t\t  traits::leading_dimension(B),\n\t\t\t\t\t\t\t  traits::vector_storage(s),\n\t\t\t\t\t\t\t  rcond,\n\t\t\t\t\t\t\t  &rank,\n\t\t\t\t\t\t\t  traits::vector_storage(work),\n\t\t\t\t\t\t\t  traits::vector_size(work),\n\t\t\t\t\t\t\t  traits::vector_storage(iwork),\n\t\t\t\t\t\t\t  &info);\n\n\t\t\t\treturn info;\n\t\t\t}\n\n\t\t\t// gelsd for complex type\n\t\t\ttemplate <typename MatrA, typename MatrB, typename VecS, \n\t\t\t\t\t\ttypename Work, typename RWork>\n\t\t\tinline int gelsd(MatrA& A, MatrB& B, VecS& s, Work& work, RWork& rwork)\n\t\t\t{\n\t\t\t\ttypedef typename MatrA::value_type val_t;\n\t\t\t\ttypedef typename traits::type_traits<val_t>::real_type real_t;\n\n\t\t\t\tconst int m = traits::matrix_size1(A);\n\t\t\t\tconst int n = traits::matrix_size2(A);\n\t\t\t\tconst int nrhs = traits::matrix_size2(B);\n\t\t\t\tconst int maxmn = std::max(m, n);\n\t\t\t\tconst int minmn = std::min(m, n);\n\n\t\t\t\t// sanity checks\n\t\t\t\tassert(m >= 0 && n >= 0);\n\t\t\t\tassert(nrhs >= 0);\n\t\t\t\tassert(traits::leading_dimension(A) >= std::max(1, m));\n\t\t\t\tassert(traits::leading_dimension(B) >= std::max(1, maxmn));\n\t\t\t\tassert(traits::vector_size(work) >= 1);\n\t\t\t\tassert(traits::vector_size(s) >= std::max(1, minmn));\n\n\t\t\t\tint info;\n\t\t\t\tconst real_t rcond = -1;\t// use machine precision\n\t\t\t\tint rank;\n\n\t\t\t\t// query for maximum size of subproblems\n\t\t\t\tconst int smlsiz = ilaenv(9, \"GELSD\", \"\");\n\t\t\t\tconst int nlvl = static_cast<int>(((std::log(static_cast<float>(minmn))/std::log(2.f))/ (smlsiz+1)) + 1);\n\n\t\t\t\ttraits::detail::array<int> iwork(3*minmn*nlvl + 11*minmn);\n\n\t\t\t\tdetail::gelsd(traits::matrix_size1(A),\n\t\t\t\t\ttraits::matrix_size2(A),\n\t\t\t\t\ttraits::matrix_size2(B),\n\t\t\t\t\ttraits::matrix_storage(A),\n\t\t\t\t\ttraits::leading_dimension(A),\n\t\t\t\t\ttraits::matrix_storage(B),\n\t\t\t\t\ttraits::leading_dimension(B),\n\t\t\t\t\ttraits::vector_storage(s),\n\t\t\t\t\trcond,\n\t\t\t\t\t&rank,\n\t\t\t\t\ttraits::vector_storage(work),\n\t\t\t\t\ttraits::vector_size(work),\n\t\t\t\t\ttraits::vector_storage(rwork),\n\t\t\t\t\ttraits::vector_storage(iwork),\n\t\t\t\t\t&info);\n\n\t\t\t\treturn info;\n\t\t\t}\n\n\t\t\ttemplate <int N>\n\t\t\tstruct Gelsd { };\n\n\t\t\t// specialization for gelsd real flavors (sgelsd, dgelsd)\n\t\t\ttemplate <>\n\t\t\tstruct Gelsd<1>\n\t\t\t{\n\t\t\t\ttemplate <typename MatrA, typename MatrB, typename VecS>\n\t\t\t\tinline int operator() (MatrA& A, MatrB& B, VecS& s, minimal_workspace) const\n\t\t\t\t{\n\t\t\t\t\ttypedef typename MatrA::value_type val_t;\n\n\t\t\t\t\tconst int m = traits::matrix_size1(A);\n\t\t\t\t\tconst int n = traits::matrix_size2(A);\n\t\t\t\t\tconst int nrhs = traits::matrix_size2(B);\n\n\t\t\t\t\tconst int minmn = std::min(m, n);\t\t\t// minmn = m < n ? m : n\n\t\t\t\t\tconst int maxmn = std::max(m, n);\t\t\t// maxmn = m > n ? m : n\n\t\t\t\t\tconst int maxmnr = std::max(maxmn, nrhs);\t// maxmnr = maxmn > nrhs ? maxmn : nrhs\n\n\t\t\t\t\t// query for maximum size of subproblems\n\t\t\t\t\tconst int smlsiz = ilaenv(9, \"GELSD\", \"\");\n\t\t\t\t\tconst int nlvl = static_cast<int>(((std::log(static_cast<float>(minmn))/std::log(2.f))/ (smlsiz+1)) + 1);\n\n\t\t\t\t\tconst int lwork = 12*minmn + 2*minmn*smlsiz + 8*minmn*nlvl + \n\t\t\t\t\t\t\t     \t  minmn*nrhs + (smlsiz+1)*(smlsiz+1);\n\n\t\t\t\t\ttraits::detail::array<val_t> work(lwork);\n\n\t\t\t\t\treturn gelsd(A, B, s, work);\n\t\t\t\t}\n\n\t\t\t\ttemplate <typename MatrA, typename MatrB, typename VecS>\n\t\t\t\tinline int operator() (MatrA& A, MatrB& B, VecS& s, optimal_workspace) const\n\t\t\t\t{\n\t\t\t\t\ttypedef typename MatrA::value_type val_t;\n\t\t\t\t\ttypedef typename traits::type_traits<val_t>::real_type real_t;\n\n\t\t\t\t\tconst int m = traits::matrix_size1(A);\n\t\t\t\t\tconst int n = traits::matrix_size2(A);\n\t\t\t\t\tconst int nrhs = traits::matrix_size2(B);\n\n\t\t\t\t\tconst int minmn = std::min(m, n);\t\t\t// minmn = m < n ? m : n\n\t\t\t\t\tconst int maxmn = std::max(m, n);\t\t\t// maxmn = m > n ? m : n\n\t\t\t\t\tconst int maxmnr = std::max(maxmn, nrhs);\t// maxmnr = maxmn > nrhs ? maxmn : nrhs\n\n\t\t\t\t\tval_t temp_work;\n\t\t\t\t\tint temp_iwork;\n\n\t\t\t\t\tconst real_t rcond = -1;\n\t\t\t\t\tint rank;\n\t\t\t\t\tint info;\n\n\t\t\t\t\t// query for optimal workspace size\n\t\t\t\t\tdetail::gelsd(traits::matrix_size1(A),\n\t\t\t\t\t\t\t\t  traits::matrix_size2(A),\n\t\t\t\t\t\t\t\t  traits::matrix_size2(B),\n\t\t\t\t\t\t\t\t  traits::matrix_storage(A),\n\t\t\t\t\t\t\t\t  traits::leading_dimension(A),\n\t\t\t\t\t\t\t\t  traits::matrix_storage(B),\n\t\t\t\t\t\t\t\t  traits::leading_dimension(B),\n\t\t\t\t\t\t\t\t  traits::vector_storage(s),\n\t\t\t\t\t\t\t\t  rcond,\n\t\t\t\t\t\t\t\t  &rank,\n\t\t\t\t\t\t\t\t  &temp_work,\t//traits::vector_storage(work),\n\t\t\t\t\t\t\t\t  -1,\t\t\t//traits::vector_size(work),\n\t\t\t\t\t\t\t\t  &temp_iwork,\n\t\t\t\t\t\t\t\t  &info);\n\n\t\t\t\t\tassert(info == 0);\n\n\t\t\t\t\tconst int lwork = traits::detail::to_int(temp_work);\n\n\t\t\t\t\ttraits::detail::array<val_t> work(lwork);\n\n\t\t\t\t\treturn gelsd(A, B, s, work);\n\t\t\t\t}\n\n\t\t\t\ttemplate <typename MatrA, typename MatrB, typename VecS, typename Work>\n\t\t\t\tinline int operator() (MatrA& A, MatrB& B, VecS& s, detail::workspace1<Work>& workspace) const\n\t\t\t\t{\n\t\t\t\t\tconst int m = traits::matrix_size1(A);\n\t\t\t\t\tconst int n = traits::matrix_size2(A);\n\t\t\t\t\tconst int nrhs = traits::matrix_size2(B);\n\n\t\t\t\t\tconst int minmn = std::min(m, n);\t\t\t// minmn = m < n ? m : n\n\t\t\t\t\tconst int maxmn = std::max(m, n);\t\t\t// maxmn = m > n ? m : n\n\t\t\t\t\tconst int maxmnr = std::max(maxmn, nrhs);\t// maxmnr = maxmn > nrhs ? maxmn : nrhs\n\n\t\t\t\t\treturn gelsd(A, B, s, workspace.w_);\n\t\t\t\t}\n\t\t\t};\n\n\t\t\t// specialization for gelsd (cgelsd, zgelsd)\n\t\t\ttemplate <>\n\t\t\tstruct Gelsd<2>\n\t\t\t{\n\t\t\t\ttemplate <typename MatrA, typename MatrB, typename VecS>\n\t\t\t\tinline int operator() (MatrA& A, MatrB& B, VecS& s, minimal_workspace) const\n\t\t\t\t{\n\t\t\t\t\ttypedef typename MatrA::value_type val_t;\n\t\t\t\t\ttypedef typename traits::type_traits<val_t>::real_type real_t;\n\n\t\t\t\t\tconst int m = traits::matrix_size1(A);\n\t\t\t\t\tconst int n = traits::matrix_size2(A);\n\t\t\t\t\tconst int nrhs = traits::matrix_size2(B);\n\n\t\t\t\t\tconst int minmn = std::min(m, n);\t\t\t// minmn = m < n ? m : n\n\t\t\t\t\tconst int maxmn = std::max(m, n);\t\t\t// maxmn = m > n ? m : n\n\t\t\t\t\tconst int maxmnr = std::max(maxmn, nrhs);\t// maxmnr = maxmn > nrhs ? maxmn : nrhs\n\n\t\t\t\t\t// query for maximum size of subproblems\n\t\t\t\t\tconst int smlsiz = ilaenv(9, \"GELSD\", \"\");\n\t\t\t\t\tconst int nlvl = static_cast<int>(((std::log(static_cast<float>(minmn))/std::log(2.f))/ (smlsiz+1)) + 1);\n\n\t\t\t\t\ttraits::detail::array<val_t> work(2*minmn + minmn*nrhs);\n\n\t\t\t\t\tconst int rwork_size = 10*minmn + 2*minmn*smlsiz + 8*minmn*nlvl + \n\t\t\t\t\t\t\t\t\t\t   3*smlsiz*nrhs + (smlsiz+1)*(smlsiz+1);\n\n\t\t\t\t\ttraits::detail::array<real_t> rwork(std::max(1, rwork_size));\n\n\t\t\t\t\treturn gelsd(A, B, s, work, rwork);\n\t\t\t\t}\n\n\t\t\t\ttemplate <typename MatrA, typename MatrB, typename VecS>\n\t\t\t\tinline int operator() (MatrA& A, MatrB& B, VecS& s, optimal_workspace) const\n\t\t\t\t{\n\t\t\t\t\ttypedef typename MatrA::value_type val_t;\n\t\t\t\t\ttypedef typename traits::type_traits<val_t>::real_type real_t;\n\n\t\t\t\t\tconst int m = traits::matrix_size1(A);\n\t\t\t\t\tconst int n = traits::matrix_size2(A);\n\t\t\t\t\tconst int nrhs = traits::matrix_size2(B);\n\n\t\t\t\t\tconst int minmn = std::min(m, n);\t\t\t// minmn = m < n ? m : n\n\t\t\t\t\tconst int maxmn = std::max(m, n);\t\t\t// maxmn = m > n ? m : n\n\t\t\t\t\tconst int maxmnr = std::max(maxmn, nrhs);\t// maxmnr = maxmn > nrhs ? maxmn : nrhs\n\n\t\t\t\t\tval_t temp_work;\n\t\t\t\t\treal_t temp_rwork;\n\t\t\t\t\tint temp_iwork;\n\n\t\t\t\t\tconst real_t rcond = -1;\n\t\t\t\t\tint rank;\n\t\t\t\t\tint info;\n\n\t\t\t\t\t// query for optimal workspace size\n\t\t\t\t\tdetail::gelsd(traits::matrix_size1(A),\n\t\t\t\t\t\t\t\t  traits::matrix_size2(A),\n\t\t\t\t\t\t\t\t  traits::matrix_size2(B),\n\t\t\t\t\t\t\t\t  traits::matrix_storage(A),\n\t\t\t\t\t\t\t\t  traits::leading_dimension(A),\n\t\t\t\t\t\t\t\t  traits::matrix_storage(B),\n\t\t\t\t\t\t\t\t  traits::leading_dimension(B),\n\t\t\t\t\t\t\t\t  traits::vector_storage(s),\n\t\t\t\t\t\t\t\t  rcond,\n\t\t\t\t\t\t\t\t  &rank,\n\t\t\t\t\t\t\t\t  &temp_work,\t//traits::vector_storage(work),\n\t\t\t\t\t\t\t\t  -1,\t\t\t//traits::vector_size(work),\n\t\t\t\t\t\t\t\t  &temp_rwork,\n\t\t\t\t\t\t\t\t  &temp_iwork,\n\t\t\t\t\t\t\t\t  &info);\n\n\t\t\t\t\tassert(info == 0);\n\n\t\t\t\t\tconst int lwork = traits::detail::to_int(temp_work);\n\n\t\t\t\t\ttraits::detail::array<val_t> work(lwork);\n\n\t\t\t\t\t// query for maximum size of subproblems\n\t\t\t\t\tconst int smlsiz = ilaenv(9, \"GELSD\", \"\");\n\t\t\t\t\tconst int nlvl = static_cast<int>(((std::log(static_cast<float>(minmn))/std::log(2.f))/ (smlsiz+1)) + 1);\n\n\t\t\t\t\tconst int rwork_size = 10*minmn + 2*minmn*smlsiz + 8*minmn*nlvl + \n\t\t\t\t\t\t\t\t\t\t\t3*smlsiz*nrhs + (smlsiz+1)*(smlsiz+1);\n\n\t\t\t\t\ttraits::detail::array<real_t> rwork(std::max(1, rwork_size));\n\n\t\t\t\t\treturn gelsd(A, B, s, work, rwork);\n\t\t\t\t}\n\n\t\t\t\ttemplate <typename MatrA, typename MatrB, typename VecS, typename Work, typename RWork>\n\t\t\t\tinline int operator() (MatrA& A, MatrB& B, VecS& s, detail::workspace2<Work, RWork>& workspace) const\n\t\t\t\t{\n\t\t\t\t\tconst int m = traits::matrix_size1(A);\n\t\t\t\t\tconst int n = traits::matrix_size2(A);\n\t\t\t\t\tconst int nrhs = traits::matrix_size2(B);\n\n\t\t\t\t\tconst int minmn = std::min(m, n);\t\t\t// minmn = m < n ? m : n\n\t\t\t\t\tconst int maxmn = std::max(m, n);\t\t\t// maxmn = m > n ? m : n\n\t\t\t\t\tconst int maxmnr = std::max(maxmn, nrhs);\t// maxmnr = maxmn > nrhs ? maxmn : nrhs\n\n\t\t\t\t\treturn gelsd(A, B, s, workspace.w_, workspace.wr_);\n\t\t\t\t}\n\t\t\t};\n\n\t\t} // detail\n\n\t\t// gelsd\n\t\t// Parameters:\n\t\t//\tA:\t\t\tmatrix of coefficients\n\t\t//\tB:\t\t\tmatrix of solutions (stored column-wise)\n\t\t//\ts:\t\t\tvector to store singular values on output, length >= max(1, min(m,n))\n\t\t//  workspace:\teither optimal, minimal, or user supplied\n\t\t//\n\t\ttemplate <typename MatrA, typename MatrB, typename VecS, typename Work>\n\t\tinline int gelsd(MatrA& A, MatrB& B, VecS& s, Work& workspace)\n\t\t{\n\t\t\ttypedef typename MatrA::value_type val_t;\n\n\t\t\treturn detail::Gelsd<n_workspace_args<val_t>::value>() (A, B, s, workspace);\n\t\t}\n\n\t\t// gelsd, no singular values are returned\n\t\t// Parameters:\n\t\t//\tA:\t\t\tmatrix of coefficients\n\t\t//\tB:\t\t\tmatrix of solutions (stored column-wise)\n\t\t//\tworkspace:\teither optimal, minimal, or user supplied\n\t\t//\n\t\ttemplate <typename MatrA, typename MatrB, typename Work>\n\t\tinline int gelsd(MatrA& A, MatrB& B, Work& workspace)\n\t\t{\n\t\t\ttypedef typename MatrA::value_type val_t;\n\t\t\ttypedef typename traits::type_traits<val_t>::real_type real_t;\n\n\t\t\tconst int m = traits::matrix_size1(A);\n\t\t\tconst int n = traits::matrix_size2(A);\n\n\t\t\tconst int s_size = std::max(1, std::min(m,n));\n\t\t\ttraits::detail::array<real_t> s(s_size);\n\n\t\t\treturn detail::Gelsd<n_workspace_args<val_t>::value>() (A, B, s, workspace);\n\t\t}\n\n\t} // lapack\n\n}}}\n\n#endif\n", "meta": {"hexsha": "1347b78b72921a72ff17ac1f5a8e516811485c83", "size": 14259, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/numeric/bindings/lapack/gelsd.hpp", "max_stars_repo_name": "inducer/boost-numeric-bindings", "max_stars_repo_head_hexsha": "1f994e8a2e161cddb6577eacc76b7bc358701cbe", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2015-11-13T16:40:57.000Z", "max_stars_repo_stars_event_max_datetime": "2017-09-15T15:37:19.000Z", "max_issues_repo_path": "openrave/plugins/include/boost/numeric/bindings/lapack/gelsd.hpp", "max_issues_repo_name": "jdsika/holy", "max_issues_repo_head_hexsha": "a2ac55fa1751a3a8038cf61d29b95005f36d6264", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2016-06-13T01:29:51.000Z", "max_issues_repo_issues_event_max_datetime": "2016-06-14T00:38:27.000Z", "max_forks_repo_path": "openrave/plugins/include/boost/numeric/bindings/lapack/gelsd.hpp", "max_forks_repo_name": "jdsika/holy", "max_forks_repo_head_hexsha": "a2ac55fa1751a3a8038cf61d29b95005f36d6264", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-05-05T20:18:25.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-05T20:18:25.000Z", "avg_line_length": 33.8693586698, "max_line_length": 110, "alphanum_fraction": 0.6240970615, "num_tokens": 4442, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6893056167854461, "lm_q2_score": 0.5, "lm_q1q2_score": 0.34465280839272305}}
{"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_ALGORITHMS_INTERSECTION_HPP\n#define BOOST_GEOMETRY_ALGORITHMS_INTERSECTION_HPP\n\n\n#include <boost/geometry/core/coordinate_dimension.hpp>\n#include <boost/geometry/algorithms/detail/overlay/intersection_insert.hpp>\n#include <boost/geometry/algorithms/intersects.hpp>\n\n\nnamespace boost { namespace geometry\n{\n\n#ifndef DOXYGEN_NO_DETAIL\nnamespace detail { namespace intersection\n{\n\ntemplate\n<\n    typename Box1, typename Box2,\n    typename BoxOut,\n    typename Strategy,\n    std::size_t Dimension, std::size_t DimensionCount\n>\nstruct intersection_box_box\n{\n    static inline bool apply(Box1 const& box1,\n            Box2 const& box2, BoxOut& box_out,\n            Strategy const& strategy)\n    {\n        typedef typename coordinate_type<BoxOut>::type ct;\n\n        ct min1 = get<min_corner, Dimension>(box1);\n        ct min2 = get<min_corner, Dimension>(box2);\n        ct max1 = get<max_corner, Dimension>(box1);\n        ct max2 = get<max_corner, Dimension>(box2);\n\n        if (max1 < min2 || max2 < min1)\n        {\n            return false;\n        }\n        // Set dimensions of output coordinate\n        set<min_corner, Dimension>(box_out, min1 < min2 ? min2 : min1);\n        set<max_corner, Dimension>(box_out, max1 > max2 ? max2 : max1);\n\n        return intersection_box_box\n            <\n                Box1, Box2, BoxOut, Strategy,\n                Dimension + 1, DimensionCount\n            >::apply(box1, box2, box_out, strategy);\n    }\n};\n\ntemplate\n<\n    typename Box1, typename Box2,\n    typename BoxOut,\n    typename Strategy,\n    std::size_t DimensionCount\n>\nstruct intersection_box_box<Box1, Box2, BoxOut, Strategy, DimensionCount, DimensionCount>\n{\n    static inline bool apply(Box1 const&, Box2 const&, BoxOut&, Strategy const&)\n    {\n        return true;\n    }\n};\n\n\n}} // namespace detail::intersection\n#endif // DOXYGEN_NO_DETAIL\n\n\n\n#ifndef DOXYGEN_NO_DISPATCH\nnamespace dispatch\n{\n\n// By default, all is forwarded to the intersection_insert-dispatcher\ntemplate\n<\n    typename Tag1, typename Tag2, typename TagOut,\n    typename Geometry1, typename Geometry2,\n    typename GeometryOut,\n    typename Strategy\n>\nstruct intersection\n{\n    typedef std::back_insert_iterator<GeometryOut> output_iterator;\n\n    static inline bool apply(Geometry1 const& geometry1,\n            Geometry2 const& geometry2,\n            GeometryOut& geometry_out,\n            Strategy const& strategy)\n    {\n        typedef typename boost::range_value<GeometryOut>::type OneOut;\n\n        intersection_insert\n        <\n            Tag1, Tag2, typename geometry::tag<OneOut>::type,\n            geometry::is_areal<Geometry1>::value,\n            geometry::is_areal<Geometry2>::value,\n            geometry::is_areal<OneOut>::value,\n            Geometry1, Geometry2,\n            detail::overlay::do_reverse<geometry::point_order<Geometry1>::value, false>::value,\n            detail::overlay::do_reverse<geometry::point_order<Geometry2>::value, false>::value,\n            detail::overlay::do_reverse<geometry::point_order<OneOut>::value>::value,\n            output_iterator, OneOut,\n            overlay_intersection,\n            Strategy\n        >::apply(geometry1, geometry2, std::back_inserter(geometry_out), strategy);\n\n        return true;\n    }\n\n};\n\n\ntemplate\n<\n    typename Box1, typename Box2,\n    typename BoxOut,\n    typename Strategy\n>\nstruct intersection\n    <\n        box_tag, box_tag, box_tag,\n        Box1, Box2, BoxOut,\n        Strategy\n    > : public detail::intersection::intersection_box_box\n            <\n                Box1, Box2, BoxOut,\n                Strategy,\n                0, geometry::dimension<Box1>::value\n            >\n{};\n\n\ntemplate\n<\n    typename Tag1, typename Tag2, typename TagOut,\n    typename Geometry1, typename Geometry2,\n    typename GeometryOut,\n    typename Strategy\n>\nstruct intersection_reversed\n{\n    static inline bool apply(Geometry1 const& geometry1,\n            Geometry2 const& geometry2,\n            GeometryOut& geometry_out,\n            Strategy const& strategy)\n    {\n        return intersection\n            <\n                Tag2, Tag1, TagOut,\n                Geometry2, Geometry1,\n                GeometryOut, Strategy\n            >::apply(geometry2, geometry1, geometry_out, strategy);\n    }\n};\n\n\n\n\n} // namespace dispatch\n#endif // DOXYGEN_NO_DISPATCH\n\n\n/*!\n\\brief \\brief_calc2{intersection}\n\\ingroup intersection\n\\details \\details_calc2{intersection, spatial set theoretic intersection}.\n\\tparam Geometry1 \\tparam_geometry\n\\tparam Geometry2 \\tparam_geometry\n\\tparam GeometryOut Collection of geometries (e.g. std::vector, std::deque, boost::geometry::multi*) of which\n    the value_type fulfills a \\p_l_or_c concept, or it is the output geometry (e.g. for a box)\n\\param geometry1 \\param_geometry\n\\param geometry2 \\param_geometry\n\\param geometry_out The output geometry, either a multi_point, multi_polygon,\n    multi_linestring, or a box (for intersection of two boxes)\n\n\\qbk{[include reference/algorithms/intersection.qbk]}\n*/\ntemplate\n<\n    typename Geometry1,\n    typename Geometry2,\n    typename GeometryOut\n>\ninline bool intersection(Geometry1 const& geometry1,\n            Geometry2 const& geometry2,\n            GeometryOut& geometry_out)\n{\n    concept::check<Geometry1 const>();\n    concept::check<Geometry2 const>();\n\n    typedef strategy_intersection\n        <\n            typename cs_tag<Geometry1>::type,\n            Geometry1,\n            Geometry2,\n            typename geometry::point_type<Geometry1>::type\n        > strategy;\n\n\n    return boost::mpl::if_c\n        <\n            geometry::reverse_dispatch<Geometry1, Geometry2>::type::value,\n            dispatch::intersection_reversed\n            <\n                    typename geometry::tag<Geometry1>::type,\n                    typename geometry::tag<Geometry2>::type,\n                    typename geometry::tag<GeometryOut>::type,\n                    Geometry1, Geometry2, GeometryOut, strategy\n            >,\n            dispatch::intersection\n            <\n                    typename geometry::tag<Geometry1>::type,\n                    typename geometry::tag<Geometry2>::type,\n                    typename geometry::tag<GeometryOut>::type,\n                    Geometry1, Geometry2, GeometryOut, strategy\n            >\n        >::type::apply(geometry1, geometry2, geometry_out, strategy());\n}\n\n\n}} // namespace boost::geometry\n\n\n#endif // BOOST_GEOMETRY_ALGORITHMS_INTERSECTION_HPP\n", "meta": {"hexsha": "8d3dd68b3aba2df7a1b9124939dc1f3f74c6f80e", "size": 6731, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/boost/geometry/algorithms/intersection.hpp", "max_stars_repo_name": "randolphwong/mcsema", "max_stars_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 50.0, "max_stars_repo_stars_event_min_datetime": "2015-07-18T08:40:20.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-03T13:10:02.000Z", "max_issues_repo_path": "boost/boost/geometry/algorithms/intersection.hpp", "max_issues_repo_name": "randolphwong/mcsema", "max_issues_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/boost/geometry/algorithms/intersection.hpp", "max_forks_repo_name": "randolphwong/mcsema", "max_forks_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 13.0, "max_forks_repo_forks_event_min_datetime": "2016-01-05T06:58:23.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-18T18:36:40.000Z", "avg_line_length": 28.281512605, "max_line_length": 109, "alphanum_fraction": 0.6523547764, "num_tokens": 1499, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6893056167854461, "lm_q2_score": 0.5, "lm_q1q2_score": 0.34465280839272305}}
{"text": "/*\n *  carpack.cpp\n *  carpack\n *\n *  Created by Brandon Kelly on 12/19/12.\n *\n *  Method definitions of classes for MCMC sampling from continuous time\n *  autoregressive (CAR) models.\n *\n */\n\n// Standard includes\n#include <complex>\n#include <iostream>\n\n// Armadillo includes\n#include <armadillo>\n\n// Boost includes\n#include <boost/math/special_functions/binomial.hpp>\n\n// Local includes\n#include \"include/carpack.hpp\"\n\n// Global random number generator object, instantiated in random.cpp\nextern boost::random::mt19937 rng;\n\n// Object containing some common random number generators.\nextern RandomGenerator RandGen;\n\n/********************************************************************\n\t\t\t\t\t\tMETHODS OF CAR1 CLASS\n *******************************************************************/\n\n// Method of CAR1 class to generate the starting values of the\n// parameters theta = (mu, sigma, measerr_scale, log(omega)).\n\narma::vec CAR1::StartingValue()\n{\n\tdouble log_omega_start, car1_stdev_start, sigma;\n\n\t// Initialize the standard deviation of the CAR(1) process\n\t// by drawing from its prior\n\tcar1_stdev_start = RandGen.scaled_inverse_chisqr(y_.n_elem-1, arma::var(y_));\n\tcar1_stdev_start = sqrt(car1_stdev_start);\n    \n    // Get initial value of the time series mean\n    double mu = RandGen.normal(arma::mean(y_), car1_stdev_start / y_.n_elem);\n\n\t// Initialize log(omega) to log( 1 / (a * median(dt)) ), where\n\t// a ~ Uniform(1,50) , under the constraint that \n\t// tau = 1 / omega < max(time)\n\t\n    arma::vec dt = time_(arma::span(1,time_.n_elem-1)) - time_(arma::span(0,time_.n_elem-2));\n\tlog_omega_start = -1.0 * log(arma::median(dt) * RandGen.uniform( 1.0, 50.0 ));\n\tlog_omega_start = std::min(log_omega_start, max_freq_);\n\t\n\tsigma = car1_stdev_start * sqrt(2.0 * exp(log_omega_start));\n\t\n\t// Get initial value of the measurement error scaling parameter by\n\t// drawing from its prior.\n\t\n\tdouble measerr_scale = RandGen.scaled_inverse_chisqr(measerr_dof_, 1.0);\n    measerr_scale = std::min(measerr_scale, 1.99);\n    measerr_scale = std::max(measerr_scale, 0.51);\n\t\n\tarma::vec theta(4);\n\t\n\ttheta << car1_stdev_start << measerr_scale << mu << log_omega_start << arma::endr;\n\t\n\t// Initialize the Kalman filter\n    pKFilter_->SetOmega(exp(log_omega_start));\n    pKFilter_->SetSigsqr(sigma * sigma);\n    arma::vec proposed_yerr = sqrt(measerr_scale) * yerr_;\n    pKFilter_->SetTimeSeriesErr(proposed_yerr);\n    arma::vec ycent = y_ - mu;\n    pKFilter_->SetTimeSeries(ycent);\n    pKFilter_->Filter();\n\t\n\treturn theta;\n}\n\narma::vec CAR1::SetStartingValue(arma::vec init)\n{\n   if (init.n_elem != 4) {\n      std::cout << \"WARNING: initial guess not length 4, initializing with prior\" << std::endl;\n      return StartingValue();\n   }\n\n   double logpost = LogDensity(init);\n   bool good_initials = arma::is_finite(logpost);\n   if (good_initials == false) {\n      std::cout << \"WARNING: initial guess yields non-finite likelihood, initializing with prior\" << std::endl;\n      return StartingValue();\n   }\n      \n   double mu, log_omega_start, car1_stdev_start, sigma, measerr_scale;\n   car1_stdev_start = init[0];\n   measerr_scale    = init[1];\n   mu               = init[2];\n   log_omega_start  = init[3];\n   sigma            = car1_stdev_start * sqrt(2.0 * exp(log_omega_start));\n\n   pKFilter_->SetOmega(exp(log_omega_start));\n   pKFilter_->SetSigsqr(sigma * sigma);\n   arma::vec proposed_yerr = sqrt(measerr_scale) * yerr_;\n   pKFilter_->SetTimeSeriesErr(proposed_yerr);\n   arma::vec ycent = y_ - mu;\n   pKFilter_->SetTimeSeries(ycent);\n   pKFilter_->Filter();\n\n   return init;\n}\n\n\nbool CAR1::CheckPriorBounds(arma::vec theta)\n{\n    double ysigma = theta(0);\n    double measerr_scale = theta(1);\n    double omega = exp(theta(3));\n    \n    bool prior_satisfied = true;\n    if ( (omega > max_freq_) || (omega < min_freq_) ||\n        (ysigma > max_stdev_) || (ysigma < 0) ||\n        (measerr_scale < 0.5) || (measerr_scale > 2.0) ) {\n\t\t// prior bounds not satisfied\n\t\tprior_satisfied = false;\n\t}\n    return prior_satisfied;\n}\n\n/********************************************************************\n                        METHODS OF CARp CLASS\n *******************************************************************/\n\n// Calculate the roots of the AR(p) polynomial from the parameters\narma::cx_vec CARp::ARRoots(arma::vec theta)\n{\n    arma::cx_vec ar_roots(p_);\n    \n    // Construct the complex vector of roots of the characteristic polynomial:\n    // alpha(s) = s^p + alpha_1 s^{p-1} + ... + alpha_{p-1} s + alpha_p\n    for (int i=0; i<p_/2; i++) {\n        // alpha(s) decomposed into its quadratic terms:\n        //   alpha(s) = (quad_term1 + quad_term2 * s + s^2) * ...\n        double quad_term1 = exp(theta(3+2*i));\n        double quad_term2 = exp(theta(3+2*i+1));\n\n        double discriminant = quad_term2 * quad_term2 - 4.0 * quad_term1;\n        \n        if (discriminant > 0) {\n            // two real roots\n            double root1 = -0.5 * (quad_term2 + sqrt(discriminant));\n            double root2 = -0.5 * (quad_term2 - sqrt(discriminant));\n            ar_roots(2*i) = std::complex<double> (root1, 0.0);\n            ar_roots(2*i+1) = std::complex<double> (root2, 0.0);\n        } else {\n            double real_part = -0.5 * quad_term2;\n            double imag_part = -0.5 * sqrt(-discriminant);\n            ar_roots(2*i) = std::complex<double> (real_part, imag_part);\n            ar_roots(2*i+1) = std::complex<double> (real_part, -imag_part);\n        }\n    }\n\t\n    if ((p_ % 2) == 1) {\n        // p is odd, so add in additional low-frequency component\n        double real_root = -exp(theta(3+p_-1));\n        ar_roots(p_-1) = std::complex<double> (real_root, 0.0);\n    }\n        \n    return ar_roots;\n}\n\n// Return the starting value and set log_posterior_\narma::vec CARp::StartingValue()\n{\n    // Create the parameter vector, theta\n    arma::vec theta(p_+3);\n    \n    bool good_initials = false;\n    int iguess_count = 0;\n    while (!good_initials) {\n\n        arma::vec loga = StartingAR();\n        for (int i=0; i<p_; i++) {\n            theta(3+i) = loga(i);\n        }\n        \n        // Initial guess for model standard deviation is randomly distributed\n        // around measured standard deviation of the time series\n        double yvar = RandGen.scaled_inverse_chisqr(y_.n_elem-1, arma::var(y_));\n        \n        // Get initial value of the time series mean\n        double mu = RandGen.normal(arma::mean(y_), sqrt(yvar) / y_.n_elem);\n\n        arma::cx_vec alpha_roots = ARRoots(theta);\n        double sigsqr = yvar / Variance(alpha_roots, ma_coefs_, 1.0);\n        \n        // Get initial value of the measurement error scaling parameter by\n        // drawing from its prior.\n        double measerr_scale = RandGen.scaled_inverse_chisqr(measerr_dof_, 1.0);\n        measerr_scale = std::min(measerr_scale, 1.99);\n        measerr_scale = std::max(measerr_scale, 0.51);\n        \n        theta(0) = sqrt(yvar);\n        theta(1) = measerr_scale;\n        theta(2) = mu;\n        \n        // set the Kalman filter parameters\n        pKFilter_->SetSigsqr(sigsqr);\n        pKFilter_->SetOmega(ExtractAR(theta));\n        arma::vec proposed_yerr = sqrt(measerr_scale) * yerr_;\n        pKFilter_->SetTimeSeriesErr(proposed_yerr);\n        arma::vec ycent = y_ - mu;\n        pKFilter_->SetTimeSeries(ycent);\n        \n        // run the kalman filter\n        pKFilter_->Filter();\n        \n        double logpost = LogDensity(theta);\n        good_initials = arma::is_finite(logpost);\n        \n        iguess_count++;\n        if (iguess_count > 200) {\n            std::cout << \"Tried 200 initial guesses, still trying...\" << std::endl;\n        }\n    } // continue loop until the starting values give us a finite posterior\n    \n    return theta;\n}\n\n// Return the starting value and set log_posterior_\narma::vec CARp::SetStartingValue(arma::vec init)\n{\n\n   if (init.n_elem != (p_+3)) {\n      std::cout << \"WARNING: initial guess wrong length, initializing with prior\" << std::endl;\n      return StartingValue();\n   }\n\n   double logpost = LogDensity(init);\n   bool good_initials = arma::is_finite(logpost);\n   if (good_initials == false) {\n      std::cout << \"WARNING: initial guess yields non-finite likelihood, initializing with prior\" << std::endl;\n      return StartingValue();\n   }\n\n   double yvar = init(0)*init(0);\n   double measerr_scale = init(1);\n   double mu = init(2);\n\n   arma::cx_vec alpha_roots = ARRoots(init);\n   double sigsqr = yvar / Variance(alpha_roots, ma_coefs_, 1.0);\n   \n   // set the Kalman filter parameters\n   pKFilter_->SetSigsqr(sigsqr);\n   pKFilter_->SetOmega(ExtractAR(init));\n   arma::vec proposed_yerr = sqrt(measerr_scale) * yerr_;\n   pKFilter_->SetTimeSeriesErr(proposed_yerr);\n   arma::vec ycent = y_ - mu;\n   pKFilter_->SetTimeSeries(ycent);\n   pKFilter_->Filter();\n\n   return init;\n}\n\n// return the starting values for the autoregressive polynomial paramters\narma::vec CARp::StartingAR() {\n    double min_freq = 1.0 / (time_.max() - time_.min());\n    \n    // Obtain initial values for Lorentzian centroids (= system frequencies) and\n    // widths (= break frequencies)\n    arma::vec lorentz_cent((p_+1)/2);\n    lorentz_cent.randu();\n    lorentz_cent = log(max_freq_ / min_freq) * lorentz_cent + log(min_freq);\n    lorentz_cent = arma::exp(lorentz_cent);\n    \n    // Force system frequencies to be in descending order to make the model identifiable\n    lorentz_cent = arma::sort(lorentz_cent, 1);\n    \n    arma::vec lorentz_width((p_+1)/2);\n    lorentz_width.randu();\n    lorentz_width = log(max_freq_ / min_freq) * lorentz_width + log(min_freq);\n    lorentz_width = arma::exp(lorentz_width);\n    \n    if ((p_ % 2) == 1) {\n        // p is odd, so add additional low-frequency component\n        lorentz_cent(p_/2) = 0.0;\n        // make initial break frequency of low-frequency component less than minimum\n        // value of the system frequencies\n        lorentz_width(p_/2) = exp(RandGen.uniform(log(min_freq), log(lorentz_cent(p_/2-1))));\n    }\n\n    arma::vec loga(p_);\n    \n    // convert the PSD lorentzian parameters to quadratic terms in the AR polynomial decomposition\n    for (int i=0; i<p_/2; i++) {\n        double real_part = -2.0 * arma::datum::pi * lorentz_width(i);\n        double imag_part = 2.0 * arma::datum::pi * lorentz_cent(i);\n        double quad_term1 = real_part * real_part + imag_part * imag_part;\n        double quad_term2 = -2.0 * real_part;\n        loga(2*i) = log(quad_term1);\n        loga(1+2*i) = log(quad_term2);\n    }\n    if ((p_ % 2) == 1) {\n        // p is odd, so add in additional value of lorentz_width\n        double real_part = -2.0 * arma::datum::pi * lorentz_width(p_/2);\n        loga(p_-1) = log(-real_part);\n    }\n    return loga;\n}\n\n// check prior bounds\nbool CARp::CheckPriorBounds(arma::vec theta)\n{\n    if (ignore_prior_) {return true;}\n\n    double ysigma = theta(0);\n    double measerr_scale = theta(1);\n    arma::cx_vec ar_roots = ExtractAR(theta);\n    \n    arma::vec lorentz_cent = arma::abs(arma::imag(ar_roots)) / 2.0 / arma::datum::pi;\n    arma::vec lorentz_width = -arma::real(ar_roots) / 2.0 / arma::datum::pi;\n    \n    // Find the set of Frequencies satisfying the prior bounds\n    arma::uvec valid_frequencies1 = arma::find(lorentz_cent < max_freq_);\n\tarma::uvec valid_frequencies2 = arma::find(lorentz_width < max_freq_);\n    arma::uvec valid_frequencies3 = arma::find(lorentz_width > min_freq_);\n    \n    double tol = 1e-4;\n    bool prior_satisfied = unique_roots(ar_roots, tol); // are the roots unique?\n    \n    if ( (valid_frequencies1.n_elem != lorentz_cent.n_elem) ||\n        (valid_frequencies2.n_elem != lorentz_width.n_elem) ||\n        (valid_frequencies3.n_elem != lorentz_width.n_elem) ||\n        (ysigma > max_stdev_) || (ysigma < 0) ||\n        (measerr_scale < 0.5) || (measerr_scale > 2.0) ) {\n        // Value are outside of prior bounds\n        \n//        std::cout << \"prior bounds violated\" << std::endl;\n//        std::cout << \"# of valid centroids: \" << valid_frequencies1.n_elem << std::endl;\n//        std::cout << \"# of valid widths: \" << valid_frequencies2.n_elem << std::endl;\n//        std::cout << \"max_freq: \" << max_freq_ << std::endl;\n//        std::cout << \"min_freq: \" << min_freq_ << std::endl;\n//        lorentz_cent.print(\"centroid\");\n//        lorentz_width.print(\"width\");\n//        std::cout << \"ysigma: \" << ysigma << \", max_stdev: \" << max_stdev_ << std::endl;\n//        std::cout << \"measerr_scale: \" << measerr_scale << std::endl;\n//        \n        prior_satisfied = false;\n    }\n    \n    if (order_lorentzians_) {\n        // Make sure the Lorentzian centroids are still in decreasing order\n        for (int i=1; i<lorentz_cent.n_elem; i++) {\n            double lorentz_cent_difference = lorentz_cent(i) - lorentz_cent(i-1);\n            if (lorentz_cent_difference > 1e-8) {\n                // Lorentzians are not in decreasing order, reject this proposal\n                prior_satisfied = false;\n            }\n        }\n    }\n\n//    // Make sure Lorentzian widths are greater than minimum frequency for those Lorentzians with centroids\n//    // less than the minimum frequency.\n//    for (int i=0; i<lorentz_cent.n_elem; i++) {\n//        if (lorentz_cent(i) < min_freq_) {\n//            if (lorentz_width(i) < min_freq_) {\n//                prior_satisfied = false;\n//            }\n//        }\n//    }    \n    return prior_satisfied;\n}\n\n// Calculate the variance of the CAR(p) process\ndouble CARp::Variance(arma::cx_vec alpha_roots, arma::vec ma_coefs, double sigma, double dt)\n{\n    std::complex<double> car_var(0.0,0.0);\n    std::complex<double> denom(0.0,0.0);\n    std::complex<double> numer(0.0,0.0);\n    \n\t// Calculate the variance of a CAR(p) process\n\tfor (int k=0; k<alpha_roots.n_elem; k++) {\n\t\tstd::complex<double> denom_product(1.0,0.0);\n\t\t\n\t\tfor (int l=0; l<alpha_roots.n_elem; l++) {\n\t\t\tif (l != k) {\n\t\t\t\tdenom_product *= (alpha_roots(l) - alpha_roots(k)) * \n                (std::conj(alpha_roots(l)) + alpha_roots(k));\n\t\t\t}\n\t\t}\n        denom = -2.0 * std::real(alpha_roots(k)) * denom_product;\n        \n        int q = ma_coefs.n_elem;\n        std::complex<double> ma_sum1(0.0,0.0);\n        std::complex<double> ma_sum2(0.0,0.0);\n        for (int l=0; l<q; l++) {\n            ma_sum1 += ma_coefs(l) * std::pow(alpha_roots(k),l);\n            ma_sum2 += ma_coefs(l) * std::pow(-alpha_roots(k),l);\n        }\n        numer = ma_sum1 * ma_sum2 * std::exp(alpha_roots(k) * dt);\n        \n        car_var += numer / denom;\n\t}\n\t\n\t// Variance is real-valued, so only return the real part of CARMA_var.\n    return sigma * sigma * car_var.real();\n}\n\n/*******************************************************************\n                        METHODS OF CARMA CLASS\n ******************************************************************/\n\n// Return the starting value and set log_posterior_\narma::vec CARMA::StartingValue()\n{\n    // Create the parameter vector, theta\n    arma::vec theta(p_+q_+3);\n    \n    bool good_initials = false;\n    while (!good_initials) {\n        \n        // Initial guess for model standard deviation is randomly distributed\n        // around measured standard deviation of the time series\n        arma::vec loga = StartingAR();\n        for (int i=0; i<p_; i++) {\n            theta(3+i) = loga(i);\n        }\n        \n        arma::vec log_ma_quad = StartingMA();\n        theta(arma::span(p_+3,theta.n_elem-1)) = log_ma_quad;\n        arma::vec ma_coefs = ExtractMA(theta);\n\n        // Initial guess for model standard deviation is randomly distributed\n        // around measured standard deviation of the time series\n        double yvar = RandGen.scaled_inverse_chisqr(y_.n_elem-1, arma::var(y_));\n        \n        // Get initial value of the time series mean\n        double mu = RandGen.normal(arma::mean(y_), sqrt(yvar) / y_.n_elem);\n        \n        arma::cx_vec alpha_roots = ARRoots(theta);\n        double sigsqr = yvar / Variance(alpha_roots, ma_coefs, 1.0);\n        good_initials = arma::is_finite(sigsqr);\n        // Don't run kalman filter if we're already bad_initials\n\n        if (good_initials) {\n            // Get initial value of the measurement error scaling parameter by\n            // drawing from its prior.\n        \n            double measerr_scale = RandGen.scaled_inverse_chisqr(measerr_dof_, 1.0);\n            measerr_scale = std::min(measerr_scale, 1.99);\n            measerr_scale = std::max(measerr_scale, 0.51);\n        \n            theta(0) = sqrt(yvar);\n            theta(1) = measerr_scale;\n            theta(2) = mu;\n                \n            // set the Kalman filter parameters\n            pKFilter_->SetSigsqr(sigsqr);\n            pKFilter_->SetOmega(ExtractAR(theta));\n            pKFilter_->SetMA(ExtractMA(theta));\n            arma::vec proposed_yerr = sqrt(measerr_scale) * yerr_;\n            pKFilter_->SetTimeSeriesErr(proposed_yerr);\n            arma::vec ycent = y_ - mu;\n            pKFilter_->SetTimeSeries(ycent);\n        \n            // run the kalman filter\n            pKFilter_->Filter();\n        \n            double logpost = LogDensity(theta);\n            good_initials = arma::is_finite(logpost);\n        }\n    } // continue loop until the starting values give us a finite posterior\n    \n    return theta;\n}\n\narma::vec CARMA::SetStartingValue(arma::vec init)\n{\n   if (init.n_elem != (p_+q_+3)) {\n      std::cout << \"WARNING: initial guess wrong length, initializing with prior\" << std::endl;\n      return StartingValue();\n   }\n\n   double logpost = LogDensity(init);\n   bool good_initials = arma::is_finite(logpost);\n   if (good_initials == false) {\n      std::cout << \"WARNING: initial guess yields non-finite likelihood, initializing with prior\" << std::endl;\n      return StartingValue();\n   }\n   \n   double yvar          = init(0)*init(0);        \n   double measerr_scale = init(1);\n   double mu            = init(2);\n   \n   arma::cx_vec alpha_roots = ARRoots(init);\n   arma::vec ma_coefs       = ExtractMA(init);\n   double sigsqr            = yvar / Variance(alpha_roots, ma_coefs, 1.0);\n   \n   // set the Kalman filter parameters\n   pKFilter_->SetSigsqr(sigsqr);\n   pKFilter_->SetOmega(ExtractAR(init));\n   pKFilter_->SetMA(ExtractMA(init));\n   arma::vec proposed_yerr = sqrt(measerr_scale) * yerr_;\n   pKFilter_->SetTimeSeriesErr(proposed_yerr);\n   arma::vec ycent = y_ - mu;\n   pKFilter_->SetTimeSeries(ycent);\n   pKFilter_->Filter();\n   \n   return init;\n}\n\n// get initial guess for the moving average polynomial coefficients\narma::vec CARMA::StartingMA() {\n    arma::vec ma_quad(q_);\n    ma_quad.randn();\n    return arma::abs(ma_quad);\n}\n\n// extract the moving-average coefficients from the CARMA parameter vector\narma::vec CARMA::ExtractMA(arma::vec theta)\n{\n    arma::cx_vec ma_roots(q_);\n    \n    // Construct the complex vector of roots of the characteristic polynomial:\n    // alpha(s) = s^p + alpha_1 s^{p-1} + ... + alpha_{p-1} s + alpha_p\n    for (int i=0; i<q_/2; i++) {\n        // alpha(s) decomposed into its quadratic terms:\n        //   alpha(s) = (quad_term1 + quad_term2 * s + s^2) * ...\n        double quad_term1 = exp(theta(3+p_+2*i));\n        double quad_term2 = exp(theta(3+p_+2*i+1));\n        \n        double discriminant = quad_term2 * quad_term2 - 4.0 * quad_term1;\n        \n        if (discriminant > 0) {\n            // two real roots\n            double root1 = -0.5 * (quad_term2 + sqrt(discriminant));\n            double root2 = -0.5 * (quad_term2 - sqrt(discriminant));\n            ma_roots(2*i) = std::complex<double> (root1, 0.0);\n            ma_roots(2*i+1) = std::complex<double> (root2, 0.0);\n        } else {\n            double real_part = -0.5 * quad_term2;\n            double imag_part = -0.5 * sqrt(-discriminant);\n            ma_roots(2*i) = std::complex<double> (real_part, imag_part);\n            ma_roots(2*i+1) = std::complex<double> (real_part, -imag_part);\n        }\n    }\n\t\n    if ((q_ % 2) == 1) {\n        // p is odd, so add in additional low-frequency component\n        double real_root = -exp(theta(3+p_+q_-1));\n        ma_roots(q_-1) = std::complex<double> (real_root, 0.0);\n    }\n\n    // calculate the coefficients of the polynomial\n    //\n    //    p(x) = x^q + c_1 * x^{q-1} + ... + c_{q-1} * x + c_q\n    //\n    // from it roots. note that poly_coefs[0] = 1.0 = c_0.\n    arma::vec poly_coefs = polycoefs(ma_roots);\n\n    // convert coefficients to MA polynomial representation:\n    //\n    //   beta(s) = beta_q * x^q + beta_{q-1} * x^{q-1} + ... + beta_1 x + beta_0,\n    //\n    // where beta_0 = 1.0.\n    //\n    poly_coefs = poly_coefs / poly_coefs(q_); // standardize so c_q = 1 instead of c_0;\n    arma::vec ma_coefs = arma::zeros(p_);\n    \n    // poly_coefs[0]   poly_coefs[1]   ...   poly_coefs[q] = 1.0\n    //    ||                ||                     ||\n    // ma_coefs[q]    ma_coefs[q-1]    ...    ma_coefs[0]\n    for (int i=0; i<q_+1; i++) {\n        ma_coefs(i) = poly_coefs(q_-i);\n    }\n\n    return ma_coefs;\n}\n\n/*******************************************************************\n                        METHODS OF ZCARMA CLASS\n *******************************************************************/\n\narma::vec ZCARMA::StartingValue()\n{\n    // Create the parameter vector, theta\n    arma::vec theta(p_+4);\n    \n    bool good_initials = false;\n    while (!good_initials) {\n        \n        // Initial guess for model standard deviation is randomly distributed\n        // around measured standard deviation of the time series\n        arma::vec loga = StartingAR();\n        for (int i=0; i<p_; i++) {\n            theta(3+i) = loga(i);\n        }\n        \n        theta(3+p_) = logit(StartingKappa());\n        \n        // compute the coefficients of the MA polynomial\n        arma::vec ma_coefs = ExtractMA(theta);\n        \n        // Initial guess for model standard deviation is randomly distributed\n        // around measured standard deviation of the time series\n        double yvar = RandGen.scaled_inverse_chisqr(y_.n_elem-1, arma::var(y_));\n        \n        // Get initial value of the time series mean\n        double mu = RandGen.normal(arma::mean(y_), sqrt(yvar) / y_.n_elem);\n        \n        arma::cx_vec alpha_roots = ARRoots(theta);\n        double sigsqr = yvar / Variance(alpha_roots, ma_coefs, 1.0);\n        \n        // Get initial value of the measurement error scaling parameter by\n        // drawing from its prior.\n        \n        double measerr_scale = RandGen.scaled_inverse_chisqr(measerr_dof_, 1.0);\n        measerr_scale = std::min(measerr_scale, 1.99);\n        measerr_scale = std::max(measerr_scale, 0.51);\n        \n        theta(0) = sqrt(yvar);\n        theta(1) = measerr_scale;\n        theta(2) = mu;\n        \n        // set the Kalman filter parameters\n        pKFilter_->SetSigsqr(sigsqr);\n        pKFilter_->SetOmega(ExtractAR(theta));\n        pKFilter_->SetMA(ma_coefs);\n        arma::vec proposed_yerr = sqrt(measerr_scale) * yerr_;\n        pKFilter_->SetTimeSeriesErr(proposed_yerr);\n        arma::vec ycent = y_ - mu;\n        pKFilter_->SetTimeSeries(ycent);\n        \n        // run the kalman filter\n        pKFilter_->Filter();\n        \n        double logpost = LogDensity(theta);\n        good_initials = arma::is_finite(logpost);\n    } // continue loop until the starting values give us a finite posterior\n    \n    return theta;\n}\n\narma::vec ZCARMA::SetStartingValue(arma::vec init)\n{\n   if (init.n_elem != (p_+4)) {\n      std::cout << \"WARNING: initial guess wrong length, initializing with prior\" << std::endl;\n      return StartingValue();\n   }\n\n   double logpost = LogDensity(init);\n   bool good_initials = arma::is_finite(logpost);\n   if (good_initials == false) {\n      std::cout << \"WARNING: initial guess yields non-finite likelihood, initializing with prior\" << std::endl;\n      return StartingValue();\n   }\n\n   double yvar          = init(0)*init(0);        \n   double measerr_scale = init(1);\n   double mu            = init(2);\n\n   arma::cx_vec alpha_roots = ARRoots(init);\n   arma::vec ma_coefs = ExtractMA(init);\n   double sigsqr = yvar / Variance(alpha_roots, ma_coefs, 1.0);\n\n   pKFilter_->SetSigsqr(sigsqr);\n   pKFilter_->SetOmega(ExtractAR(init));\n   pKFilter_->SetMA(ma_coefs);\n   arma::vec proposed_yerr = sqrt(measerr_scale) * yerr_;\n   pKFilter_->SetTimeSeriesErr(proposed_yerr);\n   arma::vec ycent = y_ - mu;\n   pKFilter_->SetTimeSeries(ycent);\n   pKFilter_->Filter();\n\n   return init;\n}\n\n// get initial guess for the moving average polynomial coefficients, parameterized by kappa\ndouble ZCARMA::StartingKappa() {\n    double kappa_normed = RandGen.uniform();\n    return kappa_normed;\n}\n\n// extract the moving average coefficients from the parameter vector\narma::vec ZCARMA::ExtractMA(arma::vec theta)\n{\n    double kappa_normed = inv_logit(theta(3 + p_));\n    double kappa = (kappa_high_ - kappa_low_) * kappa_normed + kappa_low_;\n    // Set the moving average terms\n    arma::vec ma_coefs(p_);\n\tma_coefs(0) = 1.0;\n\tfor (int i=1; i<p_; i++) {\n\t\tma_coefs(i) = boost::math::binomial_coefficient<double>(p_-1, i) / pow(kappa,i);\n\t}\n    return ma_coefs;\n}\n\n/*********************************************************************\n                                FUNCTIONS\n ********************************************************************/\n\ndouble logit(double x) { return log(x / (1.0 - x)); }\ndouble inv_logit(double x) { return exp(x) / (1.0 + exp(x)); }\n\n// Check that all of the roots are unique to within a specified fractional\n// tolerance.\nbool unique_roots(arma::cx_vec roots, double tolerance)\n{\n    // Initialize the smallest fractional difference\n    double min_frac_diff = 100.0 * tolerance;\n\n    int p = roots.n_elem;\n    \n    for (int i=0; i<(p-1); i++) {\n        for (int j=i+1; j<p; j++) {\n            // Calculate fractional difference between roots(i) and roots(j)\n            double frac_diff = std::abs( (roots(i) - roots(j)) / \n                                        (roots(i) + roots(j)) );\n            if (frac_diff < min_frac_diff) {\n                // Found new minimum fractional difference, record it\n                min_frac_diff = frac_diff;\n            }\n        }\n    }\n    \n    // Test if the roots unique to within the specified tolerance\n    bool unique = (min_frac_diff > tolerance);\n    \n    return unique;\n}\n    \n// Return the coefficients of a polynomial given its roots. The polynomial\n// is assumed to be of the form:\n//\n//      p(x) = x^n + c_1 * x^{n-1} + ... + c_{n-1} * x + c_n\n//\n// where {c_i ; i=1,...,n} are the coefficients. Note that this function\n// returns a (n+1)-element column vector, where c_0 = 1.0.\n\narma::vec polycoefs(arma::cx_vec roots)\n{    \n    arma::cx_vec coefs(roots.n_elem+1);\n    coefs.zeros(); // Initialize all values to zero\n    \n    coefs(0) = 1.0; // Coefficient for highest order term is set to one\n    \n    for (int i=0; i<roots.n_elem; i++) {\n        // Calculate the coefficients using a recursion formula\n        coefs(arma::span(1,i+1)) = coefs(arma::span(1,i+1)) - roots(i) * coefs(arma::span(0,i));\n    }\n    \n    // The coefficients must be real, so only return the real part\n    return arma::real(coefs);\n}\n", "meta": {"hexsha": "e36537e84e02862b2912936d6fccb0ca3d9f7451", "size": 27016, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/carpack.cpp", "max_stars_repo_name": "Jamieryan/carma_pack", "max_stars_repo_head_hexsha": "347ea78818cc808e53e4a46d341829f787198df5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 39.0, "max_stars_repo_stars_event_min_datetime": "2015-01-25T19:24:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-28T11:55:28.000Z", "max_issues_repo_path": "src/carpack.cpp", "max_issues_repo_name": "Jamieryan/carma_pack", "max_issues_repo_head_hexsha": "347ea78818cc808e53e4a46d341829f787198df5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 13.0, "max_issues_repo_issues_event_min_datetime": "2015-04-29T12:37:45.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-28T23:31:29.000Z", "max_forks_repo_path": "src/carpack.cpp", "max_forks_repo_name": "Jamieryan/carma_pack", "max_forks_repo_head_hexsha": "347ea78818cc808e53e4a46d341829f787198df5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 19.0, "max_forks_repo_forks_event_min_datetime": "2015-09-15T00:41:28.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-28T07:28:47.000Z", "avg_line_length": 35.6882430647, "max_line_length": 111, "alphanum_fraction": 0.5979789754, "num_tokens": 7438, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.658417500561683, "lm_q2_score": 0.523420348936324, "lm_q1q2_score": 0.34462911788977846}}
{"text": "#ifndef ODESOLVERIMEX_HPP_INCLUDED\n#define ODESOLVERIMEX_HPP_INCLUDED\n\n#include <petscts.h>\n#include <string>\n#include <cmath>\n#include <vector>\n#include <map>\n#include <algorithm>\n#include <assert.h>\n#include <boost/circular_buffer.hpp>\n#include \"integratorContextImex.hpp\"\n#include \"genFuncs.hpp\"\n\nusing namespace std;\n\n/*\n * Provides a set of algorithms to solve a system of ODEs of\n * the form y' = f(t,y) using IMEX time stepping,\n * where y is represented as an array of one or more Vecs\n * (PETSc data type).\n *\n * Containers for integration:\n *   var          map<string,Vec> of explicitly integrated variables\n *   varIm    map<string,Vec> of implicitly integrated variables\n *\n * SOLVER TYPE        ALGORITHM\n *  RK32_WBE        explicit part Runge-Kutta (2,3), implicit controlled by user\n *  RK43_WBE        explicit part Runge-Kutta (3,4), implicit controlled by user\n *\n *\n * At minimum, the user must specify:\n *     QUANTITY               FUNCTION\n *  max number of steps      constructor\n *  solver type              constructor\n *  initial conditions       setInitialConds     Note: this array will be modified during integration\n *  initial step size        constructor\n *  step size alg            constructor (this is only used by the adaptive time-stepping algorithm)\n *  f(t,y)                   object passed to integrate must have member function d_dt(PetscScalar, PetscScalar*,PetscScalar*)\n *  final time               constructor and setTimeRange\n *  timeMonitor              object passed to integrate must have member function timeMonitor\n *\n *\n * Optional fields that can also be specified:\n *     QUANTITY               FUNCTION\n *  tolerance                setTolerance\n *  maximum step size        setStepSize\n *  minimum step size        setTimeStepBounds\n *  initial step size        setTimeStepBounds\n *\n * Once the odeSolver context is set, call integrate() to perform\n * the integration.\n *\n * y(t=final time) is stored in the initial conditions array.  Summary output\n * information is provided by viewSolver.  Users can obtain information at\n * each time step within a user-defined monitor function.\n *\n */\n\nclass OdeSolverImex\n{\npublic:\n\n  PetscReal               _initT,_finalT,_currT,_deltaT;\n  PetscReal          _newDeltaT; // stores future deltaT for access by outside classes, primarily for checkpointing\n  PetscInt                _maxNumSteps,_stepCount;\n  map<string,Vec>         _varEx,_dvar; // explicit integration variable and rate\n  map<string,Vec>         _varIm; // implicit integration variable, once per time step\n  vector<string>          _errInds; // which inds of _var to use for error control\n  vector<double>          _scale; // scale factor for entries in _errInds\n  double                  _runTime;\n  string                  _controlType;\n  string                  _normType;\n\n  PetscReal   _minDeltaT,_maxDeltaT;\n  PetscReal   _totTol; // total tolerance, might be atol, or rtol, or a combination of both\n  PetscInt    _numRejectedSteps,_numMinSteps,_numMaxSteps;\n\n  // for PID error control\n  boost::circular_buffer<double> _errA;\n\n  // constructor and destructor\n  OdeSolverImex(PetscInt maxNumSteps,PetscReal finalT,PetscReal deltaT,string controlType);\n  virtual ~OdeSolverImex() {};\n\n  // member functions\n  PetscErrorCode setInitialStepCount(const PetscReal stepCount);\n  PetscErrorCode setToleranceType(const string normType); // type of norm used for error control\n\n  // virtual member functions are declared in base class and redefined in derived class\n  virtual PetscErrorCode setTimeRange(const PetscReal initT,const PetscReal finalT) = 0;\n  virtual PetscErrorCode setStepSize(const PetscReal deltaT) = 0;\n  virtual PetscErrorCode setTolerance(const PetscReal tol) = 0;\n  virtual PetscErrorCode setTimeStepBounds(const PetscReal minDeltaT, const PetscReal maxDeltaT) = 0;\n  virtual PetscErrorCode setInitialConds(map<string,Vec>& varEx, map<string,Vec>& varIm) = 0;\n  virtual PetscErrorCode setErrInds(vector<string>& errInds) = 0;\n  virtual PetscErrorCode setErrInds(vector<string>& errInds, vector<double> scale) = 0;\n\n  virtual PetscErrorCode view() = 0;\n  virtual PetscErrorCode integrate(IntegratorContextImex *obj) = 0;\n  virtual PetscReal computeStepSize(const PetscReal totErr) = 0;\n  virtual PetscReal computeError() = 0;\n};\n\n\n// Explicit RK32 scheme from Hairer et al., with added Backward Euler implicit scheme once per time step\n// derived class from OdeSolverImex\nclass RK32_WBE : public OdeSolverImex\n{\npublic:\n\n  // for P or PID error control\n  PetscReal   _kappa,_ord; // safety factor in step size determinance, order of accuracy of method\n  PetscReal   _totErr; // error between 3rd order solution and embedded 2nd order solution\n\n  // intermediate values for time stepping for the explicit variable\n  map<string,Vec> _k1,_f1,_k2,_f2,_y2,_y3;\n  map<string,Vec> _vardTIm;\n\n  // constructor and destructor\n  RK32_WBE(PetscInt maxNumSteps,PetscReal finalT,PetscReal deltaT,string controlType);\n  ~RK32_WBE();\n\n  // member functions\n  PetscErrorCode setTimeRange(const PetscReal initT,const PetscReal finalT);\n  PetscErrorCode setStepSize(const PetscReal deltaT);\n  PetscErrorCode setTolerance(const PetscReal tol);\n  PetscErrorCode setTimeStepBounds(const PetscReal minDeltaT, const PetscReal maxDeltaT);\n  PetscErrorCode setInitialConds(map<string,Vec>& varEx, map<string,Vec>& varIm);\n  PetscErrorCode setErrInds(vector<string>& errInds);\n  PetscErrorCode setErrInds(vector<string>& errInds, vector<double> scale);\n  PetscErrorCode view();\n  PetscErrorCode integrate(IntegratorContextImex *obj);\n  PetscReal computeStepSize(const PetscReal totErr);\n  PetscReal computeError();\n};\n\n\n// Runge-Kutta 4(3) scheme for explicit time integration, with added\n// Backward Euler implicit scheme once per time step.\n// Based on \"ARK4(3)6L[2]SA-ERK\" algorithm from Kennedy and Carpenter (2003):\n// \"Additive Runge-Kutta schemes for convection-diffusion-reaction equations\"\n// Note: Has matching IMEX equivalent\n// derived class from OdeSolverImex\nclass RK43_WBE : public OdeSolverImex\n{\npublic:\n\n  // for P or PID error control\n  // safety factor in step size determinance, order of accuracy of method\n  PetscReal   _kappa,_ord;\n  // error between 3rd order solution and embedded 2nd order solution\n  PetscReal   _totErr;\n\n  // intermediate values for time stepping for the explicit variable\n  map<string,Vec> _k1,_k2,_k3,_k4,_k5,_k6,_y4,_y3;\n  map<string,Vec> _f1,_f2,_f3,_f4,_f5,_f6;\n\n  // intermediate value for implict variable\n  map<string,Vec> _vardTIm;\n\n  // constructor and destructor\n  RK43_WBE(PetscInt maxNumSteps,PetscReal finalT,PetscReal deltaT,string controlType);\n  ~RK43_WBE();\n\n  // member functions\n  PetscErrorCode setTimeRange(const PetscReal initT,const PetscReal finalT);\n  PetscErrorCode setStepSize(const PetscReal deltaT);\n  PetscErrorCode setTolerance(const PetscReal tol);\n  PetscErrorCode setTimeStepBounds(const PetscReal minDeltaT, const PetscReal maxDeltaT);\n  PetscErrorCode setInitialConds(map<string,Vec>& varEx, map<string,Vec>& varIm);\n  PetscErrorCode setErrInds(vector<string>& errInds);\n  PetscErrorCode setErrInds(vector<string>& errInds, vector<double> scale);\n  PetscErrorCode view();\n  PetscErrorCode integrate(IntegratorContextImex *obj);\n  PetscReal computeStepSize(const PetscReal totErr);\n  PetscReal computeError();\n};\n\n#endif\n\n", "meta": {"hexsha": "96a513ecd0d486710f38b84d343a1cddc3eceeef", "size": 7361, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "source/odeSolverImex.hpp", "max_stars_repo_name": "kali-allison/SCycle", "max_stars_repo_head_hexsha": "0a81edfae8730acb44531e2c2b3f51f25ea193d2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2019-04-12T16:36:36.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-16T00:35:03.000Z", "max_issues_repo_path": "source/odeSolverImex.hpp", "max_issues_repo_name": "kali-allison/SCycle", "max_issues_repo_head_hexsha": "0a81edfae8730acb44531e2c2b3f51f25ea193d2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "source/odeSolverImex.hpp", "max_forks_repo_name": "kali-allison/SCycle", "max_forks_repo_head_hexsha": "0a81edfae8730acb44531e2c2b3f51f25ea193d2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2019-07-22T23:53:15.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-10T03:30:50.000Z", "avg_line_length": 40.4450549451, "max_line_length": 126, "alphanum_fraction": 0.740116832, "num_tokens": 1847, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.658417500561683, "lm_q2_score": 0.523420348936324, "lm_q1q2_score": 0.34462911788977846}}
{"text": "#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <cmath>\n#include \"GSLInterface.h\"\n#include <gsl/gsl_poly.h>\n#include \"utils.h\"\n#include \"coordsys.h\"\n#include \"coordtransforms.h\"\n#include \"potential.h\"\n#include \"orbit.h\"\n#include \"aa.h\"\n#include <boost/python.hpp>\n#include <boost/python/numeric.hpp>\nusing namespace boost::python;\n\nnamespace {\n\tboost::python::numeric::array Stack_Triax_Forces(boost::python::numeric::array f){\n\t\tStackelTriaxial T(3.61/500.,-30.,-20.);\n\t\tVecDoub x(3,0); for(int i=0;i<3;i++)x[i]=extract<double>(f[i]);\n\t\tVecDoub v = T.Forces(x);\n    \treturn boost::python::numeric::array(make_tuple(v[0],v[1],v[2]));\n\t}\n\tdouble Stack_Triax_H(boost::python::numeric::array f){\n\t\tStackelTriaxial T(3.61/500.,-30.,-20.);\n\t\tVecDoub x(6,0);for(int i=0;i<6;i++)x[i]=extract<double>(f[i]);\n\t\treturn T.H(x);\n\t}\n\tboost::python::numeric::array Stack_Triax_Actions(boost::python::numeric::array f){\n\t\tStackelTriaxial T(3.61/500.,-30.,-20.);\n\t\tVecDoub x(6,0);for(int i=0;i<6;i++)x[i]=extract<double>(f[i]);\n\t\tActions_TriaxialStackel AA(&T);\n\t\tVecDoub v = AA.actions(x);\n    \treturn boost::python::numeric::array(make_tuple(v[0],v[1],v[2]));\n\t}\n\n\tboost::python::numeric::array Stack_Triax_Freqs(boost::python::numeric::array f){\n\t\tStackelTriaxial T(3.61/500.,-30.,-20.);\n\t\tVecDoub x(6,0);for(int i=0;i<6;i++)x[i]=extract<double>(f[i]);\n\t\tActions_TriaxialStackel AA(&T);\n\t\tVecDoub v = AA.actions(x,1);\n    \treturn boost::python::numeric::array(make_tuple(v[3],v[4],v[5]));\n\t}\n}\n\nBOOST_PYTHON_MODULE(triax_py){\n\tboost::python::numeric::array::set_module_and_type(\"numpy\", \"ndarray\");\n    def(\"Stack_Triax_Forces\", Stack_Triax_Forces);\n    def(\"Stack_Triax_H\", Stack_Triax_H);\n    def(\"Stack_Triax_Actions\", Stack_Triax_Actions);\n    def(\"Stack_Triax_Freqs\", Stack_Triax_Freqs);\n}\t", "meta": {"hexsha": "6dbc3cda76609bc785bc7dc42582eb29f7c5479b", "size": 1802, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "new_struct/src/triax_py.cpp", "max_stars_repo_name": "jlsanders/genfunc", "max_stars_repo_head_hexsha": "6a608a21651be37462e42289c0a15233b8e29bbb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-05-12T13:24:27.000Z", "max_stars_repo_stars_event_max_datetime": "2019-10-14T01:06:54.000Z", "max_issues_repo_path": "new_struct/src/triax_py.cpp", "max_issues_repo_name": "jlsanders/genfunc", "max_issues_repo_head_hexsha": "6a608a21651be37462e42289c0a15233b8e29bbb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "new_struct/src/triax_py.cpp", "max_forks_repo_name": "jlsanders/genfunc", "max_forks_repo_head_hexsha": "6a608a21651be37462e42289c0a15233b8e29bbb", "max_forks_repo_licenses": ["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.6538461538, "max_line_length": 84, "alphanum_fraction": 0.6881243063, "num_tokens": 609, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7057850402140659, "lm_q2_score": 0.48828339529583464, "lm_q1q2_score": 0.34462311578473126}}
{"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_CLUSTERING_COEFFICIENT_HPP\n#define BOOST_GRAPH_CLUSTERING_COEFFICIENT_HPP\n\n#include <boost/utility.hpp>\n#include <boost/graph/graph_traits.hpp>\n#include <boost/graph/graph_concepts.hpp>\n\nnamespace boost\n{\nnamespace detail\n{\n    template <class Graph>\n    inline typename graph_traits<Graph>::degree_size_type\n    possible_edges(const Graph& g, std::size_t k, directed_tag)\n    {\n        function_requires< GraphConcept<Graph> >();\n        typedef typename graph_traits<Graph>::degree_size_type T;\n        return T(k) * (T(k) - 1);\n    }\n\n    template <class Graph>\n    inline typename graph_traits<Graph>::degree_size_type\n    possible_edges(const Graph& g, size_t k, undirected_tag)\n    {\n        // dirty little trick...\n        return possible_edges(g, k, directed_tag()) / 2;\n    }\n\n    // This template matches directedS and bidirectionalS.\n    template <class Graph>\n    inline typename graph_traits<Graph>::degree_size_type\n    count_edges(const Graph& g,\n                typename Graph::vertex_descriptor u,\n                typename Graph::vertex_descriptor v,\n                directed_tag)\n\n    {\n        function_requires< AdjacencyMatrixConcept<Graph> >();\n        return (edge(u, v, g).second ? 1 : 0) +\n                (edge(v, u, g).second ? 1 : 0);\n    }\n\n    // This template matches undirectedS\n    template <class Graph>\n    inline typename graph_traits<Graph>::degree_size_type\n    count_edges(const Graph& g,\n                typename Graph::vertex_descriptor u,\n                typename Graph::vertex_descriptor v,\n                undirected_tag)\n    {\n        function_requires< AdjacencyMatrixConcept<Graph> >();\n        return edge(u, v, g).second ? 1 : 0;\n    }\n}\n\ntemplate <typename Graph, typename Vertex>\ninline typename graph_traits<Graph>::degree_size_type\nnum_paths_through_vertex(const Graph& g, Vertex v)\n{\n    function_requires< AdjacencyGraphConcept<Graph> >();\n    typedef typename graph_traits<Graph>::directed_category Directed;\n    typedef typename graph_traits<Graph>::adjacency_iterator AdjacencyIterator;\n\n    // TODO: There should actually be a set of neighborhood functions\n    // for things like this (num_neighbors() would be great).\n\n    AdjacencyIterator i, end;\n    tie(i, end) = adjacent_vertices(v, g);\n    std::size_t k = std::distance(i, end);\n    return detail::possible_edges(g, k, Directed());\n}\n\ntemplate <typename Graph, typename Vertex>\ninline typename graph_traits<Graph>::degree_size_type\nnum_triangles_on_vertex(const Graph& g, Vertex v)\n{\n    function_requires< IncidenceGraphConcept<Graph> >();\n    function_requires< AdjacencyGraphConcept<Graph> >();\n    typedef typename graph_traits<Graph>::degree_size_type Degree;\n    typedef typename graph_traits<Graph>::directed_category Directed;\n    typedef typename graph_traits<Graph>::adjacency_iterator AdjacencyIterator;\n\n    // TODO: I might be able to reduce the requirement from adjacency graph\n    // to incidence graph by using out edges.\n\n    Degree count(0);\n    AdjacencyIterator i, j, end;\n    for(tie(i, end) = adjacent_vertices(v, g); i != end; ++i) {\n        for(j = boost::next(i); j != end; ++j) {\n            count += detail::count_edges(g, *i, *j, Directed());\n        }\n    }\n    return count;\n} /* namespace detail */\n\ntemplate <typename T, typename Graph, typename Vertex>\ninline T\nclustering_coefficient(const Graph& g, Vertex v)\n{\n    T zero(0);\n    T routes = T(num_paths_through_vertex(g, v));\n    return (routes > zero) ?\n        T(num_triangles_on_vertex(g, v)) / routes : zero;\n}\n\ntemplate <typename Graph, typename Vertex>\ninline double\nclustering_coefficient(const Graph& g, Vertex v)\n{ return clustering_coefficient<double>(g, v); }\n\ntemplate <typename Graph, typename ClusteringMap>\ninline typename property_traits<ClusteringMap>::value_type\nall_clustering_coefficients(const Graph& g, ClusteringMap cm)\n{\n    function_requires< VertexListGraphConcept<Graph> >();\n    typedef typename graph_traits<Graph>::vertex_descriptor Vertex;\n    typedef typename graph_traits<Graph>::vertex_iterator VertexIterator;\n    function_requires< WritablePropertyMapConcept<ClusteringMap,Vertex> >();\n    typedef typename property_traits<ClusteringMap>::value_type Coefficient;\n\n    Coefficient sum(0);\n    VertexIterator i, end;\n    for(tie(i, end) = vertices(g); i != end; ++i) {\n        Coefficient cc = clustering_coefficient<Coefficient>(g, *i);\n        put(cm, *i, cc);\n        sum += cc;\n    }\n    return sum / Coefficient(num_vertices(g));\n}\n\ntemplate <typename Graph, typename ClusteringMap>\ninline typename property_traits<ClusteringMap>::value_type\nmean_clustering_coefficient(const Graph& g, ClusteringMap cm)\n{\n    function_requires< VertexListGraphConcept<Graph> >();\n    typedef typename graph_traits<Graph>::vertex_descriptor Vertex;\n    typedef typename graph_traits<Graph>::vertex_iterator VertexIterator;\n    function_requires< ReadablePropertyMapConcept<ClusteringMap,Vertex> >();\n    typedef typename property_traits<ClusteringMap>::value_type Coefficient;\n\n    Coefficient cc(0);\n    VertexIterator i, end;\n    for(tie(i, end) = vertices(g); i != end; ++i) {\n        cc += get(cm, *i);\n    }\n    return cc / Coefficient(num_vertices(g));\n}\n\n} /* namespace boost */\n\n#endif\n", "meta": {"hexsha": "c84c48027fdabcd8cbc392f92f029e5111b08b06", "size": 5462, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/lib/boost/graph/clustering_coefficient.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/clustering_coefficient.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/clustering_coefficient.hpp", "max_forks_repo_name": "EricBoittier/vina-carb-docker", "max_forks_repo_head_hexsha": "e8730d1ef90395e3d7ed3ad00264702313b0766a", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 11.0, "max_forks_repo_forks_event_min_datetime": "2015-02-03T19:24:10.000Z", "max_forks_repo_forks_event_max_datetime": "2019-09-20T10:59:50.000Z", "avg_line_length": 34.5696202532, "max_line_length": 79, "alphanum_fraction": 0.7023068473, "num_tokens": 1276, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5926666143433998, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.3445189346395196}}
{"text": "\n#include <NTL/ZZ.h>\n#include <NTL/vec_ZZ.h>\n#include <NTL/Lazy.h>\n#include <NTL/fileio.h>\n\n#include <cstring>\n\n\n\nNTL_START_IMPL\n\n\n\n\n\nconst ZZ& ZZ::zero()\n{\n   \n   static const ZZ z; // GLOBAL (relies on C++11 thread-safe init)\n   return z;\n}\n\n\nconst ZZ& ZZ_expo(long e)\n{\n   NTL_TLS_LOCAL(ZZ, expo_helper);\n\n   conv(expo_helper, e);\n   return expo_helper;\n}\n\n\n\nvoid AddMod(ZZ& x, const ZZ& a, long b, const ZZ& n)\n{\n   NTL_ZZRegister(B);\n   conv(B, b);\n   AddMod(x, a, B, n);\n}\n\n\nvoid SubMod(ZZ& x, const ZZ& a, long b, const ZZ& n)\n{\n   NTL_ZZRegister(B);\n   conv(B, b);\n   SubMod(x, a, B, n);\n}\n\nvoid SubMod(ZZ& x, long a, const ZZ& b, const ZZ& n)\n{\n   NTL_ZZRegister(A);\n   conv(A, a);\n   SubMod(x, A, b, n);\n}\n\n\n\n// ****** input and output\n\n\nstatic NTL_CHEAP_THREAD_LOCAL long iodigits = 0;\nstatic NTL_CHEAP_THREAD_LOCAL long ioradix = 0;\n// iodigits is the greatest integer such that 10^{iodigits} < NTL_WSP_BOUND\n// ioradix = 10^{iodigits}\n\nstatic void InitZZIO()\n{\n   long x;\n\n   x = (NTL_WSP_BOUND-1)/10;\n   iodigits = 0;\n   ioradix = 1;\n\n   while (x) {\n      x = x / 10;\n      iodigits++;\n      ioradix = ioradix * 10;\n   }\n\n   if (iodigits <= 0) TerminalError(\"problem with I/O\");\n}\n\n\nistream& operator>>(istream& s, ZZ& x)\n{\n   long c;\n   long cval;\n   long sign;\n   long ndigits;\n   long acc;\n   NTL_ZZRegister(a);\n\n   if (!s) NTL_INPUT_ERROR(s, \"bad ZZ input\");\n\n   if (!iodigits) InitZZIO();\n\n   a = 0;\n\n   SkipWhiteSpace(s);\n   c = s.peek();\n\n   if (c == '-') {\n      sign = -1;\n      s.get();\n      c = s.peek();\n   }\n   else\n      sign = 1;\n\n   cval = CharToIntVal(c);\n\n   if (cval < 0 || cval > 9) NTL_INPUT_ERROR(s, \"bad ZZ input\");\n\n   ndigits = 0;\n   acc = 0;\n   while (cval >= 0 && cval <= 9) {\n      acc = acc*10 + cval;\n      ndigits++;\n\n      if (ndigits == iodigits) {\n         mul(a, a, ioradix);\n         add(a, a, acc);\n         ndigits = 0;\n         acc = 0;\n      }\n\n      s.get();\n      c = s.peek();\n      cval = CharToIntVal(c);\n   }\n\n   if (ndigits != 0) {\n      long mpy = 1;\n      while (ndigits > 0) {\n         mpy = mpy * 10;\n         ndigits--;\n      }\n\n      mul(a, a, mpy);\n      add(a, a, acc);\n   }\n\n   if (sign == -1)\n      negate(a, a);\n\n   x = a;\n   return s;\n}\n\n\n// The class _ZZ_local_stack should be defined in an empty namespace,\n// but since I don't want to rely on namespaces, we just give it a funny \n// name to avoid accidental name clashes.\n\nstruct _ZZ_local_stack {\n   long top;\n   Vec<long> data;\n\n   _ZZ_local_stack() { top = -1; }\n\n   long pop() { return data[top--]; }\n   long empty() { return (top == -1); }\n   void push(long x);\n};\n\nvoid _ZZ_local_stack::push(long x)\n{\n   if (top+1 >= data.length()) \n      data.SetLength(max(32, long(1.414*data.length())));\n\n   top++;\n   data[top] = x;\n}\n\n\nstatic\nvoid PrintDigits(ostream& s, long d, long justify)\n{\n   NTL_TLS_LOCAL_INIT(Vec<char>, buf, (INIT_SIZE, iodigits));\n\n   long i = 0;\n\n   while (d) {\n      buf[i] = IntValToChar(d % 10);\n      d = d / 10;\n      i++;\n   }\n\n   if (justify) {\n      long j = iodigits - i;\n      while (j > 0) {\n         s << \"0\";\n         j--;\n      }\n   }\n\n   while (i > 0) {\n      i--;\n      s << buf[i];\n   }\n}\n      \n\n   \n\nostream& operator<<(ostream& s, const ZZ& a)\n{\n   ZZ b;\n   _ZZ_local_stack S;\n   long r;\n   long k;\n\n   if (!iodigits) InitZZIO();\n\n   b = a;\n\n   k = sign(b);\n\n   if (k == 0) {\n      s << \"0\";\n      return s;\n   }\n\n   if (k < 0) {\n      s << \"-\";\n      negate(b, b);\n   }\n\n   do {\n      r = DivRem(b, b, ioradix);\n      S.push(r);\n   } while (!IsZero(b));\n\n   r = S.pop();\n   PrintDigits(s, r, 0);\n\n   while (!S.empty()) {\n      r = S.pop();\n      PrintDigits(s, r, 1);\n   }\n      \n   return s;\n}\n\n\n\nlong GCD(long a, long b)\n{\n   long u, v, t, x;\n\n   if (a < 0) {\n      if (a < -NTL_MAX_LONG) ResourceError(\"GCD: integer overflow\");\n      a = -a;\n   }\n\n   if (b < 0) {\n      if (b < -NTL_MAX_LONG) ResourceError(\"GCD: integer overflow\");\n      b = -b;\n   }\n\n\n   if (b==0)\n      x = a;\n   else {\n      u = a;\n      v = b;\n      do {\n         t = u % v;\n         u = v; \n         v = t;\n      } while (v != 0);\n\n      x = u;\n   }\n\n   return x;\n}\n\n         \n\nvoid XGCD(long& d, long& s, long& t, long a, long b)\n{\n   long  u, v, u0, v0, u1, v1, u2, v2, q, r;\n\n   long aneg = 0, bneg = 0;\n\n   if (a < 0) {\n      if (a < -NTL_MAX_LONG) ResourceError(\"XGCD: integer overflow\");\n      a = -a;\n      aneg = 1;\n   }\n\n   if (b < 0) {\n      if (b < -NTL_MAX_LONG) ResourceError(\"XGCD: integer overflow\");\n      b = -b;\n      bneg = 1;\n   }\n\n   u1=1; v1=0;\n   u2=0; v2=1;\n   u = a; v = b;\n\n   while (v != 0) {\n      q = u / v;\n      r = u % v;\n      u = v;\n      v = r;\n      u0 = u2;\n      v0 = v2;\n      u2 =  u1 - q*u2;\n      v2 = v1- q*v2;\n      u1 = u0;\n      v1 = v0;\n   }\n\n   if (aneg)\n      u1 = -u1;\n\n   if (bneg)\n      v1 = -v1;\n\n   d = u;\n   s = u1;\n   t = v1;\n}\n   \nlong InvModStatus(long& x, long a, long n)\n{\n   long d, s, t;\n\n   XGCD(d, s, t, a, n);\n   if (d != 1) {\n      x = d;\n      return 1;\n   }\n   else {\n      if (s < 0)\n         x = s + n;\n      else\n         x = s;\n\n      return 0;\n   }\n}\n\nlong InvMod(long a, long n)\n{\n   long d, s, t;\n\n   XGCD(d, s, t, a, n);\n   if (d != 1) {\n      InvModError(\"InvMod: inverse undefined\");\n   }\n   if (s < 0)\n      return s + n;\n   else\n      return s;\n}\n\n\nlong PowerMod(long a, long ee, long n)\n{\n   long x, y;\n\n   unsigned long e;\n\n   if (ee < 0)\n      e = - ((unsigned long) ee);\n   else\n      e = ee;\n\n   x = 1;\n   y = a;\n   while (e) {\n      if (e & 1) x = MulMod(x, y, n);\n      y = MulMod(y, y, n);\n      e = e >> 1;\n   }\n\n   if (ee < 0) x = InvMod(x, n);\n\n   return x;\n}\n\nlong ProbPrime(long n, long NumTests)\n{\n   long m, x, y, z;\n   long i, j, k;\n\n   if (n <= 1) return 0;\n\n\n   if (n == 2) return 1;\n   if (n % 2 == 0) return 0;\n\n   if (n == 3) return 1;\n   if (n % 3 == 0) return 0;\n\n   if (n == 5) return 1;\n   if (n % 5 == 0) return 0;\n\n   if (n == 7) return 1;\n   if (n % 7 == 0) return 0;\n\n   if (n >= NTL_SP_BOUND) {\n      return ProbPrime(to_ZZ(n), NumTests);\n   }\n\n   m = n - 1;\n   k = 0;\n   while((m & 1) == 0) {\n      m = m >> 1;\n      k++;\n   }\n\n   // n - 1 == 2^k * m, m odd\n\n   for (i = 0; i < NumTests; i++) {\n      do {\n         x = RandomBnd(n);\n      } while (x == 0);\n      // x == 0 is not a useful candidtae for a witness!\n\n\n      if (x == 0) continue;\n      z = PowerMod(x, m, n);\n      if (z == 1) continue;\n   \n      j = 0;\n      do {\n         y = z;\n         z = MulMod(y, y, n);\n         j++;\n      } while (j != k && z != 1);\n\n      if (z != 1 || y !=  n-1) return 0;\n   }\n\n   return 1;\n}\n\n\nlong MillerWitness(const ZZ& n, const ZZ& x)\n{\n   ZZ m, y, z;\n   long j, k;\n\n   if (x == 0) return 0;\n\n   add(m, n, -1);\n   k = MakeOdd(m);\n   // n - 1 == 2^k * m, m odd\n\n   PowerMod(z, x, m, n);\n   if (z == 1) return 0;\n\n   j = 0;\n   do {\n      y = z;\n      SqrMod(z, y, n);\n      j++;\n   } while (j != k && z != 1);\n\n   if (z != 1) return 1;\n   add(y, y, 1);\n   if (y != n) return 1;\n   return 0;\n}\n\n\n// ComputePrimeBound computes a reasonable bound for trial\n// division in the Miller-Rabin test.\n// It is computed a bit on the \"low\" side, since being a bit\n// low doesn't hurt much, but being too high can hurt a lot.\n\nstatic\nlong ComputePrimeBound(long bn)\n{\n   long wn = (bn+NTL_ZZ_NBITS-1)/NTL_ZZ_NBITS;\n\n   long fn;\n\n   if (wn <= 36)\n      fn = wn/4 + 1;\n   else\n      fn = long(1.67*sqrt(double(wn)));\n\n   long prime_bnd;\n\n   if (NumBits(bn) + NumBits(fn) > NTL_SP_NBITS)\n      prime_bnd = NTL_SP_BOUND;\n   else\n      prime_bnd = bn*fn;\n\n   return prime_bnd;\n}\n\n\nlong ProbPrime(const ZZ& n, long NumTrials)\n{\n   if (n <= 1) return 0;\n\n   if (n.SinglePrecision()) {\n      return ProbPrime(to_long(n), NumTrials);\n   }\n\n\n   long prime_bnd = ComputePrimeBound(NumBits(n));\n\n\n   PrimeSeq s;\n   long p;\n\n   p = s.next();\n   while (p && p < prime_bnd) {\n      if (rem(n, p) == 0)\n         return 0;\n\n      p = s.next();\n   }\n\n   ZZ W;\n   W = 2;\n\n   // first try W == 2....the exponentiation\n   // algorithm runs slightly faster in this case\n\n   if (MillerWitness(n, W))\n      return 0;\n\n\n   long i;\n\n   for (i = 0; i < NumTrials; i++) {\n      do {\n         RandomBnd(W, n);\n      } while (W == 0);\n      // W == 0 is not a useful candidate for a witness!\n\n      if (MillerWitness(n, W)) \n         return 0;\n   }\n\n   return 1;\n}\n\n\nvoid RandomPrime(ZZ& n, long l, long NumTrials)\n{\n   if (l <= 1)\n      LogicError(\"RandomPrime: l out of range\");\n\n   if (l == 2) {\n      if (RandomBnd(2))\n         n = 3;\n      else\n         n = 2;\n\n      return;\n   }\n\n   do {\n      RandomLen(n, l);\n      if (!IsOdd(n)) add(n, n, 1);\n   } while (!ProbPrime(n, NumTrials));\n}\n\nvoid NextPrime(ZZ& n, const ZZ& m, long NumTrials)\n{\n   ZZ x;\n\n   if (m <= 2) {\n      n = 2;\n      return;\n   }\n\n   x = m;\n\n   while (!ProbPrime(x, NumTrials))\n      add(x, x, 1);\n\n   n = x;\n}\n\nlong NextPrime(long m, long NumTrials)\n{\n   long x;\n\n   if (m <= 2) \n      return 2;\n\n   x = m;\n\n   while (x < NTL_SP_BOUND && !ProbPrime(x, NumTrials))\n      x++;\n\n   if (x >= NTL_SP_BOUND)\n      ResourceError(\"NextPrime: no more primes\");\n\n   return x;\n}\n\n\n\nlong NextPowerOfTwo(long m)\n{\n   long k; \n   unsigned long n, um;\n\n   if (m < 0) return 0;\n\n   um = m;\n   n = 1;\n   k = 0;\n\n   while (n < um) {\n      n = n << 1;\n      k++;\n   }\n\n   if (k >= NTL_BITS_PER_LONG-1)\n      ResourceError(\"NextPowerOfTwo: overflow\");\n\n   return k;\n}\n\n\n\nlong NumBits(long a)\n{\n   unsigned long aa;\n   if (a < 0) \n      aa = - ((unsigned long) a);\n   else\n      aa = a;\n\n   long k = 0;\n   while (aa) {\n      k++;\n      aa = aa >> 1;\n   }\n\n   return k;\n}\n\n\nlong bit(long a, long k)\n{\n   unsigned long aa;\n   if (a < 0)\n      aa = - ((unsigned long) a);\n   else\n      aa = a;\n\n   if (k < 0 || k >= NTL_BITS_PER_LONG) \n      return 0;\n   else\n      return long((aa >> k) & 1);\n}\n\n\n\nlong divide(ZZ& q, const ZZ& a, const ZZ& b)\n{\n   NTL_ZZRegister(qq);\n   NTL_ZZRegister(r);\n\n   if (IsZero(b)) {\n      if (IsZero(a)) {\n         clear(q);\n         return 1;\n      }\n      else\n         return 0;\n   }\n\n\n   if (IsOne(b)) {\n      q = a;\n      return 1;\n   }\n\n   DivRem(qq, r, a, b);\n   if (!IsZero(r)) return 0;\n   q = qq;\n   return 1;\n}\n\nlong divide(const ZZ& a, const ZZ& b)\n{\n   NTL_ZZRegister(r);\n\n   if (IsZero(b)) return IsZero(a);\n   if (IsOne(b)) return 1;\n\n   rem(r, a, b);\n   return IsZero(r);\n}\n\nlong divide(ZZ& q, const ZZ& a, long b)\n{\n   NTL_ZZRegister(qq);\n\n   if (!b) {\n      if (IsZero(a)) {\n         clear(q);\n         return 1;\n      }\n      else\n         return 0;\n   }\n\n   if (b == 1) {\n      q = a;\n      return 1;\n   }\n\n   long r = DivRem(qq, a, b);\n   if (r) return 0;\n   q = qq;\n   return 1;\n}\n\nlong divide(const ZZ& a, long b)\n{\n   if (!b) return IsZero(a);\n   if (b == 1) {\n      return 1;\n   }\n\n   long r = rem(a,  b);\n   return (r == 0);\n}\n\n\nvoid InvMod(ZZ& x, const ZZ& a, const ZZ& n)\n{\n   // NOTE: the underlying LIP routines write to the first argument,\n   // even if inverse is undefined\n\n   NTL_ZZRegister(xx);\n   if (InvModStatus(xx, a, n)) \n      InvModError(\"InvMod: inverse undefined\", a, n);\n   x = xx;\n}\n\nvoid PowerMod(ZZ& x, const ZZ& a, const ZZ& e, const ZZ& n)\n{\n   // NOTE: this ensures that all modular inverses are computed\n   // in the routine InvMod above, rather than the LIP-internal\n   // modular inverse routine\n   if (e < 0) {\n      ZZ a_inv;\n      ZZ e_neg;\n\n      InvMod(a_inv, a, n);\n      negate(e_neg, e);\n      LowLevelPowerMod(x, a_inv, e_neg, n);\n   }\n   else\n      LowLevelPowerMod(x, a, e, n); \n}\n   \n#ifdef NTL_EXCEPTIONS\n\nvoid InvModError(const char *s, const ZZ& a, const ZZ& n)\n{\n   throw InvModErrorObject(s, a, n); \n}\n\n#else\n\nvoid InvModError(const char *s, const ZZ& a, const ZZ& n)\n{\n   TerminalError(s);\n}\n\n\n#endif\n\nlong RandomPrime_long(long l, long NumTrials)\n{\n   if (l <= 1 || l >= NTL_BITS_PER_LONG)\n      ResourceError(\"RandomPrime: length out of range\");\n\n   long n;\n   do {\n      n = RandomLen_long(l);\n   } while (!ProbPrime(n, NumTrials));\n\n   return n;\n}\n\n\nstatic Lazy< Vec<char> > lowsieve_storage;\n// This is a GLOBAL VARIABLE\n\n\nPrimeSeq::PrimeSeq()\n{\n   movesieve = 0;\n   pshift = -1;\n   pindex = -1;\n   exhausted = 0;\n}\n\n\nlong PrimeSeq::next()\n{\n   if (exhausted) {\n      return 0;\n   }\n\n   if (pshift < 0) {\n      shift(0);\n      return 2;\n   }\n\n   for (;;) {\n      const char *p = movesieve;\n      long i = pindex;\n\n      while ((++i) < NTL_PRIME_BND) {\n         if (p[i]) {\n            pindex = i;\n            return pshift + 2 * i + 3;\n         }\n      }\n\n      long newshift = pshift + 2*NTL_PRIME_BND;\n\n      if (newshift > 2 * NTL_PRIME_BND * (2 * NTL_PRIME_BND + 1)) {\n         /* end of the road */\n         exhausted = 1;\n         return 0;\n      }\n\n      shift(newshift);\n   }\n}\n\nvoid PrimeSeq::shift(long newshift)\n{\n   long i;\n   long j;\n   long jstep;\n   long jstart;\n   long ibound;\n   char *p;\n\n   if (!lowsieve_storage.built())\n      start();\n\n   const char *lowsieve = lowsieve_storage->elts();\n\n\n   if (newshift < 0) {\n      pshift = -1;\n   }\n   else if (newshift == 0) {\n      pshift = 0;\n      movesieve = lowsieve;\n   } \n   else if (newshift != pshift) {\n      if (movesieve_mem.length() == 0) {\n         movesieve_mem.SetLength(NTL_PRIME_BND);\n      }\n\n      pshift = newshift;\n      movesieve = p = movesieve_mem.elts();\n      for (i = 0; i < NTL_PRIME_BND; i++)\n         p[i] = 1;\n\n      jstep = 3;\n      ibound = pshift + 2 * NTL_PRIME_BND + 1;\n      for (i = 0; jstep * jstep <= ibound; i++) {\n         if (lowsieve[i]) {\n            if (!((jstart = (pshift + 2) / jstep + 1) & 1))\n               jstart++;\n            if (jstart <= jstep)\n               jstart = jstep;\n            jstart = (jstart * jstep - pshift - 3) / 2;\n            for (j = jstart; j < NTL_PRIME_BND; j += jstep)\n               p[j] = 0;\n         }\n         jstep += 2;\n      }\n   }\n\n   pindex = -1;\n   exhausted = 0;\n}\n\n\nvoid PrimeSeq::start()\n{\n   long i;\n   long j;\n   long jstep;\n   long jstart;\n   long ibnd;\n   char *p;\n\n   do {\n      Lazy< Vec<char> >::Builder builder(lowsieve_storage);\n      if (!builder()) break;\n\n      UniquePtr< Vec<char> > ptr;\n      ptr.make();\n      ptr->SetLength(NTL_PRIME_BND);\n\n      p = ptr->elts();\n\n      for (i = 0; i < NTL_PRIME_BND; i++)\n         p[i] = 1;\n         \n      jstep = 1;\n      jstart = -1;\n      ibnd = (SqrRoot(2 * NTL_PRIME_BND + 1) - 3) / 2;\n      for (i = 0; i <= ibnd; i++) {\n         jstart += 2 * ((jstep += 2) - 1);\n         if (p[i])\n            for (j = jstart; j < NTL_PRIME_BND; j += jstep)\n               p[j] = 0;\n      }\n\n      builder.move(ptr);\n   } while (0);\n\n}\n\nvoid PrimeSeq::reset(long b)\n{\n   if (b > (2*NTL_PRIME_BND+1)*(2*NTL_PRIME_BND+1)) {\n      exhausted = 1;\n      return;\n   }\n\n   if (b <= 2) {\n      shift(-1);\n      return;\n   }\n\n   if ((b & 1) == 0) b++;\n\n   shift(((b-3) / (2*NTL_PRIME_BND))* (2*NTL_PRIME_BND));\n   pindex = (b - pshift - 3)/2 - 1;\n}\n \nlong Jacobi(const ZZ& aa, const ZZ& nn)\n{\n   ZZ a, n;\n   long t, k;\n   long d;\n\n   a = aa;\n   n = nn;\n   t = 1;\n\n   while (a != 0) {\n      k = MakeOdd(a);\n      d = trunc_long(n, 3);\n      if ((k & 1) && (d == 3 || d == 5)) t = -t;\n\n      if (trunc_long(a, 2) == 3 && (d & 3) == 3) t = -t;\n      swap(a, n);\n      rem(a, a, n);\n   }\n\n   if (n == 1)\n      return t;\n   else\n      return 0;\n}\n\n\nvoid SqrRootMod(ZZ& x, const ZZ& aa, const ZZ& nn)\n{\n   if (aa == 0 || aa == 1) {\n      x = aa;\n      return;\n   }\n\n   // at this point, we must have nn >= 5\n\n   if (trunc_long(nn, 2) == 3) {  // special case, n = 3 (mod 4)\n      ZZ n, a, e, z;\n\n      n = nn;\n      a  = aa;\n\n      add(e, n, 1);\n      RightShift(e, e, 2);\n\n      PowerMod(z, a, e, n);\n      x = z;\n\n      return;\n   }\n\n   ZZ n, m;\n   int h, nlen;\n\n   n = nn;\n   nlen = NumBits(n);\n\n   sub(m, n, 1);\n   h = MakeOdd(m);  // h >= 2\n\n\n   if (nlen > 50 && h < SqrRoot(nlen)) {\n      long i, j;\n      ZZ a, b, a_inv, c, r, m1, d;\n\n      a = aa;\n      InvMod(a_inv, a, n);\n\n      if (h == 2) \n         b = 2;\n      else {\n         do {\n            RandomBnd(b, n);\n         } while (Jacobi(b, n) != -1);\n      }\n\n\n      PowerMod(c, b, m, n);\n      \n      add(m1, m, 1);\n      RightShift(m1, m1, 1);\n      PowerMod(r, a, m1, n);\n\n      for (i = h-2; i >= 0; i--) {\n         SqrMod(d, r, n);\n         MulMod(d, d, a_inv, n);\n         for (j = 0; j < i; j++)\n            SqrMod(d, d, n);\n         if (!IsOne(d))\n            MulMod(r, r, c, n);\n         SqrMod(c, c, n);\n      } \n\n      x = r;\n      return;\n   } \n\n\n\n\n\n   long i, k;\n   ZZ ma, t, u, v, e;\n   ZZ t1, t2, t3, t4;\n\n   n = nn;\n   NegateMod(ma, aa, n);\n\n   // find t such that t^2 - 4*a is not a square\n\n   MulMod(t1, ma, 4, n);\n   do {\n      RandomBnd(t, n);\n      SqrMod(t2, t, n);\n      AddMod(t2, t2, t1, n);\n   } while (Jacobi(t2, n) != -1);\n\n   // compute u*X + v = X^{(n+1)/2} mod f, where f = X^2 - t*X + a\n\n   add(e, n, 1);\n   RightShift(e, e, 1);\n\n   u = 0;\n   v = 1;\n\n   k = NumBits(e);\n\n   for (i = k - 1; i >= 0; i--) {\n      add(t2, u, v);\n      sqr(t3, t2);  // t3 = (u+v)^2\n      sqr(t1, u);\n      sqr(t2, v);\n      sub(t3, t3, t1);\n      sub(t3, t3, t2); // t1 = u^2, t2 = v^2, t3 = 2*u*v\n      rem(t1, t1, n);\n      mul(t4, t1, t);\n      add(t4, t4, t3);\n      rem(u, t4, n);\n\n      mul(t4, t1, ma);\n      add(t4, t4, t2);\n      rem(v, t4, n);\n      \n      if (bit(e, i)) {\n         MulMod(t1, u, t, n);\n         AddMod(t1, t1, v, n);\n         MulMod(v, u, ma, n);\n         u = t1;\n      }\n\n   }\n\n   x = v;\n}\n\n\n\n// Chinese Remaindering.\n//\n// This version in new to v3.7, and is significantly\n// simpler and faster than the previous version.\n//\n// This function takes as input g, a, G, p,\n// such that a > 0, 0 <= G < p, and gcd(a, p) = 1.\n// It computes a' = a*p and g' such that \n//   * g' = g (mod a);\n//   * g' = G (mod p);\n//   * -a'/2 < g' <= a'/2.\n// It then sets g := g' and a := a', and returns 1 iff g has changed.\n//\n// Under normal use, the input value g satisfies -a/2 < g <= a/2;\n// however, this was not documented or enforced in earlier versions,\n// so to maintain backward compatability, no restrictions are placed\n// on g.  This routine runs faster, though, if -a/2 < g <= a/2,\n// and the first thing the routine does is to make this condition\n// hold.\n//\n// Also, under normal use, both a and p are odd;  however, the routine\n// will still work even if this is not so.\n//\n// The routine is based on the following simple fact.\n//\n// Let -a/2 < g <= a/2, and let h satisfy\n//   * g + a h = G (mod p);\n//   * -p/2 < h <= p/2.\n// Further, if p = 2*h and g > 0, set\n//   g' := g - a h;\n// otherwise, set\n//   g' := g + a h.\n// Then g' so defined satisfies the above requirements.\n//\n// It is trivial to see that g's satisfies the congruence conditions.\n// The only thing is to check that the \"balancing\" condition\n// -a'/2 < g' <= a'/2 also holds.\n\n\nlong CRT(ZZ& gg, ZZ& a, long G, long p)\n{\n   if (p >= NTL_SP_BOUND) {\n      ZZ GG, pp;\n      conv(GG, G);\n      conv(pp, p);\n      return CRT(gg, a, GG, pp);\n   }\n\n   long modified = 0;\n\n   NTL_ZZRegister(g);\n\n   if (!CRTInRange(gg, a)) {\n      modified = 1;\n      ZZ a1;\n      rem(g, gg, a);\n      RightShift(a1, a, 1);\n      if (g > a1) sub(g, g, a);\n   }\n   else\n      g = gg;\n\n\n   long p1;\n   p1 = p >> 1;\n\n   long a_inv;\n   a_inv = rem(a, p);\n   a_inv = InvMod(a_inv, p);\n\n   long h;\n   h = rem(g, p);\n   h = SubMod(G, h, p);\n   h = MulMod(h, a_inv, p);\n   if (h > p1)\n      h = h - p;\n\n   if (h != 0) {\n      modified = 1;\n\n      if (!(p & 1) && g > 0 && (h == p1))\n         MulSubFrom(g, a, h);\n      else\n         MulAddTo(g, a, h);\n   }\n\n   mul(a, a, p);\n   gg = g;\n\n   return modified;\n}\n\nlong CRT(ZZ& gg, ZZ& a, const ZZ& G, const ZZ& p)\n{\n   long modified = 0;\n\n   ZZ g;\n\n   if (!CRTInRange(gg, a)) {\n      modified = 1;\n      ZZ a1;\n      rem(g, gg, a);\n      RightShift(a1, a, 1);\n      if (g > a1) sub(g, g, a);\n   }\n   else\n      g = gg;\n\n\n   ZZ p1;\n   RightShift(p1, p, 1);\n\n   ZZ a_inv;\n   rem(a_inv, a, p);\n   InvMod(a_inv, a_inv, p);\n\n   ZZ h;\n   rem(h, g, p);\n   SubMod(h, G, h, p);\n   MulMod(h, h, a_inv, p);\n   if (h > p1)\n      sub(h, h, p);\n\n   if (h != 0) {\n      modified = 1;\n      ZZ ah;\n      mul(ah, a, h);\n\n      if (!IsOdd(p) && g > 0 &&  (h == p1))\n         sub(g, g, ah);\n      else\n         add(g, g, ah);\n   }\n\n   mul(a, a, p);\n   gg = g;\n\n   return modified;\n}\n\n\n\nvoid sub(ZZ& x, const ZZ& a, long b)\n{\n   NTL_ZZRegister(B);\n   conv(B, b);\n   sub(x, a, B);\n}\n\nvoid sub(ZZ& x, long a, const ZZ& b)\n{\n   NTL_ZZRegister(A);\n   conv(A, a);\n   sub(x, A, b);\n}\n\n\nvoid power2(ZZ& x, long e)\n{\n   if (e < 0) ArithmeticError(\"power2: negative exponent\");\n   set(x);\n   LeftShift(x, x, e);\n}\n\n   \nvoid conv(ZZ& x, const char *s)\n{\n   long c;\n   long cval;\n   long sign;\n   long ndigits;\n   long acc;\n   long i = 0;\n\n   NTL_ZZRegister(a);\n\n   if (!s) InputError(\"bad ZZ input\");\n\n   if (!iodigits) InitZZIO();\n\n   a = 0;\n\n   c = s[i];\n   while (IsWhiteSpace(c)) {\n      i++;\n      c = s[i];\n   }\n\n   if (c == '-') {\n      sign = -1;\n      i++;\n      c = s[i];\n   }\n   else\n      sign = 1;\n\n   cval = CharToIntVal(c);\n   if (cval < 0 || cval > 9) InputError(\"bad ZZ input\");\n\n   ndigits = 0;\n   acc = 0;\n   while (cval >= 0 && cval <= 9) {\n      acc = acc*10 + cval;\n      ndigits++;\n\n      if (ndigits == iodigits) {\n         mul(a, a, ioradix);\n         add(a, a, acc);\n         ndigits = 0;\n         acc = 0;\n      }\n\n      i++;\n      c = s[i];\n      cval = CharToIntVal(c);\n   }\n\n   if (ndigits != 0) {\n      long mpy = 1;\n      while (ndigits > 0) {\n         mpy = mpy * 10;\n         ndigits--;\n      }\n\n      mul(a, a, mpy);\n      add(a, a, acc);\n   }\n\n   if (sign == -1)\n      negate(a, a);\n\n   x = a;\n}\n\n\n\nvoid bit_and(ZZ& x, const ZZ& a, long b)\n{\n   NTL_ZZRegister(B);\n   conv(B, b);\n   bit_and(x, a, B);\n}\n\nvoid bit_or(ZZ& x, const ZZ& a, long b)\n{\n   NTL_ZZRegister(B);\n   conv(B, b);\n   bit_or(x, a, B);\n}\n\nvoid bit_xor(ZZ& x, const ZZ& a, long b)\n{\n   NTL_ZZRegister(B);\n   conv(B, b);\n   bit_xor(x, a, B);\n}\n\n\nlong power_long(long a, long e)\n{\n   if (e < 0) ArithmeticError(\"power_long: negative exponent\");\n\n   if (e == 0) return 1;\n\n   if (a == 1) return 1;\n   if (a == -1) {\n      if (e & 1)\n         return -1;\n      else\n         return 1;\n   }\n\n   // no overflow check --- result is computed correctly\n   // modulo word size\n\n   unsigned long res = 1;\n   unsigned long aa = a;\n   long i;\n\n   for (i = 0; i < e; i++)\n      res *= aa;\n\n   return to_long(res);\n}\n\n\n\n// ======================= new PRG stuff ======================\n\n\n\n\n#if (NTL_BITS_PER_INT32 == 32)\n#define INT32MASK(x) (x)\n#else\n#define INT32MASK(x) ((x) & _ntl_uint32(0xffffffff))\n#endif\n\n\n\n// SHA256 code adapted from an implementauin by Brad Conte.\n// The following is from his original source files.\n/*********************************************************************\n* Filename:   sha256.c\n* Author:     Brad Conte (brad AT bradconte.com)\n* Copyright:\n* Disclaimer: This code is presented \"as is\" without any guarantees.\n* Details:    Implementation of the SHA-256 hashing algorithm.\n              SHA-256 is one of the three algorithms in the SHA2\n              specification. The others, SHA-384 and SHA-512, are not\n              offered in this implementation.\n              Algorithm specification can be found here:\n               * http://csrc.nist.gov/publications/fips/fips180-2/fips180-2withchangenotice.pdf\n              This implementation uses little endian byte order.\n*********************************************************************/\n\n// And the following is from the description at \n// https://github.com/B-Con/crypto-algorithms\n\n/*********************************************************************\n\nThese are basic implementations of standard cryptography algorithms, written by\nBrad Conte (brad@bradconte.com) from scratch and without any cross-licensing.\nThey exist to provide publically accessible, restriction-free implementations\nof popular cryptographic algorithms, like AES and SHA-1. These are primarily\nintended for educational and pragmatic purposes (such as comparing a\nspecification to actual implementation code, or for building an internal\napplication that computes test vectors for a product). The algorithms have been\ntested against standard test vectors.\n\nThis code is released into the public domain free of any restrictions. The\nauthor requests acknowledgement if the code is used, but does not require it.\nThis code is provided free of any liability and without any quality claims by\nthe author.\n\nNote that these are not cryptographically secure implementations. They have no\nresistence to side-channel attacks and should not be used in contexts that need\ncryptographically secure implementations.\n\nThese algorithms are not optimized for speed or space. They are primarily\ndesigned to be easy to read, although some basic optimization techniques have\nbeen employed.\n\n*********************************************************************/\n\n\n\n\n\n\n#define SHA256_BLOCKSIZE (64)\n#define SHA256_HASHSIZE  (32)\n\n// DBL_INT_ADD treats two unsigned ints a and b as one 64-bit integer and adds c to it\nstatic inline\nvoid DBL_INT_ADD(_ntl_uint32& a, _ntl_uint32& b, _ntl_uint32 c)\n{\n   _ntl_uint32 aa = INT32MASK(a);\n   if (aa > INT32MASK(_ntl_uint32(0xffffffff) - c)) b++;\n   a = aa + c;\n}\n\n#define ROTLEFT(a,b) (((a) << (b)) | (INT32MASK(a) >> (32-(b))))\n#define ROTRIGHT(a,b) ((INT32MASK(a) >> (b)) | ((a) << (32-(b))))\n\n#define CH(x,y,z) (((x) & (y)) ^ (~(x) & (z)))\n#define MAJ(x,y,z) (((x) & (y)) ^ ((x) & (z)) ^ ((y) & (z)))\n#define EP0(x) (ROTRIGHT(x,2) ^ ROTRIGHT(x,13) ^ ROTRIGHT(x,22))\n#define EP1(x) (ROTRIGHT(x,6) ^ ROTRIGHT(x,11) ^ ROTRIGHT(x,25))\n#define SIG0(x) (ROTRIGHT(x,7) ^ ROTRIGHT(x,18) ^ (INT32MASK(x) >> 3))\n#define SIG1(x) (ROTRIGHT(x,17) ^ ROTRIGHT(x,19) ^ (INT32MASK(x) >> 10))\n\nstruct SHA256_CTX {\n   unsigned char data[64];\n   _ntl_uint32 datalen;\n   _ntl_uint32 bitlen[2];\n   _ntl_uint32 state[8];\n};\n\nstatic const _ntl_uint32 sha256_const[64] = {\n   0x428a2f98,0x71374491,0xb5c0fbcf,0xe9b5dba5,0x3956c25b,0x59f111f1,0x923f82a4,0xab1c5ed5,\n   0xd807aa98,0x12835b01,0x243185be,0x550c7dc3,0x72be5d74,0x80deb1fe,0x9bdc06a7,0xc19bf174,\n   0xe49b69c1,0xefbe4786,0x0fc19dc6,0x240ca1cc,0x2de92c6f,0x4a7484aa,0x5cb0a9dc,0x76f988da,\n   0x983e5152,0xa831c66d,0xb00327c8,0xbf597fc7,0xc6e00bf3,0xd5a79147,0x06ca6351,0x14292967,\n   0x27b70a85,0x2e1b2138,0x4d2c6dfc,0x53380d13,0x650a7354,0x766a0abb,0x81c2c92e,0x92722c85,\n   0xa2bfe8a1,0xa81a664b,0xc24b8b70,0xc76c51a3,0xd192e819,0xd6990624,0xf40e3585,0x106aa070,\n   0x19a4c116,0x1e376c08,0x2748774c,0x34b0bcb5,0x391c0cb3,0x4ed8aa4a,0x5b9cca4f,0x682e6ff3,\n   0x748f82ee,0x78a5636f,0x84c87814,0x8cc70208,0x90befffa,0xa4506ceb,0xbef9a3f7,0xc67178f2\n};\n\n\nstatic\nvoid sha256_transform(SHA256_CTX& ctx, unsigned char *data)\n{  \n   _ntl_uint32 a,b,c,d,e,f,g,h,i,j,t1,t2,m[64];\n      \n   for (i=0,j=0; i < 16; ++i, j += 4)\n      m[i] = (data[j] << 24) | (data[j+1] << 16) | (data[j+2] << 8) | (data[j+3]);\n   for ( ; i < 64; ++i)\n      m[i] = SIG1(m[i-2]) + m[i-7] + SIG0(m[i-15]) + m[i-16];\n\n   a = ctx.state[0];\n   b = ctx.state[1];\n   c = ctx.state[2];\n   d = ctx.state[3];\n   e = ctx.state[4];\n   f = ctx.state[5];\n   g = ctx.state[6];\n   h = ctx.state[7];\n   \n   for (i = 0; i < 64; ++i) {\n      t1 = h + EP1(e) + CH(e,f,g) + sha256_const[i] + m[i];\n      t2 = EP0(a) + MAJ(a,b,c);\n      h = g;\n      g = f;\n      f = e;\n      e = d + t1;\n      d = c;\n      c = b;\n      b = a;\n      a = t1 + t2;\n   }\n   \n   ctx.state[0] += a;\n   ctx.state[1] += b;\n   ctx.state[2] += c;\n   ctx.state[3] += d;\n   ctx.state[4] += e;\n   ctx.state[5] += f;\n   ctx.state[6] += g;\n   ctx.state[7] += h;\n}  \n\nstatic\nvoid sha256_init(SHA256_CTX& ctx)\n{  \n   ctx.datalen = 0; \n   ctx.bitlen[0] = 0; \n   ctx.bitlen[1] = 0; \n   ctx.state[0] = 0x6a09e667;\n   ctx.state[1] = 0xbb67ae85;\n   ctx.state[2] = 0x3c6ef372;\n   ctx.state[3] = 0xa54ff53a;\n   ctx.state[4] = 0x510e527f;\n   ctx.state[5] = 0x9b05688c;\n   ctx.state[6] = 0x1f83d9ab;\n   ctx.state[7] = 0x5be0cd19;\n}\n\nstatic\nvoid sha256_update(SHA256_CTX& ctx, const unsigned char *data, _ntl_uint32 len)\n{  \n   _ntl_uint32 i;\n   \n   for (i=0; i < len; ++i) { \n      ctx.data[ctx.datalen] = data[i]; \n      ctx.datalen++; \n      if (ctx.datalen == 64) { \n         sha256_transform(ctx,ctx.data);\n         DBL_INT_ADD(ctx.bitlen[0],ctx.bitlen[1],512); \n         ctx.datalen = 0; \n      }  \n   }  \n}  \n\nstatic\nvoid sha256_final(SHA256_CTX& ctx, unsigned char *hash, \n                  long hlen=SHA256_HASHSIZE)\n{  \n   _ntl_uint32 i, j; \n   \n   i = ctx.datalen; \n   \n   // Pad whatever data is left in the buffer. \n   if (ctx.datalen < 56) { \n      ctx.data[i++] = 0x80; \n      while (i < 56) \n         ctx.data[i++] = 0x00; \n   }  \n   else { \n      ctx.data[i++] = 0x80; \n      while (i < 64) \n         ctx.data[i++] = 0x00; \n      sha256_transform(ctx,ctx.data);\n      memset(ctx.data,0,56); \n   }  \n   \n   // Append to the padding the total message's length in bits and transform. \n   DBL_INT_ADD(ctx.bitlen[0],ctx.bitlen[1],ctx.datalen * 8);\n\n   ctx.data[63] = ctx.bitlen[0]; \n   ctx.data[62] = ctx.bitlen[0] >> 8; \n   ctx.data[61] = ctx.bitlen[0] >> 16; \n   ctx.data[60] = ctx.bitlen[0] >> 24; \n   ctx.data[59] = ctx.bitlen[1]; \n   ctx.data[58] = ctx.bitlen[1] >> 8; \n   ctx.data[57] = ctx.bitlen[1] >> 16;  \n   ctx.data[56] = ctx.bitlen[1] >> 24; \n   sha256_transform(ctx,ctx.data);\n   \n   for (i = 0; i < 8; i++) {\n      _ntl_uint32 w = ctx.state[i];\n      for (j = 0; j < 4; j++) {\n         if (hlen <= 0) break;\n         hash[4*i + j] = w >> (24-j*8); \n         hlen--;\n      }\n   }\n\n}  \n\n\n\nstatic\nvoid sha256(const unsigned char *data, long dlen, unsigned char *hash, \n            long hlen=SHA256_HASHSIZE)\n{\n   if (dlen < 0) dlen = 0;\n   if (hlen < 0) hlen = 0;\n\n   SHA256_CTX ctx;\n   sha256_init(ctx);\n\n   const long BLKSIZE = 4096;\n\n   long i;\n   for (i = 0; i <= dlen-BLKSIZE; i += BLKSIZE) \n      sha256_update(ctx, data + i, BLKSIZE);\n\n   if (i < dlen)\n      sha256_update(ctx, data + i, dlen - i);\n\n   sha256_final(ctx, hash, hlen);\n}\n\n\nstatic\nvoid hmac_sha256(const unsigned char *key, long klen, \n                 const unsigned char *data, long dlen,\n                 unsigned char *hash, long hlen=SHA256_HASHSIZE)\n{\n   if (klen < 0) klen = 0;\n   if (dlen < 0) dlen = 0;\n   if (hlen < 0) hlen = 0;\n\n   unsigned char K[SHA256_BLOCKSIZE];\n   unsigned char tmp[SHA256_HASHSIZE];\n\n   long i;\n\n   if (klen <= SHA256_BLOCKSIZE) {\n      for (i = 0; i < klen; i++)\n         K[i] = key[i];\n      for (i = klen; i < SHA256_BLOCKSIZE; i++) \n         K[i] = 0;\n   }\n   else {\n      sha256(key, klen, K, SHA256_BLOCKSIZE); \n      for (i = SHA256_HASHSIZE; i < SHA256_BLOCKSIZE; i++)\n         K[i] = 0;\n   }\n\n   for (i = 0; i < SHA256_BLOCKSIZE; i++)\n      K[i] ^= 0x36;\n\n   SHA256_CTX ctx;\n   sha256_init(ctx);\n   sha256_update(ctx, K, SHA256_BLOCKSIZE);\n   sha256_update(ctx, data, dlen);\n   sha256_final(ctx, tmp);\n\n   for (i = 0; i < SHA256_BLOCKSIZE; i++)\n      K[i] ^= (0x36 ^ 0x5C);\n\n   sha256_init(ctx);\n   sha256_update(ctx, K, SHA256_BLOCKSIZE);\n   sha256_update(ctx, tmp, SHA256_HASHSIZE);\n   sha256_final(ctx, hash, hlen);\n}\n\n\n// This key derivation uses HMAC with a zero key to derive\n// an intermediate key K from the data, and then uses HMAC\n// as a PRF in counter mode with key K to derive the final key\n\nvoid DeriveKey(unsigned char *key, long klen,  \n               const unsigned char *data, long dlen)\n{\n   if (dlen < 0) LogicError(\"DeriveKey: bad args\");\n   if (klen < 0) LogicError(\"DeriveKey: bad args\");\n\n   long i, j;\n\n\n   unsigned char K[SHA256_HASHSIZE];\n   hmac_sha256(0, 0, data, dlen, K); \n\n   // initialize 64-bit counter to zero\n   unsigned char counter[8];\n   for (j = 0; j < 8; j++) counter[j] = 0;\n\n   for (i = 0; i <= klen-SHA256_HASHSIZE; i += SHA256_HASHSIZE) {\n      hmac_sha256(K, SHA256_HASHSIZE, counter, 8, key+i); \n\n      // increment counter\n      for (j = 0; j < 8; j++) {\n         counter[j]++;\n         if (counter[j] != 0) break; \n      }\n   }\n\n   if (i < klen) \n      hmac_sha256(K, SHA256_HASHSIZE, counter, 8, key+i, klen-i);\n}\n\n\n\n\n// ******************** ChaCha20 stuff ***********************\n\nstatic const _ntl_uint32 chacha_const[4] = \n   { 0x61707865, 0x3320646e, 0x79622d32, 0x6b206574 };\n\n\n#define LE(p) (((_ntl_uint32)((p)[0])) + ((_ntl_uint32)((p)[1]) << 8) + \\\n    ((_ntl_uint32)((p)[2]) << 16) + ((_ntl_uint32)((p)[3]) << 24))\n\n#define FROMLE(p, x) (p)[0] = (x), (p)[1] = ((x) >> 8), \\\n   (p)[2] = ((x) >> 16), (p)[3] = ((x) >> 24)\n\n\n#define QUARTERROUND(x, a, b, c, d) \\\n    x[a] += x[b], x[d] = ROTLEFT(x[d] ^ x[a], 16), \\\n    x[c] += x[d], x[b] = ROTLEFT(x[b] ^ x[c], 12), \\\n    x[a] += x[b], x[d] = ROTLEFT(x[d] ^ x[a], 8), \\\n    x[c] += x[d], x[b] = ROTLEFT(x[b] ^ x[c], 7)\n\n\nstatic\nvoid salsa20_core(_ntl_uint32* data)\n{\n   long i;\n\n   for (i = 0; i < 10; i++) {\n      QUARTERROUND(data, 0, 4, 8, 12);\n      QUARTERROUND(data, 1, 5, 9, 13);\n      QUARTERROUND(data, 2, 6, 10, 14);\n      QUARTERROUND(data, 3, 7, 11, 15);\n      QUARTERROUND(data, 0, 5, 10, 15);\n      QUARTERROUND(data, 1, 6, 11, 12);\n      QUARTERROUND(data, 2, 7, 8, 13);\n      QUARTERROUND(data, 3, 4, 9, 14);\n   }\n}\n\n\n// key K must be exactly 32 bytes\nstatic\nvoid salsa20_init(_ntl_uint32 *state, const unsigned char *K)  \n{\n   long i;\n\n   for (i = 0; i < 4; i++)\n      state[i] = chacha_const[i];\n\n   for (i = 4; i < 12; i++)\n      state[i] = LE(K + 4*(i-4));\n\n   for (i = 12; i < 16; i++)\n      state[i] = 0;\n}\n\n\n\n// state and data are of length 16\nstatic\nvoid salsa20_apply(_ntl_uint32 *state, _ntl_uint32 *data)\n{\n   long i;\n\n   for (i = 0; i < 16; i++) data[i] = state[i];\n\n   salsa20_core(data);\n\n   for (i = 0; i < 16; i++) data[i] += state[i];\n\n   for (i = 12; i < 16; i++) {\n      state[i]++;\n      state[i] = INT32MASK(state[i]);\n      if (state[i] != 0) break;\n   }\n}\n\n\n#if 0\n// state is 16 words, data is 64 bytes\nstatic\nvoid salsa20_apply(_ntl_uint32 *state, unsigned char *data)\n{\n   _ntl_uint32 wdata[16];\n   salsa20_apply(state, wdata);\n\n   long i;\n   for (i = 0; i < 16; i++)\n      FROMLE(data + 4*i, wdata[i]);\n\n   // FIXME: could use memcpy for above if everything \n   // is right\n}\n#endif\n\n\n\nRandomStream::RandomStream(const unsigned char *key)\n{\n   salsa20_init(state, key);\n   pos = 64;\n}\n\n\nvoid RandomStream::do_get(unsigned char *NTL_RESTRICT res, long n)\n{\n   if (n < 0) LogicError(\"RandomStream::get: bad args\");\n\n   long i, j;\n\n   if (n <= 64-pos) {\n      for (i = 0; i < n; i++) res[i] = buf[pos+i];\n      pos += n;\n      return;\n   }\n\n   // read remainder of buffer\n   for (i = 0; i < 64-pos; i++) res[i] = buf[pos+i];\n   n -= 64-pos;\n   res += 64-pos;\n   pos = 64;\n\n   _ntl_uint32 wdata[16];\n\n   // read 64-byte chunks\n   for (i = 0; i <= n-64; i += 64) {\n      salsa20_apply(state, wdata);\n      for (j = 0; j < 16; j++)\n         FROMLE(res + i + 4*j, wdata[j]);\n   }\n\n   if (i < n) { \n      salsa20_apply(state, wdata);\n\n      for (j = 0; j < 16; j++)\n         FROMLE(buf + 4*j, wdata[j]);\n\n      pos = n-i;\n      for (j = 0; j < pos; j++)\n         res[i+j] = buf[j];\n   }\n}\n\n\nNTL_TLS_GLOBAL_DECL(UniquePtr<RandomStream>,  CurrentRandomStream);\n\n\nvoid SetSeed(const RandomStream& s)\n{\n   NTL_TLS_GLOBAL_ACCESS(CurrentRandomStream);\n\n   if (!CurrentRandomStream)\n      CurrentRandomStream.make(s);\n   else\n      *CurrentRandomStream = s;\n}\n\n\nvoid SetSeed(const unsigned char *data, long dlen)\n{\n   if (dlen < 0) LogicError(\"SetSeed: bad args\");\n\n   Vec<unsigned char> key;\n   key.SetLength(NTL_PRG_KEYLEN);\n   DeriveKey(key.elts(), NTL_PRG_KEYLEN, data, dlen);\n \n   SetSeed(RandomStream(key.elts()));\n}\n\nvoid SetSeed(const ZZ& seed)\n{\n   long nb = NumBytes(seed);\n\n   Vec<unsigned char> buf;\n   buf.SetLength(nb);\n\n   BytesFromZZ(buf.elts(), seed, nb);\n\n   SetSeed(buf.elts(), nb);\n}\n\n\nstatic\nvoid InitRandomStream()\n{\n   const string& id = UniqueID();\n   SetSeed((const unsigned char *) id.c_str(), id.length());\n}\n\nstatic inline\nRandomStream& LocalGetCurrentRandomStream()\n{\n   NTL_TLS_GLOBAL_ACCESS(CurrentRandomStream);\n\n   if (!CurrentRandomStream) InitRandomStream();\n   return *CurrentRandomStream;\n}\n\nRandomStream& GetCurrentRandomStream()\n{\n   return LocalGetCurrentRandomStream();\n}\n\n\n\n\n\n\n\nstatic inline\nunsigned long WordFromBytes(const unsigned char *buf, long n)\n{\n   unsigned long res = 0;\n   long i;\n\n   for (i = n-1; i >= 0; i--)\n      res = (res << 8) | buf[i];\n\n   return res;\n}\n\n\nunsigned long RandomWord()\n{\n   RandomStream& stream = LocalGetCurrentRandomStream();\n   unsigned char buf[NTL_BITS_PER_LONG/8];\n\n   stream.get(buf, NTL_BITS_PER_LONG/8);\n   return WordFromBytes(buf, NTL_BITS_PER_LONG/8);\n}\n\nlong RandomBits_long(long l)\n{\n   if (l <= 0) return 0;\n   if (l >= NTL_BITS_PER_LONG) \n      ResourceError(\"RandomBits: length too big\");\n\n   RandomStream& stream = LocalGetCurrentRandomStream();\n   unsigned char buf[NTL_BITS_PER_LONG/8];\n   long nb = (l+7)/8;\n   stream.get(buf, nb);\n\n   return long(WordFromBytes(buf, nb) & ((1UL << l)-1UL)); \n}\n\nunsigned long RandomBits_ulong(long l)\n{\n   if (l <= 0) return 0;\n   if (l > NTL_BITS_PER_LONG) \n      ResourceError(\"RandomBits: length too big\");\n\n   RandomStream& stream = LocalGetCurrentRandomStream();\n   unsigned char buf[NTL_BITS_PER_LONG/8];\n   long nb = (l+7)/8;\n   stream.get(buf, nb);\n   unsigned long res = WordFromBytes(buf, nb);\n   if (l < NTL_BITS_PER_LONG)\n      res = res & ((1UL << l)-1UL);\n   return res;\n}\n\nlong RandomLen_long(long l)\n{\n   if (l <= 0) return 0;\n   if (l == 1) return 1;\n   if (l >= NTL_BITS_PER_LONG) \n      ResourceError(\"RandomLen: length too big\");\n\n   RandomStream& stream = LocalGetCurrentRandomStream();\n   unsigned char buf[NTL_BITS_PER_LONG/8];\n   long nb = ((l-1)+7)/8;\n   stream.get(buf, nb);\n   unsigned long res = WordFromBytes(buf, nb);\n   unsigned long mask = (1UL << (l-1)) - 1UL;\n   return long((res & mask) | (mask+1UL)); \n}\n\n\nlong RandomBnd(long bnd)\n{\n   if (bnd <= 1) return 0;\n\n   RandomStream& stream = LocalGetCurrentRandomStream();\n   unsigned char buf[NTL_BITS_PER_LONG/8];\n   long l = NumBits(bnd-1);\n   long nb = (l+7)/8;\n\n   long tmp;\n   do {\n      stream.get(buf, nb);\n      tmp = long(WordFromBytes(buf, nb) & ((1UL << l)-1UL));\n   } while (tmp >= bnd);\n\n   return tmp;\n}\n\n\n\nvoid RandomBits(ZZ& x, long l)\n{\n   if (l <= 0) {\n      x = 0;\n      return;\n   }\n\n   if (NTL_OVERFLOW(l, 1, 0))\n      ResourceError(\"RandomBits: length too big\");\n\n   RandomStream& stream = LocalGetCurrentRandomStream();\n\n   long nb = (l+7)/8;\n   unsigned long mask = (1UL << (8 - nb*8 + l)) - 1UL;\n\n   NTL_TLS_LOCAL(Vec<unsigned char>, buf_mem);\n   Vec<unsigned char>::Watcher watch_buf_mem(buf_mem);\n\n   buf_mem.SetLength(nb);\n   unsigned char *buf = buf_mem.elts();\n\n   x.SetSize((l + NTL_ZZ_NBITS - 1)/NTL_ZZ_NBITS);\n   // pre-allocate to ensure strong ES\n\n   stream.get(buf, nb);\n   buf[nb-1] &= mask;\n   \n   ZZFromBytes(x, buf, nb);\n}\n\n\nvoid RandomLen(ZZ& x, long l)\n{\n   if (l <= 0) {\n      x = 0;\n      return;\n   }\n\n   if (l == 1) {\n      x = 1;\n      return;\n   }\n\n   if (NTL_OVERFLOW(l, 1, 0))\n      ResourceError(\"RandomLen: length too big\");\n\n   RandomStream& stream = LocalGetCurrentRandomStream();\n\n   long nb = (l+7)/8;\n   unsigned long mask = (1UL << (8 - nb*8 + l)) - 1UL;\n\n   NTL_TLS_LOCAL(Vec<unsigned char>, buf_mem);\n   Vec<unsigned char>::Watcher watch_buf_mem(buf_mem);\n\n   buf_mem.SetLength(nb);\n   unsigned char *buf = buf_mem.elts();\n\n   x.SetSize((l + NTL_ZZ_NBITS - 1)/NTL_ZZ_NBITS);\n   // pre-allocate to ensure strong ES\n\n   stream.get(buf, nb);\n   buf[nb-1] &= mask;\n   buf[nb-1] |= ((mask >> 1) + 1UL);\n   \n   ZZFromBytes(x, buf, nb);\n}\n\n\n\n\n\n/**********************************************************\n\nThe following implementation of RandomBnd is designed\nfor speed.  It certainly is not resilient against a\ntiming side-channel attack (but then again, none of these\nPRG routines are designed to be).\n\nThe naive strategy generates random candidates of the right \nbit length until the candidate < bnd.\nThe idea in this implementation is to generate the high\norder two bytes of the candidate first, and compare this\nto the high order two bytes of tmp.  We can discard the\ncandidate if this is already too large.\n\n***********************************************************/\n\nvoid RandomBnd(ZZ& x, const ZZ& bnd)\n{\n   if (bnd <= 1) {\n      x = 0;\n      return;\n   }\n\n   RandomStream& stream = LocalGetCurrentRandomStream();\n\n   long l = NumBits(bnd);\n   long nb = (l+7)/8;\n\n   if (nb <= 3) {\n      long lbnd = conv<long>(bnd);\n      unsigned char lbuf[3];\n      long ltmp;\n      \n      x.SetSize((l + NTL_ZZ_NBITS - 1)/NTL_ZZ_NBITS);\n      // pre-allocate to ensure strong ES\n      do {\n         stream.get(lbuf, nb);\n         ltmp = long(WordFromBytes(lbuf, nb) & ((1UL << l)-1UL));\n      } while (ltmp >= lbnd);\n\n     conv(x, ltmp);\n     return;\n   }\n\n   // deal with possible alias\n   NTL_ZZRegister(tmp_store);\n   const ZZ& bnd_ref = ((&x == &bnd) ? (tmp_store = bnd) : bnd); \n\n\n   NTL_ZZRegister(hbnd);\n   RightShift(hbnd, bnd_ref, (nb-2)*8);\n   long lhbnd = conv<long>(hbnd);\n\n   unsigned long mask = (1UL << (16 - nb*8 + l)) - 1UL;\n\n   NTL_TLS_LOCAL(Vec<unsigned char>, buf_mem);\n   Vec<unsigned char>::Watcher watch_buf_mem(buf_mem);\n   buf_mem.SetLength(nb);\n   unsigned char *buf = buf_mem.elts();\n\n   unsigned char hbuf[2];\n\n   x.SetSize((l + NTL_ZZ_NBITS - 1)/NTL_ZZ_NBITS);\n   // pre-allocate to ensure strong ES\n   for (;;) {\n      stream.get(hbuf, 2);\n      long hpart = long(WordFromBytes(hbuf, 2) & mask);\n\n      if (hpart > lhbnd) continue;\n\n      stream.get(buf, nb-2);\n      buf[nb-2] = ((unsigned long) hpart);\n      buf[nb-1] = ((unsigned long) hpart) >> 8; \n\n      ZZFromBytes(x, buf, nb);\n      if (hpart < lhbnd || x < bnd_ref) break;\n   }\n}\n\n\n\n\n// More prime generation stuff...\n\nstatic\ndouble Log2(double x)\n{\n   static const double log2 = log(2.0); // GLOBAL (relies on C++11 thread-safe init)\n   return log(x)/log2;\n}\n\n// Define p(k,t) to be the conditional probability that a random, odd, k-bit \n// number is composite, given that it passes t iterations of the \n// Miller-Rabin test.\n// This routine returns 0 or 1, and if it returns 1 then\n// p(k,t) <= 2^{-n}.\n// This basically encodes the estimates of Damgard, Landrock, and Pomerance;\n// it uses floating point arithmetic, but is coded in such a way\n// that its results should be correct, assuming that the log function\n// is computed with reasonable precision.\n// \n// It is assumed that k >= 3 and t >= 1; if this does not hold,\n// then 0 is returned.\n\nstatic\nlong ErrBoundTest(long kk, long tt, long nn)\n\n{\n   const double fudge = (1.0 + 1024.0/NTL_FDOUBLE_PRECISION);\n   const double log2_3 = Log2(3.0);\n   const double log2_7 = Log2(7.0);\n   const double log2_20 = Log2(20.0);\n\n   double k = kk;\n   double t = tt;\n   double n = nn;\n\n   if (k < 3 || t < 1) return 0;\n   if (n < 1) return 1;\n\n   // the following test is largely academic\n   if (9*t > NTL_FDOUBLE_PRECISION) LogicError(\"ErrBoundTest: t too big\");\n\n   double log2_k = Log2(k);\n\n   if ((n + log2_k)*fudge <= 2*t)\n      return 1;\n\n   if ((2*log2_k + 4.0 + n)*fudge <= 2*sqrt(k))\n      return 2;\n\n   if ((t == 2 && k >= 88) || (3 <= t && 9*t <= k && k >= 21)) {\n      if ((1.5*log2_k + t + 4.0 + n)*fudge <= 0.5*Log2(t) + 2*(sqrt(t*k)))\n         return 3;\n   }\n\n   if (k <= 9*t && 4*t <= k && k >= 21) {\n      if ( ((log2_3 + log2_7 + log2_k + n)*fudge <= log2_20 + 5*t)  &&\n           ((log2_3 + (15.0/4.0)*log2_k + n)*fudge <= log2_7 + k/2 + 2*t) &&\n           ((2*log2_3 + 2 + log2_k + n)*fudge <= k/4 + 3*t) )\n         return 4; \n   }\n\n   if (4*t >= k && k >= 21) {\n      if (((15.0/4.0)*log2_k + n)*fudge <= log2_7 + k/2 + 2*t)\n         return 5;\n   }\n\n   return 0;\n}\n\n\nvoid GenPrime(ZZ& n, long k, long err)\n{\n   if (k <= 1) LogicError(\"GenPrime: bad length\");\n\n   if (k > (1L << 20)) ResourceError(\"GenPrime: length too large\");\n\n   if (err < 1) err = 1;\n   if (err > 512) err = 512;\n\n   if (k == 2) {\n      if (RandomBnd(2))\n         n = 3;\n      else\n         n = 2;\n\n      return;\n   }\n\n\n   long t;\n\n   t = 1;\n   while (!ErrBoundTest(k, t, err))\n      t++;\n\n   RandomPrime(n, k, t);\n}\n\n\nlong GenPrime_long(long k, long err)\n{\n   if (k <= 1) LogicError(\"GenPrime: bad length\");\n\n   if (k >= NTL_BITS_PER_LONG) ResourceError(\"GenPrime: length too large\");\n\n   if (err < 1) err = 1;\n   if (err > 512) err = 512;\n\n   if (k == 2) {\n      if (RandomBnd(2))\n         return 3;\n      else\n         return 2;\n   }\n\n   long t;\n\n   t = 1;\n   while (!ErrBoundTest(k, t, err))\n      t++;\n\n   return RandomPrime_long(k, t);\n}\n\n\nvoid GenGermainPrime(ZZ& n, long k, long err)\n{\n   if (k <= 1) LogicError(\"GenGermainPrime: bad length\");\n\n   if (k > (1L << 20)) ResourceError(\"GenGermainPrime: length too large\");\n\n   if (err < 1) err = 1;\n   if (err > 512) err = 512;\n\n   if (k == 2) {\n      if (RandomBnd(2))\n         n = 3;\n      else\n         n = 2;\n\n      return;\n   }\n\n\n   long prime_bnd = ComputePrimeBound(k);\n\n   if (NumBits(prime_bnd) >= k/2)\n      prime_bnd = (1L << (k/2-1));\n\n\n   ZZ two;\n   two = 2;\n\n   ZZ n1;\n\n   \n   PrimeSeq s;\n\n   ZZ iter;\n   iter = 0;\n\n\n   for (;;) {\n      iter++;\n\n      RandomLen(n, k);\n      if (!IsOdd(n)) add(n, n, 1);\n\n      s.reset(3);\n      long p;\n\n      long sieve_passed = 1;\n\n      p = s.next();\n      while (p && p < prime_bnd) {\n         long r = rem(n, p);\n\n         if (r == 0) {\n            sieve_passed = 0;\n            break;\n         }\n\n         // test if 2*r + 1 = 0 (mod p)\n         if (r == p-r-1) {\n            sieve_passed = 0;\n            break;\n         }\n\n         p = s.next();\n      }\n\n      if (!sieve_passed) continue;\n\n\n      if (MillerWitness(n, two)) continue;\n\n      // n1 = 2*n+1\n      mul(n1, n, 2);\n      add(n1, n1, 1);\n\n\n      if (MillerWitness(n1, two)) continue;\n\n      // now do t M-R iterations...just to make sure\n \n      // First compute the appropriate number of M-R iterations, t\n      // The following computes t such that \n      //       p(k,t)*8/k <= 2^{-err}/(5*iter^{1.25})\n      // which suffices to get an overall error probability of 2^{-err}.\n      // Note that this method has the advantage of not requiring \n      // any assumptions on the density of Germain primes.\n\n      long err1 = max(1, err + 7 + (5*NumBits(iter) + 3)/4 - NumBits(k));\n      long t;\n      t = 1;\n      while (!ErrBoundTest(k, t, err1))\n         t++;\n\n      ZZ W;\n      long MR_passed = 1;\n\n      long i;\n      for (i = 1; i <= t; i++) {\n         do {\n            RandomBnd(W, n);\n         } while (W == 0);\n         // W == 0 is not a useful candidate witness!\n\n         if (MillerWitness(n, W)) {\n            MR_passed = 0;\n            break;\n         }\n      }\n\n      if (MR_passed) break;\n   }\n}\n\nlong GenGermainPrime_long(long k, long err)\n{\n   if (k >= NTL_BITS_PER_LONG-1)\n      ResourceError(\"GenGermainPrime_long: length too long\");\n\n   ZZ n;\n   GenGermainPrime(n, k, err);\n   return to_long(n);\n}\n\n\nNTL_END_IMPL\n", "meta": {"hexsha": "8e73a948a1740d1cdbf506a29e2f35f069a0f16a", "size": 46697, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "code/NTL_mod/ZZ_bak.cpp", "max_stars_repo_name": "wonderit/secure-gwas", "max_stars_repo_head_hexsha": "39b34addd3e649309f4abd63144b24737b08ef94", "max_stars_repo_licenses": ["MIT"], "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/NTL_mod/ZZ_bak.cpp", "max_issues_repo_name": "wonderit/secure-gwas", "max_issues_repo_head_hexsha": "39b34addd3e649309f4abd63144b24737b08ef94", "max_issues_repo_licenses": ["MIT"], "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/NTL_mod/ZZ_bak.cpp", "max_forks_repo_name": "wonderit/secure-gwas", "max_forks_repo_head_hexsha": "39b34addd3e649309f4abd63144b24737b08ef94", "max_forks_repo_licenses": ["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.2564948454, "max_line_length": 95, "alphanum_fraction": 0.5277855108, "num_tokens": 16217, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5926665999540698, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.3445189262749576}}
{"text": "\n\n/* --------------------------------------------------------------------- \n * \n * Copyright (C) 2020 - 2021 by the deal.II authors \n * \n * This file is part of the deal.II library. \n * \n * The deal.II library is free software; you can use it, redistribute \n * it, and/or modify it under the terms of the GNU Lesser General \n * Public License as published by the Free Software Foundation; either \n * version 2.1 of the License, or (at your option) any later version. \n * The full text of the license can be found in the file LICENSE.md at \n * the top level directory of deal.II. \n * \n * --------------------------------------------------------------------- \n * \n * Authors: Bruno Blais, Toni El Geitani Nehme, Rene Gassmoeller, Peter Munch \n */ \n\n\n// @sect3{Include files}  \n#include <deal.II/base/bounding_box.h> \n#include <deal.II/base/conditional_ostream.h> \n#include <deal.II/base/discrete_time.h> \n#include <deal.II/base/mpi.h> \n#include <deal.II/base/parameter_acceptor.h> \n#include <deal.II/base/timer.h> \n\n#include <deal.II/distributed/cell_weights.h> \n#include <deal.II/distributed/solution_transfer.h> \n#include <deal.II/distributed/tria.h> \n\n#include <deal.II/dofs/dof_handler.h> \n#include <deal.II/dofs/dof_tools.h> \n\n#include <deal.II/fe/fe_q.h> \n#include <deal.II/fe/fe_system.h> \n#include <deal.II/fe/mapping_q.h> \n\n#include <deal.II/grid/grid_generator.h> \n#include <deal.II/grid/grid_tools.h> \n\n#include <deal.II/lac/la_parallel_vector.h> \n#include <deal.II/lac/vector.h> \n\n#include <deal.II/numerics/data_out.h> \n#include <deal.II/numerics/vector_tools.h> \n\n// 从下面的include文件中，我们导入了ParticleHandler类，该类允许你管理漂浮在 Particles::Particle), 类型的粒子集合（代表具有一些附加属性（例如，一个id）的点集合的对象）。 Particles命名空间中的方法和类允许人们轻松实现Particle-In-Cell方法和分布式三角形上的粒子追踪。\n\n#include <deal.II/particles/particle_handler.h> \n\n// 我们导入粒子发生器，使我们能够插入粒子。在本步骤中，粒子是通过非匹配的超壳三角形全局插入的。\n\n#include <deal.II/particles/generators.h> \n\n// 由于粒子没有形成三角形，它们有自己特定的DataOut类，这将使我们能够把它们写成常用的并行vtu格式（或其他任何数量的文件格式）。\n\n#include <deal.II/particles/data_out.h> \n\n#include <cmath> \n#include <iostream> \n\nnamespace Step68 \n{ \n  using namespace dealii; \n// @sect3{Run-time parameter handling}  \n\n// 与 step-60 中的做法类似，我们建立了一个持有我们问题的所有参数的类，并从ParameterAcceptor类中派生出来以简化参数文件的管理和创建。\n\n// ParameterAcceptor范式要求所有的参数都可以被ParameterAcceptor方法写入。为了避免出现很难追踪的bug（比如写成`if (time = 0)`而不是`if(time == 0)`），我们在一个外部类中声明所有的参数，该类在实际的`ParticleTracking`类之前被初始化，并将其作为`const`引用传递给主类。\n\n// 该类的构造函数负责该类的成员与ParameterHandler中的相应条目之间的连接。由于使用了 ParameterHandler::add_parameter() 方法，这种连接是微不足道的，但要求这个类的所有成员都是可写的。\n\n  class ParticleTrackingParameters : public ParameterAcceptor \n  { \n  public: \n    ParticleTrackingParameters(); \n\n// 该类主要由成员变量组成，描述了粒子跟踪模拟及其离散化的细节。下面的参数是关于输出应该写到哪里，速度的空间离散化（默认是 $Q_1$ ），时间步长和输出频率（在我们再次生成图形输出之前应该经过多少时间步长）。\n\n    std::string output_directory = \"./\"; \n\n    unsigned int velocity_degree       = 1; \n    double       time_step             = 0.002; \n    double       final_time            = 4.0; \n    unsigned int output_frequency      = 10; \n    unsigned int repartition_frequency = 5; \n\n// 我们允许每个网格独立地被细化。在本教程中，流体网格上没有解决物理问题，其速度是通过分析计算得出的。\n\n    unsigned int fluid_refinement              = 4; \n    unsigned int particle_insertion_refinement = 3; \n  }; \n\n// 还有一个任务就是声明我们在输入文件中可以接受哪些运行时参数。由于我们的参数数量非常有限，所有的参数都在同一章节中声明。\n\n  ParticleTrackingParameters::ParticleTrackingParameters() \n    : ParameterAcceptor(\"Particle Tracking Problem/\") \n  { \n    add_parameter( \n      \"Velocity degree\", velocity_degree, \"\", prm, Patterns::Integer(1)); \n\n    add_parameter(\"Output frequency\", \n                  output_frequency, \n                  \"Iteration frequency at which output results are written\", \n                  prm, \n                  Patterns::Integer(1)); \n\n    add_parameter(\"Repartition frequency\", \n                  repartition_frequency, \n                  \"Iteration frequency at which the mesh is load balanced\", \n                  prm, \n                  Patterns::Integer(1)); \n\n    add_parameter(\"Output directory\", output_directory); \n\n    add_parameter(\"Time step\", time_step, \"\", prm, Patterns::Double()); \n\n    add_parameter(\"Final time\", \n                  final_time, \n                  \"End time of the simulation\", \n                  prm, \n                  Patterns::Double()); \n\n    add_parameter(\"Fluid refinement\", \n                  fluid_refinement, \n                  \"Refinement level of the fluid domain\", \n                  prm, \n                  Patterns::Integer(0)); \n\n    add_parameter( \n      \"Particle insertion refinement\", \n      particle_insertion_refinement, \n      \"Refinement of the volumetric mesh used to insert the particles\", \n      prm, \n      Patterns::Integer(0)); \n  } \n\n//  @sect3{Velocity profile}  \n\n// 速度曲线是作为一个函数对象提供的。这个函数在例子中是硬编码的。\n\n  template <int dim> \n  class Vortex : public Function<dim> \n  { \n  public: \n    Vortex() \n      : Function<dim>(dim) \n    {} \n\n    virtual void vector_value(const Point<dim> &point, \n                              Vector<double> &  values) const override; \n  }; \n\n// Rayleigh-Kothe顶点的速度曲线是随时间变化的。因此，必须从函数对象中收集模拟的当前时间（t）。\n\n  template <int dim> \n  void Vortex<dim>::vector_value(const Point<dim> &point, \n                                 Vector<double> &  values) const \n  { \n    const double T = 4; \n    const double t = this->get_time(); \n\n    const double px = numbers::PI * point(0); \n    const double py = numbers::PI * point(1); \n    const double pt = numbers::PI / T * t; \n\n    values[0] = -2 * cos(pt) * pow(sin(px), 2) * sin(py) * cos(py); \n    values[1] = 2 * cos(pt) * pow(sin(py), 2) * sin(px) * cos(px); \n    if (dim == 3) \n      { \n        values[2] = 0; \n      } \n  } \n\n//  @sect3{The <code>ParticleTracking</code> class declaration}  \n\n// 我们现在准备介绍我们的教程程序的主类。\n\n  template <int dim> \n  class ParticleTracking \n  { \n  public: \n    ParticleTracking(const ParticleTrackingParameters &par, \n                     const bool                        interpolated_velocity); \n    void run(); \n\n  private: \n\n// 这个函数负责在背景网格之上初始生成粒子。\n\n    void generate_particles(); \n\n// 当速度曲线被内插到粒子的位置时，必须首先使用自由度来存储。因此，和其他并行情况一样（例如 step-40 ），我们在背景网格上初始化自由度。\n\n    void setup_background_dofs(); \n\n// 在其中一个测试案例中，该函数被映射到背景网格上，并使用有限元插值来计算粒子位置的速度。这个函数计算三角形的支持点处的函数值。\n\n    void interpolate_function_to_field(); \n\n// 下面两个函数分别负责对速度场在粒子位置插值或分析计算的情况下进行显式欧拉时间积分的步骤。\n\n    void euler_step_interpolated(const double dt); \n    void euler_step_analytical(const double dt); \n\n// `cell_weight()`函数向三角计算表明在这个单元上预计会发生多少计算工作，因此需要对域进行划分，以使每个MPI等级得到大致相等的工作量（可能不是相等的单元数量）。虽然该函数是从外部调用的，但它与该类内部的相应信号相连，因此它可以是 \"私有 \"的。\n\n    unsigned int cell_weight( \n      const typename parallel::distributed::Triangulation<dim>::cell_iterator \n        &cell, \n      const typename parallel::distributed::Triangulation<dim>::CellStatus \n        status) const; \n\n// 以下两个函数分别负责输出粒子的模拟结果和背景网格上的速度曲线。\n\n    void output_particles(const unsigned int it); \n    void output_background(const unsigned int it); \n\n// 该类的私有成员与其他并行deal.II例子相似。参数被存储为`const`成员。值得注意的是，我们保留了`Vortex`类的成员，因为它的时间必须随着模拟的进行而被修改。\n\n    const ParticleTrackingParameters &par; \n\n    MPI_Comm                                  mpi_communicator; \n    parallel::distributed::Triangulation<dim> background_triangulation; \n    Particles::ParticleHandler<dim>           particle_handler; \n\n    DoFHandler<dim>                            fluid_dh; \n    FESystem<dim>                              fluid_fe; \n    MappingQ1<dim>                             mapping; \n    LinearAlgebra::distributed::Vector<double> velocity_field; \n\n    Vortex<dim> velocity; \n\n    ConditionalOStream pcout; \n\n    bool interpolated_velocity; \n  }; \n\n//  @sect3{The <code>PatricleTracking</code> class implementation}  \n// @sect4{Constructor}  \n\n// 构造函数和析构函数是相当微不足道的。它们与  step-40  中的做法非常相似。我们将我们要工作的处理器设置为所有可用的机器（`MPI_COMM_WORLD`），并初始化  <code>pcout</code>  变量，只允许处理器0输出任何东西到标准输出。\n\n  template <int dim> \n  ParticleTracking<dim>::ParticleTracking(const ParticleTrackingParameters &par, \n                                          const bool interpolated_velocity) \n    : par(par) \n    , mpi_communicator(MPI_COMM_WORLD) \n    , background_triangulation(mpi_communicator) \n    , fluid_dh(background_triangulation) \n    , fluid_fe(FE_Q<dim>(par.velocity_degree), dim) \n    , pcout(std::cout, Utilities::MPI::this_mpi_process(mpi_communicator) == 0) \n    , interpolated_velocity(interpolated_velocity) \n\n  {} \n\n//  @sect4{Cell weight}  \n\n// 这个函数是让我们动态平衡本例中计算负载的关键部分。该函数为每个单元赋予一个权重，代表该单元的计算工作。在这里，大部分的工作预计会发生在粒子上，因此这个函数的返回值（代表 \"这个单元的工作\"）是根据当前单元中的粒子数量来计算。该函数与三角形内部的cell_weight()信号相连，每一个单元将被调用一次，每当三角形在等级之间重新划分领域时（该连接是在该类的generate_particles()函数中创建的）。\n\n  template <int dim> \n  unsigned int ParticleTracking<dim>::cell_weight( \n    const typename parallel::distributed::Triangulation<dim>::cell_iterator \n      &                                                                  cell, \n    const typename parallel::distributed::Triangulation<dim>::CellStatus status) \n    const \n  { \n\n// 我们不给我们不拥有的细胞分配任何权重（即人工或幽灵细胞）。\n\n    if (!cell->is_locally_owned()) \n      return 0; \n\n// 这决定了粒子工作与细胞工作相比有多重要（默认情况下每个细胞的权重为1000）。我们将每个粒子的权重设置得更高，以表明在这个例子中，粒子的负载是唯一对分配单元很重要的。这个数字的最佳值取决于应用，可以从0（廉价的粒子操作，昂贵的单元操作）到远远大于1000（昂贵的粒子操作，廉价的单元操作，像本例中假定的那样）。\n\n    const unsigned int particle_weight = 10000; \n\n// 这个例子没有使用自适应细化，因此每个单元都应该有`CELL_PERSIST`的状态。然而这个函数也可以用来在细化过程中分配负载，因此我们也考虑细化或粗化的单元。\n\n    if (status == parallel::distributed::Triangulation<dim>::CELL_PERSIST || \n        status == parallel::distributed::Triangulation<dim>::CELL_REFINE) \n      { \n        const unsigned int n_particles_in_cell = \n          particle_handler.n_particles_in_cell(cell); \n        return n_particles_in_cell * particle_weight; \n      } \n    else if (status == parallel::distributed::Triangulation<dim>::CELL_COARSEN) \n      { \n        unsigned int n_particles_in_cell = 0; \n\n        for (unsigned int child_index = 0; child_index < cell->n_children(); \n             ++child_index) \n          n_particles_in_cell += \n            particle_handler.n_particles_in_cell(cell->child(child_index)); \n\n        return n_particles_in_cell * particle_weight; \n      } \n\n    Assert(false, ExcInternalError()); \n    return 0; \n  } \n\n//  @sect4{Particles generation}  \n\n// 这个函数生成示踪粒子和这些粒子演化的背景三角图。\n\n  template <int dim> \n  void ParticleTracking<dim>::generate_particles() \n  { \n\n// 我们创建一个超立方体三角形，并对其进行全局细化。这个三角形覆盖了粒子的全部运动轨迹。\n\n    GridGenerator::hyper_cube(background_triangulation, 0, 1); \n    background_triangulation.refine_global(par.fluid_refinement); \n\n// 为了在重新划分三角形时考虑粒子，该算法需要知道三件事。\n\n// 1.给每个单元分配多少权重（里面有多少粒子）；2.在运送数据之前如何包装粒子；3.在重新分区之后如何拆开粒子。\n\n// 我们将正确的函数附加到信号里面  parallel::distributed::Triangulation.  这些信号将在每次调用repartition()函数时被调用。这些连接只需要创建一次，所以我们不妨在这个类的构造函数中设置它们，但为了这个例子，我们要把粒子相关的指令分组。\n\n    background_triangulation.signals.cell_weight.connect( \n      [&]( \n        const typename parallel::distributed::Triangulation<dim>::cell_iterator \n          &cell, \n        const typename parallel::distributed::Triangulation<dim>::CellStatus \n          status) -> unsigned int { return this->cell_weight(cell, status); }); \n\n    background_triangulation.signals.pre_distributed_repartition.connect( \n      [this]() { this->particle_handler.register_store_callback_function(); }); \n\n    background_triangulation.signals.post_distributed_repartition.connect( \n      [&]() { this->particle_handler.register_load_callback_function(false); }); \n\n// 这将初始化粒子所处的背景三角，以及粒子的属性数量。\n\n    particle_handler.initialize(background_triangulation, mapping, 1 + dim); \n\n// 我们创建了一个粒子三角图，这个三角图只用来生成将用于插入粒子的点。这个三角形是一个偏离模拟域中心的超壳。这将被用来生成一个充满粒子的圆盘，这将使我们能够很容易地监测由于涡流而产生的运动。\n\n    Point<dim> center; \n    center[0] = 0.5; \n    center[1] = 0.75; \n    if (dim == 3) \n      center[2] = 0.5; \n\n    const double outer_radius = 0.15; \n    const double inner_radius = 0.01; \n\n    parallel::distributed::Triangulation<dim> particle_triangulation( \n      MPI_COMM_WORLD); \n\n    GridGenerator::hyper_shell( \n      particle_triangulation, center, inner_radius, outer_radius, 6); \n    particle_triangulation.refine_global(par.particle_insertion_refinement); \n\n// 我们为粒子发生器生成必要的边界盒。这些边界框是快速识别插入的粒子位于哪个进程的子域中，以及哪个单元拥有它的必要条件。\n\n    const auto my_bounding_box = GridTools::compute_mesh_predicate_bounding_box( \n      background_triangulation, IteratorFilters::LocallyOwnedCell()); \n    const auto global_bounding_boxes = \n      Utilities::MPI::all_gather(MPI_COMM_WORLD, my_bounding_box); \n\n// 我们生成一个空的属性向量。一旦粒子生成，我们将把这些属性赋予它们。\n\n    std::vector<std::vector<double>> properties( \n      particle_triangulation.n_locally_owned_active_cells(), \n      std::vector<double>(dim + 1, 0.)); \n\n// 我们在单点正交的位置生成粒子。因此，在每个单元的中心点将生成一个粒子。\n\n    Particles::Generators::quadrature_points(particle_triangulation, \n                                             QMidpoint<dim>(), \n                                             global_bounding_boxes, \n                                             particle_handler, \n                                             mapping, \n                                             properties); \n\n    pcout << \"Number of particles inserted: \" \n          << particle_handler.n_global_particles() << std::endl; \n  } \n\n//  @sect4{Background DOFs and interpolation}  \n\n// 这个函数设置了用于速度插值的背景自由度，并分配了存储整个速度场解决方案的场向量。\n\n  template <int dim> \n  void ParticleTracking<dim>::setup_background_dofs() \n  { \n    fluid_dh.distribute_dofs(fluid_fe); \n    const IndexSet locally_owned_dofs = fluid_dh.locally_owned_dofs(); \n    IndexSet       locally_relevant_dofs; \n    DoFTools::extract_locally_relevant_dofs(fluid_dh, locally_relevant_dofs); \n\n    velocity_field.reinit(locally_owned_dofs, \n                          locally_relevant_dofs, \n                          mpi_communicator); \n  } \n\n// 这个函数负责将涡流速度场插值到场矢量上。这可以通过使用 VectorTools::interpolate() 函数相当容易地实现。\n\n  template <int dim> \n  void ParticleTracking<dim>::interpolate_function_to_field() \n  { \n    velocity_field.zero_out_ghost_values(); \n    VectorTools::interpolate(mapping, fluid_dh, velocity, velocity_field); \n    velocity_field.update_ghost_values(); \n  } \n\n//  @sect4{Time integration of the trajectories}  \n\n// 我们使用分析定义的速度场来整合粒子的轨迹。这展示了粒子的一个相对微不足道的用法。\n\n  template <int dim> \n  void ParticleTracking<dim>::euler_step_analytical(const double dt) \n  { \n    const unsigned int this_mpi_rank = \n      Utilities::MPI::this_mpi_process(mpi_communicator); \n    Vector<double> particle_velocity(dim); \n\n// 使用粒子迭代器在域中的所有粒子上进行循环操作\n\n    for (auto &particle : particle_handler) \n      { \n\n// 我们使用粒子的当前位置来计算它们的速度。\n\n        Point<dim> particle_location = particle.get_location(); \n        velocity.vector_value(particle_location, particle_velocity); \n\n// 这就更新了粒子的位置，并将旧的位置设定为等于粒子的新位置。\n\n        for (int d = 0; d < dim; ++d) \n          particle_location[d] += particle_velocity[d] * dt; \n\n        particle.set_location(particle_location); \n\n// 我们在粒子属性中存储处理器ID（标量）和粒子速度（矢量）。在这个例子中，这样做纯粹是为了可视化的目的。\n\n        ArrayView<double> properties = particle.get_properties(); \n        for (int d = 0; d < dim; ++d) \n          properties[d] = particle_velocity[d]; \n        properties[dim] = this_mpi_rank; \n      } \n  } \n\n// 与前面的函数不同，在这个函数中，我们通过将自由度处的速度场值插值到粒子的位置来积分粒子的轨迹。\n\n  template <int dim> \n  void ParticleTracking<dim>::euler_step_interpolated(const double dt) \n  { \n    Vector<double> local_dof_values(fluid_fe.dofs_per_cell); \n\n// 我们在所有的本地粒子上循环。虽然这可以直接通过循环所有的单元格来实现，但这将迫使我们循环许多不包含粒子的单元格。相反，我们在所有的粒子上循环，但是，我们得到粒子所在的单元格的引用，然后在该单元格中循环所有的粒子。这使我们能够从 \"velocity_field \"向量中收集一次速度值，并将其用于该单元中的所有粒子。\n\n    auto particle = particle_handler.begin(); \n    while (particle != particle_handler.end()) \n      { \n        const auto cell = \n          particle->get_surrounding_cell(background_triangulation); \n        const auto dh_cell = \n          typename DoFHandler<dim>::cell_iterator(*cell, &fluid_dh); \n\n        dh_cell->get_dof_values(velocity_field, local_dof_values); \n\n// 接下来，通过评估粒子位置的有限元解来计算粒子位置的速度。这基本上是第19步中粒子平流功能的优化版本，但我们不是为每个单元创建正交对象和FEValues对象，而是用手进行评估，这在一定程度上更有效率，而且只对本教程有意义，因为粒子工作是整个程序的主要成本。\n\n        const auto pic = particle_handler.particles_in_cell(cell); \n        Assert(pic.begin() == particle, ExcInternalError()); \n        for (auto &p : pic) \n          { \n            const Point<dim> reference_location = p.get_reference_location(); \n            Tensor<1, dim>   particle_velocity; \n            for (unsigned int j = 0; j < fluid_fe.dofs_per_cell; ++j) \n              { \n                const auto comp_j = fluid_fe.system_to_component_index(j); \n\n                particle_velocity[comp_j.first] += \n                  fluid_fe.shape_value(j, reference_location) * \n                  local_dof_values[j]; \n              } \n\n            Point<dim> particle_location = particle->get_location(); \n            for (int d = 0; d < dim; ++d) \n              particle_location[d] += particle_velocity[d] * dt; \n            p.set_location(particle_location); \n\n// 同样，我们在粒子属性中存储了粒子速度和处理器ID，以便于可视化。\n\n            ArrayView<double> properties = p.get_properties(); \n            for (int d = 0; d < dim; ++d) \n              properties[d] = particle_velocity[d]; \n\n            properties[dim] = \n              Utilities::MPI::this_mpi_process(mpi_communicator); \n\n            ++particle; \n          } \n      } \n  } \n\n//  @sect4{Data output}  \n\n// 接下来的两个函数负责将粒子和背景网格用pvtu记录写入vtu中。这可以确保在并行启动仿真时，仿真结果可以被可视化。\n\n  template <int dim> \n  void ParticleTracking<dim>::output_particles(const unsigned int it) \n  { \n    Particles::DataOut<dim, dim> particle_output; \n\n    std::vector<std::string> solution_names(dim, \"velocity\"); \n    solution_names.push_back(\"process_id\"); \n\n    std::vector<DataComponentInterpretation::DataComponentInterpretation> \n      data_component_interpretation( \n        dim, DataComponentInterpretation::component_is_part_of_vector); \n    data_component_interpretation.push_back( \n      DataComponentInterpretation::component_is_scalar); \n\n    particle_output.build_patches(particle_handler, \n                                  solution_names, \n                                  data_component_interpretation); \n    const std::string output_folder(par.output_directory); \n    const std::string file_name(interpolated_velocity ? \n                                  \"interpolated-particles\" : \n                                  \"analytical-particles\"); \n\n    pcout << \"Writing particle output file: \" << file_name << \"-\" << it \n          << std::endl; \n\n    particle_output.write_vtu_with_pvtu_record( \n      output_folder, file_name, it, mpi_communicator, 6); \n  } \n\n  template <int dim> \n  void ParticleTracking<dim>::output_background(const unsigned int it) \n  { \n    std::vector<std::string> solution_names(dim, \"velocity\"); \n    std::vector<DataComponentInterpretation::DataComponentInterpretation> \n      data_component_interpretation( \n        dim, DataComponentInterpretation::component_is_part_of_vector); \n\n    DataOut<dim> data_out; \n\n// 将解决方案的数据附加到data_out对象上\n\n    data_out.attach_dof_handler(fluid_dh); \n    data_out.add_data_vector(velocity_field, \n                             solution_names, \n                             DataOut<dim>::type_dof_data, \n                             data_component_interpretation); \n    Vector<float> subdomain(background_triangulation.n_active_cells()); \n    for (unsigned int i = 0; i < subdomain.size(); ++i) \n      subdomain(i) = background_triangulation.locally_owned_subdomain(); \n    data_out.add_data_vector(subdomain, \"subdomain\"); \n\n    data_out.build_patches(mapping); \n\n    const std::string output_folder(par.output_directory); \n    const std::string file_name(\"background\"); \n\n    pcout << \"Writing background field file: \" << file_name << \"-\" << it \n          << std::endl; \n\n    data_out.write_vtu_with_pvtu_record( \n      output_folder, file_name, it, mpi_communicator, 6); \n  } \n\n//  @sect4{Running the simulation}  这个函数协调了整个模拟过程。它与其他时间相关的教程程序非常相似--以 step-21 或 step-26 为例。注意，我们使用DiscreteTime类来监控时间、时间步长和 step- 号。这个函数相对来说是比较简单的。\n\n  template <int dim> \n  void ParticleTracking<dim>::run() \n  { \n    DiscreteTime discrete_time(0, par.final_time, par.time_step); \n\n    generate_particles(); \n\n    pcout << \"Repartitioning triangulation after particle generation\" \n          << std::endl; \n    background_triangulation.repartition(); \n\n// 我们通过在分析法和插值法的情况下进行时间步长为0的显式欧拉迭代来设置粒子的初始属性。\n\n    if (interpolated_velocity) \n      { \n        setup_background_dofs(); \n        interpolate_function_to_field(); \n        euler_step_interpolated(0.); \n      } \n    else \n      euler_step_analytical(0.); \n\n    output_particles(discrete_time.get_step_number()); \n    if (interpolated_velocity) \n      output_background(discrete_time.get_step_number()); \n\n// 粒子通过循环的方式随时间推移而平移。\n\n    while (!discrete_time.is_at_end()) \n      { \n        discrete_time.advance_time(); \n        velocity.set_time(discrete_time.get_previous_time()); \n\n        if ((discrete_time.get_step_number() % par.repartition_frequency) == 0) \n          { \n            background_triangulation.repartition(); \n            if (interpolated_velocity) \n              setup_background_dofs(); \n          } \n\n        if (interpolated_velocity) \n          { \n            interpolate_function_to_field(); \n            euler_step_interpolated(discrete_time.get_previous_step_size()); \n          } \n        else \n          euler_step_analytical(discrete_time.get_previous_step_size()); \n\n// 在粒子被移动之后，有必要确定它们现在所在的单元。这可以通过调用 <code>sort_particles_into_subdomains_and_cells</code> 来实现。\n        particle_handler.sort_particles_into_subdomains_and_cells(); \n\n        if ((discrete_time.get_step_number() % par.output_frequency) == 0) \n          { \n            output_particles(discrete_time.get_step_number()); \n            if (interpolated_velocity) \n              output_background(discrete_time.get_step_number()); \n          } \n      } \n  } \n\n} // namespace Step68 \n\n//  @sect3{The main() function}  \n\n// 代码的其余部分，即`main()`函数，是标准的。我们注意到，我们用分析速度和插值速度运行粒子跟踪，并产生两种结果\n\nint main(int argc, char *argv[]) \n{ \n  using namespace Step68; \n  using namespace dealii; \n  deallog.depth_console(1); \n\n  try \n    { \n      Utilities::MPI::MPI_InitFinalize mpi_initialization(argc, argv, 1); \n\n      std::string prm_file; \n      if (argc > 1) \n        prm_file = argv[1]; \n      else \n        prm_file = \"parameters.prm\"; \n\n      ParticleTrackingParameters par; \n      ParameterAcceptor::initialize(prm_file); \n      { \n        Step68::ParticleTracking<2> particle_tracking(par, false); \n        particle_tracking.run(); \n      } \n      { \n        Step68::ParticleTracking<2> particle_tracking(par, true); \n        particle_tracking.run(); \n      } \n    } \n  catch (std::exception &exc) \n    { \n      std::cerr << std::endl \n                << std::endl \n                << \"----------------------------------------------------\" \n                << std::endl; \n      std::cerr << \"Exception on processing: \" << std::endl \n                << exc.what() << std::endl \n                << \"Aborting!\" << std::endl \n                << \"----------------------------------------------------\" \n                << std::endl; \n\n      return 1; \n    } \n  catch (...) \n    { \n      std::cerr << std::endl \n                << std::endl \n                << \"----------------------------------------------------\" \n                << std::endl; \n      std::cerr << \"Unknown exception!\" << std::endl \n                << \"Aborting!\" << std::endl \n                << \"----------------------------------------------------\" \n                << std::endl; \n      return 1; \n    } \n\n  return 0; \n} \n\n\n", "meta": {"hexsha": "84ab6e4d8d89ca6d9b54ee7c7ecf68e7273346ea", "size": 23274, "ext": "cc", "lang": "C++", "max_stars_repo_path": "Translator_file/examples/step-68/step-68.cc", "max_stars_repo_name": "jiaqiwang969/deal.ii-course-practice", "max_stars_repo_head_hexsha": "0da5ad1537d8152549d8a0e4de5872efe7619c8a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Translator_file/examples/step-68/step-68.cc", "max_issues_repo_name": "jiaqiwang969/deal.ii-course-practice", "max_issues_repo_head_hexsha": "0da5ad1537d8152549d8a0e4de5872efe7619c8a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Translator_file/examples/step-68/step-68.cc", "max_forks_repo_name": "jiaqiwang969/deal.ii-course-practice", "max_forks_repo_head_hexsha": "0da5ad1537d8152549d8a0e4de5872efe7619c8a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.3438395415, "max_line_length": 209, "alphanum_fraction": 0.6464294921, "num_tokens": 7782, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5813030906443133, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.3445189262749576}}
{"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 HASHCLASH_SIGNED_DIGIT_REPRESENTATION_HPP\n#define HASHCLASH_SIGNED_DIGIT_REPRESENTATION_HPP\n\n#include <vector>\n#include <ostream>\n#include <functional>\n\n#ifndef NOSERIALIZATION\n#include <boost/serialization/serialization.hpp>\n#include <boost/serialization/nvp.hpp>\n#endif // NOSERIALIZATION\n\n#include \"types.hpp\"\n\nnamespace hashclash {\n\n\t// A class that holds a binary Signed Digit Representation (SDR) (modulo 2^32):\n\tclass sdr;\n\t// calculate hamming weight:\n\tinline unsigned hw(uint32 n);\n//\tinline unsigned hw(unsigned n) { return hw(uint32(n)); }\n\tinline unsigned hw(int n) { return hw(uint32(n)); }\n\tinline unsigned hw(uint64 n) {\n\t\treturn hw(uint32(n>>32)) + hw(uint32(n));\n\t}\n\t// calculate hamming weight of the NAF of n - is the lowest hamming weight among all SDR's:\n\tinline unsigned hwnaf(uint32 n);\n\t// calculate the NAF of n:\n\tsdr naf(uint32 n);\n\n\t// when rotating a difference, 4 possible differences exist after rotation. Use this function to find them:\n\t// returns possible differences with probability >= than minprob/2^32\n\tvoid rotate_difference(uint32 diff, int rc, std::vector<uint32>& rotateddiff, uint32 minprob = uint32(1)<<30);\n\tvoid rotate_difference(uint32 diff, int rc, std::vector<std::pair<uint32,double> >& rotateddiff);\n\tuint32 best_rotated_difference(uint32 diff, int rc);\n\n\tclass sdr {\n\tpublic:\n\t\t/**** constructors ****/\n\t\tsdr(): mask(0), sign(0) {}\n\t\tsdr(uint32 n): mask(n), sign(n) {}\n\t\tsdr(uint32 n1, uint32 n2): mask(n1^n2), sign(n2&~n1) {}\n\t\tsdr(const sdr& r): mask(r.mask), sign(r.sign) {}\n\n\t\t/**** assign functions/operators ****/\n\t\tsdr& set(const sdr& r)\n\t\t{\n\t\t\tmask = r.mask;\n\t\t\tsign = r.sign;\n\t\t\treturn *this;\n\t\t}\n\t\tsdr& set(uint32 n)\n\t\t{\n\t\t\tmask = sign = n;\n\t\t\treturn *this;\n\t\t}\n\t\tsdr& set(uint32 n1, uint32 n2)\n\t\t{\n\t\t\tmask = n1^n2;\n\t\t\tsign = n2 & ~n1;\n\t\t\treturn *this;\n\t\t}\n\t\tsdr& operator= (const sdr& r)\n\t\t{ return set(r); }\n\t\tsdr& operator= (const uint32 n)\n\t\t{ return set(n); }\n\t\tsdr& clear()\n\t\t{ return set(0); }\t\t\n\t\t\n\t\t/**** compare operators ****/\n\t\tbool operator== (const sdr& r) const\n\t\t{ return mask == r.mask && sign == r.sign; }\n\t\tbool operator< (const sdr& r) const\n\t\t{ return mask < r.mask || (mask == r.mask && sign < r.sign); }\n\t\tbool operator!= (const sdr& r) const\n\t\t{ return !(*this == r); }\n\t\tbool operator> (const sdr& r) const\n\t\t{ return r < *this; }\n\t\tbool operator<= (const sdr& r) const\n\t\t{ return !(*this > r); }\n\t\tbool operator>= (const sdr& r) const\n\t\t{ return !(*this < r); }\n\n\t\t/**** arithmetic operators ****/\n\t\tsdr operator-() const\n\t\t{\n\t\t\tsdr tmp(*this);\n\t\t\ttmp.sign ^= tmp.mask;\n\t\t\treturn tmp;\n\t\t}\n\n\t\tsdr& operator+= (const sdr& r)\n\t\t{\n\t\t\tuint32 set1 = set1conditions() + r.set1conditions();\n\t\t\treturn set(set1, set1 + adddiff() + r.adddiff());\n\t\t}\n\t\tsdr operator+ (const sdr& r) const\n\t\t{ return sdr(*this) += r; }\n\n\t\tsdr& operator-= (const sdr& r)\n\t\t{\n\t\t\tuint32 set1 = set1conditions() + r.sign;\n\t\t\treturn set(set1, set1 + adddiff() - r.adddiff());\n\t\t}\n\t\tsdr operator- (const sdr& r) const\n\t\t{ return sdr(*this) -= r; }\n\n\t\tsdr& operator^= (const sdr& r)\n\t\t{\n\t\t\tmask ^= r.mask;\n\t\t\tsign = mask & ~(sign^r.sign);\n\t\t\treturn *this;\n\t\t}\n\t\tsdr operator^ (const sdr& r) const\n\t\t{ return sdr(*this) ^= r; }\n\n\t\tsdr& operator<<= (unsigned n)\n\t\t{\n\t\t\tmask <<= n;\n\t\t\tsign <<= n;\n\t\t\treturn *this;\n\t\t}\n\t\tsdr operator<< (unsigned n) const\n\t\t{ return sdr(*this) <<= n; }\n\n\t\tsdr& operator>>= (unsigned n)\n\t\t{\n\t\t\tmask >>= n;\n\t\t\tsign >>= n;\n\t\t\treturn *this;\n\t\t}\n\t\tsdr operator>> (unsigned n) const\n\t\t{ return sdr(*this) >>= n; }\n\n\t\tsdr rotate_left(unsigned n) const\n\t\t{\n\t\t\tsdr tmp(*this);\n\t\t\ttmp.mask = hashclash::rotate_left(mask, n);\n\t\t\ttmp.sign = hashclash::rotate_left(sign, n);\n\t\t\treturn tmp;\n\t\t}\n\t\tsdr rotate_right(unsigned n) const\n\t\t{\n\t\t\tsdr tmp(*this);\n\t\t\ttmp.mask = hashclash::rotate_right(mask, n);\n\t\t\ttmp.sign = hashclash::rotate_right(sign, n);\n\t\t\treturn tmp;\n\t\t}\n\n\t\t/**** other functions ****/\n\t\tuint32 adddiff() const\n\t\t{ return sign - (sign^mask); }\n\t\tuint32 xordiff() const\n\t\t{ return mask; }\n\t\tuint32 set0conditions() const\n\t\t{ return ~sign; }\n\t\tuint32 set1conditions() const\n\t\t{ return sign^mask; }\n\n\t\tint get(unsigned b) const \n\t\t{\n\t\t\treturn int((sign>>b)&1) - int(((sign^mask)>>b)&1);\n\t\t}\n\t\tint operator[] (unsigned b) const\n\t\t{ return get(b); }\n\n\t\tunsigned hw() const\n\t\t{ return hashclash::hw(mask); }\n\t\tunsigned hwnaf() const\n\t\t{ return hashclash::hwnaf(adddiff()); }\n\t\tsdr naf() const\n\t\t{ return hashclash::naf(adddiff()); }\n\n\t\t/**** members ****/\n\t\tuint32 mask, sign;\n\t};\n\n\tinline void swap(sdr& l, sdr& r)\n\t{\n\t\tstd::swap(l.mask, r.mask);\n\t\tstd::swap(l.sign, r.sign);\n\t}\n\n\tstd::ostream& operator<<(std::ostream& o, const sdr& n);\n\tstd::istream& operator>>(std::istream& i, sdr& n);\n\n\textern unsigned hw_table[0x800];\n\tinline unsigned hw(uint32 n)\n\t{\n\t\tunsigned w = hw_table[n & 0x7FF];\n\t\tw += hw_table[(n >> 11) & 0x7FF];\n\t\tw += hw_table[n >> 22];\n\t\treturn w;\n\t}\n\n\tinline unsigned hwnaf(uint32 n)\n\t{\n\t\tuint32 a = n>>1;\n\t\tuint32 w = a ^ (n+a);\n\t\treturn hw(w);\n\t}\n\n\tinline sdr naf(uint32 n)\n\t{\n\t\tuint32 a = n>>1;\n\t\treturn sdr(a,a+n);\n\t}\n\n\tinline unsigned hw(const sdr& n)\n\t{ return n.hw(); }\n\tinline unsigned hwnaf(const sdr& n)\n\t{ return n.hwnaf(); }\n\tinline sdr naf(const sdr& n)\n\t{ return n.naf(); }\n\n\tunsigned count_sdrs(uint32 n, unsigned maxweight = 32);\n\tvoid table_sdrs(std::vector<sdr>& result, uint32 n, unsigned maxweight);\n\n\tunsigned count_sdrs(uint32 n, unsigned weight, bool signpos);\n\tvoid table_sdrs(std::vector<sdr>& result, uint32 n, unsigned weight, bool signpos);\n\n\tunsigned count_sdrs(sdr n, unsigned maxweight, unsigned rot);\n\tvoid table_sdrs(std::vector<sdr>& result, sdr n, unsigned maxweight, unsigned rot);\n\n\t// call this in a other global constructor using hw or hwnaf \n\t// due to the inpredictable order of which global constructors are called\n\t// otherwise the correct functioning of hw and hwnaf are not guaranteed\n\tvoid hashclash_sdr_hpp_init();\n\n} // namespace hashclash\n\n\n#ifndef NOSERIALIZATION\nnamespace boost {\n\tnamespace serialization {\n\n\t\ttemplate<class Archive>\n\t\tvoid serialize(Archive& ar, hashclash::sdr& d, const unsigned int file_version)\n\t\t{\n\t\t\tar & make_nvp(\"mask\", d.mask);\n\t\t\tar & make_nvp(\"sign\", d.sign);\n\t\t}\n\n\t}\n}\n#endif // NOSERIALIZATION\n\n#endif // HASHCLASH_SIGNED_DIGIT_REPRESENTATION_HPP\n", "meta": {"hexsha": "4bc3a427fff028ba190d713781fce7cb1b3769b1", "size": 7096, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "lib/hashclash/sdr.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": "lib/hashclash/sdr.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": "lib/hashclash/sdr.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": 26.4776119403, "max_line_length": 111, "alphanum_fraction": 0.6357102593, "num_tokens": 2159, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5964331462646255, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.3444373776110126}}
{"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_MATRIX_POISSON2D_DIRICHLET_INCLUDE\n#define MTL_MATRIX_POISSON2D_DIRICHLET_INCLUDE\n\n#include <boost/numeric/mtl/concept/collection.hpp>\n#include <boost/numeric/mtl/utility/ashape.hpp>\n#include <boost/numeric/mtl/utility/exception.hpp>\n#include <boost/numeric/mtl/vector/mat_cvec_multiplier.hpp>\n\nnamespace mtl { namespace mat {\n\n/// Matrix-free linear operator for a Poisson equation on a rectangular domain of \\p m by \\p n with Dirichlet boundary conditions\nstruct poisson2D_dirichlet\n{\n    /// Constructor\n    poisson2D_dirichlet(int m, int n) : m(m), n(n), s(m * n) {}\n\n    /// Member function that realizes the multiplication\n    template <typename VectorIn, typename VectorOut, typename Assign>\n    void mult(const VectorIn& v, VectorOut& w, Assign) const\n    {\n\tMTL_DEBUG_THROW_IF(int(size(v)) != s, incompatible_size());\n\tMTL_DEBUG_THROW_IF(size(v) != size(w), incompatible_size());\n\n\tconst int nb = n < 3 ? 1 : (n - 2) / 4 * 4 + 1;\n\n\t// Inner domain\n\tfor (int i= 1; i < m-1; i++) {\n\t    int kmax= i * n + nb;\n\t    for (int k= i * n + 1; k < kmax; k+= 4) {\n\t\ttypename Collection<VectorIn>::value_type const v0= v[k], v1= v[k+1], v2= v[k+2], v3= v[k+3];\n\t\tAssign::apply(w[k], 4 * v0 - v[k-n] - v[k+n] - v[k-1] - v1); \n\t\tAssign::apply(w[k+1], 4 * v1 - v[k-n+1] - v[k+n+1] - v0 - v2); \n\t\tAssign::apply(w[k+2], 4 * v2 - v[k-n+2] - v[k+n+2] - v1 - v3); \n\t\tAssign::apply(w[k+3], 4 * v3 - v[k-n+3] - v[k+n+3] - v2 - v[k+4]); \n\t    }\n\t    for (int j= nb, k= i * n + j; j < n-1; j++, k++) \n\t\tAssign::apply(w[k], 4 * v[k] - v[k-n] - v[k+n] - v[k-1] - v[k+1]); \n\t}\n\t    \n\t// Upper border\n\tfor (int j= 1; j < n-1; j++) \n\t    Assign::apply(w[j], 4 * v[j] - v[j+n] - v[j-1] - v[j+1]);\n\n\t// Lower border\n\tfor (int j= 1, k= (m-1) * n + j; j < n-1; j++, k++) \n\t    Assign::apply(w[k], 4 * v[k] - v[k-n] - v[k-1] - v[k+1]); \n\t\n\t// Left border\n\tfor (int i= 1, k= n; i < m-1; i++, k+= n)\n\t    Assign::apply(w[k], 4 * v[k] - v[k-n] - v[k+n] - v[k+1]); \n\n\t// Right border\n\tfor (int i= 1, k= n+n-1; i < m-1; i++, k+= n)\n\t    Assign::apply(w[k], 4 * v[k] - v[k-n] - v[k+n] - v[k-1]); \n\n\t// Corners\n\tAssign::apply(w[0], 4 * v[0] - v[1] - v[n]);\n\tAssign::apply(w[n-1], 4 * v[n-1] - v[n-2] - v[2*n - 1]);\n\tAssign::apply(w[(m-1)*n], 4 * v[(m-1)*n] - v[(m-2)*n] - v[(m-1)*n+1]);\n\tAssign::apply(w[m*n-1], 4 * v[m*n-1] - v[m*n-2] - v[m*n-n-1]);\n    }\n\n    /// Multiplication is procastinated until we know where the product goes\n    template <typename VectorIn>\n    vec::mat_cvec_multiplier<poisson2D_dirichlet, VectorIn> operator*(const VectorIn& v) const\n    {\treturn vec::mat_cvec_multiplier<poisson2D_dirichlet, VectorIn>(*this, v);    }\n\n    int m, n, s;\n};\n\ninline std::size_t size(const poisson2D_dirichlet& A) { return A.s * A.s; } ///< Matrix size\ninline std::size_t num_rows(const poisson2D_dirichlet& A) { return A.s; } ///< Number of rows\ninline std::size_t num_cols(const poisson2D_dirichlet& A) { return A.s; } ///< Number of columns\n\n}} // namespace mtl::matrix\n\nnamespace mtl { \n\n    template <>\n    struct Collection<mat::poisson2D_dirichlet>\n    {\n\ttypedef double value_type;\n\ttypedef int    size_type;\n    };\n\n    namespace ashape {\n\ttemplate <> struct ashape_aux<mtl::mat::poisson2D_dirichlet> \n\t{\ttypedef nonscal type;    };\n    }\n}\n\n#endif // MTL_MATRIX_POISSON2D_DIRICHLET_INCLUDE\n", "meta": {"hexsha": "2c10d9be0f1d5a9531d126b495e0d592208ddae0", "size": 3730, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/numeric/mtl/matrix/poisson2D_dirichlet.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/poisson2D_dirichlet.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/poisson2D_dirichlet.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": 35.5238095238, "max_line_length": 129, "alphanum_fraction": 0.608310992, "num_tokens": 1336, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5964331462646255, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.3444373776110126}}
{"text": "//=======================================================================\n// Copyright (c) 2013 Piotr Wygocki\n//\n// Distributed under the Boost Software License, Version 1.0. (See\n// accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n//=======================================================================\n\n/**\n * @file knapsack_greedy.hpp\n * @brief\n * @author Piotr Wygocki\n * @version 1.0\n * @date 2013-10-07\n */\n\n#ifndef PAAL_KNAPSACK_GREEDY_HPP\n#define PAAL_KNAPSACK_GREEDY_HPP\n\n#include \"paal/utils/accumulate_functors.hpp\"\n#include \"paal/utils/knapsack_utils.hpp\"\n\n#include <boost/iterator/counting_iterator.hpp>\n#include <boost/range/algorithm/remove_if.hpp>\n\nnamespace paal {\nnamespace detail {\n\n// if the knapsack dynamic table is indexed by values,\n// the procedure to find the best element is to find the biggest index i in the\n// table that\n// *i is smaller than given threshold(capacity)\ntemplate <typename MaxValueType, typename SizeType>\nstruct get_max_element_on_value_indexed_collection {\n    get_max_element_on_value_indexed_collection(MaxValueType maxValue)\n        : m_max_value(maxValue) {}\n\n    template <typename Iterator, typename Comparator>\n    Iterator operator()(Iterator begin, Iterator end, Comparator compare) {\n        auto compareOpt = make_less_pointees_t(compare);\n        // traverse in reverse order, skip the first\n        for (auto iter = end - 1; iter != begin; --iter) {\n            if (*iter && compareOpt(m_max_value, *iter)) {\n                return iter;\n            }\n        }\n\n        return end;\n    }\n\n  private:\n    MaxValueType m_max_value;\n};\n\n// if the knapsack dynamic table is indexed by sizes,\n// the procedure to find the best element is to find the biggest\n// index i in the table that maximizes *i\ntemplate <typename ValueType>\nstruct get_max_element_on_capacity_indexed_collection {\n    template <typename Iterator, typename Comparator>\n    Iterator operator()(Iterator begin, Iterator end, Comparator compare) {\n        return std::max_element(begin, end, make_less_pointees_t(compare));\n    }\n};\n\ntemplate <typename KnapsackData,\n          typename Is_0_1_Tag,\n          typename Value = typename KnapsackData::value,\n          typename Size  = typename KnapsackData::size>\ntypename KnapsackData::return_type knapsack_general_two_app(\n    KnapsackData knapsack_data, Is_0_1_Tag is_0_1_Tag) {\n\n    using ObjectRef = typename KnapsackData::object_ref;\n\n    static_assert(std::is_arithmetic<Value>::value &&\n                      std::is_arithmetic<Size>::value,\n                  \"Size type and Value type must be arithmetic types\");\n    auto capacity = knapsack_data.get_capacity();\n\n    auto bad_size = [=](ObjectRef o){return knapsack_data.get_size(o) > capacity;};\n\n    auto objects = boost::remove_if<boost::return_begin_found>(knapsack_data.get_objects(), bad_size);\n\n    if (boost::empty(objects)) {\n        return std::pair<Value, Size>();\n    }\n\n    // finding the element with the greatest density\n    auto greedyFill = get_greedy_fill(\n            make_knapsack_data(\n                objects, capacity,\n                knapsack_data.get_size(),\n                knapsack_data.get_value(),\n                knapsack_data.get_output_iter()), is_0_1_Tag);\n\n    // finding the biggest set elements with the greatest density\n    // this is actually small optimization compare to original algorithm\n    // note that largest is transformed iterator!\n    auto largest = max_element_functor(objects, knapsack_data.get_value());\n\n    if (*largest > std::get<0>(greedyFill)) {\n        knapsack_data.out(*largest.base());\n        return std::make_pair(*largest, knapsack_data.get_size(*largest.base()));\n    } else {\n        greedy_to_output(std::get<2>(greedyFill), knapsack_data.get_output_iter(), is_0_1_Tag);\n        return std::make_pair(std::get<0>(greedyFill), std::get<1>(greedyFill));\n    }\n}\n\ntemplate <typename Range>\nstruct is_range_const {\n    using ref = typename boost::range_reference<Range>::type;\n    static const bool value = std::is_const<ref>::value ||\n                     !std::is_reference<ref>::value;\n};\n} //! detail\n} //! paal\n#endif // PAAL_KNAPSACK_GREEDY_HPP\n", "meta": {"hexsha": "4f25de5b145d57df86d178d3051c2db0beb3f25c", "size": 4184, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/paal/greedy/knapsack/knapsack_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/knapsack/knapsack_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/knapsack/knapsack_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": 35.1596638655, "max_line_length": 102, "alphanum_fraction": 0.668499044, "num_tokens": 986, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5774953651858117, "lm_q2_score": 0.5964331462646255, "lm_q1q2_score": 0.34443737761101256}}
{"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\n#include <votca/xtp/gwbse.h>\n\n#include <boost/format.hpp>\n#include <boost/filesystem.hpp>\n#include <boost/numeric/ublas/operation.hpp>\n#include <votca/xtp/aomatrix.h>\n#include <votca/xtp/threecenters.h>\n// #include <votca/xtp/logger.h>\n#include <votca/xtp/qmpackagefactory.h>\n#include <boost/math/constants/constants.hpp>\n#include <boost/numeric/ublas/symmetric.hpp>\n#include <votca/tools/linalg.h>\n\nusing boost::format;\nusing namespace boost::filesystem;\n\nnamespace votca {\n    namespace xtp {\n        namespace ub = boost::numeric::ublas;\n\n        // +++++++++++++++++++++++++++++ //\n        // MBPT MEMBER FUNCTIONS         //\n        // +++++++++++++++++++++++++++++ //\n\n        \n        void GWBSE::BSE_qp_setup(){\n            _eh_qp = ub::zero_matrix<real_gwbse>( _bse_size , _bse_size );\n            BSE_Add_qp2H( _eh_qp );\n            return;\n        }\n        \n    \n\n\n        void GWBSE::BSE_solve_triplets(){\n            \n            // add full QP Hamiltonian contributions to free transitions\n           \n            ub::matrix<real_gwbse> _bse=_eh_d;\n            \n            linalg_eigenvalues(  _bse, _bse_triplet_energies, _bse_triplet_coefficients, _bse_nmax);\n            return;\n        }\n        \n        \n        void GWBSE::Solve_nonhermitian(ub::matrix<double>& H, ub::matrix<double>& LT) {\n\n            // remove stuff from Cholesky and Calculated L^T,, because more efficient for mat prods \n            #pragma omp parallel for\n            for (unsigned i = 0; i < LT.size1(); i++) {\n                for (unsigned j = i + 1; j < LT.size1(); j++) {\n                    LT(i, j) = LT(j, i);\n                    LT(j, i) = 0;\n                }\n            }\n\n            CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp() << \" Removed non referenced part of Cholesky decompostion\" << flush;\n            // determine H = L^T(A-B)L\n            ub::matrix<double> _temp = ub::prod(H, ub::trans(LT));\n            H= ub::prod(LT, _temp);\n            _temp.resize(0, 0);\n            CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp() << \" Calculated H = L^T(A+B)L \" << flush;\n\n            // solve eigenvalue problem: HR_l = eps_l^2 R_l\n            ub::vector<double> _eigenvalues;\n            ub::matrix<double> _eigenvectors;\n\n            linalg_eigenvalues(H, _eigenvalues, _eigenvectors, _bse_nmax);\n            CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp() << \" Solved HR_l = eps_l^2 R_l \" << flush;\n            H.resize(0, 0);\n            // reconstruct real eigenvalues eps_l = sqrt(eps_l^2)\n            _bse_singlet_energies.resize(_bse_nmax);\n            for (int _i = 0; _i < _bse_nmax; _i++) {\n                _bse_singlet_energies(_i) = sqrt(_eigenvalues(_i)); // store positive energies in orbitals objects\n            }\n\n\n            // reconstruct real eigenvectors X_l = 1/2 [sqrt(eps_l) (L^T)^-1 + 1/sqrt(eps_l)L ] R_l\n            //                               Y_l = 1/2 [sqrt(eps_l) (L^T)^-1 - 1/sqrt(eps_l)L ] R_l\n\n            // determine inverse of L^T\n            ub::matrix<double> _cholesky_transposed_invert;\n            ub::matrix<double> L = ub::trans(LT);\n            linalg_invert(LT, _cholesky_transposed_invert);\n\n            int dim = L.size1();\n            _bse_singlet_coefficients.resize(dim, _bse_nmax); // resonant part (_X_evec)\n            _bse_singlet_coefficients_AR.resize(dim, _bse_nmax); // anti-resonant part (_Y_evec)\n\n\n            for (int _i = 0; _i < _bse_nmax; _i++) {\n                //real_gwbse sqrt_eval = sqrt(_eigenvalues(_i));\n                double sqrt_eval = sqrt(_bse_singlet_energies(_i));\n                // get l-th reduced EV\n                ub::matrix<double> _reduced_evec = ub::project(_eigenvectors, ub::range(0, dim), ub::range(_i, _i + 1)); // potentially col<->row\n\n                ub::matrix<double> _transform = 0.5 * (sqrt_eval * _cholesky_transposed_invert + 1.0 / sqrt_eval * L);\n                ub::project(_bse_singlet_coefficients, ub::range(0, dim), ub::range(_i, _i + 1)) = ub::prod(_transform, _reduced_evec);\n                _transform = 0.5 * (sqrt_eval * _cholesky_transposed_invert - 1.0 / sqrt_eval * L);\n                ub::project(_bse_singlet_coefficients_AR, ub::range(0, dim), ub::range(_i, _i + 1)) = ub::prod(_transform, _reduced_evec);\n            }\n            return;\n        }\n        \n      void GWBSE::BSE_solve_singlets_BTDA(){\n        \n          \n        // For details of the method, see EPL,78(2007)12001,\n        // Nuclear Physics A146(1970)449, Nuclear Physics A163(1971)257.\n        \n          // setup resonant (A) and RARC blocks (B)\n          // TOCHECK: Isn't that memory overkill here? _A and _B are never needed again?\n           // ub::matrix<real_gwbse> _A = _eh_d + 2.0 * _eh_x;\n           // ub::matrix<real_gwbse> _B = _eh_d2 + 2.0 * _eh_x;\n          ub::matrix<double> _ApB = _eh_d + _eh_d2 + 4.0 * _eh_x;\n          ub::matrix<double> _AmB = _eh_d - _eh_d2;\n\n            \n        \n            \n          // calculate Cholesky decomposition of A-B = LL^T. It throws an error if not positive definite\n            //(A-B) is not needed any longer and can be overwritten\n          \n          bool positive_definite=true;\n          CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp() << \" Trying Cholesky decomposition of KAA-KAB\" << flush;\n          try\n            {\n            linalg_cholesky_decompose( _AmB );\n            }\n            catch (const std::runtime_error& error)\n            {\n                positive_definite=false;\n                CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp() <<error.what()<<endl;\n                CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp() << \"Trying Cholesky decomposition of KAA+KAB\" << flush;\n                linalg_cholesky_decompose( _ApB );\n                _AmB = _eh_d - _eh_d2;\n            }\n            \n          if(positive_definite){\n              Solve_nonhermitian(_ApB,_AmB);\n          }\n          else{\n              Solve_nonhermitian(_AmB,_ApB);\n          }\n          \n          return;\n      }\n        \n        \n      void GWBSE::BSE_Add_qp2H( ub::matrix<real_gwbse>& qp ){\n              \n          #pragma omp parallel for\n            for ( size_t _v1 = 0 ; _v1 < _bse_vtotal ; _v1++){\n                for ( size_t _c1 = 0 ; _c1 < _bse_ctotal ; _c1++){\n                    size_t _index_vc = _bse_ctotal * _v1 + _c1;\n                    // diagonal\n                    qp( _index_vc , _index_vc ) += _vxc(_c1 + _bse_vtotal ,_c1 + _bse_vtotal ) - _vxc(_v1,_v1);\n                    // v->c\n                    for ( size_t _c2 = 0 ; _c2 < _bse_ctotal ; _c2++){\n                        size_t _index_vc2 = _bse_ctotal * _v1 + _c2;\n                        if ( _c1 != _c2 ){\n                            qp( _index_vc , _index_vc2 ) += _vxc(_c1+ _bse_vtotal ,_c2 + _bse_vtotal );\n                        }\n                    }\n                    \n                    // c-> v\n                    for ( size_t _v2 = 0 ; _v2 < _bse_vtotal ; _v2++){\n                        size_t _index_vc2 = _bse_ctotal * _v2 + _c1;\n                        if ( _v1 != _v2 ){\n                            qp( _index_vc , _index_vc2 ) -= _vxc(_v1,_v2);\n                        }\n                    } \n                }\n            }\n            return;\n      }\n   \n        \n      void GWBSE::BSE_solve_singlets(){\n            \n            ub::matrix<real_gwbse> _bse = _eh_d + 2.0 * _eh_x;\n            \n            // _bse_singlet_energies.resize(_bse_singlet_coefficients.size1());\n            linalg_eigenvalues(_bse, _bse_singlet_energies, _bse_singlet_coefficients, _bse_nmax);\n            return;\n        } \n        \n        \n        void GWBSE::BSE_d_setup ( TCMatrix& _Mmn){\n            // gwbasis size\n            size_t _gwsize = _Mmn[_homo].size1();\n\n            // messy procedure, first get two matrices for occ and empty subbparts\n            // store occs directly transposed\n            ub::matrix<real_gwbse> _storage_v = ub::zero_matrix<real_gwbse>(  _bse_vtotal * _bse_vtotal , _gwsize );\n            #pragma omp parallel for\n            for ( size_t _v1 = 0; _v1 < _bse_vtotal; _v1++){\n                const ub::matrix<real_gwbse>& Mmn = _Mmn[_v1 + _bse_vmin ];\n                for ( size_t _v2 = 0; _v2 < _bse_vtotal; _v2++){\n                    size_t _index_vv = _bse_vtotal * _v1 + _v2;\n                    for ( size_t _i_gw = 0 ; _i_gw < _gwsize ; _i_gw++) {\n                        _storage_v( _index_vv , _i_gw ) = Mmn( _i_gw , _v2 + _bse_vmin );\n                    }\n                }\n            }\n            \n            \n            ub::matrix<real_gwbse> _storage_c = ub::zero_matrix<real_gwbse>( _gwsize, _bse_ctotal * _bse_ctotal );\n            #pragma omp parallel for\n            for ( size_t _c1 = 0; _c1 < _bse_ctotal; _c1++){\n                const ub::matrix<real_gwbse>& Mmn = _Mmn[_c1 + _bse_cmin];\n                for ( size_t _c2 = 0; _c2 < _bse_ctotal; _c2++){\n                    size_t _index_cc = _bse_ctotal * _c1 + _c2;\n                    for ( size_t _i_gw = 0 ; _i_gw < _gwsize ; _i_gw++) {\n                        _storage_c( _i_gw , _index_cc ) = Mmn( _i_gw , _c2 + _bse_cmin );\n                    }\n                }\n            }\n            \n            if ( ! _do_bse_singlets )  _Mmn.Cleanup();\n            \n            // store elements in a vtotal^2 x ctotal^2 matrix\n            // cout << \"BSE_d_setup 1 [\" << _storage_v.size1() << \"x\" << _storage_v.size2() << \"]\\n\" << std::flush;\n            ub::matrix<real_gwbse> _storage_prod = ub::prod( _storage_v , _storage_c );\n            \n\n            // now patch up _storage for screened interaction\n            #pragma omp parallel for\n            for ( size_t _i_gw = 0 ; _i_gw < _gwsize ; _i_gw++ ){  \n                if (_ppm_weight(_i_gw) < 1.e-9) {                    \n                    for ( size_t _v = 0 ; _v < (_bse_vtotal* _bse_vtotal) ; _v++){\n                        _storage_v( _v , _i_gw ) = 0;\n                    }\n                    for ( size_t _c = 0 ; _c < (_bse_ctotal*_bse_ctotal) ; _c++){\n                        _storage_c( _i_gw , _c ) =0;\n                    }\n                \n                }else{\n                    double _ppm_factor = sqrt( _ppm_weight( _i_gw ));\n                    for ( size_t _v = 0 ; _v < (_bse_vtotal* _bse_vtotal) ; _v++){\n                        _storage_v( _v , _i_gw ) = _ppm_factor * _storage_v(_v , _i_gw );\n                    }\n                    for ( size_t _c = 0 ; _c < (_bse_ctotal*_bse_ctotal) ; _c++){\n                        _storage_c( _i_gw , _c ) = _ppm_factor * _storage_c( _i_gw , _c  );\n                    }\n                }\n            }\n            \n            // multiply and subtract from _storage_prod\n         \n            _storage_prod -= ub::prod( _storage_v , _storage_c );\n            \n            // free storage_v and storage_c\n            _storage_c.resize(0,0);\n            _storage_v.resize(0,0);\n            \n            // finally resort into _eh_d\n            // can be limited to upper diagonal !\n            _eh_d = ub::zero_matrix<real_gwbse>( _bse_size , _bse_size );\n            #pragma omp parallel for\n            for ( size_t _v1 = 0 ; _v1 < _bse_vtotal ; _v1++){\n                for ( size_t _v2 = 0 ; _v2 < _bse_vtotal ; _v2++){\n                    size_t _index_vv = _bse_vtotal * _v1 + _v2;\n                    \n                    for ( size_t _c1 = 0 ; _c1 < _bse_ctotal ; _c1++){\n                        size_t _index_vc1 = _bse_ctotal * _v1 + _c1 ;\n                              \n                        \n                        for ( size_t _c2 = 0 ; _c2 < _bse_ctotal ; _c2++){\n                            size_t _index_vc2 = _bse_ctotal * _v2 + _c2 ;\n                            size_t _index_cc  = _bse_ctotal * _c1 + _c2;\n\n                            _eh_d( _index_vc1 , _index_vc2 ) = -_storage_prod( _index_vv , _index_cc ); \n                        }\n                    }\n                }\n            }\n            \n            return;\n        }\n        \n        \n         void GWBSE::BSE_d2_setup ( TCMatrix& _Mmn){\n            // gwbasis size\n            size_t _gwsize = _Mmn[_homo].size1();\n\n            // messy procedure, first get two matrices for occ and empty subbparts\n            // store occs directly transposed\n            ub::matrix<real_gwbse> _storage_cv = ub::zero_matrix<real_gwbse>(  _bse_vtotal * _bse_ctotal , _gwsize );\n            #pragma omp parallel for\n            for ( size_t _c1 = 0; _c1 < _bse_ctotal; _c1++){\n                const ub::matrix<real_gwbse>& Mmn = _Mmn[_c1 + _bse_cmin ];\n                for ( size_t _v2 = 0; _v2 < _bse_vtotal; _v2++){\n                    size_t _index_cv = _bse_vtotal * _c1 + _v2;\n                    for ( size_t _i_gw = 0 ; _i_gw < _gwsize ; _i_gw++) {\n                        _storage_cv( _index_cv , _i_gw ) = Mmn( _i_gw , _v2 + _bse_vmin );\n                    }\n                }\n            }\n         \n            ub::matrix<real_gwbse> _storage_vc = ub::zero_matrix<real_gwbse>( _gwsize, _bse_vtotal * _bse_ctotal );\n            #pragma omp parallel for\n            for ( size_t _v1 = 0; _v1 < _bse_vtotal; _v1++){\n                const ub::matrix<real_gwbse>& Mmn = _Mmn[_v1 + _bse_vmin];\n                for ( size_t _c2 = 0; _c2 < _bse_ctotal; _c2++){\n                    size_t _index_vc = _bse_ctotal * _v1 + _c2;\n                    for ( size_t _i_gw = 0 ; _i_gw < _gwsize ; _i_gw++) {\n                        _storage_vc( _i_gw , _index_vc ) = Mmn( _i_gw , _c2 + _bse_cmin );\n                    }\n                }\n            }\n            \n            if ( ! _do_bse_singlets )  _Mmn.Cleanup();\n            \n            // store elements in a vtotal^2 x ctotal^2 matrix\n            ub::matrix<real_gwbse> _storage_prod = ub::prod( _storage_cv , _storage_vc );\n       \n            \n            // now patch up _storage for screened interaction\n            #pragma omp parallel for\n            for ( size_t _i_gw = 0 ; _i_gw < _gwsize ; _i_gw++ ){  \n                if (_ppm_weight(_i_gw) < 1.e-9) {\n                    for ( size_t _v = 0 ; _v < (_bse_vtotal* _bse_ctotal) ; _v++){\n                    _storage_vc(  _i_gw , _v ) =0;\n                }\n                for ( size_t _c = 0 ; _c < (_bse_ctotal*_bse_vtotal) ; _c++){\n                    _storage_cv( _c, _i_gw  ) = 0;\n                }\n                }else{\n                double _ppm_factor = sqrt( _ppm_weight( _i_gw ));\n                for ( size_t _v = 0 ; _v < (_bse_vtotal* _bse_ctotal) ; _v++){\n                    _storage_vc(  _i_gw , _v ) = _ppm_factor * _storage_vc( _i_gw , _v );\n                }\n                for ( size_t _c = 0 ; _c < (_bse_ctotal*_bse_vtotal) ; _c++){\n                    _storage_cv( _c, _i_gw  ) = _ppm_factor * _storage_cv( _c , _i_gw  );\n                }\n                    }\n            }\n         \n            // multiply and subtract from _storage_prod\n            _storage_prod -= ub::prod( _storage_cv , _storage_vc );\n            \n            // free storage_v and storage_c\n            _storage_cv.resize(0,0);\n            _storage_vc.resize(0,0);\n            // finally resort into _eh_d\n            // can be limited to upper diagonal !\n            _eh_d2 = ub::zero_matrix<real_gwbse>( _bse_size , _bse_size );\n            #pragma omp parallel for\n            for ( size_t _v1 = 0 ; _v1 < _bse_vtotal ; _v1++){\n                for ( size_t _v2 = 0 ; _v2 < _bse_vtotal ; _v2++){ \n                    for ( size_t _c1 = 0 ; _c1 < _bse_ctotal ; _c1++){\n                        size_t _index_v1c1 = _bse_ctotal * _v1 + _c1 ;\n\n                        size_t _index_c1v2 =_bse_vtotal * _c1 + _v2;\n                        \n                        for ( size_t _c2 = 0 ; _c2 < _bse_ctotal ; _c2++){\n                            size_t _index_v2c2 = _bse_ctotal * _v2 + _c2 ;\n                            size_t _index_v1c2 = _bse_ctotal * _v1 + _c2;\n\n                            _eh_d2( _index_v1c1 , _index_v2c2 ) = -_storage_prod( _index_c1v2 , _index_v1c2 ); \n\n                        }\n                    }\n                }\n            }\n         return;   \n        }\n        \n        \n        \n        void GWBSE::BSE_x_setup( TCMatrix& _Mmn){\n            \n            /* unlike the fortran code, we store eh interaction directly in\n             * a suitable matrix form instead of a four-index array\n             */\n                        \n            // gwbasis size\n            size_t _gwsize = _Mmn[_homo].size1();\n            \n            // get a different storage for 3-center integrals we need\n            //cout<< \"Starting to set up \"<< endl;\n            ub::matrix<real_gwbse> _storage = ub::zero_matrix<real_gwbse>( _gwsize , _bse_size);\n            //cout<< \"Storage set up\"<< endl;\n         \n            // occupied levels\n            #pragma omp parallel for\n            for ( size_t _v = 0; _v < _bse_vtotal ; _v++ ){\n                // cout << \" act threads: \" << omp_get_thread_num( ) << \" total threads \" << omp_get_num_threads( ) << \" max threads \" << omp_get_max_threads( ) <<endl;\n                ub::matrix<real_gwbse>& Mmn = _Mmn[_v + _bse_vmin];\n                // empty levels\n                for (size_t _c =0 ; _c < _bse_ctotal ; _c++ ){\n                    size_t _index_vc = _bse_ctotal * _v + _c ;\n                    for (size_t _i_gw = 0 ; _i_gw < _gwsize ; _i_gw++ ){\n                        _storage( _i_gw, _index_vc ) = Mmn( _i_gw, _c + _bse_cmin);\n                    }\n                }\n            }\n            \n            _Mmn.Cleanup();   \n            // with this storage, _eh_x is obtained by matrix multiplication\n\t    _eh_x = ub::prod( ub::trans( _storage ), _storage ); \n            return;    \n        }\n        \n        \n        \n\n    }\n    \n \n};\n", "meta": {"hexsha": "632d1229d8a1fb5d05c651433bc08c89c354657b", "size": 18425, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/libxtp/gwbse/bse.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/bse.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/bse.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.5519630485, "max_line_length": 168, "alphanum_fraction": 0.4900949796, "num_tokens": 5275, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.7662936430859597, "lm_q2_score": 0.4493926344647597, "lm_q1q2_score": 0.3443667190399977}}
{"text": "//---------------------------------------------------------------------------//\n//!\n//! \\file   MonteCarlo_FormFactorSquared.hpp\n//! \\author Alex Robinson\n//! \\brief  The form factor squared declaration\n//!\n//---------------------------------------------------------------------------//\n\n#ifndef MONTE_CARLO_FORM_FACTOR_SQUARED_HPP\n#define MONTE_CARLO_FORM_FACTOR_SQUARED_HPP\n\n// Boost Includes\n#include <boost/units/quantity.hpp>\n\n// FRENSIE Includes\n#include \"Utility_InverseSquareCentimeterUnit.hpp\"\n#include \"Utility_InverseCentimeterUnit.hpp\"\n\nnamespace MonteCarlo{\n\n//! The form factor squared class\nclass FormFactorSquared\n{\n\npublic:\n\n  //! The form factor independent quantity type\n  typedef boost::units::quantity<Utility::Units::InverseCentimeter> ArgumentQuantity;\n\n  //! The form factor squared independent quantity type\n  typedef boost::units::quantity<Utility::Units::InverseSquareCentimeter> SquaredArgumentQuantity;\n\n  //! Default constructor\n  FormFactorSquared()\n  { /* ... */ }\n\n  //! Destructor\n  virtual ~FormFactorSquared()\n  { /* ... */ }\n\n  //! Evaluate the form factor squared\n  virtual double evaluate( const SquaredArgumentQuantity square_argument ) const = 0;\n  \n  //! Evaluate the form factor squared\n  double evaluate( const ArgumentQuantity argument ) const;\n\n  //! Sample from the form factor squared\n  virtual SquaredArgumentQuantity sample() const = 0;\n\n  //! Sample from the form factor squared in a subrange\n  virtual SquaredArgumentQuantity sampleInSubrange( const SquaredArgumentQuantity square_arg ) const = 0;\n\n  //! Return the max form factor squared value\n  virtual double getMaxValue() const = 0;\n\n  //! Return the min form factor squared value\n  virtual double getMinValue() const = 0;\n\n  //! Return the lower bound of the square argument\n  virtual SquaredArgumentQuantity getLowerBoundOfSquaredArgument() const = 0;\n\n  //! Return the upper bound of the square argument\n  virtual SquaredArgumentQuantity getUpperBoundOfSquaredArgument() const = 0;\n};\n\n// Evaluate the form factor squared\n/*! \\details This method is provided for convenience. Instead of passing in\n * a squared argument the original argument can be passed in and it will be\n * squared before evaluating the squared form factor.\n */\ninline double FormFactorSquared::evaluate(\n                                        const ArgumentQuantity argument ) const\n{\n  return this->evaluate( argument*argument );\n}\n\n} // end MonteCarlo namespace\n\n#endif // end MONTE_CARLO_FORM_FACTOR_SQUARED_HPP\n\n//---------------------------------------------------------------------------//\n// end MonteCarlo_FormFactorSquared.hpp\n//---------------------------------------------------------------------------//\n", "meta": {"hexsha": "4e9f2227940a82ed5a73bf1d33f1ad17dade194e", "size": 2698, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "packages/monte_carlo/collision/photon/src/MonteCarlo_FormFactorSquared.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_FormFactorSquared.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_FormFactorSquared.hpp", "max_forks_repo_name": "bam241/FRENSIE", "max_forks_repo_head_hexsha": "e1760cd792928699c84f2bdce70ff54228e88094", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2020-02-12T17:37:07.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-08T18:59:51.000Z", "avg_line_length": 32.119047619, "max_line_length": 105, "alphanum_fraction": 0.6634544107, "num_tokens": 533, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6297746074044134, "lm_q2_score": 0.5467381519846138, "lm_q1q2_score": 0.3443218050191247}}
{"text": "﻿// Copyright 2016 by Glukhov V. O. 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#include \"pooling_layer.hpp\"\n#include <armadillo>\n#include <cmath>\n\nnamespace cnn\n{\n\tnamespace nn\n\t{\n\t\tvoid MaxPoolingLayer::Forward(std::shared_ptr<arma::Cube<double>> input)\n\t\t{\n\t\t\tusing namespace arma;\n\n\t\t\tinput_ = input;\n\t\t\tuword output_height = (input_->n_rows - kernel_size_.height);\n\t\t\tuword output_width = (input_->n_cols - kernel_size_.width);\n\n#ifndef NDEBUG\n\t\t\tassert(output_height % stride_ == 0);\n\t\t\tassert(output_width % stride_ == 0);\n\t\t\t//TODO: for release build in case of working in another thread\n\t\t\t//TODO: we should use std::exception_ptr for thread-safety\n#endif\n\t\t\toutput_height = output_height / stride_ + 1;\n\t\t\toutput_width = output_width / stride_ + 1;\n\t\t\tif (!receptiveField_) {\n\t\t\t\treceptiveField_ = std::make_shared<Cube<double>>(output_height, output_width,\n\t\t\t\t                                                input_->n_slices, fill::zeros);\n\t\t\t} else {\n\t\t\t\treceptiveField_->set_size(output_height, output_width, input_->n_slices);\n\t\t\t\treceptiveField_->zeros();\n\t\t\t}\n\n\t\t\tconnectIndexes_.set_size(input_->n_rows, input_->n_cols, input_->n_slices);\n\t\t\tconnectIndexes_.zeros();\n\t\t\tdouble maxVal;\n\t\t\tuword rowIdx, colIdx;\n\n\t\t\tfor (uword d = 0; d < input_->n_slices; ++d) {\n\t\t\t\tuword out_col = 0;\n\t\t\t\tfor (uword c = 0; c < input_->n_cols; c += stride_) {\n\t\t\t\t\tuword out_row = 0;\n\t\t\t\t\tfor (uword r = 0; r < input_->n_rows; r += stride_) {\n\t\t\t\t\t\tmaxVal = input_->slice(d)(span(r, r + kernel_size_.height - 1),\n\t\t\t\t\t\t                          span(c, c + kernel_size_.height - 1)).max(rowIdx, colIdx);\n\t\t\t\t\t\t(*receptiveField_)(out_row, out_col, d) = maxVal;\n\t\t\t\t\t\tconnectIndexes_(r + rowIdx, c + colIdx, d) = 1;\n\t\t\t\t\t\t++out_row;\n\t\t\t\t\t}\n\t\t\t\t\t++out_col;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// currently common to use the activation function after convolution layer\n\t\t\t// instead of a subsample layer\n\t\t\tif (!activFunc_) {\n\t\t\t\toutput_ = receptiveField_;\n\t\t\t} else {\n\t\t\t\tif (!output_) {\n\t\t\t\t\toutput_ = std::make_shared<Cube<double>>(output_height, output_width,\n\t\t\t\t\t                                        input_->n_slices);\n\t\t\t\t} else {\n\t\t\t\t\toutput_->set_size(output_height, output_width, input_->n_slices);\n\t\t\t\t}\n\t\t\t\tactivFunc_->Compute(receptiveField_, output_);\n\t\t\t}\n\t\t}\n\n\t\tstd::pair<tensor4d, tensor4d> MaxPoolingLayer::Backward(\n\t\t\tconst std::shared_ptr<arma::Cube<double>>& prevLocalLoss)\n\t\t{\n\t\t\tusing namespace arma;\n#ifndef NDEBUG\n\t\t\tassert(prevLocalLoss);\n#endif\n\t\t\t// top layer was 1d. we need reshape error to 3d\n\t\t\tif (prevLocalLoss->n_slices == 1 && prevLocalLoss->n_cols == 1) {\n\t\t\t\t(*prevLocalLoss) = unvectorise(prevLocalLoss->get_ref(), output_->n_rows,\n\t\t\t\t                               output_->n_cols, output_->n_slices);\n\t\t\t}\n\n\t\t\tif (!localLoss_) {\n\t\t\t\tlocalLoss_ = std::make_shared<Cube<double>>(\n\t\t\t\t\tinput_->n_rows, input_->n_cols, input_->n_slices, fill::zeros);\n\t\t\t} else {\n\t\t\t\tlocalLoss_->set_size(input_->n_rows, input_->n_cols, input_->n_slices);\n\t\t\t\tlocalLoss_->zeros();\n\t\t\t}\n\t\t\tuword rowIdx, colIdx;\n\t\t\tfor (uword d = 0; d < input_->n_slices; ++d) {\n\t\t\t\tuword lossCol = 0;\n\t\t\t\tfor (uword c = 0; c < input_->n_cols; c += stride_) {\n\t\t\t\t\tuword lossRow = 0;\n\t\t\t\t\tfor (uword r = 0; r < input_->n_rows; r += stride_) {\n\t\t\t\t\t\t// from top to bottom propagates only connected losses\n\t\t\t\t\t\tconnectIndexes_.slice(d)(span(r, r + kernel_size_.height - 1),\n\t\t\t\t\t\t                         span(c, c + kernel_size_.height - 1)\n\t\t\t\t\t\t               ).max(rowIdx, colIdx);\n\t\t\t\t\t\t(*localLoss_)(r + rowIdx, c + colIdx, d) = (*prevLocalLoss)(\n\t\t\t\t\t\t\tlossRow, lossCol, d);\n\t\t\t\t\t\t++lossRow;\n\t\t\t\t\t}\n\t\t\t\t\t++lossCol;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (activFunc_) {\n\t\t\t\tlocalLoss_->transform([&] (double value) {\n\t\t\t\t\tif (!value) {\n\t\t\t\t\t\treturn value;\n\t\t\t\t\t} else\n\t\t\t\t\t\treturn activFunc_->Derivative(value);\n\t\t\t\t});\n\t\t\t}\n\n\t\t\t// pool layer doesn't has weights\n\t\t\treturn\n\t\t\t\t\tstd::make_pair(tensor4d(), tensor4d());\n\t\t}\n\n\t\tstd::pair<tensor4d, tensor4d> MaxPoolingLayer::Backward2nd(\n\t\t\tconst std::shared_ptr<arma::Cube<double>>& prevLocalLoss)\n\t\t{\n\t\t\tusing namespace arma;\n#ifndef NDEBUG\n\t\t\tassert(prevLocalLoss);\n#endif\n\t\t\t// top layer was 1d. we need reshape error to 3d\n\t\t\tif (prevLocalLoss->n_slices == 1 && prevLocalLoss->n_cols == 1) {\n\t\t\t\t(*prevLocalLoss) = unvectorise(prevLocalLoss->get_ref(), output_->n_rows,\n\t\t\t\t\t\t\t\t\t\t\t   output_->n_cols, output_->n_slices);\n\t\t\t}\n\n\t\t\tif (!localLoss_) {\n\t\t\t\tlocalLoss_ = std::make_shared<Cube<double>>(\n\t\t\t\t\tinput_->n_rows, input_->n_cols, input_->n_slices, fill::zeros);\n\t\t\t} else {\n\t\t\t\tlocalLoss_->set_size(input_->n_rows, input_->n_cols, input_->n_slices);\n\t\t\t\tlocalLoss_->zeros();\n\t\t\t}\n\t\t\tuword rowIdx, colIdx;\n\t\t\tfor (uword d = 0; d < input_->n_slices; ++d) {\n\t\t\t\tuword lossCol = 0;\n\t\t\t\tfor (uword c = 0; c < input_->n_cols; c += stride_) {\n\t\t\t\t\tuword lossRow = 0;\n\t\t\t\t\tfor (uword r = 0; r < input_->n_rows; r += stride_) {\n\t\t\t\t\t\t// from top to bottom propagates only connected losses\n\t\t\t\t\t\tconnectIndexes_.slice(d)(span(r, r + kernel_size_.height - 1),\n\t\t\t\t\t\t\t\t\t\t\t\t span(c, c + kernel_size_.height - 1)\n\t\t\t\t\t\t\t\t\t\t\t\t ).max(rowIdx, colIdx);\n\t\t\t\t\t\t(*localLoss_)(r + rowIdx, c + colIdx, d) = (*prevLocalLoss)(\n\t\t\t\t\t\t\tlossRow, lossCol, d);\n\t\t\t\t\t\t++lossRow;\n\t\t\t\t\t}\n\t\t\t\t\t++lossCol;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (activFunc_) {\n\t\t\t\tlocalLoss_->transform([&](double value) {\n\t\t\t\t\tif (!value) {\n\t\t\t\t\t\treturn value;\n\t\t\t\t\t} else\n\t\t\t\t\t\treturn std::pow(activFunc_->Derivative(value), 2);\n\t\t\t\t});\n\t\t\t}\n\n\t\t\t// pool layer doesn't has weights\n\t\t\treturn std::make_pair(tensor4d(), tensor4d());\n\t\t}\n\t}\n}\n", "meta": {"hexsha": "dba5a0b3549c088c2a035e559900fd8b9df02fdc", "size": 6029, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/cnn/pooling_layer.cpp", "max_stars_repo_name": "Matumba/CNN-Library", "max_stars_repo_head_hexsha": "09c2214a8bbc901da132253e2175b6a5579c4477", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-08-27T22:19:19.000Z", "max_stars_repo_stars_event_max_datetime": "2019-08-27T22:19:19.000Z", "max_issues_repo_path": "src/cnn/pooling_layer.cpp", "max_issues_repo_name": "Matumba/CNN-Library", "max_issues_repo_head_hexsha": "09c2214a8bbc901da132253e2175b6a5579c4477", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/cnn/pooling_layer.cpp", "max_forks_repo_name": "Matumba/CNN-Library", "max_forks_repo_head_hexsha": "09c2214a8bbc901da132253e2175b6a5579c4477", "max_forks_repo_licenses": ["Apache-2.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.5891891892, "max_line_length": 90, "alphanum_fraction": 0.6218278321, "num_tokens": 1734, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6992544335934766, "lm_q2_score": 0.49218813572079556, "lm_q1q2_score": 0.3441647360648741}}
{"text": "\n/******************************************************************************\n\n  Point-to-point implementation of the ICP registration algorithm for 3D point\n  clouds.\n\n  Copyright (c) 2012\n  Alexander Rukletsov <rukletsov@gmail.com>\n  Dzmitry Hlindzich <hlindzich@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 ICP_3D_HPP_507CF525_CC8A_4499_80D2_E8C8644603F5_\n#define ICP_3D_HPP_507CF525_CC8A_4499_80D2_E8C8644603F5_\n\n#include <vector>\n#include <utility>\n#include <boost/array.hpp>\n#include <boost/shared_ptr.hpp>\n#include <boost/noncopyable.hpp>\n#include <boost/function.hpp>\n#include <boost/assert.hpp>\n\n#include \"bo/core/vector.hpp\"\n#include \"bo/core/kdtree.hpp\"\n#include \"bo/math/mean.hpp\"\n#include \"bo/math/transformation_3d.hpp\"\n#include \"bo/math/blas_extensions.hpp\"\n#include \"bo/math/blas_conversions.hpp\"\n\n/* Usage example:\n\n    std::vector<Vertex> std_source();\n    ... // Initialize the source point cloud here.\n\n    boost::shared_ptr<std::vector<Vertex> > std_target_ptr = boost::shared_ptr<std::vector<Vertex> >\n    (new std::vector<Vertex>());\n    ... // Initialize the target point cloud here.\n\n    // Create an ICP registrator.\n    bo::registration::ICP3D<float> icp(std_source, std_target_ptr,\n    bo::distances::euclidean_distance<float, 3>);\n\n    // Initialize auxiliary variables.\n    // Iteration counter.\n    std::size_t iteration = 0;\n    // Norm of the transformation difference.\n    float epsilon = std::numeric_limits<float>::max();\n    // Distance between the source and target point clouds.\n    float distance = std::numeric_limits<float>::max();\n    // Transformation matrices.\n    bo::math::matrix<float> m1;\n    bo::math::matrix<float> m2;\n\n    // Iteratively register two point clouds.\n    while (iteration < max_allowed_iterations && epsilon >= min_transformation_epsilon)\n    {\n        // Cache the transformation from the previous iteration.\n        m1 = m2;\n\n        // Perform a new ICP registration step and update the current distance\n        // between the source and target.\n        distance = icp.next();\n\n        // Update the current transformation.\n        m2 = icp.current_transformation().matrix();\n\n        // Update the norm of the transformation difference.\n        if (iteration > 0)\n        {\n            bo::math::matrix<float> mdif = m2 - m1;\n            epsilon = bo::math::l1_norm(mdif);\n        }\n\n        ++iteration;\n    }\n\n    // The final transformation.\n    bo::Transformation3D<float> final_transformation = icp.current_transformation();\n\n    // The corresponding final transformation matrix.\n    bo::math::matrix<float> final_matrix = final_transformation.matrix();\n*/\n\nnamespace bo {\nnamespace registration {\n\ntemplate <typename RealType>\nclass ICP3D: public boost::noncopyable\n{\npublic:\n    typedef Vector<RealType, 3> Point3D;\n    typedef std::vector<Point3D> PointCloud;\n    typedef boost::shared_ptr<PointCloud> PointCloudPtr;\n    typedef boost::function<RealType (Point3D, Point3D)> Metric;\n    typedef math::Transformation3D<RealType> Transformation;\n\npublic:\n    ICP3D(const PointCloud& source, PointCloudPtr target, Metric dist_fun,\n          bool is_preprocess = true);\n\n    RealType next();\n    Transformation current_transformation() const;\n    const PointCloud& current_cloud() const;\n    const PointCloud& current_correspondence() const;\n\nprivate:\n\n    typedef bo::KDTree<3, Point3D, std::pointer_to_binary_function\n        <const Point3D&, std::size_t, RealType> > Point3DTree;\n    static RealType point_bac(const Point3D& p, std::size_t k);\n\n    void overlay_();\n    Point3D centroid_(PointCloud* cloud) const;\n    // Attention: the elements cloud2[i] must correspond to the elements cloud1[i].  \n    math::matrix<RealType> cross_covariance_(PointCloud* cloud1, PointCloud* cloud2,\n        const Point3D& centroid1, const Point3D& centroid2) const;\n    // Attention: the elements cloud2[i] must correspond to the elements cloud1[i].  \n    RealType distance_(PointCloud* cloud1, PointCloud* cloud2) const;\n    void update_current_transform_and_cloud_(const Transformation& m);\n\nprivate:\n    PointCloudPtr target_cloud_;\n    PointCloud current_cloud_;\n    PointCloud corresp_cloud_;\n    Transformation current_trans_;\n    Point3DTree tree_;   \n    Metric dist_fun_;\n};\n\n\n// Includes computing a kd-tree for the target point cloud.\ntemplate <typename RealType>\nICP3D<RealType>::ICP3D(const PointCloud& source, PointCloudPtr target,\n    Metric dist_fun, bool is_preprocess):\n    current_cloud_(source), target_cloud_(target), dist_fun_(dist_fun), \n    current_trans_(),\n    tree_(target->begin(), target->end(), std::ptr_fun(ICP3D<RealType>::point_bac))\n{    \n    if (is_preprocess)\n        overlay_();\n}\n\ntemplate <typename RealType>\nRealType ICP3D<RealType>::next()\n{\n    // Calculate the mass center of the current point cloud.\n    Point3D current_centroid = centroid_(&current_cloud_);\n\n    // Update the correspondence.\n    corresp_cloud_.clear();\n    for (typename PointCloud::const_iterator it = current_cloud_.begin(); it != current_cloud_.end(); ++it)\n    {\n        std::pair<typename Point3DTree::const_iterator, RealType> closest = tree_.find_nearest(*it);\n        corresp_cloud_.push_back(*closest.first);\n    }\n\n    // Calculate the mass center of the corresponding points.\n    Point3D corresp_centroid = centroid_(&corresp_cloud_);\n    \n    // Calculate the cross covariance for the current points and the target ones.\n    math::matrix<RealType> Spx = cross_covariance_(&current_cloud_, &corresp_cloud_, current_centroid,\n        corresp_centroid);\n\n    math::matrix<RealType> SpxT = trans(Spx);\n\n    // Create the asymmetrical matrix.\n    math::matrix<RealType> Apx = Spx - SpxT;\n\n    // Calculate the matrix trace.\n    RealType traceSpx = Spx(0, 0) + Spx(1, 1) + Spx(2, 2);\n\n    math::matrix<RealType> Bpx = Spx + SpxT -\n        traceSpx * math::identity_matrix<RealType>(3);\n\n    // Create the 4x4 matrix.\n    math::matrix<RealType> Qpx(4, 4);\n    \n    // Fill in the matrix.\n    // Block 1.\n    Qpx(0, 0) = traceSpx;\n    // Block 2.\n    Qpx(0, 1) = Apx(1, 2); \n    Qpx(0, 2) = Apx(2, 0);\n    Qpx(0, 3) = Apx(0, 1);\n    // Block 3.\n    Qpx(1, 0) = Apx(1, 2); \n    Qpx(2, 0) = Apx(2, 0);\n    Qpx(3, 0) = Apx(0, 1);\n    // Block 4.\n    math::subrange(Qpx, 1, 4, 1, 4) = math::subrange(Bpx, 0, 3, 0, 3);\n\n    math::eigen_symmetric(Qpx);\n\n    // Quaternion that defines the optimal rotation.\n//    Vector<RealType, 4> quaternion = math::to_bo_vector(math::column(Qpx, 3));\n    math::bounded_vector<RealType, 4> col(math::column(Qpx, 3));\n    Vector<RealType, 4> quaternion = math::to_bo_vector(col);\n\n    // Optimal translation. \n    Point3D translation = corresp_centroid - Transformation(quaternion) * current_centroid;\n\n    // Create the optimal transformation.\n    Transformation optimal_trans(quaternion, translation);\n\n    // Update the current point cloud and the transformation.\n    update_current_transform_and_cloud_(optimal_trans);\n\n    return distance_(&current_cloud_, &corresp_cloud_);\n}\n\ntemplate <typename RealType>\ntypename ICP3D<RealType>::Transformation ICP3D<RealType>::current_transformation() const\n{\n    return current_trans_;\n}\n\ntemplate <typename RealType>\nconst typename ICP3D<RealType>::PointCloud& ICP3D<RealType>::current_cloud() const\n{\n    return current_cloud_;\n}\n\ntemplate <typename RealType>\nconst typename ICP3D<RealType>::PointCloud& ICP3D<RealType>::current_correspondence() const\n{\n    return corresp_cloud_;\n}\n\ntemplate <typename RealType>\nvoid ICP3D<RealType>::overlay_()\n{\n    // Cloud shift using centroids.\n\n    Point3D translation = centroid_(target_cloud_.get()) - centroid_(&current_cloud_);\n\n    Transformation shift_transform(translation);\n    \n    // Update the current point cloud and the transformation.\n    update_current_transform_and_cloud_(shift_transform);\n}\n\ntemplate <typename RealType>\ntypename ICP3D<RealType>::Point3D ICP3D<RealType>::centroid_(PointCloud* cloud) const\n{\n    BOOST_ASSERT(cloud->size() > 0);\n    Point3D mass_center = math::mean(*cloud);\n\n    return mass_center;\n}\n\ntemplate <typename RealType>\nmath::matrix<RealType> ICP3D<RealType>::cross_covariance_(PointCloud* cloud1, PointCloud* cloud2,\n    const Point3D& centroid1, const Point3D& centroid2) const\n{\n    const std::size_t n = cloud1->size();\n\n    BOOST_ASSERT(cloud2->size() == n && n > 0);\n\n    math::matrix<RealType> m = math::zero_matrix<RealType>(3, 3);\n    math::matrix<RealType> p(3, 1);\n    math::matrix<RealType> x(1, 3);\n\n    for (std::size_t i = 0; i < n; ++i)\n    {\n        Point3D a = cloud1->at(i);\n        Point3D b = cloud2->at(i);\n\n        p(0, 0) = a[0] - centroid1[0];\n        p(1, 0) = a[1] - centroid1[1];\n        p(2, 0) = a[2] - centroid1[2];\n\n        x(0, 0) = b[0] - centroid2[0];\n        x(0, 1) = b[1] - centroid2[1];\n        x(0, 2) = b[2] - centroid2[2];\n\n        // Accumulate the elements.\n        // Warning: type overflow is possible here!\n        m = m + math::prod(p, x);\n    }   \n\n    m = m / n;\n\n    return m;\n}\n\ntemplate <typename RealType>\nRealType ICP3D<RealType>::distance_(PointCloud* cloud1, PointCloud* cloud2) const\n{   \n    const std::size_t n = cloud1->size();\n\n    BOOST_ASSERT(cloud2->size() == n);\n\n    RealType sum(0);\n\n    for (std::size_t i = 0; i < n; ++i)\n    {\n        Point3D a = cloud1->at(i);\n        Point3D b = cloud2->at(i);\n        sum += dist_fun_(a, b);\n    }\n\n    return sum;\n}\n\n// Point3D brackets accessor.\ntemplate <typename RealType>\ninline RealType ICP3D<RealType>::point_bac(const Point3D& p, std::size_t k)\n{ \n    return p[k]; \n}\n\ntemplate <typename RealType>\nvoid ICP3D<RealType>::update_current_transform_and_cloud_(const Transformation& m)\n{\n    // Update the current transformation.\n    current_trans_ = m * current_trans_;\n\n    // Update the current point cloud.\n    for (typename PointCloud::iterator it = current_cloud_.begin(); it != current_cloud_.end(); ++it)\n    {\n        *it = m * (*it);\n    }\n}\n\n} // namespace registration\n} // namespace bo\n\n#endif // ICP_3D_HPP_507CF525_CC8A_4499_80D2_E8C8644603F5_\n", "meta": {"hexsha": "16bf90416e88e2078cf9410c3413cc4e03cd5421", "size": 11360, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Bo/registration/icp_3d.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/registration/icp_3d.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/registration/icp_3d.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": 32.2727272727, "max_line_length": 107, "alphanum_fraction": 0.6832746479, "num_tokens": 2970, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6992544210587585, "lm_q2_score": 0.49218813572079556, "lm_q1q2_score": 0.3441647298954345}}
{"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__OCP_TO_QP_HPP_\n#define SMOOTH__FEEDBACK__OCP_TO_QP_HPP_\n\n/**\n * @file\n * @brief Formulate optimal control problem as a quadratic program\n */\n\n#include <Eigen/Core>\n#include <smooth/diff.hpp>\n\n#include \"collocation/mesh.hpp\"\n#include \"collocation/mesh_function.hpp\"\n#include \"ocp.hpp\"\n#include \"qp.hpp\"\n\nnamespace smooth::feedback {\n\n// \\cond\nnamespace detail {\n\n/**\n * @brief Working memory for ocp_to_qp\n */\nstruct OcpToQpWorkmemory\n{\n  MeshValue<1> cr_out;   /// @brief output of mesh_eval\n  MeshValue<2> int_out;  /// @brief output of mesh_integrate\n};\n\n/**\n * @brief Allocate a qp for ocp_to_qp_update()\n *\n * @param[out] qp quadratic program to allocate\n * @param[out] work working memory to allocate\n * @param[in] ocp input problem\n * @param[in] mesh time discretization\n */\ntemplate<diff::Type DT = diff::Type::Default>\nvoid ocp_to_qp_allocate(\n  QuadraticProgramSparse<double> & qp,\n  OcpToQpWorkmemory & work,\n  OCPType auto & ocp,\n  const MeshType auto & mesh)\n{\n  using ocp_t = typename std::decay_t<decltype(ocp)>;\n\n  using X = typename ocp_t::X;\n  using U = typename ocp_t::U;\n\n  static constexpr auto Nx = ocp_t::Nx;\n  static constexpr auto Nu = ocp_t::Nu;\n\n  /////////////////////////\n  //// VARIABLE LAYOUT ////\n  /////////////////////////\n\n  // [x0 x1 ... xN u0 u1 ... uN-1]\n\n  const auto N = mesh.N_colloc();\n\n  const auto xvar_L = Nx * (N + 1);\n  const auto uvar_L = Nu * N;\n\n  const auto dcon_L  = Nx * N;\n  const auto crcon_L = ocp_t::Ncr * N;\n  const auto cecon_L = ocp_t::Nce;\n\n  const auto dcon_B  = 0u;\n  const auto crcon_B = dcon_L;\n  const auto cecon_B = crcon_B + crcon_L;\n\n  const auto Nvar = xvar_L + uvar_L;\n  const auto Ncon = dcon_L + crcon_L + cecon_L;\n\n  // resize qp\n  qp.P.resize(Nvar, Nvar);\n  qp.q.setZero(Nvar);\n  qp.A.resize(Ncon, Nvar);\n  qp.l.setZero(Ncon);\n  qp.u.setZero(Ncon);\n\n  // sparsity pattern of A (row-major)\n  Eigen::VectorXi A_pattern = Eigen::VectorXi::Zero(Ncon);\n  for (auto ival = 0u, I0 = 0u; ival < mesh.N_ivals(); I0 += mesh.N_colloc_ival(ival), ++ival) {\n    const auto Ki = mesh.N_colloc_ival(ival);  // number of nodes in interval\n    A_pattern.segment(dcon_B + I0 * Nx, Ki * Nx) +=\n      Eigen::VectorXi::Constant(Ki * Nx, Nx + Ki + Nu);\n  }\n  A_pattern.segment(crcon_B, crcon_L).setConstant(Nx + Nu);\n  A_pattern.segment(cecon_B, cecon_L).setConstant(2 * Nx);\n  qp.A.reserve(A_pattern);\n\n  // sparsity pattern of P\n  Eigen::VectorXi P_pattern = Eigen::VectorXi::Zero(Nvar);\n  for (auto i = 0u; i < N; ++i) {\n    for (auto j = 0u; j < Nx; ++j) { P_pattern(Nx * i + j) = j + 1; }\n  }\n  for (auto j = 0u; j < Nx; ++j) { P_pattern(Nx * N + j) = Nx + j + 1; }\n  for (auto i = 0u; i < N; ++i) {\n    for (auto j = 0u; j < Nu; ++j) { P_pattern(Nx * (N + 1) + Nu * i + j) = Nx + (j + 1); }\n  }\n  qp.P.reserve(P_pattern);\n\n  // compute work stuff once to allocate pattern\n  const double tf = 1.;\n  auto xslin      = mesh.all_nodes() | transform([&](double) { return Identity<X>(); });\n  auto uslin      = mesh.all_nodes() | transform([&](double) { return Identity<U>(); });\n\n  work.int_out.lambda.setConstant(1, 1);\n  mesh_eval<1, DT>(work.cr_out, mesh, ocp.cr, 0, tf, xslin, uslin);       // allocates work.cr_out\n  mesh_integrate<2, DT>(work.int_out, mesh, ocp.g, 0, tf, xslin, uslin);  // allocates work.int_out\n\n  work.cr_out.dF.makeCompressed();\n  work.int_out.dF.makeCompressed();\n  work.int_out.d2F.makeCompressed();\n}\n\n/// @brief ocp_to_qp_update: cost part\ntemplate<diff::Type DT = diff::Type::Default>\nvoid ocp_to_qp_update_cost(\n  QuadraticProgramSparse<double> & qp,\n  OcpToQpWorkmemory & work,\n  OCPType auto & ocp,\n  const MeshType auto & mesh,\n  double tf,\n  auto && xl_fun,\n  auto && ul_fun)\n{\n  using ocp_t = typename std::decay_t<decltype(ocp)>;\n  using X     = typename ocp_t::X;\n\n  static constexpr auto Nx = ocp_t::Nx;\n  static constexpr auto Nu = ocp_t::Nu;\n  static constexpr auto Nq = ocp_t::Nq;\n  const double t0          = 0.;\n\n  static_assert(ocp_t::Nq == 1, \"exactly one integral supported in ocp_to_qp\");\n\n  /////////////////////////\n  //// VARIABLE LAYOUT ////\n  /////////////////////////\n\n  const auto N      = mesh.N_colloc();\n  const auto xvar_L = Nx * (N + 1);\n  const auto uvar_L = Nu * N;\n  const auto xvar_B = 0u;\n  const auto uvar_B = xvar_L;\n\n  ////////////////////////\n  //// ZERO VARIABLES ////\n  ////////////////////////\n\n  set_zero(qp.P);\n  qp.q.setZero();\n\n  //////////////////////////////\n  //// LINEARIZATION POINTS ////\n  //////////////////////////////\n\n  const X xl0 = xl_fun(0.);\n  const X xlf = xl_fun(tf);\n\n  auto xslin = mesh.all_nodes() | transform([&](double t) { return xl_fun(t0 + (tf - t0) * t); });\n  auto uslin = mesh.all_nodes() | transform([&](double t) { return ul_fun(t0 + (tf - t0) * t); });\n\n  const Eigen::Vector<double, 1> ql{1.};\n\n  ///////////////////////\n  //// INTEGRAL COST ////\n  ///////////////////////\n\n  const auto & [th, dth, d2th] = diff::dr<2, DT>(ocp.theta, wrt(tf, xl0, xlf, ql));\n\n  const Eigen::Vector<double, Nx> qo_x0 = dth.middleCols(1, Nx).transpose();\n  const Eigen::Vector<double, Nx> qo_xf = dth.middleCols(1 + Nx, Nx).transpose();\n  const Eigen::Vector<double, Nq> qo_q  = dth.middleCols(1 + 2 * Nx, Nq).transpose();\n\n  mesh_integrate<2, DT>(work.int_out, mesh, ocp.g, 0, tf, xslin, uslin);\n\n  // clang-format off\n  block_add(qp.P, 0, 0, work.int_out.d2F.block(2, 2, xvar_L + uvar_L, xvar_L + uvar_L), qo_q.x(), true);\n\n  qp.q.segment(xvar_B, xvar_L) = qo_q.x() * work.int_out.dF.middleCols(2, xvar_L).transpose();\n  qp.q.segment(uvar_B, uvar_L) = qo_q.x() * work.int_out.dF.middleCols(2 + xvar_L, uvar_L).transpose();\n  // clang-format on\n\n  ///////////////////////\n  //// ENDPOINT COST ////\n  ///////////////////////\n\n  block_add(qp.P, 0, 0, d2th.block(1, 1, Nx, Nx), 0.5, true);                      // d2q / dx0x0\n  block_add(qp.P, 0, Nx * N, d2th.block(1, 1 + Nx, Nx, Nx), 0.5, true);            // d2q / dx0xf\n  block_add(qp.P, Nx * N, Nx * N, d2th.block(1 + Nx, 1 + Nx, Nx, Nx), 0.5, true);  // d2q / dxfxf\n\n  qp.q.segment(0, Nx) += qo_x0;       // dq / dx0\n  qp.q.segment(Nx * N, Nx) += qo_xf;  // dq / dxf\n}\n\n/// @brief ocp_to_qp_update: dyn part\ntemplate<diff::Type DT = diff::Type::Default>\nvoid ocp_to_qp_update_dyn(\n  QuadraticProgramSparse<double> & qp,\n  [[maybe_unused]] OcpToQpWorkmemory & work,\n  OCPType auto & ocp,\n  const MeshType auto & mesh,\n  double tf,\n  auto && xl_fun,\n  auto && ul_fun)\n{\n  using utils::zip;\n  using namespace std::views;\n  using ocp_t = typename std::decay_t<decltype(ocp)>;\n  using X     = typename ocp_t::X;\n\n  static constexpr auto Nx = ocp_t::Nx;\n  static constexpr auto Nu = ocp_t::Nu;\n  const double t0          = 0.;\n\n  static_assert(ocp_t::Nq == 1, \"exactly one integral supported in ocp_to_qp\");\n\n  /////////////////////////\n  //// VARIABLE LAYOUT ////\n  /////////////////////////\n\n  const auto N      = mesh.N_colloc();\n  const auto xvar_L = Nx * (N + 1);\n  const auto dcon_L = Nx * N;\n  const auto xvar_B = 0u;\n  const auto uvar_B = xvar_L;\n  const auto dcon_B = 0u;\n\n  ////////////////////////\n  //// ZERO VARIABLES ////\n  ////////////////////////\n\n  set_zero(qp.A.middleRows(dcon_B, dcon_L));\n\n  /////////////////////////////////\n  //// COLLOCATION CONSTRAINTS ////\n  /////////////////////////////////\n\n  for (auto ival = 0u, M = 0u; ival < mesh.N_ivals(); M += mesh.N_colloc_ival(ival), ++ival) {\n    const auto Ki = mesh.N_colloc_ival(ival);  // number of nodes in interval\n\n    const auto [alpha, Dus] = mesh.interval_diffmat_unscaled(ival);\n\n    // in each interval the collocation constraint is\n    // [A0 x0 ... Ak-1 xk-1 0]  + [B0 u0 ... Bk-1 uk-1] + [E0 ... Ek-1] = alpha * X Dus\n\n    for (const auto & [i, tau_i] : zip(iota(0u, Ki), mesh.interval_nodes(ival))) {\n      const auto t_i             = t0 + (tf - t0) * tau_i;             // unscaled time\n      const auto & [xl_i, dxl_i] = diff::dr<1, DT>(xl_fun, wrt(t_i));  // x-lin\n      const auto ul_i            = ul_fun(t_i);                        // u-lin\n\n      // linearize dynamics and insert new constraint A xi + B ui + E = [x0 ... XNi] di\n\n      const auto & [f_i, df_i] = diff::dr<1, DT>(ocp.f, wrt(t_i, xl_i, ul_i));\n\n      // clang-format off\n      block_add(qp.A, dcon_B + (M + i) * Nx, xvar_B + (M + i) * Nx, df_i.template middleCols<Nx>(1), tf);        // A\n      block_add(qp.A, dcon_B + (M + i) * Nx, uvar_B + (M + i) * Nu, df_i.template middleCols<Nu>(1 + Nx), tf);   // B\n      // clang-format on\n\n      if constexpr (!IsCommutative<X>) {\n        block_add(qp.A, dcon_B + (M + i) * Nx, xvar_B + (M + i) * Nx, ad<X>(f_i + dxl_i), -tf / 2);\n      }\n\n      for (auto j = 0u; j < Ki + 1; ++j) {\n        for (auto diag = 0u; diag < Nx; ++diag) {\n          qp.A.coeffRef(dcon_B + (M + i) * Nx + diag, (M + j) * Nx + diag) -= alpha * Dus(j, i);\n        }\n      }\n\n      qp.l.segment(dcon_B + (M + i) * Nx, Nx) = -tf * (f_i - dxl_i);\n      qp.u.segment(dcon_B + (M + i) * Nx, Nx) = qp.l.segment(dcon_B + (M + i) * Nx, Nx);\n    }\n  }\n}\n\n/// @brief ocp_to_qp_update: running constraints part\ntemplate<diff::Type DT = diff::Type::Default>\nvoid ocp_to_qp_update_cr(\n  QuadraticProgramSparse<double> & qp,\n  OcpToQpWorkmemory & work,\n  OCPType auto & ocp,\n  const MeshType auto & mesh,\n  double tf,\n  auto && xl_fun,\n  auto && ul_fun)\n{\n  using ocp_t = typename std::decay_t<decltype(ocp)>;\n\n  static constexpr auto Nx = ocp_t::Nx;\n  static constexpr auto Nu = ocp_t::Nu;\n\n  const double t0 = 0.;\n\n  /////////////////////////\n  //// VARIABLE LAYOUT ////\n  /////////////////////////\n\n  const auto N       = mesh.N_colloc();\n  const auto xvar_L  = Nx * (N + 1);\n  const auto uvar_L  = Nu * N;\n  const auto dcon_L  = Nx * N;\n  const auto crcon_L = ocp_t::Ncr * N;\n  const auto crcon_B = dcon_L;\n\n  //////////////////////////////\n  //// LINEARIZATION POINTS ////\n  //////////////////////////////\n\n  auto xslin = mesh.all_nodes() | transform([&](double t) { return xl_fun(t0 + (tf - t0) * t); });\n  auto uslin = mesh.all_nodes() | transform([&](double t) { return ul_fun(t0 + (tf - t0) * t); });\n\n  /////////////////////////////\n  //// RUNNING CONSTRAINTS ////\n  /////////////////////////////\n\n  mesh_eval<1, DT>(work.cr_out, mesh, ocp.cr, 0, tf, xslin, uslin);\n\n  block_write(qp.A, crcon_B, 0, work.cr_out.dF.middleCols(2, xvar_L + uvar_L));\n  qp.l.segment(crcon_B, crcon_L) = ocp.crl.replicate(N, 1) - work.cr_out.F;\n  qp.u.segment(crcon_B, crcon_L) = ocp.cru.replicate(N, 1) - work.cr_out.F;\n}\n\n/// @brief ocp_to_qp_update: end constraints part\ntemplate<diff::Type DT = diff::Type::Default>\nvoid ocp_to_qp_update_ce(\n  QuadraticProgramSparse<double> & qp,\n  [[maybe_unused]] OcpToQpWorkmemory & work,\n  OCPType auto & ocp,\n  const MeshType auto & mesh,\n  double tf,\n  auto && xl_fun,\n  [[maybe_unused]] auto && ul_fun)\n{\n  using ocp_t = typename std::decay_t<decltype(ocp)>;\n  using X     = typename ocp_t::X;\n\n  static constexpr auto Nx = ocp_t::Nx;\n\n  /////////////////////////\n  //// VARIABLE LAYOUT ////\n  /////////////////////////\n\n  const auto N       = mesh.N_colloc();\n  const auto xvar_L  = Nx * (N + 1);\n  const auto xvar_B  = 0u;\n  const auto dcon_L  = Nx * N;\n  const auto crcon_L = ocp_t::Ncr * N;\n  const auto cecon_L = ocp_t::Nce;\n  const auto crcon_B = dcon_L;\n  const auto cecon_B = crcon_B + crcon_L;\n\n  //////////////////////////////\n  //// LINEARIZATION POINTS ////\n  //////////////////////////////\n\n  const X xl0 = xl_fun(0.);\n  const X xlf = xl_fun(tf);\n\n  //////////////////////////////\n  //// ENDPOINT CONSTRAINTS ////\n  //////////////////////////////\n\n  const Eigen::Vector<double, 1> ql{1.};\n  const auto & [ceval, dceval] = diff::dr<1, DT>(ocp.ce, wrt(tf, xl0, xlf, ql));\n\n  block_write(qp.A, cecon_B, xvar_B, dceval.middleCols(1, Nx));                     // dce / dx0\n  block_write(qp.A, cecon_B, xvar_B + xvar_L - Nx, dceval.middleCols(1 + Nx, Nx));  // dce / dxf\n\n  qp.l.segment(cecon_B, cecon_L) = ocp.cel - ceval;\n  qp.u.segment(cecon_B, cecon_L) = ocp.ceu - ceval;\n}\n\n/**\n * @brief Update a qp for ocp_to_qp_update()\n *\n * @param[out] qp quadratic program\n * @param[in, out] work\n * @param[in] ocp input problem\n * @param[in] mesh time discretization\n * @param[in] tf time horizon\n * @param[in] xl_fun state linearization (must be differentiable w.r.t. time)\n * @param[in] ul_fun input linearization\n */\ntemplate<diff::Type DT = diff::Type::Default>\nvoid ocp_to_qp_update(\n  QuadraticProgramSparse<double> & qp,\n  [[maybe_unused]] OcpToQpWorkmemory & work,\n  OCPType auto & ocp,\n  const MeshType auto & mesh,\n  double tf,\n  const auto & xl_fun,\n  [[maybe_unused]] const auto & ul_fun)\n{\n  ocp_to_qp_update_cost<DT>(qp, work, ocp, mesh, tf, xl_fun, ul_fun);\n  ocp_to_qp_update_dyn<DT>(qp, work, ocp, mesh, tf, xl_fun, ul_fun);\n  ocp_to_qp_update_cr<DT>(qp, work, ocp, mesh, tf, xl_fun, ul_fun);\n  ocp_to_qp_update_ce<DT>(qp, work, ocp, mesh, tf, xl_fun, ul_fun);\n}\n\n}  // namespace detail\n// \\endcond\n\n/**\n * @brief Formulate an optimal control problem as a quadratic program via linearization.\n *\n * @param ocp input problem\n * @param mesh time discretization\n * @param tf time horizon\n * @param xl_fun state linearization (must be differentiable w.r.t. time)\n * @param ul_fun input linearization\n *\n * @return sparse quadratic program for a flattened formulation of ocp.\n *\n * @note allocates memory for each call. To reduce memory allocation for repeated calls, see\n * ocp_to_qp_allocate() and ocp_to_qp_update().\n *\n * @see qpsol_to_ocpsol()\n */\ntemplate<diff::Type DT = diff::Type::Default>\nQuadraticProgramSparse<double> ocp_to_qp(\n  const OCPType auto & ocp, const MeshType auto & mesh, double tf, auto && xl_fun, auto && ul_fun)\n{\n  QuadraticProgramSparse<double> qp;\n  detail::OcpToQpWorkmemory work;\n\n  detail::ocp_to_qp_allocate<DT>(qp, work, ocp, mesh);\n  detail::ocp_to_qp_update<DT>(qp, work, ocp, mesh, tf, xl_fun, ul_fun);\n\n  qp.A.makeCompressed();\n  qp.P.makeCompressed();\n\n  return qp;\n}\n\n/**\n * @brief Convert QP solution to OCP solution\n *\n * If qp_sol solves a QP obtained via ocp_to_qp(), then qpsol_to_ocpsol(qp_sol)\n * is the corrensponding OCP solution.\n *\n * @param ocp optimal control problem\n * @param mesh discretization mesh\n * @param qpsol solution to quadratic program obtained via ocp_to_qp()\n * @param tf final time used in ocp_to_qp()\n * @param xl_fun state linearization trajectory used in ocp_to_qp()\n * @param ul_fun input linearization trajectory used in ocp_to_qp()\n *\n * @see ocp_to_qp()\n */\nauto qpsol_to_ocpsol(\n  const OCPType auto & ocp,\n  const MeshType auto & mesh,\n  const QPSolution<-1, -1, double> & qpsol,\n  double tf,\n  auto && xl_fun,\n  auto && ul_fun)\n{\n  using ocp_t = std::decay_t<decltype(ocp)>;\n\n  using X = typename ocp_t::X;\n  using U = typename ocp_t::U;\n\n  static constexpr int Nx  = ocp_t::Nx;\n  static constexpr int Nu  = ocp_t::Nu;\n  static constexpr int Nq  = ocp_t::Nq;\n  static constexpr int Ncr = ocp_t::Ncr;\n  static constexpr int Nce = ocp_t::Nce;\n\n  const auto N = mesh.N_colloc();\n\n  const auto xvar_L = Nx * (N + 1);\n  const auto uvar_L = Nu * N;\n\n  const auto xvar_B    = 0u;\n  const auto uvar_B    = xvar_L;\n  Eigen::MatrixXd Xmat = qpsol.primal.segment(xvar_B, xvar_L).reshaped(Nx, N + 1);\n  Eigen::MatrixXd Umat = qpsol.primal.segment(uvar_B, uvar_L).reshaped(Nu, N);\n\n  auto xfun = [t0     = 0.,\n               tf     = tf,\n               mesh   = mesh,\n               Xmat   = std::move(Xmat),\n               xl_fun = std::forward<decltype(xl_fun)>(xl_fun)](double t) -> X {\n    const auto tngnt =\n      mesh.template eval<Eigen::Vector<double, Nx>>((t - t0) / (tf - t0), Xmat.colwise(), 0, true);\n    return rplus(xl_fun(t), tngnt);\n  };\n\n  auto ufun = [t0     = 0.,\n               tf     = tf,\n               mesh   = mesh,\n               Umat   = std::move(Umat),\n               ul_fun = std::forward<decltype(ul_fun)>(ul_fun)](double t) -> U {\n    const auto tngnt =\n      mesh.template eval<Eigen::Vector<double, Nu>>((t - t0) / (tf - t0), Umat.colwise(), 0, false);\n    return rplus(ul_fun(t), tngnt);\n  };\n\n  return OCPSolution<X, U, Nq, Nce, Ncr>{\n    .t0 = 0.,\n    .tf = tf,\n    .u  = std::move(ufun),\n    .x  = std::move(xfun),\n  };\n}\n\n}  // namespace smooth::feedback\n\n#endif  // SMOOTH__FEEDBACK__OCP_TO_QP_HPP_\n", "meta": {"hexsha": "9a1b67dd0fd54a285d750cf05a1313cf94af35af", "size": 17420, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/smooth/feedback/ocp_to_qp.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/ocp_to_qp.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/ocp_to_qp.hpp", "max_forks_repo_name": "tgurriet/smooth_feedback", "max_forks_repo_head_hexsha": "1f926cb4269741ddc09ba048af5bea5e0390a053", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.2592592593, "max_line_length": 117, "alphanum_fraction": 0.6061997704, "num_tokens": 5535, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6039318337259584, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.3441521567221512}}
{"text": "//==============================================================================\n//         Copyright 2003 - 2012   LASMEA UMR 6602 CNRS/Univ. Clermont II\n//         Copyright 2009 - 2013   LRI    UMR 8623 CNRS/Univ Paris Sud XI\n//\n//          Distributed under the Boost Software License, Version 1.0.\n//                 See accompanying file LICENSE.txt or copy at\n//                     http://www.boost.org/LICENSE_1_0.txt\n//==============================================================================\n#ifndef NT2_LINALG_FUNCTIONS_FACTORIZATIONS_CHOL_HPP_INCLUDED\n#define NT2_LINALG_FUNCTIONS_FACTORIZATIONS_CHOL_HPP_INCLUDED\n\n#include <nt2/linalg/functions/lu.hpp>\n#include <nt2/include/functions/qr.hpp>\n#include <nt2/include/functions/is_gtz.hpp>\n#include <nt2/include/functions/potrf.hpp>\n#include <nt2/include/functions/tie.hpp>\n#include <nt2/include/functions/triu.hpp>\n#include <nt2/include/functions/tril.hpp>\n#include <nt2/linalg/details/utility/f77_wrapper.hpp>\n#include <nt2/linalg/details/utility/lapack_verify.hpp>\n#include <nt2/linalg/options.hpp>\n#include <nt2/core/container/dsl/as_terminal.hpp>\n#include <nt2/core/container/table/table.hpp>\n#include <nt2/core/container/colon/colon.hpp>\n#include <boost/assert.hpp>\n#include <boost/dispatch/attributes.hpp>\n\nnamespace nt2 { namespace ext\n{\n  //============================================================================\n  //CHOL Scalar\n  //============================================================================\n  BOOST_DISPATCH_IMPLEMENT  ( chol_, 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      BOOST_ASSERT_MSG(is_gtz(a0), \"Matrix must be positive definite\");\n      return  nt2::sqrt(a0);\n    }\n  };\n\n  BOOST_DISPATCH_IMPLEMENT  ( chol_, tag::cpu_\n                            , (A0)(A1)\n                            , (scalar_<unspecified_<A0> >)\n                              (unspecified_<A1>)\n                            )\n  {\n    typedef typename nt2::meta::as_real<A0>::type result_type;\n\n    BOOST_FORCEINLINE result_type operator()(const A0& a0, const A1&) const\n    {\n      BOOST_ASSERT_MSG(is_gtz(a0), \"Matrix must be positive definite\");\n      return nt2::sqrt(a0);\n    }\n  };\n\n  BOOST_DISPATCH_IMPLEMENT  ( chol_, tag::cpu_\n                            , (A0)(A1)(A2)\n                            , (scalar_<unspecified_<A0> >)\n                              (unspecified_<A1>)\n                              (unspecified_<A2>)\n                            )\n  {\n    typedef typename nt2::meta::as_real<A0>::type result_type;\n\n    BOOST_FORCEINLINE result_type operator()(const A0& a0, const A1&, const A2&) const\n    {\n      BOOST_ASSERT_MSG(is_gtz(a0), \"Matrix must be positive definite\");\n      return nt2::sqrt(a0);\n    }\n  };\n  //============================================================================\n  //Cholesky factorization\n  //============================================================================\n  BOOST_DISPATCH_IMPLEMENT  ( chol_, tag::cpu_\n                            , (A0)(N0)(A1)(N1)\n                            , ((node_<A0, nt2::tag::chol_\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 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\n    //==========================================================================\n    /// INTERNAL ONLY - R = chol(A)\n    BOOST_FORCEINLINE\n    void eval ( A0& a0 ,  A1& a1\n              , boost::mpl::long_<1> const& , boost::mpl::long_<1> const&\n              ) const\n    {\n      NT2_AS_TERMINAL_INOUT(o_semantic, a\n                           , boost::proto::child_c<0>(a0)\n                           , boost::proto::child_c<0>(a1));\n      NT2_LAPACK_VERIFY(nt2::potrf(boost::proto::value(a),'U'));\n      boost::proto::child_c<0>(a1) = nt2::triu(a);\n    }\n\n    //==========================================================================\n    /// INTERNAL ONLY - L = chol(A,lower_/upper_)\n    BOOST_FORCEINLINE\n    void eval ( A0& a0 , A1& a1\n              , boost::mpl::long_<2> const& , boost::mpl::long_<1> const&\n              ) const\n    {\n      eval( a0, a1, N0(), N1()\n          , boost::proto::value(boost::proto::child_c<1>(a0))\n          );\n    }\n\n    //==========================================================================\n    /// INTERNAL ONLY - L = chol(A,lower_)\n    BOOST_FORCEINLINE\n    void eval( A0& a0 , A1& a1\n              , boost::mpl::long_<2> const& , boost::mpl::long_<1> const&\n              , nt2::policy<ext::lower_> const&\n              ) const\n    {\n      NT2_AS_TERMINAL_INOUT(o_semantic, a\n                           , boost::proto::child_c<0>(a0)\n                           , boost::proto::child_c<0>(a1));\n      NT2_LAPACK_VERIFY(nt2::potrf(boost::proto::value(a),'L'));\n      boost::proto::child_c<0>(a1) = nt2::tril(a);\n    }\n\n\n    //==========================================================================\n    /// INTERNAL ONLY - R = chol(A,upper_)\n    BOOST_FORCEINLINE\n    void eval ( A0& a0 , A1& a1\n              , boost::mpl::long_<2> const& , boost::mpl::long_<1> const&\n              , nt2::policy<ext::upper_> const&\n              ) const\n    {\n      eval(a0,a1,boost::mpl::long_<1>(),N1());\n    }\n\n\n    //==========================================================================\n    /// INTERNAL ONLY - [R,P] = chol(A)\n    BOOST_FORCEINLINE\n    void eval ( A0& a0 , A1& a1\n              , boost::mpl::long_<1> const& , boost::mpl::long_<2> const&\n              ) const\n    {\n      NT2_AS_TERMINAL_INOUT(o_semantic, a\n                           , boost::proto::child_c<0>(a0)\n                           , boost::proto::child_c<0>(a1));\n      nt2_la_int info = nt2::potrf(boost::proto::value(a),'U');\n      BOOST_ASSERT_MSG(info >= 0, \"invalid parameter in potrf call\");\n      if (info == 0)\n        boost::proto::child_c<0>(a1) = nt2::triu(a);\n      else\n        boost::proto::child_c<0>(a1) = nt2::triu(a(nt2::_(1, info-1), nt2::_(1, info-1)));\n      boost::proto::child_c<1>(a1) = info;\n    }\n\n    //==========================================================================\n    /// INTERNAL ONLY - [R,P] = chol(A,lower_/upper_)\n    BOOST_FORCEINLINE\n    void eval ( A0& a0 , A1& a1\n              , boost::mpl::long_<2> const& , boost::mpl::long_<2> const&\n              ) const\n    {\n      eval( a0, a1, N0(), N1()\n          , boost::proto::value(boost::proto::child_c<1>(a0))\n          );\n    }\n\n    //==========================================================================\n    /// INTERNAL ONLY - L = chol(A, raw_,lower_/upper_)\n    BOOST_FORCEINLINE\n    void eval ( A0& a0 , A1& a1\n              , boost::mpl::long_<3> const& , boost::mpl::long_<2> const&\n              ) const\n    {\n      eval( a0, a1, N0(), N1()\n          , boost::proto::value(boost::proto::child_c<1>(a0))\n          , boost::proto::value(boost::proto::child_c<2>(a0))\n          );\n    }\n\n    //==========================================================================\n    /// INTERNAL ONLY - [L,P] = chol(A,lower_)\n    BOOST_FORCEINLINE\n    void eval ( A0& a0 , A1& a1\n              , boost::mpl::long_<2> const& , boost::mpl::long_<2> const&\n              , nt2::policy<ext::lower_> const&\n              ) const\n    {\n      NT2_AS_TERMINAL_INOUT(o_semantic, a\n                           , boost::proto::child_c<0>(a0)\n                           , boost::proto::child_c<0>(a1));\n      nt2_la_int info = nt2::potrf(boost::proto::value(a),'L');\n      BOOST_ASSERT_MSG(info >= 0, \"invalid parameter in potrf call\");\n      if (info == 0)\n        boost::proto::child_c<0>(a1) = nt2::tril(a);\n      else\n        boost::proto::child_c<0>(a1) = nt2::tril(a(nt2::_(1, info-1), nt2::_(1, info-1)));\n      boost::proto::child_c<1>(a1) = info;\n    }\n\n    //==========================================================================\n    /// INTERNAL ONLY - [R,P] = chol(A,upper_)\n    BOOST_FORCEINLINE\n    void eval ( A0& a0 , A1& a1\n              , boost::mpl::long_<2> const& , boost::mpl::long_<2> const&\n              , nt2::policy<ext::upper_> const&\n              ) const\n    {\n      eval(a0,a1,\n           boost::mpl::long_<1>(),N1());\n    }\n\n    //==========================================================================\n    /// INTERNAL ONLY - [L,P] = chol(A,raw_)\n    BOOST_FORCEINLINE\n    void eval ( A0& a0 , A1& a1\n              , boost::mpl::long_<2> const& , boost::mpl::long_<2> const&\n              , nt2::policy<ext::raw_> const&\n              ) const\n    {\n      NT2_AS_TERMINAL_INOUT(o_semantic, a\n                           , boost::proto::child_c<0>(a0)\n                           , boost::proto::child_c<0>(a1));\n      nt2_la_int info = nt2::potrf(boost::proto::value(a),'U');\n      BOOST_ASSERT_MSG(info >= 0, \"invalid parameter in potrf call\");\n      assign_swap( boost::proto::child_c<0>(a1), a);\n      boost::proto::child_c<1>(a1) = info;\n    }\n\n    //==========================================================================\n    /// INTERNAL ONLY - [L,P] = chol(A,raw_,lower_)\n    BOOST_FORCEINLINE\n    void eval ( A0& a0 , A1& a1\n              , boost::mpl::long_<3> const& , boost::mpl::long_<2> const&\n              , nt2::policy<ext::raw_> const&\n              , nt2::policy<ext::lower_> const&\n              ) const\n    {\n      NT2_AS_TERMINAL_INOUT(o_semantic, a\n                           , boost::proto::child_c<0>(a0)\n                           , boost::proto::child_c<0>(a1));\n      nt2_la_int info = nt2::potrf(boost::proto::value(a),'L');\n      BOOST_ASSERT_MSG(info >= 0, \"invalid parameter in potrf call\");\n      assign_swap( boost::proto::child_c<0>(a1), a);\n      boost::proto::child_c<1>(a1) =  info;\n    }\n\n    //==========================================================================\n    /// INTERNAL ONLY - [L,P] = chol(A,raw_,upper_)\n    BOOST_FORCEINLINE\n    void eval ( A0& a0 , A1& a1\n              , boost::mpl::long_<3> const& , boost::mpl::long_<2> const&\n              , nt2::policy<ext::raw_> const&\n              , nt2::policy<ext::upper_> const&\n              ) const\n    {\n      eval(a0, a1\n          , boost::mpl::long_<2>(), N1(), nt2::policy<ext::raw_>());\n    }\n\n    //==========================================================================\n    /// INTERNAL ONLY - [L,P] = chol(A,upper_,raw_)\n    BOOST_FORCEINLINE\n    void eval ( A0& a0 , A1& a1\n              , boost::mpl::long_<3> const& , boost::mpl::long_<2> const&\n              , nt2::policy<ext::upper_> const&\n              , nt2::policy<ext::raw_> const&\n              ) const\n    {\n      eval(a0, a1\n          , boost::mpl::long_<2>(), N1(), nt2::policy<ext::raw_>());\n    }\n\n    //==========================================================================\n    /// INTERNAL ONLY - [L,P] = chol(A,lower_,raw_)\n    BOOST_FORCEINLINE\n    void eval ( A0& a0 , A1& a1\n              , boost::mpl::long_<3> const& , boost::mpl::long_<2> const&\n              , nt2::policy<ext::lower_> const&\n              , nt2::policy<ext::raw_> const&\n              ) const\n    {\n      eval(a0, a1\n          , boost::mpl::long_<3>(),  boost::mpl::long_<2>()\n          , nt2::policy<ext::raw_>(), nt2::policy<ext::lower_>());\n    }\n\n\n  };\n} }\n\n#endif\n\n\n", "meta": {"hexsha": "280ec7dd101c88228a4d855cd51ab8746ac4088b", "size": 11894, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/core/linalg/include/nt2/linalg/functions/factorizations/chol.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/chol.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/chol.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": 37.8789808917, "max_line_length": 90, "alphanum_fraction": 0.446359509, "num_tokens": 3024, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6477982043529715, "lm_q2_score": 0.5312093733737562, "lm_q1q2_score": 0.34411647820698643}}
{"text": "/*********************************************************************\n* Software License Agreement (BSD License)\n*\n*  Copyright (c) 2010, Rice University\n*  All rights reserved.\n*\n*  Redistribution and use in source and binary forms, with or without\n*  modification, are permitted provided that the following conditions\n*  are met:\n*\n*   * Redistributions of source code must retain the above copyright\n*     notice, this list of conditions and the following disclaimer.\n*   * Redistributions in binary form must reproduce the above\n*     copyright notice, this list of conditions and the following\n*     disclaimer in the documentation and/or other materials provided\n*     with the distribution.\n*   * Neither the name of the Rice University nor the names of its\n*     contributors may be used to endorse or promote products derived\n*     from this software without specific prior written permission.\n*\n*  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n*  \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n*  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n*  FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n*  COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n*  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n*  BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n*  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n*  CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n*  LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n*  ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n*  POSSIBILITY OF SUCH DAMAGE.\n*********************************************************************/\n\n/* Author: Mark Moll */\n\n#include \"ompl/base/spaces/DubinsStateSpace.h\"\n#include \"ompl/base/SpaceInformation.h\"\n#include \"ompl/util/Exception.h\"\n#include <queue>\n#include <boost/math/constants/constants.hpp>\n\nusing namespace ompl::base;\n\nnamespace\n{\n    const double twopi = 2. * boost::math::constants::pi<double>();\n    const double DUBINS_EPS = 1e-6;\n    const double DUBINS_ZERO = -1e-7;\n\n    inline double mod2pi(double x)\n    {\n        if (x < 0 && x > DUBINS_ZERO)\n            return 0;\n        double xm = x - twopi * floor(x / twopi);\n        if (twopi - xm < .5 * DUBINS_EPS) xm = 0.;\n        return xm;\n    }\n\n    DubinsStateSpace::DubinsPath dubinsLSL(double d, double alpha, double beta)\n    {\n        double ca = cos(alpha), sa = sin(alpha), cb = cos(beta), sb = sin(beta);\n        double tmp = 2. + d * d - 2. * (ca * cb + sa * sb - d * (sa - sb));\n        if (tmp >= DUBINS_ZERO)\n        {\n            double theta = atan2(cb - ca, d + sa - sb);\n            double t = mod2pi(-alpha + theta);\n            double p = sqrt(std::max(tmp, 0.));\n            double q = mod2pi(beta - theta);\n            assert(fabs(p * cos(alpha + t) - sa + sb - d) < 2 * DUBINS_EPS);\n            assert(fabs(p * sin(alpha + t) + ca - cb) < 2 * DUBINS_EPS);\n            assert(mod2pi(alpha + t + q - beta + .5 * DUBINS_EPS) < DUBINS_EPS);\n            return DubinsStateSpace::DubinsPath(DubinsStateSpace::dubinsPathType[0], t, p, q);\n        }\n        return {};\n    }\n\n    DubinsStateSpace::DubinsPath dubinsRSR(double d, double alpha, double beta)\n    {\n        double ca = cos(alpha), sa = sin(alpha), cb = cos(beta), sb = sin(beta);\n        double tmp = 2. + d * d - 2. * (ca * cb + sa * sb - d * (sb - sa));\n        if (tmp >= DUBINS_ZERO)\n        {\n            double theta = atan2(ca - cb, d - sa + sb);\n            double t = mod2pi(alpha - theta);\n            double p = sqrt(std::max(tmp, 0.));\n            double q = mod2pi(-beta + theta);\n            assert(fabs(p * cos(alpha - t) + sa - sb - d) < 2* DUBINS_EPS);\n            assert(fabs(p * sin(alpha - t) - ca + cb) < 2 * DUBINS_EPS);\n            assert(mod2pi(alpha - t - q - beta + .5 * DUBINS_EPS) < DUBINS_EPS);\n            return DubinsStateSpace::DubinsPath(DubinsStateSpace::dubinsPathType[1], t, p, q);\n        }\n        return {};\n    }\n\n    DubinsStateSpace::DubinsPath dubinsRSL(double d, double alpha, double beta)\n    {\n        double ca = cos(alpha), sa = sin(alpha), cb = cos(beta), sb = sin(beta);\n        double tmp = d * d - 2. + 2. * (ca * cb + sa * sb - d * (sa + sb));\n        if (tmp >= DUBINS_ZERO)\n        {\n            double p = sqrt(std::max(tmp, 0.));\n            double theta = atan2(ca + cb, d - sa - sb) - atan2(2., p);\n            double t = mod2pi(alpha - theta);\n            double q = mod2pi(beta - theta);\n            assert(fabs(p * cos(alpha - t) - 2. * sin(alpha - t) + sa + sb - d) < 2 * DUBINS_EPS);\n            assert(fabs(p * sin(alpha - t) + 2. * cos(alpha - t) - ca - cb) < 2 * DUBINS_EPS);\n            assert(mod2pi(alpha - t + q - beta + .5 * DUBINS_EPS) < DUBINS_EPS);\n            return DubinsStateSpace::DubinsPath(DubinsStateSpace::dubinsPathType[2], t, p, q);\n        }\n        return {};\n    }\n\n    DubinsStateSpace::DubinsPath dubinsLSR(double d, double alpha, double beta)\n    {\n        double ca = cos(alpha), sa = sin(alpha), cb = cos(beta), sb = sin(beta);\n        double tmp = -2. + d * d + 2. * (ca * cb + sa * sb + d * (sa + sb));\n        if (tmp >= DUBINS_ZERO)\n        {\n            double p = sqrt(std::max(tmp, 0.));\n            double theta = atan2(-ca - cb, d + sa + sb) - atan2(-2., p);\n            double t = mod2pi(-alpha + theta);\n            double q = mod2pi(-beta + theta);\n            assert(fabs(p * cos(alpha + t) + 2. * sin(alpha + t) - sa - sb - d) < 2 * DUBINS_EPS);\n            assert(fabs(p * sin(alpha + t) - 2. * cos(alpha + t) + ca + cb) < 2 * DUBINS_EPS);\n            assert(mod2pi(alpha + t - q - beta + .5 * DUBINS_EPS) < DUBINS_EPS);\n            return DubinsStateSpace::DubinsPath(DubinsStateSpace::dubinsPathType[3], t, p, q);\n        }\n        return {};\n    }\n\n    DubinsStateSpace::DubinsPath dubinsRLR(double d, double alpha, double beta)\n    {\n        double ca = cos(alpha), sa = sin(alpha), cb = cos(beta), sb = sin(beta);\n        double tmp = .125 * (6. - d * d + 2. * (ca * cb + sa * sb + d * (sa - sb)));\n        if (fabs(tmp) < 1.)\n        {\n            double p = twopi - acos(tmp);\n            double theta = atan2(ca - cb, d - sa + sb);\n            double t = mod2pi(alpha - theta + .5 * p);\n            double q = mod2pi(alpha - beta - t + p);\n            assert(fabs(2. * sin(alpha - t + p) - 2. * sin(alpha - t) - d + sa - sb) < 2 * DUBINS_EPS);\n            assert(fabs(-2. * cos(alpha - t + p) + 2. * cos(alpha - t) - ca + cb) < 2 * DUBINS_EPS);\n            assert(mod2pi(alpha - t + p - q - beta + .5 * DUBINS_EPS) < DUBINS_EPS);\n            return DubinsStateSpace::DubinsPath(DubinsStateSpace::dubinsPathType[4], t, p, q);\n        }\n        return {};\n    }\n\n    DubinsStateSpace::DubinsPath dubinsLRL(double d, double alpha, double beta)\n    {\n        double ca = cos(alpha), sa = sin(alpha), cb = cos(beta), sb = sin(beta);\n        double tmp = .125 * (6. - d * d + 2. * (ca * cb + sa * sb - d * (sa - sb)));\n        if (fabs(tmp) < 1.)\n        {\n            double p = twopi - acos(tmp);\n            double theta = atan2(-ca + cb, d + sa - sb);\n            double t = mod2pi(-alpha + theta + .5 * p);\n            double q = mod2pi(beta - alpha - t + p);\n            assert(fabs(-2. * sin(alpha + t - p) + 2. * sin(alpha + t) - d - sa + sb) < 2 * DUBINS_EPS);\n            assert(fabs(2. * cos(alpha + t - p) - 2. * cos(alpha + t) + ca - cb) < 2 * DUBINS_EPS);\n            assert(mod2pi(alpha + t - p + q - beta + .5 * DUBINS_EPS) < DUBINS_EPS);\n            return DubinsStateSpace::DubinsPath(DubinsStateSpace::dubinsPathType[5], t, p, q);\n        }\n        return {};\n    }\n\n    DubinsStateSpace::DubinsPath dubins(double d, double alpha, double beta)\n    {\n        if (d < DUBINS_EPS && fabs(alpha - beta) < DUBINS_EPS)\n            return {DubinsStateSpace::dubinsPathType[0], 0, d, 0};\n\n        DubinsStateSpace::DubinsPath path(dubinsLSL(d, alpha, beta)), tmp(dubinsRSR(d, alpha, beta));\n        double len, minLength = path.length();\n\n        if ((len = tmp.length()) < minLength)\n        {\n            minLength = len;\n            path = tmp;\n        }\n        tmp = dubinsRSL(d, alpha, beta);\n        if ((len = tmp.length()) < minLength)\n        {\n            minLength = len;\n            path = tmp;\n        }\n        tmp = dubinsLSR(d, alpha, beta);\n        if ((len = tmp.length()) < minLength)\n        {\n            minLength = len;\n            path = tmp;\n        }\n        tmp = dubinsRLR(d, alpha, beta);\n        if ((len = tmp.length()) < minLength)\n        {\n            minLength = len;\n            path = tmp;\n        }\n        tmp = dubinsLRL(d, alpha, beta);\n        if ((len = tmp.length()) < minLength)\n            path = tmp;\n        return path;\n    }\n}\n\nconst ompl::base::DubinsStateSpace::DubinsPathSegmentType ompl::base::DubinsStateSpace::dubinsPathType[6][3] = {\n    {DUBINS_LEFT, DUBINS_STRAIGHT, DUBINS_LEFT},\n    {DUBINS_RIGHT, DUBINS_STRAIGHT, DUBINS_RIGHT},\n    {DUBINS_RIGHT, DUBINS_STRAIGHT, DUBINS_LEFT},\n    {DUBINS_LEFT, DUBINS_STRAIGHT, DUBINS_RIGHT},\n    {DUBINS_RIGHT, DUBINS_LEFT, DUBINS_RIGHT},\n    {DUBINS_LEFT, DUBINS_RIGHT, DUBINS_LEFT}};\n\ndouble ompl::base::DubinsStateSpace::distance(const State *state1, const State *state2) const\n{\n    if (isSymmetric_)\n        return rho_ * std::min(dubins(state1, state2).length(), dubins(state2, state1).length());\n    return rho_ * dubins(state1, state2).length();\n}\n\nvoid ompl::base::DubinsStateSpace::interpolate(const State *from, const State *to, const double t, State *state) const\n{\n    bool firstTime = true;\n    DubinsPath path;\n    interpolate(from, to, t, firstTime, path, state);\n}\n\nvoid ompl::base::DubinsStateSpace::interpolate(const State *from, const State *to, const double t, bool &firstTime,\n                                               DubinsPath &path, State *state) const\n{\n    if (firstTime)\n    {\n        if (t >= 1.)\n        {\n            if (to != state)\n                copyState(state, to);\n            return;\n        }\n        if (t <= 0.)\n        {\n            if (from != state)\n                copyState(state, from);\n            return;\n        }\n\n        path = dubins(from, to);\n        if (isSymmetric_)\n        {\n            DubinsPath path2(dubins(to, from));\n            if (path2.length() < path.length())\n            {\n                path2.reverse_ = true;\n                path = path2;\n            }\n        }\n        firstTime = false;\n    }\n    interpolate(from, path, t, state);\n}\n\nvoid ompl::base::DubinsStateSpace::interpolate(const State *from, const DubinsPath &path, double t, State *state) const\n{\n    auto *s = allocState()->as<StateType>();\n    double seg = t * path.length(), phi, v;\n\n    s->setXY(0., 0.);\n    s->setYaw(from->as<StateType>()->getYaw());\n    if (!path.reverse_)\n    {\n        for (unsigned int i = 0; i < 3 && seg > 0; ++i)\n        {\n            v = std::min(seg, path.length_[i]);\n            phi = s->getYaw();\n            seg -= v;\n            switch (path.type_[i])\n            {\n                case DUBINS_LEFT:\n                    s->setXY(s->getX() + sin(phi + v) - sin(phi), s->getY() - cos(phi + v) + cos(phi));\n                    s->setYaw(phi + v);\n                    break;\n                case DUBINS_RIGHT:\n                    s->setXY(s->getX() - sin(phi - v) + sin(phi), s->getY() + cos(phi - v) - cos(phi));\n                    s->setYaw(phi - v);\n                    break;\n                case DUBINS_STRAIGHT:\n                    s->setXY(s->getX() + v * cos(phi), s->getY() + v * sin(phi));\n                    break;\n            }\n        }\n    }\n    else\n    {\n        for (unsigned int i = 0; i < 3 && seg > 0; ++i)\n        {\n            v = std::min(seg, path.length_[2 - i]);\n            phi = s->getYaw();\n            seg -= v;\n            switch (path.type_[2 - i])\n            {\n                case DUBINS_LEFT:\n                    s->setXY(s->getX() + sin(phi - v) - sin(phi), s->getY() - cos(phi - v) + cos(phi));\n                    s->setYaw(phi - v);\n                    break;\n                case DUBINS_RIGHT:\n                    s->setXY(s->getX() - sin(phi + v) + sin(phi), s->getY() + cos(phi + v) - cos(phi));\n                    s->setYaw(phi + v);\n                    break;\n                case DUBINS_STRAIGHT:\n                    s->setXY(s->getX() - v * cos(phi), s->getY() - v * sin(phi));\n                    break;\n            }\n        }\n    }\n    state->as<StateType>()->setX(s->getX() * rho_ + from->as<StateType>()->getX());\n    state->as<StateType>()->setY(s->getY() * rho_ + from->as<StateType>()->getY());\n    getSubspace(1)->enforceBounds(s->as<SO2StateSpace::StateType>(1));\n    state->as<StateType>()->setYaw(s->getYaw());\n    freeState(s);\n}\n\nompl::base::DubinsStateSpace::DubinsPath ompl::base::DubinsStateSpace::dubins(const State *state1,\n                                                                              const State *state2) const\n{\n    const auto *s1 = static_cast<const StateType *>(state1);\n    const auto *s2 = static_cast<const StateType *>(state2);\n    double x1 = s1->getX(), y1 = s1->getY(), th1 = s1->getYaw();\n    double x2 = s2->getX(), y2 = s2->getY(), th2 = s2->getYaw();\n    double dx = x2 - x1, dy = y2 - y1, d = sqrt(dx * dx + dy * dy) / rho_, th = atan2(dy, dx);\n    double alpha = mod2pi(th1 - th), beta = mod2pi(th2 - th);\n    return ::dubins(d, alpha, beta);\n}\n\nvoid ompl::base::DubinsMotionValidator::defaultSettings()\n{\n    stateSpace_ = dynamic_cast<DubinsStateSpace *>(si_->getStateSpace().get());\n    if (stateSpace_ == nullptr)\n        throw Exception(\"No state space for motion validator\");\n}\n\nbool ompl::base::DubinsMotionValidator::checkMotion(const State *s1, const State *s2,\n                                                    std::pair<State *, double> &lastValid) const\n{\n    /* assume motion starts in a valid configuration so s1 is valid */\n\n    bool result = true, firstTime = true;\n    DubinsStateSpace::DubinsPath path;\n    int nd = stateSpace_->validSegmentCount(s1, s2);\n\n    if (nd > 1)\n    {\n        /* temporary storage for the checked state */\n        State *test = si_->allocState();\n\n        for (int j = 1; j < nd; ++j)\n        {\n            stateSpace_->interpolate(s1, s2, (double)j / (double)nd, firstTime, path, test);\n            if (!si_->isValid(test))\n            {\n                lastValid.second = (double)(j - 1) / (double)nd;\n                if (lastValid.first != nullptr)\n                    stateSpace_->interpolate(s1, s2, lastValid.second, firstTime, path, lastValid.first);\n                result = false;\n                break;\n            }\n        }\n        si_->freeState(test);\n    }\n\n    if (result)\n        if (!si_->isValid(s2))\n        {\n            lastValid.second = (double)(nd - 1) / (double)nd;\n            if (lastValid.first != nullptr)\n                stateSpace_->interpolate(s1, s2, lastValid.second, firstTime, path, lastValid.first);\n            result = false;\n        }\n\n    if (result)\n        valid_++;\n    else\n        invalid_++;\n\n    return result;\n}\n\nbool ompl::base::DubinsMotionValidator::checkMotion(const State *s1, const State *s2) const\n{\n    /* assume motion starts in a valid configuration so s1 is valid */\n    if (!si_->isValid(s2))\n        return false;\n\n    bool result = true, firstTime = true;\n    DubinsStateSpace::DubinsPath path;\n    int nd = stateSpace_->validSegmentCount(s1, s2);\n\n    /* initialize the queue of test positions */\n    std::queue<std::pair<int, int>> pos;\n    if (nd >= 2)\n    {\n        pos.emplace(1, nd - 1);\n\n        /* temporary storage for the checked state */\n        State *test = si_->allocState();\n\n        /* repeatedly subdivide the path segment in the middle (and check the middle) */\n        while (!pos.empty())\n        {\n            std::pair<int, int> x = pos.front();\n\n            int mid = (x.first + x.second) / 2;\n            stateSpace_->interpolate(s1, s2, (double)mid / (double)nd, firstTime, path, test);\n\n            if (!si_->isValid(test))\n            {\n                result = false;\n                break;\n            }\n\n            pos.pop();\n\n            if (x.first < mid)\n                pos.emplace(x.first, mid - 1);\n            if (x.second > mid)\n                pos.emplace(mid + 1, x.second);\n        }\n\n        si_->freeState(test);\n    }\n\n    if (result)\n        valid_++;\n    else\n        invalid_++;\n\n    return result;\n}\n", "meta": {"hexsha": "4fe4b7825bdff3147f9e09c2432409ee93455f0d", "size": 16484, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/ompl/base/spaces/src/DubinsStateSpace.cpp", "max_stars_repo_name": "ericpairet/ompl", "max_stars_repo_head_hexsha": "25c76431cef25f0100ed74d09dd88944ecca5ee1", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 837.0, "max_stars_repo_stars_event_min_datetime": "2015-01-07T12:01:20.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T08:42:42.000Z", "max_issues_repo_path": "src/ompl/base/spaces/src/DubinsStateSpace.cpp", "max_issues_repo_name": "ericpairet/ompl", "max_issues_repo_head_hexsha": "25c76431cef25f0100ed74d09dd88944ecca5ee1", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 271.0, "max_issues_repo_issues_event_min_datetime": "2015-01-12T22:05:06.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T22:16:01.000Z", "max_forks_repo_path": "src/ompl/base/spaces/src/DubinsStateSpace.cpp", "max_forks_repo_name": "ericpairet/ompl", "max_forks_repo_head_hexsha": "25c76431cef25f0100ed74d09dd88944ecca5ee1", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 452.0, "max_forks_repo_forks_event_min_datetime": "2015-02-10T08:48:21.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-23T06:53:33.000Z", "avg_line_length": 37.7208237986, "max_line_length": 119, "alphanum_fraction": 0.5299077894, "num_tokens": 4530, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7401743620390163, "lm_q2_score": 0.4649015713733885, "lm_q1q2_score": 0.34410822400223406}}
{"text": "#ifndef BOOST_GEOMETRY_PROJECTIONS_CEA_HPP\n#define BOOST_GEOMETRY_PROJECTIONS_CEA_HPP\n\n// Boost.Geometry - extensions-gis-projections (based on PROJ4)\n// This file is automatically generated. DO NOT EDIT.\n\n// Copyright (c) 2008-2012 Barend Gehrels, Amsterdam, the Netherlands.\n\n// Use, modification and distribution is subject to the Boost Software License,\n// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n\n// This file is converted from PROJ4, http://trac.osgeo.org/proj\n// PROJ4 is originally written by Gerald Evenden (then of the USGS)\n// PROJ4 is maintained by Frank Warmerdam\n// PROJ4 is converted to Boost.Geometry by Barend Gehrels\n\n// Original copyright notice:\n \n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the \"Software\"),\n// to deal in the Software without restriction, including without limitation\n// the rights to use, copy, modify, merge, publish, distribute, sublicense,\n// and/or sell copies of the Software, and to permit persons to whom the\n// Software is furnished to do so, subject to the following conditions:\n\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n// DEALINGS IN THE SOFTWARE.\n\n#include <boost/math/special_functions/hypot.hpp>\n\n#include <boost/geometry/extensions/gis/projections/impl/base_static.hpp>\n#include <boost/geometry/extensions/gis/projections/impl/base_dynamic.hpp>\n#include <boost/geometry/extensions/gis/projections/impl/projects.hpp>\n#include <boost/geometry/extensions/gis/projections/impl/factory_entry.hpp>\n#include <boost/geometry/extensions/gis/projections/impl/pj_qsfn.hpp>\n#include <boost/geometry/extensions/gis/projections/impl/pj_auth.hpp>\n\nnamespace boost { namespace geometry { namespace projections\n{\n    #ifndef DOXYGEN_NO_DETAIL\n    namespace detail { namespace cea{ \n            static const double EPS = 1e-10;\n\n            struct par_cea\n            {\n                double qp;\n                double apa[APA_SIZE];\n            };\n\n            // template class, using CRTP to implement forward/inverse\n            template <typename Geographic, typename Cartesian, typename Parameters>\n            struct base_cea_ellipsoid : public base_t_fi<base_cea_ellipsoid<Geographic, Cartesian, Parameters>,\n                     Geographic, Cartesian, Parameters>\n            {\n\n                 typedef double geographic_type;\n                 typedef double cartesian_type;\n\n                par_cea m_proj_parm;\n\n                inline base_cea_ellipsoid(const Parameters& par)\n                    : base_t_fi<base_cea_ellipsoid<Geographic, Cartesian, Parameters>,\n                     Geographic, Cartesian, Parameters>(*this, par) {}\n\n                inline void fwd(geographic_type& lp_lon, geographic_type& lp_lat, cartesian_type& xy_x, cartesian_type& xy_y) const\n                {\n                    xy_x = this->m_par.k0 * lp_lon;\n                    xy_y = .5 * pj_qsfn(sin(lp_lat), this->m_par.e, this->m_par.one_es) / this->m_par.k0;\n                }\n\n                inline void inv(cartesian_type& xy_x, cartesian_type& xy_y, geographic_type& lp_lon, geographic_type& lp_lat) const\n                {\n                    lp_lat = pj_authlat(asin( 2. * xy_y * this->m_par.k0 / this->m_proj_parm.qp), this->m_proj_parm.apa);\n                    lp_lon = xy_x / this->m_par.k0;\n                }\n            };\n\n            // template class, using CRTP to implement forward/inverse\n            template <typename Geographic, typename Cartesian, typename Parameters>\n            struct base_cea_spheroid : public base_t_fi<base_cea_spheroid<Geographic, Cartesian, Parameters>,\n                     Geographic, Cartesian, Parameters>\n            {\n\n                 typedef double geographic_type;\n                 typedef double cartesian_type;\n\n                par_cea m_proj_parm;\n\n                inline base_cea_spheroid(const Parameters& par)\n                    : base_t_fi<base_cea_spheroid<Geographic, Cartesian, Parameters>,\n                     Geographic, Cartesian, Parameters>(*this, par) {}\n\n                inline void fwd(geographic_type& lp_lon, geographic_type& lp_lat, cartesian_type& xy_x, cartesian_type& xy_y) const\n                {\n                    xy_x = this->m_par.k0 * lp_lon;\n                    xy_y = sin(lp_lat) / this->m_par.k0;\n                }\n\n                inline void inv(cartesian_type& xy_x, cartesian_type& xy_y, geographic_type& lp_lon, geographic_type& lp_lat) const\n                {\n                    double t;\n                \n                    if ((t = fabs(xy_y *= this->m_par.k0)) - EPS <= 1.) {\n                        if (t >= 1.)\n                            lp_lat = xy_y < 0. ? -HALFPI : HALFPI;\n                        else\n                            lp_lat = asin(xy_y);\n                        lp_lon = xy_x / this->m_par.k0;\n                    } else throw proj_exception();;\n                }\n            };\n\n            // Equal Area Cylindrical\n            template <typename Parameters>\n            void setup_cea(Parameters& par, par_cea& proj_parm)\n            {\n                double t = 0;\n                if (pj_param(par.params, \"tlat_ts\").i &&\n                    (par.k0 = cos(t = pj_param(par.params, \"rlat_ts\").f)) < 0.)\n                  throw proj_exception(-24);\n                if (par.es) {\n                    t = sin(t);\n                    par.k0 /= sqrt(1. - par.es * t * t);\n                    par.e = sqrt(par.es);\n                    pj_authset(par.es, proj_parm.apa);\n                    proj_parm.qp = pj_qsfn(1., par.e, par.one_es);\n                // par.inv = e_inverse;\n                // par.fwd = e_forward;\n                } else {\n                // par.inv = s_inverse;\n                // par.fwd = s_forward;\n                }\n            }\n\n        }} // namespace detail::cea\n    #endif // doxygen \n\n    /*!\n        \\brief Equal Area Cylindrical 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         - lat_ts=\n        \\par Example\n        \\image html ex_cea.gif\n    */\n    template <typename Geographic, typename Cartesian, typename Parameters = parameters>\n    struct cea_ellipsoid : public detail::cea::base_cea_ellipsoid<Geographic, Cartesian, Parameters>\n    {\n        inline cea_ellipsoid(const Parameters& par) : detail::cea::base_cea_ellipsoid<Geographic, Cartesian, Parameters>(par)\n        {\n            detail::cea::setup_cea(this->m_par, this->m_proj_parm);\n        }\n    };\n\n    /*!\n        \\brief Equal Area Cylindrical 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         - lat_ts=\n        \\par Example\n        \\image html ex_cea.gif\n    */\n    template <typename Geographic, typename Cartesian, typename Parameters = parameters>\n    struct cea_spheroid : public detail::cea::base_cea_spheroid<Geographic, Cartesian, Parameters>\n    {\n        inline cea_spheroid(const Parameters& par) : detail::cea::base_cea_spheroid<Geographic, Cartesian, Parameters>(par)\n        {\n            detail::cea::setup_cea(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 cea_entry : public detail::factory_entry<Geographic, Cartesian, Parameters>\n        {\n            public :\n                virtual projection<Geographic, Cartesian>* create_new(const Parameters& par) const\n                {\n                    if (par.es)\n                        return new base_v_fi<cea_ellipsoid<Geographic, Cartesian, Parameters>, Geographic, Cartesian, Parameters>(par);\n                    else\n                        return new base_v_fi<cea_spheroid<Geographic, Cartesian, Parameters>, Geographic, Cartesian, Parameters>(par);\n                }\n        };\n\n        template <typename Geographic, typename Cartesian, typename Parameters>\n        inline void cea_init(detail::base_factory<Geographic, Cartesian, Parameters>& factory)\n        {\n            factory.add_to_factory(\"cea\", new cea_entry<Geographic, Cartesian, Parameters>);\n        }\n\n    } // namespace detail \n    #endif // doxygen\n\n}}} // namespace boost::geometry::projections\n\n#endif // BOOST_GEOMETRY_PROJECTIONS_CEA_HPP\n\n", "meta": {"hexsha": "4f7594bdcf43c3cdd80bd2a23457f29700a4302a", "size": 9289, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/geometry/extensions/gis/projections/proj/cea.hpp", "max_stars_repo_name": "ballisticwhisper/boost", "max_stars_repo_head_hexsha": "f72119ab640b564c4b983bd457457046b52af9ee", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2015-01-02T14:24:56.000Z", "max_stars_repo_stars_event_max_datetime": "2015-01-02T14:25:17.000Z", "max_issues_repo_path": "boost/geometry/extensions/gis/projections/proj/cea.hpp", "max_issues_repo_name": "ballisticwhisper/boost", "max_issues_repo_head_hexsha": "f72119ab640b564c4b983bd457457046b52af9ee", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2019-01-13T23:45:51.000Z", "max_issues_repo_issues_event_max_datetime": "2019-02-03T08:13:26.000Z", "max_forks_repo_path": "boost/geometry/extensions/gis/projections/proj/cea.hpp", "max_forks_repo_name": "ballisticwhisper/boost", "max_forks_repo_head_hexsha": "f72119ab640b564c4b983bd457457046b52af9ee", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2016-05-29T13:41:15.000Z", "max_forks_repo_forks_event_max_datetime": "2016-05-29T13:41:15.000Z", "avg_line_length": 41.46875, "max_line_length": 135, "alphanum_fraction": 0.6131984067, "num_tokens": 2027, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7279754371026368, "lm_q2_score": 0.4726834766204328, "lm_q1q2_score": 0.3441019605039536}}
{"text": "#include \"fssh.hpp\"\n#include \"electronic.hpp\"\n#include \"constants.hpp\"\n#include \"decoherence_afssh.hpp\"\n#include \"util.hpp\"\n#include <armadillo>\n#include <complex>\n#include <cmath>\n#include <iostream>\n\nConfigBlockReader FSSH::setup_reader()\n{\n    using types = ConfigBlockReader::types;\n    ConfigBlockReader reader{\"fssh\"};\n    reader.add_entry(\"dtc\", types::DOUBLE);\n    reader.add_entry(\"delta_e_tol\", 1e-4);\n\n    reader.add_entry(\"amplitude_file\", \"cs.dat\");\n    reader.add_entry(\"decoherence\", \"\");\n    // FIXME: make ConfigBlockReader complain if adding the same key twice!\n\n    std::random_device rd; // generate default random seed\n    reader.add_entry(\"random_seed\", (size_t) rd());\n    {\n      std::vector<std::complex<double>> cs {};\n      reader.add_entry(\"amplitudes\", cs);\n    }\n    return reader;\n}\n\n\nvoid FSSH::get_reader_data(ConfigBlockReader& reader) {\n  {\n    double in_dtc;\n    reader.get_data(\"dtc\", in_dtc);\n    // FIXME?: Should input time be in fs as it is (because our\n    // interface is general) or in ns to match GMX?\n    dtc = in_dtc * (1e-15 / AU2SI_TIME); // fs -> a.u.\n  }\n\n  reader.get_data(\"delta_e_tol\", delta_e_tol);\n  reader.get_data(\"amplitude_file\", amplitude_file);\n\n  /* added in BOMD::add_qm_keys() */\n  reader.get_data(\"min_state\", min_state);\n\n\n  /* \n     Must set rng seed before decoherence because Decoherence will use\n     armadillo random number generator\n  */\n  {\n    size_t seed = 0; // a default seed is set in setup_reader(); this value will not be propagated.\n\n    // FIXME: ConfigReader won't throw an error if the wrong type is passed in\n    reader.get_data(\"random_seed\", seed);\n    arma::arma_rng::set_seed(seed);\n\n    std::cerr << \"[FSSH] random_seed = \" << seed << std::endl;\n  }\n\n  {\n    size_t excited_states;\n    /* added in BOMD::add_qm_keys() */\n    reader.get_data(\"excited_states\", excited_states);\n\n    shstates = excited_states + 1 - min_state;\n  }\n\n  if (shstates < 2){\n    throw std::logic_error(\"Cannot run FSSH on a single surface!\");\n  }\n\n  if (!(min_state <= active_state && active_state <= min_state + shstates)){\n    throw std::range_error(\"Active state not in the range of hopping states!\");\n  }\n\n  {\n    std::string decoherence_in;\n    reader.get_data(\"decoherence\", decoherence_in);\n\n    if (decoherence_in == \"\") {\n      // do nothing; already nullptr\n    } else if (decoherence_in == \"afssh\" ||\n               decoherence_in == \"jain2016\" ) {\n      decoherence = new AFSSH(&qm, dtc, min_state, shstates, NQM(), NMM());\n    }\n    else{\n      throw std::runtime_error(\"Decoherence class, '\" + decoherence_in + \"', not recognized!\");\n    }\n  }\n\n  active_state -= min_state;\n\n  energy.set_size(shstates);\n\n  U.set_size(shstates, shstates);\n  T.set_size(shstates, shstates);\n  V.set_size(shstates, shstates);\n\n  /*\n    FIXME: should be able to configure (multiple) initial electronic\n    state(s). Can use DVEC?\n  */\n\n  {\n    std::vector<std::complex<double>> cs_vec {};\n    reader.get_data(\"amplitudes\", cs_vec);\n    if (cs_vec.size() > 0){\n      if (cs_vec.size() != (arma::uword) shstates){\n        throw std::runtime_error(\"Number of Amplitudes do not match number of hopping surfaces!\");\n      }\n      double norm = 0;\n      for (const auto& c: cs_vec){\n        norm += std::norm(c);\n      }\n      std::cerr << \"[FSSH] amplitude norm = \" << norm << std::endl;\n      if (std::abs(1.0 -norm) > 1e-6){\n        throw std::runtime_error(\"Amplitudes are not normed; check your input!\");\n      }\n      arma::cx_vec cs_arma(shstates);\n      for (arma::uword i = 0; i < (arma::uword) shstates; i++){\n        cs_arma(i) = cs_vec[i];\n      }\n      c = Electronic(cs_arma);\n    }\n    else{\n      c.reset(shstates, 1, active_state);\n    }\n  }\n}\n\n\n// For use in the update_gradient() call; Jain step 4\nvoid FSSH::electronic_evolution(void){\n  if (hopping){\n    throw std::logic_error(\"Should never be hopping at start of electronic evolution!\");\n  }\n\n  PropMap props{};\n  props.emplace(QMProperty::wfoverlap, &U);\n  qm->get_properties(props);\n\n  Electronic::phase_match(U);\n  T = arma::real(arma::logmat(U)) / dtc;\n\n  // R.B.: energy was updated in update_gradient()\n  V = diagmat(energy);\n\n  /*\n    Since the off-diagonal elements of V are always 0 in this\n    implementation, we work only with the diagonal of V. Equation 20\n    seems to have been developed for a system with positive energy\n    eigenvalues. A constant shift of energy scale to the negative (Vii\n    = Vii - max(V.diag) can cause Eq. 20 to fail.\n\n    FIXME: construct an alternate to Eq. 20 that is applicable to Vii < 0\n  */\n\n  // compute max time step for electronic propagation (eqs. 20, 21)\n  {\n    double dtq_ = std::min(dtc,\n\t\t\t   std::min(0.02 / T.max(),\n\t\t\t\t    0.02 / arma::max( V.diag() - arma::mean(V.diag()) )\n\t\t\t\t    )\n\t\t\t   );\n\n    dtq = dtc / std::round(dtc / dtq_);\n  }\n  const size_t n_steps = (size_t) dtc / dtq;\n  const std::complex<double> I(0,1);\n\n  // Propagate electronic coefficients and compute hopping probabilities for dtc\n  for (size_t nt = 0; nt < n_steps; nt++){\n    /*\n      Propagate all states simultaneously. Recall that\n      Electronic::advance(H, dt) uses rk4 to propagate the internally\n      held coefficients, c, according the Hamiltonian H for time dt\n    */\n\n    // FIXME: should use rk4\n    //c.advance_rk4(V - I*T, dtq);\n    c.advance_exact(V - I*T, dtq);\n\n    // Check for a hop unless we've already had one\n    if (! hopping){\n      const arma::uword a = active_state;\n\n      /*\n\tCompute transition probabilities. Jain (2016) eq. 12 has the\n        conjugate on the wrong element; cf. Tully (1990) -- discussion\n        with Zeyu Zhou\n      */\n      arma::vec g = -2 * arma::real(c(a) * arma::conj(c()) % T.col(a)) * dtq / std::norm(c(a));\n      // set negative elements to 0\n      g.elem( arma::find(g < 0) ).zeros();\n\n      /*\n\tEnsure that g is normed by adding any residual density to the\n\tactive state. This maintains the correct transition\n\tprobability to all states.\n      */\n      g(a) += 1.0 - arma::sum(g);\n\n      // randomly select an element from the discrete distribution represented by g\n      arma::uword j = util::sample_discrete(g);\n      if (a != j){\n      \t// will update these in the velocity_rescale call\n      \thopping = true;\n      \ttarget_state = j;\n      }\n    }  // end hopping check\n  }  // end loop over dtq\n}\n\n\n// For use within the velocity_rescale() call; Jain steps 5 & 6\n// returns energy gap if the hop succeeds without frustration\ndouble FSSH::hop_and_scale(arma::mat &total_gradient, arma::mat &velocities, const arma::vec &m){\n  if (! hopping){\n    throw std::logic_error(\"Should not be attempting a hop right now!\");\n  }\n\n  bool hop_succeeds = false;\n  \n  /*\n    Recall that in our implementation, the kinetic energy reservoir to\n    balance a hop includes the MM atoms, a region of arbitrary\n    size. However, the kinetic energy is only available in proportion\n    to the NAC vector, which is properly computed over the MM region\n    (Thank you, Ou Qi!)  and, we believe, decays with distance. See\n    the calculation of vd below.\n  */\n\n  nac.set_size(3, NQM() + NMM());\n\n  arma::mat qmg_new, mmg_new;\n  qmg_new.set_size(3,NQM());\n\n  {\n    PropMap props{};\n    props.emplace(QMProperty::nacvector, {min_state + active_state, min_state + target_state}, &nac);\n    props.emplace(QMProperty::qmgradient, {min_state + target_state}, &qmg_new);\n\n    if (NMM() > 0){\n      mmg_new.set_size(3, NMM());\n      props.emplace(QMProperty::mmgradient, {min_state + target_state}, &mmg_new);\n    }\n\n    qm->get_properties(props);\n  }\n  \n  // Make 3N vector versions of the NAC, velocity, and new\n  // gradient. (m comes in as 3N.)\n  // FIXME: How do each of these interact with link atoms?\n  const arma::vec & nacv = nac.as_col();\n\n  // FIXME: find a safer way to have a writeable velocity view\n  arma::vec vel(velocities.memptr(), 3 * (NQM() + NMM()), false, true);\n\n  arma::vec gradv(3 * (NQM() + NMM()));\n  gradv.head(3*NQM()) = arma::vectorise(qmg_new);\n  if (NMM() > 0){\n    gradv.tail(3*NMM()) = arma::vectorise(mmg_new);\n  }\n\n  double deltaE = energy(target_state) - energy(active_state);\n\n  /*\n    The hopping energy-conservation equations are documented in\n    Vale's GQSH notes dated May 14, 2021.\n  */\n\n  double vd  = arma::as_scalar(vel.t() * nacv);\n  double dmd = arma::as_scalar(nacv.t() * (nacv / m));\n  \n  double discriminant = (vd/dmd)*(vd/dmd) - 2*deltaE/dmd;\n  if (discriminant > 0){\n    hop_succeeds = true;\n    std::cerr << \"[FSSH] Hop, \" << active_state + min_state << \"->\"\n              << target_state + min_state << \" succeeds; energy difference = \"\n              << deltaE << std::endl;\n\n    // test the sign of dmv to pick the root yielding the smallest value of alpha\n    double alpha = (vd > 0 ? 1.0 : -1.0) * std::sqrt(discriminant) - (vd/dmd);\n    vel = vel + alpha * (nacv / m); // recall the nacv has dimension of momentum\n    active_state = target_state;\n    \n    // Update the gradient with the new surface so that GMX can take its second step\n    auto rows=arma::span(arma::span::all); auto cols = arma::span(0, NQM() - 1);\n    total_gradient(rows, cols) += qmg_new - qm_grd;\n    qm_grd = qmg_new;\n\n    if (NMM() > 0){\n      cols = arma::span(NQM(), NQM() + NMM() - 1);\n      total_gradient(rows, cols) += mmg_new - mm_grd;\n      mm_grd = mmg_new;\n    }\n  }\n  else{\n    hop_succeeds = false;\n    std::cerr << \"[FSSH] Hop is frustrated---will remain on \" << active_state + min_state << \"; \";\n    /*\n      Momentum reversal along nac as per Jasper, A. W.; Truhlar,\n      D. G. Chem. Phys. Lett. 2003, 369, 60--67 c.f. eqns. 1 & 2\n\n      In Jain (2016) a second criterion was imposed. But, in January\n      2020 A. Jain indicated to JES that this was not necessary. We\n      follow the original Jasper-Truhlar prescription in line with\n      Jain's updated advice.\n    */\n    if (arma::as_scalar((-gradv.t() * nacv)*(nacv.t() * (vel % m))) < 0){\n      std::cerr << \"velocities reversed.\" << std::endl;\n      const arma::vec nacu = arma::normalise(nacv);\n      //vel = vel - 2.0 * (nacu * nacu.t() * (vel % m))/m;\n      vel = vel - 2.0 * (nacu / m) * (nacu.t() * (vel % m));\n    }\n    else{\n      std::cerr << \"velocities, unchanged.\" << std::endl;\n      // Ignore the unsuccessful hop; active_state remains unchanged\n    }\n  }\n\n  hopping = false;  // update class-level state\n  return hop_succeeds ? deltaE : 0;\n}\n\n\n\n/*\n  Call this function when energy fluctuation tolerance in the MD\n  driver is exceeded and we've had a hop. Update the current surface\n  and to the total gradient, add (new-old). Similarly, take a step in\n  velocity space backwards along the old gradient and then forwards\n  along the new one.\n\n  N.B.: When working with Gromacs, it is not necessary to do any\n  back-propagation in positions, only velocities. Gromacs's\n  velocity-Verlet integrator splits velocity integration over 2 steps\n  (so that all of the tooling for leap-frog still works) and then does\n  position integration in a single step afterwards. See\n  gifs/docs/GromacsVVImplementation.jpg for notes.\n\n  Conversation with Amber in Marhc 2021 indicated that it was faster\n  and didn't rely on an ad hoc selection of energy tolerance to simply\n  converge properties in dtc directly rather than use this scheme.\n\n  void FSSH::backpropagate_gradient_velocities(\n    arma::mat &total_gradient,\n    arma::mat &velocities,\n    arma::vec &masses);\n*/\n\n\n// This is our primary hook into the Gromacs (or other) MD loop\ndouble FSSH::update_gradient(void){\n  qm->update();\n\n  // get gradients and energies\n  {\n    PropMap props{};\n    props.emplace(QMProperty::qmgradient, {min_state + active_state}, &qm_grd);\n    props.emplace(QMProperty::mmgradient, {min_state + active_state}, &mm_grd);\n    props.emplace(QMProperty::energies, util::range(min_state, min_state + shstates), &energy);\n    qm->get_properties(props);\n  }\n  \n  // write amplitudes\n  {\n    std::ofstream output(amplitude_file, std::ios_base::app);\n    output << active_state + min_state << \" \";\n    c().st().print(output);\n    output.close();\n  }\n\n  electronic_evolution();\n\n  return energy(active_state);\n}\n\n\n/*\n  rescale_velocities() comes after the first MD half-step (and before\n  constraint forces are calculated in gromacs)\n*/\n\n// FIXME: should alter velocity rescale interface so we take inverse masses as 3N vector\nbool FSSH::rescale_velocities(arma::mat &velocities, arma::vec &masses, arma::mat &total_gradient, double total_energy){\n  // call parent to update edrift\n  BOMD::rescale_velocities(velocities, masses, total_gradient, total_energy);\n\n  // FIXME: don't fire on the first inf\n  if (std::abs(edrift) > delta_e_tol){\n    std::cerr << \"WARNING, energy drift exceeds tolerance!\" << std::endl;\n  }\n  \n  if (masses.has_inf() || arma::any(masses==0)){\n    throw std::logic_error(\"Cannot do surface hopping with massless atoms or momentum sinks!\");\n  }\n\n  // 3N vector of masses\n  arma::vec m (3 * (NQM() + NMM()), arma::fill::zeros);\n  for(arma::uword i = 0 ; i < m.n_elem ; i++){\n    // no reason to do this without a bounds [] check!\n    m(i) =  masses(i/3);\n  }\n    \n  bool update = hopping; // copy so hopping can be reset\n  double deltaE = 0;\n  if (hopping){\n    std::cerr <<  \"[FSSH] Attempting hop: \" << active_state + min_state\n              << \"->\" << target_state + min_state << std::endl;\n    \n    deltaE = hop_and_scale(total_gradient, velocities, m);\n    \n    if (decoherence && deltaE > 0){\n      decoherence->hopped(c, active_state);\n    }\n  }\n\n  if (decoherence){\n    decoherence->decohere(c, U, active_state, velocities.as_col(), m);\n  }\n  \n  // update indicates we need to copy velocity and gradient back to GMX\n  return update;\n}\n", "meta": {"hexsha": "433063839fa6e9a8d1c0d1b34b82f280a71a1629", "size": 13644, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "gifs_src/fssh.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/fssh.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/fssh.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": 31.8785046729, "max_line_length": 120, "alphanum_fraction": 0.645998241, "num_tokens": 3831, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6723316860482762, "lm_q2_score": 0.5117166047041654, "lm_q1q2_score": 0.34404328761965075}}
{"text": "#ifndef SHIFT_RC_IMAGE_UTIL_CONVERT_HPP\n#define SHIFT_RC_IMAGE_UTIL_CONVERT_HPP\n\n#include <cstdint>\n#include <type_traits>\n#include <boost/assert.hpp>\n#include <shift/core/mpl.hpp>\n#include <shift/math/half.hpp>\n#include <shift/math/vector.hpp>\n#include \"shift/rc/image_util/linear_image_view.hpp\"\n#include \"shift/rc/image_util/convert_pixel_component.hpp\"\n\nnamespace shift::rc::image_util\n{\nnamespace detail\n{\n  template <typename T, typename PixelChannel>\n  struct unorm_converter\n  {\n    static_assert(std::is_integral_v<T> && std::is_unsigned_v<T>);\n    static_assert(!PixelChannel::is_block_format);\n\n    static constexpr float to_float(T value)\n    {\n      return value / static_cast<float>((1 << PixelChannel::size_in_bits) - 1);\n    }\n\n    static constexpr T from_float(float value)\n    {\n      return static_cast<T>(value * ((1 << PixelChannel::size_in_bits) - 1));\n    }\n  };\n\n  template <typename T, typename PixelChannel>\n  struct snorm_converter\n  {\n    static_assert(std::is_integral_v<T> && std::is_signed_v<T>);\n    static_assert(!PixelChannel::is_block_format);\n\n    static constexpr float to_float(T value)\n    {\n      static_assert(\n        static_cast<T>(std::numeric_limits<std::make_unsigned_t<T>>::max()\n                       << 1) == -2);\n      // The minimum value of a PixelChannel::size_in_bits sized signed integer,\n      // sign extended and stored in a value of type T.\n      constexpr T min_value =\n        static_cast<T>(std::numeric_limits<std::make_unsigned_t<T>>::max()\n                       << (PixelChannel::size_in_bits - 1));\n      if (value == min_value)\n      {\n        return -1.0f;\n      }\n      else\n      {\n        return value /\n               static_cast<float>((1 << (PixelChannel::size_in_bits - 1)) - 1);\n      }\n    }\n\n    static constexpr T from_float(float value)\n    {\n      return static_cast<T>(value *\n                            ((1 << (PixelChannel::size_in_bits - 1)) - 1));\n    }\n  };\n\n  struct srgb_converter\n  {\n    static constexpr float to_linear(float srgb_value)\n    {\n      if (srgb_value <= 0.0f)\n        return 0.0f;\n      else if (srgb_value < 0.04045f)\n        return srgb_value / 12.92f;\n      else if (srgb_value < 1.0f)\n        return std::pow((srgb_value + 0.055f) / 1.055f, 2.4f);\n      else\n        return 1.0f;\n    }\n\n    static constexpr float from_linear(float linear_value)\n    {\n      if (linear_value <= 0.0f)\n        return 0.0f;\n      else if (linear_value < 0.0031308f)\n        return linear_value * 12.92f;\n      else if (linear_value < 1.0f)\n        return std::pow(linear_value, 1.0f / 2.4f) * 1.055f - 0.055f;\n      else\n        return 1.0f;\n    }\n  };\n\n  template <typename DestinationPixel, typename SourcePixel>\n  struct channel_converter\n  {\n    template <typename DestinationChannel>\n    void operator()(const DestinationChannel*,\n                    DestinationPixel& destination_pixel,\n                    const SourcePixel& source_pixel) const\n    {\n      using destination_t = typename DestinationPixel::component_t;\n      using source_t = typename SourcePixel::component_t;\n\n      constexpr auto destination_channel_index =\n        channel_index_v<typename DestinationPixel::channels_t,\n                        DestinationChannel>;\n      static_assert(destination_channel_index <\n                    DestinationPixel::channel_count);\n      using destination_channel_t =\n        core::get_type_opt_t<destination_channel_index,\n                             typename DestinationPixel::channels_t>;\n\n      constexpr auto source_channel_index =\n        channel_index_v<typename SourcePixel::channels_t, DestinationChannel>;\n      using source_channel_t =\n        core::get_type_opt_t<source_channel_index,\n                             typename SourcePixel::channels_t>;\n\n      if constexpr (source_channel_index >= SourcePixel::channel_count)\n      {\n        // There is no matching source channel. We have to fill the destination\n        // with a default value.\n        destination_pixel[destination_channel_index] = destination_t{};\n      }\n      else if constexpr ((SourcePixel::data_type ==\n                          DestinationPixel::data_type) &&\n                         std::is_same_v<source_t, destination_t> &&\n                         std::is_same_v<source_channel_t,\n                                        destination_channel_t>)\n      {\n        // Source and destination channels are of the same channel type and\n        // data type, so we can perform a direct copy.\n        destination_pixel[destination_channel_index] =\n          source_pixel[source_channel_index];\n      }\n      else if constexpr (SourcePixel::data_type == pixel_data_type::unorm)\n      {\n        if constexpr (DestinationPixel::data_type == pixel_data_type::unorm)\n        {\n          // Convert unorm to float.\n          auto temp = unorm_converter<source_t, source_channel_t>::to_float(\n            source_pixel[source_channel_index]);\n          // Convert float to unorm.\n          destination_pixel[destination_channel_index] =\n            unorm_converter<destination_t, destination_channel_t>::from_float(\n              temp);\n        }\n        else if constexpr (DestinationPixel::data_type ==\n                           pixel_data_type::snorm)\n        {\n          // Convert unorm to float.\n          auto temp = unorm_converter<source_t, source_channel_t>::to_float(\n            source_pixel[source_channel_index]);\n          // Convert float to snorm.\n          destination_pixel[destination_channel_index] =\n            snorm_converter<destination_t, destination_channel_t>::from_float(\n              temp);\n        }\n        else if constexpr (DestinationPixel::data_type ==\n                             pixel_data_type::ufloat ||\n                           DestinationPixel::data_type ==\n                             pixel_data_type::sfloat)\n        {\n          // Convert unorm to float.\n          destination_pixel[destination_channel_index] =\n            unorm_converter<source_t, source_channel_t>::to_float(\n              source_pixel[source_channel_index]);\n        }\n        else if constexpr (DestinationPixel::data_type == pixel_data_type::srgb)\n        {\n          // Convert unorm to float.\n          auto temp = unorm_converter<source_t, source_channel_t>::to_float(\n            source_pixel[source_channel_index]);\n          // Convert color space from linear to sRGB.\n          temp = srgb_converter::from_linear(temp);\n          // Convert float to unorm.\n          destination_pixel[destination_channel_index] =\n            unorm_converter<destination_t, destination_channel_t>::from_float(\n              temp);\n        }\n        else\n          BOOST_ASSERT(false);\n      }\n      else if constexpr (SourcePixel::data_type == pixel_data_type::snorm)\n      {\n        if constexpr (DestinationPixel::data_type == pixel_data_type::unorm)\n        {\n          // Convert snorm to float.\n          auto temp = snorm_converter<source_t, source_channel_t>::to_float(\n            source_pixel[source_channel_index]);\n          // Clamp values < 0.0f.\n          temp = std::max(temp, 0.0f);\n          // Convert float to unorm.\n          destination_pixel[destination_channel_index] =\n            unorm_converter<destination_t, destination_channel_t>::from_float(\n              temp);\n        }\n        else if constexpr (DestinationPixel::data_type ==\n                           pixel_data_type::snorm)\n        {\n          // Convert snorm to float.\n          auto temp = snorm_converter<source_t, source_channel_t>::to_float(\n            source_pixel[source_channel_index]);\n          // Convert float to snorm.\n          destination_pixel[destination_channel_index] =\n            snorm_converter<destination_t, destination_channel_t>::from_float(\n              temp);\n        }\n        else if constexpr (DestinationPixel::data_type ==\n                             pixel_data_type::ufloat ||\n                           DestinationPixel::data_type ==\n                             pixel_data_type::sfloat)\n        {\n          // Convert snorm -> float.\n          destination_pixel[destination_channel_index] =\n            snorm_converter<source_t, source_channel_t>::to_float(\n              source_pixel[source_channel_index]);\n        }\n        else if constexpr (DestinationPixel::data_type == pixel_data_type::srgb)\n        {\n          // Convert snorm -> float.\n          auto temp = snorm_converter<source_t, source_channel_t>::to_float(\n            source_pixel[source_channel_index]);\n          // Clamp values < 0.0f.\n          temp = std::max(temp, 0.0f);\n          // Convert color space from linear to sRGB.\n          temp = srgb_converter::from_linear(temp);\n          // Convert float to unorm.\n          destination_pixel[destination_channel_index] =\n            unorm_converter<destination_t, destination_channel_t>::from_float(\n              temp);\n        }\n        else\n          BOOST_ASSERT(false);\n      }\n      else if constexpr (SourcePixel::data_type == pixel_data_type::ufloat)\n      {\n        if constexpr (DestinationPixel::data_type == pixel_data_type::unorm)\n        {\n          // Clamp values above 1.0f.\n          auto temp = std::min(\n            static_cast<float>(source_pixel[source_channel_index]), 1.0f);\n          // Convert float to unorm.\n          destination_pixel[destination_channel_index] =\n            unorm_converter<destination_t, destination_channel_t>::from_float(\n              temp);\n        }\n        else if constexpr (DestinationPixel::data_type ==\n                           pixel_data_type::snorm)\n        {\n          // Clamp values above 1.0f.\n          auto temp = std::min(\n            static_cast<float>(source_pixel[source_channel_index]), 1.0f);\n          // Convert float to snorm.\n          destination_pixel[destination_channel_index] =\n            snorm_converter<destination_t, destination_channel_t>::from_float(\n              temp);\n        }\n        else if constexpr (DestinationPixel::data_type ==\n                           pixel_data_type::ufloat)\n        {\n          // Simply copy value.\n          destination_pixel[destination_channel_index] =\n            static_cast<float>(source_pixel[source_channel_index]);\n        }\n        else if constexpr (DestinationPixel::data_type ==\n                           pixel_data_type::sfloat)\n        {\n          // Simply copy value.\n          destination_pixel[destination_channel_index] =\n            static_cast<destination_t>(source_pixel[source_channel_index]);\n        }\n        else if constexpr (DestinationPixel::data_type == pixel_data_type::srgb)\n        {\n          // Clamp values above 1.0f.\n          auto temp = std::min(\n            static_cast<float>(source_pixel[source_channel_index]), 1.0f);\n          // Convert color space from linear to sRGB.\n          temp = srgb_converter::from_linear(temp);\n          // Convert float to unorm.\n          destination_pixel[destination_channel_index] =\n            unorm_converter<destination_t, destination_channel_t>::from_float(\n              temp);\n        }\n        else\n          BOOST_ASSERT(false);\n      }\n      else if constexpr (SourcePixel::data_type == pixel_data_type::sfloat)\n      {\n        if constexpr (DestinationPixel::data_type == pixel_data_type::unorm)\n        {\n          // Clamp values between 0.0f and 1.0f.\n          auto temp = std::clamp(\n            static_cast<float>(source_pixel[source_channel_index]), 0.0f, 1.0f);\n          // Convert float to unorm.\n          destination_pixel[destination_channel_index] =\n            unorm_converter<destination_t, destination_channel_t>::from_float(\n              temp);\n        }\n        else if constexpr (DestinationPixel::data_type ==\n                           pixel_data_type::snorm)\n        {\n          // Clamp values between -1.0f and 1.0f.\n          auto temp =\n            std::clamp(static_cast<float>(source_pixel[source_channel_index]),\n                       -1.0f, 1.0f);\n          // Convert float to snorm.\n          destination_pixel[destination_channel_index] =\n            snorm_converter<destination_t, destination_channel_t>::from_float(\n              temp);\n        }\n        else if constexpr (DestinationPixel::data_type ==\n                           pixel_data_type::ufloat)\n        {\n          // Clamp values below 0.0f.\n          destination_pixel[destination_channel_index] = std::max(\n            static_cast<float>(source_pixel[source_channel_index]), 0.0f);\n        }\n        else if constexpr (DestinationPixel::data_type ==\n                           pixel_data_type::sfloat)\n        {\n          // Simply copy value.\n          destination_pixel[destination_channel_index] =\n            static_cast<destination_t>(source_pixel[source_channel_index]);\n        }\n        else if constexpr (DestinationPixel::data_type == pixel_data_type::srgb)\n        {\n          // Clamp values between 0.0f and 1.0f.\n          auto temp = std::clamp(\n            static_cast<float>(source_pixel[source_channel_index]), 0.0f, 1.0f);\n          // Convert color space from linear to sRGB.\n          temp = srgb_converter::from_linear(temp);\n          // Convert float to unorm.\n          destination_pixel[destination_channel_index] =\n            unorm_converter<destination_t, destination_channel_t>::from_float(\n              temp);\n        }\n        else\n          BOOST_ASSERT(false);\n      }\n      else if constexpr (SourcePixel::data_type == pixel_data_type::srgb)\n      {\n        if constexpr (DestinationPixel::data_type == pixel_data_type::unorm)\n        {\n          // Convert unorm to float.\n          auto temp = unorm_converter<source_t, source_channel_t>::to_float(\n            source_pixel[source_channel_index]);\n          // Convert color space from sRGB to linear.\n          temp = srgb_converter::to_linear(temp);\n          // Convert float to unorm.\n          destination_pixel[destination_channel_index] =\n            unorm_converter<destination_t, destination_channel_t>::from_float(\n              temp);\n        }\n        else if constexpr (DestinationPixel::data_type ==\n                           pixel_data_type::snorm)\n        {\n          // Convert unorm to float.\n          auto temp = unorm_converter<source_t, source_channel_t>::to_float(\n            source_pixel[source_channel_index]);\n          // Convert color space from sRGB to linear.\n          temp = srgb_converter::to_linear(temp);\n          // Convert float to snorm.\n          destination_pixel[destination_channel_index] =\n            snorm_converter<destination_t, destination_channel_t>::from_float(\n              temp);\n        }\n        else if constexpr (DestinationPixel::data_type ==\n                             pixel_data_type::ufloat ||\n                           DestinationPixel::data_type ==\n                             pixel_data_type::sfloat)\n        {\n          // Convert unorm to float.\n          auto temp = unorm_converter<source_t, source_channel_t>::to_float(\n            source_pixel[source_channel_index]);\n          // Convert color space from sRGB to linear.\n          destination_pixel[destination_channel_index] =\n            srgb_converter::to_linear(temp);\n        }\n        else if constexpr (DestinationPixel::data_type == pixel_data_type::srgb)\n        {\n          // Convert unorm to float.\n          auto temp = unorm_converter<source_t, source_channel_t>::to_float(\n            source_pixel[source_channel_index]);\n          // Convert float to unorm.\n          destination_pixel[destination_channel_index] =\n            unorm_converter<destination_t, destination_channel_t>::from_float(\n              temp);\n        }\n        else\n          BOOST_ASSERT(false);\n      }\n      else\n        BOOST_ASSERT(false);\n    }\n  };\n}\n\n/// This class converts a single pixel from one format to another.\ntemplate <typename DestinationPixel, typename SourcePixel>\nclass pixel_converter\n{\npublic:\n  using destination_pixel_t = DestinationPixel;\n  using source_pixel_t = SourcePixel;\n\n  void operator()(destination_pixel_t& destination,\n                  const source_pixel_t& source) const\n  {\n    if constexpr (std::is_same_v<destination_pixel_t, source_pixel_t>)\n      std::memcpy(&destination, &source, destination_pixel_t::size_in_bytes);\n    else\n    {\n      // Convert each destination pixel channel separately.\n      core::for_each<typename DestinationPixel::channels_t>(\n        detail::channel_converter<DestinationPixel, SourcePixel>{}, destination,\n        source);\n    }\n  }\n};\n}\n\n#endif\n", "meta": {"hexsha": "53628bf28d8532cadd36ec00f9fc9ac21353eb8f", "size": 16490, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "shift/rc/private/shift/rc/image_util/convert.hpp", "max_stars_repo_name": "cspanier/shift", "max_stars_repo_head_hexsha": "5b3b9be310155fbc57d165d06259b723a5728828", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2018-11-28T18:14:08.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-06T07:44:36.000Z", "max_issues_repo_path": "shift/rc/private/shift/rc/image_util/convert.hpp", "max_issues_repo_name": "cspanier/shift", "max_issues_repo_head_hexsha": "5b3b9be310155fbc57d165d06259b723a5728828", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2018-11-06T21:01:05.000Z", "max_issues_repo_issues_event_max_datetime": "2019-02-19T07:52:52.000Z", "max_forks_repo_path": "shift/rc/private/shift/rc/image_util/convert.hpp", "max_forks_repo_name": "cspanier/shift", "max_forks_repo_head_hexsha": "5b3b9be310155fbc57d165d06259b723a5728828", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.7089201878, "max_line_length": 80, "alphanum_fraction": 0.6084899939, "num_tokens": 3403, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7217432182679956, "lm_q2_score": 0.47657965106367595, "lm_q1q2_score": 0.34396813111973584}}
{"text": "// Copyright (C) 2015 The Regents of the University of California (Regents).\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are\n// met:\n//\n//     * Redistributions of source code must retain the above copyright\n//       notice, this list of conditions and the following disclaimer.\n//\n//     * Redistributions in binary form must reproduce the above\n//       copyright notice, this list of conditions and the following\n//       disclaimer in the documentation and/or other materials provided\n//       with the distribution.\n//\n//     * Neither the name of The Regents or University of California nor the\n//       names of its contributors may be used to endorse or promote products\n//       derived from this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE\n// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n// POSSIBILITY OF SUCH DAMAGE.\n//\n// Please contact the author of this library if you have any questions.\n// Author: Chris Sweeney (cmsweeney@cs.ucsb.edu)\n\n#include \"theia/sfm/global_pose_estimation/linear_position_estimator.h\"\n\n#include <ceres/rotation.h>\n#include <Eigen/Core>\n#include <Eigen/SparseCore>\n#include <Eigen/SparseLU>\n#include <glog/logging.h>\n#include <algorithm>\n#include <unordered_map>\n#include <unordered_set>\n#include <vector>\n\n#include \"spectra/include/SymEigsSolver.h\"\n\n#include \"theia/math/matrix/linear_operator.h\"\n#include \"theia/sfm/find_common_tracks_in_views.h\"\n#include \"theia/sfm/global_pose_estimation/compute_triplet_baseline_ratios.h\"\n#include \"theia/sfm/reconstruction.h\"\n#include \"theia/sfm/types.h\"\n#include \"theia/sfm/view_graph/triplet_extractor.h\"\n#include \"theia/sfm/view_triplet.h\"\n#include \"theia/util/map_util.h\"\n#include \"theia/util/threadpool.h\"\n\nnamespace theia {\n\nusing Eigen::Matrix3d;\nusing Eigen::Vector3d;\n\nnamespace {\n\n// Adds the 3x3 matrix to the triplet list with the top-left corner in the\n// sparse matrix corresponding to (row, col).\nvoid Add3x3MatrixToTripletList(\n    const Matrix3d& mat,\n    const int row,\n    const int col,\n    std::vector<Eigen::Triplet<double> >* triplet_list) {\n  // If col < 0 then we are holding this particular view constant so it should\n  // not be added to the linear system.\n  if (col < 0) {\n    return;\n  }\n\n  triplet_list->emplace_back(row + 0, col + 0, mat(0, 0));\n  triplet_list->emplace_back(row + 1, col + 0, mat(1, 0));\n  triplet_list->emplace_back(row + 2, col + 0, mat(2, 0));\n  triplet_list->emplace_back(row + 0, col + 1, mat(0, 1));\n  triplet_list->emplace_back(row + 1, col + 1, mat(1, 1));\n  triplet_list->emplace_back(row + 2, col + 1, mat(2, 1));\n  triplet_list->emplace_back(row + 0, col + 2, mat(0, 2));\n  triplet_list->emplace_back(row + 1, col + 2, mat(1, 2));\n  triplet_list->emplace_back(row + 2, col + 2, mat(2, 2));\n}\n\ninline Matrix3d AngleAxisToRotationMatrix(const Vector3d angle_axis) {\n  const double angle = angle_axis.norm();\n  const Eigen::AngleAxisd rotation_aa(angle, angle_axis / angle);\n  return rotation_aa.toRotationMatrix();\n}\n\n// Adds a triplet constraint to the linear system. The weight of the constraint\n// (w), the global orientations, baseline (ratios), and view triplet information\n// are needed to form the constraint.\nvoid AddTripletConstraint(const ViewTriplet& triplet,\n                          const int start_row,\n                          const std::vector<int> cols,\n                          const double w,\n                          const std::vector<Vector3d>& orientations,\n                          const Vector3d& baselines,\n                          std::vector<Eigen::Triplet<double> >* triplet_list) {\n  // Relative camera positions.\n  const Matrix3d orientation0 = AngleAxisToRotationMatrix(orientations[0]);\n  const Matrix3d orientation1 = AngleAxisToRotationMatrix(orientations[1]);\n  const Vector3d t01 =\n      -orientation0.transpose() * triplet.info_one_two.position_2;\n  const Vector3d t02 =\n      -orientation0.transpose() * triplet.info_one_three.position_2;\n  const Vector3d t12 =\n      -orientation1.transpose() * triplet.info_two_three.position_2;\n\n  // Rotations between the translation vectors.\n  const Matrix3d r012 =\n      Eigen::Quaterniond::FromTwoVectors(t12, -t01).toRotationMatrix();\n  const Matrix3d r201 =\n      Eigen::Quaterniond::FromTwoVectors(t01, t02).toRotationMatrix();\n  const Matrix3d r120 =\n      Eigen::Quaterniond::FromTwoVectors(-t02, -t12).toRotationMatrix();\n\n  // Baselines ratios.\n  const double s_012 = baselines[0] / baselines[2];\n  const double s_201 = baselines[1] / baselines[0];\n  const double s_120 = baselines[2] / baselines[1];\n\n  // Assume that t01 is perfect and solve for c2.\n  Matrix3d m1 =\n      (-s_201 * r201 + r012.transpose() / s_012 + Matrix3d::Identity()) * w;\n  Matrix3d m2 =\n      (s_201 * r201 - r012.transpose() / s_012 + Matrix3d::Identity()) * w;\n  Matrix3d m3 = -2.0 * w * Matrix3d::Identity();\n  Add3x3MatrixToTripletList(m1, start_row, cols[0], triplet_list);\n  Add3x3MatrixToTripletList(m2, start_row, cols[1], triplet_list);\n  Add3x3MatrixToTripletList(m3, start_row, cols[2], triplet_list);\n\n  // Assume t02 is perfect and solve for c1.\n  m1 = (-r201.transpose() / s_201 + s_120 * r120 + Matrix3d::Identity()) * w;\n  m2 = -2.0 * w * Matrix3d::Identity();\n  m3 = (r201.transpose() / s_201 - s_120 * r120 + Matrix3d::Identity()) * w;\n  Add3x3MatrixToTripletList(m1, start_row + 3, cols[0], triplet_list);\n  Add3x3MatrixToTripletList(m2, start_row + 3, cols[1], triplet_list);\n  Add3x3MatrixToTripletList(m3, start_row + 3, cols[2], triplet_list);\n\n  // Assume t12 is perfect and solve for c0.\n  m1 = -2.0  * w * Matrix3d::Identity();\n  m2 = (-s_012 * r012 + r120.transpose() / s_120 + Matrix3d::Identity()) * w;\n  m3 = (s_012 * r012 - r120.transpose() / s_120 + Matrix3d::Identity()) * w;\n  Add3x3MatrixToTripletList(m1, start_row + 6, cols[0], triplet_list);\n  Add3x3MatrixToTripletList(m2, start_row + 6, cols[1], triplet_list);\n  Add3x3MatrixToTripletList(m3, start_row + 6, cols[2], triplet_list);\n}\n\n// Returns true if the vector R1 * (c2 - c1) is in the same direction as t_12.\nbool VectorsAreSameDirection(const Vector3d& position1,\n                             const Vector3d& position2,\n                             const Vector3d& rotation1,\n                             const Vector3d& relative_position12) {\n  const Vector3d global_relative_position =\n      (position2 - position1).normalized();\n  Vector3d rotated_relative_position;\n  ceres::AngleAxisRotatePoint(rotation1.data(),\n                              global_relative_position.data(),\n                              rotated_relative_position.data());\n  return rotated_relative_position.dot(relative_position12) > 0;\n}\n\n}  // namespace\n\nLinearPositionEstimator::LinearPositionEstimator(\n    const Options& options,\n    const Reconstruction& reconstruction)\n    : options_(options), reconstruction_(reconstruction) {\n  CHECK_GT(options.num_threads, 0);\n}\n\nbool LinearPositionEstimator::EstimatePositions(\n    const std::unordered_map<ViewIdPair, TwoViewInfo>& view_pairs,\n    const std::unordered_map<ViewId, Vector3d>& orientations,\n    std::unordered_map<ViewId, Vector3d>* positions) {\n  CHECK_NOTNULL(positions)->clear();\n\n  // Extract triplets from the view pairs. As of now, we only consider the\n  // largest connected triplet in the viewing graph.\n  // TODO(cmsweeney): Utilize all connected triplet graphs.\n  VLOG(2) << \"Extracting triplets from the viewing graph.\";\n  TripletExtractor extractor;\n  std::vector<std::vector<ViewTriplet> > triplets_vec;\n  CHECK(extractor.ExtractTripletsFromViewPairs(view_pairs, &triplets_vec));\n  // Find the largest triplet.\n  int largest_triplet_graph = 0;\n  for (int i = 1; i < triplets_vec.size(); i++) {\n    if (triplets_vec[i].size() > triplets_vec[largest_triplet_graph].size()) {\n      largest_triplet_graph = i;\n    }\n  }\n  triplets_ = triplets_vec[largest_triplet_graph];\n\n  // Count the number of times each view is in a triplet.\n  for (int i = 0; i < triplets_.size(); i++) {\n    num_triplets_for_view_[triplets_[i].view_ids[0]] =\n        num_triplets_for_view_[triplets_[i].view_ids[0]] + 1;\n    num_triplets_for_view_[triplets_[i].view_ids[1]] =\n        num_triplets_for_view_[triplets_[i].view_ids[1]] + 1;\n    num_triplets_for_view_[triplets_[i].view_ids[2]] =\n        num_triplets_for_view_[triplets_[i].view_ids[2]] + 1;\n\n    // Determine the order of the views in the linear system. We subtract 1 from\n    // the linear system index so that the first position added to the system\n    // will be set constant (index of -1 is intentionally not evaluated later).\n    InsertIfNotPresent(&linear_system_index_,\n                       triplets_[i].view_ids[0],\n                       linear_system_index_.size() - 1);\n    InsertIfNotPresent(&linear_system_index_,\n                       triplets_[i].view_ids[1],\n                       linear_system_index_.size() - 1);\n    InsertIfNotPresent(&linear_system_index_,\n                       triplets_[i].view_ids[2],\n                       linear_system_index_.size() - 1);\n  }\n\n  VLOG(2) << \"Determining baseline ratios within each triplet...\";\n  // Baselines where (x, y, z) corresponds to the baseline of the first, second,\n  // and third view pair in the triplet.\n  std::vector<Vector3d> baselines(triplets_.size());\n  std::unique_ptr<ThreadPool> pool(new ThreadPool(options_.num_threads));\n  for (int i = 0; i < triplets_.size(); i++) {\n    pool->Add(&LinearPositionEstimator::ComputeBaselineRatioForTriplet,\n              this,\n              triplets_[i],\n              &baselines[i]);\n  }\n  // Wait for the baseline ratio computation to finish.\n  pool.reset(nullptr);\n\n  VLOG(2) << \"Building the constraint matrix...\";\n  // Create the linear system based on triplet constraints.\n  Eigen::SparseMatrix<double> constraint_matrix;\n  CreateLinearSystem(orientations, baselines, &constraint_matrix);\n  // Try to remove any 0 elements that were accidentally added.\n  constraint_matrix.makeCompressed();\n\n  const Eigen::SparseMatrix<double> aTa(constraint_matrix.transpose() *\n                                        constraint_matrix);\n\n  // Solve for positions by examining the smallest eigenvalues. Since we have\n  // set one position constant at the origin, we only need to solve for the\n  // eigenvector corresponding to the smallest eigenvalue. This can be done\n  // efficiently with inverse power iterations.\n  VLOG(2) << \"Solving for positions from the sparse eigenvalue problem...\";\n  SparseSymShiftSolveLLT op(aTa);\n  Spectra::SymEigsShiftSolver<double, Spectra::LARGEST_MAGN,\n                              SparseSymShiftSolveLLT> eigs(&op, 1, 6, 0.0);\n  eigs.init();\n  eigs.compute();\n  // Compute with power iterations.\n  const Eigen::VectorXd solution = eigs.eigenvectors().col(0);\n\n  // Add the solutions to the output. Set the position with an index of -1 to\n  // be at the origin.\n  for (const auto& view_index : linear_system_index_) {\n    if (view_index.second < 0) {\n      (*positions)[view_index.first].setZero();\n    } else {\n      (*positions)[view_index.first] =\n          solution.segment<3>(view_index.second * 3);\n    }\n  }\n\n  // Flip the sign of the positions if necessary.\n  FlipSignOfPositionsIfNecessary(orientations, positions);\n\n  return true;\n}\n\nvoid LinearPositionEstimator::ComputeBaselineRatioForTriplet(\n    const ViewTriplet& triplet, Vector3d* baseline) {\n  baseline->setZero();\n\n  const View& view1 = *reconstruction_.View(triplet.view_ids[0]);\n  const View& view2 = *reconstruction_.View(triplet.view_ids[1]);\n  const View& view3 = *reconstruction_.View(triplet.view_ids[2]);\n\n  // Find common tracks.\n  const std::vector<ViewId> triplet_view_ids = {\n      triplet.view_ids[0], triplet.view_ids[1], triplet.view_ids[2]};\n  const std::vector<TrackId>& common_tracks =\n      FindCommonTracksInViews(reconstruction_, triplet_view_ids);\n\n  // Normalize all features.\n  std::vector<Feature> feature1, feature2, feature3;\n  feature1.reserve(common_tracks.size());\n  feature2.reserve(common_tracks.size());\n  feature3.reserve(common_tracks.size());\n  for (const TrackId track_id : common_tracks) {\n    feature1.emplace_back(GetNormalizedFeature(view1, track_id));\n    feature2.emplace_back(GetNormalizedFeature(view2, track_id));\n    feature3.emplace_back(GetNormalizedFeature(view3, track_id));\n  }\n\n  // Get the baseline ratios.\n  ComputeTripletBaselineRatios(triplet, feature1, feature2, feature3, baseline);\n}\n\n// Sets up the linear system with the constraints that each triplet adds.\nvoid LinearPositionEstimator::CreateLinearSystem(\n    const std::unordered_map<ViewId, Vector3d>& orientations,\n    const std::vector<Vector3d>& baselines,\n    Eigen::SparseMatrix<double>* constraint_matrix) {\n  const int num_views = num_triplets_for_view_.size();\n\n  std::vector<Eigen::Triplet<double> > triplet_list;\n\n  int num_valid_triplets = 0;\n  for (int i = 0; i < triplets_.size(); i++) {\n    // If we were not able to extract a stable baseline for this triplet then\n    // skip this triplet.\n    if (baselines[i] == Eigen::Vector3d::Zero()) {\n      continue;\n    }\n\n    const ViewTriplet& triplet = triplets_[i];\n    const std::vector<Vector3d> triplet_orientations = {\n      FindOrDie(orientations, triplet.view_ids[0]),\n      FindOrDie(orientations, triplet.view_ids[1]),\n      FindOrDie(orientations, triplet.view_ids[2])\n    };\n    // Get the row and columns that we will modify.\n    const std::vector<int> cols = {\n        static_cast<int>(3 *\n                         FindOrDie(linear_system_index_, triplet.view_ids[0])),\n        static_cast<int>(3 *\n                         FindOrDie(linear_system_index_, triplet.view_ids[1])),\n        static_cast<int>(3 *\n                         FindOrDie(linear_system_index_, triplet.view_ids[2]))};\n\n    const double w =\n        1.0 / sqrt(std::min({num_triplets_for_view_[triplet.view_ids[0]],\n                             num_triplets_for_view_[triplet.view_ids[1]],\n                             num_triplets_for_view_[triplet.view_ids[2]]}));\n    AddTripletConstraint(triplet,\n                         9 * num_valid_triplets,\n                         cols,\n                         w,\n                         triplet_orientations,\n                         baselines[i],\n                         &triplet_list);\n    ++num_valid_triplets;\n  }\n  // One position is set constant, which is why we use (num_views - 1) * 3\n  // columns.\n  constraint_matrix->resize(num_valid_triplets * 9, (num_views - 1) * 3);\n  constraint_matrix->setFromTriplets(triplet_list.begin(), triplet_list.end());\n}\n\nFeature LinearPositionEstimator::GetNormalizedFeature(const View& view,\n                                                      const TrackId track_id) {\n  Feature normalized_feature = *view.GetFeature(track_id);\n  const Camera& camera = view.Camera();\n  normalized_feature.y() = (normalized_feature.y() - camera.PrincipalPointY()) /\n                           (camera.FocalLength() * camera.AspectRatio());\n  normalized_feature.x() =\n      (normalized_feature.x() - camera.Skew() * normalized_feature.y() -\n       camera.PrincipalPointX()) /\n      camera.FocalLength();\n  return normalized_feature;\n}\n\nvoid LinearPositionEstimator::FlipSignOfPositionsIfNecessary(\n    const std::unordered_map<ViewId, Vector3d>& orientation,\n    std::unordered_map<ViewId, Vector3d>* positions) {\n  // If this value is below zero, then we should flip the sign.\n  int correct_sign_votes = 0;\n\n  std::unordered_set<ViewIdPair> pairs_visited;\n  for (const ViewTriplet& triplet : triplets_) {\n    const ViewIdPair id_pair_12(triplet.view_ids[0], triplet.view_ids[1]);\n    const ViewIdPair id_pair_13(triplet.view_ids[0], triplet.view_ids[2]);\n    const ViewIdPair id_pair_23(triplet.view_ids[1], triplet.view_ids[2]);\n\n    // It is not guaranteed that these positions are needed, but it should be\n    // very fast to fetch them regardless so this will not be a significant\n    // performance cost.\n    const Vector3d& position1 = FindOrDie(*positions, triplet.view_ids[0]);\n    const Vector3d& position2 = FindOrDie(*positions, triplet.view_ids[1]);\n    const Vector3d& position3 = FindOrDie(*positions, triplet.view_ids[2]);\n\n    // Check the relative translation of views 1 and 2 in the triplet.\n    if (!ContainsKey(pairs_visited, id_pair_12)) {\n      pairs_visited.insert(id_pair_12);\n      correct_sign_votes +=\n          (VectorsAreSameDirection(position1, position2,\n                                   FindOrDie(orientation, id_pair_12.first),\n                                   triplet.info_one_two.position_2))\n              ? 1\n              : -1;\n    }\n\n    // Check the relative translation of views 1 and 3 in the triplet.\n    if (!ContainsKey(pairs_visited, id_pair_13)) {\n      pairs_visited.insert(id_pair_13);\n      correct_sign_votes +=\n          (VectorsAreSameDirection(position1, position3,\n                                   FindOrDie(orientation, id_pair_13.first),\n                                   triplet.info_one_three.position_2))\n              ? 1\n              : -1;\n    }\n\n    // Check the relative translation of views 2 and 3 in the triplet.\n    if (!ContainsKey(pairs_visited, id_pair_23)) {\n      pairs_visited.insert(id_pair_23);\n      correct_sign_votes +=\n          (VectorsAreSameDirection(position2, position3,\n                                   FindOrDie(orientation, id_pair_23.first),\n                                   triplet.info_two_three.position_2))\n              ? 1\n              : -1;\n    }\n  }\n\n  // If the sign of the votes is below zero, we must flip the sign of all\n  // position estimates.\n  if (correct_sign_votes < 0) {\n    const int num_correct_votes =\n        (pairs_visited.size() + correct_sign_votes) / 2;\n    VLOG(2) << \"Sign of the positions was incorrect: \" << num_correct_votes\n            << \" of \" << pairs_visited.size()\n            << \" relative translations had the correct sign. \"\n               \"Flipping the sign of the camera positions.\";\n    for (auto& position : *positions) {\n      position.second *= -1.0;\n    }\n  }\n}\n\n}  // namespace theia\n", "meta": {"hexsha": "e40e9f1c15c10ce05ffdf96f720dd2dd7dadadba", "size": 18810, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/theia/sfm/global_pose_estimation/linear_position_estimator.cc", "max_stars_repo_name": "hunter-packages/TheiaSfM", "max_stars_repo_head_hexsha": "07e142435946e94324cf395ce19e917bca2e6333", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/theia/sfm/global_pose_estimation/linear_position_estimator.cc", "max_issues_repo_name": "hunter-packages/TheiaSfM", "max_issues_repo_head_hexsha": "07e142435946e94324cf395ce19e917bca2e6333", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/theia/sfm/global_pose_estimation/linear_position_estimator.cc", "max_forks_repo_name": "hunter-packages/TheiaSfM", "max_forks_repo_head_hexsha": "07e142435946e94324cf395ce19e917bca2e6333", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-10-01T04:02:04.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-01T07:43:16.000Z", "avg_line_length": 42.75, "max_line_length": 80, "alphanum_fraction": 0.678096757, "num_tokens": 4699, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6825737344123242, "lm_q2_score": 0.5039061705290805, "lm_q1q2_score": 0.3439531166114479}}
{"text": "//          Copyright (C) 2012, Michele Caini.\n// Distributed under the Boost Software License, Version 1.0.\n//    (See accompanying file LICENSE_1_0.txt or copy at\n//          http://www.boost.org/LICENSE_1_0.txt)\n\n//          Two Graphs Common Spanning Trees Algorithm\n//      Based on academic article of Mint, Read and Tarjan\n//     Efficient Algorithm for Common Spanning Tree Problem\n// Electron. Lett., 28 April 1983, Volume 19, Issue 9, p.346-347\n\n#ifndef BOOST_GRAPH_TWO_GRAPHS_COMMON_SPANNING_TREES_HPP\n#define BOOST_GRAPH_TWO_GRAPHS_COMMON_SPANNING_TREES_HPP\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\nnamespace boost\n{\n\nnamespace detail\n{\n\n    template < typename TreeMap, typename PredMap, typename DistMap,\n        typename LowMap, typename Buffer >\n    struct bridges_visitor : public default_dfs_visitor\n    {\n        bridges_visitor(TreeMap tree, PredMap pred, DistMap dist, LowMap low,\n            Buffer& buffer)\n        : mTree(tree), mPred(pred), mDist(dist), mLow(low), mBuffer(buffer)\n        {\n            mNum = -1;\n        }\n\n        template < typename Vertex, typename Graph >\n        void initialize_vertex(const Vertex& u, const Graph& g)\n        {\n            put(mPred, u, u);\n            put(mDist, u, -1);\n        }\n\n        template < typename Vertex, typename Graph >\n        void discover_vertex(const Vertex& u, const Graph& g)\n        {\n            put(mDist, u, ++mNum);\n            put(mLow, u, get(mDist, u));\n        }\n\n        template < typename Edge, typename Graph >\n        void tree_edge(const Edge& e, const Graph& g)\n        {\n            put(mPred, target(e, g), source(e, g));\n            put(mTree, target(e, g), e);\n        }\n\n        template < typename Edge, typename Graph >\n        void back_edge(const Edge& e, const Graph& g)\n        {\n            put(mLow, source(e, g),\n                (std::min)(get(mLow, source(e, g)), get(mDist, target(e, g))));\n        }\n\n        template < typename Vertex, typename Graph >\n        void finish_vertex(const Vertex& u, const Graph& g)\n        {\n            Vertex parent = get(mPred, u);\n            if (get(mLow, u) > get(mDist, parent))\n                mBuffer.push(get(mTree, u));\n            put(mLow, parent, (std::min)(get(mLow, parent), get(mLow, u)));\n        }\n\n        TreeMap mTree;\n        PredMap mPred;\n        DistMap mDist;\n        LowMap mLow;\n        Buffer& mBuffer;\n        int mNum;\n    };\n\n    template < typename Buffer >\n    struct cycle_finder : public base_visitor< cycle_finder< Buffer > >\n    {\n        typedef on_back_edge event_filter;\n        cycle_finder() : mBuffer(0) {}\n        cycle_finder(Buffer* buffer) : mBuffer(buffer) {}\n        template < typename Edge, typename Graph >\n        void operator()(const Edge& e, const Graph& g)\n        {\n            if (mBuffer)\n                mBuffer->push(e);\n        }\n        Buffer* mBuffer;\n    };\n\n    template < typename DeletedMap > struct deleted_edge_status\n    {\n        deleted_edge_status() {}\n        deleted_edge_status(DeletedMap map) : mMap(map) {}\n        template < typename Edge > bool operator()(const Edge& e) const\n        {\n            return (!get(mMap, e));\n        }\n        DeletedMap mMap;\n    };\n\n    template < typename InLMap > struct inL_edge_status\n    {\n        inL_edge_status() {}\n        inL_edge_status(InLMap map) : mMap(map) {}\n        template < typename Edge > bool operator()(const Edge& e) const\n        {\n            return get(mMap, e);\n        }\n        InLMap mMap;\n    };\n\n    template < typename Graph, typename Func, typename Seq, typename Map >\n    void rec_two_graphs_common_spanning_trees(const Graph& iG,\n        bimap< bimaps::set_of< int >,\n            bimaps::set_of< typename graph_traits< Graph >::edge_descriptor > >\n            iG_bimap,\n        Map aiG_inL, Map diG, const Graph& vG,\n        bimap< bimaps::set_of< int >,\n            bimaps::set_of< typename graph_traits< Graph >::edge_descriptor > >\n            vG_bimap,\n        Map avG_inL, Map dvG, Func func, Seq inL)\n    {\n        typedef graph_traits< Graph > GraphTraits;\n\n        typedef typename GraphTraits::vertex_descriptor vertex_descriptor;\n        typedef typename GraphTraits::edge_descriptor edge_descriptor;\n\n        typedef typename Seq::size_type seq_size_type;\n\n        int edges = num_vertices(iG) - 1;\n        //\n        //  [ Michele Caini ]\n        //\n        //  Using the condition (edges != 0) leads to the accidental submission\n        //  of\n        //    sub-graphs ((V-1+1)-fake-tree, named here fat-tree).\n        //  Remove this condition is a workaround for the problem of fat-trees.\n        //  Please do not add that condition, even if it improves performance.\n        //\n        //  Here is proposed the previous guard (that was wrong):\n        //     for(seq_size_type i = 0; (i < inL.size()) && (edges != 0); ++i)\n        //\n        {\n            for (seq_size_type i = 0; i < inL.size(); ++i)\n                if (inL[i])\n                    --edges;\n\n            if (edges < 0)\n                return;\n        }\n\n        bool is_tree = (edges == 0);\n        if (is_tree)\n        {\n            func(inL);\n        }\n        else\n        {\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            {\n                if (!inL[j] && !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(detail::cycle_finder<\n                            std::stack< edge_descriptor > >(&iG_buf)),\n                        associative_property_map<\n                            std::map< vertex_descriptor, default_color_type > >(\n                            vertex_color),\n                        associative_property_map<\n                            std::map< edge_descriptor, default_color_type > >(\n                            edge_color));\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(detail::cycle_finder<\n                            std::stack< edge_descriptor > >(&vG_buf)),\n                        associative_property_map<\n                            std::map< vertex_descriptor, default_color_type > >(\n                            vertex_color),\n                        associative_property_map<\n                            std::map< edge_descriptor, default_color_type > >(\n                            edge_color));\n\n                    if (iG_buf.empty() && vG_buf.empty())\n                    {\n                        inL[j] = true;\n                        found = true;\n                        m = j;\n                    }\n                    else\n                    {\n                        while (!iG_buf.empty())\n                            iG_buf.pop();\n                        while (!vG_buf.empty())\n                            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\n                std::stack< edge_descriptor > iG_buf_copy, vG_buf_copy;\n                for (seq_size_type j = 0; j < inL.size(); ++j)\n                {\n                    if (!inL[j] && !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<\n                                    associative_property_map<\n                                        std::map< edge_descriptor, bool > > >(\n                                    aiG_inL)),\n                            make_dfs_visitor(detail::cycle_finder<\n                                std::stack< edge_descriptor > >(&iG_buf)),\n                            associative_property_map< std::map<\n                                vertex_descriptor, default_color_type > >(\n                                vertex_color),\n                            associative_property_map< std::map< edge_descriptor,\n                                default_color_type > >(edge_color));\n                        undirected_dfs(\n                            make_filtered_graph(vG,\n                                detail::inL_edge_status<\n                                    associative_property_map<\n                                        std::map< edge_descriptor, bool > > >(\n                                    avG_inL)),\n                            make_dfs_visitor(detail::cycle_finder<\n                                std::stack< edge_descriptor > >(&vG_buf)),\n                            associative_property_map< std::map<\n                                vertex_descriptor, default_color_type > >(\n                                vertex_color),\n                            associative_property_map< std::map< edge_descriptor,\n                                default_color_type > >(edge_color));\n\n                        if (!iG_buf.empty() || !vG_buf.empty())\n                        {\n                            while (!iG_buf.empty())\n                                iG_buf.pop();\n                            while (!vG_buf.empty())\n                                vG_buf.pop();\n                            put(diG, iG_bimap.left.at(j), true);\n                            put(dvG, vG_bimap.left.at(j), true);\n                            iG_buf_copy.push(iG_bimap.left.at(j));\n                            vG_buf_copy.push(vG_bimap.left.at(j));\n                        }\n\n                        put(aiG_inL, iG_bimap.left.at(j), false);\n                        put(avG_inL, vG_bimap.left.at(j), false);\n                    }\n                }\n\n                // REC\n                detail::rec_two_graphs_common_spanning_trees< Graph, Func, Seq,\n                    Map >(iG, iG_bimap, aiG_inL, diG, vG, vG_bimap, aiG_inL,\n                    dvG, func, inL);\n\n                while (!iG_buf_copy.empty())\n                {\n                    put(diG, iG_buf_copy.top(), false);\n                    put(dvG,\n                        vG_bimap.left.at(iG_bimap.right.at(iG_buf_copy.top())),\n                        false);\n                    iG_buf_copy.pop();\n                }\n                while (!vG_buf_copy.empty())\n                {\n                    put(dvG, vG_buf_copy.top(), false);\n                    put(diG,\n                        iG_bimap.left.at(vG_bimap.right.at(vG_buf_copy.top())),\n                        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                    associative_property_map<\n                        std::map< vertex_descriptor, vertex_descriptor > >,\n                    associative_property_map<\n                        std::map< vertex_descriptor, int > >,\n                    associative_property_map<\n                        std::map< vertex_descriptor, int > >,\n                    std::stack< edge_descriptor > >\n                iG_vis(associative_property_map<\n                           std::map< vertex_descriptor, edge_descriptor > >(\n                           tree_map),\n                    associative_property_map<\n                        std::map< vertex_descriptor, vertex_descriptor > >(\n                        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                    vG_vis(associative_property_map<\n                               std::map< vertex_descriptor, edge_descriptor > >(\n                               tree_map),\n                        associative_property_map<\n                            std::map< vertex_descriptor, vertex_descriptor > >(\n                            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                undirected_dfs(\n                    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 > >(\n                        vertex_color),\n                    associative_property_map<\n                        std::map< edge_descriptor, default_color_type > >(\n                        edge_color));\n                undirected_dfs(\n                    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 > >(\n                        vertex_color),\n                    associative_property_map<\n                        std::map< edge_descriptor, default_color_type > >(\n                        edge_color));\n\n                found = false;\n                std::stack< edge_descriptor > iG_buf_tmp, vG_buf_tmp;\n                while (!iG_buf.empty() && !found)\n                {\n                    if (!inL[iG_bimap.right.at(iG_buf.top())])\n                    {\n                        put(aiG_inL, iG_buf.top(), true);\n                        put(avG_inL,\n                            vG_bimap.left.at(iG_bimap.right.at(iG_buf.top())),\n                            true);\n\n                        undirected_dfs(\n                            make_filtered_graph(iG,\n                                detail::inL_edge_status<\n                                    associative_property_map<\n                                        std::map< edge_descriptor, bool > > >(\n                                    aiG_inL)),\n                            make_dfs_visitor(detail::cycle_finder<\n                                std::stack< edge_descriptor > >(&iG_buf_tmp)),\n                            associative_property_map< std::map<\n                                vertex_descriptor, default_color_type > >(\n                                vertex_color),\n                            associative_property_map< std::map< edge_descriptor,\n                                default_color_type > >(edge_color));\n                        undirected_dfs(\n                            make_filtered_graph(vG,\n                                detail::inL_edge_status<\n                                    associative_property_map<\n                                        std::map< edge_descriptor, bool > > >(\n                                    avG_inL)),\n                            make_dfs_visitor(detail::cycle_finder<\n                                std::stack< edge_descriptor > >(&vG_buf_tmp)),\n                            associative_property_map< std::map<\n                                vertex_descriptor, default_color_type > >(\n                                vertex_color),\n                            associative_property_map< std::map< edge_descriptor,\n                                default_color_type > >(edge_color));\n\n                        if (!iG_buf_tmp.empty() || !vG_buf_tmp.empty())\n                        {\n                            found = true;\n                        }\n                        else\n                        {\n                            while (!iG_buf_tmp.empty())\n                                iG_buf_tmp.pop();\n                            while (!vG_buf_tmp.empty())\n                                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,\n                            vG_bimap.left.at(iG_bimap.right.at(iG_buf.top())),\n                            false);\n                    }\n                    iG_buf.pop();\n                }\n                while (!vG_buf.empty() && !found)\n                {\n                    if (!inL[vG_bimap.right.at(vG_buf.top())])\n                    {\n                        put(avG_inL, vG_buf.top(), true);\n                        put(aiG_inL,\n                            iG_bimap.left.at(vG_bimap.right.at(vG_buf.top())),\n                            true);\n\n                        undirected_dfs(\n                            make_filtered_graph(iG,\n                                detail::inL_edge_status<\n                                    associative_property_map<\n                                        std::map< edge_descriptor, bool > > >(\n                                    aiG_inL)),\n                            make_dfs_visitor(detail::cycle_finder<\n                                std::stack< edge_descriptor > >(&iG_buf_tmp)),\n                            associative_property_map< std::map<\n                                vertex_descriptor, default_color_type > >(\n                                vertex_color),\n                            associative_property_map< std::map< edge_descriptor,\n                                default_color_type > >(edge_color));\n                        undirected_dfs(\n                            make_filtered_graph(vG,\n                                detail::inL_edge_status<\n                                    associative_property_map<\n                                        std::map< edge_descriptor, bool > > >(\n                                    avG_inL)),\n                            make_dfs_visitor(detail::cycle_finder<\n                                std::stack< edge_descriptor > >(&vG_buf_tmp)),\n                            associative_property_map< std::map<\n                                vertex_descriptor, default_color_type > >(\n                                vertex_color),\n                            associative_property_map< std::map< edge_descriptor,\n                                default_color_type > >(edge_color));\n\n                        if (!iG_buf_tmp.empty() || !vG_buf_tmp.empty())\n                        {\n                            found = true;\n                        }\n                        else\n                        {\n                            while (!iG_buf_tmp.empty())\n                                iG_buf_tmp.pop();\n                            while (!vG_buf_tmp.empty())\n                                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,\n                            iG_bimap.left.at(vG_bimap.right.at(vG_buf.top())),\n                            false);\n                    }\n                    vG_buf.pop();\n                }\n\n                if (!found)\n                {\n\n                    while (!iG_buf_copy.empty())\n                    {\n                        inL[iG_bimap.right.at(iG_buf_copy.top())] = true;\n                        put(aiG_inL, iG_buf_copy.top(), true);\n                        put(avG_inL,\n                            vG_bimap.left.at(\n                                iG_bimap.right.at(iG_buf_copy.top())),\n                            true);\n                        iG_buf.push(iG_buf_copy.top());\n                        iG_buf_copy.pop();\n                    }\n                    while (!vG_buf_copy.empty())\n                    {\n                        inL[vG_bimap.right.at(vG_buf_copy.top())] = true;\n                        put(avG_inL, vG_buf_copy.top(), true);\n                        put(aiG_inL,\n                            iG_bimap.left.at(\n                                vG_bimap.right.at(vG_buf_copy.top())),\n                            true);\n                        vG_buf.push(vG_buf_copy.top());\n                        vG_buf_copy.pop();\n                    }\n\n                    // REC\n                    detail::rec_two_graphs_common_spanning_trees< Graph, Func,\n                        Seq, Map >(iG, iG_bimap, aiG_inL, diG, vG, vG_bimap,\n                        aiG_inL, dvG, func, inL);\n\n                    while (!iG_buf.empty())\n                    {\n                        inL[iG_bimap.right.at(iG_buf.top())] = false;\n                        put(aiG_inL, iG_buf.top(), false);\n                        put(avG_inL,\n                            vG_bimap.left.at(iG_bimap.right.at(iG_buf.top())),\n                            false);\n                        iG_buf.pop();\n                    }\n                    while (!vG_buf.empty())\n                    {\n                        inL[vG_bimap.right.at(vG_buf.top())] = false;\n                        put(avG_inL, vG_buf.top(), false);\n                        put(aiG_inL,\n                            iG_bimap.left.at(vG_bimap.right.at(vG_buf.top())),\n                            false);\n                        vG_buf.pop();\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} // namespace detail\n\ntemplate < typename Coll, typename Seq > struct tree_collector\n{\n\npublic:\n    BOOST_CONCEPT_ASSERT((BackInsertionSequence< Coll >));\n    BOOST_CONCEPT_ASSERT((RandomAccessContainer< Seq >));\n    BOOST_CONCEPT_ASSERT((CopyConstructible< Seq >));\n\n    typedef typename Coll::value_type coll_value_type;\n    typedef typename Seq::value_type seq_value_type;\n\n    BOOST_STATIC_ASSERT((is_same< coll_value_type, Seq >::value));\n    BOOST_STATIC_ASSERT((is_same< seq_value_type, bool >::value));\n\n    tree_collector(Coll& seqs) : mSeqs(seqs) {}\n\n    inline void operator()(Seq seq) { mSeqs.push_back(seq); }\n\nprivate:\n    Coll& mSeqs;\n};\n\ntemplate < typename Graph, typename Order, typename Func, typename Seq >\nBOOST_CONCEPT_REQUIRES(\n    ((RandomAccessContainer< Order >))((IncidenceGraphConcept< Graph >))(\n        (UnaryFunction< Func, void, Seq >))(\n        (Mutable_RandomAccessContainer< Seq >))(\n        (VertexAndEdgeListGraphConcept< Graph >)),\n    (void))\ntwo_graphs_common_spanning_trees(const Graph& iG, Order iG_map, const Graph& vG,\n    Order vG_map, Func func, Seq inL)\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::value_type seq_value_type;\n    typedef typename Seq::size_type seq_size_type;\n\n    typedef typename Order::value_type order_value_type;\n    typedef typename Order::size_type order_size_type;\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) || inL.size() != num_edges(vG))\n        return;\n\n    if (iG_map.size() != num_edges(iG) || vG_map.size() != num_edges(vG))\n        return;\n\n    typedef bimaps::bimap< bimaps::set_of< int >,\n        bimaps::set_of< order_value_type > >\n        bimap_type;\n    typedef typename bimap_type::value_type bimap_value;\n\n    bimap_type iG_bimap, vG_bimap;\n    for (order_size_type i = 0; i < iG_map.size(); ++i)\n        iG_bimap.insert(bimap_value(i, iG_map[i]));\n    for (order_size_type i = 0; i < vG_map.size(); ++i)\n        vG_bimap.insert(bimap_value(i, vG_map[i]));\n\n    edge_iterator current, last;\n    boost::tuples::tie(current, last) = edges(iG);\n    for (; current != last; ++current)\n        if (iG_bimap.right.find(*current) == iG_bimap.right.end())\n            return;\n    boost::tuples::tie(current, last) = edges(vG);\n    for (; current != last; ++current)\n        if (vG_bimap.right.find(*current) == vG_bimap.right.end())\n            return;\n\n    std::stack< edge_descriptor > iG_buf, vG_buf;\n\n    std::map< vertex_descriptor, edge_descriptor > tree_map;\n    std::map< vertex_descriptor, vertex_descriptor > pred_map;\n    std::map< vertex_descriptor, int > dist_map, low_map;\n\n    detail::bridges_visitor< associative_property_map< std::map<\n                                 vertex_descriptor, edge_descriptor > >,\n        associative_property_map<\n            std::map< vertex_descriptor, vertex_descriptor > >,\n        associative_property_map< std::map< vertex_descriptor, int > >,\n        associative_property_map< std::map< vertex_descriptor, int > >,\n        std::stack< edge_descriptor > >\n    iG_vis(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 > >(\n            dist_map),\n        associative_property_map< std::map< vertex_descriptor, int > >(low_map),\n        iG_buf),\n        vG_vis(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 > >(\n                dist_map),\n            associative_property_map< std::map< vertex_descriptor, int > >(\n                low_map),\n            vG_buf);\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    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    while (!iG_buf.empty())\n    {\n        inL[iG_bimap.right.at(iG_buf.top())] = true;\n        iG_buf.pop();\n    }\n    while (!vG_buf.empty())\n    {\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 > > aiG_inL(\n        iG_inL),\n        avG_inL(vG_inL);\n\n    for (seq_size_type i = 0; i < inL.size(); ++i)\n    {\n        if (inL[i])\n        {\n            put(aiG_inL, iG_bimap.left.at(i), true);\n            put(avG_inL, vG_bimap.left.at(i), true);\n        }\n        else\n        {\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<\n                associative_property_map< std::map< edge_descriptor, bool > > >(\n                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    undirected_dfs(\n        make_filtered_graph(vG,\n            detail::inL_edge_status<\n                associative_property_map< std::map< edge_descriptor, bool > > >(\n                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    if (iG_buf.empty() && vG_buf.empty())\n    {\n\n        std::map< edge_descriptor, bool > iG_deleted, vG_deleted;\n        associative_property_map< std::map< edge_descriptor, bool > > diG(\n            iG_deleted);\n        associative_property_map< std::map< edge_descriptor, bool > > dvG(\n            vG_deleted);\n\n        boost::tuples::tie(current, last) = edges(iG);\n        for (; current != last; ++current)\n            put(diG, *current, false);\n        boost::tuples::tie(current, last) = edges(vG);\n        for (; current != last; ++current)\n            put(dvG, *current, false);\n\n        for (seq_size_type j = 0; j < inL.size(); ++j)\n        {\n            if (!inL[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 > >(\n                            &iG_buf)),\n                    associative_property_map<\n                        std::map< vertex_descriptor, default_color_type > >(\n                        vertex_color),\n                    associative_property_map<\n                        std::map< edge_descriptor, default_color_type > >(\n                        edge_color));\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 > >(\n                            &vG_buf)),\n                    associative_property_map<\n                        std::map< vertex_descriptor, default_color_type > >(\n                        vertex_color),\n                    associative_property_map<\n                        std::map< edge_descriptor, default_color_type > >(\n                        edge_color));\n\n                if (!iG_buf.empty() || !vG_buf.empty())\n                {\n                    while (!iG_buf.empty())\n                        iG_buf.pop();\n                    while (!vG_buf.empty())\n                        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 > >(\n                com_map));\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 > >(\n                com_map));\n\n        if (cc != 2)\n            return;\n\n        // REC\n        detail::rec_two_graphs_common_spanning_trees< Graph, Func, Seq,\n            associative_property_map< std::map< edge_descriptor, bool > > >(\n            iG, iG_bimap, aiG_inL, diG, vG, vG_bimap, aiG_inL, dvG, func, inL);\n    }\n}\n\ntemplate < typename Graph, typename Func, typename Seq >\nBOOST_CONCEPT_REQUIRES(\n    ((IncidenceGraphConcept< Graph >))((EdgeListGraphConcept< Graph >)), (void))\ntwo_graphs_common_spanning_trees(\n    const Graph& iG, const Graph& vG, Func func, Seq inL)\n{\n    typedef graph_traits< Graph > GraphTraits;\n\n    typedef typename GraphTraits::edge_descriptor edge_descriptor;\n    typedef typename GraphTraits::edge_iterator edge_iterator;\n\n    std::vector< edge_descriptor > iGO, vGO;\n    edge_iterator curr, last;\n\n    boost::tuples::tie(curr, last) = edges(iG);\n    for (; curr != last; ++curr)\n        iGO.push_back(*curr);\n\n    boost::tuples::tie(curr, last) = edges(vG);\n    for (; curr != last; ++curr)\n        vGO.push_back(*curr);\n\n    two_graphs_common_spanning_trees(iG, iGO, vG, vGO, func, inL);\n}\n\n} // namespace boost\n\n#endif // BOOST_GRAPH_TWO_GRAPHS_COMMON_SPANNING_TREES_HPP\n", "meta": {"hexsha": "a41dc84b217f8a420bf9d78b88fc0ee86dbdbe15", "size": 34996, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ReactNativeFrontend/ios/Pods/boost/boost/graph/two_graphs_common_spanning_trees.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/two_graphs_common_spanning_trees.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/two_graphs_common_spanning_trees.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": 41.0269636577, "max_line_length": 80, "alphanum_fraction": 0.4926848783, "num_tokens": 7139, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6825737214979745, "lm_q2_score": 0.5039061705290805, "lm_q1q2_score": 0.3439531101038274}}
{"text": "/*******************************************************************************\n *\n * MIT License\n *\n * Copyright (c) 2019 Advanced Micro Devices, Inc.\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n *\n *******************************************************************************/\n#ifndef BFLOAT16_H_\n#define BFLOAT16_H_\n#include <boost/operators.hpp>\n#include <iostream>\n#include <miopen/config.h>\n\nclass bfloat16 : boost::totally_ordered<bfloat16, boost::arithmetic<bfloat16>>\n{\n    public:\n    bfloat16() : data_{0} {}\n    explicit bfloat16(float rhs)\n    {\n        union\n        {\n            float float_st;\n            std::uint32_t bf16_st;\n        } bits_st = {rhs};\n\n        // BF16 round and NaN preservation code matches\n        // https://github.com/ROCmSoftwarePlatform/rocBLAS/blob/develop/library/include/rocblas_bfloat16.h\n        if((~bits_st.bf16_st & 0x7f800000) == 0) // Inf or NaN\n        {\n            // When all of the exponent bits are 1, the value is Inf or NaN.\n            // Inf is indicated by a zero mantissa. NaN is indicated by any nonzero\n            // mantissa bit. Quiet NaN is indicated by the most significant mantissa\n            // bit being 1. Signaling NaN is indicated by the most significant\n            // mantissa bit being 0 but some other bit(s) being 1. If any of the\n            // lower 16 bits of the mantissa are 1, we set the least significant bit\n            // of the bfloat16 mantissa, in order to preserve signaling NaN in case\n            // the bloat16's mantissa bits are all 0.\n            if((bits_st.bf16_st & 0xffff) != 0)\n            {\n                bits_st.bf16_st |= 0x10000; // Preserve signaling NaN\n            }\n        }\n        else\n        {\n#if MIOPEN_USE_RNE_BFLOAT16 == 1\n            // When the exponent bits are not all 1s, then the value is zero, normal,\n            // or subnormal. We round the bfloat16 mantissa up by adding 0x7FFF, plus\n            // 1 if the least significant bit of the bfloat16 mantissa is 1 (odd).\n            // This causes the bfloat16's mantissa to be incremented by 1 if the 16\n            // least significant bits of the float mantissa are greater than 0x8000,\n            // or if they are equal to 0x8000 and the least significant bit of the\n            // bfloat16 mantissa is 1 (odd). This causes it to be rounded to even when\n            // the lower 16 bits are exactly 0x8000. If the bfloat16 mantissa already\n            // has the value 0x7f, then incrementing it causes it to become 0x00 and\n            // the exponent is incremented by one, which is the next higher FP value\n            // to the unrounded bfloat16 value. When the bfloat16 value is subnormal\n            // with an exponent of 0x00 and a mantissa of 0x7F, it may be rounded up\n            // to a normal value with an exponent of 0x01 and a mantissa of 0x00.\n            // When the bfloat16 value has an exponent of 0xFE and a mantissa of 0x7F,\n            // incrementing it causes it to become an exponent of 0xFF and a mantissa\n            // of 0x00, which is Inf, the next higher value to the unrounded value.\n            bits_st.bf16_st +=\n                (0x7fff + ((bits_st.bf16_st >> 16) & 1)); // Round to nearest, round to even\n#else                                                     // truncation\n// do nothing\n#endif\n        }\n        data_ = bits_st.bf16_st >> 16;\n    }\n    operator float() const\n    {\n        union\n        {\n            std::uint32_t bf16_st;\n            float float_st;\n        } bits_st = {data_};\n\n        bits_st.bf16_st = bits_st.bf16_st << 16;\n        return bits_st.float_st;\n    }\n\n    bfloat16 operator-() const { return bfloat16(-static_cast<float>(*this)); }\n    bfloat16 operator+() const { return *this; }\n\n    bfloat16& operator=(const float rhs)\n    {\n        *this = bfloat16(rhs);\n        return *this;\n    }\n    bfloat16& operator+=(bfloat16 rhs)\n    {\n        *this = bfloat16(static_cast<float>(*this) + static_cast<float>(rhs));\n        return *this;\n    }\n\n    bfloat16& operator+=(float rhs)\n    {\n        *this = bfloat16(static_cast<float>(*this) + rhs);\n        return *this;\n    }\n\n    bfloat16& operator-=(bfloat16 rhs)\n    {\n        *this += -rhs;\n        return *this;\n    }\n    bfloat16& operator*=(bfloat16 rhs)\n    {\n        *this = bfloat16(static_cast<float>(*this) * static_cast<float>(rhs));\n        return *this;\n    }\n    bfloat16& operator*=(float rhs)\n    {\n        *this = bfloat16(static_cast<float>(*this) * rhs);\n        return *this;\n    }\n\n    bfloat16& operator/=(bfloat16 rhs)\n    {\n        *this = bfloat16(static_cast<float>(*this) / static_cast<float>(rhs));\n        return *this;\n    }\n    bool operator<(bfloat16 rhs) const\n    {\n        return static_cast<float>(*this) < static_cast<float>(rhs);\n    }\n    bool operator==(bfloat16 rhs) const { return std::equal_to<float>()(*this, rhs); }\n\n    static constexpr bfloat16 generate(uint16_t val) { return bfloat16{val, true}; }\n\n    private:\n    constexpr bfloat16(std::uint16_t val, bool) : data_{val} {}\n\n    std::uint16_t data_;\n};\n\nnamespace std {\ntemplate <>\nclass numeric_limits<bfloat16>\n{\n    public:\n    static constexpr bool is_specialized = true;\n    static constexpr bfloat16 min() noexcept { return bfloat16::generate(0x007F); }\n    static constexpr bfloat16 max() noexcept { return bfloat16::generate(0x7F7F); }\n    static constexpr bfloat16 lowest() noexcept { return bfloat16::generate(0xFF7F); }\n    static constexpr bfloat16 epsilon() noexcept { return bfloat16::generate(0x3C00); }\n    static constexpr bfloat16 infinity() noexcept { return bfloat16::generate(0x7F80); }\n    static constexpr bfloat16 quiet_NaN() noexcept { return bfloat16::generate(0x7FC0); }\n    static constexpr bfloat16 signaling_NaN() noexcept { return bfloat16::generate(0x7FC0); }\n    static constexpr bfloat16 denorm_min() noexcept { return bfloat16::generate(0); }\n};\n} // namespace std\n#endif\n", "meta": {"hexsha": "a9679f0a666c22d375281bce954bdf6e5ecb5df2", "size": 6957, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/include/miopen/bfloat16.hpp", "max_stars_repo_name": "GENGNUAA/MIOpen", "max_stars_repo_head_hexsha": "a5796851e54df4eb1617e309be57e1e878a1d4f6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 745.0, "max_stars_repo_stars_event_min_datetime": "2017-07-01T22:03:25.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T23:46:27.000Z", "max_issues_repo_path": "src/include/miopen/bfloat16.hpp", "max_issues_repo_name": "GENGNUAA/MIOpen", "max_issues_repo_head_hexsha": "a5796851e54df4eb1617e309be57e1e878a1d4f6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1348.0, "max_issues_repo_issues_event_min_datetime": "2017-07-02T12:37:48.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T23:45:51.000Z", "max_forks_repo_path": "src/include/miopen/bfloat16.hpp", "max_forks_repo_name": "GENGNUAA/MIOpen", "max_forks_repo_head_hexsha": "a5796851e54df4eb1617e309be57e1e878a1d4f6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 158.0, "max_forks_repo_forks_event_min_datetime": "2017-07-01T19:37:04.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-30T11:57:04.000Z", "avg_line_length": 40.4476744186, "max_line_length": 106, "alphanum_fraction": 0.6272818744, "num_tokens": 1744, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6076631698328916, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.3439486172814331}}
{"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 HASHCLASH_BOOLEANFUNCTION_HPP\n#define HASHCLASH_BOOLEANFUNCTION_HPP\n\n#include <vector>\n#include <string>\n#include <set>\n#include <map>\n\n#include <boost/function.hpp>\n\n#include \"types.hpp\"\n#include \"sdr.hpp\"\n#include \"md5detail.hpp\"\n#include \"conditions.hpp\"\n\nnamespace hashclash {\n\n\ttypedef triple<bitcondition, bitcondition, bitcondition> bf_conditions;\n\n\tstruct bf_outcome {\n\t\tunsigned char c;\n\n\t\tstatic const unsigned char fconstant = 1;\n\t\tstatic const unsigned char fplus = 2;\n\t\tstatic const unsigned char fminus = 4;\n\t\tbf_outcome(): c(0) {}\n\t\tbf_outcome(unsigned char k): c(k) {}\n\t\tbf_outcome& operator=(const bf_outcome& r)\n\t\t{ c = r.c; return *this; }\n\t\tbf_outcome& operator=(unsigned char k)\n\t\t{ c = k; return *this; }\n\n\t\tbool constant() const\n\t\t{ return (c&fconstant) != 0; }\n\t\tbool plus() const\n\t\t{ return (c&fplus) != 0; }\n\t\tbool minus() const\n\t\t{ return (c&fminus) != 0; }\n\t\tunsigned size() const\n\t\t{\n\t\t\tunsigned w = 0;\n\t\t\tif (constant()) ++w;\n\t\t\tif (plus()) ++w;\n\t\t\tif (minus()) ++w;\n\t\t\treturn w;\n\t\t}\n\t\tuint32 operator()(unsigned index, unsigned b) const\n\t\t{\n\t\t\tif (index == 0) {\n\t\t\t\tif (constant()) return 0;\n\t\t\t\tif (plus()) return 0+(1<<b);\n\t\t\t\treturn 0-(1<<b);\n\t\t\t} else if (index == 1) {\n\t\t\t\tif (constant())\t{\n\t\t\t\t\tif (plus()) return 0+(1<<b);\n\t\t\t\t\treturn 0-(1<<b);\n\t\t\t\t} else \n\t\t\t\t\treturn 0-(1<<b);\n\t\t\t} else\n\t\t\t\treturn 0-(1<<b);\n\t\t}\n\t\tbitcondition operator[](unsigned index) const\n\t\t{\n\t\t\tif (index == 0) {\n\t\t\t\tif (constant()) return bc_constant;\n\t\t\t\tif (plus()) return bc_plus;\n\t\t\t\treturn bc_minus;\n\t\t\t} else if (index == 1) {\n\t\t\t\tif (constant())\t{\n\t\t\t\t\tif (plus()) return bc_plus;\n\t\t\t\t\treturn bc_minus;\n\t\t\t\t} else \n\t\t\t\t\treturn bc_minus;\n\t\t\t} else \n\t\t\t\treturn bc_minus;\n\t\t}\n\t};\n\t\n\tclass booleanfunction {\n\tpublic:\n\t\tbooleanfunction(const boost::function<uint32(uint32,uint32,uint32)>& F, const std::string& description = \"\");\n\t\t\n\t\tconst bf_outcome& outcome(bitcondition input1, bitcondition input2, bitcondition input3)\n\t\t{ return outcome_table[(input1<<8) + (input2<<4) + input3]; }\n\t\tconst bf_outcome& outcome(const bf_conditions& c)\n\t\t{ return outcome(c.first, c.second, c.third); }\n\n\t\tconst bf_conditions& forwardconditions(bitcondition input1, bitcondition input2, bitcondition input3, bitcondition outcome)\n\t\t{ return forward_table[(outcome<<12)+(input1<<8)+(input2<<4)+input3]; }\n\t\tconst bf_conditions& forwardconditions(const bf_conditions& c, bitcondition outcome)\n\t\t{ return forwardconditions(c.first, c.second, c.third, outcome); }\n\n\t\tconst bf_conditions& backwardconditions(bitcondition input1, bitcondition input2, bitcondition input3, bitcondition outcome)\n\t\t{ return backward_table[(outcome<<12)+(input1<<8)+(input2<<4)+input3]; }\n\t\tconst bf_conditions& backwardconditions(const bf_conditions& c, bitcondition outcome)\n\t\t{ return backwardconditions(c.first, c.second, c.third, outcome); }\n\n\t\tuint32 F(uint32 input1, uint32 input2, uint32 input3) const\n\t\t{ return f(input1, input2, input3); }\n\n\t\tconst std::string& description() const\n\t\t{ return f_description; }\n\t\t\n\tprivate:\n\t\tboost::function<uint32(uint32,uint32,uint32)> f;\n\t\tstd::string f_description;\n\n\t\tstd::vector<bf_outcome> outcome_table;\n\t\tstd::vector<bf_conditions> forward_table;\n\t\tstd::vector<bf_conditions> backward_table;\n\n\t\tstd::map<bf_conditions, std::set<uint32> > conds_to_values;\n\n\t\tvoid find_booleanfunction_outcomes(const bf_conditions& cond, bf_outcome& outcomes, std::set<uint32>& values);\n\t\tbf_conditions preferred_conditions(const bf_conditions& cond, std::vector<bf_conditions>& vec_conds);\n\t};\n\n\textern booleanfunction MD5_F_data, MD5_G_data, MD5_H_data, MD5_I_data;\n\n} // namespace hashclash\n\n#endif //HASHCLASH_BOOLEANFUNCTION_HPP\n", "meta": {"hexsha": "086d1a7e7a296e031c51fcafcb10a39ca976e6ce", "size": 4514, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "lib/hashclash/booleanfunction.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": "lib/hashclash/booleanfunction.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": "lib/hashclash/booleanfunction.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": 31.7887323944, "max_line_length": 126, "alphanum_fraction": 0.6727957466, "num_tokens": 1220, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6076631698328916, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.3439486172814331}}
{"text": "#pragma once\n\n#include \"quadrature_base.hpp\"\n\n#include <boost/multi_array.hpp>\n#include <vector>\n\n\nnamespace boltzmann {\n\ntemplate <typename Q1, typename Q2>\nclass TensorProductQuadrature : public Quadrature<2>\n{\n public:\n  typedef Quadrature<2> base_type;\n  using base_type::dim;\n  using base_type::coord_type;\n\n public:\n  TensorProductQuadrature(const Q1& q1, const Q2& q2);\n\n private:\n  using base_type::pts_;\n  using base_type::wts_;\n};\n\n// ---------------------------------------------------------------------------\ntemplate <typename Q1, typename Q2>\nTensorProductQuadrature<Q1, Q2>::TensorProductQuadrature(const Q1& q1, const Q2& q2)\n    : base_type(q1.size() * q2.size())\n{\n  typedef boost::multi_array_ref<double, 2> wts_ref_t;\n  typedef boost::multi_array_ref<coord_type, 2> pts_ref_t;\n\n  wts_ref_t wts_ref(this->wts_.data(), boost::extents[q1.size()][q2.size()]);\n  pts_ref_t pts_ref(this->pts_.data(), boost::extents[q1.size()][q2.size()]);\n\n  for (unsigned int i = 0; i < q1.size(); ++i) {\n    for (unsigned int j = 0; j < q2.size(); ++j) {\n      wts_ref[i][j] = q1.wts(i) * q2.wts(j);\n      pts_ref[i][j][0] = q1.pts(i);\n      pts_ref[i][j][1] = q2.pts(j);\n    }\n  }\n}\n\n// ----------------------------------------------------------------------------\n/**\n * @brief Build tensor product quadrature for R^2, from\n *        quad. rules in polar coordinates.\n *        Stores quadrature points as complex number\n *\n * @tparam Q1 Quad. rule in angular direction\n * @tparam Q2 Quad. rule in radial direction\n *\n */\ntemplate <typename Q1, typename Q2>\nclass TensorProductQuadratureC : public Quadrature<2>\n{\n public:\n  typedef Quadrature<2> base_type;\n  using base_type::dim;\n  using base_type::coord_type;\n\n public:\n  TensorProductQuadratureC(const Q1& q1, const Q2& q2);\n\n  /**\n   * @brief returns quad. points as std::complex<double>\n   *\n   * @param i index\n   */\n  const std::complex<double>& ptsC(unsigned int i) const { return ptsC_[i]; }\n\n  const std::vector<std::complex<double> >& ptsC() const { return ptsC_; }\n  const std::array<unsigned int, 2>& dims() const { return dims_; }\n\n private:\n  using base_type::pts_;\n  using base_type::wts_;\n  std::vector<std::complex<double> > ptsC_;\n  std::array<unsigned int, 2> dims_;\n};\n\n// ---------------------------------------------------------------------------\ntemplate <typename Q1, typename Q2>\nTensorProductQuadratureC<Q1, Q2>::TensorProductQuadratureC(const Q1& q1, const Q2& q2)\n    : base_type(q1.size() * q2.size())\n    , dims_({q1.size(), q2.size()})\n{\n  typedef boost::multi_array_ref<double, 2> wts_ref_t;\n  typedef boost::multi_array_ref<coord_type, 2> pts_ref_t;\n\n  wts_ref_t wts_ref(this->wts_.data(), boost::extents[q1.size()][q2.size()]);\n  pts_ref_t pts_ref(this->pts_.data(), boost::extents[q1.size()][q2.size()]);\n\n  for (unsigned int i = 0; i < q1.size(); ++i) {\n    for (unsigned int j = 0; j < q2.size(); ++j) {\n      wts_ref[i][j] = q1.wts(i) * q2.wts(j);\n      pts_ref[i][j][0] = q1.pts(i);\n      pts_ref[i][j][1] = q2.pts(j);\n    }\n  }\n\n  std::complex<double> ii(0, 1);\n  ptsC_.resize(pts_.size());\n  for (unsigned int i = 0; i < pts_.size(); ++i) {\n    ptsC_[i] = pts_[i][1] * std::exp(ii * pts_[i][0]);\n  }\n}\n\n}  // end namespace boltzmann\n", "meta": {"hexsha": "d6db37ae17a6c1e9dcf9d5b73325d9ee3b901be6", "size": 3227, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "spectral/quadrature/tensor_product_quadrature.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": "spectral/quadrature/tensor_product_quadrature.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": "spectral/quadrature/tensor_product_quadrature.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": 28.5575221239, "max_line_length": 86, "alphanum_fraction": 0.6045863031, "num_tokens": 967, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6076631556226291, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.3439486092381612}}
{"text": "/**\n * @file\n * @brief Implementation of charge propagation module with transient behavior simulation\n * @copyright Copyright (c) 2019-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 \"TransientPropagationModule.hpp\"\n\n#include <map>\n#include <memory>\n#include <string>\n#include <utility>\n\n#include <Eigen/Core>\n\n#include \"core/utils/distributions.h\"\n#include \"core/utils/log.h\"\n#include \"objects/PixelCharge.hpp\"\n#include \"objects/PropagatedCharge.hpp\"\n#include \"tools/runge_kutta.h\"\n\nusing namespace allpix;\nusing namespace ROOT::Math;\n\nTransientPropagationModule::TransientPropagationModule(Configuration& config,\n                                                       Messenger* messenger,\n                                                       std::shared_ptr<Detector> detector)\n    : Module(config, detector), messenger_(messenger), detector_(std::move(detector)) {\n    // Enable multithreading of this module if multithreading is enabled\n    allow_multithreading();\n\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>(\"timestep\", Units::get(0.01, \"ns\"));\n    config_.setDefault<double>(\"integration_time\", Units::get(25, \"ns\"));\n    config_.setDefault<unsigned int>(\"charge_per_step\", 10);\n\n    // Models:\n    config_.setDefault<std::string>(\"mobility_model\", \"jacoboni\");\n    config_.setDefault<std::string>(\"recombination_model\", \"none\");\n\n    config_.setDefault<double>(\"temperature\", 293.15);\n    config_.setDefault<bool>(\"output_plots\", false);\n    config_.setDefault<unsigned int>(\"distance\", 1);\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_ = config_.get<double>(\"timestep\");\n    integration_time_ = config_.get<double>(\"integration_time\");\n    distance_ = config_.get<unsigned int>(\"distance\");\n    charge_per_step_ = config_.get<unsigned int>(\"charge_per_step\");\n\n    output_plots_ = config_.get<bool>(\"output_plots\");\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 TransientPropagationModule::initialize() {\n\n    auto detector = getDetector();\n\n    // Check for electric field\n    if(!detector->hasElectricField()) {\n        LOG(WARNING) << \"This detector does not have an electric field.\";\n    }\n\n    if(!detector_->hasWeightingPotential()) {\n        throw ModuleError(\"This module requires a weighting potential.\");\n    }\n\n    if(detector_->getElectricFieldType() == FieldType::LINEAR) {\n        throw ModuleError(\"This module cannot be used with linear electric fields.\");\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    // 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        potential_difference_ = CreateHistogram<TH1D>(\n            \"potential_difference\",\n            \"Weighting potential difference between two steps;#left|#Delta#phi_{w}#right| [a.u.];events\",\n            500,\n            0,\n            1);\n        induced_charge_histo_ = CreateHistogram<TH1D>(\"induced_charge_histo\",\n                                                      \"Induced charge per time, all pixels;Drift time [ns];charge [e]\",\n                                                      static_cast<int>(integration_time_ / timestep_),\n                                                      0,\n                                                      static_cast<double>(Units::convert(integration_time_, \"ns\")));\n        induced_charge_e_histo_ =\n            CreateHistogram<TH1D>(\"induced_charge_e_histo\",\n                                  \"Induced charge per time, electrons only, all pixels;Drift time [ns];charge [e]\",\n                                  static_cast<int>(integration_time_ / timestep_),\n                                  0,\n                                  static_cast<double>(Units::convert(integration_time_, \"ns\")));\n        induced_charge_h_histo_ =\n            CreateHistogram<TH1D>(\"induced_charge_h_histo\",\n                                  \"Induced charge per time, holes only, all pixels;Drift time [ns];charge [e]\",\n                                  static_cast<int>(integration_time_ / timestep_),\n                                  0,\n                                  static_cast<double>(Units::convert(integration_time_, \"ns\")));\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        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\nvoid TransientPropagationModule::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    unsigned int propagated_charges_count = 0;\n    unsigned int recombined_charges_count = 0;\n\n    // Loop over all deposits for propagation\n    LOG(TRACE) << \"Propagating charges in sensor\";\n    for(const auto& deposit : deposits_message->getData()) {\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            std::map<Pixel::Index, Pulse> px_map;\n\n            // Get position and propagate through sensor\n            auto [local_position, time, alive] = propagate(\n                event, deposit.getLocalPosition(), deposit.getType(), charge_per_step, deposit.getLocalTime(), px_map);\n\n            // Create a new propagated charge and add it to the list\n            auto global_position = detector_->getGlobalPosition(local_position);\n            PropagatedCharge propagated_charge(local_position,\n                                               global_position,\n                                               deposit.getType(),\n                                               std::move(px_map),\n                                               deposit.getLocalTime() + time,\n                                               deposit.getGlobalTime() + time,\n                                               &deposit);\n\n            LOG(DEBUG) << \" Propagated \" << charge_per_step << \" to \" << Units::display(local_position, {\"mm\", \"um\"})\n                       << \" in \" << Units::display(time, \"ns\") << \" time, induced \"\n                       << Units::display(propagated_charge.getCharge(), {\"e\"});\n\n            propagated_charges.push_back(std::move(propagated_charge));\n\n            if(alive) {\n                propagated_charges_count += charge_per_step;\n            } else {\n                recombined_charges_count += charge_per_step;\n            }\n\n            if(output_plots_) {\n                drift_time_histo_->Fill(static_cast<double>(Units::convert(time, \"ns\")), charge_per_step);\n            }\n        }\n    }\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. A 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>\nTransientPropagationModule::propagate(Event* event,\n                                      const ROOT::Math::XYZPoint& pos,\n                                      const CarrierType& type,\n                                      const unsigned int charge,\n                                      const double initial_time,\n                                      std::map<Pixel::Index, Pulse>& pixel_map) {\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, double timestep) -> Eigen::Vector3d {\n        double diffusion_constant = boltzmann_kT_ * mobility_(type, efield_mag, doping);\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(event->getRandomEngine());\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\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\n    auto runge_kutta = make_runge_kutta(\n        tableau::RK5, (has_magnetic_field_ ? carrier_velocity_withB : carrier_velocity_noB), timestep_, position);\n\n    // Continue propagation until the deposit is outside the sensor\n    Eigen::Vector3d last_position = position;\n    bool within_sensor = true;\n    bool is_alive = true;\n    while(within_sensor && (initial_time + runge_kutta.getTime()) < integration_time_ && is_alive) {\n        // Save previous position and time\n        last_position = position;\n\n        // Execute a Runge Kutta step\n        auto step = runge_kutta.step();\n\n        // Get the current result\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(event->getRandomEngine()),\n                                   timestep_);\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        }\n\n        // Check for overshooting outside the sensor and correct for it:\n        if(!detector_->getModel()->isWithinSensor(static_cast<ROOT::Math::XYZPoint>(position))) {\n            LOG(TRACE) << \"Carrier outside sensor: \" << Units::display(static_cast<ROOT::Math::XYZPoint>(position), {\"nm\"});\n            // within_sensor = false;\n\n            auto check_position = position;\n            check_position.z() = last_position.z();\n            // Correct for position in z by interpolation to increase precision:\n            if(detector_->getModel()->isWithinSensor(static_cast<ROOT::Math::XYZPoint>(check_position))) {\n                // FIXME this currently depends in the direction of the drift\n                if(position.z() > 0 && type == CarrierType::HOLE) {\n                    LOG(DEBUG) << \"Not stopping carrier \" << type << \" at \"\n                               << Units::display(static_cast<ROOT::Math::XYZPoint>(position), {\"um\"});\n                } else if(position.z() < 0 && type == CarrierType::ELECTRON) {\n                    LOG(DEBUG) << \"Not stopping carrier \" << type << \" at \"\n                               << Units::display(static_cast<ROOT::Math::XYZPoint>(position), {\"um\"});\n                } else {\n                    within_sensor = false;\n                }\n\n                // Carrier left sensor on top or bottom surface, interpolate\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                LOG(TRACE) << \"Moved carrier to: \" << Units::display(static_cast<ROOT::Math::XYZPoint>(position), {\"nm\"});\n            } else {\n                within_sensor = false;\n            }\n        }\n\n        // Find the nearest pixel - before and after the step\n        auto [xpixel, ypixel] = model_->getPixelIndex(static_cast<ROOT::Math::XYZPoint>(position));\n        auto [last_xpixel, last_ypixel] = model_->getPixelIndex(static_cast<ROOT::Math::XYZPoint>(last_position));\n        auto idx = Pixel::Index(static_cast<unsigned int>(xpixel), static_cast<unsigned int>(ypixel));\n        auto neighbors = model_->getNeighbors(idx, distance_);\n\n        // If the charge carrier crossed pixel boundaries, ensure that we always calculate the induced current for both of\n        // them by extending the induction matrix temporarily. Otherwise we end up doing \"double-counting\" because we would\n        // only jump \"into\" a pixel but never \"out\". At the border of the induction matrix, this would create an imbalance.\n        if(last_xpixel != xpixel || last_ypixel != ypixel) {\n            auto last_idx = Pixel::Index(static_cast<unsigned int>(last_xpixel), static_cast<unsigned int>(last_ypixel));\n            neighbors.merge(model_->getNeighbors(last_idx, distance_));\n            LOG(TRACE) << \"Carrier crossed boundary from pixel \"\n                       << Pixel::Index(static_cast<unsigned int>(last_xpixel), static_cast<unsigned int>(last_ypixel))\n                       << \" to pixel \" << Pixel::Index(static_cast<unsigned int>(xpixel), static_cast<unsigned int>(ypixel));\n        }\n        LOG(TRACE) << \"Moving carriers below pixel \"\n                   << Pixel::Index(static_cast<unsigned int>(xpixel), static_cast<unsigned int>(ypixel)) << \" from \"\n                   << Units::display(static_cast<ROOT::Math::XYZPoint>(last_position), {\"um\", \"mm\"}) << \" to \"\n                   << Units::display(static_cast<ROOT::Math::XYZPoint>(position), {\"um\", \"mm\"}) << \", \"\n                   << Units::display(initial_time + runge_kutta.getTime(), \"ns\");\n\n        for(const auto& pixel_index : neighbors) {\n            auto ramo = detector_->getWeightingPotential(static_cast<ROOT::Math::XYZPoint>(position), pixel_index);\n            auto last_ramo = detector_->getWeightingPotential(static_cast<ROOT::Math::XYZPoint>(last_position), pixel_index);\n\n            // Induced charge on electrode is q_int = q * (phi(x1) - phi(x0))\n            auto induced = charge * (ramo - last_ramo) * static_cast<std::underlying_type<CarrierType>::type>(type);\n            LOG(TRACE) << \"Pixel \" << pixel_index << \" dPhi = \" << (ramo - last_ramo) << \", induced \" << type\n                       << \" q = \" << Units::display(induced, \"e\");\n\n            // Create pulse if it doesn't exist. Store induced charge in the returned pulse iterator\n            auto pixel_map_iterator = pixel_map.emplace(pixel_index, Pulse(timestep_));\n            pixel_map_iterator.first->second.addCharge(induced, initial_time + runge_kutta.getTime());\n\n            if(output_plots_) {\n                potential_difference_->Fill(std::fabs(ramo - last_ramo));\n                induced_charge_histo_->Fill(initial_time + runge_kutta.getTime(), induced);\n                if(type == CarrierType::ELECTRON) {\n                    induced_charge_e_histo_->Fill(initial_time + runge_kutta.getTime(), induced);\n                } else {\n                    induced_charge_h_histo_->Fill(initial_time + runge_kutta.getTime(), induced);\n                }\n            }\n        }\n    }\n\n    // Return the final position of the propagated charge\n    return std::make_tuple(static_cast<ROOT::Math::XYZPoint>(position), initial_time + runge_kutta.getTime(), is_alive);\n}\n\nvoid TransientPropagationModule::finalize() {\n    if(output_plots_) {\n        potential_difference_->Write();\n        step_length_histo_->Write();\n        drift_time_histo_->Write();\n        recombine_histo_->Write();\n        induced_charge_histo_->Write();\n        induced_charge_e_histo_->Write();\n        induced_charge_h_histo_->Write();\n    }\n}\n", "meta": {"hexsha": "f6a542fd1177c185e3e7f370e11abf5c866ca4c0", "size": 21684, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/modules/TransientPropagation/TransientPropagationModule.cpp", "max_stars_repo_name": "allpix-squared/allpix-squared", "max_stars_repo_head_hexsha": "15565f2b9c0447991c451bd9211a10a0c7eb958e", "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/TransientPropagation/TransientPropagationModule.cpp", "max_issues_repo_name": "allpix-squared/allpix-squared", "max_issues_repo_head_hexsha": "15565f2b9c0447991c451bd9211a10a0c7eb958e", "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/TransientPropagation/TransientPropagationModule.cpp", "max_forks_repo_name": "allpix-squared/allpix-squared", "max_forks_repo_head_hexsha": "15565f2b9c0447991c451bd9211a10a0c7eb958e", "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.8482758621, "max_line_length": 125, "alphanum_fraction": 0.607959786, "num_tokens": 4565, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.8289388083214155, "lm_q2_score": 0.4148988457967688, "lm_q1q2_score": 0.34392575480870424}}
{"text": "#include \"stiffness_checker/Stiffness.h\"\n#include \"stiffness_checker/Util.h\"\n#include \"stiffness_checker/SharedConst.h\"\n#include \"stiffness_checker/StiffnessSolver.h\"\n#include \"stiffness_checker/StiffnessIO.h\"\n\n#include <cstdlib>\n#include <cmath>\n#include <set>\n#include <algorithm>\n#include <numeric>\n#include <chrono>\n#include <ctime>\n\n#include <Eigen/Dense>\n#include <Eigen/Sparse>\n\nnamespace{\nconst std::string PathSeparator =\n#ifdef _WIN32\n\"\\\\\";\n#else\n\"/\";\n#endif\n}\n\nnamespace conmech\n{\nnamespace stiffness_checker\n{\n\nStiffness Stiffness::create(const Eigen::MatrixXd& V, const Eigen::MatrixXi& E, const Eigen::MatrixXi& Fixities,\n                            const std::vector<conmech::material::Material>& materials,\n                            const bool& verbose, const std::string& model_type, const bool& output_json) \n{ \n  return Stiffness(V, E, Fixities, materials, verbose, model_type, output_json); \n}\n\nStiffness::Stiffness(const std::string& file_path,\n                     const bool& verbose, const std::string& model_type, const bool& output_json)\n{\n  Eigen::MatrixXd V;\n  Eigen::MatrixXi E;\n  Eigen::MatrixXi Fixities;\n  std::vector<conmech::material::Material> mats;\n  parseFrameJson(file_path, V, E, Fixities, mats);\n\n  init(V, E, Fixities, mats, verbose, model_type, output_json);\n}\n\nStiffness::Stiffness(const Eigen::MatrixXd& V, const Eigen::MatrixXi& E, const Eigen::MatrixXi& Fixities, \n                     const std::vector<conmech::material::Material>& materials,\n                     const bool& verbose, const std::string& model_type, const bool& output_json)\n{\n  init(V, E, Fixities, materials, verbose, model_type, output_json);\n}\n\nStiffness::Stiffness(const Eigen::MatrixXd& V, const Eigen::MatrixXi& E, const Eigen::MatrixXi& Fixities,\n                     const std::vector<nlohmann::json>& material_jsons,\n                     const bool& verbose, const std::string& model_type, const bool& output_json)\n{\n  using namespace conmech::material;\n  std::vector<Material> materials;\n  for (const auto& m_json : material_jsons)\n  {\n    Material m(m_json);\n    materials.push_back(m);\n  }\n  init(V, E, Fixities, materials, verbose, model_type, output_json);\n}\n\nStiffness::~Stiffness()\n{\n}\n\nbool Stiffness::init(const Eigen::MatrixXd& V, const Eigen::MatrixXi& E, const Eigen::MatrixXi& Fixities, \n                     const std::vector<conmech::material::Material>& materials,\n                     const bool& verbose, const std::string& model_type, const bool& output_json)\n{\n  Vertices_ = V; \n  Elements_ = E; \n  Fixities_ = Fixities; \n  materials_ = materials;\n  verbose_ = verbose; \n  model_type_ = model_type;\n  write_result_ = output_json,\n  stiff_solver_.timing_ = verbose;\n\n  // default settings\n  is_init_ = false; \n  include_self_weight_load_ = false;\n  has_stored_deformation_ = false; \n  stored_compliance_ = -1.0;\n  transl_tol_ = 1e-3; \n  rot_tol_ = 3 * (3.14 / 180);\n  output_json_file_name_ = \"\";\n  output_json_file_path_ = \"\";\n\n  // init starts\n  dim_ = int(this->Vertices_.cols());\n\n  // TODO: generalize to 2D\n  ASSERT(3 == dim_, \"only support 3D structure now!\");\n\n  if (3 == dim_) {\n    gravity_direction_ = Eigen::VectorXd(3);\n    gravity_direction_ << 0, 0, -1;\n  } else {\n    gravity_direction_ = Eigen::VectorXd(2);\n    gravity_direction_ << 0, -1;\n  }\n\n  // set up dimension, node_dof\n  if (3 == dim_)\n  {\n    // 3D case, x, y, z, xx, yy, zz\n    full_node_dof_ = 6;\n    if (model_type_ == \"frame\")\n    {\n      node_dof_ = 6;\n      xyz_dof_id_ = Eigen::VectorXi::LinSpaced(node_dof_ * 2, 0, node_dof_ * 2 - 1);\n      e_react_dof_id_ = Eigen::VectorXi::LinSpaced(node_dof_ * 2, 0, node_dof_ * 2 - 1);\n    }\n    if (model_type_ == \"truss\")\n    {\n      node_dof_ = 3;\n      xyz_dof_id_ = Eigen::VectorXi(6);\n      xyz_dof_id_ << 0, 1, 2, 6, 7, 8;\n\n      e_react_dof_id_ = Eigen::VectorXi(2);\n      e_react_dof_id_ << 0, 6;\n    }\n  }\n  else\n  {\n    // 2D case, x, y, theta\n    full_node_dof_ = 3;\n    if (model_type_ == \"frame\")\n    {\n      node_dof_ = 3;\n      xyz_dof_id_ = Eigen::VectorXi::LinSpaced(node_dof_ * 2, 0, node_dof_ * 2 - 1);\n      e_react_dof_id_ = Eigen::VectorXi::LinSpaced(node_dof_ * 2, 0, node_dof_ * 2 - 1);\n    }\n    if (model_type_ == \"truss\")\n    {\n      node_dof_ = 2;\n      xyz_dof_id_ = Eigen::VectorXi(4);\n      xyz_dof_id_ << 0, 1, 3, 4;\n\n      e_react_dof_id_ = Eigen::VectorXi(2);\n      e_react_dof_id_ << 0, 3;\n    }\n  }\n  ASSERT(xyz_dof_id_.size() == node_dof_ * 2, \"\");\n\n  // init per-element material properties\n  precomputeElementStiffnessMatrixList();\n  precomputeElementSelfWeightLumpedLoad();\n\n  // create id_map_\n  int dof = nV() * node_dof_;\n  int N_element = nE();\n  int N_node = nV();\n\n  id_map_.resize(N_element, node_dof_ * 2);\n  v_id_map_.resize(N_node, node_dof_);\n  auto lin_sp_id = Eigen::VectorXi::LinSpaced(node_dof_, 0, node_dof_ - 1); // 0,1,..,5\n\n  for (int i = 0; i < N_node; i++)\n  {\n    v_id_map_.block(i, 0, 1, node_dof_) =\n      (Eigen::VectorXi::Constant(node_dof_, node_dof_ * i) + lin_sp_id).transpose();\n  }\n\n  for (int i = 0; i < N_element; i++)\n  {\n    const auto end_u_id = Elements_(i, 0);\n    const auto end_v_id = Elements_(i, 1);\n\n    id_map_.block(i, 0, 1, node_dof_) =\n      (Eigen::VectorXi::Constant(node_dof_, node_dof_ * end_u_id) + lin_sp_id).transpose();\n    id_map_.block(i, node_dof_, 1, node_dof_) =\n      (Eigen::VectorXi::Constant(node_dof_, node_dof_ * end_v_id) + lin_sp_id).transpose();\n  }\n\n  // create zero load\n  nodal_load_P_ = Eigen::VectorXd::Zero(dof);\n\n  if (verbose_)\n  {\n    std::cout << \"Initialization done\" << std::endl;\n  }\n  is_init_ = true;\n  return true;\n}\n\nvoid Stiffness::setNodalDisplacementTolerance(double transl_tol, double rot_tol)\n{\n  if(transl_tol <= 0 || rot_tol <= 0) {\n    throw std::runtime_error(\"invalid tolerance: tolerance must be bigger than 0!\");\n  }\n  transl_tol_ = transl_tol;\n  rot_tol_ = rot_tol;\n}\n\nvoid Stiffness::precomputeElementStiffnessMatrixList()\n{\n  // complete element stiffness matrix\n  // in local frame: [MSA McGuire et al.] P73\n\n  // for all cross section's geometrical properties\n  // cross section: m^2\n  // Iz, Iy: m^4\n  // J: m^4\n  // element length L: m\n  // E, G: kN/m^2\n  // Force: kN\n  // Moment: kN-m\n\n  int N_element = nE();\n\n  element_K_list_.clear();\n  rot_m_list_.clear();\n  element_K_list_.reserve(N_element);\n  rot_m_list_.reserve(N_element);\n\n  for (int i = 0; i < N_element; i++)\n  {\n    int end_u_id = Elements_(i, 0);\n    int end_v_id = Elements_(i, 1);\n    Eigen::VectorXd end_u, end_v;\n    getNodePoints(Vertices_, end_u_id, end_v_id, end_u, end_v);\n\n    // element length, unit: m\n    double L = (end_u - end_v).norm();\n\n    // material properties\n    double A = materials_[i].cross_sec_area_;\n    double Jx = materials_[i].Jx_;\n    double Iy = materials_[i].Iy_;\n    double Iz = materials_[i].Iz_;\n\n    // E,G: MPa; mu (poisson ratio): unitless\n    double E = materials_[i].youngs_modulus_;\n    double mu = materials_[i].poisson_ratio_;\n    double G = materials_[i].shear_modulus_;\n\n    Eigen::Matrix3d R_LG;\n    getGlobal2LocalRotationMatrix(end_u, end_v, R_LG);\n\n    // element stiffness matrix in local frame\n    Eigen::MatrixXd K_loc;\n    createLocalStiffnessMatrix(L, A, dim_, Jx, Iy, Iz, E, G, mu, K_loc);\n\n    // transform to global frame\n    Eigen::MatrixXd R_LG_diag = Eigen::MatrixXd::Zero(full_node_dof_ * 2, full_node_dof_ * 2);\n\n    // 4 block or 2 block\n    for (int j = 0; j < (full_node_dof_ / 3) * 2; j++)\n    {\n      R_LG_diag.block<3, 3>(j * 3, j * 3) = R_LG;\n    }\n\n    Eigen::MatrixXd R_temp = Eigen::MatrixXd::Zero(e_react_dof_id_.size(), xyz_dof_id_.size());\n    Eigen::MatrixXd K_loc_temp = Eigen::MatrixXd::Zero(e_react_dof_id_.size(), e_react_dof_id_.size());\n\n    for (int k = 0; k < e_react_dof_id_.size(); k++)\n    {\n      for (int kk = 0; kk < xyz_dof_id_.size(); kk++)\n      {\n        // assert(e_react_dof_id_(k) < R_LG_diag.rows() && xyz_dof_id_(kk) < R_LG_diag.cols());\n        R_temp(k, kk) = R_LG_diag(e_react_dof_id_(k), xyz_dof_id_(kk));\n      }\n    }\n    R_LG_diag = R_temp;\n\n    for (int k = 0; k < e_react_dof_id_.size(); k++)\n    {\n      for (int kk = 0; kk < e_react_dof_id_.size(); kk++)\n      {\n        // assert(e_react_dof_id_(k) < K_loc.rows() && e_react_dof_id_(kk) < K_loc.cols());\n        K_loc_temp(k, kk) = K_loc(e_react_dof_id_(k), e_react_dof_id_(kk));\n      }\n    }\n    K_loc = K_loc_temp;\n\n    auto R_LG_diagT = R_LG_diag.transpose();\n    K_loc = R_LG_diagT * K_loc * R_LG_diag;\n\n    element_K_list_.push_back(K_loc);\n    rot_m_list_.push_back(R_LG_diag);\n  }\n}\n\nvoid Stiffness::createCompleteGlobalStiffnessMatrix(const std::vector<int> &exist_e_ids)\n{\n  // std::clock_t c_start = std::clock();\n\n  assert(element_K_list_.size() > 0);\n  assert(exist_e_ids.size() > 0);\n  assert(id_map_.rows() >= int(exist_e_ids.size()));\n\n  int total_dof = nV() * node_dof_;\n  int N_element = nE();\n\n  K_assembled_full_.resize(total_dof, total_dof);\n  std::vector<Eigen::Triplet<double>> K_triplets;\n\n  for (const int& e_id : exist_e_ids)\n  {\n    assert(e_id >= 0 && e_id < nE());\n    const auto K_e = element_K_list_[e_id];\n    assert(K_e.rows() == 2 * node_dof_ && K_e.cols() == 2 * node_dof_);\n\n    for (int i = 0; i < 2 * node_dof_; i++)\n    {\n      int row_id = id_map_(e_id, i);\n\n      for (int j = 0; j < 2 * node_dof_; j++)\n      {\n        // TODO: threhold push_back by checking double_eps\n        int col_id = id_map_(e_id, j);\n        K_triplets.push_back(Eigen::Triplet<double>(row_id, col_id, K_e(i, j)));\n      }\n    }\n  } // end e_id\n  K_assembled_full_.setFromTriplets(K_triplets.begin(), K_triplets.end());\n\n  // std::clock_t c_end = std::clock();\n  // std::cout << \"create global stiffness matrix: \" << 1e3 * (c_end - c_start) / CLOCKS_PER_SEC << \" ms\" << std::endl;\n}\n\nvoid Stiffness::setLoad(const Eigen::MatrixXd &nodal_forces)\n{\n  // assert(is_init_);\n\n  int dof = node_dof_ * nV();\n  bool is_empty_ext = nodal_forces.isZero(0) || nodal_forces.rows() == 0;\n\n  if (!is_empty_ext)\n  {\n    createExternalNodalLoad(nodal_forces, nodal_load_P_);\n  } else {\n    throw std::runtime_error(\"No load is assigned.\");\n  }\n}\n\nvoid Stiffness::setUniformlyDistributedLoad(const Eigen::MatrixXd &element_load_density)\n{\n  // assert(is_init_);\n  bool is_empty_ext = element_load_density.isZero(0) || element_load_density.rows() == 0;\n  if (!is_empty_ext)\n  {\n    precomputeElementUniformlyDistributedLumpedLoad(element_load_density);\n  } else {\n    throw std::runtime_error(\"No load is assigned.\");\n  }\n}\n\nvoid Stiffness::setGravityDirection(const Eigen::VectorXd& gravity_direction) {\n    if (gravity_direction.size() == dim_) {\n      gravity_direction_ = gravity_direction;\n      precomputeElementSelfWeightLumpedLoad();\n    }\n  }\n\nvoid Stiffness::createExternalNodalLoad(\n  const Eigen::MatrixXd &nodal_forces, Eigen::VectorXd &ext_load)\n{\n  // assert(is_init_);\n  // assert(nodal_forces.cols() == node_dof_ + 1);\n\n  int full_dof = node_dof_ * nV();\n  ext_load.resize(full_dof);\n\n  for (int i = 0; i < nodal_forces.rows(); i++)\n  {\n    int v_id = int(nodal_forces(i, 0));\n\n    ext_load.segment(v_id * 6, 6) = nodal_forces.block<1, 6>(i, 1);\n  }\n}\n\nvoid Stiffness::computeLumpedUniformlyDistributedLoad(const Eigen::Vector3d &w_G, const Eigen::Matrix3d &R_LG, const double &Le, \n  Eigen::VectorXd &fixed_end_lumped_load)\n{\n  fixed_end_lumped_load = Eigen::VectorXd::Zero(2 * node_dof_);\n\n  // node 0,1 force\n  fixed_end_lumped_load.segment(0, 3) = - w_G * Le / 2.0;\n  fixed_end_lumped_load.segment(6, 3) = - w_G * Le / 2.0;\n\n  // transform global load density to local density\n  Eigen::Vector3d w_l = - R_LG * w_G;\n\n  // node 0, 1 local moment\n  Eigen::Vector3d M_0_l(3);\n  M_0_l << 0, - w_l(2)*std::pow(Le,2)/12.0, w_l(1)*std::pow(Le,2)/12.0;\n  Eigen::Vector3d M_1_l = - M_0_l;\n\n  // transform local moment back to global\n  fixed_end_lumped_load.segment(3, 3) = R_LG.transpose() * M_0_l;\n  fixed_end_lumped_load.segment(9, 3) = R_LG.transpose() * M_1_l;\n\n  // equivalent nodal load P_e = - P_fixed_end\n  fixed_end_lumped_load *= -1;\n}\n\nvoid Stiffness::precomputeElementUniformlyDistributedLumpedLoad(const Eigen::MatrixXd &element_load_density)\n{\n  // refer [MSA McGuire et al.] P111\n  // Loads between nodal points\n  int N_vert = nV();\n  int N_element = nE();\n\n  element_lumped_nload_list_.resize(N_element);\n  for (int i = 0; i < N_element; i++)\n  {\n    element_lumped_nload_list_[i] = Eigen::VectorXd::Zero(6);\n  }\n\n  for (int i = 0; i < element_load_density.rows(); i++)\n  {\n    int e_id = int(element_load_density(i, 0));\n    int end_u_id = Elements_(e_id, 0);\n    int end_v_id = Elements_(e_id, 1);\n    Eigen::VectorXd end_u, end_v;\n    getNodePoints(Vertices_, end_u_id, end_v_id, end_u, end_v);\n    double Le = (end_u - end_v).norm();\n\n    Eigen::Vector3d w_g = element_load_density.block<1, 3>(i, 1);\n    \n    Eigen::Matrix3d R_LG;\n    getGlobal2LocalRotationMatrix(end_u, end_v, R_LG);\n\n    Eigen::VectorXd fixed_end_lumped_load;\n    computeLumpedUniformlyDistributedLoad(w_g, R_LG, Le, fixed_end_lumped_load);\n\n    element_lumped_nload_list_[e_id] = fixed_end_lumped_load;\n  }\n}\n\nvoid Stiffness::createUniformlyDistributedLumpedLoad(const std::vector<int>& exist_e_ids, Eigen::VectorXd &ext_load)\n{\n  // solve-time calculation\n  int N_vert = nV();\n  ext_load = Eigen::VectorXd::Zero(N_vert * node_dof_);\n\n  if (element_lumped_nload_list_.size() != nE()) \n  {\n    return;\n  }\n\n  for (const int e_id : exist_e_ids) \n  {\n    // assert(0 <= e_id && e_id < element_lumped_nload_list_.size());\n    auto Qe = element_lumped_nload_list_[e_id];\n\n    for (int j = 0; j < id_map_.cols(); j++) \n    {\n      ext_load[id_map_(e_id, j)] += Qe[j];\n    }\n  }\n}\n\nvoid Stiffness::precomputeElementSelfWeightLumpedLoad()\n{\n  // TODO: reuse element uniformly distributed load?\n  // gravity - Precomputation\n  // refer [MSA McGuire et al.] P111\n  // Loads between nodal points\n  int N_vert = nV();\n  int N_element = nE();\n\n  element_gravity_nload_list_.clear();\n  element_gravity_nload_list_.resize(N_element);\n\n  for (int i = 0; i < N_element; i++)\n  {\n    int end_u_id = Elements_(i, 0);\n    int end_v_id = Elements_(i, 1);\n    Eigen::VectorXd end_u, end_v;\n    getNodePoints(Vertices_, end_u_id, end_v_id, end_u, end_v);\n    double Le = (end_u - end_v).norm();\n\n    // uniform force density along the element\n    // due to gravity\n    // density kN / m^3 * m^2\n    double q_sw = materials_[i].density_ * materials_[i].cross_sec_area_;\n\n    if (model_type_ == \"frame\")\n    {\n      if (3 == dim_)\n      {\n        // Eigen::Vector3d w_g(3);\n        // w_g << 0, 0, -q_sw;\n        Eigen::Vector3d w_g = gravity_direction_ * q_sw;\n        // std::cout << \"gravity force: \" << w_g.transpose() << std::endl;\n    \n        Eigen::Matrix3d R_LG;\n        getGlobal2LocalRotationMatrix(end_u, end_v, R_LG);\n\n        Eigen::VectorXd fixed_end_lumped_load;\n        computeLumpedUniformlyDistributedLoad(w_g, R_LG, Le, fixed_end_lumped_load);\n\n        element_gravity_nload_list_[i] = fixed_end_lumped_load;\n      }\n      else\n      {\n        // TODO\n        assert(false && \"2D frame gravity not implemented yet.\");\n      }\n    }\n    else\n    {\n      // TODO\n      assert(false && \"truss gravity not implemented yet.\");\n    }\n  }\n}\n\nvoid Stiffness::createSelfWeightLumpedLoad(const std::vector<int> &exist_e_ids, Eigen::VectorXd &self_weight_load_P)\n{\n  // solve-time calculation\n  // assert(is_init_);\n  // assert(id_map_.cols() == 2 * node_dof_);\n\n  int N_vert = nV();\n  self_weight_load_P = Eigen::VectorXd::Zero(N_vert * node_dof_);\n\n  for (const int e_id : exist_e_ids)\n  {\n    // assert(0 <= e_id && e_id < element_gravity_nload_list_.size());\n    auto Qe = element_gravity_nload_list_[e_id];\n    // assert(Qe.size() == id_map_.cols());\n\n    for (int j = 0; j < id_map_.cols(); j++)\n    {\n      self_weight_load_P[id_map_(e_id, j)] += Qe[j];\n    }\n  }\n}\n\nbool Stiffness::solve(\n  const std::vector<int> &exist_element_ids,\n  Eigen::MatrixXd &node_displ,\n  Eigen::MatrixXd &fixities_reaction,\n  Eigen::MatrixXd &element_reaction,\n  const bool &cond_num)\n{\n  using namespace std;\n\n  int n_Element = nE();\n  int n_Node = nV();\n\n  if (verbose_)\n  {\n    create_k_.Start();\n  }\n\n  // start with assuming all dof does not exist (-1)\n  int dof = node_dof_ * n_Node;\n  Eigen::VectorXi full_f = Eigen::VectorXi::Constant(dof, -1);\n\n  if(!(exist_element_ids.size() > 0 && int(exist_element_ids.size()) <= n_Element)) \n  {\n      throw std::invalid_argument(\"input existing ids not within range!\");\n  }\n\n  std::set<int> sub_nodes_set;\n  for (int e_id : exist_element_ids)\n  {\n    // assert(e_id >= 0 && e_id < nE());\n    int end_u_id = Elements_(e_id, 0);\n    int end_v_id = Elements_(e_id, 1);\n    sub_nodes_set.insert(end_u_id);\n    sub_nodes_set.insert(end_v_id);\n\n    // turn the existing node's dofs to free(0)\n    full_f.segment(node_dof_ * end_u_id, node_dof_) = Eigen::VectorXi::Constant(node_dof_, 0);\n    full_f.segment(node_dof_ * end_v_id, node_dof_) = Eigen::VectorXi::Constant(node_dof_, 0);\n  }\n\n  // Assemble the list of fixed DOFs fixedList, a matrix of size\n  // 1-by-(number of fixities)\n  int n_SubFixedNode = 0;\n  int n_Fixities = 0;\n  for (int i = 0; i < Fixities_.rows(); i++)\n  {\n    int v_id = Fixities_(i, 0);\n\n    if (sub_nodes_set.end() != sub_nodes_set.find(v_id))\n    {\n      full_f.segment(node_dof_ * v_id, node_dof_) = (Fixities_.block(i, 1, 1, node_dof_)).transpose();\n\n      n_Fixities += full_f.segment(node_dof_ * v_id, node_dof_).sum();\n      n_SubFixedNode++;\n    }\n  }\n\n  if (0 == n_Fixities)\n  {\n    if (verbose_){\n      std::cout << \"Not stable: At least one node needs to be fixed in the considered substructure!\" << std::endl;\n    }\n    return false;\n  }\n\n  // count supp_dof and res_dof to init K_slice\n  int n_Nexist = node_dof_ * (n_Node - int(sub_nodes_set.size()));\n  int n_Free = dof - n_Fixities - n_Nexist;\n\n  // generate permute id map\n  int free_tail = 0;\n  int fix_tail = n_Free;\n  int nexist_tail = n_Free + n_Fixities;\n  Eigen::VectorXi id_map_RO = Eigen::VectorXi::LinSpaced(dof, 0, dof - 1);\n  for (int i = 0; i < dof; i++)\n  {\n    if (0 == full_f[i])\n    {\n      id_map_RO[free_tail] = i;\n      free_tail++;\n    }\n    if (1 == full_f[i])\n    {\n      id_map_RO[fix_tail] = i;\n      fix_tail++;\n    }\n    if (-1 == full_f[i])\n    {\n      id_map_RO[nexist_tail] = i;\n      nexist_tail++;\n    }\n  }\n\n  // a row permuatation matrix (multiply left)\n  Eigen::SparseMatrix<double> Perm(dof, dof);\n  std::vector<Eigen::Triplet<double>> perm_triplets;\n  for (int i = 0; i < dof; i++)\n  {\n    perm_triplets.push_back(Eigen::Triplet<double>(i, id_map_RO[i], 1));\n  }\n  Perm.setFromTriplets(perm_triplets.begin(), perm_triplets.end());\n  // perm operator on the right (column) = inverse of perm operation on the left (row)\n  auto Perm_T = Perm.transpose();\n\n  // permute the full stiffness matrix & carve the needed portion out\n  createCompleteGlobalStiffnessMatrix(exist_element_ids);\n\n  auto K_perm = Perm * K_assembled_full_ * Perm_T;\n  auto K_mm = K_perm.block(0, 0, n_Free, n_Free);\n  auto K_fm = K_perm.block(n_Free, 0, n_Fixities, n_Free);\n\n  Eigen::VectorXd nodal_load_P_tmp = nodal_load_P_;\n\n  Eigen::VectorXd element_lumped_load;\n  createUniformlyDistributedLumpedLoad(exist_element_ids, element_lumped_load);\n  nodal_load_P_tmp += element_lumped_load;\n\n  if (include_self_weight_load_)\n  {\n    Eigen::VectorXd load_sw;\n    createSelfWeightLumpedLoad(exist_element_ids, load_sw);\n    nodal_load_P_tmp += load_sw;\n  }\n\n  Eigen::VectorXd Q_perm = Perm * nodal_load_P_tmp;\n  auto Q_m = Q_perm.segment(0, n_Free);\n  auto Q_f = Q_perm.segment(n_Free, n_Fixities);\n\n  if (verbose_)\n  {\n    create_k_.Stop();\n  }\n\n  Eigen::VectorXd U_m(n_Free);\n  // TODO: clamping by tolerance here?\n  if (nodal_load_P_tmp.isZero())\n  {\n    U_m.setZero();\n  }\n  else\n  {\n    // TODO: what's the best solve strategy?\n    // TODO: Conjugate gradient, precondition? https://www.cs.cmu.edu/~baraff/papers/sig98.pdf\n    if (!stiff_solver_.solveSparseSimplicialLDLT(K_mm, Q_m, U_m, verbose_))\n    {\n      if (verbose_)\n      {\n        std::cout << \"ERROR: Stiffness Solver fail! The sub-structure contains mechanism.\\n\" << std::endl;\n      }\n      return false;\n    }\n  }\n\n  stored_compliance_ = 0.5 * U_m.dot(Q_m);\n\n  // reaction force\n  Eigen::VectorXd R(dof);\n  R.setZero();\n\n  auto R_f = K_fm * U_m - Q_f;\n  R.segment(n_Free, n_Fixities) = R_f;\n  R = Perm_T * R.eval();\n\n  // displacement\n  Eigen::VectorXd U(dof);\n  U.setZero();\n  U.segment(0, n_Free) = U_m;\n  U = Perm_T * U.eval();\n\n  // start raw computattion results conversion\n  // element internal reaction\n  element_reaction = Eigen::MatrixXd::Zero(exist_element_ids.size(), 1 + e_react_dof_id_.size());\n  int cnt = 0;\n  for (const int e_id : exist_element_ids)\n  {\n    Eigen::VectorXd Ue(2 * node_dof_);\n    for (int k = 0; k < 2 * node_dof_; k++)\n    {\n      Ue[k] = U[id_map_(e_id, k)];\n    }\n\n    element_reaction(cnt, 0) = e_id;\n    element_reaction.block(cnt, 1, 1, e_react_dof_id_.size()) =\n      (rot_m_list_[e_id] * element_K_list_[e_id] * Ue).transpose();\n    cnt++;\n  }\n  stored_element_reaction_ = element_reaction;\n\n  // fixities reaction\n  fixities_reaction = Eigen::MatrixXd::Zero(n_SubFixedNode, 1 + node_dof_);\n  cnt = 0;\n  for (int i = 0; i < Fixities_.rows(); i++)\n  {\n    int fix_node_id = Fixities_(i, 0);\n    if (sub_nodes_set.end() != sub_nodes_set.find(fix_node_id))\n    {\n      fixities_reaction(cnt, 0) = fix_node_id;\n      fixities_reaction.block(cnt, 1, 1, node_dof_) = (R.segment(fix_node_id * node_dof_, node_dof_)).transpose();\n      cnt++;\n    }\n  }\n  stored_fixities_reaction_ = fixities_reaction;\n\n  // node displacement\n  node_displ = Eigen::MatrixXd::Zero(sub_nodes_set.size(), 1 + node_dof_);\n  cnt = 0;\n  for (auto it = sub_nodes_set.begin(); it != sub_nodes_set.end(); ++it)\n  {\n    int v_id = *it;\n    node_displ(cnt, 0) = v_id;\n    node_displ.block(cnt, 1, 1, node_dof_) = (U.segment(v_id * node_dof_, node_dof_)).transpose();\n    cnt++;\n  }\n  stored_nodal_deformation_ = node_displ;\n\n  if (verbose_)\n  {\n    printOutTimer();\n  }\n\n  if (write_result_)\n  {\n    write_output_json(Vertices_, Elements_, node_displ, fixities_reaction, element_reaction, \n      output_json_file_path_ + PathSeparator + output_json_file_name_);\n  }\n\n  has_stored_deformation_ = true;\n  stored_existing_ids_ = exist_element_ids;\n\n  // void *testWhetherMemoryLeakDetectionWorks = malloc(1);\n\n  // stiffness criteria check\n  return checkStiffnessCriteria(node_displ, fixities_reaction, element_reaction);\n} // end core solve function\n\n// overloaded solve\nbool Stiffness::solve(const std::vector<int> &exist_element_ids,\n                      const bool &cond_num)\n{\n  Eigen::MatrixXd U, R, F;\n  return solve(exist_element_ids, U, R, F, cond_num);\n}\n\n// overloaded solve\nbool Stiffness::solve(Eigen::MatrixXd& node_displ,\n                      Eigen::MatrixXd& fixities_reaction,\n                      Eigen::MatrixXd& element_reaction,\n                      const bool& cond_num)\n{\n  int nElement = nE();\n  std::vector<int> all_e_ids;\n  for (int i = 0; i < nElement; i++)\n  {\n    all_e_ids.push_back(i);\n  }\n  return solve(\n    all_e_ids, node_displ, fixities_reaction, element_reaction, cond_num);\n}\n\n// overloaded solve\nbool Stiffness::solve(const bool &cond_num)\n{\n  Eigen::MatrixXd U, R, F;\n  return solve(U, R, F, cond_num);\n}\n\nbool Stiffness::getElementStiffnessMatrices(std::vector<Eigen::MatrixXd> &element_stiffness_mats)\n{\n    if (!is_init_) \n    {\n      throw std::runtime_error(\"stiffness checker not inited yet.\\n\");\n    }\n    element_stiffness_mats = element_K_list_;\n    return true;\n}\n\nbool Stiffness::getElementLocal2GlobalRotationMatrices(std::vector<Eigen::MatrixXd> &e_L2G_rot_mats)\n{\n  if (!is_init_) \n  {\n    throw std::runtime_error(\"stiffness checker not inited yet.\\n\");\n  }\n  e_L2G_rot_mats = rot_m_list_;\n  return true;\n}\n\nbool Stiffness::getSelfWeightNodalLoad(const std::vector<int>& exist_e_ids, Eigen::VectorXd& self_weight_load)\n{\n  createSelfWeightLumpedLoad(exist_e_ids, self_weight_load);\n  return true;\n}\n\nbool Stiffness::getUniformlyDistributedLumpedLoad(const std::vector<int>& exist_e_ids, Eigen::VectorXd& lumped_load)\n{\n  createUniformlyDistributedLumpedLoad(exist_e_ids, lumped_load);\n  return true;\n}\n\nint Stiffness::nE() const  \n{\n  return int(this->Elements_.rows());\n}\n\nint Stiffness::nV() const\n{\n  return int(this->Vertices_.rows());\n}\n\nint Stiffness::nFixV() const\n{\n  return int(this->Fixities_.rows());\n}\n\nint Stiffness::dim() const\n{ \n  return this->dim_; \n}\n\nbool Stiffness::getSolvedResults(Eigen::MatrixXd &node_displ,\n                      Eigen::MatrixXd &fixities_reaction,\n                      Eigen::MatrixXd &element_reaction,\n                      bool &pass_criteria)\n{\n  if(!hasStoredResults()) {\n    throw std::runtime_error(\"no stored result found.\\n\");\n  }\n  node_displ = stored_nodal_deformation_;\n  fixities_reaction = stored_fixities_reaction_;\n  element_reaction = stored_element_reaction_;\n  pass_criteria = checkStiffnessCriteria(node_displ, fixities_reaction, element_reaction);\n  return true;\n}\n\nbool Stiffness::getSolvedCompliance(double &compliance)\n{\n  if (!hasStoredResults()) \n  {\n    throw std::runtime_error(\"no stored result found.\\n\");\n  }\n  compliance = stored_compliance_;\n  return true;\n}\n\nbool Stiffness::getMaxNodalDeformation(double &max_trans, double &max_rot,\n    int &max_trans_vid, int &max_rot_vid)\n{\n  if (!hasStoredResults()) \n  {\n    throw std::runtime_error(\"no stored result found.\\n\");\n  }\n  const int nNode = int(stored_nodal_deformation_.rows());\n  int mt_i, mr_i, mr_j;\n\n  Eigen::VectorXd trans_norm(nNode);\n  trans_norm.setZero();\n  for(int i = 0; i < nNode; i++)\n  {\n    for(int j = 1; j <= 3; j++)\n    {\n      trans_norm[i] += std::pow(stored_nodal_deformation_(i, j), 2);\n    }\n    trans_norm[i] = sqrt(trans_norm[i]);\n  }\n  max_trans = trans_norm.maxCoeff(&mt_i);\n  max_trans_vid = int(stored_nodal_deformation_(mt_i, 0));\n  // max_trans = stored_nodal_deformation_.block(0, 1, nNode, 3).cwiseAbs().maxCoeff(&mt_i, &mt_j);\n  // max_trans_vid = stored_nodal_deformation_(mt_i, 0);\n\n  max_rot = stored_nodal_deformation_.block(0, 4, nNode, 3).cwiseAbs().maxCoeff(&mr_i, &mr_j);\n  max_rot_vid = int(stored_nodal_deformation_(mr_j, 0));\n  return true;\n}\n\nbool Stiffness::checkStiffnessCriteria(const Eigen::MatrixXd &node_displ,\n                                       const Eigen::MatrixXd &fixities_reaction,\n                                       const Eigen::MatrixXd &element_reation)\n{\n  // stiffness check\n  // nodal displacement check\n  const int nNode = int(node_displ.rows());\n\n  Eigen::VectorXd trans_norm(nNode);\n  trans_norm.setZero();\n  for(int i = 0; i < nNode; i++)\n  {\n    for(int j = 1; j <= 3; j++)\n    {\n      trans_norm[i] += std::pow(node_displ(i, j), 2);\n    }\n    trans_norm[i] = sqrt(trans_norm[i]);\n  }\n  double max_trans = trans_norm.maxCoeff();\n  if (max_trans > transl_tol_)\n  {\n    return false;\n  }\n\n  // stability check\n  // element reaction check\n  // grounded element shouldn't be in tension\n  // double sec_mod = M_PI * std::pow(material_parm_.radius_, 3) / 4;\n  // double area = M_PI * std::pow(material_parm_.radius_, 2);\n  //\n  // for (int i = 0; i < fixities_reaction.rows(); i++)\n  // {\n  //   int v_id = (int) fixities_reaction(i, 0);\n  //   const auto vertF = frame_.getVert(v_id);\n  //   const auto& nghdE = vertF->getNghdElement();\n  //\n  //   double eF_lx;\n  //   for(const auto& e : nghdE) {\n  //     if(e->isFixed()) {\n  //       // find element reaction\n  //       int e_result_id = -1;\n  //\n  //       for(int j = 0; j < element_reation.size(); j++) {\n  //         if (e->id() == element_reation(j, 0)) {\n  //           e_result_id = j;\n  //           break;\n  //         }\n  //       }\n  //\n  //       if(e->endVertU()->id() == v_id) {\n  //         eF_lx = element_reation(e_result_id, 1);\n  //         // only want tensile\n  //         if(eF_lx <= 0) {\n  //           eF_lx = 0;\n  //         }\n  //       } else {\n  //         eF_lx = element_reation(e_result_id, 7);\n  //         // only want tensile\n  //         if(eF_lx >= 0) {\n  //           eF_lx = 0;\n  //         }\n  //       } // end pts in local axis\n  //     } // e is fixed\n  //   }\n  //   std::cout << \"result eM: \" << eF_lx << std::endl;\n  //\n  //   // moment reaction at fixities\n  //   Eigen::VectorXd fixM = fixities_reaction.block<1,2>(i, 4);\n  //\n  //   // tension/compression bending stress\n  //   Eigen::VectorXd sigma_b = fixM / sec_mod;\n  //   std::cout << \"bending stess: \" << sigma_b << std::endl;\n  //\n  //   // axial tensile stress\n  //   Eigen::VectorXd sigma_a = (eF_lx / area) * Eigen::VectorXd::Ones(2);\n  //   std::cout << \"axial stess: \" << sigma_a << std::endl;\n  //\n  //   // total tensile stress = bending tensile stress + axial tensile stress\n  //   Eigen::VectorXd total_tensile = sigma_b + sigma_a;\n  //   std::cout << \"total stess: \" << total_tensile << \"\\n/\" << 0.1 * material_parm_.tensile_yeild_stress_ << std::endl;\n  //\n  //   // if  > 0.1 (tbd) * yield stress\n  //   if(std::abs(total_tensile.maxCoeff()) > 0.1 * material_parm_.tensile_yeild_stress_) {\n  //     return false;\n  //   }\n  // } // fixities_reaction\n\n // for (int i = 0; i < element_reation.rows(); i++)\n // {\n //   int e_id = (int) element_reation(i, 0);\n //   const auto e = frame_.getElement(e_id);\n //   if (e->endVertU()->isFixed() || e->endVertV()->isFixed())\n //   {\n //     // check tension\n //     if (element_reation(i, 1) < 0)\n //     {\n //       assert(element_reation(i, 7) > 0 && \"element axial reaction sign not consistent!\");\n //\n //       if (verbose_)\n //       {\n //         std::cout << \"grounded element #\" << e_id\n //                   << \" is in tension, the structure is not stable.\" << std::endl;\n //       }\n //\n //       return false;\n //     }\n //   }\n // }\n\n  return true;\n}\n\nvoid Stiffness::printOutTimer()\n{\n  if (verbose_)\n  {\n    printf(\"***Stiffness timer result:\\n\");\n    stiff_solver_.solve_timer_.Print(\"SolveK:\");\n    create_k_.Print(\"CreateGlobalK:\");\n    // check_ill_.Print(\"CheckIllCond:\");\n  }\n}\n\n} // namespace stiffness_checker\n} // namespace conmech\n", "meta": {"hexsha": "c1bd9856a6e3850af32a5270eaf01acd80c7c6b2", "size": 30050, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/stiffness_checker/Stiffness.cpp", "max_stars_repo_name": "yijiangh/conmech", "max_stars_repo_head_hexsha": "9f24230f08587c5e62e3b482f8829f5ea449a169", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2018-12-10T17:52:15.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-12T05:49:34.000Z", "max_issues_repo_path": "src/stiffness_checker/Stiffness.cpp", "max_issues_repo_name": "yijiangh/conmech", "max_issues_repo_head_hexsha": "9f24230f08587c5e62e3b482f8829f5ea449a169", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 32.0, "max_issues_repo_issues_event_min_datetime": "2018-11-28T04:00:24.000Z", "max_issues_repo_issues_event_max_datetime": "2020-03-14T21:20:38.000Z", "max_forks_repo_path": "src/stiffness_checker/Stiffness.cpp", "max_forks_repo_name": "yijiangh/conmech", "max_forks_repo_head_hexsha": "9f24230f08587c5e62e3b482f8829f5ea449a169", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-09-23T01:19:00.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-23T01:19:00.000Z", "avg_line_length": 28.8387715931, "max_line_length": 129, "alphanum_fraction": 0.643327787, "num_tokens": 9242, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6619228758499942, "lm_q2_score": 0.519521321952093, "lm_q1q2_score": 0.3438830474919201}}
{"text": "#ifndef COMMON_SEGMENTS_HPP\n#define COMMON_SEGMENTS_HPP\n\n#include <iostream>\n#include <vector>\n#include <memory>\n#include <Eigen/Dense>\n\n\n/*\n\nセグメントクラスの設計\n\nこのクラスは自立分散システム？（ADS）における自立個を表現する\n\nまず、自立個として必要なことは、\n・自分の状態を保持する自己状態ベクトルr\nを保持し、\n・自立分散システム全体の状態を表現するシステム状態ベクトルR\n・系全体の状態Rから得られるベクトル？z\nを受け取ることで、次の自己状態ベクトルをえることである。\n\n\n ながれとしては\n\n 各セグメントの\n システムの記述、パラメータの設定\n ・パラメータは同じシステムでも異なってくるのでシステム定義とは異なり、複数存在しなければならない\n ・複数のセグメントの状態、パラメータをそれぞれのセグメントにどのように渡すのか？\n\n\n\n まず、\n\n セグメントクラス\n 含有として\n ・状態\n ・\n\n */\n\nnamespace ADS {\n\n    // ADS内のセグメント挙動を記述するインターフェイスクラス？ これを継承して具体的なセグメントのシステムを記述する\n    // 各個セグメントにおけるパラメータの設定が問題になる\n\n\n    /*\n     * バランス\n     * 負荷配分\n     *\n     */\n\n    //状態量ツリー\n    template<typename T>\n    class TreeState {\n    public:\n\n        TreeState();\n        TreeState(const std::vector<std::vector<T> >&);\n        TreeState(const TreeState&);\n\n\n        //vector<vector <T>> の本体を返す\n        std::vector<std::vector<T> >& GetTree() { return R; };\n        //本体を更新\n        //void SetTree(std::vector<std::vector<T> >& in_) {R = in_;};\n\n        //RVOSによる最適化が働くのでそのまま帰すことにする\n        //MOVEセマンティクスは考えない\n        const TreeState<T> operator+(const TreeState<T>&) const;\n\n        const TreeState<T> operator-(const TreeState<T>&) const;\n\n        const TreeState<T> operator*(double) const;\n        //const TreeState<T> operator/(double, const TreeState<T> &);\n\n    private:\n\n        //コア\n        //状態量ツリー\n        std::vector<std::vector<T> > R;\n\n    };\n\n    /*\n     * セグメントクラスがやること\n     *\n     * １セグメントのシステムを書く\n     * システムは\n     * r_dot = f(t, P, z, R, idx)\n     * (t:時間、P:系のパラメータ、z:系全体から定まるベクトル、R:系全体を示す状態ベクトル、idx:セグメントのINDEX)\n     * として書かれる\n     *\n     * また、系全体から定まるベクトルzを計算する関数を書く\n     * これは\n     * z = g(t, P, R)\n     * (t:時間、P:系のパラメータ、R:系全体を示す状態ベクトル)\n     * として書かれる\n     *\n     * Rについて これはAdsManager内で管理される\n     * Rは系全体の状態を示す、実質行列となる\n     * セグメントiにおける状態を示すベクトルをr_iとすれば、Rは\n     * R＝{r_1 r_2 ... r_n} (n個のセグメント)\n     * となる\n     * これはvectorで示すことにする\n     *\n     * Pについて これはAdsManager内で管理される\n     * Pはこのセグメント群（おなじシステムで記述されるセグメントの集まり）すべてのパラメータを示す、多くの実装では行列になると思われる\n     * セグメントiにおけるパラメータを示すベクトルをp_iとすれば、Pは\n     * P={p_1 p_2 ... p_n} (n個のセグメント)\n     * となる\n     * なのでPはvectorで示すことになる\n     *\n     * */\n    template<typename T>\n    class Segment {\n\n    public:\n\n        Segment();\n\n        Segment(unsigned int no_);\n\n        //セグメントのシステム\n//        * １セグメントのシステムを書く\n//                * システムは\n//        * r_dot = f(t, P, z, R, idx)\n//                  * (t:時間、P:系のパラメータ、z:系全体から定まるベクトル、R:系全体を示す状態ベクトル、idx:セグメントのINDEX)\n//        * として書かれる\n        virtual T f(double t_\n                , const std::vector<std::vector<std::vector<double> > >& P_\n                , const std::vector<double>& z_\n                , const std::vector<std::vector<T> >& R_\n                , unsigned long idx_) = 0;\n\n        virtual T f(double t_\n                , const std::vector<std::vector<std::vector<double> > >& P_\n                , const std::vector<double>& z_\n                , const TreeState& R_\n                , unsigned long idx_) = 0;\n\n\n        // 入力として、系の状態ベクトルを受け取り、系全体から定まるベクトルを返す\n//        * z = g(t, P, R)\n//              * (t:時間、P:系のパラメータ、R:系全体を示す状態ベクトル)\n//        * として書かれる\n        virtual std::vector<double> g(double t_, const std::vector<std::vector<std::vector<double> > >& P_,\n                const std::vector<std::vector<T> >& R_) = 0;\n\n        virtual std::vector<double> g(double t_\n                , const std::vector<std::vector<std::vector<double> > >& P_\n                , const TreeState& R_) = 0;\n\n        //このシステムで記述されるセグメント数の設定\n        void SetNo(const unsigned int no_) { no_segments = no_; };\n\n        //セグメント数の取得\n        const unsigned int GetNo() { return no_segments; };\n\n        // 組み込みセグメントIDの設定\n        void SetID(const unsigned int id_) { id = id_; };\n\n        //セグメントIDの取得\n        const unsigned int GetID() { return id; };\n\n        //セグメントの有効化、無効化\n        void Enable() { is_enable = true; };\n\n        void Disable() { is_enable = false; };\n\n    private:\n\n        unsigned int no_segments; //セグメント数\n\n        unsigned int id;        // 組み込みセグメントID\n\n        bool is_enable;         //有効化\n\n\n    };\n\n    //ここでは各々のセグメントの時間発展とそれらの組み込み、初期状態設定を行う\n    /*\n     * AdsManagerがホストする状態量としては\n     *\n     * 経過時間:t\n     * 系の状態ベクトル:R\n     * 系のパラメータ:P\n     *\n     * セグメントの実装から決まったこと\n     * 系の状態ベクトルRはツリー構造をもつ\n     * なので実装はR:vector<vector<T>>となる\n     *\n     * また、それぞれのセグメントにおけるパラメータ設定も、ツリー構造とした\n     * なのでP:vector<vector<vector<double>>>となる\n     *TODO: パラメータベクトルは使いやすそうなクラスかなんかにする\n     *\n     *\n     * */\n\n    template<typename T>\n    class AdsManager {\n    public:\n\n        AdsManager();\n\n        //セグメントの登録を行う、セグメントIDを返す\n        /*\n         * セグメントの登録を行う\n         * 処理の流れとしては\n         *\n         * セグメントストレージにプッシュバック\n         * 個数分の状態量、パラメータベクトルの確保を行う\n         *\n         * セグメントインデックスを返す\n         *\n         * */\n        unsigned long AddSegment(std::shared_ptr<Segment<T> >);\n\n        //セグメント数の設定も行う\n        unsigned long AddSegment(std::shared_ptr<Segment<T> >, unsigned int no_segments_);\n\n\n        //パラメータ設定、初期値設定インターフェース\n\n\n        //各セグメントの状態を更新する\n        /*\n         * 全体の積分計算を行う\n         * */\n        void Update();\n\n    private:\n\n        //セグメント\n        std::vector<std::shared_ptr<Segment<T> > > segments;\n        //状態量ツリー\n        //std::vector<std::vector<T> > R;\n        TreeState R;\n        //パラメータツリー\n        std::vector<std::vector<std::vector<double> > > P;\n\n        //経過時間\n        double t;\n\n        //タイムピッチ\n        double dt;\n\n    };\n\n\n};\n\n#endif\t// COMMON_SEGMENTS_HPP\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n", "meta": {"hexsha": "3b7a4ed68a32396ec9e5a93f03592fe9c5480e8e", "size": 5518, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "common/segments.hpp", "max_stars_repo_name": "eryeden/ADS", "max_stars_repo_head_hexsha": "b756c3e3f595bf03d51ea054704d75f97146d491", "max_stars_repo_licenses": ["MIT"], "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/segments.hpp", "max_issues_repo_name": "eryeden/ADS", "max_issues_repo_head_hexsha": "b756c3e3f595bf03d51ea054704d75f97146d491", "max_issues_repo_licenses": ["MIT"], "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/segments.hpp", "max_forks_repo_name": "eryeden/ADS", "max_forks_repo_head_hexsha": "b756c3e3f595bf03d51ea054704d75f97146d491", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 18.3322259136, "max_line_length": 107, "alphanum_fraction": 0.5569046756, "num_tokens": 2572, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.661922862511608, "lm_q2_score": 0.519521321952093, "lm_q1q2_score": 0.3438830405623441}}
{"text": "//---------------------------------------------------------------------------//\n//!\n//! \\file   Utility_BasicBivariateDistribution.hpp\n//! \\author Alex Robinson\n//! \\brief  The basic bivariate distribution class declaration\n//!\n//---------------------------------------------------------------------------//\n\n#ifndef UTILITY_BASIC_BIVARIATE_DISTRIBUTION_HPP\n#define UTILITY_BASIC_BIVARIATE_DISTRIBUTION_HPP\n\n// Std Lib Includes\n#include <stdexcept>\n\n// Boost Includes\n#include <boost/serialization/split_member.hpp>\n\n// FRENSIE Includes\n#include \"Utility_OStreamableObject.hpp\"\n#include \"Utility_UnitTraits.hpp\"\n#include \"Utility_QuantityTraits.hpp\"\n#include \"Utility_DistributionTraits.hpp\"\n#include \"Utility_DistributionSerializationHelpers.hpp\"\n\n/*! \\defgroup bivariate_distributions Bivariate Distributions\n */\n\nnamespace Utility{\n\n/*! The unit-aware basic bivariate distribution\n * \\ingroup bivariate_distributions\n */\ntemplate<typename PrimaryIndependentUnit,\n         typename SecondaryIndependentUnit,\n         typename DependentUnit>\nclass UnitAwareBasicBivariateDistribution : public OStreamableObject\n{\n\n  // Typedef for this type\n  typedef UnitAwareBasicBivariateDistribution<PrimaryIndependentUnit,SecondaryIndependentUnit,DependentUnit> ThisType;\n\nprotected:\n\n  //! The primary independent unit traits typedef\n  typedef UnitTraits<PrimaryIndependentUnit> PrimaryIndepUnitTraits;\n\n  //! The secondary independent unit traits typedef\n  typedef UnitTraits<SecondaryIndependentUnit> SecondaryIndepUnitTraits;\n\n  //! The inverse primary independent unit traits typedef\n  typedef UnitTraits<typename UnitTraits<PrimaryIndependentUnit>::InverseUnit> InversePrimaryIndepUnitTraits;\n\n  //! The inverse secondary independent unit traits typedef\n  typedef UnitTraits<typename UnitTraits<SecondaryIndependentUnit>::InverseUnit> InverseSecondaryIndepUnitTraits;\n\n  //! The inverse independent unit traits typedef\n  typedef UnitTraits<typename UnitTraits<typename UnitTraits<PrimaryIndependentUnit>::InverseUnit>::template GetMultipliedUnitType<typename UnitTraits<SecondaryIndependentUnit>::InverseUnit>::type> InverseIndepUnitTraits;\n\n  //! The dependent unit traits typedef\n  typedef UnitTraits<DependentUnit> DepUnitTraits;\n\npublic:\n\n  //! The primary independent unit type\n  typedef PrimaryIndependentUnit PrimaryIndepUnit;\n\n  //! The secondary independent unit type\n  typedef SecondaryIndependentUnit SecondaryIndepUnit;\n\n  //! The dependent unit type\n  typedef DependentUnit DepUnit;\n\n  //! The primary independent quantity type\n  typedef typename PrimaryIndepUnitTraits::template GetQuantityType<double>::type PrimaryIndepQuantity;\n\n  //! The secondary independent quantity type\n  typedef typename SecondaryIndepUnitTraits::template GetQuantityType<double>::type SecondaryIndepQuantity;\n\n  //! The inverse secondary independent quantity type\n  typedef typename InverseSecondaryIndepUnitTraits::template GetQuantityType<double>::type InverseSecondaryIndepQuantity;\n\n  //! The dependent quantity type\n  typedef typename DepUnitTraits::template GetQuantityType<double>::type DepQuantity;\n\n  //! Constructor\n  UnitAwareBasicBivariateDistribution()\n  { /* ... */ }\n\n  //! Destructor\n  virtual ~UnitAwareBasicBivariateDistribution()\n  { /* ... */ }\n\n  //! Evaluate the distribution\n  virtual DepQuantity evaluate(\n            const PrimaryIndepQuantity primary_indep_var_value,\n            const SecondaryIndepQuantity secondary_indep_var_value ) const = 0;\n\n  //! Evaluate the secondary conditional PDF\n  virtual InverseSecondaryIndepQuantity evaluateSecondaryConditionalPDF(\n            const PrimaryIndepQuantity primary_indep_var_value,\n            const SecondaryIndepQuantity secondary_indep_var_value ) const = 0;\n\n  //! Return a random sample from the secondary conditional PDF\n  virtual SecondaryIndepQuantity sampleSecondaryConditional(\n                const PrimaryIndepQuantity primary_indep_var_value ) const = 0;\n\n  //! Return a random sample and record the number of trials\n  virtual SecondaryIndepQuantity sampleSecondaryConditionalAndRecordTrials(\n                            const PrimaryIndepQuantity primary_indep_var_value,\n                            DistributionTraits::Counter& trials ) const = 0;\n\n  //! Return the upper bound of the distribution primary independent variable\n  virtual PrimaryIndepQuantity getUpperBoundOfPrimaryIndepVar() const = 0;\n\n  //! Return the lower bound of the distribution primary independent variable\n  virtual PrimaryIndepQuantity getLowerBoundOfPrimaryIndepVar() const = 0;\n\n  //! Return the upper bound of the secondary conditional distribution\n  virtual SecondaryIndepQuantity getUpperBoundOfSecondaryConditionalIndepVar(\n                const PrimaryIndepQuantity primary_indep_var_value ) const = 0;\n\n  //! Return the lower bound of the secondary conditional distribution\n  virtual SecondaryIndepQuantity getLowerBoundOfSecondaryConditionalIndepVar(\n                const PrimaryIndepQuantity primary_indep_var_value ) const = 0;\n\n  //! Test if the distribution is tabular in the primary dimension\n  virtual bool isPrimaryDimensionTabular() const = 0;\n\n  //! Test if the distribution is continuous in the primary dimension\n  virtual bool isPrimaryDimensionContinuous() const = 0;\n\n  //! Test if the distribution has the same primary bounds\n  bool hasSamePrimaryBounds( const UnitAwareBasicBivariateDistribution& distribution ) const;\n\nprotected:\n\n  //! Add distribution data to the stream\n  template<typename... Types>\n  void toStreamDistImpl( std::ostream& os,\n                         const std::string& name,\n                         const Types&... data ) const;\n\nprivate:\n\n  // Save the distribution to an archive\n  template<typename Archive>\n  void save( Archive& ar, const unsigned version ) const\n  { /* ... */ }\n\n  // Load the distribution from an archive\n  template<typename Archive>\n  void load( Archive& ar, const unsigned version )\n  { /* ... */ }\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/*! The basic bivariate distribution (unit-agnostic)\n * \\ingroup bivariate_distributions\n */\ntypedef UnitAwareBasicBivariateDistribution<void,void,void> BasicBivariateDistribution;\n\n/*! \\brief Exception thrown by BivariateDistribution objects when an invalid\n * parameter is encountered.\n * \\ingroup bivariate_distributions\n */\nclass BadBivariateDistributionParameter : public std::logic_error\n{\npublic:\n  BadBivariateDistributionParameter( const std::string& msg )\n    : std::logic_error( msg )\n  { /* ... */ }\n\n  ~BadBivariateDistributionParameter() throw()\n  { /* ... */ }\n};\n\n} // end Utility namespace\n\nBOOST_SERIALIZATION_ASSUME_ABSTRACT_DISTRIBUTION3( UnitAwareBasicBivariateDistribution );\nBOOST_SERIALIZATION_DISTRIBUTION3_VERSION( UnitAwareBasicBivariateDistribution, 0 );\n\n//---------------------------------------------------------------------------//\n// Template Includes\n//---------------------------------------------------------------------------//\n\n#include \"Utility_BasicBivariateDistribution_def.hpp\"\n\n//---------------------------------------------------------------------------//\n\n#endif // end UTILITY_BASIC_BIVARIATE_DISTRIBUTION_HPP\n\n//---------------------------------------------------------------------------//\n// end Utility_BivariateDistribution.hpp\n//---------------------------------------------------------------------------//\n", "meta": {"hexsha": "37ff86b0ad2e9f6ce5749103a44acd3d9a181e30", "size": 7434, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "packages/utility/distribution/src/Utility_BasicBivariateDistribution.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/distribution/src/Utility_BasicBivariateDistribution.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/distribution/src/Utility_BasicBivariateDistribution.hpp", "max_forks_repo_name": "bam241/FRENSIE", "max_forks_repo_head_hexsha": "e1760cd792928699c84f2bdce70ff54228e88094", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2020-02-12T17:37:07.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-08T18:59:51.000Z", "avg_line_length": 37.3567839196, "max_line_length": 221, "alphanum_fraction": 0.7210115685, "num_tokens": 1420, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6334102636778401, "lm_q2_score": 0.5428632831725052, "lm_q1q2_score": 0.3438551753353145}}
{"text": "\n#define OFDIS_INTERNAL\n#include <Eigen/Core>\n#include <Eigen/LU>\n#include <Eigen/Dense>\n#include \"litiv/3rdparty/ofdis/fdf/image.h\"\n#include \"litiv/3rdparty/ofdis/patch.hpp\"\n#include \"litiv/3rdparty/ofdis/patchgrid.hpp\"\n#include \"litiv/utils/defines.hpp\" // only used here for compiler flags\n\ntemplate<ofdis::FlowInputType eInput, ofdis::FlowOutputType eOutput>\nofdis::PatGridClass<eInput,eOutput>::PatGridClass(\n        const camparam* cpt_in,\n        const camparam* cpo_in,\n        const optparam* op_in) :\n        cpt(cpt_in),\n        cpo(cpo_in),\n        op(op_in) {\n    // Generate grid on current scale\n    steps = op->steps;\n    nopw = ceil((float)cpt->width/(float)steps);\n    noph = ceil((float)cpt->height/(float)steps);\n    const int offsetw = floor((cpt->width-(nopw-1)*steps)/2);\n    const int offseth = floor((cpt->height-(noph-1)*steps)/2);\n    nopatches = nopw*noph;\n    pt_ref.resize(nopatches);\n    p_init.resize(nopatches);\n    pat.reserve(nopatches);\n    im_ao_eg = new Eigen::Map<const Eigen::MatrixXf>(nullptr,cpt->height,cpt->width);\n    im_ao_dx_eg = new Eigen::Map<const Eigen::MatrixXf>(nullptr,cpt->height,cpt->width);\n    im_ao_dy_eg = new Eigen::Map<const Eigen::MatrixXf>(nullptr,cpt->height,cpt->width);\n    im_bo_eg = new Eigen::Map<const Eigen::MatrixXf>(nullptr,cpt->height,cpt->width);\n    im_bo_dx_eg = new Eigen::Map<const Eigen::MatrixXf>(nullptr,cpt->height,cpt->width);\n    im_bo_dy_eg = new Eigen::Map<const Eigen::MatrixXf>(nullptr,cpt->height,cpt->width);\n    int patchid = 0;\n    for(int x=0; x<nopw; ++x) {\n        for(int y=0; y<noph; ++y) {\n            int i = x*noph+y;\n            pt_ref[i][0] = x*steps+offsetw;\n            pt_ref[i][1] = y*steps+offseth;\n            p_init[i].setZero();\n            pat.push_back(new PatClass<eInput,eOutput>(cpt,cpo,op,patchid));\n            patchid++;\n        }\n    }\n}\n\ntemplate<ofdis::FlowInputType eInput, ofdis::FlowOutputType eOutput>\nofdis::PatGridClass<eInput,eOutput>::~PatGridClass() {\n    delete im_ao_eg;\n    delete im_ao_dx_eg;\n    delete im_ao_dy_eg;\n    delete im_bo_eg;\n    delete im_bo_dx_eg;\n    delete im_bo_dy_eg;\n    for(int i=0; i< nopatches; ++i)\n        delete pat[i];\n}\n\ntemplate<ofdis::FlowInputType eInput, ofdis::FlowOutputType eOutput>\nvoid ofdis::PatGridClass<eInput,eOutput>::SetComplGrid(PatGridClass *cg_in) {\n    cg = cg_in;\n}\n\ntemplate<ofdis::FlowInputType eInput, ofdis::FlowOutputType eOutput>\nvoid ofdis::PatGridClass<eInput,eOutput>::InitializeGrid(const float* im_ao_in, const float* im_ao_dx_in, const float* im_ao_dy_in) {\n    im_ao = im_ao_in;\n    im_ao_dx = im_ao_dx_in;\n    im_ao_dy = im_ao_dy_in;\n    new(im_ao_eg) Eigen::Map<const Eigen::MatrixXf>(im_ao,cpt->height,cpt->width); // new placement operator\n    new(im_ao_dx_eg) Eigen::Map<const Eigen::MatrixXf>(im_ao_dx,cpt->height,cpt->width);\n    new(im_ao_dy_eg) Eigen::Map<const Eigen::MatrixXf>(im_ao_dy,cpt->height,cpt->width);\n#if USING_OPENMP\n    #pragma omp parallel for schedule(static)\n#endif //USING_OPENMP\n    for (int i = 0; i < nopatches; ++i) {\n        pat[i]->InitializePatch(im_ao_eg, im_ao_dx_eg, im_ao_dy_eg, pt_ref[i]);\n        p_init[i].setZero();\n    }\n}\n\ntemplate<ofdis::FlowInputType eInput, ofdis::FlowOutputType eOutput>\nvoid ofdis::PatGridClass<eInput,eOutput>::SetTargetImage(const float* im_bo_in, const float* im_bo_dx_in, const float* im_bo_dy_in) {\n    im_bo = im_bo_in;\n    im_bo_dx = im_bo_dx_in;\n    im_bo_dy = im_bo_dy_in;\n    new(im_bo_eg) Eigen::Map<const Eigen::MatrixXf>(im_bo,cpt->height,cpt->width); // new placement operator\n    new(im_bo_dx_eg) Eigen::Map<const Eigen::MatrixXf>(im_bo_dx,cpt->height,cpt->width); // new placement operator\n    new(im_bo_dy_eg) Eigen::Map<const Eigen::MatrixXf>(im_bo_dy,cpt->height,cpt->width); // new placement operator\n#if USING_OPENMP\n    #pragma omp parallel for schedule(static)\n#endif //USING_OPENMP\n    for(int i = 0; i < nopatches; ++i)\n        pat[i]->SetTargetImage(im_bo_eg, im_bo_dx_eg, im_bo_dy_eg);\n}\n\ntemplate<ofdis::FlowInputType eInput, ofdis::FlowOutputType eOutput>\nvoid ofdis::PatGridClass<eInput,eOutput>::Optimize() {\n#if USING_OPENMP\n    #pragma omp parallel for schedule(dynamic,10)\n#endif //USING_OPENMP\n    for(int i = 0; i < nopatches; ++i)\n        pat[i]->OptimizeIter(p_init[i], true); // optimize until convergence\n}\n\ntemplate<ofdis::FlowInputType eInput, ofdis::FlowOutputType eOutput>\nvoid ofdis::PatGridClass<eInput,eOutput>::InitializeFromCoarserOF(const float* flow_prev) {\n#if USING_OPENMP\n    #pragma omp parallel for schedule(dynamic,10)\n#endif //USING_OPENMP\n    for (int ip = 0; ip < nopatches; ++ip) {\n        int x = floor(pt_ref[ip][0] / 2); // better, but slower: use bil. interpolation here\n        int y = floor(pt_ref[ip][1] / 2);\n        int i = y*(cpt->width/2) + x;\n        if(eOutput==ofdis::FlowOutput_OpticalFlow) {\n            p_init[ip](0) = flow_prev[2*i]*2;\n            p_init[ip](1) = flow_prev[2*i+1]*2;\n        }\n        else\n            p_init[ip](0) = flow_prev[i]*2;\n    }\n}\n\ntemplate<ofdis::FlowInputType eInput, ofdis::FlowOutputType eOutput>\nvoid ofdis::PatGridClass<eInput,eOutput>::AggregateFlowDense(float *flowout) const {\n    float* we = new float[cpt->width * cpt->height];\n    memset(flowout, 0, sizeof(float) * (op->nop * cpt->width * cpt->height) );\n    memset(we,      0, sizeof(float) * (          cpt->width * cpt->height) );\n#ifdef USE_PARALLEL_ON_FLOWAGGR // Using this enables OpenMP on flow aggregation. This can lead to race conditions. Experimentally we found that the result degrades only marginally. However, for our experiments we did not enable this.\n    #pragma omp parallel for schedule(static)\n#endif\n    for(int ip = 0; ip < nopatches; ++ip) {\n        if(pat[ip]->IsValid()) {\n            const typename p_init_type::value_type* fl = pat[ip]->GetParam(); // flow/horiz displacement of this patch\n            typename p_init_type::value_type flnew;\n            const float* pweight = pat[ip]->GetpWeightPtr(); // use image error as weight\n            int lb = -op->p_samp_s/2;\n            int ub = op->p_samp_s/2-1;\n            for(int y = lb; y <= ub; ++y) {\n                for(int x = lb; x <= ub; ++x, ++pweight) {\n                    int yt = (y + pt_ref[ip][1]);\n                    int xt = (x + pt_ref[ip][0]);\n                    if (xt >= 0 && yt >= 0 && xt < cpt->width && yt < cpt->height) {\n                        int i = yt*cpt->width + xt;\n                        float absw;\n                        if(eInput==ofdis::FlowInput_RGB) {\n                            absw = (float)(std::max(op->minerrval,*pweight)); ++pweight;\n                            absw+= (float)(std::max(op->minerrval,*pweight)); ++pweight;\n                            absw+= (float)(std::max(op->minerrval,*pweight));\n                            absw = 1.0f/absw;\n                        }\n                        else\n                            absw = 1.0f/(float)(std::max(op->minerrval,*pweight));\n                        flnew = (*fl) * absw;\n                        we[i] += absw;\n                        if(eOutput==ofdis::FlowOutput_OpticalFlow) {\n                            flowout[2*i]   += flnew[0];\n                            flowout[2*i+1] += flnew[1];\n                        }\n                        else\n                            flowout[i] += flnew[0];\n                    }\n                }\n            }\n        }\n    }\n\n    // if complementary (forward-backward merging) is given, integrate negative backward flow as well\n    if(cg) {\n        Eigen::Vector4f wbil; // bilinear weight vector\n        Eigen::Vector4i pos;\n#if USING_OPENMP\n    #ifdef USE_PARALLEL_ON_FLOWAGGR\n        #pragma omp parallel for schedule(static)\n    #endif\n#endif //USING_OPENMP\n        for(int ip = 0; ip < cg->nopatches; ++ip) {\n            if (cg->pat[ip]->IsValid()) {\n                const typename p_init_type::value_type* fl = (cg->pat[ip]->GetParam()); // flow/horiz displacement of this patch\n                typename p_init_type::value_type flnew;\n                const Eigen::Vector2f rppos = cg->pat[ip]->GetPointPos(); // get patch position after optimization\n                const float* pweight = cg->pat[ip]->GetpWeightPtr(); // use image error as weight\n                Eigen::Vector2f resid;\n                // compute bilinear weight vector\n                pos[0] = ceil(rppos[0] +.00001); // make sure they are rounded up to natural number\n                pos[1] = ceil(rppos[1] +.00001); // make sure they are rounded up to natural number\n                pos[2] = floor(rppos[0]);\n                pos[3] = floor(rppos[1]);\n                resid[0] = rppos[0] - pos[2];\n                resid[1] = rppos[1] - pos[3];\n                wbil[0] = resid[0]*resid[1];\n                wbil[1] = (1-resid[0])*resid[1];\n                wbil[2] = resid[0]*(1-resid[1]);\n                wbil[3] = (1-resid[0])*(1-resid[1]);\n                int lb = -op->p_samp_s/2;\n                int ub = op->p_samp_s/2-1;\n                for(int y = lb; y <= ub; ++y) {\n                    for(int x = lb; x <= ub; ++x, ++pweight) {\n                        int yt = y + pos[1];\n                        int xt = x + pos[0];\n                        if(xt >= 1 && yt >= 1 && xt < (cpt->width-1) && yt < (cpt->height-1)) {\n                            float absw;\n                            if(eInput==ofdis::FlowInput_RGB) {\n                                absw = (float)(std::max(op->minerrval,*pweight)); ++pweight;\n                                absw+= (float)(std::max(op->minerrval,*pweight)); ++pweight;\n                                absw+= (float)(std::max(op->minerrval,*pweight));\n                                absw = 1.0f/absw;\n                            }\n                            else\n                                absw = 1.0f/(float)(std::max(op->minerrval,*pweight));\n                            flnew = (*fl) * absw;\n                            int idxcc =  xt    +  yt   *cpt->width;\n                            int idxfc = (xt-1) +  yt   *cpt->width;\n                            int idxcf =  xt    + (yt-1)*cpt->width;\n                            int idxff = (xt-1) + (yt-1)*cpt->width;\n                            we[idxcc] += wbil[0] * absw;\n                            we[idxfc] += wbil[1] * absw;\n                            we[idxcf] += wbil[2] * absw;\n                            we[idxff] += wbil[3] * absw;\n                            if(eOutput==ofdis::FlowOutput_OpticalFlow) {\n                                flowout[2*idxcc  ] -= wbil[0] * flnew[0];   // use reversed flow\n                                flowout[2*idxcc+1] -= wbil[0] * flnew[1];\n                                flowout[2*idxfc  ] -= wbil[1] * flnew[0];\n                                flowout[2*idxfc+1] -= wbil[1] * flnew[1];\n                                flowout[2*idxcf  ] -= wbil[2] * flnew[0];\n                                flowout[2*idxcf+1] -= wbil[2] * flnew[1];\n                                flowout[2*idxff  ] -= wbil[3] * flnew[0];\n                                flowout[2*idxff+1] -= wbil[3] * flnew[1];\n                            }\n                            else {\n                                flowout[idxcc] -= wbil[0] * flnew[0]; // simple averaging of inverse horizontal displacement\n                                flowout[idxfc] -= wbil[1] * flnew[0];\n                                flowout[idxcf] -= wbil[2] * flnew[0];\n                                flowout[idxff] -= wbil[3] * flnew[0];\n                            }\n                        }\n                    }\n                }\n            }\n        }\n    }\n#if USING_OPENMP\n    #pragma omp parallel for schedule(static, 100)\n#endif //USING_OPENMP\n    // normalize each pixel by dividing displacement by aggregated weights from all patches\n    for (int yi = 0; yi < cpt->height; ++yi) {\n        for (int xi = 0; xi < cpt->width; ++xi) {\n            int i = yi*cpt->width + xi;\n            if (we[i]>0) {\n                if(eOutput==ofdis::FlowOutput_OpticalFlow) {\n                    flowout[2*i  ] /= we[i];\n                    flowout[2*i+1] /= we[i];\n                }\n                else\n                    flowout[i] /= we[i];\n            }\n        }\n    }\n    delete[] we;\n}\n\ntemplate class ofdis::PatGridClass<ofdis::FlowInput_Grayscale,ofdis::FlowOutput_OpticalFlow>;\ntemplate class ofdis::PatGridClass<ofdis::FlowInput_Gradient,ofdis::FlowOutput_OpticalFlow>;\ntemplate class ofdis::PatGridClass<ofdis::FlowInput_RGB,ofdis::FlowOutput_OpticalFlow>;\ntemplate class ofdis::PatGridClass<ofdis::FlowInput_Grayscale,ofdis::FlowOutput_StereoDepth>;\ntemplate class ofdis::PatGridClass<ofdis::FlowInput_Gradient,ofdis::FlowOutput_StereoDepth>;\ntemplate class ofdis::PatGridClass<ofdis::FlowInput_RGB,ofdis::FlowOutput_StereoDepth>;", "meta": {"hexsha": "10cbd9b0dd054b6d1a3d36dc06eceb93c7f6d3b3", "size": 12770, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "3rdparty/ofdis/src/patchgrid.cpp", "max_stars_repo_name": "jpjodoin/litiv", "max_stars_repo_head_hexsha": "435556bea20d60816aff492f50587b1a2d748b21", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 97.0, "max_stars_repo_stars_event_min_datetime": "2015-10-16T04:32:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T07:04:02.000Z", "max_issues_repo_path": "3rdparty/ofdis/src/patchgrid.cpp", "max_issues_repo_name": "jpjodoin/litiv", "max_issues_repo_head_hexsha": "435556bea20d60816aff492f50587b1a2d748b21", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 19.0, "max_issues_repo_issues_event_min_datetime": "2016-07-01T16:37:02.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-10T06:09:39.000Z", "max_forks_repo_path": "3rdparty/ofdis/src/patchgrid.cpp", "max_forks_repo_name": "jpjodoin/litiv", "max_forks_repo_head_hexsha": "435556bea20d60816aff492f50587b1a2d748b21", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 41.0, "max_forks_repo_forks_event_min_datetime": "2015-11-17T05:59:23.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-16T09:30:28.000Z", "avg_line_length": 47.8277153558, "max_line_length": 234, "alphanum_fraction": 0.5452623336, "num_tokens": 3572, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7520125737597972, "lm_q2_score": 0.4571367168274948, "lm_q1q2_score": 0.34377255898154796}}
{"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_INIT_GRID_SAMPLING_HPP\n#define LIMBO_INIT_GRID_SAMPLING_HPP\n\n#include <Eigen/Core>\n\n#include <limbo/tools/macros.hpp>\n\nnamespace limbo {\n    namespace defaults {\n        struct init_gridsampling {\n            ///@ingroup init_defaults\n            BO_PARAM(int, bins, 5);\n        };\n    }\n    namespace init {\n        /** @ingroup init\n          \\rst\n          Grid sampling.\n\n          Parameter:\n            - ``int bins`` (number of bins)\n          \\endrst\n        */\n        template <typename Params>\n        struct GridSampling {\n            template <typename StateFunction, typename AggregatorFunction, typename Opt>\n            void operator()(const StateFunction& seval, const AggregatorFunction&, Opt& opt) const\n            {\n                _explore(0, seval, Eigen::VectorXd::Constant(StateFunction::dim_in(), 0), opt);\n            }\n\n        private:\n            // recursively explore all the dimensions\n            template <typename StateFunction, typename Opt>\n            void _explore(int dim_in, const StateFunction& seval, const Eigen::VectorXd& current,\n                Opt& opt) const\n            {\n                for (double x = 0; x <= 1.0f; x += 1.0f / (double)Params::init_gridsampling::bins()) {\n                    Eigen::VectorXd point = current;\n                    point[dim_in] = x;\n                    if (dim_in == current.size() - 1) {\n                        opt.eval_and_add(seval, point);\n                    }\n                    else {\n                        _explore(dim_in + 1, seval, point, opt);\n                    }\n                }\n            }\n        };\n    }\n}\n#endif\n", "meta": {"hexsha": "6e184f9898ec845734556a92eb31aa10841e517f", "size": 4037, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "limbo/src/limbo/init/grid_sampling.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/init/grid_sampling.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/init/grid_sampling.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": 41.193877551, "max_line_length": 102, "alphanum_fraction": 0.6477582363, "num_tokens": 963, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6113819732941511, "lm_q2_score": 0.5621765008857982, "lm_q1q2_score": 0.34370457845116037}}
{"text": "//---------------------------------------------------------------------------//\n// Copyright (c) 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_ALGEBRA_FFT_MAKE_EVALUATION_DOMAIN_HPP\n#define CRYPTO3_ALGEBRA_FFT_MAKE_EVALUATION_DOMAIN_HPP\n\n#include <vector>\n\n#include <boost/math/tools/polynomial.hpp>\n\n#include <nil/crypto3/fft/domains/evaluation_domain.hpp>\n#include <nil/crypto3/fft/domains/arithmetic_sequence_domain.hpp>\n#include <nil/crypto3/fft/domains/basic_radix2_domain.hpp>\n#include <nil/crypto3/fft/domains/extended_radix2_domain.hpp>\n#include <nil/crypto3/fft/domains/geometric_sequence_domain.hpp>\n#include <nil/crypto3/fft/domains/step_radix2_domain.hpp>\n\n#include <nil/crypto3/fft/detail/field_utils.hpp>\n\nnamespace nil {\n    namespace crypto3 {\n        namespace fft {\n\n            /*!\n            @brief\n             A convenience method for choosing an evaluation domain\n             Returns an evaluation domain object in which the domain S has size\n             |S| >= MinSize.\n             The function get_evaluation_domain is chosen from different supported domains,\n             depending on MinSize.\n            */\n\n            namespace detail {\n                using namespace nil::crypto3::algebra;\n\n                template<typename FieldType>\n                bool is_basic_radix2_domain(std::size_t m) {\n                    const std::size_t log_m = static_cast<std::size_t>(std::ceil(std::log2(m)));\n\n                    return (m > 1) && (log_m <= fields::arithmetic_params<FieldType>::s) && (m == (1ul << log_m));\n                }\n\n                template<typename FieldType>\n                bool is_extended_radix2_domain(std::size_t m) {\n                    const std::size_t log_m = static_cast<std::size_t>(std::ceil(std::log2(m)));\n                    const std::size_t small_m = m / 2;\n                    const std::size_t log_small_m = static_cast<std::size_t>(std::ceil(std::log2(small_m)));\n\n                    return (m > 1) && (log_m == fields::arithmetic_params<FieldType>::s + 1) &&\n                           (small_m == (1ul << log_small_m)) &&\n                           (log_small_m <= fields::arithmetic_params<FieldType>::s);\n                }\n\n                template<typename FieldType>\n                bool is_step_radix2_domain(std::size_t m) {\n                    const std::size_t log_m = static_cast<std::size_t>(std::ceil(std::log2(m)));\n                    const std::size_t shift_log_m = (1ul << log_m);\n                    const std::size_t log_shift_log_m = static_cast<std::size_t>(std::ceil(std::log2(shift_log_m)));\n                    const std::size_t small_m = m - (1ul << (static_cast<std::size_t>(std::ceil(std::log2(m))) - 1));\n                    const std::size_t log_small_m = static_cast<std::size_t>(std::ceil(std::log2(small_m)));\n\n                    return (m > 1) && (small_m == (1ul << log_small_m)) && (shift_log_m == (1ul << log_shift_log_m)) &&\n                           (log_shift_log_m <= fields::arithmetic_params<FieldType>::s);\n                }\n\n                template<typename FieldType>\n                bool is_geometric_sequence_domain(std::size_t m) {\n                    return (m > 1) &&\n                           (typename FieldType::value_type(fields::arithmetic_params<FieldType>::geometric_generator) !=\n                            FieldType::value_type::zero());\n                }\n\n                template<typename FieldType>\n                bool is_arithmetic_sequence_domain(std::size_t m) {\n                    return (m > 1) && (typename FieldType::value_type(\n                                           fields::arithmetic_params<FieldType>::arithmetic_generator) !=\n                                       FieldType::value_type::zero());\n                }\n\n            }    // namespace detail\n\n            template<typename FieldType>\n            std::shared_ptr<evaluation_domain<FieldType>> make_evaluation_domain(std::size_t m) {\n                typedef std::shared_ptr<evaluation_domain<FieldType>> ret_type;\n\n                const std::size_t big = 1ul << (std::size_t(std::ceil(std::log2(m))) - 1);\n                const std::size_t rounded_small = (1ul << std::size_t(std::ceil(std::log2(m - big))));\n\n                if (detail::is_basic_radix2_domain<FieldType>(m)) {\n                    ret_type result;\n                    result.reset(new basic_radix2_domain<FieldType>(m));\n                    return result;\n                }\n\n                if (detail::is_extended_radix2_domain<FieldType>(m)) {\n                    ret_type result;\n                    result.reset(new extended_radix2_domain<FieldType>(m));\n                    return result;\n                }\n\n                if (detail::is_step_radix2_domain<FieldType>(m)) {\n                    ret_type result;\n                    result.reset(new step_radix2_domain<FieldType>(m));\n                    return result;\n                }\n\n                if (detail::is_basic_radix2_domain<FieldType>(big + rounded_small)) {\n                    ret_type result;\n                    result.reset(new basic_radix2_domain<FieldType>(big + rounded_small));\n                    return result;\n                }\n\n                if (detail::is_extended_radix2_domain<FieldType>(big + rounded_small)) {\n                    ret_type result;\n                    result.reset(new extended_radix2_domain<FieldType>(big + rounded_small));\n                    return result;\n                }\n\n                if (detail::is_step_radix2_domain<FieldType>(big + rounded_small)) {\n                    ret_type result;\n                    result.reset(new step_radix2_domain<FieldType>(big + rounded_small));\n                    return result;\n                }\n\n                if (detail::is_geometric_sequence_domain<FieldType>(m)) {\n                    ret_type result;\n                    result.reset(new geometric_sequence_domain<FieldType>(m));\n                    return result;\n                }\n\n                if (detail::is_arithmetic_sequence_domain<FieldType>(m)) {\n                    ret_type result;\n                    result.reset(new arithmetic_sequence_domain<FieldType>(m));\n                    return result;\n                }\n\n                return ret_type();\n            }\n        }    // namespace fft\n    }        // namespace crypto3\n}    // namespace nil\n\n#endif    // CRYPTO3_ALGEBRA_FFT_MAKE_EVALUATION_DOMAIN_HPP\n", "meta": {"hexsha": "3ccc9a7263542343acdf073c2f810e0d3b2c3ef4", "size": 7668, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "snark-logic/libs-source/fft/include/nil/crypto3/fft/make_evaluation_domain.hpp", "max_stars_repo_name": "podlodkin/podlodkin-freeton-year-control", "max_stars_repo_head_hexsha": "e394c11f2414804d2fbde93a092ae589d4359739", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "snark-logic/libs-source/fft/include/nil/crypto3/fft/make_evaluation_domain.hpp", "max_issues_repo_name": "podlodkin/podlodkin-freeton-year-control", "max_issues_repo_head_hexsha": "e394c11f2414804d2fbde93a092ae589d4359739", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "snark-logic/libs-source/fft/include/nil/crypto3/fft/make_evaluation_domain.hpp", "max_forks_repo_name": "podlodkin/podlodkin-freeton-year-control", "max_forks_repo_head_hexsha": "e394c11f2414804d2fbde93a092ae589d4359739", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-08-31T06:27:19.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-31T06:27:19.000Z", "avg_line_length": 46.1927710843, "max_line_length": 120, "alphanum_fraction": 0.5709441836, "num_tokens": 1567, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6926419958239132, "lm_q2_score": 0.4960938294709195, "lm_q1q2_score": 0.3436154201606657}}
{"text": "/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */\n\n/*\n Copyright (C) 2003 Neil Firth\n Copyright (C) 2003 Ferdinando Ametrano\n Copyright (C) 2007 StatPro Italia srl\n\n This file is part of QuantLib, a free-software/open-source library\n for financial quantitative analysts and developers - http://quantlib.org/\n\n QuantLib is free software: you can redistribute it and/or modify it\n under the terms of the QuantLib license.  You should have received a\n copy of the license along with this program; if not, please email\n <quantlib-dev@lists.sf.net>. The license is also available online at\n <http://quantlib.org/license.shtml>.\n\n This program is distributed in the hope that it will be useful, but WITHOUT\n ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n FOR A PARTICULAR PURPOSE.  See the license for more details.\n*/\n\n#include <ql/instruments/barrieroption.hpp>\n#include <ql/instruments/impliedvolatility.hpp>\n#include <ql/pricingengines/barrier/analyticbarrierengine.hpp>\n#include <ql/exercise.hpp>\n#include <boost/scoped_ptr.hpp>\n\nnamespace QuantLib {\n\n    BarrierOption::BarrierOption(\n        Barrier::Type barrierType,\n        Real barrier,\n        Real rebate,\n        const ext::shared_ptr<StrikedTypePayoff>& payoff,\n        const ext::shared_ptr<Exercise>& exercise)\n    : OneAssetOption(payoff, exercise),\n      barrierType_(barrierType), barrier_(barrier), rebate_(rebate) {}\n\n    void BarrierOption::setupArguments(PricingEngine::arguments* args) const {\n\n        OneAssetOption::setupArguments(args);\n\n        auto* moreArgs = dynamic_cast<BarrierOption::arguments*>(args);\n        QL_REQUIRE(moreArgs != nullptr, \"wrong argument type\");\n        moreArgs->barrierType = barrierType_;\n        moreArgs->barrier = barrier_;\n        moreArgs->rebate = rebate_;\n    }\n\n\n    Volatility BarrierOption::impliedVolatility(\n             Real targetValue,\n             const ext::shared_ptr<GeneralizedBlackScholesProcess>& process,\n             Real accuracy,\n             Size maxEvaluations,\n             Volatility minVol,\n             Volatility maxVol) const {\n\n        QL_REQUIRE(!isExpired(), \"option expired\");\n\n        ext::shared_ptr<SimpleQuote> volQuote(new SimpleQuote);\n\n        ext::shared_ptr<GeneralizedBlackScholesProcess> newProcess =\n            detail::ImpliedVolatilityHelper::clone(process, volQuote);\n\n        // engines are built-in for the time being\n        boost::scoped_ptr<PricingEngine> engine;\n        switch (exercise_->type()) {\n          case Exercise::European:\n            engine.reset(new AnalyticBarrierEngine(newProcess));\n            break;\n          case Exercise::American:\n          case Exercise::Bermudan:\n            QL_FAIL(\"engine not available for non-European barrier option\");\n            break;\n          default:\n            QL_FAIL(\"unknown exercise type\");\n        }\n\n        return detail::ImpliedVolatilityHelper::calculate(*this,\n                                                          *engine,\n                                                          *volQuote,\n                                                          targetValue,\n                                                          accuracy,\n                                                          maxEvaluations,\n                                                          minVol, maxVol);\n    }\n\n\n    BarrierOption::arguments::arguments()\n    : barrierType(Barrier::Type(-1)), barrier(Null<Real>()),\n      rebate(Null<Real>()) {}\n\n    void BarrierOption::arguments::validate() const {\n        OneAssetOption::arguments::validate();\n\n        switch (barrierType) {\n          case Barrier::DownIn:\n          case Barrier::UpIn:\n          case Barrier::DownOut:\n          case Barrier::UpOut:\n            break;\n          default:\n            QL_FAIL(\"unknown type\");\n        }\n\n        QL_REQUIRE(barrier != Null<Real>(), \"no barrier given\");\n        QL_REQUIRE(rebate != Null<Real>(), \"no rebate given\");\n    }\n\n    bool BarrierOption::engine::triggered(Real underlying) const {\n        switch (arguments_.barrierType) {\n          case Barrier::DownIn:\n          case Barrier::DownOut:\n            return underlying < arguments_.barrier;\n          case Barrier::UpIn:\n          case Barrier::UpOut:\n            return underlying > arguments_.barrier;\n          default:\n            QL_FAIL(\"unknown type\");\n        }\n    }\n\n}\n\n", "meta": {"hexsha": "a71ab5491ceefe35cf940d6baf5ae98558d39fff", "size": 4412, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ql/instruments/barrieroption.cpp", "max_stars_repo_name": "igitur/quantlib", "max_stars_repo_head_hexsha": "3f6b7271a68004cdb6db90f0e87346e8208234a2", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-03-16T16:41:39.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-16T16:41:39.000Z", "max_issues_repo_path": "ql/instruments/barrieroption.cpp", "max_issues_repo_name": "igitur/quantlib", "max_issues_repo_head_hexsha": "3f6b7271a68004cdb6db90f0e87346e8208234a2", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2021-02-08T06:07:05.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-29T12:23:40.000Z", "max_forks_repo_path": "ql/instruments/barrieroption.cpp", "max_forks_repo_name": "puszkarz/QuantLib", "max_forks_repo_head_hexsha": "9bb90c8cc4127927fc6737dcc083bbd9cbdf4a2f", "max_forks_repo_licenses": ["BSD-3-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.0158730159, "max_line_length": 79, "alphanum_fraction": 0.6035811423, "num_tokens": 913, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6926419958239132, "lm_q2_score": 0.49609382947091946, "lm_q1q2_score": 0.3436154201606657}}
{"text": "#ifndef GPSOINN_HXX\n#define GPSOINN_HXX\n\n#include \"graph/graph.hxx\"\n\n#include <Eigen/Dense>\n#include <Eigen/StdVector>\n#include <algorithm>\n#include <array>\n#include <cmath>\n#include <random>\n\nnamespace GPSOINN {\n\ntemplate <unsigned dimension> class GPNet {\n  private:\n    typedef Eigen::Matrix<double, dimension, 1> NodeVector;\n    struct Node {\n        NodeVector vector;\n        size_t win_count;\n    };\n    typedef std::array<double, dimension> array;\n    typedef UndirectedGraph<Node, unsigned, std::less<NodeVector>,\n                            Eigen::aligned_allocator<NodeVector>>\n        UGraph;\n\n  public:\n    GPNet(unsigned lambda = 20000, unsigned age_max = 50, unsigned k = 1,\n          double sigma_2 = 1e-6);\n    ~GPNet() {}\n\n    void train(array &data);\n    double predict(array &data);\n\n  private:\n    UGraph m_graph;\n    double m_sigma_2;\n    unsigned m_local_opt_coeff = 100;\n    unsigned m_age_max;\n    unsigned m_lambda;\n    unsigned m_k;\n    unsigned m_cycles = 0;\n    const double m_const_coeff;\n\n    std::pair<double, double> threshold(size_t index,\n                                        const NodeVector &x_vector);\n}; // class GPNet\n\n} // namespace GPSOINN\n\nnamespace GPSOINN {\n\ntemplate <unsigned dimension>\nGPNet<dimension>::GPNet(unsigned lambda, unsigned age_max, unsigned k,\n                        double sigma_2)\n    : m_lambda(lambda), m_age_max(age_max), m_k(k), m_sigma_2(sigma_2),\n      m_const_coeff(std::sqrt(std::pow(2 * M_PI, dimension))) {\n    m_graph.insert_vertex(Node{.vector = NodeVector::Random(), .win_count = 0});\n    m_graph.insert_vertex(Node{.vector = NodeVector::Random(), .win_count = 0});\n}\n\ntemplate <unsigned dimension> void GPNet<dimension>::train(array &data) {\n    using namespace Eigen;\n    using NodeM = Matrix<double, dimension, Dynamic>;\n\n    if (m_graph.vertex_count() < 2) {\n        m_graph.insert_vertex(\n            Node{.vector = NodeVector::Random(), .win_count = 0});\n        m_graph.insert_vertex(\n            Node{.vector = NodeVector::Random(), .win_count = 0});\n    }\n    std::random_device rand_dev;\n    std::srand(rand_dev());\n\n    typename NodeM::Index min_index, min2_index;\n    Map<NodeVector> input(data.data());\n\n    {\n        // construct the data matrix\n        NodeM nodes(dimension, m_graph.vertex_count());\n\n        size_t col = 0;\n        for (auto &node : m_graph) {\n            nodes.col(col) = node.value().vector;\n            ++col;\n        }\n\n        // find the winner and the second winner\n        RowVectorXd distances =\n            (nodes.colwise() - input).colwise().squaredNorm();\n        distances.minCoeff(&min_index);\n\n        if (min_index == 0) {\n            distances(0) = distances(1);\n            distances.minCoeff(&min2_index);\n            if (min2_index == 0)\n                min2_index = 1;\n        } else {\n            distances(min_index) = distances(min_index - 1);\n            distances.minCoeff(&min2_index);\n            if (min2_index == min_index)\n                ++min2_index;\n        }\n    }\n\n    auto min_iter = m_graph.begin();\n    auto min2_iter = m_graph.begin();\n    for (size_t i = 0; i != min_index; ++i)\n        ++min_iter;\n    for (size_t i = 0; i != min2_index; ++i)\n        ++min2_iter;\n\n    auto[threshold1, prob1] = threshold(min_index, input);\n    auto[threshold2, prob2] = threshold(min2_index, input);\n\n    if ((prob1 > prob2 && prob1 > threshold1) || prob2 > threshold2) {\n        m_graph.insert_edge(min_iter, min2_iter, 0);\n\n        auto &win_count = min_iter->value().win_count;\n        NodeVector &winner_vec = min_iter->value().vector;\n        ++win_count;\n        winner_vec.array() += ((input - winner_vec).array() / (win_count + 1));\n\n        for (auto &edge : *min_iter) {\n            NodeVector &node_vec = m_graph[edge.head].value().vector;\n            node_vec.array() += ((input - node_vec).array() /\n                                 m_local_opt_coeff / (win_count + 1));\n            ++edge.weight;\n        }\n\n        for (auto niter = m_graph.cbegin(); niter != m_graph.cend(); ++niter) {\n            for (auto edge = niter->cbegin(), pre = niter->cbefore_begin();\n                 edge != niter->cend();) {\n                if (edge->weight > m_age_max) {\n                    edge = m_graph.erase_after_edge(niter, pre);\n                } else {\n                    ++edge;\n                    ++pre;\n                }\n            }\n        }\n    } else {\n        m_graph.insert_vertex(Node{.vector = input, .win_count = 0});\n    }\n\n    ++m_cycles;\n    if (m_cycles == m_lambda) {\n        m_cycles = 0;\n        for (auto iter = m_graph.cbegin(); iter != m_graph.cend();) {\n            if (std::distance(iter->cbegin(), iter->cend()) < m_k)\n                iter = m_graph.erase_vertex(iter);\n            else\n                ++iter;\n        }\n    }\n} // namespace GPSOINN\n\ntemplate <unsigned dimension>\nstd::pair<double, double>\nGPNet<dimension>::threshold(size_t index, const NodeVector &x_vector) {\n    using namespace Eigen;\n\n    Matrix<double, dimension, dimension> local_cov;\n    local_cov.setZero();\n    auto iter = m_graph.begin();\n    for (size_t i = 0; i != index; ++i)\n        ++iter;\n\n    NodeVector &winner_vec = iter->value().vector;\n    size_t win_sum = 0;\n    size_t neighbour_cnt = 0;\n    for (auto edge : *iter) {\n        NodeVector &node_vec = m_graph[edge.head].value().vector;\n        local_cov.array() +=\n            ((node_vec - winner_vec) * (node_vec - winner_vec).transpose())\n                .array() *\n            edge.weight;\n        win_sum += edge.weight;\n        ++neighbour_cnt;\n    }\n    if (win_sum)\n        local_cov.array() /= win_sum;\n    local_cov += MatrixXd::Identity(dimension, dimension) * m_sigma_2;\n\n    // if (neighbour_cnt > dimension) {\n    //     Matrix<bool, dimension, 1> comp;\n    //     SelfAdjointEigenSolver<Matrix<double, dimension, dimension>>\n    //     eigens(local_cov);\n    //     comp = ((eigens.eigenvalues()).array() >=\n    //     m_sigma_2)\n    //                .template cast<bool>();\n\n    //     unsigned count = comp.count();\n    //     Matrix<double, dimension, Dynamic> p_components(dimension, count);\n    //     VectorXd eigenvals(count);\n\n    //     {\n    //         unsigned cnt = 0;\n    //         for (unsigned i = 0; i != dimension; ++i) {\n    //             if (comp(i)) {\n    //                 p_components.col(cnt) =\n    //                 eigens.eigenvectors().col(i); eigenvals(cnt) =\n    //                 eigens.eigenvalues()(i);\n    //                 ++cnt;\n    //             }\n    //         }\n    //     }\n    //     local_cov =\n    //         p_components * eigenvals.asDiagonal() * p_components.transpose()\n    //         + MatrixXd::Identity(dimension, dimension) * m_sigma_2;\n    // }\n\n    SelfAdjointEigenSolver<Matrix<double, dimension, dimension>> eigens(\n        local_cov);\n    double determinant_sqrt = std::sqrt(std::abs(eigens.eigenvalues().prod()));\n    double threshold = 1;\n    Matrix<double, dimension, dimension> cov_inv =\n        eigens.eigenvectors() *\n        eigens.eigenvalues().array().inverse().matrix().asDiagonal() *\n        eigens.eigenvectors().transpose();\n    if (neighbour_cnt) {\n        for (auto edge : *iter) {\n            NodeVector &node_vec = m_graph[edge.head].value().vector;\n            double prob = std::exp(-((x_vector - node_vec).transpose() *\n                                     cov_inv * (x_vector - node_vec))(0) /\n                                   2) /\n                          m_const_coeff / determinant_sqrt;\n\n            if (prob < threshold)\n                threshold = prob;\n        }\n    } else\n        threshold = 0.55;\n\n    double xprob = std::exp(-((x_vector - winner_vec).transpose() * cov_inv *\n                              (x_vector - winner_vec))(0) /\n                            2) /\n                   m_const_coeff / determinant_sqrt;\n    return {\n        threshold,\n        xprob,\n    };\n}\ntemplate <unsigned dimension> double GPNet<dimension>::predict(array &data) {\n    using namespace Eigen;\n\n    Map<NodeVector> input(data.data());\n\n    double prob = 0;\n    size_t wins = 0;\n    for (auto &node : m_graph) {\n        Matrix<double, dimension, dimension> local_cov;\n        local_cov.setZero();\n        size_t win_sum = 0;\n        for (auto edge : node) {\n            NodeVector &edge_vec = m_graph[edge.head].value().vector;\n            NodeVector &node_vec = node.value().vector;\n            local_cov.array() +=\n                ((edge_vec - node_vec) * (edge_vec - node_vec).transpose())\n                    .array() *\n                edge.weight;\n            win_sum += edge.weight;\n        }\n        if (win_sum)\n            local_cov.array() /= win_sum;\n        local_cov += MatrixXd::Identity(dimension, dimension) * m_sigma_2;\n\n        SelfAdjointEigenSolver<Matrix<double, dimension, dimension>> eigens(\n            local_cov);\n        double determinant_sqrt = std::sqrt(eigens.eigenvalues().prod());\n        Matrix<double, dimension, dimension> cov_inv =\n            eigens.eigenvectors() *\n            eigens.eigenvalues().array().inverse().matrix().asDiagonal() *\n            eigens.eigenvectors().transpose();\n\n        NodeVector &node_vec = node.value().vector;\n        double xprob = std::exp(-((input - node_vec).transpose() * cov_inv *\n                                  (input - node_vec))(0) /\n                                2) /\n                       m_const_coeff / determinant_sqrt;\n        prob += xprob * node.value().win_count;\n        wins += node.value().win_count;\n    }\n\n    if (wins)\n        prob /= wins;\n    return prob;\n}\n\n// specialization\ntemplate <> class GPNet<0> {\n  public:\n    typedef Eigen::Matrix<double, Eigen::Dynamic, 1> NodeVector;\n    struct Node {\n        NodeVector vector;\n        size_t win_count;\n    };\n\n  private:\n    typedef std::vector<double> vector_d;\n    typedef UndirectedGraph<Node, unsigned, std::less<NodeVector>,\n                            Eigen::aligned_allocator<NodeVector>>\n        UGraph;\n\n  public:\n    GPNet(unsigned dimension = 1, unsigned lambda = 20000,\n          unsigned age_max = 50, unsigned k = 1, double sigma_2 = 1e-6);\n    ~GPNet() {}\n\n    void train(vector_d &data);\n    double predict(vector_d &data);\n\n  private:\n    UGraph m_graph;\n    double m_sigma_2;\n    unsigned m_local_opt_coeff = 100;\n    unsigned m_age_max;\n    unsigned m_lambda;\n    unsigned m_k;\n    unsigned m_cycles = 0;\n    double m_const_coeff;\n    unsigned m_dimension;\n\n    std::pair<double, double> threshold(size_t index,\n                                        const NodeVector &x_vector);\n}; // class GPNet\n\nGPNet<0>::GPNet(unsigned dimension, unsigned lambda, unsigned age_max,\n                unsigned k, double sigma_2)\n    : m_lambda(lambda), m_age_max(age_max), m_k(k), m_sigma_2(sigma_2),\n      m_const_coeff(std::sqrt(std::pow(2 * M_PI, dimension))),\n      m_dimension(dimension) {\n    m_graph.insert_vertex(\n        Node{.vector = NodeVector::Random(m_dimension, 1), .win_count = 0});\n    m_graph.insert_vertex(\n        Node{.vector = NodeVector::Random(m_dimension, 1), .win_count = 0});\n}\n\nvoid GPNet<0>::train(vector_d &data) {\n    using namespace Eigen;\n    using NodeM = Matrix<double, Dynamic, Dynamic>;\n\n    if (m_graph.vertex_count() < 2) {\n        m_graph.insert_vertex(\n            Node{.vector = NodeVector::Random(m_dimension, 1), .win_count = 0});\n        m_graph.insert_vertex(\n            Node{.vector = NodeVector::Random(m_dimension, 1), .win_count = 0});\n    }\n    std::random_device rand_dev;\n    std::srand(rand_dev());\n\n    typename NodeM::Index min_index, min2_index;\n    Map<NodeVector> input(data.data(), m_dimension);\n\n    {\n        // construct the data matrix\n        NodeM nodes(m_dimension, m_graph.vertex_count());\n\n        size_t col = 0;\n        for (auto &node : m_graph) {\n            nodes.col(col) = node.value().vector;\n            ++col;\n        }\n\n        // find the winner and the second winner\n        RowVectorXd distances =\n            (nodes.colwise() - input).colwise().squaredNorm();\n        distances.minCoeff(&min_index);\n\n        if (min_index == 0) {\n            distances(0) = distances(1);\n            distances.minCoeff(&min2_index);\n            if (min2_index == 0)\n                min2_index = 1;\n        } else {\n            distances(min_index) = distances(min_index - 1);\n            distances.minCoeff(&min2_index);\n            if (min2_index == min_index)\n                ++min2_index;\n        }\n    }\n\n    auto min_iter = m_graph.begin();\n    auto min2_iter = m_graph.begin();\n    for (size_t i = 0; i != min_index; ++i)\n        ++min_iter;\n    for (size_t i = 0; i != min2_index; ++i)\n        ++min2_iter;\n\n    auto[threshold1, prob1] = threshold(min_index, input);\n    auto[threshold2, prob2] = threshold(min2_index, input);\n\n    if ((prob1 > prob2 && prob1 > threshold1) || prob2 > threshold2) {\n        m_graph.insert_edge(min_iter, min2_iter, 0);\n\n        auto &win_count = min_iter->value().win_count;\n        NodeVector &winner_vec = min_iter->value().vector;\n        ++win_count;\n        winner_vec.array() += ((input - winner_vec).array() / (win_count + 1));\n\n        for (auto &edge : *min_iter) {\n            NodeVector &node_vec = m_graph[edge.head].value().vector;\n            node_vec.array() += ((input - node_vec).array() /\n                                 m_local_opt_coeff / (win_count + 1));\n            ++edge.weight;\n        }\n\n        for (auto niter = m_graph.cbegin(); niter != m_graph.cend(); ++niter) {\n            for (auto edge = niter->cbegin(), pre = niter->cbefore_begin();\n                 edge != niter->cend();) {\n                if (edge->weight > m_age_max) {\n                    edge = m_graph.erase_after_edge(niter, pre);\n                } else {\n                    ++edge;\n                    ++pre;\n                }\n            }\n        }\n    } else {\n        m_graph.insert_vertex(Node{.vector = input, .win_count = 0});\n    }\n\n    ++m_cycles;\n    if (m_cycles == m_lambda) {\n        m_cycles = 0;\n        for (auto iter = m_graph.cbegin(); iter != m_graph.cend();) {\n            if (std::distance(iter->cbegin(), iter->cend()) < m_k)\n                iter = m_graph.erase_vertex(iter);\n            else\n                ++iter;\n        }\n    }\n} // namespace GPSOINN\n\nstd::pair<double, double> GPNet<0>::threshold(size_t index,\n                                              const NodeVector &x_vector) {\n    using namespace Eigen;\n\n    Matrix<double, Dynamic, Dynamic> local_cov(m_dimension, m_dimension);\n    local_cov.setZero();\n    auto iter = m_graph.begin();\n    for (size_t i = 0; i != index; ++i)\n        ++iter;\n\n    NodeVector &winner_vec = iter->value().vector;\n    size_t win_sum = 0;\n    size_t neighbour_cnt = 0;\n    for (auto edge : *iter) {\n        NodeVector &node_vec = m_graph[edge.head].value().vector;\n        local_cov.array() +=\n            ((node_vec - winner_vec) * (node_vec - winner_vec).transpose())\n                .array() *\n            edge.weight;\n        win_sum += edge.weight;\n        ++neighbour_cnt;\n    }\n    if (win_sum)\n        local_cov.array() /= win_sum;\n    local_cov += MatrixXd::Identity(m_dimension, m_dimension) * m_sigma_2;\n\n    // if (neighbour_cnt > m_dimension) {\n    //     Matrix<bool, Dynamic, 1> comp(m_dimension, 1);\n    //     SelfAdjointEigenSolver<Matrix<double, Dynamic, Dynamic>>\n    //     eigens(local_cov);\n    //     comp = ((eigens.eigenvalues()).array() >=\n    //     m_sigma_2)\n    //                .template cast<bool>();\n\n    //     unsigned count = comp.count();\n    //     Matrix<double, Dynamic, Dynamic> p_components(m_dimension, count);\n    //     VectorXd eigenvals(count);\n\n    //     {\n    //         unsigned cnt = 0;\n    //         for (unsigned i = 0; i != m_dimension; ++i) {\n    //             if (comp(i)) {\n    //                 p_components.col(cnt) =\n    //                 eigens.eigenvectors().col(i); eigenvals(cnt) =\n    //                 eigens.eigenvalues()(i);\n    //                 ++cnt;\n    //             }\n    //         }\n    //     }\n    //     local_cov =\n    //         p_components * eigenvals.asDiagonal() * p_components.transpose()\n    //         + MatrixXd::Identity(m_dimension, m_dimension) * m_sigma_2;\n    // }\n\n    SelfAdjointEigenSolver<Matrix<double, Dynamic, Dynamic>> eigens(local_cov);\n    double determinant_sqrt = std::sqrt(eigens.eigenvalues().prod());\n    double threshold = 1;\n    Matrix<double, Dynamic, Dynamic> cov_inv =\n        eigens.eigenvectors() *\n        eigens.eigenvalues().array().inverse().matrix().asDiagonal() *\n        eigens.eigenvectors().transpose();\n    if (neighbour_cnt) {\n        for (auto edge : *iter) {\n            NodeVector &node_vec = m_graph[edge.head].value().vector;\n            double prob = std::exp(-((x_vector - node_vec).transpose() *\n                                     cov_inv * (x_vector - node_vec))(0) /\n                                   2) /\n                          m_const_coeff / determinant_sqrt;\n\n            if (prob < threshold)\n                threshold = prob;\n        }\n    } else\n        threshold = 0.55;\n\n    double xprob = std::exp(-((x_vector - winner_vec).transpose() * cov_inv *\n                              (x_vector - winner_vec))(0) /\n                            2) /\n                   m_const_coeff / determinant_sqrt;\n    return {\n        threshold,\n        xprob,\n    };\n}\ndouble GPNet<0>::predict(vector_d &data) {\n    using namespace Eigen;\n\n    Map<NodeVector> input(data.data(), m_dimension);\n\n    double prob = 0;\n    size_t wins = 0;\n    for (auto &node : m_graph) {\n        Matrix<double, Dynamic, Dynamic> local_cov(m_dimension, m_dimension);\n        local_cov.setZero();\n        size_t win_sum = 0;\n        for (auto edge : node) {\n            NodeVector &edge_vec = m_graph[edge.head].value().vector;\n            NodeVector &node_vec = node.value().vector;\n            local_cov.array() +=\n                ((edge_vec - node_vec) * (edge_vec - node_vec).transpose())\n                    .array() *\n                edge.weight;\n            win_sum += edge.weight;\n        }\n        if (win_sum)\n            local_cov.array() /= win_sum;\n        local_cov += MatrixXd::Identity(m_dimension, m_dimension) * m_sigma_2;\n\n        SelfAdjointEigenSolver<Matrix<double, Dynamic, Dynamic>> eigens(\n            local_cov);\n        double determinant_sqrt =\n            std::sqrt(std::abs(eigens.eigenvalues().prod()));\n        Matrix<double, Dynamic, Dynamic> cov_inv =\n            eigens.eigenvectors() *\n            eigens.eigenvalues().array().inverse().matrix().asDiagonal() *\n            eigens.eigenvectors().transpose();\n\n        NodeVector &node_vec = node.value().vector;\n        double xprob = std::exp(-((input - node_vec).transpose() * cov_inv *\n                                  (input - node_vec))(0) /\n                                2) /\n                       m_const_coeff / determinant_sqrt;\n        prob += xprob * node.value().win_count;\n        wins += node.value().win_count;\n    }\n\n    if (wins)\n        prob /= wins;\n    return prob;\n}\n} // namespace GPSOINN\n\n#endif // GPSOINN_HXX\n", "meta": {"hexsha": "15bb83e9e5f2e74e0207380f2f6b1aca085b0dc2", "size": 19091, "ext": "hxx", "lang": "C++", "max_stars_repo_path": "gpsoinn.hxx", "max_stars_repo_name": "kylerky/gpsoinn", "max_stars_repo_head_hexsha": "badf74581f800d26077443a0d6d57bb6db52bb65", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "gpsoinn.hxx", "max_issues_repo_name": "kylerky/gpsoinn", "max_issues_repo_head_hexsha": "badf74581f800d26077443a0d6d57bb6db52bb65", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "gpsoinn.hxx", "max_forks_repo_name": "kylerky/gpsoinn", "max_forks_repo_head_hexsha": "badf74581f800d26077443a0d6d57bb6db52bb65", "max_forks_repo_licenses": ["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.610915493, "max_line_length": 80, "alphanum_fraction": 0.5481116757, "num_tokens": 4642, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6926419704455589, "lm_q2_score": 0.4960938294709195, "lm_q1q2_score": 0.34361540757062076}}
{"text": "#include <iostream>\n#include <vector>\n#include <deque>\n#include <typeinfo>\n#include <set>\n#include <cstdlib>\n// -------------------- OpenMesh\n#include <OpenMesh/Core/IO/MeshIO.hh>\n#include <OpenMesh/Core/Mesh/PolyMesh_ArrayKernelT.hh>\n#include <OpenMesh/Core/Mesh/PolyMeshT.hh>\n#include <imgui/imgui.h>\n#include <igl/opengl/glfw/imgui/ImGuiMenu.h>\n#include <igl/opengl/glfw/imgui/ImGuiHelpers.h>\n#include <igl/avg_edge_length.h>\n#include <igl/gaussian_curvature.h>\n#include <igl/principal_curvature.h>\n#include <igl/massmatrix.h>\n#include <igl/invert_diag.h>\n#include <igl/readOFF.h>\n#include <igl/opengl/glfw/Viewer.h>\n#include <igl/jet.h>\n#include <igl/pinv.h>\n#include <Eigen/Eigenvalues>\n#include <Eigen/QR>\n#include <string>\n#include <iostream>\n\n\nusing namespace Eigen;\nusing namespace std;\n\n// ----------------------------------------------------------------------------\ntypedef OpenMesh::PolyMesh_ArrayKernelT<> _Mesh;\ntypedef OpenMesh::Vec3d v3d_t;\ntypedef vector<v3d_t> vv3d_t;\n// ----------------------------------------------------------------------------\n// Build a simple cube and write it to std::cout\nbool is_visible = false;\nbool is_visible_offset = false;\nbool is_visible_vert = false;\n\nvoid view_f_normals(_Mesh mesh_in, MatrixXd PD, MatrixXd f_centers) {\n    mesh_in.triangulate();\n    MatrixXd V;\n    MatrixXi F;\n\n    V.resize(mesh_in.n_vertices(), 3);\n    F.resize(mesh_in.n_faces(), 3);\n\n    for (size_t i = 0; i < mesh_in.n_vertices(); ++i) {\n        auto p = mesh_in.point(mesh_in.vertex_handle(i));\n        V(i, 0) = p[0];\n        V(i, 1) = p[1];\n        V(i, 2) = p[2];\n    }\n\n    for (size_t i = 0; i < mesh_in.n_faces(); ++i) {\n        auto fh = mesh_in.face_handle(i);\n        int vi = 0;\n        for (_Mesh::ConstFaceVertexCCWIter fvi = mesh_in.cfv_ccwbegin(fh); fvi != mesh_in.cfv_ccwend(fh); ++fvi) {\n//            cout << vi << \" \" << endl;\n            F(i, vi) = fvi->idx();\n            vi++;\n        }\n//        cout << endl;\n    }\n\n    // Plot the mesh_in with pseudocolors\n    igl::opengl::glfw::Viewer viewer;\n    igl::opengl::glfw::imgui::ImGuiMenu menu;\n    viewer.plugins.push_back(&menu);\n    // Customize the menu\n    double doubleVariable = 0.1f; // Shared between two menus\n    // Add content to the default menu windowOh\n    menu.callback_draw_viewer_menu = [&]() {\n        // Draw parent menu content\n        menu.draw_viewer_menu();\n\n        // Add new group\n        if (ImGui::CollapsingHeader(\"New Group\", ImGuiTreeNodeFlags_DefaultOpen)) {\n            // Expose variable directly ...\n            ImGui::InputDouble(\"double\", &doubleVariable, 0, 0, \"%.4f\");\n\n            // ... or using a custom callback\n            static bool boolVariable = true;\n            if (ImGui::Checkbox(\"bool\", &boolVariable)) {\n                // do something\n                cout << \"boolVariable: \" << boolalpha << boolVariable << endl;\n            }\n\n            // Expose an enumeration type\n            enum Orientation {\n                Up = 0, Down, Left, Right\n            };\n            static Orientation dir = Up;\n            ImGui::Combo(\"Direction\", (int *) (&dir), \"Up\\0Down\\0Left\\0Right\\0\\0\");\n\n            // We can also use a vector<string> defined dynamically\n            static int num_choices = 3;\n            static vector<string> choices;\n            static int idx_choice = 0;\n            if (ImGui::InputInt(\"Num letters\", &num_choices)) {\n                num_choices = max(1, min(26, num_choices));\n            }\n            if (num_choices != (int) choices.size()) {\n                choices.resize(num_choices);\n                for (int i = 0; i < num_choices; ++i)\n                    choices[i] = string(1, 'A' + i);\n                if (idx_choice >= num_choices)\n                    idx_choice = num_choices - 1;\n            }\n            ImGui::Combo(\"Letter\", &idx_choice, choices);\n\n            // Add a button\n            if (ImGui::Button(\"Print Hello\", ImVec2(-1, 0))) {\n                cout << \"Hello\\n\";\n            }\n        }\n    };\n\n    viewer.data(0).set_mesh(V, F);\n\n    // for showing the direction of normals.\n    const RowVector3d red(0.8, 0.2, 0.2);\n    const RowVector3d blue(0.2, 0.4, 0.87);\n    // Average edge length for sizing\n    const double avg = igl::avg_edge_length(V, F);\n    cout << avg << \"the avg is \" << endl;  //testing the length\n\n    viewer.data(0).add_edges(f_centers + PD * avg, f_centers - PD * avg, red);\n    viewer.launch();\n}\n\nvoid view_v_normal(_Mesh mesh_in, MatrixXd PD) {\n    mesh_in.triangulate();\n    MatrixXd V;\n    MatrixXi F;\n\n    V.resize(mesh_in.n_vertices(), 3);\n    F.resize(mesh_in.n_faces(), 3);\n\n    for (size_t i = 0; i < mesh_in.n_vertices(); ++i) {\n        auto p = mesh_in.point(mesh_in.vertex_handle(i));\n        V(i, 0) = p[0];\n        V(i, 1) = p[1];\n        V(i, 2) = p[2];\n    }\n\n    for (size_t i = 0; i < mesh_in.n_faces(); ++i) {\n        auto fh = mesh_in.face_handle(i);\n        int vi = 0;\n        for (_Mesh::ConstFaceVertexCCWIter fvi = mesh_in.cfv_ccwbegin(fh); fvi != mesh_in.cfv_ccwend(fh); ++fvi) {\n            F(i, vi) = fvi->idx();\n            vi++;\n        }\n    }\n\n    // Plot the mesh_in with pseudocolors\n    igl::opengl::glfw::Viewer viewer;\n    igl::opengl::glfw::imgui::ImGuiMenu menu;\n    viewer.plugins.push_back(&menu);\n    // Customize the menu\n    double doubleVariable = 0.1f; // Shared between two menus\n    // Add content to the default menu windowOh\n    menu.callback_draw_viewer_menu = [&]() {\n        // Draw parent menu content\n        menu.draw_viewer_menu();\n\n        // Add new group\n        if (ImGui::CollapsingHeader(\"New Group\", ImGuiTreeNodeFlags_DefaultOpen)) {\n            // Expose variable directly ...\n            ImGui::InputDouble(\"double\", &doubleVariable, 0, 0, \"%.4f\");\n\n            // ... or using a custom callback\n            static bool boolVariable = true;\n            if (ImGui::Checkbox(\"bool\", &boolVariable)) {\n                // do something\n                cout << \"boolVariable: \" << boolalpha << boolVariable << endl;\n            }\n\n            // Expose an enumeration type\n            enum Orientation {\n                Up = 0, Down, Left, Right\n            };\n            static Orientation dir = Up;\n            ImGui::Combo(\"Direction\", (int *) (&dir), \"Up\\0Down\\0Left\\0Right\\0\\0\");\n\n            // We can also use a vector<string> defined dynamically\n            static int num_choices = 3;\n            static vector<string> choices;\n            static int idx_choice = 0;\n            if (ImGui::InputInt(\"Num letters\", &num_choices)) {\n                num_choices = max(1, min(26, num_choices));\n            }\n            if (num_choices != (int) choices.size()) {\n                choices.resize(num_choices);\n                for (int i = 0; i < num_choices; ++i)\n                    choices[i] = string(1, 'A' + i);\n                if (idx_choice >= num_choices)\n                    idx_choice = num_choices - 1;\n            }\n            ImGui::Combo(\"Letter\", &idx_choice, choices);\n\n            // Add a button\n            if (ImGui::Button(\"Print Hello\", ImVec2(-1, 0))) {\n                cout << \"Hello\\n\";\n            }\n        }\n    };\n\n    viewer.data(0).set_mesh(V, F);\n\n    // for showing the direction of normals.\n    const RowVector3d red(0.8, 0.2, 0.2);\n    const RowVector3d blue(0.2, 0.4, 0.87);\n    // Average edge length for sizing\n    const double avg = igl::avg_edge_length(V, F);\n    cout << avg << \"the avg is \" << endl;  //testing the length\n\n    viewer.data(0).add_edges(V + PD * avg, V - PD * avg, red);\n    viewer.launch();\n}\n\nvoid triangle(_Mesh mesh_in, MatrixXi *F) {\n    F->resize(mesh_in.n_faces() * 2, 3);\n\n    int count = 0;\n    int fcount = 0;\n    for (auto f_it = mesh_in.faces_begin(); f_it != mesh_in.faces_end(); f_it++) { // face\n        int vidx = 0;\n        int first=0;\n        int second=0;\n        for (auto fh_it = mesh_in.fv_iter(*f_it); fh_it.is_valid(); ++fh_it) {\n            if(vidx != 3)\n            {\n                (F->row(f_it->idx()*2))(first) = fh_it->idx();\n                first++;\n            }\n\n\n            if(vidx != 1) {\n                (F->row(f_it->idx()*2+1))(second) = fh_it->idx();\n                second++;\n            }\n            vidx++;\n        }\n        fcount += 2;\n    }\n}\n\n//void black_rec(_Mesh mesh_in, MatrixXd *V, MatrixXi *F) {\n//    V->resize(mesh_in.n_vertices(), 3);\n//    F->resize(mesh_in.n_faces() * 2, 3);\n//\n//    int count = 0;\n//    int fcount = 0;\n//    for (auto f_it = mesh_in.faces_begin(); f_it != mesh_in.faces_end(); f_it++) { // face\n//        int vidx = 0;\n//        int first=0;\n//        int second=0;\n//        for (auto fh_it = mesh_in.fh_iter(*f_it); fh_it.is_valid(); ++fh_it) {\n//            auto vert_idx = (mesh_in.to_vertex_handle(*fh_it)).idx();\n//            (*V)(vert_idx, 0) = ((mesh_in.point(mesh_in.to_vertex_handle(*fh_it)))[0] +\n//                              (mesh_in.point(mesh_in.from_vertex_handle(*fh_it)))[0]) / 2;\n//            (*V)(vert_idx, 1) = ((mesh_in.point(mesh_in.to_vertex_handle(*fh_it)))[1] +\n//                              (mesh_in.point(mesh_in.from_vertex_handle(*fh_it)))[1]) / 2;\n//            (*V)(vert_idx, 2) = ((mesh_in.point(mesh_in.to_vertex_handle(*fh_it)))[2] +\n//                              (mesh_in.point(mesh_in.from_vertex_handle(*fh_it)))[2]) / 2;\n//            count++;\n//\n//            if(vidx != 3)\n//            {\n//                (F->row(fcount))(first) = vert_idx;\n//                first++;\n//            }\n//\n//\n//            if(vidx != 1) {\n//                (F->row(fcount+1))(second) = vert_idx;\n//                second++;\n//            }\n//            vidx++;\n//        }\n//        fcount += 2;\n//    }\n//}\n\n\nvoid black_rec(_Mesh mesh_in, MatrixXd *V, MatrixXi *F) {\n    V->resize(mesh_in.n_faces() * 4, 3);\n    F->resize(mesh_in.n_faces() * 2, 3);\n\n    int count = 0;\n    int fcount = 0;\n    for (auto f_it = mesh_in.faces_begin(); f_it != mesh_in.faces_end(); f_it++) { // face\n        for (auto fh_it = mesh_in.fh_iter(*f_it); fh_it.is_valid(); ++fh_it) {\n            (*V)(count, 0) = ((mesh_in.point(mesh_in.to_vertex_handle(*fh_it)))[0] +\n                              (mesh_in.point(mesh_in.from_vertex_handle(*fh_it)))[0]) / 2;\n            (*V)(count, 1) = ((mesh_in.point(mesh_in.to_vertex_handle(*fh_it)))[1] +\n                              (mesh_in.point(mesh_in.from_vertex_handle(*fh_it)))[1]) / 2;\n            (*V)(count, 2) = ((mesh_in.point(mesh_in.to_vertex_handle(*fh_it)))[2] +\n                              (mesh_in.point(mesh_in.from_vertex_handle(*fh_it)))[2]) / 2;\n            count++;\n        }\n        auto idx_base = fcount * 2;\n        F->row(fcount) << idx_base, idx_base + 1, idx_base + 2;\n        F->row(++fcount) << idx_base, idx_base + 2, idx_base + 3;\n        fcount++;\n    }\n}\n\nvoid offset_black_rec(_Mesh mesh_in, MatrixXd f_normals, MatrixXd *V, MatrixXi *F) {\n    V->resize(mesh_in.n_faces() * 4, 3);\n    F->resize(mesh_in.n_faces() * 2, 3);\n\n    int count = 0;\n    int fcount = 0;\n    for (auto f_it = mesh_in.faces_begin(); f_it != mesh_in.faces_end(); f_it++) { // face\n        for (auto fh_it = mesh_in.fh_iter(*f_it); fh_it.is_valid(); ++fh_it) {\n            (*V)(count, 0) = ((mesh_in.point(mesh_in.to_vertex_handle(*fh_it)))[0] +\n                              (mesh_in.point(mesh_in.from_vertex_handle(*fh_it)))[0]) / 2 +\n                             f_normals.row(f_it->idx())[0];\n            (*V)(count, 1) = ((mesh_in.point(mesh_in.to_vertex_handle(*fh_it)))[1] +\n                              (mesh_in.point(mesh_in.from_vertex_handle(*fh_it)))[1]) / 2 +\n                             f_normals.row(f_it->idx())[1];\n            (*V)(count, 2) = ((mesh_in.point(mesh_in.to_vertex_handle(*fh_it)))[2] +\n                              (mesh_in.point(mesh_in.from_vertex_handle(*fh_it)))[2]) / 2 +\n                             f_normals.row(f_it->idx())[2];\n            count++;\n        }\n        auto idx_base = fcount * 2;\n        F->row(fcount) << idx_base, idx_base + 1, idx_base + 2;\n        F->row(++fcount) << idx_base, idx_base + 2, idx_base + 3;\n        fcount++;\n    }\n}\n\nvoid offset_black_v_normals(MatrixXd Vorig, MatrixXi Forig, MatrixXd v_normals, MatrixXd *V, MatrixXi *F) {\n    V->resize(Vorig.rows(), 3);\n    F->resize(Forig.rows(), 3);\n\n    *V = Vorig - v_normals;\n    *F = Forig;\n}\n\n// mesh_in, init_v_normals, v_normals, f_centers, f_normals, v_normals, gaussian_curvatures, mean_curvatures\nvoid view_total_info(_Mesh mesh_in, MatrixXd init_v_normals, MatrixXd v_normals, MatrixXd f_centers,\n                     MatrixXd f_normals, MatrixXd gaussian_curvatures, MatrixXd mean_curvatures,\n                     MatrixXd pc1, MatrixXd pc2) {\n    igl::opengl::glfw::Viewer viewer;\n    viewer.data().line_width = 4.0; //line width\n\n    // for showing the direction of normals.\n    const RowVector3d red(0.8, 0.2, 0.2);\n    const RowVector3d blue(0, 1, 0);\n    const RowVector3d black(0, 0, 0);\n    MatrixXd to_vert, from_vert;\n    to_vert.resize(mesh_in.n_vertices() * 4, 3);\n    from_vert.resize(mesh_in.n_vertices() * 4, 3);\n\n    // for offsetting the faces and balck rec\n    MatrixXd Vinner, Voffset, Vvert;\n    MatrixXi Finner, Foffset, Fvert;\n    black_rec(mesh_in, &Vinner, &Finner);\n    offset_black_rec(mesh_in, f_normals, &Voffset, &Foffset);\n\n    // for showing quad mesh\n    MatrixXi F;\n    triangle(mesh_in, &F);\n//    mesh_in.triangulate();\n    MatrixXd V;\n//    MatrixXi F;\n    V.resize(mesh_in.n_vertices(), 3);\n//    F.resize(mesh_in.n_faces(), 3);\n\n    for (size_t i = 0; i < mesh_in.n_vertices(); ++i) {\n        auto p = mesh_in.point(mesh_in.vertex_handle(i));\n        V(i, 0) = p[0];\n        V(i, 1) = p[1];\n        V(i, 2) = p[2];\n    }\n\n\n    // offset\n    offset_black_v_normals(V, F, v_normals, &Vvert, &Fvert);\n\n    // Plot the mesh_in with pseudocolors\n    // Average edge length for sizing\n    const double avg = igl::avg_edge_length(V, F);\n//    cout << avg << \"the avg is \" << endl;  //testing the length\n\n    // set mesh and add edges. multi-layer drawing,\n    // by concealing the trangle mesh (cancle the wireframe) we will show the the quad mesh in the higher layer\n    // show everything we have step by step by pressing different keys\n    // default. initial v_normal and optimized v_normal\n    // 1. show black midpoint division\n    // 2. show face normals.\n    // 3. show offset faces.\n    // 4. curvatures of face guassian\n    // 5. mean curvatures.\n\n    viewer.data(0).set_mesh(V, F);\n//    viewer.data(0).add_edges(from_vert, to_vert, black);\n    viewer.data(0).add_edges(V, V - init_v_normals * avg, red);\n    viewer.data(0).add_edges(V, V - v_normals * avg, blue);\n    viewer.append_mesh(false);\n    viewer.append_mesh(false);\n    viewer.append_mesh(false);\n    viewer.append_mesh(false);\n    viewer.append_mesh(false);\n    viewer.append_mesh(false);\n\n    // cout<< \"vinner\"<<Vinner <<endl<< \"Finner\"<<Finner<<endl;  // bebuging\n    viewer.data_list[1].set_mesh(Vinner, Finner);  // show black\n//    viewer.data_list[2].set_mesh(Voffset, Foffset);\n    viewer.data_list[2].set_mesh(V, F);\n    viewer.data_list[2].add_edges(f_centers + f_normals * avg, f_centers - f_normals * avg, black);\n    viewer.data_list[3].set_mesh(Vvert, Fvert);\n\n    viewer.data_list[4].set_mesh(V, F);\n    MatrixXd C;\n    igl::jet(gaussian_curvatures, true, C);\n//    cout<<\"\\n---------\"<<\"C size is \"<< C.size() << \"mesh\"<<mesh_in.n_vertices()<<\"\\n\"<<C<<endl;\n    viewer.data_list[4].set_colors(C);\n    // cout << \"Vertex size, \" << V.rows() << \"Face size, : \" << F.rows() << endl;\n    // cout << \"COlor size << \" <<  gaussian_curvatures.rows() << \"x\" << gaussian_curvatures.cols() << endl;\n\n    viewer.data_list[5].set_mesh(V, F);\n    MatrixXd mean_cur_color;\n    igl::jet(mean_curvatures, true, mean_cur_color);\n    viewer.data_list[5].set_colors(mean_cur_color);\n\n    viewer.data_list[6].set_mesh(V, F);\n    viewer.data_list[6].add_edges(f_centers + 1.2*pc1 * avg, f_centers - 1.2*pc1 * avg, red);\n    viewer.data_list[6].add_edges(f_centers + 1.2*pc2 * avg, f_centers - 1.2*pc2 * avg, blue);\n    viewer.data(6).line_width = 3.0; //line width\n\n    viewer.selected_data_index = 0;\n    viewer.callback_key_down =\n            [&](igl::opengl::glfw::Viewer &, unsigned int key, int mod) {\n                if (key == GLFW_KEY_0) {\n                    cout << \"got 0\" << endl;\n                    viewer.data(1).set_visible(false);\n                    viewer.data(2).set_visible(false);\n                    viewer.data(3).set_visible(false);\n                    viewer.data(4).set_visible(false);\n                    viewer.data(5).set_visible(false);\n                    viewer.data(0).set_visible(true);\n                    return true;\n                }\n\n                if (key == GLFW_KEY_1) {\n                    cout << \"got 1\" << endl;\n                    int old_id = viewer.data().id;\n                    cout << old_id << endl;\n                    cout << \"selected idx \" << viewer.selected_data_index << endl;\n                    viewer.selected_data_index = 1;\n                    viewer.data_list[viewer.selected_data_index].set_colors(RowVector3d(0.1, 0.1, 0.9));\n                    is_visible = !is_visible;\n                    viewer.data(viewer.selected_data_index).set_visible(is_visible);\n                    return true;\n                }\n                else if (key == GLFW_KEY_SPACE)\n                {\n                    viewer.selected_data_index = (viewer.selected_data_index+1) %6;\n                    return true;\n                }\n                else if (key == GLFW_KEY_ENTER)\n                {\n                    is_visible = !is_visible;\n                    viewer.data(0).set_visible(is_visible);\n                    return true;\n                }\n\n                else if (key == GLFW_KEY_2) {\n                    cout << \"got enter\" << endl;\n                    is_visible_offset = !is_visible_offset;\n                    viewer.data(2).set_visible(!is_visible_offset);\n                    viewer.data(0).set_visible(false);\n                    return true;\n                } else if (key == GLFW_KEY_3) {\n                    // close 1\n                    viewer.selected_data_index = 0;\n                    viewer.data(viewer.selected_data_index).set_visible(true);\n\n                    cout << \"got 3\" << endl;\n                    int old_id = viewer.data().id;\n                    cout << old_id << endl;\n                    cout << \"selected idx \" << viewer.selected_data_index << endl;\n\n                    viewer.selected_data_index = 3;\n                    viewer.data_list[viewer.selected_data_index].set_colors(RowVector3d(0.8, 0.5, 0.9));\n                    is_visible_vert = !is_visible_vert;\n                    viewer.data(viewer.selected_data_index).set_visible(is_visible_vert);\n                    return true;\n                } else if (key == GLFW_KEY_4) {\n                    cout << \"got 4\" << endl;\n                    int old_id = viewer.data().id;\n                    cout << old_id << endl;\n                    cout << \"selected idx \" << viewer.selected_data_index << endl;\n                    viewer.selected_data_index = 4;\n                    is_visible_offset = !is_visible_offset;\n                    viewer.data(viewer.selected_data_index).set_visible(!is_visible_offset);\n\n                    // close 0\n                    viewer.selected_data_index = 0;\n                    viewer.data(viewer.selected_data_index).set_visible(false);\n                    return true;\n                } else if (key == GLFW_KEY_5) {\n                    cout << \"got 5\" << endl;\n                    viewer.selected_data_index = 5;\n                    is_visible_offset = !is_visible_offset;\n                    viewer.data(viewer.selected_data_index).set_visible(!is_visible_offset);\n\n                    // close 0\n                    viewer.selected_data_index = 0;\n                    viewer.data(viewer.selected_data_index).set_visible(false);\n                    return true;\n                }\n                else if (key == GLFW_KEY_6) {\n                    cout << \"got 6\" << endl;\n                    viewer.selected_data_index = 6;\n                    is_visible_offset = !is_visible_offset;\n                    viewer.data(viewer.selected_data_index).set_visible(!is_visible_offset);\n\n                    // close 0\n                    viewer.selected_data_index = 0;\n                    viewer.data(viewer.selected_data_index).set_visible(false);\n                    return true;\n\n                }\n                return false;\n            };\n\n    igl::opengl::glfw::imgui::ImGuiMenu menu;\n    viewer.plugins.push_back(&menu);\n    // Customize the menu\n    double doubleVariable = 0.1f; // Shared between two menus\n    // Add content to the default menu windowOh\n    menu.callback_draw_viewer_menu = [&]() {\n        // Draw parent menu content\n        menu.draw_viewer_menu();\n        // Add new group\n        if (ImGui::CollapsingHeader(\"New Group\", ImGuiTreeNodeFlags_DefaultOpen)) {\n            // Expose variable directly ...\n            ImGui::InputDouble(\"double\", &doubleVariable, 0, 0, \"%.4f\");\n\n            // ... or using a custom callback\n            static bool boolVariable = true;\n            if (ImGui::Checkbox(\"bool\", &boolVariable)) {\n                // do something\n                cout << \"boolVariable: \" << boolalpha << boolVariable << endl;\n            }\n\n            // Expose an enumeration type\n            enum Orientation {\n                Up = 0, Down, Left, Right\n            };\n            static Orientation dir = Up;\n            ImGui::Combo(\"Direction\", (int *) (&dir), \"Up\\0Down\\0Left\\0Right\\0\\0\");\n\n            // We can also use a vector<string> defined dynamically\n            static int num_choices = 3;\n            static vector<string> choices;\n            static int idx_choice = 0;\n            if (ImGui::InputInt(\"Num letters\", &num_choices)) {\n                num_choices = max(1, min(26, num_choices));\n            }\n            if (num_choices != (int) choices.size()) {\n                choices.resize(num_choices);\n                for (int i = 0; i < num_choices; ++i)\n                    choices[i] = string(1, 'A' + i);\n                if (idx_choice >= num_choices)\n                    idx_choice = num_choices - 1;\n            }\n            ImGui::Combo(\"Letter\", &idx_choice, choices);\n\n            // Add a button\n            if (ImGui::Button(\"Print Hello\", ImVec2(-1, 0))) {\n                cout << \"Hello\\n\";\n            }\n        }\n    };\n\n    viewer.launch();\n}\n\n\ntemplate<class MatT>\nEigen::Matrix<typename MatT::Scalar, MatT::ColsAtCompileTime, MatT::RowsAtCompileTime>\npseudoinverse(const MatT &mat, typename MatT::Scalar tolerance = typename MatT::Scalar{1e-7}) // choose appropriately\n{\n    typedef typename MatT::Scalar Scalar;\n    auto svd = mat.jacobiSvd(Eigen::ComputeFullU | Eigen::ComputeFullV);\n    const auto &singularValues = svd.singularValues();\n    Eigen::Matrix<Scalar, MatT::ColsAtCompileTime, MatT::RowsAtCompileTime> singularValuesInv(mat.cols(), mat.rows());\n    singularValuesInv.setZero();\n    for (unsigned int i = 0; i < singularValues.size(); ++i) {\n        if (singularValues(i) > tolerance) {\n            singularValuesInv(i, i) = Scalar{1} / singularValues(i);\n        } else {\n            singularValuesInv(i, i) = Scalar{0};\n        }\n    }\n    return svd.matrixV() * singularValuesInv * svd.matrixU().adjoint();\n}\n\nint main(int argc, char *argv[]) {\n    std::cout << \"Implementation of quad mesh curvature estimation via optimization\" << std::endl;\n\n    //// --------------------- read meashes\n    _Mesh mesh;\n    if (!OpenMesh::IO::read_mesh(mesh, \"../../../model/FlyingCarpet_quad.obj\")) {\n        std::cerr << \"read error\\n\";\n        exit(1);\n    }\n\n    //// --------------------- normal initialize\n    // initilize the normal for each vertex as the cross product of two edges.\n    // which is the initial guess by normalized cross product of two edges\n    vv3d_t one_ring_edges;\n    vector<size_t> valence;\n    v3d_t center;\n    MatrixXd v_normals = MatrixXd::Zero(mesh.n_vertices(), 3);\n    int n_neighbor;\n    for (auto v_it = mesh.vertices_begin(); v_it != mesh.vertices_end(); v_it++) { // vertex\n        center = mesh.point(*v_it);\n        n_neighbor = 0;\n        for (_Mesh::VertexVertexIter vv_it = mesh.vv_iter(*v_it); vv_it.is_valid(); ++vv_it) {\n            auto curr = mesh.point(*vv_it);\n            one_ring_edges.push_back(v3d_t(curr - center).normalized());\n            n_neighbor++;\n        }\n        valence.push_back(one_ring_edges.size());\n        if (n_neighbor > 2) {\n            one_ring_edges.push_back(one_ring_edges[0]);\n        }\n\n        v3d_t normal = v3d_t(0);\n        for (size_t ii = 0; ii < one_ring_edges.size() - 1; ii++) {\n            normal += one_ring_edges[ii] % one_ring_edges[ii + 1]; // % is the cross product\n        }\n        normal /= one_ring_edges.size() - 1;\n        one_ring_edges.clear();\n        v_normals(v_it->idx(), 0) = normal[0];\n        v_normals(v_it->idx(), 1) = normal[1];\n        v_normals(v_it->idx(), 2) = normal[2];\n    }\n\n    // Now we have all the vertex normals (but just the simple guess).\n    // check if v_normals is correct or not.\n    // todo: why so many zeros.\n//    cout << \"\\n-------------------\" << endl << \"v_normals\" << endl << v_normals << \"\\n-------------------\" << endl;\n//    view_v_normal(mesh, v_normals);\n\n    //// --------------------- face_normals, which is always the same during optimization\n    // get the normal for each face using the cross product between the intercross lines of the quad.\n    MatrixXd f_normals;\n    MatrixXd f_centers;\n    f_normals.resize(mesh.n_faces(), 3);\n    f_centers.resize(mesh.n_faces(), 3);\n    vv3d_t quad_vertices;\n    for (auto f_it = mesh.faces_begin(); f_it != mesh.faces_end(); f_it++) { // face\n        for (auto fv_it = mesh.fv_iter(*f_it); fv_it.is_valid(); ++fv_it) {\n            quad_vertices.push_back(v3d_t(mesh.point(*fv_it)));\n        }\n\n        auto normal = ((quad_vertices[0] - quad_vertices[2]) %\n                       (quad_vertices[1] - quad_vertices[3])).normalized();\n\n        auto f_center = quad_vertices[2] + (quad_vertices[0] - quad_vertices[2]) / 2;\n        quad_vertices.clear();\n\n        f_normals(f_it->idx(), 0) = normal[0];\n        f_normals(f_it->idx(), 1) = normal[1];\n        f_normals(f_it->idx(), 2) = normal[2];\n\n        f_centers(f_it->idx(), 0) = f_center[0];\n        f_centers(f_it->idx(), 1) = f_center[1];\n        f_centers(f_it->idx(), 2) = f_center[2];\n    }\n\n    //  Now we have all the vertex normals (initial guess), and face normals\n    // cout << \"\\n-------------------\" << endl << \"f_normals\" << endl << f_normals << \"\\n-------------------\" << endl;\n    // view_f_normals(mesh, f_normals, f_centers);\n\n    //// ----------------------- lets get the face normal of the adjacent faces of each quad.\n    MatrixXd adj_f_normals;\n    MatrixXi edg_orders;\n    adj_f_normals.resize(mesh.n_faces(), 12);\n    edg_orders.resize(mesh.n_faces(), 4);\n    for (auto f_it = mesh.faces_begin(); f_it != mesh.faces_end(); f_it++) { // face\n        int face_count = 0;\n        for (auto fh_it = mesh.fh_iter(*f_it); fh_it.is_valid(); ++fh_it) {\n            edg_orders(f_it->idx(), face_count) = fh_it->idx();\n            auto opposite_idx = (mesh.opposite_face_handle(*fh_it)).idx();\n            if (!mesh.is_boundary(*fh_it) and opposite_idx != -1) {\n                adj_f_normals(f_it->idx(), 3 * face_count) = f_normals.row(opposite_idx)(0);\n                adj_f_normals(f_it->idx(), 3 * face_count + 1) = f_normals.row(opposite_idx)(1);\n                adj_f_normals(f_it->idx(), 3 * face_count + 2) = f_normals.row(opposite_idx)(2);\n                face_count++;\n            }\n        }\n    }\n\n\n    //  Now we have all the vertex normals, and face normals, adjacent face normals\n    // cout << \"\\n-------------------\" << endl << \"edg_orders\" << endl << edg_orders << \"\\n-------------------\" << endl;\n    // cout << \"\\n-------------------\" << endl << \"adjacent f_normals\" << endl << adj_f_normals << \"\\n-------------------\" << endl;\n\n    //// ----------------- optimization, update the vertices normals, and then calculate the vertex curvatures.\n    /// -> shape operator -> egien value -> principal curvatures\n    // for 12 constraints\n    // MatrixXd lin_sys_a = MatrixXd::Zero(12, 12);\n    // VectorXd lin_sys_b; lin_sys_b.resize(12, 1);\n    // lin_sys_b << 2.0 ,  2.0 ,  2.0 ,  0 ,  2.0 ,  2.0 ,  2.0 ,  2.0, 0.0, 0.0, 0.0, 0.0;\n    // for 16 constraints (over constraint, default)\n\n    MatrixXd lin_sys_a = MatrixXd::Zero(16, 12);\n    VectorXd lin_sys_b;\n    lin_sys_b.resize(16, 1);\n    lin_sys_b << 2.0, 2.0, 2.0, 0, 2.0, 2.0, 2.0, 2.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0;\n\n    MatrixXd solution;\n\n    MatrixXd init_v_normals = v_normals;\n    MatrixXd new_v_normals = v_normals;\n    deque<Vector3d> vertices_;\n    deque<v3d_t> adj_normals;\n    Vector3d f_normal;\n    Vector3d of_normal; //opposite_face_normal\n    MatrixXd v_normals_diff = MatrixXd::Zero(4, 3);\n    MatrixXd v_normals_diff2 = MatrixXd::Zero(4, 3);\n    MatrixXd opp_normals = MatrixXd::Zero(4, 3);\n    int f_it_idx;\n    vector<size_t> v_idx_of_face;\n    v3d_t v_normal;\n    set<int, greater<int>> neighbours;\n    set<int, greater<int>> vtx_neighbours;\n\n    //// optimization\n    // argv is the input argument for optimization steps.\n    for (int k = 0; k < atoi(argv[1]); k++) {   // optimization steps\n        for (auto f_it = mesh.faces_begin(); f_it != mesh.faces_end(); f_it++) { // faces\n            f_it_idx = f_it->idx();\n            //  cout << \"=====> curr_face \" << f_it_idx << \"/\" << mesh.n_faces() << endl;\n            for (size_t ii = 0; ii < 4; ii++) {  // number of edges of each face is 4\n                int e = edg_orders(f_it_idx, ii);   // handle No. of edge\n                auto edge = mesh.halfedge_handle(e);    // half edge handle\n                auto v_from = mesh.from_vertex_handle(edge);    // v_from handle\n                auto f_idx = mesh.face_handle(edge);\n\n                f_normal = f_normals.row(f_idx.idx());\n                // get the opposite face normals, when there is a boundary (no adj face), of_normal will be zero\n                of_normal(0) = adj_f_normals.row(f_it_idx)(ii * 3);\n                of_normal(1) = adj_f_normals.row(f_it_idx)(ii * 3 + 1);\n                of_normal(2) = adj_f_normals.row(f_it_idx)(ii * 3 + 2);\n\n                v_idx_of_face.push_back(v_from.idx());  // 4 vertices of a face\n                auto vtx = mesh.point(v_from);\n                // get 4 vertices and 4 adj_normals\n                vertices_.push_back(Vector3d(vtx[0], vtx[1], vtx[2]));\n                adj_normals.push_back(v3d_t(of_normal(0), of_normal(1), of_normal(2)));\n\n                //// this part is a little bit confusing at the first time,\n                /// this is for getting the vertice v_j along the same line of v.\n                // get the neighbors of vertex on the inside and outside\n                // indexed properly. so that we get the constraints on the vertex normals\n                // in the two PC directions\n                // for opp face, add vtx\n                //for curr face add vtx\n                // find out = set\\curr_vtx_neigh\n                //pair is out, mesh.from(he)\n                auto opposite_fidx = mesh.opposite_face_handle(edge);\n                auto curr_fidx = mesh.face_handle(edge);\n                int opp_vtx_idx, in_vtx_idx;\n                if (!mesh.is_boundary(edge) and opposite_fidx.idx() != -1) {\n                    for (auto curr_fvit = mesh.fv_iter(opposite_fidx); curr_fvit.is_valid(); ++curr_fvit) {\n                        neighbours.insert(curr_fvit->idx());\n                    }\n                }\n \n                if (!mesh.is_boundary(edge) and curr_fidx.idx() != -1) {\n                    for (auto curr_fvit = mesh.fv_iter(curr_fidx); curr_fvit.is_valid(); ++curr_fvit) {\n                        neighbours.insert(curr_fvit->idx());\n                    }\n                }\n\n                for (auto vv_it = mesh.vv_iter(v_from); vv_it.is_valid(); ++vv_it) {\n                    vtx_neighbours.insert(vv_it->idx());\n                }\n\n                // you may have nothing here.\n                for (auto jj: vtx_neighbours) {\n                    if (!neighbours.count(jj)) {\n                        opp_vtx_idx = jj;\n                        in_vtx_idx = mesh.to_vertex_handle(edge).idx();\n//                        in_vtx_idx = v_from.idx();\n                        v_normals_diff(ii, 0) = v_normals(opp_vtx_idx, 0) - v_normals(in_vtx_idx, 0);\n                        v_normals_diff(ii, 1) = v_normals(opp_vtx_idx, 1) - v_normals(in_vtx_idx, 1);\n                        v_normals_diff(ii, 2) = v_normals(opp_vtx_idx, 2) - v_normals(in_vtx_idx, 2);\n                    }\n                }\n\n                // find the second pair. If not exists, zeros\n                neighbours.clear(); // do not clear vtx_neighbours, we will use them.\n                if (ii == 0) { e = edg_orders(f_it_idx, 3); }\n                else { e = edg_orders(f_it_idx, ii - 1); }\n\n                //// todo: the only thing missing is error checking in the edg order function as sometiomes the edge handles are useless when the edge to visit is a boundary edge\n                // if (e >= mesh.n_halfedges() || e < 0 ){\n                //     continue;\n                // }\n\n                edge = mesh.halfedge_handle(e);\n                opposite_fidx = mesh.opposite_face_handle(edge);\n                if (!mesh.is_boundary(edge) and opposite_fidx.idx() != -1) {\n                    for (auto curr_fvit = mesh.fv_iter(opposite_fidx); curr_fvit.is_valid(); ++curr_fvit) {\n                        neighbours.insert(curr_fvit->idx());\n                    }\n                }\n\n                if (!mesh.is_boundary(edge) and curr_fidx.idx() != -1) {\n                    for (auto curr_fvit = mesh.fv_iter(curr_fidx); curr_fvit.is_valid(); ++curr_fvit) {\n                        neighbours.insert(curr_fvit->idx());\n                    }\n                }\n\n\n                for (auto jj: vtx_neighbours) {\n                    if (!neighbours.count(jj)) {\n                        opp_vtx_idx = jj;\n                        in_vtx_idx = mesh.to_vertex_handle(edge).idx();\n                        v_normals_diff2(ii, 0) = v_normals(opp_vtx_idx, 0) - v_normals(in_vtx_idx, 0);\n                        v_normals_diff2(ii, 1) = v_normals(opp_vtx_idx, 1) - v_normals(in_vtx_idx, 1);\n                        v_normals_diff2(ii, 2) = v_normals(opp_vtx_idx, 2) - v_normals(in_vtx_idx, 2);\n\n                        // below is for another method, keep it.\n                        //v_normal[0] = v_normals(opp_vtx_idx, 0);\n                        //v_normal[1] = v_normals(opp_vtx_idx, 1);\n                        //v_normal[2] = v_normals(opp_vtx_idx, 2);\n                        //opp_normals(ii) = 2- of_normal % v_normal;\n                    }\n                }\n            }\n\n            /// now we build the linear system and solve it. Here we construct A and b matrix one by one element-wise\n            /// Black-rectangle constraints\n            lin_sys_a(0, 0) = f_normal[0];\n            lin_sys_a(0, 1) = f_normal[1];\n            lin_sys_a(0, 2) = f_normal[2];\n            lin_sys_a(0, 3) = f_normal[0];\n            lin_sys_a(0, 4) = f_normal[1];\n            lin_sys_a(0, 5) = f_normal[2];\n\n            lin_sys_a(1, 3) = f_normal[0];\n            lin_sys_a(1, 4) = f_normal[1];\n            lin_sys_a(1, 5) = f_normal[2];\n            lin_sys_a(1, 6) = f_normal[0];\n            lin_sys_a(1, 7) = f_normal[1];\n            lin_sys_a(1, 8) = f_normal[2];\n\n            lin_sys_a(2, 6) = f_normal[0];\n            lin_sys_a(2, 7) = f_normal[1];\n            lin_sys_a(2, 8) = f_normal[2];\n            lin_sys_a(2, 9) = f_normal[0];\n            lin_sys_a(2, 10) = f_normal[1];\n            lin_sys_a(2, 11) = f_normal[2];\n\n            /// Shape operator constraint\n            auto v13 = vertices_[1] - vertices_[3];\n            auto v20 = vertices_[2] - vertices_[0];\n            lin_sys_a(3, 0) = v13[0];\n            lin_sys_a(3, 1) = v13[1];\n            lin_sys_a(3, 2) = v13[2];\n            lin_sys_a(3, 3) = v20[0];\n            lin_sys_a(3, 4) = v20[1];\n            lin_sys_a(3, 5) = v20[2];\n            lin_sys_a(3, 6) = -v13[0];\n            lin_sys_a(3, 7) = -v13[1];\n            lin_sys_a(3, 8) = -v13[2];\n            lin_sys_a(3, 9) = -v20[0];\n            lin_sys_a(3, 10) = -v20[1];\n            lin_sys_a(3, 11) = -v20[2];\n\n            /// Adjacent face constraints\n            lin_sys_a(4, 0) = adj_normals[0][0];\n            lin_sys_a(4, 1) = adj_normals[0][1];\n            lin_sys_a(4, 2) = adj_normals[0][2];\n            lin_sys_a(4, 3) = adj_normals[0][0];\n            lin_sys_a(4, 4) = adj_normals[0][1];\n            lin_sys_a(4, 5) = adj_normals[0][2];\n\n            lin_sys_a(5, 3) = adj_normals[1][0];\n            lin_sys_a(5, 4) = adj_normals[1][1];\n            lin_sys_a(5, 5) = adj_normals[1][2];\n            lin_sys_a(5, 6) = adj_normals[1][0];\n            lin_sys_a(5, 7) = adj_normals[1][1];\n            lin_sys_a(5, 8) = adj_normals[1][2];\n\n            lin_sys_a(6, 6) = adj_normals[2][0];\n            lin_sys_a(6, 7) = adj_normals[2][1];\n            lin_sys_a(6, 8) = adj_normals[2][2];\n            lin_sys_a(6, 9) = adj_normals[2][0];\n            lin_sys_a(6, 10) = adj_normals[2][1];\n            lin_sys_a(6, 11) = adj_normals[2][2];\n\n            lin_sys_a(7, 0) = adj_normals[3][0];\n            lin_sys_a(7, 1) = adj_normals[3][1];\n            lin_sys_a(7, 2) = adj_normals[3][2];\n            lin_sys_a(7, 9) = adj_normals[3][0];\n            lin_sys_a(7, 10) = adj_normals[3][1];\n            lin_sys_a(7, 11) = adj_normals[3][2];\n\n            /// Adjacent face constraints. This is for the second method, have not finished\n            // lin_sys_a(8, 0) = opp_normals[0][0];\n            // lin_sys_a(8, 1) = adj_normals[0][1];\n            // lin_sys_a(8, 2) = adj_normals[0][2];\n            // lin_sys_a(8, 3) = adj_normals[0][0];\n            // lin_sys_a(8, 4) = adj_normals[0][1];\n            // lin_sys_a(8, 5) = adj_normals[0][2];\n\n            /// gordon's inline constraint\n            lin_sys_a(8, 0) = v_normals_diff(0, 0);\n            lin_sys_a(8, 1) = v_normals_diff(0, 1);\n            lin_sys_a(8, 2) = v_normals_diff(0, 2);\n\n            lin_sys_a(9, 3) = v_normals_diff(1, 0);\n            lin_sys_a(9, 4) = v_normals_diff(1, 1);\n            lin_sys_a(9, 5) = v_normals_diff(1, 2);\n\n            lin_sys_a(10, 6) = v_normals_diff(2, 0);\n            lin_sys_a(10, 7) = v_normals_diff(2, 1);\n            lin_sys_a(10, 8) = v_normals_diff(2, 2);\n\n            lin_sys_a(11, 9) = v_normals_diff(3, 0);\n            lin_sys_a(11, 10) = v_normals_diff(3, 1);\n            lin_sys_a(11, 11) = v_normals_diff(3, 2);\n\n            lin_sys_a(12, 0) = v_normals_diff2(0, 0);\n            lin_sys_a(12, 1) = v_normals_diff2(0, 1);\n            lin_sys_a(12, 2) = v_normals_diff2(0, 2);\n\n            lin_sys_a(13, 3) = v_normals_diff2(1, 0);\n            lin_sys_a(13, 4) = v_normals_diff2(1, 1);\n            lin_sys_a(13, 5) = v_normals_diff2(1, 2);\n\n            lin_sys_a(14, 6) = v_normals_diff2(2, 0);\n            lin_sys_a(14, 7) = v_normals_diff2(2, 1);\n            lin_sys_a(14, 8) = v_normals_diff2(2, 2);\n\n            lin_sys_a(15, 9) = v_normals_diff2(3, 0);\n            lin_sys_a(15, 10) = v_normals_diff2(3, 1);\n            lin_sys_a(15, 11) = v_normals_diff2(3, 2);\n\n            solution = lin_sys_a.colPivHouseholderQr().solve(lin_sys_b);\n\n            /// now we get the new local v_normals : solution.\n            new_v_normals(v_idx_of_face[0], 0) = solution(0);\n            new_v_normals(v_idx_of_face[0], 1) = solution(1);\n            new_v_normals(v_idx_of_face[0], 2) = solution(2);\n            new_v_normals(v_idx_of_face[1], 0) = solution(3);\n            new_v_normals(v_idx_of_face[1], 1) = solution(4);\n            new_v_normals(v_idx_of_face[1], 2) = solution(5);\n            new_v_normals(v_idx_of_face[2], 0) = solution(6);\n            new_v_normals(v_idx_of_face[2], 1) = solution(7);\n            new_v_normals(v_idx_of_face[2], 2) = solution(8);\n            new_v_normals(v_idx_of_face[3], 0) = solution(9);\n            new_v_normals(v_idx_of_face[3], 1) = solution(10);\n            new_v_normals(v_idx_of_face[3], 2) = solution(11);\n\n            // cout << \"\\t\\tRelative error \" << (lin_sys_a * solution - lin_sys_b).norm() / lin_sys_b.norm() << endl;\n\n            v_idx_of_face.clear();\n            adj_normals.clear();\n            // lin_sys_a = MatrixXd::Zero(12, 12); // this is for the second method, comgaussian_curvaturesment it if not used.\n            lin_sys_a = MatrixXd::Zero(16, 12);\n            neighbours.clear();\n            vtx_neighbours.clear();\n            v_normals_diff = MatrixXd::Zero(4, 3);\n        }\n        v_normals = v_normals + 0.001 * new_v_normals;  /// important. The step size is 0.001\n    }\n\n    /// Now we have everthing.\n    /// calculate curvatures locally by solving the local shape operator and get its egenvalues.\n    MatrixXd lin_sys_v = MatrixXd::Zero(2, 3);  // vertices corrdinates\n    MatrixXd lin_sys_n = MatrixXd::Zero(2, 3);  // v_normals.\n    MatrixXd shape_operator = MatrixXd::Zero(2, 2);\n    vector<RowVector3d> quad_v_normals;\n    quad_vertices.clear(); // we use the quad_vertices defined before.\n\n    MatrixXd curvature = MatrixXd::Zero(1, 2); //local curvature\n    MatrixXd principle_vector = MatrixXd::Zero(2, 2);\n    MatrixXd gaussian_curvatures = MatrixXd::Zero(mesh.n_faces()*2, 1); // we have to change to traingle.\n    MatrixXd mean_curvatures = MatrixXd::Zero(mesh.n_faces()*2, 1);\n    MatrixXd pc1 = MatrixXd::Zero(mesh.n_faces(), 3);\n    MatrixXd pc2 = MatrixXd::Zero(mesh.n_faces(), 3);\n    MatrixXd coor_trans = MatrixXd::Zero(3, 3);\n\n    for (auto f_it = mesh.faces_begin(); f_it != mesh.faces_end(); f_it++) { // face\n        for (auto fv_it = mesh.fv_iter(*f_it); fv_it.is_valid(); ++fv_it) {  // v\n            quad_vertices.push_back(v3d_t(mesh.point(*fv_it)));\n            quad_v_normals.push_back(v_normals.row((fv_it->idx())));\n        }\n        lin_sys_v(0, 0) = quad_vertices[0][0] - quad_vertices[2][0];\n        lin_sys_v(0, 1) = quad_vertices[0][1] - quad_vertices[2][1];\n        lin_sys_v(0, 2) = quad_vertices[0][2] - quad_vertices[2][2];\n        lin_sys_v(1, 0) = quad_vertices[1][0] - quad_vertices[3][0];\n        lin_sys_v(1, 1) = quad_vertices[1][1] - quad_vertices[3][1];\n        lin_sys_v(1, 2) = quad_vertices[1][2] - quad_vertices[3][2];\n\n        lin_sys_n(0, 0) = quad_v_normals[2][0] - quad_v_normals[0][0];\n        lin_sys_n(0, 1) = quad_v_normals[2][1] - quad_v_normals[0][1];\n        lin_sys_n(0, 2) = quad_v_normals[2][2] - quad_v_normals[0][2];\n        lin_sys_n(1, 0) = quad_v_normals[3][0] - quad_v_normals[1][0];\n        lin_sys_n(1, 1) = quad_v_normals[3][1] - quad_v_normals[1][1];\n        lin_sys_n(1, 2) = quad_v_normals[3][2] - quad_v_normals[1][2];\n\n        cout << \"----------------\\n\"<<\"lin_sys\\n\"<<lin_sys_v << endl << lin_sys_n <<endl;  //debuging\n        shape_operator = lin_sys_n * pseudoinverse(lin_sys_v);\n        cout << \"shape operator \\n\"<< shape_operator<<endl;\n        Eigen::SelfAdjointEigenSolver<Eigen::Matrix2d> eigensolver(shape_operator);\n        if (eigensolver.info() != Eigen::Success) abort();\n\n        curvature = eigensolver.eigenvalues();\n        cout << \"egienvalues \\n\"<< curvature<<endl;  //debuging\n        principle_vector = eigensolver.eigenvectors();\n        auto f_idx = f_it->idx();\n        gaussian_curvatures(f_idx*2, 0) = curvature(0, 0) * curvature(1,0);\n        gaussian_curvatures(f_idx*2+1, 0) = curvature(0,0) * curvature(1,0);\n        mean_curvatures(f_idx*2, 0) = (curvature(0,0) + curvature(1,0)) / 2;\n        mean_curvatures(f_idx*2+1, 0) = (curvature(0,0) + curvature(1,0)) / 2;\n\n        coor_trans(0, 2) = f_normals(f_idx, 0);\n        coor_trans(1, 2) = f_normals(f_idx, 1);\n        coor_trans(2, 2) = f_normals(f_idx, 2);\n\n        coor_trans(0, 0) = quad_vertices[0][0] - quad_vertices[2][0];\n        coor_trans(1, 0) = quad_vertices[0][1] - quad_vertices[2][1];\n        coor_trans(2, 0) = quad_vertices[0][2] - quad_vertices[2][2];\n\n        coor_trans( 0, 1) = quad_vertices[1][0] - quad_vertices[3][0];\n        coor_trans( 1, 1) = quad_vertices[1][1] - quad_vertices[3][1];\n        coor_trans( 2, 1) = quad_vertices[1][2] - quad_vertices[3][2];\n\n        pc1.row(f_idx) = coor_trans * Vector3d(principle_vector(0,0), principle_vector(1,0), 0);\n        pc2.row(f_idx) = coor_trans * Vector3d(principle_vector(0,1), principle_vector(1,1), 0);\n\n        quad_vertices.clear();\n        quad_v_normals.clear();\n    }\n    /// curvarues.\n    //cout << \"\\n-------------------\" << endl << \"guassian_curvatures\" << endl << gaussian_curvatures\n     //    << \"\\n-------------------\" << endl;\n    //cout << \"\\n-------------------\" << endl << \"mean_curvatures\" << endl << mean_curvatures << \"\\n-------------------\"<< endl;\n    //cout << \"\\n-------------------\" << endl << \"principal direction 1\"<<pc1 <<endl;\n    //cout << \"\\n-------------------\" << endl << \"principal direction 2\"<<pc2 <<endl;\n\n    /// now we have the curvatures, we will show the curvatures of each vertices.\n    // show everything we have step by step by pressing different keys\n    // 1: face normals.\n    // 2. initial v_normal and optimized v_normal\n    // 3. offset faces.\n    // 4. curvatures of face guassian\n    // 5. mean curvatures.\n    view_total_info(mesh, init_v_normals, v_normals, f_centers, f_normals, gaussian_curvatures, mean_curvatures, pc1, pc2);\n    return 0;\n}", "meta": {"hexsha": "0af9f5c622726e511e275e56d44d66f356b84d6e", "size": 45662, "ext": "cc", "lang": "C++", "max_stars_repo_path": "killing field/src/OpenMesh/Apps/curvature_estimation/main.cc", "max_stars_repo_name": "jiayaozhang/CS-370-Mesh-Processing", "max_stars_repo_head_hexsha": "26646d29af8cbc0d461302afa137f12b508b8b1b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "killing field/src/OpenMesh/Apps/curvature_estimation/main.cc", "max_issues_repo_name": "jiayaozhang/CS-370-Mesh-Processing", "max_issues_repo_head_hexsha": "26646d29af8cbc0d461302afa137f12b508b8b1b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "killing field/src/OpenMesh/Apps/curvature_estimation/main.cc", "max_forks_repo_name": "jiayaozhang/CS-370-Mesh-Processing", "max_forks_repo_head_hexsha": "26646d29af8cbc0d461302afa137f12b508b8b1b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 42.714686623, "max_line_length": 178, "alphanum_fraction": 0.544566598, "num_tokens": 12574, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5273165233795672, "lm_q2_score": 0.6513548646660543, "lm_q1q2_score": 0.3434701827220723}}
{"text": "/**\n *  Safe landing control of DC9-30 with the abstraction-based engine.\n *\n *  Created by Yinan Li on Jan 11, 2021.\n *  Hybrid Systems Group, University of Waterloo.\n */\n\n#include <iostream>\n#include <boost/algorithm/string.hpp>\n#include <cmath>\n#include <sys/stat.h>\n\n#include \"src/system.hpp\"\n#include \"src/abstraction.hpp\"\n#include \"src/DBAparser.h\"\n#include \"src/bsolver.hpp\"\n#include \"src/hdf5io.h\"\n\n\n/* Parameters of the model */\ndouble mg = 60000.0*9.81;\ndouble mi = 1.0/60000; /* weight inverse: 1/m */\n\n\n\n/* ODE of the longitudinal equation of motions for DC9-30 */\nstruct eomlong {\n    static const int n = 3;  // state dimension\n    static const int m = 2;  // control dimension\n    \n    /**\n     * Constructors: \n     * @param[out] dx (dV, dgamma, dh)\n     * @param[in] x (V,gamma,h).\n     * @param[in] u (T, alpha) control input (thrust, angle of attack)\n     */\n    template<typename S>\n    eomlong(S *dx, const S *x, rocs::Rn u) {\n\tdouble c = 1.25+4.2*u[1];\n\tdx[0] = mi*(u[0]*cos(u[1])-(2.7+3.08*c*c)*x[0]*x[0]-mg*sin(x[1]));\n\tdx[1] = (1.0/(60000*x[0]))*(u[0]*sin(u[1])+68.6*c*x[0]*x[0]-mg*cos(x[1]));\n\tdx[2] = x[0]*sin(x[1]);\n    }\n    \n};\n\n/** A target set in the form of f(x)<=0:\n * x(0)*sin(x(1)) >= -0.91\n *\n **/\ntemplate<typename T>\nT target_area(const T &x) {\n    T y(7);\n    y[0] = -0.91-x[0]*sin(x[1]);\n    y[1] = 63 - x[0];\n    y[2] = x[0] - 75;\n    y[3] = -3*M_PI/180 - x[1];\n    y[4] = x[1];\n    y[5] = -x[2];\n    y[6] = x[2] - 2.5;\n    return y;\n}\n\n\nint main(int argc, char *argv[])\n{   \n    /**\n     * Define the control system \n     **/\n    /* Set sampling time and disturbance */\n    double tau = 0.25;\n    double delta = 10;\n    /* Set parameters for computation */\n    int kmax = 5;\n    double tol = 0.01;\n    double alpha = 0.5;\n    double beta = 2;\n    rocs::params controlparams(kmax, tol, alpha, beta);\n    rocs::CTCntlSys<eomlong> aircraft(\"landing\", tau, eomlong::n,\n\t\t\t\t      eomlong::m, delta, &controlparams);\n    /* set the state space */\n    double xlb[] = {58, -3*M_PI/180, 0};\n    double xub[] = {83, 0, 56};\n    double ulb[] = {0,0};\n    double uub[] = {32000, 8*M_PI/180};\n    double mu[] = {32000, 9.0/8.0*M_PI/180};\n    aircraft.init_workspace(xlb, xub);\n    aircraft.init_inputset(mu, ulb, uub);\n    // std::cout << \"# of u= \" << aircraft._ugrid._nv\n    // \t      << \", dimension= \" << aircraft._ugrid._dim << '\\n';\n    // for(int i = 0; i < aircraft._ugrid._nv; ++i) {\n    // \tstd::cout << aircraft._ugrid._data[i][0] << ','\n    // \t\t  << aircraft._ugrid._data[i][1] << '\\n';\n    // }\n    aircraft.allocate_flows();\n\n\n    /**\n     * Compute abstraction\n     */\n    /* Set the target set */\n    const double eta[] = {25.0/362, 3*M_PI/180/66, 56.0/334};\n    double glb[] = {63, -3*M_PI/180, 0};\n    double gub[] = {75, 0, 2.5};\n    rocs::abstraction< rocs::CTCntlSys<eomlong> > abst(&aircraft);\n    abst.init_state(eta, xlb, xub);\n    std::cout << \"The number of abstraction states: \" << abst._x._nv << '\\n';\n    auto target = [&abst, &eta, &glb, &gub](size_t i) {\n\t\t      std::vector<double> x(abst._x._dim);\n\t\t      abst._x.id_to_val(x, i);\n\t\t      double c[]{eta[0]/2.0, eta[1]/2.0, eta[2]/2.0}; //+1e-10;\n\t\t      if(x[0]-c[0] >= glb[0] && x[0]+c[0] <= gub[0] &&\n\t\t\t x[1]-c[1] >= glb[1] && x[1]+c[1] <= gub[1] &&\n\t\t\t x[2]-c[2] >= glb[2] && x[2]+c[2] <= gub[2])\n\t\t\t  return 1;\n\t\t      else\n\t\t\t  return 0;\n\t\t  };\n    abst.assign_labels(target);\n    abst.assign_label_outofdomain(0);\n    /* Compute abstraction */\n    clock_t tb, te;\n    std::string transfile = \"abstraction.h5\";\n    struct stat buffer;\n    float tabst;\n    if(stat(transfile.c_str(), &buffer) == 0) {\n\t/* Read from a file */\n\tstd::cout << \"Transitions have been computed. Reading transitions...\\n\";\n\trocs::h5FileHandler transRdr(transfile, H5F_ACC_RDONLY);\n\ttb = clock();\n\ttransRdr.read_transitions(abst._ts);\n\tte = clock();\n\ttabst = (float)(te - tb)/CLOCKS_PER_SEC;\n\tstd::cout << \"Time of reading abstraction: \" << tabst << '\\n';\n    } else {\n\tstd::cout << \"Transitions haven't been computed. Computing transitions...\\n\";\n\t/* Robustness margins */\n\tdouble e1[] = {0,0,0};\n\tdouble e2[] = {0,0,0};\n\ttb = clock();\n\tabst.assign_transitions(e1, e2);\n\tte = clock();\n\ttabst = (float)(te - tb)/CLOCKS_PER_SEC;\n\tstd::cout << \"Time of computing abstraction: \" << tabst << '\\n';\n\t/* Write transitions to file */\n\trocs::h5FileHandler transWtr(transfile, H5F_ACC_TRUNC);\n\ttransWtr.write_transitions(abst._ts);\n    }\n    std::cout << \"# of transitions: \" << abst._ts._ntrans << '\\n';\n    \n    std::vector<size_t> targetIDs;\n    std::vector< std::vector<double> > targetPts;   //initial invariant set\n    std::vector<double> x(abst._x._dim);\n    for(size_t i = 0; i < abst._labels.size(); ++i) {\n    \tif(abst._labels[i] > 0) {\n    \t    targetIDs.push_back(i);\n    \t    abst._x.id_to_val(x, i);\n    \t    targetPts.push_back(x);\n    \t}\n    }\n\n    \n    /**\n     * Reachability control synthesis\n     */\n    rocs::DSolver solver(&abst._ts);\n    tb = clock();\n    solver.reachability(targetIDs);\n    te = clock();\n    float tsyn = (float)(te - tb)/CLOCKS_PER_SEC;\n    std::cout << \"Time of control synthesis: \" << tsyn << '\\n';\n    std::cout << \"The size of winning set: \" << solver._nw << '\\n';\n\n    \n    /**\n     * Write the control synthesis result into .h5 file.\n     */\n    std::string datafile = \"controller_abst_safelanding.h5\";\n    rocs::h5FileHandler ctlrWtr(datafile, H5F_ACC_TRUNC);\n    ctlrWtr.write_problem_setting< rocs::CTCntlSys<eomlong> >(aircraft);\n    ctlrWtr.write_2d_array<double>(targetPts, \"G\");\n    ctlrWtr.write_array<double>(eta, 3, \"eta\");\n    ctlrWtr.write_2d_array<double>(abst._x._data, \"xgrid\");\n    ctlrWtr.write_discrete_controller(solver);\n\n\n    aircraft.release_flows();\n    return 0;\n}\n", "meta": {"hexsha": "611fdac5a049c403f87e418415b358a85df1110c", "size": 5723, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/aircraft/aircraftAbst.cpp", "max_stars_repo_name": "yinanl/rocs", "max_stars_repo_head_hexsha": "bf2483903e39f4c0ea254a9ef56720a1259955ad", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/aircraft/aircraftAbst.cpp", "max_issues_repo_name": "yinanl/rocs", "max_issues_repo_head_hexsha": "bf2483903e39f4c0ea254a9ef56720a1259955ad", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/aircraft/aircraftAbst.cpp", "max_forks_repo_name": "yinanl/rocs", "max_forks_repo_head_hexsha": "bf2483903e39f4c0ea254a9ef56720a1259955ad", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.1210526316, "max_line_length": 78, "alphanum_fraction": 0.5776690547, "num_tokens": 1948, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6513548646660543, "lm_q2_score": 0.5273165233795671, "lm_q1q2_score": 0.3434701827220722}}
{"text": "#ifndef KERNELS_HPP\n#define KERNELS_HPP\n\n#include <skelly_sim.hpp>\n\n#include <Eigen/Dense>\n#include <STKFMM/STKFMM.hpp>\n\n/// Namespace for miscellaneous \"kernel\" functions and related convenience FMM class\nnamespace kernels {\ntypedef Eigen::MatrixXd (*fmm_kernel_func_t)(const int n_trg, MatrixRef &f_sl, MatrixRef &f_dl, stkfmm::STKFMM *);\n\nEigen::MatrixXd oseen_tensor_contract_direct(MatrixRef &r_src, MatrixRef &r_trg, MatrixRef &density, double eta = 1.0,\n                                             double reg = 5E-3, double epsilon_distance = 1E-5);\n\nEigen::MatrixXd stokes_vel_fmm(const int n_trg, MatrixRef &f_sl, MatrixRef &f_dl, stkfmm::STKFMM *fmmPtr);\n\nEigen::MatrixXd stokes_pvel_fmm(const int n_trg, MatrixRef &f_sl, MatrixRef &f_dl, stkfmm::STKFMM *fmmPtr);\n\nEigen::MatrixXd oseen_tensor_direct(MatrixRef &r_src, MatrixRef &r_trg, double eta = 1.0, double reg = 5E-3,\n                                    double epsilon_distance = 1E-5);\n\nEigen::MatrixXd rotlet(MatrixRef &r_src, MatrixRef &r_trg, MatrixRef &density, double eta = 1.0, double reg = 5E-3,\n                       double epsilon_distance = 1E-5);\n\nEigen::MatrixXd stresslet_times_normal(MatrixRef &r_src, MatrixRef &normals, double eta = 1.0, double reg = 5E-3,\n                                       double epsilon_distance = 1E-5);\n\nEigen::MatrixXd stresslet_times_normal_times_density(MatrixRef &r_src, MatrixRef &normals, MatrixRef &density,\n                                                     double eta = 1.0, double reg = 5E-3,\n                                                     double epsilon_distance = 1E-5);\n\n/// Convenience class to represent an FMM interaction, which stores the STKFMM pointer. This\n/// setup allows for a direct call to the FMM object which returns the relevant target kernel\n/// evaluation matrix to each MPI rank.\ntemplate <typename stkfmm_type>\nclass FMM {\n  public:\n    template <typename F>\n    FMM(const int order, const int maxPoints, const stkfmm::PAXIS paxis, const stkfmm::KERNEL k, const F &kernel_func)\n        : fmmPtr_(new stkfmm_type(order, maxPoints, paxis, static_cast<unsigned>(k))), k_(k),\n          kernel_func_(kernel_func){};\n\n    /// @brief Set flag to force next call to set up tree, regardless of cache variables\n    void force_setup_tree() { force_setup_tree_ = true; };\n\n    /// @brief Evaluate the FMM kernel given the given sources/targets\n    ///\n    /// Repeated calls to the FMM object with the same source/target positions will maintain\n    /// the FMM tree and therefore avoid the costly STKFMM::setupTree() call.\n    ///\n    /// @param[in] r_sl [ 3 x n_src ] matrix of 'single-layer' source coordinates\n    /// @param[in] r_dl [ 3 x n_src ] matrix of 'double-layer' source coordinates\n    /// @param[in] r_trg [ 3 x n_trg ] matrix of target coordinates\n    /// @param[in] f_sl [ k_dim_sl x n_src ] matrix of 'single-layer' source strengths\n    /// @param[in] f_sl [ k_dim_dl x n_src ] matrix of 'double-layer' source strengths\n    /// @returns [ k_dim_trg x n_trg ] matrix of kernel evaluated at target positions given the sources\n    Eigen::MatrixXd operator()(MatrixRef &r_sl, MatrixRef &r_dl, MatrixRef &r_trg, MatrixRef &f_sl, MatrixRef &f_dl) {\n        // Check if LOCAL source/target points have changed, and then broadcast that for a GLOBAL update\n        char setup_flag_local =\n            (force_setup_tree_ || r_sl_old_.size() != r_sl.size() || r_dl_old_.size() != r_dl.size() ||\n             r_trg_old_.size() != r_trg.size() || r_sl_old_ != r_sl || r_dl_old_ != r_dl || r_trg_old_ != r_trg);\n        char setup_flag;\n        MPI_Allreduce(&setup_flag_local, &setup_flag, 1, MPI_CHAR, MPI_LOR, MPI_COMM_WORLD);\n\n        if (setup_flag) {\n            double sl_min = r_sl.size() ? r_sl.minCoeff() : std::numeric_limits<double>::max();\n            double dl_min = r_dl.size() ? r_dl.minCoeff() : std::numeric_limits<double>::max();\n            double trg_min = r_trg.size() ? r_trg.minCoeff() : std::numeric_limits<double>::max();\n            double sl_max = r_sl.size() ? r_sl.maxCoeff() : std::numeric_limits<double>::min();\n            double dl_max = r_dl.size() ? r_dl.maxCoeff() : std::numeric_limits<double>::min();\n            double trg_max = r_trg.size() ? r_trg.maxCoeff() : std::numeric_limits<double>::min();\n\n            // Find most extreme points to define our box, which is required to be a cube\n            double local_min = std::min(std::min(sl_min, dl_min), trg_min);\n            double local_max = std::max(std::max(sl_max, dl_max), trg_max);\n\n            double global_min, global_max;\n            MPI_Allreduce(&local_min, &global_min, 1, MPI_DOUBLE, MPI_MIN, MPI_COMM_WORLD);\n            MPI_Allreduce(&local_max, &global_max, 1, MPI_DOUBLE, MPI_MAX, MPI_COMM_WORLD);\n\n            // Scale box coordinates so that no source/target lies on the box boundary\n            global_min *= 1.01;\n            global_max *= 1.01;\n            const double L = global_max - global_min;\n\n            // Update FMM tree and cache coordinates\n            double origin[3] = {global_min, global_min, global_min};\n            fmmPtr_->setBox(origin, L);\n            fmmPtr_->setPoints(r_sl.size() / 3, r_sl.data(), r_trg.size() / 3, r_trg.data(), r_dl.size() / 3,\n                               r_dl.data());\n            fmmPtr_->setupTree(k_);\n            r_sl_old_ = r_sl;\n            r_dl_old_ = r_dl;\n            r_trg_old_ = r_trg;\n            force_setup_tree_ = false;\n        }\n\n        int n_trg = r_trg.size() / 3;\n        return kernel_func_(n_trg, f_sl, f_dl, fmmPtr_.get());\n    }\n\n  private:\n    std::unique_ptr<stkfmm::STKFMM> fmmPtr_; ///< Pointer to underlying STKFMM object\n    bool force_setup_tree_ = true; ///< When set, forces tree to rebuild on next call, then is cleared. Useful for\n                                   ///< testing/benchmarking\n    Eigen::MatrixXd r_sl_old_;     ///< cached 'single-layer' source positions to check for FMM tree invalidation\n    Eigen::MatrixXd r_dl_old_;     ///< cache 'double-layer' source positions to check for FMM tree invalidation\n    Eigen::MatrixXd r_trg_old_;    ///< cache target positions to check for FMM tree invalidation\n    stkfmm::KERNEL k_;             ///< Kernel enum from STKFMM that this interaction calls\n    fmm_kernel_func_t\n        kernel_func_; ///< Kernel function pointer from our own kernels namespace for the kernel this object will call\n};\n}; // namespace kernels\n\n#endif\n", "meta": {"hexsha": "da99e1c6d0f26fc59cbdae991ecaf17a3ca96937", "size": 6428, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/kernels.hpp", "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": "include/kernels.hpp", "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": "include/kernels.hpp", "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": 54.9401709402, "max_line_length": 118, "alphanum_fraction": 0.6470130678, "num_tokens": 1654, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7090191460821871, "lm_q2_score": 0.48438008427698437, "lm_q1q2_score": 0.34343475373328525}}
{"text": "#include <cstring>\n#include <cstdio>\n#include <cstdlib>\n#include <cmath>\n#include <ctime>\n#include <string>\n#include <algorithm>\n#include <pthread.h>\n#include <unordered_map>\n#include <unordered_set>\n#include <list>\n#include <vector>\n#include <tuple>\n#include \"hashing.h\"\n#include <boost/functional/hash.hpp>\nusing namespace std;\n\nconst double pi = 3.141592653589793238462643383;\n\nint ptranseThreads = 1;\nint ptranseTrainTimes = 3000;\nint nbatches = 1;\nint dimension = 50;\ndouble ptranseAlpha = 0.001;\ndouble margin = 1;\n\nstring inPath = \"data/\";\nstring outPath = \"res/\";\n\nint *lefHead, *rigHead;\nint *lefTail, *rigTail;\n\nstruct Triple {\n    int h, r, t;\n    list<pair<vector<int>, double> > pathList;\n};\n\nTriple **trainHead, **trainTail, ** trainList;\n\n// restore (h, r, t)s\nunordered_set<tuple<int, int, int>> isInTrain;\nunordered_map<pair<vector<int>, int>, double, pair_hash> pathConfidence;\n\n\nstruct cmp_head {\n    bool operator()(const Triple* const &a, const Triple* const &b) {\n        return (a->h < b->h)||(a->h == b->h && a->r < b->r)||(a->h == b->h && a->r == b->r && a->t < b->t);\n    }\n};\n\nstruct cmp_tail {\n    bool operator()(const Triple* const &a, const Triple* const &b) {\n        return (a->t < b->t)||(a->t == b->t && a->r < b->r)||(a->t == b->t && a->r == b->r && a->h < b->h);\n    }\n};\n\n/*\n    There are some math functions for the program initialization.\n*/\nunsigned long long *next_random;\n\nunsigned long long randd(int id) {\n    next_random[id] = next_random[id] * (unsigned long long)25214903917 + 11;\n    return next_random[id];\n}\n\nint rand_max(int id, int x) {\n    int res = randd(id) % x;\n    while (res<0)\n        res+=x;\n    return res;\n}\n\ndouble rand(double min, double max) {\n    return min + (max - min) * rand() / (RAND_MAX + 1.0);\n}\n\ndouble normal(double x, double miu,double sigma) {\n    return 1.0/sqrt(2*pi)/sigma*exp(-1*(x-miu)*(x-miu)/(2*sigma*sigma));\n}\n\ndouble randn(double miu,double sigma, double min ,double max) {\n    double x, y, dScope;\n    do {\n        x = rand(min,max);\n        y = normal(x,miu,sigma);\n        dScope=rand(0.0,normal(miu,miu,sigma));\n    } while (dScope > y);\n    return x;\n}\n\nvoid norm(double * con) {\n    double x = 0;\n    for (int  ii = 0; ii < dimension; ii++)\n        x += (*(con + ii)) * (*(con + ii));\n    x = sqrt(x);\n    if (x>1)\n        for (int ii=0; ii < dimension; ii++)\n            *(con + ii) /= x;\n}\n\ndouble sqr(double x){\n    return x * x;\n}\n\n/*\n    Read triples from the training file.\n*/\n\nint relationTotal, entityTotal, tripleTotal;\ndouble *relationVec, *entityVec;\n\nint ptranseBatch, ptranseLen;\ndouble res;\n\nvoid gradient(int e1_a, int e2_a, int rel_a, int e1_b, int e2_b, int rel_b) {\n    int lasta1 = e1_a * dimension;\n    int lasta2 = e2_a * dimension;\n    int lastar = rel_a * dimension;\n    int lastb1 = e1_b * dimension;\n    int lastb2 = e2_b * dimension;\n    int lastbr = rel_b * dimension;\n    for (int ii=0; ii  < dimension; ii++) {\n        double x;\n        x = (entityVec[lasta2 + ii] - entityVec[lasta1 + ii] - relationVec[lastar + ii]);\n        if (x > 0)\n            x = -ptranseAlpha;\n        else\n            x = ptranseAlpha;\n        relationVec[lastar + ii] -= x;\n        entityVec[lasta1 + ii] -= x;\n        entityVec[lasta2 + ii] += x;\n        x = (entityVec[lastb2 + ii] - entityVec[lastb1 + ii] - relationVec[lastbr + ii]);\n        if (x > 0)\n            x = ptranseAlpha;\n        else\n            x = -ptranseAlpha;\n        relationVec[lastbr + ii] -=  x;\n        entityVec[lastb1 + ii] -= x;\n        entityVec[lastb2 + ii] += x;\n    }\n}\n\ndouble calc_sum(int e1, int e2, int rel) {\n    double sum=0;\n    int last1 = e1 * dimension;\n    int last2 = e2 * dimension;\n    int lastr = rel * dimension;\n    for (int ii=0; ii < dimension; ii++) {\n                    sum += fabs(entityVec[last2 + ii] - entityVec[last1 + ii] - relationVec[lastr + ii]);\n                }\n    return sum;\n}\n\nvoid train_kb(int e1_a, int e2_a, int rel_a, int e1_b, int e2_b, int rel_b) {\n    double sum1 = calc_sum(e1_a, e2_a, rel_a);\n    double sum2 = calc_sum(e1_b, e2_b, rel_b);\n    if (sum1 + margin > sum2) {\n        res += margin + sum1 - sum2;\n        gradient(e1_a, e2_a, rel_a, e1_b, e2_b, rel_b);\n    }\n}\n\nint corrupt_head(int id, int h, int r) {\n    int lef, rig, mid, ll, rr;\n    lef = lefHead[h] - 1;\n    rig = rigHead[h];\n    while (lef + 1 < rig) {\n        mid = (lef + rig) >> 1;\n        if (trainHead[mid]->r >= r) rig = mid; else\n        lef = mid;\n    }\n    ll = rig;\n    lef = lefHead[h];\n    rig = rigHead[h] + 1;\n    while (lef + 1 < rig) {\n        mid = (lef + rig) >> 1;\n        if (trainHead[mid]->r <= r) lef = mid; else\n        rig = mid;\n    }\n    rr = lef;\n    int tmp = rand_max(id, entityTotal - (rr - ll + 1));\n    if (tmp < trainHead[ll]->t) return tmp;\n    if (tmp > trainHead[rr]->t - rr + ll - 1) return tmp + rr - ll + 1;\n    lef = ll, rig = rr + 1;\n    while (lef + 1 < rig) {\n        mid = (lef + rig) >> 1;\n        if (trainHead[mid]->t - mid + ll - 1 < tmp)\n            lef = mid;\n        else\n            rig = mid;\n    }\n    return tmp + lef - ll + 1;\n}\n\nint corrupt_tail(int id, int t, int r) {\n    int lef, rig, mid, ll, rr;\n    lef = lefTail[t] - 1;\n    rig = rigTail[t];\n    while (lef + 1 < rig) {\n        mid = (lef + rig) >> 1;\n        if (trainTail[mid]->r >= r) rig = mid; else\n        lef = mid;\n    }\n    ll = rig;\n    lef = lefTail[t];\n    rig = rigTail[t] + 1;\n    while (lef + 1 < rig) {\n        mid = (lef + rig) >> 1;\n        if (trainTail[mid]->r <= r) lef = mid; else\n        rig = mid;\n    }\n    rr = lef;\n    int tmp = rand_max(id, entityTotal - (rr - ll + 1));\n    if (tmp < trainTail[ll]->h) return tmp;\n    if (tmp > trainTail[rr]->h - rr + ll - 1) return tmp + rr - ll + 1;\n    lef = ll, rig = rr + 1;\n    while (lef + 1 < rig) {\n        mid = (lef + rig) >> 1;\n        if (trainTail[mid]->h - mid + ll - 1 < tmp)\n            lef = mid;\n        else\n            rig = mid;\n    }\n    return tmp + lef - ll + 1;\n}\n\ndouble calc_path(int r1, const vector<int>& relPath) {\n    double sum = 0;\n    for (int ii = 0; ii < dimension; ii++) {\n        double tmp = relationVec[r1 * dimension + ii];\n        for (auto &j : relPath)\n            tmp -= relationVec[j * dimension + ii];\n            // L1 norm as default\n            sum+=fabs(tmp);\n    }\n    return sum;\n}\n\nvoid gradient_path(int r1, const vector<int>& relPath, double belta) {\n    for (int ii=0; ii < dimension; ii++) {\n        double x = relationVec[r1 * dimension + ii];\n        for (auto &j : relPath)\n            x -= relationVec[j * dimension + ii];\n        if (x>0) x=1;\n            else x=-1;\n        relationVec[r1 * dimension + ii]+=belta*ptranseAlpha*x;\n        for (auto &j : relPath)\n            relationVec[j * dimension + ii]-=belta*ptranseAlpha*x;\n    }\n}\n\nvoid train_path(int rel, int relNeg, const vector<int>& relPath, double margin,double x) {\n    double sum1 = calc_path(rel,relPath);\n    double sum2 = calc_path(relNeg,relPath);\n    double lambda = 1;\n    if (sum1+margin>sum2) {\n        res+=x*lambda*(margin+sum1-sum2);\n        gradient_path(rel,relPath, -x*lambda);\n        gradient_path(relNeg,relPath, x*lambda);\n    }\n}\n\nvoid* ptransetrainMode(void *con) {\n    int id;\n    id = (unsigned long long)(con);\n    next_random[id] = rand();\n    for (int k = ptranseBatch / ptranseThreads; k >= 0; k--) {\n        int i = rand_max(id, ptranseLen);\n\n        // transe part\n        int j; // corrupted part\n        int pr = 500;\n        if (randd(id) % 1000 < pr){\n            j = corrupt_head(id, trainList[i]->h, trainList[i]->r);\n            train_kb(trainList[i]->h, trainList[i]->t, trainList[i]->r, trainList[i]->h, j, trainList[i]->r);\n        }\n        else {\n            j = corrupt_tail(id, trainList[i]->t, trainList[i]->r);\n            train_kb(trainList[i]->h, trainList[i]->t, trainList[i]->r, j, trainList[i]->t, trainList[i]->r);\n        }\n\n        // ptranse part\n        j = rand_max(id, relationTotal);\n        while (isInTrain.find(make_tuple(trainList[i]->h, j, trainList[i]->t)) != isInTrain.end())\n            j = rand_max(id, relationTotal);\n        for (auto & pathList : trainList[i]->pathList){\n            vector<int> relPath = pathList.first;\n            double pr = pathList.second;\n            double pr_path = 0;\n            if (pathConfidence.count(make_pair(relPath, trainList[i]->r))>0)\n                pr_path = pathConfidence[make_pair(relPath, trainList[i]->r)];\n            pr_path = 0.99*pr_path + 0.01;\n            train_path(trainList[i]->r, j, relPath, 2*margin, pr*pr_path);\n        }\n\n        //norm\n        norm(relationVec + dimension * trainList[i]->r);\n        norm(entityVec + dimension * trainList[i]->h);\n        norm(entityVec + dimension * trainList[i]->t);\n        norm(entityVec + dimension * j);\n    }\n}\n\nvoid* train_ptranse(void *con) {\n    ptranseLen = tripleTotal;\n    ptranseBatch = ptranseLen / nbatches;\n    next_random = (unsigned long long *)calloc(ptranseThreads, sizeof(unsigned long long));\n    for (int epoch = 0; epoch < ptranseTrainTimes; epoch++) {\n        printf(\"epoch %d started.\\n\", epoch);\n        res = 0;\n        for (int batch = 0; batch < nbatches; batch++) {\n            pthread_t *pt = (pthread_t *)malloc(ptranseThreads * sizeof(pthread_t));\n            for (int a = 0; a < ptranseThreads; a++)\n                pthread_create(&pt[a], NULL, ptransetrainMode,  (void*)a);\n            for (int a = 0; a < ptranseThreads; a++)\n                pthread_join(pt[a], NULL);\n            free(pt);\n        }\n        printf(\"epoch %d %f\\n\", epoch, res);\n    }\n}\n\nvoid init() {\n\n    FILE *fin;\n    int tmp;\n\n    // fin = fopen((inPath + \"relation2id.txt\").c_str(), \"r\");\n    // tmp = fscanf(fin, \"%d\", &relationTotal);\n    // fclose(fin);\n    relationTotal = 1345;\n    printf(\"Relations:\\t%d\\n\", relationTotal);\n\n    relationTotal <<= 1;\n    relationVec = (double *)calloc(relationTotal * dimension, sizeof(double));\n    for (int i = 0; i < relationTotal; i++) {\n        for (int ii=0; ii<dimension; ii++)\n            relationVec[i * dimension + ii] = randn(0, 1.0 / dimension, -6 / sqrt(dimension), 6 / sqrt(dimension));\n    }\n\n    // fin = fopen((inPath + \"entity2id.txt\").c_str(), \"r\");\n    // tmp = fscanf(fin, \"%d\", &entityTotal);\n    // fclose(fin);\n    entityTotal = 14951;\n    printf(\"Entities:\\t%d\\n\", entityTotal);\n\n    entityVec = (double *)calloc(entityTotal * dimension, sizeof(double));\n    for (int i = 0; i < entityTotal; i++) {\n        for (int ii=0; ii<dimension; ii++)\n            entityVec[i * dimension + ii] = randn(0, 1.0 / dimension, -6 / sqrt(dimension), 6 / sqrt(dimension));\n        norm(entityVec+i*dimension);\n    }\n    printf(\"Entities' vectors initialized.\\n\");\n\n    fin = fopen((inPath + \"train_pra.txt\").c_str(), \"r\");\n    tmp = fscanf(fin, \"%d\", &tripleTotal);\n    printf(\"Triples:\\t%d\\n\", tripleTotal);\n    trainHead = (Triple **)calloc(tripleTotal, sizeof(Triple*));\n    trainTail = (Triple **)calloc(tripleTotal, sizeof(Triple*));\n    trainList = (Triple **)calloc(tripleTotal, sizeof(Triple*));\n    tripleTotal = 0;\n    // establish new triple in advance\n    trainHead[tripleTotal] = new Triple();\n    trainTail[tripleTotal] = new Triple();\n    trainList[tripleTotal] = new Triple();\n    while (fscanf(fin, \"%d\", &trainList[tripleTotal]->h) == 1) {\n\n        //input (h, t, r)\n        tmp = fscanf(fin, \"%d\", &trainList[tripleTotal]->t);\n        tmp = fscanf(fin, \"%d\", &trainList[tripleTotal]->r);\n\n\n        //input paths\n        //input path_amount\n        int pathsAmount;\n        tmp = fscanf(fin, \"%d\", &pathsAmount);\n        //input each path\n        for(int i = 0;i<pathsAmount;i++){\n            int pathLength, pathElement;\n            double pathProbability;\n            vector<int> relPath;\n            relPath.clear();\n            tmp = fscanf(fin, \"%d\", &pathLength);\n            for(int j = 0;j<pathLength;j++){\n                tmp = fscanf(fin, \"%d\", &pathElement);\n                relPath.push_back(pathElement);\n            }\n            tmp = fscanf(fin, \"%lf\", &pathProbability);\n            trainList[tripleTotal]->pathList.push_back(make_pair(relPath, pathProbability));\n        }\n\n        //put (h, r, t) into training set\n        isInTrain.insert(make_tuple(trainList[tripleTotal]->h, trainList[tripleTotal]->r, trainList[tripleTotal]->t));\n\n        //copy trainList to trainHead trainTail\n        (*trainHead[tripleTotal]) = (*trainTail[tripleTotal]) = (*trainList[tripleTotal]);\n        tripleTotal++;\n        trainHead[tripleTotal] = new Triple();\n        trainTail[tripleTotal] = new Triple();\n        trainList[tripleTotal] = new Triple();\n\n    }\n    fclose(fin);\n\n    sort(trainHead, trainHead + tripleTotal, cmp_head());\n    sort(trainTail, trainTail + tripleTotal, cmp_tail());\n\n    lefHead = (int *)calloc(entityTotal, sizeof(int));\n    rigHead = (int *)calloc(entityTotal, sizeof(int));\n    lefTail = (int *)calloc(entityTotal, sizeof(int));\n    rigTail = (int *)calloc(entityTotal, sizeof(int));\n    memset(rigHead, -1, entityTotal * sizeof(int));\n    memset(rigTail, -1, entityTotal * sizeof(int));\n    memset(lefHead, -1, entityTotal * sizeof(int));\n    memset(lefTail, -1, entityTotal * sizeof(int));\n    // tripleTotal should be larger than 0, otherwise could cause errors.\n    lefTail[trainTail[0]->t] = 0;\n    lefHead[trainHead[0]->h] = 0;\n    for (int i = 1; i < tripleTotal; i++) {\n        if (trainTail[i]->t != trainTail[i - 1]->t) {\n            rigTail[trainTail[i - 1]->t] = i - 1;\n            lefTail[trainTail[i]->t] = i;\n        }\n        if (trainHead[i]->h != trainHead[i - 1]->h) {\n            rigHead[trainHead[i - 1]->h] = i - 1;\n            lefHead[trainHead[i]->h] = i;\n        }\n    }\n    rigHead[trainHead[tripleTotal - 1]->h] = tripleTotal - 1;\n    rigTail[trainTail[tripleTotal - 1]->t] = tripleTotal - 1;\n\n    // input confidence file\n    fin = fopen((inPath + \"confidence.txt\").c_str(), \"r\");\n    int pathLength;\n    while (fscanf(fin, \"%d\", &pathLength)==1){\n        int pathElement;\n        vector<int> relPath;\n        relPath.clear();\n        for (int i=0; i<pathLength; i++)\n        {\n            tmp = fscanf(fin, \"%d\", &pathElement);\n            relPath.push_back(pathElement);\n        }\n        int relationsAmount;\n        fscanf(fin, \"%d\", &relationsAmount);\n        for (int i=0; i<relationsAmount; i++)\n        {\n            int relation;\n            double pr;\n            tmp = fscanf(fin, \"%d%lf\", &relation, &pr);\n            pathConfidence[make_pair(relPath, relation)] = pr;\n        }\n    }\n    fclose(fin);\n    printf(\"Initialization completed.\\n\");\n}\n\nvoid destruct(){\n    for(int i = 0;i<=tripleTotal;i++){\n        delete(trainHead[i]);\n        delete(trainTail[i]);\n        delete(trainList[i]);\n    }\n}\n\nvoid out_ptranse() {\n\t\tFILE* f2 = fopen((outPath + \"relation2vec.bern\").c_str(), \"w\");\n\t\tFILE* f3 = fopen((outPath + \"entity2vec.bern\").c_str(), \"w\");\n\t\tfor (int i=0; i < relationTotal; i++) {\n\t\t\tint last = dimension * i;\n\t\t\tfor (int ii = 0; ii < dimension; ii++)\n\t\t\t\tfprintf(f2, \"%.6lf\\t\", relationVec[last + ii]);\n\t\t\tfprintf(f2,\"\\n\");\n\t\t}\n\t\tfor (int  i = 0; i < entityTotal; i++) {\n\t\t\tint last = i * dimension;\n\t\t\tfor (int ii = 0; ii < dimension; ii++)\n\t\t\t\tfprintf(f3, \"%.6lf\\t\", entityVec[last + ii] );\n\t\t\tfprintf(f3,\"\\n\");\n\t\t}\n\t\tfclose(f2);\n\t\tfclose(f3);\n}\n\nint main() {\n    init();\n    train_ptranse(NULL);\n    out_ptranse();\n    destruct();\n    return 0;\n}\n", "meta": {"hexsha": "7156ab80d737a4e1f3d8220ab08e757236e57abb", "size": 15385, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Fast-PTransE/ptranse.cpp", "max_stars_repo_name": "xw-666/Fast-TransX", "max_stars_repo_head_hexsha": "68e5b2df183a34c4ea9ff141f6ab892afa559c95", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 380.0, "max_stars_repo_stars_event_min_datetime": "2016-11-15T07:24:12.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-27T09:29:24.000Z", "max_issues_repo_path": "Fast-PTransE/ptranse.cpp", "max_issues_repo_name": "xw-666/Fast-TransX", "max_issues_repo_head_hexsha": "68e5b2df183a34c4ea9ff141f6ab892afa559c95", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 57.0, "max_issues_repo_issues_event_min_datetime": "2017-04-07T08:52:08.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-04T13:18:17.000Z", "max_forks_repo_path": "Fast-PTransE/ptranse.cpp", "max_forks_repo_name": "xw-666/Fast-TransX", "max_forks_repo_head_hexsha": "68e5b2df183a34c4ea9ff141f6ab892afa559c95", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 111.0, "max_forks_repo_forks_event_min_datetime": "2016-11-22T07:04:48.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-15T11:35:01.000Z", "avg_line_length": 31.2068965517, "max_line_length": 118, "alphanum_fraction": 0.5561910952, "num_tokens": 4596, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.709019146082187, "lm_q2_score": 0.48438008427698437, "lm_q1q2_score": 0.3434347537332852}}
{"text": "/*\n * The MIT License\n *\n * Copyright (c) 2015-2017 Parresia Research Limited, New Zealand\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// Namespace Vaango::\n#include <CCA/Components/MPM/Materials/ConstitutiveModel/ArenaSoilBanerjeeBrannon/ArenaPartiallySaturated.h>\n#include <CCA/Components/MPM/Materials/ConstitutiveModel/ArenaSoilBanerjeeBrannon/Models/ElasticModuliModelFactory.h>\n#include <CCA/Components/MPM/Materials/ConstitutiveModel/ArenaSoilBanerjeeBrannon/Models/YieldConditionFactory.h>\n\n// Namespace Uintah::\n\n#include <CCA/Components/MPM/Materials/MPMMaterial.h>\n#include <CCA/Ports/DataWarehouse.h>\n\n#include <Core/Exceptions/InvalidValue.h>\n#include <Core/Exceptions/ParameterNotFound.h>\n\n#include <Core/Grid/Box.h>\n#include <Core/Grid/Level.h>\n#include <Core/Grid/Patch.h>\n#include <Core/Grid/Task.h>\n#include <Core/Grid/Variables/NCVariable.h>\n#include <Core/Grid/Variables/NodeIterator.h>\n#include <Core/Grid/Variables/ParticleVariable.h>\n#include <Core/Grid/Variables/VarLabel.h>\n#include <Core/Grid/Variables/VarTypes.h>\n\n#include <CCA/Components/MPM/Core/MPMLabel.h>\n\n#include <Core/Malloc/Allocator.h>\n\n#include <Core/Math/Matrix3.h>\n#include <Core/Math/MinMax.h>\n#include <Core/Math/MiscMath.h>\n\n#include <Core/ProblemSpec/ProblemSpec.h>\n\n// Namespace std::\n#include <cerrno>\n#include <cfenv>\n#include <chrono>\n#include <cmath>\n#include <fstream>             \n#include <iostream>\n#include <limits>\n#include <stdexcept>\n\n// Boost\n//#include <boost/range/combine.hpp>\n//#include <boost/foreach.hpp>\n\n#define CHECK_FOR_NAN\n#define CLAMP_DEF_GRAD\n#define USE_SIMPLIFIED_CONSISTENCY_BISECTION\n//#define CHECK_FOR_NAN_EXTRA\n//#define WRITE_YIELD_SURF\n//#define CHECK_INTERNAL_VAR_EVOLUTION\n//#define DEBUG_INTERNAL_VAR_EVOLUTION\n//#define DEBUG_INTERNAL_VAR_EVOLUTION_COMPUTATION\n//#define CHECK_HYDROSTATIC_TENSION\n//#define CHECK_TENSION_STATES\n//#define CHECK_TENSION_STATES_1\n//#define CHECK_DAMAGE_ALGORITHM\n//#define CHECK_SUBSTEP\n//#define CHECK_TRIAL_STRESS\n//#define CHECK_YIELD_SURFACE_NORMAL\n//#define CHECK_FLOATING_POINT_OVERFLOW\n//#define DEBUG_YIELD_BISECTION_R\n//#define CHECK_CONSISTENCY_BISECTION_CONVERGENCE\n//#define TEST_FRACTURE_STRAIN_CRITERION\n\nusing namespace Vaango;\nusing Uintah::VarLabel;\nusing Uintah::Matrix3;\n\nconst double ArenaPartiallySaturated::one_third(1.0/3.0);\nconst double ArenaPartiallySaturated::two_third(2.0/3.0);\nconst double ArenaPartiallySaturated::four_third = 4.0/3.0;\nconst double ArenaPartiallySaturated::sqrt_two = std::sqrt(2.0);\nconst double ArenaPartiallySaturated::one_sqrt_two = 1.0/sqrt_two;\nconst double ArenaPartiallySaturated::sqrt_three = std::sqrt(3.0);\nconst double ArenaPartiallySaturated::one_sqrt_three = 1.0/sqrt_three;\nconst double ArenaPartiallySaturated::one_sixth = 1.0/6.0;\nconst double ArenaPartiallySaturated::one_ninth = 1.0/9.0;\nconst double ArenaPartiallySaturated::pi = M_PI;\nconst double ArenaPartiallySaturated::pi_fourth = 0.25*pi;\nconst double ArenaPartiallySaturated::pi_half = 0.5*pi;\nconst Matrix3 ArenaPartiallySaturated::Identity(1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0);\nconst Matrix3 ArenaPartiallySaturated::Zero(0.0);\n\n// Implementing boost::combine functionality for ArenaPartiallySaturated\nnamespace Vaango {\n  template<class Column1, class Column2>\n  std::vector< std::pair<Column1, Column2> > combine(std::vector<Column1> column1,\n                                                     std::vector<Column2> column2)\n  {\n    auto col1 = column1.begin();\n    auto col2 = column2.begin();\n    std::vector< std::pair<Column1, Column2> > zipped;\n    while ( col1 != column1.end() && col2 != column2.end() ) {\n      zipped.push_back( std::pair<Column1, Column2>(*col1, *col2) );\n      col1++; col2++;\n    }\n    return zipped;\n  }\n}\n\n// Requires the necessary input parameters CONSTRUCTORS\nArenaPartiallySaturated::ArenaPartiallySaturated(Uintah::ProblemSpecP& ps, \n                                                 Uintah::MPMFlags* mpmFlags)\n  : Uintah::ConstitutiveModel(mpmFlags)\n{\n  // Bulk and shear modulus models\n  d_elastic = Vaango::ElasticModuliModelFactory::create(ps);\n  if(!d_elastic){\n    std::ostringstream desc;\n    desc << \"**ERROR** Internal error while creating ElasticModuliModel.\" << std::endl;\n    throw Uintah::InternalError(desc.str(), __FILE__, __LINE__);\n  }\n\n  // Yield condition model\n  d_yield = Vaango::YieldConditionFactory::create(ps);\n  if(!d_yield){\n    std::ostringstream desc;\n    desc << \"**ERROR** Internal error while creating YieldConditionModel.\" << std::endl;\n    throw Uintah::InternalError(desc.str(), __FILE__, __LINE__);\n  }\n\n  // Get initial porosity and saturation\n  ps->require(\"initial_porosity\",        d_fluidParam.phi0);       // Initial porosity\n  ps->require(\"initial_saturation\",      d_fluidParam.Sw0);        // Initial water saturation\n  ps->require(\"initial_fluid_pressure\",  d_fluidParam.pbar_w0);    // Initial fluid pressure\n\n  // The porosity of the reference material used to calibrate the modulus and crush curve models\n  ps->getWithDefault(\"reference_porosity\", d_fluidParam.phi_ref, d_fluidParam.phi0);    \n\n  // Algorithmic parameters\n  ps->getWithDefault(\"yield_surface_radius_scaling_factor\", \n                     d_cm.yield_scale_fac, 1.0);\n  ps->getWithDefault(\"consistency_bisection_tolerance\",\n                     d_cm.consistency_bisection_tolerance, 1.0e-4);   \n  d_cm.max_bisection_iterations = \n    (int) std::ceil(-10.0*std::log(d_cm.consistency_bisection_tolerance));\n  ps->getWithDefault(\"subcycling_characteristic_number\",\n                     d_cm.subcycling_characteristic_number, 256);    // allowable subcycles\n  ps->getWithDefault(\"use_disaggregation_algorithm\",\n                     d_cm.use_disaggregation_algorithm, false);\n\n  // Get the hydrostatic compression model parameters\n  ps->require(\"p0\",     d_crushParam.p0);  \n  ps->require(\"p1\",     d_crushParam.p1); \n  ps->require(\"p1_sat\", d_crushParam.p1_sat);\n  ps->getWithDefault(\"p1_density_scale_fac\", d_crushParam.p1_density_scale_fac, 0.0);\n  ps->require(\"p2\",     d_crushParam.p2); \n  ps->require(\"p3\",     d_crushParam.p3);\n \n  // Make sure p0 is at least 1000 pressure units\n  d_crushParam.p0 = std::max(d_crushParam.p0, 1000.0);\n \n  // Compute modulus and compressive strength scaling factors\n  // Using Pabst and Gregorova, 2015, Materials Science and Tech, 31:15, 1801.\n  double phi_0 =   d_fluidParam.phi0;\n  double phi_ref = d_fluidParam.phi_ref;\n  double density_fac = d_crushParam.p1_density_scale_fac;\n  d_modulus_scale_fac = std::exp(-phi_0/(1.0 - phi_0) +  phi_ref/(1.0 - phi_ref));\n  d_strength_scale_fac = std::exp(density_fac*d_modulus_scale_fac*(d_modulus_scale_fac - 1.0));\n\n  // Do density scaling\n  d_crushParam.p1 *= d_strength_scale_fac;\n\n  // Get the damage model parameters\n  ps->getWithDefault(\"do_damage\",                    d_cm.do_damage, false);\n  ps->getWithDefault(\"fspeed\",                       d_damageParam.fSpeed, 1.0e-9);\n  ps->getWithDefault(\"time_at_failure\",              d_damageParam.tFail,  1.0e9);\n  ps->getWithDefault(\"eq_plastic_strain_at_failure\", d_damageParam.ep_f_eq, 1.0e9);\n\n  // MPM needs three functions to interact with ICE in MPMICE\n  // 1) p = f(rho) 2) rho = g(p) 3) C = 1/K(rho)\n  // Because the ArenaPartiallySaturated bulk modulus model does not have any closed\n  // form expressions for these functions, we use a Murnaghan equation of state\n  // with parameters K_0 and n = K_0'.  These parameters are read in here.\n  // **WARNING** The default values are for Mason sand.\n  ps->getWithDefault(\"K0_Murnaghan_EOS\", d_cm.K0_Murnaghan_EOS, 2.5e8);\n  ps->getWithDefault(\"n_Murnaghan_EOS\", d_cm.n_Murnaghan_EOS, 13);\n\n  checkInputParameters();\n\n  initializeLocalMPMLabels();\n}\n\nvoid \nArenaPartiallySaturated::checkInputParameters()\n{\n  \n  if (d_cm.consistency_bisection_tolerance < 1.0e-16 || d_cm.consistency_bisection_tolerance > 1.0e-2) {\n    std::ostringstream warn;\n    warn << \"Consistency bisection tolerance should be in range [1.0e-16, 1.0e-2].  Default = 1.0e-4\"\n         << std::endl;\n    throw Uintah::ProblemSetupException(warn.str(), __FILE__, __LINE__);\n  }\n\n  if (d_cm.subcycling_characteristic_number < 1) {\n    std::ostringstream warn;\n    warn << \"Subcycling characteristic number should be > 1. Default = 256\"\n         << std::endl;\n    throw Uintah::ProblemSetupException(warn.str(), __FILE__, __LINE__);\n  }\n\n  if (d_cm.yield_scale_fac < 1.0 || d_cm.yield_scale_fac > 1.0e6) {\n    std::ostringstream warn;\n    warn << \"Yield surface scaling factor should be between 1 and 1.0e6. Default = 1.\"\n         << std::endl;\n    throw Uintah::ProblemSetupException(warn.str(), __FILE__, __LINE__);\n  }\n\n  // *TODO*  Add checks for the other parameters\n}\n\n// Initialize all labels of the particle variables associated with \n// ArenaPartiallySaturated.\nvoid \nArenaPartiallySaturated::initializeLocalMPMLabels()\n{\n  pElasticVolStrainLabel = VarLabel::create(\"p.elasticVolStrain\",\n    Uintah::ParticleVariable<double>::getTypeDescription());\n  pElasticVolStrainLabel_preReloc = VarLabel::create(\"p.elasticVolStrain+\",\n    Uintah::ParticleVariable<double>::getTypeDescription());\n\n  pStressQSLabel = VarLabel::create(\"p.stressQS\",\n    Uintah::ParticleVariable<Matrix3>::getTypeDescription());\n  pStressQSLabel_preReloc = VarLabel::create(\"p.stressQS+\",\n    Uintah::ParticleVariable<Matrix3>::getTypeDescription());\n\n  pPlasticStrainLabel = Uintah::VarLabel::create(\"p.plasticStrain\",\n    Uintah::ParticleVariable<Uintah::Matrix3>::getTypeDescription());\n  pPlasticStrainLabel_preReloc = Uintah::VarLabel::create(\"p.plasticStrain+\",\n    Uintah::ParticleVariable<Uintah::Matrix3>::getTypeDescription());\n\n  pPlasticCumEqStrainLabel = Uintah::VarLabel::create(\"p.plasticCumEqStrain\",\n    Uintah::ParticleVariable<double>::getTypeDescription());\n  pPlasticCumEqStrainLabel_preReloc = Uintah::VarLabel::create(\"p.plasticCumEqStrain+\",\n    Uintah::ParticleVariable<double>::getTypeDescription());\n\n  pPlasticVolStrainLabel = Uintah::VarLabel::create(\"p.plasticVolStrain\",\n    Uintah::ParticleVariable<double>::getTypeDescription());\n  pPlasticVolStrainLabel_preReloc = Uintah::VarLabel::create(\"p.plasticVolStrain+\",\n    Uintah::ParticleVariable<double>::getTypeDescription());\n\n  pBackstressLabel = Uintah::VarLabel::create(\"p.porePressure\",\n    Uintah::ParticleVariable<Uintah::Matrix3>::getTypeDescription());\n  pBackstressLabel_preReloc = Uintah::VarLabel::create(\"p.porePressure+\",\n    Uintah::ParticleVariable<Uintah::Matrix3>::getTypeDescription());\n\n  pPorosityLabel = Uintah::VarLabel::create(\"p.porosity\",\n    Uintah::ParticleVariable<double>::getTypeDescription());\n  pPorosityLabel_preReloc = Uintah::VarLabel::create(\"p.porosity+\",\n    Uintah::ParticleVariable<double>::getTypeDescription());\n\n  pSaturationLabel = Uintah::VarLabel::create(\"p.saturation\",\n    Uintah::ParticleVariable<double>::getTypeDescription());\n  pSaturationLabel_preReloc = Uintah::VarLabel::create(\"p.saturation+\",\n    Uintah::ParticleVariable<double>::getTypeDescription());\n      \n  pCapXLabel = Uintah::VarLabel::create(\"p.capX\",\n    Uintah::ParticleVariable<double>::getTypeDescription());\n  pCapXLabel_preReloc = Uintah::VarLabel::create(\"p.capX+\",\n    Uintah::ParticleVariable<double>::getTypeDescription());\n\n  pP3Label = Uintah::VarLabel::create(\"p.p3\",\n    Uintah::ParticleVariable<double>::getTypeDescription());\n  pP3Label_preReloc = Uintah::VarLabel::create(\"p.p3+\",\n    Uintah::ParticleVariable<double>::getTypeDescription());\n\n  pCoherenceLabel = Uintah::VarLabel::create(\"p.COHER\",\n    Uintah::ParticleVariable<double>::getTypeDescription());\n  pCoherenceLabel_preReloc = Uintah::VarLabel::create(\"p.COHER+\",\n    Uintah::ParticleVariable<double>::getTypeDescription());\n\n  pTGrowLabel = Uintah::VarLabel::create(\"p.TGROW\",\n    Uintah::ParticleVariable<double>::getTypeDescription());\n  pTGrowLabel_preReloc = Uintah::VarLabel::create(\"p.TGROW+\",\n    Uintah::ParticleVariable<double>::getTypeDescription());\n}\n\n// DESTRUCTOR\nArenaPartiallySaturated::~ArenaPartiallySaturated()\n{\n  VarLabel::destroy(pElasticVolStrainLabel);              //Elastic Volumetric Strain\n  VarLabel::destroy(pElasticVolStrainLabel_preReloc);\n  VarLabel::destroy(pStressQSLabel);\n  VarLabel::destroy(pStressQSLabel_preReloc);\n\n  VarLabel::destroy(pPlasticStrainLabel);\n  VarLabel::destroy(pPlasticStrainLabel_preReloc);\n  VarLabel::destroy(pPlasticCumEqStrainLabel);\n  VarLabel::destroy(pPlasticCumEqStrainLabel_preReloc);\n  VarLabel::destroy(pPlasticVolStrainLabel);\n  VarLabel::destroy(pPlasticVolStrainLabel_preReloc);\n  VarLabel::destroy(pBackstressLabel);\n  VarLabel::destroy(pBackstressLabel_preReloc);\n  VarLabel::destroy(pPorosityLabel);\n  VarLabel::destroy(pPorosityLabel_preReloc);\n  VarLabel::destroy(pSaturationLabel);\n  VarLabel::destroy(pSaturationLabel_preReloc);\n  VarLabel::destroy(pCapXLabel);\n  VarLabel::destroy(pCapXLabel_preReloc);\n\n  VarLabel::destroy(pP3Label);\n  VarLabel::destroy(pP3Label_preReloc);\n  VarLabel::destroy(pCoherenceLabel);\n  VarLabel::destroy(pCoherenceLabel_preReloc);\n  VarLabel::destroy(pTGrowLabel);\n  VarLabel::destroy(pTGrowLabel_preReloc);\n\n  delete d_yield;\n  delete d_elastic;\n}\n\n//adds problem specification values to checkpoint data for restart\nvoid \nArenaPartiallySaturated::outputProblemSpec(Uintah::ProblemSpecP& ps, bool output_cm_tag)\n{\n  Uintah::ProblemSpecP cm_ps = ps;\n  if (output_cm_tag) {\n    cm_ps = ps->appendChild(\"constitutive_model\");\n    cm_ps->setAttribute(\"type\",\"ArenaSoil\");\n  }\n\n  d_elastic->outputProblemSpec(cm_ps);\n  d_yield->outputProblemSpec(cm_ps);\n\n  cm_ps->appendElement(\"reference_porosity\",     d_fluidParam.phi_ref);\n  cm_ps->appendElement(\"initial_porosity\",       d_fluidParam.phi0);\n  cm_ps->appendElement(\"initial_saturation\",     d_fluidParam.Sw0);\n  cm_ps->appendElement(\"initial_fluid_pressure\", d_fluidParam.pbar_w0);\n\n  cm_ps->appendElement(\"yield_surface_radius_scaling_factor\", d_cm.yield_scale_fac);\n  cm_ps->appendElement(\"consistency_bisection_tolerance\",  d_cm.consistency_bisection_tolerance);\n  cm_ps->appendElement(\"subcycling_characteristic_number\", d_cm.subcycling_characteristic_number);\n  cm_ps->appendElement(\"use_disaggregation_algorithm\",     d_cm.use_disaggregation_algorithm);\n\n  cm_ps->appendElement(\"p0\",     d_crushParam.p0);\n  cm_ps->appendElement(\"p1\",     d_crushParam.p1/d_strength_scale_fac);\n  cm_ps->appendElement(\"p1_density_scale_fac\",     d_crushParam.p1_density_scale_fac);\n  cm_ps->appendElement(\"p1_sat\", d_crushParam.p1_sat);\n  cm_ps->appendElement(\"p2\",     d_crushParam.p2);\n  cm_ps->appendElement(\"p3\",     d_crushParam.p3);\n\n  // Get the damage model parameters\n  cm_ps->appendElement(\"do_damage\",                    d_cm.do_damage);\n  cm_ps->appendElement(\"fspeed\",                       d_damageParam.fSpeed);\n  cm_ps->appendElement(\"time_at_failure\",              d_damageParam.tFail);\n  cm_ps->appendElement(\"eq_plastic_strain_at_failure\", d_damageParam.ep_f_eq);\n\n  // MPMICE Murnaghan EOS\n  cm_ps->appendElement(\"K0_Murnaghan_EOS\", d_cm.K0_Murnaghan_EOS);\n  cm_ps->appendElement(\"n_Murnaghan_EOS\",  d_cm.n_Murnaghan_EOS);\n}\n\nArenaPartiallySaturated* \nArenaPartiallySaturated::clone()\n{\n  return scinew ArenaPartiallySaturated(*this);\n}\n\n//When a particle is pushed from patch to patch, carry information needed for the particle\nvoid \nArenaPartiallySaturated::addParticleState(std::vector<const VarLabel*>& from,\n                                          std::vector<const VarLabel*>& to)\n{\n  // Push back all the particle variables associated with ArenaSoil.\n  // Important to keep from and to lists in same order!\n  from.push_back(pElasticVolStrainLabel);\n  to.push_back(pElasticVolStrainLabel_preReloc);\n\n  from.push_back(pStressQSLabel);\n  to.push_back(pStressQSLabel_preReloc);\n\n  // Add the particle state for the internal variable models\n  from.push_back(pPlasticStrainLabel);\n  to.push_back(pPlasticStrainLabel_preReloc);\n\n  from.push_back(pPlasticCumEqStrainLabel);\n  to.push_back(pPlasticCumEqStrainLabel_preReloc);\n\n  from.push_back(pPlasticVolStrainLabel);\n  to.push_back(pPlasticVolStrainLabel_preReloc);\n\n  from.push_back(pBackstressLabel);\n  to.push_back(pBackstressLabel_preReloc);\n\n  from.push_back(pPorosityLabel);\n  to.push_back(pPorosityLabel_preReloc);\n\n  from.push_back(pSaturationLabel);\n  to.push_back(pSaturationLabel_preReloc);\n\n  from.push_back(pCapXLabel);\n  to.push_back(pCapXLabel_preReloc);\n\n  // For disaggregation and failure\n  from.push_back(pP3Label);\n  to.push_back(pP3Label_preReloc);\n\n  // For damage\n  from.push_back(pCoherenceLabel);\n  to.push_back(pCoherenceLabel_preReloc);\n\n  from.push_back(pTGrowLabel);\n  to.push_back(pTGrowLabel_preReloc);\n\n  // Add the particle state for the yield condition model\n  d_yield->addParticleState(from, to);\n\n}\n\n/*!------------------------------------------------------------------------*/\nvoid \nArenaPartiallySaturated::addInitialComputesAndRequires(Uintah::Task* task,\n                                                       const Uintah::MPMMaterial* matl, \n                                                       const Uintah::PatchSet* patch) const\n{\n  // Add the computes and requires that are common to all explicit\n  // constitutive models.  The method is defined in the ConstitutiveModel\n  // base class.\n  const Uintah::MaterialSubset* matlset = matl->thisMaterial();\n\n  // Other constitutive model and input dependent computes and requires\n  task->computes(pElasticVolStrainLabel, matlset);\n  task->computes(pStressQSLabel,         matlset);\n\n  // Add internal evolution variables\n  task->computes(pPlasticStrainLabel,    matlset);\n  task->computes(pPlasticCumEqStrainLabel,  matlset);\n  task->computes(pPlasticVolStrainLabel, matlset);\n  task->computes(pBackstressLabel,       matlset);\n  task->computes(pPorosityLabel,         matlset);\n  task->computes(pSaturationLabel,       matlset);\n  task->computes(pCapXLabel,             matlset);\n  task->computes(pP3Label,               matlset);\n  task->computes(pCoherenceLabel,        matlset);\n  task->computes(pTGrowLabel,            matlset);\n\n  // Add yield function variablity computes\n  d_yield->addInitialComputesAndRequires(task, matl, patch);\n\n}\n\n/*!------------------------------------------------------------------------*/\nvoid \nArenaPartiallySaturated::initializeCMData(const Uintah::Patch* patch,\n                                          const Uintah::MPMMaterial* matl,\n                                          Uintah::DataWarehouse* new_dw)\n{\n  // Add the initial porosity and saturation to the parameter dictionary\n  ParameterDict allParams;\n  allParams[\"phi0\"] = d_fluidParam.phi0;\n  allParams[\"Sw0\"] = d_fluidParam.Sw0;\n  allParams[\"pbar_w0\"] = d_fluidParam.pbar_w0;\n\n  // Get the particles in the current patch\n  Uintah::ParticleSubset* pset = new_dw->getParticleSubset(matl->getDWIndex(),patch);\n\n  // Get the particle volume and mass\n  Uintah::constParticleVariable<double> pVolume, pMass;\n  new_dw->get(pVolume, lb->pVolumeLabel, pset);\n  new_dw->get(pMass,   lb->pMassLabel,   pset);\n\n  // Initialize variables for yield function parameter variability\n  d_yield->initializeLocalVariables(patch, pset, new_dw, pVolume);\n\n  ParameterDict yieldParams = d_yield->getParameters();\n  allParams.insert(yieldParams.begin(), yieldParams.end());\n  proc0cout << \"ArenaPartSat Model parameters are: \" << std::endl;\n  for (auto param : allParams) {\n    proc0cout << \"\\t \\t\" << param.first << \" \" << param.second << std::endl;\n  }\n\n  // Initialize variables for internal variables (needs yield function initialized first)\n  initializeInternalVariables(patch, matl, pset, new_dw, allParams);\n\n  // Now initialize the other variables\n  Uintah::ParticleVariable<double>  pdTdt, pCoherence, pTGrow;\n  Uintah::ParticleVariable<Matrix3> pStress, pDefGrad;\n  Uintah::ParticleVariable<double>  pElasticVolStrain; // Elastic Volumetric Strain\n  Uintah::ParticleVariable<Matrix3> pStressQS;\n\n  new_dw->allocateAndPut(pdTdt,       lb->pdTdtLabel,               pset);\n  new_dw->allocateAndPut(pDefGrad,    lb->pDeformationMeasureLabel, pset);\n  new_dw->allocateAndPut(pStress,     lb->pStressLabel,             pset);\n\n  new_dw->allocateAndPut(pElasticVolStrain, pElasticVolStrainLabel, pset);\n  new_dw->allocateAndPut(pStressQS,         pStressQSLabel,         pset);\n  new_dw->allocateAndPut(pCoherence,        pCoherenceLabel,        pset);\n  new_dw->allocateAndPut(pTGrow,            pTGrowLabel,            pset);\n\n  // To fix : For a material that is initially stressed we need to\n  // modify the stress tensors to comply with the initial stress state\n  for(auto iter = pset->begin(); iter != pset->end(); iter++){\n    pdTdt[*iter]             = 0.0;\n    pDefGrad[*iter]          = Identity;\n    pStress[*iter]           = allParams[\"pbar_w0\"]*Identity;\n    pElasticVolStrain[*iter] = 0.0;\n    pStressQS[*iter]         = pStress[*iter];\n\n    // Initialize damage parameters\n    pCoherence[*iter]        = 1.0;\n    pTGrow[*iter]            = 0.0;\n  }\n\n  // Compute timestep\n  computeStableTimeStep(patch, matl, new_dw);\n}\n\nvoid \nArenaPartiallySaturated::initializeInternalVariables(const Uintah::Patch* patch,\n                                                     const Uintah::MPMMaterial* matl,\n                                                     Uintah::ParticleSubset* pset,\n                                                     Uintah::DataWarehouse* new_dw,\n                                                     ParameterDict& params)\n{\n  Uintah::constParticleVariable<double> pMass, pVolume;\n  new_dw->get(pVolume, lb->pVolumeLabel, pset);\n  new_dw->get(pMass,   lb->pMassLabel,   pset);\n\n  Uintah::ParticleVariable<Matrix3> pPlasticStrain;\n  Uintah::ParticleVariable<Matrix3> pBackstress;\n  Uintah::ParticleVariable<double>  pPlasticCumEqStrain, pPlasticVolStrain;\n  Uintah::ParticleVariable<double>  pPorosity, pSaturation;\n  Uintah::ParticleVariable<double>  pCapX, pP3;\n  new_dw->allocateAndPut(pPlasticStrain,    pPlasticStrainLabel,    pset);\n  new_dw->allocateAndPut(pPlasticCumEqStrain,  pPlasticCumEqStrainLabel,  pset);\n  new_dw->allocateAndPut(pPlasticVolStrain, pPlasticVolStrainLabel, pset);\n  new_dw->allocateAndPut(pBackstress,       pBackstressLabel,       pset);\n  new_dw->allocateAndPut(pPorosity,         pPorosityLabel,         pset);\n  new_dw->allocateAndPut(pSaturation,       pSaturationLabel,       pset);\n  new_dw->allocateAndPut(pCapX,             pCapXLabel,             pset);\n  new_dw->allocateAndPut(pP3,               pP3Label,               pset);\n\n  /* Need these if we are to save pKappa */\n  /*\n    double PEAKI1;\n    double CR;\n    try {\n    PEAKI1 = params.at(\"PEAKI1\");\n    CR = params.at(\"CR\");\n    } catch (std::out_of_range) {\n    std::ostringstream err;\n    err << \"**ERROR** Could not find yield parameters PEAKI1, CR\" << std::endl;\n    err << \"\\t Available parameters are:\" << std::endl;\n    for (auto param : params) {\n    err << \"\\t \\t\" << param.first << \" \" << param.second << std::endl;\n    throw Uintah::InternalError(err.str(), __FILE__, __LINE__);\n    }\n    }\n  */\n\n  double pbar_w0 = d_fluidParam.pbar_w0;\n  double phi0    = d_fluidParam.phi0;\n  double Sw0     = d_fluidParam.Sw0;\n  double p0      = d_crushParam.p0;\n  double p1_sat  = d_crushParam.p1_sat;\n  for (auto iter = pset->begin(); iter != pset->end(); iter++) {\n\n    pPlasticStrain[*iter].set(0.0);\n    pPlasticCumEqStrain[*iter] = 0.0;\n    pPlasticVolStrain[*iter] = 0.0;\n\n    if (pbar_w0 > 0.0) {\n      pBackstress[*iter]  = (-pbar_w0)*Identity;\n    } else {\n      pBackstress[*iter]  = Zero;\n    }\n    pPorosity[*iter]    = d_fluidParam.phi0;\n    pSaturation[*iter]  = d_fluidParam.Sw0;\n\n    double ep_v_bar = 0.0;\n    \n    // Calculate p3\n    double p3 = -std::log(1.0 - phi0);\n    if (d_cm.use_disaggregation_algorithm) {\n      p3 = -std::log(pMass[*iter]/(pVolume[*iter]*(matl->getInitialDensity()))*(1.0 - phi0));\n    }\n    pP3[*iter] = p3;\n\n    // Calcuate the drained hydrostatic strength\n    double Xbar_d = 0.0, dXbar_d = 0.0;\n    computeDrainedHydrostaticStrengthAndDeriv(ep_v_bar, p3, Xbar_d, dXbar_d);\n    if (Sw0 > 0.0) {\n      double Xbar_eff = p0 + (1.0 - Sw0 + p1_sat*Sw0)*(Xbar_d - p0);\n      double Xbar = Xbar_eff + 3.0*pbar_w0;\n      pCapX[*iter] = -Xbar;\n    } else {\n      pCapX[*iter] = -Xbar_d;\n    }\n    //std::cout << \"pCapX = \" << pCapX[*iter] << std::endl;\n  }\n}\n\n\n// Compute stable timestep based on both the particle velocities\n// and wave speed\nvoid \nArenaPartiallySaturated::computeStableTimeStep(const Uintah::Patch* patch,\n                                               const Uintah::MPMMaterial* matl,\n                                               Uintah::DataWarehouse* new_dw)\n{\n  int matID = matl->getDWIndex();\n\n  // Compute initial elastic moduli\n  ElasticModuli moduli = d_elastic->getInitialElasticModuli();\n  double bulk = moduli.bulkModulus;\n  double shear = moduli.shearModulus;\n\n  // Scale moduli using reference porosity (proxy for reference density)\n  bulk *= d_modulus_scale_fac;\n  shear *= d_modulus_scale_fac;\n\n  // Initialize wave speed\n  double c_dil = std::numeric_limits<double>::min();\n  Uintah::Vector dx = patch->dCell();\n  Uintah::Vector WaveSpeed(c_dil, c_dil, c_dil);\n\n  // Get the particles in the current patch\n  Uintah::ParticleSubset* pset = new_dw->getParticleSubset(matID, patch);\n\n  // Get particles mass, volume, and velocity\n  Uintah::constParticleVariable<double> pMass, pVolume;\n  Uintah::constParticleVariable<Uintah::long64> pParticleID;\n  Uintah::constParticleVariable<Uintah::Vector> pVelocity;\n\n  new_dw->get(pMass,       lb->pMassLabel,       pset);\n  new_dw->get(pVolume,     lb->pVolumeLabel,     pset);\n  new_dw->get(pParticleID, lb->pParticleIDLabel, pset);\n  new_dw->get(pVelocity,   lb->pVelocityLabel,   pset);\n\n  // loop over the particles in the patch\n  for (auto iter = pset->begin(); iter != pset->end(); iter++) {\n\n    Uintah::particleIndex idx = *iter;\n\n    // Compute wave speed + particle velocity at each particle,\n    // store the maximum\n    c_dil = std::sqrt((bulk + four_third*shear)*(pVolume[idx]/pMass[idx]));\n\n    //std::cout << \"K = \" << bulk << \" G = \" << shear << \" c_dil = \" << c_dil << std::endl;\n    WaveSpeed = Uintah::Vector(Uintah::Max(c_dil+std::abs(pVelocity[idx].x()), WaveSpeed.x()),\n                               Uintah::Max(c_dil+std::abs(pVelocity[idx].y()), WaveSpeed.y()),\n                               Uintah::Max(c_dil+std::abs(pVelocity[idx].z()), WaveSpeed.z()));\n  }\n\n  // Compute the stable timestep based on maximum value of\n  // \"wave speed + particle velocity\"\n  WaveSpeed = dx/WaveSpeed;\n  double delT_new = WaveSpeed.minComponent();\n  new_dw->put(Uintah::delt_vartype(delT_new), lb->delTLabel, patch->getLevel());\n}\n\n/**\n * Added computes/requires for computeStressTensor\n */\nvoid ArenaPartiallySaturated::addComputesAndRequires(Uintah::Task* task,\n                                                     const Uintah::MPMMaterial* matl,\n                                                     const Uintah::PatchSet* patches ) const\n{\n  // Add the computes and requires that are common to all explicit\n  // constitutive models.  The method is defined in the ConstitutiveModel\n  // base class.\n  const Uintah::MaterialSubset* matlset = matl->thisMaterial();\n  addSharedCRForHypoExplicit(task, matlset, patches);\n  task->requires(Uintah::Task::OldDW, lb->pParticleIDLabel,   matlset, Uintah::Ghost::None);\n  task->requires(Uintah::Task::OldDW, pElasticVolStrainLabel, matlset, Uintah::Ghost::None);\n  task->requires(Uintah::Task::OldDW, pStressQSLabel,         matlset, Uintah::Ghost::None);\n  task->computes(pElasticVolStrainLabel_preReloc, matlset);\n  task->computes(pStressQSLabel_preReloc,         matlset);\n\n  // Add yield Function computes and requires\n  d_yield->addComputesAndRequires(task, matl, patches);\n\n  // Add internal variable computes and requires\n  task->requires(Uintah::Task::OldDW, pPlasticStrainLabel,       matlset, Uintah::Ghost::None);\n  task->requires(Uintah::Task::OldDW, pPlasticCumEqStrainLabel,  matlset, Uintah::Ghost::None);\n  task->requires(Uintah::Task::OldDW, pPlasticVolStrainLabel,    matlset, Uintah::Ghost::None);\n  task->requires(Uintah::Task::OldDW, pBackstressLabel,          matlset, Uintah::Ghost::None);\n  task->requires(Uintah::Task::OldDW, pPorosityLabel,            matlset, Uintah::Ghost::None);\n  task->requires(Uintah::Task::OldDW, pSaturationLabel,          matlset, Uintah::Ghost::None);\n  task->requires(Uintah::Task::OldDW, pCapXLabel,                matlset, Uintah::Ghost::None);\n  task->computes(pPlasticStrainLabel_preReloc,         matlset);\n  task->computes(pPlasticCumEqStrainLabel_preReloc,    matlset);\n  task->computes(pPlasticVolStrainLabel_preReloc,      matlset);\n  task->computes(pBackstressLabel_preReloc,            matlset);\n  task->computes(pPorosityLabel_preReloc,              matlset);\n  task->computes(pSaturationLabel_preReloc,            matlset);\n  task->computes(pCapXLabel_preReloc,                  matlset);\n\n  // Add damage variable computes and requires\n  task->requires(Uintah::Task::OldDW, lb->pLocalizedMPMLabel, matlset, Uintah::Ghost::None);\n  task->requires(Uintah::Task::OldDW, pP3Label,               matlset, Uintah::Ghost::None);\n  task->requires(Uintah::Task::OldDW, pCoherenceLabel,        matlset, Uintah::Ghost::None);\n  task->requires(Uintah::Task::OldDW, pTGrowLabel,            matlset, Uintah::Ghost::None);\n\n  task->computes(lb->pLocalizedMPMLabel_preReloc, matlset);\n  task->computes(pP3Label_preReloc,               matlset);\n  task->computes(pCoherenceLabel_preReloc,        matlset);\n  task->computes(pTGrowLabel_preReloc,            matlset);\n}\n\n// ------------------------------------- BEGIN COMPUTE STRESS TENSOR FUNCTION\n/**\n *  ArenaPartiallySaturated::computeStressTensor \n *  is the core of the ArenaPartiallySaturated model which computes\n *  the updated stress at the end of the current timestep along with all other\n *  required data such plastic strain, elastic strain, cap position, etc.\n */\nvoid \nArenaPartiallySaturated::computeStressTensor(const Uintah::PatchSubset* patches,\n                                             const Uintah::MPMMaterial* matl,\n                                             Uintah::DataWarehouse* old_dw,\n                                             Uintah::DataWarehouse* new_dw)\n{\n  // Get the yield parameter variable labels\n  std::vector<std::string> pYieldParamVarLabels = d_yield->getLocalVariableLabels();\n\n  // Global loop over each patch\n  for(int p=0;p<patches->size();p++){\n\n    // Declare and initial value assignment for some variables\n    const Uintah::Patch* patch = patches->get(p);\n\n    // Initialize wave speed\n    double c_dil = std::numeric_limits<double>::min();\n    Uintah::Vector WaveSpeed(c_dil, c_dil, c_dil);\n    Uintah::Vector dx = patch->dCell();\n\n    // Initialize strain energy\n    double se = 0.0;  \n\n    // Get particle subset for the current patch\n    int matID = matl->getDWIndex();\n    Uintah::ParticleSubset* pset = old_dw->getParticleSubset(matID, patch);\n\n    // Get the yield condition parameter variables\n    std::vector<Uintah::constParticleVariable<double> > pYieldParamVars = \n      d_yield->getLocalVariables(pset, old_dw);\n\n    // Get the internal variables\n    Uintah::constParticleVariable<double>          pEpv, pEpeq_old, pCapX, pP3; \n    Uintah::constParticleVariable<double>          pPorosity_old, pSaturation_old;\n    Uintah::constParticleVariable<Uintah::Matrix3> pEp, pBackstress_old; \n    old_dw->get(pEp,               pPlasticStrainLabel,       pset);\n    old_dw->get(pEpeq_old,         pPlasticCumEqStrainLabel,  pset);\n    old_dw->get(pEpv,              pPlasticVolStrainLabel,    pset);\n    old_dw->get(pBackstress_old,   pBackstressLabel,          pset); \n    old_dw->get(pPorosity_old,     pPorosityLabel,            pset); \n    old_dw->get(pSaturation_old,   pSaturationLabel,          pset); \n    old_dw->get(pCapX,             pCapXLabel,                pset);\n\n    // Allocate and put internal variables\n    Uintah::ParticleVariable<Uintah::Matrix3> pEp_new, pBackstress_new;\n    Uintah::ParticleVariable<double>  pEpv_new, pEpeq_new, pCapX_new;\n    Uintah::ParticleVariable<double>  pPorosity_new, pSaturation_new;\n    new_dw->allocateAndPut(pEp_new,         pPlasticStrainLabel_preReloc,       pset);\n    new_dw->allocateAndPut(pEpeq_new,       pPlasticCumEqStrainLabel_preReloc,  pset);\n    new_dw->allocateAndPut(pEpv_new,        pPlasticVolStrainLabel_preReloc,    pset);\n    new_dw->allocateAndPut(pBackstress_new, pBackstressLabel_preReloc,          pset);\n    new_dw->allocateAndPut(pPorosity_new,   pPorosityLabel_preReloc,            pset);\n    new_dw->allocateAndPut(pSaturation_new, pSaturationLabel_preReloc,          pset);\n    new_dw->allocateAndPut(pCapX_new,       pCapXLabel_preReloc,                pset);\n    \n    // Get the damage variables\n    Uintah::constParticleVariable<int>     pLocalized_old;\n    Uintah::constParticleVariable<double>  pP3_old, pCoherence_old, pTGrow_old; \n\n    old_dw->get(pLocalized_old,        lb->pLocalizedMPMLabel, pset); \n    old_dw->get(pP3_old,               pP3Label,               pset);\n    old_dw->get(pCoherence_old,        pCoherenceLabel,        pset);\n    old_dw->get(pTGrow_old,            pTGrowLabel,            pset);\n\n    // Allocate and put the damage variables\n    Uintah::ParticleVariable<int>     pLocalized_new;\n    Uintah::ParticleVariable<double>  pP3_new, pCoherence_new, pTGrow_new;\n\n    new_dw->allocateAndPut(pLocalized_new,  lb->pLocalizedMPMLabel_preReloc, pset);\n    new_dw->allocateAndPut(pP3_new,         pP3Label_preReloc,               pset);\n    new_dw->allocateAndPut(pCoherence_new,  pCoherenceLabel_preReloc,        pset);\n    new_dw->allocateAndPut(pTGrow_new,      pTGrowLabel_preReloc,            pset);\n\n    // Get the particle variables\n    Uintah::delt_vartype                   delT;\n    Uintah::constParticleVariable<double>  pMass,           //used for stable timestep\n      pElasticVolStrain;\n    Uintah::constParticleVariable<Uintah::long64>  pParticleID;\n    Uintah::constParticleVariable<Uintah::Vector>  pVelocity;\n    Uintah::constParticleVariable<Uintah::Matrix3> pDefGrad,\n      pStress_old, pStressQS_old;\n\n    old_dw->get(delT,            lb->delTLabel,   getLevel(patches));\n    old_dw->get(pMass,           lb->pMassLabel,               pset);\n    old_dw->get(pParticleID,     lb->pParticleIDLabel,         pset);\n    old_dw->get(pVelocity,       lb->pVelocityLabel,           pset);\n    old_dw->get(pDefGrad,        lb->pDeformationMeasureLabel, pset);\n    old_dw->get(pStress_old,     lb->pStressLabel,             pset); \n\n    old_dw->get(pElasticVolStrain, pElasticVolStrainLabel,       pset);\n    old_dw->get(pStressQS_old,     pStressQSLabel,               pset);\n\n    // Get the particle variables from interpolateToParticlesAndUpdate() in SerialMPM\n    Uintah::constParticleVariable<double>  pVolume;\n    Uintah::constParticleVariable<Uintah::Matrix3> pVelGrad_new, pDefGrad_new;\n    new_dw->get(pVolume,        lb->pVolumeLabel_preReloc,  pset);\n    new_dw->get(pVelGrad_new,   lb->pVelGradLabel_preReloc, pset);\n    new_dw->get(pDefGrad_new,   lb->pDeformationMeasureLabel_preReloc, pset);\n\n    // Get the particle variables from compute kinematics\n    Uintah::ParticleVariable<double>  p_q, pdTdt; \n    Uintah::ParticleVariable<Uintah::Matrix3> pStress_new;\n    new_dw->allocateAndPut(p_q,                 lb->p_qLabel_preReloc,         pset);\n    new_dw->allocateAndPut(pdTdt,               lb->pdTdtLabel,                pset);\n    new_dw->allocateAndPut(pStress_new,         lb->pStressLabel_preReloc,     pset);\n\n    Uintah::ParticleVariable<double>  pElasticVolStrain_new;\n    Uintah::ParticleVariable<Uintah::Matrix3> pStressQS_new;\n    new_dw->allocateAndPut(pElasticVolStrain_new, pElasticVolStrainLabel_preReloc, pset);\n    new_dw->allocateAndPut(pStressQS_new,         pStressQSLabel_preReloc,         pset);\n\n    // Loop over the particles of the current patch to update particle\n    // stress at the end of the current timestep along with all other\n    // required data such plastic strain, elastic strain, cap position, etc.\n    for (auto iter = pset->begin(); iter!=pset->end(); iter++) {\n      Uintah::particleIndex idx = *iter;  //patch index\n      //cout<<\"pID=\"<<pParticleID[idx]<<std::endl;\n\n      // A parameter to consider the thermal effects of the plastic work which\n      // is not coded in the current source code. Further development of ArenaSoil\n      // may activate this feature.\n      pdTdt[idx] = 0.0;\n\n      // Compute the symmetric part of the velocity gradient\n      //std::cout << \"DefGrad = \" << pDefGrad_new[idx] << std::endl;\n      //std::cout << \"VelGrad = \" << pVelGrad_new[idx] << std::endl;\n      Uintah::Matrix3 DD = (pVelGrad_new[idx] + pVelGrad_new[idx].Transpose())*.5;\n\n      // Use polar decomposition to compute the rotation and stretch tensors\n      Uintah::Matrix3 FF = pDefGrad[idx];\n      Uintah::Matrix3 RR, UU;\n      FF.polarDecompositionRMB(UU, RR);\n\n      // Compute the unrotated symmetric part of the velocity gradient\n      DD = (RR.Transpose())*(DD*RR);\n#ifdef CHECK_FOR_NAN\n      //if (std::abs(DD(0,0)) < 1.0e-16 || std::isnan(DD(0, 0))) {\n      if (std::isnan(DD(0, 0))) {\n        std::cout << \" L_new = \" << pVelGrad_new[idx]\n                  << \" F_new = \" << pDefGrad_new[idx]\n                  << \" F = \" << FF\n                  << \" R = \" << RR << \" U = \" << UU\n                  << \" D = \" << DD \n                  << \" delT = \" << delT << std::endl;\n        //throw Uintah::InternalError(\"**ERROR** Zero or Nan in rate of deformation\", __FILE__, __LINE__);\n      }\n#endif\n\n      // To support non-linear elastic properties and to allow for the fluid bulk modulus\n      // model to increase elastic stiffness under compression, we allow for the bulk\n      // modulus to vary for each substep.  To compute the required number of substeps\n      // we use a conservative value for the bulk modulus (the high pressure limit B0+B1)\n      // to compute the trial stress and use this to subdivide the strain increment into\n      // appropriately sized substeps.  The strain increment is a product of the strain\n      // rate and time step, so we pass the strain rate and subdivided time step (rather\n      // than a subdivided trial stress) to the substep function.\n\n      // Compute the unrotated stress at the start of the current timestep\n      Uintah::Matrix3 sigma_old = (RR.Transpose())*(pStress_old[idx]*RR);\n      Uintah::Matrix3 sigmaQS_old = (RR.Transpose())*(pStressQS_old[idx]*RR);\n\n      //std::cout << \"pStress_old = \" << pStress_old[idx] << std::endl\n      //          << \"pStressQS_old = \" << pStressQS_old[idx] << std::endl;\n      //std::cout << \"sigma_old = \" << sigma_old << std::endl\n      //          << \"sigmaQS_old = \" << sigmaQS_old << std::endl;\n\n      // initial assignment for the updated values of plastic strains, volumetric\n      // part of the plastic strain, volumetric part of the elastic strain, \n      // and the backstress. tentative assumption of elasticity\n      ModelState_Arena state_old;\n      state_old.particleID          = pParticleID[idx];\n      state_old.capX                = pCapX[idx];\n      state_old.pbar_w              = -pBackstress_old[idx].Trace()/3.0;\n      state_old.stressTensor        = sigmaQS_old;\n      state_old.plasticStrainTensor = pEp[idx];\n      state_old.ep_cum_eq           = pEpeq_old[idx];\n      state_old.porosity            = pPorosity_old[idx];\n      state_old.saturation          = pSaturation_old[idx];\n      state_old.p3                  = pP3_old[idx];\n      state_old.coherence           = pCoherence_old[idx];\n      state_old.t_grow              = pTGrow_old[idx];\n\n      //std::cout << \"state_old.Stress = \" << state_old.stressTensor << std::endl;\n\n      // Get the parameters of the yield surface (for variability)\n      for (auto & zipped : combine(pYieldParamVarLabels, pYieldParamVars)) {\n        auto yield_param_label = std::get<0>(zipped);\n        auto yield_param_var   = std::get<1>(zipped);\n        state_old.yieldParams[yield_param_label] = yield_param_var[idx];\n      }\n      //std::string                            yield_param_label;\n      //Uintah::constParticleVariable<double>  yield_param_var;\n      //BOOST_FOREACH(boost::tie(yield_param_label, yield_param_var),\n      //              boost::combine(pYieldParamVarLabels, pYieldParamVars)) {\n      //  state_old.yieldParams[yield_param_label] = yield_param_var[idx];\n      //}\n\n      // Compute the elastic moduli at t = t_n\n      computeElasticProperties(state_old);\n      //std::cout << \"State old: \" << state_old << std::endl;\n\n      //---------------------------------------------------------\n      // Rate-independent plastic step\n      // Divides the strain increment into substeps, and calls substep function\n      ModelState_Arena state_new;\n      bool isSuccess = rateIndependentPlasticUpdate(DD, delT, \n                                                    idx, pParticleID[idx], state_old,\n                                                    state_new);\n\n      if (isSuccess) {\n\n        pStressQS_new[idx] = state_new.stressTensor;     // unrotated stress at end of step\n        pCapX_new[idx] = state_new.capX;                 // hydrostatic compressive strength at end of step\n        pBackstress_new[idx] = Identity*(-state_new.pbar_w);  // trace of isotropic backstress at end of step\n        pEp_new[idx] = state_new.plasticStrainTensor;    // plastic strain at end of step\n        pEpv_new[idx] = pEp_new[idx].Trace();            // Plastic volumetric strain at end of step\n        pEpeq_new[idx] = state_new.ep_cum_eq;            // Equivalent plastic strain at end of step\n\n        // Elastic volumetric strain at end of step, compute from updated deformation gradient.\n        pElasticVolStrain_new[idx] = log(pDefGrad_new[idx].Determinant()) - pEpv_new[idx];\n\n        pPorosity_new[idx] = state_new.porosity;\n        pSaturation_new[idx] = state_new.saturation;\n\n        pLocalized_new[idx] = pLocalized_old[idx];\n        pP3_new[idx] = pP3_old[idx];\n        pCoherence_new[idx] = state_new.coherence;\n        pTGrow_new[idx] = state_new.t_grow;\n      } else {\n\n        // If the updateStressAndInternalVars function can't converge it will return false.  \n        // This indicates substepping has failed, and the particle will be deleted.\n        pLocalized_new[idx]=-999;\n        std::cout << \"** WARNING ** Bad step, deleting particle\"\n                  << \" idx = \" << idx \n                  << \" particleID = \" << pParticleID[idx] \n                  << \":\" << __FILE__ << \":\" << __LINE__ << std::endl;\n\n        pStressQS_new[idx] = pStressQS_old[idx];\n        pCapX_new[idx] = state_old.capX; \n        pBackstress_new[idx] = pBackstress_old[idx];\n        pEp_new[idx] = state_old.plasticStrainTensor;    // plastic strain at start of step\n        pEpv_new[idx] = pEp_new[idx].Trace();\n        pEpeq_new[idx] = pEpeq_old[idx];\n        pElasticVolStrain_new[idx] = pElasticVolStrain[idx];\n        pPorosity_new[idx] = pPorosity_old[idx];\n        pSaturation_new[idx] = pSaturation_old[idx];\n\n        pP3_new[idx] = pP3_old[idx];\n        pCoherence_new[idx] = pCoherence_old[idx];\n        pTGrow_new[idx] = pTGrow_old[idx];\n      }\n\n      //---------------------------------------------------------\n      // Rate-dependent plastic step\n      ModelState_Arena stateQS_old(state_old);\n      stateQS_old.stressTensor = pStressQS_old[idx];\n      ModelState_Arena stateQS_new(state_new);\n      stateQS_new.stressTensor = pStressQS_new[idx];\n\n#ifdef CHECK_TRIAL_STRESS\n      std::cout << \"p_qs = \" << stateQS_new.stressTensor.Trace() << std::endl;\n#endif\n      \n      //std::cout << \"State QS old\";\n      computeElasticProperties(stateQS_old);\n      //std::cout << \"State QS new\";\n      computeElasticProperties(stateQS_new);\n \n      rateDependentPlasticUpdate(DD, delT, stateQS_old, stateQS_new, state_old,\n                                 pStress_new[idx]);\n\n\n      //---------------------------------------------------------\n      // Use polar decomposition to compute the rotation and stretch tensors.  These checks prevent\n      // failure of the polar decomposition algorithm if [F_new] has some extreme values.\n      Uintah::Matrix3 FF_new = pDefGrad_new[idx];\n      double Fmax_new = FF_new.MaxAbsElem();\n      double JJ_new = FF_new.Determinant();\n      if ((Fmax_new > 1.0e16) || (JJ_new < 1.0e-16) || (JJ_new > 1.0e16)) {\n        pLocalized_new[idx]=-999;\n        proc0cout << \"Deformation gradient component unphysical: [F] = \" << FF << std::endl;\n        proc0cout << \"Resetting [F]=[I] for this step and deleting particle\"\n                  << \" idx = \" << idx \n                  << \" particleID = \" << pParticleID[idx] << std::endl;\n        Identity.polarDecompositionRMB(UU, RR);\n      } else {\n        FF_new.polarDecompositionRMB(UU, RR);\n      }\n\n      // Dont't allow deformation gradients greater than 5.0\n#ifdef CLAMP_DEF_GRAD\n      if (d_cm.do_damage) {\n        if (Fmax_new > 10.0 || pEpv_new[idx] > 5.0) {\n          pLocalized_new[idx]=-999;\n          proc0cout << \"Deformation gradient or volumetric plastic strain too large for soils:\"\n                    << \"[F] = \" << FF \n                    << \"pEpv_new = \" << pEpv_new[idx]\n                    << std::endl;\n          proc0cout << \"Deleting particle\" << \" idx = \" << idx \n                    << \" particleID = \" << pParticleID[idx] << std::endl;\n        }\n      }\n#endif\n\n      // Compute the rotated dynamic and quasistatic stress at the end of the current timestep\n      pStress_new[idx] = (RR*pStress_new[idx])*(RR.Transpose());\n      pStressQS_new[idx] = (RR*pStressQS_new[idx])*(RR.Transpose());\n\n      //std::cout << \"pStress_new = \" << pStress_new[idx]\n      //          << \"pStressQS_new = \" << pStressQS_new[idx] << std::endl;\n\n      // Compute wave speed + particle velocity at each particle, store the maximum\n      //std::cout << \"State QS new rotated\";\n      computeElasticProperties(stateQS_new); \n      double bulk = stateQS_new.bulkModulus;\n      double shear = stateQS_new.shearModulus;\n      double rho_cur = pMass[idx]/pVolume[idx];\n      c_dil = sqrt((bulk+four_third*shear)/rho_cur);\n      //std::cout << \"K = \" << bulk << \" G = \" << shear << \" c_dil = \" << c_dil << std::endl;\n      WaveSpeed = Uintah::Vector(Uintah::Max(c_dil+std::abs(pVelocity[idx].x()),WaveSpeed.x()),\n                                 Uintah::Max(c_dil+std::abs(pVelocity[idx].y()),WaveSpeed.y()),\n                                 Uintah::Max(c_dil+std::abs(pVelocity[idx].z()),WaveSpeed.z()));\n\n      // Compute artificial viscosity term\n      if (flag->d_artificial_viscosity) {\n        double dx_ave = (dx.x() + dx.y() + dx.z())*one_third;\n        double c_bulk = sqrt(bulk/rho_cur);\n        p_q[idx] = artificialBulkViscosity(DD.Trace(), c_bulk, rho_cur, dx_ave);\n      } else {\n        p_q[idx] = 0.;\n      }\n\n      // Update p3\n      if (d_cm.use_disaggregation_algorithm) {\n        double phi0 = d_fluidParam.phi0;\n        double p3 = -std::log(pMass[*iter]/(pVolume[*iter]*(matl->getInitialDensity()))*(1 - phi0));\n        double phi = 1.0 - std::exp(-p3);\n        pP3_new[idx] = (phi > phi0) ? p3 : pP3_old[idx];\n      }\n\n      // Compute the averaged stress\n      Uintah::Matrix3 AvgStress = (pStress_new[idx] + pStress_old[idx])*0.5;\n\n      // Compute the strain energy increment associated with the particle\n      double e = (DD(0,0)*AvgStress(0,0) +\n                  DD(1,1)*AvgStress(1,1) +\n                  DD(2,2)*AvgStress(2,2) +\n                  2.0*(DD(0,1)*AvgStress(0,1) +\n                       DD(0,2)*AvgStress(0,2) +\n                       DD(1,2)*AvgStress(1,2))) * pVolume[idx]*delT;\n\n      // Accumulate the total strain energy\n      // MH! Note the initialization of se needs to be fixed as it is currently reset to 0\n      se += e;\n\n    } // End particle set loop\n\n    // Update yield condition parameter variability\n    if (d_cm.do_damage) {\n      // Each particle has a different set of parameters which are scaled by\n      // the coherence\n      d_yield->updateLocalVariables(pset, old_dw, new_dw, pCoherence_old, pCoherence_new);\n    } else {\n      // Each particle has a different set of parameters which remain\n      // constant through the simulation\n      d_yield->copyLocalVariables(pset, old_dw, new_dw);\n    }\n\n    // Compute the stable timestep based on maximum value of \"wave speed + particle velocity\"\n    WaveSpeed = dx/WaveSpeed; // Variable now holds critical timestep (not speed)\n\n    double delT_new = WaveSpeed.minComponent();\n\n    // Put the stable timestep and total strain enrgy\n    new_dw->put(Uintah::delt_vartype(delT_new), lb->delTLabel, patch->getLevel());\n    if (flag->d_reductionVars->accStrainEnergy ||\n        flag->d_reductionVars->strainEnergy) {\n      new_dw->put(Uintah::sum_vartype(se),        lb->StrainEnergyLabel);\n    }\n  }\n} // -----------------------------------END OF COMPUTE STRESS TENSOR FUNCTION\n\n// ***************************************************************************************\n// ***************************************************************************************\n// **** HOMEL's FUNCTIONS FOR GENERALIZED RETURN AND NONLINEAR ELASTICITY ****************\n// ***************************************************************************************\n// ***************************************************************************************\n/**\n * Function: \n *   rateIndependentPlasticUpdate\n *\n * Purpose:\n *   Divides the strain increment into substeps, and calls substep function\n *   All stress values within computeStep are quasistatic.\n */\nbool \nArenaPartiallySaturated::rateIndependentPlasticUpdate(const Uintah::Matrix3& D, \n                                                      const double& delT,\n                                                      Uintah::particleIndex idx, \n                                                      Uintah::long64 pParticleID, \n                                                      const ModelState_Arena& state_old,\n                                                      ModelState_Arena& state_new)\n{\n#ifdef CHECK_FOR_NAN_EXTRA\n  std::cout << \"Rate independent update:\" << std::endl;\n  std::cout << \" D = \" << D << \" delT = \" << delT << std::endl;\n  std::cout << \"\\t State old:\" << state_old << std::endl;\n#endif\n\n  // Compute the strain increment\n  Uintah::Matrix3 strain_inc = D*delT;\n  if (strain_inc.Norm() < 1.0e-30) {\n    state_new = state_old;\n    return true;\n  }\n  \n\n  // Compute the trial stress\n  Uintah::Matrix3 stress_trial = computeTrialStress(state_old, strain_inc);\n\n  // Set up a trial state, update the stress invariants, and compute elastic properties\n  ModelState_Arena state_trial(state_old);\n  state_trial.stressTensor = stress_trial;\n  computeElasticProperties(state_trial);\n  \n#ifdef CHECK_FOR_NAN_EXTRA\n  std::cout << \"\\t strain_inc = \" << strain_inc << std::endl;\n  std::cout << \"\\t State trial:\" << state_trial << std::endl;\n#endif\n\n  // Determine the number of substeps (nsub) based on the magnitude of\n  // the trial stress increment relative to the characteristic dimensions\n  // of the yield surface.  Also compare the value of the pressure dependent\n  // elastic properties at sigma_old and sigma_trial and adjust nsub if\n  // there is a large change to ensure an accurate solution for nonlinear\n  // elasticity even with fully elastic loading.\n  int nsub = computeStepDivisions(idx, pParticleID, state_old, state_trial);\n\n  // * Upon FAILURE *\n  // Delete the particle if the number of substeps is unreasonable\n  // Send ParticleDelete Flag to Host Code, Store Inputs to particle data:\n  // input values for sigma_new, X_new, Zeta_new, ep_new, along with error flag\n  if (nsub < 0) {\n    state_new = state_old;\n    proc0cout << \"Step Failed: Particle idx = \" << idx << \" ID = \" << pParticleID \n              << \" because nsub = \" << nsub << std::endl;\n    // bool success  = false;\n    return false;\n  }\n\n  // Compute a subdivided time step:\n  // Loop at least once or until substepping is successful\n  const int CHI_MAX = 5;       // max allowed subcycle multiplier\n\n  double dt = delT/nsub;       // substep time increment\n\n  int chi = 1;                 // subcycle multiplier\n  double tlocal = 0.0;\n  bool isSuccess = false;\n\n  // Set up the initial states for the substeps\n  ModelState_Arena state_k_old(state_old);\n  ModelState_Arena state_k_new(state_old);\n  do {\n\n    //  Call substep function {sigma_new, ep_new, X_new, Zeta_new}\n    //    = computeSubstep(D, dt, sigma_substep, ep_substep, X_substep, Zeta_substep)\n    //  Repeat while substeps continue to be successful\n    isSuccess = computeSubstep(D, dt, state_k_old, state_k_new);\n    if (isSuccess) {\n\n      tlocal += dt;\n\n#ifdef WRITE_YIELD_SURF\n      std::cout << \"K = \" << state_k_old.bulkModulus << std::endl;\n      std::cout << \"G = \" << state_k_old.shearModulus << std::endl;\n      std::cout << \"capX = \" << state_k_new.capX << std::endl;\n      std::cout << \"pbar_w = \" << state_k_new.pbar_w << std::endl;\n#endif\n\n      state_k_old = state_k_new;\n\n#ifdef WRITE_YIELD_SURF\n      Uintah::Matrix3 sig = state_k_new.stressTensor;\n      std::cout << \"sigma_new = np.array([[\" \n                << sig(0,0) << \",\" << sig(0,1) << \",\" << sig(0,2) << \"],[\" \n                << sig(1,0) << \",\" << sig(1,1) << \",\" << sig(1,2) << \"],[\" \n                << sig(2,0) << \",\" << sig(2,1) << \",\" << sig(2,2) << \"]])\"\n                << std::endl;\n      std::cout << \"plot_stress_state(K, G, sigma_trial, sigma_new, 'b')\" << std::endl;\n#endif\n\n    } else {\n\n      // Substepping has failed. Take tenth the timestep.\n      dt /= 10.0;\n\n      // Increase chi to keep track of the number of times the timstep has\n      // been reduced\n      chi += 1; \n      if (chi > CHI_MAX) {\n        state_new = state_k_old;\n        proc0cout << \"Substep failed because chi = \"  << chi << \" > \" << CHI_MAX\n                  << std::endl;\n        return isSuccess; // isSuccess = false;\n      }\n\n      proc0cout << \"**WARNING** Decreasing substep time increment to \" \n                << dt << \" because computeSubstep failed.\" << std::endl;\n\n    }\n#ifdef CHECK_SUBSTEP\n    if (tlocal < delT) {\n      std::cout << \"tlocal = \" << tlocal << \" delT = \" << delT << \" nsub = \" << nsub << std::endl;\n    }\n#endif\n  } while (tlocal < delT);\n    \n  state_new = state_k_new;\n\n#ifdef CHECK_INTERNAL_VAR_EVOLUTION\n//if (state_old.particleID == 3377699720593411) {\n  std::cout << \"rateIndependentPlasticUpdate: \"\n            << \" pbar_w_old = \" << state_old.pbar_w\n            << \" pbar_w_new = \" << state_new.pbar_w \n            << \" Xbar_old = \" << -state_old.capX\n            << \" Xbar_new = \" << -state_new.capX \n            << \" Xeff_old = \" << -state_old.capX - state_old.pbar_w\n            << \" Xeff_new = \" << -state_new.capX - state_new.pbar_w\n            << \" ep_v_old = \" << state_old.ep_v\n            << \" ep_v_new = \" << state_new.ep_v\n            << std::endl;\n//}\n#endif\n\n  return isSuccess;\n\n} \n\n/** \n * Method: computeElasticProperties\n *\n * Purpose: \n *   Compute the bulk and shear modulus at a given state\n *\n * Side effects:\n *   **WARNING** Also computes stress invariants and plastic strain invariants\n */\nvoid \nArenaPartiallySaturated::computeElasticProperties(ModelState_Arena& state)\n{\n  state.updateStressInvariants();\n  state.updatePlasticStrainInvariants();\n  ElasticModuli moduli = d_elastic->getCurrentElasticModuli(&state);\n  state.bulkModulus = moduli.bulkModulus;\n  state.shearModulus = moduli.shearModulus;\n\n  // Scale moduli using reference porosity (proxy for reference density)\n  state.bulkModulus *= d_modulus_scale_fac;\n  state.shearModulus *= d_modulus_scale_fac;\n\n  // Modify the moduli if damage is being used\n  if (d_cm.do_damage) {\n    state.bulkModulus *= (state.coherence + 1.0e-16);\n    state.shearModulus *= (state.coherence + 1.0e-16);\n  }\n\n  // Modify the moduli if disaggregation is being used\n  if (d_cm.use_disaggregation_algorithm) {\n    //double phi = 1.0 - std::exp(-state.p3);\n    double phi = std::max(state.porosity, 1.0 - std::exp(-state.p3));\n    double scale = (phi > d_fluidParam.phi0) ? std::max((1.0 - phi)/(1.0 + phi), 0.00001) : 1.0;\n    /*\n      if (state.particleID == 3659178992271360) {\n      std::cout << \"bulk modulus scale factor = \" << scale << std::endl;\n      }\n    */\n    state.bulkModulus *= scale;\n    state.shearModulus *= scale;\n  }\n}\n\n/**\n * Method: computeTrialStress\n * Purpose: \n *   Compute the trial stress for some increment in strain assuming linear elasticity\n *   over the step.\n */\nUintah::Matrix3 \nArenaPartiallySaturated::computeTrialStress(const ModelState_Arena& state_old,\n                                            const Uintah::Matrix3& strain_inc)\n{\n  // Compute the trial stress\n  Uintah::Matrix3 stress_old = state_old.stressTensor;\n  Uintah::Matrix3 deps_iso = Identity*(one_third*strain_inc.Trace());\n  Uintah::Matrix3 deps_dev = strain_inc - deps_iso;\n  Uintah::Matrix3 stress_trial = stress_old + \n    deps_iso*(3.0*state_old.bulkModulus) + \n    deps_dev*(2.0*state_old.shearModulus);\n//#ifdef CHECK_TRIAL_STRESS\n#ifdef CHECK_FOR_NAN\n  if (std::isnan(stress_trial(0, 0))) {\n    std::cout << \" stress_old = \" << stress_old\n              << \" stress_trial = \" << stress_trial\n              << \" p_trial = \" << stress_trial.Trace()/3.0\n              << \" strain_inc = \" << strain_inc\n              << \" deps_iso = \" << deps_iso\n              << \" deps_dev = \" << deps_dev\n              << \" K = \" << state_old.bulkModulus\n              << \" G = \" << state_old.shearModulus << std::endl;\n    throw Uintah::InternalError(\"**ERROR** Nan in compute trial stress.\", __FILE__, __LINE__);\n  }\n#endif\n//#endif\n\n  return stress_trial;\n} \n\n/**\n * Method: computeStepDivisions\n * Purpose: \n *   Compute the number of step divisions (substeps) based on a comparison\n *   of the trial stress relative to the size of the yield surface, as well\n *   as change in elastic properties between sigma_n and sigma_trial.\n * \n * Caveat:  Uses the mean values of the yield condition parameters.\n */\nint \nArenaPartiallySaturated::computeStepDivisions(Uintah::particleIndex idx,\n                                              Uintah::long64 particleID, \n                                              const ModelState_Arena& state_old,\n                                              const ModelState_Arena& state_trial)\n{\n  \n  // Get the yield parameters\n  double PEAKI1;\n  //double STREN;\n  try {\n    PEAKI1 = state_old.yieldParams.at(\"PEAKI1\");\n    //STREN = state_old.yieldParams.at(\"STREN\");\n  } \n  catch( std::out_of_range ) {\n    std::ostringstream err;\n    err << \"**ERROR** Could not find yield parameters PEAKI1 and STREN\" << std::endl;\n    for (auto param : state_old.yieldParams) {\n      err << param.first << \" \" << param.second << std::endl;\n    }\n    throw Uintah::InternalError(err.str(), __FILE__, __LINE__);\n  }\n\n  \n  // Compute change in bulk modulus:\n  double bulk_old = state_old.bulkModulus;\n  double bulk_trial = state_trial.bulkModulus;\n\n  int n_bulk = std::max(std::ceil(std::abs(bulk_old - bulk_trial)/bulk_old), 1.0);  \n#ifdef CHECK_FOR_NAN_EXTRA\n  std::cout << \"bulk_old = \" << bulk_old \n            << \" bulk_trial = \" << bulk_trial\n            << \" n_bulk = \" << n_bulk << std::endl;\n#endif\n  \n  // Compute trial stress increment relative to yield surface size:\n  Matrix3 d_sigma = state_trial.stressTensor - state_old.stressTensor;\n  double X_eff = state_old.capX + 3.0*state_old.pbar_w;\n  double I1_size = 0.5*(PEAKI1 - X_eff);\n  double J2_size = d_yield->evalYieldConditionMax(&state_old);\n  double size = std::max(I1_size, J2_size);\n  //if (STREN > 0.0){\n  //  size = std::min(I1_size, STREN);\n  //}  \n  size *= d_cm.yield_scale_fac;\n  int n_yield = ceil(d_sigma.Norm()/size);\n\n#ifdef CHECK_FOR_NAN_EXTRA\n//if (state_old.particleID == 3377699720593411) {\n  proc0cout << \"bulk_old = \" << bulk_old \n            << \" bulk_trial = \" << bulk_trial\n            << \" n_bulk = \" << n_bulk << std::endl;\n  proc0cout << \"PEAKI1 = \" << PEAKI1 \n            << \" capX_old = \" << state_old.capX\n            << \" pbar_w_old = \" << state_old.pbar_w\n            << \" size = \" << size \n            << \" |dsigma| = \" << d_sigma.Norm() \n            << \" n_yield = \" << n_yield << std::endl;\n//}\n#endif\n\n  // nsub is the maximum of the two values.above.  If this exceeds allowable,\n  // throw warning and delete particle.\n  int nsub = std::max(std::max(n_bulk, n_yield), 1);\n  int nmax = d_cm.subcycling_characteristic_number;\n \n  if (nsub > nmax) {\n    proc0cout << \"\\n **WARNING** Too many substeps needed for particle \"\n              << \" idx = \" << idx \n              << \" particle ID = \" << particleID << std::endl;\n    proc0cout << \"\\t\" << __FILE__ << \":\" << __LINE__ << std::endl;\n    proc0cout << \"\\t State at t_n: \" << state_old;\n    \n    proc0cout << \"\\t Trial state at t_n+1: \" << state_trial;\n\n    proc0cout << \"\\t Ratio of trial bulk modulus to t_n bulk modulus \"\n              << n_bulk << std::endl;\n\n    proc0cout << \"\\t ||sig_trial - sigma_n|| \" << d_sigma.Norm() << std::endl;\n    proc0cout << \"\\t Yield surface radius in I1-space: \" << size << std::endl;\n    proc0cout << \"\\t Ratio of ||sig_trial - sigma_n|| and \" << d_cm.yield_scale_fac \n              << \"*y.s. radius: \"\n              << n_yield << std::endl;\n    proc0cout << \"\\t PEAKI1 = \" << PEAKI1 << \" X_eff = \" << X_eff << \" X = \" << state_old.capX  \n              << \" pbar_w = \" << state_old.pbar_w << std::endl;\n    proc0cout << \"\\t I1_size = \" << I1_size << \" J2_size = \" << J2_size << std::endl;\n\n    proc0cout << \"** BECAUSE** nsub = \" << nsub << \" > \" \n              << d_cm.subcycling_characteristic_number\n              << \" : Probably too much tension in the particle.\"\n              << std::endl;\n    nsub = -1;\n  }\n  return nsub;\n} \n\n/** \n * Method: computeSubstep\n *\n * Purpose: \n *   Computes the updated stress state for a substep that may be either \n *   elastic, plastic, or partially elastic.   \n */\nbool \nArenaPartiallySaturated::computeSubstep(const Uintah::Matrix3& D,\n                                        const double& dt,\n                                        const ModelState_Arena& state_k_old,\n                                        ModelState_Arena& state_k_new)\n{\n#ifdef CHECK_FOR_NAN_EXTRA\n  std::cout << \"\\t D = \" << D << std::endl;\n  std::cout << \"\\t dt:\" << dt << std::endl;\n#endif\n\n  // Compute the trial stress\n  Uintah::Matrix3 deltaEps = D*dt;\n  Uintah::Matrix3 stress_k_trial = computeTrialStress(state_k_old, deltaEps);\n\n#ifdef CHECK_FOR_NAN_EXTRA\n  std::cout << \"\\t deltaEps = \" << deltaEps << std::endl;\n  std::cout << \"\\t Stress k trial:\" << stress_k_trial << std::endl;\n#endif\n\n#ifdef WRITE_YIELD_SURF\n  //std::cout << \"Inside computeSubstep:\" << std::endl;\n  std::cout << \"K = \" << state_k_old.bulkModulus << std::endl;\n  std::cout << \"G = \" << state_k_old.shearModulus << std::endl;\n  std::cout << \"capX = \" << state_k_old.capX << std::endl;\n  std::cout << \"pbar_w = \" << state_k_old.pbar_w << std::endl;\n  Matrix3 sig = stress_k_trial;\n  std::cout << \"sigma_trial = np.array([[\" \n            << sig(0,0) << \",\" << sig(0,1) << \",\" << sig(0,2) << \"],[\" \n            << sig(1,0) << \",\" << sig(1,1) << \",\" << sig(1,2) << \"],[\" \n            << sig(2,0) << \",\" << sig(2,1) << \",\" << sig(2,2) << \"]])\"\n            << std::endl;\n  std::cout << \"plot_stress_state(K, G, sigma_new, sigma_trial, 'r')\" << std::endl;\n  //std::cout << \"\\t computeSubstep: sigma_old = \" << state_k_old.stressTensor\n  //         << \" sigma_trial = \" << stress_trial \n  //         << \" D = \" << D << \" dt = \" << dt\n  //         << \" deltaEps = \" << deltaEps << std::endl;\n#endif\n\n  // Set up a trial state, update the stress invariants\n  ModelState_Arena state_k_trial(state_k_old);\n  state_k_trial.stressTensor = stress_k_trial;\n\n  // Compute elastic moduli at trial stress state\n  // and update stress invariants\n  computeElasticProperties(state_k_trial);\n\n  // Evaluate the yield function at the trial stress:\n  int yield = (int) d_yield->evalYieldCondition(&state_k_trial); \n\n  //std::cout << \"Has yielded ? 1 = Yes, -1 = No.\" << yield << std::endl;\n  //std::cout << \"computeSubstep:Elastic:sigma_new = \" << state_k_new.stressTensor \n  //          << \" pbar_w_trial = \" << state_k_trial.pbar_w\n  //          << \" Xbar_trial = \" << -state_k_trial.capX\n  //          << \" Xeff_trial = \" << -state_k_trial.capX - state_k_trial.pbar_w\n  //          << \" ep_v_trial = \" << state_k_trial.ep_v\n  //          << std::endl;\n\n  // Elastic substep\n  if (!(yield == 1)) { \n    state_k_new = state_k_trial;\n\n#ifdef CHECK_INTERNAL_VAR_EVOLUTION\n    std::cout << \"computeSubstep:Elastic:sigma_new = \" << state_k_new.stressTensor \n              << \" pbar_w_trial = \" << state_k_trial.pbar_w\n              << \" Xbar_trial = \" << -state_k_trial.capX\n              << \" Xeff_trial = \" << -state_k_trial.capX - state_k_trial.pbar_w\n              << \" ep_v_trial = \" << state_k_trial.ep_v\n              << std::endl;\n#endif\n\n    return true; // bool isSuccess = true;\n  }\n\n#ifdef DEBUG_YIELD_BISECTION_R\n  std::cout << \"before_non_hardening_return  = 1\" << std::endl;\n  std::cout << \"I1_eff = \" << state_k_old.I1_eff << std::endl;\n  std::cout << \"sqrt_J2 = \" << state_k_old.sqrt_J2 << std::endl;\n#endif\n  // Elastic-plastic or fully-plastic substep\n  // Compute non-hardening return to initial yield surface:\n  // std::cout << \"\\t Doing nonHardeningReturn\\n\";\n  Uintah::Matrix3 sig_fixed(0.0);        // final stress state for non-hardening return\n  Uintah::Matrix3 deltaEps_p_fixed(0.0); // increment in plastic strain for non-hardening return\n  bool isSuccess = nonHardeningReturn(deltaEps, state_k_old, state_k_trial, \n                                      sig_fixed, deltaEps_p_fixed);\n  if (!isSuccess) {\n    proc0cout << \"**WARNING** nonHardeningReturn has failed.\" << std::endl;\n    return isSuccess;\n  }\n\n  // Do \"consistency bisection\"\n  // std::cout << \"\\t Doing consistencyBisection\\n\";\n  state_k_new = state_k_old;\n#ifdef USE_SIMPLIFIED_CONSISTENCY_BISECTION\n  isSuccess = consistencyBisectionSimplified(deltaEps, state_k_old, state_k_trial,\n                                             deltaEps_p_fixed, sig_fixed, \n                                             state_k_new);\n#else\n  isSuccess = consistencyBisection(deltaEps, state_k_old, state_k_trial,\n                                   deltaEps_p_fixed, sig_fixed, \n                                   state_k_new);\n#endif\n\n#ifdef DEBUG_INTERNAL_VAR_EVOLUTION\n  std::cout << \"computeSubstep: \"\n            << \" pbar_w_old = \" << state_k_old.pbar_w\n            << \" pbar_w_new = \" << state_k_new.pbar_w \n            << \" Xbar_old = \" << -state_k_old.capX\n            << \" Xbar_new = \" << -state_k_new.capX \n            << \" Xeff_old = \" << -state_k_old.capX - state_k_old.pbar_w\n            << \" Xeff_new = \" << -state_k_new.capX - state_k_new.pbar_w\n            << \" ep_v_old = \" << state_k_old.ep_v\n            << \" ep_v_new = \" << state_k_new.ep_v\n            << std::endl;\n#endif\n\n#ifdef DEBUG_YIELD_BISECTION_R\n  std::cout << \"after_consistency_bisection  = 1\" << std::endl;\n  std::cout << \"I1_eff = \" << state_k_new.I1_eff << std::endl;\n  std::cout << \"sqrt_J2 = \" << state_k_new.sqrt_J2 << std::endl;\n#endif\n\n  // Update damage parameters\n  if (isSuccess) {\n    updateDamageParameters(D, dt, state_k_old, state_k_new);\n  } else {\n    proc0cout << \"consistency bisection has failed in \" << __FILE__ << \":\" << __LINE__\n              << std::endl;\n  }\n\n  return isSuccess;\n\n} //===================================================================\n\n\n/**\n * Method: nonHardeningReturn\n * Purpose: \n *   Computes a non-hardening return to the yield surface in the meridional profile\n *   (constant Lode angle) based on the current values of the internal state variables\n *   and elastic properties.  Returns the updated stress and  the increment in plastic\n *   strain corresponding to this return.\n *\n *   NOTE: all values of r and z in this function are transformed!\n */\nbool \nArenaPartiallySaturated::nonHardeningReturn(const Uintah::Matrix3& strain_inc,\n                                            const ModelState_Arena& state_k_old,\n                                            const ModelState_Arena& state_k_trial,\n                                            Uintah::Matrix3& sig_fixed,\n                                            Uintah::Matrix3& plasticStrain_inc_fixed)\n{\n  // Get the yield parameters\n  double BETA;\n  //double PEAKI1;\n  try {\n    BETA = state_k_old.yieldParams.at(\"BETA\");\n    //PEAKI1 = state_k_old.yieldParams.at(\"PEAKI1\");\n  } catch (std::out_of_range) {\n    std::ostringstream err;\n    err << \"**ERROR** Could not find yield parameters BETA and PEAKI1\" << std::endl;\n    for (auto param : state_k_old.yieldParams) {\n      err << param.first << \" \" << param.second << std::endl;\n    }\n    throw Uintah::InternalError(err.str(), __FILE__, __LINE__);\n  }\n\n  // Compute ratio of bulk and shear moduli\n  double K_old = state_k_old.bulkModulus;\n  double G_old = state_k_old.shearModulus;\n  const double sqrt_K_over_G_old = std::sqrt(1.5*K_old/G_old);\n#ifdef CHECK_FOR_NAN_EXTRA\n  std::cout << \" K_old = \" << K_old << \" G_old = \" << G_old << std::endl;\n#endif\n\n  // Save the r and z Lode coordinates for the trial stress state\n  double r_trial = BETA*state_k_trial.rr;\n  double z_eff_trial = state_k_trial.zz_eff;\n#ifdef CHECK_FOR_NAN_EXTRA\n  std::cout << \" state_k_trial \" << state_k_trial << std::endl;\n#endif\n\n  // Compute transformed r coordinates\n  double rprime_trial = r_trial*sqrt_K_over_G_old;\n#ifdef CHECK_FOR_NAN_EXTRA\n  std::cout << \" z_trial = \" << z_eff_trial \n            << \" r_trial = \" << rprime_trial/sqrt_K_over_G_old << std::endl;\n#endif\n\n  // Find closest point\n  double z_eff_closest = 0.0, rprime_closest = 0.0;\n  d_yield->getClosestPoint(&state_k_old, z_eff_trial, rprime_trial, \n                           z_eff_closest, rprime_closest);\n#ifdef CHECK_FOR_NAN_EXTRA\n  std::cout << \" z_eff_closest = \" << z_eff_closest \n            << \" r_closest = \" << rprime_closest/sqrt_K_over_G_old << std::endl;\n#endif\n\n  // Compute updated invariants of total stress\n  double I1_closest = std::sqrt(3.0)*z_eff_closest - 3.0*state_k_old.pbar_w;\n  double sqrtJ2_closest = 1.0/(sqrt_K_over_G_old*BETA*sqrt_two)*rprime_closest;\n\n#ifdef CHECK_FOR_NAN_EXTRA\n  std::cout << \"I1_eff_closest = \" << I1_closest + 3.0*state_k_old.pbar_w\n            << \" sqrtJ2_closest = \" << sqrtJ2_closest << std::endl;\n  std::cout << \"Trial state = \" << state_k_trial << std::endl;\n#endif\n#ifdef CHECK_HYDROSTATIC_TENSION\n  if (I1_closest < 0) {\n    std::cout << \"I1_eff_closest = \" << I1_closest + 3.0*state_k_old.pbar_w\n              << \" sqrtJ2_closest = \" << sqrtJ2_closest << std::endl;\n    std::cout << \"Trial state = \" << state_k_trial << std::endl;\n  }\n#endif\n\n  // Compute new stress\n  Uintah::Matrix3 sig_dev = state_k_trial.deviatoricStressTensor;\n  if (state_k_trial.sqrt_J2 > 0.0) {\n    //double z_close = I1_closest*one_sqrt_three;\n    //double r_close = sqrtJ2_closest*sqrt_two;\n    //double norm_Identity = sqrt_three;\n    //double norm_s_trial = sig_dev.Norm();\n    //sig_fixed = Identity*(z_close/norm_Identity) + sig_dev*(r_close/norm_s_trial);\n    sig_fixed = one_third*I1_closest*Identity + \n      (sqrtJ2_closest/state_k_trial.sqrt_J2)*sig_dev;\n  } else {\n    //double z_close = I1_closest*one_sqrt_three;\n    //double norm_Identity = sqrt_three;\n    //sig_fixed = Identity*(z_close/norm_Identity) + sig_dev;\n    sig_fixed = one_third*I1_closest*Identity + sig_dev;\n  }\n\n  // Compute new plastic strain increment\n  //  d_ep = d_e - [C]^-1:(sigma_new-sigma_old)\n  Uintah::Matrix3 sig_inc = sig_fixed - state_k_old.stressTensor;\n  Uintah::Matrix3 sig_inc_iso = one_third*sig_inc.Trace()*Identity;\n  Uintah::Matrix3 sig_inc_dev = sig_inc - sig_inc_iso;\n  Uintah::Matrix3 elasticStrain_inc = sig_inc_iso*(one_third/K_old) + sig_inc_dev*(0.5/G_old);\n  plasticStrain_inc_fixed = strain_inc - elasticStrain_inc;\n\n  // Compute volumetric plastic strain and compare with p3\n  Uintah::Matrix3 eps_p = state_k_old.plasticStrainTensor + plasticStrain_inc_fixed;\n  double ep_v = eps_p.Trace();\n  if (ep_v < 0.0) {\n    if (-ep_v > state_k_old.p3) {\n      proc0cout << \"**WARNING** Nonhardening return has failed because \"\n                << \" epsbar_p_v > p3 : \" << -ep_v << \" > \" << state_k_old.p3 << std::endl;\n      proc0cout << \" K_old = \" << K_old << \" G_old = \" << G_old << std::endl;\n      proc0cout << \" state_k_trial \" << state_k_trial << std::endl;\n      proc0cout << \" z_trial = \" << z_eff_trial \n                << \" r_trial = \" << rprime_trial/sqrt_K_over_G_old << std::endl;\n      proc0cout << \" z_eff_closest = \" << z_eff_closest \n                << \" r_closest = \" << rprime_closest/sqrt_K_over_G_old << std::endl;\n      proc0cout << \"Delta eps = \" << strain_inc << std::endl;\n      proc0cout << \"sig_n = \" << state_k_old.stressTensor << std::endl;\n      proc0cout << \"sig_n+1 = \" << sig_fixed << std::endl;\n      proc0cout << \"Delta sig = \" << sig_inc << std::endl;\n      proc0cout << \"Delta sig_iso = \" << sig_inc_iso << std::endl;\n      proc0cout << \"Delta sig_dev = \" << sig_inc_dev << std::endl;\n      proc0cout << \"Delta eps_e = \" << elasticStrain_inc << std::endl;\n      proc0cout << \"Delta eps_p = \" << plasticStrain_inc_fixed << std::endl;\n      proc0cout << \"I1_J2_trial = [\" << state_k_trial.I1_eff << \" \" \n                << state_k_trial.sqrt_J2 << \"];\" << std::endl;\n      proc0cout << \"I1_J2_closest = [\" << I1_closest + 3.0*state_k_old.pbar_w \n                << \" \" << sqrtJ2_closest << \"];\" << std::endl;\n      proc0cout << \"plot([I1 I1_J2_closest(1)],[sqrtJ2 I1_J2_closest(2)],'gx')\" \n                <<\";\" << std::endl;\n      proc0cout << \"plot([I1_J2_trial(1) I1_J2_closest(1)],[I1_J2_trial(2) I1_J2_closest(2)],'r-')\" \n                <<\";\" << std::endl;\n\n      return false;  // The plastic volume strain is too large, try again\n    }\n  }\n\n#ifdef CHECK_YIELD_SURFACE_NORMAL\n//if (state_k_old.particleID == 3377699720593411) {\n  std::cout << \"Delta eps = \" << strain_inc << std::endl;\n  std::cout << \"Trial state = \" << state_k_trial << std::endl;\n  std::cout << \"Delta sig = \" << sig_inc << std::endl;\n  std::cout << \"Delta sig_iso = \" << sig_inc_iso << std::endl;\n  std::cout << \"Delta sig_dev = \" << sig_inc_dev << std::endl;\n  std::cout << \"Delta eps_e = \" << elasticStrain_inc << std::endl;\n  std::cout << \"Delta eps_p = \" << plasticStrain_inc_fixed << std::endl;\n\n  // Test normal to yield surface\n  ModelState_Arena state_test(state_k_old);\n  state_test.stressTensor = sig_fixed;\n  state_test.updateStressInvariants();\n\n  Uintah::Matrix3 df_dsigma;\n  d_yield->eval_df_dsigma(Identity, &state_test, df_dsigma);\n  std::cout << \"df_dsigma = \" << df_dsigma << std::endl;\n  std::cout << \"ratio = [\" << plasticStrain_inc_fixed(0,0)/df_dsigma(0,0) << \",\"\n            << plasticStrain_inc_fixed(1,1)/df_dsigma(1,1) << \",\"\n            << plasticStrain_inc_fixed(2,2)/df_dsigma(2,2) << std::endl;\n\n  // Compute CN = C:df_dsigma\n  double lambda = state_test.bulkModulus - 2.0/3.0*state_test.shearModulus;\n  double mu = state_test.shearModulus;\n  Uintah::Matrix3 CN = Identity*(lambda*df_dsigma.Trace()) + df_dsigma*(2.0*mu);\n  Uintah::Matrix3 sig_diff = state_k_trial.stressTensor - sig_fixed;\n  std::cout << \"sig_trial = [\" << state_k_trial.stressTensor << \"];\" << std::endl;\n  std::cout << \"sig_n+1 = [\" << sig_fixed << \"];\" << std::endl;\n  std::cout << \"sig_trial - sig_n+1 = [\" << sig_diff << \"];\" << std::endl;\n  std::cout << \"C_df_dsigma = [\" << CN << \"];\" << std::endl;\n  std::cout << \"sig ratio = [\" << sig_diff(0,0)/CN(0,0) << \" \"\n            << sig_diff(1,1)/CN(1,1) << \" \"\n            << sig_diff(2,2)/CN(2,2) << \"];\" << std::endl;\n\n  // Compute a test stress to check normal\n  Uintah::Matrix3 sig_test = sig_fixed + df_dsigma*sig_diff(0,0);\n  ModelState_Arena state_sig_test(state_k_old);\n  state_sig_test.stressTensor = sig_test;\n  state_sig_test.updateStressInvariants();\n  std::cout << \"I1 = \" << state_sig_test.I1_eff << \";\" << std::endl;\n  std::cout << \"sqrtJ2 = \" << state_sig_test.sqrt_J2 << \";\" << std::endl;\n  std::cout << \"I1_J2_trial = [\" << state_k_trial.I1_eff << \" \" << state_k_trial.sqrt_J2 << \"];\" << std::endl;\n  std::cout << \"I1_J2_closest = [\" << I1_closest + 3.0*state_k_old.pbar_w << \" \" << sqrtJ2_closest << \"];\" << std::endl;\n  std::cout << \"plot([I1 I1_J2_closest(1)],[sqrtJ2 I1_J2_closest(2)],'gx-')\" <<\";\" << std::endl;\n  std::cout << \"plot([I1_J2_trial(1) I1_J2_closest(1)],[I1_J2_trial(2) I1_J2_closest(2)],'r-')\" <<\";\" << std::endl;\n\n  // Check actual location of projected point\n  Uintah::Matrix3 sig_test_actual = state_k_trial.stressTensor - CN*(std::abs(sig_diff(0,0)/CN(0,0)));\n  state_sig_test.stressTensor = sig_test_actual;\n  state_sig_test.updateStressInvariants();\n  std::cout << \"I1 = \" << state_sig_test.I1_eff << \";\" << std::endl;\n  std::cout << \"sqrtJ2 = \" << state_sig_test.sqrt_J2 << \";\" << std::endl;\n  std::cout << \"plot([I1 I1_J2_trial(1)],[sqrtJ2 I1_J2_trial(2)],'rx')\" <<\";\" << std::endl;\n//}\n#endif\n\n#ifdef CHECK_FOR_NAN\n  if (std::isnan(sig_fixed(0,0))) {\n    std::cout << \" K_old = \" << K_old << \" G_old = \" << G_old << std::endl;\n    std::cout << \" z_trial = \" << z_eff_trial \n              << \" r_trial = \" << rprime_trial/sqrt_K_over_G_old << std::endl;\n    std::cout << \" z_eff_closest = \" << z_eff_closest \n              << \" r_closest = \" << rprime_closest/sqrt_K_over_G_old << std::endl;\n    std::cout << \"I1_eff_closest = \" << I1_closest + 3.0*state_k_old.pbar_w\n              << \" sqrtJ2_closest = \" << sqrtJ2_closest << std::endl;\n    std::cout << \"Trial state = \" << state_k_trial << std::endl;\n    std::cout << \"\\t\\t\\t sig_fixed = \" << sig_fixed << std::endl;\n    std::cout << \"\\t\\t\\t I1_closest = \" << I1_closest << std::endl;\n    std::cout << \"\\t\\t\\t sqrtJ2_closest = \" << sqrtJ2_closest << std::endl;\n    std::cout << \"\\t\\t\\t state_k_trial.sqrt_J2 = \" << state_k_trial.sqrt_J2 << std::endl;\n    std::cout << \"\\t\\t\\t sig_dev = \" << sig_dev << std::endl;\n    std::cout << \"\\t\\t\\t sig_inc = \" << sig_inc << std::endl;\n    std::cout << \"\\t\\t\\t strain_inc = \" << strain_inc << std::endl;\n    std::cout << \"\\t\\t\\t sig_inc_iso = \" << sig_inc_iso << std::endl;\n    std::cout << \"\\t\\t\\t sig_inc_dev = \" << sig_inc_dev << std::endl;\n    std::cout << \"\\t\\t\\t plasticStrain_inc_fixed = \" << plasticStrain_inc_fixed << std::endl;\n  }\n#endif\n\n#ifdef CHECK_HYDROSTATIC_TENSION\n  if (I1_closest < 0) {\n    std::cout << \"\\t\\t\\t sig_inc = \" << sig_inc << std::endl;\n    std::cout << \"\\t\\t\\t strain_inc = \" << strain_inc << std::endl;\n    std::cout << \"\\t\\t\\t sig_inc_iso = \" << sig_inc_iso << std::endl;\n    std::cout << \"\\t\\t\\t sig_inc_dev = \" << sig_inc_dev << std::endl;\n    std::cout << \"\\t\\t\\t plasticStrain_inc_fixed = \" << plasticStrain_inc_fixed << std::endl;\n  }\n#endif\n\n  return true; // isSuccess = true\n\n} //===================================================================\n\n/**\n * Method: consistencyBisectionSimplified\n * Purpose: \n *   Find the updated stress for hardening plasticity using the consistency bisection \n *   algorithm\n *   Returns whether the procedure is sucessful or has failed\n */\nbool \nArenaPartiallySaturated::consistencyBisectionSimplified(const Uintah::Matrix3& deltaEps_new,\n                                                        const ModelState_Arena& state_k_old, \n                                                        const ModelState_Arena& state_k_trial,\n                                                        const Uintah::Matrix3& deltaEps_p_fixed, \n                                                        const Uintah::Matrix3& sig_fixed, \n                                                        ModelState_Arena& state_k_new)\n{\n  // bisection convergence tolerance on eta (if changed, change imax)\n  const double TOLERANCE = d_cm.consistency_bisection_tolerance; \n  // imax = ceil(-10.0*log(TOL)); // Update this if TOL changes\n  const int    IMAX      = d_cm.max_bisection_iterations;   \n\n  // Get the old state\n  Uintah::Matrix3 sig_old       = state_k_old.stressTensor;\n  Uintah::Matrix3 eps_p_old     = state_k_old.plasticStrainTensor;\n\n  // Get the fixed non-hardening return state and compute invariants\n  double  deltaEps_p_v_fixed    = deltaEps_p_fixed.Trace();\n  //double  norm_deltaEps_p_fixed = deltaEps_p_fixed.Norm();\n\n  // Create a state for the fixed non-hardening yield surface state\n  // and update only the stress and plastic strain\n  ModelState_Arena state_k_fixed(state_k_old);\n  state_k_fixed.stressTensor = sig_fixed;\n  state_k_fixed.plasticStrainTensor = eps_p_old + deltaEps_p_fixed;\n\n  // Initialize the new consistently updated state\n  Uintah::Matrix3 sig_fixed_new             = sig_fixed;\n  Uintah::Matrix3 deltaEps_p_fixed_new      = deltaEps_p_fixed;\n  double  deltaEps_p_v_fixed_new    = deltaEps_p_v_fixed;\n  //double  norm_deltaEps_p_fixed_new = norm_deltaEps_p_fixed;\n\n  // Set up a local trial state\n  ModelState_Arena state_trial_local(state_k_trial);\n\n  // Start loop\n  int ii = 1;\n  double eta_lo = 0.0, eta_hi = 1.0, eta_mid = 0.5;\n  bool isSuccess = false;\n\n  while (std::abs(eta_hi - eta_lo) > TOLERANCE) {\n\n#ifdef DEBUG_YIELD_BISECTION_R\n    std::cout << \"consistency_iter = \" << ii << std::endl;\n    std::cout << \"eta_hi = \" << eta_hi << std::endl;\n    std::cout << \"eta_lo = \" << eta_lo << std::endl;\n#endif\n\n    // Reset the local trial state \n    state_trial_local = state_k_trial;\n\n    // Compute the volumetric plastic strain at eta = eta_mid\n    eta_mid = 0.5*(eta_lo + eta_hi); \n    double deltaEps_p_v_mid = eta_mid*deltaEps_p_v_fixed;\n\n    // Update the internal variables at eta = eta_mid in the local trial state\n    isSuccess = computeInternalVariables(state_trial_local, deltaEps_p_v_mid);\n    if (!isSuccess) {\n      state_k_new = state_k_old;\n      proc0cout << \"computeInternalVariables has failed.\" << std::endl;\n      return false;\n    }\n\n    // Test the yield condition to check whether the yield surface moves beyond the\n    // trial stress state when the internal variables are changed.\n    // If the yield surface is too big, the plastic strain is reduced\n    // by bisecting <eta> and the loop is repeated.\n    int yield = (int) d_yield->evalYieldCondition(&state_trial_local);\n\n    // If the local trial state is inside the updated yield surface the yield\n    // condition evaluates to \"elastic\".  We need to reduce the size of the \n    // yield surface by decreasing the plastic strain increment.\n    if (yield != 1) {  // Elastic or on yield surface\n      eta_hi = eta_mid;\n      ii++;\n      continue;\n    } \n\n    // At this point, state_trial_local contains the trial stress, the plastic strain at\n    // the beginning of the timestep, and the updated values of the internal variables\n    // The yield surface depends only on X and p_w.  We will compute the updated location\n    // of the yield surface based on the updated internal variables (keeping the\n    // elastic moduli at the values at the beginning of the step) and do \n    // a non-hardening return to that yield surface.\n    ModelState_Arena state_k_updated(state_k_old);\n    state_k_updated.pbar_w = state_trial_local.pbar_w;\n    state_k_updated.porosity = state_trial_local.porosity;\n    state_k_updated.saturation = state_trial_local.saturation;\n    state_k_updated.capX = state_trial_local.capX;\n    state_k_updated.updateStressInvariants();\n    isSuccess = nonHardeningReturn(deltaEps_new, state_k_updated, state_trial_local, \n                                   sig_fixed_new, deltaEps_p_fixed_new);\n    if (!isSuccess) {\n      proc0cout << \"nonHardeningReturn inside consistencyBisection failed.\" << std::endl;\n      return isSuccess;\n    }\n\n    // Check whether the isotropic component of the return has changed sign, as this\n    // would indicate that the cap apex has moved past the trial stress, indicating\n    // too much plastic strain in the return.\n    Uintah::Matrix3 sig_trial = state_trial_local.stressTensor;\n    double  diff_trial_fixed_new = (sig_trial - sig_fixed_new).Trace();\n    double  diff_trial_fixed     = (sig_trial - sig_fixed).Trace();\n    if (std::signbit(diff_trial_fixed_new) != std::signbit(diff_trial_fixed)) {\n      eta_hi = eta_mid;\n      ii++;\n      continue;\n    }\n\n    // Compare magnitude of plastic strain with prior update\n    deltaEps_p_v_fixed_new = deltaEps_p_fixed_new.Trace();\n    deltaEps_p_v_fixed = eta_mid*deltaEps_p_fixed.Trace();\n\n#ifdef CHECK_CONSISTENCY_BISECTION_CONVERGENCE\n    auto norm_deltaEps_p_fixed = eta_mid*deltaEps_p_fixed.Norm();\n    auto norm_deltaEps_p_fixed_new = deltaEps_p_fixed_new.Norm();\n    std::cout << \"eta_mid = \" << eta_mid \n              << \" eta_mid*||deltaEps_p_fixed|| = \" << eta_mid*norm_deltaEps_p_fixed\n              << \" ||deltaEps_p_fixed_new|| = \" << norm_deltaEps_p_fixed_new \n              << \" ratio = \" << eta_mid*norm_deltaEps_p_fixed/norm_deltaEps_p_fixed_new << std::endl;\n    std::cout << \" delta_eps_p_v_mid = \" << deltaEps_p_v_mid\n              << \" delta_eps_p_v_fixed_new = \" << deltaEps_p_v_fixed_new\n              << \" ratio = \" << deltaEps_p_v_mid/deltaEps_p_fixed_new.Trace() << std::endl;\n#endif\n\n    //if (norm_deltaEps_p_fixed_new > eta_mid*norm_deltaEps_p_fixed) {\n    if (std::abs(deltaEps_p_v_fixed_new) > eta_mid*std::abs(deltaEps_p_v_fixed)) {\n      eta_lo = eta_mid;\n    } else {\n      eta_hi = eta_mid;\n    }\n\n    // Increment i and check\n    ii++;\n    if (ii > IMAX) {\n      state_k_new = state_k_old;\n      proc0cout << \"Consistency bisection has failed because ii > IMAX.\" \n                << ii << \" > \" << IMAX << std::endl;\n      return false;   // bool isSuccess = false;\n    }\n\n  } // end  while (std::abs(eta_hi - eta_lo) > TOLERANCE);\n\n  // Set the new state to the old trial state\n  // The volumetric strain may not have converged so recompute internal variables\n  state_k_new = state_k_trial;\n  isSuccess = computeInternalVariables(state_k_new, deltaEps_p_v_fixed_new);\n  if (!isSuccess) {\n    state_k_new = state_k_old;\n    proc0cout << \"computeInternalVariables has failed.\" << std::endl;\n    return false;\n  }\n\n  // Update the stress and plastic strain of the new state +  the elastic moduli\n  state_k_new.stressTensor        = sig_fixed_new;\n  state_k_new.plasticStrainTensor = eps_p_old + deltaEps_p_fixed_new;;\n  computeElasticProperties(state_k_new);\n\n#ifdef DEBUG_YIELD_BISECTION_R\n  std::cout << \"pbar_w_before_consistency_3 = \" << 3.0*state_k_old.pbar_w << std::endl;\n  std::cout << \"pbar_w_after_consistency_3 = \" << 3.0*state_k_new.pbar_w << std::endl;\n  std::cout << \"K_before_consistency = \" << state_k_old.bulkModulus << std::endl;\n  std::cout << \"K_after_consistency = \" << state_k_new.bulkModulus << std::endl;\n  std::cout << \"I1_before_consistency = \" << state_k_old.stressTensor.Trace() << std::endl;\n  std::cout << \"I1_after_consistency = \" << state_k_new.stressTensor.Trace() << std::endl;\n  std::cout << \"I1_eff_before_consistency = \" << state_k_old.I1_eff << std::endl;\n  std::cout << \"I1_eff_after_consistency = \" << state_k_new.I1_eff << std::endl;\n#endif\n\n  // Update the cumulative equivalent plastic strain\n  double deltaEps_p_v = deltaEps_p_fixed_new.Trace();\n  Uintah::Matrix3 deltaEps_p_dev = deltaEps_p_fixed_new - Identity*(deltaEps_p_v/3.0);\n  state_k_new.ep_cum_eq = state_k_old.ep_cum_eq +  \n    std::sqrt(2.0/3.0*deltaEps_p_dev.Contract(deltaEps_p_dev));\n\n#ifdef DEBUG_INTERNAL_VAR_EVOLUTION\n  std::cout << \"consistencyBisection: \" << std::endl\n            << \"\\t state_old = \" << state_k_old << std::endl\n            << \"\\t state_new = \" << state_k_new << std::endl;\n#endif\n\n  // Return success = true  \n  return true;   // bool isSuccess = true;\n}\n\n/**\n * Method: consistencyBisection\n * Purpose: \n *   Find the updated stress for hardening plasticity using the consistency bisection \n *   algorithm\n *   Returns whether the procedure is sucessful or has failed\n */\nbool \nArenaPartiallySaturated::consistencyBisection(const Uintah::Matrix3& deltaEps_new,\n                                              const ModelState_Arena& state_k_old, \n                                              const ModelState_Arena& state_k_trial,\n                                              const Uintah::Matrix3& deltaEps_p_fixed, \n                                              const Uintah::Matrix3& sig_fixed, \n                                              ModelState_Arena& state_k_new)\n{\n  // bisection convergence tolerance on eta (if changed, change imax)\n  const double TOLERANCE = d_cm.consistency_bisection_tolerance; \n  // imax = ceil(-10.0*log(TOL)); // Update this if TOL changes\n  const int    IMAX      = d_cm.max_bisection_iterations;   \n  // jmax = ceil(-10.0*log(TOL)); // Update this if TOL changes\n  const int    JMAX      = d_cm.max_bisection_iterations;   \n\n  // Get the old state\n  Uintah::Matrix3 sig_old       = state_k_old.stressTensor;\n  Uintah::Matrix3 eps_p_old     = state_k_old.plasticStrainTensor;\n\n  // Get the fixed non-hardening return state and compute invariants\n  double  deltaEps_p_v_fixed    = deltaEps_p_fixed.Trace();\n  double  norm_deltaEps_p_fixed = deltaEps_p_fixed.Norm();\n\n  // Create a state for the fixed non-hardening yield surface state\n  // and update only the stress and plastic strain\n  ModelState_Arena state_k_fixed(state_k_old);\n  state_k_fixed.stressTensor = sig_fixed;\n  state_k_fixed.plasticStrainTensor = eps_p_old + deltaEps_p_fixed;\n\n  // Initialize the new consistently updated state\n  Uintah::Matrix3 sig_fixed_new             = sig_fixed;\n  Uintah::Matrix3 deltaEps_p_fixed_new      = deltaEps_p_fixed;\n  //double  norm_deltaEps_p_fixed_new = norm_deltaEps_p_fixed;\n\n  // Set up a local trial state\n  ModelState_Arena state_trial_local(state_k_trial);\n\n  // Start loop\n  int ii = 1;\n  double eta_lo = 0.0, eta_hi = 1.0, eta_mid = 0.5;\n\n  while (std::abs(eta_hi - eta_lo) > TOLERANCE) {\n\n#ifdef DEBUG_YIELD_BISECTION_R\n    std::cout << \"consistency_iter = \" << ii << std::endl;\n    std::cout << \"eta_hi = \" << eta_hi << std::endl;\n    std::cout << \"eta_lo = \" << eta_lo << std::endl;\n#endif\n    // This loop checks whether the yield surface moves beyond the\n    // trial stress state when the internal variables are changed.\n    // If the yield surface is too big, the plastic strain is reduced\n    // by bisecting <eta> and the loop is repeated.\n    int jj = 1;\n    bool isElastic = true;\n    while (isElastic) { \n\n      // Reset the local trial state \n      state_trial_local = state_k_trial;\n\n      // Compute the volumetric plastic strain at eta = eta_mid\n      eta_mid = 0.5*(eta_lo + eta_hi); \n      double deltaEps_p_v_mid = eta_mid*deltaEps_p_v_fixed;\n\n      // Update the internal variables at eta = eta_mid in the local trial state\n      bool isSuccess = computeInternalVariables(state_trial_local, deltaEps_p_v_mid);\n      if (!isSuccess) {\n        state_k_new = state_k_old;\n        proc0cout << \"computeInternalVariables has failed.\" << std::endl;\n        return false;\n      }\n\n#ifdef CHECK_TENSION_STATES\n      std::cout << \"While elastic:\" << std::endl;\n      std::cout << \"\\t\\t \" << \"eta_lo = \" << eta_lo << \" eta_mid = \" << eta_mid\n                << \" eta_hi = \" << eta_hi\n                << \" capX_fixed = \" << state_k_old.capX \n                << \" capX_new = \" << state_trial_local.capX \n                << \" pbar_w_fixed = \" << state_k_old.pbar_w \n                << \" pbar_w_new = \" << state_trial_local.pbar_w \n                << \" ||delta eps_p_fixed|| = \" << norm_deltaEps_p_fixed \n                << \" ||delta eps_p_fixed_new|| = \" << norm_deltaEps_p_fixed_new << std::endl;\n#endif\n\n      // Test the yield condition\n      int yield = (int) d_yield->evalYieldCondition(&state_trial_local);\n\n      // If the local trial state is inside the updated yield surface the yield\n      // condition evaluates to \"elastic\".  We need to reduce the size of the \n      // yield surface by decreasing the plastic strain increment.\n      isElastic = false; \n      if (yield != 1) {\n        isElastic = true;   // Elastic or on yield surface\n        eta_hi = eta_mid;\n        jj++;\n        if (jj > JMAX) {\n          state_k_new = state_k_old;\n          proc0cout << \"Consistency bisection has failed because jj > JMAX.\" \n                    << jj << \" > \" << JMAX << std::endl;\n          return false;    // bool isSuccess = false;\n        }\n      } \n    } // end while(isElastic)\n\n    // At this point, state_trial_local contains the trial stress, the plastic strain at\n    // the beginning of the timestep, and the updated values of the internal variables\n    // The yield surface depends only on X and p_w.  We will compute the updated location\n    // of the yield surface based on the updated internal variables (keeping the\n    // elastic moduli at the values at the beginning of the step) and do \n    // a non-hardening return to that yield surface.\n\n    ModelState_Arena state_k_updated(state_k_old);\n    state_k_updated.pbar_w = state_trial_local.pbar_w;\n    state_k_updated.porosity = state_trial_local.porosity;\n    state_k_updated.saturation = state_trial_local.saturation;\n    state_k_updated.capX = state_trial_local.capX;\n    state_k_updated.updateStressInvariants();\n    bool isSuccess = nonHardeningReturn(deltaEps_new, state_k_updated, state_trial_local, \n                                        sig_fixed_new, deltaEps_p_fixed_new);\n    if (!isSuccess) {\n      proc0cout << \"nonHardeningReturn in old consistencyBisection has failed.\" << std::endl;\n      return isSuccess;\n    }\n\n    // Check whether the isotropic component of the return has changed sign, as this\n    // would indicate that the cap apex has moved past the trial stress, indicating\n    // too much plastic strain in the return.\n    Uintah::Matrix3 sig_trial = state_trial_local.stressTensor;\n    double  diff_trial_fixed_new = (sig_trial - sig_fixed_new).Trace();\n    double  diff_trial_fixed     = (sig_trial - sig_fixed).Trace();\n    if (std::signbit(diff_trial_fixed_new) != std::signbit(diff_trial_fixed)) {\n      eta_hi = eta_mid;\n      ii++;\n      continue;\n    }\n\n    // Compare magnitude of plastic strain with prior update\n    auto norm_deltaEps_p_fixed_new = deltaEps_p_fixed_new.Norm();\n    norm_deltaEps_p_fixed = eta_mid*deltaEps_p_fixed.Norm();\n\n#ifdef CHECK_TENSION_STATES_1\n    std::cout << \"eta_mid = \" << eta_mid \n              << \" eta_mid*||deltaEps_p_fixed|| = \" << eta_mid*norm_deltaEps_p_fixed\n              << \" ||deltaEps_p_fixed_new|| = \" << norm_deltaEps_p_fixed_new << std::endl;\n#endif\n\n    if (norm_deltaEps_p_fixed_new > eta_mid*norm_deltaEps_p_fixed) {\n      eta_lo = eta_mid;\n    } else {\n      eta_hi = eta_mid;\n    }\n\n    // Increment i and check\n    ii++;\n    if (ii > IMAX) {\n      state_k_new = state_k_old;\n      proc0cout << \"Consistency bisection has failed because ii > IMAX.\" \n                << ii << \" > \" << IMAX << std::endl;\n      return false;   // bool isSuccess = false;\n    }\n\n  } // end  while (std::abs(eta_hi - eta_lo) > TOLERANCE);\n\n  // Set the new state to the original trial state and\n  // update the internal variables\n  state_k_new            = state_k_trial;\n  /*\n    state_k_new.pbar_w     = state_trial_local.pbar_w;\n    state_k_new.porosity   = state_trial_local.porosity;\n    state_k_new.saturation = state_trial_local.saturation;\n    state_k_new.capX       = state_trial_local.capX;\n  */\n\n  bool isSuccess = computeInternalVariables(state_k_new, deltaEps_p_fixed_new.Trace());\n  if (!isSuccess) {\n    state_k_new = state_k_old;\n    proc0cout << \"computeInternalVariables has failed.\" << std::endl;\n    return false;\n  }\n\n  // Update the rest of the new state including the elastic moduli\n  //state_k_new.stressTensor = sig_fixed_new + \n  //  3.0*(-state_k_new.pbar_w + state_trial_local.pbar_w)*Identity;\n  state_k_new.stressTensor = sig_fixed_new;\n  state_k_new.plasticStrainTensor = eps_p_old + deltaEps_p_fixed_new;;\n  computeElasticProperties(state_k_new);\n\n#ifdef DEBUG_YIELD_BISECTION_R\n  std::cout << \"pbar_w_before_consistency_3 = \" << 3.0*state_k_old.pbar_w << std::endl;\n  std::cout << \"pbar_w_after_consistency_3 = \" << 3.0*state_k_new.pbar_w << std::endl;\n  std::cout << \"K_before_consistency = \" << state_k_old.bulkModulus << std::endl;\n  std::cout << \"K_after_consistency = \" << state_k_new.bulkModulus << std::endl;\n  std::cout << \"I1_before_consistency = \" << state_k_old.stressTensor.Trace() << std::endl;\n  std::cout << \"I1_after_consistency = \" << state_k_new.stressTensor.Trace() << std::endl;\n  std::cout << \"I1_eff_before_consistency = \" << state_k_old.I1_eff << std::endl;\n  std::cout << \"I1_eff_after_consistency = \" << state_k_new.I1_eff << std::endl;\n#endif\n\n  // Update the cumulative equivalent plastic strain\n  double deltaEps_p_v = deltaEps_p_fixed_new.Trace();\n  Uintah::Matrix3 deltaEps_p_dev = deltaEps_p_fixed_new - Identity*(deltaEps_p_v/3.0);\n  state_k_new.ep_cum_eq = state_k_old.ep_cum_eq +  \n    std::sqrt(2.0/3.0*deltaEps_p_dev.Contract(deltaEps_p_dev));\n\n#ifdef DEBUG_INTERNAL_VAR_EVOLUTION\n  std::cout << \"consistencyBisection: \" << std::endl\n            << \"\\t state_old = \" << state_k_old << std::endl\n            << \"\\t state_new = \" << state_k_new << std::endl;\n#endif\n\n  // Return success = true  \n  return true;   // bool isSuccess = true;\n}\n\n/** \n * Method: computeInternalVariables\n * Purpose: \n *   Update an old state with new values of internal variables given the old state and an \n *   increment in volumetric plastic strain\n */\nbool\nArenaPartiallySaturated::computeInternalVariables(ModelState_Arena& state,\n                                                  const double& delta_eps_p_v)\n{\n  // Internal variables are not allowed to evolve when the effective stress is tensile\n  //if (state.I1_eff > 0.0) {\n  //  return;\n  //}\n\n  // Convert strain increment to barred quantity (positive in compression)\n  double delta_epsbar_p_v = -delta_eps_p_v;\n\n  // Get the initial fluid pressure\n  double pbar_w0 = d_fluidParam.pbar_w0;\n\n  // Get the initial porosity and saturation\n  double phi0 = d_fluidParam.phi0;\n  double Sw0 = d_fluidParam.Sw0;\n\n  // Get the old values of the internal variables\n  double epsbar_p_v_old = -state.ep_v;\n  double pbar_w_old = state.pbar_w;\n  double phi_old = state.porosity;\n  double Sw_old = state.saturation;\n  // double Xbar_old = -state.capX;\n  double p3_old = state.p3;\n\n  // If epsbar_p_v_old + Delta epsbar_p_v > p3 don't do anything\n  if ((epsbar_p_v_old + delta_epsbar_p_v) > p3_old) {\n    proc0cout << \"**WARNING** eps_p_v > p3_old : \" << epsbar_p_v_old << \"+\"\n              << delta_epsbar_p_v << \">\" << p3_old << std::endl;\n    return false;\n  }\n\n  // Compute the bulk moduli of air and water at the old value of pbar_w\n  double K_a = d_air.computeBulkModulus(pbar_w_old);\n  double K_w = d_water.computeBulkModulus(pbar_w_old);\n  double one_over_K_a = 1.0/K_a;\n  double one_over_K_w = 1.0/K_w;\n\n  // Compute the volumetric strain in the air and water at the old value of pbar_w\n  double ev_a0 = d_air.computeElasticVolumetricStrain(pbar_w0, 0.0);\n  double ev_a = d_air.computeElasticVolumetricStrain(pbar_w_old, 0.0);\n  double ev_w = d_water.computeElasticVolumetricStrain(pbar_w_old, pbar_w0);\n  double epsbar_v_a = std::max(-(ev_a - ev_a0), 0.0);\n  double epsbar_v_w = std::max(-ev_w, 0.0);\n\n#ifdef CHECK_FLOATING_POINT_OVERFLOW\n  errno = 0;\n  std::feclearexcept(FE_ALL_EXCEPT);\n#endif\n  double exp_ev_a_minus_ev_w = std::exp(epsbar_v_a - epsbar_v_w);\n#ifdef CHECK_FLOATING_POINT_OVERFLOW\n  if (errno == ERANGE) {\n    std::cout << \" in exp(): errno == ERANGE: \" << std::strerror(errno) << std::endl;\n  }\n  if (std::fetestexcept(FE_OVERFLOW)) {\n    std::cout << \"    FE_OVERFLOW raised\\n\";\n  }\n#endif\n\n  // Compute C_p and 1/(1+Cp)^2\n  double C_p = Sw0*exp_ev_a_minus_ev_w;\n  // double one_over_one_p_C_p_Sq = (1.0 - Sw0)/((1.0 - Sw0 + C_p)*(1.0 - Sw0 + C_p));\n\n  // Compute dC_p/dp_w\n  // double dC_p_dpbar_w = C_p*(one_over_K_a - one_over_K_w);\n\n  // Compute B_p\n#ifdef CHECK_FLOATING_POINT_OVERFLOW\n  errno = 0;\n  std::feclearexcept(FE_ALL_EXCEPT);\n#endif\n  double exp_ev_p_minus_ev_a = std::exp(epsbar_p_v_old - epsbar_v_a);\n  double exp_ev_p_minus_ev_w = std::exp(epsbar_p_v_old - epsbar_v_w);\n#ifdef CHECK_FLOATING_POINT_OVERFLOW\n  if (errno == ERANGE) {\n    std::cout << \" in exp(): errno == ERANGE: \" << std::strerror(errno) << std::endl;\n  }\n  if (std::fetestexcept(FE_OVERFLOW)) {\n    std::cout << \"    FE_OVERFLOW raised\\n\";\n  }\n#endif\n\n  double B_p =  1.0/((1.0 - Sw0)*exp_ev_p_minus_ev_a + Sw0*exp_ev_p_minus_ev_w)*\n    (-(1.0-phi_old)*(phi_old/phi0)*(Sw_old*one_over_K_w + (1.0 - Sw_old)*one_over_K_a) +\n     (1.0 - Sw0)*one_over_K_a*exp_ev_p_minus_ev_a + Sw0*one_over_K_w*exp_ev_p_minus_ev_w);\n  //double one_over_B_p = (std::abs(B_p) < 1.0e-30) ? 1.0e30 : 1.0/B_p;\n  double one_over_B_p = 1.0/B_p;\n\n  // Update the pore pressure\n  double pbar_w_new = pbar_w_old + one_over_B_p*delta_epsbar_p_v;\n\n#ifdef DEBUG_INTERNAL_VAR_EVOLUTION_COMPUTATION\n  std::cout << \"computeInternalVar: epsbar_p_v = \" << -state.ep_v \n            << \" delta epsbar_p_v = \" << delta_epsbar_p_v \n            << \" pbar_w = \" << state.pbar_w \n            << \" pbar_w_old = \" << pbar_w_old \n            << \" pbar_w_new = \" << pbar_w_new \n            << \" Sw0 = \" << Sw0 << \" Sw = \" << Sw_old\n            << \" phi0 = \" << phi0 << \" phi = \" << phi_old\n            << \" epsbar_v_a = \" << epsbar_v_a << \" epsbar_v_w = \" << epsbar_v_w\n            << \" Ka = \" << K_a << \" Kw = \" << K_w << \" B_p = \" << B_p << std::endl;\n#endif\n\n  // Don't allow negative pressures during dilatative plastic deformations\n  pbar_w_new = std::max(pbar_w_new, 0.0);\n  //assert(!(pbar_w_new < 0.0));\n\n  // Update the hydrostatic compressive strength\n  // (using integration)\n  /*\n  // Compute the drained hydrostatic compressive strength\n  double Xbar_d = 0.0;\n  double derivXbar_d = 0.0;\n  computeDrainedHydrostaticStrengthAndDeriv(epsbar_p_v_old, p3_old, Xbar_d, derivXbar_d);\n\n  // Update the hydrostatic strength\n  double p1_sat = d_crushParam.p1_sat;\n  double Xbar_new = Xbar_old + ((1.0 - Sw_old + p1_sat*Sw_old)*derivXbar_d +\n  Xbar_d*(p1_sat - 1.0)*one_over_B_p*one_over_one_p_C_p_Sq*dC_p_dpbar_w + 3.0*one_over_B_p)*\n  delta_epsbar_p_v;\n  double Xbar_clamp = d_crushParam.p0 + 3.0*pbar_w_new;\n  Xbar_new = (Xbar_new < Xbar_clamp) ? Xbar_clamp : Xbar_new;\n  //assert(!(Xbar_new < 0.0));\n  */\n\n  // Get the new value of the volumetric plastic strain\n  double epsbar_p_v_new = epsbar_p_v_old + delta_epsbar_p_v;\n\n  // Compute the volumetric strain in the air and water at the new value of pbar_w\n  ev_a = d_air.computeElasticVolumetricStrain(pbar_w_new, 0.0);\n  ev_w = d_water.computeElasticVolumetricStrain(pbar_w_new, pbar_w0);\n  epsbar_v_a = std::max(-(ev_a - ev_a0), 0.0);\n  epsbar_v_w = std::max(-ev_w, 0.0);\n  exp_ev_a_minus_ev_w = std::exp(epsbar_v_a - epsbar_v_w);\n  exp_ev_p_minus_ev_a = std::exp(epsbar_p_v_new - epsbar_v_a);\n  exp_ev_p_minus_ev_w = std::exp(epsbar_p_v_new - epsbar_v_w);\n\n  // Update the saturation using closed form expression\n  C_p = Sw0*exp_ev_a_minus_ev_w;\n  double Sw_new = C_p/(1.0 - Sw0 + C_p);\n  //assert(!(Sw_new < 0.0));\n\n  // Update the porosity using closed form expression\n  double phi_new = (1.0 - Sw0)*phi0*exp_ev_p_minus_ev_a +\n    Sw0*phi0*exp_ev_p_minus_ev_w;\n  //assert(!(phi_new < 0.0));\n\n  // Update the hydrostatic compressive strength\n  // (using closed form solution)\n  // Compute the drained hydrostatic compressive strength\n  double Xbar_d = 0.0;\n  double derivXbar_d = 0.0;\n  computeDrainedHydrostaticStrengthAndDeriv(epsbar_p_v_new, p3_old, Xbar_d, derivXbar_d);\n  \n  // Update the hydrostatic strength\n  double p0     = d_crushParam.p0;\n  double p1_sat = d_crushParam.p1_sat;\n  double Xbar_new = p0 + (1.0 - Sw0 + p1_sat*Sw0)*(Xbar_d - p0) + 3.0*pbar_w_new;\n  /*\n    if (state.particleID == 3377699720593411) {\n    std::cout << \"pbar_w_old = \" << pbar_w_old\n    << \"pbar_w_new = \" << pbar_w_new\n    << \"Xbar_d = \" << Xbar_d\n    << \"Xbar_new = \" << Xbar_new << std::endl;\n    }\n  */\n\n#ifdef CHECK_FOR_NAN\n  if (std::isnan(Xbar_new)) {\n    std::cout << \"State = \" << state << std::endl;\n    std::cout << \"epsbar_p_v_new = \" << epsbar_p_v_new << std::endl;\n    std::cout << \"epsbar_p_v_old \" << epsbar_p_v_old << std::endl;\n    std::cout << \"delta_epsbar_p_v = \" << delta_epsbar_p_v << std::endl;\n    std::cout << \"pbar_w_old = \" << pbar_w_old\n              << \"pbar_w_new = \" << pbar_w_new\n              << \"Xbar_d = \" << Xbar_d\n              << \"Xbar_new = \" << Xbar_new << std::endl;\n  }\n#endif\n\n  if (phi_new > 1.0) {\n    proc0cout << \"**WARNING** Porosity > 1.0 in particle \" << state.particleID << std::endl;\n    proc0cout << \"\\t ev_a = \" << epsbar_v_a\n              << \" ev_w = \" << epsbar_v_w\n              << \" ev_p_old = \" << epsbar_p_v_old\n              << \" ev_p = \" << epsbar_p_v_new\n              << \" exp(ev_p - ev_a) = \" << exp_ev_p_minus_ev_a \n              << \" exp(ev_p - ev_w) = \" << exp_ev_p_minus_ev_w \n              << \" phi_new = \" << phi_new << std::endl;\n    //proc0cout << \"** WARNING ** Bad step, deleting particle\"\n    //          << \":\" << __FILE__ << \":\" << __LINE__ << std::endl;\n\n    return false; // May have to delete the particle\n  }\n\n  // Update the state with new values of the internal variables\n  state.pbar_w = pbar_w_new;\n  state.porosity = phi_new;\n  state.saturation = Sw_new;\n  state.capX = -Xbar_new;\n\n  return true;\n}\n                                                      \n/** \n * Method: computeDrainedHydrostaticStrengthAndDeriv\n * Purpose: \n *   Compute the drained hydrostatic compressive strength and its derivative\n */\nvoid \nArenaPartiallySaturated::computeDrainedHydrostaticStrengthAndDeriv(const double& epsbar_p_v,\n                                                                   const double& p3,\n                                                                   double& Xbar_d,\n                                                                   double& derivXbar_d) const\n{\n  // Get the initial porosity\n  double phi0 = d_fluidParam.phi0;\n\n  // Get the crush curve parameters\n  double p0 = d_crushParam.p0;\n  double p1 = d_crushParam.p1;\n  double p2 = d_crushParam.p2;\n  // double p3 = -std::log(1.0 - phi0); // For disaggregation: Use p3 from particle instead\n\n  Xbar_d = p0;\n  derivXbar_d = 0.0;\n  //std::cout << \"\\t\\t eps_bar_p_v = \" << eps_bar_p_v << std::endl;\n  if (epsbar_p_v > 0.0) {\n    double local_epsbar_p_v = std::min(epsbar_p_v, 0.99999999*p3);\n    double phi_temp = std::exp(-p3 + local_epsbar_p_v);\n    double phi = 1.0 - phi_temp;\n    double phi0_phi = phi0/phi;\n    double phi0_phi_minus_one = std::max((phi0_phi - 1.0), 0.0);\n    double xi_bar = p1*std::pow(phi0_phi_minus_one, 1.0/p2);\n    Xbar_d += xi_bar;\n    derivXbar_d = 1.0/p2*phi0_phi*phi_temp*xi_bar/(phi*phi0_phi_minus_one);\n#ifdef CHECK_FOR_NAN\n    if (std::isnan(Xbar_d)) {\n      proc0cout << \"**ERROR** NaN in hydrostatic compressive strength.\" << std::endl;\n      proc0cout << \"\\t Local values : epsbar_p_v = \" << local_epsbar_p_v << std::endl;\n      proc0cout << \"\\t\\t phi_temp = \" << phi_temp << \" phi = \" << phi << \" xi_bar = \" << xi_bar\n                << \" Xbar_d = \" << Xbar_d \n                << \" dXbar_d = \" << derivXbar_d << std::endl; \n    }\n#endif\n  } \n\n  return;\n}\n\n/**\n * Function: updateDamageParameters\n *\n * Purpose: Update the damage parameters local to this model\n */\nvoid \nArenaPartiallySaturated::updateDamageParameters(const Uintah::Matrix3& D,\n                                                const double& delta_t,\n                                                const ModelState_Arena& state_k_old,\n                                                ModelState_Arena& state_k_new) const\n{\n#ifndef TEST_FRACTURE_STRAIN_CRITERION\n  // Compute total strain increment\n  Uintah::Matrix3 deltaEps = D*delta_t;\n  double deltaEpsNorm = deltaEps.Norm();\n\n  // Compute plastic strain increment\n  Uintah::Matrix3 deltaEps_p = state_k_new.plasticStrainTensor - state_k_old.plasticStrainTensor;\n  double deltaEps_p_Norm = deltaEps_p.Norm();\n\n  // Compute fraction of time increment spent on yield surface\n  double t_grow_inc = std::min(delta_t, (deltaEps_p_Norm/deltaEpsNorm)*delta_t);\n  \n  // Update t_grow\n  double t_grow = state_k_old.t_grow + t_grow_inc;\n\n  // Compute coherence\n  double fspeed = d_damageParam.fSpeed;\n  double xvar = std::exp(-fspeed*(t_grow/d_damageParam.tFail - 1.0));\n  double coher = xvar/(1.0 + xvar);\n\n#ifdef CHECK_DAMAGE_ALGORITHM\n  std::cout << \"||Delta Eps|| = \" << deltaEpsNorm\n            << \" ||Delta Eps_p|| = \" << deltaEps_p_Norm\n            << \" Delta t_grow = \" << t_grow_inc \n            << \" t_grow = \" << t_grow << \" coher = \" << coher << std::endl;\n#endif\n\n  // Update the state\n  state_k_new.t_grow = t_grow;\n  state_k_new.coherence = std::min(coher, state_k_old.coherence);\n\n\n#ifdef CHECK_DAMAGE_ALGORITHM\n  std::cout << \"t_grow = \" << t_grow << \" t_fail = \" << d_damageParam.tFail \n            << \"\\t coherence = \" << state_k_new.coherence << std::endl;\n#endif\n\n#else\n\n  // Compute time rate of plastic strain\n  double eps_p_f_eq = d_damageParam.ep_f_eq;\n  double dot_eps_p_eq = D.Norm();\n  // double dot_eps_p_eq = (state_k_new.ep_cum_eq - state_k_old.ep_cum_eq)/delta_t;\n\n  // If the plastic strain hasn't changed, return the old values\n  if (dot_eps_p_eq < delta_t*1.0e-6) {\n    state_k_new.t_grow = state_k_old.t_grow;\n    state_k_new.coherence = state_k_old.coherence;\n    return;\n  }\n\n  // Update t_grow\n  double t_grow = state_k_new.t_grow + delta_t;\n\n  // Compute t_fail\n  //double eps_p_eq = state_k_new.ep_cum_eq;\n  //double t_fail = t_grow + (eps_p_f_eq - eps_p_eq)/dot_eps_p_eq;\n  double t_fail = eps_p_f_eq/dot_eps_p_eq;\n\n  // Compute coherence\n  double fspeed = d_damageParam.fSpeed;\n  double xvar = std::exp(-fspeed*(t_grow/t_fail - 1.0));\n  double coher = xvar/(1.0 + xvar);\n\n  // Update the state\n  state_k_new.t_grow = t_grow;\n  state_k_new.coherence = std::min(coher, state_k_old.coherence);\n\n#ifdef CHECK_DAMAGE_ALGORITHM\n  std::cout << \"t_grow = \" << t_grow << \" t_fail = \" << t_fail << \" eps_p_f_eq = \" << eps_p_f_eq\n            << \" dot_eps_p_eq = \" << dot_eps_p_eq << \" coher = \" << coher << std::endl\n            << \"\\t coherence = \" << state_k_new.coherence << std::endl;\n  std::cout << \"\\t ep_cum_eq(old) = \" << state_k_old.ep_cum_eq\n            << \" ep_cum_eq(new) = \" << state_k_new.ep_cum_eq\n            << \" ep_eq(old) = \" << state_k_old.ep_eq\n            << \" ep_eq(new) = \" << state_k_new.ep_eq << std::endl;\n#endif\n#endif\n\n  return;\n}\n\n\n//===================================================================\n/** \n * Function: rateDependentPlasticUpdate\n *\n * Purpose:\n *   Rate-dependent plastic step\n *   Compute the new dynamic stress from the old dynamic stress and the new and old QS stress\n *   using Duvaut-Lions rate dependence, as described in \"Elements of Phenomenological Plasticity\",\n *   by RM Brannon.\n */\nbool \nArenaPartiallySaturated::rateDependentPlasticUpdate(const Uintah::Matrix3& D,\n                                                    const double& delT,\n                                                    const ModelState_Arena& stateStatic_old,\n                                                    const ModelState_Arena& stateStatic_new,\n                                                    const ModelState_Arena& stateDynamic_old,\n                                                    Uintah::Matrix3& pStress_new) \n{\n  // Get the T1 & T2 parameters\n  double T1 = 0.0, T2 = 0.0;\n  try {\n    T1 = stateStatic_old.yieldParams.at(\"T1\");\n    T2 = stateStatic_old.yieldParams.at(\"T2\");\n  } catch (std::out_of_range) {\n    std::ostringstream err;\n    err << \"**ERROR** Could not find yield parameters T1 and T2\" << std::endl;\n    for (auto param : stateStatic_old.yieldParams) {\n      err << param.first << \" \" << param.second << std::endl;\n    }\n    throw Uintah::InternalError(err.str(), __FILE__, __LINE__);\n  }\n\n  // Check if rate-dependent plasticity has been turned on\n  if (T1 == 0.0 || T2 == 0.0) {\n\n    // No rate dependence, the dynamic stress equals the static stress.\n    pStress_new = stateStatic_new.stressTensor;\n    // bool isRateDependent = false;\n    return false;\n\n  }\n\n  // This is not straightforward, due to nonlinear elasticity.  The equation requires that we\n  // compute the trial stress for the step, but this is not known, since the bulk modulus is\n  // evolving through the substeps.  It would be necessary to to loop through the substeps to\n  // compute the trial stress assuming nonlinear elasticity, but instead we will approximate\n  // the trial stress the average of the elastic moduli at the start and end of the step.\n\n  // Compute midstep bulk and shear modulus\n  ModelState_Arena stateDynamic(stateDynamic_old);\n  stateDynamic.bulkModulus = 0.5*(stateStatic_old.bulkModulus + stateStatic_new.bulkModulus);\n  stateDynamic.shearModulus = 0.5*(stateStatic_old.shearModulus + stateStatic_new.shearModulus);\n\n  Uintah::Matrix3 strain_inc = D*delT;\n  if (strain_inc.Norm() < 1.0e-30) {\n    pStress_new = stateStatic_new.stressTensor;\n    return true;\n  }\n\n  Uintah::Matrix3 sigma_trial = computeTrialStress(stateDynamic, strain_inc);\n\n  // The characteristic time is defined from the rate dependence input parameters and the\n  // magnitude of the strain rate.\n  // tau = T1*(epsdot)^(-T2) = T1*(1/epsdot)^T2, modified to avoid division by zero.\n  double tau = T1*std::pow(1.0/std::max(D.Norm(), 1.0e-15), T2);\n\n  // RH and rh are defined by eq. 6.93 in the RMB book chapter, but there seems to be a sign error\n  // in the text, and I've rewritten it to avoid computing the exponential twice.\n  double dtbytau = delT/tau;\n  double rh  = std::exp(-dtbytau);\n  double RH  = (1.0 - rh)/dtbytau;\n\n  // sigma_new = sigmaQS_new + sigma_over_new, as defined by eq. 6.92\n  // sigma_over_new = [(sigma_trial_new - sigma_old) - (sigmaQS_new-sigmaQS_old)]*RH + sigma_over_old*rh\n  Uintah::Matrix3 sigmaQS_old = stateStatic_old.stressTensor;\n  Uintah::Matrix3 sigmaQS_new = stateStatic_new.stressTensor;\n  Uintah::Matrix3 sigma_old = stateDynamic_old.stressTensor;\n  pStress_new = sigmaQS_new\n    + ((sigma_trial - sigma_old) - (sigmaQS_new - sigmaQS_old))*RH\n    + (sigma_old - sigmaQS_old)*rh;\n\n  // bool isRateDependent = true;\n  return true;\n}\n\n\n// ****************************************************************************************************\n// ****************************************************************************************************\n// ************** PUBLIC Uintah MPM constitutive model specific functions *****************************\n// ****************************************************************************************************\n// ****************************************************************************************************\n\nvoid ArenaPartiallySaturated::carryForward(const Uintah::PatchSubset* patches,\n                                           const Uintah::MPMMaterial* matl,\n                                           Uintah::DataWarehouse* old_dw,\n                                           Uintah::DataWarehouse* new_dw)\n{\n  // Carry forward the data.\n  for(int p=0;p<patches->size();p++){\n    const Uintah::Patch* patch = patches->get(p);\n    int matID = matl->getDWIndex();\n    Uintah::ParticleSubset* pset = old_dw->getParticleSubset(matID, patch);\n\n    // Carry forward the data common to all constitutive models\n    // when using RigidMPM.\n    // This method is defined in the ConstitutiveModel base class.\n    carryForwardSharedData(pset, old_dw, new_dw, matl);\n\n    // Carry forward the data local to this constitutive model\n    new_dw->put(Uintah::delt_vartype(1.e10), lb->delTLabel, patch->getLevel());\n\n    if (flag->d_reductionVars->accStrainEnergy ||\n        flag->d_reductionVars->strainEnergy) {\n      new_dw->put(Uintah::sum_vartype(0.0),     lb->StrainEnergyLabel);\n    }\n  }\n}\n\n\n//T2D: Throw exception that this is not supported\nvoid ArenaPartiallySaturated::addComputesAndRequires(Uintah::Task* ,\n                                                     const Uintah::MPMMaterial* ,\n                                                     const Uintah::PatchSet* ,\n                                                     const bool, \n                                                     const bool ) const\n{\n  std::cout << \"NO Implicit VERSION OF addComputesAndRequires EXISTS YET FOR ArenaPartiallySaturated\"<<std::endl;\n}\n\n\n/*! ---------------------------------------------------------------------------------------\n *  This is needed for converting from one material type to another.  The functionality\n *  has been removed from the main Uintah branch.\n *  ---------------------------------------------------------------------------------------\n */\nvoid \nArenaPartiallySaturated::allocateCMDataAdd(Uintah::DataWarehouse* new_dw,\n                                           Uintah::ParticleSubset* addset,\n                                           Uintah::ParticleLabelVariableMap* newState,\n                                           Uintah::ParticleSubset* delset,\n                                           Uintah::DataWarehouse* old_dw)\n{\n  std::ostringstream out;\n  out << \"Material conversion after failure not implemented for ArenaSoil.\";\n  throw Uintah::ProblemSetupException(out.str(), __FILE__, __LINE__);\n  //task->requires(Task::NewDW, pPorosityLabel_preReloc,         matlset, Ghost::None);\n  //task->requires(Task::NewDW, pSaturationLabel_preReloc,       matlset, Ghost::None);\n}\n\n/*---------------------------------------------------------------------------------------\n * MPMICE Hooks\n *---------------------------------------------------------------------------------------*/\ndouble ArenaPartiallySaturated::computeRhoMicroCM(double pressure,\n                                                  const double p_ref,\n                                                  const Uintah::MPMMaterial* matl,\n                                                  double temperature,\n                                                  double rho_guess)\n{\n  double rho_0 = matl->getInitialDensity();\n  double K0 = d_cm.K0_Murnaghan_EOS;\n  double n = d_cm.n_Murnaghan_EOS;\n\n  double p_gauge = pressure - p_ref;\n  double rho_cur = rho_0*std::pow(((n*p_gauge)/K0 + 1), (1.0/n));\n\n  return rho_cur;\n}\n\nvoid ArenaPartiallySaturated::computePressEOSCM(double rho_cur,\n                                                double& pressure, double p_ref,\n                                                double& dp_drho, \n                                                double& soundSpeedSq,\n                                                const Uintah::MPMMaterial* matl,\n                                                double temperature)\n{\n  double rho_0 = matl->getInitialDensity();\n  double K0 = d_cm.K0_Murnaghan_EOS;\n  double n = d_cm.n_Murnaghan_EOS;\n\n  double eta = rho_cur/rho_0;\n  double p_gauge = K0/n*(std::pow(eta, n) - 1.0);\n\n  double bulk = K0 + n*p_gauge;\n  // double nu = 0.0;\n  double shear = 1.5*bulk;\n\n  pressure = p_ref + p_gauge;\n  dp_drho  = K0*std::pow(eta, n-1);\n  soundSpeedSq = (bulk + 4.0*shear/3.0)/rho_cur;  // speed of sound squared\n}\n\ndouble ArenaPartiallySaturated::getCompressibility()\n{\n  std::cout << \"NO VERSION OF getCompressibility EXISTS YET FOR ArenaPartiallySaturated\"\n            << std::endl;\n  return 1.0/d_cm.K0_Murnaghan_EOS;\n}\n\n", "meta": {"hexsha": "ad5cbe7a6265cc260a3282199f8acc3e7064ad8f", "size": 120198, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/CCA/Components/MPM/Materials/ConstitutiveModel/ArenaSoilBanerjeeBrannon/ArenaPartiallySaturated.cc", "max_stars_repo_name": "abagusetty/Uintah", "max_stars_repo_head_hexsha": "fa1bf819664fa6f09c5a7cd076870a40816d35c9", "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/MPM/Materials/ConstitutiveModel/ArenaSoilBanerjeeBrannon/ArenaPartiallySaturated.cc", "max_issues_repo_name": "abagusetty/Uintah", "max_issues_repo_head_hexsha": "fa1bf819664fa6f09c5a7cd076870a40816d35c9", "max_issues_repo_licenses": ["MIT"], "max_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/MPM/Materials/ConstitutiveModel/ArenaSoilBanerjeeBrannon/ArenaPartiallySaturated.cc", "max_forks_repo_name": "abagusetty/Uintah", "max_forks_repo_head_hexsha": "fa1bf819664fa6f09c5a7cd076870a40816d35c9", "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": 42.9585418156, "max_line_length": 120, "alphanum_fraction": 0.6408509293, "num_tokens": 33031, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7090191337850932, "lm_q2_score": 0.48438008427698437, "lm_q1q2_score": 0.3434347477768179}}
{"text": "//---------------------------------------------------------------------------//\n// Copyright (c) 2020 Mikhail Komarov <nemo@nil.foundation>\n// Copyright (c) 2019 Alexey Moskvin\n// Copyright (c) 2020 Ilias Khairullin <ilias@nil.foundation>\n//\n// Distributed under the Boost Software License, Version 1.0\n// See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt\n//---------------------------------------------------------------------------//\n\n#ifndef BOOST_MULTIPRECISION_MONTGOMERY_PARAMS_HPP\n#define BOOST_MULTIPRECISION_MONTGOMERY_PARAMS_HPP\n\n#include <boost/container/vector.hpp>\n\n#include <boost/type_traits/is_integral.hpp>\n\n#include <nil/crypto3/multiprecision/cpp_int.hpp>\n#include <nil/crypto3/multiprecision/cpp_int/cpp_int_config.hpp>\n#include <nil/crypto3/multiprecision/modular/base_params.hpp>\n#include <nil/crypto3/multiprecision/modular/barrett_params.hpp>\n\n#include <type_traits>\n#include <tuple>\n#include <array>\n#include <cstddef>    // std::size_t\n#include <limits>\n#include <string>\n\nnamespace nil {\n    namespace crypto3 {\n        namespace multiprecision {\n            namespace backends {\n                /**\n                 * Parameters for Montgomery Reduction\n                 */\n                template<typename Backend>\n                class montgomery_params : public base_params<Backend> {\n                    typedef number<Backend> number_type;\n\n                protected:\n                    template<typename Number>\n                    inline void initialize_montgomery_params(const Number& p) {\n                        this->initialize_base_params(p);\n                        find_const_variables(p);\n                    }\n\n                    inline void initialize_montgomery_params(const montgomery_params<Backend>& p) {\n                        this->initialize_base_params(p);\n                        find_const_variables(p);\n                    }\n\n                    limb_type monty_inverse(limb_type a) {\n                        if (a % 2 == 0) {\n                            throw std::invalid_argument(\"Monty_inverse only valid for odd integers\");\n                        }\n\n                        limb_type b = 1;\n                        limb_type r = 0;\n\n                        for (size_t i = 0; i != sizeof(limb_type) * CHAR_BIT; ++i) {\n                            const limb_type bi = b % 2;\n                            r >>= 1;\n                            r += bi << (sizeof(limb_type) * CHAR_BIT - 1);\n\n                            b -= a * bi;\n                            b >>= 1;\n                        }\n\n                        // Now invert in addition space\n                        r = (~static_cast<limb_type>(0) - r) + 1;\n\n                        return r;\n                    }\n\n                    template<typename T>\n                    void find_const_variables(const T& pp) {\n                        number_type p = pp;\n                        if (p <= 0 || !(p % 2)) {\n                            return;\n                        }\n\n                        m_p_words = this->m_mod.backend().size();\n\n                        m_p_dash = monty_inverse(this->m_mod.backend().limbs()[0]);\n\n                        number_type r;\n\n                        default_ops::eval_bit_set(r.backend(), m_p_words * sizeof(limb_type) * CHAR_BIT);\n\n                        m_r2 = r * r;\n                        barrett_params<Backend> barrettParams(this->m_mod);\n                        barrettParams.barret_reduce(m_r2.backend());\n                    }\n\n                public:\n                    montgomery_params() : base_params<Backend>() {\n                    }\n\n                    template<typename Number>\n                    explicit montgomery_params(const Number& p) : base_params<Backend>(p) {\n                        initialize_montgomery_params(p);\n                    }\n\n                    inline const number_type& r2() const {\n                        return m_r2;\n                    }\n\n                    inline limb_type p_dash() const {\n                        return m_p_dash;\n                    }\n\n                    inline size_t p_words() const {\n                        return m_p_words;\n                    }\n\n                    template<class V>\n                    montgomery_params& operator=(const V& v) {\n                        initialize_montgomery_params(v);\n                        return *this;\n                    }\n\n                    inline void montgomery_reduce(Backend& result) const {\n                        using default_ops::eval_lt;\n                        using default_ops::eval_multiply_add;\n\n                        typedef cpp_int_backend<sizeof(limb_type) * CHAR_BIT * 3, sizeof(limb_type) * CHAR_BIT * 3,\n                                                unsigned_magnitude, unchecked, void>\n                            cpp_three_int_backend;\n\n                        const size_t p_size = m_p_words;\n                        const limb_type p_dash = m_p_dash;\n                        const size_t z_size = 2 * (p_words() + 1);\n\n                        boost::container::vector<limb_type> z(\n                            result.size(), 0);    // container::vector<limb_type, alloc> z(result.size(), 0);\n                        for (size_t i = 0; i < result.size(); ++i) {\n                            z[i] = result.limbs()[i];\n                        }\n\n                        if (result.size() < z_size) {\n                            result.resize(z_size, z_size);\n                            z.resize(z_size, 0);\n                        }\n\n                        cpp_three_int_backend w(z[0]);\n\n                        result.limbs()[0] = w.limbs()[0] * p_dash;\n\n                        eval_multiply_add(w, result.limbs()[0], this->m_mod.backend().limbs()[0]);\n                        eval_right_shift(w, sizeof(limb_type) * CHAR_BIT);\n\n                        for (size_t i = 1; i != p_size; ++i) {\n                            for (size_t j = 0; j < i; ++j) {\n                                eval_multiply_add(w, result.limbs()[j], this->m_mod.backend().limbs()[i - j]);\n                            }\n\n                            eval_add(w, z[i]);\n\n                            result.limbs()[i] = w.limbs()[0] * p_dash;\n\n                            eval_multiply_add(w, result.limbs()[i], this->m_mod.backend().limbs()[0]);\n\n                            eval_right_shift(w, sizeof(limb_type) * CHAR_BIT);\n                        }\n\n                        for (size_t i = 0; i != p_size; ++i) {\n                            for (size_t j = i + 1; j != p_size; ++j) {\n                                eval_multiply_add(w, result.limbs()[j], this->m_mod.backend().limbs()[p_size + i - j]);\n                            }\n\n                            eval_add(w, z[p_size + i]);\n\n                            result.limbs()[i] = w.limbs()[0];\n\n                            eval_right_shift(w, sizeof(limb_type) * CHAR_BIT);\n                        }\n\n                        eval_add(w, z[z_size - 1]);\n\n                        result.limbs()[p_size] = w.limbs()[0];\n                        result.limbs()[p_size + 1] = w.limbs()[1];\n\n                        if (result.size() != p_size + 1) {\n                            result.resize(p_size + 1, p_size + 1);\n                        }\n                        result.normalize();\n                    }\n\n                protected:\n                    number_type m_r2;\n                    limb_type m_p_dash;\n                    size_t m_p_words;\n                };\n\n                // // fixed precision montgomery params type which supports compile-time execution\n                // template<unsigned MinBits, cpp_integer_type SignType, cpp_int_check_type Checked>\n                // class montgomery_params<cpp_int_backend<MinBits, MinBits, SignType, Checked, void>>\n                //     : public base_params<cpp_int_backend<MinBits, MinBits, SignType, Checked, void>>\n                // {\n                //  protected:\n                //    typedef base_params<cpp_int_backend<MinBits, MinBits, SignType, Checked, void>> base_type;\n                //    typedef typename base_type::policy_type policy_type;\n                //\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                //    typedef typename policy_type::Backend Backend;\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                //    typedef typename policy_type::number_type number_type;\n                //\n                //    constexpr static auto limbs_count = policy_type::limbs_count;\n                //    constexpr static auto limb_bits = policy_type::limb_bits;\n                //\n                //    constexpr void initialize_montgomery_params(const number_type& p)\n                //    {\n                //       this->initialize_base_params(p);\n                //       find_const_variables(p);\n                //       find_modulus_mask();\n                //    }\n                //\n                //    constexpr internal_limb_type monty_inverse(internal_limb_type a)\n                //    {\n                //       if (a % 2 == 0)\n                //       {\n                //          throw std::invalid_argument(\"Monty_inverse only valid for odd integers\");\n                //       }\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                //       {\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(const number_type& pp)\n                //    {\n                //       using padded_dbl_number_type = number<Backend_doubled_padded_limbs>;\n                //\n                //       number_type p = pp;\n                //       if (p <= 0 || !(p % 2))\n                //       {\n                //          return;\n                //       }\n                //\n                //       m_p_words = this->m_mod.backend().size();\n                //\n                //       m_p_dash = monty_inverse(this->m_mod.backend().limbs()[0]);\n                //\n                //       padded_dbl_number_type r;\n                //\n                //       default_ops::eval_bit_set(r.backend(), m_p_words * limb_bits);\n                //\n                //       r = r * r;\n                //       barrett_params<Backend> barrettParams(this->m_mod);\n                //       barrettParams.barret_reduce(r.backend());\n                //       m_r2 = static_cast<Backend>(r.backend());\n                //    }\n                //\n                //    constexpr void find_modulus_mask()\n                //    {\n                //       m_modulus_mask = static_cast<internal_limb_type>(1u);\n                //       eval_left_shift(m_modulus_mask, this->m_mod.backend().size() * limb_bits);\n                //       eval_subtract(m_modulus_mask, static_cast<internal_limb_type>(1u));\n                //    }\n                //\n                //  public:\n                //    constexpr montgomery_params()\n                //        : base_type(), m_p_dash(), m_p_words(), m_modulus_mask() {}\n                //\n                //    constexpr explicit montgomery_params(const number_type& p)\n                //        : base_type(p), m_p_dash(), m_p_words(), m_modulus_mask()\n                //    {\n                //       initialize_montgomery_params(p);\n                //    }\n                //\n                //    constexpr const auto& r2() const { return m_r2; }\n                //\n                //    constexpr auto p_dash() const { return m_p_dash; }\n                //\n                //    constexpr auto p_words() const { return m_p_words; }\n                //\n                //    constexpr const auto& modulus_mask() const { return m_modulus_mask; }\n                //\n                //    constexpr montgomery_params& operator=(const number_type& p)\n                //    {\n                //       initialize_montgomery_params(p);\n                //       return *this;\n                //    }\n                //\n                //    template<typename BackendT,\n                //        typename = typename boost::enable_if<\n                //            /// result should fit in the output parameter\n                //            max_precision<BackendT>::value >= max_precision<Backend>::value>::type>\n                //    constexpr void montgomery_reduce(BackendT& result) const\n                //    {\n                //       BackendT input(result);\n                //       montgomery_reduce(result, input);\n                //    }\n                //\n                //    template<typename Backend1, typename Backend2,\n                //        typename = typename boost::enable_if<\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<Backend2>::value <= max_precision<Backend_doubled_limbs>::value>::type>\n                //    constexpr void montgomery_reduce(Backend1& result, const Backend2& input) const\n                //    {\n                //       Backend_doubled_padded_limbs accum(input);\n                //       Backend_doubled_padded_limbs prod;\n                //\n                //       for (auto i = 0; i < this->m_mod.backend().size(); ++i)\n                //       {\n                //          eval_multiply(prod, this->m_mod.backend(), accum.limbs()[i] * p_dash());\n                //          eval_left_shift(prod, i * limb_bits);\n                //          eval_add(accum, prod);\n                //       }\n                //\n                //       eval_right_shift(accum, this->m_mod.backend().size() * limb_bits);\n                //\n                //       if (accum.compare(this->m_mod.backend()) >= 0)\n                //       {\n                //          eval_subtract(accum, this->m_mod.backend());\n                //       }\n                //       eval_bitwise_and(accum, m_modulus_mask);\n                //       result = accum;\n                //    }\n                //\n                //    template<typename Backend1, typename Backend2,\n                //        typename = typename boost::enable_if<\n                //            /// result should fit in the output parameter\n                //            max_precision<Backend1>::value >= max_precision<Backend>::value &&\n                //            /// multiplier should fit in input parameter type\n                //            max_precision<Backend2>::value >= max_precision<Backend1>::value>::type>\n                //    constexpr void montgomery_mul(Backend1& result, const Backend2& y) const\n                //    {\n                //       Backend2 x(result);\n                //       montgomery_mul(result, x, y);\n                //    }\n                //\n                //    template<typename Backend1, typename Backend2,\n                //             typename = typename boost::enable_if<\n                //                 /// result should fit in the output parameter\n                //                 max_precision<Backend1>::value >= max_precision<Backend>::value &&\n                //                 /// multipliers should consist of the same number of limbs as modulus\n                //                 max_precision<Backend2>::value >= max_precision<Backend>::value>::type>\n                //    constexpr void montgomery_mul(Backend1& result, const Backend2& x, const Backend2& y) const\n                //    {\n                //       using default_ops::eval_lt;\n                //\n                //       /// input parameters should be lesser than modulus\n                //       BOOST_ASSERT(eval_lt(x, this->m_mod.backend()) && eval_lt(y, this->m_mod.backend()));\n                //\n                //       Backend_padded_limbs A(internal_limb_type(0u));\n                //\n                //       for (auto i = 0; i < this->m_mod.backend().size(); i++)\n                //       {\n                //          internal_limb_type u_i = (A.limbs()[0] + get_limb_value(x, i) * get_limb_value(y, 0)) *\n                //          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 = 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                //          // TODO: maybe error here in static_cast<internal_limb_type>(z) if internal_double_limb_type\n                //          is nil::crypto3::multiprecision::number internal_double_limb_type z2 =\n                //          static_cast<internal_double_limb_type>(get_limb_value(this->m_mod.backend(), 0)) *\n                //                                         static_cast<internal_double_limb_type>(u_i) +\n                //                                         static_cast<internal_limb_type>(z) + k2;\n                //          k = z >> std::numeric_limits<internal_limb_type>::digits;\n                //          k2 = z2 >> std::numeric_limits<internal_limb_type>::digits;\n                //\n                //          for (auto j = 1; j < this->m_mod.backend().size(); ++j)\n                //          {\n                //             internal_double_limb_type t = static_cast<internal_double_limb_type>(get_limb_value(y,\n                //             j)) *\n                //                                           static_cast<internal_double_limb_type>(get_limb_value(x,\n                //                                           i)) + A.limbs()[j] + k;\n                //             // TODO: maybe error here in static_cast<internal_limb_type>(t) if\n                //             internal_double_limb_type is nil::crypto3::multiprecision::number\n                //             internal_double_limb_type t2 =\n                //             static_cast<internal_double_limb_type>(get_limb_value(this->m_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] = t2;\n                //             k = t >> std::numeric_limits<internal_limb_type>::digits;\n                //             k2 = t2 >> std::numeric_limits<internal_limb_type>::digits;\n                //          }\n                //          internal_double_limb_type tmp =\n                //          static_cast<internal_double_limb_type>(A.limbs()[this->m_mod.backend().size()]) + k + k2;\n                //          A.limbs()[this->m_mod.backend().size()-1] = tmp;\n                //          A.limbs()[this->m_mod.backend().size()] = tmp >>\n                //          std::numeric_limits<internal_limb_type>::digits;\n                //       }\n                //       A.resize(this->m_mod.backend().size(), 1);\n                //\n                //       if (A.compare(this->m_mod.backend()) >= 0)\n                //       {\n                //          eval_subtract(A, this->m_mod.backend());\n                //       }\n                //       eval_bitwise_and(A, m_modulus_mask);\n                //       result = A;\n                //    }\n                //\n                //    // TODO: replace in modular_params - need to refactor modular_adaptor structure\n                //    template<typename Backend1, typename Backend2,\n                //        typename = typename boost::enable_if<\n                //            /// result should fit in the output parameter\n                //            max_precision<Backend1>::value >= max_precision<Backend>::value>::type>\n                //    constexpr void mont_exp(Backend1& result, const Backend2& exp) const\n                //    {\n                //       Backend1 a(result);\n                //       mont_exp(result, a, exp);\n                //    }\n                //\n                //    // TODO: replace in modular_params - need to refactor modular_adaptor structure\n                //    template<typename Backend1, typename Backend2, typename Backend3,\n                //             typename = typename boost::enable_if<\n                //                 /// result should fit in the output parameter\n                //                 max_precision<Backend1>::value >= max_precision<Backend>::value &&\n                //                 /// input number should fit modulus\n                //                 max_precision<Backend2>::value >= max_precision<Backend>::value>::type>\n                //    constexpr void mont_exp(Backend1& result, const Backend2& a, Backend3 exp) const\n                //    {\n                //       using default_ops::eval_eq;\n                //       using default_ops::eval_right_shift;\n                //       using default_ops::eval_left_shift;\n                //       using default_ops::eval_modulus;\n                //\n                //       Backend_doubled_limbs tmp(static_cast<internal_limb_type>(1u));\n                //       eval_multiply(tmp, r2().backend());\n                //       montgomery_reduce(tmp);\n                //       Backend R_mod_m(tmp);\n                //\n                //       Backend base(a);\n                //\n                //       Backend3 zero(static_cast<internal_limb_type>(0u));\n                //       if (eval_eq(exp, zero))\n                //       {\n                //          result = static_cast<internal_limb_type>(1u);\n                //          return;\n                //       }\n                //       if (eval_eq(this->m_mod.backend(), static_cast<internal_limb_type>(1u)))\n                //       {\n                //          result = static_cast<internal_limb_type>(0u);\n                //          return;\n                //       }\n                //\n                //       while (true)\n                //       {\n                //          internal_limb_type lsb = exp.limbs()[0] & 1u;\n                //          eval_right_shift(exp, static_cast<internal_limb_type>(1u));\n                //          if (lsb)\n                //          {\n                //             montgomery_mul(R_mod_m, base);\n                //             if (eval_eq(exp, zero))\n                //             {\n                //                break;\n                //             }\n                //          }\n                //          montgomery_mul(base, base);\n                //       }\n                //       result = R_mod_m;\n                //    }\n                //\n                //  protected:\n                //    number_type m_r2;\n                //    internal_limb_type m_p_dash;\n                //    size_t m_p_words;\n                //    Backend_padded_limbs m_modulus_mask;\n                // };\n            }    // namespace backends\n        }        // namespace multiprecision\n    }            // namespace crypto3\n}    // namespace nil\n\n#endif\n", "meta": {"hexsha": "da8d443b067a4ece7e98b3d7d9fce6cb329183ed", "size": 24398, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "snark-logic/libs-source/multiprecision/include/nil/crypto3/multiprecision/modular/montgomery_params.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": "snark-logic/libs-source/multiprecision/include/nil/crypto3/multiprecision/modular/montgomery_params.hpp", "max_issues_repo_name": "podlodkin/podlodkin-freeton-year-control", "max_issues_repo_head_hexsha": "e394c11f2414804d2fbde93a092ae589d4359739", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "snark-logic/libs-source/multiprecision/include/nil/crypto3/multiprecision/modular/montgomery_params.hpp", "max_forks_repo_name": "podlodkin/podlodkin-freeton-year-control", "max_forks_repo_head_hexsha": "e394c11f2414804d2fbde93a092ae589d4359739", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-08-31T06:27:19.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-31T06:27:19.000Z", "avg_line_length": 49.3886639676, "max_line_length": 120, "alphanum_fraction": 0.4292974834, "num_tokens": 4757, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6150878555160665, "lm_q2_score": 0.5583269943353745, "lm_q1q2_score": 0.34342015362247647}}
{"text": "/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */\n\n/*\n Copyright (C)  2017 Cord Harms\n\n This file is part of QuantLib, a free-software/open-source library\n for financial quantitative analysts and developers - http://quantlib.org/\n\n QuantLib is free software: you can redistribute it and/or modify it\n under the terms of the QuantLib license.  You should have received a\n copy of the license along with this program; if not, please email\n <quantlib-dev@lists.sf.net>. The license is also available online at\n <http://quantlib.org/license.shtml>.\n\n This program is distributed in the hope that it will be useful, but WITHOUT\n ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n FOR A PARTICULAR PURPOSE.  See the license for more details.\n*/\n\n#include <ql/experimental/termstructures/localcorrtermstructure.hpp>\n#include <ql/quotes/simplequote.hpp>\n#include <boost/make_shared.hpp>\n\nnamespace QuantLib {\n\n    LocalCorrTermStructure::LocalCorrTermStructure(const std::vector<boost::shared_ptr<QuantLib::GeneralizedBlackScholesProcess>>& processes, \n\t\t\t\t\t\t\t\t\t\t\t\t   const boost::shared_ptr<QuantLib::GeneralizedBlackScholesProcess>&\t\t\t\t\t\t\t\t   processToCal)\n    : CorrelationTermStructureStrike(processes[0]->blackVolatility()->referenceDate(), \n\t\tprocesses[0]->blackVolatility()->calendar(), \n\t\tprocesses[0]->blackVolatility()->businessDayConvention(), \n\t\tprocesses[0]->blackVolatility()->dayCounter()), processToCal_(processToCal){\n\t\n\t\tprocesses_ = std::vector<boost::shared_ptr<QuantLib::HestonSLVProcess>>(processes.size());\n\t\t\n\t\tfor (size_t i = 0; i < processes_.size(); i++)\n\t\t{\n\t\t\tprocesses_[i] = boost::shared_ptr<QuantLib::HestonSLVProcess >( new QuantLib::HestonSLVProcess(\n\t\t\t\tboost::shared_ptr<QuantLib::HestonProcess >(new QuantLib::HestonProcess(\n\t\t\t\t\t\tprocesses[i]->riskFreeRate(), processes[i]->dividendYield(), \n\t\t\t\t\t\tHandle<Quote>(boost::make_shared<SimpleQuote>(processes[i]->x0())),1.0,\n\t\t\t\t\t\t0.0,0.0,0.0,0.0))\n\t\t\t\t, boost::shared_ptr<LocalVolTermStructure>(processes[i]->localVolatility().currentLink())));\n\t\t}\n\t\n\t}\n\n\tLocalCorrTermStructure::LocalCorrTermStructure(const std::vector<boost::shared_ptr<QuantLib::HestonSLVProcess>>& processes,\n\t\tconst boost::shared_ptr<QuantLib::GeneralizedBlackScholesProcess>&\t\t\t   processToCal) \n\t\t: CorrelationTermStructureStrike(processes[0]->leverageFct()->referenceDate(),\n\t\t\tprocesses[0]->leverageFct()->calendar(),\n\t\t\tprocesses[0]->leverageFct()->businessDayConvention(),\n\t\t\tprocesses[0]->leverageFct()->dayCounter()), processToCal_(processToCal), processes_(processes) {}\n\n    void LocalCorrTermStructure::localCorr(RealStochasticProcess::MatA& corrMatrix, \n\t\t\t\t\t\t\t\t\t\t\t   const Date& d,\n\t\t\t\t\t\t\t\t\t\t\t   const RealStochasticProcess::VecA& X0,\n                                               bool extrapolate) {\n        \n\t\tfor (size_t i = 0; i < X0.size(); i++)\n\t\t{\n\t\t\tcheckRange(d, extrapolate);\n\t\t\tcheckStrike(X0[i], i, extrapolate);\n\t\t} \n        Time t = timeFromReference(d);\n        \n\t\tlocalCorrImpl(corrMatrix, t, X0,extrapolate);\n    }\n\n    void LocalCorrTermStructure::localCorr(RealStochasticProcess::MatA& corrMatrix, \n\t\t\t\t\t\t\t\t\t\t\t   Time t,\n\t\t\t\t\t\t\t\t\t\t\t   const RealStochasticProcess::VecA& X0,\n                                               bool extrapolate) {\n\t\tcheckRange(t, extrapolate);\n\t\tfor (size_t i = 0; i < X0.size(); i++)\n\t\t{\n\t\t\tcheckStrike(X0[i], i, extrapolate);\n\t\t}\n        localCorrImpl(corrMatrix, t, X0, extrapolate);\n\n\t\t//cap to 1 and floor to -1:\n\t\tfor (size_t i = 0; i < corrMatrix.size(); i++)\n\t\t{\n\t\t\tfor (size_t j = i+1; j < corrMatrix.size(); j++)\n\t\t\t{\n\t\t\t\tif (corrMatrix[i][j] > 1 || corrMatrix[i][j] < -1) {\n\t\t\t\t\tQL_FAIL(\"Correlation values have to be checked and corrected by checkLambdaValue function.\");\n\t\t\t\t}\n\t\t\t}\n\t\t}\n    }\n\n    void LocalCorrTermStructure::accept(AcyclicVisitor& v) {\n        Visitor<LocalCorrTermStructure>* v1 =\n            dynamic_cast<Visitor<LocalCorrTermStructure>*>(&v);\n        if (v1 != 0)\n            v1->visit(*this);\n        else\n            QL_FAIL(\"not a local-Correlation term structure visitor\");\n    }\n\n\tconst Date& LocalCorrTermStructure::referenceDate() const {\n\t\treturn processes_[0]->leverageFct()->referenceDate();\n\t}\n\n\tDayCounter LocalCorrTermStructure::dayCounter() const {\n\t\treturn processes_[0]->leverageFct()->dayCounter();\n\t}\n\n\tDate LocalCorrTermStructure::maxDate() const {\n\t\tDate minMaxDate = processes_[0]->leverageFct()->maxDate();\n\t\tfor (size_t i = 0; i < processes_.size(); i++)\n\t\t{\n\t\t\tif (minMaxDate < processes_[i]->leverageFct()->maxDate()) minMaxDate = processes_[i]->leverageFct()->maxDate();\n\t\t}\n\t\treturn minMaxDate;\n\t}\n\n\tReal LocalCorrTermStructure::minStrike(Natural ulId) const {\n\t\treturn processes_[ulId]->leverageFct()->minStrike();\n\t}\n\n\tReal LocalCorrTermStructure::maxStrike(Natural ulId) const {\n\t\treturn processes_[ulId]->leverageFct()->maxStrike();\n\t}\n\n}\n", "meta": {"hexsha": "181c8ee79391b04c448d00d061af07d5fecf2d37", "size": 4870, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ql/experimental/termstructures/localcorrtermstructure.cpp", "max_stars_repo_name": "urgu00/QuantLib", "max_stars_repo_head_hexsha": "fecce0abb0ff3d50da29c129f8f9e73176e20ab9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ql/experimental/termstructures/localcorrtermstructure.cpp", "max_issues_repo_name": "urgu00/QuantLib", "max_issues_repo_head_hexsha": "fecce0abb0ff3d50da29c129f8f9e73176e20ab9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 17.0, "max_issues_repo_issues_event_min_datetime": "2020-11-23T07:24:16.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-28T10:29:06.000Z", "max_forks_repo_path": "ql/experimental/termstructures/localcorrtermstructure.cpp", "max_forks_repo_name": "urgu00/QuantLib", "max_forks_repo_head_hexsha": "fecce0abb0ff3d50da29c129f8f9e73176e20ab9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2017-04-24T08:28:43.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-15T08:59:54.000Z", "avg_line_length": 38.3464566929, "max_line_length": 142, "alphanum_fraction": 0.6839835729, "num_tokens": 1331, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6370307944803832, "lm_q2_score": 0.5389832206876841, "lm_q1q2_score": 0.34334890928627115}}
{"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 <cassert>\n#include <cmath>\n#include <cstring>\n\n#include <vector>\n#include <utility>\n#include <exception>\n\n#include <boost/numeric/odeint.hpp>\n\n#include <Rcpp.h>\n\nusing std::vector;\n\nusing Rcpp::NumericMatrix;\nusing Rcpp::NumericVector;\nusing Rcpp::CharacterVector;\nusing Rcpp::XPtr;\nusing Rcpp::wrap;\nusing Rcpp::as;\n\nusing namespace boost::numeric::odeint;\nusing namespace boost::math;\nusing namespace std;\n\n/*\n  Thanks \n  http://www.boost.org/doc/libs/1_55_0/libs/numeric/odeint/doc/html/boost_numeric_odeint/odeint_in_detail/steppers.html#boost_numeric_odeint.odeint_in_detail.steppers.implicit_solvers \n  for example code on an sde\n*/\n\ntemplate< class T > class stochastic_euler\n{\npublic:\n\n    typedef T state_type;\n    typedef T deriv_type;\n    typedef double value_type;\n    typedef double time_type;\n    typedef unsigned short order_type;\n    typedef boost::numeric::odeint::stepper_tag stepper_category;\n\n    static order_type order( void ) { return 1; }\n\n    template< class System >\n    void do_step( System system , state_type &x , time_type t , time_type dt ) const\n    {\n        deriv_type det , stoch ;\n        system.first( x , det );\n        system.second( x , stoch );\n        for( size_t i=0 ; i<x.size() ; ++i )\n            x[i] += dt * det[i] + sqrt( dt ) * stoch[i];\n    }\n};\n\nstruct r_compute{\n  Rcpp::Function f;\n\n  r_compute(Rcpp::Function g) : f(g){}\n\n  void operator()(vector<double> &q, vector<double> &out){\n    out = as<vector<double> >(f(q));\n  }\n  \n};\n\n//' Simulates an SDE explicitly (derivative free)\n//' \n//' For an Ito form SDE dx = f(x) dt + g(x) E sqrt(dt)\n//' \n//' @param d_det R function representing f(x)\n//' @param d_stoch R function representing g(x) E\n//' @param start numeric vector with initial state\n//' @param from scalar with initial time\n//' @param to scalar with final time\n//' @param steps number of steps to take\n//' @export\n// [[Rcpp::export]]\nNumericMatrix solve_general_sde(Rcpp::Function d_det\n\t\t\t   , Rcpp::Function d_stoch\n\t\t\t   , vector<double> start\n\t\t\t   , double from, double to, int steps ) {\n  stochastic_euler< vector<double> > se;\n  const double dt = (to - from)/steps;\n  r_compute sd = r_compute(d_det);\n  r_compute ss = r_compute(d_stoch);\n\n  vector<double> state(start);\n\n  NumericMatrix result(steps+1, start.size());\n\n  for(int j = 0; j < start.size(); ++j)\n    result(0, j) = state[j];\n\n  for(int i = 1; i <= steps; ++i) {\n    se.do_step(std::make_pair(sd, ss), state, i*dt, dt);\n    for(int j = 0; j < start.size(); ++j)\n      result(i, j) = state[j];\n  }\n\n  return result;\n}\n", "meta": {"hexsha": "cda412c744d82c8b6d90825eb08c7f9c3cf91a27", "size": 4216, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/solve_general_sde.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/solve_general_sde.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/solve_general_sde.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": 30.1142857143, "max_line_length": 184, "alphanum_fraction": 0.6987666034, "num_tokens": 1045, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6370307944803831, "lm_q2_score": 0.5389832206876841, "lm_q1q2_score": 0.3433489092862711}}
{"text": "/*\n *\n * Copyright (c) Toon Knapen & Kresimir Fresl 2003\n *\n * Distributed under the Boost Software License, Version 1.0.\n * (See accompanying file LICENSE_1_0.txt or copy at\n * http://www.boost.org/LICENSE_1_0.txt)\n *\n * KF acknowledges the support of the Faculty of Civil Engineering,\n * University of Zagreb, Croatia.\n *\n */\n\n#ifndef BOOST_NUMERIC_BINDINGS_LAPACK_SYSV_HPP\n#define BOOST_NUMERIC_BINDINGS_LAPACK_SYSV_HPP\n\n#include <boost/numeric/bindings/traits/type_traits.hpp>\n#include <boost/numeric/bindings/traits/traits.hpp>\n#include <boost/numeric/bindings/lapack/lapack.h>\n#include <boost/numeric/bindings/traits/detail/array.hpp>\n#include \"boost/numeric/bindings/traits/ublas_symmetric.hpp\"\n#include <boost/numeric/bindings/lapack/ilaenv.hpp>\n\n\n#ifndef BOOST_NUMERIC_BINDINGS_NO_STRUCTURE_CHECK\n#  include <boost/static_assert.hpp>\n#  include <boost/type_traits/is_same.hpp>\n#endif\n\n#include <cassert>\n\nnamespace boost { namespace numeric { namespace bindings {\n\n  namespace lapack {\n\n    /////////////////////////////////////////////////////////////////////\n    //\n    // system of linear equations A * X = B with A symmetric matrix\n    //\n    /////////////////////////////////////////////////////////////////////\n\n    namespace detail {\n\n      inline\n      integer_t sytrf_block (float, integer_t const ispec, char const ul, integer_t const n)\n      {\n        char ul2[2] = \"x\"; ul2[0] = ul; \n        return ilaenv (ispec, \"SSYTRF\", ul2, n);\n      }\n      inline\n      integer_t sytrf_block (double, integer_t const ispec, char const ul, integer_t const n) {\n        char ul2[2] = \"x\"; ul2[0] = ul;\n        return ilaenv (ispec, \"DSYTRF\", ul2, n);\n      }\n      inline\n      integer_t sytrf_block (traits::complex_f,\n                       integer_t const ispec, char const ul, integer_t const n)\n      {\n        char ul2[2] = \"x\"; ul2[0] = ul;\n        return ilaenv (ispec, \"CSYTRF\", ul2, n);\n      }\n      inline\n      integer_t sytrf_block (traits::complex_d,\n                       integer_t const ispec, char const ul, integer_t const n)\n      {\n        char ul2[2] = \"x\"; ul2[0] = ul;\n        return ilaenv (ispec, \"ZSYTRF\", ul2, n);\n      }\n    }\n\n\n    template <typename SymmA>\n    integer_t sytrf_block (char const q, char const ul, SymmA const& a)\n    {\n#ifndef BOOST_NUMERIC_BINDINGS_NO_STRUCTURE_CHECK\n      BOOST_STATIC_ASSERT((boost::is_same<\n        typename traits::matrix_traits<SymmA>::matrix_structure,\n        traits::general_t\n      >::value));\n#endif\n      assert (q == 'O' || q == 'M');\n      assert (ul == 'U' || ul == 'L');\n\n      integer_t n = traits::matrix_size1 (a);\n      assert (n == traits::matrix_size2 (a));\n\n#ifndef BOOST_NUMERIC_BINDINGS_POOR_MANS_TRAITS\n      typedef typename traits::matrix_traits<SymmA>::value_type val_t;\n#else\n      typedef typename SymmA::value_type val_t;\n#endif\n      integer_t ispec = (q == 'O' ? 1 : 2);\n      return detail::sytrf_block (val_t(), ispec, ul, n);\n    }\n\n    template <typename SymmA>\n    integer_t sytrf_block (char const q, SymmA const& a)\n    {\n#ifndef BOOST_NUMERIC_BINDINGS_NO_STRUCTURE_CHECK\n      BOOST_STATIC_ASSERT((boost::is_same<\n        typename traits::matrix_traits<SymmA>::matrix_structure,\n        traits::symmetric_t\n      >::value));\n#endif\n      assert (q == 'O' || q == 'M');\n\n      char ul = traits::matrix_uplo_tag (a);\n      integer_t n = traits::matrix_size1 (a);\n      assert (n == traits::matrix_size2 (a));\n\n#ifndef BOOST_NUMERIC_BINDINGS_POOR_MANS_TRAITS\n      typedef typename traits::matrix_traits<SymmA>::value_type val_t;\n#else\n      typedef typename SymmA::value_type val_t;\n#endif\n      integer_t ispec = (q == 'O' ? 1 : 2);\n      return detail::sytrf_block (val_t(), ispec, ul, n);\n    }\n\n    template <typename SymmA>\n    integer_t sytrf_work (char const q, char const ul, SymmA const& a)\n    {\n#ifndef BOOST_NUMERIC_BINDINGS_NO_STRUCTURE_CHECK\n      BOOST_STATIC_ASSERT((boost::is_same<\n        typename traits::matrix_traits<SymmA>::matrix_structure,\n        traits::general_t\n      >::value));\n#endif\n      assert (q == 'O' || q == 'M');\n      assert (ul == 'U' || ul == 'L');\n\n      integer_t n = traits::matrix_size1 (a);\n      assert (n == traits::matrix_size2 (a));\n\n#ifndef BOOST_NUMERIC_BINDINGS_POOR_MANS_TRAITS\n      typedef typename traits::matrix_traits<SymmA>::value_type val_t;\n#else\n      typedef typename SymmA::value_type val_t;\n#endif\n      integer_t lw = -13;\n      if (q == 'M')\n        lw = 1;\n      if (q == 'O')\n        lw = n * detail::sytrf_block (val_t(), 1, ul, n);\n      return lw;\n    }\n\n    template <typename SymmA>\n    integer_t sytrf_work (char const q, SymmA const& a) {\n\n#ifndef BOOST_NUMERIC_BINDINGS_NO_STRUCTURE_CHECK\n      BOOST_STATIC_ASSERT((boost::is_same<\n        typename traits::matrix_traits<SymmA>::matrix_structure,\n        traits::symmetric_t\n      >::value));\n#endif\n      assert (q == 'O' || q == 'M');\n\n      char ul = traits::matrix_uplo_tag (a);\n      integer_t n = traits::matrix_size1 (a);\n      assert (n == traits::matrix_size2 (a));\n\n#ifndef BOOST_NUMERIC_BINDINGS_POOR_MANS_TRAITS\n      typedef typename traits::matrix_traits<SymmA>::value_type val_t;\n#else\n      typedef typename SymmA::value_type val_t;\n#endif\n      integer_t lw = -13;\n      if (q == 'M')\n        lw = 1;\n      if (q == 'O')\n        lw = n * detail::sytrf_block (val_t(), 1, ul, n);\n      return lw;\n    }\n\n\n    template <typename SymmA>\n    inline\n    integer_t sysv_work (char const q, char const ul, SymmA const& a) {\n      return sytrf_work (q, ul, a);\n    }\n\n    template <typename SymmA>\n    inline\n    integer_t sysv_work (char const q, SymmA const& a) { return sytrf_work (q, a); }\n\n\n    /*\n     * sysv() computes the solution to a system of linear equations\n     * A * X = B, where A is an N-by-N symmetric matrix and X and B\n     * are N-by-NRHS matrices.\n     *\n     * The diagonal pivoting method is used to factor A as\n     *   A = U * D * U^T,  if UPLO = 'U',\n     *   A = L * D * L^T,  if UPLO = 'L',\n     * where  U (or L) is a product of permutation and unit upper\n     * (lower) triangular matrices, and D is symmetric and block\n     * diagonal with 1-by-1 and 2-by-2 diagonal blocks.\n     * The factored form of A is then used to solve the system\n     * of equations A * X = B.\n     */\n\n    namespace detail\n    {\n\n      inline\n      void sysv (char const uplo, integer_t const n, integer_t const nrhs,\n                 float* a, integer_t const lda, integer_t* ipiv,\n                 float* b, integer_t const ldb,\n                 float* w, integer_t const lw, integer_t* info)\n      {\n        LAPACK_SSYSV (&uplo, &n, &nrhs, a, &lda, ipiv, b, &ldb, w, &lw, info);\n      }\n\n      inline\n      void sysv (char const uplo, integer_t const n, integer_t const nrhs,\n                 double* a, integer_t const lda, integer_t* ipiv,\n                 double* b, integer_t const ldb,\n                 double* w, integer_t const lw, integer_t* info)\n      {\n        LAPACK_DSYSV (&uplo, &n, &nrhs, a, &lda, ipiv, b, &ldb, w, &lw, info);\n      }\n\n      inline\n      void sysv (char const uplo, integer_t const n, integer_t const nrhs,\n                 traits::complex_f* a, integer_t const lda, integer_t* ipiv,\n                 traits::complex_f* b, integer_t const ldb,\n                 traits::complex_f* w, integer_t const lw, integer_t* info)\n      {\n        LAPACK_CSYSV (&uplo, &n, &nrhs,\n                      traits::complex_ptr (a), &lda, ipiv,\n                      traits::complex_ptr (b), &ldb,\n                      traits::complex_ptr (w), &lw, info);\n      }\n\n      inline\n      void sysv (char const uplo, integer_t const n, integer_t const nrhs,\n                 traits::complex_d* a, integer_t const lda, integer_t* ipiv,\n                 traits::complex_d* b, integer_t const ldb,\n                 traits::complex_d* w, integer_t const lw, integer_t* info)\n      {\n        LAPACK_ZSYSV (&uplo, &n, &nrhs,\n                      traits::complex_ptr (a), &lda, ipiv,\n                      traits::complex_ptr (b), &ldb,\n                      traits::complex_ptr (w), &lw, info);\n      }\n\n      template <typename SymmA, typename MatrB, typename IVec, typename Work>\n      int sysv (char const ul, SymmA& a, IVec& i, MatrB& b, Work& w)\n      {\n        integer_t const n = traits::matrix_size1 (a);\n        assert (n == traits::matrix_size2 (a));\n        assert (n == traits::matrix_size1 (b));\n        assert (n == traits::vector_size (i));\n\n        integer_t info;\n        sysv (ul, n, traits::matrix_size2 (b),\n              traits::matrix_storage (a),\n              traits::leading_dimension (a),\n              traits::vector_storage (i),\n              traits::matrix_storage (b),\n              traits::leading_dimension (b),\n              traits::vector_storage (w),\n              traits::vector_size (w),\n              &info);\n        return info;\n      }\n\n    }\n\n    template <typename SymmA, typename MatrB, typename IVec, typename Work>\n    inline\n    int sysv (char const ul, SymmA& a, IVec& i, MatrB& b, Work& w)\n    {\n      assert (ul == 'U' || ul == 'L');\n\n#ifndef BOOST_NUMERIC_BINDINGS_NO_STRUCTURE_CHECK\n      BOOST_STATIC_ASSERT((boost::is_same<\n        typename traits::matrix_traits<SymmA>::matrix_structure,\n        traits::general_t\n      >::value));\n      BOOST_STATIC_ASSERT((boost::is_same<\n        typename traits::matrix_traits<MatrB>::matrix_structure,\n        traits::general_t\n      >::value));\n#endif\n\n      assert (traits::vector_size (w) >= 1);\n      return detail::sysv (ul, a, i, b, w);\n    }\n\n    template <typename SymmA, typename MatrB, typename IVec, typename Work>\n    inline\n    int sysv (SymmA& a, IVec& i, MatrB& b, Work& w) {\n\n#ifndef BOOST_NUMERIC_BINDINGS_NO_STRUCTURE_CHECK\n      BOOST_STATIC_ASSERT((boost::is_same<\n        typename traits::matrix_traits<SymmA>::matrix_structure,\n        traits::symmetric_t\n      >::value));\n      BOOST_STATIC_ASSERT((boost::is_same<\n        typename traits::matrix_traits<MatrB>::matrix_structure,\n        traits::general_t\n      >::value));\n#endif\n\n      assert (traits::vector_size (w) >= 1);\n      char uplo = traits::matrix_uplo_tag (a);\n      return detail::sysv (uplo, a, i, b, w);\n    }\n\n    template <typename SymmA, typename MatrB>\n    int sysv (char const ul, SymmA& a, MatrB& b)\n    {\n      // with 'internal' pivot and work vectors\n\n      assert (ul == 'U' || ul == 'L');\n\n#ifndef BOOST_NUMERIC_BINDINGS_NO_STRUCTURE_CHECK\n      BOOST_STATIC_ASSERT((boost::is_same<\n        typename traits::matrix_traits<SymmA>::matrix_structure,\n        traits::general_t\n      >::value));\n      BOOST_STATIC_ASSERT((boost::is_same<\n        typename traits::matrix_traits<MatrB>::matrix_structure,\n        traits::general_t\n      >::value));\n#endif\n\n      integer_t const n = traits::matrix_size1 (a);\n      integer_t info = -101;\n      traits::detail::array<integer_t> i (n);\n\n      if (i.valid()) {\n        info = -102;\n        integer_t lw = sytrf_work ('O', ul, a);\n        assert (lw >= 1); // paranoia ?\n#ifndef BOOST_NUMERIC_BINDINGS_POOR_MANS_TRAITS\n        typedef typename traits::matrix_traits<SymmA>::value_type val_t;\n#else\n        typedef typename SymmA::value_type val_t;\n#endif\n        traits::detail::array<val_t> w (lw);\n        if (w.valid())\n          info =  detail::sysv (ul, a, i, b, w);\n      }\n      return info;\n    }\n\n    template <typename SymmA, typename MatrB>\n    int sysv (SymmA& a, MatrB& b)\n    {\n      // with 'internal' pivot and work vectors\n\n#ifndef BOOST_NUMERIC_BINDINGS_NO_STRUCTURE_CHECK\n      BOOST_STATIC_ASSERT((boost::is_same<\n        typename traits::matrix_traits<SymmA>::matrix_structure,\n        traits::symmetric_t\n      >::value));\n      BOOST_STATIC_ASSERT((boost::is_same<\n        typename traits::matrix_traits<MatrB>::matrix_structure,\n        traits::general_t\n      >::value));\n#endif\n\n      integer_t const n = traits::matrix_size1 (a);\n      char uplo = traits::matrix_uplo_tag (a);\n      integer_t info = -101;\n      traits::detail::array<integer_t> i (n);\n\n      if (i.valid()) {\n        info = -102;\n        integer_t lw = sytrf_work ('O', a);\n        assert (lw >= 1); // paranoia ?\n#ifndef BOOST_NUMERIC_BINDINGS_POOR_MANS_TRAITS\n        typedef typename traits::matrix_traits<SymmA>::value_type val_t;\n#else\n        typedef typename SymmA::value_type val_t;\n#endif\n        traits::detail::array<val_t> w (lw);\n        if (w.valid())\n          info =  detail::sysv (uplo, a, i, b, w);\n      }\n      return info;\n    }\n\n\n    /*\n     * sytrf() computes the factorization of a symmetric matrix A using\n     * the  Bunch-Kaufman diagonal pivoting method. The form of the\n     * factorization is\n     *    A = U * D * U^T  or  A = L * D * L^T\n     * where U (or L) is a product of permutation and unit upper (lower)\n     * triangular matrices, and D is symmetric and block diagonal with\n     * 1-by-1 and 2-by-2 diagonal blocks.\n     */\n\n    namespace detail\n    {\n      inline\n      void sytrf (char const uplo, integer_t const n,\n                  float* a, integer_t const lda, integer_t* ipiv,\n                  float* w, integer_t const lw, integer_t* info)\n      {\n        LAPACK_SSYTRF (&uplo, &n, a, &lda, ipiv, w, &lw, info);\n      }\n\n      inline\n      void sytrf (char const uplo, integer_t const n,\n                  double* a, integer_t const lda, integer_t* ipiv,\n                  double* w, integer_t const lw, integer_t* info)\n      {\n        LAPACK_DSYTRF (&uplo, &n, a, &lda, ipiv, w, &lw, info);\n      }\n\n      inline\n      void sytrf (char const uplo, integer_t const n,\n                  traits::complex_f* a, integer_t const lda, integer_t* ipiv,\n                  traits::complex_f* w, integer_t const lw, integer_t* info)\n      {\n        LAPACK_CSYTRF (&uplo, &n,\n                       traits::complex_ptr (a), &lda, ipiv,\n                       traits::complex_ptr (w), &lw, info);\n      }\n\n      inline\n      void sytrf (char const uplo, integer_t const n,\n                  traits::complex_d* a, integer_t const lda, integer_t* ipiv,\n                  traits::complex_d* w, integer_t const lw, integer_t* info)\n      {\n        LAPACK_ZSYTRF (&uplo, &n,\n                       traits::complex_ptr (a), &lda, ipiv,\n                       traits::complex_ptr (w), &lw, info);\n      }\n\n      template <typename SymmA, typename IVec, typename Work>\n      int sytrf (char const ul, SymmA& a, IVec& i, Work& w) {\n\n        integer_t const n = traits::matrix_size1 (a);\n        assert (n == traits::matrix_size2 (a));\n        assert (n == traits::vector_size (i));\n\n        integer_t info;\n        sytrf (ul, n, traits::matrix_storage (a),\n               traits::leading_dimension (a),\n               traits::vector_storage (i),\n               traits::vector_storage (w),\n               traits::vector_size (w),\n               &info);\n        return info;\n      }\n\n    }\n\n    template <typename SymmA, typename IVec, typename Work>\n    inline\n    int sytrf (char const ul, SymmA& a, IVec& i, Work& w)\n    {\n      assert (ul == 'U' || ul == 'L');\n\n#ifndef BOOST_NUMERIC_BINDINGS_NO_STRUCTURE_CHECK\n      BOOST_STATIC_ASSERT((boost::is_same<\n        typename traits::matrix_traits<SymmA>::matrix_structure,\n        traits::general_t\n      >::value));\n#endif\n\n      assert (traits::vector_size (w) >= 1);\n      return detail::sytrf (ul, a, i, w);\n    }\n\n    template <typename SymmA, typename IVec, typename Work>\n    inline\n    int sytrf (SymmA& a, IVec& i, Work& w)\n    {\n#ifndef BOOST_NUMERIC_BINDINGS_NO_STRUCTURE_CHECK\n      BOOST_STATIC_ASSERT((boost::is_same<\n        typename traits::matrix_traits<SymmA>::matrix_structure,\n        traits::symmetric_t\n      >::value));\n#endif\n\n      assert (traits::vector_size (w) >= 1);\n      char uplo = traits::matrix_uplo_tag (a);\n      return detail::sytrf (uplo, a, i, w);\n    }\n\n    template <typename SymmA, typename Ivec>\n    int sytrf (char const ul, SymmA& a, Ivec& i)\n    {\n      // with 'internal' work vector\n\n      assert (ul == 'U' || ul == 'L');\n\n#ifndef BOOST_NUMERIC_BINDINGS_NO_STRUCTURE_CHECK\n      BOOST_STATIC_ASSERT((boost::is_same<\n        typename traits::matrix_traits<SymmA>::matrix_structure,\n        traits::general_t\n      >::value));\n#endif\n\n      integer_t info = -101;\n      integer_t lw = sytrf_work ('O', ul, a);\n      assert (lw >= 1); // paranoia ?\n#ifndef BOOST_NUMERIC_BINDINGS_POOR_MANS_TRAITS\n      typedef typename traits::matrix_traits<SymmA>::value_type val_t;\n#else\n      typedef typename SymmA::value_type val_t;\n#endif\n      traits::detail::array<val_t> w (lw);\n      if (w.valid())\n        info =  detail::sytrf (ul, a, i, w);\n      return info;\n    }\n\n    template <typename SymmA, typename Ivec>\n    int sytrf (SymmA& a, Ivec& i)\n    {\n      // with 'internal' work vector\n\n#ifndef BOOST_NUMERIC_BINDINGS_NO_STRUCTURE_CHECK\n      BOOST_STATIC_ASSERT((boost::is_same<\n        typename traits::matrix_traits<SymmA>::matrix_structure,\n        traits::symmetric_t\n      >::value));\n#endif\n\n      char uplo = traits::matrix_uplo_tag (a);\n      integer_t info = -101;\n      integer_t lw = sytrf_work ('O', a);\n      assert (lw >= 1); // paranoia ?\n#ifndef BOOST_NUMERIC_BINDINGS_POOR_MANS_TRAITS\n      typedef typename traits::matrix_traits<SymmA>::value_type val_t;\n#else\n      typedef typename SymmA::value_type val_t;\n#endif\n      traits::detail::array<val_t> w (lw);\n      if (w.valid())\n        info =  detail::sytrf (uplo, a, i, w);\n      return info;\n    }\n\n\n    /*\n     * sytrs() solves a system of linear equations A*X = B with\n     * a symmetric matrix A using the factorization\n     *    A = U * D * U^T   or  A = L * D * L^T\n     * computed by sytrf().\n     */\n\n    namespace detail {\n\n      inline\n      void sytrs (char const uplo, integer_t const n, integer_t const nrhs,\n                  float const* a, integer_t const lda, integer_t const* ipiv,\n                  float* b, integer_t const ldb, integer_t* info)\n      {\n        LAPACK_SSYTRS (&uplo, &n, &nrhs, a, &lda, ipiv, b, &ldb, info);\n      }\n\n      inline\n      void sytrs (char const uplo, integer_t const n, integer_t const nrhs,\n                  double const* a, integer_t const lda, integer_t const* ipiv,\n                  double* b, integer_t const ldb, integer_t* info)\n      {\n        LAPACK_DSYTRS (&uplo, &n, &nrhs, a, &lda, ipiv, b, &ldb, info);\n      }\n\n      inline\n      void sytrs (char const uplo, integer_t const n, integer_t const nrhs,\n                  traits::complex_f const* a, integer_t const lda,\n                  integer_t const* ipiv,\n                  traits::complex_f* b, integer_t const ldb, integer_t* info)\n      {\n        LAPACK_CSYTRS (&uplo, &n, &nrhs,\n                      traits::complex_ptr (a), &lda, ipiv,\n                      traits::complex_ptr (b), &ldb, info);\n      }\n\n      inline\n      void sytrs (char const uplo, integer_t const n, integer_t const nrhs,\n                  traits::complex_d const* a, integer_t const lda,\n                  integer_t const* ipiv,\n                  traits::complex_d* b, integer_t const ldb, integer_t* info)\n      {\n        LAPACK_ZSYTRS (&uplo, &n, &nrhs,\n                       traits::complex_ptr (a), &lda, ipiv,\n                       traits::complex_ptr (b), &ldb, info);\n      }\n\n      template <typename SymmA, typename MatrB, typename IVec>\n      int sytrs (char const ul, SymmA const& a, IVec const& i, MatrB& b) {\n\n        integer_t const n = traits::matrix_size1 (a);\n        assert (n == traits::matrix_size2 (a));\n        assert (n == traits::matrix_size1 (b));\n        assert (n == traits::vector_size (i));\n\n        integer_t info;\n        sytrs (ul, n, traits::matrix_size2 (b),\n#ifndef BOOST_NO_FUNCTION_TEMPLATE_ORDERING\n               traits::matrix_storage (a),\n#else\n               traits::matrix_storage_const (a),\n#endif\n               traits::leading_dimension (a),\n#ifndef BOOST_NO_FUNCTION_TEMPLATE_ORDERING\n               traits::vector_storage (i),\n#else\n               traits::vector_storage_const (i),\n#endif\n               traits::matrix_storage (b),\n               traits::leading_dimension (b), &info);\n        return info;\n      }\n\n    }\n\n    template <typename SymmA, typename MatrB, typename IVec>\n    inline\n    int sytrs (char const ul, SymmA const& a, IVec const& i, MatrB& b) {\n\n      assert (ul == 'U' || ul == 'L');\n\n#ifndef BOOST_NUMERIC_BINDINGS_NO_STRUCTURE_CHECK\n      BOOST_STATIC_ASSERT((boost::is_same<\n        typename traits::matrix_traits<SymmA>::matrix_structure,\n        traits::general_t\n      >::value));\n      BOOST_STATIC_ASSERT((boost::is_same<\n        typename traits::matrix_traits<MatrB>::matrix_structure,\n        traits::general_t\n      >::value));\n#endif\n\n      return detail::sytrs (ul, a, i, b);\n    }\n\n    template <typename SymmA, typename MatrB, typename IVec>\n    inline\n    int sytrs (SymmA const& a, IVec const& i, MatrB& b) {\n\n#ifndef BOOST_NUMERIC_BINDINGS_NO_STRUCTURE_CHECK\n      BOOST_STATIC_ASSERT((boost::is_same<\n        typename traits::matrix_traits<SymmA>::matrix_structure,\n        traits::symmetric_t\n      >::value));\n      BOOST_STATIC_ASSERT((boost::is_same<\n        typename traits::matrix_traits<MatrB>::matrix_structure,\n        traits::general_t\n      >::value));\n#endif\n\n      char uplo = traits::matrix_uplo_tag (a);\n      return detail::sytrs (uplo, a, i, b);\n    }\n\n\n\n    namespace detail\n    {\n      inline\n      void sytri (char const uplo, integer_t const n, float* a, integer_t const lda,\n          integer_t const* ipiv, float* work, integer_t* info)\n      {\n        LAPACK_SSYTRI (&uplo, &n, a, &lda, ipiv, work, info);\n      }\n\n      inline\n      void sytri (char const uplo, integer_t const n, double* a, integer_t const lda,\n          integer_t const* ipiv, double* work, integer_t* info)\n      {\n        LAPACK_DSYTRI (&uplo, &n, a, &lda, ipiv, work, info);\n      }\n\n      inline\n      void sytri (char const uplo, integer_t const n, traits::complex_f* a,\n          integer_t const lda, integer_t const* ipiv, traits::complex_f* work, integer_t* info)\n      {\n        LAPACK_CSYTRI (&uplo, &n, traits::complex_ptr (a), &lda, ipiv,\n            traits::complex_ptr (work), info);\n      }\n\n      inline\n      void sytri (char const uplo, integer_t const n, traits::complex_d* a,\n          integer_t const lda, integer_t const* ipiv, traits::complex_d* work, integer_t* info)\n      {\n        LAPACK_ZSYTRI (&uplo, &n, traits::complex_ptr (a), &lda, ipiv,\n            traits::complex_ptr (work), info);\n      }\n\n      template <typename SymmA, typename IVec, typename Work>\n      int sytri (char const ul, SymmA& a, IVec const& ipiv, Work& work)\n      {\n        assert (ul == 'U' || ul == 'L');\n\n        integer_t const n = traits::matrix_size1 (a);\n        assert (n == traits::matrix_size2 (a));\n        assert (n == traits::vector_size (ipiv));\n        assert (n == traits::vector_size (work));\n\n        integer_t info;\n        //const double* dummy = traits::matrix_storage (a);\n        detail::sytri (ul, n, traits::matrix_storage (a),\n            traits::leading_dimension (a),\n#ifndef BOOST_NO_FUNCTION_TEMPLATE_ORDERING\n            traits::vector_storage (ipiv),\n#else\n            traits::vector_storage_const (ipiv),\n#endif\n            traits::vector_storage (work),\n            &info);\n        return info;\n      }\n\n    } // namespace detail\n\n\n    //Internal allocation of workspace, general matrix with up/low tag\n    template <typename SymmA, typename IVec>\n    int sytri (char const ul, SymmA& a, IVec const& ipiv)\n    {\n      assert (ul == 'U' || ul == 'L');\n\n#ifndef BOOST_NUMERIC_BINDINGS_NO_STRUCTURE_CHECK\n      BOOST_STATIC_ASSERT((boost::is_same<\n            typename traits::matrix_traits<SymmA>::matrix_structure,\n            traits::general_t\n            >::value));\n#endif\n\n      typedef typename SymmA::value_type value_type;\n      std::ptrdiff_t n = traits::matrix_size1(a);\n      traits::detail::array<value_type> work(std::max<std::ptrdiff_t>(1,n));\n\n      return detail::sytri (ul, a, ipiv, work);\n    }\n\n    //Internal allocation of workspace, symmetric matrix\n\n    /*Warning: the function will work only if SymmA is a\n      symmetric_adaptor. With SymmA = symmetric_matrix a\n      boost::STATIC_ASSERTION_FAILURE will be thrown at compile\n      time, because symmetric_matrix has a symmetric_packed_t\n      structure instead of symmetric_t. Use sptri() for\n      symmetric packed matrices.\n      */\n    template <typename SymmA, typename IVec>\n    int sytri (SymmA& a, IVec const& ipiv)\n    {\n\n#ifndef BOOST_NUMERIC_BINDINGS_NO_STRUCTURE_CHECK\n      BOOST_STATIC_ASSERT((boost::is_same<\n        typename traits::matrix_traits<SymmA>::matrix_structure,\n        traits::symmetric_t\n      >::value));\n#endif\n\n      typedef typename SymmA::value_type value_type;\n      std::ptrdiff_t n = traits::matrix_size1(a);\n      traits::detail::array<value_type> work(std::max<std::ptrdiff_t>(1,n));\n\n      char uplo = traits::matrix_uplo_tag (a);\n      return detail::sytri (uplo, a, ipiv, work);\n    }\n\n  } // namespace lapack\n\n}}} // namespace boost::numeric::bindings\n\n#endif\n", "meta": {"hexsha": "8a5c558e7024f183eca3aeb04e8c9e8ec62155fa", "size": 24993, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "PROX/3RDPARTY/BOOST_BINDINGS/boost_bindings/boost/numeric/bindings/lapack/sysv.hpp", "max_stars_repo_name": "diku-dk/PROX", "max_stars_repo_head_hexsha": "c6be72cc253ff75589a1cac28e4e91e788376900", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "PROX/3RDPARTY/BOOST_BINDINGS/boost_bindings/boost/numeric/bindings/lapack/sysv.hpp", "max_issues_repo_name": "diku-dk/PROX", "max_issues_repo_head_hexsha": "c6be72cc253ff75589a1cac28e4e91e788376900", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "PROX/3RDPARTY/BOOST_BINDINGS/boost_bindings/boost/numeric/bindings/lapack/sysv.hpp", "max_forks_repo_name": "diku-dk/PROX", "max_forks_repo_head_hexsha": "c6be72cc253ff75589a1cac28e4e91e788376900", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.3743523316, "max_line_length": 95, "alphanum_fraction": 0.6004481255, "num_tokens": 6661, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6370307944803831, "lm_q2_score": 0.5389832206876841, "lm_q1q2_score": 0.3433489092862711}}
{"text": "#include \"ModalWarpingTrainingModel.h\"\n#include \"Integrator/ImplicitNewMatkSparseIntegrator.h\"\n#include <random>\n#include <fstream>\n#include <iostream>\n#include <time.h> \n#include \"Simulator/DeepWarp/ModalRotationMatrix.h\"\n#include \"Integrator/ImplicitModalWarpingIntegrator.h\"\n#include \"Functions/GeoMatrix.h\"\n#include <Eigen/QR>\n#include \"Functions/findElementInVector.h\"\n#include \"LoboVolumetricMesh/LoboVolumetriceMeshCore.h\"\n#include \"Simulator/ForceField/RotateForceField.h\"\n\n#include \"Simulator/ReducedSTVK/ReducedSTVKModel.h\"\n#include \"Simulator/ReducedForceModel/ReducedForceModel.h\"\n#include \"Simulator/ReducedForceModel/ReducedSTVKForceModel.h\"\n#include \"Integrator/ImpicitNewMarkDenseIntegrator.h\"\n\n\nModalWarpingTrainingModel::ModalWarpingTrainingModel(LoboVolumetricMesh* volumtrciMesh_, VectorXd gravity_, SparseMatrix<double>* modalRotationSparseMatrix_, ModalRotationMatrix* modalrotationMatrix_, MatrixXd* subspaceModes_, int r, double timestep, SparseMatrix<double>* massMatrix_, LoboForceModel* forcemodel_, LoboForceModel* nonlinearforceModel_, int numConstrainedDOFs_, int* constrainedDOFs_, double dampingMassCoef, double dampingStiffnessCoef, bool useStaticSolver) :WarpingMapTrainingModel(subspaceModes_, r, timestep, massMatrix_, forcemodel_, nonlinearforceModel_, numConstrainedDOFs_, constrainedDOFs_, dampingMassCoef, dampingStiffnessCoef, useStaticSolver)\n{\n\tthis->volumtrciMesh = volumtrciMesh_;\n\tthis->modalRotationSparseMatrix = modalRotationSparseMatrix_;\n\tthis->modalrotationMatrix = modalrotationMatrix_;\n\tlocalOrientationMatrixR = new SparseMatrix<double>();\n\tmatrixR_ = new SparseMatrix<double>();\n\n\tthis->gravity = gravity_;\n\n\t//0.001\n\tmodalwarpingintegrator = new ImplicitModalWarpingIntegrator(modalrotationMatrix, modalRotationSparseMatrix,\n\t\tr, 0.001, massMatrix_, loboforceModel, 1, numConstrainedDOFs_, constrainedDOFs_, dampingMassCoef, dampingStiffnessCoef, 1, 1e-7, 0.25, 0.5, false\n\t\t);\n\n\n\tif (subspaceModes->size() > 0)\n\t{\n\t\tstd::cout << \"read modes please\" << std::endl;\n\t\treducedMassMatrix = new MatrixXd();\n\t\t*reducedMassMatrix = subspaceModes->transpose()*(*massMatrix)**subspaceModes;\n\t\tint r = subspaceModes->cols();\n\t\tVectorXd reducedgraivty(r);\n\t\tint R = volumtrciMesh->getNumVertices() * 3;\n\n\t\treducedSTVKmodel = new ReducedSTVKModel(this->volumtrciMesh, this->massMatrix, subspaceModes);\n\n\t\treducedSTVKmodel->computeGravity(&reducedgraivty, massMatrix, R);\n\t\treducedSTVKmodel->setGravityForce(reducedgraivty.data());\n\t\treducedSTVKmodel->setGravity(false);\n\t\treducedSTVKmodel->computeReducedModesCoefficients();\n\n\t\treducedforcemodel = new ReducedSTVKForceModel(reducedSTVKmodel);\n\n\t\treducedIntergrator = new ImpicitNewMarkDenseIntegrator(r, timestep, reducedMassMatrix, reducedforcemodel, 0, 0, dampingMassCoef, dampingStiffnessCoef, 1);\n\t}\n\n\n\tmodalwarpingintegrator->setDampingMassCoef(0.1);\n\tmodalwarpingintegrator->setDampingStiffnessCoef(0.1); //0.1\n\n\tnonLinearIntegrator->setDampingMassCoef(0.3);\n\tnonLinearIntegrator->setDampingStiffnessCoef(0.3);\n\tnonLinearIntegrator->setTimeStep(0.005);\n\n\tintegrator->setDampingMassCoef(0.8);\n\tintegrator->setDampingStiffnessCoef(0.8);\n\n\tnonLinearIntegrator->setMaxInteration(50);\n}\n\nModalWarpingTrainingModel::~ModalWarpingTrainingModel()\n{\n\tdelete localOrientationMatrixR;\n\tdelete matrixR_;\n\tdelete reducedIntergrator;\n\tdelete modalwarpingintegrator;\n\tdelete reducedforcemodel;\n\tdelete reducedSTVKmodel;\n}\n\nvoid ModalWarpingTrainingModel::excute()\n{\n\tif (getForcefieldType() == 1)\n\t{\n\t\tmodalwarpingintegrator->setTimeStep(0.002);\n\t\tmodalwarpingintegrator->setDampingMassCoef(0.2);\n\t\tmodalwarpingintegrator->setDampingStiffnessCoef(0.2); //0.1\n\t\tmethod12Twist();\n\t}\n\telse\n\tif (getForcefieldType() == 0)\n\t{\n\t\tmodalwarpingintegrator->setTimeStep(0.002);\n\t\tmodalwarpingintegrator->setDampingMassCoef(0.5);\n\t\tmodalwarpingintegrator->setDampingStiffnessCoef(0.5); //0.1\n\t\tmethod10();\n\t}\n\t//methodFortwist();\n\t//method9();\n\treturn;\n}\n\nvoid ModalWarpingTrainingModel::getTraingLinearForce(int index, VectorXd &force)\n{\n\t//force = modalwarpingintegrator->getInteranlForce(trainingNonLinearDis[index]);\n\n\t//force = gravity;\n\tVector3d nodeacc = forcefieldDirection[index];\n\tVectorXd fullforce = this->createGravity(nodeacc);\n\tforce = fullforce;\n\t//force = gravity;\n}\n\nvoid ModalWarpingTrainingModel::getTraingLinearForce(VectorXd& lq, VectorXd &force)\n{\n\tforce = modalwarpingintegrator->getInteranlForce(lq);\n\t//force = gravity;\n}\n\nvoid ModalWarpingTrainingModel::getTraingLinearForce(VectorXd& lq, VectorXd &force, double poisson)\n{\n\tLoboVolumetricMesh::Material* materia = volumtrciMesh->getMaterialById(0);\n\tLoboVolumetricMesh::ENuMaterial* enmateria = (LoboVolumetricMesh::ENuMaterial*)materia;\n\tenmateria->setNu(poisson);\n\tmodalwarpingintegrator->updateMaterial();\n\tforce = modalwarpingintegrator->getInteranlForce(lq);\n\n}\n\nEigen::VectorXd ModalWarpingTrainingModel::getNonlinearInternalforce(int disid)\n{\n\treturn nonLinearIntegrator->getInteranlForce(trainingNonLinearDis[disid]);\n}\n\nvoid ModalWarpingTrainingModel::subexcute3()\n{\n\tstd::cout << \"num low fre data.\" << getNumTrainingSet() << std::endl;\n\tstd::cout << \"num high fre data.\" << getNumTrainingHighFreq() << std::endl;\n\n\ttrainingLinearDis.clear();\n\ttrainingNonLinearDis.clear();\n\tint maxIteration = 1000;\n\ttrainingLinearDis.reserve(getNumTrainingSet() + getNumTrainingHighFreq());\n\ttrainingNonLinearDis.reserve(getNumTrainingSet() + getNumTrainingHighFreq());\n\tVectorXd reducedForce(subspaceModes->cols());\n\tint dataCount = 0;\n\n\twhile (dataCount < getNumTrainingSet())\n\t{\n\t\tstd::cout << dataCount << std::endl;\n\t\tsrand(time(NULL) + dataCount);\n\t\tstd::default_random_engine generator;\n\t\tgenerator.seed(time(NULL) + dataCount);\n\t\tstd::uniform_real_distribution<double> latitude_distribution(-forceScale, forceScale);\n\t\tdouble scale = (this->forceScale / getNumTrainingSet()) *(getNumTrainingSet() - dataCount) + 0.01;\n\t\tstd::cout << \"scale \" << scale << std::endl;\n\t\tdouble angle = (PI_/2 / getNumTrainingSet())*dataCount + 0.01;\n\n\t\tVector3d axis(0, 0, 1);\n\n\t\tangle *= -1;\n\n\t\t//axis.setRandom();\n\t\t//axis.normalize();\n\t\t//test\n\n\t\tVectorXd fullforce = this->rotationGravity(gravity, angle, axis);\n\n\t\t//reducedForce.setRandom();\n\t\t//fullforce = (*subspaceModes)*reducedForce;\n\n\t\t//fullforce.setRandom();\n\t\t//fullforce *= scale;\n\n\t\t//fullforce = gravity*scale;\n\n\t\tnonLinearIntegrator->setExternalForces(fullforce.data());\n\t\tnonLinearIntegrator->resetToRest();\n\t\tnonLinearIntegrator->setSaveStepResidual(true);\n\t\tVectorXd q_dis;\n\n\t\t//store training linear dis\n\t\t//trainingLinearDis.push_back(q_dis);\n\t\tdouble preNorm = DBL_MAX;\n\t\tVectorXd preDis = gravity;\n\t\tpreDis.setConstant(1000);\n\n\t\tdouble residual;\n\n\t\tfor (int j = 0; j < maxIteration; j++)\n\t\t{\n\t\t\tnonLinearIntegrator->doTimeStep();\n\t\t\tdouble norm_ = nonLinearIntegrator->getVectorq().norm();\n\t\t\tVectorXd cur_dis = nonLinearIntegrator->getVectorq();\n\n\t\t\tresidual = std::abs((preNorm - norm_) / preNorm);\n\t\t\t//We only pick the displacement which has larget difference\n\t\t\tif (residual > 0.001)\n\t\t\t{\n\t\t\t\tif (norm_ > 0.01)\n\t\t\t\t{\n\t\t\t\t\ttrainingNonLinearDis.push_back(cur_dis);\n\n\t\t\t\t\tVectorXd curExternalForce = nonLinearIntegrator->getStep_residual();\n\t\t\t\t\tmodalwarpingintegrator->setSaveStepResidual(true);\n\t\t\t\t\tconvergeIntegrationLocal(modalwarpingintegrator, curExternalForce, 1000);\n\t\t\t\t\tq_dis = modalwarpingintegrator->getVectorq();\n\n\t\t\t\t\ttrainingLinearDis.push_back(q_dis);\n\n\t\t\t\t\tdataCount++;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tpreNorm = norm_;\n\t\t\tif (residual < 1e-5)\n\t\t\t{\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tif (dataCount > getNumTrainingSet())\n\t\t\t{\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\tnonLinearIntegrator->setSaveStepResidual(false);\n\t}\n}\n\nvoid ModalWarpingTrainingModel::subexcute()\n{\n\tstd::cout << \"num low fre data.\" << getNumTrainingSet() << std::endl;\n\tstd::cout << \"num high fre data.\" << getNumTrainingHighFreq() << std::endl;\n\n\ttrainingLinearDis.clear();\n\ttrainingNonLinearDis.clear();\n\tint maxIteration = 1000;\n\ttrainingLinearDis.reserve(getNumTrainingSet() + getNumTrainingHighFreq());\n\ttrainingNonLinearDis.reserve(getNumTrainingSet() + getNumTrainingHighFreq());\n\tVectorXd reducedForce(subspaceModes->cols());\n\tint dataCount = 0;\n\twhile (dataCount < getNumTrainingSet())\n\t{\n\t\tstd::cout << dataCount << std::endl;\n\t\tsrand(time(NULL) + dataCount);\n\t\tstd::default_random_engine generator;\n\t\tgenerator.seed(time(NULL) + dataCount);\n\t\tstd::uniform_real_distribution<double> latitude_distribution(-forceScale, forceScale);\n\t\tdouble scale = (this->forceScale / getNumTrainingSet()) *(getNumTrainingSet()-dataCount) + 0.01;\n\t\tstd::cout <<\"scale \"<< scale << std::endl;\n\t\tdouble angle = (PI_ / getNumTrainingSet())*dataCount - PI_ / 2 + 0.1;\n\n\t\tVector3d axis(0, 0, 1);\n\t\t//axis.setRandom();\n\t\t//axis.normalize();\n\t\t//test\n\t\tangle = PI_ / 2;\n\n\t\tVectorXd fullforce = this->rotationGravity(gravity, angle, axis);\n\t\t\n\t\t//reducedForce.setRandom();\n\t\t//fullforce = (*subspaceModes)*reducedForce;\n\n\t\t//fullforce.setRandom();\n\t\t//fullforce *= scale;\n\n\t\tfullforce = gravity*scale;\n\n\t\tmodalwarpingintegrator->resetToRest();\n\t\tmodalwarpingintegrator->setSaveStepResidual(true);\n\t\tdouble preNorm = DBL_MAX;\n\t\tdouble residual = DBL_MAX;\n\t\tVectorXd preq = fullforce;\n\t\tpreq.setConstant(10000);\n\n\t\tfor (int j = 0; j < maxIteration; j++)\n\t\t{\n\t\t\tVectorXd fullq = modalwarpingintegrator->getVectorq();\n\t\t\tVectorXd w = (*modalRotationSparseMatrix)*fullq;\n\n\t\t\t//set the external force\n\t\t\tmodalrotationMatrix->computeLocalOrientationMatrixR(localOrientationMatrixR, w);\n\t\t\t//VectorXd mergedExternalForce = (*localOrientationMatrixR)*fullforce;\n\t\t\tmodalwarpingintegrator->setExternalForces(fullforce.data());\n\t\t\tmodalwarpingintegrator->doTimeStep();\n\n\t\t\tdouble norm_ = modalwarpingintegrator->getVectorq().norm();\n\n\t\t\tresidual = std::abs((fullq - preq).norm() / preq.norm());\n\n\t\t\tif (residual > 0.01)\n\t\t\t{\n\t\t\t\tpreNorm = norm_;\n\t\t\t\tpreq = fullq;\n\n\t\t\t\tif (norm_ > 0.01)\n\t\t\t\t{\n\t\t\t\t\tbool reset = false;\n\t\t\t\t\tif (j == 0)\n\t\t\t\t\t{\n\t\t\t\t\t\treset = true;\n\t\t\t\t\t}\n\n\t\t\t\t\tVectorXd q_dis;\n\t\t\t\t\tq_dis = modalwarpingintegrator->getVectorq();\n\t\t\t\t\tw = (*modalRotationSparseMatrix)*q_dis;\n\t\t\t\t\t//store training linear dis\n\t\t\t\t\ttrainingLinearDis.push_back(q_dis);\n\t\t\t\t\tVectorXd curExternalForce = modalwarpingintegrator->getStep_residual();\n\t\t\t\t\tmodalrotationMatrix->computeLocalOrientationMatrixR(localOrientationMatrixR, w,false);\n\t\t\t\t\tcurExternalForce = (*localOrientationMatrixR)*curExternalForce;\n\n\t\t\t\t\tconvergeIntegrationNonLinear(nonLinearIntegrator, curExternalForce, maxIteration, reset);\n\t\t\t\t\tq_dis = nonLinearIntegrator->getVectorq();\n\t\t\t\t\ttrainingNonLinearDis.push_back(q_dis);\n\t\t\t\t\tdataCount++;\n\t\t\t\t\tstd::cout << dataCount << std::endl;\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\n\t\t\tif (residual < 1e-6)\n\t\t\t{\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tif (dataCount > getNumTrainingSet())\n\t\t\t{\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\tmodalwarpingintegrator->setSaveStepResidual(false);\n\t}\n\tstd::cout << \"excute finished\" << std::endl;\n}\n\nvoid ModalWarpingTrainingModel::subexcute2()\n{\n\tstd::vector<Vector3d> nodedisplacement;\n\n\tgenerateRotationVectorSample(M_PI * 2, 0, 3,\n\t\tM_PI / 2, -M_PI / 2, 1,\n\t\t0, M_PI/3, 2, nodedisplacement);\n\n\t/*Vector3d firstNode = nodedisplacement[10];\n\tnodedisplacement.clear();\n\tnodedisplacement.push_back(firstNode);*/\n\n\n\n\tint r = this->gravity.rows();\n\n\tdouble maxNodedisdance = -DBL_MAX;\n\tint maxNodeid = -1;\n\t\n\tfor (int j = 0; j < r / 3; j++)\n\t{\n\t\tif (node_distance[j] > maxNodedisdance)\n\t\t{\n\t\t\tmaxNodedisdance = node_distance[j];\n\t\t\tmaxNodeid = j;\n\t\t}\n\t}\n\n\tLoboNodeBase* nodep = volumtrciMesh->getNodeRef(maxNodeid);\n\tint correspondingSize = 3 + nodep->neighbor.size() * 3;\n\tint Phi_1_Size = nodep->neighbor.size() * 3;\n\tMatrixXd phi1(3, Phi_1_Size);\n\tphi1.setZero();\n\tMatrixXd phi2(3, 3);\n\tphi2.setZero();\n\tMatrixXd phitotal(3, Phi_1_Size + 3);\n\t\n\tfor (int k = 0; k < modalRotationSparseMatrix->outerSize(); ++k)\n\t\tfor (SparseMatrix<double>::InnerIterator it(*modalRotationSparseMatrix, k); it; ++it)\n\t\t{\n\t\t\tif (it.row() / 3 == maxNodeid)\n\t\t\t{\n\t\t\t\tint neighborid = it.col() / 3;\n\t\t\t\tint insideIndex = findElementIndex(nodep->neighbor, neighborid);\n\t\t\t\tif (insideIndex != -1)\n\t\t\t\t{\n\t\t\t\t\tphi1.data()[(insideIndex * 3 + it.col() % 3) * 3 + it.row() % 3] = it.value();\n\t\t\t\t\tphitotal.data()[(insideIndex * 3 + it.col() % 3) * 3 + it.row() % 3] = it.value();\n\n\t\t\t\t}\n\t\t\t\tif (it.col() / 3 == maxNodeid)\n\t\t\t\t{\n\t\t\t\t\tphi2.data()[(it.col() % 3) * 3 + it.row() % 3] = it.value();\n\t\t\t\t\tphitotal.data()[(nodep->neighbor.size() * 3 + it.col() % 3) * 3 + it.row() % 3] = it.value();\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\tMatrixXd invPhi1 = pseudoinverse(phi1);\n\tMatrixXd invPhitotal = pseudoinverse(phitotal);\n\n\tif (subspaceModes == NULL)\n\t{\n\t\tstd::cout << \"subspaceModes is NULL\" << std::endl;\n\t}\n\n\tMatrixXd subModes(Phi_1_Size + 3, subspaceModes->cols());\n\tsubModes.setZero();\n\tfor (int i = 0; i < nodep->neighbor.size() * 3; i++)\n\t{\n\t\tint neighborid = nodep->neighbor[i / 3];\n\t\tint row = neighborid * 3 + i % 3;\n\t\tfor (int j = 0; j < subspaceModes->cols(); j++)\n\t\t{\n\t\t\tsubModes.data()[j*subModes.rows() + i] = subspaceModes->data()[j*subspaceModes->rows() + row];\n\t\t}\n\t}\n\n\tfor (int i = 0; i < 3; i++)\n\t{\n\t\tint row = maxNodeid * 3 + i;\n\t\tfor (int j = 0; j < subspaceModes->cols(); j++)\n\t\t{\n\t\t\tsubModes.data()[j*subModes.rows() + i + Phi_1_Size] = subspaceModes->data()[j*subspaceModes->rows() + row];\n\t\t}\n\t}\n\n\tMatrixXd phiSubModes = phitotal*subModes;\n\tMatrixXd invPhiSubModes = pseudoinverse(phiSubModes);\n\tMatrixXd invSubModes = pseudoinverse(subModes);\n\t\n\tmodalwarpingintegrator->setStoreLagrangeMultipliers(true);\n\n\tint numscale = 1;\n\n\tstd::vector<VectorXd> exforceList;\n\n\tfor (int i = 0; i < subspaceModes->cols(); i++)\n\t{\n\t\tVectorXd lq = subspaceModes->col(i);\n\t\tVectorXd w = (*modalRotationSparseMatrix)*lq;\n\t\tmodalrotationMatrix->computeWarpingRotationMatrixR(localOrientationMatrixR, w);\n\t\tVectorXd nq = *localOrientationMatrixR*lq;\n\t\tVectorXd constrainForce = nonLinearIntegrator->getInteranlForce(nq);\n\t\texforceList.push_back(constrainForce);\n\t}\n\n\tif (0)\n\tfor (int i = 0; i < nodedisplacement.size(); i++)\n\t{\n\t\tVectorXd w(r);\n\t\tw.setZero();\n\n\t\t\n\t\tVector3d w_j = nodedisplacement[i];\n\n\t\tfor (int j = 0; j < numscale; j++)\n\t\t{\n\t\t\tVector3d uscale = Vector3d(0, -j*0.06, 0);\n\n\t\t\tVectorXd targetq;\n\n\t\t\tVectorXd T(nodep->neighbor.size() * 3 + 3);\n\t\t\tT.setZero();\n\n\t\t\tfor (int k = 0; k < T.rows() / 3; k++)\n\t\t\t{\n\t\t\t\tT.data()[k * 3 + 0] = uscale.data()[0];\n\t\t\t\tT.data()[k * 3 + 1] = uscale.data()[1];\n\t\t\t\tT.data()[k * 3 + 2] = uscale.data()[2];\n\t\t\t}\n\n\t\t\ttargetq = invPhitotal*(w_j - phitotal*T);\n\t\t\ttargetq += T;\n\n\t\t\tVectorXd linearq;\n\t\t\tVectorXd reducedq = invPhiSubModes*(w_j);\n\t\t\tlinearq = subModes*reducedq;\n\t\t\ttargetq = linearq + T;\n\n\t\t\tSparseMatrix<double> constrainMatrix;\n\t\t\tVectorXd constrainTarget;\n\n\t\t\tVectorXd lq(r);\n\t\t\tlq.setZero();\n\t\t\tlq = *subspaceModes*invSubModes*targetq;\n\t\t\tw = (*modalRotationSparseMatrix)*lq;\n\t\t\tmodalrotationMatrix->computeWarpingRotationMatrixR(localOrientationMatrixR, w);\n\t\t\tVectorXd nq = *localOrientationMatrixR*lq;\n\n\t\t\tVectorXd constrainForce = nonLinearIntegrator->getInteranlForce(nq);\n\t\t\t/*constrainForce = modalwarpingintegrator->getInteranlForce(lq);\n\t\t\tmodalrotationMatrix->computeLocalOrientationMatrixR(localOrientationMatrixR, w, false);\n\t\t\tconstrainForce = *localOrientationMatrixR*constrainForce;*/\n\t\t\texforceList.push_back(constrainForce);\n\n\t\t\t//VectorXd nq;\n\t\t\t////nq = *localOrientationMatrixR*lq;\n\t\t\t//nq = nonLinearIntegrator->getVectorq();\n\n\t\t\t//trainingLinearDis.push_back(lq);\n\n\t\t\t//trainingNonLinearDis.push_back(nq);\n\t\t}\n\t}\n\n\tint maxIteration = 1000;\n\tint dataCount = 0;\n\t/*VectorXd temp = exforceList[0];\n\texforceList.clear();\n\texforceList.push_back(temp);*/\n\t\n\tthis->setNumTrainingSet(exforceList.size());\n\tthis->setNumTrainingHighFreq(0);\n\n\tstd::cout << \"num low fre data.\" << getNumTrainingSet() << std::endl;\n\tstd::cout << \"num high fre data.\" << getNumTrainingHighFreq() << std::endl;\n\n\tfor (int i = 0; i < exforceList.size(); i++)\n\t{\n\t\tstd::cout <<\"--------\"<< i <<\"----------\"<< std::endl;\n\t\tVectorXd fullforce = exforceList[i];\n\n\t\t//reducedForce.setRandom();\n\t\t//fullforce = (*subspaceModes)*reducedForce;\n\n\t\t//fullforce.setRandom();\n\t\t//fullforce *= scale;\n\n\t\tnonLinearIntegrator->setExternalForces(fullforce.data());\n\t\tnonLinearIntegrator->resetToRest();\n\t\tnonLinearIntegrator->setSaveStepResidual(true);\n\t\tVectorXd q_dis;\n\n\t\t//store training linear dis\n\t\t//trainingLinearDis.push_back(q_dis);\n\t\tdouble preNorm = DBL_MAX;\n\t\tVectorXd preDis = gravity;\n\t\tpreDis.setConstant(1000);\n\n\t\tdouble residual;\n\t\tVectorXd qn = subspaceModes->col(i);\n\t\tbool converged = convergeIntegrationLocal(modalwarpingintegrator, fullforce, 1000, true);\n\t\tVectorXd ql = modalwarpingintegrator->getVectorq();\n\t\ttrainingNonLinearDis.push_back(qn);\n\t\ttrainingLinearDis.push_back(ql);\n\n\t\tif (0)\n\t\tfor (int j = 0; j < maxIteration; j++)\n\t\t{\n\t\t\tnonLinearIntegrator->doTimeStep();\n\n\t\t\tdouble norm_ = nonLinearIntegrator->getVectorq().norm();\n\t\t\tVectorXd cur_dis = nonLinearIntegrator->getVectorq();\n\n\t\t\tresidual = std::abs((preNorm - norm_) / preNorm);\n\t\t\t//We only pick the displacement which has larget difference\n\t\t\tif (residual < 1e-5)\n\t\t\t{\n\t\t\t\tif (norm_ > 0.01)\n\t\t\t\t{\n\t\t\t\t\tVectorXd curExternalForce = nonLinearIntegrator->getStep_residual();\n\t\t\t\t\tmodalrotationMatrix->computeLocalOrientationByPolarDecomposition(localOrientationMatrixR, cur_dis, true);\n\t\t\t\t\tcurExternalForce = (*localOrientationMatrixR)*curExternalForce;\n\n\t\t\t\t\tbool ifreset = false;\n\t\t\t\t\tif (j == 0)\n\t\t\t\t\t{\n\t\t\t\t\t\tifreset = true;\n\t\t\t\t\t}\n\t\t\t\t\tbool converged = convergeIntegrationLocal(modalwarpingintegrator, curExternalForce, 1000, ifreset);\n\n\t\t\t\t\tif (!converged)\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\tq_dis = modalwarpingintegrator->getVectorq();\n\t\t\t\t\ttrainingNonLinearDis.push_back(cur_dis);\n\t\t\t\t\ttrainingLinearDis.push_back(q_dis);\n\n\t\t\t\t\tdataCount++;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tpreNorm = norm_;\n\n\t\t\tif (dataCount > getNumTrainingSet())\n\t\t\t{\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\tnonLinearIntegrator->setSaveStepResidual(false);\n\t}\n\n\tstd::cout << \"excute finished\" << std::endl;\n\n}\n\nvoid ModalWarpingTrainingModel::subexcute4()\n{\n\tint numScale = 100;\n\tthis->setNumTrainingSet(numScale);\n\tthis->setNumTrainingHighFreq(0);\n\n\tMatrixXd forceMatrix(subspaceModes->rows(), numScale);\n\n\tfor (int i = 0; i < numScale; i++)\n\t{\n\t\tVectorXd lq = subspaceModes->col(2) * (i*0.1+0.1);\n\t\t\n\t\tVectorXd w = *modalRotationSparseMatrix*lq;\n\n\t\tVectorXd extforce = modalwarpingintegrator->getInteranlForce(lq);\n\n\t\tmodalrotationMatrix->computeLocalOrientationMatrixR(localOrientationMatrixR, w, false);\n\n\t\textforce = *localOrientationMatrixR*extforce;\n\n\t\t\n\t\tmodalrotationMatrix->computeWarpingRotationMatrixR(localOrientationMatrixR, w);\n\n\t\tVectorXd guessq = *localOrientationMatrixR*lq;\n\t\tVectorXd modalwarpingforce = nonLinearIntegrator->getInteranlForce(guessq);\n\t\tstd::cout <<\"diff force = > \"<< (modalwarpingforce - extforce).norm() / extforce.norm() << std::endl;\n\t\tforceMatrix.col(i) = extforce;\n\n\n\t\t//convergeIntegrationNonLinear(nonLinearIntegrator, extforce, 1000, false);\n\n\t\t//VectorXd nq = nonLinearIntegrator->getVectorq();\n\n\t\ttrainingNonLinearDis.push_back(guessq);\n\t\ttrainingLinearDis.push_back(lq);\n\n\t}\n\n}\n\nvoid ModalWarpingTrainingModel::subexcute5()\n{\n\tint numScale = 600;\n\tint numData = 400;\n\tthis->setNumTrainingSet(numData-1);\n\tthis->setNumTrainingHighFreq(0);\n\n\tfor (int i = 0; i < numScale; i++)\n\t{\n\t\tstd::cout << \"Iteration => \" << i << std::endl;\n\t\tVectorXd lq = ((subspaceModes->col(3)*10)/numScale)*(i+1);\n\t\tVectorXd lf = modalwarpingintegrator->getInteranlForce(lq);\n\t\tVectorXd w = *modalRotationSparseMatrix*lq;\n\t\tmodalrotationMatrix->computeLocalOrientationMatrixR(localOrientationMatrixR, w, false);\n\t\tVectorXd nf = *localOrientationMatrixR*lf;\n\t\tmodalrotationMatrix->computeWarpingRotationMatrixR(matrixR_, w);\n\t\tVectorXd wq = *matrixR_*lq;\n\n\t\t\n\t\tif (i / numScale < 0.1)\n\t\t{\n\t\t\tnonLinearIntegrator->setState(wq.data());\n\t\t}\n\n\t\tnonLinearIntegrator->setMaxInteration(80);\n\t\tconvergeIntegrationNonLinear(nonLinearIntegrator, nf, 100, false);\n\n\t\tVectorXd nq = nonLinearIntegrator->getVectorq();\n\n\t\tif (numScale - i <= numData)\n\t\t{\n\t\t\ttrainingNonLinearDis.push_back(nq);\n\t\t\ttrainingLinearDis.push_back(lq);\n\t\t}\n\t}\n\n\n\n}\n\nvoid ModalWarpingTrainingModel::method6()\n{\n\n\tint numScale = 100;\n\tint numData = 100;\n\tthis->setNumTrainingSet(numData*2);\n\tthis->setNumTrainingHighFreq(0);\n\n\tint numVertex = volumtrciMesh->getNumVertices();\n\tstd::ofstream test(\"test2.txt\");\n\tVectorXd nodeYaxis(numVertex * 3);\n\tnodeYaxis.setZero();\n\tfor (int i = 0; i < numVertex; i++)\n\t{\n\t\tnodeYaxis.data()[i * 3 + 1] = 1;\n\t}\n\n\tVectorXd lq = (subspaceModes->col(3) * 10);\n\n\tVectorXd lf = modalwarpingintegrator->getInteranlForce(lq);\n\tVectorXd w = *modalRotationSparseMatrix*lq;\n\tmodalrotationMatrix->computeLocalOrientationMatrixR(localOrientationMatrixR, w, false);\n\tVectorXd lqorientation = *localOrientationMatrixR*nodeYaxis;\n\n\tVectorXd nf = *localOrientationMatrixR*lf;\n\tmodalrotationMatrix->computeWarpingRotationMatrixR(matrixR_, w);\n\tVectorXd wq = *matrixR_*lq;\n\tmodalrotationMatrix->computeLocalOrientationByPolarDecomposition(localOrientationMatrixR, wq, false);\n\tVectorXd nqorientation = *localOrientationMatrixR*nodeYaxis;\n\ttest << lqorientation.transpose() << std::endl;\n\ttest << nqorientation.transpose() << std::endl;\n\ttest.close();\n\tstd::cout << (lqorientation - nqorientation).norm() / nqorientation.norm() << std::endl;\n\n\tVectorXd ori_p(numVertex * 3);\n\tfor (int i = 0; i < numVertex; i++)\n\t{\n\t\tVector3d nodeori = volumtrciMesh->getNodeRestPosition(i);\n\t\tori_p.data()[i * 3 + 0] = nodeori.data()[0];\n\t\tori_p.data()[i * 3 + 1] = nodeori.data()[1];\n\t\tori_p.data()[i * 3 + 2] = nodeori.data()[2];\n\t}\n\n\tfor (int i = 0; i < numScale; i++)\n\t{\n\t\tstd::cout << \"Iteration => \" << i << std::endl;\n\t\tVectorXd nq = ((*matrixR_*lq) / numScale)*(i + 1);\n\t\tVectorXd originlq = lq / numScale*(i + 1);\n\t\t\n\t\tVectorXd real_nf = nonLinearIntegrator->getInteranlForce(nq);\n\t\tmodalrotationMatrix->computeLocalOrientationByPolarDecomposition(localOrientationMatrixR, nq, true);\n\t\t//modalrotationMatrix->computeLocalOrientationMatrixR(localOrientationMatrixR, w, true);\n\t\tVectorXd warp_nf = *localOrientationMatrixR*real_nf;\n\n\t\tconvergeIntegrationLocal(modalwarpingintegrator, warp_nf, 200, true);\n\n\t\tVectorXd real_lq = modalwarpingintegrator->getVectorq();\n\t\t//VectorXd real_lq;\n\t\t//real_lq = *localOrientationMatrixR*nq;\n\n\t\tif (numScale - i <= numData)\n\t\t{\n\t\t\ttrainingNonLinearDis.push_back(nq);\n\t\t\ttrainingLinearDis.push_back(real_lq);\n\t\t\ttrainingNonLinearDis.push_back(nq);\n\t\t\ttrainingLinearDis.push_back(originlq);\n\t\t}\n\t}\n}\n\nvoid ModalWarpingTrainingModel::method7()\n{\n\tint numScale = 1;\n\tint numData = 1;\n\tthis->setNumTrainingSet(numData * 2);\n\tthis->setNumTrainingHighFreq(0);\n\n\tVector3d axis(0, 0, 1);\n\tdouble angle = PI_/2;\n\tVectorXd fullforce = this->rotationGravity(gravity, angle, axis);\n\n\tconvergeIntegrationNonLinear(nonLinearIntegrator, fullforce, 1000, true);\n\tVectorXd targetnq = nonLinearIntegrator->getVectorq();\n\n\tfor (int i = numScale-1; i < numScale; i++)\n\t{\n\t\tstd::cout << \"Iteration => \" << i << std::endl;\n\t\tVectorXd nq = ((targetnq) / numScale)*(i + 1);\n\t\tVectorXd real_nf = nonLinearIntegrator->getInteranlForce(nq);\n\t\tmodalrotationMatrix->computeLocalOrientationByPolarDecomposition(localOrientationMatrixR, nq, true);\n\t\tVectorXd warp_nf = *localOrientationMatrixR*real_nf;\n\t\tconvergeIntegrationLocal(modalwarpingintegrator, warp_nf, 200, true);\n\t\tVectorXd real_lq = modalwarpingintegrator->getVectorq();\n\n\t\t//warp real_lq\n\t\tVectorXd w = *modalRotationSparseMatrix*real_lq;\n\t\tmodalrotationMatrix->computeWarpingRotationMatrixR(matrixR_, w);\n\t\tVectorXd wq = *matrixR_*real_lq;\n\n\t\tif (numScale - i <= numData)\n\t\t{\n\t\t\ttrainingNonLinearDis.push_back(nq);\n\t\t\ttrainingLinearDis.push_back(real_lq);\n\t\t\ttrainingNonLinearDis.push_back(nq);\n\t\t\ttrainingLinearDis.push_back(wq);\n\t\t}\n\t}\n\n}\n\nvoid ModalWarpingTrainingModel::method8()\n{\n\tstd::vector<Vector3d> nodedisplacement;\n\tnodedisplacement.clear();\n\tstd::vector<Vector3d> potentialDirection;\n\tstd::vector<double> poissonPerdirection;\n\tstd::vector<bool> ifreset;\n\n\t//if (0)\n\t{\n\t\tgenerateRotationVectorSample(M_PI, M_PI, 1,\n\t\t\tM_PI/3.0, -M_PI / 2.0, 10,\n\t\t\t9.8, 4.9, 2, nodedisplacement, ifreset, potentialDirection);\n\t\tsamplePoissonRatio(0.3, 0.3, 1, 1, nodedisplacement, potentialDirection, ifreset, poissonPerdirection);\n\t}\n\n\t/*nodedisplacement.push_back(Vector3d(0, -1, 0)*9.8);\n\tifreset.push_back(true);\n\tpotentialDirection.push_back(Vector3d(0, -1, 0));\n\tpoissonPerdirection.push_back(0.20);*/\n\n\tfor (int i = 0; i < nodedisplacement.size(); i++)\n\t{\n\t\tstd::cout << nodedisplacement[i].transpose() << std::endl;\n\t\tstd::cout << \"poisson \" << poissonPerdirection[i] << std::endl;\n\t}\n\t\n\tint numDataPerSample = getNumTrainingSet() / nodedisplacement.size();\n\tsetNumTrainingHighFreq(0);\n\n\tstd::vector<VectorXd> qn_list;\n\tstd::vector<VectorXd> ql_list;\n\n\tint dataCount = 0;\n\tfor (int i = 0; i < nodedisplacement.size(); i++)\n\t{\n\t\tVectorXd nodeacc = nodedisplacement[i];\n\t\tVectorXd fullforce = this->createGravity(nodeacc);\n\n\n\t\tLoboVolumetricMesh::Material* materia = volumtrciMesh->getMaterialById(0);\n\t\tLoboVolumetricMesh::ENuMaterial* enmateria = (LoboVolumetricMesh::ENuMaterial*)materia;\n\t\tenmateria->setNu(poissonPerdirection[i]);\n\t\tmodalwarpingintegrator->updateMaterial();\n\t\tnonLinearIntegrator->updateMaterial();\n\n\t\tconvergeIntegrationNonLinearBuffer(nonLinearIntegrator, fullforce, 2000, qn_list, true);\n\n\t\tint range = qn_list.size() / numDataPerSample;\n\t\trange = 1;\n\t\tfor (int j = 0; j <qn_list.size(); j++)\n\t\t{\n\t\t\tVectorXd nq = qn_list[j];\n\n\t\t\tif (trainingLinearDis.size() > 0)\n\t\t\t\tif ((nq - trainingNonLinearDis.back()).norm() / trainingNonLinearDis.back().norm() < 1e-3)\n\t\t\t\t{\n\t\t\t\t\t//the diff is too small\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\tVectorXd real_nf = nonLinearIntegrator->getInteranlForce(nq);\n\t\t\tmodalrotationMatrix->computeLocalOrientationMatrixR(localOrientationMatrixR, nq, true);\n\t\t\tVectorXd warp_nf = *localOrientationMatrixR*real_nf;\n\t\t\t\n\t\t\tbool reset = false;\n\n\t\t\tif (j == 0 && ifreset[i] == true)\n\t\t\t{\n\t\t\t\treset = true;\n\t\t\t}\n\n\t\t\tconvergeIntegrationLocal(modalwarpingintegrator, real_nf, 2000, reset);\n\t\t\t\n\t\t\tVectorXd real_lq = modalwarpingintegrator->getVectorq();\n\n\t\t\ttrainingNonLinearDis.push_back(nq);\n\t\t\ttrainingLinearDis.push_back(real_lq);\n\t\t\tforcefieldDirection.push_back(potentialDirection[i]);\n\t\t\tpoissonPerDis.push_back(poissonPerdirection[i]);\n\n\t\t\tstd::cout << dataCount << \"/\" << getNumTrainingSet() << std::endl;\n\t\t\tdataCount++;\n\t\t}\n\t}\n\tsetNumTrainingSet(trainingNonLinearDis.size());\n\n\tstd::cout << \"finished\" << std::endl;\n}\n\nvoid ModalWarpingTrainingModel::method9()\n{\n\tstd::vector<Vector3d> nodedisplacement;\n\tstd::vector<Vector3d> potentialDirection;\n\tstd::vector<double> poissonPerdirection;\n\tnodedisplacement.clear();\n\tstd::vector<bool> ifreset;\n\n\tnodedisplacement.clear();\n\tifreset.clear();\n\n\t//if (0)\n\t{\n\t\tgenerateRotationVectorSample(M_PI, M_PI, 1,\n\t\t\tM_PI / 2.0, -M_PI / 2.0, 10,\n\t\t\t4.0, 2.0, 2, nodedisplacement, ifreset, potentialDirection);\n\n\t\tsamplePoissonRatio(0.2, 0.2, 1, 1, nodedisplacement, potentialDirection, ifreset, poissonPerdirection);\n\t}\n\n\t/*nodedisplacement.push_back(Vector3d(0, -1, 0)*9.8);\n\tifreset.push_back(true);\n\tpotentialDirection.push_back(Vector3d(0, -1, 0));\n\tpoissonPerdirection.push_back(0.20);*/\n\n\t//nodedisplacement.push_back(Vector3d(-4.9, 1.83721e-032, 3.00038e-016));\n\t//ifreset.push_back(true);\n\t//potentialDirection.push_back(Vector3d(-1, 0, 0));\n\t//poissonPerdirection.push_back(0.2);\n\n\n\tfor (int i = 0; i < nodedisplacement.size(); i++)\n\t{\n\t\tstd::cout << nodedisplacement[i].transpose() << std::endl;\n\t\tstd::cout <<\"poisson \" << poissonPerdirection[i] << std::endl;\n\t}\n\n\tint numDataPerSample = getNumTrainingSet() / nodedisplacement.size();\n\tsetNumTrainingHighFreq(0);\n\n\tstd::vector<VectorXd> qn_list;\n\tint dataCount = 0;\n\tnonLinearIntegrator->resetToRest();\n\t//VectorXd q_test(volumtrciMesh->getNumVertices() * 3);\n\t//q_test.setRandom();\n\tfor (int i = 0; i < nodedisplacement.size(); i++)\n\t{\n\t\tVector3d nodeacc = nodedisplacement[i];\n\t\tVectorXd fullforce = this->createGravity(nodeacc);\n\t\t\n\t\tLoboVolumetricMesh::Material* materia = volumtrciMesh->getMaterialById(0);\n\t\tLoboVolumetricMesh::ENuMaterial* enmateria = (LoboVolumetricMesh::ENuMaterial*)materia;\n\t\tenmateria->setNu(poissonPerdirection[i]);\n\t\tmodalwarpingintegrator->updateMaterial();\n\t\tnonLinearIntegrator->updateMaterial();\n\n\t\t//reset = false;\n\t\tbool reset = ifreset[i];\n\n\t\tstd::cout <<\"ifrest\"<< reset << std::endl;\n\t\tconvergeIntegrationLocalBuffer(modalwarpingintegrator, fullforce, 1000, qn_list, reset);\n\n\t\tint range = qn_list.size() / numDataPerSample;\n\t\tif (range <= 1)\n\t\t{\n\t\t\trange = 2;\n\t\t}\n\t\trange = 1;\n\n\t\tstd::cout <<\"range => \"<< range << std::endl;\n\t\tfor (int j = 0; j < qn_list.size(); j += range)\n\t\t{\n\t\t\tstd::cout << \"force \" << i << \"/\" << nodedisplacement.size() - 1 << std::endl;\n\t\t\tstd::cout << \"q_list \" << j << \"/\" << qn_list.size() - 1 << std::endl;\n\t\t\tVectorXd lq = qn_list[j];\n\n\t\t\tif (trainingLinearDis.size() > 0)\n\t\t\t\tif ((lq - trainingLinearDis.back()).norm() / trainingLinearDis.back().norm() < 1e-3)\n\t\t\t\t{\n\t\t\t\t\t//the diff is too small\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t//use ku = f instead of ku = Rf\n\t\t\tVectorXd nq;\n\t\t\tif (getLinearDisOnly())\n\t\t\t{\n\t\t\t\tVectorXd w = *modalRotationSparseMatrix*lq;\n\t\t\t\tmodalrotationMatrix->computeWarpingRotationMatrixR(localOrientationMatrixR, w);\n\t\t\t\tnq = *localOrientationMatrixR*lq;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tVectorXd w = *modalRotationSparseMatrix*lq;\n\t\t\t\tmodalrotationMatrix->computeLocalOrientationMatrixR(localOrientationMatrixR, w, false);\n\t\t\t\tVectorXd lf = modalwarpingintegrator->getInteranlForce(lq);\n\t\t\t\tVectorXd nf = *localOrientationMatrixR*lf;\n\n\t\t\t\tbool reset = false;\n\n\t\t\t\tif (j == 0 && ifreset[i] == true)\n\t\t\t\t{\n\t\t\t\t\treset = true;\n\t\t\t\t}\n\n\t\t\t\tbool converged = this->convergeIntegrationNonLinear(nonLinearIntegrator, nf, 1000, reset);\n\n\t\t\t\tnq = nonLinearIntegrator->getVectorq();\n\n\t\t\t\tif (converged == false)\n\t\t\t\t{\n\t\t\t\t\tstd::cout << \"break\" << std::endl;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (dataCount % 2 == 1)\n\t\t\t{\n\t\t\t\tdataCount++;\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\ttrainingNonLinearDis.push_back(nq);\n\t\t\ttrainingLinearDis.push_back(lq);\n\t\t\tforcefieldDirection.push_back(potentialDirection[i]);\n\t\t\t\n\t\t\tpoissonPerDis.push_back(poissonPerdirection[i]);\n\n\t\t\tstd::cout << dataCount << \"/\" << getNumTrainingSet() << std::endl;\n\t\t\tdataCount++;\n\t\t}\n\t}\n\tsetNumTrainingSet(trainingNonLinearDis.size());\n}\n\nvoid ModalWarpingTrainingModel::method10()\n{\n\tstd::vector<Vector3d> nodedisplacement;\n\tstd::vector<Vector3d> potentialDirection;\n\tstd::vector<double> poissonPerdirection;\n\tnodedisplacement.clear();\n\tstd::vector<bool> ifreset;\n\n\tnodedisplacement.clear();\n\tifreset.clear();\n\n\tif (0)\n\t{\n\t\tgenerateRotationVectorSample(M_PI, M_PI, 1,\n\t\t\tM_PI / 2.0, -M_PI / 2.0, 10,\n\t\t\t4.0, 2.0, 2, nodedisplacement, ifreset, potentialDirection);\n\n\t\tsamplePoissonRatio(0.2, 0.2, 1, 1, nodedisplacement, potentialDirection, ifreset, poissonPerdirection);\n\t}\n\n\tnodedisplacement.push_back(Vector3d(0, -1, 0)*9.8);\n\tifreset.push_back(true);\n\tpotentialDirection.push_back(Vector3d(0, -1, 0));\n\tpoissonPerdirection.push_back(0.20);\n\n\t//nodedisplacement.push_back(Vector3d(-4.9, 1.83721e-032, 3.00038e-016));\n\t//ifreset.push_back(true);\n\t//potentialDirection.push_back(Vector3d(-1, 0, 0));\n\t//poissonPerdirection.push_back(0.2);\n\n\n\tfor (int i = 0; i < nodedisplacement.size(); i++)\n\t{\n\t\tstd::cout << nodedisplacement[i].transpose() << std::endl;\n\t\tstd::cout << \"poisson \" << poissonPerdirection[i] << std::endl;\n\t}\n\n\tint numDataPerSample = getNumTrainingSet() / nodedisplacement.size();\n\tsetNumTrainingHighFreq(0);\n\n\tstd::vector<VectorXd> qn_list;\n\tint dataCount = 0;\n\tnonLinearIntegrator->resetToRest();\n\t//VectorXd q_test(volumtrciMesh->getNumVertices() * 3);\n\t//q_test.setRandom();\n\tfor (int i = 0; i < nodedisplacement.size(); i++)\n\t{\n\t\tVector3d nodeacc = nodedisplacement[i];\n\t\tVectorXd fullforce = this->createGravity(nodeacc);\n\n\t\tLoboVolumetricMesh::Material* materia = volumtrciMesh->getMaterialById(0);\n\t\tLoboVolumetricMesh::ENuMaterial* enmateria = (LoboVolumetricMesh::ENuMaterial*)materia;\n\t\tenmateria->setNu(poissonPerdirection[i]);\n\t\tmodalwarpingintegrator->updateMaterial();\n\t\t//nonLinearIntegrator->updateMaterial();\n\n\t\t//reset = false;\n\t\tbool reset = ifreset[i];\n\n\t\tstd::cout << \"ifrest\" << reset << std::endl;\n\t\tconvergeIntegrationLocalBuffer(modalwarpingintegrator, fullforce, 1000, qn_list, reset);\n\n\t\tint range = qn_list.size() / numDataPerSample;\n\t\tif (range <= 1)\n\t\t{\n\t\t\trange = 2;\n\t\t}\n\t\trange = 1;\n\n\t\tstd::cout << \"range => \" << range << std::endl;\n\t\tfor (int j = 0; j < qn_list.size(); j += range)\n\t\t{\n\t\t\tstd::cout << \"force \" << i << \"/\" << nodedisplacement.size() - 1 << std::endl;\n\t\t\tstd::cout << \"q_list \" << j << \"/\" << qn_list.size() - 1 << std::endl;\n\t\t\tVectorXd lq = qn_list[j];\n\n\t\t\tif (trainingLinearDis.size() > 0)\n\t\t\t\tif ((lq - trainingLinearDis.back()).norm() / trainingLinearDis.back().norm() < 1e-3)\n\t\t\t\t{\n\t\t\t\t\t//the diff is too small\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t//use ku = f instead of ku = Rf\n\t\t\tVectorXd nq;\n\t\t\tif (getLinearDisOnly())\n\t\t\t{\n\t\t\t\tVectorXd w = *modalRotationSparseMatrix*lq;\n\t\t\t\tmodalrotationMatrix->computeWarpingRotationMatrixR(localOrientationMatrixR, w);\n\t\t\t\tnq = *localOrientationMatrixR*lq;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tVectorXd w = *modalRotationSparseMatrix*lq;\n\t\t\t\tmodalrotationMatrix->computeLocalOrientationMatrixR(localOrientationMatrixR, w, false);\n\t\t\t\tVectorXd lf = modalwarpingintegrator->getInteranlForce(lq);\n\t\t\t\tVectorXd nf = *localOrientationMatrixR*lf;\n\n\t\t\t\tbool reset = false;\n\n\t\t\t\tif (j == 0 && ifreset[i] == true)\n\t\t\t\t{\n\t\t\t\t\treset = true;\n\t\t\t\t}\n\n\t\t\t\tVectorXd reducednf = subspaceModes->transpose()*nf;\n\n\t\t\t\tbool converged = this->convergeIntegrationNonlinearReduced(reducedIntergrator, nf, 1000, reset);\n\n\t\t\t\tnq = nonLinearIntegrator->getVectorq();\n\n\t\t\t\tif (converged == false)\n\t\t\t\t{\n\t\t\t\t\tstd::cout << \"break\" << std::endl;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (dataCount % 2 == 1)\n\t\t\t{\n\t\t\t\tdataCount++;\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\ttrainingNonLinearDis.push_back(nq);\n\t\t\ttrainingLinearDis.push_back(lq);\n\t\t\tforcefieldDirection.push_back(potentialDirection[i]);\n\n\t\t\tpoissonPerDis.push_back(poissonPerdirection[i]);\n\n\t\t\tstd::cout << dataCount << \"/\" << getNumTrainingSet() << std::endl;\n\t\t\tdataCount++;\n\t\t}\n\t}\n\tsetNumTrainingSet(trainingNonLinearDis.size());\n}\n\nvoid ModalWarpingTrainingModel::method10Twist()\n{\n\tstd::vector<VectorXd> qn_list;\n\tint dataCount = 0;\n\n\tRotateForceField* forcefield = new RotateForceField(volumtrciMesh, Vector3d(1, 0, 0));\n\tforcefield->setForceMagnitude(0.0005);\n\t\n\tconvergeIntegrationNonLinearBuffer(nonLinearIntegrator, forcefield, 300, qn_list, true);\n\n\tdelete forcefield;\n\n\tint range = 1;\n\tstd::cout << \"range => \" << range << std::endl;\n\tfor (int j = 0; j < qn_list.size(); j += range)\n\t{\n\t\tstd::cout << \"q_list \" << j << \"/\" << qn_list.size() - 1 << std::endl;\n\t\tVectorXd nq = qn_list[j];\n\n\t\tif (trainingNonLinearDis.size() > 0)\n\t\t\tif ((nq - trainingNonLinearDis.back()).norm() / trainingNonLinearDis.back().norm() < 1e-3)\n\t\t\t{\n\t\t\t\t//the diff is too small\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\tVectorXd nf = nonLinearIntegrator->getInteranlForce(nq);\t\n\n\t\tbool reset = false;\n\t\tif (j == 0)\n\t\t\treset = true;\n\n\t\tconvergeIntegrationLocal(modalwarpingintegrator, nf, 1000, reset);\n\t\tVectorXd lq = modalwarpingintegrator->getVectorq();\n\n\t\ttrainingNonLinearDis.push_back(nq);\n\t\ttrainingLinearDis.push_back(lq);\n\t\tstd::cout << dataCount << \"/\" << getNumTrainingSet() << std::endl;\n\t\tdataCount++;\n\t}\n\tsetNumTrainingSet(trainingNonLinearDis.size());\n\tsetNumTrainingHighFreq(0);\n}\n\nvoid ModalWarpingTrainingModel::method11Twist()\n{\n\tstd::vector<VectorXd> qn_list;\n\tint dataCount = 0;\n\n\tRotateForceField* forcefield = new RotateForceField(volumtrciMesh, Vector3d(1, 0, 0));\n\tforcefield->setForceMagnitude(0.002);\n\tconvergeIntegrationLocalBuffer(modalwarpingintegrator, forcefield, 200, qn_list, true);\n\n\tdelete forcefield;\n\n\t//qn_list.clear();\n\t//\n\t//double maxscale = 8;\n\t//for (int i = 0; i < 4000; i++)\n\t//{\n\t//\tdouble scale = maxscale / 4000 * i;\n\t//\tqn_list.push_back(subspaceModes->col(2)*scale);\n\t//}\n\n\tint range = 1;\n\tstd::cout << \"range => \" << range << std::endl;\n\tfor (int j = 0; j < qn_list.size(); j += range)\n\t{\n\t\tstd::cout << \"q_list \" << j << \"/\" << qn_list.size() - 1 << std::endl;\n\t\tVectorXd lq = qn_list[j];\n\n\t\tif (trainingLinearDis.size() > 0)\n\t\t\tif ((lq - trainingLinearDis.back()).norm() / trainingLinearDis.back().norm() < 1e-4)\n\t\t\t{\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\tVectorXd w = *modalRotationSparseMatrix*lq;\n\t\tmodalrotationMatrix->computeLocalOrientationMatrixR(localOrientationMatrixR, w, false);\n\t\tVectorXd lf = modalwarpingintegrator->getInteranlForce(lq);\n\t\t\n\t\tVectorXd nf = *localOrientationMatrixR*lf;\n\n\t\tbool reset = false;\n\t\tif (j == 0)\n\t\t\treset = true;\n\t\treset = false;\n\n\t\tbool converge = this->convergeIntegrationNonLinear(nonLinearIntegrator, nf, 1000, reset);\n\n\t\tVectorXd nq = nonLinearIntegrator->getVectorq();\n\n\t\tif (converge == false)\n\t\t{\n\t\t\tbreak;\n\t\t}\n\n\t\t/*if (j % 2 != 0)\n\t\t{\n\t\t\tcontinue;\n\t\t}*/\n\n\t\ttrainingNonLinearDis.push_back(nq);\n\t\ttrainingLinearDis.push_back(lq);\n\n\t\tstd::cout << dataCount << \"/\" << getNumTrainingSet() << std::endl;\n\t\tdataCount++;\n\t}\n\tsetNumTrainingSet(trainingNonLinearDis.size());\n\tsetNumTrainingHighFreq(0);\n}\n\nvoid ModalWarpingTrainingModel::method12Twist()\n{\n\tstd::vector<Vector3d> nodedisplacement;\n\tstd::vector<Vector3d> potentialDirection;\n\tstd::vector<double> poissonPerdirection;\n\tnodedisplacement.clear();\n\tstd::vector<bool> ifreset;\n\n\t/*generateRotationVectorSample(M_PI/2 , 0, 3,\n\t\tM_PI / 2, 0, 3,\n\t\t1, 1, 1, nodedisplacement);*/\n\n\tgenerateRotationVectorSample(M_PI, M_PI, 1,\n\t\t-M_PI / 2, -M_PI / 2, 1,\n\t\t1, 1, 1, nodedisplacement, ifreset, potentialDirection);\n\n\tsamplePoissonRatio(0.20, 0.20, 1, 1, nodedisplacement, potentialDirection, ifreset, poissonPerdirection);\n\n\t//nodedisplacement.clear();\n\t//nodedisplacement.push_back(Vector3d(1, 0, 0));\n\n\tfor (int i = 0; i < nodedisplacement.size(); i++)\n\t{\n\t\tstd::cout << nodedisplacement[i].transpose() << std::endl;\n\t\tstd::cout << \"poisson \" << poissonPerdirection[i] << std::endl;\n\t}\n\n\tint dataCount = 0;\n\n\tRotateForceField* forcefield = new RotateForceField(volumtrciMesh, Vector3d(1, 0, 0));\n\tforcefield->setForceMagnitude(0.001);\n\tforcefield->centeraxis_position = this->getPotentialCenter();\n\n\tstd::cout << \"nodedisplacement.size()\" << nodedisplacement.size() << std::endl;\n\n\tfor (int i = 0; i < nodedisplacement.size(); i++)\n\t{\n\t\tforcefield->centeraxis = nodedisplacement[i].normalized();\n\t\tstd::cout << forcefield->centeraxis.transpose() << std::endl;\n\n\t\tLoboVolumetricMesh::Material* materia = volumtrciMesh->getMaterialById(0);\n\t\tLoboVolumetricMesh::ENuMaterial* enmateria = (LoboVolumetricMesh::ENuMaterial*)materia;\n\t\tenmateria->setNu(poissonPerdirection[i]);\n\t\tmodalwarpingintegrator->updateMaterial();\n\t\tnonLinearIntegrator->updateMaterial();\n\n\t\tdouble preNorm = DBL_MAX;\n\t\tdouble residual = DBL_MAX;\n\n\t\tint r = volumtrciMesh->getNumVertices() * 3;\n\t\tint maxIteration = 200;\n\n\t\tVectorXd preq(r);\n\t\tVectorXd extForce(r);\n\t\tVectorXd nq(r);\n\t\tnq.setZero();\n\t\textForce.setZero();\n\t\tpreq.setConstant(1000);\n\n\t\tbool converged = false;\n\t\tstd::cout << std::endl;\n\n\t\tmodalwarpingintegrator->resetToRest();\n\t\tfor (int j = 0; j < maxIteration; j++)\n\t\t{\n\t\t\tbool reset = false;\n\t\t\tif (j == 0)\n\t\t\t\treset = true;\n\n\t\t\tstd::cout << '\\r';\n\t\t\tstd::cout << j;\n\n\t\t\tvolumtrciMesh->setDisplacement(nq.data());\n\t\t\tforcefield->computeCurExternalForce(extForce);\n\n\t\t\tVectorXd mergedExternalForce = extForce;\n\t\t\tmodalwarpingintegrator->setExternalForces(mergedExternalForce.data());\n\n\t\t\tmodalwarpingintegrator->doTimeStep();\n\n\t\t\tVectorXd curq = modalwarpingintegrator->getVectorq();\n\n\t\t\tresidual = std::abs((preq - curq).norm() / preq.norm());\n\t\t\tpreq = curq;\n\n\t\t\tVectorXd w = *modalRotationSparseMatrix*curq;\n\n\t\t\tdouble maxangle = getMaxRotatedAngleFromW(w);\n\t\t\tstd::cout << \"  maxangle => \" << maxangle << \"  \";\n\n\t\t\t/*if (maxangle > M_PI)\n\t\t\t{\n\t\t\t\tbreak;\n\t\t\t}*/\n\n\t\t\tmodalrotationMatrix->computeLocalOrientationMatrixR(localOrientationMatrixR, w, false);\n\t\t\tVectorXd lf = modalwarpingintegrator->getInteranlForce(curq);\n\t\t\tVectorXd nf = *localOrientationMatrixR*lf;\n\n\t\t\t//bool converge = true;\n\t\t\t\n\t\t\tbool converge = this->convergeIntegrationNonLinear(nonLinearIntegrator, nf, 1000, reset);\n\t\t\t\n\t\t\tnq = nonLinearIntegrator->getVectorq();\n\n\t\t\tif (converge == false)\n\t\t\t{\n\t\t\t\tstd::cout << \"not coverged\" << \" \" << std::endl;\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\t/*if (j % 2 != 0)\n\t\t\t{\n\t\t\tcontinue;\n\t\t\t}*/\n\n\t\t\ttrainingNonLinearDis.push_back(nq);\n\t\t\ttrainingLinearDis.push_back(curq);\n\t\t\tforcefieldDirection.push_back(forcefield->centeraxis);\n\t\t\tpoissonPerDis.push_back(poissonPerdirection[i]);\n\n\n\t\t\tstd::cout << \"         \" << trainingNonLinearDis.size() << \" \";\n\n\t\t\tif (residual < 1e-5)\n\t\t\t{\n\t\t\t\tconverged = true;\n\t\t\t\tstd::cout << \"converged\" << std::endl;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\n\tstd::cout << std::endl;\n\tsetNumTrainingSet(trainingNonLinearDis.size());\n\tsetNumTrainingHighFreq(0);\n}\n\nvoid ModalWarpingTrainingModel::methodFortwist()\n{\n\tVectorXd baselq = subspaceModes->col(2);\n\tfor (int i = -50; i < 50; i++)\n\t{\n\t\tVectorXd lq = baselq*i*0.1;\n\t\ttrainingNonLinearDis.push_back(lq);\n\t\ttrainingLinearDis.push_back(lq);\n\t}\n\n\tsetNumTrainingSet(trainingNonLinearDis.size());\n\tsetNumTrainingHighFreq(0);\n\n}\n\nbool ModalWarpingTrainingModel::convergeIntegrationLocal(LoboIntegrator* integrator_loc, VectorXd &extForce, int maxIteration, bool reset)\n{\n\tif (reset)\n\tintegrator_loc->resetToRest();\n\n\t/*modalwarpingintegrator->computeStaticDisplacement(extForce, false);\n\n\treturn true;*/\n\n\tstd::cout << \"convergeIntegrationLocal === >\" << std::endl;\n\tdouble preNorm = DBL_MAX;\n\tdouble residual = DBL_MAX;\n\tVectorXd preq(extForce.rows());\n\tpreq.setConstant(1000);\n\n\tbool converged = false;\n\n\tfor (int j = 0; j < maxIteration; j++)\n\t{\n\t\tVectorXd fullq = integrator_loc->getVectorq();\n\t\t//set the external force\n\t\tVectorXd mergedExternalForce = extForce;\n\t\tintegrator_loc->setExternalForces(mergedExternalForce.data());\n\n\t\tintegrator_loc->doTimeStep();\n\n\t\tVectorXd curq = integrator_loc->getVectorq();\n\t\tresidual = std::abs((preq - curq).norm() / preq.norm());\n\t\tpreq = integrator_loc->getVectorq();\n\t\tif (residual < 1e-6)\n\t\t{\n\t\t\tconverged = true;\n\t\t\tstd::cout << \"converged\" << std::endl;\n\t\t\tbreak;\n\t\t}\n\t}\n\tstd::cout << residual << std::endl;\n\treturn converged;\n}\n\nbool ModalWarpingTrainingModel::convergeIntegrationLocalBuffer(LoboIntegrator* integrator_loc, VectorXd &extForce, int maxIteration, std::vector<VectorXd> &qn_list, bool reset /*= true*/)\n{\n\tif (reset)\n\t\tintegrator_loc->resetToRest();\n\n\tstd::cout << \"convergeIntegrationLocal === >\" << std::endl;\n\tdouble preNorm = DBL_MAX;\n\tdouble residual = DBL_MAX;\n\tVectorXd preq(extForce.rows());\n\tpreq.setConstant(1000);\n\n\tbool converged = false;\n\tqn_list.clear();\n\tstd::cout << std::endl;\n\tfor (int j = 0; j < maxIteration; j++)\n\t{\n\t\tstd::cout << '\\r';\n\t\tstd::cout << j;\n\t\tVectorXd fullq = integrator_loc->getVectorq();\n\t\t//set the external force\n\t\tVectorXd mergedExternalForce = extForce;\n\t\tintegrator_loc->setExternalForces(mergedExternalForce.data());\n\n\t\tintegrator_loc->doTimeStep();\n\n\t\tVectorXd curq = integrator_loc->getVectorq();\n\t\tqn_list.push_back(curq);\n\t\tresidual = std::abs((preq - curq).norm() / preq.norm());\n\t\tpreq = integrator_loc->getVectorq();\n\t\tif (residual < 1e-5)\n\t\t{\n\t\t\tconverged = true;\n\t\t\tstd::cout << \"converged\" << std::endl;\n\t\t\tbreak;\n\t\t}\n\t}\n\tstd::cout << std::endl;\n\n\tstd::cout << residual << std::endl;\n\treturn converged;\n}\n\nbool ModalWarpingTrainingModel::convergeIntegrationLocalBuffer(LoboIntegrator* integrator_loc, RotateForceField* forcefiled, int maxIteration, std::vector<VectorXd> &qn_list, bool reset /*= true*/)\n{\n\tif (reset)\n\t\tintegrator_loc->resetToRest();\n\n\tstd::cout << \"convergeIntegrationLocal === >\" << std::endl;\n\tdouble preNorm = DBL_MAX;\n\tdouble residual = DBL_MAX;\n\n\tint r = volumtrciMesh->getNumVertices() * 3;\n\n\tVectorXd preq(r);\n\tVectorXd extForce(r);\n\textForce.setZero();\n\tpreq.setConstant(1000);\n\n\tbool converged = false;\n\tqn_list.clear();\n\tstd::cout << std::endl;\n\tfor (int j = 0; j < maxIteration; j++)\n\t{\n\t\tstd::cout << '\\r';\n\t\tstd::cout << j;\n\t\tVectorXd fullq = integrator_loc->getVectorq();\n\t\t//set the external force\n\t\tVectorXd w = *modalRotationSparseMatrix*fullq;\n\t\tmodalrotationMatrix->computeWarpingRotationMatrixR(localOrientationMatrixR, w);\n\n\t\tVectorXd nq = (*localOrientationMatrixR)*fullq;\n\t\tvolumtrciMesh->setDisplacement(nq.data());\n\t\tforcefiled->computeCurExternalForce(extForce);\n\n\t\tVectorXd mergedExternalForce = extForce;\n\t\tintegrator_loc->setExternalForces(mergedExternalForce.data());\n\n\t\tintegrator_loc->doTimeStep();\n\n\t\tVectorXd curq = integrator_loc->getVectorq();\n\t\tqn_list.push_back(curq);\n\t\tresidual = std::abs((preq - curq).norm() / preq.norm());\n\t\tpreq = integrator_loc->getVectorq();\n\n\t\tif (residual < 1e-5)\n\t\t{\n\t\t\tconverged = true;\n\t\t\tstd::cout << \"converged\" << std::endl;\n\t\t\tbreak;\n\t\t}\n\t}\n\tstd::cout << std::endl;\n\n\tstd::cout << residual << std::endl;\n\treturn converged;\n}\n\nbool ModalWarpingTrainingModel::convergeIntegrationNonLinear(LoboIntegrator* integrator_loc, VectorXd &extForce, int maxIteration, bool reset)\n{\n\tif (reset)\n\t\tintegrator_loc->resetToRest();\n\n\tbool converge = ((ImplicitNewMatkSparseIntegrator*)integrator_loc)->computeStaticDisplacement(extForce, false);\n\n\treturn converge;\n\n\tstd::cout << \"convergeIntegrationNonLinear === >\" << std::endl;\n\n\tdouble preNorm = DBL_MAX;\n\tdouble residual = DBL_MAX;\n\tVectorXd preq(extForce.rows());\n\tpreq.setConstant(1000);\n\tstd::cout << std::endl;\n\n\tfor (int j = 0; j < maxIteration; j++)\n\t{\n\t\tstd::cout << '\\r';\n\t\tstd::cout << j;\n\t\tintegrator_loc->setExternalForces(extForce.data());\n\t\tintegrator_loc->doTimeStep();\n\t\tVectorXd curq = integrator_loc->getVectorq();\n\t\tresidual = std::abs((preq - curq).norm() / preq.norm());\n\t\tpreq = integrator_loc->getVectorq();\n\t\tif (residual < 1e-5)\n\t\t{\n\t\t\tstd::cout << curq.norm() << std::endl;\n\t\t\tstd::cout << \"converged\" << std::endl;\n\t\t\tbreak;\n\t\t}\n\t}\n\tstd::cout << std::endl;\n\n\tstd::cout << residual << std::endl;\n\n\treturn true;\n}\n\nbool ModalWarpingTrainingModel::convergeIntegrationNonlinearReduced(LoboIntegrator* integrator_loc, VectorXd &extForce, int maxIteration, bool reset /*= true*/)\n{\n\tif (reset)\n\t\tintegrator_loc->resetToRest();\n\n\tbool converge = ((ImpicitNewMarkDenseIntegrator*)integrator_loc)->computeStaticDisplacement(extForce, false);\n\n\treturn converge;\n}\n\nvoid ModalWarpingTrainingModel::convergeIntegrationNonLinearBuffer(LoboIntegrator* integrator_loc, VectorXd &extForce, int maxIteration, std::vector<VectorXd> &qn_list, bool reset /*= true*/)\n{\n\tqn_list.clear();\n\n\tif (reset)\n\t\tintegrator_loc->resetToRest();\n\n\tdouble preNorm = DBL_MAX;\n\tdouble residual = DBL_MAX;\n\tVectorXd preq(extForce.rows());\n\tpreq.setConstant(1000);\n\tstd::cout << std::endl;\n\tfor (int j = 0; j < maxIteration; j++)\n\t{\n\t\tstd::cout << '\\r';\n\t\tstd::cout << j;\n\t\tintegrator_loc->setExternalForces(extForce.data());\n\t\tintegrator_loc->doTimeStep();\n\t\tVectorXd curq = integrator_loc->getVectorq();\n\t\tqn_list.push_back(curq);\n\t\tresidual = std::abs((preq - curq).norm() / preq.norm());\n\t\tpreq = integrator_loc->getVectorq();\n\t\tif (residual < 1e-5)\n\t\t{\n\t\t\tstd::cout << curq.norm() << std::endl;\n\t\t\tstd::cout << \"converged\" << std::endl;\n\t\t\tbreak;\n\t\t}\n\t}\n\tstd::cout << std::endl;\n\tstd::cout << residual << std::endl;\n}\n\nvoid ModalWarpingTrainingModel::convergeIntegrationNonLinearBuffer(LoboIntegrator* integrator_loc, RotateForceField* forcefiled, int maxIteration, std::vector<VectorXd> &qn_list, bool reset /*= true*/)\n{\n\tqn_list.clear();\n\n\tif (reset)\n\t\tintegrator_loc->resetToRest();\n\n\tdouble preNorm = DBL_MAX;\n\tdouble residual = DBL_MAX;\n\t\n\tint r = volumtrciMesh->getNumVertices() * 3;\n\n\tVectorXd preq(r);\n\tVectorXd extForce(r);\n\n\tpreq.setConstant(1000);\n\tstd::cout << std::endl;\n\tfor (int j = 0; j < maxIteration; j++)\n\t{\n\t\tstd::cout << '\\r';\n\t\tstd::cout << j;\n\n\t\tVectorXd iq = integrator_loc->getVectorq();\n\t\tvolumtrciMesh->setDisplacement(iq.data());\n\t\tforcefiled->computeCurExternalForce(extForce);\n\n\t\tintegrator_loc->setExternalForces(extForce.data());\n\t\tintegrator_loc->doTimeStep();\n\t\tVectorXd curq = integrator_loc->getVectorq();\n\n\t\tqn_list.push_back(curq);\n\t\tresidual = std::abs((preq - curq).norm() / preq.norm());\n\t\tpreq = curq;\n\t\tif (residual < 1e-4)\n\t\t{\n\t\t\tstd::cout << curq.norm() << std::endl;\n\t\t\tstd::cout << \"converged\" << std::endl;\n\t\t\tbreak;\n\t\t}\n\t}\n\tstd::cout << std::endl;\n\tstd::cout << residual << std::endl;\n}\n\ntypedef Eigen::Triplet<double> EIGEN_TRI;\n\nvoid ModalWarpingTrainingModel::generateConstrainMatrixAndVector(SparseMatrix<double>* constrainMatrix, VectorXd &constrainTarget, LoboNodeBase* nodep, int nodeid, VectorXd target_)\n{\n\tint numVertex = this->volumtrciMesh->getNumVertices();\n\tint totalConstrain = numConstrainedDOFs + nodep->neighbor.size() * 3 +3;\n\n\tconstrainMatrix->resize(totalConstrain, numVertex * 3);\n\tconstrainTarget.resize(totalConstrain, 1);\n\tconstrainTarget.setZero();\n\tstd::vector<EIGEN_TRI> entrys;\n\n\tfor (int i = 0; i < numConstrainedDOFs; i++)\n\t{\n\t\tint row = i;\n\t\tint col = constrainedDOFs[i];\n\t\tentrys.push_back(EIGEN_TRI(row, col, 1));\n\t\tconstrainTarget.data()[row] = 0;\n\t}\n\n\tfor (int i = 0; i < nodep->neighbor.size()*3; i++)\n\t{\n\t\tint row = i + numConstrainedDOFs;\n\t\tint col = nodep->neighbor[i/3]*3 + i % 3;\n\t\tentrys.push_back(EIGEN_TRI(row, col, 1));\n\t\tconstrainTarget.data()[row] = target_.data()[i];\n\t}\n\n\tfor (int i = 0; i < 3; i++)\n\t{\n\t\tint row = i + numConstrainedDOFs + nodep->neighbor.size() * 3;\n\t\tint col = nodeid * 3 + i;\n\t\tentrys.push_back(EIGEN_TRI(row, col, 1));\n\t\tconstrainTarget.data()[row] = target_.data()[nodep->neighbor.size() * 3+i];\n\t}\n\tconstrainMatrix->setFromTriplets(entrys.begin(), entrys.end());\n\n}\n\ndouble ModalWarpingTrainingModel::getMaxRotatedAngleFromW(VectorXd &w)\n{\n\tdouble maxAngle = -DBL_MAX;\n\tint numVertex = w.rows() / 3;\n\tfor (int i = 0; i < numVertex; i++)\n\t{\n\t\tVector3d wi;\n\t\twi.data()[0] = w.data()[i * 3 + 0];\n\t\twi.data()[1] = w.data()[i * 3 + 1];\n\t\twi.data()[2] = w.data()[i * 3 + 2];\n\t\tdouble angle = wi.norm();\n\t\tif (angle > maxAngle)\n\t\t{\n\t\t\tmaxAngle = angle;\n\t\t}\n\t}\n\treturn maxAngle;\n}\n\nvoid ModalWarpingTrainingModel::samplePoissonRatio(double maxPoisson, double minPoisson, int maxNumPoisson, int minNumPoisson, std::vector<Vector3d> &nodeforce, std::vector<Vector3d> &forcedirection, std::vector<bool> &ifreset, std::vector<double> &poissonPerdirection)\n{\n\tint num_direction = nodeforce.size();\n\tpoissonPerdirection.clear();\n\n\tVector3d baseline(-1, 0, 0);\n\tdouble maxpoisson = maxPoisson;\n\tdouble minpoisson = minPoisson;\n\tint maxnumpoisson = maxNumPoisson;\n\tint minnumpoisson = minNumPoisson;\n\tthis->poissonPerDis.clear();\n\n\tstd::vector<Vector3d> finalnodeforce;\n\tstd::vector<Vector3d> finalforcedirection;\n\tstd::vector<bool> finalifreset;\n\n\tfor (int i = 0; i < num_direction; i++)\n\t{\n\t\tdouble angle = forcedirection[i].dot(baseline);\n\t\tangle = std::acos(angle);\n\t\tint  numpoisson = angle / (M_PI / 2.0)*(minnumpoisson - maxnumpoisson) + maxnumpoisson;\n\t\tfor (int j = 0; j < numpoisson; j++)\n\t\t{\n\t\t\tfinalnodeforce.push_back(nodeforce[i]);\n\t\t\tfinalforcedirection.push_back(forcedirection[i]);\n\t\t\tfinalifreset.push_back(ifreset[i]);\n\n\t\t\tdouble interval = (maxpoisson - minpoisson) / (numpoisson - 1);\n\t\t\tif (numpoisson == 1)\n\t\t\t{\n\t\t\t\tinterval = (maxpoisson - minpoisson);\n\t\t\t}\n\t\t\tdouble poisson = interval*j + minpoisson;\n\t\t\tpoissonPerdirection.push_back(poisson);\n\t\t}\n\t}\n\n\tnodeforce = finalnodeforce;\n\tforcedirection = finalforcedirection;\n\tifreset = finalifreset;\n}\n", "meta": {"hexsha": "e358298087f30805125526f541d2e6243a3affc1", "size": 51234, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Release/src/DeepWarp/ModalWarpingTrainingModel.cpp", "max_stars_repo_name": "lrquad/NNWarp", "max_stars_repo_head_hexsha": "69e20bc02beb0bd655620cdcfa512a00521e9a9c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2019-01-28T04:39:26.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-25T09:30:24.000Z", "max_issues_repo_path": "Release/src/DeepWarp/ModalWarpingTrainingModel.cpp", "max_issues_repo_name": "lrquad/NNWarp", "max_issues_repo_head_hexsha": "69e20bc02beb0bd655620cdcfa512a00521e9a9c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-08-02T02:44:52.000Z", "max_issues_repo_issues_event_max_datetime": "2019-08-02T02:44:52.000Z", "max_forks_repo_path": "Release/src/DeepWarp/ModalWarpingTrainingModel.cpp", "max_forks_repo_name": "lrquad/NNWarp", "max_forks_repo_head_hexsha": "69e20bc02beb0bd655620cdcfa512a00521e9a9c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2019-11-11T06:14:04.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-24T05:19:16.000Z", "avg_line_length": 28.7025210084, "max_line_length": 672, "alphanum_fraction": 0.703204903, "num_tokens": 15754, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7772998611746912, "lm_q2_score": 0.4416730056646256, "lm_q1q2_score": 0.3433123659877221}}
{"text": "// This file generate the score file .pss and produce a skeleton file\n#include <cstdlib>\n#include <ctime>\n#include <math.h>\n#include <stdexcept>\n\n#include <boost/program_options.hpp>\n#include <boost/timer/timer.hpp>\n#include <boost/thread.hpp>\n#include <boost/algorithm/string.hpp>  \n\n#include \"urlearning/base/record_file.h\"\n#include \"urlearning/base/bayesian_network.h\"\n#include \"urlearning/base/variable.h\"\n\n#include \"urlearning/ad_tree/ad_node.h\"\n#include \"urlearning/ad_tree/ad_tree.h\"\n\n#include \"urlearning/scoring_function/scoring_function.h\"\n#include \"urlearning/scoring_function/score_calculator.h\"\n\n#include \"urlearning/scoring_function/constraints.h\"\n#include \"urlearning/base/skeleton.hpp\"\n\n#include \"urlearning/scoring_function/bdeu_scoring_function.h\"\n#include \"urlearning/scoring_function/bic_scoring_function.h\"\n#include \"urlearning/scoring_function/fnml_scoring_function.h\"\n#include \"urlearning/scoring_function/lasso_entropy_scoring_function.h\"\n#include \"urlearning/scoring_function/adaptive_lasso_entropy.h\"\n#include \"urlearning/scoring_function/BIC_OLS.h\"\nnamespace po = boost::program_options;\n/**\n * The file containing the data.\n */\nstd::string inputFile;\n\n/**\n * The delimiter in each line.\n */\nchar delimiter = ',';\n\n/**\n * The file to write the scores.\n */\nstd::string outputFile;\n\n/**\n * File specifying constraints on the scores.\n */\nstd::string constraintsFile;\n\n/**\n * Skeleton File specifies the skeleton superstructure\n */\nstd::string skeletonFile;\n\ndatastructures::Skeleton skeleton;\n\n/**\n * The minimum number of records in the AD-tree.\n */\nint rMin = 5;\n\n/**\n * The scoring function to use.\n */\nstd::string sf = \"lasso\";\n\n/**\n * which score to use, 0 for lasso, 1 for entropy1, 2 for entropy2\n */\nint which = 1;\n/**\n * A reference to the scoring function object.\n */\nscoring::ScoringFunction *scoringFunction;\n\n/**\n * The ess to use for BDeu.\n */\n\nfloat equivalentSampleSize = 1.0f;\n\n/**\n * A hard limit on the size of parent sets.\n */\nint maxParents = -1;\n\n/**\n * The number of threads to use.\n */\nint threadCount = 1;\n\n/**\n * The maximum amount of time to use for each variable.\n */\nint runningTime = -1;\n\n/**\n * Whether the data file has variable names in the first row.\n */\nbool hasHeader = false;\n\n/**\n * Whether to prune the scores before printing\n */\nbool prune = true;\n\n/**\n * Whether to use deCampos-style pruning.\n */\nbool enableDeCamposPruning = false;\n\n/**\n * The network information.\n */\ndatastructures::BayesianNetwork network;\n\n/**\n * Constraints on the allowed scores.\n */\nscoring::Constraints *constraints;\n\ninline std::string getTime() {\n    time_t now = time(0);\n    tm *gmtm = gmtime(&now);\n    std::string dt(asctime(gmtm));\n    boost::trim(dt);\n    return dt;\n}\n\nvoid scoringThread(int thread) {\n    scoring::ScoreCalculator scoreCalculator(scoringFunction, maxParents, network.size(), runningTime, constraints);\n    const int num = network.size();\n    \n    for (int variable = 0; variable < network.size(); variable++) {\n        if (variable % threadCount != thread) {\n            continue;\n        }\n\n        printf(\"Thread: %d, Variable: %d, Time: %s\\n\", thread, variable, getTime().c_str());\n\n        FloatMap sc;\n        init_map(sc);\n\t// also include neighbors' neighbors\n\tvarset orig_neighbor_bits = skeleton.get_neighbors(variable);\n\tvarset neighbor_bits = orig_neighbor_bits;\n\tconst int card1 = cardinality(orig_neighbor_bits);\n\tfor(int j=0; j < num; j++)\n\t{\n\t  if(VARSET_GET(orig_neighbor_bits, j) and j != variable)\n\t    neighbor_bits = VARSET_OR( neighbor_bits, skeleton.get_neighbors(j) );\n\t}\n\tconst int card2 = cardinality(neighbor_bits);\n        scoreCalculator.calculateScores( variable, sc, neighbor_bits );\n\n        //#ifdef DEBUG\n        int size = sc.size();\n        printf(\"Thread: %d, Variable: %d, Size before pruning: %d, Time: %s, neighbor cardinality %d/%d: %s / %s\\n\"\n\t      , thread, variable, size, getTime().c_str(), card1, card2\n\t      , varsetToString(orig_neighbor_bits).c_str(), varsetToString(neighbor_bits).c_str() );\n        //#endif\n        \n        //Ni added, print out score\n        //printf(\"Independent and dependent scores, variable # %d, ind_score %f, depend_score %f\\n\", variable, sc[0], sc[optimal_parents[variable]]);\n//    Ni added, commented out on June 10, 2017, prune might not work with continuous case\n//        if (prune) {\n//            scoreCalculator.prune(sc);\n//            int prunedSize = sc.size();\n//            printf(\"Thread: %d, Variable: %d, Size after pruning: %d, Time: %s\\n\", thread, variable, prunedSize, getTime().c_str());\n//        }\n\n        std::string varFilename = outputFile + \".\" + TO_STRING(variable);\n        FILE *varOut = fopen(varFilename.c_str(), \"w\");\n\n        datastructures::Variable *var = network.get(variable);\n        fprintf(varOut, \"VAR %s\\n\", var->getName().c_str());\n        fprintf(varOut, \"META arity=%d\\n\", var->getCardinality());\n\n        //fprintf(varOut, \"META values=\");\n        //for (int i = 0; i < var->getCardinality(); i++) {\n        //    fprintf(varOut, \"%s \", var->getValue(i).c_str());\n        //}\n        //fprintf(varOut, \"\\n\");\n\n\n        for (auto score = sc.begin(); score != sc.end(); score++) {\n            varset parentSet = (*score).first;\n            float s = (*score).second;\n\n            fprintf(varOut, \"%f \", s);\n\n            for (int p = 0; p < network.size(); p++) {\n                if (VARSET_GET(parentSet, p)) {\n                    fprintf(varOut, \"%s \", network.get(p)->getName().c_str());\n                }\n            }\n\n            fprintf(varOut, \"\\n\");\n        }\n\n        fprintf(varOut, \"\\n\");\n        fclose(varOut);\n\n        sc.clear();\n    }\n}\n\nint main(int argc, char** argv) {\n    boost::timer::auto_cpu_timer t;\n\n    std::string description = std::string(\"Compute the scores for a csv file.  Example usage: \") + argv[0] + \" iris.csv iris.pss\";\n    po::options_description desc(description);\n    double lambda = 0.5; // for lasso \n    bool adaptive = false;\n    desc.add_options()\n            (\"input\", po::value<std::string > (&inputFile)->required(), \"The input file. First positional argument.\")\n            (\"output\", po::value<std::string > (&outputFile)->required(), \"The output file. Second positional argument.\")\n            (\"delimiter,d\", po::value<char> (&delimiter)->required()->default_value(','), \"The delimiter of the input file.\")\n            (\"lambda,l\", po::value<double> (&lambda), \"The lambda in Lasso.\")\n            (\"adaptive,a\", \"Use adaptive Lasso\")\n            (\"scoreType,w\", po::value<int> (&which)->default_value(1), \"which score, 0 for lasso, 1 for entropy1, 2 for entropy2\")\n            (\"constraints,c\", po::value<std::string > (&constraintsFile), \"The file specifying constraints on the scores.\")\n            (\"skeleton,k\", po::value<std::string > (&skeletonFile), \"The file specifying the skeleton superstructure\")\n            (\"rMin,m\", po::value<int> (&rMin)->default_value(5), \"The minimum number of records in the AD-tree nodes.\")\n            (\"function,f\", po::value<std::string > (&sf)->default_value(\"BIC\"), \"The scoring function to use.\")\n            (\"ess,e\", po::value<float> (&equivalentSampleSize)->default_value(1.0f), \"The equivalent sample size, if BDeu is used.\")\n            (\"maxParents,p\", po::value<int> (&maxParents)->default_value(0), \"The maximum number of parents for any variable. A value less than 1 means no limit.\")\n            (\"threads,t\", po::value<int> (&threadCount)->default_value(1), \"The number of separate threads to use for score calculations.\")\n            (\"time,r\", po::value<int> (&runningTime)->default_value(-1), \"The maximum amount of time to use for each variable. A value less than 1 means no limit.\")\n            (\"hasHeader,s\", \"Add this flag if the first line of the input file gives the variable names.\")\n            (\"doNotPrune,o\", \"Add this flag if the scores should NOT be pruned at the end of the search.\")\n            (\"enableDeCamposPruning\", \"Add this flag to ENABLE DeCampos & Ji (JMLR 2011) pruning for BDeu. This feature is experimental and appears to contain some bugs for sufficiently large parent limits for BDeu. This flag has no effect for BIC or fNML.\")\n            (\"help,h\", \"Show this help message.\")\n            ;\n\n    po::positional_options_description positionalOptions;\n    positionalOptions.add(\"input\", 1);\n    positionalOptions.add(\"output\", 1);\n\n    po::variables_map vm;\n    po::store(po::command_line_parser(argc, argv).options(desc)\n            .positional(positionalOptions).run(),\n            vm);\n\n    if (vm.count(\"help\") || argc == 1) {\n        std::cout << desc;\n        return 0;\n    }\n    if(vm.count(\"adaptive\"))\n    {\n        adaptive = true;\n        std::cout << \"Will use adaptive Lasso\\n\";\n    }\n\n    po::notify(vm);\n\n    hasHeader = vm.count(\"hasHeader\");\n    prune = (vm.count(\"doNotPrune\") == 0);\n    enableDeCamposPruning = vm.count(\"enableDeCamposPruning\");\n\n    if (threadCount < 1) {\n        threadCount = 1;\n    }\n\n    printf(\"URLearning, Score Calculator\\n\");\n    printf(\"Input file: '%s'\\n\", inputFile.c_str());\n    printf(\"Output file: '%s'\\n\", outputFile.c_str());\n    printf(\"Delimiter: '%c'\\n\", delimiter);\n    printf(\"Constraints file: '%s'\\n\", constraintsFile.c_str());\n    printf(\"r_min: '%d'\\n\", rMin);\n    printf(\"Scoring function: '%s'\\n\", sf.c_str());\n    printf(\"ESS: '%f'\\n\", equivalentSampleSize);\n    printf(\"Maximum parents: '%d'\\n\", maxParents);\n    printf(\"Threads: '%d'\\n\", threadCount);\n    printf(\"Running time (per variable): '%d'\\n\", runningTime);\n    printf(\"Has header: '%s'\\n\", (hasHeader ? \"true\" : \"false\"));\n    printf(\"Enable end-of-scoring pruning: '%s'\\n\", (prune ? \"true\" : \"False\"));\n    printf(\"Enable deCampos-style pruning (experimental for BDeu): '%s'\\n\", (enableDeCamposPruning ? \"true\" : \"False\"));\n\n\n    printf(\"Parsing input file.\\n\");\n    datastructures::RecordFile recordFile(inputFile, delimiter, hasHeader);\n    recordFile.read();\n\n    printf(\"Initializing data specifications.\\n\");\n    network.initialize(recordFile);\n\n    printf(\"Creating AD-tree.\\n\");\n    scoring::ADTree *adTree = new scoring::ADTree(rMin);\n    adTree->initialize(network, recordFile);\n    adTree->createTree();\n\n    boost::algorithm::to_lower(sf);\n\n    if (maxParents > network.size() || maxParents < 1) {\n        maxParents = network.size() - 1;\n    }\n\n    if (sf.compare(\"bic\") == 0) { // bic discrete\n        int maxParentCount = log(2 * recordFile.size() / log(recordFile.size()));\n        if (maxParentCount < maxParents) {\n            maxParents = maxParentCount;\n        }\n    } else if (sf.compare(\"cbic\") == 0) { // bic continuous\n    } else if (sf.compare(\"fnml\") == 0) {\n    } else if (sf.compare(\"bdeu\") == 0) {\n    } else if (sf.compare(\"lasso\") == 0 or sf.compare(\"entropy\") == 0) {  //Ni added\n    } else if (sf.compare(\"adaptive_lasso\") == 0 or sf.compare(\"adaptive\") == 0) {  //Ni added\n    } else {\n        throw std::runtime_error(\"Invalid scoring function.  Options are: 'lasso','adaptive', 'BIC', 'fNML' or 'BDeu'.\");\n    }\n\n    scoring::Constraints *constraints = NULL;\n    if (constraintsFile.length() > 0) {\n        constraints = scoring::parseConstraints(constraintsFile, network);\n    }\n    printf(\"Skeleton file %s\\n\", skeletonFile.c_str());\n    if(skeletonFile.size() > 0) //Need parse the skeleton file\n    {\n    \tif(skeletonFile.find(\".arc\") + 4 == skeletonFile.size())\n    \t\tskeleton.read_arc_list_file(skeletonFile, network.size());\n    \telse\n    \t\tskeleton.read_matrix_file(skeletonFile);\n    }\n    else\n    {\n        skeleton.set_variable_count(network.size());\n    }\n    \n    \n    scoringFunction = NULL;\n    scoring::LogLikelihoodCalculator *llc = NULL;\n    std::vector< std::vector< float >* >* regret = NULL;\n\n    if(sf.compare(\"bic\") == 0 or sf.compare(\"fnml\") == 0)\n    {\n      std::vector<float> ilogi = scoring::LogLikelihoodCalculator::getLogCache(recordFile.size());\n      llc = new scoring::LogLikelihoodCalculator(adTree, network, ilogi);\n      regret = scoring::getRegretCache(recordFile.size(), network.getMaxCardinality());\n    }\n\n\n    if (sf.compare(\"bic\") == 0) //bic for discrete variables\n    { \n        scoringFunction = new scoring::BICScoringFunction(network, recordFile, llc, constraints, enableDeCamposPruning);\n    }\n    else if(sf.compare(\"cbic\") == 0) // bic for continuous variables\n    {\n\tprintf(\"Creating continuous BIC function\\n\");\n\tscoringFunction = new scoring::BIC_OLS_Function(network, inputFile, constraints, enableDeCamposPruning, lambda);\n    } \n    else if (sf.compare(\"fnml\") == 0) \n    {\n        scoringFunction = new scoring::fNMLScoringFunction(network, llc, constraints, regret, enableDeCamposPruning);\n    } \n    else if (sf.compare(\"bdeu\") == 0) \n    {\n        scoringFunction = new scoring::BDeuScoringFunction(equivalentSampleSize, network, adTree, constraints, enableDeCamposPruning);\n    } \n    else if (sf.compare(\"lasso\") == 0 or sf.compare(\"entropy\") == 0)\n    {\n        printf(\"Creating Entropy/LassoFunction with input file %s\\n\", inputFile.c_str());\n        scoringFunction = new scoring::LassoEntropyScoringFunction(network, which, inputFile, lambda, constraints, enableDeCamposPruning);\n    } \n    else if (sf.compare(\"adaptive_lasso\") == 0 or sf.compare(\"adaptive\") == 0)\n    {\n        printf(\"Creating Adaptive Entropy/LassoFunction with input file %s\\n\", inputFile.c_str());\n        scoringFunction = new scoring::AdaptiveLassoEntropyScoringFunction(network, which, inputFile, lambda, constraints, adaptive, enableDeCamposPruning);\n    }\n    \n    std::vector<boost::thread*> threads;\n    for (int thread = 0; thread < threadCount; thread++) {\n        boost::thread *workerThread = new boost::thread(scoringThread, thread);\n        threads.push_back(workerThread);\n    }\n\n    for (auto it = threads.begin(); it != threads.end(); it++) {\n        (*it)->join();\n    }\n\n\n    // concatenate all of the files together\n    std::ofstream out(outputFile, std::ios_base::out | std::ios_base::binary);\n\n    // first, the header information\n    std::string header = \"META pss_version = 0.1\\nMETA input_file=\" + inputFile + \"\\nMETA num_records=\" + TO_STRING(recordFile.size()) + \"\\n\";\n    header += \"META parent_limit=\" + TO_STRING(maxParents) + \"\\nMETA score_type=\" + sf + \"\\nMETA ess=\" + TO_STRING(equivalentSampleSize) + \"\\n\\n\";\n    out.write(header.c_str(), header.size());\n\n    for (int variable = 0; variable < network.size(); variable++) {\n        std::string varFilename = outputFile + \".\" + TO_STRING(variable);\n        std::ofstream varFile(varFilename, std::ios_base::in | std::ios_base::binary);\n\n        out << varFile.rdbuf();\n        varFile.close();\n\n        // and remove the variable file\n        remove(varFilename.c_str());\n    }\n\n    out.close();\n}\n", "meta": {"hexsha": "d48a7c2e42184f4f18385f5fc00c14639c5911a4", "size": 14711, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "urlearning/score/score_main.cpp", "max_stars_repo_name": "ninalu/urlearning-cpp", "max_stars_repo_head_hexsha": "c4c51b0046646b45573aec1b35c1678c422b3802", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "urlearning/score/score_main.cpp", "max_issues_repo_name": "ninalu/urlearning-cpp", "max_issues_repo_head_hexsha": "c4c51b0046646b45573aec1b35c1678c422b3802", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "urlearning/score/score_main.cpp", "max_forks_repo_name": "ninalu/urlearning-cpp", "max_forks_repo_head_hexsha": "c4c51b0046646b45573aec1b35c1678c422b3802", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-02-12T04:17:55.000Z", "max_forks_repo_forks_event_max_datetime": "2018-02-12T04:17:55.000Z", "avg_line_length": 36.4133663366, "max_line_length": 258, "alphanum_fraction": 0.6409489498, "num_tokens": 3717, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6757646140788307, "lm_q2_score": 0.5078118642792044, "lm_q1q2_score": 0.3431612884892881}}
{"text": "#ifndef STAN_MATH_PRIM_SCAL_FUN_UB_CONSTRAIN_HPP\n#define STAN_MATH_PRIM_SCAL_FUN_UB_CONSTRAIN_HPP\n\n#include <stan/math/prim/meta.hpp>\n#include <boost/math/tools/promotion.hpp>\n#include <stan/math/prim/scal/fun/identity_constrain.hpp>\n#include <stan/math/prim/scal/fun/constants.hpp>\n#include <cmath>\n\nnamespace stan {\nnamespace math {\n\n/**\n * Return the upper-bounded value for the specified unconstrained\n * scalar and upper bound.\n *\n * <p>The transform is\n *\n * <p>\\f$f(x) = U - \\exp(x)\\f$\n *\n * <p>where \\f$U\\f$ is the upper bound.\n *\n * If the upper bound is positive infinity, this function\n * reduces to <code>identity_constrain(x)</code>.\n *\n * @tparam T type of scalar\n * @tparam U type of upper bound\n * @param[in] x free scalar.\n * @param[in] ub upper bound\n * @return scalar constrained to have upper bound\n */\ntemplate <typename T, typename U>\ninline return_type_t<T, U> ub_constrain(const T& x, const U& ub) {\n  using std::exp;\n  if (ub == INFTY) {\n    return identity_constrain(x);\n  }\n  return ub - exp(x);\n}\n\n/**\n * Return the upper-bounded value for the specified unconstrained\n * scalar and upper bound and increment the specified log\n * probability reference with the log absolute Jacobian\n * determinant of the transform.\n *\n * <p>The transform is as specified for\n * <code>ub_constrain(T, double)</code>.  The log absolute Jacobian\n * determinant is\n *\n * <p>\\f$ \\log | \\frac{d}{dx} -\\mbox{exp}(x) + U |\n *     = \\log | -\\mbox{exp}(x) + 0 | = x\\f$.\n *\n * If the upper bound is positive infinity, this function\n * reduces to <code>identity_constrain(x, lp)</code>.\n *\n * @tparam T type of scalar\n * @tparam U type of upper bound\n * @param[in] x free scalar.\n * @param[in] ub upper bound\n * @param[in,out] lp log density\n * @return scalar constrained to have upper bound\n */\ntemplate <typename T, typename U>\ninline return_type_t<T, U> ub_constrain(const T& x, const U& ub, T& lp) {\n  using std::exp;\n  if (ub == INFTY) {\n    return identity_constrain(x, lp);\n  }\n  lp += x;\n  return ub - exp(x);\n}\n\n}  // namespace math\n\n}  // namespace stan\n\n#endif\n", "meta": {"hexsha": "badf291b8ab162edd42a3f27c329a2e40f9a9bf7", "size": 2071, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "stan/math/prim/scal/fun/ub_constrain.hpp", "max_stars_repo_name": "PhilClemson/math", "max_stars_repo_head_hexsha": "fffe604a7ead4525be2551eb81578c5f351e5c87", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "stan/math/prim/scal/fun/ub_constrain.hpp", "max_issues_repo_name": "PhilClemson/math", "max_issues_repo_head_hexsha": "fffe604a7ead4525be2551eb81578c5f351e5c87", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "stan/math/prim/scal/fun/ub_constrain.hpp", "max_forks_repo_name": "PhilClemson/math", "max_forks_repo_head_hexsha": "fffe604a7ead4525be2551eb81578c5f351e5c87", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.2151898734, "max_line_length": 73, "alphanum_fraction": 0.6837276678, "num_tokens": 588, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6757646140788307, "lm_q2_score": 0.5078118642792044, "lm_q1q2_score": 0.3431612884892881}}
{"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: Jeremiah Willcock\n//           Douglas Gregor\n//           Andrew Lumsdaine\n#ifndef BOOST_GRAPH_GURSOY_ATUN_LAYOUT_HPP\n#define BOOST_GRAPH_GURSOY_ATUN_LAYOUT_HPP\n\n// Gursoy-Atun graph layout, based on:\n// \"Neighbourhood Preserving Load Balancing: A Self-Organizing Approach\"\n// in EuroPar 2000, p. 234 of LNCS 1900\n// http://springerlink.metapress.com/link.asp?id=pcu07ew5rhexp9yt\n\n#include <boost/config/no_tr1/cmath.hpp>\n#include <boost/throw_exception.hpp>\n#include <vector>\n#include <exception>\n#include <algorithm>\n\n#include <boost/graph/visitors.hpp>\n#include <boost/graph/properties.hpp>\n#include <boost/random/uniform_01.hpp>\n#include <boost/random/linear_congruential.hpp>\n#include <boost/shared_ptr.hpp>\n#include <boost/graph/breadth_first_search.hpp>\n#include <boost/graph/dijkstra_shortest_paths.hpp>\n#include <boost/graph/named_function_params.hpp>\n#include <boost/graph/topology.hpp>\n\nnamespace boost { \n\nnamespace detail {\n\nstruct over_distance_limit : public std::exception {};\n\ntemplate <typename PositionMap, typename NodeDistanceMap,  typename Topology,\n          typename Graph>\nstruct update_position_visitor {\n  typedef typename Topology::point_type Point;\n  PositionMap position_map;\n  NodeDistanceMap node_distance;\n  const Topology& space;\n  Point input_vector;\n  double distance_limit;\n  double learning_constant;\n  double falloff_ratio;\n\n  typedef boost::on_examine_vertex event_filter;\n\n  typedef typename graph_traits<Graph>::vertex_descriptor\n    vertex_descriptor;\n\n  update_position_visitor(PositionMap position_map,\n                          NodeDistanceMap node_distance,\n                          const Topology& space,\n                          const Point& input_vector,\n                          double distance_limit,\n                          double learning_constant,\n                          double falloff_ratio):\n    position_map(position_map), node_distance(node_distance), \n    space(space),\n    input_vector(input_vector), distance_limit(distance_limit),\n    learning_constant(learning_constant), falloff_ratio(falloff_ratio) {}\n\n  void operator()(vertex_descriptor v, const Graph&) const \n  {\n#ifndef BOOST_NO_STDC_NAMESPACE\n    using std::pow;\n#endif\n\n    if (get(node_distance, v) > distance_limit)\n      BOOST_THROW_EXCEPTION(over_distance_limit());\n    Point old_position = get(position_map, v);\n    double distance = get(node_distance, v);\n    double fraction = \n      learning_constant * pow(falloff_ratio, distance * distance);\n    put(position_map, v,\n        space.move_position_toward(old_position, fraction, input_vector));\n  }\n};\n\ntemplate<typename EdgeWeightMap>\nstruct gursoy_shortest\n{\n  template<typename Graph, typename NodeDistanceMap, typename UpdatePosition>\n  static inline void \n  run(const Graph& g, typename graph_traits<Graph>::vertex_descriptor s,\n      NodeDistanceMap node_distance,  UpdatePosition& update_position,\n      EdgeWeightMap weight)\n  {\n    boost::dijkstra_shortest_paths(g, s, weight_map(weight).\n      visitor(boost::make_dijkstra_visitor(std::make_pair(\n       boost::record_distances(node_distance, boost::on_edge_relaxed()),\n        update_position))));\n  }\n};\n\ntemplate<>\nstruct gursoy_shortest<dummy_property_map>\n{\n  template<typename Graph, typename NodeDistanceMap, typename UpdatePosition>\n  static inline void \n  run(const Graph& g, typename graph_traits<Graph>::vertex_descriptor s,\n      NodeDistanceMap node_distance,  UpdatePosition& update_position,\n      dummy_property_map)\n  {\n    boost::breadth_first_search(g, s,\n      visitor(boost::make_bfs_visitor(std::make_pair(\n        boost::record_distances(node_distance, boost::on_tree_edge()),\n        update_position))));\n  }\n};\n\n} // namespace detail\n\ntemplate <typename VertexListAndIncidenceGraph,  typename Topology,\n          typename PositionMap, typename Diameter, typename VertexIndexMap, \n          typename EdgeWeightMap>\nvoid \ngursoy_atun_step\n  (const VertexListAndIncidenceGraph& graph,  \n   const Topology& space,\n   PositionMap position,\n   Diameter diameter,\n   double learning_constant,\n   VertexIndexMap vertex_index_map,\n   EdgeWeightMap weight)\n{\n#ifndef BOOST_NO_STDC_NAMESPACE\n  using std::pow;\n  using std::exp;\n#endif\n\n  typedef typename graph_traits<VertexListAndIncidenceGraph>::vertex_iterator\n    vertex_iterator;\n  typedef typename graph_traits<VertexListAndIncidenceGraph>::vertex_descriptor\n    vertex_descriptor;\n  typedef typename Topology::point_type point_type;\n  vertex_iterator i, iend;\n  std::vector<double> distance_from_input_vector(num_vertices(graph));\n  typedef boost::iterator_property_map<std::vector<double>::iterator, \n                                       VertexIndexMap,\n                                       double, double&>\n    DistanceFromInputMap;\n  DistanceFromInputMap distance_from_input(distance_from_input_vector.begin(),\n                                           vertex_index_map);\n  std::vector<double> node_distance_map_vector(num_vertices(graph));\n  typedef boost::iterator_property_map<std::vector<double>::iterator, \n                                       VertexIndexMap,\n                                       double, double&>\n    NodeDistanceMap;\n  NodeDistanceMap node_distance(node_distance_map_vector.begin(),\n                                vertex_index_map);\n  point_type input_vector = space.random_point();\n  vertex_descriptor min_distance_loc \n    = graph_traits<VertexListAndIncidenceGraph>::null_vertex();\n  double min_distance = 0.0;\n  bool min_distance_unset = true;\n  for (boost::tie(i, iend) = vertices(graph); i != iend; ++i) {\n    double this_distance = space.distance(get(position, *i), input_vector);\n    put(distance_from_input, *i, this_distance);\n    if (min_distance_unset || this_distance < min_distance) {\n      min_distance = this_distance;\n      min_distance_loc = *i;\n    }\n    min_distance_unset = false;\n  }\n  assert (!min_distance_unset); // Graph must have at least one vertex\n  boost::detail::update_position_visitor<\n      PositionMap, NodeDistanceMap, Topology,\n      VertexListAndIncidenceGraph> \n    update_position(position, node_distance, space,\n                    input_vector, diameter, learning_constant, \n                    exp(-1. / (2 * diameter * diameter)));\n  std::fill(node_distance_map_vector.begin(), node_distance_map_vector.end(), 0);\n  try {\n    typedef detail::gursoy_shortest<EdgeWeightMap> shortest;\n    shortest::run(graph, min_distance_loc, node_distance, update_position,\n                  weight);    \n  } catch (detail::over_distance_limit) { \n    /* Thrown to break out of BFS or Dijkstra early */ \n  }\n}\n\ntemplate <typename VertexListAndIncidenceGraph,  typename Topology,\n          typename PositionMap, typename VertexIndexMap, \n          typename EdgeWeightMap>\nvoid gursoy_atun_refine(const VertexListAndIncidenceGraph& graph,  \n                        const Topology& space,\n                        PositionMap position,\n                        int nsteps,\n                        double diameter_initial,\n                        double diameter_final,\n                        double learning_constant_initial,\n                        double learning_constant_final,\n                        VertexIndexMap vertex_index_map,\n                        EdgeWeightMap weight) \n{\n#ifndef BOOST_NO_STDC_NAMESPACE\n  using std::pow;\n  using std::exp;\n#endif\n\n  typedef typename graph_traits<VertexListAndIncidenceGraph>::vertex_iterator\n    vertex_iterator;\n  typedef typename graph_traits<VertexListAndIncidenceGraph>::vertex_descriptor\n    vertex_descriptor;\n  typedef typename Topology::point_type point_type;\n  vertex_iterator i, iend;\n  double diameter_ratio = (double)diameter_final / diameter_initial;\n  double learning_constant_ratio = \n    learning_constant_final / learning_constant_initial;\n  std::vector<double> distance_from_input_vector(num_vertices(graph));\n  typedef boost::iterator_property_map<std::vector<double>::iterator, \n                                       VertexIndexMap,\n                                       double, double&>\n    DistanceFromInputMap;\n  DistanceFromInputMap distance_from_input(distance_from_input_vector.begin(),\n                                           vertex_index_map);\n  std::vector<int> node_distance_map_vector(num_vertices(graph));\n  typedef boost::iterator_property_map<std::vector<int>::iterator, \n                                       VertexIndexMap, double, double&>\n    NodeDistanceMap;\n  NodeDistanceMap node_distance(node_distance_map_vector.begin(),\n                                vertex_index_map);\n  for (int round = 0; round < nsteps; ++round) {\n    double part_done = (double)round / (nsteps - 1);\n    int diameter = (int)(diameter_initial * pow(diameter_ratio, part_done));\n    double learning_constant = \n      learning_constant_initial * pow(learning_constant_ratio, part_done);\n    gursoy_atun_step(graph, space, position, diameter, learning_constant, \n                     vertex_index_map, weight);\n  }\n}\n\ntemplate <typename VertexListAndIncidenceGraph,  typename Topology,\n          typename PositionMap, typename VertexIndexMap, \n          typename EdgeWeightMap>\nvoid gursoy_atun_layout(const VertexListAndIncidenceGraph& graph,  \n                        const Topology& space,\n                        PositionMap position,\n                        int nsteps,\n                        double diameter_initial,\n                        double diameter_final,\n                        double learning_constant_initial,\n                        double learning_constant_final,\n                        VertexIndexMap vertex_index_map,\n                        EdgeWeightMap weight)\n{\n  typedef typename graph_traits<VertexListAndIncidenceGraph>::vertex_iterator\n    vertex_iterator;\n  vertex_iterator i, iend;\n  for (boost::tie(i, iend) = vertices(graph); i != iend; ++i) {\n    put(position, *i, space.random_point());\n  }\n  gursoy_atun_refine(graph, space,\n                     position, nsteps,\n                     diameter_initial, diameter_final, \n                     learning_constant_initial, learning_constant_final,\n                     vertex_index_map, weight);\n}\n\ntemplate <typename VertexListAndIncidenceGraph,  typename Topology,\n          typename PositionMap, typename VertexIndexMap>\nvoid gursoy_atun_layout(const VertexListAndIncidenceGraph& graph,  \n                        const Topology& space,\n                        PositionMap position,\n                        int nsteps,\n                        double diameter_initial,\n                        double diameter_final,\n                        double learning_constant_initial,\n                        double learning_constant_final,\n                        VertexIndexMap vertex_index_map)\n{\n  gursoy_atun_layout(graph, space, position, nsteps, \n                     diameter_initial, diameter_final, \n                     learning_constant_initial, learning_constant_final, \n                     vertex_index_map, dummy_property_map());\n}\n\ntemplate <typename VertexListAndIncidenceGraph, typename Topology,\n          typename PositionMap>\nvoid gursoy_atun_layout(const VertexListAndIncidenceGraph& graph,  \n                        const Topology& space,\n                        PositionMap position,\n                        int nsteps,\n                        double diameter_initial,\n                        double diameter_final = 1.0,\n                        double learning_constant_initial = 0.8,\n                        double learning_constant_final = 0.2)\n{ \n  gursoy_atun_layout(graph, space, position, nsteps, diameter_initial,\n                     diameter_final, learning_constant_initial,\n                     learning_constant_final, get(vertex_index, graph)); \n}\n\ntemplate <typename VertexListAndIncidenceGraph, typename Topology,\n          typename PositionMap>\nvoid gursoy_atun_layout(const VertexListAndIncidenceGraph& graph,  \n                        const Topology& space,\n                        PositionMap position,\n                        int nsteps)\n{\n#ifndef BOOST_NO_STDC_NAMESPACE\n  using std::sqrt;\n#endif\n\n  gursoy_atun_layout(graph, space, position, nsteps, \n                     sqrt((double)num_vertices(graph)));\n}\n\ntemplate <typename VertexListAndIncidenceGraph, typename Topology,\n          typename PositionMap>\nvoid gursoy_atun_layout(const VertexListAndIncidenceGraph& graph,  \n                        const Topology& space,\n                        PositionMap position)\n{\n  gursoy_atun_layout(graph, space, position, num_vertices(graph));\n}\n\ntemplate<typename VertexListAndIncidenceGraph, typename Topology,\n         typename PositionMap, typename P, typename T, typename R>\nvoid \ngursoy_atun_layout(const VertexListAndIncidenceGraph& graph,  \n                   const Topology& space,\n                   PositionMap position,\n                   const bgl_named_params<P,T,R>& params)\n{\n#ifndef BOOST_NO_STDC_NAMESPACE\n  using std::sqrt;\n#endif\n\n  std::pair<double, double> diam(sqrt(double(num_vertices(graph))), 1.0);\n  std::pair<double, double> learn(0.8, 0.2);\n  gursoy_atun_layout(graph, space, position,\n                     choose_param(get_param(params, iterations_t()),\n                                  num_vertices(graph)),\n                     choose_param(get_param(params, diameter_range_t()), \n                                  diam).first,\n                     choose_param(get_param(params, diameter_range_t()), \n                                  diam).second,\n                     choose_param(get_param(params, learning_constant_range_t()), \n                                  learn).first,\n                     choose_param(get_param(params, learning_constant_range_t()), \n                                  learn).second,\n                     choose_const_pmap(get_param(params, vertex_index), graph,\n                                       vertex_index),\n                     choose_param(get_param(params, edge_weight), \n                                  dummy_property_map()));\n}\n\n} // namespace boost\n\n#endif // BOOST_GRAPH_GURSOY_ATUN_LAYOUT_HPP\n", "meta": {"hexsha": "b16a01f68fc1e673cae72f07fe034337b6211e12", "size": 14266, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "external/boost_1_44_0/boost/graph/gursoy_atun_layout.hpp", "max_stars_repo_name": "RaptDept/slimtune", "max_stars_repo_head_hexsha": "a9a248a342a51d95b7c833bce5bb91bf3db987f3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 27.0, "max_stars_repo_stars_event_min_datetime": "2020-11-12T19:24:54.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-27T23:10:45.000Z", "max_issues_repo_path": "external/boost_1_44_0/boost/graph/gursoy_atun_layout.hpp", "max_issues_repo_name": "RaptDept/slimtune", "max_issues_repo_head_hexsha": "a9a248a342a51d95b7c833bce5bb91bf3db987f3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-11-02T06:30:39.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-23T18:39:55.000Z", "max_forks_repo_path": "external/boost_1_44_0/boost/graph/gursoy_atun_layout.hpp", "max_forks_repo_name": "RaptDept/slimtune", "max_forks_repo_head_hexsha": "a9a248a342a51d95b7c833bce5bb91bf3db987f3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2018-06-27T13:17:56.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-02T16:59:24.000Z", "avg_line_length": 39.7381615599, "max_line_length": 82, "alphanum_fraction": 0.659119585, "num_tokens": 2844, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6757646010190476, "lm_q2_score": 0.5078118642792044, "lm_q1q2_score": 0.3431612818573753}}
{"text": "/*\n * DivRightHandSideAdjoint.cpp\n *\n *  Created on: 03.08.2017\n *      Author: thies\n */\n\n#include <deal.II/base/exceptions.h>\n#include <deal.II/base/types.h>\n#include <deal.II/base/work_stream.h>\n#include <deal.II/fe/fe.h>\n#include <deal.II/fe/fe_update_flags.h>\n#include <deal.II/fe/fe_values.h>\n\n#include <base/DiscretizedFunction.h>\n#include <forward/DivRightHandSideAdjoint.h>\n\n#include <functional>\n#include <vector>\n\nnamespace wavepi {\nnamespace forward {\nusing namespace dealii;\nusing namespace wavepi::base;\n\ntemplate <int dim>\nDivRightHandSideAdjoint<dim>::DivRightHandSideAdjoint(std::shared_ptr<Function<dim>> a,\n                                                      std::shared_ptr<Function<dim>> u)\n    : a(a), u(u) {}\n\ntemplate <int dim>\nDivRightHandSideAdjoint<dim>::AssemblyScratchData::AssemblyScratchData(const FiniteElement<dim> &fe,\n                                                                       const Quadrature<dim> &quad)\n    : fe_values(fe, quad, update_values | update_gradients | update_quadrature_points | update_JxW_values) {}\n\ntemplate <int dim>\nDivRightHandSideAdjoint<dim>::AssemblyScratchData::AssemblyScratchData(const AssemblyScratchData &scratch_data)\n    : fe_values(scratch_data.fe_values.get_fe(), scratch_data.fe_values.get_quadrature(),\n                update_values | update_gradients | update_quadrature_points | update_JxW_values) {}\n\ntemplate <int dim>\nvoid DivRightHandSideAdjoint<dim>::copy_local_to_global(Vector<double> &result, const AssemblyCopyData &copy_data) {\n  for (unsigned int i = 0; i < copy_data.local_dof_indices.size(); ++i)\n    result(copy_data.local_dof_indices[i]) += copy_data.cell_rhs(i);\n}\n\ntemplate <int dim>\nvoid DivRightHandSideAdjoint<dim>::local_assemble_dd(const Vector<double> &a, const Vector<double> &u,\n                                                     const typename DoFHandler<dim>::active_cell_iterator &cell,\n                                                     AssemblyScratchData &scratch_data, AssemblyCopyData &copy_data) {\n  const unsigned int dofs_per_cell = scratch_data.fe_values.get_fe().dofs_per_cell;\n  const unsigned int n_q_points    = scratch_data.fe_values.get_quadrature().size();\n\n  copy_data.cell_rhs.reinit(dofs_per_cell);\n  copy_data.local_dof_indices.resize(dofs_per_cell);\n  scratch_data.fe_values.reinit(cell);\n\n  cell->get_dof_indices(copy_data.local_dof_indices);\n\n  for (unsigned int q_point = 0; q_point < n_q_points; ++q_point)\n    for (unsigned int i = 0; i < dofs_per_cell; ++i)\n      for (unsigned int ka = 0; ka < dofs_per_cell; ++ka)\n        for (unsigned int ku = 0; ku < dofs_per_cell; ++ku)\n          copy_data.cell_rhs(i) -= a[copy_data.local_dof_indices[ka]] * scratch_data.fe_values.shape_grad(ka, q_point) *\n                                   u[copy_data.local_dof_indices[ku]] * scratch_data.fe_values.shape_grad(ku, q_point) *\n                                   scratch_data.fe_values.shape_value(i, q_point) * scratch_data.fe_values.JxW(q_point);\n}\n\ntemplate <int dim>\nvoid DivRightHandSideAdjoint<dim>::local_assemble_cc(const Function<dim> *const a, const Function<dim> *const u,\n                                                     const typename DoFHandler<dim>::active_cell_iterator &cell,\n                                                     AssemblyScratchData &scratch_data, AssemblyCopyData &copy_data) {\n  const unsigned int dofs_per_cell = scratch_data.fe_values.get_fe().dofs_per_cell;\n  const unsigned int n_q_points    = scratch_data.fe_values.get_quadrature().size();\n\n  copy_data.cell_rhs.reinit(dofs_per_cell);\n  copy_data.local_dof_indices.resize(dofs_per_cell);\n  scratch_data.fe_values.reinit(cell);\n\n  cell->get_dof_indices(copy_data.local_dof_indices);\n\n  for (unsigned int q_point = 0; q_point < n_q_points; ++q_point) {\n    auto grad_a = a->gradient(scratch_data.fe_values.quadrature_point(q_point));\n    auto grad_u = u->gradient(scratch_data.fe_values.quadrature_point(q_point));\n\n    for (unsigned int i = 0; i < dofs_per_cell; ++i)\n      copy_data.cell_rhs(i) -=\n          grad_a * grad_u * scratch_data.fe_values.shape_value(i, q_point) * scratch_data.fe_values.JxW(q_point);\n  }\n}\n\ntemplate <int dim>\nvoid DivRightHandSideAdjoint<dim>::create_right_hand_side(const DoFHandler<dim> &dof, const Quadrature<dim> &quad,\n                                                          Vector<double> &rhs) const {\n  AssertThrow(a != nullptr, ExcZero());\n  AssertThrow(u != nullptr, ExcZero());\n\n  a->set_time(this->get_time());\n  u->set_time(this->get_time());\n\n  auto a_d = dynamic_cast<DiscretizedFunction<dim> *>(a.get());\n  auto u_d = dynamic_cast<DiscretizedFunction<dim> *>(u.get());\n\n  if (a_d != nullptr && u_d != nullptr) {\n    Vector<double> ca = a_d->get_function_coefficients(a_d->get_time_index());\n    Vector<double> cu = u_d->get_function_coefficients(u_d->get_time_index());\n\n    Assert(ca.size() == dof.n_dofs(), ExcDimensionMismatch(ca.size(), dof.n_dofs()));\n    Assert(cu.size() == dof.n_dofs(), ExcDimensionMismatch(cu.size(), dof.n_dofs()));\n\n    WorkStream::run(\n        dof.begin_active(), dof.end(),\n        std::bind(&DivRightHandSideAdjoint<dim>::local_assemble_dd, *this, std::ref(ca), std::ref(cu),\n                  std::placeholders::_1, std::placeholders::_2, std::placeholders::_3),\n        std::bind(&DivRightHandSideAdjoint<dim>::copy_local_to_global, *this, std::ref(rhs), std::placeholders::_1),\n        AssemblyScratchData(dof.get_fe(), quad), AssemblyCopyData());\n  } else\n    WorkStream::run(\n        dof.begin_active(), dof.end(),\n        std::bind(&DivRightHandSideAdjoint<dim>::local_assemble_cc, *this, a.get(), u.get(), std::placeholders::_1,\n                  std::placeholders::_2, std::placeholders::_3),\n        std::bind(&DivRightHandSideAdjoint<dim>::copy_local_to_global, *this, std::ref(rhs), std::placeholders::_1),\n        AssemblyScratchData(dof.get_fe(), quad), AssemblyCopyData());\n}\n\ntemplate <int dim>\nDiscretizedFunction<dim> DivRightHandSideAdjoint<dim>::run_adjoint(std::shared_ptr<SpaceTimeMesh<dim>> mesh) {\n  DiscretizedFunction<dim> target(mesh);\n\n  for (size_t i = 0; i < mesh->length(); i++) {\n    this->set_time(mesh->get_time(i));\n    auto dof_handler = mesh->get_dof_handler(i);\n\n    Vector<double> tmp(dof_handler->n_dofs());\n    this->create_right_hand_side(*dof_handler, mesh->get_quadrature(), tmp);\n    target[i] = tmp;\n  }\n\n  return target;\n}\n\ntemplate class DivRightHandSideAdjoint<1>;\ntemplate class DivRightHandSideAdjoint<2>;\ntemplate class DivRightHandSideAdjoint<3>;\n\n} /* namespace forward */\n} /* namespace wavepi */\n", "meta": {"hexsha": "3036384ccfd0f340786eaf3cc2dc86530db1be89", "size": 6559, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lib/forward/DivRightHandSideAdjoint.cpp", "max_stars_repo_name": "thiesgerken/wavepi", "max_stars_repo_head_hexsha": "5af37946dcc1910ad1cccdc76d2e2f546eeafec4", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "lib/forward/DivRightHandSideAdjoint.cpp", "max_issues_repo_name": "thiesgerken/wavepi", "max_issues_repo_head_hexsha": "5af37946dcc1910ad1cccdc76d2e2f546eeafec4", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lib/forward/DivRightHandSideAdjoint.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": 44.3175675676, "max_line_length": 120, "alphanum_fraction": 0.6789144687, "num_tokens": 1629, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6757646010190476, "lm_q2_score": 0.5078118642792044, "lm_q1q2_score": 0.3431612818573753}}
{"text": "/*Copyright (c) 2021 James Gayvert\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n*/\n\n#include <iostream>\n#include <cmath>\n#include <stdlib.h>\n#include <vector>\n//#include <boost/math/special_functions/gamma.hpp>  remove for now, keep in case we ever end up using boost\n#include <vector>\n#include \"Shell.h\"\n#include \"boxcap.h\"\n#include \"../asa/asa239.h\"\n\nusing namespace std;\n\n\nconst double PI = 3.14159265358979;\nconst double sqrt_pi = 1.77245385090552;\nconst double OOPI3 = 1.0 / (PI * PI * PI);\nconst double gauss_factor[] = {1.0, 0.5, 0.75, 1.875, 6.5625, 29.53125, 162.421875};\n\n//\n// box-CAP helper functions\n//\ndouble intmod_r2(double a, int k, double cl, double cu);\nint xi (double z, int i);\ndouble intgauss(double alpha, int n, int = 0, const char* = \"message \");\nvector<double> polmulti(vector<double>& g, int n, vector<double>& h, int m,\n\t       int = 0, const char* = \"message\");\nvoid poltrans (vector<double>& f, double alpha, double beta, int n,\n\t       int = 0, const char* = \"message \");\nvoid gauss2(double ao, double alpha, double bo, double beta,\n\t    double& co, double& expo, double& factor, int = 0);\nvoid print_vector(vector<double>& v, const char msg[]);\n\n/*\n     gaussian integral of the softbox potential \n     V  = { (x+boxlength)^2  for x < -boxlength\n          {        0         for -boxlength < x < boxlength\n          { (x-boxlength)^2  for x > boxlength \n\nThis is a Fortran to Cpp translation of our old code from the late 1990ties.\nFortran by Uwe Riss, Robin Santra, and Thomas Sommerfeld\nCpp translation by Thomas Sommerfeld, Nov 2018 T. Sommerfeld\n\nThe integrals of the so-called box-CAP are computed analytically.\nDo not even try to backwards-engineer this, dig out Robin's paper. \n\n@Article{santra99,\nauthor = \"R. Santra and L. S. Cederbaum and H.-D. Meyer\",\njournal = \"Chem. Phys. Lett.\",\nvolume = 303,\nyear =   1999,\npages =  413,\ntitle =  \"Electronic decay of molecular clusters: Non-stationary states computed by standard quantum chemistry methods\"}\n\ngto1 and gto2 define two primitive Cartesian GTOs including their l value,\nsay, px, or dx^2.\nboxlength[3] are the cutoff parameters defined above\nnormalized [0] is a flag 0=unnormalized GTOs, 1=normalized GTOs\nverbose can be increased to create debug information  \n\n*/\n\ndouble integrate_box_cap(Shell shell1, Shell shell2, \nstd::array<size_t,3> l1, std::array<size_t,3> l2, double boxlength[3])\n{\n  double sum = 0;\n\tfor(size_t prim1 =0;prim1<shell1.num_prims;prim1++)\n  {\n    gto gto1 = {shell1.origin,shell1.exps[prim1],l1};\n    for(size_t prim2=0;prim2<shell2.num_prims;prim2++)\n    {\n      gto gto2 = {shell2.origin,shell2.exps[prim2],l2};\n      sum+= shell1.coeffs[prim1] * shell2.coeffs[prim2] * boxcap(gto1,gto2,boxlength,false,0);\n    }\n  }\n  return sum;\n}\n\ndouble boxcap(gto gto1, gto gto2, double boxlength[3],\n\t      int normalized, int verbose) {\n\n  int debug = verbose;\n  \n  double cen[3] = {0, 0, 0};\n  double alpha = gto1.a;\n  double beta  = gto2.a;\n  double d0, delta, fakt;\n  \n  double ovl[3] = {0,0,0};\n  double dip[3] = {0,0,0};\n  for (int k = 0; k < 3; ++k) {\n    int m = gto1.l[k];\n    int n = gto2.l[k];\n    int nm = n+m;\n    double ao = gto1.r[k];\n    double bo = gto2.r[k];\n    gauss2(ao, alpha,  bo, beta, d0, delta, fakt, verbose);    \n    \n    vector<double> g (m+1,0);\n    vector<double> h (n+1,0);\n    g[m] = 1;\n    h[n] = 1;\n    poltrans(g, ao, d0, m, debug, \" g = \");\n    poltrans(h, bo, d0, n, debug, \" h = \");\n    vector<double> f = polmulti(g, m, h, n, debug, \" f = \");\n\n    double cl = cen[k] - d0 - boxlength[k];\n    double cu = cen[k] - d0 + boxlength[k];\n    \n    double temp1 = 0;\n    double temp2 = 0;\n    for (int i = 0; i <= nm; ++i) \n    {\n      temp1 += f[i] * intgauss( delta, i, debug, \"  I = \");\n      temp2 += f[i] * intmod_r2(delta, i, cl, cu);\n    }\n    ovl[k] = fakt * temp1;\n    dip[k] = fakt * temp2;\n  }\n  if (verbose > 1) {\n    cout << \"Ovl: \" << ovl[0] << \", \" <<  ovl[1] << \", \" <<  ovl[2] << endl;\n    cout << \"Dip: \" << dip[0] << \", \" <<  dip[1] << \", \" <<  dip[2] << endl; \n  }\n\n  double cap = dip[0]*ovl[1]*ovl[2] + ovl[0]*dip[1]*ovl[2] + ovl[0]*ovl[1]*dip[2];\n  if (normalized == 0)\n    return cap;\n  else {\n    alpha *= 2;\n    beta *= 2;\n    double ovl[3] = {0, 0, 0};\n    for (int k=0; k < 3; ++k) {\n      int m = 2 * gto1.l[k]; \n      int n = 2 * gto2.l[k];\n      ovl[k] = intgauss(alpha,m) * intgauss(beta,n);\n    }\n    if (verbose > 1)\n      cout << \"<0>: \" << ovl[0] << \", \" <<  ovl[1] << \", \" <<  ovl[2] << endl;\n    return cap / sqrt(ovl[0]*ovl[1]*ovl[2]);\n  }\n}\n\n\n//\n// \n// integrate(x**k * f(x) * exp(-a*x**2), x, -oo, oo)\n//\n// where \n//\n//        (x + cl)**2 if x < cl\n// f(x) =    0        if cl <= x <= cu \n//        (x - cu)**2 if x > cu\n//\n// This integral can be expressed in terms of the incomplete gamma-function.    \n// see:\n//  @Article{santra99,\n//  author = \"R. Santra and L. S. Cederbaum and H.-D. Meyer\",\n//  journal = \"Chem. Phys. Lett.\",\n//  volume = 303,\n//  year =   1999,\n//  pages =  413,\n//  title =  \"Electronic decay of molecular clusters:\n//            Non-stationary states computed by standard quantum chemistry methods\"}\n//\n//\ndouble intmod_r2(double a, int k, double cl, double cu) {\n  int sg = -1;\n  if ((k % 2) == 0)\n    sg = 1;\n  double ql = a*cl*cl;\n  double qu = a*cu*cu;\n  double result = 0;\n  int ifault = 0;\n  for (int i = 0; i < 3; ++i) {\n    int j = k + i;\n    double par = 0.5*(j + 1);\n    int ex = 2 - i;\n    double dl = pow(cl,ex);\n    double du = pow(-cu,ex);\n    double term = tgamma(par)*(sg*dl + du);\n    double norm_factor = tgamma(par);\n    term -= sg*dl*gammad(ql,par,&ifault)*norm_factor*xi(-cl,j);\n    term -=    du*gammad(qu,par,&ifault)*norm_factor*xi( cu,j);\n    //term -= sg*dl*boost::math::tgamma_lower(par,ql)*xi(-cl,j);  func is not normalized w/ boost\n    //term -=    du*boost::math::tgamma_lower(par,qu)*xi( cu,j);  func is not normalized w/ boost\n    term /= pow(a,par);\n    if (i == 1)\n      term *= 2;\n    result += term;\n  }\n  return 0.5*result;\n}\n\n\n//\n//  computes a sign needed in intmod_r2()\n//\nint xi (double z, int i) {\n  if (z >= 0)\n    return 1;\n  else {\n    if ((i%2) == 0)\n      return -1;\n    else\n      return 1;\n  }\n}\n\n\n\n\n//\n//  returns int dx x^n exp(-alpha*x^2)\n//\ndouble intgauss(double alpha, int n, int debug, const char* msg) {\n  double integral = 0.0;\n  if (n%2 == 0) {\n    int k = n/2;\n    double a = pow(alpha,k);\n    integral = gauss_factor[k] * sqrt(PI / alpha) / a;\n  }\n  if (debug > 3)\n    cout << msg << integral << endl;\n  return integral;\n}\n\n\n//\n//   {sum} a_i x^i  *  {sum} b_i x^i  ->  {sum} c_i x^i \n//\nvector<double> polmulti(vector<double>& g, int n, vector<double>& h, int m,\n\t\t\tint verbose, const char msg[]) {\n  vector<double> f (n+m+1,0);\n  for (int i = 0; i <= n; ++i) {\n    for (int j = 0; j <= m; ++j) {\n      f[i+j] += g[i] * h[j];\n    }\n  }\n  if (verbose > 2) {\n    print_vector(f, msg);\n  }\n  return f;\n}\n\n\n//\n// {sum} a_i ( x - a )^i   ->   {sum} b_i ( x - b )^i\n//\nvoid poltrans (vector<double> &f, double alpha, double beta, int n,\n\t       int verbose, const char msg[]) {\n  double diff = beta - alpha;\n  int k = 1;\n  for (int j = 0; j <= n; ++j) {\n    double w = 0;\n    for (int i = n; i >= j; --i) {\n      w = w*diff + f[i];\n      f[i] *= (i-j);\n    }\n    f[j] = w / k;\n    k = (j+1)*k;\n  }\n  if (verbose > 2)\n    print_vector(f, msg);\n}\n\n\nvoid gauss2(double ao, double alpha, double bo, double beta,\n\t    double& co, double& expo, double& factor, int verbose) {\n  expo = alpha + beta;\n  co = (ao*alpha + bo*beta) / expo;\n  factor = alpha * beta * (bo-ao) * (bo-ao) / expo;\n  factor = exp(-factor);\n  if (verbose > 2)\n    cout << \"gs2:\" << co << \"  \" << expo << \"  \"  << factor << endl;\n}\n\n\nvoid print_vector(vector<double> &v, const char msg[]) {\n  int n = static_cast<int>(v.size());\n  cout << msg;\n  for (int i = 0; i < n; ++i) {\n    cout << v[i];\n    if ((i+1)%5 == 0)\n      cout << endl;\n    else\n      cout << \", \";\n  }\n  if (n%5 != 0)\n    cout << endl;\n}\n\n", "meta": {"hexsha": "e26462620e9ba1bb4da652b3d06c3a485ad96f3c", "size": 8917, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "opencap/src/boxcap.cpp", "max_stars_repo_name": "SoubhikM/opencap", "max_stars_repo_head_hexsha": "08706ea07e576c96eed32dc224070201781981b2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "opencap/src/boxcap.cpp", "max_issues_repo_name": "SoubhikM/opencap", "max_issues_repo_head_hexsha": "08706ea07e576c96eed32dc224070201781981b2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "opencap/src/boxcap.cpp", "max_forks_repo_name": "SoubhikM/opencap", "max_forks_repo_head_hexsha": "08706ea07e576c96eed32dc224070201781981b2", "max_forks_repo_licenses": ["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.5801282051, "max_line_length": 120, "alphanum_fraction": 0.5910059437, "num_tokens": 2998, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6757646010190476, "lm_q2_score": 0.5078118642792044, "lm_q1q2_score": 0.3431612818573753}}
{"text": "#ifndef STAN_MATH_PRIM_PROB_SKEW_DOUBLE_EXPONENTIAL_RNG_HPP\n#define STAN_MATH_PRIM_PROB_SKEW_DOUBLE_EXPONENTIAL_RNG_HPP\n\n#include <stan/math/prim/meta.hpp>\n#include <stan/math/prim/err.hpp>\n#include <stan/math/prim/fun/log1m.hpp>\n#include <stan/math/prim/fun/max_size.hpp>\n#include <boost/random/uniform_real_distribution.hpp>\n#include <boost/random/variate_generator.hpp>\n#include <cmath>\n\nnamespace stan {\nnamespace math {\n\n/** \\ingroup prob_dists\n * Return a skew double exponential random variate with the given location\n * scale and skewness using the specified random number generator.\n *\n * mu, sigma and tau can each be a scalar or a one-dimensional container. Any\n * non-scalar inputs must be the same size.\n *\n * @tparam T_loc Type of location parameter\n * @tparam T_scale Type of scale parameter\n * @tparam T_skewness Type of skewness parameter\n * @tparam RNG class of random number generator\n * @param mu (Sequence of) location parameter(s)\n * @param sigma (Sequence of) scale parameter(s)\n * @param tau (Sequence of) skewness parameter(s)\n * @param rng random number generator\n * @return (Sequence of) double exponential random variate(s)\n * @throw std::domain_error if mu is infinite or sigma is nonpositive or tau is\n *  not bound between 0.0 and 1.0\n * @throw std::invalid_argument if non-scalar arguments are of different\n * sizes\n */\ntemplate <typename T_loc, typename T_scale, typename T_skewness, class RNG>\ninline typename VectorBuilder<true, double, T_loc, T_scale, T_skewness>::type\nskew_double_exponential_rng(const T_loc& mu, const T_scale& sigma,\n                            const T_skewness& tau, RNG& rng) {\n  using boost::variate_generator;\n  using boost::random::uniform_real_distribution;\n  using T_mu_ref = ref_type_t<T_loc>;\n  using T_sigma_ref = ref_type_t<T_scale>;\n  using T_tau_ref = ref_type_t<T_skewness>;\n  static const char* function = \"skew_double_exponential_rng\";\n  check_consistent_sizes(function, \"Location parameter\", mu, \"Scale Parameter\",\n                         sigma, \"Skewness Parameter\", tau);\n  T_mu_ref mu_ref = mu;\n  T_sigma_ref sigma_ref = sigma;\n  T_tau_ref tau_ref = tau;\n  check_finite(function, \"Location parameter\", mu_ref);\n  check_positive_finite(function, \"Scale parameter\", sigma_ref);\n  check_bounded(function, \"Skewness parameter\", tau_ref, 0.0, 1.0);\n\n  scalar_seq_view<T_mu_ref> mu_vec(mu_ref);\n  scalar_seq_view<T_sigma_ref> sigma_vec(sigma_ref);\n  scalar_seq_view<T_tau_ref> tau_vec(tau_ref);\n  size_t N = max_size(mu, sigma, tau);\n  VectorBuilder<true, double, T_loc, T_scale, T_skewness> output(N);\n\n  variate_generator<RNG&, uniform_real_distribution<> > z_rng(\n      rng, uniform_real_distribution<>(0.0, 1.0));\n  for (size_t n = 0; n < N; ++n) {\n    double z = z_rng();\n    if (z < tau_vec[n]) {\n      output[n]\n          = log(z / tau_vec[n]) * sigma_vec[n] / (2.0 * (1.0 - tau_vec[n]))\n            + mu_vec[n];\n    } else {\n      output[n] = log((1.0 - z) / (1.0 - tau_vec[n])) * (-sigma_vec[n])\n                      / (2.0 * tau_vec[n])\n                  + mu_vec[n];\n    }\n  }\n\n  return output.data();\n}\n\n}  // namespace math\n}  // namespace stan\n#endif\n", "meta": {"hexsha": "0b3f2fd1e5d18753f09b412c7ff3c1e9a58a333b", "size": 3137, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "stan/math/prim/prob/skew_double_exponential_rng.hpp", "max_stars_repo_name": "LaudateCorpus1/math", "max_stars_repo_head_hexsha": "990a66b3cccd27a5fd48626360bb91093a48278b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "stan/math/prim/prob/skew_double_exponential_rng.hpp", "max_issues_repo_name": "LaudateCorpus1/math", "max_issues_repo_head_hexsha": "990a66b3cccd27a5fd48626360bb91093a48278b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "stan/math/prim/prob/skew_double_exponential_rng.hpp", "max_forks_repo_name": "LaudateCorpus1/math", "max_forks_repo_head_hexsha": "990a66b3cccd27a5fd48626360bb91093a48278b", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.256097561, "max_line_length": 79, "alphanum_fraction": 0.7060886197, "num_tokens": 838, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.665410558746814, "lm_q2_score": 0.5156199157230157, "lm_q1q2_score": 0.343098936222237}}
{"text": "/*  _______________________________________________________________________\n\n    DAKOTA: Design Analysis Kit for Optimization and Terascale Applications\n    Copyright 2014 Sandia Corporation.\n    This software is distributed under the GNU Lesser General Public License.\n    For more information, see the README file in the top Dakota directory.\n    _______________________________________________________________________ */\n\n//- Class:\t NonDGPImpSampling\n//- Description: Implementation code for NonDGPImpSampling class\n//- Owner:       Laura Swiler and Keith Dalbey\n//- Checked by:\n//- Version:\n\n#include \"NonDGPImpSampling.hpp\"\n#include \"dakota_system_defs.hpp\"\n#include \"dakota_data_types.hpp\"\n#include \"dakota_data_io.hpp\"\n#include \"DakotaModel.hpp\"\n#include \"DakotaResponse.hpp\"\n#include \"NonDLHSSampling.hpp\"\n#include \"ProblemDescDB.hpp\"\n#include \"DataFitSurrModel.hpp\"\n#include \"pecos_data_types.hpp\"\n#include \"pecos_stat_util.hpp\"\n#include \"DakotaApproximation.hpp\"\n#include <boost/lexical_cast.hpp>\n\nstatic const char rcsId[]=\"@(#) $Id: NonDGPImpSampling.cpp 7035 2010-10-22 21:45:39Z mseldre $\";\n\n\nnamespace Dakota {\n\n/** This constructor is called for a standard letter-envelope iterator \n    instantiation.  In this case, set_db_list_nodes has been called and \n    probDescDB can be queried for settings from the method specification. */\nNonDGPImpSampling::NonDGPImpSampling(ProblemDescDB& problem_db, Model& model):\n  NonDSampling(problem_db, model)\n{\n  // sampleType default in DataMethod.cpp is SUBMETHOD_DEFAULT (0).\n  // Enforce an LHS default for this method.\n  if (!sampleType)\n    sampleType = SUBMETHOD_LHS;\n\n  samplingVarsMode = ACTIVE_UNIFORM;\n  String sample_reuse, approx_type(\"global_kriging\");/*(\"global_kriging\");*/\n  UShortArray approx_order; // not used by GP/kriging\n  short corr_order = -1, data_order = 1, corr_type = NO_CORRECTION;\n  if (probDescDB.get_bool(\"method.derivative_usage\")) {\n    if (iteratedModel.gradient_type() != \"none\") data_order |= 2;\n    if (iteratedModel.hessian_type()  != \"none\") data_order |= 4;\n  }\n  unsigned short sample_type = SUBMETHOD_DEFAULT;\n  statsFlag = true; //print computed probability levels at end\n  bool vary_pattern = false; // for consistency across outer loop invocations\n  // get point samples file\n  const String& import_pts_file\n    = probDescDB.get_string(\"method.import_build_points_file\");\n  // BMA: This was previously using numSamples = initial_samples from base class\n  numSamples = probDescDB.get_int(\"method.build_samples\");\n  int samples = numSamples;\n  if (!import_pts_file.empty())\n    { samples = 0; sample_reuse = \"all\"; }\n\n  gpBuild.assign_rep(new NonDLHSSampling(iteratedModel, sample_type,\n     samples, randomSeed, rngName, varyPattern, ACTIVE_UNIFORM), false);\n  //distribution 1 which is the distribution that the initial set of samples\n  //used to build the initial GP are drawn from this should \"ALWAYS\" be \n  //uniform in the input of the GP (even if the nominal distribution is not\n  //uniform) because it is a set of samples to build a good GP and nothing\n  //else.  Rho 0 is the nonminal distribution of the input variable\n\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  gpModel.assign_rep(new DataFitSurrModel(gpBuild, iteratedModel,\n    gp_set, approx_type, approx_order, corr_type, corr_order, data_order,\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  vary_pattern = true; // allow seed to run among multiple approx sample sets\n  // need to add to input spec\n  numEmulEval = probDescDB.get_int(\"method.nond.samples_on_emulator\");\n  if (numEmulEval==0)\n    numEmulEval = 10000;\n  construct_lhs(gpEval, gpModel, sample_type, numEmulEval, randomSeed,\n\t\trngName, vary_pattern);\n  if (maxIterations < 0) \n    numPtsAdd = 150;\n  else\n    numPtsAdd = maxIterations;\n\n  //construct sampler to generate one draw from rhoOne distribution, with \n  //seed varying between invocations\n  construct_lhs(sampleRhoOne, iteratedModel, sample_type, 1, randomSeed,\n\t\trngName, vary_pattern); \n}\n\n\nNonDGPImpSampling::~NonDGPImpSampling()\n{ }\n\n\nbool NonDGPImpSampling::resize()\n{\n  bool parent_reinit_comms = NonDSampling::resize();\n\n  Cerr << \"\\nError: Resizing is not yet supported in method \"\n       << method_enum_to_string(methodName) << \".\" << std::endl;\n  abort_handler(METHOD_ERROR);\n\n  return parent_reinit_comms;\n}\n\n\nvoid NonDGPImpSampling::derived_init_communicators(ParLevLIter pl_iter)\n{\n  iteratedModel.init_communicators(pl_iter, maxEvalConcurrency);\n\n  // gpBuild and gpEval use NoDBBaseConstructor, so no need to\n  // manage DB list nodes at this level\n  //gpBuild.init_communicators(pl_iter);\n  gpEval.init_communicators(pl_iter);\n} \n\n\nvoid NonDGPImpSampling::derived_set_communicators(ParLevLIter pl_iter)\n{\n  NonD::derived_set_communicators(pl_iter);\n\n  // gpBuild and gpEval use NoDBBaseConstructor, so no need to\n  // manage DB list nodes at this level\n  //gpBuild.set_communicators(pl_iter);\n  gpEval.set_communicators(pl_iter);\n} \n\n\nvoid NonDGPImpSampling::derived_free_communicators(ParLevLIter pl_iter)\n{\n  gpEval.free_communicators(pl_iter);\n  //gpBuild.free_communicators(pl_iter);\n\n  iteratedModel.free_communicators(pl_iter, maxEvalConcurrency);\n}\n\n\n/** Calculate the failure probabilities for specified probability levels \n    using Gaussian process based importance sampling. */\nvoid NonDGPImpSampling::core_run()\n{\n  numPtsTotal = numSamples + numPtsAdd;\n \n  // Build initial GP model.  This will be built over the initial LHS sample set\n  // defined in the constructor.\n  gpModel.build_approximation();\n  \n  gpCvars.resize(numEmulEval);\n  RealVector temp_cvars;\n  gpVar.resize(numEmulEval);\n  gpMeans.resize(numEmulEval);\n  indicator.resize(numPtsTotal);\n  expIndicator.resize(numEmulEval);\n  rhoDraw.resize(numEmulEval);\n  normConst.resize(numPtsAdd);\n  rhoMix.resize(numPtsTotal);\n  //RealVector rhoEmul0(numEmulEval);\n  //RealVector rhoEmul2(numEmulEval);\n  int num_problem_vars=iteratedModel.acv();\n  RealVector c_upper = iteratedModel.continuous_upper_bounds(), \n             c_lower = iteratedModel.continuous_lower_bounds();\n\n  int i,j,k;\n \n// This piece of code prints out the build points, not the approximation points.\n// const Pecos::SurrogateData& gp_data = gpModel.approximation_data(0);\n//  for (j = 0; j < numSamples; j++) {\n//    Cout << \" Surrogate Vars \" << gp_data.continuous_variables(j) << '\\n';\n//    Cout << \" Surrogate Response \" << gp_data.response_function(j); \n//  }\n\n// We have built the initial GP.  Now we need to go through, per response function\n// and response level and calculate the failure probability. \n// We will need to add error handling:  we will only be calculating \n// results per response level, not probability level or reliability index.\n   \n  size_t resp_fn_count, level_count, iter;\n  RealVector new_X;\n  initialize_level_mappings();\n  ParLevLIter pl_iter = methodPCIter->mi_parallel_level_iterator(miPLIndex);\n\n  for (resp_fn_count=0; resp_fn_count<numFunctions; resp_fn_count++) {\n    size_t num_levels = requestedRespLevels[resp_fn_count].length();\n    const Pecos::SurrogateData& gp_data = gpModel.approximation_data(resp_fn_count);\n    for (level_count=0; level_count<num_levels; level_count++) {\n      Cout << \"Starting calculations for response function \" << resp_fn_count+1 << '\\n';\n      Cout << \"Starting calculations for level  \" << level_count+1 << '\\n';\n      Cout << \"Threshold level is \" << requestedRespLevels[resp_fn_count][level_count] << '\\n';\n      Real z = requestedRespLevels[resp_fn_count][level_count];\n       // Calculate indicator over the true function evaluations\n      double cdfMult = (cdfFlag?1.0:-1.0);\n      for (j = 0; j < numSamples; j++) {\n        indicator(j) = static_cast<double>((z-gp_data.response_function(j))*cdfMult>0.0); \n        if (outputLevel > NORMAL_OUTPUT)\n          Cout << \"indicator(\" << j << \")=\" << indicator(j) << '\\n';\n      }\n      \n      // rho0 is the original PDF, rho1 is the compon importance pdf, rho2 is the \n      // distribution used to generate candidate points for the emulator\n      // For the initial implementation, we assume rho1 is uniform, and \n      // rho0 and rho2 are uniform also with the same distribution.  \n      double rho0const, rho1const, rho2const;\n      rho0const = 1.0;\n      for (i = 0; i < num_problem_vars; i++) \n        rho0const = rho0const/(c_upper[i]-c_lower[i]);\n      rho1const = rho0const;\n      rho2const = rho0const;\n \n       // Here we loop over the number of points added, \n       // where each time we calculate the expected indicator function \n       // and add to the approximation. \n      for (k = 0; k < numPtsAdd; k++) { \n\t// generate new set of emulator samples.\n\t// Note this will have a different seed each time.\n        gpEval.run(pl_iter);\n         // obtain results \n        const RealMatrix&  all_samples = gpEval.all_samples();\n        const IntResponseMap& all_resp = gpEval.all_responses();\n        for (i = 0; i< numEmulEval; i++) {\n          temp_cvars = Teuchos::getCol(Teuchos::View,\n\t    const_cast<RealMatrix&>(all_samples), i);\n          gpCvars[i] = temp_cvars;\n          //Cout << \"input is \" << gpCvars[i] << '\\n';\n\t  // update gpModel currentVariables for use in approx_variances()\n\t  gpModel.continuous_variables(temp_cvars);\n          gpVar[i]\n\t    = gpModel.approximation_variances(gpModel.current_variables());\n          //Cout << \"variance is \" << gpVar[i];\n        }\n\n        IntRespMCIter resp_it = all_resp.begin();\n        for (j=0, resp_it=all_resp.begin(); j<numEmulEval; ++j, ++resp_it) {\n          RealVector temp_resp(numFunctions);\n            for (i=0; i<numFunctions; i++)\n              temp_resp(i) = resp_it->second.function_value(i);\n            gpMeans[j]=temp_resp;\n            //Cout << \"output is \" << gpMeans[j] << '\\n';\n        }\n          \n       // calculate expected indicator function;\n        expIndicator = calcExpIndicator(resp_fn_count,z);\n       // calculate distribution pdfs required to calculate the draw distribution\n       // distribution_pdf(rhoEmul2);\n       // distribution_pdf(rhoEmul0);\n       // FOR NOW, we assume distribution 0 and 2 are the same, \n       // but in general rhoDrawThis = expIndicator * rhoEmul0/rhoEmul2;\n        for (i = 0; i< numEmulEval; i++) \n          rhoDraw(i) = expIndicator(i)*rho0const/rho2const; \n      \t\n       // calculate the normalization constant\n        Cout << \"numEmulEval \" << numEmulEval << '\\n';\n        Cout << \"size exp indicator \" << expIndicator.length() << '\\n';\n\tdouble temp_sum_nc=0.0;\n        normConst(k)=0.0;\n        for (j = 0; j < numEmulEval; j++) {\n\t  temp_sum_nc+=rhoDraw(j);\n        }\n\ttemp_sum_nc/=numEmulEval;\n        normConst(k)=temp_sum_nc;\n        Real temp_norm_const = normConst(k);\n        Cout << \"norm const \" << k << \"=\" << temp_sum_nc << \"=\" << normConst(k) <<  \"\\n\";\n       // calculate the draw distribution\n        rhoDrawThis.resize(0);\n        xDrawThis.resize(0);\n        expIndThis.resize(0);\n        calcRhoDraw();\n          \n        iter = 1;\n        while ((iter<20) && (temp_norm_const*numEmulEval<25)) {\n\t  iter = iter+1;\n          gpEval.run(pl_iter);\n           // obtain results \n          const RealMatrix&  this_samples = gpEval.all_samples();\n          const IntResponseMap& this_resp = gpEval.all_responses();\n          for (i = 0; i< numEmulEval; i++) {\n\t    temp_cvars = Teuchos::getCol(Teuchos::View,\n\t       const_cast<RealMatrix&>(this_samples), i);\n            gpCvars[i] = temp_cvars;\n            //Cout << \"input is \" << gpCvars[i] << '\\n';\n\t    // update gpModel currentVariables for use in approx_variances()\n\t    gpModel.continuous_variables(temp_cvars);\n            gpVar[i]\n\t      = gpModel.approximation_variances(gpModel.current_variables());\n            //Cout << \"variance is \" << gpVar[i];\n           }\n\n          resp_it = this_resp.begin();\n          for (j=0, resp_it=this_resp.begin(); j<numEmulEval; ++j, ++resp_it) {\n            RealVector temp_resp(numFunctions);\n            for (i=0; i<numFunctions; i++)\n              temp_resp(i) = resp_it->second.function_value(i);\n            gpMeans[j]=temp_resp;\n            //Cout << \"output is \" << gpMeans[j] << '\\n';\n          }\n          \n       // calculate expected indicator function;\n          expIndicator = calcExpIndicator(resp_fn_count,z);\n          for (j = 0; j < numEmulEval; j++) \n            rhoDraw(j)=expIndicator(j)*rho0const/rho2const;\n          Real temp_norm_this=0.0;\n          for (j = 0; j < numEmulEval; j++) \n\t    temp_norm_this+=rhoDraw(j);\n          temp_norm_this/=numEmulEval;\n          temp_norm_const = temp_norm_const+temp_norm_this;\n          calcRhoDraw();\n        }     \n\n       // xDrawThis, rhoDrawThis, and expIndThis should be populated now\n        normConst(k)=temp_norm_const/iter;\n        if (outputLevel > NORMAL_OUTPUT) \n          Cout << \"NormConst \" << k << \" =  \" << normConst(k) << '\\n';\n \n        int num_eval_kept = xDrawThis.size();  \n        Real est_prob_hit_failregion; \n \n        if (num_eval_kept==0) {\n\t  normConst(k)=0.0;\n          sampleRhoOne.run(pl_iter);\n         // obtain results \n          const RealMatrix&  rho1_samples = sampleRhoOne.all_samples();\n          // For now, we always only draw one sample\n            new_X = Teuchos::getCol(Teuchos::View,\n\t      const_cast<RealMatrix&>(rho1_samples), 0);\n            Cout << \"Draw from Rho One is \" << new_X << '\\n';\n        }  \n        else \n          new_X = drawNewX(k);\n         \n         // add new_X to the build points and append approximation\n        iteratedModel.continuous_variables(new_X);\n        iteratedModel.evaluate();\n        IntResponsePair resp_truth(iteratedModel.evaluation_id(),\n                                   iteratedModel.current_response());\n        gpModel.append_approximation(iteratedModel.current_variables(), resp_truth, true);\n\tindicator(numSamples+k) = static_cast<double>((z-gp_data.response_function(numSamples+k))*cdfMult>0.0); \n        //if (gp_data.response_function(numSamples+k-1)<z) \n\t//indicator(numSamples+k-1)=1;\n        //else indicator(numSamples+k-1)=0;\n        Cout << \"Done with iteration k \"; \n      }\n      RealVectorArray gp_final_data(numPtsTotal);\n      for (j = 0; j < numPtsTotal; j++) \n        gp_final_data[j]=gp_data.continuous_variables(j);\n      Cout << \"GP final data size \" <<  gp_final_data.size() << '\\n'; \n//\n//This is where we need some re-architecting.  I want to evaluate the GPmodel at a \n//set of pre-defined points.  We will need to use a parameter list study. \n//something like the following\n//Iterator listStudy;\n//The list of points will be the full X data, consisting of the original plus added points\n//We have this stored in the Surrogate data\n//VariablesArray list_points;\n//list_points.resize(numPtsTotal);\n//for (j = 0; j < numSamples; j++) {\n//    list_points[j]=gp_data.continuous_variables(j);\n//}\n//\n//listStudy.assign_rep(new ParamStudy(gpModel,\"LIST\", list_points));\n//\n      rhoOne.resize(numPtsTotal);\n//not sure if I have this correct \n//for now, since we are assuming rho0=rho1=rho2=all uniform, just set rho1 to 1.\n      for (j = 0; j < numPtsTotal; j++) \n        rhoOne(j)=rho1const; //for uniform this should be 1.0/prod(xmax-xmin) across all dimensions... ok now I see this isn't rhoOne it's rhoOne/rhoZero... if rho0=rho1=rho2 this should be ok\n  \n      for (j = 0; j < numPtsTotal; j++)\n        rhoMix(j)=rhoOne(j)*numSamples;\n         \n      for (j = numPtsAdd-1; j>=0; j--){\n        if (normConst(j)==0.0) {\n          for (k = 0; k < numPtsTotal; k++) \n            rhoMix(k)=rhoMix(k)+rhoOne(k);\n        }\n        else {\n          RealVector this_mean;\n          RealVector this_var;\n          RealVector exp_ind_this(numPtsTotal);\n          for (k = 0; k < numPtsTotal; k++){ \n            gpModel.continuous_variables(gp_final_data[k]);\n            gpModel.evaluate();\n            this_mean = gpModel.current_response().function_values();\n            this_var\n\t      = gpModel.approximation_variances(gpModel.current_variables());\n            exp_ind_this(k) = calcExpIndPoint(resp_fn_count,z,this_mean,this_var);\n            if (outputLevel > NORMAL_OUTPUT) \n              Cout << \"exp_ind_final \" << k << \" \" <<  exp_ind_this(k) << '\\n';\n          }\n          for (k = 0; k < numPtsTotal; k++) \n            rhoMix(k)=rhoMix(k)+exp_ind_this(k)*rho0const/normConst(j);\n\t  //the 1.0 here is reall rhoZero/rhoZero (ok for rho0=rho1=rho2)\n          gpModel.pop_approximation(false, true);\n          //gpModel.update_approximation(true);\n          Cout << \"Size of build data set \" << gp_data.points() << '\\n';\n        } \n//Since we need to evaluate the SUCCESSIVE SEQUENCES of GPs built using numSamples-->numPtsTotal\n//it might be most efficient to \"pop\" the data and go backward: \n//listStudy.run(pl_iter);\n//obtain results and expected indicator functions\n//gpModel.pop_approximation();\n//\n      }            \n      if (outputLevel > NORMAL_OUTPUT) {\n        Cout << \"rhoMix \" << rhoMix << '\\n';\n        Cout << \"indicator \" << indicator << '\\n'; \n      }\n      for (j = 0; j < numPtsTotal; j++) {\n\tReal yada=rhoMix(j);\n        rhoMix(j)=yada/numPtsTotal;\n      }\n      Real prob_mix=0.0;\n      for (j = 0; j < numPtsTotal; j++) \n        prob_mix+=rho0const*indicator(j)/rhoMix(j);\n      //the 1.0 here is reall rhoZero/rhoZero (ok for rho0=rho1=rho2)\n      prob_mix/=numPtsTotal;\n      Cout << \"Prob Mix IS \" << prob_mix << '\\n'; \n \n      Real fract_fail_mix = 0.0;\n      for (j = 0; j < numPtsTotal; j++) \n        fract_fail_mix+=indicator(j);\n      fract_fail_mix/=numPtsTotal;\n      Cout << \"Fraction Fail IS \" << fract_fail_mix << '\\n'; \n      finalProb = prob_mix; \n      computedProbLevels[resp_fn_count][level_count]=finalProb;  \n    }\n  }\n}\n\n\nRealVector NonDGPImpSampling::drawNewX(int this_k)\n{\n  int i,j,templength;\n  templength = xDrawThis.size();\n  RealVector binEnds;\n  binEnds.size(templength);\n  Real cum_sum = 0.; \n  Real est_prob_hit_failregion = 0;\n  Real yada2;\n  //Cout << \"templength \" << templength << '\\n'; \n  for (i=0; i<templength; i++) {\n    Real yada=rhoDrawThis(i);\n    rhoDrawThis(i)=yada/normConst(this_k);\n    if (i==0)\n      binEnds(i)=rhoDrawThis(i);\n    else{\n      yada=rhoDrawThis(i);\n      yada2=binEnds(i-1);\n      binEnds(i)=yada+yada2;\n    }\n  }\n  cum_sum = binEnds(templength-1);\n  //Cout << \"Cum Sum\"  << cum_sum << '\\n';\n  //Cout << \"BinEnds \" << binEnds << '\\n';\n  //Cout << \"RhoDrawThis \" << rhoDrawThis << '\\n';\n  for (i=0; i<templength; i++) {\n    yada2=binEnds(i);\n    binEnds(i)=yada2/cum_sum;\n  }\n  //std::srand(randomSeed);\n  double rand_cdf = (double)std::rand()/RAND_MAX;\n  //Cout << \"randcdf \" << rand_cdf << '\\n';\n  bool found_cdf=false; \n  i=0; \n  while ((i<templength) && !found_cdf) {\n    if (binEnds(i) > rand_cdf)\n      found_cdf = true;\n    else \n      i = i+1;\n  }\n  for (j=0; j<templength; j++) {\n    est_prob_hit_failregion+=expIndThis(j)*rhoDrawThis(j)/cum_sum;\n  } \n  Cout << \"Estimated prob of hitting failure region \" << est_prob_hit_failregion << '\\n';\n  return xDrawThis[i];\n}\n\nvoid NonDGPImpSampling::calcRhoDraw()\n{ \n  int i, templength;\n  templength = xDrawThis.size();\n\n  for (i = 0; i<numEmulEval; i++) {\n    if (expIndicator(i)!=0.0) {\n      xDrawThis.resize(templength+1);\n      expIndThis.resize(templength+1);\n      rhoDrawThis.resize(templength+1);\n      xDrawThis[templength]=gpCvars[i];\n      expIndThis(templength)=expIndicator(i);\n      // for now this is OK because rho0const = rho2const, will need to change this\n      rhoDrawThis(templength)=expIndicator(i);\n      templength=templength+1;\n    }\n  }    \n  \n  //for (i = 0; i< templength; i++) {\n  //  Cout << \"xDrawThis  \" << i << xDrawThis[i] << '\\n';\n  //  Cout << \"rhoDrawThis  \"  << rhoDrawThis[i] << '\\n';\n  //}\n}\n\nRealVector NonDGPImpSampling::calcExpIndicator(const int resp_fn_count, const Real respThresh)\n{\n  int i, j;\n  RealVector ei(numEmulEval);\n\n  Real cdf,snv,stdv;\n  for (i = 0; i< numEmulEval; i++) {\n    //Cout << \"GPmean  \" << gpMeans[i][resp_fn_count];\n    //Cout << \"GPvar  \" << gpVar[i][resp_fn_count];\n    snv = (respThresh-gpMeans[i][resp_fn_count])*(cdfFlag?1.0:-1.0);\n    //this conditional sign maps the problem to the case where the mean being\n    //\"below\" the threshold (i.e. snv > 0) indicates \"mostly failure\" and the\n    //mean being \"above\" the threshold (i.e. snv < 0) indicates \"mostly not\n    //failure\" this allows the mapped problem to ALWAYS use the cdf (instead\n    //of complimentary cdf)\n\n    stdv = std::sqrt(gpVar[i][resp_fn_count]); \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      ei(i)=(snv>=0.0)?1.0:0.0;\n      //the mean being exactly at the threshold when variance=0.0 is \n      //considered to indicate failure\n    }\n    else{\n      snv/=stdv;\n      ei(i)= Pecos::NormalRandomVariable::std_cdf(snv);\n      //the expected indicator is the fraction of the mapped problem's cdf\n      //that fails, the simple mapping is at most a change in sign of the\n      //snv and might be the identity mapping (not even a change in sign)\n    }\n\n    //Cout << \"EI \" << ei(i) << \" respThresh= \" << respThresh << \" mu= \" << gpMeans[i][resp_fn_count] << \" stdv= \" << stdv << '\\n';\n  }    \n  return ei;\n}\n\nReal NonDGPImpSampling::calcExpIndPoint(const int resp_fn_count, const Real respThresh, const RealVector this_mean, const RealVector this_var)\n{\n  int i, j;\n  Real ei;\n\n  Real cdf,snv,stdv;\n  //  Cout << \"GPmean  \" << this_mean(resp_fn_count);\n  //  Cout << \"GPvar  \" << this_var(resp_fn_count);\n  snv = (respThresh-this_mean(resp_fn_count))*(cdfFlag?1.0:-1.0);\n    //this conditional sign maps the problem to the case where the mean being\n    //\"below\" the threshold (i.e. snv > 0) indicates \"mostly failure\" and the\n    //mean being \"above\" the threshold (i.e. snv < 0) indicates \"mostly not\n    //failure\" this allows the mapped problem to ALWAYS use the cdf (instead\n    //of complimentary cdf)\n  stdv = std::sqrt(this_var(resp_fn_count)); \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    ei=(snv>=0.0)?1.0:0.0;\n    //the mean being exactly at the threshold when variance=0.0 is \n    //considered to indicate failure\n  }\n  else{\n    snv/=stdv;\n    ei= Pecos::NormalRandomVariable::std_cdf(snv);\n    //the expected indicator is the fraction of the mapped problem's cdf\n    //that fails, the simple mapping is at most a change in sign of the\n    //snv and might be the identity mapping (not even a change in sign)\n  }\n\n  //Cout << \"EI \" << ei << \" respThresh= \" << respThresh << \" mu= \" << this_mean(resp_fn_count) << \" stdv= \" << stdv << '\\n';\n      \n  return ei;\n}\n\nvoid NonDGPImpSampling::print_results(std::ostream& s, short results_state)\n{\n  if (statsFlag) {\n    s << \"\\nStatistics based on the importance sampling calculations:\\n\";\n    print_level_mappings(s);\n  }\n}\n\n} // namespace Dakota\n", "meta": {"hexsha": "4c6f90193faad2f2324b26d56da17b1e9967cc3d", "size": 23205, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/NonDGPImpSampling.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/NonDGPImpSampling.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/NonDGPImpSampling.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.3972835314, "max_line_length": 192, "alphanum_fraction": 0.6594699418, "num_tokens": 6346, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.665410558746814, "lm_q2_score": 0.5156199157230156, "lm_q1q2_score": 0.3430989362222369}}
{"text": "//==============================================================================\n//         Copyright 2003 - 2012   LASMEA UMR 6602 CNRS/Univ. Clermont II\n//         Copyright 2009 - 2012   LRI    UMR 8623 CNRS/Univ Paris Sud XI\n//\n//          Distributed under the Boost Software License, Version 1.0.\n//                 See accompanying file LICENSE.txt or copy at\n//                     http://www.boost.org/LICENSE_1_0.txt\n//==============================================================================\n#ifndef NT2_LINALG_FUNCTIONS_GALLERY_ORTHOG_HPP_INCLUDED\n#define NT2_LINALG_FUNCTIONS_GALLERY_ORTHOG_HPP_INCLUDED\n#include <nt2/linalg/functions/orthog.hpp>\n#include <nt2/include/functions/whereij.hpp>\n#include <nt2/include/functions/sin.hpp>\n#include <nt2/include/functions/cos.hpp>\n#include <nt2/include/functions/sinpi.hpp>\n#include <nt2/include/functions/cospi.hpp>\n#include <nt2/include/functions/ric.hpp>\n#include <nt2/include/functions/cic.hpp>\n#include <nt2/include/functions/cif.hpp>\n#include <nt2/include/functions/rif.hpp>\n#include <nt2/include/functions/tril.hpp>\n#include <nt2/include/functions/from_diag.hpp>\n#include <nt2/include/functions/ones.hpp>\n#include <nt2/include/functions/eye.hpp>\n#include <nt2/include/functions/rec.hpp>\n#include <nt2/include/functions/max.hpp>\n#include <nt2/include/functions/sqrt.hpp>\n#include <nt2/include/constants/two.hpp>\n#include <nt2/include/constants/pi.hpp>\n#include <nt2/include/constants/half.hpp>\n#include <nt2/include/constants/twopi.hpp>\n#include <nt2/include/functions/multiplies.hpp>\n#include <nt2/include/functions/mul_i.hpp>\n#include <nt2/include/functions/exp.hpp>\n#include <nt2/include/functions/divides.hpp>\n#include <nt2/include/functions/is_eqz.hpp>\n#include <nt2/include/functions/is_nez.hpp>\n#include <nt2/include/functions/oneminus.hpp>\n#include <nt2/include/functions/sqrt.hpp>\n#include <nt2/include/functions/horzcat.hpp>\n#include <nt2/include/functions/mtimes.hpp>\n#include <nt2/include/functions/logical_and.hpp>\n#include <boost/mpl/int.hpp>\n#include <boost/simd/include/functor.hpp>\n#include <boost/dispatch/include/functor.hpp>\n\nnamespace nt2\n{\n  namespace details\n  {\n    struct isij0\n    {\n      template < class I, class J> inline\n      typename meta::as_logical<I>::type operator()(const I & i , const J& j) const\n      {\n        return nt2::is_eqz(i*j);\n      }\n    };\n    struct isi0\n    {\n      template < class I, class J> inline\n      typename meta::as_logical<I>::type operator()(const I & i , const J& ) const\n      {\n        return nt2::is_eqz(i);\n      }\n    };\n    struct isdiagpos\n    {\n      template < class I, class J> inline\n      typename meta::as_logical<I>::type operator()(const I & i , const J& j ) const\n      {\n        return nt2::logical_and(nt2::is_nez(i), nt2::eq(i, j));\n      }\n    };\n    template < class A0, class K, class T > struct orthog_return{};\n  }\n#define NT2_ORTHOG(V, K, Body)                                      \\\n  namespace ext                                                     \\\n  {                                                                 \\\n    NT2_FUNCTOR_IMPLEMENTATION( nt2::tag::orthog##K##_, tag::cpu_,  \\\n                                (A0)(T),                            \\\n                                (scalar_<integer_<A0> >)            \\\n                                (target_<scalar_<floating_<T> > > ) \\\n                              )                                     \\\n    {                                                               \\\n      typedef typename T::type t_t;                                 \\\n      BOOST_DISPATCH_RETURNS(2, (A0 const& n,  T const& t),         \\\n                             Body                                   \\\n                            )                                       \\\n        };                                                          \\\n  }                                                                 \\\n  namespace details                                                 \\\n  {                                                                 \\\n    template < class A0, class T >                                  \\\n    struct orthog_return < A0,  boost::mpl::int_<V>, T>             \\\n      {                                                             \\\n        typedef typename nt2::meta::as_<T> Target;                  \\\n        typedef typename nt2::meta::call<nt2::tag::orthog##K##_(A0, \\\n                                               Target)>::type type; \\\n      };                                                            \\\n   }                                                                \\\n  template<class T>                                                 \\\n  typename details::orthog_return<ptrdiff_t,                        \\\n                                  boost::mpl::int_<V>, T>::type     \\\n                    orthog(ptrdiff_t n, const boost::mpl::int_<V>&) \\\n  {                                                                 \\\n    return nt2::orthog##K(n, meta::as_<T>());                       \\\n  }                                                                 \\\n/**/\n\n  NT2_ORTHOG(1, 1, (nt2::sinpi(nt2::rif(n,T())*nt2::cif(n,T())/t_t(n+1))*nt2::sqrt(Two<t_t>()/t_t(n+1))))\n  NT2_ORTHOG(2, 2, (nt2::sinpi(nt2::rif(n,T())*nt2::cif(n,T())*nt2::Two<t_t>()/t_t(2*n+1))*(Two<t_t>()/nt2::sqrt(t_t(2*n+1)))))\n  NT2_ORTHOG(3, 3, (nt2::exp(nt2::mul_i(nt2::ric(n,T())*nt2::cic(n,T())*nt2::Twopi<t_t>()/t_t(n)))/nt2::sqrt(t_t(n))))\n  NT2_ORTHOG(4, 4, (nt2::mtimes(nt2::from_diag(nt2::rec(nt2::sqrt(nt2::cath(t_t(n), _(t_t(1), t_t(n-1)))*_(t_t(1), t_t(n))))),\n                                nt2::whereij(details::isdiagpos(),\n                                             nt2::from_diag(nt2::oneminus(nt2::_(t_t(1), t_t(n)))),\n                                             nt2::whereij(details::isi0(),\n                                                          nt2::ones(n, T()),\n                                                          nt2::tril(nt2::ones(n, T()))\n                                                         )\n                                            )\n                               )\n                   )\n            )\n  NT2_ORTHOG(5, 5,((nt2::cospi(nt2::ric(n,T())*nt2::cic(n,T())*nt2::Two<t_t>()/t_t(n))+\n                    nt2::sinpi(nt2::ric(n,T())*nt2::cic(n,T())*nt2::Two<t_t>()/t_t(n)))/nt2::sqrt(t_t(n))))\n  NT2_ORTHOG(6, 6, (nt2::cospi((nt2::rif(n, T())-Half<t_t>())*(nt2::cif(n, T())-Half<t_t>())/t_t(n))*nt2::sqrt(nt2::Two<t_t>()/t_t(n))))\n  NT2_ORTHOG(7, 7, (nt2::whereij(details::isij0(), nt2::ones(n,T())/nt2::sqrt(t_t(n)),nt2::eye(n,T())-ones(n,T())*(1+rec(sqrt(t_t(n))))/t_t(n-1))))\n  NT2_ORTHOG(-1, m1, (nt2::cospi(nt2::ric(n,T())*nt2::cic(n,T())*nt2::rec(nt2::max(t_t(1), t_t(n-1))))))\n  NT2_ORTHOG(-2, m2, (nt2::cospi(nt2::ric(n,T())*(nt2::cic(n,T())+nt2::Half<t_t>())*nt2::rec(t_t(n)))))\n\n#undef ORTHOG\n\n  template<int K, class T>\n  typename details::orthog_return<ptrdiff_t,  boost::mpl::int_<K>, T>::type\n  orthog(ptrdiff_t n)\n  {\n    return nt2::orthog<T>(n, boost::mpl::int_<K>());\n  }\n\n}\n\n\n#endif\n", "meta": {"hexsha": "6db2aef9caf9f8e952f2a5688b0df18dd557b212", "size": 7081, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/core/linalg/include/nt2/linalg/functions/gallery/orthog.hpp", "max_stars_repo_name": "pbrunet/nt2", "max_stars_repo_head_hexsha": "2aeca0f6a315725b335efd5d9dc95d72e10a7fb7", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "modules/core/linalg/include/nt2/linalg/functions/gallery/orthog.hpp", "max_issues_repo_name": "pbrunet/nt2", "max_issues_repo_head_hexsha": "2aeca0f6a315725b335efd5d9dc95d72e10a7fb7", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "modules/core/linalg/include/nt2/linalg/functions/gallery/orthog.hpp", "max_forks_repo_name": "pbrunet/nt2", "max_forks_repo_head_hexsha": "2aeca0f6a315725b335efd5d9dc95d72e10a7fb7", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 48.8344827586, "max_line_length": 147, "alphanum_fraction": 0.4623640729, "num_tokens": 1773, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.665410558746814, "lm_q2_score": 0.5156199157230156, "lm_q1q2_score": 0.3430989362222369}}
{"text": "/// @file  cmdet.hpp\n/// @brief Declarations for methods based on Cayley-Menger determinants.\n\n#pragma once\n#ifndef OGT_EMBED_CMDET_HPP\n#define OGT_EMBED_CMDET_HPP\n\n#include <ogt/config.hpp>\n#include <Eigen/Dense>\n#include <memory>\n\nnamespace OGT_NAMESPACE {\nnamespace embed {\n\n/// Captures a set of Cayley-Menger reference vertices which can be used to find\n/// pairwise distances between points, or to embed the set.\n///\n/// This method is based on:\n/// [1]\tM. J. Sippl and H. A. Scheraga, \"Cayley-Menger coordinates.,\"\n///     Proceedings of the National Academy of Sciences, Apr. 1986.\nstruct CMReference {\n\n\t/// Construct a concrete instance, given all pairwise squared Euclidean\n\t/// distances between the reference vertices.\n\tstatic std::shared_ptr<CMReference> Create(Eigen::MatrixXd refSqDists);\n\n\t/// Virtual destructor.\n\tvirtual ~CMReference() = default;\n\n\t/// Find the squared Euclidean distance between two points with the given\n\t/// squared Euclidean distances to the reference vertices.\n\tvirtual double sqDist(Eigen::VectorXd v1, Eigen::VectorXd v2) = 0;\n};\n\n} // end namespace embed\n} // end namespace OGT_NAMESPACE\n#endif /* OGT_EMBED_CMDET_HPP */\n", "meta": {"hexsha": "cc5d85c30fd220bb5eec6887ead3cdc9aef234c8", "size": 1165, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/ogt/embed/cmdet.hpp", "max_stars_repo_name": "jesand/lloe", "max_stars_repo_head_hexsha": "66235b16fb8cfbb39f72a289c320e701bde94159", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-08-11T21:31:22.000Z", "max_stars_repo_stars_event_max_datetime": "2019-12-30T09:23:04.000Z", "max_issues_repo_path": "include/ogt/embed/cmdet.hpp", "max_issues_repo_name": "jesand/lloe", "max_issues_repo_head_hexsha": "66235b16fb8cfbb39f72a289c320e701bde94159", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/ogt/embed/cmdet.hpp", "max_forks_repo_name": "jesand/lloe", "max_forks_repo_head_hexsha": "66235b16fb8cfbb39f72a289c320e701bde94159", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-08-11T21:31:33.000Z", "max_forks_repo_forks_event_max_datetime": "2020-08-27T20:57:26.000Z", "avg_line_length": 30.6578947368, "max_line_length": 80, "alphanum_fraction": 0.7450643777, "num_tokens": 283, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.7025300698514778, "lm_q2_score": 0.48828339529583464, "lm_q1q2_score": 0.34303376780449946}}
{"text": "/*\nCopyright 2020 Dennis Rohde\n\nPermission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n*/\n#pragma once\n\n#include <boost/python.hpp>\n#include <boost/python/numpy.hpp>\n\n#include \"types.hpp\"\n#include \"clustering.hpp\"\n#include \"frechet.hpp\"\n\nnamespace np = boost::python::numpy;\nnamespace p = boost::python;\n\nnamespace Coreset {\n    \nclass Onemedian_Coreset {\n\n    std::vector<curve_number_t> coreset;\n    std::vector<distance_t> lambda;\n    const distance_t Lambda = 76;\n    distance_t cost;\n\npublic:\n    Onemedian_Coreset() {}\n    \n    inline Onemedian_Coreset(const curve_size_t ell, const Curves &in, const distance_t epsilon, const double constant = 1) {\n        compute(ell, in, epsilon, constant);\n    }\n    \n    inline void compute(const curve_size_t ell, const Curves &in, const distance_t epsilon, const double eps, const bool round = true, const double constant = 1) {\n        const auto n = in.size();\n        const auto m = in.get_m();\n        auto distances = Clustering::Distance_Matrix(in.size(), in.size());\n        const auto c_approx = Clustering::arya(1, ell, in, distances, false);\n        const auto center = c_approx.centers[0];\n        cost = c_approx.value;\n        if (cost == 0) {\n            std::cerr << \"WARNING: cost is zero, coreset construction not possible - check your input\" << std::endl;\n            return;\n        }\n        std::vector<double> probabilities(n);\n        lambda = std::vector<distance_t>(n);\n        \n        for (curve_number_t i = 0; i < n; ++i) {\n            lambda[i] = 52.0 / n + 24.0 / cost * Frechet::Continuous::distance(in[i], center).value;\n            probabilities[i] = (lambda[i]) / Lambda;\n        }\n        \n        auto prob_gen = Random::Custom_Probability_Generator<double>(probabilities);\n        const std::size_t ssize = std::ceil(constant * 1/epsilon * 1/epsilon * std::log(m));\n        const auto coreset_ind = prob_gen.get(ssize);\n        for (curve_number_t i = 0; i < ssize; ++i) {\n            coreset.push_back(coreset_ind[i]);\n        }\n    }\n    \n    inline np::ndarray get_lambda() const {\n        np::dtype dt = np::dtype::get_builtin<distance_t>();\n        p::list l;\n        np::ndarray result = np::array(l, dt);\n        for (const auto &elem: lambda) {\n            l.append(elem);\n        }\n        result = np::array(l, dt);\n        return result;\n    }\n    \n    inline distance_t get_Lambda() const {\n        return Lambda;\n    }\n    \n    inline np::ndarray get_curves() const {\n        np::dtype dt = np::dtype::get_builtin<curve_number_t>();\n        p::list l;\n        np::ndarray result = np::array(l, dt);\n        for (const auto &elem: coreset) {\n            l.append(elem);\n        }\n        result = np::array(l, dt);\n        return result;\n    }\n    \n    inline distance_t get_cost() const {\n        return cost;\n    }\n\n};\n\n};\n", "meta": {"hexsha": "a1a47c8f79abe620dc7d90cc5b35e121ab8f1c73", "size": 3790, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/coreset.hpp", "max_stars_repo_name": "hairbeRt/Fred", "max_stars_repo_head_hexsha": "ae3770e2ad62f83a7d2070e8e48087d89aa09bfc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/coreset.hpp", "max_issues_repo_name": "hairbeRt/Fred", "max_issues_repo_head_hexsha": "ae3770e2ad62f83a7d2070e8e48087d89aa09bfc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/coreset.hpp", "max_forks_repo_name": "hairbeRt/Fred", "max_forks_repo_head_hexsha": "ae3770e2ad62f83a7d2070e8e48087d89aa09bfc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.6734693878, "max_line_length": 460, "alphanum_fraction": 0.6482849604, "num_tokens": 896, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7025300573952054, "lm_q2_score": 0.48828339529583464, "lm_q1q2_score": 0.3430337617223085}}
{"text": "//#include <Rcpp.h>\n//#include <armadillo>\n#include <RcppArmadillo.h>\n#include <Rmath.h>\n#include <math.h>\n#include <iostream>\n#include <fstream>\n#include <R_ext/Utils.h>\n#include \"MIMOSA.h\"\n//#define DEBUG2\n//#define NDEBUG\n/*\n * 18 parameters\n */\n // [[register]]\nRcppExport SEXP fitMCMC(SEXP _stim, SEXP _unstim, SEXP _alphas, SEXP _alphau, SEXP _q, SEXP _z,SEXP _iter, SEXP _burn, SEXP _thin, SEXP _tune,SEXP _outfile, SEXP _filter, SEXP _upper, SEXP _lower, SEXP _bfilter, SEXP _fast, SEXP _exprate, SEXP _pXi){\n\tBEGIN_RCPP\n\tntune=0;\n\t//TODO add argument to pass the complete list of unstimulated samples.\n\tusing namespace Rcpp;\n\tusing namespace arma;\n\tusing namespace std;\n\tbool fixed = false;\n\n\tRNGScope globalscope;\n\t//\t\t\tprintf(\"%f %f %f %f\\n\",exp(normconstIBeta(15,3000,30,3000)),(normconstMC(30,3000,15,3000)),(exp(normconstIBeta(3000,30,3000,15))),(normconstMC(3000,15,3000,30)));\n\t//\t\t\texit(0);\n\t/*\n\t * Copy R variables to standard vectors\n\t */\n\tRcpp::LogicalVector rfilter(_filter);\n\tstd::vector<bool> filter(rfilter.length(),0);\n\tfilter.resize(rfilter.length());\n\tcopy(rfilter.begin(),rfilter.end(),filter.begin());\n\n\tFILTER = Rcpp::as<bool> (_bfilter);\n\tFAST = Rcpp::as<bool> (_fast);\n\tdouble UPPER = Rcpp::as<double>(_upper);\n\tdouble LOWER = Rcpp::as<double>(_lower);\n\tbool REJECT = false;\n\tEXPRATE = Rcpp::as<double>(_exprate);\n\t//printf(\"exponential prior rate = %f\\n\",EXPRATE);\n\n\tstd::vector< double > alphas = Rcpp::as<std::vector<double> >(_alphas);\n\tstd::vector< double > alphau = Rcpp::as<std::vector<double> \t>(_alphau);\n\tdouble q = Rcpp::as<double>(_q);\n\n\tstd::vector< double > z = Rcpp::as<vector <double> >(_z);\n\tstd::vector< double > stdstim = Rcpp::as < vector < double > > (_stim);\n\tstd::vector< double > stdunstim = Rcpp::as < vector < double > > (_unstim);\n  //double pXi = Rcpp::as<double>(_pXi);\n  NumericVector pXi(_pXi);\n\t/*\n\t * Wrap R variables in Rcpp objects\n\t */\n\tRcpp::NumericMatrix const stim(_stim);\n\tRcpp::NumericMatrix const unstim(_unstim);\n\tRcpp::NumericVector const iter(_iter);\n\tRcpp::NumericVector const burn(_burn);\n\tRcpp::NumericVector const thin(_thin);\n\tRcpp::NumericVector const tune(_tune);\n\n\tstd::string outfile = Rcpp::as<std::string>(_outfile);\n\n\tstd::string outfilep(outfile.data());\n\toutfilep.append(\"P\");\n\n\tRprintf(\"Creating %s\\n\",outfile.data());\n  \n  \n\tFILE* file = fopen(outfile.data(),\"w\");\n\tFILE* fileP = fopen(outfilep.data(),\"w\");\n\tif(file==NULL|fileP==NULL){\n\t\treturn(wrap(\"Can't open file!\"));\n\t}\n\t/*\n\t * Parameters\n\t */\n\tconst double NITERS=iter[0];\n\tconst double BURNIN=burn[0];\n\tconst double THINNING=thin[0];\n\tconst double TUNING=tune[0];\n\tdouble realitcounter=0;\n\n\t/*\n\t * Assert that dimensions match\n\t */\n\tif(alphas.size()!=stim.ncol()){\n     ::Rf_error( \"dimensions don't match\");\n\t}\n\tif(stim.nrow()!=unstim.nrow()){\n     ::Rf_error( \"dimensions don't match\");\n\t}\n\tif(stim.ncol()!=unstim.ncol()){\n     ::Rf_error( \"dimensions don't match\");\n\t}\n\tif(alphas.size()!=alphau.size()){\n     ::Rf_error( \"dimensions don't match\"); \n\t}\n\t/*\n\t * Dimensions of the problem\n\t */\n\tconst int k = stim.ncol();\n\tconst int P = stim.nrow();\n\n\t/*\n\t * Output variables\n\t */\n\tstd::vector<double> ps(P,0),pu(P,0);\n\tstd::vector <double> llnull(P,0);\n\tstd::vector <double> llresp(P,0);\n\tstd::vector <double> llnullNew(P,0);\n\tstd::vector <double> llrespNew(P,0);\n\n\n\tstd::vector <double> stdsum_data_alphas(P*k,0);\n\tstd::vector <double> stdsum_data_alphau(P*k,0);\n\n\tarma::vec asi, aui;\n\t/*\n\t * Armadillo objects will store the simulations from the tuning phase\n\t * so we can easily compute variances and so forth.\n\t */\n\tarma::mat Ms(int(TUNING),alphas.size());\n#ifdef DEBUG2\n\tRprintf(\"init Ms\\n\");\n#endif\n\tarma::mat Mu(int(TUNING),alphau.size());\n#ifdef DEBUG2\n\tRprintf(\"init Mu\\n\");\n#endif\n\n\t/*\n\t * Precompute and preallocate a few things we'll need\n\t */\n\tstd::vector <double> sum_stim_unstim(P*k,0);\n\tstd::transform(stdstim.begin(),stdstim.end(),stdunstim.begin(),sum_stim_unstim.begin(),plus<double>());\n\n\n\tstd::vector<double> newalphas(alphas.size(),0);\n\tnewalphas.resize(alphas.size());\n\tstd::vector<double> newalphau(alphau.size(),0);\n\tnewalphau.resize(alphau.size());\n\n\n\tNumericVector sigmas(alphas.size(),10.0);\n\tNumericVector sigmau(alphau.size(),10.0);\n\n\tarma::vec rateS(alphas.size());\n#ifdef DEBUG2\n\tRprintf(\"init rateS\\n\");\n#endif\n\tarma::vec rateU(alphau.size());\n#ifdef DEBUG2\n\tRprintf(\"init rateU\\n\");\n#endif\n\trateS.fill(RATE);\n\trateU.fill(RATE);\n\tNumericVector accepts(alphas.size(),0.0);\n\tNumericVector acceptu(alphas.size(),0.0);\n\tstd::vector<double> cll(P,0.0);\n\tstd::vector<double> p(P,0.0);\n\tstd::vector<double> cz(P,0.0);\n\tstd::vector<double> prr(NITERS-BURNIN,0.0);\n\n\n\tdouble prior=0,newprior=0;\n\tdouble oldll=0,newll=0;\n\n\n\t/*\n\t * Construct the header string\n\t *\n\t */\n\tstd::stringstream headers(stringstream::in|stringstream::out);\n\tstd::stringstream headersP(stringstream::in|stringstream::out);\n\n\t//write the z's and p's to the second file\n\tfor(int i=0;i<P;i++){\n\t\theadersP<<\"z.\"<<i<<\"\\t\";\n\t}\n\tfor(int i=0;i<P-1;i++){\n\t\theadersP<<\"ps.\"<<i<<\"\\t\"<<\"pu.\"<<i<<\"\\t\";\n\t}\n\theadersP<<\"ps.\"<<P-1<<\"\\t\"<<\"pu.\"<<P-1<<std::endl;\n\n\n\n\tfor(int i=0;i<alphas.size();i++){\n\t\theaders<<\"alphas.\"<<i<<\"\\t\";\n\t}\n\tfor(int i=0;i<alphau.size();i++){\n\t\theaders<<\"alphau.\"<<i<<\"\\t\";\n\t}\n\theaders<<\"q\"<<std::endl;\n\t//counters\n\tint iteration=0,j=0;\n\t/*\n\t * Run the MCMC algorithm\n\t */\n\n\t/*\n\t * Initialize the normalizing constants\n\t */\n\n\n\tfor(iteration = 0; iteration < NITERS; iteration++){\n\t\t//::Rprintf(\"%d \",iteration);\n\t\tfor(j=0;j<k;j++){\n\t\t\t/*\n\t\t\t * prior for the current alphas_j\n\t\t\t */\n\n\t\t\tprior=::Rf_dexp(alphas[j],1.0/EXPRATE,true);\n\t\t\tstd::copy(alphas.begin(),alphas.end(),newalphas.begin());\n\n\t\t\t//current null marginal log likelihood\n\t\t\tloglikenull(sum_stim_unstim,alphau,llnull,stdsum_data_alphau,P,k);\n\n\t\t\t//If alternative is greater compute the ratio of normalizing constants for the alternative marginal log likelihood\n\t\t\tif(FILTER&&k==2&&!FAST){\n\t\t\t\tnormalizingConstant(stdstim,stdunstim,alphas,alphau,llresp,P,k);\n\t\t\t}else{\n\t\t\t\t//otherwise the two sided marginal log likelihood\n\t\t\t\tloglikeresp(stdstim,alphas,stdunstim,alphau,llresp,stdsum_data_alphas,stdsum_data_alphau,P,k);\n\t\t\t}\n\n\t\t\t//compute z1*lnull+z2*lresp+prior\n\t\t\tcompleteLL(z,llnull,llresp,cll,filter,P,k);\n\t\t\t\n\t\t\toldll=std::accumulate(cll.begin(),cll.end(),0.0)+prior;\n\t\t\tif(isfinite(oldll)!=1){\n         ::Rf_error( \"oldll != 1\");\n\t\t\t}\n\n\n\t\t\t//simulate alphas_j\n\t\t\t//try integral values for alpha_s beta_s\n\t\t\tif(FILTER&&k==2&&!FAST){\n\t\t\t\tnewalphas[j]=ceil(alphaProposal(alphas,sigmas[j]*rateS[j],j));\n\t\t\t}else{\n\t\t\t\tnewalphas[j]=alphaProposal(alphas,sigmas[j]*rateS[j],j);\n\t\t\t}\n\t\t\tif(newalphas[j]>0){\n//\t\t\t\tif(FILTER&&k==2&&!FAST){\n//\t\t\t\t\tnewprior=dgeom(newalphas[j],EXPRATE);\n//\t\t\t\t}else{\n\t\t\t\t\tnewprior=::Rf_dexp(newalphas[j],1.0/EXPRATE,true);\n//\t\t\t\t}\n\n\t\t\t\t//don't need to recompute the null marginal log likelihood since it doesn't depend on alphas_j\n\t\t\t\tstd::copy(llnull.begin(),llnull.end(),llnullNew.begin());\n\t\t\t\tif(FILTER&&k==2&&!FAST){\n\t\t\t\t\t//compute one sided marginal log likelihood\n\t\t\t\t\tnormalizingConstant(stdstim,stdunstim,newalphas,alphau,llrespNew,P,k);\n\t\t\t\t}else{\n\t\t\t\t\t//two sided\n\t\t\t\t\tloglikeresp(stdstim,newalphas,stdunstim,alphau,llrespNew,stdsum_data_alphas,stdsum_data_alphau,P,k);\n\t\t\t\t}\n\t\t\t\t//compute z1*lnull+z2*lresp+prior\n\t\t\t\tcompleteLL(z,llnullNew,llrespNew,cll,filter,P,k);\n\t\t\t\tnewll=std::accumulate(cll.begin(),cll.end(),0.0)+newprior;\n\t\t\t}else{\n\t\t\t\tREJECT=true;\n\t\t\t\tnewll=nan(\"0\");\n\t\t\t}\n\n\n\t\t\t//Rprintf(\"newll - oldll = %f isfinite()=%d\\n\",newll-oldll,isfinite(newll-oldll));\n\n\t\t\tif(!REJECT&&newalphas[j]>0&&(::log(Rf_runif(0.0,1.0)) <= (newll-oldll) )&&(!ISNAN(newll-oldll)&&(!ISNAN(newll))&&isfinite(::exp(newll-oldll)))){\n#ifdef NDEBUG\n\t\t\t\tRprintf(\"ACCEPTED alphas_%d %f prob: %f newll %f oldll %f\\n\",j,newalphas[j],::exp(newll-oldll), newll, oldll);\n#endif\n\t\t\t\taccepts[j]=accepts[j]+1;//increment acceptance count\n\t\t\t\talphas[j]=newalphas[j]; //new alphas_j is accepted\n\t\t\t\toldll=newll-newprior; //save the new complete data log likelihood (minus the prior for alphas_j) so we don't recompute it for the next step\n\t\t\t\tstd::copy(llnullNew.begin(),llnullNew.end(),llnull.begin()); //ditto for the null and alternative marginal log likelihood\n\t\t\t\tstd::copy(llrespNew.begin(),llrespNew.end(),llresp.begin());\n\t\t\t}else{\n\t\t\t\toldll=oldll-prior; //reject so just subtract the alpha-specific prior\n#ifdef NDEBUG\n\t\t\t\tRprintf(\"REJECTED alphas_%d %f, deltall: %f newll %f oldll %f\\n\",j,newalphas[j],(newll-oldll),newll, oldll);\n\t\t\t\tREJECT=false;\n#endif\n\t\t\t}\n\t\t\tif(isfinite(oldll)!=1){\n         ::Rf_error( \"oldll != 1\");\n\t\t\t}\n\n\n\t\t\t/*\n\t\t\t * Simulate alphau_j\n\t\t\t */\n\t\t\t//prior for the current alphau_j\n//\t\t\tif(FILTER&&k==2&&!FAST){\n//\t\t\t\tprior=dgeom(alphau[j],EXPRATE);\n//\t\t\t}else{\n\t\t\t\tprior=Rf_dexp(alphau[j],1.0/EXPRATE,true);\n//\t\t\t}\n\t\t\toldll=oldll+prior;\n\n\t\t\t//recompute to see if we still have problems with alpha u beta u estimates\n//\t\t\tloglikenull(stdsum_stim_unstim,stdalphau,stdllnullRes,stdsum_data_alphau,P,k); //new null marginal likelihood.\n//\t\t\tif(FILTER&&k==2&&!FAST){\n//\t\t\t\tnormalizingConstant(stdstim,stdunstim,stdalphas,stdalphau,stdllrespRes,P,k); //new responder marginal LL - one sided\n//\t\t\t}else{\n//\t\t\t\t//two sided\n//\t\t\t\tloglikeresp(stdstim,stdalphas,stdunstim,stdalphau,stdllrespRes,stdsum_data_alpha,stdsum_data_alphau,P,k);\n//\t\t\t}\n//\t\t\tcompleteLL(z,stdllnullRes,stdllrespRes,cll,filter,P,k);\n//\t\t\toldll=std::accumulate(cll.begin(),cll.end(),0.0)+prior;\n\n\n\n\t\t\tif(isfinite(oldll)!=1){\n         ::Rf_error( \"dimensions don't match\");\n\t\t\t}\n\t\t\t//copy the alphau vector to the proposal vector.\n\t\t\tstd::copy(alphau.begin(),alphau.end(),newalphau.begin());//copy the current alpha vector to the new alpha vector prior to drawing a sample\n\n\t\t\t//simulate alphau)j\n\t\t\tif(FILTER&&k==2&&!FAST){\n\t\t\t\tnewalphau[j]=ceil(alphaProposal(alphau,sigmau[j]*rateU[j],j));\n\t\t\t}else{\n\t\t\t\tnewalphau[j]=alphaProposal(alphau,sigmau[j]*rateU[j],j);\n\t\t\t}\n\t\t\tif(newalphau[j]>0){\n\n//\t\t\t\tif(FILTER&&k==2&&!FAST){\n//\t\t\t\t\tnewprior=dgeom(newalphau[j],EXPRATE);\n//\t\t\t\t}else{\n\t\t\t\t\tnewprior=Rf_dexp(newalphau[j],1.0/EXPRATE,true);\n//\t\t\t\t}\n\n\t\t\t\t//compute z1*lnull+z2*lresp+prior\n\t\t\t\tloglikenull(sum_stim_unstim,newalphau,llnullNew,stdsum_data_alphau,P,k); //new null marginal likelihood.\n\t\t\t\tif(FILTER&&k==2&&!FAST){\n\t\t\t\t\tnormalizingConstant(stdstim,stdunstim,alphas,newalphau,llrespNew,P,k); //new responder marginal LL - one sided\n\t\t\t\t}else{\n\t\t\t\t\t//two sided\n\t\t\t\t\tloglikeresp(stdstim,alphas,stdunstim,newalphau,llrespNew,stdsum_data_alphas,stdsum_data_alphau,P,k);\n\t\t\t\t}\n\t\t\t\t//compute z1*lnull+z2*lresp+prior\n\t\t\t\tcompleteLL(z,llnullNew,llrespNew,cll,filter,P,k);\n\t\t\t\tnewll=std::accumulate(cll.begin(),cll.end(),0.0)+newprior;\n\t\t\t}else{\n\t\t\t\tREJECT=true;\n\t\t\t\tnewll=nan(\"0\");\n\t\t\t}\n\n\t\t\t//\tprintf(\"newll - oldll = %f isfinite()=%d\\n\",newll-oldll,isfinite(newll-oldll));\n\t\t\tif(!REJECT&&newalphau[j]>0&&(log(Rf_runif(0.0,1.0)) <= (newll-oldll) )&&(!ISNAN(newll-oldll)&&(!ISNAN(newll))&&isfinite(::exp(newll-oldll)))){\n\t\t\t\t//increment acceptance count for alphauj\n#ifdef NDEBUG\n\t\t\t\tRprintf(\"ACCEPTED alphau_%d %f, prob ratio %f newll %f oldll %f\\n\",j,newalphau[j],::exp(newll-oldll),newll, oldll);\n#endif\n\t\t\t\tacceptu[j]=acceptu[j]+1;\n\t\t\t\talphau[j]=newalphau[j];//new alphau_j is accepted\n\t\t\t\toldll=newll-newprior; //complete data log likelihood (minus the prior)\n\t\t\t\t//marginal null and alternative log likelihoods for the accepted parameter are saved so we don't have to recompute them\n\t\t\t\tstd::copy(llnullNew.begin(),llnullNew.end(),llnull.begin());\n\t\t\t\tstd::copy(llrespNew.begin(),llrespNew.end(),llresp.begin());\n\t\t\t}else{\n\t\t\t\toldll=oldll-prior;\n\t\t\t\tREJECT=false;\n#ifdef NDEBUG\n\t\t\t\tRprintf(\"REJECTED alphau_%d %f, deltall: %f newll %f oldll %f\\n\",j,newalphau[j],(newll-oldll),newll, oldll);\n#endif\n\t\t\t}\n\t\t\t//simulate q (w)\n\t\t\tq=simQ(z,P,k,pXi);\n\t\t\t//simulate z\n\t\t\tsimZ(q,llnull,llresp,z,p,filter,P,k); //overwrites the current z. A running average is stored in cz\n\n\t\t}\n\n\t\t/*\n\t\t * If we haven't fixed the step sizes yet..\n\t\t */\n\t\tif(!fixed){\n\t\t\t/*\n\t\t\t * Tuning phase\n\t\t\t */\n\t\t\t//Fill in the Ms and Mu matrices\n\t\t\tasi = conv_to<arma::vec>::from(alphas);\n#ifdef DEBUG2\n\t\t\tRprintf(\"conv alphas to asi\\n\");\n#endif\n\t\t\taui = conv_to<arma::vec>::from(alphau);\n#ifdef DEBUG2\n\t\t\tRprintf(\"conv alphau to aui\\n\");\n#endif\n//print some dimensions\n#ifdef DEBUG2\n\t\t\tRprintf(\"Ms size is %d rows by %d columns and asi size is %d rows by %d columns\\n\",Ms.n_rows,Ms.n_cols,asi.n_rows,asi.n_cols);\n#endif\n\t\t\tMs.row(iteration%(int)TUNING) = trans(asi);\n#ifdef DEBUG2\n\t\t\tRprintf(\"assign asi to Ms.row\\n\");\n#endif\n\t\t\tMu.row(iteration%(int)TUNING) = trans(aui);\n#ifdef DEBUG2\n\t\t\tRprintf(\"assign aui to Mu.row\\n\");\n#endif\n\t\t\t//Tuning\n\t\t\tif(((iteration+1) % (int)TUNING)==0){\n\t\t\t\tntune=ntune+1;\n\t\t\t\t//Compute the covariances\n\t\t\t\tarma::mat covarianceS = arma::cov(Ms);\n#ifdef DEBUG2\n\t\t\t\tRprintf(\"compute cov Ms\\n\");\n#endif\n\t\t\t\tarma::mat covarianceU = arma::cov(Mu);\n#ifdef DEBUG2\n\t\t\t\tRprintf(\"compute cov Mu\\n\");\n#endif\n\t\t\t\tarma::vec dS = arma::sqrt(covarianceS.diag());\n#ifdef DEBUG2\n\t\t\t\tRprintf(\"sqrt diag S\\n\");\n#endif\n\t\t\t\tarma::vec dU = arma::sqrt(covarianceU.diag());\n#ifdef DEBUG2\n\t\t\t\tRprintf(\"sqrt diag U\\n\");\n#endif\n\t\t\t\t//Weight and assign\n\t\t\t\t//Tweak the acceptance rates\n\t\t\t\taccepts=accepts/TUNING;\n\t\t\t\tacceptu=acceptu/TUNING;\n\n//\t\t\t\tprintf(\"sigmas: \");\n//\t\t\t\tfor(j=0;j<sigmas.length();j++){\n//\t\t\t\t\tprintf(\"%f %f \",sigmas[j],sigmau[j]);\n//\t\t\t\t}\n//\t\t\t\tprintf(\"\\n Acceptance rates:\");\n//\t\t\t\tfor(j = 0; j < accepts.length(); j++){\n//\t\t\t\t\tprintf(\"%f %f \",accepts[j],acceptu[j]);\n//\t\t\t\t}\n//\t\t\t\tprintf(\"\\n\");\n\t\t\t\tRprintf(\"Tuning: %d\\t\",ntune);\n\t\t\t\tif((ntune<=12&&(Rcpp::any(accepts > UPPER).is_true() || Rcpp::any(acceptu > UPPER).is_true() || Rcpp::any(accepts < LOWER).is_true() || Rcpp::any(acceptu < LOWER).is_true()))){\n\t\t\t\t\tfor(j=0;j<accepts.length();j++){\n\t\t\t\t\t\t//stimulated\n\t\t\t\t\t\tif((accepts[j]/DEFAULT_RATE) > 1.1 || (accepts[j]/DEFAULT_RATE )<0.8){\n\t\t\t\t\t\t\trateS[j]=accepts[j]/DEFAULT_RATE;\n\t\t\t\t\t\t}\n\t\t\t\t\t\t//unstimulated\n\t\t\t\t\t\tif((acceptu[j]/DEFAULT_RATE) > 1.1 || (acceptu[j]/DEFAULT_RATE) < 0.8){\n\t\t\t\t\t\t\trateU[j]=acceptu[j]/DEFAULT_RATE;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tfor(j=0;j<sigmas.length();j++){\n\t\t\t\t\t\tsigmas[j] = dS(j);\n\t\t\t\t\t\tsigmau[j] = dU(j);\n\t\t\t\t\t}\n\n\t\t\t\t\tfor(j=0;j<k;j++){\n\t\t\t\t\t\tif(rateS[j]==0){\n\t\t\t\t\t\t\tR_CheckUserInterrupt();\n\t\t\t\t\t\t\trateS[j]=1;\n\t\t\t\t\t\t\taccepts[j]=0;\n\t\t\t\t\t\t\titeration=0;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif(ISNAN(sigmas[j])||sigmas[j]==0){\n\t\t\t\t\t\t\tR_CheckUserInterrupt();\n\t\t\t\t\t\t\tsigmas[j]=1;\n\t\t\t\t\t\t\taccepts[j]=0;\n\t\t\t\t\t\t\titeration=0;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif(rateU[j]==0){\n\t\t\t\t\t\t\tR_CheckUserInterrupt();\n\t\t\t\t\t\t\trateU[j]=1;\n\t\t\t\t\t\t\titeration=0;\n\t\t\t\t\t\t\tacceptu[j]=0;\n\t\t\t\t\t\t}if(ISNAN(sigmau[j])||sigmau[j]==0){\n\t\t\t\t\t\t\tR_CheckUserInterrupt();\n\t\t\t\t\t\t\tsigmau[j]=1;\n\t\t\t\t\t\t\titeration=0;\n\t\t\t\t\t\t\tacceptu[j]=0;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t}else{\n\t\t\t\t\tRprintf(\"Fixed step size\\n\");\n\t\t\t\t\tRprintf(\"sigmas: \");\n\t\t\t\t\tfor(int j=0;j<sigmas.length();j++){\n\t\t\t\t\t\tRprintf(\"%f %f \",sigmas[j],sigmau[j]);\n\t\t\t\t\t}\n\t\t\t\t\tRprintf(\"\\n Acceptance rates:\");\n\t\t\t\t\tfor(int j = 0; j < accepts.length(); j++){\n\t\t\t\t\t\tRprintf(\"%f %f \",accepts[j],acceptu[j]);\n\t\t\t\t\t}\n\t\t\t\t\tRprintf(\"\\n\");\n\t\t\t\t\tfixed=true;\n\t\t\t\t\titeration = 0;\n\t\t\t\t\t//write out the headers for the two data files\n\t\t\t\t\tfprintf(file,\"%s\",headers.str().data());\n\t\t\t\t\tfprintf(fileP,\"%s\",headersP.str().data());\n\t\t\t\t}\n\t\t\t\t//reset the acceptance counts\n\t\t\t\taccepts.fill(0);\n\t\t\t\tacceptu.fill(0);\n\t\t\t}\n\t\t}\n\t\t/*\n\t\t * Running average of z1's after the burn-in\n\t\t */\n\n\t\tif((iteration+1)%10000==0){\n\t\t\tR_CheckUserInterrupt();\n\t\t\tif(iteration==0){\n\t\t\t\tstd::copy(p.begin(),p.end(),cz.begin());\n\t\t\t}\n\t\t\tRprintf(\"--- Done %i iterations ---\\n\",(int)iteration+1);\n\t\t\t//\t\t\tprintf(\"\\n Acceptance rates:\");\n\t\t\t//\t\t\tfor(int j = 0; j < accepts.length(); j++){\n\t\t\t//\t\t\t\tprintf(\"%f %f\",accepts[j],acceptu[j]);\n\t\t\t//\t\t\t}\n\t\t\t//\t\t\tprintf(\"\\n\");\n\t\t}\n\n\t\tif(iteration>=BURNIN&&iteration%(int)THINNING==0&&fixed){\n\t\t\trealitcounter++;\n\t\t\tfor(int j=0;j<p.size();j++){\n\t\t\t\tdouble f = realitcounter/(realitcounter+1.0);\n\t\t\t\tdouble foo = p[j]/realitcounter;\n\t\t\t\tcz[j]=(cz[j]+foo)*f;\n\t\t\t}\n\t\t\t//write chain to file\n\t\t\t//write out the z's\n\t\t\t//when the model is two dimensional..\n\t\t\tif(k==2){\n\t\t\t\t//and the proportions sampled from each model\n\t\t\t\tsampleP(sum_stim_unstim,stdstim,stdunstim,alphas,alphau,z,ps,pu,P,k);\n\t\t\t\tfor(int obs=0;obs<P;obs++){\n\t\t\t\t\tfprintf(fileP,\"%f\\t\", z[obs]);\n\t\t\t\t  // prr[iteration-BURNIN]+=(1-z[obs]);\n\t\t\t\t}\n\t\t\t\tfor(int obs=0;obs<P-1;obs++){\n\t\t\t\t\tfprintf(fileP,\"%f\\t%f\\t\",ps[obs],pu[obs]);\n\t\t\t\t}\n\t\t\t\tfprintf(fileP,\"%f\\t%f\\n\",ps[P-1],pu[P-1]);\n\t\t\t}\n\t\t\tfor(int obs=0;obs<alphas.size();obs++){\n\t\t\t\tfprintf(file,\"%f\\t\", alphas[obs]);\n\t\t\t}\n\t\t\tfor(int obs=0;obs<alphau.size();obs++){\n\t\t\t\tfprintf(file,\"%f\\t\", alphau[obs]);\n\t\t\t}\n\t\t\tfprintf(file,\"%f\\n\",q);\n\t\t\t// std::cout<<\"PRR: \"<<prr[iteration-BURNIN]/P<<std::endl;\n\t\t}\n#ifdef NDEBUG\n\t\tRprintf(\"alphas: %f %f alphau: %f %f\\n\",alphas[0],alphas[1],alphau[0],alphau[1]);\n#endif\n\t}\n\tif(!fixed){\n\t\tRprintf(\"Failed to set step size. Run a longer chain.\\n\");\n\t}\n\n\t/*\n\t * Close the file and return some stuff to R.\n\t */\n\tfflush(file);fflush(fileP);\n\tfclose(file);fclose(fileP);\n\tntune=0;\n\treturn Rcpp::List::create(\n\t\t\tRcpp::Named(\"z\") = cz,\n\t\t\tRcpp::Named(\"stepsizeS\") = sigmas,\n\t\t\tRcpp::Named(\"stepsizeU\") = sigmau);\n\t    // Rcpp::Named(\"prr\") = prr);\n\tEND_RCPP\n}\n\n/*\n * Null component log likelihood\n * data is the data, alpha is the parameters, output is the result, sum_dat_alphau is data+alpha\n */\nvoid loglikenull(const std::vector<double> &data,const std::vector<double>  &alpha,std::vector<double> &output, std::vector<double> &sum_dat_alphau,int P, int k){\n\tint i=0,j=0;\n\tdouble da=0,a=0;\n\ta=lkbeta(alpha);\n\tfor(i=0;i<P;i++){\n\t\tfor(j=0;j<k;j++){\n\t\t\tsum_dat_alphau[j*P+i]=data[j*P+i]+alpha[j];\n\t\t}\n\t\tda=lkbeta(sum_dat_alphau,i,k,P);\n\t\toutput[i]=da-a;\n\t}\n\n}\n/*\n * Responder component log-likelihood\n */\nvoid loglikeresp(const std::vector<double>  &stim, const std::vector<double>  &alphas,const  std::vector<double>  &unstim, const std::vector<double>  &alphau,std::vector<double> &output, std::vector<double> &sum_dat_alphas,std::vector<double> &sum_dat_alphau,int P, int k){\n\tint i=0,j=0;\n\tdouble da,db,a,b;\n\tb=lkbeta(alphau);\n\ta=lkbeta(alphas);\n\tfor(i=0;i<P;i++){\n\t\tfor(j=0;j<k;j++){\n\t\t\tsum_dat_alphas[j*P+i]=stim[j*P+i]+alphas[j];\n\t\t\tsum_dat_alphau[j*P+i]=unstim[j*P+i]+alphau[j];\n\t\t}\n\t\tda=lkbeta(sum_dat_alphas,i,k,P);\n\t\tdb=lkbeta(sum_dat_alphau,i,k,P);\n\t\toutput[i]=da+db-a-b;\n\t}\n}\n\n\n/*\n * K-dimensional Beta function\n */\ninline double lkbeta(const std::vector<double>& alpha,int I,int k,int P){\n\tdouble sum_alpha=0;\n\tdouble sum_log_gamma_alpha=0;\n\tdouble log_gamma_sum_alpha=0;\n\tfor(int j = 0;j<k;j++){\n\t\tsum_alpha=sum_alpha+alpha[I+j*P];\n\t\tsum_log_gamma_alpha = sum_log_gamma_alpha+lgamma(alpha[j*P+I]);\n\t}\n\tlog_gamma_sum_alpha = lgamma(sum_alpha);\n\treturn sum_log_gamma_alpha-log_gamma_sum_alpha;\n}\n\ninline double lkbeta(const std::vector<double> &alpha){\n\tdouble sum_alpha = std::accumulate(alpha.begin(),alpha.end(),0.0);\n\tdouble log_gamma_sum_alpha = lgamma(sum_alpha);\n\tdouble sum_log_gamma_alpha=0;\n\tfor(int i=0;i<alpha.size();i++){\n\t\tsum_log_gamma_alpha=sum_log_gamma_alpha+lgamma(alpha[i]);\n\t}\n\treturn sum_log_gamma_alpha-log_gamma_sum_alpha;\n}\n\n\n/*\n * log-gamma function for use with std::transform\n */\ndouble op_lgamma(double i){\n\treturn lgamma(i);\n}\n\n/*\n * Draw a proposal for the ith component of an alpha vector\n */\ndouble alphaProposal(const std::vector<double> &alpha, double sigma, int i){\n\tdouble na;\n\tna = ::Rf_rnorm(alpha[i],sigma);\n\treturn na;\n}\ndouble alphaDiscreteProposal(const std::vector<double> &alpha, double d, int i){\n\tdouble na;\n\td=round(std::abs(d));\n\tif(d<1){\n    ::Rf_error( \"d is < 1\");\n\t}\n\tna = ::Rf_runif(-d,d);\n\tna=alpha[i]+na;\n\treturn na;\n}\n\n/*\n * Compute the complete data log-likelihood\n * If FILTER is true, we check each index against the value of filter, and set the posterior probability to zero for FILTER_j = true\n */\nvoid completeLL(std::vector<double> &z,std::vector<double> &lnull, std::vector<double> &lresp,std::vector<double> &cll,std::vector<bool> &filter,int P, int k){\n\tint i;\n\tfor(i=0;i< P;i++){\n\t\tif(FAST&filter[i]){\n\t\t\tz[i+P]=0.0;z[i]=1.0;\n\t\t}\n\t\tcll[i] = z[i]*lnull[i]+z[i+P]*(lresp[i]);\n\t}\n}\nvoid simZ(double &q,std::vector<double> &lnull, std::vector<double> &lresp,std::vector<double>& z,std::vector<double> &p,std::vector<bool> &filter,int P, int k){\n\tint i;\n\tdouble lq = ::log(q);\n\tdouble mlq = ::log(1.0-q);\n\tfor(i=0;i < lnull.size(); i++){\n\t\tlnull[i]=lnull[i]+lq;\n\t\tlresp[i]=lresp[i]+mlq;\n\t\tdouble mx=std::max(lnull[i],lresp[i]);\n\t\t//printf(\"null:%f\\talternative: %f\\n\",lnull[i],lresp[i]);\n\t\tif(FAST&filter[i]){\n\t\t\tp[i]=1;\n\t\t}else{\n\t\t\tp[i] = ::exp(lnull[i]-::log(::exp(lnull[i]-mx)+::exp(lresp[i]-mx))-mx);\n\t\t\tz[i] = ::Rf_rbinom(1.0,p[i]);\n\t\t\tz[i+P] = 1.0-z[i];\n\t\t}\n\t}\n}\n//inline double simQ(std::vector<double> &z, int P,int k,double pXi){\ninline double simQ(std::vector<double> &z, int P,int k, NumericVector pXi){\n\tstd::vector<double> ab(2,0);\n\tdouble q;\n\tfor(int j=0;j<2;j++){\n\t\tfor(int i=0;i<P;i++){\n\t\t\tab[j]=ab[j]+z[j*P+i];\n\t\t}\n\t}\n\tq = 1.0-::Rf_rbeta(ab[1]+pXi[0],ab[0]+pXi[1]);\n\treturn q;\n}\n\nvoid normalizingConstant(std::vector<double> &stim,std::vector<double> &unstim,std::vector<double> &alphas,std::vector<double> &alphau,std::vector<double> &llresp, int P,int k){\n\tif(k!=2){\n     ::Rf_error( \"k!=2\");\n\t}\n\tdouble numerator=0,denominator=0,nummc,denommc;\n\tdouble C=1,CC=1;\n\t//If any alphas are <= 0 fill with nan;\n\tstd::vector<double> u(2,0), s(2,0);\n\tint i=0,j=0;\n\tfor(i=0;i<P;i++){\n\t\tfor(j=0;j<2;j++){\n\t\t\ts[j]=stim[i+j*P]+alphas[j];\n\t\t\tu[j]=unstim[i+j*P]+alphau[j];\n\t\t}\n\t\t//alphas[1] is alpha, alphas[0] is beta\n\t\t//data+hyperparameters\n\t\t//Rprintf(\"s1 %f, s0 %f, u1 %f u0 %f\\n\",s[1],s[0],u[1],u[0]);\n\t\t//Rprintf(\"alphas %f, betas %f, alphau %f betau %f\\n\",alphas[1],alphas[0],alphau[1],alphau[0]);\n\n\t\tnumerator=normconstIBeta((double)s[0],(double)s[1],(double)u[0],(double)u[1]);\n\t\t//hyperparameters only\n\t\tdenominator=normconstIBeta((double)alphas[0],(double)alphas[1],(double)alphau[0],(double)alphau[1]);\n\t\t//\t\t\t\t\tnummc = normconstMC((double)s[1],(double)s[0],(double)u[1],(double)u[0]);\n\t\t//\t\t\t\t\tdenommc = normconstMC((double)alphas[1],(double)alphas[0],(double)alphau[1],(double)alphau[0]);\n\t\t//\tRprintf(\"%f/%f\\n\",nummc,denommc);\n\t\t//\tRprintf(\"%f  %f  %f\\n\",log(nummc),log(denommc),log(nummc)-log(denommc));\n\n\n\t\t//Rprintf(\"numerator: %f, denominator %f\\n\",exp(numerator), exp(denominator));\n\t\tCC=numerator-denominator;\n\t\t//printf(\"alphas %f betas %f alphau %f betau %f\\n\",alphas[1], alphas[0], alphau[1],alphau[0]);\n\n\t\t//\t\tC=log(nummc)-log(denommc);\n\t\t//printf(\"%d.\\t%f\\t%f\\n\",i,nummc,denommc);\n\t\t//\tprintf(\"C: %f CC: %f  diff: %f\\n\",C,CC, C-CC);\n\t\t//double K=lgamma((double)s[1])+lgamma((double)s[0])-lgamma(s[1]+s[0])+lgamma((double)u[1])+lgamma((double)u[0])-lgamma(u[1]+u[0])-lgamma((double)alphas[1])-lgamma((double)alphas[0])+lgamma(alphas[1]+alphas[0])-lgamma((double)alphau[1])-lgamma((double)alphau[0])+lgamma(alphau[1]+alphau[0]);\n\t\tdouble K = ::Rf_lbeta((double) s[1],(double) s[0])+::Rf_lbeta((double) u[1], (double) u[0])-::Rf_lbeta((double) alphas[1],(double)alphas[0])-::Rf_lbeta((double)alphau[1],(double)alphau[0]);\n\t\tif(ISNAN(CC)){\n\t\t\t//\t\t\tprintf(\"s0: %f s1: %f u0: %f u1: %f as0: %f as1: %f au0: %f au1: %f \\n\",s[0],s[1],u[0],u[1],alphas[0],alphas[1],alphau[0],alphau[1]);\n\t\t\t//\t\t\tprintf(\"numerator: %f  denominator %f  C: %f\\n\",numerator,denominator,numerator-denominator);\n\t\t\t//\t\t\tprintf(\"log(1-exp(C))=%f\\n\",log(1-exp(numerator-denominator)));\n\t\t\tnummc = (normconstMC((double)s[1],(double)s[0],(double)u[1],(double)u[0]));\n\t\t\tdenommc = (normconstMC((double)alphas[1],(double)alphas[0],(double)alphau[1],(double)alphau[0]));\n\t\t\tC=log(nummc)-log(denommc);\n\t\t\tCC=C;\n\t\t}\n\t\t//\t\tprintf(\"mc: %f acpprox: %f difference %f\\n\",C+K,K+CC,C-CC);\n\t\t//Rprintf(\"C:%f\\n\",exp(CC));\n\t\t//Rprintf(\"ll:%f\\n\\n\",K+CC);\n\n\t\tllresp[i]=K+CC;\n\t\t//printf(\"%d.\\t%f\\n\",i,llresp[i]);\n\t}\n}\n\ndouble normconstMC(double as, double bs, double au, double bu){\n\tdouble res;\n\tNumericVector r = rbeta(1000,au,bu);\n\tr=pbeta(r,as,bs,false,false);\n\tres = std::accumulate(r.begin(),r.end(),0.0)/r.length();\n\treturn res;\n}\n\n//estimate_logZus_int<-function(alpha.u,beta.u,alpha.s,beta.s)\n//{\n//  if(round(beta.u)!=beta.u) # Test if it's an integer\n//  {\n//    # Compute for integer values around the true value\n//    betaU<-beta.u\n//    beta.u<-floor(betaU)\n//    j<-alpha.u:(alpha.u+beta.u-1)\n//    K<- -lbeta(alpha.s,beta.s)+lfactorial(alpha.u+beta.u-1)+lbeta(j+alpha.s,alpha.u+beta.u-1-j+beta.s)-lfactorial(j)-lfactorial(alpha.u+beta.u-1-j)\n//    I1<-sum(exp(K))\n//\n//    beta.u<-ceiling(betaU)\n//    j<-alpha.u:(alpha.u+beta.u-1)\n//    K<- -lbeta(alpha.s,beta.s)+lfactorial(alpha.u+beta.u-1)+lbeta(j+alpha.s,alpha.u+beta.u-1-j+beta.s)-lfactorial(j)-lfactorial(alpha.u+beta.u-1-j)\n//    I2<-sum(exp(K))\n//\n//    # Interpolation\n//    I<-(ceiling(betaU)-betaU)*I1+(betaU-floor(betaU))*I2\n//  }\n//  else\n//  {\n//  j<-alpha.u:(alpha.u+beta.u-1)\n//  K<- -lbeta(alpha.s,beta.s)+lfactorial(alpha.u+beta.u-1)+lbeta(j+alpha.s,alpha.u+beta.u-1-j+beta.s)-lfactorial(j)-lfactorial(alpha.u+beta.u-1-j)\n//  I<-sum(exp(K))\n//  }\n//  return(I)\n//}\n\n\ndouble normconstIBeta(double au, double bu, double as, double bs){\n\tdouble alphau = round(au);\n\tdouble betaU = round(bu);\n\tdouble alphas = as;\n\tdouble betas = bs;\n\tdouble mx;\n\tstd::vector<double> upper((int)betaU,0.0);\n\tdouble sum=0;\n\tdouble K=-Rf_lbeta(alphas,betas)+lgamma(alphau+betaU);\n\t//printf(\"summation length: %d\\n\",betaU);\n\tfor(int j=alphau;j<=alphau+betaU-1;j++){\n\t\tupper[j-alphau]=Rf_lbeta(j+alphas,alphau+betaU-1-j+betas)-lgamma(j+1)-lgamma(alphau+betaU-j)+K;\n\t}\n\tstd::vector<double>::iterator where=std::max_element(upper.begin(),upper.end());\n\tmx = *where;\n\tfor(int i=0;i<upper.size();i++){\n\t\tsum=sum+::exp(upper[i]-mx);\n\t}\n\tsum=log(sum)+mx;\n\treturn sum;\n}\n//double normconstIBeta(double as, double bs, double au, double bu){\n//\tdouble alphas = as;\n//\tdouble betas = bs;\n//\tdouble alphau = (double)ceil(au);\n//\tdouble betau = (double)ceil(bu);\n//\t//moved the test for negative proposal outside to the main loop\n//\t//\tif(alphas<=0||betas<=0||alphau<=0||betau<=0){\n//\t//\t\treturn 0.0/0.0; //if any parameters are negative return nan.\n//\t//\t}\n//\tdouble sum=0,mx=0;\n//\tdouble upper = (double) (alphau+betau);\n//\tstd::vector<double> res((int)betau,0.0);\n//\t//\tprintf(\"as=%f bs=%f au=%f bu=%f\\n\",as,bs,au,bu);\n//\t//\tprintf(\"INTS: as=%f bs=%f au=%f bu=%f\\n\",alphas,betas,alphau,betau);\n//\t//\tprintf(\"upper: %d, alphau: %d size: %d\\n\",upper, alphau,res.size());\n//\tdouble K = -::Rf_lbeta(alphas,betas)+Rf_lgammafn(alphau+betau)-Rf_lgammafn(alphas+betas+alphau+betau-1);\n//#ifdef FOO\n//\tprintf(\"upper=%f\\n\",upper);\n//\tprintf(\"K=%f\\n\",K);\n//\tprintf(\"-::Rf_lbeta(alphas,betas)=%f\\n\",-::Rf_lbeta(alphas,betas));\n//\tprintf(\"Rf_lgammafn(alphau+betau)=%f\\n\",Rf_lgammafn(alphau+betau));\n//\tprintf(\"-Rf_lgammafn(alphas+betas+alphau-1)=%f\\n\",-Rf_lgammafn(alphas+betas+alphau-1));\n//#endif\n//\tfor(int j = (int)alphau;j<=((int)upper-1);j++){\n//#ifdef FOO\n//\t\tprintf(\"j=%d\\n\",j);\n//\t\tprintf(\"Rf_lgammafn(alphas+j)=%f\\n\",Rf_lgammafn(alphas+j));\n//\t\tprintf(\"Rf_lgammafn(alphau+betau+betas-1)=%f\\n\",Rf_lgammafn(alphau+betau+betas-j-1));\n//\t\tprintf(\"-Rf_lgammafn(j+1)=%f\\n\",-Rf_lgammafn(j+1));\n//\t\tprintf(\"-Rf_lgammafn(alphau+betau-j)=%f\\n\",-Rf_lgammafn(alphau+betau-j));\n//\t\tprintf(\"sm = %f\\n\",K+Rf_lgammafn(alphas+j)+Rf_lgammafn(alphau+betau+betas-j-1)-Rf_lgammafn(j+1)-Rf_lgammafn(alphau+betau-j));\n//#endif\n//\t\tres[j-(int)alphau]=K+Rf_lgammafn(alphas+j)+Rf_lgammafn(alphau+betau+betas-j-1)-Rf_lgammafn(j+1)-Rf_lgammafn(alphau+betau-j);\n//\t}\n//\n//\t//todo normalized sum of exponentials\n//\tstd::vector<double>::iterator where=std::max_element(res.begin(),res.end());\n//\tmx = *where;\n//\tfor(int i=0;i<res.size();i++){\n//\t\tsum=sum+::exp(res[i]-mx);\n//\t}\n//\tsum=log(sum)+mx;\n//\t//printf(\"%f \\n\",sum);\n//\treturn(sum);\n//}\n\n\n//samples P's for the 2-d case only.\nvoid sampleP(std::vector<double>& sumdata,std::vector<double>& stim,std::vector<double>& unstim,std::vector<double>& alphas,std::vector<double>& alphau,std::vector<double>& z, std::vector<double> &ps, std::vector<double> &pu, int P,int k){\n\tfor(int i=0;i<P;i++){\n\t\tif(z[i+P]==0){\n\t\t\t//sample from the null model\n\t\t\tps[i]=Rf_rbeta(sumdata[i+1*P]+alphas[1]+alphau[1],sumdata[i+0*P]+alphas[0]+alphau[0]);\n\t\t\tpu[i]=ps[i];\n\t\t}else{\n\t\t\t//otherwise sample from the responder model\n\t\t\tps[i]=Rf_rbeta(stim[i+1*P]+alphas[1],stim[i+0*P]+alphas[0]);\n\t\t\tpu[i]=Rf_rbeta(unstim[i+1*P]+alphau[1],unstim[i+0*P]+alphau[0]);\n\t\t}\n\t}\n}\n\ndouble nc(double as, double bs, double au,double bu,double B){\n\tdouble K,mx,sm=0;\n\tstd::vector<double> s(B+1,0);\n\tK=::Rf_lbeta(au+as,bu+bs)-::log(au);\n\ts[0]=K;\n\tfor(int i=0;i<(s.size()-1);i++){\n\t\ts[i+1]=(Rf_lbeta(au+1,i+1)+Rf_lbeta(au+as+i+1,bu+bs)-Rf_lbeta(au+bu,i+1)-log(au));\n\t}\n\tstd::vector<double>::iterator where=std::max_element(s.begin(),s.end());\n\tmx=*where;\n\tfor(int i=0;i<s.size();i++){\n\t\ts[i]=::exp(s[i]-mx);\n\t\tsm=sm+s[i];\n\t}\n\tsm=log(sm)+mx;\n\treturn(sm);\n}\n\ndouble dgeom(int k,double p){\n\tif(k<1){\n   ::Rf_error( \"k<1\");\n\t}\n\tif(p<0||p>1){\n   ::Rf_error( \"p is not between 0 and 1\");\n\t}\n\tdouble olp=log(1-p);\n\tdouble lp=log(p);\n\tdouble res=olp*(k-1)+lp;\n\treturn res;\n}\n", "meta": {"hexsha": "b757ed59118ea7937deab678f22967ec1de2e4f8", "size": 29092, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/MCMC.cpp", "max_stars_repo_name": "MiguelRodo/MIMOSA", "max_stars_repo_head_hexsha": "45b5147478b1ccc9e750483a526e53d6328b20a9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2015-08-20T15:55:27.000Z", "max_stars_repo_stars_event_max_datetime": "2019-07-14T19:45:16.000Z", "max_issues_repo_path": "src/MCMC.cpp", "max_issues_repo_name": "MiguelRodo/MIMOSA", "max_issues_repo_head_hexsha": "45b5147478b1ccc9e750483a526e53d6328b20a9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2015-09-03T21:25:20.000Z", "max_issues_repo_issues_event_max_datetime": "2020-07-08T22:02:38.000Z", "max_forks_repo_path": "src/MCMC.cpp", "max_forks_repo_name": "MiguelRodo/MIMOSA", "max_forks_repo_head_hexsha": "45b5147478b1ccc9e750483a526e53d6328b20a9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2017-02-17T23:09:05.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-01T05:41:09.000Z", "avg_line_length": 31.8641840088, "max_line_length": 293, "alphanum_fraction": 0.6398322563, "num_tokens": 10061, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.640635868562172, "lm_q2_score": 0.5350984286266115, "lm_q1q2_score": 0.34280324658946265}}
{"text": "﻿#include <step_50.h>\n#include <deal.II/grid/grid_tools.h>\n#include<unordered_set>\n\nusing namespace dealii;\nusing namespace Step50;\n\nParameterReader::ParameterReader(ParameterHandler &paramhandler)\n  :\n  prm(paramhandler)\n{}\n\nvoid ParameterReader::declare_parameters()\n{\n  prm.enter_subsection(\"Geometry\");\n  {\n    prm.declare_entry(\"Number of global refinement\",\"2\",Patterns::Integer(),\n                      \"The uniform global mesh refinement on the Domain in the power of 4\");\n\n    prm.declare_entry(\"Domain limit left\",\"-1\",Patterns::Double(),\n                      \"Left limit of domain\");\n\n    prm.declare_entry(\"Domain limit right\",\"1\",Patterns::Double(),\n                      \"Right limit of domain\");\n\n    prm.declare_entry(\"Mesh size\",\"0.25\", Patterns::Double(),\n                      \"Mesh size for initial domain\");\n\n    prm.declare_entry(\"Vacuum repetitions\",\"1\", Patterns::Integer(),\n                      \"Number of repetitions for vacuum on each side in terms of 2 * Mesh size\");\n  }\n  prm.leave_subsection();\n\n\n  prm.enter_subsection(\"Problem Selection\");\n  {\n    prm.declare_entry (\"Problem\",\"Step16\",Patterns::Selection(\"Step16 | GaussianCharges\"),\n                       \"Problem definition for RHS Function\");\n\n    prm.declare_entry (\"Dimension\", \"2\", Patterns::Integer(), \"Problem space dimension\");\n\n    prm.declare_entry (\"Boundary conditions selection\", \"Inhomogeneous\",\n                       Patterns::Selection (\"Homogeneous | Inhomogeneous | Exact\"),\n                       \"Selection between Homogeneous, Inhomogeneous or Exact dirichlet boundary condtions\");\n  }\n  prm.leave_subsection();\n\n  prm.enter_subsection(\"Misc\");\n  {\n    prm.declare_entry (\"Number of Adaptive Refinement\",\"2\",Patterns::Integer(),\n                       \"Number of Adaptive refinement cycles to be done\");\n\n    prm.declare_entry (\"smoothing length\", \"0.5\", Patterns::Double(),\n                       \"The smoothing length parameter for each Gaussian atom\");\n\n    prm.declare_entry (\"Nonzero Density radius parameter around each charge\",\"3\",Patterns::Double(),\n                       \"Set the parameter to localize the density around each charge where it is nonzero\");\n\n    prm.declare_entry (\"Output and calculation of Analytical solution\", \"false\", Patterns::Bool (),\n                       \"Set flag for whether to calculate and output the analytical solution\");\n\n    prm.declare_entry (\"Output of RHS field\", \"false\", Patterns::Bool (),\n                       \"Set flag for whether to output the RHS field\");\n\n    prm.declare_entry (\"Output of support of each atom\", \"false\", Patterns::Bool (),\n                       \"Set flag for whether to output the support of each atom\");\n\n    prm.declare_entry (\"Flag for RHS evaluation optimization\", \"false\", Patterns::Bool(),\n                       \"Set flag for whether to evaluate the RHS field with local optimization\");\n\n    prm.declare_entry (\"Quadrature points for RHS function\", \"1\", Patterns::Integer (),\n                       \"Number of quadrature points for RHS function (total points = degree + these points)\");\n\n    prm.declare_entry (\"Output time summary table\", \"true\", Patterns::Bool (),\n                       \"Set flag for whether to output the time summary\");\n\n  }\n  prm.leave_subsection();\n\n  prm.declare_entry(\"Polynomial degree\", \"1\", Patterns::Integer(),\n                    \"Polynomial degree of finite elements\");\n\n  prm.enter_subsection(\"Solver input data\");\n  {\n    prm.declare_entry (\"Preconditioner\",\"GMG\",Patterns::Selection(\"GMG | Jacobi\"),\n                       \"Preconditioner type to be applied to the system matrix\");\n  }\n  prm.leave_subsection();\n\n  prm.enter_subsection(\"Lammps data\");\n  {\n    prm.declare_entry (\"Lammps input file\",\"atom_8.data\",Patterns::Anything(),\n                       \"Lammps input file with atoms, charges and positions\");\n  }\n  prm.leave_subsection();\n}\n\nvoid ParameterReader::read_parameters(const std::string &parameter_file)\n{\n  prm.parse_input(parameter_file);\n}\n\n\ntemplate <int dim>\nLaplaceProblem<dim>::LaplaceProblem (const unsigned int degree , ParameterHandler &param,\n                                     const std::string &Problemtype, const std::string &PreconditionerType, const std::string &LammpsInputFile,\n                                     const std::string &Boundary_conditions, const double &domain_size_left, const double &domain_size_right,\n                                     const double &mesh_size_h, const unsigned int &repetitions_for_vacuum,\n                                     const unsigned int &number_of_global_refinement,\n                                     const unsigned int &number_of_adaptive_refinement_cycles,\n                                     const double &r_c, const double &nonzero_density_radius_parameter, const bool &flag_rhs_assembly,\n                                     const bool &flag_analytical_solution, const bool &flag_rhs_field, const bool &flag_atoms_support,\n                                     const bool &flag_output_time, const unsigned int &quadrature_degree_rhs)\n  :\n  pcout (std::cout,\n        (Utilities::MPI::this_mpi_process(MPI_COMM_WORLD)\n         == 0)),\n  computing_timer(MPI_COMM_WORLD, pcout, TimerOutput::never,\n                 TimerOutput::wall_times),\n  triangulation (MPI_COMM_WORLD,Triangulation<dim>::\n                limit_level_difference_at_vertices,\n                parallel::distributed::Triangulation<dim>::construct_multigrid_hierarchy),\n  fe (degree),\n  mg_dof_handler (triangulation),\n  degree(degree),\n  prm(param),\n  number_of_global_refinement(number_of_global_refinement),\n  number_of_adaptive_refinement_cycles(number_of_adaptive_refinement_cycles),\n  domain_size_left(domain_size_left),\n  domain_size_right(domain_size_right),\n  mesh_size_h(mesh_size_h),\n  repetitions_for_vacuum(repetitions_for_vacuum),\n  Problemtype(Problemtype),\n  PreconditionerType(PreconditionerType),\n  LammpsInputFilename(LammpsInputFile),\n  Boundary_conditions(Boundary_conditions),\n  flag_analytical_solution (flag_analytical_solution),\n  flag_rhs_field (flag_rhs_field),\n  flag_atoms_support (flag_atoms_support),\n  flag_rhs_assembly(flag_rhs_assembly),\n  flag_output_time (flag_output_time),\n  r_c(r_c),\n  nonzero_density_radius_parameter(nonzero_density_radius_parameter),\n  quadrature_degree_rhs(quadrature_degree_rhs),\n  quadrature_formula_laplace(degree+1),\n  quadrature_formula_rhs(degree+quadrature_degree_rhs)\n{\n  pcout<<\"Problem type is:   \" << Problemtype<<std::endl;\n  pcout<<\"Preconditioner :    \" << PreconditionerType<<std::endl;\n  if (flag_rhs_assembly)\n    pcout<<\"Rhs assembly optimization ENABLED\"<<std::endl;\n  else\n    pcout<<\"Without rhs assembly optimization\"<<std::endl;\n\n  if (Problemtype == \"Step16\")\n    {\n      rhs_func   = std::make_shared<Step16::RightHandSide<dim>>();\n      coeff_func = std::make_shared<Step16::Coefficient<dim>>();\n    }\n  if (Problemtype == \"GaussianCharges\")\n    {\n      rhs_func   = std::make_shared<GaussianCharges::RightHandSide<dim>>(r_c);\n      coeff_func = std::make_shared<GaussianCharges::Coefficient<dim>>();\n      exact_solution = dealii::std_cxx14::make_unique<GaussianCharges::Analytical_Solution<dim>>(r_c,\n                       atom_positions,\n                       charges);\n    }\n}\n\ntemplate <int dim>\nLaplaceProblem<dim>::~LaplaceProblem ()\n{\n  triangulation.clear();\n  mg_dof_handler.clear();\n  if (flag_rhs_assembly)\n    charges_list_for_each_cell.clear();\n  density_values_for_each_cell.clear();\n}\n\n\ntemplate <int dim>\nvoid LaplaceProblem<dim>::read_lammps_input_file(const std::string &filename)\n{\n  TimerOutput::Scope t(computing_timer, \"Read LAMMPS input file\");\n  std::ifstream file(filename);\n  unsigned int count = 0;\n  std::string input;\n\n  double a = 0.0, b = 0.0;\n\n  Point<dim> p;\n\n\n\n  if (dim == 3)\n    {\n\n      if (file.is_open())\n        {\n          lammpsinput = 1;\n          while (!file.eof())\n            {\n              if (count == 2)\n                {\n                  file >> number_of_atoms;\n                  pcout<< \"Number of atoms: \" << number_of_atoms<< std::endl;\n                  atom_types.resize(number_of_atoms);\n                  charges.resize(number_of_atoms);\n                  atom_positions.resize(number_of_atoms);\n                }\n              else if (count == 35)\n                {\n                  for (unsigned int i = 0; i < number_of_atoms; ++i)\n                    {\n                      file >> a ;\n                      file >> b;\n                      file >> atom_types[i];\n                      file >> charges[i];\n                      file >> p(0);\n                      file >> p(1);\n                      file >> p(2); //For 2d test case comment\n//      file>>input;\n\n                      atom_positions[i] = p;\n\n                      /*\n                      const Point<dim> test1 = atom_positions[i];\n                      std::cout << test1 <<std::endl;\n\n                      std::cout<< \"atom types: \"<< atom_types[i]<< \"  \"<<\n                                  \"charges: \"<<charges[i]<< \"  \"<<\n                                  \"atom pos: \"<<p<<std::endl;\n                      */\n\n                    }\n                }\n              else\n                {\n                  file >> input;\n                  //std::cout<< input << \"  \"<< count<<std::endl;\n                }\n              count++;\n            }\n        }\n      else\n        {\n          lammpsinput = 0;\n          pcout<<\"Unable to open the file.\"<< std::endl;\n        }\n      file.close();\n    }\n  else\n    {\n      lammpsinput = 0;\n      pcout<< \"\\nReading of Lammps input file implemented for 3D only\\n\" <<std::endl;\n    }\n\n}\n\ntemplate <int dim>\nvoid LaplaceProblem<dim>::rhs_assembly_optimization()\n{\n  TimerOutput::Scope t(computing_timer, \"RHS assembly optimization\");\n  typename DoFHandler<dim>::active_cell_iterator\n  cell = mg_dof_handler.begin_active(),\n  endc = mg_dof_handler.end();\n\n  for (; cell!= endc; ++cell)\n    if (cell->is_locally_owned())\n      {\n        std::set<unsigned int> atom_indices;\n\n        for (unsigned int i = 0; i < number_of_atoms; ++i)\n          {\n            for (unsigned int vertex_number = 0; vertex_number < GeometryInfo<dim>::vertices_per_cell; ++vertex_number)\n              {\n                const Point<dim> &Xi = this->atom_positions[i];\n                const double distance_from_vertex_to_atom = Xi.distance(cell->vertex(vertex_number));\n                if ( distance_from_vertex_to_atom < nonzero_density_radius_parameter * r_c)\n                  {\n                    atom_indices.insert(i);\n                  }\n              }\n          }\n\n        this->charges_list_for_each_cell.insert(std::make_pair(cell, atom_indices));\n\n        //clear std::set content for next cell\n        atom_indices.clear();\n      }\n\n//    std::set<unsigned int>::iterator iter;\n//    typename std::map<cell_it, std::set<unsigned int> >::iterator it;\n\n//        //Print the contents of std::map as cell level, index : atom_list\n//  for(it = charges_list_for_each_cell.begin(); it != charges_list_for_each_cell.end(); ++it)\n//      {\n//    if(!it->second.empty())\n//        {\n//      std::cout<< it->first->level()<<\" \"<<it->first->index() << \":\" ;\n//      for(iter = it->second.begin(); iter != it->second.end(); ++iter)\n//          std::cout<< *iter << \" \";\n//      std::cout<< std::endl;\n//        }\n//      }\n}\n\n// Output the grid with atoms list for each cell\n// Preferable to run only for one refinement\ntemplate <int dim>\nvoid LaplaceProblem<dim>::grid_output_debug(const unsigned int cycle)\n{\n  std::map<types::global_dof_index, Point<dim> > support_points;\n  MappingQ1<dim> mapping;\n  DoFTools::map_dofs_to_support_points(mapping, mg_dof_handler, support_points);\n\n  const std::string base_filename =\n    \"grid\" + dealii::Utilities::int_to_string(dim) + \"_p\" + \"_cycle\"+ dealii::Utilities::int_to_string(cycle) + dealii::Utilities::int_to_string(Utilities::MPI::this_mpi_process(MPI_COMM_WORLD));\n  const std::string filename =  base_filename + \".gp\";\n  std::ofstream f(filename.c_str());\n\n  f << \"set terminal png size 400,410 enhanced font \\\"Helvetica,8\\\"\" << std::endl\n    << \"set output \\\"\" << base_filename << \".png\\\"\" << std::endl\n    << \"set size square\" << std::endl\n    << \"set view equal xy\" << std::endl\n    << \"unset xtics\" << std::endl\n    << \"unset ytics\" << std::endl\n    << \"plot '-' using 1:2 with lines notitle, '-' with labels point pt 2 offset 1,1 notitle\" << std::endl;\n  GridOut().write_gnuplot(triangulation, f);\n  f << \"e\" << std::endl;\n\n  for (auto it : this->charges_list_for_each_cell)\n    {\n      f << it.first->center() << \" \\\"\";\n      for (auto el : it.second)\n        f << el << \", \";\n      f << \"\\\"\\n\";\n    }\n\n  f << std::flush;\n\n  f << \"e\" << std::endl;\n\n//        Output another grid with flag output for atom presence on each cell\n//        if atom assigned to the cell flag 1 else flag 0\n  const std::string base_filename_2 =\n    \"grid_atom_presence\" + dealii::Utilities::int_to_string(dim) + \"_p\" + \"_cycle\"+ dealii::Utilities::int_to_string(cycle) + dealii::Utilities::int_to_string(Utilities::MPI::this_mpi_process(MPI_COMM_WORLD));\n  const std::string filename_2 =  base_filename_2 + \".gp\";\n  std::ofstream g(filename_2.c_str());\n\n  g << \"set terminal png size 400,410 enhanced font \\\"Helvetica,8\\\"\" << std::endl\n    << \"set output \\\"\" << base_filename_2 << \".png\\\"\" << std::endl\n    << \"set size square\" << std::endl\n    << \"set view equal xy\" << std::endl\n    << \"unset xtics\" << std::endl\n    << \"unset ytics\" << std::endl\n    << \"plot '-' using 1:2 with lines notitle, '-' with labels point pt 2 offset 1,1 notitle\" << std::endl;\n  GridOut().write_gnuplot(triangulation, g);\n  g << \"e\" << std::endl;\n\n  for (auto it : this->charges_list_for_each_cell)\n    {\n      g << it.first->center() << \" \\\"\";\n      if (it.second.empty())\n        g << 0;\n      else\n        g << 1;\n      g << \"\\\"\\n\";\n    }\n\n  g << std::flush;\n\n  g << \"e\" << std::endl;\n\n}\n\ntemplate <int dim>\nvoid LaplaceProblem<dim>::pack_function(const typename parallel::distributed::Triangulation<dim,dim>::cell_iterator &cell,\n                                        const typename parallel::distributed::Triangulation<dim,dim>::CellStatus status, void *data)\n{\n  if (status==parallel::distributed::Triangulation<dim,dim>::CELL_COARSEN)\n    {\n      Assert(cell->has_children(), ExcInternalError());\n    }\n  else\n    {\n      Assert(!cell->has_children(), ExcInternalError());\n    }\n\n  unsigned int *data_store = reinterpret_cast<unsigned int *>(data);\n\n  std::set<unsigned int> set_atom_indices;\n  std::vector<unsigned int> vec_atom_indices;\n  set_atom_indices = this->charges_list_for_each_cell.at(cell);\n  std::copy(set_atom_indices.begin(), set_atom_indices.end(), std::back_inserter(vec_atom_indices));\n  const unsigned int n_indices = vec_atom_indices.size();\n  Assert (sizeof(unsigned int) * (n_indices+1) <= this->data_size_in_bytes,\n          ExcInternalError());\n  std::memcpy(data_store, &n_indices, sizeof(unsigned int));\n  data_store++;\n  std::memcpy(data_store, &vec_atom_indices[0], sizeof(unsigned int)*n_indices);\n  set_atom_indices.clear();\n  vec_atom_indices.clear();\n}\n\ntemplate <int dim>\nvoid LaplaceProblem<dim>::unpack_function (const typename parallel::distributed::Triangulation<dim,dim>::cell_iterator &cell,\n                                           const typename parallel::distributed::Triangulation<dim,dim>::CellStatus status, const void *data)\n{\n  Assert ((status!=parallel::distributed::Triangulation<dim,dim>::CELL_COARSEN),\n          ExcNotImplemented());\n  if (status==parallel::distributed::Triangulation<dim,dim>::CELL_REFINE)\n    {\n      Assert(cell->has_children(), ExcInternalError());\n    }\n  else\n    {\n      Assert(!cell->has_children(), ExcInternalError());\n    }\n\n  (void) status;\n  const unsigned int *data_store = reinterpret_cast<const unsigned int *>(data);\n  unsigned int n_indices = 0;\n  std::memcpy(&n_indices, data_store, sizeof(unsigned int));\n  data_store++;\n  std::vector<unsigned int> vec_atom_indices(n_indices);\n  std::memcpy(&vec_atom_indices[0], data_store, sizeof(unsigned int) * n_indices);\n\n  // print debug\n//    if(n_indices != 0)\n//    {\n//      std::cout << \"cell with center \" << cell->center() << \" has \" << n_indices << \" values:\" << std::endl;\n//      for (auto &ind : vec_atom_indices)\n//    std::cout <<\" \" << ind;\n//      std::cout << std::endl;\n//    }\n\n  std::set<unsigned int> set_atom_indices;  //(vec_atom_indices.begin(), vec_atom_indices.end());\n  std::copy(vec_atom_indices.begin(), vec_atom_indices.end(), std::inserter(set_atom_indices, set_atom_indices.begin()));\n\n  if (cell->has_children())\n    {\n      for (unsigned int child=0; child<cell->n_children(); ++child)\n        if (cell->child(child)->is_locally_owned())\n          {\n//                Assert(this->charges_list_for_each_cell.find(cell->child(child)) == this->charges_list_for_each_cell.end(),\n//                       ExcInternalError());\n            this->charges_list_for_each_cell[cell->child(child)] = set_atom_indices;\n          }\n    }\n  else\n    {\n//  Assert(this->charges_list_for_each_cell.find(cell) == this->charges_list_for_each_cell.end(),\n//         ExcInternalError());\n      this->charges_list_for_each_cell[cell] = set_atom_indices;\n    }\n  vec_atom_indices.clear();\n  set_atom_indices.clear();\n}\n\ntemplate <int dim>\nvoid LaplaceProblem<dim>::prepare_for_coarsening_and_refinement ( )\n{\n  unsigned int number_of_values = 0;\n  for (typename parallel::distributed::Triangulation<dim>::active_cell_iterator it = triangulation.begin_active();\n       it != triangulation.end(); it++)\n    if (it->is_locally_owned())\n      number_of_values = std::max(static_cast<unsigned int>(this->charges_list_for_each_cell.at(it).size()),\n                                  number_of_values);\n\n  number_of_values = Utilities::MPI::max(number_of_values, triangulation.get_communicator ()) + 1;\n  Assert (number_of_values > 0, ExcInternalError());\n  this->data_size_in_bytes = sizeof(unsigned int) * number_of_values;\n  this->offset = triangulation.register_data_attach(data_size_in_bytes, std::bind(&Step50::LaplaceProblem<dim>::pack_function,\n                                                    this,\n                                                    std::placeholders::_1,\n                                                    std::placeholders::_2,\n                                                    std::placeholders::_3));\n\n\n}\n\ntemplate <int dim>\nvoid LaplaceProblem<dim>::project_cell_data()\n{\n  triangulation.notify_ready_to_unpack(this->offset, std::bind(&Step50::LaplaceProblem<dim>::unpack_function,\n                                       this,\n                                       std::placeholders::_1,\n                                       std::placeholders::_2,\n                                       std::placeholders::_3));\n}\n\ntemplate <int dim>\ndouble LaplaceProblem<dim>::long_ranged_potential(const Point<dim> &point, const Point<dim> &atom_position,\n                                                  const double &charge) const\n{\n  const double radial_distance = point.distance(atom_position);\n  return charge * (erf(radial_distance/ this->r_c) / radial_distance);\n}\n\ntemplate <int dim>\nconst double LaplaceProblem<dim>::short_ranged_potential(const Point<dim> &point, const Point<dim> &atom_position,\n                                                         const double &charge)\n{\n  const double radial_distance = point.distance(atom_position);\n  return charge * (erfc(radial_distance/ this->r_c) / radial_distance);\n}\n\ntemplate <int dim>\nvoid LaplaceProblem<dim>::compute_charge_densities()\n{\n  TimerOutput::Scope t(computing_timer, \"Compute charge densities\");\n  this->density_values_for_each_cell.clear();\n\n  FEValues<dim> fe_values (fe, this->quadrature_formula_rhs,\n                           update_values    |  update_gradients |\n                           update_quadrature_points  |  update_JxW_values);\n  const unsigned int   n_q_points    = this->quadrature_formula_rhs.size();\n\n  std::vector<double> density_values(n_q_points);\n\n  const double constant_value = 4.0 * (numbers::PI)  / (std::pow(this->r_c, 3) * std::pow(numbers::PI, 1.5));\n  const double r_c_squared_inverse = 1.0 / (this->r_c * this->r_c);\n\n  // Evaluate the charge densities to be used in RHS assembly here\n  typename DoFHandler<dim>::active_cell_iterator\n  cell = mg_dof_handler.begin_active(),\n  endc = mg_dof_handler.end();\n  for (; cell!=endc; ++cell)\n    if (cell->is_locally_owned())\n      {\n        fe_values.reinit (cell);\n        const std::vector<Point<dim> > &quadrature_points = fe_values.get_quadrature_points();\n\n        for (unsigned int q_point = 0; q_point < n_q_points; ++q_point)\n          {\n            density_values[q_point] = 0.0;\n            // Check: loop over all the atoms or the std::set of neigboring atoms\n            // according to the localization\n\n            //If flag = false iterate over all the atoms in the domain, i.e. do not optimize the assembly\n            if (!flag_rhs_assembly)\n              {\n                for (unsigned int k = 0; k < number_of_atoms; ++k)\n                  {\n                    const Point<dim> &Xi = this->atom_positions[k];\n                    const double &r = Xi.distance(quadrature_points[q_point]);;\n                    const double &r_squared = r * r;\n\n                    density_values[q_point] +=  constant_value *\n                                                exp(-r_squared * r_c_squared_inverse) *\n                                                this->charges[k];\n                  }\n              }\n\n            //If flag = true iterate only over the neighouring atoms and apply rhs optimization\n            if (flag_rhs_assembly)\n              {\n                const std::set<unsigned int> &set_atom_indices = this->charges_list_for_each_cell.at(cell);\n                for (const auto &i : set_atom_indices)\n                  {\n                    const Point<dim> &Xi = this->atom_positions[i];\n                    const double &r = Xi.distance(quadrature_points[q_point]);\n                    const double &r_squared = r * r;\n\n                    density_values[q_point] +=  constant_value *\n                                                exp(-r_squared * r_c_squared_inverse) *\n                                                this->charges[i];\n                  }\n              }\n          }\n\n        this->density_values_for_each_cell.insert(std::make_pair(cell, density_values));\n      }\n}\n\n\ntemplate <int dim>\nvoid LaplaceProblem<dim>::compute_moments()\n{\n  TimerOutput::Scope t(computing_timer, \"Compute dipole moments\");\n  FEValues<dim> fe_values (fe, this->quadrature_formula_rhs,\n                           update_values    |  update_gradients |\n                           update_quadrature_points  |  update_JxW_values);\n  const unsigned int   n_q_points    = this->quadrature_formula_rhs.size();\n\n  // Compute the dipole moment Po\n  dipole_moment = Tensor<1, dim, double>();\n  for (unsigned int k = 0; k < number_of_atoms; ++k)\n    dipole_moment += this->charges[k] * this->atom_positions[k];\n\n  const SymmetricTensor<2, dim> I = unit_symmetric_tensor<dim>();\n\n  // Compute the quadrupole moment Qo\n  // numerical integration by quadrature rule\n  quadrupole_moment = Tensor<2, dim, double>();\n  typename DoFHandler<dim>::active_cell_iterator\n  cell = mg_dof_handler.begin_active(),\n  endc = mg_dof_handler.end();\n  for (; cell!=endc; ++cell)\n    if (cell->is_locally_owned())\n      {\n        fe_values.reinit (cell);\n        const std::vector<Point<dim> > &quadrature_points = fe_values.get_quadrature_points();\n        const std::vector<double> &density_values = this->density_values_for_each_cell.at(cell);\n\n        for (unsigned int q_point = 0; q_point < n_q_points; ++q_point)\n          {\n            Tensor<2, dim, double> x_dyad_x = Tensor<2, dim, double>();\n            for (unsigned int p = 0; p < dim; ++p)\n              for (unsigned int q = 0; q < dim; ++q)\n                x_dyad_x[p][q] = quadrature_points[q_point](p) * quadrature_points[q_point](q);\n            /*\n            outer_product(x_dyad_x, static_cast<const Tensor< 1, dim, double> &> quadrature_points[q_point],\n              static_cast<const Tensor< 1, dim, double> &> quadrature_points[q_point]);\n              */\n\n            const double x_norm = quadrature_points[q_point].norm();\n            this->quadrupole_moment += density_values[q_point] * (3.0 * x_dyad_x - x_norm * x_norm * I) * fe_values.JxW(q_point);\n          }\n      }\n\n  this->quadrupole_moment = dealii::Utilities::MPI::sum(this->quadrupole_moment, MPI_COMM_WORLD);\n  this->quadrupole_moment = 0.0;\n  /*\n      // Debug the moments Tensors\n      pcout << \"Dipole : \" << std::endl;\n      for(unsigned int p = 0; p < dim; ++p)\n    {\n        pcout << this->dipole_moment[p] << \"    \";\n    }\n      pcout << std::endl;\n\n      pcout << \"Quadrupole : \" << std::endl;\n      for(unsigned int p = 0; p < dim; ++p)\n    {\n    for(unsigned int q = 0; q < dim; ++q)\n        {\n      pcout << this->quadrupole_moment[p][q] << \" \";\n        }\n    pcout << std::endl;\n    }\n      pcout << std::endl;*/\n}\n\ntemplate <int dim>\nvoid LaplaceProblem<dim>::setup_system (const unsigned int &cycle)\n{\n  TimerOutput::Scope t(computing_timer, \"Setup system\");\n  mg_dof_handler.distribute_dofs (fe);\n  mg_dof_handler.distribute_mg_dofs (fe);\n\n  DoFTools::extract_locally_relevant_dofs (mg_dof_handler,\n                                           locally_relevant_set);\n\n  solution.reinit(mg_dof_handler.locally_owned_dofs(), MPI_COMM_WORLD);\n  system_rhs.reinit(mg_dof_handler.locally_owned_dofs(), MPI_COMM_WORLD);\n\n  this->error_per_cell.reinit(triangulation.n_active_cells());\n\n  constraints.reinit (locally_relevant_set);\n  hanging_node_constraints.reinit (locally_relevant_set);\n  DoFTools::make_hanging_node_constraints (mg_dof_handler, hanging_node_constraints);\n  DoFTools::make_hanging_node_constraints (mg_dof_handler, constraints);\n\n  std::set<types::boundary_id>         dirichlet_boundary;\n  typename FunctionMap<dim>::type      dirichlet_boundary_functions;\n\n  // Need the std::map of charge list for computing the densities\n  if ((cycle == 0) && (flag_rhs_assembly))\n    rhs_assembly_optimization();\n\n  // Compute the moments for each ref cycle for some given point (taken as origin)\n  // also computes the charge densities later to be used in RHS assembly\n  if (lammpsinput != 0)\n    {\n      compute_charge_densities();\n      compute_moments();\n    }\n\n  dirichlet_boundary.insert(0);\n  ZeroFunction<dim>                    homogeneous_dirichlet_bc ;\n  GaussianCharges::NonZeroDBC<dim> nonzeroDBC(Point<dim>(),this->dipole_moment,this->quadrupole_moment);\n\n  if (Boundary_conditions == \"Homogeneous\")\n    dirichlet_boundary_functions[0] = static_cast<const Function<dim>* >(&homogeneous_dirichlet_bc);\n  else if (Boundary_conditions == \"Inhomogeneous\")\n    dirichlet_boundary_functions[0] = static_cast<const Function<dim>* >(&nonzeroDBC);\n  else if (Boundary_conditions == \"Exact\")\n    dirichlet_boundary_functions[0] = static_cast<const Function<dim>* >(exact_solution.get());\n\n  VectorTools::interpolate_boundary_values (mg_dof_handler,\n                                            dirichlet_boundary_functions,\n                                            constraints);\n\n  constraints.close ();\n  hanging_node_constraints.close ();\n\n  DynamicSparsityPattern dsp(mg_dof_handler.n_dofs(), mg_dof_handler.n_dofs());\n  DoFTools::make_sparsity_pattern (mg_dof_handler, dsp, constraints);\n  system_matrix.reinit (mg_dof_handler.locally_owned_dofs(), dsp, MPI_COMM_WORLD, true);\n\n\n  mg_constrained_dofs.clear();\n  mg_constrained_dofs.initialize(mg_dof_handler);\n  mg_constrained_dofs.make_zero_boundary_constraints(mg_dof_handler, dirichlet_boundary);\n\n\n  const unsigned int n_levels = triangulation.n_global_levels();\n\n  mg_interface_matrices.resize(0, n_levels-1);\n  mg_interface_matrices.clear_elements ();\n  mg_matrices.resize(0, n_levels-1);\n  mg_matrices.clear_elements ();\n\n  for (unsigned int level=0; level<n_levels; ++level)\n    {\n      DynamicSparsityPattern dsp(mg_dof_handler.n_dofs(level),\n                                 mg_dof_handler.n_dofs(level));\n      MGTools::make_sparsity_pattern(mg_dof_handler, dsp, level);\n\n      mg_matrices[level].reinit(mg_dof_handler.locally_owned_mg_dofs(level),\n                                mg_dof_handler.locally_owned_mg_dofs(level),\n                                dsp,\n                                MPI_COMM_WORLD, true);\n\n      mg_interface_matrices[level].reinit(mg_dof_handler.locally_owned_mg_dofs(level),\n                                          mg_dof_handler.locally_owned_mg_dofs(level),\n                                          dsp,\n                                          MPI_COMM_WORLD, true);\n    }\n}\n\n\ntemplate <int dim>\nvoid LaplaceProblem<dim>::assemble_system ()\n{\n  TimerOutput::Scope t(computing_timer, \"Assemble system\");\n\n  system_matrix = 0.;\n  system_rhs = 0.;\n\n  // Use of different number of quadrature points for laplace and rhs integration\n  FEValues<dim> fe_values_laplace (fe, this->quadrature_formula_laplace,\n                                   update_values    |  update_gradients |\n                                   update_quadrature_points  |  update_JxW_values);\n  FEValues<dim> fe_values_rhs (fe, this->quadrature_formula_rhs,\n                               update_values    |  update_gradients |\n                               update_quadrature_points  |  update_JxW_values);\n\n\n  const unsigned int   dofs_per_cell = fe.dofs_per_cell;\n  const unsigned int   n_q_points_laplace    = this->quadrature_formula_laplace.size();\n  const unsigned int   n_q_points_rhs    = this->quadrature_formula_rhs.size();\n\n  FullMatrix<double>   cell_matrix (dofs_per_cell, dofs_per_cell);\n  Vector<double>       cell_rhs (dofs_per_cell);\n\n  std::vector<types::global_dof_index> local_dof_indices (dofs_per_cell);\n\n  std::vector<double>    coefficient_values (n_q_points_laplace);\n\n  std::vector<double>    density_values (n_q_points_rhs);\n\n  typename DoFHandler<dim>::active_cell_iterator\n  cell = mg_dof_handler.begin_active(),\n  endc = mg_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_laplace.reinit (cell);\n        fe_values_rhs.reinit (cell);\n\n        coeff_func->value_list (fe_values_laplace.get_quadrature_points(),\n                                coefficient_values);\n\n        // Assemble local cell matrix contribution to global matrix\n        // Quadrature rule for laplace is for (degree+1) quadrature points\n        for (unsigned int q_point=0; q_point<n_q_points_laplace; ++q_point)\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) += (coefficient_values[q_point] *\n                                     fe_values_laplace.shape_grad(i,q_point) *\n                                     fe_values_laplace.shape_grad(j,q_point) *\n                                     fe_values_laplace.JxW(q_point));\n            }\n\n        cell->get_dof_indices (local_dof_indices);\n        constraints.distribute_local_to_global (cell_matrix,\n                                                local_dof_indices,\n                                                system_matrix);\n\n\n        // evaluate RHS function at quadrature points.\n        if (lammpsinput == 0)\n          {\n            rhs_func->value_list (fe_values_rhs.get_quadrature_points(),\n                                  density_values);\n          }\n        else if (lammpsinput != 0)\n          density_values = this->density_values_for_each_cell.at(cell);\n\n        Assert (density_values.size()==n_q_points_rhs, ExcInternalError());\n\n        // Assemble local cell rhs vector contribution, body loading i.e. charge density\n        // For the numerical integration of complex error function in rhs\n        // we use higher number of quadrature points taken as user parameter\n        // Thus the Quadrature rule is for (degree + user_parameter) quadrature points\n        for (unsigned int q_point=0; q_point<n_q_points_rhs; ++q_point)\n          for (unsigned int i=0; i<dofs_per_cell; ++i)\n            {\n              cell_rhs(i) += (fe_values_rhs.shape_value(i,q_point) *\n                              density_values[q_point] *\n                              fe_values_rhs.JxW(q_point));\n\n            }\n\n        // Distribute the local cell rhs contribution to global rhs vector\n        // along with the contribution arising from inhomogeneous b.c. in terms of\n        // local cell matrix element * inhomog.b.c. value for constrained dof\n        constraints.distribute_local_to_global (cell_rhs,\n                                                local_dof_indices,\n                                                system_rhs,\n                                                cell_matrix);\n      }\n\n  system_matrix.compress(VectorOperation::add);\n  system_rhs.compress(VectorOperation::add);\n}\n\ntemplate <int dim>\nvoid LaplaceProblem<dim>::assemble_multigrid ()\n{\n  TimerOutput::Scope t(computing_timer, \"Assemble Multigrid\");\n\n  FEValues<dim> fe_values (fe, this->quadrature_formula_laplace,\n                           update_values   | update_gradients |\n                           update_quadrature_points | update_JxW_values);\n\n  const unsigned int   dofs_per_cell   = fe.dofs_per_cell;\n  const unsigned int   n_q_points      = this->quadrature_formula_laplace.size();\n\n  FullMatrix<double>   cell_matrix (dofs_per_cell, dofs_per_cell);\n\n  std::vector<types::global_dof_index> local_dof_indices (dofs_per_cell);\n\n  std::vector<double>    coefficient_values (n_q_points);\n\n  std::vector<ConstraintMatrix> boundary_constraints (triangulation.n_global_levels());\n  ConstraintMatrix empty_constraints;\n  for (unsigned int level=0; level<triangulation.n_global_levels(); ++level)\n    {\n      IndexSet dofset;\n      DoFTools::extract_locally_relevant_level_dofs (mg_dof_handler, level, dofset);\n      boundary_constraints[level].reinit(dofset);\n      boundary_constraints[level].add_lines (mg_constrained_dofs.get_refinement_edge_indices(level));\n      boundary_constraints[level].add_lines (mg_constrained_dofs.get_boundary_indices(level));\n\n      boundary_constraints[level].close ();\n    }\n\n  typename DoFHandler<dim>::cell_iterator cell = mg_dof_handler.begin(),\n                                          endc = mg_dof_handler.end();\n\n  for (; cell!=endc; ++cell)\n    if (cell->level_subdomain_id()==triangulation.locally_owned_subdomain())\n      {\n        cell_matrix = 0;\n        fe_values.reinit (cell);\n\n        coeff_func->value_list (fe_values.get_quadrature_points(),\n                                coefficient_values);\n\n        for (unsigned int q_point=0; q_point<n_q_points; ++q_point)\n          for (unsigned int i=0; i<dofs_per_cell; ++i)\n            for (unsigned int j=0; j<dofs_per_cell; ++j)\n              cell_matrix(i,j) += (coefficient_values[q_point] *\n                                   fe_values.shape_grad(i,q_point) *\n                                   fe_values.shape_grad(j,q_point) *\n                                   fe_values.JxW(q_point));\n\n        cell->get_mg_dof_indices (local_dof_indices);\n\n        boundary_constraints[cell->level()].distribute_local_to_global (cell_matrix,local_dof_indices,\n            mg_matrices[cell->level()]);\n\n\n        const IndexSet &interface_dofs_on_level\n          = mg_constrained_dofs.get_refinement_edge_indices(cell->level());\n        const unsigned int lvl = cell->level();\n\n        for (unsigned int i=0; i<dofs_per_cell; ++i)\n          for (unsigned int j=0; j<dofs_per_cell; ++j)\n            if (interface_dofs_on_level.is_element(local_dof_indices[i])   // at_refinement_edge(i)\n                &&\n                !interface_dofs_on_level.is_element(local_dof_indices[j])   // !at_refinement_edge(j)\n                &&\n                (\n                  (!mg_constrained_dofs.is_boundary_index(lvl, local_dof_indices[i])\n                   &&\n                   !mg_constrained_dofs.is_boundary_index(lvl, local_dof_indices[j])\n                  ) // ( !boundary(i) && !boundary(j) )\n                  ||\n                  (\n                    mg_constrained_dofs.is_boundary_index(lvl, local_dof_indices[i])\n                    &&\n                    local_dof_indices[i]==local_dof_indices[j]\n                  ) // ( boundary(i) && boundary(j) && i==j )\n                )\n               )\n              {\n              }\n            else\n              {\n                cell_matrix(i,j) = 0;\n              }\n\n\n        empty_constraints.distribute_local_to_global (cell_matrix,\n                                                      local_dof_indices,\n                                                      mg_interface_matrices[cell->level()]);\n      }\n\n  for (unsigned int i=0; i<triangulation.n_global_levels(); ++i)\n    {\n      mg_matrices[i].compress(VectorOperation::add);\n      mg_interface_matrices[i].compress(VectorOperation::add);\n    }\n}\n\n\n\n\ntemplate <int dim>\nvoid LaplaceProblem<dim>::solve ()\n{\n  TimerOutput::Scope t(computing_timer, \"Solve\");\n  SolverControl solver_control (500, 1e-8*system_rhs.l2_norm(), false);\n  SolverCG<vector_t> solver (solver_control);\n\n  // Print the charges densities i.e. system rhs norms to compare with rhs optimization\n  pcout << \"   L1 rhs norm \" << std::setprecision(10) << std::scientific << system_rhs.l1_norm() << std::endl;\n  pcout << \"   L2 rhs norm \" << std::setprecision(10) << std::scientific << system_rhs.l2_norm() << std::endl;\n  pcout << \"   LInfinity rhs norm \" << std::setprecision(10) << std::scientific << system_rhs.linfty_norm() << std::endl;\n  // Print the Laplace matrix norm for debug purpose\n  pcout << \"   L1 Matrix norm \" << std::setprecision(10) << std::scientific << system_matrix.l1_norm() << std::endl;\n  pcout << \"   LInfinity Matrix norm \" << std::setprecision(10) << std::scientific << system_matrix.linfty_norm() << std::endl;\n  pcout << \"   Frobenius Matrix norm \" << std::setprecision(10) << std::scientific << system_matrix.frobenius_norm() << std::endl;\n\n  if (PreconditionerType == \"GMG\")\n    {\n//  TimerOutput::Scope t(computing_timer, \"Solve: GMG Preconditioner\");\n      MGTransferPrebuilt<vector_t> mg_transfer( mg_constrained_dofs);\n      mg_transfer.build_matrices(mg_dof_handler);\n\n      matrix_t &coarse_matrix = mg_matrices[0];\n\n      SolverControl coarse_solver_control (1000, 1e-10, false, false);\n      SolverCG<vector_t> coarse_solver(coarse_solver_control);\n      PreconditionIdentity id;\n      MGCoarseGridIterativeSolver<vector_t, SolverCG<vector_t>, matrix_t, PreconditionIdentity > coarse_grid_solver(coarse_solver,\n          coarse_matrix,\n          id);\n\n//  typedef LA::MPI::PreconditionJacobi Smoother;  //Jacobi Smoother for MG\n      typedef LA::MPI::PreconditionSSOR Smoother;  //Gauss Seidel variant Smoother for MG\n      MGSmootherPrecondition<matrix_t, Smoother, vector_t> mg_smoother; //Default constructor with relaxation steps nue_1 = nue_2 = 1\n      mg_smoother.initialize(mg_matrices, Smoother::AdditionalData(0.5)); //Damping factor for smoother = 0.5\n      mg_smoother.set_steps(2);   //Smoothing step on finest level = 2\n\n      mg::Matrix<vector_t> mg_matrix(mg_matrices);\n      mg::Matrix<vector_t> mg_interface_up(mg_interface_matrices);\n      mg::Matrix<vector_t> mg_interface_down(mg_interface_matrices);\n\n\n      Multigrid<vector_t > mg(mg_matrix,\n                              coarse_grid_solver,\n                              mg_transfer,\n                              mg_smoother,\n                              mg_smoother);\n\n      mg.set_edge_matrices(mg_interface_down, mg_interface_up);\n\n      PreconditionMG<dim, vector_t, MGTransferPrebuilt<vector_t> >\n      preconditioner(mg_dof_handler, mg, mg_transfer);\n\n      solver.solve (system_matrix, solution, system_rhs,\n                    preconditioner);\n\n    }\n\n  else if (PreconditionerType == \"Jacobi\")\n    {\n//  TimerOutput::Scope t(computing_timer, \"Solve: Jacobi Preconditioner\");\n      typedef LA::MPI::PreconditionJacobi JacobiPreconditioner;\n      JacobiPreconditioner preconditionJacobi;\n      preconditionJacobi.initialize (system_matrix, JacobiPreconditioner::AdditionalData(0.6));\n\n      solver.solve (system_matrix, solution, system_rhs,\n                    preconditionJacobi);\n\n    }\n\n\n  pcout << \"   Starting value \" << std::fixed << solver_control.initial_value() << std::endl;\n  pcout << \"   CG converged in \" << solver_control.last_step() << \" iterations.\" << std::endl;\n  pcout << \"   Convergence value \" << std::scientific << solver_control.last_value() << std::endl;\n  pcout << \"   L1 solution norm \" << std::setprecision(10) << std::scientific << solution.l1_norm() << std::endl;\n  pcout << \"   L2 solution norm \" << std::setprecision(10) << std::scientific << solution.l2_norm() << std::endl;\n  pcout << \"   LInfinity solution norm \" << std::setprecision(10) << std::scientific << solution.linfty_norm() << std::endl;\n\n  constraints.distribute (solution);\n}\n\n\ntemplate <int dim>\nvoid LaplaceProblem<dim>::estimate_error_and_mark_cells()\n{\n  TimerOutput::Scope t(computing_timer, \"Estimate error and mark cells\");\n  Vector<float> estimated_error_per_cell (triangulation.n_active_cells());\n\n  LA::MPI::Vector temp_solution;\n  temp_solution.reinit(locally_relevant_set, MPI_COMM_WORLD);\n  temp_solution = solution;\n\n  // Use of update hessians flag needed\n  FEValues<dim> fe_values (fe, this->quadrature_formula_rhs,\n                           update_values    |  update_gradients | update_hessians |\n                           update_quadrature_points  |  update_JxW_values);\n\n  const unsigned int   n_q_points    = this->quadrature_formula_rhs.size();\n\n  std::vector<double> fe_solution_laplacians (n_q_points);\n  std::vector<double>    density_values (n_q_points);\n\n  KellyErrorEstimator<dim>::estimate (static_cast<DoFHandler<dim>&>(mg_dof_handler),\n                                      QGauss<dim-1>(degree+1),\n                                      typename FunctionMap<dim>::type(),\n                                      temp_solution,\n                                      estimated_error_per_cell,\n                                      ComponentMask(),\n                                      nullptr,\n                                      numbers::invalid_unsigned_int,\n                                      numbers::invalid_subdomain_id,\n                                      numbers::invalid_material_id,\n                                      KellyErrorEstimator<dim>::Strategy::cell_diameter);\n\n  typename DoFHandler<dim>::active_cell_iterator\n  cell = mg_dof_handler.begin_active(),\n  endc = mg_dof_handler.end();\n  for (; cell!=endc; ++cell)\n    if (cell->is_locally_owned())\n      {\n        fe_values.reinit (cell);\n        fe_values.get_function_laplacians (temp_solution, fe_solution_laplacians);\n\n        Assert(n_q_points == fe_values.get_quadrature_points().size(), ExcInternalError());\n        if (lammpsinput == 0)\n          {\n            rhs_func->value_list (fe_values.get_quadrature_points(),\n                                  density_values);\n          }\n        else if (lammpsinput != 0)\n          density_values = this->density_values_for_each_cell.at(cell);\n\n        Assert(density_values.size() == n_q_points, ExcInternalError());\n\n        double error = 0;\n        for (unsigned int q_point = 0; q_point < n_q_points; ++q_point)\n          {\n            const double temp = fe_solution_laplacians[q_point] + 4.0 * numbers::PI * density_values[q_point];\n            error +=  temp * temp * fe_values.JxW(q_point);\n          }\n        estimated_error_per_cell(cell->active_cell_index()) = std::sqrt(\n                                                                std::pow(estimated_error_per_cell(cell->active_cell_index()),2) +\n                                                                std::pow(cell->diameter(),2) * error\n                                                              );\n      }\n\n  const double threshold = 0.6 * Utilities::MPI::max(estimated_error_per_cell.linfty_norm(), MPI_COMM_WORLD);\n\n  pcout << \"Threshold value for refinement:\t\" << threshold << std::endl;\n  this->error_per_cell = estimated_error_per_cell;\n\n  GridRefinement::refine (triangulation, estimated_error_per_cell, threshold);\n}\n\n\n\n\ntemplate <int dim>\nvoid LaplaceProblem<dim>::refine_grid (const unsigned int &cycle)\n{\n  TimerOutput::Scope t(computing_timer, \"Refine, solution transfer and sending atoms list to child cells\");\n\n  if ((lammpsinput != 0) && (flag_rhs_assembly))\n    prepare_for_coarsening_and_refinement();\n\n  parallel::distributed::SolutionTransfer<dim, LA::MPI::Vector> soltrans(mg_dof_handler);\n  triangulation.prepare_coarsening_and_refinement();\n\n  LA::MPI::Vector previous_solution;\n  previous_solution.reinit(locally_relevant_set, MPI_COMM_WORLD);\n  previous_solution = solution;\n  soltrans.prepare_for_coarsening_and_refinement(previous_solution);\n\n  triangulation.execute_coarsening_and_refinement ();\n\n  if ((lammpsinput != 0) && (flag_rhs_assembly))\n    project_cell_data();\n\n  setup_system(cycle);\n\n  soltrans.interpolate(solution);\n  constraints.set_zero (solution);\n\n}\n\ntemplate <int dim>\nclass GradientPostprocessor : public DataPostprocessorVector<dim>\n{\npublic:\n  GradientPostprocessor()\n    :\n    DataPostprocessorVector<dim> (\"grad_phi\",\n                                 update_gradients)\n  {}\n\n  virtual void\n  evaluate_scalar_field (const DataPostprocessorInputs::Scalar<dim> &input_data,\n                         std::vector<Vector<double> > &computed_quantities) const\n  {\n    AssertDimension (input_data.solution_gradients.size(),\n                     computed_quantities.size());\n\n    for (unsigned int p=0; p < input_data.solution_gradients.size(); ++p)\n      {\n        AssertDimension (computed_quantities[p].size(), dim);\n        for (unsigned int d=0; d < dim; ++d)\n          computed_quantities[p][d] = -input_data.solution_gradients[p][d];\n      }\n  }\n};\n\ntemplate <int dim>\nvoid LaplaceProblem<dim>::output_results (const unsigned int cycle) const\n{\n  GradientPostprocessor<dim> gradient_postprocessor;\n  DataOut<dim> data_out;\n\n  LA::MPI::Vector relevant_solution;\n  relevant_solution.reinit(locally_relevant_set, MPI_COMM_WORLD);\n  relevant_solution = solution;\n\n  data_out.attach_dof_handler (mg_dof_handler);\n  data_out.add_data_vector (relevant_solution, \"solution\");\n  data_out.add_data_vector (relevant_solution, gradient_postprocessor);\n\n  LA::MPI::Vector analytical_sol_ghost;\n\n  // FIXME: add parameter to disable calculation and output of analytical solution\n  //Output the analytical solution on mesh only for Gaussian charges problem with or without LAMMPS input\n  if (flag_analytical_solution)\n    {\n      if (Problemtype == \"GaussianCharges\")\n        {\n          if (lammpsinput == 0)\n            {\n              //Need to implement the analytical sol for the problem on paper\n              LA::MPI::Vector analytical_sol;\n              analytical_sol.reinit(mg_dof_handler.locally_owned_dofs(), MPI_COMM_WORLD);\n              VectorTools::interpolate (mg_dof_handler, GaussianCharges::Analytical_Solution_without_lammps<dim> (r_c),\n                                        analytical_sol);\n              analytical_sol_ghost.reinit(mg_dof_handler.locally_owned_dofs(),locally_relevant_set,MPI_COMM_WORLD);\n              analytical_sol_ghost = analytical_sol;\n              data_out.add_data_vector (analytical_sol_ghost, \"Analytical_Solution_without_lammps\");\n            }\n          else\n            {\n              if (number_of_atoms < 10)\n                {\n                  LA::MPI::Vector analytical_sol;\n                  analytical_sol.reinit(mg_dof_handler.locally_owned_dofs(), MPI_COMM_WORLD);\n                  VectorTools::interpolate (mg_dof_handler,\n                                            static_cast<const Function<dim>& >(*(exact_solution.get())),\n                                            analytical_sol);\n\n                  analytical_sol_ghost.reinit(mg_dof_handler.locally_owned_dofs(),locally_relevant_set,MPI_COMM_WORLD);\n                  analytical_sol_ghost = analytical_sol;\n                  data_out.add_data_vector (analytical_sol_ghost, \"Analytical_Solution_atoms\");\n                }\n            }\n        }\n    }\n  // FIXME: add parameter to disable output of RHS field\n  //Output the rhs to mesh for visualisation\n  if (flag_rhs_field)\n    {\n      if ((lammpsinput != 0) && (number_of_atoms < 10))\n        {\n          LA::MPI::Vector interpolated_rhs;\n          interpolated_rhs.reinit(mg_dof_handler.locally_owned_dofs(), MPI_COMM_WORLD);\n          LA::MPI::Vector interpolated_rhs_ghost;\n          interpolated_rhs_ghost.reinit(mg_dof_handler.locally_owned_dofs(), locally_relevant_set, MPI_COMM_WORLD);\n\n          if (Problemtype == \"Step16\")\n            VectorTools::interpolate (mg_dof_handler, Step16::RightHandSide<dim> (), interpolated_rhs);\n          if (Problemtype == \"GaussianCharges\")\n            VectorTools::interpolate (mg_dof_handler, GaussianCharges::RightHandSide<dim> (r_c), interpolated_rhs);\n\n          interpolated_rhs_ghost = interpolated_rhs;\n          data_out.add_data_vector (interpolated_rhs_ghost, \"interpolated_rhs\");\n        }\n    }\n  // FIXME: why do you want to output this? Don't do this?\n  /*\n  LA::MPI::Vector system_rhs_ghost;\n  system_rhs_ghost.reinit(mg_dof_handler.locally_owned_dofs(), locally_relevant_set, MPI_COMM_WORLD);\n  system_rhs_ghost = system_rhs;\n  data_out.add_data_vector (system_rhs_ghost, \"system_rhs\");\n  */\n\n  // FIXME: add parameter, don't output unless asked!\n  // probably should not do this on 100000 atoms times 100000 cells !\n  //Output support for rhs of each atom with 1 being atom present in the cell\n  if (flag_atoms_support)\n    {\n      std::vector<Vector<float>> support(number_of_atoms,\n                                         Vector<float>(this->triangulation.n_active_cells()));\n\n      if ((lammpsinput != 0) && (flag_rhs_assembly))\n        {\n          unsigned int cell_index = 0;\n          std::set<unsigned int> set_atom_indices;\n          for (auto cell: this->mg_dof_handler.active_cell_iterators())\n            {\n              if (cell->is_locally_owned())\n                {\n                  set_atom_indices = this->charges_list_for_each_cell.at(cell);\n                  if (!set_atom_indices.empty())\n                    {\n                      for (auto i: set_atom_indices)\n                        support[i](cell_index) = 1.0;\n                    }\n                }\n              cell_index++;\n              set_atom_indices.clear();\n            }\n          Assert (cell_index == this->triangulation.n_active_cells(),\n                  ExcInternalError());\n          for (unsigned int i = 0; i < number_of_atoms; i++)\n            {\n              data_out.add_data_vector (support[i],\n                                        std::string(\"support_\") +\n                                        dealii::Utilities::int_to_string(i));\n            }\n        }\n    }\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.add_data_vector (this->error_per_cell, \"error_indicator\");\n\n  data_out.build_patches (0);\n\n  const std::string filename = (\"solution-\" +\n                                Utilities::int_to_string (cycle, 5) +\n                                \".\" +\n                                Utilities::int_to_string\n                                (triangulation.locally_owned_subdomain(), 4) +\n                                \".vtu\");\n  std::ofstream output (filename.c_str());\n  data_out.write_vtu (output);\n\n  if (Utilities::MPI::this_mpi_process(MPI_COMM_WORLD) == 0)\n    {\n      std::vector<std::string> filenames;\n      for (unsigned int i=0; i<Utilities::MPI::n_mpi_processes(MPI_COMM_WORLD); ++i)\n        filenames.push_back (std::string(\"solution-\") +\n                             Utilities::int_to_string (cycle, 5) +\n                             \".\" +\n                             Utilities::int_to_string(i, 4) +\n                             \".vtu\");\n      const std::string\n      pvtu_master_filename = (\"solution-\" +\n                              Utilities::int_to_string (cycle, 5) +\n                              \".pvtu\");\n      std::ofstream pvtu_master (pvtu_master_filename.c_str());\n      data_out.write_pvtu_record (pvtu_master, filenames);\n\n      const std::string\n      visit_master_filename = (\"solution-\" +\n                               Utilities::int_to_string (cycle, 5) +\n                               \".visit\");\n      std::ofstream visit_master (visit_master_filename.c_str());\n      DataOutBase::write_visit_record (visit_master, filenames);\n\n      //std::cout << \"   wrote \" << pvtu_master_filename << std::endl;\n\n    }\n}\n\ntemplate <int dim>\nvoid LaplaceProblem<dim>::postprocess_electrostatic_energy()\n{\n  TimerOutput::Scope t(computing_timer, \"Postprocess electrostatic energy\");\n  //Evaluation of analytical energy. Part A\n  double analytical_energy = 0.0;\n  for (unsigned int i = 0; i < number_of_atoms; ++i)\n    for (unsigned int j = i+1; j < number_of_atoms; ++j)\n      {\n        const double radial_distance = this->atom_positions[i].distance(this->atom_positions[j]);\n        analytical_energy += this->charges[i] * this->charges[j] / radial_distance;\n      }\n\n  //Evaluation of energies by splitting into long- and short-ranged potentials. part B.1\n  double short_ranged_energy_contribution = 0.0;\n  for (unsigned int i = 0; i < number_of_atoms; ++i)\n    for (unsigned int j = i+1; j < number_of_atoms; ++j)\n      {\n        const double V_j_short_ranged = short_ranged_potential(this->atom_positions[j],\n                                                               this->atom_positions[i],\n                                                               this->charges[j]);\n        short_ranged_energy_contribution += this->charges[i] * V_j_short_ranged;\n      }\n\n  //Evaluation of FE solution, long-ranged potential. Part B.2\n  double fe_solution_energy_contribution = 0.0;\n  vector_t final_solution;\n  final_solution.reinit(locally_relevant_set, MPI_COMM_WORLD);\n  final_solution = solution;\n\n  // 1. loop over all atoms, find out which atoms are owned by\n  // this MPI process. (i.e. std::vector<unsigned int> gives a list of atoms owned by this process)\n  // 2. gather that information across processes so that each MPI process knows about everyone owing atoms\n  // 3. make sure that 1 atom is attributed only to a single process, i.e. take the one with lowest rank\n  // to be the owner.\n  // 4. loop over locally owned atoms and calculate...\n\n  std::vector<double> values(1);\n  std::vector<std::pair<unsigned int, double> > local_fe_contribution;\n  for (unsigned int i = 0; i < number_of_atoms; ++i)\n    {\n      try\n        {\n          const auto my_pair\n            = GridTools::find_active_cell_around_point (StaticMappingQ1<dim>::mapping, mg_dof_handler,\n                                                        this->atom_positions[i]);\n          const auto cell = my_pair.first;\n          if (!cell->is_artificial())\n            {\n              // Now we can find out about the point\n              Quadrature<dim> quad(my_pair.second);\n              FEValues<dim> fe_v(cell->get_fe(), quad, update_values);\n              fe_v.reinit(cell);\n              fe_v.get_function_values(final_solution, values);\n\n              const double local_fe_value = 0.5 * this->charges[i] * values[0];\n              local_fe_contribution.push_back(std::make_pair(i, local_fe_value));\n            }\n        }\n      catch (const VectorTools::ExcPointNotAvailableHere &)\n        {\n        }\n    }\n  // Will return a std::vector< std::vector<std::pair<> > > of size equal to nprocs\n  auto gathered_local_fe_contribution = Utilities::MPI::all_gather (MPI_COMM_WORLD, local_fe_contribution);\n\n  std::vector<bool> atom_processed (number_of_atoms, false);\n\n  //find repeated atom index and replace flag with true indicating atom index already processed for\n  // global FE energy contributuion\n  unsigned int this_counter = 0;\n  for (const auto &it : gathered_local_fe_contribution)\n    {\n      const auto local_vector = it;\n      for (const auto &iter : local_vector)\n        {\n          const unsigned int atom_index = iter.first;\n          const double fe_value = iter.second;\n          if (atom_processed[atom_index] == false)\n            {\n              fe_solution_energy_contribution += fe_value;\n              atom_processed[atom_index] = true;\n              this_counter++;\n            }\n        }\n    }\n\n  Assert(this_counter == number_of_atoms,\n         ExcMessage(std::to_string(this_counter) + \"!=\"+std::to_string(number_of_atoms)));\n\n  //Evaluation of self energy for I == J. Part B.3\n  double self_energy_contribution = 0.0;\n  for (unsigned int i = 0; i < number_of_atoms; ++i)\n    {\n      self_energy_contribution += this->charges[i] * this->charges[i] / (std::sqrt(numbers::PI) * this->r_c);\n    }\n\n  const double total_energy_with_split = short_ranged_energy_contribution + fe_solution_energy_contribution - self_energy_contribution;\n\n  pcout << \"\\nTotal analytical electrostatic energy :   \" << analytical_energy << std::endl;\n  pcout << \"Short-ranged energy contribution :  \" << short_ranged_energy_contribution << std::endl;\n  pcout << \"FE solution long-ranged energy contribution :    \" << fe_solution_energy_contribution << std::endl;\n  pcout << \"Self energy contribution : \" << self_energy_contribution << std::endl;\n  pcout << \"Total electrostatic energy with split in short- and long-ranged : \" << total_energy_with_split << std::endl;\n  pcout << \"Absolute Error between both energies :\t\" << std::abs(std::abs(analytical_energy) -\n        std::abs(total_energy_with_split)) << \"\\n\" << std::endl;\n  pcout << \"Relative Error in total electrostatic energy :\t\" << std::abs( (std::abs(analytical_energy) -\n        std::abs(total_energy_with_split)) / analytical_energy )\n        << std::endl;\n\n}\n\n\ntemplate <int dim>\nvoid LaplaceProblem<dim>::postprocess_error_in_energy_norm()\n{\n  TimerOutput::Scope t(computing_timer, \"Postprocess FE error\");\n  FEValues<dim> fe_values (fe, this->quadrature_formula_laplace,\n                           update_values    |  update_gradients |\n                           update_quadrature_points  |  update_JxW_values);\n\n  const unsigned int   n_q_points    = this->quadrature_formula_laplace.size();\n\n  vector_t fe_solution;\n  fe_solution.reinit(locally_relevant_set, MPI_COMM_WORLD);\n  fe_solution = solution;\n\n  std::vector<Tensor<1, dim> > analytical_solution_gradient (n_q_points);\n  std::vector<Tensor<1, dim> > fe_solution_gradient (n_q_points);\n  double Error = 0.0;\n\n  typename DoFHandler<dim>::active_cell_iterator\n  cell = mg_dof_handler.begin_active(),\n  endc = mg_dof_handler.end();\n  for (; cell!=endc; ++cell)\n    if (cell->is_locally_owned())\n      {\n        fe_values.reinit (cell);\n        fe_values.get_function_gradients (fe_solution, fe_solution_gradient);\n\n        Assert(n_q_points == fe_values.get_quadrature_points().size(), ExcInternalError());\n        exact_solution->gradient_list (fe_values.get_quadrature_points(), analytical_solution_gradient);\n\n        for (unsigned int q_point = 0; q_point < n_q_points; ++q_point)\n          {\n            const Tensor<1, dim, double> &temp_Tensor = fe_solution_gradient[q_point] - analytical_solution_gradient[q_point];\n            Error += temp_Tensor.norm_square() * fe_values.JxW(q_point);\n          }\n      }\n  Error = Utilities::MPI::sum (Error, MPI_COMM_WORLD);\n  pcout << \"Error in FE solution in energy norm:  \" << std::sqrt(Error) << std::endl;\n}\n\ntemplate <int dim>\nvoid LaplaceProblem<dim>::run ()\n{\n  pcout << \"Running with \"\n#ifdef USE_PETSC_LA\n        << \"PETSc\"\n#else\n        << \"Trilinos\"\n#endif\n        << \" on \"\n        << Utilities::MPI::n_mpi_processes(MPI_COMM_WORLD)\n        << \" MPI rank(s)...\" << std::endl;\n\n  computing_timer.reset();\n\n  Timer timer_test (triangulation.get_communicator(), true);\n\n  pcout << \"Dimension:\t\" << dim << std::endl;\n  Timer timer;\n  read_lammps_input_file(LammpsInputFilename);\n\n  for (unsigned int cycle=0; cycle<number_of_adaptive_refinement_cycles; ++cycle)\n    {\n      timer.start();\n\n      pcout << \"Cycle \" << cycle << ':' << std::endl;\n\n      if (cycle == 0)\n        {\n          if (Problemtype == \"Step16\")\n            {\n              // For Step16 Test edit the domain size in step-16.cc to unit lattice\n              // and add some global refinements too\n              GridGenerator::hyper_cube (triangulation,domain_size_left,domain_size_right); // 1 cell i.e. 2^(0*dim)\n              triangulation.refine_global (number_of_global_refinement);  // formula: 2^(num * dim)\n            }\n\n          if (Problemtype == \"GaussianCharges\")\n            {\n              // Here domain_left and right need to be according to the LAMMPS atom file xlo and xhi\n              // Need to set #Global_ref = 0\n              const double a = 2 * mesh_size_h;\n              const double N = (domain_size_right - domain_size_left) / a;  // N = | left - right |/ 2h\n              const double M = repetitions_for_vacuum; // Setting the vaccum around the lattice in terms of a\n              const double repetitions_in_each_direction = 2 * (N + 2 * M);   // in terms of 'h' grid size, h = a/2\n              std::vector< unsigned int > repetitions;\n              repetitions.push_back (repetitions_in_each_direction);\n              if (dim >= 2)\n                repetitions.push_back (repetitions_in_each_direction);\n              if (dim >= 3)\n                repetitions.push_back (repetitions_in_each_direction);\n\n              const Point<dim> lower_left = (dim == 2\n                                             ?\n                                             Point<dim> (domain_size_left - (M *a), domain_size_left - (M *a))\n                                             :\n                                             Point<dim> (domain_size_left - (M *a), domain_size_left - (M *a), domain_size_left - (M *a)));\n              const Point<dim> upper_right = (dim == 2\n                                              ?\n                                              Point<dim> (domain_size_right + (M *a), domain_size_right + (M *a))\n                                              :\n                                              Point<dim> (domain_size_right + (M *a), domain_size_right + (M *a), domain_size_right + (M *a)));\n\n              GridGenerator::subdivided_hyper_rectangle (triangulation, repetitions, lower_left, upper_right, false);\n            }\n        }\n      else\n        refine_grid (cycle);\n\n      pcout << \"   Number of active cells:       \"<< triangulation.n_global_active_cells() << std::endl;\n\n      if (cycle == 0)\n        setup_system (cycle);\n\n      pcout << \"   Number of degrees of freedom: \" << mg_dof_handler.n_dofs() << \" (by level: \";\n      for (unsigned int level=0; level<triangulation.n_global_levels(); ++level)\n        pcout << mg_dof_handler.n_dofs(level) << (level == triangulation.n_global_levels()-1 ? \")\" : \", \");\n      pcout << std::endl;\n\n      if (dim == 2)\n        grid_output_debug(cycle);\n\n      assemble_system ();\n\n      if (PreconditionerType == \"GMG\")\n        assemble_multigrid ();\n\n      solve ();\n\n      estimate_error_and_mark_cells();\n      output_results (cycle);\n      if (number_of_atoms < 300)\n        postprocess_electrostatic_energy();\n      postprocess_error_in_energy_norm();\n\n      timer.stop();\n//  pcout << \"   Elapsed wall time for refinement cycle \"<<cycle <<\" : \" << timer.wall_time() << \" seconds.\"<<std::endl;\n      timer.reset();\n    }\n\n  if (flag_output_time)\n    computing_timer.print_summary();\n  computing_timer.reset();\n\n  timer_test.stop();\n  if (flag_output_time)\n    pcout << \"   \\nTotal Elapsed wall time for solution: \" << timer_test.wall_time() << \" seconds.\\n\"<<std::endl;\n  timer_test.reset();\n\n\n}\n\n\n//explicit instantiation for template class\ntemplate class Step50::LaplaceProblem<2>;\ntemplate class Step50::LaplaceProblem<3>;\n", "meta": {"hexsha": "8bf2022ebe067056c404267e6d1b110369416d04", "size": 64252, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/step-50.cc", "max_stars_repo_name": "vinayak-gholap1993/Dealii-Project", "max_stars_repo_head_hexsha": "57cd408b464bf390cd225be592db20430f79863b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/step-50.cc", "max_issues_repo_name": "vinayak-gholap1993/Dealii-Project", "max_issues_repo_head_hexsha": "57cd408b464bf390cd225be592db20430f79863b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/step-50.cc", "max_forks_repo_name": "vinayak-gholap1993/Dealii-Project", "max_forks_repo_head_hexsha": "57cd408b464bf390cd225be592db20430f79863b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-11-27T11:49:39.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-27T11:49:39.000Z", "avg_line_length": 40.6915769474, "max_line_length": 209, "alphanum_fraction": 0.6166500654, "num_tokens": 14661, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.6224593452091672, "lm_q1q2_score": 0.3427307002184103}}
{"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_VECTOR_HPP_\n#define SMOOTH__MANIFOLD_VECTOR_HPP_\n\n#include <Eigen/Sparse>\n#include <numeric>\n\n#include \"concepts.hpp\"\n\nnamespace smooth {\n\n/**\n * @brief \\p std::vector based Manifold container.\n *\n * Convenient to treat a collection\n * \\f[\n *   m = (m_1, m_2, ..., m_k) \\in M \\times M \\times ... \\times M\n * \\f]\n * of Manifold elements as a single Manifold element \\f$m\\f$.\n *\n * @warning calling `size()` on a `ManifoldVector` returns\n * the degrees of freedom of \\f$M \\times M \\times \\ldots \\times M\\f$, NOT the\n * number of elements in the vector. For the latter,\n * use `vector_size()`.\n */\ntemplate<Manifold M, template<typename> typename Allocator = std::allocator>\nclass ManifoldVector : public std::vector<M, Allocator<M>>\n{\nprivate:\n  using Base = std::vector<M, Allocator<M>>;\n\npublic:\n  //! Degrees of freedom of manifold (equal to tangent space dimentsion)\n  static constexpr Eigen::Index SizeAtCompileTime = -1;\n  //! Plain return type\n  using PlainObject = ManifoldVector<M, Allocator>;\n  //! Scalar type\n  using Scalar = typename M::Scalar;\n\n  //! Default constructor of empty ManifoldVector\n  ManifoldVector()                         = default;\n  //! Copy constructor\n  ManifoldVector(const ManifoldVector & o) = default;\n  //! Move constructor\n  ManifoldVector(ManifoldVector && o)      = default;\n  //! Copy assignment operator\n  ManifoldVector & operator=(const ManifoldVector & o) = default;\n  //! Move assignment operator\n  ManifoldVector & operator=(ManifoldVector && o) = default;\n  ~ManifoldVector()                               = default;\n\n  /**\n   * Forwarding constructor to std::vector.\n   */\n  template<typename... Ts>\n  ManifoldVector(Ts &&... ts) : Base(std::forward<Ts>(ts)...)\n  {}\n\n  /**\n   * @brief Cast to different scalar type.\n   */\n  template<typename NewScalar>\n  auto cast() const\n  {\n    using CastT = typename decltype(M{}.template cast<NewScalar>())::PlainObject;\n    ManifoldVector<CastT, Allocator> ret;\n    ret.reserve(vector_size());\n    std::transform(this->begin(), this->end(), std::back_insert_iterator(ret), [](const auto & x) {\n      return x.template cast<NewScalar>();\n    });\n    return ret;\n  }\n\n  /**\n   * @brief Number of elements in ManifoldVector.\n   */\n  std::size_t vector_size() const { return Base::size(); }\n\n  /**\n   * @brief Runtime degrees of freedom.\n   *\n   * Sum of the degrees of freedom of constituent elements.\n   */\n  Eigen::Index size() const\n  {\n    if constexpr (M::SizeAtCompileTime > 0) {\n      return vector_size() * M::SizeAtCompileTime;\n    } else {\n      return std::accumulate(this->begin(), this->end(), 0u, [](auto & v1, const auto & item) {\n        return v1 + item.size();\n      });\n    }\n  }\n\n  /**\n   * @brief In-place addition.\n   *\n   * @note It must hold that size() == a.size()\n   */\n  template<typename Derived>\n  PlainObject & operator+=(const Eigen::MatrixBase<Derived> & a)\n  {\n    Eigen::Index idx = 0;\n    for (auto i = 0u; i != this->vector_size(); ++i) {\n      const auto size_i = this->operator[](i).size();\n      this->operator[](i) += a.template segment<M::SizeAtCompileTime>(idx, size_i);\n      idx += size_i;\n    }\n    return *this;\n  }\n\n  /**\n   * @brief Addition.\n   *\n   * @note It must hold that `size() == a.size()`\n   */\n  template<typename Derived>\n  PlainObject operator+(const Eigen::MatrixBase<Derived> & a) const\n  {\n    PlainObject ret = *this;\n    ret += a;\n    return ret;\n  }\n\n  /**\n   * @brief Subtraction.\n   *\n   * @note It must hold that `size() == o.size()`\n   */\n  Eigen::Matrix<Scalar, -1, 1> operator-(const PlainObject & o) const\n  {\n    std::size_t dof = 0;\n    if (M::SizeAtCompileTime > 0) {\n      dof = M::SizeAtCompileTime * vector_size();\n    } else {\n      for (auto i = 0u; i != vector_size(); ++i) { dof += this->operator[](i).size(); }\n    }\n\n    Eigen::Matrix<Scalar, -1, 1> ret(dof);\n    Eigen::Index idx = 0;\n    for (auto i = 0u; i != vector_size(); ++i) {\n      const auto & size_i                                     = this->operator[](i).size();\n      ret.template segment<M::SizeAtCompileTime>(idx, size_i) = this->operator[](i) - o[i];\n      idx += size_i;\n    }\n\n    return ret;\n  }\n};\n\n}  // namespace smooth\n\ntemplate<typename Stream, typename M, template<typename> typename Allocator>\nStream & operator<<(Stream & s, const smooth::ManifoldVector<M, Allocator> & g)\n{\n  s << \"ManifoldVector with \" << g.vector_size() << \" elements:\" << std::endl;\n  for (auto i = 0u; i != g.vector_size(); ++i) {\n    s << i << \": \" << g[i];\n    if (i != g.vector_size() - 1) { s << std::endl; }\n  }\n  return s;\n}\n\n#endif  // SMOOTH__MANIFOLD_VECTOR_HPP_\n", "meta": {"hexsha": "8f510094ff772efab43a2a122c777174290a6f7e", "size": 5881, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/smooth/manifold_vector.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/manifold_vector.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/manifold_vector.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": 31.1164021164, "max_line_length": 99, "alphanum_fraction": 0.6429178711, "num_tokens": 1535, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6224593312018546, "lm_q2_score": 0.5506073655352404, "lm_q1q2_score": 0.3427306925058808}}
{"text": "//---------------------------------------------------------------------------//\n// Copyright (c) 2018-2020 Mikhail Komarov <nemo@nil.foundation>\n// Copyright (c) 2020 Pavel Kharitonov <ipavrus@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_TIGER_HPP\n#define CRYPTO3_HASH_TIGER_HPP\n\n#include <boost/crypto3/hash/detail/tiger/tiger_policy.hpp>\n\n#include <boost/crypto3/hash/detail/merkle_damgard_construction.hpp>\n#include <boost/crypto3/hash/detail/tiger/tiger_padding.hpp>\n#include <boost/crypto3/hash/detail/block_stream_processor.hpp>\n\nnamespace boost {\n    namespace crypto3 {\n        namespace hashes {\n\n            template<std::size_t DigestBits = 192, std::size_t Passes = 3>\n            struct tiger_compressor {\n                typedef detail::tiger_policy<DigestBits, Passes> 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 state_bits = policy_type::state_bits;\n                constexpr static const std::size_t state_words = policy_type::state_words;\n                typedef typename policy_type::state_type state_type;\n\n                constexpr static const std::size_t block_bits = policy_type::block_bits;\n                constexpr static const std::size_t block_words = policy_type::block_words;\n                typedef typename policy_type::block_type block_type;\n\n                static inline void process_block(state_type &state, const block_type &block) {\n\n                    word_type A = state[0], B = state[1], C = state[2];\n                    block_type input = block;\n                    policy_type::pass(A, B, C, input, 5);\n                    policy_type::mix(input);\n                    policy_type::pass(C, A, B, input, 7);\n                    policy_type::mix(input);\n                    policy_type::pass(B, C, A, input, 9);\n\n                    for (size_t j = 3; j != policy_type::passes; ++j) {\n                        policy_type::mix(input);\n                        policy_type::pass(A, B, C, input, 9);\n                        word_type T = A;\n                        A = C;\n                        C = B;\n                        B = T;\n                    }\n\n                    state[0] ^= A;\n                    state[1] = B - state[1];\n                    state[2] += C;\n                }\n            };\n\n            /*!\n             * @brief Tiger. An older 192-bit hashes function, optimized for 64-bit\n             * systems. Possibly vulnerable to side channels due to its use of table\n             * lookups. Prefer Skein-512 or BLAKE2b in new code.\n             *\n             * @ingroup hashes\n             */\n            template<std::size_t DigestBits = 192, std::size_t Passes = 3>\n            class tiger {\n                typedef detail::tiger_policy<DigestBits, Passes> policy_type;\n\n            public:\n                struct construction {\n                    struct params_type {\n                        typedef typename policy_type::digest_endian digest_endian;\n\n                        constexpr static const std::size_t length_bits = policy_type::word_bits;\n                        constexpr static const std::size_t digest_bits = policy_type::digest_bits;\n                    };\n\n                    typedef merkle_damgard_construction<params_type, typename policy_type::iv_generator,\n                                                        tiger_compressor<DigestBits, Passes>,\n                                                        detail::tiger_padding<policy_type>>\n                        type;\n                };\n\n                template<typename StateAccumulator, std::size_t ValueBits>\n                struct stream_processor {\n                    struct params_type {\n                        typedef typename policy_type::digest_endian digest_endian;\n\n                        constexpr static const std::size_t value_bits = ValueBits;\n                    };\n\n                    typedef block_stream_processor<construction, StateAccumulator, params_type> type;\n                };\n\n                constexpr static const std::size_t digest_bits = policy_type::digest_bits;\n                typedef typename policy_type::digest_type digest_type;\n            };\n        }    // namespace hashes\n    }        // namespace crypto3\n}    // namespace boost\n\n#endif\n", "meta": {"hexsha": "123e6773b5635dbcd782bc782dd66c6154c3ca0d", "size": 4633, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/crypto3/hash/tiger.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/tiger.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/tiger.hpp", "max_forks_repo_name": "NilFoundation/boost-crypto", "max_forks_repo_head_hexsha": "a3e599b780bbbbc063b7c8da0e498125769e08be", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-02-13T21:14:37.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-13T21:14:37.000Z", "avg_line_length": 42.8981481481, "max_line_length": 104, "alphanum_fraction": 0.5346427801, "num_tokens": 890, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7371581510799253, "lm_q2_score": 0.46490157137338844, "lm_q1q2_score": 0.342705982787759}}
{"text": "/*\nCopyright 2016-2017 Robotics and Biology Lab, TU Berlin. All 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\nTHIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR 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\nThe views and conclusions contained in the software and documentation are those of the authors and should not be interpreted as representing official policies, either expressed or implied, of the FreeBSD Project.\n*/ \n\n#include <ecto_rbo_grasping/PoseSet.h>\n\n#include <tf_conversions/tf_eigen.h>\n#include <Eigen/Geometry>\n\n#include <CGAL/Gmpz.h>\n#include <CGAL/Extended_homogeneous.h>\n#include <CGAL/Exact_predicates_exact_constructions_kernel.h>\n#include <CGAL/Nef_polyhedron_3.h>\n\n#include \"Wm5IntrSegment3Box3.h\"\n#include \"Wm5IntrBox3Box3.h\"\n#include \"Wm5ContMinBox3.h\"\n\n#include <ecto_rbo_grasping/gdiam.hpp>\n\n//typedef CGAL::Exact_predicates_exact_constructions_kernel Kernel;\n//typedef CGAL::Extended_homogeneous<CGAL::Gmpz>  Kernel;\ntypedef CGAL::Extended_cartesian< CGAL::Lazy_exact_nt<CGAL::Gmpq> > Kernel;\ntypedef CGAL::Nef_polyhedron_3<Kernel>  Nef_polyhedron;\ntypedef Nef_polyhedron::Vertex_const_iterator Vertex_const_iterator;\ntypedef Nef_polyhedron::Plane_3  Plane_3;\ntypedef Nef_polyhedron::Point_3  Point_3;\ntypedef Nef_polyhedron::Vector_3  Vector_3;\n\nnamespace posesets\n{\n\nPoseSet::PoseSet(const tf::Transform& origin) :\n    origin(origin)\n{\n}\n\nPoseSet::~PoseSet()\n{\n}\n\nvoid PoseSet::updateBoxVertices(Wm5::Vector3d box_vertices[8], Wm5::Segment3d edges[12]) const\n{\n    Wm5::Vector3d origin_a(this->origin.getOrigin().x(), this->origin.getOrigin().y(), this->origin.getOrigin().z());\n    //    Wm5::Vector3d dim_a[3] = { Wm5::Vector3d(a.getBasis().getRow(0).x(), a.getBasis().getRow(0).y(), a.getBasis().getRow(0).z()),\n    //                               Wm5::Vector3d(a.getBasis().getRow(1).x(), a.getBasis().getRow(1).y(), a.getBasis().getRow(1).z()),\n    //                               Wm5::Vector3d(a.getBasis().getRow(2).x(), a.getBasis().getRow(2).y(), a.getBasis().getRow(2).z()) };\n    Wm5::Vector3d dim_a[3] = { Wm5::Vector3d(this->origin.getBasis().getColumn(0).x(), this->origin.getBasis().getColumn(0).y(), this->origin.getBasis().getColumn(0).z()),\n                               Wm5::Vector3d(this->origin.getBasis().getColumn(1).x(), this->origin.getBasis().getColumn(1).y(), this->origin.getBasis().getColumn(1).z()),\n                               Wm5::Vector3d(this->origin.getBasis().getColumn(2).x(), this->origin.getBasis().getColumn(2).y(), this->origin.getBasis().getColumn(2).z()) };\n    double size_a[3] = {0.5 * this->getPositions()[0], 0.5 * this->getPositions()[1], 0.5 * this->getPositions()[2]};\n\n    Wm5::Box3d box_a(origin_a, dim_a, size_a);\n    box_a.ComputeVertices(box_vertices);\n\n    edges[0] = Wm5::Segment3d(box_vertices[0], box_vertices[1]);\n    edges[1] = Wm5::Segment3d(box_vertices[0], box_vertices[3]);\n    edges[2] = Wm5::Segment3d(box_vertices[0], box_vertices[4]);\n    edges[3] = Wm5::Segment3d(box_vertices[1], box_vertices[2]);\n    edges[4] = Wm5::Segment3d(box_vertices[1], box_vertices[5]);\n    edges[5] = Wm5::Segment3d(box_vertices[2], box_vertices[6]);\n    edges[6] = Wm5::Segment3d(box_vertices[2], box_vertices[3]);\n    edges[7] = Wm5::Segment3d(box_vertices[3], box_vertices[7]);\n    edges[8] = Wm5::Segment3d(box_vertices[4], box_vertices[7]);\n    edges[9] = Wm5::Segment3d(box_vertices[4], box_vertices[5]);\n    edges[10] = Wm5::Segment3d(box_vertices[5], box_vertices[6]);\n    edges[11] = Wm5::Segment3d(box_vertices[6], box_vertices[7]);\n}\n\nvoid PoseSet::setOrigin(const tf::Transform& origin)\n{\n    this->origin = origin;\n}\n\nvoid PoseSet::setOrientations(const OrientationSet& orientations)\n{\n    this->orientations = orientations;\n}\n\nvoid PoseSet::setPositions(const tf::Vector3& positions)\n{\n    this->positions = positions;\n}\n\nconst tf::Transform& PoseSet::getOrigin() const\n{\n    return origin;\n}\n\nOrientationSet& PoseSet::getOrientations()\n{\n    return orientations;\n}\n\nconst OrientationSet& PoseSet::getOrientations() const\n{\n    return orientations;\n}\n\nconst tf::Vector3& PoseSet::getPositions() const\n{\n    return positions;\n}\n\nWm5::Box3d PoseSet::getWm5Box3d() const\n{\n    Wm5::Vector3d origin_a(origin.getOrigin().x(), origin.getOrigin().y(), origin.getOrigin().z());\n    Wm5::Vector3d dim_a[3] = { Wm5::Vector3d(origin.getBasis().getColumn(0).x(), origin.getBasis().getColumn(0).y(), origin.getBasis().getColumn(0).z()),\n                               Wm5::Vector3d(origin.getBasis().getColumn(1).x(), origin.getBasis().getColumn(1).y(), origin.getBasis().getColumn(1).z()),\n                               Wm5::Vector3d(origin.getBasis().getColumn(2).x(), origin.getBasis().getColumn(2).y(), origin.getBasis().getColumn(2).z()) };\n    double size_a[3] = {0.5 * positions[0], 0.5 * positions[1], 0.5 * positions[2]};\n\n    return Wm5::Box3d(origin_a, dim_a, size_a);\n}\n\nbool PoseSet::isIntersecting(const PoseSet& other) const\n{\n//    if (this->orientations.getIntersection(other.getOrientations()).empty())\n    if (!this->orientations.hasIntersection(other.getOrientations()))\n    {\n//        std::cout << \"orientation false \" << std::endl;\n        return false;\n    }\n\n    Wm5::IntrBox3Box3d intersector(this->getWm5Box3d(), other.getWm5Box3d());\n\n//    if (!intersector.Test())\n//        std::cout << \"position false \" << std::endl;\n\n    return intersector.Test();\n}\n\nbool PoseSet::intersect(const PoseSet& other)\n{\n    this->orientations.intersect(other.getOrientations());\n\n    if (this->orientations.empty())\n        return false;\n\n    return intersectBoxesGeometricTools(this->origin, this->positions, other.getOrigin(), other.getPositions(), this->origin, this->positions);\n\n    /*\n    if (intersectBoxes(this->origin, this->positions, other.getOrigin(), other.getPositions()))\n    {\n        ROS_INFO(\"Intersection! (maybe)\");\n//        this->origin.setOrigin(origin.getOrigin().lerp(other.getOrigin().getOrigin(), 0.5));\n//        this->positions.setMin(other.getPositions());\n    }\n    else {\n        ROS_INFO(\"They DONT intersect!\");\n        this->origin.setIdentity();\n        this->positions.setZero();\n    }\n    */\n}\n\n\nbool PoseSet::intersectBoxesGeometricTools(const tf::Transform& a, const tf::Vector3& extents_a, const tf::Transform& b, const tf::Vector3& extents_b, tf::Transform& n, tf::Vector3& extents_n)\n{\n    Wm5::Vector3d origin_a(a.getOrigin().x(), a.getOrigin().y(), a.getOrigin().z());\n//    Wm5::Vector3d dim_a[3] = { Wm5::Vector3d(a.getBasis().getRow(0).x(), a.getBasis().getRow(0).y(), a.getBasis().getRow(0).z()),\n//                               Wm5::Vector3d(a.getBasis().getRow(1).x(), a.getBasis().getRow(1).y(), a.getBasis().getRow(1).z()),\n//                               Wm5::Vector3d(a.getBasis().getRow(2).x(), a.getBasis().getRow(2).y(), a.getBasis().getRow(2).z()) };\n    Wm5::Vector3d dim_a[3] = { Wm5::Vector3d(a.getBasis().getColumn(0).x(), a.getBasis().getColumn(0).y(), a.getBasis().getColumn(0).z()),\n                               Wm5::Vector3d(a.getBasis().getColumn(1).x(), a.getBasis().getColumn(1).y(), a.getBasis().getColumn(1).z()),\n                               Wm5::Vector3d(a.getBasis().getColumn(2).x(), a.getBasis().getColumn(2).y(), a.getBasis().getColumn(2).z()) };\n    double size_a[3] = {0.5 * extents_a[0], 0.5 * extents_a[1], 0.5 * extents_a[2]};\n\n    Wm5::Vector3d origin_b(b.getOrigin().x(), b.getOrigin().y(), b.getOrigin().z());\n//    Wm5::Vector3d dim_b[3] = { Wm5::Vector3d(b.getBasis().getRow(0).x(), b.getBasis().getRow(0).y(), b.getBasis().getRow(0).z()),\n//                               Wm5::Vector3d(b.getBasis().getRow(1).x(), b.getBasis().getRow(1).y(), b.getBasis().getRow(1).z()),\n//                               Wm5::Vector3d(b.getBasis().getRow(2).x(), b.getBasis().getRow(2).y(), b.getBasis().getRow(2).z()) };\n    Wm5::Vector3d dim_b[3] = { Wm5::Vector3d(b.getBasis().getColumn(0).x(), b.getBasis().getColumn(0).y(), b.getBasis().getColumn(0).z()),\n                               Wm5::Vector3d(b.getBasis().getColumn(1).x(), b.getBasis().getColumn(1).y(), b.getBasis().getColumn(1).z()),\n                               Wm5::Vector3d(b.getBasis().getColumn(2).x(), b.getBasis().getColumn(2).y(), b.getBasis().getColumn(2).z()) };\n    double size_b[3] = {0.5 * extents_b[0], 0.5 * extents_b[1], 0.5 * extents_b[2]};\n\n    Wm5::Box3d box_a(origin_a, dim_a, size_a);\n    Wm5::Box3d box_b(origin_b, dim_b, size_b);\n    Wm5::IntrBox3Box3d intersector(box_a, box_b);\n\n    if (!intersector.Test())\n    {\n        //ROS_INFO(\"NO intersection.\");\n        n.setIdentity();\n        extents_n.setZero();\n        return false;\n    }\n\n    // do static check differently:\n    // check intersections between 12 edges (segments) of one box with the other box\n    intersection_points.clear();\n//    std::vector<Wm5::Vector3d> intersection_points;\n    for (int l = 0; l < 2; ++l)\n    {\n        const Wm5::Box3d& box = (l == 0) ? box_a : box_b;\n        const Wm5::Box3d& other_box = (l == 1) ? box_a : box_b;\n\n        Wm5::Vector3d vertices[8];\n        box.ComputeVertices(vertices);\n\n//        if (l == 0)\n//            for (int k = 0; k < 8; ++k)\n//                this->box_vertices[k] = vertices[k];\n\n        Wm5::Segment3d edges[12] = {\n            Wm5::Segment3d(vertices[0], vertices[1]),\n            Wm5::Segment3d(vertices[0], vertices[3]),\n            Wm5::Segment3d(vertices[0], vertices[4]),\n            Wm5::Segment3d(vertices[1], vertices[2]),\n            Wm5::Segment3d(vertices[1], vertices[5]),\n            Wm5::Segment3d(vertices[2], vertices[6]),\n            Wm5::Segment3d(vertices[2], vertices[3]),\n            Wm5::Segment3d(vertices[3], vertices[7]),\n            Wm5::Segment3d(vertices[4], vertices[7]),\n            Wm5::Segment3d(vertices[4], vertices[5]),\n            Wm5::Segment3d(vertices[5], vertices[6]),\n            Wm5::Segment3d(vertices[6], vertices[7])\n        };\n\n        for (int i = 0; i < 12; ++i)\n        {\n            Wm5::IntrSegment3Box3d intersector2(edges[i], other_box, true);\n            if (!intersector2.Find())\n                continue;\n\n            int no_intersections = intersector2.GetQuantity();\n\n    //        std::cout << \"Found: \" << no_intersections << std::endl;\n            for (int j = 0; j < no_intersections; ++j)\n            {\n//                bool already_in_there = false;\n                const Wm5::Vector3d& candidate = intersector2.GetPoint(j);\n//                // check if for some reasons this point is already in there\n//                for (int k = 0; k < intersection_points.size(); ++k)\n//                {\n//                    if (fabs(candidate.X() - intersection_points[k].X()) < 0.001f ||\n//                        fabs(candidate.Y() - intersection_points[k].Y()) < 0.001f ||\n//                        fabs(candidate.Z() - intersection_points[k].Z()) < 0.001f)\n//                    {\n//                        already_in_there = true;\n//                        break;\n//                    }\n//                }\n//                if (!already_in_there)\n                    intersection_points.push_back(intersector2.GetPoint(j));\n            }\n        }\n    }\n    \n    /*\n    std::cout << \"In Total: \" << intersection_points.size() << std::endl;\n    for (std::vector<Wm5::Vector3d>::iterator it = intersection_points.begin(); it != intersection_points.end(); ++it)\n    {\n        std::cout << \" (\" << it->X() << \" \" << it->Y() << \" \" << it->Z() << \")\";\n    }\n    std::cout << std::endl;\n    */\n    \n    if (intersection_points.size() < 4)\n    {\n        n.setIdentity();\n        extents_n.setZero();\n        return false;\n    }\n\n//    Wm5::Box3d minBox = Wm5::MinBox3<double>((int) intersection_points.size(), &intersection_points[0], 0.001, Wm5::Query::QT_REAL);\n\n//    n.setBasis(tf::Matrix3x3(minBox.Axis[0].X(), minBox.Axis[0].Y(), minBox.Axis[0].Z(),\n//                             minBox.Axis[1].X(), minBox.Axis[1].Y(), minBox.Axis[1].Z(),\n//                             minBox.Axis[2].X(), minBox.Axis[2].Y(), minBox.Axis[2].Z()));\n\n//    n.setOrigin(tf::Vector3(minBox.Center.X(), minBox.Center.Y(), minBox.Center.Z()));\n\n//    std::cout << \"New Box extents: \" << extents_n[0] << \" \" << extents_n[1] << \" \" << extents_n[2] << std::endl;\n\n//    extents_n.setX(minBox.Extent[0]);\n//    extents_n.setY(minBox.Extent[1]);\n//    extents_n.setZ(minBox.Extent[2]);\n\n//    if (extents_n[0] == 0 || extents_n[1] == 0 || extents_n[2] == 0)\n//    {\n//        n.setIdentity();\n//        extents_n.setZero();\n//        return false;\n//    }\n\n\n//    intersector.Find(0.0, Wm5::Vector3d::ZERO, Wm5::Vector3d::ZERO);\n//    intersector.Find(0.1, Wm5::Vector3d(0.1, 0.1, 0.1), Wm5::Vector3d(0.1, 0.1, 0.1));\n//    int number_of_intersection_points = intersector.GetQuantity();\n\n//    std::cout << \"Number of intersection points: \" << number_of_intersection_points << std::endl;\n//    if (number_of_intersection_points == 0)\n//    {\n//        n.setIdentity();\n//        extents_n.setZero();\n//        return false;\n//    }\n\n    gdiam_real* points;\n    points = (gdiam_point)malloc( sizeof( gdiam_point_t ) * intersection_points.size());\n\n    for (int i = 0; i < intersection_points.size(); ++i)\n    {\n        const Wm5::Vector3d& p = intersection_points[i];\n        points[i * 3 + 0] = p.X();\n        points[i * 3 + 1] = p.Y();\n        points[i * 3 + 2] = p.Z();\n//        std::cout << \"HA: \" << p.X() << \" \" << p.Y() << \" \" << p.Z() << std::endl;\n    }\n\n    gdiam_point* pnt_arr;\n    gdiam_bbox bb;\n    pnt_arr = gdiam_convert( (gdiam_real *)points, intersection_points.size());\n\n//    printf( \"Computing a tight-fitting bounding box of the point-set\\n\" );\n//    bb = gdiam_approx_mvbb_grid_sample(pnt_arr, nefI.number_of_vertices(), 5, 400 );\n    bb = gdiam_approx_mvbb(pnt_arr, intersection_points.size(), 0.01f);\n\n    //printf( \"Resulting bounding box:\\n\" );\n    bb.dump();\n\n    gdiam_point bb_dir0 = bb.get_dir(0);\n    gdiam_point bb_dir1 = bb.get_dir(1);\n    gdiam_point bb_dir2 = bb.get_dir(2);\n\n    n.setBasis(tf::Matrix3x3(bb_dir0[0], bb_dir1[0], bb_dir2[0],\n                             bb_dir0[1], bb_dir1[1], bb_dir2[1],\n                             bb_dir0[2], bb_dir1[2], bb_dir2[2]));\n\n    double x, y, z;\n    bb.get_vertex(0.5, 0.5, 0.5, &x, &y, &z);\n    n.setOrigin(tf::Vector3(x, y, z));\n\n    extents_n.setX(bb.get_len(0) * 1.f);\n    extents_n.setY(bb.get_len(1) * 1.f);\n    extents_n.setZ(bb.get_len(2) * 1.f);\n\n//    if (extents_n[0] == 0 || extents_n[1] == 0 || extents_n[2] == 0)\n    if (bb.volume() == 0)\n    {\n        //ROS_INFO(\"Too Small!\");\n        n.setIdentity();\n        extents_n.setZero();\n        return false;\n    }\n\n    return true;\n}\n\nvoid PoseSet::intersectBoxesCGAL(const tf::Transform& a, const tf::Vector3& extents_a, const tf::Transform& b, const tf::Vector3& extents_b, tf::Transform& n, tf::Vector3& extents_n)\n{\n    // generate a Nef Polyhedron for box A\n    Point_3 origin_a(a.getOrigin().x(), a.getOrigin().x(), a.getOrigin().x());\n    Vector_3 dim1_a(a.getBasis().getRow(0).x(), a.getBasis().getRow(0).y(), a.getBasis().getRow(0).z());\n    Vector_3 dim2_a(a.getBasis().getRow(1).x(), a.getBasis().getRow(1).y(), a.getBasis().getRow(1).z());\n    Vector_3 dim3_a(a.getBasis().getRow(2).x(), a.getBasis().getRow(2).y(), a.getBasis().getRow(2).z());\n    Nef_polyhedron NA1(Plane_3(origin_a + dim1_a * extents_a[0], dim1_a), Nef_polyhedron::INCLUDED);\n    Nef_polyhedron NA2(Plane_3(origin_a - dim1_a * extents_a[0], -dim1_a), Nef_polyhedron::INCLUDED);\n    Nef_polyhedron NA3(Plane_3(origin_a + dim2_a * extents_a[1], dim2_a), Nef_polyhedron::INCLUDED);\n    Nef_polyhedron NA4(Plane_3(origin_a - dim2_a * extents_a[1], -dim2_a), Nef_polyhedron::INCLUDED);\n    Nef_polyhedron NA5(Plane_3(origin_a + dim3_a * extents_a[2], dim3_a), Nef_polyhedron::INCLUDED);\n    Nef_polyhedron NA6(Plane_3(origin_a - dim3_a * extents_a[2], -dim3_a), Nef_polyhedron::INCLUDED);\n\n//    Nef_polyhedron nefA = NA1 * NA2 * NA3 * NA4 * NA5 * NA6;\n\n    // generate a Nef Polyhedron for box B\n    Point_3 origin_b(b.getOrigin().x(), b.getOrigin().x(), b.getOrigin().x());\n    Vector_3 dim1_b(b.getBasis().getRow(0).x(), b.getBasis().getRow(0).y(), b.getBasis().getRow(0).z());\n    Vector_3 dim2_b(b.getBasis().getRow(1).x(), b.getBasis().getRow(1).y(), b.getBasis().getRow(1).z());\n    Vector_3 dim3_b(b.getBasis().getRow(2).x(), b.getBasis().getRow(2).y(), b.getBasis().getRow(2).z());\n    Nef_polyhedron NB1(Plane_3(origin_b + dim1_b * extents_b[0], dim1_b), Nef_polyhedron::INCLUDED);\n    Nef_polyhedron NB2(Plane_3(origin_b - dim1_b * extents_b[0], -dim1_b), Nef_polyhedron::INCLUDED);\n    Nef_polyhedron NB3(Plane_3(origin_b + dim2_b * extents_b[1], dim2_b), Nef_polyhedron::INCLUDED);\n    Nef_polyhedron NB4(Plane_3(origin_b - dim2_b * extents_b[1], -dim2_b), Nef_polyhedron::INCLUDED);\n    Nef_polyhedron NB5(Plane_3(origin_b + dim3_b * extents_b[2], dim3_b), Nef_polyhedron::INCLUDED);\n    Nef_polyhedron NB6(Plane_3(origin_b - dim3_b * extents_b[2], -dim3_b), Nef_polyhedron::INCLUDED);\n\n//    Nef_polyhedron nefB = NB1 * NB2 * NB3 * NB4 * NB5 * NB6;\n\n//    Nef_polyhedron nefI = nefA.intersection(nefB);\n    Nef_polyhedron nefI = NA1 * NA2 * NA3 * NA4 * NA5 * NA6 * NB1 * NB2 * NB3 * NB4 * NB5 * NB6;\n\n    /*\n    std::cout << \"properties: \" << std::endl;\n    std::cout << \"is_simple: \" << nefI.is_simple() << std::endl;\n    std::cout << \"is_bounded: \" << nefI.is_bounded() << std::endl;\n//    std::cout << \"is_convex: \" << nefI.is_convex() << std::endl;\n    std::cout << \"vertices: \" << nefI.number_of_vertices() << std::endl;\n    std::cout << \"is_empty: \" << nefI.is_empty() << std::endl;\n    */\n    \n    if (nefI.is_empty())\n        return;\n\n    Vertex_const_iterator it;\n//    gdiam_point* pnt_arr;// = new gdiam_point[nefI.number_of_vertices()];\n//    pnt_arr = (gdiam_point *)malloc( sizeof( gdiam_point ) * nefI.number_of_vertices());\n    gdiam_real* points;\n    points = (gdiam_point)malloc( sizeof( gdiam_point_t ) * nefI.number_of_vertices());\n\n    size_t i = 0;\n    CGAL_forall_vertices(it, nefI)\n    {\n        //std::cout << CGAL::to_double(it->point().x()) << \" HAH \" << CGAL::to_double(it->point().y()) << \" \" << CGAL::to_double(it->point().z()) << std::endl;\n//        pnt_init((gdiam_point)(pnt_arr[i]), 0, 0, 0);\n        points[i * 3 + 0] = CGAL::to_double(it->point().x());\n        points[i * 3 + 1] = CGAL::to_double(it->point().y());\n        points[i * 3 + 2] = CGAL::to_double(it->point().z());\n//        pnt_init(pnt_arr[i], CGAL::to_double(it->point().x()), CGAL::to_double(it->point().y()), CGAL::to_double(it->point().z()));\n        ++i;\n    }\n\n    gdiam_point* pnt_arr;\n    gdiam_bbox bb;\n    pnt_arr = gdiam_convert( (gdiam_real *)points, nefI.number_of_vertices());\n\n//    printf( \"Computing a tight-fitting bounding box of the point-set\\n\" );\n//    bb = gdiam_approx_mvbb_grid_sample(pnt_arr, nefI.number_of_vertices(), 5, 400 );\n    bb = gdiam_approx_mvbb(pnt_arr, nefI.number_of_vertices(), 0.1f);\n\n    //printf( \"Resulting bounding box:\\n\" );\n    bb.dump();\n\n    gdiam_point bb_dir0 = bb.get_dir(0);\n    gdiam_point bb_dir1 = bb.get_dir(1);\n    gdiam_point bb_dir2 = bb.get_dir(2);\n\n    n.setBasis(tf::Matrix3x3(bb_dir0[0], bb_dir0[1], bb_dir0[2],\n                             bb_dir1[0], bb_dir1[1], bb_dir1[2],\n                             bb_dir2[0], bb_dir2[1], bb_dir2[2]));\n\n    double x, y, z;\n    bb.get_vertex(0.5, 0.5, 0.5, &x, &y, &z);\n    n.setOrigin(tf::Vector3(x, y, z));\n\n    extents_n.setX(bb.get_len(0) * 0.5f);\n    extents_n.setY(bb.get_len(1) * 0.5f);\n    extents_n.setZ(bb.get_len(2) * 0.5f);\n}\n\nvoid PoseSet::intersectBoxes(const tf::Transform& a, const tf::Vector3& extents_a, const tf::Transform& b, const tf::Vector3& extents_b, tf::Transform& n, tf::Vector3& extents_n)\n{\n//    tf::Transform b_a = a.inverseTimes(b);\n//    tf::Transform a_b = b.inverseTimes(a);\n\n//    // do aabb-intersection along axes of a\n//    tf::Matrix3x3 all_dot_products = a.getBasis().transposeTimes(b_a.getBasis());\n//    tf::Vector3 extents_b_a(all_dot_products.getRow(0)[all_dot_products.getRow(0).maxAxis()],\n//                            all_dot_products.getRow(1)[all_dot_products.getRow(1).maxAxis()],\n//                            all_dot_products.getRow(2)[all_dot_products.getRow(2).maxAxis()]);\n//    extents_b_a *= extents_b;\n\n//    // do aabb-intersection along axes of b\n////    all_dot_products = b.getBasis().transposeTimes(a_b.getBasis());\n////    tf::Vector3 extents_a_b(all_dot_products.getRow(0)[all_dot_products.getRow(0).maxAxis()],\n////                            all_dot_products.getRow(1)[all_dot_products.getRow(1).maxAxis()],\n////                            all_dot_products.getRow(2)[all_dot_products.getRow(2).maxAxis()]);\n////    extents_a_b *= extents_a;\n\n////    if (extents_b_a.length2() < extents_a_b.length2())\n////    {\n//        // a is the reference frame\n//        Eigen::Vector3d extents, origin;\n//        tf::vectorTFToEigen(extents_a, extents);\n//        tf::vectorTFToEigen(a.getOrigin(), origin);\n//        Eigen::AlignedBox<float, 3> box_a(origin + extents, origin - extents);\n\n////        Eigen::AlignedBox<float, 3> box_b(v, v);\n\n////        Eigen::AlignedBox<float, 3> box_i = box_a.intersection(box_b);\n\n////        tf::vectorEigenToTF(box_i.center(), n.getOrigin());\n////        tf::vectorEigenToTF(box_i.max(), extents_n);\n////        n.setRotation(a.getRotation());\n////    }\n////    else {\n////        extents_n = (extents_b - extents_a_b).absolute();\n////        n.setOrigin(b.getOrigin() + extents_b - extents_n * 0.5);\n////        n.setRotation(b.getRotation());\n////    }\n}\n\nbool PoseSet::intersectBoxes(const tf::Transform& a, const tf::Vector3& extents_a, const tf::Transform& b, const tf::Vector3& extents_b)\n{\n    tf::Matrix3x3 A = a.getBasis();\n    tf::Matrix3x3 B = b.getBasis();\n\n    //translation, in parent frame\n    tf::Vector3 v = b.getOrigin() - a.getOrigin();\n    //translation, in A's frame\n    tf::Vector3 T(v.dot(A.getColumn(0)), v.dot(A.getColumn(1)), v.dot(A.getColumn(2)));\n\n    //B's basis with respect to A's local frame\n    tf::Matrix3x3 R = A.transposeTimes(B);\n    float ra, rb, t;\n    long i, k;\n\n    //calculate rotation matrix\n//        for( i=0 ; i<3 ; i++ )\n//            for( k=0 ; k<3 ; k++ )\n//                R[i][k] = A.getColumn(i).dot(B.getColumn(k));\n    /*ALGORITHM: Use the separating axis test for all 15 potential\nseparating axes. If a separating axis could not be found, the two\nboxes overlap. */\n\n    //A's basis vectors\n    for( i=0 ; i<3 ; i++ )\n    {\n        ra = extents_a[i];\n        rb = extents_b[0]*fabs(R[i][0]) + extents_b[1]*fabs(R[i][1]) + extents_b[2]*fabs(R[i][2]);\n\n        t = fabs( T[i] );\n\n        if( t > ra + rb )\n            return false;\n    }\n\n    //B's basis vectors\n    for( k=0 ; k<3 ; k++ )\n    {\n        ra = extents_a[0]*fabs(R[0][k]) + extents_a[1]*fabs(R[1][k]) + extents_a[2]*fabs(R[2][k]);\n        rb = extents_b[k];\n\n        t = fabs( T[0]*R[0][k] + T[1]*R[1][k] + T[2]*R[2][k] );\n\n        if( t > ra + rb )\n            return false;\n    }\n\n    //9 cross products\n\n    //L = A0 x B0\n    ra = extents_a[1]*fabs(R[2][0]) + extents_a[2]*fabs(R[1][0]);\n\n    rb = extents_b[1]*fabs(R[0][2]) + extents_b[2]*fabs(R[0][1]);\n\n    t = fabs( T[2]*R[1][0] - T[1]*R[2][0] );\n\n    if( t > ra + rb )\n        return false;\n\n    //L = A0 x B1\n    ra = extents_a[1]*fabs(R[2][1]) + extents_a[2]*fabs(R[1][1]);\n\n    rb = extents_b[0]*fabs(R[0][2]) + extents_b[2]*fabs(R[0][0]);\n\n    t = fabs( T[2]*R[1][1] - T[1]*R[2][1] );\n\n    if( t > ra + rb )\n        return false;\n\n    //L = A0 x B2\n    ra = extents_a[1]*fabs(R[2][2]) + extents_a[2]*fabs(R[1][2]);\n\n    rb = extents_b[0]*fabs(R[0][1]) + extents_b[1]*fabs(R[0][0]);\n\n    t = fabs( T[2]*R[1][2] - T[1]*R[2][2] );\n\n    if( t > ra + rb )\n        return false;\n\n    //L = A1 x B0\n    ra = extents_a[0]*fabs(R[2][0]) + extents_a[2]*fabs(R[0][0]);\n\n    rb = extents_b[1]*fabs(R[1][2]) + extents_b[2]*fabs(R[1][1]);\n\n    t = fabs( T[0]*R[2][0] - T[2]*R[0][0] );\n\n    if( t > ra + rb )\n        return false;\n\n    //L = A1 x B1\n    ra = extents_a[0]*fabs(R[2][1]) + extents_a[2]*fabs(R[0][1]);\n\n    rb = extents_b[0]*fabs(R[1][2]) + extents_b[2]*fabs(R[1][0]);\n\n    t = fabs( T[0]*R[2][1] - T[2]*R[0][1] );\n\n    if( t > ra + rb )\n        return false;\n\n    //L = A1 x B2\n    ra = extents_a[0]*fabs(R[2][2]) + extents_a[2]*fabs(R[0][2]);\n\n    rb = extents_b[0]*fabs(R[1][1]) + extents_b[1]*fabs(R[1][0]);\n\n    t = fabs( T[0]*R[2][2] - T[2]*R[0][2] );\n\n    if( t > ra + rb )\n        return false;\n\n    //L = A2 x B0\n    ra = extents_a[0]*fabs(R[1][0]) + extents_a[1]*fabs(R[0][0]);\n\n    rb = extents_b[1]*fabs(R[2][2]) + extents_b[2]*fabs(R[2][1]);\n\n    t = fabs( T[1]*R[0][0] - T[0]*R[1][0] );\n\n    if( t > ra + rb )\n        return false;\n\n    //L = A2 x B1\n    ra = extents_a[0]*fabs(R[1][1]) + extents_a[1]*fabs(R[0][1]);\n\n    rb = extents_b[0] *fabs(R[2][2]) + extents_b[2]*fabs(R[2][0]);\n\n    t = fabs( T[1]*R[0][1] - T[0]*R[1][1] );\n\n    if( t > ra + rb )\n        return false;\n\n    //L = A2 x B2\n    ra = extents_a[0]*fabs(R[1][2]) + extents_a[1]*fabs(R[0][2]);\n\n    rb = extents_b[0]*fabs(R[2][1]) + extents_b[1]*fabs(R[2][0]);\n\n    t = fabs( T[1]*R[0][2] - T[0]*R[1][2] );\n\n    if( t > ra + rb )\n        return false;\n\n    /*no separating axis found, the two boxes overlap */\n\n    return true;\n}\n\n}\n", "meta": {"hexsha": "61db01823029d4830154d15c8f9d877b333f2a4f", "size": 26360, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ecto_rbo_grasping/src/ecto_rbo_grasping/PoseSet.cpp", "max_stars_repo_name": "SoMa-Project/vision", "max_stars_repo_head_hexsha": "ea8199d98edc363b2be79baa7c691da3a5a6cc86", "max_stars_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-07-24T23:40:01.000Z", "max_stars_repo_stars_event_max_datetime": "2020-07-24T23:40:01.000Z", "max_issues_repo_path": "ecto_rbo_grasping/src/ecto_rbo_grasping/PoseSet.cpp", "max_issues_repo_name": "SoMa-Project/vision", "max_issues_repo_head_hexsha": "ea8199d98edc363b2be79baa7c691da3a5a6cc86", "max_issues_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2020-05-19T18:14:33.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-19T15:53:43.000Z", "max_forks_repo_path": "ecto_rbo_grasping/src/ecto_rbo_grasping/PoseSet.cpp", "max_forks_repo_name": "SoMa-Project/vision", "max_forks_repo_head_hexsha": "ea8199d98edc363b2be79baa7c691da3a5a6cc86", "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": 41.2519561815, "max_line_length": 736, "alphanum_fraction": 0.5990136571, "num_tokens": 8192, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7690802264851919, "lm_q2_score": 0.44552953503957266, "lm_q1q2_score": 0.3426479557140768}}
{"text": "// boost\\math\\distributions\\non_central_beta.hpp\n\n// Copyright John Maddock 2008.\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_SPECIAL_NON_CENTRAL_BETA_HPP\n#define BOOST_MATH_SPECIAL_NON_CENTRAL_BETA_HPP\n\n#include <boost/math/distributions/fwd.hpp>\n#include <boost/math/special_functions/beta.hpp> // for incomplete gamma. gamma_q\n#include <boost/math/distributions/complement.hpp> // complements\n#include <boost/math/distributions/beta.hpp> // central distribution\n#include <boost/math/distributions/detail/generic_mode.hpp>\n#include <boost/math/distributions/detail/common_error_handling.hpp> // error checks\n#include <boost/math/special_functions/fpclassify.hpp> // isnan.\n#include <boost/math/tools/roots.hpp> // for root finding.\n#include <boost/math/tools/series.hpp>\n\nnamespace boost\n{\n   namespace math\n   {\n\n      template <class RealType, class Policy>\n      class non_central_beta_distribution;\n\n      namespace detail{\n\n         template <class T, class Policy>\n         T non_central_beta_p(T a, T b, T lam, T x, T y, const Policy& pol, T init_val = 0)\n         {\n            BOOST_MATH_STD_USING\n               using namespace boost::math;\n            //\n            // Variables come first:\n            //\n            boost::uintmax_t max_iter = policies::get_max_series_iterations<Policy>();\n            T errtol = boost::math::policies::get_epsilon<T, Policy>();\n            T l2 = lam / 2;\n            //\n            // k is the starting point for iteration, and is the\n            // maximum of the poisson weighting term,\n            // note that unlike other similar code, we do not set\n            // k to zero, when l2 is small, as forward iteration\n            // is unstable:\n            //\n            int k = itrunc(l2);\n            if(k == 0)\n               k = 1;\n            T pois;\n            if(k == 0)\n            {\n               // Starting Poisson weight:\n               pois = exp(-l2);\n            }\n            else\n            {\n               // Starting Poisson weight:\n               pois = gamma_p_derivative(T(k+1), l2, pol);\n            }\n            if(pois == 0)\n               return init_val;\n            // recurance term:\n            T xterm;\n            // Starting beta term:\n            T beta = x < y\n               ? detail::ibeta_imp(T(a + k), b, x, pol, false, true, &xterm)\n               : detail::ibeta_imp(b, T(a + k), y, pol, true, true, &xterm);\n\n            xterm *= y / (a + b + k - 1);\n            T poisf(pois), betaf(beta), xtermf(xterm);\n            T sum = init_val;\n\n            if((beta == 0) && (xterm == 0))\n               return init_val;\n\n            //\n            // Backwards recursion first, this is the stable\n            // direction for recursion:\n            //\n            T last_term = 0;\n            boost::uintmax_t count = k;\n            for(int i = k; i >= 0; --i)\n            {\n               T term = beta * pois;\n               sum += term;\n               if(((fabs(term/sum) < errtol) && (last_term >= term)) || (term == 0))\n               {\n                  count = k - i;\n                  break;\n               }\n               pois *= i / l2;\n               beta += xterm;\n               xterm *= (a + i - 1) / (x * (a + b + i - 2));\n               last_term = term;\n            }\n            for(int i = k + 1; ; ++i)\n            {\n               poisf *= l2 / i;\n               xtermf *= (x * (a + b + i - 2)) / (a + i - 1);\n               betaf -= xtermf;\n\n               T term = poisf * betaf;\n               sum += term;\n               if((fabs(term/sum) < errtol) || (term == 0))\n               {\n                  break;\n               }\n               if(static_cast<boost::uintmax_t>(count + i - k) > max_iter)\n               {\n                  return policies::raise_evaluation_error(\n                     \"cdf(non_central_beta_distribution<%1%>, %1%)\",\n                     \"Series did not converge, closest value was %1%\", sum, pol);\n               }\n            }\n            return sum;\n         }\n\n         template <class T, class Policy>\n         T non_central_beta_q(T a, T b, T lam, T x, T y, const Policy& pol, T init_val = 0)\n         {\n            BOOST_MATH_STD_USING\n               using namespace boost::math;\n            //\n            // Variables come first:\n            //\n            boost::uintmax_t max_iter = policies::get_max_series_iterations<Policy>();\n            T errtol = boost::math::policies::get_epsilon<T, Policy>();\n            T l2 = lam / 2;\n            //\n            // k is the starting point for iteration, and is the\n            // maximum of the poisson weighting term:\n            //\n            int k = itrunc(l2);\n            T pois;\n            if(k <= 30)\n            {\n               //\n               // Might as well start at 0 since we'll likely have this number of terms anyway:\n               //\n               if(a + b > 1)\n                  k = 0;\n               else if(k == 0)\n                  k = 1;\n            }\n            if(k == 0)\n            {\n               // Starting Poisson weight:\n               pois = exp(-l2);\n            }\n            else\n            {\n               // Starting Poisson weight:\n               pois = gamma_p_derivative(T(k+1), l2, pol);\n            }\n            if(pois == 0)\n               return init_val;\n            // recurance term:\n            T xterm;\n            // Starting beta term:\n            T beta = x < y\n               ? detail::ibeta_imp(T(a + k), b, x, pol, true, true, &xterm)\n               : detail::ibeta_imp(b, T(a + k), y, pol, false, true, &xterm);\n\n            xterm *= y / (a + b + k - 1);\n            T poisf(pois), betaf(beta), xtermf(xterm);\n            T sum = init_val;\n            if((beta == 0) && (xterm == 0))\n               return init_val;\n            //\n            // Forwards recursion first, this is the stable\n            // direction for recursion, and the location\n            // of the bulk of the sum:\n            //\n            T last_term = 0;\n            boost::uintmax_t count = 0;\n            for(int i = k + 1; ; ++i)\n            {\n               poisf *= l2 / i;\n               xtermf *= (x * (a + b + i - 2)) / (a + i - 1);\n               betaf += xtermf;\n\n               T term = poisf * betaf;\n               sum += term;\n               if((fabs(term/sum) < errtol) && (last_term >= term))\n               {\n                  count = i - k;\n                  break;\n               }\n               if(static_cast<boost::uintmax_t>(i - k) > max_iter)\n               {\n                  return policies::raise_evaluation_error(\n                     \"cdf(non_central_beta_distribution<%1%>, %1%)\",\n                     \"Series did not converge, closest value was %1%\", sum, pol);\n               }\n               last_term = term;\n            }\n            for(int i = k; i >= 0; --i)\n            {\n               T term = beta * pois;\n               sum += term;\n               if(fabs(term/sum) < errtol)\n               {\n                  break;\n               }\n               if(static_cast<boost::uintmax_t>(count + k - i) > max_iter)\n               {\n                  return policies::raise_evaluation_error(\n                     \"cdf(non_central_beta_distribution<%1%>, %1%)\",\n                     \"Series did not converge, closest value was %1%\", sum, pol);\n               }\n               pois *= i / l2;\n               beta -= xterm;\n               xterm *= (a + i - 1) / (x * (a + b + i - 2));\n            }\n            return sum;\n         }\n\n         template <class RealType, class Policy>\n         inline RealType non_central_beta_cdf(RealType x, RealType y, RealType a, RealType b, RealType l, bool invert, const Policy&)\n         {\n            typedef typename policies::evaluation<RealType, Policy>::type value_type;\n            typedef typename policies::normalise<\n               Policy,\n               policies::promote_float<false>,\n               policies::promote_double<false>,\n               policies::discrete_quantile<>,\n               policies::assert_undefined<> >::type forwarding_policy;\n\n            BOOST_MATH_STD_USING\n\n            if(x == 0)\n               return invert ? 1.0f : 0.0f;\n            if(y == 0)\n               return invert ? 0.0f : 1.0f;\n            value_type result;\n            value_type c = a + b + l / 2;\n            value_type cross = 1 - (b / c) * (1 + l / (2 * c * c));\n            if(l == 0)\n               result = cdf(boost::math::beta_distribution<RealType, Policy>(a, b), x);\n            else if(x > cross)\n            {\n               // Complement is the smaller of the two:\n               result = detail::non_central_beta_q(\n                  static_cast<value_type>(a),\n                  static_cast<value_type>(b),\n                  static_cast<value_type>(l),\n                  static_cast<value_type>(x),\n                  static_cast<value_type>(y),\n                  forwarding_policy(),\n                  static_cast<value_type>(invert ? 0 : -1));\n               invert = !invert;\n            }\n            else\n            {\n               result = detail::non_central_beta_p(\n                  static_cast<value_type>(a),\n                  static_cast<value_type>(b),\n                  static_cast<value_type>(l),\n                  static_cast<value_type>(x),\n                  static_cast<value_type>(y),\n                  forwarding_policy(),\n                  static_cast<value_type>(invert ? -1 : 0));\n            }\n            if(invert)\n               result = -result;\n            return policies::checked_narrowing_cast<RealType, forwarding_policy>(\n               result,\n               \"boost::math::non_central_beta_cdf<%1%>(%1%, %1%, %1%)\");\n         }\n\n         template <class T, class Policy>\n         struct nc_beta_quantile_functor\n         {\n            nc_beta_quantile_functor(const non_central_beta_distribution<T,Policy>& d, T t, bool c)\n               : dist(d), target(t), comp(c) {}\n\n            T operator()(const T& x)\n            {\n               return comp ?\n                  T(target - cdf(complement(dist, x)))\n                  : T(cdf(dist, x) - target);\n            }\n\n         private:\n            non_central_beta_distribution<T,Policy> dist;\n            T target;\n            bool comp;\n         };\n\n         //\n         // This is more or less a copy of bracket_and_solve_root, but\n         // modified to search only the interval [0,1] using similar\n         // heuristics.\n         //\n         template <class F, class T, class Tol, class Policy>\n         std::pair<T, T> bracket_and_solve_root_01(F f, const T& guess, T factor, bool rising, Tol tol, boost::uintmax_t& max_iter, const Policy& pol)\n         {\n            BOOST_MATH_STD_USING\n               static const char* function = \"boost::math::tools::bracket_and_solve_root_01<%1%>\";\n            //\n            // Set up inital brackets:\n            //\n            T a = guess;\n            T b = a;\n            T fa = f(a);\n            T fb = fa;\n            //\n            // Set up invocation count:\n            //\n            boost::uintmax_t count = max_iter - 1;\n\n            if((fa < 0) == (guess < 0 ? !rising : rising))\n            {\n               //\n               // Zero is to the right of b, so walk upwards\n               // until we find it:\n               //\n               while((boost::math::sign)(fb) == (boost::math::sign)(fa))\n               {\n                  if(count == 0)\n                  {\n                     b = policies::raise_evaluation_error(function, \"Unable to bracket root, last nearest value was %1%\", b, pol);\n                     return std::make_pair(a, b);\n                  }\n                  //\n                  // Heuristic: every 20 iterations we double the growth factor in case the\n                  // initial guess was *really* bad !\n                  //\n                  if((max_iter - count) % 20 == 0)\n                     factor *= 2;\n                  //\n                  // Now go ahead and move are guess by \"factor\",\n                  // we do this by reducing 1-guess by factor:\n                  //\n                  a = b;\n                  fa = fb;\n                  b = 1 - ((1 - b) / factor);\n                  fb = f(b);\n                  --count;\n                  BOOST_MATH_INSTRUMENT_CODE(\"a = \" << a << \" b = \" << b << \" fa = \" << fa << \" fb = \" << fb << \" count = \" << count);\n               }\n            }\n            else\n            {\n               //\n               // Zero is to the left of a, so walk downwards\n               // until we find it:\n               //\n               while((boost::math::sign)(fb) == (boost::math::sign)(fa))\n               {\n                  if(fabs(a) < tools::min_value<T>())\n                  {\n                     // Escape route just in case the answer is zero!\n                     max_iter -= count;\n                     max_iter += 1;\n                     return a > 0 ? std::make_pair(T(0), T(a)) : std::make_pair(T(a), T(0));\n                  }\n                  if(count == 0)\n                  {\n                     a = policies::raise_evaluation_error(function, \"Unable to bracket root, last nearest value was %1%\", a, pol);\n                     return std::make_pair(a, b);\n                  }\n                  //\n                  // Heuristic: every 20 iterations we double the growth factor in case the\n                  // initial guess was *really* bad !\n                  //\n                  if((max_iter - count) % 20 == 0)\n                     factor *= 2;\n                  //\n                  // Now go ahead and move are guess by \"factor\":\n                  //\n                  b = a;\n                  fb = fa;\n                  a /= factor;\n                  fa = f(a);\n                  --count;\n                  BOOST_MATH_INSTRUMENT_CODE(\"a = \" << a << \" b = \" << b << \" fa = \" << fa << \" fb = \" << fb << \" count = \" << count);\n               }\n            }\n            max_iter -= count;\n            max_iter += 1;\n            std::pair<T, T> r = toms748_solve(\n               f,\n               (a < 0 ? b : a),\n               (a < 0 ? a : b),\n               (a < 0 ? fb : fa),\n               (a < 0 ? fa : fb),\n               tol,\n               count,\n               pol);\n            max_iter += count;\n            BOOST_MATH_INSTRUMENT_CODE(\"max_iter = \" << max_iter << \" count = \" << count);\n            return r;\n         }\n\n         template <class RealType, class Policy>\n         RealType nc_beta_quantile(const non_central_beta_distribution<RealType, Policy>& dist, const RealType& p, bool comp)\n         {\n            static const char* function = \"quantile(non_central_beta_distribution<%1%>, %1%)\";\n            typedef typename policies::evaluation<RealType, Policy>::type value_type;\n            typedef typename policies::normalise<\n               Policy,\n               policies::promote_float<false>,\n               policies::promote_double<false>,\n               policies::discrete_quantile<>,\n               policies::assert_undefined<> >::type forwarding_policy;\n\n            value_type a = dist.alpha();\n            value_type b = dist.beta();\n            value_type l = dist.non_centrality();\n            value_type r;\n            if(!beta_detail::check_alpha(\n               function,\n               a, &r, Policy())\n               ||\n            !beta_detail::check_beta(\n               function,\n               b, &r, Policy())\n               ||\n            !detail::check_non_centrality(\n               function,\n               l,\n               &r,\n               Policy())\n               ||\n            !detail::check_probability(\n               function,\n               static_cast<value_type>(p),\n               &r,\n               Policy()))\n                  return (RealType)r;\n            //\n            // Special cases first:\n            //\n            if(p == 0)\n               return comp\n               ? 1.0f\n               : 0.0f;\n            if(p == 1)\n               return !comp\n               ? 1.0f\n               : 0.0f;\n\n            value_type c = a + b + l / 2;\n            value_type mean = 1 - (b / c) * (1 + l / (2 * c * c));\n            /*\n            //\n            // Calculate a normal approximation to the quantile,\n            // uses mean and variance approximations from:\n            // Algorithm AS 310:\n            // Computing the Non-Central Beta Distribution Function\n            // R. Chattamvelli; R. Shanmugam\n            // Applied Statistics, Vol. 46, No. 1. (1997), pp. 146-156.\n            //\n            // Unfortunately, when this is wrong it tends to be *very*\n            // wrong, so it's disabled for now, even though it often\n            // gets the initial guess quite close.  Probably we could\n            // do much better by factoring in the skewness if only\n            // we could calculate it....\n            //\n            value_type delta = l / 2;\n            value_type delta2 = delta * delta;\n            value_type delta3 = delta * delta2;\n            value_type delta4 = delta2 * delta2;\n            value_type G = c * (c + 1) + delta;\n            value_type alpha = a + b;\n            value_type alpha2 = alpha * alpha;\n            value_type eta = (2 * alpha + 1) * (2 * alpha + 1) + 1;\n            value_type H = 3 * alpha2 + 5 * alpha + 2;\n            value_type F = alpha2 * (alpha + 1) + H * delta\n               + (2 * alpha + 4) * delta2 + delta3;\n            value_type P = (3 * alpha + 1) * (9 * alpha + 17)\n               + 2 * alpha * (3 * alpha + 2) * (3 * alpha + 4) + 15;\n            value_type Q = 54 * alpha2 + 162 * alpha + 130;\n            value_type R = 6 * (6 * alpha + 11);\n            value_type D = delta\n               * (H * H + 2 * P * delta + Q * delta2 + R * delta3 + 9 * delta4);\n            value_type variance = (b / G)\n               * (1 + delta * (l * l + 3 * l + eta) / (G * G))\n               - (b * b / F) * (1 + D / (F * F));\n            value_type sd = sqrt(variance);\n\n            value_type guess = comp\n               ? quantile(complement(normal_distribution<RealType, Policy>(static_cast<RealType>(mean), static_cast<RealType>(sd)), p))\n               : quantile(normal_distribution<RealType, Policy>(static_cast<RealType>(mean), static_cast<RealType>(sd)), p);\n\n            if(guess >= 1)\n               guess = mean;\n            if(guess <= tools::min_value<value_type>())\n               guess = mean;\n            */\n            value_type guess = mean;\n            detail::nc_beta_quantile_functor<value_type, Policy>\n               f(non_central_beta_distribution<value_type, Policy>(a, b, l), p, comp);\n            tools::eps_tolerance<value_type> tol(policies::digits<RealType, Policy>());\n            boost::uintmax_t max_iter = policies::get_max_root_iterations<Policy>();\n\n            std::pair<value_type, value_type> ir\n               = bracket_and_solve_root_01(\n                  f, guess, value_type(2.5), true, tol,\n                  max_iter, Policy());\n            value_type result = ir.first + (ir.second - ir.first) / 2;\n\n            if(max_iter >= policies::get_max_root_iterations<Policy>())\n            {\n               return policies::raise_evaluation_error<RealType>(function, \"Unable to locate solution in a reasonable time:\"\n                  \" either there is no answer to quantile of the non central beta distribution\"\n                  \" or the answer is infinite.  Current best guess is %1%\",\n                  policies::checked_narrowing_cast<RealType, forwarding_policy>(\n                     result,\n                     function), Policy());\n            }\n            return policies::checked_narrowing_cast<RealType, forwarding_policy>(\n               result,\n               function);\n         }\n\n         template <class T, class Policy>\n         T non_central_beta_pdf(T a, T b, T lam, T x, T y, const Policy& pol)\n         {\n            BOOST_MATH_STD_USING\n               using namespace boost::math;\n            //\n            // Variables come first:\n            //\n            boost::uintmax_t max_iter = policies::get_max_series_iterations<Policy>();\n            T errtol = boost::math::policies::get_epsilon<T, Policy>();\n            T l2 = lam / 2;\n            //\n            // k is the starting point for iteration, and is the\n            // maximum of the poisson weighting term:\n            //\n            int k = itrunc(l2);\n            // Starting Poisson weight:\n            T pois = gamma_p_derivative(T(k+1), l2, pol);\n            // Starting beta term:\n            T beta = x < y ?\n               ibeta_derivative(a + k, b, x, pol)\n               : ibeta_derivative(b, a + k, y, pol);\n            T sum = 0;\n            T poisf(pois);\n            T betaf(beta);\n\n            //\n            // Stable backwards recursion first:\n            //\n            boost::uintmax_t count = k;\n            for(int i = k; i >= 0; --i)\n            {\n               T term = beta * pois;\n               sum += term;\n               if((fabs(term/sum) < errtol) || (term == 0))\n               {\n                  count = k - i;\n                  break;\n               }\n               pois *= i / l2;\n               beta *= (a + i - 1) / (x * (a + i + b - 1));\n            }\n            for(int i = k + 1; ; ++i)\n            {\n               poisf *= l2 / i;\n               betaf *= x * (a + b + i - 1) / (a + i - 1);\n\n               T term = poisf * betaf;\n               sum += term;\n               if((fabs(term/sum) < errtol) || (term == 0))\n               {\n                  break;\n               }\n               if(static_cast<boost::uintmax_t>(count + i - k) > max_iter)\n               {\n                  return policies::raise_evaluation_error(\n                     \"pdf(non_central_beta_distribution<%1%>, %1%)\",\n                     \"Series did not converge, closest value was %1%\", sum, pol);\n               }\n            }\n            return sum;\n         }\n\n         template <class RealType, class Policy>\n         RealType nc_beta_pdf(const non_central_beta_distribution<RealType, Policy>& dist, const RealType& x)\n         {\n            BOOST_MATH_STD_USING\n            static const char* function = \"pdf(non_central_beta_distribution<%1%>, %1%)\";\n            typedef typename policies::evaluation<RealType, Policy>::type value_type;\n            typedef typename policies::normalise<\n               Policy,\n               policies::promote_float<false>,\n               policies::promote_double<false>,\n               policies::discrete_quantile<>,\n               policies::assert_undefined<> >::type forwarding_policy;\n\n            value_type a = dist.alpha();\n            value_type b = dist.beta();\n            value_type l = dist.non_centrality();\n            value_type r;\n            if(!beta_detail::check_alpha(\n               function,\n               a, &r, Policy())\n               ||\n            !beta_detail::check_beta(\n               function,\n               b, &r, Policy())\n               ||\n            !detail::check_non_centrality(\n               function,\n               l,\n               &r,\n               Policy())\n               ||\n            !beta_detail::check_x(\n               function,\n               static_cast<value_type>(x),\n               &r,\n               Policy()))\n                  return (RealType)r;\n\n            if(l == 0)\n               return pdf(boost::math::beta_distribution<RealType, Policy>(dist.alpha(), dist.beta()), x);\n            return policies::checked_narrowing_cast<RealType, forwarding_policy>(\n               non_central_beta_pdf(a, b, l, static_cast<value_type>(x), value_type(1 - static_cast<value_type>(x)), forwarding_policy()),\n               \"function\");\n         }\n\n         template <class T>\n         struct hypergeometric_2F2_sum\n         {\n            typedef T result_type;\n            hypergeometric_2F2_sum(T a1_, T a2_, T b1_, T b2_, T z_) : a1(a1_), a2(a2_), b1(b1_), b2(b2_), z(z_), term(1), k(0) {}\n            T operator()()\n            {\n               T result = term;\n               term *= a1 * a2 / (b1 * b2);\n               a1 += 1;\n               a2 += 1;\n               b1 += 1;\n               b2 += 1;\n               k += 1;\n               term /= k;\n               term *= z;\n               return result;\n            }\n            T a1, a2, b1, b2, z, term, k;\n         };\n\n         template <class T, class Policy>\n         T hypergeometric_2F2(T a1, T a2, T b1, T b2, T z, const Policy& pol)\n         {\n            typedef typename policies::evaluation<T, Policy>::type value_type;\n\n            const char* function = \"boost::math::detail::hypergeometric_2F2<%1%>(%1%,%1%,%1%,%1%,%1%)\";\n\n            hypergeometric_2F2_sum<value_type> s(a1, a2, b1, b2, z);\n            boost::uintmax_t max_iter = policies::get_max_series_iterations<Policy>();\n#if BOOST_WORKAROUND(__BORLANDC__, BOOST_TESTED_AT(0x582))\n            value_type zero = 0;\n            value_type result = boost::math::tools::sum_series(s, boost::math::policies::get_epsilon<value_type, Policy>(), max_iter, zero);\n#else\n            value_type result = boost::math::tools::sum_series(s, boost::math::policies::get_epsilon<value_type, Policy>(), max_iter);\n#endif\n            policies::check_series_iterations<T>(function, max_iter, pol);\n            return policies::checked_narrowing_cast<T, Policy>(result, function);\n         }\n\n      } // namespace detail\n\n      template <class RealType = double, class Policy = policies::policy<> >\n      class non_central_beta_distribution\n      {\n      public:\n         typedef RealType value_type;\n         typedef Policy policy_type;\n\n         non_central_beta_distribution(RealType a_, RealType b_, RealType lambda) : a(a_), b(b_), ncp(lambda)\n         {\n            const char* function = \"boost::math::non_central_beta_distribution<%1%>::non_central_beta_distribution(%1%,%1%)\";\n            RealType r;\n            beta_detail::check_alpha(\n               function,\n               a, &r, Policy());\n            beta_detail::check_beta(\n               function,\n               b, &r, Policy());\n            detail::check_non_centrality(\n               function,\n               lambda,\n               &r,\n               Policy());\n         } // non_central_beta_distribution constructor.\n\n         RealType alpha() const\n         { // Private data getter function.\n            return a;\n         }\n         RealType beta() const\n         { // Private data getter function.\n            return b;\n         }\n         RealType non_centrality() const\n         { // Private data getter function.\n            return ncp;\n         }\n      private:\n         // Data member, initialized by constructor.\n         RealType a;   // alpha.\n         RealType b;   // beta.\n         RealType ncp; // non-centrality parameter\n      }; // template <class RealType, class Policy> class non_central_beta_distribution\n\n      typedef non_central_beta_distribution<double> non_central_beta; // Reserved name of type double.\n\n      // Non-member functions to give properties of the distribution.\n\n      template <class RealType, class Policy>\n      inline const std::pair<RealType, RealType> range(const non_central_beta_distribution<RealType, Policy>& /* dist */)\n      { // Range of permissible values for random variable k.\n         using boost::math::tools::max_value;\n         return std::pair<RealType, RealType>(static_cast<RealType>(0), static_cast<RealType>(1));\n      }\n\n      template <class RealType, class Policy>\n      inline const std::pair<RealType, RealType> support(const non_central_beta_distribution<RealType, Policy>& /* dist */)\n      { // Range of supported values for random variable k.\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>(static_cast<RealType>(0), static_cast<RealType>(1));\n      }\n\n      template <class RealType, class Policy>\n      inline RealType mode(const non_central_beta_distribution<RealType, Policy>& dist)\n      { // mode.\n         static const char* function = \"mode(non_central_beta_distribution<%1%> const&)\";\n\n         RealType a = dist.alpha();\n         RealType b = dist.beta();\n         RealType l = dist.non_centrality();\n         RealType r;\n         if(!beta_detail::check_alpha(\n               function,\n               a, &r, Policy())\n               ||\n            !beta_detail::check_beta(\n               function,\n               b, &r, Policy())\n               ||\n            !detail::check_non_centrality(\n               function,\n               l,\n               &r,\n               Policy()))\n                  return (RealType)r;\n         RealType c = a + b + l / 2;\n         RealType mean = 1 - (b / c) * (1 + l / (2 * c * c));\n         return detail::generic_find_mode_01(\n            dist,\n            mean,\n            function);\n      }\n\n      //\n      // We don't have the necessary information to implement\n      // these at present.  These are just disabled for now,\n      // prototypes retained so we can fill in the blanks\n      // later:\n      //\n      template <class RealType, class Policy>\n      inline RealType mean(const non_central_beta_distribution<RealType, Policy>& dist)\n      {\n         BOOST_MATH_STD_USING\n         RealType a = dist.alpha();\n         RealType b = dist.beta();\n         RealType d = dist.non_centrality();\n         RealType apb = a + b;\n         return exp(-d / 2) * a * detail::hypergeometric_2F2<RealType, Policy>(1 + a, apb, a, 1 + apb, d / 2, Policy()) / apb;\n      } // mean\n\n      template <class RealType, class Policy>\n      inline RealType variance(const non_central_beta_distribution<RealType, Policy>& dist)\n      { \n         //\n         // Relative error of this function may be arbitarily large... absolute\n         // error will be small however... that's the best we can do for now.\n         //\n         BOOST_MATH_STD_USING\n         RealType a = dist.alpha();\n         RealType b = dist.beta();\n         RealType d = dist.non_centrality();\n         RealType apb = a + b;\n         RealType result = detail::hypergeometric_2F2(RealType(1 + a), apb, a, RealType(1 + apb), RealType(d / 2), Policy());\n         result *= result * -exp(-d) * a * a / (apb * apb);\n         result += exp(-d / 2) * a * (1 + a) * detail::hypergeometric_2F2(RealType(2 + a), apb, a, RealType(2 + apb), RealType(d / 2), Policy()) / (apb * (1 + apb));\n         return result;\n      }\n\n      // RealType standard_deviation(const non_central_beta_distribution<RealType, Policy>& dist)\n      // standard_deviation provided by derived accessors.\n      template <class RealType, class Policy>\n      inline RealType skewness(const non_central_beta_distribution<RealType, Policy>& /*dist*/)\n      { // skewness = sqrt(l).\n         const char* function = \"boost::math::non_central_beta_distribution<%1%>::skewness()\";\n         typedef typename Policy::assert_undefined_type assert_type;\n         BOOST_STATIC_ASSERT(assert_type::value == 0);\n\n         return policies::raise_evaluation_error<RealType>(\n            function,\n            \"This function is not yet implemented, the only sensible result is %1%.\",\n            std::numeric_limits<RealType>::quiet_NaN(), Policy()); // infinity?\n      }\n\n      template <class RealType, class Policy>\n      inline RealType kurtosis_excess(const non_central_beta_distribution<RealType, Policy>& /*dist*/)\n      {\n         const char* function = \"boost::math::non_central_beta_distribution<%1%>::kurtosis_excess()\";\n         typedef typename Policy::assert_undefined_type assert_type;\n         BOOST_STATIC_ASSERT(assert_type::value == 0);\n\n         return policies::raise_evaluation_error<RealType>(\n            function,\n            \"This function is not yet implemented, the only sensible result is %1%.\",\n            std::numeric_limits<RealType>::quiet_NaN(), Policy()); // infinity?\n      } // kurtosis_excess\n\n      template <class RealType, class Policy>\n      inline RealType kurtosis(const non_central_beta_distribution<RealType, Policy>& dist)\n      {\n         return kurtosis_excess(dist) + 3;\n      }\n\n      template <class RealType, class Policy>\n      inline RealType pdf(const non_central_beta_distribution<RealType, Policy>& dist, const RealType& x)\n      { // Probability Density/Mass Function.\n         return detail::nc_beta_pdf(dist, x);\n      } // pdf\n\n      template <class RealType, class Policy>\n      RealType cdf(const non_central_beta_distribution<RealType, Policy>& dist, const RealType& x)\n      {\n         const char* function = \"boost::math::non_central_beta_distribution<%1%>::cdf(%1%)\";\n            RealType a = dist.alpha();\n            RealType b = dist.beta();\n            RealType l = dist.non_centrality();\n            RealType r;\n            if(!beta_detail::check_alpha(\n               function,\n               a, &r, Policy())\n               ||\n            !beta_detail::check_beta(\n               function,\n               b, &r, Policy())\n               ||\n            !detail::check_non_centrality(\n               function,\n               l,\n               &r,\n               Policy())\n               ||\n            !beta_detail::check_x(\n               function,\n               x,\n               &r,\n               Policy()))\n                  return (RealType)r;\n\n         if(l == 0)\n            return cdf(beta_distribution<RealType, Policy>(a, b), x);\n\n         return detail::non_central_beta_cdf(x, RealType(1 - x), a, b, l, false, Policy());\n      } // cdf\n\n      template <class RealType, class Policy>\n      RealType cdf(const complemented2_type<non_central_beta_distribution<RealType, Policy>, RealType>& c)\n      { // Complemented Cumulative Distribution Function\n         const char* function = \"boost::math::non_central_beta_distribution<%1%>::cdf(%1%)\";\n         non_central_beta_distribution<RealType, Policy> const& dist = c.dist;\n            RealType a = dist.alpha();\n            RealType b = dist.beta();\n            RealType l = dist.non_centrality();\n            RealType x = c.param;\n            RealType r;\n            if(!beta_detail::check_alpha(\n               function,\n               a, &r, Policy())\n               ||\n            !beta_detail::check_beta(\n               function,\n               b, &r, Policy())\n               ||\n            !detail::check_non_centrality(\n               function,\n               l,\n               &r,\n               Policy())\n               ||\n            !beta_detail::check_x(\n               function,\n               x,\n               &r,\n               Policy()))\n                  return (RealType)r;\n\n         if(l == 0)\n            return cdf(complement(beta_distribution<RealType, Policy>(a, b), x));\n\n         return detail::non_central_beta_cdf(x, RealType(1 - x), a, b, l, true, Policy());\n      } // ccdf\n\n      template <class RealType, class Policy>\n      inline RealType quantile(const non_central_beta_distribution<RealType, Policy>& dist, const RealType& p)\n      { // Quantile (or Percent Point) function.\n         return detail::nc_beta_quantile(dist, p, false);\n      } // quantile\n\n      template <class RealType, class Policy>\n      inline RealType quantile(const complemented2_type<non_central_beta_distribution<RealType, Policy>, RealType>& c)\n      { // Quantile (or Percent Point) function.\n         return detail::nc_beta_quantile(c.dist, c.param, true);\n      } // quantile complement.\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_MATH_SPECIAL_NON_CENTRAL_BETA_HPP\n\n", "meta": {"hexsha": "ebb6e91fa1c4feb3a09041642f7542a6ef5a533e", "size": 35949, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Pods/boost/boost/math/distributions/non_central_beta.hpp", "max_stars_repo_name": "dzq1991/DJ_YingKe", "max_stars_repo_head_hexsha": "53f093ecf5fcd6093756b6935bf66e79c4d5fa5e", "max_stars_repo_licenses": ["Apache-2.0"], "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_1_49/boost/math/distributions/non_central_beta.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/math/distributions/non_central_beta.hpp", "max_forks_repo_name": "jjzhang166/WinUtil4", "max_forks_repo_head_hexsha": "7c7b1e9bbe2fb6177bb066d74764d10711748ec5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 44.0, "max_forks_repo_forks_event_min_datetime": "2015-03-18T09:20:37.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-21T08:09:17.000Z", "avg_line_length": 38.4481283422, "max_line_length": 165, "alphanum_fraction": 0.4911402264, "num_tokens": 8270, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7431680199891789, "lm_q2_score": 0.46101677931231594, "lm_q1q2_score": 0.3426129270633221}}
{"text": "#include \"focal_grid.h\"\n\n#include <string>\n#include <stdint.h>\n#include <iostream>\n#include <iomanip>\n#include <math.h>\n#include <chrono>\n#include <vector>\n#include <map>\n#include <unordered_map>\n#include <iterator>\n#include <future>\n#include <thread>\n#include <algorithm>\n#include <dirent.h>\n#include <armadillo>\n\nusing namespace std;\n\nFocalGrid::FocalGrid() {\n\t// empty\n}\n\nbool FocalGrid::LoadCalibration(session_param &ses_par, vox_grid &vox, frames &frame) {\n\n\tbool grid_loaded = true;\n\n\ttry {\n\n\t\tvox.image_size.clear();\n\t\tvox.calib_mat.clear();\n\t\tvox.X_xyz.clear();\n\t\tvox.X_uv.clear();\n\t\tvox.uv_offset.clear();\n\n\t\timage_size.clear();\n\t\tcalib_mat.clear();\n\t\tX_xyz.clear();\n\t\tX_uv.clear();\n\t\tuv_offset.clear();\n\n\t\tstring calib_file = ses_par.session_loc + \"/\" + ses_par.cal_loc + \"/\" + ses_par.cal_name;\n\n\t\tarma::Mat<double> CalibMatrix;\n\n\t\tCalibMatrix.load(calib_file);\n\n\t\tfor (int i=0; i<ses_par.N_cam; i++) {\n\t\t\tvox.image_size.push_back(frame.image_size[i]);\n\t\t\tvox.calib_mat.push_back(CalibMatrix.col(i));\n\t\t\tvox.X_xyz.push_back(FocalGrid::Camera2WorldMatrix(CalibMatrix.col(i)));\n\t\t\tvox.X_uv.push_back(FocalGrid::World2CameraMatrix(CalibMatrix.col(i)));\n\t\t\tarma::Col<double> uv_off_i = {CalibMatrix(10,i)/2.0-CalibMatrix(12,i)/2.0, CalibMatrix(9,i)/2.0-CalibMatrix(11,i)/2.0, 0.0};\n\t\t\tvox.uv_offset.push_back(uv_off_i);\n\n\t\t\timage_size.push_back(frame.image_size[i]);\n\t\t\tcalib_mat.push_back(CalibMatrix.col(i));\n\t\t\tX_xyz.push_back(FocalGrid::Camera2WorldMatrix(CalibMatrix.col(i)));\n\t\t\tX_uv.push_back(FocalGrid::World2CameraMatrix(CalibMatrix.col(i)));\n\t\t\tuv_offset.push_back(uv_off_i);\n\t\t}\n\n\t\t// Populate internal parameters\n\n\t\tN_cam = vox.N_cam;\n\t\tN_threads = vox.N_threads;\n\t\tnx = vox.nx;\n\t\tny = vox.ny;\n\t\tnz = vox.nz;\n\t\tds = vox.ds;\n\t\tx0 = vox.x0;\n\t\ty0 = vox.y0;\n\t\tz0 = vox.z0;\n\n\t}\n\tcatch (...) {\n\t\tgrid_loaded = false;\n\t}\n\n\treturn grid_loaded;\n}\n\nbool FocalGrid::ConstructFocalGrid(vox_grid &vox) {\n\n\tbool grid_build = true;\n\n\tint voxel_ind = 0;\n\n\ttry {\n\n\t\tvox.pix2vox.clear();\n\n\t\tvox.vox2pix.clear();\n\n\t\tfor (int k=0; k<nz; k++) {\n\t\t\tcout << k << endl;\n\t\t\tfor (int j=0; j<ny; j++) {\n\t\t\t\tfor (int i=0; i<nx; i++) {\n\t\t\t\t\tvector<int> uv_voxel = FocalGrid::CheckVoxel(i, j, k);\n\t\t\t\t\tif (uv_voxel.size()==N_cam) {\n\t\t\t\t\t\tvoxel_ind = k*nx*ny+j*nx+i;\n\t\t\t\t\t\tvox.pix2vox.insert(pair<int,int>(uv_voxel[0],voxel_ind));\n\t\t\t\t\t\tvox.vox2pix.insert(pair<int,vector<int>>(voxel_ind,uv_voxel));\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t}\n\tcatch (...) {\n\t\tgrid_build = false;\n\t}\n\n\treturn grid_build;\n}\n\nvector<int> FocalGrid::CheckVoxel(int i, int j, int k) {\n\n\tvector<int> uv_out;\n\n\tint uv_ind = -1;\n\n\tarma::Col<double> xyz(4);\n\n\txyz = {x0-((nx-1)/2.0)*ds+i*ds, \n\t\ty0-((ny-1)/2.0)*ds+j*ds,\n\t\tz0-((nz-1)/2.0)*ds+k*ds,\n\t\t1.0};\n\n\tarma::Col<double> uv(3);\n\n\tint n=0;\n\tbool uv_out_of_range = false;\n\n\twhile (n<N_cam && uv_out_of_range==false) {\n\n\t\tuv = X_uv[n]*xyz-uv_offset[n];\n\n\t\tif (uv(0)>=0 && uv(0)<(get<1>(image_size[n]))) {\n\t\t\tif (uv(1)>=0 && uv(1)<(get<0>(image_size[n]))) {\n\t\t\t\tuv_ind = ((int) uv(1))*get<1>(image_size[n])+((int) uv(0));\n\t\t\t\tuv_out.push_back(uv_ind);\n\t\t\t}\n\t\t\telse {\n\t\t\t\tuv_out.clear();\n\t\t\t\tuv_out_of_range = true;\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\tuv_out.clear();\n\t\t\tuv_out_of_range = true;\n\t\t}\n\t\tn++;\n\t}\n\n\treturn uv_out;\n}\n\narma::Col<double> FocalGrid::PointCloudMatching(arma::Mat<double> &dest_pcl, arma::Mat<double> &src_pcl, double search_radius) {\n\n\t// Create a multimap of the two pointclouds and try to find dest-src pairs in the x, y and z direction:\n\n\tmultimap<int,double> xy_map;\n\tmultimap<int,double> xz_map;\n\tmultimap<int,double> yz_map;\n\n\tint N_dest = dest_pcl.n_cols;\n\n\tcout << \"N_dest\" << endl;\n\tcout << N_dest << endl;\n\n\tfor (int i=0; i<N_dest; i++) {\n\n\t\tint i_x = (int) (dest_pcl(1,i)-x0)/ds+((nx-1)/2.0);\n\t\tint i_y = (int) (dest_pcl(2,i)-y0)/ds+((ny-1)/2.0);\n\t\tint i_z = (int) (dest_pcl(3,i)-z0)/ds+((nz-1)/2.0);\n\n\t\txy_map.insert(pair<int,double>(i_y*nx+i_x,dest_pcl(1,i)));\n\t\txz_map.insert(pair<int,double>(i_x*nz+i_z,dest_pcl(2,i)));\n\t\tyz_map.insert(pair<int,double>(i_z*ny+i_y,dest_pcl(3,i)));\n\n\t}\n\n\tint N_src = src_pcl.n_cols;\n\n\tcout << \"N_src\" << endl;\n\tcout << N_src << endl;\n\n\tarma::Col<double> src_cg;\n\tsrc_cg.zeros(3);\n\n\tvector<tuple<double,double,double>> delta_x_vec; \n\tvector<tuple<double,double,double>> delta_y_vec; \n\tvector<tuple<double,double,double>> delta_z_vec;\n\n\tfor (int j=0; j<N_src; j++) {\n\n\t\tsrc_cg(0) += src_pcl(1,j)/(N_src*1.0);\n\t\tsrc_cg(1) += src_pcl(2,j)/(N_src*1.0);\n\t\tsrc_cg(2) += src_pcl(3,j)/(N_src*1.0);\n\n\t\tint j_x = (int) (src_pcl(1,j)-x0)/ds+((nx-1)/2.0);\n\t\tint j_y = (int) (src_pcl(2,j)-y0)/ds+((ny-1)/2.0);\n\t\tint j_z = (int) (src_pcl(3,j)-z0)/ds+((nz-1)/2.0);\n\n\t\t// delta z\n\t\tpair<multimap<int,double>::iterator, multimap<int,double>::iterator> dest_z_voxels;\n\t\tdest_z_voxels = xy_map.equal_range(j_y*nx+j_x);\n\t\tdouble delta_z = 100000.0;\n\t\tdouble delta_z_new;\n\t\tdouble z_val;\n\n\t\tfor (multimap<int,double>::iterator it_z=dest_z_voxels.first; it_z != dest_z_voxels.second; ++it_z) {\n\t\t\tz_val = it_z->second;\n\t\t\tdelta_z_new = z_val-src_pcl(3,j);\n\t\t\tif (abs(delta_z_new)<abs(delta_z)) {\n\t\t\t\tdelta_z = delta_z_new;\n\t\t\t}\n\t\t}\n\n\t\tif (abs(delta_z)<search_radius) {\n\t\t\tdelta_z_vec.push_back(make_tuple(delta_z,src_pcl(1,j),src_pcl(2,j)));\n\t\t}\n\n\t\t// delta y\n\t\tpair<multimap<int,double>::iterator, multimap<int,double>::iterator> dest_y_voxels;\n\t\tdest_y_voxels = xz_map.equal_range(j_x*nz+j_z);\n\t\tdouble delta_y = 100000.0;\n\t\tdouble delta_y_new;\n\t\tdouble y_val;\n\n\t\tfor (multimap<int,double>::iterator it_y=dest_y_voxels.first; it_y != dest_y_voxels.second; ++it_y) {\n\t\t\ty_val = it_y->second;\n\t\t\tdelta_y_new = y_val-src_pcl(2,j);\n\t\t\tif (abs(delta_y_new)<abs(delta_y)) {\n\t\t\t\tdelta_y = delta_y_new;\n\t\t\t}\n\t\t}\n\n\t\tif (abs(delta_y)<search_radius) {\n\t\t\tdelta_y_vec.push_back(make_tuple(delta_y,src_pcl(1,j),src_pcl(3,j)));\n\t\t}\n\n\t\t// delta x\n\t\tpair<multimap<int,double>::iterator, multimap<int,double>::iterator> dest_x_voxels;\n\t\tdest_x_voxels = yz_map.equal_range(j_z*ny+j_y);\n\t\tdouble delta_x = 100000.0;\n\t\tdouble delta_x_new;\n\t\tdouble x_val;\n\n\t\tfor (multimap<int,double>::iterator it_x=dest_x_voxels.first; it_x != dest_x_voxels.second; ++it_x) {\n\t\t\tx_val = it_x->second;\n\t\t\tdelta_x_new = x_val-src_pcl(1,j);\n\t\t\tif (abs(delta_x_new)<abs(delta_x)) {\n\t\t\t\tdelta_x = delta_x_new;\n\t\t\t}\n\t\t}\n\n\t\tif (abs(delta_x)<search_radius) {\n\t\t\tdelta_x_vec.push_back(make_tuple(delta_x,src_pcl(2,j),src_pcl(3,j)));\n\t\t}\n\n\t}\n\n\tdouble theta_x = 0.0;\n\tdouble trans_x = 0.0;\n\tdouble theta_y = 0.0;\n\tdouble trans_y = 0.0;\n\tdouble theta_z = 0.0;\n\tdouble trans_z = 0.0;\n\n\tint N_dx = delta_x_vec.size();\n\tint N_dy = delta_y_vec.size();\n\tint N_dz = delta_z_vec.size();\n\n\tcout << \"delta x size\" << endl;\n\tcout << N_dx << endl;\n\tcout << \"delta y size\" << endl;\n\tcout << N_dy << endl;\n\tcout << \"delta z size\" << endl;\n\tcout << N_dz << endl;\n\n\tdouble mse_x = 0.0;\n\tdouble mse_y = 0.0;\n\tdouble mse_z = 0.0;\n\n\tdouble theta_x_update;\n\tdouble theta_y_update;\n\tdouble theta_z_update;\n\tdouble trans_x_update;\n\tdouble trans_y_update;\n\tdouble trans_z_update;\n\n\tint N_theta_x = 0;\n\tint N_theta_y = 0;\n\tint N_theta_z = 0;\n\tint N_trans_x = 0;\n\tint N_trans_y = 0;\n\tint N_trans_z = 0;\n\n\tfor (int k=0; k<N_dx; k++) {\n\n\t\ttrans_x_update = get<0>(delta_x_vec[k]);\n\t\ttheta_y_update = atan2(get<0>(delta_x_vec[k]),get<2>(delta_x_vec[k])-src_cg(2));\n\t\ttheta_z_update = atan2(get<0>(delta_x_vec[k]),get<1>(delta_x_vec[k])-src_cg(1));\n\n\t\tif (isfinite(trans_x_update)==true) {\n\t\t\ttrans_x += trans_x_update;\n\t\t\tmse_x += pow(get<0>(delta_x_vec[k]),2);\n\t\t\tN_trans_x++;\n\t\t}\n\t\tif (isfinite(theta_y_update)==true) {\n\t\t\ttheta_y += theta_y_update;\n\t\t\tN_theta_y++;\n\t\t}\n\t\tif (isfinite(theta_z_update)==true) {\n\t\t\ttheta_z -= theta_z_update;\n\t\t\tN_theta_z++;\n\t\t}\n\t}\n\n\tfor (int k=0; k<N_dy; k++) {\n\n\t\ttrans_y_update = get<0>(delta_y_vec[k]);\n\t\ttheta_x_update = atan2(get<0>(delta_y_vec[k]),get<2>(delta_y_vec[k])-src_cg(2));\n\t\ttheta_z_update = atan2(get<0>(delta_y_vec[k]),get<2>(delta_y_vec[k])-src_cg(0));\n\n\t\tif (isfinite(trans_y_update)==true) {\n\t\t\ttrans_y += trans_y_update;\n\t\t\tmse_y += pow(get<0>(delta_y_vec[k]),2);\n\t\t\tN_trans_y++;\n\t\t}\n\t\tif (isfinite(theta_x_update)==true) {\n\t\t\ttheta_x -= theta_x_update;\n\t\t\tN_theta_x++;\n\t\t}\n\t\tif (isfinite(theta_z_update)==true) {\n\t\t\ttheta_z += theta_z_update;\n\t\t\tN_theta_z++;\n\t\t}\n\t}\n\n\tfor (int k=0; k<N_dz; k++) {\n\n\t\ttrans_z_update = get<0>(delta_z_vec[k]);\n\t\ttheta_x_update = atan2(get<0>(delta_z_vec[k]),get<2>(delta_z_vec[k])-src_cg(1));\n\t\ttheta_y_update = atan2(get<0>(delta_z_vec[k]),get<1>(delta_z_vec[k])-src_cg(0));\n\n\t\tif (isfinite(trans_z_update)==true) {\n\t\t\ttrans_z += trans_z_update;\n\t\t\tmse_z += pow(get<0>(delta_z_vec[k]),2);\n\t\t\tN_trans_z++;\n\t\t}\n\t\tif (isfinite(theta_x_update)==true) {\n\t\t\ttheta_x += theta_x_update;\n\t\t\tN_theta_x++;\n\t\t}\n\t\tif (isfinite(theta_y_update)==true) {\n\t\t\ttheta_y -= theta_y_update;\n\t\t\tN_theta_y++;\n\t\t}\n\t}\n\n\tarma::Col<double> state_update(9);\n\n\tif (N_theta_x>3) {\n\t\tstate_update(0) = theta_x/(N_theta_x*1.0);\n\t}\n\telse {\n\t\tstate_update(0) = 0.0;\n\t}\n\tif (N_theta_y>3) {\n\t\tstate_update(1) = theta_y/(N_theta_y*1.0);\n\t}\n\telse {\n\t\tstate_update(1) = 0.0;\n\t}\n\tif (N_theta_z>3) {\n\t\tstate_update(2) = theta_z/(N_theta_z*1.0);\n\t}\n\telse {\n\t\tstate_update(2) = 0.0;\n\t}\n\tif (N_trans_x>3) {\n\t\tstate_update(3) = trans_x/(N_trans_x*1.0);\n\t\tstate_update(6) = mse_x/(N_trans_x*1.0);\n\t}\n\telse {\n\t\tstate_update(3) = 0.0;\n\t\tstate_update(6) = 1.0;\n\t}\n\tif (N_trans_y>3) {\n\t\tstate_update(4) = trans_y/(N_trans_y*1.0);\n\t\tstate_update(7) = mse_y/(N_trans_y*1.0);\n\t}\n\telse {\n\t\tstate_update(4) = 0.0;\n\t\tstate_update(7) = 1.0;\n\t}\n\tif (N_trans_z>3) {\n\t\tstate_update(5) = trans_z/(N_trans_z*1.0);\n\t\tstate_update(8) = mse_z/(N_trans_z*1.0);\n\t}\n\telse {\n\t\tstate_update(5) = 0.0;\n\t\tstate_update(8) = 1.0;\n\t}\n\n\tcout << \"state update\" << endl;\n\tcout << state_update << endl;\n\n\treturn state_update;\n}\n\nvector<tuple<int,double,double,double,double,double,double>> FocalGrid::ProjectImage2Cloud(vector<arma::Col<int>> &frame_in, vox_grid &vox) {\n\n\t//vector<tuple<double,double,double,int>> pcl_now;\n\n\tvector<tuple<int,double,double,double,double,double,double>> pcl_now;\n\n\tunordered_map<int,int> pcl_voxels;\n\n\tint N_row = get<0>(vox.image_size[0]);\n\tint N_col = get<1>(vox.image_size[0]);\n\n\tpair<multimap<int,int>::iterator, multimap<int,int>::iterator> voxels_i;\n\n\tint vox_now;\n\tvector<int> uv_now;\n\n\tint n = 0;\n\tbool is_voxel = true;\n\n\tint frame_val_0 = 0;\n\tint frame_val_n = 0;\n\n\tint code_now = 0;\n\n\tint count = 0;\n\n\t// Insert voxels into an unordered map and give them a segment code:\n\tfor (int i=0; i<(N_row*N_col); i++) {\n\t\tframe_val_0 = frame_in[0](i);\n\t\tif (frame_val_0>0) {\n\t\t\tvoxels_i = vox.pix2vox.equal_range(i);\n\t\t\tfor (multimap<int,int>::iterator it=voxels_i.first; it != voxels_i.second; ++it) {\n\t\t\t\tvox_now = it->second;\n\t\t\t\tuv_now = vox.vox2pix[vox_now];\n\t\t\t\tn = 1;\n\t\t\t\tis_voxel = true;\n\t\t\t\tcode_now = frame_val_0;\n\t\t\t\twhile (is_voxel==true && n < N_cam) {\n\t\t\t\t\tframe_val_n = frame_in[n](uv_now[n]);\n\t\t\t\t\tif (frame_val_n>0) {\n\t\t\t\t\t\tcode_now = code_now+pow(max_n_seg,n)*frame_val_n;\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tis_voxel = false;\n\t\t\t\t\t}\n\t\t\t\t\tn++;\n\t\t\t\t}\n\t\t\t\tif (is_voxel==true) {\n\t\t\t\t\tcount++;\n\t\t\t\t\tpcl_voxels.insert(pair<int,int>(vox_now,code_now));\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// For each voxel in the pcl_voxels map:\n\t// -> find the neighboring voxels\n\t// -> calculate normal\n\t// -> if a normal could be calculated, add the voxel_id, xyz_pos and normal to pcl_now\n\n\tunordered_map<int,int>::iterator nb_it;\n\n\tarma::Col<int> neighbors(27);\n\n\tarma::Col<double> nb_vec(27);\n\n\tarma::Col<double> normal(3);\n\n\tarma::Col<double> xyz_pos(3);\n\n\tint nb_vox_id;\n\tint nb_vox_code;\n\n\tfor (nb_it = pcl_voxels.begin(); nb_it != pcl_voxels.end(); nb_it++) {\n\t\tvox_now = nb_it->first;\n\t\tcode_now = nb_it->second;\n\t\tneighbors = FocalGrid::FindNeighbors(vox_now);\n\t\tif (neighbors(13)>0) {\n\t\t\tfor (int m=0; m<27; m++) {\n\t\t\t\tif (pcl_voxels.find(neighbors(m)) != pcl_voxels.end()) {\n\t\t\t\t\tnb_vec(m) = 0.0;\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tnb_vec(m) = 1.0;\n\t\t\t\t}\n\t\t\t}\n\t\t\tnormal = FocalGrid::CalculateNormal(nb_vec);\n\t\t\tif (arma::norm(normal,2)>0.5) {\n\t\t\t\txyz_pos = FocalGrid::CalculatePosition(vox_now);\n\t\t\t\tpcl_now.push_back(make_tuple(code_now,xyz_pos(0),xyz_pos(1),xyz_pos(2),normal(0),normal(1),normal(2)));\n\t\t\t}\n\t\t}\n\t}\n\n\tif (pcl_now.size() <= 0) {\n\t\tpcl_now.push_back(make_tuple(0,0.0,0.0,0.0,0.0,0.0,0.0));\n\t}\n\treturn pcl_now;\n}\n\narma::Col<int> FocalGrid::FindNeighbors(int vox_ind) {\n\n\t// find the neighboring voxels:\n\n\tarma::Col<int> vox_int_mat(27);\n\n\tint i = vox_ind % nx;\n\tint j = ((vox_ind-i)/nx) % ny;\n\tint k = (vox_ind-i-j*nx)/(nx*ny);\n\n\tif ((i>0 && i<(nx-1)) && (j>0 && j<(ny-1)) && (k>0 && k<(nz-1))) {\n\n\t\tvox_int_mat(0) = vox_ind-nx*ny-nx-1;\n\t\tvox_int_mat(1) = vox_ind-nx*ny-nx;\n\t\tvox_int_mat(2) = vox_ind-nx*ny-nx+1;\n\t\tvox_int_mat(3) = vox_ind-nx*ny-1;\n\t\tvox_int_mat(4) = vox_ind-nx*ny;\n\t\tvox_int_mat(5) = vox_ind-nx*ny+1;\n\t\tvox_int_mat(6) = vox_ind-nx*ny+nx-1;\n\t\tvox_int_mat(7) = vox_ind-nx*ny+nx;\n\t\tvox_int_mat(8) = vox_ind-nx*ny+nx+1;\n\t\tvox_int_mat(9) = vox_ind-nx-1;\n\t\tvox_int_mat(10) = vox_ind-nx;\n\t\tvox_int_mat(11) = vox_ind-nx+1;\n\t\tvox_int_mat(12) = vox_ind-1;\n\t\tvox_int_mat(13) = vox_ind;\n\t\tvox_int_mat(14) = vox_ind+1;\n\t\tvox_int_mat(15) = vox_ind+nx-1;\n\t\tvox_int_mat(16) = vox_ind+nx;\n\t\tvox_int_mat(17) = vox_ind+nx+1;\n\t\tvox_int_mat(18) = vox_ind+nx*ny-nx-1;\n\t\tvox_int_mat(19) = vox_ind+nx*ny-nx;\n\t\tvox_int_mat(20) = vox_ind+nx*ny-nx+1;\n\t\tvox_int_mat(21) = vox_ind+nx*ny-1;\n\t\tvox_int_mat(22) = vox_ind+nx*ny;\n\t\tvox_int_mat(23) = vox_ind+nx*ny+1;\n\t\tvox_int_mat(24) = vox_ind+nx*ny+nx-1;\n\t\tvox_int_mat(25) = vox_ind+nx*ny+nx;\n\t\tvox_int_mat(26) = vox_ind+nx*ny+nx+1;\n\n\t}\n\telse {\n\t\tvox_int_mat.zeros();\n\t}\n\n\treturn vox_int_mat;\n}\n\narma::Col<double> FocalGrid::CalculatePosition(int vox_ind) {\n\n\tint i = vox_ind % nx;\n\tint j = ((vox_ind-i)/nx) % ny;\n\tint k = (vox_ind-i-j*nx)/(nx*ny);\n\n\tarma::Col<double> xyz_pos(3);\n\n\txyz_pos(0) = x0-((nx-1)/2.0)*ds+i*ds;\n\txyz_pos(1) = y0-((ny-1)/2.0)*ds+j*ds;\n\txyz_pos(2) = z0-((nz-1)/2.0)*ds+k*ds;\n\n\treturn xyz_pos;\n}\n\narma::Col<double> FocalGrid::CalculateNormal(arma::Col<double> neighbor_vector) {\n\n\tarma::Col<double> normal;\n\n\tnormal.zeros(3);\n\n\tif (arma::sum(neighbor_vector)>1.0 && arma::sum(neighbor_vector)<20.0) {\n\t\tnormal = normal_mat.t()*neighbor_vector;\n\t\tif (arma::norm(normal,2)>0.5){\n\t\t\tnormal = arma::normalise(normal);\n\t\t}\n\t\telse {\n\t\t\tnormal.zeros(3);\n\t\t}\n\t}\n\n\treturn normal;\n}\n\nvector<arma::Col<int>> FocalGrid::ProjectCloud2Image(vector<tuple<double,double,double,int>> &cloud_in) {\n\n\tvector<arma::Col<int>> frame_now;\n\n\tint N_vox = cloud_in.size();\n\n\tfor (int n=0; n<N_cam; n++) {\n\t\tarma::Col<int> frame_n;\n\t\tframe_n.zeros(get<0>(image_size[n])*get<1>(image_size[n]));\n\t\tframe_now.push_back(frame_n);\n\t}\n\n\tarma::Col<double> uv;\n\tarma::Col<double> xyz;\n\tint u = 0;\n\tint v = 0;\n\n\tfor (int i=0; i<N_vox; i++) {\n\t\tfor (int j=0; j<N_cam; j++) {\n\t\t\txyz = {get<0>(cloud_in[i]),get<1>(cloud_in[i]),get<2>(cloud_in[i]),1.0};\n\t\t\tuv = X_uv[j]*xyz-uv_offset[j];\n\t\t\tif (uv(0)>=0 && uv(0)<(get<1>(image_size[j]))) {\n\t\t\t\tif (uv(1)>=0 && uv(1)<(get<0>(image_size[j]))) {\n\t\t\t\t\tu = (int) uv(0);\n\t\t\t\t\tv = (int) uv(1);\n\t\t\t\t\tif (frame_now[j](get<1>(image_size[j])*v+u)==0) {\n\t\t\t\t\t\tframe_now[j](get<1>(image_size[j])*v+u) = get<3>(cloud_in[i]);\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tif (frame_now[j](get<1>(image_size[j])*v+u)>get<3>(cloud_in[i])) {\n\t\t\t\t\t\t\tframe_now[j](get<1>(image_size[j])*v+u) = get<3>(cloud_in[i]);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn frame_now;\n}\n\narma::Mat<int> FocalGrid::TransformXYZ2UV(arma::Col<double> xyz_pos) {\n\n\tarma::Mat<int> uv_mat(2,N_cam);\n\n\tfor (int n=0; n<N_cam; n++) {\n\t\tarma::Col<double> uv = X_uv[n]*xyz_pos-uv_offset[n];\n\t\tuv_mat(0,n) = int(uv(0));\n\t\tuv_mat(1,n) = int(uv(1));\n\t}\n\n\treturn uv_mat;\n}\n\ntuple<arma::Mat<int>, arma::Col<double>> FocalGrid::RayCasting(int cam_nr, arma::Col<double> xyz_pos_prev, arma::Col<double> uv_pos_prev, arma::Col<double> uv_pos_now) {\n\n\t// Calculate the 3D translation vector:\n\tarma::Col<double> xyz_uv_prev = X_xyz[cam_nr]*(uv_pos_prev+uv_offset[cam_nr]);\n\tarma::Col<double> xyz_uv_now = X_xyz[cam_nr]*(uv_pos_now+uv_offset[cam_nr]);\n\tarma::Col<double> trans_vec = xyz_uv_now-xyz_uv_prev;\n\ttrans_vec(3) = 0.0;\n\n\t// Add the translation to the xyz position:\n\tarma::Col<double> xyz_pos_now = xyz_pos_prev + trans_vec;\n\n\t// Project the new position back to the camera views:\n\n\tarma::Mat<int> uv_mat(3,N_cam);\n\n\tfor (int n=0; n<N_cam; n++) {\n\t\tarma::Col<double> uv = X_uv[n]*xyz_pos_now-uv_offset[n];\n\t\tif (uv(0)>=0 && uv(0)<(get<1>(image_size[n])) && uv(1)>=0 && uv(1)<(get<0>(image_size[n]))) {\n\t\t\tuv_mat(0,n) = int(uv(0));\n\t\t\tuv_mat(1,n) = int(uv(1));\n\t\t\tuv_mat(2,n) = int(uv(2));\n\t\t}\n\t\telse {\n\t\t\tarma::Col<double> uv_old = X_uv[n]*xyz_pos_prev-uv_offset[n];\n\t\t\tuv_mat(0,n) = int(uv_old(0));\n\t\t\tuv_mat(1,n) = int(uv_old(1));\n\t\t\tuv_mat(2,n) = int(uv_old(2));\n\t\t}\n\t}\n\n\treturn make_tuple(uv_mat,xyz_pos_now);\n}\n\narma::Mat<double> FocalGrid::Camera2WorldMatrix(arma::Col<double> calib_param) {\n\n\t// return the world to camera projection matrix\n\n\tarma::Mat<double> C = {{calib_param(0), calib_param(2), 0, 0},\n\t\t \t\t\t{0, calib_param(1), 0, 0},\n\t\t \t\t\t{0, 0, 0, 1}};\n\n\tdouble theta = sqrt(pow(calib_param(3),2)+pow(calib_param(4),2)+pow(calib_param(5),2));\n\n\tarma::Mat<double> omega = {{0, -calib_param(5), calib_param(4)},\n\t\t\t \t\t\t{calib_param(5), 0, -calib_param(3)},\n\t\t\t \t\t\t{-calib_param(4), calib_param(3), 0}};\n\n\tarma::Mat<double> R(3,3); R.eye();\n\n\tR = R+(sin(theta)/theta)*omega+((1-cos(theta))/pow(theta,2))*(omega*omega);\n\n\tarma::Col<double> T = {calib_param(6), calib_param(7), calib_param(8)};\n\n\tarma::Mat<double> K = {{R(0,0), R(0,1), R(0,2), T(0)},\n\t\t \t\t\t\t{R(1,0), R(1,1), R(1,2), T(1)},\n\t\t \t\t\t\t{R(2,0), R(2,1), R(2,2), T(2)},\n\t\t \t\t\t\t{0, 0, 0, 1}};\n\n\treturn arma::inv(K)*arma::pinv(C);\n\n}\n\narma::Mat<double> FocalGrid::World2CameraMatrix(arma::Col<double> calib_param) {\n\n\t// return the world to camera projection matrix\n\n\tarma::Mat<double> C = {{calib_param(0), calib_param(2), 0, 0},\n\t\t \t\t\t{0, calib_param(1), 0, 0},\n\t\t \t\t\t{0, 0, 0, 1}};\n\n\tdouble theta = sqrt(pow(calib_param(3),2)+pow(calib_param(4),2)+pow(calib_param(5),2));\n\n\tarma::Mat<double> omega = {{0, -calib_param(5), calib_param(4)},\n\t\t\t \t\t\t{calib_param(5), 0, -calib_param(3)},\n\t\t\t \t\t\t{-calib_param(4), calib_param(3), 0}};\n\n\tarma::Mat<double> R(3,3); R.eye();\n\n\tR = R+(sin(theta)/theta)*omega+((1-cos(theta))/pow(theta,2))*(omega*omega);\n\n\tarma::Col<double> T = {calib_param(6), calib_param(7), calib_param(8)};\n\n\tarma::Mat<double> K = {{R(0,0), R(0,1), R(0,2), T(0)},\n\t\t \t\t\t\t{R(1,0), R(1,1), R(1,2), T(1)},\n\t\t \t\t\t\t{R(2,0), R(2,1), R(2,2), T(2)},\n\t\t \t\t\t\t{0, 0, 0, 1}};\n\n\treturn C*K;\n\n}", "meta": {"hexsha": "8e2f9a6d626cd6ac81409e654a428c9cdaa34a55", "size": 18437, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "FlyTrackApp/focal_grid.cpp", "max_stars_repo_name": "jmmelis/FlyTrackApp", "max_stars_repo_head_hexsha": "7c03eb0aeda7b0bd4e0c6181bc776c92e4fbc582", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "FlyTrackApp/focal_grid.cpp", "max_issues_repo_name": "jmmelis/FlyTrackApp", "max_issues_repo_head_hexsha": "7c03eb0aeda7b0bd4e0c6181bc776c92e4fbc582", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "FlyTrackApp/focal_grid.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": 24.9148648649, "max_line_length": 169, "alphanum_fraction": 0.6353528231, "num_tokens": 6741, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6959583250334526, "lm_q2_score": 0.4921881357207956, "lm_q1q2_score": 0.34254243053758254}}
{"text": "// Copyright (C) 2015 The Regents of the University of California (Regents)\n// and Google, Inc. All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are\n// met:\n//\n//     * Redistributions of source code must retain the above 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, Google,\n//       nor the names of its contributors may be used to endorse or promote\n//       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\"\n// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE\n// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n// POSSIBILITY OF SUCH DAMAGE.\n//\n// Please contact the author of this library if you have any questions.\n// Author: Chris Sweeney (cmsweeney@cs.ucsb.edu)\n\n#include \"theia/sfm/pose/two_point_pose_partial_rotation.h\"\n\n#include <math.h>\n\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n\n#include \"theia/math/closed_form_polynomial_solver.h\"\n\nnamespace theia {\nusing Eigen::Map;\nusing Eigen::Vector3d;\nusing Eigen::Quaterniond;\n\nnamespace {\n\n// Adds a specific pose solution corresponding to the ray lengths.\ninline void AddPoseSolution(const Vector3d& axis,\n                            const Vector3d& model_point_1,\n                            const Vector3d& model_point_2,\n                            const Vector3d& image_ray_1,\n                            const Vector3d& image_ray_2,\n                            const double ray_length_1,\n                            const double ray_length_2,\n                            Quaterniond* rotation,\n                            Vector3d* translation) {\n  // Scales the image_rays by the calculated ray lengths, computing the points\n  // in image space.\n  const Vector3d point_in_image_space_1 = ray_length_1 * image_ray_1;\n  const Vector3d point_in_image_space_2 = ray_length_2 * image_ray_2;\n  const Vector3d image_points_diff =\n      point_in_image_space_1 - point_in_image_space_2;\n\n  const Vector3d model_points_diff = model_point_1 - model_point_2;\n\n  // Computes two basis vectors that lie on the plane orthogonal to the axis.\n  const Vector3d basis_vector_2 = axis.cross(model_points_diff).normalized();\n  const Vector3d basis_vector_1 = basis_vector_2.cross(axis).normalized();\n\n  assert(0.0 < basis_vector_1.dot(basis_vector_1));\n\n  // Finds the projection of the image_points_diff vector in this basis.\n  const double dp_1 = basis_vector_1.dot(image_points_diff);\n  const double dp_2 = basis_vector_2.dot(image_points_diff);\n\n  // Finds the angle around the axis.\n  const double angle = atan2(dp_2, dp_1);\n  *rotation = Quaterniond(Eigen::AngleAxisd(angle, axis));\n\n  // Calculates the translation, after taking into account the rotation.\n  *translation = point_in_image_space_1 - *rotation * model_point_1;\n}\n\nint TwoPointPoseCore(const Vector3d& axis,\n                     const Vector3d& model_point_1,\n                     const Vector3d& model_point_2,\n                     const Vector3d& image_ray_1,\n                     const Vector3d& image_ray_2,\n                     Quaterniond soln_rotations[2],\n                     Vector3d soln_translations[2]) {\n  // Let the points in the camera coordinate system be\n  // y * image_ray_1, x * image_ray_2, where x, y are the lengths of the\n  // rays. Since there is only rotation about the passed axis, the difference\n  // between the values in the model and camera coordinate systems, projected\n  // on the axis, should be the same. So:\n  //\n  // DotProd(axis, y * image_ray_1 - x * image_ray_2)  =\n  //     DotProd(axis, model_points[0] - model_points[1])\n  //\n  // This allows x to be expressed in terms of y:\n  //\n  // x = m + n * y\n  const double ray_1_axis_dp = image_ray_1.dot(axis);\n  const double ray_2_axis_dp = image_ray_2.dot(axis);\n  const double model_diff_axis_dp = (model_point_1 - model_point_2).dot(axis);\n\n  const double m = model_diff_axis_dp / ray_1_axis_dp;\n  const double n = ray_2_axis_dp / ray_1_axis_dp;\n\n  // Next, the distance between the model points and the image points should\n  // be the same:\n  //\n  // |y * image_ray_1 - x * image_ray_2| =\n  //     |model_points[0] - model_points[1]|\n  //\n  // Using this and the substitution for x above we can create a quadratic\n  // equation in y.\n\n  // Computes the coefficients of the quadratic equation ay^2 + by + c = 0.0.\n  const double ray_dp = image_ray_1.dot(image_ray_2);\n\n  const long double a = n * (n - 2.0 * ray_dp) + 1.0;\n  const long double b = 2.0 * m * (n - ray_dp);\n  const long double c = m * m - (model_point_1 - model_point_2).squaredNorm();\n\n  double roots[2] = { 0.0, 0.0 };\n  const int number_of_roots = SolveQuadraticReals(a, b, c, roots);\n\n  int num_solutions = 0;\n  for (int i = 0; i < number_of_roots; ++i) {\n    // Only accept positive ray distances.\n    if (roots[i] > 0) {\n      // Computes the other ray distance.\n      const double ray_distance = m + n * roots[i];\n      if (ray_distance > 0) {\n        AddPoseSolution(axis, model_point_1, model_point_2, image_ray_1,\n                        image_ray_2, ray_distance, roots[i],\n                        &soln_rotations[num_solutions],\n                        &soln_translations[num_solutions]);\n        num_solutions++;\n      }\n    }\n  }\n  return num_solutions;\n}\n\n}  // namespace\n\nint TwoPointPosePartialRotation(const Vector3d& axis,\n                                const Vector3d& model_point_1,\n                                const Vector3d& model_point_2,\n                                const Vector3d& image_ray_1,\n                                const Vector3d& image_ray_2,\n                                Quaterniond soln_rotations[2],\n                                Vector3d soln_translations[2]) {\n  static const double kEpsilon = 1e-9;\n  assert(fabs(image_ray_1.squaredNorm() - 1.0) < kEpsilon);\n  assert(fabs(image_ray_2.squaredNorm() - 1.0) < kEpsilon);\n\n  if (fabs(image_ray_1.dot(axis)) < kEpsilon) {\n    if (fabs(image_ray_2.dot(axis)) > kEpsilon) {\n      // If image_ray_1.y() == 0 then the function above doesn't work because\n      // the calculate m and n will have a divide by 0.\n      // However if image_ray_2.y() is not equal to zero then we can swap\n      // and the points and call the above function with the swapped points.\n      // TODO(cmsweeney): Maybe always swap to improve the conditioning?\n      return TwoPointPoseCore(axis, model_point_2, model_point_1, image_ray_2,\n                              image_ray_1, soln_rotations, soln_translations);\n    }\n    return 0;\n  } else {\n    return TwoPointPoseCore(axis, model_point_1, model_point_2, image_ray_1,\n                            image_ray_2, soln_rotations, soln_translations);\n  }\n}\n\n}  // namespace theia\n", "meta": {"hexsha": "61e30c4ed8ba829ec3fc3767abd63513ce685218", "size": 7742, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/theia/sfm/pose/two_point_pose_partial_rotation.cc", "max_stars_repo_name": "SpectacularAI/TheiaSfM", "max_stars_repo_head_hexsha": "3dbb45cd6c239a4bab2beb46812c4ba7094a0625", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/theia/sfm/pose/two_point_pose_partial_rotation.cc", "max_issues_repo_name": "SpectacularAI/TheiaSfM", "max_issues_repo_head_hexsha": "3dbb45cd6c239a4bab2beb46812c4ba7094a0625", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/theia/sfm/pose/two_point_pose_partial_rotation.cc", "max_forks_repo_name": "SpectacularAI/TheiaSfM", "max_forks_repo_head_hexsha": "3dbb45cd6c239a4bab2beb46812c4ba7094a0625", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-02-19T19:01:13.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-19T19:01:13.000Z", "avg_line_length": 42.306010929, "max_line_length": 78, "alphanum_fraction": 0.6692069233, "num_tokens": 1896, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6959583124210896, "lm_q2_score": 0.49218813572079556, "lm_q1q2_score": 0.3425424243299271}}
{"text": "\n#include \"DelaunayTriangulation.h\"\n#include \"DelaunayMemoryManager.h\"\n#include \"math/mathutils.h\"\n#include <float.h>\n#include <cassert>\n#include <set>\n#include <list>\n#include <boost/bind.hpp>\n\n\nnamespace math\n{\n   //--------------------------------------------------------------------------\n\n   DelaunayTriangulation::DelaunayTriangulation(double xmin, double ymin, double xmax, double ymax, EDelaunayLocationAlgorithms eAlgorithm)\n      : _xmin(xmin), _ymin(ymin), _xmax(xmax), _ymax(ymax), _pStartTriangle(0), _eLocationAlgorithm(eAlgorithm)\n   {\n      assert(_xmin<_xmax);\n      assert(_ymin<_ymax);\n\n      _Init();\n   }\n\n   //--------------------------------------------------------------------------\n\n   DelaunayTriangulation::~DelaunayTriangulation()\n   {\n      Clear();\n      if (_pStartTriangle)\n      {\n         //std::cout << \"<b>Removing Triangle</b>\\n\";\n         _qLocationStructure->DeleteMemory(_pStartTriangle);\n\n         // This assertion is only valid when one instance of DelaunayTriangulation exists!\n         //assert(DelaunayMemoryManager::GetNumTriangles() == 0);\n         //assert(DelaunayMemoryManager::GetNumVertices() == 0);\n\n      }\n   }\n\n   //--------------------------------------------------------------------------\n\n   void DelaunayTriangulation::_Init()\n   {\n      // calculate Triangle that surrounds area defined in _xmin, _ymin, _xmax, _ymax\n      double Mx = _xmin + (_xmax-_xmin)/2.0;\n      double My = _ymin + (_ymax-_ymin)/2.0;\n      double r = sqrt((_xmax-Mx)*(_xmax-Mx)+(_ymax-My)*(_ymax-My));\n      double Cy = _ymax + (_xmax-Mx)*(_xmax-Mx) / (_ymax-My);\n      double Cx = Mx;\n      double By = My -r;\n      double Bx = Cx-(Cy-My+r)*(_xmax-Cx)/(_ymax-Cy); \n      double Ay = My - r;\n      double Ax = Cx-(Cy-My+r)*(_xmin-Cx)/(_ymax-Cy);\n\n      \n      DelaunayVertex* A = DelaunayMemoryManager::AllocVertex(Ax,Ay,0,-1);\n      DelaunayVertex* B = DelaunayMemoryManager::AllocVertex(Bx,By,0,-1);\n      DelaunayVertex* C = DelaunayMemoryManager::AllocVertex(Cx,Cy,0,-1);\n\n      _pStartTriangle = DelaunayMemoryManager::AllocTriangle();\n\n      _pStartTriangle->SetVertex(0, A);\n      _pStartTriangle->SetVertex(1, B);\n      _pStartTriangle->SetVertex(2, C);\n\n      double xmax, ymax, xmin, ymin;\n      xmax = ymax = -1e20;\n      xmin = ymin = 1e20;\n\n      xmin = math::Min<double>(Ax, xmin);\n      xmin = math::Min<double>(Bx, xmin);\n      xmin = math::Min<double>(Cx, xmin);\n      ymin = math::Min<double>(Ay, ymin);\n      ymin = math::Min<double>(By, ymin);\n      ymin = math::Min<double>(Cy, ymin);\n      xmax = math::Max<double>(Ax, xmax);\n      xmax = math::Max<double>(Bx, xmax);\n      xmax = math::Max<double>(Cx, xmax);\n      ymax = math::Max<double>(Ay, ymax);\n      ymax = math::Max<double>(By, ymax);\n      ymax = math::Max<double>(Cy, ymax);\n\n      _qLocationStructure = IDelaunayLocationStructure::CreateLocationStructure(xmin, ymin, xmax, ymax, _eLocationAlgorithm);\n      if (_qLocationStructure)\n      {\n         _qLocationStructure->AddTriangle(_pStartTriangle);\n      }\n\n      if (!_pStartTriangle->IsCCW())\n      {\n         std::cout << \"Error: Start-triangle is not ccw!\\n\";\n         assert(false);\n      }\n\n      _bError = false;\n   }\n\n   //--------------------------------------------------------------------------\n\n   void DelaunayTriangulation::_CollectTriangle(DelaunayTriangle* pTri)\n   {\n      _vecTriangles.push_back(pTri);\n   }\n\n   //--------------------------------------------------------------------------\n\n   void DelaunayTriangulation::Clear()\n   {\n      if (_pStartTriangle)\n      {\n         _vecTriangles.clear();\n         _qLocationStructure->Traverse(boost::bind(&DelaunayTriangulation::_CollectTriangle, this, _1));\n\n         for (size_t i=0;i<_vecTriangles.size();i++)\n         {\n            _qLocationStructure->DeleteMemory(_vecTriangles[i]);\n         }\n\n         _pStartTriangle = 0;\n         _Init();\n      }\n   }\n\n   //--------------------------------------------------------------------------\n\n \n\n\n   //--------------------------------------------------------------------------\n\n\n   namespace internal\n   {\n      inline double _CalcTriArea(const ElevationPoint& A, const ElevationPoint& B, const ElevationPoint& C)\n      {\n         return math::ccw(A.x, A.y, B.x, B.y, C.x, C.y);\n         //return 0.5*((B.x - A.x)*(C.y - A.y) - (B.y - A.y)*(C.x - A.x));\n      }\n   }\n\n\n   double DelaunayTriangulation::GetElevationAt(double x, double y, ElevationQuery& query_result)\n   {\n      if (x<=_xmax && x>=_xmin &&\n         y<=_ymax && y>=_ymin)\n      {\n         query_result = EQ_INTERIOR;\n         ePointTriangleRelation relation;\n         DelaunayTriangle* pTri = _qLocationStructure->GetTriangleAt(x,y,relation);\n\n         if (pTri && !pTri->IsSuperSimplex())\n         {\n            ElevationPoint P;\n            P.x = x; P.y = y; P.elevation = 0.0;\n\n            ElevationPoint A = pTri->GetVertex(0)->GetElevationPointCopy();\n            ElevationPoint B = pTri->GetVertex(1)->GetElevationPointCopy();\n            ElevationPoint C = pTri->GetVertex(2)->GetElevationPointCopy();\n\n            double elva = A.elevation;\n            double elvb = B.elevation;\n            double elvc = C.elevation;\n\n            switch(relation)\n            {\n            case PointTriangle_Edge0:  // Point on Edge 0\n            case PointTriangle_Edge1:  // Point on Edge 1  \n            case PointTriangle_Edge2:  // Point on Edge 2  \n            case PointTriangle_Inside: // Point inside triangle\n               {\n                  A.elevation = 0.0;\n                  B.elevation = 0.0;\n                  C.elevation = 0.0;\n\n                  double F_abc = internal::_CalcTriArea(A,B,C);\n                  double F_pbc = internal::_CalcTriArea(P,B,C);\n                  double F_apc = internal::_CalcTriArea(A,P,C);\n\n                  double r = F_pbc/F_abc;\n                  double s = F_apc/F_abc;\n                  double t = 1.0-r-s;\n\n                  A.elevation = elva;\n                  B.elevation = elvb;\n                  C.elevation = elvc;\n\n                  double Pelv = r*A.elevation + s*B.elevation + t*C.elevation;\n                  return Pelv;\n               }\n               break;\n            case PointTriangle_Vertex0:  // Point lies on vertex 0\n               return pTri->GetVertex(0)->elevation();\n            case PointTriangle_Vertex1:  // Point lies on vertex 1\n               return pTri->GetVertex(1)->elevation();\n            case PointTriangle_Vertex2:  // Point lies on vertex 2\n               return pTri->GetVertex(2)->elevation();\n            default: // outside triangle / invalid triangle\n               query_result = EQ_EXTERIOR;\n               return 0.0;\n            }\n         }\n         else\n         {\n            query_result = EQ_EXTERIOR;\n            return 0.0;\n         }\n      }\n      else\n      {\n         query_result = EQ_UNDEFINED; // outside valid triangulation area\n         return 0.0;\n      }\n\n   }\n\n   //--------------------------------------------------------------------------\n\n   void DelaunayTriangulation::InsertPoint(const ElevationPoint& pt)\n   {\n      if (pt.x<=_xmax && pt.x>=_xmin &&\n         pt.y<=_ymax && pt.y>=_ymin)\n      {\n         DelaunayVertex* pNewVertex = DelaunayMemoryManager::AllocVertex(pt);\n         _pStartTriangle = _qLocationStructure->InsertVertex(pNewVertex, _pStartTriangle);\n         _bError = false; // inserting a point invalidates errors!\n      }\n   }\n\n\n   void DelaunayTriangulation::_InsertPointSetId(const ElevationPoint& pt, int id)\n   {\n      if (pt.x<=_xmax && pt.x>=_xmin &&\n         pt.y<=_ymax && pt.y>=_ymin)\n      {\n         DelaunayVertex* pNewVertex = DelaunayMemoryManager::AllocVertex(pt);\n         pNewVertex->SetId(id);\n         _pStartTriangle = _qLocationStructure->InsertVertex(pNewVertex, _pStartTriangle);\n         _bError = false; // inserting a point invalidates errors!\n      }\n   }\n\n   //--------------------------------------------------------------------------\n\n   void DelaunayTriangulation::_ResetVertexId(DelaunayTriangle* pTri)\n   {\n      assert(pTri);\n      assert(pTri->GetVertex(0));\n      assert(pTri->GetVertex(1));\n      assert(pTri->GetVertex(2));\n\n      pTri->GetVertex(0)->SetId(-1);\n      pTri->GetVertex(1)->SetId(-1);\n      pTri->GetVertex(2)->SetId(-1);\n   }\n\n   //--------------------------------------------------------------------------\n\n   void DelaunayTriangulation::_CollectElevationPoints(DelaunayTriangle* pTri)\n   {\n      assert(pTri);\n      assert(pTri->GetVertex(0));\n      assert(pTri->GetVertex(1));\n      assert(pTri->GetVertex(2));\n\n      // ignore supersimplex triangles.\n      if (!pTri->IsSuperSimplex())\n      {\n         for (int v=0;v<3;v++)\n         {\n            if (pTri->GetVertex(v)->GetId() == -1)\n            { \n               pTri->GetVertex(v)->SetId(_idcnt);\n               _vPts.push_back(pTri->GetVertex(v)->GetElevationPoint());\n               _idcnt++;\n            }\n\n            _vIndex.push_back(pTri->GetVertex(v)->GetId());\n         }\n      }\n   }\n\n\n   //--------------------------------------------------------------------------\n\n   // before calling this make sure to clear _vCutEdge, _vIndex and _vPts\n   void DelaunayTriangulation::_CollectTriangulationStructure(DelaunayTriangle* pTri)\n   {\n      assert(pTri);\n      assert(pTri->GetVertex(0));\n      assert(pTri->GetVertex(1));\n      assert(pTri->GetVertex(2));\n\n      // ignore supersimplex triangles.\n      if (!pTri->IsSuperSimplex())\n      {\n         for (int v=0;v<3;v++)\n         {\n            if (pTri->GetVertex(v)->GetId() == -1)\n            { \n               pTri->GetVertex(v)->SetId(_idcnt);\n               _vPts.push_back(pTri->GetVertex(v)->GetElevationPoint());\n               _idcnt++;\n            }\n\n            _vIndex.push_back(pTri->GetVertex(v)->GetId());\n         }\n\n        \n         if (pTri->GetTriangle(0) == 0)\n         {\n            _vCutEdge.push_back(std::pair<int, int>(pTri->GetVertex(0)->GetId(), pTri->GetVertex(1)->GetId()));\n         }\n\n         if (pTri->GetTriangle(1) == 0)\n         {\n            _vCutEdge.push_back(std::pair<int, int>(pTri->GetVertex(1)->GetId(), pTri->GetVertex(2)->GetId()));\n         }\n\n         if (pTri->GetTriangle(2) == 0)\n         {\n            _vCutEdge.push_back(std::pair<int, int>(pTri->GetVertex(2)->GetId(), pTri->GetVertex(0)->GetId()));\n         }\n\n      }\n\n   }\n\n   //--------------------------------------------------------------------------\n\n   // Retrieve Triangulation as Point / Index List\n   void DelaunayTriangulation::GetPointVec(std::vector<ElevationPoint>& vPoints)\n   {\n      \n\n      // Reset All Vertices to 0\n      _qLocationStructure->Traverse(boost::bind(&DelaunayTriangulation::_ResetVertexId, this, _1));\n\n      _idcnt = 0; _vPts.clear(); _vIndex.clear(); _vCutEdge.clear();\n      _qLocationStructure->Traverse(boost::bind(&DelaunayTriangulation::_CollectTriangulationStructure, this, _1));\n\n      vPoints = _vPts;\n      _vPts.clear();\n\n   }\n\n  \n   //--------------------------------------------------------------------------\n\n   void DelaunayTriangulation::GetTriangleIndices(std::vector<int>& vIndices)\n   {\n      vIndices = _vIndex;\n   }\n\n   //--------------------------------------------------------------------------\n\n   void DelaunayTriangulation::GetCutEdges(std::vector<std::pair<int, int> >& vCutEdges)\n   {\n      vCutEdges = _vCutEdge;\n   }\n   //--------------------------------------------------------------------------\n\n   std::vector<DelaunayTriangle*>& DelaunayTriangulation::GetAllTriangles()\n   {\n      _vecTriangles.clear();\n      _qLocationStructure->Traverse(boost::bind(&DelaunayTriangulation::_CollectTriangle, this, _1));\n\n      return _vecTriangles;\n   }\n\n   //--------------------------------------------------------------------------\n\n   void DelaunayTriangulation::DeleteMemory(DelaunayTriangle* pTri)\n   {\n      _qLocationStructure->DeleteMemory(pTri);\n   }\n\n   //--------------------------------------------------------------------------\n\n   void DelaunayTriangulation::_CutEdges(std::vector< std::pair<int,int> >& vCut)\n   {\n      // Traverse triangulation structure and delete corresponding triangles \n\n      std::vector<DelaunayTriangle*>& vTri = DelaunayTriangulation::GetAllTriangles();\n\n      std::set<DelaunayTriangle*> setDelete;\n\n      for (size_t i=0;i<vTri.size();i++)\n      {\n         DelaunayTriangle* pTri = vTri[i];\n         DelaunayTriangle* pTri0 = pTri->GetTriangle(0);\n         DelaunayTriangle* pTri1 = pTri->GetTriangle(1);\n         DelaunayTriangle* pTri2 = pTri->GetTriangle(2);\n\n         int A,B,C;\n         A = pTri->GetVertex(0)->GetId();\n         B = pTri->GetVertex(1)->GetId();\n         C = pTri->GetVertex(2)->GetId();\n\n         // does this triangle contain a cut edge ?\n\n         for (size_t c=0;c<vCut.size();c++)\n         {\n            int start = vCut[c].first;\n            int end = vCut[c].second;\n\n            if (A == start && B == end)\n            {\n               setDelete.insert(pTri0);\n            }\n            else if (B == start && C == end)\n            {\n               setDelete.insert(pTri1);\n            }\n            else if (C == start && A == end)\n            {\n               setDelete.insert(pTri2);\n            }\n         }\n      }\n\n      std::set<DelaunayTriangle*>::iterator it = setDelete.begin();\n\n      while (it != setDelete.end())\n      {\n         DeleteMemory(*it);\n         it++;\n      }\n\n   }\n\n   //--------------------------------------------------------------------------\n\n   void DelaunayTriangulation::SetEpsilon(double epsilon)\n   {\n      assert(_qLocationStructure);\n\n      if (_qLocationStructure)\n      {\n         _qLocationStructure->SetEpsilon(epsilon);\n      }\n   }\n\n   //--------------------------------------------------------------------------\n\n   void DelaunayTriangulation::_ResetVertexErrors(DelaunayTriangle* pTri)\n   {\n      pTri->GetVertex(0)->GetElevationPoint().error = -1.0;\n      pTri->GetVertex(1)->GetElevationPoint().error = -1.0;\n      pTri->GetVertex(2)->GetElevationPoint().error = -1.0;\n   }\n\n   //--------------------------------------------------------------------------\n\n   void DelaunayTriangulation::_GetCCWVertices(DelaunayTriangle* pTri, int vertex_index, std::vector<DelaunayVertex*>& outputVertices)\n   {\n      outputVertices.clear();\n      std::list<DelaunayVertex*> lst;\n\n      const DelaunayTriangle* pStartTriangle = pTri;\n\n      int vtx = vertex_index;\n      int triangle_index = (vtx+2)%3;\n      lst.push_front(pTri->GetVertex((vtx+2)%3));\n\n      DelaunayTriangle* A = pTri;\n      DelaunayTriangle* C = pTri->GetTriangle(triangle_index);\n\n\n      while(C && C != pStartTriangle && !C->IsSuperSimplex() && !A->IsSuperSimplex())\n      {\n         if (A->GetVertex(vtx) == C->GetVertex(0))\n         {\n            vtx = 0;\n         }\n         else if (A->GetVertex(vtx) == C->GetVertex(1))\n         {\n            vtx = 1;\n         }\n         else if (A->GetVertex(vtx) == C->GetVertex(2))\n         {\n            vtx = 2;\n         }\n         else\n         {\n            assert(false);\n            break;\n         }\n\n         lst.push_front(C->GetVertex((vtx+2)%3));\n\n         triangle_index = (vtx+2)%3; \n         A = C;\n         C = C->GetTriangle(triangle_index);\n      }\n\n      lst.push_back(pTri->GetVertex((vertex_index+1)%3));\n\n      // ignore non ccw direction!\n      // copy result to output\n      std::list<DelaunayVertex*>::iterator it = lst.begin();\n      while (it!=lst.end())\n      {\n         outputVertices.push_back(*it);\n         it++;\n      }\n\n   }\n\n   //--------------------------------------------------------------------------\n\n   void DelaunayTriangulation::_CreateSurroundingPolygon(DelaunayTriangle* pTri, int vertex_index, std::vector<ElevationPoint>& outputPolygon)\n   {\n      outputPolygon.clear();\n      std::list<ElevationPoint> lst;\n\n      const DelaunayTriangle* pStartTriangle = pTri;\n\n      int vtx = vertex_index;\n      int triangle_index = (vtx+2)%3;\n      lst.push_front(pTri->GetVertex((vtx+2)%3)->GetElevationPoint());\n\n      DelaunayTriangle* A = pTri;\n      DelaunayTriangle* B;\n      DelaunayTriangle* C = pTri->GetTriangle(triangle_index);\n\n      while(C && C != pStartTriangle && !C->IsSuperSimplex() && !A->IsSuperSimplex())\n      {\n         if (A->GetVertex(vtx) == C->GetVertex(0))\n         {\n            vtx = 0;\n         }\n         else if (A->GetVertex(vtx) == C->GetVertex(1))\n         {\n            vtx = 1;\n         }\n         else if (A->GetVertex(vtx) == C->GetVertex(2))\n         {\n            vtx = 2;\n         }\n         else\n         {\n            assert(false);\n            break;\n         }\n\n         lst.push_front(C->GetVertex((vtx+2)%3)->GetElevationPoint());\n\n         triangle_index = (vtx+2)%3; \n         A = C;\n         C = C->GetTriangle(triangle_index);\n      }\n\n      // other direction and only if pTri->GetTriangle(vtx) != pStartTriangle\n      lst.push_back(pTri->GetVertex((vertex_index+1)%3)->GetElevationPoint());\n\n      if (C != pStartTriangle)\n      {\n         vtx = vertex_index;\n         triangle_index = vtx;\n\n         A = pTri;\n         B = pTri->GetTriangle(triangle_index);\n\n         while(B && B != pStartTriangle && !B->IsSuperSimplex() && !A->IsSuperSimplex())\n         {\n            if (A->GetVertex(vtx) == B->GetVertex(0))\n            {\n               vtx = 0;\n            }\n            else if (A->GetVertex(vtx) == B->GetVertex(1))\n            {\n               vtx = 1;\n            }\n            else if (A->GetVertex(vtx) == B->GetVertex(2))\n            {\n               vtx = 2;\n            }\n\n\n            lst.push_back(B->GetVertex((vtx+1)%3)->GetElevationPoint());\n            triangle_index = vtx; \n\n            A = B;\n            B = B->GetTriangle(triangle_index);\n         }\n\n      }\n\n\n\n\n      // Convert list to vector (for returning values)\n      if (lst.size()>2)\n      {      \n         std::list<ElevationPoint>::iterator it = lst.begin();\n         while (it!=lst.end())\n         {\n            outputPolygon.push_back(*it);\n            it++;\n         }\n      }\n \n   }\n\n   //--------------------------------------------------------------------------\n\n   void DelaunayTriangulation::_CalcVertexErrorsVtx(DelaunayTriangle* pTri, int vtx)\n   {\n      assert(vtx>=0 && vtx<=3);\n      assert(pTri);\n\n      ElevationPoint pt = pTri->GetVertex(vtx)->GetElevationPoint();\n\n      // corner points always have max error\n      if (pt.weight < -2 \n         || pTri->GetVertex((vtx+1)%3)->GetElevationPoint().weight < -2\n         || pTri->GetVertex((vtx+2)%3)->GetElevationPoint().weight < -2)\n      {\n         pTri->GetVertex(vtx)->GetElevationPoint().error = DBL_MAX;\n      }\n      else\n      {\n         boost::shared_ptr<DelaunayTriangulation> qTriangulation;\n\n         if (pTri->GetVertex(vtx)->GetElevationPoint().error <= -1.0)\n         {\n            std::vector<ElevationPoint> outputPolygon;\n            _CreateSurroundingPolygon(pTri, vtx, outputPolygon);\n\n            qTriangulation = boost::shared_ptr<DelaunayTriangulation>(new DelaunayTriangulation(_xmin, _ymin, _xmax, _ymax, _eLocationAlgorithm));\n            qTriangulation->SetEpsilon(DBL_EPSILON); // can be removed later\n\n            for (size_t i=0;i<outputPolygon.size();i++)\n            {\n               qTriangulation->InsertPoint(outputPolygon[i]);\n            }\n\n            math::ElevationQuery query;\n            double elv = qTriangulation->GetElevationAt(pt.x, pt.y, query);\n\n            if (query == EQ_INTERIOR)\n            {\n               double dError = fabs(elv - pt.elevation);\n               pTri->GetVertex(vtx)->GetElevationPoint().error = dError;\n               \n               if (dError < _minError)\n               {\n                  _oVertexMinError.pTri = pTri;\n                  _oVertexMinError.idx0 = vtx;\n                  _minError = dError;\n               }\n               \n            }\n            else\n            {\n               pTri->GetVertex(vtx)->GetElevationPoint().error = DBL_MAX;\n            }\n\n         }\n\n      }\n   }\n\n   //--------------------------------------------------------------------------\n\n   void DelaunayTriangulation::_CalcVertexErrors(DelaunayTriangle* pTri)\n   {\n      assert(pTri);\n\n      if (!pTri->IsSuperSimplex()) // ignore supersimplex triangles!\n      {\n         _CalcVertexErrorsVtx(pTri,0);\n         _CalcVertexErrorsVtx(pTri,1);\n         _CalcVertexErrorsVtx(pTri,2);\n      }\n   }\n\n   //--------------------------------------------------------------------------\n\n   void DelaunayTriangulation::CalculateVertexErrors()\n   {\n      _oVertexMinError.pTri = 0;\n      _oVertexMinError.idx0 = -1;\n\n      _minError = DBL_MAX;\n      // Reset Errors:\n      _qLocationStructure->Traverse(boost::bind(&DelaunayTriangulation::_ResetVertexErrors, this, _1));\n      _qLocationStructure->Traverse(boost::bind(&DelaunayTriangulation::_CalcVertexErrors, this, _1));\n   \n      _bError = true;\n      //std::cout << \"MinError: \" << _minError << \"\\n\";\n   }\n\n   //--------------------------------------------------------------------------\n\n   void DelaunayTriangulation::UpdateVertexErrors(std::vector<DelaunayVertex*>& vVertex)\n   {\n\n      ePointTriangleRelation e;\n      DelaunayTriangle* pTri;\n      int idx;\n      \n      for (size_t i=0;i<vVertex.size();i++)\n      {\n         idx = -1;\n         pTri = _qLocationStructure->GetTriangleAt(vVertex[i]->x(),vVertex[i]->y(),e);\n         if (pTri && !pTri->IsSuperSimplex())\n         {\n            if (pTri->GetVertex(0) == vVertex[i])\n               idx = 0;\n            else if (pTri->GetVertex(1) == vVertex[i])\n               idx = 1;\n            else if (pTri->GetVertex(2) == vVertex[i])\n               idx = 2;\n\n            if (idx != -1)\n            {\n               _CalcVertexErrorsVtx(pTri,idx);\n            }\n            else\n            {\n               assert(false); // vertex not found!! How can this be ??!??\n            }\n         }\n\n      }\n      \n      _UpdateMinError();\n   }\n\n   //--------------------------------------------------------------------------\n\n   void DelaunayTriangulation::_UpdateVertexErrors(DelaunayTriangle* pTri)\n   {\n      double dError;\n\n      if (!pTri->IsSuperSimplex())\n      {\n         for (int i=0;i<3;i++)\n         {\n            dError = pTri->GetVertex(i)->GetElevationPoint().error;\n            if (dError < _minError)\n            {\n               _oVertexMinError.pTri = pTri;\n               _oVertexMinError.idx0 = i;\n               _minError = dError;\n            }\n         }\n      }\n   }\n\n   //--------------------------------------------------------------------------\n\n   void DelaunayTriangulation::_UpdateMinError()\n   {\n      _minError = DBL_MAX;\n      _qLocationStructure->Traverse(boost::bind(&DelaunayTriangulation::_UpdateVertexErrors, this, _1));    \n   }\n\n   //--------------------------------------------------------------------------\n\n   void DelaunayTriangulation::RemoveLeastErrorVertex()\n   {\n      if (_minError == DBL_MAX)\n         return;\n\n\n      if (_oVertexMinError.pTri)\n      {\n         // GetNeighbourVertices and save in list\n         if (_oVertexMinError.pTri->GetVertex(_oVertexMinError.idx0)->weight() == -3)\n         {\n            std::cout << \"**** FATAL ERROR ****: Removing corner vertex!!\\n\";\n         }\n\n         _RemoveVertex(_oVertexMinError.pTri, _oVertexMinError.idx0);\n         _oVertexMinError.pTri = 0;\n         _oVertexMinError.idx0 = -1;\n      }\n\n   }\n\n\n   //--------------------------------------------------------------------------\n\n   int DelaunayTriangulation::Simplify(double epsilon, int maxiterations)\n   {\n      std::vector<DelaunayVertex*> vVertex;\n      int rmvsteps = 0;\n      if (!_bError)\n         CalculateVertexErrors();\n\n       while (_minError <= epsilon && _minError != DBL_MAX && rmvsteps < maxiterations)\n       {\n          GetCCWVertices(_oVertexMinError.pTri, _oVertexMinError.idx0, vVertex);\n          RemoveLeastErrorVertex(); rmvsteps++;\n          UpdateVertexErrors(vVertex);\n       }\n\n       /*if (rmvsteps >= maxiterations)\n       {\n          std::cout << \"Simplify-Condition: Max Iterations reached!\\n\";\n       }\n\n       if (_minError > epsilon)\n       {\n          std::cout << \"Simplify-Condition: Epsilon condition reached!\\n\";\n       }*/\n\n       return rmvsteps;\n\n   }\n\n   //--------------------------------------------------------------------------\n   void DelaunayTriangulation::Reduce(int nPoints)\n   {\n      std::vector<DelaunayVertex*> vVertex;\n      int rmvsteps = 0;\n      if (!_bError)\n         CalculateVertexErrors();\n\n      while (_minError != DBL_MAX && rmvsteps < nPoints)\n      {\n         GetCCWVertices(_oVertexMinError.pTri, _oVertexMinError.idx0, vVertex);\n         RemoveLeastErrorVertex(); rmvsteps++;\n         UpdateVertexErrors(vVertex);\n      }\n   }\n\n   //--------------------------------------------------------------------------\n\n   void DelaunayTriangulation::_GetVertexAt(double x, double y, DelaunayTriangle*& pTri, int& idx)\n   {\n      ePointTriangleRelation e;\n      pTri = _qLocationStructure->GetTriangleAt(x,y,e);\n      if (pTri)\n      {\n         const ElevationPoint& P0 = pTri->GetVertex(0)->GetElevationPoint();\n         const ElevationPoint& P1 = pTri->GetVertex(1)->GetElevationPoint();\n         const ElevationPoint& P2 = pTri->GetVertex(2)->GetElevationPoint();\n\n         double dist0, dist1, dist2;\n\n         dist0 = sqrt((P0.x-x)*(P0.x-x)+(P0.y-y)*(P0.y-y));\n         dist1 = sqrt((P1.x-x)*(P1.x-x)+(P1.y-y)*(P1.y-y));\n         dist2 = sqrt((P2.x-x)*(P2.x-x)+(P2.y-y)*(P2.y-y));\n\n         if (dist0 <= dist1 && dist0 <= dist2)\n         {   \n            idx = 0;\n         }\n         else if (dist1 <= dist0 && dist1 <= dist2)\n         {\n            idx = 1;\n         }\n         else //if (dist2 <= dist0 && dist2 <=dist1)\n         {\n            idx = 2;\n         }\n      }\n      else\n      {\n         // no triangle found!!\n         idx = -1;\n      }\n   }\n\n   //--------------------------------------------------------------------------\n\n   void DelaunayTriangulation::GetCCWTriangles(DelaunayTriangle* pTri, int vertex_index, std::vector<STriangleVertex>& outputVertices)\n   {\n      outputVertices.clear();\n      std::list<STriangleVertex> lst;\n\n      const DelaunayTriangle* pStartTriangle = pTri;\n\n      STriangleVertex oElement;\n      int vtx = vertex_index;\n      int triangle_index = (vtx+2)%3;\n\n      oElement.pTri = pTri;\n      oElement.idx0 = (vertex_index+1)%3;\n      lst.push_front(oElement);\n\n      DelaunayTriangle* A = pTri;\n      DelaunayTriangle* B;\n      DelaunayTriangle* C = pTri->GetTriangle(triangle_index);\n\n\n      while(C && C != pStartTriangle)\n      {\n         if (A->GetVertex(vtx) == C->GetVertex(0))\n         {\n            vtx = 0;\n         }\n         else if (A->GetVertex(vtx) == C->GetVertex(1))\n         {\n            vtx = 1;\n         }\n         else if (A->GetVertex(vtx) == C->GetVertex(2))\n         {\n            vtx = 2;\n         }\n         else\n         {\n            assert(false);\n            break;\n         }\n\n         oElement.pTri = C;\n         oElement.idx0 = (vtx+1)%3;\n         lst.push_front(oElement);\n\n         triangle_index = (vtx+2)%3; \n         A = C;\n         C = C->GetTriangle(triangle_index);\n      }\n\n      // move around other side:\n\n      if (C != pStartTriangle)\n      {\n         vtx = vertex_index;\n         triangle_index = vtx;\n\n         A = pTri;\n         B = pTri->GetTriangle(triangle_index);\n\n         while(B && B != pStartTriangle)\n         {\n            if (A->GetVertex(vtx) == B->GetVertex(0))\n            {\n               vtx = 0;\n            }\n            else if (A->GetVertex(vtx) == B->GetVertex(1))\n            {\n               vtx = 1;\n            }\n            else if (A->GetVertex(vtx) == B->GetVertex(2))\n            {\n               vtx = 2;\n            }\n\n            oElement.pTri = B;\n            oElement.idx0 = (vtx+1)%3;\n            lst.push_back(oElement);\n            triangle_index = vtx; \n\n            A = B;\n            B = B->GetTriangle(triangle_index);\n         }\n\n      }\n\n      std::reverse(lst.begin(), lst.end());\n\n      // copy result to output\n      std::list<STriangleVertex>::iterator it = lst.begin();\n      while (it!=lst.end())\n      {\n         outputVertices.push_back(*it);\n         it++;\n      }\n   }\n\n   //--------------------------------------------------------------------------\n\n   void DelaunayTriangulation::GetCCWVertices(DelaunayTriangle* pTri, int vertex_index, std::vector<DelaunayVertex*>& outputVertices)\n   {\n      outputVertices.clear();\n      std::list<DelaunayVertex*> lst;\n\n      const DelaunayTriangle* pStartTriangle = pTri;\n\n      int vtx = vertex_index;\n      int triangle_index = (vtx+2)%3;\n\n      lst.push_front(pTri->GetVertex((vertex_index+1)%3));\n\n      DelaunayTriangle* A = pTri;\n      DelaunayTriangle* B;\n      DelaunayTriangle* C = pTri->GetTriangle(triangle_index);\n\n\n      while(C && C != pStartTriangle)\n      {\n         if (A->GetVertex(vtx) == C->GetVertex(0))\n         {\n            vtx = 0;\n         }\n         else if (A->GetVertex(vtx) == C->GetVertex(1))\n         {\n            vtx = 1;\n         }\n         else if (A->GetVertex(vtx) == C->GetVertex(2))\n         {\n            vtx = 2;\n         }\n         else\n         {\n            assert(false);\n            break;\n         }\n\n         lst.push_front(C->GetVertex((vtx+1)%3));\n\n         triangle_index = (vtx+2)%3; \n         A = C;\n         C = C->GetTriangle(triangle_index);\n      }\n\n      // move around other side:\n\n      if (C != pStartTriangle)\n      {\n         vtx = vertex_index;\n         triangle_index = vtx;\n\n         A = pTri;\n         B = pTri->GetTriangle(triangle_index);\n\n         while(B && B != pStartTriangle)\n         {\n            if (A->GetVertex(vtx) == B->GetVertex(0))\n            {\n               vtx = 0;\n            }\n            else if (A->GetVertex(vtx) == B->GetVertex(1))\n            {\n               vtx = 1;\n            }\n            else if (A->GetVertex(vtx) == B->GetVertex(2))\n            {\n               vtx = 2;\n            }\n\n            lst.push_back(B->GetVertex((vtx+1)%3));\n            triangle_index = vtx; \n\n            A = B;\n            B = B->GetTriangle(triangle_index);\n         }\n\n      }\n\n      std::reverse(lst.begin(), lst.end());\n\n      // copy result to output\n      std::list<DelaunayVertex*>::iterator it = lst.begin();\n      while (it!=lst.end())\n      {\n         outputVertices.push_back(*it);\n         it++;\n      }\n   }\n\n   //--------------------------------------------------------------------------\n\n   void DelaunayTriangulation::_RemoveVertex(DelaunayTriangle* pTri, int idx)\n   {\n      if (pTri && idx>=0 && idx<=3)\n      {\n         bool DebugOutput = false;\n         DelaunayVertex* pVertex = pTri->GetVertex(idx); // this is the point P to be removed.\n\n         std::vector<STriangleVertex> outputTriangles;\n         GetCCWTriangles(pTri, idx, outputTriangles);\n\n         if (outputTriangles.size() < 3 )\n         {\n            // this can't happen in a \"normal\" triangulation\n            // unless you try to remove supersimplex corner.\n            // however this can happen in a triangulation with holes. This\n            // case is currently not supported!\n            std::cout<< \"*Error* Can't remove specified vertex! (Triangulation would be broken.)\\n\";\n            return;\n         }\n         else\n         {\n            //std::cout << \"-----------------------------\\n\";\n            //std::cout << \"Removing Point\\n\";\n            do \n            {\n               size_t num_changes = 0;\n\n               //std::cout << \"outputTriangles: \" << outputTriangles.size() << \"\\n\";\n\n               if (outputTriangles.size() > 3)\n               {\n\n\n                  std::vector<STriangleVertex>::iterator it = outputTriangles.begin();\n\n                  while (it != outputTriangles.end() && outputTriangles.size()>3)\n                  {\n\n                     DelaunayTriangle* pCurrentTriangle = (*it).pTri;\n                     int idx0 = (*it).idx0;\n                     int idx1 = (idx0+1)%3;\n\n\n                     DelaunayVertex* s0 = pCurrentTriangle->GetVertex(idx0);\n                     DelaunayVertex* s1 = pCurrentTriangle->GetVertex(idx1);\n                     DelaunayVertex* s2 = pCurrentTriangle->GetOppositeVertex(idx1);\n\n                     // for debugging reasons only:\n                     ElevationPoint s0p = s0->GetElevationPoint(); \n                     ElevationPoint s1p = s1->GetElevationPoint(); \n                     ElevationPoint s2p = s2->GetElevationPoint(); \n                     ElevationPoint sP = pVertex->GetElevationPoint();\n\n                     double ccwpredicate = math::ccw(s0,s1,s2);\n\n                     if (DebugOutput)\n                        std::cout << \"ccwpredicate0 = \" << ccwpredicate << \"\\n\";\n\n                     if (ccwpredicate<=0)\n                     {\n                        // this triangle-combination is ignored!\n                     }\n                     else\n                     {\n                        ccwpredicate = math::ccw(s0,s2,pVertex);\n                        if (DebugOutput)\n                           std::cout << \"ccwpredicate1 = \" << ccwpredicate << \"\\n\";\n                        if (ccwpredicate<0) // P encloses Triangle ?\n                        {\n                           \n                           // this triangle-combination is ignored!\n                        }\n                        else\n                        {\n                           // Check if other points are inside cirumcircle!\n                           bool bCircleTest = true;\n\n                           std::vector<STriangleVertex>::iterator it2 = outputTriangles.begin();\n                           while (it2 != outputTriangles.end())\n                           {     \n                              if ((*it2).pTri != (*it).pTri)\n                              {\n                                 int tidx0 = (*it2).idx0;\n                                 int tidx1 = (tidx0+1)%3;\n\n                                 DelaunayVertex* p0 = (*it2).pTri->GetVertex(tidx0);\n                                 DelaunayVertex* p1 = (*it2).pTri->GetVertex(tidx1);\n\n                                 assert(p0 != pVertex);\n                                 assert(p1 != pVertex);\n                                 \n                                 if (p0 != s0 && p0 != s1 && p0 != s2 && \n                                     p1 != s0 && p1 != s1 && p1 != s2)\n                                 {\n                                    double circ = math::InCircleValue(s0,s1,s2,p0);\n                                    if (DebugOutput)\n                                       std::cout << \"circ0 = \" << circ << \"\\n\";\n                                    if (circ >= DBL_EPSILON)\n                                    {\n                                       bCircleTest = false;\n                                    }\n                                    circ = math::InCircleValue(s0,s1,s2,p1);\n                                    if (DebugOutput)\n                                       std::cout << \"circ1 = \" << circ << \"\\n\";\n                                    if (circ >= DBL_EPSILON)\n                                    {\n                                       bCircleTest = false;\n                                    }\n                                 }\n                              }\n                              it2++;\n                           }\n\n                           if (bCircleTest)\n                           {\n                              // this triangle and (next) are swapped and removed from list.\n                              // new (swapped) triangle containing P will be added to list.\n\n                              DelaunayTriangle* C;\n                              DelaunayTriangle* D;\n\n                              if (pCurrentTriangle->FlipEdge(idx1, &C, &D))\n                              {\n                                 it = outputTriangles.erase(it);\n                                 if (it==outputTriangles.end())\n                                 {\n                                    it = outputTriangles.begin();\n                                 }\n                                 it = outputTriangles.erase(it);\n\n                                 STriangleVertex newElement;\n\n                                 if (C->GetVertex(0) == pVertex)\n                                 {\n                                    newElement.pTri = C; newElement.idx0 = 1;\n                                 }\n                                 else if (C->GetVertex(1) == pVertex)\n                                 {\n                                    newElement.pTri = C; newElement.idx0 = 2;\n                                 }\n                                 else if (C->GetVertex(2) == pVertex)\n                                 {\n                                    newElement.pTri = C; newElement.idx0 = 0;\n                                 }\n                                 else if (D->GetVertex(0) == pVertex)\n                                 {\n                                    newElement.pTri = D; newElement.idx0 = 1;\n                                 }\n                                 else if (D->GetVertex(1) == pVertex)\n                                 {\n                                    newElement.pTri = D; newElement.idx0 = 2;\n                                 }\n                                 else if (D->GetVertex(2) == pVertex)\n                                 {\n                                    newElement.pTri = D; newElement.idx0 = 0;\n                                 }\n                                 else\n                                 {\n                                    assert(false);\n                                 }\n\n                                 it = outputTriangles.insert(it, newElement);\n                                 num_changes++;\n                              }\n                              else\n                              {\n                                 // can't flip\n                              }\n                           }\n\n                        }\n                     }\n\n\n                     it++;\n                  }  \n               }\n\n               if (outputTriangles.size()>3 && num_changes == 0)\n               {\n                  std::cout << \"<b>*WARNING* Detected infinite loop!</b>\\n\";\n                  pVertex->GetElevationPoint().error = -0.5;\n\n                  if (DebugOutput)\n                     break;\n                  else\n                     DebugOutput = true;\n               }\n\n\n               // 3 Remaining pairs: Remove 3 Triangles!!\n               if (outputTriangles.size() == 3)\n               {\n                  STriangleVertex* st0 =  &outputTriangles[0];\n                  STriangleVertex* st1 =  &outputTriangles[1];\n                  STriangleVertex* st2 =  &outputTriangles[2];\n\n                  // Create New Triangle\n                  DelaunayTriangle* pNewTriangle = DelaunayMemoryManager::AllocTriangle();\n                  pNewTriangle->SetVertex(0, st0->pTri->GetVertex(st0->idx0));\n                  pNewTriangle->SetVertex(1, st1->pTri->GetVertex(st1->idx0));\n                  pNewTriangle->SetVertex(2, st2->pTri->GetVertex(st2->idx0));\n\n\n                  DelaunayTriangle* pNeighbour0 = st0->pTri->GetTriangle(st0->idx0);\n                  int nr0 = st0->pTri->NeighbourReference(st0->idx0);\n\n                  DelaunayTriangle* pNeighbour1 = st1->pTri->GetTriangle(st1->idx0);\n                  int nr1 = st1->pTri->NeighbourReference(st1->idx0);\n\n                  DelaunayTriangle* pNeighbour2 = st2->pTri->GetTriangle(st2->idx0);\n                  int nr2 = st2->pTri->NeighbourReference(st2->idx0);\n\n                  pNewTriangle->SetTriangle(0, pNeighbour0);\n                  pNewTriangle->SetTriangle(1, pNeighbour1);\n                  pNewTriangle->SetTriangle(2, pNeighbour2);\n\n                  _qLocationStructure->DeleteMemory(st0->pTri);\n                  _qLocationStructure->DeleteMemory(st1->pTri);\n                  _qLocationStructure->DeleteMemory(st2->pTri);\n\n                  if (pNeighbour0) \n                     pNeighbour0->SetTriangle(nr0, pNewTriangle);\n\n                  if (pNeighbour1)\n                     pNeighbour1->SetTriangle(nr1, pNewTriangle);\n\n                  if (pNeighbour2)\n                     pNeighbour2->SetTriangle(nr2, pNewTriangle);\n\n                  _qLocationStructure->AddTriangle(pNewTriangle);\n\n                  //assert(pNewTriangle->IsCCW()); // the mosted hated assertion\n               }\n\n            } \n            while (outputTriangles.size()>3);   \n         }\n\n      }\n   }\n\n   //--------------------------------------------------------------------------\n\n   void DelaunayTriangulation::RemoveVertex(double x, double y)\n   {\n      int idx;\n      DelaunayTriangle* pTri;\n      _GetVertexAt(x,y,pTri,idx);\n      _RemoveVertex(pTri,idx);\n   }\n\n   //--------------------------------------------------------------------------\n\n} // namespace\n\n", "meta": {"hexsha": "ca383ff6b62e37a2f1a7359678165bf2211a7f5b", "size": 40941, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "source/og-core/math/delaunay/DelaunayTriangulation.cpp", "max_stars_repo_name": "OpenWebGlobe/Application-SDK", "max_stars_repo_head_hexsha": "b819ca8ccb44b70815f6c5332cfb041ea23dab61", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2015-12-20T01:38:05.000Z", "max_stars_repo_stars_event_max_datetime": "2019-07-02T11:01:29.000Z", "max_issues_repo_path": "source/og-core/math/delaunay/DelaunayTriangulation.cpp", "max_issues_repo_name": "OpenWebGlobe/Application-SDK", "max_issues_repo_head_hexsha": "b819ca8ccb44b70815f6c5332cfb041ea23dab61", "max_issues_repo_licenses": ["MIT"], "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/og-core/math/delaunay/DelaunayTriangulation.cpp", "max_forks_repo_name": "OpenWebGlobe/Application-SDK", "max_forks_repo_head_hexsha": "b819ca8ccb44b70815f6c5332cfb041ea23dab61", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2015-01-20T09:18:39.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-06T08:19:30.000Z", "avg_line_length": 31.0865603645, "max_line_length": 146, "alphanum_fraction": 0.4626657874, "num_tokens": 9675, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7185943805178139, "lm_q2_score": 0.476579651063676, "lm_q1q2_score": 0.34246745912349813}}
{"text": "#include <iostream>\n#include <Eigen/Dense>\n#include <random>\n#include <vector>\n#include <iomanip>\n#include <fstream>\n#include <bitset>\n#include <string>\n#include <map>\n\n#ifndef QST_TOMOGRAPHY_HPP\n#define QST_TOMOGRAPHY_HPP\n\nnamespace qst{\n\n//Quantum State Tomography class\ntemplate<class NNState,class Observer,class Optimizer> class Tomography {\n\n    NNState & NNstate_;                         // Neural network representation of the state\n    Optimizer & opt_;                           // Optimizer\n    Observer &obs_;                             // Observer\n\n    int N_;                                     // Number of physical degrees of freedom\n    int npar_;                                  // Number of variational parameters\n    int nparLambda_;                            // Number of amplitude variational parameters\n    int nparMu_;                                // Number of phase variational parameters\n    int bs_;                                    // Batch size\n    int cd_;                                    // Number of Gibbs stepos in contrastive divergence\n    int epochs_;                                // Number of training iterations\n    double lr_;                                 // Learning rate\n    double l2_;                                 // L2 regularization constant\n\n    Eigen::VectorXd grad_;                      // Gradients \n    Eigen::VectorXcd rotated_grad_;             // Rotated gradients\n    std::mt19937 rgen_;                         // Random number generator\n    std::map<std::string,Eigen::MatrixXcd> U_;  // Structure containin the single unitary rotations\npublic:\n    \n    Tomography(Optimizer & opt,NNState & NNstate,Observer &obs,Parameters &par):opt_(opt),NNstate_(NNstate),obs_(obs),N_(NNstate.N()),bs_(par.bs_),cd_(par.cd_) {\n            \n        npar_=NNstate_.Npar();\n        nparLambda_ = NNstate_.NparLambda();\n        nparMu_ = NNstate_.NparMu();\n        opt_.SetNpar(npar_);\n        bs_ = par.bs_;\n        cd_ = par.cd_;\n        lr_ = par.lr_;\n        l2_ = par.l2_;\n        epochs_ = par.ep_;\n        grad_.resize(npar_);\n        rotated_grad_.resize(npar_);\n    }\n\n    //Compute gradient of KL divergence \n    void ComputeGradient(const Eigen::MatrixXd & batchSamples,const std::vector<std::vector<std::string> >& batchBases){ \n        grad_.setZero();\n\n        int bID = 0;\n        //Positive Phase\n        for(int k=0;k<bs_;k++){\n            bID = 0;\n            for(int j=0;j<N_;j++){ // Check if the basis is the reference one\n                if (batchBases[k][j]!=\"Z\"){\n                    bID = 1;\n                    break;\n                }\n            }\n            if (bID==0){ // Positive phase - Lambda gradient in the reference basis\n                grad_.head(nparLambda_) += NNstate_.LambdaGrad(batchSamples.row(k))/double(bs_);\n            }\n            else { // Positive phase - Lambda and Mu gradients for non-trivial bases\n                NNstate_.rotatedGrad(batchBases[k],batchSamples.row(k),U_,rotated_grad_);\n                //getRotatedGradient(batchBases[k],batchSamples.row(k),rotated_grad_);\n                grad_.head(nparLambda_) += rotated_grad_.head(nparLambda_).real()/double(bs_);\n                grad_.tail(nparMu_) -= rotated_grad_.tail(nparMu_).imag()/double(bs_);\n            }\n        }\n        \n        //Negative Phase\n        NNstate_.Sample(cd_);\n        for(int k=0;k<NNstate_.Nchains();k++){\n            grad_.head(nparLambda_) -= NNstate_.LambdaGrad(NNstate_.VisibleStateRow(k))/double(NNstate_.Nchains());\n        }\n        opt_.getUpdates(grad_);\n    }\n    \n    // Update rbm parameters\n    void UpdateParameters(){\n        auto pars=NNstate_.GetParameters();\n        opt_.Update(pars);\n        NNstate_.SetParameters(pars);\n    }\n    \n    ////Run the tomography\n    void Run(Eigen::MatrixXd & trainData,std::vector<std::vector<std::string> >& trainBases){\n        //opt_.Reset();\n        int index;\n        int counter = 0;\n        int trainSize = trainData.rows();\n        int saveFrequency =  int(trainSize / bs_);\n        Eigen::MatrixXd batch_samples;\n        std::vector<std::vector<std::string> > batch_bases;\n        std::uniform_int_distribution<int> distribution(0,trainSize-1);\n        \n        int epoch = 0;\n        for(int i=0;i<epochs_;i++){\n            // Randomize a batch and set the visible layer to a data point \n            SetUpTrainingStep(trainData,batch_samples,trainBases,batch_bases,distribution); \n            // Perform one step of optimization\n            ComputeGradient(batch_samples,batch_bases);\n            UpdateParameters();\n            //Compute stuff and print\n            if (counter == saveFrequency){\n                epoch += 1;\n                obs_.Scan(epoch);\n                counter = 0;\n            }\n            counter++;\n        }\n    }\n    \n    //Set the value of the target wavefunction\n    void setBasisRotations(std::map<std::string,Eigen::MatrixXcd> & U){\n        U_ = U;\n    }\n    // Setup the training batch and visible layer initial configuration\n    void SetUpTrainingStep(Eigen::MatrixXd & trainData,\n                           Eigen::MatrixXd &batch_samples,\n                           std::vector<std::vector<std::string> >& trainBases,\n                           std::vector<std::vector<std::string> > &batch_bases,\n                           std::uniform_int_distribution<int> & distribution){\n            int index;\n            // Initialize the visible layer to random data samples\n            batch_samples.resize(NNstate_.Nchains(),N_);\n            for(int k=0;k<NNstate_.Nchains();k++){\n                index = distribution(rgen_);\n                batch_samples.row(k) = trainData.row(index);\n            }\n            NNstate_.SetVisibleLayer(batch_samples);\n            \n            // Build the batch of data\n            batch_samples.resize(bs_,N_); \n            batch_bases.resize(bs_,std::vector<std::string>(N_));\n            for(int k=0;k<bs_;k++){\n                index = distribution(rgen_);\n                batch_samples.row(k) = trainData.row(index);\n                batch_bases[k] = trainBases[index];\n            }\n    }\n};\n}\n\n#endif\n", "meta": {"hexsha": "48490cf4547f4c7a100937c3a5de3ad56e73a1c2", "size": 6136, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "qucumber/cpp/tomography.hpp", "max_stars_repo_name": "PatrickHuembeli/QuCumber", "max_stars_repo_head_hexsha": "a9f8912a086f334ab2af20bf52493a528332a214", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-10-02T10:03:45.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-02T10:03:45.000Z", "max_issues_repo_path": "qucumber/cpp/tomography.hpp", "max_issues_repo_name": "PatrickHuembeli/QuCumber", "max_issues_repo_head_hexsha": "a9f8912a086f334ab2af20bf52493a528332a214", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "qucumber/cpp/tomography.hpp", "max_forks_repo_name": "PatrickHuembeli/QuCumber", "max_forks_repo_head_hexsha": "a9f8912a086f334ab2af20bf52493a528332a214", "max_forks_repo_licenses": ["Apache-2.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.8441558442, "max_line_length": 161, "alphanum_fraction": 0.5498696219, "num_tokens": 1352, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7490872131147275, "lm_q2_score": 0.4571367168274948, "lm_q1q2_score": 0.3424352692207244}}
{"text": "/*******************************************************************************\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 * 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 <gmpxx.h>\n#include <boost/functional/hash.hpp>\n#include <crab/common/types.hpp>\n\nnamespace ikos {\n\nclass z_number {\n  friend class q_number;\n\nprivate:\n  mpz_class _n;\n\npublic:\n\n  z_number(mpz_class n) : _n(n) {}\n\n  static z_number from_ulong(unsigned long n) {\n    mpz_class b(n);\n    return z_number(b);\n  }\n\n  static z_number from_slong(signed long n) {\n    mpz_class b(n);\n    return z_number(b);\n  }\n\n  // overloaded typecast operators\n  explicit operator long() const { \n    if (_n.fits_slong_p ()) {\n      return _n.get_si ();\n    }\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    }\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 { \n    return _n;\n  } \n\npublic:\n\n  z_number() : _n(0) {}\n\n  z_number(std::string s) {\n    try {\n      this->_n = s;\n    } catch (std::invalid_argument& e) {\n      CRAB_ERROR (\"z_number: invalid string in constructor\", s);\n    }\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  std::string get_str () const {\n    return _n.get_str();\n  }\n\n  bool fits_sint() const {\n    return _n.fits_sint_p();\n  }\n\n  bool fits_slong() const {\n    return _n.fits_slong_p();\n  }\n\n  z_number operator+(z_number x) const {\n    mpz_class r = this->_n + x._n;\n    return z_number(r);\n  }\n\n  z_number operator*(z_number x) const {\n    mpz_class r = this->_n * x._n;\n    return z_number(r);\n  }\n\n  z_number operator-(z_number x) const {\n    mpz_class r = this->_n - x._n;\n    return z_number(r);\n  }\n\n  z_number operator-() const {\n    mpz_class r = -this->_n;\n    return z_number(r);\n  }\n\n  z_number operator/(z_number x) const {\n    if (x._n == 0) {\n      CRAB_ERROR(\"z_number: division by zero [1]\");\n    } else {\n      mpz_class r = this->_n / x._n;\n      return z_number(r);\n    }\n  }\n\n  z_number operator%(z_number x) const {\n    if (x._n == 0) {\n      CRAB_ERROR(\"z_number: division by zero [2]\");\n    } else {\n      mpz_class r = this->_n % x._n;\n      return z_number(r);\n    }\n  }\n\n  z_number& operator+=(z_number x) {\n    this->_n += x._n;\n    return *this;\n  }\n\n  z_number& operator*=(z_number x) {\n    this->_n *= x._n;\n    return *this;\n  }\n\n  z_number& operator-=(z_number x) {\n    this->_n -= x._n;\n    return *this;\n  }\n\n  z_number& operator/=(z_number x) {\n    if (x._n == 0) {\n      CRAB_ERROR(\"z_number: division by zero [3]\");\n    } else {\n      this->_n /= x._n;\n      return *this;\n    }\n  }\n\n  z_number& operator%=(z_number x) {\n    if (x._n == 0) {\n      CRAB_ERROR(\"z_number: division by zero [4]\");\n    } else {\n      this->_n %= x._n;\n      return *this;\n    }\n  }\n\n  z_number& operator--() {\n    --(this->_n);\n    return *this;\n  }\n\n  z_number& operator++() {\n    ++(this->_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==(z_number x) const { return this->_n == x._n; }\n\n  bool operator!=(z_number x) const { return this->_n != x._n; }\n\n  bool operator<(z_number x) const { return this->_n < x._n; }\n\n  bool operator<=(z_number x) const { return this->_n <= x._n; }\n\n  bool operator>(z_number x) const { return this->_n > x._n; }\n\n  bool operator>=(z_number x) const { return this->_n >= x._n; }\n\n  z_number operator&(z_number x) const { return z_number(this->_n & x._n); }\n\n  z_number operator|(z_number x) const { return z_number(this->_n | x._n); }\n\n  z_number operator^(z_number x) const { return z_number(this->_n ^ x._n); }\n\n  z_number operator<<(z_number x) const {\n    mpz_t tmp;\n    mpz_init(tmp);\n    mpz_mul_2exp(tmp, this->_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>>(z_number x) const {\n    mpz_class tmp(this->_n);\n    return z_number(tmp.operator>>=(mpz_get_ui(x._n.get_mpz_t())));\n  }\n\n  z_number fill_ones() const {\n    assert(this->_n >= 0);\n    if (this->_n == 0) {\n      return z_number(0);\n    }\n\n    mpz_class result;\n    for (result = 1; result < this->_n; result = 2 * result + 1)\n      ;\n    return z_number(result);\n  }\n\n  void write(crab::crab_os& o) { o << this->_n.get_str(); }\n\n}; // class z_number\n\ninline crab::crab_os& operator<<(crab::crab_os& o, z_number z) {\n  z.write(o);\n  return o;\n}\n\ninline std::size_t hash_value(const z_number& n) {\n  boost::hash<std::string> hasher;\n  return hasher(n.get_str());\n}\n\nclass q_number {\nprivate:\n  mpq_class _n;\n\npublic:\n  \n  q_number() : _n(0) {}\n\n  q_number(mpq_class n) : _n(n) {}\n  \n  q_number(std::string s) {\n    try {\n      this->_n = s;\n      this->_n.canonicalize();\n    } catch (std::invalid_argument& e) {\n      CRAB_ERROR(\"q_number: invalid string in constructor \",s);\n    }\n  }\n\n  q_number(double n): _n(n) { this->_n.canonicalize(); }\n  \n  q_number(z_number n) : _n(n._n) { this->_n.canonicalize(); }\n\n  q_number(z_number n, z_number d) : _n(n._n, d._n) { this->_n.canonicalize(); }\n\n  explicit operator mpq_class() const { \n    return _n;\n  } \n\n  std::string get_str () const {\n    return _n.get_str();\n  }\n\n  q_number operator+(q_number x) const {\n    mpq_class r = this->_n + x._n;\n    return q_number(r);\n  }\n\n  q_number operator*(q_number x) const {\n    mpq_class r = this->_n * x._n;\n    return q_number(r);\n  }\n\n  q_number operator-(q_number x) const {\n    mpq_class r = this->_n - x._n;\n    return q_number(r);\n  }\n\n  q_number operator-() const {\n    mpq_class r = -this->_n;\n    return q_number(r);\n  }\n\n  q_number operator/(q_number x) const {\n    if (x._n == 0) {\n      CRAB_ERROR(\"q_number: division by zero [1]\");\n    } else {\n      mpq_class r = this->_n / x._n;\n      return q_number(r);\n    }\n  }\n\n  q_number& operator+=(q_number x) {\n    this->_n += x._n;\n    return *this;\n  }\n\n  q_number& operator*=(q_number x) {\n    this->_n *= x._n;\n    return *this;\n  }\n\n  q_number& operator-=(q_number x) {\n    this->_n -= x._n;\n    return *this;\n  }\n\n  q_number& operator/=(q_number x) {\n    if (x._n == 0) {\n      CRAB_ERROR(\"q_number: division by zero [2]\");\n    } else {\n      this->_n /= x._n;\n      return *this;\n    }\n  }\n\n  q_number& operator--() {\n    --(this->_n);\n    return *this;\n  }\n\n  q_number& operator++() {\n    ++(this->_n);\n    return *this;\n  }\n\n  q_number operator--(int) {\n    q_number r(*this);\n    --(*this);\n    return r;\n  }\n\n  q_number operator++(int) {\n    q_number r(*this);\n    ++(*this);\n    return r;\n  }\n\n  bool operator==(q_number x) const { return this->_n == x._n; }\n\n  bool operator!=(q_number x) const { return this->_n != x._n; }\n\n  bool operator<(q_number x) const { return this->_n < x._n; }\n\n  bool operator<=(q_number x) const { return this->_n <= x._n; }\n\n  bool operator>(q_number x) const { return this->_n > x._n; }\n\n  bool operator>=(q_number x) const { return this->_n >= x._n; }\n\n  z_number numerator() const { return z_number(this->_n.get_num()); }\n\n  z_number denominator() const { return z_number(this->_n.get_den()); }\n\n  z_number round_to_upper() const {\n    z_number num = numerator();\n    z_number den = denominator();\n    z_number q = num / den;\n    z_number r = num % den;\n    if (r == 0 || *this < 0) {\n      return q;\n    } else {\n      return q + 1;\n    }\n  }\n\n  z_number round_to_lower() const {\n    z_number num = numerator();\n    z_number den = denominator();\n    z_number q = num / den;\n    z_number r = num % den;\n    if (r == 0 || *this > 0) {\n      return q;\n    } else {\n      return q - 1;\n    }\n  }\n\n  void write(crab::crab_os& o) { o << this->_n.get_str(); }\n\n}; // class q_number\n\ninline crab::crab_os& operator<<(crab::crab_os& o, q_number q) {\n  q.write(o);\n  return o;\n}\n\ninline std::size_t hash_value(const q_number& n) {\n  boost::hash<std::string> hasher;\n  return hasher(n.get_str());\n}\n}\n\n", "meta": {"hexsha": "eb9c1374566b4b03b49aa0037491bc93e104bf57", "size": 10381, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/crab/common/bignums.hpp", "max_stars_repo_name": "bishoksan/crab-latest", "max_stars_repo_head_hexsha": "204762a5fc44318e3f9bc2ba23bb9f58348778e6", "max_stars_repo_licenses": ["Apache-2.0"], "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/common/bignums.hpp", "max_issues_repo_name": "bishoksan/crab-latest", "max_issues_repo_head_hexsha": "204762a5fc44318e3f9bc2ba23bb9f58348778e6", "max_issues_repo_licenses": ["Apache-2.0"], "max_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/common/bignums.hpp", "max_forks_repo_name": "bishoksan/crab-latest", "max_forks_repo_head_hexsha": "204762a5fc44318e3f9bc2ba23bb9f58348778e6", "max_forks_repo_licenses": ["Apache-2.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.700913242, "max_line_length": 93, "alphanum_fraction": 0.6108274733, "num_tokens": 3035, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6261241772283034, "lm_q2_score": 0.5467381519846138, "lm_q1q2_score": 0.34232597557068944}}
{"text": "#ifndef STAN_MATH_PRIM_ARR_FUNCTOR_INTEGRATE_ODE_RK45_HPP\n#define STAN_MATH_PRIM_ARR_FUNCTOR_INTEGRATE_ODE_RK45_HPP\n\n#include <stan/math/prim/arr/err/check_nonzero_size.hpp>\n#include <stan/math/prim/arr/err/check_ordered.hpp>\n#include <stan/math/prim/arr/functor/coupled_ode_system.hpp>\n#include <stan/math/prim/arr/functor/coupled_ode_observer.hpp>\n#include <stan/math/prim/scal/fun/value_of.hpp>\n#include <stan/math/prim/scal/err/check_less.hpp>\n#include <stan/math/prim/scal/err/check_finite.hpp>\n#include <stan/math/prim/scal/err/invalid_argument.hpp>\n#include <stan/math/prim/scal/meta/return_type.hpp>\n#include <boost/version.hpp>\n#if BOOST_VERSION == 106400\n#include <boost/serialization/array_wrapper.hpp>\n#endif\n#include <boost/numeric/odeint.hpp>\n#include <ostream>\n#include <vector>\n\nnamespace stan {\nnamespace math {\n\n/**\n * Return the solutions for the specified system of ordinary\n * differential equations given the specified initial state,\n * initial times, times of desired solution, and parameters and\n * data, writing error and warning messages to the specified\n * stream.\n *\n * <b>Warning:</b> If the system of equations is stiff, roughly\n * defined by having varying time scales across dimensions, then\n * this solver is likely to be slow.\n *\n * This function is templated to allow the initial times to be\n * either data or autodiff variables and the parameters to be data\n * or autodiff variables.  The autodiff-based implementation for\n * reverse-mode are defined in namespace <code>stan::math</code>\n * and may be invoked via argument-dependent lookup by including\n * their headers.\n *\n * This function uses the <a\n * href=\"http://en.wikipedia.org/wiki/Dormand–Prince_method\">Dormand-Prince\n * method</a> as implemented in Boost's <code>\n * boost::numeric::odeint::runge_kutta_dopri5</code> integrator.\n *\n * @tparam F type of ODE system function.\n * @tparam T1 type of scalars for initial values.\n * @tparam T2 type of scalars for parameters.\n * @param[in] f functor for the base ordinary differential equation.\n * @param[in] y0 initial state.\n * @param[in] t0 initial time.\n * @param[in] ts times of the desired solutions, in strictly\n * increasing order, all greater than the initial time.\n * @param[in] theta parameter vector for the ODE.\n * @param[in] x continuous data vector for the ODE.\n * @param[in] x_int integer data vector for the ODE.\n * @param[out] msgs the print stream for warning messages.\n * @param[in] relative_tolerance relative tolerance parameter\n *   for Boost's ode solver. Defaults to 1e-6.\n * @param[in] absolute_tolerance absolute tolerance parameter\n *   for Boost's ode solver. Defaults to 1e-6.\n * @param[in] max_num_steps maximum number of steps to take within\n *   the Boost ode solver.\n * @return a vector of states, each state being a vector of the\n * same size as the state variable, corresponding to a time in ts.\n */\ntemplate <typename F, typename T1, typename T2>\nstd::vector<std::vector<typename stan::return_type<T1, T2>::type> >\nintegrate_ode_rk45(const F& f, const std::vector<T1>& y0, double t0,\n                   const std::vector<double>& ts, const std::vector<T2>& theta,\n                   const std::vector<double>& x, const std::vector<int>& x_int,\n                   std::ostream* msgs = nullptr,\n                   double relative_tolerance = 1e-6,\n                   double absolute_tolerance = 1e-6, int max_num_steps = 1E6) {\n  using boost::numeric::odeint::integrate_times;\n  using boost::numeric::odeint::make_dense_output;\n  using boost::numeric::odeint::max_step_checker;\n  using boost::numeric::odeint::runge_kutta_dopri5;\n\n  check_finite(\"integrate_ode_rk45\", \"initial state\", y0);\n  check_finite(\"integrate_ode_rk45\", \"initial time\", t0);\n  check_finite(\"integrate_ode_rk45\", \"times\", ts);\n  check_finite(\"integrate_ode_rk45\", \"parameter vector\", theta);\n  check_finite(\"integrate_ode_rk45\", \"continuous data\", x);\n\n  check_nonzero_size(\"integrate_ode_rk45\", \"times\", ts);\n  check_nonzero_size(\"integrate_ode_rk45\", \"initial state\", y0);\n  check_ordered(\"integrate_ode_rk45\", \"times\", ts);\n  check_less(\"integrate_ode_rk45\", \"initial time\", t0, ts[0]);\n\n  if (relative_tolerance <= 0)\n    invalid_argument(\"integrate_ode_rk45\", \"relative_tolerance,\",\n                     relative_tolerance, \"\", \", must be greater than 0\");\n  if (absolute_tolerance <= 0)\n    invalid_argument(\"integrate_ode_rk45\", \"absolute_tolerance,\",\n                     absolute_tolerance, \"\", \", must be greater than 0\");\n  if (max_num_steps <= 0)\n    invalid_argument(\"integrate_ode_rk45\", \"max_num_steps,\", max_num_steps, \"\",\n                     \", must be greater than 0\");\n\n  // creates basic or coupled system by template specializations\n  coupled_ode_system<F, T1, T2> coupled_system(f, y0, theta, x, x_int, msgs);\n\n  // first time in the vector must be time of initial state\n  std::vector<double> ts_vec(ts.size() + 1);\n  ts_vec[0] = t0;\n  for (size_t n = 0; n < ts.size(); n++)\n    ts_vec[n + 1] = ts[n];\n\n  std::vector<std::vector<double> > y_coupled(ts_vec.size());\n  coupled_ode_observer observer(y_coupled);\n\n  // the coupled system creates the coupled initial state\n  std::vector<double> initial_coupled_state = coupled_system.initial_state();\n\n  const double step_size = 0.1;\n  integrate_times(\n      make_dense_output(absolute_tolerance, relative_tolerance,\n                        runge_kutta_dopri5<std::vector<double>, double,\n                                           std::vector<double>, double>()),\n      boost::ref(coupled_system), initial_coupled_state, boost::begin(ts_vec),\n      boost::end(ts_vec), step_size, observer, max_step_checker(max_num_steps));\n\n  // remove the first state corresponding to the initial value\n  y_coupled.erase(y_coupled.begin());\n\n  // the coupled system also encapsulates the decoupling operation\n  return coupled_system.decouple_states(y_coupled);\n}\n\n}  // namespace math\n\n}  // namespace stan\n\n#endif\n", "meta": {"hexsha": "dc03886e257397c4c0df86c23c028002ed7c25d7", "size": 5918, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "stan/math/prim/arr/functor/integrate_ode_rk45.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/arr/functor/integrate_ode_rk45.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/arr/functor/integrate_ode_rk45.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": 43.197080292, "max_line_length": 80, "alphanum_fraction": 0.718992903, "num_tokens": 1526, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6261241772283034, "lm_q2_score": 0.5467381519846138, "lm_q1q2_score": 0.34232597557068944}}
{"text": "#include \"parser.h\"\n\n#include <boost/spirit/home/x3.hpp>\n\nnamespace x3 = boost::spirit::x3;\n\nnamespace new_math {\n\nx3::rule<class expression, uint64_t> const expression = \"expression\";\nx3::rule<class term, uint64_t> const term = \"term\";\n\nauto const set = [](auto &context) { x3::_val(context) = x3::_attr(context); };\nauto const add = [](auto &context) { x3::_val(context) += x3::_attr(context); };\nauto const mul = [](auto &context) { x3::_val(context) *= x3::_attr(context); };\n\nauto const expression_def = term[set] >>\n                            *(('+' >> term[add]) | ('*' >> term[mul]));\nauto const term_def = x3::uint_ | ('(' >> expression >> ')');\n\nBOOST_SPIRIT_DEFINE(expression, term);\n\n} // namespace new_math\n\nnamespace advanced_math {\n\nauto const set = [](auto &context) { x3::_val(context) = x3::_attr(context); };\nauto const add = [](auto &context) { x3::_val(context) += x3::_attr(context); };\nauto const mul = [](auto &context) { x3::_val(context) *= x3::_attr(context); };\n\nx3::rule<class expression, uint64_t> const expression = \"expression\";\nx3::rule<class term, uint64_t> const term = \"term\";\nx3::rule<class factor, uint64_t> const factor = \"factor\";\n\nauto const expression_def = factor[set] >> *('*' >> factor[mul]);\nauto const factor_def = term[set] >> *('+' >> term[add]);\nauto const term_def = x3::uint_ | ('(' >> expression >> ')');\n\nBOOST_SPIRIT_DEFINE(expression, term, factor);\n\n} // namespace advanced_math\n\nuint64_t parse_expression(std::string input, Math math) {\n  uint64_t result = 0;\n\n  auto first = input.begin();\n  auto last = input.end();\n\n  auto passed = math == Math::New\n                    ? x3::phrase_parse(first, last, new_math::expression,\n                                       x3::space, result)\n                    : x3::phrase_parse(first, last, advanced_math::expression,\n                                       x3::space, result);\n\n  if (not passed || first != last) {\n    throw std::invalid_argument{\"parse error\"};\n  }\n\n  return result;\n}\n", "meta": {"hexsha": "8b833f81403bec7e17fad86a6147dcfff882a2d5", "size": 1992, "ext": "cc", "lang": "C++", "max_stars_repo_path": "source/day-18/parser.cc", "max_stars_repo_name": "raphaelmeyer/advent-of-code-2020", "max_stars_repo_head_hexsha": "c9d2eea98667c03a29ec6f0681ac733455df9dbd", "max_stars_repo_licenses": ["MIT"], "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/day-18/parser.cc", "max_issues_repo_name": "raphaelmeyer/advent-of-code-2020", "max_issues_repo_head_hexsha": "c9d2eea98667c03a29ec6f0681ac733455df9dbd", "max_issues_repo_licenses": ["MIT"], "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/day-18/parser.cc", "max_forks_repo_name": "raphaelmeyer/advent-of-code-2020", "max_forks_repo_head_hexsha": "c9d2eea98667c03a29ec6f0681ac733455df9dbd", "max_forks_repo_licenses": ["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.2, "max_line_length": 80, "alphanum_fraction": 0.6119477912, "num_tokens": 518, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6261241632752915, "lm_q2_score": 0.5467381519846138, "lm_q1q2_score": 0.3423259679420455}}
{"text": "#include \"tkdCmdParser.h\"\n\n#include \"vnl/vnl_vector.h\"\n#include \"vnl/vnl_matrix.h\"\n#include \"vnl/vnl_matrix_fixed.h\"\n#include <vnl/algo/vnl_cholesky.h>\n#include <vnl/vnl_transpose.h>\n\n#include <cmath>\n#include <ctime>\n\n#include <list>\n\n#include <itkImage.h>\n#include <itkImageFileReader.h>\n#include <itkImageFileWriter.h>\n#include <itkImageRegionIteratorWithIndex.h>\n#include <itkImageLinearIteratorWithIndex.h>\n#include <itkImageRegionIterator.h>\n#include <itkDiffusionTensor3D.h>\n\n#include <boost/tokenizer.hpp>\n#include <boost/lexical_cast.hpp>\n#include <boost/random/uniform_int.hpp>\n#include <boost/random/uniform_real.hpp>\n#include <boost/random/variate_generator.hpp>\n#include <boost/random.hpp>\n#include <boost/math/distributions/gamma.hpp>\n\n/**\n * dki namespace.\n */\nnamespace dki\n{\n\n\tstruct parameters\n\t{\n\t\tstd::string inputFileName;\n\t\tstd::string maskFileName;\n\t\tstd::string bvecsFileName;\n\t\tstd::string bvalsFileName;\n\t\tstd::string outputFileName;\n\t\tstd::string sep;\n\t\tint iterations;\n\t\tbool regularize;\n\t};\n\n\ttypedef double PixelType;\n\ttypedef unsigned char MaskPixelType;\n\n\ttypedef itk::Image< PixelType, 4 > ImageType;\n\ttypedef itk::Image< MaskPixelType, 3 > MaskImageType;\n\n\ttypedef itk::Image< PixelType, 3 > OutputImageType;\n\n\ttypedef itk::DiffusionTensor3D< PixelType > DTITensorType;\n\ttypedef vnl_vector_fixed< PixelType, 15 > DKITensorType;\n\n\ttypedef itk::ImageFileReader< ImageType > ReaderType;\n\ttypedef itk::ImageFileReader< MaskImageType > MaskReaderType;\n\n\ttypedef vnl_vector< PixelType > VectorType;\n\ttypedef vnl_matrix< PixelType > MatrixType;\n\n\ttypedef itk::ImageLinearConstIteratorWithIndex< ImageType > ConstIterator4DType;\n\ttypedef itk::ImageRegionConstIteratorWithIndex< MaskImageType > ConstIterator3DType;\n\ttypedef itk::ImageRegionIteratorWithIndex< OutputImageType > Iterator3DType;\n\n\ttypedef itk::ImageFileWriter< OutputImageType > WriterType;\n\n\ttypedef boost::tokenizer< boost::char_separator< char > > TokType;\n\ttypedef boost::mt19937 random_number_type;\n\n\n\t/**\n\t * Return 2-rand DTI tensor.\n\t *\n\t * ITK tensor layout =>\n\t * \t\t\t\t\t| 0  1  2  |\n\t *\t\t\t        | X  3  4  |\n\t *       \t\t\t| X  X  5  |\n\t */\n\tstatic DTITensorType GetDTITensor( const VectorType& theta )\n\t{\n\t\tDTITensorType D( 0.0 );\n\n\t\tD( 0, 0 ) = theta( 1 );\n\t\tD( 0, 1 ) = theta( 4 );\n\t\tD( 0, 2 ) = theta( 6 );\n\t\tD( 1, 1 ) = theta( 2 );\n\t\tD( 1, 2 ) = theta( 5 );\n\t\tD( 2, 2 ) = theta( 3 );\n\n\t\treturn D;\n\t}\n\n\t/**\n\t * Return 4-rand DKI tensor (for now a fixed vector with 15 elements).\n\t *\n\t * theta_dki = [W_1111, W_2222, W_3333,\n\t * \t\t\t\tW_1112, W_2223, W_2221,\n\t * \t\t\t\tW_2223, W_3331, W_3332,\n\t * \t\t\t\tW_1122, W_1133, W_2233,\n\t * \t\t\t\tW_1123, W_1223, W_1233]\n\t */\n\tDKITensorType GetDKITensor( const VectorType& theta )\n\t{\n\t\tDKITensorType tensor;\n\t\tfor( unsigned int i = 0; i < 15; i++ )\n\t\t\ttensor( i ) = theta( 7 + i );\n\n\t\treturn tensor;\n\t}\n\n\t/**\n\t * Predicate to remove non positive semi-definite DTI/DKI tensors.\n\t */\n\tclass non_positive_definite\n\t{\n\t\tpublic:\n\n\t\t/**\n\t\t * Check for non positive semi-definite tensor.\n\t\t */\n\t\tbool operator() ( const VectorType& beta, bool dki_tensor = false )\n\t\t{\n\t\t\tDTITensorType DT = GetDTITensor( beta );\n\n\t\t\tDTITensorType::EigenValuesArrayType eigenValues;\n\t\t\tDT.ComputeEigenValues( eigenValues );\n\n\t\t\tbool non_negative = false;\n\n\t\t\tfor( unsigned int i = 0; i < 3; i++ )\n\t\t\t\tif( eigenValues[ i ] < 0 )\n\t\t\t\t\tnon_negative = true;\n\n\t\t\tif( dki_tensor )\n\t\t\t{\n\t\t\t\tDKITensorType DK = GetDKITensor( beta );\n\t\t\t\t// TODO calculate if DK tensor is postive semi-definite ...\n\t\t\t}\n\n\t\t\treturn non_negative;\n\t\t}\n\t};\n\n\n\t/**\n\t * Date, 06-01-2011.\n\t *\n\t * Implement Gibbs sampler for linear DTI fits.\n\t *\n\t * Ref: \"Introduction to Applied Bayesian Statistics and Estimation for Social Scientists, Scott M. Lynch, 2007. Springer\"\n\t */\n\tclass DKIFit\n    {\n        public:\n\n\t\tImageType::Pointer Input;\n\t\tMaskImageType::Pointer Mask;\n\n\t\tMatrixType X_dti; // dti design matrix\n\t\tMatrixType X_dki; // dki design matrix\n\t\tMatrixType Z; // covariance matrix\n\t\tVectorType B; // bvals\n\t\tMatrixType R; // bvecs\n\n\t\tOutputImageType::Pointer S0_dti;\n\t\tOutputImageType::Pointer S0_dki;\n\n\t\tOutputImageType::Pointer FA_dti;\n\t\tOutputImageType::Pointer FA_dki;\n\n\t\tOutputImageType::Pointer Trace_dti;\n\t\tOutputImageType::Pointer Trace_dki;\n\n\t\tOutputImageType::Pointer AKC;\n\t\tOutputImageType::Pointer Kmax;\n\t\tOutputImageType::Pointer Kmin;\n\n\t\t/**\n\t\t * Start DKI fit.\n\t\t */\n\t\tvoid Run( const parameters& args )\n        {\n\t\t\tSetImage( args.inputFileName );\n\t\t\tSetMask( args.maskFileName, Input.GetPointer() );\n\t\t\tSetBVals( args.bvalsFileName, args.sep );\n\t\t\tSetBVecs( args.bvecsFileName, args.sep );\n\t\t\tSetDTIDesignMatrix();\n\t\t\tSetDKIDesignMatrix();\n\t\t\tAllocateOutput( Input.GetPointer() );\n\t\t\tFit( args.iterations, args.regularize );\n\t\t\tWrite( args.outputFileName );\n        }\n\n        protected:\n\n\t\t/**\n\t\t * Return cholesky decomposition for symmetric matrix.\n\t\t *\n\t\t * Sqrt( A ) using cholesky decomposition is twice as fast as svd/qr.\n\t\t *\n\t\t * The cholesky decomposition decomposes symmetric A = LL'\n\t\t * where L is lower triangular.\n\t\t */\n\t\tMatrixType Cholesky( const MatrixType& A )\n\t\t{\n\t\t\t/* Test Cholesky ...\n\t\t\tMatrixType A( 3, 3 );\n\t\t\tA( 0, 0 ) = 2; A( 0, 1 ) = 0; A( 0, 2 ) = 0.1;\n\t\t\tA( 1, 0 ) = 0; A( 1, 1 ) = 2; A( 1, 2 ) = 0;\n\t\t\tA( 2, 0 ) = 0.1; A( 2, 1 ) = 0; A( 2, 2 ) = 4;\n\t\t\tMatrixType L = Cholesky( A );\n\t\t\tstd::cout << \"Cholesky: \" << L * L.transpose() << std::endl;\n\t\t\t*/\n\t\t\tvnl_cholesky::Operation op = vnl_cholesky::quiet;\n\n\t\t\tvnl_cholesky chol( A, op );\n\n\t\t\treturn chol.upper_triangle(); // A = U'U\n\t\t}\n\n\t\t/**\n\t\t * Normal distribution sampler.\n\t\t */\n\t\tVectorType SampleNormal( random_number_type& ran, unsigned int total, double mean, double sigma )\n\t\t{\n\t\t\tusing namespace boost;\n\n\t\t\t// select Gaussian probability distribution\n\t\t\tnormal_distribution< double > norm_dist( mean, sigma );\n\n\t\t\t// bind random number generator to distribution, forming a function\n\t\t\tvariate_generator< random_number_type&, normal_distribution< double > > sampler( ran, norm_dist );\n\n\t\t\tVectorType samples( total );\n\n\t\t\tfor( unsigned int i = 0; i < total; i++ )\n\t\t\t\tsamples( i ) = sampler(); // sample from the distribution\n\n\t\t\treturn samples;\n\t\t}\n\n\t\t/**\n\t\t * Inverse gamma distribution sampler.\n\t\t *\n\t\t * Implemented as 1 / gamma, with boost library 1.45 switch to inverse_gamma_distribution()\n\t\t *\n\t\t * shape =~ alpha\n\t\t * scale =~ beta\n\t\t */\n\t\tVectorType SampleIGamma( random_number_type& ran, unsigned int total, double alpha, double beta )\n\t\t{\n\t\t\tusing namespace boost;\n\n\t\t    gamma_distribution< double > gamma_dist( alpha );\n\n\t\t    variate_generator< random_number_type&, gamma_distribution< double > > sampler( ran, gamma_dist );\n\n\t\t    VectorType samples( total );\n\n\t\t    for( unsigned int i = 0; i < total; i++ )\n\t\t    \tsamples( i ) = 1 / ( beta * sampler() ); // sample gamma distribution with scale = 1, and invert\n\n\t\t    return samples;\n\t\t}\n\n\n\t\t/**\n\t\t * Design matrix with ln(S0) as constant .\n\t\t *\n\t\t * See: \"C.G. Koay et al / Journal of Magnetic Resonance 128 (2006) pag. 116\"\n\t\t *\n\t\t * DTI tensor thus: ln(S0), Dxx, Dyy, Dzz, Dxy, Dyz, Dxz.\n\t\t */\n\t\tvoid SetDTIDesignMatrix()\n\t\t{\n\t\t\tMatrixType A( R.rows(), 7, 0 ); // 5 x 7\n\n\t\t\tfor ( unsigned int i = 0; i < R.rows(); i++ )\n\t\t\t{\n\t\t\t\tdouble b = B( i );\n\t\t\t\tdouble Gx = R( i, 0 );\n\t\t\t\tdouble Gy = R( i, 1 );\n\t\t\t\tdouble Gz = R( i, 2 );\n\n\t\t\t\tA( i, 0 ) = 1; // ln(S0 )\n\n\t\t\t\tA( i, 1 ) = -b * Gx * Gx;\n\n\t\t\t\tA( i, 2 ) = -b * Gy * Gy;\n\n\t\t\t\tA( i, 3 ) = -b * Gz * Gz;\n\n\t\t\t\tA( i, 4 ) = -2 * b * Gx * Gy;\n\n\t\t\t\tA( i, 5 ) = -2 * b * Gy * Gz;\n\n\t\t\t\tA( i, 6 ) = -2 * b * Gx * Gz;\n\t\t\t}\n\n\t\t\tX_dti = A;\n\t\t}\n\n\t\t/**\n\t\t * Bayesian Linear least squares fit.\n         *\n\t\t * // TODO add covariance matrix W => to get linear 'weighted' regression.\n\t\t * beta = (X' * X)^-1 * X' * ln( y )\n\t\t */\n\t\tVectorType FitVoxel( const MatrixType& X, const VectorType& y, unsigned int iterations,\n\t\t\t\tunsigned int k, unsigned int n, bool regularize )\n\t\t{\n\t\t\t// (X' * X)^-1\n\n\t\t\tvnl_svd< PixelType > svd( X.transpose() * X );\n\t\t\tMatrixType XTXI = svd.inverse();\n\n\t\t\t// ln( y )\n\n\t\t\tVectorType Y( y.size() );\n\t\t\tfor( unsigned int i = 0; i < y.size(); i++ )\n\t\t\t\tY( i ) = log( y( i ) );\n\n\t\t\t// (X' * X)^-1 * X' * ln( y )\n\n\t\t\tVectorType beta = XTXI * X.transpose() * Y;\n\n\t\t\t// sample sigma from it's inverse gamma marginal distribution\n\n\t\t\t// Create a Mersenne twister random number generator\n\t\t\trandom_number_type eng( static_cast< unsigned int > ( std::time( 0 ) ) );\n\n\t\t\tPixelType shape = 0.5 * ( n - k );\n\t\t\tPixelType scale = 0.5 * dot_product( ( Y - X * beta ), ( Y - X * beta ) );\n\t\t\tVectorType s2 = SampleIGamma( eng, iterations, shape, scale );\n\n\t\t\t// -----------------------------------\n\t\t\t// sample distribution for beta (MVN):\n\t\t\t// -----------------------------------\n\t\t\t// mean => inv(X'X) * (X'Y)\t\t\t\t[fitted beta]\n\t\t\t// variance => sigma^2 * inv(X'X)\t\t[sqrt using cholesky decomp.]\n\n\t\t\tstd::list< VectorType > bs;\n\t\t\tfor( unsigned int i = 0; i < iterations; i++ )\n\t\t\t\tbs.push_back( beta + SampleNormal( eng, k, 0, 1 ) * Cholesky( s2( i ) * XTXI ) );\n\n\t\t\t// remove non positive semi definite tensors\n\t\t\tif (regularize )\n\t\t\t\tbs.remove_if( non_positive_definite() );\n\n\t\t\t// if nothing left, return zero tensor ...\n\n\t\t\tif( bs.empty() )\n\t\t\t{\n\t\t\t\t//std::cout << \"Voxel found with sampled tensors not positive semi-definite!\" << std::endl;\n\t\t\t\treturn VectorType( beta.size(), 0 ); // return empty tensor\n\t\t\t}\n\n\t\t\t// get mean tensor\n\n\t\t\tVectorType mean_beta( beta.size(), 0 );\n\n\t\t\tfor( std::list< VectorType >::iterator it = bs.begin(); it != bs.end(); ++it )\n\t\t\t\tmean_beta += *it;\n\n\t\t\treturn mean_beta /= bs.size();\n\t\t}\n\n\t\t/**\n\t\t * Read bvals from file.\n\t\t */\n\t\tvoid SetBVals( const std::string& bvalsFileName, const std::string& sep )\n\t\t{\n\t\t\t// init\n\t\t\tVectorType b( GetNumberOfRows( bvalsFileName ), 0 );\n\n\t\t\t// open data ...\n\t\t\tstd::ifstream in( bvalsFileName.c_str() );\n\t\t\tif ( in.fail() )\n\t\t\t{\n\t\t\t\tstd::cerr << \"*** ERROR ***: could not read from: \" << bvalsFileName << std::endl;\n\t\t\t\texit( EXIT_FAILURE );\n\t\t\t}\n\n\t\t\tstd::string line;\n\t\t\tunsigned int rowIndex = 0;\n\n\t\t\twhile ( getline( in, line ) )\n\t\t\t{\n\t\t\t\tTokType tok( line, boost::char_separator< char >( sep.c_str() ) );\n\t\t\t\ttry\n\t\t\t\t{\n\t\t\t\t\tfor ( TokType::iterator id = tok.begin(); id != tok.end(); ++id )\n\t\t\t\t\t{\n\t\t\t\t\t\tb( rowIndex ) = boost::lexical_cast< PixelType >( *id );\n\t\t\t\t\t}\n\t\t\t\t\trowIndex++;\n\t\t\t\t}\n\t\t\t\tcatch ( boost::bad_lexical_cast& e )\n\t\t\t\t{\n\t\t\t\t\tstd::cout << \"*** WARNING ***: could not parse \" << bvalsFileName << std::endl;\n\t\t\t\t\te.what();\n\t\t\t\t\texit( EXIT_FAILURE );\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tin.close();\n\n\t\t\tB = b;\n\t\t}\n\n\t\tvoid SetBVecs( const std::string& bvecsFileName, const std::string& sep )\n\t\t{\n\t\t\t// init\n\t\t\tMatrixType r( GetNumberOfRows( bvecsFileName ), 3, 0 );\n\n\t\t\t// open data ...\n\t\t\tstd::ifstream in( bvecsFileName.c_str() );\n\t\t\tif ( in.fail() )\n\t\t\t{\n\t\t\t\tstd::cerr << \"*** ERROR ***: could not read from: \" << bvecsFileName << std::endl;\n\t\t\t\texit( EXIT_FAILURE );\n\t\t\t}\n\n\t\t\tstd::string line;\n\t\t\tunsigned int rowIndex = 0;\n\n\t\t\twhile ( getline( in, line ) )\n\t\t\t{\n\t\t\t\tTokType tok( line, boost::char_separator< char >( sep.c_str() ) );\n\t\t\t\ttry\n\t\t\t\t{\n\t\t\t\t\tunsigned int colIndex = 0;\n\t\t\t\t\tfor ( TokType::iterator id = tok.begin(); id != tok.end(); ++id )\n\t\t\t\t\t{\n\t\t\t\t\t\tr( rowIndex, colIndex ) = boost::lexical_cast< PixelType >( *id );\n\t\t\t\t\t\tcolIndex++;\n\t\t\t\t\t}\n\t\t\t\t\trowIndex++;\n\t\t\t\t}\n\t\t\t\tcatch ( boost::bad_lexical_cast& e )\n\t\t\t\t{\n\t\t\t\t\tstd::cout << \"*** WARNING ***: could not parse \" << bvecsFileName << std::endl;\n\t\t\t\t\tstd::cout << e.what() << std::endl;\n\t\t\t\t\texit( EXIT_FAILURE );\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tin.close();\n\n\t\t\tR = r;\n\t\t}\n\n\t\t/**\n\t\t * Build X_dki from bvecs and bvals input files.\n\t\t *\n\t\t * DTI tensor elements:\n\t\t * --------------------\n\t\t * [D_11, D_12, D_13, D_22, D_23, D_33]\n\t\t *\n\t\t * DKI tensor elements:\n\t\t * --------------------\n\t\t * [W_1111, W_2222, W_3333,\n\t\t * \tW_1112, W_2223, W_2221, W_2223, W_3331, W_3332,\n\t\t *  W_1122, W_1133, W_2233,\n\t\t * \tW_1123, W_1223, W_1233]\n\t\t */\n\t\tvoid SetDKIDesignMatrix()\n\t\t{\n\t\t\t// check ...\n\t\t\tif( B.size() != R.rows() )\n\t\t\t{\n\t\t\t\tstd::cerr << \"*** ERROR ***: bvals and bvecs size does not match!\" << std::endl;\n\t\t\t\texit( EXIT_FAILURE );\n\t\t\t}\n\n\t\t\t// init ( e.g. [52 x 22] ) ...\n\t\t\tX_dki = MatrixType( R.rows(), 22, 0 );\n\n\t\t\tfor ( unsigned int i = 0; i < R.rows(); i++ )\n\t\t\t{\n\t\t\t\tdouble b = B( i );\n\t\t\t\tdouble Gx = R( i, 0 );\n\t\t\t\tdouble Gy = R( i, 1 );\n\t\t\t\tdouble Gz = R( i, 2 );\n\n\t\t\t\t// ln( S0 )\n\n\t\t\t\tX_dki( i, 0 ) = 1;\n\n\t\t\t\t// DTI tensor\n\n\t\t\t\tX_dki( i, 1 ) = -b * Gx * Gx;\n\t\t\t\tX_dki( i, 2 ) = -b * Gy * Gy;\n\t\t\t\tX_dki( i, 3 ) = -b * Gz * Gz;\n\t\t\t\tX_dki( i, 4 ) = -2 * b * Gx * Gy;\n\t\t\t\tX_dki( i, 5 ) = -2 * b * Gy * Gz;\n\t\t\t\tX_dki( i, 6 ) = -2 * b * Gx * Gz;\n\n\t\t\t\t// DKI tensor\n\n\t\t\t\tPixelType c = ( b * b ) / 6;\n\n\t\t\t\tX_dki( i, 7 ) = c * Gx * Gx * Gx * Gx; // W_1111\n\t\t\t\tX_dki( i, 8 ) = c * Gy * Gy * Gy * Gy; // W_2222\n\t\t\t\tX_dki( i, 9 ) = c * Gz * Gz * Gz * Gz; // W_3333\n\n\t\t\t\tX_dki( i, 10 ) = 4 * c * Gx * Gx * Gx * Gy; // W_1112\n\t\t\t\tX_dki( i, 11 ) = 4 * c * Gx * Gx * Gx * Gy; // W_2223\n\t\t\t\tX_dki( i, 12 ) = 4 * c * Gx * Gy * Gy * Gy; // W_2221\n\t\t\t\tX_dki( i, 13 ) = 4 * c * Gy * Gy * Gy * Gz; // W_2223\n\t\t\t\tX_dki( i, 14 ) = 4 * c * Gx * Gz * Gz * Gz; // W_3331\n\t\t\t\tX_dki( i, 15 ) = 4 * c * Gy * Gz * Gz * Gz; // W_3332\n\n\t\t\t\tX_dki( i, 16 ) = 6 * c * Gx * Gx * Gy * Gy; // W_1122\n\t\t\t\tX_dki( i, 17 ) = 6 * c * Gx * Gx * Gz * Gz; // W_1133\n\t\t\t\tX_dki( i, 18 ) = 6 * c * Gy * Gy * Gz * Gz; // W_2233\n\n\t\t\t\tX_dki( i, 19 ) = 12 * c * Gx * Gx * Gy * Gz; // W_1123\n\t\t\t\tX_dki( i, 20 ) = 12 * c * Gx * Gy * Gy * Gz; // W_1223\n\t\t\t\tX_dki( i, 21 ) = 12 * c * Gx * Gy * Gz * Gz; // W_1233\n\t\t\t}\n\t\t}\n\n\t\t/**\n\t\t * Return S0.\n\t\t */\n\t\tPixelType GetS0( const VectorType& theta )\n\t\t{\n\t\t\treturn std::exp( theta( 0 ) );\n\t\t}\n\n\t\t/**\n\t\t * Return largest AKC value.\n\t\t *\n\t\t * See:\n\t\t * \"Principal invariant and inherent parameters of diffusion kurtosis tensors\"\n\t\t * \"L. Qi et al / J. Math. Anal. Appl. 349 (2009) 165 - 180.\"\n\t\t *\n\t\t * return [mean(k), min(k), max(k)]\n\t\t */\n\t\tVectorType GetKurtosisValues( const PixelType MD, const VectorType& D_app, const DKITensorType& W )\n\t\t{\n\t\t\t// get number of b-zeros ...\n\t\t\tunsigned int b0s = 0;\n\t\t\tfor( unsigned int i = 0; i < B.size(); i++ )\n\t\t\t\tif( B( i ) == 0 )\n\t\t\t\t\tb0s++;\n\n\t\t\tVectorType K( R.rows() - b0s, 0 );\n\n\t\t\tunsigned int dwi_index = 0;\n\n\t\t\tfor ( unsigned int i = 0; i < R.rows(); i++ )\n\t\t\t{\n\t\t\t\tif( B( i ) != 0 ) // only dwi ...\n\t\t\t\t{\n\t\t\t\t\tdouble Gx = R( i, 0 );\n\t\t\t\t\tdouble Gy = R( i, 1 );\n\t\t\t\t\tdouble Gz = R( i, 2 );\n\n\t\t\t\t\tPixelType tmp0 = MD * MD / ( D_app( i ) * D_app( i ) ); // D_app contains b0s ...\n\n\t\t\t\t\tPixelType tmp1 = W( 0 ) * Gx * Gx * Gx * Gx + W( 1 ) * Gy * Gy * Gy * Gy + W( 2 ) * Gz * Gz * Gz * Gz;\n\n\t\t\t\t\tPixelType tmp2 = 4 * ( W( 3 ) * Gx * Gx * Gx * Gy + W( 4 ) * Gx * Gx * Gx * Gy + W( 5 ) * Gx * Gy * Gy * Gy + W( 6 ) * Gy * Gy * Gy * Gz + W( 7 ) * Gx * Gz * Gz * Gz + W( 8 ) * Gy * Gz * Gz * Gz );\n\n\t\t\t\t\tPixelType tmp3 = 6 * ( W( 9 ) * Gx * Gx * Gy * Gy + W( 10 ) * Gx * Gx * Gz * Gz + W( 11 ) * Gy * Gy * Gz * Gz );\n\n\t\t\t\t\tPixelType tmp4 = 12 * ( W( 12 ) * Gx * Gx * Gy * Gz + W( 13 ) * Gx * Gy * Gy * Gz + W( 14 ) * Gx * Gy * Gz * Gz );\n\n\t\t\t\t\tK( dwi_index ) = tmp0 * ( tmp1 + tmp2 + tmp3 + tmp4 );\n\n\t\t\t\t\tdwi_index++;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tVectorType output( 3, 0 ); // average K, min K, max K\n\n\t\t\toutput( 0 ) = K.mean();\n\t\t\toutput( 1 ) = K.min_value();\n\t\t\toutput( 2 ) = K.max_value();\n\n\t\t\treturn output;\n\t\t}\n\n\t\t/**\n\t\t * Return number of training data points.\n\t\t */\n\t\tunsigned int GetNumberOfRows( const std::string& inputFile )\n\t\t{\n\t\t\tstd::ifstream in( inputFile.c_str() );\n\n\t\t\tif ( in.fail() )\n\t\t\t{\n\t\t\t\tstd::cerr << \"*** ERROR ***: could not read from: \" << inputFile << std::endl;\n\t\t\t\texit( EXIT_FAILURE );\n\t\t\t}\n\t\t\tstd::string line;\n\t\t\tunsigned int result = 0;\n\n\t\t\twhile ( getline( in, line ) )\n\t\t\t\tresult++;\n\n\t\t\tin.close();\n\t\t\treturn result;\n\t\t}\n\n\t\t/**\n\t\t * MCMC DTI fitting.\n\t\t */\n\t\tvoid Fit( unsigned int iterations, bool regularize )\n\t\t{\n\t\t\tConstIterator4DType it( Input, Input->GetLargestPossibleRegion() );\n\t\t\tConstIterator3DType mit( Mask, Mask->GetLargestPossibleRegion() );\n\n\t\t\tIterator3DType itS0_dti( S0_dti, S0_dti->GetLargestPossibleRegion() );\n\t\t\tIterator3DType itS0_dki( S0_dki, S0_dki->GetLargestPossibleRegion() );\n\n\t\t\tIterator3DType itFA_dti( FA_dti, FA_dti->GetLargestPossibleRegion() );\n\t\t\tIterator3DType itFA_dki( FA_dki, FA_dki->GetLargestPossibleRegion() );\n\n\t\t\tIterator3DType itTrace_dti( Trace_dti, Trace_dti->GetLargestPossibleRegion() );\n\t\t\tIterator3DType itTrace_dki( Trace_dki, Trace_dki->GetLargestPossibleRegion() );\n\n\t\t\tIterator3DType itAKC( AKC, AKC->GetLargestPossibleRegion() );\n\t\t\tIterator3DType itKmin( Kmin, Kmin->GetLargestPossibleRegion() );\n\t\t\tIterator3DType itKmax( Kmax, Kmax->GetLargestPossibleRegion() );\n\n\t\t\tit.SetDirection( 3 );\n\t\t\tit.GoToBegin();\n\t\t\tmit.GoToBegin();\n\n\t\t\titS0_dti.GoToBegin();\n\t\t\titS0_dki.GoToBegin();\n\n\t\t\titFA_dti.GoToBegin();\n\t\t\titFA_dki.GoToBegin();\n\n\t\t\titTrace_dti.GoToBegin();\n\t\t\titTrace_dki.GoToBegin();\n\n\t\t\titAKC.GoToBegin();\n\t\t\titKmin.GoToBegin();\n\t\t\titKmax.GoToBegin();\n\n\t\t\tunsigned int totalDWI = ( Input->GetLargestPossibleRegion().GetSize() )[3];\n\n\t\t\tunsigned int sliceIndex = 0;\n\n\t\t\t// for each series of DWI ...\n\t\t\twhile ( !it.IsAtEnd(), !mit.IsAtEnd() )\n\t\t\t{\n\t\t\t\tif ( mit.Get() != 0 )\n\t\t\t\t{\n\t\t\t\t\t// slice index\n\t\t\t\t\tif( sliceIndex != mit.GetIndex()[ 2 ] )\n\t\t\t\t\t{\n\t\t\t\t\t\tstd::cout << \"Processing slice: \" << sliceIndex << std::endl;\n\t\t\t\t\t\tsliceIndex = mit.GetIndex()[ 2 ];\n\t\t\t\t\t}\n\n\t\t\t\t\tVectorType y( totalDWI );\n\n\t\t\t\t\twhile ( !it.IsAtEndOfLine() )\n\t\t\t\t\t{\n\t\t\t\t\t\ty( ( it.GetIndex() )[3] ) = it.Get();\n\t\t\t\t\t\t++it;\n\t\t\t\t\t}\n\n\t\t\t\t\t// DTI => 7 elements (ln(S0) = 1, theta_D = 6)\n\t\t\t\t\t// DTI fit only ...\n\n\t\t\t\t\tunsigned int k = 7;\n\t\t\t\t\tunsigned int n = y.size();\n\t\t\t\t\tVectorType theta_dti = FitVoxel( X_dti, y, iterations, k, n, regularize );\n\t\t\t\t\titS0_dti.Set( GetS0( theta_dti ) );\n\t\t\t\t\tDTITensorType tensor_simple = GetDTITensor( theta_dti );\n\t\t\t\t\titFA_dti.Set( tensor_simple.GetFractionalAnisotropy() );\n\t\t\t\t\titTrace_dti.Set( tensor_simple.GetTrace() );\n\n\t\t\t\t\t// DKI => 22 elements (ln(S0) = 1, theta_D = 6, theta_K = 15)\n\t\t\t\t\t// DTI and DKI fit in one...\n\n\t\t\t\t\tk += 15;\n\n\t\t\t\t\tVectorType theta_dki = FitVoxel( X_dki, y, iterations, k, n, regularize );\n\t\t\t\t\titS0_dki.Set( GetS0( theta_dki ) );\n\n\t\t\t\t\tDTITensorType tensor_dti = GetDTITensor( theta_dki ); // DTI tensor from DKI fit ...\n\t\t\t\t\titFA_dki.Set( tensor_dti.GetFractionalAnisotropy() );\n\t\t\t\t\titTrace_dki.Set( tensor_dti.GetTrace() );\n\n\t\t\t\t\tDKITensorType tensor_dki = GetDKITensor( theta_dki );\n\t\t\t\t\tVectorType tmp = GetKurtosisValues( tensor_dti.GetTrace(), FitDapp( y ), tensor_dki );\n\n\t\t\t\t\titAKC.Set( tmp( 0 ) );\n\t\t\t\t\titKmin.Set( tmp( 1 ) );\n\t\t\t\t\titKmax.Set( tmp( 2 ) );\n\t\t\t\t}\n\n\t\t\t\tit.NextLine();\n\t\t\t\t++mit;\n\n\t\t\t\t++itS0_dti;\n\t\t\t\t++itS0_dki;\n\n\t\t\t\t++itFA_dti;\n\t\t\t\t++itFA_dki;\n\n\t\t\t\t++itTrace_dti;\n\t\t\t\t++itTrace_dki;\n\n\t\t\t\t++itAKC;\n\t\t\t\t++itKmin;\n\t\t\t\t++itKmax;\n\t\t\t}\n\t\t}\n\n\t\t/**\n\t\t * Return apparant diffusion per direction.\n\t\t *\n\t\t * ln( Sb / S0 ) / -b = D_app\n\t\t */\n\t\tVectorType FitDapp( const VectorType& y )\n\t\t{\n\t\t\t// average S0 ...\n\n\t\t\tPixelType S0 = 0;\n\t\t\tPixelType totalS0;\n\n\t\t\tfor( unsigned int i = 0; i < B.size(); i++ )\n\t\t\t{\n\t\t\t\tif( B( i ) == 0 )\n\t\t\t\t{\n\t\t\t\t\tS0 += y( i );\n\t\t\t\t\ttotalS0++;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif( totalS0 == 0 )\n\t\t\t{\n\t\t\t\tstd::cerr << \"*** ERROR ***: no b-zeros!\" << std::endl;\n\t\t\t\texit( EXIT_FAILURE );\n\t\t\t}\n\t\t\tS0 /= totalS0;\n\n\t\t\t// D_app ...\n\n\t\t\tVectorType D_app( R.rows(), 0 );\n\n\t\t\tfor( unsigned int i = 0; i < B.size(); i++ )\n\t\t\t{\n\t\t\t\tif( B( i ) != 0 )\n\t\t\t\t\tD_app( i ) = log( y( i )  / S0 ) / - B( i );\n\t\t\t}\n\n\t\t\treturn D_app;\n\t\t}\n\n\t\t/**\n\t\t * Return covariate matrix Z.\n\t\t */\n\t\tMatrixType BuildCovarianceMatrix( const VectorType& y )\n\t\t{\n\t\t\tMatrixType Z( y.size(), y.size(), 0 );\n\n\t\t\t// fill diagonal\n\t\t\tfor( unsigned int i = 0; i < Z.rows(); i++ )\n\t\t\t\tZ( i, i ) = y( i ) * y( i );\n\n\t\t\treturn Z;\n\t\t}\n\n\t\t/**\n\t\t * Allocate all output images to 0.\n\t\t */\n\t\tvoid AllocateOutput( ImageType::ConstPointer input )\n\t\t{\n\t\t\tMaskImageType::Pointer output = MaskImageType::New();\n\n\t\t\tOutputImageType::RegionType region3D;\n\t\t\tOutputImageType::IndexType index3D;\n\t\t\tOutputImageType::SizeType size3D;\n\t\t\tOutputImageType::SpacingType spacing3D;\n\t\t\tOutputImageType::PointType origin3D;\n\n\t\t\tImageType::RegionType region = input->GetLargestPossibleRegion();\n\t\t\tImageType::SizeType size = region.GetSize();\n\t\t\tImageType::IndexType index = region.GetIndex();\n\t\t\tImageType::SpacingType spacing = input->GetSpacing();\n\t\t\tImageType::PointType origin = input->GetOrigin();\n\n\t\t\tsize3D[0] = size[0];\n\t\t\tsize3D[1] = size[1];\n\t\t\tsize3D[2] = size[2];\n\t\t\tindex3D[0] = index[0];\n\t\t\tindex3D[1] = index[1];\n\t\t\tindex3D[2] = index[2];\n\t\t\torigin3D[0] = origin[0];\n\t\t\torigin3D[1] = origin[1];\n\t\t\torigin3D[2] = origin[2];\n\t\t\tspacing3D[0] = spacing[0];\n\t\t\tspacing3D[1] = spacing[1];\n\t\t\tspacing3D[2] = spacing[2];\n\n\t\t\tregion3D.SetSize( size3D );\n\t\t\tregion3D.SetIndex( index3D );\n\n\t\t\t// create\n\t\t\tS0_dti = OutputImageType::New();\n\t\t\tS0_dki = OutputImageType::New();\n\n\t\t\tFA_dti = OutputImageType::New();\n\t\t\tFA_dki = OutputImageType::New();\n\n\t\t\tTrace_dti = OutputImageType::New();\n\t\t\tTrace_dki = OutputImageType::New();\n\n\t\t\tAKC = OutputImageType::New();\n\t\t\tKmax = OutputImageType::New();\n\t\t\tKmin = OutputImageType::New();\n\n\t\t\t// set\n\t\t\tS0_dti->SetRegions( region3D );\n\t\t\tS0_dti->SetSpacing( spacing3D );\n\t\t\tS0_dti->SetOrigin( origin3D );\n\t\t\tS0_dti->Allocate();\n\t\t\tS0_dti->FillBuffer( 0 );\n\n\t\t\tS0_dki->SetRegions( region3D );\n\t\t\tS0_dki->SetSpacing( spacing3D );\n\t\t\tS0_dki->SetOrigin( origin3D );\n\t\t\tS0_dki->Allocate();\n\t\t\tS0_dki->FillBuffer( 0 );\n\n\t\t\tFA_dti->SetRegions( region3D );\n\t\t\tFA_dti->SetSpacing( spacing3D );\n\t\t\tFA_dti->SetOrigin( origin3D );\n\t\t\tFA_dti->Allocate();\n\t\t\tFA_dti->FillBuffer( 0 );\n\n\t\t\tFA_dki->SetRegions( region3D );\n\t\t\tFA_dki->SetSpacing( spacing3D );\n\t\t\tFA_dki->SetOrigin( origin3D );\n\t\t\tFA_dki->Allocate();\n\t\t\tFA_dki->FillBuffer( 0 );\n\n\t\t\tTrace_dti->SetRegions( region3D );\n\t\t\tTrace_dti->SetSpacing( spacing3D );\n\t\t\tTrace_dti->SetOrigin( origin3D );\n\t\t\tTrace_dti->Allocate();\n\t\t\tTrace_dti->FillBuffer( 0 );\n\n\t\t\tTrace_dki->SetRegions( region3D );\n\t\t\tTrace_dki->SetSpacing( spacing3D );\n\t\t\tTrace_dki->SetOrigin( origin3D );\n\t\t\tTrace_dki->Allocate();\n\t\t\tTrace_dki->FillBuffer( 0 );\n\n\t\t\tAKC->SetRegions( region3D );\n\t\t\tAKC->SetSpacing( spacing3D );\n\t\t\tAKC->SetOrigin( origin3D );\n\t\t\tAKC->Allocate();\n\t\t\tAKC->FillBuffer( 0 );\n\n\t\t\tKmax->SetRegions( region3D );\n\t\t\tKmax->SetSpacing( spacing3D );\n\t\t\tKmax->SetOrigin( origin3D );\n\t\t\tKmax->Allocate();\n\t\t\tKmax->FillBuffer( 0 );\n\n\t\t\tKmin->SetRegions( region3D );\n\t\t\tKmin->SetSpacing( spacing3D );\n\t\t\tKmin->SetOrigin( origin3D );\n\t\t\tKmin->Allocate();\n\t\t\tKmin->FillBuffer( 0 );\n\t\t}\n\n\t\t/**\n\t\t * Set input image.\n\t\t */\n\t\tvoid SetImage( const std::string& inputFileName )\n\t\t{\n\t\t\tif ( !inputFileName.empty() )\n\t\t\t{\n\t\t\t\tReaderType::Pointer reader = ReaderType::New();\n\t\t\t\treader->SetFileName( inputFileName );\n\t\t\t\treader->Update();\n\t\t\t\tInput = reader->GetOutput();\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tstd::cerr << \"Could not read input!\" << std::endl;\n\t\t\t\texit( EXIT_FAILURE );\n\t\t\t}\n\t\t}\n\n\t\t/**\n\t\t * Return mask if file given, else create empty mask from input file.\n\t\t */\n\t\tvoid SetMask( const std::string& maskFileName, ImageType::ConstPointer input )\n\t\t{\n\t\t\tif ( !maskFileName.empty() )\n\t\t\t{\n\t\t\t\tMaskReaderType::Pointer reader = MaskReaderType::New();\n\t\t\t\treader->SetFileName( maskFileName );\n\t\t\t\treader->Update();\n\t\t\t\tMask = reader->GetOutput();\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tMaskImageType::Pointer output = MaskImageType::New();\n\t\t\t\tMaskImageType::RegionType region3D;\n\t\t\t\tMaskImageType::IndexType index3D;\n\t\t\t\tMaskImageType::SizeType size3D;\n\t\t\t\tMaskImageType::SpacingType spacing3D;\n\t\t\t\tMaskImageType::PointType origin3D;\n\n\t\t\t\tImageType::RegionType region = input->GetLargestPossibleRegion();\n\t\t\t\tImageType::SizeType size = region.GetSize();\n\t\t\t\tImageType::IndexType index = region.GetIndex();\n\t\t\t\tImageType::SpacingType spacing = input->GetSpacing();\n\t\t\t\tImageType::PointType origin = input->GetOrigin();\n\n\t\t\t\tsize3D[0] = size[0];\n\t\t\t\tsize3D[1] = size[1];\n\t\t\t\tsize3D[2] = size[2];\n\t\t\t\tindex3D[0] = index[0];\n\t\t\t\tindex3D[1] = index[1];\n\t\t\t\tindex3D[2] = index[2];\n\t\t\t\torigin3D[0] = origin[0];\n\t\t\t\torigin3D[1] = origin[1];\n\t\t\t\torigin3D[2] = origin[2];\n\t\t\t\tspacing3D[0] = spacing[0];\n\t\t\t\tspacing3D[1] = spacing[1];\n\t\t\t\tspacing3D[2] = spacing[2];\n\n\t\t\t\tregion3D.SetSize( size3D );\n\t\t\t\tregion3D.SetIndex( index3D );\n\n\t\t\t\t// set\n\t\t\t\toutput->SetRegions( region3D );\n\t\t\t\toutput->SetSpacing( spacing3D );\n\t\t\t\toutput->SetOrigin( origin3D );\n\t\t\t\toutput->Allocate();\n\t\t\t\toutput->FillBuffer( 1 );\n\n\t\t\t\tMask = output;\n\t\t\t}\n\t\t}\n\n\t\t/**\n\t\t * Write output images.\n\t\t */\n\t\tvoid Write( const std::string& outputFileName )\n\t\t{\n\t\t\t// Writer\n\t\t\tWriterType::Pointer writer = WriterType::New();\n\n\t\t\t// S0\n\t\t\twriter->SetFileName( ( outputFileName + std::string( \"_S0_dti.nii.gz\" ) ).c_str() );\n\t\t\twriter->SetInput( S0_dti );\n\t\t\twriter->Update();\n\n\t\t\twriter->SetFileName( ( outputFileName + std::string( \"_S0_dki.nii.gz\" ) ).c_str() );\n\t\t\twriter->SetInput( S0_dki );\n\t\t\twriter->Update();\n\n\t\t\t// FA\n\t\t\twriter->SetFileName( ( outputFileName + std::string( \"_FA_dti.nii.gz\" ) ).c_str() );\n\t\t\twriter->SetInput( FA_dti );\n\t\t\twriter->Update();\n\n\t\t\twriter->SetFileName( ( outputFileName + std::string( \"_FA_dki.nii.gz\" ) ).c_str() );\n\t\t\twriter->SetInput( FA_dki );\n\t\t\twriter->Update();\n\n\t\t\t// Trace\n\t\t\twriter->SetFileName( ( outputFileName + std::string( \"_Trace_dti.nii.gz\" ) ).c_str() );\n\t\t\twriter->SetInput( Trace_dti );\n\t\t\twriter->Update();\n\n\t\t\twriter->SetFileName( ( outputFileName + std::string( \"_Trace_dki.nii.gz\" ) ).c_str() );\n\t\t\twriter->SetInput( Trace_dki );\n\t\t\twriter->Update();\n\n\t\t\t// AKC\n\t\t\twriter->SetFileName( ( outputFileName + std::string( \"_AKC.nii.gz\" ) ).c_str() );\n\t\t\twriter->SetInput( AKC );\n\t\t\twriter->Update();\n\n\t\t\t// Kmin\n\t\t\twriter->SetFileName( ( outputFileName + std::string( \"_Kmin.nii.gz\" ) ).c_str() );\n\t\t\twriter->SetInput( Kmin );\n\t\t\twriter->Update();\n\n\t\t\t// Kmax\n\t\t\twriter->SetFileName( ( outputFileName + std::string( \"_Kmax.nii.gz\" ) ).c_str() );\n\t\t\twriter->SetInput( Kmax );\n\t\t\twriter->Update();\n\t\t}\n\n    }; // end class DKIFit\n\n} // end namespace dki\n\n\n/**\n * DKI fitting routine.\n */\nint main( int argc, char ** argv )\n{\n    tkd::CmdParser p( argv[0], \"Fit voxel-wise DTI using Gibbs sampling and postitive semi-definite tensor regularization.\" );\n\n    dki::parameters args;\n    args.sep = \" \";\n    args.iterations = 1000;\n    args.regularize = false;\n\n    p.AddArgument( args.inputFileName, \"input\" )\n        ->AddAlias( \"i\" )\n        ->SetDescription( \"Input 4D image\" )\n        ->SetRequired( true );\n\n    p.AddArgument( args.bvecsFileName, \"bvecs\" )\n        ->AddAlias( \"r\" )\n        ->SetDescription( \"Diffusion gradient vectors (FSL format)\" )\n        ->SetRequired( true );\n\n    p.AddArgument( args.bvalsFileName, \"bvals\" )\n        ->AddAlias( \"b\" )\n        ->SetDescription( \"Diffusion b-value vector (FSL format)\" )\n        ->SetRequired( true );\n\n    p.AddArgument( args.outputFileName, \"output\" )\n        ->AddAlias( \"o\" )\n        ->SetDescription( \"Output filename base\" )\n        ->SetRequired( true );\n\n    p.AddArgument( args.maskFileName, \"mask\" )\n        ->AddAlias( \"m\" )\n        ->SetDescription( \"Mask 3D image\" );\n\n    p.AddArgument( args.sep, \"separation\" )\n        ->AddAlias( \"s\" )\n        ->SetDescription( \"Separation string in bvecs file (default: ' ')\" );\n\n    p.AddArgument( args.iterations, \"iterations\" )\n        ->AddAlias( \"it\" )\n        ->SetDescription( \"Number of MCMC sampling iterations per voxel (default: 1000)\" );\n\n    p.AddArgument( args.regularize, \"regularize\" )\n        ->AddAlias( \"reg\" )\n        ->SetDescription( \"Regularize posteriors by removal of non postivive semi-definite tensors (default: false)\" );\n\n    if ( !p.Parse( argc, argv ) )\n    {\n        p.PrintUsage( std::cout );\n        return EXIT_FAILURE;\n    }\n\n    dki::DKIFit fit;\n    fit.Run( args );\n\n    return EXIT_SUCCESS;\n}\n\n\n\n\n\n", "meta": {"hexsha": "ffcf7edb4e5fe669c71f45c8c5734a4c87761233", "size": 27756, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/bayesian_dti/bayesianDTI.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/bayesian_dti/bayesianDTI.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/bayesian_dti/bayesianDTI.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": 25.8195348837, "max_line_length": 202, "alphanum_fraction": 0.59367344, "num_tokens": 9286, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6688802735722128, "lm_q2_score": 0.5117166047041654, "lm_q1q2_score": 0.342277142545966}}
{"text": "#pragma once\n#ifndef OPENGM_MINSTCUTBOOST_HXX\n#define OPENGM_MINSTCUTBOOST_HXX\n\n#ifndef BOOST_DISABLE_ASSERTS\n#define BOOST_DISABLE_ASSERTS\n#define USED_BOOST_DISABLE_ASSERTS\n#endif  \n\n#include <queue>\n#include <cassert>\n\n#include <boost/graph/graph_traits.hpp>\n#include <boost/graph/one_bit_color_map.hpp>\n#include <boost/property_map/property_map.hpp>\n#include <boost/typeof/typeof.hpp>\n\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/edmonds_karp_max_flow.hpp>\n#include <boost/graph/push_relabel_max_flow.hpp>\n#include <boost/graph/boykov_kolmogorov_max_flow.hpp>\n\nnamespace opengm {\n\n   enum BoostMaxFlowAlgorithm {\n      PUSH_RELABEL, EDMONDS_KARP, KOLMOGOROV\n   };\n\n   /// \\brief Boost solvers for the min st-cut framework GraphCut\n   template<class NType, class VType, BoostMaxFlowAlgorithm mfalg>\n   class MinSTCutBoost {\n   public:\n      // Type-Definitions\n      typedef NType node_type;\n      typedef VType ValueType;\n      typedef boost::vecS OutEdgeList;\n      typedef boost::vecS VertexList;\n      typedef boost::adjacency_list_traits<OutEdgeList, VertexList, boost::directedS> graph_traits;\n      typedef graph_traits::edge_descriptor edge_descriptor;\n      typedef graph_traits::vertex_descriptor vertex_descriptor;\n\n      /// \\cond HIDDEN_SYMBOLS\n      struct Edge {\n         Edge() : capacity(ValueType()), residual(ValueType()), reverse(edge_descriptor()) \n            {}\n         ValueType capacity;\n         ValueType residual;\n         edge_descriptor reverse;\n      };\n      /// \\endcond\n\n      typedef boost::adjacency_list<OutEdgeList, VertexList, boost::directedS, size_t, Edge> graph_type;\n      typedef typename boost::graph_traits<graph_type>::edge_iterator edge_iterator;\n      typedef typename boost::graph_traits<graph_type>::out_edge_iterator out_edge_iterator;\n\n      // Methods\n      MinSTCutBoost();\n      MinSTCutBoost(size_t numberOfNodes, size_t numberOfEdges);\n      void addEdge(node_type, node_type, ValueType);\n      void calculateCut(std::vector<bool>&);\n\n   private:\n      // Members\n      graph_type graph_;\n      size_t numberOfNodes_;\n      size_t numberOfEdges_;\n      static const NType S = 0;\n      static const NType T = 1;\n   };\n\n   //*********************\n   //** Implementation  **\n   //*********************\n\n   template<class NType, class VType, BoostMaxFlowAlgorithm mfalg>\n   MinSTCutBoost<NType, VType, mfalg>::MinSTCutBoost() {\n      numberOfNodes_ = 2;\n      numberOfEdges_ = 0;\n   }\n\n   template<class NType, class VType, BoostMaxFlowAlgorithm mfalg>\n   MinSTCutBoost<NType, VType, mfalg>::MinSTCutBoost(size_t numberOfNodes, size_t numberOfEdges) {\n      numberOfNodes_ = numberOfNodes;\n      numberOfEdges_ = numberOfEdges;\n      graph_ = graph_type(numberOfNodes_);\n      //std::cout << \"#nodes : \" << numberOfNodes_ << std::endl;\n   }\n\n   template<class NType, class VType, BoostMaxFlowAlgorithm mfalg>\n   void MinSTCutBoost<NType, VType, mfalg>::addEdge(node_type n1, node_type n2, ValueType cost) {\n      assert(n1 < numberOfNodes_);\n      assert(n2 < numberOfNodes_);\n      assert(cost >= 0);\n      std::pair<edge_descriptor, bool> e = add_edge(n1, n2, graph_);\n      std::pair<edge_descriptor, bool> er = add_edge(n2, n1, graph_);\n      graph_[e.first].capacity += cost;\n      graph_[e.first].reverse = er.first;\n      graph_[er.first].reverse = e.first;\n      //std::cout << n1 << \"->\" << n2 << \" : \" << cost << std::endl;\n   }\n\n   template<class NType, class VType, BoostMaxFlowAlgorithm mfalg>\n   void MinSTCutBoost<NType, VType, mfalg>::calculateCut(std::vector<bool>& segmentation) {\n      if (mfalg == KOLMOGOROV) {//Kolmogorov\n         std::vector<boost::default_color_type> color(num_vertices(graph_));\n         std::vector<edge_descriptor> pred(num_vertices(graph_));\n         std::vector<vertex_descriptor> dist(num_vertices(graph_));\n         boykov_kolmogorov_max_flow(graph_,\n            get(&Edge::capacity, graph_),\n            get(&Edge::residual, graph_),\n            get(&Edge::reverse, graph_),\n            &pred[0],\n            &color[0],\n            &dist[0],\n            get(boost::vertex_index, graph_),\n            S, T\n            );\n         // find (s,t)-cut set\n         segmentation.resize(num_vertices(graph_));\n         for (size_t j = 2; j < num_vertices(graph_); ++j) {\n            if (color[j] == boost::black_color || color[j] == boost::gray_color) {\n               segmentation[j] = false;\n            } else if (color[j] == boost::white_color) {\n               segmentation[j] = true;\n            }\n         }\n      } \n      else if (mfalg == PUSH_RELABEL) {// PushRelable\n\n         push_relabel_max_flow(graph_, S, T,\n            get(&Edge::capacity, graph_),\n            get(&Edge::residual, graph_),\n            get(&Edge::reverse, graph_),\n            get(boost::vertex_index_t(), graph_)\n            );\n         // find (s,t)-cut set \n         segmentation.resize(num_vertices(graph_), true);\n         segmentation[S] = false; // source\n         segmentation[T] = false; // sink\n         typedef typename boost::property_map<graph_type, boost::vertex_index_t>::type VertexIndexMap;\n         VertexIndexMap vertexIndexMap = get(boost::vertex_index, graph_);\n         std::queue<vertex_descriptor> q;\n         q.push(*(vertices(graph_).first)); // source\n         while (!q.empty()) {\n            out_edge_iterator current, end;\n            boost::tie(current, end) = out_edges(q.front(), graph_);\n            q.pop();\n            while (current != end) {\n               if (graph_[*current].residual > 0) {\n                  vertex_descriptor v = target(*current, graph_);\n                  if (vertexIndexMap[v] > 1 && segmentation[vertexIndexMap[v]] == true) {\n                     segmentation[vertexIndexMap[v]] = false;\n                     q.push(v);\n                  }\n               }\n               ++current;\n            }\n         }\n      } \n      else if (mfalg == EDMONDS_KARP) {//EdmondsKarp\n         std::vector<boost::default_color_type> color(num_vertices(graph_));\n         std::vector<edge_descriptor> pred(num_vertices(graph_));\n         edmonds_karp_max_flow(graph_, S, T,\n            get(&Edge::capacity, graph_),\n            get(&Edge::residual, graph_),\n            get(&Edge::reverse, graph_),\n            &color[0], &pred[0]\n            );\n         // find (s,t)-cut set\n         segmentation.resize(num_vertices(graph_));\n         for (size_t j = 2; j < num_vertices(graph_); ++j) {\n            if (color[j] == boost::black_color) {\n               segmentation[j] = false;\n            } else if (color[j] == boost::white_color) {\n               segmentation[j] = true;\n            } else {\n               throw std::runtime_error(\"At least one vertex is labeled neither black nor white.\");\n            }\n         }\n      } \n      else {//UNKNOWN MaxFlowalgorithm\n         throw std::runtime_error(\"Unknown MaxFlow-algorithm in MinSTCutBoost.hxx\");\n      }\n      return;\n   }\n\n} // namespace opengm\n\n#ifdef USED_BOOST_DISABLE_ASSERTS\n#undef BOOST_DISABLE_ASSERTS\n#undef USED_BOOST_DISABLE_ASSERTS\n#endif \n\n\n#endif // #ifndef OPENGM_MINSTCUTBOOST_HXX\n", "meta": {"hexsha": "0a479beb69d08a6f35b37555da9cda384f56901c", "size": 7106, "ext": "hxx", "lang": "C++", "max_stars_repo_path": "include/opengm/inference/auxiliary/minstcutboost.hxx", "max_stars_repo_name": "ilastik/opengm", "max_stars_repo_head_hexsha": "3ae6d003c3c360d56e66be4e70872d7f54c26753", "max_stars_repo_licenses": ["MIT"], "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/inference/auxiliary/minstcutboost.hxx", "max_issues_repo_name": "ilastik/opengm", "max_issues_repo_head_hexsha": "3ae6d003c3c360d56e66be4e70872d7f54c26753", "max_issues_repo_licenses": ["MIT"], "max_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/inference/auxiliary/minstcutboost.hxx", "max_forks_repo_name": "ilastik/opengm", "max_forks_repo_head_hexsha": "3ae6d003c3c360d56e66be4e70872d7f54c26753", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-10-05T16:36:22.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-05T16:36:22.000Z", "avg_line_length": 36.2551020408, "max_line_length": 104, "alphanum_fraction": 0.6168027019, "num_tokens": 1710, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6688802735722128, "lm_q2_score": 0.5117166047041652, "lm_q1q2_score": 0.3422771425459659}}
{"text": "/* ----------------------------------------------------------------------- *//**\n *\n * @file multilogistic.cpp\n *\n * @brief Multinomial Logistic-Regression functions\n *\n * We implement the iteratively-reweighted-least-squares method.\n *\n *//* ----------------------------------------------------------------------- */\n\n#include <dbconnector/dbconnector.hpp>\n\n#include <modules/shared/HandleTraits.hpp>\n#include <modules/prob/boost.hpp>\n#include <boost/math/distributions.hpp>\n#include <modules/prob/student.hpp>\n#include \"multilogistic.hpp\"\n\n#include <vector>\n#include <fstream>\n\nnamespace madlib {\n\n// Use Eigen\nusing namespace dbal::eigen_integration;\n\nnamespace modules {\n\n// Import names from other MADlib modules\nusing dbal::NoSolutionFoundException;\n\nnamespace regress {\n\n/**\n * @brief Logistic function\n */\ninline double sigma(double x) {\n    return 1. / (1. + std::exp(-x));\n}\n\n\n/**\n * @brief Inter- and intra-iteration state for iteratively-reweighted-least-\n *        squares method for logistic regression\n *\n * TransitionState encapsualtes the transition state during the\n * logistic-regression aggregate function. To the database, the state is\n * exposed as a single DOUBLE PRECISION array, to the C++ code it is a proper\n * object containing scalars, a vector, and a matrix.\n *\n * Note: We assume that the DOUBLE PRECISION array is initialized by the\n * database with length at least 4, and all elemenets are 0.\n */\ntemplate <class Handle>\nclass MLogRegrIRLSTransitionState {\n\n    // By §14.5.3/9: \"Friend declarations shall not declare partial\n    // specializations.\" We do access protected members in operator+=().\n    template <class OtherHandle>\n    friend class MLogRegrIRLSTransitionState;\n\npublic:\n\n\n    MLogRegrIRLSTransitionState(const AnyType &inArray)\n        : mStorage(inArray.getAs<Handle>()) {\n        rebind(static_cast<uint16_t>(mStorage[0]),static_cast<uint16_t>(mStorage[1]));\n    }\n\n    /**\n     * @brief Convert to backend representation\n     *\n     * We define this function so that we can use State in the\n     * argument list and as a return type.\n     */\n    inline operator AnyType() const {\n        return mStorage;\n    }\n\n    /**\n     * @brief Initialize the iteratively-reweighted-least-squares state.\n     *\n     * This function is only called for the first iteration, for the first row.\n     */\n    inline void initialize(\n        const Allocator &inAllocator,\n        uint16_t inWidthOfX,\n        uint16_t inNumCategories, uint16_t inRefCategory) {\n\n        size_t state_size = arraySize(inWidthOfX, inNumCategories);\n        // GPDB limits the single array size to be 1GB, which means that the size\n        // of a double array cannot be large than 134217727 because\n        // (134217727 * 8) / (1024 * 1024) = 1023. And solve\n        // state_size = x^2 + 2^x + 6 <= 134217727 will give x <= 11584.\n        if(state_size > 134217727)\n            throw std::domain_error(\n                \"The product of number of independent variables and number of \"\n                 \"categories cannot be larger than 11584.\");\n\n        mStorage = inAllocator.allocateArray<double, dbal::AggregateContext,\n            dbal::DoZero, dbal::ThrowBadAlloc>(state_size);\n        rebind(inWidthOfX, inNumCategories);\n        widthOfX = inWidthOfX;\n        numCategories = inNumCategories;\n        ref_category = inRefCategory;\n    }\n\n    /**\n     * @brief We need to support assigning the previous state\n     */\n    template <class OtherHandle> MLogRegrIRLSTransitionState &operator=(\n        const MLogRegrIRLSTransitionState<OtherHandle> &inOtherState) {\n\n        for (size_t i = 0; i < mStorage.size(); i++)\n            mStorage[i] = inOtherState.mStorage[i];\n        return *this;\n    }\n\n    /**\n     * @brief Merge with another State object by copying the intra-iteration\n     *     fields\n     */\n    template <class OtherHandle> MLogRegrIRLSTransitionState &operator+=(\n        const MLogRegrIRLSTransitionState<OtherHandle> &inOtherState) {\n        if (mStorage.size() != inOtherState.mStorage.size() ||\n            widthOfX != inOtherState.widthOfX)\n            throw std::logic_error(\"Internal error: Incompatible transition \"\n                \"states\");\n\n        numRows += inOtherState.numRows;\n        gradient += inOtherState.gradient;\n        X_transp_AX += inOtherState.X_transp_AX;\n        logLikelihood += inOtherState.logLikelihood;\n        return *this;\n    }\n\n    /**\n     * @brief Reset the inter-iteration fields.\n     */\n    inline void reset() {\n        numRows = 0;\n        gradient.fill(0);\n        X_transp_AX.fill(0);\n        logLikelihood = 0;\n    }\n\nprivate:\n    static inline uint32_t arraySize(const uint16_t inWidthOfX,\n        const uint16_t inNumCategories) {\n        return 6 + inWidthOfX * inWidthOfX * inNumCategories * inNumCategories\n                                 + 2 * inWidthOfX * inNumCategories;\n    }\n\n    void rebind(uint16_t inWidthOfX = 0, uint16_t inNumCategories = 0) {\n        widthOfX.rebind(&mStorage[0]);\n        numCategories.rebind(&mStorage[1]);\n        conditionNo.rebind(&mStorage[2]);\n\n        coef.rebind(&mStorage[3], inWidthOfX*inNumCategories);\n\n        numRows.rebind(&mStorage[3 + inWidthOfX*inNumCategories]);\n\n        gradient.rebind(&mStorage[4 + inWidthOfX*inNumCategories],inWidthOfX*inNumCategories);\n        X_transp_AX.rebind(&mStorage[4 + 2 * inWidthOfX*inNumCategories],\n            inNumCategories*inWidthOfX, inWidthOfX*inNumCategories);\n        logLikelihood.rebind(&mStorage[4 +\n             inNumCategories*inNumCategories*inWidthOfX*inWidthOfX\n             + 2 * inWidthOfX*inNumCategories]);\n        ref_category.rebind(&mStorage[5 +\n             inNumCategories*inNumCategories*inWidthOfX*inWidthOfX\n             + 2 * inWidthOfX*inNumCategories]);\n    }\n\n    Handle mStorage;\n\npublic:\n    typename HandleTraits<Handle>::ReferenceToUInt16 widthOfX;\n    typename HandleTraits<Handle>::ReferenceToUInt16 numCategories;\n    typename HandleTraits<Handle>::ReferenceToDouble conditionNo;\n\n    typename HandleTraits<Handle>::ColumnVectorTransparentHandleMap coef;\n    typename HandleTraits<Handle>::ReferenceToUInt64 numRows;\n    typename HandleTraits<Handle>::ColumnVectorTransparentHandleMap gradient;\n    typename HandleTraits<Handle>::MatrixTransparentHandleMap X_transp_AX;\n    typename HandleTraits<Handle>::ReferenceToDouble logLikelihood;\n    typename HandleTraits<Handle>::ReferenceToUInt16 ref_category;\n};\n\n\n/**\n * @brief Inter- and intra-iteration state for robust variance calculations\n *\n * TransitionState encapsualtes the transition state during the\n * logistic-regression robust variance calculation. To the database, the state is\n * exposed as a single DOUBLE PRECISION array, to the C++ code it is a proper\n * object containing scalars, a vector, and a matrix.\n *\n * Note: We assume that the DOUBLE PRECISION array is initialized by the\n * database with length at least 4, and all elemenets are 0.\n */\ntemplate <class Handle>\nclass MLogRegrRobustTransitionState {\n\n    // By §14.5.3/9: \"Friend declarations shall not declare partial\n    // specializations.\" We do access protected members in operator+=().\n    template <class OtherHandle>\n    friend class MLogRegrRobustTransitionState;\n\npublic:\n    MLogRegrRobustTransitionState(const AnyType &inArray)\n        : mStorage(inArray.getAs<Handle>()) {\n        rebind(static_cast<uint16_t>(mStorage[0]),static_cast<uint16_t>(mStorage[1]));\n    }\n\n    /**\n     * @brief Convert to backend representation\n     *\n     * We define this function so that we can use State in the\n     * argument list and as a return type.\n     */\n    inline operator AnyType() const {\n        return mStorage;\n    }\n\n    /**\n     * @brief Initialize the iteratively-reweighted-least-squares state.\n     *\n     * This function is only called for the first iteration, for the first row.\n     */\n    inline void initialize(const Allocator &inAllocator,\n        uint16_t inWidthOfX, uint16_t inNumCategories, uint16_t inRefCategory) {\n        mStorage = inAllocator.allocateArray<double, dbal::AggregateContext,\n            dbal::DoZero, dbal::ThrowBadAlloc>(arraySize(inWidthOfX, inNumCategories));\n        rebind(inWidthOfX, inNumCategories);\n        widthOfX = inWidthOfX;\n        numCategories = inNumCategories;\n        ref_category = inRefCategory;\n    }\n\n    /**\n     * @brief We need to support assigning the previous state\n     */\n    template <class OtherHandle> MLogRegrRobustTransitionState &operator=(\n        const MLogRegrRobustTransitionState<OtherHandle> &inOtherState) {\n        for (size_t i = 0; i < mStorage.size(); i++)\n            mStorage[i] = inOtherState.mStorage[i];\n        return *this;\n    }\n\n    /**\n     * @brief Merge with another State object by copying the intra-iteration\n     *     fields\n     */\n    template <class OtherHandle> MLogRegrRobustTransitionState &operator+=(\n        const MLogRegrRobustTransitionState<OtherHandle> &inOtherState) {\n        if (mStorage.size() != inOtherState.mStorage.size() ||\n            widthOfX != inOtherState.widthOfX)\n            throw std::logic_error(\"Internal error: Incompatible transition \"\n                \"states\");\n\n        numRows += inOtherState.numRows;\n        X_transp_AX += inOtherState.X_transp_AX;\n        meat += inOtherState.meat;\n        return *this;\n    }\n\n    /**\n     * @brief Reset the inter-iteration fields.\n     */\n    inline void reset() {\n        numRows = 0;\n        meat.fill(0);\n        X_transp_AX.fill(0);\n    }\n\nprivate:\n    static inline uint32_t arraySize(const uint16_t inWidthOfX,\n        const uint16_t inNumCategories) {\n        return 4 + 2*inWidthOfX * inWidthOfX * inNumCategories * inNumCategories\n                                 + inWidthOfX * inNumCategories;\n    }\n\n    /**\n     * @brief Rebind to a new storage array\n     *\n     * @param inWidthOfX             The number of independent variables.\n     * @param inNumCategories The number of categories of the dependant var\n\n\n     * Array layout (iteration refers to one aggregate-function call):\n     * Inter-iteration components (updated in final function):\n     * - 0: widthOfX (number of independant variables)\n     * - 1: numCategories (number of categories)\n     * - 2: ref_category\n     * - 3: coef (vector of coefficients)\n     *\n     * Intra-iteration components (updated in transition step):\n     * - 3 + widthOfX*numCategories: numRows (number of rows already processed in this iteration)\n     * - 4 + widthOfX * inNumCategories: X_transp_AX (X^T A X).\n     * - 4 + widthOfX^2*numCategories^2: meat  (The meat matrix)\n     */\n    void rebind(uint16_t inWidthOfX = 0, uint16_t inNumCategories = 0) {\n        widthOfX.rebind(&mStorage[0]);\n        numCategories.rebind(&mStorage[1]);\n        ref_category.rebind(&mStorage[2]);\n        coef.rebind(&mStorage[3], inWidthOfX * inNumCategories);\n        numRows.rebind(&mStorage[3 + inWidthOfX * inNumCategories]);\n        X_transp_AX.rebind(&mStorage[4 + inWidthOfX * inNumCategories],\n            inNumCategories * inWidthOfX, inWidthOfX * inNumCategories);\n        meat.rebind(&mStorage[4 +\n             inNumCategories * inNumCategories * inWidthOfX * inWidthOfX\n             + inWidthOfX * inNumCategories], inWidthOfX * inNumCategories, inWidthOfX * inNumCategories);\n    }\n\n    Handle mStorage;\n\npublic:\n    typename HandleTraits<Handle>::ReferenceToUInt16 widthOfX;\n    typename HandleTraits<Handle>::ReferenceToUInt16 numCategories;\n    typename HandleTraits<Handle>::ReferenceToUInt16 ref_category;\n\n    typename HandleTraits<Handle>::ColumnVectorTransparentHandleMap coef;\n    typename HandleTraits<Handle>::ReferenceToUInt64 numRows;\n    typename HandleTraits<Handle>::MatrixTransparentHandleMap X_transp_AX;\n    typename HandleTraits<Handle>::MatrixTransparentHandleMap meat;\n};\n\n/**\n * @brief IRLS Transition\n * @param args\n *\n * Arguments (Matched with PSQL wrapped)\n * - 0: Current State\n * - 1: y value (Integer)\n * - 2: numCategories (Integer)\n * - 3: ref_category (Integer)\n * - 4: X value (Column Vector)\n * - 5: Previous State\n\n */\nAnyType\n__mlogregr_irls_step_transition::run(AnyType &args) {\n    MLogRegrIRLSTransitionState<MutableArrayHandle<double> > state = args[0];\n\n    if (args[1].isNull() || args[2].isNull() || args[3].isNull() ||\n            args[4].isNull()) {\n        return args[0];\n    }\n\n    // Get x as a vector of double\n    MappedColumnVector x;\n    try{\n        // an exception is raised in the backend if args[2] contains nulls\n        MappedColumnVector xx = args[4].getAs<MappedColumnVector>();\n        // x is a const reference, we can only rebind to change its pointer\n        x.rebind(xx.memoryHandle(), xx.size());\n    } catch (const ArrayWithNullException &e) {\n        return args[0];\n    }\n\n    // Get the category & numCategories as integer\n    int32_t category = args[1].getAs<int32_t>();\n    // Number of categories after pivoting (we pivot around the first category)\n    int32_t numCategories = (args[2].getAs<int32_t>() - 1);\n    int32_t ref_category = args[3].getAs<int32_t>();\n\n    // The following check was added with MADLIB-138.\n    if (!x.is_finite())\n            throw std::domain_error(\"Design matrix is not finite.\");\n\n    if (state.numRows == 0) {\n        if (x.size() > std::numeric_limits<uint16_t>::max())\n                throw std::domain_error(\"Number of independent variables cannot be \"\n                        \"larger than 65535.\");\n\n        if (numCategories < 1)\n                throw std::domain_error(\"Number of cateogires must be at least 2\");\n\n        // Init the state (requires x.size() and category.size())\n        state.initialize(*this,\n            static_cast<uint16_t>(x.size()) ,\n            static_cast<uint16_t>(numCategories),\n            static_cast<uint16_t>(ref_category));\n\n        if (!args[5].isNull()) {\n                MLogRegrIRLSTransitionState<ArrayHandle<double> >\n                        previousState = args[5];\n                state = previousState;\n                state.reset();\n        }\n    }\n\n\n    /*\n     * This check should be done for each iteration. Only checking the first\n     * run is not enough.\n     */\n    if (category > numCategories || category < 0)\n        throw std::domain_error(\"Invalid category. Categories must be integer \"\n            \"values between 0 and (number of categories - 1).\");\n\n    if (ref_category > numCategories || ref_category < 0)\n        throw std::domain_error(\"Invalid reference category. Reference category must be integer \"\n            \"value between 0 and (number of categories - 1).\");\n\n    // Now do the transition step\n    state.numRows++;\n    /*     Get y: Convert to 1/0 boolean vector\n            Example: Category 4 : 0 0 0 1 0 0\n            Storing it in this forms helps us get a nice closed form expression\n    */\n\n    //To pivot around the specified reference category\n    ColumnVector y(numCategories);\n    y.fill(0);\n    if (category > ref_category) {\n        y(category - 1) = 1;\n    } else if (category < ref_category) {\n        y(category) = 1;\n    }\n\n    /*\n    Compute the parameter vector (the 'pi' vector in the documentation)\n    for the data point being processed.\n    Casting the coefficients into a matrix makes the calculation simple.\n    */\n    Matrix coef = state.coef;\n    coef.resize(numCategories, state.widthOfX);\n\n    //Store the intermediate calculations because we'll reuse them in the LLH\n    ColumnVector t1 = x; //t1 is vector of size state.widthOfX\n    t1 = coef*x;\n    /* Note: The above 2 lines could have been written as:\n        ColumnVector t1 = -coef*x;\n\n        but this creates warnings. These warnings are somehow related to the factor\n        that x is of an immutable type. The following alternative could resolve\n        the warnings (although not necessary the best alternative):\n    */\n\n    ColumnVector t2 = t1.array().exp();\n    double t3 = 1 + t2.sum();\n    ColumnVector pi = t2/t3;\n\n    //The gradient matrix has numCategories rows and widthOfX columns\n    Matrix grad = -y*x.transpose() + pi*x.transpose();\n    //We cast the gradient into a vector to make the Newton step calculations much easier.\n    grad.resize(numCategories*state.widthOfX,1);\n\n    /*\n         a is a matrix of size JxJ where J is the number of categories\n         a_j1j2 = -pi(j1)*(1-pi(j2))if j1 == j2\n         a_j1j2 =  pi(j1)*pi(j2) if j1 != j2\n    */\n    Matrix a(numCategories,numCategories);\n    // Compute the 'a' matrix.\n    Matrix piDiag = pi.asDiagonal();\n    a = pi * pi.transpose() - piDiag;\n    state.gradient.noalias() += grad;\n\n    //Start the Hessian calculations\n    Matrix X_transp_AX(numCategories * state.widthOfX, numCategories * state.widthOfX);\n\n    /*\n        Again: The following 3 lines could have been written as\n        Matrix XXTrans = x * x.transpose();\n        but it creates warnings related to the type of x. Here is an easy fix\n    */\n    Matrix cv_x = x;\n    Matrix XXTrans = trans(cv_x);\n    XXTrans = cv_x * XXTrans;\n\n    //Eigen doesn't supported outer-products for matrices, so we have to do our own.\n    //This operation is also known as a tensor-product.\n    for (int i1 = 0; i1 < state.widthOfX; i1++){\n         for (int i2 = 0; i2 <state.widthOfX; i2++){\n            int rowOffset = numCategories * i1;\n            int colOffset = numCategories * i2;\n\n            X_transp_AX.block(rowOffset, colOffset, numCategories,  numCategories) = XXTrans(i1,i2)*a;\n        }\n    }\n\n    triangularView<Lower>(state.X_transp_AX) += X_transp_AX;\n\n    state.logLikelihood += y.transpose()*t1 - log(t3);\n\n    return state;\n\n}\n\n/**\n * @brief Perform the perliminary aggregation function: Merge transition states\n     This merge step is the same as that of logistic regression.\n */\nAnyType\n__mlogregr_irls_step_merge_states::run(AnyType &args) {\n    MLogRegrIRLSTransitionState<MutableArrayHandle<double> > stateLeft = args[0];\n    MLogRegrIRLSTransitionState<ArrayHandle<double> > stateRight = args[1];\n\n    // We first handle the trivial case where this function is called with one\n    // of the states being the initial state\n    if (stateLeft.numRows == 0)\n        return stateRight;\n    else if (stateRight.numRows == 0)\n        return stateLeft;\n\n    // Merge states together and return\n    stateLeft += stateRight;\n    return stateLeft;\n}\n\n/**\n * @brief Perform the logistic-regression final step\n */\nAnyType\n__mlogregr_irls_step_final::run(AnyType &args) {\n    // We request a mutable object.\n    // Depending on the backend, this might perform a deep copy.\n    MLogRegrIRLSTransitionState<MutableArrayHandle<double> > state = args[0];\n\n    // Aggregates that haven't seen any data just return Null.\n    if (state.numRows == 0)\n        return Null();\n\n    // See MADLIB-138. At least on certain platforms and with certain versions,\n    // LAPACK will run into an infinite loop if pinv() is called for non-finite\n    // matrices. We extend the check also to the dependent variables.\n    if (!state.X_transp_AX.is_finite() || !state.gradient.is_finite())\n        throw NoSolutionFoundException(\"Over- or underflow in intermediate \"\n            \"calculation. Input data is likely of poor numerical condition.\");\n\n    SymmetricPositiveDefiniteEigenDecomposition<Matrix> decomposition(\n        -1 * state.X_transp_AX, EigenvaluesOnly, ComputePseudoInverse);\n\n    // Precompute (X^T * A * X)^-1\n    Matrix hessianInv = -1 * decomposition.pseudoInverse();\n\n    state.coef.noalias() += hessianInv * state.gradient;\n\n    if(!state.coef.is_finite())\n        throw NoSolutionFoundException(\"Over- or underflow in Newton step, \"\n            \"while updating coefficients. Input data is likely of poor \"\n            \"numerical condition.\");\n\n    // We use the intra-iteration field gradient for storing the diagonal\n    // of X^T A X, so that we don't have to recompute it in the result function.\n    // Likewise, we store the condition number.\n    // FIXME: This feels a bit like a hack.\n    state.conditionNo = decomposition.conditionNo();\n    state.X_transp_AX = -1 * hessianInv;\n\n    return state;\n}\n\n/**\n * @brief Compute the diagnostic statistics\n *\n * This function wraps the common parts of mlogregr state into the result.\n * (the result data type is defined in multilogistic.sql_in)\n */\nAnyType mLogstateToResult(\n    const Allocator &inAllocator,\n    MLogRegrIRLSTransitionState<ArrayHandle<double> > state) {\n\n    int ref_category = state.ref_category;\n    const HandleMap<const ColumnVector, TransparentHandle<double> > &inCoef = state.coef;\n    double logLikelihood = state.logLikelihood;\n    uint64_t num_processed = state.numRows;\n\n    // Per the hack at the end of the final function we place the inverse\n    // of the X_tranp_AX into the state.X_transp_AX\n    const Matrix & X_transp_AX_inverse = state.X_transp_AX;\n    const ColumnVector &diagonal_of_hessian = X_transp_AX_inverse.diagonal();\n\n    MutableNativeColumnVector stdErr(\n        inAllocator.allocateArray<double>(inCoef.size()));\n    MutableNativeColumnVector waldZStats(\n        inAllocator.allocateArray<double>(inCoef.size()));\n    MutableNativeColumnVector waldPValues(\n        inAllocator.allocateArray<double>(inCoef.size()));\n    MutableNativeColumnVector oddsRatios(\n        inAllocator.allocateArray<double>(inCoef.size()));\n\n    for (Index i = 0; i < inCoef.size(); ++i) {\n        stdErr(i) = std::sqrt(diagonal_of_hessian(i));\n        waldZStats(i) = inCoef(i) / stdErr(i);\n        waldPValues(i) = 2. * prob::cdf( prob::normal(),\n            -std::abs(waldZStats(i)));\n        oddsRatios(i) = std::exp( inCoef(i) );\n    }\n    int num_iterations = 0;\n    // Return all coefficients, standard errors, etc. in a tuple\n    AnyType tuple;\n    tuple << ref_category << inCoef << logLikelihood << stdErr\n          << waldZStats << waldPValues << oddsRatios\n          << static_cast<double>(state.conditionNo) << num_iterations << num_processed;\n    return tuple;\n}\n\n\n/**\n * @brief Return the difference in log-likelihood between two states\n */\nAnyType\n__internal_mlogregr_irls_step_distance::run(AnyType &args) {\n    MLogRegrIRLSTransitionState<ArrayHandle<double> > stateLeft = args[0];\n    MLogRegrIRLSTransitionState<ArrayHandle<double> > stateRight = args[1];\n\n    return std::abs(stateLeft.logLikelihood - stateRight.logLikelihood);\n}\n\n/**\n * @brief Return the coefficients and diagnostic statistics of the state\n */\nAnyType\n__internal_mlogregr_irls_result::run(AnyType &args) {\n    MLogRegrIRLSTransitionState<ArrayHandle<double> > state = args[0];\n\n    return mLogstateToResult(*this, state);\n    // state.ref_category, state.coef,\n    // state.gradient, state.logLikelihood, state.X_transp_AX(0,0));\n}\n\n/**\n * @brief Return the coefficients and diagnostic statistics of the state\n */\nAnyType\n__internal_mlogregr_summary_results::run(AnyType &args) {\n    MLogRegrIRLSTransitionState<ArrayHandle<double> > state = args[0];\n    const Matrix & X_transp_AX_inverse = state.X_transp_AX;\n    // X_transp_AX is actually it's inverse - this is a hack added at the end of\n    // the final function\n    AnyType tuple;\n    Matrix coef = state.coef;\n    coef.resize(state.numCategories, state.widthOfX);\n    coef.transposeInPlace();\n    tuple << coef << X_transp_AX_inverse;\n    return tuple;\n}\n// ----------------- End of Multinomial Logistic Regression --------------------\n\n// ---------------------------------------------------------------------------\n//             Robust Variance Multi-Logistic\n// ---------------------------------------------------------------------------\n\nAnyType\nmlogregr_robust_step_transition::run(AnyType &args) {\n    using std::endl;\n\n\tMLogRegrRobustTransitionState<MutableArrayHandle<double> > state = args[0];\n\n   if (args[1].isNull() || args[2].isNull() || args[3].isNull() ||\n            args[4].isNull() || args[5].isNull()) {\n        return args[0];\n    }\n\n    // Get x as a vector of double\n    MappedColumnVector x;\n    try{\n        // an exception is raised in the backend if args[2] contains nulls\n        MappedColumnVector xx = args[4].getAs<MappedColumnVector>();\n        // x is a const reference, we can only rebind to change its pointer\n        x.rebind(xx.memoryHandle(), xx.size());\n    } catch (const ArrayWithNullException &e) {\n        return args[0];\n    }\n\n    // Get the category & numCategories as integer\n    int16_t category = static_cast<int16_t>(args[1].getAs<int>());\n    // Number of categories after pivoting (We pivot around the first category)\n    int16_t numCategories = static_cast<int16_t>(args[2].getAs<int>() - 1);\n    int32_t ref_category = args[3].getAs<int32_t>();\n\tMappedMatrix coefMat = args[5].getAs<MappedMatrix>();\n\n    // The following check was added with MADLIB-138.\n    if (!x.is_finite())\n            throw std::domain_error(\"Design matrix is not finite.\");\n\n    if (state.numRows == 0) {\n        if (x.size() > std::numeric_limits<uint16_t>::max())\n                throw std::domain_error(\"Number of independent variables cannot be \"\n                        \"larger than 65535.\");\n        if (numCategories < 1)\n                throw std::domain_error(\"Number of cateogires must be at least 2\");\n        if (category > numCategories)\n                throw std::domain_error(\"You have entered a category > numCategories\"\n                    \"Categories must be of values {0,1... numCategories-1}\");\n\n        // Init the state (requires x.size() and category.size())\n        state.initialize(*this,\n            static_cast<uint16_t>(x.size()) ,\n            static_cast<uint16_t>(numCategories),\n            static_cast<uint16_t>(ref_category));\n\n        Matrix mat = coefMat;\n        mat.transposeInPlace();\n        mat.resize(coefMat.size(), 1);\n        state.coef = mat;\n    }\n\n    // Now do the transition step\n    state.numRows++;\n    /*\n        Get y: Convert to 1/0 boolean vector\n        Example: Category 4 : 0 0 0 1 0 0\n        Storing it in this forms helps us get a nice closed form expression\n    */\n\n    //To pivot around the specified reference category\n    ColumnVector y(numCategories);\n    y.fill(0);\n    if (category > ref_category) {\n        y(category - 1) = 1;\n    } else if (category < ref_category) {\n        y(category) = 1;\n    }\n\n    /*\n    Compute the parameter vector (the 'pi' vector in the documentation)\n    for the data point being processed.\n    Casting the coefficients into a matrix makes the calculation simple.\n    */\n\n    Matrix coef = state.coef;\n    coef.resize(numCategories, state.widthOfX);\n\n    //Store the intermediate calculations because we'll reuse them in the LLH\n    ColumnVector t1 = x; //t1 is vector of size state.widthOfX\n    t1 = coef*x;\n    /*\n        Note: The above 2 lines could have been written as:\n        ColumnVector t1 = -coef*x;\n\n        but this creates warnings. These warnings are somehow related to the factor\n        that x is an immutable type.\n    */\n\n    ColumnVector t2 = t1.array().exp();\n    double t3 = 1 + t2.sum();\n    ColumnVector pi = t2/t3;\n\n\t//The gradient matrix has numCategories rows and widthOfX columns\n    Matrix grad = -y * x.transpose() + pi * x.transpose();\n    //We cast the gradient into a vector to make the math easier.\n    grad.resize(numCategories * state.widthOfX, 1);\n\n    Matrix GradGradTranspose;\n    GradGradTranspose = grad * grad.transpose();\n\tstate.meat += GradGradTranspose;\n\n    /*\n         a is a matrix of size JxJ where J is the number of categories\n         a_j1j2 = -pi(j1)*(1-pi(j2))if j1 == j2\n         a_j1j2 =  pi(j1)*pi(j2) if j1 != j2\n    */\n    // Compute the 'a' matrix.\n    Matrix a(numCategories,numCategories);\n    Matrix piDiag = pi.asDiagonal();\n    a = pi * pi.transpose() - piDiag;\n\n    //Start the Hessian calculations\n    Matrix X_transp_AX(numCategories * state.widthOfX, numCategories * state.widthOfX);\n\n    /*\n        Again: The following 3 lines could have been written as\n        Matrix XXTrans = x * x.transpose();\n        but it creates warnings related to the type of x. Here is an easy fix\n    */\n    Matrix cv_x = x;\n    Matrix XXTrans = trans(cv_x);\n    XXTrans = cv_x * XXTrans;\n\n    //Eigen doesn't supported outer-products for matrices, so we have to do our own.\n    //This operation is also known as a tensor-product.\n    for (int i1 = 0; i1 < state.widthOfX; i1++){\n         for (int i2 = 0; i2 <state.widthOfX; i2++){\n            int rowOffset = numCategories * i1;\n            int colOffset = numCategories * i2;\n\n            X_transp_AX.block(rowOffset, colOffset, numCategories,  numCategories) = XXTrans(i1, i2) * a;\n        }\n    }\n\n    triangularView<Lower>(state.X_transp_AX) += X_transp_AX;\n\n    return state;\n\n}\n\n/**\n * @brief Perform the perliminary aggregation function: Merge transition states\n     This merge step is the same as that of logistic regression.\n */\nAnyType\nmlogregr_robust_step_merge_states::run(AnyType &args) {\n    MLogRegrRobustTransitionState<MutableArrayHandle<double> > stateLeft = args[0];\n    MLogRegrRobustTransitionState<ArrayHandle<double> > stateRight = args[1];\n\n    // We first handle the trivial case where this function is called with one\n    // of the states being the initial state\n    if (stateLeft.numRows == 0)\n        return stateRight;\n    else if (stateRight.numRows == 0)\n        return stateLeft;\n\n    // Merge states together and return\n    stateLeft += stateRight;\n    return stateLeft;\n}\n\nAnyType MLrobuststateToResult(\n    const Allocator &inAllocator,\n    int ref_category,\n    const HandleMap<const ColumnVector, TransparentHandle<double> >& inCoef,\n    const ColumnVector &diagonal_of_varianceMat) {\n\n\tMutableNativeColumnVector variance(\n        inAllocator.allocateArray<double>(inCoef.size()));\n    MutableNativeColumnVector stdErr(\n        inAllocator.allocateArray<double>(inCoef.size()));\n    MutableNativeColumnVector waldZStats(\n        inAllocator.allocateArray<double>(inCoef.size()));\n    MutableNativeColumnVector waldPValues(\n        inAllocator.allocateArray<double>(inCoef.size()));\n\n    for (Index i = 0; i < inCoef.size(); ++i) {\n        variance(i) = diagonal_of_varianceMat(i);\n        stdErr(i) = std::sqrt(diagonal_of_varianceMat(i));\n        waldZStats(i) = inCoef(i) / stdErr(i);\n        waldPValues(i) = 2. * prob::cdf(\n            prob::normal(), -std::abs(waldZStats(i)));\n    }\n\n    // Return all coefficients, standard errors, etc. in a tuple\n    AnyType tuple;\n    tuple <<  ref_category << inCoef << stdErr << waldZStats << waldPValues;\n    return tuple;\n}\n\n\n/**\n * @brief Perform the logistic-regression final step\n */\nAnyType\nmlogregr_robust_step_final::run(AnyType &args) {\n    // We request a mutable object. Depending on the backend, this might perform\n    // a deep copy.\n    MLogRegrRobustTransitionState<ArrayHandle<double> > state = args[0];\n    // Aggregates that haven't seen any data just return Null.\n    if (state.numRows == 0)\n        return Null();\n\n    // See MADLIB-138. At least on certain platforms and with certain versions,\n    // LAPACK will run into an infinite loop if pinv() is called for non-finite\n    // matrices. We extend the check also to the dependent variables.\n    if (!state.X_transp_AX.is_finite())\n        throw NoSolutionFoundException(\"Over- or underflow in intermediate \"\n            \"calculation. Input data is likely of poor numerical condition.\");\n\n\n    SymmetricPositiveDefiniteEigenDecomposition<Matrix> decomposition(\n        -1 * state.X_transp_AX, EigenvaluesOnly, ComputePseudoInverse);\n\n    // Precompute (X^T * A * X)^-1\n    Matrix bread = decomposition.pseudoInverse();\n\tMatrix varianceMat;\n    varianceMat = bread * state.meat * bread;\n\n    if(!state.coef.is_finite())\n        throw NoSolutionFoundException(\"Over- or underflow in Newton step, \"\n            \"while updating coefficients. Input data is likely of poor \"\n            \"numerical condition.\");\n\n    return MLrobuststateToResult(*this, state.ref_category, state.coef, varianceMat.diagonal());\n}\n// ------------------------ End of Robust Variance -----------------------------\n\nAnyType __sub_array::run(AnyType &args) {\n    if (args[0].isNull() || args[1].isNull())\n        return Null();\n\n    ArrayHandle<double> value = args[0].getAs<ArrayHandle<double> >();\n    ArrayHandle<int32> index = args[1].getAs<ArrayHandle<int32> >();\n\n    for (size_t i = 0; i < index.size(); i++) {\n        if (index[i] < 1 || index[i] > static_cast<int>(value.size()))\n            throw std::domain_error(\"Invalid indices - out of bound\");\n    }\n\n    MutableArrayHandle<double> res =\n        allocateArray<double, dbal::AggregateContext, dbal::DoZero,\n            dbal::ThrowBadAlloc>(index.size());\n\n    for (size_t i = 0; i < index.size(); i++)\n        res[i] = value[index[i] - 1];\n\n    return res;\n}\n\n// ----------------------------------------------------------------------------\ntypedef struct __sr_ctx{\n    const double * inarray;\n    int32_t maxcall;\n    int32_t num_feature;\n    int32_t num_category;\n    int32_t ref_category;\n    int32_t curcall;\n} sr_ctx;\n\nvoid *\n__mlogregr_format::SRF_init(AnyType &args) {\n    sr_ctx *ctx = new sr_ctx;\n    ctx->curcall = 0;\n\n    MutableArrayHandle<double> inarray = NULL;\n    try{\n        inarray = args[0].getAs<MutableArrayHandle<double> >();\n    } catch (const ArrayWithNullException &e) {\n        ctx->maxcall = 0;\n        return ctx;\n    }\n\n    int32_t num_feature = args[1].getAs<int32_t>();\n    int32_t num_category = args[2].getAs<int32_t>();\n    int32_t ref_category = args[3].getAs<int32_t>();\n\n    ctx->inarray = inarray.ptr();\n    ctx->maxcall = num_category - 1;\n    ctx->num_category = num_category - 1;\n    ctx->num_feature = num_feature;\n    ctx->ref_category = ref_category;\n\n    if (num_feature * (num_category - 1) !=\n            static_cast<int32_t>(inarray.size())) {\n        throw std::runtime_error(\"num_feature * (num_category - 1) != \"\n                \"inarray.size()\");\n    }\n\n    if (ref_category >= num_category){\n        throw std::runtime_error(\"ref_category >= num_category\");\n    }\n\n    return ctx;\n}\n\nAnyType\n__mlogregr_format::SRF_next(void * user_fctx, bool * is_last_call) {\n    sr_ctx * ctx = (sr_ctx *) user_fctx;\n    if (ctx->curcall >= ctx->maxcall) {\n        *is_last_call = true;\n        return Null();\n    }\n\n    MutableArrayHandle<double> outarray =\n        allocateArray<double, dbal::FunctionContext,\n            dbal::DoZero, dbal::ThrowBadAlloc>(ctx->num_feature);\n    for(int i = 0; i < ctx->num_feature; i++) {\n        outarray[i] = ctx->inarray[i * ctx->num_category + ctx->curcall];\n    }\n\n    AnyType tuple;\n    tuple << (ctx->curcall < ctx->ref_category\n            ? ctx->curcall\n            : ctx->curcall + 1)\n          << outarray;\n\n    ctx->curcall++;\n\n    return tuple;\n}\n/* ------------------------------------------------------------ */\n\n\nAnyType mlogregr_predict_prob::run(AnyType &args)\n{\n    // dimension: N x (L - 1), where L is the number of categories\n    MappedMatrix coef = args[0].getAs<MappedMatrix>();\n\n    int ref_category = args[1].getAs<int>();\n    MappedColumnVector x;\n    try {\n        MappedColumnVector xx = args[2].getAs<MappedColumnVector>();\n        x.rebind(xx.memoryHandle(), xx.size());\n    } catch (const ArrayWithNullException &e) {\n        return Null();\n    }\n\n    int L = static_cast<int>(coef.cols()) + 1; // number of categories\n\n    ColumnVector res(L);\n    int cat_index = 0;\n    for (int i = 0; i < L; i++) {\n        if (i == ref_category) {\n            res(i) = 1;\n        } else {\n            res(i) = exp(coef.col(cat_index).dot(x));\n            cat_index++;\n        }\n    }\n    res /= res.sum();\n    return res;\n}\n/* ------------------------------------------------------------ */\n\nAnyType mlogregr_predict_response::run(AnyType &args)\n{\n    // dimension: N x (L - 1), where L is the number of categories\n    MappedMatrix coef = args[0].getAs<MappedMatrix>();\n\n    int ref_category = args[1].getAs<int>();\n    MappedColumnVector x;\n    try {\n        MappedColumnVector xx = args[2].getAs<MappedColumnVector>();\n        x.rebind(xx.memoryHandle(), xx.size());\n    } catch (const ArrayWithNullException &e) {\n        return Null();\n    }\n\n    ColumnVector linear_predictors(x.transpose() * coef);\n    Index max_cat = 0;\n    linear_predictors.maxCoeff(&max_cat);\n    double max_lp = linear_predictors(max_cat);\n\n    if (exp(max_lp) < 1){\n        // no category has high enough probability as reference category\n        return ref_category;\n    } else if (max_cat < ref_category){\n        return static_cast<uint>(max_cat);\n    }\n    else{\n        // since ref_category is not present in the coef matrix, index of\n        // categories after ref_category is 1 less than the actual index\n        return static_cast<uint>(max_cat + 1u);\n    }\n}\n\n} // namespace regress\n\n} // namespace modules\n\n} // namespace madlib\n", "meta": {"hexsha": "4e44d3e6b5379eaba8a672be5f235b398c58f1a4", "size": 36631, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/modules/regress/multilogistic.cpp", "max_stars_repo_name": "pandeyh/incubator-madlib", "max_stars_repo_head_hexsha": "c69515081d26b63089677fcccccd3393a0dc59dd", "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/regress/multilogistic.cpp", "max_issues_repo_name": "Acidburn0zzz/madlib", "max_issues_repo_head_hexsha": "59c7afdbcb2b561cd43d6d57bed03d0bc0fa122e", "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/regress/multilogistic.cpp", "max_forks_repo_name": "Acidburn0zzz/madlib", "max_forks_repo_head_hexsha": "59c7afdbcb2b561cd43d6d57bed03d0bc0fa122e", "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": 35.1208053691, "max_line_length": 106, "alphanum_fraction": 0.6492861238, "num_tokens": 9148, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.668880247169804, "lm_q2_score": 0.5117166047041654, "lm_q1q2_score": 0.342277129035415}}
{"text": "// Copyright (c) 2014\n// Akira Takahashi, Fumiki Fukuda.\n// Released under the CC0 1.0 Universal license.\n\n#include <iostream>\n#include <cmath> // sqrt\n#include <algorithm> // min\n#include <utility> // pair\n#include <boost/utility/enable_if.hpp>\n\nstruct point_category {};\n\ntemplate <class T, class Enable = void>\nstruct get_geometry_category;\n\ntemplate <class T, class Enable = void>\nstruct point_traits {\n  static double x(const T& p) { return p.x(); }\n  static double y(const T& p) { return p.y(); }\n\n  static T subtract(const T& a, const T& b)\n    { return T(a.x() - b.x(), a.y() - b.y()); }\n};\n\nclass point {\n  double x_ = 0;\n  double y_ = 0;\npublic:\n  point() = default;\n  point(double x, double y)\n    : x_(x), y_(y) {}\n\n  // それぞれの座標を取得する\n  double x() const { return x_; }\n  double y() const { return y_; }\n};\n\ntemplate <>\nstruct get_geometry_category<point> {\n  typedef point_category type;\n};\n\n// 別の計算幾何ライブラリ\nnamespace geo {\n\ntemplate <class T>\nstruct is_point_category {\n  static const bool value = false;\n};\n\ntemplate <class T>\nstruct point_traits {\n  static double getX(const T& p) { return p.getX(); }\n  static double getY(const T& p) { return p.getY(); }\n\n  static T subtract(const T& a, const T& b)\n    { return T(a.getX() - b.getX(), a.getY() - b.getY()); }\n};\n\nclass point {\n  double x_ = 0;\n  double y_ = 0;\npublic:\n  point() = default;\n  point(double x, double y)\n    : x_(x), y_(y) {}\n\n  // それぞれの座標を取得する\n  double getX() const { return x_; }\n  double getY() const { return y_; }\n};\n\ntemplate <>\nstruct is_point_category<point> {\n  static const bool value = true;\n};\n\ntemplate <>\nstruct point_traits<std::pair<double, double>> {\n  typedef std::pair<double, double> point_type;\n\n  static double getX(const point_type& p)\n    { return p.first; }\n\n  static double getY(const point_type& p)\n    { return p.second; }\n\n  static point_type subtract(\n                      const point_type& a,\n                      const point_type& b)\n  {\n    return std::make_pair(\n             a.first - b.first,\n             a.second - b.second);\n  }\n};\n\ntemplate <>\nstruct is_point_category<std::pair<double, double>> {\n  static const bool value = true;\n};\n\n} // namespace geo\n\ntemplate <class T>\nstruct get_geometry_category<\n         T,\n         typename boost::enable_if<\n           geo::is_point_category<T>\n         >::type\n       > {\n  typedef point_category type;\n};\n\ntemplate <class T>\nstruct point_traits<\n         T,\n         typename boost::enable_if<\n           geo::is_point_category<T>\n         >::type\n       > {\n  static double x(const T& p) { return geo::point_traits<T>::getX(p); }\n  static double y(const T& p) { return geo::point_traits<T>::getY(p); }\n\n  static T subtract(const T& a, const T& b)\n    { return geo::point_traits<T>::subtract(a, b); }\n};\n\n// 点と点\ntemplate <class Point>\ndouble distance_impl(Point a, Point b,\n                     point_category, point_category)\n{\n  typedef point_traits<Point> traits;\n  const Point d = traits::subtract(a, b);\n  return std::sqrt(traits::x(d) * traits::x(d) +\n                   traits::y(d) * traits::y(d));\n}\n\ntemplate <class Geometry1, class Geometry2>\ndouble distance(Geometry1 a, Geometry2 b)\n{\n  return distance_impl(a, b,\n           typename get_geometry_category<Geometry1>::type(),\n           typename get_geometry_category<Geometry2>::type());\n}\n\nint main()\n{\n  {\n    point p1(0.0, 0.0);\n    point p2(3.0, 3.0);\n\n    double d = distance(p1, p2);\n    std::cout << d << std::endl;\n  }\n  {\n    geo::point p1(0.0, 0.0);\n    geo::point p2(3.0, 3.0);\n\n    double d = distance(p1, p2);\n    std::cout << d << std::endl;\n  }\n  {\n    std::pair<double, double> p1(0.0, 0.0);\n    std::pair<double, double> p2(3.0, 3.0);\n\n    double d = distance(p1, p2);\n    std::cout << d << std::endl;\n  }\n}\n", "meta": {"hexsha": "eda9a8e866a38fed224d52ffbe2d8dc88dcd9596", "size": 3757, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "07_concept/06_specialize_template_with_concept.cpp", "max_stars_repo_name": "cpptt-book/2nd", "max_stars_repo_head_hexsha": "d710af6df9ed2561bc7432be7b0b0b93dafecb0a", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 17.0, "max_stars_repo_stars_event_min_datetime": "2015-01-07T08:10:09.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-21T13:07:25.000Z", "max_issues_repo_path": "07_concept/06_specialize_template_with_concept.cpp", "max_issues_repo_name": "cpptt-book/2nd", "max_issues_repo_head_hexsha": "d710af6df9ed2561bc7432be7b0b0b93dafecb0a", "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": "07_concept/06_specialize_template_with_concept.cpp", "max_forks_repo_name": "cpptt-book/2nd", "max_forks_repo_head_hexsha": "d710af6df9ed2561bc7432be7b0b0b93dafecb0a", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2015-05-02T19:07:43.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-14T21:21:32.000Z", "avg_line_length": 21.8430232558, "max_line_length": 71, "alphanum_fraction": 0.6089965398, "num_tokens": 1079, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5774953651858118, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.34226221457390893}}
{"text": "\n/******************************************************************************\n\n  Modified Christiansen algorithm for tiling two contours.\n\n  Copyright (c) 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 CHRISTIANSEN_TILING_HPP_D80E68A2_DF31_11E2_BAA7_4057033B4CBB\n#define CHRISTIANSEN_TILING_HPP_D80E68A2_DF31_11E2_BAA7_4057033B4CBB\n\n#include <vector>\n#include <limits>\n#include <stdexcept>\n#include <utility>\n#include <boost/function.hpp>\n#include <boost/noncopyable.hpp>\n#include <boost/shared_ptr.hpp>\n#include <boost/make_shared.hpp>\n\n#include \"bo/distances/distances_3d.hpp\"\n#include \"bo/surfaces/detail/container_traversers.hpp\"\n#include \"bo/surfaces/detail/indexed_tstrip.hpp\"\n\nnamespace bo {\nnamespace surfaces {\n\nnamespace detail {\n\n// A struct incorporating contour data. Instances can be safely swapped.\ntemplate <typename PointsCont>\nstruct ContourDescriptor\n{\n    typedef boost::shared_ptr<PointsCont> PointsContPtr;\n\n    ContourDescriptor(std::size_t id, PointsContPtr points_ptr, bool is_closed)\n        : ID(id), PointsPtr(points_ptr), IsClosed(is_closed), Size(points_ptr->size())\n    { }\n\n    void swap(ContourDescriptor& other)\n    {\n        // Clone data before swapping in order not to spoil original contours.\n        PointsContPtr new_this(new PointsCont(*PointsPtr));\n        PointsContPtr new_other(new PointsCont(*other.PointsPtr));\n        PointsPtr = new_other;\n        other.PointsPtr = new_this;\n\n        std::swap(ID, other.ID);\n        std::swap(IsClosed, other.IsClosed);\n        std::swap(Size, other.Size);\n    }\n\n    std::size_t ID;\n    PointsContPtr PointsPtr;\n    bool IsClosed;\n    std::size_t Size;\n};\n\n} // namespace detail\n\n\n// A class performing modified Christiansen tiling for two slices. Accepts both closed\n// contours and contours with exactly one hole.\ntemplate <typename RealType>\nclass ChristiansenTiling: public boost::noncopyable\n{\npublic:\n    typedef ChristiansenTiling<RealType> this_type;\n\n    typedef Vector<RealType, 3> Point3D;\n    typedef boost::function<RealType (Point3D, Point3D)> Metric;\n    typedef std::vector<Point3D> Contour;\n    typedef boost::shared_ptr<Contour> ContourPtr;\n    typedef detail::ContourDescriptor<Contour> ContourDescriptor;\n\n    typedef detail::ContainerConstTraverser<Contour> ContourTraverser;\n    typedef detail::TraverseRuleFactory<Contour> TraverseFactory;\n\npublic:\n    ChristiansenTiling(std::size_t id1, ContourPtr contour1, bool closed1,\n                  std::size_t id2, ContourPtr contour2, bool closed2)\n        : contour_descr1_(id1, contour1, closed1), contour_descr2_(id2, contour2, closed2),\n          metric_(&bo::distances::euclidean_distance<RealType, 3>)\n    { }\n\n    // Implementation for Christiansen algorithm for closed and opened contours.\n    //\n    // If a contour is closed, it is traversed cyclical starting and ending in the\n    // same vertex.\n    //\n    // If a contour has exactly one hole (i.e. opened), it is traversed once\n    // from the start to the end (from one hole edge to the other).\n    detail::IndexedTStrip run()\n    {\n        // Check contours' length.\n        if ((contour_descr1_.Size < 2) && (contour_descr2_.Size < 2))\n            throw std::logic_error(\"Cannot run Christiansen triangulation for contours \"\n                                   \"consisting of less than 2 vertices.\");\n\n        // If the first contour is closed but the second is opened, traverse direction\n        // for the second contour may be determined incorrectly.\n        if (contour_descr1_.IsClosed && !contour_descr2_.IsClosed)\n            contour_descr1_.swap(contour_descr2_);\n\n        // Create traversers for contours.\n        ContourTraverser current1 = create_traverser1_();\n        ContourTraverser candidate1 = current1 + 1;\n\n        ContourTraverser current2 = create_traverser2_(current1);\n        ContourTraverser candidate2 = current2 + 1;\n\n        // Initialize output TStrip structure.\n        detail::IndexedTStrip tstrip(contour_descr1_.ID, current1.index(),\n                             contour_descr2_.ID, current2.index(),\n                             contour_descr1_.Size + contour_descr2_.Size);\n\n        // Iterate until both contours are exhausted.\n        while (candidate1.is_valid() || candidate2.is_valid())\n        {\n            // Calculate span norms for candidate vertices.\n            RealType span1_norm = span_norm(candidate1, current2);\n            RealType span2_norm = span_norm(candidate2, current1);\n\n            // Choose and add candidate vertex and corresponding face.\n            if (span1_norm > span2_norm)\n            {\n                tstrip.add2(candidate2.index());\n                current2 = candidate2;\n                ++candidate2;\n            }\n            else\n            {\n                tstrip.add1(candidate1.index());\n                current1 = candidate1;\n                ++candidate1;\n            }\n        }\n\n        return tstrip;\n    }\n\nprivate:\n    // Creates an appropriate traverser for the first contour depending whether\n    // it is closed or not.\n    ContourTraverser create_traverser1_() const\n    {\n        ContourTraverser retvalue = contour_descr1_.IsClosed ?\n            ContourTraverser(TraverseFactory::Create(contour_descr1_.PointsPtr, 0, true)) :\n            ContourTraverser(TraverseFactory::Create(contour_descr1_.PointsPtr, true));\n        return retvalue;\n    }\n\n    // Creates an appropriate traverser for the second contour depending whether\n    // the contour is closed and how the first contour is oriented.\n    ContourTraverser create_traverser2_(const ContourTraverser& traverser1) const\n    {\n        ContourTraverser retvalue;\n\n        if (contour_descr2_.IsClosed)\n        {\n            // Find closest vertex on the second contour and determine direction.\n            // No need of using kd-tree here, since the operation is done once.\n            std::size_t c2min_idx = 0;\n            RealType c2min_dist = std::numeric_limits<RealType>::max();\n\n            for (std::size_t c2_idx = 0; c2_idx < contour_descr2_.Size; ++c2_idx)\n            {\n                RealType cur_dist = metric_(contour_descr2_.PointsPtr->at(c2_idx), *traverser1);\n                if (cur_dist < c2min_dist)\n                {\n                    c2min_idx = c2_idx;\n                    c2min_dist = cur_dist;\n                }\n            }\n\n            // Create a default directed traverser. This is need to calculate the\n            // direction if c2min_idx is the last element in the collection.\n            retvalue = ContourTraverser(TraverseFactory::Create(contour_descr2_.PointsPtr,\n                                                                c2min_idx, true));\n\n            // Contour2 traverse direction should be swapped in order to correspond\n            // with the contour1 direction.\n            Point3D direction1 = *(traverser1 + 1) - *traverser1;\n            Point3D direction2 = *(retvalue + 1) - *retvalue;\n            if (direction1 * direction2 < 0)\n                retvalue = ContourTraverser(TraverseFactory::Create(\n                        contour_descr2_.PointsPtr, c2min_idx, false));\n        }\n        else\n        {\n            // Check if contour2_ traverse direction should be swapped in order to\n            // correspond with the contour1_'s direction.\n            RealType dist_to_first = metric_(contour_descr2_.PointsPtr->front(), *traverser1);\n            RealType dist_to_last = metric_(contour_descr2_.PointsPtr->back(), *traverser1);\n            bool is_forward2 = (dist_to_first < dist_to_last) ? true : false;\n\n            retvalue = ContourTraverser(TraverseFactory::Create(contour_descr2_.PointsPtr,\n                                                                is_forward2));\n        }\n\n        return retvalue;\n    }\n\n    // Calculates the euclidean norm of the span between candidate vertex on one\n    // contour and current vertex on another. If candidate vertex is invalid (this\n    // indicates that the corresponding contour has been exhausted), returns infinity.\n    // This guarantees that vertices will be sampled solely from the other contour.\n    RealType span_norm(const ContourTraverser& candidate,\n                       const ContourTraverser& other_current) const\n    {\n        RealType norm = candidate.is_valid() ?\n                    metric_(*candidate, *other_current):\n                    std::numeric_limits<RealType>::max();\n        return norm;\n    }\n\nprivate:\n    ContourDescriptor contour_descr1_;\n    ContourDescriptor contour_descr2_;\n    const Metric metric_;\n};\n\n} // namespace surfaces\n} // namespace bo\n\n#endif // CHRISTIANSEN_TILING_HPP_D80E68A2_DF31_11E2_BAA7_4057033B4CBB\n", "meta": {"hexsha": "781cdbd26446a5d5d48f404e730b5a19727c20b1", "size": 10027, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Bo/surfaces/christiansen_tiling.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/christiansen_tiling.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/christiansen_tiling.hpp", "max_forks_repo_name": "rukletsov/bo", "max_forks_repo_head_hexsha": "bfece9e8f910b0c8f522733854405bf0a801b0e8", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.9482071713, "max_line_length": 96, "alphanum_fraction": 0.6587214521, "num_tokens": 2251, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5926665999540698, "lm_q2_score": 0.5774953651858117, "lm_q1q2_score": 0.3422622145739089}}
{"text": "/* pcmsolver_copyright_start */\n/*\n *     PCMSolver, an API for the Polarizable Continuum Model\n *     Copyright (C) 2013-2016 Roberto Di Remigio, Luca Frediani and contributors\n *     \n *     This file is part of PCMSolver.\n *     \n *     PCMSolver is free software: you can redistribute it and/or modify\n *     it under the terms of the GNU Lesser General Public License as published by\n *     the Free Software Foundation, either version 3 of the License, or\n *     (at your option) any later version.\n *     \n *     PCMSolver is distributed in the hope that it will be useful,\n *     but WITHOUT ANY WARRANTY; without even the implied warranty of\n *     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n *     GNU Lesser General Public License for more details.\n *     \n *     You should have received a copy of the GNU Lesser General Public License\n *     along with PCMSolver.  If not, see <http://www.gnu.org/licenses/>.\n *     \n *     For information on the complete list of contributors to the\n *     PCMSolver API, see: <http://pcmsolver.readthedocs.io/>\n */\n/* pcmsolver_copyright_end */\n\n#ifndef INTERFACESIMPL_HPP\n#define INTERFACESIMPL_HPP\n\n#include <cmath>\n#include <fstream>\n#include <vector>\n\n#include \"Config.hpp\"\n\n#include <Eigen/Core>\n#include <boost/foreach.hpp>\n\n// Boost.Odeint includes\n#include <boost/numeric/odeint.hpp>\n\n#include \"utils/MathUtils.hpp\"\n\nnamespace interfaces {\n/*! \\typedef StateType\n *  \\brief state vector for the differential equation integrator\n */\ntypedef std::vector<double> StateType;\n\n/*! \\typedef ProfileEvaluator\n *  \\brief sort of a function pointer to the dielectric profile evaluation function\n */\ntypedef pcm::function< pcm::tuple<double, double>(const double) > ProfileEvaluator;\n\n/*! \\struct IntegratorParameters\n *  \\brief holds parameters for the integrator\n */\nstruct IntegratorParameters\n{\n    /*! Absolute tolerance level */\n    double eps_abs_     ;\n    /*! Relative tolerance level */\n    double eps_rel_     ;\n    /*! Weight of the state      */\n    double factor_x_    ;\n    /*! Weight of the state derivative */\n    double factor_dxdt_ ;\n    /*! Lower bound of the integration interval */\n    double r_0_         ;\n    /*! Upper bound of the integration interval */\n    double r_infinity_  ;\n    /*! Time step between observer calls */\n    double observer_step_;\n    IntegratorParameters(double e_abs, double e_rel, double f_x, double f_dxdt, double r0, double rinf, double step)\n        : eps_abs_(e_abs), eps_rel_(e_rel), factor_x_(f_x),\n        factor_dxdt_(f_dxdt), r_0_(r0), r_infinity_(rinf), observer_step_(step) {}\n};\n\n/*! \\class LnTransformedRadial\n *  \\brief system of ln-transformed first-order radial differential equations\n *  \\author Roberto Di Remigio\n *  \\date 2015\n *\n *  Provides a handle to the system of differential equations for the integrator.\n *  The dielectric profile comes in as a boost::function object.\n */\nclass LnTransformedRadial\n{\n    private:\n        /*! Dielectric profile function and derivative evaluation */\n        ProfileEvaluator eval_;\n        /*! Angular momentum */\n        int l_;\n    public:\n        /*! Constructor from profile evaluator and angular momentum */\n        LnTransformedRadial(const ProfileEvaluator & e, int lval) : eval_(e), l_(lval) {}\n        /*! Provides a functor for the evaluation of the system\n         *  of first-order ODEs needed by Boost.Odeint\n         *  The second-order ODE and the system of first-order ODEs\n         *  are reported in the manuscript.\n         *  \\param[in] rho state vector holding the function and its first derivative\n         *  \\param[out] drhodr state vector holding the first and second derivative\n         *  \\param[in] r position on the integration grid\n         */\n        void operator()(const StateType & rho, StateType & drhodr, const double r)\n        {\n            // Evaluate the dielectric profile\n            double eps = 0.0, epsPrime = 0.0;\n            pcm::tie(eps, epsPrime) = eval_(r);\n            if (numericalZero(eps)) throw std::domain_error(\"Division by zero!\");\n            double gamma_epsilon = epsPrime / eps;\n            // System of equations is defined here\n            drhodr[0] = rho[1];\n            drhodr[1] = -rho[1] * (rho[1] + 2.0/r + gamma_epsilon) + l_ * (l_ + 1) / std::pow(r, 2);\n        }\n};\n} // namespace interfaces\n\nusing interfaces::ProfileEvaluator;\nusing interfaces::IntegratorParameters;\n\n/*! \\file InterfacesImpl.hpp\n *  \\class RadialFunction\n *  \\brief represents solutions to the radial 2nd order ODE\n *  \\author Roberto Di Remigio\n *  \\date 2015\n *  \\tparam StateVariable type of the state variable used in the ODE solver\n *  \\tparam ODESystem system of 1st order ODEs replacing the 2nd order ODE\n *  \\tparam IndependentSolution encodes which type of radial solution\n */\ntemplate <typename StateVariable,\n          typename ODESystem,\n          template <typename, typename> class IndependentSolution>\nclass RadialFunction __final\n{\n    public:\n        RadialFunction() : solution_(IndependentSolution<StateVariable, ODESystem>()) {}\n        RadialFunction(int l, double r0, double rinf, const ProfileEvaluator & eval, const IntegratorParameters & parms)\n            : solution_(IndependentSolution<StateVariable, ODESystem>(l, r0, rinf, eval, parms)) {}\n        ~RadialFunction() {}\n        /*! \\brief Returns value of function and its first derivative at given point\n         *  \\param[in] point evaluation point\n         */\n        pcm::tuple<double, double> operator()(double point) const {\n            return solution_(point);\n        }\n        friend std::ostream & operator<<(std::ostream &os, RadialFunction & obj) {\n            os << obj.solution_;\n            return os;\n        }\n    private:\n        /// Independent solution to the radial equation\n        IndependentSolution<StateVariable, ODESystem> solution_;\n};\n\n/*! \\file InterfacesImpl.hpp\n *  \\class Zeta\n *  \\brief 1st solution to the radial second order ODE, with r^l behaviour in the origin\n *  \\author Roberto Di Remigio\n *  \\date 2015\n *  \\tparam StateVariable type of the state variable used in the ODE solver\n *  \\tparam ODESystem system of 1st order ODEs replacing the 2nd order ODE\n */\ntemplate <typename StateVariable,\n          typename ODESystem>\nclass Zeta __final\n{\n    public:\n        Zeta() : L_(0), r_0_(0.0), r_infinity_(0.0) {}\n        Zeta(int l, double r0, double rinf, const ProfileEvaluator & eval, const IntegratorParameters & parms)\n            : L_(l), r_0_(r0), r_infinity_(rinf) { compute(eval, parms); }\n        ~Zeta() {}\n        pcm::tuple<double, double> operator()(double point) const {\n            return pcm::make_tuple(function_impl(point), derivative_impl(point));\n        }\n        friend std::ostream & operator<<(std::ostream &os, Zeta & obj) {\n            for (size_t i = 0; i < obj.function_[0].size(); ++i) {\n                os << obj.function_[0][i] << \"    \"\n                   << obj.function_[1][i] << \"    \"\n                   << obj.function_[2][i] << std::endl;\n            }\n            return os;\n        }\n    private:\n        typedef pcm::array<StateVariable, 3> RadialSolution;\n        /// Angular momentum of the solution\n        int L_;\n        /// Lower bound of the integration interval\n        double r_0_;\n        /// Upper bound of the integration interval\n        double r_infinity_;\n        /// The actual data: grid, function value and first derivative values\n        RadialSolution function_;\n        /*! Reports progress of differential equation integrator */\n        void push_back(const StateVariable & x, double r) {\n            function_[0].push_back(r);\n            function_[1].push_back(x[0]);\n            function_[2].push_back(x[1]);\n        }\n        /*! \\brief Calculates 1st radial solution, i.e. the one with r^l behavior\n         *  \\param[in] eval   dielectric profile evaluator function object\n         *  \\param[in] parms parameters for the integrator\n         */\n        void compute(const ProfileEvaluator & eval, const IntegratorParameters & parms) {\n            namespace odeint = boost::numeric::odeint;\n            odeint::bulirsch_stoer_dense_out<StateVariable> stepper(parms.eps_abs_, parms.eps_rel_, parms.factor_x_, parms.factor_dxdt_);\n            ODESystem system(eval, L_);\n            // Holds the initial conditions\n            StateVariable init_zeta(2);\n            // Set initial conditions\n            init_zeta[0] = L_ * std::log(r_0_);\n            init_zeta[1] = L_ / r_0_;\n            odeint::integrate_adaptive(stepper, system, init_zeta,\n                    r_0_, r_infinity_, parms.observer_step_,\n                    pcm::bind(&Zeta<StateVariable, ODESystem>::push_back, this, pcm::_1, pcm::_2));\n        }\n        /*! \\brief Returns value of function at given point\n         *  \\param[in] point evaluation point\n         *\n         *  We first check if point is below r_0_, if yes we use\n         *  the asymptotic form L*log(r) in point.\n         */\n        double function_impl(double point) const {\n            double zeta = 0.0;\n            if (point <= r_0_) {\n                zeta = L_ * std::log(point);\n            } else {\n                zeta = splineInterpolation(point, function_[0], function_[1]);\n            }\n            return zeta;\n        }\n        /*! \\brief Returns value of 1st derivative of function at given point\n         *  \\param[in] point evaluation point\n         *\n         *  We first check if point is below r_0_, if yes we use\n         *  the asymptotic form L / r in point.\n         */\n        double derivative_impl(double point) const {\n            double zeta = 0.0;\n            if (point <= r_0_) {\n                zeta = L_ / point;\n            } else {\n                zeta = splineInterpolation(point, function_[0], function_[2]);\n            }\n            return zeta;\n        }\n};\n\n/*! \\file InterfacesImpl.hpp\n *  \\class Omega\n *  \\brief 2nd solution to the radial second order ODE, with r^(-l-1) behaviour at infinity\n *  \\author Roberto Di Remigio\n *  \\date 2015\n *  \\tparam StateVariable type of the state variable used in the ODE solver\n *  \\tparam ODESystem system of 1st order ODEs replacing the 2nd order ODE\n */\ntemplate <typename StateVariable,\n          typename ODESystem>\nclass Omega __final\n{\n    public:\n        Omega() : L_(0), r_0_(0.0), r_infinity_(0.0) {}\n        Omega(int l, double r0, double rinf, const ProfileEvaluator & eval, const IntegratorParameters & parms)\n            : L_(l), r_0_(r0), r_infinity_(rinf) { compute(eval, parms); }\n        ~Omega() {}\n        pcm::tuple<double, double> operator()(double point) const {\n            return pcm::make_tuple(function_impl(point), derivative_impl(point));\n        }\n        friend std::ostream & operator<<(std::ostream &os, Omega & obj) {\n            for (size_t i = 0; i < obj.function_[0].size(); ++i) {\n                os << obj.function_[0][i] << \"    \"\n                   << obj.function_[1][i] << \"    \"\n                   << obj.function_[2][i] << std::endl;\n            }\n            return os;\n        }\n    private:\n        typedef pcm::array<StateVariable, 3> RadialSolution;\n        /// Angular momentum of the solution\n        int L_;\n        /// Lower bound of the integration interval\n        double r_0_;\n        /// Upper bound of the integration interval\n        double r_infinity_;\n        /// The actual data: grid, function value and first derivative values\n        RadialSolution function_;\n        /*! Reports progress of differential equation integrator */\n        void push_back(const StateVariable & x, double r) {\n            function_[0].push_back(r);\n            function_[1].push_back(x[0]);\n            function_[2].push_back(x[1]);\n        }\n        /*! \\brief calculates 2nd radial solution, i.e. the one with r^(-l-1) behavior\n         *  \\param[in] eval   dielectric profile evaluator function object\n         *  \\param[in] parms parameters for the integrator\n         */\n        void compute(const ProfileEvaluator & eval, const IntegratorParameters & parms) {\n            namespace odeint = boost::numeric::odeint;\n            odeint::bulirsch_stoer_dense_out<StateVariable> stepper(parms.eps_abs_, parms.eps_rel_, parms.factor_x_, parms.factor_dxdt_);\n            ODESystem system(eval, L_);\n            // Holds the initial conditions\n            StateVariable init_omega(2);\n            // Set initial conditions\n            init_omega[0] = -(L_ + 1) * std::log(r_infinity_);\n            init_omega[1] = -(L_ + 1) / r_infinity_;\n            // Notice that we integrate BACKWARDS, so we pass -step to integrate_adaptive\n            boost::numeric::odeint::integrate_adaptive(stepper, system, init_omega,\n                    r_infinity_, r_0_, -parms.observer_step_,\n                    pcm::bind(&Omega<StateVariable, ODESystem>::push_back, this, pcm::_1, pcm::_2));\n            // Reverse order of StateVariable-s in RadialSolution\n            // this ensures that they are in ascending order, as later expected by function_impl and derivative_impl\n            BOOST_FOREACH(StateVariable & comp, function_) {\n                std::reverse(comp.begin(), comp.end());\n            }\n        }\n        /*! \\brief Returns value of function at given point\n         *  \\param[in] point evaluation point\n         *\n         * We first check if point is above r_infinity_, if yes we use\n         * the asymptotic form -(L+1)*log(r) in point.\n         */\n        double function_impl(double point) const {\n            double omega = 0.0;\n            if (point >= r_infinity_) {\n                omega = -(L_ + 1) * std::log(point);\n            } else {\n                omega = splineInterpolation(point, function_[0], function_[1]);\n            }\n            return omega;\n        }\n        /*! \\brief Returns value of 1st derivative of function at given point\n         *  \\param[in] point evaluation point\n         *\n         * We first check if point is above r_infinity_, if yes we use\n         * the asymptotic form -(L+1)/r in point.\n         */\n        double derivative_impl(double point) const {\n            double omega = 0.0;\n            if (point >= r_infinity_) {\n                omega = -(L_ + 1) / point;\n            } else {\n                omega = splineInterpolation(point, function_[0], function_[2]);\n            }\n            return omega;\n        }\n};\n\n/*! \\brief Write contents of a RadialFunction to file\n *  \\param[in] f RadialSolution whose contents have to be printed\n *  \\param[in] fname name of the file\n *  \\author Roberto Di Remigio\n *  \\date 2015\n *  \\tparam StateVariable type of the state variable used in the ODE solver\n *  \\tparam ODESystem system of 1st order ODEs replacing the 2nd order ODE\n *  \\tparam IndependentSolution encodes which type of radial solution\n */\ntemplate <typename StateVariable,\n          typename ODESystem,\n          template <typename, typename> class IndependentSolution>\nvoid writeToFile(RadialFunction<StateVariable, ODESystem, IndependentSolution> & f, const std::string & fname) {\n    std::ofstream fout;\n    fout.open(fname.c_str());\n    fout << f << std::endl;\n    fout.close();\n}\n\n#endif // INTERFACESIMPL_HPP\n", "meta": {"hexsha": "9b522a81d12617ef2fcff52e446902ea2195fa05", "size": 15141, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "external/PCMSolver/PCMSolver-source/src/green/InterfacesImpl.hpp", "max_stars_repo_name": "robertodr/externalize", "max_stars_repo_head_hexsha": "c7b1dda2009dab329a6efb580c57ef8e1494cf3b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2017-02-15T22:16:34.000Z", "max_stars_repo_stars_event_max_datetime": "2017-02-15T22:16:34.000Z", "max_issues_repo_path": "external/PCMSolver/PCMSolver-source/src/green/InterfacesImpl.hpp", "max_issues_repo_name": "robertodr/externalize", "max_issues_repo_head_hexsha": "c7b1dda2009dab329a6efb580c57ef8e1494cf3b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "external/PCMSolver/PCMSolver-source/src/green/InterfacesImpl.hpp", "max_forks_repo_name": "robertodr/externalize", "max_forks_repo_head_hexsha": "c7b1dda2009dab329a6efb580c57ef8e1494cf3b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.2561307902, "max_line_length": 137, "alphanum_fraction": 0.6197080774, "num_tokens": 3646, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6791787121629465, "lm_q2_score": 0.5039061705290806, "lm_q1q2_score": 0.342242343950903}}
{"text": "// Boost.Geometry - gis-projections (based on PROJ4)\r\n\r\n// Copyright (c) 2008-2015 Barend Gehrels, Amsterdam, the Netherlands.\r\n\r\n// This file was modified by Oracle on 2017, 2018.\r\n// Modifications copyright (c) 2017-2018, Oracle and/or its affiliates.\r\n// Contributed and/or modified by Adam Wulkiewicz, on behalf of Oracle.\r\n\r\n// Use, modification and distribution is subject to the Boost Software License,\r\n// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\r\n// http://www.boost.org/LICENSE_1_0.txt)\r\n\r\n// This file is converted from PROJ4, http://trac.osgeo.org/proj\r\n// PROJ4 is originally written by Gerald Evenden (then of the USGS)\r\n// PROJ4 is maintained by Frank Warmerdam\r\n// PROJ4 is converted to Boost.Geometry by Barend Gehrels\r\n\r\n// Last updated version of proj: 5.0.0\r\n\r\n// Original copyright notice:\r\n\r\n// Copyright (c) 2008   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/* The code in this file is largly based upon procedures:\r\n *\r\n * Written by: Knud Poder and Karsten Engsager\r\n *\r\n * Based on math from: R.Koenig and K.H. Weise, \"Mathematische\r\n * Grundlagen der hoeheren Geodaesie und Kartographie,\r\n * Springer-Verlag, Berlin/Goettingen\" Heidelberg, 1951.\r\n *\r\n * Modified and used here by permission of Reference Networks\r\n * Division, Kort og Matrikelstyrelsen (KMS), Copenhagen, Denmark\r\n*/\r\n\r\n#ifndef BOOST_GEOMETRY_PROJECTIONS_ETMERC_HPP\r\n#define BOOST_GEOMETRY_PROJECTIONS_ETMERC_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/function_overloads.hpp>\r\n#include <boost/geometry/srs/projections/impl/pj_param.hpp>\r\n#include <boost/geometry/srs/projections/impl/projects.hpp>\r\n\r\n#include <boost/math/special_functions/hypot.hpp>\r\n\r\nnamespace boost { namespace geometry\r\n{\r\n\r\nnamespace projections\r\n{\r\n    #ifndef DOXYGEN_NO_DETAIL\r\n    namespace detail { namespace etmerc\r\n    {\r\n\r\n            static const int PROJ_ETMERC_ORDER = 6;\r\n\r\n            template <typename T>\r\n            struct par_etmerc\r\n            {\r\n                T    Qn;    /* Merid. quad., scaled to the projection */\r\n                T    Zb;    /* Radius vector in polar coord. systems  */\r\n                T    cgb[6]; /* Constants for Gauss -> Geo lat */\r\n                T    cbg[6]; /* Constants for Geo lat -> Gauss */\r\n                T    utg[6]; /* Constants for transv. merc. -> geo */\r\n                T    gtu[6]; /* Constants for geo -> transv. merc. */\r\n            };\r\n\r\n            template <typename T>\r\n            inline T log1py(T const& x) {              /* Compute log(1+x) accurately */\r\n                volatile T\r\n                  y = 1 + x,\r\n                  z = y - 1;\r\n                /* Here's the explanation for this magic: y = 1 + z, exactly, and z\r\n                 * approx x, thus log(y)/z (which is nearly constant near z = 0) returns\r\n                 * a good approximation to the true log(1 + x)/x.  The multiplication x *\r\n                 * (log(y)/z) introduces little additional error. */\r\n                return z == 0 ? x : x * log(y) / z;\r\n            }\r\n\r\n            template <typename T>\r\n            inline T asinhy(T const& x) {              /* Compute asinh(x) accurately */\r\n                T y = fabs(x);         /* Enforce odd parity */\r\n                y = log1py(y * (1 + y/(boost::math::hypot(1.0, y) + 1)));\r\n                return x < 0 ? -y : y;\r\n            }\r\n\r\n            template <typename T>\r\n            inline T gatg(const T *p1, int len_p1, T const& B) {\r\n                const T *p;\r\n                T h = 0, h1, h2 = 0, cos_2B;\r\n\r\n                cos_2B = 2*cos(2*B);\r\n                for (p = p1 + len_p1, h1 = *--p; p - p1; h2 = h1, h1 = h)\r\n                    h = -h2 + cos_2B*h1 + *--p;\r\n                return (B + h*sin(2*B));\r\n            }\r\n\r\n            /* Complex Clenshaw summation */\r\n            template <typename T>\r\n            inline T clenS(const T *a, int size, T const& arg_r, T const& arg_i, T *R, T *I) {\r\n                T      r, i, hr, hr1, hr2, hi, hi1, hi2;\r\n                T      sin_arg_r, cos_arg_r, sinh_arg_i, cosh_arg_i;\r\n\r\n                /* arguments */\r\n                const T* p = a + size;\r\n                sin_arg_r  = sin(arg_r);\r\n                cos_arg_r  = cos(arg_r);\r\n                sinh_arg_i = sinh(arg_i);\r\n                cosh_arg_i = cosh(arg_i);\r\n                r          =  2*cos_arg_r*cosh_arg_i;\r\n                i          = -2*sin_arg_r*sinh_arg_i;\r\n                /* summation loop */\r\n                for (hi1 = hr1 = hi = 0, hr = *--p; a - p;) {\r\n                    hr2 = hr1;\r\n                    hi2 = hi1;\r\n                    hr1 = hr;\r\n                    hi1 = hi;\r\n                    hr  = -hr2 + r*hr1 - i*hi1 + *--p;\r\n                    hi  = -hi2 + i*hr1 + r*hi1;\r\n                }\r\n                r   = sin_arg_r*cosh_arg_i;\r\n                i   = cos_arg_r*sinh_arg_i;\r\n                *R  = r*hr - i*hi;\r\n                *I  = r*hi + i*hr;\r\n                return(*R);\r\n            }\r\n\r\n            /* Real Clenshaw summation */\r\n            template <typename T>\r\n            inline T clens(const T *a, int size, T const& arg_r) {\r\n                T      r, hr, hr1, hr2, cos_arg_r;\r\n\r\n                const T* p = a + size;\r\n                cos_arg_r  = cos(arg_r);\r\n                r          =  2*cos_arg_r;\r\n\r\n                /* summation loop */\r\n                for (hr1 = 0, hr = *--p; a - p;) {\r\n                    hr2 = hr1;\r\n                    hr1 = hr;\r\n                    hr  = -hr2 + r*hr1 + *--p;\r\n                }\r\n                return(sin(arg_r)*hr);\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_etmerc_ellipsoid\r\n                : public base_t_fi<base_etmerc_ellipsoid<T, Parameters>, T, Parameters>\r\n            {\r\n                par_etmerc<T> m_proj_parm;\r\n\r\n                inline base_etmerc_ellipsoid(const Parameters& par)\r\n                    : base_t_fi<base_etmerc_ellipsoid<T, Parameters>, T, Parameters>(*this, par)\r\n                {}\r\n\r\n                // FORWARD(e_forward)  ellipsoid\r\n                // Project coordinates from geographic (lon, lat) to cartesian (x, y)\r\n                inline void fwd(T const& lp_lon, T const& lp_lat, T& xy_x, T& xy_y) const\r\n                {\r\n                    T sin_Cn, cos_Cn, cos_Ce, sin_Ce, dCn, dCe;\r\n                    T Cn = lp_lat, Ce = lp_lon;\r\n\r\n                    /* ell. LAT, LNG -> Gaussian LAT, LNG */\r\n                    Cn  = gatg(this->m_proj_parm.cbg, PROJ_ETMERC_ORDER, Cn);\r\n                    /* Gaussian LAT, LNG -> compl. sph. LAT */\r\n                    sin_Cn = sin(Cn);\r\n                    cos_Cn = cos(Cn);\r\n                    sin_Ce = sin(Ce);\r\n                    cos_Ce = cos(Ce);\r\n\r\n                    Cn     = atan2(sin_Cn, cos_Ce*cos_Cn);\r\n                    Ce     = atan2(sin_Ce*cos_Cn, boost::math::hypot(sin_Cn, cos_Cn*cos_Ce));\r\n\r\n                    /* compl. sph. N, E -> ell. norm. N, E */\r\n                    Ce  = asinhy(tan(Ce));     /* Replaces: Ce  = log(tan(fourth_pi + Ce*0.5)); */\r\n                    Cn += clenS(this->m_proj_parm.gtu, PROJ_ETMERC_ORDER, 2*Cn, 2*Ce, &dCn, &dCe);\r\n                    Ce += dCe;\r\n                    if (fabs(Ce) <= 2.623395162778) {\r\n                        xy_y  = this->m_proj_parm.Qn * Cn + this->m_proj_parm.Zb;  /* Northing */\r\n                        xy_x  = this->m_proj_parm.Qn * Ce;  /* Easting  */\r\n                    } else\r\n                        xy_x = xy_y = HUGE_VAL;\r\n                }\r\n\r\n                // INVERSE(e_inverse)  ellipsoid\r\n                // Project coordinates from cartesian (x, y) to geographic (lon, lat)\r\n                inline void inv(T const& xy_x, T const& xy_y, T& lp_lon, T& lp_lat) const\r\n                {\r\n                    T sin_Cn, cos_Cn, cos_Ce, sin_Ce, dCn, dCe;\r\n                    T Cn = xy_y, Ce = xy_x;\r\n\r\n                    /* normalize N, E */\r\n                    Cn = (Cn - this->m_proj_parm.Zb)/this->m_proj_parm.Qn;\r\n                    Ce = Ce/this->m_proj_parm.Qn;\r\n\r\n                    if (fabs(Ce) <= 2.623395162778) { /* 150 degrees */\r\n                        /* norm. N, E -> compl. sph. LAT, LNG */\r\n                        Cn += clenS(this->m_proj_parm.utg, PROJ_ETMERC_ORDER, 2*Cn, 2*Ce, &dCn, &dCe);\r\n                        Ce += dCe;\r\n                        Ce = atan(sinh(Ce)); /* Replaces: Ce = 2*(atan(exp(Ce)) - fourth_pi); */\r\n                        /* compl. sph. LAT -> Gaussian LAT, LNG */\r\n                        sin_Cn = sin(Cn);\r\n                        cos_Cn = cos(Cn);\r\n                        sin_Ce = sin(Ce);\r\n                        cos_Ce = cos(Ce);\r\n                        Ce     = atan2(sin_Ce, cos_Ce*cos_Cn);\r\n                        Cn     = atan2(sin_Cn*cos_Ce, boost::math::hypot(sin_Ce, cos_Ce*cos_Cn));\r\n                        /* Gaussian LAT, LNG -> ell. LAT, LNG */\r\n                        lp_lat = gatg(this->m_proj_parm.cgb,  PROJ_ETMERC_ORDER, Cn);\r\n                        lp_lon = Ce;\r\n                    }\r\n                    else\r\n                        lp_lat = lp_lon = HUGE_VAL;\r\n                }\r\n\r\n                static inline std::string get_name()\r\n                {\r\n                    return \"etmerc_ellipsoid\";\r\n                }\r\n\r\n            };\r\n\r\n            template <typename Parameters, typename T>\r\n            inline void setup(Parameters& par, par_etmerc<T>& proj_parm)\r\n            {\r\n                T f, n, np, Z;\r\n\r\n                if (par.es <= 0) {\r\n                    BOOST_THROW_EXCEPTION( projection_exception(error_ellipsoid_use_required) );\r\n                }\r\n\r\n                f = par.es / (1 + sqrt(1 -  par.es)); /* Replaces: f = 1 - sqrt(1-par.es); */\r\n\r\n                /* third flattening */\r\n                np = n = f/(2 - f);\r\n\r\n                /* COEF. OF TRIG SERIES GEO <-> GAUSS */\r\n                /* cgb := Gaussian -> Geodetic, KW p190 - 191 (61) - (62) */\r\n                /* cbg := Geodetic -> Gaussian, KW p186 - 187 (51) - (52) */\r\n                /* PROJ_ETMERC_ORDER = 6th degree : Engsager and Poder: ICC2007 */\r\n\r\n                proj_parm.cgb[0] = n*( 2 + n*(-2/3.0  + n*(-2      + n*(116/45.0 + n*(26/45.0 +\r\n                            n*(-2854/675.0 ))))));\r\n                proj_parm.cbg[0] = n*(-2 + n*( 2/3.0  + n*( 4/3.0  + n*(-82/45.0 + n*(32/45.0 +\r\n                            n*( 4642/4725.0))))));\r\n                np     *= n;\r\n                proj_parm.cgb[1] = np*(7/3.0 + n*( -8/5.0  + n*(-227/45.0 + n*(2704/315.0 +\r\n                            n*( 2323/945.0)))));\r\n                proj_parm.cbg[1] = np*(5/3.0 + n*(-16/15.0 + n*( -13/9.0  + n*( 904/315.0 +\r\n                            n*(-1522/945.0)))));\r\n                np     *= n;\r\n                /* n^5 coeff corrected from 1262/105 -> -1262/105 */\r\n                proj_parm.cgb[2] = np*( 56/15.0  + n*(-136/35.0 + n*(-1262/105.0 +\r\n                            n*( 73814/2835.0))));\r\n                proj_parm.cbg[2] = np*(-26/15.0  + n*(  34/21.0 + n*(    8/5.0   +\r\n                            n*(-12686/2835.0))));\r\n                np     *= n;\r\n                /* n^5 coeff corrected from 322/35 -> 332/35 */\r\n                proj_parm.cgb[3] = np*(4279/630.0 + n*(-332/35.0 + n*(-399572/14175.0)));\r\n                proj_parm.cbg[3] = np*(1237/630.0 + n*( -12/5.0  + n*( -24832/14175.0)));\r\n                np     *= n;\r\n                proj_parm.cgb[4] = np*(4174/315.0 + n*(-144838/6237.0 ));\r\n                proj_parm.cbg[4] = np*(-734/315.0 + n*( 109598/31185.0));\r\n                np     *= n;\r\n                proj_parm.cgb[5] = np*(601676/22275.0 );\r\n                proj_parm.cbg[5] = np*(444337/155925.0);\r\n\r\n                /* Constants of the projections */\r\n                /* Transverse Mercator (UTM, ITM, etc) */\r\n                np = n*n;\r\n                /* Norm. mer. quad, K&W p.50 (96), p.19 (38b), p.5 (2) */\r\n                proj_parm.Qn = par.k0/(1 + n) * (1 + np*(1/4.0 + np*(1/64.0 + np/256.0)));\r\n                /* coef of trig series */\r\n                /* utg := ell. N, E -> sph. N, E,  KW p194 (65) */\r\n                /* gtu := sph. N, E -> ell. N, E,  KW p196 (69) */\r\n                proj_parm.utg[0] = n*(-0.5  + n*( 2/3.0 + n*(-37/96.0 + n*( 1/360.0 +\r\n                            n*(  81/512.0 + n*(-96199/604800.0))))));\r\n                proj_parm.gtu[0] = n*( 0.5  + n*(-2/3.0 + n*(  5/16.0 + n*(41/180.0 +\r\n                            n*(-127/288.0 + n*(  7891/37800.0 ))))));\r\n                proj_parm.utg[1] = np*(-1/48.0 + n*(-1/15.0 + n*(437/1440.0 + n*(-46/105.0 +\r\n                            n*( 1118711/3870720.0)))));\r\n                proj_parm.gtu[1] = np*(13/48.0 + n*(-3/5.0  + n*(557/1440.0 + n*(281/630.0 +\r\n                            n*(-1983433/1935360.0)))));\r\n                np      *= n;\r\n                proj_parm.utg[2] = np*(-17/480.0 + n*(  37/840.0 + n*(  209/4480.0  +\r\n                            n*( -5569/90720.0 ))));\r\n                proj_parm.gtu[2] = np*( 61/240.0 + n*(-103/140.0 + n*(15061/26880.0 +\r\n                            n*(167603/181440.0))));\r\n                np      *= n;\r\n                proj_parm.utg[3] = np*(-4397/161280.0 + n*(  11/504.0 + n*( 830251/7257600.0)));\r\n                proj_parm.gtu[3] = np*(49561/161280.0 + n*(-179/168.0 + n*(6601661/7257600.0)));\r\n                np     *= n;\r\n                proj_parm.utg[4] = np*(-4583/161280.0 + n*(  108847/3991680.0));\r\n                proj_parm.gtu[4] = np*(34729/80640.0  + n*(-3418889/1995840.0));\r\n                np     *= n;\r\n                proj_parm.utg[5] = np*(-20648693/638668800.0);\r\n                proj_parm.gtu[5] = np*(212378941/319334400.0);\r\n\r\n                /* Gaussian latitude value of the origin latitude */\r\n                Z = gatg(proj_parm.cbg, PROJ_ETMERC_ORDER, par.phi0);\r\n\r\n                /* Origin northing minus true northing at the origin latitude */\r\n                /* i.e. true northing = N - proj_parm.Zb                         */\r\n                proj_parm.Zb  = - proj_parm.Qn*(Z + clens(proj_parm.gtu, PROJ_ETMERC_ORDER, 2*Z));\r\n            }\r\n\r\n            // Extended Transverse Mercator\r\n            template <typename Parameters, typename T>\r\n            inline void setup_etmerc(Parameters& par, par_etmerc<T>& proj_parm)\r\n            {\r\n                setup(par, proj_parm);\r\n            }\r\n\r\n            // Universal Transverse Mercator (UTM)\r\n            template <typename Params, typename Parameters, typename T>\r\n            inline void setup_utm(Params const& params, Parameters& par, par_etmerc<T>& proj_parm)\r\n            {\r\n                static const T pi = detail::pi<T>();\r\n\r\n                int zone;\r\n\r\n                if (par.es == 0.0) {\r\n                    BOOST_THROW_EXCEPTION( projection_exception(error_ellipsoid_use_required) );\r\n                }\r\n\r\n                par.y0 = pj_get_param_b<srs::spar::south>(params, \"south\", srs::dpar::south) ? 10000000. : 0.;\r\n                par.x0 = 500000.;\r\n                if (pj_param_i<srs::spar::zone>(params, \"zone\", srs::dpar::zone, zone)) /* zone input ? */\r\n                {\r\n                    if (zone > 0 && zone <= 60)\r\n                        --zone;\r\n                    else {\r\n                        BOOST_THROW_EXCEPTION( projection_exception(error_invalid_utm_zone) );\r\n                    }\r\n                }\r\n                else /* nearest central meridian input */\r\n                {\r\n                    zone = int_floor((adjlon(par.lam0) + pi) * 30. / pi);\r\n                    if (zone < 0)\r\n                        zone = 0;\r\n                    else if (zone >= 60)\r\n                        zone = 59;\r\n                }\r\n                par.lam0 = (zone + .5) * pi / 30. - pi;\r\n                par.k0 = 0.9996;\r\n                par.phi0 = 0.;\r\n\r\n                setup(par, proj_parm);\r\n            }\r\n\r\n    }} // namespace detail::etmerc\r\n    #endif // doxygen\r\n\r\n    /*!\r\n        \\brief Extended 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        \\par Projection parameters\r\n         - lat_ts: Latitude of true scale\r\n         - lat_0: Latitude of origin\r\n        \\par Example\r\n        \\image html ex_etmerc.gif\r\n    */\r\n    template <typename T, typename Parameters>\r\n    struct etmerc_ellipsoid : public detail::etmerc::base_etmerc_ellipsoid<T, Parameters>\r\n    {\r\n        template <typename Params>\r\n        inline etmerc_ellipsoid(Params const& , Parameters const& par)\r\n            : detail::etmerc::base_etmerc_ellipsoid<T, Parameters>(par)\r\n        {\r\n            detail::etmerc::setup_etmerc(this->m_par, this->m_proj_parm);\r\n        }\r\n    };\r\n\r\n    /*!\r\n        \\brief Universal Transverse Mercator (UTM) 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         - zone: UTM Zone (integer)\r\n         - south: Denotes southern hemisphere UTM zone (boolean)\r\n        \\par Example\r\n        \\image html ex_utm.gif\r\n    */\r\n    template <typename T, typename Parameters>\r\n    struct utm_ellipsoid : public detail::etmerc::base_etmerc_ellipsoid<T, Parameters>\r\n    {\r\n        template <typename Params>\r\n        inline utm_ellipsoid(Params const& params, Parameters const& par)\r\n            : detail::etmerc::base_etmerc_ellipsoid<T, Parameters>(par)\r\n        {\r\n            detail::etmerc::setup_utm(params, this->m_par, this->m_proj_parm);\r\n        }\r\n    };\r\n\r\n    #ifndef DOXYGEN_NO_DETAIL\r\n    namespace detail\r\n    {\r\n\r\n        // Static projection\r\n        BOOST_GEOMETRY_PROJECTIONS_DETAIL_STATIC_PROJECTION(srs::spar::proj_etmerc, etmerc_ellipsoid, etmerc_ellipsoid)\r\n        BOOST_GEOMETRY_PROJECTIONS_DETAIL_STATIC_PROJECTION(srs::spar::proj_utm, utm_ellipsoid, utm_ellipsoid)\r\n\r\n        // Factory entry(s)\r\n        BOOST_GEOMETRY_PROJECTIONS_DETAIL_FACTORY_ENTRY_FI(etmerc_entry, etmerc_ellipsoid)\r\n        BOOST_GEOMETRY_PROJECTIONS_DETAIL_FACTORY_ENTRY_FI(utm_entry, utm_ellipsoid)\r\n        \r\n        BOOST_GEOMETRY_PROJECTIONS_DETAIL_FACTORY_INIT_BEGIN(etmerc_init)\r\n        {\r\n            BOOST_GEOMETRY_PROJECTIONS_DETAIL_FACTORY_INIT_ENTRY(etmerc, etmerc_entry);\r\n            BOOST_GEOMETRY_PROJECTIONS_DETAIL_FACTORY_INIT_ENTRY(utm, utm_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_ETMERC_HPP\r\n\r\n", "meta": {"hexsha": "28b1da8294b97fac4745b5d6fe566fc7ddc4081a", "size": 20142, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "dep/win/include/boost/geometry/srs/projections/proj/etmerc.hpp", "max_stars_repo_name": "Netis/packet-agent", "max_stars_repo_head_hexsha": "70da3479051a07e3c235abe7516990f9fd21a18a", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 995.0, "max_stars_repo_stars_event_min_datetime": "2018-06-22T10:39:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T01:22:14.000Z", "max_issues_repo_path": "dep/win/include/boost/geometry/srs/projections/proj/etmerc.hpp", "max_issues_repo_name": "Netis/packet-agent", "max_issues_repo_head_hexsha": "70da3479051a07e3c235abe7516990f9fd21a18a", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 32.0, "max_issues_repo_issues_event_min_datetime": "2018-06-23T14:19:37.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-29T10:20:37.000Z", "max_forks_repo_path": "dep/win/include/boost/geometry/srs/projections/proj/etmerc.hpp", "max_forks_repo_name": "Netis/packet-agent", "max_forks_repo_head_hexsha": "70da3479051a07e3c235abe7516990f9fd21a18a", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 172.0, "max_forks_repo_forks_event_min_datetime": "2018-06-22T11:12:00.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-29T07:44:33.000Z", "avg_line_length": 44.3656387665, "max_line_length": 120, "alphanum_fraction": 0.4906662695, "num_tokens": 5291, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.679178699175393, "lm_q2_score": 0.5039061705290805, "lm_q1q2_score": 0.34224233740639465}}
{"text": "\r\n#include <algorithm>\r\n#include <GsTLAppli/geostat/parameters_handler.h>\r\n#include <GsTLAppli/geostat/utilities.h>\r\n#include <GsTLAppli/utils/gstl_messages.h>\r\n#include <GsTLAppli/utils/error_messages_handler.h>\r\n#include <GsTLAppli/utils/string_manipulation.h>\r\n#include <GsTLAppli/grid/grid_model/geostat_grid.h>\r\n#include <GsTLAppli/grid/grid_model/combined_neighborhood.h>\r\n#include <GsTLAppli/grid/grid_model/gval_iterator.h>\r\n#include <GsTLAppli/grid/grid_model/cartesian_grid.h>\r\n#include <GsTLAppli/grid/grid_model/point_set.h>\r\n#include <GsTLAppli/appli/manager_repository.h>\r\n#include <GsTLAppli/math/random_numbers.h>\r\n#include <GsTLAppli/appli/utilities.h>\r\n\r\n#include <GsTL/sampler/monte_carlo_sampler.h>\r\n#include <GsTL/simulation/sequential_simulation.h>\r\n\r\n\r\n//TESTING BEGIN\r\n#include <GsTL/cdf/gaussian_cdf.h>\r\n#include <GsTL/sampler/monte_carlo_sampler.h>\r\n#include <GsTL/cdf_estimator/gaussian_cdf_Kestimator.h>\r\n#include <GsTL/simulation/sequential_simulation.h>\r\n#include <GsTL/univariate_stats/cdf_transform.h>\r\n#include <GsTL/univariate_stats/build_cdf.h>\r\n//TESTING END\r\n\r\n#include <GsTLAppli/grid/grid_model/point_set_neighborhood.h>\r\n\r\n#include <iterator>\r\n#include <vector>\r\n#include <algorithm>\r\n#include <fstream>\r\n\r\n#include <GsTLAppli/grid/grid_model/reduced_grid.h>\r\n\r\n\r\n#include <boost/math/tools/roots.hpp>\r\n#include <boost/function.hpp>\r\n#include <boost/bind.hpp>\r\n#include <boost/math/special_functions/legendre.hpp>\r\n#include <boost/algorithm/minmax_element.hpp>\r\n#include <boost/math/distributions/normal.hpp>\r\n\r\n\r\n#include <qstring.h>\r\n#include <qfile.h>\r\n\r\n#include <qfiledialog.h>\r\n#include <GsTLAppli/appli/project.h>\r\n#include <GsTLAppli/utils/gstl_plugins.h>\r\n\r\n#include \"kernelsim.h\"\r\n\r\nkernelsim::kernelsim()\r\n{\r\n\tsimul_grid_ = 0;\r\n\tharddata_grid_ = 0;\r\n\ttraining_image_ = 0;\r\n\ttraining_property_ = 0;\r\n\tharddata_property_ = 0;\r\n\tassign_harddata_ = false;\r\n\tneighborhood_ = 0;\r\n\tmultireal_property_ = 0;\r\n\thard_data_ti_ = 0;\r\n\r\n\ttemporary_harddata_property_ = 0;\r\n\ttemporary_training_property_ = 0;\r\n\r\n}\r\n\r\nkernelsim::~kernelsim()\r\n{\r\n\tclean();\r\n}\r\n\r\n//intialize the parameters related to the algorithm\r\nbool kernelsim::initialize( const Parameters_handler* parameters,\r\n\t\tError_messages_handler* errors )\r\n{\r\n\t//-------------\r\n\t// Prepare the simulation grid and the property to be simulated.\r\n\r\n\tif (!get_simul_grid(parameters, errors))\r\n\t{\r\n\t\treturn false;\r\n\t}\r\n\r\n\t//Set up the hard data\r\n\r\n\tif (!get_hard_data(parameters, errors))\r\n\t{\r\n\t\treturn false;\r\n\t}\r\n\r\n\t//-------------\r\n\t// Set up the training image\r\n\r\n\tif (!get_training_image(parameters, errors))\r\n\t{\r\n\t\treturn false;\r\n\t}\r\n\r\n\t//-------------\r\n\t// Set up the search neighborhood\r\n\r\n\tif (!set_up_neighborhood(parameters, errors))\r\n\t{\r\n\t\treturn false;\r\n\t}\r\n\r\n\t//-------------\r\n\t// Set up the regions\r\n\r\n\tif (!set_up_regions(parameters, errors))\r\n\t{\r\n\t\treturn false;\r\n\t}\r\n\r\n\t//-------------\r\n\t//// Set up the covariance\r\n\t//if(!set_up_covariance(parameters, errors))\r\n\t//{\r\n\t//\treturn false;\r\n\t//}\r\n\r\n\t//set up the bound values\r\n\tif(!set_bound_values(parameters, errors))\r\n\t{\r\n\t\treturn false;\r\n\t}\r\n\t//test 0.5 2020-05-05\r\n\tbuild_frequency_table();\r\n\t\r\n\t//double c = 0;\r\n\t//std::vector<double> cutoffs;\r\n\t//while (c < 0.8) {\r\n\t//\tc += 0.01;\r\n\t//\tcutoffs.push_back(c);\r\n\t//}\r\n\t//cutoffs.push_back(1.0);\r\n\t//build_frequency_table(cutoffs);\r\n\r\n\t//You will have to tranform the properties to the interval [-1, 1] before you compute the moments.!!! 2018-02-13.\r\n\r\n\t//Use a transformation class to change the properties' values on hard grid and training image into [-1,1]\r\n\tif(temporary_harddata_property_)\r\n\t\tstd::for_each(temporary_harddata_property_->begin(),temporary_harddata_property_->end(), transform_to_legendre_domain(zmin_, zmax_));\r\n\t\t//std::for_each(temporary_harddata_property_->begin(),temporary_harddata_property_->end(), proportional_transform_legendre_domain<PropertyValueProxy>(freq_table_, val_table_, 2*bin_width_));\r\n\tif(temporary_training_property_)\r\n\t\tstd::for_each(temporary_training_property_->begin(),temporary_training_property_->end(), transform_to_legendre_domain(zmin_, zmax_));\r\n\t\t//std::for_each(temporary_training_property_->begin(),temporary_training_property_->end(), proportional_transform_legendre_domain<PropertyValueProxy>(freq_table_, val_table_, 2*bin_width_));\r\n\r\n\r\n\t///++++++++++++++++Here we store the hard data in a grid with the same size as the simulation grid+++++++++++++++\r\n\t//++++++++++++++++In addition, the data are preprocessed to computer the legendre polymials evaluated at these data values\r\n\t//++++++++++++++++For testing the hard-data-driven. 05/19/2019\r\n\r\n\tSmartPtr<Property_copier> tmp_property_copier_ = \r\n\t\tProperty_copier_factory::get_copier( harddata_grid_, hard_data_ti_);\r\n\tif( !tmp_property_copier_ ) {\r\n\t\tstd::ostringstream message;\r\n\t\tmessage << \"It is currently not possible to copy a property from a \"\r\n\t\t\t<< harddata_grid_->classname() << \" to a \" \r\n\t\t\t<< harddata_grid_->classname() ;\r\n\t\terrors->report( !tmp_property_copier_, \"Transform_Hard_Data\", message.str() );\r\n\t\treturn false;\r\n\t}\r\n\r\n\t//clear the previous data stored in the hard data TI\r\n\tfor(int i = 0; i < hard_data_ti_property_->size(); ++ i)\r\n\t{\r\n\t\thard_data_ti_property_->set_not_informed(i);\r\n\t}\r\n\r\n\ttmp_property_copier_->copy(harddata_grid_, temporary_harddata_property_, hard_data_ti_, hard_data_ti_property_);\r\n\t//tmp_property_copier_->copy(harddata_grid_, harddata_property_, hard_data_ti_, hard_data_ti_property_);\r\n\thard_data_ti_->select_property(hard_data_ti_property_->name());\r\n\tbuild_legendre_hard_ti(parameters, errors);\r\n\r\n\t//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\r\n\r\n\r\n\t//currently just fixed for testing.\r\n\t//double sigma = 0.1;\r\n\tif(!build_kernel_moments(parameters, errors))\r\n\t{\r\n\t\treturn false;\r\n\t}\r\n\r\n\t//-------------\r\n\t// Number of realizations and random number seed\r\n\t\r\n\tnb_of_realizations_ = \r\n\t\tString_Op::to_number<int>( parameters->value( \"Nb_Realizations.value\" ) );\r\n\t\r\n\tseed_ = String_Op::to_number<int>( parameters->value( \"Seed.value\" ) );\r\n\r\n\t//-------------\r\n\t//Set the simple kriging type\r\n\tgeostat_utils::KrigTagMap tags_map;\r\n\tgeostat_utils::KrigDefaultsMap defaults;\r\n\tdefaults[ geostat_utils::SK ] = \"0.0\";\r\n\r\n\tgeostat_utils::Kriging_type ktype = geostat_utils::SK;\r\n\tgeostat_utils::initialize( ktype, combiner_, Kconstraints_,\r\n\t\t\t\t\t\t\t\ttags_map,\r\n\t\t\t\t\t\t\t\tparameters, errors,\r\n\t\t\t\t\t\t\t\tsimul_grid_, defaults );\r\n\t\r\n\treturn true;\r\n}\r\n\r\n//main steps of the algorithm\r\nint kernelsim::execute( GsTL_project* proj)\r\n{\r\n\r\n\r\n\r\n\r\n\t// Set up a progress notifier\t\r\n\tint total_steps = simul_grid_->size() * (nb_of_realizations_);\r\n\tint frequency = std::max( total_steps / 20, 1 );\r\n\tSmartPtr<Progress_notifier> progress_notifier = \r\n\t\tutils::create_notifier( \"Running kernelsim\", \r\n\t\ttotal_steps, frequency );\r\n\r\n\r\n\r\n\r\n\tint nb_multigrids = 3;\r\n\tint finest_grid_nb = 1;\r\n\r\n\r\n\t// work on the fine grid\r\n\tif( dynamic_cast<Strati_grid*>( simul_grid_ ) ) {\r\n\t\tStrati_grid* sgrid = dynamic_cast<Strati_grid*>( simul_grid_ );\r\n\t\tsgrid->set_level( finest_grid_nb );\r\n\t}\r\n\r\n\t//Set the training image to the finest resolution\r\n\ttraining_image_->set_level(finest_grid_nb);\r\n\r\n\r\n\t//To be changed later:\r\n\t//null_dummy_cdf marginal;\r\n\tAvg_dummy_cdf marginal;\r\n\r\n\tGaussian_kernel_cdf ccdf;\r\n\tccdf.order(max_order_);\r\n\tccdf.learning_rate(learning_rate_);\r\n\r\n\tccdf.standard_deviation(sigma_);\r\n\t//June 01, 2018 should'nt fxied the number of the prototypes now!\r\n\t//ccdf.num_prototypes(num_prototypes_);\r\n\r\n  // set up the cdf-estimator\r\n  typedef Gaussian_cdf_Kestimator< Covariance<Location>,\r\n                                   Neighborhood,\r\n                                   geostat_utils::KrigingConstraints\r\n                                  >    Kriging_cdf_estimator;\r\n  SLM_kde_estimator<> cdf_estimator( *(dynamic_cast<Geostat_grid*>(training_image_)),\r\n\t\t\t\t\t\t\t//*harddata_grid_,\r\n\t\t\t\t\t\t\t*hard_data_ti_,\r\n\t\t\t\t\t\t\tLegendre_moments_,\r\n\t\t\t\t\t\t\tLegendre_values_,\r\n\t\t\t\t\t\t\tLegendre_values_hard_ti_,\r\n\t\t\t\t\t\t\tmarginal,\r\n\t\t\t\t\t\t\tzmin_,\r\n\t\t\t\t\t\t\tzmax_,\r\n\t\t\t\t\t\t\tangle_tol_,\r\n\t\t\t\t\t\t\tlag_tol_,\r\n\t\t\t\t\t\t\tband_tol_,\r\n\t\t\t\t\t\t\tnum_ti_replicate_,\r\n\t\t\t\t\t\t\tnum_hd_replicate_\r\n\t\t\t\t\t\t);\r\n\r\n   cdf_estimator.init_prototypes(ccdf, num_prototypes_, num_sel_protos_);\r\n\r\n\r\n\t// Initialize the global random number generator\r\n\tGlobal_random_number_generator::instance()->seed( seed_ );\r\n\r\n  // set up the sampler\r\n  Random_number_generator gen;\r\n  Monte_carlo_sampler_t< Random_number_generator > sampler( gen );\r\n  \r\n\r\n  bool from_scratch = true;\r\n  // loop on all realizations\r\n  for( int nreal = 0; nreal < nb_of_realizations_ ; nreal ++ ) {\r\n\r\n    // compute the random path\r\n    simul_grid_->init_random_path(from_scratch);\r\n    from_scratch = false;\r\n\r\n    // update the progress notifier\r\n    progress_notifier->message() << \"working on realization \" \r\n                                 << nreal+1 << gstlIO::end;\r\n    if( !progress_notifier->notify() ) return 1;\r\n\r\n\r\n    // Create a new property to hold the realization and tell the simulation \r\n    // grid to use it as the current property \r\n    appli_message( \"Creating new realization\" );\r\n    GsTLGridProperty* prop = multireal_property_->new_realization();\r\n    simul_grid_->select_property( prop->name() );\r\n    neighborhood_->select_property( prop->name() );\r\n\r\n    // initialize the new realization with the hard data, if that was requested \r\n    if( property_copier_ ) {\r\n      //Copy the property after transformation 2018-02-13\r\n \r\n\t\tproperty_copier_->copy( harddata_grid_, temporary_harddata_property_,\r\n\t\t\tsimul_grid_, prop );\r\n    }\r\n\r\n    appli_message( \"Doing simulation\" );\r\n\r\n\r\n\t\r\n    // do the simulation\r\n\r\n\t\r\n\tint status =\r\n\t\tsequential_simulation( simul_grid_->random_path_begin(),\r\n\t\t\t     simul_grid_->random_path_end(),\r\n\t\t\t     *(neighborhood_.raw_ptr()),\r\n\t\t\t     ccdf,\r\n\t\t\t\t //cdf,\r\n\t\t\t     cdf_estimator,\r\n\t\t\t     marginal,\r\n\t\t\t     sampler, progress_notifier.raw_ptr()\r\n\t\t\t     );\r\n    if( status == -1 ) {\r\n      clean( prop );\r\n      return 1;\r\n    }\r\n\r\n\tstd::cout<< \"The number of bad points is: \"<< status << std::endl;\r\n\r\n\t//At last, we should change the simulated values back to the original scale, because the previous results were drawn from [-1, 1].\r\n\tstd::for_each(simul_grid_->selected_property()->begin(), simul_grid_->selected_property()->end(), back_from_legendre_domain(zmin_, zmax_));//(lowerbound_, upperbound_));\r\n\t//std::for_each(simul_grid_->selected_property()->begin(), simul_grid_->selected_property()->end(), proportional_backfrom_legendre_domain<PropertyValueProxy>(freq_table_, val_table_, 2*bin_width_));//(lowerbound_, upperbound_));\r\n\r\n  }\r\n  cdf_estimator.close();\r\n  clean();\r\n\r\n  return 0;\r\n}\r\n\r\n//create an instance of the algorithm\r\nNamed_interface* kernelsim::create_new_interface(std::string&)\r\n{\r\n\treturn new kernelsim;\r\n}\r\n\r\n//Get the simulation grid and specify the name of property to be simulated\r\nbool kernelsim::get_simul_grid( const Parameters_handler* parameters,\r\n\t\tError_messages_handler* errors )\r\n{\r\n\tstd::string simul_grid_name = parameters->value( \"Grid_Name.value\" );\r\n\terrors->report( simul_grid_name.empty(), \r\n\t\t\"Grid_Name\", \"No grid selected\" );\r\n\tstd::string property_name = parameters->value( \"Property_Name.value\" );\r\n\terrors->report( property_name.empty(), \r\n\t\t\"Property_Name\", \"No property name specified\" );\r\n\r\n\t// Get the simulation grid from the grid manager  \r\n\tif( simul_grid_name.empty() ) return false;\r\n\r\n\tbool ok = geostat_utils::create( simul_grid_, simul_grid_name,\r\n\t\t\"Grid_Name\", errors );\r\n\r\n\t//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\r\n\t//Create a duplicate grid to hold the hard data in a Cartesian grid. 15/05/2019\r\n\t//ok = geostat_utils::create(hard_data_ti_ , simul_grid_name + \".hard\",\r\n\t//\t\"Grid_Name\", errors );\r\n\r\n\r\n\t//Need to create a new Cartesian grid to do this!!\r\n\t//if( !ok)\r\n\t{\r\n\t\thard_ti_name_ = simul_grid_name + \".hard\";\r\n\t\tstd::string full_name( \"/GridObject/Model/\" + simul_grid_name + \".hard\" );\r\n\t\tSmartPtr<Named_interface> ni = \r\n\t\t\tRoot::instance()->new_interface(\"cgrid://\"+ simul_grid_name + \".hard\", full_name);\r\n  \r\n\t\tif( ni.raw_ptr() == 0 ) {\r\n\t\terrors->report( \"Object \" + full_name + \" already exists. Use a different name.\" );\r\n\t\t//    appli_warning( \"object \" << full_name << \"already exists\" );\r\n\t\treturn false;\r\n\t\t}\r\n  \r\n\t\tCartesian_grid* grid = dynamic_cast<Cartesian_grid*>( ni.raw_ptr() );\r\n\t\tCartesian_grid* sgrid = dynamic_cast<Cartesian_grid*>( simul_grid_);\r\n\t\tgrid->set_dimensions(\r\n\t\t\tsgrid->geometry()->dim(0), \r\n\t\t\tsgrid->geometry()->dim(1), \r\n\t\t\tsgrid->geometry()->dim(2),\r\n\t\t\tsgrid->cell_dimensions()[0], \r\n\t\t\tsgrid->cell_dimensions()[1], \r\n\t\t\tsgrid->cell_dimensions()[2]\r\n\t\t);\r\n\r\n\t\tgrid->origin(sgrid->origin());\r\n\t\t//grid->set_rotation_z(sgrid->rotation_z());\r\n\r\n\t\thard_data_ti_ = grid;\r\n\t\tok = true;\r\n\t}\r\n\r\n\thard_data_ti_property_ = hard_data_ti_->property(property_name);\r\n\tif(!hard_data_ti_property_)\r\n\t\thard_data_ti_property_ = hard_data_ti_->add_property(property_name);\r\n\r\n\t//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//\r\n\r\n\tif( !ok ) return false;\r\n\r\n\t// create  a multi-realization property\r\n\tmultireal_property_ = \r\n\t\tsimul_grid_->add_multi_realization_property( property_name );\r\n\r\n\treturn true;\r\n}\r\n\r\n//retrieve the hard data grid\r\nbool kernelsim::get_hard_data( const Parameters_handler* parameters,\r\n\t\tError_messages_handler* errors )\r\n{\r\n\tstd::string harddata_grid_name = parameters->value( \"Hard_Data.grid\" );\r\n\r\n\tif( !harddata_grid_name.empty() ) {\r\n\t\tstd::string hdata_prop_name = parameters->value( \"Hard_Data.property\" );\r\n\t\terrors->report( hdata_prop_name.empty(), \r\n\t\t\t\"Hard_Data\", \"No property name specified\" );\r\n\r\n\t\t// Get the hard data grid from the grid manager\r\n\t\tbool ok = geostat_utils::create( harddata_grid_, harddata_grid_name, \r\n\t\t\t\"Hard_Data\", errors );\r\n\t\tif( !ok ) return false;\r\n\r\n\t\tharddata_property_ = harddata_grid_->property( hdata_prop_name );\r\n\t\tif( !harddata_property_ ) {\r\n\t\t\tstd::ostringstream error_stream;\r\n\t\t\terror_stream <<  harddata_grid_name \r\n\t\t\t\t<<  \" does not have a property called \" \r\n\t\t\t\t<< hdata_prop_name;\r\n\t\t\terrors->report( \"Hard_Data\", error_stream.str() );\r\n\t\t\treturn false;\r\n\t\t}\r\n\r\n\r\n\t\t//Generate a temporary property that stores what is transformed to interval [-1,1] based on\r\n\t\t//the linear transformation of the original property, because the Legendre polynomials were\r\n\t\t//defined on D=[-1,1].\r\n\t\tstd::string tmp_hdata_prop_name = hdata_prop_name + \"temporary_\";\r\n\r\n\t\ttemporary_harddata_property_ = harddata_grid_->add_property(tmp_hdata_prop_name);\r\n\r\n\t\tif( !temporary_harddata_property_ ) {\r\n\t\t\tstd::ostringstream error_stream;\r\n\t\t\terror_stream <<  harddata_grid_name \r\n\t\t\t\t<<  \" can not create a temporary property called \" \r\n\t\t\t\t<< tmp_hdata_prop_name;\r\n\t\t\terrors->report( \"Hard_Data\", error_stream.str() );\r\n\t\t\treturn false;\r\n\t\t}\r\n\t\tSmartPtr<Property_copier> tmp_property_copier_ = \r\n\t\t\tProperty_copier_factory::get_copier( harddata_grid_, harddata_grid_ );\r\n\r\n\t\tif( !tmp_property_copier_ ) {\r\n\t\t\tstd::ostringstream message;\r\n\t\t\tmessage << \"It is currently not possible to copy a property from a \"\r\n\t\t\t\t<< harddata_grid_->classname() << \" to a \" \r\n\t\t\t\t<< harddata_grid_->classname() ;\r\n\t\t\terrors->report( !tmp_property_copier_, \"Transform_Hard_Data\", message.str() );\r\n\t\t\treturn false;\r\n\t\t}\r\n\r\n\t\ttmp_property_copier_->copy(harddata_grid_, harddata_property_, harddata_grid_, temporary_harddata_property_);\r\n\r\n\t}\r\n\r\n\r\n\r\n\t// hard data assignment and transform is only needed if we have a valid\r\n\t// hard data grid and property.  We always assign the data if it belongs\r\n\t// the same grid\r\n\r\n\tassign_harddata_ = \r\n\t\tString_Op::to_number<bool>( parameters->value( \"Assign_Hard_Data.value\" ) );\r\n\tif( harddata_grid_ == NULL ) assign_harddata_=false; \r\n\telse if( harddata_grid_ == simul_grid_ ) assign_harddata_=true;\r\n\r\n\tif( assign_harddata_ ) {\r\n\t\tproperty_copier_ = \r\n\t\t\tProperty_copier_factory::get_copier( harddata_grid_, simul_grid_ );\r\n\t\tif( !property_copier_ ) {\r\n\t\t\tstd::ostringstream message;\r\n\t\t\tmessage << \"It is currently not possible to copy a property from a \"\r\n\t\t\t\t<< harddata_grid_->classname() << \" to a \" \r\n\t\t\t\t<< simul_grid_->classname() ;\r\n\t\t\terrors->report( !property_copier_, \"Assign_Hard_Data\", message.str() );\r\n\t\t\treturn false;\r\n\t\t}\r\n\t} \r\n\r\n\treturn true;\r\n}\r\n\r\n//Get the instance of training image\r\nbool kernelsim::get_training_image( const Parameters_handler* parameters,\r\n\t\tError_messages_handler* error_mesgs )\r\n{\r\n\ttraining_image_name_ = parameters->value( \"PropertySelector_Training.grid\" );\r\n\terror_mesgs->report( training_image_name_.empty(), \r\n\t\t\"PropertySelector_Training\", \"No training image selected\" );\r\n\r\n\ttraining_property_name_ = parameters->value( \"PropertySelector_Training.property\" );\r\n\terror_mesgs->report( training_property_name_.empty(), \r\n\t\t\"PropertySelector_Training\", \"No training property selected\" );\r\n\r\n\t// Get the training image from the grid manager\r\n\t// and select the training property\r\n\tif( !training_image_name_.empty() ) \r\n\t{\r\n\t\ttraining_image_ = dynamic_cast<RGrid*>( \r\n\t\t\tRoot::instance()->interface( \r\n\t\t\tgridModels_manager + \"/\" + training_image_name_).raw_ptr() );\r\n\r\n\t\tif( !training_image_ ) \r\n\t\t{\r\n\t\t\tstd::ostringstream error_stream;\r\n\t\t\terror_stream <<  training_image_name_ <<  \" is not a valid training image\";\r\n\t\t\terror_mesgs->report( \"PropertySelector_Training\", error_stream.str() );\r\n\t\t\treturn false;\r\n\t\t}\r\n\r\n\t\ttraining_property_ = training_image_->property( training_property_name_ );\r\n\t\tif( !training_property_ ) {\r\n\t\t\tstd::ostringstream error_stream;\r\n\t\t\terror_stream <<  training_image_name_ \r\n\t\t\t\t<<  \" does not have a property called \" \r\n\t\t\t\t<< training_property_name_;\r\n\t\t\terror_mesgs->report( \"Training_Data\", error_stream.str() );\r\n\t\t\treturn false;\r\n\t\t}\r\n\r\n\t\t//Generate a temporary property that stores what is transformed to interval [-1,1] based on\r\n\t\t//the linear transformation of the original property, because the Legendre polynomials were\r\n\t\t//defined on D=[-1,1].\r\n\t\tstd::string tmp_training_prop_name = training_property_name_ + \"temporary_\";\r\n\r\n\t\ttemporary_training_property_ = training_image_->add_property(tmp_training_prop_name);\r\n\r\n\t\tif( !temporary_training_property_ ) {\r\n\t\t\tstd::ostringstream error_stream;\r\n\t\t\terror_stream <<  training_image_name_ \r\n\t\t\t\t<<  \" can not create a temporary property called \" \r\n\t\t\t\t<< tmp_training_prop_name;\r\n\t\t\terror_mesgs->report( \"Hard_Data\", error_stream.str() );\r\n\t\t\treturn false;\r\n\t\t}\r\n\t\tSmartPtr<Property_copier> tmp_property_copier_ = \r\n\t\t\tProperty_copier_factory::get_copier( training_image_, training_image_ );\r\n\r\n\t\tif( !tmp_property_copier_ ) {\r\n\t\t\tstd::ostringstream message;\r\n\t\t\tmessage << \"It is currently not possible to copy a property from a \"\r\n\t\t\t\t<< training_image_->classname() << \" to a \" \r\n\t\t\t\t<< training_image_->classname() ;\r\n\t\t\terror_mesgs->report( !tmp_property_copier_, \"Transform_Training_Data\", message.str() );\r\n\t\t\treturn false;\r\n\t\t}\r\n\r\n\t\ttmp_property_copier_->copy(training_image_, training_property_, training_image_, temporary_training_property_);\r\n\r\n\t\ttraining_image_->select_property( tmp_training_prop_name );\r\n\r\n\t\treturn true;\r\n\t}\r\n\telse \r\n\t\treturn false;\r\n}\r\n\r\n\r\n//Set the covariance model\r\nbool kernelsim::set_up_covariance( const Parameters_handler* parameters,\r\n\t\tError_messages_handler* errors )\r\n{\r\n  //-------------\r\n  // Variogram (covariance) initialization \r\n\r\n  bool init_cov_ok = \r\n    geostat_utils::initialize_covariance( &covar_, \"Variogram\", \r\n                                          parameters, errors );\r\n\r\n  return init_cov_ok;\r\n}\r\n\r\n\r\n//initialize the parameters for searching\r\nbool kernelsim::set_up_neighborhood(const Parameters_handler* parameters,\r\n\tError_messages_handler* errors)\r\n{\r\n\tint max_neigh =\r\n\t\tString_Op::to_number<int>(parameters->value(\"Max_Conditioning_Data.value\"));\r\n\r\n\tnum_ti_replicate_ = String_Op::to_number<int>(parameters->value(\"num_ti_replicate.value\"));\r\n\tnum_hd_replicate_ = String_Op::to_number<int>(parameters->value(\"num_hd_replicate.value\"));\r\n\r\n\t//Get the values for the tolerances to find a replicate in the hard data\r\n\tangle_tol_ = String_Op::to_number<double>(parameters->value(\"Angle_tol.value\"));\r\n\t//Change to radian\r\n\tconst static double pi = 3.14159265359;\r\n\tangle_tol_ = angle_tol_ * pi / 180.0;\r\n\r\n\tlag_tol_ = String_Op::to_number<double>(parameters->value(\"Lag_tol.value\"));\r\n\tband_tol_ = String_Op::to_number<double>(parameters->value(\"Band_tol.value\"));\r\n\r\n\tGsTLTriplet ranges;\r\n\tGsTLTriplet angles;\r\n\tbool extract_ok =\r\n\t\tgeostat_utils::extract_ellipsoid_definition(ranges, angles,\r\n\t\t\t\"Search_Ellipsoid.value\",\r\n\t\t\tparameters, errors);\r\n\tif (!extract_ok) return false;\r\n\r\n\t// If the hard data are not \"relocated\" on the simulation grid,\r\n\t// use a \"combined neighborhood\", otherwise use a single \r\n\t// neighborhood\r\n\tif (!harddata_grid_ || assign_harddata_) {\r\n\r\n\t\tneighborhood_ = SmartPtr<Neighborhood>(\r\n\t\t\tsimul_grid_->neighborhood(ranges, angles));\r\n\r\n\t}\r\n\telse {\r\n\t\tNeighborhood* simul_neigh = simul_grid_->neighborhood(ranges, angles);\r\n\r\n\t\tsimul_neigh->max_size(max_neigh);\r\n\t\tharddata_grid_->select_property(harddata_property_->name());\r\n\r\n\t\tNeighborhood* harddata_neigh;\r\n\t\tif (dynamic_cast<Point_set*>(harddata_grid_)) {\r\n\t\t\tharddata_neigh =\r\n\t\t\t\tharddata_grid_->neighborhood(ranges, angles, 0, true);\r\n\t\t}\r\n\t\telse {\r\n\t\t\tharddata_neigh =\r\n\t\t\t\tharddata_grid_->neighborhood(ranges, angles, 0);\r\n\t\t}\r\n\r\n\r\n\t\tharddata_neigh->max_size(max_neigh);\r\n\t\t//  harddata_neigh->select_property( harddata_property_->name() );\r\n\r\n\t\tneighborhood_ =\r\n\t\t\tSmartPtr<Neighborhood>(new Combined_neighborhood(harddata_neigh,\r\n\t\t\t\tsimul_neigh));\r\n\t\t//     SmartPtr<Neighborhood>( new Combined_neighborhood_dedup( harddata_neigh,\r\n\t   //\t\t\t\t\t\t\t                                           simul_neigh, &covar_, false) );\r\n\t}\r\n\r\n\tneighborhood_->max_size(max_neigh);\r\n\r\n\t// octant_2D_filter * filter = new octant_2D_filter(20, 6, 1, 5);\r\n\r\n\tdouble r = ranges[0];\r\n\tif (r < ranges[1])\r\n\t\tr = ranges[1];\r\n\tif (r < ranges[2])\r\n\t\tr = ranges[2];\r\n\r\n\tif (num_hd_replicate_  == 0 || num_hd_replicate_ == 1)\r\n\t{\r\n\t\tsearch_filter * filter = new search_filter(lag_tol_, band_tol_, angle_tol_, r + lag_tol_,  0.5*lag_tol_);\r\n\t\tneighborhood_->search_neighborhood_filter(filter);\r\n\t}\r\n\r\n\r\n  //Do not include the center\r\n  neighborhood_->includes_center(false);\r\n  //For advanced parameters such as octant searching\r\n  geostat_utils::set_advanced_search(neighborhood_, \r\n                      \"AdvancedSearch\", parameters, errors);\r\n\r\n  return true;\r\n}\r\n\r\n//set the regions for simulation (not used here now)\r\nbool kernelsim::set_up_regions( const Parameters_handler* parameters,\r\n\t\tError_messages_handler* errors )\r\n{\r\n\tstd::string region_name = parameters->value( \"Grid_Name.region\" );\r\n\tif (!region_name.empty() && simul_grid_->region( region_name ) == NULL ) {\r\n\t\terrors->report(\"Grid_Name\",\"Region \"+region_name+\" does not exist\");\r\n\t}\r\n\telse grid_region_.set_temporary_region( region_name, simul_grid_);\r\n\r\n\tif(harddata_grid_ && !assign_harddata_ && harddata_grid_ != simul_grid_) {\r\n\t\tregion_name = parameters->value( \"Hard_Data.region\" );\r\n\t\tif (!region_name.empty() && harddata_grid_->region( region_name ) == NULL ) {\r\n\t\t\terrors->report(\"Hard_Data\",\"Region \"+region_name+\" does not exist\");\r\n\t\t}\r\n\t\telse  hd_grid_region_.set_temporary_region( region_name,harddata_grid_ );\r\n\t}\r\n\r\n\tif(training_image_ != simul_grid_) {\r\n\t\tstd::string region_name = parameters->value( \"PropertySelector_Training.region\" );\r\n\t\tif (!region_name.empty() && training_image_->region( region_name ) == NULL ) {\r\n\t\t\terrors->report(\"PropertySelector_Training\",\"Region \"+region_name+\" does not exist\");\r\n\t\t}\r\n\t\telse ti_grid_region_.set_temporary_region( region_name, training_image_);\r\n\t\treturn true;\r\n\t}\r\n\r\n\treturn true;\r\n}\r\n\r\n\r\nbool kernelsim::set_bound_values( const Parameters_handler* parameters, Error_messages_handler* errors )\r\n{\r\n\t\r\n\tstd::string orderstr = parameters->value(\"Maximum_order.value\");\r\n\tif(orderstr.empty()){\r\n\t\terrors->report(\"Maximum_order\", \"Define an maximal order of Legenddre polynomials to approximate the cdf\");\r\n\t\treturn false;\r\n\t}\r\n\r\n\tmax_order_ = String_Op::to_number<int>(orderstr);\r\n\r\n\r\n\t//I have to rewritten the minmax finding program, because the MS std::minmax_element or boost\r\n\t//is very, very slow to do this, probabily due to the safety bound check on the iterator with every visiting.\r\n\t//Although this can be avoided by define the _SECURE_SCL to 0, however this definition must be\r\n\t//consistent on every library (file) that use the STL, otherwise it will produce strange runtime errors.\r\n\tproperty_type zmax, zmin;\r\n\t\r\n\tif(harddata_property_){\r\n\t\tzmax = *(harddata_property_->begin());\r\n\t\tzmin = zmax;\r\n\t\tfor(GsTLGridProperty::iterator iter = harddata_property_->begin(); iter != harddata_property_->end(); ++ iter){\r\n\t\t\tif(zmax < *iter)\r\n\t\t\t\tzmax = *iter;\r\n\t\t\tif(zmin > *iter)\r\n\t\t\t\tzmin = *iter;\r\n\t\t}\r\n\t}\r\n\telse{\r\n\t\tzmax = *(training_property_->begin());\r\n\t\tzmin = zmax;\r\n\t}\r\n\t\r\n\tfor(GsTLGridProperty::iterator iter = training_property_->begin(); iter != training_property_->end(); ++ iter){\r\n\t\tif(zmax < *iter)\r\n\t\t\tzmax = *iter;\r\n\t\tif(zmin > *iter)\r\n\t\t\tzmin = *iter;\r\n\t}\r\n\r\n\tstd::string strzmin = parameters->value(\"Min_value.value\");\r\n\tstd::string strzmax = parameters->value(\"Max_value.value\");\r\n\tif(strzmin.empty()){\r\n\t\terrors->report(\"Min_value\", \"The input lower bound is required\");\r\n\t\treturn false;\r\n\t}\r\n\r\n\tif(strzmax.empty()){\r\n\t\terrors->report(\"Max_value\", \"The input upper bound is required\");\r\n\t\treturn false;\r\n\t}\r\n\r\n\tzmax_ = zmax;\r\n\tzmin_ = zmin;\r\n\r\n\tupperbound_ = zmax;\r\n\tlowerbound_ = zmin;\r\n\r\n\tzmax = String_Op::to_number<property_type>(strzmax);\r\n\tzmin = String_Op::to_number<property_type>(strzmin);\r\n\r\n\tif(zmax < zmax_){\r\n\t\terrors->report(\"Max_value\", \"The input upper bound is less than the existing data\");\r\n\t\treturn false;\r\n\t}\r\n\telse{\r\n\t\tzmax_ = zmax;\r\n\t}\r\n\r\n\tif(zmin > zmin_){\r\n\t\terrors->report(\"Min_value\", \"The input lower bound is greater than the existing data\");\r\n\t\treturn false;\r\n\t}\r\n\telse{\r\n\t\tzmin_ = zmin;\r\n\t}\r\n\r\n\r\n\tnum_prototypes_ = String_Op::to_number<int>( parameters->value( \"num_prototypes.value\" ) );\r\n\tnum_sel_protos_ = String_Op::to_number<int>( parameters->value( \"num_sel_prototypes.value\" ) );\r\n\r\n\tstd::string str = parameters->value(\"optimize_check.value\");\r\n\tif(str == \"1\")\r\n\t{\r\n\t\tb_optmize_width_ = true;\r\n\t}\r\n\telse \r\n\t\tb_optmize_width_ = false;\r\n\r\n\tstr = parameters->value(\"max_num_iteration.value\");\r\n\r\n\tif(b_optmize_width_){\r\n\t\tif(str.empty()){\r\n\t\t\terrors->report(\"max_num_iteration\", \"Define the maximum iterations\");\r\n\t\t\treturn false;\r\n\t\t}\r\n\r\n\t\tnum_max_iterations_ = String_Op::to_number<int>(str);\r\n\t}\r\n\r\n\tstr = parameters->value(\"sigma_lower_bound.value\");\r\n\tsigma_lb_ = String_Op::to_number<double>(str);\r\n\r\n\tstr = parameters->value(\"sigma_upper_bound.value\");\r\n\tsigma_ub_ = String_Op::to_number<double>(str);\r\n\r\n\tstr = parameters->value(\"learning_rate.value\");\r\n\tlearning_rate_ = String_Op::to_number<double>(str);\r\n\r\n\r\n\treturn true;\r\n\r\n}\r\n\r\n\r\n//free the memory usage\r\nvoid kernelsim::clean( GsTLGridProperty* prop )\r\n{\r\n\tif(prop)\r\n\t\tsimul_grid_->remove_property( prop->name() );\r\n\t\r\n\tif(temporary_harddata_property_){\r\n\t\tharddata_grid_->remove_property(temporary_harddata_property_->name());\r\n\t\ttemporary_harddata_property_ = 0;\r\n\t}\r\n\tif(temporary_training_property_){\r\n\t\ttraining_image_->remove_property(temporary_training_property_->name());\r\n\t\ttemporary_training_property_ = 0;\r\n\t} \r\n\tfor(int i = 0; i < Legendre_moments_.size(); ++ i)\r\n\t{\r\n\t\tdelete Legendre_moments_[i];\r\n\t}\r\n\tfor(int i = 0; i < Legendre_values_.size(); ++ i)\r\n\t{\r\n\t\tdelete Legendre_values_[i];\r\n\t}\r\n\tLegendre_moments_.clear();\r\n\tLegendre_values_.clear();\r\n\r\n\tif (hard_data_ti_)\r\n\t{\r\n\t\t//std::string str = hard_data_ti_->name();\r\n\t\tRoot::instance()->delete_interface(\"/GridObject/Model/\" + hard_ti_name_);// hard_data_ti_->name());\r\n\t\thard_data_ti_ = 0;\r\n\t}\r\n\r\n}\r\n\r\n\r\n//Build the kernel moments and Legendre polynomial values for the training image\r\n//These values will be used in the later steps to build the matrix for the Quadratic\r\n//programming, since we are assuming now that all the replicates come from the training\r\n//image.\r\nbool kernelsim::build_kernel_moments( const Parameters_handler* parameters,\r\n\t\tError_messages_handler* errors )\r\n{\r\n\r\n\tstd::string widthstr = parameters->value(\"kernel_width.value\");\r\n\tif(widthstr.empty()){\r\n\t\terrors->report(\"kernel_width\", \"Define the kernel width\");\r\n\t\treturn false;\r\n\t}\r\n\r\n\tsigma_ = String_Op::to_number<double>(widthstr);\r\n\r\n\t//Initialize the moments up to W the same size as the training image.\r\n\t//We are working on the properties that are transformed to the interval [-1, 1].\r\n\tfor(int w = 0; w <= max_order_; ++ w)\r\n\t{\r\n\t\tLegendre_moments_.push_back(new GsTLGridProperty(temporary_training_property_->size(), \"moments\"));\r\n\t}\r\n\t//We don't store the first two order of Legendre polynomials since they are trivial.\r\n\tfor(int w = 0; w <= max_order_ - 2; ++ w)\r\n\t{\r\n\t\tLegendre_values_.push_back(new GsTLGridProperty(temporary_training_property_->size(), \"values\"));\r\n\t}\r\n\r\n\r\n\t//kermel moments\r\n\tstd::vector<double> I(max_order_ + 1, 0.0);\r\n\t//intermediate variable to compute the kernel moments\r\n\tstd::vector<double> T(max_order_ + 1, 0.0);\r\n\t//Legendre polynomial values\r\n\tstd::vector<double> P(max_order_ + 1, 0.0);\r\n\r\n\r\n\t//Now let's go through the property array of the training image.\r\n\tfor(int i = 0; i < temporary_training_property_->size(); ++ i)\r\n\t{\r\n\t\t//Added to skip non-data-value in the TI, May 22, 2018\r\n\t\tif(!temporary_training_property_->is_informed(i))\r\n\t\t\tcontinue;\r\n\r\n\t\t//we need to define the normal distribution with the mean as the node value and standard deviation as sigma at first.\r\n\t\tdouble mu = temporary_training_property_->get_value(i);\r\n\t\tboost::math::normal df(mu, sigma_);\r\n\t\t//I[0] = boost::math::cdf(df, 1) - boost::math::cdf(df, -1);\r\n\t\t//double c1 = sigma_*sigma_*(boost::math::pdf(df, -1) - boost::math::pdf(df, 1));\r\n\t\t//double c2 = sigma_*sigma_*(boost::math::pdf(df, 1) + boost::math::pdf(df, -1));\r\n\t\tdouble scaling = boost::math::cdf(df, 1) - boost::math::cdf(df, -1);\r\n\t\tI[0] = 1;\r\n\t\t//double c1 = sigma_*sigma_*(boost::math::pdf(df, -1) - boost::math::pdf(df, 1))/scaling;\r\n\t\tdouble c1 = sigma_*sigma_*(boost::math::pdf(df, 1) - boost::math::pdf(df, -1))/scaling;\r\n\t\tdouble c2 = sigma_*sigma_*(boost::math::pdf(df, 1) + boost::math::pdf(df, -1))/scaling;\r\n\r\n\t\tI[1] = mu * I[0] - c1;\r\n\t\tT[0] = I[1];\r\n\t\tP[0] = 1;\r\n\t\tP[1] = mu;\r\n\t\t//The above are the initialized values for the recursive computations\r\n\r\n\t\tLegendre_moments_[0]->set_value(I[0], i);\r\n\t\tLegendre_moments_[1]->set_value(I[1], i);\r\n\r\n\r\n\t\tfor(int w = 1; w < max_order_; ++ w)\r\n\t\t{\r\n\t\t\tT[w] = mu * I[w] - (w%2?c2:c1);\r\n\t\t\tint k = w - 1;\r\n\t\t\twhile (k >= 0)\r\n\t\t\t{\r\n\t\t\t\tT[w] += sigma_*sigma_* (2*k+1)*I[k];\r\n\t\t\t\tk -= 2;\r\n\t\t\t}\r\n\r\n\r\n\t\t\tI[w+1] = ((2*w+1)*T[w] - w*I[w-1])/double (w+1);\r\n\r\n\r\n\t\t\tP[w+1] = (mu*P[w]*(2*w+1) - w*P[w-1])/double(w+1);\r\n\r\n\t\t\tLegendre_moments_[w+1]->set_value(I[w+1], i);\r\n\t\t\tLegendre_values_[w-1]->set_value(P[w+1], i);\r\n\t\t}\r\n\r\n\t}\r\n\r\n\treturn true;\r\n\r\n}\r\n\r\n\r\n//+++++++++++++precompute the legendre values for the hard data +++++++++++++++++++++++++++++ \r\nbool kernelsim::build_legendre_hard_ti( const Parameters_handler* parameters,\r\n\t\tError_messages_handler* errors )\r\n{\r\n\r\n\t//We don't store the first two order of Legendre polynomials since they are trivial.\r\n\tfor(int w = 0; w <= max_order_ - 2; ++ w)\r\n\t{\r\n\t\tLegendre_values_hard_ti_.push_back(new GsTLGridProperty(hard_data_ti_property_->size(), \"values\"));\r\n\t}\r\n\r\n\r\n\t//kermel moments\r\n\tstd::vector<double> I(max_order_ + 1, 0.0);\r\n\t//intermediate variable to compute the kernel moments\r\n\tstd::vector<double> T(max_order_ + 1, 0.0);\r\n\t//Legendre polynomial values\r\n\tstd::vector<double> P(max_order_ + 1, 0.0);\r\n\r\n\r\n\t//Now let's go through the property array of the training image.\r\n\tfor(int i = 0; i < hard_data_ti_property_->size(); ++ i)\r\n\t{\r\n\t\t//Added to skip non-data-value in the TI, May 22, 2018\r\n\t\tif(!hard_data_ti_property_->is_informed(i))\r\n\t\t\tcontinue;\r\n\r\n\t\t//we need to define the normal distribution with the mean as the node value and standard deviation as sigma at first.\r\n\t\tdouble mu = hard_data_ti_property_->get_value(i);\r\n\t\tP[0] = 1;\r\n\t\tP[1] = mu;\r\n\t\t//The above are the initialized values for the recursive computations\r\n\r\n\t\tfor(int w = 1; w < max_order_; ++ w)\r\n\t\t{\r\n\t\t\tP[w+1] = (mu*P[w]*(2*w+1) - w*P[w-1])/double(w+1);\r\n\t\t\tLegendre_values_hard_ti_[w-1]->set_value(P[w+1], i);\r\n\t\t}\r\n\r\n\t}\r\n\r\n\treturn true;\r\n\r\n}\r\n\r\n\r\n//An copy and paster from the ::build_kernel_moments\r\nvoid kernelsim::update_kernel_moments()\r\n{\r\n\t//kermel moments\r\n\tstd::vector<double> I(max_order_ + 1, 0.0);\r\n\t//intermediate variable to compute the kernel moments\r\n\tstd::vector<double> T(max_order_ + 1, 0.0);\r\n\t//Legendre polynomial values\r\n\tstd::vector<double> P(max_order_ + 1, 0.0);\r\n\r\n\r\n\t//Now let's go through the property array of the training image.\r\n\tfor(int i = 0; i < temporary_training_property_->size(); ++ i)\r\n\t{\r\n\t\t//Added to skip non-data-value in the TI, May 22, 2018\r\n\t\tif(!temporary_training_property_->is_informed(i))\r\n\t\t\tcontinue;\r\n\r\n\t\t//we need to define the normal distribution with the mean as the node value and standard deviation as sigma at first.\r\n\t\tdouble mu = temporary_training_property_->get_value(i);\r\n\t\tboost::math::normal df(mu, sigma_);\r\n\t\t//I[0] = boost::math::cdf(df, 1) - boost::math::cdf(df, -1);\r\n\t\t//double c1 = sigma_*sigma_*(boost::math::pdf(df, -1) - boost::math::pdf(df, 1));\r\n\t\t//double c2 = sigma_*sigma_*(boost::math::pdf(df, 1) + boost::math::pdf(df, -1));\r\n\t\tdouble scaling = boost::math::cdf(df, 1) - boost::math::cdf(df, -1);\r\n\t\tI[0] = 1;\r\n\t\t//double c1 = sigma_*sigma_*(boost::math::pdf(df, -1) - boost::math::pdf(df, 1))/scaling;\r\n\t\tdouble c1 = sigma_*sigma_*(boost::math::pdf(df, 1) - boost::math::pdf(df, -1))/scaling;\r\n\t\tdouble c2 = sigma_*sigma_*(boost::math::pdf(df, 1) + boost::math::pdf(df, -1))/scaling;\r\n\r\n\r\n\r\n\r\n\t\tI[1] = mu * I[0] - c1;\r\n\t\tT[0] = I[1];\r\n\t\tP[0] = 1;\r\n\t\tP[1] = mu;\r\n\t\t\r\n\t\t//The above are the initialized values for the recursive computations\r\n\r\n\r\n\r\n\r\n\t\tLegendre_moments_[0]->set_value(I[0], i);\r\n\t\tLegendre_moments_[1]->set_value(I[1], i);\r\n\r\n\r\n\r\n\r\n\r\n\t\tfor(int w = 1; w < max_order_; ++ w)\r\n\t\t{\r\n\t\r\n\r\n\t\t\tT[w] = mu * I[w] - (w%2?c2:c1);\r\n\t\t\tint k = w - 1;\r\n\t\t\twhile (k >= 0)\r\n\t\t\t{\r\n\t\t\t\tT[w] += sigma_*sigma_* (2*k+1)*I[k];\r\n\t\t\t\tk -= 2;\r\n\t\t\t}\r\n\r\n\r\n\t\t\tI[w+1] = ((2*w+1)*T[w] - w*I[w-1])/double (w+1);\r\n\r\n\r\n\t\t\tP[w+1] = (mu*P[w]*(2*w+1) - w*P[w-1])/double(w+1);\r\n\r\n\r\n\t\t\tLegendre_moments_[w+1]->set_value(I[w+1], i);\r\n\t\t\tLegendre_values_[w-1]->set_value(P[w+1], i);\r\n\t\t}\r\n\r\n\t}\r\n}\r\n\r\nvoid kernelsim::compute_derivative()\r\n{\r\n\t\r\n\r\n}\r\n\r\n\r\n//Optimze the kernel width by stochastic gradient descent. June 15 2018\r\nint kernelsim::optimize_kernel_width()\r\n{\r\n\r\n\r\n\treturn 0;\r\n}\r\n\r\n\r\nvoid kernelsim::build_frequency_table(double bin_width)\r\n{\r\n\tbin_width_ = bin_width;\r\n\tif(!temporary_harddata_property_)\r\n\t\treturn;\r\n\t//Copy the data vaules to a new vector\r\n\tstd::vector<double> values(temporary_harddata_property_->size());\r\n\r\n\tfor(int i = 0; i < values.size(); ++ i)\r\n\t{\r\n\t\tvalues[i] = temporary_harddata_property_->get_value(i);\r\n\t}\r\n\r\n\t//sort the values\r\n\t//CAN'T UNDERSTAND WHY SORT FUNCTION DOES NOT WORK ON THIS MACHINE!\r\n\t//std::sort(values.begin(), values.end());\r\n\r\n\t//\r\n\tint num_bins = int (1.0/bin_width);\r\n\tfreq_table_.resize(num_bins+1);\r\n\tval_table_.resize(num_bins+1);\r\n\r\n\tfreq_table_[0] = -1;\r\n\tval_table_[0] = zmin_;\r\n\r\n\tfor(int i = 1; i < num_bins; ++ i)\r\n\t{\r\n\t\tfreq_table_[i] = freq_table_[i-1] + bin_width*2;\r\n\t\tint n = int (bin_width * i * values.size());\r\n\r\n\t\tstd::nth_element(values.begin(), values.begin() + n - 1, values.end());\r\n\t\tval_table_[i] = values[n];\r\n\t}\r\n\r\n\tfreq_table_[num_bins] = 1;\r\n\t//val_table_[num_bins] = 12;\r\n\tval_table_[num_bins] = zmax_;\r\n\r\n}\r\n\r\nvoid kernelsim::build_frequency_table(std::vector<double>& cutoffs)\r\n{\r\n\tif (!temporary_harddata_property_)\r\n\t\treturn;\r\n\t//Copy the data vaules to a new vector\r\n\tstd::vector<double> values(temporary_harddata_property_->size());\r\n\r\n\tfor (int i = 0; i < values.size(); ++i)\r\n\t{\r\n\t\tvalues[i] = temporary_harddata_property_->get_value(i);\r\n\t}\r\n\r\n\t//\r\n\tint num_bins = cutoffs.size();\r\n\tfreq_table_.resize(num_bins);\r\n\tval_table_.resize(num_bins);\r\n\r\n\tfreq_table_[0] = -1;\r\n\tval_table_[0] = zmin_;\r\n\r\n\tfor (int i = 1; i < num_bins-1; ++i)\r\n\t{\r\n\t\tfreq_table_[i] = freq_table_[i - 1] + (cutoffs[i]-cutoffs[i-1])* 2;\r\n\t\tint n = int(cutoffs[i] * values.size());\r\n\r\n\t\tstd::nth_element(values.begin(), values.begin() + n - 1, values.end());\r\n\t\tval_table_[i] = values[n];\r\n\t}\r\n\r\n\tfreq_table_[num_bins-1] = 1;\r\n\tval_table_[num_bins - 1] = zmax_;\r\n\t//val_table_[num_bins - 1] = 12;\r\n\r\n}\r\n\r\n\r\n\r\n//inversion of the probability\r\ndouble Base_kernel_cdf::inverse(double p) const\r\n{\r\n\tdouble result = 0.0;\r\n\r\n\t//boost::uintmax_t max_iter = 1000;\r\n\r\n\tstatic const double lim=1.0e-12;\r\n\tstatic const double INFINITY=GsTL::INFINITY;\r\n\r\n\tstd::pair<double, double> root = boost::math::tools::bisect(\r\n\t\t//boost::BOOST_BIND(&Truncated_Legendre_cdf::prob,this,_1),\r\n\t\tBase_kernel_cdf::root_find_helper (const_cast<Base_kernel_cdf*> (this), p),\r\n\t\t-1.0,\r\n\t\t1.0,\r\n\t\t//-INFINITY,\r\n\t\t//INFINITY,\r\n\t\tbasic_toleration()//,\r\n\t\t//max_iter\r\n\t\t);\r\n\r\n \r\n\tresult = (root.first + root.second)/2;\r\n\r\n\treturn result;\r\n}\r\n\r\n\r\n#include <boost/math/distributions/normal.hpp>\r\n\r\n\r\n//Compute the value of probability Prob(Z <= z)\r\ndouble Gaussian_kernel_cdf::prob( double z ) const\r\n{\r\n\tdouble p = 0.0;\r\n\r\n\r\n\t//double s = std::accumulate(coefs_.begin(), coefs_.end(), 0.0);\r\n\t//double s = std::sqrt(variance_);\r\n\t\r\n\r\n\tfor (int i = 0; i < means_.size(); ++ i)\r\n\t{\r\n\t\t//boost::math::normal c(means_[0], s);\r\n\t\t//double x = boost::math::cdf(c, z);\r\n\t\t//p += coefs_[i] * x;\r\n\r\n\t\tGaussian_cdf cdf(means_[i], variance_);//0.2);\r\n\t\t//x = cdf.prob(z);\r\n\t\t\r\n\t\t//if(coefs_[i]==0.0)\r\n\t\t//\tcontinue;\r\n\t\t//p += coefs_[i] * cdf.prob(z);\r\n\t\t//To shift accoring to the definition of a truncated normal distribution.\r\n\t\tp += coefs_[i] * (cdf.prob(z) - shift_[i])/scaling_[i];\r\n\t\t//p += coefs_[i] * cdf.prob(z);\r\n\r\n\r\n\t}\r\n\r\n\t//p -= overall_shift_;\r\n\t//p /= overall_scaling_;\r\n\r\n\t//if(p<0)\r\n\t//\tp = 0;\r\n\t//else if(p>1)\r\n\t//\tp = 1.0;\r\n\r\n\t//assert( p>=0 && p<=1);\r\n\r\n\treturn p;\r\n}\r\n\r\nvoid Gaussian_kernel_cdf::balance()\r\n{\r\n\tif(balanced_)\r\n\t\treturn;\r\n\r\n\tshift_.resize(means_.size());\r\n\tscaling_.resize(means_.size());\r\n\r\n\toverall_shift_ = 0;\r\n\toverall_scaling_ = 0;\r\n\r\n\tfor (int i = 0; i < means_.size(); ++ i)\r\n\t{\r\n\t\t//boost::math::normal c(means_[0], s);\r\n\t\t//double x = boost::math::cdf(c, z);\r\n\t\t//p += coefs_[i] * x;\r\n\t\tGaussian_cdf cdf(means_[i], variance_);\r\n\r\n\t\t//To shift accoring to the definition of a truncated normal distribution.\r\n\t\tshift_[i] =  cdf.prob(-1.0);\r\n\t\tdouble s = cdf.prob(1.0) - shift_[i];\r\n\t\tscaling_[i] = s;\r\n\r\n\t\toverall_shift_ += coefs_[i] * shift_[i];\r\n\t\toverall_scaling_ += coefs_[i] * s;\r\n\r\n\t}\r\n\r\n\r\n\tbalanced_ = true;\r\n}\r\n\r\n\r\n\r\n//Some helpful functions related to the algorithm of reproducing kernel generated by Legendre polynomials.\r\n\r\n\r\n//This function compute the moment of a univariate Legendre polynomial with normal distribution on the interval [-1,1].\r\n//Store the moments up to w in the vector\r\nint Legendre_Gauss_Mom(int max_order, double mu, double sigma, std::vector<double>& moments, std::vector<double>& P, std::vector<double>& prototype_derivatives)\r\n{\r\n\t//We only consider the moments of positive orders\r\n\tassert (max_order >= 1);\r\n\r\n\t//Moments from order 0 to order w\r\n\t//moments.resize(max_order+1, 0.0);\r\n\tmoments.assign(max_order+1, 0.0);\r\n\r\n\t//Derivatives corresponding to the moments on sigma 2018-10-12\r\n\t//prototype_derivatives.resize(max_order+1, 0.0);\r\n\tprototype_derivatives.assign(max_order+1, 0.0);\r\n\r\n\t//intermediate variable to compute the kernel moments\r\n\tstd::vector<double> T(max_order + 1, 0.0);\r\n\t//Legendre polynomial values\r\n\t//P.resize(max_order + 1, 0.0);\r\n\tP.assign(max_order + 1, 0.0);\r\n\r\n\r\n\t//The vector to store intermediate values to compute derivatives 12/10/2018\r\n\tstd::vector<double> DI(max_order + 1, 0.0);\r\n\tstd::vector<double> DT(max_order + 1, 0.0);\r\n\r\n\t\tboost::math::normal df(mu, sigma);\r\n\t\t//June 04, 2018. IMPORTANT, we actually need a truncated normal distribution on [-1, 1] here to be the prototypes.\r\n\t\t//OTHERWISE, the integral of the pdf is not 1 and will intend to generate extreme high values in the simulation.\r\n\t\t//moments[0] = boost::math::cdf(df, 1) - boost::math::cdf(df, -1);\r\n\t\t//double c1 = sigma*sigma*(boost::math::pdf(df, -1) - boost::math::pdf(df, 1));\r\n\t\t//double c2 = sigma*sigma*(boost::math::pdf(df, 1) + boost::math::pdf(df, -1));\r\n\r\n\t\tdouble scaling = boost::math::cdf(df, 1) - boost::math::cdf(df, -1);\r\n\t\tmoments[0] = 1.0; \r\n\t\tdouble c1 = sigma*sigma*(boost::math::pdf(df, 1) - boost::math::pdf(df, -1))/scaling;\r\n\t\tdouble c2 = sigma*sigma*(boost::math::pdf(df, 1) + boost::math::pdf(df, -1))/scaling;\r\n\t\tmoments[1] = mu * moments[0] - c1;\r\n\t\tT[0] = moments[1];\r\n\t\tP[0] = 1;\r\n\t\tP[1] = mu;\r\n\t\t//The above are the initialized values for the recursive computations\r\n\r\n\r\n\t\t//The derivatives of initialized values --Added on 12/10/2018\r\n\t\tdouble C1 = ((1-mu)*(1-mu)/sigma + sigma)/scaling * boost::math::pdf(df, 1) - ((1+mu)*(1+mu)/sigma + sigma)/scaling  * boost::math::pdf(df, -1)\r\n\t\t\t+ ((1-mu)*boost::math::pdf(df, 1) + (1+mu)*boost::math::pdf(df, -1))*c1/sigma/scaling;\r\n\r\n\t\tdouble C2 = ((1-mu)*(1-mu)/sigma+ sigma)/scaling  * boost::math::pdf(df, 1) + ((1+mu)*(1+mu)/sigma + sigma)/scaling * boost::math::pdf(df, -1)\r\n\t\t\t+ ((1-mu)*boost::math::pdf(df, 1) + (1+mu)*boost::math::pdf(df, -1))*c2/sigma/scaling;\r\n\r\n\t\t//\r\n\t\tDI[0] = 0;\r\n\t\tDI[1] = -C1;\r\n\t\tDT[0] = DI[1];\r\n\t\t//The above are intialized to compute the derivatives recursively.\r\n\r\n\t\t//It's a waste of memory to store the constant value DI[0], but just for the temporary convenience.\r\n\t\tprototype_derivatives[0] = DI[0];\r\n\t\tprototype_derivatives[1] = DI[1];\r\n\r\n\t\tfor(int w = 1; w < max_order; ++ w)\r\n\t\t{\r\n\t\t\tDT[w] = mu * DI[w] - (w%2?C2:C1);\r\n\r\n\t\t\tT[w] = mu * moments[w] - (w%2?c2:c1);\r\n\t\t\tint k = w - 1;\r\n\t\t\twhile (k >= 0)\r\n\t\t\t{\r\n\t\t\t\tDT[w] += (sigma*sigma*DI[k] + 2*sigma*moments[k])*(2*k+1);\r\n\r\n\t\t\t\tT[w] += sigma*sigma* (2*k+1)*moments[k];\r\n\t\t\t\tk -= 2;\r\n\t\t\t}\r\n\r\n\t\t\t\t\t\t\r\n\t\t\tDI[w+1] = ((2*w+1)*DT[w] - w*DI[w-1])/double (w+1);\r\n\t\t\tP[w+1] = (mu*P[w]*(2*w+1) - w*P[w-1])/double(w+1);\r\n\r\n\t\t\tprototype_derivatives[w+1] = DI[w+1];\r\n\t\t\tmoments[w+1] = ((2*w+1)*T[w] - w*moments[w-1])/double (w+1);\r\n\t\t}\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t////Let's calculate E[P_0] at first, not that P_0(x) = 1.\r\n\t//boost::math::normal c(m, 1.0); \r\n\r\n\t//double EP0 =  boost::math::cdf(c, 1-m) - boost::math::cdf(c, -1-m);\r\n\t////Now let's compute E[P_1] and note thata P_1(x) = x.\r\n\r\n\t////Check the derivation on the blue notebook.(YLQ)\r\n\t//double EP1 = m * EP0 + boost::math::pdf(c, -1-m) - boost::math::pdf(c, 1-m);\r\n\r\n\t//moments[0] = EP0;\r\n\t//if (w == 0){\t\t\r\n\t//\treturn 0;\r\n\t//}\r\n\t//moments[1] = EP1;\r\n\t//if (w==1){\r\n\t//\t\r\n\t//\treturn 0;\r\n\t//}\r\n\r\n\t//double c1 = boost::math::pdf(c, 1);\r\n\t//double c2 = boost::math::pdf(c, -1);\r\n\r\n\t////Now calculate the moments based on the recursive relations.\r\n\t////Check the derivation from the blue notebook.\r\n\t//double dP0 = EP0;\r\n\t//double dP1 = EP1;\r\n\t//for(int n = 2; n <= w; ++ n){\r\n\r\n\t//\tdouble realn = (double) n;\r\n\t//\t//note the property of Pn(-1) = (-1)^n and Pn(1) = 1\r\n\t//\tdouble cn = ((n%2)? c2:-c2) - c1;\t\t\r\n\r\n\r\n\t//\t//Compute integral of Gau(x)dP_(n-1)\r\n\t//\t//for( int i = n - 1; i > 0; i -= 2){\r\n\t//\t\t//dP += (2*i + 1) * moments[i];\r\n\t//\t//}\r\n\t//\t\r\n\t//\tmoments[n] =  ( (2 * realn - 1) *(cn + m * moments[n-1] + ((n%2)?dP0:dP1)) - \r\n\t//\t\t\t\t\t(realn - 1) * moments[n-2] ) / realn;\r\n\t//\tif(n%2){\r\n\t//\t\tdP0 += moments[n];\r\n\t//\t}\r\n\t//\telse{\r\n\t//\t\tdP1 += moments[n];\r\n\t//\t}\r\n\t//}\r\n\r\n\treturn 0;\r\n}\r\n\r\n\r\n//This function compute the moment of a univariate Legendre polynomial with normal distribution on the interval [-1,1].\r\n//Store the moments up to w in the vector\r\nint Legendre_Gauss_Mom(int max_order, double mu, double sigma, std::vector<double>& moments, std::vector<double>& P)\r\n{\r\n\t//We only consider the moments of positive orders\r\n\tassert (max_order >= 1);\r\n\r\n\t//Moments from order 0 to order w\r\n\t//moments.resize(max_order+1, 0.0);\r\n\tmoments.assign(max_order+1, 0.0);\r\n\r\n\r\n\t//intermediate variable to compute the kernel moments\r\n\tstd::vector<double> T(max_order + 1, 0.0);\r\n\t//Legendre polynomial values\r\n\t//P.resize(max_order + 1, 0.0);\r\n\tP.assign(max_order + 1, 0.0);\r\n\r\n\r\n\t\tboost::math::normal df(mu, sigma);\r\n\t\t//June 04, 2018. IMPORTANT, we actually need a truncated normal distribution on [-1, 1] here to be the prototypes.\r\n\t\t//OTHERWISE, the integral of the pdf is not 1 and will intend to generate extreme high values in the simulation.\r\n\t\t//moments[0] = boost::math::cdf(df, 1) - boost::math::cdf(df, -1);\r\n\t\t//double c1 = sigma*sigma*(boost::math::pdf(df, -1) - boost::math::pdf(df, 1));\r\n\t\t//double c2 = sigma*sigma*(boost::math::pdf(df, 1) + boost::math::pdf(df, -1));\r\n\r\n\t\tdouble scaling = boost::math::cdf(df, 1) - boost::math::cdf(df, -1);\r\n\t\tmoments[0] = 1.0; \r\n\t\tdouble c1 = sigma*sigma*(boost::math::pdf(df, 1) - boost::math::pdf(df, -1))/scaling;\r\n\t\tdouble c2 = sigma*sigma*(boost::math::pdf(df, 1) + boost::math::pdf(df, -1))/scaling;\r\n\t\tmoments[1] = mu * moments[0] - c1;\r\n\t\tT[0] = moments[1];\r\n\t\tP[0] = 1;\r\n\t\tP[1] = mu;\r\n\t\t//The above are the initialized values for the recursive computations\r\n\r\n\r\n\r\n\t\tfor(int w = 1; w < max_order; ++ w)\r\n\t\t{\r\n\r\n\t\t\tT[w] = mu * moments[w] - (w%2?c2:c1);\r\n\t\t\tint k = w - 1;\r\n\t\t\twhile (k >= 0)\r\n\t\t\t{\r\n\t\t\t\tT[w] += sigma*sigma* (2*k+1)*moments[k];\r\n\t\t\t\tk -= 2;\r\n\t\t\t}\r\n\r\n\t\t\tP[w+1] = (mu*P[w]*(2*w+1) - w*P[w-1])/double(w+1);\r\n\r\n\t\t\tmoments[w+1] = ((2*w+1)*T[w] - w*moments[w-1])/double (w+1);\r\n\t\t}\r\n\r\n\r\n\treturn 0;\r\n}\r\n\r\nGEOSTAT_PLUGIN(kernelsim)", "meta": {"hexsha": "c0fa1dfb5ab0d64b31241c0a8fc8fd97e1eaa5e6", "size": 45662, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "kernelsim.cpp", "max_stars_repo_name": "yaolq/kernelsim", "max_stars_repo_head_hexsha": "1e450a6e9cbec4639a6fe5163179d46db80777a7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2021-03-25T04:24:10.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-25T04:24:41.000Z", "max_issues_repo_path": "kernelsim.cpp", "max_issues_repo_name": "yaolq/kernelsim", "max_issues_repo_head_hexsha": "1e450a6e9cbec4639a6fe5163179d46db80777a7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "kernelsim.cpp", "max_forks_repo_name": "yaolq/kernelsim", "max_forks_repo_head_hexsha": "1e450a6e9cbec4639a6fe5163179d46db80777a7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-02-21T14:36:48.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-30T07:32:27.000Z", "avg_line_length": 30.5840589417, "max_line_length": 230, "alphanum_fraction": 0.6601769524, "num_tokens": 13015, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6442251064863697, "lm_q2_score": 0.5312093733737563, "lm_q1q2_score": 0.34221841512826584}}
{"text": "/*\n *  Submitted as the final project for Dr. Adrian Del Maestro's PHYS 642\n *  Statistical Mechanics (Phase Transitions and Critical Phenomena) class, \n *  Fall 2021 semester at University of Tennessee, Knoxville.\n *\n *  I did it in C++ because I figured I can get good practice in this way. I\n *  also didn't want to use <iostream> because, other than operator overloading,\n *  it's pretty familiar (not that it really should make a huge difference in\n *  this program one way or the other) - at least, the std::cin/cout part is \n *  familiar, which is all that I'd really use.\n */\n\n#include <boost/program_options.hpp>\n#define BOOST_PROGRAM_OPTIONS_SET\n\n\n#include \"common_headers.hpp\"\n#include \"MC_functions.hpp\"\n// #include \"MC_functions.cpp\"\n// #include \"GetOptions.cpp\"\n\nusing std::string;\n\nnamespace br = boost::random;\nnamespace bu = boost::uuids;\nnamespace po = boost::program_options;\n\nint main(int ac, char **av)\n{\n    // Command-line parameters\n    size_t L            = 16;\n    double temp         = 1/3;\n//    double beta         = 1;\n    size_t numSamp      = pow(2, 17);   // 2^17 > 10^5\n    uint64_t numEqSteps = pow(2, 15);\n\n//    uint64_t result = GetOptions(ac, av, &L, &beta, &numSamp, &numEqSteps);\n    uint64_t result = GetOptions(ac, av, &L, &temp, &numSamp, &numEqSteps);\n\n    if(result == 0) {}\n\n    else if(result == 1) {return 0; }\n\n    else if(result != 0 && result != 1)\n    {\n        printf(\"Please enter valid options and try again.\\n\");\n        return 2;\n    }\n\n    // The rest of the parameters\n    size_t N            = L*L;\n//    double J            = 1;  // These aren't actually implemented, but could\n//    double kB           = 1;  // be easily\n    bu::uuid id = bu::random_generator()();\n    string string_uuid = bu::to_string(id);\n    string baseName = string_uuid + \".dat\";\n\n    // Accumulators, etc., for desired quantities\n    //\n    \n    br::random_device rd;\n    br::mt19937_64 rng(rd);\n    br::uniform_real_distribution<double> dist01(0,1);\n//    Params Pars(L, N, numSamp, numEqSteps, beta, baseName, id, rng, dist01);\n    Params Pars(L, N, numSamp, numEqSteps, temp, baseName, id, rng, dist01);\n    \n    MonteCarlo(Pars);\n\n    return 0;\n}\n", "meta": {"hexsha": "7a5415d93367d2b5df73c708583c82bb806929bd", "size": 2189, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "IsingMC_FinalProject.cpp", "max_stars_repo_name": "CaryRock/Phys642_Final_Project", "max_stars_repo_head_hexsha": "fb1e49b84efb0585857bb16379fbc6ac39074c5c", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "IsingMC_FinalProject.cpp", "max_issues_repo_name": "CaryRock/Phys642_Final_Project", "max_issues_repo_head_hexsha": "fb1e49b84efb0585857bb16379fbc6ac39074c5c", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "IsingMC_FinalProject.cpp", "max_forks_repo_name": "CaryRock/Phys642_Final_Project", "max_forks_repo_head_hexsha": "fb1e49b84efb0585857bb16379fbc6ac39074c5c", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.8309859155, "max_line_length": 80, "alphanum_fraction": 0.634536318, "num_tokens": 619, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.6442250928250375, "lm_q1q2_score": 0.34221840787123814}}
{"text": "#ifndef BOOST_GEOMETRY_PROJECTIONS_AITOFF_HPP\n#define BOOST_GEOMETRY_PROJECTIONS_AITOFF_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// Purpose:  Implementation of the aitoff (Aitoff) and wintri (Winkel Tripel)\n// projections.\n// Author:   Gerald Evenden\n// Copyright (c) 1995, Gerald Evenden\n\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the \"Software\"),\n// to deal in the Software without restriction, including without limitation\n// the rights to use, copy, modify, merge, publish, distribute, sublicense,\n// and/or sell copies of the Software, and to permit persons to whom the\n// Software is furnished to do so, subject to the following conditions:\n\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n// DEALINGS IN THE SOFTWARE.\n\n#include <boost/core/ignore_unused.hpp>\n#include <boost/geometry/util/math.hpp>\n\n#include <boost/geometry/srs/projections/impl/base_static.hpp>\n#include <boost/geometry/srs/projections/impl/base_dynamic.hpp>\n#include <boost/geometry/srs/projections/impl/projects.hpp>\n#include <boost/geometry/srs/projections/impl/factory_entry.hpp>\n\nnamespace boost { namespace geometry\n{\n\nnamespace srs { namespace par4\n{\n    struct aitoff {};\n    struct wintri {};\n\n}} //namespace srs::par4\n\nnamespace projections\n{\n    #ifndef DOXYGEN_NO_DETAIL\n    namespace detail { namespace aitoff\n    {\n            template <typename T>\n            struct par_aitoff\n            {\n                T    cosphi1;\n                int  mode;\n            };\n\n            // template class, using CRTP to implement forward/inverse\n            template <typename CalculationType, typename Parameters>\n            struct base_aitoff_spheroid : public base_t_fi<base_aitoff_spheroid<CalculationType, Parameters>,\n                     CalculationType, Parameters>\n            {\n\n                typedef CalculationType geographic_type;\n                typedef CalculationType cartesian_type;\n\n                par_aitoff<CalculationType> m_proj_parm;\n\n                inline base_aitoff_spheroid(const Parameters& par)\n                    : base_t_fi<base_aitoff_spheroid<CalculationType, Parameters>,\n                     CalculationType, Parameters>(*this, par) {}\n\n                // FORWARD(s_forward)  spheroid\n                // Project coordinates from geographic (lon, lat) to cartesian (x, y)\n                inline void fwd(geographic_type& lp_lon, geographic_type& lp_lat, cartesian_type& xy_x, cartesian_type& xy_y) const\n                {\n                    CalculationType c, d;\n\n                    if((d = acos(cos(lp_lat) * cos(c = 0.5 * lp_lon)))) {/* basic Aitoff */\n                        xy_x = 2. * d * cos(lp_lat) * sin(c) * (xy_y = 1. / sin(d));\n                        xy_y *= d * sin(lp_lat);\n                    } else\n                        xy_x = xy_y = 0.;\n                    if (this->m_proj_parm.mode) { /* Winkel Tripel */\n                        xy_x = (xy_x + lp_lon * this->m_proj_parm.cosphi1) * 0.5;\n                        xy_y = (xy_y + lp_lat) * 0.5;\n                    }\n                }\n                /***********************************************************************************\n                *\n                * Inverse functions added by Drazen Tutic and Lovro Gradiser based on paper:\n                *\n                * I.Özbug Biklirici and Cengizhan Ipbüker. A General Algorithm for the Inverse\n                * Transformation of Map Projections Using Jacobian Matrices. In Proceedings of the\n                * Third International Symposium Mathematical & Computational Applications,\n                * pages 175{182, Turkey, September 2002.\n                *\n                * Expected accuracy is defined by EPSILON = 1e-12. Should be appropriate for\n                * most applications of Aitoff and Winkel Tripel projections.\n                *\n                * Longitudes of 180W and 180E can be mixed in solution obtained.\n                *\n                * Inverse for Aitoff projection in poles is undefined, longitude value of 0 is assumed.\n                *\n                * Contact : dtutic@geof.hr\n                * Date: 2015-02-16\n                *\n                ************************************************************************************/\n\n                // INVERSE(s_inverse)  sphere\n                // Project coordinates from cartesian (x, y) to geographic (lon, lat)\n                inline void inv(cartesian_type& xy_x, cartesian_type& xy_y, geographic_type& lp_lon, geographic_type& lp_lat) const\n                {\n                    static const CalculationType ONEPI = detail::ONEPI<CalculationType>();\n                    static const CalculationType TWOPI = detail::TWOPI<CalculationType>();\n                    static const CalculationType EPSILON = 1e-12;\n\n                    int iter, MAXITER = 10, round = 0, MAXROUND = 20;\n                    CalculationType D, C, f1, f2, f1p, f1l, f2p, f2l, dp, dl, sl, sp, cp, cl, x, y;\n\n                    if ((fabs(xy_x) < EPSILON) && (fabs(xy_y) < EPSILON )) { lp_lat = 0.; lp_lon = 0.; return; }\n\n                    /* intial values for Newton-Raphson method */\n                    lp_lat = xy_y; lp_lon = xy_x;\n                    do {\n                        iter = 0;\n                        do {\n                            sl = sin(lp_lon * 0.5); cl = cos(lp_lon * 0.5);\n                            sp = sin(lp_lat); cp = cos(lp_lat);\n                            D = cp * cl;\n                                   C = 1. - D * D;\n                            D = acos(D) / pow(C, 1.5);\n                                   f1 = 2. * D * C * cp * sl;\n                                   f2 = D * C * sp;\n                                   f1p = 2.* (sl * cl * sp * cp / C - D * sp * sl);\n                                   f1l = cp * cp * sl * sl / C + D * cp * cl * sp * sp;\n                                f2p = sp * sp * cl / C + D * sl * sl * cp;\n                                  f2l = 0.5 * (sp * cp * sl / C - D * sp * cp * cp * sl * cl);\n                                  if (this->m_proj_parm.mode) { /* Winkel Tripel */\n                                f1 = 0.5 * (f1 + lp_lon * this->m_proj_parm.cosphi1);\n                                f2 = 0.5 * (f2 + lp_lat);\n                                f1p *= 0.5;\n                                f1l = 0.5 * (f1l + this->m_proj_parm.cosphi1);\n                                f2p = 0.5 * (f2p + 1.);\n                                f2l *= 0.5;\n                            }\n                            f1 -= xy_x; f2 -= xy_y;\n                            dl = (f2 * f1p - f1 * f2p) / (dp = f1p * f2l - f2p * f1l);\n                            dp = (f1 * f2l - f2 * f1l) / dp;\n                            while (dl > ONEPI) dl -= ONEPI; /* set to interval [-ONEPI, ONEPI]  */\n                            while (dl < -ONEPI) dl += ONEPI; /* set to interval [-ONEPI, ONEPI]  */\n                            lp_lat -= dp;    lp_lon -= dl;\n                        } while ((fabs(dp) > EPSILON || fabs(dl) > EPSILON) && (iter++ < MAXITER));\n                        if (lp_lat > TWOPI) lp_lat -= 2.*(lp_lat-TWOPI); /* correct if symmetrical solution for Aitoff */\n                        if (lp_lat < -TWOPI) lp_lat -= 2.*(lp_lat+TWOPI); /* correct if symmetrical solution for Aitoff */\n                        if ((fabs(fabs(lp_lat) - TWOPI) < EPSILON) && (!this->m_proj_parm.mode)) lp_lon = 0.; /* if pole in Aitoff, return longitude of 0 */\n\n                        /* calculate x,y coordinates with solution obtained */\n                        if((D = acos(cos(lp_lat) * cos(C = 0.5 * lp_lon)))) {/* Aitoff */\n                            x = 2. * D * cos(lp_lat) * sin(C) * (y = 1. / sin(D));\n                            y *= D * sin(lp_lat);\n                        } else\n                            x = y = 0.;\n                        if (this->m_proj_parm.mode) { /* Winkel Tripel */\n                            x = (x + lp_lon * this->m_proj_parm.cosphi1) * 0.5;\n                            y = (y + lp_lat) * 0.5;\n                        }\n                    /* if too far from given values of x,y, repeat with better approximation of phi,lam */\n                    } while (((fabs(xy_x-x) > EPSILON) || (fabs(xy_y-y) > EPSILON)) && (round++ < MAXROUND));\n\n                    //if (iter == MAXITER && round == MAXROUND) fprintf(stderr, \"Warning: Accuracy of 1e-12 not reached. Last increments: dlat=%e and dlon=%e\\n\", dp, dl);\n                }\n\n                static inline std::string get_name()\n                {\n                    return \"aitoff_spheroid\";\n                }\n\n            };\n\n            template <typename Parameters, typename T>\n            inline void setup(Parameters& par, par_aitoff<T>& proj_parm) \n            {\n                boost::ignore_unused(proj_parm);\n                par.es = 0.;\n            }\n\n\n            // Aitoff\n            template <typename Parameters, typename T>\n            inline void setup_aitoff(Parameters& par, par_aitoff<T>& proj_parm)\n            {\n                proj_parm.mode = 0;\n                setup(par, proj_parm);\n            }\n\n            // Winkel Tripel\n            template <typename Parameters, typename T>\n            inline void setup_wintri(Parameters& par, par_aitoff<T>& proj_parm)\n            {\n                static const T TWO_D_PI = detail::TWO_D_PI<T>();\n\n                proj_parm.mode = 1;\n                if (pj_param(par.params, \"tlat_1\").i) {\n                    if ((proj_parm.cosphi1 = cos(pj_param(par.params, \"rlat_1\").f)) == 0.)\n                        BOOST_THROW_EXCEPTION( projection_exception(-22) );\n                } else /* 50d28' or phi1=acos(2/pi) */\n                    proj_parm.cosphi1 = TWO_D_PI;\n                setup(par, proj_parm);\n            }\n\n    }} // namespace detail::aitoff\n    #endif // doxygen\n\n    /*!\n        \\brief Aitoff 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_aitoff.gif\n    */\n    template <typename CalculationType, typename Parameters>\n    struct aitoff_spheroid : public detail::aitoff::base_aitoff_spheroid<CalculationType, Parameters>\n    {\n        inline aitoff_spheroid(const Parameters& par) : detail::aitoff::base_aitoff_spheroid<CalculationType, Parameters>(par)\n        {\n            detail::aitoff::setup_aitoff(this->m_par, this->m_proj_parm);\n        }\n    };\n\n    /*!\n        \\brief Winkel Tripel projection\n        \\ingroup projections\n        \\tparam Geographic latlong point type\n        \\tparam Cartesian xy point type\n        \\tparam Parameters parameter type\n        \\par Projection characteristics\n         - Miscellaneous\n         - Spheroid\n        \\par Projection parameters\n         - lat_1: Latitude of first standard parallel (degrees)\n        \\par Example\n        \\image html ex_wintri.gif\n    */\n    template <typename CalculationType, typename Parameters>\n    struct wintri_spheroid : public detail::aitoff::base_aitoff_spheroid<CalculationType, Parameters>\n    {\n        inline wintri_spheroid(const Parameters& par) : detail::aitoff::base_aitoff_spheroid<CalculationType, Parameters>(par)\n        {\n            detail::aitoff::setup_wintri(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::aitoff, aitoff_spheroid, aitoff_spheroid)\n        BOOST_GEOMETRY_PROJECTIONS_DETAIL_STATIC_PROJECTION(srs::par4::wintri, wintri_spheroid, wintri_spheroid)\n\n        // Factory entry(s)\n        template <typename CalculationType, typename Parameters>\n        class aitoff_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<aitoff_spheroid<CalculationType, Parameters>, CalculationType, Parameters>(par);\n                }\n        };\n\n        template <typename CalculationType, typename Parameters>\n        class wintri_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<wintri_spheroid<CalculationType, Parameters>, CalculationType, Parameters>(par);\n                }\n        };\n\n        template <typename CalculationType, typename Parameters>\n        inline void aitoff_init(detail::base_factory<CalculationType, Parameters>& factory)\n        {\n            factory.add_to_factory(\"aitoff\", new aitoff_entry<CalculationType, Parameters>);\n            factory.add_to_factory(\"wintri\", new wintri_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_AITOFF_HPP\n\n", "meta": {"hexsha": "7d34a2328795587751277af12c50ea6a806831fe", "size": 14643, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost_1_67_0/boost/geometry/srs/projections/proj/aitoff.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/aitoff.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/aitoff.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": 45.0553846154, "max_line_length": 170, "alphanum_fraction": 0.54927269, "num_tokens": 3383, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7122321842389469, "lm_q2_score": 0.480478678047907, "lm_q1q2_score": 0.3422123783463025}}
{"text": "#if COMPILATION_INSTRUCTIONS\n(echo \"#include<\" $0 \">\" > $0x.cpp) && time clang++ - O3 - std = c++ 1z - Wall `# - Wfatal\n        - errors` - I..- D_TEST_SPARSE_COO_MATRIX $0x.cpp - lstdc++ fs - lboost_system - lboost_timer - o $0x.x\n    && time $0x.x $ @ && rm - f $0x.cpp;\nexit\n#endif\n\n////////////////////////////////////////////////////////////////////////////////\n// File developed by:\n// Alfredo Correa, correaa@llnl.gov\n//    Lawrence Livermore National Laboratory\n//\n// File created by:\n// Alfredo Correa, correaa@llnl.gov\n//    Lawrence Livermore National Laboratory\n////////////////////////////////////////////////////////////////////////////////\n\n#ifndef SPARSE_COO_MATRIX_HPP\n#define SPARSE_COO_MATRIX_HPP\n\n#include <array>\n#include <cassert>\n#include <cstddef> // ptrdiff_t\n#include <vector>\n#include <tuple>\n\n    namespace ma\n{\n  namespace sparse\n  {\n  using size_type = std::size_t;\n\n  template<class T, class index, class Alloc = std::allocator<T>>\n  class coo_matrix\n  {\n  protected:\n    using alloc_ts        = std::allocator_traits<Alloc>;\n    using index_allocator = typename alloc_ts::template rebind_alloc<index>;\n    std::vector<index, index_allocator> is_;\n    std::vector<index, index_allocator> js_;\n    std::vector<T, Alloc> vs_;\n    size_type cols_;\n    size_type rows_;\n\n  public:\n    using element                            = T;\n    coo_matrix(coo_matrix const&)            = default;\n    coo_matrix(coo_matrix&&)                 = default;\n    bool operator==(coo_matrix const&) const = delete;\n    coo_matrix(std::tuple<index, index> const& arr                                    = std::tuple<index, index>{0, 0},\n               std::initializer_list<std::pair<std::tuple<index, index>, element>> il = {})\n        : cols_(std::get<0>(arr)), rows_(std::get<1>(arr))\n    {\n      for (auto e : il)\n        emplace(e.first, e.second);\n    }\n    void reserve(size_type s)\n    {\n      is_.reserve(s);\n      js_.reserve(s);\n      vs_.reserve(s);\n    }\n    auto size() const { return rows_; }\n    auto num_elements() const { return size() * cols_; }\n    std::array<index, 2> shape() const { return {{size(), cols_}}; }\n    auto num_non_zero_elements() const { return vs_.size(); }\n    T* non_zero_values_data() { return vs_.data(); }\n    index* non_zero_indices1_data() { return (index*)is_.data(); }\n    index* non_zero_indices2_data() const { return (index*)js_.data(); }\n    decltype(auto) move_non_zero_values() && { return std::move(vs_); }\n    decltype(auto) move_non_zero_indices1() && { return std::move(is_); }\n    decltype(auto) move_non_zero_indices2() && { return std::move(js_); }\n    void clear()\n    {\n      is_.clear();\n      js_.clear();\n      vs_.clear();\n      cols_ = 0;\n      rows_ = 0;\n    }\n    template<class Pair = std::array<index, 2>, class TT>\n    void emplace(Pair&& indices, TT&& tt)\n    {\n      using std::get;\n      is_.emplace_back(get<0>(std::forward<Pair>(indices)));\n      js_.emplace_back(get<1>(std::forward<Pair>(indices)));\n      vs_.emplace_back(std::forward<TT>(tt));\n    }\n\n  protected:\n    struct row_reference\n    {\n      coo_matrix& self_;\n      index i_;\n      struct element_reference\n      {\n        row_reference& self_;\n        index j_;\n        template<class TT>\n        element_reference&& operator=(TT&& tt) &&\n        {\n          self_.self_.emplace({{self_.i_, j_}}, std::forward<TT>(tt));\n          return std::move(*this);\n        }\n      };\n      using reference = element_reference;\n      reference operator[](index i) && { return reference{*this, i}; }\n    };\n\n  public:\n    using reference = row_reference;\n    reference operator[](index i) { return reference{*this, i}; }\n    friend decltype(auto) size(coo_matrix const& s) { return s.size(); }\n    friend decltype(auto) shape(coo_matrix const& s) { return s.shape(); }\n    friend decltype(auto) clear(coo_matrix& s) { s.clear(); }\n  };\n  /*\ntemplate<class... Ts>\nstd::array<index, 2> index_bases(coo_matrix<Ts...> const&){return {{0,0}};}\ntemplate<class... Ts>\nauto num_non_zero_elements(coo_matrix<Ts...> const& s){\n\treturn s.num_non_zero_elements();\n}\ntemplate<class... Ts>\nauto non_zero_values_data(coo_matrix<Ts...>& s){return s.non_zero_values_data();}\ntemplate<class... Ts>\nauto non_zero_indices1_data(coo_matrix<Ts...>& s){\n\treturn s.non_zero_indices1_data();\n}\ntemplate<class... Ts>\nauto non_zero_indices2_data(coo_matrix<Ts...>& s){\n\treturn s.non_zero_indices2_data();\n}\n*/\n  } // namespace sparse\n}\n\n#ifdef _TEST_SPARSE_COO_MATRIX\n\n#include \"iterator/zipper.hpp\"\n#include \"timer/timed.hpp\"\n\n#include <boost/timer/timer.hpp>\n\n#include <algorithm> // std::sort\n#include <cassert>\n#include <iostream>\n#include <random>\n\nusing std::cerr;\nusing std::cout;\nusing std::get;\n\nint main()\n{\n  using ma::sparse::coo_matrix;\n\n  auto const M          = 40000;\n  auto const N          = 40000;\n  double const sparsity = 0.01;\n\n  // generate tuples for reference\n  auto const csource = [&]() {\n    std::vector<std::tuple<int, int, double>> source;\n    source.reserve(M * N * sparsity);\n    std::default_random_engine gen;\n    std::uniform_real_distribution<double> dist;\n    std::uniform_real_distribution<double> dist2(0, 10);\n    for (auto i = M; i != 0; --i)\n      for (auto j = N; j != 0; --j)\n        if (dist(gen) < sparsity)\n          source.emplace_back(i - 1, j - 1, dist2(gen));\n    return source;\n  }();\n\n  cerr << \"value size \" << csource.size() * sizeof(double) / 1000000 << \" MB\\n\";\n  {\n    coo_matrix<double> coom({M, N});\n    {\n      boost::timer::auto_cpu_timer t(\"ugly syntax: %t seconds\\n\");\n      for (auto& s : csource)\n        coom.emplace({{get<0>(s), get<1>(s)}}, get<2>(s));\n    }\n  }\n  {\n    coo_matrix<double> coom({M, N});\n    {\n      boost::timer::auto_cpu_timer t(\"generic syntax: %t seconds\\n\");\n      for (auto& s : csource)\n        coom[get<0>(s)][get<1>(s)] = get<2>(s);\n    }\n  }\n\n  coo_matrix<double> small({4, 4}, {{{3, 3}, 1}, {{2, 1}, 3}, {{0, 1}, 9}});\n}\n\n#endif\n#endif\n", "meta": {"hexsha": "dc6453a84e899d4ff4f166e7385c97f43392e9be", "size": 5943, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/AFQMC/Matrix/coo_matrix.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/Matrix/coo_matrix.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/Matrix/coo_matrix.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": 29.864321608, "max_line_length": 119, "alphanum_fraction": 0.593639576, "num_tokens": 1625, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5964331462646254, "lm_q2_score": 0.5736784074525096, "lm_q1q2_score": 0.34216081750098004}}
{"text": "/*\n *            Copyright 2009-2018 The VOTCA Development Team\n *                       (http://www.votca.org)\n *\n *      Licensed under the Apache License, Version 2.0 (the \"License\")\n *\n * You may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *              http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n */\n\n\n\n#include <votca/xtp/sigma.h>\n#include <cmath>\n#include <boost/math/constants/constants.hpp>\n#include <votca/tools/constants.h>\n#include <votca/xtp/ppm.h>\n#include <votca/xtp/threecenter.h>\n\n\nnamespace votca {\n  namespace xtp {\n\n    Eigen::MatrixXd Sigma::SetupFullQPHamiltonian() {\n\n      // constructing full QP Hamiltonian\n      Eigen::MatrixXd Hqp = _sigma_x + _sigma_c - (*_vxc);\n      // diagonal elements are given by _qp_energies\n      for (int m = 0; m < Hqp.rows(); m++) {\n        Hqp(m, m) = _gwa_energies(m + _qpmin);\n      }\n      return Hqp;\n    }\n\n    void Sigma::X_diag(const TCMatrix_gwbse& Mmn){\n      int gwsize = Mmn.getAuxDimension(); // size of the GW basis\n      _sigma_x=Eigen::MatrixXd::Zero(_qptotal,_qptotal);\n      #pragma omp parallel for\n      for (int gw_level = 0; gw_level < _qptotal; gw_level++) {\n        const MatrixXfd & Mmn1 = Mmn[ gw_level + _qpmin ];\n        double sigma_x = 0;\n        for (int i_gw = 0; i_gw < gwsize; i_gw++) {\n          // loop over all occupied bands used in screening\n          for (int i_occ = 0; i_occ <= _homo; i_occ++) {\n            sigma_x -= Mmn1( i_occ,i_gw) * Mmn1( i_occ,i_gw);\n          } // occupied bands\n        } // gwbasis functions             \n        _sigma_x(gw_level, gw_level) = (1.0 - _ScaHFX) * sigma_x;\n      }\n    }\n\n    void Sigma::C_diag(const TCMatrix_gwbse& Mmn, const PPM& ppm, const Eigen::VectorXd& qp_old){\n      int levelsum = Mmn.get_ntot(); // total number of bands\n      int gwsize = Mmn.getAuxDimension(); // size of the GW basis\n      \n      // loop over all GW levels\n#pragma omp parallel for\n      for (int gw_level = 0; gw_level < _qptotal; gw_level++) {\n        const MatrixXfd & Mmn1 = Mmn[ gw_level + _qpmin ];\n        const double qpmin = qp_old(gw_level + _qpmin);\n        double sigma_c = 0.0;\n        // loop over all functions in GW basis\n        for (int i_gw = 0; i_gw < gwsize; i_gw++) {\n          // the ppm_weights smaller 1.e-5 are set to zero in rpa.cc PPM_construct_parameters\n          if (ppm.getPpm_weight()(i_gw) < 1.e-9) {\n            continue;\n          }\n          const double ppm_freq = ppm.getPpm_freq()(i_gw);\n          const double fac = 0.5*ppm.getPpm_weight()(i_gw) * ppm_freq;\n          // loop over all bands\n          double sigma_c_loc=0.0;\n          for (int i = 0; i < _homo+1; i++) {\n            const double factor=Stabilize(qpmin - qp_old(i) +ppm_freq);\n            // sigma_c diagonal elements\n            sigma_c_loc += factor * Mmn1(i, i_gw) * Mmn1( i,i_gw);\n          }// bands\n          for (int i = _homo+1; i < levelsum; i++) {\n            const double factor=Stabilize(qpmin - qp_old(i) -ppm_freq);\n            // sigma_c diagonal elements\n            sigma_c_loc += factor * Mmn1(i,i_gw) * Mmn1(i,i_gw);\n          }// bands\n          sigma_c+=sigma_c_loc*fac;\n        }// GW functions\n        _sigma_c(gw_level, gw_level) = sigma_c;\n        // update _qp_energies\n        _gwa_energies(gw_level + _qpmin) = (*_dftenergies)(gw_level + _qpmin) + sigma_c + _sigma_x(gw_level, gw_level) - (*_vxc)(gw_level, gw_level);\n      }// all bands\n    }\n\n    void Sigma::CalcdiagElements(const TCMatrix_gwbse& Mmn, const PPM & ppm) {\n        X_diag(Mmn);\n        if(_gwa_energies.size()<1){\n            throw std::runtime_error(\"Sigma gwa_energies not set!\");\n        }\n      _sigma_c=Eigen::MatrixXd::Zero(_qptotal,_qptotal);\n\n      // initial _qp_energies are dft energies\n      Eigen::VectorXd qp_old = _gwa_energies;\n      // only diagonal elements except for in final iteration\n      for (int g_iter = 0; g_iter < _g_sc_max_iterations; g_iter++) {\n        \n        C_diag(Mmn, ppm, qp_old);\n        Eigen::VectorXd diff = qp_old - _gwa_energies;\n        bool energies_converged = true;\n\n        int state = 0;\n        double diff_max = diff.cwiseAbs().maxCoeff(&state);\n        if (diff_max > _g_sc_limit) {\n          energies_converged = false;\n        }\n\n        if (tools::globals::verbose) {\n          double _DFTgap = (*_dftenergies)(_homo + 1) - (*_dftenergies)(_homo);\n          double _QPgap = _gwa_energies(_homo + 1) - _gwa_energies(_homo);\n          CTP_LOG(ctp::logDEBUG, *_log) << ctp::TimeStamp() << \" G_Iteration: \" << g_iter + 1 << \" shift=\" << _QPgap - _DFTgap << \" E_diff max=\" << diff_max << \" StateNo:\" << state << std::flush;\n        }\n        double alpha = 0.0;\n        _gwa_energies = (1 - alpha) * _gwa_energies + alpha*qp_old;\n\n        if (energies_converged) {\n          CTP_LOG(ctp::logDEBUG, *_log) << ctp::TimeStamp() << \" Converged after \" << g_iter + 1 << \" G iterations.\" << std::flush;\n          break;\n        } else if (g_iter == _g_sc_max_iterations - 1) {\n          CTP_LOG(ctp::logDEBUG, *_log) << ctp::TimeStamp() << \" G-self-consistency cycle not converged after \" << _g_sc_max_iterations << \" iterations.\" << std::flush;\n          break;\n\n        } else {\n          qp_old = _gwa_energies;\n        }\n      } // iterations\n      return;\n    }\n\n    void Sigma::X_offdiag(const TCMatrix_gwbse& Mmn){\n      int gwsize = Mmn.getAuxDimension();\n      #pragma omp parallel for schedule(dynamic)\n      for (int gw_level1 = 0; gw_level1 < _qptotal; gw_level1++) {\n        const MatrixXfd& Mmn1 = Mmn[ gw_level1 + _qpmin ];\n        for (int gw_level2 = gw_level1+1; gw_level2 < _qptotal; gw_level2++) {\n          const MatrixXfd & Mmn2 = Mmn[ gw_level2 + _qpmin ];\n          double sigma_x = 0;\n          for (int i_gw = 0; i_gw < gwsize; i_gw++) {\n            // loop over all occupied bands used in screening\n            for (int i_occ = 0; i_occ <= _homo; i_occ++) {\n              sigma_x -= Mmn1(i_occ,i_gw) * Mmn2(i_occ,i_gw);\n            } // occupied bands\n          } // gwbasis functions\n          _sigma_x(gw_level1, gw_level2) = (1.0 - _ScaHFX) * sigma_x;\n          _sigma_x(gw_level2, gw_level1) = (1.0 - _ScaHFX) * sigma_x;\n        }\n      }\n      return;\n    }\n\n    double Sigma::Stabilize(double denom){\n      const double fourpi = 4*boost::math::constants::pi<double>();\n      double stab = 1.0;\n      if (std::abs(denom) < 0.25) {\n        stab = 0.5 * (1.0 - std::cos(fourpi * denom));\n      }\n      return stab / denom;\n    }\n\n    double Sigma::SumSymmetric(real_gwbse Mmn1xMmn2, double qpmin1, double qpmin2, double gwa_energy){\n      double factor=Stabilize(qpmin1 - gwa_energy);\n      factor+= Stabilize(qpmin2 - gwa_energy);\n      return Mmn1xMmn2 * factor;\n    }\n\n    void Sigma::C_offdiag(const TCMatrix_gwbse& Mmn, const PPM& ppm){\n\n      #pragma omp parallel \n      {\n        int lumo=_homo+1;\n        const int levelsum = Mmn.get_ntot(); // total number of bands\n        const int gwsize = Mmn.getAuxDimension(); // size of the GW basis\n        const Eigen::VectorXd ppm_weight=ppm.getPpm_weight();\n        const Eigen::VectorXd ppm_freqs=ppm.getPpm_freq();\n        #pragma omp for schedule(dynamic)\n        for (int gw_level1 = 0; gw_level1 < _qptotal; gw_level1++) {\n        const MatrixXfd& Mmn1=Mmn[ gw_level1 + _qpmin ];\n        for (int gw_level2 = gw_level1+1; gw_level2 < _qptotal; gw_level2++) {\n          const MatrixXfd Mmn1xMmn2=Mmn[ gw_level2 + _qpmin ].cwiseProduct(Mmn1);\n          const Eigen::VectorXd gwa_energies=_gwa_energies;\n          const double qpmin1 = gwa_energies(gw_level1 + _qpmin);\n          const double qpmin2 = gwa_energies(gw_level2 + _qpmin);\n \n          double sigma_c=0;\n          for (int i_gw = 0; i_gw < gwsize; i_gw++) {\n            // the ppm_weights smaller 1.e-5 are set to zero in rpa.cc PPM_construct_parameters\n            if (ppm_weight(i_gw) < 1.e-9) {\n              continue;\n            }\n            const double ppm_freq= ppm_freqs(i_gw);\n            const double fac = 0.25* ppm_weight(i_gw) * ppm_freq;\n            double sigma_loc=0.0;\n            // loop over occ screening levels\n              for (int i = 0; i < lumo; i++) {\n                const double gwa_energy = gwa_energies(i) - ppm_freq;\n                sigma_loc+=SumSymmetric(Mmn1xMmn2(i,i_gw), qpmin1, qpmin2, gwa_energy);\n              }\n              // loop over unocc screening levels\n              for (int i = lumo; i < levelsum; i++) {\n                const double gwa_energy = gwa_energies(i) + ppm_freq;\n                sigma_loc+=SumSymmetric(Mmn1xMmn2(i,i_gw), qpmin1, qpmin2, gwa_energy);\n              }\n              sigma_c += sigma_loc*fac;\n            }\n          _sigma_c(gw_level1, gw_level2) = sigma_c;\n          _sigma_c(gw_level2, gw_level1) = sigma_c;\n        }// GW row             \n      }//GW col\n      }\n      \n      return;\n    }\n\n    void Sigma::CalcOffDiagElements(const TCMatrix_gwbse& Mmn, const PPM & ppm) {\n     \n      X_offdiag(Mmn);\n      C_offdiag(Mmn, ppm);\n\n      return;\n    }\n\n  }\n};\n", "meta": {"hexsha": "7a3c30911c840b026a0de7c0cce7acb6450468e0", "size": 9344, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/libxtp/gwbse/sigma.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/sigma.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/sigma.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.4261603376, "max_line_length": 195, "alphanum_fraction": 0.5891481164, "num_tokens": 2771, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7745833841649233, "lm_q2_score": 0.4416730056646256, "lm_q1q2_score": 0.342112571421999}}
{"text": "\n\n#include <ripple/basics/contract.h>\n#include <ripple/protocol/IOUAmount.h>\n#include <boost/multiprecision/cpp_int.hpp>\n#include <algorithm>\n#include <numeric>\n#include <iterator>\n#include <stdexcept>\n\nnamespace ripple {\n\n\nstatic std::int64_t const minMantissa = 1000000000000000ull;\nstatic std::int64_t const maxMantissa = 9999999999999999ull;\n\nstatic int const minExponent = -96;\nstatic int const maxExponent = 80;\n\nvoid\nIOUAmount::normalize ()\n{\n    if (mantissa_ == 0)\n    {\n        *this = beast::zero;\n        return;\n    }\n\n    bool const negative = (mantissa_ < 0);\n\n    if (negative)\n        mantissa_ = -mantissa_;\n\n    while ((mantissa_ < minMantissa) && (exponent_ > minExponent))\n    {\n        mantissa_ *= 10;\n        --exponent_;\n    }\n\n    while (mantissa_ > maxMantissa)\n    {\n        if (exponent_ >= maxExponent)\n            Throw<std::overflow_error> (\"IOUAmount::normalize\");\n\n        mantissa_ /= 10;\n        ++exponent_;\n    }\n\n    if ((exponent_ < minExponent) || (mantissa_ < minMantissa))\n    {\n        *this = beast::zero;\n        return;\n    }\n\n    if (exponent_ > maxExponent)\n        Throw<std::overflow_error> (\"value overflow\");\n\n    if (negative)\n        mantissa_ = -mantissa_;\n}\n\nIOUAmount&\nIOUAmount::operator+= (IOUAmount const& other)\n{\n    if (other == beast::zero)\n        return *this;\n\n    if (*this == beast::zero)\n    {\n        *this = other;\n        return *this;\n    }\n\n    auto m = other.mantissa_;\n    auto e = other.exponent_;\n\n    while (exponent_ < e)\n    {\n        mantissa_ /= 10;\n        ++exponent_;\n    }\n\n    while (e < exponent_)\n    {\n        m /= 10;\n        ++e;\n    }\n\n    mantissa_ += m;\n\n    if (mantissa_ >= -10 && mantissa_ <= 10)\n    {\n        *this = beast::zero;\n        return *this;\n    }\n\n    normalize ();\n\n    return *this;\n}\n\nbool\nIOUAmount::operator<(IOUAmount const& other) const\n{\n    bool const lneg = mantissa_ < 0;\n    bool const rneg = other.mantissa_ < 0;\n\n    if (lneg != rneg)\n        return lneg;\n\n    if (mantissa_ == 0)\n        return other.mantissa_ > 0;\n\n    if (other.mantissa_ == 0)\n        return false;\n\n    if (exponent_ > other.exponent_)\n        return lneg;\n    if (exponent_ < other.exponent_)\n        return !lneg;\n\n    return mantissa_ < other.mantissa_;\n}\n\nstd::string\nto_string (IOUAmount const& amount)\n{\n    if (amount == beast::zero)\n        return \"0\";\n\n    int const exponent = amount.exponent ();\n    auto mantissa = amount.mantissa ();\n\n    if (((exponent != 0) && ((exponent < -25) || (exponent > -5))))\n    {\n        std::string ret = std::to_string (mantissa);\n        ret.append (1, 'e');\n        ret.append (std::to_string (exponent));\n        return ret;\n    }\n\n    bool negative = false;\n\n    if (mantissa < 0)\n    {\n        mantissa = -mantissa;\n        negative = true;\n    }\n\n    assert (exponent + 43 > 0);\n\n    size_t const pad_prefix = 27;\n    size_t const pad_suffix = 23;\n\n    std::string const raw_value (std::to_string (mantissa));\n    std::string val;\n\n    val.reserve (raw_value.length () + pad_prefix + pad_suffix);\n    val.append (pad_prefix, '0');\n    val.append (raw_value);\n    val.append (pad_suffix, '0');\n\n    size_t const offset (exponent + 43);\n\n    auto pre_from (val.begin ());\n    auto const pre_to (val.begin () + offset);\n\n    auto const post_from (val.begin () + offset);\n    auto post_to (val.end ());\n\n    if (std::distance (pre_from, pre_to) > pad_prefix)\n        pre_from += pad_prefix;\n\n    assert (post_to >= post_from);\n\n    pre_from = std::find_if (pre_from, pre_to,\n        [](char c)\n        {\n            return c != '0';\n        });\n\n    if (std::distance (post_from, post_to) > pad_suffix)\n        post_to -= pad_suffix;\n\n    assert (post_to >= post_from);\n\n    post_to = std::find_if(\n        std::make_reverse_iterator (post_to),\n        std::make_reverse_iterator (post_from),\n        [](char c)\n        {\n            return c != '0';\n        }).base();\n\n    std::string ret;\n\n    if (negative)\n        ret.append (1, '-');\n\n    if (pre_from == pre_to)\n        ret.append (1, '0');\n    else\n        ret.append(pre_from, pre_to);\n\n    if (post_to != post_from)\n    {\n        ret.append (1, '.');\n        ret.append (post_from, post_to);\n    }\n\n    return ret;\n}\n\nIOUAmount\nmulRatio (\n    IOUAmount const& amt,\n    std::uint32_t num,\n    std::uint32_t den,\n    bool roundUp)\n{\n    using namespace boost::multiprecision;\n\n    if (!den)\n        Throw<std::runtime_error> (\"division by zero\");\n\n    static auto const powerTable = []\n    {\n        std::vector<uint128_t> result;\n        result.reserve (30);  \n        uint128_t cur (1);\n        for (int i = 0; i < 30; ++i)\n        {\n            result.push_back (cur);\n            cur *= 10;\n        };\n        return result;\n    }();\n\n    static auto log10Floor = [](uint128_t const& v)\n    {\n        auto const l = std::lower_bound (powerTable.begin (), powerTable.end (), v);\n        int index = std::distance (powerTable.begin (), l);\n        if (*l != v)\n            --index;\n        return index;\n    };\n\n    static auto log10Ceil = [](uint128_t const& v)\n    {\n        auto const l = std::lower_bound (powerTable.begin (), powerTable.end (), v);\n        return int(std::distance (powerTable.begin (), l));\n    };\n\n    static auto const fl64 =\n        log10Floor (std::numeric_limits<std::int64_t>::max ());\n\n    bool const neg = amt.mantissa () < 0;\n    uint128_t const den128 (den);\n    uint128_t const mul =\n        uint128_t (neg ? -amt.mantissa () : amt.mantissa ()) * uint128_t (num);\n\n    auto low = mul / den128;\n    uint128_t rem (mul - low * den128);\n\n    int exponent = amt.exponent ();\n\n    if (rem)\n    {\n        auto const roomToGrow = fl64 - log10Ceil (low);\n        if (roomToGrow > 0)\n        {\n            exponent -= roomToGrow;\n            low *= powerTable[roomToGrow];\n            rem *= powerTable[roomToGrow];\n        }\n        auto const addRem = rem / den128;\n        low += addRem;\n        rem = rem - addRem * den128;\n    }\n\n    bool hasRem = bool(rem);\n    auto const mustShrink = log10Ceil (low) - fl64;\n    if (mustShrink > 0)\n    {\n        uint128_t const sav (low);\n        exponent += mustShrink;\n        low /= powerTable[mustShrink];\n        if (!hasRem)\n            hasRem = bool(sav - low * powerTable[mustShrink]);\n    }\n\n    std::int64_t mantissa = low.convert_to<std::int64_t> ();\n\n    if (neg)\n        mantissa *= -1;\n\n    IOUAmount result (mantissa, exponent);\n\n    if (hasRem)\n    {\n        if (roundUp && !neg)\n        {\n            if (!result)\n            {\n                return IOUAmount (minMantissa, minExponent);\n            }\n            return IOUAmount (result.mantissa () + 1, result.exponent ());\n        }\n\n        if (!roundUp && neg)\n        {\n            if (!result)\n            {\n                return IOUAmount (-minMantissa, minExponent);\n            }\n            return IOUAmount (result.mantissa () - 1, result.exponent ());\n        }\n    }\n\n    return result;\n}\n\n\n}\n\n\n\n\n\n\n", "meta": {"hexsha": "d799cb17146c18264328e906e7f314661e25e15c", "size": 6956, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/dfm/protocol/impl/IOUAmount.cpp", "max_stars_repo_name": "dfm-official/dfm", "max_stars_repo_head_hexsha": "97f133aa87b17c760b90f2358d6ba10bc7ad9d1f", "max_stars_repo_licenses": ["ISC"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/dfm/protocol/impl/IOUAmount.cpp", "max_issues_repo_name": "dfm-official/dfm", "max_issues_repo_head_hexsha": "97f133aa87b17c760b90f2358d6ba10bc7ad9d1f", "max_issues_repo_licenses": ["ISC"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/dfm/protocol/impl/IOUAmount.cpp", "max_forks_repo_name": "dfm-official/dfm", "max_forks_repo_head_hexsha": "97f133aa87b17c760b90f2358d6ba10bc7ad9d1f", "max_forks_repo_licenses": ["ISC"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.0151057402, "max_line_length": 84, "alphanum_fraction": 0.5451408856, "num_tokens": 1903, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6584175139669997, "lm_q2_score": 0.519521321952093, "lm_q1q2_score": 0.3420619372525463}}
{"text": "// Copyright 2020 Makani Technologies LLC\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//      http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\n#include \"sim/math/ode_solver_odeint.h\"\n\n#include <glog/logging.h>\n#include <boost/numeric/odeint.hpp>\n#include <boost/ref.hpp>\n\n#include <algorithm>\n#include <exception>\n#include <vector>\n\n#include \"sim/math/ode_solver.h\"\n\nnamespace odeint = boost::numeric::odeint;\n\nnamespace sim {\n\nOdeSolverStatus OdeIntOdeSolver::Integrate(double t0, double tf,\n                                           const std::vector<double> &x0,\n                                           double *t_int,\n                                           std::vector<double> *x) {\n  std::copy(x0.begin(), x0.end(), x->begin());\n  try {\n    odeint::runge_kutta_cash_karp54<std::vector<double>> stepper;\n    odeint::integrate_adaptive(\n        odeint::make_controlled(params_.abs_tolerance, params_.rel_tolerance,\n                                stepper),\n        boost::ref(*this), *x, t0, tf, params_.initial_time_step);\n    if (t_int != nullptr) {\n      *t_int = tf;\n    }\n  } catch (std::exception &ex) {\n    LOG(ERROR) << \"odeint reported an error: \" << ex.what();\n    return OdeSolverStatus::kError;\n  }\n  return OdeSolverStatus::kSuccess;\n}\n\nvoid OdeIntOdeSolver::operator()(\n    const std::vector<double> &x,\n    std::vector<double> &dx,  // NOLINT(runtime/references)\n    double t) {\n  ode_system_.CalcDerivatives(t, x, &dx);\n}\n\n}  // namespace sim\n", "meta": {"hexsha": "46d053ee5585385c9277d3cbaf34bc5f54fa36df", "size": 1928, "ext": "cc", "lang": "C++", "max_stars_repo_path": "sim/math/ode_solver_odeint.cc", "max_stars_repo_name": "leozz37/makani", "max_stars_repo_head_hexsha": "c94d5c2b600b98002f932e80a313a06b9285cc1b", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1178.0, "max_stars_repo_stars_event_min_datetime": "2020-09-10T17:15:42.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T14:59:35.000Z", "max_issues_repo_path": "sim/math/ode_solver_odeint.cc", "max_issues_repo_name": "leozz37/makani", "max_issues_repo_head_hexsha": "c94d5c2b600b98002f932e80a313a06b9285cc1b", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-05-22T05:22:35.000Z", "max_issues_repo_issues_event_max_datetime": "2020-05-22T05:22:35.000Z", "max_forks_repo_path": "sim/math/ode_solver_odeint.cc", "max_forks_repo_name": "leozz37/makani", "max_forks_repo_head_hexsha": "c94d5c2b600b98002f932e80a313a06b9285cc1b", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 107.0, "max_forks_repo_forks_event_min_datetime": "2020-09-10T17:29:30.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-18T09:00:14.000Z", "avg_line_length": 32.1333333333, "max_line_length": 77, "alphanum_fraction": 0.6462655602, "num_tokens": 470, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.658417500561683, "lm_q2_score": 0.519521321952093, "lm_q1q2_score": 0.3420619302881985}}
{"text": "#pragma once\n\n#include <Eigen/Core>\n#include <Eigen/Sparse>\n#include <iostream>\n#include <utility>\n#include <vector>\n\n#include \"aux/filtered_range.hpp\"\n#include \"enum/enum.hpp\"\n#include \"spectral/basis/toolbox/spectral_basis.hpp\"\n\n\nnamespace boltzmann {\n\n// ----------------------------------------------------------------------\ntemplate <typename SPECTRAL_BASIS>\nclass RotateBasis\n{\n private:\n  typedef SPECTRAL_BASIS basis_t;\n  typedef typename basis_t::index_t index_t;\n\n public:\n  RotateBasis(const SPECTRAL_BASIS& basis)\n      : basis_(basis)\n  {\n    this->init();\n  }\n\n  void init();\n\n  /**\n   * @brief rotate in counter clockwise direction\n   *\n   * @param out\n   * @param in\n   * @param phi angle\n   * @param L number of repetitions\n   */\n  template <typename NUMERIC>\n  void apply(NUMERIC* out, const NUMERIC* in, const double phi, const int L = 1) const;\n\n private:\n  const basis_t& basis_;\n  Eigen::SparseMatrix<double> R_;\n\n  // internal variable\n  mutable double theta_;\n\n  typedef int a_freq;  // angular frequency\n  std::unordered_map<a_freq, std::vector<std::pair<index_t, index_t> > > v_pairs_;\n\n  // those elements who do not depend on the angular index `l` need just to be copied\n  std::vector<index_t> v_copy_;\n\n  int l_max;\n};\n\n// ----------------------------------------------------------------------\ntemplate <typename SPECTRAL_BASIS>\nvoid\nRotateBasis<SPECTRAL_BASIS>::init()\n{\n  int N = basis_.n_dofs();\n  R_.resize(N, N);\n  l_max = spectral::get_max_l(basis_);\n\n  typedef typename basis_t::elem_t elem_t;\n  typedef typename basis_t::index_t index_t;\n\n  typedef typename boost::mpl::at_c<typename elem_t::types_t, 1>::type radial_elem_t;\n  typedef typename boost::mpl::at_c<typename elem_t::types_t, 0>::type ang_elem_t;\n\n  typename elem_t::Acc::template get<radial_elem_t> get_rad;\n  typename elem_t::Acc::template get<ang_elem_t> get_ang;\n\n  {\n    // im cos(0*phi) elements do not change, append their\n    // indices to the v_copy_ array.\n    std::function<bool(const elem_t&)> pred = [&](const elem_t& e) {\n      return (get_ang(e).get_id().l == 0);\n    };\n    auto range = filtered_range(basis_.begin(), basis_.end(), pred);\n\n    auto begin = std::get<0>(range);\n    auto end = std::get<1>(range);\n    for (auto it = begin; it != end; ++it) {\n      v_copy_.push_back(basis_.get_dof_index(it->get_id()));\n    }\n  }\n\n  for (int l = 1; l <= l_max; ++l) {\n    std::function<bool(const elem_t&)> pred = [&](const elem_t& e) {\n      return (get_ang(e).get_id().l == l);\n    };\n    auto range = filtered_range(basis_.begin(), basis_.end(), pred);\n    auto begin = std::get<0>(range);\n    auto end = std::get<1>(range);\n\n    for (auto it = begin; it != end; ++it) {\n      auto ang_elem = get_ang(*it);\n      auto rad_elem = get_rad(*it);\n\n      typedef std::vector<std::pair<index_t, index_t> > vec_t;\n\n      if (ang_elem.get_id().t == SIN) {\n        index_t i_sin = basis_.get_dof_index(it->get_id());\n        ang_elem_t cos_elem(COS, l);\n        elem_t elem2(cos_elem, rad_elem);\n        index_t i_cos = basis_.get_dof_index(elem2.get_id());\n\n        auto search = v_pairs_.find(l);\n        if (search == v_pairs_.end()) {\n          v_pairs_[l] = vec_t({std::make_pair(i_cos, i_sin)});\n        } else {\n          v_pairs_[l].push_back(std::make_pair(i_cos, i_sin));\n        }\n      }\n    }\n  }\n}\n\n// ----------------------------------------------------------------------\ntemplate <typename SPECTRAL_BASIS>\ntemplate <typename NUMERIC>\nvoid\nRotateBasis<SPECTRAL_BASIS>::apply(NUMERIC* out,\n                                   const NUMERIC* in,\n                                   const double phi,\n                                   const int L) const\n{\n  typedef NUMERIC numeric_t;\n  const unsigned int N = basis_.n_dofs();\n\n  Eigen::VectorXd vsin(l_max + 1);\n  Eigen::VectorXd vcos(l_max + 1);\n\n  for (int i = 0; i <= l_max; ++i) {\n    vsin[i] = std::sin(-i * phi);\n    vcos[i] = std::cos(i * phi);\n  }\n\n  //#pragma omp parallel for\n  for (int ix = 0; ix < L; ++ix) {\n    numeric_t* p_out = out + ix * N;\n    const numeric_t* p_in = in + ix * N;\n\n    // walk through v_copy_\n    for (auto& i : v_copy_) {\n      p_out[i] = p_in[i];\n    }\n\n    // apply the rotation\n    for (auto it = v_pairs_.begin(); it != v_pairs_.end(); ++it) {\n      int l = it->first;\n\n      const double rcos = vcos[l];\n      const double rsin = vsin[l];\n\n      for (auto it_v = it->second.begin(); it_v != it->second.end(); ++it_v) {\n        index_t i_cos = it_v->first;\n        index_t i_sin = it_v->second;\n\n        p_out[i_sin] = p_in[i_sin] * rcos - p_in[i_cos] * rsin;\n        p_out[i_cos] = p_in[i_sin] * rsin + p_in[i_cos] * rcos;\n      }\n    }\n  }\n}\n\n}  // end namespace\n", "meta": {"hexsha": "ed8169d4fa3a92745a62d8a2ce60b8a3cd59c16a", "size": 4673, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/spectral/rotate_basis.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/spectral/rotate_basis.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/spectral/rotate_basis.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": 27.0115606936, "max_line_length": 87, "alphanum_fraction": 0.584635138, "num_tokens": 1308, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.600188359260205, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.34201892787234045}}
{"text": "// Copyright (C) 2013  Davis E. King (davis@dlib.net)\n// License: Boost Software License   See LICENSE.txt for the full license.\n\n#include \"opaque_types.h\"\n#include <dlib/python.h>\n#include <dlib/matrix.h>\n#include <dlib/geometry.h>\n#include <dlib/image_transforms.h>\n#include <pybind11/stl_bind.h>\n#include \"indexing.h\"\n\nusing namespace dlib;\nusing namespace std;\n\ntypedef matrix<double,0,1> cv;\n\n\nvoid cv_set_size(cv& m, long s)\n{\n    m.set_size(s);\n    m = 0;\n}\n\ndouble dotprod ( const cv& a, const cv& b)\n{\n    return dot(a,b);\n}\n\nstring cv__str__(const cv& v)\n{\n    ostringstream sout;\n    for (long i = 0; i < v.size(); ++i)\n    {\n        sout << v(i);\n        if (i+1 < v.size())\n            sout << \"\\n\";\n    }\n    return sout.str();\n}\n\nstring cv__repr__ (const cv& v)\n{\n    std::ostringstream sout;\n    sout << \"dlib.vector([\";\n    for (long i = 0; i < v.size(); ++i)\n    {\n        sout << v(i);\n        if (i+1 < v.size())\n            sout << \", \";\n    }\n    sout << \"])\";\n    return sout.str();\n}\n\nstd::shared_ptr<cv> cv_from_object(py::object obj)\n{\n    try {\n        long nr = obj.cast<long>();\n        auto temp = std::make_shared<cv>(nr);\n        *temp = 0;\n        return temp;\n    } catch(py::cast_error&) {\n        py::list li = obj.cast<py::list>();\n        const long nr = len(obj);\n        auto temp = std::make_shared<cv>(nr);\n        for ( long r = 0; r < nr; ++r)\n        {\n            (*temp)(r) = li[r].cast<double>();\n        }\n        return temp;\n    }\n}\n\nlong cv__len__(cv& c)\n{\n    return c.size();\n}\n\n\nvoid cv__setitem__(cv& c, long p, double val)\n{\n    if (p < 0) {\n        p = c.size() + p; // negative index\n    }\n    if (p > c.size()-1) {\n        PyErr_SetString( PyExc_IndexError, \"index out of range\"\n        );\n        throw py::error_already_set();\n    }\n    c(p) = val;\n}\n\ndouble cv__getitem__(cv& m, long r)\n{\n    if (r < 0) {\n        r = m.size() + r; // negative index\n    }\n    if (r > m.size()-1 || r < 0) {\n        PyErr_SetString( PyExc_IndexError, \"index out of range\"\n        );\n        throw py::error_already_set();\n    }\n    return m(r);\n}\n\n\ncv cv__getitem2__(cv& m, py::slice r)\n{\n    size_t start, stop, step, slicelength;\n    if (!r.compute(m.size(), &start, &stop, &step, &slicelength))\n        throw py::error_already_set();\n\n    cv temp(slicelength);\n\n    for (size_t i = 0; i < slicelength; ++i) {\n         temp(i) = m(start); start += step;\n    }\n    return temp;\n}\n\npy::tuple cv_get_matrix_size(cv& m)\n{\n    return py::make_tuple(m.nr(), m.nc());\n}\n\n// ----------------------------------------------------------------------------------------\n\nstring point_transform_projective__repr__ (const point_transform_projective& tform)\n{\n    std::ostringstream sout;\n    sout << \"point_transform_projective(\\n\" << csv << tform.get_m() << \")\";\n    return sout.str();\n}\n\nstring point_transform_projective__str__(const point_transform_projective& tform)\n{\n    std::ostringstream sout;\n    sout << \"(\" << csv << tform.get_m() << \")\";\n    return sout.str();\n}\n\npoint_transform_projective init_point_transform_projective (\n    const numpy_image<double>& m_\n)\n{\n    const_image_view<numpy_image<double>> m(m_);\n    DLIB_CASSERT(m.nr() == 3 && m.nc() == 3,\n        \"The matrix used to construct a point_transform_projective object must be 3x3.\");\n\n    return point_transform_projective(mat(m));\n}\n\n// ----------------------------------------------------------------------------------------\n\nstring point__repr__ (const point& p)\n{\n    std::ostringstream sout;\n    sout << \"point(\" << p.x() << \", \" << p.y() << \")\";\n    return sout.str();\n}\n\nstring point__str__(const point& p)\n{\n    std::ostringstream sout;\n    sout << \"(\" << p.x() << \", \" << p.y() << \")\";\n    return sout.str();\n}\n\nstring dpoint__repr__ (const dpoint& p)\n{\n    std::ostringstream sout;\n    sout << \"dpoint(\" << p.x() << \", \" << p.y() << \")\";\n    return sout.str();\n}\n\nstring dpoint__str__(const dpoint& p)\n{\n    std::ostringstream sout;\n    sout << \"(\" << p.x() << \", \" << p.y() << \")\";\n    return sout.str();\n}\n\nlong point_x(const point& p) { return p.x(); }\nlong point_y(const point& p) { return p.y(); }\ndouble dpoint_x(const dpoint& p) { return p.x(); }\ndouble dpoint_y(const dpoint& p) { return p.y(); }\n\n// ----------------------------------------------------------------------------------------\n\ntemplate <typename T>\ndlib::vector<T,2> numpy_to_dlib_vect (\n    const py::array_t<T>& v\n)\n/*!\n    ensures\n        - converts a numpy array with 2 elements into a dlib::vector<T,2>\n!*/\n{\n    DLIB_CASSERT(v.size() == 2, \"You can only convert a numpy array to a dlib point or dpoint if it has just 2 elements.\");\n    DLIB_CASSERT(v.ndim() == 1 || v.ndim() == 2, \"The input needs to be interpretable as a row or column vector.\");\n    dpoint temp;\n    if (v.ndim() == 1)\n    {\n        temp.x() = v.at(0);\n        temp.y() = v.at(1);\n    }\n    else if (v.shape(0) == 2)\n    {\n        temp.x() = v.at(0,0);\n        temp.y() = v.at(1,0);\n    }\n    else\n    {\n        temp.x() = v.at(0,0);\n        temp.y() = v.at(0,1);\n    }\n    return temp;\n}\n\n// ----------------------------------------------------------------------------------------\n\npoint_transform_projective py_find_projective_transform (\n    const std::vector<dpoint>& from_points,\n    const std::vector<dpoint>& to_points\n)\n{\n    DLIB_CASSERT(from_points.size() == to_points.size(),\n        \"from_points and to_points must have the same number of points.\");\n    DLIB_CASSERT(from_points.size() >= 4, \n        \"You need at least 4 points to find a projective transform.\");\n    return find_projective_transform(from_points, to_points);\n}\n\ntemplate <typename T>\npoint_transform_projective py_find_projective_transform2 (\n    const numpy_image<T>& from_points_,\n    const numpy_image<T>& to_points_\n)\n{\n    const_image_view<numpy_image<T>> from_points(from_points_);\n    const_image_view<numpy_image<T>> to_points(to_points_);\n\n    DLIB_CASSERT(from_points.nc() == 2 && to_points.nc() == 2, \n        \"Both from_points and to_points must be arrays with 2 columns.\");\n    DLIB_CASSERT(from_points.nr() == to_points.nr(),\n        \"from_points and to_points must have the same number of rows.\");\n    DLIB_CASSERT(from_points.nr() >= 4, \n        \"You need at least 4 rows in the input matrices to find a projective transform.\");\n                 \n    std::vector<dpoint> from, to;\n    for (long r = 0; r < from_points.nr(); ++r)\n    {\n        from.push_back(dpoint(from_points[r][0], from_points[r][1]));\n        to.push_back(dpoint(to_points[r][0], to_points[r][1]));\n    }\n\n    return find_projective_transform(from, to);\n}\n\n// ----------------------------------------------------------------------------------------\n\nvoid register_point_transform_projective(\n    py::module& m\n)\n{\n                \n    py::class_<point_transform_projective>(m, \"point_transform_projective\", \n        \"This is an object that takes 2D points and applies a projective transformation to them.\")\n            .def(py::init<>(),\n\"ensures \\n\\\n    - This object will perform the identity transform.  That is, given a point \\n\\\n      as input it will return the same point as output.  Therefore, self.m == a 3x3 identity matrix.\" \n        /*!\n            ensures\n                - This object will perform the identity transform.  That is, given a point\n                  as input it will return the same point as output.  Therefore, self.m == a 3x3 identity matrix.\n        !*/\n                )\n            .def(py::init<>(&init_point_transform_projective), py::arg(\"m\"),\n\"ensures \\n\\\n    - self.m == m\" \n                )\n            .def(\"__repr__\", &point_transform_projective__repr__)\n            .def(\"__str__\", &point_transform_projective__str__)\n            .def(\"__call__\", [](const point_transform_projective& tform, const dpoint& p){return tform(p);}, py::arg(\"p\"),\n\"ensures \\n\\\n    - Applies the projective transformation defined by this object's constructor \\n\\\n      to p and returns the result.  To define this precisely: \\n\\\n        - let p_h == the point p in homogeneous coordinates.  That is: \\n\\\n            - p_h.x == p.x \\n\\\n            - p_h.y == p.y \\n\\\n            - p_h.z == 1  \\n\\\n        - let x == m*p_h  \\n\\\n        - Then this function returns the value x/x.z\" \n        /*!\n            ensures\n                - Applies the projective transformation defined by this object's constructor\n                  to p and returns the result.  To define this precisely:\n                    - let p_h == the point p in homogeneous coordinates.  That is:\n                        - p_h.x == p.x\n                        - p_h.y == p.y\n                        - p_h.z == 1 \n                    - let x == m*p_h \n                    - Then this function returns the value x/x.z\n        !*/\n                )\n            .def_property_readonly(\"m\", [](const point_transform_projective& tform){numpy_image<double> tmp; assign_image(tmp,tform.get_m()); return tmp;},\n                \"m is the 3x3 matrix that defines the projective transformation.\")\n            .def(py::pickle(&getstate<point_transform_projective>, &setstate<point_transform_projective>));\n\n\n    m.def(\"inv\", [](const point_transform_projective& tform){return inv(tform); }, py::arg(\"trans\"),\n\"ensures \\n\\\n    - If trans is an invertible transformation then this function returns a new \\n\\\n      transformation that is the inverse of trans. \" \n    /*!\n        ensures\n            - If trans is an invertible transformation then this function returns a new\n              transformation that is the inverse of trans. \n    !*/\n        );\n\n\n    m.def(\"find_projective_transform\", &py_find_projective_transform, py::arg(\"from_points\"), py::arg(\"to_points\"),\n\"requires \\n\\\n    - len(from_points) == len(to_points) \\n\\\n    - len(from_points) >= 4 \\n\\\nensures \\n\\\n    - returns a point_transform_projective object, T, such that for all valid i: \\n\\\n        length(T(from_points[i]) - to_points[i]) \\n\\\n      is minimized as often as possible.  That is, this function finds the projective \\n\\\n      transform that maps points in from_points to points in to_points.  If no \\n\\\n      projective transform exists which performs this mapping exactly then the one \\n\\\n      which minimizes the mean squared error is selected. \" \n    /*!\n        requires\n            - len(from_points) == len(to_points)\n            - len(from_points) >= 4\n        ensures\n            - returns a point_transform_projective object, T, such that for all valid i:\n                length(T(from_points[i]) - to_points[i])\n              is minimized as often as possible.  That is, this function finds the projective\n              transform that maps points in from_points to points in to_points.  If no\n              projective transform exists which performs this mapping exactly then the one\n              which minimizes the mean squared error is selected. \n    !*/\n        );\n\n    const char* docs = \n\"requires \\n\\\n    - from_points and to_points have two columns and the same number of rows. \\n\\\n      Moreover, they have at least 4 rows. \\n\\\nensures \\n\\\n    - returns a point_transform_projective object, T, such that for all valid i: \\n\\\n        length(T(dpoint(from_points[i])) - dpoint(to_points[i])) \\n\\\n      is minimized as often as possible.  That is, this function finds the projective \\n\\\n      transform that maps points in from_points to points in to_points.  If no \\n\\\n      projective transform exists which performs this mapping exactly then the one \\n\\\n      which minimizes the mean squared error is selected. \";\n    /*!\n        requires\n            - from_points and to_points have two columns and the same number of rows.\n              Moreover, they have at least 4 rows.\n        ensures\n            - returns a point_transform_projective object, T, such that for all valid i:\n                length(T(dpoint(from_points[i])) - dpoint(to_points[i]))\n              is minimized as often as possible.  That is, this function finds the projective\n              transform that maps points in from_points to points in to_points.  If no\n              projective transform exists which performs this mapping exactly then the one\n              which minimizes the mean squared error is selected. \n    !*/\n    m.def(\"find_projective_transform\", &py_find_projective_transform2<float>, py::arg(\"from_points\"), py::arg(\"to_points\"), docs);\n    m.def(\"find_projective_transform\", &py_find_projective_transform2<double>, py::arg(\"from_points\"), py::arg(\"to_points\"), docs);\n\n}\n\n// ----------------------------------------------------------------------------------------\n\ndouble py_polygon_area(\n    const std::vector<dpoint>& pts\n)\n{\n    return polygon_area(pts);\n}\n\ndouble py_polygon_area2(\n    const py::list& pts\n)\n{\n    std::vector<dpoint> temp(len(pts));\n    for (size_t i = 0; i < temp.size(); ++i)\n        temp[i] = pts[i].cast<dpoint>();\n\n    return polygon_area(temp);\n}\n\n// ----------------------------------------------------------------------------------------\n\nvoid bind_vector(py::module& m)\n{\n    {\n    py::class_<cv, std::shared_ptr<cv>>(m, \"vector\", \"This object represents the mathematical idea of a column vector.\")\n        .def(py::init())\n        .def(\"set_size\", &cv_set_size)\n        .def(\"resize\", &cv_set_size)\n        .def(py::init(&cv_from_object))\n        .def(\"__repr__\", &cv__repr__)\n        .def(\"__str__\", &cv__str__)\n        .def(\"__len__\", &cv__len__)\n        .def(\"__getitem__\", &cv__getitem__)\n        .def(\"__getitem__\", &cv__getitem2__)\n        .def(\"__setitem__\", &cv__setitem__)\n        .def_property_readonly(\"shape\", &cv_get_matrix_size)\n        .def(py::pickle(&getstate<cv>, &setstate<cv>));\n\n    m.def(\"dot\", &dotprod, \"Compute the dot product between two dense column vectors.\");\n    }\n    {\n    typedef point type;\n    py::class_<type>(m, \"point\", \"This object represents a single point of integer coordinates that maps directly to a dlib::point.\")\n            .def(py::init<long,long>(), py::arg(\"x\"), py::arg(\"y\"))\n            .def(py::init<dpoint>(), py::arg(\"p\"))\n            .def(py::init<>(&numpy_to_dlib_vect<long>), py::arg(\"v\"))\n            .def(py::init<>(&numpy_to_dlib_vect<float>), py::arg(\"v\"))\n            .def(py::init<>(&numpy_to_dlib_vect<double>), py::arg(\"v\"))\n            .def(\"__repr__\", &point__repr__)\n            .def(\"__str__\", &point__str__)\n            .def(py::self + py::self)\n            .def(py::self - py::self)\n            .def(py::self / double())\n            .def(py::self * double())\n            .def(double() * py::self)\n            .def(\"normalize\", &type::normalize, \"Returns a unit normalized copy of this vector.\")\n            .def_property(\"x\", &point_x, [](point& p, long x){p.x()=x;}, \"The x-coordinate of the point.\")\n            .def_property(\"y\", &point_y, [](point& p, long y){p.y()=y;}, \"The y-coordinate of the point.\")\n            .def(py::pickle(&getstate<type>, &setstate<type>));\n    }\n    {\n    typedef std::vector<point> type;\n    py::bind_vector<type>(m, \"points\", \"An array of point objects.\")\n        .def(py::init<size_t>(), py::arg(\"initial_size\"))\n        .def(\"clear\", &type::clear)\n        .def(\"resize\", resize<type>)\n        .def(\"extend\", extend_vector_with_python_list<point>)\n        .def(py::pickle(&getstate<type>, &setstate<type>));\n    }\n\n    {\n    typedef dpoint type;\n    py::class_<type>(m, \"dpoint\", \"This object represents a single point of floating point coordinates that maps directly to a dlib::dpoint.\")\n            .def(py::init<double,double>(), py::arg(\"x\"), py::arg(\"y\"))\n            .def(py::init<point>(), py::arg(\"p\"))\n            .def(py::init<>(&numpy_to_dlib_vect<long>), py::arg(\"v\"))\n            .def(py::init<>(&numpy_to_dlib_vect<float>), py::arg(\"v\"))\n            .def(py::init<>(&numpy_to_dlib_vect<double>), py::arg(\"v\"))\n            .def(\"__repr__\", &dpoint__repr__)\n            .def(\"__str__\", &dpoint__str__)\n            .def(\"normalize\", &type::normalize, \"Returns a unit normalized copy of this vector.\")\n            .def_property(\"x\", &dpoint_x, [](dpoint& p, double x){p.x()=x;}, \"The x-coordinate of the dpoint.\")\n            .def_property(\"y\", &dpoint_y, [](dpoint& p, double y){p.y()=y;}, \"The y-coordinate of the dpoint.\")\n            .def(py::self + py::self)\n            .def(py::self - py::self)\n            .def(py::self / double())\n            .def(py::self * double())\n            .def(double() * py::self)\n            .def(py::pickle(&getstate<type>, &setstate<type>));\n    }\n    {\n    typedef std::vector<dpoint> type;\n    py::bind_vector<type>(m, \"dpoints\", \"An array of dpoint objects.\")\n        .def(py::init<size_t>(), py::arg(\"initial_size\"))\n        .def(\"clear\", &type::clear)\n        .def(\"resize\", resize<type>)\n        .def(\"extend\", extend_vector_with_python_list<dpoint>)\n        .def(py::pickle(&getstate<type>, &setstate<type>));\n    }\n\n    m.def(\"length\", [](const point& p){return length(p); }, \n        \"returns the distance from p to the origin, i.e. the L2 norm of p.\", py::arg(\"p\"));\n    m.def(\"length\", [](const dpoint& p){return length(p); }, \n        \"returns the distance from p to the origin, i.e. the L2 norm of p.\", py::arg(\"p\"));\n\n    m.def(\"dot\", [](const point& a, const point& b){return dot(a,b); },  \"Returns the dot product of the points a and b.\", py::arg(\"a\"), py::arg(\"b\"));\n    m.def(\"dot\", [](const dpoint& a, const dpoint& b){return dot(a,b); },  \"Returns the dot product of the points a and b.\", py::arg(\"a\"), py::arg(\"b\"));\n\n    register_point_transform_projective(m);\n\n    m.def(\"polygon_area\", &py_polygon_area, py::arg(\"pts\"));\n    m.def(\"polygon_area\", &py_polygon_area2, py::arg(\"pts\"),\n\"ensures \\n\\\n    - If you walk the points pts in order to make a closed polygon, what is its \\n\\\n      area?  This function returns that area.  It uses the shoelace formula to \\n\\\n      compute the result and so works for general non-self-intersecting polygons.\" \n    /*!\n        ensures\n            - If you walk the points pts in order to make a closed polygon, what is its\n              area?  This function returns that area.  It uses the shoelace formula to\n              compute the result and so works for general non-self-intersecting polygons.\n    !*/\n        );\n\n}\n\n", "meta": {"hexsha": "9c8e3ab93cf83a9253a47247ae4949b73a8e3917", "size": 18169, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tools/python/src/vector.cpp", "max_stars_repo_name": "babic95/dlib", "max_stars_repo_head_hexsha": "285f0255f6deef4e59e97f93023de112594c0741", "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/vector.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/vector.cpp", "max_forks_repo_name": "KiLJ4EdeN/dlib", "max_forks_repo_head_hexsha": "eb1f08ce6ab3ca6f9d10425d899103de3c0df56c", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 3308.0, "max_forks_repo_forks_event_min_datetime": "2015-01-01T14:34:16.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T07:20:07.000Z", "avg_line_length": 36.0496031746, "max_line_length": 155, "alphanum_fraction": 0.5744399802, "num_tokens": 4660, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5698526514141571, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.34201892787234045}}
{"text": "//---------------------------------------------------------------------------//\n//!\n//! \\file   Utility_GaussKronrodIntegrator.hpp\n//! \\author Luke Kersting\n//! \\brief  Gauss-Kronrod integrator\n//!\n//---------------------------------------------------------------------------//\n\n#ifndef UTILITY_GAUSS_KRONROD_INTEGRATOR_HPP\n#define UTILITY_GAUSS_KRONROD_INTEGRATOR_HPP\n\n// std Includes\n#include <queue>\n\n// Boost Includes\n#include <boost/numeric/odeint.hpp>\n\n// FRENSIE Includes\n#include \"Utility_Vector.hpp\"\n#include \"Utility_ArrayView.hpp\"\n\nnamespace Utility{\n\ntemplate<typename T>\nstruct BinTraits\n{\n  T lower_limit;\n  T upper_limit;\n  T result;\n  T error;\n\n  bool operator <( const BinTraits<T>& bins ) const\n  {\n    return error < bins.error;\n  }\n};\n\ntemplate<typename T>\nstruct ExtrapolatedBinTraits\n{\n  T lower_limit;\n  T upper_limit;\n  T result;\n  T error;\n  int level;\n\n  bool operator <( const ExtrapolatedBinTraits<T>& bins ) const\n  {\n    return error < bins.error;\n  }\n};\n\n//! The Gauss-Kronrod integrator\ntemplate<typename T>\nclass GaussKronrodIntegrator\n{\n\npublic:\n\ntypedef std::priority_queue<BinTraits<T>> BinQueue;\ntypedef std::vector<ExtrapolatedBinTraits<T>> BinArray;\n\n  //! Constructor\n  GaussKronrodIntegrator( const T relative_error_tol,\n                          const T absolute_error_tol = 0.0,\n                          const size_t subinterval_limit = 1000 );\n\n  //! Destructor\n  ~GaussKronrodIntegrator()\n  { /* ... */ }\n\n  //! Throw exception on dirty integration\n  void throwExceptionOnDirtyIntegration();\n\n  //! Check if an exception will be thrown on dirty integration\n  bool isExceptionThrownOnDirtyIntegration() const;\n\n  //! Warn on dirty integration (default)\n  void warnOnDirtyIntegration();\n\n  //! Use heuristic roundoff error estimator (default)\n  void estimateRoundoff();\n\n  //! Don't use heuristic roundoff error estimator\n  void dontEstimateRoundoff();\n\n  //! Set the realtive error tolerance\n  void setRelativeErrorTolerance( const double relative_error_tol );\n\n  //! Get the relative error tolerance\n  double getRelativeErrorTolerance() const;\n\n  //! Set the absolute error tolerance\n  void setAbsoluteErrorTolerance( const double absolute_error_tol );\n\n  //! Get the absolute error tolerance\n  double getAbsoluteErrorTolerance() const;\n\n/*\n  //! Integrate the function\n  template<typename Functor>\n  void integrate( Functor& integrand,\n\t\t  T lower_limit,\n\t\t  T upper_limit,\n\t\t  T& result,\n\t\t  T& absolute_error,\n\t\t  size_t& number_of_function_eval ) const;\n*/\n  //! Integrate the function adaptively with BinQueue\n  template<int Points, typename FunctorType = double, typename Functor>\n  void integrateAdaptively( Functor& integrand,\n\t\t\t    T lower_limit,\n\t\t\t    T upper_limit,\n\t\t\t    T& result,\n\t\t\t    T& absolute_error ) const;\n\n  //! Integrate the function adaptively with BinQueue\n  template<int Points, typename FunctorType = double,\n                       typename ParameterType = double, typename Functor>\n  void integrateAdaptively( Functor& integrand,\n                            ParameterType integrand_parameter,\n\t\t\t    T lower_limit,\n\t\t\t    T upper_limit,\n\t\t\t    T& result,\n\t\t\t    T& absolute_error ) const;\n/*\n  //! Integrate the function over a semi-infinite interval (+infinity)\n  template<typename Functor>\n  void integrateSemiInfiniteIntervalUpper( Functor& integrand,\n\t\t\t\t\t   T lower_limit,\n\t\t\t\t\t   T& result,\n\t\t\t\t\t   T& absolute_error ) const;\n\n  //! Integrate the function over a semi-infinite interval (-infinity)\n  template<typename Functor>\n  void integrateSemiInfiniteIntervalLower( Functor& integrand,\n\t\t\t\t\t   T upper_limit,\n\t\t\t\t\t   T& result,\n\t\t\t\t\t   T& absolute_error ) const;\n\n  //! Integrate the function over an infinite interval (-infinity,+infinity)\n  template<typename Functor>\n  void integrateInfiniteInterval( Functor& integrand,\n\t\t\t\t  T& result,\n\t\t\t\t  T& absolute_error ) const;\n\n  //! Integrate a function with integrable singularities adaptively\n  template<typename Functor>\n  void integrateAdaptivelyWynnEpsilon( Functor& integrand,\n\t\t\t\t       T lower_limit,\n\t\t\t\t       T upper_limit,\n\t\t\t\t       T& result,\n\t\t\t\t       T& absolute_error ) const;\n*/\n  //! Integrate a function with known integrable singularities adaptively\n  template<typename FunctorType = double, typename Functor>\n  void integrateAdaptivelyWynnEpsilon(\n\t\t\t  Functor& integrand,\n\t\t\t  const Utility::ArrayView<T>& points_of_interest,\n\t\t\t  T& result,\n\t\t\t  T& absolute_error ) const;\n\n  //! Integrate a function with known integrable singularities adaptively\n  template<typename FunctorType = double, typename ParameterType = double, typename Functor>\n  void integrateAdaptivelyWynnEpsilon(\n\t\t\t  Functor& integrand,\n                          ParameterType integrand_parameter,\n\t\t\t  const Utility::ArrayView<T>& points_of_interest,\n\t\t\t  T& result,\n\t\t\t  T& absolute_error ) const;\n\n  //! Integrate the function with point rule\n  template<int Points, typename FunctorType = double, typename Functor>\n  void integrateWithPointRule(\n                Functor& integrand,\n\t\t\t    T lower_limit,\n\t\t\t    T upper_limit,\n\t\t\t    T& result,\n\t\t\t    T& absolute_error,\n                T& result_abs,\n                T& result_asc ) const;\n\n  //! Integrate the function with point rule\n  template<int Points, typename FunctorType = double,\n                       typename ParameterType = double, typename Functor>\n  void integrateWithPointRule(\n                Functor& integrand,\n                ParameterType integrand_parameter,\n\t\t\t    T lower_limit,\n\t\t\t    T upper_limit,\n\t\t\t    T& result,\n\t\t\t    T& absolute_error,\n                T& result_abs,\n                T& result_asc ) const;\n\nprotected:\n\n  // Calculate the quadrature upper and lower integrand values at an abscissa\n  template<typename FunctorType = double, typename Functor>\n  void calculateQuadratureIntegrandValuesAtAbscissa(\n    Functor& integrand,\n    T abscissa,\n    T half_length,\n    T midpoint,\n    T& integrand_value_lower,\n    T& integrand_value_upper ) const;\n\n  // Calculate the quadrature upper and lower integrand values at an abscissa\n  template<typename FunctorType = double, typename ParameterType = double, typename Functor>\n  void calculateQuadratureIntegrandValuesAtAbscissa(\n    Functor& integrand,\n    ParameterType functor_parameter,\n    T abscissa,\n    T half_length,\n    T midpoint,\n    T& integrand_value_lower,\n    T& integrand_value_upper ) const;\n\n  // Bisect and integrate the given bin interval\n  template<int Points, typename FunctorType = double, typename Functor, typename Bin>\n  void bisectAndIntegrateBinInterval(\n    Functor& integrand,\n    const Bin& bin,\n    Bin& bin_1,\n    Bin& bin_2,\n    T& bin_1_asc,\n    T& bin_2_asc ) const;\n\n  // Bisect and integrate the given bin interval\n  template<int Points, typename FunctorType = double, typename ParameterType = double, typename Functor, typename Bin>\n  void bisectAndIntegrateBinInterval(\n    Functor& integrand,\n    ParameterType functor_parameter,\n    const Bin& bin,\n    Bin& bin_1,\n    Bin& bin_2,\n    T& bin_1_asc,\n    T& bin_2_asc ) const;\n\n  // Rescale absolute error from integration\n  void rescaleAbsoluteError(\n    T& absolute_error,\n    T result_abs,\n    T result_asc ) const;\n\n  // Test if subinterval is too small\n  template<int Points>\n  bool subintervalTooSmall( T& lower_limit_1,\n                                   T& lower_limit_2,\n                                   T& upper_limit_2 ) const;\n\n  // check the roundoff error\n  void checkRoundoffError(\n                       const BinTraits<T>& bin,\n                       const BinTraits<T>& bin_1,\n                       const BinTraits<T>& bin_2,\n                       const T& bin_1_asc,\n                       const T& bin_2_asc,\n                       int& round_off_1,\n                       int& round_off_2,\n                       const int number_of_iterations ) const;\n\n  // check the roundoff error\n  void checkRoundoffError(\n                       const ExtrapolatedBinTraits<T>& bin,\n                       const ExtrapolatedBinTraits<T>& bin_1,\n                       const ExtrapolatedBinTraits<T>& bin_2,\n                       const T& bin_1_asc,\n                       const T& bin_2_asc,\n                       int& round_off_1,\n                       int& round_off_2,\n                       int& round_off_3,\n                       const bool extrapolate,\n                       const int number_of_iterations ) const;\n\n  // Sort the bin order from highest to lowest error\n  void sortBins(\n        std::vector<int>& bin_order,\n        BinArray& bin_array,\n        const ExtrapolatedBinTraits<T>& bin_1,\n        const ExtrapolatedBinTraits<T>& bin_2,\n        const int& number_of_intervals,\n        int& nr_max ) const;\n\n  // get the Wynn Epsilon-Algorithm extrapolated value\n  void getWynnEpsilonAlgorithmExtrapolation(\n        std::vector<T>& bin_extrapolated_result,\n        std::vector<T>& last_three_results,\n        T& extrapolated_result,\n        T& extrapolated_error,\n        int& number_of_extrapolated_intervals,\n        int& number_of_extrapolated_calls  ) const;\n\nprivate:\n  // The relative error tolerance\n  T d_relative_error_tol;\n\n  // The absolute error tolerance\n  T d_absolute_error_tol;\n\n  // The subinterval limit\n  size_t d_subinterval_limit;\n\n  // Throw exception on dirty integration\n  bool d_throw_exceptions;\n\n  // Estimate roundoff error and throw exceptions/warnings\n  bool d_estimate_roundoff;\n\n  // return epsilon numerical limit for type T\n  T getLimitEpsilon() const;\n\n  // return min numerical limit for type T\n  T getLimitMin() const;\n\n  // return max numerical limit for type T\n  T getLimitMax() const;\n\n  // return max of two variables of type T\n  T getMax( T variable_1, T variable_2 ) const;\n};\n\n} // end Utility namespace\n\n//---------------------------------------------------------------------------//\n// Template Includes\n//---------------------------------------------------------------------------//\n\n#include \"Utility_GaussKronrodIntegrator_def.hpp\"\n\n//---------------------------------------------------------------------------//\n\n#endif // end UTILITY_GAUSS_KRONROD_INTEGRATOR_HPP\n\n//---------------------------------------------------------------------------//\n// end Utility_GaussKronrodIntegrator.hpp\n//---------------------------------------------------------------------------//\n", "meta": {"hexsha": "8e490d216a8279f337e22f6453b961834a7c9b7f", "size": 10304, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "packages/utility/integrator/src/Utility_GaussKronrodIntegrator.hpp", "max_stars_repo_name": "bam241/FRENSIE", "max_stars_repo_head_hexsha": "e1760cd792928699c84f2bdce70ff54228e88094", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2019-11-14T19:58:30.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-04T17:44:09.000Z", "max_issues_repo_path": "packages/utility/integrator/src/Utility_GaussKronrodIntegrator.hpp", "max_issues_repo_name": "bam241/FRENSIE", "max_issues_repo_head_hexsha": "e1760cd792928699c84f2bdce70ff54228e88094", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 43.0, "max_issues_repo_issues_event_min_datetime": "2020-03-03T19:59:20.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-08T03:36:08.000Z", "max_forks_repo_path": "packages/utility/integrator/src/Utility_GaussKronrodIntegrator.hpp", "max_forks_repo_name": "bam241/FRENSIE", "max_forks_repo_head_hexsha": "e1760cd792928699c84f2bdce70ff54228e88094", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2020-02-12T17:37:07.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-08T18:59:51.000Z", "avg_line_length": 30.4852071006, "max_line_length": 118, "alphanum_fraction": 0.6384899068, "num_tokens": 2253, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6001883449573376, "lm_q2_score": 0.5698526514141572, "lm_q1q2_score": 0.34201891972181364}}
{"text": "#ifndef MIRRORPLASMA_HPP\n#define MIRRORPLASMA_HPP\n\n#include \"PlasmaPhysics.hpp\"\n#include \"Species.hpp\"\n#include \"NetCDFIO.hpp\"\n#include <toml.hpp>\n\n#include <boost/math/interpolators/barycentric_rational.hpp>\n\n#include <memory>\n#include <cmath>\n\nclass MirrorPlasma {\n\tpublic:\n\t\tclass VacuumMirrorConfiguration {\n\t\t\tpublic:\n\t\t\t\tVacuumMirrorConfiguration( toml::value const& );\n\t\t\t\t/*\n\t\t\t\tVacuumMirrorConfiguration( const& VacuumMirrorConfiguration other ) :\n\t\t\t\t\tIonSpecies( other.IonSpecies )\n\t\t\t\t{\n\t\t\t\t\tMirrorRatio = other.MirrorRatio;\n\t\t\t\t\tPlasmaColumnWidth = other.PlasmaColumnWidth;\n\t\t\t\t\tPlasmaLength = other.PlasmaLength;\n\t\t\t\t\tAxialGapDistance = other.AxialGapDistance;\n\t\t\t\t\tWallRadius = other.WallRadius;\n\t\t\t\t\tCentralCellFieldStrength = other.CentralCellFieldStrength;\n\t\t\t\t\tAuxiliaryHeating = other.AuxiliaryHeating;\n\t\t\t\t}\n\t\t\t\t*/\n\t\t\t\tSpecies_t IonSpecies;\n\t\t\t\tdouble MirrorRatio;\n\t\t\t\tdouble PlasmaColumnWidth;\n\t\t\t\tdouble PlasmaLength;\n\t\t\t\tdouble AxialGapDistance;\n\t\t\t\tdouble WallRadius;\n\t\t\t\tdouble CentralCellFieldStrength;\n\t\t\t\tdouble AuxiliaryHeating;\n\n\t\t\t\tdouble ParallelFudgeFactor;\n\t\t\t\tdouble PerpFudgeFactor;\n\t\t\t\tbool AmbipolarPhi;\n\n\t\t\t\tbool AlphaHeating;\n\t\t\t\tbool ReportNuclearDiagnostics;\n\t\t\t\tbool ReportThrust;\n\n\t\t\t\tdouble InitialTemp;\n\t\t\t\tdouble InitialMach;\n\t\t\t\tbool Collisional;\n\n\t\t\t\tstd::string OutputFile;\n\t\t\t\tstd::string NetcdfOutputFile;\n\n\n\t\t\t\tdouble PlasmaVolume() const {\n\t\t\t\t\treturn M_PI * ( PlasmaColumnWidth + 2 * AxialGapDistance ) * PlasmaColumnWidth * PlasmaLength;\n\t\t\t\t};\n\t\t\t\tdouble WallArea() const {\n\t\t\t\t\treturn 2.0 * M_PI * WallRadius * WallRadius * PlasmaLength;\n\t\t\t\t};\n\n\t\t\t\tdouble ImposedVoltage;\n\t\t\t\tdouble PlasmaInnerRadius() const { return AxialGapDistance; };\n\t\t\t\tdouble PlasmaOuterRadius() const { return AxialGapDistance + PlasmaColumnWidth; };\n\t\t\t\tdouble PlasmaCentralRadius() const { return AxialGapDistance + PlasmaColumnWidth / 2.0; };\n\t\t\tprivate:\n\n\t\t};\n\n\t\t// Copy Constructor\n\t\t/*\n\t\tMirrorPlasma( MirrorPlasma const& other ) :\n\t\t\tpVacuumConfig( other.pVacuumConfig )\n\t\t{\n\t\t\tFuellingRate = other.FuellingRate;\n\t\t\tIonDensity = other.IonDensity;\n\t\t\tIonTemperature = other.IonTemperature;\n\t\t\tElectronDensity = other.ElectronDensity;\n\t\t\tElectronTemperature = other.ElectronTemperature;\n\t\t   NeutralDensity = other.NeutralDensity;\n\t\t\tNeutralSource = other.NeutralSource;\n\t\t\tZeff = other.Zeff;\n\t\t   MachNumber = other.MachNumber;\n\t\t};\n\t\t*/\n\n\t\tMirrorPlasma( MirrorPlasma const& ) = delete;\n\n\t\tMirrorPlasma( toml::value const& configSection );\n\n\t\tdouble FuellingRate;\n\t\tdouble IonDensity,IonTemperature;\n\t\tdouble ElectronDensity,ElectronTemperature;\n\t\tdouble NeutralDensity,NeutralSource;\n\t\tdouble Zeff;\n\n\t\tdouble MachNumber; // Sonic Mach number defined with c_s^2 = Z T_e/m_i\n\n\t\tdouble SoundSpeed() const {\n\t\t\t// We *define* c_s^2 = Z_i T_e / m_i.\n\t\t\tdouble cs = ::sqrt( pVacuumConfig->IonSpecies.Charge * ElectronTemperature*ReferenceTemperature / ( pVacuumConfig->IonSpecies.Mass * ProtonMass ) );\n\t\t\treturn cs;\n\t\t};\n\n\t\t// Defining (3/2) d( n_i T_i )/dt = IonHeating - IonHeatLosses\n\t\t//\n\t\tdouble ElectronHeatLosses() const;\n\t\tdouble IonHeatLosses() const;\n\t\tdouble ElectronHeating() const;\n\t\tdouble IonHeating() const;\n\n\n\t\tdouble EnergyConfinementTime() const {\n\t\t\tdouble StoredEnergy = 1.5 * ( ElectronDensity * ElectronTemperature + IonDensity * IonTemperature ) * ReferenceDensity * ReferenceTemperature;\n\t\t\tdouble TotalHeatLosses = ElectronHeatLosses() + IonHeatLosses();\n\t\t\treturn StoredEnergy / TotalHeatLosses;\n\t\t};\n\n\t\t// RHS of dn/dt = <stuff>\n\t\tdouble IonParticleLosses() const;\n\t\tdouble ElectronParticleLosses() const;\n\n\t\tdouble ElectricPotential() const {\n\t\t\treturn pVacuumConfig->CentralCellFieldStrength * MachNumber * SoundSpeed() * pVacuumConfig->PlasmaColumnWidth;\n\t\t};\n\t\tdouble IonLarmorRadius() const {\n\t\t\treturn 1.02 * ::sqrt( pVacuumConfig->IonSpecies.Mass * IonTemperature * 1000 ) / ( pVacuumConfig->IonSpecies.Charge * pVacuumConfig->CentralCellFieldStrength * 10000 );\n\t\t};\n\n\t\tdouble Beta() const;\n\t\tdouble DebyeLength() const;\n\n\t\tdouble NuStar() const;\n\t\tdouble KineticEnergy() const;\n\t\tdouble ThermalEnergy() const;\n\n\t\tvoid PrintReport();\n\n\t\tvoid InitialiseNetCDF();\n\t\tvoid WriteTimeslice( double T );\n\t\tvoid FinaliseNetCDF();\n\n\n\t\tstd::shared_ptr< VacuumMirrorConfiguration > pVacuumConfig;\n\n\t\tvoid SetMachFromVoltage();\n\t\tdouble AmbipolarPhi() const;\n\n\t\tvoid ComputeSteadyStateNeutrals();\n\n\t\tdouble ParallelMomentumLossRate() const;\n\t\tdouble initialTemperature() const { return pVacuumConfig->InitialTemp; };\n\t\tdouble initialMach() const { return pVacuumConfig->InitialMach; };\n\tprivate:\n\t\tNetCDFIO nc_output;\n\n\t\tdouble LogLambdaElectron() const;\n\t\tdouble LogLambdaIon() const;\n\t\tdouble LogLambdaAlphaElectron() const;\n\n\n\t\tdouble ElectronCollisionTime() const;\n\t\tdouble IonCollisionTime() const;\n\t\tdouble CollisionalTemperatureEquilibrationTime() const;\n\n\t\tdouble SlowingDownTime() const;\n\n\t\tdouble IonToElectronHeatTransfer() const;\n\n\t\tdouble BremsstrahlungLosses() const;\n\t\tdouble NeutralLosses() const;\n\t\tdouble ClassicalHeatLosses() const;\n\t\tdouble ParallelHeatLosses() const;\n\n\t\tdouble ParallelElectronPastukhovLossRate( double Phi ) const;\n\t\tdouble ParallelElectronParticleLoss() const;\n\t\tdouble ParallelElectronHeatLoss() const;\n\n\t\tdouble Chi_i( double ) const;\n\t\tdouble Chi_i() const;\n\n\t\tdouble ParallelIonPastukhovLossRate( double Phi ) const;\n\t\tdouble ParallelIonParticleLoss() const;\n\t\tdouble ParallelIonHeatLoss() const;\n\n\t\tdouble ParallelKineticEnergyLoss() const;\n\n\t\tdouble ClassicalIonHeatLoss() const;\n\t\tdouble ClassicalElectronHeatLoss() const;\n\n\t\tdouble ClassicalElectronParticleLosses() const;\n\t\tdouble ClassicalIonParticleLosses() const;\n\n\t\tdouble ClassicalViscosity() const;\n\t\tdouble AlfvenMachNumber() const;\n\n\t\tdouble ViscousHeating() const;\n\n\t\tdouble CentrifugalPotential() const;\n\n\t\tdouble IonCyclotronFrequency() const\n\t\t{\n\t\t\tdouble MagneticField = pVacuumConfig->CentralCellFieldStrength;\n\t\t\treturn pVacuumConfig->IonSpecies.Charge * ElectronCharge * MagneticField / ( pVacuumConfig->IonSpecies.Mass * ProtonMass );\n\t\t};\n\n\t\tdouble ElectronCyclotronFrequency() const\n\t\t{\n\t\t\tdouble MagneticField = pVacuumConfig->CentralCellFieldStrength;\n\t\t\treturn ElectronCharge * MagneticField / ElectronMass;\n\t\t};\n\n\t\tdouble FusionAlphaPowerDensity() const;\n\t\tdouble AlphaProductionRate() const;\n\t\tdouble NeutronOutput() const;\n\t\tdouble ThermalPowerOutput() const;\n\t\tdouble NeutronWallLoading() const;\n\t\tdouble DDNeutronRate() const;\n\n\t\tusing interpolant = boost::math::barycentric_rational<double>;\n\t\tstd::unique_ptr<interpolant> VoltageFunction;\n\t\tvoid ReadVoltageFile( std::string const& );\n\t\tdouble time;\n\t\tbool isTimeDependent;\n\tpublic:\n\t\tdouble AlphaHeating() const;\n\t\tdouble PromptAlphaLossFraction() const;\n\t\tdouble PromptAlphaThrust() const;\n\t\tdouble AlphaPromptLosses() const;\n\t\tdouble AlphaParallelLossRate() const;\n\t\tdouble ViscousTorque() const;\n\t\tdouble ParallelAngularMomentumLossRate() const;\n\t\tdouble RadialCurrent() const;\n\t\tdouble ParallelIonThrust() const;\n\t\tdouble ParallelCurrent(double) const;\n\t\tvoid UpdateVoltage();\n\t\tvoid SetTime( double );\n};\n\n\n\n\n#endif // MIRRORPLASMA_HPP\n", "meta": {"hexsha": "4b3bbc5a27da25bd9abefb963450ce6702a6483b", "size": 7081, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "MirrorPlasma.hpp", "max_stars_repo_name": "ianabel/MCTrans", "max_stars_repo_head_hexsha": "958c447e4a83dffb72fff69d378b1780a2a0aad4", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2022-02-10T15:55:10.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-10T15:56:00.000Z", "max_issues_repo_path": "MirrorPlasma.hpp", "max_issues_repo_name": "ianabel/MCTrans", "max_issues_repo_head_hexsha": "958c447e4a83dffb72fff69d378b1780a2a0aad4", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 7.0, "max_issues_repo_issues_event_min_datetime": "2021-05-25T20:06:08.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-02T05:58:49.000Z", "max_forks_repo_path": "MirrorPlasma.hpp", "max_forks_repo_name": "ianabel/MCTrans", "max_forks_repo_head_hexsha": "958c447e4a83dffb72fff69d378b1780a2a0aad4", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-01-05T19:55:49.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-05T19:55:49.000Z", "avg_line_length": 28.7845528455, "max_line_length": 171, "alphanum_fraction": 0.7476345149, "num_tokens": 1817, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6893056167854461, "lm_q2_score": 0.49609382947091946, "lm_q1q2_score": 0.3419602631069061}}
{"text": "/*\n * DiscretizedFunction.cpp\n *\n *  Created on: 16.06.2017\n *      Author: thies\n */\n\n#include <deal.II/base/data_out_base.h>\n#include <deal.II/base/logstream.h>\n#include <deal.II/base/thread_management.h>\n#include <deal.II/base/timer.h>\n#include <deal.II/base/utilities.h>\n#include <deal.II/lac/precondition.h>\n#include <deal.II/lac/solver_cg.h>\n#include <deal.II/lac/solver_control.h>\n#include <deal.II/lac/sparse_direct.h>\n#include <deal.II/numerics/data_out.h>\n#include <deal.II/numerics/vector_tools.h>\n\n#include <algorithm>\n#include <cmath>\n#include <fstream>\n#include <iostream>\n#include <random>\n#include <utility>\n\n#include <base/DiscretizedFunction.h>\n\nusing namespace dealii;\n\nnamespace wavepi {\nnamespace base {\n\ninline double square(const double x) { return x * x; }\n\ninline double pow4(const double x) { return x * x * x * x; }\n\ntemplate <int dim>\nDiscretizedFunction<dim>::DiscretizedFunction(std::shared_ptr<SpaceTimeMesh<dim>> mesh,\n                                              std::shared_ptr<Norm<DiscretizedFunction<dim>>> norm,\n                                              bool store_derivative)\n    : mesh(mesh), norm_(norm), store_derivative(store_derivative), cur_time_idx(0) {\n  Assert(mesh && norm, ExcNotInitialized());\n\n  function_coefficients.reserve(mesh->length());\n\n  if (store_derivative) derivative_coefficients.reserve(mesh->length());\n\n  for (size_t i = 0; i < mesh->length(); i++) {\n    function_coefficients.emplace_back(mesh->n_dofs(i));\n\n    if (store_derivative) derivative_coefficients.emplace_back(mesh->n_dofs(i));\n  }\n}\n\ntemplate <int dim>\nDiscretizedFunction<dim>::DiscretizedFunction(std::shared_ptr<SpaceTimeMesh<dim>> mesh,\n                                              std::shared_ptr<Norm<DiscretizedFunction<dim>>> norm)\n    : DiscretizedFunction(mesh, norm, false) {}\n\ntemplate <int dim>\nDiscretizedFunction<dim>::DiscretizedFunction(std::shared_ptr<SpaceTimeMesh<dim>> mesh)\n    : DiscretizedFunction(mesh, std::make_shared<InvalidNorm<DiscretizedFunction<dim>>>()) {}\n\ntemplate <int dim>\nDiscretizedFunction<dim>::DiscretizedFunction(std::shared_ptr<SpaceTimeMesh<dim>> mesh, Function<dim>& function,\n                                              std::shared_ptr<Norm<DiscretizedFunction<dim>>> norm)\n    : mesh(mesh), norm_(norm), store_derivative(false), cur_time_idx(0) {\n  Assert(mesh && norm, ExcNotInitialized());\n\n  function_coefficients.reserve(mesh->length());\n\n  for (size_t i = 0; i < mesh->length(); i++) {\n    auto dof_handler = mesh->get_dof_handler(i);\n\n    Vector<double> tmp(dof_handler->n_dofs());\n    function.set_time(mesh->get_time(i));\n\n    VectorTools::interpolate(*dof_handler, function, tmp);\n    mesh->get_constraint_matrix(i)->distribute(tmp);\n\n    function_coefficients.push_back(std::move(tmp));\n  }\n}\n\ntemplate <int dim>\nDiscretizedFunction<dim>::DiscretizedFunction(std::shared_ptr<SpaceTimeMesh<dim>> mesh, Function<dim>& function)\n    : DiscretizedFunction(mesh, function, std::make_shared<InvalidNorm<DiscretizedFunction<dim>>>()) {}\n\ntemplate <int dim>\nDiscretizedFunction<dim>::DiscretizedFunction(DiscretizedFunction<dim>&& o)\n    : LightFunction<dim>(),\n      mesh(std::move(o.mesh)),\n      norm_(o.norm_),\n      store_derivative(o.store_derivative),\n      cur_time_idx(o.cur_time_idx),\n      function_coefficients(std::move(o.function_coefficients)),\n      derivative_coefficients(std::move(o.derivative_coefficients)) {\n  Assert(mesh, ExcNotInitialized());\n\n  o.mesh = std::shared_ptr<SpaceTimeMesh<dim>>();\n}\n\ntemplate <int dim>\nDiscretizedFunction<dim>::DiscretizedFunction(const DiscretizedFunction<dim>& o)\n    : LightFunction<dim>(),\n      mesh(o.mesh),\n      norm_(o.norm_),\n      store_derivative(o.store_derivative),\n      cur_time_idx(o.cur_time_idx),\n      function_coefficients(o.function_coefficients),\n      derivative_coefficients(o.derivative_coefficients) {\n  Assert(mesh, ExcNotInitialized());\n}\n\ntemplate <int dim>\nDiscretizedFunction<dim>& DiscretizedFunction<dim>::operator=(DiscretizedFunction<dim>&& o) {\n  mesh                    = std::move(o.mesh);\n  norm_                   = o.norm_;\n  store_derivative        = o.store_derivative;\n  cur_time_idx            = o.cur_time_idx;\n  function_coefficients   = std::move(o.function_coefficients);\n  derivative_coefficients = std::move(o.derivative_coefficients);\n\n  o.mesh = std::shared_ptr<SpaceTimeMesh<dim>>();\n\n  Assert(mesh, ExcNotInitialized());\n  return *this;\n}\n\ntemplate <int dim>\nDiscretizedFunction<dim>& DiscretizedFunction<dim>::operator=(const DiscretizedFunction<dim>& o) {\n  mesh                    = o.mesh;\n  norm_                   = o.norm_;\n  store_derivative        = o.store_derivative;\n  cur_time_idx            = o.cur_time_idx;\n  function_coefficients   = o.function_coefficients;\n  derivative_coefficients = o.derivative_coefficients;\n\n  Assert(mesh, ExcNotInitialized());\n  return *this;\n}\n\ntemplate <int dim>\nDiscretizedFunction<dim> DiscretizedFunction<dim>::derivative() const {\n  AssertThrow(store_derivative, ExcInternalError());\n  AssertThrow(mesh, ExcNotInitialized());\n\n  DiscretizedFunction<dim> result(mesh);\n  result.function_coefficients = this->derivative_coefficients;\n\n  return result;\n}\n\ntemplate <int dim>\nDiscretizedFunction<dim> DiscretizedFunction<dim>::calculate_derivative() const {\n  AssertThrow(mesh, ExcNotInitialized());\n  AssertThrow(mesh->length() > 1, ExcInternalError());\n  // AssertThrow(!store_derivative, ExcInternalError()); // why would you want to calculate it in this case?\n\n  DiscretizedFunction<dim> result(mesh, norm_);\n\n  /* implementation for constant mesh */\n  /*\n   for (size_t i = 0; i < mesh->length(); i++) {\n   if (i < mesh->length() - 1)\n   AssertThrow(function_coefficients[i + 1].size() == function_coefficients[i].size(),\n   ExcNotImplemented());\n\n   if (i == 0) {\n   result.function_coefficients[i] = function_coefficients[i + 1];\n   result.function_coefficients[i] -= function_coefficients[i];\n   result.function_coefficients[i] /= mesh->get_time(i + 1) - mesh->get_time(i);\n   } else if (i == mesh->length() - 1) {\n   result.function_coefficients[i] = function_coefficients[i];\n   result.function_coefficients[i] -= function_coefficients[i - 1];\n   result.function_coefficients[i] /= mesh->get_time(i) - mesh->get_time(i - 1);\n   } else {\n   result.function_coefficients[i] = function_coefficients[i + 1];\n   result.function_coefficients[i] -= function_coefficients[i - 1];\n   result.function_coefficients[i] /= mesh->get_time(i + 1) - mesh->get_time(i - 1);\n   }\n   }\n   */\n\n  /* naive, but working implementation for non-constant mesh */\n  /*\n   for (size_t i = 0; i < mesh->length(); i++) {\n   if (i == 0) {\n   Vector<double> next_coefficients = function_coefficients[i + 1];\n   mesh->transfer(i + 1, i, { &next_coefficients });\n\n   result.function_coefficients[i] = next_coefficients;\n   result.function_coefficients[i] -= function_coefficients[i];\n   result.function_coefficients[i] /= mesh->get_time(i + 1) - mesh->get_time(i);\n   } else if (i == mesh->length() - 1) {\n   Vector<double> last_coefficients = function_coefficients[i - 1];\n   mesh->transfer(i - 1, i, { &last_coefficients });\n\n   result.function_coefficients[i] = function_coefficients[i];\n   result.function_coefficients[i] -= last_coefficients;\n   result.function_coefficients[i] /= mesh->get_time(i) - mesh->get_time(i - 1);\n   } else {\n   Vector<double> last_coefficients = function_coefficients[i - 1];\n   Vector<double> next_coefficients = function_coefficients[i + 1];\n\n   mesh->transfer(i - 1, i, { &last_coefficients });\n   mesh->transfer(i + 1, i, { &next_coefficients });\n\n   result.function_coefficients[i] = next_coefficients;\n   result.function_coefficients[i] -= last_coefficients;\n   result.function_coefficients[i] /= mesh->get_time(i + 1) - mesh->get_time(i - 1);\n   }\n   }\n   */\n\n  /* better: forward- and backward sweep */\n  // forward sweep\n  for (size_t i = 0; i < mesh->length(); i++) {\n    if (i == 0) {\n      result.function_coefficients[i].equ(-1.0 / (mesh->get_time(i + 1) - mesh->get_time(i)), function_coefficients[i]);\n    } else if (i == mesh->length() - 1) {\n      Vector<double> last_coefficients = function_coefficients[i - 1];\n      mesh->transfer(i - 1, i, {&last_coefficients});\n\n      result.function_coefficients[i] = function_coefficients[i];\n      result.function_coefficients[i] -= last_coefficients;\n      result.function_coefficients[i] /= mesh->get_time(i) - mesh->get_time(i - 1);\n    } else {\n      Vector<double> last_coefficients = function_coefficients[i - 1];\n      mesh->transfer(i - 1, i, {&last_coefficients});\n\n      result.function_coefficients[i].equ(-1.0 / (mesh->get_time(i + 1) - mesh->get_time(i - 1)), last_coefficients);\n    }\n  }\n\n  // backward sweep\n  for (size_t j = 0; j < mesh->length(); j++) {\n    size_t i = mesh->length() - 1 - j;\n\n    if (i == 0) {\n      Vector<double> next_coefficients = function_coefficients[i + 1];\n      mesh->transfer(i + 1, i, {&next_coefficients});\n\n      result.function_coefficients[i].add(1.0 / (mesh->get_time(i + 1) - mesh->get_time(i)), next_coefficients);\n    } else if (i == mesh->length() - 1) {\n      // nothing to be done\n    } else {\n      Vector<double> next_coefficients = function_coefficients[i + 1];\n      mesh->transfer(i + 1, i, {&next_coefficients});\n\n      result.function_coefficients[i].add(1.0 / (mesh->get_time(i + 1) - mesh->get_time(i - 1)), next_coefficients);\n    }\n  }\n\n  return result;\n}\n\ntemplate <int dim>\nDiscretizedFunction<dim> DiscretizedFunction<dim>::calculate_second_derivative() const {\n  AssertThrow(mesh, ExcNotInitialized());\n  AssertThrow(mesh->length() > 1, ExcInternalError());\n\n  DiscretizedFunction<dim> result(mesh, norm_);\n\n  /* implementation for constant mesh */\n\n  for (size_t i = 0; i < mesh->length(); i++) {\n    if (i < mesh->length() - 1)\n      AssertThrow(function_coefficients[i + 1].size() == function_coefficients[i].size(), ExcNotImplemented());\n\n    if (i == 0) {\n      result.function_coefficients[i] = function_coefficients[i];\n      result.function_coefficients[i].add(-2, function_coefficients[i + 1]);\n      result.function_coefficients[i].add(1, function_coefficients[i + 2]);\n      result.function_coefficients[i] /= square(mesh->get_time(i + 1) - mesh->get_time(i));\n    } else if (i == mesh->length() - 1) {\n      result.function_coefficients[i] = function_coefficients[i];\n      result.function_coefficients[i].add(-2, function_coefficients[i - 1]);\n      result.function_coefficients[i].add(1, function_coefficients[i - 2]);\n      result.function_coefficients[i] /= square(mesh->get_time(i) - mesh->get_time(i - 1));\n    } else {\n      result.function_coefficients[i].equ(-2, function_coefficients[i]);\n      result.function_coefficients[i].add(1, function_coefficients[i + 1]);\n      result.function_coefficients[i].add(1, function_coefficients[i - 1]);\n      result.function_coefficients[i] /= square(mesh->get_time(i + 1) - mesh->get_time(i - 1)) / 4;\n    }\n  }\n\n  return result;\n}\n\ntemplate <int dim>\ndouble DiscretizedFunction<dim>::absolute_error(DiscretizedFunction<dim>& other, double* norm_out) const {\n  LogStream::Prefix p(\"calculate_error\");\n  AssertThrow(other.mesh == mesh, ExcInternalError());\n\n  DiscretizedFunction<dim> tmp = other;\n  tmp.set_norm(norm_);\n\n  if (norm_out) *norm_out = tmp.norm();\n\n  tmp -= *this;\n\n  return tmp.norm();\n}\n\ntemplate <int dim>\nDiscretizedFunction<dim> DiscretizedFunction<dim>::calculate_derivative_transpose() const {\n  AssertThrow(mesh, ExcNotInitialized());\n\n  // because of the special cases\n  AssertThrow(mesh->length() > 3, ExcInternalError());\n\n  DiscretizedFunction<dim> result(mesh, norm_);\n\n  /* implementation for constant mesh */\n  /*\n   for (size_t i = 0; i < mesh->length(); i++) {\n   auto dest = &result.function_coefficients[i];\n\n   if (i < mesh->length() - 1)\n   AssertThrow(function_coefficients[i + 1].size() == function_coefficients[i].size(),\n   ExcNotImplemented());\n\n   if (i == 0) {\n   *dest = function_coefficients[i + 1];\n   dest->sadd(-1.0 / (mesh->get_time(i + 2) - mesh->get_time(i)),\n   -1.0 / (mesh->get_time(i + 1) - mesh->get_time(i)), function_coefficients[i]);\n   } else if (i == 1) {\n   *dest = function_coefficients[i + 1];\n   dest->sadd(-1.0 / (mesh->get_time(i + 2) - mesh->get_time(i)),\n   1.0 / (mesh->get_time(i) - mesh->get_time(i - 1)), function_coefficients[i - 1]);\n   } else if (i == mesh->length() - 1) {\n   *dest = function_coefficients[i];\n   dest->sadd(1.0 / (mesh->get_time(i) - mesh->get_time(i - 1)),\n   1.0 / (mesh->get_time(i) - mesh->get_time(i - 2)), function_coefficients[i - 1]);\n   } else if (i == mesh->length() - 2) {\n   *dest = function_coefficients[i + 1];\n   dest->sadd(-1.0 / (mesh->get_time(i + 1) - mesh->get_time(i)),\n   1.0 / (mesh->get_time(i) - mesh->get_time(i - 2)), function_coefficients[i - 1]);\n   } else {\n   *dest = function_coefficients[i + 1];\n   dest->sadd(-1.0 / (mesh->get_time(i + 2) - mesh->get_time(i)),\n   1.0 / (mesh->get_time(i) - mesh->get_time(i - 2)), function_coefficients[i - 1]);\n   }\n   }\n   */\n\n  /* naive, but working implementation for non-constant mesh */\n  /*for (size_t i = 0; i < mesh->length(); i++) {\n   auto& dest = result.function_coefficients[i];\n\n   if (i == 0) {\n   Vector<double> tmp = function_coefficients[i + 1];\n   mesh->transfer(i + 1, i, {&tmp});\n   dest.add(-1.0 / (mesh->get_time(i + 2) - mesh->get_time(i)), tmp);\n\n   dest.add(-1.0 / (mesh->get_time(i + 1) - mesh->get_time(i)), function_coefficients[i]);\n   } else if (i == 1) {\n   Vector<double> tmp = function_coefficients[i + 1];\n   mesh->transfer(i + 1, i, {&tmp});\n   dest.add(-1.0 / (mesh->get_time(i + 2) - mesh->get_time(i)), tmp);\n\n   tmp = function_coefficients[i - 1];\n   mesh->transfer(i - 1, i, {&tmp});\n   dest.add(1.0 / (mesh->get_time(i) - mesh->get_time(i - 1)), tmp);\n   } else if (i == mesh->length() - 1) {\n   dest.add(1.0 / (mesh->get_time(i) - mesh->get_time(i - 1)), function_coefficients[i]);\n\n   Vector<double> tmp = function_coefficients[i - 1];\n   mesh->transfer(i - 1, i, &tmp);\n   dest.add(1.0 / (mesh->get_time(i) - mesh->get_time(i - 2)), tmp);\n   } else if (i == mesh->length() - 2) {\n   Vector<double> tmp = function_coefficients[i + 1];\n   mesh->transfer(i + 1, i, {&tmp});\n   dest.add(-1.0 / (mesh->get_time(i + 1) - mesh->get_time(i)), tmp);\n\n   tmp = function_coefficients[i - 1];\n   mesh->transfer(i - 1, i, {&tmp});\n   dest.add(1.0 / (mesh->get_time(i) - mesh->get_time(i - 2)), tmp);\n   } else {\n   Vector<double> tmp = function_coefficients[i + 1];\n   mesh->transfer(i + 1, i, {&tmp});\n   dest.add(-1.0 / (mesh->get_time(i + 2) - mesh->get_time(i)), tmp);\n\n   tmp = function_coefficients[i - 1];\n   mesh->transfer(i - 1, i, {&tmp});\n   dest.add(1.0 / (mesh->get_time(i) - mesh->get_time(i - 2)), tmp);\n   }\n   }\n   */\n\n  /* better: forward- and backward sweep */\n  // forward sweep\n  for (size_t i = 0; i < mesh->length(); i++) {\n    auto& dest = result.function_coefficients[i];\n\n    if (i == 0) {\n      dest.add(-1.0 / (mesh->get_time(i + 1) - mesh->get_time(i)), function_coefficients[i]);\n    } else if (i == 1) {\n      Vector<double> tmp = function_coefficients[i - 1];\n      mesh->transfer(i - 1, i, {&tmp});\n      dest.add(1.0 / (mesh->get_time(i) - mesh->get_time(i - 1)), tmp);\n    } else if (i == mesh->length() - 1) {\n      Vector<double> tmp = function_coefficients[i - 1];\n      mesh->transfer(i - 1, i, {&tmp});\n      dest.add(1.0 / (mesh->get_time(i) - mesh->get_time(i - 2)), tmp);\n\n      dest.add(1.0 / (mesh->get_time(i) - mesh->get_time(i - 1)), function_coefficients[i]);\n    } else if (i == mesh->length() - 2) {\n      Vector<double> tmp = function_coefficients[i - 1];\n      mesh->transfer(i - 1, i, {&tmp});\n      dest.add(1.0 / (mesh->get_time(i) - mesh->get_time(i - 2)), tmp);\n    } else {\n      Vector<double> tmp = function_coefficients[i - 1];\n      mesh->transfer(i - 1, i, {&tmp});\n      dest.add(1.0 / (mesh->get_time(i) - mesh->get_time(i - 2)), tmp);\n    }\n  }\n\n  // backward sweep\n  for (size_t j = 0; j < mesh->length(); j++) {\n    size_t i   = mesh->length() - 1 - j;\n    auto& dest = result.function_coefficients[i];\n\n    if (i == 0) {\n      Vector<double> tmp = function_coefficients[i + 1];\n      mesh->transfer(i + 1, i, {&tmp});\n      dest.add(-1.0 / (mesh->get_time(i + 2) - mesh->get_time(i)), tmp);\n    } else if (i == 1) {\n      Vector<double> tmp = function_coefficients[i + 1];\n      mesh->transfer(i + 1, i, {&tmp});\n      dest.add(-1.0 / (mesh->get_time(i + 2) - mesh->get_time(i)), tmp);\n    } else if (i == mesh->length() - 1) {\n      // nothing to be done\n    } else if (i == mesh->length() - 2) {\n      Vector<double> tmp = function_coefficients[i + 1];\n      mesh->transfer(i + 1, i, {&tmp});\n      dest.add(-1.0 / (mesh->get_time(i + 1) - mesh->get_time(i)), tmp);\n    } else {\n      Vector<double> tmp = function_coefficients[i + 1];\n      mesh->transfer(i + 1, i, {&tmp});\n      dest.add(-1.0 / (mesh->get_time(i + 2) - mesh->get_time(i)), tmp);\n    }\n  }\n\n  return result;\n}\n\ntemplate <int dim>\nDiscretizedFunction<dim> DiscretizedFunction<dim>::calculate_second_derivative_transpose() const {\n  AssertThrow(mesh, ExcNotInitialized());\n\n  // because of the special cases\n  AssertThrow(mesh->length() > 3, ExcInternalError());\n\n  DiscretizedFunction<dim> result(mesh, norm_);\n\n  /* implementation for constant mesh */\n\n  for (size_t i = 0; i < mesh->length(); i++) {\n    auto dest = &result.function_coefficients[i];\n\n    if (i < mesh->length() - 1)\n      AssertThrow(function_coefficients[i + 1].size() == function_coefficients[i].size(), ExcNotImplemented());\n\n    if (i == 0) {\n      dest->equ(1.0 / square(mesh->get_time(i + 1) - mesh->get_time(i)), function_coefficients[i]);\n      dest->add(1.0 * 4 / square(mesh->get_time(i + 2) - mesh->get_time(i)), function_coefficients[i + 1]);\n    } else if (i == 1) {\n      dest->equ(-2.0 * 4 / square(mesh->get_time(i + 1) - mesh->get_time(i - 1)), function_coefficients[i]);\n      dest->add(-2.0 / square(mesh->get_time(i) - mesh->get_time(i - 1)), function_coefficients[i - 1]);\n      dest->add(1.0 * 4 / square(mesh->get_time(i + 2) - mesh->get_time(i)), function_coefficients[i + 1]);\n    } else if (i == 2) {\n      dest->equ(-2.0 * 4 / square(mesh->get_time(i + 1) - mesh->get_time(i - 1)), function_coefficients[i]);\n      dest->add(1.0 * 4 / square(mesh->get_time(i) - mesh->get_time(i - 2)), function_coefficients[i - 1]);\n      dest->add(1.0 * 4 / square(mesh->get_time(i + 2) - mesh->get_time(i)), function_coefficients[i + 1]);\n      dest->add(1.0 / square(mesh->get_time(i - 2) - mesh->get_time(i - 1)), function_coefficients[i - 2]);\n    } else if (i == mesh->length() - 1) {\n      dest->equ(1.0 / square(mesh->get_time(i) - mesh->get_time(i - 1)), function_coefficients[i]);\n      dest->add(1.0 * 4 / square(mesh->get_time(i) - mesh->get_time(i - 2)), function_coefficients[i - 1]);\n    } else if (i == mesh->length() - 2) {\n      dest->equ(-2.0 * 4 / square(mesh->get_time(i + 1) - mesh->get_time(i - 1)), function_coefficients[i]);\n      dest->add(-2.0 / square(mesh->get_time(i) - mesh->get_time(i + 1)), function_coefficients[i + 1]);\n      dest->add(1.0 * 4 / square(mesh->get_time(i - 2) - mesh->get_time(i)), function_coefficients[i - 1]);\n    } else if (i == mesh->length() - 3) {\n      dest->equ(-2.0 * 4 / square(mesh->get_time(i + 1) - mesh->get_time(i - 1)), function_coefficients[i]);\n      dest->add(1.0 * 4 / square(mesh->get_time(i) - mesh->get_time(i - 2)), function_coefficients[i - 1]);\n      dest->add(1.0 * 4 / square(mesh->get_time(i + 2) - mesh->get_time(i)), function_coefficients[i + 1]);\n      dest->add(1.0 / square(mesh->get_time(i + 2) - mesh->get_time(i + 1)), function_coefficients[i + 2]);\n    } else {\n      dest->equ(-2.0 * 4 / square(mesh->get_time(i + 1) - mesh->get_time(i - 1)), function_coefficients[i]);\n      dest->add(1.0 * 4 / square(mesh->get_time(i) - mesh->get_time(i - 2)), function_coefficients[i - 1]);\n      dest->add(1.0 * 4 / square(mesh->get_time(i + 2) - mesh->get_time(i)), function_coefficients[i + 1]);\n    }\n  }\n\n  return result;\n}\n\ntemplate <int dim>\nDiscretizedFunction<dim>& DiscretizedFunction<dim>::operator=(double x) {\n  AssertThrow(mesh, ExcNotInitialized());\n\n  for (size_t i = 0; i < mesh->length(); i++) {\n    function_coefficients[i] = x;\n\n    if (store_derivative) derivative_coefficients[i] = 0.0;\n  }\n\n  return *this;\n}\n\ntemplate <int dim>\nDiscretizedFunction<dim>& DiscretizedFunction<dim>::operator+=(double offset) {\n  // note that this is correct independent of store_derivative.\n\n  for (size_t i = 0; i < mesh->length(); i++) {\n    function_coefficients[i].add(offset);\n  }\n\n  return *this;\n}\n\ntemplate <int dim>\nDiscretizedFunction<dim>& DiscretizedFunction<dim>::operator+=(const DiscretizedFunction<dim>& V) {\n  AssertThrow(norm_ && V.norm_, ExcNotInitialized());\n  AssertThrow(*norm_ == *V.norm_, ExcMessage(\"DiscretizedFunction<dim>::operator+= : Norms not compatible\"));\n  this->add(1.0, V);\n\n  return *this;\n}\n\ntemplate <int dim>\nDiscretizedFunction<dim>& DiscretizedFunction<dim>::operator-=(const DiscretizedFunction<dim>& V) {\n  AssertThrow(norm_ && V.norm_, ExcNotInitialized());\n  AssertThrow(*norm_ == *V.norm_, ExcMessage(\"DiscretizedFunction<dim>::operator-= : Norms not compatible\"));\n  this->add(-1.0, V);\n\n  return *this;\n}\n\ntemplate <int dim>\nDiscretizedFunction<dim>& DiscretizedFunction<dim>::operator*=(const double factor) {\n  AssertThrow(mesh, ExcNotInitialized());\n\n  for (size_t i = 0; i < mesh->length(); i++) {\n    function_coefficients[i] *= factor;\n\n    if (store_derivative) derivative_coefficients[i] *= factor;\n  }\n\n  return *this;\n}\n\ntemplate <int dim>\nDiscretizedFunction<dim> DiscretizedFunction<dim>::noise(const DiscretizedFunction<dim>& like) {\n  Assert(!like.store_derivative, ExcInternalError());\n\n  DiscretizedFunction<dim> res = noise(like.mesh);\n  res.set_norm(like.get_norm());\n\n  return res;\n}\n\ntemplate <int dim>\nDiscretizedFunction<dim> DiscretizedFunction<dim>::noise(std::shared_ptr<SpaceTimeMesh<dim>> mesh) {\n  Assert(mesh, ExcNotInitialized());\n\n  DiscretizedFunction<dim> res(mesh);\n\n  // auto time = std::chrono::high_resolution_clock::now();\n  // std::default_random_engine generator(time.time_since_epoch().count() % 1000000);\n  std::default_random_engine generator(2307);\n  std::uniform_real_distribution<double> distribution(-1, 1);\n\n  for (size_t i = 0; i < res.mesh->length(); i++)\n    for (size_t j = 0; j < res.function_coefficients[i].size(); j++)\n      res.function_coefficients[i][j] = distribution(generator);\n\n  return res;\n}\n\ntemplate <int dim>\nDiscretizedFunction<dim> DiscretizedFunction<dim>::noise(const DiscretizedFunction<dim>& like, double norm) {\n  DiscretizedFunction<dim> result = noise(like);\n\n  result *= norm / result.norm();\n\n  return result;\n}\n\ntemplate <int dim>\nDiscretizedFunction<dim>& DiscretizedFunction<dim>::operator/=(const double factor) {\n  return this->operator*=(1.0 / factor);\n}\n\ntemplate <int dim>\nvoid DiscretizedFunction<dim>::pointwise_multiplication(const DiscretizedFunction<dim>& V) {\n  Assert(mesh, ExcNotInitialized());\n  Assert(mesh == V.mesh, ExcInternalError());\n  Assert(!store_derivative || (store_derivative == V.store_derivative), ExcInternalError());\n\n  for (size_t i = 0; i < mesh->length(); i++) {\n    Assert(function_coefficients[i].size() == V.function_coefficients[i].size(),\n           ExcDimensionMismatch(function_coefficients[i].size(), V.function_coefficients[i].size()));\n\n    if (store_derivative) {\n      Assert(derivative_coefficients[i].size() == V.derivative_coefficients[i].size(),\n             ExcDimensionMismatch(derivative_coefficients[i].size(), V.derivative_coefficients[i].size()));\n\n      derivative_coefficients[i].scale(V.function_coefficients[i]);\n\n      Vector<double> tmp = function_coefficients[i];\n      tmp.scale(V.derivative_coefficients[i]);\n\n      derivative_coefficients[i] += tmp;\n    }\n\n    function_coefficients[i].scale(V.function_coefficients[i]);\n  }\n}\n\ntemplate <int dim>\nvoid DiscretizedFunction<dim>::add(const double a, const DiscretizedFunction<dim>& V) {\n  AssertThrow(mesh && norm_ && V.norm_, ExcNotInitialized());\n  AssertThrow(mesh == V.mesh, ExcInternalError());\n  AssertThrow(!store_derivative || (store_derivative == V.store_derivative), ExcInternalError());\n  AssertThrow(*norm_ == *V.norm_, ExcMessage(\"DiscretizedFunction<dim>::add : Norms not compatible\"));\n\n  for (size_t i = 0; i < mesh->length(); i++) {\n    Assert(function_coefficients[i].size() == V.function_coefficients[i].size(),\n           ExcDimensionMismatch(function_coefficients[i].size(), V.function_coefficients[i].size()));\n\n    function_coefficients[i].add(a, V.function_coefficients[i]);\n\n    if (store_derivative) {\n      Assert(derivative_coefficients[i].size() == V.derivative_coefficients[i].size(),\n             ExcDimensionMismatch(derivative_coefficients[i].size(), V.derivative_coefficients[i].size()));\n\n      derivative_coefficients[i].add(a, V.derivative_coefficients[i]);\n    }\n  }\n}\n\ntemplate <int dim>\nvoid DiscretizedFunction<dim>::sadd(const double s, const double a, const DiscretizedFunction<dim>& V) {\n  AssertThrow(mesh && norm_ && V.norm_, ExcNotInitialized());\n  AssertThrow(mesh == V.mesh, ExcInternalError());\n  AssertThrow(!store_derivative || (store_derivative == V.store_derivative), ExcInternalError());\n  AssertThrow(*norm_ == *V.norm_, ExcMessage(\"DiscretizedFunction<dim>::sadd : Norms not compatible\"));\n\n  for (size_t i = 0; i < mesh->length(); i++) {\n    Assert(function_coefficients[i].size() == V.function_coefficients[i].size(),\n           ExcDimensionMismatch(function_coefficients[i].size(), V.function_coefficients[i].size()));\n\n    function_coefficients[i].sadd(s, a, V.function_coefficients[i]);\n\n    if (store_derivative) {\n      Assert(derivative_coefficients[i].size() == V.derivative_coefficients[i].size(),\n             ExcDimensionMismatch(derivative_coefficients[i].size(), V.derivative_coefficients[i].size()));\n\n      derivative_coefficients[i].sadd(s, a, V.derivative_coefficients[i]);\n    }\n  }\n}\n\ntemplate <int dim>\nvoid DiscretizedFunction<dim>::throw_away_derivative() {\n  store_derivative        = false;\n  derivative_coefficients = std::vector<Vector<double>>();\n}\n\ntemplate <int dim>\ndouble DiscretizedFunction<dim>::norm() const {\n  Assert(mesh && norm_, ExcNotInitialized());\n  Assert(!store_derivative, ExcInternalError());\n\n  return norm_->norm(*this);\n}\n\ntemplate <int dim>\ndouble DiscretizedFunction<dim>::operator*(const DiscretizedFunction<dim>& V) const {\n  Assert(mesh && norm_ && V.norm_, ExcNotInitialized());\n  Assert(!store_derivative, ExcInternalError());\n  AssertThrow(*V.norm_ == *norm_, ExcMessage(\"DiscretizedFunction<dim>::operator* : Norms not compatible\"));\n\n  return norm_->dot(*this, V);\n}\n\ntemplate <int dim>\ndouble DiscretizedFunction<dim>::dot(const DiscretizedFunction<dim>& V) const {\n  return (*this) * V;\n}\n\ntemplate <int dim>\nvoid DiscretizedFunction<dim>::duality_mapping_lp(double p) {\n  AssertThrow(p > 1, ExcMessage(\"duality_mapping_lp: p has to be larger than 1!\"));\n\n  for (size_t i = 0; i < mesh->length(); i++)\n    for (size_t j = 0; j < function_coefficients[i].size(); j++)\n      if (function_coefficients[i][j] != 0.0)\n        function_coefficients[i][j] =\n            std::pow(std::abs(function_coefficients[i][j]), p - 2) * function_coefficients[i][j];\n}\n\ntemplate <int dim>\nvoid DiscretizedFunction<dim>::duality_mapping(double p) {\n  Assert(mesh && norm_, ExcNotInitialized());\n  Assert(!store_derivative, ExcInternalError());\n\n  norm_->duality_mapping(*this, p);\n}\n\ntemplate <int dim>\nvoid DiscretizedFunction<dim>::duality_mapping_dual(double q) {\n  Assert(mesh && norm_, ExcNotInitialized());\n  Assert(!store_derivative, ExcInternalError());\n\n  norm_->duality_mapping_dual(*this, q);\n}\n\ntemplate <int dim>\ndouble DiscretizedFunction<dim>::norm_dual() const {\n  Assert(mesh && norm_, ExcNotInitialized());\n  Assert(!store_derivative, ExcInternalError());\n\n  return norm_->norm_dual(*this);\n}\n\ntemplate <int dim>\ndouble DiscretizedFunction<dim>::norm_p(double p) {\n  AssertThrow(p >= 1, ExcMessage(\"norm_p: p has to be >= 1!\"));\n  double result = 0.0;\n\n  for (size_t i = 0; i < mesh->length(); i++)\n    for (size_t j = 0; j < function_coefficients[i].size(); j++)\n      result += std::pow(std::abs(function_coefficients[i][j]), p);\n\n  return std::pow(result, 1 / p);\n}\n\ntemplate <int dim>\nbool DiscretizedFunction<dim>::hilbert() const {\n  Assert(mesh && norm_, ExcNotInitialized());\n  Assert(!store_derivative, ExcInternalError());\n\n  return norm_->hilbert();\n}\n\ntemplate <int dim>\nvoid DiscretizedFunction<dim>::dot_transform() {\n  Assert(mesh && norm_, ExcNotInitialized());\n  Assert(!store_derivative, ExcInternalError());\n\n  norm_->dot_transform(*this);\n}\n\ntemplate <int dim>\nvoid DiscretizedFunction<dim>::dot_transform_inverse() {\n  Assert(mesh && norm_, ExcNotInitialized());\n  Assert(!store_derivative, ExcInternalError());\n\n  norm_->dot_transform_inverse(*this);\n}\n\ntemplate <int dim>\nvoid DiscretizedFunction<dim>::dot_solve_mass_and_transform() {\n  Assert(mesh && norm_, ExcNotInitialized());\n  Assert(!store_derivative, ExcInternalError());\n\n  norm_->dot_solve_mass_and_transform(*this);\n}\n\ntemplate <int dim>\nvoid DiscretizedFunction<dim>::dot_mult_mass_and_transform_inverse() {\n  Assert(mesh && norm_, ExcNotInitialized());\n  Assert(!store_derivative, ExcInternalError());\n\n  norm_->dot_mult_mass_and_transform_inverse(*this);\n}\n\ntemplate <int dim>\nvoid DiscretizedFunction<dim>::mult_mass() {\n  Assert(!store_derivative, ExcInternalError());\n\n  for (size_t i = 0; i < mesh->length(); i++) {\n    Vector<double> tmp(function_coefficients[i].size());\n    mesh->get_mass_matrix(i)->vmult(tmp, function_coefficients[i]);\n    function_coefficients[i] = tmp;\n  }\n}\n\ntemplate <int dim>\nvoid DiscretizedFunction<dim>::solve_mass() {\n  Assert(!store_derivative, ExcInternalError());\n\n  LogStream::Prefix p(\"solve_mass\");\n  Timer timer;\n  timer.start();\n\n  // PreconditionIdentity precondition;\n  PreconditionSSOR<SparseMatrix<double>> precondition;\n  precondition.initialize(*mesh->get_mass_matrix(0), PreconditionSSOR<SparseMatrix<double>>::AdditionalData(1.0));\n\n  for (size_t i = 0; i < mesh->length(); i++) {\n    LogStream::Prefix p(\"step-\" + Utilities::int_to_string(i, 4));\n\n    Vector<double> tmp(function_coefficients[i].size());\n\n    SolverControl solver_control(2000, 1e-10 * function_coefficients[i].l2_norm());\n    SolverCG<> cg(solver_control);\n\n    cg.solve(*mesh->get_mass_matrix(i), tmp, function_coefficients[i], precondition);\n    function_coefficients[i] = tmp;\n  }\n\n  deallog << \"solved space-time-mass matrices in \" << timer.wall_time() << \"s\" << std::endl;\n}\n\ntemplate <int dim>\nvoid DiscretizedFunction<dim>::write_pvd(std::string path, std::string filename, std::string name) const {\n  write_pvd(path, filename, name, name + \"_prime\");\n}\n\ntemplate <int dim>\nvoid DiscretizedFunction<dim>::write_pvd(std::string path, std::string filename, std::string name,\n                                         std::string name_deriv) const {\n  Assert(mesh, ExcNotInitialized());\n\n  LogStream::Prefix p(\"write_pvd\");\n  deallog << \"Writing \" << path << filename << \".pvd\" << std::endl;\n\n  Assert(mesh->length() < 10000, ExcNotImplemented());  // 4 digits are ok\n  std::vector<std::pair<double, std::string>> times_and_names(mesh->length(), std::pair<double, std::string>(0.0, \"\"));\n\n  for (size_t i = 0; i < mesh->length(); i++) {\n    const std::string vtuname = filename + \"-\" + Utilities::int_to_string(i, 4) + \".vtu\";\n    times_and_names[i]        = std::pair<double, std::string>(mesh->get_time(i), vtuname);\n\n    write_vtu(name, name_deriv, path + vtuname, i);\n  }\n\n  std::ofstream pvd_output(path + filename + \".pvd\");\n  AssertThrow(pvd_output, ExcMessage(\"write_pvd :: output handle invalid\"));\n\n  DataOutBase::write_pvd_record(pvd_output, times_and_names);\n  // deallog << \"Wrote \" << filename << std::endl;\n}\n\ntemplate <int dim>\nvoid DiscretizedFunction<dim>::write_vtu(const std::string name, const std::string name_deriv,\n                                         const std::string filename, size_t i) const {\n  DataOut<dim> data_out;\n\n  data_out.attach_dof_handler(*mesh->get_dof_handler(i));\n  data_out.add_data_vector(function_coefficients[i], name);\n\n  if (store_derivative) data_out.add_data_vector(derivative_coefficients[i], name_deriv);\n\n  data_out.build_patches();\n\n  deallog << \"Writing \" << filename << std::endl;\n\n  std::ofstream output(filename.c_str());\n  AssertThrow(output, ExcMessage(\"write_vtk :: output handle invalid\"));\n\n  data_out.write_vtu(output);\n  // deallog << \"Wrote \" << filename << std::endl;\n}\n\ntemplate <int dim>\nconst std::shared_ptr<Norm<DiscretizedFunction<dim>>> DiscretizedFunction<dim>::get_norm() const {\n  return norm_;\n}\n\ntemplate <int dim>\nvoid DiscretizedFunction<dim>::set_norm(std::shared_ptr<Norm<DiscretizedFunction<dim>>> norm) {\n  this->norm_ = norm;\n}\n\ntemplate <int dim>\ndouble DiscretizedFunction<dim>::evaluate(const Point<dim>& p, const double time) const {\n  const size_t time_idx = mesh->find_time(time);\n\n  return VectorTools::point_value(*mesh->get_dof_handler(time_idx), function_coefficients[time_idx], p);\n}\n\ntemplate <int dim>\ndouble DiscretizedFunction<dim>::value(const Point<dim>& p, const unsigned int component) const {\n  Assert(component == 0, ExcIndexRange(component, 0, 1));\n  Assert(cur_time_idx >= 0 && cur_time_idx < mesh->length(), ExcIndexRange(cur_time_idx, 0, mesh->length()));\n\n  return VectorTools::point_value(*mesh->get_dof_handler(cur_time_idx), function_coefficients[cur_time_idx], p);\n}\n\ntemplate <int dim>\nTensor<1, dim, double> DiscretizedFunction<dim>::gradient(const Point<dim>& p, const unsigned int component) const {\n  Assert(component == 0, ExcIndexRange(component, 0, 1));\n  Assert(cur_time_idx >= 0 && cur_time_idx < mesh->length(), ExcIndexRange(cur_time_idx, 0, mesh->length()));\n\n  return VectorTools::point_gradient(*mesh->get_dof_handler(cur_time_idx), function_coefficients[cur_time_idx], p);\n}\n\ntemplate <int dim>\ndouble DiscretizedFunction<dim>::get_time_index() const {\n  return cur_time_idx;\n}\n\ntemplate <int dim>\nvoid DiscretizedFunction<dim>::set_time(const double new_time) {\n  Function<dim>::set_time(new_time);\n  cur_time_idx = mesh->find_time(new_time);\n}\n\ntemplate <int dim>\nstd::shared_ptr<SpaceTimeMesh<dim>> DiscretizedFunction<dim>::get_mesh() const {\n  return mesh;\n}\n\ntemplate <int dim>\nvoid DiscretizedFunction<dim>::min_max_value(double* min_out, double* max_out) const {\n  *min_out = std::numeric_limits<double>::infinity();\n  *max_out = -std::numeric_limits<double>::infinity();\n\n  for (size_t i = 0; i < this->length(); i++)\n    for (size_t j = 0; j < function_coefficients[i].size(); j++) {\n      if (*min_out > function_coefficients[i][j]) *min_out = function_coefficients[i][j];\n\n      if (*max_out < function_coefficients[i][j]) *max_out = function_coefficients[i][j];\n    }\n}\n\ntemplate <int dim>\ndouble DiscretizedFunction<dim>::min_value() const {\n  double tmp = std::numeric_limits<double>::infinity();\n\n  for (size_t i = 0; i < this->length(); i++)\n    for (size_t j = 0; j < function_coefficients[i].size(); j++)\n      if (tmp > function_coefficients[i][j]) tmp = function_coefficients[i][j];\n\n  return tmp;\n}\n\ntemplate <int dim>\ndouble DiscretizedFunction<dim>::max_value() const {\n  double tmp = -std::numeric_limits<double>::infinity();\n\n  for (size_t i = 0; i < this->length(); i++)\n    for (size_t j = 0; j < function_coefficients[i].size(); j++)\n      if (tmp < function_coefficients[i][j]) tmp = function_coefficients[i][j];\n\n  return tmp;\n}\n\ntemplate <int dim>\ndouble DiscretizedFunction<dim>::relative_error(const DiscretizedFunction<dim>& other) const {\n  DiscretizedFunction<dim> tmp(*this);\n  tmp -= other;\n\n  double denom = this->norm();\n  return tmp.norm() / (denom == 0.0 ? 1.0 : denom);\n}\n\n#ifdef WAVEPI_MPI\ntemplate <int dim>\nvoid DiscretizedFunction<dim>::mpi_irecv(size_t source, std::vector<MPI_Request>& reqs) {\n  AssertThrow(reqs.size() == 0, ExcInternalError());\n\n  reqs.reserve(function_coefficients.size());\n\n  for (size_t i = 0; i < mesh->length(); i++) {\n    reqs.emplace_back();\n    MPI_Irecv(&function_coefficients[i][0], function_coefficients[i].size(), MPI_DOUBLE, source, 1, MPI_COMM_WORLD,\n              &reqs[i]);\n  }\n\n  if (store_derivative) {\n    reqs.reserve(function_coefficients.size() + derivative_coefficients.size());\n\n    for (size_t i = 0; i < mesh->length(); i++) {\n      reqs.emplace_back();\n      MPI_Irecv(&derivative_coefficients[i][0], derivative_coefficients[i].size(), MPI_DOUBLE, source, 1,\n                MPI_COMM_WORLD, &reqs[function_coefficients.size() + i]);\n    }\n  }\n}\n\ntemplate <int dim>\nvoid DiscretizedFunction<dim>::mpi_send(size_t destination) {\n  for (size_t i = 0; i < mesh->length(); i++)\n    MPI_Send(&function_coefficients[i][0], function_coefficients[i].size(), MPI_DOUBLE, destination, 1, MPI_COMM_WORLD);\n\n  if (store_derivative) {\n    for (size_t i = 0; i < mesh->length(); i++)\n      MPI_Send(&derivative_coefficients[i][0], derivative_coefficients[i].size(), MPI_DOUBLE, destination, 1,\n               MPI_COMM_WORLD);\n  }\n}\n\ntemplate <int dim>\nvoid DiscretizedFunction<dim>::mpi_bcast(size_t root) {\n  for (size_t i = 0; i < mesh->length(); i++)\n    MPI_Bcast(&function_coefficients[i][0], function_coefficients[i].size(), MPI_DOUBLE, root, MPI_COMM_WORLD);\n\n  if (store_derivative) {\n    for (size_t i = 0; i < mesh->length(); i++)\n      MPI_Bcast(&derivative_coefficients[i][0], derivative_coefficients[i].size(), MPI_DOUBLE, root, MPI_COMM_WORLD);\n  }\n}\n\ntemplate <int dim>\nvoid DiscretizedFunction<dim>::mpi_isend(size_t destination, std::vector<MPI_Request>& reqs) {\n  AssertThrow(reqs.size() == 0, ExcInternalError());\n\n  reqs.reserve(function_coefficients.size());\n\n  for (size_t i = 0; i < mesh->length(); i++) {\n    reqs.emplace_back();\n    MPI_Isend(&function_coefficients[i][0], function_coefficients[i].size(), MPI_DOUBLE, destination, 1, MPI_COMM_WORLD,\n              &reqs[i]);\n  }\n\n  if (store_derivative) {\n    reqs.reserve(function_coefficients.size() + derivative_coefficients.size());\n\n    for (size_t i = 0; i < mesh->length(); i++) {\n      reqs.emplace_back();\n      MPI_Isend(&derivative_coefficients[i][0], derivative_coefficients[i].size(), MPI_DOUBLE, destination, 1,\n                MPI_COMM_WORLD, &reqs[function_coefficients.size() + i]);\n    }\n  }\n}\n\ntemplate <int dim>\nvoid DiscretizedFunction<dim>::mpi_all_reduce(DiscretizedFunction<dim> source, MPI_Op op) {\n  for (size_t i = 0; i < mesh->length(); i++)\n    MPI_Allreduce(&source.function_coefficients[i][0], &function_coefficients[i][0], function_coefficients[i].size(),\n                  MPI_DOUBLE, op, MPI_COMM_WORLD);\n\n  if (store_derivative) {\n    for (size_t i = 0; i < mesh->length(); i++)\n      MPI_Allreduce(&source.derivative_coefficients[i][0], &derivative_coefficients[i][0],\n                    derivative_coefficients[i].size(), MPI_DOUBLE, op, MPI_COMM_WORLD);\n  }\n}\n#endif\n\ntemplate class DiscretizedFunction<1>;\ntemplate class DiscretizedFunction<2>;\ntemplate class DiscretizedFunction<3>;\n\n}  // namespace base\n}  // namespace wavepi\n", "meta": {"hexsha": "2593273dec32e358638939d24c2402182a2c2c48", "size": 39174, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lib/base/DiscretizedFunction.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/base/DiscretizedFunction.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/base/DiscretizedFunction.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": 37.0965909091, "max_line_length": 120, "alphanum_fraction": 0.6698830857, "num_tokens": 10676, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.689305616785446, "lm_q2_score": 0.49609382947091946, "lm_q1q2_score": 0.341960263106906}}
{"text": "// External libraries\n#include <boost/property_tree/ptree.hpp>\n\n// Local libraries\n#include <fmath/physics.h>\n#include <fparameters/Dimension.h>\n#include <fparameters/parameters.h>\n#include <fparameters/SpaceIterator.h>\n\n// Local headers\n#include \"State.h\"\n#include \"globalVariables.h\"\n#include \"adafFunctions.h\"\n#include \"modelParameters.h\"\n#include \"messages.h\"\n\nusing namespace std;\n\nState::State(boost::property_tree::ptree& cfg):\n    photon{ \"photon\" },\n\tntPhoton{ \"ntPhoton\" },\n    ntProton{ \"ntProton\" },\n    ntElectron{ \"ntElectron\" },\n    ntNeutron{ \"ntNeutron\" },\n\tntChargedPion{ \"ntChargedPion\" },\n\tntMuon{ \"ntMuon\" },\n\tneutrino{ \"neutrino\" },\n\tntPair{ \"ntPair\" },\n\ttau_gg(ntPhoton.ps, false),\n    magf(ntPhoton.ps, false),\n    denf_i(ntPhoton.ps, false),\n    denf_e(ntPhoton.ps, false),\n    tempElectrons(ntPhoton.ps, false),\n    tempIons(ntPhoton.ps, false),\n    thetaH(ntPhoton.ps, false),\n    height(ntPhoton.ps, false)\n{\n    show_message(msgStart, Module_state);\n\n\tparticles.push_back(&photon);\n\tparticles.push_back(&ntPhoton);\n    particles.push_back(&ntElectron);\n    particles.push_back(&ntProton);\n    particles.push_back(&ntNeutron);\n\tparticles.push_back(&ntChargedPion);\n\tparticles.push_back(&ntMuon);\n\tparticles.push_back(&neutrino);\n\tparticles.push_back(&ntPair);\n    for (auto p : particles) {\n        initializeParticle(*p, cfg);\n    }\n    magf.initialize();\n    magf.fill([&](const SpaceIterator& i){\n        double r = i.val(DIM_R);\n        return magneticField(r);\n    });\n    denf_i.initialize();\n    denf_i.fill([&](const SpaceIterator& i) {\n        double r = i.val(DIM_R); \n        double dens = massDensityADAF(r)/(atomicMassUnit*iMeanMolecularWeight);\n\t\treturn dens;\n    });\n    denf_e.initialize();\n    denf_e.fill([&](const SpaceIterator& i) {\n        double r = i.val(DIM_R);\n        return massDensityADAF(r)/(atomicMassUnit*eMeanMolecularWeight);\n    });\n    tempElectrons.initialize();\n    tempElectrons.fill([&](const SpaceIterator& i) {\n        double r = i.val(DIM_R);\n        return electronTemp(r);\n    });\n    tempIons.initialize();\n    tempIons.fill([&](const SpaceIterator& i) {\n        double r = i.val(DIM_R);\n        return ionTemp(r);\n    });\n    thetaH.initialize();\n    thetaH.fill([&](const SpaceIterator& i) {\n        double r = i.val(DIM_R);\n        return acos(costhetaH(r));\n    });\n    height.initialize();\n    height.fill([&](const SpaceIterator& i) {\n        double r = i.val(DIM_R);\n        return height_fun(r);\n    });\n\ttau_gg.initialize();\n\n    show_message(msgEnd, Module_state);\n}\n\nDimension* State::createDimension(Particle& p, string dimid, \n\t\tfunction<void(Vector&, double, double)> initializer, function<double(double)> to_linear,  function<double(double)> from_linear, boost::property_tree::ptree& cfg)\n{\n\tint samples = p.getpar<int>(cfg, \"dim.\"+dimid+\".samples\");\n\tdouble min = p.getpar<double>(cfg, \"dim.\"+dimid+\".min\");\n\tdouble max = p.getpar<double>(cfg, \"dim.\"+dimid+\".max\");\n\treturn new Dimension(samples, bind(initializer, placeholders::_1, min, max), to_linear, from_linear);\n}\n\nauto l10 = [](double x) { return (x > 0.0) ? log10(x) : -300.0;};\nauto e10 = [](double x) { return exp10(x); };\n\nvoid State::initializeParticle(Particle& p, boost::property_tree::ptree& cfg)\n{\n\tusing std::bind;\n\tp.configure(cfg.get_child(\"particle.default\"));\n\tp.configure(cfg.get_child(\"particle.\"+p.id));\n\n\t// add dimension for energies\n\tp.ps.add(\n\t\tcreateDimension(\n\t\t\tp,\n\t\t\t\"energy\",\n\t\t\tinitEnergyPoints,\n\t\t\tl10, e10,\n\t\t\tcfg\n\t\t)\n\t);\n\t\n\t// add dimension for r\n\tdouble innerRadius = exp(logr.front()) * schwRadius;\n\tdouble edgeRadius = exp(logr.back()) * schwRadius;\n\tp.ps.add(new Dimension(nR, bind(initGridLogarithmically, placeholders::_1, innerRadius, edgeRadius), l10, e10));\n\t\t\t\t\t\t\t\n\t// add dimension for rcd\n\tp.ps.add(new Dimension(nRcd,bind(initGridLogarithmically,placeholders::_1,\n\t\t\t\t\t\t\trTr, rOutCD),l10,e10));\n\t\n\tp.initialize();\n}\n", "meta": {"hexsha": "05d23656b3a2dece79e544ba6f4cdfe9bddf0e5c", "size": 3906, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/adaf/State.cpp", "max_stars_repo_name": "eduardomgutierrez/RIAF_radproc", "max_stars_repo_head_hexsha": "0e4166f04cce27fed2cbd2c7078023c10e0e8d12", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-08-30T06:56:03.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-30T06:56:03.000Z", "max_issues_repo_path": "src/adaf/State.cpp", "max_issues_repo_name": "eduardomgutierrez/RIAF_radproc", "max_issues_repo_head_hexsha": "0e4166f04cce27fed2cbd2c7078023c10e0e8d12", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/adaf/State.cpp", "max_forks_repo_name": "eduardomgutierrez/RIAF_radproc", "max_forks_repo_head_hexsha": "0e4166f04cce27fed2cbd2c7078023c10e0e8d12", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.3684210526, "max_line_length": 163, "alphanum_fraction": 0.6653865847, "num_tokens": 1063, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6893056040203135, "lm_q2_score": 0.49609382947091946, "lm_q1q2_score": 0.34196025677420255}}
{"text": "/*\n\nPICCANTE\nThe hottest HDR imaging library!\nhttp://vcg.isti.cnr.it/piccante\n\nCopyright (C) 2014\nVisual Computing Laboratory - ISTI CNR\nhttp://vcg.isti.cnr.it\nFirst author: Francesco Banterle\n\nThis Source Code Form is subject to the terms of the Mozilla Public\nLicense, v. 2.0. If a copy of the MPL was not distributed with this\nfile, You can obtain one at http://mozilla.org/MPL/2.0/.\n\n*/\n\n#ifndef PIC_COMPUTER_VISION_NELDER_MEAD_OPT_TRIANGULATION_HPP\n#define PIC_COMPUTER_VISION_NELDER_MEAD_OPT_TRIANGULATION_HPP\n\n#include \"../util/matrix_3_x_3.hpp\"\n#include \"../util/nelder_mead_opt_base.hpp\"\n\n#ifndef PIC_DISABLE_EIGEN\n#ifndef PIC_EIGEN_NOT_BUNDLED\n   #include \"../externals/Eigen/Dense\"\n#else\n    #include <Eigen/Dense>\n#endif\n#endif\n\nnamespace pic {\n\n#ifndef PIC_DISABLE_EIGEN\n\nclass NelderMeadOptTriangulation: public NelderMeadOptBase<double>\n{\npublic:\n\n    std::vector< Eigen::Matrix34d > M;\n    std::vector< Eigen::Vector2f > p;\n\n    /**\n     * @brief NelderMeadOptTriangulation\n     * @param M0\n     * @param M1\n     */\n    NelderMeadOptTriangulation(Eigen::Matrix34d &M0, Eigen::Matrix34d &M1) : NelderMeadOptBase()\n    {\n        this->M.push_back(M0);\n        this->M.push_back(M1);\n    }\n\n    /**\n     * @brief NelderMeadOptTriangulation\n     * @param M0\n     * @param M1\n     */\n    NelderMeadOptTriangulation(std::vector< Eigen::Matrix34d> &M) : NelderMeadOptBase()\n    {\n        this->M.assign(M.begin(), M.end());\n    }\n\n    /**\n     * @brief update\n     * @param p0\n     * @param p1\n     */\n    void update(Eigen::Vector2f &p0, Eigen::Vector2f &p1)\n    {\n        this->p.clear();\n        this->p.push_back(p0);\n        this->p.push_back(p1);\n    }\n\n    /**\n     * @brief update\n     * @param p0\n     * @param p1\n     */\n    void update(std::vector< Eigen::Vector2f> &p)\n    {\n        this->p.clear();\n        this->p.assign(p.begin(), p.end());\n    }\n\n    /**\n     * @brief function\n     * @param x\n     * @param n\n     * @return\n     */\n    double function(double *x, unsigned int n)\n    {\n        Eigen::Vector4d point(x[0], x[1], x[2], 1.0);\n\n        double err = 0.0;\n        for(unsigned int i = 0; i < M.size(); i++) {\n            Eigen::Vector3d proj = M[i] * point;\n\n            proj[0] /= proj[2];\n            proj[1] /= proj[2];\n\n            double dx = p[i][0] - proj[0];\n            double dy = p[i][1] - proj[1];\n\n            err += (dx * dx) + (dy * dy);\n        }\n\n        return err;\n    }\n};\n\n#endif\n\n}\n\n#endif // PIC_COMPUTER_VISION_NELDER_MEAD_OPT_TRIANGULATION_HPP\n", "meta": {"hexsha": "e9fc960175d9a3aa4605934c0514f87272d7bf1d", "size": 2505, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/computer_vision/nelder_mead_opt_triangulation.hpp", "max_stars_repo_name": "ecarpita93/HPC_projet_1", "max_stars_repo_head_hexsha": "a2c00e056c03227711c43cf2ad23d75c6afbe698", "max_stars_repo_licenses": ["Xnet", "X11"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/computer_vision/nelder_mead_opt_triangulation.hpp", "max_issues_repo_name": "ecarpita93/HPC_projet_1", "max_issues_repo_head_hexsha": "a2c00e056c03227711c43cf2ad23d75c6afbe698", "max_issues_repo_licenses": ["Xnet", "X11"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/computer_vision/nelder_mead_opt_triangulation.hpp", "max_forks_repo_name": "ecarpita93/HPC_projet_1", "max_forks_repo_head_hexsha": "a2c00e056c03227711c43cf2ad23d75c6afbe698", "max_forks_repo_licenses": ["Xnet", "X11"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.0504201681, "max_line_length": 96, "alphanum_fraction": 0.5952095808, "num_tokens": 768, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6297745935070806, "lm_q2_score": 0.5428632831725052, "lm_q1q2_score": 0.34188150348988366}}
{"text": "#include <boost/python.hpp>\n#include <boost/python/numpy.hpp>\n\n#include <iostream>\n#include \"species.h\"\n\n\nusing namespace std;\nnamespace p = boost::python;\nnamespace np = boost::python::numpy;\nnamespace bm = boost::math;\n\n\ntemplate<typename T>\nstatic T det(const array<array<T, 3>, 3> &p) {\n    T sum{};\n    for (size_t i = 0; i < 3; i++) {\n        sum += p[1][(i + 1) % 3] * p[2][(i + 2) % 3] * p[0][i];\n        sum -= p[1][(i + 2) % 3] * p[2][(i + 1) % 3] * p[0][i];\n    }\n    return sum;\n};\n\n\nclass Solver {\n\n    double kperp, kpara;\n\n    vector<Species> species;\n\npublic:\n\n    Solver(const p::list &list, const double B) {\n        Py_Initialize();\n        np::initialize();\n        for (int i = 0; i < len(list); i++) {\n            species.push_back(Species(list[i], B));\n        }\n    }\n\n    void push_kperp(const double kperp) {\n        this->kperp = kperp;\n        for (Species &spec: species) {\n            spec.push_kperp(kperp);\n        }\n    }\n\n    void push_kpara(const double kpara) {\n        this->kpara = kpara;\n    }\n\n    array<array<cdouble, 3>, 3> evaluateM(const double wr, const double wi) {\n        array<array<cdouble, 3>, 3> M{};\n        for (Species &spec: species) {\n            M += spec.push_omega(kpara, kperp, wr, wi);\n        }\n        double kperp2 = kperp*kperp;\n        double kperp3 = kperp2*kperp;\n        double kperp4 = kperp2*kperp2;\n        double kpara2 = kpara*kpara;\n        double kpara4 = kpara2*kpara2;\n        double kpara5 = kpara4*kpara;\n        double kpara6 = kpara4*kpara2;\n\n        M[0][0] += kperp2*kpara4;\n        M[1][1] += kperp2*kpara4;\n        M[2][2] += kperp2*kpara4;\n\n        cdouble c2_w2 = pow(cl / cdouble{wr, wi}, 2);\n\n        M[0][0] -= c2_w2*kperp2*kpara6;\n        M[0][2] += c2_w2*kperp3*kpara5;\n        M[1][1] -= c2_w2*kperp2*kpara6;\n        M[1][1] -= c2_w2*kperp4*kpara4;\n        M[2][0] += c2_w2*kperp3*kpara5;\n        M[2][2] -= c2_w2*kperp4*kpara4;\n\n        M *= (1.0/(kpara4*kperp2));\n\n\n\n        return M;\n    };\n\n    array<array<cdouble, 3>, 3> evaluateEps(const double wr, const double wi) {\n        array<array<cdouble, 3>, 3> Eps{};\n        for (Species &spec: species) {\n            Eps += spec.push_omega(kpara, kperp, wr, wi);\n        }\n\n        double kperp2 = kperp*kperp;\n        double kperp3 = kperp2*kperp;\n        double kperp4 = kperp2*kperp2;\n        double kpara2 = kpara*kpara;\n        double kpara4 = kpara2*kpara2;\n\n        Eps[0][0] += kperp2*kpara4;\n        Eps[1][1] += kperp2*kpara4;\n        Eps[2][2] += kperp2*kpara4;\n\n        Eps *= (1.0/(kpara4*kperp2));\n\n\n\n        return Eps;\n    };\n\n    np::ndarray convertM(const double wr, const double wi) {\n        array<array<cdouble, 3>, 3> M = evaluateM(wr, wi);\n\n        p::tuple shape = p::make_tuple(3, 3);\n        np::ndarray npM = np::zeros(shape, np::dtype::get_builtin<cdouble>());\n\n        for (size_t i=0;i<3;i++){\n            for (size_t j=0;j<3;j++){\n                npM[i][j] = M[i][j];\n            }\n        }\n\n        return npM;\n    }\n\n    np::ndarray convertEps(const double wr, const double wi) {\n        array<array<cdouble, 3>, 3> M = evaluateEps(wr, wi);\n\n        p::tuple shape = p::make_tuple(3, 3);\n        np::ndarray npM = np::zeros(shape, np::dtype::get_builtin<cdouble>());\n\n        for (size_t i=0;i<3;i++){\n            for (size_t j=0;j<3;j++){\n                npM[i][j] = M[i][j];\n            }\n        }\n\n        return npM;\n    }\n\n    cdouble evaluateDetM(const double wr, const double wi) {\n        array<array<cdouble, 3>, 3> M = evaluateM(wr, wi);\n        cdouble detM = det(M);\n        double wa = sqrt(wr*wr + wi*wi);\n        return detM * pow(wa, 4) / pow((kpara * kpara + kperp * kperp) * cl * cl, 2);\n    }\n\n    cdouble evaluateDetMLongitudinal(const double wr, const double wi) {\n        array<array<cdouble, 3>, 3> M = evaluateM(wr, wi);\n        array<cdouble, 3> ML{};\n        ML[0] = kperp*M[0][0] + kpara*M[0][2];\n        ML[2] = kperp*M[2][0] + kpara*M[2][2];\n\n        cdouble detML = (ML[0]*kperp + ML[2]*kpara)/(kperp*kperp + kpara*kpara);\n        return detML;\n    }\n\n    np::ndarray marginalize(const np::ndarray &arr) {\n        int nd = arr.get_nd();\n        Py_intptr_t const *shape = arr.get_shape();\n        Py_intptr_t const *stride = arr.get_strides();\n        np::ndarray result = np::zeros(nd, shape, arr.get_dtype());\n        if (nd == 1) {\n            for (size_t i = 0; i < (size_t) shape[0]; i++) {\n                cdouble w = *reinterpret_cast<cdouble const *>(arr.get_data() + i * stride[0]);\n                cdouble res = evaluateDetM(w.real(), w.imag());\n                *reinterpret_cast<cdouble *>(result.get_data() + i * stride[0]) = res;\n            }\n        } else if (nd == 2) {\n            for (size_t i = 0; i < (size_t) shape[0]; i++) {\n                for (size_t j = 0; j < (size_t) shape[1]; j++) {\n                    cdouble w = *reinterpret_cast<cdouble const *>(arr.get_data() + i * stride[0] + j * stride[1]);\n                    cdouble res = evaluateDetM(w.real(), w.imag());\n                    *reinterpret_cast<cdouble *>(result.get_data() + i * stride[0] + j * stride[1]) = res;\n                }\n            }\n        } else\n            throw std::runtime_error(\"Unsupported marginalization dimensionality. \");\n        return result;\n    }\n\n};\n\n\nBOOST_PYTHON_MODULE (libSolver) {\n    p::class_<Solver>(\"Solver\", p::init<const boost::python::list, double>())\n            .def(\"push_kperp\", &Solver::push_kperp)\n            .def(\"push_kpara\", &Solver::push_kpara)\n            .def(\"evaluateDetM\", &Solver::evaluateDetM)\n            .def(\"evaluateDetMLongitudinal\", &Solver::evaluateDetMLongitudinal)\n            .def(\"evaluateM\", &Solver::convertM)\n            .def(\"evaluateEps\", &Solver::convertEps)\n            .def(\"marginalize\", &Solver::marginalize);\n}\n\n\n\n", "meta": {"hexsha": "96b092133dfe2b6b3264a2ef44beeb0efe72eae8", "size": 5798, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/KineticDispersion/solver.cpp", "max_stars_repo_name": "SamuelIrvine/Kinetic-Dispersion-Solver", "max_stars_repo_head_hexsha": "6056ece40e9c241d8c2df3ce8a089d3f10fb99b1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2021-02-03T17:07:43.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-29T14:56:16.000Z", "max_issues_repo_path": "src/KineticDispersion/solver.cpp", "max_issues_repo_name": "SamuelIrvine/Kinetic-Dispersion-Solver", "max_issues_repo_head_hexsha": "6056ece40e9c241d8c2df3ce8a089d3f10fb99b1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-01-03T03:44:58.000Z", "max_issues_repo_issues_event_max_datetime": "2020-01-09T09:41:23.000Z", "max_forks_repo_path": "src/KineticDispersion/solver.cpp", "max_forks_repo_name": "SamuelIrvine/Kinetic-Dispersion-Solver", "max_forks_repo_head_hexsha": "6056ece40e9c241d8c2df3ce8a089d3f10fb99b1", "max_forks_repo_licenses": ["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.7333333333, "max_line_length": 115, "alphanum_fraction": 0.5263884098, "num_tokens": 1870, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7057850278370112, "lm_q2_score": 0.48438008427698437, "lm_q1q2_score": 0.3418682112651253}}
{"text": "/**\n * @file\n * @copyright This code is licensed under the 3-clause BSD license.\\n\n *            Copyright ETH Zurich, Laboratory of Physical Chemistry, Reiher Group.\\n\n *            See LICENSE.txt for details.\n */\n#include \"KrylovDiagonalizer.h\"\n#include \"../MathUtils.h\"\n#include \"DiagonalizerSettings.h\"\n#include \"PreconditionerEvaluator.h\"\n#include \"SigmaVectorEvaluator.h\"\n#include \"SubspaceCollapser.h\"\n#include \"SubspaceOrthogonalizer.h\"\n#include <Core/Log.h>\n#include <Eigen/Eigenvalues>\n#include <numeric>\n\nnamespace Scine {\nnamespace Utils {\n\nKrylovDiagonalizer::KrylovDiagonalizer(int eigenvaluesToCompute, int totalDimension)\n  : IterativeDiagonalizer(eigenvaluesToCompute, totalDimension) {\n  settings_ = std::make_unique<KrylovSettings>(eigenvaluesToCompute, totalDimension);\n  initialize(totalDimension);\n  notConvergedRoots_.resize(eigenvaluesToCompute_);\n  std::iota(notConvergedRoots_.begin(), notConvergedRoots_.end(), 0);\n}\n\nvoid KrylovDiagonalizer::applySettings() {\n  IterativeDiagonalizer::applySettings();\n  subspaceCollapser_ = std::make_unique<SubspaceCollapser>();\n  subspaceCollapser_->setMaxSubspaceDimension(settings_->getInt(subspaceCollapseDimensionOption));\n  subspaceCollapser_->setEigenvaluesToCompute(eigenvaluesToCompute_);\n}\n\nvoid KrylovDiagonalizer::performIteration(Core::Log& log) {\n  // Handle for, for instance, orthogonalizing\n  onIterationStart();\n\n  const Eigen::MatrixXd& projector = guessVectors_.leftCols(subspaceDimension_);\n  // Handle for, for instance, calculating basis overlap\n  onSigmaMatrixEvaluation(projector);\n  // Sigma vectors evaluation + Hamiltonian projection\n  const Eigen::MatrixXd& sigmaMatrix = sigmaVectorEvaluator_->evaluate(projector);\n  Eigen::MatrixXd projectedMatrix = (projector.transpose() * sigmaMatrix).selfadjointView<Eigen::Lower>();\n\n  // Solve eigenproblem in subspace\n  subspaceEigenpairs_ = eigenDecomposition(projectedMatrix);\n\n  calculateResiduals(sigmaMatrix, projector);\n\n  checkConvergence();\n\n  if (converged_) {\n    ritzEstimate_ = {ritzEstimate_.eigenValues.head(eigenvaluesToCompute_),\n                     ritzEstimate_.eigenVectors.leftCols(eigenvaluesToCompute_)};\n    return;\n  }\n  // Collapse subspace\n  collapse(projector, log);\n}\n\ninline void KrylovDiagonalizer::calculateResiduals(const Eigen::MatrixXd& sigmaMatrix, const Eigen::MatrixXd& projector) {\n  ritzEstimate_.eigenVectors = projector * subspaceEigenpairs_.eigenVectors.leftCols(eigenvaluesToCompute_);\n  ritzEstimate_.eigenValues = subspaceEigenpairs_.eigenValues.head(eigenvaluesToCompute_);\n  // Calculate residuals\n  // TODO: Allow for expansion of more than just not converged roots (f.i. 2 new vectors per root)\n  residualVectors_.resize(sigmaMatrix.rows(), notConvergedRoots_.size());\n  int index = 0;\n  for (int notConvergedRoot : notConvergedRoots_) {\n    residualVectors_.col(index) = sigmaMatrix * subspaceEigenpairs_.eigenVectors.col(notConvergedRoot);\n    residualVectors_.col(index).noalias() -=\n        ritzEstimate_.eigenVectors.col(notConvergedRoot) * ritzEstimate_.eigenValues(notConvergedRoot);\n    ++index;\n  }\n}\n\ninline void KrylovDiagonalizer::checkConvergence() {\n  residualNorms_ = residualVectors_.colwise().norm();\n  numberConvergedRoots_ = 0;\n  // Maps the index in the residual norms to the actual root number\n  std::vector<int> oldNotConvergedRoots = notConvergedRoots_;\n  notConvergedRoots_.clear();\n\n  // Keep track of converged roots\n  for (int i = 0; i < residualVectors_.cols(); ++i) {\n    if (residualNorms_(i) < settings_->getDouble(residualNormToleranceOption)) {\n      rootConverged_[oldNotConvergedRoots[i]] = true;\n    }\n    else {\n      rootConverged_[oldNotConvergedRoots[i]] = false;\n      notConvergedRoots_.push_back(oldNotConvergedRoots[i]);\n    }\n  }\n  numberConvergedRoots_ = std::count(rootConverged_.begin(), rootConverged_.end(), true);\n  converged_ = std::count(rootConverged_.begin(), rootConverged_.end(), false) == 0;\n\n  assert(numberConvergedRoots_ <= eigenvaluesToCompute_);\n}\n\nvoid KrylovDiagonalizer::collapse(const Eigen::MatrixXd& projector, Core::Log& log) {\n  subspaceCollapser_->setMaxSubspaceDimension(\n      SubspaceCollapser::calculateSubspaceCollapserIterations(eigenvaluesToCompute_, numberConvergedRoots_, maxDimension_));\n  if (!subspaceCollapser_->collapseNeeded(ritzEstimate_, subspaceDimension_, notConvergedRoots_)) {\n    expandSubspace(projector);\n  }\n  else {\n    callCollapserImpl();\n    // If total space is small, one-shot this\n    if (guessVectors_.cols() >= maxDimension_) {\n      guessVectors_ = Eigen::MatrixXd::Identity(maxDimension_, maxDimension_);\n      subspaceDimension_ = maxDimension_;\n    }\n    sigmaVectorEvaluator_->collapsed(subspaceDimension_);\n    std::fill(rootConverged_.begin(), rootConverged_.end(), false);\n    numberConvergedRoots_ = 0;\n    converged_ = false;\n    notConvergedRoots_.resize(eigenvaluesToCompute_);\n    std::iota(notConvergedRoots_.begin(), notConvergedRoots_.end(), 0);\n    log.output << Core::Log::nl << \"Subspace collapsed. New dimension is \" << subspaceDimension_ << Core::Log::nl\n               << Core::Log::endl;\n\n    printHeader(log);\n  }\n}\n\ninline void KrylovDiagonalizer::expandSubspace(const Eigen::MatrixXd& projector) {\n  // look at each residual vector\n  Eigen::MatrixXd newGuessVectors(guessVectors_.rows(), notConvergedRoots_.size());\n  int index = 0;\n  for (int notConvergedRoot : notConvergedRoots_) {\n    newGuessVectors.col(index) =\n        preconditionerEvaluator_->evaluate(residualVectors_.col(index), ritzEstimate_.eigenValues(notConvergedRoot));\n    ++index;\n  }\n  filterCorrectionVectors(projector, newGuessVectors);\n\n  addVectorsToGuessBasis(newGuessVectors);\n}\n\nvoid KrylovDiagonalizer::filterCorrectionVectors(const Eigen::MatrixXd& /*projector*/,\n                                                 Eigen::MatrixXd& /*newGuessVectors*/) const {\n}\n\nvoid KrylovDiagonalizer::addVectorsToGuessBasis(const Eigen::MatrixXd& newVectors) {\n  int vectorsAdded = newVectors.cols();\n  if (subspaceDimension_ + vectorsAdded < maxDimension_) {\n    subspaceDimension_ += vectorsAdded;\n    guessVectors_.conservativeResize(Eigen::NoChange, subspaceDimension_);\n    guessVectors_.rightCols(vectorsAdded) = newVectors;\n  }\n  else {\n    guessVectors_.conservativeResize(Eigen::NoChange, maxDimension_);\n    guessVectors_.rightCols(maxDimension_ - subspaceDimension_) = newVectors.leftCols(maxDimension_ - subspaceDimension_);\n    subspaceDimension_ = maxDimension_;\n  }\n}\n\nvoid KrylovDiagonalizer::onIterationStart() {\n}\n\nvoid KrylovDiagonalizer::onSigmaMatrixEvaluation(const Eigen::MatrixXd& /*projector*/) {\n}\n\nKrylovDiagonalizer::~KrylovDiagonalizer() = default;\n\n} // namespace Utils\n} // namespace Scine\n", "meta": {"hexsha": "7457d835d2d058cf1167033b24b9cdce021c2ac7", "size": 6702, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Utils/Utils/Math/IterativeDiagonalizer/KrylovDiagonalizer.cpp", "max_stars_repo_name": "qcscine/utilities", "max_stars_repo_head_hexsha": "493b8db45772b231bc0296535a09905b8e292f77", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Utils/Utils/Math/IterativeDiagonalizer/KrylovDiagonalizer.cpp", "max_issues_repo_name": "qcscine/utilities", "max_issues_repo_head_hexsha": "493b8db45772b231bc0296535a09905b8e292f77", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2019-06-19T14:34:38.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-25T15:07:18.000Z", "max_forks_repo_path": "src/Utils/Utils/Math/IterativeDiagonalizer/KrylovDiagonalizer.cpp", "max_forks_repo_name": "qcscine/utilities", "max_forks_repo_head_hexsha": "493b8db45772b231bc0296535a09905b8e292f77", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2019-06-14T16:44:19.000Z", "max_forks_repo_forks_event_max_datetime": "2020-04-19T20:48:19.000Z", "avg_line_length": 39.6568047337, "max_line_length": 124, "alphanum_fraction": 0.7563413906, "num_tokens": 1736, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7057850278370112, "lm_q2_score": 0.48438008427698437, "lm_q1q2_score": 0.3418682112651253}}
{"text": "//\r\n//=======================================================================\r\n// Copyright 2002 Marc Wintermantel (wintermantel@imes.mavt.ethz.ch)\r\n// ETH Zurich, Center of Structure Technologies (www.imes.ethz.ch/st)\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#ifndef BOOST_GRAPH_PROFILE_HPP\r\n#define BOOST_GRAPH_PROFILE_HPP\r\n\r\n#include <boost/graph/graph_traits.hpp>\r\n#include <boost/detail/numeric_traits.hpp>\r\n#include <boost/graph/bandwidth.hpp>\r\n\r\nnamespace boost {\r\n\r\n  template <typename Graph, typename VertexIndexMap>\r\n  typename graph_traits<Graph>::vertices_size_type\r\n  profile(const Graph& g, VertexIndexMap index)\r\n  {\r\n    typename graph_traits<Graph>::vertices_size_type b = 0;\r\n    typename graph_traits<Graph>::vertex_iterator i, end;\r\n    for (tie(i, end) = vertices(g); i != end; ++i){\r\n      b += ith_bandwidth(*i, g, index) + 1;\r\n    }\r\n    \r\n    return b;\r\n  }\r\n\r\n  template <typename Graph>\r\n  typename graph_traits<Graph>::vertices_size_type\r\n  profile(const Graph& g)\r\n  {\r\n    return profile(g, get(vertex_index, g));\r\n  }\r\n \r\n  \r\n} // namespace boost\r\n\r\n#endif // BOOST_GRAPH_PROFILE_HPP\r\n", "meta": {"hexsha": "8889ce3db2d8aa30faa258abacd7e467509c40af", "size": 2168, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "sdk/boost_1_30_0/boost/graph/profile.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/profile.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/profile.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.5409836066, "max_line_length": 74, "alphanum_fraction": 0.6715867159, "num_tokens": 467, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5660185351961015, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.3418366118838624}}
{"text": "//---------------------------------------------------------------------------//\n// Copyright (c) 2018-2020 Mikhail Komarov <nemo@nil.foundation>\n//\n// MIT License\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in all\n// copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n// SOFTWARE.\n//---------------------------------------------------------------------------//\n\n#ifndef CRYPTO3_DETAIL_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\n#include <boost/static_assert.hpp>\n\n#include <climits>\n#include <cstring>\n\nnamespace nil {\n    namespace crypto3 {\n        namespace detail {\n\n            // By definition, for all imploders, InputBits < OutputBits,\n            // so we're taking many smaller values and combining them into one value\n\n            template<typename Endianness, int InputBits, int OutputBits, int k>\n            struct imploder_step;\n\n            template<int UnitBits, int InputBits, int OutputBits, int k>\n            struct imploder_step<stream_endian::big_unit_big_bit<UnitBits>, InputBits, OutputBits, k> {\n                template<typename InputValue, typename OutputValue>\n                static void step(InputValue z, OutputValue &x) {\n                    int const shift = OutputBits - (InputBits + k);\n                    OutputValue y = low_bits<InputBits>(OutputValue(z));\n                    x |= unbounded_shl<shift>(y);\n                }\n            };\n\n            template<int UnitBits, int InputBits, int OutputBits, int k>\n            struct imploder_step<stream_endian::little_unit_big_bit<UnitBits>, InputBits, OutputBits, k> {\n                template<typename InputValue, typename OutputValue>\n                static void step(InputValue z, OutputValue &x) {\n                    int const kb = (k % UnitBits);\n                    int const ku = k - kb;\n                    int const shift = InputBits >= UnitBits  ? k :\n                                      OutputBits >= UnitBits ? ku + (UnitBits - (InputBits + kb)) :\n                                                               OutputBits - (InputBits + kb);\n                    OutputValue y = low_bits<InputBits>(OutputValue(z));\n                    x |= unbounded_shl<shift>(y);\n                }\n            };\n\n            template<int UnitBits, int InputBits, int OutputBits, int k>\n            struct imploder_step<stream_endian::big_unit_little_bit<UnitBits>, InputBits, OutputBits, k> {\n                template<typename InputValue, typename OutputValue>\n                static void step(InputValue z, OutputValue &x) {\n                    int const kb = (k % UnitBits);\n                    int const ku = k - kb;\n                    int const shift = InputBits >= UnitBits  ? OutputBits - (InputBits + k) :\n                                      OutputBits >= UnitBits ? OutputBits - (UnitBits + ku) + kb :\n                                                               kb;\n                    OutputValue y = low_bits<InputBits>(OutputValue(z));\n                    x |= unbounded_shl<shift>(y);\n                }\n            };\n\n            template<int UnitBits, int InputBits, int OutputBits, int k>\n            struct imploder_step<stream_endian::little_unit_little_bit<UnitBits>, InputBits, OutputBits, k> {\n                template<typename InputValue, typename OutputValue>\n                static void step(InputValue z, OutputValue &x) {\n                    int const shift = k;\n                    OutputValue y = low_bits<InputBits>(OutputValue(z));\n                    x |= unbounded_shl<shift>(y);\n                }\n            };\n\n            template<int UnitBits, int InputBits, int OutputBits, int k>\n            struct imploder_step<stream_endian::host_unit<UnitBits>, InputBits, OutputBits, k> {\n                template<typename InputValue, typename OutputValue>\n                static void step(InputValue z, OutputValue &x) {\n                    BOOST_STATIC_ASSERT(sizeof(InputValue) * CHAR_BIT == InputBits);\n                    BOOST_STATIC_ASSERT(sizeof(OutputValue) * CHAR_BIT == OutputBits);\n                    std::memcpy((char *)&x + k / CHAR_BIT, &z, InputBits / CHAR_BIT);\n                }\n            };\n\n            template<typename Endianness, int InputBits, int OutputBits, int k = 0>\n            struct imploder;\n\n            template<template<int> class Endian, int UnitBits, int InputBits, int OutputBits, int k>\n            struct imploder<Endian<UnitBits>, InputBits, OutputBits, k> {\n\n                // To keep the implementation managable, input and output sizes must\n                // be multiples or factors of the unit size.\n                // If one of these is firing, you may want a bit-only stream_endian\n                // rather than one that mentions bytes or octets.\n                BOOST_STATIC_ASSERT(!(InputBits % UnitBits && UnitBits % InputBits));\n                BOOST_STATIC_ASSERT(!(OutputBits % UnitBits && UnitBits % OutputBits));\n\n                typedef Endian<UnitBits> Endianness;\n                typedef imploder_step<Endianness, InputBits, OutputBits, k> step_type;\n                typedef imploder<Endianness, InputBits, OutputBits, k + InputBits> next_type;\n\n                template<typename InIter, typename OutputValue>\n                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 Endian, int UnitBits, int InputBits, int OutputBits>\n            struct imploder<Endian<UnitBits>, InputBits, OutputBits, OutputBits> {\n                template<typename InIter, typename OutputValue>\n                static void implode(InIter &, OutputValue &) {\n                }\n            };\n\n        }    // namespace detail\n    }        // namespace crypto3\n}    // namespace nil\n\n#endif    // CRYPTO3_BLOCK_DETAIL_IMPLODER_HPP\n", "meta": {"hexsha": "ff835cb798975e422c6ee78656844f56ff81ffac", "size": 6930, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/nil/crypto3/detail/imploder.hpp", "max_stars_repo_name": "nemo1369/vdf", "max_stars_repo_head_hexsha": "69c18131b42429e58788a7854b2deb7def217364", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2020-11-14T03:02:05.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-25T13:20:52.000Z", "max_issues_repo_path": "include/nil/crypto3/detail/imploder.hpp", "max_issues_repo_name": "nemo1369/vdf", "max_issues_repo_head_hexsha": "69c18131b42429e58788a7854b2deb7def217364", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2019-11-07T18:17:56.000Z", "max_issues_repo_issues_event_max_datetime": "2020-03-22T14:22:28.000Z", "max_forks_repo_path": "include/nil/crypto3/detail/imploder.hpp", "max_forks_repo_name": "nemo1369/vdf", "max_forks_repo_head_hexsha": "69c18131b42429e58788a7854b2deb7def217364", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-01-11T15:36:12.000Z", "max_forks_repo_forks_event_max_datetime": "2020-01-11T15:36:12.000Z", "avg_line_length": 49.5, "max_line_length": 109, "alphanum_fraction": 0.5836940837, "num_tokens": 1396, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7606506526772884, "lm_q2_score": 0.44939263446475963, "lm_q1q2_score": 0.34183080071398547}}
{"text": "// Dynamics used for integrating\n#ifndef DYNAMICS_H\n#define DYNAMICS_H\n\n#include \"segway_sim/common.hpp\"\n#include <Eigen/Dense>\n#include <math.h>\n\nstatic const double model[15] = {44.798,            //mb\n                                 2.485,             //mw\n                                 0.055936595310797, //Jw\n                                 -0.02322718759275, //a2\n                                 0.166845864363019, //c2\n                                 3.604960049044268, //A2\n                                 3.836289730154863, //B2\n                                 1.069672194414735, //C2\n                                 1.261650363363571, //K\n                                 0.195,             //r\n                                 0.5,               //L\n                                 9.81,              //gGravity\n                                 0.,                //FricCoeff 3.185188257847262\n                                 1.0e-3,            //velEps\n                                 1.225479467549329  //FricCoeff 1.225479467549329\n                                 };\n\nvoid dynamics(const double t,\n              const double X[STATE_LENGTH],\n              const double U[INPUT_LENGTH],\n                    double xDot[STATE_LENGTH])\n{\n\tdouble g[STATE_LENGTH*INPUT_LENGTH];\n\tdouble Fric;\n\tdouble a_tmp;\n\tdouble b_a_tmp;\n\tdouble f_tmp;\n\tdouble b_f_tmp;\n\tdouble c_f_tmp;\n\tdouble d_f_tmp;\n\tdouble e_f_tmp;\n\tdouble f_f_tmp;\n\tdouble g_f_tmp;\n\tdouble h_f_tmp;\n\tdouble i_f_tmp;\n\tdouble j_f_tmp;\n\tdouble k_f_tmp;\n\tdouble l_f_tmp;\n\tdouble m_f_tmp;\n\tdouble n_f_tmp;\n\tdouble o_f_tmp;\n\tdouble p_f_tmp;\n\tdouble q_f_tmp;\n\tdouble r_f_tmp;\n\tdouble s_f_tmp;\n\tdouble t_f_tmp;\n\tdouble u_f_tmp;\n\tdouble v_f_tmp;\n\tdouble f_tmp_tmp;\n\tdouble b_f_tmp_tmp;\n\tdouble w_f_tmp;\n\tdouble x_f_tmp;\n\n/*  */\n\tFric = X[3] - X[6] * model[9];\n\tFric = model[12] * tanh(Fric / model[13]) + model[14] * Fric;\n\ta_tmp = cos(X[5]);\n\tb_a_tmp = sin(X[5]);\n\txDot[0] = X[3] * cos(X[2]);\n\txDot[1] = X[3] * sin(X[2]);\n\txDot[2] = X[4];\n\tf_tmp = model[3] * model[3];\n\tb_f_tmp = model[9] * model[9];\n\tc_f_tmp = model[4] * model[4];\n\td_f_tmp = model[0] * model[0];\n\te_f_tmp = 4.0 * f_tmp;\n\tf_f_tmp = 4.0 * c_f_tmp;\n\tg_f_tmp = X[4] * X[4];\n\th_f_tmp = X[6] * X[6];\n\ti_f_tmp = 4.0 * h_f_tmp + 3.0 * g_f_tmp;\n\tj_f_tmp = cos(2.0 * X[5]);\n\tk_f_tmp = cos(3.0 * X[5]);\n\tl_f_tmp = pow(model[3], 3.0);\n\tm_f_tmp = 4.0 * model[6] * model[4] * model[0];\n\tn_f_tmp = pow(model[4], 3.0);\n\to_f_tmp = sin(2.0 * X[5]);\n\tp_f_tmp = model[5] * model[4] * model[0] * model[9] * g_f_tmp;\n\tq_f_tmp = -model[4] * model[7] * model[0] * model[9] * g_f_tmp;\n\tr_f_tmp = sin(3.0 * X[5]);\n\ts_f_tmp = 3.0 * f_tmp * model[4] * d_f_tmp * model[9] * g_f_tmp;\n\tt_f_tmp = -4.0 * model[3] * model[4];\n\tu_f_tmp = 2.0 * model[3] * model[4];\n\tv_f_tmp = f_tmp * d_f_tmp;\n\tf_tmp_tmp = v_f_tmp * b_f_tmp;\n\tb_f_tmp_tmp = c_f_tmp * d_f_tmp * b_f_tmp;\n\tf_f_tmp = 1.0 / ((((((((((4.0 * model[6] * model[2] + e_f_tmp * model[2] *\n\t\tmodel[0]) + f_f_tmp * model[2] * model[0]) + 2.0 * model[6] * model[0] *\n\tb_f_tmp) + f_tmp_tmp) + b_f_tmp_tmp) + 4.0 * model[6] * model[1] * b_f_tmp)\n\t+ e_f_tmp * model[0] * model[1] * b_f_tmp) + f_f_tmp *\n\tmodel[0] * model[1] * b_f_tmp) + (f_tmp + -c_f_tmp) *\n\td_f_tmp * b_f_tmp * j_f_tmp) + u_f_tmp * d_f_tmp * b_f_tmp *\n\to_f_tmp);\n\tw_f_tmp = 2.0 * f_tmp;\n\txDot[3] = 0.5 * model[9] * f_f_tmp * (((((((((((((((((((((((-8.0 * model[6] *\n\t\tFric + -8.0 * f_tmp * Fric * model[0]) + -8.0 * c_f_tmp * Fric * model[0]) +\n\tmodel[0] * model[9] * ((((-8.0 * model[4] * Fric + model[3] * (-model[5] +\n\t\tmodel[7]) * g_f_tmp) + 4.0 * model[3] * model[6] * (h_f_tmp + g_f_tmp)) +\n\tl_f_tmp * model[0] * i_f_tmp) + model[3] * c_f_tmp * model[0] * i_f_tmp) *\n\ta_tmp) + t_f_tmp * model[11] * d_f_tmp * model[9] * j_f_tmp) + model[3] *\n\tmodel[5] * model[0] * model[9] * g_f_tmp * k_f_tmp) + -model[3] * model[7] *\n\tmodel[0] * model[9] * g_f_tmp * k_f_tmp) + l_f_tmp * d_f_tmp * model[9] *\n\tg_f_tmp * k_f_tmp) + -3.0 * model[3] * c_f_tmp * d_f_tmp * model[9] *\n\tg_f_tmp * k_f_tmp) + 8.0 * model[3] * Fric * model[0] * model[9] * b_a_tmp)\n\t+ m_f_tmp * h_f_tmp * model[9] * b_a_tmp) + e_f_tmp * model[4] * d_f_tmp *\n\th_f_tmp * model[9] * b_a_tmp) + 4.0 * n_f_tmp * d_f_tmp * h_f_tmp * model[9]\n\t* b_a_tmp) + p_f_tmp * b_a_tmp) + m_f_tmp * model[9] * g_f_tmp * b_a_tmp) +\n\tq_f_tmp * b_a_tmp) + s_f_tmp * b_a_tmp) + 3.0 * n_f_tmp * d_f_tmp * model[9]\n\t* g_f_tmp * b_a_tmp) + w_f_tmp * model[11] * d_f_tmp * model[9] * o_f_tmp) +\n\t-2.0 * c_f_tmp * model[11] * d_f_tmp * model[9] * o_f_tmp) + p_f_tmp *\n\tr_f_tmp) + q_f_tmp * r_f_tmp) + s_f_tmp * r_f_tmp) + -n_f_tmp * d_f_tmp *\n\tmodel[9] * g_f_tmp * r_f_tmp);\n\te_f_tmp = model[10] * model[10];\n\ti_f_tmp = -2.0 * f_tmp;\n\tk_f_tmp = 2.0 * c_f_tmp;\n\tl_f_tmp = i_f_tmp * model[0];\n\tm_f_tmp = k_f_tmp * model[0];\n\tn_f_tmp = f_tmp * model[0];\n\tc_f_tmp *= model[0];\n\tp_f_tmp = model[4] * model[0];\n\tq_f_tmp = model[2] * e_f_tmp;\n\te_f_tmp *= model[1];\n\tr_f_tmp = 2.0 * (model[7] + n_f_tmp);\n\ts_f_tmp = 2.0 * (model[5] + c_f_tmp);\n\tu_f_tmp *= model[0];\n\txDot[4] = b_f_tmp * X[4] * ((-2.0 * model[3] * model[0] * X[3] * a_tmp + t_f_tmp *\n\t\tmodel[0] * X[6] * j_f_tmp) + -2.0 * (p_f_tmp * X[3] + (((model[5] + -model[7])\n\t\t\t+ l_f_tmp) + m_f_tmp) * X[6] * a_tmp) * b_a_tmp) * (1.0 / ((((q_f_tmp +\n\t\t\t\te_f_tmp * b_f_tmp) + r_f_tmp * b_f_tmp * (a_tmp * a_tmp)) + s_f_tmp *\n\t\t\tb_f_tmp * (b_a_tmp * b_a_tmp)) + u_f_tmp * b_f_tmp * o_f_tmp));\n\t\t\txDot[5] = X[6];\n\t\t\tt_f_tmp = 4.0 * model[4] * model[11];\n\t\t\tk_f_tmp = k_f_tmp * model[2] * model[0];\n\t\t\tm_f_tmp = m_f_tmp * model[1] * b_f_tmp;\n\t\t\tx_f_tmp = -(model[4] * model[4]) * d_f_tmp;\n\t\t\txDot[6] = f_f_tmp * ((((((((((((((((((((8.0 * Fric * model[2] + 4.0 * Fric *\n\t\t\t\tmodel[0] * b_f_tmp) + 8.0 * Fric * model[1] * b_f_tmp) + 2.0 * model[0] *\n\t\t\t(2.0 * model[4] * Fric * model[9] + model[3] * model[11] * (2.0 * model[2] +\n\t\t\t\t(model[0] + 2.0 * model[1]) * b_f_tmp)) * a_tmp) + -2.0 * model[3] * model[4]\n\t\t\t* model[0] * (model[0] * h_f_tmp * b_f_tmp + -2.0 * (model[2] + model[1] *\n\t\t\t\tb_f_tmp) * g_f_tmp) * j_f_tmp) + t_f_tmp * model[2] * model[0] * b_a_tmp) +\n\t\t\t-4.0 * model[3] * Fric * model[0] * model[9] * b_a_tmp) + 2.0 * model[4] *\n\t\t\tmodel[11] * d_f_tmp * b_f_tmp * b_a_tmp) + t_f_tmp * model[0] * model[1] *\n\t\t\tb_f_tmp * b_a_tmp) + v_f_tmp * h_f_tmp * b_f_tmp * o_f_tmp) + x_f_tmp *\n\t\t\th_f_tmp * b_f_tmp * o_f_tmp) + -2.0 * model[5] * model[2] * g_f_tmp *\n\t\t\to_f_tmp) + 2.0 * model[7] * model[2] * g_f_tmp * o_f_tmp) + i_f_tmp * model\n\t\t\t[2] * model[0] * g_f_tmp * o_f_tmp) + k_f_tmp * g_f_tmp * o_f_tmp) + -model\n\t\t\t[5] * model[0] * b_f_tmp * g_f_tmp * o_f_tmp) + model[7] * model[0] *\n\t\t\tb_f_tmp * g_f_tmp * o_f_tmp) + -2.0 * model[5] * model[1]\n\t\t\t* b_f_tmp * g_f_tmp * o_f_tmp) + 2.0 * model[7] * model[1]\n\t\t\t* b_f_tmp * g_f_tmp * o_f_tmp) + l_f_tmp * model[1] *\n\t\t\tb_f_tmp * g_f_tmp * o_f_tmp) + m_f_tmp * g_f_tmp * o_f_tmp);\n\t\t\tt_f_tmp = x_f_tmp * b_f_tmp;\n\t\t\tl_f_tmp = (((((((2.0 * model[6] * model[2] + w_f_tmp * model[2] * model[0]) +\n\t\t\t\tk_f_tmp) + model[6] * model[0] * b_f_tmp) + f_tmp_tmp) +\n\t\t\tb_f_tmp_tmp) + 2.0 * model[6] * model[1] * b_f_tmp) + w_f_tmp *\n\t\t\tmodel[0] * model[1] * b_f_tmp) + m_f_tmp;\n\t\t\tj_f_tmp = -f_tmp * d_f_tmp * b_f_tmp;\n\t\t\ti_f_tmp = model[3] * model[4] * d_f_tmp * b_f_tmp * o_f_tmp;\n\t\t\tg_f_tmp = p_f_tmp * model[9] * a_tmp;\n\t\t\th_f_tmp = -model[3] * model[0] * model[9] * b_a_tmp;\n\t\t\tFric = model[8] * model[9] * ((((model[6] + n_f_tmp) + c_f_tmp) + g_f_tmp) +\n\t\t\t\th_f_tmp);\n\t\t\tg[3] = Fric * (1.0 / (((l_f_tmp + t_f_tmp * (a_tmp * a_tmp)) + j_f_tmp *\n\t\t\t\t(b_a_tmp * b_a_tmp)) + i_f_tmp));\n\t\t\tg[10] = Fric * (1.0 / (((l_f_tmp + t_f_tmp * (a_tmp * a_tmp)) + j_f_tmp *\n\t\t\t\t(b_a_tmp * b_a_tmp)) + i_f_tmp));\n\t\t\tt_f_tmp = r_f_tmp * model[9];\n\t\t\tl_f_tmp = q_f_tmp * (1.0 / model[9]) + e_f_tmp * model[9];\n\t\t\tj_f_tmp = s_f_tmp * model[9];\n\t\t\ti_f_tmp = u_f_tmp * model[9] * o_f_tmp;\n\t\t\tg[4] = -model[8] * model[10] * (1.0 / (((l_f_tmp + t_f_tmp * (a_tmp * a_tmp))\n\t\t\t\t+ j_f_tmp * (b_a_tmp * b_a_tmp)) + i_f_tmp));\n\t\t\tg[11] = model[8] * model[10] * (1.0 / (((l_f_tmp + t_f_tmp * (a_tmp * a_tmp))\n\t\t\t\t+ j_f_tmp * (b_a_tmp * b_a_tmp)) + i_f_tmp));\n\t\t\tg[0] = 0.0;\n\t\t\tg[1] = 0.0;\n\t\t\tg[2] = 0.0;\n\t\t\tg[5] = 0.0;\n\t\t\tg[7] = 0.0;\n\t\t\tg[8] = 0.0;\n\t\t\tg[9] = 0.0;\n\t\t\tg[12] = 0.0;\n\t\t\tt_f_tmp = -2.0 * model[8] * ((((2.0 * model[2] + model[0] * b_f_tmp) + 2.0 *\n\t\t\t\tmodel[1] * b_f_tmp) + g_f_tmp) + h_f_tmp) * f_f_tmp;\n\t\t\tg[6] = t_f_tmp;\n\t\t\tg[13] = t_f_tmp;\n\n\t\t\tfor(int i=0; i<STATE_LENGTH; i++)\n\t\t\t{\n\t\t\t\tfor(int j=0; j<INPUT_LENGTH; j++)\n\t\t\t\t{\n\t\t\t\t\txDot[i]+=g[i+j*STATE_LENGTH]*U[j];\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n#endif", "meta": {"hexsha": "82f2ac388a0d70ef5805998bd7b43375e56d3dc9", "size": 8547, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/segway_sim/dynamics.hpp", "max_stars_repo_name": "hardikparwana/segway_sim", "max_stars_repo_head_hexsha": "792c8ed9e6e26e3e28e5f120be6822f178f17bf2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2020-10-08T03:16:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-19T02:58:53.000Z", "max_issues_repo_path": "include/segway_sim/dynamics.hpp", "max_issues_repo_name": "hardikparwana/segway_sim", "max_issues_repo_head_hexsha": "792c8ed9e6e26e3e28e5f120be6822f178f17bf2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/segway_sim/dynamics.hpp", "max_forks_repo_name": "hardikparwana/segway_sim", "max_forks_repo_head_hexsha": "792c8ed9e6e26e3e28e5f120be6822f178f17bf2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2020-10-07T22:14:12.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-21T01:22:21.000Z", "avg_line_length": 41.6926829268, "max_line_length": 83, "alphanum_fraction": 0.5406575407, "num_tokens": 3499, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7606506418255927, "lm_q2_score": 0.44939263446475963, "lm_q1q2_score": 0.3418307958373134}}
{"text": "#include <string>\n#include <vector>\n#include <map>\n#include <stdexcept>\n#include <math.h>\n#include <algorithm>\n#include <cctype>\n\n#include <fstream>\n#include <iostream>\n#include <sstream>\n#include <iterator>\n\n#include \"thermodynamics.h\"\n#include \"unitsets.h\"\n\n#include <Eigen/Dense>\n\nusing namespace std;\nusing namespace Thermodynamics::Types;\n\nusing namespace Thermodynamics::UOM::SI;\n\nnamespace Thermodynamics\n{\n\n    void Database::scan_database_file()\n    {\n        ifstream infile;\n        infile.open(this->filename);\n        if (infile.fail())\n        { // oops the file did not exist for reading?\n            cout << \"Opening Property database file \" << this->filename << \" failed.\" << endl;\n            exit(1);\n        }\n\n        string line;\n        while (getline(infile, line))\n        { //read data from file object and put it into string.\n            std::istringstream iss(line);\n            std::vector<std::string> results((std::istream_iterator<std::string>(iss)),\n                                             std::istream_iterator<std::string>());\n\n            if (results[0] == \"SYST\")\n            {\n                auto maxComp = stoi(results[3]);\n                this->NC = maxComp;\n                for (int i = 0; i < maxComp; i++)\n                {\n                    this->known_components.push_back(Substance());\n                }\n            }\n            if (results[0] == \"SHOR\")\n            {\n                auto index = stoi(results[1]) - 1;\n                this->known_components[index].identifier = results[2];\n                this->component_names.push_back(results[2]);\n            }\n            if (results[0] == \"NAME\")\n            {\n                auto index = stoi(results[1]) - 1;\n                this->known_components[index].name = results[2];\n            }\n            if (results[0] == \"CASN\")\n            {\n                auto index = stoi(results[1]) - 1;\n                this->known_components[index].casNo = results[2];\n            }\n\n            if (results[0] == \"MOLW\")\n            {\n                auto index = stoi(results[1]) - 1;\n                auto value = stod(results[3]);\n                this->known_components[index].constants.insert(\n                    {MolecularProperties::MolarWeight,\n                     Quantity(results[0], results[0], value, kg / kmol)});\n            }\n\n            if (results[0] == \"PC\")\n            {\n                auto index = stoi(results[1]) - 1;\n                auto value = stod(results[3]);\n                this->known_components[index].constants.insert(\n                    {MolecularProperties::CriticalPressure,\n                     Quantity(results[0], results[0], value, Pa)});\n            }\n            if (results[0] == \"TC\")\n            {\n                auto index = stoi(results[1]) - 1;\n                auto value = stod(results[3]);\n                this->known_components[index].constants.insert(\n                    {MolecularProperties::CriticalTemperature,\n                     Quantity(results[0], results[0], value, K)});\n            }\n            if (results[0] == \"AC\")\n            {\n                auto index = stoi(results[1]) - 1;\n                auto value = stod(results[3]);\n                this->known_components[index].constants.insert(\n                    {MolecularProperties::AcentricFactor,\n                     Quantity(results[0], results[0], value, none)});\n            }\n\n            if (results[0] == \"VP\")\n            {\n                auto index = stoi(results[1]) - 1;\n                auto function = this->parse_function(infile, results);\n                function.property = PureProperties::VaporPressure;\n                this->known_components[index].functions.insert(\n                    {PureProperties::VaporPressure,\n                     function});\n            }\n\n            if (results[0] == \"CPID\")\n            {\n                auto index = stoi(results[1]) - 1;\n                auto function = this->parse_function(infile, results);\n                function.property = PureProperties::IdealGasHeatCapacity;\n                this->known_components[index].functions.insert(\n                    {PureProperties::IdealGasHeatCapacity,\n                     function});\n            }\n            if (results[0] == \"HVAP\")\n            {\n                auto index = stoi(results[1]) - 1;\n                auto function = this->parse_function(infile, results);\n                function.property = PureProperties::HeatOfVaporization;\n                this->known_components[index].functions.insert(\n                    {PureProperties::HeatOfVaporization,\n                     function});\n            }\n            if (results[0] == \"DENL\")\n            {\n                auto index = stoi(results[1]) - 1;\n                auto function = this->parse_function(infile, results);\n                function.property = PureProperties::LiquidDensity;\n                this->known_components[index].functions.insert(\n                    {PureProperties::LiquidDensity,\n                     function});\n            }\n            if (results[0] == \"ST\")\n            {\n                auto index = stoi(results[1]) - 1;\n                auto function = this->parse_function(infile, results);\n                function.property = PureProperties::SurfaceTension;\n                this->known_components[index].functions.insert(\n                    {PureProperties::SurfaceTension,\n                     function});\n            }\n            if (results[0] == \"CL\")\n            {\n                auto index = stoi(results[1]) - 1;\n                auto function = this->parse_function(infile, results);\n                function.property = PureProperties::LiquidHeatCapacity;\n                this->known_components[index].functions.insert(\n                    {PureProperties::LiquidHeatCapacity,\n                     function});\n            }\n\n            if (results[0] == \"KLIQ\")\n            {\n                auto index = stoi(results[1]) - 1;\n                auto function = this->parse_function(infile, results);\n                function.property = PureProperties::LiquidHeatConductivity;\n                this->known_components[index].functions.insert(\n                    {PureProperties::LiquidHeatConductivity,\n                     function});\n            }\n            if (results[0] == \"KVAP\")\n            {\n                auto index = stoi(results[1]) - 1;\n                auto function = this->parse_function(infile, results);\n                function.property = PureProperties::VaporHeatConductivity;\n                this->known_components[index].functions.insert(\n                    {PureProperties::VaporHeatConductivity,\n                     function});\n            }\n            if (results[0] == \"VISL\")\n            {\n                auto index = stoi(results[1]) - 1;\n                auto function = this->parse_function(infile, results);\n                function.property = PureProperties::LiquidViscosity;\n                this->known_components[index].functions.insert(\n                    {PureProperties::LiquidViscosity,\n                     function});\n            }\n            if (results[0] == \"VISV\")\n            {\n                auto index = stoi(results[1]) - 1;\n                auto function = this->parse_function(infile, results);\n                function.property = PureProperties::VaporViscosity;\n                this->known_components[index].functions.insert(\n                    {PureProperties::VaporViscosity,\n                     function});\n            }\n            if (results[0] == \"LVEQ\")\n            {\n                if (results[2] == \"NRTL\")\n                {\n                    this->binaryparameters.insert({\"NRTL\", BinaryParameterSet(\"NRTL\", this->NC)});\n                }\n            }\n\n            if (results[0] == \"NRTL\")\n            {\n                auto matrix = results[1];\n                auto i = stoi(results[2]) - 1;\n                auto j = stoi(results[3]) - 1;\n                auto kij = stod(results[4]);\n                auto kji = stod(results[5]);\n\n                this->binaryparameters.at(\"NRTL\").set_value(matrix, i, j, kij);\n                this->binaryparameters.at(\"NRTL\").set_value(matrix, j, i, kji);\n            }\n        }\n        std::cout.flush();\n        infile.close();\n    }\n\n    PureFunction Database::parse_function(ifstream &infile, vector<string> &results)\n    {\n        auto function = PureFunction();\n\n        function.tmin = stod(results[5]);\n        function.tmax = stod(results[6]);\n\n        string paramline;\n        getline(infile, paramline);\n        std::istringstream iss2(paramline);\n        std::vector<std::string> parameters((std::istream_iterator<std::string>(iss2)), std::istream_iterator<std::string>());\n\n        function.c = Eigen::VectorXd(parameters.size());\n\n        for (size_t i = 0; i < parameters.size(); i++)\n        {\n            /* code */\n            function.c(i) = stod(parameters[i]);\n        }\n\n        function.xUnit= SI::K;\n        if (Thermodynamics::Types::NameToCorrelation.count(results[3]) > 0)\n            function.correlation = Thermodynamics::Types::NameToCorrelation[results[3]];\n        else\n            function.correlation = Thermodynamics::Types::PureCorrelations::None;\n\n        return function;\n    }\n\n    Substance Database::find_component(std::string name)\n    {\n\n        for (auto comp : this->known_components)\n        {\n            if (comp.identifier == name || comp.name == name)\n                return comp;\n        }\n\n        Substance comp;\n        comp.name = \"ERROR\";\n        comp.identifier = \"ERROR\";\n        return comp;\n    }\n\n    void Database::fill_binary_parameters(ThermodynamicSystem *system)\n    {\n        auto nrtlsys = BinaryParameterSet(\"NRTL\", system->NC);\n        auto nrtldb = this->binaryparameters.at(\"NRTL\");\n        auto matrices = {\"A\", \"B\", \"C\", \"D\", \"E\", \"F\"};\n\n        for (int i = 0; i < system->NC; i++)\n        {\n            for (int j = 0; j < system->NC; j++)\n            {\n                if (i == j)\n                    continue;\n\n                auto name_i = system->substances[i].identifier;\n                auto name_j = system->substances[j].identifier;\n\n                auto idb = find(this->component_names.begin(), this->component_names.end(), name_i);\n                int ii = distance(this->component_names.begin(), idb);\n                auto jdb = find(this->component_names.begin(), this->component_names.end(), name_j);\n                int jj = distance(this->component_names.begin(), jdb);\n\n                for (auto matrix : matrices)\n                {\n                    auto aij = nrtldb.get_value(matrix, ii, jj);\n                    auto aji = nrtldb.get_value(matrix, jj, ii);\n                    nrtlsys.set_value(matrix, i, j, aij);\n                    nrtlsys.set_value(matrix, j, i, aji);\n                }\n            }\n            system->binaryparameters.insert({\"NRTL\", nrtlsys});\n        }\n    }\n\n    std::vector<string> Database::get_component_list()\n    {\n        return this->component_names;\n    }\n\n} // namespace Thermodynamics", "meta": {"hexsha": "c375dbc8fb485ca2d55965b1bf5b3ac1fd9d7385", "size": 11072, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "openikcape/core/database.cpp", "max_stars_repo_name": "Nukleon84/openikcape", "max_stars_repo_head_hexsha": "7612a7c68237920373c11f137130d74f7ad134eb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 19.0, "max_stars_repo_stars_event_min_datetime": "2020-09-08T07:23:10.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-10T19:12:51.000Z", "max_issues_repo_path": "openikcape/core/database.cpp", "max_issues_repo_name": "Nukleon84/openikcape", "max_issues_repo_head_hexsha": "7612a7c68237920373c11f137130d74f7ad134eb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "openikcape/core/database.cpp", "max_forks_repo_name": "Nukleon84/openikcape", "max_forks_repo_head_hexsha": "7612a7c68237920373c11f137130d74f7ad134eb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-09-09T15:10:39.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-05T00:53:28.000Z", "avg_line_length": 36.6622516556, "max_line_length": 126, "alphanum_fraction": 0.4997290462, "num_tokens": 2279, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.8311430394931456, "lm_q2_score": 0.411110869232168, "lm_q1q2_score": 0.3416919374222932}}
{"text": "/*\r\nCopyright (c) 2009 Yahoo! Inc.  All rights reserved.  The copyrights\r\nembodied in the content of this file are licensed under the BSD\r\n(revised) open source license\r\n */\r\n#include <fstream>\r\n#include <vector>\r\n#include <float.h>\r\n#include <netdb.h>\r\n#include <string.h>\r\n#include <stdio.h>\r\n#include <assert.h>\r\n#include \"parse_example.h\"\r\n#include \"constant.h\"\r\n#include \"sparse_dense.h\"\r\n#include \"gd.h\"\r\n#include \"lda_core.h\"\r\n#include \"cache.h\"\r\n#include \"multisource.h\"\r\n#include \"simple_label.h\"\r\n#include \"delay_ring.h\"\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 = vx.i;\r\n  y *= 1.0f / (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 = 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 (float* gamma)\r\n{\r\n  unsigned int n = global.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 \r\nvexpdigammify_2(float*       gamma, \r\n                const float* norm)\r\n{\r\n  size_t n = global.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#warning \"lda IS NOT using sse instructions\"\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\nsize_t max_w = 0;\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. - 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(t);\r\n  double logoldt = log(old_t);\r\n  return (old_t / t) * exp(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 decayfunc2(t, old_t, power_t);\r\n}\r\n\r\nvoid expdigammify(float* gamma)\r\n{\r\n  float sum=0;\r\n  for (size_t i = 0; i<global.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<global.lda; i++)\r\n    gamma[i] = fmax(1e-10, exp(gamma[i] - sum));\r\n}\r\n\r\nvoid expdigammify_2(float* gamma, float* norm)\r\n{\r\n  for (size_t i = 0; i<global.lda; i++)\r\n    {\r\n      gamma[i] = fmax(1e-10, exp(mydigamma(gamma[i]) - norm[i]));\r\n    }\r\n}\r\n\r\nfloat average_diff(float* oldgamma, float* newgamma)\r\n{\r\n  float sum = 0.;\r\n  float normalizer = 0.;\r\n  for (size_t i = 0; i<global.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\nv_array<float> Elogtheta;\r\n\r\n// Returns E_q[log p(\\theta)] - E_q[log q(\\theta)].\r\nfloat theta_kl(float* gamma)\r\n{\r\n  float gammasum = 0;\r\n  Elogtheta.erase();\r\n  for (size_t k = 0; k < global.lda; k++) {\r\n    push(Elogtheta, 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 = -(global.lda*mylgamma(global.lda_alpha));\r\n  kl += mylgamma(global.lda_alpha*global.lda) - gammasum;\r\n  for (size_t k = 0; k < global.lda; k++) {\r\n    Elogtheta[k] -= digammasum;\r\n    kl += (global.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(float* u_for_w, float* v)\r\n{\r\n  float c_w = 0;\r\n  for (size_t k =0; k<global.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\nfloat lda_loop(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 < global.lda; i++)\r\n    {\r\n      push(new_gamma, 1.f);\r\n      push(old_gamma, 0.f);\r\n    }\r\n  size_t num_words =0;\r\n  for (size_t* i = ec->indices.begin; i != ec->indices.end; i++)\r\n    num_words += ec->subsets[*i][1] - ec->subsets[*i][0];\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)*global.lda);\r\n      myexpdigammify(v);\r\n\r\n      memcpy(old_gamma.begin,new_gamma.begin,sizeof(float)*global.lda);\r\n      memset(new_gamma.begin,0,sizeof(float)*global.lda);\r\n\r\n      score = 0;\r\n      size_t word_count = 0;\r\n      doc_length = 0;\r\n      for (size_t* i = ec->indices.begin; i != ec->indices.end; i++)\r\n\t{\r\n\t  feature *f = ec->subsets[*i][0];\r\n\t  for (; f != ec->subsets[*i][1]; f++)\r\n\t    {\r\n\t      float* u_for_w = &weights[(f->weight_index&global.thread_mask)+global.lda+1];\r\n\t      float c_w = find_cw(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 = global.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<global.lda; k++)\r\n\tnew_gamma[k] = new_gamma[k]*v[k]+global.lda_alpha;\r\n    }\r\n  while (average_diff(old_gamma.begin, new_gamma.begin) > 0.001);\r\n\r\n  ec->topic_predictions.erase();\r\n  if (ec->topic_predictions.end_array - ec->topic_predictions.begin < (int)global.lda)\r\n    reserve(ec->topic_predictions,global.lda);\r\n  memcpy(ec->topic_predictions.begin,new_gamma.begin,global.lda*sizeof(float));\r\n\r\n  score += theta_kl(new_gamma.begin);\r\n\r\n  return score / doc_length;\r\n}\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\nstd::vector<index_feature> sorted_features;\r\n\r\nvoid start_lda(gd_thread_params t)\r\n{\r\n  regressor reg = t.reg;\r\n  example* ec = NULL;\r\n\r\n  v_array<float> total_lambda;\r\n  v_array<float> total_new;\r\n  v_array<example* > examples;\r\n  v_array<int> doc_lengths;\r\n  v_array<float> digammas;\r\n  v_array<float> v;\r\n  reserve(v, global.lda*global.minibatch);\r\n  \r\n  total_lambda.erase();\r\n\r\n  for (size_t k = 0; k < global.lda; k++)\r\n    push(total_lambda, 0.f);\r\n  size_t stride = global.stride;\r\n  weight* weights = reg.weight_vectors[0];\r\n\r\n  for (size_t i =0; i <= global.thread_mask;i+=stride)\r\n    for (size_t k = 0; k < global.lda; k++)\r\n      total_lambda[k] += weights[i+k];\r\n\r\n  v_array<float> decay_levels;\r\n  push(decay_levels, 0.f);\r\n  double example_t = global.initial_t;\r\n  while ( true )\r\n    {\r\n      example_t++;\r\n      total_new.erase();\r\n      for (size_t k = 0; k < global.lda; k++)\r\n\tpush(total_new, 0.f);\r\n\r\n      sorted_features.resize(0);\r\n\r\n      float eta = -1;\r\n      float minuseta = -1;\r\n      examples.erase();\r\n      doc_lengths.erase();\r\n      size_t batch_size = global.minibatch;\r\n      for (size_t d = 0; d < batch_size; d++)\r\n\t{\r\n          push(doc_lengths, 0);\r\n\t  if ((ec = get_example(0)) != NULL)//semiblocking operation.\r\n\t    {\r\n\t      push(examples, ec);\r\n              for (size_t* i = ec->indices.begin; i != ec->indices.end; i++) {\r\n                feature* f = ec->subsets[*i][0];\r\n                for (; f != ec->subsets[*i][1]; f++) {\r\n                  index_feature temp = {(uint32_t)d, *f};\r\n                  sorted_features.push_back(temp);\r\n                  doc_lengths[d] += f->x;\r\n                }\r\n              }\r\n\t    }\r\n\t  else if (thread_done(0))\r\n\t    batch_size = d;\r\n\t  else\r\n\t    d--;\r\n\t}\r\n\r\n      sort(sorted_features.begin(), sorted_features.end());\r\n\r\n      eta = global.eta * powf(example_t, -t.vars->power_t);\r\n      minuseta = 1.0 - eta;\r\n      eta *= global.lda_D / batch_size;\r\n      push(decay_levels, decay_levels.last() + log(minuseta));\r\n\r\n      digammas.erase();\r\n      float additional = (float)(global.length()) * global.lda_rho;\r\n      for (size_t i = 0; i<global.lda; i++) {\r\n\tpush(digammas,mydigamma(total_lambda[i] + additional));\r\n      }\r\n      \r\n      size_t last_weight_index = -1;\r\n      for (index_feature* s = &sorted_features[0]; s <= &sorted_features.back(); s++)\r\n\t{\r\n\t  if (last_weight_index == s->f.weight_index)\r\n\t    continue;\r\n\t  last_weight_index = s->f.weight_index;\r\n\t  float* weights_for_w = &(weights[s->f.weight_index & global.thread_mask]);\r\n          float decay = fmin(1.0, exp(decay_levels.end[-2] - decay_levels.end[(int)(-1-example_t+weights_for_w[global.lda])]));\r\n\t  float* u_for_w = weights_for_w + global.lda+1;\r\n\r\n\t  weights_for_w[global.lda] = example_t;\r\n\t  for (size_t k = 0; k < global.lda; k++)\r\n\t    {\r\n\t      weights_for_w[k] *= decay;\r\n\t      u_for_w[k] = weights_for_w[k] + global.lda_rho;\r\n\t    }\r\n\t  myexpdigammify_2(u_for_w, digammas.begin);\r\n\t}\r\n\r\n      v.erase();\r\n\r\n      for (size_t d = 0; d < batch_size; d++)\r\n\t{\r\n          float score = lda_loop(&v[d*global.lda], weights, examples[d],t.vars->power_t);\r\n          if (global.audit)\r\n\t    print_audit_features(reg, examples[d]);\r\n          // If the doc is empty, give it loss of 0.\r\n          if (doc_lengths[d] > 0) {\r\n            global.sd->sum_loss -= score;\r\n            global.sd->sum_loss_since_last_dump -= score;\r\n          }\r\n          finish_example(examples[d]);\r\n\t}\r\n\r\n      for (index_feature* s = &sorted_features[0]; s <= &sorted_features.back();)\r\n\t{\r\n\t  index_feature* next = s+1;\r\n\t  while(next <= &sorted_features.back() && next->f.weight_index == s->f.weight_index)\r\n\t    next++;\r\n\r\n\t  float* word_weights = &(weights[s->f.weight_index & global.thread_mask]);\r\n\t  for (size_t k = 0; k < global.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\r\n\t  for (; s != next; s++) {\r\n\t    float* v_s = &v[s->document*global.lda];\r\n\t    float* u_for_w = &weights[(s->f.weight_index & global.thread_mask) + global.lda + 1];\r\n\t    float c_w = eta*find_cw(u_for_w, v_s)*s->f.x;\r\n\t    for (size_t k = 0; k < global.lda; k++) {\r\n\t      float new_value = u_for_w[k]*v_s[k]*c_w;\r\n\t      total_new[k] += new_value;\r\n \t      word_weights[k] += new_value;\r\n\t    }\r\n\t  }\r\n\t}\r\n      for (size_t k = 0; k < global.lda; k++) {\r\n\ttotal_lambda[k] *= minuseta;\r\n\ttotal_lambda[k] += total_new[k];\r\n      }\r\n\r\n      if (thread_done(0))\r\n\t{\r\n\t  for (size_t i = 0; i < global.length(); i++) {\r\n\t    weight* weights_for_w = & (weights[i*global.stride]);\r\n            float decay = fmin(1.0, exp(decay_levels.last() - decay_levels.end[(int)(-1-example_t+weights_for_w[global.lda])]));\r\n\t    for (size_t k = 0; k < global.lda; k++) {\r\n\t      weights_for_w[k] *= decay;\r\n            }\r\n\t  }\r\n\r\n\t  if (global.local_prediction > 0)\r\n\t    shutdown(global.local_prediction, SHUT_WR);\r\n\r\n\t  return;\r\n\t}\r\n    }\r\n}\r\n\r\nvoid end_lda()\r\n{\r\n  \r\n}\r\n", "meta": {"hexsha": "e60e965165a4573917885f00258d43f781cc8b37", "size": 17056, "ext": "cc", "lang": "C++", "max_stars_repo_path": "lda_core.cc", "max_stars_repo_name": "clementfarabet/vowpal_wabbit", "max_stars_repo_head_hexsha": "f851b9885a2802a5f5821b73dc3fc6210a15ddc7", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-06-09T21:48:50.000Z", "max_stars_repo_stars_event_max_datetime": "2019-06-09T21:48:50.000Z", "max_issues_repo_path": "lda_core.cc", "max_issues_repo_name": "clementfarabet/vowpal_wabbit", "max_issues_repo_head_hexsha": "f851b9885a2802a5f5821b73dc3fc6210a15ddc7", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lda_core.cc", "max_forks_repo_name": "clementfarabet/vowpal_wabbit", "max_forks_repo_head_hexsha": "f851b9885a2802a5f5821b73dc3fc6210a15ddc7", "max_forks_repo_licenses": ["BSD-3-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.4434108527, "max_line_length": 141, "alphanum_fraction": 0.5838414634, "num_tokens": 5628, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6477982179521103, "lm_q2_score": 0.5273165233795671, "lm_q1q2_score": 0.34159470414198595}}
{"text": "// json parser\n#include <boost/property_tree/json_parser.hpp>\n#include <boost/property_tree/ptree.hpp>\n#include <utility>\nnamespace pt = boost::property_tree;\n\n// integration routine\n#include \"../Calculations/Integrations.h\"\n\n#include \"../Permittivity/PermittivityFactory.h\"\n#include \"../ReflectionCoefficients/ReflectionCoefficientsFactory.h\"\n#include \"GreensTensorPlate.h\"\n\nGreensTensorPlate::GreensTensorPlate(\n    double v, double beta, double za,\n    std::shared_ptr<ReflectionCoefficients> reflection_coefficients,\n    double delta_cut, const vec::fixed<2> &rel_err)\n    : GreensTensor(v, beta), za(za), delta_cut(delta_cut), rel_err(rel_err),\n      reflection_coefficients(std::move(reflection_coefficients)) {\n\n  // assertions\n  assert(this->za >= 0);\n  assert(this->delta_cut >= 0);\n  assert(this->rel_err(0) >= 0 && this->rel_err(1) >= 0);\n}\n\nGreensTensorPlate::GreensTensorPlate(const std::string &input_file)\n    : GreensTensor(input_file) {\n  this->reflection_coefficients =\n      ReflectionCoefficientsFactory::create(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>(\"GreensTensor.type\");\n  assert(type == \"plate\");\n\n  // read parameters\n  this->za = root.get<double>(\"GreensTensor.za\");\n  this->delta_cut = root.get<double>(\"GreensTensor.delta_cut\");\n  this->rel_err(0) = root.get<double>(\"GreensTensor.rel_err_0\");\n  this->rel_err(1) = root.get<double>(\"GreensTensor.rel_err_1\");\n\n  // assertions\n  assert(this->za >= 0);\n  assert(this->delta_cut >= 0);\n  assert(this->rel_err(0) >= 0 && this->rel_err(1) >= 0);\n}\n\nvoid GreensTensorPlate::calculate_tensor(double omega, vec::fixed<2> k,\n                                         cx_mat::fixed<3, 3> &GT) const {\n  // imaginary unit\n  std::complex<double> I(0.0, 1.0);\n\n  // load wavevectors from the struct into the corresponding variables\n  double kx = k(0);\n  double ky = k(1);\n  double k_quad = kx * kx + ky * ky;\n\n  // squared and absolute value of the frequency\n  // The tensor is calculated for a positive frequency omega\n  // and afterwards transformed with respect to the sign of omega\n  double omega_abs = std::abs(omega);\n  double omega_quad = omega_abs * omega_abs;\n\n  // propagation in free space and within the surface material\n  // kappa is defined to have either a purely\n  // positive real part or purely negatively imaginary part\n  std::complex<double> kappa =\n      sqrt(std::complex<double>(k_quad - omega_quad, 0.));\n  kappa = std::complex<double>(std::abs(kappa.real()), -std::abs(kappa.imag()));\n\n  // produce the reflection coefficients in s- and p-polarization\n  std::complex<double> r_p, r_s;\n  reflection_coefficients->calculate(omega_abs, kappa, r_p, r_s);\n\n  // For an better overview and a efficient calculation, the\n  // pre-factors of the p and s polarization are collected separately\n  std::complex<double> pre = (2 * M_PI) * exp(-(2 * za) * kappa);\n  std::complex<double> prefactor_s =\n      pre * r_s * omega_quad / (k_quad - omega_quad);\n  std::complex<double> prefactor_p = pre * r_p;\n\n  // In the following, odd orders in ky are already omitted\n  GT.zeros();\n  GT(0, 0) = (prefactor_p * kx * kx + prefactor_s * ky * ky) * kappa / k_quad;\n  GT(1, 1) = (prefactor_p * ky * ky + prefactor_s * kx * kx) * kappa / k_quad;\n  GT(2, 2) = prefactor_p * k_quad / kappa;\n  GT(2, 0) = I * prefactor_p * kx;\n  GT(0, 2) = -GT(2, 0);\n\n  // In case of negative frequencies, the tensor has to be hermitian transposed\n  if (omega < 0) {\n    GT = trans(GT);\n  }\n}\n\nvoid GreensTensorPlate::integrate_k(double omega, cx_mat::fixed<3, 3> &GT,\n                                    Tensor_Options fancy_complex,\n                                    Weight_Options weight_function) const {\n\n  // imaginary unit\n  std::complex<double> I(0.0, 1.0);\n\n  // intialize Green's tensor\n  GT.zeros();\n\n  // calculate the five non-zero elements of the Green's tensor. Here, the\n  // symmetry in y direction was already applied. Thus, the integration only\n  // consideres twice the domain from 0 to pi.\n\n  // the xx element\n  auto F_xx = [=](double x) -> double {\n    return this->integrand_1d_k(x, omega, {0, 0}, fancy_complex,\n                                weight_function);\n  };\n  GT(0, 0) = cquad(F_xx, 0, M_PI, rel_err(1), 0) / M_PI;\n\n  // the yy element\n  auto F_yy = [=](double x) -> double {\n    return this->integrand_1d_k(x, omega, {1, 1}, fancy_complex,\n                                weight_function);\n  };\n  GT(1, 1) = cquad(F_yy, 0, M_PI, rel_err(1), 0) / M_PI;\n\n  // the zz element\n  auto F_zz = [=](double x) -> double {\n    return this->integrand_1d_k(x, omega, {2, 2}, fancy_complex,\n                                weight_function);\n  };\n  GT(2, 2) = cquad(F_zz, 0, M_PI, rel_err(1), 0) / M_PI;\n\n  // the zx element\n  auto F_zx = [=](double x) -> double {\n    return this->integrand_1d_k(x, omega, {2, 0}, fancy_complex,\n                                weight_function);\n  };\n  GT(2, 0) = I * cquad(F_zx, 0, M_PI, rel_err(1), 0) / M_PI;\n\n  // the xz element\n  GT(0, 2) = -GT(2, 0);\n}\n\ndouble GreensTensorPlate::integrand_1d_k(double phi, double omega,\n                                         const uvec::fixed<2> &indices,\n                                         Tensor_Options fancy_complex,\n                                         Weight_Options weight_function) const {\n\n  double result;\n\n  // The cut-off parameters acts as upper bound of the kappa integration.\n  double kappa_cut = delta_cut / (2 * za);\n\n  // read integration variable phi\n  double cos_phi = std::cos(phi);\n\n  // define integrand\n  auto F = [=](double x) -> double {\n    return this->integrand_2d_k(x, omega, phi, indices, fancy_complex,\n                                weight_function);\n  };\n\n  // Calculate low-temperature edge\n  double edge = std::abs(omega / (v * cos_phi));\n\n  // Calculate the integrand corresponding to the given options. To resolve the\n  // probably sharp edge of the Bose-Einstein distribution, the integration is\n  // split at the edge, if the edged lies below the cut-off kappa_cut.\n  if ( (kappa_cut > edge) && (2*za/v < beta) ) {\n    result = cquad(F, 0, std::abs(omega / (v * cos_phi)), rel_err(0), 0);\n    result += cquad(F, edge, kappa_cut, rel_err(0), std::abs(result)*rel_err(0));\n  } else {\n    result = cquad(F, 0, kappa_cut, rel_err(0), 0);\n  }\n    result += cquad(F, -std::abs(omega), 0, rel_err(0), std::abs(result)*rel_err(0));\n\n  return result;\n}\n\ndouble GreensTensorPlate::integrand_2d_k(double kappa_double, double omega,\n                                         double phi,\n                                         const uvec::fixed<2> &indices,\n                                         Tensor_Options fancy_complex,\n                                         Weight_Options weight_function) const {\n\n  double v_quad = v * v;\n  double omega_quad = omega * omega;\n  double cos_phi = cos(phi);\n  double cos_phi_quad = cos_phi * cos_phi;\n  double sin_phi_quad = 1.0 - cos_phi_quad;\n\n  // Before the real or imaginary part of the chosen matrix element can be\n  // calculated, the complex result is stored in result_complex.\n  std::complex<double> result_complex;\n  double result = 0.;\n\n  // imaginary unit\n  std::complex<double> I(0.0, 1.0);\n\n  // permittivity and propagation through vacuum (kappa) and surface material\n  std::complex<double> kappa_complex;\n  double kappa_quad;\n  // Transfer kappa to the correct complex value\n  if (kappa_double < 0.0) {\n    kappa_complex = std::complex<double>(0.0, kappa_double);\n    kappa_quad = -kappa_double * kappa_double;\n  } else {\n    kappa_complex = std::complex<double>(kappa_double, 0.0);\n    kappa_quad = kappa_double * kappa_double;\n  }\n\n  // Express kappa via frequency and kappa.\n  // In order to achieve the desired accuracy, we subtract first \n  // (kappa^2 + omega^2), since this might be equal zero.\n  double k = (sqrt((kappa_quad + omega_quad)- kappa_quad * v_quad * cos_phi_quad) +\n              v * omega * cos_phi) / (1.E0 - v_quad * cos_phi_quad);\n  double k_quad = k * k;\n\n  // Define the Doppler-shifted frequency\n  double omega_pl = (omega + k * cos_phi * v);\n  double omega_pl_quad = omega_pl * omega_pl;\n\n  // In order to obey reality in time, a positive omega_pl is used for the\n  // actual calculation. Afterwards, the corresponding symmetry operation is\n  // performed if the sign of omega_pl is negative.\n  double omega_pl_abs = std::abs(omega_pl);\n\n  // producing the reflection coefficients in p- and s-polarization\n  // reflection coefficients and pre-factors of the corresponding polarization\n  std::complex<double> r_p, r_s;\n  reflection_coefficients->calculate(omega_pl_abs, kappa_complex, r_p, r_s);\n\n  // Impose reality in time\n  if (omega_pl < 0) {\n    r_s = conj(r_s);\n    r_p = conj(r_p);\n    kappa_complex = conj(kappa_complex);\n  }\n\n  // helpful prefactors\n  // general prefactor with volume element and exponential\n  std::complex<double> prefactor = std::abs(kappa_complex) *\n                                   exp(-2 * za * kappa_complex) /\n                                   (1. - cos_phi * v * omega_pl / k);\n  // For an better overview and a efficient calculation, we collect the\n  // pre-factors of the p and s polarization separately\n  std::complex<double> prefactor_s =\n      prefactor * r_s * omega_pl_quad / kappa_complex;\n  std::complex<double> prefactor_p = prefactor * r_p * kappa_complex;\n\n  // Calculate the G_xx element\n  if (indices(0) == 0 && indices(1) == 0) {\n    result_complex = prefactor_p * cos_phi_quad + prefactor_s * sin_phi_quad;\n  }\n  // Calculate the G_yy element\n  else if (indices(0) == 1 && indices(1) == 1) {\n    result_complex = prefactor_p * sin_phi_quad + prefactor_s * cos_phi_quad;\n  }\n  // Calculate the G_zz element\n  else if (indices(0) == 2 && indices(1) == 2) {\n    result_complex = prefactor_p * k_quad / kappa_quad;\n  }\n  // Calculate the G_zx element\n  else if (indices(0) == 2 && indices(1) == 0) {\n    result_complex = prefactor_p * I * cos_phi * k / kappa_complex;\n  }\n  // Calculate the G_xz element\n  else if (indices(0) == 0 && indices(1) == 2) {\n    result_complex = -prefactor_p * I * cos_phi * k / kappa_complex;\n  } else {\n    result_complex = 0.;\n  }\n\n  // Add weighting function if demanded\n  if (weight_function == KV) {\n    result_complex *= k * cos_phi;\n  } else if (weight_function == TEMP) {\n    result_complex /= (1.0 - exp(-beta * omega_pl));\n  } else if (weight_function == NON_LTE) {\n    result_complex *=\n        1. / (1.0 - exp(-beta * omega_pl)) - 1. / (1.0 - exp(-beta * omega));\n  } else if (weight_function == KV_TEMP) {\n    result_complex *= k * cos_phi / (1.0 - exp(-beta * omega_pl));\n  } else if (weight_function == KV_NON_LTE) {\n    result_complex *=\n        k * cos_phi *\n        (1. / (1.0 - exp(-beta * omega_pl)) - 1. / (1.0 - exp(-beta * omega)));\n  }\n\n  // Calculate fancy real part of the given matrix element\n  if (fancy_complex == RE) {\n    if ((indices(0) == 2 && indices(1) == 0) ||\n        (indices(0) == 0 && indices(1) == 2)) {\n      // Mind the missing leading I! This must be added after the double\n      // integration!\n      result = result_complex.imag();\n    } else {\n      result = result_complex.real();\n    }\n  }\n  // Calculate fancy imaginary part of the given matrix element\n  else if (fancy_complex == IM) {\n    if ((indices(0) == 2 && indices(1) == 0) ||\n        (indices(0) == 0 && indices(1) == 2)) {\n      // Mind the missing leading I! This must be added after the double\n      // integration!\n      result = -result_complex.real();\n    } else {\n      result = result_complex.imag();\n    }\n  }\n\n  return result;\n}\n\nstd::complex<double> GreensTensorPlate::get_r_p(double omega, double k) const {\n  std::complex<double> r_p, r_s;\n  std::complex<double> kappa;\n  if (k < omega) {\n    kappa = std::complex<double>(0., -sqrt(omega * omega - k * k));\n  } else {\n    kappa = std::complex<double>(sqrt(k * k - omega * omega), 0.);\n  }\n  reflection_coefficients->calculate(omega, kappa, r_p, r_s);\n  return r_p;\n}\n\nstd::complex<double> GreensTensorPlate::get_r_s(double omega, double k) const {\n  std::complex<double> r_s, r_p;\n  std::complex<double> kappa;\n  if (k < omega) {\n    kappa = std::complex<double>(0., -sqrt(omega * omega - k * k));\n  } else {\n    kappa = std::complex<double>(sqrt(k * k - omega * omega), 0.);\n  }\n  reflection_coefficients->calculate(omega, kappa, r_p, r_s);\n  return r_s;\n}\n\ndouble GreensTensorPlate::omega_ch() const {\n  // Calculate omega_cut (reasonable for every plate setup)\n  return this->delta_cut * this->v / this->za;\n}\n\nvoid GreensTensorPlate::print_info(std::ostream &stream) const {\n  stream << \"# GreensTensorPlate\\n#\\n\"\n         << \"# v = \" << v << \"\\n\"\n         << \"# beta = \" << beta << \"\\n\"\n         << \"# za = \" << za << \"\\n\"\n         << \"# delta_cut = \" << delta_cut << \"\\n\"\n         << \"# rel_err = \" << rel_err(0) << \",\" << rel_err(1) << \"\\n\";\n}\n", "meta": {"hexsha": "92e6f4d6b1f7b6f43b1b829b25d186535cccfca2", "size": 12929, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/GreensTensor/GreensTensorPlate.cpp", "max_stars_repo_name": "QuaCaTeam/quaca", "max_stars_repo_head_hexsha": "ab2d213f3e0e357bd72930ae1e4e703184130270", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-05-19T09:01:40.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-20T07:57:54.000Z", "max_issues_repo_path": "src/GreensTensor/GreensTensorPlate.cpp", "max_issues_repo_name": "myoelmy/quaca", "max_issues_repo_head_hexsha": "def47981b710a73f2fb3a7c14c354f8de91cf88f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 31.0, "max_issues_repo_issues_event_min_datetime": "2020-05-19T08:01:46.000Z", "max_issues_repo_issues_event_max_datetime": "2020-05-28T07:33:35.000Z", "max_forks_repo_path": "src/GreensTensor/GreensTensorPlate.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.2156862745, "max_line_length": 85, "alphanum_fraction": 0.6288962797, "num_tokens": 3596, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6477982043529715, "lm_q2_score": 0.5273165233795671, "lm_q1q2_score": 0.3415946969709353}}
{"text": "//==============================================================================\n//         Copyright 2003 - 2012   LASMEA UMR 6602 CNRS/Univ. Clermont II\n//         Copyright 2009 - 2013   LRI    UMR 8623 CNRS/Univ Paris Sud XI\n//\n//          Distributed under the Boost Software License, Version 1.0.\n//                 See accompanying file LICENSE.txt or copy at\n//                     http://www.boost.org/LICENSE_1_0.txt\n//==============================================================================\n#ifndef NT2_LINALG_FUNCTIONS_LAPACK_PLINSOLVE_HPP_INCLUDED\n#define NT2_LINALG_FUNCTIONS_LAPACK_PLINSOLVE_HPP_INCLUDED\n\n#include <nt2/linalg/functions/plinsolve.hpp>\n#include <nt2/include/functions/gesvx.hpp>\n#include <nt2/include/functions/sysvx.hpp>\n#include <nt2/include/functions/clinsolve.hpp>\n#include <nt2/include/functions/posvx.hpp>\n#include <nt2/include/functions/of_size.hpp>\n#include <nt2/include/functions/resize.hpp>\n#include <nt2/include/functions/zeros.hpp>\n#include <nt2/linalg/options.hpp>\n#include <nt2/linalg/functions/details/eval_linsolve.hpp>\n#include <nt2/sdk/meta/settings_of.hpp>\n#include <nt2/sdk/meta/as_real.hpp>\n\n#include <nt2/include/functions/tie.hpp>\n#include <nt2/core/container/table/table.hpp>\n#include <boost/dispatch/meta/terminal_of.hpp>\n#include <boost/core/ignore_unused.hpp>\n\nnamespace nt2 { namespace ext\n{\n  //============================================================================\n  // LINSOLVE\n  //============================================================================\n  BOOST_DISPATCH_IMPLEMENT  ( plinsolve_, tag::cpu_\n                            , (A0)(A1)(A2)(N2)\n                            , ((ast_<A0, nt2::container::domain>))  // A\n                              ((ast_<A1, nt2::container::domain>))  // B\n                              ((node_<A2, nt2::tag::tie_             // X-R\n                                    , N2, nt2::container::domain\n                                     >\n                              ))\n                            )\n  {\n    typedef void  result_type;\n    typedef typename A0::value_type ctype_t;\n    typedef typename nt2::meta::as_real<ctype_t>::type   type_t;\n    typedef typename meta::option<typename A0::settings_type,nt2::tag::shape_>::type shape;\n    typedef nt2::memory::container<tag::table_, ctype_t, nt2::settings(nt2::_2D)> desired_semantic;\n    typedef nt2::memory::container<tag::table_, ctype_t, nt2::settings(nt2::_2D,shape)> desired_semantic1;\n\n    BOOST_FORCEINLINE result_type operator()( A0 const& a0, A1 const& a1, A2 const&  a2 ) const\n    {\n      eval(a0,a1,a2,N2(),shape());\n    }\n\n    //==========================================================================\n    /// INTERNAL ONLY - Shape analysis\n\n    /// INTERNAL ONLY - X = LINSOLVE(A,B) -- Rectangular shape\n    BOOST_FORCEINLINE\n    void eval ( A0 const& a0, A1 const& a1 , A2 const& a2 ,boost::mpl::long_<1> const\n              , nt2::rectangular_ const&) const\n    {\n      type_t rcond;\n      boost::proto::child_c<0>(a2).resize(nt2::of_size(a0.leading_size(),1));\n      NT2_AS_TERMINAL_IN(desired_semantic1,a,a0);\n      NT2_AS_TERMINAL_IN(desired_semantic,b,a1);\n      nt2::gesvx( boost::proto::value(a), boost::proto::value(b)\n              , boost::proto::value(boost::proto::child_c<0>(a2)), rcond );\n    }\n\n    //==========================================================================\n    /// INTERNAL ONLY - [X,R] = LINSOLVE(A,B) -- Rectangular shape\n    BOOST_FORCEINLINE\n    void eval ( A0 const& a0, A1 const& a1 , A2 const& a2 ,boost::mpl::long_<2> const\n              , nt2::rectangular_ const&) const\n    {\n      type_t rcond;\n      boost::proto::child_c<0>(a2).resize(nt2::of_size(a0.leading_size(),1));\n      NT2_AS_TERMINAL_IN(desired_semantic1,a,a0);\n      NT2_AS_TERMINAL_IN(desired_semantic,b,a1);\n      nt2::gesvx( boost::proto::value(a), boost::proto::value(b)\n              , boost::proto::value(boost::proto::child_c<0>(a2))\n              , rcond );\n      boost::proto::child_c<1>(a2) = rcond;\n    }\n\n    //==========================================================================\n    /// INTERNAL ONLY - X = LINSOLVE(A,B) -- symmetric shape\n    BOOST_FORCEINLINE\n    void eval ( A0 const& a0, A1 const& a1 , A2 const& a2 ,boost::mpl::long_<1> const\n              , nt2::symmetric_ const&) const\n    {\n      type_t rcond;\n      nt2::container::table<nt2_la_int> piv = nt2::zeros(a0.leading_size(), 1\n                                            , nt2::meta::as_<nt2_la_int>() );\n      boost::proto::child_c<0>(a2).resize(nt2::of_size(a0.leading_size(),1));\n      NT2_AS_TERMINAL_IN(desired_semantic1,a,a0);\n      NT2_AS_TERMINAL_IN(desired_semantic,b,a1);\n      nt2_la_int iter = nt2::sysvx( boost::proto::value(a),boost::proto::value(piv)\n                                 , boost::proto::value(b)\n                                 , boost::proto::value(boost::proto::child_c<0>(a2))\n                                 , rcond);\n      boost::ignore_unused(iter);\n    }\n\n    //==========================================================================\n    /// INTERNAL ONLY - [X,R] = LINSOLVE(A,B) -- symmetric shape\n    BOOST_FORCEINLINE\n    void eval ( A0 const& a0, A1 const& a1 , A2 const& a2 ,boost::mpl::long_<2> const\n              , nt2::symmetric_ const&) const\n    {\n      type_t rcond;\n      nt2::container::table<nt2_la_int> piv(nt2::of_size(a0.leading_size(),1));\n      boost::proto::child_c<0>(a2).resize(nt2::of_size(a0.leading_size(),1));\n      NT2_AS_TERMINAL_IN(desired_semantic1,a,a0);\n      NT2_AS_TERMINAL_IN(desired_semantic,b,a1);\n      nt2_la_int iter = nt2::sysvx( boost::proto::value(a),boost::proto::value(piv)\n                                 , boost::proto::value(b)\n                                 , boost::proto::value(boost::proto::child_c<0>(a2))\n                                 , rcond);\n\n      boost::ignore_unused(iter);\n      boost::proto::child_c<1>(a2) = rcond;\n    }\n\n    //==========================================================================\n    /// INTERNAL ONLY - X = LINSOLVE(A,B) -- positive definite shape\n    BOOST_FORCEINLINE\n    void eval ( A0 const& a0, A1 const& a1 , A2 const& a2 ,boost::mpl::long_<1> const\n              , nt2::positive_definite_ const&) const\n    {\n      type_t rcond;\n      boost::proto::child_c<0>(a2).resize(nt2::of_size(a0.leading_size(),1));\n      NT2_AS_TERMINAL_IN(desired_semantic1,a,a0);\n      NT2_AS_TERMINAL_IN(desired_semantic,b,a1);\n      nt2_la_int iter = nt2::posvx( boost::proto::value(a), boost::proto::value(b)\n                                  , boost::proto::value(boost::proto::child_c<0>(a2))\n                                  , rcond);\n      boost::ignore_unused(iter);\n    }\n\n    //==========================================================================\n    /// INTERNAL ONLY - [X,R] = LINSOLVE(A,B) -- positive definite shape\n    BOOST_FORCEINLINE\n    void eval ( A0 const& a0, A1 const& a1 , A2 const& a2 ,boost::mpl::long_<2> const\n              , nt2::positive_definite_ const&) const\n    {\n      type_t rcond;\n      boost::proto::child_c<0>(a2).resize(nt2::of_size(a0.leading_size(),1));\n      NT2_AS_TERMINAL_IN(desired_semantic1,a,a0);\n      NT2_AS_TERMINAL_IN(desired_semantic,b,a1);\n      nt2_la_int iter = nt2::posvx( boost::proto::value(a), boost::proto::value(b)\n                                  , boost::proto::value(boost::proto::child_c<0>(a2))\n                                  , rcond);\n\n      boost::ignore_unused(iter);\n      boost::proto::child_c<1>(a2) = rcond;\n    }\n\n    /// INTERNAL ONLY - No info on this shape\n    template<typename N,typename sh>\n    BOOST_FORCEINLINE\n    void eval ( A0 const& a0, A1 const& a1, A2 const& a2, N const&, sh const&) const\n    {\n      nt2::clinsolve(a0,a1,a2);\n    }\n\n  };\n\n\n} }\n\n\n#endif\n", "meta": {"hexsha": "a14d7ddbe645bcdc8220840cdd67aec00bc9e721", "size": 7762, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/core/linalg/include/nt2/linalg/functions/lapack/plinsolve.hpp", "max_stars_repo_name": "psiha/nt2", "max_stars_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 34.0, "max_stars_repo_stars_event_min_datetime": "2017-05-19T18:10:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-04T02:18:13.000Z", "max_issues_repo_path": "modules/core/linalg/include/nt2/linalg/functions/lapack/plinsolve.hpp", "max_issues_repo_name": "psiha/nt2", "max_issues_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "modules/core/linalg/include/nt2/linalg/functions/lapack/plinsolve.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": 43.8531073446, "max_line_length": 106, "alphanum_fraction": 0.5329811904, "num_tokens": 1997, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.63341027751814, "lm_q2_score": 0.5389832206876841, "lm_q1q2_score": 0.3413975113934069}}
{"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_LA_SOLVER_EIGEN_HH\n#define DUNE_STUFF_LA_SOLVER_EIGEN_HH\n\n#include <string>\n#include <vector>\n#include <algorithm>\n#include <sstream>\n#include <cmath>\n#include <complex>\n\n#include <dune/stuff/common/disable_warnings.hh>\n#if HAVE_EIGEN\n#include <Eigen/Dense>\n#include <Eigen/SparseCore>\n#include <Eigen/IterativeLinearSolvers>\n#include <Eigen/SparseCholesky>\n#include <Eigen/SparseLU>\n#include <Eigen/SparseQR>\n//#   if HAVE_UMFPACK\n//#     include <Eigen/UmfPackSupport>\n//#   endif\n//#   include <Eigen/SPQRSupport>\n//#   include <Eigen/CholmodSupport>\n//#   if HAVE_SUPERLU\n//#     include <Eigen/SuperLUSupport>\n//#   endif\n#endif // HAVE_EIGEN\n#include <dune/stuff/common/reenable_warnings.hh>\n\n#include <dune/stuff/common/exceptions.hh>\n#include <dune/stuff/common/configuration.hh>\n#include <dune/stuff/la/container/eigen.hh>\n\n#include \"../solver.hh\"\n\nnamespace Dune {\nnamespace Stuff {\nnamespace LA {\n\n#if HAVE_EIGEN\n\ntemplate <class S, class CommunicatorType>\nclass Solver<EigenDenseMatrix<S>, CommunicatorType> : protected SolverUtils\n{\npublic:\n  typedef EigenDenseMatrix<S> MatrixType;\n  typedef typename MatrixType::RealType R;\n\n  Solver(const MatrixType& matrix) : matrix_(matrix) {}\n\n  Solver(const MatrixType& matrix, const CommunicatorType& /*communicator*/) : matrix_(matrix) {}\n\n  static std::vector<std::string> types()\n  {\n    return {\"lu.partialpiv\",\n            \"qr.householder\",\n            \"llt\",\n            \"ldlt\",\n            \"qr.colpivhouseholder\",\n            \"qr.fullpivhouseholder\",\n            \"lu.fullpiv\"};\n  } // ... types()\n\n  static Common::Configuration options(const std::string type = \"\")\n  {\n    const std::string tp = !type.empty() ? type : types()[0];\n    SolverUtils::check_given(tp, types());\n    Common::Configuration default_options({\"type\", \"post_check_solves_system\", \"check_for_inf_nan\"}, {tp, \"1e-5\", \"1\"});\n    // * for symmetric matrices\n    if (tp == \"ldlt\" || tp == \"llt\") {\n      default_options.set(\"pre_check_symmetry\", \"1e-8\");\n    }\n    return default_options;\n  } // ... options(...)\n\n  template <class T1, class T2>\n  void apply(const EigenBaseVector<T1, S>& rhs, EigenBaseVector<T2, S>& solution) const\n  {\n    apply(rhs, solution, types()[0]);\n  }\n\n  template <class T1, class T2>\n  void apply(const EigenBaseVector<T1, S>& rhs, EigenBaseVector<T2, S>& solution, const std::string& type) const\n  {\n    apply(rhs, solution, options(type));\n  }\n\n  template <class T1, class T2>\n  void apply(const EigenBaseVector<T1, S>& rhs, EigenBaseVector<T2, S>& solution,\n             const Common::Configuration& opts) const\n  {\n    if (!opts.has_key(\"type\"))\n      DUNE_THROW(Exceptions::configuration_error,\n                 \"Given options (see below) need to have at least the key 'type' set!\\n\\n\" << opts);\n    const auto type = opts.get<std::string>(\"type\");\n    SolverUtils::check_given(type, types());\n    const Common::Configuration default_opts = options(type);\n    // check for inf or nan\n    const bool check_for_inf_nan = opts.get(\"check_for_inf_nan\", default_opts.get<bool>(\"check_for_inf_nan\"));\n    if (check_for_inf_nan) {\n      for (size_t ii = 0; ii < matrix_.rows(); ++ii) {\n        for (size_t jj = 0; jj < matrix_.cols(); ++jj) {\n          const S& val = matrix_.backend()(ii, jj);\n          if (Common::isnan(val) || Common::isinf(val)) {\n            std::stringstream msg;\n            msg << \"Given matrix contains inf or nan and you requested checking (see options below)!\\n\"\n                << \"If you want to disable this check, set 'check_for_inf_nan = 0' in the options.\\n\\n\"\n                << \"Those were the given options:\\n\\n\" << opts;\n            if (rhs.size() <= internal::max_size_to_print)\n              msg << \"\\nThis was the given matrix:\\n\\n\" << matrix_ << \"\\n\";\n            DUNE_THROW(Exceptions::linear_solver_failed_bc_data_did_not_fulfill_requirements, msg.str());\n          }\n        }\n      }\n      for (size_t ii = 0; ii < rhs.size(); ++ii) {\n        const S& val = rhs[ii];\n        if (Common::isnan(val) || Common::isinf(val)) {\n          std::stringstream msg;\n          msg << \"Given rhs contains inf or nan and you requested checking (see options below)!\\n\"\n              << \"If you want to disable this check, set 'check_for_inf_nan = 0' in the options.\\n\\n\"\n              << \"Those were the given options:\\n\\n\" << opts;\n          if (rhs.size() <= internal::max_size_to_print)\n            msg << \"\\nThis was the given right hand side:\\n\\n\" << rhs << \"\\n\";\n          DUNE_THROW(Exceptions::linear_solver_failed_bc_data_did_not_fulfill_requirements, msg.str());\n        }\n      }\n    }\n    // check for symmetry (if solver needs it)\n    if (type == \"ldlt\" || type == \"llt\") {\n      const R pre_check_symmetry_threshhold = opts.get(\"pre_check_symmetry\", default_opts.get<R>(\"pre_check_symmetry\"));\n      if (pre_check_symmetry_threshhold > 0) {\n        const MatrixType tmp(matrix_.backend() - matrix_.backend().adjoint());\n        // serialize difference to compute L^\\infty error (no copy done here)\n        const R error = std::max(tmp.backend().cwiseAbs().minCoeff(), tmp.backend().cwiseAbs().maxCoeff());\n        if (error > pre_check_symmetry_threshhold) {\n          std::stringstream msg;\n          msg << \"Given matrix is not symmetric and you requested checking (see options below)!\\n\"\n              << \"If you want to disable this check, set 'pre_check_symmetry = 0' in the options.\\n\\n\"\n              << \"  (A - A').sup_norm() = \" << error << \"\\n\\n\"\n              << \"Those were the given options:\\n\\n\" << opts;\n          if (rhs.size() <= internal::max_size_to_print)\n            msg << \"\\nThis was the given matrix A:\\n\\n\" << matrix_ << \"\\n\";\n          DUNE_THROW(Exceptions::linear_solver_failed_bc_data_did_not_fulfill_requirements, msg.str());\n        }\n      }\n    }\n    // solve\n    if (type == \"qr.colpivhouseholder\") {\n      solution.backend() = matrix_.backend().colPivHouseholderQr().solve(rhs.backend());\n    } else if (type == \"qr.fullpivhouseholder\")\n      solution.backend() = matrix_.backend().fullPivHouseholderQr().solve(rhs.backend());\n    else if (type == \"qr.householder\")\n      solution.backend() = matrix_.backend().householderQr().solve(rhs.backend());\n    else if (type == \"lu.fullpiv\")\n      solution.backend() = matrix_.backend().fullPivLu().solve(rhs.backend());\n    else if (type == \"llt\")\n      solution.backend() = matrix_.backend().llt().solve(rhs.backend());\n    else if (type == \"ldlt\")\n      solution.backend() = matrix_.backend().ldlt().solve(rhs.backend());\n    else if (type == \"lu.partialpiv\")\n      solution.backend() = matrix_.backend().partialPivLu().solve(rhs.backend());\n    else\n      DUNE_THROW(Exceptions::internal_error,\n                 \"Given type '\" << type << \"' is not supported, although it was reported by types()!\");\n    // check\n    if (check_for_inf_nan)\n      for (size_t ii = 0; ii < solution.size(); ++ii) {\n        const S& val = solution[ii];\n        if (Common::isnan(val) || Common::isinf(val)) {\n          std::stringstream msg;\n          msg << \"The computed solution contains inf or nan and you requested checking (see options \"\n              << \"below)!\\n\"\n              << \"If you want to disable this check, set 'check_for_inf_nan = 0' in the options.\\n\\n\"\n              << \"Those were the given options:\\n\\n\" << opts;\n          if (rhs.size() <= internal::max_size_to_print)\n            msg << \"\\nThis was the given matrix A:\\n\\n\" << matrix_ << \"\\nThis was the given right hand side b:\\n\\n\"\n                << rhs << \"\\nThis is the computed solution:\\n\\n\" << solution << \"\\n\";\n          DUNE_THROW(Exceptions::linear_solver_failed_bc_data_did_not_fulfill_requirements, msg.str());\n        }\n      }\n    const R post_check_solves_system_threshold =\n        opts.get(\"post_check_solves_system\", default_opts.get<R>(\"post_check_solves_system\"));\n    if (post_check_solves_system_threshold > 0) {\n      auto tmp = rhs.copy();\n      tmp.backend() = matrix_.backend() * solution.backend() - rhs.backend();\n      const R sup_norm = tmp.sup_norm();\n      if (sup_norm > post_check_solves_system_threshold || DSC::isnan(sup_norm) || DSC::isinf(sup_norm)) {\n        std::stringstream msg;\n        msg << \"The computed solution does not solve the system (although the eigen backend reported \"\n            << \"'Success') and you requested checking (see options below)!\\n\"\n            << \"If you want to disable this check, set 'post_check_solves_system = 0' in the options.\"\n            << \"\\n\\n\"\n            << \"  (A * x - b).sup_norm() = \" << tmp.sup_norm() << \"\\n\\n\"\n            << \"Those were the given options:\\n\\n\" << opts;\n        if (rhs.size() <= internal::max_size_to_print)\n          msg << \"\\nThis was the given matrix A:\\n\\n\" << matrix_ << \"\\nThis was the given right hand side b:\\n\\n\" << rhs\n              << \"\\nThis is the computed solution:\\n\\n\" << solution << \"\\n\";\n        DUNE_THROW(Exceptions::linear_solver_failed_bc_the_solution_does_not_solve_the_system, msg.str());\n      }\n    }\n  } // ... apply(...)\n\nprivate:\n  const MatrixType& matrix_;\n}; // class Solver\n\n/**\n *  \\note lu.sparse will copy the matrix to column major\n *  \\note qr.sparse will copy the matrix to column major\n *  \\note ldlt.simplicial will copy the matrix to column major\n *  \\note llt.simplicial will copy the matrix to column major\n */\ntemplate <class S, class CommunicatorType>\nclass Solver<EigenRowMajorSparseMatrix<S>, CommunicatorType> : protected SolverUtils\n{\n  typedef ::Eigen::SparseMatrix<S, ::Eigen::ColMajor> ColMajorBackendType;\n\npublic:\n  typedef EigenRowMajorSparseMatrix<S> MatrixType;\n  typedef typename MatrixType::RealType R;\n\nprivate:\n  typedef typename MatrixType::BackendType::Index EIGEN_size_t;\n\npublic:\n  Solver(const MatrixType& matrix) : matrix_(matrix) {}\n\n  Solver(const MatrixType& matrix, const CommunicatorType& /*communicator*/) : matrix_(matrix) {}\n\n  static std::vector<std::string> types()\n  {\n    return {\n        \"bicgstab.ilut\",\n        \"lu.sparse\",\n        \"llt.simplicial\" // <- does only work with symmetric matrices\n        ,\n        \"ldlt.simplicial\" // <- does only work with symmetric matrices\n        ,\n        \"bicgstab.diagonal\" // <- slow for complicated matrices\n        ,\n        \"bicgstab.identity\" // <- slow for complicated matrices\n        ,\n        \"qr.sparse\" // <- produces correct results, but is painfully slow\n        ,\n        \"cg.diagonal.lower\" // <- does only work with symmetric matrices, may produce correct results\n        ,\n        \"cg.diagonal.upper\" // <- does only work with symmetric matrices, may produce correct results\n        ,\n        \"cg.identity.lower\" // <- does only work with symmetric matrices, may produce correct results\n        ,\n        \"cg.identity.upper\" // <- does only work with symmetric matrices, may produce correct results\n                            //           , \"spqr\"                  // <- does not compile\n                            //           , \"llt.cholmodsupernodal\" // <- does not compile\n                            //#if HAVE_UMFPACK\n                            //           , \"lu.umfpack\"            // <- untested\n                            //#endif\n                            //#if HAVE_SUPERLU\n                            //           , \"superlu\"               // <- untested\n                            //#endif\n    };\n  } // ... types()\n\n  static Common::Configuration options(const std::string type = \"\")\n  {\n    const std::string tp = !type.empty() ? type : types()[0];\n    // check\n    SolverUtils::check_given(tp, types());\n    // default config\n    Common::Configuration default_options({\"type\", \"post_check_solves_system\", \"check_for_inf_nan\"}, {tp, \"1e-5\", \"1\"});\n    Common::Configuration iterative_options({\"max_iter\", \"precision\"}, {\"10000\", \"1e-10\"});\n    iterative_options += default_options;\n    // direct solvers\n    if (tp == \"lu.sparse\" || tp == \"qr.sparse\" || tp == \"lu.umfpack\" || tp == \"spqr\" || tp == \"llt.cholmodsupernodal\"\n        || tp == \"superlu\")\n      return default_options;\n    // * for symmetric matrices\n    if (tp == \"ldlt.simplicial\" || tp == \"llt.simplicial\") {\n      default_options.set(\"pre_check_symmetry\", \"1e-8\");\n      return default_options;\n    }\n    // iterative solvers\n    if (tp == \"bicgstab.ilut\") {\n      iterative_options.set(\"preconditioner.fill_factor\", \"10\");\n      iterative_options.set(\"preconditioner.drop_tol\", \"1e-4\");\n    } else if (tp.substr(0, 3) == \"cg.\")\n      iterative_options.set(\"pre_check_symmetry\", \"1e-8\");\n    return iterative_options;\n  } // ... options(...)\n\n  template <class T1, class T2>\n  void apply(const EigenBaseVector<T1, S>& rhs, EigenBaseVector<T2, S>& solution) const\n  {\n    apply(rhs, solution, types()[0]);\n  }\n\n  template <class T1, class T2>\n  void apply(const EigenBaseVector<T1, S>& rhs, EigenBaseVector<T2, S>& solution, const std::string& type) const\n  {\n    apply(rhs, solution, options(type));\n  }\n\n  template <class T1, class T2>\n  void apply(const EigenBaseVector<T1, S>& rhs, EigenBaseVector<T2, S>& solution,\n             const Common::Configuration& opts) const\n  {\n    if (!opts.has_key(\"type\"))\n      DUNE_THROW(Exceptions::configuration_error,\n                 \"Given options (see below) need to have at least the key 'type' set!\\n\\n\" << opts);\n    const auto type = opts.get<std::string>(\"type\");\n    SolverUtils::check_given(type, types());\n    const Common::Configuration default_opts = options(type);\n    // check for inf or nan\n    const bool check_for_inf_nan = opts.get(\"check_for_inf_nan\", default_opts.get<bool>(\"check_for_inf_nan\"));\n    if (check_for_inf_nan) {\n      // iterates over the non-zero entries of matrix_.backend() and checks them\n      typedef typename MatrixType::BackendType::InnerIterator InnerIterator;\n      for (EIGEN_size_t ii = 0; ii < matrix_.backend().outerSize(); ++ii) {\n        for (InnerIterator it(matrix_.backend(), ii); it; ++it) {\n          if (DSC::isnan(std::real(it.value())) || DSC::isnan(std::imag(it.value()))\n              || DSC::isinf(std::abs(it.value())))\n            DUNE_THROW(Exceptions::linear_solver_failed_bc_data_did_not_fulfill_requirements,\n                       \"Given matrix contains inf or nan and you requested checking (see options below)!\\n\"\n                           << \"If you want to disable this check, set 'check_for_inf_nan = 0' in the options.\\n\\n\"\n                           << \"Those were the given options:\\n\\n\"\n                           << opts);\n        }\n      }\n      for (size_t ii = 0; ii < rhs.size(); ++ii) {\n        const S& val = rhs[ii];\n        if (Common::isnan(val) || Common::isinf(val))\n          DUNE_THROW(Exceptions::linear_solver_failed_bc_data_did_not_fulfill_requirements,\n                     \"Given rhs contains inf or nan and you requested checking (see options below)!\\n\"\n                         << \"If you want to disable this check, set 'check_for_inf_nan = 0' in the options.\\n\\n\"\n                         << \"Those were the given options:\\n\\n\"\n                         << opts);\n      }\n    }\n    // check for symmetry (if solver needs it)\n    if (type.substr(0, 3) == \"cg.\" || type == \"ldlt.simplicial\" || type == \"llt.simplicial\") {\n      const R pre_check_symmetry_threshhold = opts.get(\"pre_check_symmetry\", default_opts.get<R>(\"pre_check_symmetry\"));\n      if (pre_check_symmetry_threshhold > 0) {\n        ColMajorBackendType colmajor_copy(matrix_.backend());\n        colmajor_copy -= matrix_.backend().adjoint();\n        // iterates over non-zero entries as above\n        typedef typename ColMajorBackendType::InnerIterator InnerIterator;\n        for (EIGEN_size_t ii = 0; ii < colmajor_copy.outerSize(); ++ii) {\n          for (InnerIterator it(colmajor_copy, ii); it; ++it) {\n            if (std::max(std::abs(std::real(it.value())), std::abs(std::imag(it.value())))\n                > pre_check_symmetry_threshhold)\n              DUNE_THROW(Exceptions::linear_solver_failed_bc_data_did_not_fulfill_requirements,\n                         \"Given matrix is not symmetric/hermitian and you requested checking (see options below)!\\n\"\n                             << \"If you want to disable this check, set 'pre_check_symmetry = 0' in the options.\\n\\n\"\n                             << \"Those were the given options:\\n\\n\"\n                             << opts);\n          }\n        }\n      }\n    }\n    ::Eigen::ComputationInfo info;\n    if (type == \"cg.diagonal.lower\") {\n      typedef ::Eigen::ConjugateGradient<typename MatrixType::BackendType,\n                                         ::Eigen::Lower,\n                                         ::Eigen::DiagonalPreconditioner<S>> SolverType;\n      SolverType solver(matrix_.backend());\n      solver.setMaxIterations(opts.get(\"max_iter\", default_opts.get<int>(\"max_iter\")));\n      solver.setTolerance(opts.get(\"precision\", default_opts.get<R>(\"precision\")));\n      solution.backend() = solver.solve(rhs.backend());\n      info = solver.info();\n    } else if (type == \"cg.diagonal.upper\") {\n      typedef ::Eigen::ConjugateGradient<typename MatrixType::BackendType,\n                                         ::Eigen::Upper,\n                                         ::Eigen::DiagonalPreconditioner<S>> SolverType;\n      SolverType solver(matrix_.backend());\n      solver.setMaxIterations(opts.get(\"max_iter\", default_opts.get<int>(\"max_iter\")));\n      solver.setTolerance(opts.get(\"precision\", default_opts.get<R>(\"precision\")));\n      solution.backend() = solver.solve(rhs.backend());\n      info = solver.info();\n    } else if (type == \"cg.identity.lower\") {\n      typedef ::Eigen::ConjugateGradient<typename MatrixType::BackendType,\n                                         ::Eigen::Lower,\n                                         ::Eigen::IdentityPreconditioner> SolverType;\n      SolverType solver(matrix_.backend());\n      solver.setMaxIterations(opts.get(\"max_iter\", default_opts.get<int>(\"max_iter\")));\n      solver.setTolerance(opts.get(\"precision\", default_opts.get<R>(\"precision\")));\n      solution.backend() = solver.solve(rhs.backend());\n      info = solver.info();\n    } else if (type == \"cg.identity.upper\") {\n      typedef ::Eigen::ConjugateGradient<typename MatrixType::BackendType,\n                                         ::Eigen::Lower,\n                                         ::Eigen::IdentityPreconditioner> SolverType;\n      SolverType solver(matrix_.backend());\n      solver.setMaxIterations(opts.get(\"max_iter\", default_opts.get<int>(\"max_iter\")));\n      solver.setTolerance(opts.get(\"precision\", default_opts.get<R>(\"precision\")));\n      solution.backend() = solver.solve(rhs.backend());\n      info = solver.info();\n    } else if (type == \"bicgstab.ilut\") {\n      typedef ::Eigen::BiCGSTAB<typename MatrixType::BackendType, ::Eigen::IncompleteLUT<S>> SolverType;\n      SolverType solver(matrix_.backend());\n      solver.setMaxIterations(opts.get(\"max_iter\", default_opts.get<int>(\"max_iter\")));\n      solver.setTolerance(opts.get(\"precision\", default_opts.get<R>(\"precision\")));\n      solver.preconditioner().setDroptol(\n          opts.get(\"preconditioner.drop_tol\", default_opts.get<R>(\"preconditioner.drop_tol\")));\n      solver.preconditioner().setFillfactor(\n          opts.get(\"preconditioner.fill_factor\", default_opts.get<int>(\"preconditioner.fill_factor\")));\n      solution.backend() = solver.solve(rhs.backend());\n      info = solver.info();\n    } else if (type == \"bicgstab.diagonal\") {\n      typedef ::Eigen::BiCGSTAB<typename MatrixType::BackendType, ::Eigen::DiagonalPreconditioner<S>> SolverType;\n      SolverType solver(matrix_.backend());\n      solver.setMaxIterations(opts.get(\"max_iter\", default_opts.get<int>(\"max_iter\")));\n      solver.setTolerance(opts.get(\"precision\", default_opts.get<R>(\"precision\")));\n      solution.backend() = solver.solve(rhs.backend());\n      info = solver.info();\n    } else if (type == \"bicgstab.identity\") {\n      typedef ::Eigen::BiCGSTAB<typename MatrixType::BackendType, ::Eigen::IdentityPreconditioner> SolverType;\n      SolverType solver(matrix_.backend());\n      solver.setMaxIterations(opts.get(\"max_iter\", default_opts.get<int>(\"max_iter\")));\n      solver.setTolerance(opts.get(\"precision\", default_opts.get<R>(\"precision\")));\n      solution.backend() = solver.solve(rhs.backend());\n      info = solver.info();\n    } else if (type == \"lu.sparse\") {\n      ColMajorBackendType colmajor_copy(matrix_.backend());\n      colmajor_copy.makeCompressed();\n      typedef ::Eigen::SparseLU<ColMajorBackendType> SolverType;\n      SolverType solver;\n      solver.analyzePattern(colmajor_copy);\n      solver.factorize(colmajor_copy);\n      solution.backend() = solver.solve(rhs.backend());\n      info = solver.info();\n    } else if (type == \"qr.sparse\") {\n      ColMajorBackendType colmajor_copy(matrix_.backend());\n      colmajor_copy.makeCompressed();\n      typedef ::Eigen::SparseQR<ColMajorBackendType, ::Eigen::COLAMDOrdering<int>> SolverType;\n      SolverType solver;\n      solver.analyzePattern(colmajor_copy);\n      solver.factorize(colmajor_copy);\n      solution.backend() = solver.solve(rhs.backend());\n      info = solver.info();\n    } else if (type == \"ldlt.simplicial\") {\n      ColMajorBackendType colmajor_copy(matrix_.backend());\n      colmajor_copy.makeCompressed();\n      typedef ::Eigen::SimplicialLDLT<ColMajorBackendType> SolverType;\n      SolverType solver;\n      solver.analyzePattern(colmajor_copy);\n      solver.factorize(colmajor_copy);\n      solution.backend() = solver.solve(rhs.backend());\n      info = solver.info();\n    } else if (type == \"llt.simplicial\") {\n      ColMajorBackendType colmajor_copy(matrix_.backend());\n      colmajor_copy.makeCompressed();\n      typedef ::Eigen::SimplicialLLT<ColMajorBackendType> SolverType;\n      SolverType solver;\n      solver.analyzePattern(colmajor_copy);\n      solver.factorize(colmajor_copy);\n      solution.backend() = solver.solve(rhs.backend());\n      info = solver.info();\n      //#if HAVE_UMFPACK\n      //    } else if (type == \"lu.umfpack\") {\n      //      typedef ::Eigen::UmfPackLU< typename MatrixType::BackendType > SolverType;\n      //      SolverType solver;\n      //      solver.analyzePattern(matrix_.backend());\n      //      solver.factorize(matrix_.backend());\n      //      solution.backend() = solver.solve(rhs.backend());\n      //      info = solver.info();\n      //#endif // HAVE_UMFPACK\n      //    } else if (type == \"spqr\") {\n      //      ColMajorBackendType colmajor_copy(matrix_.backend());\n      //      colmajor_copy.makeCompressed();\n      //      typedef ::Eigen::SPQR< ColMajorBackendType > SolverType;\n      //      SolverType solver;\n      //      solver.analyzePattern(colmajor_copy);\n      //      solver.factorize(colmajor_copy);\n      //      solution.backend() = solver.solve(rhs.backend());\n      //      if (solver.info() != ::Eigen::Success)\n      //        return solver.info();\n      //    } else if (type == \"cholmodsupernodalllt\") {\n      //      typedef ::Eigen::CholmodSupernodalLLT< typename MatrixType::BackendType > SolverType;\n      //      SolverType solver;\n      //      solver.analyzePattern(matrix_.backend());\n      //      solver.factorize(matrix_.backend());\n      //      solution.backend() = solver.solve(rhs.backend());\n      //      if (solver.info() != ::Eigen::Success)\n      //        return solver.info();\n      //#if HAVE_SUPERLU\n      //    } else if (type == \"superlu\") {\n      //      typedef ::Eigen::SuperLU< typename MatrixType::BackendType > SolverType;\n      //      SolverType solver;\n      //      solver.analyzePattern(matrix_.backend());\n      //      solver.factorize(matrix_.backend());\n      //      solution.backend() = solver.solve(rhs.backend());\n      //      info = solver.info();\n      //#endif // HAVE_SUPERLU\n    } else\n      DUNE_THROW(Exceptions::internal_error,\n                 \"Given type '\" << type << \"' is not supported, although it was reported by types()!\");\n    // handle eigens info\n    if (info != ::Eigen::Success) {\n      if (info == ::Eigen::NumericalIssue)\n        DUNE_THROW(Exceptions::linear_solver_failed_bc_data_did_not_fulfill_requirements,\n                   \"The eigen backend reported 'NumericalIssue'!\\n\"\n                       << \"=> see http://eigen.tuxfamily.org/dox/group__enums.html#ga51bc1ac16f26ebe51eae1abb77bd037b \"\n                          \"for eigens explanation\\n\"\n                       << \"Those were the given options:\\n\\n\"\n                       << opts);\n      else if (info == ::Eigen::NoConvergence)\n        DUNE_THROW(Exceptions::linear_solver_failed_bc_it_did_not_converge,\n                   \"The eigen backend reported 'NoConvergence'!\\n\"\n                       << \"=> see http://eigen.tuxfamily.org/dox/group__enums.html#ga51bc1ac16f26ebe51eae1abb77bd037b \"\n                          \"for eigens explanation\\n\"\n                       << \"Those were the given options:\\n\\n\"\n                       << opts);\n      else if (info == ::Eigen::InvalidInput)\n        DUNE_THROW(Exceptions::linear_solver_failed_bc_it_was_not_set_up_correctly,\n                   \"The eigen backend reported 'InvalidInput'!\\n\"\n                       << \"=> see http://eigen.tuxfamily.org/dox/group__enums.html#ga51bc1ac16f26ebe51eae1abb77bd037b \"\n                          \"for eigens explanation\\n\"\n                       << \"Those were the given options:\\n\\n\"\n                       << opts);\n      else\n        DUNE_THROW(Exceptions::internal_error,\n                   \"The eigen backend reported an unknown status!\\n\"\n                       << \"Please report this to the dune-stuff developers!\");\n    }\n    // check\n    if (check_for_inf_nan)\n      for (size_t ii = 0; ii < solution.size(); ++ii) {\n        const S& val = solution[ii];\n        if (Common::isnan(val) || Common::isinf(val))\n          DUNE_THROW(Exceptions::linear_solver_failed_bc_data_did_not_fulfill_requirements,\n                     \"The computed solution contains inf or nan and you requested checking (see options \"\n                         << \"below)!\\n\"\n                         << \"If you want to disable this check, set 'check_for_inf_nan = 0' in the options.\\n\\n\"\n                         << \"Those were the given options:\\n\\n\"\n                         << opts);\n      }\n    const R post_check_solves_system_threshold =\n        opts.get(\"post_check_solves_system\", default_opts.get<R>(\"post_check_solves_system\"));\n    if (post_check_solves_system_threshold > 0) {\n      auto tmp = rhs.copy();\n      tmp.backend() = matrix_.backend() * solution.backend() - rhs.backend();\n      const R sup_norm = tmp.sup_norm();\n      if (sup_norm > post_check_solves_system_threshold || DSC::isnan(sup_norm) || DSC::isinf(sup_norm))\n        DUNE_THROW(Exceptions::linear_solver_failed_bc_the_solution_does_not_solve_the_system,\n                   \"The computed solution does not solve the system (although the eigen backend reported \"\n                       << \"'Success') and you requested checking (see options below)!\\n\"\n                       << \"If you want to disable this check, set 'post_check_solves_system = 0' in the options.\"\n                       << \"\\n\\n\"\n                       << \"  (A * x - b).sup_norm() = \"\n                       << tmp.sup_norm()\n                       << \"\\n\\n\"\n                       << \"Those were the given options:\\n\\n\"\n                       << opts);\n    }\n  } // ... apply(...)\n\nprivate:\n  const MatrixType& matrix_;\n}; // class Solver\n\n#else // HAVE_EIGEN\n\ntemplate <class S>\nclass Solver<EigenDenseMatrix<S>>\n{\n  static_assert(Dune::AlwaysFalse<S>::value, \"You are missing Eigen!\");\n};\n\ntemplate <class S>\nclass Solver<EigenRowMajorSparseMatrix<S>>\n{\n  static_assert(Dune::AlwaysFalse<S>::value, \"You are missing Eigen!\");\n};\n\n#endif // HAVE_EIGEN\n\n} // namespace LA\n} // namespace Stuff\n} // namespace Dune\n\n#endif // DUNE_STUFF_LA_SOLVER_EIGEN_HH\n", "meta": {"hexsha": "74bdf02005ddf9713ed3f5ee10e1f8d7829d9877", "size": 28013, "ext": "hh", "lang": "C++", "max_stars_repo_path": "dune/stuff/la/solver/eigen.hh", "max_stars_repo_name": "ftalbrecht/dune-stuff-simplified", "max_stars_repo_head_hexsha": "fc1f80dedaa78fae6e6d67e8f5424a6b3ec86b5d", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "dune/stuff/la/solver/eigen.hh", "max_issues_repo_name": "ftalbrecht/dune-stuff-simplified", "max_issues_repo_head_hexsha": "fc1f80dedaa78fae6e6d67e8f5424a6b3ec86b5d", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "dune/stuff/la/solver/eigen.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": 47.8037542662, "max_line_length": 120, "alphanum_fraction": 0.6118587799, "num_tokens": 6670, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.63341027751814, "lm_q2_score": 0.5389832206876841, "lm_q1q2_score": 0.3413975113934069}}
{"text": "#include \"LevelSet.h\"\n\n#include <iostream>\n\n#include \"tbb/tbb.h\"\n\n#include <Eigen/Dense>\n#include <Eigen/SVD>\n\nnamespace FluidSim2D::SurfaceTrackers\n{\n\nvoid LevelSet::drawGrid(Renderer& renderer, bool doOnlyNarrowBand) const\n{\n\tif (doOnlyNarrowBand)\n\t{\n\t\tforEachVoxelRange(Vec2i(0), size(), [&](const Vec2i& cell)\n\t\t{\n\t\t\tif (std::fabs(myPhiGrid(cell)) < myNarrowBand)\n\t\t\t\tmyPhiGrid.drawGridCell(renderer, cell);\n\t\t});\n\t}\n\telse myPhiGrid.drawGrid(renderer);\n}\n\nvoid LevelSet::drawMeshGrid(Renderer& renderer) const\n{\n\tTransform xform(myPhiGrid.dx(), myPhiGrid.offset() + Vec2f(0.5) * myPhiGrid.dx());\n\tScalarGrid<int> tempGrid(xform, myPhiGrid.size());\n\ttempGrid.drawGrid(renderer);\n}\n\nvoid LevelSet::drawSupersampledValues(Renderer& renderer, float radius, int samples, float sampleSize) const\n{\n\tmyPhiGrid.drawSupersampledValues(renderer, radius, samples, sampleSize);\n}\nvoid LevelSet::drawNormals(Renderer& renderer, const Vec3f& colour, float length) const\n{\n\tmyPhiGrid.drawSampleGradients(renderer, colour, length);\n}\n\nvoid LevelSet::drawSurface(Renderer& renderer, const Vec3f& colour, float lineWidth) const\n{\n\tEdgeMesh surface = buildMSMesh();\n\tsurface.drawMesh(renderer, colour, lineWidth);\n}\n\nvoid LevelSet::drawDCSurface(Renderer& renderer, const Vec3f& colour, float lineWidth) const\n{\n\tEdgeMesh surface = buildDCMesh();\n\tsurface.drawMesh(renderer, colour, lineWidth);\n}\n\n// Find the nearest point on the interface starting from the index position.\n// If the position falls outside of the narrow band, there isn't a defined gradient\n// to use. In this case, the original position will be returned.\n\nVec2f LevelSet::findSurface(const Vec2f& worldPoint, int iterationLimit) const\n{\n\tassert(iterationLimit >= 0);\n\n\tfloat phi = myPhiGrid.biLerp(worldPoint);\n\n\tfloat epsilon = 1E-2 * dx();\n\tVec2f tempPoint = worldPoint;\n\n\tint iterationCount = 0;\n\tif (std::fabs(phi) < myNarrowBand)\n\t{\n\t\twhile (std::fabs(phi) > epsilon && iterationCount < iterationLimit)\n\t\t{\n\t\t\ttempPoint -= phi * normal(tempPoint);\n\t\t\tphi = myPhiGrid.biCubicInterp(tempPoint);\n\t\t\t++iterationCount;\n\t\t}\n\t}\n\n\treturn tempPoint;\n}\n\nVec2f LevelSet::findSurfaceIndex(const Vec2f& indexPoint, int iterationLimit) const\n{\n\tVec2f worldPoint = indexToWorld(indexPoint);\n\tworldPoint = findSurface(worldPoint, iterationLimit);\n\treturn worldToIndex(worldPoint);\n}\n\nvoid LevelSet::reinit(bool rebuildWithFIM)\n{\n\tUniformGrid<VisitedCellLabels> reinitializedCells(size(), VisitedCellLabels::UNVISITED_CELL);\n\n\t// Find the zero crossings, update their distances and flag as source cells\n\tScalarGrid<float> tempPhiGrid = myPhiGrid;\n\n\ttbb::parallel_for(tbb::blocked_range<int>(0, voxelCount(), tbbLightGrainSize), [&](const tbb::blocked_range<int> &range)\n\t{\n\t\tfor (int cellIndex = range.begin(); cellIndex != range.end(); ++cellIndex)\n\t\t{\n\t\t\tVec2i cell = reinitializedCells.unflatten(cellIndex);\n\n\t\t\t// Check for a zero crossing\n\t\t\tbool isAtZeroCrossing = false;\n\t\t\tfor (int axis = 0; axis < 2 && !isAtZeroCrossing; ++axis)\n\t\t\t\tfor (int direction : {0, 1})\n\t\t\t\t{\n\t\t\t\t\tVec2i adjacentCell = cellToCell(cell, axis, direction);\n\n\t\t\t\t\tif (adjacentCell[axis] < 0 || adjacentCell[axis] >= size()[axis]) continue;\n\n\t\t\t\t\tif ((myPhiGrid(cell) <= 0 && myPhiGrid(adjacentCell) > 0) ||\n\t\t\t\t\t\t(myPhiGrid(cell) > 0 && myPhiGrid(adjacentCell) <= 0))\n\t\t\t\t\t{\n\t\t\t\t\t\tisAtZeroCrossing = true;\n\n\t\t\t\t\t\tVec2f worldPoint = indexToWorld(Vec2f(cell));\n\t\t\t\t\t\tVec2f interfacePoint = findSurface(worldPoint, 5);\n\n\t\t\t\t\t\tfloat distance = dist(worldPoint, interfacePoint);\n\n\t\t\t\t\t\ttempPhiGrid(cell) = myPhiGrid(cell) < 0. ? -distance : distance;\n\t\t\t\t\t\treinitializedCells(cell) = VisitedCellLabels::FINISHED_CELL;\n\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t// Set unvisited grid cells to background value, using old grid for inside/outside sign\n\t\t\tif (!isAtZeroCrossing)\n\t\t\t{\n\t\t\t\tassert(reinitializedCells(cell) == VisitedCellLabels::UNVISITED_CELL);\n\t\t\t\ttempPhiGrid(cell) = myPhiGrid(cell) < 0. ? -myNarrowBand : myNarrowBand;\n\t\t\t}\n\t\t}\n\t});\n\n\t//std::swap(myPhiGrid, tempPhiGrid);\n\tmyPhiGrid = tempPhiGrid;\n\n\tif (rebuildWithFIM)\n\t\treinitFastIterative(reinitializedCells);\n\telse\n\t\treinitFastMarching(reinitializedCells);\n}\n\nvoid LevelSet::reinitFastIterative(UniformGrid<VisitedCellLabels>& reinitializedCells)\n{\n\tassert(reinitializedCells.size() == size());\n\n\t//\n\t// Before starting the iterations, we want to construct the active list of voxels\n\t// to reinitialize.\n\t//\n\n\ttbb::enumerable_thread_specific<std::vector<Vec2i>> parallelActiveCellList;\n\n\ttbb::parallel_for(tbb::blocked_range<int>(0, voxelCount(), tbbLightGrainSize), [&](const tbb::blocked_range<int>& range)\n\t{\n\t\tstd::vector<Vec2i>& localActiveCellList = parallelActiveCellList.local();\n\n\t\tfor (int cellIndex = range.begin(); cellIndex != range.end(); ++cellIndex)\n\t\t{\n\t\t\tVec2i cell = reinitializedCells.unflatten(cellIndex);\n\n\t\t\tif (reinitializedCells(cell) == VisitedCellLabels::FINISHED_CELL)\n\t\t\t{\n\t\t\t\t// Add neighbours to the list\n\t\t\t\tfor (int axis : {0, 1})\n\t\t\t\t\tfor (int direction : {0, 1})\n\t\t\t\t\t{\n\t\t\t\t\t\tVec2i adjacentCell = cellToCell(cell, axis, direction);\n\n\t\t\t\t\t\tif (adjacentCell[axis] < 0 || adjacentCell[axis] >= size()[axis]) continue;\n\n\t\t\t\t\t\tif (reinitializedCells(adjacentCell) == VisitedCellLabels::UNVISITED_CELL)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tlocalActiveCellList.push_back(adjacentCell);\n\t\t\t\t\t\t\treinitializedCells(adjacentCell) = VisitedCellLabels::VISITED_CELL;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t}\n\t\t}\n\t});\n\n\tstd::vector<Vec2i> activeCellList;\n\tmergeLocalThreadVectors(activeCellList, parallelActiveCellList);\n\n\tparallelActiveCellList.clear();\n\n\tauto vecCompare = [](const Vec2i& a, const Vec2i& b) -> bool\n\t{\n\t\tif (a[0] < b[0]) return true;\n\t\telse if (a[0] == b[0] && a[1] < b[1]) return true;\n\t\treturn false;\n\t};\n\n\ttbb::parallel_sort(activeCellList.begin(), activeCellList.end(), vecCompare);\n\n\tfloat dx = myPhiGrid.dx();\n\n\t// Now that the correct distances and signs have been recorded at the interface,\n\t// it's important to flood fill that the signed distances outwards into the entire grid.\n\t// We use the Eikonal equation here to build this outward.\n\n\tauto solveEikonal = [&](const Vec2i& idx) -> float\n\t{\n\t\tfloat Ul = (idx[0] == 0) ? std::numeric_limits<float>::max() : myPhiGrid(idx[0] - 1, idx[1]);\n\t\tfloat Ur = (idx[0] == myPhiGrid.size()[0] - 1) ? std::numeric_limits<float>::max() : myPhiGrid(idx[0] + 1, idx[1]);\n\n\t\tfloat Ub = (idx[1] == 0) ? std::numeric_limits<float>::max() : myPhiGrid(idx[0], idx[1] - 1);\n\t\tfloat Ut = (idx[1] == myPhiGrid.size()[1] - 1) ? std::numeric_limits<float>::max() : myPhiGrid(idx[0], idx[1] + 1);\n\n\t\tfloat u = std::fabs(myPhiGrid(idx[0], idx[1]));\n\n\t\tint count = 0;\n\n\t\tfloat a = std::min(std::fabs(Ul), std::fabs(Ur));\n\t\tif (u - a <= 0.) a = std::numeric_limits<float>::max();\n\t\telse ++count;\n\n\t\tfloat b = std::min(std::fabs(Ub), std::fabs(Ut));\n\n\t\tif (u - b <= 0.) b = std::numeric_limits<float>::max();\n\t\telse ++count;\n\n\t\tif (a > b) std::swap(a, b);\n\n\t\tif (count == 1) u = a + dx;\n\t\telse if (count == 2)\n\t\t{\n\t\t\tfloat temp = -sqr(a) - sqr(b) + 2. * a * b + 2. * sqr(dx);\n\t\t\tif (temp < 0.) u = a + dx;\n\t\t\telse u = .5 * (a + b + sqrt(temp));\n\t\t\tassert(std::isfinite(u));\n\t\t}\n\t\t// There shouldn't be a case where count is 0 but it seems to be happenning..\n\n\t\treturn u;\n\n\t};\n\n\tScalarGrid<float> tempPhiGrid = myPhiGrid;\n\n\tfloat tolerance = dx * 1E-5;\n\tbool stillActiveCells = true;\n\n\tint activeCellCount = activeCellList.size();\n\n\tint iteration = 0;\n\tint maxIterations = 5 * myNarrowBand / dx;\n\n\twhile (activeCellCount > 0 && iteration < maxIterations)\n\t{\n\t\ttbb::parallel_for(tbb::blocked_range<int>(0, activeCellCount, tbbLightGrainSize), [&](const tbb::blocked_range<int>& range)\n\t\t{\n\t\t\tauto& localActiveCellList = parallelActiveCellList.local();\n\n\t\t\tVec2i oldCell(-1);\n\n\t\t\tfor (int cellIndex = range.begin(); cellIndex != range.end(); ++cellIndex)\n\t\t\t{\n\t\t\t\tVec2i newCell = activeCellList[cellIndex];\n\n\t\t\t\tif (oldCell == newCell)\n\t\t\t\t\tcontinue;\n\n\t\t\t\toldCell = newCell;\n\n\t\t\t\tassert(reinitializedCells(newCell) == VisitedCellLabels::VISITED_CELL);\n\n\t\t\t\tfloat newPhi = solveEikonal(newCell);\n\n\t\t\t\t// If we hit the narrow band, we don't need to make any changes\n\t\t\t\tif (newPhi > myNarrowBand) continue;\n\n\t\t\t\ttempPhiGrid(newCell) = myPhiGrid(newCell) < 0 ? -newPhi : newPhi;\n\n\t\t\t\t// Check if new phi is converged\n\t\t\t\tfloat oldPhi = myPhiGrid(newCell);\n\n\t\t\t\t// If the cell is converged, load up the neighbours that aren't currently being VISITED\n\t\t\t\tif (std::fabs(newPhi - std::fabs(oldPhi)) < tolerance)\n\t\t\t\t{\n\t\t\t\t\tfor (int axis : {0, 1})\n\t\t\t\t\t\tfor (int direction : {0, 1})\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tVec2i adjacentCell = cellToCell(newCell, axis, direction);\n\n\t\t\t\t\t\t\tif (adjacentCell[axis] < 0 || adjacentCell[axis] >= size()[axis]) continue;\n\n\t\t\t\t\t\t\tif (reinitializedCells(adjacentCell) == VisitedCellLabels::UNVISITED_CELL)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tfloat adjacentNewPhi = solveEikonal(adjacentCell);\n\n\t\t\t\t\t\t\t\tif (adjacentNewPhi > myNarrowBand) continue;\n\n\t\t\t\t\t\t\t\t// Check if new phi is less than the current value\n\t\t\t\t\t\t\t\tfloat adjacentOldPhi = std::fabs(myPhiGrid(adjacentCell));\n\n\t\t\t\t\t\t\t\tif ((adjacentNewPhi < adjacentOldPhi) && (std::fabs(adjacentNewPhi - adjacentOldPhi) > tolerance))\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\ttempPhiGrid(adjacentCell) = myPhiGrid(adjacentCell) < 0 ? -adjacentNewPhi : adjacentNewPhi;\n\n\t\t\t\t\t\t\t\t\tlocalActiveCellList.push_back(adjacentCell);\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}\n\t\t\t\t}\n\t\t\t\t// If the cell hasn't converged, toss it back into the list\n\t\t\t\telse\n\t\t\t\t\tlocalActiveCellList.push_back(newCell);\n\t\t\t}\n\t\t});\n\n\t\t// Turn off VISITED labels for current list\n\t\ttbb::parallel_for(tbb::blocked_range<int>(0, activeCellCount, tbbLightGrainSize), [&](const tbb::blocked_range<int> &range)\n\t\t{\n\t\t\tfor (int cellIndex = range.begin(); cellIndex != range.end(); ++cellIndex)\n\t\t\t{\n\t\t\t\tVec2i cell = activeCellList[cellIndex];\n\t\t\t\tassert(reinitializedCells(cell) != VisitedCellLabels::FINISHED_CELL);\n\t\t\t\treinitializedCells(cell) = VisitedCellLabels::UNVISITED_CELL;\n\t\t\t}\n\t\t});\n\n\t\tactiveCellList.clear();\n\n\t\tmergeLocalThreadVectors(activeCellList, parallelActiveCellList);\n\n\t\tparallelActiveCellList.clear();\n\n\t\ttbb::parallel_sort(activeCellList.begin(), activeCellList.end(), vecCompare);\n\n\t\tactiveCellCount = activeCellList.size();\n\n\t\t// Turn on VISITED labels for new list\n\t\ttbb::parallel_for(tbb::blocked_range<int>(0, activeCellCount, tbbLightGrainSize), [&](const tbb::blocked_range<int> &range)\n\t\t{\n\t\t\tfor (int cellIndex = range.begin(); cellIndex != range.end(); ++cellIndex)\n\t\t\t{\n\t\t\t\tVec2i cell = activeCellList[cellIndex];\n\t\t\t\tassert(reinitializedCells(cell) != VisitedCellLabels::FINISHED_CELL);\n\t\t\t\treinitializedCells(cell) = VisitedCellLabels::VISITED_CELL;\n\t\t\t}\n\t\t});\n\n\t\t//std::swap(tempPhiGrid, myPhiGrid);\n\t\tmyPhiGrid = tempPhiGrid;\n\n\t\t++iteration;\n\t}\n}\n\nvoid LevelSet::initFromMesh(const EdgeMesh& initialMesh, bool doResizeGrid)\n{\n\tif (doResizeGrid)\n\t{\n\t\t// Determine the bounding box of the mesh to build the underlying grids\n\t\tVec2f minBoundingBox(std::numeric_limits<float>::max());\n\t\tVec2f maxBoundingBox(std::numeric_limits<float>::lowest());\n\n\t\tfor (int vertexIndex = 0; vertexIndex < initialMesh.vertexCount(); ++vertexIndex)\n\t\t\tupdateMinAndMax(minBoundingBox, maxBoundingBox, initialMesh.vertex(vertexIndex).point());\n\n\t\t// Just for nice whole numbers, let's clamp the bounding box to be an integer\n\t\t// offset in index space then bring it back to world space\n\t\tfloat maxNarrowBand = 10.;\n\t\tmaxNarrowBand = std::min(myNarrowBand / dx(), maxNarrowBand);\n\n\t\tminBoundingBox = dx() * (Vec2f(floor(minBoundingBox / dx())) - 2 * Vec2f(maxNarrowBand));\n\t\tmaxBoundingBox = dx() * (Vec2f(ceil(maxBoundingBox / dx())) + 2 * Vec2f(maxNarrowBand));\n\n\t\tclear();\n\t\tTransform xform(dx(), minBoundingBox);\n\t\t// Since we know how big the mesh is, we know how big our grid needs to be (wrt to grid spacing)\n\t\tmyPhiGrid = ScalarGrid<float>(xform, Vec2i((maxBoundingBox - minBoundingBox) / dx()), myNarrowBand);\n\t}\n\telse\n\t\tmyPhiGrid.resize(size(), myNarrowBand);\n\n\t// We want to track which cells in the level set contain valid distance information.\n\t// The first pass will set cells close to the mesh as FINISHED.\n\tUniformGrid<VisitedCellLabels> reinitializedCells(size(), VisitedCellLabels::UNVISITED_CELL);\n\tUniformGrid<int> meshCellParities(size(), 0);\n\n\tfor (const auto& edge : initialMesh.edges())\n\t{\n\t\t// It's easier to work in our index space and just scale the distance later.\n\t\tconst Vec2f& startPoint = worldToIndex(initialMesh.vertex(edge.vertex(0)).point());\n\t\tconst Vec2f& endPoint = worldToIndex(initialMesh.vertex(edge.vertex(1)).point());\n\n\t\t// Record mesh-grid intersections between cell nodes (i.e. on grid edges)\n\t\t// Since we only cast rays *left-to-right* for inside/outside checking, we don't\n\t\t// need to know if the mesh intersects y-aligned grid edges\n\t\tVec2f vmin, vmax;\n\t\tminAndMax(vmin, vmax, startPoint, endPoint);\n\n\t\tVec2i edgeCeilMin = Vec2i(ceil(vmin));\n\t\tVec2i edgeFloorMin = Vec2i(floor(vmin)) - Vec2i(1);\n\t\tVec2i edgeFloorMax = Vec2i(floor(vmax));\n\n\t\tfor (int j = edgeCeilMin[1]; j <= edgeFloorMax[1]; ++j)\n\t\t\tfor (int i = edgeFloorMax[0]; i >= edgeFloorMin[0]; --i)\n\t\t\t{\n\t\t\t\tVec2f gridNode(i, j);\n\t\t\t\tIntersectionLabels intersectionResult = exactEdgeIntersect(startPoint, endPoint, gridNode, Axis::XAXIS);\n\n\t\t\t\t// TODO: remove once test complete\n\t\t\t\tif (gridNode[0] < 0 || gridNode[1] < 0 || gridNode[0] >= myPhiGrid.size()[0] ||\n\t\t\t\t\tgridNode[1] >= myPhiGrid.size()[1])\n\t\t\t\t{\n\t\t\t\t\tstd::cout << \"Caught out of bounds. Node: \" << gridNode[0] << \" \" << gridNode[1] << std::endl;\n\t\t\t\t}\n\n\t\t\t\tif (intersectionResult == IntersectionLabels::NO) continue;\n\n\t\t\t\t// Increment the parity since the grid_node is\n\t\t\t\t// \"left\" of the mesh-edge crossing the grid-edge.\n\t\t\t\t// This indicates a negative normal in the x-direction\n\t\t\t\t// and means we're entering into the material.\n\t\t\t\tint parityChange = -1;\n\t\t\t\tif (startPoint[1] < endPoint[1])\n\t\t\t\t\tparityChange = 1;\n\n\t\t\t\tif (intersectionResult == IntersectionLabels::YES)\n\t\t\t\t\tmeshCellParities(i + 1, j) += parityChange;\n\t\t\t\t// If the grid node is explicitly on the mesh-edge, set distance to zero\n\t\t\t\t// since it might not be exactly zero due to floating point error above.\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tassert(intersectionResult == IntersectionLabels::ON);\n\t\t\t\t\t// Technically speaking, the zero isocountour means we're inside\n\t\t\t\t\t// the surface. So we should change the parity at the node that\n\t\t\t\t\t// is intersected even though it's zero and the sign is meaningless.\n\t\t\t\t\treinitializedCells(i, j) = VisitedCellLabels::FINISHED_CELL;\n\t\t\t\t\tmyPhiGrid(i, j) = 0.;\n\t\t\t\t\tmeshCellParities(i, j) += parityChange;\n\t\t\t\t}\n\n\t\t\t\tbreak;\n\t\t\t}\n\t}\n\n\t// Now that all the x-axis edge crossings have been found, we can compile the parity changes\n\t// and label grid nodes that are at the interface\n\tfor (int j = 0; j < size()[1]; ++j)\n\t{\n\t\tint parity = myIsBackgroundNegative ? 1 : 0;\n\n\t\t// We loop x-major because that's how we've set up our edge intersection.\n\t\tfor (int i = 0; i < size()[0]; ++i) // TODO: double check that I've resized right\n\t\t{\n\t\t\t// Update parity before changing sign since the parity values above used the convention\n\t\t\t// of putting the change on the \"far\" node (i.e. after the mesh-grid intersection).\n\n\t\t\tVec2i cell(i, j);\n\t\t\tparity += meshCellParities(cell);\n\t\t\tmeshCellParities(cell) = parity;\n\n\t\t\t// Set inside cells to negative\n\t\t\tif (parity > 0) myPhiGrid(cell) = -std::fabs(myPhiGrid(cell));\n\t\t}\n\n\t\tassert(myIsBackgroundNegative ? parity == 1 : parity == 0);\n\t}\n\n\t// With the parity assigned, loop over the grid once more and label nodes that have an implied sign change\n\t// with neighbouring nodes (this means parity goes from -'ve (and zero) to +'ve or vice versa).\n\tforEachVoxelRange(Vec2i(1), size() - Vec2i(1), [&](const Vec2i& cell)\n\t{\n\t\tbool isCellInside = meshCellParities(cell) > 0;\n\n\t\tfor (int axis : {0, 1})\n\t\t\tfor (int direction : {0, 1})\n\t\t\t{\n\t\t\t\tVec2i adjacentCell = cellToCell(cell, axis, direction);\n\n\t\t\t\tbool isAdjacentCellInside = meshCellParities(adjacentCell) > 0;\n\n\t\t\t\tif (isCellInside != isAdjacentCellInside)\n\t\t\t\t\treinitializedCells(cell) = VisitedCellLabels::FINISHED_CELL;\n\t\t\t}\n\t});\n\n\t// Loop over all the edges in the mesh. Level set grid cells labelled as VISITED will be\n\t// updated with the distance to the surface if it happens to be shorter than the current\n\t// distance to the surface.\n\tfor (const auto& edge : initialMesh.edges())\n\t{\n\t\t// Using the vertices of the edge, we can update distance values for cells\n\t\t// within the bounding box of the mesh. It's easier to work in our index space\n\t\t// and just scale the distance later.\n\t\tconst Vec2f& startPoint = worldToIndex(initialMesh.vertex(edge.vertex(0)).point());\n\t\tconst Vec2f& endPoint = worldToIndex(initialMesh.vertex(edge.vertex(1)).point());\n\n\t\t// Build bounding box\n\n\t\tVec2i minBoundingBox = Vec2i(floor(minUnion(startPoint, endPoint))) - Vec2i(2);\n\t\tminBoundingBox = maxUnion(minBoundingBox, Vec2i(0));\n\n\t\tVec2i maxBoundingBox = Vec2i(ceil(maxUnion(startPoint, endPoint))) + Vec2i(2);\n\t\tVec2i top = size() - Vec2i(1);\n\t\tmaxBoundingBox = minUnion(maxBoundingBox, top);\n\n\t\t// Update distances to the mesh at grid cells within the bounding box\n\t\tassert(minBoundingBox[0] >= 0 && minBoundingBox[1] >= 0 && maxBoundingBox[0] < size()[0] && maxBoundingBox[1] < size()[1]);\n\n\t\tforEachVoxelRange(minBoundingBox, maxBoundingBox + Vec2i(1), [&](const Vec2i& cell)\n\t\t{\n\t\t\tif (reinitializedCells(cell) != VisitedCellLabels::UNVISITED_CELL)\n\t\t\t{\n\t\t\t\tVec2f cellPoint(cell);\n\t\t\t\tVec2f vec0 = cellPoint - startPoint;\n\t\t\t\tVec2f vec1 = endPoint - startPoint;\n\n\t\t\t\tfloat s = dot(vec0, vec1) / dot(vec1, vec1); // Find projection along edge.\n\t\t\t\ts = clamp(s, float(0), float(1));\n\n\t\t\t\t// Remove on-edge projection to get vector from closest point on edge to cell point.\n\t\t\t\tfloat surfaceDistance = mag(vec0 - s * vec1) * dx();\n\n\t\t\t\t// Update if the distance to this edge is shorter than previous values.\n\t\t\t\tif (surfaceDistance < std::fabs(myPhiGrid(cell)))\n\t\t\t\t{\n\t\t\t\t\t// If the parity says the node is inside, set it to be negative\n\t\t\t\t\tmyPhiGrid(cell) = (meshCellParities(cell) > 0) ? -surfaceDistance : surfaceDistance;\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t}\n\n\treinitFastIterative(reinitializedCells);\n\t//reinitFastMarching(reinitializedCells);\n}\n\nvoid LevelSet::reinitFastMarching(UniformGrid<VisitedCellLabels>& reinitializedCells)\n{\n\tassert(reinitializedCells.size() == size());\n\n\t// Now that the correct distances and signs have been recorded at the interface,\n\t// it's important to flood fill that the signed distances outwards into the entire grid.\n\t// We use the Eikonal equation here to build this outward\n\tauto solveEikonal = [&](const Vec2i& cell) -> float\n\t{\n\t\tfloat max = std::numeric_limits<float>::max();\n\n\t\tfloat U_bx = (cell[0] > 0) ? std::fabs(myPhiGrid(cell[0] - 1, cell[1])) : max;\n\t\tfloat U_fx = (cell[0] < size()[0] - 1) ? std::fabs(myPhiGrid(cell[0] + 1, cell[1])) : max;\n\n\t\tfloat U_by = (cell[1] > 0) ? std::fabs(myPhiGrid(cell[0], cell[1] - 1)) : max;\n\t\tfloat U_fy = (cell[1] < size()[1] - 1) ? std::fabs(myPhiGrid(cell[0], cell[1] + 1)) : max;\n\n\t\tfloat Uh = std::min(U_bx, U_fx);\n\t\tfloat Uv = std::min(U_by, U_fy);\n\t\tfloat U;\n\t\t\n\t\tif (std::fabs(Uh - Uv) >= dx())\n\t\t\tU = std::min(Uh, Uv) + dx();\n\t\telse\n\t\t\t// Quadratic equation from the Eikonal\n\t\t\tU = (Uh + Uv) / 2. + .5 * std::sqrt(pow(Uh + Uv, 2.) - 2. * (sqr(Uh) + sqr(Uv) - sqr(dx())));\n\n\t\treturn U;\n\t};\n\n\t// Load up the BFS queue with the unvisited cells next to the finished ones\n\tusing Node = std::pair<Vec2i, float>;\n\tauto cmp = [](const Node& a, const Node& b) -> bool { return std::fabs(a.second) > std::fabs(b.second); };\n\tstd::priority_queue<Node, std::vector<Node>, decltype(cmp)> marchingQ(cmp);\n\n\tforEachVoxelRange(Vec2i(0), size(), [&](const Vec2i& cell)\n\t{\n\t\tif (reinitializedCells(cell) == VisitedCellLabels::FINISHED_CELL)\n\t\t{\n\t\t\tfor (int axis : {0, 1})\n\t\t\t\tfor (int direction : {0, 1})\n\t\t\t\t{\n\t\t\t\t\tVec2i adjacentCell = cellToCell(cell, axis, direction);\n\n\t\t\t\t\tif (adjacentCell[axis] < 0 || adjacentCell[axis] >= size()[axis]) continue;\n\n\t\t\t\t\tif (reinitializedCells(adjacentCell) == VisitedCellLabels::UNVISITED_CELL)\n\t\t\t\t\t{\n\t\t\t\t\t\tfloat dist = solveEikonal(adjacentCell);\n\t\t\t\t\t\tassert(dist >= 0);\n\n\t\t\t\t\t\tmyPhiGrid(adjacentCell) = (myPhiGrid(adjacentCell) < 0.) ? -dist : dist;\n\n\t\t\t\t\t\tNode node(adjacentCell, dist);\n\n\t\t\t\t\t\tmarchingQ.push(node);\n\t\t\t\t\t\treinitializedCells(adjacentCell) = VisitedCellLabels::VISITED_CELL;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t}\n\t});\n\n\twhile (!marchingQ.empty())\n\t{\n\t\tNode localNode = marchingQ.top();\n\t\tVec2i localCell = localNode.first;\n\t\tmarchingQ.pop();\n\n\t\t// Since you can't just update parts of the priority queue,\n\t\t// it's possible that a cell has been solidified at a smaller distance\n\t\t// and an older insert if floating around.\n\t\tif (reinitializedCells(localCell) == VisitedCellLabels::FINISHED_CELL)\n\t\t{\n\t\t\t// Make sure that the distance assigned to the cell is smaller than\n\t\t\t// what is floating around\n\t\t\tassert(std::fabs(myPhiGrid(localCell)) <= std::fabs(localNode.second));\n\t\t\tcontinue;\n\t\t}\n\t\tassert(reinitializedCells(localCell) == VisitedCellLabels::VISITED_CELL);\n\n\t\tif (std::fabs(myPhiGrid(localCell)) < myNarrowBand)\n\t\t{\n\t\t\t// Debug check that there is indeed a FINISHED cell next to it\n\t\t\tbool foundFinishedCell = false;\n\n\t\t\t// Loop over the neighbouring cells and load the unvisited cells\n\t\t\t// and update the visited cells\n\t\t\tfor (int axis : {0, 1})\n\t\t\t\tfor (int direction : {0, 1})\n\t\t\t\t{\n\t\t\t\t\tVec2i adjacentCell = cellToCell(localCell, axis, direction);\n\n\t\t\t\t\tif (adjacentCell[axis] < 0 || adjacentCell[axis] >= reinitializedCells.size()[axis])\n\t\t\t\t\t\tcontinue;\n\n\t\t\t\t\tif (reinitializedCells(adjacentCell) == VisitedCellLabels::FINISHED_CELL)\n\t\t\t\t\t\tfoundFinishedCell = true;\n\t\t\t\t\telse // If visited, then we'll update it\n\t\t\t\t\t{\n\t\t\t\t\t\tfloat dist = solveEikonal(adjacentCell);\n\t\t\t\t\t\tassert(dist >= 0);\n\t\t\t\t\t\t\n\t\t\t\t\t\tif (dist > myNarrowBand) dist = myNarrowBand;\n\n\t\t\t\t\t\tif (reinitializedCells(adjacentCell) == VisitedCellLabels::VISITED_CELL && dist > std::fabs(myPhiGrid(adjacentCell)))\n\t\t\t\t\t\t\tcontinue;\n\n\t\t\t\t\t\tmyPhiGrid(adjacentCell) = myPhiGrid(adjacentCell) < 0 ? -dist : dist;\n\n\t\t\t\t\t\tNode node(adjacentCell, dist);\n\n\t\t\t\t\t\tmarchingQ.push(node);\n\t\t\t\t\t\treinitializedCells(adjacentCell) = VisitedCellLabels::VISITED_CELL;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t//Check that a marked cell was indeed visited\n\t\t\tassert(foundFinishedCell);\n\t\t}\n\t\t// Clamp to narrow band\n\t\telse myPhiGrid(localCell) = myPhiGrid(localCell) < 0 ? -myNarrowBand : myNarrowBand;\n\n\t\t// Solidify cell now that we've handled all it's neighbours\n\t\treinitializedCells(localCell) = VisitedCellLabels::FINISHED_CELL;\n\t}\n}\n\n// Extract a mesh representation of the interface. Useful for rendering but not much\n// else since there will be duplicate vertices per grid edge in the current implementation.\n\nEdgeMesh LevelSet::buildMSMesh() const\n{\n\tstd::vector<Vec2f> verts;\n\tstd::vector<Vec2i> edges;\n\n\t// Run marching squares loop\n\tforEachVoxelRange(Vec2i(0), size() - Vec2i(1), [&](const Vec2i& cell)\n\t{\n\t\tint mcKey = 0;\n\n\t\tfor (int direction = 0; direction < 4; ++direction)\n\t\t{\n\t\t\tVec2i node = cellToNodeCCW(cell, direction);\n\t\t\tif (myPhiGrid(node) <= 0.) mcKey += (1 << direction);\n\t\t}\n\n\t\t// Connect edges using the marching squares template\n\t\tfor (int edgeIndex = 0; edgeIndex < 4 && marchingSquaresTemplate[mcKey][edgeIndex] >= 0; edgeIndex += 2)\n\t\t{\n\t\t\t// Find first vertex\n\t\t\tint edge = marchingSquaresTemplate[mcKey][edgeIndex];\n\n\t\t\tVec3i faceMap = cellToFaceCCW(cell, edge);\n\n\t\t\tVec2i face(faceMap[0], faceMap[1]);\n\t\t\tint axis = faceMap[2];\n\t\t\tVec2i startNode = faceToNode(face, axis, 0);\n\t\t\tVec2i endNode = faceToNode(face, axis, 1);\n\n\t\t\tVec2f startPoint = interpolateInterface(startNode, endNode);\n\n\t\t\t// Find second vertex\n\t\t\tedge = marchingSquaresTemplate[mcKey][edgeIndex + 1];\n\t\t\tfaceMap = cellToFaceCCW(cell, edge);\n\n\t\t\tface = Vec2i(faceMap[0], faceMap[1]);\n\t\t\taxis = faceMap[2];\n\n\t\t\tstartNode = faceToNode(face, axis, 0);\n\t\t\tendNode = faceToNode(face, axis, 1);\n\n\t\t\tVec2f endPoint = interpolateInterface(startNode, endNode);\n\n\t\t\t// Store vertices\n\t\t\tVec2f worldStartPoint = indexToWorld(startPoint);\n\t\t\tVec2f worldEndPoint = indexToWorld(endPoint);\n\n\t\t\tverts.push_back(worldStartPoint);\n\t\t\tverts.push_back(worldEndPoint);\n\n\t\t\tedges.emplace_back(verts.size() - 2, verts.size() - 1);\n\t\t}\n\t});\n\n\treturn EdgeMesh(edges, verts);\n}\n\n// Extract a mesh representation of the interface using dual contouring\nEdgeMesh LevelSet::buildDCMesh() const\n{\n\tstd::vector<Vec2f> verts;\n\tstd::vector<Vec2i> edges;\n\n\t// Create grid to store index to dual contouring point. Note that phi is\n\t// center sampled so the DC grid must be node sampled and one cell shorter\n\t// in each dimension\n\tUniformGrid<int> dcPointIndex(size() - Vec2i(1), -1);\n\n\t// Run dual contouring loop\n\tforEachVoxelRange(Vec2i(0), dcPointIndex.size(), [&](const Vec2i& cell)\n\t{\n\t\tstd::vector<Vec2f> qefPoints;\n\t\tstd::vector<Vec2f> qefNormals;\n\n\t\tfor (int axis : {0, 1})\n\t\t\tfor (int direction : {0, 1})\n\t\t\t{\n\t\t\t\tVec2i face = cellToFace(cell, axis, direction);\n\n\t\t\t\tVec2i backwardNode = faceToNode(face, axis, 0);\n\t\t\t\tVec2i forwardNode = faceToNode(face, axis, 1);\n\n\t\t\t\tif ((myPhiGrid(backwardNode) <= 0 && myPhiGrid(forwardNode) > 0) ||\n\t\t\t\t\t(myPhiGrid(backwardNode) > 0 && myPhiGrid(forwardNode) <= 0))\n\t\t\t\t{\n\t\t\t\t\t// Find interface point\n\t\t\t\t\tVec2f interfacePoint = interpolateInterface(backwardNode, forwardNode);\n\t\t\t\t\tqefPoints.push_back(interfacePoint);\n\n\t\t\t\t\t// Find associated surface normal\n\t\t\t\t\tVec2f surfaceNormal = normal(indexToWorld(interfacePoint));\n\t\t\t\t\tqefNormals.push_back(surfaceNormal);\n\t\t\t\t}\n\t\t\t}\n\n\t\tif (qefPoints.size() > 0)\n\t\t{\n\t\t\tEigen::MatrixXd A(qefPoints.size(), 2);\n\t\t\tEigen::VectorXd b(qefPoints.size());\n\t\t\tEigen::VectorXd pointCOM = Eigen::VectorXd::Zero(2);\n\n\t\t\tassert(qefPoints.size() > 1);\n\n\t\t\tfor (int pointIndex = 0; pointIndex < qefPoints.size(); ++pointIndex)\n\t\t\t{\n\t\t\t\tA(pointIndex, 0) = qefNormals[pointIndex][0];\n\t\t\t\tA(pointIndex, 1) = qefNormals[pointIndex][1];\n\n\t\t\t\tb(pointIndex) = dot(qefNormals[pointIndex], qefPoints[pointIndex]);\n\n\t\t\t\tpointCOM[0] += qefPoints[pointIndex][0];\n\t\t\t\tpointCOM[1] += qefPoints[pointIndex][1];\n\t\t\t}\n\n\t\t\tpointCOM /= float(qefPoints.size());\n\n\t\t\tEigen::JacobiSVD<Eigen::MatrixXd> svd(A, Eigen::ComputeThinU | Eigen::ComputeThinV);\n\t\t\tsvd.setThreshold(1E-2);\n\n\t\t\tEigen::VectorXd dcPoint = pointCOM + svd.solve(b - A * pointCOM);\n\n\t\t\tVec2f vecCOM(pointCOM[0], pointCOM[1]);\n\n\t\t\tVec2f boundingBoxMin = floor(vecCOM);\n\t\t\tVec2f boundingBoxMax = ceil(vecCOM);\n\n\t\t\tif (dcPoint[0] < boundingBoxMin[0] ||\n\t\t\t\tdcPoint[1] < boundingBoxMin[1] ||\n\t\t\t\tdcPoint[0] > boundingBoxMax[0] ||\n\t\t\t\tdcPoint[1] > boundingBoxMax[1])\n\t\t\t\tdcPoint = pointCOM;\n\n\t\t\tverts.push_back(indexToWorld(Vec2f(dcPoint[0], dcPoint[1])));\n\t\t\tdcPointIndex(cell) = verts.size() - 1;\n\t\t}\n\t});\n\n\tfor (int axis : {0, 1})\n\t{\n\t\tVec2i start(0); ++start[axis];\n\t\tVec2i end(dcPointIndex.size());\n\n\t\tforEachVoxelRange(start, end, [&](const Vec2i& face)\n\t\t{\n\t\t\tVec2i backwardNode = faceToNode(face, axis, 0);\n\t\t\tVec2i forwardNode = faceToNode(face, axis, 1);\n\n\t\t\tif ((myPhiGrid(backwardNode) <= 0 && myPhiGrid(forwardNode) > 0) ||\n\t\t\t\t(myPhiGrid(backwardNode) > 0 && myPhiGrid(forwardNode) <= 0))\n\t\t\t{\n\t\t\t\tVec2i backwardCell = faceToCell(Vec2i(face), axis, 0);\n\t\t\t\tVec2i forwardCell = faceToCell(Vec2i(face), axis, 1);\n\n\t\t\t\tassert(dcPointIndex(backwardCell) >= 0 && dcPointIndex(forwardCell) >= 0);\n\n\t\t\t\tVec2i edge;\n\t\t\t\tif (myPhiGrid(backwardNode) <= 0.)\n\t\t\t\t{\n\t\t\t\t\tif (axis == 0)\n\t\t\t\t\t\tedge = Vec2i(dcPointIndex(backwardCell), dcPointIndex(forwardCell));\n\t\t\t\t\telse\n\t\t\t\t\t\tedge = Vec2i(dcPointIndex(forwardCell), dcPointIndex(backwardCell));\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tif (axis == 0)\n\t\t\t\t\t\tedge = Vec2i(dcPointIndex(forwardCell), dcPointIndex(backwardCell));\n\t\t\t\t\telse\n\t\t\t\t\t\tedge = Vec2i(dcPointIndex(backwardCell), dcPointIndex(forwardCell));\n\t\t\t\t}\n\n\t\t\t\tedges.push_back(edge);\n\t\t\t}\n\t\t});\n\t}\n\n\treturn EdgeMesh(edges, verts);\n}\n\nVec2f LevelSet::interpolateInterface(const Vec2i& startPoint, const Vec2i& endPoint) const\n{\n\tassert((myPhiGrid(startPoint[0], startPoint[1]) <= 0 && myPhiGrid(endPoint[0], endPoint[1]) > 0) ||\n\t\t\t(myPhiGrid(startPoint[0], startPoint[1]) > 0 && myPhiGrid(endPoint[0], endPoint[1]) <= 0));\n\n\t//Find weight to zero isosurface\n\tfloat s = myPhiGrid(startPoint) / (myPhiGrid(startPoint) - myPhiGrid(endPoint));\n\ts = clamp(s, float(0), float(1));\n\n\tVec2f dx = Vec2f(endPoint) - Vec2f(startPoint);\n\treturn Vec2f(startPoint) + s * dx;\n}\n\nvoid LevelSet::unionSurface(const LevelSet& unionPhi)\n{\n\tassert(isGridMatched(unionPhi));\n\n\ttbb::parallel_for(tbb::blocked_range<int>(0, voxelCount(), tbbLightGrainSize), [&](const tbb::blocked_range<int>& range)\n\t{\n\t\tfor (int cellIndex = range.begin(); cellIndex != range.end(); ++cellIndex)\n\t\t{\n\t\t\tVec2i cell = myPhiGrid.unflatten(cellIndex);\n\t\t\tif (unionPhi(cell) < 2 * unionPhi.dx())\n\t\t\t\tmyPhiGrid(cell) = std::min(myPhiGrid(cell), unionPhi(cell));\n\t\t}\n\t});\n\n\treinitMesh();\n}\n\n}", "meta": {"hexsha": "e3789467ae904e9c4b1e61f2a1796aa99bbfd95c", "size": 28707, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Library/SurfaceTrackers/LevelSet.cpp", "max_stars_repo_name": "rgoldade/2DFluid", "max_stars_repo_head_hexsha": "8a30e17fc4bd97ca3c15e4b74f2aef896f39977c", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 19.0, "max_stars_repo_stars_event_min_datetime": "2019-03-07T15:24:05.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-03T13:11:09.000Z", "max_issues_repo_path": "Library/SurfaceTrackers/LevelSet.cpp", "max_issues_repo_name": "rgoldade/2DFluid", "max_issues_repo_head_hexsha": "8a30e17fc4bd97ca3c15e4b74f2aef896f39977c", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2019-07-07T12:42:09.000Z", "max_issues_repo_issues_event_max_datetime": "2020-02-04T18:56:56.000Z", "max_forks_repo_path": "Library/SurfaceTrackers/LevelSet.cpp", "max_forks_repo_name": "rgoldade/2DFluid", "max_forks_repo_head_hexsha": "8a30e17fc4bd97ca3c15e4b74f2aef896f39977c", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2019-05-14T05:45:45.000Z", "max_forks_repo_forks_event_max_datetime": "2019-10-11T17:13:00.000Z", "avg_line_length": 32.808, "max_line_length": 125, "alphanum_fraction": 0.6829693106, "num_tokens": 8370, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6334102775181399, "lm_q2_score": 0.5389832206876841, "lm_q1q2_score": 0.34139751139340685}}
{"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, Jonathan Gammell*/\n\n#include \"ompl/util/RandomNumbers.h\"\n#include \"ompl/util/Exception.h\"\n#include \"ompl/util/Console.h\"\n#include <mutex>\n#include <memory>\n#include <boost/math/constants/constants.hpp>\n#include <boost/scoped_ptr.hpp>\n#include <boost/random/uniform_on_sphere.hpp>\n#include <boost/random/variate_generator.hpp>\n#include <Eigen/Core>\n\n/// @cond IGNORE\nnamespace\n{\n    /// We use a different random number generator for the seeds of the\n    /// other random generators. The root seed is from the number of\n    /// nano-seconds in the current time, or given by the user.\n    class RNGSeedGenerator\n    {\n    public:\n        RNGSeedGenerator()\n          : firstSeed_(std::chrono::duration_cast<std::chrono::microseconds>(\n                           std::chrono::system_clock::now() - std::chrono::system_clock::time_point::min())\n                           .count())\n          , sGen_(firstSeed_)\n          , sDist_(1, 1000000000)\n        {\n        }\n\n        std::uint_fast32_t firstSeed()\n        {\n            std::lock_guard<std::mutex> slock(rngMutex_);\n            return firstSeed_;\n        }\n\n        void setSeed(std::uint_fast32_t seed)\n        {\n            std::lock_guard<std::mutex> slock(rngMutex_);\n            if (seed > 0)\n            {\n                if (someSeedsGenerated_)\n                {\n                    OMPL_ERROR(\"Random number generation already started. Changing seed now will not lead to \"\n                               \"deterministic sampling.\");\n                }\n                else\n                {\n                    // In this case, since no seeds have been generated yet, so we remember this seed as the first one.\n                    firstSeed_ = seed;\n                }\n            }\n            else\n            {\n                if (someSeedsGenerated_)\n                {\n                    OMPL_WARN(\"Random generator seed cannot be 0. Ignoring seed.\");\n                    return;\n                }\n                OMPL_WARN(\"Random generator seed cannot be 0. Using 1 instead.\");\n                seed = 1;\n            }\n            sGen_.seed(seed);\n        }\n\n        std::uint_fast32_t nextSeed()\n        {\n            std::lock_guard<std::mutex> slock(rngMutex_);\n            someSeedsGenerated_ = true;\n            return sDist_(sGen_);\n        }\n\n    private:\n        bool someSeedsGenerated_{false};\n        std::uint_fast32_t firstSeed_;\n        std::mutex rngMutex_;\n        std::ranlux24_base sGen_;\n        std::uniform_int_distribution<> sDist_;\n    };\n\n    std::once_flag g_once;\n    boost::scoped_ptr<RNGSeedGenerator> g_RNGSeedGenerator;\n\n    void initRNGSeedGenerator()\n    {\n        g_RNGSeedGenerator.reset(new RNGSeedGenerator());\n    }\n\n    RNGSeedGenerator &getRNGSeedGenerator()\n    {\n        std::call_once(g_once, &initRNGSeedGenerator);\n        return *g_RNGSeedGenerator;\n    }\n}  // namespace\n/// @endcond\n\n/// @cond IGNORE\nclass ompl::RNG::SphericalData\n{\npublic:\n    /** \\brief The container type for the variate generators. */\n    using container_type_t = std::vector<double>;\n\n    /** \\brief The uniform_on_sphere distribution type. */\n    using spherical_dist_t = boost::uniform_on_sphere<double, container_type_t>;\n\n    /** \\brief The resulting variate generator type. */\n    using variate_generator_t = boost::variate_generator<std::mt19937 *, spherical_dist_t>;\n\n    /** \\brief Constructor */\n    SphericalData(std::mt19937 *generatorPtr) : generatorPtr_(generatorPtr){};\n\n    /** \\brief The generator for a specified dimension. Will create if not existent */\n    container_type_t generate(unsigned int dim)\n    {\n        // Assure that the dimension is in the range of the vector.\n        growVector(dim);\n\n        // Assure that the dimension is allocated:\n        allocateDimension(dim);\n\n        // Return the generator\n        return (*dimVector_.at(dim).second)();\n    };\n\n    /** \\brief Iterate over all the dimensions and reset the generators that exist. */\n    void reset()\n    {\n        // Iterate over each dimension\n        for (auto &i : dimVector_)\n            // Check if the variate_generator is allocated\n            if (bool(i.first))\n                // It is, reset THE DATA (not the pointer)\n                i.first->reset();\n        // No else, this is an uninitialized dimension.\n    };\n\nprivate:\n    /** \\brief The pair of distribution and variate generator. */\n    using dist_gen_pair_t = std::pair<std::shared_ptr<spherical_dist_t>, std::shared_ptr<variate_generator_t>>;\n\n    /** \\brief A vector distribution and variate generators (as pointers) indexed on dimension. */\n    std::vector<dist_gen_pair_t> dimVector_;\n\n    /** \\brief A pointer to the generator owned by the outer class. Needed for creating new variate_generators */\n    std::mt19937 *generatorPtr_;\n\n    /** \\brief Grow the vector until it contains an (empty) entry for the specified dimension. */\n    void growVector(unsigned int dim)\n    {\n        // Iterate until the index associated with this dimension is in the vector\n        while (dim >= dimVector_.size())\n            // Create a pair of empty pointers:\n            dimVector_.emplace_back();\n    };\n\n    /** \\brief Assure that a distribution/generator is allocated for the specified index. */\n    void allocateDimension(unsigned int dim)\n    {\n        // Only do this if unallocated, so check that:\n        if (dimVector_.at(dim).first == nullptr)\n        {\n            // It is not allocated, so....\n            // First construct the distribution\n            dimVector_.at(dim).first = std::make_shared<spherical_dist_t>(dim);\n            // Then the variate generator\n            dimVector_.at(dim).second = std::make_shared<variate_generator_t>(generatorPtr_, *dimVector_.at(dim).first);\n        }\n        // No else, the pointer is already allocated.\n    };\n};\n/// @endcond\n\nstd::uint_fast32_t ompl::RNG::getSeed()\n{\n    return getRNGSeedGenerator().firstSeed();\n}\n\nvoid ompl::RNG::setSeed(std::uint_fast32_t seed)\n{\n    getRNGSeedGenerator().setSeed(seed);\n}\n\nompl::RNG::RNG()\n  : localSeed_(getRNGSeedGenerator().nextSeed())\n  , generator_(localSeed_)\n  , sphericalDataPtr_(std::make_shared<SphericalData>(&generator_))\n{\n}\n\nompl::RNG::RNG(std::uint_fast32_t localSeed)\n  : localSeed_(localSeed), generator_(localSeed_), sphericalDataPtr_(std::make_shared<SphericalData>(&generator_))\n{\n}\n\nvoid ompl::RNG::setLocalSeed(std::uint_fast32_t localSeed)\n{\n    // Store the seed\n    localSeed_ = localSeed;\n\n    // Change the generator's seed\n    generator_.seed(localSeed_);\n\n    // Reset the distributions used by the variate generators, as they can cache values\n    uniDist_.reset();\n    normalDist_.reset();\n    sphericalDataPtr_->reset();\n}\n\ndouble ompl::RNG::halfNormalReal(double r_min, double r_max, double focus)\n{\n    assert(r_min <= r_max);\n\n    const double mean = r_max - r_min;\n    double v = gaussian(mean, mean / focus);\n\n    if (v > mean)\n        v = 2.0 * mean - v;\n    double r = v >= 0.0 ? v + r_min : r_min;\n    return r > r_max ? r_max : r;\n}\n\nint ompl::RNG::halfNormalInt(int r_min, int r_max, double focus)\n{\n    auto r = (int)floor(halfNormalReal((double)r_min, (double)(r_max) + 1.0, focus));\n    return (r > r_max) ? r_max : r;\n}\n\n// From: \"Uniform Random Rotations\", Ken Shoemake, Graphics Gems III,\n//       pg. 124-132\nvoid ompl::RNG::quaternion(double value[4])\n{\n    double x0 = uniDist_(generator_);\n    double r1 = sqrt(1.0 - x0), r2 = sqrt(x0);\n    double t1 = 2.0 * boost::math::constants::pi<double>() * uniDist_(generator_),\n           t2 = 2.0 * boost::math::constants::pi<double>() * uniDist_(generator_);\n    double c1 = cos(t1), s1 = sin(t1);\n    double c2 = cos(t2), s2 = sin(t2);\n    value[0] = s1 * r1;\n    value[1] = c1 * r1;\n    value[2] = s2 * r2;\n    value[3] = c2 * r2;\n}\n\n// From Effective Sampling and Distance Metrics for 3D Rigid Body Path Planning, by James Kuffner, ICRA 2004\nvoid ompl::RNG::eulerRPY(double value[3])\n{\n    value[0] = boost::math::constants::pi<double>() * (-2.0 * uniDist_(generator_) + 1.0);\n    value[1] = acos(1.0 - 2.0 * uniDist_(generator_)) - boost::math::constants::pi<double>() / 2.0;\n    value[2] = boost::math::constants::pi<double>() * (-2.0 * uniDist_(generator_) + 1.0);\n}\n\nvoid ompl::RNG::uniformNormalVector(std::vector<double> &v)\n{\n    // Generate a random value, the variate_generator is returning a shallow_array_adaptor, which will modify the value\n    // array:\n    v = sphericalDataPtr_->generate(v.size());\n}\n\n// See: http://math.stackexchange.com/a/87238\nvoid ompl::RNG::uniformInBall(double r, std::vector<double> &v)\n{\n    // Draw a random point on the unit sphere\n    uniformNormalVector(v);\n\n    // Draw a random radius scale\n    double radiusScale = r * std::pow(uniformReal(0.0, 1.0), 1.0 / static_cast<double>(v.size()));\n\n    // Scale the point on the unit sphere\n    std::transform(v.begin(), v.end(), v.begin(), [radiusScale](double x) { return radiusScale * x; });\n}\n\nvoid ompl::RNG::uniformProlateHyperspheroidSurface(const std::shared_ptr<const ProlateHyperspheroid> &phsPtr,\n                                                   double value[])\n{\n    // Variables\n    // The spherical point as a std::vector\n    std::vector<double> sphere(phsPtr->getDimension());\n\n    // Get a random point on the sphere\n    uniformNormalVector(sphere);\n\n    // Transform to the PHS\n    phsPtr->transform(&sphere[0], value);\n}\n\nvoid ompl::RNG::uniformProlateHyperspheroid(const std::shared_ptr<const ProlateHyperspheroid> &phsPtr, double value[])\n{\n    // Variables\n    // The spherical point as a std::vector\n    std::vector<double> sphere(phsPtr->getDimension());\n\n    // Get a random point in the sphere\n    uniformInBall(1.0, sphere);\n\n    // Transform to the PHS\n    phsPtr->transform(&sphere[0], value);\n}\n", "meta": {"hexsha": "98268ae80ffb6a5fe225e3fe2c66c1544753a319", "size": 11583, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/ompl/util/src/RandomNumbers.cpp", "max_stars_repo_name": "juleswh/ompl", "max_stars_repo_head_hexsha": "5f384c8f2a4886c0656ed2f063d385137c4e930e", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-08-11T13:01:27.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-11T13:01:27.000Z", "max_issues_repo_path": "src/ompl/util/src/RandomNumbers.cpp", "max_issues_repo_name": "juleswh/ompl", "max_issues_repo_head_hexsha": "5f384c8f2a4886c0656ed2f063d385137c4e930e", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_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/util/src/RandomNumbers.cpp", "max_forks_repo_name": "juleswh/ompl", "max_forks_repo_head_hexsha": "5f384c8f2a4886c0656ed2f063d385137c4e930e", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-12-06T11:15:08.000Z", "max_forks_repo_forks_event_max_datetime": "2020-01-29T12:04:40.000Z", "avg_line_length": 34.6796407186, "max_line_length": 120, "alphanum_fraction": 0.6339463006, "num_tokens": 2826, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6334102775181399, "lm_q2_score": 0.5389832206876841, "lm_q1q2_score": 0.34139751139340685}}
{"text": "#include <iostream>\n#include <vector>\n#include <string>\n\n#include <boost/program_options.hpp>\n#include <boost/property_tree/ptree.hpp>\n#include <boost/property_tree/json_parser.hpp>\n#include <boost/preprocessor/seq/for_each.hpp>\n\n#include <amgcl/backend/builtin.hpp>\n#include <amgcl/value_type/static_matrix.hpp>\n#include <amgcl/adapter/crs_tuple.hpp>\n#include <amgcl/adapter/block_matrix.hpp>\n\n#if defined(SOLVER_BACKEND_VEXCL)\n#  include <amgcl/backend/vexcl.hpp>\n#  include <amgcl/backend/vexcl_static_matrix.hpp>\n#elif defined(SOLVER_BACKEND_CUDA)\n#  include <amgcl/backend/cuda.hpp>\n#  include <amgcl/relaxation/cusparse_ilu0.hpp>\n#else\n#  ifndef SOLVER_BACKEND_BUILTIN\n#    define SOLVER_BACKEND_BUILTIN\n#  endif\n#endif\n\n#include <amgcl/mpi/util.hpp>\n#include <amgcl/mpi/make_solver.hpp>\n#include <amgcl/mpi/preconditioner.hpp>\n#include <amgcl/mpi/solver/runtime.hpp>\n\n#include <amgcl/io/mm.hpp>\n#include <amgcl/io/binary.hpp>\n#include <amgcl/profiler.hpp>\n\n#ifndef AMGCL_BLOCK_SIZES\n#  define AMGCL_BLOCK_SIZES (3)(4)\n#endif\n\nnamespace amgcl {\n    profiler<> prof;\n}\n\nnamespace math = amgcl::math;\n\n//---------------------------------------------------------------------------\nptrdiff_t assemble_poisson3d(amgcl::mpi::communicator comm,\n        ptrdiff_t n, 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 n3 = n * n * n;\n\n    ptrdiff_t chunk = (n3 + comm.size - 1) / comm.size;\n    if (chunk % block_size != 0) {\n        chunk += block_size - chunk % block_size;\n    }\n    ptrdiff_t row_beg = std::min(n3, chunk * comm.rank);\n    ptrdiff_t row_end = std::min(n3, row_beg + chunk);\n    chunk = row_end - row_beg;\n\n    ptr.clear(); ptr.reserve(chunk + 1);\n    col.clear(); col.reserve(chunk * 7);\n    val.clear(); val.reserve(chunk * 7);\n\n    rhs.resize(chunk);\n    std::fill(rhs.begin(), rhs.end(), 1.0);\n\n    const double h2i = (n - 1) * (n - 1);\n    ptr.push_back(0);\n\n    for (ptrdiff_t idx = row_beg; idx < row_end; ++idx) {\n        ptrdiff_t k = idx / (n * n);\n        ptrdiff_t j = (idx / n) % n;\n        ptrdiff_t i = idx % n;\n\n        if (k > 0)  {\n            col.push_back(idx - n * n);\n            val.push_back(-h2i);\n        }\n\n        if (j > 0)  {\n            col.push_back(idx - n);\n            val.push_back(-h2i);\n        }\n\n        if (i > 0) {\n            col.push_back(idx - 1);\n            val.push_back(-h2i);\n        }\n\n        col.push_back(idx);\n        val.push_back(6 * h2i);\n\n        if (i + 1 < n) {\n            col.push_back(idx + 1);\n            val.push_back(-h2i);\n        }\n\n        if (j + 1 < n) {\n            col.push_back(idx + n);\n            val.push_back(-h2i);\n        }\n\n        if (k + 1 < n) {\n            col.push_back(idx + n * n);\n            val.push_back(-h2i);\n        }\n\n        ptr.push_back( col.size() );\n    }\n\n    return chunk;\n}\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        typename Backend::vector &rhs, const typename Backend::params &bprm,\n        amgcl::runtime::mpi::partition::type ptype, int block_size = 1)\n{\n    typedef typename Backend::value_type val_type;\n    typedef typename amgcl::math::rhs_of<val_type>::type rhs_type;\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    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#if defined(SOLVER_BACKEND_BUILTIN)\n    amgcl::backend::numa_vector<rhs_type> new_rhs(J->loc_rows());\n#elif defined(SOLVER_BACKEND_VEXCL)\n    vex::vector<rhs_type> new_rhs(bprm.q, J->loc_rows());\n#elif defined(SOLVER_BACKEND_CUDA)\n    thrust::device_vector<rhs_type> new_rhs(J->loc_rows());\n#endif\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//---------------------------------------------------------------------------\n#if defined(SOLVER_BACKEND_BUILTIN) || defined(SOLVER_BACKEND_VEXCL)\ntemplate <int B>\nvoid solve_block(\n        amgcl::mpi::communicator comm,\n        ptrdiff_t chunk,\n        const std::vector<ptrdiff_t>      &ptr,\n        const std::vector<ptrdiff_t>      &col,\n        const std::vector<double>         &val,\n        const boost::property_tree::ptree &prm,\n        const std::vector<double>         &f,\n        amgcl::runtime::mpi::partition::type ptype\n        )\n{\n    typedef amgcl::static_matrix<double, B, B> val_type;\n    typedef amgcl::static_matrix<double, B, 1> rhs_type;\n\n#if defined(SOLVER_BACKEND_BUILTIN)\n    typedef amgcl::backend::builtin<val_type> Backend;\n#elif defined(SOLVER_BACKEND_VEXCL)\n    typedef amgcl::backend::vexcl<val_type> Backend;\n#endif\n\n    typedef\n        amgcl::mpi::make_solver<\n            amgcl::runtime::mpi::preconditioner<Backend>,\n            amgcl::runtime::mpi::solver::wrapper<Backend>\n            >\n        Solver;\n\n    using amgcl::prof;\n\n    typename Backend::params bprm;\n\n#if defined(SOLVER_BACKEND_BUILTIN)\n    amgcl::backend::numa_vector<rhs_type> rhs(\n            reinterpret_cast<const rhs_type*>(&f[0]),\n            reinterpret_cast<const rhs_type*>(&f[0]) + chunk / B\n            );\n#elif defined(SOLVER_BACKEND_VEXCL)\n    vex::Context ctx(vex::Filter::Env);\n    bprm.q = ctx;\n\n    vex::scoped_program_header header(ctx,\n            amgcl::backend::vexcl_static_matrix_declaration<double,B>());\n\n    if (comm.rank == 0) std::cout << ctx << std::endl;\n\n    vex::vector<rhs_type> rhs(ctx, chunk / B, reinterpret_cast<const rhs_type*>(&f[0]));\n#endif\n\n    prof.tic(\"setup\");\n    std::shared_ptr<Solver> solve;\n    if (ptype) {\n        auto A = partition<Backend>(comm,\n                amgcl::adapter::block_matrix<val_type>(std::tie(chunk, ptr, col, val)),\n                rhs, bprm, ptype, prm.get(\"precond.coarsening.aggr.block_size\", 1));\n\n        solve = std::make_shared<Solver>(comm, A, prm, bprm);\n        chunk = A->loc_rows();\n    } else {\n        solve = std::make_shared<Solver>(comm,\n                amgcl::adapter::block_matrix<val_type>(std::tie(chunk, ptr, col, val)),\n                prm, bprm);\n    }\n    prof.toc(\"setup\");\n\n    if (comm.rank == 0) {\n        std::cout << *solve << std::endl;\n    }\n\n#if defined(SOLVER_BACKEND_BUILTIN)\n    amgcl::backend::numa_vector<rhs_type> x(chunk);\n#elif defined(SOLVER_BACKEND_VEXCL)\n    vex::vector<rhs_type> x(ctx, chunk);\n    x = math::zero<rhs_type>();\n#endif\n\n    int    iters;\n    double error;\n\n    prof.tic(\"solve\");\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#endif\n\n//---------------------------------------------------------------------------\nvoid solve_scalar(\n        amgcl::mpi::communicator comm,\n        ptrdiff_t chunk,\n        const std::vector<ptrdiff_t> &ptr,\n        const std::vector<ptrdiff_t> &col,\n        const std::vector<double> &val,\n        const boost::property_tree::ptree &prm,\n        const std::vector<double> &f,\n        amgcl::runtime::mpi::partition::type ptype\n        )\n{\n#if defined(SOLVER_BACKEND_BUILTIN)\n    typedef amgcl::backend::builtin<double> Backend;\n#elif defined(SOLVER_BACKEND_VEXCL)\n    typedef amgcl::backend::vexcl<double> Backend;\n#elif defined(SOLVER_BACKEND_CUDA)\n    typedef amgcl::backend::cuda<double> Backend;\n#endif\n\n    typedef\n        amgcl::mpi::make_solver<\n            amgcl::runtime::mpi::preconditioner<Backend>,\n            amgcl::runtime::mpi::solver::wrapper<Backend>\n            >\n        Solver;\n\n    using amgcl::prof;\n\n    typename Backend::params bprm;\n\n#if defined(SOLVER_BACKEND_BUILTIN)\n    amgcl::backend::numa_vector<double> rhs(f);\n#elif defined(SOLVER_BACKEND_VEXCL)\n    vex::Context ctx(vex::Filter::Env);\n    bprm.q = ctx;\n\n    if (comm.rank == 0) std::cout << ctx << std::endl;\n\n    vex::vector<double> rhs(ctx, f);\n#elif defined(SOLVER_BACKEND_CUDA)\n    cusparseCreate(&bprm.cusparse_handle);\n    thrust::device_vector<double> rhs(f);\n#endif\n\n    prof.tic(\"setup\");\n    std::shared_ptr<Solver> solve;\n    if (ptype) {\n        auto A = partition<Backend>(comm,\n                std::tie(chunk, ptr, col, val), rhs, bprm, ptype,\n                prm.get(\"precond.coarsening.aggr.block_size\", 1));\n\n        solve = std::make_shared<Solver>(comm, A, prm, bprm);\n        chunk = A->loc_rows();\n    } else {\n        solve = std::make_shared<Solver>(comm, std::tie(chunk, ptr, col, val), prm, bprm);\n    }\n    prof.toc(\"setup\");\n\n    if (comm.rank == 0) {\n        std::cout << *solve << std::endl;\n    }\n\n#if defined(SOLVER_BACKEND_BUILTIN)\n    amgcl::backend::numa_vector<double> x(chunk);\n#elif defined(SOLVER_BACKEND_VEXCL)\n    vex::vector<double> x(ctx, chunk);\n    x = 0.0;\n#elif defined(SOLVER_BACKEND_CUDA)\n    thrust::device_vector<double> x(chunk, 0.0);\n#endif\n\n    int    iters;\n    double error;\n\n    prof.tic(\"solve\");\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\n//---------------------------------------------------------------------------\nint main(int argc, char *argv[]) {\n    amgcl::mpi::init_thread mpi(&argc, &argv);\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         \"Ap\",\n         po::value< std::vector<std::string> >()->multitoken(),\n         \"Pre-partitioned matrix (single file per MPI process)\"\n        )\n        (\n         \"fp\",\n         po::value< std::vector<std::string> >()->multitoken(),\n         \"Pre-partitioned RHS (single file per MPI process)\"\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         \"When specified, the system matrix is assumed to have block-wise structure. \"\n         \"This usually is the case for problems in elasticity, structural mechanics, \"\n         \"for coupled systems of PDE (such as Navier-Stokes equations), etc. \"\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_PARMETIS)\n             amgcl::runtime::mpi::partition::parmetis\n#else\n             amgcl::runtime::mpi::partition::merge\n#endif\n             ),\n         \"Repartition the system matrix\"\n        )\n        (\n         \"size,n\",\n         po::value<ptrdiff_t>()->default_value(128),\n         \"domain size\"\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::positional_options_description p;\n    p.add(\"prm\", -1);\n\n    po::variables_map vm;\n    po::store(po::command_line_parser(argc, argv).options(desc).positional(p).run(), vm);\n    po::notify(vm);\n\n    if (vm.count(\"help\")) {\n        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    int aggr_block = prm.get(\"precond.coarsening.aggr.block_size\", 1);\n\n    bool binary = vm[\"binary\"].as<bool>();\n    amgcl::runtime::mpi::partition::type ptype = vm[\"partitioner\"].as<amgcl::runtime::mpi::partition::type>();\n\n    if (vm.count(\"matrix\")) {\n        prof.tic(\"read\");\n        if (binary) {\n            n = read_binary(comm,\n                    vm[\"matrix\"].as<std::string>(),\n                    vm[\"rhs\"].as<std::string>(),\n                    block_size * aggr_block, 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 * aggr_block, ptr, col, val, rhs);\n        }\n        prof.toc(\"read\");\n    } else if (vm.count(\"Ap\")) {\n        prof.tic(\"read\");\n        ptype = static_cast<amgcl::runtime::mpi::partition::type>(0);\n\n        std::vector<std::string> Aparts = vm[\"Ap\"].as<std::vector<std::string>>();\n        comm.check(Aparts.size() == static_cast<size_t>(comm.size),\n                \"--Ap should have single entry per MPI process\");\n\n        if (binary) {\n            amgcl::io::read_crs(Aparts[comm.rank], n, ptr, col, val);\n        } else {\n            ptrdiff_t m;\n            std::tie(n, m) = amgcl::io::mm_reader(Aparts[comm.rank])(ptr, col, val);\n        }\n\n        if (vm.count(\"fp\")) {\n            std::vector<std::string> fparts = vm[\"fp\"].as<std::vector<std::string>>();\n            comm.check(fparts.size() == static_cast<size_t>(comm.size),\n                    \"--fp should have single entry per MPI process\");\n\n            ptrdiff_t rows;\n            ptrdiff_t cols;\n\n            if (binary) {\n                amgcl::io::read_dense(fparts[comm.rank], rows, cols, rhs);\n            } else {\n                std::tie(rows, cols) = amgcl::io::mm_reader(fparts[comm.rank])(rhs);\n            }\n\n            comm.check(rhs.size() == static_cast<size_t>(n), \"Wrong RHS size\");\n        } else {\n            rhs.resize(n, 1);\n        }\n        prof.toc(\"read\");\n    } else {\n        prof.tic(\"assemble\");\n        n = assemble_poisson3d(comm,\n                vm[\"size\"].as<ptrdiff_t>(),\n                block_size * aggr_block, ptr, col, val, rhs);\n        prof.toc(\"assemble\");\n    }\n\n    switch(block_size) {\n\n#if defined(SOLVER_BACKEND_BUILTIN) || defined(SOLVER_BACKEND_VEXCL)\n#  define AMGCL_CALL_BLOCK_SOLVER(z, data, B)                        \\\n        case B:                                                      \\\n            solve_block<B>(comm, n, ptr, col, val, prm, rhs, ptype); \\\n            break;\n\n        BOOST_PP_SEQ_FOR_EACH(AMGCL_CALL_BLOCK_SOLVER, ~, AMGCL_BLOCK_SIZES)\n\n#  undef AMGCL_CALL_BLOCK_SOLVER\n#endif\n\n        case 1:\n            solve_scalar(comm, n, ptr, col, val, prm, rhs, ptype);\n            break;\n        default:\n            if (comm.rank == 0)\n                std::cout << \"Unsupported block size!\" << std::endl;\n    }\n}\n", "meta": {"hexsha": "db49b6012f2f0077cc0f7c14a827bc434470d485", "size": 18464, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/mpi/mpi_solver.cpp", "max_stars_repo_name": "tenglongcong/amgcl", "max_stars_repo_head_hexsha": "61948e1a49c1cbc9fdb68c92d532c8b70e021516", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 504.0, "max_stars_repo_stars_event_min_datetime": "2015-03-11T13:50:39.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-20T13:08:55.000Z", "max_issues_repo_path": "examples/mpi/mpi_solver.cpp", "max_issues_repo_name": "tenglongcong/amgcl", "max_issues_repo_head_hexsha": "61948e1a49c1cbc9fdb68c92d532c8b70e021516", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 209.0, "max_issues_repo_issues_event_min_datetime": "2015-01-02T19:13:22.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T06:44:12.000Z", "max_forks_repo_path": "examples/mpi/mpi_solver.cpp", "max_forks_repo_name": "tenglongcong/amgcl", "max_forks_repo_head_hexsha": "61948e1a49c1cbc9fdb68c92d532c8b70e021516", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 92.0, "max_forks_repo_forks_event_min_datetime": "2015-01-04T06:11:22.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-24T09:49:12.000Z", "avg_line_length": 30.3684210526, "max_line_length": 110, "alphanum_fraction": 0.5603877816, "num_tokens": 4916, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6334102498375401, "lm_q2_score": 0.5389832206876841, "lm_q1q2_score": 0.341397496474028}}
{"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-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/**\n* \\file\n* \\author Martin Weiser\n* This file contains an implementation of an additive hierarchical basis preconditioner.\n*/\n\n#ifndef HB_HH\n#define HB_HH\n\n#include <cassert>\n#include <cmath>\n#include <iostream>\n#include <vector>\n\n#include <boost/utility/result_of.hpp>\n\n#include \"dune/grid/common/grid.hh\"\n#include \"dune/istl/preconditioners.hh\"\n\n#include \"fem/barycentric.hh\"\n\n\nnamespace Kaskade {\n  \n  /**\n  * \\ingroup linalgsolution\n  * \\brief A hierarchical basis preconditioner.\n  *\n  * This preconditioner realizes an approximative inverse of a Laplace operator with constant diffusion coefficient\n  * discretized by linear finite elements in nodal basis over the leaf view of the provided grid.\n  *\n  * This implementation is geometry- and coefficient-agnostic, i.e. it assumes that the diagonal of the stiffness matrix is\n  * just the identity. The advantage of this approach are its extreme simplicity, both in terms of interface and implementation,\n  * a minimal memory footprint, and very cheap set-up phase and application. The drawback is, of course, a worse resulting\n  * condition number in case non-uniform coarse grids, anisotropic coarse grids, or spatially varying or anisotropic\n  * diffusion coefficients are to be treated.\n  *\n  * Extending the implementation to take more structure (stiffness matrices, non-uniform grids) into account is probably\n  * not worth the while, as the iteration count grows anyway in proportion to the number of refinement levels in 2D\n  * or even faster in 3D. If the simplicity of the PrecondType::HB preconditioner does'nt pay off, have a look at \\ref MultigridSolver\n  * or \\ref BPXYPreconditioner.\n  *\n  * We refer to Deuflhard/Weiser Chapter 7.3.\n  *\n  * \\tparam Grid the grid on which the Laplace operator is discretized. This implementation assumes that the grid \n  *              is purely simplicial and that on refinement new nodes are created only at edge midpoints.\n  * \\tparam Domain the type of domain space vectors\n  * \\tparam Range the type of range space vectors\n  */\n\n\n\n  template <class Grid, class Domain, class Range>\n  class HierarchicalBasisPreconditioner: public Dune::Preconditioner<Domain,Range> {\n    private:\n      typedef typename Grid::LevelGridView::IndexSet::IndexType Index;\n      typedef std::vector<Index>                                NodeSet;\n\t    \n      static int const dim = Grid::dimension;\n      \n    public:\n      enum { category = Dune::SolverCategory::sequential };\n\t    \n      /**\n      * \\brief Constructor.\n      * \\param grid the grid \n      * \\param mat_ a matrix containing (at least) the diagonal of the stiffness matrix\n      */\n      explicit HierarchicalBasisPreconditioner(Grid const& grid) \n      {\n\t// make sure the grid satisfies our assumptions: a purely simplicial grid\n\tassert(grid.leafIndexSet().geomTypes(0).size()==1 && grid.leafIndexSet().geomTypes(0)[0].isSimplex()\n\t      && \"HierarchicalBasisPreconditioner currently requires purely simplicial grids\");\n\n\t      \n\t// extract and store relevant sizes\n\tj = grid.maxLevel();\n\tn = grid.leafIndexSet().size(dim);\n\t\n\t\n\ttypedef typename Grid::template Codim<0>::LevelIterator  CellLevelIterator;\n\ttypedef typename Grid::template Codim<dim>::LevelIterator LeafVertexIterator;\n\t\n\t// extract the coarse grid nodes\n\tnodesOnLevel.resize(j+1); \n\tfor (LeafVertexIterator i=grid.template lbegin<dim>(0); i!=grid.template lend<dim>(0); ++i)\n\t  nodesOnLevel[0].push_back(grid.leafIndexSet().index(*i));\n\t\n\t// extract the coarse grid elements' vertices\n\tcoarseElement.reserve(grid.levelIndexSet(0).size(0));\n\tfor (CellLevelIterator ci=grid.template lbegin<0>(0); ci!=grid.template lend<0>(0); ++ci)\n\t{\n\t  Dune::FieldVector<Index,dim+1> idx;\n\t  for (int i=0; i<=dim; ++i)\n\t    idx[i] = grid.leafIndexSet().index(*(ci->template subEntity<dim>(i)));\n\t  coarseElement.push_back(idx);\n\t}\n\t\n\t// compute the parents of each node on level >0\n\tparents.resize(n,std::make_pair(n,n)); // invalid sentinel (n,n) denotes not yet processed nodes.\n\tfor (int k=1; k<=j; ++k) \n\t{\n\t  // On each level, look out where nodes of this level are located in their father cell. Their barycentric coordinates\n\t  // should have exactly two nonzero entries of size 0.5. The corresponding corners of the father cell are the parents.\n\t  for (CellLevelIterator ci=grid.template lbegin<0>(k); ci!=grid.template lend<0>(k); ++ci)\n\t  {\n\t    typedef typename Grid::template Codim<0>::EntityPointer CellPointer;\n\t    CellPointer father = ci->father();\n\t    \n\t    // Extract indices of father's vertices\n\t    // @TODO Variable is never read! Remove or keep for future extension of the preconditioner??\n//            Index fatherCornerIndex[dim+1];\n//            for (int i=0; i<=dim; ++i)\n//              fatherCornerIndex[i] = grid.leafIndexSet().index(*(father->template subEntity<dim>(i)));\n\t    \n\t    // consider each vertex of current cell in turn\n\t    for (int i=0; i<=dim; ++i)\n\t    {\n\t      typename Grid::template Codim<dim>::EntityPointer vertexPointer = ci->template subEntity<dim>(i);\n\t      Index idx = grid.leafIndexSet().index(*vertexPointer);\n\t      \n\t      \n\t      // Edge midpoints can be reached from multiple cells depending on the spatial dimension. The parent nodes \n\t      // are independent of from which cell we look. Thus we check wether we've already done the work.\n\t      if (parents[idx].first==n && vertexPointer->level()>0) // not yet processed (but has parents)\n\t      {\n\t\t// Obtain barycentric coordinates of child corner in father. For child nodes located on an edge,\n\t\t// there will be exactly two nonzero entries associated to the vertices. Note that the barycentric\n\t\t// coordinates as implemented in fem/barycentric.hh are shifted by index 1 compared to the \n\t\t// reference element vertex numbering.\n\t\tDune::FieldVector<typename Grid::ctype,dim+1> relativeCoord = barycentric(ci->geometryInFather().corner(i));\n\t\t\n\t\t// Extract the two coordinates with value 0.5\n\t\tint coords[dim+1];\n\t\tint pos = 0;\n\t\tfor (int m=0; m<=dim; ++m)\n\t\t  if (relativeCoord[m] > 0.4)\n\t\t    coords[pos++] = (m+1)%(dim+1);\n\t\t  \n\t\tif (pos==2)\n\t\t{\n\t\t  // that's an edge midpoint: obtain the leaf indices of those father corners\n\t\t  parents[idx].first  = grid.leafIndexSet().index(*(father->template subEntity<dim>(coords[0])));\n\t\t  parents[idx].second = grid.leafIndexSet().index(*(father->template subEntity<dim>(coords[1])));\n\t\t  \n\t\t  // write down that this node appeared first on level k\n\t\t  nodesOnLevel[k].push_back(idx);\n\t\t}\n\t      }\n\t    }\n\t  }\n\t}\n\t\n\t// perform sanity checks\n\t#ifndef NDEBUG\n\t// check that each level >0 node has parents\n\tint count = nodesOnLevel[0].size();\n\tfor (int k=1; k<=j; ++k) \n\t{\n\t  for (typename NodeSet::const_iterator i=nodesOnLevel[k].begin(); i!=nodesOnLevel[k].end(); ++i)\n\t    assert(parents[*i].first<n && parents[*i].second<n);\n\t  count += nodesOnLevel[k].size();\n\t}\n\tassert(count==n);\n\t#endif\n      }\n      \n      /** \n      * \\brief Has to be called before the first call to apply\n      */\n      virtual void pre (Domain& x, Range& b) \n      {\n\t// actually, does nothing :)\n      }\n\n      /**\n      * \\brief applies the preconditioner to the residual \\arg d, which results in the correction \\arg v\n      */\n      virtual void apply (Domain& v, const Range& d) \n      {\n\tusing namespace boost::fusion;\n      // We modify the residual (in-place), hence we have to copy it here.\n\tRange r = d;\n\t\n\t// apply smoother and recursively restrict the residual downwards through the mesh hierarchy\n\tfor (int k=j; k>0; --k) \n\t{\n\t  // correct scaling for diagonal coefficients\n\t  typename Domain::field_type a = std::pow(2.0,(Grid::dimension-2.0)*(k-j));\n\t  \n\t  //  for all nodes on level k\n\t  for (typename NodeSet::const_iterator i=nodesOnLevel[k].begin(); i!=nodesOnLevel[k].end(); ++i)\n\t  {\n\t    // apply one Jacobi step, care for correct scaling of lower level hierarchical basis functions\n\t    // Beispiel at_c<0>(estSol.data)[*j];\n\t    \n\t    at_c<0>(v.data)[*i] = at_c<0>(r.data)[*i];\n\t    at_c<0>(v.data)[*i] /= a; \n\t    \n\t    // restrict the residual\n\t    at_c<0>(r.data)[parents[*i].first]  += 0.5 * at_c<0>(r.data)[*i];\n\t    at_c<0>(r.data)[parents[*i].second] += 0.5 * at_c<0>(r.data)[*i];\n\t  }\n\t}\n\t\n\t// \"solve\" on coarse grid. \n\tcoarseGridSolution(v,r);\n\t\n\t// prolongate the correction recursively upwards through the mesh hierarchy, adding up\n\t// all the corrections from different levels\n\tfor (int k=1; k<=j; ++k) \n\t  // the nodes on level k get contributions of 0.5 from each of their parent nodes - that's all\n\t  for (typename NodeSet::const_iterator i=nodesOnLevel[k].begin(); i!=nodesOnLevel[k].end(); ++i)\n\t    at_c<0>(v.data)[*i] += 0.5*(at_c<0>(v.data)[parents[*i].first]+at_c<0>(v.data)[parents[*i].second]);\n      }\n\n      /**\n      * \\brief Has to be called after the last call to apply\n      */\n      virtual void post (Domain& x)\n      {\n\t// actually, does nothing :)\n      }\n\n    private:\n      std::vector<NodeSet>                       nodesOnLevel;   // hierarchical basis node sets\n      std::vector<std::pair<Index,Index> >       parents;        // parent nodes of child nodes on level >0\n      int                                        j;              // maximum grid level\n      Index                                      n;              // total number of nodes\n      std::vector<Dune::FieldVector<Index,dim+1> > coarseElement;\n      \n      // This coarse grid solution employs a simple Jacobi iteration, where the \n      // matrix is simply patched together from identical elemental stiffness matrices.\n      // TODO: maybe it would be better to explicitly form the coarse grid matrix and use a direct solver\n      void coarseGridSolution(Domain& v, Range& r) const {\n\tusing namespace boost::fusion;\n\t// get the correct scaling for the coarse grid\n\ttypename Domain::field_type a = std::pow(2.0,-(Grid::dimension-2.0));\n\t\n\t// Initialize correction to zero\n\tfor (typename NodeSet::const_iterator i=nodesOnLevel[0].begin(); i!=nodesOnLevel[0].end(); ++i)\n\t  at_c<0>(v.data)[*i] = 0;\n\tDomain dv = v; // TODO: that's a looooong vector (overkill)\n\t\n\t// perform a couple of Jacobi iterations\n\tfor (int k=0; k<20; ++k)\n\t{\n\t  // add correction: solve with diagonal and set residual to zero\n\t  for (typename NodeSet::const_iterator i=nodesOnLevel[0].begin(); i!=nodesOnLevel[0].end(); ++i)\n\t  {\n\t    at_c<0>(dv.data)[*i] = at_c<0>(r.data)[*i]; \n\t    at_c<0>(v.data)[*i] += at_c<0>(dv.data)[*i] / a; \n\t  }\n\t  \n\t  // update the residual. We are geometry agnostic here and use a rough approximation of the Laplacian: On each\n\t  // coarse grid element we assume we have the following element matrices in 1D, 2D, 3D, respectively:\n\t  // [ 1 -1 ]       [ 2 -1 -1 ]        [  3 -1 -1 -1 ]\n\t  // [ -1 1 ], 1/12 [-1  2 -1 ], 1/60  [ -1  3 -1 -1 ]\n\t  //                [-1 -1  2 ]        [ -1 -1  3 -1 ]\n\t  //                                   [ -1 -1 -1  3 ]\n\t  // Obviously, the matrixes are just  s*(-e*e^T + (d+1)*I), where e is the vector with all entries zero. In order\n\t  // to have an invertible matrix, we add a little bit more of the identity, i.e. we end up with element matrices\n\t  // s*(-e*e^T + (d+1.1)*I) with s=1, 1/12, 1/60 for d=1,2,3, respectively. In this form, multiplication with the\n\t  // total stiffness matrix is just summing up the contributions of the elemental matrices that can efficiently\n\t  // been computed.\n\t  typename Dune::Preconditioner<Domain,Range>::field_type s = dim==1? 1.0: dim==2? 1/12.0 : 1/60.0;\n\t  for (int i=0; i<coarseElement.size(); ++i) \n\t  {\n\t    //typename Domain::block_type eTdv = 0;\n\t    double eTdv = 0;\n\t    for (int m=0; m<=dim; ++m)\n\t      eTdv += at_c<0>(dv.data)[coarseElement[i][m]];\n\t    for (int m=0; m<=dim; ++m)\n\t      at_c<0>(r.data)[coarseElement[i][m]] -= a*s*(-eTdv+(dim+1.1)*at_c<0>(dv.data)[coarseElement[i][m]]);\n\t  }\n\t}\n      }\n  };\n  \n}\n\n#endif\n", "meta": {"hexsha": "83ed3f41af25dc50605bf516f6dde3d293e0995d", "size": 12676, "ext": "hh", "lang": "C++", "max_stars_repo_path": "Kaskade/mg/hb.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/mg/hb.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/mg/hb.hh", "max_forks_repo_name": "chenzongxiong/streambox", "max_forks_repo_head_hexsha": "76f95780d1bf6c02731e39d8ac73937cea352b95", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-12-03T04:41:18.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-11T21:44:42.000Z", "avg_line_length": 42.9694915254, "max_line_length": 134, "alphanum_fraction": 0.6244872199, "num_tokens": 3401, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6113819874558604, "lm_q2_score": 0.5583269943353744, "lm_q1q2_score": 0.34135106744701804}}
{"text": "#include <iostream>\r\n#include <cstdio>\r\n#include <algorithm>\r\n#include <boost/graph/adjacency_list.hpp>\r\n#include <boost/graph/dijkstra_shortest_paths.hpp>\r\n#include <boost/graph/connected_components.hpp>\r\n// #include <boost/unordered_set.hpp>\r\n#include <ctime>\r\n#include <stack>\r\n#include <queue>\r\n#include <fstream>\r\n// #include <boost/range/algorithm/set_algorithm.hpp>\r\n#include <boost/functional/hash.hpp>\r\n#include <random>\r\n#include <unordered_set>\r\n#include <unordered_map>\r\n// using namespace std;\r\nusing namespace boost;\r\n\r\ntypedef std::vector < std::vector <int> > vvi;\r\n\r\ntypedef adjacency_list< listS, vecS, undirectedS, no_property, property<edge_weight_t, float> > Graph;\r\n// typedef adjacency_list< listS,vecS, undirectedS > Graph;\r\ntypedef graph_traits < Graph> ::vertex_descriptor vertex_descriptor;\r\ntypedef graph_traits < Graph> ::edge_descriptor edge_descriptor;\r\ntypedef Graph::vertex_iterator vertex_iterator;\r\ntypedef Graph::edge_iterator edge_iterator;\r\ntypedef std::pair <int, int> Edge;\r\ntypedef graph_traits < Graph> ::adjacency_iterator my_adjacency_iterator;\r\nproperty_map<Graph, edge_weight_t>::type weight;\r\n\r\n\r\nstd::unordered_set<int> union_(std::unordered_set<int> &set1, std::unordered_set<int> &set2)\r\n{\r\n\t// returns the union of two unordered sets of integers\r\n\tstd::unordered_set<int> new_set = set1;\r\n\r\n\tfor(auto thing : set2)\r\n\t\tnew_set.insert(thing);\r\n\treturn new_set;\r\n}\r\n\r\nstd::vector< std::vector <int> > sample(std::vector <int> &things, int &k)\r\n{\r\n\t// Returns the set of sampled nodes needed for the whole process of spanner construction as vector of integer vectors \r\n\tstd::vector< std::vector<int> > master_v;\r\n\tstd::vector<int> v = things;\r\n\r\n\tint i = 1, n = v.size(), s;\r\n\tfloat f;\r\n\r\n\tstd::vector<int> counts;\r\n\r\n\tfor(i = 1; i < k; i ++)\r\n\t{\r\n\t\tf = i / (float) k;\r\n\t\ts = ceil(pow(n, 1 - f));\r\n\t\tcounts.push_back(s);\r\n\t}\r\n\r\n\tmaster_v.push_back(v);\r\n\r\n\tstd::default_random_engine engine(std::random_device {}());\r\n\tstd::shuffle(master_v[0].begin(), master_v[0].end(), engine);\r\n\r\n\tfor(i = 1; i < k; i ++)\r\n\t{\r\n\t\tstd::vector<int> temp;\r\n\t\tfor(int j = 0; j < counts[i - 1]; j ++)\r\n\t\t\ttemp.push_back(master_v[i - 1][j]);\r\n\t\tstd::shuffle(temp.begin(), temp.end(), engine);\r\n\t\tmaster_v.push_back(temp);\r\n\t}\r\n\treturn master_v;\r\n}\r\n\r\n\r\ntuple<Graph, Graph, Graph> read_graphs(std::string filename)\r\n{\r\n\t// Reads the graphs from the edgelist. At first, the graphs G, G_comm and G_prime are all the same\r\n\tstd::ifstream fp(filename);\r\n\tGraph G, G_comm, G_prime;\r\n\tint u, v;\r\n\tfloat w;\r\n\r\n\twhile(fp >> u >> v >> w)\r\n\t{\r\n\t\tadd_edge(u, v, w, G);\r\n\t\tadd_edge(u, v, w, G_comm);\r\n\t\tadd_edge(u, v, w, G_prime);\r\n\t}\r\n\tfp.close();\r\n\treturn make_tuple(G, G_comm, G_prime);\r\n}\r\n\r\nGraph make_spanner(std::string filename, int k)\r\n{\r\n\t// constructs the (2k - 1)-spanner using Baswana and Sen's randomized algorithm \r\n\tGraph G, G_comm, G_prime;\r\n\tGraph G_spanner;\r\n\r\n\ttie(G, G_comm, G_prime) = read_graphs(filename);\r\n\r\n\tstd::unordered_set <std::pair<int, int>, hash< std::pair<int, int> > > old_Ei;\r\n\tstd::unordered_set <std::pair<int, int>, hash< std::pair<int, int> > > new_Ei;\r\n\r\n\tstd::unordered_set <int> v_prime_flag;\r\n\tstd::unordered_map <int, int> membership_oldc;\r\n\tstd::unordered_map <int, int> membership_newc;\r\n\tstd::unordered_map <int, int> neighborhood;\r\n\r\n\tstd::unordered_map <int, std::unordered_set <int> > old_c;\r\n\r\n\tstd::pair <vertex_iterator, vertex_iterator> vp;\r\n\r\n\tstd::vector <int> all_nodes;\r\n\r\n\tfor(vp = vertices(G); vp.first != vp.second; ++vp.first) // iterating over all the nodes\r\n\t{\r\n\t\tauto node = *vp.first;\r\n\t\told_c[node].insert(node);\r\n\t\tv_prime_flag.insert(node);\r\n\t\tmembership_oldc[node] = node;\r\n\t\tmembership_newc[node] = -1;\r\n\t\tall_nodes.push_back(node);\r\n\t}\r\n\r\n\tmy_adjacency_iterator start, end;\r\n\r\n\tstd::vector < std::vector<int> > R_vector; //this stores all the randomly sampled cluster heads for all iterations\r\n\r\n\tR_vector = sample(all_nodes, k); // R_vector stores the set of sampled nodes required at each iteration\r\n\r\n\tfor(int i = 1; i < k; i ++)\r\n\t{\r\n\t\t/*****1. Forming a sample of clusters **********************/\r\n\r\n\t\tstd::unordered_set<int> R_i(R_vector[i].begin(), R_vector[i].end()); // R_vector[i] gives the randomly picked cluster heads for ith iteration\r\n\t\tstd::unordered_map <int, std::unordered_set <int> > new_c;\r\n\r\n\t\tfor(auto item : old_c)\r\n\t\t{\r\n\t\t\tint v = item.first;\r\n\r\n\t\t\tif(R_i.find(v) != R_i.end())\r\n\t\t\t\tnew_c[v] = old_c[v];\r\n\t\t}\r\n\r\n\t\tstd::unordered_set <int> sampled_nodes;\r\n\r\n\t\tfor(auto v : R_i)\r\n\t\t\tsampled_nodes = union_(sampled_nodes, old_c[v]);\r\n\r\n\t\tstd::unordered_set <int> unsampled_nodes;\r\n\r\n\r\n\t\tfor(vp = vertices(G_prime); vp.first != vp.second; ++vp.first)\r\n\t\t{\r\n\t\t\tint node = *(vp.first);\r\n\t\t\tif(sampled_nodes.find(node) == sampled_nodes.end())\r\n\t\t\t\tunsampled_nodes.insert(node);\r\n\t\t}\r\n\r\n\t\tneighborhood.clear();\r\n\t\tfor(auto node : unsampled_nodes)\r\n\t\t\tneighborhood[node] = -1;\r\n\r\n\t\tif(i == 1)\r\n\t\t\tfor(auto v : R_i)\r\n\t\t\t\tmembership_newc[v] = v;\r\n\r\n\t\telse\r\n\t\t{\r\n\t\t\tstd::pair <vertex_iterator, vertex_iterator> vp;\r\n\t\t\tfor(vp = vertices(G_prime); vp.first != vp.second; ++ vp.first)\r\n\t\t\t{\r\n\t\t\t\tauto v = *(vp.first);\r\n\t\t\t\tif(membership_newc[v] != -1)\r\n\t\t\t\t\tif(R_i.find(membership_newc[v]) == R_i.end())\r\n\t\t\t\t\t\tmembership_newc[v] = -1;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tnew_Ei = old_Ei;\r\n\t\tint u, v;\r\n\r\n\t\tfor(auto edge : old_Ei)\r\n\t\t{\r\n\t\t\ttie(u, v) = edge;\r\n\t\t\tif(R_i.find(membership_newc[u]) == R_i.end() || R_i.find(membership_newc[v]) == R_i.end())\r\n\t\t\t{\r\n\t\t\t\tstd::pair<int, int> e = std::make_pair(u, v);\r\n\t\t\t\tnew_Ei.erase(e);\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\t/***********************end of step 1**************************/\r\n\r\n\t\t/********2. finding nearest neighboring sampled cluster*********/\r\n\r\n\t\tfor(int v : unsampled_nodes)\r\n\t\t{\r\n\t\t\tif(v_prime_flag.find(v) == v_prime_flag.end()) // if v is not in G_prime, we don't consider it\r\n\t\t\t\tcontinue;\r\n\r\n\t\t\tstd::unordered_map <int, std::pair<float, int> > min_table;\r\n\t\t\tedge_descriptor e;\r\n\t\t\tvertex_descriptor src, dest;\r\n\r\n\t\t\tfor(std::tie(start, end) = adjacent_vertices(v, G_prime); start != end; ++ start)\r\n\t\t\t{\r\n\t\t\t\tint neighbor = *start;\r\n\t\t\t\tfloat wt;\r\n\t\t\t\tsrc = vertex(v, G);\r\n\t\t\t\tdest = vertex(neighbor, G);\r\n\r\n\t\t\t\tstd::tie(e, std::ignore) = edge(src, dest, G);\r\n\r\n\t\t\t\twt = get(weight, e);\r\n\r\n\t\t\t\tif(membership_newc[neighbor] != -1) // checking if the neighbor is sampled\r\n\t\t\t\t{\r\n\t\t\t\t\tif(min_table.find(membership_newc[neighbor]) == min_table.end())\r\n\t\t\t\t\t\tmin_table[membership_newc[neighbor]] = std::make_pair(wt, neighbor);\r\n\r\n\r\n\t\t\t\t\telse if(wt < min_table[membership_newc[neighbor]].first)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tmin_table[membership_newc[neighbor]].first = wt;\r\n\t\t\t\t\t\tmin_table[membership_newc[neighbor]].second = neighbor;\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\tfloat min_ = INT_MAX;\r\n\t\t\tint nearest_neighbor = -1;\r\n\r\n\t\t\tfor(auto item : min_table)\r\n\t\t\t{\r\n\t\t\t\tif(item.second.first  < min_)\r\n\t\t\t\t{\r\n\t\t\t\t\tmin_ = item.second.first;\r\n\t\t\t\t\tnearest_neighbor = item.second.second;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\tneighborhood[v] = nearest_neighbor;\r\n\t\t}\r\n\r\n\t\t/************end of step 2 ********************************/\r\n\r\n\r\n\t\t/* **********3. adding edges to spanner ******************/\r\n\r\n\t\tfor(int v : unsampled_nodes)\r\n\t\t{\r\n\t\t\tif(v_prime_flag.find(v) == v_prime_flag.end())\r\n\t\t\t\tcontinue;\r\n\r\n\t\t\tif(neighborhood[v] == -1) //v is not adjacent to any sampled nodes\r\n\t\t\t{\r\n\t\t\t\tstd::unordered_map <int, std::pair<float, int> > min_table;\r\n\r\n\t\t\t\tedge_descriptor e;\r\n\t\t\t\tvertex_descriptor src, dest;\r\n\t\t\t\tstd::vector <std::pair<int, int> > edges_to_be_removed;\r\n\t\t\t\tmy_adjacency_iterator start, end;\r\n\r\n\r\n\t\t\t\tfor(std::tie(start, end) = adjacent_vertices(v, G_prime); start != end; ++ start)\r\n\t\t\t\t{\r\n\t\t\t\t\tint neighbor = *start;\r\n\t\t\t\t\tfloat wt;\r\n\r\n\t\t\t\t\tsrc = vertex(v, G);\r\n\t\t\t\t\tdest = vertex(neighbor, G);\r\n\r\n\t\t\t\t\tstd::tie(e, std::ignore) = edge(src, dest, G);\r\n\r\n\t\t\t\t\twt = get(weight, e);\r\n\r\n\t\t\t\t\tif(membership_oldc[neighbor] != -1)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tif(min_table.find(neighbor) == min_table.end())\r\n\t\t\t\t\t\t\tmin_table[neighbor] = std::make_pair(wt, neighbor);\r\n\r\n\t\t\t\t\t\tif(wt <= min_table[neighbor].first)\r\n\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\tmin_table[neighbor].first = wt;\r\n\t\t\t\t\t\t\tmin_table[neighbor].second = neighbor;\r\n\r\n\t\t\t\t\t\t\tedges_to_be_removed.push_back(std::make_pair(v, neighbor));\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\tfor(auto edge : edges_to_be_removed)\r\n\t\t\t\t\tremove_edge(edge.first, edge.second, G_prime);\r\n\r\n\t\t\t\tfor(auto item : min_table)\r\n\t\t\t\t{\r\n\t\t\t\t\tadd_edge(v, item.second.second, item.second.first, G_spanner);\r\n\t\t\t\t\tremove_edge(v, item.second.second, G_comm);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\r\n\t\t\telse\r\n\t\t\t{\r\n\t\t\t\tmy_adjacency_iterator start, end;\r\n\t\t\t\tfloat wt;\r\n\r\n\t\t\t\tedge_descriptor e;\r\n\t\t\t\tstd::tie(e, std::ignore) = edge(v, neighborhood[v], G);\r\n\t\t\t\twt = get(weight, e);\r\n\r\n\t\t\t\tadd_edge(v, neighborhood[v], wt, G_spanner);\r\n\t\t\t\tremove_edge(v, neighborhood[v], G_comm);\r\n\r\n\t\t\t\tnew_Ei.insert(std::make_pair(v, neighborhood[v]));\r\n\r\n\t\t\t\tstd::vector <int> neighbors;\r\n\t\t\t\tfor(std::tie(start, end) = adjacent_vertices(v, G_prime); start != end; ++ start)\r\n\t\t\t\t{\r\n\t\t\t\t\tint neighbor = *start;\r\n\t\t\t\t\tneighbors.push_back(neighbor);\r\n\t\t\t\t}\r\n\r\n\t\t\t\tfor(auto neighbor : neighbors)\r\n\t\t\t\t{\r\n\t\t\t\t\tif(membership_newc[neighbor] == membership_newc[neighborhood[v]])\r\n\t\t\t\t\t\tremove_edge(v, neighbor, G_prime);\r\n\t\t\t\t}\r\n\r\n\t\t\t\tstd::unordered_map <int, std::pair<float, int> > min_table;\r\n\t\t\t\tedge_descriptor e1;\r\n\t\t\t\tvertex_descriptor src, dest;\r\n\r\n\t\t\t\tfor(auto neighbor : neighbors)\r\n\t\t\t\t{\r\n\t\t\t\t\tfloat wt1, wt2;\r\n\t\t\t\t\tsrc = vertex(v, G);\r\n\t\t\t\t\tdest = vertex(neighbor, G);\r\n\r\n\t\t\t\t\tstd::tie(e1, std::ignore) = edge(src, dest, G);\r\n\t\t\t\t\twt1 = get(weight, e1);\r\n\r\n\t\t\t\t\tdest = vertex(neighborhood[v], G);\r\n\t\t\t\t\tstd::tie(e1, std::ignore) = edge(src, dest, G);\r\n\t\t\t\t\twt2 = get(weight, e1);\r\n\r\n\t\t\t\t\tif(wt1 < wt2)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tif(min_table.find(membership_oldc[neighbor]) == min_table.end())\r\n\t\t\t\t\t\t\tmin_table[membership_oldc[neighbor]] = std::make_pair(wt1, neighbor);\r\n\r\n\t\t\t\t\t\telse if(wt1 < min_table[membership_oldc[neighbor]].first)\r\n\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\tmin_table[membership_oldc[neighbor]].first = wt2;\r\n\t\t\t\t\t\t\tmin_table[membership_oldc[neighbor]].second = neighbor;\r\n\t\t\t\t\t\t\tremove_edge(v, neighbor, G_prime);\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\tfor(auto item : min_table)\r\n\t\t\t\t{\r\n\t\t\t\t\tadd_edge(v, item.second.second, item.second.first, G_spanner);\r\n\t\t\t\t\tremove_edge(v, item.second.second, G_comm);\r\n\t\t\t\t\tremove_edge(v, item.second.second, G_prime);\r\n\t\t\t\t}\r\n\r\n\r\n\t\t\t}\r\n\r\n\t\t}\r\n\r\n\r\n\t\t/************end of step 3*****************************************/\r\n\r\n\r\n\t\t/******4. removing intra cluster edges ***********************/\r\n\r\n\t\tstd::vector< std::pair <int, int> > intracluster_edges;\r\n\r\n\t\tfor(auto item : new_Ei)\r\n\t\t{\r\n\t\t\tint u = item.first;\r\n\t\t\tint v = item.second;\r\n\r\n\t\t\tif(membership_newc[u] != -1)\r\n\t\t\t{\r\n\t\t\t\tmembership_newc[v] = membership_newc[u];\r\n\t\t\t\tnew_c[membership_newc[u]].insert(v);\r\n\t\t\t}\r\n\r\n\t\t\telse if(membership_newc[v] != -1)\r\n\t\t\t{\r\n\t\t\t\tmembership_newc[u] = membership_newc[v];\r\n\t\t\t\tnew_c[membership_newc[v]].insert(u);\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tedge_iterator e_start, e_end;\r\n\r\n\t\tfor(std::tie(e_start, e_end) = edges(G_prime); e_start != e_end; ++ e_start)\r\n\t\t{\r\n\t\t\tint u = source(*e_start, G_prime), v = target(*e_start, G_prime);\r\n\r\n\t\t\tif(membership_newc[u] == membership_newc[v])\r\n\t\t\t\tintracluster_edges.push_back(std::make_pair(u, v));\r\n\t\t}\r\n\r\n\r\n\r\n\t\tfor(auto edge : intracluster_edges)\r\n\t\t{\r\n\t\t\t// // std:: cout << \"\\n(\" << edge.first << \", \" << edge.second << \")\";\r\n\t\t\tremove_edge(edge.first, edge.second, G_prime);\r\n\t\t}\r\n\r\n\t\t/*************end of step 4*************************************************/\r\n\r\n\t\t/**** updations needed at the end of iteration******************************/\r\n\r\n\t\tv_prime_flag.clear();\r\n\r\n\t\tint count = 0;\r\n\t\t// // std:: cout << \"E_prime: \\n\";\r\n\t\tfor(std::tie(e_start, e_end) = edges(G_prime); e_start != e_end; ++ e_start)\r\n\t\t{\r\n\t\t\tint u = source(*e_start, G_prime), v = target(*e_start, G_prime);\r\n\t\t\tv_prime_flag.insert(u);\r\n\t\t\tv_prime_flag.insert(v);\r\n\t\t\tcount ++;\r\n\t\t}\r\n\r\n\t\tfor(auto item : new_Ei)\r\n\t\t{\r\n\t\t\tv_prime_flag.insert(item.first);\r\n\t\t\tv_prime_flag.insert(item.second);\r\n\t\t}\r\n\r\n\t\told_c = new_c;\r\n\t\tmembership_oldc = membership_newc;\r\n\r\n\t\t/***********The end of iteration i *****************************/\r\n\t}\r\n\r\n\t/******* Phase 2 **************************/\r\n\r\n\tvertex_iterator v_start, v_end;\r\n\r\n\tfor(std::tie(v_start, v_end) = vertices(G_prime); v_start != v_end; ++ v_start)\r\n\t{\r\n\t\tint v = *v_start;\r\n\t\tif(v_prime_flag.find(v) == v_prime_flag.end())\r\n\t\t\tcontinue;\r\n\r\n\t\tstd::unordered_map <int, std::pair<float, int> > min_table;\r\n\t\tedge_descriptor e;\r\n\t\tvertex_descriptor src, dest;\r\n\r\n\t\tstd::vector <std::pair<int, int> > edges_to_be_removed;\r\n\r\n\r\n\t\tfor(std::tie(start, end) = adjacent_vertices(v, G_prime); start != end; ++ start)\r\n\t\t{\r\n\t\t\tint neighbor = *start;\r\n\t\t\tfloat wt;\r\n\t\t\tsrc = vertex(v, G);\r\n\t\t\tdest = vertex(neighbor, G);\r\n\r\n\t\t\tstd::tie(e, std::ignore) = edge(src, dest, G);\r\n\r\n\t\t\twt = get(weight, e);\r\n\r\n\t\t\tif(membership_newc[neighbor] == -1)\r\n\t\t\t\tcontinue;\r\n\r\n\t\t\tif(min_table.find(membership_newc[neighbor]) == min_table.end())\r\n\t\t\t\tmin_table[membership_newc[neighbor]] = std::make_pair(wt, neighbor);\r\n\r\n\t\t\tif(wt <= min_table[membership_newc[neighbor]].first)\r\n\t\t\t{\r\n\t\t\t\tmin_table[membership_newc[neighbor]].first = wt;\r\n\t\t\t\tmin_table[membership_newc[neighbor]].second = neighbor;\r\n\r\n\t\t\t\tedges_to_be_removed.push_back(std::make_pair(v, neighbor));\r\n\t\t\t}\r\n\r\n\t\t\tif(min_table.find(membership_newc[neighbor]) == min_table.end())\r\n\t\t\t\tedges_to_be_removed.push_back(std::make_pair(v, neighbor));\r\n\t\t}\r\n\r\n\t\tfor(auto edge : edges_to_be_removed)\r\n\t\t\tremove_edge(edge.first, edge.second, G_prime);\r\n\r\n\t\tfor(auto item : min_table)\r\n\t\t{\r\n\t\t\tadd_edge(v, item.second.second, item.second.first, G_spanner);\r\n\t\t\tremove_edge(v, item.second.second, G_comm);\r\n\t\t}\r\n\t}\r\n\treturn G_comm;\r\n}\r\n\r\nfloat THRESHOLD = 0.66;\r\n\r\n\r\nstd::stack <int> Broker_Stack;\r\nstd::queue <int> Community_Queue;\r\nstd::unordered_set <int> isolated;\r\nstd::unordered_set <int> influenced;\r\nstd::unordered_map<int, int> labels;\r\nstd::unordered_set <int> traversed;\r\nstd::unordered_set <int> brokers;\r\nstd::unordered_set <int> marked;\r\nstd::unordered_map<int, float> scores;\r\n\r\n\r\nfloat INS_score(Graph &g, int node)\r\n{\r\n\tint count = 0;\r\n\tint total_count = 0;\r\n\r\n\tmy_adjacency_iterator start, end;\r\n\tvertex_descriptor v = vertex(node, g);\r\n\r\n\r\n\tfor(std::tie(start, end) = adjacent_vertices(v, g); start != end; ++ start)\r\n\t{\r\n\t\tauto neighbor = *start;\r\n\t\tif(influenced.find(neighbor) != influenced.end())\r\n\t\t\tcount += 1;\r\n\t\ttotal_count += 1;\r\n\t}\r\n\r\n\treturn count * 1.0 / total_count;\r\n}\r\n\r\n\r\nvoid INS(Graph &g, int starting_node)\r\n{\r\n\tvertex_iterator v_st, v_end;\r\n\tinfluenced.insert(starting_node);\r\n\ttraversed.insert(starting_node);\r\n\tBroker_Stack.push(starting_node);\r\n\tbrokers.insert(starting_node);\r\n\tscores[starting_node] = 0;\r\n\tlabels[starting_node] = starting_node;\r\n\r\n\r\n\tmy_adjacency_iterator start, end;\r\n\r\n\twhile(Broker_Stack.size() + Community_Queue.size() > 0)\r\n\t{\r\n\t\tint node;\r\n\t\tif(! Community_Queue.empty())\r\n\t\t{\r\n\t\t\tnode = Community_Queue.front();\r\n\t\t\tCommunity_Queue.pop();\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\tnode = Broker_Stack.top();\r\n\t\t\tBroker_Stack.pop();\r\n\t\t}\r\n\r\n\t\tisolated.erase(node);\r\n\r\n\t\tvertex_descriptor v = vertex(node, g);\r\n\r\n\t\tfor(std::tie(start, end) = adjacent_vertices(v, g); start != end; ++ start)\r\n\t\t\tinfluenced.insert(*start);\r\n\r\n\t\tfor(std::tie(start, end) = adjacent_vertices(v, g); start != end; ++ start)\r\n\t\t{\r\n\t\t\tint neighbor = *start;\r\n\r\n\t\t\tif(traversed.find(neighbor) != traversed.end())\r\n\t\t\t\tcontinue;\r\n\t\t\telse\r\n\t\t\t{\r\n\t\t\t\ttraversed.insert(neighbor);\r\n\t\t\t}\r\n\r\n\t\t\tauto score = INS_score(g, neighbor);\r\n\t\t\t// std:: cout << \"node: \" << neighbor << \" score: \" << score << std:: endl;\r\n\t\t\tscores[neighbor] = score;\r\n\r\n\t\t\tif(score < THRESHOLD) //broker \r\n\t\t\t{\r\n\t\t\t\tlabels[neighbor] = neighbor;\r\n\t\t\t\tBroker_Stack.push(neighbor);\r\n\t\t\t\tbrokers.insert(neighbor);\r\n\t\t\t}\r\n\r\n\t\t\telse\r\n\t\t\t{\r\n\t\t\t\tif(marked.find(neighbor) == marked.end())\r\n\t\t\t\t{\r\n\t\t\t\t\tlabels[neighbor] = labels[node];\r\n\t\t\t\t\tmarked.insert(neighbor);\r\n\t\t\t\t}\r\n\r\n\t\t\t\tisolated.erase(neighbor);\r\n\t\t\t\tif(score != 1)\r\n\t\t\t\t\tCommunity_Queue.push(neighbor);\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n}\r\n\r\n\r\nvoid run_INS(Graph &G, std::string filename)\r\n{\r\n\tfor(unsigned int i = 0; i < num_vertices(G); i ++)\r\n\t\tisolated.insert(i);\r\n\r\n\tstd::vector<int> component(num_vertices(G));\r\n\tint num = connected_components(G, &component[0]);\r\n\r\n\tvvi comp_lst(num);\r\n\tfor(unsigned int i = 0; i != component.size(); ++i)\r\n\t\tcomp_lst[component[i]].push_back(i);\r\n\r\n\tstd::vector <int> starting_nodes;\r\n\tint min_deg = INT_MAX;\r\n\tint starting_node, deg;\r\n\r\n\tfor(int i = 0; i < num; i ++)\r\n\t{\r\n\t\tstarting_node = -1;\r\n\t\tmin_deg = INT_MAX;\r\n\t\tfor(auto node : comp_lst[i])\r\n\t\t{\r\n\t\t\tvertex_descriptor v = vertex(node, G);\r\n\t\t\tdeg = degree(v, G);\r\n\t\t\tif(deg == 1)\r\n\t\t\t{\r\n\t\t\t\tstarting_node = node;\r\n\t\t\t\tmin_deg = deg;\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t\telse if(deg < min_deg)\r\n\t\t\t{\r\n\t\t\t\tstarting_node = node;\r\n\t\t\t\tmin_deg = deg;\r\n\t\t\t}\r\n\t\t}\r\n\t\tstarting_nodes.push_back(starting_node);\r\n\t}\r\n\r\n\tfor(auto start_node : starting_nodes)\r\n\t\tINS(G, start_node);\r\n\r\n\tstd::string st = filename;\r\n\tstd::ofstream fout(st + \"_cover.part\");\r\n\r\n\tfor(auto it = labels.begin(); it != labels.end(); ++ it)\r\n\t{\r\n\t\tfout << it->first << \" \" << it->second << std::endl;\r\n\t}\r\n\t\r\n\tfor(auto thing : isolated)\r\n\t{\r\n\t\tfout << thing << \" \" << thing << std::endl;\r\n\t}\r\n\tfout.close();\r\n\r\n}\r\n\r\n\r\n\r\n\r\nint main(int argc, char const *argv[])\r\n{\r\n\tif(argc < 3)\r\n\t{\r\n\t\tstd::cout << \"Enter filename and k\";\r\n\t\treturn 0;\r\n\t}\r\n\tGraph G_comm;\r\n\tG_comm = make_spanner(argv[1], std::stoi(argv[2]));\r\n\t\r\n\trun_INS(G_comm, argv[1]);\r\n\treturn 0;\r\n}\r\n", "meta": {"hexsha": "f45a1057e8ab085099ca29c7c07898fcc44ea59c", "size": 17457, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "final_cpp_version.cpp", "max_stars_repo_name": "satyakisikdar/spanner-comm-detection", "max_stars_repo_head_hexsha": "96498baabd2fc9701e7c9323c9cf323c055b4cef", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-03-20T02:06:00.000Z", "max_stars_repo_stars_event_max_datetime": "2018-03-20T02:06:00.000Z", "max_issues_repo_path": "final_cpp_version.cpp", "max_issues_repo_name": "satyakisikdar/spanner-comm-detection", "max_issues_repo_head_hexsha": "96498baabd2fc9701e7c9323c9cf323c055b4cef", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "final_cpp_version.cpp", "max_forks_repo_name": "satyakisikdar/spanner-comm-detection", "max_forks_repo_head_hexsha": "96498baabd2fc9701e7c9323c9cf323c055b4cef", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2018-11-15T14:01:45.000Z", "max_forks_repo_forks_event_max_datetime": "2019-07-27T05:12:52.000Z", "avg_line_length": 25.3, "max_line_length": 144, "alphanum_fraction": 0.6082946669, "num_tokens": 4820, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6113819732941511, "lm_q2_score": 0.5583269943353745, "lm_q1q2_score": 0.3413510595401536}}
{"text": "/*\n * WaveEquationBase.cpp\n *\n *  Created on: 23.07.2017\n *      Author: thies\n */\n\n#include <deal.II/lac/precondition.h>\n#include <deal.II/lac/solver_cg.h>\n#include <deal.II/lac/solver_control.h>\n#include <deal.II/numerics/matrix_tools.h>\n#include <forward/MatrixCreator.h>\n#include <forward/WaveEquationBase.h>\n\nnamespace wavepi {\nnamespace forward {\n\nusing namespace dealii;\nusing namespace wavepi::base;\n\ntemplate <int dim>\nvoid WaveEquationBase<dim>::fill_matrices(std::shared_ptr<SpaceTimeMesh<dim>> mesh, size_t time_idx,\n                                          SparseMatrix<double> &dst_A, SparseMatrix<double> &dst_B,\n                                          SparseMatrix<double> &dst_C) {\n  //   const double time = mesh->get_time(time_idx);\n\n  // this helps only a bit because each of the operations is already parallelized\n  // tests show about 20%-30% (depending on dim) speedup on my Intel i5 4690\n  // this assembling could be done even more efficient, by looping through the mesh once and assembling all matrices.\n\n  //   Threads::TaskGroup<void> task_group;\n\n  if (!rho_time_dependent || time_idx == mesh->length() - 1) {\n    //      task_group += Threads::new_task(&WaveEquationBase<dim>::fill_A, *this, mesh, time_idx, dst_A);\n    //      task_group += Threads::new_task(&WaveEquationBase<dim>::fill_B, *this, mesh, time_idx, dst_B);\n    //      task_group += Threads::new_task(&WaveEquationBase<dim>::fill_C, *this, mesh, time_idx, dst_C);\n\n    this->fill_A(mesh, time_idx, dst_A);\n    this->fill_B(mesh, time_idx, dst_B);\n    this->fill_C(mesh, time_idx, dst_C);\n\n    matrix_C_intermediate.clear();\n    matrix_D_intermediate.clear();\n  } else {\n    // possible here because fill_*_intermediate can access different time steps of ρ in parallel\n    // (ρ is discretized and this is exploited by assembly tasks)\n\n    //      task_group += Threads::new_task(&WaveEquationBase<dim>::fill_A, *this, mesh, time_idx, dst_A);\n    //      task_group += Threads::new_task(&WaveEquationBase<dim>::fill_B, *this, mesh, time_idx, dst_B);\n    //      task_group += Threads::new_task(&WaveEquationBase<dim>::fill_C, *this, mesh, time_idx, dst_C);\n\n    this->fill_A(mesh, time_idx, dst_A);\n    this->fill_B(mesh, time_idx, dst_B);\n    this->fill_C(mesh, time_idx, dst_C);\n\n    //      task_group += Threads::new_task(&WaveEquationBase<dim>::fill_C_intermediate, *this, mesh, time_idx);\n    //      task_group += Threads::new_task(&WaveEquationBase<dim>::fill_D_intermediate, *this, mesh, time_idx);\n\n    this->fill_C_intermediate(mesh, time_idx);\n    this->fill_D_intermediate(mesh, time_idx);\n  }\n\n  //   task_group.join_all();\n}\n\n// let dst <- (D^n)^{-1} D^{n-1} M^{-1} src\n// ( i.e. dst <- src for time-independent D)\ntemplate <int dim>\nvoid WaveEquationBase<dim>::vmult_D_intermediate(const SparseMatrix<double> &mass_matrix, Vector<double> &dst,\n                                                 const Vector<double> &src, double tolerance) const {\n  if (rho_time_dependent) {\n    Vector<double> tmp(src.size());\n\n    SolverControl solver_control(2000, tolerance * src.l2_norm());\n    SolverCG<> cg(solver_control);\n\n    // PreconditionIdentity precondition = PreconditionIdentity();\n    PreconditionSSOR<SparseMatrix<double>> precondition;\n    precondition.initialize(mass_matrix, PreconditionSSOR<SparseMatrix<double>>::AdditionalData(1.0));\n\n    cg.solve(mass_matrix, tmp, src, precondition);\n\n    AssertThrow(matrix_D_intermediate.n() > 0, ExcInternalError(\"matrix_D_intermediate is missing\"));\n    matrix_D_intermediate.vmult(dst, tmp);\n  } else {\n    dst.equ(1.0, src);\n  }\n}\n\n// let dst <- M^{-1} (D^n)^{-1} D^{n-1} src\n// ( i.e. dst <- src for time-independent D)\ntemplate <int dim>\nvoid WaveEquationBase<dim>::vmult_D_intermediate_transpose(const SparseMatrix<double> &mass_matrix, Vector<double> &dst,\n                                                           const Vector<double> &src, double tolerance) const {\n  if (rho_time_dependent) {\n    Vector<double> tmp(src.size());\n\n    AssertThrow(matrix_D_intermediate.n() > 0, ExcInternalError(\"matrix_D_intermediate is missing\"));\n    matrix_D_intermediate.vmult(tmp, src);\n\n    SolverControl solver_control(2000, tolerance * tmp.l2_norm());\n    SolverCG<> cg(solver_control);\n  \n    // PreconditionIdentity precondition = PreconditionIdentity();\n    PreconditionSSOR<SparseMatrix<double>> precondition;\n    precondition.initialize(mass_matrix, PreconditionSSOR<SparseMatrix<double>>::AdditionalData(1.0));\n\n    cg.solve(mass_matrix, dst, tmp, precondition);\n  } else {\n    dst.equ(1.0, src);\n  }\n}\n\n// before mesh change, let dst <- (D^n)^{-1} C^{n-1} src\n// ( i.e. dst <- matrix_C * src for time-independent D)\ntemplate <int dim>\nvoid WaveEquationBase<dim>::vmult_C_intermediate(const SparseMatrix<double> &matrix_C, Vector<double> &dst,\n                                                 const Vector<double> &src) const {\n  if (rho_time_dependent) {\n    AssertThrow(matrix_C_intermediate.n() > 0, ExcInternalError(\"matrix_C_intermediate is missing\"));\n    matrix_C_intermediate.vmult(dst, src);\n  } else {\n    matrix_C.vmult(dst, src);\n  }\n}\n\ntemplate <int dim>\nvoid WaveEquationBase<dim>::fill_A(std::shared_ptr<SpaceTimeMesh<dim>> mesh, size_t time_idx,\n                                   SparseMatrix<double> &destination) {\n  const double time = mesh->get_time(time_idx);\n  auto dof_handler  = mesh->get_dof_handler(time_idx);\n\n  if ((!param_rho_disc && !param_q_disc) || !using_special_assembly(mesh))\n    MatrixCreator<dim>::create_A_matrix(dof_handler, mesh->get_quadrature(), destination, param_rho, param_q, time);\n  else if (param_rho_disc && !param_q_disc)\n    MatrixCreator<dim>::create_A_matrix(dof_handler, mesh->get_quadrature(), destination,\n                                        param_rho_disc->get_function_coefficients_by_time(time), param_q, time);\n  else if (!param_rho_disc && param_q_disc)\n    MatrixCreator<dim>::create_A_matrix(dof_handler, mesh->get_quadrature(), destination, param_rho,\n                                        param_q_disc->get_function_coefficients_by_time(time), time);\n  else\n    // (param_rho_disc && param_q_disc)\n    MatrixCreator<dim>::create_A_matrix(dof_handler, mesh->get_quadrature(), destination,\n                                        param_rho_disc->get_function_coefficients_by_time(time),\n                                        param_q_disc->get_function_coefficients_by_time(time));\n}\n\ntemplate <int dim>\nvoid WaveEquationBase<dim>::fill_B(std::shared_ptr<SpaceTimeMesh<dim>> mesh, size_t time_idx,\n                                   SparseMatrix<double> &destination) {\n  const double time = mesh->get_time(time_idx);\n  auto dof_handler  = mesh->get_dof_handler(time_idx);\n\n  if (param_nu_disc && using_special_assembly(mesh))\n    MatrixCreator<dim>::create_mass_matrix(dof_handler, mesh->get_quadrature(), destination,\n                                           param_nu_disc->get_function_coefficients_by_time(time));\n  else\n    MatrixCreator<dim>::create_mass_matrix(dof_handler, mesh->get_quadrature(), destination, param_nu, time);\n}\n\ntemplate <int dim>\nvoid WaveEquationBase<dim>::fill_C(std::shared_ptr<SpaceTimeMesh<dim>> mesh, size_t time_idx,\n                                   SparseMatrix<double> &destination) {\n  const double time = mesh->get_time(time_idx);\n  auto dof_handler  = mesh->get_dof_handler(time_idx);\n\n  if ((!param_rho_disc && !param_c_disc) || !using_special_assembly(mesh))\n    MatrixCreator<dim>::create_C_matrix(dof_handler, mesh->get_quadrature(), destination, param_rho, param_c, time,\n                                        time);\n  else if (param_rho_disc && !param_c_disc)\n    MatrixCreator<dim>::create_C_matrix(dof_handler, mesh->get_quadrature(), destination,\n                                        param_rho_disc->get_function_coefficients_by_time(time), param_c, time);\n  else if (!param_rho_disc && param_c_disc)\n    MatrixCreator<dim>::create_C_matrix(dof_handler, mesh->get_quadrature(), destination, param_rho,\n                                        param_c_disc->get_function_coefficients_by_time(time), time);\n  else\n    // (param_rho_disc && param_c_disc)\n    MatrixCreator<dim>::create_C_matrix(dof_handler, mesh->get_quadrature(), destination,\n                                        param_rho_disc->get_function_coefficients_by_time(time),\n                                        param_c_disc->get_function_coefficients_by_time(time));\n}\n\ntemplate <int dim>\nvoid WaveEquationBase<dim>::fill_C_intermediate(std::shared_ptr<SpaceTimeMesh<dim>> mesh, size_t time_idx) {\n  // fill with (D^{n+1})^{-1} C^n, n = time_idx on the mesh of time_idx\n  // -> needs to be able to change the time in ρ to the next time if continuous ρ is used\n\n  matrix_C_intermediate.reinit(*mesh->get_sparsity_pattern(time_idx));\n  double current_time = mesh->get_time(time_idx);\n  double next_time    = mesh->get_time(time_idx + 1);  // does range checking in debug mode\n  auto dof_handler    = mesh->get_dof_handler(time_idx);\n\n  if ((!param_rho_disc && !param_c_disc) || !using_special_assembly(mesh))\n    MatrixCreator<dim>::create_C_matrix(dof_handler, mesh->get_quadrature(), matrix_C_intermediate, param_rho, param_c,\n                                        next_time, current_time);\n  else if (param_rho_disc && !param_c_disc)\n    MatrixCreator<dim>::create_C_matrix(dof_handler, mesh->get_quadrature(), matrix_C_intermediate,\n                                        param_rho_disc->get_function_coefficients_by_time(next_time), param_c,\n                                        current_time);\n\n  else if (!param_rho_disc && param_c_disc)\n    MatrixCreator<dim>::create_C_matrix(dof_handler, mesh->get_quadrature(), matrix_C_intermediate, param_rho,\n                                        param_c_disc->get_function_coefficients_by_time(current_time), next_time);\n  else\n    MatrixCreator<dim>::create_C_matrix(dof_handler, mesh->get_quadrature(), matrix_C_intermediate,\n                                        param_rho_disc->get_function_coefficients_by_time(next_time),\n                                        param_c_disc->get_function_coefficients_by_time(current_time));\n}\n\ntemplate <int dim>\nvoid WaveEquationBase<dim>::fill_D_intermediate(std::shared_ptr<SpaceTimeMesh<dim>> mesh, size_t time_idx) {\n  // fill with (D^{n+1})^{-1} D^n, n = time_idx on the mesh of time_idx\n  // -> needs to be able to change the time in ρ to the next time if continuous ρ is used\n\n  matrix_D_intermediate.reinit(*mesh->get_sparsity_pattern(time_idx));\n  double current_time = mesh->get_time(time_idx);\n  double next_time    = mesh->get_time(time_idx + 1);  // does range checking in debug mode\n  auto dof_handler    = mesh->get_dof_handler(time_idx);\n\n  if (!param_rho_disc || !using_special_assembly(mesh))\n    MatrixCreator<dim>::create_D_intermediate_matrix(dof_handler, mesh->get_quadrature(), matrix_D_intermediate,\n                                                     param_rho, current_time, next_time);\n  else\n    MatrixCreator<dim>::create_D_intermediate_matrix(dof_handler, mesh->get_quadrature(), matrix_D_intermediate,\n                                                     param_rho_disc->get_function_coefficients_by_time(current_time),\n                                                     param_rho_disc->get_function_coefficients_by_time(next_time));\n}\n\ntemplate class WaveEquationBase<1>;\ntemplate class WaveEquationBase<2>;\ntemplate class WaveEquationBase<3>;\n\n} /* namespace forward */\n} /* namespace wavepi */\n", "meta": {"hexsha": "f854bb12eb8ad63c8125015075c912dae8f6e5e6", "size": 11491, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lib/forward/WaveEquationBase.cpp", "max_stars_repo_name": "thiesgerken/wavepi", "max_stars_repo_head_hexsha": "5af37946dcc1910ad1cccdc76d2e2f546eeafec4", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "lib/forward/WaveEquationBase.cpp", "max_issues_repo_name": "thiesgerken/wavepi", "max_issues_repo_head_hexsha": "5af37946dcc1910ad1cccdc76d2e2f546eeafec4", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lib/forward/WaveEquationBase.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": 48.8978723404, "max_line_length": 120, "alphanum_fraction": 0.6720041772, "num_tokens": 2706, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6619228891883802, "lm_q2_score": 0.5156199157230157, "lm_q1q2_score": 0.34130062433844766}}
{"text": "// This file is part of snark, a generic and flexible library for robotics research\n// Copyright (c) 2011 The University of Sydney\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are met:\n// 1. Redistributions of source code must retain the above copyright\n//    notice, this list of conditions and the following disclaimer.\n// 2. Redistributions in binary form must reproduce the above copyright\n//    notice, this list of conditions and the following disclaimer in the\n//    documentation and/or other materials provided with the distribution.\n// 3. Neither the name of the University of Sydney nor the\n//    names of its contributors may be used to endorse or promote products\n//    derived from this software without specific prior written permission.\n//\n// NO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE\n// GRANTED BY THIS LICENSE.  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT\n// HOLDERS AND CONTRIBUTORS \\\"AS IS\\\" AND ANY EXPRESS OR IMPLIED\n// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\n// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\n// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR\n// BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE\n// OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN\n// IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n\n#include <cmath>\n#include <boost/geometry.hpp>\n#include <boost/geometry/geometries/polygon.hpp>\n#include <boost/geometry/geometries/adapted/boost_tuple.hpp>\n#include <boost/foreach.hpp>\n#include <Eigen/Core>\n#include \"region_properties.h\"\n#include <comma/base/exception.h>\n\n#include <opencv2/imgproc/imgproc.hpp>\n#include <opencv2/highgui/highgui.hpp>\n\nBOOST_GEOMETRY_REGISTER_BOOST_TUPLE_CS( cs::cartesian )\n\nnamespace snark{ namespace imaging {\n\n/// compute the area of a polygon and its convex hull\n/// @param points polygon points\n/// @param area area of the polygon\n/// @param convexArea area of the convex hull\nvoid compute_area( const std::vector< cv::Point >& points, double& area, double& convexArea )\n{\n    boost::geometry::model::polygon< boost::tuple< double, double > > polygon;\n    for( unsigned int i = 0; i < points.size(); i++ )\n    {\n        boost::geometry::append( polygon, boost::make_tuple( points[i].x, points[i].y ) );\n    }\n    boost::geometry::append( polygon, boost::make_tuple( points[0].x, points[0].y ) ); // close polygon\n\n    area = boost::geometry::area( polygon );\n\n    boost::geometry::model::polygon< boost::tuple<double, double> > hull;\n    boost::geometry::convex_hull( polygon, hull );\n\n    convexArea = boost::geometry::area( hull );\n}\n\n/// constructor\n/// @param image input image, is considered as a binary image ( all non-zero pixels are 1 )\nregion_properties::region_properties ( const cv::Mat& image, double minArea ):\n    m_minArea( minArea )\n{\n    cv::Mat binary;\n    if( image.channels() == 3 )\n    {\n        cv::cvtColor( image, binary, CV_RGB2GRAY );\n    }\n    else if( image.channels() == 1 )\n    {\n        binary = image;\n    }\n    else\n    {\n        COMMA_THROW( comma::exception, \"incorrect number of channels, should be 1 or 3, not \" << image.channels() );\n    }\n//     cv::Mat closed;\n//     cv::morphologyEx( binary, closed, cv::MORPH_CLOSE, cv::Mat::ones( 3, 3, CV_8U) );\n    std::vector< std::vector<cv::Point> > contours;\n    cv::findContours( binary, contours, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_SIMPLE );\n    \n    for( unsigned int i = 0; i < contours.size(); i++ )\n    {\n        binary = cv::Scalar(0);\n        cv::drawContours( binary, contours, i, cv::Scalar(0xFF), CV_FILLED );\n        cv::Rect rect = cv::boundingRect( cv::Mat( contours[i]) );\n        cv::Moments moments = cv::moments( binary( rect ), true );\n        double x = moments.m10/moments.m00;\n        double y = moments.m01/moments.m00;\n        double area = moments.m00; // cv::countNonZero( binary( rect ) )\n        if( area > m_minArea )\n        {\n            // see wikipedia, image moments\n            double diff = moments.nu20 - moments.nu02;\n            double a = 0.5 * ( moments.nu20 + moments.nu02 );\n            double b = 0.5 * std::sqrt( 4 * moments.nu11 * moments.nu11 + diff * diff );\n            double minEigenValue = a - b;\n            double maxEigenValue = a + b;\n    //         std::cerr << \" min \" << minEigenValue << \" max \" << maxEigenValue << std::endl;\n            double theta = 0.5 * std::atan2( 2 * moments.nu11, diff );\n            double eccentricity = 1;\n            if( std::fabs( maxEigenValue ) > 1e-15 )\n            {\n                eccentricity = std::sqrt( 1 - minEigenValue / maxEigenValue );\n            }\n\n            double polygonArea;\n            double convexArea;\n            compute_area( contours[i], polygonArea, convexArea );\n    //         std::cerr << \" area \" << area << \" polygon \" << polygonArea << \" convex \" << convexArea << std::endl;\n\n            blob blob;\n            blob.majorAxis = 2 * std::sqrt( moments.m00 * maxEigenValue );\n            blob.minorAxis = 2 * std::sqrt( moments.m00 * minEigenValue );\n            blob.orientation = theta;\n            blob.centroid = cv::Point( x + rect.x, y + rect.y );\n            blob.area = area;\n            blob.eccentricity = eccentricity;\n            blob.solidity = 0;\n            if( std::fabs( convexArea ) > 1e-15 )\n            {\n                blob.solidity = polygonArea / convexArea;\n            }\n            m_blobs.push_back( blob );\n        }\n    }    \n}\n\n/// draw debug information on the image\nvoid region_properties::show( cv::Mat& image, bool text )\n{\n    for( unsigned int i = 0; i < m_blobs.size(); i++ )\n    {\n        cv::Point centroid = m_blobs[i].centroid;\n        cv::circle( image, centroid, 3, cv::Scalar( 0, 0, 255 ), 2 );\n        std::stringstream s;\n        s << i;\n        if( text )\n        {\n            cv::putText( image, s.str(), centroid + cv::Point( 2, 2 ), cv::FONT_HERSHEY_PLAIN ,1, cv::Scalar( 0, 0, 255 ) );\n        }\n        cv::ellipse( image, centroid, cv::Size( m_blobs[i].majorAxis, m_blobs[i].minorAxis ), m_blobs[i].orientation * 180.0 / M_PI, 0, 360, cv::Scalar( 0, 255, 0 ) );\n//         std::cerr << i << \": area \" << m_blobs[i].area << \" eccentricity \" << m_blobs[i].eccentricity << \" solidity \" << m_blobs[i].solidity << std::endl;\n    }\n}\n\n} } \n\n\n", "meta": {"hexsha": "8db4773ac8196e6d9150ad389acf5869d63182a3", "size": 6703, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "imaging/region_properties.cpp", "max_stars_repo_name": "nightfox0909/snark", "max_stars_repo_head_hexsha": "6a6ddc79af9086f13ba0c1287a555c2740fe4e70", "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": "imaging/region_properties.cpp", "max_issues_repo_name": "nightfox0909/snark", "max_issues_repo_head_hexsha": "6a6ddc79af9086f13ba0c1287a555c2740fe4e70", "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": "imaging/region_properties.cpp", "max_forks_repo_name": "nightfox0909/snark", "max_forks_repo_head_hexsha": "6a6ddc79af9086f13ba0c1287a555c2740fe4e70", "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.1572327044, "max_line_length": 167, "alphanum_fraction": 0.6343428316, "num_tokens": 1719, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.66192288918838, "lm_q2_score": 0.5156199157230157, "lm_q1q2_score": 0.34130062433844754}}
{"text": "/*\nCopyright 2009-2019 Nicolas Colombe\n\nPermission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n*/\n#include <math/polygon.hpp>\n#include <math/polygon_def.hpp>\n#include <math/segment.hpp>\n#include <set>\n\n#include <boost/polygon/polygon.hpp>\n\nnamespace boost\n{\n  namespace polygon \n  {\n  \n    template <typename Real>\n    struct geometry_concept<eXl::Polygon<Real> >{ typedef polygon_with_holes_concept type; };\n  \n    template <typename Real>\n    struct geometry_concept<eXl::Vector<eXl::Vector2<Real> > >{ typedef polygon_concept type; };\n  \n    template <typename Real>\n    struct polygon_90_traits < eXl::Polygon<Real>, boost::polygon::gtl_no > {};\n    \n  \n    template <typename Real>\n    struct polygon_90_traits < eXl::Vector<eXl::Vector2<Real> >, boost::polygon::gtl_no > {};\n    \n  \n    template <typename Real>\n    struct polygon_traits_general<eXl::Polygon<Real> > {\n      typedef Real coordinate_type;\n      typedef typename eXl::Vector<eXl::Vector2<Real> >::const_iterator iterator_type;\n      typedef eXl::Vector2<Real> point_type;\n    \n      static inline iterator_type begin_points(eXl::Polygon<Real> const& t) {\n          return t.Border().begin();\n      }\n      static inline iterator_type end_points(eXl::Polygon<Real> const& t) {\n          return t.Border().end();\n      }\n    \n      // Get the number of sides of the polygon\n      static inline std::size_t size(eXl::Polygon<Real> const& t) {\n        return t.Border().size();\n      }\n    \n      // Get the winding direction of the polygon\n      static inline winding_direction winding(eXl::Polygon<Real> const& t) {\n        return unknown_winding;\n      }\n    };\n    \n    template <typename Real>\n    struct polygon_mutable_traits<eXl::Polygon<Real> > {\n    \n      template <typename iT>\n      static inline eXl::Polygon<Real>& set_points(eXl::Polygon<Real> & t, \n                                         iT input_begin, iT input_end) {\n    \n        eXl::Vector<eXl::Vector2<Real> > tempStor;\n        //iterator_compact_to_points<iT,eXl::Vector2<Real> > iterBegin(input_begin,input_end);\n        //iterator_compact_to_points<iT,eXl::Vector2<Real> > iterEnd(input_end,input_end);\n        \n        //tempStor.assign(input_begin,input_end);\n        for (; input_begin != input_end; ++input_begin)\n        {\n          eXl::Vector2<Real> temp(boost::polygon::point_traits<typename iT::value_type>::get(*input_begin, boost::polygon::HORIZONTAL),\n                                  boost::polygon::point_traits<typename iT::value_type>::get(*input_begin, boost::polygon::VERTICAL)) ;\n          tempStor.push_back(temp);\n        }\n    \n        t = eXl::Polygon<Real>();\n        t.m_Ext.swap(tempStor);\n        t.ForceClockwise();\n        t.UpdateAABB();\n        return t;\n      }\n    \n    };\n  \n    template <typename Real>\n    struct polygon_traits_general<eXl::Vector<eXl::Vector2<Real> > > {\n      typedef Real coordinate_type;\n      typedef typename eXl::Vector<eXl::Vector2<Real> >::const_iterator iterator_type;\n      typedef eXl::Vector2<Real> point_type;\n  \n      static inline iterator_type begin_points(typename eXl::Polygon<Real>::PtList const& t) {\n          return t.begin();\n      }\n      static inline iterator_type end_points(typename eXl::Polygon<Real>::PtList const& t) {\n          return t.end();\n      }\n  \n      // Get the number of sides of the polygon\n      static inline std::size_t size(typename eXl::Polygon<Real>::PtList const& t) {\n        return t.size();\n      }\n  \n      // Get the winding direction of the polygon\n      static inline winding_direction winding(typename eXl::Polygon<Real>::PtList const& t) {\n        return unknown_winding;\n      }\n    };\n  \n    template <typename Real>\n    struct polygon_mutable_traits<eXl::Vector<eXl::Vector2<Real> > > {\n  \n      template <typename iT>\n      static inline typename eXl::Polygon<Real>::PtList& set_points(typename eXl::Polygon<Real>::PtList & t, \n                                         iT input_begin, iT input_end) {\n  \n        //iterator_compact_to_points<iT,eXl::Vector2<Real> > iterBegin(input_begin,input_end);\n        //iterator_compact_to_points<iT,eXl::Vector2<Real> > iterEnd(input_end,input_end);\n        //t.assign(input_begin,input_end);\n        t.clear();\n        for (; input_begin != input_end; ++input_begin)\n        {\n          eXl::Vector2<Real> temp(boost::polygon::point_traits<typename iT::value_type>::get(*input_begin, boost::polygon::HORIZONTAL),\n                                  boost::polygon::point_traits<typename iT::value_type>::get(*input_begin, boost::polygon::VERTICAL)) ;\n          t.push_back(temp);\n        }\n        return t;\n      }\n  \n    };\n  \n    template <typename Real,typename enable>\n    struct polygon_with_holes_traits<eXl::Polygon<Real>,enable> {\n         typedef typename eXl::Polygon<Real>::PtLists::const_iterator iterator_holes_type;\n         typedef typename eXl::Polygon<Real>::PtList hole_type;\n         static inline iterator_holes_type begin_holes(const eXl::Polygon<Real>& t) {\n              return t.Holes().begin();\n         }\n         static inline iterator_holes_type end_holes(const eXl::Polygon<Real>& t) {\n              return t.Holes().end();\n         }\n         static inline Real size_holes(const eXl::Polygon<Real>& t) {\n              return t.Holes().size();\n         }\n    };\n    \n    template <typename Real, typename enable>\n    struct polygon_with_holes_mutable_traits<eXl::Polygon<Real>,enable> {\n         template <typename iT>\n         static inline eXl::Polygon<Real>& set_holes(eXl::Polygon<Real>& t, iT inputBegin, iT inputEnd) {\n  \n              for(;inputBegin != inputEnd;++inputBegin)\n              {\n                typename eXl::Polygon<Real>::PtList hole;\n                boost::polygon::assign(hole,*inputBegin);\n                t.HolesRW().push_back(typename eXl::Polygon<Real>::PtList());\n                t.HolesRW().back().swap(hole);\n              }\n              t.ForceCClockwiseHoles();\n              return t;\n         }\n    };\n\n    template <typename T>\n    struct is_polygon_set_type<eXl::Vector<T> > {\n      typedef typename gtl_or<\n        typename is_polygonal_concept<typename geometry_concept<eXl::Vector<T> >::type>::type,\n        typename is_polygonal_concept<typename geometry_concept<typename eXl::Vector<T>::value_type>::type>::type>::type type;\n    };\n\n    template <typename T>\n    struct is_mutable_polygon_set_type<eXl::Vector<T> > {\n      typedef typename gtl_or<\n        typename gtl_same_type<polygon_set_concept, typename geometry_concept<eXl::Vector<T> >::type>::type,\n        typename is_polygonal_concept<typename geometry_concept<typename eXl::Vector<T>::value_type>::type>::type>::type type;\n    };\n\n    template <typename T>\n    struct polygon_set_mutable_traits<eXl::Vector<T> > {\n      template <typename input_iterator_type>\n      static inline void set(eXl::Vector<T>& polygon_set, input_iterator_type input_begin, input_iterator_type input_end) {\n        polygon_set.clear();\n        size_t num_ele = std::distance(input_begin, input_end);\n        polygon_set.reserve(num_ele);\n        polygon_set_data<typename polygon_set_traits<std::list<T> >::coordinate_type> ps;\n        ps.reserve(num_ele);\n        ps.insert(input_begin, input_end);\n        ps.get(polygon_set);\n      }\n    };\n  \n  }\n}\n\nnamespace eXl\n{\n  class Serializer;\n\n  template <typename PolygonType>\n  Err Stream_T(PolygonType& iPoly, Serializer iStreamer);\n\n  template <typename Real> \n  struct PreciseVector\n  {\n    typedef eXl::Vector2<typename eXl::PreciseType<Real>::type > type; \n  };\n\n  template <typename Real> \n  inline typename PreciseVector<Real>::type ToPrecise(Vector2<Real> const& iVec)\n  {\n    return typename PreciseVector<Real>::type(Math<Real>::ToPrecise(iVec.X()), Math<Real>::ToPrecise(iVec.Y()));\n  }\n\n  template <typename Real> \n  inline bool VectorNotNull(Vector2<Real> const& iVec)\n  {\n    return iVec.Length() > Math<Real>::ZERO_TOLERANCE;\n  }\n\n  template <> \n  inline bool VectorNotNull<int>(Vector2i const& iVec)\n  {\n    return iVec != Vector2i::ZERO;\n  }\n\n  template <typename Real>\n  Polygon<Real>::Polygon(){}  \n\n  template <typename Real>\n  Polygon<Real>::~Polygon(){}\n\n  template <typename Real>\n  void Polygon<Real>::Translate(Vector2<Real> const& iTrans)\n  {\n    for (unsigned int i = 0; i < m_Ext.size(); ++i)\n    {\n      m_Ext[i] += iTrans;\n    }\n    \n    for (unsigned int i = 0; i < m_Holes.size(); ++i)\n    {\n      for (unsigned int j = 0; j < m_Holes[i].size(); ++j)\n      {\n        m_Holes[i][j] += iTrans;\n      }\n    }\n    //UpdateAABB();\n    m_AABB.m_Data[0] += iTrans;\n    m_AABB.m_Data[1] += iTrans;\n  }\n\n  template <typename Real>\n  void Polygon<Real>::Scale(Real iNum, Real iDenom)\n  {\n    //Polygone valide si edge confondues ??\n    for (unsigned int i = 0; i < m_Ext.size(); ++i)\n    {\n      m_Ext[i] = (m_Ext[i] * iNum) / iDenom;\n    }\n    \n    for (unsigned int i = 0; i < m_Holes.size(); ++i)\n    {\n      for (unsigned int j = 0; j < m_Holes[i].size(); ++j)\n      {\n        m_Holes[i][j] = (m_Holes[i][j] * iNum) / iDenom;\n      }\n    }\n    UpdateAABB();\n  }\n\n  template <typename Real>\n  void Polygon<Real>::Rotate(typename eXl::PreciseType<Real>::type iAngle)\n  {\n    if(Math<typename eXl::PreciseType<Real>::type>::Abs(iAngle) > Math<typename eXl::PreciseType<Real>::type>::ZERO_TOLERANCE)\n    {\n      auto xAxis = Vector2<typename eXl::PreciseType<Real>::type>(Math<typename eXl::PreciseType<Real>::type>::Cos(iAngle), Math<typename eXl::PreciseType<Real>::type>::Sin(iAngle));\n      auto yAxis = Vector2<typename eXl::PreciseType<Real>::type>(-xAxis.Y(), xAxis.X());\n\n      for (unsigned int i = 0; i < m_Ext.size(); ++i)\n      {\n        auto vec = xAxis * m_Ext[i].X() + yAxis * m_Ext[i].Y();\n        m_Ext[i] = Vector2<Real>(Math<Real>::Round(vec.X()), Math<Real>::Round(vec.Y()));\n      }\n    \n      for (unsigned int i = 0; i < m_Holes.size(); ++i)\n      {\n        for (unsigned int j = 0; j < m_Holes[i].size(); ++j)\n        {\n          auto vec = xAxis * m_Holes[i][j].X() + yAxis * m_Holes[i][j].Y();\n          m_Holes[i][j] = Vector2<Real>(Math<Real>::Round(vec.X()), Math<Real>::Round(vec.Y()));\n        }\n      }\n\n      UpdateAABB();\n    }\n  }\n\n  template <typename Real>\n  Polygon<Real>::Polygon(Vector<Vector2<Real> > const& iPoints)\n  {\n    if(iPoints.size() > 2)\n    {\n      m_Ext = iPoints;\n      if(m_Ext.front() != m_Ext.back())\n        m_Ext.push_back(m_Ext.front());\n      ForceClockwise();\n    }\n    UpdateAABB();\n  }\n\n  template <typename Real>\n  void Polygon<Real>::UpdateAABB()\n  {\n    boost::polygon::extents(m_AABB, *this);\n  }\n\n  template <typename Real>\n  Polygon<Real>::Polygon(AABB2D<Real> const& iBox)\n  {\n    m_Ext.clear();\n    \n    m_Ext.push_back(iBox.m_Data[0]);\n    m_Ext.push_back(Vector2<Real>(iBox.m_Data[0].X(), iBox.m_Data[1].Y()));\n    m_Ext.push_back(iBox.m_Data[1]);\n    m_Ext.push_back(Vector2<Real>(iBox.m_Data[1].X(), iBox.m_Data[0].Y()));\n    m_Ext.push_back(iBox.m_Data[0]);\n\n    ForceClockwise();\n    \n    m_AABB = iBox;\n  }\n\n  template <typename Real>\n  void Polygon<Real>::Swap(Polygon& iOther)\n  {\n    AABB2D<Real> temp = iOther.m_AABB;\n    iOther.m_Ext.swap(m_Ext);\n    iOther.m_Holes.swap(m_Holes);\n    iOther.m_AABB = m_AABB;\n    m_AABB = temp;\n  }\n\n\n  template <typename Real>\n  Real Polygon<Real>::Perimeter()const\n  {\n    return boost::polygon::perimeter(*this);\n  }\n\n  template <typename Real>\n  Real Polygon<Real>::Area() const\n  {\n    return boost::polygon::area(*this);\n  }\n\n  template <typename Real>\n  void Polygon<Real>::ForceClockwise()\n  {\n    if(boost::polygon::winding(*this) != boost::polygon::CLOCKWISE)\n    {\n      std::reverse(m_Ext.begin(),m_Ext.end());\n    }\n  }\n\n  template <typename Real>\n  void Polygon<Real>::ForceCClockwiseHoles()\n  {\n    for(unsigned int i = 0;i<m_Holes.size();++i)\n    {\n      if(boost::polygon::winding(m_Holes[i]) != boost::polygon::COUNTERCLOCKWISE)\n      {\n        std::reverse(m_Holes[i].begin(),m_Holes[i].end());\n      }\n    }\n  }\n\n  template <typename Real>\n  void Polygon<Real>::InternalSwap(Polygon &iOther)const\n  {\n    m_Ext.swap(iOther.m_Ext);\n    m_Holes.swap(iOther.m_Holes);\n  }\n\n  template <typename Real>\n  void Polygon<Real>::Clear()\n  {\n    m_Ext.clear();\n    m_Holes.clear();\n  }\n\n  template <typename Real>\n  bool Polygon<Real>::Empty() const\n  {\n    return m_Ext.empty();\n  }\n\n  template <typename Real>\n  bool Polygon<Real>::ContainsPoint(Vector2<Real> const& iPoint) const\n  {\n    boost::polygon::point_data<Real> point(iPoint.X(), iPoint.Y());\n    return boost::polygon::contains(*this, point);\n  }\n\n  //template <typename Real>\n  //void Polygon<Real>::GetBoxes(Vector<AABB2D<Real> >& oBoxes)const\n  //{\n  //  Vector<Polygon> meSet;\n  //  meSet.push_back(Polygon());\n  //  InternalSwap(meSet[0]);\n  //\n  //  boost::polygon::get_rectangles(oBoxes,meSet);\n  //\n  //  InternalSwap(meSet[0]);\n  //}\n\n  template <typename Real>\n  void Polygon<Real>::Merge(Vector<Polygon>& ioPoly)\n  {\n    Vector<Polygon> res;\n    if(ioPoly.size() > 0)\n    {\n      res.push_back(ioPoly.front());\n      for(unsigned int i = 1 ; i<ioPoly.size();++i)\n      {\n        boost::polygon::operators::operator|=(res,ioPoly[i]);\n      }\n    }\n    ioPoly.swap(res);\n  }\n\n  template <typename Real>\n  void Polygon<Real>::Union(Polygon const& iOther, Polygon& oPoly)const\n  {   \n    oPoly.Clear();\n\n    Vector<Polygon> meSet;\n    Vector<Polygon> otherSet;\n    \n    meSet.push_back(Polygon());\n    InternalSwap(meSet[0]);\n    \n    otherSet.push_back(Polygon());\n    iOther.InternalSwap(otherSet[0]);\n    \n    Vector<Polygon> result;\n    boost::polygon::assign(result,boost::polygon::operators::operator+(meSet,otherSet));\n\n    InternalSwap(meSet[0]);\n    iOther.InternalSwap(otherSet[0]);\n    if (result.size() == 1)\n    {\n      oPoly.Swap(result[0]);\n    }\n  }\n\n  template <typename Real>\n  void Polygon<Real>::Difference(Polygon const& iOther, Vector<Polygon>& oPoly)const\n  {\n    oPoly.clear();\n\n    Vector<Polygon> meSet;\n    Vector<Polygon> otherSet;\n    \n    meSet.push_back(Polygon());\n    InternalSwap(meSet[0]);\n    \n    otherSet.push_back(Polygon());\n    iOther.InternalSwap(otherSet[0]);\n\n    boost::polygon::assign(oPoly,boost::polygon::operators::operator-(meSet,otherSet));\n\n    InternalSwap(meSet[0]);\n    iOther.InternalSwap(otherSet[0]);\n  }\n\n  template <typename Real>\n  void Polygon<Real>::Intersection(Polygon const& iOther, Vector<Polygon>& oPoly)const\n  {\n    Vector<Polygon> meSet;\n    Vector<Polygon> otherSet;\n    \n    meSet.push_back(Polygon());\n    InternalSwap(meSet[0]);\n    \n    otherSet.push_back(Polygon());\n    iOther.InternalSwap(otherSet[0]);\n\n    boost::polygon::assign(oPoly,boost::polygon::operators::operator&(meSet,otherSet));\n\n    InternalSwap(meSet[0]);\n    iOther.InternalSwap(otherSet[0]);\n\n  }\n\n  template <typename Real>\n  Vector<Polygon<Real> > Polygon<Real>::GetTrapezoids() const\n  {\n    Vector< Polygon<Real> > result;\n    Vector<Polygon> meSet;\n    \n    meSet.push_back(Polygon());\n    InternalSwap(meSet[0]);\n\n    boost::polygon::get_trapezoids(result, meSet, boost::polygon::VERTICAL);\n\n    InternalSwap(meSet[0]);\n\n    return result;\n  }\n\n  template <typename Real>\n  void Polygon<Real>::CutConvex(Vector2<Real> const& iOrig, Vector2<Real> const& iDir, Polygon& oLeftPoly, Polygon& oRightPoly) const\n  {\n    oLeftPoly.Clear();\n    oRightPoly.Clear();\n\n    auto lowPt = ToPrecise(m_AABB.m_Data[0]);\n    auto highPt = ToPrecise(m_AABB.m_Data[1]);\n\n    typename PreciseVector<Real>::type boxSeg[5] = \n    {lowPt,  typename PreciseVector<Real>::type(lowPt.X(), highPt.Y()),\n     highPt, typename PreciseVector<Real>::type(highPt.X(), lowPt.Y()),\n     lowPt\n    };\n\n    unsigned int curPoint = 0;\n    Vector2<Real> cutPoints[2];\n\n    auto dOrig = ToPrecise(iOrig);\n    auto dDir  = ToPrecise(iDir);\n\n    for (unsigned int i = 0; i < 4 && curPoint < 2; ++i)\n    {\n      typename PreciseVector<Real>::type res;\n      unsigned int result = Segment<typename PreciseType<Real>::type>::Intersect(dOrig, dOrig + dDir, boxSeg[i], boxSeg[i + 1], res);\n      unsigned int mask = Segment<typename PreciseType<Real>::type>::PointFound | Segment<typename PreciseType<Real>::type>::PointOnSegment2;\n      if((result & mask) == mask)\n      {\n        Vector2<Real> potPoint(Math<Real>::Round(res.X()), Math<Real>::Round(res.Y()));\n        if (curPoint == 0 || VectorNotNull(cutPoints[0] - potPoint))\n        {\n          //Snap to bbox seg if integer.\n          cutPoints[curPoint] = potPoint;\n          ++curPoint;\n        }\n      }\n    }\n\n    if (curPoint == 2)\n    {\n      Vector2<Real> cutVect = cutPoints[0] - cutPoints[1];\n      if (VectorNotNull(cutVect))\n      {\n        int origPoint = cutVect.Dot(iDir) > 0 ? 0 : 1;\n\n        typename Segment<Real>::SortByAngle sortMeth(cutPoints[origPoint]);\n        std::set<Vector2<Real>, typename Segment<Real>::SortByAngle > sortedPoints(sortMeth);\n        sortedPoints.insert(cutPoints[1 - origPoint]);\n        sortedPoints.insert(m_AABB.m_Data[0]);\n        sortedPoints.insert(m_AABB.m_Data[1]);\n        sortedPoints.insert(Vector2<Real>(m_AABB.m_Data[0].X(), m_AABB.m_Data[1].Y()));\n        sortedPoints.insert(Vector2<Real>(m_AABB.m_Data[1].X(), m_AABB.m_Data[0].Y()));\n\n        Vector<Vector2<Real> > cutPoly;\n\n        cutPoly.push_back(cutPoints[origPoint]);\n\n        auto iter = sortedPoints.begin();\n        while (*iter != cutPoints[1 - origPoint] && iter != sortedPoints.end())\n        {\n          cutPoly.push_back(*iter);\n          ++iter;\n        }\n        //eXl_ASSERT(iter != sortedPoints.end(), \"Error\");\n        //eXl_ASSERT(cutPoly.size() > 3, \"Error\");\n        if (iter != sortedPoints.end() && cutPoly.size() > 0)\n        {\n          cutPoly.push_back(*iter);\n          Vector<Polygon<Real> > oPoly1;\n          Polygon<Real> leftPoly(cutPoly);\n          Intersection(leftPoly, oPoly1);\n          //eXl_ASSERT(oPoly1.size() == 0 || oPoly1.size() == 1, \"Error\");\n          if (oPoly1.size() == 1)\n          {\n            Vector<Polygon<Real> > oPoly2;\n            Difference(oPoly1[0], oPoly2);\n            //eXl_ASSERT(oPoly2.size() == 0 || oPoly2.size() == 1, \"Error\");\n            if (oPoly2.size() < 2)\n            {\n              if (oPoly2.size() == 1)\n              {\n                oRightPoly.Swap(oPoly2[0]);\n              }\n              oLeftPoly.Swap(oPoly1[0]);\n            }\n          }\n          else if (oPoly1.size() == 0)\n          {\n            oRightPoly = *this;\n          }\n        }\n      }\n    }\n  }\n\n  template <typename Real>\n  bool Polygon<Real>::IsConvex() const\n  {\n    if(!m_Holes.empty())\n      return false;\n\n    if(m_Ext.size() <= 2)\n      return true;\n\n    Vector2<Real> initPoint = m_Ext[0];\n    Vector2<Real> lastPoint1 = initPoint;\n    Vector2<Real> lastPoint2 = m_Ext[1];\n    Vector2<Real> curPoint = m_Ext[2];\n\n    Real initSign = Segment<Real>::IsLeft(lastPoint1, lastPoint2, curPoint);\n    initSign = initSign > 0 ? 1 : -1; \n    lastPoint1 = lastPoint2;\n    lastPoint2 = curPoint;\n    //+1 to loop on the last segment.\n    for (unsigned int i = 3; i < m_Ext.size() + 1; ++i)\n    {\n      if (m_Ext.size() == i)\n      {\n        curPoint = m_Ext[0];\n        if(Segment<Real>::IsLeft(lastPoint1, lastPoint2, curPoint) * initSign < 0)\n          return false;\n      }\n      else\n      {\n        curPoint = m_Ext[i];\n        if (curPoint == initPoint)\n        {\n          if(Segment<Real>::IsLeft(lastPoint1, lastPoint2, curPoint) * initSign < 0)\n            return false;\n          break;\n        }\n        if(Segment<Real>::IsLeft(lastPoint1, lastPoint2, curPoint) * initSign < 0)\n          return false;\n\n      }\n      lastPoint1 = lastPoint2;\n      lastPoint2 = curPoint;\n    }\n    return true;\n  }\n\n  template <class Real>\n  struct SortPoints\n  {\n    bool operator()(Vector2<Real> const& iPt1, Vector2<Real> const& iPt2)\n    {\n      if(iPt1.X() == iPt2.X())\n        return iPt1.Y() < iPt2.Y();\n      return iPt1.X() < iPt2.X();\n    }\n  };\n\n  template <class Real>\n  void Polygon<Real>::ConvexHull(Polygon<Real>& oHull) const\n  {\n    return ConvexHull(m_Ext, oHull);\n  }\n\n  template <class Real>\n  void Polygon<Real>::ConvexHull(Vector<Vector2<Real> >const& iPoints, Polygon<Real>& oHull)\n  {\n    oHull.Clear();\n    if(!iPoints.empty())\n    {\n      Vector<Vector2<Real> > sorted = iPoints;\n\n      std::sort(sorted.begin(), sorted.end(), SortPoints<Real>());\n\n      int n = sorted.size();\n      int k = 0;\n\t    Vector<Vector2<Real> > H(2*n);\n\n\t    \n\t    for (int i = 0; i < n; ++i) \n      {\n\t\t    while (k >= 2 && Segment<Real>::IsLeft(H[k-2], H[k-1], sorted[i]) <= 0) \n          k--;\n\n\t\t    H[k++] = sorted[i];\n\t    }\n\n\t    // Build upper hull\n\t    for (int i = n-2, t = k+1; i >= 0; i--) \n      {\n\t\t    while (k >= t && Segment<Real>::IsLeft(H[k-2], H[k-1], sorted[i]) <= 0) \n          k--;\n\n\t\t    H[k++] = sorted[i];\n\t    }\n\n\t    H.resize(k);\n\n      oHull = Polygon<Real>(H);\n    }\n  }\n\n  template <class Real>\n  void Polygon<Real>::RemoveUselessPoints()\n  {\n    _RemoveUselessPoints(m_Ext);\n    for(unsigned int i = 0; i<m_Holes.size(); ++i)\n    {\n      _RemoveUselessPoints(m_Holes[i]);\n    }\n  }\n\n  template <class Real>\n  void Polygon<Real>::_RemoveUselessPoints(Vector<Vector2<Real> >& ioPoints)\n  {\n    Vector2<Real> prevPt1 = ioPoints.back();\n    Vector2<Real> prevPt2 = ioPoints.back();\n    for (unsigned int i = 0; i<ioPoints.size(); ++i)\n    {\n      Vector2<Real> curPt =  ioPoints[i];\n      if (curPt != prevPt1 && prevPt1 != prevPt2)\n      {\n        typename PreciseVector<Real>::type dir1 = ToPrecise<Real>(prevPt1 - prevPt2);\n        typename PreciseVector<Real>::type dir2 = ToPrecise<Real>(curPt - prevPt2);\n        typename PreciseType<Real>::type len1 = dir1.Normalize();\n        typename PreciseType<Real>::type len2 = dir2.Normalize();\n        if (dir1.Dot(dir2) > (1 - eXl::Math<typename PreciseType<Real>::type>::EPSILON) && len1 < len2)\n        {\n          ioPoints[i - 1] = curPt;\n          ioPoints.erase(ioPoints.begin() + i);\n          prevPt1 = curPt;\n          --i;\n          continue;\n        }\n      }\n      prevPt2 = prevPt1;\n      prevPt1 = curPt;\n    }\n  }\n\n  template <typename Real>\n  void Polygon<Real>::Shrink(Real iFactor,Vector<Polygon>& oOut)const\n  {\n    Vector<Polygon> meSet;\n    meSet.push_back(*this);\n\n    boost::polygon::shrink(meSet,iFactor);\n\n    if(meSet.size()>0)\n      meSet.swap(oOut);\n    else\n      oOut.clear();\n  }\n\n  template <typename Real>\n  void Polygon<Real>::Bloat(Real iFactor,Polygon& oOut)const\n  {\n    Vector<Polygon> meSet;\n    meSet.push_back(*this);\n\n    boost::polygon::bloat(meSet,iFactor);\n\n    if(meSet.size()>0)\n      meSet[0].Swap(oOut);\n    else\n      oOut.Clear();\n  }\n\n  template <typename Real>\n  void Polygon<Real>::RemoveTiny(Real iFactor,Vector<Polygon>& oOut,Vector<Polygon>& oRemoved)const\n  {\n    oOut.clear();\n    oRemoved.clear();\n    Vector<Polygon> meSet;\n    meSet.push_back(*this);\n\n    /*meSet = */boost::polygon::shrink(meSet,iFactor);\n\n    /*meSet = */boost::polygon::bloat(meSet,iFactor);\n\n    //meSet = boost::polygon::keep(meSet,0,ULLONG_MAX,iFactor,ULLONG_MAX,iFactor,ULLONG_MAX);\n\n    if(meSet.empty())\n    {\n      oRemoved.push_back(*this);\n    }\n    else\n    {\n\n      Vector<Polygon> good;\n      good.push_back(Polygon());\n      InternalSwap(good.back());\n\n      boost::polygon::assign(oRemoved,boost::polygon::operators::operator-(good,meSet));\n      InternalSwap(good.back());\n\n      //meSet.back().Swap(*this);\n      oOut.swap(meSet);\n    }\n  }\n}\n\n#include <core/stream/serializer.hpp>\n\nnamespace eXl\n{\n\n  template <typename PolygonType>\n  Err Stream_T(PolygonType& iPoly, Serializer iStreamer)\n  {\n    iStreamer.BeginStruct();\n    iStreamer.PushKey(\"Border\");\n    iStreamer &= iPoly.Border();\n    iStreamer.PopKey();\n    iStreamer.PushKey(\"Holes\");\n    iStreamer &= iPoly.Holes();\n    iStreamer.PopKey();\n    iStreamer.EndStruct();\n\n    RETURN_SUCCESS;\n  }\n\n  template <typename Real>\n  Err Polygon<Real>::Stream(Streamer& iStreamer) const\n  {\n    Serializer serializer(iStreamer);\n    return Stream_T(*this, serializer);\n  }\n\n  template <typename Real>\n  Err Polygon<Real>::Unstream(Unstreamer& iStreamer)\n  {\n    Serializer serializer(iStreamer);\n    return Stream_T(*this, serializer);\n  }\n}", "meta": {"hexsha": "917c030b1c65e68d9de6489bd9955aa0a06cb54f", "size": 25094, "ext": "inl", "lang": "C++", "max_stars_repo_path": "include/math/polygon.inl", "max_stars_repo_name": "eXl-Nic/eXl", "max_stars_repo_head_hexsha": "a5a0f77f47db3179365c107a184bb38b80280279", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/math/polygon.inl", "max_issues_repo_name": "eXl-Nic/eXl", "max_issues_repo_head_hexsha": "a5a0f77f47db3179365c107a184bb38b80280279", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/math/polygon.inl", "max_forks_repo_name": "eXl-Nic/eXl", "max_forks_repo_head_hexsha": "a5a0f77f47db3179365c107a184bb38b80280279", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.8028503563, "max_line_length": 460, "alphanum_fraction": 0.6154459233, "num_tokens": 6805, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6619228758499942, "lm_q2_score": 0.5156199157230157, "lm_q1q2_score": 0.34130061746091017}}
{"text": "/*\n * Lumi3DReWeighting.cpp\n *\n *  Created on: 5 Dec 2011\n *      Author: kreczko\n */\n\n#include \"../interface/Lumi3DReWeighting.h\"\n\n#include \"TRandom1.h\"\n#include \"TRandom2.h\"\n#include \"TRandom3.h\"\n#include \"TStopwatch.h\"\n#include \"TH1.h\"\n#include \"TH3.h\"\n#include \"TFile.h\"\n#include <string>\n#include <algorithm>\n#include <boost/shared_ptr.hpp>\n#include <boost/scoped_ptr.hpp>\n#include <iostream>\n\nnamespace BAT {\n\nLumi3DReWeighting::Lumi3DReWeighting(std::string generatedFile, std::string dataFile,\n\t\tstd::string GenHistName = \"pileup\", std::string DataHistName = \"pileup\") :\n\t\tgeneratedFileName_(generatedFile), //\n\t\tdataFileName_(dataFile), //\n\t\tGenHistName_(GenHistName), //\n\t\tDataHistName_(DataHistName) {\n\tgeneratedFile_ = boost::shared_ptr<TFile>(new TFile(generatedFileName_.c_str())); //MC distribution\n\tdataFile_ = boost::shared_ptr<TFile>(new TFile(dataFileName_.c_str())); //Data distribution\n\n\tboost::scoped_ptr<TH1> Data_temp((static_cast<TH1*>(dataFile_->Get(DataHistName_.c_str())->Clone())));\n\n\tboost::scoped_ptr<TH1> MC_temp((static_cast<TH1*>(generatedFile_->Get(GenHistName_.c_str())->Clone())));\n\n\tMC_distr_ = boost::shared_ptr<TH1>((static_cast<TH1*>(generatedFile_->Get(GenHistName_.c_str())->Clone())));\n\tData_distr_ = boost::shared_ptr<TH1>((static_cast<TH1*>(dataFile_->Get(DataHistName_.c_str())->Clone())));\n\n\t// MC * data/MC = data, so the weights are data/MC:\n\n\t// normalize both histograms first\n\n\tData_distr_->Scale(1.0 / Data_distr_->Integral());\n\tMC_distr_->Scale(1.0 / MC_distr_->Integral());\n\n}\n\nLumi3DReWeighting::Lumi3DReWeighting(std::vector<float> MC_distr, std::vector<float> Lumi_distr) {\n\t// no histograms for input: use vectors\n\n\t// now, make histograms out of them:\n\n\tInt_t NMCBins = MC_distr.size();\n\n\tMC_distr_ = boost::shared_ptr<TH1>(new TH1F(\"MC_distr\", \"MC dist\", NMCBins, 0., float(NMCBins)));\n\n\tInt_t NDBins = Lumi_distr.size();\n\n\tData_distr_ = boost::shared_ptr<TH1>(new TH1F(\"Data_distr\", \"Data dist\", NDBins, 0., float(NDBins)));\n\n\tfor (int ibin = 1; ibin < NMCBins + 1; ++ibin) {\n\t\tMC_distr_->SetBinContent(ibin, MC_distr[ibin - 1]);\n\t}\n\n\tfor (int ibin = 1; ibin < NDBins + 1; ++ibin) {\n\t\tData_distr_->SetBinContent(ibin, Lumi_distr[ibin - 1]);\n\t}\n\n\t// check integrals, make sure things are normalized\n\n\tfloat deltaH = Data_distr_->Integral();\n\tif (fabs(1.0 - deltaH) > 0.001) { //*OOPS*...\n\t\tData_distr_->Scale(1.0 / Data_distr_->Integral());\n\t}\n\tfloat deltaMC = MC_distr_->Integral();\n\tif (fabs(1.0 - deltaMC) > 0.001) {\n\t\tMC_distr_->Scale(1.0 / MC_distr_->Integral());\n\t}\n\n}\n\ndouble Lumi3DReWeighting::weight3D(int pv1, int pv2, int pv3) {\n\n\tusing std::min;\n\n\tint npm1 = min(pv1, NVERTEX - 1);\n\tint np0 = min(pv2, NVERTEX - 1);\n\tint npp1 = min(pv3, NVERTEX - 1);\n\n\treturn Weight3D_[npm1][np0][npp1];\n\n}\n\n/**\n * @PARAM ScaleFactor: Scale factor is used to shift target distribution (i.e. luminosity scale)  1. = no shift\n */\nvoid Lumi3DReWeighting::weight3D_init(float ScaleFactor) {\n\n\t//create histogram to write output weights, save pain of generating them again...\n\n\tboost::scoped_ptr<TH3D> WHist(\n\t\t\tnew TH3D(\"WHist\", \"3D weights\", NVERTEX, -.5, 49.5, NVERTEX, -.5, 49.5, NVERTEX, -.5, 49.5));\n\tboost::scoped_ptr<TH3D> DHist(\n\t\t\tnew TH3D(\"DHist\", \"3D weights\", NVERTEX, -.5, 49.5, NVERTEX, -.5, 49.5, NVERTEX, -.5, 49.5));\n\tboost::scoped_ptr<TH3D> MHist(\n\t\t\tnew TH3D(\"MHist\", \"3D weights\", NVERTEX, -.5, 49.5, NVERTEX, -.5, 49.5, NVERTEX, -.5, 49.5));\n\n\tusing std::min;\n\n\tif (MC_distr_->GetEntries() == 0) {\n\t\tstd::cout << \" MC and Data distributions are not initialised! You must call the Lumi3DReWeighting constructor. \"\n\t\t\t\t<< std::endl;\n\t}\n\n\t// arrays for storing number of interactions\n\n\tdouble MC_ints[NVERTEX][NVERTEX][NVERTEX];\n\tdouble Data_ints[NVERTEX][NVERTEX][NVERTEX];\n\n\tfor (int i = 0; i < NVERTEX; i++) {\n\t\tfor (int j = 0; j < NVERTEX; j++) {\n\t\t\tfor (int k = 0; k < NVERTEX; k++) {\n\t\t\t\tMC_ints[i][j][k] = 0.;\n\t\t\t\tData_ints[i][j][k] = 0.;\n\t\t\t}\n\t\t}\n\t}\n\n\tdouble factorial[NVERTEX];\n\tdouble PowerSer[NVERTEX];\n\tdouble base = 1.;\n\n\tfactorial[0] = 1.;\n\tPowerSer[0] = 1.;\n\n\tfor (int i = 1; i < NVERTEX + 1; ++i) {\n\t\tbase = base * float(i);\n\t\tfactorial[i] = base;\n\t}\n\n\tdouble x;\n\tdouble xweight;\n\tdouble probi, probj, probk;\n\tdouble Expval, mean;\n\tint xi;\n\n\t// Get entries for Data, MC, fill arrays:\n\n\tint NMCbin = MC_distr_->GetNbinsX();\n\n\tfor (int jbin = 1; jbin < NMCbin + 1; jbin++) {\n\t\tx = MC_distr_->GetBinCenter(jbin);\n\t\txweight = MC_distr_->GetBinContent(jbin); //use as weight for matrix\n\n\t\t//for Summer 11, we have this int feature:\n\t\txi = int(x);\n\n\t\t// Generate Poisson distribution for each value of the mean\n\n\t\tmean = double(xi);\n\n\t\tif (mean < 0.) {\n//      throw cms::Exception(\"BadInputValue\") << \" Your histogram generates MC luminosity values less than zero!\"\n//\t\t\t\t\t\t<< \" Please Check.  Terminating.\" << std::endl;\n\t\t}\n\n\t\tif (mean == 0.) {\n\t\t\tExpval = 1.;\n\t\t} else {\n\t\t\tExpval = exp(-1. * mean);\n\t\t}\n\n\t\tbase = 1.;\n\n\t\tfor (int i = 1; i < NVERTEX; ++i) {\n\t\t\tbase = base * mean;\n\t\t\tPowerSer[i] = base; // PowerSer is mean^i\n\t\t}\n\n\t\t// compute poisson probability for each Nvtx in weight matrix\n\n\t\tfor (int i = 0; i < NVERTEX; i++) {\n\t\t\tprobi = PowerSer[i] / factorial[i] * Expval;\n\t\t\tfor (int j = 0; j < NVERTEX; j++) {\n\t\t\t\tprobj = PowerSer[j] / factorial[j] * Expval;\n\t\t\t\tfor (int k = 0; k < NVERTEX; k++) {\n\t\t\t\t\tprobk = PowerSer[k] / factorial[k] * Expval;\n\t\t\t\t\t// joint probability is product of event weights multiplied by weight of input distribution bin\n\t\t\t\t\tMC_ints[i][j][k] = MC_ints[i][j][k] + probi * probj * probk * xweight;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t}\n\n\tint NDatabin = Data_distr_->GetNbinsX();\n\n\tfor (int jbin = 1; jbin < NDatabin + 1; jbin++) {\n\t\tmean = (Data_distr_->GetBinCenter(jbin)) * ScaleFactor;\n\t\txweight = Data_distr_->GetBinContent(jbin);\n\n\t\t// Generate poisson distribution for each value of the mean\n\n\t\tif (mean < 0.) {\n//      throw cms::Exception(\"BadInputValue\") << \" Your histogram generates Data luminosity values less than zero!\"\n//\t\t\t\t\t\t<< \" Please Check.  Terminating.\" << std::endl;\n\t\t}\n\n\t\tif (mean == 0.) {\n\t\t\tExpval = 1.;\n\t\t} else {\n\t\t\tExpval = exp(-1. * mean);\n\t\t}\n\n\t\tbase = 1.;\n\n\t\tfor (int i = 1; i < NVERTEX; ++i) {\n\t\t\tbase = base * mean;\n\t\t\tPowerSer[i] = base;\n\t\t}\n\n\t\t// compute poisson probability for each Nvtx in weight matrix\n\n\t\tfor (int i = 0; i < NVERTEX; i++) {\n\t\t\tprobi = PowerSer[i] / factorial[i] * Expval;\n\t\t\tfor (int j = 0; j < NVERTEX; j++) {\n\t\t\t\tprobj = PowerSer[j] / factorial[j] * Expval;\n\t\t\t\tfor (int k = 0; k < NVERTEX; k++) {\n\t\t\t\t\tprobk = PowerSer[k] / factorial[k] * Expval;\n\t\t\t\t\t// joint probability is product of event weights multiplied by weight of input distribution bin\n\t\t\t\t\tData_ints[i][j][k] = Data_ints[i][j][k] + probi * probj * probk * xweight;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t}\n\n\tfor (int i = 0; i < NVERTEX; i++) {\n\t\t//if(i<5) std::cout << \"i = \" << i << std::endl;\n\t\tfor (int j = 0; j < NVERTEX; j++) {\n\t\t\tfor (int k = 0; k < NVERTEX; k++) {\n\t\t\t\tif ((MC_ints[i][j][k]) > 0.) {\n\t\t\t\t\tWeight3D_[i][j][k] = Data_ints[i][j][k] / MC_ints[i][j][k];\n\t\t\t\t} else {\n\t\t\t\t\tWeight3D_[i][j][k] = 0.;\n\t\t\t\t}\n\t\t\t\tWHist->SetBinContent(i + 1, j + 1, k + 1, Weight3D_[i][j][k]);\n\t\t\t\tDHist->SetBinContent(i + 1, j + 1, k + 1, Data_ints[i][j][k]);\n\t\t\t\tMHist->SetBinContent(i + 1, j + 1, k + 1, MC_ints[i][j][k]);\n\t\t\t\t//\tif(i<5 && j<5 && k<5) std::cout << Weight3D_[i][j][k] << \" \" ;\n\t\t\t}\n\t\t\t//      if(i<5 && j<5) std::cout << std::endl;\n\t\t}\n\t}\n\n\tstd::cout << \" 3D Weight Matrix initialized! \" << std::endl;\n\tstd::cout << \" Writing weights to file Weight3D.root for re-use...  \" << std::endl;\n\n\tboost::scoped_ptr<TFile> outfile(new TFile(\"Weight3D.root\", \"RECREATE\"));\n\toutfile->cd();\n\tWHist->Write();\n\tMHist->Write();\n\tDHist->Write();\n\toutfile->Write();\n\toutfile->Close();\n//\toutfile->Delete();\n\n\treturn;\n\n}\n\nvoid Lumi3DReWeighting::weight3D_init(std::string WeightFileName) {\n\n\tboost::scoped_ptr<TFile> infile(new TFile(WeightFileName.c_str()));\n\tboost::scoped_ptr<TH3D> WHist((TH3D*) infile->Get(\"WHist\"));\n\n\t// Check if the histogram exists\n\tif (!WHist) {\n//    throw cms::Exception(\"HistogramNotFound\") << \" Could not find the histogram WHist in the file \"\n//\t\t\t\t\t      << \"in the file \" << WeightFileName << \".\" << std::endl;\n\t}\n\n\tfor (int i = 0; i < NVERTEX; i++) {\n\t\tfor (int j = 0; j < NVERTEX; j++) {\n\t\t\tfor (int k = 0; k < NVERTEX; k++) {\n\t\t\t\tWeight3D_[i][j][k] = WHist->GetBinContent(i + 1, j + 1, k + 1);\n\t\t\t}\n\t\t}\n\t}\n\n\tstd::cout << \" 3D Weight Matrix initialized! \" << std::endl;\n\n\treturn;\n\n}\n\nvoid Lumi3DReWeighting::weight3D_init(std::string MCWeightFileName, std::string DataWeightFileName) {\n\n\tboost::scoped_ptr<TFile> infileMC(new TFile(MCWeightFileName.c_str()));\n\tboost::scoped_ptr<TH3D> MHist((TH3D*) infileMC->Get(\"MHist\"));\n\n\t// Check if the histogram exists\n\tif (!MHist) {\n//    throw cms::Exception(\"HistogramNotFound\") << \" Could not find the histogram MHist in the file \"\n//\t\t\t\t\t      << \"in the file \" << MCWeightFileName << \".\" << std::endl;\n\t}\n\n\tboost::scoped_ptr<TFile> infileD(new TFile(DataWeightFileName.c_str()));\n\tboost::scoped_ptr<TH3D> DHist((TH3D*) infileD->Get(\"DHist\"));\n\n\t// Check if the histogram exists\n\tif (!DHist) {\n//    throw cms::Exception(\"HistogramNotFound\") << \" Could not find the histogram DHist in the file \"\n//\t\t\t\t\t      << \"in the file \" << DataWeightFileName << \".\" << std::endl;\n\t}\n\n\tfor (int i = 0; i < NVERTEX; i++) {\n\t\tfor (int j = 0; j < NVERTEX; j++) {\n\t\t\tfor (int k = 0; k < NVERTEX; k++) {\n\t\t\t\tWeight3D_[i][j][k] = DHist->GetBinContent(i + 1, j + 1, k + 1)\n\t\t\t\t\t\t/ MHist->GetBinContent(i + 1, j + 1, k + 1);\n\t\t\t}\n\t\t}\n\t}\n\n\tstd::cout << \" 3D Weight Matrix initialized! \" << std::endl;\n\n\treturn;\n\n}\n\n} /* namespace BAT */\n", "meta": {"hexsha": "6d9864cb335b360add924e535948a32be0905877", "size": 9599, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Lumi3DReWeighting.cpp", "max_stars_repo_name": "jjacob/AnalysisSoftware", "max_stars_repo_head_hexsha": "670513bcde9c3df46077f906246e912627ee251a", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Lumi3DReWeighting.cpp", "max_issues_repo_name": "jjacob/AnalysisSoftware", "max_issues_repo_head_hexsha": "670513bcde9c3df46077f906246e912627ee251a", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Lumi3DReWeighting.cpp", "max_forks_repo_name": "jjacob/AnalysisSoftware", "max_forks_repo_head_hexsha": "670513bcde9c3df46077f906246e912627ee251a", "max_forks_repo_licenses": ["Apache-2.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.6537313433, "max_line_length": 115, "alphanum_fraction": 0.6249609334, "num_tokens": 3273, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6619228758499942, "lm_q2_score": 0.5156199157230156, "lm_q1q2_score": 0.3413006174609101}}
{"text": "#include <iostream>\n#include <string>\n\n#include <boost/algorithm/string/split.hpp>\n\n#include <opts/opts.h>\n#include <dlog/log.h>\n#include <dlog/stats.h>\n\n#include <diy/decomposition.hpp>\n#include <diy/reduce-operations.hpp>\n#include <diy/io/block.hpp>\n\n#include <reeber/format.h>\n\n#include \"reader-interfaces.h\"\n\n#include \"merge-tree-block.h\"\n#include \"persistent-integral-block.h\"\n\ntypedef diy::RegularDecomposer<diy::DiscreteBounds>                 Decomposer;\ntypedef MergeTreeBlock::Vertex                                      Vertex;\ntypedef MergeTreeBlock::Value                                       Value;\n\nbool vv_cmp(const MergeTreeNode::ValueVertex& a, const MergeTreeNode::ValueVertex& b)\n{\n    return a.second < b.second;\n}\n\nclass TreeTracer\n{\n    private:\n        typedef std::map<MergeTreeNode::Vertex, MinIntegral>        MinIntegralMap;\n        typedef MergeTreeBlock::OffsetGrid                          OffsetGrid;\n        typedef std::vector<OffsetGrid*>                            OffsetGridVector;\n\n    public:\n                    TreeTracer(const Decomposer& decomposer_, diy::Master& pi_master_,\n                               Real m_, Real t_, Real e_,\n                               std::vector<std::string> avg_fn_list_,\n                               std::string density_fn_,\n                               bool density_weighted_):\n                         decomposer(decomposer_), pi_master(pi_master_),\n                         m(m_), t(t_), e(e_),\n                         density_reader(0), density_weighted(density_weighted_)\n        {\n            diy::mpi::communicator& world = pi_master_.communicator();\n\n            for(const std::string& fn : avg_fn_list_)\n                avg_var_readers.push_back(Reader::create(fn, world));\n\n            if (!density_fn_.empty())\n                density_reader = Reader::create(density_fn_, world);\n        }\n\n                    ~TreeTracer()\n        {\n            for(Reader* reader : avg_var_readers)\n                delete reader;\n            delete density_reader;\n        }\n\n        void        operator()(void* b, const diy::ReduceProxy& rp) const\n        {\n            MergeTreeBlock &block = *static_cast<MergeTreeBlock*>(b);\n\n            MinIntegralMap mi_map;\n\n            if (rp.in_link().size() == 0)\n            {\n                OffsetGridVector add_data;\n                for(Reader* reader : avg_var_readers)\n                    add_data.push_back(reader->read(block.core));\n                MergeTreeBlock::OffsetGrid *density_data = density_reader ? density_reader->read(block.core) : 0;\n\n                reeber::traverse_persistence(block.mt, Integrator(m,t,e,density_weighted, &mi_map, &block, &add_data, density_data));\n\n                for(const MinIntegral& mi : mi_map | reeber::range::map_values)\n                {\n                    if (block.mt.cmp(m, mi.min_val))\n                        continue;\n\n                    if (mi.integral == 0)                                            // this block doesn't contribute anything to this extremum\n                        continue;\n\n                    int dest_gid = decomposer.point_to_gid(block.global.position(mi.min_vtx));\n                    diy::BlockID dest = rp.out_link().target(dest_gid);              // out_link targets are ordered as gids\n                    assert(dest.gid == dest_gid);\n                    rp.enqueue(dest, mi);\n                }\n\n                for(MergeTreeBlock::OffsetGrid* og : add_data)\n                    delete og;\n                delete density_data;\n            }\n            else\n            {\n                for (int i = 0; i < rp.in_link().size(); ++i)\n                {\n                    int gid = rp.in_link().target(i).gid;\n                    assert(gid == i);\n\n                    while (rp.incoming(gid))\n                    {\n                        MinIntegral mi;\n                        rp.dequeue(gid, mi);\n                        if (mi_map.find(mi.min_vtx) == mi_map.end())\n                            mi_map[mi.min_vtx] = mi;\n                        else\n                            mi_map[mi.min_vtx].combine(mi);\n                    }\n                }\n\n                PersistentIntegralBlock *pi_block = new PersistentIntegralBlock(block);\n                for (MinIntegralMap::const_iterator it = mi_map.begin(); it != mi_map.end(); ++it)\n                    pi_block->add_integral(it->second);\n                pi_master.add(rp.gid(), pi_block, new diy::Link);\n            }\n        }\n\n        struct Integrator\n        {\n            Real                m,t,e;\n            bool                density_weighted;\n            MinIntegralMap*     mi_map_;\n            MergeTreeBlock*     b;\n            OffsetGridVector*   add_data_;\n            OffsetGrid*         density_data;\n\n                        Integrator(Real m_, Real t_, Real e_, bool density_weighted_,\n                                   MinIntegralMap* mi_map, MergeTreeBlock* b_, OffsetGridVector* add_data, OffsetGrid* density_data_):\n                            m(m_), t(t_), e(e_), density_weighted(density_weighted_),\n                            mi_map_(mi_map), b(b_), add_data_(add_data), density_data(density_data_)    {}\n\n            void        operator()(Neighbor from, Neighbor through, Neighbor to) const\n            {\n                MinIntegralMap& mi_map = *mi_map_;\n\n                // contribution of the edge from -- from->parent to the integral of from\n                mi_map[from->vertex].combine(integrate(from));\n\n                // figure out the contribution of the edge through -- through->parent to the integral of to\n                bool record_through = through->children.size() == 2;\n                if (!record_through && from != to)    // if we have more than 2 children record through when processing the highest one (lexicographically)\n                {\n                    Neighbor n = 0;\n                    for (size_t i = 0; i < through->children.size(); ++i)\n                    {\n                        Neighbor nc = through->children[i];\n                        if (static_cast<Neighbor>(nc->aux) != to && nc > n)\n                            n = nc;\n                    }\n\n                    if (n == 0)\n                        assert(from == to);\n                    else if (static_cast<Neighbor>(n->aux) == from)\n                        record_through = true;\n                }\n\n                if (record_through && from != to)\n                    mi_map[to->vertex].combine(integrate(through));\n\n                // if we are not looking at the global pair, add the entire from-integral (now correct) to the integral of to\n                if (from != to && !b->mt.cmp(t, through->value))\n                    mi_map[to->vertex].combine(mi_map[from->vertex]);\n\n                // from-through pair is not persistent enough, erase\n                if (from->value/through->value < e)     // we should make this more generic somehow\n                    mi_map.erase(from->vertex);\n                else\n                {\n                    // fix the integral id (initialized to zero up until now)\n                    MinIntegral mi(from);\n                    mi.combine(mi_map[from->vertex]);\n                    mi_map[from->vertex] = mi;\n                }\n            }\n\n            void        integrate(MinIntegral& mi, Value val, MergeTree::Vertex vrt) const\n            {\n                OffsetGridVector& add_data = *add_data_;\n\n                if (b->core.contains(vrt) && !b->mt.cmp(t, val))\n                {\n                    mi.integral += val * b->cell_size[0] * b->cell_size[1] * b->cell_size[2];\n                    ++mi.n_cells;\n                    for (size_t i = 0; i < add_data.size(); ++i)\n                    {\n                        Real new_val = (*add_data[i])(vrt);\n                        if (density_data)\n                            new_val /= (*density_data)(vrt);\n                        if (density_weighted)\n                            new_val *= val * b->cell_size[0] * b->cell_size[1] * b->cell_size[2];\n                        mi.add_sums[i] += new_val;\n                    }\n                    mi.push_back(MergeTreeNode::ValueVertex(val, vrt));\n                }\n            }\n\n            MinIntegral integrate(Neighbor n) const\n            {\n                MinIntegral mi;\n\n                integrate(mi, n->value, n->vertex);\n\n                for(const MergeTree::Node::ValueVertex& x : n->vertices)\n                    integrate(mi, x.first, x.second);\n\n                return mi;\n            }\n        };\n\n    private:\n        const Decomposer&    decomposer;\n        diy::Master&         pi_master;\n        Real                 m;\n        Real                 t;\n        Real                 e;\n        std::vector<Reader*> avg_var_readers;\n        Reader*              density_reader;\n        bool                 density_weighted;\n};\n\nstruct OutputIntegrals\n{\n                    OutputIntegrals(std::string outfn_, bool density_weighted_, bool verbose_):\n                        outfn(outfn_), density_weighted(density_weighted_), verbose(verbose_)   {}\n\n       void         operator()(PersistentIntegralBlock* b, const diy::Master::ProxyWithLink& cp) const\n       {\n           PersistentIntegralBlock&  block = *b;\n\n           std::string   dgm_fn = fmt::format(\"{}-b{}.comp\", outfn, block.gid);\n           std::ofstream ofs(dgm_fn.c_str());\n \n           for(MinIntegral &mi : block.persistent_integrals)\n           {\n               Vertex v = block.global.position(mi.min_vtx);\n               ofs << v[0] * block.cell_size[0] << \" \" << v[1] * block.cell_size[1] << \" \" << v[2] * block.cell_size[2] << \" \";\n               if (verbose)\n                   ofs << v[0] << \"x\" << v[1] << \"x\" << v[2] << \" (\" << mi.min_vtx << \") \";\n               ofs <<  mi.integral;\n               if (verbose)\n                   ofs << \" \" << mi.n_cells;\n               for(Real sum : mi.add_sums)\n                   ofs << \" \" << sum / (density_weighted ? mi.integral : mi.n_cells);\n               ofs << std::endl;\n#ifdef REEBER_PERSISTENT_INTEGRAL_TRACE_VTCS\n               std::sort(mi.vertices.begin(), mi.vertices.end(), vv_cmp);\n               for (std::vector< MergeTreeNode::ValueVertex >::const_iterator it = mi.vertices.begin(); it != mi.vertices.end(); ++it)\n                   ofs << \"   \" << it->second << \" (\" << block.global.position(it->second) <<  \")\" << std::endl;\n#if 1\n               // Consistency check for debugging\n               for (size_t i = 0; i < mi.vertices.size() - 1; ++i)\n                   if (mi.vertices[i].second == mi.vertices[i+1].second)\n                       LOG_SEV(fatal) << \"Duplicate vertex \" << mi.vertices[i].second << \" in component \" << mi.min_vtx;\n#endif\n#endif\n           }\n       }\n\n    private:\n        std::string outfn;\n        bool        density_weighted;\n        bool        verbose;\n};\n\nint main(int argc, char** argv)\n{\n    diy::mpi::environment   env(argc, argv);\n    diy::mpi::communicator  world;\n#ifdef REEBER_USE_BOXLIB_READER\n    reeber::io::BoxLib::environment boxlib_env(argc, argv, world);\n#endif\n\n    using namespace opts;\n\n    std::string prefix      = \"./DIY.XXXXXX\";\n    int         in_memory   = -1;\n    int         threads     = 1;\n    int         k           = 2;\n    Real        m           = 200;\n    Real        t           = 82;\n    Real        e           = m - t;\n\n    std::string profile_path;\n    std::string log_level = \"info\";\n    std::string avg_fn_str = \"\";\n    std::string density_fn = \"\";\n\n    Options ops(argc, argv);\n    ops\n        >> Option('m', \"memory\",    in_memory,    \"maximum blocks to store in memory\")\n        >> Option('j', \"jobs\",      threads,      \"threads to use during the computation\")\n        >> Option('k', \"k\",         k,            \"use k-ary swap\")\n        >> Option('s', \"storage\",   prefix,       \"storage prefix\")\n        >> Option('p', \"profile\",   profile_path, \"path to keep the execution profile\")\n        >> Option('l', \"log\",       log_level,    \"log level\")\n        >> Option('x', \"max\",       m,            \"maximum threshold\")\n        >> Option('i', \"iso\",       t,            \"isofind threshold\")\n        >> Option('e', \"epsilon\",   e,            \"persistence threshold\")\n        >> Option('f', \"mean\",      avg_fn_str,   \"list of additionals files/variables to average separated by ','\")\n        >> Option('q', \"quotient\",  density_fn,   \"divide by density in file\")\n    ;\n    bool absolute         = ops >> Present('a', \"absolute\", \"use absolute values for thresholds (instead of multiples of mean)\");\n    bool verbose          = ops >> Present('v', \"verbose\",  \"verbose output: logical coordiantes and number of cells\");\n    bool density_weighted = ops >> Present('w', \"weight\",   \"compute density-weighted averages\");\n    bool split            = ops >> Present(     \"split\",    \"use split IO\");\n\n    std::string infn, outfn;\n    if (  ops >> Present('h', \"help\", \"show help message\") ||\n        !(ops >> PosOption(infn) >> PosOption(outfn)))\n    {\n        if (world.rank() == 0)\n        {\n            fmt::print(\"Usage: {} IN.lgt OUT.pi\\n{}\", argv[0], ops);\n        }\n        return 1;\n    }\n\n    std::vector<std::string> avg_fn_list;\n    if (!avg_fn_str.empty())\n        boost::split(avg_fn_list, avg_fn_str, std::bind1st(std::equal_to<char>(), ','));\n\n    dlog::add_stream(std::cerr, dlog::severity(log_level))\n        << dlog::stamp() << dlog::aux_reporter(world.rank()) << dlog::color_pre() << dlog::level() << dlog::color_post() >> dlog::flush();\n\n    std::ofstream   profile_stream;\n    if (profile_path == \"-\")\n        dlog::prof.add_stream(std::cerr);\n    else if (!profile_path.empty())\n    {\n        std::string profile_fn = fmt::format(\"{}-r{}.prf\", profile_path, world.rank());\n        profile_stream.open(profile_fn.c_str());\n        dlog::prof.add_stream(profile_stream);\n    }\n\n    world.barrier();\n    dlog::Timer timer;\n    LOG_SEV_IF(world.rank() == 0, info) << \"Starting computation\";\n\n    diy::FileStorage            storage(prefix);\n\n    diy::Master                 mt_master(world,\n                                          threads,\n                                          in_memory,\n                                          &MergeTreeBlock::create,\n                                          &MergeTreeBlock::destroy,\n                                          &storage,\n                                          &MergeTreeBlock::save,\n                                          &MergeTreeBlock::load);\n\n    diy::Master                 pi_master(world,\n                                          threads,\n                                          in_memory);\n\n    diy::ContiguousAssigner     assigner(world.size(), 0);\n\n    // load the trees\n    LOG_SEV_IF(world.rank() == 0, debug) << \"Reading blocks from \" << infn;\n    if (!split)\n        diy::io::read_blocks(infn, world, assigner, mt_master);\n    else\n        diy::io::split::read_blocks(infn, world, assigner, mt_master);\n    LOG_SEV_IF(world.rank() == 0, info) << \"Blocks read: \" << mt_master.size();\n\n    world.barrier();\n    LOG_SEV_IF(world.rank() == 0, info) << \"Time to read data:                    \" << dlog::clock_to_string(timer.elapsed());\n    timer.restart();\n\n    // get the domain bounds from any block that's in memory (they are all the same) and set up a decomposer\n    MergeTreeBlock::Box global = static_cast<MergeTreeBlock*>(((const diy::Master&) mt_master).block(mt_master.loaded_block()))->global;\n    diy::DiscreteBounds domain {3};\n    for (unsigned i = 0; i < 3; ++i)\n    {\n        domain.min[i] = global.from()[i];\n        domain.max[i] = global.to()[i];\n    }\n    diy::RegularDecomposer<diy::DiscreteBounds>     decomposer(3, domain, assigner.nblocks(), Decomposer::BoolVector(3, true));\n\n    // Compute average\n    if (!absolute)\n    {\n        mt_master.foreach(&MergeTreeBlock::compute_average);\n        mt_master.exchange();\n\n        const diy::Master::ProxyWithLink& proxy = mt_master.proxy(mt_master.loaded_block());\n        double mean = proxy.get<double>() / proxy.get<size_t>();\n        m *= mean;\n        t *= mean;\n\n        LOG_SEV_IF(world.rank() == 0, info) << \"Average value is \" << mean << \". Using isofind threshold of \" << t << \" and maximum threshold of \" << m;\n    }\n\n    // Compute and combine persistent integrals\n    diy::all_to_all(mt_master, assigner, TreeTracer(decomposer, pi_master, m, t, e, avg_fn_list, density_fn, density_weighted), k);\n\n    world.barrier();\n    LOG_SEV_IF(world.rank() == 0, info) << \"Time to compute persistent integrals: \" << dlog::clock_to_string(timer.elapsed());\n    timer.restart();\n\n    // Save persistent integrals to file\n    pi_master.foreach(OutputIntegrals(outfn, density_weighted, verbose));\n\n    world.barrier();\n    LOG_SEV_IF(world.rank() == 0, info) << \"Time to output persistent integrals:  \" << dlog::clock_to_string(timer.elapsed());\n    timer.restart();\n\n    dlog::prof.flush();     // TODO: this is necessary because the profile file will close before\n                            //       the global dlog::prof goes out of scope and flushes the events.\n                            //       Need to eventually fix this.\n    dlog::stats.flush();\n}\n", "meta": {"hexsha": "812c2d7e84eabd216e782d9ce6aa161b7a49c5da", "size": 17205, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/local-global/nested-integral-lg.cpp", "max_stars_repo_name": "skn123/reeber", "max_stars_repo_head_hexsha": "7fe16b6addef2c7b2289a40afa0064d9299fcc5e", "max_stars_repo_licenses": ["BSD-3-Clause-LBNL"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2020-07-08T03:39:37.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-30T18:20:39.000Z", "max_issues_repo_path": "examples/local-global/nested-integral-lg.cpp", "max_issues_repo_name": "skn123/reeber", "max_issues_repo_head_hexsha": "7fe16b6addef2c7b2289a40afa0064d9299fcc5e", "max_issues_repo_licenses": ["BSD-3-Clause-LBNL"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-08-28T16:51:53.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-01T02:12:34.000Z", "max_forks_repo_path": "examples/local-global/nested-integral-lg.cpp", "max_forks_repo_name": "skn123/reeber", "max_forks_repo_head_hexsha": "7fe16b6addef2c7b2289a40afa0064d9299fcc5e", "max_forks_repo_licenses": ["BSD-3-Clause-LBNL"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2020-07-22T23:24:11.000Z", "max_forks_repo_forks_event_max_datetime": "2020-08-28T16:27:39.000Z", "avg_line_length": 41.5579710145, "max_line_length": 155, "alphanum_fraction": 0.5077012496, "num_tokens": 3826, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7341195152660688, "lm_q2_score": 0.46490157137338844, "lm_q1q2_score": 0.3412933162230656}}
{"text": "/*\r\n [auto_generated]\r\n boost/numeric/odeint/stepper/rosenbrock4.hpp\r\n\r\n [begin_description]\r\n Implementation of the Rosenbrock 4 method for solving stiff ODEs. Note, that a\r\n controller and a dense-output stepper exist for this method,\r\n [end_description]\r\n\r\n Copyright 2009-2011 Karsten Ahnert\r\n Copyright 2009-2011 Mario Mulansky\r\n\r\n Distributed under the Boost Software License, Version 1.0.\r\n (See accompanying file LICENSE_1_0.txt or\r\n copy at http://www.boost.org/LICENSE_1_0.txt)\r\n */\r\n\r\n\r\n#ifndef BOOST_NUMERIC_ODEINT_STEPPER_ROSENBROCK4_HPP_INCLUDED\r\n#define BOOST_NUMERIC_ODEINT_STEPPER_ROSENBROCK4_HPP_INCLUDED\r\n\r\n\r\n#include <boost/numeric/odeint/util/bind.hpp>\r\n#include <boost/numeric/odeint/util/unwrap_reference.hpp>\r\n#include <boost/numeric/ublas/vector.hpp>\r\n#include <boost/numeric/ublas/matrix.hpp>\r\n#include <boost/numeric/ublas/lu.hpp>\r\n\r\n#include <boost/numeric/odeint/stepper/stepper_categories.hpp>\r\n\r\n#include <boost/numeric/odeint/util/ublas_wrapper.hpp>\r\n#include <boost/numeric/odeint/util/is_resizeable.hpp>\r\n#include <boost/numeric/odeint/util/resizer.hpp>\r\n\r\n#include <boost/numeric/ublas/vector.hpp>\r\n#include <boost/numeric/ublas/matrix.hpp>\r\n#include <boost/numeric/ublas/lu.hpp>\r\n\r\n\r\nnamespace boost {\r\nnamespace numeric {\r\nnamespace odeint {\r\n\r\n\r\n/*\r\n * ToDo:\r\n *\r\n * 2. Interfacing for odeint, check if controlled_error_stepper can be used\r\n * 3. dense output\r\n */\r\n\r\n\r\n\r\ntemplate< class Value >\r\nstruct default_rosenbrock_coefficients\r\n{\r\n    typedef Value value_type;\r\n    typedef unsigned short order_type;\r\n\r\n    default_rosenbrock_coefficients( void )\r\n    : gamma ( static_cast< value_type >( 0.25 ) ) ,\r\n      d1 ( static_cast< value_type >( 0.25 ) ) ,\r\n      d2 ( static_cast< value_type >( -0.1043 ) ) ,\r\n      d3 ( static_cast< value_type >( 0.1035 ) ) ,\r\n      d4 ( static_cast< value_type >( 0.3620000000000023e-01 ) ) ,\r\n      c2 ( static_cast< value_type >( 0.386 ) ) ,\r\n      c3 ( static_cast< value_type >( 0.21 ) ) ,\r\n      c4 ( static_cast< value_type >( 0.63 ) ) ,\r\n      c21 ( static_cast< value_type >( -0.5668800000000000e+01 ) ) ,\r\n      a21 ( static_cast< value_type >( 0.1544000000000000e+01 ) ) ,\r\n      c31 ( static_cast< value_type >( -0.2430093356833875e+01 ) ) ,\r\n      c32 ( static_cast< value_type >( -0.2063599157091915e+00 ) ) ,\r\n      a31 ( static_cast< value_type >( 0.9466785280815826e+00 ) ) ,\r\n      a32 ( static_cast< value_type >( 0.2557011698983284e+00 ) ) ,\r\n      c41 ( static_cast< value_type >( -0.1073529058151375e+00 ) ) ,\r\n      c42 ( static_cast< value_type >( -0.9594562251023355e+01 ) ) ,\r\n      c43 ( static_cast< value_type >( -0.2047028614809616e+02 ) ) ,\r\n      a41 ( static_cast< value_type >( 0.3314825187068521e+01 ) ) ,\r\n      a42 ( static_cast< value_type >( 0.2896124015972201e+01 ) ) ,\r\n      a43 ( static_cast< value_type >( 0.9986419139977817e+00 ) ) ,\r\n      c51 ( static_cast< value_type >( 0.7496443313967647e+01 ) ) ,\r\n      c52 ( static_cast< value_type >( -0.1024680431464352e+02 ) ) ,\r\n      c53 ( static_cast< value_type >( -0.3399990352819905e+02 ) ) ,\r\n      c54 ( static_cast< value_type >(  0.1170890893206160e+02 ) ) ,\r\n      a51 ( static_cast< value_type >( 0.1221224509226641e+01 ) ) ,\r\n      a52 ( static_cast< value_type >( 0.6019134481288629e+01 ) ) ,\r\n      a53 ( static_cast< value_type >( 0.1253708332932087e+02 ) ) ,\r\n      a54 ( static_cast< value_type >( -0.6878860361058950e+00 ) ) ,\r\n      c61 ( static_cast< value_type >( 0.8083246795921522e+01 ) ) ,\r\n      c62 ( static_cast< value_type >( -0.7981132988064893e+01 ) ) ,\r\n      c63 ( static_cast< value_type >( -0.3152159432874371e+02 ) ) ,\r\n      c64 ( static_cast< value_type >( 0.1631930543123136e+02 ) ) ,\r\n      c65 ( static_cast< value_type >( -0.6058818238834054e+01 ) ) ,\r\n      d21 ( static_cast< value_type >( 0.1012623508344586e+02 ) ) ,\r\n      d22 ( static_cast< value_type >( -0.7487995877610167e+01 ) ) ,\r\n      d23 ( static_cast< value_type >( -0.3480091861555747e+02 ) ) ,\r\n      d24 ( static_cast< value_type >( -0.7992771707568823e+01 ) ) ,\r\n      d25 ( static_cast< value_type >( 0.1025137723295662e+01 ) ) ,\r\n      d31 ( static_cast< value_type >( -0.6762803392801253e+00 ) ) ,\r\n      d32 ( static_cast< value_type >( 0.6087714651680015e+01 ) ) ,\r\n      d33 ( static_cast< value_type >( 0.1643084320892478e+02 ) ) ,\r\n      d34 ( static_cast< value_type >( 0.2476722511418386e+02 ) ) ,\r\n      d35 ( static_cast< value_type >( -0.6594389125716872e+01 ) )\r\n    {}\r\n\r\n    const value_type gamma;\r\n    const value_type d1 , d2 , d3 , d4;\r\n    const value_type c2 , c3 , c4;\r\n    const value_type c21 ;\r\n    const value_type a21;\r\n    const value_type c31 , c32;\r\n    const value_type a31 , a32;\r\n    const value_type c41 , c42 , c43;\r\n    const value_type a41 , a42 , a43;\r\n    const value_type c51 , c52 , c53 , c54;\r\n    const value_type a51 , a52 , a53 , a54;\r\n    const value_type c61 , c62 , c63 , c64 , c65;\r\n    const value_type d21 , d22 , d23 , d24 , d25;\r\n    const value_type d31 , d32 , d33 , d34 , d35;\r\n\r\n    static const order_type stepper_order = 4;\r\n    static const order_type error_order = 3;\r\n};\r\n\r\n\r\n\r\ntemplate< class Value , class Coefficients = default_rosenbrock_coefficients< Value > , class Resizer = initially_resizer >\r\nclass rosenbrock4\r\n{\r\nprivate:\r\n\r\npublic:\r\n\r\n    typedef Value value_type;\r\n    typedef boost::numeric::ublas::vector< value_type > state_type;\r\n    typedef state_type deriv_type;\r\n    typedef value_type time_type;\r\n    typedef boost::numeric::ublas::matrix< value_type > matrix_type;\r\n    typedef boost::numeric::ublas::permutation_matrix< size_t > pmatrix_type;\r\n    typedef Resizer resizer_type;\r\n    typedef Coefficients rosenbrock_coefficients;\r\n    typedef stepper_tag stepper_category;\r\n    typedef unsigned short order_type;\r\n\r\n    typedef state_wrapper< state_type > wrapped_state_type;\r\n    typedef state_wrapper< deriv_type > wrapped_deriv_type;\r\n    typedef state_wrapper< matrix_type > wrapped_matrix_type;\r\n    typedef state_wrapper< pmatrix_type > wrapped_pmatrix_type;\r\n\r\n    typedef rosenbrock4< Value , Coefficients , Resizer > stepper_type;\r\n\r\n    const static order_type stepper_order = rosenbrock_coefficients::stepper_order;\r\n    const static order_type error_order = rosenbrock_coefficients::error_order;\r\n\r\n    rosenbrock4( void )\r\n    : m_resizer() , m_x_err_resizer() ,\r\n      m_jac() , m_pm() ,\r\n      m_dfdt() , m_dxdt() , m_dxdtnew() ,\r\n      m_g1() , m_g2() , m_g3() , m_g4() , m_g5() ,\r\n      m_cont3() , m_cont4() , m_xtmp() , m_x_err() ,\r\n      m_coef()\r\n    { }\r\n\r\n\r\n    order_type order() const { return stepper_order; } \r\n\r\n    template< class System >\r\n    void do_step( System system , const state_type &x , time_type t , state_type &xout , time_type dt , state_type &xerr )\r\n    {\r\n        // get the system and jacobi function\r\n        typedef typename odeint::unwrap_reference< System >::type system_type;\r\n        typedef typename odeint::unwrap_reference< typename system_type::first_type >::type deriv_func_type;\r\n        typedef typename odeint::unwrap_reference< typename system_type::second_type >::type jacobi_func_type;\r\n        system_type &sys = system;\r\n        deriv_func_type &deriv_func = sys.first;\r\n        jacobi_func_type &jacobi_func = sys.second;\r\n\r\n        const size_t n = x.size();\r\n\r\n        m_resizer.adjust_size( x , detail::bind( &stepper_type::template resize_impl<state_type> , detail::ref( *this ) , detail::_1 ) );\r\n\r\n        for( size_t i=0 ; i<n ; ++i )\r\n            m_pm.m_v( i ) = i;\r\n\r\n        deriv_func( x , m_dxdt.m_v , t );\r\n        jacobi_func( x , m_jac.m_v , t , m_dfdt.m_v );\r\n\r\n        m_jac.m_v *= -1.0;\r\n        m_jac.m_v += 1.0 / m_coef.gamma / dt * boost::numeric::ublas::identity_matrix< value_type >( n );\r\n        boost::numeric::ublas::lu_factorize( m_jac.m_v , m_pm.m_v );\r\n\r\n        for( size_t i=0 ; i<n ; ++i )\r\n            m_g1.m_v[i] = m_dxdt.m_v[i] + dt * m_coef.d1 * m_dfdt.m_v[i];\r\n        boost::numeric::ublas::lu_substitute( m_jac.m_v , m_pm.m_v , m_g1.m_v );\r\n\r\n\r\n        for( size_t i=0 ; i<n ; ++i )\r\n            m_xtmp.m_v[i] = x[i] + m_coef.a21 * m_g1.m_v[i];\r\n        deriv_func( m_xtmp.m_v , m_dxdtnew.m_v , t + m_coef.c2 * dt );\r\n        for( size_t i=0 ; i<n ; ++i )\r\n            m_g2.m_v[i] = m_dxdtnew.m_v[i] + dt * m_coef.d2 * m_dfdt.m_v[i] + m_coef.c21 * m_g1.m_v[i] / dt;\r\n        boost::numeric::ublas::lu_substitute( m_jac.m_v , m_pm.m_v , m_g2.m_v );\r\n\r\n\r\n        for( size_t i=0 ; i<n ; ++i )\r\n            m_xtmp.m_v[i] = x[i] + m_coef.a31 * m_g1.m_v[i] + m_coef.a32 * m_g2.m_v[i];\r\n        deriv_func( m_xtmp.m_v , m_dxdtnew.m_v , t + m_coef.c3 * dt );\r\n        for( size_t i=0 ; i<n ; ++i )\r\n            m_g3.m_v[i] = m_dxdtnew.m_v[i] + dt * m_coef.d3 * m_dfdt.m_v[i] + ( m_coef.c31 * m_g1.m_v[i] + m_coef.c32 * m_g2.m_v[i] ) / dt;\r\n        boost::numeric::ublas::lu_substitute( m_jac.m_v , m_pm.m_v , m_g3.m_v );\r\n\r\n\r\n        for( size_t i=0 ; i<n ; ++i )\r\n            m_xtmp.m_v[i] = x[i] + m_coef.a41 * m_g1.m_v[i] + m_coef.a42 * m_g2.m_v[i] + m_coef.a43 * m_g3.m_v[i];\r\n        deriv_func( m_xtmp.m_v , m_dxdtnew.m_v , t + m_coef.c4 * dt );\r\n        for( size_t i=0 ; i<n ; ++i )\r\n            m_g4.m_v[i] = m_dxdtnew.m_v[i] + dt * m_coef.d4 * m_dfdt.m_v[i] + ( m_coef.c41 * m_g1.m_v[i] + m_coef.c42 * m_g2.m_v[i] + m_coef.c43 * m_g3.m_v[i] ) / dt;\r\n        boost::numeric::ublas::lu_substitute( m_jac.m_v , m_pm.m_v , m_g4.m_v );\r\n\r\n\r\n        for( size_t i=0 ; i<n ; ++i )\r\n            m_xtmp.m_v[i] = x[i] + m_coef.a51 * m_g1.m_v[i] + m_coef.a52 * m_g2.m_v[i] + m_coef.a53 * m_g3.m_v[i] + m_coef.a54 * m_g4.m_v[i];\r\n        deriv_func( m_xtmp.m_v , m_dxdtnew.m_v , t + dt );\r\n        for( size_t i=0 ; i<n ; ++i )\r\n            m_g5.m_v[i] = m_dxdtnew.m_v[i] + ( m_coef.c51 * m_g1.m_v[i] + m_coef.c52 * m_g2.m_v[i] + m_coef.c53 * m_g3.m_v[i] + m_coef.c54 * m_g4.m_v[i] ) / dt;\r\n        boost::numeric::ublas::lu_substitute( m_jac.m_v , m_pm.m_v , m_g5.m_v );\r\n\r\n        for( size_t i=0 ; i<n ; ++i )\r\n            m_xtmp.m_v[i] += m_g5.m_v[i];\r\n        deriv_func( m_xtmp.m_v , m_dxdtnew.m_v , t + dt );\r\n        for( size_t i=0 ; i<n ; ++i )\r\n            xerr[i] = m_dxdtnew.m_v[i] + ( m_coef.c61 * m_g1.m_v[i] + m_coef.c62 * m_g2.m_v[i] + m_coef.c63 * m_g3.m_v[i] + m_coef.c64 * m_g4.m_v[i] + m_coef.c65 * m_g5.m_v[i] ) / dt;\r\n        boost::numeric::ublas::lu_substitute( m_jac.m_v , m_pm.m_v , xerr );\r\n\r\n        for( size_t i=0 ; i<n ; ++i )\r\n            xout[i] = m_xtmp.m_v[i] + xerr[i];\r\n    }\r\n\r\n    template< class System >\r\n    void do_step( System system , state_type &x , time_type t , time_type dt , state_type &xerr )\r\n    {\r\n        do_step( system , x , t , x , dt , xerr );\r\n    }\r\n\r\n    /*\r\n     * do_step without error output - just calls above functions with and neglects the error estimate\r\n     */\r\n    template< class System >\r\n    void do_step( System system , const state_type &x , time_type t , state_type &xout , time_type dt )\r\n    {\r\n        m_x_err_resizer.adjust_size( x , detail::bind( &stepper_type::template resize_x_err<state_type> , detail::ref( *this ) , detail::_1 ) );\r\n        do_step( system , x , t , xout , dt , m_x_err.m_v );\r\n    }\r\n\r\n    template< class System >\r\n    void do_step( System system , state_type &x , time_type t , time_type dt )\r\n    {\r\n        m_x_err_resizer.adjust_size( x , detail::bind( &stepper_type::template resize_x_err<state_type> , detail::ref( *this ) , detail::_1 ) );\r\n        do_step( system , x , t , dt , m_x_err.m_v );\r\n    }\r\n\r\n    void prepare_dense_output()\r\n    {\r\n        const size_t n = m_g1.m_v.size();\r\n        for( size_t i=0 ; i<n ; ++i )\r\n        {\r\n            m_cont3.m_v[i] = m_coef.d21 * m_g1.m_v[i] + m_coef.d22 * m_g2.m_v[i] + m_coef.d23 * m_g3.m_v[i] + m_coef.d24 * m_g4.m_v[i] + m_coef.d25 * m_g5.m_v[i];\r\n            m_cont4.m_v[i] = m_coef.d31 * m_g1.m_v[i] + m_coef.d32 * m_g2.m_v[i] + m_coef.d33 * m_g3.m_v[i] + m_coef.d34 * m_g4.m_v[i] + m_coef.d35 * m_g5.m_v[i];\r\n        }\r\n    }\r\n\r\n\r\n    void calc_state( time_type t , state_type &x ,\r\n            const state_type &x_old , time_type t_old ,\r\n            const state_type &x_new , time_type t_new )\r\n    {\r\n        const size_t n = m_g1.m_v.size();\r\n        time_type dt = t_new - t_old;\r\n        time_type s = ( t - t_old ) / dt;\r\n        time_type s1 = 1.0 - s;\r\n        for( size_t i=0 ; i<n ; ++i )\r\n            x[i] = x_old[i] * s1 + s * ( x_new[i] + s1 * ( m_cont3.m_v[i] + s * m_cont4.m_v[i] ) );\r\n    }\r\n\r\n\r\n\r\n    template< class StateType >\r\n    void adjust_size( const StateType &x )\r\n    {\r\n        resize_impl( x );\r\n        resize_x_err( x );\r\n    }\r\n\r\n\r\nprotected:\r\n\r\n    template< class StateIn >\r\n    bool resize_impl( const StateIn &x )\r\n    {\r\n        bool resized = false;\r\n        resized |= adjust_size_by_resizeability( m_dxdt , x , typename is_resizeable<deriv_type>::type() );\r\n        resized |= adjust_size_by_resizeability( m_dfdt , x , typename is_resizeable<deriv_type>::type() );\r\n        resized |= adjust_size_by_resizeability( m_dxdtnew , x , typename is_resizeable<deriv_type>::type() );\r\n        resized |= adjust_size_by_resizeability( m_xtmp , x , typename is_resizeable<state_type>::type() );\r\n        resized |= adjust_size_by_resizeability( m_g1 , x , typename is_resizeable<state_type>::type() );\r\n        resized |= adjust_size_by_resizeability( m_g2 , x , typename is_resizeable<state_type>::type() );\r\n        resized |= adjust_size_by_resizeability( m_g3 , x , typename is_resizeable<state_type>::type() );\r\n        resized |= adjust_size_by_resizeability( m_g4 , x , typename is_resizeable<state_type>::type() );\r\n        resized |= adjust_size_by_resizeability( m_g5 , x , typename is_resizeable<state_type>::type() );\r\n        resized |= adjust_size_by_resizeability( m_cont3 , x , typename is_resizeable<state_type>::type() );\r\n        resized |= adjust_size_by_resizeability( m_cont4 , x , typename is_resizeable<state_type>::type() );\r\n        resized |= adjust_size_by_resizeability( m_jac , x , typename is_resizeable<matrix_type>::type() );\r\n        resized |= adjust_size_by_resizeability( m_pm , x , typename is_resizeable<pmatrix_type>::type() );\r\n        return resized;\r\n    }\r\n\r\n    template< class StateIn >\r\n    bool resize_x_err( const StateIn &x )\r\n    {\r\n        return adjust_size_by_resizeability( m_x_err , x , typename is_resizeable<state_type>::type() );\r\n    }\r\n\r\nprivate:\r\n\r\n\r\n    resizer_type m_resizer;\r\n    resizer_type m_x_err_resizer;\r\n\r\n    wrapped_matrix_type m_jac;\r\n    wrapped_pmatrix_type m_pm;\r\n    wrapped_deriv_type m_dfdt , m_dxdt , m_dxdtnew;\r\n    wrapped_state_type m_g1 , m_g2 , m_g3 , m_g4 , m_g5;\r\n    wrapped_state_type m_cont3 , m_cont4;\r\n    wrapped_state_type m_xtmp;\r\n    wrapped_state_type m_x_err;\r\n\r\n    const rosenbrock_coefficients m_coef;\r\n};\r\n\r\n\r\n} // namespace odeint\r\n} // namespace numeric\r\n} // namespace boost\r\n\r\n#endif // BOOST_NUMERIC_ODEINT_STEPPER_ROSENBROCK4_HPP_INCLUDED\r\n", "meta": {"hexsha": "cb024e4fafc52d90264a06d9dc8c140a0e011026", "size": 14916, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/numeric/odeint/stepper/rosenbrock4.hpp", "max_stars_repo_name": "PXLVision/opengv", "max_stars_repo_head_hexsha": "e48f77da4db7b8cee36ec677ed4ff5c5354571bb", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2018-08-22T03:43:30.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-11T18:20:27.000Z", "max_issues_repo_path": "third_party/boost/numeric/odeint/stepper/rosenbrock4.hpp", "max_issues_repo_name": "PXLVision/opengv", "max_issues_repo_head_hexsha": "e48f77da4db7b8cee36ec677ed4ff5c5354571bb", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 7.0, "max_issues_repo_issues_event_min_datetime": "2020-10-06T16:34:12.000Z", "max_issues_repo_issues_event_max_datetime": "2020-12-06T17:29:22.000Z", "max_forks_repo_path": "third_party/boost/numeric/odeint/stepper/rosenbrock4.hpp", "max_forks_repo_name": "PXLVision/opengv", "max_forks_repo_head_hexsha": "e48f77da4db7b8cee36ec677ed4ff5c5354571bb", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 71.0, "max_forks_repo_forks_event_min_datetime": "2015-03-26T10:28:04.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-07T10:09:12.000Z", "avg_line_length": 43.1098265896, "max_line_length": 184, "alphanum_fraction": 0.6283185841, "num_tokens": 4618, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6825737473266735, "lm_q2_score": 0.5, "lm_q1q2_score": 0.34128687366333677}}
{"text": "/*\n * Copyright 2016,\n * François Bleibel,\n * Olivier Stasse,\n *\n * CNRS/AIST\n *\n */\n#include <pinocchio/fwd.hpp>\n#include <sot/core/debug.hh>\n\n#include <sot/dynamic-pinocchio/dynamic-pinocchio.h>\n\n#include <boost/version.hpp>\n#include <boost/filesystem.hpp>\n#include <boost/format.hpp>\n\n#include <pinocchio/algorithm/kinematics.hpp>\n#include <pinocchio/algorithm/center-of-mass.hpp>\n#include <pinocchio/algorithm/jacobian.hpp>\n#include <pinocchio/spatial/motion.hpp>\n#include <pinocchio/algorithm/crba.hpp>\n#include <pinocchio/algorithm/centroidal.hpp>\n#include <pinocchio/multibody/model.hpp>\n\n#include <dynamic-graph/all-commands.h>\n\n#include \"../src/dynamic-command.h\"\n\nusing namespace dynamicgraph::sot;\nusing namespace dynamicgraph;\n\nconst std::string dg::sot::DynamicPinocchio::CLASS_NAME = \"DynamicPinocchio\";\n\nDynamicPinocchio::DynamicPinocchio(const std::string& name)\n    : Entity(name),\n      m_model(NULL),\n      m_data(NULL)\n\n      ,\n      jointPositionSIN(NULL, \"sotDynamicPinocchio(\" + name + \")::input(vector)::position\"),\n      freeFlyerPositionSIN(NULL, \"sotDynamicPinocchio(\" + name + \")::input(vector)::ffposition\"),\n      jointVelocitySIN(NULL, \"sotDynamicPinocchio(\" + name + \")::input(vector)::velocity\"),\n      freeFlyerVelocitySIN(NULL, \"sotDynamicPinocchio(\" + name + \")::input(vector)::ffvelocity\"),\n      jointAccelerationSIN(NULL, \"sotDynamicPinocchio(\" + name + \")::input(vector)::acceleration\"),\n      freeFlyerAccelerationSIN(NULL, \"sotDynamicPinocchio(\" + name + \")::input(vector)::ffacceleration\")\n\n      ,\n      pinocchioPosSINTERN(boost::bind(&DynamicPinocchio::getPinocchioPos, this, _1, _2),\n                          jointPositionSIN << freeFlyerPositionSIN,\n                          \"sotDynamicPinocchio(\" + name + \")::intern(dummy)::pinocchioPos\"),\n      pinocchioVelSINTERN(boost::bind(&DynamicPinocchio::getPinocchioVel, this, _1, _2),\n                          jointVelocitySIN << freeFlyerVelocitySIN,\n                          \"sotDynamicPinocchio(\" + name + \")::intern(dummy)::pinocchioVel\"),\n      pinocchioAccSINTERN(boost::bind(&DynamicPinocchio::getPinocchioAcc, this, _1, _2),\n                          jointAccelerationSIN << freeFlyerAccelerationSIN,\n                          \"sotDynamicPinocchio(\" + name + \")::intern(dummy)::pinocchioAcc\")\n\n      ,\n      newtonEulerSINTERN(boost::bind(&DynamicPinocchio::computeNewtonEuler, this, _1, _2),\n                         pinocchioPosSINTERN << pinocchioVelSINTERN << pinocchioAccSINTERN,\n                         \"sotDynamicPinocchio(\" + name + \")::intern(dummy)::newtoneuler\"),\n      jacobiansSINTERN(boost::bind(&DynamicPinocchio::computeJacobians, this, _1, _2), pinocchioPosSINTERN,\n                       \"sotDynamicPinocchio(\" + name + \")::intern(dummy)::computeJacobians\"),\n      forwardKinematicsSINTERN(boost::bind(&DynamicPinocchio::computeForwardKinematics, this, _1, _2),\n                               pinocchioPosSINTERN << pinocchioVelSINTERN << pinocchioAccSINTERN,\n                               \"sotDynamicPinocchio(\" + name + \")::intern(dummy)::computeForwardKinematics\"),\n      ccrbaSINTERN(boost::bind(&DynamicPinocchio::computeCcrba, this, _1, _2),\n                   pinocchioPosSINTERN << pinocchioVelSINTERN,\n                   \"sotDynamicPinocchio(\" + name + \")::intern(dummy)::computeCcrba\"),\n      zmpSOUT(boost::bind(&DynamicPinocchio::computeZmp, this, _1, _2), newtonEulerSINTERN,\n              \"sotDynamicPinocchio(\" + name + \")::output(vector)::zmp\"),\n      JcomSOUT(boost::bind(&DynamicPinocchio::computeJcom, this, _1, _2), pinocchioPosSINTERN,\n               \"sotDynamicPinocchio(\" + name + \")::output(matrix)::Jcom\"),\n      comSOUT(boost::bind(&DynamicPinocchio::computeCom, this, _1, _2), forwardKinematicsSINTERN,\n              \"sotDynamicPinocchio(\" + name + \")::output(vector)::com\"),\n      inertiaSOUT(boost::bind(&DynamicPinocchio::computeInertia, this, _1, _2), pinocchioPosSINTERN,\n                  \"sotDynamicPinocchio(\" + name + \")::output(matrix)::inertia\"),\n      footHeightSOUT(boost::bind(&DynamicPinocchio::computeFootHeight, this, _1, _2), pinocchioPosSINTERN,\n                     \"sotDynamicPinocchio(\" + name + \")::output(double)::footHeight\"),\n      upperJlSOUT(boost::bind(&DynamicPinocchio::getUpperPositionLimits, this, _1, _2), sotNOSIGNAL,\n                  \"sotDynamicPinocchio(\" + name + \")::output(vector)::upperJl\")\n\n      ,\n      lowerJlSOUT(boost::bind(&DynamicPinocchio::getLowerPositionLimits, this, _1, _2), sotNOSIGNAL,\n                  \"sotDynamicPinocchio(\" + name + \")::output(vector)::lowerJl\")\n\n      ,\n      upperVlSOUT(boost::bind(&DynamicPinocchio::getUpperVelocityLimits, this, _1, _2), sotNOSIGNAL,\n                  \"sotDynamicPinocchio(\" + name + \")::output(vector)::upperVl\")\n\n      ,\n      upperTlSOUT(boost::bind(&DynamicPinocchio::getMaxEffortLimits, this, _1, _2), sotNOSIGNAL,\n                  \"sotDynamicPinocchio(\" + name + \")::output(vector)::upperTl\")\n\n      ,\n      inertiaRotorSOUT(\"sotDynamicPinocchio(\" + name + \")::output(matrix)::inertiaRotor\"),\n      gearRatioSOUT(\"sotDynamicPinocchio(\" + name + \")::output(matrix)::gearRatio\"),\n      inertiaRealSOUT(boost::bind(&DynamicPinocchio::computeInertiaReal, this, _1, _2),\n                      inertiaSOUT << gearRatioSOUT << inertiaRotorSOUT,\n                      \"sotDynamicPinocchio(\" + name + \")::output(matrix)::inertiaReal\"),\n      MomentaSOUT(boost::bind(&DynamicPinocchio::computeMomenta, this, _1, _2), ccrbaSINTERN,\n                  \"sotDynamicPinocchio(\" + name + \")::output(vector)::momenta\"),\n      AngularMomentumSOUT(boost::bind(&DynamicPinocchio::computeAngularMomentum, this, _1, _2), ccrbaSINTERN,\n                          \"sotDynamicPinocchio(\" + name + \")::output(vector)::angularmomentum\"),\n      dynamicDriftSOUT(boost::bind(&DynamicPinocchio::computeTorqueDrift, this, _1, _2), newtonEulerSINTERN,\n                       \"sotDynamicPinocchio(\" + name + \")::output(vector)::dynamicDrift\") {\n  sotDEBUGIN(5);\n\n  // TODO-------------------------------------------\n\n  // if( build ) buildModel();\n  // firstSINTERN.setDependencyType(TimeDependency<int>::BOOL_DEPENDENT);\n  // DEBUG: Why =0? should be function. firstSINTERN.setConstant(0);\n  // endTODO--------------------------------------------\n\n  signalRegistration(jointPositionSIN);\n  signalRegistration(freeFlyerPositionSIN);\n  signalRegistration(jointVelocitySIN);\n  signalRegistration(freeFlyerVelocitySIN);\n  signalRegistration(jointAccelerationSIN);\n  signalRegistration(freeFlyerAccelerationSIN);\n  signalRegistration(zmpSOUT);\n  signalRegistration(comSOUT);\n  signalRegistration(JcomSOUT);\n  signalRegistration(footHeightSOUT);\n  signalRegistration(upperJlSOUT);\n  signalRegistration(lowerJlSOUT);\n  signalRegistration(upperVlSOUT);\n  signalRegistration(upperTlSOUT);\n  signalRegistration(inertiaSOUT);\n  signalRegistration(inertiaRealSOUT);\n  signalRegistration(inertiaRotorSOUT);\n  signalRegistration(gearRatioSOUT);\n  signalRegistration(MomentaSOUT);\n  signalRegistration(AngularMomentumSOUT);\n  signalRegistration(dynamicDriftSOUT);\n\n  //\n  // Commands\n  //\n  std::string docstring;\n  // setFiles\n\n  docstring =\n      \"\\n\"\n      \"    Display the current robot configuration.\\n\"\n      \"\\n\"\n      \"      Input:\\n\"\n      \"        - none \\n\"\n      \"\\n\";\n  addCommand(\"displayModel\", new command::DisplayModel(*this, docstring));\n  docstring =\n      \"    \\n\"\n      \"    Get the dimension of the robot configuration.\\n\"\n      \"    \\n\"\n      \"      Return:\\n\"\n      \"        an unsigned int: the dimension.\\n\"\n      \"    \\n\";\n  addCommand(\"getDimension\", new command::GetDimension(*this, docstring));\n\n  {\n    using namespace ::dg::command;\n    // CreateOpPoint\n    // TODO add operational joints\n    docstring =\n        \"    \\n\"\n        \"    Create an operational point attached to a robot joint local frame.\\n\"\n        \"    \\n\"\n        \"      Input: \\n\"\n        \"        - a string: name of the operational point,\\n\"\n        \"        - a string: name the joint, or among (gaze, left-ankle, right ankle\\n\"\n        \"          , left-wrist, right-wrist, waist, chest).\\n\"\n        \"\\n\";\n    addCommand(\"createOpPoint\", makeCommandVoid2(*this, &DynamicPinocchio::cmd_createOpPointSignals, docstring));\n\n    docstring = docCommandVoid2(\"Create a jacobian (world frame) signal only for one joint.\", \"string (signal name)\",\n                                \"string (joint name)\");\n    addCommand(\"createJacobian\", makeCommandVoid2(*this, &DynamicPinocchio::cmd_createJacobianWorldSignal, docstring));\n\n    docstring = docCommandVoid2(\"Create a jacobian (endeff frame) signal only for one joint.\", \"string (signal name)\",\n                                \"string (joint name)\");\n    addCommand(\"createJacobianEndEff\",\n               makeCommandVoid2(*this, &DynamicPinocchio::cmd_createJacobianEndEffectorSignal, docstring));\n\n    docstring = docCommandVoid2(\n        \"Create a jacobian (endeff frame) signal only for one joint. \"\n        \"The returned jacobian is placed at the joint position, but oriented with the world axis.\",\n        \"string (signal name)\", \"string (joint name)\");\n    addCommand(\"createJacobianEndEffWorld\",\n               makeCommandVoid2(*this, &DynamicPinocchio::cmd_createJacobianEndEffectorWorldSignal, docstring));\n\n    docstring = docCommandVoid2(\"Create a position (matrix homo) signal only for one joint.\", \"string (signal name)\",\n                                \"string (joint name)\");\n    addCommand(\"createPosition\", makeCommandVoid2(*this, &DynamicPinocchio::cmd_createPositionSignal, docstring));\n\n    docstring = docCommandVoid2(\"Create a velocity (vector) signal only for one joint.\", \"string (signal name)\",\n                                \"string (joint name)\");\n    addCommand(\"createVelocity\", makeCommandVoid2(*this, &DynamicPinocchio::cmd_createVelocitySignal, docstring));\n\n    docstring = docCommandVoid2(\"Create an acceleration (vector) signal only for one joint.\", \"string (signal name)\",\n                                \"string (joint name)\");\n    addCommand(\"createAcceleration\",\n               makeCommandVoid2(*this, &DynamicPinocchio::cmd_createAccelerationSignal, docstring));\n    docstring =\n        \"\\n\"\n        \"  Return robot joint names.\\n\\n\";\n    addCommand(\"getJointNames\", new command::GetJointNames(*this, docstring));\n  }\n\n  sphericalJoints.clear();\n\n  sotDEBUG(10) << \"Dynamic class_name address\" << &CLASS_NAME << std::endl;\n  sotDEBUGOUT(5);\n}\n\nDynamicPinocchio::~DynamicPinocchio(void) {\n  sotDEBUGIN(15);\n  // TODO currently, m_model and m_data are pointers owned by the Python interpreter\n  // so we should not delete them.\n  // I (Joseph Mirabel) think it would be wiser to make them belong to this class but\n  // I do not know the impact it has.\n  // if (0!=m_data ) { delete m_data ; m_data =NULL; }\n  // if (0!=m_model) { delete m_model; m_model=NULL; }\n\n  for (std::list<SignalBase<int>*>::iterator iter = genericSignalRefs.begin(); iter != genericSignalRefs.end();\n       ++iter) {\n    SignalBase<int>* sigPtr = *iter;\n    delete sigPtr;\n  }\n  sotDEBUGOUT(15);\n}\n\nvoid DynamicPinocchio::setModel(pinocchio::Model* modelPtr) {\n  this->m_model = modelPtr;\n\n  if (this->m_model->nq > m_model->nv) {\n    if (pinocchio::nv(this->m_model->joints[1]) == 6) sphericalJoints.push_back(3);  // FreeFlyer Orientation\n\n    for (int i = 1; i < this->m_model->njoints; i++)     // 0: universe\n      if (pinocchio::nq(this->m_model->joints[i]) == 4)  // Spherical Joint Only\n        sphericalJoints.push_back(pinocchio::idx_v(this->m_model->joints[i]));\n  }\n}\n\nvoid DynamicPinocchio::setData(pinocchio::Data* dataPtr) { this->m_data = dataPtr; }\n\n/*--------------------------------GETTERS-------------------------------------------*/\n\ndg::Vector& DynamicPinocchio::getLowerPositionLimits(dg::Vector& res, const int&) const {\n  sotDEBUGIN(15);\n  assert(m_model);\n\n  res.resize(m_model->nv);\n  if (!sphericalJoints.empty()) {\n\n    int fillingIndex = 0;  // SoTValue\n    int origIndex = 0;     // PinocchioValue\n    for (std::vector<int>::const_iterator it = sphericalJoints.begin(); it < sphericalJoints.end(); it++) {\n      if (*it - fillingIndex > 0) {\n        res.segment(fillingIndex, *it - fillingIndex) =\n            m_model->lowerPositionLimit.segment(origIndex, *it - fillingIndex);\n\n        // Don't Change this order\n        origIndex += *it - fillingIndex;\n        fillingIndex += *it - fillingIndex;\n      }\n      // Found a Spherical Joint.\n      // Assuming that spherical joint limits are unset\n      // Version C++11 \n      //res(fillingIndex) = std::numeric_limits<double>::lowest();\n      //res(fillingIndex + 1) = std::numeric_limits<double>::lowest();\n      //res(fillingIndex + 2) = std::numeric_limits<double>::lowest();\n      // For now use C++98\n      res(fillingIndex) = -std::numeric_limits<double>::max();\n      res(fillingIndex + 1) = -std::numeric_limits<double>::max();\n      res(fillingIndex + 2) = -std::numeric_limits<double>::max();\n\n      fillingIndex += 3;\n      origIndex += 4;\n    }\n\n    assert(m_model->nv - fillingIndex == m_model->nq - origIndex);\n    if (m_model->nv > fillingIndex)\n      res.segment(fillingIndex, m_model->nv - fillingIndex) =\n          m_model->lowerPositionLimit.segment(origIndex, m_model->nv - fillingIndex);\n  } else {\n    res = m_model->lowerPositionLimit;\n  }\n  sotDEBUG(15) << \"lowerLimit (\" << res << \")=\" << std::endl;\n  sotDEBUGOUT(15);\n  return res;\n}\n\ndg::Vector& DynamicPinocchio::getUpperPositionLimits(dg::Vector& res, const int&) const {\n  sotDEBUGIN(15);\n  assert(m_model);\n\n  res.resize(m_model->nv);\n  if (!sphericalJoints.empty()) {\n    int fillingIndex = 0;  // SoTValue\n    int origIndex = 0;     // PinocchioValue\n    for (std::vector<int>::const_iterator it = sphericalJoints.begin(); it < sphericalJoints.end(); it++) {\n      if (*it - fillingIndex > 0) {\n        res.segment(fillingIndex, *it - fillingIndex) =\n            m_model->upperPositionLimit.segment(origIndex, *it - fillingIndex);\n\n        // Don't Change this order\n        origIndex += *it - fillingIndex;\n        fillingIndex += *it - fillingIndex;\n      }\n      // Found a Spherical Joint.\n      // Assuming that spherical joint limits are unset\n      res(fillingIndex) = std::numeric_limits<double>::max();\n      res(fillingIndex + 1) = std::numeric_limits<double>::max();\n      res(fillingIndex + 2) = std::numeric_limits<double>::max();\n      fillingIndex += 3;\n      origIndex += 4;\n    }\n    assert(m_model->nv - fillingIndex == m_model->nq - origIndex);\n    if (m_model->nv > fillingIndex)\n      res.segment(fillingIndex, m_model->nv - fillingIndex) =\n          m_model->upperPositionLimit.segment(origIndex, m_model->nv - fillingIndex);\n  } else {\n    res = m_model->upperPositionLimit;\n  }\n  sotDEBUG(15) << \"upperLimit (\" << res << \")=\" << std::endl;\n  sotDEBUGOUT(15);\n  return res;\n}\n\ndg::Vector& DynamicPinocchio::getUpperVelocityLimits(dg::Vector& res, const int&) const {\n  sotDEBUGIN(15);\n  assert(m_model);\n\n  res.resize(m_model->nv);\n  res = m_model->velocityLimit;\n\n  sotDEBUG(15) << \"upperVelocityLimit (\" << res << \")=\" << std::endl;\n  sotDEBUGOUT(15);\n  return res;\n}\n\ndg::Vector& DynamicPinocchio::getMaxEffortLimits(dg::Vector& res, const int&) const {\n  sotDEBUGIN(15);\n  assert(m_model);\n\n  res.resize(m_model->nv);\n  res = m_model->effortLimit;\n\n  sotDEBUGOUT(15);\n  return res;\n}\n\n/* ---------------- INTERNAL ------------------------------------------------ */\ndg::Vector& DynamicPinocchio::getPinocchioPos(dg::Vector& q, const int& time) {\n  sotDEBUGIN(15);\n  dg::Vector qJoints = jointPositionSIN.access(time);\n  if (!sphericalJoints.empty()) {\n    if (freeFlyerPositionSIN) {\n      dg::Vector qFF = freeFlyerPositionSIN.access(time);\n      qJoints.head<6>() = qFF;          // Overwrite qJoints ff with ffposition value\n      assert(sphericalJoints[0] == 3);  // FreeFlyer should ideally be present.\n    }\n    q.resize(qJoints.size() + sphericalJoints.size());\n    int fillingIndex = 0;\n    int origIndex = 0;\n    for (std::vector<int>::const_iterator it = sphericalJoints.begin(); it < sphericalJoints.end(); it++) {\n      if (*it - origIndex > 0) {\n        q.segment(fillingIndex, *it - origIndex) = qJoints.segment(origIndex, *it - origIndex);\n        fillingIndex += *it - origIndex;\n        origIndex += *it - origIndex;\n      }\n      assert(*it == origIndex);\n      Eigen::Quaternion<double> temp = Eigen::AngleAxisd(qJoints(origIndex + 2), Eigen::Vector3d::UnitZ()) *\n                                       Eigen::AngleAxisd(qJoints(origIndex + 1), Eigen::Vector3d::UnitY()) *\n                                       Eigen::AngleAxisd(qJoints(origIndex), Eigen::Vector3d::UnitX());\n      q(fillingIndex) = temp.x();\n      q(fillingIndex + 1) = temp.y();\n      q(fillingIndex + 2) = temp.z();\n      q(fillingIndex + 3) = temp.w();\n      fillingIndex += 4;\n      origIndex += 3;\n    }\n    if (qJoints.size() > origIndex)\n      q.segment(fillingIndex, qJoints.size() - origIndex) = qJoints.tail(qJoints.size() - origIndex);\n  } else {\n    q.resize(qJoints.size());\n    q = qJoints;\n  }\n\n  sotDEBUG(15) << \"Position out\" << q << std::endl;\n  sotDEBUGOUT(15);\n  return q;\n}\n\ndg::Vector& DynamicPinocchio::getPinocchioVel(dg::Vector& v, const int& time) {\n  const Eigen::VectorXd vJoints = jointVelocitySIN.access(time);\n  if (freeFlyerVelocitySIN) {\n    const Eigen::VectorXd vFF = freeFlyerVelocitySIN.access(time);\n    if (v.size() != vJoints.size() + vFF.size()) v.resize(vJoints.size() + vFF.size());\n    v << vFF, vJoints;\n    return v;\n  } else {\n    v = vJoints;\n    return v;\n  }\n}\n\ndg::Vector& DynamicPinocchio::getPinocchioAcc(dg::Vector& a, const int& time) {\n  const Eigen::VectorXd aJoints = jointAccelerationSIN.access(time);\n  if (freeFlyerAccelerationSIN) {\n    const Eigen::VectorXd aFF = freeFlyerAccelerationSIN.access(time);\n    if (a.size() != aJoints.size() + aFF.size()) a.resize(aJoints.size() + aFF.size());\n    a << aFF, aJoints;\n    return a;\n  } else {\n    a = aJoints;\n    return a;\n  }\n}\n\n/* --- SIGNAL ACTIVATION ---------------------------------------------------- */\ndg::SignalTimeDependent<dg::Matrix, int>& DynamicPinocchio::createJacobianSignal(const std::string& signame,\n                                                                                 const std::string& jointName) {\n  sotDEBUGIN(15);\n  assert(m_model);\n  dg::SignalTimeDependent<dg::Matrix, int>* sig;\n  if (m_model->existFrame(jointName)) {\n    long int frameId = m_model->getFrameId(jointName);\n    sig = new dg::SignalTimeDependent<dg::Matrix, int>(\n        boost::bind(&DynamicPinocchio::computeGenericJacobian, this, true, frameId, _1, _2), jacobiansSINTERN,\n        \"sotDynamicPinocchio(\" + name + \")::output(matrix)::\" + signame);\n  } else if (m_model->existJointName(jointName)) {\n    long int jointId = m_model->getJointId(jointName);\n    sig = new dg::SignalTimeDependent<dg::Matrix, int>(\n        boost::bind(&DynamicPinocchio::computeGenericJacobian, this, false, jointId, _1, _2), jacobiansSINTERN,\n        \"sotDynamicPinocchio(\" + name + \")::output(matrix)::\" + signame);\n  } else\n    SOT_THROW ExceptionDynamic(ExceptionDynamic::GENERIC, \"Robot has no joint corresponding to \" + jointName);\n\n  genericSignalRefs.push_back(sig);\n  signalRegistration(*sig);\n  sotDEBUGOUT(15);\n  return *sig;\n}\n\ndg::SignalTimeDependent<dg::Matrix, int>& DynamicPinocchio::createEndeffJacobianSignal(const std::string& signame,\n                                                                                       const std::string& jointName,\n                                                                                       const bool isLocal) {\n  sotDEBUGIN(15);\n  assert(m_model);\n  dg::SignalTimeDependent<dg::Matrix, int>* sig;\n\n  if (m_model->existFrame(jointName)) {\n    long int frameId = m_model->getFrameId(jointName);\n    sig = new dg::SignalTimeDependent<dg::Matrix, int>(\n        boost::bind(&DynamicPinocchio::computeGenericEndeffJacobian, this, true, isLocal, frameId, _1, _2),\n        jacobiansSINTERN << forwardKinematicsSINTERN, \"sotDynamicPinocchio(\" + name + \")::output(matrix)::\" + signame);\n  } else if (m_model->existJointName(jointName)) {\n    long int jointId = m_model->getJointId(jointName);\n    sig = new dg::SignalTimeDependent<dg::Matrix, int>(\n        boost::bind(&DynamicPinocchio::computeGenericEndeffJacobian, this, false, isLocal, jointId, _1, _2),\n        jacobiansSINTERN << forwardKinematicsSINTERN, \"sotDynamicPinocchio(\" + name + \")::output(matrix)::\" + signame);\n  } else\n    SOT_THROW ExceptionDynamic(ExceptionDynamic::GENERIC, \"Robot has no joint corresponding to \" + jointName);\n  genericSignalRefs.push_back(sig);\n  signalRegistration(*sig);\n  sotDEBUGOUT(15);\n  return *sig;\n}\n\ndg::SignalTimeDependent<MatrixHomogeneous, int>& DynamicPinocchio::createPositionSignal(const std::string& signame,\n                                                                                        const std::string& jointName) {\n  sotDEBUGIN(15);\n  assert(m_model);\n  dg::SignalTimeDependent<MatrixHomogeneous, int>* sig;\n  if (m_model->existFrame(jointName)) {\n    long int frameId = m_model->getFrameId(jointName);\n    sig = new dg::SignalTimeDependent<MatrixHomogeneous, int>(\n        boost::bind(&DynamicPinocchio::computeGenericPosition, this, true, frameId, _1, _2), forwardKinematicsSINTERN,\n        \"sotDynamicPinocchio(\" + name + \")::output(matrixHomo)::\" + signame);\n  } else if (m_model->existJointName(jointName)) {\n    long int jointId = m_model->getJointId(jointName);\n    sig = new dg::SignalTimeDependent<MatrixHomogeneous, int>(\n        boost::bind(&DynamicPinocchio::computeGenericPosition, this, false, jointId, _1, _2), forwardKinematicsSINTERN,\n        \"sotDynamicPinocchio(\" + name + \")::output(matrixHomo)::\" + signame);\n  } else\n    SOT_THROW ExceptionDynamic(ExceptionDynamic::GENERIC, \"Robot has no joint corresponding to \" + jointName);\n\n  genericSignalRefs.push_back(sig);\n  signalRegistration(*sig);\n  sotDEBUGOUT(15);\n  return *sig;\n}\n\nSignalTimeDependent<dg::Vector, int>& DynamicPinocchio::createVelocitySignal(const std::string& signame,\n                                                                             const std::string& jointName) {\n  sotDEBUGIN(15);\n  assert(m_model);\n  long int jointId = m_model->getJointId(jointName);\n\n  SignalTimeDependent<dg::Vector, int>* sig = new SignalTimeDependent<dg::Vector, int>(\n      boost::bind(&DynamicPinocchio::computeGenericVelocity, this, jointId, _1, _2), forwardKinematicsSINTERN,\n      \"sotDynamicPinocchio(\" + name + \")::output(dg::Vector)::\" + signame);\n  genericSignalRefs.push_back(sig);\n  signalRegistration(*sig);\n\n  sotDEBUGOUT(15);\n  return *sig;\n}\n\ndg::SignalTimeDependent<dg::Vector, int>& DynamicPinocchio::createAccelerationSignal(const std::string& signame,\n                                                                                     const std::string& jointName) {\n  sotDEBUGIN(15);\n  assert(m_model);\n  long int jointId = m_model->getJointId(jointName);\n  dg::SignalTimeDependent<dg::Vector, int>* sig = new dg::SignalTimeDependent<dg::Vector, int>(\n      boost::bind(&DynamicPinocchio::computeGenericAcceleration, this, jointId, _1, _2), forwardKinematicsSINTERN,\n      \"sotDynamicPinocchio(\" + name + \")::output(dg::Vector)::\" + signame);\n\n  genericSignalRefs.push_back(sig);\n  signalRegistration(*sig);\n\n  sotDEBUGOUT(15);\n  return *sig;\n}\n\nvoid DynamicPinocchio::destroyJacobianSignal(const std::string& signame) {\n  sotDEBUGIN(15);\n\n  bool deletable = false;\n  dg::SignalTimeDependent<dg::Matrix, int>* sig = &jacobiansSOUT(signame);\n  for (std::list<SignalBase<int>*>::iterator iter = genericSignalRefs.begin(); iter != genericSignalRefs.end();\n       ++iter) {\n    if ((*iter) == sig) {\n      genericSignalRefs.erase(iter);\n      deletable = true;\n      break;\n    }\n  }\n\n  if (!deletable) {\n    SOT_THROW ExceptionDynamic(ExceptionDynamic::CANT_DESTROY_SIGNAL, \"Cannot destroy signal\",\n                               \" (while trying to remove generic jac. signal <%s>).\", signame.c_str());\n  }\n  signalDeregistration(signame);\n  delete sig;\n}\n\nvoid DynamicPinocchio::destroyPositionSignal(const std::string& signame) {\n  sotDEBUGIN(15);\n  bool deletable = false;\n  dg::SignalTimeDependent<MatrixHomogeneous, int>* sig = &positionsSOUT(signame);\n  for (std::list<SignalBase<int>*>::iterator iter = genericSignalRefs.begin(); iter != genericSignalRefs.end();\n       ++iter) {\n    if ((*iter) == sig) {\n      genericSignalRefs.erase(iter);\n      deletable = true;\n      break;\n    }\n  }\n\n  if (!deletable) {\n    SOT_THROW ExceptionDynamic(ExceptionDynamic::CANT_DESTROY_SIGNAL, \"Cannot destroy signal\",\n                               \" (while trying to remove generic pos. signal <%s>).\", signame.c_str());\n  }\n\n  signalDeregistration(signame);\n\n  delete sig;\n}\n\nvoid DynamicPinocchio::destroyVelocitySignal(const std::string& signame) {\n  sotDEBUGIN(15);\n  bool deletable = false;\n  SignalTimeDependent<dg::Vector, int>* sig = &velocitiesSOUT(signame);\n  for (std::list<SignalBase<int>*>::iterator iter = genericSignalRefs.begin(); iter != genericSignalRefs.end();\n       ++iter) {\n    if ((*iter) == sig) {\n      genericSignalRefs.erase(iter);\n      deletable = true;\n      break;\n    }\n  }\n\n  if (!deletable) {\n    SOT_THROW ExceptionDynamic(ExceptionDynamic::CANT_DESTROY_SIGNAL, \"Cannot destroy signal\",\n                               \" (while trying to remove generic pos. signal <%s>).\", signame.c_str());\n  }\n\n  signalDeregistration(signame);\n\n  delete sig;\n}\n\nvoid DynamicPinocchio::destroyAccelerationSignal(const std::string& signame) {\n  sotDEBUGIN(15);\n  bool deletable = false;\n  dg::SignalTimeDependent<dg::Vector, int>* sig = &accelerationsSOUT(signame);\n  for (std::list<SignalBase<int>*>::iterator iter = genericSignalRefs.begin(); iter != genericSignalRefs.end();\n       ++iter) {\n    if ((*iter) == sig) {\n      genericSignalRefs.erase(iter);\n      deletable = true;\n      break;\n    }\n  }\n\n  if (!deletable) {\n    SOT_THROW ExceptionDynamic(ExceptionDynamic::CANT_DESTROY_SIGNAL, getName() + \":cannot destroy signal\",\n                               \" (while trying to remove generic acc \"\n                               \"signal <%s>).\",\n                               signame.c_str());\n  }\n\n  signalDeregistration(signame);\n\n  delete sig;\n}\n\n/* --------------------- COMPUTE ------------------------------------------------- */\n\ndg::Vector& DynamicPinocchio::computeZmp(dg::Vector& res, const int& time) {\n  // TODO: To be verified\n  sotDEBUGIN(25);\n  assert(m_data);\n  if (res.size() != 3) res.resize(3);\n  newtonEulerSINTERN(time);\n\n  const pinocchio::Force& ftau = m_data->oMi[1].act(m_data->f[1]);\n  const pinocchio::Force::Vector3& tau = ftau.angular();\n  const pinocchio::Force::Vector3& f = ftau.linear();\n  res(0) = -tau[1] / f[2];\n  res(1) = tau[0] / f[2];\n  res(2) = 0;\n\n  sotDEBUGOUT(25);\n\n  return res;\n}\n\n// In world coordinates\n\n// Updates the jacobian matrix in m_data\nint& DynamicPinocchio::computeJacobians(int& dummy, const int& time) {\n  sotDEBUGIN(25);\n  forwardKinematicsSINTERN(time);\n  pinocchio::computeJointJacobians(*m_model, *m_data);\n  sotDEBUG(25) << \"Jacobians updated\" << std::endl;\n  sotDEBUGOUT(25);\n  return dummy;\n}\nint& DynamicPinocchio::computeForwardKinematics(int& dummy, const int& time) {\n  sotDEBUGIN(25);\n  assert(m_model);\n  assert(m_data);\n  const Eigen::VectorXd& q = pinocchioPosSINTERN.access(time);\n  const Eigen::VectorXd& v = pinocchioVelSINTERN.access(time);\n  const Eigen::VectorXd& a = pinocchioAccSINTERN.access(time);\n  pinocchio::forwardKinematics(*m_model, *m_data, q, v, a);\n  sotDEBUG(25) << \"Kinematics updated\" << std::endl;\n  sotDEBUGOUT(25);\n  return dummy;\n}\n\nint& DynamicPinocchio::computeCcrba(int& dummy, const int& time) {\n  sotDEBUGIN(25);\n  const Eigen::VectorXd& q = pinocchioPosSINTERN.access(time);\n  const Eigen::VectorXd& v = pinocchioVelSINTERN.access(time);\n  pinocchio::ccrba(*m_model, *m_data, q, v);\n  sotDEBUG(25) << \"Inertia and Momentum updated\" << std::endl;\n  sotDEBUGOUT(25);\n  return dummy;\n}\n\ndg::Matrix& DynamicPinocchio::computeGenericJacobian(const bool isFrame, const int jointId, dg::Matrix& res,\n                                                     const int& time) {\n  sotDEBUGIN(25);\n  assert(m_model);\n  assert(m_data);\n  if (res.rows() != 6 || res.cols() != m_model->nv) res = Matrix::Zero(6, m_model->nv);\n  jacobiansSINTERN(time);\n\n  pinocchio::JointIndex id =\n      isFrame ? m_model->frames[(pinocchio::JointIndex)jointId].parent : (pinocchio::JointIndex)jointId;\n\n  // Computes Jacobian in world coordinates.\n  pinocchio::getJointJacobian(*m_model, *m_data, id, pinocchio::WORLD, res);\n  sotDEBUGOUT(25);\n  return res;\n}\n\ndg::Matrix& DynamicPinocchio::computeGenericEndeffJacobian(const bool isFrame, const bool isLocal, const int id,\n                                                           dg::Matrix& res, const int& time) {\n  sotDEBUGIN(25);\n  assert(m_model);\n  assert(m_data);\n  if (res.rows() != 6 || res.cols() != m_model->nv) res = Matrix::Zero(6, m_model->nv);\n\n  jacobiansSINTERN(time);\n\n  pinocchio::FrameIndex fid;\n  pinocchio::JointIndex jid;\n  bool changeFrame = !isLocal;\n  pinocchio::SE3 M;\n\n  // Computes Jacobian in end-eff coordinates.\n  if (isFrame) {\n    changeFrame = true;\n    fid = (pinocchio::FrameIndex)id;\n    const pinocchio::Frame& frame = m_model->frames[fid];\n    jid = frame.parent;\n\n    M = frame.placement.inverse();\n    if (!isLocal)  // Express the jacobian is world coordinate system.\n      M.rotation() = m_data->oMf[fid].rotation() * M.rotation();\n  } else {\n    jid = (pinocchio::JointIndex)id;\n    if (!isLocal) {  // Express the jacobian is world coordinate system.\n      M.rotation() = m_data->oMi[jid].rotation();\n      M.translation().setZero();\n    }\n  }\n  pinocchio::getJointJacobian(*m_model, *m_data, jid, pinocchio::LOCAL, res);\n\n  if (changeFrame) pinocchio::motionSet::se3Action(M, res, res);\n\n  sotDEBUGOUT(25);\n  return res;\n}\n\nMatrixHomogeneous& DynamicPinocchio::computeGenericPosition(const bool isFrame, const int id, MatrixHomogeneous& res,\n                                                            const int& time) {\n  sotDEBUGIN(25);\n  forwardKinematicsSINTERN(time);\n  if (isFrame) {\n    const pinocchio::Frame& frame = m_model->frames[id];\n    res.matrix() = (m_data->oMi[frame.parent] * frame.placement).toHomogeneousMatrix();\n  } else {\n    res.matrix() = m_data->oMi[id].toHomogeneousMatrix();\n  }\n  sotDEBUG(25) << \"For \" << (isFrame ? m_model->frames[id].name : m_model->names[id]) << \" with id: \" << id\n               << \" position is \" << res << std::endl;\n  sotDEBUGOUT(25);\n  return res;\n}\n\ndg::Vector& DynamicPinocchio::computeGenericVelocity(const int jointId, dg::Vector& res, const int& time) {\n  sotDEBUGIN(25);\n  forwardKinematicsSINTERN(time);\n  res.resize(6);\n  const pinocchio::Motion& aRV = m_data->v[jointId];\n  res << aRV.linear(), aRV.angular();\n  sotDEBUGOUT(25);\n  return res;\n}\n\ndg::Vector& DynamicPinocchio::computeGenericAcceleration(const int jointId, dg::Vector& res, const int& time) {\n  sotDEBUGIN(25);\n  forwardKinematicsSINTERN(time);\n  res.resize(6);\n  const pinocchio::Motion& aRA = m_data->a[jointId];\n  res << aRA.linear(), aRA.angular();\n  sotDEBUGOUT(25);\n  return res;\n}\n\nint& DynamicPinocchio::computeNewtonEuler(int& dummy, const int& time) {\n  sotDEBUGIN(15);\n  assert(m_model);\n  assert(m_data);\n  const Eigen::VectorXd& q = pinocchioPosSINTERN.access(time);\n  const Eigen::VectorXd& v = pinocchioVelSINTERN.access(time);\n  const Eigen::VectorXd& a = pinocchioAccSINTERN.access(time);\n  pinocchio::rnea(*m_model, *m_data, q, v, a);\n\n  sotDEBUG(1) << \"pos = \" << q << std::endl;\n  sotDEBUG(1) << \"vel = \" << v << std::endl;\n  sotDEBUG(1) << \"acc = \" << a << std::endl;\n\n  sotDEBUGOUT(15);\n  return dummy;\n}\n\ndg::Matrix& DynamicPinocchio::computeJcom(dg::Matrix& Jcom, const int& time) {\n  sotDEBUGIN(25);\n  forwardKinematicsSINTERN(time);\n  Jcom = pinocchio::jacobianCenterOfMass(*m_model, *m_data, false);\n  sotDEBUGOUT(25);\n  return Jcom;\n}\n\ndg::Vector& DynamicPinocchio::computeCom(dg::Vector& com, const int& time) {\n  sotDEBUGIN(25);\n  if (JcomSOUT.needUpdate(time)) {\n    forwardKinematicsSINTERN(time);\n    pinocchio::centerOfMass(*m_model, *m_data, false);\n  }\n  com = m_data->com[0];\n  sotDEBUGOUT(25);\n  return com;\n}\n\ndg::Matrix& DynamicPinocchio::computeInertia(dg::Matrix& res, const int& time) {\n  sotDEBUGIN(25);\n  const Eigen::VectorXd& q = pinocchioPosSINTERN.access(time);\n  res = pinocchio::crba(*m_model, *m_data, q);\n  res.triangularView<Eigen::StrictlyLower>() = res.transpose().triangularView<Eigen::StrictlyLower>();\n  sotDEBUGOUT(25);\n  return res;\n}\n\ndg::Matrix& DynamicPinocchio::computeInertiaReal(dg::Matrix& res, const int& time) {\n  sotDEBUGIN(25);\n\n  const dg::Matrix& A = inertiaSOUT(time);\n  const dg::Vector& gearRatio = gearRatioSOUT(time);\n  const dg::Vector& inertiaRotor = inertiaRotorSOUT(time);\n\n  res = A;\n  for (int i = 0; i < gearRatio.size(); ++i) res(i, i) += (gearRatio(i) * gearRatio(i) * inertiaRotor(i));\n\n  sotDEBUGOUT(25);\n  return res;\n}\n\ndouble& DynamicPinocchio::computeFootHeight(double& res, const int&) {\n  // Ankle position in local foot frame\n  // TODO: Confirm that it is in the foot frame\n  sotDEBUGIN(25);\n  if (!m_model->existJointName(\"r_sole_joint\")) {\n    SOT_THROW ExceptionDynamic(ExceptionDynamic::GENERIC, \"Robot has no joint corresponding to rigthFoot\");\n  }\n  long int jointId = m_model->getJointId(\"r_sole_joint\");\n  Eigen::Vector3d anklePosInLocalRefFrame = m_data->liMi[jointId].translation();\n  // TODO: positive or negative? Current output:negative\n  res = anklePosInLocalRefFrame(2);\n  sotDEBUGOUT(25);\n  return res;\n}\n\ndg::Vector& DynamicPinocchio::computeTorqueDrift(dg::Vector& tauDrift, const int& time) {\n  sotDEBUGIN(25);\n  newtonEulerSINTERN(time);\n  tauDrift = m_data->tau;\n  sotDEBUGOUT(25);\n  return tauDrift;\n}\n\ndg::Vector& DynamicPinocchio::computeMomenta(dg::Vector& Momenta, const int& time) {\n  sotDEBUGIN(25);\n  ccrbaSINTERN(time);\n  if (Momenta.size() != 6) Momenta.resize(6);\n\n  Momenta = m_data->hg.toVector_impl();\n\n  sotDEBUGOUT(25) << \"Momenta :\" << Momenta;\n  return Momenta;\n}\n\ndg::Vector& DynamicPinocchio::computeAngularMomentum(dg::Vector& Momenta, const int& time) {\n  sotDEBUGIN(25);\n  ccrbaSINTERN(time);\n\n  if (Momenta.size() != 3) Momenta.resize(3);\n  Momenta = m_data->hg.angular_impl();\n\n  sotDEBUGOUT(25) << \"AngularMomenta :\" << Momenta;\n  return Momenta;\n}\n\n/* ------------------------ SIGNAL CASTING--------------------------------------- */\n\ndg::SignalTimeDependent<dg::Matrix, int>& DynamicPinocchio::jacobiansSOUT(const std::string& name) {\n  SignalBase<int>& sigabs = Entity::getSignal(name);\n  try {\n    dg::SignalTimeDependent<dg::Matrix, int>& res = dynamic_cast<dg::SignalTimeDependent<dg::Matrix, int>&>(sigabs);\n    return res;\n  } catch (std::bad_cast e) {\n    SOT_THROW ExceptionSignal(ExceptionSignal::BAD_CAST, \"Impossible cast.\",\n                              \" (while getting signal <%s> of type matrix.\", name.c_str());\n  }\n}\ndg::SignalTimeDependent<MatrixHomogeneous, int>& DynamicPinocchio::positionsSOUT(const std::string& name) {\n  SignalBase<int>& sigabs = Entity::getSignal(name);\n  try {\n    dg::SignalTimeDependent<MatrixHomogeneous, int>& res =\n        dynamic_cast<dg::SignalTimeDependent<MatrixHomogeneous, int>&>(sigabs);\n    return res;\n  } catch (std::bad_cast e) {\n    SOT_THROW ExceptionSignal(ExceptionSignal::BAD_CAST, \"Impossible cast.\",\n                              \" (while getting signal <%s> of type matrixHomo.\", name.c_str());\n  }\n}\n\ndg::SignalTimeDependent<dg::Vector, int>& DynamicPinocchio::velocitiesSOUT(const std::string& name) {\n  SignalBase<int>& sigabs = Entity::getSignal(name);\n  try {\n    dg::SignalTimeDependent<dg::Vector, int>& res = dynamic_cast<dg::SignalTimeDependent<dg::Vector, int>&>(sigabs);\n    return res;\n  } catch (std::bad_cast e) {\n    SOT_THROW ExceptionSignal(ExceptionSignal::BAD_CAST, \"Impossible cast.\",\n                              \" (while getting signal <%s> of type Vector.\", name.c_str());\n  }\n}\n\ndg::SignalTimeDependent<dg::Vector, int>& DynamicPinocchio::accelerationsSOUT(const std::string& name) {\n  SignalBase<int>& sigabs = Entity::getSignal(name);\n  try {\n    dg::SignalTimeDependent<dg::Vector, int>& res = dynamic_cast<dg::SignalTimeDependent<dg::Vector, int>&>(sigabs);\n    return res;\n  } catch (std::bad_cast e) {\n    SOT_THROW ExceptionSignal(ExceptionSignal::BAD_CAST, \"Impossible cast.\",\n                              \" (while getting signal <%s> of type Vector.\", name.c_str());\n  }\n}\n\n/*-------------------------------------------------------------------------*/\n\n/*-------------------------------------------------------------------------*/\n\n/* --- PARAMS --------------------------------------------------------------- */\n\n// jointName is either a fixed-joint (pinocchio operational frame) or a\n// movable joint (pinocchio joint-variant).\nvoid DynamicPinocchio::cmd_createOpPointSignals(const std::string& opPointName, const std::string& jointName) {\n  createEndeffJacobianSignal(std::string(\"J\") + opPointName, jointName, true);\n  createPositionSignal(opPointName, jointName);\n}\nvoid DynamicPinocchio::cmd_createJacobianWorldSignal(const std::string& signalName, const std::string& jointName) {\n  createJacobianSignal(signalName, jointName);\n}\nvoid DynamicPinocchio::cmd_createJacobianEndEffectorSignal(const std::string& signalName,\n                                                           const std::string& jointName) {\n  createEndeffJacobianSignal(signalName, jointName, true);\n}\n\nvoid DynamicPinocchio::cmd_createJacobianEndEffectorWorldSignal(const std::string& signalName,\n                                                                const std::string& jointName) {\n  createEndeffJacobianSignal(signalName, jointName, false);\n}\n\nvoid DynamicPinocchio::cmd_createPositionSignal(const std::string& signalName, const std::string& jointName) {\n  createPositionSignal(signalName, jointName);\n}\nvoid DynamicPinocchio::cmd_createVelocitySignal(const std::string& signalName, const std::string& jointName) {\n  createVelocitySignal(signalName, jointName);\n}\nvoid DynamicPinocchio::cmd_createAccelerationSignal(const std::string& signalName, const std::string& jointName) {\n  createAccelerationSignal(signalName, jointName);\n}\n", "meta": {"hexsha": "707f42e7cfa4d38fd009bdd3248e566e7bffc62a", "size": 38311, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/sot-dynamic-pinocchio.cpp", "max_stars_repo_name": "jmirabel/sot-dynamic-pinocchio", "max_stars_repo_head_hexsha": "9ebbca039968a1b8bccdc39d562fd1ca001742f8", "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/sot-dynamic-pinocchio.cpp", "max_issues_repo_name": "jmirabel/sot-dynamic-pinocchio", "max_issues_repo_head_hexsha": "9ebbca039968a1b8bccdc39d562fd1ca001742f8", "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/sot-dynamic-pinocchio.cpp", "max_forks_repo_name": "jmirabel/sot-dynamic-pinocchio", "max_forks_repo_head_hexsha": "9ebbca039968a1b8bccdc39d562fd1ca001742f8", "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.2004197272, "max_line_length": 119, "alphanum_fraction": 0.6481950354, "num_tokens": 10394, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.7279754489059774, "lm_q2_score": 0.4687906266262437, "lm_q1q2_score": 0.34126806686115424}}
{"text": "//==================================================================================================\n/*!\n  @file\n\n  @copyright 2016 NumScale SAS\n\n  Distributed under the Boost Software License, Version 1.0.\n  (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\n*/\n//==================================================================================================\n#ifndef BOOST_SIMD_ARCH_COMMON_SCALAR_FUNCTION_ATAN2_HPP_INCLUDED\n#define BOOST_SIMD_ARCH_COMMON_SCALAR_FUNCTION_ATAN2_HPP_INCLUDED\n#include <boost/simd/function/fast.hpp>\n#include <boost/simd/function/std.hpp>\n\n#include <boost/simd/constant/nan.hpp>\n#include <boost/simd/constant/one.hpp>\n#include <boost/simd/constant/pi.hpp>\n#include <boost/simd/arch/common/detail/tags.hpp>\n#include <boost/simd/arch/common/detail/scalar/f_invtrig.hpp>\n#include <boost/simd/arch/common/detail/scalar/d_invtrig.hpp>\n#include <boost/simd/arch/common/detail/tags.hpp>\n#include <boost/simd/function/copysign.hpp>\n#include <boost/simd/function/if_else.hpp>\n#include <boost/simd/function/if_else_zero.hpp>\n#include <boost/simd/function/is_gtz.hpp>\n#include <boost/simd/function/is_inf.hpp>\n#include <boost/simd/function/is_ltz.hpp>\n#include <boost/simd/function/is_negative.hpp>\n#include <boost/simd/function/is_positive.hpp>\n#include <boost/simd/function/is_nan.hpp>\n#include <boost/simd/function/rec.hpp>\n#include <boost/simd/function/signnz.hpp>\n#include <boost/simd/detail/dispatch/function/overload.hpp>\n#include <boost/config.hpp>\n\nnamespace boost { namespace simd { namespace ext\n{\n  namespace bd = boost::dispatch;\n  namespace bs = boost::simd;\n  BOOST_DISPATCH_OVERLOAD ( atan2_\n                          , (typename A0)\n                          , bd::cpu_\n                          , bd::scalar_< bd::floating_<A0> >\n                          , bd::scalar_< bd::floating_<A0> >\n                          )\n  {\n    BOOST_FORCEINLINE A0 operator() ( A0 a0, A0 a1) const BOOST_NOEXCEPT\n    {\n      #ifndef BOOST_SIMD_NO_NANS\n      if (is_nan(a0) || is_nan(a1)) return Nan<A0>();\n      #endif\n\n      #ifndef BOOST_SIMD_NO_INFINITIES\n      if (is_inf(a0) && is_inf(a1))\n      {\n        a0 = copysign(One<A0>(), a0);\n        a1 = copysign(One<A0>(), a1);\n      }\n      #endif\n      A0 q = bs::abs(a0/a1);\n      A0 z = detail::invtrig_base<A0,tag::radian_tag, tag::not_simd_type>::kernel_atan(q, rec(q));\n      A0 sgn = signnz(a0);\n      z = (is_positive(a1)? z: Pi<A0>()-z)*sgn;\n    return is_eqz(a0) ? if_else_zero(is_negative(a1), Pi<A0>()*sgn) : z;\n    }\n  };\n  BOOST_DISPATCH_OVERLOAD ( atan2_\n                          , (typename A0)\n                          , bd::cpu_\n                          , bs::std_tag\n                          , bd::scalar_< bd::floating_<A0> >\n                          , bd::scalar_< bd::floating_<A0> >\n                          )\n  {\n    BOOST_FORCEINLINE A0 operator() (const std_tag &,  A0 a0, A0 a1) const BOOST_NOEXCEPT\n    {\n      return std::atan2(a0, a1);\n    }\n  };\n  BOOST_DISPATCH_OVERLOAD ( atan2_\n                          , (typename A0)\n                          , bd::cpu_\n                          , bs::fast_tag\n                          , bd::scalar_< bd::floating_<A0> >\n                          , bd::scalar_< bd::floating_<A0> >\n                          )\n  {\n    BOOST_FORCEINLINE A0 operator() (const fast_tag &,  A0 a0, A0 a1) const BOOST_NOEXCEPT\n    {\n      A0 q = bs::abs(a0/a1);\n      A0 z = detail::invtrig_base<A0,tag::radian_tag, tag::not_simd_type>::kernel_atan(q, bs::rec(q));\n      return (is_positive(a1)? z: Pi<A0>()-z)*signnz(a0);\n    }\n  };\n} } }\n\n\n#endif\n", "meta": {"hexsha": "3195eaa01a2d095e02c7654dceac31b3e9ab4d42", "size": 3611, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/arch/common/scalar/function/atan2.hpp", "max_stars_repo_name": "xmar/pythran", "max_stars_repo_head_hexsha": "dbf2e8b70ed1e4d4ac6b5f26ead4add940a72592", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-01-14T12:49:14.000Z", "max_stars_repo_stars_event_max_datetime": "2018-01-14T12:49:14.000Z", "max_issues_repo_path": "third_party/boost/simd/arch/common/scalar/function/atan2.hpp", "max_issues_repo_name": "xmar/pythran", "max_issues_repo_head_hexsha": "dbf2e8b70ed1e4d4ac6b5f26ead4add940a72592", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "third_party/boost/simd/arch/common/scalar/function/atan2.hpp", "max_forks_repo_name": "xmar/pythran", "max_forks_repo_head_hexsha": "dbf2e8b70ed1e4d4ac6b5f26ead4add940a72592", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2017-12-12T12:29:52.000Z", "max_forks_repo_forks_event_max_datetime": "2019-04-08T15:55:25.000Z", "avg_line_length": 36.11, "max_line_length": 102, "alphanum_fraction": 0.5657712545, "num_tokens": 922, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7401743620390163, "lm_q2_score": 0.4610167793123159, "lm_q1q2_score": 0.3412328005167754}}
{"text": "#include \"sev/acp_ros_conversions/conversions.h\"\n\n#include <array>\n#include <chrono>\n#include <cmath>\n#include <cstddef>\n#include <limits>\n#include <sstream>\n#include <utility>\n\n#include \"geometry_msgs/Pose.h\"\n#include \"geometry_msgs/PoseStamped.h\"\n#include \"geometry_msgs/Twist.h\"\n#include \"geometry_msgs/TwistStamped.h\"\n#include \"minkindr_conversions/kindr_msg.h\"\n#include \"std_msgs/Header.h\"\n\n#include \"sev/acp/types.h\"\n\n#include <Eigen/Core>\n\nnamespace sev_conversions {\n\nusing Transformation = kindr::minimal::QuatTransformation;\nusing Position3D = kindr::minimal::Position;\n\n// Conversion from rotation matrix to roll, pitch, yaw angles.\ntemplate <typename Derived>\ninline Eigen::Matrix<typename Derived::Scalar, 3, 1>\nRotationMatrixToRollPitchYaw(const Eigen::MatrixBase<Derived>& rot) {\n  EIGEN_STATIC_ASSERT_MATRIX_SPECIFIC_SIZE(Eigen::MatrixBase<Derived>, 3, 3);\n  Eigen::Matrix<typename Derived::Scalar, 3, 1> rpy;\n  rpy(1, 0) =\n      atan2(-rot(2, 0), sqrt(rot(0, 0) * rot(0, 0) + rot(1, 0) * rot(1, 0)));\n  if (std::abs(cos(rpy(1, 0))) >\n      static_cast<typename Derived::Scalar>(1.0e-12)) {\n    rpy(2, 0) = atan2(rot(1, 0) / cos(rpy(1, 0)), rot(0, 0) / cos(rpy(1, 0)));\n    rpy(0, 0) = atan2(rot(2, 1) / cos(rpy(1, 0)), rot(2, 2) / cos(rpy(1, 0)));\n  } else if (sin(rpy(1, 0)) > static_cast<typename Derived::Scalar>(0)) {\n    rpy(2, 0) = static_cast<typename Derived::Scalar>(0);\n    rpy(0, 0) = atan2(rot(0, 1), rot(1, 1));\n  } else {\n    rpy(2, 0) = static_cast<typename Derived::Scalar>(0);\n    rpy(0, 0) = -atan2(rot(0, 1), rot(1, 1));\n  }\n  return rpy;\n}\n\n// Conversion from roll, pitch, yaw to rotation matrix.\ntemplate <typename Derived>\ninline Eigen::Matrix<typename Derived::Scalar, 3, 3>\nRollPitchYawToRotationMatrix(const Eigen::MatrixBase<Derived>& roll_pitch_yaw) {\n  EIGEN_STATIC_ASSERT_MATRIX_SPECIFIC_SIZE(Eigen::MatrixBase<Derived>, 3, 1);\n  Eigen::Matrix<typename Derived::Scalar, 3, 3> rotation_matrix_x;\n  typename Derived::Scalar zero = static_cast<typename Derived::Scalar>(0.);\n  typename Derived::Scalar one = static_cast<typename Derived::Scalar>(1.);\n  rotation_matrix_x << one, zero, zero, zero, cos(roll_pitch_yaw(0)),\n      -sin(roll_pitch_yaw(0)), zero, sin(roll_pitch_yaw(0)),\n      cos(roll_pitch_yaw(0));\n\n  Eigen::Matrix<typename Derived::Scalar, 3, 3> rotation_matrix_y;\n  rotation_matrix_y << cos(roll_pitch_yaw(1)), zero, sin(roll_pitch_yaw(1)),\n      zero, one, zero, -sin(roll_pitch_yaw(1)), 0, cos(roll_pitch_yaw(1));\n\n  Eigen::Matrix<typename Derived::Scalar, 3, 3> rotation_matrix_z;\n  rotation_matrix_z << cos(roll_pitch_yaw(2)), -sin(roll_pitch_yaw(2)), zero,\n      sin(roll_pitch_yaw(2)), cos(roll_pitch_yaw(2)), zero, zero, zero, one;\n\n  return rotation_matrix_z * rotation_matrix_y * rotation_matrix_x;\n}\n\nusing TimePoint = std::chrono::time_point<std::chrono::system_clock>;\nusing Duration = std::chrono::nanoseconds;\nconstexpr double kNanosecondsToSeconds = 1e-9;\nconstexpr double kSecondsToNanoSeconds = 1e9;\n\ninline TimePoint toTimePoint(const int64_t timestamp_ns) {\n  // Making sure that conversion between TimePoint and int64_t comes at no\n  // runtime cost.\n  static_assert(std::is_same<TimePoint::rep, int64_t>::value, \"\");\n  static_assert(\n      std::is_same<\n          std::chrono::system_clock::period, std::ratio<1, 1000000000>>::value,\n      \"\");\n  return TimePoint{std::chrono::nanoseconds{timestamp_ns}};\n}\n\ninline TimePoint toTimePoint(const ros::Time& ros_time) {\n  const int64_t timestamp_ns = ros_time.toNSec();\n  return toTimePoint(timestamp_ns);\n}\n\ninline int64_t toNs(const TimePoint timestamp) {\n  return timestamp.time_since_epoch().count();\n}\n\ninline ros::Time toRosTime(const TimePoint& time_point) {\n  const int64_t timestamp_ns = toNs(time_point);\n  const int32_t ros_timestamp_sec = timestamp_ns * kNanosecondsToSeconds;\n  const int32_t ros_timestamp_nsec =\n      timestamp_ns % static_cast<int64_t>(kSecondsToNanoSeconds);\n  return ros::Time(ros_timestamp_sec, ros_timestamp_nsec);\n}\n\ninline ros::Time convertNanosecondsInt64ToRosTime(\n    const int64_t timestamp_nanoseconds) {\n  return toRosTime(toTimePoint(timestamp_nanoseconds));\n}\n\ninline int64_t convertRosTimeToNanosecondsInt64(\n    const ros::Time& ros_timestamp) {\n  return toNs(toTimePoint(ros_timestamp));\n}\n}  // namespace sev_conversions\n\nnamespace sev::acp::udp_ros_bridge {\nconstexpr double M_TO_MM = 1000;\n#ifndef M_PI\n#error \"M_PI is not defined (issue with _USE_MATH_DEFINES?)\"\n#endif\nconstexpr double RAD_TO_CDEG = 100 * 180 / M_PI;\n\nstd_msgs::Header convertToRosStamped(sev::acp::MessageHeader const& mh) {\n  std_msgs::Header retval;\n  retval.seq = mh.seq;\n  retval.stamp =\n      sev_conversions::convertNanosecondsInt64ToRosTime(mh.timestamp);\n  return retval;\n}\n\nsev::acp::MessageHeader convertToAcp(const std_msgs::Header& header) {\n  sev::acp::MessageHeader mh;\n  mh.seq = header.seq;\n  mh.timestamp =\n      sev_conversions::convertRosTimeToNanosecondsInt64(header.stamp);\n  return mh;\n}\n\nauto getRotationMatrix(const geometry_msgs::Pose& ros_pose) {\n  // Protection against invalid data.\n  const auto compute_sq_norm = [](const auto& o) {\n    return o.x * o.x + o.y * o.y + o.z * o.z + o.w * o.w;\n  };\n  const auto norm_sq = compute_sq_norm(ros_pose.orientation);\n\n  // Copied from minkindr.\n  // The decision boundary should be at the (binary represented) same number,\n  // therefore using abs() would lead to slightly different decision than in\n  // kindr's CHECK.\n  if ((norm_sq > (1. - 1.e-4)) && (norm_sq < (1. + 1.e-4))) {\n    sev_conversions::Transformation T_M_I;\n    tf::poseMsgToKindr(ros_pose, &T_M_I);\n    return T_M_I.getRotation().getRotationMatrix();\n  } else {\n    std::stringstream ss;\n    ss << \"Encountered non-normalized orientation during conversion:\\n\";\n    ss << ros_pose.orientation;\n    throw ConversionError(ss.str());\n  }\n}\n\ngeometry_msgs::Pose poseFromMatrix(\n    const std::array<double, 3>& position_array,\n    const sev_conversions::Transformation::RotationMatrix& rotation_matrix) {\n  // TODO(pseyfert): Simplify until poseKindrToMsg.\n  if (sev_conversions::Transformation::Rotation::isValidRotationMatrix(\n          rotation_matrix)) {\n    sev_conversions::Position3D position(&position_array[0]);\n    const auto quat_trafo = sev_conversions::Transformation(\n        sev_conversions::Transformation::Rotation{std::move(rotation_matrix)},\n        std::move(position));\n    geometry_msgs::Pose ros_pose;\n    tf::poseKindrToMsg(std::move(quat_trafo), &ros_pose);\n    return ros_pose;\n  } else {\n    std::stringstream ss;\n    ss << \"Encountered invalid rotation during conversion:\\n\";\n    ss << rotation_matrix;\n    throw ConversionError(ss.str());\n  }\n}\n\ngeometry_msgs::Pose poseFromMatrix(\n    const std::array<double, 3>& position_array, const sev::acp::Rot3& R_m_r) {\n  // TODO(pseyfert): Simplify until poseKindrToMsg.\n  sev_conversions::Transformation::RotationMatrix rotation_matrix;\n  for (std::size_t i = 0; i < 9; ++i) {\n    rotation_matrix.data()[i] = R_m_r.mat[i];\n  }\n  return poseFromMatrix(position_array, rotation_matrix);\n}\n\nstd::tuple<sev::acp::Pose> convertToAcp(\n    const geometry_msgs::PoseStamped& ros_message) {\n  sev::acp::Pose out_pose;\n  const auto& ros_pose = ros_message.pose;\n  out_pose.position[0] = ros_pose.position.x;\n  out_pose.position[1] = ros_pose.position.y;\n  out_pose.position[2] = ros_pose.position.z;\n\n  for (std::size_t i = 0; i < 3; ++i) {\n    out_pose.velocity[i] = std::numeric_limits<double>::quiet_NaN();\n  }\n\n  const auto rotation_matrix = getRotationMatrix(ros_pose);\n\n  for (std::size_t i = 0; i < 9; ++i) {\n    out_pose.R_m_r.mat[i] = rotation_matrix.data()[i];\n  }\n  out_pose.yaw =\n      sev_conversions::RotationMatrixToRollPitchYaw(rotation_matrix)[2];\n\n  out_pose.header = convertToAcp(ros_message.header);\n  return std::make_tuple(std::move(out_pose));\n}\n\nstd::tuple<geometry_msgs::PoseStamped> convertToRosStamped(\n    const sev::acp::Pose& acp_pose) {\n  geometry_msgs::PoseStamped ros_pose;\n\n  std::array<double, 3> position;\n  for (std::size_t i = 0; i < position.size(); i++) {\n    position[i] = acp_pose.position[i];\n  }\n  ros_pose.pose = poseFromMatrix(position, acp_pose.R_m_r);\n  // TODO(pseyfert): acp_pose.velocity is ignored.\n\n  ros_pose.header = convertToRosStamped(acp_pose.header);\n  return std::make_tuple(std::move(ros_pose));\n}\n\nstd::tuple<sev::acp::WheelOdometryIntegrated, sev::acp::WheelOdometryInt>\nconvertToAcp(const geometry_msgs::TwistStamped& ros_message) {\n  const auto& linear = ros_message.twist.linear;\n  const auto& angular = ros_message.twist.angular;\n  const auto header = convertToAcp(ros_message.header);\n\n  const auto woi_int = [&]() {\n    sev::acp::WheelOdometryInt woi;\n    const auto buffer =\n        std::array<int, 6>{linear.x * M_TO_MM,      linear.y * M_TO_MM,\n                           linear.z * M_TO_MM,      angular.x * RAD_TO_CDEG,\n                           angular.y * RAD_TO_CDEG, angular.z * RAD_TO_CDEG};\n    // Can't use std::copy because woi.twist is packed and STL algorithms don't\n    // handle packed structs.\n    for (std::size_t i = 0; i < buffer.size(); ++i) {\n      woi.twist[i] = buffer[i];\n    }\n    woi.header = header;\n    return woi;\n  }();\n  const auto woi_integrated = [&]() {\n    sev::acp::WheelOdometryIntegrated woi;\n    const auto buffer = std::array{linear.x,  linear.y,  linear.z,\n                                   angular.x, angular.y, angular.z};\n    // Can't use std::copy because woi.twist is packed and STL algorithms don't\n    // handle packed structs.\n    for (std::size_t i = 0; i < buffer.size(); ++i) {\n      woi.twist[i] = buffer[i];\n    }\n    woi.header = header;\n    return woi;\n  }();\n  return {std::move(woi_integrated), std::move(woi_int)};\n}\n\nstd::tuple<geometry_msgs::TwistStamped> convertToRosStamped(\n    const sev::acp::WheelOdometryIntegrated& woi) {\n  geometry_msgs::TwistStamped ros_message;\n\n  std::size_t i = 0;\n  ros_message.twist.linear.x = woi.twist[i++];\n  ros_message.twist.linear.y = woi.twist[i++];\n  ros_message.twist.linear.z = woi.twist[i++];\n  ros_message.twist.angular.x = woi.twist[i++];\n  ros_message.twist.angular.y = woi.twist[i++];\n  ros_message.twist.angular.z = woi.twist[i++];\n\n  ros_message.header = convertToRosStamped(woi.header);\n  return std::make_tuple(std::move(ros_message));\n}\n\nstd::tuple<sev::acp::OperationState> convertToAcp(\n    const state_machine_msgs::State& status) {\n  sev::acp::OperationState acp;\n  acp.task = status.state_int;\n  acp.stage = status.substate_int;\n  // TODO(pseyfert): Fill with meaningful data.\n  for (std::size_t i = 0; i < 16; ++i) {\n    acp.task_uuid[i] = 0;\n  }\n  acp.optimization_progress = -1;\n  acp.header = convertToAcp(status.header);\n  return std::make_tuple(std::move(acp));\n}\n\nstd::tuple<state_machine_msgs::State> convertToRosStamped(\n    const sev::acp::OperationState& os) {\n  state_machine_msgs::State state;\n  state.state_int = os.task;\n  state.substate_int = os.stage;\n  // TODO(pseyfert): Fill with meaningful data.\n  // state.state =\n  // state.substate =\n  state.header = convertToRosStamped(os.header);\n  return std::make_tuple(std::move(state));\n}\n\n// sev::acp::Notifications\nstd::tuple<sev::acp::Notifications> convertToAcp(\n    const state_machine_msgs::Status& status) {\n  sev::acp::Notifications acp;\n  acp.module_id = status.module;\n  acp.status_code = status.status_code;\n  acp.severity = status.severity;\n  // TODO(pseyfert): Fill with meaningful data.\n  acp.logId = -1;\n  acp.logEntryId = -1;\n  acp.header = convertToAcp(status.header);\n  return std::make_tuple(std::move(acp));\n}\n\nstd::tuple<state_machine_msgs::Status> convertToRosStamped(\n    const sev::acp::Notifications& notifications) {\n  state_machine_msgs::Status status;\n  status.severity = notifications.severity;\n  status.module = notifications.module_id;\n  status.status_code = notifications.status_code;\n  // TODO(pseyfert): Fill with meaningful data.\n  // status.status_text =\n  status.header = convertToRosStamped(notifications.header);\n  return std::make_tuple(std::move(status));\n}\n\nstd::tuple<atlas_msgs::PositioningUpdate> convertToRosStamped(\n    const sev::acp::PoseInt& acp_pose) {\n  atlas_msgs::PositioningUpdate retval;\n  retval.header = convertToRosStamped(acp_pose.header);\n  std::array<double, 3> position;\n  for (std::size_t i = 0; i < 3; ++i) {\n    position[i] = acp_pose.position_mm[i] / M_TO_MM;\n  }\n  Eigen::Matrix<double, 3, 1> angles{\n      acp_pose.roll_cdeg / RAD_TO_CDEG,\n      acp_pose.pitch_cdeg / RAD_TO_CDEG,\n      acp_pose.yaw_cdeg / RAD_TO_CDEG,\n  };\n  const auto rotation_matrix =\n      sev_conversions::RollPitchYawToRotationMatrix(angles);\n  retval.pose = poseFromMatrix(position, rotation_matrix);\n  retval.quality.level = acp_pose.quality;\n  retval.is_relocalization_event = acp_pose.relocalization;\n  return std::make_tuple(std::move(retval));\n}\n\nstd::tuple<sev::acp::PoseFloat, sev::acp::PoseInt> convertToAcp(\n    const atlas_msgs::PositioningUpdate& ros_msg) {\n  const auto rotation_matrix = getRotationMatrix(ros_msg.pose);\n  const auto angles =\n      sev_conversions::RotationMatrixToRollPitchYaw(rotation_matrix);\n  const auto header = convertToAcp(ros_msg.header);\n\n  const auto pose_int = [&]() {\n    sev::acp::PoseInt retval;\n\n    retval.position_mm[0] = ros_msg.pose.position.x * M_TO_MM;\n    retval.position_mm[1] = ros_msg.pose.position.y * M_TO_MM;\n    retval.position_mm[2] = ros_msg.pose.position.z * M_TO_MM;\n\n    for (std::size_t i = 0; i < 3; ++i) {\n      // TODO(pseyfert): Fill with meaningful data.\n      retval.velocity_mmps[i] = 0;\n    }\n    retval.quality = ros_msg.quality.level;\n\n    retval.roll_cdeg = angles[0] * RAD_TO_CDEG;\n    retval.pitch_cdeg = angles[1] * RAD_TO_CDEG;\n    retval.yaw_cdeg = angles[2] * RAD_TO_CDEG;\n\n    retval.relocalization = ros_msg.is_relocalization_event ? 1 : 0;\n\n    retval.header = header;\n    return retval;\n  }();\n\n  const auto pose_float = [&]() {\n    sev::acp::PoseFloat retval;\n\n    retval.position[0] = ros_msg.pose.position.x;\n    retval.position[1] = ros_msg.pose.position.y;\n    retval.position[2] = ros_msg.pose.position.z;\n\n    for (std::size_t i = 0; i < 3; ++i) {\n      retval.velocity[i] = std::numeric_limits<double>::quiet_NaN();\n    }\n    retval.quality = ros_msg.quality.level;\n\n    for (std::size_t i = 0; i < 9; ++i) {\n      retval.rot.mat[i] = rotation_matrix.data()[i];\n    }\n    retval.roll = angles[0];\n    retval.pitch = angles[1];\n    retval.yaw = angles[2];\n\n    retval.relocalization = ros_msg.is_relocalization_event ? 1 : 0;\n\n    retval.header = header;\n    return retval;\n  }();\n\n  return {std::move(pose_float), std::move(pose_int)};\n}\n\nstd::tuple<geometry_msgs::PoseStamped, atlas_msgs::PositioningUpdate>\nconvertToRosStamped(const sev::acp::PoseFloat& acp_pose) {\n  atlas_msgs::PositioningUpdate positioning_update;\n  geometry_msgs::PoseStamped ros_pose;\n\n  std::array<double, 3> position;\n  for (std::size_t i = 0; i < position.size(); i++) {\n    position[i] = acp_pose.position[i];\n  }\n  positioning_update.pose = poseFromMatrix(position, acp_pose.rot);\n  ros_pose.pose = poseFromMatrix(position, acp_pose.rot);\n\n  positioning_update.header = convertToRosStamped(acp_pose.header);\n  ros_pose.header = convertToRosStamped(acp_pose.header);\n  positioning_update.quality.level = acp_pose.quality;\n  positioning_update.is_relocalization_event = acp_pose.relocalization;\n  return std::make_tuple(std::move(ros_pose), std::move(positioning_update));\n}\n\nstd::tuple<geometry_msgs::TwistStamped> convertToRosStamped(\n    const sev::acp::WheelOdometryInt& woi) {\n  geometry_msgs::TwistStamped ros_message;\n\n  std::size_t i = 0;\n  ros_message.twist.linear.x = woi.twist[i++] / M_TO_MM;\n  ros_message.twist.linear.y = woi.twist[i++] / M_TO_MM;\n  ros_message.twist.linear.z = woi.twist[i++] / M_TO_MM;\n  ros_message.twist.angular.x = woi.twist[i++] / RAD_TO_CDEG;\n  ros_message.twist.angular.y = woi.twist[i++] / RAD_TO_CDEG;\n  ros_message.twist.angular.z = woi.twist[i++] / RAD_TO_CDEG;\n\n  ros_message.header = convertToRosStamped(woi.header);\n  return std::make_tuple(std::move(ros_message));\n}\n}  // namespace sev::acp::udp_ros_bridge\n", "meta": {"hexsha": "219813f60b1dc84958be20b34dd0fe272eca8d44", "size": 16067, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "acp_ros_conversions/src/conversions.cpp", "max_stars_repo_name": "sevensense-robotics/alphasense_acp_bridge", "max_stars_repo_head_hexsha": "58482fef6c5d74f8e2e7c5ea34116bf4eb3ceaf4", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-02-03T09:31:31.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-03T09:31:31.000Z", "max_issues_repo_path": "acp_ros_conversions/src/conversions.cpp", "max_issues_repo_name": "sevensense-robotics/alphasense_acp_bridge", "max_issues_repo_head_hexsha": "58482fef6c5d74f8e2e7c5ea34116bf4eb3ceaf4", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "acp_ros_conversions/src/conversions.cpp", "max_forks_repo_name": "sevensense-robotics/alphasense_acp_bridge", "max_forks_repo_head_hexsha": "58482fef6c5d74f8e2e7c5ea34116bf4eb3ceaf4", "max_forks_repo_licenses": ["BSD-3-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.7839643653, "max_line_length": 80, "alphanum_fraction": 0.7051098525, "num_tokens": 4600, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7401743620390162, "lm_q2_score": 0.46101677931231594, "lm_q1q2_score": 0.3412328005167754}}
{"text": "#include <iostream>                  // for std::cout\n#include <utility>                   // for std::pair\n#include <algorithm>                 // for std::for_each\n#include <boost/graph/graph_traits.hpp> // for creation of descriptors vertex and edges.\n#include <boost/graph/adjacency_list.hpp> //for usage of adjacency list\n#include <boost/graph/graphml.hpp>\n#include <boost/graph/connected_components.hpp>\n#include <ilcplex/ilocplex.h>\n#include <boost/pending/disjoint_sets.hpp>\n#include <boost/graph/incremental_components.hpp>\n#include <boost/graph/copy.hpp>\n#include <boost/dynamic_bitset.hpp>\n#include <boost/program_options.hpp>\n#include <boost/algorithm/string/split.hpp>\n#include <boost/algorithm/string/classification.hpp>\n#include <boost/algorithm/string/trim.hpp>\n#include <boost/graph/filtered_graph.hpp>\n#include <boost/random/mersenne_twister.hpp>\n#include <boost/random/uniform_int_distribution.hpp>\n#include <boost/exception/all.hpp>\n#include <exception>\n#include <vector>\nILOSTLBEGIN //initialization make vs work properly\n\nusing namespace boost;\nnamespace po = boost::program_options;\n//basic definitions\ntypedef IloArray<IloNumVarArray> IloVarMatrix;\n\n\ntypedef dynamic_bitset<> db;\ntypedef std::map<int, std::size_t> rank_t; // => order on Element\ntypedef std::map<int, int> parent_t;\n\ntemplate <typename EdgeColorMap, typename ValidColorsMap>\nstruct valid_edge_color {\n\tvalid_edge_color() { }\n\tvalid_edge_color(EdgeColorMap color, ValidColorsMap v_colors) : m_color(color), v_map(v_colors) { }\n\ttemplate <typename Edge>\n\tbool operator()(const Edge& e) const {\n\t\treturn v_map.test(get(m_color, e));\n\t}\n\tEdgeColorMap m_color;\n\tValidColorsMap v_map;\n};\n\n\n\ntemplate<class Graph, class Mask>\nvoid print_filtered_graph(Graph &g, Mask valid) { //pay atention to the position of the bits and the colors positions in array\n\ttypedef typename property_map<Graph, edge_color_t>::type EdgeColorMap;\n\ttypedef typename boost::dynamic_bitset<> db;\n\ttypedef filtered_graph<Graph, valid_edge_color<EdgeColorMap, db> > fg;\n\n\tvalid_edge_color<EdgeColorMap, Mask> filter(get(edge_color, g), valid);\n\tfg tg(g, filter);\n\tprint_edges(edges(tg).first, edges(tg).second, tg);\n}\n//template function to print edges.\ntemplate<class EdgeIter, class Graph>\nvoid print_edges(EdgeIter first, EdgeIter last, const Graph& G) {\n\ttypedef typename property_map<Graph, edge_color_t>::const_type ColorMap;\n\tColorMap colors = get(edge_color, G);\n\t//make color type generic\n\t//typedef typename property_traits<ColorMap>::value_type ColorType;\n\t//ColorType edge_color;\n\tfor (auto it = first; it != last; ++it) {\n\t\tstd::cout << \"Edge: \" << \"(\" << source(*it, G) << \",\" << target(*it, G) << \") \" << \" Color: \" << colors[*it] << \"\\n\";\n\t\tstd::cout << \"Edge: \" << \"(\" << target(*it, G) << \",\" << source(*it, G) << \") \" << \" Color: \" << colors[*it] << \"\\n\";\n\t}\n\tstd::cout << \" Number of vertex: \" << num_vertices(G) << std::endl;\n\tstd::cout << \" Number of edges: \" << num_edges(G) << std::endl;\n\tstd::vector<int> components(num_vertices(G));\n\tint num = connected_components(G, &components[0]);\n\tstd::vector<int>::size_type i;\n\tstd::cout << \"Total number of components: \" << num << std::endl;\n\tfor (i = 0; i != components.size(); ++i)\n\t\tstd::cout << \"Vertex \" << i << \" is in component \" << components[i] << std::endl;\n\tstd::cout << std::endl;\n}\ntemplate<class Graph, class Mask>\nint get_components(Graph &g, Mask &m, vector<int> &components) {\n\ttypedef typename property_map<Graph, edge_color_t>::type EdgeColorMap;\n\ttypedef typename boost::dynamic_bitset<> db;\n\ttypedef filtered_graph<Graph, valid_edge_color<EdgeColorMap, db> > fg;\n\tvalid_edge_color<EdgeColorMap, Mask> filter(get(edge_color, g), m);\n\tfg tg(g, filter);\n\tint num = connected_components(tg, &components[0]);\n\treturn num;\n}\n\n//MVCA modified always has k colors\ntemplate <class Graph>\nint kLSFMVCA(Graph &g, int k_sup, int n_labels) {\n\tstd::vector<int> components(num_vertices(g));\n\tdb temp(n_labels);\n\tint f_colors = n_labels - num_vertices(g) + 1;\n\tint num_c = get_components(g, temp, components);\n\tint num_c_best = num_c;\n\twhile (temp.count() < k_sup) {\n\t\tint best_label = 0;\n\t\tfor (int i = 0; i < f_colors; ++i) {\n\t\t\tif (!temp.test(i)) {\n\t\t\t\ttemp.set(i);\n\t\t\t\tint nc = get_components(g, temp, components);\n\t\t\t\tif (nc <= num_c_best) {\n\t\t\t\t\tnum_c_best = nc;\n\t\t\t\t\tbest_label = i;\n\t\t\t\t}\n\t\t\t\ttemp.flip(i);\n\t\t\t}\n\t\t}\n\t\ttemp.set(best_label);\n\t}\n\tnum_c_best = get_components(g, temp, components);\n\t//print_filtered_graph(g,temp);\n\treturn  num_c_best;//just to be right\n}\n\ntemplate <class Graph>\ndb MkLSFMVCA(Graph &g, int k_sup, int n_labels) {\n\tstd::vector<int> components(num_vertices(g));\n\tint f_colors = size - num_vertices(g) + 1;\n\tdb temp(n_labels);\n\tint num_c = get_components(g, temp, components);\n\tint num_c_best = num_c;\n\twhile (temp.count() < k_sup) {\n\t\tint best_label = 0;\n\t\tfor (int i = 0; i < f_colors; ++i) {\n\t\t\tif (!temp.test(i)) {\n\t\t\t\ttemp.set(i);\n\t\t\t\tint nc = get_components(g, temp, components);\n\t\t\t\tif (nc <= num_c_best) {\n\t\t\t\t\tnum_c_best = nc;\n\t\t\t\t\tbest_label = i;\n\t\t\t\t}\n\t\t\t\ttemp.flip(i);\n\t\t\t}\n\t\t}\n\t\ttemp.set(best_label);\n\t}\n\t//num_c_best = get_components(g, temp, components);\n\t//print_filtered_graph(g,temp);\n\treturn  temp;//just to be right\n}\n\nint root(int current, std::vector<int> &parent) {\n\twhile (parent[current] != current) {\n\t\tcurrent = parent[current];\n\t}\n\treturn current;\n}\n\ntemplate<class Graph>\nint max_reduce(Graph &g, int n_curr, int n_colors, std::vector<int> &comp, int label) {\n\tstd::vector<int> parent(n_curr), level(n_curr);\n\tvolatile int comp_a, comp_b; //so i could debug dont know why.\n\tint result;\n\tfor (int i = 0; i < n_curr; ++i) {\n\t\tparent[i] = i;\n\t\tlevel[i] = 0;\n\t}\n\tresult = 0;\n\n\ttypedef typename property_map<Graph, edge_color_t>::type EdgeColorMap;\n\ttypedef filtered_graph<Graph, valid_edge_color<EdgeColorMap, db> > fg;\n\ttypedef typename fg::edge_iterator eit;\n\teit it, end;\n\tdb mask(n_colors);\n\tmask.set(label);\n\tvalid_edge_color<EdgeColorMap, db> filter(get(edge_color, g), mask);\n\tfg G(g, filter);\n\tstd::tie(it, end) = boost::edges(G);\n\n\twhile (it != end) {\n\t\tcomp_a = comp[source(*it, G)];\n\t\tcomp_b = comp[target(*it, G)];\n\t\tif (comp_a != comp_b) {\n\t\t\tvolatile int root_a, root_b;\n\t\t\troot_a = root(comp_a, parent);\n\t\t\troot_b = root(comp_b, parent);\n\t\t\tif (root(comp_a, parent) != root(comp_b, parent)) {\n\t\t\t\tif (level[root(comp_a, parent)] > level[root(comp_b, parent)]) parent[root(comp_b, parent)] = root(comp_a, parent);\n\t\t\t\telse {\n\t\t\t\t\tif (level[root(comp_a, parent)] == level[root(comp_b, parent)]) {\n\t\t\t\t\t\tlevel[root(comp_b, parent)]++;\n\t\t\t\t\t}\n\t\t\t\t\tparent[root(comp_a, parent)] = root(comp_b, parent);\n\t\t\t\t}\n\t\t\t\tresult++;\n\t\t\t}\n\t\t}\n\t\t++it;\n\t}\n\treturn result;\n}\n\ntypedef typename adjacency_list<vecS, vecS, undirectedS, no_property, property<edge_color_t, int>> graph_t;\n\ntemplate<class Graph>\nproperty_map<graph_t, edge_color_t>::type get_colors(Graph &g) {\n\ttypedef typename property_map<Graph, edge_color_t>::type ColorMap;\n\tColorMap colors = get(edge_color, g);\n\t//make color type generic\n\treturn colors;\n}\n\ntemplate<class Graph,class Model,class Mask>\nvoid generateCuts(Graph g, Model &mod,Mask temp,int n_colors,IloBoolVarArray& z) {\n\tstd::vector<int> components(num_vertices(g));\n\tauto colors = get_colors(g);\n\tgraph_traits<graph_t>::edge_iterator it, end;\n\t//std::cout << \" user cutting\" << std::endl;\n\tint no = get_components(g, temp, components);\n\tint num_c_best = no;\n\tint best_label = -1;\n\tboost::random::mt19937 gen(std::time(0));\n\tboost::random::uniform_int_distribution<> dist(3, 10);\n\tint i = dist(gen);\n\twhile (num_c_best >= i) {//peharps temp.count() < k_sup\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t   /*boost::random::uniform_int_distribution<> gen(0, size-1);\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t   int i = gen(rng);\t\t\t\t\t\t\t\t\t\t\t\t\t   if (!temp.test(i))temp.set(i);\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t   */\n\t\tint diff;\n\t\tint best_diff = num_vertices(g);\n\t\tno = num_c_best;\n\t\tbest_label = -1;\n\t\tfor (int i = 0; i < n_colors; ++i) {\n\t\t\tif (!temp.test(i)) {\n\t\t\t\ttemp.set(i);\n\t\t\t\tnum_c_best = get_components(g, temp, components);\n\t\t\t\tdiff = no - num_c_best;\n\t\t\t\tif (diff < best_diff) {\n\t\t\t\t\tbest_diff = diff;\n\t\t\t\t\tbest_label = i;\n\t\t\t\t\ttemp.flip(i);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\ttemp.flip(i);\n\t\t\t}\n\t\t}\n\t\tif (best_label >= 0)temp.set(best_label);\n\t\tnum_c_best = get_components(g, temp, components);\n\t}\n\tif (best_label >= 0)temp.flip(best_label);\n\tnum_c_best = get_components(g, temp, components);\n\tif (num_c_best > 1) {\n\t\t//std::cout << \"add user cut\" << std::endl;\n\t\t//db temp1(size);\n\t\tstd::tie(it, end) = edges(g);\n\t\tIloExpr expr(mod.getEnv());\n\t\tvector<db> masks(num_c_best);\n\t\tfor (int i = 0; i < num_c_best; ++i) masks[i].resize(n_colors);\n\t\twhile (it != end) {\n\t\t\tif (components[source(*it, g)] != components[target(*it, g)]) {\n\t\t\t\tmasks[components[source(*it, g)]].set(colors[*it]);\n\t\t\t\tmasks[components[target(*it, g)]].set(colors[*it]);\n\t\t\t}\n\t\t\t++it;\n\t\t}\n\t\tfor (int i = 0; i < num_c_best; ++i) {\n\t\t\tfor (int j = 0; j < n_colors; ++j) if (masks[i].test(j))expr += z[j];\n\t\t\tmod.add(expr >= 1);\n\t\t\texpr.clear();\n\t\t}\n\t\texpr.end();\n\t}\n\n\n}\n\n\n\n// preprocessing functions\ntemplate<class Graph>\nvoid treefy(Graph& g, int n_colors) {\n\tGraph result(num_vertices(g));\n\ttypedef boost::graph_traits<Graph>::edge_descriptor edge_t;\n\ttypedef typename property_map<Graph, edge_color_t>::type EdgeColorMap;\n\ttypedef filtered_graph<Graph, valid_edge_color<EdgeColorMap, db> > fg;\n\ttypedef typename fg::edge_iterator eit;\n\teit it, end;\n\tfor (int l = 0; l < n_colors; ++l) {\n\t\tdb mask(n_colors);\n\t\tmask.set(l);\n\t\tstd::vector<int> components(num_vertices(g));// components graph\n\t\tint n_curr = get_components(g, mask, components);\n\t\tstd::vector<int> my_mapping(n_curr, -1);\n\t\tfor (int u = 0; u < num_vertices(g); ++u) {\n\t\t\tif (my_mapping[components[u]] == -1)my_mapping[components[u]] = u;\n\t\t\telse add_edge(my_mapping[components[u]], u, property<edge_color_t, int>(l), result);\n\t\t}\n\t}\n\tg.clear();\n\tcopy_graph(result, g);\n}\ntemplate<class Graph>\nvoid completefy(Graph& g, int n_colors) {\n\tGraph result(num_vertices(g));\n\ttypedef boost::graph_traits<Graph>::edge_descriptor edge_t;\n\ttypedef typename property_map<Graph, edge_color_t>::type EdgeColorMap;\n\ttypedef filtered_graph<Graph, valid_edge_color<EdgeColorMap, db> > fg;\n\ttypedef typename fg::edge_iterator eit;\n\teit it, end;\n\tfor (int l = 0; l < n_colors; ++l) {\n\t\tdb mask(n_colors);\n\t\tmask.set(l);\n\t\tstd::vector<int> components(num_vertices(g));// components graph\n\t\tint n_curr = get_components(g, mask, components);\n\t\tstd::vector<int> my_mapping(n_curr, -1);\n\t\tfor (int u = 0; u < num_vertices(g); ++u) {\n\t\t\tfor (int v = u + 1; v < num_vertices(g); ++v) {\n\t\t\t\tif (components[u] == components[v]) {\n\t\t\t\t\tadd_edge(u, v, property<edge_color_t, int>(l), result);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tg.clear();\n\tcopy_graph(result, g);\n}\n// preprocessing functions\ntemplate<class Graph>\nvoid MCR(Graph& g, int n_colors) {\n\tGraph result(num_vertices(g));\n\ttypedef boost::graph_traits<Graph>::edge_descriptor edge_t;\n\ttypedef typename property_map<Graph, edge_color_t>::type EdgeColorMap;\n\ttypedef filtered_graph<Graph, valid_edge_color<EdgeColorMap, db> > fg;\n\ttypedef typename fg::edge_iterator eit;\n\teit it, end;\n\tfor (int l = 0; l < n_colors; ++l) {\n\t\tdb mask(n_colors);\n\t\tmask.set(l);\n\t\tvalid_edge_color<EdgeColorMap, db> filter(get(edge_color, g), mask);\n\t\tfg H(g, filter);\n\t\ttypedef typename property_map<fg, vertex_index_t>::type IndexMap;\n\t\tIndexMap index = get(vertex_index, H);\n\t\t//disjoint_sets ds(num_vertices(g))\n\t\n\t\trank_t rank_map;\n\t\tparent_t parent_map;\n\t\tboost::associative_property_map<rank_t>   rank_pmap(rank_map);\n\t\tboost::associative_property_map<parent_t> parent_pmap(parent_map);\n\t\tboost::disjoint_sets<\n\t\t\tassociative_property_map<rank_t>,\n\t\t\tassociative_property_map<parent_t> > ds(\n\t\t\t\trank_pmap,\n\t\t\t\tparent_pmap);\n\t\t//std::vector<Element> elements;\n\t\t//elements.push_back(Element(...));\n\t\t//rank_t rank_map;\n\t\t//parent_t parent_map;\n\n\t\t//boost::associative_property_map<rank_t>   rank_pmap(rank_map);\n\t\t//boost::associative_property_map<parent_t> parent_pmap(parent_map);\n\n\t\tfor (int i = 0; i < num_vertices(g); ++i) {\n\t\t\tds.make_set(i);\n\t\t}\n\t\tstd::tie(it, end) = edges(H);\n\t\twhile (it != end) {\n\t\t\tint u = index[source(*it, H)];\n\t\t\tint v = index[target(*it, H)];\n\t\t\tif (ds.find_set(u) != ds.find_set(v)) {\n\t\t\t\tadd_edge(u, v, property<edge_color_t, int>(l), result);\n\t\t\t\tds.union_set(u, v);\n\t\t\t}\n\t\t\telse {\n\t\t\t\tstd::cout << \"MCR removed edge:\" << \" (\" << u << \",\" << v << \") \" << \" Color: \" << l << std::endl;\n\t\t\t}\n\t\t\t++it;\n\t\t}\n\t}\n\tg.clear();\n\tcopy_graph(result, g);\n}\n\n\ntemplate<class Graph> // dont work with multigraph\nvoid buildFlowModel(IloModel mod, IloBoolVarArray Z, IloVarMatrix F, const int k, const Graph &g,int opt,int lower_bound) {\n\tIloEnv env = mod.getEnv();\n\tint n_colors = Z.getSize();\n\ttypedef typename property_map<Graph, edge_color_t>::const_type ColorMap;\n\ttypedef typename graph_traits<Graph>::edge_descriptor edge_desc;\n\tColorMap colors = get(edge_color, g);\n\t/*std::vector<Graph> monocromatic_graphs(n_colors, Graph(num_vertices(g)));\n\t//creating new colored graphs mantain diferent colors\n\tauto[it_edges, last_edge] = edges(g);\n\tColorMap colors = get(edge_color, g);\n\twhile (it_edges != last_edge) {\n\t\tadd_edge(source(*it_edges, g), target(*it_edges, g), property<edge_color_t, int>(colors[*it_edges]), monocromatic_graphs[colors[*it_edges]]);\n\t\tit_edges++;\n\t}*/\n\n\t//modelling objective function\n\tIloExpr exp(env);\n\tint n_vertices = num_vertices(g);\n\tint s = n_vertices - 1;//super source\n\tint f_colors = n_colors - n_vertices + 1;\n\tfor (int i = f_colors; i < n_colors; ++i) {\n\t\texp += Z[i];\n\t}\n\tmod.add(IloMinimize(env, exp));\n\t//mod.add(exp >= lower_bound);\n\t//mod.add(exp>=40);\n\t//mod.add(exp == 1);\n\t//exp.end();\n\t//modelling f_{ij} temporario ajeitar para deixar mais compactor depois um para cada aresta\n\n\tfor (int i = 0; i < n_vertices; ++i) {\n\t\tF[i] = IloNumVarArray(env, n_vertices, 0, n_vertices-1, ILOFLOAT);\n\t}\n\tfor (int i = 0; i < n_vertices; ++i) {\n\t\tfor (int j = 0; j < n_vertices; ++j) {\n\t\t\tF[i][j].setName((\"f_\" + std::to_string(i) + \"_\" + std::to_string(j)).c_str());\n\t\t}\n\t}\n\t//setting names to labels variables.\n\tfor (int i = 0; i<n_colors; ++i) {\n\t\tZ[i].setName((\"z\" + std::to_string(i)).c_str());\n\t}\n\t// first constraint\n\ttypedef typename graph_traits<Graph>::vertex_iterator vertex_it;\n\ttypedef typename graph_traits<Graph>::in_edge_iterator in_edge_it;\n\tIloExpr lhs(env);\n\tIloExpr lhs1(env);\n\tvertex_it vit, vend;\n\tstd::tie(vit, vend) = vertices(g);\n\tin_edge_it eit, eend;\n\tfor (auto it = vit; it != vend && *it<s; ++it) {\n\t\tstd::tie(eit, eend) = in_edges(*it, g);\n\t\tfor (auto tit = eit; tit != eend; ++tit) {\n\t\t\tlhs += F[source(*tit, g)][target(*tit, g)];\n\t\t\t//new constraint 1\n\t\t\t//if (source(*tit, g) != s) {\n\t\t\t\tlhs -= F[target(*tit, g)][source(*tit, g)];\n\t\t\t\tlhs1 += F[target(*tit, g)][source(*tit, g)];\n\t\t\t//}\n\t\t}\n\t\tmod.add(lhs == 0);\n\t\tmod.add(lhs1 >= 1);\n\t\tlhs.clear();\n\t\tlhs1.clear();\n\t}\n\tlhs.end();\n\tlhs1.end();\n\n\tedge_desc my_edge;\n\tbool result = false;\n\t//IloExpr expression1(env);\n\tfor (int i = 0; i < n_vertices-1; ++i) {\n\t\tfor (int j = 0; j < n_vertices-1; ++j) {\n\t\t\tstd::tie(my_edge, result) = edge(i, j, g);\n\t\t\tif (result) {\n\t\t\t\tmod.add(F[i][j]<= (n_vertices - 1) * Z[colors[my_edge]]);\n\t\t\t}\n\t\t}\n\n\t}\n\t//expression1.end();\n\t//third big-mconstraint\n\tfor (int i = f_colors; i < n_colors; ++i) {\n\t\tmod.add(F[s][i - f_colors] == IloInt(1));\n\t\tmod.add(F[i - f_colors][s] <= IloInt(n_vertices-1)*Z[i]);\n\t\tmod.add(F[i - f_colors][s] >= Z[i]);\n\t\t//mod.add(F[s][i - f_colors] <= IloInt(n_vertices - 1)*Z[i]);\n\t}\n\texp.end();\n\n\n\t//constraint every vertex has a colored edge incident\n\tauto [first_vertex, last_vertex] = vertices(g);\n\twhile (first_vertex != last_vertex) {\n\t\tdb used_colors(n_colors);\n\t\tauto[first_edge, last_edge] = in_edges(*first_vertex,g);\n\t\tIloExpr expInEdges(env);\n\t\twhile (first_edge != last_edge) {\n\t\t\tvolatile int idx = colors[*first_edge];\n\t\t\tif (!used_colors.test_set(idx,1)) {\n\t\t\t\texpInEdges += Z[colors[*first_edge]];\n\t\t\t}\n\t\t\tfirst_edge++;\n\t\t}\n\t\tmod.add(expInEdges >= 1);\n\t\texpInEdges.end();\n\t\tfirst_vertex++;\n\t}\n\n\n\tIloExpr texp(env);\n\tfor (int i = 0; i < f_colors; ++i) {\n\t\ttexp += Z[i];\n\t}\n\tmod.add(texp == k);\n\ttexp.end();\n\n}\n\n\ntemplate<class Graph>\nvoid solveModel(int n_vertices, int n_colors, int k, Graph &g) {\n\n\t//starting cplex code part\n\tIloEnv   env; //environment\n\ttry {\n\t\tIloModel model(env);\n\t\tIloBoolVarArray Z(env, n_colors);\n\t\tIloNumArray pri(env, n_colors);\n\t\tIloVarMatrix    F(env, n_vertices); //each edge has at least a edge to the supersource\n\t\tint opt = kLSFMVCA(g, k, n_colors) - 1;\n\t\tbuildFlowModel(model, Z, F, k, g, opt, 1);\n\t\tIloCplex cplex(model);\n\t\tint f_colors = n_colors - num_vertices(g) + 1;\n\t\tcplex.exportModel(\"kSLF_fluxo.lp\"); // good to see if the model is correct\n\t\t\t\t\t\t\t\t\t\t\t//cross your fingers\n\t\t{//set priorities number edges by color.\n\t\t\tauto it = boost::edges(g).first;\n\t\t\tauto end = boost::edges(g).second;\n\t\t\tauto colormap = get(edge_color, g);\n\t\t\twhile (it != end) {\n\t\t\t\tpri[colormap[*it]]++;\n\t\t\t\t++it;\n\t\t\t}\n\t\t}\n\n\n\t\t//trying to disable automatic cuts\n\t\t//cplex.setParam(IloCplex::Param::MIP::Limits::CutPasses,-1);\n\t\tcplex.setParam(IloCplex::Param::MIP::Tolerances::UpperCutoff, opt);\n\t\tcplex.setParam(IloCplex::Param::Threads, 4);\n\t\t//cplex.setParam(IloCplex::Param::Parallel, -1);\n\t\tcplex.setParam(IloCplex::Param::Emphasis::MIP, 1);\n\t\tcplex.setParam(IloCplex::Param::Benders::Strategy, 3);\n\t\tcplex.setParam(IloCplex::TiLim, 7300);\n\t\tcplex.setPriorities(Z, pri);\n\t\tcplex.solve();\n\t\t//cplex.exportModel(\"kSLF_fluxo_after_presolve.lp\");\n\t\tcplex.out() << \"solution status = \" << cplex.getStatus() << endl;\n\n\t\tcplex.out() << endl;\n\t\tcplex.out() << \"Number of components   = \" << cplex.getObjValue() << endl;\n\t\tdb temp(n_colors);\n\t\tcplex.out() << \"color(s) solution:\";\n\t\tfor (int i = 0; i < f_colors; i++) {\n\t\t\tif (std::abs(cplex.getValue(Z[i]) - 1.0f) <= 1e-3)cplex.out() << \" \" << i;\n\t\t}\n\t\tcplex.out() << endl;\n\t\tcplex.out() << \"root(s) solution:\";\n\t\t//int f_colors = Z.getSize() - n_vertices + 1;\n\t\tfor (int i = f_colors; i < n_colors; i++) {\n\t\t\tif (std::abs(cplex.getValue(Z[i]) - 1.0f) <= 1e-3)cplex.out() << \" \" << i - f_colors;\n\t\t}\n\t\tcplex.out() << endl;\n\t}\n\tcatch (IloException& e) {\n\t\tcerr << \"Concert exception caught: \" << e << endl;\n\t}\n\tcatch (...) {\n\t\tcerr << \"Unknown exception caught\" << endl;\n\t}\n\t//memory cleaning\n\tenv.end();\n}\n\n\nint main(int argc, const char *argv[])\n{\n\ttypedef adjacency_list<vecS, vecS, undirectedS, no_property, property<edge_color_t, int>> Graph;\n\ttypedef std::pair<int, int> Edge;\n\ttypedef boost::graph_traits<Graph>::vertex_descriptor vertex_t;\n\tGraph::edge_iterator it, end;\n\tGraph g;\n\tint n_vertices, n_colors;\n\t//command-line processor\n\n\ttry {\n\t\tstd::ifstream ifn;\n\t\tpo::options_description desc{ \"Options\" };\n\t\tdesc.add_options()(\"help,h\", \"produce help message\")\n\t\t\t(\"input-file,i\", po::value< string >(), \"input file\")\n\t\t\t(\"include-path,I\", po::value< string >(), \"include path\")\n\t\t\t(\"setup-file\", po::value< string >(), \"setup file\");\n\t\tpo::positional_options_description p;\n\t\tp.add(\"input-file\", -1);\n\n\n\t\tpo::variables_map vm;\n\t\tpo::store(po::command_line_parser(argc, argv).\n\t\t\toptions(desc).positional(p).run(), vm);\n\t\tpo::notify(vm);\n\n\t\tif (vm.count(\"help\")) {\n\t\t\tcout << desc << \"\\n\";\n\t\t\treturn 1;\n\t\t}\n\t\telse if (vm.count(\"input-file\"))\n\t\t{\n\t\t\tstd::cout << \"Input files are: \" << vm[\"input-file\"].as<string>() << \"\\n\";\n\t\t\tif (vm.count(\"include-path\"))ifn.open((vm[\"include-path\"].as<string>() + vm[\"input-file\"].as<string>()).c_str(), ifstream::in);\n\t\t\telse ifn.open(vm[\"input-file\"].as<string>().c_str(), ifstream::in);\n\t\t\tif (!ifn.is_open()) {\n\t\t\t\tstd::cout << \"error opening file\" << std::endl;\n\t\t\t\texit(EXIT_FAILURE);\n\t\t\t}\n\t\t\tdynamic_properties dp;\n\t\t\tdp.property(\"color\", get(edge_color, g));\n\t\t\tread_graphml(ifn, g, dp);\n\n\t\t\tvector<string> vecI;\n\t\t\tsplit(vecI, vm[\"input-file\"].as<string>(), is_any_of(\"-.\"), token_compress_off);\n\t\t\tif (vecI.size() == 6) {\n\t\t\t\tstd::cout << vecI[0] << std::endl;\n\t\t\t\tn_vertices = stoi(vecI[0]);\n\t\t\t\tstd::cout << vecI[2] << std::endl;\n\t\t\t\tn_colors = stoi(vecI[2]);\n\t\t\t\tstd::cout << vecI[3] << std::endl;\n\t\t\t\tint k = stoi(vecI[3]);\n\t\t\t\t//add edges to super source vertex. remember!!!\n\t\t\t\tvertex_t u = add_vertex(g);\n\t\t\t\tn_vertices++;\n\t\t\t\tfor (int i = 0; i < n_vertices - 1; ++i) boost::add_edge(u, i, property<edge_color_t, int>(n_colors++), g);\n\t\t\t\t//std::tie(it, end) = boost::edges(g);\n\t\t\t\t//print_edges(it, end, g);\n\t\t\t\tMCR(g, n_colors);\n\t\t\t\t//treefy(g, n_colors);\n\t\t\t\t//completefy(g, n_colors);\n\t\t\t\t//auto colors = get(edge_color, g);\n\t\t\t\t//dynamic_properties dp;\n\t\t\t\t//dp.property(\"Color\", colors);\n\t\t\t\t//std::ofstream tmp(\"out.graphml\");\n\t\t\t\t//write_graphml(tmp, g, dp, true);\n\t\t\t\tsolveModel(n_vertices, n_colors, k, g);\n\t\t\t}\n\t\t\telse {\n\t\t\t\tstd::cout << \"file wrong name format.\" << std::endl;\n\t\t\t}\n\n\t\t}\n\t\telse if (vm.count(\"setup-file\")) {\n\t\t\tstd::cout << \"Not implemented yet\" << std::endl;\n\t\t}\n\t\telse {\n\t\t\tstd::cout << \"see options(-h).\" << std::endl;\n\t\t}\n\n\n\t}\n\tcatch (const po::error &ex) {\n\t\tstd::cout << ex.what();\n\t\texit(EXIT_FAILURE);\n\t}\n\tcatch (boost::exception &ex) {\n\t\tstd::cout << boost::diagnostic_information(ex) << std::endl;\n\t}\n\tcatch (std::exception &ex) {\n\t\tstd::cout << ex.what();\n\t\texit(EXIT_FAILURE);\n\t}\n\n\treturn 0;\n}\n\n\n", "meta": {"hexsha": "42f5c2bf2e43431ec9e949bb7603387b8089c93c", "size": 21138, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Cplex12802/main.cpp", "max_stars_repo_name": "Huebr/kLSFlow", "max_stars_repo_head_hexsha": "74a840888faa7e930e1487620bd763f0f85e6aba", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Cplex12802/main.cpp", "max_issues_repo_name": "Huebr/kLSFlow", "max_issues_repo_head_hexsha": "74a840888faa7e930e1487620bd763f0f85e6aba", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Cplex12802/main.cpp", "max_forks_repo_name": "Huebr/kLSFlow", "max_forks_repo_head_hexsha": "74a840888faa7e930e1487620bd763f0f85e6aba", "max_forks_repo_licenses": ["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.8343373494, "max_line_length": 143, "alphanum_fraction": 0.6537988457, "num_tokens": 6298, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7401743505760728, "lm_q2_score": 0.4610167793123159, "lm_q1q2_score": 0.3412327952321661}}
{"text": "/*\n This program is free software; you can redistribute it and/or modify it under\n the terms of the European Union Public Licence - EUPL v.1.1 as published by\n the European Commission.\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 European Union Public Licence - EUPL v.1.1\n for more details.\n\n You should have received a copy of the European Union Public Licence - EUPL v.1.1\n along with this program.\n\n Further information about the European Union Public Licence - EUPL v.1.1 can\n also be found on the world wide web at http://ec.europa.eu/idabc/eupl\n\n*/\n\n/*\n ------ Copyright (C) 2010 STA Steering Board (space.trajectory.analysis AT gmail.com) ----\n*/\n\n/*\n------------------ Author:       Marnix Volckaert               -------------------\n------------------ Affiliation:  TUDelft                        -------------------\n-----------------------------------------------------------------------------------\n Modified by Tiziana Sabatini on May-July 2009\n*/\n\n\n#include <QDir>\n#include <QTextStream>\n\n#include \"EntryTrajectory.h\"\n#include \"Astro-Core/EODE/eode.h\"\n#include <Eigen/Core>\n#include <QProcess>\n#include <QDebug>\n\n\n\n/*Function containing the equations of motion*/\n//=================================================================================================\nvoid derivstate (VectorXd state, double time, VectorXd parameters, VectorXd& derivative)\n{\n        derivative[0] = state[3];\n        derivative[1] = state[4];\n        derivative[2] = state[5];\n        derivative[3] = parameters[3] + parameters[0] + pow(parameters[6],2)*state[0] + 2.0*parameters[6]*state[4];\n        derivative[4] = parameters[4] + parameters[1] + pow(parameters[6],2)*state[1] - 2.0*parameters[6]*state[3];\n        derivative[5] = parameters[5] + parameters[2];\n        derivative[6] = parameters[7];\n        derivative[7] = parameters[8];\n}\n\nclass EntryDerivativeCalculator : public DerivativeCalculator<8>\n{\npublic:\n    EntryDerivativeCalculator(EntryTrajectory *trajectory):\n            m_trajectory(trajectory)\n            //m_perturbationList(perturbationList)\n    {\n    }\n\n    virtual void compute(const State& state, double t, State& derivatives) const\n    {\n        Vector3d position = state.segment<3>(0);\n        Vector3d velocity = state.segment<3>(3);\n        sta::StateVector stateVector=StateVector(position,velocity);\n        Vector3d gravity;                   //Components of gravitational acceleration in appropriate elements\n        Vector3d aero;                     \t//Components of aerodynamic acceleration in appropriate elements\n        VectorXd parameters(9);             //List of parameters to send to integration: 0,1,2 = gravity, 3,4,5 = aero, 6 = omega, 7 = Qdot\n        double Cdc;\n        double tau = m_trajectory->settings.stepsize;\n\n        m_trajectory->body.updateGravity(stateVector, gravity);\n        m_trajectory->body.updateAero(stateVector, m_trajectory->state2, m_trajectory->atmosphere, m_trajectory->capsule, aero, Cdc);\n        /*\n        Vector3d perturbingAcceleration(0, 0, 0);\n        foreach (Perturbations* perturbation, perturbationList)\n        {\n            perturbingAcceleration += perturbation->calculateAcceleration(stateVector, time, tau);\n        }\n        gravity += perturbingAcceleration;\n        */\n        m_trajectory->calculateState2(aero, Cdc);\n        m_trajectory->updateEndstate();\n\n        //Test for status\n        m_trajectory->checkStatus();\n        if ( m_trajectory->status != OK) {\n            m_trajectory->result.status = m_trajectory->status;\n        }\n        parameters << gravity, aero, m_trajectory->body.getOmega(), m_trajectory->state2(3), m_trajectory->state2(4);\n        //TO DO : re-insert the heat load integration (now heat flux is always set to zero)\n        VectorXd state3(8);\n                state3 << stateVector.position, stateVector.velocity, 0, 0;\n\n\n                derivatives[0] = state3[3];\n                derivatives[1] = state3[4];\n                derivatives[2] = state3[5];\n                derivatives[3] = parameters[3] + parameters[0] + pow(parameters[6],2)*state3[0] + 2.0*parameters[6]*state3[4];\n                derivatives[4] = parameters[4] + parameters[1] + pow(parameters[6],2)*state3[1] - 2.0*parameters[6]*state3[3];\n                derivatives[5] = parameters[5] + parameters[2];\n                derivatives[6] = parameters[7];\n                derivatives[7] = parameters[8];\n    }\n\nprivate:\n    EntryTrajectory* m_trajectory;\n\n    //const QList<Perturbations*>& m_perturbationList;\n\n};\n\nEntryTrajectory::EntryTrajectory(EntrySettings _settings)\n{\n    //Set the entry trajectory's settings to the input settings\n    //---------------------------------------------------------\n    settings = _settings;\n    //---------------------------------------------------------\n\n    //Assign body, atmosphere and heat rate, and capsule Cd profile\n    //---------------------------------------------------------\n    atmosphere.selectModel(settings.modelname);\n    body.selectBody(settings.bodyname);\n    heatrate.selectBody(settings.bodyname);\n    capsule.flag = 0;\n    capsule.selectCdCprofile(settings.CdCprofilename);\n    capsule.selectClCprofile(settings.ClCprofilename);\n    capsule.selectCsCprofile(settings.CsCprofilename);\n\n    //capsule.selectCdPprofile(settings.CdPprofilename);\n    //capsule.Sp = settings.parachuteArea;\n\n    state.resize(8);\n    state2.resize(10);\n}\n\n\nsta::StateVector EntryTrajectory::initialise(EntryParameters _parameters,sta::StateVector initialState, double startTime)\n{\n\n    parameters = _parameters;           //Save the parameters as a member of the trajectory, to possibly use later in plotting\n\n    capsule.Sc = parameters.Sref;\n    capsule.m = parameters.m;\n    capsule.Rn = parameters.Rn;\n\n    double theta = getGreenwichHourAngle(startTime);\n    int celestialbody;\n    if (settings.bodyname == \"Earth\")\n         celestialbody = 0;\n    else if (settings.bodyname == \"Mars\")\n         celestialbody = 3;\n    //inertialTOfixed(celestialbody, theta, initialState.position.x(), initialState.position.y(), initialState.position.z(), initialState.velocity.x(), initialState.velocity.y(), initialState.velocity.z(),\n      //          state(0), state(1), state(2), state(3), state(4), state(5));\n\n    //const Eigen::Vector3d position(initialState.position.x(),initialState.position.y(),initialState.position.z());\n    //const Eigen::Vector3d velocity(state(3), state(4), state(5));\n    //initialState = sta::StateVector(position,velocity);\n    double omega=7.29211585494e-5;\n    initialState.velocity.x()+=initialState.position.y()*omega;\n    initialState.velocity.y()+=-initialState.position.x()*omega;\n\n    \n    //----- Initialise the heat loads to zero\n    state(6) = 0.0;\n    state(7) = 0.0;\n    //---------------------------------------------------------\n\n    //Initialise the rest\n    //---------------------------------------------------------\n    time = sta::daysToSecs(sta::JdToMjd(startTime));\n    for (int i=0; i<10; i++) {\n        state2(i) = 0.0;\n    }\n    state2(5) = parameters.inputstate[0];          //Initial altitude\n    status = OK;                                   //Status = OK\n    result.Machone_transition_altitude = 0.0;      //Needs to be zero at first so that it only gets set once\n    result.parachutedeploy_altitude = 0.0;         //Needs to be zero at first so that it only gets set once\n    result.maxconvheatrate.value = 0.0;\n    result.maxradheatrate.value = 0.0;\n    result.maxtotalheatrate.value = 0.0;\n    result.maxloadfactor.value = 0.0;\n\n    trajectory.open(\"data/REMTrajectory.stae\");\n\n    return initialState;\n}\n\n\nEndstate EntryTrajectory::getEndstate()\n{\n    save = false;\n    QList<double> sampleTimesTemp;\n    QList<sta::StateVector> samplesTemp;\n    //integrate(sampleTimesTemp, samplesTemp);\n    return (result);\n}\n\n\nvoid EntryTrajectory::saveTrajectory (QList<double>& sampleTimes, QList<sta::StateVector>& samples)\n{\n    save = true;\n    trajectory.open(\"data/REMTrajectory.stae\");\n    misc.open(\"data/REMMiscellaneous.stam\");\n    //integrate(sampleTimes, samples);\n    misc.close();\n    trajectory.close();\n    printReport();\n}\n\n\nsta::StateVector EntryTrajectory::integrate(sta::StateVector stateVector, QList<Perturbations*> perturbationsList)//Modified by Dominic to improve integration stability\n{\n    double tau = settings.stepsize;\n\n    /*\n    Vector3d gravity;                   //Components of gravitational acceleration in appropriate elements\n    Vector3d aero;                     \t//Components of aerodynamic acceleration in appropriate elements\n    VectorXd parameters(9);             //List of parameters to send to integration: 0,1,2 = gravity, 3,4,5 = aero, 6 = omega, 7 = Qdot\n    double Cdc;\n\n    //Update gravity, perturbations and aerodynamic accelerations\n    body.updateGravity(stateVector, gravity);\n    body.updateAero(stateVector, state2, atmosphere, capsule, aero, Cdc);\n\n    //Vector3d perturbingAcceleration(0, 0, 0);\n    //foreach (Perturbations* perturbation, perturbationsList)\n    //{\n    //    perturbingAcceleration += perturbation->calculateAcceleration(stateVector, time, tau);\n    //}\n    //gravity += perturbingAcceleration;\n\n    calculateState2(aero, Cdc);\n    updateEndstate();\n\n    //Test for status\n    checkStatus();\n    if ( status != OK) {\n        result.status = status;\n    }\n\n    //Build the parameters vector to send to equations of motion\n    parameters << gravity, aero, body.getOmega(), state2(3), state2(4);\n    //TO DO : re-insert the heat load integration (now heat flux is always set to zero)\n    VectorXd state(8);\n            state << stateVector.position, stateVector.velocity, 0, 0;\n\n    //if (settings.integrator == \"RK4\")\n        rk4 (state, 8, time, tau, derivstate, parameters);\n    */\n    EntryDerivativeCalculator entryCalculator(this);// entryCalculator(this,QList<Perturbations*> perturbationsList);\n    Matrix<double, 8, 1> state;\n    state<<stateVector.position, stateVector.velocity, 0, 0;\n    rk4(state, time, tau, &entryCalculator);\n\n\n\n    const Vector3d vec1(state(0), state(1), state(2));\n    const Vector3d vec2(state(3), state(4), state(5));\n    sta::StateVector vector = sta::StateVector(vec1, vec2);\n\n    stateVector = vector;\n\n    time += tau;\n\n    //------ Calculate the rest of the endstate structure ------\n    calculateEndstate();\n\n    return stateVector;\n}\n\n\nvoid EntryTrajectory::calculateState2(Vector3d& aero, double Cdc)\n{\n    state2(2) = aero.norm() / 9.81; //n = magnitude of resultant vector of accelerations / g\n    //------ calculate heat rate at stagnation point ------\n    state2(3) = heatrate.ConvectiveHeatRate(state2(6), state2(0), capsule.Rn);\n    state2(4) = heatrate.RadiativeHeatRate(state2(6), state2(0), capsule.Rn);\n    state2(8) = state2(3) + state2(4);\n    state2(9) = state(6) + state(7);\n}\n\n\ninline void EntryTrajectory::checkStatus()\n{\n    if (state2(5) < 0.0) {status = landed;};\n    if (state2(5) > settings.maxaltitude) {status = gone;};     //If higher than x times initial altitude -> gone\n    if (state2(8) > settings.maxheatrate) {status = burnt;};\n    if (result.maxloadfactor.value > settings.maxloadfactor) {status = crushed;};\n}\n\n\nEndstate EntryTrajectory::updateEndstate()\n{\n    if (state2(1) < 1.0 && result.Machone_transition_altitude == 0.0) {\n        result.Machone_transition_time = time;\n        result.Machone_transition_altitude = state2(5);\n    }//-------------------------------------\n    if (state2(1) < settings.parachuteDeployMach && result.parachutedeploy_altitude == 0.0) {\n        result.parachutedeploy_time = time;\n        result.parachutedeploy_altitude = state2(5);\n        state2(7) = 1.0;\n    }//-------------------------------------\n    if (state2(2) > result.maxloadfactor.value && state2(7) != 1.0) {         //find the maximum load factor\n        result.maxloadfactor.value = state2(2);\n        result.maxloadfactor.time = time;\n        result.maxloadfactor.altitude = state2(5);\n    }//-------------------------------------\n    if (state2(3) > result.maxconvheatrate.value) {           //find the maximum heat rate at the stagnation point\n        result.maxconvheatrate.value = state2(3);\n        result.maxconvheatrate.time = time;\n        result.maxconvheatrate.altitude = state2(5);\n    }//-------------------------------------\n    if (state2(4) > result.maxradheatrate.value) {           //find the maximum heat rate at the stagnation point\n        result.maxradheatrate.value = state2(4);\n        result.maxradheatrate.time = time;\n        result.maxradheatrate.altitude = state2(5);\n    }//-------------------------------------\n    if (state2(8) > result.maxtotalheatrate.value) {         //find the maximum total heat rate\n        result.maxtotalheatrate.value = state2(8);\n        result.maxtotalheatrate.time = time;\n        result.maxtotalheatrate.altitude = state2(5);\n    }\n    return(result);\n}\n\n\nEndstate EntryTrajectory::calculateEndstate() {\n\n    //------ Update the maximum values one more time ------\n    if (state2(2) > result.maxloadfactor.value) {         //find the maximum heat rate\n        result.maxloadfactor.value = state2(2);\n        result.maxloadfactor.time = time;\n        result.maxloadfactor.altitude = state2(5);\n    }//-------------------------------------\n    if (state2(3) > result.maxconvheatrate.value) {           //find the maximum heat rate at the stagnation point\n        result.maxconvheatrate.value = state2(3);\n        result.maxconvheatrate.time = time;\n        result.maxconvheatrate.altitude = state2(5);\n    }//-------------------------------------\n    if (state2(4) > result.maxradheatrate.value) {           //find the maximum heat rate at the stagnation point\n        result.maxradheatrate.value = state2(3);\n        result.maxradheatrate.time = time;\n        result.maxradheatrate.altitude = state2(5);\n    }//-------------------------------------\n    if (state2(8) > result.maxtotalheatrate.value) {         //find the maximum total heat rate\n\n        result.maxtotalheatrate.value = state2(4);\n        result.maxtotalheatrate.time = time;\n        result.maxtotalheatrate.altitude = state2(5);\n    }\n    //------ Compute time of flight, total heat load and impact velocity ------\n    result.timeofflight = time;\n    result.totalheatload = state2(9);\n    result.tpsmass = (0.0009*pow(state(6),0.5306)) * parameters.m;\n    result.impactvelocity = state2(6);\n\n    //The following is only applicable for a successful landing\n    //---------------------------------------------------------\n    if (status == 0) {\n        //------ Compute the landing longitude ------\n        result.longitude = atan2(state(1), state(0)) / acos(-1.0) * 180;\n        //------ Compute the landing latitude ------\n        //lambda = asin( state(2) / sqrt(pow(state(0),2) + pow(state(1),2) + pow(state(2),2)) );\n        //result.latitude = body.geocentric2geodetic_latitude(lambda) / acos(-1) * 180;\n        result.latitude = asin( state(2) / sqrt(pow(state(0),2) + pow(state(1),2) + pow(state(2),2)) ) / acos(-1.0) * 180;\n    }\n    //---------------------------------------------------------\n    return(result);\n}\n\n\ninline void EntryTrajectory::saveOutput (double time)\n{\n\n    double stateSpherical[6];\n    cartesianTOspherical(state(0), state(1), state(2), state(3), state(4), state(5),\n                         stateSpherical[0], stateSpherical[1], stateSpherical[2], stateSpherical[3], stateSpherical[4], stateSpherical[5]);\n    stateSpherical[2] = body.altitude(stateSpherical[2] , stateSpherical[1] );\n    double theta = getGreenwichHourAngle(sta::MjdToJd(sta::secsToDays(time)));\n    double a,b,c,d,e,f;\n    int celestialbody;\n    if (settings.bodyname == \"Earth\")\n         celestialbody = 0;\n    else if (settings.bodyname == \"Mars\")\n         celestialbody = 3;\n    fixedTOinertial(celestialbody, theta, state(0), state(1), state(2), state(3), state(4), state(5),\n                    a,b,c,d,e,f);\n    double v = sqrt(d*d + e*e + f*f);\n    double g,h,i;\n    cartesianTOspherical(a, b, c, d, e, f,\n                         g, h, i, stateSpherical[3], stateSpherical[4], stateSpherical[5]);\n\n    trajectory << setfill('0');\n        trajectory << setiosflags(ios::fixed) << setprecision(2) << setw(10) << state(0) << \"     \";\n        trajectory << setiosflags(ios::fixed) << setprecision(2) << setw(10) << state(1) << \"     \";\n        trajectory << setiosflags(ios::fixed) << setprecision(2) << setw(10) << state(2) << \"     \";\n        trajectory << setiosflags(ios::fixed) << setprecision(2) << setw(8) << state(3) << \"     \";\n        trajectory << setiosflags(ios::fixed) << setprecision(2) << setw(8) << state(4) << \"     \";\n        trajectory << setiosflags(ios::fixed) << setprecision(2) << setw(8) << state(5) << \"     \";\n        trajectory << stateSpherical[0]*1000 << \"     \";\n        trajectory << stateSpherical[1]*1000 << \"     \";\n        trajectory << setiosflags(ios::fixed) << setprecision(2) << setw(10) << stateSpherical[2]*1000 << \"     \";\n        trajectory << setiosflags(ios::fixed) << setprecision(2) << setw(10) << v << \"     \";\n        trajectory << stateSpherical[4]*1000 << \"     \";\n        trajectory << setiosflags(ios::fixed) << setprecision(2) << setw(10) << stateSpherical[5]*1000 << \"     \";\n        trajectory << state2[0]*1000 << \"     \";//density\n        trajectory << state2[1] << \"     \";//Ma\n        trajectory << state2[2]*1000 << \"     \";//load factor\n        trajectory << state2[3] << \"     \";//qdot_c\n        trajectory << state2[4] << \"     \";//qdot_r\n        trajectory << state[7] << \"     \";//parachute\n        trajectory << state2[8]*1000 << \"     \";//totalheatrate\n        trajectory << time << endl;\n}\n\n\ninline void EntryTrajectory::printReport ()\n{\n\n    angle longitude_angle;\n    angle latitude_angle;\n    angle entrylong_angle;\n    angle entrylat_angle;\n    AngleConversion angleconversion;\n    //angleconversion.decimalToDegMinSec(result.longitude, longitude_angle.degrees, longitude_angle.minutes, longitude_angle.seconds);\n    //angleconversion.decimalToDegMinSec(result.latitude, latitude_angle.degrees, latitude_angle.minutes, latitude_angle.seconds);\n    angleconversion.decimalToDegMinSec(parameters.inputstate[1], entrylong_angle.degrees, entrylong_angle.minutes, entrylong_angle.seconds);\n    angleconversion.decimalToDegMinSec(parameters.inputstate[2], entrylat_angle.degrees, entrylat_angle.minutes, entrylat_angle.seconds);\n\n//    angle longitude_angle = double2angle (result.longitude);\n//    angle latitude_angle = double2angle (result.latitude);\n//    angle entrylong_angle = double2angle (parameters.inputstate[1]);\n//    angle entrylat_angle = double2angle (parameters.inputstate[2]);\n    //ofstream report (\"C:/Users/Tizy/Desktop/Code/trunk/sta-src/Entry/REMReport.txt\");\n    ofstream report(\"data/REMReport.txt\");\n\n    //ofstream summary (\"data/REMSummary.txt\");\n\n    switch (status)\n       {\n       case landed:\n            cout << \"Landed\" << endl;\n            report << \"Status report: succesful landing\" << endl;\n            report << \"================================\" << endl;\n            report << \" \" << endl;\n            report << \"Capsule data and initial conditions\" << endl;\n            report << \"--------------------------------\" << endl;\n            //report << \"Capsule base radius:\\t\" << parameters.R << \" m\" << endl; Make consistent with enw schema\n            report << \"Capsule mass:\\t\\t\" << parameters.m << \" kg\" << endl;\n            report << \"Capsule nose radius:\\t\" << parameters.Rn << \" m\" << endl;\n            report << \"Entry altitude:\\t\\t\" << parameters.inputstate[0] / 1000.0 << \" km\" << endl;\n            report << \"Entry longitude:\\t\" << entrylong_angle.degrees << \"° \" << entrylong_angle.minutes << \"' \" << entrylong_angle.seconds << \"'' \" << \"(\" << parameters.inputstate[1] << \"°)\" << endl;\n            report << \"Entry latitude:\\t\\t\" << entrylat_angle.degrees << \"° \" << entrylat_angle.minutes << \"' \" << entrylat_angle.seconds << \"'' \" << \"(\" << parameters.inputstate[2] << \"°)\"<< endl;\n            report << \"Velocity:\\t\\t\" << parameters.inputstate[3] << \" m/s\" << endl;\n            report << \"Flight path angle:\\t\" << parameters.inputstate[4] << \" deg\" << endl;\n            report << \"Heading:\\t\\t\" << parameters.inputstate[5] << \" deg\" << endl;\n            report << \"--------------------------------\" << endl;\n            report << \" \" << endl;\n            report << \"Trajectory data\" << endl;\n            report << \"--------------------------------\" << endl;\n            //report << \"Impact longitude:\\t\" << longitude_angle.degrees << \"° \" << longitude_angle.minutes << \"' \" << longitude_angle.seconds << \"'' \" << \"(\" << result.longitude << \"°)\" << endl;\n            //report << \"Impact latitude:\\t\" << latitude_angle.degrees << \"° \" << latitude_angle.minutes << \"' \" << latitude_angle.seconds << \"'' \" << \"(\" << result.latitude << \"°)\" << endl;\n            report << setprecision (3);\n            report << \"Impact velocity:\\t\" << result.impactvelocity << \" m/s\" << endl;\n            report << fixed;\n            report << \"Total time of flight:\\t\" << result.timeofflight << \" s\" << endl;\n            report << \"--------------------------------\" << endl;\n            report << \" \" << endl;\n            report << \"Load data\" << endl;\n            report << \"--------------------------------\" << endl;\n            report << \"Maximum G load:\\t\\t\\t\" << result.maxloadfactor.value << \" G (limit: \" << settings.maxloadfactor << \" G)\" << endl;\n            report << \"Maximum convective heat rate:\\t\" << result.maxconvheatrate.value << \" W/cm²\" << endl;\n            report << \"Maximum radiative heat rate:\\t\" << result.maxradheatrate.value << \" W/cm²\" << endl;\n            report << \"Maximum total heat rate:\\t\" << result.maxtotalheatrate.value << \" W/cm² (limit: \" << settings.maxheatrate << \" W/cm²)\" << endl;\n            report << \"Total heat load:\\t\\t\" << result.totalheatload << \" J/cm²\" << endl;\n            report << setprecision (3);\n            report << \"TPS mass estimate:\\t\\t\" << result.tpsmass << \" kg (\" << (0.0009 * pow(result.totalheatload,0.5306))*100.0 << \" % of capsule mass)\" << endl;\n            report << fixed;\n            report << \"--------------------------------\" << endl;\n            report << \" \" << endl;\n            report << \"Entry profile: altitude\" << endl;\n            report << \"--------------------------------\" << endl;\n            report << \"Maximum radiative heat rate:\\t\" << result.maxradheatrate.altitude / 1000.0 << \" km\" << endl;\n            report << \"Maximum total heat rate:\\t\" << result.maxtotalheatrate.altitude / 1000.0 << \" km\" << endl;\n            report << \"Maximum convective heat rate:\\t\" << result.maxconvheatrate.altitude / 1000.0 << \" km\" << endl;\n            report << \"Maximum G:\\t\\t\\t\" << result.maxloadfactor.altitude / 1000.0 << \" km\" << endl;\n            report << \"Mach 1 transition:\\t\\t\" << result.Machone_transition_altitude / 1000.0 << \" km\" << endl;\n            report << \"Parachute deployment:\\t\\t\" << result.parachutedeploy_altitude / 1000.0 << \" km (M \" << settings.parachuteDeployMach << \")\" << endl;\n            report << \"--------------------------------\" << endl;\n            report << \" \" << endl;\n            report << \"Entry profile: time (TE = time of entry, TI = time of impact)\" << endl;\n            report << \"--------------------------------\" << endl;\n            report << \"Maximum radiative heat rate:\\tTE + \" << result.maxradheatrate.time << \" s, TI - \" << (result.timeofflight - result.maxradheatrate.time) << \" s\" << endl;\n            report << \"Maximum total heat rate:\\tTE + \" << result.maxtotalheatrate.time << \" s, TI - \" << (result.timeofflight - result.maxtotalheatrate.time) << \" s\" << endl;\n            report << \"Maximum convective heat rate:\\tTE + \" << result.maxconvheatrate.time << \" s, TI - \" << (result.timeofflight - result.maxconvheatrate.time) << \" s\" << endl;\n            report << \"Maximum G:\\t\\t\\tTE + \" << result.maxloadfactor.time << \" s, TI - \" << (result.timeofflight - result.maxloadfactor.time) << \" s\" << endl;\n            report << \"Mach 1 transition:\\t\\tTE + \" << result.Machone_transition_time << \" s, TI - \" << (result.timeofflight - result.Machone_transition_time) << \" s\" << endl;\n            report << \"Parachute deployment:\\t\\tTE + \" << result.parachutedeploy_time << \" s, TI - \" << (result.timeofflight - result.parachutedeploy_time) << \" s (M \" << settings.parachuteDeployMach << \")\" << endl;\n            report << \"================================\";\n            //    summary << longitude_angle.degrees << endl; summary << longitude_angle.minutes << endl; summary << longitude_angle.seconds << endl;\n            //    summary << latitude_angle.degrees << endl; summary << latitude_angle.minutes << endl; summary << latitude_angle.seconds << endl;\n            //    summary << result.maxconvheatrate.value << endl; summary << result.maxconvheatrate.altitude << endl; summary << result.maxconvheatrate.time << endl;\n            //    summary << result.maxradheatrate.value << endl; summary << result.maxradheatrate.altitude << endl; summary << result.maxradheatrate.time << endl;\n            //    summary << result.maxtotalheatrate.value << endl; summary << result.maxtotalheatrate.altitude << endl; summary << result.maxtotalheatrate.time << endl;\n            //    summary << result.maxloadfactor.value << endl; summary << result.maxloadfactor.altitude << endl; summary << result.maxloadfactor.time << endl;\n            //    summary << result.Machone_transition_altitude << endl; summary << result.Machone_transition_time << endl;\n            //    summary << result.parachutedeploy_altitude << endl;  summary << result.parachutedeploy_time << endl;\n            //    summary << result.totalheatload << endl; summary << result.timeofflight << endl; summary << result.impactvelocity << endl;\n            break;\n        case gone:\n            cout << \"Gone\" << endl;\n            report << \"Status report: unsuccesful landing\" << endl;\n            report << \"==================================\" << endl;\n            report << \"The capsule reached maximum altitude after \" << result.timeofflight << \" s\" << endl;\n            break;\n        case crushed:\n            cout << \"Crushed\" << endl;\n            break;\n        case burnt:\n            cout << \"Burnt\" << endl;\n            break;\n        case OK:\n            cout << \"In air\" << endl;\n            break;\n\n\n        }\n\n    report.close();\n    //summary.close();\n}\n", "meta": {"hexsha": "5b31cc16d13b24bbdb247339cabc52f816dc35c8", "size": 26562, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "sta-src/Entry/EntryTrajectory.cpp", "max_stars_repo_name": "hoehnp/SpaceDesignTool", "max_stars_repo_head_hexsha": "9abd34048274b2ce9dbbb685124177b02d6a34ca", "max_stars_repo_licenses": ["IJG"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2018-09-05T12:41:59.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-01T05:34:23.000Z", "max_issues_repo_path": "sta-src/Entry/EntryTrajectory.cpp", "max_issues_repo_name": "hoehnp/SpaceDesignTool", "max_issues_repo_head_hexsha": "9abd34048274b2ce9dbbb685124177b02d6a34ca", "max_issues_repo_licenses": ["IJG"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2015-02-07T19:09:21.000Z", "max_issues_repo_issues_event_max_datetime": "2015-08-14T03:15:42.000Z", "max_forks_repo_path": "sta-src/Entry/EntryTrajectory.cpp", "max_forks_repo_name": "hoehnp/SpaceDesignTool", "max_forks_repo_head_hexsha": "9abd34048274b2ce9dbbb685124177b02d6a34ca", "max_forks_repo_licenses": ["IJG"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2015-03-25T15:50:31.000Z", "max_forks_repo_forks_event_max_datetime": "2017-12-06T12:16:47.000Z", "avg_line_length": 49.4636871508, "max_line_length": 215, "alphanum_fraction": 0.5905428808, "num_tokens": 6563, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.7931059511841119, "lm_q2_score": 0.4301473485858429, "lm_q1q2_score": 0.3411524220494987}}
{"text": "\n#include <iostream>\n#include <valarray> // No nice indexing.\n// We load Eigen just to have nice indexing & printing!\n// Download Eigen & place Eigen/ -> ./Eigen/\n//                        unsupported/ -> Eigen_unsupported/\n#include <Eigen/Dense>\n#include <Eigen_unsupported/Eigen/CXX11/Tensor>\n\nusing namespace std;\nusing namespace Eigen;\n\ntypedef TensorMap<Tensor<int64_t, 3>> TensorMap3d;\ntypedef Matrix<int64_t, 3, 1> Vector3i64;\ntypedef Matrix<int64_t, Dynamic, 1> VectorXi64;\ntypedef Matrix<int64_t, Dynamic, Dynamic> MatrixXi64;\n\nextern \"C\" {\n  int density_gradient(\n                       double* point_ptr,\n                       const int64_t nmo,\n                       const int64_t natm,\n                       const int64_t nprims,\n                       const int64_t mgrp,\n                       const int64_t ngto_h,\n                       int64_t* ngroup_ptr,\n                       int64_t* ityp_ptr,\n                       int64_t* nzexp_ptr,\n                       int64_t* nlm_ptr,\n                       int64_t* nuexp_ptr,\n                       double* occ_ptr,\n                       double* oexp_ptr,\n                       double* xyz_ptr,\n                       double* rcutte_ptr,\n                       double* coef_ptr,\n                       double* grad_ptr\n                      ) ;\n}\n\nint density_gradient(\n                     double* point_ptr,\n                     const int64_t nmo,\n                     const int64_t natm,\n                     const int64_t nprims,\n                     const int64_t mgrp,\n                     const int64_t ngto_h,\n                     int64_t* ngroup_ptr,\n                     int64_t* ityp_ptr,\n                     int64_t* nzexp_ptr,\n                     int64_t* nlm_ptr,\n                     int64_t* nuexp_ptr,\n                     double* occ_ptr,\n                     double* oexp_ptr,\n                     double* xyz_ptr,\n                     double* rcutte_ptr,\n                     double* coef_ptr,\n                     double* grad_ptr\n\t\t\t\t\t\t\t\t\t\t) {\n\n  // input & output variables\n  Map<Vector3d>   point(point_ptr, 3);\n  Map<VectorXi64> ngroup(ngroup_ptr, natm);\n  Map<VectorXi64> ityp(ityp_ptr, nprims);\n  Map<MatrixXi64> nzexp(nzexp_ptr, natm, mgrp);\n  Map<MatrixXi64> nlm(nlm_ptr, 56, 3); // could be static ... => () -> []\n  TensorMap3d     nuexp(nuexp_ptr, natm, mgrp, ngto_h);\n  Map<VectorXd>   occ(occ_ptr, nmo);\n  Map<VectorXd>   oexp(oexp_ptr, nprims);\n  Map<MatrixXd>   xyz(xyz_ptr, natm, 3);\n  Map<MatrixXd>   rcutte(rcutte_ptr, natm, mgrp);\n  Map<MatrixXd>   coef(coef_ptr, 2*nmo, nprims);\n  Map<Vector3d>   grad(grad_ptr, 3);\n  // local variables\n  Vector3d fun   = Vector3d::Zero(3);\n  Vector3d fun1  = Vector3d::Zero(3);\n  Vector3d xcoor = Vector3d::Zero(3);\n  VectorXd gun   = VectorXd::Zero(nmo);\n  MatrixXd gun1  = MatrixXd::Zero(nmo,3);\n  int k, i, itip, n;\n  double dis2, ori, dp2, aexp, x2, x;\n  double f12, f123, fa, fb, fc, cfj;\n  double fac, facgun;\n\n  grad.setZero();\n\n  // Run over centers\n  for ( int ic=0; ic<natm; ic++) {\n    // Atomic coordinates of this center\n    xcoor(0) = point(0) - xyz(ic,0);\n    xcoor(1) = point(1) - xyz(ic,1);\n    xcoor(2) = point(2) - xyz(ic,2);\n    dis2 = xcoor.cwiseAbs2().sum();\n    // Loop over different shell in this atom\n    for ( int m=0; m<ngroup(ic); m++) {\n      k = nuexp(ic, m, 0)-1;\n      // Skip to compute this primitive if distance is too big.\n      if (dis2 > rcutte(ic, m) * rcutte(ic, m) ) {\n        continue;\n      }\n      ori = -oexp(k);\n      dp2 = 2.0*ori;\n      // All primitives in a shell share the same exponent.\n      aexp = exp( ori * dis2 );\n      // Loop over the different primitives in this shell.\n      for ( int jj=0; jj<nzexp(ic,m); jj++) {\n        // \"i\" is the original index of the primitive in the WFN.\n        i = nuexp(ic, m, jj)-1;\n        itip = ityp(i)-1;\n        // Integer coefficients.\n        Vector3i64 it = Vector3i64::Zero();\n        it(0) = nlm(itip,0);\n        it(1) = nlm(itip,1);\n        it(2) = nlm(itip,2);\n\n        for ( int j=0; j<3; j++) {\n          n = it(j);\n          x = xcoor(j);\n          if (n == 0) {\n                  fun1(j) = dp2 * x;\n                  fun(j) = 1.0;\n          } else if (n == 1) {\n                  fun1(j) = 1.0 + dp2 * x * x;\n                  fun(j) = x;\n          } else if (n == 2) {\n                  x2 = x * x;\n                  fun1(j) = x * ( 2.0 + dp2 * x2 );\n                  fun(j) = x2;\n          } else if (n == 3) {\n                  x2 = x * x;\n                  fun1(j) = x2 * ( 3.0 + dp2 * x2 );\n                  fun(j) = x * x2;\n          } else if (n == 4) {\n                  x2 = x * x;\n                  fun1(j) = x2 * x * ( 4.0 + dp2 * x2 );\n                  fun(j) = x2 * x2;\n          } else if (n == 5) {\n                  x2 = x * x;\n                  fun1(j) = x2 * x2 * ( 5.0 + dp2 * x2 );\n                  fun(j) = x2 * x2 * x;\n          }\n        } // endfor j\n        f12 = fun(0) * fun(1) * aexp;\n        f123 = f12 * fun(2);\n        fa = fun1(0) * fun(1) * fun(2) * aexp;\n        fb = fun1(1) * fun(0) * fun(2) * aexp;\n        fc = fun1(2) * f12;\n\n        // run over orbitals\n        for ( int j=0; j<nmo; j++) {\n          cfj = coef(j,i);\n          gun(j) = gun(j) + cfj * f123;\n          gun1(j,0) += cfj * fa;\n          gun1(j,1) += cfj * fb;\n          gun1(j,2) += cfj * fc;\n        }\n\n      } // endfor jj\n    } // endfor m\n  } // endfor ic\n\n  // Run again over orbitals\n  for ( int i=0; i<nmo; i++) {\n    fac = occ(i);\n    facgun = fac * gun(i);\n    for ( int j=0; j<3; j++) {\n      grad(j) += facgun * gun1(i,j);\n    }\n  }\n  grad *= 2.0;\n\n  return EXIT_SUCCESS;\n}\n", "meta": {"hexsha": "6af0e7941b0c2d68152053eec20d197605cb5e70", "size": 5651, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cpp/lib.cpp", "max_stars_repo_name": "zyth0s/bench_density_gradient_wfn", "max_stars_repo_head_hexsha": "54d3cf630c17cd7dd6c87c835d5f3808b2db38ed", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2021-05-17T08:21:54.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-02T12:32:10.000Z", "max_issues_repo_path": "cpp/lib.cpp", "max_issues_repo_name": "zyth0s/bench_density_gradient_wfn", "max_issues_repo_head_hexsha": "54d3cf630c17cd7dd6c87c835d5f3808b2db38ed", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-05-19T20:37:06.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-19T20:37:06.000Z", "max_forks_repo_path": "cpp/lib.cpp", "max_forks_repo_name": "zyth0s/bench_density_gradient_wfn", "max_forks_repo_head_hexsha": "54d3cf630c17cd7dd6c87c835d5f3808b2db38ed", "max_forks_repo_licenses": ["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.6647398844, "max_line_length": 73, "alphanum_fraction": 0.4625729959, "num_tokens": 1722, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.8221891305219504, "lm_q2_score": 0.41489884579676883, "lm_q1q2_score": 0.3411253212802062}}
{"text": "/* \n    Copyright (C) 2008 Wei Dong <wdong@princeton.edu>. All Rights Reserved.\n  \n    This file is part of LSHKIT.\n  \n    LSHKIT is free software: you can redistribute it and/or modify\n    it under the terms of the GNU General Public License as published by\n    the Free Software Foundation, either version 3 of the License, or\n    (at your option) any later version.\n\n    LSHKIT is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n    GNU General Public License for more details.\n\n    You should have received a copy of the GNU General Public License\n    along with LSHKIT.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#include <cmath>\n#include <boost/functional.hpp>\n#include <boost/math/special_functions/digamma.hpp>\n#include <boost/math/tools/roots.hpp>\n\n#include <idmlib/lshkit/common.h>\n#include <idmlib/lshkit/mplsh.h>\n\n#define ABS_ERROR   1e-5l\n#define REL_ERROR   1e-5l\n#define MAX_SHAPE   1000.0l\n#define LIMIT       40000\n\nnamespace lshkit {\n\nstatic GaussianDouble normal;\n\n/* Maximum Likelihood Estimation of gamma distribution */\nclass GammaDoubleMleHelper\n{\n    double rate_; // G / M\npublic:\n    GammaDoubleMleHelper(double rate): rate_(rate) {}\n\n    double operator () (double k)\n    {\n        return std::log(k) - boost::math::digamma(k) + std::log(rate_);\n    }\n};\n\nbool GammaDoubleMleTol (double first, double second)\n{\n    return (second - first) < ABS_ERROR;\n}\n\nGammaDouble GammaDoubleMLE (double M, double G)\n{\n    GammaDoubleMleHelper hlp(G/M);\n    std::pair<double,double> pair = boost::math::tools::bisect(hlp, ABS_ERROR, MAX_SHAPE, GammaDoubleMleTol);\n    double k = (pair.first + pair.second) / 2.0;\n    return GammaDouble(k, M/k);\n}\n\n/* estimate the cost and miss of LSH */\nstatic inline double col_helper (double x)\n{\n    double result;\n    result = 2.0*boost::math::cdf(normal, x) - 1.0;\n    result += std::sqrt(2.0/M_PI) * (std::exp(-x*x/2.0)-1.0)/x;\n    return result; \n}\n\nstatic inline double p_col_helper (double x, double k)\n{\n    return boost::math::cdf(normal,(1.0 + k) * x)\n        - boost::math::cdf(normal, k*x);\n}\n\ndouble MultiProbeLshModel::recall (double x) const\n{\n/*\n    double x2 = W_ / x;\n    double p = col_helper(x2);\n\n\n    unsigned MT =  __probeSequenceTemplates[M_].size();\n    if (MT > T_) MT = T_;\n    \n    double result = 0;\n    for (unsigned i = 0; i < MT; i++)\n    {\n        double r = 1.0;\n        for (unsigned j = 0; j < M_; j++)\n        {\n            Probe &probe = __probeSequenceTemplates[M_][i];\n            if (probe.mask & leftshift(j))\n            {\n                double delta = (j + 1.0) / (M_ + 1.0) * 0.5; // expected value\n                if (probe.shift & leftshift(j))\n                {\n                    r *= p_col_helper(x2, 1.0 - delta);\n                }\n                else\n                {\n                    r *= p_col_helper(x2, delta);\n                }\n            }\n            else r *= p;\n        }\n        result += r;\n    }\n    return 1.0 - std::exp(std::log(1.0 - result) * L_);\n*/\n    return 0;\n}\n\nstruct __MpLshMdlHlpr\n{\n    const MultiProbeLshModel *model;\n    const GammaDouble *gamma;\n};\n/*\nstatic double recall_helper (double xsqr, void *_param)\n{\n    __MpLshMdlHlpr *param = reinterpret_cast<__MpLshMdlHlpr\n        *>(_param);\n    return boost::math::pdf(*param->gamma, xsqr) * param->model->recall(std::sqrt(xsqr));\n}\n*/\nstatic double recall (__MpLshMdlHlpr *param)\n{\n/*\n    static gsl_integration_workspace *workspace = NULL;\n    double f, error;\n    gsl_function I;\n    if (workspace == NULL)\n    {\n        workspace = gsl_integration_workspace_alloc(LIMIT);\n        BOOST_VERIFY(workspace != NULL);\n    }\n    I.params = param;\n    I.function = recall_helper;\n    if (gsl_integration_qagiu(&I, 0.0, ABS_ERROR, REL_ERROR, LIMIT, workspace, &f, &error) != 0) f = 1.0;\n    return f;\n*/\n    return 0;\n}\n\ndouble MultiProbeLshDataModel::avgRecall () const\n{\n    double f = 0.0;\n    __MpLshMdlHlpr param;\n    param.model = this;\n    for (unsigned k = 0; k < topkDists_.size(); k++)\n    {\n        param.gamma = &topkDists_[k];\n        f += lshkit::recall(&param);\n    }\n    f /= topkDists_.size();\n    return f;\n}\n\ndouble MultiProbeLshDataModel::cost () const\n{\n    __MpLshMdlHlpr param;\n    param.model = this;\n    param.gamma = &globalDist_;\n    return lshkit::recall(&param);\n}\n\n}\n", "meta": {"hexsha": "c03452c4bd7e3e1140d1ed7b612301c5ef7d4f8e", "size": 4419, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "source/lshkit/mplsh-model.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/lshkit/mplsh-model.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/lshkit/mplsh-model.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": 25.8421052632, "max_line_length": 109, "alphanum_fraction": 0.617107943, "num_tokens": 1261, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7154239957834733, "lm_q2_score": 0.47657965106367595, "lm_q1q2_score": 0.34095651827306844}}
{"text": "// Flatten.cpp : Defines the entry point for the console application.\n//\n\n#ifdef WIN32\n#define NOMINMAX\n#include <windows.h>\n#endif\n\n#if defined (__APPLE__) || defined (OSX)\n#include <OpenGL/gl.h>\n#include <GLUT/glut.h>\n#else\n#include <GL/gl.h>\n#include <GL/glut.h>\n#endif\n\n#include \"GA/c3ga.h\"\n#include \"GA/c3ga_util.h\"\n#include \"GA/gl_util.h\"\n\n#include \"primitivedraw.h\"\n#include \"gahelper.h\"\n#include \"Laplacian.h\"\n\n#include <memory>\n\n#include <vector>\n#include <queue>\n#include <map>\n#include \"numerics.h\"\n#include \"HalfEdge/Mesh.h\"\n\n#include <Eigen/Core>\n#include <Eigen/Dense>\n#include <Eigen/Sparse>\n#include <Eigen/Geometry>\n\n// #include <ppl.h>\n\n#include \"Benchs.h\"\n\nconst char *WINDOW_TITLE = \"Interactive 3D Shape Deformation using Conformal Geometric Algebra\";\n\n// GLUT state information\nint g_viewportWidth = 800;\nint g_viewportHeight = 600;\n\nvoid display();\nvoid reshape(GLint width, GLint height);\nvoid MouseButton(int button, int state, int x, int y);\nvoid MouseMotion(int x, int y);\nvoid KeyboardUpFunc(unsigned char key, int x, int y);\nvoid SpecialFunc(int key, int x, int y);\nvoid SpecialUpFunc(int key, int x, int y);\nvoid Idle();\nvoid DestroyWindow();\n\n//using namespace boost;\nusing namespace c3ga;\nusing namespace std;\nusing namespace numerics;\n\nclass Camera\n{\npublic:\n\tfloat\t\tpos[3];\n\tfloat\t\tfw[3];\n\tfloat\t\tup[3];\n\tfloat\t\ttranslateVel;\n\tfloat\t\trotateVel;\n\n\tCamera()\n\t{\n\t\tfloat\t\t_pos[] = { 0, 0, -2};\n\t\tfloat\t\t_fw[] = { 0, 0, 1 };\n\t\tfloat\t\t_up[] = { 0, 1, 0 };\n\n\t\ttranslateVel = 0.005;\n\t\trotateVel = 0.005;\n\t\tmemcpy(pos, _pos, sizeof(float)*3);\n\t\tmemcpy(fw, _fw, sizeof(float)*3);\n\t\tmemcpy(up, _up, sizeof(float)*3);\n\t}\n\n\tvoid glLookAt()\n\t{\n\t\tgluLookAt( pos[0], pos[1], pos[2], fw[0],  fw[1],  fw[2], up[0],  up[1],  up[2] );\n\t}\n};\n\nclass VertexBuffer\n{\npublic:\n\tstd::vector<Eigen::Vector3d> deformedPositions; //deformed mesh positions\n\tstd::map<int, Eigen::Vector3d> constrainedPositions; //positional constraints\n\tstd::vector<Eigen::Vector3d> laplacianCoordinates; //laplacian Coordinates\n\tstd::vector<Eigen::Vector3d> normals; //for rendering (lighting)\n\tstd::vector<Eigen::Vector3d> normalsOrig; //original normals\n\tstd::vector<Eigen::Quaterniond> rotors;\n\tstd::vector<Eigen::Matrix4d> JtJ;\n\tstd::vector<Eigen::Vector4d> b;\n\tint size;\n\n\tVertexBuffer() : size(0)\n\t{\n\t}\n\n\tvoid resize(int size)\n\t{\n\t\tthis->size = size;\n\t\tdeformedPositions.resize(size);\n\t\tlaplacianCoordinates.resize(size);\n\t\tnormals.resize(size);\n\t\tnormalsOrig.resize(size);\n\t\trotors.resize(size);\n\t\tJtJ.resize(size);\n\t\tb.resize(size);\n\t}\n\tint get_size() { return size; }\n\n};\n\nclass IndexBuffer {\npublic:\n\tstd::vector<int> faces;\n\tint size;\n\n\tIndexBuffer() : size(0)\n\t{\n\t}\n\n\tvoid resize(int size)\n\t{\n\t\tthis->size = size;\n\t\tfaces.resize(size);\n\t}\n\tint get_size() { return size; }\n\n};\n\nclass Handle\n{\npublic:\n\trotor R;\n\ttranslator T;\n\ttranslator Tcenter;\n\tdualSphere dS;\n\tstd::set<int> constraints;\n\n\tHandle() {\n\t\tT = _rotor(1.0);\n\t\tR = _translator(1.0);\n\t\tTcenter = _translator(1.0);\n\t}\n\tHandle(dualSphere dS)\n\t{\n\t\tnormalizedPoint x = DualSphereCenter(dS);\n\t\tTcenter = exp(-0.5 * _vectorE3GA(x) * ni);\n\t\tT = _translator(1.0);\n\t\tR = _rotor(1.0);\n\t\tthis->dS = dS;\n\t}\n\n\tTRversor GetTRVersor()\n\t{\n\t\treturn _TRversor(T * _TRversor(Tcenter * R * inverse(Tcenter)));\n\t}\n};\n\nCamera g_camera;\nMesh mesh, meshLow;\nmap<int, int> mapping, rotorClusters;\nvectorE3GA g_prevMousePos;\nbool g_rotateModel = false;\nbool g_rotateModelOutOfPlane = false;\nrotor g_modelRotor = _rotor(1.0);\nbool g_rotateKeyRotors = false;\nbool g_translateKeyRotors = false;\nbool g_computeBasis = false;\nfloat g_dragDistance = -1.0f;\nint g_dragObject;\nstd::shared_ptr<SparseMatrix> A;\nstd::shared_ptr<SparseMatrix> AHi;\nEigen::SparseLU<Eigen::SparseMatrix<double>, Eigen::COLAMDOrdering<int>> solverLow, solverHi;\nint systemType = LaplaceBeltrami; //MeanValue; //LaplaceBeltrami\nbool g_showSpheres = true;\nbool g_showWires = false;\nbool g_iterateManyTimes = false;\nEigen::MatrixXd b3Low;\nEigen::MatrixXd xyzLow;\nEigen::MatrixXd b3Hi;\nEigen::MatrixXd xyzHi;\ndouble g_meshArea = 0.0;\n\nbool g_automaticAnimation = false;\nbool g_convergence = false;\nBenchmarks benchs;\n\nVertexBuffer vertexDescriptors;\nVertexBuffer vertexDescriptorsLow;\nIndexBuffer trianglesHi;\nstd::vector<Handle> handles;\n\nEigen::Affine3d MotorToMatrix(const TRversor& R) {\n\tTRversor Ri = inverse(R);\n\n\t// compute images of basis vectors:\n\tc3ga::flatPoint imageOfE1NI = _flatPoint(R * c3ga::e1ni * Ri);\n\tc3ga::flatPoint imageOfE2NI = _flatPoint(R * c3ga::e2ni * Ri);\n\tc3ga::flatPoint imageOfE3NI = _flatPoint(R * c3ga::e3ni * Ri);\n\tc3ga::flatPoint imageOfNONI = _flatPoint(R * c3ga::noni * Ri);\n\n\t// create matrix representation:\n\tEigen::Affine3d M;\n\tM(0, 0) = imageOfE1NI.m_c[0];\n\tM(1, 0) = imageOfE1NI.m_c[1];\n\tM(2, 0) = imageOfE1NI.m_c[2];\n\tM(3, 0) = imageOfE1NI.m_c[3];\n\tM(0, 1) = imageOfE2NI.m_c[0];\n\tM(1, 1) = imageOfE2NI.m_c[1];\n\tM(2, 1) = imageOfE2NI.m_c[2];\n\tM(3, 1) = imageOfE2NI.m_c[3];\n\tM(0, 2) = imageOfE3NI.m_c[0];\n\tM(1, 2) = imageOfE3NI.m_c[1];\n\tM(2, 2) = imageOfE3NI.m_c[2];\n\tM(3, 2) = imageOfE3NI.m_c[3];\n\tM(0, 3) = imageOfNONI.m_c[0];\n\tM(1, 3) = imageOfNONI.m_c[1];\n\tM(2, 3) = imageOfNONI.m_c[2];\n\tM(3, 3) = imageOfNONI.m_c[3];\n\treturn M;\n}\n\nvoid ComputeLaplacianCoordinates(std::shared_ptr<SparseMatrix> A, Mesh* mesh, std::vector<Eigen::Vector3d>& laplacianCoordinates)\n{\n\tstd::fill(laplacianCoordinates.begin(), laplacianCoordinates.end(), Eigen::Vector3d(0, 0, 0));\n\n\tauto numRows = A->numRows();\n\n\tfor (int i = 0; i < numRows; ++i)\n\t{\n\t\tSparseMatrix::RowIterator aIter = A->iterator(i);\n\t\tfor (; !aIter.end(); ++aIter)\n\t\t{\n\t\t\tauto j = aIter.columnIndex();\n\t\t\tlaplacianCoordinates[i] += mesh->vertexAt(j).p * aIter.value();\n\t\t}\n\t}\n}\n\nbool is_constrained(std::set<int>& constraints, int vertex)\n{\n\treturn constraints.find(vertex) != constraints.end();\n}\n\nvoid PreFactor(std::shared_ptr<SparseMatrix> A, std::set<int>& constraints, Eigen::SparseLU<Eigen::SparseMatrix<double>, Eigen::COLAMDOrdering<int>>& solver)\n{\n\n\tEigen::SparseMatrix<double> Lc = Eigen::SparseMatrix<double>(A->numRows(), A->numColumns());\n\n\tauto numRows = A->numRows();\n\tfor (int i = 0; i < numRows; ++i)\n\t{\n\t\tif (!is_constrained(constraints, i))\n\t\t{\n\t\t\tSparseMatrix::RowIterator aIter = A->iterator(i);\n\t\t\tfor (; !aIter.end(); ++aIter)\n\t\t\t{\n\t\t\t\tauto j = aIter.columnIndex();\n\t\t\t\tLc.insert(i, j) = (*A)(i, j);\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\tLc.insert(i, i) = 1.0;\n\t\t}\n\t}\n\n\tLc.makeCompressed();\n\tsolver.compute(Lc);\n\tif (solver.info() != Eigen::Success) {\n\t\t// TODO: error handling\n\t}\n\n}\n\ndouble meshArea(Mesh *mesh)\n{\n\tdouble area = 0.0;\n\tfor(Face& face :  mesh->getFaces())\n\t{\n\t\tEigen::Vector3d\tu = face.edge->next->vertex->p - face.edge->vertex->p;\n\t\tEigen::Vector3d\tv = face.edge->next->next->vertex->p - face.edge->vertex->p;\n\t\tarea += 0.5 * u.cross(v).norm();\n\t}\n\treturn area;\n}\n\nvoid meshMapping(Mesh *meshLow, Mesh *mesh, map<int, int>& mapping)\n{\n\tfor (Vertex& vertexLow : meshLow->getVertices())\n\t{\n\t\tdouble minDist = 1e38;\n\t\tint mappedPoint = -1;\n\t\tEigen::Vector3d& pLow = vertexLow.p;\n\t\tfor (Vertex& vertexHi : mesh->getVertices())\n\t\t{\n\t\t\tEigen::Vector3d& p = vertexHi.p;\n\t\t\tdouble dist = (pLow - p).norm();\n\t\t\tif (dist < minDist) {\n\t\t\t\tminDist = dist;\n\t\t\t\tmappedPoint = vertexHi.ID;\n\t\t\t}\n\t\t}\n\t\tmapping[vertexLow.ID] = mappedPoint;\n\t}\n\n\tvector<bool> visited = vector<bool>(mesh->numVertices(), false);\n\tqueue<int> assigned;\n\n\tfor (auto&& pair : mapping){\n\t\tvisited[pair.second] = true;\n\t\trotorClusters[pair.second] = pair.first;\n\t\tassigned.push(pair.second);\n\t}\n\n\twhile (!assigned.empty())\n\t{\n\t\tint i = assigned.front();\n\t\tassigned.pop();\n\t\tvisited[i] = true;\n\n\t\tfor (Vertex::EdgeAroundIterator edgeAroundIter = mesh->vertexAt(i).iterator(); !edgeAroundIter.end(); edgeAroundIter++)\n\t\t{\n\t\t\tint j = edgeAroundIter.edge_out()->pair->vertex->ID;\n\t\t\tif (visited[j] == false)\n\t\t\t{\n\t\t\t\trotorClusters[j] = rotorClusters[i];\n\t\t\t\tassigned.push(j);\n\t\t\t}\n\t\t}\n\t}\n}\n\nint main(int argc, char* argv[])\n{\n\tmesh.readOBJ(\"cactus2.obj\"); //armadillo-5k-smooth.obj female.obj david.obj rabbit.obj tyra.obj horse.obj cylinder.obj bar.obj planewithpeaks.obj dragon.obj catHead.obj  cactus.obj  bunny.obj  764_hand-olivier-10kf.obj armadillo.obj\n\tmesh.CenterAndNormalize();\n\tmesh.computeNormals();\n\n\tmeshLow.readOBJ(\"cactus1.obj\"); //armadillo-5k-smooth.obj female.obj david.obj rabbit.obj tyra.obj horse.obj cylinder.obj bar.obj planewithpeaks.obj dragon.obj catHead.obj  cactus.obj  bunny.obj  764_hand-olivier-10kf.obj armadillo.obj\n\tmeshLow.CenterAndNormalize();\n\tmeshLow.computeNormals();\n\n\tmeshMapping(&meshLow, &mesh, mapping);\n\n\t// GLUT Window Initialization:\n\tglutInit (&argc, argv);\n\tglutInitWindowSize(g_viewportWidth, g_viewportHeight);\n\tglutInitDisplayMode( GLUT_RGB | GLUT_ALPHA | GLUT_DOUBLE | GLUT_DEPTH);\n\tglutCreateWindow(WINDOW_TITLE);\n\n\t// Register callbacks:\n\tglutDisplayFunc(display);\n\tglutReshapeFunc(reshape);\n\tglutMouseFunc(MouseButton);\n\tglutMotionFunc(MouseMotion);\n\tglutKeyboardUpFunc(KeyboardUpFunc);\n\tglutSpecialFunc(SpecialFunc);\n\tglutSpecialUpFunc(SpecialUpFunc);\n\tglutIdleFunc(Idle);\n\tatexit(DestroyWindow);\n\n\tInitializeDrawing();\n\n\t//cactus.obj\n\thandles.push_back(Handle(_dualSphere(c3gaPoint(.0, .04, 0.7) - 0.5*SQR(0.15)*ni)));\n\thandles.push_back(Handle(_dualSphere(c3gaPoint(.0, .04, -0.8) - 0.5*SQR(0.15)*ni)));\n\n\t////cylinder.obj\n\t//handles.push_back(std::shared_ptr<Handle>(new Handle(_dualSphere(c3gaPoint(.0, 0.9, .0) - 0.5*SQR(0.25)*ni), false, P1)));\n\t//handles.push_back(std::shared_ptr<Handle>(new Handle(_dualSphere(c3gaPoint(.0, -0.9, .0) - 0.5*SQR(0.25)*ni), true, P2)));\n\n\t//Armadillo Pie y Mano\n\t//handles.push_back(std::shared_ptr<Handle>(new Handle(_dualSphere(c3gaPoint(-.5, 0.45, -.3) - 0.5*SQR(0.15)*ni), false, P1)));\n\t//handles.push_back(std::shared_ptr<Handle>(new Handle(_dualSphere(c3gaPoint(.2, -0.6, .1) - 0.5*SQR(0.15)*ni), true, P2)));\n\t//Armadillo Pubis y Cabeza\n\t//handles.push_back(std::shared_ptr<Handle>(new Handle(_dualSphere(c3gaPoint(.0, 0.4, -.2) - 0.5*SQR(0.15)*ni), false, P1)));\n\t//handles.push_back(std::shared_ptr<Handle>(new Handle(_dualSphere(c3gaPoint(.0, -0.05, .1) - 0.5*SQR(0.15)*ni), true, P2)));\n\n\t//handles[0]->extrema = 0;\n\t//handles[1]->extrema = 1;\n\t//extremas[0]->handle = 0;\n\t//extremas[1]->handle = 1;\n\n\tvertexDescriptorsLow.resize(meshLow.numVertices());\n\tvertexDescriptors.resize(mesh.numVertices());\n\ttrianglesHi.resize(mesh.numFaces() * 3);\n\n\tfor( Vertex& vertexLow : meshLow.getVertices())\n\t{\n\t\tvertexDescriptorsLow.rotors[vertexLow.ID] = Eigen::Quaterniond::Identity();\n\t\tnormalizedPoint position = c3gaPoint(vertexLow.p.x(), vertexLow.p.y(), vertexLow.p.z());\n\n\t\tfor (Handle& handle : handles)\n\t\t{\n\t\t\tTRversor TR = handle.GetTRVersor();\n\n\t\t\tif (_double(position << (TR * handle.dS * inverse(TR))) > 0) //inside the sphere\n\t\t\t{\n\t\t\t\thandle.constraints.insert(vertexLow.ID);\n\t\t\t\tvertexDescriptorsLow.constrainedPositions[vertexLow.ID] = vertexLow.p;\n\t\t\t}\n\t\t}\n\t}\n\n\tA = CreateLaplacianMatrix( &meshLow, systemType );\n\t\n\tComputeLaplacianCoordinates(A, &meshLow, vertexDescriptorsLow.laplacianCoordinates);\n\n\tb3Low = Eigen::MatrixXd(A->numRows(), 3);\n\n\tstd::set<int> allconstraints;\n\tfor (Handle& handle : handles) {\n\t\tallconstraints.insert(handle.constraints.begin(), handle.constraints.end());\n\t}\n\tPreFactor(A, allconstraints, solverLow);\n\n\tg_meshArea = meshArea(&meshLow);\n\n\tfor (Vertex& vertexHi : mesh.getVertices()) {\n\t\tvertexDescriptors.normalsOrig[vertexHi.ID] = vertexHi.n;\n\t\tvertexDescriptors.rotors[vertexHi.ID] = Eigen::Quaterniond::Identity();\n\t}\n\n\tfor (Face& face : mesh.getFaces()) {\n\t\tint i = face.ID;\n\t\tint\tv1 = face.edge->vertex->ID;\n\t\tint\tv2 = face.edge->next->vertex->ID;\n\t\tint\tv3 = face.edge->next->next->vertex->ID;\n\t\ttrianglesHi.faces[i * 3 + 0] = v1;\n\t\ttrianglesHi.faces[i * 3 + 1] = v2;\n\t\ttrianglesHi.faces[i * 3 + 2] = v3;\n\t}\n\n\n\tAHi = CreateLaplacianMatrix(&mesh, systemType);\n\tComputeLaplacianCoordinates(AHi, &mesh, vertexDescriptors.laplacianCoordinates);\n\tstd::set<int> constraintsHi;\n\tfor (map<int, int>::iterator iter = mapping.begin(); iter != mapping.end(); iter++){\n\t\tconstraintsHi.insert(iter->second);\n\t}\n\tb3Hi = Eigen::MatrixXd(AHi->numRows(), 3);\n\tPreFactor(AHi, constraintsHi, solverHi);\n\n\tglutMainLoop();\n\n\treturn 0;\n}\n\nvoid transferRotations(Mesh *mesh, std::shared_ptr<SparseMatrix> A, VertexBuffer& vertexDescriptors, VertexBuffer& vertexDescriptorsLow)\n{\n\tfor (auto&& pair : rotorClusters) {\n\t\tvertexDescriptors.rotors[pair.first] = vertexDescriptorsLow.rotors[pair.second];\n\t}\n\n\tstd::fill(vertexDescriptors.laplacianCoordinates.begin(), vertexDescriptors.laplacianCoordinates.end(), Eigen::Vector3d(0, 0, 0));\n\n\t//concurrency::parallel_for_each(mesh->getVertices().begin(), mesh->getVertices().end(), [&](Vertex& vertex)\n\tfor (Vertex& vertex : mesh->getVertices())\n\t{\n\t\tint i = vertex.ID;\n\t\tfor (Vertex::EdgeAroundIterator edgeAroundIter = vertex.iterator(); !edgeAroundIter.end(); edgeAroundIter++)\n\t\t{\n\t\t\tint j = edgeAroundIter.edge_out()->pair->vertex->ID;\n\t\t\tdouble wij = (*A)(i, j);\n\t\t\tEigen::Quaterniond &Ri = vertexDescriptors.rotors[i];\n\t\t\tEigen::Quaterniond &Rj = vertexDescriptors.rotors[j];\n\t\t\tEigen::Vector3d V = mesh->vertexAt(j).p - mesh->vertexAt(i).p;\n\t\t\tvertexDescriptors.laplacianCoordinates[i] += 0.5 * wij * (Ri._transformVector(V) + Rj._transformVector(V));;\n\t\t}\n\t}\n\t//});\n}\n\nvoid SolveLinearSystemTaucs(VertexBuffer& vertexDescriptors)\n{\n\tint n = vertexDescriptors.get_size();\n\n\tfor (int i = 0; i < n; ++i) {\n\t\tb3Low.row(i) = vertexDescriptors.laplacianCoordinates[i];\n\t}\n\n\tfor (Handle& handle : handles) {\n\t\tEigen::Affine3d M = MotorToMatrix(handle.GetTRVersor());\n\t\tfor (int i : handle.constraints) {\n\t\t\tb3Low.row(i) = M * vertexDescriptors.constrainedPositions[i];\n\t\t}\n\t}\n\n\txyzLow = solverLow.solve(b3Low);\n\n\tfor( int i = 0 ; i < n ; ++i ) {\n\t\tvertexDescriptors.deformedPositions[i] = xyzLow.row(i);\n\t}\n}\n\nvoid SolveLinearSystemTaucsHi(VertexBuffer& vertexDescriptors, VertexBuffer& vertexDescriptorsLow)\n{\n\tint n = vertexDescriptors.get_size();\n\n\tfor (int i = 0; i < n; ++i) {\n\t\tb3Hi.row(i) = vertexDescriptors.laplacianCoordinates[i];\n\t}\n\n\tfor (auto&& pair : mapping){\n\t\tb3Hi.row(pair.second) = vertexDescriptorsLow.deformedPositions[pair.first];\n\t}\n\n\txyzHi = solverHi.solve(b3Hi);\n\n\tfor (int i = 0; i < n; ++i) {\n\t\tvertexDescriptors.deformedPositions[i] = xyzHi.row(i);\n\t\tvertexDescriptors.normals[i] = vertexDescriptors.rotors[i]._transformVector(vertexDescriptors.normalsOrig[i]);\n\t}\n}\n\nvoid E3GA_Prep(const vector<Eigen::Vector3d>& P, const vector<Eigen::Vector3d>& Q, double wij2, const int N, Eigen::Matrix4d &JtJ, Eigen::Vector4d &b)\n{\n\tJtJ.setZero();\n\n\tdouble q3p3;\n\tdouble q2p2;\n\tdouble p1q1;\n\tdouble q1p1;\n\tdouble p2q2;\n\tdouble p3q3;\n\tdouble p1q1_2;\n\tdouble p2q2_2;\n\tdouble p3q3_2;\n\tdouble q2p2_2;\n\tdouble q1p1_2;\n\tdouble q3p3_2;\n\n\tfor (int i = 0; i < N; ++i)\n\t{\n\t\tconst Eigen::Vector3d& Pi = P[i];\n\t\tconst Eigen::Vector3d& Qi = Q[i];\n\n\t\tq1p1 = Qi.x() + Pi.x();\n\t\tq2p2 = Qi.y() + Pi.y();\n\t\tq3p3 = Qi.z() + Pi.z();\n\t\tp1q1 = Pi.x() - Qi.x();\n\t\tp2q2 = Pi.y() - Qi.y();\n\t\tp3q3 = Pi.z() - Qi.z();\n\n\t\tp1q1_2 = p1q1 * p1q1;\n\t\tp2q2_2 = p2q2 * p2q2;\n\t\tp3q3_2 = p3q3 * p3q3;\n\t\tq2p2_2 = q2p2 * q2p2;\n\t\tq1p1_2 = q1p1 * q1p1;\n\t\tq3p3_2 = q3p3 * q3p3;\n\n\t\tJtJ(0, 0) += p1q1_2 + p2q2_2 + p3q3_2;\n\t\tJtJ(0, 1) += p1q1 * q2p2 - p2q2 * q1p1;\n\t\tJtJ(0, 2) += p1q1 * q3p3 - p3q3 * q1p1;\n\t\tJtJ(0, 3) += p2q2 * q3p3 - p3q3 * q2p2;\n\t\tJtJ(1, 1) += q2p2_2 + q1p1_2 + p3q3_2;\n\t\tJtJ(1, 2) += q2p2 * q3p3 - p3q3 * p2q2;\n\t\tJtJ(1, 3) += -q1p1 * q3p3 + p3q3 * p1q1;\n\t\tJtJ(2, 2) += q3p3_2 + q1p1_2 + p2q2_2;\n\t\tJtJ(2, 3) += q1p1 * q2p2 - p2q2 * p1q1;\n\t\tJtJ(3, 3) += q3p3_2 + q2p2_2 + p1q1_2;\n\t}\n\n\tb(0) = -JtJ(0, 0);\n\tb(1) = -JtJ(0, 1);\n\tb(2) = -JtJ(0, 2);\n\tb(3) = -JtJ(0, 3);\n\n\tconst double nwij2 = N * wij2 + 1e-6;\n\n\tJtJ(0, 0) += nwij2;\n\tJtJ(1, 1) += nwij2;\n\tJtJ(2, 2) += nwij2;\n\tJtJ(3, 3) += nwij2;\n\n\tJtJ(1, 0) = JtJ(0, 1);\n\tJtJ(2, 0) = JtJ(0, 2);\n\tJtJ(2, 1) = JtJ(1, 2);\n\tJtJ(3, 0) = JtJ(0, 3);\n\tJtJ(3, 1) = JtJ(1, 3);\n\tJtJ(3, 2) = JtJ(2, 3);\n\n\tJtJ = JtJ.inverse().eval();\n}\n\nEigen::Quaterniond E3GA_Fast5(double wij, const vector<Eigen::Quaterniond>& Rq, const Eigen::Quaterniond& Rx, const int N, const Eigen::Matrix4d &JtJ, const Eigen::Vector4d &b)\n{\n\tEigen::Vector4d x;\n\tEigen::Vector4d b2;\n\tb2.setZero();\n\t//const double wij2 = wij;// *wij;\n\n\tfor (int i = 0; i < N; ++i)\n\t{\n\t\tconst Eigen::Quaterniond& Rqi = Rq[i];\n\t\tb2(0) += Rqi.w() - 1.0; // 1.0\n\t\tb2(1) += -Rqi.z(); // e1 ^ e2\n\t\tb2(2) += Rqi.y(); // e1 ^ e3\n\t\tb2(3) += -Rqi.x(); // e2 ^ e3\n\t}\n\n\tb2 *= wij;\n\n\tb2(0) += b(0) + 1e-6 * (Rx.w() - 1.0); // 1.0\n\tb2(1) += b(1) + 1e-6 * -Rx.z(); // e1 ^ e2\n\tb2(2) += b(2) + 1e-6 * Rx.y(); // e1 ^ e3\n\tb2(3) += b(3) + 1e-6 * -Rx.x(); // e2 ^ e3\n\n\tx.noalias() = JtJ * b2;\n\n\treturn Eigen::Quaterniond(1.0 + x(0), -x(3), x(2), -x(1)); //rotor(rotor_scalar_e1e2_e2e3_e3e1, 1.0 + x(0), x(1), x(3), -x(2));\n}\n\nvoid UpdateLaplaciansRotationPrep(Mesh *mesh, std::shared_ptr<SparseMatrix> A, VertexBuffer& vertexDescriptors)\n{\n\t//Matrix3x3 m;\n\t//Matrix3x3 U, W, V, Ut;\n\t//Matrix3x3 M;\n\t//ICP icp;\n\tvector<Eigen::Vector3d> P;\n\tvector<Eigen::Vector3d> Q;\n\n\tP.resize(32);\n\tQ.resize(32);\n\n\tconst double alpha = 0.14;\n\t//concurrency::parallel_for_each(mesh->getVertices().begin(), mesh->getVertices().end(), [&](Vertex& vertex)\n\tfor (Vertex& vertex : mesh->getVertices())\n\t{\n\t\tint i = vertex.ID;\n\n\t\tEigen::Vector3d &pi = vertex.p;\n\t\tEigen::Vector3d &tpi = vertexDescriptors.deformedPositions[i];\n\n\t\tint vertexDegree = 0;\n\t\tfor (Vertex::EdgeAroundIterator edgeAroundIter = vertex.iterator(); vertexDegree < 32 && !edgeAroundIter.end(); edgeAroundIter++, vertexDegree++)\n\t\t{\n\t\t\tint j = edgeAroundIter.edge_out()->pair->vertex->ID;\n\n\t\t\tEigen::Vector3d &tpj = vertexDescriptors.deformedPositions[j];\n\t\t\tEigen::Vector3d &pj = mesh->vertexAt(j).p;\n\t\t\tEigen::Vector3d eij = (pj - pi) * (*A)(i, j);\n\t\t\tEigen::Vector3d teij = tpj - tpi;\n\n\t\t\tP[vertexDegree] = eij;\n\t\t\tQ[vertexDegree] = teij;\n\t\t}\n\t\tdouble invVertexDegree = alpha * g_meshArea / (double)vertexDegree;\n\t\t//rotor M = E3GA4(P, Q, vertexDescriptors[i]->M, vertexDegree);\n\t\t//rotor M = E3GA5(P, Q, vertexDegree);\n\t\tE3GA_Prep(P, Q, invVertexDegree, vertexDegree, vertexDescriptors.JtJ[i], vertexDescriptors.b[i]);\n\t}\n\t//});\n}\n\nvoid UpdateLaplaciansRotationExec(Mesh *mesh, std::shared_ptr<SparseMatrix> A, VertexBuffer& vertexDescriptors, bool updateLaplacian)\n{\n\tconst double alpha = 0.14;\n\tvector<Eigen::Quaterniond> Rq;\n\n\tRq.resize(32);\n\t//concurrency::parallel_for_each(mesh->getVertices().begin(), mesh->getVertices().end(), [&](Vertex& vertex)\n\tfor (Vertex& vertex : mesh->getVertices())\n\t{\n\t\tint i = vertex.ID;\n\n\t\tEigen::Vector3d &pi = vertex.p;\n\t\tEigen::Vector3d &tpi = vertexDescriptors.deformedPositions[i];\n\n\t\tint vertexDegree = 0;\n\t\tfor (Vertex::EdgeAroundIterator edgeAroundIter = vertex.iterator(); vertexDegree < 32 && !edgeAroundIter.end(); edgeAroundIter++, vertexDegree++)\n\t\t{\n\t\t\tint j = edgeAroundIter.edge_out()->pair->vertex->ID;\n\t\t\tRq[vertexDegree] = vertexDescriptors.rotors[j];\n\t\t}\n\t\tdouble invVertexDegree = alpha * g_meshArea / (double)vertexDegree;\n\t\tEigen::Quaterniond M = E3GA_Fast5(invVertexDegree, Rq, vertexDescriptors.rotors[i], vertexDegree, vertexDescriptors.JtJ[i], vertexDescriptors.b[i]);\n\t\tvertexDescriptors.rotors[i] = M.normalized();\n\t}\n\t//});\n\n\tif (!updateLaplacian) {\n\t\treturn;\n\t}\n\n\tstd::fill(vertexDescriptors.laplacianCoordinates.begin(), vertexDescriptors.laplacianCoordinates.end(), Eigen::Vector3d(0, 0, 0));\n\n\t//concurrency::parallel_for_each(mesh->getVertices().begin(), mesh->getVertices().end(), [&](Vertex& vertex)\n\tfor (Vertex& vertex : mesh->getVertices())\n\t{\n\t\tint i = vertex.ID;\n\t\tfor (Vertex::EdgeAroundIterator edgeAroundIter = vertex.iterator(); !edgeAroundIter.end(); edgeAroundIter++)\n\t\t{\n\t\t\tint j = edgeAroundIter.edge_out()->pair->vertex->ID;\n\t\t\tdouble wij = (*A)(i, j);\n\t\t\tEigen::Quaterniond&Ri = vertexDescriptors.rotors[i];\n\t\t\tEigen::Quaterniond&Rj = vertexDescriptors.rotors[j];\n\t\t\tEigen::Vector3d V = mesh->vertexAt(j).p - mesh->vertexAt(i).p;\n\t\t\tvertexDescriptors.laplacianCoordinates[i] += 0.5 * wij * (Ri._transformVector(V) + Rj._transformVector(V));;\n\t\t}\n\t}\n\t//});\n}\n\ndouble ComputeEnergy(Mesh *mesh, std::shared_ptr<SparseMatrix> A, VertexBuffer& vertexDescriptors)\n{\n\tdouble arapEnergy = 0.0;\n\tconst double alpha = 0.08;\n\t//concurrency::parallel_for_each(mesh->vertices.begin(), mesh->vertices.end(), [&](Vertex * vertex)\n\tfor (Vertex& vertex : mesh->getVertices())\n\t{\n\t\tint i = vertex.ID;\n\n\t\tEigen::Vector3d& pi = vertex.p;\n\t\tEigen::Vector3d &tpi = vertexDescriptors.deformedPositions[i];\n\t\tauto& Ri = vertexDescriptors.rotors[i];\n\n\t\tint vertexDegree = 0;\n\t\tfor (Vertex::EdgeAroundIterator edgeAroundIter = vertex.iterator(); !edgeAroundIter.end(); edgeAroundIter++)\n\t\t{\n\t\t\tvertexDegree++;\n\t\t}\n\n\t\tdouble invVertexDegree = alpha * g_meshArea / (double)vertexDegree;\n\n\t\tfor (Vertex::EdgeAroundIterator edgeAroundIter = vertex.iterator(); !edgeAroundIter.end(); edgeAroundIter++)\n\t\t{\n\t\t\tint j = edgeAroundIter.edge_out()->pair->vertex->ID;\n\n\t\t\tEigen::Vector3d &tpj = vertexDescriptors.deformedPositions[j];\n\t\t\tEigen::Vector3d &pj = mesh->vertexAt(j).p;\n\n\t\t\tEigen::Vector3d eij = (pj - pi);\n\t\t\tauto q_ij = tpj - tpi;\n\t\t\tauto p_ij = eij;\n\t\t\tauto& Rj = vertexDescriptors.rotors[j];\n\n\t\t\tarapEnergy += (*A)(i, j) * (Ri._transformVector(p_ij) - q_ij).squaredNorm();\n\t\t\tarapEnergy += invVertexDegree * (Rj.coeffs() - Ri.coeffs()).squaredNorm();\n\t\t}\n\t}//);\n\n\treturn arapEnergy;\n}\n\nvoid display()\n{\n\t/*\n\t *\tmatrices\n\t */\n\tglViewport( 0, 0, g_viewportWidth, g_viewportHeight );\n\tglMatrixMode(GL_PROJECTION);\n\tglLoadIdentity();\n\tpickLoadMatrix();\n\tGLpick::g_frustumFar = 1000.0;\n\tGLpick::g_frustumNear = .1;\n\tgluPerspective( 60.0, (double)g_viewportWidth/(double)g_viewportHeight, GLpick::g_frustumNear, GLpick::g_frustumFar );\n\tglMatrixMode(GL_MODELVIEW);\n\tglLoadIdentity();\n\n\tglShadeModel(GL_SMOOTH);\t//gouraud shading\n\tglClearDepth(1.0f);\n\tglClearColor( .75f, .75f, .75f, .0f );\n\tglHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST );\n\n\t/*\n\t *\testados\n\t */\n\tglEnable(GL_CULL_FACE);\t\t//face culling\n\tglCullFace( GL_BACK );\n\tglFrontFace( GL_CCW );\n\tglEnable(GL_DEPTH_TEST);\t//z-buffer\n\tglDepthFunc(GL_LEQUAL);\n\n\t/*\n\t *\tiluminacion\n\t */\n\tfloat\t\tambient[] = { .3f, .3f, .3f, 1.f };\n\tfloat\t\tdiffuse[] = { .3f, .3f, .3f, 1.f };\n\tfloat\t\tposition[] = { .0f, 0.f, -150.f, 1.f };\n\tfloat\t\tspecular[] = { 1.f, 1.f, 1.f };\n\n\tglLightfv( GL_LIGHT0, GL_AMBIENT, ambient );\n\tglLightfv( GL_LIGHT0, GL_DIFFUSE, diffuse );\n\tglLightf(GL_LIGHT0, GL_CONSTANT_ATTENUATION, 0);\n\tglLightf(GL_LIGHT0, GL_LINEAR_ATTENUATION, 0.0125);\n\tglEnable(  GL_LIGHT0   );\n\tglEnable(  GL_LIGHTING );\n\tglMaterialfv( GL_FRONT_AND_BACK, GL_SPECULAR, specular );\n\tglMaterialf( GL_FRONT_AND_BACK, GL_SHININESS, 50.f );\n\n\tglClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );\n\n\tglLoadIdentity();\n\n\tg_camera.glLookAt();\n\n\tglLightfv( GL_LIGHT0, /*GL_POSITION*/GL_SPOT_DIRECTION, position );\n\n\tglPushMatrix();\n\n\trotorGLMult(g_modelRotor);\n\n\tbenchs.Begin();\n\n\tif(!g_computeBasis)\n\t{\n\t\tstatic bool oneTime = true;\n\t\tif (oneTime || (g_rotateKeyRotors || g_translateKeyRotors || g_automaticAnimation))\n\t\t{\n\t\t\tif(oneTime == true)\n\t\t\t{\n\t\t\t\tSolveLinearSystemTaucs(vertexDescriptorsLow);\n\t\t\t}\n\n\t\t\toneTime = false;\n\n\t\t\tfor(int i = 0 ; i < 3 ; ++i)\n\t\t\t{\n\t\t\t\tUpdateLaplaciansRotationPrep(&meshLow, A, vertexDescriptorsLow);\n\t\t\t\tUpdateLaplaciansRotationExec(&meshLow, A, vertexDescriptorsLow, false);\n\t\t\t\tUpdateLaplaciansRotationExec(&meshLow, A, vertexDescriptorsLow, false);\n\t\t\t\tUpdateLaplaciansRotationExec(&meshLow, A, vertexDescriptorsLow, false);\n\t\t\t\tUpdateLaplaciansRotationExec(&meshLow, A, vertexDescriptorsLow, false);\n\t\t\t\tUpdateLaplaciansRotationExec(&meshLow, A, vertexDescriptorsLow, false);\n\t\t\t\tUpdateLaplaciansRotationExec(&meshLow, A, vertexDescriptorsLow, true);\n\t\t\t\tSolveLinearSystemTaucs(vertexDescriptorsLow);\n\t\t\t}\n\t\t\ttransferRotations(&mesh, AHi, vertexDescriptors, vertexDescriptorsLow);\n\t\t\tSolveLinearSystemTaucsHi(vertexDescriptors, vertexDescriptorsLow);\n\t\t}\n\t}\n\tif(g_iterateManyTimes)\n\t{\n\t\tif (g_convergence)\n\t\t{\n\t\t\tclock_t begin;\n\t\t\tclock_t end;\n\t\t\tdouble avgTime = 0.0;\n\n\t\t\tauto arapEnergy = ComputeEnergy(&meshLow, A, vertexDescriptorsLow);\n\t\t\tint count = 0;\n\t\t\tfor (; count < 2500; ++count)\n\t\t\t{\n\t\t\t\tbegin = clock();\n\n\t\t\t\tUpdateLaplaciansRotationPrep(&meshLow, A, vertexDescriptorsLow);\n\t\t\t\tUpdateLaplaciansRotationExec(&meshLow, A, vertexDescriptorsLow, false);\n\t\t\t\tUpdateLaplaciansRotationExec(&meshLow, A, vertexDescriptorsLow, false);\n\t\t\t\tUpdateLaplaciansRotationExec(&meshLow, A, vertexDescriptorsLow, false);\n\t\t\t\tUpdateLaplaciansRotationExec(&meshLow, A, vertexDescriptorsLow, false);\n\t\t\t\tUpdateLaplaciansRotationExec(&meshLow, A, vertexDescriptorsLow, false);\n\t\t\t\tUpdateLaplaciansRotationExec(&meshLow, A, vertexDescriptorsLow, true);\n\t\t\t\tSolveLinearSystemTaucs(vertexDescriptorsLow);\n\n\t\t\t\tend = clock();\n\n\t\t\t\tdouble secDeform = (double)(end - begin) / CLOCKS_PER_SEC;\n\n\t\t\t\tavgTime += secDeform;\n\n\t\t\t\tauto newArapEnergy = ComputeEnergy(&meshLow, A, vertexDescriptorsLow);\n\t\t\t\tif (fabs(arapEnergy - newArapEnergy) < 1e-4)\n\t\t\t\t{\n\t\t\t\t\tstd::cout << \"convergence after \" << count + 1 << \" iterations\" << std::endl;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tarapEnergy = newArapEnergy;\n\t\t\t}\n\t\t\tarapEnergy = ComputeEnergy(&meshLow, A, vertexDescriptorsLow);\n\t\t\tstd::cout << arapEnergy << std::endl;\n\t\t\tstd::cout << \"Average iteration time (sec): \" << avgTime / (double)(count + 1) << endl;\n\t\t\tstd::cout << \"Total accum time (sec): \" << avgTime << endl;\n\n\t\t\ttransferRotations(&mesh, AHi, vertexDescriptors, vertexDescriptorsLow);\n\t\t\tSolveLinearSystemTaucsHi(vertexDescriptors, vertexDescriptorsLow);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tfor (int i = 0; i < 100; ++i)\n\t\t\t{\n\t\t\t\tUpdateLaplaciansRotationPrep(&meshLow, A, vertexDescriptorsLow);\n\t\t\t\tUpdateLaplaciansRotationExec(&meshLow, A, vertexDescriptorsLow, false);\n\t\t\t\tUpdateLaplaciansRotationExec(&meshLow, A, vertexDescriptorsLow, false);\n\t\t\t\tUpdateLaplaciansRotationExec(&meshLow, A, vertexDescriptorsLow, false);\n\t\t\t\tUpdateLaplaciansRotationExec(&meshLow, A, vertexDescriptorsLow, false);\n\t\t\t\tUpdateLaplaciansRotationExec(&meshLow, A, vertexDescriptorsLow, false);\n\t\t\t\tUpdateLaplaciansRotationExec(&meshLow, A, vertexDescriptorsLow, true);\n\t\t\t\tSolveLinearSystemTaucs(vertexDescriptorsLow);\n\t\t\t}\n\t\t\ttransferRotations(&mesh, AHi, vertexDescriptors, vertexDescriptorsLow);\n\t\t\tSolveLinearSystemTaucsHi(vertexDescriptors, vertexDescriptorsLow);\n\t\t}\n\t\tg_iterateManyTimes = false;\n\t}\n\n\tbenchs.End();\n\n\tif (GLpick::g_pickActive) glLoadName((GLuint)-1);\n\n\tdouble alpha = 1.0;\n\n\t//glEnable (GL_BLEND);\n\t//glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);\n\t//alpha = 0.5;\n\n\t//Mesh-Faces Rendering\n\tglPolygonMode( GL_FRONT_AND_BACK, GL_FILL /*GL_LINE GL_FILL GL_POINT*/);\n\tglEnable (GL_POLYGON_OFFSET_FILL);\n\tglPolygonOffset (1., 1.);\n\tglColorMaterial(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE);\n\tglEnable( GL_COLOR_MATERIAL );\n\tif (GLpick::g_pickActive) glLoadName((GLuint)10);\n\n\tglColor4d(1, 1, 1, alpha);\n\tglEnableClientState(GL_NORMAL_ARRAY);\n\tglEnableClientState(GL_VERTEX_ARRAY);\n\tglVertexPointer(3, GL_DOUBLE, 0, &vertexDescriptors.deformedPositions[0]);\n\tglNormalPointer(GL_DOUBLE, 0, &vertexDescriptors.normals[0]);\n\t// draw the model\n\tglDrawElements(GL_TRIANGLES, trianglesHi.get_size(), GL_UNSIGNED_INT, &trianglesHi.faces[0]);\n\t// deactivate vertex arrays after drawing\n\tglDisableClientState(GL_VERTEX_ARRAY);\n\tglDisableClientState(GL_NORMAL_ARRAY);\n\n\tif (g_showWires)\n\t{\n\t\tif (!GLpick::g_pickActive)\n\t\t{\n\t\t\t//Mesh-Edges Rendering (superimposed to faces)\n\t\t\tglPolygonMode(GL_FRONT_AND_BACK, GL_LINE /*GL_LINE GL_FILL GL_POINT*/);\n\t\t\tglColor4d(.5, .5, .5, alpha);\n\t\t\tglDisable(GL_LIGHTING);\n\t\t\tglEnableClientState(GL_VERTEX_ARRAY);\n\t\t\tglVertexPointer(3, GL_DOUBLE, 0, &vertexDescriptors.deformedPositions[0]);\n\t\t\t// draw the model\n\t\t\tglDrawElements(GL_TRIANGLES, trianglesHi.get_size(), GL_UNSIGNED_INT, &trianglesHi.faces[0]);\n\t\t\t// deactivate vertex arrays after drawing\n\t\t\tglDisableClientState(GL_VERTEX_ARRAY);\n\t\t\tglEnable(GL_LIGHTING);\n\t\t}\n\t}\n\n\t//for (map<int, int>::iterator iter = mapping.begin(); iter != mapping.end(); iter++){\n\t//\tDrawPoint(c3gaPoint(vertexDescriptors[iter->second]->deformedPosition));\n\t//}\n\n\tglDisable( GL_COLOR_MATERIAL );\n\tglDisable(GL_POLYGON_OFFSET_FILL);\n\n\t//glDisable (GL_BLEND);\n\n\tif(g_showSpheres)\n\t{\n\t\t//Handles rendering\n\t\tglPolygonMode( GL_FRONT_AND_BACK, GL_FILL /*GL_LINE GL_FILL GL_POINT*/);\n\n\t\tfloat\tturcoise[] = { .0f, .5f, .5f, 0.3f };\n\t\tfloat\tred[] = { .5f, .0f, .0f, 0.3f };\n\n\t\tfor( int k = 0 ; k < handles.size() ; ++k)\n\t\t{\n\t\t\tif (GLpick::g_pickActive) glLoadName((GLuint)k);\n\t\t\tTRversor R = handles[k].GetTRVersor();\n\t\t\tDrawTransparentDualSphere( _dualSphere( R * handles[k].dS * inverse(R) ), turcoise );\n\t\t}\t\t\n\t}\n\n\tglPopMatrix();\n\n\tglutSwapBuffers();\n}\n\nvoid reshape(GLint width, GLint height)\n{\n\tg_viewportWidth = width;\n\tg_viewportHeight = height;\n\n\t// redraw viewport\n\tglutPostRedisplay();\n}\n\nvectorE3GA mousePosToVector(int x, int y) {\n\tx -= g_viewportWidth / 2;\n\ty -= g_viewportHeight / 2;\n\treturn _vectorE3GA((float)-x * e1 - (float)y * e2);\n}\n\nvoid MouseButton(int button, int state, int x, int y)\n{\n\tg_rotateModel = false;\n\tg_rotateKeyRotors = false;\n\tg_translateKeyRotors = false;\n\n\tif (button == GLUT_LEFT_BUTTON)\n\t{\n\t\tg_prevMousePos = mousePosToVector(x, y);\n\n\t\tGLpick::g_pickWinSize = 1;\n\t\tg_dragObject = pick(x, g_viewportHeight - y, display, &g_dragDistance);\n\n\t\tif(g_dragObject == -1 || g_dragObject == 10 )\n\t\t{\n\t\t\tvectorE3GA mousePos = mousePosToVector(x, y);\n\t\t\tg_rotateModel = true;\n\n\t\t\tif ((_Float(norm_e(mousePos)) / _Float(norm_e(g_viewportWidth * e1 + g_viewportHeight * e2))) < 0.2)\n\t\t\t\tg_rotateModelOutOfPlane = true;\n\t\t\telse g_rotateModelOutOfPlane = false;\n\t\t}\n\t\telse if(g_dragObject >= 0 && g_dragObject < handles.size())\n\t\t{\n\t\t\tg_rotateKeyRotors = true;\n\t\t}\n\t}\n\n\tif (button == GLUT_RIGHT_BUTTON)\n\t{\n\t\tg_prevMousePos = mousePosToVector(x, y);\n\n\t\tGLpick::g_pickWinSize = 1;\n\t\tg_dragObject = pick(x, g_viewportHeight - y, display, &g_dragDistance);\n\n\t\tif(g_dragObject >= 0 && g_dragObject < handles.size())\n\t\t\tg_translateKeyRotors = true;\n\t}\n}\n\nvoid MouseMotion(int x, int y)\n{\n\tif (g_rotateModel || g_rotateKeyRotors || g_translateKeyRotors )\n\t{\n\t\t// get mouse position, motion\n\t\tvectorE3GA mousePos = mousePosToVector(x, y);\n\t\tvectorE3GA motion = mousePos - g_prevMousePos;\n\n\t\tif (g_rotateModel)\n\t\t{\n\t\t\t// update rotor\n\t\t\tif (g_rotateModelOutOfPlane)\n\t\t\t\tg_modelRotor = exp(g_camera.rotateVel * (motion ^ e3) ) * g_modelRotor;\n\t\t\telse \n\t\t\t\tg_modelRotor = exp(0.00001f * (motion ^ mousePos) ) * g_modelRotor;\n\t\t}\n\t\tif(g_rotateKeyRotors)\n\t\t{\n\t\t\t//rotor R1 =  _rotor( inverse(g_modelRotor) * exp(-g_camera.rotateVel * (motion ^ e3) ) * g_modelRotor);\n\t\t\trotor R1 =  _rotor( exp(-g_camera.rotateVel * (motion ^ e3) ) );\n\t\t\tif(g_dragObject < handles.size())\n\t\t\t{\n\t\t\t\trotor R = handles[g_dragObject].R;\n\t\t\t\thandles[g_dragObject].R = normalize(_TRversor( R1 * R  ) );\n\t\t\t}\n\t\t}\n\n\t\tif(g_translateKeyRotors)\n\t\t{\n\t\t\tnormalizedTranslator T1 = _normalizedTranslator(inverse(g_modelRotor) * exp( _freeVector(-g_camera.translateVel*motion*ni) ) * g_modelRotor);\n\t\t\tif(g_dragObject < handles.size())\n\t\t\t{\n\t\t\t\ttranslator T = handles[g_dragObject].T;\n\t\t\t\thandles[g_dragObject].T = normalize(_TRversor( T1 * T ));\n\t\t\t}\n\t\t}\n\n\t\t// remember mouse pos for next motion:\n\t\tg_prevMousePos = mousePos;\n\n\t\t// redraw viewport\n\t\tglutPostRedisplay();\n\t}\n}\n\nvoid SpecialFunc(int key, int x, int y)\n{\n\tswitch(key) {\n\t\tcase GLUT_KEY_F1 :\n\t\t\t{\n\t\t\t\tint mod = glutGetModifiers();\n\t\t\t\tif(mod == GLUT_ACTIVE_CTRL || mod == GLUT_ACTIVE_SHIFT )\n\t\t\t\t{\n\t\t\t\t}\n\t\t\t}\n\t\t\tbreak;\n\t\tcase GLUT_KEY_UP:\n\t\t\t{\n\t\t\t\tif(g_rotateKeyRotors)\n\t\t\t\t{\n\t\t\t\t\thandles[g_dragObject].dS = ChangeDualSphereRadiusSize(handles[g_dragObject].dS, 0.025);\n\n\t\t\t\t\t// redraw viewport\n\t\t\t\t\tglutPostRedisplay();\n\t\t\t\t}\n\t\t\t}\n\t\t\tbreak;\n\t\tcase GLUT_KEY_DOWN:\n\t\t\t{\n\t\t\t\tif(g_rotateKeyRotors)\n\t\t\t\t{\n\t\t\t\t\thandles[g_dragObject].dS = ChangeDualSphereRadiusSize(handles[g_dragObject].dS, -0.025);\n\n\t\t\t\t\t// redraw viewport\n\t\t\t\t\tglutPostRedisplay();\n\t\t\t\t}\n\t\t\t}\n\t\t\tbreak;\n\t}\n}\n\nvoid SpecialUpFunc(int key, int x, int y)\n{\n}\n\nvoid KeyboardUpFunc(unsigned char key, int x, int y)\n{\n\tif (key == 'c' || key == 'C')\n\t{\n\t\tg_convergence = !g_convergence;\n\t\tvectorE3GA motion = _vectorE3GA(-70.0, -60.0, 0);\n\t\tnormalizedTranslator T1 = _normalizedTranslator(inverse(g_modelRotor) * exp(_freeVector(-g_camera.translateVel*motion*ni)) * g_modelRotor);\n\t\ttranslator T = handles[0].T;\n\t\thandles[0].T = normalize(_TRversor(T1 * T));\n\n\t\tglutPostRedisplay();\n\t}\n\n\tif (key == 'a' || key == 'A')\n\t{\n\t\tg_automaticAnimation = !g_automaticAnimation;\n\t\tif (g_automaticAnimation)\n\t\t{\n\t\t\tbenchs.Start();\n\t\t}\n\t\telse\n\t\t{\n\t\t\tbenchs.Stop();\n\t\t}\n\n\t\tglutPostRedisplay();\n\t}\n\n\tif(key == 'w' || key == 'W')\n\t{\n\t\tg_showWires = !g_showWires;\n\t\tglutPostRedisplay();\n\t}\n\t\n\tif( key == 'h' || key == 'H' )\n\t{\n\t\tg_showSpheres = !g_showSpheres;\n\t\tglutPostRedisplay();\n\t}\n\n\tif( key == 'x' || key == 'X' )\n\t{\n\t\tg_iterateManyTimes = true;\n\t\tglutPostRedisplay();\n\t}\n}\n\nvoid Idle()\n{\n\t// redraw viewport\n\tif (g_automaticAnimation)\n\t{\n\t\tconst int minCount = -50;\n\t\tconst int maxCount = 50;\n\t\tstatic int mycount = 0;\n\t\tstatic int direction = 0;\n\t\tvectorE3GA motion = _vectorE3GA(1.0, 0, 0);\n\t\tif (mycount == maxCount)\n\t\t{\n\t\t\tdirection = 1;\n\t\t}\n\t\tif (mycount == minCount)\n\t\t{\n\t\t\tdirection = 0;\n\t\t}\n\n\t\tif (mycount < maxCount && direction == 0)\n\t\t{\n\t\t\tmotion = _vectorE3GA(1.0, 0, 0);\n\t\t\tmycount++;\n\t\t}\n\t\tif (mycount > minCount && direction == 1)\n\t\t{\n\t\t\tmotion = _vectorE3GA(-1.0, 0, 0);\n\t\t\tmycount--;\n\t\t}\n\n\t\tnormalizedTranslator T1 = _normalizedTranslator(inverse(g_modelRotor) * exp(_freeVector(-g_camera.translateVel*motion*ni)) * g_modelRotor);\n\t\ttranslator T = handles[0].T;\n\t\thandles[0].T = normalize(_TRversor(T1 * T));\n\n\t\tif (!benchs.IsStarted())\n\t\t{\n\t\t\tbenchs.Start();\n\t\t}\n\n\t\tglutPostRedisplay();\n\t}\n}\n\nvoid DestroyWindow()\n{\n\tReleaseDrawing();\n}\n\n", "meta": {"hexsha": "c35a6cc3b5b889b1cab3cd33f727ef4cd7e35428", "size": 33709, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Flatten.cpp", "max_stars_repo_name": "mauriciocele/arap-sr", "max_stars_repo_head_hexsha": "b0a70d7dcdb62adbcaf396cb60ae4ddcc54c9da2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2020-01-10T17:26:34.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T10:40:58.000Z", "max_issues_repo_path": "src/Flatten.cpp", "max_issues_repo_name": "mauriciocele/arap-sr", "max_issues_repo_head_hexsha": "b0a70d7dcdb62adbcaf396cb60ae4ddcc54c9da2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Flatten.cpp", "max_forks_repo_name": "mauriciocele/arap-sr", "max_forks_repo_head_hexsha": "b0a70d7dcdb62adbcaf396cb60ae4ddcc54c9da2", "max_forks_repo_licenses": ["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.6076986077, "max_line_length": 236, "alphanum_fraction": 0.6839123083, "num_tokens": 11059, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7154239957834733, "lm_q2_score": 0.47657965106367595, "lm_q1q2_score": 0.34095651827306844}}
{"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/Types.h\"\n#include \"latbuilder/Parser/SizeParam.h\"\n#include \"latbuilder/Parser/Weights.h\"\n#include \"latbuilder/Parser/FigureOfMerit.h\"\n#include \"latbuilder/Parser/MeritFilterList.h\"\n#include \"latbuilder/TextStream.h\"\n#include \"latbuilder/LFSR258.h\"\n\n#include \"latbuilder/GenSeq/VectorCreator.h\"\n#include \"latbuilder/GenSeq/CoprimeIntegers.h\"\n#include \"latbuilder/LatSeq/Combiner.h\"\n\n#include \"latbuilder/MeritSeq/CBC.h\"\n#include \"latbuilder/MeritSeq/CoordUniformCBC.h\"\n#include \"latbuilder/MeritSeq/CoordUniformInnerProd.h\"\n#include \"latbuilder/MeritSeq/LatSeqOverCBC.h\"\n\n#include <boost/lexical_cast.hpp>\n\nusing namespace LatBuilder;\nusing TextStream::operator<<;\n\ntemplate <typename T1, typename T2, typename T3, typename T4>\nvoid printTableRow(\n      const T1& x1,\n      const T2& x2,\n      const T3& x3,\n      const T4& x4\n      )\n{\n   using namespace std;\n   cout << x1 << '\\t';\n   cout << scientific << setprecision(8) << x2 << '\\t';\n   cout << scientific << setprecision(8) << x3 << '\\t';\n   cout << scientific << setprecision(8) << x4 << endl;;\n}\n\nstruct Execute {\n   template <class FIG2>\n   void operator()(\n         FIG2 fig2,\n         const std::string& fig1,\n         std::unique_ptr<LatticeTester::Weights> weights1,\n         LatBuilder::SizeParam<LatticeType::ORDINARY, EmbeddingType::UNILEVEL> size,\n         Dimension dimension,\n         MeritFilterList<LatticeType::ORDINARY, EmbeddingType::UNILEVEL> filters,\n         size_t nrand\n         ) const\n   {\n      Parser::FigureOfMerit<LatticeType::ORDINARY>::parse(\n\t    \"2\",\n            fig1,\n            1,\n            std::move(weights1),\n            *this,\n            std::move(fig2),\n            std::move(size),\n            dimension,\n            std::move(filters),\n            nrand\n            );\n   }\n\n   template <class FIG1, class FIG2>\n   void operator()(\n         FIG1 fig1,\n         FIG2 fig2,\n         LatBuilder::SizeParam<LatticeType::ORDINARY, EmbeddingType::UNILEVEL> size,\n         Dimension dimension,\n         MeritFilterList<LatticeType::ORDINARY, EmbeddingType::UNILEVEL> filters,\n         size_t nrand\n         ) const\n   {\n      Storage<LatticeType::ORDINARY, EmbeddingType::UNILEVEL, fig1.suggestedCompression()> storage1(size);\n      Storage<LatticeType::ORDINARY, EmbeddingType::UNILEVEL, fig2.suggestedCompression()> storage2(size);\n\n      typedef GenSeq::CoprimeIntegers<fig1.suggestedCompression(), Traversal::Random<LFSR258>> Coprime;\n      auto genSeqs = GenSeq::VectorCreator<Coprime>::create(size, dimension, nrand);\n      genSeqs[0] = GenSeq::Creator<Coprime>::create(SizeParam<LatticeType::ORDINARY, EmbeddingType::UNILEVEL>(2));\n\n      auto latSeq = LatSeq::combine<Zip>(size, std::move(genSeqs));\n\n      auto lsoc1 = MeritSeq::latSeqOverCBC(MeritSeq::cbc(storage1, fig1));\n      auto lsoc2 = MeritSeq::latSeqOverCBC(MeritSeq::cbc(storage2, fig2));\n\n      auto fseq1 = filters.apply(lsoc1.meritSeq(latSeq));\n      auto fseq2 = filters.apply(lsoc2.meritSeq(latSeq));\n\n      printTableRow(\"gen\", fig1.name(), fig2.name(),\n            \"rel\" + fig1.name() + \"m\" + fig2.name());\n      \n      auto it1 = fseq1.begin();\n      auto it2 = fseq2.begin();\n      while (it1 != fseq1.end()) {\n         printTableRow(\n               it1.base().base()->gen(),\n               *it1,\n               *it2,\n               (*it1 - *it2) / *it1\n               );\n         ++it1;\n         ++it2;\n      }\n\n   }\n};\n\nint main(int argc, const char *argv[])\n{\n   if (argc < 7 + 1) {\n      std::cerr << \"usage: correlation <nrand> <size> <dimension> <figure1> <weights1> <figure2> <weights2> [<filter> [...]]\" << std::endl;\n      return 1;\n   }\n\n   int iarg = 1;\n   auto nrand = boost::lexical_cast<size_t>(argv[iarg++]);\n   auto size = Parser::SizeParam<LatticeType::ORDINARY, EmbeddingType::UNILEVEL>::parse(argv[iarg++]);\n   auto dimension = boost::lexical_cast<Dimension>(argv[iarg++]);\n   std::string figSpec1 = argv[iarg++];\n   std::string weightsSpec1 = argv[iarg++];\n   std::string figSpec2 = argv[iarg++];\n   std::string weightsSpec2 = argv[iarg++];\n   std::vector<std::string> filtersSpec(&argv[iarg], &argv[argc]);\n\n   auto weights1 = Parser::Weights::parse(weightsSpec1);\n   auto weights2 = Parser::Weights::parse(weightsSpec2);\n\n   auto filters = Parser::MeritFilterList<LatticeType::ORDINARY>::parse(\"\", filtersSpec, size, *weights1, 2);\n\n   Parser::FigureOfMerit<LatticeType::ORDINARY>::parse(\n         \"2\",\n         figSpec2,\n         1,\n         std::move(weights2),\n         Execute(),\n         figSpec1,\n         std::move(weights1),\n         std::move(size),\n         dimension,\n         std::move(filters),\n         nrand\n         );\n\n   return 0;\n}\n", "meta": {"hexsha": "044eff8c1f6ea7493b487af745cf12599eb7686b", "size": 5382, "ext": "cc", "lang": "C++", "max_stars_repo_path": "examples/correlation.cc", "max_stars_repo_name": "YochevedDarmon/latnetbuilder", "max_stars_repo_head_hexsha": "7df3a7ba89e10ca51d4af347b75cdb0987e5151c", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2020-01-21T06:08:51.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-24T16:11:31.000Z", "max_issues_repo_path": "examples/correlation.cc", "max_issues_repo_name": "YochevedDarmon/latnetbuilder", "max_issues_repo_head_hexsha": "7df3a7ba89e10ca51d4af347b75cdb0987e5151c", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2019-10-31T07:49:28.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-03T12:07:49.000Z", "max_forks_repo_path": "examples/correlation.cc", "max_forks_repo_name": "YochevedDarmon/latnetbuilder", "max_forks_repo_head_hexsha": "7df3a7ba89e10ca51d4af347b75cdb0987e5151c", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2016-07-27T19:25:26.000Z", "max_forks_repo_forks_event_max_datetime": "2018-05-22T20:00:47.000Z", "avg_line_length": 33.2222222222, "max_line_length": 139, "alphanum_fraction": 0.6376811594, "num_tokens": 1456, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7154239836484143, "lm_q2_score": 0.47657965106367595, "lm_q1q2_score": 0.3409565124897463}}
{"text": "#include <scitbx/array_family/boost_python/flex_fwd.h>\n\n#include <scitbx/array_family/boost_python/flex_wrapper.h>\n#include <scitbx/serialization/single_buffered.h>\n#include <scitbx/matrix/transpose_multiply.h>\n#include <scitbx/math/utils.h>\n#include <boost/python/make_constructor.hpp>\n#include <boost/python/args.hpp>\n#include <boost/python/return_arg.hpp>\n#include <boost/format.hpp>\n#include \"flex_helpers.h\"\n\nnamespace scitbx { namespace serialization { namespace single_buffered {\n\n  inline\n  char* to_string(char* start, vec3<double> const& value)\n  {\n    return\n      to_string(to_string(to_string(start, value[0]), value[1]), value[2]);\n  }\n\n  template <>\n  struct from_string<vec3<double> >\n  {\n    from_string(const char* start)\n    {\n      end = start;\n      for(std::size_t i=0;i<3;i++) {\n        from_string<double> proxy(end);\n        value[i] = proxy.value;\n        end = proxy.end;\n      }\n    }\n\n    vec3<double> value;\n    const char* end;\n  };\n\n}}} // namespace scitbx::serialization::single_buffered\n\n#include <scitbx/array_family/boost_python/flex_pickle_single_buffered.h>\n\nnamespace scitbx { namespace af {\nnamespace {\n\n  flex<vec3<double> >::type*\n  join(\n    af::const_ref<double> const& x,\n    af::const_ref<double> const& y,\n    af::const_ref<double> const& z)\n  {\n    SCITBX_ASSERT(y.size() == x.size());\n    SCITBX_ASSERT(z.size() == x.size());\n    af::shared<vec3<double> > result((af::reserve(x.size())));\n    for(std::size_t i=0;i<x.size();i++) {\n      result.push_back(vec3<double>(x[i],y[i],z[i]));\n    }\n    return new flex<vec3<double> >::type(result, result.size());\n  }\n\n  flex<vec3<double> >::type*\n  from_double(\n    af::const_ref<double> const& x)\n  {\n    SCITBX_ASSERT(x.size() % 3 == 0);\n    std::size_t result_size = x.size() / 3;\n    af::shared<vec3<double> > result((af::reserve(result_size)));\n    const double* d = x.begin();\n    for(std::size_t i=0;i<result_size;i++) {\n      result.push_back(vec3<double>(d));\n      d += 3;\n    }\n    return new flex<vec3<double> >::type(result, result.size());\n  }\n\n  boost::python::tuple\n  part_names()\n  {\n    return boost::python::make_tuple(\"x\", \"y\", \"z\");\n  }\n\n  boost::python::tuple\n  parts(\n    versa<vec3<double>, flex_grid<> > const& O)\n  {\n    tiny<versa<double, flex_grid<> >, 3> result;\n    std::size_t n = O.size();\n    for(std::size_t i=0;i<3;i++) {\n      result[i].resize(O.accessor());\n      for(std::size_t j=0;j<n;j++) {\n        result[i][j] = O[j][i];\n      }\n    }\n    return boost::python::make_tuple(result[0], result[1], result[2]);\n  }\n\n  af::shared<vec3<double> >\n  rotate_around_origin(\n    flex<vec3<double> >::type const& a,\n    vec3<double> const& direction,\n    double const& angle)\n  {\n    SCITBX_ASSERT(direction.length() > 0)(direction.length());\n    vec3<double> unit = direction.normalize();\n    af::shared<vec3<double> > result((af::reserve(a.size())));\n    for(std::size_t i=0;i<a.size();i++) {\n      result.push_back(a[i].unit_rotate_around_origin(\n        unit, angle));\n    }\n    return result;\n  }\n\n  af::shared<vec3<double> >\n  rotate_around_origin(\n    flex<vec3<double> >::type const& a,\n    vec3<double> const& direction,\n    flex<double>::type const& angles)\n  {\n    SCITBX_ASSERT(direction.length() > 0)(direction.length());\n    vec3<double> unit = direction.normalize();\n    af::shared<vec3<double> > result((af::reserve(a.size())));\n    for(std::size_t i=0;i<a.size();i++) {\n      result.push_back(a[i].unit_rotate_around_origin(\n        unit, angles[i]));\n    }\n    return result;\n  }\n\n  af::shared<vec3<double> >\n  rotate_around_origin(\n    flex<vec3<double> >::type const& a,\n    flex<vec3<double> >::type const& directions,\n    flex<double>::type const& angles)\n  {\n    af::shared<vec3<double> > result((af::reserve(a.size())));\n    SCITBX_ASSERT(directions.size() == a.size());\n    SCITBX_ASSERT(angles.size() == a.size());\n    for(std::size_t i=0;i<a.size();i++) {\n      SCITBX_ASSERT(directions[i].length() > 0)(directions[i].length());\n      vec3<double> unit = directions[i].normalize();\n      result.push_back(a[i].unit_rotate_around_origin(\n        unit, angles[i]));\n    }\n    return result;\n  }\n\n  af::shared<double> angle(\n      af::const_ref< vec3<double> > const& self,\n      vec3<double> other, bool deg) {\n    af::shared<double> result(self.size());\n    for (std::size_t i = 0; i < self.size(); ++i) {\n      boost::optional<double> oa = self[i].angle_rad(other);\n      if (oa) {\n        double a = *oa;\n        if (deg) {\n          a = rad_as_deg(a);\n        }\n        result[i] = a;\n      } else {\n        result[i] = 0.0;\n      }\n    }\n    return result;\n  }\n\n  af::shared<double> angle(\n      af::const_ref< vec3<double> > const& self,\n      af::const_ref< vec3<double> > const& other,\n      bool deg) {\n    SCITBX_ASSERT(self.size() == other.size());\n    af::shared<double> result(self.size());\n    for (std::size_t i = 0; i < self.size(); ++i) {\n      boost::optional<double> oa = self[i].angle_rad(other[i]);\n      if (oa) {\n        double a = *oa;\n        if (deg) {\n          a = rad_as_deg(a);\n        }\n        result[i] = a;\n      } else {\n        result[i] = 0.0;\n      }\n    }\n    return result;\n  }\n\n\n  flex_double\n  as_double(flex<vec3<double> >::type const& a)\n  {\n    SCITBX_ASSERT(a.accessor().is_trivial_1d());\n    flex_double result(a.size()*3, init_functor_null<double>());\n    double* r = result.begin();\n    const_ref<vec3<double> > a_ref = a.const_ref().as_1d();\n    for(std::size_t i=0;i<a_ref.size();i++) {\n      for(std::size_t j=0;j<3;j++) {\n        *r++ = a_ref[i][j];\n      }\n    }\n    return result;\n  }\n\n  vec3<double>\n  vec3_min(flex<vec3<double> >::type const& a)\n  {\n    SCITBX_ASSERT(!a.accessor().is_padded());\n    vec3<double> result(0,0,0);\n    af::const_ref<vec3<double>, af::flex_grid<> > a_ref = a.const_ref();\n    if (a_ref.size() > 0) {\n      result = a_ref[0];\n      for(std::size_t i=1;i<a_ref.size();i++) {\n        result.each_update_min(a_ref[i]);\n      }\n    }\n    return result;\n  }\n\n  vec3<double>\n  vec3_max(flex<vec3<double> >::type const& a)\n  {\n    SCITBX_ASSERT(!a.accessor().is_padded());\n    vec3<double> result(0,0,0);\n    af::const_ref<vec3<double>, af::flex_grid<> > a_ref = a.const_ref();\n    if (a_ref.size() > 0) {\n      result = a_ref[0];\n      for(std::size_t i=1;i<a_ref.size();i++) {\n        result.each_update_max(a_ref[i]);\n      }\n    }\n    return result;\n  }\n\n  af::shared<vec3<double> >\n  round(\n    af::const_ref<vec3<double> > const& a,\n    int n_digits)\n  {\n    af::shared<vec3<double> > result((af::reserve(a.size())));\n    for (std::size_t i=0; i<a.size(); i++) {\n      vec3<double> const& src = a[i];\n      vec3<double> result_i;\n      for (std::size_t j=0; j<3; j++) {\n        result_i[j] = math::round(src[j], n_digits);\n      }\n      result.push_back(result_i);\n    }\n    return result;\n  }\n\n  af::shared<vec3<int> >\n  iround(\n    af::const_ref<vec3<double> > const& a)\n  {\n    af::shared<vec3<int> > result((af::reserve(a.size())));\n    for (std::size_t i=0; i<a.size(); i++) {\n      vec3<double> const& src = a[i];\n      vec3<int> result_i;\n      for (std::size_t j=0; j<3; j++) {\n        result_i[j] = math::iround(src[j]);\n      }\n      result.push_back(result_i);\n    }\n    return result;\n  }\n\n  vec3<double>\n  mean_weighted_a_a(\n    af::const_ref<vec3<double> > const& self,\n    af::const_ref<double> const& weights)\n  {\n    return af::mean_weighted(self, weights);\n  }\n\n  af::shared<vec3<double> >\n  mul_a_scalar(\n    af::const_ref<vec3<double> > const& a,\n    double f)\n  {\n    af::shared<vec3<double> > result((af::reserve(a.size())));\n    for(std::size_t i=0;i<a.size();i++) {\n      result.push_back(a[i] * f);\n    }\n    return result;\n  }\n\n  af::shared<vec3<double> >\n  mul_a_a_scalar(\n    af::const_ref<vec3<double> > const& lhs,\n    af::const_ref<double> const& rhs)\n  {\n    SCITBX_ASSERT(lhs.size() == rhs.size());\n    af::shared<vec3<double> > result((af::reserve(lhs.size())));\n    for(std::size_t i=0;i<lhs.size();i++) {\n      result.push_back(lhs[i] * rhs[i]);\n    }\n    return result;\n  }\n\n  void\n  imul_a_scalar(\n    af::ref<vec3<double> > const& a,\n    double f)\n  {\n    for(std::size_t i=0;i<a.size();i++) a[i] *= f;\n  }\n\n  af::shared<vec3<double> >\n  div_a_as(\n    af::ref<vec3<double> > const& lhs,\n    af::ref<double> const& rhs)\n  {\n    SCITBX_ASSERT(lhs.size() == rhs.size());\n    af::shared<vec3<double> > result((af::reserve(lhs.size())));\n    for(std::size_t i=0;i<lhs.size();i++) {\n      SCITBX_ASSERT(rhs[i] != 0);\n      result.push_back(lhs[i] / rhs[i]);\n    }\n    return result;\n  }\n\n  af::shared<vec3<double> >\n  mul_a_mat3(\n    af::const_ref<vec3<double> > const& a,\n    mat3<double> const& m)\n  {\n    af::shared<vec3<double> > result((af::reserve(a.size())));\n    for(std::size_t i=0;i<a.size();i++) {\n      result.push_back(a[i] * m);\n    }\n    return result;\n  }\n\n  af::shared<vec3<double> >\n  rmul_a_mat3(\n    af::const_ref<vec3<double> > const& a,\n    mat3<double> const& m)\n  {\n    mat3<double> m_transposed = m.transpose();\n    af::shared<vec3<double> > result((af::reserve(a.size())));\n    for(std::size_t i=0;i<a.size();i++) {\n      result.push_back(a[i] * m_transposed);\n    }\n    return result;\n  }\n\n  af::shared<double>\n  dot_a_a(\n    af::const_ref<vec3<double> > const& lhs,\n    af::const_ref<vec3<double> > const& rhs)\n  {\n    SCITBX_ASSERT(lhs.size() == rhs.size());\n    af::shared<double> result((af::reserve(lhs.size())));\n    for(std::size_t i=0;i<lhs.size();i++) {\n      result.push_back(lhs[i] * rhs[i]);\n    }\n    return result;\n  }\n\n  af::shared<double>\n  dot_a_s(\n    af::const_ref<vec3<double> > const& lhs,\n    vec3<double> rhs)\n  {\n    af::shared<double> result((af::reserve(lhs.size())));\n    for(std::size_t i=0;i<lhs.size();i++) {\n      result.push_back(lhs[i] * rhs);\n    }\n    return result;\n  }\n\n  af::shared<double>\n  dot_a(\n    af::const_ref<vec3<double> > const& lhs)\n  {\n    af::shared<double> result((af::reserve(lhs.size())));\n    for(std::size_t i=0;i<lhs.size();i++) {\n      result.push_back(lhs[i] * lhs[i]);\n    }\n    return result;\n  }\n\n  af::shared<vec3<double> >\n  cross_a_a(\n    af::const_ref<vec3<double> > const& lhs,\n    af::const_ref<vec3<double> > const& rhs)\n  {\n    SCITBX_ASSERT(lhs.size() == rhs.size());\n    af::shared<vec3<double> > result((af::reserve(lhs.size())));\n    for(std::size_t i=0;i<lhs.size();i++) {\n      result.push_back(lhs[i].cross(rhs[i]));\n    }\n    return result;\n  }\n\n  af::shared<double>\n  norms_(\n    af::const_ref<vec3<double> > const& lhs)\n  {\n    af::shared<double> result((af::reserve(lhs.size())));\n    for(std::size_t i=0;i<lhs.size();i++) {\n      result.push_back(std::sqrt(lhs[i] * lhs[i]));\n    }\n    return result;\n  }\n\n  double\n  sum_sq_(\n    af::const_ref<vec3<double> > const& self)\n  {\n    double result = 0;\n    for(std::size_t i=0;i<self.size();i++) {\n      result += self[i] * self[i];\n    }\n    return result;\n  }\n\n  double\n  norm_(\n    af::const_ref<vec3<double> > const& self)\n  {\n    return std::sqrt(sum_sq_(self));\n  }\n\n  af::shared<vec3<double> >\n  each_normalize(\n    af::const_ref<vec3<double> > const& a,\n    bool raise_if_length_zero=true)\n  {\n    af::shared<vec3<double> > result(a.begin(), a.end());\n    vec3<double>* r = result.begin();\n    std::size_t n_zero = 0;\n    for(std::size_t i=0;i<a.size();i++) {\n      double length = r[i].length();\n      if (length == 0) n_zero++;\n      else r[i] *= (1 / length);\n    }\n    if (n_zero != 0 && raise_if_length_zero) {\n      throw std::runtime_error((boost::format(\n        \"flex.vec3_double.each_normalize():\"\n        \" number of vectors with length zero: %lu of %lu\")\n          % n_zero % a.size()).str());\n    }\n    return result;\n  }\n\n  double\n  min_distance_between_any_pair(\n    af::const_ref<vec3<double> > const& lhs,\n    af::const_ref<vec3<double> > const& rhs)\n  {\n    if (lhs.size() == 0) return 0;\n    if (rhs.size() == 0) return 0;\n    double min_length_sq = (lhs[0]-rhs[0]).length_sq();\n    for(std::size_t i=0;i<lhs.size();i++) {\n      for(std::size_t j=0;j<rhs.size();j++) {\n        math::update_min(min_length_sq, (lhs[i]-rhs[j]).length_sq());\n      }\n    }\n    return std::sqrt(min_length_sq);\n  }\n\n\n  boost::python::tuple\n  min_distance_between_any_pair_with_id(\n    af::const_ref<vec3<double> > const& lhs,\n    af::const_ref<vec3<double> > const& rhs)\n  {\n    if (lhs.size() == 0) return boost::python::make_tuple(0, 0, 0);\n    if (rhs.size() == 0) return boost::python::make_tuple(0, 0, 0);\n    double min_length_sq = (lhs[0]-rhs[0]).length_sq();\n    double working_length_sq = 0;\n    int best_i=0;\n    int best_j=0;\n    for(std::size_t i=0;i<lhs.size();i++) {\n      for(std::size_t j=0;j<rhs.size();j++) {\n        working_length_sq=(lhs[i]-rhs[j]).length_sq();\n        if (working_length_sq < min_length_sq) {\n          best_i=i;\n          best_j=j;\n          min_length_sq=working_length_sq;\n        }\n      }\n    }\n    return boost::python::make_tuple(std::sqrt(min_length_sq), best_i, best_j);\n  }\n\n  double\n  max_distance(\n    af::const_ref<vec3<double> > const& lhs,\n    af::const_ref<vec3<double> > const& rhs)\n  {\n    SCITBX_ASSERT(lhs.size() == rhs.size());\n    if (lhs.size() == 0) return 0;\n    double max_length_sq = 0;\n    for(std::size_t i=0;i<lhs.size();i++) {\n      math::update_max(max_length_sq, (lhs[i]-rhs[i]).length_sq());\n    }\n    return std::sqrt(max_length_sq);\n  }\n\n  double\n  rms_difference(\n    af::const_ref<vec3<double> > const& lhs,\n    af::const_ref<vec3<double> > const& rhs)\n  {\n    SCITBX_ASSERT(lhs.size() == rhs.size());\n    if (lhs.size() == 0) return 0;\n    double sum_length_sq = 0;\n    for(std::size_t i=0;i<lhs.size();i++) {\n      sum_length_sq += (lhs[i]-rhs[i]).length_sq();\n    }\n    return std::sqrt(sum_length_sq / lhs.size());\n  }\n\n  double\n  rms_length(\n    af::const_ref<vec3<double> > const& lhs)\n  {\n    if (lhs.size() == 0) return 0;\n    double sum_length_sq = 0;\n    for(std::size_t i=0;i<lhs.size();i++) {\n      sum_length_sq += lhs[i].length_sq();\n    }\n    return std::sqrt(sum_length_sq / lhs.size());\n  }\n\n} // namespace <anonymous>\n\nnamespace boost_python {\n\n  template <>\n  struct flex_default_element<vec3<double> >\n  {\n    static vec3<double>\n    get() { return vec3<double>(0,0,0); }\n  };\n\n  void wrap_flex_vec3_double()\n  {\n    using namespace boost::python;\n    using boost::python::arg;\n    typedef flex_wrapper<vec3<double> > f_w;\n    f_w::plain(\"vec3_double\")\n      .def_pickle(flex_pickle_single_buffered<vec3<double>,\n        3*pickle_size_per_element<double>::value>())\n      .def(\"__init__\", make_constructor(join))\n      .def(\"__init__\", make_constructor(from_double))\n      .def(\"part_names\", part_names)\n      .staticmethod(\"part_names\")\n      .def(\"parts\", parts)\n      .def(\"rotate_around_origin\",\n        (af::shared<vec3<double> >(*)(\n          flex<vec3<double> >::type const&,\n          vec3<double> const&,\n          double const&)) rotate_around_origin)\n      .def(\"rotate_around_origin\",\n        (af::shared<vec3<double> >(*)(\n          flex<vec3<double> >::type const&,\n          vec3<double> const&,\n          flex<double>::type const&)) rotate_around_origin)\n      .def(\"rotate_around_origin\",\n        (af::shared<vec3<double> >(*)(\n          flex<vec3<double> >::type const&,\n          flex<vec3<double> >::type const&,\n          flex<double>::type const&)) rotate_around_origin)\n      .def(\"angle\",\n        (af::shared<double>(*)(\n          af::const_ref< vec3<double> > const&,\n          vec3<double>, bool)) &angle, (\n            arg(\"other\"),\n            arg(\"deg\") = false))\n      .def(\"angle\",\n        (af::shared<double>(*)(\n          af::const_ref< vec3<double> > const&,\n          af::const_ref< vec3<double> > const&,\n          bool)) &angle, (\n            arg(\"other\"),\n            arg(\"deg\") = false))\n      .def(\"as_double\", as_double)\n      .def(\"add_selected\",\n        (object(*)(\n          object const&,\n          af::const_ref<std::size_t> const&,\n          af::const_ref<vec3<double> > const&)) add_selected_unsigned_a, (\n            arg(\"indices\"), arg(\"values\")))\n      .def(\"min\", vec3_min)\n      .def(\"max\", vec3_max)\n      .def(\"sum\", f_w::sum_a)\n      .def(\"mean\", f_w::mean_a)\n      .def(\"mean_weighted\", mean_weighted_a_a, (arg(\"weights\")))\n      .def(\"__add__\", f_w::add_a_s)\n      .def(\"__add__\", f_w::add_a_a)\n      .def(\"__iadd__\", f_w::iadd_a_s)\n      .def(\"__iadd__\", f_w::iadd_a_a)\n      .def(\"__sub__\", f_w::sub_a_s)\n      .def(\"__sub__\", f_w::sub_a_a)\n      .def(\"__isub__\", f_w::isub_a_s)\n      .def(\"__mul__\", mul_a_scalar)\n      .def(\"__rmul__\", mul_a_scalar)\n      .def(\"__mul__\", mul_a_a_scalar)\n      .def(\"__rmul__\", mul_a_a_scalar)\n      .def(\"__imul__\", imul_a_scalar, return_self<>())\n      .def(\"__div__\", div_a_as)\n      .def(\"__truediv__\", div_a_as)\n      .def(\"__mul__\", mul_a_mat3)\n      .def(\"__rmul__\", rmul_a_mat3)\n      .def(\"round\", round)\n      .def(\"iround\", iround)\n      .def(\"dot\", dot_a_s)\n      .def(\"dot\", dot_a_a)\n      .def(\"dot\", dot_a)\n      .def(\"cross\", cross_a_a)\n      .def(\"norms\", norms_)\n      .def(\"transpose_multiply\",\n        (mat3<double>(*)(\n          af::const_ref<vec3<double> > const&,\n          af::const_ref<vec3<double> > const&)) matrix::transpose_multiply)\n      .def(\"sum_sq\", sum_sq_)\n      .def(\"norm\", norm_)\n      .def(\"each_normalize\", each_normalize, (\n        arg(\"raise_if_length_zero\")=true))\n      .def(\"min_distance_between_any_pair\", min_distance_between_any_pair)\n      .def(\"min_distance_between_any_pair_with_id\",\n            min_distance_between_any_pair_with_id)\n      .def(\"max_distance\", max_distance)\n      .def(\"rms_difference\", rms_difference)\n      .def(\"rms_length\", rms_length)\n    ;\n  }\n\n}}} // namespace scitbx::af::boost_python\n", "meta": {"hexsha": "f50836341a59f4773ded56f01d31cabb81ec1c03", "size": 17679, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "scitbx/array_family/boost_python/flex_vec3_double.cpp", "max_stars_repo_name": "jbeilstenedmands/cctbx_project", "max_stars_repo_head_hexsha": "c228fb15ab10377f664c39553d866281358195aa", "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": "scitbx/array_family/boost_python/flex_vec3_double.cpp", "max_issues_repo_name": "jbeilstenedmands/cctbx_project", "max_issues_repo_head_hexsha": "c228fb15ab10377f664c39553d866281358195aa", "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": "scitbx/array_family/boost_python/flex_vec3_double.cpp", "max_forks_repo_name": "jbeilstenedmands/cctbx_project", "max_forks_repo_head_hexsha": "c228fb15ab10377f664c39553d866281358195aa", "max_forks_repo_licenses": ["BSD-3-Clause-LBNL"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.9731012658, "max_line_length": 79, "alphanum_fraction": 0.5833474744, "num_tokens": 5309, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6513548646660542, "lm_q2_score": 0.523420348936324, "lm_q1q2_score": 0.3409323905448782}}
{"text": "#include <iostream>\n#include <fstream>\n#include <iomanip>\n#include \"gausslegendre128_quadrature.h\"\n#include \"lebedev59_quadrature.h\"\n#include \"solid_real_sphericalharmonics_maxl5.h\"\n#include \"slater_poisson_maxn7.h\"\n#include \"sto_params.h\"\n\n#include \"site_type.h\"\n\n#include \"json/json.h\"\n\n#include <Eigen/Eigen>\n\n#include \"site.h\"\n#include \"computations.h\"\n#include \"timer.h\"\n\n\n\n\n//using namespace std;\nbool cmdOptionExists(char** begin, char** end, const std::string& option)\n{\n    return std::find(begin, end, option) != end;\n}\n\nint main(int argc, char * argv[])\n{\n    try\n    {\n\n        bool test = false;        test = true;\n        if(cmdOptionExists(argv, argv+argc, \"-t\")) test = true;\n\n        std::string rho_cube_file = \"rho.cube\";\n        bool cube = false;;\n        if(cmdOptionExists(argv, argv+argc, \"-c\")) cube = true;\n\n\n        //std::string input_file = \"input.json\";\n        std::string input_file = \"test/t1.json\";\n\n        std::cout << \"# ################### #\" << std::endl;\n        std::cout << \"# STO based DFT code! #\" << std::endl;\n        std::cout << \"# ################### #\" << std::endl;\n        std::cout << std::endl;\n\n        Timer general_time;\n        std::cout << \"# Loading input... \" << std::endl;\n        Json::Value root;\n\n        std::string test_reference;\n        if(test)\n        {\n\n            std::cout << \"# LOADING TEST VERSION!\" << std::endl;\n            std::istringstream is( \"{ \\\"labels\\\" : [ \\\"Li\\\" , \\\"Li\\\" ], \"\n                                   \"\\\"positions\\\" : [ [0.0 , 0.0, 0.0 ] , [1.0, 0.0, 0.0 ] ], \"\n                                   \"\\\"a1\\\" : [10.0,0.0,0.0], \\\"a2\\\" : [0.0,10.0,0.0], \\\"a3\\\" : [0.0,0.0,10.0], \"\n                                   \"\\\"scf\\\" : { \"\n                                   \"\\\"alpha\\\" : 0.5, \"\n                                   \"\\\"pulay_number\\\" : 4, \"\n                                   \"\\\"max_iteration\\\" : 50, \"\n                                   \"\\\"total_energy_tolerance\\\" :0.0000000001, \"\n                                   \"\\\"density_matrix_norm_tolerance\\\" : 0.0000000001 }, \"\n                                   \" \\\"Li\\\" : { \\\"symbol\\\" : \\\"Li\\\" , \\\"zindex\\\" : 3.0 , \\\"nelectron\\\" : 3.0 , \\\"radius\\\" : 10.0 , \"\n                                               \"\\\"mass\\\" : 3.0 , \\\"grid\\\" : { \\\"scale\\\" : 0.6, \\\"gauss\\\" : 32, \\\"lebedev\\\" : 29 }, \"\n                                               \"\\\"name\\\" : \\\"Lithium\\\", \\\"title\\\" : \\\"Lithium (SZ)\\\", \"\n                                               \"\\\"basis\\\" : [ [\\\"1S\\\" , 2.69], [\\\"2S\\\" , 0.80], [\\\"2P\\\" , 0.80] ], \"\n                                               \"\\\"qbasis\\\" : [ [\\\"1S\\\" , 5.38 , 0.488016982152593E+00], [\\\"2S\\\" , 5.41 , -0.369857854120576E+00], [\\\"2S\\\" , 3.36 , -0.154262136775740E+00], [\\\"3S\\\" , 3.08 , -0.630098272767401E-01], [\\\"3S\\\" , 2.06 , 0.526058672124576E-01], [\\\"3S\\\" , 1.38 , 0.115711696734655E-01], [\\\"3S\\\" , 0.92 , -0.236602213283877E-03], [\\\"2P\\\" , 3.49], [\\\"2P\\\" , 1.96], [\\\"2P\\\" , 1.10], [\\\"3P\\\" , 0.92], [\\\"3D\\\" , 1.60], [\\\"3D\\\" , 1.21], [\\\"3D\\\" , 0.92], [\\\"4F\\\" , 5.00], [\\\"4F\\\" , 3.50], [\\\"5G\\\" , 3.50] ] } }\");\n            is >> root;\n            test_reference = \"# ###### TEST REFERENCE #### ITERATION:   19 ###### TEST REFERENCE ##### #\\n\"\n                             \"#       homo-2         homo-1           homo           lumo         lumo+1\\n\"\n                             \"    2.00000000     2.00000000     2.00000000     0.00000000     0.00000000\\n\"\n                             \"   -3.03288837    -1.46004831    -0.14705546    -0.09326319    -0.09326319\\n\"\n                             \"#         Etot          Ecoul            Exc          dEtot          dDens\\n\"\n                             \"  -22.94421063    13.66422634    -4.58908025    -0.00027827     0.00664729\\n\"\n                             \"# ---------------------------------------------------------------------- #\\n\"\n                             \"# Self-sonsitent iteration stopped in 6.53s = 0.11m = 0.00h\\n\"\n                             \"# ###### TEST REFERENCE #### ############### ###### TEST REFERENCE ##### #\\n\";\n        }\n        else\n        {\n\n            std::ifstream config_doc(input_file, std::ifstream::binary);\n            config_doc >> root;\n\n        }\n        Computation computation;\n        computation.init_from_json(root);\n\n        std::cout << \"# Number of atoms     = \" << computation.multisites.sites.size() << std::endl;\n        std::cout << \"# Number of basis     = \" << computation.multisites.basis_ref.size() << std::endl;\n        std::cout << \"# Number of qbasis    = \" << computation.multisites.qbasis_ref.size() << std::endl;\n        std::cout << \"# Number of electrons = \" << computation.multisites.total_electron << std::endl;\n\n        for(int i = 0; i < computation.multisites.sites.size(); i++ )\n        {\n            std::cout << \"# Site \" << i+1 << \" \" << computation.multisites.sites[i].label << \" \" << std::endl;\n        }\n        std::cout << \"# Input is loaded! (\"<< general_time.elapsed() <<\"s)\"<< std::endl;\n\n        general_time.reset();\n        std::cout << \"# Initializing the system... \" << std::endl;\n        computation.compute_Hinit2();\n        std::cout << \"# Number of grid points = \" << computation.rho_grid.size() << std::endl;\n        std::cout << \"# System is initialized! (\"<< general_time.elapsed() <<\"s)\"<< std::endl;\n\n        std::cout << std::endl;\n        std::cout << \"# Starting self-consistent calculation... \"<< std::endl;\n        std::cout << computation.dDensdiff << std::endl;\n\n        general_time.reset();\n        for(size_t i = 0; i<computation.diis.max_iteration; i++)\n        {\n            computation.compute_Hscf2();\n            std::cout << \"# ########################## ITERATION: \" << std::setw(4) << i << \" ########################### #\"<< std::endl;\n\n            std::cout << '#';\n            std::cout << std::setprecision(8) << std::fixed << std::setw(13)<< \"homo-2\" << ' ';\n            std::cout << std::setprecision(8) << std::fixed << std::setw(14)<< \"homo-1\" << ' ';\n            std::cout << std::setprecision(8) << std::fixed << std::setw(14)<< \"homo\" << ' ';\n            std::cout << std::setprecision(8) << std::fixed << std::setw(14)<< \"lumo\"  << ' ';\n            std::cout << std::setprecision(8) << std::fixed << std::setw(14)<< \"lumo+1\" << ' ';\n            std::cout << std::endl;\n            for(size_t k = std::max(0,int(computation.ihomo-2)); k < std::min(computation.ilumo+2,int(computation.occ.size())); k++)\n            {\n                std::cout << std::setprecision(8) << std::fixed << std::setw(14) << computation.occ[k] << ' ';\n            }\n            std::cout << std::endl;\n            for(size_t k = std::max(0,int(computation.ihomo-2)); k < std::min(computation.ilumo+2,int(computation.occ.size())); k++)\n            {\n                std::cout << std::setprecision(8) << std::fixed << std::setw(14) << computation.eE[k] << ' ';\n            }\n            std::cout << std::endl;\n            /*\n            for(size_t k = 0; k < computation.occ.size(); k++) if (computation.occ[k==0?k:k-1]>0.0) {\n                std::cout << std::setprecision(8) << std::setw(12) << std::fixed << computation.eE(k) << ' ';\n            }\n            std::cout << std::endl;*/\n\n            std::cout << '#';\n            std::cout << std::setprecision(8) << std::fixed << std::setw(13)<< \"Etot\" << ' ';\n            std::cout << std::setprecision(8) << std::fixed << std::setw(14)<< \"Ecoul\" << ' ';\n            std::cout << std::setprecision(8) << std::fixed << std::setw(14)<< \"Exc\" << ' ';\n            std::cout << std::setprecision(8) << std::fixed << std::setw(14)<< \"dEtot\"  << ' ';\n            std::cout << std::setprecision(8) << std::fixed << std::setw(14)<< \"dDens\" << ' ';\n            std::cout << std::endl;\n\n            std::cout << std::setprecision(8) << std::fixed << std::setw(14)<< computation.Etot << ' ';\n            std::cout << std::setprecision(8) << std::fixed << std::setw(14)<< computation.Ecoul << ' ';\n            std::cout << std::setprecision(8) << std::fixed << std::setw(14)<< computation.Exc << ' ';\n            std::cout << std::setprecision(8) << std::fixed << std::setw(14)<< computation.dEtot << ' ';\n            std::cout << std::setprecision(8) << std::fixed << std::setw(14)<< computation.dDensdiff << ' ';\n            std::cout << std::endl;\n            if(std::abs(computation.dEtot)<computation.diis.total_energy_tolerance) break;\n            if(std::abs(computation.dDensdiff)<computation.diis.density_matrix_norm_tolerance) break;\n            std::cout << \"# ---------------------------------------------------------------------- #\"<< std::endl;\n\n        }\n\n        std::cout << std::setprecision(2) << std::fixed << \"# Self-sonsitent iteration stopped in \" << general_time.elapsed() << \"s = \" << general_time.elapsed()/60.0<< \"m = \" << general_time.elapsed()/3600.0 << \"h\"<< std::endl;\n\n        if (test)\n        {\n            std::cout << test_reference << std::endl;\n        }\n        if (cube)\n        {\n            general_time.reset();\n            std::cout << \"# Saving qcoeff to cube file... \" << std::endl;\n            save_cube_from_qcoeff(computation.multisites.sites,computation.qcoeff, {-2,-2,-2}, {3,2,2},0.1,rho_cube_file);\n            std::cout << \"# qcoeff is saved! (\"<< general_time.elapsed() <<\"s)\"<< std::endl;\n        }\n\n    }\n    catch (const char * e)\n    {\n        std::cerr << e << std::endl;\n    }\n    return 0;\n}\n", "meta": {"hexsha": "3f88d3cc8854f6ae7444d460ba36b1b79c945fe6", "size": 9429, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "main.cpp", "max_stars_repo_name": "dzsm/sqc-dft", "max_stars_repo_head_hexsha": "c6871e5d0533b482fc5491040b5dfc53c0df449c", "max_stars_repo_licenses": ["MIT"], "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": "dzsm/sqc-dft", "max_issues_repo_head_hexsha": "c6871e5d0533b482fc5491040b5dfc53c0df449c", "max_issues_repo_licenses": ["MIT"], "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": "dzsm/sqc-dft", "max_forks_repo_head_hexsha": "c6871e5d0533b482fc5491040b5dfc53c0df449c", "max_forks_repo_licenses": ["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.9675675676, "max_line_length": 531, "alphanum_fraction": 0.4565701559, "num_tokens": 2673, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6926419958239132, "lm_q2_score": 0.4921881357207956, "lm_q1q2_score": 0.3409101726465029}}
{"text": "/**\n * Copyright (c) 2019, Arjan van der Velde, Weng 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 * * 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#pragma once\n\n#include <Eigen/Dense>\n#include <cmath>\n\nnamespace zdock {\n\nclass TransformUtil {\nprivate:\n  typedef Eigen::Transform<double, 3, Eigen::Affine> Transform;\n  typedef Eigen::Matrix<double, 3, Eigen::Dynamic> Matrix;\n\npublic:\n  static const double PI;\n\n  // Euler angles to Z-X-Z transformation matrix\n  static inline const Transform eulerRotation(const double (&r)[3],\n                                              bool rev = false) {\n    Transform t;\n\n    using Eigen::AngleAxisd;\n    using Eigen::Vector3d;\n\n    t = AngleAxisd(r[0], Vector3d::UnitZ()) *\n        AngleAxisd(r[1], Vector3d::UnitX()) *\n        AngleAxisd(r[2], Vector3d::UnitZ());\n    return (rev ? t.inverse() : t);\n  }\n\n  // Adjust grid coordinates to fall inside box of size 'boxsize',\n  // NOTE: returns Vector3d (double).\n  static inline const Eigen::Vector3d boxedGridCoord(const int (&v)[3],\n                                                     const int boxsize) {\n    Eigen::Vector3d d;\n    d << (v[0] >= boxsize / 2 ? v[0] - boxsize : v[0]),\n        (v[1] >= boxsize / 2 ? v[1] - boxsize : v[1]),\n        (v[2] >= boxsize / 2 ? v[2] - boxsize : v[2]);\n    return d;\n  }\n};\n\n} // namespace zdock\n", "meta": {"hexsha": "80cda1329a8e4e0c527817eb0dc90a9876f073f4", "size": 2569, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/zdock/TransformUtil.hpp", "max_stars_repo_name": "weng-lab/libzdock", "max_stars_repo_head_hexsha": "a634d5b179e7064ac26f6a8a2550e14901732ebe", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2019-03-27T18:12:16.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-27T11:36:24.000Z", "max_issues_repo_path": "src/zdock/TransformUtil.hpp", "max_issues_repo_name": "hardhary/libzdock", "max_issues_repo_head_hexsha": "a634d5b179e7064ac26f6a8a2550e14901732ebe", "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/zdock/TransformUtil.hpp", "max_forks_repo_name": "hardhary/libzdock", "max_forks_repo_head_hexsha": "a634d5b179e7064ac26f6a8a2550e14901732ebe", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-01-15T00:21:34.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-15T00:21:34.000Z", "avg_line_length": 37.231884058, "max_line_length": 81, "alphanum_fraction": 0.6780848579, "num_tokens": 608, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6926419831347361, "lm_q2_score": 0.4921881357207956, "lm_q1q2_score": 0.34091016640104055}}
{"text": "/* Copyright 2022 Zuru Tech HK Limited.\n *\n * Licensed under the Apache License, Version 2.0(the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n * \n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n#include <cstring>\n#include <stdexcept>\n\n#include <Eigen/Dense>\n\n#include <petscksp.h>\n\n#include <solvers/PetscSolver.hpp>\n#include <solvers/SparseSystem.hpp>\n\nnamespace solvers {\n\nPetscSolver::PetscSolver(const PetscMethod method,\n                         const PetscPreconditioner preconditioner)\n{\n    KSPCreate(PETSC_COMM_SELF, &_ksp);\n    KSPType ksp_type;\n    PCType pc_type = \"\";\n    switch (method) {\n        case PetscMethod::CG:\n            ksp_type = KSPCG;\n            break;\n        case PetscMethod::FlexibleCG:\n            ksp_type = KSPFCG;\n            break;\n        case PetscMethod::GMRES:\n            ksp_type = KSPGMRES;\n            break;\n        case PetscMethod::FlexibleGMRES:\n            ksp_type = KSPFGMRES;\n            break;\n        case PetscMethod::QMR:\n            ksp_type = KSPTCQMR;\n            break;\n        case PetscMethod::CR:\n            ksp_type = KSPCR;\n            break;\n        case PetscMethod::MinRes:\n            ksp_type = KSPMINRES;\n            break;\n        case PetscMethod::SymmLQ:\n            ksp_type = KSPSYMMLQ;\n            break;\n        case PetscMethod::Cholesky:\n            ksp_type = KSPPREONLY;\n            pc_type = PCCHOLESKY;\n            break;\n        case PetscMethod::LU:\n            ksp_type = KSPPREONLY;\n            pc_type = PCLU;\n            break;\n        case PetscMethod::QR:\n            ksp_type = KSPPREONLY;\n            pc_type = PCQR;\n            break;\n        default:\n            throw std::logic_error(\"Invalid solving method\");\n            break;\n    }\n    KSPSetType(_ksp, ksp_type);\n    PC pc;\n    KSPGetPC(_ksp, &pc);\n    if (strlen(pc_type) != 0) {\n        if (preconditioner != PetscPreconditioner::None) {\n            throw std::logic_error(\n                \"The preconditioner cannot be used with direct methods\");\n        }\n    }\n    else {\n        switch (preconditioner) {\n            case PetscPreconditioner::None:\n                pc_type = PCNONE;\n                break;\n            case PetscPreconditioner::Jacobi:\n                pc_type = PCJACOBI;\n                break;\n            case PetscPreconditioner::SOR:\n                pc_type = PCSOR;\n                break;\n            case PetscPreconditioner::Eisenstat:\n                pc_type = PCEISENSTAT;\n                break;\n            case PetscPreconditioner::ILU:\n                pc_type = PCILU;\n                break;\n            case PetscPreconditioner::ICC:\n                pc_type = PCICC;\n                break;\n            default:\n                throw std::logic_error(\"Invalid preconditioner\");\n                break;\n        }\n    }\n    PCSetType(pc, pc_type);\n    KSPSetFromOptions(_ksp);\n}\n\nEigen::VectorXd PetscSolver::solve(const SparseSystem& system,\n                                   double& duration) const\n{\n    auto [A, b] = system.toPetscCSR();\n    KSPReset(_ksp);\n    KSPSetOperators(_ksp, A, A);\n    double start;\n    double end;\n    PetscTime(&start);\n    KSPSolve(_ksp, b, b);\n    PetscTime(&end);\n    double* result_data;\n    VecGetArray(b, &result_data);\n    Eigen::VectorXd result = Eigen::Map<Eigen::VectorXd>(\n        result_data, static_cast<int64_t>(system.dim()));\n    duration = end - start;\n    return result;\n}\n\n}    // namespace solvers", "meta": {"hexsha": "0a7f2b1b429ab5dcd25013c864d59a47d90353a2", "size": 3842, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "solvers/src/solvers/PetscSolver.cpp", "max_stars_repo_name": "zurutech/stand", "max_stars_repo_head_hexsha": "a341f691d991072a61d07aac6fa7e634e2d112d3", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 9.0, "max_stars_repo_stars_event_min_datetime": "2022-01-17T07:30:49.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-20T17:27:52.000Z", "max_issues_repo_path": "solvers/src/solvers/PetscSolver.cpp", "max_issues_repo_name": "zurutech/stand", "max_issues_repo_head_hexsha": "a341f691d991072a61d07aac6fa7e634e2d112d3", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "solvers/src/solvers/PetscSolver.cpp", "max_forks_repo_name": "zurutech/stand", "max_forks_repo_head_hexsha": "a341f691d991072a61d07aac6fa7e634e2d112d3", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.1060606061, "max_line_length": 75, "alphanum_fraction": 0.5671525247, "num_tokens": 912, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6926419831347361, "lm_q2_score": 0.49218813572079556, "lm_q1q2_score": 0.3409101664010405}}
{"text": "#include \"hoCuNDArray_utils.h\"\n#include \"radial_utilities.h\"\n#include \"cuNDArray_fileio.h\"\n#include \"cuNDArray_math.h\"\n#include \"imageOperator.h\"\n#include \"identityOperator.h\"\n#include \"hoPartialDerivativeOperator.h\"\n#include \"hoCuConebeamProjectionOperator.h\"\n#include \"cuConvolutionOperator.h\"\n#include \"hoCuNDArray_blas.h\"\n#include \"hoCuNDArray_elemwise.h\"\n#include \"hoCuNDArray_blas.h\"\n#include \"cgSolver.h\"\n#include \"CBCT_acquisition.h\"\n#include \"complext.h\"\n#include \"encodingOperatorContainer.h\"\n#include \"vector_td_io.h\"\n#include \"hoPartialDerivativeOperator.h\"\n#include \"hoCuGPBBSolver.h\"\n#include \"hoCuTvOperator.h\"\n#include \"hoCuTvPicsOperator.h\"\n#include \"hoCuNCGSolver.h\"\n#include \"hoCuCgDescentSolver.h\"\n#include \"hoNDArray_utils.h\"\n#include \"hoCuPartialDerivativeOperator.h\"\n#include \"cuTvOperator.h\"\n#include \"cuTv1dOperator.h\"\n#include \"cuTvPicsOperator.h\"\n#include \"CBSubsetOperator.h\"\n#include \"osSPSSolver.h\"\n#include \"osMOMSolver.h\"\n#include \"osMOMSolverD.h\"\n#include \"osMOMSolverD2.h\"\n#include \"hoCuNCGSolver.h\"\n#include \"osMOMSolverD3.h\"\n#include \"osMOMSolverL1.h\"\n#include \"osMOMSolverF.h\"\n#include \"osAHZCSolver.h\"\n#include \"hoCuOSNESTSolver.h\"\n#include \"ADMMSolver.h\"\n#include <iostream>\n#include <algorithm>\n#include <sstream>\n#include <math_constants.h>\n#include <boost/program_options.hpp>\n#include <boost/make_shared.hpp>\n#include <GPUTimer.h>\n#include <operators/cuGaussianFilterOperator.h>\n#include <multiplicationOperatorContainer.h>\n#include \"cuSolverUtils.h\"\n#include \"osPDsolver.h\"\n#include \"osLALMSolver.h\"\n#include \"osLALMSolver2.h\"\n#include \"cuATrousOperator.h\"\n#include \"hdf5_utils.h\"\n#include \"cuEdgeATrousOperator.h\"\n#include \"cuDCTOperator.h\"\n#include \"cuDCTDerivativeOperator.h\"\n#include \"dicomWriter.h\"\n#include \"conebeam_projection.h\"\n#include \"weightingOperator.h\"\n#include \"hoNDArray_math.h\"\n#include \"cuNCGSolver.h\"\n#include \"CT_acquisition.h\"\nusing namespace std;\nusing namespace Gadgetron;\n\nnamespace po = boost::program_options;\n\nboost::shared_ptr<hoCuNDArray<float>> downsample_projections(hoCuNDArray<float>* projections, unsigned int num_downsamples )\n{\n\n\tif (num_downsamples == 0) return boost::make_shared<hoCuNDArray<float>>(*projections);\n\n\tauto tmp = Gadgetron::downsample<float,2>(projections);\n\n\tfor (int k = 1; k < num_downsamples; k++)\n\t\ttmp = Gadgetron::downsample<float,2>(tmp.get());\n\n\treturn boost::make_shared<hoCuNDArray<float>>(*tmp);\n}\n\n\n\n\nint main(int argc, char** argv)\n{\n\n\tstring acquisition_filename;\n\tstring outputFile;\n\tuintd3 imageSize;\n\tfloatd3 voxelSize;\n\tint device;\n\tunsigned int downsamples;\n\tunsigned int iterations;\n\tunsigned int subsets;\n\tfloat rho,tau;\n\tfloat tv_weight,pics_weight, wavelet_weight,huber,sigma,dct_weight;\n\tfloat tv_4d,atv_4d;\n    bool use_non_negativity;\n\tint reg_iter;\n\n\tpo::options_description desc(\"Allowed options\");\n\n\tdesc.add_options()\n    \t\t\t\t(\"help\", \"produce help message\")\n    \t\t\t\t(\"acquisition,a\", po::value<string>(&acquisition_filename)->default_value(\"acquisition.hdf5\"), \"Acquisition data\")\n    \t\t\t\t(\"samples,n\",po::value<unsigned int>(),\"Number of samples per ray\")\n    \t\t\t\t(\"output,f\", po::value<string>(&outputFile)->default_value(\"reconstruction.hdf5\"), \"Output filename\")\n    \t\t\t\t(\"size,s\",po::value<uintd3>(&imageSize)->default_value(uintd3(512,512,1)),\"Image size in pixels\")\n    \t\t\t\t(\"binning,b\",po::value<string>(),\"Binning file for 4d reconstruction\")\n    \t\t\t\t(\"SAG\",\"Use exact SAG correction if present\")\n    \t\t\t\t(\"voxelSize,v\",po::value<floatd3>(&voxelSize)->default_value(floatd3(0.488f,0.488f,1.0f)),\"Voxel size in mm\")\n    \t\t\t\t(\"dimensions,d\",po::value<floatd3>(),\"Image dimensions in mm. Overwrites voxelSize.\")\n    \t\t\t\t(\"iterations,i\",po::value<unsigned int>(&iterations)->default_value(10),\"Number of iterations\")\n    \t\t\t\t(\"device\",po::value<int>(&device)->default_value(0),\"Number of the device to use (0 indexed)\")\n    \t\t\t\t(\"downsample,D\",po::value<unsigned int>(&downsamples)->default_value(0),\"Downsample projections this factor\")\n    \t\t\t\t(\"subsets,u\",po::value<unsigned int>(&subsets)->default_value(10),\"Number of subsets to use\")\n    \t\t\t\t(\"TV\",po::value<float>(&tv_weight)->default_value(0),\"Total variation weight in spatial dimensions\")\n\t\t\t\t\t\t\t(\"TV4D\",po::value<float>(&tv_4d)->default_value(0),\"Total variation weight in temporal dimensions\")\n\t\t\t\t\t\t\t(\"ATV4D\",po::value<float>(&atv_4d)->default_value(0),\"Advanced Total variation weight in temporal dimensions\")\n    \t\t\t\t(\"PICS\",po::value<float>(&pics_weight)->default_value(0),\"PICS weight\")\n    \t\t\t\t(\"Wavelet,W\",po::value<float>(&wavelet_weight)->default_value(0),\"Weight of the wavelet operator\")\n    \t\t\t\t(\"Huber\",po::value<float>(&huber)->default_value(0),\"Huber weight\")\n\n\n\n\n    \t\t\t\t(\"3D\",\"Only use binning for selecting valid projections\")\n\t\t\t\t\t\t\t(\"tau\",po::value<float>(&tau)->default_value(1e-5),\"Tau value for solver\")\n\t\t\t\t\t\t\t(\"reg_iter\",po::value<int>(&reg_iter)->default_value(2))\n    \t\t\t\t;\n\n\tpo::variables_map vm;\n\tpo::store(po::parse_command_line(argc, argv, desc), vm);\n\tpo::notify(vm);\n\n\tif (vm.count(\"help\")) {\n\t\tcout << desc << \"\\n\";\n\t\treturn 1;\n\t}\n\n\tstd::stringstream command_line_string;\n\tstd::cout << \"Command line options:\" << std::endl;\n\tfor (po::variables_map::iterator it = vm.begin(); it != vm.end(); ++it){\n\t\tboost::any a = it->second.value();\n\t\tcommand_line_string << it->first << \": \";\n\t\tif (a.type() == typeid(std::string)) command_line_string << it->second.as<std::string>();\n\t\telse if (a.type() == typeid(int)) command_line_string << it->second.as<int>();\n\t\telse if (a.type() == typeid(unsigned int)) command_line_string << it->second.as<unsigned int>();\n\t\telse if (a.type() == typeid(float)) command_line_string << it->second.as<float>();\n\t\telse if (a.type() == typeid(vector_td<float,3>)) command_line_string << it->second.as<vector_td<float,3> >();\n\t\telse if (a.type() == typeid(vector_td<int,3>)) command_line_string << it->second.as<vector_td<int,3> >();\n\t\telse if (a.type() == typeid(vector_td<unsigned int,3>)) command_line_string << it->second.as<vector_td<unsigned int,3> >();\n        else if (a.type() == typeid(bool)) command_line_string << it->second.as<bool>();\n\t\telse command_line_string << \"Unknown type\" << std::endl;\n\t\tcommand_line_string << std::endl;\n\t}\n\tstd::cout << command_line_string.str();\n\n\tcudaSetDevice(device);\n\tcudaDeviceReset();\n\n\t//Really weird stuff. Needed to initialize the device?? Should find real bug.\n\tcudaDeviceManager::Instance()->lockHandle();\n\tcudaDeviceManager::Instance()->unlockHandle();\n\n\tboost::shared_ptr<CBCT_acquisition> ps(new CBCT_acquisition());\n\tps->load(acquisition_filename);\n\tps->get_geometry()->print(std::cout);\n\n\n\tfloat SDD = ps->get_geometry()->get_SDD();\n\tfloat SAD = ps->get_geometry()->get_SAD();\n\n\tboost::shared_ptr<CBCT_binning> binning(new CBCT_binning());\n\tif (vm.count(\"binning\")){\n\t\tstd::cout << \"Loading binning data\" << std::endl;\n\t\tbinning->load(vm[\"binning\"].as<string>());\n\t\tif (vm.count(\"3D\"))\n\t\t\tbinning = binning->get_3d_binning();\n\t} else binning->set_as_default_3d_bin(ps->get_projections()->get_size(2));\n\tbinning->print(std::cout);\n\n\tfloatd3 imageDimensions;\n\tif (vm.count(\"dimensions\")){\n\t\timageDimensions = vm[\"dimensions\"].as<floatd3>();\n\t\tvoxelSize = imageDimensions/imageSize;\n\t}\n\telse imageDimensions = voxelSize*imageSize;\n\n\tfloat lengthOfRay_in_mm = norm(imageDimensions);\n\tunsigned int numSamplesPerPixel = 3;\n\tfloat minSpacing = min(voxelSize)/numSamplesPerPixel;\n\n\tunsigned int numSamplesPerRay;\n\tif (vm.count(\"samples\")) numSamplesPerRay = vm[\"samples\"].as<unsigned int>();\n\telse numSamplesPerRay = ceil( lengthOfRay_in_mm / minSpacing );\n\n\tfloat step_size_in_mm = lengthOfRay_in_mm / numSamplesPerRay;\n\tsize_t numProjs = ps->get_projections()->get_size(2);\n\tsize_t needed_bytes = 2 * prod(imageSize) * sizeof(float);\n\tstd::vector<size_t> is_dims = to_std_vector((uint64d3)imageSize);\n\n\tstd::cout << \"IS dimensions \" << is_dims[0] << \" \" << is_dims[1] << \" \" << is_dims[2] << std::endl;\n\tstd::cout << \"Image size \" << imageDimensions << std::endl;\n\n\tis_dims.push_back(binning->get_number_of_bins());\n\n\t//scatter_correct(binning,ps,ps->get_projections().get(),is_dims,imageDimensions);\n\n\tps->downsample(downsamples);\n\n\n\t//osLALMSolver<cuNDArray<float>> solver;\n\thoCuOSNESTSolver<float> solver;\n\t//osMOMSolverL1<cuNDArray<float>> solver;\n\t//osAHZCSolver<cuNDArray<float>> solver;\n\t//osMOMSolverF<cuNDArray<float>> solver;\n\t//ADMMSolver<cuNDArray<float>> solver;\n\tsolver.set_dump(false);\n\n\n\n\n\tsolver.set_max_iterations(iterations);\n\tsolver.set_output_mode(osSPSSolver<cuNDArray<float>>::OUTPUT_VERBOSE);\n\tsolver.set_tau(tau);\n\tsolver.set_non_negativity_constraint(use_non_negativity);\n\tsolver.set_huber(huber);\n\tsolver.set_reg_steps(reg_iter);\n\t//solver.set_rho(rho);\n\tsolver.set_beta(1e-6);\n  if (tv_weight > 0) {\n\n\t  auto Dx = boost::make_shared<cuPartialDerivativeOperator<float, 4>>(0);\n\t  Dx->set_weight(tv_weight);\n\t  Dx->set_domain_dimensions(&is_dims);\n\t  Dx->set_codomain_dimensions(&is_dims);\n\n\t  auto Dy = boost::make_shared<cuPartialDerivativeOperator<float, 4>>(1);\n\t  Dy->set_weight(tv_weight);\n\t  Dy->set_domain_dimensions(&is_dims);\n\t  Dy->set_codomain_dimensions(&is_dims);\n\n\n\t  auto Dz = boost::make_shared<cuPartialDerivativeOperator<float, 4>>(2);\n\t  Dz->set_weight(tv_weight);\n\t  Dz->set_domain_dimensions(&is_dims);\n\t  Dz->set_codomain_dimensions(&is_dims);\n\n\t  solver.add_regularization_group({Dx, Dy, Dz});\n\n\t  if (tv_4d > 0) {\n\t\t  auto Dt = boost::make_shared<cuPartialDerivativeOperator<float, 4>>(3);\n\t\t  Dt->set_weight(tv_4d);\n\t\t  Dt->set_domain_dimensions(&is_dims);\n\t\t  Dt->set_codomain_dimensions(&is_dims);\n\t\t  solver.add_regularization_operator(Dt);\n\t  }\n  }\n\n\n      if (atv_4d > 0) {\n          auto Dt = boost::make_shared<cuPartialDerivativeOperator<float, 4>>(3);\n          Dt->set_domain_dimensions(&is_dims);\n          Dt->set_codomain_dimensions(&is_dims);\n\n\n\n          auto Dx = boost::make_shared<cuPartialDerivativeOperator<float,4>>(0);\n          Dx->set_domain_dimensions(&is_dims);\n          Dx->set_codomain_dimensions(&is_dims);\n\n          auto Dy = boost::make_shared<cuPartialDerivativeOperator<float, 4>>(1);\n          Dy->set_domain_dimensions(&is_dims);\n          Dy->set_codomain_dimensions(&is_dims);\n\n\n          auto Dz = boost::make_shared<cuPartialDerivativeOperator<float, 4>>(2);\n          Dz->set_domain_dimensions(&is_dims);\n          Dz->set_codomain_dimensions(&is_dims);\n\n\n\n          auto Dx2 = boost::make_shared<multiplicationOperatorContainer<cuNDArray<float>>>();\n          Dx2->add_operator(Dx);\n          Dx2->add_operator(Dt);\n          Dx2->set_weight(atv_4d);\n\n          auto Dy2 = boost::make_shared<multiplicationOperatorContainer<cuNDArray<float>>>();\n          Dy2->add_operator(Dy);\n          Dy2->add_operator(Dt);\n          Dy->set_weight(atv_4d);\n\n          auto Dz2 = boost::make_shared<multiplicationOperatorContainer<cuNDArray<float>>>();\n          Dz2->add_operator(Dz);\n          Dz2->add_operator(Dt);\n          Dz2->set_weight(atv_4d);\n\n          solver.add_regularization_group({Dx2, Dy2, Dz2});\n\n\n      }\n\n\n\n\tauto E = boost::make_shared<CBSubsetOperator<cuNDArray> >(subsets);\n\n\n\t//E->setup(ps,binning,imageDimensions);\n\tE->setup(ps,binning,imageDimensions);\n\tE->set_domain_dimensions(&is_dims);\n\tE->set_codomain_dimensions(ps->get_projections()->get_dimensions().get());\n\n\n\tsolver.set_encoding_operator(E);\n\n\n\n\tauto projections = ps->get_projections();\n\tstd::cout << \"Projection norm:\" << nrm2(projections.get()) << std::endl;\n\t//E->set_use_offset_correction(false);\n\n\t//boost::shared_ptr<cuNDArray<bool>> mask;\n\t//mask = E->calculate_mask(projections,0.03f);\n\t//ps->set_projections(boost::shared_ptr<hoCuNDArray<float>>()); //Clear projections from host memory.\n\n/*\n\t{\n\t\tcuNDArray<float> cu_proj(*projections);\n\t\tE->offset_correct(&cu_proj);\n\t\t*projections = cu_proj;\n\t}\n\n\t{\n\t\tcuNDArray<float> cu_air(*ps->get_airscan());\n\t\tE->offset_correct(&cu_air);\n\t\t*ps->get_airscan() = cu_air;\n\t}\n*/\n\n\t//E->set_mask(mask);\n\tstd::cout << \"Projection norm:\" << nrm2(projections.get()) << std::endl;\n\n\n\n\t//solver.set_damping(1e-6);\n\n\t/*\n    boost::shared_ptr<hoCuNDArray<float> > prior;\n\n  if (vm.count(\"use_prior\")) {\n  \tprior = calculate_prior(binning,ps,projections,is_dims,imageDimensions);\n  \tsolver.set_x0(prior);\n  }\n\t */\n\tauto airscan = downsample_projections(ps->get_airscan().get(),downsamples);\n\n\tboost::shared_ptr<hoCuNDArray<float>> result;\n\t{\n\t\tGPUTimer tim(\"Solver\");\n\t\tresult = solver.solve(projections.get(),airscan.get());\n\t}\n//\tglobal_timer.reset();\n\tstd::cout << \"Penguin\" << nrm2(result.get()) << std::endl;\n\n\tstd::cout << \"Result sum \" << asum(result.get()) << std::endl;\n\n\t//apply_mask(result.get(),mask.get());\n\n\tstd::cout << \"Result sum \" << asum(result.get()) << std::endl;\n\t//saveNDArray2HDF5(result.get(),outputFile,imageDimensions,vector_td<float,3>(0),command_line_string.str(),iterations);\n\n\n\n\n\tsaveNDArray2HDF5(result.get(),outputFile,imageDimensions,floatd3(0,0,0),command_line_string.str(),iterations);\n//\twrite_nd_array(result.get(),\"reconstruction.real\");\n\twrite_dicom(result.get(),command_line_string.str(),imageDimensions);\n\n\n\n}\n", "meta": {"hexsha": "0abf24a280aa6c7f053d3b77607e4a377e2019f5", "size": 13063, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "xray/cuCBOSStat_reconstruct.cpp", "max_stars_repo_name": "ahsanjav/gt-tomography", "max_stars_repo_head_hexsha": "1f53d72672ccda417bc8966d8497af6d786e8935", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2017-06-26T13:41:55.000Z", "max_stars_repo_stars_event_max_datetime": "2019-06-10T11:06:27.000Z", "max_issues_repo_path": "xray/cuCBOSStat_reconstruct.cpp", "max_issues_repo_name": "ahsanjav/gt-tomography", "max_issues_repo_head_hexsha": "1f53d72672ccda417bc8966d8497af6d786e8935", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "xray/cuCBOSStat_reconstruct.cpp", "max_forks_repo_name": "ahsanjav/gt-tomography", "max_forks_repo_head_hexsha": "1f53d72672ccda417bc8966d8497af6d786e8935", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-09-27T14:37:29.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-27T14:37:29.000Z", "avg_line_length": 33.9298701299, "max_line_length": 125, "alphanum_fraction": 0.7078006583, "num_tokens": 3538, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7718434978390747, "lm_q2_score": 0.44167300566462553, "lm_q1q2_score": 0.34090243759328204}}
{"text": "/*    Copyright (c) 2010-2019, Delft University of Technology\n*    All rigths reserved\n*\n*    This file is part of the Tudat. Redistribution and use in source and\n*    binary forms, with or without modification, are permitted exclusively\n*    under the terms of the Modified BSD license. You should have received\n*    a copy of the license with this file. If not, please or visit:\n*    http://tudat.tudelft.nl/LICENSE.\n*/\n\n#include <iostream>\n#include <fstream>\n#include <functional>\n\n#include <boost/filesystem.hpp>\n#include \"Problems/applicationOutput.h\"\n#include \"Problems/getAlgorithm.h\"\n#include \"Problems/saveOptimizationResults.h\"\n\n#include \"tudat/simulation/simulation.h\"\n#include \"tudat/astro/LowThrustTrajectories/lowThrustOptimisationSetup.h\"\n#include \"tudat/astro/LowThrustTrajectories/ShapeBasedMethods/hodographicShaping.h\"\n#include \"tudat/astro/LowThrustTrajectories/ShapeBasedMethods/sphericalShaping.h\"\n#include \"tudat/astro/LowThrustTrajectories/ShapeBasedMethods/createBaseFunctionHodographicShaping.h\"\n#include \"tudat/astro/LowThrustTrajectories/lowThrustLegSettings.h\"\n#include \"tudat/astro/LowThrustTrajectories/lowThrustLeg.h\"\n#include \"tudat/astro/ephemerides/approximatePlanetPositions.h\"\n#include \"tudat/astro/LowThrustTrajectories/ShapeBasedMethods/hodographicShapingOptimisationSetup.h\"\n#include \"tudat/astro/LowThrustTrajectories/ShapeBasedMethods/getRecommendedBaseFunctionsHodographicShaping.h\"\n#include \"tudat/simulation/optimisationSettings.h\"\n\nusing namespace tudat;\nusing namespace tudat::shape_based_methods;\nusing namespace tudat::numerical_integrators;\nusing namespace tudat::simulation_setup;\n\nstd::vector< std::vector< std::shared_ptr< BaseFunctionHodographicShaping > > > getShapingBasisFunctions(\n        const double timeOfFlight, const int numberOfRevolutions )\n{\n    Eigen::VectorXd dummyVector;\n\n    // Get recommended base functions for the radial velocity composite function.\n    std::vector< std::shared_ptr< BaseFunctionHodographicShaping > > radialVelocityFunctionComponents;\n    getRecommendedRadialVelocityBaseFunctions(\n                radialVelocityFunctionComponents, dummyVector, timeOfFlight );\n\n    // Get recommended base functions for the normal velocity composite function.\n    std::vector< std::shared_ptr< BaseFunctionHodographicShaping > > normalVelocityFunctionComponents;\n    getRecommendedNormalAxialBaseFunctions(\n                normalVelocityFunctionComponents, dummyVector, timeOfFlight );\n\n    // Get recommended base functions for the axial velocity composite function.\n    std::vector< std::shared_ptr< BaseFunctionHodographicShaping > > axialVelocityFunctionComponents;\n    getRecommendedAxialVelocityBaseFunctions(\n                axialVelocityFunctionComponents, dummyVector, timeOfFlight, numberOfRevolutions );\n\n    {\n        double frequency = 2.0 * mathematical_constants::PI / timeOfFlight;\n        double scaleFactor = 1.0 / timeOfFlight;\n\n        std::shared_ptr< BaseFunctionHodographicShapingSettings > fourthRadialVelocityBaseFunctionSettings =\n                std::make_shared< PowerTimesTrigonometricFunctionHodographicShapingSettings >(\n                    1.0, 0.5 * frequency, scaleFactor );\n        std::shared_ptr< BaseFunctionHodographicShapingSettings > fifthRadialVelocityBaseFunctionSettings =\n                std::make_shared< PowerTimesTrigonometricFunctionHodographicShapingSettings >(\n                    1.0, 0.5 * frequency, scaleFactor );\n\n        // Add two additional base functions\n        radialVelocityFunctionComponents.push_back(\n                    createBaseFunctionHodographicShaping( scaledPowerSine, fourthRadialVelocityBaseFunctionSettings ) );\n        radialVelocityFunctionComponents.push_back(\n                    createBaseFunctionHodographicShaping( scaledPowerCosine, fifthRadialVelocityBaseFunctionSettings ) );\n\n    }\n\n    {\n        double scaleFactor = 1.0 / timeOfFlight;\n\n        // Create base function settings for the components of the axial velocity composite function.\n        std::shared_ptr< shape_based_methods::BaseFunctionHodographicShapingSettings > firstAxialVelocityBaseFunctionSettings =\n                std::make_shared< shape_based_methods::PowerFunctionHodographicShapingSettings >( 3.0, scaleFactor );\n        std::shared_ptr< shape_based_methods::BaseFunctionHodographicShapingSettings > secondAxialVelocityBaseFunctionSettings =\n                std::make_shared< shape_based_methods::PowerFunctionHodographicShapingSettings >( 4.0, scaleFactor );\n        std::shared_ptr< shape_based_methods::BaseFunctionHodographicShapingSettings > thirdAxialVelocityBaseFunctionSettings =\n                std::make_shared< shape_based_methods::PowerFunctionHodographicShapingSettings >( 5.0, scaleFactor );\n\n\n        // Set components for the axial velocity function.\n        axialVelocityFunctionComponents.push_back(\n                    createBaseFunctionHodographicShaping( shape_based_methods::scaledPower, firstAxialVelocityBaseFunctionSettings ) );\n        axialVelocityFunctionComponents.push_back(\n                    createBaseFunctionHodographicShaping( shape_based_methods::scaledPower, secondAxialVelocityBaseFunctionSettings ) );\n        axialVelocityFunctionComponents.push_back(\n                    createBaseFunctionHodographicShaping( shape_based_methods::scaledPower, thirdAxialVelocityBaseFunctionSettings ) );\n\n    }\n\n    return { radialVelocityFunctionComponents, normalVelocityFunctionComponents, axialVelocityFunctionComponents };\n}\n\n//! Execute  main\nint main( )\n{\n    //Set seed for reproducible results\n    pagmo::random_device::set_seed( 123 );\n\n    tudat::spice_interface::loadStandardSpiceKernels( );\n\n    // Ephemeris functions of bodies.\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\n    std::function< Eigen::Vector6d( const double ) > departureStateFunction = [ = ]( const double currentTime )\n    { return pointerToDepartureBodyEphemeris->getCartesianState( currentTime ); };\n    std::function< Eigen::Vector6d( const double ) > arrivalStateFunction = [ = ]( const double currentTime )\n    { return pointerToArrivalBodyEphemeris->getCartesianState( currentTime ); };\n\n\n    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n    //////////////////////        GRID SEARCH FOR HODOGRAPHIC SHAPING LOWEST-ORDER SOLUTION            /////////////////////////\n    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n\n    // Define bounds for departure date and time-of-flight.\n    std::pair< double, double > departureTimeBounds =\n            std::make_pair( 7304.5 * physical_constants::JULIAN_DAY, 13225.5 * physical_constants::JULIAN_DAY  );\n    std::pair< double, double > timeOfFlightBounds =\n            std::make_pair( 300.0 * physical_constants::JULIAN_DAY, 2000.0 * physical_constants::JULIAN_DAY );\n\n    // Define lower and upper bounds for the radial velocity free coefficients.\n    std::vector< std::vector< double > > bounds( 2, std::vector< double >( 7, 0.0 ) );\n    bounds[ 0 ][ 0 ] =  departureTimeBounds.first;\n    bounds[ 1 ][ 0 ] = departureTimeBounds.second;\n    bounds[ 0 ][ 1 ] = timeOfFlightBounds.first;\n    bounds[ 1 ][ 1 ] = timeOfFlightBounds.second;\n    bounds[ 0 ][ 2 ] = - 5000.0;\n    bounds[ 1 ][ 2 ] = 5000.0;\n    bounds[ 0 ][ 3 ] = -5000;\n    bounds[ 1 ][ 3 ] = 5000.0;\n    bounds[ 0 ][ 4 ] = - 5000.0;\n    bounds[ 1 ][ 4 ] = 5000.0;\n    bounds[ 0 ][ 5 ] = -5000;\n    bounds[ 1 ][ 5 ] = 5000.0;\n    bounds[ 0 ][ 6 ] = -5000;\n    bounds[ 1 ][ 6 ] = 5000.0;\n\n    for( int useMultiObjective = 0; useMultiObjective < 2; useMultiObjective++ )\n    {\n        for( int revolutions = 2; revolutions < 3; revolutions++ )\n        {\n            // Create object to compute the problem fitness\n            problem prob{ HodographicShapingOptimisationProblem(\n                            departureStateFunction, arrivalStateFunction, spice_interface::getBodyGravitationalParameter( \"Sun\" ),\n                            revolutions, std::bind( &getShapingBasisFunctions, std::placeholders::_1, revolutions ), bounds,\n                            useMultiObjective, 2000.0 ) };\n\n            //sade, gaco, sga, de\n            algorithm algo;\n            if( !useMultiObjective )\n            {\n                algo = algorithm{ simulated_annealing( ) };\n            }\n            else\n            {\n                algo = algorithm{ nsga2( ) };\n            }\n\n            // Create an island with 1000 individuals\n            island isl{algo, prob, 2000 };\n\n            // Evolve for 512 generations\n            for( int i = 0 ; i < 101; i++ )\n            {\n                isl.evolve( );\n                while( isl.status( ) != pagmo::evolve_status::idle &&\n                       isl.status( ) != pagmo::evolve_status::idle_error )\n                {\n                    isl.wait( );\n                }\n\n                if( i % 25 == 0 )\n                {\n                    if( !useMultiObjective )\n                    {\n                        std::cout<<\"Iteration: \"<<\" \"<<i<<\"; Best Delta V: \"<<isl.get_population( ).champion_f( ).at( 0 )<<std::endl;\n\n                        printPopulationToFile( isl.get_population( ).get_x( ), \"hodograph_single_objective_\" + std::to_string( i / 25 ), false );\n                        printPopulationToFile( isl.get_population( ).get_f( ), \"hodograph_single_objective_\" + std::to_string( i / 25 ), true );\n                    }\n                    else\n                    {\n                        std::cout<<\"Iteration: \"<<\" \"<<i<<std::endl;\n\n                        printPopulationToFile( isl.get_population( ).get_x( ), \"hodograph_multi_objective_\" + std::to_string( i / 25 ), false );\n                        printPopulationToFile( isl.get_population( ).get_f( ), \"hodograph_multi_objective_\" + std::to_string( i / 25 ), true );\n                    }\n                }\n\n            }\n\n\n            if( !useMultiObjective )\n            {\n                std::cout<<\"Final best Delta V: \"<<isl.get_population( ).champion_f( ).at( 0 )<<std::endl;\n\n                std::vector< double > bestPopulation = isl.get_population( ).champion_x( );\n\n                Eigen::VectorXd radialFreeParameters = Eigen::VectorXd::Zero( 2 );\n                Eigen::VectorXd normalFreeParameters = Eigen::VectorXd::Zero( 0 );\n                Eigen::VectorXd axialFreeParameters = Eigen::VectorXd::Zero( 3 );\n\n                radialFreeParameters << bestPopulation.at( 2 ), bestPopulation.at( 3 );\n                axialFreeParameters << bestPopulation.at( 4 ), bestPopulation.at( 5 ), bestPopulation.at( 6 );\n\n                double timeOfFlight = bestPopulation.at( 1 );\n                double derpartureTime = bestPopulation.at( 0 );\n                double arrivalTime = derpartureTime + timeOfFlight;\n\n                double initialMass = 2000.0;\n                double specificImpulse = 3000.0;\n\n\n                std::vector< std::vector< std::shared_ptr< BaseFunctionHodographicShaping > > > shapingFunctions = getShapingBasisFunctions(\n                            timeOfFlight, 2 );\n\n                std::shared_ptr< HodographicShaping > hodographicShaping =\n                        std::make_shared< HodographicShaping >(\n                            departureStateFunction( derpartureTime ), arrivalStateFunction( arrivalTime ), timeOfFlight,\n                            spice_interface::getBodyGravitationalParameter( \"Sun\" ), 2,\n                            shapingFunctions.at( 0 ), shapingFunctions.at( 1 ), shapingFunctions.at( 2 ),\n                            radialFreeParameters, normalFreeParameters, axialFreeParameters, initialMass );\n\n                // Save results\n                int numberOfSteps = 1000;\n                double stepSize = timeOfFlight / static_cast< double >( numberOfSteps );\n                std::shared_ptr< numerical_integrators::IntegratorSettings< double > > integratorSettings =\n                        std::make_shared< numerical_integrators::IntegratorSettings< double > > ( numerical_integrators::rungeKutta4, 0.0, stepSize );\n\n                std::vector< double > epochsToSaveResults;\n                for ( int i = 0 ; i <= numberOfSteps ; i++ )\n                {\n                    epochsToSaveResults.push_back( i * stepSize );\n                }\n\n                std::map< double, Eigen::Vector6d > hodographicShapingTrajectory;\n                std::map< double, Eigen::VectorXd > hodographicShapingMassProfile;\n                std::map< double, Eigen::VectorXd > hodographicShapingThrustProfile;\n                std::map< double, Eigen::VectorXd > hodographicShapingThrustAcceleration;\n\n                hodographicShaping->getTrajectory(\n                            epochsToSaveResults, hodographicShapingTrajectory );\n                hodographicShaping->getMassProfile(\n                            epochsToSaveResults, hodographicShapingMassProfile, [ = ]( const double ){ return specificImpulse; }, integratorSettings );\n                hodographicShaping->getThrustForceProfile(\n                            epochsToSaveResults, hodographicShapingThrustProfile, [ = ]( const double ){ return specificImpulse; }, integratorSettings );\n                hodographicShaping->getCylindricalThrustAccelerationProfile(\n                            epochsToSaveResults, hodographicShapingThrustAcceleration );\n\n                input_output::writeDataMapToTextFile(\n                            hodographicShapingTrajectory, \"hodographicShapingOptimalTrajectory.dat\", tudat_pagmo_applications::getOutputPath( ) );\n\n                input_output::writeDataMapToTextFile(\n                            hodographicShapingMassProfile, \"hodographicShapingOptimalMassProfile.dat\", tudat_pagmo_applications::getOutputPath( ) );\n\n                input_output::writeDataMapToTextFile(\n                            hodographicShapingThrustProfile, \"hodographicShapingOptimalThrustProfile.dat\", tudat_pagmo_applications::getOutputPath( ) );\n\n                input_output::writeDataMapToTextFile(\n                            hodographicShapingThrustAcceleration, \"hodographicShapingOptimalThrustAcceleration.dat\", tudat_pagmo_applications::getOutputPath( ) );\n            }\n        }\n    }\n}\n", "meta": {"hexsha": "7e3c812098591aea057fa1e387a618d79113de6c", "size": 14682, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/pagmo/hodographicShapingFullOptimisationExample.cpp", "max_stars_repo_name": "kimonito98/tudat", "max_stars_repo_head_hexsha": "c28f2a3e78b8492e2e054ad5e0d1f9ad785cd092", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/pagmo/hodographicShapingFullOptimisationExample.cpp", "max_issues_repo_name": "kimonito98/tudat", "max_issues_repo_head_hexsha": "c28f2a3e78b8492e2e054ad5e0d1f9ad785cd092", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/pagmo/hodographicShapingFullOptimisationExample.cpp", "max_forks_repo_name": "kimonito98/tudat", "max_forks_repo_head_hexsha": "c28f2a3e78b8492e2e054ad5e0d1f9ad785cd092", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 53.3890909091, "max_line_length": 162, "alphanum_fraction": 0.6472551424, "num_tokens": 3300, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7718434978390747, "lm_q2_score": 0.4416730056646256, "lm_q1q2_score": 0.34090243759328204}}
{"text": "//#include <cassert>\n//#include <cstdio>\n//#include <cmath>\n//#include <iostream>\n//#include <iomanip>\n//#include <sstream>\n//#include <vector>\n//#include <set>\n//#include <map>\n//#include <queue>\n//#include <numeric>\n//#include <algorithm>\n//\n//#include <boost/heap/fibonacci_heap.hpp>\n//\n//using namespace std;\n//using lint = long long;\n//constexpr int MOD = 1000000007, INF = 1010101010;\n//constexpr lint LINF = 1LL << 60;\n//\n//template <class T>\n//ostream &operator<<(ostream &os, const vector<T> &vec) {\n//\tfor (const auto &e : vec) os << e << (&e == &vec.back() ? \"\\n\" : \" \");\n//\treturn os;\n//}\n//\n//template <class T>\n//ostream &operator<<(ostream &os, const set<T> &st) {\n//\tfor (const auto &e : st) os << e << \" \";\n//\treturn os;\n//}\n//\n//template <class T1, class T2>\n//ostream &operator<<(ostream &os, const pair<T1, T2> &p) {\n//\tos << \"(\" << p.first << \",\" << p.second << \")\";\n//\treturn os;\n//}\n//\n//template <class T1, class T2>\n//ostream &operator<<(ostream &os, const map<T1, T2> &mp) {\n//\tfor (const auto &e : mp) os << e << \" \";\n//\treturn os;\n//}\n//\n//#ifdef _DEBUG\n//template <class T>\n//void dump(const char* str, T &&h) { cerr << str << \" = \" << h << \"\\n\"; };\n//template <class Head, class... Tail>\n//void dump(const char* str, Head &&h, Tail &&... t) {\n//\twhile (*str != ',') cerr << *str++; cerr << \" = \" << h << \"\\n\";\n//\tdump(str + (*(str + 1) == ' ' ? 2 : 1), t...);\n//}\n//#define DMP(...) dump(#__VA_ARGS__, __VA_ARGS__)\n//#else \n//#define DMP(...) ((void)0)\n//#endif\n//\n//template<class T = lint>\n//struct Edge {\n//\tint to;\n//\tT cost;\n//\tint tank;\n//\tEdge() {}\n//\tEdge(int to, T cost, int tank = 0) : to(to), cost(cost), tank(tank) {}\n//\tbool operator>(const Edge &r) const { return this->cost > r.cost; }\n//};\n//\n//int main() {\n//\n//\tcin.tie(nullptr);\n//\tios::sync_with_stdio(false);\n//\n//\tint N, M, L;\n//\tcin >> N >> M >> L;\n//\n//\tvector<vector<Edge<int>>> edges(N);\n//\tfor (int i = 0; i < M; i++) {\n//\t\tint u, v, len;\n//\t\tcin >> u >> v >> len;\n//\t\tu--, v--;\n//\t\tif (len > L) continue;\n//\t\tedges[u].emplace_back(v, len);\n//\t\tedges[v].emplace_back(u, len);\n//\t}\n//\n//\tauto dijkstra = [&](int st) {\n//\t\tvector<pair<int, int>> dp(N, { INF, 0 });\n//\t\tdp[st] = { 0, -L };\n//\t\tusing ppi = pair<pair<int, int>,int>;\n//\t\tpriority_queue<ppi, vector<ppi>, greater<ppi>> que;\n//\t\tque.emplace(dp[st], st);\n//\t\twhile (!que.empty()) {\n//\t\t\tauto now = que.top();\n//\t\t\tque.pop();\n//\n//\t\t\tif (now.first > dp[now.second]) continue;\n//\n//\t\t\tfor (const auto &e : edges[now.second]) {\n//\n//\t\t\t\tauto tmp = now.first;\n//\t\t\t\tif (e.cost > -tmp.second) {\n//\t\t\t\t\ttmp.first++;\n//\t\t\t\t\ttmp.second = -L + e.cost;\n//\t\t\t\t}\n//\t\t\t\telse tmp.second += e.cost;\n//\n//\t\t\t\tif (tmp < dp[e.to]) {\n//\t\t\t\t\tdp[e.to] = tmp;\n//\t\t\t\t\tque.emplace(tmp, e.to);\n//\t\t\t\t}\n//\n//\t\t\t}\n//\t\t}\n//\t\treturn dp;\n//\t};\n//\n//\tvector<vector<pair<int, int>>> memo(N);\n//\tfor (int i = 0; i < N; i++) memo[i] = dijkstra(i);\n//\n//\tint Q;\n//\tcin >> Q;\n//\tfor (int i = 0; i < Q; i++) {\n//\t\tint s, t;\n//\t\tcin >> s >> t;\n//\t\ts--, t--;\n//\t\tauto tmp = memo[s][t].first;\n//\t\tif (tmp != INF) cout << tmp << \"\\n\";\n//\t\telse cout << -1 << \"\\n\";\n//\t}\n//\n//\treturn 0;\n//}", "meta": {"hexsha": "7df7bb21c66288b4c18dd7a710f779832e676875", "size": 3113, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ABC/ABC143/E_ver2.cpp", "max_stars_repo_name": "rajyan/AtCoder", "max_stars_repo_head_hexsha": "2c1187994016d4c19b95489d2f2d2c0eab43dd8e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-06-01T17:13:44.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-01T17:13:44.000Z", "max_issues_repo_path": "ABC/ABC143/E_ver2.cpp", "max_issues_repo_name": "rajyan/AtCoder", "max_issues_repo_head_hexsha": "2c1187994016d4c19b95489d2f2d2c0eab43dd8e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ABC/ABC143/E_ver2.cpp", "max_forks_repo_name": "rajyan/AtCoder", "max_forks_repo_head_hexsha": "2c1187994016d4c19b95489d2f2d2c0eab43dd8e", "max_forks_repo_licenses": ["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.5833333333, "max_line_length": 75, "alphanum_fraction": 0.5101188564, "num_tokens": 1051, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6370308082623217, "lm_q2_score": 0.5350984286266116, "lm_q1q2_score": 0.3408741844879087}}
{"text": "//---------------------------------------------------------------------------//\n// Copyright (c) 2018-2019 Mikhail Komarov <nemo@nil.foundation>\n// Copyright (c) 2020 Nikita Kaskov <nbering@nil.foundation>\n//\n// Distributed under the Boost Software License, Version 1.0\n// See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt\n//---------------------------------------------------------------------------//\n\n#ifndef CRYPTO3_DETAIL_ENDIAN_SHIFT_HPP\n#define CRYPTO3_DETAIL_ENDIAN_SHIFT_HPP\n\n#include <boost/assert.hpp>\n\n#include <boost/crypto3/detail/stream_endian.hpp>\n#include <boost/crypto3/detail/basic_functions.hpp>\n#include <boost/crypto3/detail/unbounded_shift.hpp>\n\nnamespace boost {\n    namespace crypto3 {\n        namespace detail {\n\n            template<typename Endianness, std::size_t WordBits>\n            struct endian_shift;\n\n            template<int UnitBits, std::size_t WordBits>\n            struct endian_shift<stream_endian::big_unit_big_bit<UnitBits>, WordBits>\n                : public basic_functions<WordBits> {\n\n                constexpr static const std::size_t word_bits = basic_functions<WordBits>::word_bits;\n                typedef typename basic_functions<WordBits>::word_type word_type;\n\n                static word_type &to_msb(word_type &w, std::size_t shift) {\n                    // shift to most significant bits according to endianness\n                    w = unbounded_shl(w, shift);\n                    return w;\n                }\n            };\n\n            template<int UnitBits, std::size_t WordBits>\n            struct endian_shift<stream_endian::little_unit_big_bit<UnitBits>, WordBits>\n                : public basic_functions<WordBits> {\n\n                constexpr static const std::size_t word_bits = basic_functions<WordBits>::word_bits;\n                typedef typename basic_functions<WordBits>::word_type word_type;\n\n                static word_type &to_msb(word_type &w, std::size_t shift) {\n                    // shift to most significant bits according to endianness\n                    std::size_t shift_rem = shift % UnitBits;\n                    std::size_t shift_unit_bits = shift - shift_rem;\n\n                    std::size_t sz[2] = {UnitBits - shift_rem, shift_rem};\n                    word_type masks[2];\n                    masks[0] = unbounded_shl(low_bits<word_bits>(~word_type(), sz[0]), shift_unit_bits);\n                    masks[1] =\n                        unbounded_shl(low_bits<word_bits>(~word_type(), sz[1]), shift_unit_bits + UnitBits + sz[0]);\n                    std::size_t bits_left = word_bits - shift;\n\n                    word_type w_combined = 0;\n                    int ind = 0;\n\n                    while (bits_left) {\n                        w_combined |= (!ind ? unbounded_shl(w & masks[0], shift_rem) :\n                                              unbounded_shr(w & masks[1], UnitBits + sz[0]));\n                        bits_left -= sz[ind];\n                        masks[ind] = unbounded_shl(masks[ind], UnitBits);\n                        ind = 1 - ind;\n                    }\n\n                    w = unbounded_shr(w_combined, shift_unit_bits);\n                    return w;\n                }\n            };\n\n            template<int UnitBits, std::size_t WordBits>\n            struct endian_shift<stream_endian::big_unit_little_bit<UnitBits>, WordBits>\n                : public basic_functions<WordBits> {\n\n                constexpr static const std::size_t word_bits = basic_functions<WordBits>::word_bits;\n                typedef typename basic_functions<WordBits>::word_type word_type;\n\n                static word_type &to_msb(word_type &w, std::size_t shift) {\n                    // shift to most significant bits according to endianness\n                    std::size_t shift_rem = shift % UnitBits;\n                    std::size_t shift_unit_bits = shift - shift_rem;\n\n                    std::size_t sz[2] = {UnitBits - shift_rem, shift_rem};\n                    word_type masks[2] = {\n                        unbounded_shr(high_bits<word_bits>(~word_type(), sz[0]), shift_unit_bits),\n                        unbounded_shr(high_bits<word_bits>(~word_type(), sz[1]), shift_unit_bits + UnitBits + sz[0])};\n\n                    std::size_t bits_left = word_bits - shift;\n                    word_type w_combined = 0;\n                    int ind = 0;\n\n                    while (bits_left) {\n                        w_combined |= (!ind ? unbounded_shr(w & masks[0], shift_rem) :\n                                              unbounded_shl(w & masks[1], UnitBits + sz[0]));\n                        bits_left -= sz[ind];\n                        masks[ind] = unbounded_shr(masks[ind], UnitBits);\n                        ind = 1 - ind;\n                    }\n\n                    w = unbounded_shl(w_combined, shift_unit_bits);\n                    return w;\n                }\n            };\n\n            template<int UnitBits, std::size_t WordBits>\n            struct endian_shift<stream_endian::little_unit_little_bit<UnitBits>, WordBits>\n                : public basic_functions<WordBits> {\n\n                constexpr static const std::size_t word_bits = basic_functions<WordBits>::word_bits;\n                typedef typename basic_functions<WordBits>::word_type word_type;\n\n                static word_type &to_msb(word_type &w, std::size_t shift) {\n\n                    // shift to most significant bits according to endianness\n                    w = unbounded_shr(w, shift);\n                    return w;\n                }\n            };\n        }    // namespace detail\n    }        // namespace crypto3\n}    // namespace boost\n\n#endif    // CRYPTO3_DETAIL_ENDIAN_SHIFT_HPP\n", "meta": {"hexsha": "e1c44b48801b0dbac840d64e3608cc8c7c753aa2", "size": 5709, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/crypto3/detail/endian_shift.hpp", "max_stars_repo_name": "NilFoundation/boost-crypto", "max_stars_repo_head_hexsha": "a3e599b780bbbbc063b7c8da0e498125769e08be", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2020-09-02T06:19:14.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-07T04:55:03.000Z", "max_issues_repo_path": "include/boost/crypto3/detail/endian_shift.hpp", "max_issues_repo_name": "NilFoundation/boost-crypto", "max_issues_repo_head_hexsha": "a3e599b780bbbbc063b7c8da0e498125769e08be", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2020-04-06T21:49:03.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-18T04:54:51.000Z", "max_forks_repo_path": "include/boost/crypto3/detail/endian_shift.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": 44.6015625, "max_line_length": 118, "alphanum_fraction": 0.5394990366, "num_tokens": 1168, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7520125848754472, "lm_q2_score": 0.4532618480153861, "lm_q1q2_score": 0.3408586139514726}}
{"text": "\n/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */\n/*                                                                           */\n/*  This file is part of the library KASKADE 7                               */\n/*    see http://www.zib.de/projects/kaskade7-finite-element-toolbox         */\n/*                                                                           */\n/*  Copyright (C) 2015-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 MG_MULTIPLICATIVEMULTIGRID_HH\n#define MG_MULTIPLICATIVEMULTIGRID_HH\n\n#include <type_traits>\n\n#include <boost/timer/timer.hpp>\n\n#include <dune/istl/preconditioner.hh>\n\n#include \"fem/spaces.hh\"\n#include \"linalg/conjugation.hh\"\n#include \"linalg/direct.hh\"\n#include \"linalg/domainDecompositionPreconditioner.hh\"\n#include \"linalg/jacobiPreconditioner.hh\"\n#include \"linalg/symmetricOperators.hh\"\n#include \"mg/prolongation.hh\"\n#include \"utilities/memory.hh\"\n#include \"utilities/timing.hh\"\n\nnamespace Kaskade\n{\n\n\n  // ----------------------------------------------------------------------------------------------------------------------\n\n  /**\n   * \\ingroup multigrid\n   * \\brief A general multiplicative multigrid preconditioner.\n   *\n   * This realizes a classical V-cycle with a specified number of pre- and post-smoothings. Two (possibly different)\n   * preconditioners are used for (i) smoothing on the levels and (ii) approximately solving the coarse grid system.\n   *\n   * Note that this is only a preconditioner, no solver. In fact, the computed step is not guaranteed to decrease the energy\n   * of the error (depending on the smoother - Gauss-Seidel does, but Jacobi need not).\n   *\n   * \\tparam Entry the type of projected Galerkin matrix entries\n   * \\tparam Index the index type of Galerkin matrices (usually size_t)\n   * \\tparam Smoother a smoother type\n   * \\tparam Prolongation the type of prolongations (conceptually a sparse matrix type)\n   *\n   * The smoother may rely on the matrix provided on construction remaining available during any\n   * method calls besides the smoother destruction. Hence it is perfectly suitable for the smoother\n   * just to reference parts of the matrix.\n   *\n   * A convenient construction of multiplicative multigrid preconditioners is provided by the functions\n   * makeMultiplicativeMultiGrid and makeJacobiMultiGrid for h-multigrid in grid hierarchies, and\n   * makeMultiplicativePMultiGrid makeJacobiPMultiGrid for p-h-multigrid exploiting both polynomial order\n   * and grid hierarchies.\n   *\n   * Multigrid preconditioners can be put together easily from the three main ingredients multigrid stack,\n   * coarse solver, and smoother as follows:\n   * \\code\n   * auto mgStack = makeGeometricMultiGridStack(gridman,duplicate(A),onlyLowerTriangle);\n   * auto coarsePreconditioner = makeDirectPreconditioner(std::move(mgStack.coarseGridMatrix()));\n   * auto mg = makeMultiplicativeMultiGrid(std::move(mgStack),MakeJacobiSmoother(),moveUnique(std::move(coarsePreconditioner)),nPre,nPost);\n   * mg.setSmootherStepSize(0.5);\n   * \\endcode\n   */\n  template <class Entry, class Index, class Smoother, class Prolongation>\n  class MultiplicativeMultiGrid: public SymmetricPreconditioner<typename Smoother::domain_type,typename Smoother::range_type>\n  {\n  public:\n    using field_type = typename Smoother::field_type;\n    using domain_type = typename Smoother::domain_type;\n    using range_type = typename Smoother::range_type;\n    using CoarsePreconditioner = Dune::Preconditioner<domain_type,range_type>; // symmetric would be better? but elaborate implementation for direct solvers\n\n    /**\n     * \\brief Default constructor.\n     */\n    MultiplicativeMultiGrid() = default;\n\n    /**\n     * \\brief Constructor.\n     * \\param A the Galerkin matrix to be preconditioned\n     * \\param Ps the stack of multigrid prolongations\n     * \\param makeSmoother a callable object with arguments (Matrix const&, int level) that creates a smoother of type Smoother\n     *\n     * \\see makeMultiplicativeMultiGrid\n     * \\see makeJacobiMultiGrid\n     */\n    template <class MakeSmoother>\n    MultiplicativeMultiGrid(MultiGridStack<Prolongation,Entry,Index>&& mgStack_, MakeSmoother const& makeSmoother,\n                            std::unique_ptr<CoarsePreconditioner>&& coarsePreconditioner_, int nPre_=3, int nPost_=3)\n    : mgStack(std::move(mgStack_)), nPre(nPre_), nPost(nPost_), coarsePreconditioner(std::move(coarsePreconditioner_)),\n      linesearch(false), smootherStepSize(1.0)\n    {\n      // Create the smoothers for all levels.\n      Timings& timer = Timings::instance();\n      timer.start(\"smoother construction\");\n      for (int l=1; l<mgStack.levels(); ++l)\n        smoothers.push_back(makeSmoother(mgStack.a(l)));\n      timer.stop(\"smoother construction\");\n    }\n\n    MultiplicativeMultiGrid(MultiplicativeMultiGrid&& other) = default;\n\n    MultiplicativeMultiGrid& operator=(MultiplicativeMultiGrid&& other) = default;\n\n\n    /**\n     * \\brief Application of preconditioner.\n     *\n     * Precondition: x = 0\n     */\n    virtual void apply(domain_type& x, range_type const& r)\n    {\n      assert(x.two_norm()==0);\n      range_type b = r;\n      runMG(x,b,mgStack.levels()-1);\n    }\n\n    virtual field_type applyDp(domain_type& x, range_type const& r)\n    {\n      apply(x,r);\n      return x*r;\n    }\n\n    virtual bool requiresInitializedInput() const\n    {\n      return true;\n    }\n\n    /**\n     * \\brief Sets the number of pre- and post-smoothing iterations to perform.\n     *\n     * Note that the sum of pre- and postsmoothings must be positive.\n     *\n     * \\param nPre number of pre-smoothings (nonnegative)\n     * \\param nPost number of post-smoothings (nonnegative)\n     */\n    void setSmoothings(int nPre_, int nPost_)\n    {\n      nPre = nPre_;\n      nPost = nPost_;\n      assert(nPre>=0 && nPost>=0 && nPre+nPost>0);\n    }\n\n    /**\n     * \\brief Define the smoother step size.\n     *\n     * The default step length is 1.\n     */\n    void setSmootherStepSize(double w)\n    {\n      assert(w>0);\n      smootherStepSize = w;\n    }\n\n    double getSmootherStepSize() const { return smootherStepSize; }\n\n    /**\n     * \\brief Enable or disable the line search option.\n     *\n     * With line search option, at the end of each level in the V-cycle a line search is performed for\n     * an optimal scaling of the correction. This may improve the contraction (but need not, for simple\n     * Laplace type problems it does not) and guarantee convergence of the multigrid as a fixed point\n     * iteration (removing the need for an outer stepsize loop), but incurs one more matrix-vector product\n     * (an overhead of up to 30%) and renders the V-cycle a nonlinear scheme, not suited as preconditioner\n     * in CG.\n     *\n     * The default value on construction is off.\n     */\n    void setLinesearch(bool ls)\n    {\n      linesearch = ls;\n    }\n\n    /**\n     * \\brief Provides access to the coarse grid preconditioner.\n     */\n    CoarsePreconditioner& getCoarsePreconditioner()\n    {\n      return *coarsePreconditioner;\n    }\n\n    /**\n     * \\brief Returns a pair of number of pre- and post-smoothing iterations to perform.\n     */\n    std::pair<int,int> getSmoothings()\n    {\n      return std::make_pair(nPre,nPost);\n    }\n\n  private:\n    // precondition: x==0\n    void runMG(domain_type& x, range_type& r, int level)\n    {\n      if (level==0)\n      {\n        coarsePreconditioner->pre(x,r);\n        coarsePreconditioner->apply(x,r);\n        coarsePreconditioner->post(x);\n      }\n      else\n      {\n        auto& s = smoothers[level-1];             // Smoother S\n        auto const& a = mgStack.a(level);         // Galerkin matrix A\n        double w = smootherStepSize;\n        domain_type dx(x);                        // temporary vector\n        range_type adx(r);\n\n        // pre-smoothing\n        bool const sRequiresZeroInput = s.requiresInitializedInput();\n        s.pre(x,r);\n        for (int i=0; i<nPre; ++i)\n        {\n          if (sRequiresZeroInput) dx = 0;\n          s.apply(dx,r);                          // dx = B^{-1} r\n          if (linesearch)\n          {\n            double dxadx = a.mv(dx,adx);          // adx = A*dx           residual update direction\n            w = dx*r / (dxadx);                   // w = dx*r / dx*A*dx   \"optimal\" step length\n            r.axpy(-w,adx);                       // r = r - w*adx        update residual\n          }\n          else\n            a.usmv(-w,dx,r);                      // r = r - w*A*dx       update residual (without intermediate adx access)\n          x.axpy(w,dx);                           // x = x + w*dx         update iterate\n        }\n        s.post(x);\n\n        // coarse grid correction\n        auto const& p = mgStack.p(level-1);\n        range_type cr; cr.resize(p.M());\n        p.mtv(r,cr);                             // cr = P^T r\n        domain_type cx; cx.resize(p.M()); cx = 0;\n        runMG(cx,cr,level-1);                    // cx ~ (P^T A P)^{-1} cr\n        p.mv(cx,dx);                             // dx = P*cx\n        x += dx;                                 // x = x+dx\n        a.usmv(-1,dx,r);                         // r = r-A*dx\n\n\n        // post-smoothing\n        s.pre(x,r);\n        for (int i=0; i<nPost; ++i)\n        {\n          if (sRequiresZeroInput) dx = 0;\n          s.apply(dx,r);                          // dx = B^{-1} r\n          if (i+1<nPost || linesearch)            // update residual only if needed lateron\n          {\n            if (linesearch)\n            {\n              double dxadx = a.mv(dx,adx);        // adx = A*dx\n              w = dx*r / (dxadx);                 // w = dx*r / dx*A*dx\n              r.axpy(-w,adx);                     // r = r - w*adx\n            }\n            else\n              a.usmv(-w,dx,r);                    // r = r - w*A*dx\n          }\n          x.axpy(w,dx);                           // x = x + w*dx\n        }\n        s.post(x);\n\n        // optional line search\n        if (linesearch)\n        {\n          a.mv(x,dx);                             // dx = Ax\n          double omega = (x*r) / (dx*x);          // omega = r^T x / x^T A x\n          x *= 1+omega;                           // x = x + omega * x\n        }\n      }\n    }\n\n    MultiGridStack<Prolongation,Entry,Index>  mgStack;\n    std::vector<Smoother>                     smoothers;\n    int                                       nPre, nPost;\n    std::unique_ptr<CoarsePreconditioner>     coarsePreconditioner;\n    bool                                      linesearch;\n    double                                    smootherStepSize;\n  };\n\n  // ----------------------------------------------------------------------------------------------------------------------\n\n  /**\n   * \\ingroup multigrid\n   * \\brief Convenience function creating multiplicative multigrid preconditioner of V-cycle type for P1 elements.\n   *\n   * \\param mgStack a stack of prolongations and matching projected Galerkin matrices\n   * \\param makeSmoother a callable object taking a (projected) Galerkin matrix of type NumaBCRSMatrix<Entry,Index>\n   *                     and a level, returning a preconditioner\n   * \\param coarsePreconditioner a symmetric preconditioner to be used for \"solving\" on the coarsest level\n   * \\param nPre the number of pre-smoothings\n   * \\param nPost the number of post-smoothings\n   *\n   * \\relates MultiplicativeMultiGrid\n   */\n  template <class Entry, class Index, class Prolongation, class MakeSmoother, class CoarsePreconditioner>\n  auto makeMultiplicativeMultiGrid(MultiGridStack<Prolongation,Entry,Index>&& mgStack,\n                                   MakeSmoother const& makeSmoother,\n                                   std::unique_ptr<CoarsePreconditioner>&& coarsePreconditioner,\n                                   int nPre=3, int nPost=3)\n  {\n    using Smoother = std::result_of_t<MakeSmoother(NumaBCRSMatrix<Entry,Index>)>;\n    return MultiplicativeMultiGrid<Entry,Index,Smoother,Prolongation>(\n                std::move(mgStack),makeSmoother,std::move(coarsePreconditioner),nPre,nPost);\n  }\n\n  // ----------------------------------------------------------------------------------------------------------------------\n  // ----------------------------------------------------------------------------------------------------------------------\n\n  /**\n   * \\ingroup smoothers\n   * \\brief Functor for creating Jacobi smoothers.\n   */\n  class MakeJacobiSmoother\n  {\n  public:\n    template <typename Matrix>\n    auto operator()(Matrix const& a) const\n    {\n      return makeJacobiPreconditioner(a);\n    }\n  };\n\n  /**\n   * \\ingroup smoothers\n   * \\brief Functor for creating overlapping Schwarz smoothers.\n   */\n  template <typename Space>\n  class MakeAdditiveSchwarzSmoother\n  {\n  public:\n    MakeAdditiveSchwarzSmoother(Space const& space_): space(space_) {}\n\n    template <typename Entry, typename Index>\n    auto operator()(NumaBCRSMatrix<Entry,Index> const& a) const\n    {\n      return PatchDomainDecompositionPreconditioner<Space,Entry::rows>(space,a);\n    }\n\n  private:\n    Space const& space;\n  };\n\n  /**\n   * \\ingroup multigrid\n   * \\brief Creates a direct solver for the given matrix.\n   */\n  template <typename Matrix>\n  auto makeDirectPreconditioner(Matrix&& A, DirectType directType=DirectType::MUMPS)\n  {\n    return DirectSolver<typename MatrixTraits<Matrix>::NaturalDomain,typename MatrixTraits<Matrix>::NaturalRange>(A,directType);\n  }\n\n  // ----------------------------------------------------------------------------------------------------------------------\n  // ----------------------------------------------------------------------------------------------------------------------\n\n  /**\n   * \\ingroup multigrid\n   * \\brief Convenience function creating multiplicative Jacobi multigrid for P1 elements.\n   *\n   * This creates a V-cycle multigrid preconditioner with Jacobi smoother. A direct solver is used for grid level 0.\n   *\n   * \\param A the sparse Galerkin matrix for P1 finite elements on the leaf view of the given simplicial grid\n   * \\param gridman a grid manager base of a simplicial grid\n   * \\param nPre the number of pre-smoothings\n   * \\param nPost the number of post-smoothings\n   * \\param onlyLowerTriangle if true, A is assumed to be symmetric and only its lower triangular part is accessed\n   *\n   * \\relates MultiplicativeMultiGrid\n   */\n  template <class Entry, class Index, class GridMan>\n  auto makeJacobiMultiGrid(NumaBCRSMatrix<Entry,Index> const& A, GridMan const& gridman,\n                           int nPre=3, int nPost=3, bool onlyLowerTriangle=false)\n  {\n    Timings& timer = Timings::instance();\n\n    timer.start(\"MG stack creation\");\n    auto mgStack = makeGeometricMultiGridStack(gridman,duplicate(A),onlyLowerTriangle);\n    timer.stop(\"MG stack creation\");\n\n    timer.start(\"direct solver creation\");\n    auto coarsePreconditioner = makeDirectPreconditioner(std::move(mgStack.coarseGridMatrix()));\n    timer.stop(\"direct solver creation\");\n\n    timer.start(\"MG creation\");\n    auto mg = makeMultiplicativeMultiGrid(std::move(mgStack),MakeJacobiSmoother(),moveUnique(std::move(coarsePreconditioner)),nPre,nPost);\n    timer.stop(\"MG creation\");\n    mg.setSmootherStepSize(0.5);\n\n    return mg;\n  }\n\n  /**\n   * \\ingroup multigrid\n   * \\brief Convenience function creating multiplicative multigrid preconditioner of V-cycle type for higher order elements.\n   *\n   * \\param A the sparse Galerkin matrix for higher order finite elements on the leaf view of the given simplicial grid\n   * \\param space a higher order finite element space\n   * \\param p1Space a linear finite element space\n   * \\param makeSmoother a callable object taking a (projected) Galerkin matrix of type NumaBCRSMatrix<Entry,Index> and a level, returning a preconditioner\n   * \\param nPre the number of pre-smoothings\n   * \\param nPost the number of post-smoothings\n   * \\param onlyLowerTriangle if true, A is assumed to be symmetric and only its lower triangular part is accessed\n   *\n   * \\relates MultiplicativeMultiGrid\n   */\n  template <class Entry, class Index, class Space, class MakeSmoother>\n  auto makeMultiplicativePMultiGrid(NumaBCRSMatrix<Entry,Index>&& A, Space const& space,\n                                    MakeSmoother const& makeSmoother, int nPre=3, int nPost=3, bool onlyLowerTriangle=false)\n  {\n    Timings& timer = Timings::instance();\n    timer.start(\"create P multigrid stack\");\n    auto mgStack = makePMultiGridStack(space,std::move(A),onlyLowerTriangle);\n    timer.stop(\"create P multigrid stack\");\n\n    timer.start(\"create MG as coarse solver\");\n    auto coarsePreconditioner = makeJacobiMultiGrid(std::move(mgStack.coarseGridMatrix()),space.gridManager(),nPre,nPost,onlyLowerTriangle);\n    coarsePreconditioner.setSmootherStepSize(0.6);\n    timer.stop(\"create MG as coarse solver\");\n\n    timer.start(\"create multigrid\");\n    auto mg = makeMultiplicativeMultiGrid(std::move(mgStack),makeSmoother,moveUnique(std::move(coarsePreconditioner)),nPre,nPost);\n    timer.stop(\"create multigrid\");\n\n    return mg;\n  }\n\n  /**\n   * \\ingroup multigrid\n   * \\brief Convenience function creating multiplicative multigrid preconditioner of V-cycle type for higher order elements.\n   *\n   * This is realized as a multiplicative h-multigrid nested within a two-grid scheme.\n   * The outer two-level algorithm uses an overlapping domain decomposition smoother on the patches around grid vertices.\n   * Classical h-multigrid with point Jacobi smoother is used as a coarse level preconditioner/solver.\n   *\n   * The default smoother step sizes are 0.5 for the domain decomposition smoother and 0.8 for the Jacobi smoother. In a\n   * preliminary test (Poisson equation on the unit square, 2016-01) these values turned out to be quite good.\n   *\n   * \\param A the sparse Galerkin matrix for higher order finite elements on the leaf view of the given simplicial grid\n   * \\param space a higher order finite element space\n   * \\param nPre the number of pre-smoothings\n   * \\param nPost the number of post-smoothings\n   * \\param onlyLowerTriangle if true, A is assumed to be symmetric and only its lower triangular part is accessed\n   *\n   * \\relates MultiplicativeMultiGrid\n   */\n  template <class Entry, class Index, class Space, class CoarseSpace>\n  auto makeBlockJacobiPMultiGrid(NumaBCRSMatrix<Entry,Index> A, Space const& space,\n                                 NumaBCRSMatrix<Entry,Index> coarseA, CoarseSpace const& coarseSpace,\n                                 int nPre=3, int nPost=3)\n  {\n    Timings& timer = Timings::instance();\n    timer.start(\"create P multigrid stack\");\n    auto mgStack = makePMultiGridStack(space,std::move(A),coarseSpace,std::move(coarseA));\n    timer.stop(\"create P multigrid stack\");\n\n    timer.start(\"create MG as coarse solver\");\n    auto coarsePreconditioner = makeJacobiMultiGrid(std::move(mgStack.coarseGridMatrix()),space.gridManager(),nPre,nPost);\n    coarsePreconditioner.setSmootherStepSize(0.6);\n    timer.stop(\"create MG as coarse solver\");\n\n    timer.start(\"create multigrid\");\n    auto mg = makeMultiplicativeMultiGrid(std::move(mgStack),MakeAdditiveSchwarzSmoother<Space>(space),\n                                          moveUnique(std::move(coarsePreconditioner)),nPre,nPost);\n    mg.setSmootherStepSize(0.5);\n    timer.stop(\"create multigrid\");\n\n    return mg;\n  }\n\n  /**\n   * \\ingroup multigrid\n   * \\brief Convenience function creating multiplicative multigrid preconditioner of V-cycle type for higher order elements.\n   *\n   * This is realized as a multiplicative h-multigrid nested within a two-grid scheme.\n   * The outer two-level algorithm uses an overlapping domain decomposition smoother on the patches around grid vertices.\n   * Classical h-multigrid with point Jacobi smoother is used as a coarse level preconditioner/solver.\n   *\n   * The default smoother step sizes are 0.5 for the domain decomposition smoother and 0.8 for the Jacobi smoother. In a\n   * preliminary test (Poisson equation on the unit square, 2016-01) these values turned out to be quite good.\n   *\n   * \\param A the sparse Galerkin matrix for higher order finite elements on the leaf view of the given simplicial grid\n   * \\param space a higher order finite element space\n   * \\param nPre the number of pre-smoothings\n   * \\param nPost the number of post-smoothings\n   * \\param onlyLowerTriangle if true, A is assumed to be symmetric and only its lower triangular part is accessed\n   *\n   * \\relates MultiplicativeMultiGrid\n   */\n  template <class Entry, class Index, class Space>\n  auto makeBlockJacobiPMultiGrid(NumaBCRSMatrix<Entry,Index> A, Space const& space,\n                                 int nPre=3, int nPost=3, bool onlyLowerTriangle=false)\n  {\n    auto mg = makeMultiplicativePMultiGrid(std::move(A),space,MakeAdditiveSchwarzSmoother<Space>(space),\n                                           nPre,nPost,onlyLowerTriangle);\n    mg.setSmootherStepSize(0.5);\n    return mg;\n  }\n\n  /**\n   * \\ingroup multigrid\n   * \\brief Convenience function creating multiplicative multigrid preconditioner of V-cycle type with Jacobi smoother for higher order elements.\n   *\n   * \\param A the sparse Galerkin matrix for higher order finite elements on the leaf view of the given simplicial grid\n   * \\param space a higher order finite element space\n   * \\param nPre the number of pre-smoothings\n   * \\param nPost the number of post-smoothings\n   * \\param onlyLowerTriangle if true, A is assumed to be symmetric and only its lower triangular part is accessed\n   *\n   * \\relates MultiplicativeMultiGrid\n   */\n  template <class Entry, class Index, class FineSpace>\n  auto makeJacobiPMultiGrid(NumaBCRSMatrix<Entry,Index> A, FineSpace const& space,\n                            int nPre=3, int nPost=3, bool onlyLowerTriangle=false)\n  {\n    auto mg = makeMultiplicativePMultiGrid(std::move(A),space,MakeJacobiSmoother(),nPre,nPost,onlyLowerTriangle);\n    mg.setSmootherStepSize(0.5);\n    return mg;\n  }\n\n\n\n\n  // ---------------------------------------------------------------------------------------------------------\n\n\n}\n\n#endif\n", "meta": {"hexsha": "c9f5e7ce9c0382cd6e5378cec385557bea2ad103", "size": 22424, "ext": "hh", "lang": "C++", "max_stars_repo_path": "Kaskade/mg/multiplicativeMultigrid.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/mg/multiplicativeMultigrid.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/mg/multiplicativeMultigrid.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.9925093633, "max_line_length": 156, "alphanum_fraction": 0.6159471994, "num_tokens": 5388, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6187804478040617, "lm_q2_score": 0.5506073655352404, "lm_q1q2_score": 0.34070507221011076}}
{"text": "/*\n * runAlgoWithTuner.cc\n *\n *  Created on: Feb 10, 2014\n *      Author: chteflio\n */\n//    Copyright 2015 Christina Teflioudi\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/filesystem.hpp>\n#include <boost/program_options.hpp>\n\n#include <iostream>\n#include <mips/mips.h>\n\n#include <cblas.h>\n\n#define L2_CACHE_SIZE 256000\n#define MAX_MEM_SIZE (257840L*1024L*1024L)\n\nusing namespace std;\nusing namespace mips;\nusing namespace boost::program_options;\n\ninline void computeTopRating(double *ratings_matrix, int *top_K_items,\n                             const int num_users, const int num_items) {\n  for (int user_id = 0; user_id < num_users; user_id++) {\n\n    unsigned long index = user_id;\n    index *= num_items;\n    int best_item_id = cblas_idamax(num_items, &ratings_matrix[index], 1);\n    top_K_items[user_id] = best_item_id;\n  }\n}\n\ninline void computeTopK(double *ratings_matrix, int *top_K_items,\n                        const int num_users, const int num_items, const int K) {\n\n  for (int i = 0; i < num_users; i++) {\n\n    std::priority_queue<std::pair<double, int>,\n                        std::vector<std::pair<double, int> >,\n                        std::greater<std::pair<double, int> > > q;\n\n    unsigned long index = i;\n    index *= num_items;\n\n    for (int j = 0; j < K; j++) {\n      q.push(std::make_pair(ratings_matrix[index + j], j));\n    }\n\n    for (int j = K; j < num_items; j++) {\n      if (ratings_matrix[index + j] > q.top().first) {\n        q.pop();\n        q.push(std::make_pair(ratings_matrix[index + j], j));\n      }\n    }\n\n    for (int j = 0; j < K; j++) {\n      const std::pair<double, int> p = q.top();\n      top_K_items[i * K + K - 1 - j] = p.second;\n      q.pop();\n    }\n  }\n}\n\ninline double decisionRuleBlockedMM(VectorMatrix &q, VectorMatrix &p,\n                                    const unsigned int rand_ind,\n                                    const unsigned long num_users_per_block,\n                                    const int K) {\n\n  double *user_ptr = q.getMatrixRowPtr(rand_ind);\n  double *item_ptr = p.getMatrixRowPtr(0);\n  const long m = num_users_per_block;\n  const int n = p.rowNum;\n  const int k = q.colNum;\n  const float alpha = 1.0;\n  const float beta = 0.0;\n  double *matrix_product = (double *)malloc(m * n * sizeof(double));\n  int *top_K_items = (int *)malloc(m * K * sizeof(int));\n\n  rg::Timer tt;\n  tt.start();\n  cblas_dgemm(CblasRowMajor, CblasNoTrans, CblasTrans, m, n, k, alpha, user_ptr,\n              k, item_ptr, k, beta, matrix_product, n);\n\n  if (K == 1) {\n    computeTopRating(matrix_product, top_K_items, m, n);\n  } else {\n    computeTopK(matrix_product, top_K_items, m, n, K);\n  }\n  tt.stop();\n  free(matrix_product);\n  free(top_K_items);\n  return (tt.elapsedTime().nanos() / 1E9) / num_users_per_block;\n}\n\n\nint main(int argc, char *argv[]) {\n    double theta, R, epsilon, user_sample_ratio;\n    string usersFile;\n    string itemsFile;\n    string logFile, resultsFile;\n\n    bool querySideLeft = true;\n    bool isTARR = true;\n    int k, cacheSizeinKB, threads, r, m, n;\n    std::string methodStr;\n    LEMP_Method method;\n\n    // read command line\n    options_description desc(\"Options\");\n    desc.add_options()\n            (\"help\", \"produce help message\")\n            (\"Q^T\", value<string>(&usersFile), \"file containing the query matrix (left side)\")\n            (\"P\", value<string>(&itemsFile), \"file containing the probe matrix (right side)\")\n            (\"theta\", value<double>(&theta), \"theta value\")\n            (\"R\", value<double>(&R)->default_value(0.97), \"recall parameter for LSH\")\n            (\"x\", value<double>(&user_sample_ratio)->default_value(0.0), \"user sample ratio\")\n\t    (\"epsilon\", value<double>(&epsilon)->default_value(0.0), \"epsilon value for LEMP-LI with Absolute or Relative Approximation\")\n            (\"querySideLeft\", value<bool>(&querySideLeft)->default_value(true), \"1 if Q^T contains the queries (default). Interesting for Row-Top-k\")\n            (\"isTARR\", value<bool>(&isTARR)->default_value(true), \"for LEMP-TA. If 1 Round Robin schedule is used (default). Otherwise Max PiQi\")\n            (\"method\", value<string>(&methodStr), \"LEMP_X where X: L, LI, LC, I, C, TA, TREE, AP, LSH\")\n            (\"k\", value<int>(&k)->default_value(0), \"top k (default 0). If 0 Above-theta will run\")\n            (\"logFile\", value<string>(&logFile)->default_value(\"\"), \"output File (contains runtime information)\")\n\t    (\"resultsFile\", value<string>(&resultsFile)->default_value(\"\"), \"output File (contains the results)\")\n            (\"cacheSizeinKB\", value<int>(&cacheSizeinKB)->default_value(8192), \"cache size in KB\")\n            (\"t\", value<int>(&threads)->default_value(1), \"num of threads (default 1)\")\n            (\"r\", value<int>(&r)->default_value(0), \"num of coordinates in each vector (needed when reading from csv files)\")\n            (\"m\", value<int>(&m)->default_value(0), \"num of vectors in Q^T (needed when reading from csv files)\")\n            (\"n\", value<int>(&n)->default_value(0), \"num of vectors in P (needed when reading from csv files)\")\n            ;\n\n    positional_options_description pdesc;\n    pdesc.add(\"Q^T\", 1);\n    pdesc.add(\"P\", 2);\n\n    variables_map vm;\n    store(command_line_parser(argc, argv).options(desc).positional(pdesc).run(), vm);\n    notify(vm);\n\n    if (vm.count(\"help\") || vm.count(\"Q^T\") == 0 || vm.count(\"P\") == 0) {\n        cout << \"runLemp [options] <Q^T> <P>\" << endl << endl;\n        cout << desc << endl;\n        return 1;\n    }\n        \n    InputArguments args;\n    args.logFile = logFile;\n    args.theta = theta;\n    args.k = k;\n    args.threads = threads;\n\n    if (methodStr.compare(\"LEMP_LI\") == 0) {\n        method = LEMP_LI;\n    } else if (methodStr.compare(\"LEMP_LC\") == 0) {\n        method = LEMP_LC;\n    } else if (methodStr.compare(\"LEMP_L\") == 0) {\n        method = LEMP_L;\n    } else if (methodStr.compare(\"LEMP_I\") == 0) {\n        method = LEMP_I;\n    } else if (methodStr.compare(\"LEMP_C\") == 0) {\n        method = LEMP_C;\n    } else if (methodStr.compare(\"LEMP_TA\") == 0) {\n        method = LEMP_TA;\n    } else if (methodStr.compare(\"LEMP_TREE\") == 0) {\n        method = LEMP_TREE;\n    } else if (methodStr.compare(\"LEMP_AP\") == 0) {\n        method = LEMP_AP;\n    } else if (methodStr.compare(\"LEMP_LSH\") == 0) {\n        method = LEMP_LSH;\n    } else if (methodStr.compare(\"LEMP_BLSH\") == 0) {\n        method = LEMP_BLSH;\n    } \n    else {\n        cout << \"[ERROR] This method is not possible. Please try {LEMP_L, LEMP_LI, LEMP_LC, LEMP_I, LEMP_C, LEMP_TA, LEMP_TREE, LEMP_AP, LEMP_LSH, LEMP_BLSH}\" << endl << endl;\n        cout << desc << endl;\n        return 1;\n    }\n\n    VectorMatrix leftMatrix, rightMatrix;\n\n    if (querySideLeft) {\n        leftMatrix.readFromFile(usersFile, r, m, true);\n        rightMatrix.readFromFile(itemsFile, r, n, false);\n    } else {\n        leftMatrix.readFromFile(itemsFile, r, n, false);\n        rightMatrix.readFromFile(usersFile, r, m, true);\n    }\n\n    mips::Lemp algo(args, cacheSizeinKB, method, isTARR, R, epsilon);\n    \n    algo.initialize(rightMatrix);\n\n    Results results;\n    if (args.k > 0) {\n#ifdef ONLINE_DECISION_RULE\n    std::random_device rd; // only used once to initialise (seed) engine\n    std::mt19937 rng(\n        rd()); // random-number engine used (Mersenne-Twister in this case)\n    unsigned long num_users_per_block = 0;\n    if (user_sample_ratio == 0.0) {\n      // Default\n      num_users_per_block =\n          4 * L2_CACHE_SIZE / (sizeof(double) * leftMatrix.colNum);\n      while (num_users_per_block * rightMatrix.rowNum * sizeof(double) > MAX_MEM_SIZE) {\n        num_users_per_block /= 2;\n      }\n    } else {\n      num_users_per_block = (long)(user_sample_ratio * leftMatrix.rowNum);\n    }\n    std::uniform_int_distribution<int> uni(\n        0, leftMatrix.rowNum - num_users_per_block); // guaranteed unbiased\n    const unsigned int rand_ind = uni(rng);\n\n    const double blocked_mm_time =\n        decisionRuleBlockedMM(leftMatrix, rightMatrix, rand_ind, num_users_per_block, args.k);\n\n    double *sample_ptr = leftMatrix.getMatrixRowPtr(rand_ind);\n    double *new_ptr = (double *)malloc(num_users_per_block * leftMatrix.colNum * sizeof(double));\n    std::memcpy(new_ptr, sample_ptr, num_users_per_block * leftMatrix.colNum * sizeof(double));\n\n\n    VectorMatrix sampleLeftMatrix(new_ptr, leftMatrix.colNum, num_users_per_block);\n    \n    rg::Timer tt;\n    tt.start();\n    // sample using rand_ind and num_users_per_block\n    algo.runTopK(sampleLeftMatrix, results);\n    tt.stop();\n\n    const double lemp_time = (tt.elapsedTime().nanos() / 1E9) / num_users_per_block;\n\n    algo.addSampleStats(user_sample_ratio, blocked_mm_time, lemp_time);\n    cout << \"Blocked MM time: \" << blocked_mm_time << \"s\" << endl;\n    cout << \"LEMP time: \" << lemp_time << \"s\" << endl;\n    if (blocked_mm_time < lemp_time) {\n      cout << \"Blocked MM wins\" << endl;\n    } else {\n      cout << \"LEMP wins\" << endl;\n#ifndef TEST_ONLY\n      // TODO: run it on everything else [0-rand_ind), [rand_ind +\n      // num_users_per_block, num_users) and output results\n\n      algo.runTopK(leftMatrix, results);\n#endif\n    }\n    algo.outputStats();\n#else\n      algo.runTopK(leftMatrix, results);\n      algo.outputStats();\n#endif\n    } else {\n        algo.runAboveTheta(leftMatrix, results);\n        algo.outputStats();\n    }\n    \n    if (resultsFile != \"\") {\n        results.writeToFile(resultsFile);\n    }\n\n    return 0;\n}\n\n\n", "meta": {"hexsha": "dc7a88579941f434204eb974e6cd48394d7f79d7", "size": 9963, "ext": "cc", "lang": "C++", "max_stars_repo_path": "tools/runLemp.cc", "max_stars_repo_name": "stanford-futuredata/LEMP-benchmarking", "max_stars_repo_head_hexsha": "0279528b427aa4fae59e4d3598b1f098fcb4cf4b", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-07-06T20:49:51.000Z", "max_stars_repo_stars_event_max_datetime": "2020-07-06T20:49:51.000Z", "max_issues_repo_path": "tools/runLemp.cc", "max_issues_repo_name": "d3v3l0/LEMP-benchmarking", "max_issues_repo_head_hexsha": "0279528b427aa4fae59e4d3598b1f098fcb4cf4b", "max_issues_repo_licenses": ["Apache-2.0"], "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/runLemp.cc", "max_forks_repo_name": "d3v3l0/LEMP-benchmarking", "max_forks_repo_head_hexsha": "0279528b427aa4fae59e4d3598b1f098fcb4cf4b", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-07-06T20:49:52.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-06T20:49:52.000Z", "avg_line_length": 35.8381294964, "max_line_length": 175, "alphanum_fraction": 0.6235069758, "num_tokens": 2676, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6187804478040616, "lm_q2_score": 0.5506073655352403, "lm_q1q2_score": 0.3407050722101106}}
{"text": "#include <cassert>\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 \"../Calculations/Integrations.h\"\n#include \"GreensTensorVacuum.h\"\n\nGreensTensorVacuum::GreensTensorVacuum(double v, double beta, double relerr)\n    : GreensTensor(v, beta), relerr(relerr) {\n    assert(relerr >= 0);\n    }\n\nGreensTensorVacuum::GreensTensorVacuum(const std::string& input_file)\n    : GreensTensor(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  // Load relative accuracy\n  this->relerr = root.get<double>(\"GreensTensor.rel_err_1\");\n\n  assert(relerr >= 0);\n\n  // check if type is right\n  std::string type = root.get<std::string>(\"GreensTensor.type\");\n  assert(type == \"vacuum\");\n}\n\n// Compute the full Green's tensor for a given frequency \\omega and a given\n// momentum vector k For the definition see notes/VacuumGreen.pdf eq. (2)\nvoid GreensTensorVacuum::calculate_tensor(double omega, vec::fixed<2> k,\n                                          cx_mat::fixed<3, 3> &GT) const {\n  // Read out the k-vector and the frequency \\omega\n  double k_x = k(0);\n  double k_y = k(1);\n\n  // Define useful variables\n  double k_quad = k_x * k_x + k_y * k_y;\n  double omega_quad = omega * omega;\n\n  // Reset tensor in which the final result is stored\n  GT.zeros();\n\n  // Ensure that heavyside function is fulfilled\n  if (omega_quad - k_quad > 0) {\n    // Compute the diagonal components of the tensor. The off-diagonal\n    // elements are all zero\n    double pre = 1.0 / (2 * M_PI * sqrt(omega_quad - k_quad));\n    GT(0, 0) = pre * (omega_quad - k_x * k_x);\n    GT(1, 1) = pre * (omega_quad - k_y * k_y);\n    GT(2, 2) = pre * k_quad;\n  }\n}\n\n// Compute the integration with respect to the 2-d k vector\n// Ref: notes/VacuumFriction.pdf eq. (10)\nvoid GreensTensorVacuum::integrate_k(double omega, cx_mat::fixed<3, 3> &GT,\n                                     Tensor_Options fancy_complex,\n                                     Weight_Options weight_function) const {\n  if (fancy_complex == RE) {\n    // Even though the real part of the Green's tensor is not implemented, a\n    // default return value of an empty tensor was chosen, to allow for the\n    // general structure of the polarizability to depend both on the real and\n    // imaginary part of a given Green's tensor\n    GT.zeros();\n  } else if (fancy_complex == IM) {\n\n    // Reset the tensor to store the final result\n    GT.zeros();\n    // Ensure that the integration limits are properly ordered\n    if (omega >= 0) {\n\n      // Numerically integrate the xx component\n      auto F_xx = [=](double x) -> double {\n        return this->integrand_k(x, omega, {0, 0}, fancy_complex,\n                                 weight_function);\n      };\n      GT(0, 0) = cquad(F_xx, -omega / (1.0 + this->v), omega / (1.0 - this->v),\n                       this->relerr, 0);\n\n      // yy component\n      auto F_yy = [=](double x) -> double {\n        return this->integrand_k(x, omega, {1, 1}, fancy_complex,\n                                 weight_function);\n      };\n      GT(1, 1) = cquad(F_yy, -omega / (1.0 + this->v), omega / (1.0 - this->v),\n                       this->relerr, 0);\n\n      // zz component\n      GT(2, 2) = GT(1, 1);\n    }\n    // Switching the integration bounds for negative frequencies\n    if (omega < 0) {\n\n      // Numerically integrate the xx component\n      auto F_xx = [=](double x) -> double {\n        return this->integrand_k(x, omega, {0, 0}, fancy_complex,\n                                 weight_function);\n      };\n      GT(0, 0) = -cquad(F_xx, omega / (1.0 - this->v), -omega / (1.0 + this->v),\n                        this->relerr, 0);\n\n      // yy component\n      auto F_yy = [=](double x) -> double {\n        return this->integrand_k(x, omega, {1, 1}, fancy_complex,\n                                 weight_function);\n      };\n      GT(1, 1) = -cquad(F_yy, omega / (1.0 - this->v), -omega / (1.0 + this->v),\n                        this->relerr, 0);\n\n      // zz component\n      GT(2, 2) = GT(1, 1);\n    }\n  }\n}\n\n// Implementation of the different integrands for the integration\n// of the 2-d k-vector\n// Ref: notes/VacuumFriction eq. (10) and (11)\ndouble GreensTensorVacuum::integrand_k(double kv, double omega,\n                                       const uvec::fixed<2> &indices,\n                                       Tensor_Options fancy_complex,\n                                       Weight_Options weight_function) const {\n  double omega_pl = (omega + kv * v);\n  double omega_pl_quad = omega_pl * omega_pl;\n  double xi_quad = omega_pl_quad - kv * kv;\n\n  // Variable to store the final result\n  double result = 0;\n\n  // Only the imaginary part is implemented\n  if (fancy_complex == IM) {\n    // Compute the basis integrand of eq. (10)\n    if (indices(0) == 0 && indices(1) == 0) {\n      result = 0.5 * xi_quad;\n    } else if (indices(0) == indices(1)) {\n      result = 0.5 * (omega_pl_quad - xi_quad * 0.5);\n    } else {\n      return 0;\n    }\n\n    // Multply with the additional weight function f, the options can be found\n    // in eq. (11)\n    if (weight_function == KV) {\n      result *= kv;\n    } else if (weight_function == TEMP) {\n      result /= (1.0 - exp(-beta * omega_pl));\n    } else if (weight_function == KV_TEMP) {\n      result *= kv / (1.0 - exp(-beta * omega_pl));\n    } else if (weight_function == NON_LTE) {\n      result *=\n          (1. / (1. - exp(-beta * omega_pl)) - 1. / (1. - exp(-beta * omega)));\n    } else if (weight_function == KV_NON_LTE) {\n      result *= kv * (1. / (1. - exp(-beta * omega_pl)) -\n                      1. / (1. - exp(-beta * omega)));\n    }\n  }\n\n  return result;\n}\n\ndouble GreensTensorVacuum::omega_ch() const { return 0; }\n\nvoid GreensTensorVacuum::print_info(std::ostream &stream) const {\n  stream << \"# GreensTensorPlateVacuum\\n#\\n\"\n         << \"# v = \" << v << \"\\n\"\n         << \"# beta = \" << beta << \"\\n\"\n         << \"# relerr = \" << relerr << \"\\n\";\n}\n", "meta": {"hexsha": "33aa15d6a62f55b685fb8712af19c905d55d58a4", "size": 6040, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/GreensTensor/GreensTensorVacuum.cpp", "max_stars_repo_name": "QuaCaTeam/quaca", "max_stars_repo_head_hexsha": "ab2d213f3e0e357bd72930ae1e4e703184130270", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-05-19T09:01:40.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-20T07:57:54.000Z", "max_issues_repo_path": "src/GreensTensor/GreensTensorVacuum.cpp", "max_issues_repo_name": "myoelmy/quaca", "max_issues_repo_head_hexsha": "def47981b710a73f2fb3a7c14c354f8de91cf88f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 31.0, "max_issues_repo_issues_event_min_datetime": "2020-05-19T08:01:46.000Z", "max_issues_repo_issues_event_max_datetime": "2020-05-28T07:33:35.000Z", "max_forks_repo_path": "src/GreensTensor/GreensTensorVacuum.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": 34.3181818182, "max_line_length": 80, "alphanum_fraction": 0.5731788079, "num_tokens": 1673, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6187804337438501, "lm_q2_score": 0.5506073655352404, "lm_q1q2_score": 0.3407050644684546}}
{"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 \"truth_table_utils.hpp\"\n\n#include <deque>\n#include <iostream>\n\n#include <boost/pending/integer_log2.hpp>\n\n#include <core/utils/conversion_utils.hpp>\n#include <core/utils/string_utils.hpp>\n\nnamespace cirkit\n{\n\n/******************************************************************************\n * Truth table store                                                          *\n ******************************************************************************/\n\ntt_store& tt_store::i()\n{\n  static tt_store instance;\n  return instance;\n}\n\ntt_store::tt_store()\n{\n  assert( sizeof( unsigned long ) == 8 );\n}\n\n/******************************************************************************\n * Public functions                                                           *\n ******************************************************************************/\n\ntt tt_const0()\n{\n  return boost::dynamic_bitset<>( 64u, 0u );\n}\n\ntt tt_const1()\n{\n  return ~tt_const0();\n}\n\ntt tt_nth_var( unsigned i )\n{\n  if ( i < 6u )\n  {\n    return tt_store::i()( i );\n  }\n  else\n  {\n    tt t( 1u << i, 0ul );\n    t.resize( 1u << ( i + 1 ), true );\n    return t;\n  }\n}\n\nunsigned tt_num_vars( const tt& t )\n{\n  return boost::integer_log2( t.size() );\n}\n\nvoid tt_extend( tt& t, unsigned to )\n{\n  unsigned nv = tt_num_vars( t );\n  tt::size_type s, i;\n\n  while ( nv < to )\n  {\n    s = t.size();\n    t.resize( s << 1u );\n    for ( i = 0u; i < s; ++i )\n    {\n      t[s + i] = t[i];\n    }\n    ++nv;\n  }\n}\n\nvoid tt_shrink( tt& t, unsigned to )\n{\n  t.resize( 1u << to );\n}\n\nvoid tt_align( tt& t1, tt& t2 )\n{\n  unsigned nv1 = tt_num_vars( t1 ), nv2 = tt_num_vars( t2 );\n  if ( nv1 < nv2 )\n  {\n    tt_extend( t1, nv2 );\n  }\n  else if ( nv2 < nv1 )\n  {\n    tt_extend( t2, nv1 );\n  }\n}\n\nbool tt_has_var( const tt& t, unsigned i )\n{\n  auto n = tt_num_vars( t );\n\n  if ( i >= n ) { return false; }\n\n  auto tc = t;\n  if ( n < tt_store::i().width ) { tt_extend( tc, tt_store::i().width ); }\n\n  auto tv = ~tt_nth_var( i );\n  tt_extend( tv, n );\n\n  return ( (tc >> (1 << i)) & tv )  != ( tc & tv );\n}\n\nboost::dynamic_bitset<> tt_support( const tt& t )\n{\n  unsigned n = tt_num_vars( t );\n\n  boost::dynamic_bitset<> support( n );\n  for ( unsigned i = 0u; i < n; ++i )\n  {\n    support.set( i, tt_has_var( t, i ) );\n  }\n\n  return support;\n}\n\nunsigned tt_support_size( const tt& t )\n{\n  return tt_support( t ).count();\n}\n\ntt tt_cof0( const tt& t, unsigned i )\n{\n  auto n = tt_num_vars( t );\n  assert( i < n );\n  auto tv = ~tt_nth_var( i );\n  tt_extend( tv, n );\n\n  auto tc = t;\n  if ( n < tt_store::i().width ) { tt_extend( tc, tt_store::i().width ); }\n\n  return (tc & tv) | ((tc & tv) << (1 << i));\n}\n\ntt tt_cof1( const tt& t, unsigned i )\n{\n  auto n = tt_num_vars( t );\n  assert( i < n );\n  auto tv = tt_nth_var( i );\n  tt_extend( tv, n );\n\n  auto tc = t;\n  if ( n < tt_store::i().width ) { tt_extend( tc, tt_store::i().width ); }\n\n  return (tc & tv) | ((tc & tv) >> (1 << i));\n}\n\nbool tt_cof0_is_const0( const tt& t, unsigned i )\n{\n  auto n = tt_num_vars( t );\n  assert( i < n );\n  auto tv = ~tt_nth_var( i );\n  tt_extend( tv, n );\n\n  auto tc = t;\n  if ( n < tt_store::i().width ) { tt_extend( tc, tt_store::i().width ); }\n\n  return ( tc & tv ).empty();\n}\n\nbool tt_cof0_is_const1( const tt& t, unsigned i )\n{\n  auto n = tt_num_vars( t );\n  assert( i < n );\n  auto tv = ~tt_nth_var( i );\n  tt_extend( tv, n );\n\n  auto tc = t;\n  if ( n < tt_store::i().width ) { tt_extend( tc, tt_store::i().width ); }\n\n  return ( tc & tv ) == tv;\n}\n\nbool tt_cof1_is_const0( const tt& t, unsigned i )\n{\n  auto n = tt_num_vars( t );\n  assert( i < n );\n  auto tv = tt_nth_var( i );\n  tt_extend( tv, n );\n\n  auto tc = t;\n  if ( n < tt_store::i().width ) { tt_extend( tc, tt_store::i().width ); }\n\n  return ( tc & tv ).empty();\n}\n\nbool tt_cof1_is_const1( const tt& t, unsigned i )\n{\n  auto n = tt_num_vars( t );\n  assert( i < n );\n  auto tv = tt_nth_var( i );\n  tt_extend( tv, n );\n\n  auto tc = t;\n  if ( n < tt_store::i().width ) { tt_extend( tc, tt_store::i().width ); }\n\n  return ( tc & tv ) == tv;\n}\n\nbool tt_cofs_opposite( const tt& t, unsigned i )\n{\n  auto n = tt_num_vars( t );\n  assert( i < n );\n  auto tv = tt_nth_var( i );\n  tt_extend( tv, n );\n\n  auto tc = t;\n  if ( n < tt_store::i().width ) { tt_extend( tc, tt_store::i().width ); }\n\n  unsigned shift = ( 1u << i );\n  return ((tc << shift) & tv) == (~tc & tv);\n}\n\nvoid tt_resize( tt& t, unsigned size )\n{\n  auto num_vars = tt_num_vars( t );\n  if ( num_vars == size ) return;\n  else if ( num_vars < size )\n  {\n    tt_extend( t, size );\n  }\n  else\n  {\n    tt_shrink( t, size );\n  }\n}\n\nbool tt_is_const0( const tt& t )\n{\n  tt t0 = tt_const0();\n  tt_resize( t0, tt_num_vars( t ) );\n  return t0 == t;\n}\n\nbool tt_is_const1( const tt& t )\n{\n  tt t1 = tt_const1();\n  tt_resize( t1, tt_num_vars( t ) );\n  return t1 == t;\n}\n\ntt tt_exists( const tt& t, unsigned i )\n{\n  return tt_cof0( t, i ) | tt_cof1( t, i );\n}\n\ntt tt_forall( const tt& t, unsigned i )\n{\n  return tt_cof0( t, i ) & tt_cof1( t, i );\n}\n\ntt tt_permute( const tt& t, unsigned i, unsigned j )\n{\n  if ( i == j ) return t;\n\n  unsigned n = tt_num_vars( t );\n  assert( i < n );\n  assert( j < n );\n\n  tt vi = tt_nth_var( i );\n  tt vj = tt_nth_var( j );\n  tt_extend( vi, n );\n  tt_extend( vj, n );\n\n  tt c0 = tt_cof0( t, i );\n  tt c1 = tt_cof1( t, i );\n  tt c00 = tt_cof0( c0, j );\n  tt c01 = tt_cof1( c0, j );\n  tt c10 = tt_cof0( c1, j );\n  tt c11 = tt_cof1( c1, j );\n\n  auto tt_new = ( ~vi & ( ( ~vj & c00 ) | ( vj & c10 ) ) ) | ( vi & ( ( ~vj & c01 ) | ( vj & c11 ) ) );\n\n  if ( n < 6u )\n  {\n    tt_shrink( tt_new, n );\n  }\n\n  return tt_new;\n}\n\ntt tt_remove_var( const tt& t, unsigned i )\n{\n  unsigned n = tt_num_vars( t );\n  assert( n > 0u );\n  tt ret = t;\n\n  for ( unsigned j = i; j < n - 1u; ++j )\n  {\n    ret = tt_permute( ret, j, j + 1u );\n  }\n\n  ret.resize( (tt::size_type)1 << ( n - 1 ) );\n  return ret;\n}\n\ntt tt_flip( const tt& t, unsigned i )\n{\n  auto n = tt_num_vars( t );\n  assert( i < n );\n\n  auto vi = tt_nth_var( i );\n  tt_extend( vi, n );\n\n  auto tc = t;\n  if ( n < tt_store::i().width ) { tt_shrink( vi, n ); }\n\n  return ((tc << (1 << i)) & vi) | ((tc & vi) >> (1 << i));\n}\n\nvoid tt_to_minbase( tt& t, boost::dynamic_bitset<>* psupport )\n{\n  auto support = tt_support( t );\n\n  if ( psupport ) *psupport = support;\n\n  auto to_pos = 0u;\n  auto pos = support.find_first();\n\n  while ( pos != boost::dynamic_bitset<>::npos )\n  {\n    t = tt_permute( t, pos, to_pos++ );\n    pos = support.find_next( pos );\n  }\n\n  /* resize */\n  t.resize( 1 << support.count() );\n}\n\nvoid tt_to_minbase_and_discard( tt& t, unsigned max_size, boost::dynamic_bitset<>* psupport )\n{\n  boost::dynamic_bitset<> support = tt_support( t );\n\n  if ( psupport ) *psupport = support;\n\n  unsigned to_pos = 0u;\n  boost::dynamic_bitset<>::size_type pos = support.find_first();\n\n  while ( pos != boost::dynamic_bitset<>::npos )\n  {\n    if ( to_pos < max_size )\n    {\n      t = tt_permute( t, pos, to_pos++ );\n    }\n    else\n    {\n      t = tt_exists( t, pos );\n    }\n    pos = support.find_next( pos );\n  }\n\n  /* resize */\n  t.resize( 1 << std::min( to_pos, max_size ) );\n}\n\nvoid tt_from_minbase( tt& t, const boost::dynamic_bitset<> pattern )\n{\n  std::deque<unsigned> positions;\n\n  tt_extend( t, pattern.size() );\n\n  boost::dynamic_bitset<>::size_type pos = pattern.find_first();\n  while ( pos != boost::dynamic_bitset<>::npos )\n  {\n    positions.push_front( pos );\n    pos = pattern.find_next( pos );\n  }\n\n  unsigned support_size = tt_support_size( t );\n  assert( positions.size() == support_size );\n\n  unsigned tpos = support_size - 1u;\n  for ( const auto& pos : positions )\n  {\n    assert( pos >= tpos );\n    t = tt_permute( t, tpos--, pos );\n  }\n}\n\nstd::string tt_to_hex( const tt& t )\n{\n  std::string s;\n  to_string( t, s );\n\n  std::string result;\n  for ( unsigned i = 0u; i < s.length(); i += 4u )\n  {\n    result += convert_bin2hex( s.substr( i, 4u ) );\n  }\n  return result;\n}\n\ntt tt_from_hex( const std::string& s )\n{\n  const auto bin = convert_hex2bin( s );\n  auto t = tt( bin.size(), 0u );\n  for ( auto i = 0u; i < bin.size(); ++i )\n  {\n    assert( bin[i] == '0' || bin[i] == '1' );\n    t[ t.size() - i - 1 ] = ( bin[i] == '1' );\n  }\n  return t;\n}\n\ntt tt_from_hex( const std::string& s, unsigned to )\n{\n  auto t = tt_from_hex( s );\n  const auto num_vars = tt_num_vars( t );\n  if ( num_vars < to )\n  {\n    tt_extend( t, to );\n  }\n  else if ( num_vars > to )\n  {\n    tt_shrink( t, to );\n  }\n  return t;\n}\n\n/******************************************************************************\n * truth table from expression                                                *\n ******************************************************************************/\n\nstd::pair<tt, unsigned> tt_expression_evaluator::on_const( bool value ) const\n{\n  return {value ? tt_const1() : tt_const0(), 0u};\n}\n\nstd::pair<tt, unsigned> tt_expression_evaluator::on_var( unsigned index ) const\n{\n  return {tt_nth_var( index ), index + 1u};\n}\n\nstd::pair<tt, unsigned> tt_expression_evaluator::on_inv( const std::pair<tt, unsigned>& value ) const\n{\n  return {~( value.first ), value.second};\n}\n\nstd::pair<tt, unsigned> tt_expression_evaluator::on_and( const std::pair<tt, unsigned>& value1, const std::pair<tt, unsigned>& value2 ) const\n{\n  auto _v1 = value1.first;\n  auto _v2 = value2.first;\n  tt_align( _v1, _v2 );\n  return {_v1 & _v2, std::max( value1.second, value2.second )};\n}\n\nstd::pair<tt, unsigned> tt_expression_evaluator::on_or( const std::pair<tt, unsigned>& value1, const std::pair<tt, unsigned>& value2 ) const\n{\n  auto _v1 = value1.first;\n  auto _v2 = value2.first;\n  tt_align( _v1, _v2 );\n  return {_v1 | _v2, std::max( value1.second, value2.second )};\n}\n\nstd::pair<tt, unsigned> tt_expression_evaluator::on_maj( const std::pair<tt, unsigned>& value1, const std::pair<tt, unsigned>& value2, const std::pair<tt, unsigned>& value3 ) const\n{\n  auto _v1 = value1.first;\n  auto _v2 = value2.first;\n  auto _v3 = value3.first;\n  tt_align( _v1, _v2 );\n  tt_align( _v2, _v3 );\n  tt_align( _v1, _v3 );\n  return {( _v1 & _v2 ) | ( _v1 & _v3 ) | ( _v2 & _v3 ), std::max( value1.second, std::max( value2.second, value3.second ) )};\n}\n\nstd::pair<tt, unsigned> tt_expression_evaluator::on_xor( const std::pair<tt, unsigned>& value1, const std::pair<tt, unsigned>& value2 ) const\n{\n  auto _v1 = value1.first;\n  auto _v2 = value2.first;\n  tt_align( _v1, _v2 );\n  return {_v1 ^ _v2, std::max( value1.second, value2.second )};\n}\n\ntt tt_from_expression( const expression_t::ptr& expr )\n{\n  const auto v = evaluate_expression( expr, tt_expression_evaluator() );\n  auto t = v.first;\n  tt_shrink( t, v.second );\n  return t;\n}\n\ntt tt_from_sop_spec( const std::string& spec )\n{\n  enum class pla_type_t { none, on, off };\n  auto pla_type = pla_type_t::none;\n  tt f( 1u );\n  \n  foreach_string( spec, \"\\n\", [&f, &pla_type]( const std::string& line ) {\n      const auto pair = split_string_pair( line, \" \" );\n      const auto p = pair.first;\n\n      switch ( pla_type )\n      {\n      case pla_type_t::none:\n        pla_type = ( pair.second == \"1\" ) ? pla_type_t::on : pla_type_t::off;\n        f = tt( 1u << p.size() );\n        if ( pla_type == pla_type_t::off )\n        {\n          f.flip();\n        }\n        break;\n      case pla_type_t::on:   assert( pair.second == \"1\" ); break;\n      case pla_type_t::off:  assert( pair.second == \"0\" ); break;\n      }\n\n      auto cube = ( pla_type == pla_type_t::on ) ? ~tt( 1 << p.size() ) : tt( 1 << p.size() );\n      for ( auto i = 0u; i < p.size(); ++i )\n      {\n        if ( p[i] == '-' ) continue;\n        auto v = ( p[i] == '0' ) != ( pla_type == pla_type_t::off ) ? ~tt_nth_var( i ) : tt_nth_var( i );\n        if ( p.size() < 6 )\n        {\n          tt_shrink( v, p.size() );\n        }\n        else\n        {\n          tt_align( v, cube );\n        }\n        \n        if ( pla_type == pla_type_t::on )\n        {\n          cube &= v;\n        }\n        else\n        {\n          cube |= v;\n        }\n      }\n\n      if ( pla_type == pla_type_t::on )\n      {\n        f |= cube;\n      }\n      else\n      {\n        f &= cube;\n      }\n    } );\n\n  return f;\n}\n\nstd::vector<int> walsh_spectrum( const tt& func )\n{\n  const auto n = tt_num_vars( func );\n\n  std::vector<int> spectra( func.size(), 0u );\n  foreach_bit( func, [&spectra]( unsigned pos ) { spectra[pos] = 1u; } );\n\n  /* butterfly loops */\n  for ( auto i = 0u; i < n; ++i )\n  {\n    auto i1 = 0u;\n\n    const unsigned d = ( 1 << ( n - 1 - i ) );\n    /* blocks? */\n    for ( auto b = 0u; b < ( 1u << i ); ++b, i1 += d )\n    {\n      /* block elements */\n      for ( auto e = 0u; e < d; ++e, ++i1 )\n      {\n        const auto i2 = i1 + d;\n\n        const auto v1 = spectra[i1] + spectra[i2];\n        const auto v2 = spectra[i1] - spectra[i2];\n        spectra[i1] = v1;\n        spectra[i2] = v2;\n      }\n    }\n  }\n\n  return spectra;\n}\n\ntt tt_maj(tt a, tt b, tt c)\n{\n  return (a & b) | (b & c) | (a & c);\n}\n\nkitty::dynamic_truth_table to_kitty( const tt& tt )\n{\n  kitty::dynamic_truth_table ret( tt_num_vars( tt ) );\n  boost::to_block_range( tt, ret.begin() );\n  return ret;\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": "67aeb5664a07a50c1e9cdcef296c2855b04af4b8", "size": 14371, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/classical/utils/truth_table_utils.cpp", "max_stars_repo_name": "eletesta/cirkit", "max_stars_repo_head_hexsha": "6d0939798ea25cecf92306ce796be154139b94f5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/classical/utils/truth_table_utils.cpp", "max_issues_repo_name": "eletesta/cirkit", "max_issues_repo_head_hexsha": "6d0939798ea25cecf92306ce796be154139b94f5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/classical/utils/truth_table_utils.cpp", "max_forks_repo_name": "eletesta/cirkit", "max_forks_repo_head_hexsha": "6d0939798ea25cecf92306ce796be154139b94f5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.8837579618, "max_line_length": 180, "alphanum_fraction": 0.5505531974, "num_tokens": 4485, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6187804196836383, "lm_q2_score": 0.5506073655352404, "lm_q1q2_score": 0.34070505672679846}}
{"text": "// -----------------------------------------------------------------------\n// RTToolbox - DKFZ radiotherapy quantitative evaluation library\n//\n// Copyright (c) German Cancer Research Center (DKFZ),\n// Software development for Integrated Diagnostics and Therapy (SIDT).\n// ALL RIGHTS RESERVED.\n// See rttbCopyright.txt or\n// http://www.dkfz.de/en/sidt/projects/rttb/copyright.html\n//\n// This software is distributed WITHOUT ANY WARRANTY; without even\n// the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n// PURPOSE.  See the above copyright notices for more information.\n//\n//------------------------------------------------------------------------\n\n#include \"rttbBoostMaskVoxelizationThread.h\"\n\n#include \"rttbInvalidParameterException.h\"\n\n#include <boost/geometry.hpp>\n#include <boost/make_shared.hpp>\n\nnamespace rttb\n{\n\tnamespace masks\n\t{\n\t\tnamespace boost\n\t\t{\n\t\t\tBoostMaskVoxelizationThread::BoostMaskVoxelizationThread(const BoostPolygonMap& APolygonMap,\n                const VoxelIndexVector& aGlobalBoundingBox, BoostArrayMapPointer anArrayMap, ::boost::shared_ptr<std::mutex> aMutex, bool strict) : _geometryCoordinateBoostPolygonMap(APolygonMap),\n                _globalBoundingBox(aGlobalBoundingBox), _resultVoxelization(anArrayMap), _mutex(aMutex), _strict(strict)\n\t\t\t{\n\t\t\t}\n\n\t\t\tvoid BoostMaskVoxelizationThread::operator()()\n\t\t\t{\n\t\t\t\trttb::VoxelGridIndex3D minIndex = _globalBoundingBox.at(0);\n\t\t\t\trttb::VoxelGridIndex3D maxIndex = _globalBoundingBox.at(1);\n\t\t\t\tconst unsigned int globalBoundingBoxSize0 = maxIndex[0] - minIndex[0] + 1;\n\t\t\t\tconst unsigned int globalBoundingBoxSize1 = maxIndex[1] - minIndex[1] + 1;\n\n                std::map<double, ::boost::shared_ptr<BoostArray2D> > voxelizationMapInThread;\n\n                 for (auto & it : _geometryCoordinateBoostPolygonMap)\n\t\t\t\t{\n                    BoostArray2D maskArray(::boost::extents[globalBoundingBoxSize0][globalBoundingBoxSize1]);\n\n\t\t\t\t\tBoostPolygonVector boostPolygonVec = it.second;\n\n\t\t\t\t\tfor (unsigned int x = 0; x < globalBoundingBoxSize0; ++x)\n\t\t\t\t\t{\n\t\t\t\t\t\tfor (unsigned int y = 0; y < globalBoundingBoxSize1; ++y)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\trttb::VoxelGridIndex3D currentIndex;\n\t\t\t\t\t\t\tcurrentIndex[0] = x + minIndex[0];\n\t\t\t\t\t\t\tcurrentIndex[1] = y + minIndex[1];\n\t\t\t\t\t\t\tcurrentIndex[2] = 0;\n\n\t\t\t\t\t\t\t//Get intersection polygons of the dose voxel and the structure\n\t\t\t\t\t\t\tBoostPolygonDeque polygons = getIntersections(currentIndex, boostPolygonVec);\n\n\t\t\t\t\t\t\t//Calc areas of all intersection polygons\n\t\t\t\t\t\t\tdouble volumeFraction = calcArea(polygons);\n                            volumeFraction = correctForErrorAndStrictness(volumeFraction, _strict);\n                            if (volumeFraction < 0 || volumeFraction > 1 )\n                            {\n                                throw rttb::core::InvalidParameterException(\"Mask calculation failed! The volume fraction should >= 0 and <= 1!\");\n                            }\n\n\t\t\t\t\t\t\tmaskArray[x][y] = volumeFraction;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n                    voxelizationMapInThread.insert(std::pair<double, BoostArray2DPointer>(it.first, ::boost::make_shared<BoostArray2D>(maskArray)));\n\t\t\t\t}\n                //insert gathered values into voxelization map\n                std::unique_lock<std::mutex> lock(*_mutex);\n                _resultVoxelization->insert(voxelizationMapInThread.begin(), voxelizationMapInThread.end());\n\n\t\t\t}\n\n\t\t\t/*Get intersection polygons of the contour and a voxel polygon*/\n\t\t\tBoostMaskVoxelizationThread::BoostPolygonDeque BoostMaskVoxelizationThread::getIntersections(\n\t\t\t    const rttb::VoxelGridIndex3D&\n\t\t\t    aVoxelIndex3D, const BoostPolygonVector& intersectionSlicePolygons)\n\t\t\t{\n\t\t\t\tBoostMaskVoxelizationThread::BoostPolygonDeque polygonDeque;\n\n\t\t\t\tBoostRing2D voxelPolygon = get2DContour(aVoxelIndex3D);\n\t\t\t\t::boost::geometry::correct(voxelPolygon);\n\n\t\t\t\tBoostPolygonVector::const_iterator it;\n\n\t\t\t\tfor (it = intersectionSlicePolygons.begin(); it != intersectionSlicePolygons.end(); ++it)\n\t\t\t\t{\n\t\t\t\t\tBoostPolygon2D contour = *it;\n\t\t\t\t\t::boost::geometry::correct(contour);\n\t\t\t\t\t\n\t\t\t\t\tBoostPolygonDeque intersection;\n\t\t\t\t\t::boost::geometry::intersection(voxelPolygon, contour, intersection);\n\t\t\t\t\tpolygonDeque.insert(polygonDeque.end(), intersection.begin(), intersection.end());\n\t\t\t\t}\n\n\t\t\t\treturn polygonDeque;\n\t\t\t}\n\n\t\t\tBoostMaskVoxelizationThread::BoostRing2D BoostMaskVoxelizationThread::get2DContour(\n\t\t\t    const rttb::VoxelGridIndex3D& aVoxelGrid3D)\n\t\t\t{\n\t\t\t\tBoostRing2D polygon;\n\n\n\t\t\t\tBoostPoint2D point1(aVoxelGrid3D[0] - 0.5, aVoxelGrid3D[1] - 0.5);\n\t\t\t\t::boost::geometry::append(polygon, point1);\n\n\t\t\t\tBoostPoint2D point2(aVoxelGrid3D[0] + 0.5, aVoxelGrid3D[1] - 0.5);\n\t\t\t\t::boost::geometry::append(polygon, point2);\n\n\t\t\t\tBoostPoint2D point3(aVoxelGrid3D[0] + 0.5, aVoxelGrid3D[1] + 0.5);\n\t\t\t\t::boost::geometry::append(polygon, point3);\n\n\t\t\t\tBoostPoint2D point4(aVoxelGrid3D[0] - 0.5, aVoxelGrid3D[1] + 0.5);\n\t\t\t\t::boost::geometry::append(polygon, point4);\n\n\t\t\t\t::boost::geometry::append(polygon, point1);\n\n\t\t\t\treturn polygon;\n\n\t\t\t}\n\n\t\t\t/*Calculate the intersection area*/\n\t\t\tdouble BoostMaskVoxelizationThread::calcArea(const BoostPolygonDeque& aPolygonDeque)\n\t\t\t{\n\t\t\t\tdouble area = 0;\n\n\t\t\t\tBoostPolygonDeque::const_iterator it;\n\n\t\t\t\tfor (it = aPolygonDeque.begin(); it != aPolygonDeque.end(); ++it)\n\t\t\t\t{\n\t\t\t\t\tarea += ::boost::geometry::area(*it);\n\t\t\t\t}\n\n\t\t\t\treturn area;\n\t\t\t}\n\n            double BoostMaskVoxelizationThread::correctForErrorAndStrictness(double volumeFraction, bool strict) const\n            {\n                if (strict){\n                    if (volumeFraction > 1 && (volumeFraction - 1) <= errorConstant)\n                    {\n                        volumeFraction = 1;\n                    }\n                }\n                else {\n                    if (volumeFraction > 1){\n                        volumeFraction = 1;\n                    }\n                    else if (volumeFraction < 0){\n                        volumeFraction = 0;\n                    }\n                }\n                return volumeFraction;\n            }\n\n        }\n\t}\n}\n", "meta": {"hexsha": "399d4063ebf1f7d03c7ac83bb2c8f0931ac86d3a", "size": 6055, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "code/masks/rttbBoostMaskVoxelizationThread.cpp", "max_stars_repo_name": "MIC-DKFZ/RTTB", "max_stars_repo_head_hexsha": "8b772501fd3fffcb67233a9307661b03dff72785", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 18.0, "max_stars_repo_stars_event_min_datetime": "2018-04-19T12:57:32.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-12T17:43:02.000Z", "max_issues_repo_path": "code/masks/rttbBoostMaskVoxelizationThread.cpp", "max_issues_repo_name": "MIC-DKFZ/RTTB", "max_issues_repo_head_hexsha": "8b772501fd3fffcb67233a9307661b03dff72785", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "code/masks/rttbBoostMaskVoxelizationThread.cpp", "max_forks_repo_name": "MIC-DKFZ/RTTB", "max_forks_repo_head_hexsha": "8b772501fd3fffcb67233a9307661b03dff72785", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2018-06-24T21:09:56.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-09T09:30:49.000Z", "avg_line_length": 36.0416666667, "max_line_length": 196, "alphanum_fraction": 0.6350123865, "num_tokens": 1496, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7090191337850932, "lm_q2_score": 0.48047867804790706, "lm_q1q2_score": 0.34066857611173373}}
{"text": "#ifndef STAN_MATH_PRIM_SCAL_FUN_LOCSCALE_CONSTRAIN_HPP\n#define STAN_MATH_PRIM_SCAL_FUN_LOCSCALE_CONSTRAIN_HPP\n\n#include <boost/math/tools/promotion.hpp>\n#include <stan/math/prim/scal/fun/identity_constrain.hpp>\n#include <stan/math/prim/scal/fun/abs.hpp>\n#include <stan/math/prim/scal/meta/size_of.hpp>\n#include <stan/math/prim/scal/err/check_positive_finite.hpp>\n#include <stan/math/prim/scal/err/check_finite.hpp>\n#include <cmath>\n#include <limits>\n\nnamespace stan {\nnamespace math {\n\n/**\n * Return the linearly transformed value for the specified unconstrained input\n * and specified location and scale.\n *\n * <p>The transform applied is\n *\n * <p>\\f$f(x) = mu + sigma * x\\f$\n *\n * <p>where mu is the location and sigma is the scale.\n *\n * <p>If the location is zero and the scale is one this\n * reduces to <code>identity_constrain(x)</code>.\n *\n * @tparam T type of scalar\n * @tparam M type of mean\n * @tparam S type of scale\n * @param[in] x Unconstrained scalar input\n * @param[in] mu location of constrained output\n * @param[in] sigma scale of constrained output\n * @return linear transformed value correspdonding to inputs\n * @throw std::domain_error if sigma <= 0\n * @throw std::domain_error if mu is not finite\n */\ntemplate <typename T, typename M, typename S>\ninline typename boost::math::tools::promote_args<T, M, S>::type\nlocscale_constrain(const T& x, const M& mu, const S& sigma) {\n  check_finite(\"locscale_constrain\", \"location\", mu);\n  if (sigma == 1) {\n    if (mu == 0)\n      return identity_constrain(x);\n    return mu + x;\n  }\n  check_positive_finite(\"locscale_constrain\", \"scale\", sigma);\n  return mu + sigma * x;\n}\n\n/**\n * Return the linearly transformed value for the specified unconstrained input\n * and specified location and scale, incrementing the specified\n * reference with the log absolute Jacobian determinant of the\n * transform.\n *\n * <p>The transform applied is\n *\n * <p>\\f$f(x) = mu + sigma * x\\f$\n *\n * <p>where mu is the location and sigma is the scale.\n *\n * If the location is zero and scale is one, this function\n * reduces to <code>identity_constraint(x, lp)</code>.\n *\n * @tparam T type of scalar\n * @tparam M type of mean\n * @tparam S type of scale\n * @param[in] x Unconstrained scalar input\n * @param[in] mu location of constrained output\n * @param[in] sigma scale of constrained output\n * @param[in,out] lp Reference to log probability to increment.\n * @return linear transformed value corresponding to inputs\n * @throw std::domain_error if sigma <= 0\n * @throw std::domain_error if mu is not finite\n */\ntemplate <typename T, typename M, typename S>\ninline typename boost::math::tools::promote_args<T, M, S>::type\nlocscale_constrain(const T& x, const M& mu, const S& sigma, T& lp) {\n  using std::log;\n  check_finite(\"locscale_constrain\", \"location\", mu);\n  if (sigma == 1) {\n    if (mu == 0)\n      return identity_constrain(x);\n    return mu + x;\n  }\n  check_positive_finite(\"locscale_constrain\", \"scale\", sigma);\n  lp += size_of(x) * log(sigma);\n  return mu + sigma * x;\n}\n\n}  // namespace math\n\n}  // namespace stan\n\n#endif\n", "meta": {"hexsha": "81ae83f879ee51c085cc6fd5c3a5ff6eea026aec", "size": 3068, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "stan/math/prim/scal/fun/locscale_constrain.hpp", "max_stars_repo_name": "jrmie/math", "max_stars_repo_head_hexsha": "2850ec262181075a5843968e805dc9ad1654e069", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "stan/math/prim/scal/fun/locscale_constrain.hpp", "max_issues_repo_name": "jrmie/math", "max_issues_repo_head_hexsha": "2850ec262181075a5843968e805dc9ad1654e069", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "stan/math/prim/scal/fun/locscale_constrain.hpp", "max_forks_repo_name": "jrmie/math", "max_forks_repo_head_hexsha": "2850ec262181075a5843968e805dc9ad1654e069", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.306122449, "max_line_length": 78, "alphanum_fraction": 0.7099087353, "num_tokens": 822, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6757646140788307, "lm_q2_score": 0.5039061705290806, "lm_q1q2_score": 0.34052195885952563}}
{"text": "#ifndef KDL_CHAINIKSOLVERPOS_GN_HPP\n#define KDL_CHAINIKSOLVERPOS_GN_HPP\n/**\n \\file   chainiksolverpos_lma.hpp\n \\brief  computing inverse position kinematics using Levenberg-Marquardt.\n*/\n\n/**************************************************************************\n    begin                : May 2012\n    copyright            : (C) 2012 Erwin Aertbelien\n    email                : firstname.lastname@mech.kuleuven.ac.be\n\n History (only major changes)( AUTHOR-Description ) :\n\n ***************************************************************************\n *   This library is free software; you can redistribute it and/or         *\n *   modify it under the terms of the GNU Lesser General Public            *\n *   License as published by the Free Software Foundation; either          *\n *   version 2.1 of the License, or (at your option) any later version.    *\n *                                                                         *\n *   This library is distributed in the hope that it will be useful,       *\n *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *\n *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU     *\n *   Lesser General Public License for more details.                       *\n *                                                                         *\n *   You should have received a copy of the GNU Lesser General Public      *\n *   License along with this library; if not, write to the Free Software   *\n *   Foundation, Inc., 59 Temple Place,                                    *\n *   Suite 330, Boston, MA  02111-1307  USA                                *\n *                                                                         *\n ***************************************************************************/\n\n\n#include \"chainiksolver.hpp\"\n#include \"chain.hpp\"\n#include <Eigen/Dense>\n\nnamespace KDL\n{\n\n/**\n * \\brief Solver for the inverse position kinematics that uses Levenberg-Marquardt.\n *\n * The robustness and speed of this solver is improved in several ways:\n *   - by using a Levenberg-Marquardt method that automatically adapts the damping when\n *     computing the inverse damped least squares inverse velocity kinematics.\n *   - by using an internal implementation of forward position kinematics and the\n *     Jacobian kinematics.  This implementation is more numerically robust,\n *     is able to cache previous computations, and implements an \\f$ \\mathcal{O}(N) \\f$\n *     algorithm for the computation of the Jacobian (with \\f$N\\f$, the number of joints, and for\n *     a fixed size task space).\n *   - by providing a way to specify the weights in task space, you can weigh rotations wrt translations.\n *     This is important e.g. to specify that rotations do not matter for the problem at hand, or to\n *     specify how important you judge rotations w.r.t. translations, typically in S.I.-units, ([m],[rad]),\n *     the rotations are over-specified, this can be avoided using the weight matrix. <B>Weights also\n *     make the solver more robust </B>.\n *   - only the constructors call <B>memory allocation</B>.\n *\n * De general principles behind the optimisation is inspired on:\n *   Jorge Nocedal, Stephen J. Wright, Numerical Optimization,Springer-Verlag New York, 1999.\n\n * \\ingroup KinematicFamily\n */\nclass ChainIkSolverPos_LMA : public KDL::ChainIkSolverPos\n{\nprivate:\n\ttypedef double ScalarType;\n    typedef Eigen::Matrix<ScalarType,Eigen::Dynamic,Eigen::Dynamic> MatrixXq;\n    typedef Eigen::Matrix<ScalarType,Eigen::Dynamic,1> VectorXq;\npublic:\n\n    static const int E_GRADIENT_JOINTS_TOO_SMALL = -100;\n    static const int E_INCREMENT_JOINTS_TOO_SMALL = -101;\n\n    /**\n\t * \\brief constructs an ChainIkSolverPos_LMA solver.\n\t *\n\t * The default parameters are choosen to be applicable to industrial-size robots\n\t * (e.g. 0.5 to 3 meters range in task space), with an accuracy that is more then\n\t * sufficient for typical industrial applications.\n\t *\n\t * Weights are applied in task space, i.e. the kinematic solver minimizes:\n\t * \\f$ E = \\Delta \\mathbf{x}^T \\mathbf{L} \\mathbf{L}^T \\Delta \\mathbf{x} \\f$, with \\f$\\mathbf{L}\\f$ a diagonal matrix.\n\t *\n\t * \\param _chain specifies the kinematic chain.\n\t * \\param _L specifies the \"square root\" of the weight (diagonal) matrix in task space. This diagonal matrix is specified as a vector.\n\t * \\param _eps specifies the desired accuracy in task space; <B>after</B> weighing with\n\t *        the weight matrix, it is applied on \\f$E\\f$.\n\t * \\param _maxiter specifies the maximum number of iterations.\n\t * \\param _eps_joints specifies that the algorithm has to stop when the computed joint angle increments are\n\t *        smaller then _eps_joints.  This is to avoid unnecessary computations up to _maxiter when the joint angle\n\t *        increments are so small that they effectively (in floating point) do not change the joint angles any more.  The default\n\t *        is a few digits above numerical accuracy.\n     */\n    ChainIkSolverPos_LMA(\n    \t\tconst KDL::Chain& _chain,\n    \t\tconst Eigen::Matrix<double,6,1>& _L,\n    \t\tdouble _eps=1E-5,\n    \t\tint _maxiter=500,\n    \t\tdouble _eps_joints=1E-15\n    );\n\n    /**\n     * \\brief identical the full constructor for ChainIkSolverPos_LMA, but provides for a default weight matrix.\n     *\n     *  \\f$\\mathbf{L} = \\mathrm{diag}\\left( \\begin{bmatrix} 1 & 1 & 1 & 0.01 & 0.01 & 0.01 \\end{bmatrix} \\right) \\f$.\n     */\n    ChainIkSolverPos_LMA(\n    \t\tconst KDL::Chain& _chain,\n    \t\tdouble _eps=1E-5,\n    \t\tint _maxiter=500,\n    \t\tdouble _eps_joints=1E-15\n    );\n\n    /**\n     * \\brief computes the inverse position kinematics.\n     *\n     * \\param q_init initial joint position.\n     * \\param T_base_goal goal position expressed with respect to the robot base.\n     * \\param q_out  joint position that achieves the specified goal position (if successful).\n     * \\return E_NOERROR if successful,\n     *         E_GRADIENT_JOINTS_TOO_SMALL the gradient of \\f$ E \\f$ towards the joints is to small,\n     *         E_INCREMENT_JOINTS_TOO_SMALL if joint position increments are to small,\n     *         E_MAX_ITER_EXCEEDED if number of iterations is exceeded.\n     */\n    virtual int CartToJnt(const KDL::JntArray& q_init, const KDL::Frame& T_base_goal, KDL::JntArray& q_out);\n\n    /**\n     * \\brief destructor.\n     */\n    virtual ~ChainIkSolverPos_LMA();\n\n    /**\n     * \\brief for internal use only.\n     *\n     * Only exposed for test and diagnostic purposes.\n     */\n    void compute_fwdpos(const VectorXq& q);\n\n    /**\n     * \\brief for internal use only.\n     * Only exposed for test and diagnostic purposes.\n     * compute_fwdpos(q) should always have been called before.\n     */\n    void compute_jacobian(const VectorXq& q);\n\n    /**\n     * \\brief for internal use only.\n     * Only exposed for test and diagnostic purposes.\n     */\n    void display_jac(const KDL::JntArray& jval);\n\n\n    /// @copydoc KDL::SolverI::strError()\n    virtual const char* strError(const int error) const;\n\nprivate:\n    const KDL::Chain& chain;\n    unsigned int nj;\n    unsigned int ns;\n\npublic:\n\n\n    /**\n     * \\brief contains the last number of  iterations for an execution of CartToJnt.\n     */\n    int lastNrOfIter;\n\n    /**\n     * \\brief contains the last value for \\f$ E \\f$ after an execution of CartToJnt.\n     */\n    double lastDifference;\n\n    /**\n     * \\brief contains the last value for the (unweighted) translational difference after an execution of CartToJnt.\n     */\n    double lastTransDiff;\n\n    /**\n     * \\brief contains the last value for the (unweighted) rotational difference after an execution of CartToJnt.\n     */\n    double lastRotDiff;\n\n    /**\n     * \\brief contains the last values for the singular values of the weighted Jacobian after an execution of CartToJnt.\n     */\n    VectorXq lastSV;\n\n    /**\n     * \\brief for internal use only.\n     *\n     * contains the last value for the Jacobian after an execution of compute_jacobian.\n     */\n    MatrixXq jac;\n\n    /**\n     * \\brief for internal use only.\n     *\n     * contains the gradient of the error criterion after an execution of CartToJnt.\n     */\n    VectorXq grad;\n    /**\n     * \\brief for internal use only.\n     *\n     * contains the last value for the position of the tip of the robot (head) with respect to the base, after an execution of compute_jacobian.\n     */\n    KDL::Frame T_base_head;\n\n    /**\n     * \\brief display information on each iteration step to the console.\n     */\n    bool display_information;\nprivate:\n    // additional specification of the inverse position kinematics problem:\n    unsigned int maxiter;\n    double eps;\n    double eps_joints;\n    Eigen::Matrix<ScalarType,6,1> L;\n\n\n\n    // state of compute_fwdpos and compute_jacobian:\n    std::vector<KDL::Frame> T_base_jointroot;\n    std::vector<KDL::Frame> T_base_jointtip;\n\t\t\t\t\t// need 2 vectors because of the somewhat strange definition of segment.hpp\n\t\t\t\t\t// you could also recompute jointtip out of jointroot,\n    \t\t\t\t// but then you'll need more expensive cos/sin functions.\n\n\n    // the following are state of CartToJnt that is pre-allocated:\n\n    VectorXq q;\n    MatrixXq A;\n    VectorXq tmp;\n    Eigen::LDLT<MatrixXq> ldlt;\n    Eigen::JacobiSVD<MatrixXq> svd;\n    VectorXq diffq;\n    VectorXq q_new;\n    VectorXq original_Aii;\n};\n\n\n\n\n\n}; // namespace KDL\n\n\n\n\n\n\n#endif\n", "meta": {"hexsha": "874f889c26371caf78fcb6c0b7adbf6c01d562e5", "size": 9314, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/scene_manager/include/kdl/chainiksolverpos_lma.hpp", "max_stars_repo_name": "Omnirobotic/godot", "max_stars_repo_head_hexsha": "d50b5d047bbf6c68fc458c1ad097321ca627185d", "max_stars_repo_licenses": ["CC-BY-3.0", "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": "modules/scene_manager/include/kdl/chainiksolverpos_lma.hpp", "max_issues_repo_name": "Omnirobotic/godot", "max_issues_repo_head_hexsha": "d50b5d047bbf6c68fc458c1ad097321ca627185d", "max_issues_repo_licenses": ["CC-BY-3.0", "Apache-2.0", "MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2019-11-14T12:20:06.000Z", "max_issues_repo_issues_event_max_datetime": "2020-08-07T13:51:10.000Z", "max_forks_repo_path": "modules/scene_manager/include/kdl/chainiksolverpos_lma.hpp", "max_forks_repo_name": "Omnirobotic/godot", "max_forks_repo_head_hexsha": "d50b5d047bbf6c68fc458c1ad097321ca627185d", "max_forks_repo_licenses": ["CC-BY-3.0", "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": 36.5254901961, "max_line_length": 144, "alphanum_fraction": 0.6416147735, "num_tokens": 2244, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6757646010190476, "lm_q2_score": 0.5039061705290805, "lm_q1q2_score": 0.3405219522786202}}
{"text": "#include <iostream>\n#include <cassert>\n#include <cstdlib>\n#include <ctime>\n#include <cmath>\n#include <random>\n#include <armadillo>\n#include \"port_authority.hpp\"\n#include \"mpi.h\"\n\nusing namespace std;\nusing namespace pauth;\nusing namespace arma;\n\nint main() {\n    \n  int taskid, numtasks;\n  MPI_Init(nullptr, nullptr);\n  MPI_Comm_size(MPI_COMM_WORLD, &numtasks);\n  MPI_Comm_rank(MPI_COMM_WORLD, &taskid);\n\n  srand(time(NULL));\n  const auto delta_max = static_cast<double>( (rand() % 200 + 50) / 100.0 );\n  const auto spring_const = static_cast<double>( (rand() % 1990 + 10) / 500.0 );\n  const auto T = static_cast<double>( (rand() % 200000 + 10) / 1000.0 );\n  const auto p0x = static_cast<double>( (rand() % 100 - 200) / 50.0 );\n  const auto p0y = static_cast<double>( (rand() % 100 - 200) / 50.0 );\n  const auto p0z = static_cast<double>( (rand() % 100 - 200) / 50.0 );\n  const auto E0x = static_cast<double>( (rand() % 100 - 200) / 20.0 );\n  const auto E0y = static_cast<double>( (rand() % 100 - 200) / 20.0 );\n  const auto E0z = static_cast<double>( (rand() % 100 - 200) / 20.0 );\n  const unsigned nsteps = 20000000;\n\n  if (taskid == 0) {\n    cout << \"3D linear dipole test started.\\n\";\n    cout << '\\n';\n    cout << \"delta_max = \" << delta_max << '\\n';\n    cout << \"k         = \" << spring_const << '\\n';\n    cout << \"T         = \" << T << '\\n';\n    cout << \"p0x       = \" << p0x << '\\n';\n    cout << \"p0y       = \" << p0y << '\\n';\n    cout << \"p0z       = \" << p0z << '\\n';\n    cout << \"E0x       = \" << E0x << '\\n';\n    cout << \"E0y       = \" << E0y << '\\n';\n    cout << \"E0z       = \" << E0z << '\\n';\n    cout << '\\n';\n  }\n  \n  const double dx = 0.1;\n  const double kB = 1.0;\n  const molecular_id id = molecular_id::Test1;\n  const size_t N = 1;\n  const size_t D = 3;\n  const double L = 1.0;\n  const metric m = euclidean;\n  const bc boundary = no_bc;\n  const mat inv_chi = arma::eye(3, 3);\n  const vec E0({E0x, E0y, E0z});\n  const vec pequil = inv_chi.i() * E0;\n  dipole_strain_linear_3d_potential strain_pot(inv_chi);\n  dipole_electric_potential electric_pot({E0x, E0y, E0z}, {0, 1, 2});\n\n  metropolis sim(id, N, D, L, continuous_trial_move(delta_max), \n                 {&strain_pot, &electric_pot}, T, kB, m, boundary, \n                 metropolis_acc, hardware_entropy_seed_gen, true);\n  sim.set_positions(pequil, 0);\n  const double u0 = accessors::U(sim);\n  sim.set_positions({p0x, p0y, p0z}, 0);\n  \n  metropolis_suite msuite(sim, 0, 1, info_lvl_flag::QUIET);\n  \n  msuite.add_variable_to_average(\"px\", [](const metropolis &sim) {\n    return sim.positions()(0, 0);\n  });\n  msuite.add_variable_to_average(\"py\", [](const metropolis &sim) {\n    return sim.positions()(1, 0);\n  });\n  msuite.add_variable_to_average(\"pz\", [](const metropolis &sim) {\n    return sim.positions()(2, 0);\n  });\n  msuite.add_variable_to_average(\"px^2\", [](const metropolis &sim) {\n    auto x = sim.positions()(0, 0);\n    return x*x;\n  });\n  msuite.add_variable_to_average(\"py^2\", [](const metropolis &sim) {\n    auto y = sim.positions()(1, 0);\n    return y*y;\n  });\n  msuite.add_variable_to_average(\"pz^2\", [](const metropolis &sim) {\n    auto z = sim.positions()(2, 0);\n    return z*z;\n  });\n  msuite.add_variable_to_average(\"U\", accessors::U);\n  msuite.add_variable_to_average(\"delta(x - x0)\", [=](const metropolis &sim) {\n    for (unsigned i = 0; i < 3; ++i) {\n      const double pi = sim.positions()(i, 0);\n      if (pi < pequil(i) - dx || pi > pequil(i) + dx) return 0;\n    }\n    return 1;\n  });\n\n  msuite.simulate(nsteps);\n\n  if(taskid == 0) {\n\n    auto averages = msuite.averages();\n\n    const double exp_px = averages[\"px\"];\n    const double exp_py = averages[\"py\"];\n    const double exp_pz = averages[\"pz\"];\n\n    const double exp_pxsq = averages[\"px^2\"];\n    const double exp_pysq = averages[\"py^2\"];\n    const double exp_pzsq = averages[\"pz^2\"];\n    \n    const double exp_E = averages[\"U\"];\n\n    vec eigval;\n    mat eigvec;\n    eig_sym(eigval, eigvec, inv_chi);\n    \n    vec Ev = eigvec * E0;\n    double Z_an = 1.0;\n    for(unsigned i = 0; i < 3; ++i)\n      Z_an *= sqrt(2 * M_PI * kB * T / eigval(i)) * \n              exp(Ev(i)*Ev(i) / (2 * eigval(i) * kB * T));\n\n    const auto exp_pxsq_an = (kB * T / eigval(0));\n    const auto exp_pysq_an = (kB * T / eigval(1));\n    const auto exp_pzsq_an = (kB * T / eigval(2));\n\n    const auto exp_E_an = 3 * kB * T / 2.0;\n\n    cout << \"exp_px    =   \" << exp_px << \" ?= \" << pequil(0) << '\\n';\n    assert(abs((exp_px - pequil(0)) / pequil(0)) < 5e-2);\n    cout << \"exp_py    =   \" << exp_py << \" ?= \" << pequil(1) << '\\n';\n    assert(abs((exp_py - pequil(1)) / pequil(1)) < 5e-2);\n    cout << \"exp_pz    =   \" << exp_pz << \" ?= \" << pequil(2) << '\\n';\n    assert(abs((exp_pz - pequil(2)) / pequil(2)) < 5e-2);\n\n    cout << \"exp_px^2  =   \" << exp_pxsq << \" ?= \" << exp_pxsq_an << '\\n';\n    assert(abs((exp_pxsq - exp_pxsq_an) / exp_pxsq_an) < 1e-2);\n    cout << \"exp_py^2  =   \" << exp_pysq << \" ?= \" << exp_pysq_an << '\\n';\n    assert(abs((exp_pysq - exp_pysq_an) / exp_pysq_an) < 1e-2);\n    cout << \"exp_pz^2  =   \" << exp_pzsq << \" ?= \" << exp_pzsq_an << '\\n';\n    assert(abs((exp_pzsq - exp_pzsq_an) / exp_pzsq_an) < 1e-2);\n\n    cout << \"exp_E    =   \" << exp_E << \" ?= \" << exp_E_an << '\\n';\n    assert(abs((exp_E - exp_E_an) / exp_E_an) < 1e-2);\n    cout << \"Z        =   \" \n         << (2.0 * dx * exp(-u0 / (kB * T)) / averages[\"delta(x - x0)\"])\n         << \" ?= \" << Z_an << '\\n';\n    assert(abs( ((pow(2.0 * dx, 3) * exp(-u0 / (kB * T)) / averages[\"delta(x - x0)\"]) -\n                Z_an) / Z_an ) < 1e-2);\n    cout << \"---------------------------------------------\\n\";\n\n  }\n\n  if(taskid == 0) cout << \"3D linear dipole test passed.\\n\";\n\n  MPI_Finalize();\n\n  return 0;\n\n}\n", "meta": {"hexsha": "9475a43d711676eea310c016afa5dc5fba243db1", "size": 5716, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/test_dipole_linear.cpp", "max_stars_repo_name": "grasingerm/port-authority", "max_stars_repo_head_hexsha": "51db6b09d6a1545eafeaf6be037a23d47313c490", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/test_dipole_linear.cpp", "max_issues_repo_name": "grasingerm/port-authority", "max_issues_repo_head_hexsha": "51db6b09d6a1545eafeaf6be037a23d47313c490", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/test_dipole_linear.cpp", "max_forks_repo_name": "grasingerm/port-authority", "max_forks_repo_head_hexsha": "51db6b09d6a1545eafeaf6be037a23d47313c490", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.4337349398, "max_line_length": 87, "alphanum_fraction": 0.5523093072, "num_tokens": 1976, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6757646010190476, "lm_q2_score": 0.5039061705290805, "lm_q1q2_score": 0.3405219522786202}}
{"text": "#include <pybind11/pybind11.h>\n#include <pybind11/eigen.h>\n\n#include <Eigen/Core>\n\n#include <iostream>\n\ndouble summation(const Eigen::MatrixXd& X, const Eigen::MatrixXd& Y) {\n#ifndef _OPENMP\n    std::cerr << \"Warning: OpenMP is disabled.\" << std::endl;\n#endif\n    double s = 0;\n    size_t i, j;\n#ifdef _OPENMP\n#pragma omp parallel for private(j) reduction(+:s)\n#endif\n    for (i = 0; i < X.rows(); ++i) {\n        for (j = 0; j < Y.rows(); ++j) {\n            if (0 < X(i) * Y(j)) {\n                s += std::log10((X(i) + Y(j)) * (X(i) + Y(j))) + std::sqrt(X(i) * Y(j));\n            }\n        }\n    }\n    return s;\n}\n\nPYBIND11_MODULE(openmp_cpp, m) {\n    m.def(\"summation\", &summation);\n}\n", "meta": {"hexsha": "7bdc0b76e8cfa043328cb9f3c8ba4e1ff1ada64e", "size": 688, "ext": "cc", "lang": "C++", "max_stars_repo_path": "multiple_loop/openmp_cpp.cc", "max_stars_repo_name": "shinsumicco/pybind11-tutorials", "max_stars_repo_head_hexsha": "b2f544653035172f1a7e489942dc8b796e7df72b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "multiple_loop/openmp_cpp.cc", "max_issues_repo_name": "shinsumicco/pybind11-tutorials", "max_issues_repo_head_hexsha": "b2f544653035172f1a7e489942dc8b796e7df72b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "multiple_loop/openmp_cpp.cc", "max_forks_repo_name": "shinsumicco/pybind11-tutorials", "max_forks_repo_head_hexsha": "b2f544653035172f1a7e489942dc8b796e7df72b", "max_forks_repo_licenses": ["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.9333333333, "max_line_length": 88, "alphanum_fraction": 0.5363372093, "num_tokens": 220, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.665410558746814, "lm_q2_score": 0.5117166047041654, "lm_q1q2_score": 0.34050163185622123}}
{"text": "/// \\file nuslam.hpp\n/// \\brief A package for Extended Kalman Filter Slam implementation.\n\n#ifndef NUSLAM_INCLUDE_GUARD_HPP\n#define NUSLAM_INCLUDE_GUARD_HPP\n\n#include \"rigid2d/diff_drive.hpp\"\n#include \"rigid2d/rigid2d.hpp\"\n\n#include <armadillo>\n#include <cmath>\n#include <iosfwd>\n#include <map>\n#include <utility>\n#include <vector>\n\nnamespace nuslam\n{\n  using rigid2d::Config2D;\n  using rigid2d::Twist2D;\n\n  /// \\brief A Mesurement vector Vector\n  struct Measurement\n  {\n    /// \\param r - the distance to landmark\n    double r;\n    /// \\param phi - the relative bearing of landmark\n    double phi;\n    /// \\param id - the measured landmark id\n    int id;\n\n    /// \\brief create zero-measurement\n    Measurement();\n\n    /// \\brief create a measurement with r,phi inputs\n    /// \\param x_ - x input of the measurement\n    /// \\param y_ - y input of the measurement\n    /// \\param id_ - the measured landmark id\n    explicit Measurement(double x_, double y_, int id_);\n\n    /// \\brief create a measurement vector\n    /// \\return the measurement vector\n    arma::mat compute_z();\n  };\n\n  /// \\brief initialize the guess of the robot's state and covariance matrix.\n  /// Start with a guess for the robot state (0, 0, 0) and zero covariance matrix.\n  class EKF\n  {\n  private:\n    arma::mat q_t = arma::mat(3, 1);\n    arma::mat m_t;\n\n    // arma::mat xi = arma::mat(3, 1);\n    // arma::mat cov = arma::mat(3, 3);\n\n    arma::mat Q_mat = arma::mat(3, 3);\n    arma::mat R_mat = arma::mat(2, 2);\n\n    arma::mat xi_predict = arma::mat(3, 1);\n    arma::mat cov_predict = arma::mat(3, 3);\n\n    std::map<int, int> id2landmark;\n\n  public:\n    /// \\brief initialize the combined state vector.\n    /// Start with a guess for the robot state (0, 0, 0) and zero e map state.\n    EKF();\n\n    /// \\brief updates the landmarks matrix and landmark covariance.\n    /// \\param meas - the measured landmark.\n    void add_new_measurement(const Measurement &meas);\n\n    /// \\brief check if the measured landmark exists in the landmark dictionary.\n    /// \\param landmark_id - the id of the measured landmark.\n    /// \\return bool - is the measured exists?\n    bool check_landmarks(const int landmark_id);\n\n    /// \\brief updates the landmarks matrix and landmark covariance.\n    /// \\param meas - the measured landmark.\n    void update_landmark(const Measurement &meas);\n\n    /// \\brief gets the state q_t.\n    /// \\param twist - the twist of the robot.\n    /// \\return the updated state q_t\n    arma::mat get_new_state(const Twist2D &twist);\n\n    /// \\brief gets derivative of g with respect to the state ξ.\n    /// \\param twist - the twist of the robot.\n    arma::mat get_transition(const Twist2D &twist);\n\n    /// \\brief predicts the next step - finds the estimated state and covariance.\n    /// \\param twist - the twist of the robot.\n    void predict(const Twist2D &twist);\n\n    /// \\brief compute the measurement h for range and bearing to landmark.\n    /// \\param index - the index of the measured landmark in the landmark matrix.\n    /// \\return the h matrix.\n    arma::mat get_h(int index);\n\n    /// \\brief compute the derivative of h with respect to the state.\n    /// \\param index - the index of the measured landmark in the landmark matrix.\n    /// \\return the H matrix.\n    arma::mat get_H(int index);\n\n    /// \\brief updates the next step.\n    /// \\param meas - the measured landmark.\n    void update(std::vector<Measurement> meas);\n\n    /// \\brief add a new zero row and column to a matrix (used when adding new\n    /// landmark). \\param mat - the current matrix. \\return the updated matrix.\n    arma::mat update_matrix_size(arma::mat mat);\n\n    /// \\brief run the Extended Kalman Filter algorithm.\n    /// \\param twist - the twist of the robot.\n    /// \\param meas -  the current measurement.\n    void run_ekf(const Twist2D &twist, const std::vector<Measurement> &meas);\n\n    /// \\brief output the robot state\n    /// \\return the robot state\n    arma::mat output_state();\n\n    /// \\brief output the map state\n    /// \\return the map state\n    arma::mat output_map_state();\n  };\n} // namespace nuslam\n\n#endif", "meta": {"hexsha": "af8a4cc15c716f9c703e6edda88fc052958eed09", "size": 4094, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "nuslam/include/nuslam/nuslam.hpp", "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/include/nuslam/nuslam.hpp", "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/include/nuslam/nuslam.hpp", "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": 31.7364341085, "max_line_length": 82, "alphanum_fraction": 0.6624328285, "num_tokens": 1048, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.665410558746814, "lm_q2_score": 0.5117166047041654, "lm_q1q2_score": 0.34050163185622123}}
{"text": "//\n//  matrix_boost.hpp\n//  jerome\n//\n//  Created by Anton Leuski on 5/13/16.\n//  Copyright © 2016 Anton Leuski & ICT/USC. All rights reserved.\n//\n//  This file is part of Jerome.\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 __jerome_type_matrix_boost_hpp__\n#define __jerome_type_matrix_boost_hpp__\n\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Wshorten-64-to-32\"\n\n#define BOOST_UBLAS_MOVE_SEMANTICS\n\n#include <boost/numeric/ublas/vector_sparse.hpp>\n#include <boost/numeric/ublas/vector.hpp>\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/matrix_proxy.hpp>\n#include <boost/numeric/ublas/operation.hpp>\n#include <boost/numeric/ublas/symmetric.hpp>\n#include <boost/range/algorithm/max_element.hpp>\n\n#pragma clang diagnostic pop\n\nnamespace boost {\n  namespace numeric {\n    namespace ublas {\n      \n      // (op v) [i] = op( v [i] )\n      template<class OP, class E>\n      BOOST_UBLAS_INLINE\n      typename boost::numeric::ublas::vector_unary_traits<E, OP>::result_type\n      apply_to_all (const boost::numeric::ublas::vector_expression<E> &e, const OP& op = OP() ) {\n        typedef typename boost::numeric::ublas::vector_unary_traits<E, OP>::expression_type expression_type;\n        return expression_type (e ());\n      }\n      \n      template<class T>\n      struct scalar_log:\n      public scalar_unary_functor<T> {\n        typedef typename scalar_unary_functor<T>::argument_type argument_type;\n        typedef typename scalar_unary_functor<T>::result_type result_type;\n        \n        static BOOST_UBLAS_INLINE\n        result_type apply (argument_type t) {\n          return std::log(t);\n        }\n      };\n      \n      template<class T>\n      struct scalar_log_plus1:\n      public scalar_unary_functor<T> {\n        typedef typename scalar_unary_functor<T>::argument_type argument_type;\n        typedef typename scalar_unary_functor<T>::result_type result_type;\n        \n        static BOOST_UBLAS_INLINE\n        result_type apply (argument_type t) {\n          return std::log(t+1.0);\n        }\n      };\n      \n      template<class T>\n      struct scalar_exp:\n      public scalar_unary_functor<T> {\n        typedef typename scalar_unary_functor<T>::argument_type argument_type;\n        typedef typename scalar_unary_functor<T>::result_type result_type;\n        \n        static BOOST_UBLAS_INLINE\n        result_type apply (argument_type t) {\n          return std::exp(t);\n        }\n      };\n      \n      template<class T1, class T2>\n      struct scalar_pow:\n      public scalar_binary_functor<T1, T2> {\n        typedef typename scalar_binary_functor<T1, T2>::argument1_type argument1_type;\n        typedef typename scalar_binary_functor<T1, T2>::argument2_type argument2_type;\n        typedef typename scalar_binary_functor<T1, T2>::result_type result_type;\n        \n        static BOOST_UBLAS_INLINE\n        result_type apply (argument1_type t1, argument2_type t2) {\n          return std::pow((double)t1,(double)t2);\n        }\n      };\n      \n      // (log v) [i] = log (v [i])\n      template<class E>\n      BOOST_UBLAS_INLINE\n      typename vector_unary_traits<E, scalar_log<typename E::value_type> >::result_type\n      log (const vector_expression<E> &e) {\n        typedef typename vector_unary_traits<E, scalar_log<typename E::value_type> >::expression_type expression_type;\n        return expression_type (e ());\n      }\n      \n      // (log v) [i] = log (v [i])\n      template<class E>\n      BOOST_UBLAS_INLINE\n      typename vector_unary_traits<E, scalar_log_plus1<typename E::value_type> >::result_type\n      log_plus1 (const vector_expression<E> &e) {\n        typedef typename vector_unary_traits<E, scalar_log_plus1<typename E::value_type> >::expression_type expression_type;\n        return expression_type (e ());\n      }\n      \n      // (exp v) [i] = exp (v [i])\n      template<class E>\n      BOOST_UBLAS_INLINE\n      typename vector_unary_traits<E, scalar_exp<typename E::value_type> >::result_type\n      exp (const vector_expression<E> &e) {\n        typedef typename vector_unary_traits<E, scalar_exp<typename E::value_type> >::expression_type expression_type;\n        return expression_type (e ());\n      }\n      \n      // (log m) [i] [j] = log (m [i] [j])\n      template<class E>\n      BOOST_UBLAS_INLINE\n      typename matrix_unary1_traits<E, scalar_log<typename E::value_type> >::result_type\n      log (const matrix_expression<E> &e) {\n        typedef typename matrix_unary1_traits<E, scalar_log<typename E::value_type> >::expression_type expression_type;\n        return expression_type (e ());\n      }\n      \n      // (exp m) [i] [j] = exp (m [i] [j])\n      template<class E>\n      BOOST_UBLAS_INLINE\n      typename matrix_unary1_traits<E, scalar_exp<typename E::value_type> >::result_type\n      exp (const matrix_expression<E> &e) {\n        typedef typename matrix_unary1_traits<E, scalar_exp<typename E::value_type> >::expression_type expression_type;\n        return expression_type (e ());\n      }\n      \n      // (pow(v, t) ) [i] = pow(v [i], t)\n      template<class E1, class T2>\n      BOOST_UBLAS_INLINE\n      typename enable_if< is_convertible<T2, typename E1::value_type >,\n      typename vector_binary_scalar2_traits<E1, const T2, scalar_pow<typename E1::value_type, T2> >::result_type\n      >::type\n      element_pow (const vector_expression<E1> &e1,\n                   const T2 &e2) {\n        typedef typename vector_binary_scalar2_traits<E1, const T2, scalar_pow<typename E1::value_type, T2> >::expression_type expression_type;\n        return expression_type (e1 (), e2);\n      }\n      \n      \n      // (pow(m, t)) [i] [j] = pow(m [i] [j], t)\n      template<class E1, class T2>\n      BOOST_UBLAS_INLINE\n      typename enable_if< is_convertible<T2, typename E1::value_type>,\n      typename matrix_binary_scalar2_traits<E1, const T2, scalar_pow<typename E1::value_type, T2> >::result_type\n      >::type\n      element_pow (const matrix_expression<E1> &e1,\n                   const T2 &e2) {\n        typedef typename matrix_binary_scalar2_traits<E1, const T2, scalar_pow<typename E1::value_type, T2> >::expression_type expression_type;\n        return expression_type (e1 (), e2);\n      }\n      \n      \n      template<class M>\n      BOOST_UBLAS_INLINE\n      matrix_vector_slice<M> diag(M &data) {\n        const typename M::size_type s = std::min(data.size1(),data.size2());\n        return matrix_vector_slice<M>(data, slice(0,1,s), slice(0,1,s));\n      };\n      \n      template<class M>\n      BOOST_UBLAS_INLINE\n      const matrix_vector_slice<const M> diag(const M &data) {\n        const typename M::size_type s = std::min(data.size1(),data.size2());\n        return matrix_vector_slice<const M>(data, slice(0,1,s), slice(0,1,s));\n      };\n      \n      \n      \n    }\n  }\n}\n\nnamespace jerome {\n  \n  namespace ublas = boost::numeric::ublas;\n  \n  template<class T> using Vector = ublas::vector<T>;\n  // sparse array\n  template<class T> using SparseVector = ublas::compressed_vector<T>;\n  \n  typedef ublas::matrix<WeightValue, ublas::column_major>     WeightMatrix;\n  typedef ublas::matrix_row<WeightMatrix>                     WeightMatrixRow;\n  typedef ublas::matrix_row<const WeightMatrix>               WeightMatrixConstRow;\n  typedef ublas::matrix_column<WeightMatrix>                  WeightMatrixColumn;\n  typedef ublas::matrix_column<const WeightMatrix>            WeightMatrixConstColumn;\n  typedef ublas::vector<WeightMatrix::value_type>             WeightVector;\n  typedef ublas::compressed_vector<WeightMatrix::value_type>\tSparseWeightVector;\n  \n  typedef ublas::symmetric_matrix<WeightMatrix::value_type, ublas::upper>\t\t\tSymmetricWeightMatrix;\n  typedef ublas::matrix_range<SymmetricWeightMatrix>\t\t\t\t\tSymmetricWeightMatrixRange;\n  \n  template <class M>\n  struct traits {\n    typedef typename M::size_type size_type;\n    typedef typename M::value_type value_type;\n  };\n    \n  struct MatrixSize {\n    traits<WeightMatrix>::size_type rowCount;\n    traits<WeightMatrix>::size_type columnCount;\n    \n    MatrixSize() = default;\n    \n    MatrixSize(const WeightMatrix& m)\n    : rowCount(m.size1()), columnCount(m.size2())\n    {}\n  };\n  \n  typedef ublas::scalar_matrix<WeightMatrix::value_type>\n  WeightMatrixScalar;\n  \n  typedef ublas::scalar_vector<WeightMatrix::value_type>\n  WeightVectorScalar;\n  \n  inline WeightMatrixScalar WeightMatrixZero(const MatrixSize& size)\n  {\n    return WeightMatrixScalar(size.rowCount, size.columnCount, 0);\n  }\n  \n  inline WeightMatrixScalar WeightMatrixOnes(const MatrixSize& size)\n  {\n    return WeightMatrixScalar(size.rowCount, size.columnCount, 1);\n  }\n  \n  inline WeightVectorScalar WeightVectorZero(traits<WeightVector>::size_type size)\n  {\n    return WeightVectorScalar(size, 0);\n  }\n  \n  inline WeightVectorScalar WeightVectorOnes(traits<WeightVector>::size_type size)\n  {\n    return WeightVectorScalar(size, 1);\n  }\n  \n  template <typename M, typename C>\n  inline auto column(M&& m, C c)\n  -> decltype(ublas::matrix_column<typename std::remove_reference<M>::type>(std::forward<M>(m), c))\n  {\n    return ublas::matrix_column<typename std::remove_reference<M>::type>(std::forward<M>(m), c);\n  }\n\n  template <typename M, typename C>\n  inline auto row(M&& m, C c)\n  -> decltype(ublas::matrix_row<typename std::remove_reference<M>::type>(std::forward<M>(m), c))\n  {\n    return ublas::matrix_row<typename std::remove_reference<M>::type>(std::forward<M>(m), c);\n  }\n  \n  template <typename M>\n  inline auto sum(const M& m)\n  -> decltype(ublas::sum(m))\n  {\n    return ublas::sum(m);\n  }\n\n  template <typename A, typename B>\n  inline auto prod(const A& a, const B& b)\n  -> decltype(ublas::prod(a, b))\n  {\n    return ublas::prod(a, b);\n  }\n\n  template <typename A, typename B>\n  inline auto outer_prod(const A& a, const B& b)\n  -> decltype(ublas::outer_prod(a, b))\n  {\n    return ublas::outer_prod(a, b);\n  }\n\n  template <typename A, typename B>\n  inline auto element_pow(const A& a, B b)\n  -> decltype(ublas::element_pow(a, b))\n  {\n    return ublas::element_pow(a, b);\n  }\n\n  template <typename A, typename B>\n  inline auto element_prod(const A& a, const B& b)\n  -> decltype(ublas::element_prod(a, b))\n  {\n    return ublas::element_prod(a, b);\n  }\n  \n  template <typename M>\n  inline SparseWeightVector sparse_log_plus1(const M& m)\n  {\n    SparseWeightVector result(m.size());\n    for (auto a_it = m.begin(), a_end = m.end(); a_it != a_end; ++a_it) {\n      result(a_it.index()) = std::log(1.0+ (*a_it));\n    }\n    \n    return result;\n  }\n\n  template <typename M>\n  inline auto max_element(const M& m)\n  -> decltype(*boost::max_element(m))\n  {\n    return *boost::max_element(m);\n  }\n  \n  template <typename M, typename S>\n  inline void resize(M&& m, const S& s)\n  {\n    m.resize(s);\n  }\n\n  template <typename V>\n  inline void append_vector_to_vector(const V& src, V&& dst, const typename traits<V>::size_type& off) {\n    for(auto i = src.begin(), e = src.end(); i != e; ++i) {\n      dst[i.index()+off] = *i;\n    }\n  }\n\n  template <typename V>\n  inline void append_sparse_vector_to_sparse_vector(const V& src, V&& dst,\n                                                    const typename traits<V>::size_type& off) {\n    for(auto i = src.begin(), e = src.end(); i != e; ++i) {\n      dst[i.index()+off] = *i;\n    }\n  }\n  \n  template <typename X, typename I, typename V>\n  inline auto set_value_at_index_in_vector(const X& x, const I& i, V&& v)\n  -> decltype(v[i])\n  {\n    return v[i] = x;\n  }\n\n  template <typename I, typename V>\n  inline auto increment_value_at_index_in_vector(const I& i, V&& v)\n  -> decltype(v[i])\n  {\n    return v[i] += 1;\n  }\n\n  template <typename T, typename M>\n  inline auto matrix_cast(M&& m)\n  -> decltype(m)\n  {\n    return m;\n  }\n\n  template <typename V, typename OP>\n  inline void for_each(const V& v, OP&& op) {\n    for (auto E = v.begin(), __end = v.end(); E != __end; ++E) {\n      op(E.index(), *E);\n    }\n  }\n  \n  // dense vectors only!!!!\n  template <typename V, typename Q>\n  inline auto element_div(const V& v, const Q& q)\n  -> decltype(ublas::element_div(v, q))\n  {\n    // ubleas::element_div causes divide by zero. I guess, it tries to compute\n    // 1/|Dl| for each values v even for 0 ones....\n    // return element_div(term.tfs() * lambda().value(),\n    // field.documentLengths());\n    return ublas::element_div(v, q);\n  }\n\n  template <typename A, typename B, typename C>\n  inline void sparse_outer_prod_add_to(const A& a, const B& b, C&& c) {\n    for (auto a_it = a.begin(), a_end = a.end(); a_it != a_end; ++a_it) {\n      const auto a_index = a_it.index();\n      const auto a_value = *a_it;\n      for (auto b_it = b.begin(), b_end = b.end(); b_it != b_end; ++b_it) {\n        c(a_index, b_it.index()) += a_value * (*b_it);\n      }\n    }\n  }\n  \n  template <typename A, typename B, typename C>\n  inline void sparse_scale_add_to(const A& a, const B& b, C&& c) {\n    for (auto a_it = a.begin(), a_end = a.end(); a_it != a_end; ++a_it) {\n      c(a_it.index()) += (*a_it) * b;\n    }\n  }\n\n  // boost UBLAS is horrible at taking advantage of sparse vectors.\n  // Every element-wise operation you apply to sparse vectors is applied\n  // to every vector element including zero ones. So we have to implement\n  // them ourselves.\n  template <typename A, typename B, typename C>\n  inline SparseWeightVector sparse_scale_div_by(const A& a, const B& b, const C& c) {\n    SparseWeightVector result(a.size());\n    for (auto a_it = a.begin(), a_end = a.end(); a_it != a_end; ++a_it) {\n      result(a_it.index()) = (*a_it) * b / c(a_it.index());\n    }\n    return result;\n  }\n\n  \n}\n\nnamespace boost { namespace numeric { namespace ublas {\n  \n  std::ostream& operator << (std::ostream& outs, const jerome::WeightMatrix& obj);\n  std::ostream& operator << (std::ostream& outs, const jerome::SymmetricWeightMatrix& obj);\n  std::ostream& operator << (std::ostream& outs, const jerome::SymmetricWeightMatrixRange& obj);\n  std::ostream& operator << (std::ostream& outs, const jerome::WeightVector& obj);\n  \n  // fascinating shit: when looking for an overloaded operator, compiler looks into the\n  // namespace of the object parameter. Aparently, if you have a typedef, the compiler\n  // ignores the namespace of the typedef and goes directly for the namespace of the class used\n  // in the typedef. in this case it's boost:numeric::ublas.\n  \n  // if you do not put the operator in the namespace, the compiler will not find it.\n}}}\n\n#endif // __jerome_type_matrix_boost_hpp__\n", "meta": {"hexsha": "45f00a5c3d4974b26ee4c124171e6165c86e0fec", "size": 14927, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "jerome/type/matrix_boost.hpp", "max_stars_repo_name": "leuski-ict/jerome", "max_stars_repo_head_hexsha": "6141a21c50903e98a04c79899164e7d0e82fe1c2", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2018-06-11T10:48:54.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-30T07:10:15.000Z", "max_issues_repo_path": "jerome/type/matrix_boost.hpp", "max_issues_repo_name": "leuski-ict/jerome", "max_issues_repo_head_hexsha": "6141a21c50903e98a04c79899164e7d0e82fe1c2", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "jerome/type/matrix_boost.hpp", "max_forks_repo_name": "leuski-ict/jerome", "max_forks_repo_head_hexsha": "6141a21c50903e98a04c79899164e7d0e82fe1c2", "max_forks_repo_licenses": ["Apache-2.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.3940092166, "max_line_length": 143, "alphanum_fraction": 0.657734307, "num_tokens": 3873, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.665410558746814, "lm_q2_score": 0.5117166047041654, "lm_q1q2_score": 0.34050163185622123}}
{"text": "/*\n\nCandyPoker\nhttps://github.com/sweeterthancandy/CandyPoker\n\nMIT License\n\nCopyright (c) 2019 Gerry Candy\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n\n*/\n#include \"ps/base/algorithm.h\"\n#include \"ps/base/rank_hasher.h\"\n\n#include <boost/range/algorithm.hpp>\n#include <map>\n\nnamespace ps{\n\n/*\n\n   The idea of this is to 2-tuple of permutations (C,S), \n   so for a vector of n-players, we apply the permutation\n                        C : c -> c',\n   ie\n                (p1,p2,p3) -> (p1', p2', p3'),\n   and then apply the suit permutation S : s -> s'\n                (p1', p2', p3') -> (p1'', p2'', p3''),\n   so that given and set of players, we can can an injective\n   mapping to a small subset. Ei, AA vs KK == KK vs AA \n   with the player orientation swapped around.\n        Noting that we can complete ignore any permutation \n   of suits for all practical purposes, as always just want\n   to find a suit permutation so that it's injective\n\n                    eval(AA,KK vs AA,KK)\n    \n        =           eval(AA vs AA ) * w0 + \n                    eval(AA vs KK ) * w1 + \n                    eval(KK vs AA ) * w2 + \n                    eval(KK vs KK ) * w3\n    \n        =           eval(AA vs AA ) * w0 + \n                    eval(AA vs KK ) * w1 + \n            Inverse(eval(AA vs KK )) * w2 + \n                    eval(KK vs KK ) * w3\n\n          \n        \n        \n\n        \n */\nstruct rank_info{\n        size_t index;\n        holdem_id hid;\n        rank_hasher::rank_hash_t rank_hash;\n        bool is_suited;\n        friend bool operator==(rank_info const& l, rank_info const& r)noexcept{\n                return ( ! ( l < r ) ) && ( ! ( r < l ) );\n        }\n        friend bool operator!=(rank_info const& l, rank_info const& r)noexcept{\n                return ( ! (l == r) );\n        }\n        friend bool operator<(rank_info const& l, rank_info const& r)noexcept{\n                if( l.rank_hash != r.rank_hash ){\n                        return l.rank_hash <  r.rank_hash;\n                }\n                return l.is_suited <  r.is_suited;\n        }\n};\nstruct suit_perm_info{\n        std::array<suit_id, 4> suit_perm;\n        std::vector<int> player_perm;\n        holdem_hand_vector hv;\n        size_t card_mask;\n        friend bool operator<(suit_perm_info const& l, suit_perm_info const& r)noexcept{\n                #if 0\n                if( l.card_mask != r.card_mask )\n                        return l.card_mask < r.card_mask;\n                #endif\n                return l.hv < r.hv;\n        }\n};\n\n\nstd::tuple<\n        std::vector<int>,\n        std::vector<holdem_id>\n> permutate_for_the_better( std::vector<holdem_id> const& players )\n{\n        enum{ Debug = false };\n\n        std::vector< rank_info > ri;\n        for(size_t idx=0;idx!=players.size();++idx){\n                auto h =  holdem_hand_decl::get( players[idx] ) ;\n                auto rank_hash = rank_hasher::create_from_cards(h.first(), h.second());\n                ri.emplace_back(rank_info{idx, players[idx], rank_hash, h.is_suited()});\n        }\n        boost::sort( ri );\n\n        std::vector< std::vector<rank_info> > level_sets;\n\n        level_sets.emplace_back();\n        level_sets.back().push_back( ri[0] );\n        for(size_t idx=1; idx < ri.size();++idx){\n                if( level_sets.back().front() == ri[idx]){\n                        // same set\n                        level_sets.back().push_back(ri[idx]);\n                } else {\n                        // start new set\n                        level_sets.emplace_back();\n                        level_sets.back().push_back(ri[idx]);\n                }\n        }\n\n        if( Debug ){\n                PS_LOG(trace) << \"begin level_sets\";\n                for(auto const& ls : level_sets ){\n                        holdem_hand_vector hv;\n                        for(auto const& _ : ls){\n                                hv.push_back(_.hid);\n                        }\n                        PS_LOG(trace) << \"    -\" << hv;\n                }\n                PS_LOG(trace) << \"end   level_sets\";\n        }\n\n        std::vector< std::vector< rank_info > > rank_permutations;\n        rank_permutations.emplace_back();\n\n        for(auto& ls : level_sets){\n                if( ls.size() == 1 ){\n                        for(auto& _ : rank_permutations ){\n                                _.push_back(ls.back());\n                        }\n                } else {\n                        \n                        decltype(rank_permutations) next;\n\n                        // should be sorted anyway\n                        boost::sort(ls);\n                        do{\n                                for(auto rp : rank_permutations ){\n                                        for(auto const& item : ls ){\n                                                rp.push_back(item);\n                                        }\n                                        next.push_back(rp);\n                                }\n                        }while(boost::next_permutation(ls, [](auto const& l, auto const& r){ return l.index < r.index; }));\n                        rank_permutations = std::move(next);\n                }\n        }\n\n        if( Debug ){\n                PS_LOG(trace) << \"rank_permutations.size() => \" << rank_permutations.size();\n                PS_LOG(trace) << \"begin rank_permutations\";\n                for(auto const& rp : rank_permutations ){\n                        holdem_hand_vector hv;\n                        for(auto const& _ : rp){\n                                hv.push_back(_.hid);\n                        }\n                        PS_LOG(trace) << \"    -\" << hv;\n                }\n                PS_LOG(trace) << \"end   rank_permutations\";\n        }\n        \n        std::vector<suit_perm_info> suit_perm_vec;\n\n        std::array<suit_id, 4> suits = { 0, 1, 2, 3};\n        for(auto const& rp : rank_permutations ){\n                boost::sort(suits);\n                do{\n                        std::vector<int> player_perm;\n                        holdem_hand_vector hv;\n                        size_t mask = 0;\n\n                        for(auto const& _ : rp){\n\n                                auto h =  holdem_hand_decl::get( _.hid ) ;\n\n                                rank_id r0 = h.first().rank();\n                                suit_id s0 = h.first().suit();\n                                rank_id r1 = h.second().rank();\n                                suit_id s1 = h.second().suit();\n\n                                suit_id m0 = suits[s0];\n                                suit_id m1 = suits[s1];\n\n                                holdem_id mhid = holdem_hand_decl::make_id(r0, m0, r1, m1);\n\n                                mask |= static_cast<size_t>(1) << mhid;\n\n                                player_perm.push_back(_.index);\n                                hv.push_back(mhid);\n                        }\n\n                        suit_perm_vec.push_back(suit_perm_info{suits, std::move(player_perm),\n                                                               hv, mask});\n\n                }while(boost::next_permutation(suits));\n        }\n\n        boost::sort(suit_perm_vec);\n        if( Debug ){\n                PS_LOG(trace) << \"begin rank_permutations\";\n                for(auto const& sp : suit_perm_vec ){\n                        PS_LOG(trace) << \"    -\" << sp.hv;\n                }\n                PS_LOG(trace) << \"end   rank_permutations\";\n                PS_LOG(trace) << \"hv = \" << suit_perm_vec.front().hv;\n        }\n\n        return { suit_perm_vec.front().player_perm, suit_perm_vec.front().hv };\n\n}\n\n#if 0\nstd::tuple<\n        std::vector<int>,\n        std::vector<holdem_id>\n> permutate_for_the_better( std::vector<holdem_id> const& players ){\n        // first create vector of n, and token_n = hh_n\n        //      (0,hh_0), (1,hh_1), ... (n,hh_n),\n        // where first h is greater handk the second h\n        std::vector< std::tuple< size_t, std::string> > player_perm;\n        for(size_t i=0;i!=players.size();++i){\n                auto h =  holdem_hand_decl::get( players[i] ) ;\n                player_perm.emplace_back(i, h.first().rank().to_string() +\n                                            h.second().rank().to_string() );\n        }\n        // sort it by the token\n        boost::sort(player_perm, [](auto const& left, auto const& right){\n                return std::get<1>(left) < std::get<1>(right);\n        });\n\n        // new work out the perm used to create it\n        std::vector<int> perm;\n        for(size_t i=0;i!=players.size();++i){\n                perm.emplace_back( std::get<0>(player_perm[i]) );\n        }\n\n        std::vector<std::vector<holdem_hand_decl> > decls;\n\n\n\n        // now we allocate suits, starting with 0 etc\n        std::array< int, 4> rev_suit_map{-1,-1,-1,-1};\n        int suit_iter = 0; // using the fact we know suits \\in {0,1,2,3}\n        // allocate pocket pairs common types first\n\n        // AA KK -> AaAb KcKa\n        //       -> AaAb KcKb -> AbAa KcKb\n\n        std::map<int, int> pp_count;\n        for(size_t i=0;i!=players.size();++i){\n                auto h =  holdem_hand_decl::get( players[perm[i]] ) ;\n                if( h.first().rank() != h.second().rank()){\n                        continue;\n                }\n                ++pp_count[h.first().suit()];\n                ++pp_count[h.second().suit()];\n        }\n\n        for(size_t i=0;i!=players.size();++i){\n                auto h =  holdem_hand_decl::get( players[perm[i]] ) ;\n\n                auto a = &h.first();\n                auto b = &h.second();\n                // TODO pocket pair\n                #if 1\n                if( a->rank() == b->rank()){\n                        if( pp_count[a->suit()] > pp_count[b->suit()] ){\n                                std::swap(a,b);\n                        }\n                }\n                #endif\n\n\n                if(     rev_suit_map[a->suit()] == -1 )\n                        rev_suit_map[a->suit()] = suit_iter++;\n                if(     rev_suit_map[b->suit()] == -1 )\n                        rev_suit_map[b->suit()] = suit_iter++;\n        }\n\n        // TODO remove this, unneeded\n        for(size_t i=0;i != 4;++i){\n                if(     rev_suit_map[i] == -1 )\n                        rev_suit_map[i] = suit_iter++;\n        }\n\n        // crate map\n        std::vector< int> suit_perms;\n        for(size_t i=0;i != 4;++i){\n                suit_perms.emplace_back(rev_suit_map[i]);\n        }\n        \n        std::vector<holdem_id> perm_hands;\n        for(size_t i=0;i != players.size();++i){\n                auto h =  holdem_hand_decl::get( players[perm[i]] ) ;\n\n                #if 0\n                if( h.first().rank() == h.second().rank() ){\n                        if( suit_perms[h.first().suit()] > suit_perms[h.second().suit()] ){\n                                perm_hands.emplace_back( \n                                        holdem_hand_decl::make_id(\n                                                h.first().rank(),\n                                                suit_perms[h.second().suit()],\n                                                h.second().rank(),\n                                                suit_perms[h.first().suit()]));\n                        } else {\n                                perm_hands.emplace_back( \n                                        holdem_hand_decl::make_id(\n                                                h.first().rank(),\n                                                suit_perms[h.first().suit()],\n                                                h.second().rank(),\n                                                suit_perms[h.second().suit()]));\n                        } \n                } else{\n                #endif\n                        perm_hands.emplace_back( \n                                holdem_hand_decl::make_id(\n                                        h.first().rank(),\n                                        suit_perms[h.first().suit()],\n                                        h.second().rank(),\n                                        suit_perms[h.second().suit()]));\n                #if 0\n                }\n                #endif\n\n        }\n        return std::make_tuple( perm, perm_hands);\n}\n#endif\n\n} // ps\n", "meta": {"hexsha": "e4bbc2bfe22df7df91630cd10bfe74929b271525", "size": 13228, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lib/base/algorithm.cpp", "max_stars_repo_name": "sweeterthancandy/CandyPoker", "max_stars_repo_head_hexsha": "53dfcc92402492739a2300847aeb298d389d546a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9.0, "max_stars_repo_stars_event_min_datetime": "2019-10-31T12:57:38.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-16T10:41:18.000Z", "max_issues_repo_path": "lib/base/algorithm.cpp", "max_issues_repo_name": "sweeterthancandy/CandyPoker", "max_issues_repo_head_hexsha": "53dfcc92402492739a2300847aeb298d389d546a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lib/base/algorithm.cpp", "max_forks_repo_name": "sweeterthancandy/CandyPoker", "max_forks_repo_head_hexsha": "53dfcc92402492739a2300847aeb298d389d546a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-04-01T06:05:52.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-01T06:05:52.000Z", "avg_line_length": 37.3672316384, "max_line_length": 123, "alphanum_fraction": 0.4501058361, "num_tokens": 2824, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.665410558746814, "lm_q2_score": 0.5117166047041652, "lm_q1q2_score": 0.3405016318562211}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\n\n// Copyright (c) 2015, Oracle and/or its affiliates.\n\n// Contributed and/or modified by Menelaos Karavelas, on behalf of Oracle\n\n// Licensed under the Boost Software License version 1.0.\n// http://www.boost.org/users/license.html\n\n#ifndef BOOST_GEOMETRY_ALGORITHMS_DETAIL_MAX_INTERVAL_GAP_HPP\n#define BOOST_GEOMETRY_ALGORITHMS_DETAIL_MAX_INTERVAL_GAP_HPP\n\n#include <cstddef>\n#include <queue>\n#include <utility>\n#include <vector>\n\n#include <boost/core/ref.hpp>\n#include <boost/range.hpp>\n#include <boost/type_traits/remove_const.hpp>\n#include <boost/type_traits/remove_reference.hpp>\n\n#include <boost/geometry/core/assert.hpp>\n#include <boost/geometry/util/math.hpp>\n#include <boost/geometry/algorithms/detail/sweep.hpp>\n\n\nnamespace boost { namespace geometry\n{\n\n#ifndef DOXYGEN_NO_DETAIL\nnamespace detail { namespace max_interval_gap\n{\n\n// the class Interval must provide the following:\n// * must define the type value_type\n// * must define the type difference_type\n// * must have the methods:\n//   value_type get<Index>() const\n//   difference_type length() const\n// where an Index value of 0 (resp., 1) refers to the left (resp.,\n// right) endpoint of the interval\n\ntemplate <typename Interval>\nclass sweep_event\n{\npublic:\n    typedef Interval interval_type;\n    typedef typename Interval::value_type time_type;\n\n    sweep_event(Interval const& interval, bool start_event = true)\n        : m_interval(boost::cref(interval))\n        , m_start_event(start_event)\n    {}\n\n    inline bool is_start_event() const\n    {\n        return m_start_event;\n    }\n\n    inline interval_type const& interval() const\n    {\n        return m_interval;\n    }\n\n    inline time_type time() const\n    {\n        return (m_start_event)\n            ? interval().template get<0>()\n            : interval().template get<1>();\n    }\n\n    inline bool operator<(sweep_event const& other) const\n    {\n        if (! math::equals(time(), other.time()))\n        {\n            return time() < other.time();\n        }\n        // a start-event is before an end-event with the same event time\n        return is_start_event() && ! other.is_start_event();\n    }\n\nprivate:\n    boost::reference_wrapper<Interval const> m_interval;\n    bool m_start_event;\n};\n\ntemplate <typename Event>\nstruct event_greater\n{\n    inline bool operator()(Event const& event1, Event const& event2) const\n    {\n        return event2 < event1;\n    }\n};\n\n\nstruct initialization_visitor\n{\n    template <typename Range, typename PriorityQueue, typename EventVisitor>\n    static inline void apply(Range const& range,\n                             PriorityQueue& queue,\n                             EventVisitor&)\n    {\n        BOOST_GEOMETRY_ASSERT(queue.empty());\n\n        // it is faster to build the queue directly from the entire\n        // range, rather than insert elements one after the other\n        PriorityQueue pq(boost::begin(range), boost::end(range));\n        std::swap(pq, queue);\n    }\n};\n\n\ntemplate <typename Event>\nclass event_visitor\n{\n    typedef typename Event::time_type event_time_type;\n    typedef typename Event::interval_type::difference_type difference_type;\n\n    typedef typename boost::remove_const\n        <\n            typename boost::remove_reference\n                <\n                    event_time_type\n                >::type\n        >::type bare_time_type;\n\n\npublic:\n    event_visitor()\n        : m_overlap_count(0)\n        , m_max_gap_left(0)\n        , m_max_gap_right(0)\n    {}\n\n    template <typename PriorityQueue>\n    inline void apply(Event const& event, PriorityQueue& queue)\n    {\n        if (event.is_start_event())\n        {\n            ++m_overlap_count;\n            queue.push(Event(event.interval(), false));\n        }\n        else\n        {\n            --m_overlap_count;\n            if (m_overlap_count == 0 && ! queue.empty())\n            {\n                // we may have a gap\n                BOOST_GEOMETRY_ASSERT(queue.top().is_start_event());\n\n                event_time_type next_event_time\n                    = queue.top().interval().template get<0>();\n                difference_type gap = next_event_time - event.time();\n                if (gap > max_gap())\n                {\n                    m_max_gap_left = event.time();\n                    m_max_gap_right = next_event_time;\n                }\n            }\n        }\n    }\n\n    bare_time_type const& max_gap_left() const\n    {\n        return m_max_gap_left;\n    }\n\n    bare_time_type const& max_gap_right() const\n    {\n        return m_max_gap_right;\n    }\n\n    difference_type max_gap() const\n    {\n        return m_max_gap_right - m_max_gap_left;\n    }\n\nprivate:\n    std::size_t m_overlap_count;\n    bare_time_type m_max_gap_left, m_max_gap_right;\n};\n\n}} // namespace detail::max_interval_gap\n#endif // DOXYGEN_NO_DETAIL\n\n\n// Given a range of intervals I1, I2, ..., In, maximum_gap() returns\n// the maximum length of an interval M that satisfies the following\n// properties:\n//\n// 1. M.left >= min(I1, I2, ..., In)\n// 2. M.right <= max(I1, I2, ..., In)\n// 3. intersection(interior(M), Ik) is the empty set for all k=1, ..., n\n// 4. length(M) is maximal\n//\n// where M.left and M.right denote the left and right extreme values\n// for the interval M, and length(M) is equal to M.right - M.left.\n//\n// If M does not exist (or, alternatively, M is identified as the\n// empty set), 0 is returned.\n//\n// The algorithm proceeds for performing a sweep: the left endpoints\n// are inserted into a min-priority queue with the priority being the\n// value of the endpoint. The sweep algorithm maintains an \"overlap\n// counter\" that counts the number of overlaping intervals at any\n// specific sweep-time value.\n// There are two types of events encountered during the sweep:\n// (a) a start event: the left endpoint of an interval is found.\n//     In this case the overlap count is increased by one and the\n//     right endpoint of the interval in inserted into the event queue\n// (b) an end event: the right endpoint of an interval is found.\n//     In this case the overlap count is decreased by one. If the\n//     updated overlap count is 0, then we could expect to have a gap\n//     in-between intervals. This gap is measured as the (absolute)\n//     distance of the current interval right endpoint (being\n//     processed) to the upcoming left endpoint of the next interval\n//     to be processed (if such an interval exists). If the measured\n//     gap is greater than the current maximum gap, it is recorded.\n// The initial maximum gap is initialized to 0. This value is returned\n// if no gap is found during the sweeping procedure.\n\ntemplate <typename RangeOfIntervals, typename T>\ninline typename boost::range_value<RangeOfIntervals>::type::difference_type\nmaximum_gap(RangeOfIntervals const& range_of_intervals,\n            T& max_gap_left, T& max_gap_right)\n{\n    typedef typename boost::range_value<RangeOfIntervals>::type interval_type;\n    typedef detail::max_interval_gap::sweep_event<interval_type> event_type;\n\n    // create a min-priority queue for the events\n    std::priority_queue\n        <\n            event_type,\n            std::vector<event_type>,\n            detail::max_interval_gap::event_greater<event_type>\n        > queue;\n\n    // define initialization and event-process visitors\n    detail::max_interval_gap::initialization_visitor init_visitor;\n    detail::max_interval_gap::event_visitor<event_type> sweep_visitor;\n\n    // perform the sweep\n    geometry::sweep(range_of_intervals,\n                    queue,\n                    init_visitor,\n                    sweep_visitor);\n\n    max_gap_left = sweep_visitor.max_gap_left();\n    max_gap_right = sweep_visitor.max_gap_right();\n    return sweep_visitor.max_gap();\n}\n\ntemplate <typename RangeOfIntervals>\ninline typename boost::range_value<RangeOfIntervals>::type::difference_type\nmaximum_gap(RangeOfIntervals const& range_of_intervals)\n{\n    typedef typename boost::remove_const\n        <\n            typename boost::remove_reference\n                <\n                    typename boost::range_value\n                        <\n                            RangeOfIntervals\n                        >::type::value_type\n                >::type\n        >::type value_type;\n\n    value_type left, right;\n\n    return maximum_gap(range_of_intervals, left, right);\n}\n\n\n}} // namespace boost::geometry\n\n#endif // BOOST_GEOMETRY_ALGORITHMS_DETAIL_MAX_INTERVAL_GAP_HPP\n", "meta": {"hexsha": "3e32cf4676a02e783966768631893138be7a7246", "size": 8429, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "deps/src/boost_1_65_1/boost/geometry/algorithms/detail/max_interval_gap.hpp", "max_stars_repo_name": "shreyasvj25/turicreate", "max_stars_repo_head_hexsha": "32e84ca16aef8d04aff3d49ae9984bd49326bffd", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 11356.0, "max_stars_repo_stars_event_min_datetime": "2017-12-08T19:42:32.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T16:55:25.000Z", "max_issues_repo_path": "deps/src/boost_1_65_1/boost/geometry/algorithms/detail/max_interval_gap.hpp", "max_issues_repo_name": "shreyasvj25/turicreate", "max_issues_repo_head_hexsha": "32e84ca16aef8d04aff3d49ae9984bd49326bffd", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2402.0, "max_issues_repo_issues_event_min_datetime": "2017-12-08T22:31:01.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-28T19:25:52.000Z", "max_forks_repo_path": "deps/src/boost_1_65_1/boost/geometry/algorithms/detail/max_interval_gap.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": 30.2114695341, "max_line_length": 78, "alphanum_fraction": 0.6574919919, "num_tokens": 1831, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6406358411176238, "lm_q2_score": 0.5312093733737563, "lm_q1q2_score": 0.34031176372086225}}
{"text": "#pragma once\n#include \"VimCommon.h\"\n#pragma warning (disable:4756)\n\n#include <iostream>\n#include <queue>\n\n#ifdef _OPENMP\n#include <omp.h>\n#endif // _OPENMP\n\n#ifndef _OPENMP\nint omp_get_num_procs(void) { return 1; }\nint omp_get_thread_num(void) { return 0; }\n#endif // _OPENMP\n\n#define _f3_(x, y, z) (float)(x), (float)(y), (float)(z)\n#define _i3_(x, y, z) (int)(x), (int)(y), (int)(z)\n#define _fp_ float*\n\n#define __v3minmax(__INOUT, __IN, __OP) {\\\n\t__INOUT.x = __OP(__INOUT.x, __IN.x);\\\n\t__INOUT.y = __OP(__INOUT.y, __IN.y);\\\n\t__INOUT.z = __OP(__INOUT.z, __IN.z);\\\n};\n\n#define EXB 2\n\nusing namespace vmobjects;\nusing namespace vmmath;\nusing namespace std;\n\ntemplate <typename T>\ninline T __ReadVoxel(const vmint3& idx, const int width_slice, const int exb, T** vol_slices)\n{\n\treturn vol_slices[idx.z + exb][idx.x + exb + (idx.y + exb) * width_slice];\n};\n\ntemplate <typename T>\ninline void __WriteVoxel(T v, const vmint3& idx, const int width_slice, const int exb, T** vol_slices)\n{\n\tvol_slices[idx.z + exb][idx.x + exb + (idx.y + exb) * width_slice] = v;\n};\n\ninline vmint3 __MultInt3(const vmint3* pi3_0, const vmint3* pi3_1)\n{\n\treturn vmint3(pi3_0->x * pi3_1->x, pi3_0->y * pi3_1->y, pi3_0->z * pi3_1->z);\n}\n\ninline bool __SafeCheck(const vmint3& idx, const vmint3& vol_size)\n{\n\tvmint3 max_dir = idx - (vol_size - vmint3(1, 1, 1));\n\tvmint3 mult_dot = __MultInt3(&max_dir, &idx);\n\treturn !(mult_dot.x > 0 || mult_dot.y > 0 || mult_dot.z > 0);\n}\n\ntemplate <typename T>\ninline T __Safe__ReadVoxel(const vmint3& idx, const vmint3& vol_size, const int width_slice, const int exb, T** vol_slices, const T bnd_v = 0)\n{\n\treturn __SafeCheck(idx, vol_size) ? __ReadVoxel<T>(idx, width_slice, exb, vol_slices) : (T)bnd_v;\n};\n\ninline float __TrilinearInterpolation(float v_0, float v_1, float v_2, float v_3, float v_4, float v_5, float v_6, float v_7,\n\tconst vmfloat3& ratio)\n{\n\tfloat v01 = v_0 * (1.f - ratio.x) + v_1 * ratio.x;\n\tfloat v23 = v_2 * (1.f - ratio.x) + v_3 * ratio.x;\n\tfloat v0123 = v01 * (1.f - ratio.y) + v23 * ratio.y;\n\tfloat v45 = v_4 * (1.f - ratio.x) + v_5 * ratio.x;\n\tfloat v67 = v_6 * (1.f - ratio.x) + v_7 * ratio.x;\n\tfloat v4567 = v45 * (1.f - ratio.y) + v67 * ratio.y;\n\treturn v0123 * (1.f - ratio.z) + v4567 * ratio.z;\n}\n\ntemplate <typename T>\ninline float __Safe_TrilinearSample(const vmfloat3& pos_sample, const vmint3& vol_size, const int width_slice, const int exb, T** vol_slices, const T bnd_v = 0)\n{\n\tvmfloat3 __pos_sample = pos_sample + vmfloat3(1000.f, 1000.f, 1000.f); // SAFE //\n\tvmint3 idx_sample = vmint3((int)__pos_sample.x, (int)__pos_sample.y, (int)__pos_sample.z);\n\tvmfloat3 ratio = vmfloat3((__pos_sample.x) - (float)(idx_sample.x), (__pos_sample.y) - (float)(idx_sample.y), (__pos_sample.z) - (float)(idx_sample.z));\n\tidx_sample -= vmint3(1000, 1000, 1000);\n\n\tfloat v0, v1, v2, v3, v4, v5, v6, v7;\n\tv0 = (float)__Safe__ReadVoxel<T>(idx_sample + vmint3(0, 0, 0), vol_size, width_slice, exb, vol_slices, bnd_v);\n\tv1 = (float)__Safe__ReadVoxel<T>(idx_sample + vmint3(1, 0, 0), vol_size, width_slice, exb, vol_slices, bnd_v);\n\tv2 = (float)__Safe__ReadVoxel<T>(idx_sample + vmint3(0, 1, 0), vol_size, width_slice, exb, vol_slices, bnd_v);\n\tv3 = (float)__Safe__ReadVoxel<T>(idx_sample + vmint3(1, 1, 0), vol_size, width_slice, exb, vol_slices, bnd_v);\n\tv4 = (float)__Safe__ReadVoxel<T>(idx_sample + vmint3(0, 0, 1), vol_size, width_slice, exb, vol_slices, bnd_v);\n\tv5 = (float)__Safe__ReadVoxel<T>(idx_sample + vmint3(1, 0, 1), vol_size, width_slice, exb, vol_slices, bnd_v);\n\tv6 = (float)__Safe__ReadVoxel<T>(idx_sample + vmint3(0, 1, 1), vol_size, width_slice, exb, vol_slices, bnd_v);\n\tv7 = (float)__Safe__ReadVoxel<T>(idx_sample + vmint3(1, 1, 1), vol_size, width_slice, exb, vol_slices, bnd_v);\n\treturn __TrilinearInterpolation(v0, v1, v2, v3, v4, v5, v6, v7, ratio);\n};\n\ntemplate <typename T>\ninline vmfloat3 __Safe_Gradient_by_Samples(const vmfloat3& pos_sample, const vmint3& vol_size, const vmfloat3& dir_x, const vmfloat3& dir_y, const vmfloat3& dir_z, const int width_slice, const int exb, T** vol_slices)\n{\n\tfloat v_XL = __Safe_TrilinearSample<T>(pos_sample - dir_x, vol_size, width_slice, exb, vol_slices);\n\tfloat v_XR = __Safe_TrilinearSample<T>(pos_sample + dir_x, vol_size, width_slice, exb, vol_slices);\n\tfloat v_YL = __Safe_TrilinearSample<T>(pos_sample - dir_y, vol_size, width_slice, exb, vol_slices);\n\tfloat v_YR = __Safe_TrilinearSample<T>(pos_sample + dir_y, vol_size, width_slice, exb, vol_slices);\n\tfloat v_ZL = __Safe_TrilinearSample<T>(pos_sample - dir_z, vol_size, width_slice, exb, vol_slices);\n\tfloat v_ZR = __Safe_TrilinearSample<T>(pos_sample + dir_z, vol_size, width_slice, exb, vol_slices);\n\tfloat g_x = v_XR - v_XL;\n\tfloat g_y = v_YR - v_YL;\n\tfloat g_z = v_ZR - v_ZL;\n\treturn vmfloat3(g_x, g_y, g_z) * 0.5f;\n}\n\n#define SGRAD(p, vinfo) __Safe_Gradient_by_Samples(p, vinfo.vol_size, \\\n\tvinfo.vec_grad_dirs[0], vinfo.vec_grad_dirs[1], vinfo.vec_grad_dirs[2], \\\n\t\tvinfo.width_slice, EXB, vinfo.vol_slices)\n\ntemplate <typename T>\nvoid ___debugout(std::string str, T v)\n{\n\tstd::cout << str.c_str() << std::to_string(v).c_str() << std::endl;\n}\n\ntemplate <typename T>\nstruct __VolSampleInfo\n{\n\t//ushort** vol_slices_filtered;\n\tT** vol_slices;\n\tvmint3 vol_size;\n\tint width_slice;\n\tvmmat44f mat_ws2vs;\n\tvmmat44f mat_vs2ws;\n\tvmfloat3 vec_grad_dirs[3];\n\tfloat min_sample_dist;\n\n\t__VolSampleInfo() : vol_slices(NULL), //vol_slices_origin(NULL),\n\t\tvol_size(vmint3()), width_slice(0), mat_ws2vs(NULL), mat_vs2ws(NULL) {};\n\n\t__VolSampleInfo(T** _vol_slices, vmint3 _vol_size,\n\t\tint _width_slice, vmmat44f _mat_ws2vs, vmmat44f _mat_vs2ws,\n\t\tvmfloat3 _vec_grad_dirs[3], float _min_sample_dist) : vol_slices(_vol_slices),\n\t\tvol_size(_vol_size), width_slice(_width_slice), mat_ws2vs(_mat_ws2vs), mat_vs2ws(_mat_vs2ws), min_sample_dist(_min_sample_dist)\n\t{\n\t\t//vol_slices_filtered = _vol_slices;\n\t\tvec_grad_dirs[0] = _vec_grad_dirs[0];\n\t\tvec_grad_dirs[1] = _vec_grad_dirs[1];\n\t\tvec_grad_dirs[2] = _vec_grad_dirs[2];\n\t}\n};\n\ntemplate <typename T>\n__VolSampleInfo<T> Get_volsample_info(VmVObjectVolume* pCVolume, const double sample_dist_scale)\n{\n\tif (pCVolume == NULL) return __VolSampleInfo<T>();\n\n\tvmfloat3 vecVoxelGradDirs[3];// = { vmfloat3(1, 0, 0), vmfloat3(0, 1, 0), vmfloat3(0, 0, 1) };\n\tVolumeData* volArchive = pCVolume->GetVolumeData();\n\tfloat min_dist_sample = (float)min(min(volArchive->vox_pitch.x, volArchive->vox_pitch.y), volArchive->vox_pitch.z);\n\tfTransformVector(&vecVoxelGradDirs[0], &vmfloat3(min_dist_sample, 0, 0), &pCVolume->GetMatrixWS2OSf());\n\tfTransformVector(&vecVoxelGradDirs[1], &vmfloat3(0, min_dist_sample, 0), &pCVolume->GetMatrixWS2OSf());\n\tfTransformVector(&vecVoxelGradDirs[2], &vmfloat3(0, 0, min_dist_sample), &pCVolume->GetMatrixWS2OSf());\n\n\tvmfloat3 vecVoxelGradDirs_unit[3] = {\n\t\tvecVoxelGradDirs[0] * (float)sample_dist_scale,\n\t\tvecVoxelGradDirs[1] * (float)sample_dist_scale,\n\t\tvecVoxelGradDirs[2] * (float)sample_dist_scale };\n\n\tVolumeData *volArchiveSample = pCVolume->GetVolumeData();\n\tvmint3 volSize = volArchiveSample->vol_size;\n\tvmint3 volSizeEx = volArchiveSample->bnd_size;\n\tint widthSamplePitch = volSize.x + volSizeEx.x * 2;\n\n\treturn __VolSampleInfo<T>((T**)volArchiveSample->vol_slices,\n\t\tvolSize, widthSamplePitch, pCVolume->GetMatrixWS2OSf(), pCVolume->GetMatrixOS2WSf(), vecVoxelGradDirs_unit, min_dist_sample);\n};\n\n#include \"../nanoflann.hpp\"\ntemplate <typename T, typename TT>\nstruct PointCloud\n{\n\t//public:\n\tconst TT* pts;\n\tconst size_t num_pts;\n\tPointCloud(const TT* _pts, const size_t _num_pts) : pts(_pts), num_pts(_num_pts) { }\n\tPointCloud(const vector<TT>& vtr_pts) : pts(&vtr_pts[0]), num_pts(vtr_pts.size()) { }\n\n\t// Must return the number of data points\n\tinline size_t kdtree_get_point_count() const { return num_pts; }\n\n\t// Returns the distance between the vector \"p1[0:size-1]\" and the data point with index \"idx_p2\" stored in the class:\n\tinline T kdtree_distance(const T *p1, const size_t idx_p2, size_t) const\n\t{\n\t\tconst T d0 = p1[0] - pts[idx_p2].x;\n\t\tconst T d1 = p1[1] - pts[idx_p2].y;\n\t\tconst T d2 = p1[2] - pts[idx_p2].z;\n\t\treturn d0 * d0 + d1 * d1 + d2 * d2;\n\t}\n\n\t// Returns the dim'th component of the idx'th point in the class:\n\t// Since this is inlined and the \"dim\" argument is typically an immediate value, the\n\t//  \"if/else's\" are actually solved at compile time.\n\tinline T kdtree_get_pt(const size_t idx, int dim) const\n\t{\n\t\tif (dim == 0) return pts[idx].x;\n\t\telse if (dim == 1) return pts[idx].y;\n\t\telse return pts[idx].z;\n\t}\n\n\t// Optional bounding-box computation: return false to default to a standard bbox computation loop.\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.\n\t//   Look at bb.size() to find out the expected dimensionality (e.g. 2 or 3 for point clouds)\n\ttemplate <class BBOX>\n\tbool kdtree_get_bbox(BBOX&) const { return false; }\n};\n\ntypedef nanoflann::KDTreeSingleIndexAdaptor<\n\tnanoflann::L2_Simple_Adaptor<float, PointCloud<float, vmfloat3> >,\n\tPointCloud<float, vmfloat3>,\n\t3 // dim \n> kd_tree_t;\n\nvoid make_band(__VolSampleInfo<char>& band_info, const int v_low, const int v_high, const __VolSampleInfo<ushort>& vol_info_outside, const __VolSampleInfo<ushort>& vol_info_inside)\n{\n\tconst int clip_bnd = 2;\n#pragma omp parallel for num_threads( omp_get_num_procs() )\n\tfor (int z = 0; z < band_info.vol_size.z; z++)\n\t\tfor (int y = 0; y < band_info.vol_size.y; y++)\n\t\t\tfor (int x = 0; x < band_info.vol_size.x; x++)\n\t\t\t{\n\t\t\t\tif (x < clip_bnd || y < clip_bnd || z < clip_bnd\n\t\t\t\t\t|| x >= band_info.vol_size.x - clip_bnd\n\t\t\t\t\t|| y >= band_info.vol_size.y - clip_bnd\n\t\t\t\t\t|| z >= band_info.vol_size.z - clip_bnd)\n\t\t\t\t\tcontinue;\n\t\t\t\tint v_out = __ReadVoxel(vmint3(x, y, z), vol_info_outside.width_slice, EXB, vol_info_outside.vol_slices);\n\t\t\t\tint v_in = __ReadVoxel(vmint3(x, y, z), vol_info_inside.width_slice, EXB, vol_info_inside.vol_slices);\n\t\t\t\tif (v_in > v_high) __WriteVoxel((char)-1, vmint3(x, y, z), band_info.width_slice, EXB, band_info.vol_slices);\n\t\t\t\telse if (v_out < v_low) __WriteVoxel((char)1, vmint3(x, y, z), band_info.width_slice, EXB, band_info.vol_slices);\n\t\t\t}\n}\n\ntemplate <typename T>\nvoid get_isosurface_vtx(set<tuple<float, float, float>>& voxel_pts_set,\n\tconst float isovalue, const uint sampleoffset, const __VolSampleInfo<T>& vol_info)\n{\n\tauto __read_v = [&](vmint3& idx)\n\t{\n\t\tidx.x = min(idx.x, vol_info.vol_size.x - 1);\n\t\tidx.y = min(idx.y, vol_info.vol_size.y - 1);\n\t\tidx.z = min(idx.z, vol_info.vol_size.z - 1);\n\t\treturn (float)__ReadVoxel(idx, vol_info.width_slice, EXB, vol_info.vol_slices);\n\t};\n\n\tconst float offset = (float)sampleoffset;\n\tfor (int z = 0; z <= vol_info.vol_size.z; z += sampleoffset)\n\t{\n\t\tfor (int y = 0; y <= vol_info.vol_size.y; y += sampleoffset)\n\t\t{\n\t\t\tfor (int x = 0; x <= vol_info.vol_size.x; x += sampleoffset)\n\t\t\t{\n\t\t\t\t// sample at 8 nodes of a cell\n\t\t\t\tfloat samplevalues[4] = {\n\t\t\t\t\t__read_v(vmint3(x + 0, y + 0, z + 0)),\n\t\t\t\t\t__read_v(vmint3(x + sampleoffset, y + 0, z + 0)),\n\t\t\t\t\t__read_v(vmint3(x + 0, y + sampleoffset, z + 0)),\n\t\t\t\t\t__read_v(vmint3(x + 0, y + 0, z + sampleoffset)),\n\t\t\t\t};\n\n\t\t\t\tbool isOriSmall = samplevalues[0] < isovalue;\n\t\t\t\tbool isEdgeXSmall = samplevalues[1] < isovalue;\n\t\t\t\tbool isEdgeYSmall = samplevalues[2] < isovalue;\n\t\t\t\tbool isEdgeZSmall = samplevalues[3] < isovalue;\n\n\t\t\t\tif (isOriSmall != isEdgeXSmall)\n\t\t\t\t{\n\t\t\t\t\tfloat ratio = (float)(isovalue - samplevalues[0]) / (float)(samplevalues[1] - samplevalues[0]);\n\t\t\t\t\tvmfloat3 pos = vmfloat3((float)x + ratio * offset, (float)y, (float)z);\n\t\t\t\t\tvoxel_pts_set.insert(tuple<float, float, float>(pos.x, pos.y, pos.z));\n\t\t\t\t}\n\t\t\t\tif (isOriSmall != isEdgeYSmall)\n\t\t\t\t{\n\t\t\t\t\tfloat ratio = (float)(isovalue - samplevalues[0]) / (float)(samplevalues[2] - samplevalues[0]);\n\t\t\t\t\tvmfloat3 pos = vmfloat3((float)x, (float)y + ratio * offset, (float)z);\n\t\t\t\t\tvoxel_pts_set.insert(tuple<float, float, float>(pos.x, pos.y, pos.z));\n\t\t\t\t}\n\t\t\t\tif (isOriSmall != isEdgeZSmall)\n\t\t\t\t{\n\t\t\t\t\tfloat ratio = (float)(isovalue - samplevalues[0]) / (float)(samplevalues[3] - samplevalues[0]);\n\t\t\t\t\tvmfloat3 pos = vmfloat3((float)x, (float)y, (float)z + ratio * offset);\n\t\t\t\t\tvoxel_pts_set.insert(tuple<float, float, float>(pos.x, pos.y, pos.z));\n\t\t\t\t}\n\t\t\t} // for x\n\t\t} // for y\n\t} //for z\n}\n\nvoid simplify_points_ugrid(vector<vmfloat3>& pos_simplified_pts, vmfloat3& aabb_diff, const vector<vmfloat3>& pos_pts, const float grid_length)\n{\n\tuint num_pts = (uint)pos_pts.size();\n\tvmfloat3 aabb_min(FLT_MAX), aabb_max(-FLT_MAX);\n\tfor (uint i = 0; i < num_pts; i++)\n\t{\n\t\tconst vmfloat3& pos_pt = pos_pts[i];\n\t\t__v3minmax(aabb_min, pos_pt, min);\n\t\t__v3minmax(aabb_max, pos_pt, max);\n\t}\n\taabb_diff = aabb_max - aabb_min;\n\tvmint3 aabb_size = vmint3(aabb_diff / grid_length) + vmint3(1);\n\tuint* index_map = new uint[aabb_size.x * aabb_size.y * aabb_size.z];\n\tmemset(index_map, 0, sizeof(uint) * aabb_size.x * aabb_size.y * aabb_size.z);\n\n\tuint count = 0;\n\tfor (uint i = 0; i < num_pts; i++)\n\t{\n\t\tconst vmfloat3& pos_pt = pos_pts[i];\n\t\tvmfloat3 pos_cell = (pos_pt - aabb_min) / grid_length;\n\t\tvmint3 idx_cell = pos_cell;\n\t\tuint addr = (uint)idx_cell.x + (uint)(idx_cell.y * aabb_size.x) + (uint)idx_cell.z * (uint)(aabb_size.x * aabb_size.y);\n\t\tuint prev_idx = index_map[addr];\n\t\tif (prev_idx == 0)\n\t\t{\n\t\t\tindex_map[addr] = i + 1;\n\t\t\tcount++;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tconst vmfloat3& pos_prev_pt = pos_pts[prev_idx];\n\t\t\tvmfloat3 pos_prev_cell = (pos_prev_pt - aabb_min) / grid_length;\n\t\t\tvmint3 idx_prev_cell = pos_prev_cell;\n\n\t\t\tvmfloat3 cell_pos = pos_cell - (vmfloat3)idx_cell - vmfloat3(0.5f);\n\t\t\tvmfloat3 prev_cell_pos = pos_prev_cell - (vmfloat3)idx_prev_cell - vmfloat3(0.5f);\n\t\t\tif (fLengthVectorSq(&cell_pos) < fLengthVectorSq(&prev_cell_pos))\n\t\t\t\tindex_map[addr] = i + 1;\n\t\t}\n\t}\n\n\tpos_simplified_pts.assign(count, vmfloat3());\n\tuint count_idx = 0;\n\tfor (uint i = 0; i < (uint)aabb_size.x * (uint)aabb_size.y * (uint)aabb_size.z; i++)\n\t{\n\t\tuint idx = index_map[i];\n\t\tif (idx > 0)\n\t\t\tpos_simplified_pts[count_idx++] = pos_pts[idx - 1];\n\t}\n\n\tVMSAFE_DELETEARRAY(index_map);\n}\n\nint OtsuThresholdValue(ullong* pullHistogramValues, int histo_size, int begin_idx, int end_idx)\n{\n\tdouble total_elements = 0;\n\tdouble sum1 = 0;\n\n\t//for (int i = begin_idx; i <= end_idx; i++)\n\tfor (int i = 0; i < histo_size; i++)\n\t{\n\t\ttotal_elements += (double)pullHistogramValues[i];\n\t\tsum1 += (double)i * (double)pullHistogramValues[i];\n\t}\n\n\tdouble sumB = 0;\n\tdouble wB = 0;\n\tdouble _maximum = 0;\n\tbegin_idx = min(begin_idx, histo_size - 1);\n\tend_idx = min(end_idx, histo_size - 1);\n\n\tint otsuThreshold = 0;\n\tfor (int i = begin_idx; i <= end_idx; i++)\n\t{\n\t\twB += (double)pullHistogramValues[i];\n\t\tdouble wF = total_elements - wB;\n\t\tif (wB == 0 || wF == 0)\n\t\t\tcontinue;\n\n\t\tsumB += (double)i * (double)pullHistogramValues[i];\n\t\tdouble mF = (sum1 - sumB) / wF;\n\t\tdouble btn = wB * wF * ((sumB / wB) - mF) * ((sumB / wB) - mF);\n\t\tif (btn >= _maximum)\n\t\t{\n\t\t\totsuThreshold = i;\n\t\t\t_maximum = btn;\n\t\t}\n\t}\n\n\treturn otsuThreshold;\n}\n\nvoid raytraversal_gradmax(std::vector<vmfloat3>& lmax_pts,\n\tconst std::vector<vmfloat3>& pos_pts, const std::vector<vmfloat3>& dir_pts,\n\tconst int num_maxrc_steps,\n\tconst float dir_scale, /*const bool use_quadinterpolation, const bool use_consistent_dir,*/\n\tconst float min_v, const float max_v,\n\tconst __VolSampleInfo<char>& band_info,\n\tconst __VolSampleInfo<ushort>& vol_info)\n{\n\tauto __gradient = [&](const vmfloat3& pos_vs)\n\t{\n\t\treturn SGRAD(pos_vs, vol_info);\n\t\t//return -__Safe_TrilinearSample_T(pos_vs, mask_Info.vol_size, mask_Info.width_slice, 0, mask_Info.grad_slices, vmfloat3());\n\t};\n\n\tint num_pts = (int)pos_pts.size();\n\tlmax_pts.assign(num_pts, vmfloat3(0, 0, 0));\n\t//std::vector<__float3> tmp_lmax_pts(num_pts, __float3(FLT_MAX, FLT_MAX, FLT_MAX));\n\tvmfloat3 vol_size_f(_f3_(vol_info.vol_size.x, vol_info.vol_size.y, vol_info.vol_size.z));\n\tconst float safe_bnd = 2.f;\n\n#pragma omp parallel for num_threads( omp_get_num_procs() )\n\tfor (int i = 0; i < num_pts; i++)\n\t{\n\t\tconst vmfloat3& dir = dir_pts[i];\n\t\tif (fLengthVectorSq(&dir) < FLT_EPSILON)\n\t\t{\n\t\t\tlmax_pts[i] = pos_pts[i];\n\t\t\tcontinue;\n\t\t}\n\n\t\tfloat max_gmsq = -1;\n\t\tconst vmfloat3& pos_start = pos_pts[i];\n\t\tvmfloat3 pos_lmax = pos_start;\n\n\t\tfor (int j = 0; j < num_maxrc_steps; j++)\n\t\t{\n\t\t\tvmfloat3 pos_cur = pos_start + dir * dir_scale * (float)j, pos_cur_vs;\n\t\t\tfTransformPoint(&pos_cur_vs, &pos_cur, &vol_info.mat_ws2vs);\n\n\t\t\tif (pos_cur_vs.x < safe_bnd || pos_cur_vs.y < safe_bnd || pos_cur_vs.z < safe_bnd\n\t\t\t\t|| pos_cur_vs.x >= vol_size_f.x - safe_bnd\n\t\t\t\t|| pos_cur_vs.y >= vol_size_f.y - safe_bnd\n\t\t\t\t|| pos_cur_vs.z >= vol_size_f.z - safe_bnd)\n\t\t\t\tcontinue;\n\n\t\t\tif (j > 1 && band_info.vol_slices) // j > 1 is for safe zone\n\t\t\t{\n\t\t\t\tfloat mask_value = __Safe_TrilinearSample<char>(pos_cur_vs, band_info.vol_size, band_info.width_slice, EXB, band_info.vol_slices, -1);\n\t\t\t\tif (mask_value == 1.f || mask_value == -1.f)\n\t\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tvmfloat3 grad = SGRAD(pos_cur_vs, vol_info);\n\t\t\tfloat sample_v = __Safe_TrilinearSample<ushort>(pos_cur_vs, vol_info.vol_size, vol_info.width_slice, EXB, vol_info.vol_slices, -1);\n\t\t\tif (fDotVector(&dir, &grad) >= 0 || sample_v  < min_v || sample_v > max_v)\n\t\t\t\tcontinue;\n\n\t\t\tfloat gmsq = fLengthVectorSq(&grad);\n\t\t\tif (max_gmsq < gmsq)\n\t\t\t{\n\t\t\t\tmax_gmsq = gmsq;\n\t\t\t\tpos_lmax = pos_cur;\n\t\t\t}\n\t\t}\n\n//#define QUADRATIC\n#ifdef QUADRATIC\n\t\tauto quadratic_maxsampler = [](const vmfloat3& pos_a, const vmfloat3& pos_c, const float gm_a, const float gm_b, const float gm_c)\n\t\t{\n\t\t\tvmfloat3 pos_max;\n\t\t\tfloat _div_ = (gm_a + gm_c) - 2.f * gm_b;\n\t\t\tif (_div_ == 0)\n\t\t\t{\n\t\t\t\tpos_max = pos_a;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tfloat t = (3.f * gm_a + gm_c - 4.f * gm_b) / (4.f * _div_);\n\t\t\t\tpos_max = pos_a + min(max(t, 0.f), 1.f) * (pos_c - pos_a);\n\t\t\t}\n\t\t\treturn pos_max;\n\t\t};\n\t\tif (max_gmsq > 0)\n\t\t{\n\t\t\tvmfloat3 pos_a = pos_lmax - dir * dir_scale, pos_a_vs;\n\t\t\tvmfloat3 pos_c = pos_lmax + dir * dir_scale, pos_c_vs;\n\t\t\tfTransformPoint(&pos_a_vs, &pos_a, &vol_info.mat_ws2vs);\n\t\t\tfTransformPoint(&pos_c_vs, &pos_c, &vol_info.mat_ws2vs);\n\t\t\tfloat edge_a = fLengthVector(&SGRAD(pos_a_vs, vol_info));\n\t\t\tfloat edge_c = fLengthVector(&SGRAD(pos_c_vs, vol_info));\n\t\t\tlmax_pts[i] = quadratic_maxsampler(pos_a, pos_c, edge_a, sqrt(max_gmsq), edge_c);\n\t\t}\n\t\telse\n\t\t\tlmax_pts[i] = pos_lmax;\n#else\n\t\tlmax_pts[i] = pos_lmax;\n#endif\n\t}\n}\n\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n#include <Eigen/LU>\n#include <Eigen/Cholesky>\n#include <Eigen/Householder>\n#include <Eigen/SVD>\n#include <Eigen/QR>\n#include <Eigen/Eigenvalues>\n#include <Eigen/Sparse>\n#include <Eigen/Dense>\n#include <Eigen/Eigen>\n#define _DIM_ 3\nauto __construct_covariance_matrix = [](const Eigen::VectorXd& cov) -> Eigen::MatrixXd\n{\n\tEigen::MatrixXd m(_DIM_, _DIM_);\n\n\tfor (std::size_t i = 0; i < _DIM_; ++i)\n\t{\n\t\tfor (std::size_t j = i; j < _DIM_; ++j)\n\t\t{\n\t\t\tm(i, j) = static_cast<float>(cov[(_DIM_ * i) + j - ((i * (i + 1)) / 2)]);\n\n\t\t\tif (i != j)\n\t\t\t\tm(j, i) = m(i, j);\n\t\t}\n\t}\n\n\treturn m;\n};\nauto __diagonalize_selfadjoint_matrix = [](Eigen::MatrixXd& m, Eigen::MatrixXd& eigenvectors, Eigen::VectorXd& eigenvalues) -> bool\n{\n\tEigen::SelfAdjointEigenSolver<Eigen::MatrixXd> eigensolver;\n\n\t//eigensolver.computeDirect(m);\n\teigensolver.compute(m);\n\n\tif (eigensolver.info() != Eigen::Success)\n\t\treturn false;\n\n\teigenvalues = eigensolver.eigenvalues();\n\teigenvectors = eigensolver.eigenvectors();\n\n\treturn true;\n};\nauto __diagonalize_selfadjoint_covariance_matrix = [&]\n(const Eigen::VectorXd& cov, float* eigenvalues, vmfloat3* eigenvectors)\n{\n\tEigen::MatrixXd m = __construct_covariance_matrix(cov);\n\n\t// Diagonalizing the matrix\n\tEigen::VectorXd eigenvalues_;\n\tEigen::MatrixXd eigenvectors_;\n\tbool res = __diagonalize_selfadjoint_matrix(m, eigenvectors_, eigenvalues_);\n\n\tif (res)\n\t{\n\t\tfor (std::size_t i = 0; i < _DIM_; ++i)\n\t\t{\n\t\t\teigenvalues[i] = static_cast<float>(eigenvalues_[i]);\n\n\t\t\tfor (std::size_t j = 0; j < _DIM_; ++j)\n\t\t\t\t((float*)eigenvectors)[_DIM_*i + j] = static_cast<float>(eigenvectors_(j, i));\n\t\t}\n\t}\n\n\treturn res;\n};\n\nfloat estimate_shape_variation(const vmfloat3& pos_src, const vmfloat3& nrl_src, const vmfloat3* pos_pts, const vmfloat3* nrl_pts, const kd_tree_t& kdt_index, const float kernel_radius)\n{\n\tfloat sv = 1.f;\n\tconst float r_sq = kernel_radius * kernel_radius;\n\n\tstatic nanoflann::SearchParams params;\n\tparams.sorted = false;\n\n\tstd::vector<std::pair<size_t, float>> ret_matches;\n\tconst int nMatches = (int)kdt_index.radiusSearch((float*)&pos_src, r_sq, ret_matches, params);\n\n\tstd::vector<int> valid_idx_pts;\n\tfor (int k = 0; k < nMatches; k++)\n\t{\n\t\tint idx_neighbor = (int)ret_matches[k].first;\n\t\tvmfloat3 nrl_nb = nrl_pts[idx_neighbor];\n\t\tif (nrl_src.x * nrl_nb.x + nrl_src.y * nrl_nb.y + nrl_src.z * nrl_nb.z >= 0)\n\t\t\tvalid_idx_pts.push_back(idx_neighbor);\n\t}\n\n\tconst int num_valid_nb_pts = (int)valid_idx_pts.size();\n\tif (num_valid_nb_pts < 3)\n\t\treturn 1; // treated as an outlier\n\n\tvmdouble3 pos_centroid = vmdouble3();\n\tdouble ft_num_ptns = (double)nMatches;\n\tfor (int k = 0; k < nMatches; k++)\n\t{\n\t\tint idx_nb = (int)ret_matches[k].first;\n\t\tvmdouble3 pos_nb = pos_pts[idx_nb];\n\t\tpos_centroid.x += ((double)pos_nb.x / ft_num_ptns);\n\t\tpos_centroid.y += ((double)pos_nb.y / ft_num_ptns);\n\t\tpos_centroid.z += ((double)pos_nb.z / ft_num_ptns);\n\t}\n\n\tvmfloat3 pos_centroid_f = vmfloat3((float)pos_centroid.x, (float)pos_centroid.y, (float)pos_centroid.z);\n\t//Eigen::VectorXd evecs(6); evecs << 0, 0, 0, 0, 0, 0;\n\tEigen::VectorXd evecs = Eigen::VectorXd::Zero(6);\n\tfor (int k = 0; k < nMatches; k++)\n\t{\n\t\tint idx_nb = (int)ret_matches[k].first;\n\t\tvmfloat3 pos_nb = pos_pts[idx_nb];\n\t\tvmfloat3 diff = vmfloat3(pos_centroid_f.x - pos_nb.x, pos_centroid_f.y - pos_nb.y, pos_centroid_f.z - pos_nb.z);\n\t\tevecs(0) += diff.x * diff.x;\n\t\tevecs(1) += diff.x * diff.y;\n\t\tevecs(2) += diff.x * diff.z;\n\t\tevecs(3) += diff.y * diff.y;\n\t\tevecs(4) += diff.y * diff.z;\n\t\tevecs(5) += diff.z * diff.z;\n\t}\n\n\tfloat eigenvalues[3];\n\tvmfloat3 eigenvectors[3];\n\tif (__diagonalize_selfadjoint_covariance_matrix(evecs, eigenvalues, eigenvectors))\n\t{\n\t\t// eigenvalues[0] is smallest\n\t\tfloat sum_egv = eigenvalues[0] + eigenvalues[1] + eigenvalues[2];\n\t\tsv = eigenvalues[0] / sum_egv * 3.f;\n\t}\n\n\treturn sv;\n}\n\nfloat estimate_orient_variation(const vmfloat3& pos_src, const __VolSampleInfo<ushort>& vol_info, const float kernel_radius)\n{\n\tauto __sample_v = [&](const vmfloat3& pos_vs)\n\t{\n\t\treturn __Safe_TrilinearSample(pos_vs, vol_info.vol_size, vol_info.width_slice, EXB, vol_info.vol_slices);\n\t};\n\n\tfloat ov = 1.f;\n\tfloat voxel_kernel = kernel_radius / vol_info.min_sample_dist;\n\tvmfloat3 dirs[3] = { vol_info.vec_grad_dirs[0] * 0.5f * voxel_kernel, vol_info.vec_grad_dirs[1] * 0.5f * voxel_kernel, vol_info.vec_grad_dirs[2] * 0.5f * voxel_kernel };\n\n\tvmfloat3 pos_sample_vs;\n\tfTransformPoint(&pos_sample_vs, &pos_src, &vol_info.mat_ws2vs);\n\n\tfloat v = __sample_v(pos_sample_vs);\n\tfloat v_XXR = __sample_v(pos_sample_vs + 2.f * dirs[0]);\n\tfloat v_XXL = __sample_v(pos_sample_vs - 2.f * dirs[0]);\n\tfloat v_YYR = __sample_v(pos_sample_vs + 2.f * dirs[1]);\n\tfloat v_YYL = __sample_v(pos_sample_vs - 2.f * dirs[1]);\n\tfloat v_ZZR = __sample_v(pos_sample_vs + 2.f * dirs[2]);\n\tfloat v_ZZL = __sample_v(pos_sample_vs - 2.f * dirs[2]);\n\tfloat v_XR = __sample_v(pos_sample_vs + dirs[0]);\n\tfloat v_XL = __sample_v(pos_sample_vs - dirs[0]);\n\tfloat v_YR = __sample_v(pos_sample_vs + dirs[1]);\n\tfloat v_YL = __sample_v(pos_sample_vs - dirs[1]);\n\tfloat v_ZR = __sample_v(pos_sample_vs + dirs[2]);\n\tfloat v_ZL = __sample_v(pos_sample_vs - dirs[2]);\n\tfloat v_XRYR = __sample_v(pos_sample_vs + dirs[0] + dirs[1]);\n\tfloat v_XRYL = __sample_v(pos_sample_vs + dirs[0] - dirs[1]);\n\tfloat v_XLYR = __sample_v(pos_sample_vs - dirs[0] + dirs[1]);\n\tfloat v_XLYL = __sample_v(pos_sample_vs - dirs[0] - dirs[1]);\n\tfloat v_YRZR = __sample_v(pos_sample_vs + dirs[1] + dirs[2]);\n\tfloat v_YRZL = __sample_v(pos_sample_vs + dirs[1] - dirs[2]);\n\tfloat v_YLZR = __sample_v(pos_sample_vs - dirs[1] + dirs[2]);\n\tfloat v_YLZL = __sample_v(pos_sample_vs - dirs[1] - dirs[2]);\n\tfloat v_XRZR = __sample_v(pos_sample_vs + dirs[0] + dirs[2]);\n\tfloat v_XRZL = __sample_v(pos_sample_vs + dirs[0] - dirs[2]);\n\tfloat v_XLZR = __sample_v(pos_sample_vs - dirs[0] + dirs[2]);\n\tfloat v_XLZL = __sample_v(pos_sample_vs - dirs[0] - dirs[2]);\n\n\tvmmat44f H;\n\n\tvmfloat3 g = vmfloat3(v_XR - v_XL, v_YR - v_YL, v_ZR - v_ZL);\n\tH[0][0] = v_XXR - 2.f * v + v_XXL; // f_xx\n\tH[0][1] = (v_XRYR - v_XLYR - v_XRYL + v_XLYL);\t//f_xy\n\tH[0][2] = (v_XRZR - v_XLZR - v_XRZL + v_XLZL);\t//f_xz\n\tH[1][0] = H[0][1];\n\tH[1][1] = v_YYR - 2.f * v + v_YYL;\t\t\t\t\t\t\t\t//f_yy\n\tH[1][2] = (v_YRZR - v_YLZR - v_YRZL + v_YLZL);\t//f_yz\n\tH[2][0] = H[0][2];\n\tH[2][1] = H[1][2];\n\tH[2][2] = v_ZZR - 2.f * v + v_ZZL;\t\t\t\t\t\t\t\t//f_zz\n\tH[3][3] = 1;\n\t//\n\tfloat gm = fLengthVector(&g);\n\tif (gm > FLT_EPSILON)\n\t{\n\t\tvmfloat3 n = -g / gm;\n\t\tvmmat44f nnT, P;\n\t\tnnT[0][0] = n.x*n.x;\n\t\tnnT[0][1] = n.x*n.y;\n\t\tnnT[0][2] = n.x*n.z;\n\t\tnnT[1][0] = n.y*n.x;\n\t\tnnT[1][1] = n.y*n.y;\n\t\tnnT[1][2] = n.y*n.z;\n\t\tnnT[2][0] = n.z*n.x;\n\t\tnnT[2][1] = n.z*n.y;\n\t\tnnT[2][2] = n.z*n.z;\n\t\tnnT[3][3] = 0;\n\t\tP[0][0] = 1.0f;\n\t\tP[1][1] = 1.0f;\n\t\tP[2][2] = 1.0f;\n\t\tP[3][3] = 1.0f;\n\t\tP = P - nnT;\n\t\t/////////////////////////\n\t\tvmmat44f FF = (-P * H) / (float)gm * nnT;\n\t\tfloat fFlowCurv = sqrt(FF[0][0] * FF[0][0] + FF[0][1] * FF[0][1] + FF[0][2] * FF[0][2]\n\t\t\t+ FF[1][0] * FF[1][0] + FF[1][1] * FF[1][1] + FF[1][2] * FF[1][2]\n\t\t\t+ FF[2][0] * FF[2][0] + FF[2][1] * FF[2][1] + FF[2][2] * FF[2][2]);\n\t\tov = min(fFlowCurv, 1.0f);\n\t}\n\treturn ov;\n}\n\nvoid compute_geometry_info(vector<vmfloat3>& nrl_pts, vector<vmfloat2>& gm_gc_pts, vector<vmfloat3>& pos_pts, const float kernel_radius, const __VolSampleInfo<ushort>& vol_info)\n{\n\tint num_pts = (int)pos_pts.size();\n\tnrl_pts.assign(num_pts, vmfloat3());\n\tgm_gc_pts.assign(num_pts, vmfloat2());\n\n#pragma omp parallel for num_threads( omp_get_num_procs() )\n\tfor (int i = 0; i < num_pts; i++)\n\t{\n\t\tvmfloat3 pos_src = pos_pts[i], pos_vs;\n\t\tfTransformPoint(&pos_vs, &pos_src, &vol_info.mat_ws2vs);\n\t\tnrl_pts[i] = -SGRAD(pos_vs, vol_info);\n\t\tfloat leng = fLengthVector(&nrl_pts[i]);\n\t\tnrl_pts[i] = leng > FLT_EPSILON ? nrl_pts[i] / leng : vmfloat3();\n\t\tgm_gc_pts[i].x = leng;\n\t}\n\n\tPointCloud<float, vmfloat3> pc_kdt(pos_pts);\n\tkd_tree_t kdt(3, pc_kdt, nanoflann::KDTreeSingleIndexAdaptorParams(10));\n\tkdt.buildIndex();\n\n#pragma omp parallel for num_threads( omp_get_num_procs() )\n\tfor (int i = 0; i < num_pts; i++)\n\t{\n\t\tvmfloat3 pos_src = pos_pts[i];\n\t\tfloat sv = min(estimate_shape_variation(pos_src, nrl_pts[i], &pos_pts[0], &nrl_pts[0], kdt, kernel_radius), 1.f);\n\t\tfloat ov = min(estimate_orient_variation(pos_src, vol_info, kernel_radius), 1.f);\n\t\tgm_gc_pts[i].y = max(sv, ov);\n\t}\n}\n\nvoid clustering(std::map<int, std::vector<int>>& map_clusters, const std::vector<vmfloat3>& pos_pts, const kd_tree_t& kdt, const std::vector<vmfloat3>& nrl_pts, const float e_c)\n{\n\tint num_pts = (int)pos_pts.size();\n\tif (num_pts == 0) return;\n\n\tnanoflann::SearchParams params;\n\tparams.sorted = false;\n\tconst float r_sq = e_c * e_c;\n\n\tauto is_side_angle = [](const vmfloat3& p, const vmfloat3& q, const float eps)\n\t{\n\t\tfloat angle = std::acos(max(min(fDotVector(&p, &q), 1.f), -1.f)); // 0 to PI\n\t\treturn (angle > VM_PI / 2.f - eps) && (angle < VM_PI / 2.f + eps);\n\t};\n\tauto subs_norm = [](const vmfloat3& p, const vmfloat3& q)\n\t{\n\t\tvmfloat3 v = vmfloat3(p.x - q.x, p.y - q.y, p.z - q.z);\n\t\tfNormalizeVector(&v, &v);\n\t\treturn v;\n\t};\n\n\tstd::vector<int> cluster_map_pts;\n\tcluster_map_pts.assign(num_pts, 0);\n\n\tint count_id_cluster = 1;\n\tfor (int i = 0; i < num_pts; i++)\n\t{\n\t\tif (cluster_map_pts[i] != 0) continue;\n\n\t\tstd::vector<int> index_cluster_pts;\n\t\tstd::queue<int> que_for_process;\n\n\t\tque_for_process.push(i);\n\t\tindex_cluster_pts.push_back(i);\n\t\tcluster_map_pts[i] = count_id_cluster;\n\n\t\tint error_prop_count = 0;\n\t\twhile (!que_for_process.empty())\n\t\t{\n\t\t\tif (error_prop_count++ > 50000000)\n\t\t\t{\n\t\t\t\tcout << \"ERROR, num conf. clusters : \" << map_clusters.size() << endl;\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tint source_idx = que_for_process.front();\n\t\t\tque_for_process.pop();\n\n\t\t\tconst vmfloat3& pos_src = pos_pts[source_idx];\n\t\t\tconst vmfloat3& nrl_src = nrl_pts[source_idx];\n\n\t\t\tstd::vector<std::pair<size_t, float> >   ret_matches;\n\t\t\tconst int nMatches = (int)kdt.radiusSearch((float*)&pos_src, r_sq, ret_matches, params);\n\n\t\t\tfor (int j = 0; j < nMatches; j++)\n\t\t\t{\n\t\t\t\tint idx_nb = (int)ret_matches[j].first;\n\t\t\t\tvmfloat3 pos_nb = pos_pts[idx_nb];\n\t\t\t\tif (cluster_map_pts[idx_nb] == 0\n\t\t\t\t\t&& is_side_angle(nrl_src, subs_norm(pos_nb, pos_src), VM_fPI / 6.f)\n\t\t\t\t\t)\n\t\t\t\t{\n\t\t\t\t\tque_for_process.push(idx_nb);\n\t\t\t\t\tindex_cluster_pts.push_back(idx_nb);\n\t\t\t\t\tcluster_map_pts[idx_nb] = count_id_cluster;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif (index_cluster_pts.size() > 0)\n\t\t\tmap_clusters[count_id_cluster++] = index_cluster_pts;\n\t}\n}\n\nvoid estimating_hole(bool& is_boundary, bool& is_src_vector_set, vmfloat3& vector_o,\n\tdouble(&btw_angles_max)[4], double(&btw_angles_min)[4],\n\tconst std::vector<std::pair<size_t, float> > ret_matches,\n\tconst std::vector<vmfloat3>& pos_pts, const vmfloat3& pos_src, const vmfloat3& nrl_src,\n\tconst float thres_susceptibility_sq)\n{\n\tconst int nMatches = (int)ret_matches.size();\n\tfor (int j = 0; j < nMatches; j++)\n\t{\n\t\tint idx_nb = (int)ret_matches[j].first;\n\n\t\tconst vmfloat3& pos_nb = pos_pts[idx_nb];\n\n\t\t// plane is defined by pos_src and nrl_src\n\t\tvmfloat3 _v = pos_nb - pos_src;\n\t\tvmfloat3 _tv = nrl_src * fDotVector(&_v, &nrl_src);\n\t\tvmfloat3 pos_nb_on_plane = pos_nb - _tv;\n\t\tvmfloat3 vec_on_plane = pos_nb_on_plane - pos_src;\n\t\tdouble length_sq = fLengthVectorSq(&vec_on_plane);\n\n\t\tif (length_sq > thres_susceptibility_sq)\n\t\t{\n\t\t\tvec_on_plane /= (float)std::sqrt(length_sq);\n\n\t\t\tif (!is_src_vector_set)\n\t\t\t{\n\t\t\t\tis_src_vector_set = true;\n\t\t\t\tvector_o = vec_on_plane;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tdouble btw_angle = std::acos(max(min(fDotVector(&vector_o, &vec_on_plane), 1.f), -1.f)); // 0 to PI\n\t\t\t\tvmfloat3 cross_v;\n\t\t\t\tfCrossDotVector(&cross_v, &vec_on_plane, &vector_o);\n\t\t\t\tif (fDotVector(&nrl_src, &cross_v) < 0)\n\t\t\t\t\tbtw_angle = 2 * VM_fPI - btw_angle;\n\t\t\t\t//ordered_angles.insert((float)btw_angle);\n\n\t\t\t\tif (btw_angle < VM_fPI * 0.5)\n\t\t\t\t{\n\t\t\t\t\tbtw_angles_max[0] = max(btw_angle, btw_angles_max[0]);\n\t\t\t\t\t//btw_angles_min[0] = min(btw_angle, btw_angles_min[0]);//\n\t\t\t\t}\n\t\t\t\telse if (btw_angle < VM_fPI)\n\t\t\t\t{\n\t\t\t\t\tbtw_angles_max[1] = max(btw_angle, btw_angles_max[1]);\n\t\t\t\t\tbtw_angles_min[1] = min(btw_angle, btw_angles_min[1]);\n\t\t\t\t}\n\t\t\t\telse if (btw_angle < VM_fPI * 1.5)\n\t\t\t\t{\n\t\t\t\t\tbtw_angles_max[2] = max(btw_angle, btw_angles_max[2]);\n\t\t\t\t\tbtw_angles_min[2] = min(btw_angle, btw_angles_min[2]);\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\t//btw_angles_max[3] = max(btw_angle, btw_angles_max[3]); //\n\t\t\t\t\tbtw_angles_min[3] = min(btw_angle, btw_angles_min[3]);\n\t\t\t\t}\n\n\t\t\t\tif (btw_angles_min[1] - btw_angles_max[0] < VM_fPI / 2.\n\t\t\t\t\t&& btw_angles_min[2] - btw_angles_max[1] < VM_fPI / 2.\n\t\t\t\t\t&& btw_angles_min[3] - btw_angles_max[2] < VM_fPI / 2.)\n\t\t\t\t{\n\t\t\t\t\tis_boundary = false;\n\t\t\t\t\tbreak; // for (int j = 0; j < nMatches; j++)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\nvoid detecting_boundary(std::vector<int>& bnd_id_pts, const std::vector<vmfloat3>& pos_pts, const std::vector<vmfloat3>& nrl_pts,\n\tconst kd_tree_t& kdt_index, const float e_b, const bool consistent_dir_neighbors/*projecting except opposite directional points of the target poin*/)\n{\n\tfloat thres_susceptibility_sq = e_b * 0.01f;\n\tthres_susceptibility_sq *= thres_susceptibility_sq;\n\tint num_pts = (int)pos_pts.size();\n\n\tnanoflann::SearchParams params;\n\tparams.sorted = false;\n\tconst float r_sq = e_b * e_b;\n\t// params.eps\n\n\tbool* hole_flags = new bool[num_pts];\n\tZeroMemory(hole_flags, sizeof(bool) * num_pts);\n\n#pragma omp parallel for num_threads( omp_get_num_procs() )\n\tfor (int i = 0; i < num_pts; i++)\n\t{\n\t\tconst vmfloat3& pos_src = pos_pts[i];\n\t\tconst vmfloat3& nrl_src = nrl_pts[i];\n\n\t\tstd::vector<std::pair<size_t, float> >   ret_matches;\n\t\tconst int nMatches = (int)kdt_index.radiusSearch((float*)&pos_src, r_sq, ret_matches, params);\n\n\t\t//std::set<float> ordered_angles;\n\t\tbool is_src_vector_set = false;\n\t\tvmfloat3 vector_o;\n\n\t\tdouble btw_angles_max[4] = { -100000., -100000., -100000., -100000. };\n\t\tdouble btw_angles_min[4] = { 100000., 100000., 100000., 100000. };\n\t\tbool is_boundary = true;\n\t\t// criterion 2 angle criterion\n\t\tstd::vector<std::pair<size_t, float> >   dir_matches;\n\t\t{\n\t\t\tfor (int j = 0; j < nMatches; j++)\n\t\t\t{\n\t\t\t\tvmfloat3 nrl_nb = nrl_pts[ret_matches[j].first];\n\t\t\t\tif (fDotVector((vmfloat3*)&nrl_src, (vmfloat3*)&nrl_nb) >= 0 || !consistent_dir_neighbors)\n\t\t\t\t\tdir_matches.push_back(ret_matches[j]);\n\t\t\t}\n\t\t}\n\n\t\testimating_hole(is_boundary, is_src_vector_set, vector_o,\n\t\t\tbtw_angles_max, btw_angles_min, dir_matches, pos_pts, pos_src, nrl_src, thres_susceptibility_sq);\n\n\t\t// store boundary result\n\t\tif (is_boundary) hole_flags[i] = true;\n\t}\n\n\tfor (int i = 0; i < num_pts; i++)\n\t\tif (hole_flags[i]) bnd_id_pts.push_back(i);\n\n\tdelete[] hole_flags;\n}\n\n\n#define RANGE_SURF_STEP_MAX_NUM 10 \n#define SURFACE_REFINEMENT_NUM 5 \nvoid relocate_to_target_densities(vmfloat3* pos_relocated_pts,\n\tconst vmfloat3* pos_pts, const vmfloat3* nrl_pts, const float* densities_pts, const int num_pts,\n\tconst float sample_dist, const __VolSampleInfo<ushort>& vol_info)\n{\n\tauto __sample_v = [&](const vmfloat3& pos_vs)\n\t{\n\t\treturn __Safe_TrilinearSample(pos_vs, vol_info.vol_size, vol_info.width_slice, EXB, vol_info.vol_slices);\n\t};\n\n\tauto __traverse_serach_dstv = [&__sample_v, &vol_info](vmfloat3& pos_dst, const vmfloat3& pos_start, const vmfloat3& vec_sample, const float dst_v, const bool from_lower)\n\t{\n\t\tfor (int j = 1; j < RANGE_SURF_STEP_MAX_NUM; j++)\n\t\t{\n\t\t\tvmfloat3 pos_sample = pos_start + vec_sample * (float)j, pos_sample_vs;\n\t\t\tfTransformPoint(&pos_sample_vs, &pos_sample, &vol_info.mat_ws2vs);\n\t\t\tfloat sample_v = __sample_v(pos_sample_vs);\n\n\t\t\tif (\n\t\t\t\t(sample_v > dst_v && from_lower)\n\t\t\t\t|| (sample_v < dst_v && !from_lower)\n\t\t\t\t)\n\t\t\t{\n\t\t\t\t// requires boundary-fitting\n\t\t\t\tvmfloat3 pos_S = pos_sample - vec_sample;\n\t\t\t\tvmfloat3 pos_E = pos_sample;\n\t\t\t\tvmfloat3 pos_O = pos_S;\n\t\t\t\tfor (uint k = 0; k < SURFACE_REFINEMENT_NUM; k++)\n\t\t\t\t{\n\t\t\t\t\tvmfloat3 pos_bis = (pos_S + pos_E) * 0.5f, pos_bis_vs;\n\t\t\t\t\tfTransformPoint(&pos_bis_vs, &pos_bis, &vol_info.mat_ws2vs);\n\t\t\t\t\tsample_v = __sample_v(pos_bis_vs);\n\n\t\t\t\t\tif (\n\t\t\t\t\t\t(sample_v > dst_v && from_lower)\n\t\t\t\t\t\t|| (sample_v < dst_v && !from_lower))\n\t\t\t\t\t\tpos_E = pos_bis;\n\t\t\t\t\telse\n\t\t\t\t\t\tpos_S = pos_bis;\n\t\t\t\t}\n\n\t\t\t\tpos_dst = pos_S;\n\t\t\t\treturn true;\n\t\t\t}\n\t\t} // for (uint j = 1; j < RANGE_SURF_STEP_MAX_NUM; j++)\n\t\treturn false;\n\t};\n\n\t//pos_relocated_pts.clear();\n\t//pos_relocated_pts.assign(num_pts, vmfloat3());\n\n#pragma omp parallel for num_threads( omp_get_num_procs() )\n\tfor (int i = 0; i < num_pts; i++)\n\t{\n\t\tconst vmfloat3& pos_sample = pos_pts[i];\n\t\tconst vmfloat3& nrl_sample = nrl_pts[i];\n\t\tvmfloat3 pos_sample_vs;\n\t\tfloat dst_v = densities_pts[i];\n\t\tif (dst_v == 7777777)\n\t\t{\n\t\t\tpos_relocated_pts[i] = pos_sample;\n\t\t\tcontinue; // magic number exception\n\t\t}\n\t\tfTransformPoint(&pos_sample_vs, &pos_sample, &vol_info.mat_ws2vs);\n\t\tfloat sample_v = __sample_v(pos_sample_vs);\n\n\t\tvmfloat3 pos_dst_0, pos_dst_1;\n\t\tbool ret_0 = __traverse_serach_dstv(pos_dst_0, pos_sample, nrl_sample * sample_dist, dst_v, sample_v < dst_v);\n\t\tbool ret_1 = __traverse_serach_dstv(pos_dst_1, pos_sample, -nrl_sample * sample_dist, dst_v, sample_v < dst_v);\n\t\tif (ret_0 && ret_1)\n\t\t{\n\t\t\tpos_relocated_pts[i] = fLengthVectorSq(&(pos_sample - pos_dst_0)) < fLengthVectorSq(&(pos_sample - pos_dst_1)) ? pos_dst_0 : pos_dst_1;\n\t\t}\n\t\telse if (ret_0)\n\t\t{\n\t\t\tpos_relocated_pts[i] = pos_dst_0;\n\t\t}\n\t\telse if (ret_1)\n\t\t{\n\t\t\tpos_relocated_pts[i] = pos_dst_1;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tpos_relocated_pts[i] = pos_sample;\n\t\t}\n\t} // for (uint i = 0; i < numVoxels; i++)\n}\n\n//#include <opencv2/highgui.hpp>\n// ui work\nvoid register_pobj(VmVObjectPrimitive& pobj, const vector<vmfloat3>& pos_pts, const vector<vmfloat3>& nrl_pts, const vector<vmfloat3>* ptr_clr_pts)\n{\n\tPrimitiveData vtx_data;\n\tvtx_data.is_ccw = true; // NA //\n\tvtx_data.is_stripe = false; // NA//\n\tvtx_data.check_redundancy = true; // NA //\n\tvtx_data.ptype = PrimitiveTypePOINT;\n\tvtx_data.idx_stride = 1;\n\tvtx_data.num_vtx = (uint)pos_pts.size();\n\tvtx_data.num_prims = vtx_data.num_vtx;\n\n\tvmfloat3* buf_vtx_pos = new vmfloat3[vtx_data.num_vtx];\n\tvmfloat3* buf_nrl_pos = new vmfloat3[vtx_data.num_vtx];\n\tvmfloat3* buf_clr_pos = new vmfloat3[vtx_data.num_vtx];\n\tmemcpy(buf_vtx_pos, &pos_pts[0], sizeof(vmfloat3) * vtx_data.num_vtx);\n\tmemcpy(buf_nrl_pos, &nrl_pts[0], sizeof(vmfloat3) * vtx_data.num_vtx);\n\tif (ptr_clr_pts)\n\t{\n\t\tmemcpy(buf_clr_pos, &ptr_clr_pts->at(0), sizeof(vmfloat3) * vtx_data.num_vtx);\n\t}\n\telse\n\t{\n\t\tfor (uint i = 0; i < vtx_data.num_vtx; i++)\n\t\t\tbuf_clr_pos[i] = vmfloat3(1);\n\t}\n\n\tvtx_data.ReplaceOrAddVerticeDefinition(\"POSITION\", buf_vtx_pos);\n\tvtx_data.ReplaceOrAddVerticeDefinition(\"NORMAL\", buf_nrl_pos);\n\tvtx_data.ReplaceOrAddVerticeDefinition(\"TEXCOORD0\", buf_clr_pos); // special case //\n\tvtx_data.ComputeOrthoBoundingBoxWithCurrentValues();\n\n\tpobj.RegisterPrimitiveData(vtx_data);\n\tpobj.UpdateKDTree();\n\tpobj.RegisterCustomParameter(\"_bool_ApplyShadingFactors\", true);\n\tpobj.RegisterCustomParameter(\"_bool_CtModelerStep\", true);\n}\n\n#define COLORMAP_SIZE 1024\nvoid fill_jet_colormap(int* colorarray, int ary_size)\n{\n\tint prev_idx = 0;\n\n\tfloat gap = (float)ary_size / 4.f;\n\tvmfloat3 redf = vmfloat3(1.f, 0, 0);\n\tvmfloat3 greenf = vmfloat3(0, 1.f, 0);\n\tvmfloat3 bluef = vmfloat3(0, 0, 1.f);\n\n\tint index_1 = (int)(gap / 2.f + 0.5f);\n\tint index_2 = (int)(gap / 2.f + gap + 0.5f);\n\tint index_3 = (int)(gap / 2.f + 2 * gap + 0.5f);\n\tint index_4 = (int)(gap / 2.f + 3 * gap + 0.5f);\n\tint index_5 = ary_size;\n\n\tauto float3_2_int = [&](vmfloat3& c)\n\t{\n\t\tbyte r = (byte)__min(c.x * 255.f, 255.f);\n\t\tbyte g = (byte)__min(c.y * 255.f, 255.f);\n\t\tbyte b = (byte)__min(c.z * 255.f, 255.f);\n\t\treturn (r << 16) | (g << 8) | (b);\n\t};\n\n\tfor (int i = 0; i <= index_1; i++)\n\t{\n\t\tvmfloat3 clr = bluef * (0.5f + 0.5f * (float)i / (float)index_1);\n\t\tcolorarray[i] = float3_2_int(clr);\n\t}\n\tfor (int i = index_1; i <= index_2; i++)\n\t{\n\t\tfloat ratio = (float)(i - index_1) / (float)(index_2 - index_1);\n\t\tvmfloat3 clr = bluef + greenf * ratio;\n\t\tcolorarray[i] = float3_2_int(clr);\n\t}\n\tfor (int i = index_2; i <= index_3; i++)\n\t{\n\t\tfloat ratio = (float)(i - index_2) / (float)(index_3 - index_2);\n\t\tvmfloat3 clr = greenf + bluef * (1.f - ratio) + redf * ratio;\n\t\tcolorarray[i] = float3_2_int(clr);\n\t}\n\tfor (int i = index_3; i <= index_4; i++)\n\t{\n\t\tfloat ratio = (float)(i - index_3) / (float)(index_4 - index_3);\n\t\tvmfloat3 clr = redf + greenf * (1.f - ratio);\n\t\tcolorarray[i] = float3_2_int(clr);\n\t}\n\tfor (int i = index_4; i < index_5; i++)\n\t{\n\t\tvmfloat3 clr = redf * (1.f - 0.5f * (float)(i - index_4) / (float)(index_5 - index_4));\n\t\tcolorarray[i] = float3_2_int(clr);\n\t}\n}\n\nvoid fill_cool_colormap(int* colorarray, int ary_size)\n{\n\tint prev_idx = 0;\n\n\tfloat gap = (float)ary_size / 4.f;\n\tvmfloat3 pinkf = vmfloat3(1.f, 0, 1.f);\n\tvmfloat3 skyf = vmfloat3(0, 1.f, 1.f);\n\n\tauto float3_2_int = [&](vmfloat3& c)\n\t{\n\t\tbyte r = (byte)__min(c.x * 255.f, 255.f);\n\t\tbyte g = (byte)__min(c.y * 255.f, 255.f);\n\t\tbyte b = (byte)__min(c.z * 255.f, 255.f);\n\t\treturn (r << 16) | (g << 8) | (b);\n\t};\n\n\tfor (int i = 0; i < ary_size; i++)\n\t{\n\t\tfloat ratio = (float)(i) / (float)(ary_size);\n\t\tvmfloat3 clr = skyf * (1 - ratio) + pinkf * ratio;\n\t\tcolorarray[i] = float3_2_int(clr);\n\t}\n}\n\ninline void convert_int_to_float3(const int _color, vmfloat3& rgb)\n{\n\trgb.r = ((_color >> 16) & 0xFF) / 255.f;\n\trgb.g = ((_color >> 8) & 0xFF) / 255.f;\n\trgb.b = ((_color >> 0) & 0xFF) / 255.f;\n}\n\n\n//auto is_inside_box = [](vmfloat3& p, vmfloat3& bp, float bs)\n//{\n//\tvmfloat3 pos_min = bp - vmfloat3(bs);\n//\tvmfloat3 pos_max = bp + vmfloat3(bs);\n//\treturn p.x >= pos_min.x && p.x <= pos_max.x\n//\t\t&& p.y >= pos_min.y && p.y <= pos_max.y\n//\t\t&& p.z >= pos_min.z && p.z <= pos_max.z;\n//};\n//auto cout_f3 = [](string prefix, vmfloat3& p)\n//{\n//\tcout << prefix << p.x << \", \" << p.y << \", \" << p.z << endl;\n//};", "meta": {"hexsha": "725a70e13e622555128e655ae78f6def094ab10c", "size": 39938, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "isosurf modeler/helpers.hpp", "max_stars_repo_name": "korfriend/LocalIsosurfaceModeler", "max_stars_repo_head_hexsha": "6ca0080c24e1f7a6bdf27d915d653104c82f142c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-09-07T13:47:26.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-07T13:47:26.000Z", "max_issues_repo_path": "isosurf modeler/helpers.hpp", "max_issues_repo_name": "korfriend/LocalIsosurfaceModeler", "max_issues_repo_head_hexsha": "6ca0080c24e1f7a6bdf27d915d653104c82f142c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "isosurf modeler/helpers.hpp", "max_forks_repo_name": "korfriend/LocalIsosurfaceModeler", "max_forks_repo_head_hexsha": "6ca0080c24e1f7a6bdf27d915d653104c82f142c", "max_forks_repo_licenses": ["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.5185825411, "max_line_length": 217, "alphanum_fraction": 0.6793029195, "num_tokens": 13772, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6406358411176238, "lm_q2_score": 0.5312093733737562, "lm_q1q2_score": 0.3403117637208622}}
{"text": "#include<iostream>\n//#define EIGEN_USE_MKL_ALL\n#include\"basis.hpp\"\n#include\"operators.hpp\"\n#include\"diag.h\"\n#include\"tpoperators.hpp\"\n#include\"files.hpp\"\n#include\"timeev.hpp\"\n#include\"ETH.hpp\"\n#include<iomanip>\n#include <boost/program_options.hpp>\n\nusing namespace boost::program_options;\nint main(int argc, char *argv[])\n{\n  using namespace Eigen;\nusing namespace std;\nusing namespace Many_Body;\n  using Fermi_HubbardBasis= TensorProduct<ElectronBasis, ElectronBasis>;\n   using HolsteinBasis= TensorProduct<ElectronBasis, PhononBasis>;\n  using Mat= Operators::Mat;\n   using boost::program_options::value;\n   int M{};\n  int L{};\n  int i{};\n  int j{};\n    double T{};\n      double tot{};\n        double dt{};\n  double t0{};\n  double omega{};\n  double gamma{};\n  double cutoff{};\n  bool PB{};\n\n\n  std::string sM{};\n  std::string sL{};\n  std::string si{};\n  std::string sj{};\n  std::string star{};\n  std::string sT{};\n    std::string stot{};\n      std::string sdt{};\n  std::string st0{};\n  std::string somega{};\n  std::string sgamma{};\n  std::string starget{};\n  std::string scutoff{};\n  std::string sPB{};\n  std::string filename=\"SPexT\";\n  try\n  {\n    boost::program_options::options_description desc{\"Options\"};\n    desc.add_options()\n      (\"help,h\", \"Help screen\")\n      (\"L\", value(&L)->default_value(4), \"L\")\n      (\"i\", value(&i)->default_value(0), \"i\")\n      (\"j\", value(&j)->default_value(1), \"j\")\n      (\"T\", value(&T)->default_value(0.1), \"T\")\n      (\"M,m\", value(&M)->default_value(2), \"M\")\n      (\"tot\", value(&tot)->default_value(1.), \"tot\")\n      (\"dt\", value(&dt)->default_value(0.1), \"dt\")\n      (\"t0\", value(&t0)->default_value(1.), \"t0\")\n      (\"gam\", value(&gamma)->default_value(1.), \"gamma\")\n      (\"omg\", value(&omega)->default_value(1.), \"omega\")\n      (\"pb\", value(&PB)->default_value(0), \"pb\");\n  boost::program_options::variables_map vm;\n  boost::program_options::store(parse_command_line(argc, argv, desc), vm);\n  boost::program_options::notify(vm);\n\n  if (vm.count(\"help\"))\n      {std::cout << desc << '\\n'; return 0;}\n    else{\n      if (vm.count(\"L\"))\n      {      std::cout << \"L: \" << vm[\"L\"].as<int>() << '\\n';\n      \tsL=\"L\"+std::to_string(vm[\"L\"].as<int>());\n\tfilename+=sL;\n      }\n         if (vm.count(\"M\"))\n      {      std::cout << \"M: \" << vm[\"M\"].as<int>() << '\\n';\n      \tsM=\"M\"+std::to_string(vm[\"M\"].as<int>());\n\tfilename+=sM;\n      }\n\t   if (vm.count(\"i\"))\n      {      std::cout << \"i: \" << i << '\\n';\n      \tsi=\"i\"+std::to_string(i);\n\tfilename+=si;\n      }\n\t   if (vm.count(\"j\"))\n      {      std::cout << \"j: \" << j << '\\n';\n      \tsj=\"j\"+std::to_string(j);\n\tfilename+=sj;\n      }\n      \t if (vm.count(\"t0\"))\n      {      std::cout << \"t0: \" << vm[\"t0\"].as<double>() << '\\n';\n      \tst0=\"t0\"+std::to_string(vm[\"t0\"].as<double>()).substr(0, 3);\n      \tfilename+=st0;\n      }\n      \t \t if (vm.count(\"omg\"))\n      {      std::cout << \"omega: \" << vm[\"omg\"].as<double>() << '\\n';\n      \tsomega=\"omg\"+std::to_string(vm[\"omg\"].as<double>()).substr(0, 3);\n      \t\tfilename+=somega;\n      }\n\t\t \n      \t\t if (vm.count(\"gam\"))\n      {      std::cout << \"gamma: \" << vm[\"gam\"].as<double>() << '\\n';\n      \tsgamma=\"gam\"+std::to_string(vm[\"gam\"].as<double>()).substr(0, 3);\n      \t\tfilename+=sgamma;\n      }\n\t\t      \t\t if (vm.count(\"tot\"))\n      {      std::cout << \"tot: \" << vm[\"tot\"].as<double>() << '\\n';\n      \tstot=\"tot\"+std::to_string(vm[\"tot\"].as<double>()).substr(0, 3);\n      \t\tfilename+=stot;\n      }\n\t\t\t\t if (vm.count(\"dt\"))\n      {      std::cout << \"dt: \" << vm[\"dt\"].as<double>() << '\\n';\n      \tsdt=\"dt\"+std::to_string(vm[\"dt\"].as<double>()).substr(0, 3);\n      \t\tfilename+=sdt;\n      }\n\n      \t\t if (vm.count(\"T\"))\n      {      std::cout << \"T: \" << T << '\\n';\n      \tsT=\"T\"+std::to_string(vm[\"T\"].as<double>()).substr(0, 3);\n      \tfilename+=sT;\n      }\n\t\t if (vm.count(\"pb\"))\n      {      std::cout << \"PB: \" << vm[\"pb\"].as<bool>() << '\\n';\n      \tsPB=\"PB\"+std::to_string(vm[\"pb\"].as<bool>());\n      \t\tfilename+=sPB;\n      }\n      }\n    }\n  catch (const boost::program_options::error &ex)\n  {\n    std::cerr << ex.what() << '\\n';\n    return 0;\n  }\n  filename+=\".bin\";\n  double mean=0.5*L*M*omega;\n\n  // declaring the tensor products with 0 e, 1, e, 2 e\n    ElectronBasis e0( L, 0);\n  ElectronBasis e1( L, 1);\n  ElectronBasis e2( L, 2);\n  std::cout<< e2<<std::endl; \n  PhononBasis ph(L, M);\nHolsteinBasis TP0(e0, ph);\n      HolsteinBasis TP1(e1, ph);\n        HolsteinBasis TP2(e2, ph);\n\n\n   \t\t  std::cout<< TP1.dim << std::endl;     \n\t\t  //std::cout<< ph << std::endl;\n\t\t  //    std::cout<< e1 << std::endl;\n      Eigen::VectorXd eigenVals1(TP1.dim);\n      Eigen::VectorXd eigenVals2(TP2.dim);\n      Eigen::VectorXd eigenVals0(TP0.dim);\n      Mat H0=Operators::HolsteinHam(TP0, t0, omega, gamma, PB);\n      Mat H1=Operators::HolsteinHam(TP1, t0, omega, gamma, PB);\n      Mat H2=Operators::HolsteinHam(TP2, t0, omega, gamma, PB);\n    Eigen::MatrixXd HH0=Eigen::MatrixXd(H0);\n    Eigen::MatrixXd HH1=Eigen::MatrixXd(H1);\n    Eigen::MatrixXd HH2=Eigen::MatrixXd(H2);\n    //         std::cout<< HH<<std::endl;\n    //  Eigen::MatrixXd N=Eigen::MatrixXd(Eph);\n    Many_Body::diagMat(HH0, eigenVals0);\n\t  Many_Body::diagMat(HH1, eigenVals1);\n       Many_Body::diagMat(HH2, eigenVals2);\n       // \n       auto C2=Operators::CdagOperator(TP1, TP2, j,  PB);\n       auto C1=Operators::CdagOperator(TP1, TP0,i,  PB);\n       std::cout<<\"MIN E0 \"<<std::setprecision(15)<< eigenVals0(0)<< std::endl;\n     std::cout<<\"MIN E1 \"<<std::setprecision(15)<< eigenVals1(0)<< std::endl;\n     std::cout<<\"MIN E2 \"<<std::setprecision(15)<< eigenVals2(0)<< std::endl;\n     std::cout<< \" dim T0 \"<< TP0.dim<<std::endl;\n          std::cout<< \" dim T1 \"<< TP1.dim<<std::endl;\n\t       std::cout<< \" dim T2 \"<< TP2.dim<<std::endl;\n\n     // std::cout<< Eigen::MatrixXd(Cdag) << std::endl;\n     // std::cout<< std::endl;\n     // std::cout<<TP0<<std::endl;\n     //      std::cout<<TP1<<std::endl;\n\t       std::cout<< \"mat \"<< std::endl;\n\t       std::cout<< Eigen::MatrixXd(C1)*Eigen::MatrixXd(C1).transpose()<< std::endl;\n      std::cout<< \"endl \"<<std::endl;\n      std::cout<< Eigen::MatrixXd(C2) << std::endl;\n     // std::cout<< \"\\n\";\n     //  std::cout<< Eigen::MatrixXd(Operators::CdagOperator(TP1, TP0,1,  PB)) << std::endl;\n       int n=0;\n       Eigen::MatrixXcd evExpbeta=Eigen::MatrixXcd::Zero(eigenVals1.rows(), eigenVals1.rows());\n       double Z{0};\n       for(int k=0; k<eigenVals1.rows(); k++)\n\t {\n\t   double ex=std::exp(-(eigenVals1(k)-eigenVals1(0))/T);\n\t   evExpbeta(k, k)=std::complex<double>{std::exp(-(eigenVals1(k)-eigenVals1(0))/T), 0};\n\tZ+=ex;\n\t//\tsum+=ex*en;\n\t }\n       \n       //=TimeEv::EigenvalExponent(eigenVals1, -Many_Body::im*1./T);\n    \n     std::vector<double> time;\n     std::vector<std::complex<double>> cdagc;\n     std::vector<std::complex<double>> ccdag;\n     auto H1T=HH1.transpose();\n     auto H2T=HH2.transpose();\n       auto H0T=HH0.transpose();\n  //       while(n*dt<tot)\n  //       \t{\n     \t  \t  \n\n  //    \t    Eigen::MatrixXcd evExp1m=TimeEv::EigenvalExponent(eigenVals1, n*dt);\n  //      Eigen::MatrixXcd evExp1p=TimeEv::EigenvalExponent(eigenVals1, -n*dt);\n  //       Eigen::MatrixXcd evExp2m=TimeEv::EigenvalExponent(eigenVals2, n*dt);\n  //        Eigen::MatrixXcd evExp0p=TimeEv::EigenvalExponent(eigenVals0, -n*dt);\n\n  // \t auto CDAGC=(evExpbeta*H1T*C1*HH0*evExp0p*H0T*C1.adjoint()*HH1*evExp1m).trace()/Z;\n\t\n  // \t //.trace()/Z;\n  // \t\t     //*evExp1m).trace()/Z;\n  // \t \t auto CCDAG= ((evExpbeta*evExp1p*H1T*C2.adjoint()*HH2*evExp2m*H2T*C2*HH1)).trace()/Z;\n  // \t // std::cout<< \"shape2 \"<< CCDAG.rows() << \" x \"  << CCDAG.cols() << \" tr \"<< CCDAG.trace()<<std::endl;\n  // \t\t std::cout<<n*dt << \"\\t\"<< CCDAG<< \" and  \"<<CDAGC<< \"diff \"<< CCDAG+CDAGC<< std::endl;\n  // \t\t      //\tstd::cout<<n*dt << \"\\t\"<<  \" and  \"<<CCDAG<< \"  \"<< \"  sum  \" <<Z<<std::endl;\n  //      \t\t\t\t    time.push_back(n*dt);\n  //    \t\t\t\t    ccdag.push_back(CCDAG);\n  //    \t\t\t    cdagc.push_back(CDAGC);\n  // n++;\n\n  // \t \t}\n  // \tstd::cout<< ccdag.size() << \"  \"<< cdagc.size()<< std::endl;\n  //     bin_write(\"time\"+filename, time);\n  //     bin_write(\"CCDAG\"+filename, ccdag);\n  //     bin_write(\"CDAGC\"+filename, cdagc);\n  \n \n    // \t\t\t  int pb=PB;\n    // \t\t  \t  std::string Hs=\"H\";\n    // \t\t\t  std::string Ts=\"T\";\n    // \t\t\t  std::string phds=\"PHD\";\n\t  \n    // \t\t      bin_write(\"E\"+filename, Evec);\n    // \t\t      bin_write(\"Nph\"+filename, Ovec);\n    // \t\t      bin_write(\"EK\"+filename, Ovec2);\n    // \t\t      bin_write(\"nX\"+filename, Ovec3);\n    // \t\t      bin_write(\"temp\"+filename, Tr);\n  return 0;\n}\n \n", "meta": {"hexsha": "ce679cde8709a3fefed861ebde0d41e51334bacb", "size": 8549, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/holstFTSPexactSmart.cpp", "max_stars_repo_name": "jansendavid/many-body-lib", "max_stars_repo_head_hexsha": "eb8fcb2d61b4fdba1c1effaa706e3c298a17042b", "max_stars_repo_licenses": ["MIT"], "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/holstFTSPexactSmart.cpp", "max_issues_repo_name": "jansendavid/many-body-lib", "max_issues_repo_head_hexsha": "eb8fcb2d61b4fdba1c1effaa706e3c298a17042b", "max_issues_repo_licenses": ["MIT"], "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/holstFTSPexactSmart.cpp", "max_forks_repo_name": "jansendavid/many-body-lib", "max_forks_repo_head_hexsha": "eb8fcb2d61b4fdba1c1effaa706e3c298a17042b", "max_forks_repo_licenses": ["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.0597609562, "max_line_length": 110, "alphanum_fraction": 0.5383085741, "num_tokens": 2818, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6859494678483918, "lm_q2_score": 0.49609382947091946, "lm_q1q2_score": 0.34029529832844807}}
{"text": "// This file is part of Eigen, a lightweight C++ template library\n// for linear algebra.\n//\n// Copyright (C) 2009 Gael Guennebaud <g.gael@free.fr>\n//\n// This Source Code Form is subject to the terms of the Mozilla\n// Public License v. 2.0. If a copy of the MPL was not distributed\n// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.\n\n#ifndef ALIGNED_EIGEN_TYPES_HPP\n#define ALIGNED_EIGEN_TYPES_HPP\n\n#include <Eigen/Geometry>\n\nnamespace Eigen {\n\n/**\n * \\defgroup Aligned4Vector3_Module Aligned vector3 module\n *\n * \\code\n * #include <unsupported/Eigen/Aligned4Vector3>\n * \\endcode\n */\n//@{\n\n/** \\class Aligned4Vector3\n *\n * \\brief A vectorization friendly 3D vector\n *\n * This class represents a 3D vector internally using a 4D vector\n * such that vectorization can be seamlessly enabled. Of course,\n * the same result can be achieved by directly using a 4D vector.\n * This class makes this process simpler.\n *\n */\n// TODO specialize Cwise\ntemplate <typename _Scalar>\nclass Aligned4Vector3;\n\nnamespace internal {\ntemplate <typename _Scalar>\nstruct traits<Aligned4Vector3<_Scalar> > : traits<Matrix<_Scalar, 3, 1, 0, 3, 1> > {};\n}  // namespace internal\n\ntemplate <typename _Scalar>\nclass Aligned4Vector3 : public MatrixBase<Aligned4Vector3<_Scalar> > {\n  typedef Matrix<_Scalar, 4, 1> CoeffType;\n  CoeffType m_coeffs;\n\n public:\n  typedef MatrixBase<Aligned4Vector3<_Scalar> > Base;\n  EIGEN_DENSE_PUBLIC_INTERFACE(Aligned4Vector3)\n  using Base::operator*;\n\n  inline Index rows() const { return 3; }\n  inline Index cols() const { return 1; }\n\n  Scalar* data() { return m_coeffs.data(); }\n  const Scalar* data() const { return m_coeffs.data(); }\n  Index innerStride() const { return 1; }\n  Index outerStride() const { return m_coeffs.outerStride(); }\n\n  inline const Scalar& coeff(Index row, Index col) const { return m_coeffs.coeff(row, col); }\n\n  inline Scalar& coeffRef(Index row, Index col) { return m_coeffs.coeffRef(row, col); }\n\n  inline const Scalar& coeff(Index index) const { return m_coeffs.coeff(index); }\n\n  inline Scalar& coeffRef(Index index) { return m_coeffs.coeffRef(index); }\n\n  inline Aligned4Vector3(const Scalar& x, const Scalar& y, const Scalar& z) : m_coeffs(x, y, z, Scalar(1)) {}\n\n  inline Aligned4Vector3() : m_coeffs(Scalar(0), Scalar(0), Scalar(0), Scalar(1)) {}\n\n  inline Aligned4Vector3(const Aligned4Vector3& other) : Base(), m_coeffs(other.m_coeffs) {}\n\n  template <typename XprType, int Size = XprType::SizeAtCompileTime>\n  struct generic_assign_selector {};\n\n  template <typename XprType>\n  struct generic_assign_selector<XprType, 4> {\n    inline static void run(Aligned4Vector3& dest, const XprType& src) {\n      dest.m_coeffs = src;\n      dest.m_coeffs.w() = Scalar(1);\n    }\n  };\n\n  template <typename XprType>\n  struct generic_assign_selector<XprType, 3> {\n    inline static void run(Aligned4Vector3& dest, const XprType& src) {\n      dest.m_coeffs.template head<3>() = src;\n      dest.m_coeffs.w() = Scalar(1);\n    }\n  };\n\n  template <typename Derived>\n  inline Aligned4Vector3(const MatrixBase<Derived>& other) {\n    generic_assign_selector<Derived>::run(*this, other.derived());\n  }\n\n  inline Aligned4Vector3& operator=(const Aligned4Vector3& other) {\n    m_coeffs = other.m_coeffs;\n    return *this;\n  }\n\n  template <typename Derived>\n  inline Aligned4Vector3& operator=(const MatrixBase<Derived>& other) {\n    generic_assign_selector<Derived>::run(*this, other.derived());\n    return *this;\n  }\n\n  inline Aligned4Vector3 operator+(const Aligned4Vector3& other) const {\n    return Aligned4Vector3(m_coeffs + other.m_coeffs);\n  }\n\n  inline Aligned4Vector3& operator+=(const Aligned4Vector3& other) {\n    m_coeffs += other.m_coeffs;\n    return *this;\n  }\n\n  inline Aligned4Vector3 operator-(const Aligned4Vector3& other) const {\n    return Aligned4Vector3(m_coeffs - other.m_coeffs);\n  }\n\n  inline Aligned4Vector3 operator-=(const Aligned4Vector3& other) {\n    m_coeffs -= other.m_coeffs;\n    return *this;\n  }\n\n  inline Aligned4Vector3 operator*(const Scalar& s) const { return Aligned4Vector3(m_coeffs * s); }\n\n  inline friend Aligned4Vector3 operator*(const Scalar& s, const Aligned4Vector3& vec) {\n    return Aligned4Vector3(s * vec.m_coeffs);\n  }\n\n  inline Aligned4Vector3& operator*=(const Scalar& s) {\n    m_coeffs *= s;\n    return *this;\n  }\n\n  inline Aligned4Vector3 operator/(const Scalar& s) const { return Aligned4Vector3(m_coeffs / s); }\n\n  inline Aligned4Vector3& operator/=(const Scalar& s) {\n    m_coeffs /= s;\n    return *this;\n  }\n\n  inline Scalar dot(const Aligned4Vector3& other) const {\n    eigen_assert(m_coeffs.w() == Scalar(1));\n    eigen_assert(other.m_coeffs.w() == Scalar(1));\n    return m_coeffs.dot(other.m_coeffs) - Scalar(1);\n  }\n\n  inline void normalize() { m_coeffs /= norm(); }\n\n  inline Aligned4Vector3 normalized() const { return Aligned4Vector3(m_coeffs / norm()); }\n\n  inline Scalar sum() const {\n    eigen_assert(m_coeffs.w() == Scalar(1));\n    return m_coeffs.sum() - Scalar(1);\n  }\n\n  inline Scalar squaredNorm() const {\n    eigen_assert(m_coeffs.w() == Scalar(1));\n    return m_coeffs.squaredNorm() - Scalar(1);\n  }\n\n  inline Scalar norm() const {\n    using std::sqrt;\n    return sqrt(squaredNorm());\n  }\n\n  inline Aligned4Vector3 cross(const Aligned4Vector3& other) const {\n    return Aligned4Vector3(m_coeffs.cross3(other.m_coeffs));\n  }\n\n  template <typename Derived>\n  inline bool isApprox(const MatrixBase<Derived>& other, RealScalar eps = NumTraits<Scalar>::dummy_precision()) const {\n    return m_coeffs.template head<3>().isApprox(other, eps);\n  }\n\n  CoeffType& coeffs() { return m_coeffs; }\n  const CoeffType& coeffs() const { return m_coeffs; }\n};\n\nnamespace internal {\n\ntemplate <typename _Scalar>\nstruct eval<Aligned4Vector3<_Scalar>, Dense> {\n  typedef const Aligned4Vector3<_Scalar>& type;\n};\n\ntemplate <typename Scalar>\nstruct evaluator<Aligned4Vector3<Scalar> > : evaluator<Matrix<Scalar, 4, 1> > {\n  typedef Aligned4Vector3<Scalar> XprType;\n  typedef evaluator<Matrix<Scalar, 4, 1> > Base;\n\n  evaluator(const XprType& m) : Base(m.coeffs()) {}\n};\n\n}  // namespace internal\n\n//@}\n\n}  // namespace Eigen\n\n#endif  // ALIGNED_EIGEN_TYPES\n", "meta": {"hexsha": "4e3dc0f15c908b663ae14dfacbf107d1fa60acb7", "size": 6147, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/arc_utilities/aligned_eigen_types.hpp", "max_stars_repo_name": "UM-ARM-Lab/arc_utilities", "max_stars_repo_head_hexsha": "e21bd5062983b25e61e33f832ec66b937540ba10", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2017-01-09T14:37:14.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-16T08:02:08.000Z", "max_issues_repo_path": "include/arc_utilities/aligned_eigen_types.hpp", "max_issues_repo_name": "UM-ARM-Lab/arc_utilities", "max_issues_repo_head_hexsha": "e21bd5062983b25e61e33f832ec66b937540ba10", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 62.0, "max_issues_repo_issues_event_min_datetime": "2017-05-25T16:52:38.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-08T20:05:09.000Z", "max_forks_repo_path": "include/arc_utilities/aligned_eigen_types.hpp", "max_forks_repo_name": "UM-ARM-Lab/arc_utilities", "max_forks_repo_head_hexsha": "e21bd5062983b25e61e33f832ec66b937540ba10", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2017-08-04T13:06:17.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-16T08:02:11.000Z", "avg_line_length": 29.5528846154, "max_line_length": 119, "alphanum_fraction": 0.710102489, "num_tokens": 1656, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6859494550081925, "lm_q2_score": 0.4960938294709195, "lm_q1q2_score": 0.34029529195850444}}
{"text": "//==============================================================================\n//         Copyright 2003 - 2011 LASMEA UMR 6602 CNRS/Univ. Clermont II\n//         Copyright 2009 - 2011 LRI    UMR 8623 CNRS/Univ Paris Sud XI\n//\n//          Distributed under the Boost Software License, Version 1.0.\n//                 See accompanying file LICENSE.txt or copy at\n//                     http://www.boost.org/LICENSE_1_0.txt\n//==============================================================================\n#ifndef BOOST_SIMD_TOOLBOX_ARITHMETIC_FUNCTIONS_SCALAR_TWO_SPLIT_HPP_INCLUDED\n#define BOOST_SIMD_TOOLBOX_ARITHMETIC_FUNCTIONS_SCALAR_TWO_SPLIT_HPP_INCLUDED\n#include <boost/simd/toolbox/arithmetic/functions/two_split.hpp>\n#include <boost/simd/include/constants/splitfactor.hpp>\n#include <boost/fusion/tuple.hpp>\n\nnamespace boost { namespace simd { namespace ext\n{\n  BOOST_SIMD_FUNCTOR_IMPLEMENTATION(boost::simd::tag::two_split_, tag::cpu_,\n                          (A0),\n                          ((scalar_<floating_<A0> >))\n                          ((scalar_<floating_<A0> >))\n                          ((scalar_<floating_<A0> >))\n                         )\n  {\n    typedef int result_type;\n    inline result_type operator()(A0 const& a,\n                              A0 & r0,A0 & r1) const\n    {\n      A0 c  = Splitfactor<A0>()*a;\n      r0 = c-(c-a);\n      r1 = a-r0;\n      return 0;\n    }\n  };\n\n  BOOST_SIMD_FUNCTOR_IMPLEMENTATION(boost::simd::tag::two_split_, tag::cpu_,\n                          (A0),\n                          ((scalar_<floating_<A0> >))\n                          ((scalar_<floating_<A0> >))\n                         )\n  {\n    typedef A0 result_type;\n    inline result_type operator()(A0 const& a0,A0 const& a2) const\n    {\n      A0 a1;\n      two_split(a0,a1,a2);\n      return a1;\n    }\n  };\n\n  BOOST_SIMD_FUNCTOR_IMPLEMENTATION(boost::simd::tag::two_split_, tag::cpu_,\n                            (A0),\n                            ((scalar_<floating_<A0> >))\n                           )\n  {\n    typedef typename boost::fusion::tuple<A0, A0> result_type;\n    BOOST_SIMD_FUNCTOR_CALL(1)\n    {\n      result_type res;\n      two_split(a0,boost::fusion::at_c<0>(res),boost::fusion::at_c<1>(res));\n      return res;\n    }\n\n    private :\n    inline void eval(A0 const& a, A0& r0, A0& r1)const\n    {\n      A0 c;\n      c  = Splitfactor<A0>()*a;\n      r0 = c-(c-a);\n      r1 = a-r0;\n    }\n  };\n} } }\n\n#endif\n", "meta": {"hexsha": "f7411a2c348309e55880f2f46e8d047a538d819b", "size": 2428, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/boost/simd/arithmetic/include/boost/simd/toolbox/arithmetic/functions/scalar/two_split.hpp", "max_stars_repo_name": "timblechmann/nt2", "max_stars_repo_head_hexsha": "6c71f7063ca4e5975c9c019877e6b2fe07c9e4ce", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2016-09-14T00:23:53.000Z", "max_stars_repo_stars_event_max_datetime": "2018-01-14T12:51:18.000Z", "max_issues_repo_path": "modules/boost/simd/arithmetic/include/boost/simd/toolbox/arithmetic/functions/scalar/two_split.hpp", "max_issues_repo_name": "timblechmann/nt2", "max_issues_repo_head_hexsha": "6c71f7063ca4e5975c9c019877e6b2fe07c9e4ce", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "modules/boost/simd/arithmetic/include/boost/simd/toolbox/arithmetic/functions/scalar/two_split.hpp", "max_forks_repo_name": "timblechmann/nt2", "max_forks_repo_head_hexsha": "6c71f7063ca4e5975c9c019877e6b2fe07c9e4ce", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.3733333333, "max_line_length": 80, "alphanum_fraction": 0.5086490939, "num_tokens": 605, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6859494421679929, "lm_q2_score": 0.49609382947091946, "lm_q1q2_score": 0.3402952855885606}}
{"text": "#define SDL_MAIN_HANDLED // for some reason SDL main is broken on my computer\n#include <SDL2/SDL.h>\n#include <imgui/imgui.h>\n#include <imgui/imgui_impl_sdl.h>\n#include <imgui/imgui_impl_sdlrenderer.h>\n#include <stdio.h>\n#include <fstream>\n#include <sstream>\n#include <Eigen/Dense>\n#define AINI_IMPLEMENTATION\n#include \"aini.hpp\"\n#include \"KerrBlackHole.hpp\"\n#include \"physicalConstants.hpp\"\n#include \"drawUtility.hpp\"\n\nusing vec = Eigen::Vector2<double>;\n\nstatic std::string readText(std::ifstream const& settingsFile)\n{\n\tstd::ostringstream sstream;\n\tsstream << settingsFile.rdbuf();\n\treturn sstream.str();\n}\n\nint main(int, char**)\n{\n\tif (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_TIMER | SDL_INIT_GAMECONTROLLER) != 0)\n\t{\n\t\tprintf(\"Error: %s\\n\", SDL_GetError());\n\t\treturn -1;\n\t}\n\n\t// Setup window\n\tSDL_WindowFlags const window_flags = (SDL_WindowFlags)(SDL_WINDOW_RESIZABLE | SDL_WINDOW_ALLOW_HIGHDPI);\n\tSDL_Window* window = SDL_CreateWindow(\"Interstellar-sandbox-2d\", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 1280, 720, window_flags);\n\n\t// Setup SDL_Renderer instance\n\tSDL_Renderer* renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_PRESENTVSYNC | SDL_RENDERER_ACCELERATED);\n\tif (renderer == nullptr)\n\t{\n\t\tprintf(\"Error: %s\\n\", SDL_GetError());\n\t\treturn -1;\n\t}\n\n\t// Setup Dear ImGui context\n\tIMGUI_CHECKVERSION();\n\tImGui::CreateContext();\n\tImGuiIO& io = ImGui::GetIO(); (void)io;\n\tio.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard;     // Enable Keyboard Controls\n\n\t// Setup Dear ImGui style\n\tImGui::StyleColorsDark();\n\n\t// Setup Platform/Renderer backends\n\tImGui_ImplSDL2_InitForSDLRenderer(window, renderer);\n\tImGui_ImplSDLRenderer_Init(renderer);\n\n\t// Our state\n\tImVec4 clear_color = ImVec4(0.0f, 0.0f, 0.0f, 1.00f);\n\tImVec4 grid_color = ImVec4(0.0f, 1.0f, 0.0f, 1.00f);\n\n\tvec initialPos{};\n\n\tint grid_size = 20;\n\tint n_rays = 360;\n\tdouble pixel_scale = 1;\n\tdouble constexpr G = 1;\n\tdouble constexpr C = 1;\n\tfloat time = 0.0;\n\tfloat animation_speed = 1.0f;\n\tdouble M = 1000;\n\tSchwarzschildBlackHole blackHole;\n\t{\n\t\tstd::ifstream saveFile(\"save.ini\");\n\t\tif (saveFile.is_open())\n\t\t{\n\t\t\taini::Reader reader(readText(saveFile));\n\t\t\tblackHole.deserialize(reader);\n\t\t}\n\t}\n\n\t// Main loop\n\tbool done = false;\n\tint steps = 400;\n\twhile (!done)\n\t{\n\t\t// Poll and handle events (inputs, window resize, etc.)\n\t\t// You can read the io.WantCaptureMouse, io.WantCaptureKeyboard flags to tell if dear imgui wants to use your inputs.\n\t\t// - When io.WantCaptureMouse is true, do not dispatch mouse input data to your main application, or clear/overwrite your copy of the mouse data.\n\t\t// - When io.WantCaptureKeyboard is true, do not dispatch keyboard input data to your main application, or clear/overwrite your copy of the keyboard data.\n\t\t// Generally you may always pass all inputs to dear imgui, and hide them from your application based on those two flags.\n\t\tSDL_Event event;\n\t\twhile (SDL_PollEvent(&event))\n\t\t{\n\t\t\tImGui_ImplSDL2_ProcessEvent(&event);\n\t\t\tif (event.type == SDL_QUIT)\n\t\t\t\tdone = true;\n\t\t\tif (event.type == SDL_WINDOWEVENT && event.window.event == SDL_WINDOWEVENT_CLOSE && event.window.windowID == SDL_GetWindowID(window))\n\t\t\t\tdone = true;\n\t\t}\n\n\t\t// Start the Dear ImGui frame\n\t\tImGui_ImplSDLRenderer_NewFrame();\n\t\tImGui_ImplSDL2_NewFrame();\n\t\tImGui::NewFrame();\n\n\t\t// 2. Show a simple window that we create ourselves. We use a Begin/End pair to created a named window.\n\t\t{\n\t\t\tImGui::Begin(\"Settings\");\n\t\t\tImGui::ColorEdit3(\"clear color\", (float*)&clear_color); \n\t\t\tImGui::ColorEdit3(\"grid color\", (float*)&grid_color);   \n\t\t\tImGui::SliderInt(\"grid size\", &grid_size, 10, 100);\n\n\t\t\tImGui::DragInt(\"steps\", &steps, 100, 1, 0);\n\t\t\tImGui::DragInt(\"n rays\", &n_rays, 1, 1, 0);\n\t\t\tImGui::DragDouble(\"pixel scale\", &pixel_scale);\n\t\t\tImGui::DragDouble(\"M\", &M);\n\t\t\tImGui::SliderFloat(\"Time\", &time, 0, 1.0f);\n\t\t\tImGui::DragFloat(\"animation speed\", &animation_speed);\n\t\t\tstatic bool animate = false;\n\t\t\tImGui::Checkbox(\"Animate\", &animate);\n\t\t\tif (animate)\n\t\t\t{\n\t\t\t\ttime += animation_speed * ImGui::GetIO().DeltaTime;\n\t\t\t\tif (time > 1.0f)\n\t\t\t\t\ttime = 0.0f;\n\t\t\t\tif (time < 0.0f)\n\t\t\t\t\ttime = 1.0f;\n\t\t\t}\n\n\t\t\tImGui::DragDouble(\"initial pos x\", &initialPos[0]);\n\t\t\tImGui::DragDouble(\"initial pos y\", &initialPos[1]);\n\n\t\t\tblackHole.showEditor();\n\n\t\t\tif (ImGui::Button(\"save\"))\n\t\t\t{\n\t\t\t\taini::Writer writer;\n\t\t\t\tblackHole.serialize(writer);\n\t\t\t\tstd::ofstream saveFile(\"save.ini\");\n\t\t\t\tsaveFile << writer.write();\n\t\t\t\tsaveFile.flush();\n\t\t\t}\n\n\t\t\tImGui::Text(\"Application average %.3f ms/frame (%.1f FPS)\", 1000.0f / ImGui::GetIO().Framerate, ImGui::GetIO().Framerate);\n\t\t\tImGui::End();\n\t\t}\n\n\n\t\tSDL_RenderClear(renderer);\n\n\t\tSDL_SetRenderDrawColor(renderer, (Uint8)(grid_color.x * 255), (Uint8)(grid_color.y * 255), (Uint8)(grid_color.z * 255), (Uint8)(grid_color.w * 255));\n\t\tint width, height;\n\t\tSDL_GetWindowSize(window, &width, &height);\n\n\t\t// newton approximation\n\t\t// see: https://fr.wikipedia.org/wiki/Tests_exp%C3%A9rimentaux_de_la_relativit%C3%A9_g%C3%A9n%C3%A9rale\n\t\t// https://fr.wikipedia.org/wiki/Loi_universelle_de_la_gravitation\n\n\t\tauto draw_ray = [&](vec pos, double angle)\n\t\t{\n\t\t\tvec dir{ cos(angle), sin(angle) };\n\t\t\tfor (int i = 0; i < (int)(steps * time); i++)\n\t\t\t{\n\t\t\t\tvec const d = blackHole.pos - pos;\n\t\t\t\tauto const F = (G * M) / (d.squaredNorm());\n\t\t\t\tauto const gravity = d.normalized() * F;\n\t\t\t\tdir += gravity;\n\t\t\t\tpos += dir * C;\n\n\t\t\t\tSDL_RenderDrawPoint(renderer, (int)(pos[0] / pixel_scale), (int)(pos[1] / pixel_scale));\n\t\t\t}\n\t\t};\n\n\t\tdouble const angleStep = (M_PI * 2.0) / n_rays;\n\t\tdouble angle = 0;\n\t\tfor (int n = 0; n < n_rays; n++)\n\t\t{\n\t\t\tdraw_ray(initialPos, angle);\n\t\t\tangle += angleStep;\n\t\t}\n\n\t\t// draw black hole center\n\t\tSDL_SetRenderDrawColor(renderer, 255, 0, 0, 255);\n\t\tSDL_Rect brect{ (int)(blackHole.pos[0] / pixel_scale), (int)(blackHole.pos[1] / pixel_scale), 4, 4};\n\t\tSDL_RenderFillRect(renderer, &brect);\n\t\t//draw_circle(renderer, blackHole.pos[0] / pixel_scale, blackHole.pos[1] / pixel_scale, blackHole.SchwarzschildRadius() / pixel_scale);\n\t\t\t\t\n\t\tImGui::Render();\n\t\tSDL_SetRenderDrawColor(renderer, (Uint8)(clear_color.x * 255), (Uint8)(clear_color.y * 255), (Uint8)(clear_color.z * 255), (Uint8)(clear_color.w * 255));\n\t\tImGui_ImplSDLRenderer_RenderDrawData(ImGui::GetDrawData());\n\t\tSDL_RenderPresent(renderer);\n\t}\n\n\t// Cleanup\n\tImGui_ImplSDLRenderer_Shutdown();\n\tImGui_ImplSDL2_Shutdown();\n\tImGui::DestroyContext();\n\n\tSDL_DestroyRenderer(renderer);\n\tSDL_DestroyWindow(window);\n\tSDL_Quit();\n\n\treturn 0;\n}", "meta": {"hexsha": "51ffe7a60dcf1476c98053b89554d74bfcbfd8e5", "size": 6453, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Interstellar/Interstellar/Interstellar.cpp", "max_stars_repo_name": "blackbird806/interstellar-sandbox", "max_stars_repo_head_hexsha": "a509e46c01eaf690066533beca25c85352f68091", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Interstellar/Interstellar/Interstellar.cpp", "max_issues_repo_name": "blackbird806/interstellar-sandbox", "max_issues_repo_head_hexsha": "a509e46c01eaf690066533beca25c85352f68091", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Interstellar/Interstellar/Interstellar.cpp", "max_forks_repo_name": "blackbird806/interstellar-sandbox", "max_forks_repo_head_hexsha": "a509e46c01eaf690066533beca25c85352f68091", "max_forks_repo_licenses": ["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.4780487805, "max_line_length": 156, "alphanum_fraction": 0.6961103363, "num_tokens": 1907, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7025300698514778, "lm_q2_score": 0.48438008427698437, "lm_q1q2_score": 0.34029157444177455}}
{"text": "// Demonstration of estimating an RC network using MST\n// to accompany \"Analyzing On-Chip Interconnect with Modern C++\"\n// Author: Jeff Trull <edaskel@att.net>\n\n/*\nCopyright (c) 2014 Jeffrey E. Trull\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 <iostream>\n#include <vector>\n\n#include <boost/iterator/counting_iterator.hpp>\n#include <boost/graph/prim_minimum_spanning_tree.hpp>\n#include <boost/property_map/function_property_map.hpp>\n\n#include \"ckt_graph.h\"\n\n// Define an implicit graph class\nstruct pin_distance_graph {\n    // For Prim we must model \"Vertex List Graph\" and \"Incidence Graph\"\n    // Graph requirements\n    typedef size_t vertex_descriptor;\n    typedef std::pair<size_t, size_t> edge_descriptor;\n    typedef boost::undirected_tag directed_category;\n    typedef boost::disallow_parallel_edge_tag edge_parallel_category;\n    // inherit traversal from both concepts\n    struct traversal_category : virtual public boost::vertex_list_graph_tag,\n                                virtual public boost::incidence_graph_tag {};\n\n    // Vertex List Graph requirements\n    typedef boost::counting_iterator<size_t> vertex_iterator;\n    typedef size_t vertices_size_type;\n\n    // Incidence Graph requirements\n    // The most complicated part is generating new edges\n    // We need to make a standard conforming edge iterator\n    // The Boost.Iterator library can help us make a \"forward iterator\"\n    struct  edge_iterator_t : boost::iterator_facade<edge_iterator_t,\n                                                     edge_descriptor,\n                                                     boost::forward_traversal_tag,\n                                                     edge_descriptor const&> {\n        // Implementation constrained by two things:\n        // 1) We need to provide a default constructor, so sentinel cannot reference graph\n        // 2) We need to provide a non-const dereference operator for Prim, so must keep\n        //    a true edge descriptor around\n\n        edge_iterator_t()\n            : g_(nullptr) {}  // initialize to invalid\n        edge_iterator_t(pin_distance_graph const* g, vertex_descriptor u)\n            : current_edge_(std::make_pair(u, 0)), g_(g) {\n            advance_to_legal();\n        }\n    private:\n        friend class boost::iterator_core_access;\n        // iterator_facade requirements:\n        void increment() {\n            current_edge_.second++;\n            advance_to_legal();\n        }\n        bool equal(edge_iterator_t const& other) const {\n            // true if both invalid, or they match source/dest\n            if (invalid()) {\n                return other.invalid();\n            } else {\n                return !other.invalid() && (current_edge_ == other.current_edge_);\n            }\n        }\n        edge_descriptor const& dereference() const {\n            return current_edge_;\n        }\n        // implementation details for above:\n        bool invalid() const {\n            return ((g_ == nullptr) || (current_edge_.second >= num_vertices(*g_)));\n        }\n        void advance_to_legal() {\n            // ensure target and source are not the same\n            if (current_edge_.first == current_edge_.second) {\n                current_edge_.second++;\n            }\n        }\n        edge_descriptor current_edge_;\n        pin_distance_graph const* g_;\n    };\n                                                     \n    typedef edge_iterator_t out_edge_iterator;\n    typedef size_t degree_size_type;\n\n    // Vertex List Graph free functions\n    friend std::pair<vertex_iterator, vertex_iterator>\n    vertices(pin_distance_graph const& g) {\n        return std::make_pair(vertex_iterator(0), vertex_iterator(g.points_.size()));\n    }\n\n    friend vertices_size_type num_vertices(pin_distance_graph const& g) {\n        return g.points_.size();\n    }\n\n    // Incidence Graph free functions\n    friend vertex_descriptor source(edge_descriptor const& e, pin_distance_graph const&) {\n        return e.first;\n    }\n\n    friend vertex_descriptor target(edge_descriptor const& e, pin_distance_graph const&) {\n        return e.second;\n    }\n\n    friend std::pair<out_edge_iterator, out_edge_iterator>\n    out_edges(vertex_descriptor u, pin_distance_graph const& g) {\n        return std::make_pair(edge_iterator_t(&g, u), edge_iterator_t());\n    }\n\n    friend degree_size_type\n    out_degree(vertex_descriptor, pin_distance_graph const& g) {\n        return g.points_.size() - 1;  // \"complete\" graph, every node connected to every other\n    }\n        \n    // Main functionality\n    typedef std::pair<int, int> point_t;\n    template<typename PtIter>\n    pin_distance_graph(PtIter beg, PtIter end) : points_(beg, end) {}\n\n    // Provide bracket operator a la adjacency_list\n    point_t operator[](vertex_descriptor u) const {\n        return points_[u];\n    }\n\nprivate:\n    std::vector<point_t> points_;\n\n};\n\n// Run Prim on it\n// Prim seems vertex-focused, as opposed to the edge-focused Kruskal\n// since our edges are implicit I favored the former\n\nint main() {\n    using namespace boost;\n    using namespace std;\n\n    // Data for implicit graph - a list of points\n    vector<pair<int, int>> pinlocs =\n        {{-100, -100}, {-100, 100}, {0, 0}, {100, 100}, {100, -100},\n         {-50, 0}, {103, 100}, {100, 90}};\n\n    pin_distance_graph pdg(pinlocs.begin(), pinlocs.end());\n\n    // Create Prim requirements (temporary data structures used in algorithm)\n\n    // vertex index map.  Since we use size_t for vertex descriptors, they\n    // are immediately usable as indices:\n    auto vindex_map = typed_identity_property_map<size_t>();\n\n    // Predecessor map\n    vector<pin_distance_graph::vertex_descriptor> predvec(num_vertices(pdg));   // underlying storage\n    auto predpmap = make_iterator_property_map(predvec.begin(), vindex_map);\n    \n    // Weight Map\n    // Another case where we can be \"implicit\" - the weight of an edge is\n    // the Manhattan distance between the vertices\n    typedef pin_distance_graph::edge_descriptor edge_t;\n    auto weightpmap = make_function_property_map<edge_t>(\n        [&pdg](edge_t e) -> int {\n            auto coord1 = pdg[source(e, pdg)];\n            auto coord2 = pdg[target(e, pdg)];\n            return abs(coord1.first - coord2.first) + abs(coord1.second - coord2.second);\n        });    \n\n    // call Prim\n    prim_minimum_spanning_tree(pdg, predpmap,\n                               weight_map(weightpmap).\n                               vertex_index_map(vindex_map));\n\n    // produce output as SVG\n    cout << \"<svg xmlns=\\\"http://www.w3.org/2000/svg\\\"\" << endl;\n    cout << \"     xmlns:xlink=\\\"http://www.w3.org/1999/xlink\\\">\" << endl;\n    auto vitpair = vertices(pdg);\n    for (auto v : make_iterator_range(vitpair.first, vitpair.second)) {\n        // SVG wants positive numbers, and the Y coordinate is canvas style (reversed from Cartesian)\n        // so we will transform the data en route to the display for viewability:\n        // scale by 2X, mirror Y axis, and add 250 to both\n        int x2 = 250 + 2*pdg[v].first;\n        int y2 = 250 - 2*pdg[v].second;\n        if (predvec[v] == v) {\n            // Root.  Make a red circle\n            cout << \"    <circle cx=\\\"\" << x2 << \"\\\" cy=\\\"\" << y2 << \"\\\" r=\\\"10\\\" style=\\\"fill:#cc0000\\\"/>\" << endl;\n        } else {\n            // Not Root: a gray one\n            cout << \"    <circle cx=\\\"\" << x2 << \"\\\" cy=\\\"\" << y2 << \"\\\" r=\\\"10\\\" style=\\\"fill:#cccccc; stroke:#222222\\\"/>\" << endl;\n        }\n    }\n    // Go back and add lines on top of the circles (for visibility)\n    for (auto v : make_iterator_range(vitpair.first, vitpair.second)) {\n        int x2 = 250 + 2*pdg[v].first;\n        int y2 = 250 - 2*pdg[v].second;\n        if (predvec[v] != v) {\n            int x1 = 250 + 2*pdg[predvec[v]].first;\n            int y1 = 250 - 2*pdg[predvec[v]].second;\n            // Make a line to the successor node\n            cout << \"    <line x1=\\\"\" << x1 << \"\\\" y1=\\\"\" << y1 << \"\\\" x2=\\\"\" << x2 << \"\\\" y2=\\\"\" << y2 << \"\\\" style=\\\"stroke:#666666; stroke-width:3px\\\"/>\" << endl;\n        }\n    }\n    cout << \"</svg>\" << endl;\n\n    // Future work: turn resulting tree into an implicit graph compatible with ckt_graph_t,\n    // with estimated RC values on edges\n\n}\n", "meta": {"hexsha": "5187ef7d73d58d0079d7413508d97d84b22f5f1e", "size": 9198, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "rmst.cpp", "max_stars_repo_name": "jefftrull/OnChipInterconnect", "max_stars_repo_head_hexsha": "11d1b2483b5a4486ea0d2b3eb6a3f0104488d1c4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2015-01-04T11:05:20.000Z", "max_stars_repo_stars_event_max_datetime": "2015-01-04T11:05:20.000Z", "max_issues_repo_path": "rmst.cpp", "max_issues_repo_name": "jefftrull/OnChipInterconnect", "max_issues_repo_head_hexsha": "11d1b2483b5a4486ea0d2b3eb6a3f0104488d1c4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "rmst.cpp", "max_forks_repo_name": "jefftrull/OnChipInterconnect", "max_forks_repo_head_hexsha": "11d1b2483b5a4486ea0d2b3eb6a3f0104488d1c4", "max_forks_repo_licenses": ["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.6991150442, "max_line_length": 165, "alphanum_fraction": 0.6353555121, "num_tokens": 2094, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5813030906443133, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.34012110927789324}}
{"text": "// STL includes\n#include <iostream>\n#include <fstream>\n#include <set>\n#include <cstdlib> // error codes\n#include <memory>\n#include <cmath>\n#include <chrono>\n#include <random>\n// Local includes\n#include \"models.h\"\n#include \"types.h\"\n#include \"config.h\"\n\n#if HAVE_LIBBOOST_PROGRAM_OPTIONS == 1\n  // Boost\n  #include <boost/program_options.hpp>\n  namespace po = boost::program_options;\n#endif\n\n\nstd::string model_desc_help_string(std::set<std::string> models,\n                                   std::map<std::string, std::string> models_desc,\n                                   std::string base_string)\n{\n  std::string help_string = base_string;\n  for (auto m: models)\n    help_string += \" \\\"\" + m + \"\\\"\" + \" : \" + models_desc.at(m) + \"\\n\";\n  return help_string.substr(0, help_string.size() - 1);\n}\n\n\nint main(int argc, char const *argv[])\n{\n  // models\n  std::map<std::string, std::string> models_description;\n  std::map<std::string, std::string> models_parameters;\n  std::map<std::string, unsigned int> models_parameters_count;\n  std::set<std::string> implemented_models = {\"delayed\", \"gn\", \"bianconi_barabasi\", \"generalized_gn\"};\n  // unstructured models\n  models_description[\"delayed\"] = \"L. H.-Dufresne. et al., PRE 92, (2015).\";\n  models_parameters[\"delayed\"] = \"a, alpha, b, mu, tau.\";\n  models_parameters_count[\"delayed\"] = 5;\n  // structured models\n  models_description[\"gn\"] = \"Krapivsky-Redner, PRE 63, (2001).\";\n  models_parameters[\"gn\"] = \"gamma, m.\";\n  models_parameters_count[\"gn\"] = 2;\n  models_description[\"bianconi_barabasi\"] = \"Bianconie-Barabasi, PRL 86, (2001).\";\n  models_parameters[\"bianconi_barabasi\"] = \"gamma, nu, avg, std, m.\";\n  models_parameters_count[\"bianconi_barabasi\"] = 5;\n  models_description[\"generalized_gn\"] = \"General PA with densification.\";\n  models_parameters[\"generalized_gn\"] = \"a, alpha, b, m1, m2, gamma, tau, negative_kernel.\";\n  models_parameters_count[\"generalized_gn\"] = 8;\n\n  /* ~~~~~ Program options ~~~~~~~*/\n  unsigned int T;\n  double_vec_t parameters;\n  std::string model_name;\n  unsigned int seed = 0;\n  std::string state_file_path;\n\n\n\n  // ================\n  // BOOST INTERFACE\n  // ================\n  #if HAVE_LIBBOOST_PROGRAM_OPTIONS == 1\n    // boost::po call\n    po::options_description description(\"Options\");\n    description.add_options()\n    (\"model,m\", po::value<std::string>(&model_name)->default_value(\"gn\"),\n      // automatically generated help message\n      model_desc_help_string(implemented_models,\n                             models_description,\n                             \"Name of the growth model. The implemented models are:\\n\").c_str())\n    (\"parameters,p\", po::value<double_vec_t>(&parameters)->multitoken(),\n      // automatically generated help message\n      model_desc_help_string(implemented_models,\n                             models_parameters,\n                             \"Parameters of the model, provided as a list of doubles.\\n\").c_str())\n    (\"T,t\", po::value<unsigned int>(&T)->default_value(1000), \"Number of growth events.\")\n    (\"seed,d\", po::value<unsigned int>(&seed),\n        \"Seed of the pseudo random number generator (Mersenne-twister 19937).\"\\\n        \"Seeded with current time if seed is not specified or equal to 0.\")\n    (\"state_file,f\", po::value<std::string>(&state_file_path),\n      \"Save state variables in a file upon completion (degree, fitness, etc.).\")\n    (\"verbose,v\", \"Output parameters to stdlog.\")\n    (\"help,h\", \"Produce this help message.\")\n    ;\n    po::variables_map var_map;\n    try\n    {\n      po::store(po::parse_command_line(argc,argv,description), var_map);\n      po::notify(var_map);\n    }\n    catch (po::validation_error& e)\n    {\n      std::clog << \"Boost program option error:\\n\";\n      std::clog << e.what();\n      std::clog << \"\\n\";\n      return EXIT_FAILURE;\n    }\n\n    // Input validation and actions\n    if (var_map.count(\"help\") > 0 || argc == 1)\n    {\n      std::clog << \"Usage:\\n\"\n                << \"  \"+std::string(argv[0])+\" [--option_1=value] [--option_s2=value] ...\\n\";\n      std::clog << description;\n      return EXIT_SUCCESS;\n    }\n    if (var_map.count(\"seed\") == 0)\n    {\n      seed = (unsigned int) std::chrono::high_resolution_clock::now().time_since_epoch().count();\n    }\n    if (models_parameters_count[model_name] != parameters.size())\n    {\n      std::clog << \"Incorrect number of parameters for the \\\"\" + model_name + \"\\\" growth model.\\n\";\n      return EXIT_FAILURE;\n    }\n    if (implemented_models.find(model_name) == implemented_models.end())\n    {\n      std::clog << \"Model \\\"\" + model_name + \"\\\" not implemented.\\n\";\n      return EXIT_FAILURE;\n    }\n    if (T <= 1)\n    {\n      std::clog << \"Number of event T is too small (T=\" << T << \")\\n\";\n      return EXIT_FAILURE;\n    }\n\n    // Logger\n    if (var_map.count(\"verbose\") > 0)\n    {\n      std::clog << \"Model: \" << model_name << \"\\n\";\n      std::clog << \"Parameters (\" + models_parameters[model_name] + \"): \";\n      for (auto p: parameters)\n        std::clog << p << \" \";\n      std::clog << \"\\n\";\n      std::clog << \"T: \" << T << \"\\n\";\n      std::clog << \"Seed: \" << seed << \"\\n\";\n    }\n  // ================\n  // end of boost interface\n  // ================\n  #else\n    model_name = std::string(argv[1]);\n    if (model_name==\"-h\")\n    {\n      std::clog << \"This is the limited interface of this program. boost::program_options could not be found and linked.\\n\";\n      std::clog << \"Usage: \" << argv[0] << \"  model_name T seed param1 param2 ...\\n\\n\"; \n      std::clog << model_desc_help_string(implemented_models,\n                                          models_description,\n                                          \"Name of the growth model. The implemented models are:\\n\");\n      std::clog << \"\\n\\n\";\n      std::clog << model_desc_help_string(implemented_models,\n                                          models_parameters,\n                                          \"Parameters of the model, provided as a list of doubles.\\n\");\n      std::clog << \"\\n\";\n      return EXIT_SUCCESS;\n    }\n    T = std::atoi(argv[2]);\n    seed = std::atoi(argv[3]);\n    parameters.resize(models_parameters_count[model_name], 0);\n    for (unsigned int i = 0; i < models_parameters_count[model_name]; ++i)\n    {\n      parameters[i] = std::atof(argv[4 + i]);\n    }\n  #endif\n\n  /*~~~~~~~Initialize model~~~~~~~~~~~~*/\n  std::shared_ptr<growth_model> model;\n\n  // unstructured models\n  if (model_name == \"delayed\")\n  {\n    double a = parameters[0];\n    double alpha = parameters[1];\n    double b = parameters[2];\n    double gamma = parameters[3];\n    double tau = parameters[4];\n    model = std::make_shared<delayed_model>(a, alpha, b, gamma, tau);\n  }\n  // structured models\n  if (model_name == \"gn\")\n  {\n    double gamma = parameters[0];\n    unsigned int m = (unsigned int) parameters[1];\n    model = std::make_shared<gn_model>(gamma, m);\n  }\n  if (model_name == \"generalized_gn\")\n  {\n    double a = parameters[0];\n    double alpha = parameters[1];\n    double b = parameters[2];\n    unsigned int m1 = (unsigned int) parameters[3];\n    unsigned int m2 = (unsigned int) parameters[4];\n    double gamma = parameters[5];\n    double tau = parameters[6];\n    if (parameters[7]) gamma = -gamma;\n    model = std::make_shared<generalized_gn_model>(a, alpha, b, m1, m2, gamma, tau);\n    --T; // we start with an edge\n  }\n  if (model_name == \"bianconi_barabasi\")\n  {\n    double gamma = parameters[0];\n    double nu = parameters[1];\n    double avg = parameters[2];\n    double std = parameters[3];\n    unsigned int m = (unsigned int) parameters[4];\n    model = std::make_shared<bianconi_barabasi_model>(gamma, nu, avg, std, m);\n  }\n\n\n  /*~~~~~~~~~~~Run~~~~~~~~~~~~~~~~*/\n  std::mt19937 engine(seed);\n  model->run(T, engine);\n  // std::clog << \"Ran\\n\";\n\n  /*~~~Dump history to stream~~~~*/\n  model->print_history(std::cout);\n  #if HAVE_LIBBOOST_PROGRAM_OPTIONS == 1\n      if (var_map.count(\"state_file\") > 0)\n      {\n        std::ofstream sf(state_file_path.c_str(), std::ios::out);\n        model->print_states(sf);\n        sf.close();\n      }\n  #endif\n\n\n  return 0;\n}\n", "meta": {"hexsha": "ec883d6df0f313c65e5f61451bc008e1f539bdf6", "size": 8049, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "generators/src/growth_main.cpp", "max_stars_repo_name": "junipertcy/network-archaeology", "max_stars_repo_head_hexsha": "7cef0de7a388e8dde812e746d50470d167da8a9b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "generators/src/growth_main.cpp", "max_issues_repo_name": "junipertcy/network-archaeology", "max_issues_repo_head_hexsha": "7cef0de7a388e8dde812e746d50470d167da8a9b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "generators/src/growth_main.cpp", "max_forks_repo_name": "junipertcy/network-archaeology", "max_forks_repo_head_hexsha": "7cef0de7a388e8dde812e746d50470d167da8a9b", "max_forks_repo_licenses": ["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.3974358974, "max_line_length": 124, "alphanum_fraction": 0.5949807429, "num_tokens": 2105, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5851011542032312, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.34012110927789324}}
{"text": "#include <cassert>\n#include <exception>\n#include <iostream>\n\n#include <boost/safe_numerics/safe_integer.hpp>\n\nint main(int, const char *[]){\n    std::cout << \"example 2:\";\n    std::cout << \"undetected overflow in data type\" << std::endl;\n    // problem: undetected overflow\n    std::cout << \"Not using safe numerics\" << std::endl;\n    try{\n        int x = INT_MAX;\n        // the following silently produces an incorrect result\n        ++x;\n        std::cout << x << \" != \" << INT_MAX << \" + 1\" << std::endl;\n        std::cout << \"error NOT detected!\" << std::endl;\n    }\n    catch(std::exception){\n        std::cout << \"error detected!\" << std::endl;\n    }\n    // solution: replace int with safe<int>\n    std::cout << \"Using safe numerics\" << std::endl;\n    try{\n        using namespace boost::safe_numerics;\n        safe<int> x = INT_MAX;\n        // throws exception when result is past maximum possible \n        ++x;\n        assert(false); // never arrive here\n    }\n    catch(std::exception & e){\n        std::cout << e.what() << std::endl;\n        std::cout << \"error detected!\" << std::endl;\n    }\n    return 0;\n}\n", "meta": {"hexsha": "c1b3e6a36ff0aa8a5d1b66bfdb5c5bb208f2901a", "size": 1120, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "deps/boost/libs/safe_numerics/example/example2.cpp", "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/libs/safe_numerics/example/example2.cpp", "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/libs/safe_numerics/example/example2.cpp", "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": 30.2702702703, "max_line_length": 67, "alphanum_fraction": 0.5633928571, "num_tokens": 290, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5888891163376236, "lm_q2_score": 0.5774953651858117, "lm_q1q2_score": 0.3400807352933459}}
{"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#include <iostream>\n#include <random>\n#include <vector>\n\n#include \"cutil.hpp\"\n#include \"util.hpp\"\n#include \"zipf_dist.hpp\"\n\n#include <boost/filesystem.hpp>\n#include <boost/program_options.hpp>\n\nnamespace po = boost::program_options;\nnamespace fs = boost::filesystem;\n\npo::variables_map parse_cmdargs(int argc, char const* argv[])\n{\n    po::variables_map vm;\n    po::options_description desc(\"Allowed options\");\n    // clang-format off\n    desc.add_options()\n        (\"help,h\", \"produce help message\")\n        (\"text,t\", \"text (default is uint32_t binary)\")\n        (\"num,n\",po::value<size_t>()->required(), \"number of integers per file\")\n        (\"output,o\",po::value<std::string>()->required(), \"output path\");\n    // clang-format on\n    try {\n        po::store(po::parse_command_line(argc, argv, desc), vm);\n        if (vm.count(\"help\")) {\n            std::cout << desc << \"\\n\";\n            exit(EXIT_SUCCESS);\n        }\n        po::notify(vm);\n    } catch (const po::required_option& e) {\n        std::cout << desc;\n        std::cerr << \"Missing required option: \" << e.what() << std::endl;\n        exit(EXIT_FAILURE);\n    } catch (po::error& e) {\n        std::cout << desc;\n        std::cerr << \"Error parsing cmdargs: \" << e.what() << std::endl;\n        exit(EXIT_FAILURE);\n    }\n\n    return vm;\n}\n\ntemplate <class t_dist>\nvoid generate_data(\n    const t_dist& dist, size_t n, std::string out_file, bool write_text)\n{\n    std::string file_name = out_file;\n    std::cout << \"generating file \" << file_name << std::endl;\n    std::vector<uint32_t> nums;\n    std::mt19937 gen(0);\n    t_dist dst = dist;\n    for (size_t i = 0; i < n; i++) {\n        nums.push_back(dst(gen));\n    }\n    if (write_text)\n        write_file_text(nums, file_name + \".txt\");\n    else\n        write_file_u32(nums, file_name + \".u32\");\n}\n\nint main(int argc, char const* argv[])\n{\n    auto cmdargs = parse_cmdargs(argc, argv);\n    auto output_path = cmdargs[\"output\"].as<std::string>();\n    auto n = cmdargs[\"num\"].as<size_t>();\n    auto write_text = cmdargs.count(\"text\") != 0;\n\n    generate_data(std::uniform_int_distribution<uint32_t>(0, (1 << 8) - 1), n,\n        output_path + \"/uniform08\", write_text);\n    generate_data(std::uniform_int_distribution<uint32_t>(0, (1 << 12) - 1), n,\n        output_path + \"/uniform12\", write_text);\n    generate_data(std::uniform_int_distribution<uint32_t>(0, (1 << 16) - 1), n,\n        output_path + \"/uniform16\", write_text);\n    generate_data(std::uniform_int_distribution<uint32_t>(0, (1 << 20) - 1), n,\n        output_path + \"/uniform20\", write_text);\n\n    generate_data(std::geometric_distribution<uint32_t>(0.01), n,\n        output_path + \"/geom0.01\", write_text);\n    generate_data(std::geometric_distribution<uint32_t>(0.1), n,\n        output_path + \"/geom0.1\", write_text);\n    generate_data(std::geometric_distribution<uint32_t>(0.2), n,\n        output_path + \"/geom0.2\", write_text);\n    generate_data(std::geometric_distribution<uint32_t>(0.4), n,\n        output_path + \"/geom0.4\", write_text);\n    generate_data(std::geometric_distribution<uint32_t>(0.6), n,\n        output_path + \"/geom0.6\", write_text);\n    generate_data(std::geometric_distribution<uint32_t>(0.8), n,\n        output_path + \"/geom0.8\", write_text);\n    generate_data(std::geometric_distribution<uint32_t>(0.9), n,\n        output_path + \"/geom0.9\", write_text);\n    generate_data(std::geometric_distribution<uint32_t>(0.99), n,\n        output_path + \"/geom0.99\", write_text);\n\n    generate_data(zipf_distribution<uint32_t>(1 << 12), n,\n        output_path + \"/zipf12\", write_text);\n    generate_data(zipf_distribution<uint32_t>(1 << 20), n,\n        output_path + \"/zipf20\", write_text);\n}\n", "meta": {"hexsha": "131f4d74564d9886bf82e6763af020513e8264f6", "size": 4485, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/generate_inputs.cpp", "max_stars_repo_name": "mpetri/ans-large-alphabet", "max_stars_repo_head_hexsha": "416c7e794a3f6ffa4db4d327b4ac2f3c229e99ff", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/generate_inputs.cpp", "max_issues_repo_name": "mpetri/ans-large-alphabet", "max_issues_repo_head_hexsha": "416c7e794a3f6ffa4db4d327b4ac2f3c229e99ff", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/generate_inputs.cpp", "max_forks_repo_name": "mpetri/ans-large-alphabet", "max_forks_repo_head_hexsha": "416c7e794a3f6ffa4db4d327b4ac2f3c229e99ff", "max_forks_repo_licenses": ["Apache-2.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.6890756303, "max_line_length": 80, "alphanum_fraction": 0.6512820513, "num_tokens": 1165, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5926665999540698, "lm_q2_score": 0.5736784074525096, "lm_q1q2_score": 0.3400000312119444}}
{"text": "#pragma once\n\n#include <deal.II/base/exceptions.h>\n#include <deal.II/base/index_set.h>\n#include <deal.II/base/utilities.h>\n#include <deal.II/dofs/dof_handler.h>\n#include <deal.II/lac/trilinos_vector.h>\n\n#include \"collision_tensor.hpp\"\n#include \"collision_tensor_galerkin.hpp\"\n#include \"dense/collision_tensor_zlastAM.hpp\"\n#include \"dense/collision_tensor_zlastAM_eigen.hpp\"\n#include \"spectral/basis/spectral_basis_factory_ks.hpp\"\n\nnamespace boltzmann {\n// -------------------------------------------------------------------------------------\n// -------------------------------------------------------------------------------------\n// -------------------------------------------------------------------------------------\nclass CollisionTensorOperatorBase\n{\n protected:\n  typedef typename SpectralBasisFactoryKS::basis_type spectral_basis_t;\n  typedef dealii::TrilinosWrappers::MPI::Vector trilinos_vector_t;\n\n protected:\n  CollisionTensorOperatorBase(MPI_Comm& communicator)\n      : comm(communicator)\n  { /* empty */\n  }\n\n public:\n  /// explicit Euler step\n  virtual void apply(trilinos_vector_t& out, double dt) const = 0;\n  /// load tensor from HDF5-file\n  virtual void load_tensor(std::string fname) = 0;\n  void set_truncation_threshold(double tre);\n\n\n protected:\n  MPI_Comm comm;\n  double truncate_treshold_ = 0;\n  bool use_treshold_ = false;\n\n};\n\n// -------------------------------------------------------------------------------------\n// -------------------------------------------------------------------------------------\n// -------------------------------------------------------------------------------------\nclass CollisionTensorOperatorPG : public CollisionTensorOperatorBase\n{\n public:\n  CollisionTensorOperatorPG(const dealii::DoFHandler<2>& dh,\n                            const spectral_basis_t& basis,\n                            const dealii::IndexSet& parallel_partitioning,\n                            MPI_Comm communicator = MPI_COMM_WORLD)\n      : CollisionTensorOperatorBase(communicator)\n      , n_phys_dofs(dh.n_dofs())\n      , n_velo_dofs(basis.n_dofs())\n      , Q(basis.n_dofs())\n      , vtmp(parallel_partitioning, communicator)\n      , local_buffer(parallel_partitioning.n_elements())\n  { /* empty */ }\n\n  virtual void apply(trilinos_vector_t& out, double dt) const;\n  virtual void load_tensor(std::string fname);\n\n private:\n  const unsigned int n_phys_dofs;\n  const unsigned int n_velo_dofs;\n  CollisionTensor Q;\n  mutable trilinos_vector_t vtmp;\n  mutable std::vector<double> local_buffer;\n};\n\n// -------------------------------------------------------------------------------------\n// -------------------------------------------------------------------------------------\n// -------------------------------------------------------------------------------------\nclass CollisionTensorOperatorG : public CollisionTensorOperatorBase\n{\n public:\n  CollisionTensorOperatorG(const dealii::DoFHandler<2>& dh,\n                           const spectral_basis_t& basis,\n                           const dealii::IndexSet& parallel_partitioning,\n                           MPI_Comm communicator = MPI_COMM_WORLD)\n      : CollisionTensorOperatorBase(communicator)\n      , n_phys_dofs(dh.n_dofs())\n      , n_velo_dofs(basis.n_dofs())\n      , n_local_phys_dofs_(parallel_partitioning.n_elements() / basis.n_dofs())\n      , Q(basis)\n      , vtmp(parallel_partitioning, communicator)\n  {\n    lambda.resize(4, n_local_phys_dofs_);\n    lambda_prev.resize(4, n_local_phys_dofs_);\n  }\n\n  virtual void apply(trilinos_vector_t& out, double dt) const;\n  virtual void load_tensor(std::string fname);\n\n private:\n  const unsigned int n_phys_dofs;\n  const unsigned int n_velo_dofs;\n  const unsigned int n_local_phys_dofs_;\n  CollisionTensorGalerkin Q;\n  mutable trilinos_vector_t vtmp;\n  /// conservation of momentum\n  typedef Eigen::Array<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::ColMajor> carray_t;\n  mutable carray_t lambda;\n  mutable carray_t lambda_prev;\n\n public:\n  EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n\n};\n\n#ifdef USE_MPI\n// -------------------------------------------------------------------------------------\n// -------------------------------------------------------------------------------------\n// -------------------------------------------------------------------------------------\ntemplate <typename CT_DENSE = ct_dense::CollisionTensorZLastAM>\nclass CollisionTensorOperatorDense : public CollisionTensorOperatorBase\n{\n public:\n  CollisionTensorOperatorDense(const dealii::DoFHandler<2>& dh,\n                               const spectral_basis_t& basis,\n                               const dealii::IndexSet& parallel_partitioning,\n                               int vblksize = 1,\n                               MPI_Comm communicator = MPI_COMM_WORLD)\n      : CollisionTensorOperatorBase(communicator)\n      , basis_(basis)\n      , n_phys_dofs_(dh.n_dofs())\n      , n_velo_dofs_(basis.n_dofs())\n      , vblksize_(vblksize)\n      , n_local_phys_dofs_(parallel_partitioning.n_elements() / basis.n_dofs())\n      , Q_(basis, parallel_partitioning.n_elements() / basis.n_dofs())\n      , vtmp(parallel_partitioning, communicator)\n  {\n    /* empty */\n  }\n\n private:\n  const spectral_basis_t& basis_;\n  const unsigned int n_phys_dofs_;\n  const unsigned int n_velo_dofs_;\n  const int vblksize_;\n  const int n_local_phys_dofs_;\n  CT_DENSE Q_;\n\n private:\n  mutable trilinos_vector_t vtmp;\n  typedef Eigen::Array<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::ColMajor> in_array_t;\n  /// padded input array\n  mutable in_array_t padded_in;\n  /// conservation of momentum\n  mutable in_array_t lambda;\n  mutable in_array_t lambda_prev;\n\n public:\n  virtual void apply(trilinos_vector_t& out, double dt) const override;\n  virtual void load_tensor(std::string fname) override;\n\n\n public:\n  EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n};\n\ntemplate <typename CT_DENSE>\nvoid\nCollisionTensorOperatorDense<CT_DENSE>::apply(trilinos_vector_t& out, double dt) const\n{\n  BOOST_ASSERT(out.local_size()/n_velo_dofs_ == n_local_phys_dofs_);\n  BOOST_ASSERT(vtmp.local_size()/n_velo_dofs_ == n_local_phys_dofs_);\n\n  const double* data = out.begin();\n\n  Eigen::Map<const in_array_t> vin(data, n_velo_dofs_, n_local_phys_dofs_);\n  int imax = -1;\n  if (use_treshold_) {\n    for (int i = n_velo_dofs_ -1; i >= 0; --i) {\n      if ((vin.row(i).abs() > truncate_treshold_).any()) {\n        imax = i;\n        break;\n      }\n    }\n  }\n  // pad & copy to padded array\n  Q_.pad(padded_in, vin);\n  Eigen::Map<in_array_t> vout(out.begin(), n_velo_dofs_, n_local_phys_dofs_);\n  // get lambda (moment conservation)\n  Q_.get_lambda(lambda_prev, vin);\n  // apply collision tensor write directly to output array\n  Eigen::Map<in_array_t> vtmp_eigen(vtmp.begin(), n_velo_dofs_, n_local_phys_dofs_);\n  Q_.apply(vtmp_eigen, padded_in, use_treshold_ ? imax : -1);\n  // explicit Euler timestep\n  out.sadd(1.0, dt, vtmp);\n  // get contribution to lambda from next timestep\n  Q_.get_lambda(lambda, vout);\n  lambda -= lambda_prev;\n  // conserve moments\n  Q_.project_lambda(vout, lambda);\n}\n\ntemplate <typename CT_DENSE>\nvoid\nCollisionTensorOperatorDense<CT_DENSE>::load_tensor(std::string fname)\n{\n  Q_.import_entries_mpishmem(fname, vblksize_);\n\n  // initialize buffer arrays used during ::apply\n  int npadded = Q_.padded_vector_length();\n  padded_in.resize(npadded, n_local_phys_dofs_);\n  // this needs to be done only once, the parts used to\n  // store the input vector are overwritten, and the elements in between\n  // are multiplied by zero during Q_.apply, just make sure they are not NaN's by chance.\n  padded_in.setZero();\n\n  // temporary arrays for conservation of momentum\n  lambda_prev.resize(4, n_local_phys_dofs_);\n  lambda.resize(4, n_local_phys_dofs_);\n}\n\n\n#endif\n\n}  // namespace boltzmann\n", "meta": {"hexsha": "839b398e100630bee218d1226b411d5a45b72af7", "size": 7753, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/collision_tensor/collision_tensor_operator.hpp", "max_stars_repo_name": "simonpintarelli/2dBoltzmann", "max_stars_repo_head_hexsha": "bc6b7bbeffa242ce80937947444383b416ba3fc9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/collision_tensor/collision_tensor_operator.hpp", "max_issues_repo_name": "simonpintarelli/2dBoltzmann", "max_issues_repo_head_hexsha": "bc6b7bbeffa242ce80937947444383b416ba3fc9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/collision_tensor/collision_tensor_operator.hpp", "max_forks_repo_name": "simonpintarelli/2dBoltzmann", "max_forks_repo_head_hexsha": "bc6b7bbeffa242ce80937947444383b416ba3fc9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.4577777778, "max_line_length": 91, "alphanum_fraction": 0.6176963756, "num_tokens": 1729, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5926665999540698, "lm_q2_score": 0.5736784074525096, "lm_q1q2_score": 0.3400000312119444}}
{"text": "// Copyright 2015-2022 The ALMA Project Developers\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//   http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n// implied. See the License for the specific language governing\n// permissions and limitations under the License.\n\n#pragma once\n\n/// @file\n/// Classes and functions used for sampling from several distributions\n/// used in the MC scheme.\n\n#include <vector>\n#include <utility>\n#include <tuple>\n#include <map>\n#include <random>\n#include <Eigen/Dense>\n#include <pcg_random.hpp>\n#include <structures.hpp>\n#include <qpoint_grid.hpp>\n#include <dos.hpp>\n#include <processes.hpp>\n#include <deviational_particle.hpp>\n#include <mutex>\n\nnamespace alma {\n/// Generate a random time delta from an exponential distribution\n/// @param[in] w - a scattering rate\n/// @param[in] rng - a random number generator\n/// @return an exponential deviate\ninline double random_dt(double w, pcg64& rng) {\n    if (w == 0.)\n        throw value_error(\"invalid scattering rate\");\n    ;\n    double u = std::uniform_real_distribution(0., 1.)(rng);\n    return -std::log(u) / w;\n}\n\n\n/// Base class for discrete distributions over a q-point grid.\nclass Grid_distribution {\nprotected:\n    /// Distribution function.\n    std::vector<double> cumulative;\n    /// Random number generator.\n    pcg64 rng;\n    /// Vector with particle sign\n    std::vector<alma::particle_sign> signs;\n    /// The sum of cumulative\n    double cumulsum = -1.0;\npublic:\n    /// Number of q points.\n    std::size_t nqpoints;\n    /// Number of phonon modes at each q point.\n    std::size_t nmodes;\n    /// Empty constructor\n    Grid_distribution() = default;\n\n    /// Constructor.\n    /// @param[in] grid - phonon spectrum on a regular grid\n    /// @param[in] _rng - a random number generator\n    Grid_distribution(const Gamma_grid& grid, pcg64& _rng)\n        : rng(_rng), nqpoints(grid.nqpoints),\n          nmodes(grid.get_spectrum_at_q(0).omega.size()) {\n    }\n\n\n    /// Trivial virtual destructor.\n    virtual ~Grid_distribution() {\n    }\n\n\n    /// Fill the 'cumulative' vector.\n    ///\n    /// @param[in] p - vector with the unnormalized probabilities\n    /// of each q point\n    void fill_cumulative(const std::vector<double>& p);\n\n    /// Draw a sample from the distribution.\n    ///\n    /// @return an array containing the mode number and the\n    /// q-point number.\n    std::array<std::size_t, 2> sample() {\n        double u = std::uniform_real_distribution(0., 1.)(this->rng);\n        auto pos = std::lower_bound(\n                       this->cumulative.begin(), this->cumulative.end(), u) -\n                   this->cumulative.begin();\n\n        std::array<std::size_t, 2> nruter;\n        nruter[0] = pos % this->nmodes;\n        nruter[1] = pos / this->nmodes;\n        return nruter;\n    }\n\n    /// @return a tuple containing the mode number, the\n    /// q-point number and particle sign\n    std::tuple<std::size_t, std::size_t, alma::particle_sign>\n    sample_with_sign() {\n        double u = std::uniform_real_distribution(0., 1.)(this->rng);\n        auto pos = std::lower_bound(\n                       this->cumulative.begin(), this->cumulative.end(), u) -\n                   this->cumulative.begin();\n        return std::make_tuple(\n            pos % this->nmodes, pos / this->nmodes, this->signs[pos]);\n    }\n};\n\n/// Objects of this class allow us to sample from a discrete\n/// distribution over a q-point grid with a PMF proportional\n/// to cv / tau, where cv is the contribution to the specific heat\n/// and tau is the relaxation time.\nclass BE_derivative_distribution : public Grid_distribution {\npublic:\n    /// Empty constructor\n\n    BE_derivative_distribution() = default;\n\n    /// Constructor.\n    ///\n    /// @param[in] grid - phonon spectrum on a regular grid\n    /// @param[in] w - scattering rates\n    /// @param[in] T - the temperature in K\n    /// @param[in, out] _rng - a random number generator\n    BE_derivative_distribution(const Gamma_grid& grid,\n                               const Eigen::Ref<const Eigen::ArrayXXd>& w,\n                               double T,\n                               pcg64& _rng);\n};\n\n/// Objects of this class allow us to sample from a discrete\n/// distribution over a q-point grid with a PMF proportional to one\n/// component of the group velocity and to each mode's contribution\n/// to the specific heat.\nclass Nabla_T_distribution : public Grid_distribution {\npublic:\n    /// Empty constructor\n    Nabla_T_distribution() = default;\n    /// Constructor.\n    ///\n    /// @param[in] grid - phonon spectrum on a regular grid\n    /// @param[in] nablaT - any vector parallel to the temperature\n    /// gradient.\n    /// @param[in] T - the temperature in K\n    /// @param[in, out] _rng - a random number generator\n    /// @param[in] theta - rotation of material with respect\n    /// to x-axis\n    Nabla_T_distribution(const Gamma_grid& grid,\n                         const Eigen::Ref<const Eigen::Vector3d>& nablaT,\n                         double T,\n                         pcg64& _rng,\n                         double theta = 0.);\n\n    /// Get number of generated particles for given conditions\n    ///\n    ///@param[in] time - in ps\n    ///@param[in] vol  - box_volume/unitcell_volume\n    ///@param[in] Eff  - deviational particle energy\n    std::size_t Ntogenerate(const double time,\n                            const double vol,\n                            const double Eff);\n\n    /// Returns energy introduced by the generator per unit of time\n    ///@param[in] vol  - box_volume/unitcell_volume\n    double get_energy(const double vol);\n};\n\n/// Objects of this class allow us to sample from a discrete\n/// distribution over a q-point grid given from a vector\nclass ref_distribution : public Grid_distribution {\nprivate:\n    std::mutex shield;\npublic:\n    ///Empty constructor\n    ref_distribution() = default;\n    \n    ref_distribution(const ref_distribution& that) : Grid_distribution(that) {\n    }\n    \n    ref_distribution& operator=(const ref_distribution& that) {\n        this->cumulative = that.cumulative;\n        this->rng        = that.rng;\n        this->signs      = that.signs;\n        this->cumulsum   = that.cumulsum;\n        this->nqpoints   = that.nqpoints;\n        this->nmodes     = that.nmodes;\n        return *this;\n    }\n    \n    \n    \n    /// Constructor.\n    ///\n    /// @param[in] grid - phonon spectrum on a regular grid\n    /// @param[in] fd   - the distribution\n    /// @param[in, out] _rng - a random number generator\n    ref_distribution(const Gamma_grid& grid,\n                     const Eigen::VectorXd&  fd,\n                     pcg64& _rng);\n    \n    /// Get number of generated particles for given conditions\n    ///@param [in] vol - vol_box / volume_unit_cell\n    ///@param [in] Eff - packet energy\n    std::size_t Ntogenerate(const double vol,\n                            const double Eff);\n    \n    \n    std::tuple<std::size_t,std::size_t,\n        alma::particle_sign> sample_dist() {\n        \n        shield.lock();\n        auto res = this->sample_with_sign();\n        shield.unlock();\n        return res;\n    }\n    \n};\n\n\n/// Objects of this class allow us to sample from a discrete\n/// distribution over a q-point grid with a PMF corresponding to an\n/// isothermal wall of given orientation and equilibrium\n/// temperature.  They are also useful for simple periodic systems\n/// if Teq is set accordingly.\nclass Isothermal_wall_distribution : public Grid_distribution {\npublic:\n    /// Empty constructor\n    Isothermal_wall_distribution() = default;\n    /// Constructor.\n    ///\n    /// @param[in] grid - phonon spectrum on a regular grid\n    /// @param[in] Twall - the temperature of the wall in K\n    /// @param[in] Teq - the simulation temperature in K\n    /// @param[in] normal - a normal vector pointing out\n    /// of the wall\n    /// @param[in, out] _rng - a random number generator\n    /// @param[in] theta - rotation of material with respect\n    /// to x-axis\n    Isothermal_wall_distribution(\n        const Gamma_grid& grid,\n        double Twall,\n        double Teq,\n        const Eigen::Ref<const Eigen::Vector3d>& normal,\n        pcg64& _rng,\n        double theta = 0.);\n\n    /// Get number of generated particles for given conditions\n    ///\n    ///@param[in] time - in ps\n    ///@param[in] spf  - area_boundary/unitcell_volume\n    ///@param[in] Eff  - deviational particle energy\n    std::size_t Ntogenerate(const double time,\n                            const double spf,\n                            const double Eff);\n\n    /// Get the flux:\n    ///@param[in] vuc - unitcell_volume\n    double get_flux(const double vuc);\n};\n\n\n/// Objects of this class allow us to sample from a discrete\n/// distribution over a q-point grid with a temperature\n/// different from that of reference\nclass outTref_distribution : public Grid_distribution {\npublic:\n    /// Empty constructor\n    outTref_distribution() = default;\n    /// Constructor.\n    ///\n    /// @param[in] grid - phonon spectrum on a regular grid\n    /// @param[in] Tint - the temperature in K\n    /// @param[in] Tref - reference temperature\n    /// @param[in, out] _rng - a random number generator\n    outTref_distribution(const Gamma_grid& grid,\n                         double Tinit,\n                         double Tref,\n                         pcg64& _rng);\n\n    /// Get number of generated particles for given conditions\n    ///\n    ///@param[in] vol  - box_volume/unitcell_volume\n    ///@param[in] Eff  - deviational particle energy\n    std::size_t Ntogenerate(const double vol, const double Eff);\n\n    /// Returns energy introduced by the generator\n    ///@param[in] vol  - box_volume/unitcell_volume\n    double get_energy(const double vol);\n};\n\n\n/// planar_source_distribution\n/// Emission probability for outgoing modes is proportional to\n/// heat capacity * normal velocity.\nclass planar_source_distribution : public Grid_distribution {\npublic:\n    /// Constructor.\n    ///\n    /// @param[in] grid - phonon spectrum on a regular grid\n    /// @param[in] Tref - temperature in K at which to compute heat capacities\n    /// @param[in] normal - a normal vector pointing out of the source\n    /// @param[in, out] _rng - a random number generator\n    planar_source_distribution(const Gamma_grid& grid,\n                               double Tref,\n                               const Eigen::Ref<const Eigen::Vector3d>& normal,\n                               pcg64& _rng);\n};\n\n\n/// For layered systems, this class\n/// defines the layers of each state\n/// and use them to calculate the coupling\n/// of two states in two stacks by using localization\n/// distribution and Jensen-Shanon divergence\n\nclass layer_coupling {\nprivate:\n    /// Jensen shanon diveregence plus -1\n    /// the function is defined for both STD maps\n    /// and STD vectors\n    inline double JSDm1(std::map<std::string, double>& P,\n                        std::map<std::string, double>& Q) const {\n        double PM = 0., QM = 0.;\n\n\n        for (auto& [layer_id, p] : P) {\n            double q = Q.at(layer_id);\n\n            double M = 0.5 * (p + q);\n\n            if (alma::almost_equal(M, 0.)) {\n                continue;\n            }\n\n            if (!alma::almost_equal(q, 0.)) {\n                QM += q * std::log2(q / M);\n            }\n\n            if (!alma::almost_equal(p, 0.)) {\n                PM += p * std::log2(p / M);\n            }\n        }\n\n        return std::max({1.0 - (0.5 * QM + 0.5 * PM), 0.});\n    }\n\n\n    inline double JSDm1(std::vector<double>& P, std::vector<double>& Q) const {\n        double PM = 0., QM = 0.;\n\n\n        for (std::size_t ii = 0; ii < P.size(); ii++) {\n            double p = P[ii];\n            double q = Q[ii];\n\n            double M = 0.5 * (p + q);\n\n            if (alma::almost_equal(M, 0.)) {\n                continue;\n            }\n\n            if (!alma::almost_equal(q, 0.)) {\n                QM += q * std::log2(q / M);\n            }\n\n            if (!alma::almost_equal(p, 0.)) {\n                PM += p * std::log2(p / M);\n            }\n        }\n\n        return std::max({1.0 - (0.5 * QM + 0.5 * PM), 0.});\n    }\n\n\npublic:\n    /// To store for each material the layers\n    std::map<std::string, std::map<std::string, std::vector<int>>> layers;\n\n    std::map<std::string, std::string> connection;\n    bool stack_injection = false;\n\n    /// Default constructor\n    layer_coupling() = default;\n\n    /// Calculates the coupling rate between two states\n    double get_injection_rate(Eigen::VectorXcd& wfin_,\n                              Eigen::VectorXcd& wfout_,\n                              std::string material_in,\n                              std::string material_out) const;\n};\n\n/// Diffuse mismatch distribution\n\nclass Diffuse_mismatch_distribution {\nprivate:\n    /// Number of branches, indexed via 'A' and 'B'.\n    std::map<char, std::size_t> Nbranches;\n    /// Number of phonon modes, indexed via 'A' and 'B'.\n    std::map<char, std::size_t> Ntot;\n    /// Unit cell volumes, indexed via 'A' and 'B'.\n    std::map<char, double> volume;\n\n    /// Material names:\n    std::string material_A, material_B;\n\n    /// Tuple describing the origin of each available mode in A or B and its\n    /// contribution to the DOS.\n    /// The first element is the material side\n    /// The second element is a branch index\n    /// The third element is a q-point index\n    /// The fourth element is the projection of its velocity on the normal to\n    /// the surface. The fifth element is the heat capacity The sixth element is\n    /// a contribution to the DOS\n    using dos_tuple = std::\n        tuple<char, std::size_t, std::size_t, double, double, Gaussian_for_DOS>;\n    /// Short notation for tuple specifying the material side, mode index, and\n    /// cumulative probability\n    typedef std::tuple<char, std::size_t, double> lookup_entry;\n    /// Lookup table for incident A modes\n    std::vector<std::vector<lookup_entry>> lookup_incidentA;\n    /// Lookup table for incident B modes\n    std::vector<std::vector<lookup_entry>> lookup_incidentB;\n    /// Random number generator.\n    pcg64 rng;\n    /// Reference temperature (for computing heat capacities)\n    double Tref;\n    /// Gather information about all available phonon modes.\n    ///\n    /// @param[in] gridA - phonon spectrum of material A\n    /// @param[in] gridB - phonon spectrum of material B\n    /// @param[in] normal - a normal vector pointing from A to B.\n    /// @param[in] scalebroad - factor modulating all the broadenings\n    /// @return a vector of dos_tuples describing all modes\n    std::vector<dos_tuple> get_modes(\n        const Gamma_grid& gridA,\n        const Gamma_grid& gridB,\n        const Eigen::Ref<const Eigen::Vector3d>& normal,\n        double scalebroad);\n\npublic:\n    /// Empty Constructor.\n    ///\n    ///\n    Diffuse_mismatch_distribution() = default;\n    ///\n    ///\n    /// Constructor.\n    ///\n    /// @param[in] gridA - phonon spectrum of material A\n    /// @param[in] poscarA - crystal structure of material A\n    /// @param[in] gridB - phonon spectrum of material B\n    /// @param[in] poscarB - crystal structure of material B\n    /// @param[in] normal - a normal vector pointing from A to B.\n    /// @param[in] scalebroad - factor modulating all the broadenings\n    /// @param[in, out] _rng - a random number generator\n    /// @param[in] Tref - reference temperature [K]\n    /// @param[in] thicknessA - material A thickness for 2D simulations [nm]\n    /// @param[in] thicknessB - material B thickness for 2D simulations [nm]\n    /// @param[in] coupling - coupling between layers\n    Diffuse_mismatch_distribution(\n        const Gamma_grid& gridA,\n        const Crystal_structure& poscarA,\n        const Gamma_grid& gridB,\n        const Crystal_structure& poscarB,\n        const Eigen::Ref<const Eigen::Vector3d>& normal,\n        double scalebroad,\n        pcg64& _rng,\n        double Tref = 300.0,\n        double thicknessA = -1.,\n        double thicknessB = -1.,\n        layer_coupling coupling = layer_coupling(),\n        std::string materialA = \"None\",\n        std::string materialB = \"None\");\n\n    /// Draw a final state for a particle incident from A or B.\n    ///\n    /// @param[in] incidence - 'A' or 'B'\n    /// @param[in, out] particle - information about the particle, before and\n    /// after the interaction.\n    /// @param[in] account_for_velocity: if true, emission probability is\n    /// proportional to abs(projected velocity).\n    /// @return 'A' or 'B', depending on the direction of emission\n    char reemit(char incidence, D_particle& particle);\n};\n\n/// Objects of this class allow us to simulate completely diffusive\n/// interfaces between two media. An incident phonon undergoes\n/// elastic diffusion and exits the interface in a mode chosen at\n/// random.\n///\n/// In contrast with Diffuse_mismatch_distribution, in this case\n/// the normal vector is not fixed at construction time.\nclass Elastic_interface_distribution {\nprivate:\n    /// Number of q points in grid A.\n    std::size_t nqA;\n    /// Number of q points in grid B.\n    std::size_t nqB;\n    /// Number of branches in grid A.\n    std::size_t nmodesA;\n    /// Number of branches in grid B.\n    std::size_t nmodesB;\n    /// Volume of the unit cell in A.\n    double VA;\n    /// Volume of the unit cell in B.\n    double VB;\n    /// Tuple describing the origin of each available mode\n    /// and its contribution to the DOS.\n    /// The first element is either 'A' or 'B'\n    /// The second element is a branch index\n    /// The third element is a q-point index\n    /// The fourth element is a contribution to the DOS\n    using dos_tuple =\n        std::tuple<char, std::size_t, std::size_t, Gaussian_for_DOS>;\n    /// Mode-to-mode cumulative transition probabilities.\n    /// Only allowed transitions are considered.\n    std::vector<std::vector<double>> cumulative;\n    /// Modes to which the elements of cumulative refer.\n    std::vector<std::vector<std::size_t>> allowed;\n    /// Unit vectors parallel to each of the group velocities\n    /// from the original grid. Each column is a 3-vector.\n    Eigen::MatrixXd directions;\n    /// Random number generator.\n    pcg64& rng;\n    /// Gather information about all available modes.\n    ///\n    /// @param[in] gridA - phonon spectrum of material A\n    /// @param[in] gridB - phonon spectrum of material B\n    /// @param[in] scalebroad - factor modulating all\n    /// the broadenings\n    /// @return a vector of tuples describing all modes\n    std::vector<dos_tuple> get_all_modes(const Gamma_grid& gridA,\n                                         const Gamma_grid& gridB,\n                                         double scalebroad) const;\n\npublic:\n    /// Constructor.\n    ///\n    /// @param[in] gridA - phonon spectrum of material A\n    /// @param[in] gridB - phonon spectrum of material B\n    /// @param[in] scalebroad - factor modulating all\n    /// the broadenings\n    /// @param[in, out] _rng - a random number generator\n    Elastic_interface_distribution(const Gamma_grid& gridA,\n                                   const Gamma_grid& gridB,\n                                   double scalebroad,\n                                   pcg64& _rng);\n    /// Draw a final state for a particle incident from A or B or\n    /// viceversa.\n    ///\n    /// @param[in] incidence - 'A' or 'B'\n    /// @param[in] normal - normal to the interface, pointing\n    /// from A to B.\n    /// @param[in, out] particle - information about the particle,\n    /// before and after the interaction.\n    /// @return 'A' or 'B', depending on the direction of emission\n    char reemit(char incidence,\n                const Eigen::Ref<const Eigen::Vector3d>& normal,\n                D_particle& particle);\n};\n\n// Simple and general class that allows us to simulate completely\n// random elastic scattering.\nclass Elastic_distribution {\nprivate:\n    /// Number of q points in the grid.\n    std::size_t nq;\n    /// Number of branches in the grid..\n    std::size_t nmodes;\n    /// Tuple describing the origin of each available mode\n    /// and its contribution to the DOS.\n    /// The first element is a branch index\n    /// The second element is a q-point index\n    /// The third element is a contribution to the DOS\n    using dos_tuple = std::tuple<std::size_t, std::size_t, Gaussian_for_DOS>;\n    /// Mode-to-mode cumulative transition probabilities.\n    /// Only allowed transitions are considered.\n    std::vector<std::vector<double>> cumulative;\n    /// Modes to which the elements of cumulative refer.\n    std::vector<std::vector<std::size_t>> allowed;\n    /// Unit vectors parallel to each of the group velocities\n    /// from the original grid. Each column is a 3-vector.\n    Eigen::MatrixXd directions;\n    /// Random number generator.\n    pcg64& rng;\n    /// Gather information about all available modes.\n    ///\n    /// @param[in] grid - description of the phonon spectrum\n    /// @param[in] scalebroad - factor modulating all\n    /// the broadenings\n    /// @return a vector of tuples describing all modes\n    std::vector<dos_tuple> get_all_modes(const Gamma_grid& grid,\n                                         double scalebroad) const;\n\npublic:\n    /// Constructor.\n    ///\n    /// @param[in] grid - phonon spectrum of the material\n    /// @param[in] scalebroad - factor modulating all\n    /// the broadenings\n    /// @param[in, out] _rng - a random number generator\n    Elastic_distribution(const Gamma_grid& grid,\n                         double scalebroad,\n                         pcg64& _rng);\n    /// Draw a final state for a particle.\n    ///\n    /// @param[in, out] particle - information about the particle,\n    /// before and after the interaction.\n    void scatter(D_particle& particle);\n\n    /// Draw a final state for a particule with the constraint that\n    /// one component of its group velocity has a predefined sign.\n    ///\n    /// @param[in] normal - direction of the projection\n    /// @param[in] refsign - an integer with the desired sign\n    /// @param[in, out] particle - information about the particle,\n    /// before and after the interaction.\n    void scatter(const Eigen::Ref<const Eigen::Vector3d>& normal,\n                 const int refsign,\n                 D_particle& particle);\n};\n} // namespace alma\n", "meta": {"hexsha": "64fd3d48c75ef980a45e1eca79632d888e357c17", "size": 22547, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/sampling.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/sampling.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/sampling.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.7321711569, "max_line_length": 80, "alphanum_fraction": 0.6201268461, "num_tokens": 5302, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.626124191181315, "lm_q2_score": 0.5428632831725052, "lm_q1q2_score": 0.339899834098418}}
{"text": "#pragma once\n\n#include <Eigen/Dense>\n\nnamespace kde1d {\n\nnamespace tools {\n\n//! applies a function to each non-NaN value, otherwise returns NaN\n//! @param x function argument.\n//! @param func function to be applied.\ntemplate<typename T>\nEigen::MatrixXd\nunaryExpr_or_nan(const Eigen::MatrixXd& x, const T& func)\n{\n  return x.unaryExpr([&func](double y) {\n    if (std::isnan(y)) {\n      return std::numeric_limits<double>::quiet_NaN();\n    } else {\n      return func(y);\n    }\n  });\n}\n\n//! applies a function to each non-NaN value, otherwise returns NaN\n//! @param x function argument.\n//! @param func function to be applied.\ntemplate<typename T>\nEigen::MatrixXd\nunaryExpr_or_nan_int(const Eigen::MatrixXi& x, const T& func)\n{\n  return x.unaryExpr([&func](int y) {\n    if (std::isnan(static_cast<double>(y))) {\n      return std::numeric_limits<double>::quiet_NaN();\n    } else {\n      return func(y);\n    }\n  });\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.\n//!\n//! @return \\f$ f^{-1}(x) \\f$.\ninline Eigen::VectorXd\ninvert_f(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  for (int iter = 0; iter < n_iter; ++iter) {\n    x_tmp = (xh + xl) / 2.0;\n    Eigen::VectorXd 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\n  return x_tmp;\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\nremove_nans(Eigen::VectorXd& 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 an entry is nan or weight is zero, move it to the end\n  size_t last = x.size() - 1;\n  for (size_t i = 0; i < last + 1; i++) {\n    bool is_nan = std::isnan(x(i));\n    if (weights.size() > 0) {\n      is_nan = is_nan | std::isnan(weights(i));\n      is_nan = is_nan | (weights(i) == 0.0);\n    }\n    if (is_nan) {\n      if (weights.size() > 0)\n        std::swap(weights(i), weights(last));\n      std::swap(x(i--), x(last--));\n    }\n  }\n\n  // remove nan rows\n  x.conservativeResize(last + 1);\n  if (weights.size() > 0)\n    weights.conservativeResize(last + 1);\n}\n\ninline Eigen::Matrix<size_t, Eigen::Dynamic, 1>\nget_order(const Eigen::VectorXd& x)\n{\n  Eigen::Matrix<size_t, Eigen::Dynamic, 1> order(x.size());\n  for (long i = 0; i < x.size(); ++i)\n    order(i) = i;\n  std::stable_sort(\n    order.data(),\n    order.data() + order.size(),\n    [&](const size_t& a, const size_t& b) { return (x[a] < x[b]); });\n  return order;\n}\n\n//! Computes bin counts for univariate data via the linear binning strategy.\n//! @param x vector of observations\n//! @param weights vector of weights for each observation.\ninline Eigen::VectorXd\nlinbin(const Eigen::VectorXd& x,\n       double lower,\n       double upper,\n       size_t num_bins,\n       const Eigen::VectorXd& weights)\n{\n  Eigen::VectorXd gcnts = Eigen::VectorXd::Zero(num_bins + 1);\n  double delta = (upper - lower) / num_bins;\n  double rem, lxi;\n  size_t li;\n  for (long i = 0; i < x.size(); ++i) {\n    lxi = (x(i) - lower) / delta;\n    li = static_cast<size_t>(lxi);\n    rem = lxi - li;\n    if (li < num_bins) {\n      gcnts(li) += (1 - rem) * weights(i);\n      gcnts(li + 1) += rem * weights(i);\n    }\n  }\n\n  return gcnts;\n}\n\n} // end kde1d tools\n\n} // end kde1d\n", "meta": {"hexsha": "c73eb033cfde826c8a73487910230b30e6c9fad0", "size": 3935, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/kde1d/tools.hpp", "max_stars_repo_name": "vinecopulib/kde1d-cpp", "max_stars_repo_head_hexsha": "caf253f3a813300f614e9c1b6b2d23269108302a", "max_stars_repo_licenses": ["MIT"], "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/kde1d/tools.hpp", "max_issues_repo_name": "vinecopulib/kde1d-cpp", "max_issues_repo_head_hexsha": "caf253f3a813300f614e9c1b6b2d23269108302a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/kde1d/tools.hpp", "max_forks_repo_name": "vinecopulib/kde1d-cpp", "max_forks_repo_head_hexsha": "caf253f3a813300f614e9c1b6b2d23269108302a", "max_forks_repo_licenses": ["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.1379310345, "max_line_length": 77, "alphanum_fraction": 0.6149936468, "num_tokens": 1147, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.6261241772283034, "lm_q1q2_score": 0.3398998265238403}}
{"text": "/*\n\nPICCANTE\nThe hottest HDR imaging library!\nhttp://vcg.isti.cnr.it/piccante\n\nCopyright (C) 2014\nVisual Computing Laboratory - ISTI CNR\nhttp://vcg.isti.cnr.it\nFirst author: Francesco Banterle\n\nThis Source Code Form is subject to the terms of the Mozilla Public\nLicense, v. 2.0. If a copy of the MPL was not distributed with this\nfile, You can obtain one at http://mozilla.org/MPL/2.0/.\n\n*/\n\n#ifndef PIC_COMPUTER_VISION_ESSENTIAL_MATRIX_HPP\n#define PIC_COMPUTER_VISION_ESSENTIAL_MATRIX_HPP\n\n#include <vector>\n#include <random>\n#include <stdlib.h>\n\n#include \"../base.hpp\"\n\n#include \"../util/math.hpp\"\n#include \"../util/eigen_util.hpp\"\n\n#include \"../computer_vision/triangulation.hpp\"\n#include \"../computer_vision/camera_matrix.hpp\"\n\n#ifndef PIC_DISABLE_EIGEN\n\n#ifndef PIC_EIGEN_NOT_BUNDLED\n    #include \"../externals/Eigen/Dense\"\n    #include \"../externals/Eigen/SVD\"\n    #include \"../externals/Eigen/Geometry\"\n#else\n    #include <Eigen/Dense>\n    #include <Eigen/SVD>\n    #include <Eigen/Geometry>\n#endif\n\n#endif\n\nnamespace pic {\n\n#ifndef PIC_DISABLE_EIGEN\n\n/**\n * @brief computeEssentialMatrix computes the essential matrix, E, from the fundamental\n * matrix, F12, and the two intrics matrices K1 and K2\n * @param F is the fundamental matrix which maps points from camera 1 into camera 2\n * @param K1 is the camera 1 intrics matrix\n * @param K2 is the camera 2 intrics matrix\n * @return\n */\nPIC_INLINE Eigen::Matrix3d computeEssentialMatrix(Eigen::Matrix3d &F, Eigen::Matrix3d &K1, Eigen::Matrix3d &K2)\n{\n    Eigen::Matrix3d K2t = Eigen::Transpose<Eigen::Matrix3d>(K2);\n    return K2t * F * K1;\n}\n\n/**\n * @brief computeEssentialMatrix computes the essential matrix, E, from the fundamental\n * matrix, F, and a single instrics camera, K.\n * @param F\n * @param K\n * @return\n */\nPIC_INLINE Eigen::Matrix3d computeEssentialMatrix(Eigen::Matrix3d &F, Eigen::Matrix3d &K)\n{\n    return computeEssentialMatrix(F, K, K);\n}\n\n/**\n * @brief decomposeEssentialMatrix decomposes an essential matrix E.\n * @param E is the essential matrix. Input.\n * Note1: E = S * R\n * Note2: S = [t]_x\n * Note3: there are four possible cases:\n * 1:     [R1 |  t]\n * 2:     [R1 | -t]\n * 3:     [R2 |  t]\n * 4:     [R2 | -t]\n * @param R1 is one possible rotation matrix. Output.\n * @param R2 is one possible rotation matrix. Output.\n * @param t is the translation vector which is not normalized. Output.\n */\nPIC_INLINE void decomposeEssentialMatrix(Eigen::Matrix3d &E, Eigen::Matrix3d &R1, Eigen::Matrix3d &R2, Eigen::Vector3d &t)\n{\n    //Solving the linear system\n    Eigen::JacobiSVD< Eigen::MatrixXd > svd(E, Eigen::ComputeThinU | Eigen::ComputeThinV);\n    Eigen::Matrix3d U = svd.matrixU();\n    Eigen::Matrix3d V = svd.matrixV();\n\n    //Z matrix\n    Eigen::Matrix3d Z;\n    Z.setZero();\n    Z(0, 1) =  1.0;\n    Z(1, 0) = -1.0;\n\n    //W matrix\n    Eigen::Matrix3d W;\n    W.setZero();\n    W(0, 1) = -1.0;\n    W(1, 0) =  1.0;\n    W(2, 2) =  1.0;\n\n    //Rotation matrices R1 and R2\n    Eigen::Matrix3d Vt = Eigen::Transpose<Eigen::Matrix3d>(V);\n    Eigen::Matrix3d Wt = Eigen::Transpose<Eigen::Matrix3d>(W);\n\n    Eigen::Matrix3d  UVt = U * Vt;\n    double detUVt = UVt.determinant();\n\n    R1 = detUVt * U * W  * Vt;\n    R2 = detUVt * U * Wt * Vt;\n\n    R1 = RotationMatrixRefinement(R1);\n    R2 = RotationMatrixRefinement(R2);\n\n    //Translation vector\n    Eigen::Matrix3d Ut = Eigen::Transpose<Eigen::Matrix3d>(U);\n    Eigen::Matrix3d S = U * Z * Ut;\n\n    t[0] = S(2, 1);\n    t[1] = S(0, 2);\n    t[2] = S(1, 0);\n\n    t.normalize();\n}\n\n/**\n * @brief decomposeEssentialMatrixWithConfiguration decomposes an essential matrix E.\n * @param E is the essential matrix.\n * @param K0\n * @param K1\n * @param points0\n * @param points1\n * @param R\n * @param t\n * @return\n */\nPIC_INLINE bool decomposeEssentialMatrixWithConfiguration(Eigen::Matrix3d &E, Eigen::Matrix3d &K0, Eigen::Matrix3d &K1,\n                                               std::vector< Eigen::Vector2f > &points0, std::vector< Eigen::Vector2f > &points1,\n                                               Eigen::Matrix3d &R, Eigen::Vector3d &t)\n{\n    if(points0.size() != points1.size()) {\n        return false;\n    }\n\n    Eigen::Matrix3d R0, R1;\n    Eigen::Vector3d T;\n    decomposeEssentialMatrix(E, R0, R1, T);\n\n    //for each configuration (R0, -T), (R0, T), (R1, -T), (R1, T)\n    //the sign of reconstructed points is checked\n    int type = -1;\n    int counter = -1;\n\n    for(unsigned int j = 0; j < 4; j++) {\n\n        Eigen::Matrix3d tmp_R = (j < 2) ? R0 : R1;\n        Eigen::Vector3d tmp_T;\n\n        if((j % 2) == 0) {\n            tmp_T = T;\n        } else {\n            tmp_T = -T;\n        }\n\n        Eigen::Matrix34d M0 = getCameraMatrixIdentity(K0);\n        Eigen::Matrix34d M1 = getCameraMatrix(K1, tmp_R, tmp_T);\n\n        int tmp_counter = 0;\n        for(unsigned int i = 0; i < points0.size(); i++) {\n            //homogeneous coordinates\n            Eigen::Vector3d point_0 = Eigen::Vector3d(points0[i][0], points0[i][1], 1.0);\n            Eigen::Vector3d point_1 = Eigen::Vector3d(points1[i][0], points1[i][1], 1.0);\n\n            Eigen::Vector4d p0 = triangulationHartleySturm(point_0, point_1, M0, M1);\n            Eigen::Vector3d p0_euc = Eigen::Vector3d(p0[0], p0[1], p0[2]);\n            Eigen::Vector3d p1 = rigidTransform(p0_euc, tmp_R, tmp_T);\n\n            if((p0[2] >= 0.0) && (p1[2] >= 0.0)) {\n                tmp_counter++;\n            }\n\n        }\n\n        #ifdef PIC_DEBUG\n            printf(\"Front: %d %d\\n\",tmp_counter,j);\n        #endif\n\n        if(tmp_counter > counter) {\n            type = j;\n            counter = tmp_counter;\n        }\n    }\n\n    if(type > -1) {\n\n        R = (type < 2) ? R0 : R1;\n\n        if((type % 2) == 0) {\n            t = T;\n        } else {\n            t = -T;\n        }\n\n        return true;\n\n    } else {\n        R.setZero();\n        t.setZero();\n\n        return false;\n    }\n}\n\n#endif // PIC_DISABLE_EIGEN\n\n} // end namespace pic\n\n#endif // PIC_COMPUTER_VISION_ESSENTIAL_MATRIX_HPP\n", "meta": {"hexsha": "d098b912580dee02968572b20b6ec418deb1cbee", "size": 5964, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/computer_vision/essential_matrix.hpp", "max_stars_repo_name": "ecarpita93/HPC_projet_1", "max_stars_repo_head_hexsha": "a2c00e056c03227711c43cf2ad23d75c6afbe698", "max_stars_repo_licenses": ["Xnet", "X11"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/computer_vision/essential_matrix.hpp", "max_issues_repo_name": "ecarpita93/HPC_projet_1", "max_issues_repo_head_hexsha": "a2c00e056c03227711c43cf2ad23d75c6afbe698", "max_issues_repo_licenses": ["Xnet", "X11"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/computer_vision/essential_matrix.hpp", "max_forks_repo_name": "ecarpita93/HPC_projet_1", "max_forks_repo_head_hexsha": "a2c00e056c03227711c43cf2ad23d75c6afbe698", "max_forks_repo_licenses": ["Xnet", "X11"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.1578947368, "max_line_length": 128, "alphanum_fraction": 0.606639839, "num_tokens": 1860, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6261241632752915, "lm_q2_score": 0.5428632831725052, "lm_q1q2_score": 0.33989981894926247}}
{"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 \"method.h\"\n\n#include <cassert>\n#include <cstdio>\n#include <cstdlib>\n#include <cstring>\n#include <iostream>\n#include <iterator>\n#include <sstream>\n#include <string>\n#include <vector>\n\n#include <boost/uuid/uuid.hpp>\n#include <boost/variant/static_visitor.hpp>\n\n#include \"db/ast-inserter.h\"\n#include \"db/query.h\"\n#include \"method/equation-grammar.h\"\n#include \"method/equation-lexer.h\"\n#include \"method/helper.h\"\n#include \"method/parser.h\"\n#include \"method/printer.h\"\n\nnamespace flint {\nnamespace method {\n\nnamespace {\n\nclass VariantPrinter : public boost::static_visitor<> {\npublic:\n\tVariantPrinter(int k, int n, std::ostream *os)\n\t\t: k_(k)\n\t\t, n_(n)\n\t\t, os_(os)\n\t{}\n\n\tvoid operator()(const Compound &c) const {\n\t\tos_->put('(');\n\t\t*os_ << c.keyword;\n\t\tfor (const auto &child : c.children) {\n\t\t\tos_->put(' ');\n\t\t\tboost::apply_visitor(*this, child);\n\t\t}\n\t\tos_->put(')');\n\t}\n\n\tvoid operator()(const std::string &s) const {\n\t\tif (s[0] != '%') {\n\t\t\t*os_ << s;\n\t\t\treturn;\n\t\t}\n\t\tif (s == \"%time\") {\n\t\t\tif (n_ == 1) {\n\t\t\t\t*os_ << \"(plus %time @dt)\";\n\t\t\t} else {\n\t\t\t\t*os_ << \"(plus %time (divide @dt \"\n\t\t\t\t\t << n_\n\t\t\t\t\t << \"))\";\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\t\t*os_ << s << '#' << k_;\n\t}\n\n\tvoid operator()(int i) const {\n\t\t*os_ << i;\n\t}\n\n\tvoid operator()(const flint::lexer::Rational &r) const {\n\t\t*os_ << r.lexeme;\n\t}\n\n\tvoid operator()(const flint::lexer::Real &r) const {\n\t\t*os_ << r.lexeme;\n\t}\n\nprivate:\n\tint k_;\n\tint n_;\n\tstd::ostream *os_;\n};\n\nclass Inserter : db::AstInserter {\npublic:\n\texplicit Inserter(sqlite3 *db)\n\t\t: db::AstInserter(db)\n\t{\n\t}\n\n\tbool PrintAndInsert(const boost::uuids::uuid &uuid,\n\t\t\t\t\t\tconst Expr &lhs,\n\t\t\t\t\t\tconst Expr &rhs)\n\t{\n\t\tstd::ostringstream oss;\n\t\tif (lhs.which() == kExprIsString) {\n\t\t\tconst std::string &id(boost::get<std::string>(lhs));\n\t\t\tif (!Even(uuid, id, rhs, 2, 2)) return false;\n\t\t\tif (!Even(uuid, id, rhs, 4, 2)) return false;\n\t\t\tif (!Even(uuid, id, rhs, 6, 1)) return false;\n\t\t\tif (!Even(uuid, id, rhs, 0, 1)) return false;\n\t\t\treturn true;\n\t\t} else {\n\t\t\tassert(lhs.which() == kExprIsCompound);\n\t\t\tconst Compound &c(boost::get<Compound>(lhs));\n\t\t\tif (c.children.size() != 2) {\n\t\t\t\tstd::cerr << \"unexpected expression with keyword: \" << c.keyword << std::endl;\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tconst Expr &e(c.children.at(1));\n\t\t\tif (e.which() != kExprIsString) {\n\t\t\t\tstd::cerr << \"got an ill-formed derivative: \" << c.keyword << std::endl;\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tconst std::string &id(boost::get<std::string>(e));\n\t\t\tstd::string name;\n\t\t\tstd::string math;\n\n\t\t\t// #1: k1 = dt * f(t_n, y_n)\n\t\t\toss.str(\"\");\n\t\t\toss << id << \"#1\";\n\t\t\tname = oss.str();\n\t\t\toss.str(\"\");\n\t\t\toss << \"(times @dt \";\n\t\t\tboost::apply_visitor(Printer(&oss), rhs);\n\t\t\toss.put(')');\n\t\t\tmath = oss.str();\n\t\t\tif (!Insert(uuid, name.c_str(), math.c_str()))\n\t\t\t\treturn false;\n\n\t\t\t// #2: y1 = y_n + k1/2\n\t\t\toss.str(\"\");\n\t\t\toss << id << \"#2\";\n\t\t\tname = oss.str();\n\t\t\toss.str(\"\");\n\t\t\toss << \"(plus \" << id << \" (divide \" << id << \"#1 2))\";\n\t\t\tmath = oss.str();\n\t\t\tif (!Insert(uuid, name.c_str(), math.c_str()))\n\t\t\t\treturn false;\n\n\t\t\t// #3: k2 = dt * f(t_n + dt/2, y1)\n\t\t\toss.str(\"\");\n\t\t\toss << id << \"#3\";\n\t\t\tname = oss.str();\n\t\t\toss.str(\"\");\n\t\t\toss << \"(times @dt \";\n\t\t\tboost::apply_visitor(VariantPrinter(2, 2, &oss), rhs);\n\t\t\toss.put(')');\n\t\t\tmath = oss.str();\n\t\t\tif (!Insert(uuid, name.c_str(), math.c_str()))\n\t\t\t\treturn false;\n\n\t\t\t// #4: y2 = y_n + k2/2\n\t\t\toss.str(\"\");\n\t\t\toss << id << \"#4\";\n\t\t\tname = oss.str();\n\t\t\toss.str(\"\");\n\t\t\toss << \"(plus \" << id << \" (divide \" << id << \"#3 2))\";\n\t\t\tmath = oss.str();\n\t\t\tif (!Insert(uuid, name.c_str(), math.c_str()))\n\t\t\t\treturn false;\n\n\t\t\t// #5: k3 = dt * f(t_n + dt/2, y2)\n\t\t\toss.str(\"\");\n\t\t\toss << id << \"#5\";\n\t\t\tname = oss.str();\n\t\t\toss.str(\"\");\n\t\t\toss << \"(times @dt \";\n\t\t\tboost::apply_visitor(VariantPrinter(4, 2, &oss), rhs);\n\t\t\toss.put(')');\n\t\t\tmath = oss.str();\n\t\t\tif (!Insert(uuid, name.c_str(), math.c_str()))\n\t\t\t\treturn false;\n\n\t\t\t// #6: y3 = y_n + k3\n\t\t\toss.str(\"\");\n\t\t\toss << id << \"#6\";\n\t\t\tname = oss.str();\n\t\t\toss.str(\"\");\n\t\t\toss << \"(plus \" << id << ' ' << id << \"#5)\";\n\t\t\tmath = oss.str();\n\t\t\tif (!Insert(uuid, name.c_str(), math.c_str()))\n\t\t\t\treturn false;\n\n\t\t\t// #7: k4 = dt * f(t_n + dt, y3)\n\t\t\toss.str(\"\");\n\t\t\toss << id << \"#7\";\n\t\t\tname = oss.str();\n\t\t\toss.str(\"\");\n\t\t\toss << \"(times @dt \";\n\t\t\tboost::apply_visitor(VariantPrinter(6, 1, &oss), rhs);\n\t\t\toss.put(')');\n\t\t\tmath = oss.str();\n\t\t\tif (!Insert(uuid, name.c_str(), math.c_str()))\n\t\t\t\treturn false;\n\n\t\t\t// #0: y_(n+1) = y_n + (k1 + 2*k2 + 2*k3 + k4)/6\n\t\t\toss.str(\"\");\n\t\t\toss << id << \"#0\";\n\t\t\tname = oss.str();\n\t\t\toss.str(\"\");\n\t\t\toss << \"(plus \" << id << \" (divide (plus \" << id << \"#1 (plus (times 2 \" << id << \"#3) (plus (times 2 \" << id << \"#5) \" << id << \"#7))) 6))\";\n\t\t\tmath = oss.str();\n\t\t\tif (!Insert(uuid, name.c_str(), math.c_str()))\n\t\t\t\treturn false;\n\n\t\t\treturn true;\n\t\t}\n\t}\n\n\tbool PrintAndInsertWiener(const boost::uuids::uuid &,\n\t\t\t\t\t\t\t  const Expr &)\n\t{\n\t\tstd::cerr << \"The Euler method cannot solve SDEs, please use the Euler-Maruyama method instead.\" << std::endl;\n\t\treturn false;\n\t}\n\nprivate:\n\tbool Even(const boost::uuids::uuid &uuid, const std::string &id, const Expr &rhs,\n\t\t\t  int k, int n) {\n\t\tstd::ostringstream oss;\n\t\toss << id << '#' << k;\n\t\tstd::string name = oss.str();\n\t\toss.str(\"\");\n\t\tboost::apply_visitor(VariantPrinter(k, n, &oss), rhs);\n\t\tstd::string math = oss.str();\n\t\treturn Insert(uuid, name.c_str(), math.c_str());\n\t}\n};\n\n}\n\nbool Rk4(sqlite3 *db, const char *input, sqlite3 *output)\n{\n\treturn Parse<8, EquationLexer, EquationGrammar, Inserter>(db, input, output);\n}\n\n}\n}\n", "meta": {"hexsha": "b42e3d891a98c321199ff3e316e9e5dd49789820", "size": 5631, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/method/rk4.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/method/rk4.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/method/rk4.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": 23.4625, "max_line_length": 144, "alphanum_fraction": 0.5478600604, "num_tokens": 1846, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5964331606115021, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.3398790179657903}}
{"text": "#include <Functions/FunctionFactory.h>\n#include <Functions/geometryConverters.h>\n\n#include <boost/geometry.hpp>\n#include <boost/geometry/geometries/point_xy.hpp>\n#include <boost/geometry/geometries/polygon.hpp>\n\n#include <base/logger_useful.h>\n\n#include <Columns/ColumnArray.h>\n#include <Columns/ColumnTuple.h>\n#include <Columns/ColumnConst.h>\n#include <DataTypes/DataTypeArray.h>\n#include <DataTypes/DataTypeTuple.h>\n#include <DataTypes/DataTypeCustomGeo.h>\n\n#include <memory>\n#include <utility>\n\nnamespace DB\n{\n\nnamespace ErrorCodes\n{\n    extern const int ILLEGAL_TYPE_OF_ARGUMENT;\n}\n\n\ntemplate <typename Point>\nclass FunctionPolygonsSymDifference : public IFunction\n{\npublic:\n    static const char * name;\n\n    explicit FunctionPolygonsSymDifference() = default;\n\n    static FunctionPtr create(ContextPtr)\n    {\n        return std::make_shared<FunctionPolygonsSymDifference>();\n    }\n\n    String getName() const override\n    {\n        return name;\n    }\n\n    bool isVariadic() const override\n    {\n        return false;\n    }\n\n    size_t getNumberOfArguments() const override\n    {\n        return 2;\n    }\n\n    DataTypePtr getReturnTypeImpl(const DataTypes &) const override\n    {\n        return DataTypeFactory::instance().get(\"MultiPolygon\");\n    }\n\n    bool isSuitableForShortCircuitArgumentsExecution(const DataTypesWithConstInfo & /*arguments*/) const override { return true; }\n\n    ColumnPtr executeImpl(const ColumnsWithTypeAndName & arguments, const DataTypePtr & /*result_type*/, size_t input_rows_count) const override\n    {\n        MultiPolygonSerializer<Point> serializer;\n\n        callOnTwoGeometryDataTypes<Point>(arguments[0].type, arguments[1].type, [&](const auto & left_type, const auto & right_type)\n        {\n            using LeftConverterType = std::decay_t<decltype(left_type)>;\n            using RightConverterType = std::decay_t<decltype(right_type)>;\n\n            using LeftConverter = typename LeftConverterType::Type;\n            using RightConverter = typename RightConverterType::Type;\n\n            if constexpr (std::is_same_v<ColumnToPointsConverter<Point>, LeftConverter> || std::is_same_v<ColumnToPointsConverter<Point>, RightConverter>)\n                throw Exception(fmt::format(\"Any argument of function {} must not be Point\", getName()), ErrorCodes::ILLEGAL_TYPE_OF_ARGUMENT);\n            else\n            {\n                auto first = LeftConverter::convert(arguments[0].column->convertToFullColumnIfConst());\n                auto second = RightConverter::convert(arguments[1].column->convertToFullColumnIfConst());\n\n                /// NOLINTNEXTLINE(clang-analyzer-core.uninitialized.Assign)\n                for (size_t i = 0; i < input_rows_count; ++i)\n                {\n                    boost::geometry::correct(first[i]);\n                    boost::geometry::correct(second[i]);\n\n                    MultiPolygon<Point> sym_difference{};\n                    boost::geometry::sym_difference(first[i], second[i], sym_difference);\n\n                    serializer.add(sym_difference);\n                }\n            }\n        });\n\n        return serializer.finalize();\n    }\n\n    bool useDefaultImplementationForConstants() const override\n    {\n        return true;\n    }\n};\n\ntemplate <>\nconst char * FunctionPolygonsSymDifference<CartesianPoint>::name = \"polygonsSymDifferenceCartesian\";\n\ntemplate <>\nconst char * FunctionPolygonsSymDifference<SphericalPoint>::name = \"polygonsSymDifferenceSpherical\";\n\nvoid registerFunctionPolygonsSymDifference(FunctionFactory & factory)\n{\n    factory.registerFunction<FunctionPolygonsSymDifference<CartesianPoint>>();\n    factory.registerFunction<FunctionPolygonsSymDifference<SphericalPoint>>();\n}\n\n}\n", "meta": {"hexsha": "4f71876012496536ca74e087290b0a42c5a933c0", "size": 3686, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Functions/polygonsSymDifference.cpp", "max_stars_repo_name": "pdv-ru/ClickHouse", "max_stars_repo_head_hexsha": "0ff975bcf3008fa6c6373cbdfed16328e3863ec5", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2020-01-02T01:52:17.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-15T13:10:37.000Z", "max_issues_repo_path": "src/Functions/polygonsSymDifference.cpp", "max_issues_repo_name": "pdv-ru/ClickHouse", "max_issues_repo_head_hexsha": "0ff975bcf3008fa6c6373cbdfed16328e3863ec5", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2021-12-13T14:45:52.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-20T21:01:10.000Z", "max_forks_repo_path": "src/Functions/polygonsSymDifference.cpp", "max_forks_repo_name": "pdv-ru/ClickHouse", "max_forks_repo_head_hexsha": "0ff975bcf3008fa6c6373cbdfed16328e3863ec5", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-03-17T13:23:06.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-17T13:23:06.000Z", "avg_line_length": 30.974789916, "max_line_length": 154, "alphanum_fraction": 0.6877373847, "num_tokens": 758, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7310585786300049, "lm_q2_score": 0.46490157137338844, "lm_q1q2_score": 0.33987028197108515}}
{"text": "/*===========================================================================*\\\n *                                                                           *\n *                               CoMISo                                      *\n *      Copyright (C) 2008-2009 by Computer Graphics Group, RWTH Aachen      *\n *                           www.rwth-graphics.de                            *\n *                                                                           *\n *---------------------------------------------------------------------------* \n *  This file is part of CoMISo.                                             *\n *                                                                           *\n *  CoMISo 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 *  CoMISo 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 CoMISo.  If not, see <http://www.gnu.org/licenses/>.          *\n *                                                                           *\n\\*===========================================================================*/ \n\n#include <CoMISo/Config/config.hh>\n#include <vector>\n#include <cstdlib>\n#include <iostream>\n\n//------------------------------------------------------------------------------------------------------\n#if COMISO_SUITESPARSE_SPQR_AVAILABLE // additional spqr library required\n//------------------------------------------------------------------------------------------------------\n\n#include <CoMISo/Utils/StopWatch.hh>\n#include <Eigen/Sparse>\n#include <CoMISo/Solver/SparseQRSolver.hh>\n#include <CoMISo/Solver/Eigen_Tools.hh>\n\n\n//------------------------------------------------------------------------------------------------------\n\n// Example main\nint main(void)\n{\n  std::cout << \"---------- 0) Using Sparse QR for solving underdetermined equations and computing Null spaces \" << std::endl;\n\n  typedef Eigen::SparseMatrix< double > SpMatrix;\n  typedef Eigen::MatrixXd DenMatrix;\n  typedef Eigen::Triplet< double > Triplet;\n\n  using COMISO_GMM::operator<<;\n\n  int dimr(4+1);\n  int dimc(4+2);\n\n  std::cout << \"---------- 1) Creating matrix \" << std::endl;\n  std::vector< Triplet > triplets;\n  for( int i = 0; i < dimc*dimr/2; ++i)\n  {\n    int x( rand()%(dimr-1));\n    int y( rand()%dimc);\n    double val( rand()%10);\n    //std::cerr << \" setting (\" << x << \", \" << y << \") to \" << val << std::endl;\n    triplets.push_back( Triplet( x, y, val));\n  }\n  SpMatrix A(dimr,dimc);\n  A.setFromTriplets(triplets.begin(), triplets.end());\n  \n  std::cerr << DenMatrix(A) << std::endl;\n  int m = dimr;\n  int n = dimc;\n\n  if( m < n )\n  {\n    std::swap( m,n);\n    std::cerr << \" ... m < n -> form transposed ...\" << std::endl;\n    A = SpMatrix(A.transpose());\n    // test make also row -rank-deficinet\n    A.middleCols(n-1,1) = A.middleCols(0,1);\n    A.middleCols(0,1) = A.middleCols(n-2,1);\n    std::cerr << DenMatrix(A) << std::endl;\n  }\n\n\n  std::cerr << \" ... m = \" << m << \"; n = \" << n << std::endl;\n  std::cerr << std::endl;\n\n  std::cout << \"---------- 2) Sparse QR \" << std::endl;\n  COMISO::SparseQRSolver spqr;\n  SpMatrix Q,R;\n  std::vector< size_t > P;\n  int rank = spqr.factorize_system_eigen( A, Q, R, P);\n  int nullity(dimc-rank);\n  // setup permutation matrix\n  SpMatrix Pm( n, n);\n  if( !P.empty())\n  {\n    for( size_t i = 0; i < P.size(); ++i)\n    {\n      Pm.coeffRef( (int)i, (int)P[i]) = 1;\n    }\n  }\n\n  std::cout << \"---------- 3) Result \" << std::endl;\n  std::cerr << \" Q         \" << std::endl << DenMatrix(Q) << std::endl;\n  std::cerr << \" R         \" << std::endl << DenMatrix(R) << std::endl;\n  std::cerr << \" P         \" << std::endl << P << std::endl;\n  std::cerr << \" P matrix  \" << std::endl << DenMatrix(Pm) << std::endl;\n  std::cerr << \" Rank      \" << rank << std::endl;\n  std::cerr << \" Nullity   \" << nullity << std::endl;\n  // extract nullspace\n  SpMatrix NullSpace( Q.middleCols( std::max( 0, m-nullity), nullity));\n  std::cerr << \" Nullspace \" << std::endl << DenMatrix(NullSpace) << std::endl;\n  // non nullspace part of R\n  //// assuming superflous column in R is the last (if A is also row deficient)\n  //SpMatrix Rtmp(R.middleCols(0,std::min(n,n-(n-rank))).transpose());\n  //SpMatrix R1( R.transpose().middleCols(0, m-nullity));\n  SpMatrix Rtmp(R.transpose());\n  SpMatrix R1t( Rtmp.middleCols(0,m-nullity));\n  SpMatrix R1( R1t.transpose());\n  std::cerr << \" Non-Nullspace R \" << std::endl << DenMatrix(R1) << std::endl;\n  \n\n\n  std::cout << \"---------- 4) Verification \" << std::endl;\n  SpMatrix reconstructedA(Q*R*Pm.transpose());\n  std::cerr << \" Q orthogonal? \\t \" << ((fabs((Q.transpose()*Q).squaredNorm()-m) < 1e-8)?\"yes\":\"no\") << std::endl;\n  std::cerr << \" A = QR?       \\t \" << (((reconstructedA-A).squaredNorm() < 1e-8)? \"yes\":\"no\") << std::endl;\n\n\n  std::cerr << std::endl << std::endl;\n  std::cout << \"---------- 5) Solving Ax=b (with x without nullspace component)\" << std::endl;\n  // NOTE: A was transposed above to be m>n\n  SpMatrix b(n,1);\n  SpMatrix x(m,1);\n  for( int i = 0; i < n; ++i)\n    b.coeffRef(i,0) = rand()%10;\n  std::cerr << \" ... System Ax = b .. \\n\";\n  std::cerr << \" A \" << std::endl << DenMatrix(A.transpose()) << \" x \" << std::endl << DenMatrix(x) << \" b \" << std::endl << DenMatrix(b) << std::endl;\n\n  std::cout << \"---------- 5.1) test: solve using sparse QR solving ..\" << std::endl;\n  SpMatrix At(A.transpose());\n  spqr.solve_system_eigen( At, b, x);\n\n  std::cerr << \" ... solution x .. \" << std::endl;\n  std::cerr << DenMatrix(x) << std::endl;\n\n  std::cerr << \" ... test: is a solution ? \" << (((A.transpose()*x-b).squaredNorm()<1e-8)?\"yes\":\"no\") << std::endl;\n  std::cerr << \" ... test: has nullspace component ? \" << ((x.transpose()*NullSpace).squaredNorm()<1e-8?\"yes\":\"no\") << std::endl;\n  std::cerr << \" ... Nullspace projections : \" << (x.transpose()*NullSpace) << std::endl;\n\n  std::cout << \"---------- 5.2) test: solve without nullspace ..\" << std::endl;\n  SpMatrix Atnull(At);\n  SpMatrix bnull(b);\n  SpMatrix xnull(m,1);\n  spqr.solve_system_eigen_min2norm( Atnull, bnull, xnull);\n  std::cerr << \" ... solution x .. \" << std::endl;\n  std::cerr << DenMatrix(xnull) << std::endl;\n\n  std::cerr << \" ... test: is a solution ? \" << (((A.transpose()*xnull-bnull).squaredNorm()<1e-8)?\"yes\":\"no\") << std::endl;\n  std::cerr << \" ... test: has nullspace component ? \" << ((xnull.transpose()*NullSpace).squaredNorm()<1e-8?\"yes\":\"no\") << std::endl;\n  std::cerr << \" ... Nullspace projections : \" << (xnull.transpose()*NullSpace) << std::endl;\n\n\n\n  return 0;\n}\n\n#else // COMISO_SUITESPARSE_SPQR_AVAILABLE\n\nint main(void)\n{\n  std::cerr << \" SUITESPARSE_SPQR not available, please re-configure!\\n\";\n  return 0;\n}\n\n#endif  // COMISO_SUITESPARSE_SPQR_AVAILABLE\n\n", "meta": {"hexsha": "0aee3e8797cff58d734bab5c1e2dfd1cf1333b20", "size": 7431, "ext": "cc", "lang": "C++", "max_stars_repo_path": "ACAP_linux/3rd/CoMISo/Examples/small_sparseqr/main.cc", "max_stars_repo_name": "shubhMaheshwari/Automatic-Unpaired-Shape-Deformation-Transfer", "max_stars_repo_head_hexsha": "8c9afe017769f9554706bcd267b6861c4c144999", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 216.0, "max_stars_repo_stars_event_min_datetime": "2018-09-09T11:53:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-19T13:41:35.000Z", "max_issues_repo_path": "ACAP_linux/3rd/CoMISo/Examples/small_sparseqr/main.cc", "max_issues_repo_name": "gaolinorange/Automatic-Unpaired-Shape-Deformation-Transfer", "max_issues_repo_head_hexsha": "8c9afe017769f9554706bcd267b6861c4c144999", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 13.0, "max_issues_repo_issues_event_min_datetime": "2018-10-23T08:29:09.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-08T06:45:34.000Z", "max_forks_repo_path": "ACAP_linux/3rd/CoMISo/Examples/small_sparseqr/main.cc", "max_forks_repo_name": "shubhMaheshwari/Automatic-Unpaired-Shape-Deformation-Transfer", "max_forks_repo_head_hexsha": "8c9afe017769f9554706bcd267b6861c4c144999", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 41.0, "max_forks_repo_forks_event_min_datetime": "2018-09-13T08:50:41.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-23T00:33:54.000Z", "avg_line_length": 41.5139664804, "max_line_length": 151, "alphanum_fraction": 0.4876867178, "num_tokens": 1982, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6959583376458153, "lm_q2_score": 0.48828339529583464, "lm_q1q2_score": 0.3398249000901436}}
{"text": "//==================================================================================================\n/*!\n  @file\n\n    @copyright 2016 NumScale SAS\n\n  Distributed under the Boost Software License, Version 1.0.\n  (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\n*/\n//==================================================================================================\n#ifndef BOOST_SIMD_FUNCTION_SEC_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_SEC_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n\n  /*!\n    @ingroup group-trigonometric\n    This function object returns the secant of the angle in radian: \\f$1/\\cos(x)\\f$.\n\n    @see cos, secd, secpi\n\n\n\n    @par Header <boost/simd/function/sec.hpp>\n\n    @par Example:\n\n      @snippet sec.cpp sec\n\n    @par Possible output:\n\n      @snippet sec.txt sec\n\n  **/\n  IEEEValue sec(IEEEValue const& x);\n} }\n#endif\n\n#include <boost/simd/function/scalar/sec.hpp>\n#include <boost/simd/function/simd/sec.hpp>\n\n#endif\n", "meta": {"hexsha": "ce7318de225a1db368a9b0c8d64199de117d9107", "size": 1003, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/function/sec.hpp", "max_stars_repo_name": "SylvainCorlay/pythran", "max_stars_repo_head_hexsha": "908ec070d837baf77d828d01c3e35e2f4bfa2bfa", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2018-02-25T22:23:33.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-15T15:13:12.000Z", "max_issues_repo_path": "third_party/boost/simd/function/sec.hpp", "max_issues_repo_name": "SylvainCorlay/pythran", "max_issues_repo_head_hexsha": "908ec070d837baf77d828d01c3e35e2f4bfa2bfa", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "third_party/boost/simd/function/sec.hpp", "max_forks_repo_name": "SylvainCorlay/pythran", "max_forks_repo_head_hexsha": "908ec070d837baf77d828d01c3e35e2f4bfa2bfa", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2017-12-12T12:36:31.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-10T14:27:07.000Z", "avg_line_length": 22.2888888889, "max_line_length": 100, "alphanum_fraction": 0.5653040877, "num_tokens": 215, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6959583376458152, "lm_q2_score": 0.48828339529583464, "lm_q1q2_score": 0.33982490009014354}}
{"text": "#ifndef DQMC_CHECKERBOARD_HPP\n#define DQMC_CHECKERBOARD_HPP\n\n#include \"la.hpp\"\n#include \"parameters.hpp\"\n\n#include <boost/multi_array.hpp>\n\n#include <exception>\n#include <cmath>\n\nnamespace dqmc {\n    namespace cx_checkerboard {\n\n\tinline void graph_to_checkerboard(dqmc::parameters& p,\n\t\t\t\t\t  dqmc::cx_workspace& ws) {\n\t    for (int i = 0; i < p.num_bonds; ++i) {\n\t\tws.bond_used[i] = -1;\n\t    }\n\t    \n\t    int bonds_used = 0;\n\t    int coupling_used = 0;\n\t    int sites_used = 0;\n\t    int first_unused_bond = 0;\n\n\n\t    alps::graph_helper<>::bond_iterator itr1, itr1_end;\n\t    int b, s1, s2, bt;\n\t    double t;\n\t    while (bonds_used < p.num_bonds) {\n\t\tcoupling_used = 0;\n\t\twhile (coupling_used < p.ts.size()) {\n\t\t    cx_sp_mat hopping(p.N, p.N);\n\t\t    cx_sp_mat hopping_inv(p.N, p.N);\n\t\t\t\t    \n\t\t    int elements = 0;\n\t\t    \n\t\t    for (int i = 0; i < p.N; ++i) {\n\t\t\tws.site_used[i] = -1;\n\t\t    }\n\t\t\n\t\t    for (boost::tie(itr1, itr1_end) = p.graph.bonds(); itr1 != itr1_end; ++itr1) {\t   \n\t\t\tif (p.graph.bond_type(*itr1) != coupling_used) continue;\n\t\t\t\n\t\t\tb = p.graph.index(*itr1);\n\t\t\ts1 = p.graph.source(*itr1);\n\t\t\ts2 = p.graph.target(*itr1);\n\t\t\tbt = p.graph.bond_type(*itr1);\n\t\t\t\n\t\t\tif (ws.bond_used[b] == 1) continue;\n\t\t\tif (ws.site_used[s1] == 1 || ws.site_used[s2] == 1) continue;\n\n\t\t\tws.chkr_bonds[bt].push_back(bond(s1, s2));\n\n\t\t\tws.bond_used[b] = 1;\n\t\t\tws.site_used[s1] = 1;\n\t\t\tws.site_used[s2] = 1;\n\t\t\tt = p.ts[bt];\t\t\t\n\t\t\thopping.insert(s1, s1) = cx_double(cosh(t * p.delta_tau/2.), 0);\n\t\t\thopping.insert(s2, s2) = cx_double(cosh(t * p.delta_tau/2.), 0);\n\t\t\thopping.insert(s1, s2) = cx_double(sinh(t * p.delta_tau/2.), 0);\n\t\t\thopping.insert(s2, s1) = cx_double(sinh(t * p.delta_tau/2.), 0);\n\n\t\t\thopping_inv.insert(s1, s1) = cx_double(cosh(t * p.delta_tau/2.), 0);\n\t\t\thopping_inv.insert(s2, s2) = cx_double(cosh(t * p.delta_tau/2.), 0);\n\t\t\thopping_inv.insert(s1, s2) = cx_double(-sinh(t * p.delta_tau/2.), 0);\n\t\t\thopping_inv.insert(s2, s1) = cx_double(-sinh(t * p.delta_tau/2.), 0);\n\t\t\t\n\t\t\t// std::cout << \"Using \" << s1 << \" and \" << s2 << std::endl;\n\t\t\t++bonds_used;\n\t\t\t++elements;\n\t\t    }\n\n\t\t    if (elements != 0) {\n\t\t\tfor (int i = 0; i < p.N; ++i) {\n\t\t\t    if(ws.site_used[i] == -1) {\n\t\t\t\thopping.insert(i, i) = 1.;\n\t\t\t\thopping_inv.insert(i, i) = 1.;\n\t\t\t    }\n\t\t\t}\n\t\t\t// arma::mat(hopping).print(\"A hopping matrix\");\n\t\t\tws.sparse_hoppings.push_back(hopping);\n\t\t\tws.sparse_hoppings_inv.push_back(hopping_inv);\n\t\t    }\t\t    \n\t\t    ++coupling_used;\n\t\t}\n\t    }\t    \n\t}\n\n\n\tinline void graph_to_checkerboard_renyi(dqmc::parameters& p, dqmc::cx_workspace& ws) {\n\t    for (int i = 0; i < p.num_bonds; ++i) {\n\t\tws.bond_used[i] = -1;\n\t    }\n\t    \n\t    int bonds_used = 0;\n\t    int coupling_used = 0;\n\t    int sites_used = 0;\n\t    int first_unused_bond = 0;\n\n\t    alps::graph_helper<>::bond_iterator itr1, itr1_end;\n\t    int b, s1, s2, s1a, s2a;\n\t    double t;\n\t    while (bonds_used < p.num_bonds) {\n\t\tcoupling_used = 0;\n\t\twhile (coupling_used < p.ts.size()) {\n\t\t    cx_sp_mat hopping_0(ws.vol, ws.vol), hopping_0_inv(ws.vol, ws.vol),\n\t\t\thopping_1(ws.vol, ws.vol), hopping_1_inv(ws.vol, ws.vol),\n\t\t\thopping_2(ws.vol, ws.vol), hopping_2_inv(ws.vol, ws.vol),\n\t\t\thopping_3(ws.vol, ws.vol), hopping_3_inv(ws.vol, ws.vol);\n\t\t\t\t    \n\t\t    int elements = 0;\n\t\t    \n\t\t    for (int i = 0; i < p.N; ++i) ws.site_used[i] = -1;\n\t\t    for (int i = 0; i < p.N + p.n_B; ++i) {\n\t\t\thopping_0.insert(i, i) = cx_double(1., 0);\n\t\t\thopping_0_inv.insert(i, i) = cx_double(1., 0);\n\t\t\thopping_1.insert(i, i) =  cx_double(1., 0);\n\t\t\thopping_1_inv.insert(i, i) =  cx_double(1., 0);\t\t\t\n\t\t\thopping_2.insert(i, i) =  cx_double(1., 0);\n\t\t\thopping_2_inv.insert(i, i) =  cx_double(1., 0);\n\t\t\thopping_3.insert(i, i) =  cx_double(1., 0);\n\t\t\thopping_3_inv.insert(i, i) =  cx_double(1., 0);\n\t\t    }\n\t\t\n\t\t    for (boost::tie(itr1, itr1_end) = p.graph.bonds(); itr1 != itr1_end; ++itr1) {\t   \n\t\t\tif (p.graph.bond_type(*itr1) != coupling_used) continue;\n\t\t\t\n\t\t\tb = p.graph.index(*itr1);\n\t\t\ts1 = p.graph.source(*itr1);\n\t\t\ts2 = p.graph.target(*itr1);\n\t\t\ts1a = s1;\n\t\t\ts2a = s2;\n\t\t\t\n\t\t\tif (ws.bond_used[b] == 1) continue;\n\t\t\tif (ws.site_used[s1] == 1 || ws.site_used[s2] == 1) continue;\n\t\t    \n\t\t\tws.bond_used[b] = 1;\n\t\t\tws.site_used[s1] = 1;\n\t\t\tws.site_used[s2] = 1;\n\n\t\t\tt = p.ts[p.graph.bond_type(*itr1)];\t\n\n\t\t\tif (s1 >= p.n_A) s1a = s1 + p.n_B;\n\t\t\tif (s2 >= p.n_A) s2a = s2 + p.n_B;\n\t\t\n\t\t\thopping_0.coeffRef(s1, s1) = cx_double(cosh(t * p.delta_tau/2.));\n\t\t\thopping_0.coeffRef(s2, s2) = cx_double(cosh(t * p.delta_tau/2.));\n\t\t\thopping_0.coeffRef(s1, s2) = cx_double(sinh(t * p.delta_tau/2.));\n\t\t\thopping_0.coeffRef(s2, s1) = cx_double(sinh(t * p.delta_tau/2.));\n\n\t\t\thopping_0_inv.coeffRef(s1, s1) = cx_double(cosh(t * p.delta_tau/2.));\n\t\t\thopping_0_inv.coeffRef(s2, s2) = cx_double(cosh(t * p.delta_tau/2.));\n\t\t\thopping_0_inv.coeffRef(s1, s2) = cx_double(-sinh(t * p.delta_tau/2.));\n\t\t\thopping_0_inv.coeffRef(s2, s1) = cx_double(-sinh(t * p.delta_tau/2.));\n\n\t\t\thopping_1.coeffRef(s1, s1) = cx_double(cosh(t * p.delta_tau/2.));\n\t\t\thopping_1.coeffRef(s2, s2) = cx_double(cosh(t * p.delta_tau/2.));\n\t\t\thopping_1.coeffRef(s1, s2) = cx_double(sinh(t * p.delta_tau/2.));\n\t\t\thopping_1.coeffRef(s2, s1) = cx_double(sinh(t * p.delta_tau/2.));\n\n\t\t\thopping_1_inv.coeffRef(s1, s1) = cx_double(cosh(t * p.delta_tau/2.));\n\t\t\thopping_1_inv.coeffRef(s2, s2) = cx_double(cosh(t * p.delta_tau/2.));\n\t\t\thopping_1_inv.coeffRef(s1, s2) = cx_double(-sinh(t * p.delta_tau/2.));\n\t\t\thopping_1_inv.coeffRef(s2, s1) = cx_double(-sinh(t * p.delta_tau/2.));\n\t\t\t\n\t\t\thopping_2.coeffRef(s1a, s1a) = cx_double(cosh(t * p.delta_tau/2.));\n\t\t\thopping_2.coeffRef(s2a, s2a) = cx_double(cosh(t * p.delta_tau/2.));\n\t\t\thopping_2.coeffRef(s1a, s2a) = cx_double(sinh(t * p.delta_tau/2.));\n\t\t\thopping_2.coeffRef(s2a, s1a) = cx_double(sinh(t * p.delta_tau/2.));\n\n\t\t\thopping_2_inv.coeffRef(s1a, s1a) = cx_double(cosh(t * p.delta_tau/2.));\n\t\t\thopping_2_inv.coeffRef(s2a, s2a) = cx_double(cosh(t * p.delta_tau/2.));\n\t\t\thopping_2_inv.coeffRef(s1a, s2a) = cx_double(-sinh(t * p.delta_tau/2.));\n\t\t\thopping_2_inv.coeffRef(s2a, s1a) = cx_double(-sinh(t * p.delta_tau/2.));\n\n\t\t\thopping_3.coeffRef(s1a, s1a) = cx_double(cosh(t * p.delta_tau/2.));\n\t\t\thopping_3.coeffRef(s2a, s2a) = cx_double(cosh(t * p.delta_tau/2.));\n\t\t\thopping_3.coeffRef(s1a, s2a) = cx_double(sinh(t * p.delta_tau/2.));\n\t\t\thopping_3.coeffRef(s2a, s1a) = cx_double(sinh(t * p.delta_tau/2.));\n\n\t\t\thopping_3_inv.coeffRef(s1a, s1a) = cx_double(cosh(t * p.delta_tau/2.));\n\t\t\thopping_3_inv.coeffRef(s2a, s2a) = cx_double(cosh(t * p.delta_tau/2.));\n\t\t\thopping_3_inv.coeffRef(s1a, s2a) = cx_double(-sinh(t * p.delta_tau/2.));\n\t\t\thopping_3_inv.coeffRef(s2a, s1a) = cx_double(-sinh(t * p.delta_tau/2.));\n\n\t\t\t// std::cout << \"Using \" << s1 << \" and \" << s2 << std::endl;\n\t\t\t++bonds_used;\n\t\t\t++elements;\n\t\t    }\n\n\t\t    if (elements != 0) {\n\t\t\t// arma::mat(hopping_0).print(\"Pushing back\");\n\t\t\tusing namespace std;\n\t\t\tws.sparse_hoppings_0.push_back(hopping_0);\n\t\t\tws.sparse_hoppings_0_inv.push_back(hopping_0_inv);\n\n\t\t\tws.sparse_hoppings_1.push_back(hopping_1);\n\t\t\tws.sparse_hoppings_1_inv.push_back(hopping_1_inv);\n\n\t\t\tws.sparse_hoppings_2.push_back(hopping_2);\n\t\t\tws.sparse_hoppings_2_inv.push_back(hopping_2_inv);\n\t\t\t\n\t\t\tws.sparse_hoppings_3.push_back(hopping_3);\n\t\t\tws.sparse_hoppings_3_inv.push_back(hopping_3_inv);\n\t\t    }\t\t    \n\t\t    ++coupling_used;\n\t\t}\n\t    }\t    \n\t}\n\n\n\tinline void hop_left(dqmc::cx_workspace * ws, cx_mat& M, double pref) {\n\t    using namespace std;\n\t    int par = 0;\n\t    \n\t    if (pref > 0) {\n\t\tfor (int i = 0; i < ws->sparse_hoppings.size(); ++i) {\n\t\t    if (par == 0) \n\t\t\tws->hop_temp = ws->sparse_hoppings[i] * M;\n\t\t    else \n\t\t\tM = ws->sparse_hoppings[i] * ws->hop_temp;\n\t\t    par = (par == 0) ? 1 : 0;\n\t\t}\n\t\t\n\t\tfor (int i = ws->sparse_hoppings.size() - 1; i >=0; --i) {\n\t\t    if (par == 0) \n\t\t\tws->hop_temp = ws->sparse_hoppings[i] * M;\n\t\t    else \n\t\t\tM = ws->sparse_hoppings[i] * ws->hop_temp;\n\t\t    par = (par == 0) ? 1 : 0;\n\t\t}\n\t    }\n\t    else {\n\t\tfor (int i = 0; i < ws->sparse_hoppings.size(); ++i) {\n\t\t    if (par == 0) \n\t\t\tws->hop_temp = ws->sparse_hoppings_inv[i] * M;\n\t\t    else \n\t\t\tM = ws->sparse_hoppings_inv[i] * ws->hop_temp;\n\t\t    par = (par == 0) ? 1 : 0;\n\t\t}\n\t\t\n\t\tfor (int i = ws->sparse_hoppings.size() - 1; i >=0; --i) {\n\t\t    if (par == 0) \n\t\t\tws->hop_temp = ws->sparse_hoppings_inv[i] * M;\n\t\t    else \n\t\t\tM = ws->sparse_hoppings_inv[i] * ws->hop_temp;\n\t\t    par = (par == 0) ? 1 : 0;\n\t\t}\n\t    }\n\t    if (par == 1)\n\t\tM = ws->hop_temp;\t    \n\t}\n\n\n\tinline void hop_right(dqmc::cx_workspace * ws, cx_mat& M, double pref) {\n\t    int par = 0;\n\t    \n\t    if (pref > 0) {\n\t\tfor (int i = 0; i < ws->sparse_hoppings.size(); ++i) {\n\t\t    if (par == 0) \n\t\t\tws->hop_temp = M * ws->sparse_hoppings[i];\n\t\t    else\n\t\t\tM = ws->hop_temp * ws->sparse_hoppings[i];\n\t\t    par = (par == 0) ? 1 : 0;\t\t    \n\t\t}\n\t\t\n\t\tfor (int i = ws->sparse_hoppings.size() - 1; i >=0; --i) {\n\t\t    if (par == 0) \n\t\t\tws->hop_temp = M * ws->sparse_hoppings[i];\n\t\t    else\n\t\t\tM = ws->hop_temp * ws->sparse_hoppings[i];\n\t\t    par = (par == 0) ? 1 : 0;\n\t\t}\n\t    }\n\t    else {\n\t\tfor (int i = 0; i < ws->sparse_hoppings.size(); ++i) {\n\t\t    if (par == 0) \n\t\t\tws->hop_temp = M * ws->sparse_hoppings_inv[i];\n\t\t    else\n\t\t\tM = ws->hop_temp * ws->sparse_hoppings_inv[i];\n\t\t    par = (par == 0) ? 1 : 0;\n\t\t}\n\t\t\n\t\tfor (int i = ws->sparse_hoppings.size() - 1; i >=0; --i) {\n\t\t    if (par == 0) \n\t\t\tws->hop_temp = M * ws->sparse_hoppings_inv[i];\n\t\t    else\n\t\t\tM = ws->hop_temp * ws->sparse_hoppings_inv[i];\n\t\t    par = (par == 0) ? 1 : 0;\n\t\t}\n\t    }\n\t    if (par == 1)\n\t\tM = ws->hop_temp;\t    \n\t}\n\n\n\t// inline void hop_left_renyi(dqmc::cx_parameters * p,\n\t// \t\t\t   dqmc::cx_workspace * ws,\n\t// \t\t\t   cx_mat& M, double spin,\n\t// \t\t\t   double pref, int section,\n\t// \t\t\t   int slice) {\n\t//     using namespace std;\n\t//     int par = 0;\n\t//     // cout << \"section \" << section << endl;\n\t//     if (pref > 0) {\n\t// \tfor (int i = 0; i < ws->sparse_hoppings_0.size(); ++i) {\n\t// \t    if (par == 0) {\n\t// \t\tif (section == 0) ws->hop_temp = ws->sparse_hoppings_0[i] * M;\n\t// \t\tif (section == 1) ws->hop_temp = ws->sparse_hoppings_1[i] * M;\n\t// \t\tif (section == 2) ws->hop_temp = ws->sparse_hoppings_2[i] * M;\n\t// \t\tif (section == 3) ws->hop_temp = ws->sparse_hoppings_3[i] * M;\n\t// \t    } else {\n\t// \t\tif (section == 0) M = ws->sparse_hoppings_0[i] * ws->hop_temp ;\n\t// \t\tif (section == 1) M = ws->sparse_hoppings_1[i] * ws->hop_temp ;\n\t// \t\tif (section == 2) M = ws->sparse_hoppings_2[i] * ws->hop_temp ;\n\t// \t\tif (section == 3) M = ws->sparse_hoppings_3[i] * ws->hop_temp ;\n\t// \t    }\n\t// \t    par = (par == 0) ? 1 : 0;\n\t// \t}\n\n\t// \t// dqmc::interaction::onsite_left_fake(p, ws, M, spin, pref, section, slice);\n\t// \tfor (int i = ws->sparse_hoppings_0.size() - 1; i >=0; --i) {\n\t// \t    if (par == 0) {\n\t// \t\tif (section == 0) ws->hop_temp = ws->sparse_hoppings_0[i] * M;\n\t// \t\tif (section == 1) ws->hop_temp = ws->sparse_hoppings_1[i] * M;\n\t// \t\tif (section == 2) ws->hop_temp = ws->sparse_hoppings_2[i] * M;\n\t// \t\tif (section == 3) ws->hop_temp = ws->sparse_hoppings_3[i] * M;\n\t// \t    } else {\n\t// \t\tif (section == 0) M = ws->sparse_hoppings_0[i] * ws->hop_temp ;\n\t// \t\tif (section == 1) M = ws->sparse_hoppings_1[i] * ws->hop_temp ;\n\t// \t\tif (section == 2) M = ws->sparse_hoppings_2[i] * ws->hop_temp ;\n\t// \t\tif (section == 3) M = ws->sparse_hoppings_3[i] * ws->hop_temp ;\n\t// \t    }\n\t// \t    par = (par == 0) ? 1 : 0;\n\t// \t}\n\t//     }\n\t//     else {\n\t// \tfor (int i = 0; i < ws->sparse_hoppings_0.size(); ++i) {\n\t// \t    if (par == 0) {\n\t// \t\tif (section == 0) ws->hop_temp = ws->sparse_hoppings_0_inv[i] * M;\n\t// \t\tif (section == 1) ws->hop_temp = ws->sparse_hoppings_1_inv[i] * M;\n\t// \t\tif (section == 2) ws->hop_temp = ws->sparse_hoppings_2_inv[i] * M;\n\t// \t\tif (section == 3) ws->hop_temp = ws->sparse_hoppings_3_inv[i] * M;\n\t// \t    } else {\n\t// \t\tif (section == 0) M = ws->sparse_hoppings_0_inv[i] * ws->hop_temp ;\n\t// \t\tif (section == 1) M = ws->sparse_hoppings_1_inv[i] * ws->hop_temp ;\n\t// \t\tif (section == 2) M = ws->sparse_hoppings_2_inv[i] * ws->hop_temp ;\n\t// \t\tif (section == 3) M = ws->sparse_hoppings_3_inv[i] * ws->hop_temp ;\n\t// \t    }\n\t// \t    par = (par == 0) ? 1 : 0;\n\t// \t}\n\n\t// \t// dqmc::interaction::onsite_left_fake(p, ws, M, spin, pref, section, slice);\n\t// \tfor (int i = ws->sparse_hoppings_0.size() - 1; i >=0; --i) {\n\t// \t    if (par == 0) {\n\t// \t\tif (section == 0) ws->hop_temp = ws->sparse_hoppings_0_inv[i] * M;\n\t// \t\tif (section == 1) ws->hop_temp = ws->sparse_hoppings_1_inv[i] * M;\n\t// \t\tif (section == 2) ws->hop_temp = ws->sparse_hoppings_2_inv[i] * M;\n\t// \t\tif (section == 3) ws->hop_temp = ws->sparse_hoppings_3_inv[i] * M;\n\t// \t    } else {\n\t// \t\tif (section == 0) M = ws->sparse_hoppings_0_inv[i] * ws->hop_temp ;\n\t// \t\tif (section == 1) M = ws->sparse_hoppings_1_inv[i] * ws->hop_temp ;\n\t// \t\tif (section == 2) M = ws->sparse_hoppings_2_inv[i] * ws->hop_temp ;\n\t// \t\tif (section == 3) M = ws->sparse_hoppings_3_inv[i] * ws->hop_temp ;\n\t// \t    }\n\t// \t    par = (par == 0) ? 1 : 0;\n\t// \t}\n\t//     }\n\t//     if (par == 1)\n\t// \tM = ws->hop_temp;\n\t// }\n\n\n\t// inline void hop_right_renyi(dqmc::cx_parameters * p,\n\t// \t\t\t    dqmc::cx_workspace * ws,\n\t// \t\t\t    cx_mat&__restrict__ M, double spin,\n\t// \t\t\t    double pref, int section,\n\t// \t\t\t    int slice) {\n\t//     int par = 0;\n\n\t//     if (pref > 0) {\n\t// \tfor (int i = 0; i < ws->sparse_hoppings_0.size(); ++i) {\n\t// \t    if (par == 0) {\n\t// \t\tif (section == 0) ws->hop_temp = M * ws->sparse_hoppings_0[i];\n\t// \t\tif (section == 1) ws->hop_temp = M * ws->sparse_hoppings_1[i];\n\t// \t\tif (section == 2) ws->hop_temp = M * ws->sparse_hoppings_2[i];\n\t// \t\tif (section == 3) ws->hop_temp = M * ws->sparse_hoppings_3[i];\n\t// \t    } else {\n\t// \t\tif (section == 0) M = ws->hop_temp * ws->sparse_hoppings_0[i];\n\t// \t\tif (section == 1) M = ws->hop_temp * ws->sparse_hoppings_1[i];\n\t// \t\tif (section == 2) M = ws->hop_temp * ws->sparse_hoppings_2[i];\n\t// \t\tif (section == 3) M = ws->hop_temp * ws->sparse_hoppings_3[i];\n\t// \t    }\n\t// \t    par = (par == 0) ? 1 : 0;\n\t// \t}\n\t\t\n\t// \tfor (int i = ws->sparse_hoppings_0.size() - 1; i >=0; --i) {\n\t// \t    if (par == 0) {\n\t// \t\tif (section == 0) ws->hop_temp = M * ws->sparse_hoppings_0[i];\n\t// \t\tif (section == 1) ws->hop_temp = M * ws->sparse_hoppings_1[i];\n\t// \t\tif (section == 2) ws->hop_temp = M * ws->sparse_hoppings_2[i];\n\t// \t\tif (section == 3) ws->hop_temp = M * ws->sparse_hoppings_3[i];\n\t// \t    } else {\n\t// \t\tif (section == 0) M = ws->hop_temp * ws->sparse_hoppings_0[i];\n\t// \t\tif (section == 1) M = ws->hop_temp * ws->sparse_hoppings_1[i];\n\t// \t\tif (section == 2) M = ws->hop_temp * ws->sparse_hoppings_2[i];\n\t// \t\tif (section == 3) M = ws->hop_temp * ws->sparse_hoppings_3[i];\n\t// \t    }\n\t// \t    par = (par == 0) ? 1 : 0;\n\t// \t}\n\t//     }\n\t//     else {\n\t// \tfor (int i = 0; i < ws->sparse_hoppings_0.size(); ++i) {\n\t// \t    if (par == 0) {\t\t\t\n\t// \t\tif (section == 0) ws->hop_temp = M * ws->sparse_hoppings_0_inv[i];\n\t// \t\tif (section == 1) ws->hop_temp = M * ws->sparse_hoppings_1_inv[i];\n\t// \t\tif (section == 2) ws->hop_temp = M * ws->sparse_hoppings_2_inv[i];\n\t// \t\tif (section == 3) ws->hop_temp = M * ws->sparse_hoppings_3_inv[i];\n\t// \t    } else {\n\t// \t\tif (section == 0) M = ws->hop_temp * ws->sparse_hoppings_0_inv[i];\n\t// \t\tif (section == 1) M = ws->hop_temp * ws->sparse_hoppings_1_inv[i];\n\t// \t\tif (section == 2) M = ws->hop_temp * ws->sparse_hoppings_2_inv[i];\n\t// \t\tif (section == 3) M = ws->hop_temp * ws->sparse_hoppings_3_inv[i];\n\t// \t    }\n\t// \t    par = (par == 0) ? 1 : 0;\n\t// \t}\n\t\t\n\t// \tfor (int i = ws->sparse_hoppings_0.size() - 1; i >=0; --i) {\n\t// \t    if (par == 0) {\t\t\t\n\t// \t\tif (section == 0) ws->hop_temp = M * ws->sparse_hoppings_0_inv[i];\n\t// \t\tif (section == 1) ws->hop_temp = M * ws->sparse_hoppings_1_inv[i];\n\t// \t\tif (section == 2) ws->hop_temp = M * ws->sparse_hoppings_2_inv[i];\n\t// \t\tif (section == 3) ws->hop_temp = M * ws->sparse_hoppings_3_inv[i];\n\t// \t    } else {\n\t// \t\tif (section == 0) M = ws->hop_temp * ws->sparse_hoppings_0_inv[i];\n\t// \t\tif (section == 1) M = ws->hop_temp * ws->sparse_hoppings_1_inv[i];\n\t// \t\tif (section == 2) M = ws->hop_temp * ws->sparse_hoppings_2_inv[i];\n\t// \t\tif (section == 3) M = ws->hop_temp * ws->sparse_hoppings_3_inv[i];\n\t// \t    }\n\t// \t    par = (par == 0) ? 1 : 0;\n\t// \t}\n\t//     }\n\t//     if (par == 1)\n\t// \tM = ws->hop_temp;\n\t// }\t\n    }\n}\n#endif\n", "meta": {"hexsha": "c95d20350d8b9d6bad211537542c3bff4c2f1384", "size": 16324, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "libdqmc/cx_checkerboard_old.hpp", "max_stars_repo_name": "pebroecker/DQMC", "max_stars_repo_head_hexsha": "c4a96cb20347ef722b6ae68c415233d464c89e93", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "libdqmc/cx_checkerboard_old.hpp", "max_issues_repo_name": "pebroecker/DQMC", "max_issues_repo_head_hexsha": "c4a96cb20347ef722b6ae68c415233d464c89e93", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "libdqmc/cx_checkerboard_old.hpp", "max_forks_repo_name": "pebroecker/DQMC", "max_forks_repo_head_hexsha": "c4a96cb20347ef722b6ae68c415233d464c89e93", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.2755555556, "max_line_length": 88, "alphanum_fraction": 0.5665890713, "num_tokens": 6277, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7248702761768248, "lm_q2_score": 0.4687906266262437, "lm_q1q2_score": 0.33981239099167204}}
{"text": "/* -*-C++-*- */\n/*\n   (c) Copyright 1993-2005, Hewlett-Packard Development Company, LP\n\n   See the file named COPYING for license details\n*/\n\n/** @file\n    \\brief Header file for a histogram class.\n*/\n\n///////////////////////////////////////////////////////////////////////////////\n//\n// This package provides histogram gathering classes on variables.\n// StatsHistograms can be used to approximate the mode and percentiles.\n// \n// The histograms collect samples into bins, where the number and size of\n// bins is determined when the histogram object is created.  Two\n// variations are provided: one version rescales bins when values falling\n// outside any bin are sampled, while the other lumps extreme values into\n// the end bins.  The former are called `scaling' histograms while the\n// latter are `fixed'.\n// \n// When specifying the domain of a histogram, you specify the low and\n// high values.  The domain is then all values low <= x < high.  For an\n// integer histogram, where you are (say) interested in collecting values\n// 0 through 11, specify 0 as the low and _12_ as the high point.\n// \n// Note also that the histograms will round the number of bins up to an\n// even number.  This may have unfortunate side-effects when working with\n// integer histograms.  To be safe, you should always specify an even\n// number of bins.  You can usually put an extra bin on the high or low\n// end.\n// \n// Note also that the `width' of bins is always a double, even in the\n// integer histograms.  This is because width is calculated from the high\n// and low points and the number of bins.  If you specify a funny\n// combination of these, you might get (say) bins alternating with two\n// and three bins.\n// \n// There are those who believe that integer histograms probably aren't\n// terribly useful.  They are probably right.\n//\n//////////////////////////////////////////////////////////////////////////////\n\n#ifndef LINTEL_STATSHISTOGRAM_HPP\n#define LINTEL_STATSHISTOGRAM_HPP\n\n#include <vector>\n#include <math.h>\n#include <boost/config.hpp>\n#include <iostream>\n#include <fstream>\n#include <Lintel/AssertBoost.hpp>\n#include <Lintel/Stats.hpp>\n\n\n/// \\brief Histogram statistics class, interface\nclass StatsHistogram : public Stats {\n\npublic:\n    enum HistMode { Uniform, Log, UniformAccum, LogAccum };\n    StatsHistogram();\n    virtual ~StatsHistogram();\n    virtual void reset();\t// Put everything back to initial values\n\n\n    //----Record a new value\n    virtual void add(const double value) = 0;\n    virtual void add(const Stats &stat);\n    virtual void add(const double index_value, const double data_value) = 0;\n\n    //----Histogram-wide access functions\n    virtual double binWidth(unsigned index) const = 0;\n    virtual double binWidth() const { return binWidth(0); }\n    virtual double low() const = 0;\n    virtual double binlow(unsigned index) const = 0;\n    virtual double bincenter(unsigned index) const = 0;\n    virtual double high() const = 0;\n    virtual double binhigh(unsigned index) const = 0;\n    virtual unsigned numBins() const = 0;\n    virtual unsigned numRescales() const = 0;\n    virtual unsigned numGrows() const = 0;\n    virtual bool isScalable() const = 0;\n    virtual bool isGrowable() const = 0;\n    virtual double mode() const = 0;\n    virtual const std::string getType() const = 0;\n    virtual void printTabular(int depth, std::ostream &out) const;\n    virtual void printHistogramRandomInput(std::ostream& out) const;\n    virtual double percentile(double p) const = 0;   // 0.0 <=p<= 1.0\n    virtual unsigned long operator[](unsigned index) const = 0;\n\t\t\t\t// returns the count in a particular bin\n\n\n    //----Value-access functions\n    virtual std::string debugString() const = 0;\n\n    //----Sometimes we want another one of these, just like this one, but fresh.\n    virtual Stats *another_new() const = 0;\n};\n\n\n\n\n/// \\brief Histogram statistics class, uniformly-sized bins\nclass StatsHistogramUniform : public StatsHistogram {\nprotected:\n    unsigned       num_bins;\t// number of bins\n    double        bin_width;\t// width of each bin\n    double        bin_low;\t// lower bound of lowest bin\n    double        bin_high;\t// upper bound of highest bin\n    unsigned long *bins;\t// array of bin-counters\n    const bool    is_scalable;\t// true if rescale on outlier, false if fixed\n    const bool    is_growable;\t// true if grow on outlier, false if fixed\n    unsigned       num_rescales;// number of times rescaled\n    unsigned       num_grows;\t// number of times rescaled\n\n    unsigned sampleBin(const double x) const;\n\npublic:\n    StatsHistogramUniform(const unsigned bins_in,\n\t\t   const double   low_in,\n\t\t   const double   high_in,\n\t\t   const bool     scalable = false,\n\t\t   const bool     growable = false);\n    virtual ~StatsHistogramUniform();\n    virtual void reset();\t// Put everything back to initial values\n\n\n    //----Record a new value\n    virtual void add(const double value);\n    virtual void add(const double index_value, const double data_value);\n    using StatsHistogram::add;\n\n    //----Histogram-wide access functions\n    double binWidth() const { return bin_width; }\n    double binWidth(unsigned /*index*/) const { return bin_width; }\n    double   low()          const { return bin_low; }\n    double binlow(unsigned index) const { return bin_low + index*bin_width; };\n    double bincenter(unsigned index) const { return bin_low + (index+0.5)*bin_width; };\n    double   high()         const { return bin_high; }\n    double binhigh(unsigned index) const { return bin_low + (index+1)*bin_width; };\n    unsigned  numBins() const { return num_bins; }\n    unsigned  numRescales()  const { return num_rescales; }\n    unsigned  numGrows()  const { return num_grows; }\n    bool     isScalable()   const { return is_scalable; }\n    bool     isGrowable()   const { return is_growable; }\n    double   mode() const;\n    double   percentile(double p) const;   // 0.0 <= p <= 1.0\n    unsigned long  operator[](unsigned index) const;\n\t\t\t\t// Count in a particular bin\n\n\n    //----Value-access functions\n    virtual std::string debugString() const;\n\n    virtual const std::string getType() const { return std::string(\"uniform\");}\n    virtual void printRome(int depth, std::ostream &out) const;\n\n    //----Sometimes we want another one of these, just like this one, but fresh.\n    virtual Stats *another_new() const;\n};\n\n/// \\brief Histogram statistics class, exponentially-sized bins\nclass StatsHistogramLog : public StatsHistogram {\nprotected:\n    unsigned\t  num_bins;\t// number of bins\n    double        smallest_bin;\t// width of bin zero\n    double        bin_high;\t// highest bound of highest bin\n    double        bin_scaling;\t// scales log(smallest-bin count) to bin#\n    const bool    is_scalable;\t// true if rescale on outlier, false if fixed\n    unsigned\t  num_rescales; // number of times rescaled\n    unsigned long *bins;\t// array of bin-counters\n\n    unsigned sampleBin(double x) const;\n    double binOffset(double index) const;\n\npublic:\n    StatsHistogramLog(const unsigned bins_in,\n\t\t   const double   low_in,\n\t\t   const double   high_in,\n                   const bool     scalable_in = false);\n    virtual ~StatsHistogramLog();\n    virtual void reset();\t// Put everything back to initial values\n\n\n    //----Record a new value\n    virtual void add(const double value);\n    virtual void add(const double index_value, const double data_value);\n    using StatsHistogram::add;\n\n    //----Histogram-wide access functions\n    double binWidth() const { return binOffset(1.0); }\n    double binWidth(unsigned index) const { return binOffset(index+1)-binOffset(index); }\n    double low() const { return smallest_bin; }\n    double binlow(unsigned index) const { return binOffset(index);};\n    double bincenter(unsigned index) const {return binOffset(index+0.5);};\n    double high() const { return bin_high; };\n    double binhigh(unsigned index) const { return binOffset(index+1); };\n    unsigned  numBins() const { return num_bins; }\n    unsigned  numRescales()  const { return 0; }\n    bool     isScalable()   const { return false; }\n    unsigned  numGrows()  const { return 0; }\n    bool     isGrowable()   const { return false; }\n    double   mode() const;\n    double   percentile(double p) const;   // 0.0 <= p <= 1.0\n    unsigned long  operator[](unsigned index) const;  // Count in a particular bin\n\n    //----Value-access functions\n    virtual std::string debugString() const;\n\n    virtual const std::string getType() const { return std::string(\"log\");}\n    virtual void printRome(int depth, std::ostream &out) const;\n    //----Sometimes we want another one of these, just like this one, but fresh.\n    virtual Stats *another_new() const;\n};\n\n\n\n/// \\brief Histogram statistics class, exponentially-sized bins, sum as well as count\n///\n/// a kind of histogram that has exponentially-sized bins, and that\n/// accumulates a value in the bin as well as the hit count.\n///\n/// The histogram can accumulate either the index value, using\n/// the add(index_value) method, or some other data value associated\n/// with the index value, using the add(index_value, data_value) method.  \n/// For example, the latter form makes it possible to accumulate response \n/// times (data values) as a function of jump distance (index values).\n\nclass StatsHistogramLogAccum : public StatsHistogramLog {\nprivate:\n    double       *val_bins;\n\npublic:\n    StatsHistogramLogAccum(const unsigned bins_in,\n\t\t   const double   low_in,\n\t\t   const double   high_in);\n    virtual ~StatsHistogramLogAccum();\n    virtual void reset();\t// Put everything back to initial values\n\n    //----Record a new value\n    virtual void add(const double value);\n    virtual void add(const double index_value, const double data_value);\n    using StatsHistogram::add;\n\n    //----Histogram-wide access functions\n    double value(unsigned index) const;\t// value in a particular bin\n\n    //----Value-access functions\n    virtual void printRome(int depth, std::ostream &out) const;\n\n    //----Sometimes we want another one of these, just like this one, but fresh.\n    virtual Stats *another_new() const;\n};\n\n\n\n\n\n\n\n\n/// \\brief Histogram statistics class, exponentially-sized bins, sum as well as count\n///\n/// a kind of histogram that has uniformly-sized bins, and that\n/// accumulates a value in the bin as well as the hit count.\n///\n/// The histogram can accumulate either the index value, using\n/// the add(index_value) method, or some other data value associated\n/// with the index value, using the add(index_value, data_value) method.  \n/// For example, the latter form makes it possible to accumulate response \n/// times (data values) as a function of jump distance (index values).\nclass StatsHistogramUniformAccum : public StatsHistogramUniform {\nprivate:\n    double       *val_bins;\n\npublic:\n    StatsHistogramUniformAccum(const unsigned bins_in,\n\t\t   const double   low_in,\n\t\t   const double   high_in,\n   \t           const bool     scalable_in = false,\n   \t           const bool     growable_in = false);\n    virtual ~StatsHistogramUniformAccum();\n    virtual void reset();\t// Put everything back to initial values\n\n    //----Record a new value\n    virtual void add(const double value);\n    virtual void add(const double index_value, const double data_value);\n    using StatsHistogramUniform::add;\n\n    //----Histogram-wide access functions\n    double value(unsigned index) const;\t// value in a particular bin\n\n    //----Value-access functions\n    virtual void printRome(int depth, std::ostream &out) const;\n\n    //----Sometimes we want another one of these, just like this one, but fresh.\n    virtual Stats *another_new() const;\n};\n\n/// \\brief Histogram with specified subranges and different histogram types for each range.\n/// \n/// StatsHistogramGroup: a collection of histograms, allowing multiple \n/// granularities of histograms over different ranges plus a low, high,\n/// and overall stats.\n///\n/// The histograms may be all the same type, or of different types,\n/// depending on the constructor method chosen. For example, a uniform histogram\n/// around 0 and exponential above 100.\nclass StatsHistogramGroup : public Stats {\npublic:\n    // ranges=[0,1,10,100] => low, hist[0..1[, hist[1..10[, hist[10,100[, high\n    StatsHistogramGroup(const StatsHistogram::HistMode mode, \n                        const int sub_hist_buckets,\n                        const std::vector<double> &ranges); \n    StatsHistogramGroup(const std::vector<StatsHistogram::HistMode> &_modes, \n                        const std::vector<int> &sub_hist_buckets,\n                        const std::vector<double> &_ranges); \n    virtual ~StatsHistogramGroup();\n    virtual void reset();\t// Put everything back to initial values\n\n    //----Record a new value\n    virtual void add(const double value);\n    virtual void add(const double index_value, const double data_value);\n    virtual void add(const Stats &stats);\n  \n    const StatsHistogram &getHistogram(unsigned int n) const {\n        INVARIANT(n < histograms.size(),\n                  boost::format(\"Requested out of bounds histogram %d valid range [%d .. %d]\")\n                  % n % 0 % histograms.size());\n        return *histograms[n];\n    }\n\n    const Stats &getLow() const { return low; }\n    const Stats &getHigh() const { return high; }\n    virtual void printRome(int depth, std::ostream &out) const;\n  \nprivate:\n    std::vector<StatsHistogram *> histograms;\n    const std::vector<StatsHistogram::HistMode> modes;\n    const std::vector<double> ranges;\n    Stats low,high;\n};\n\n#endif /* _LINTEL_HISTOGRAM_H_INCLUDED */\n\n\n\n\n\n\n\n", "meta": {"hexsha": "49e743d0ac6321402983b80a0175764ff8e8b697", "size": 13552, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/Lintel/StatsHistogram.hpp", "max_stars_repo_name": "sbu-fsl/Lintel", "max_stars_repo_head_hexsha": "b9e603aaec630c8d3fae2f21fc156582d11d84c9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/Lintel/StatsHistogram.hpp", "max_issues_repo_name": "sbu-fsl/Lintel", "max_issues_repo_head_hexsha": "b9e603aaec630c8d3fae2f21fc156582d11d84c9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-10-05T21:20:36.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-05T21:56:51.000Z", "max_forks_repo_path": "include/Lintel/StatsHistogram.hpp", "max_forks_repo_name": "sbu-fsl/Lintel", "max_forks_repo_head_hexsha": "b9e603aaec630c8d3fae2f21fc156582d11d84c9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.2824858757, "max_line_length": 94, "alphanum_fraction": 0.6816706021, "num_tokens": 3121, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5660185351961015, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.3397177359502127}}
{"text": "#include <algorithm>\n#include <queue>\n#include <vector>\n#include <boost/graph/dijkstra_shortest_paths.hpp>\n#include <boost/property_map/property_map.hpp>\n#include <CGAL/boost/graph/iterator.h>\n#include <CGAL/boost/graph/properties.h>\n\nnamespace Euclid\n{\n\nnamespace _impl\n{\n\ntemplate<typename Mesh>\nstd::vector<vertex_t<Mesh>> mark_shortest_path(\n    const Mesh& mesh,\n    vertex_t<Mesh> src,\n    std::vector<bool>& on_shortest_path_tree)\n{\n    auto vimap = get(boost::vertex_index, mesh);\n    auto eimap = get(boost::edge_index, mesh);\n    std::vector<vertex_t<Mesh>> predecessors(num_vertices(mesh));\n    boost::dijkstra_shortest_paths(\n        mesh,\n        src,\n        boost::predecessor_map(\n            boost::make_iterator_property_map(predecessors.begin(), vimap)));\n\n    for (auto v : vertices(mesh)) {\n        if (v != src) {\n            auto [h, exist] = halfedge(v, predecessors[get(vimap, v)], mesh);\n            assert(exist == true);\n            auto e = edge(h, mesh);\n            on_shortest_path_tree[get(eimap, e)] = true;\n        }\n    }\n\n    return predecessors;\n}\n\ntemplate<typename Mesh>\nvoid spanning_tree_on_dual_graph_not_cross_shortest_path_tree(\n    const Mesh& mesh,\n    const std::vector<bool>& on_shortest_path_tree,\n    std::vector<bool>& cross_spanning_tree)\n{\n    using FD = face_t<Mesh>;\n    auto fimap = get(CGAL::face_index, mesh);\n    auto eimap = get(CGAL::edge_index, mesh);\n\n    auto frange = faces(mesh);\n    auto froot = *frange.first;\n    std::queue<FD> q;\n    q.push(froot);\n    std::vector<bool> touched(num_faces(mesh), false);\n    touched[get(fimap, froot)] = true;\n\n    while (!q.empty()) {\n        auto f = q.front();\n        q.pop();\n        for (auto h : CGAL::halfedges_around_face(halfedge(f, mesh), mesh)) {\n            auto e = edge(h, mesh);\n            auto eidx = get(eimap, e);\n            if (!on_shortest_path_tree[eidx]) {\n                auto ho = opposite(h, mesh);\n                auto fo = face(ho, mesh);\n                auto fidx = get(fimap, fo);\n                if (!touched[fidx]) {\n                    touched[fidx] = true;\n                    q.push(fo);\n                    cross_spanning_tree[eidx] = true;\n                }\n            }\n        }\n    }\n}\n\ntemplate<typename Mesh>\nVertexChain<Mesh> find_generator(\n    const Mesh& mesh,\n    edge_t<Mesh> e,\n    vertex_t<Mesh> src,\n    const std::vector<vertex_t<Mesh>>& predecessors)\n{\n    auto vimap = get(boost::vertex_index, mesh);\n    auto h = halfedge(e, mesh);\n    auto v1 = source(h, mesh);\n    auto v2 = target(h, mesh);\n\n    VertexChain<Mesh> generator;\n    while (v1 != src) {\n        generator.push_back(v1);\n        v1 = predecessors[get(vimap, v1)];\n    }\n    generator.push_back(src);\n    std::reverse(generator.begin(), generator.end());\n    while (v2 != src) {\n        generator.push_back(v2);\n        v2 = predecessors[get(vimap, v2)];\n    }\n    return generator;\n}\n\ntemplate<typename Mesh>\nVertexChains<Mesh> find_generators(\n    const Mesh& mesh,\n    vertex_t<Mesh> src,\n    const std::vector<bool>& on_shortest_path_tree,\n    const std ::vector<bool>& cross_spanning_tree,\n    const std ::vector<vertex_t<Mesh>>& predecessors)\n{\n    auto eimap = get(boost::edge_index, mesh);\n\n    // find edges not on shortest path tree and crossing spanning tree\n    std::vector<edge_t<Mesh>> left_edges;\n    for (auto e : edges(mesh)) {\n        auto eidx = get(eimap, e);\n        if (!on_shortest_path_tree[eidx] && !cross_spanning_tree[eidx]) {\n            left_edges.push_back(e);\n        }\n    }\n\n    // find generators from left edges, should be 2G generators\n    VertexChains<Mesh> generators;\n    for (auto e : left_edges) {\n        generators.push_back(find_generator(mesh, e, src, predecessors));\n    }\n\n    return generators;\n}\n\n} // namespace _impl\n\ntemplate<typename Mesh>\nVertexChains<Mesh> greedy_homotopy_generators(const Mesh& mesh,\n                                              vertex_t<Mesh> v)\n{\n    std::vector<bool> on_shortest_path_tree(num_edges(mesh), false);\n    auto predecessors =\n        _impl::mark_shortest_path(mesh, v, on_shortest_path_tree);\n\n    std::vector<bool> cross_spanning_tree(num_edges(mesh), false);\n    _impl::spanning_tree_on_dual_graph_not_cross_shortest_path_tree(\n        mesh, on_shortest_path_tree, cross_spanning_tree);\n\n    auto generators = _impl::find_generators(\n        mesh, v, on_shortest_path_tree, cross_spanning_tree, predecessors);\n\n    return generators;\n}\n\n} // namespace Euclid\n", "meta": {"hexsha": "b2428f19226da4e36483b98e4f3ee17978811450", "size": 4475, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "include/Euclid/Topology/src/HomotopyGenerator.cpp", "max_stars_repo_name": "unclejimbo/euclid", "max_stars_repo_head_hexsha": "e118abdcdf51b6bc05cf5aa056bf228e052cf501", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 31.0, "max_stars_repo_stars_event_min_datetime": "2017-05-02T07:04:40.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-31T10:00:01.000Z", "max_issues_repo_path": "include/Euclid/Topology/src/HomotopyGenerator.cpp", "max_issues_repo_name": "unclejimbo/euclid", "max_issues_repo_head_hexsha": "e118abdcdf51b6bc05cf5aa056bf228e052cf501", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/Euclid/Topology/src/HomotopyGenerator.cpp", "max_forks_repo_name": "unclejimbo/euclid", "max_forks_repo_head_hexsha": "e118abdcdf51b6bc05cf5aa056bf228e052cf501", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2018-07-02T17:59:35.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-18T07:01:17.000Z", "avg_line_length": 29.0584415584, "max_line_length": 77, "alphanum_fraction": 0.625698324, "num_tokens": 1105, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6442251064863697, "lm_q2_score": 0.5273165233795672, "lm_q1q2_score": 0.3397105434262239}}
{"text": "#include <iostream>\n#include <opencv2/core/core.hpp>\n#include <opencv2/features2d/features2d.hpp>\n#include <opencv2/highgui/highgui.hpp>\n#include <opencv2/calib3d/calib3d.hpp>\n#include \"opencv2/imgproc.hpp\"\n#include \"opencv2/imgcodecs.hpp\"\n#include <ros/ros.h>\n#include <nav_msgs/Path.h>  \n#include<nav_msgs/Odometry.h>\n#include <image_transport/image_transport.h>  \n#include <cv_bridge/cv_bridge.h>\n#include <stdio.h>\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n#define ture 1\n#define false 0\n// #include \"extra.h\" // use this if in OpenCV2 \nusing namespace std;\nusing namespace cv;\nMat frame0,frame1;\n/****************************************************\n * 本程序演示了如何使用2D-2D的特征匹配估计相机运动\n * **************************************************/\n\nvoid find_feature_matches (\n    const Mat& img_1, const Mat& img_2,\n    std::vector<KeyPoint>& keypoints_1,\n    std::vector<KeyPoint>& keypoints_2,\n    std::vector< DMatch >& matches );\n\nvoid pose_estimation_2d2d (\n    std::vector<KeyPoint> keypoints_1,\n    std::vector<KeyPoint> keypoints_2,\n    std::vector< DMatch > matches,\n    Mat& R, Mat& t );\n\n// 像素坐标转相机归一化坐标\nPoint2d pixel2cam ( const Point2d& p, const Mat& K );\n\nvoid imageCallback0(const sensor_msgs::ImageConstPtr& msg)  \n{  \n\n  cv_bridge::CvImagePtr cv_ptr;  \n  try  \n  {  \n     cv_ptr = cv_bridge::toCvCopy(msg, \"mono8\");  \n  }  \n  catch (cv_bridge::Exception& e)  \n  {  \n     ROS_ERROR(\"cv_bridge exception: %s\", e.what());  \n     return;  \n  }  \n\n  // cv::Mat caml;\n  frame0 = cv_ptr->image;  \n//imshow(\"1\",caml);\n  // fail if don't have waitKey(3).\n // cv::waitKey(3);\n} \nvoid imageCallback1(const sensor_msgs::ImageConstPtr& msg)  \n{  \n\n  cv_bridge::CvImagePtr cv_ptr;  \n  try  \n  {  \n     cv_ptr = cv_bridge::toCvCopy(msg, \"mono8\");  \n  }  \n  catch (cv_bridge::Exception& e)  \n  {  \n     ROS_ERROR(\"cv_bridge exception: %s\", e.what());  \n     return;  \n  }  \n\n  // cv::Mat caml;\n  frame1 = cv_ptr->image;  \n//imshow(\"1\",caml);\n  // fail if don't have waitKey(3).\n // cv::waitKey(3);\n} \n\nint main ( int argc, char** argv )\n{\n    // if ( argc != 3 )\n    // {\n    //     cout<<\"usage: pose_estimation_2d2d img1 img2\"<<endl;\n    //     return 1;\n    // }\n    //-- 读取图像\n    ros::init(argc, argv, \"pose\");  \n    ros::NodeHandle nh;  \n    image_transport::ImageTransport it(nh);  \n   image_transport::Subscriber sub0 = it.subscribe(\"camera/fisheye0\", 1, imageCallback0);\n   image_transport::Subscriber sub1 = it.subscribe(\"camera/fisheye1\", 1, imageCallback1);\n    ros::Publisher path_pub = nh.advertise<nav_msgs::Path>(\"trajectory\",1, true);\n    ros::Publisher odom_pub = nh.advertise<nav_msgs::Odometry>(\"odom\", 50);\n    ros::Time current_time, last_time;\n    current_time = ros::Time::now();\n    last_time = ros::Time::now();\n\n    nav_msgs::Path path;\n    //nav_msgs::Path path;\n    path.header.stamp=current_time;\n    path.header.frame_id=\"odom\";\n ros::Rate loop_rate(10);\n \n while (nh.ok())\n {\n     \n\n\n    // Mat img_1 = imread ( \"/home/fsdh/桌面/slambook-master/ch7/1.png\", CV_LOAD_IMAGE_COLOR );\n    // Mat img_2 = imread ( \"/home/fsdh/桌面/slambook-master/ch7/2.png\", CV_LOAD_IMAGE_COLOR );\n   if(!frame0.empty()&!frame1.empty()){\n    vector<KeyPoint> keypoints_1, keypoints_2;\n    vector<DMatch> matches;\n    find_feature_matches ( frame0, frame1, keypoints_1, keypoints_2, matches );\n    cout<<\"一共找到了\"<<matches.size() <<\"组匹配点\"<<endl;\n     current_time = ros::Time::now();\n    //-- 估计两张图像间运动\n    Mat R,t;\n    pose_estimation_2d2d ( keypoints_1, keypoints_2, matches, R, t );\n\n     Eigen::Matrix3d ER;\n        ER<<R.at<double> ( 0,0 ),R.at<double> ( 0,1 ),R.at<double> ( 0,2 ),R.at<double> ( 1,0 ),R.at<double> ( 1,1 ),R.at<double> ( 1,2 ),R.at<double> ( 2,0 ),R.at<double> ( 2,1 ),R.at<double> ( 2,2 );\n         Eigen::Quaterniond q = Eigen::Quaterniond(ER);\n    // geometry_msgs::PoseStamped this_pose_stamped;\n    //     this_pose_stamped.pose.position.x =t.at<double> ( 0,0 );\n    //     this_pose_stamped.pose.position.y = 0;\n    // this_pose_stamped.pose.position.z =0;\n       \n    //     this_pose_stamped.pose.orientation.x=q.x();\n    //     this_pose_stamped.pose.orientation.y=q.y();\n    //     this_pose_stamped.pose.orientation.z=q.z();\n    //     this_pose_stamped.pose.orientation.w=q.w();\n\n    //     this_pose_stamped.header.stamp=current_time;\n    //     this_pose_stamped.header.frame_id=\"odom\";\n    //     path.poses.push_back(this_pose_stamped);\n\n\n   nav_msgs::Odometry odom;\n    odom.header.stamp = current_time;\n    odom.header.frame_id = \"odom\";\n \n    //set the position\n    odom.pose.pose.position.x = 0;\n    odom.pose.pose.position.y = 0;\n    odom.pose.pose.position.z = 0.0;\n    odom.pose.pose.orientation.x =q.x();\n    odom.pose.pose.orientation.y =q.y();\n    odom.pose.pose.orientation.z =q.z();\n    odom.pose.pose.orientation.w =q.w();\n    //set the velocity\n    odom.child_frame_id = \"base_link\";\n    odom.twist.twist.linear.x = 0;\n    odom.twist.twist.linear.y = 0;\n    odom.twist.twist.angular.z = 0;\n        //path_pub.publish(path);\n   \n   \n   \n    odom_pub.publish(odom);\n     //-- 验证E=t^R*scale\n    // Mat t_x = ( Mat_<double> ( 3,3 ) <<\n    //             0,                      -t.at<double> ( 2,0 ),     t.at<double> ( 1,0 ),\n    //             t.at<double> ( 2,0 ),      0,                      -t.at<double> ( 0,0 ),\n    //             -t.at<double> ( 1,0 ),     t.at<double> ( 0,0 ),      0 );\n\n    // cout<<\"t^R=\"<<endl<<t_x*R<<endl;\n\n    // //-- 验证对极约束\n    // Mat K = ( Mat_<double> ( 3,3 ) << 520.9, 0, 325.1, 0, 521.0, 249.7, 0, 0, 1 );\n    // for ( DMatch m: matches )\n    // {\n    //     Point2d pt1 = pixel2cam ( keypoints_1[ m.queryIdx ].pt, K );\n    //     Mat y1 = ( Mat_<double> ( 3,1 ) << pt1.x, pt1.y, 1 );\n    //     Point2d pt2 = pixel2cam ( keypoints_2[ m.trainIdx ].pt, K );\n    //     Mat y2 = ( Mat_<double> ( 3,1 ) << pt2.x, pt2.y, 1 );\n    //     Mat d = y2.t() * t_x * R * y1;\n    //     cout << \"epipolar constraint = \" << d << endl;\n    // }\n   }\n   ros::spinOnce(); \n   last_time = current_time;\n     loop_rate.sleep();   /* code for loop body */\n }\n   \n \n    return 0;\n}\n\nvoid find_feature_matches ( const Mat& img_1, const Mat& img_2,\n                            std::vector<KeyPoint>& keypoints_1,\n                            std::vector<KeyPoint>& keypoints_2,\n                            std::vector< DMatch >& matches )\n{\n    //-- 初始化\n    Mat descriptors_1, descriptors_2;\n    // used in OpenCV3 \n    Ptr<FeatureDetector> detector = ORB::create();\n    Ptr<DescriptorExtractor> descriptor = ORB::create();\n    // use this if you are in OpenCV2 \n    // Ptr<FeatureDetector> detector = FeatureDetector::create ( \"ORB\" );\n    // Ptr<DescriptorExtractor> descriptor = DescriptorExtractor::create ( \"ORB\" );\n    Ptr<DescriptorMatcher> matcher  = DescriptorMatcher::create ( \"BruteForce-Hamming\" );\n    //-- 第一步:检测 Oriented FAST 角点位置\n    detector->detect ( img_1,keypoints_1 );\n    detector->detect ( img_2,keypoints_2 );\n\n    //-- 第二步:根据角点位置计算 BRIEF 描述子\n    descriptor->compute ( img_1, keypoints_1, descriptors_1 );\n    descriptor->compute ( img_2, keypoints_2, descriptors_2 );\n\n    //-- 第三步:对两幅图像中的BRIEF描述子进行匹配，使用 Hamming 距离\n    vector<DMatch> match;\n    //BFMatcher matcher ( NORM_HAMMING );\n    matcher->match ( descriptors_1, descriptors_2, match );\n\n    //-- 第四步:匹配点对筛选\n    double min_dist=10000, max_dist=0;\n\n    //找出所有匹配之间的最小距离和最大距离, 即是最相似的和最不相似的两组点之间的距离\n    for ( int i = 0; i < descriptors_1.rows; i++ )\n    {\n        double dist = match[i].distance;\n        if ( dist < min_dist ) min_dist = dist;\n        if ( dist > max_dist ) max_dist = dist;\n    }\n\n    printf ( \"-- Max dist : %f \\n\", max_dist );\n    printf ( \"-- Min dist : %f \\n\", min_dist );\n\n    //当描述子之间的距离大于两倍的最小距离时,即认为匹配有误.但有时候最小距离会非常小,设置一个经验值30作为下限.\n    for ( int i = 0; i < descriptors_1.rows; i++ )\n    {\n        if ( match[i].distance <= max ( 2*min_dist, 30.0 ) )\n        {\n            matches.push_back ( match[i] );\n        }\n    }\n     Mat img_goodmatch;\n\n    drawMatches ( img_1, keypoints_1, img_2, keypoints_2, matches, img_goodmatch );\n\n    imshow ( \"优化后匹配点对\", img_goodmatch );\n    cv::waitKey(3);\n}\n\n\nPoint2d pixel2cam ( const Point2d& p, const Mat& K )\n{\n    return Point2d\n           (\n               ( p.x - K.at<double> ( 0,2 ) ) / K.at<double> ( 0,0 ),\n               ( p.y - K.at<double> ( 1,2 ) ) / K.at<double> ( 1,1 )\n           );\n}\n\n\nvoid pose_estimation_2d2d ( std::vector<KeyPoint> keypoints_1,\n                            std::vector<KeyPoint> keypoints_2,\n                            std::vector< DMatch > matches,\n                            Mat& R, Mat& t )\n{\n    // 相机内参,TUM Freiburg2\n    Mat K = ( Mat_<double> ( 3,3 ) << 259.8074, 0, 328.0466, 0, 261.0161, 236.2571, 0, 0, 1 );\n\n    //-- 把匹配点转换为vector<Point2f>的形式\n    vector<Point2f> points1;\n    vector<Point2f> points2;\n\n    for ( int i = 0; i < ( int ) matches.size(); i++ )\n    {\n        points1.push_back ( keypoints_1[matches[i].queryIdx].pt );\n        points2.push_back ( keypoints_2[matches[i].trainIdx].pt );\n    }\n\n    //-- 计算基础矩阵\n    Mat fundamental_matrix;\n    fundamental_matrix = findFundamentalMat ( points1, points2, CV_FM_8POINT );\n   // cout<<\"fundamental_matrix is \"<<endl<< fundamental_matrix<<endl;\n\n    //-- 计算本质矩阵\n    Point2d principal_point ( 325.1, 249.7 );\t//相机光心, TUM dataset标定值\n    double focal_length = 521;\t\t\t//相机焦距, TUM dataset标定值\n    Mat essential_matrix;\n    essential_matrix = findEssentialMat ( points1, points2, focal_length, principal_point );\n   // cout<<\"essential_matrix is \"<<endl<< essential_matrix<<endl;\n\n    //-- 计算单应矩阵\n    Mat homography_matrix;\n    homography_matrix = findHomography ( points1, points2, RANSAC, 3 );\n  //  cout<<\"homography_matrix is \"<<endl<<homography_matrix<<endl;\n\n    //-- 从本质矩阵中恢复旋转和平移信息.\n    recoverPose ( essential_matrix, points1, points2, R, t, focal_length, principal_point );\n    // Eigen::Matrix3d ER;\n    // ER<<R.at<double> ( 0,0 ),R.at<double> ( 0,1 ),R.at<double> ( 0,2 ),R.at<double> ( 1,0 ),R.at<double> ( 1,1 ),R.at<double> ( 1,2 ),R.at<double> ( 2,0 ),R.at<double> ( 2,1 ),R.at<double> ( 2,2 );\n    //  Eigen::Quaterniond q = Eigen::Quaterniond(ER);\n    cout<<\"R is \"<<endl<<R<<endl;\n    cout<<\"t is \"<<endl<<t<<endl;\n    // cout<<\"ER is \"<<endl<<q.coeffs()<<endl;\n    \n    \n}", "meta": {"hexsha": "6df238074e05ef48734a8ce5d95f7ca72e4faf2b", "size": 10197, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "votest/src/pose_2d_2d.cpp", "max_stars_repo_name": "zyhupup/-", "max_stars_repo_head_hexsha": "b8885d0f16c22af0199186f78b7b042acfc699f1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-05-07T15:07:36.000Z", "max_stars_repo_stars_event_max_datetime": "2019-05-07T15:07:36.000Z", "max_issues_repo_path": "votest/src/pose_2d_2d.cpp", "max_issues_repo_name": "zyhupup/votest", "max_issues_repo_head_hexsha": "b8885d0f16c22af0199186f78b7b042acfc699f1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "votest/src/pose_2d_2d.cpp", "max_forks_repo_name": "zyhupup/votest", "max_forks_repo_head_hexsha": "b8885d0f16c22af0199186f78b7b042acfc699f1", "max_forks_repo_licenses": ["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.3235294118, "max_line_length": 201, "alphanum_fraction": 0.5930175542, "num_tokens": 3327, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6442251064863697, "lm_q2_score": 0.5273165233795671, "lm_q1q2_score": 0.33971054342622387}}
{"text": "/*\n * main_optimize.cpp\n * Date: 2013-01-28\n * Author: Karsten Ahnert (karsten.ahnert@gmx.de)\n */\n\n#define FUSION_MAX_VECTOR_SIZE 20\n\n#include <gpcxx/tree.hpp>\n#include <gpcxx/generate.hpp>\n#include <gpcxx/operator.hpp>\n#include <gpcxx/eval.hpp>\n#include <gpcxx/evolve.hpp>\n#include <gpcxx/io.hpp>\n#include <gpcxx/stat.hpp>\n#include <gpcxx/app.hpp>\n\n#include <boost/fusion/include/make_vector.hpp>\n\n#include <iostream>\n#include <random>\n#include <vector>\n#include <functional>\n\n\nconst std::string tab = \"\\t\";\n\n\nnamespace pl = std::placeholders;\nnamespace fusion = boost::fusion;\n\nint main( int argc , char *argv[] )\n{\n    typedef std::mt19937 rng_type ;\n    typedef double value_type;\n    typedef char symbol_type;\n    typedef gpcxx::regression_training_data< value_type , 3 > training_data_type;\n    typedef gpcxx::regression_context< value_type , 3 > context_type;\n    typedef std::vector< value_type > fitness_type;\n\n    auto eval = gpcxx::make_static_eval_erc< value_type , symbol_type , context_type >(\n        fusion::make_vector( 1.0 , std::normal_distribution<>( 0.0 , 1.0 ) ) ,\n        fusion::make_vector(\n            fusion::make_vector( 'x' , []( context_type const& t ) { return t[0]; } )\n          , fusion::make_vector( 'y' , []( context_type const& t ) { return t[1]; } )\n          , fusion::make_vector( 'z' , []( context_type const& t ) { return t[2]; } )          \n          ) ,\n        fusion::make_vector(\n            fusion::make_vector( 's' , []( double v ) -> double { return std::sin( v ); } )\n          , fusion::make_vector( 'c' , []( double v ) -> double { return std::cos( v ); } ) \n          ) ,\n        fusion::make_vector(\n            fusion::make_vector( '+' , std::plus< double >() )\n          , fusion::make_vector( '-' , std::minus< double >() )\n          , fusion::make_vector( '*' , std::multiplies< double >() ) \n          , fusion::make_vector( '/' , std::divides< double >() ) \n          ) );\n    typedef decltype( eval ) eval_type;\n    typedef eval_type::node_attribute_type node_attribute_type;\n    \n    typedef gpcxx::basic_tree< node_attribute_type > tree_type;\n    typedef std::vector< tree_type > population_type;\n    typedef gpcxx::static_pipeline< population_type , fitness_type , rng_type > evolver_type;\n    \n    rng_type rng;\n\n    training_data_type c;\n    gpcxx::generate_regression_test_data( c , 1024 , rng , []( double x1 , double x2 , double x3 )\n                    { return  x1 * x1 * x1 + 1.0 / 10.0 * x2 * x2 - 3.0 / 4.0 * ( x3 - 4.0 ) + 1.0 ; } );\n\n\n    \n    size_t population_size = 512;\n    size_t number_elite = 1;\n    double mutation_rate = 0.2;\n    double crossover_rate = 0.6;\n    double reproduction_rate = 0.3;\n    size_t min_tree_height = 8 , max_tree_height = 8;\n\n    auto terminal_gen = eval.get_terminal_symbol_distribution();\n    auto unary_gen = eval.get_unary_symbol_distribution();\n    auto binary_gen = eval.get_binary_symbol_distribution();\n    std::array< double , 3 > weights = {{ 2.0 * double( terminal_gen.num_symbols() ) ,\n                                       double( unary_gen.num_symbols() ) ,\n                                       double( binary_gen.num_symbols() ) }};\n    auto tree_generator = gpcxx::make_ramp( rng , terminal_gen , unary_gen , binary_gen , min_tree_height , max_tree_height , 0.5 , weights );\n    \n\n    evolver_type evolver( number_elite , mutation_rate , crossover_rate , reproduction_rate , rng );\n    fitness_type fitness( population_size , 0.0 );\n    population_type population( population_size );\n\n\n    auto fitness_f = gpcxx::regression_fitness< eval_type >( eval );\n    evolver.mutation_function() = gpcxx::make_mutation(\n        gpcxx::make_simple_mutation_strategy( rng , terminal_gen , unary_gen , binary_gen ) ,\n        gpcxx::make_random_selector( rng ) );\n    evolver.crossover_function() = gpcxx::make_crossover( \n        gpcxx::make_one_point_crossover_strategy( rng , 10 ) ,\n        gpcxx::make_random_selector( rng ) );\n    evolver.reproduction_function() = gpcxx::make_reproduce( gpcxx::make_random_selector( rng ) );\n\n\n    // initialize population with random trees and evaluate fitness\n    for( size_t i=0 ; i<population.size() ; ++i )\n    {\n        tree_generator( population[i] );\n        fitness[i] = fitness_f( population[i] , c );\n    }\n    std::cout << \"Best individuals\" << std::endl << gpcxx::best_individuals( population , fitness ) << std::endl;\n    std::cout << \"Statistics : \" << gpcxx::calc_population_statistics( population ) << std::endl;\n    std::cout << std::endl << std::endl;\n\n    for( size_t i=0 ; i<100 ; ++i )\n    {\n        evolver.next_generation( population , fitness );\n        for( size_t i=0 ; i<population.size() ; ++i )\n            fitness[i] = fitness_f( population[i] , c );\n        \n        std::cout << \"Iteration \" << i << std::endl;\n        std::cout << \"Best individuals\" << std::endl << gpcxx::best_individuals( population , fitness , 1 ) << std::endl;\n        std::cout << \"Statistics : \" << gpcxx::calc_population_statistics( population ) << std::endl << std::endl;\n    }\n\n    return 0;\n}\n", "meta": {"hexsha": "01ebd5226a0b65a0b81301c912a911638d4cb76a", "size": 5059, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/symbolic_regression/symb_reg_basic_tree_erc.cpp", "max_stars_repo_name": "gchoinka/gpcxx", "max_stars_repo_head_hexsha": "143398d8a12cdc39735e6ef50c3f8a44a6e6360f", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 21.0, "max_stars_repo_stars_event_min_datetime": "2015-05-15T08:01:37.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-12T07:28:54.000Z", "max_issues_repo_path": "examples/symbolic_regression/symb_reg_basic_tree_erc.cpp", "max_issues_repo_name": "gchoinka/gpcxx", "max_issues_repo_head_hexsha": "143398d8a12cdc39735e6ef50c3f8a44a6e6360f", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2015-03-26T23:48:04.000Z", "max_issues_repo_issues_event_max_datetime": "2016-02-29T14:16:37.000Z", "max_forks_repo_path": "examples/symbolic_regression/symb_reg_basic_tree_erc.cpp", "max_forks_repo_name": "gchoinka/gpcxx", "max_forks_repo_head_hexsha": "143398d8a12cdc39735e6ef50c3f8a44a6e6360f", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2015-02-12T21:39:01.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-01T05:14:08.000Z", "avg_line_length": 39.8346456693, "max_line_length": 142, "alphanum_fraction": 0.6273967187, "num_tokens": 1351, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7185943925708561, "lm_q2_score": 0.47268347662043286, "lm_q1q2_score": 0.3396676957603404}}
{"text": "#include <iostream>\n#include <armadillo>\n#include <vector>\n#include <string>\n#include \"KS2sample.hpp\"\n\n\nint main(int argc, char **argv)\n{\n   \n    std::vector<std::string> files(4);\n    files[0] = \"Rayleigh1.bin\";\n    files[1] = \"Rayleigh2.bin\";\n    files[2] = \"Rayleigh3.bin\";\n    files[3] = \"Exponential.bin\";\n\n    for(int ii=0; ii<4; ii++)\n    {\n        arma::fvec alldata;\n        alldata.load(files[ii], arma::raw_binary);\n\n        int nrows = alldata.size() / 2;\n        arma::fmat x(alldata.memptr(), nrows,2, false);\n\n        KS2sample worker(nrows);\n        \n        double prob = worker.test(x.colptr(0), x.colptr(1));\n        std::cout << \"File: \" << files[ii] << \" Prob: \" << prob << \"\\n\";\n    }\n\n}\n", "meta": {"hexsha": "b4a5fbd5f93700530085ff420d1219df4bb08035", "size": 710, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/KS2/test_stat.cpp", "max_stars_repo_name": "dbekaert/fringe", "max_stars_repo_head_hexsha": "c696c3651777d8007406fbce4470a16a39948f74", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 52.0, "max_stars_repo_stars_event_min_datetime": "2020-03-29T18:57:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T00:35:53.000Z", "max_issues_repo_path": "tests/KS2/test_stat.cpp", "max_issues_repo_name": "dbekaert/fringe", "max_issues_repo_head_hexsha": "c696c3651777d8007406fbce4470a16a39948f74", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 48.0, "max_issues_repo_issues_event_min_datetime": "2020-04-12T12:11:48.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-23T06:00:21.000Z", "max_forks_repo_path": "tests/KS2/test_stat.cpp", "max_forks_repo_name": "dbekaert/fringe", "max_forks_repo_head_hexsha": "c696c3651777d8007406fbce4470a16a39948f74", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 39.0, "max_forks_repo_forks_event_min_datetime": "2020-03-29T14:39:51.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-17T02:04:27.000Z", "avg_line_length": 22.1875, "max_line_length": 72, "alphanum_fraction": 0.5535211268, "num_tokens": 214, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6688802603710086, "lm_q2_score": 0.5078118642792044, "lm_q1q2_score": 0.3396653319985615}}
{"text": "#ifndef STAN_MATH_REV_MAT_FUN_TCROSSPROD_HPP\n#define STAN_MATH_REV_MAT_FUN_TCROSSPROD_HPP\n\n#include <stan/math/prim/mat/fun/Eigen.hpp>\n#include <stan/math/prim/mat/fun/typedefs.hpp>\n#include <stan/math/rev/core.hpp>\n#include <stan/math/rev/mat/fun/Eigen_NumTraits.hpp>\n#include <stan/math/rev/mat/fun/typedefs.hpp>\n#include <stan/math/rev/mat/fun/dot_product.hpp>\n#include <stan/math/rev/mat/fun/dot_self.hpp>\n#include <stan/math/rev/mat/fun/columns_dot_self.hpp>\n#include <boost/math/tools/promotion.hpp>\n#include <vector>\n\nnamespace stan {\nnamespace math {\n\n/**\n * Returns the result of post-multiplying a matrix by its\n * own transpose.\n * @param M Matrix to multiply.\n * @return M times its transpose.\n */\ninline matrix_v tcrossprod(const matrix_v& M) {\n  if (M.rows() == 0)\n    return matrix_v(0, 0);\n  // if (M.rows() == 1)\n  //   return M * M.transpose();\n\n  // WAS JUST THIS\n  // matrix_v result(M.rows(), M.rows());\n  // return result.setZero().selfadjointView<Eigen::Upper>().rankUpdate(M);\n\n  matrix_v MMt(M.rows(), M.rows());\n\n  vari** vs\n      = reinterpret_cast<vari**>(ChainableStack::instance().memalloc_.alloc(\n          (M.rows() * M.cols()) * sizeof(vari*)));\n  int pos = 0;\n  for (int m = 0; m < M.rows(); ++m)\n    for (int n = 0; n < M.cols(); ++n)\n      vs[pos++] = M(m, n).vi_;\n  for (int m = 0; m < M.rows(); ++m)\n    MMt(m, m) = var(new dot_self_vari(vs + m * M.cols(), M.cols()));\n  for (int m = 0; m < M.rows(); ++m) {\n    for (int n = 0; n < m; ++n) {\n      MMt(m, n) = var(new dot_product_vari<var, var>(\n          vs + m * M.cols(), vs + n * M.cols(), M.cols()));\n      MMt(n, m) = MMt(m, n);\n    }\n  }\n  return MMt;\n}\n\n}  // namespace math\n}  // namespace stan\n#endif\n", "meta": {"hexsha": "4ff28059551d3fc1d9312d4644e03adafc4d09da", "size": 1699, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "stan/math/rev/mat/fun/tcrossprod.hpp", "max_stars_repo_name": "jrmie/math", "max_stars_repo_head_hexsha": "2850ec262181075a5843968e805dc9ad1654e069", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "stan/math/rev/mat/fun/tcrossprod.hpp", "max_issues_repo_name": "jrmie/math", "max_issues_repo_head_hexsha": "2850ec262181075a5843968e805dc9ad1654e069", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "stan/math/rev/mat/fun/tcrossprod.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": 29.2931034483, "max_line_length": 76, "alphanum_fraction": 0.6215420836, "num_tokens": 533, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6688802603710086, "lm_q2_score": 0.5078118642792044, "lm_q1q2_score": 0.3396653319985615}}
{"text": "#ifndef SKYLARK_COMBBLAS_MIXED_GEMM_HPP\n#define SKYLARK_COMBBLAS_MIXED_GEMM_HPP\n\n#include <boost/mpi.hpp>\n#include \"../exception.hpp\"\n\n#if SKYLARK_HAVE_COMBBLAS\n#include <CombBLAS.h>\n#include <CommGrid.h>\n#endif\n\n#include \"../../utility/external/view.hpp\"\n#include \"../../utility/external/combblas_comm_grid.hpp\"\n#include \"../../utility/external/elemental_comm_grid.hpp\"\n\n\n#if SKYLARK_HAVE_COMBBLAS\n\nnamespace skylark { namespace base {\n\nnamespace detail {\n\n/// only compute local product:\n///   elem(n x k) x local_part_cb(k x m) -> array(n x m)\ntemplate<typename index_type, typename value_type>\ninline void mixed_gemm_local_part_nn (\n        const double alpha,\n        const SpParMat<index_type, value_type, SpDCCols<index_type, value_type> > &A,\n        const El::DistMatrix<value_type, El::STAR, El::STAR> &S,\n        const double beta,\n        std::vector<value_type> &local_matrix) {\n\n    typedef SpDCCols< index_type, value_type > col_t;\n    typedef SpParMat< index_type, value_type, col_t > matrix_type;\n    matrix_type &_A = const_cast<matrix_type&>(A);\n    col_t &data = _A.seq();\n\n    //FIXME\n    local_matrix.resize(S.Width() * data.getnrow(), 0);\n    size_t cb_col_offset = utility::cb_my_col_offset(A);\n\n    for(typename col_t::SpColIter col = data.begcol();\n        col != data.endcol(); col++) {\n        for(typename col_t::SpColIter::NzIter nz = data.begnz(col);\n            nz != data.endnz(col); nz++) {\n\n            // we want local index here to fill local dense matrix\n            index_type rowid = nz.rowid();\n            // column needs to be global\n            index_type colid = col.colid() + cb_col_offset;\n\n            // compute application of S to yield a partial row in the result.\n            for(size_t bcol = 0; bcol < S.Width(); ++bcol) {\n                local_matrix[rowid * S.Width() + bcol] +=\n                        alpha * S.Get(colid, bcol) * nz.value();\n            }\n        }\n    }\n}\n\n\n/// implementing gemm for CB * (*/*) = (SOMETHING/*)\n//FIXME: benchmark against one-sided\ntemplate<typename index_type, typename value_type, El::Distribution col_d>\ninline void inner_panel_mixed_gemm_impl_nn(\n        const double alpha,\n        const SpParMat<index_type, value_type, SpDCCols<index_type, value_type> > &A,\n        const El::DistMatrix<value_type, El::STAR, El::STAR> &S,\n        const double beta,\n        El::DistMatrix<value_type, col_d, El::STAR> &C) {\n\n    int n_proc_side   = A.getcommgrid()->GetGridRows();\n    int output_width  = S.Width();\n    int output_height = A.getnrow();\n\n    size_t rank = A.getcommgrid()->GetRank();\n    size_t cb_row_offset = utility::cb_my_row_offset(A);\n\n    typedef SpDCCols< index_type, value_type > col_t;\n    typedef SpParMat< index_type, value_type, col_t > matrix_type;\n    matrix_type &_A = const_cast<matrix_type&>(A);\n    col_t &data = _A.seq();\n\n    // 1) compute the local values still using the CombBLAS distribution (2D\n    //    processor grid). We assume the result is dense.\n    std::vector<double> local_matrix;\n    mixed_gemm_local_part_nn(alpha, A, S, 0.0, local_matrix);\n\n    // 2) reduce first along rows so that each processor owns the values in\n    //    the output row of the SOMETHING/* matrix and values for processors in\n    //    the same processor column.\n    boost::mpi::communicator my_row_comm(\n            A.getcommgrid()->GetRowWorld(), boost::mpi::comm_duplicate);\n\n    // storage for other procs in same row communicator: rank -> (row, values)\n    typedef std::vector<std::pair<int, std::vector<double> > > for_rank_t;\n    std::vector<for_rank_t> for_rank(n_proc_side);\n\n    for(size_t local_row = 0; local_row < data.getnrow(); ++local_row) {\n\n        size_t row = local_row + cb_row_offset;\n\n        // the owner for VR/* and VC/* matrices is independent of the column\n        size_t target_proc = utility::owner(C, row, static_cast<size_t>(0));\n\n        // if the target processor is not in the current row communicator, get\n        // the value in the processor grid sharing the same row.\n        if(!A.getcommgrid()->OnSameProcRow(target_proc))\n            target_proc = static_cast<int>(rank / n_proc_side) *\n                            n_proc_side + target_proc % n_proc_side;\n\n        size_t target_row_rank = A.getcommgrid()->GetRankInProcRow(target_proc);\n\n        // reduce partial row (FIXME: if the resulting matrix is still\n        // expected to be sparse, change this to communicate only nnz).\n        // Working on local_width columns concurrently per column processing\n        // group.\n        size_t local_width = S.Width();\n        const value_type* buffer = &local_matrix[local_row * local_width];\n        std::vector<value_type> new_values(local_width);\n        boost::mpi::reduce(my_row_comm, buffer, local_width,\n                &new_values[0], std::plus<value_type>(), target_row_rank);\n\n        // processor stores result directly if it is the owning rank of that\n        // row, save for subsequent communication along rows otherwise\n        if(rank == utility::owner(C, row, static_cast<size_t>(0))) {\n            int elem_lrow = C.LocalRow(row);\n            for(size_t idx = 0; idx < local_width; ++idx) {\n                int elem_lcol = C.LocalCol(idx);\n                C.SetLocal(elem_lrow, elem_lcol,\n                    new_values[idx] + beta * C.GetLocal(elem_lrow, elem_lcol));\n            }\n        } else if (rank == target_proc) {\n            // store for later comm across rows\n            for_rank[utility::owner(C, row, static_cast<size_t>(0)) / n_proc_side].push_back(\n                    std::make_pair(row, new_values));\n        }\n    }\n\n    // 3) gather remaining values along rows: we exchange all the values with\n    //    other processors in the same communicator row and then add them to\n    //    our local part.\n    boost::mpi::communicator my_col_comm(\n            A.getcommgrid()->GetColWorld(), boost::mpi::comm_duplicate);\n\n    std::vector<for_rank_t> new_values;\n    for(int i = 0; i < n_proc_side; ++i)\n        boost::mpi::gather(my_col_comm, for_rank[i], new_values, i);\n\n    // insert new values\n    for(size_t proc = 0; proc < new_values.size(); ++proc) {\n        const for_rank_t &cur  = new_values[proc];\n\n        for(size_t i = 0; i < cur.size(); ++i) {\n            int elem_lrow = C.LocalRow(cur[i].first);\n            for(size_t j = 0; j < cur[i].second.size(); ++j) {\n                size_t elem_lcol = C.LocalCol(j);\n                C.SetLocal(elem_lrow, elem_lcol,\n                        cur[i].second[j] + beta *\n                        C.GetLocal(elem_lrow, elem_lcol));\n            }\n        }\n    }\n}\n\n\n//FIXME: benchmark against one-sided\ntemplate<typename index_type, typename value_type, El::Distribution col_d>\ninline void outer_panel_mixed_gemm_impl_nn(\n        const double alpha,\n        const SpParMat<index_type, value_type, SpDCCols<index_type, value_type> > &A,\n        const El::DistMatrix<value_type, El::STAR, El::STAR> &S,\n        const double beta,\n        El::DistMatrix<value_type, col_d, El::STAR> &C) {\n\n    utility::combblas_slab_view_t<index_type, value_type> cbview(A, false);\n\n    //FIXME: factor\n    size_t slab_size = 2 * C.Grid().Height();\n    for(size_t cur_row_idx = 0; cur_row_idx < cbview.nrows();\n        cur_row_idx += slab_size) {\n\n        size_t cur_slab_size =\n            std::min(slab_size, cbview.nrows() - cur_row_idx);\n\n        // get the next slab_size columns of B\n        El::DistMatrix<value_type, col_d, El::STAR>\n            A_row(cur_slab_size, S.Height());\n\n        cbview.extract_elemental_row_slab_view(A_row, cur_slab_size);\n\n        // assemble the distributed column vector\n        for(size_t l_col_idx = 0; l_col_idx < A_row.LocalWidth();\n            l_col_idx++) {\n\n            size_t g_col_idx = l_col_idx * A_row.RowStride()\n                               + A_row.RowShift();\n\n            for(size_t l_row_idx = 0; l_row_idx < A_row.LocalHeight();\n                ++l_row_idx) {\n\n                size_t g_row_idx = l_row_idx * A_row.ColStride()\n                                   + A_row.ColShift() + cur_row_idx;\n\n                A_row.SetLocal(l_row_idx, l_col_idx,\n                               cbview(g_row_idx, g_col_idx));\n            }\n        }\n\n        El::DistMatrix<value_type, col_d, El::STAR>\n            C_slice(cur_slab_size, C.Width());\n        El::View(C_slice, C, cur_row_idx, 0, cur_slab_size, C.Width());\n        El::LocalGemm(El::NORMAL, El::NORMAL, alpha, A_row, S,\n                        beta, C_slice);\n    }\n}\n\n\n//FIXME: benchmark against one-sided\ntemplate<typename index_type, typename value_type, El::Distribution col_d>\ninline void outer_panel_mixed_gemm_impl_tn(\n        const double alpha,\n        const SpParMat<index_type, value_type, SpDCCols<index_type, value_type> > &A,\n        const El::DistMatrix<value_type, col_d, El::STAR> &S,\n        const double beta,\n        El::DistMatrix<value_type, El::STAR, El::STAR> &C) {\n\n    El::DistMatrix<value_type, El::STAR, El::STAR>\n        tmp_C(C.Height(), C.Width());\n    El::Zero(tmp_C);\n\n    utility::combblas_slab_view_t<index_type, value_type> cbview(A, false);\n\n    //FIXME: factor\n    size_t slab_size = 2 * S.Grid().Height();\n    for(size_t cur_row_idx = 0; cur_row_idx < cbview.ncols();\n        cur_row_idx += slab_size) {\n\n        size_t cur_slab_size =\n            std::min(slab_size, cbview.ncols() - cur_row_idx);\n\n        // get the next slab_size columns of B\n        El::DistMatrix<value_type, El::STAR, El::STAR>\n            A_row(cur_slab_size, S.Height());\n\n        // transpose is column\n        //cbview.extract_elemental_column_slab_view(A_row, cur_slab_size);\n        cbview.extract_full_slab_view(cur_slab_size);\n\n        // matrix mult (FIXME only iter nz)\n        for(size_t l_row_idx = 0; l_row_idx < A_row.LocalHeight();\n            ++l_row_idx) {\n\n            size_t g_row_idx = l_row_idx * A_row.ColStride()\n                               + A_row.ColShift() + cur_row_idx;\n\n            for(size_t l_col_idx = 0; l_col_idx < A_row.LocalWidth();\n                l_col_idx++) {\n\n                //XXX: should be the same as l_col_idx\n                size_t g_col_idx = l_col_idx * A_row.RowStride()\n                                   + A_row.RowShift();\n\n                // continue if we don't own values in S in this row\n                if(!S.IsLocalRow(g_col_idx))\n                    continue;\n\n                //get transposed value\n                value_type val = alpha * cbview(g_col_idx, g_row_idx);\n\n                for(size_t s_col_idx = 0; s_col_idx < S.LocalWidth();\n                    s_col_idx++) {\n\n                    tmp_C.UpdateLocal(g_row_idx, s_col_idx,\n                                val * S.GetLocal(S.LocalRow(g_col_idx), s_col_idx));\n                }\n            }\n        }\n    }\n\n    //FIXME: scaling\n    if(A.getcommgrid()->GetRank() == 0) {\n        for(size_t col_idx = 0; col_idx < C.Width(); col_idx++)\n            for(size_t row_idx = 0; row_idx < C.Height(); row_idx++)\n                tmp_C.UpdateLocal(row_idx, col_idx,\n                        beta * C.GetLocal(row_idx, col_idx));\n    }\n\n    //FIXME: Use utility getter\n    boost::mpi::communicator world(\n            A.getcommgrid()->GetWorld(), boost::mpi::comm_duplicate);\n    boost::mpi::all_reduce (world,\n                        tmp_C.LockedBuffer(),\n                        C.Height() * C.Width(),\n                        C.Buffer(),\n                        std::plus<value_type>());\n}\n\n} // namespace detail\n\n/**\n * Mixed GEMM for Elental and CombBLAS matrices. For a distributed Elemental\n * input matrix, the output has the same distribution.\n */\n\n/// Gemm for distCombBLAS x distElental(* / *) -> distElental (SOMETHING / *)\ntemplate<typename index_type, typename value_type, El::Distribution col_d>\nvoid Gemm(El::Orientation oA, El::Orientation oB, double alpha,\n          const SpParMat<index_type, value_type, SpDCCols<index_type, value_type> > &A,\n          const El::DistMatrix<value_type, El::STAR, El::STAR> &B,\n          double beta,\n          El::DistMatrix<value_type, col_d, El::STAR> &C) {\n\n    if(oA == El::NORMAL && oB == El::NORMAL) {\n\n        if(A.getnol() != B.Height())\n            SKYLARK_THROW_EXCEPTION (\n                base::combblas_exception()\n                    << base::error_msg(\"Gemm: Dimensions do not agree\"));\n\n        if(A.getnrow() != C.Height())\n            SKYLARK_THROW_EXCEPTION (\n                base::combblas_exception()\n                    << base::error_msg(\"Gemm: Dimensions do not agree\"));\n\n        if(B.Width() != C.Width())\n            SKYLARK_THROW_EXCEPTION (\n                base::combblas_exception()\n                    << base::error_msg(\"Gemm: Dimensions do not agree\"));\n\n        //XXX: simple heuristic to decide what to communicate (improve!)\n        //     or just if A.getncol() < B.Width..\n        if(A.getnnz() < B.Height() * B.Width())\n            detail::outer_panel_mixed_gemm_impl_nn(alpha, A, B, beta, C);\n        else\n            detail::inner_panel_mixed_gemm_impl_nn(alpha, A, B, beta, C);\n    }\n}\n\n/// Gemm for distCombBLAS x distElental(SOMETHING / *) -> distElental (* / *)\ntemplate<typename index_type, typename value_type, El::Distribution col_d>\nvoid Gemm(El::Orientation oA, El::Orientation oB, double alpha,\n          const SpParMat<index_type, value_type, SpDCCols<index_type, value_type> > &A,\n          const El::DistMatrix<value_type, col_d, El::STAR> &B,\n          double beta,\n          El::DistMatrix<value_type, El::STAR, El::STAR> &C) {\n\n    if(oA == El::TRANSPOSE && oB == El::NORMAL) {\n\n        if(A.getrow() != B.Height())\n            SKYLARK_THROW_EXCEPTION (\n                base::combblas_exception()\n                    << base::error_msg(\"Gemm: Dimensions do not agree\"));\n\n        if(A.getncol() != C.Height())\n            SKYLARK_THROW_EXCEPTION (\n                    base::combblas_exception()\n                    << base::error_msg(\"Gemm: Dimensions do not agree\"));\n\n        if(B.Width() != C.Width())\n            SKYLARK_THROW_EXCEPTION (\n                base::combblas_exception()\n                    << base::error_msg(\"Gemm: Dimensions do not agree\"));\n\n        detail::outer_panel_mixed_gemm_impl_tn(alpha, A, B, beta, C);\n    }\n\n}\n\n\n} // namespace base\n} // namespace skylark\n\n#endif // SKYLARK_HAVE_COMBBLAS\n\n#endif // SKYLARK_COMBBLAS_MIXED_GEMM_HPP_\n", "meta": {"hexsha": "5e57a8f49fd68f9b15a793a32c8c771a5e442018", "size": 14321, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "base/detail/combblas_mixed_gemm.hpp", "max_stars_repo_name": "xdata-skylark/libskylark", "max_stars_repo_head_hexsha": "89c3736136a24d519c14fc0738c21f37f1e10360", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 86.0, "max_stars_repo_stars_event_min_datetime": "2015-01-20T03:12:46.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-10T04:05:21.000Z", "max_issues_repo_path": "base/detail/combblas_mixed_gemm.hpp", "max_issues_repo_name": "xdata-skylark/libskylark", "max_issues_repo_head_hexsha": "89c3736136a24d519c14fc0738c21f37f1e10360", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 48.0, "max_issues_repo_issues_event_min_datetime": "2015-05-12T09:31:23.000Z", "max_issues_repo_issues_event_max_datetime": "2018-12-05T14:45:46.000Z", "max_forks_repo_path": "base/detail/combblas_mixed_gemm.hpp", "max_forks_repo_name": "xdata-skylark/libskylark", "max_forks_repo_head_hexsha": "89c3736136a24d519c14fc0738c21f37f1e10360", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 25.0, "max_forks_repo_forks_event_min_datetime": "2015-01-18T23:02:11.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-12T07:30:35.000Z", "avg_line_length": 37.9867374005, "max_line_length": 93, "alphanum_fraction": 0.6021227568, "num_tokens": 3605, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6688802603710085, "lm_q2_score": 0.5078118642792044, "lm_q1q2_score": 0.33966533199856147}}
{"text": "/* Copyright (c) 2018-2019 the `graphkernels` developers\n * All rights reserved.\n */\n\n#include \"connected_graphlet.h\"\n\n#include <Eigen/Sparse>\n\n#include <algorithm>\n\nusing std::sort;\nusing std::vector;\n\nusing Eigen::MatrixXd;\nusing Eigen::MatrixXi;\nusing Eigen::SparseMatrix;\nusing Eigen::VectorXd;\n\nconstexpr auto FREQ_SIZE_3 = 2;\nconstexpr auto FREQ_SIZE_4 = 6;\nconstexpr auto FREQ_SIZE_5 = 21;\n\nvoid getMinValue(const MatrixXi& iam, const vector<int>& idx, vector<int>& sums) {\n    SparseMatrix<int> am = iam.sparseView();\n\n    sums.clear();\n    sums.resize(idx.size());\n    fill(sums.begin(), sums.end(), 0);\n    for (auto i = 0; i < idx.size(); ++i) {\n        for (SparseMatrix<int>::InnerIterator it(am, idx[i]); it; ++it) {\n            if (find(idx.cbegin(), idx.cend(), it.row()) != idx.cend()) {\n                sums[i] += it.value();\n            }\n        }\n    }\n    sums.push_back(1);\n}\n\nVectorXd countConnectedGraphletsFive(\n        const MatrixXi& am,\n        const vector<vector<int>>& al) {\n    vector<double> w = {\n        1.0 / 120.0, 1.0 / 72.0, 1.0 / 48.0, 1.0 / 36.0, 1.0 / 28.0, 1.0 / 20.0,\n        1.0 / 14.0,  1.0 / 10.0, 1.0 / 12.0, 1.0 / 8.0,  1.0 / 8.0,  1.0 / 4.0,\n        1.0 / 2.0,   1.0 / 12.0, 1.0 / 12.0, 1.0 / 4.0,  1.0 / 4.0,  1.0 / 2.0,\n        0.0,         0.0,        0.0};\n\n    const auto n = al.size();\n    VectorXd count_gr = VectorXd::Zero(FREQ_SIZE_5);\n\n    vector<int> idx(5);\n    vector<int> sums;\n\n    for (auto i = 0; i < n; ++i) {\n        for (auto&& j : al[i]) {\n            for (auto&& k : al[j]) {\n                if (k != i) {\n                    for (auto&& l : al[k]) {\n                        if (l != i && l != j) {\n                            for (auto&& m : al[l]) {\n                                if (m != i && m != j && m != k) {\n                                    const auto aux =\n                                        am.coeff(i, k) + am.coeff(i, l) +\n                                        am.coeff(i, m) + am.coeff(j, l) +\n                                        am.coeff(j, m) + am.coeff(k, m);\n                                    if (aux == 6) {\n                                        count_gr[0] += w[0];\n                                    } else if (aux == 5) {\n                                        count_gr[1] += w[1];\n                                    } else if (aux == 4) {\n                                        idx[0] = i;\n                                        idx[1] = j;\n                                        idx[2] = k;\n                                        idx[3] = l;\n                                        idx[4] = m;\n                                        getMinValue(am, idx, sums);\n                                        const auto aux1 = *min_element(\n                                                sums.cbegin(), sums.cend());\n                                        if (aux1 == 2) {\n                                            count_gr[3] += w[3];\n                                        } else {\n                                            count_gr[2] += w[2];\n                                        }\n                                    } else if (aux == 3) {\n                                        idx[0] = i;\n                                        idx[1] = j;\n                                        idx[2] = k;\n                                        idx[3] = l;\n                                        idx[4] = m;\n                                        getMinValue(am, idx, sums);\n                                        sort(sums.begin(), sums.end());\n                                        if (sums[0] == 1) {\n                                            count_gr[8] += w[8];\n                                        } else if (sums[1] == 3) {\n                                            count_gr[4] += w[4];\n                                        } else if (sums[2] == 2) {\n                                            count_gr[13] += w[13];\n                                        } else {\n                                            count_gr[5] += w[5];\n                                        }\n                                    } else if (aux == 2) {\n                                        idx[0] = i;\n                                        idx[1] = j;\n                                        idx[2] = k;\n                                        idx[3] = l;\n                                        idx[4] = m;\n                                        getMinValue(am, idx, sums);\n                                        vector<int> aux1;\n                                        copy(sums.cbegin(), sums.cend(),\n                                                back_inserter(aux1));\n                                        sort(aux1.begin(), aux1.end());\n                                        if (aux1[0] == 1) {\n                                            if (aux1[2] == 2) {\n                                                count_gr[15] += w[15];\n                                            } else {\n                                                count_gr[9] += w[9];\n                                            }\n                                        } else {\n                                            if (aux1[3] == 2) {\n                                                count_gr[10] += w[10];\n                                            } else {\n                                                vector<int> ind;\n                                                for (auto ii = 0; ii < sums.size(); ++ii) {\n                                                    if (sums[ii] == 3) {\n                                                        ind.push_back(ii);\n                                                    }\n                                                }\n                                                if (am.coeff(idx[ind[0]], idx[ind[1]]) == 1) {\n                                                    count_gr[6] += w[6];\n                                                } else {\n                                                    count_gr[14] += w[14];\n                                                }\n                                            }\n                                        }\n                                    } else if (aux == 1) {\n                                        idx[0] = i;\n                                        idx[1] = j;\n                                        idx[2] = k;\n                                        idx[3] = l;\n                                        idx[4] = m;\n                                        getMinValue(am, idx, sums);\n                                        vector<int> aux1;\n                                        copy(sums.cbegin(), sums.cend(),\n                                                back_inserter(aux1));\n                                        sort(aux1.begin(), aux1.end());\n                                        if (aux1[0] == 2) {\n                                            count_gr[7] += w[7];\n                                        } else if (aux1[1] == 1) {\n                                            count_gr[17] += w[17];\n                                        } else {\n                                            vector<int> ind;\n                                            for (auto ii = 0; ii < sums.size(); ++ii) {\n                                                if (sums[ii] == 3) {\n                                                    ind.push_back(ii);\n                                                }\n                                            }\n                                            for (auto ii = 0; ii < sums.size(); ++ii) {\n                                                if (sums[ii] == 1) {\n                                                    ind.push_back(ii);\n                                                }\n                                            }\n                                            if (am.coeff(idx[ind[0]], idx[ind[1]]) == 1) {\n                                                count_gr[16] += w[16];\n                                            } else {\n                                                count_gr[11] += w[11];\n                                            }\n                                        }\n                                    } else {\n                                        count_gr[12] += w[12];\n                                    }\n                                }\n                            }\n                        }\n                    }\n                }\n            }\n        }\n        // count graphlets of type 20\n        for (auto&& j : al[i]) {\n            for (auto&& k : al[j]) {\n                if (k != i && am.coeff(i, k) == 0) {\n                    for (auto&& l : al[k]) {\n                        if (l != i && l != j && am.coeff(i, l) == 0 &&\n                                am.coeff(j, l) == 0) {\n                            for (auto&& m : al[k]) {\n                                if (m != i && m != j && m != l\n                                        && am.coeff(i, m) == 0\n                                        && am.coeff(j, m) == 0\n                                        && am.coeff(l, m) == 0) {\n                                    count_gr[19] += w[19];\n                                }\n                            }\n                        }\n                    }\n                }\n            }\n        }\n        // count graphlets of type 19 and 21\n        for (auto m = al[i].size(); m-- > 3;) {\n            for (auto l = m; l-- > 2;) {\n                for (auto k = l; k-- > 1;) {\n                    for (auto j = k; j-- > 0;) {\n                        auto aux =\n                            am.coeff(al[i][j], al[i][k]) +\n                            am.coeff(al[i][j], al[i][l]) +\n                            am.coeff(al[i][j], al[i][m]) +\n                            am.coeff(al[i][k], al[i][l]) +\n                            am.coeff(al[i][k], al[i][m]) +\n                            am.coeff(al[i][l], al[i][m]);\n                        if (aux == 1) {\n                            count_gr[18]++;\n                        } else if (aux == 0) {\n                            count_gr[20]++;\n                        }\n                    }\n                }\n            }\n        }\n    }\n    const auto csum = count_gr.sum();\n    return (csum == 0.0) ? count_gr : count_gr / csum;\n}\n\nVectorXd countConnectedGraphletsFour(\n        const MatrixXi& am,\n        const vector<vector<int>>& al) {\n    vector<double> w = {1.0 / 24.0, 1.0 / 12.0, 1.0 / 4.0,\n                        0.0,        1.0 / 8.0,  1.0 / 2.0};\n\n    VectorXd count_gr = VectorXd::Zero(FREQ_SIZE_4);\n    const auto n = am.rows();\n    for (auto i = 0; i < n; ++i) {\n        for (auto&& j : al[i]) {\n            for (auto&& k : al[j]) {\n                if (k != i) {\n                    for (auto&& l : al[k]) {\n                        if (l != i && l != j) {\n                            const auto aux =\n                                am.coeff(i, k) +\n                                am.coeff(i, l) +\n                                am.coeff(j, l);\n                            if (aux == 3) {\n                                count_gr[0] += w[0];\n                            } else if (aux == 2) {\n                                count_gr[1] += w[1];\n                            } else if (aux == 1) {\n                                if (am.coeff(i, l) == 1) {\n                                    count_gr[4] += w[4];\n                                } else {\n                                    count_gr[2] += w[2];\n                                }\n                            } else {\n                                count_gr[5] += w[5];\n                            }\n                        }\n                    }\n                }\n            }\n        }\n\n        // count \"stars\"\n        for (auto l = al[i].size(); l-- > 2;) {\n            for (auto k = l; k-- > 1;) {\n                for (auto j = k; j-- > 0;) {\n                    if (am.coeff(al[i][j], al[i][k]) == 0 &&\n                            am.coeff(al[i][j], al[i][l]) == 0 &&\n                            am.coeff(al[i][k], al[i][l]) == 0) {\n                        count_gr[3]++;\n                    }\n                }\n            }\n        }\n    }\n    const auto csum = count_gr.sum();\n    return (csum == 0.0) ? count_gr : count_gr / csum;\n}\n\nVectorXd countConnectedGraphletsThree(\n        const MatrixXi& am,\n        const vector<vector<int>>& al) {\n    vector<double> w = {1.0 / 2.0, 1.0 / 6.0};\n\n    VectorXd count_gr = VectorXd::Zero(FREQ_SIZE_3);\n    const auto n = am.rows();\n    for (auto i = 0; i < n; ++i) {\n        for (auto&& j : al[i]) {\n            for (auto&& k : al[j]) {\n                if (k != i) {\n                    if (am.coeff(i, k) == 1) {\n                        count_gr[1] += w[1];\n                    } else {\n                        count_gr[0] += w[0];\n                    }\n                }\n            }\n        }\n    }\n    const auto csum = count_gr.sum();\n    return (csum == 0.0) ? count_gr : count_gr / csum;\n}\n\nMatrixXd CalculateConnectedGraphletKernelThreePy(\n        const vector<MatrixXi>& graph_adj_all,\n        const vector<vector<vector<int>>>& graph_adjlist_all) {\n    MatrixXd freq(FREQ_SIZE_3, graph_adjlist_all.size());\n\n    for (auto i = 0; i < graph_adjlist_all.size(); ++i) {\n        freq.col(i) = countConnectedGraphletsThree(\n                graph_adj_all[i], graph_adjlist_all[i]);\n    }\n\n    return freq.transpose() * freq;\n}\n\nMatrixXd CalculateConnectedGraphletKernelFourPy(\n        const vector<MatrixXi>& graph_adj_all,\n        const vector<vector<vector<int>>>& graph_adjlist_all) {\n    MatrixXd freq(FREQ_SIZE_4, graph_adjlist_all.size());\n\n    for (auto i = 0; i < graph_adjlist_all.size(); ++i) {\n        freq.col(i) = countConnectedGraphletsFour(\n                graph_adj_all[i], graph_adjlist_all[i]);\n    }\n\n    return freq.transpose() * freq;\n}\n\nMatrixXd CalculateConnectedGraphletKernelFivePy(\n        const vector<MatrixXi>& graph_adj_all,\n        const vector<vector<vector<int>>>& graph_adjlist_all) {\n    MatrixXd freq(FREQ_SIZE_5, graph_adjlist_all.size());\n\n    for (auto i = 0; i < graph_adjlist_all.size(); ++i) {\n        freq.col(i) = countConnectedGraphletsFive(\n                graph_adj_all[i], graph_adjlist_all[i]);\n    }\n\n    return freq.transpose() * freq;\n}\n", "meta": {"hexsha": "268dd05f134a86b0785e568005c99a2e2d04ccb9", "size": 14407, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "graphkernels/cppkernels/connected_graphlet.cpp", "max_stars_repo_name": "Renelvon/GraphKernels", "max_stars_repo_head_hexsha": "68d2006ff29363ee1f5435e7b2bb158f6770433a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "graphkernels/cppkernels/connected_graphlet.cpp", "max_issues_repo_name": "Renelvon/GraphKernels", "max_issues_repo_head_hexsha": "68d2006ff29363ee1f5435e7b2bb158f6770433a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "graphkernels/cppkernels/connected_graphlet.cpp", "max_forks_repo_name": "Renelvon/GraphKernels", "max_forks_repo_head_hexsha": "68d2006ff29363ee1f5435e7b2bb158f6770433a", "max_forks_repo_licenses": ["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.3735294118, "max_line_length": 94, "alphanum_fraction": 0.2793780801, "num_tokens": 3013, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.679178699175393, "lm_q2_score": 0.5, "lm_q1q2_score": 0.3395893495876965}}
{"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, 2009 StatPro Italia srl\n Copyright (C) 2004 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 array.hpp\n    \\brief 1-D array used in linear algebra.\n*/\n\n#ifndef quantlib_array_hpp\n#define quantlib_array_hpp\n\n#include <ql/types.hpp>\n#include <ql/errors.hpp>\n#include <ql/utilities/disposable.hpp>\n#include <ql/utilities/null.hpp>\n#include <boost/iterator/reverse_iterator.hpp>\n#include <boost/scoped_array.hpp>\n#include <boost/type_traits.hpp>\n#include <functional>\n#include <numeric>\n#include <vector>\n#include <iomanip>\n\nnamespace QuantLib {\n\n    //! 1-D array used in linear algebra.\n    /*! This class implements the concept of vector as used in linear\n        algebra.\n        As such, it is <b>not</b> meant to be used as a container -\n        <tt>std::vector</tt> should be used instead.\n\n        \\test construction of arrays is checked in a number of cases\n    */\n    class Array {\n      public:\n        //! \\name Constructors, destructor, and assignment\n        //@{\n        //! creates the array with the given dimension\n        explicit Array(Size size = 0);\n        //! creates the array and fills it with <tt>value</tt>\n        Array(Size size, Real value);\n        /*! \\brief creates the array and fills it according to\n            \\f$ a_{0} = value, a_{i}=a_{i-1}+increment \\f$\n        */\n        Array(Size size, Real value, Real increment);\n        Array(const Array&);\n        Array(const Disposable<Array>&);\n        //! creates the array from an iterable sequence\n        template <class ForwardIterator>\n        Array(ForwardIterator begin, ForwardIterator end);\n\n        Array& operator=(const Array&);\n        Array& operator=(const Disposable<Array>&);\n        bool operator==(const Array&) const;\n        bool operator!=(const Array&) const;\n        //@}\n        /*! \\name Vector algebra\n\n            <tt>v += x</tt> and similar operation involving a scalar value\n            are shortcuts for \\f$ \\forall i : v_i = v_i + x \\f$\n\n            <tt>v *= w</tt> and similar operation involving two vectors are\n            shortcuts for \\f$ \\forall i : v_i = v_i \\times w_i \\f$\n\n            \\pre all arrays involved in an algebraic expression must have\n            the same size.\n        */\n        //@{\n        const Array& operator+=(const Array&);\n        const Array& operator+=(Real);\n        const Array& operator-=(const Array&);\n        const Array& operator-=(Real);\n        const Array& operator*=(const Array&);\n        const Array& operator*=(Real);\n        const Array& operator/=(const Array&);\n        const Array& operator/=(Real);\n        //@}\n        //! \\name Element access\n        //@{\n        //! read-only\n        Real operator[](Size) const;\n        Real at(Size) const;\n        Real front() const;\n        Real back() const;\n        //! read-write\n        Real& operator[](Size);\n        Real& at(Size);\n        Real& front();\n        Real& back();\n        //@}\n        //! \\name Inspectors\n        //@{\n        //! dimension of the array\n        Size size() const;\n        //! whether the array is empty\n        bool empty() const;\n        //@}\n        typedef Size size_type;\n        typedef Real value_type;\n        typedef Real* iterator;\n        typedef const Real* const_iterator;\n        typedef boost::reverse_iterator<iterator> reverse_iterator;\n        typedef boost::reverse_iterator<const_iterator> const_reverse_iterator;\n        //! \\name Iterator access\n        //@{\n        const_iterator begin() const;\n        iterator begin();\n        const_iterator end() const;\n        iterator end();\n        const_reverse_iterator rbegin() const;\n        reverse_iterator rbegin();\n        const_reverse_iterator rend() const;\n        reverse_iterator rend();\n        //@}\n        //! \\name Utilities\n        //@{\n        void swap(Array&);  // never throws\n        //@}\n\n      private:\n        boost::scoped_array<Real> data_;\n        Size n_;\n    };\n\n    //! specialization of null template for this class\n    template <>\n    class Null<Array> {\n      public:\n        Null() {}\n        operator Array() const { return Array(); }\n    };\n\n\n\n    /*! \\relates Array */\n    Real DotProduct(const Array&, const Array&);\n\n    /*! \\relates Array */\n    Real Norm2(const Array&);\n\n    // unary operators\n    /*! \\relates Array */\n    const Disposable<Array> operator+(const Array& v);\n    /*! \\relates Array */\n    const Disposable<Array> operator-(const Array& v);\n\n    // binary operators\n    /*! \\relates Array */\n    const Disposable<Array> operator+(const Array&, const Array&);\n    /*! \\relates Array */\n    const Disposable<Array> operator+(const Array&, Real);\n    /*! \\relates Array */\n    const Disposable<Array> operator+(Real, const Array&);\n    /*! \\relates Array */\n    const Disposable<Array> operator-(const Array&, const Array&);\n    /*! \\relates Array */\n    const Disposable<Array> operator-(const Array&, Real);\n    /*! \\relates Array */\n    const Disposable<Array> operator-(Real, const Array&);\n    /*! \\relates Array */\n    const Disposable<Array> operator*(const Array&, const Array&);\n    /*! \\relates Array */\n    const Disposable<Array> operator*(const Array&, Real);\n    /*! \\relates Array */\n    const Disposable<Array> operator*(Real, const Array&);\n    /*! \\relates Array */\n    const Disposable<Array> operator/(const Array&, const Array&);\n    /*! \\relates Array */\n    const Disposable<Array> operator/(const Array&, Real);\n    /*! \\relates Array */\n    const Disposable<Array> operator/(Real, const Array&);\n\n    // math functions\n    /*! \\relates Array */\n    const Disposable<Array> Abs(const Array&);\n    /*! \\relates Array */\n    const Disposable<Array> Sqrt(const Array&);\n    /*! \\relates Array */\n    const Disposable<Array> Log(const Array&);\n    /*! \\relates Array */\n    const Disposable<Array> Exp(const Array&);\n    /*! \\relates Array */\n    const Disposable<Array> Pow(const Array&, Real);\n\n    // utilities\n    /*! \\relates Array */\n    void swap(Array&, Array&);\n\n    // format\n    /*! \\relates Array */\n    std::ostream& operator<<(std::ostream&, const Array&);\n\n\n    // inline definitions\n\n    inline Array::Array(Size size)\n    : data_(size ? new Real[size] : (Real*)(0)), n_(size) {}\n\n    inline Array::Array(Size size, Real value)\n    : data_(size ? new Real[size] : (Real*)(0)), n_(size) {\n        std::fill(begin(),end(),value);\n    }\n\n    inline Array::Array(Size size, Real value, Real increment)\n    : data_(size ? new Real[size] : (Real*)(0)), n_(size) {\n        for (iterator i=begin(); i!=end(); ++i, value+=increment)\n            *i = value;\n    }\n\n    inline Array::Array(const Array& from)\n    : data_(from.n_ ? new Real[from.n_] : (Real*)(0)), n_(from.n_) {\n        #if defined(QL_PATCH_MSVC) && defined(QL_DEBUG)\n        if (n_)\n        #endif\n        std::copy(from.begin(),from.end(),begin());\n    }\n\n    inline Array::Array(const Disposable<Array>& from)\n    : data_((Real*)(0)), n_(0) {\n        swap(const_cast<Disposable<Array>&>(from));\n    }\n\n    namespace detail {\n\n        template <class I>\n        inline void _fill_array_(Array& a,\n                                 boost::scoped_array<Real>& data_,\n                                 Size& n_,\n                                 I begin, I end,\n                                 const boost::true_type&) {\n            // we got redirected here from a call like Array(3, 4)\n            // because it matched the constructor below exactly with\n            // ForwardIterator = int.  What we wanted was fill an\n            // Array with a given value, which we do here.\n            Size n = begin;\n            Real value = end;\n            data_.reset(n ? new Real[n] : (Real*)(0));\n            n_ = n;\n            std::fill(a.begin(),a.end(),value);\n        }\n\n        template <class I>\n        inline void _fill_array_(Array& a,\n                                 boost::scoped_array<Real>& data_,\n                                 Size& n_,\n                                 I begin, I end,\n                                 const boost::false_type&) {\n            // true iterators\n            Size n = std::distance(begin, end);\n            data_.reset(n ? new Real[n] : (Real*)(0));\n            n_ = n;\n            #if defined(QL_PATCH_MSVC) && defined(QL_DEBUG)\n            if (n_)\n            #endif\n            std::copy(begin, end, a.begin());\n        }\n\n    }\n\n    template <class ForwardIterator>\n    inline Array::Array(ForwardIterator begin, ForwardIterator end) {\n        // Unfortunately, calls such as Array(3, 4) match this constructor.\n        // We have to detect integral types and dispatch.\n        detail::_fill_array_(*this, data_, n_, begin, end,\n                             boost::is_integral<ForwardIterator>());\n    }\n\n    inline Array& Array::operator=(const Array& from) {\n        // strong guarantee\n        Array temp(from);\n        swap(temp);\n        return *this;\n    }\n\n    inline bool Array::operator==(const Array& to) const {\n        return (n_ == to.n_) && std::equal(begin(), end(), to.begin());\n    }\n\n    inline bool Array::operator!=(const Array& to) const {\n        return !(this->operator==(to));\n    }\n\n    inline Array& Array::operator=(const Disposable<Array>& from) {\n        swap(const_cast<Disposable<Array>&>(from));\n        return *this;\n    }\n\n    inline const Array& Array::operator+=(const Array& v) {\n        QL_REQUIRE(n_ == v.n_,\n                   \"arrays with different sizes (\" << n_ << \", \"\n                   << v.n_ << \") cannot be added\");\n        std::transform(begin(),end(),v.begin(),begin(),\n                       std::plus<Real>());\n        return *this;\n    }\n\n\n    inline const Array& Array::operator+=(Real x) {\n        std::transform(begin(),end(),begin(),\n                       std::bind2nd(std::plus<Real>(),x));\n        return *this;\n    }\n\n    inline const Array& Array::operator-=(const Array& v) {\n        QL_REQUIRE(n_ == v.n_,\n                   \"arrays with different sizes (\" << n_ << \", \"\n                   << v.n_ << \") cannot be subtracted\");\n        std::transform(begin(),end(),v.begin(),begin(),\n                       std::minus<Real>());\n        return *this;\n    }\n\n    inline const Array& Array::operator-=(Real x) {\n        std::transform(begin(),end(),begin(),\n                       std::bind2nd(std::minus<Real>(),x));\n        return *this;\n    }\n\n    inline const Array& Array::operator*=(const Array& v) {\n        QL_REQUIRE(n_ == v.n_,\n                   \"arrays with different sizes (\" << n_ << \", \"\n                   << v.n_ << \") cannot be multiplied\");\n        std::transform(begin(),end(),v.begin(),begin(),\n                       std::multiplies<Real>());\n        return *this;\n    }\n\n    inline const Array& Array::operator*=(Real x) {\n        std::transform(begin(),end(),begin(),\n                       std::bind2nd(std::multiplies<Real>(),x));\n        return *this;\n    }\n\n    inline const Array& Array::operator/=(const Array& v) {\n        QL_REQUIRE(n_ == v.n_,\n                   \"arrays with different sizes (\" << n_ << \", \"\n                   << v.n_ << \") cannot be divided\");\n        std::transform(begin(),end(),v.begin(),begin(),\n                       std::divides<Real>());\n        return *this;\n    }\n\n    inline const Array& Array::operator/=(Real x) {\n        std::transform(begin(),end(),begin(),\n                       std::bind2nd(std::divides<Real>(),x));\n        return *this;\n    }\n\n    inline Real Array::operator[](Size i) const {\n        #if defined(QL_EXTRA_SAFETY_CHECKS)\n        QL_REQUIRE(i<n_,\n                   \"index (\" << i << \") must be less than \" << n_ <<\n                   \": array access out of range\");\n        #endif\n        return data_.get()[i];\n    }\n\n    inline Real Array::at(Size i) const {\n        QL_REQUIRE(i<n_,\n                   \"index (\" << i << \") must be less than \" << n_ <<\n                   \": array access out of range\");\n        return data_.get()[i];\n    }\n\n    inline Real Array::front() const {\n        #if defined(QL_EXTRA_SAFETY_CHECKS)\n        QL_REQUIRE(n_>0, \"null Array: array access out of range\");\n        #endif\n        return data_.get()[0];\n    }\n\n    inline Real Array::back() const {\n        #if defined(QL_EXTRA_SAFETY_CHECKS)\n        QL_REQUIRE(n_>0, \"null Array: array access out of range\");\n        #endif\n        return data_.get()[n_-1];\n    }\n\n    inline Real& Array::operator[](Size i) {\n        #if defined(QL_EXTRA_SAFETY_CHECKS)\n        QL_REQUIRE(i<n_,\n                   \"index (\" << i << \") must be less than \" << n_ <<\n                   \": array access out of range\");\n        #endif\n        return data_.get()[i];\n    }\n\n    inline Real& Array::at(Size i) {\n        QL_REQUIRE(i<n_,\n                   \"index (\" << i << \") must be less than \" << n_ <<\n                   \": array access out of range\");\n        return data_.get()[i];\n    }\n\n    inline Real& Array::front() {\n        #if defined(QL_EXTRA_SAFETY_CHECKS)\n        QL_REQUIRE(n_>0, \"null Array: array access out of range\");\n        #endif\n        return data_.get()[0];\n    }\n\n    inline Real& Array::back() {\n        #if defined(QL_EXTRA_SAFETY_CHECKS)\n        QL_REQUIRE(n_>0, \"null Array: array access out of range\");\n        #endif\n        return data_.get()[n_-1];\n    }\n\n    inline Size Array::size() const {\n        return n_;\n    }\n\n    inline bool Array::empty() const {\n        return n_ == 0;\n    }\n\n    inline Array::const_iterator Array::begin() const {\n        return data_.get();\n    }\n\n    inline Array::iterator Array::begin() {\n        return data_.get();\n    }\n\n    inline Array::const_iterator Array::end() const {\n        return data_.get()+n_;\n    }\n\n    inline Array::iterator Array::end() {\n        return data_.get()+n_;\n    }\n\n    inline Array::const_reverse_iterator Array::rbegin() const {\n        return const_reverse_iterator(end());\n    }\n\n    inline Array::reverse_iterator Array::rbegin() {\n        return reverse_iterator(end());\n    }\n\n    inline Array::const_reverse_iterator Array::rend() const {\n        return const_reverse_iterator(begin());\n    }\n\n    inline Array::reverse_iterator Array::rend() {\n        return reverse_iterator(begin());\n    }\n\n    inline void Array::swap(Array& from) {\n        using std::swap;\n        data_.swap(from.data_);\n        swap(n_,from.n_);\n    }\n\n    // dot product and norm\n\n    inline Real DotProduct(const Array& v1, const Array& v2) {\n        QL_REQUIRE(v1.size() == v2.size(),\n                   \"arrays with different sizes (\" << v1.size() << \", \"\n                   << v2.size() << \") cannot be multiplied\");\n        return std::inner_product(v1.begin(),v1.end(),v2.begin(),0.0);\n    }\n\n    inline Real Norm2(const Array& v) {\n        return std::sqrt(DotProduct(v, v));\n    }\n\n    // overloaded operators\n\n    // unary\n\n    inline const Disposable<Array> operator+(const Array& v) {\n        Array result = v;\n        return result;\n    }\n\n    inline const Disposable<Array> operator-(const Array& v) {\n        Array result(v.size());\n        std::transform(v.begin(),v.end(),result.begin(),\n                       std::negate<Real>());\n        return result;\n    }\n\n\n    // binary operators\n\n    inline const Disposable<Array> operator+(const Array& v1,\n                                             const Array& v2) {\n        QL_REQUIRE(v1.size() == v2.size(),\n                   \"arrays with different sizes (\" << v1.size() << \", \"\n                   << v2.size() << \") cannot be added\");\n        Array result(v1.size());\n        std::transform(v1.begin(),v1.end(),v2.begin(),result.begin(),\n                       std::plus<Real>());\n        return result;\n    }\n\n    inline const Disposable<Array> operator+(const Array& v1, Real a) {\n        Array result(v1.size());\n        std::transform(v1.begin(),v1.end(),result.begin(),\n                       std::bind2nd(std::plus<Real>(),a));\n        return result;\n    }\n\n    inline const Disposable<Array> operator+(Real a, const Array& v2) {\n        Array result(v2.size());\n        std::transform(v2.begin(),v2.end(),result.begin(),\n                       std::bind1st(std::plus<Real>(),a));\n        return result;\n    }\n\n    inline const Disposable<Array> operator-(const Array& v1,\n                                             const Array& v2) {\n        QL_REQUIRE(v1.size() == v2.size(),\n                   \"arrays with different sizes (\" << v1.size() << \", \"\n                   << v2.size() << \") cannot be subtracted\");\n        Array result(v1.size());\n        std::transform(v1.begin(),v1.end(),v2.begin(),result.begin(),\n                       std::minus<Real>());\n        return result;\n    }\n\n    inline const Disposable<Array> operator-(const Array& v1, Real a) {\n        Array result(v1.size());\n        std::transform(v1.begin(),v1.end(),result.begin(),\n                       std::bind2nd(std::minus<Real>(),a));\n        return result;\n    }\n\n    inline const Disposable<Array> operator-(Real a, const Array& v2) {\n        Array result(v2.size());\n        std::transform(v2.begin(),v2.end(),result.begin(),\n                       std::bind1st(std::minus<Real>(),a));\n        return result;\n    }\n\n    inline const Disposable<Array> operator*(const Array& v1,\n                                             const Array& v2) {\n        QL_REQUIRE(v1.size() == v2.size(),\n                   \"arrays with different sizes (\" << v1.size() << \", \"\n                   << v2.size() << \") cannot be multiplied\");\n        Array result(v1.size());\n        std::transform(v1.begin(),v1.end(),v2.begin(),result.begin(),\n                       std::multiplies<Real>());\n        return result;\n    }\n\n    inline const Disposable<Array> operator*(const Array& v1, Real a) {\n        Array result(v1.size());\n        std::transform(v1.begin(),v1.end(),result.begin(),\n                       std::bind2nd(std::multiplies<Real>(),a));\n        return result;\n    }\n\n    inline const Disposable<Array> operator*(Real a, const Array& v2) {\n        Array result(v2.size());\n        std::transform(v2.begin(),v2.end(),result.begin(),\n                       std::bind1st(std::multiplies<Real>(),a));\n        return result;\n    }\n\n    inline const Disposable<Array> operator/(const Array& v1,\n                                             const Array& v2) {\n        QL_REQUIRE(v1.size() == v2.size(),\n                   \"arrays with different sizes (\" << v1.size() << \", \"\n                   << v2.size() << \") cannot be divided\");\n        Array result(v1.size());\n        std::transform(v1.begin(),v1.end(),v2.begin(),result.begin(),\n                       std::divides<Real>());\n        return result;\n    }\n\n    inline const Disposable<Array> operator/(const Array& v1, Real a) {\n        Array result(v1.size());\n        std::transform(v1.begin(),v1.end(),result.begin(),\n                       std::bind2nd(std::divides<Real>(),a));\n        return result;\n    }\n\n    inline const Disposable<Array> operator/(Real a, const Array& v2) {\n        Array result(v2.size());\n        std::transform(v2.begin(),v2.end(),result.begin(),\n                       std::bind1st(std::divides<Real>(),a));\n        return result;\n    }\n\n    // functions\n\n    inline const Disposable<Array> Abs(const Array& v) {\n        Array result(v.size());\n        std::transform(v.begin(),v.end(),result.begin(),\n                       std::ptr_fun<Real,Real>(std::fabs));\n        return result;\n    }\n\n    inline const Disposable<Array> Sqrt(const Array& v) {\n        Array result(v.size());\n        std::transform(v.begin(),v.end(),result.begin(),\n                       std::ptr_fun<Real,Real>(std::sqrt));\n        return result;\n    }\n\n    inline const Disposable<Array> Log(const Array& v) {\n        Array result(v.size());\n        std::transform(v.begin(),v.end(),result.begin(),\n                       std::ptr_fun<Real,Real>(std::log));\n        return result;\n    }\n\n    inline const Disposable<Array> Exp(const Array& v) {\n        Array result(v.size());\n        std::transform(v.begin(),v.end(),result.begin(),\n                       std::ptr_fun<Real,Real>(std::exp));\n        return result;\n    }\n\n    inline const Disposable<Array> Pow(const Array& v, Real alpha) {\n        Array result(v.size());\n        std::transform(v.begin(), v.end(), result.begin(),\n            std::bind2nd(std::ptr_fun<Real, Real, Real>(std::pow), alpha));\n\n        return result;\n    }\n\n\n    inline void swap(Array& v, Array& w) {\n        v.swap(w);\n    }\n\n    inline std::ostream& operator<<(std::ostream& out, const Array& a) {\n        std::streamsize width = out.width();\n        out << \"[ \";\n        if (!a.empty()) {\n            for (Size n=0; n<a.size()-1; ++n)\n                out << std::setw(int(width)) << a[n] << \"; \";\n            out << std::setw(int(width)) << a.back();\n        }\n        out << \" ]\";\n        return out;\n    }\n\n}\n\n\n#endif", "meta": {"hexsha": "3376c5bd693d888a4c1f68e8f54070c32e16dd27", "size": 21599, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ql/math/array.hpp", "max_stars_repo_name": "markxio/Quantuccia", "max_stars_repo_head_hexsha": "ebe71a1b9c2a9ee7fc4ea918a9602f100316869d", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 29.0, "max_stars_repo_stars_event_min_datetime": "2017-03-20T14:17:39.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-22T08:00:52.000Z", "max_issues_repo_path": "ql/math/array.hpp", "max_issues_repo_name": "markxio/Quantuccia", "max_issues_repo_head_hexsha": "ebe71a1b9c2a9ee7fc4ea918a9602f100316869d", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 10.0, "max_issues_repo_issues_event_min_datetime": "2017-04-02T14:34:07.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-13T05:31:12.000Z", "max_forks_repo_path": "ql/math/array.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": 32.6268882175, "max_line_length": 79, "alphanum_fraction": 0.5419232372, "num_tokens": 4939, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5621765155565327, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.3395162939177265}}
{"text": "/*\n ISC License\n\n Copyright (c) 2016, Autonomous Vehicle Systems Lab, University of Colorado at Boulder\n\n Permission to use, copy, modify, and/or distribute this software for any\n purpose with or without fee is hereby granted, provided that the above\n copyright notice and this permission notice appear in all copies.\n\n THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES\n WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\n MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR\n ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\n WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\n ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF\n OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n\n */\n\n#include <iostream>\n#include <math.h>\n#include <Eigen/Dense>\n\n/*\n\n Contains various support algorithms related to using the Eigen Library\n\n */\n\n/*! This function provides a general conversion between an Eigen matrix and\nan output C array.  Note that this routine would convert an inbound type\nto a MAtrixXd and then transpose the matrix which would be inefficient\nin a lot of cases.\n@return void\n@param inMat The source Eigen matrix that we are converting\n@param outArray The destination array (sized by the user!) we copy in to\n*/\nvoid eigenMatrixXd2CArray(Eigen::MatrixXd inMat, double *outArray)\n{\n\tEigen::MatrixXd tempMat = inMat.transpose();\n\tmemcpy(outArray, tempMat.data(), inMat.rows()*inMat.cols()*sizeof(double));\n}\n\n/*! This function provides a direct conversion between a 3-vector and an\noutput C array.  We are providing this function to save on the  inline conversion\nand the transpose that would have been performed by the general case.\n@return void\n@param inMat The source Eigen matrix that we are converting\n@param outArray The destination array (sized by the user!) we copy in to\n*/\nvoid eigenVector3d2CArray(Eigen::Vector3d & inMat, double *outArray)\n{\n\tmemcpy(outArray, inMat.data(), 3 * sizeof(double));\n}\n\n/*! This function provides a direct conversion between a 3x3 matrix and an\noutput C array.  We are providing this function to save on the inline conversion\nthat would have been performed by the general case.\n@return void\n@param inMat The source Eigen matrix that we are converting\n@param outArray The destination array (sized by the user!) we copy in to\n*/\nvoid eigenMatrix3d2CArray(Eigen::Matrix3d & inMat, double *outArray)\n{\n\tEigen::MatrixXd tempMat = inMat.transpose();\n\tmemcpy(outArray, tempMat.data(), 9 * sizeof(double));\n}\n/*! This function performs the general conversion between an input C array\nand an Eigen matrix.  Note that to use this function the user MUST size\nthe Eigen matrix ahead of time so that the internal map call has enough\ninformation to ingest the C array.\n@return Eigen::MatrixXd\n@param inArray The input array (row-major)\n@param outMat The output Eigen matrix\n*/\nEigen::MatrixXd cArray2EigenMatrixXd(double *inArray, int nRows, int nCols)\n{\n    Eigen::MatrixXd outMat;\n    outMat.resize(nRows, nCols);\n\toutMat = Eigen::Map<Eigen::MatrixXd>(inArray, outMat.rows(), outMat.cols());\n    return outMat;\n}\n/*! This function performs the conversion between an input C array\n3-vector and an output Eigen vector3d.  This function is provided\nin order to save an unnecessary conversion between types\n@return Eigen::Vector3d\n@param inArray The input array (row-major)\n@param outMat The output Eigen matrix\n*/\nEigen::Vector3d cArray2EigenVector3d(double *inArray)\n{\n    return Eigen::Map<Eigen::Vector3d>(inArray, 3, 1);\n}\n/*! This function performs the conversion between an input C array\n3x3-matrix and an output Eigen vector3d.  This function is provided\nin order to save an unnecessary conversion between types\n@return Eigen::Matrix3d\n@param inArray The input array (row-major)\n@param outMat The output Eigen matrix\n*/\nEigen::Matrix3d cArray2EigenMatrix3d(double *inArray)\n{\n\treturn Eigen::Map<Eigen::Matrix3d>(inArray, 3, 3);\n}\n\n\n/*! This function returns the Eigen DCM that corresponds to a 1-axis rotation\n by the angle theta.  The DCM is the positive theta rotation from the original\n frame to the final frame.\n @return Eigen::Matrix3d\n @param angle The input rotation angle\n */\nEigen::Matrix3d eigenM1(double angle)\n{\n    Eigen::Matrix3d mOut;\n\n    mOut.setIdentity();\n\n    mOut(1,1) = cos(angle);\n    mOut(1,2) = sin(angle);\n    mOut(2,1) = -mOut(1,2);\n    mOut(2,2) = mOut(1,1);\n\n    return mOut;\n}\n\n\n/*! This function returns the Eigen DCM that corresponds to a 2-axis rotation\n by the angle theta.  The DCM is the positive theta rotation from the original\n frame to the final frame.\n @return Eigen::Matrix3d\n @param angle The input rotation angle\n */\nEigen::Matrix3d eigenM2(double angle)\n{\n    Eigen::Matrix3d mOut;\n\n    mOut.setIdentity();\n\n    mOut(0,0) = cos(angle);\n    mOut(0,2) = -sin(angle);\n    mOut(2,0) = -mOut(0,2);\n    mOut(2,2) = mOut(0,0);\n\n    return mOut;\n}\n\n\n/*! This function returns the Eigen DCM that corresponds to a 3-axis rotation\n by the angle theta.  The DCM is the positive theta rotation from the original\n frame to the final frame.\n @return Eigen::Matrix3d\n @param angle The input rotation angle\n */\nEigen::Matrix3d eigenM3(double angle)\n{\n    Eigen::Matrix3d mOut;\n\n    mOut.setIdentity();\n\n    mOut(0,0) = cos(angle);\n    mOut(0,1) = sin(angle);\n    mOut(1,0) = -mOut(0,1);\n    mOut(1,1) = mOut(0,0);\n\n    return mOut;\n}\n\n\n/*! This function returns the tilde matrix version of a vector. The tilde\n matrix is the matrixi equivalent of a vector cross product, where\n [tilde_a] b == a x b\n @return Eigen::Matrix3d\n @param vec The input vector\n */\nEigen::Matrix3d eigenTilde(Eigen::Vector3d vec)\n{\n    Eigen::Matrix3d mOut;\n\n    mOut(0,0) = mOut(1,1) = mOut(2,2) = 0.0;\n\n    mOut(0,1) = -vec(2);\n    mOut(1,0) =  vec(2);\n    mOut(0,2) =  vec(1);\n    mOut(2,0) = -vec(1);\n    mOut(1,2) = -vec(0);\n    mOut(2,1) =  vec(0);\n\n    return mOut;\n}\n\n\n/*! This function solves for the zero of the passed function using the Newton Raphson Method\n@return double\n@param initialEstimate The initial value to use for newton-raphson\n@param accuracy The desired upper bound for the error\n@param f Function to find the zero of\n@param fPrime First derivative of the function\n*/\ndouble newtonRaphsonSolve(double initialEstimate, double accuracy, std::function< double(double) >& f, std::function<\n                          double(double) >& fPrime) {\n\tdouble currentEstimate = initialEstimate;\n\tfor (int i = 0; i < 100 && std::abs(f(currentEstimate)) > accuracy; i++) {\n\t\tdouble functionVal = f(currentEstimate);\n\t\tdouble functionDeriv = fPrime(currentEstimate);\n\t\tcurrentEstimate = currentEstimate - functionVal/functionDeriv;\n\t}\n\treturn currentEstimate;\n}\n\n", "meta": {"hexsha": "5fff6c07a7acdd60491654137114f83db5a1b186", "size": 6745, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/simulation/utilities/avsEigenSupport.cpp", "max_stars_repo_name": "ian-cooke/basilisk_mag", "max_stars_repo_head_hexsha": "a8b1e37c31c1287549d6fd4d71fcaa35b6fc3f14", "max_stars_repo_licenses": ["0BSD"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/simulation/utilities/avsEigenSupport.cpp", "max_issues_repo_name": "ian-cooke/basilisk_mag", "max_issues_repo_head_hexsha": "a8b1e37c31c1287549d6fd4d71fcaa35b6fc3f14", "max_issues_repo_licenses": ["0BSD"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-03-13T20:52:22.000Z", "max_issues_repo_issues_event_max_datetime": "2019-03-13T20:52:22.000Z", "max_forks_repo_path": "src/simulation/utilities/avsEigenSupport.cpp", "max_forks_repo_name": "ian-cooke/basilisk_mag", "max_forks_repo_head_hexsha": "a8b1e37c31c1287549d6fd4d71fcaa35b6fc3f14", "max_forks_repo_licenses": ["0BSD"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.9668246445, "max_line_length": 117, "alphanum_fraction": 0.7337286879, "num_tokens": 1761, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6039318479832804, "lm_q2_score": 0.5621765008857982, "lm_q1q2_score": 0.33951629307273434}}
{"text": "// Distributed under the MIT License.\n// See LICENSE.txt for details.\n\n#pragma once\n\n#include <algorithm>\n#include <array>\n#include <boost/functional/hash.hpp>\n#include <cstddef>\n#include <functional>\n#include <tuple>\n#include <type_traits>\n#include <utility>  // IWYU pragma: keep // for std::forward\n\n#include \"DataStructures/ApplyMatrices.hpp\"\n#include \"DataStructures/DataBox/PrefixHelpers.hpp\"\n#include \"DataStructures/DataBox/Prefixes.hpp\"\n#include \"DataStructures/Matrix.hpp\"\n#include \"DataStructures/Variables.hpp\"\n#include \"Domain/Structure/Direction.hpp\"\n#include \"Domain/Structure/ElementId.hpp\"\n#include \"NumericalAlgorithms/DiscontinuousGalerkin/LiftFlux.hpp\"\n#include \"NumericalAlgorithms/Spectral/Mesh.hpp\"\n#include \"NumericalAlgorithms/Spectral/Projection.hpp\"\n#include \"Utilities/Algorithm.hpp\"\n#include \"Utilities/ErrorHandling/Assert.hpp\"\n#include \"Utilities/Gsl.hpp\"\n#include \"Utilities/MakeArray.hpp\"\n#include \"Utilities/TMPL.hpp\"\n/// \\cond\ntemplate <size_t VolumeDim>\nclass ElementId;\ntemplate <size_t VolumeDim>\nclass OrientationMap;\n// IWYU pragma: no_forward_declare Variables\n/// \\endcond\n\nnamespace dg {\n\ntemplate <size_t VolumeDim>\nusing MortarId = std::pair<::Direction<VolumeDim>, ElementId<VolumeDim>>;\ntemplate <size_t MortarDim>\nusing MortarSize = std::array<Spectral::MortarSize, MortarDim>;\ntemplate <size_t VolumeDim, typename ValueType>\nusing MortarMap = std::unordered_map<MortarId<VolumeDim>, ValueType,\n                                     boost::hash<MortarId<VolumeDim>>>;\n\n/// \\ingroup DiscontinuousGalerkinGroup\n/// Find a mesh for a mortar capable of representing data from either\n/// of two faces.\n///\n/// \\warning Make sure the two face meshes are oriented the same, i.e.\n/// their dimensions align. This is facilitated by the `orientation`\n/// passed to `domain::Initialization::create_initial_mesh`, for\n/// example.\ntemplate <size_t Dim>\nMesh<Dim> mortar_mesh(const Mesh<Dim>& face_mesh1, const Mesh<Dim>& face_mesh2);\n\n/// \\ingroup DiscontinuousGalerkinGroup\n/// Determine the size of the mortar (i.e., the part of the face it\n/// covers) for communicating with a neighbor.  This is the size\n/// relative to the size of \\p self, and will not generally agree with\n/// that determined by \\p neighbor.\ntemplate <size_t Dim>\nMortarSize<Dim - 1> mortar_size(const ElementId<Dim>& self,\n                                const ElementId<Dim>& neighbor,\n                                size_t dimension,\n                                const OrientationMap<Dim>& orientation);\n\n/// \\ingroup DiscontinuousGalerkinGroup\n/// Project variables from a face to a mortar.\ntemplate <typename Tags, size_t Dim>\nVariables<Tags> project_to_mortar(const Variables<Tags>& vars,\n                                  const Mesh<Dim>& face_mesh,\n                                  const Mesh<Dim>& mortar_mesh,\n                                  const MortarSize<Dim>& mortar_size) {\n  const auto projection_matrices = Spectral::projection_matrix_parent_to_child(\n      face_mesh, mortar_mesh, mortar_size);\n  return apply_matrices(projection_matrices, vars, face_mesh.extents());\n}\n\n/// \\ingroup DiscontinuousGalerkinGroup\n/// Project variables from a mortar to a face.\ntemplate <typename Tags, size_t Dim>\nVariables<Tags> project_from_mortar(const Variables<Tags>& vars,\n                                    const Mesh<Dim>& face_mesh,\n                                    const Mesh<Dim>& mortar_mesh,\n                                    const MortarSize<Dim>& mortar_size) {\n  ASSERT(Spectral::needs_projection(face_mesh, mortar_mesh, mortar_size),\n         \"project_from_mortar should not be called if the interface mesh and \"\n         \"mortar mesh are identical. Please elide the copy instead.\");\n  const auto projection_matrices = Spectral::projection_matrix_child_to_parent(\n      mortar_mesh, face_mesh, mortar_size);\n  return apply_matrices(projection_matrices, vars, mortar_mesh.extents());\n}\n\n}  // namespace dg\n", "meta": {"hexsha": "1d38d470cd9e15052c6ecf4f2856a2b0336bee66", "size": 3943, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/NumericalAlgorithms/DiscontinuousGalerkin/MortarHelpers.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/NumericalAlgorithms/DiscontinuousGalerkin/MortarHelpers.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/NumericalAlgorithms/DiscontinuousGalerkin/MortarHelpers.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": 40.2346938776, "max_line_length": 80, "alphanum_fraction": 0.7068222166, "num_tokens": 875, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.658417500561683, "lm_q2_score": 0.5156199157230157, "lm_q1q2_score": 0.33949317615017366}}
{"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_RANDOM_SPANNING_TREE_HPP\n#define BOOST_GRAPH_RANDOM_SPANNING_TREE_HPP\n\n#include <vector>\n#include <boost/assert.hpp>\n#include <boost/graph/loop_erased_random_walk.hpp>\n#include <boost/graph/random.hpp>\n#include <boost/graph/iteration_macros.hpp>\n#include <boost/property_map/property_map.hpp>\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/named_function_params.hpp>\n\nnamespace boost\n{\n\nnamespace detail\n{\n    // Use Wilson's algorithm (based on loop-free random walks) to generate a\n    // random spanning tree.  The distribution of edges used is controlled by\n    // the next_edge() function, so this version allows either weighted or\n    // unweighted selection of trees.\n    // Algorithm is from http://en.wikipedia.org/wiki/Uniform_spanning_tree\n    template < typename Graph, typename PredMap, typename ColorMap,\n        typename NextEdge >\n    void random_spanning_tree_internal(const Graph& g,\n        typename graph_traits< Graph >::vertex_descriptor s, PredMap pred,\n        ColorMap color, NextEdge next_edge)\n    {\n        typedef\n            typename graph_traits< Graph >::vertex_descriptor vertex_descriptor;\n\n        BOOST_ASSERT(num_vertices(g)\n            >= 1); // g must also be undirected (or symmetric) and connected\n\n        typedef color_traits< typename property_traits< ColorMap >::value_type >\n            color_gen;\n        BGL_FORALL_VERTICES_T(v, g, Graph) put(color, v, color_gen::white());\n\n        std::vector< vertex_descriptor > path;\n\n        put(color, s, color_gen::black());\n        put(pred, s, graph_traits< Graph >::null_vertex());\n\n        BGL_FORALL_VERTICES_T(v, g, Graph)\n        {\n            if (get(color, v) != color_gen::white())\n                continue;\n            loop_erased_random_walk(g, v, next_edge, color, path);\n            for (typename std::vector<\n                     vertex_descriptor >::const_reverse_iterator i\n                 = path.rbegin();\n                 boost::next(i)\n                 != (typename std::vector<\n                     vertex_descriptor >::const_reverse_iterator)path.rend();\n                 ++i)\n            {\n                typename std::vector<\n                    vertex_descriptor >::const_reverse_iterator j\n                    = i;\n                ++j;\n                BOOST_ASSERT(get(color, *j) == color_gen::gray());\n                put(color, *j, color_gen::black());\n                put(pred, *j, *i);\n            }\n        }\n    }\n}\n\n// Compute a uniformly-distributed spanning tree on a graph.  Use Wilson's\n// algorithm:\n// @inproceedings{wilson96generating,\n//    author = {Wilson, David Bruce},\n//    title = {Generating random spanning trees more quickly than the cover\n//    time}, booktitle = {STOC '96: Proceedings of the twenty-eighth annual ACM\n//    symposium on Theory of computing}, year = {1996}, isbn = {0-89791-785-5},\n//    pages = {296--303},\n//    location = {Philadelphia, Pennsylvania, United States},\n//    doi = {http://doi.acm.org/10.1145/237814.237880},\n//    publisher = {ACM},\n//    address = {New York, NY, USA},\n//  }\n//\ntemplate < typename Graph, typename Gen, typename PredMap, typename ColorMap >\nvoid random_spanning_tree(const Graph& g, Gen& gen,\n    typename graph_traits< Graph >::vertex_descriptor root, PredMap pred,\n    static_property_map< double >, ColorMap color)\n{\n    unweighted_random_out_edge_gen< Graph, Gen > random_oe(gen);\n    detail::random_spanning_tree_internal(g, root, pred, color, random_oe);\n}\n\n// Compute a weight-distributed spanning tree on a graph.\ntemplate < typename Graph, typename Gen, typename PredMap, typename WeightMap,\n    typename ColorMap >\nvoid random_spanning_tree(const Graph& g, Gen& gen,\n    typename graph_traits< Graph >::vertex_descriptor root, PredMap pred,\n    WeightMap weight, ColorMap color)\n{\n    weighted_random_out_edge_gen< Graph, WeightMap, Gen > random_oe(\n        weight, gen);\n    detail::random_spanning_tree_internal(g, root, pred, color, random_oe);\n}\n\ntemplate < typename Graph, typename Gen, typename P, typename T, typename R >\nvoid random_spanning_tree(\n    const Graph& g, Gen& gen, const bgl_named_params< P, T, R >& params)\n{\n    using namespace boost::graph::keywords;\n    typedef bgl_named_params< P, T, R > params_type;\n    BOOST_GRAPH_DECLARE_CONVERTED_PARAMETERS(params_type, params)\n    typedef typename graph_traits< Graph >::vertex_descriptor vertex_descriptor;\n    vertex_descriptor default_vertex = *vertices(g).first;\n    vertex_descriptor start_vertex = arg_pack[_root_vertex | default_vertex];\n    typename boost::parameter::binding< arg_pack_type,\n        boost::graph::keywords::tag::predecessor_map >::type pred_map\n        = arg_pack[_predecessor_map];\n    static_property_map< double > default_weight_map(1.);\n    typename boost::parameter::value_type< arg_pack_type,\n        boost::graph::keywords::tag::weight_map,\n        static_property_map< double > >::type e_w_map\n        = arg_pack[_weight_map | default_weight_map];\n    typename boost::detail::map_maker< Graph, arg_pack_type,\n        boost::graph::keywords::tag::color_map,\n        boost::default_color_type >::map_type c_map\n        = boost::detail::make_color_map_from_arg_pack(g, arg_pack);\n    random_spanning_tree(g, gen, start_vertex, pred_map, e_w_map, c_map);\n}\n}\n\n#include <boost/graph/iteration_macros_undef.hpp>\n\n#endif // BOOST_GRAPH_RANDOM_SPANNING_TREE_HPP\n", "meta": {"hexsha": "593261da81e56e44032f519ea6a8f31a44e4ac69", "size": 5775, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ReactNativeFrontend/ios/Pods/boost/boost/graph/random_spanning_tree.hpp", "max_stars_repo_name": "Harshitha91/Tmdb-react-native-node", "max_stars_repo_head_hexsha": "e06e3f25a7ee6946ef07a1f524fdf62e48424293", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 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/random_spanning_tree.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/random_spanning_tree.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": 39.8275862069, "max_line_length": 80, "alphanum_fraction": 0.6812121212, "num_tokens": 1330, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.658417500561683, "lm_q2_score": 0.5156199157230156, "lm_q1q2_score": 0.33949317615017355}}
{"text": "#include <vector>\n#include <map>\n#include <boost/pending/disjoint_sets.hpp>\n\nusing namespace std;\n\ntemplate <class T>\nclass AffinityGraphCompare{\n    private:\n        const T * mEdgeWeightArray;\n    public:\n        AffinityGraphCompare(const T * EdgeWeightArray){\n            mEdgeWeightArray = EdgeWeightArray;\n        }\n        bool operator() (const int& ind1, const int& ind2) const {\n            return (mEdgeWeightArray[ind1] > mEdgeWeightArray[ind2]);\n        }\n};\n\nvoid connected_components_cpp(const int nVert,\n               const int nEdge, const uint64_t* node1, const uint64_t* node2, const int* edgeWeight,\n               uint64_t* seg){\n    /* Make disjoint sets */\n    vector<uint64_t> rank(nVert);\n    vector<uint64_t> parent(nVert);\n    boost::disjoint_sets<uint64_t*, uint64_t*> dsets(&rank[0],&parent[0]);\n    for (int i=0; i<nVert; ++i)\n        dsets.make_set(i);\n\n    /* union */\n    for (int i = 0; i < nEdge; ++i )\n         // check bounds to make sure the nodes are valid\n        if ((edgeWeight[i]!=0) && (node1[i]>=0) && (node1[i]<nVert) && (node2[i]>=0) && (node2[i]<nVert))\n            dsets.union_set(node1[i],node2[i]);\n\n    /* find */\n    for (int i = 0; i < nVert; ++i)\n        seg[i] = dsets.find_set(i);\n}\n\n\n\nvoid marker_watershed_cpp(const int nVert, const uint64_t* marker,\n               const int nEdge, const uint64_t* node1, const uint64_t* node2, const float* edgeWeight,\n               uint64_t* seg){\n\n    /* Make disjoint sets */\n    vector<uint64_t> rank(nVert);\n    vector<uint64_t> parent(nVert);\n    boost::disjoint_sets<uint64_t*, uint64_t*> dsets(&rank[0],&parent[0]);\n    for (uint64_t i=0; i<nVert; ++i)\n        dsets.make_set(i);\n\n    /* initialize output array and find representatives of each class */\n    std::map<uint64_t,uint64_t> components;\n    for (uint64_t i=0; i<nVert; ++i){\n        seg[i] = marker[i];\n        if (seg[i] > 0)\n            components[seg[i]] = i;\n    }\n\n    // merge vertices labeled with the same marker\n    for (uint64_t i=0; i<nVert; ++i)\n        if (seg[i] > 0)\n            dsets.union_set(components[seg[i]],i);\n\n    /* Sort all the edges in decreasing order of weight */\n    std::vector<int> pqueue( nEdge );\n    int j = 0;\n    for (int i = 0; i < nEdge; ++i)\n        if ((edgeWeight[i]!=0) &&\n            (node1[i]>=0) && (node1[i]<nVert) &&\n            (node2[i]>=0) && (node2[i]<nVert) &&\n            (marker[node1[i]]>=0) && (marker[node2[i]]>=0))\n                pqueue[ j++ ] = i;\n    unsigned long nValidEdge = j;\n    pqueue.resize(nValidEdge);\n    sort( pqueue.begin(), pqueue.end(), AffinityGraphCompare<float>( edgeWeight ) );\n\n    /* Start MST */\n\tint e;\n    int set1, set2, label_of_set1, label_of_set2;\n    for (unsigned int i = 0; i < pqueue.size(); ++i ) {\n\t\te = pqueue[i];\n        set1=dsets.find_set(node1[e]);\n        set2=dsets.find_set(node2[e]);\n        label_of_set1 = seg[set1];\n        label_of_set2 = seg[set2];\n\n        if ((set1!=set2) &&\n            ( ((label_of_set1==0) && (marker[set1]==0)) ||\n             ((label_of_set2==0) && (marker[set1]==0))) ){\n\n            dsets.link(set1, set2);\n            // either label_of_set1 is 0 or label_of_set2 is 0.\n            seg[dsets.find_set(set1)] = std::max(label_of_set1,label_of_set2);\n            \n        }\n\n    }\n\n    // write out the final coloring\n    for (int i=0; i<nVert; i++)\n        seg[i] = seg[dsets.find_set(i)];\n\n}\n\n", "meta": {"hexsha": "6a54d1e6020292d22ab18246b4cccfe0a91b6307", "size": 3395, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "torch_connectomics/utils/seg/cpp/seg_core/cpp-seg_core.cpp", "max_stars_repo_name": "aarushgupta/pytorch_connectomics", "max_stars_repo_head_hexsha": "eb90ada14dbd425a741f481761d1ed9ea633e67c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2019-09-28T02:20:58.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-17T18:18:18.000Z", "max_issues_repo_path": "torch_connectomics/utils/seg/cpp/seg_core/cpp-seg_core.cpp", "max_issues_repo_name": "HoraceKem/pytorch_connectomics", "max_issues_repo_head_hexsha": "2cd4e17b6fa83005a13c1347a01b8b6964e746c3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-09-22T08:49:04.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-22T08:49:04.000Z", "max_forks_repo_path": "torch_connectomics/utils/seg/cpp/seg_core/cpp-seg_core.cpp", "max_forks_repo_name": "HoraceKem/pytorch_connectomics", "max_forks_repo_head_hexsha": "2cd4e17b6fa83005a13c1347a01b8b6964e746c3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.4351851852, "max_line_length": 105, "alphanum_fraction": 0.5681885125, "num_tokens": 998, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.658417500561683, "lm_q2_score": 0.5156199157230156, "lm_q1q2_score": 0.33949317615017355}}
{"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/tokenizer.h>\n\n// Local VOTCA includes\n#include \"votca/xtp/vxc_functionals.h\"\n#include \"votca/xtp/vxc_grid.h\"\n#include \"votca/xtp/vxc_potential.h\"\n\nnamespace votca {\nnamespace xtp {\ntemplate <class Grid>\nVxc_Potential<Grid>::~Vxc_Potential() {\n  if (_setXC) {\n    xc_func_end(&xfunc);\n    if (_use_separate) {\n      xc_func_end(&cfunc);\n    }\n  }\n}\ntemplate <class Grid>\ndouble Vxc_Potential<Grid>::getExactExchange(const std::string& functional) {\n\n  double exactexchange = 0.0;\n  Vxc_Functionals map;\n  tools::Tokenizer tok(functional, \" \");\n  std::vector<std::string> functional_names = tok.ToVector();\n\n  if (functional_names.size() > 2) {\n    throw std::runtime_error(\"Too many functional names\");\n  } else if (functional_names.size() < 1) {\n    throw std::runtime_error(\"Specify at least one functional\");\n  }\n\n  for (const std::string& functional_name : functional_names) {\n\n    int func_id = map.getID(functional_name);\n    if (func_id < 0) {\n      exactexchange = 0.0;\n      break;\n    }\n    xc_func_type func;\n    if (xc_func_init(&func, func_id, XC_UNPOLARIZED) != 0) {\n      throw std::runtime_error(\n          (boost::format(\"Functional %s not found\\n\") % functional_name).str());\n    }\n    if (exactexchange > 0 && func.cam_alpha > 0) {\n      throw std::runtime_error(\n          \"You have specified two functionals with exact exchange\");\n    }\n    exactexchange += func.cam_alpha;\n    xc_func_end(&func);\n  }\n\n  return exactexchange;\n}\ntemplate <class Grid>\nvoid Vxc_Potential<Grid>::setXCfunctional(const std::string& functional) {\n\n  Vxc_Functionals map;\n  std::vector<std::string> strs;\n  tools::Tokenizer tok(functional, \" ,\\n\\t\");\n  tok.ToVector(strs);\n  xfunc_id = 0;\n  _use_separate = false;\n  cfunc_id = 0;\n  if (strs.size() == 1) {\n    xfunc_id = map.getID(strs[0]);\n  } else if (strs.size() == 2) {\n    xfunc_id = map.getID(strs[0]);\n    cfunc_id = map.getID(strs[1]);\n    _use_separate = true;\n  } else {\n    throw std::runtime_error(\n        \"LIBXC. Please specify one combined or an exchange and a correlation \"\n        \"functionals\");\n  }\n\n  if (xc_func_init(&xfunc, xfunc_id, XC_UNPOLARIZED) != 0) {\n    throw std::runtime_error(\n        (boost::format(\"Functional %s not found\\n\") % strs[0]).str());\n  }\n  if (xfunc.info->kind != 2 && !_use_separate) {\n    throw std::runtime_error(\n        \"Your functional misses either correlation or exchange, please specify \"\n        \"another functional, separated by whitespace\");\n  }\n  if (_use_separate) {\n    if (xc_func_init(&cfunc, cfunc_id, XC_UNPOLARIZED) != 0) {\n      throw std::runtime_error(\n          (boost::format(\"Functional %s not found\\n\") % strs[1]).str());\n    }\n    if ((xfunc.info->kind + cfunc.info->kind) != 1) {\n      throw std::runtime_error(\n          \"Your functionals are not one exchange and one correlation\");\n    }\n  }\n  _setXC = true;\n  return;\n}\ntemplate <class Grid>\ntypename Vxc_Potential<Grid>::XC_entry Vxc_Potential<Grid>::EvaluateXC(\n    double rho, double sigma) const {\n\n  Vxc_Potential<Grid>::XC_entry result;\n  switch (xfunc.info->family) {\n    case XC_FAMILY_LDA:\n      xc_lda_exc_vxc(&xfunc, 1, &rho, &result.f_xc, &result.df_drho);\n      break;\n    case XC_FAMILY_GGA:\n    case XC_FAMILY_HYB_GGA:\n      xc_gga_exc_vxc(&xfunc, 1, &rho, &sigma, &result.f_xc, &result.df_drho,\n                     &result.df_dsigma);\n      break;\n  }\n  if (_use_separate) {\n    typename Vxc_Potential<Grid>::XC_entry temp;\n    // via libxc correlation part only\n    switch (cfunc.info->family) {\n      case XC_FAMILY_LDA:\n        xc_lda_exc_vxc(&cfunc, 1, &rho, &temp.f_xc, &temp.df_drho);\n        break;\n      case XC_FAMILY_GGA:\n      case XC_FAMILY_HYB_GGA:\n        xc_gga_exc_vxc(&cfunc, 1, &rho, &sigma, &temp.f_xc, &temp.df_drho,\n                       &temp.df_dsigma);\n        break;\n    }\n\n    result.f_xc += temp.f_xc;\n    result.df_drho += temp.df_drho;\n    result.df_dsigma += temp.df_dsigma;\n  }\n\n  return result;\n}\ntemplate <class Grid>\nMat_p_Energy Vxc_Potential<Grid>::IntegrateVXC(\n    const Eigen::MatrixXd& density_matrix) const {\n\n  Mat_p_Energy vxc = Mat_p_Energy(density_matrix.rows(), density_matrix.cols());\n\n#pragma omp parallel for schedule(guided) reduction(+ : vxc)\n  for (Index i = 0; i < _grid.getBoxesSize(); ++i) {\n    const GridBox& box = _grid[i];\n    if (!box.Matrixsize()) {\n      continue;\n    }\n    double EXC_box = 0.0;\n    const Eigen::MatrixXd DMAT_here = box.ReadFromBigMatrix(density_matrix);\n    const Eigen::MatrixXd DMAT_symm = DMAT_here + DMAT_here.transpose();\n    double cutoff =\n        1.e-40 / double(density_matrix.rows()) / double(density_matrix.rows());\n    if (DMAT_here.cwiseAbs2().maxCoeff() < cutoff) {\n      continue;\n    }\n    Eigen::MatrixXd Vxc_here =\n        Eigen::MatrixXd::Zero(DMAT_here.rows(), DMAT_here.cols());\n    const std::vector<Eigen::Vector3d>& points = box.getGridPoints();\n    const std::vector<double>& weights = box.getGridWeights();\n\n    // iterate over gridpoints\n    for (Index p = 0; p < box.size(); p++) {\n      Eigen::MatrixX3d ao_grad = Eigen::MatrixX3d::Zero(box.Matrixsize(), 3);\n      Eigen::VectorXd ao = box.CalcAOValue_and_Grad(ao_grad, points[p]);\n      const double rho = 0.5 * (ao.transpose() * DMAT_symm * ao).value();\n      const double weight = weights[p];\n      if (rho * weight < 1.e-20) {\n        continue;  // skip the rest, if density is very small\n      }\n      const Eigen::Vector3d rho_grad = ao.transpose() * DMAT_symm * ao_grad;\n      const double sigma = (rho_grad.transpose() * rho_grad).value();\n      const Eigen::VectorXd grad = ao_grad * rho_grad;\n      typename Vxc_Potential<Grid>::XC_entry xc = EvaluateXC(rho, sigma);\n      EXC_box += weight * rho * xc.f_xc;\n      auto addXC = weight * (0.5 * xc.df_drho * ao + 2.0 * xc.df_dsigma * grad);\n      Vxc_here.noalias() += addXC * ao.transpose();\n    }\n    box.AddtoBigMatrix(vxc.matrix(), Vxc_here);\n    vxc.energy() += EXC_box;\n  }\n\n  return Mat_p_Energy(vxc.energy(), vxc.matrix() + vxc.matrix().transpose());\n}\n\ntemplate class Vxc_Potential<Vxc_Grid>;\n\n}  // namespace xtp\n}  // namespace votca\n", "meta": {"hexsha": "3c05dd9843552993adb7e5097527699311fbad0a", "size": 6846, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/libxtp/numerical_integration/vxc_potential.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/numerical_integration/vxc_potential.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/numerical_integration/vxc_potential.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": 32.4454976303, "max_line_length": 80, "alphanum_fraction": 0.6503067485, "num_tokens": 1932, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6584175005616829, "lm_q2_score": 0.5156199157230156, "lm_q1q2_score": 0.3394931761501735}}
{"text": "\n#include <NTL/mat_ZZ_p.h>\n#include <NTL/vec_ZZVec.h>\n#include <NTL/vec_long.h>\n#include <NTL/BasicThreadPool.h>\n\n\n// FIXME: only needed if we use multi-modular MM\n#include <NTL/MatPrime.h>\n#include <NTL/mat_lzz_p.h>\n\n\n\nNTL_START_IMPL\n\n\n\n// ******************** Matrix Multiplication ************************\n\n#ifdef NTL_HAVE_LL_TYPE\n#define NTL_USE_MM_MATMUL (1)\n#else\n#define NTL_USE_MM_MATMUL (0)\n#endif\n\n#define PAR_THRESH (40000.0)\n\n\n// *********************** Plain Matrix Multiplication ***************\n\n\n\nvoid plain_mul_aux(mat_ZZ_p& X, const mat_ZZ_p& A, const mat_ZZ_p& B)  \n{  \n   long n = A.NumRows();  \n   long l = A.NumCols();  \n   long m = B.NumCols();  \n  \n   if (l != B.NumRows())  \n      LogicError(\"matrix mul: dimension mismatch\");  \n  \n   X.SetDims(n, m);  \n\n   ZZ_pContext context;\n   context.save();\n\n   long sz = ZZ_p::ModulusSize();\n   bool seq = (double(n)*double(l)*double(m)*double(sz)*double(sz) < PAR_THRESH);\n  \n   NTL_GEXEC_RANGE(seq, m, first, last)\n   NTL_IMPORT(n)\n   NTL_IMPORT(l)\n   NTL_IMPORT(m)\n\n   context.restore();\n\n   long i, j, k;  \n   ZZ acc, tmp;  \n\n   vec_ZZ_p B_col;\n   B_col.SetLength(l);\n\n   for (j = first; j < last; j++) {\n      for (k = 0; k < l; k++) B_col[k] = B[k][j];\n\n      for (i = 0; i < n; i++) {\n         clear(acc);\n         for (k = 0; k < l; k++) {\n            mul(tmp, rep(A[i][k]), rep(B_col[k]));\n            add(acc, acc, tmp);\n         }\n         conv(X[i][j], acc);\n      }\n   }\n\n   NTL_GEXEC_RANGE_END\n}  \n  \n  \nvoid plain_mul(mat_ZZ_p& X, const mat_ZZ_p& A, const mat_ZZ_p& B)  \n{  \n   if (&X == &A || &X == &B) {  \n      mat_ZZ_p tmp;  \n      plain_mul_aux(tmp, A, B);  \n      X = tmp;  \n   }  \n   else  \n      plain_mul_aux(X, A, B);  \n}  \n\n// X = A*transpose(B)\n\nvoid plain_mul_transpose_aux(mat_ZZ_p& X, const mat_ZZ_p& A, const mat_ZZ_p& B)  \n{  \n   long n = A.NumRows();  \n   long l = A.NumCols();  \n   long m = B.NumRows();  \n  \n   if (l != B.NumCols())  \n      LogicError(\"matrix mul: dimension mismatch\");  \n  \n   X.SetDims(n, m);  \n\n   ZZ_pContext context;\n   context.save();\n\n   long sz = ZZ_p::ModulusSize();\n   bool seq = (double(n)*double(l)*double(m)*double(sz)*double(sz) < PAR_THRESH);\n  \n   NTL_GEXEC_RANGE(seq, m, first, last)\n   NTL_IMPORT(n)\n   NTL_IMPORT(l)\n   NTL_IMPORT(m)\n\n   context.restore();\n\n   long i, j, k;  \n   ZZ acc, tmp;  \n\n   for (j = first; j < last; j++) {\n      const ZZ_p *B_col = B[j].elts();\n\n      for (i = 0; i < n; i++) {\n         clear(acc);\n         for (k = 0; k < l; k++) {\n            mul(tmp, rep(A[i][k]), rep(B_col[k]));\n            add(acc, acc, tmp);\n         }\n         conv(X[i][j], acc);\n      }\n   }\n\n   NTL_GEXEC_RANGE_END\n}  \n  \n  \nvoid plain_mul_transpose(mat_ZZ_p& X, const mat_ZZ_p& A, const mat_ZZ_p& B)  \n{  \n   if (&X == &A || &X == &B) {  \n      mat_ZZ_p tmp;  \n      plain_mul_transpose_aux(tmp, A, B);  \n      X = tmp;  \n   }  \n   else  \n      plain_mul_transpose_aux(X, A, B);  \n}  \n\n\n\n// ***************** Multi-modular Matrix Multiplication *************\n\nstruct mat_ZZ_p_crt_rep {\n\n   Vec< Mat<MatPrime_residue_t> > rep;\n\n};\n\n\nstatic\nconst MatPrime_crt_helper& get_MatPrime_crt_helper_info()\n{\n   do {\n      Lazy<MatPrime_crt_helper,ZZ_pInfoT::MatPrime_crt_helper_deleter_policy>::Builder\n         builder(ZZ_pInfo->MatPrime_crt_helper_info);\n      if (!builder()) break;\n\n      UniquePtr<MatPrime_crt_helper,ZZ_pInfoT::MatPrime_crt_helper_deleter_policy> p;\n      p.make();\n      build(*p, ZZ_pInfo->p);\n      builder.move(p);\n   } while (0);\n\n   return *ZZ_pInfo->MatPrime_crt_helper_info;\n}\n\nstatic\nvoid RawConvert(Mat<zz_p>& X, const Mat<MatPrime_residue_t>& A)\n{\n   long n = A.NumRows();\n   long m = A.NumCols();\n\n   X.SetDims(n, m);\n   for (long i = 0; i < n; i++) {\n      const MatPrime_residue_t *Ai = A[i].elts();\n      zz_p *Xi = X[i].elts();\n      for (long j = 0; j < m; j++)\n         Xi[j].LoopHole() = Ai[j];\n   }\n} \n\nstatic\nvoid RawConvertTranspose(Mat<zz_p>& X, const Mat<MatPrime_residue_t>& A)\n{\n   long n = A.NumRows();\n   long m = A.NumCols();\n\n   X.SetDims(m, n);\n   for (long i = 0; i < n; i++) {\n      const MatPrime_residue_t *Ai = A[i].elts();\n      for (long j = 0; j < m; j++)\n         X[j][i] = Ai[j];\n   }\n} \n\nstatic\nvoid RawConvert(Mat<MatPrime_residue_t>& X, const Mat<zz_p>& A)\n{\n   long n = A.NumRows();\n   long m = A.NumCols();\n\n   X.SetDims(n, m);\n   for (long i = 0; i < n; i++) {\n      const zz_p *Ai = A[i].elts();\n      MatPrime_residue_t *Xi = X[i].elts();\n      for (long j = 0; j < m; j++)\n         Xi[j] = rep(Ai[j]);\n   }\n} \n\n#define CRT_BLK (8)\n\nvoid to_mat_ZZ_p_crt_rep(mat_ZZ_p_crt_rep& X, const mat_ZZ_p& A)\n{\n   long n = A.NumRows();\n   long m = A.NumCols();\n\n   const MatPrime_crt_helper& H = get_MatPrime_crt_helper_info();\n   long nprimes = H.GetNumPrimes();\n\n   if (NTL_OVERFLOW(nprimes, CRT_BLK, 0))\n      ResourceError(\"overflow\"); // this is pretty academic\n\n   X.rep.SetLength(nprimes);\n   for (long k = 0; k < nprimes; k++) X.rep[k].SetDims(n, m);\n\n   ZZ_pContext context;\n   context.save();\n\n\n   bool seq = (double(n)*double(m)*H.GetCost() < PAR_THRESH);\n\n   // FIXME: right now, we just partition the rows, but if\n   // #cols > #rows, we should perhaps partition the cols\n   NTL_GEXEC_RANGE(seq, n, first, last)\n   NTL_IMPORT(n)\n   NTL_IMPORT(m)\n   NTL_IMPORT(nprimes)\n\n   context.restore();\n\n   MatPrime_crt_helper_scratch scratch;\n   Vec<MatPrime_residue_t> remainders_store;\n   remainders_store.SetLength(nprimes*CRT_BLK);\n   MatPrime_residue_t *remainders = remainders_store.elts();\n\n   for (long i = first; i < last; i++) {\n      const ZZ_p *a = A[i].elts();\n\n      long jj = 0; \n      for (; jj <= m-CRT_BLK; jj += CRT_BLK) {\n         for (long j = 0; j < CRT_BLK; j++)\n            reduce(H, rep(a[jj+j]), remainders + j*nprimes, scratch);\n         for (long k = 0; k < nprimes; k++) {\n            MatPrime_residue_t *x = X.rep[k][i].elts();\n            for (long j = 0; j < CRT_BLK; j++)\n               x[jj+j] = remainders[j*nprimes+k];\n         }\n      }\n      if (jj < m) {\n         for (long j = 0; j < m-jj; j++)\n            reduce(H, rep(a[jj+j]), remainders + j*nprimes, scratch);\n         for (long k = 0; k < nprimes; k++) {\n            MatPrime_residue_t *x = X.rep[k][i].elts();\n            for (long j = 0; j < m-jj; j++)\n               x[jj+j] = remainders[j*nprimes+k];\n         }\n      }\n   }\n\n   NTL_GEXEC_RANGE_END\n}\n\nvoid from_mat_ZZ_p_crt_rep(const mat_ZZ_p_crt_rep& X, mat_ZZ_p& A)\n{\n   long n = X.rep[0].NumRows();\n   long m = X.rep[0].NumCols();\n\n   const MatPrime_crt_helper& H = get_MatPrime_crt_helper_info();\n   long nprimes = H.GetNumPrimes();\n\n   if (NTL_OVERFLOW(nprimes, CRT_BLK, 0))\n      ResourceError(\"overflow\"); // this is pretty academic\n\n   A.SetDims(n, m);\n\n   ZZ_pContext context;\n   context.save();\n\n   bool seq = (double(n)*double(m)*H.GetCost() < PAR_THRESH);\n\n   // FIXME: right now, we just partition the rows, but if\n   // #cols > #rows, we should perhaps partition the cols\n   NTL_GEXEC_RANGE(seq, n, first, last)\n   NTL_IMPORT(n)\n   NTL_IMPORT(m)\n   NTL_IMPORT(nprimes)\n\n   context.restore();\n\n   MatPrime_crt_helper_scratch scratch;\n   Vec<MatPrime_residue_t> remainders_store;\n   remainders_store.SetLength(nprimes*CRT_BLK);\n   MatPrime_residue_t *remainders = remainders_store.elts();\n\n   for (long i = first; i < last; i++) {\n      ZZ_p *a = A[i].elts();\n\n      long jj = 0; \n      for (; jj <= m-CRT_BLK; jj += CRT_BLK) {\n         for (long k = 0; k < nprimes; k++) {\n            const MatPrime_residue_t *x = X.rep[k][i].elts();\n            for (long j = 0; j < CRT_BLK; j++)\n               remainders[j*nprimes+k] = x[jj+j];\n         }\n         for (long j = 0; j < CRT_BLK; j++)\n            reconstruct(H, a[jj+j].LoopHole(), remainders + j*nprimes, scratch);\n      }\n      if (jj < m) {\n         for (long k = 0; k < nprimes; k++) {\n            const MatPrime_residue_t *x = X.rep[k][i].elts();\n            for (long j = 0; j < m-jj; j++)\n               remainders[j*nprimes+k] = x[jj+j];\n         }\n         for (long j = 0; j < m-jj; j++)\n            reconstruct(H, a[jj+j].LoopHole(), remainders + j*nprimes, scratch);\n      }\n   }\n\n   NTL_GEXEC_RANGE_END\n}\n\nvoid mul(mat_ZZ_p_crt_rep& X, const mat_ZZ_p_crt_rep& A, const mat_ZZ_p_crt_rep& B)\n{\n   long nprimes = A.rep.length();\n\n   long n = A.rep[0].NumRows();\n   long l = A.rep[0].NumCols();\n   long m = B.rep[0].NumCols();\n\n   X.rep.SetLength(nprimes);\n   for (long k = 0; k < nprimes; k++) X.rep[k].SetDims(n, m);\n\n   bool seq = (double(n)*double(l)*double(m)*double(nprimes) < PAR_THRESH);\n\n   NTL_GEXEC_RANGE(seq, nprimes, first, last)\n   NTL_IMPORT(n)\n   NTL_IMPORT(l)\n   NTL_IMPORT(m)\n\n   zz_pPush push;\n\n   Mat<zz_p> x, a, b;\n   x.SetDims(n, m);\n   a.SetDims(n, l);\n   b.SetDims(l, m);\n\n   for (long k = first; k < last; k++) {\n      RestoreMatPrime(k);\n      RawConvert(a, A.rep[k]);\n      RawConvert(b, B.rep[k]);\n      mul(x, a, b);\n      RawConvert(X.rep[k], x);\n   }\n\n   NTL_GEXEC_RANGE_END\n}\n\n\n// X = A*transpose(B)\nvoid mul_transpose(mat_ZZ_p_crt_rep& X, const mat_ZZ_p_crt_rep& A, const mat_ZZ_p_crt_rep& B)\n{\n   long nprimes = A.rep.length();\n\n   long n = A.rep[0].NumRows();\n   long l = A.rep[0].NumCols();\n   long m = B.rep[0].NumRows();\n\n   X.rep.SetLength(nprimes);\n   for (long k = 0; k < nprimes; k++) X.rep[k].SetDims(n, m);\n\n   bool seq = (double(n)*double(l)*double(m)*double(nprimes) < PAR_THRESH);\n\n   NTL_GEXEC_RANGE(seq, nprimes, first, last)\n   NTL_IMPORT(n)\n   NTL_IMPORT(l)\n   NTL_IMPORT(m)\n\n   zz_pPush push;\n\n   Mat<zz_p> x, a, b;\n   x.SetDims(n, m);\n   a.SetDims(n, l);\n   b.SetDims(l, m);\n\n   for (long k = first; k < last; k++) {\n      RestoreMatPrime(k);\n      RawConvert(a, A.rep[k]);\n      RawConvertTranspose(b, B.rep[k]);\n      mul(x, a, b);\n      RawConvert(X.rep[k], x);\n   }\n\n   NTL_GEXEC_RANGE_END\n}\n\n\nvoid multi_modular_mul(mat_ZZ_p& X, const mat_ZZ_p& A, const mat_ZZ_p& B)\n{\n   long l = A.NumCols();\n\n   if (l != B.NumRows())\n      LogicError(\"matrix mul: dimension mismatch\");  \n\n   if (l > NTL_MatPrimeLimit)\n      ResourceError(\"matrix mul: dimension too large\");\n\n   mat_ZZ_p_crt_rep x, a, b;\n\n   to_mat_ZZ_p_crt_rep(a, A);\n   to_mat_ZZ_p_crt_rep(b, B);\n   mul(x, a, b);\n   from_mat_ZZ_p_crt_rep(x, X);\n}\n\nvoid multi_modular_mul(mat_ZZ_p& X, const mat_ZZ_p& A, const mat_ZZ_p_crt_rep& B)\n{\n   long l = A.NumCols();\n\n   if (l != B.rep[0].NumRows())\n      LogicError(\"matrix mul: dimension mismatch\");  \n\n   if (l > NTL_MatPrimeLimit)\n      ResourceError(\"matrix mul: dimension too large\");\n\n   mat_ZZ_p_crt_rep x, a;\n\n   to_mat_ZZ_p_crt_rep(a, A);\n   mul(x, a, B);\n   from_mat_ZZ_p_crt_rep(x, X);\n}\n\nvoid multi_modular_mul_transpose(mat_ZZ_p& X, const mat_ZZ_p& A, const mat_ZZ_p_crt_rep& B)\n{\n   long l = A.NumCols();\n\n   if (l != B.rep[0].NumCols())\n      LogicError(\"matrix mul: dimension mismatch\");  \n\n   if (l > NTL_MatPrimeLimit)\n      ResourceError(\"matrix mul: dimension too large\");\n\n   mat_ZZ_p_crt_rep x, a;\n\n   to_mat_ZZ_p_crt_rep(a, A);\n   mul_transpose(x, a, B);\n   from_mat_ZZ_p_crt_rep(x, X);\n}\n\n\n// ******************** mat_ZZ_p_opaque implementation ************\n\n// This could (and maybe eventually will) be implemented using\n// derived types, if we want run-time polymorphism...we'll see\n\nstruct mat_ZZ_p_opaque_body_crt : mat_ZZ_p_opaque_body {\n   mat_ZZ_p_crt_rep body;\n\n   mat_ZZ_p_opaque_body* clone() const \n   {\n      return MakeRaw<mat_ZZ_p_opaque_body_crt>(*this);\n   }\n\n   long NumRows() const\n   {\n      return body.rep.length() == 0 ? 0 : body.rep[0].NumRows();\n   }\n\n   long NumCols() const\n   {\n      return body.rep.length() == 0 ? 0 : body.rep[0].NumCols();\n   }\n\n   void mul(mat_ZZ_p& X, const mat_ZZ_p& A) const\n   { \n      multi_modular_mul(X, A, body);\n   }\n\n   void mul_transpose(mat_ZZ_p& X, const mat_ZZ_p& A) const\n   { \n      multi_modular_mul_transpose(X, A, body);\n   }\n   \n};\n\nstruct mat_ZZ_p_opaque_body_plain : mat_ZZ_p_opaque_body {\n   mat_ZZ_p body;\n\n   mat_ZZ_p_opaque_body* clone() const \n   {\n      return MakeRaw<mat_ZZ_p_opaque_body_plain>(*this);\n   }\n\n   long NumRows() const\n   {\n      return body.NumRows();\n   }\n\n   long NumCols() const\n   {\n      return body.NumCols();\n   }\n\n   void mul(mat_ZZ_p& X, const mat_ZZ_p& A) const\n   { \n      plain_mul(X, A, body);\n   }\n\n   void mul_transpose(mat_ZZ_p& X, const mat_ZZ_p& A) const\n   { \n      plain_mul_transpose(X, A, body);\n   }\n   \n};\n\n\n\n// This is a \"factory\" method that makes a mat_ZZ_p_opaque_body\n// from a matrix A.  The matrix A is destroyed in the process.\n\nmat_ZZ_p_opaque_body *mat_ZZ_p_opaque_body_move(mat_ZZ_p& A)\n{\n   if (NTL_USE_MM_MATMUL && A.NumRows() >= 16 && A.NumCols() >= 16) {\n      UniquePtr<mat_ZZ_p_opaque_body_crt> tmp;\n      tmp.make();\n      to_mat_ZZ_p_crt_rep(tmp->body, A);\n      A.kill();\n      return tmp.release();\n   }\n   else {\n      UniquePtr<mat_ZZ_p_opaque_body_plain> tmp;\n      tmp.make();\n      tmp->body.move(A);\n      return tmp.release();\n   }\n}\n\n\n\n// *******************************************************************\n\n\n\nvoid mul(mat_ZZ_p& X, const mat_ZZ_p& A, const mat_ZZ_p& B)\n{\n   long n = A.NumRows();\n   long l = A.NumCols();\n   long m = B.NumCols();\n\n   if (l != B.NumRows()) LogicError(\"matrix mul: dimension mismatch\");\n\n   if (NTL_USE_MM_MATMUL && n >= 24 && l >= 24 && m >= 24) \n      multi_modular_mul(X, A, B);\n   else\n      plain_mul(X, A, B);\n}\n\n\n\n\n// *******************************************************************\n\n\n\n  \nvoid add(mat_ZZ_p& X, const mat_ZZ_p& A, const mat_ZZ_p& B)  \n{  \n   long n = A.NumRows();  \n   long m = A.NumCols();  \n  \n   if (B.NumRows() != n || B.NumCols() != m)   \n      LogicError(\"matrix add: dimension mismatch\");  \n  \n   X.SetDims(n, m);  \n  \n   long i, j;  \n   for (i = 1; i <= n; i++)   \n      for (j = 1; j <= m; j++)  \n         add(X(i,j), A(i,j), B(i,j));  \n}  \n  \nvoid sub(mat_ZZ_p& X, const mat_ZZ_p& A, const mat_ZZ_p& B)  \n{  \n   long n = A.NumRows();  \n   long m = A.NumCols();  \n  \n   if (B.NumRows() != n || B.NumCols() != m)  \n      LogicError(\"matrix sub: dimension mismatch\");  \n  \n   X.SetDims(n, m);  \n  \n   long i, j;  \n   for (i = 1; i <= n; i++)  \n      for (j = 1; j <= m; j++)  \n         sub(X(i,j), A(i,j), B(i,j));  \n}  \n\nvoid negate(mat_ZZ_p& X, const mat_ZZ_p& A)  \n{  \n   long n = A.NumRows();  \n   long m = A.NumCols();  \n  \n  \n   X.SetDims(n, m);  \n  \n   long i, j;  \n   for (i = 1; i <= n; i++)  \n      for (j = 1; j <= m; j++)  \n         negate(X(i,j), A(i,j));  \n}  \n  \n  \n  \nstatic\nvoid mul_aux(vec_ZZ_p& x, const mat_ZZ_p& A, const vec_ZZ_p& b)  \n{  \n   long n = A.NumRows();  \n   long l = A.NumCols();  \n  \n   if (l != b.length())  \n      LogicError(\"matrix mul: dimension mismatch\");  \n  \n   x.SetLength(n);  \n  \n   long i, k;  \n   ZZ acc, tmp;  \n  \n   for (i = 1; i <= n; i++) {  \n      clear(acc);  \n      for (k = 1; k <= l; k++) {  \n         mul(tmp, rep(A(i,k)), rep(b(k)));  \n         add(acc, acc, tmp);  \n      }  \n      conv(x(i), acc);  \n   }  \n}  \n  \n  \nvoid mul(vec_ZZ_p& x, const mat_ZZ_p& A, const vec_ZZ_p& b)  \n{  \n   if (&b == &x || A.position1(x) != -1) {\n      vec_ZZ_p tmp;\n      mul_aux(tmp, A, b);\n      x = tmp;\n   }\n   else\n      mul_aux(x, A, b);\n}  \n\nstatic\nvoid mul_aux(vec_ZZ_p& x, const vec_ZZ_p& a, const mat_ZZ_p& B)  \n{  \n   long n = B.NumRows();  \n   long l = B.NumCols();  \n  \n   if (n != a.length())  \n      LogicError(\"matrix mul: dimension mismatch\");  \n  \n   x.SetLength(l);  \n  \n   long i, k;  \n   ZZ acc, tmp;  \n  \n   for (i = 1; i <= l; i++) {  \n      clear(acc);  \n      for (k = 1; k <= n; k++) {  \n         mul(tmp, rep(a(k)), rep(B(k,i)));\n         add(acc, acc, tmp);  \n      }  \n      conv(x(i), acc);  \n   }  \n}  \n\nvoid mul(vec_ZZ_p& x, const vec_ZZ_p& a, const mat_ZZ_p& B)\n{\n   if (&a == &x) {\n      vec_ZZ_p tmp;\n      mul_aux(tmp, a, B);\n      x = tmp;\n   }\n   else\n      mul_aux(x, a, B);\n}\n\n     \n  \nvoid ident(mat_ZZ_p& X, long n)  \n{  \n   X.SetDims(n, n);  \n   long i, j;  \n  \n   for (i = 1; i <= n; i++)  \n      for (j = 1; j <= n; j++)  \n         if (i == j)  \n            set(X(i, j));  \n         else  \n            clear(X(i, j));  \n} \n\n\n\nvoid determinant(ZZ_p& d, const mat_ZZ_p& M_in)\n{\n   ZZ t1, t2;\n\n   const ZZ& p = ZZ_p::modulus();\n\n   long n = M_in.NumRows();\n\n   if (M_in.NumCols() != n)\n      LogicError(\"determinant: nonsquare matrix\");\n\n   if (n == 0) {\n      set(d);\n      return;\n   }\n\n   Vec<ZZVec> M;\n   sqr(t1, p);\n   mul(t1, t1, n);\n\n   M.SetLength(n);\n   for (long i = 0; i < n; i++) {\n      M[i].SetSize(n, t1.size());\n      for (long j = 0; j < n; j++)\n         M[i][j] = rep(M_in[i][j]);\n   }\n\n   ZZ det;\n   set(det);\n\n   for (long k = 0; k < n; k++) {\n      long pos = -1;\n      for (long i = k; i < n; i++) {\n         rem(t1, M[i][k], p);\n         M[i][k] = t1;\n         if (pos == -1 && !IsZero(t1))\n            pos = i;\n      }\n\n      if (pos != -1) {\n         if (k != pos) {\n            swap(M[pos], M[k]);\n            NegateMod(det, det, p);\n         }\n\n         MulMod(det, det, M[k][k], p);\n\n         // make M[k, k] == -1 mod p, and make row k reduced\n\n         InvMod(t1, M[k][k], p);\n         NegateMod(t1, t1, p);\n         for (long j = k+1; j < n; j++) {\n            rem(t2, M[k][j], p);\n            MulMod(M[k][j], t2, t1, p);\n         }\n\n\n         bool seq =\n            double(n-(k+1))*(n-(k+1))*double(p.size())*double(p.size()) < PAR_THRESH;\n         NTL_GEXEC_RANGE(seq, n-(k+1), first, last)\n         NTL_IMPORT(n)\n         NTL_IMPORT(k)\n\n         ZZ t1, t2;\n\n         for (long ii = first; ii < last; ii++) {\n            long i = ii + k+1;\n\n            // M[i] = M[i] + M[k]*M[i,k]\n\n            t1 = M[i][k];   // this is already reduced\n\n            ZZ *x = M[i].elts() + (k+1);\n            ZZ *y = M[k].elts() + (k+1);\n\n            for (long j = k+1; j < n; j++, x++, y++) {\n               // *x = *x + (*y)*t1\n\n               mul(t2, *y, t1);\n               add(*x, *x, t2);\n            }\n         }\n\n         NTL_GEXEC_RANGE_END\n\n      }\n      else {\n         clear(d);\n         return;\n      }\n   }\n\n   conv(d, det);\n}\n\n\n\n\n\nlong IsIdent(const mat_ZZ_p& A, long n)\n{\n   if (A.NumRows() != n || A.NumCols() != n)\n      return 0;\n\n   long i, j;\n\n   for (i = 1; i <= n; i++)\n      for (j = 1; j <= n; j++)\n         if (i != j) {\n            if (!IsZero(A(i, j))) return 0;\n         }\n         else {\n            if (!IsOne(A(i, j))) return 0;\n         }\n\n   return 1;\n}\n            \n\nvoid transpose(mat_ZZ_p& X, const mat_ZZ_p& A)\n{\n   long n = A.NumRows();\n   long m = A.NumCols();\n\n   long i, j;\n\n   if (&X == & A) {\n      if (n == m)\n         for (i = 1; i <= n; i++)\n            for (j = i+1; j <= n; j++)\n               swap(X(i, j), X(j, i));\n      else {\n         mat_ZZ_p tmp;\n         tmp.SetDims(m, n);\n         for (i = 1; i <= n; i++)\n            for (j = 1; j <= m; j++)\n               tmp(j, i) = A(i, j);\n         X.kill();\n         X = tmp;\n      }\n   }\n   else {\n      X.SetDims(m, n);\n      for (i = 1; i <= n; i++)\n         for (j = 1; j <= m; j++)\n            X(j, i) = A(i, j);\n   }\n}\n   \n\n\nstatic\nvoid solve_impl(ZZ_p& d, vec_ZZ_p& X, const mat_ZZ_p& A, const vec_ZZ_p& b, bool trans)\n\n{\n   long n = A.NumRows();\n   if (A.NumCols() != n)\n      LogicError(\"solve: nonsquare matrix\");\n\n   if (b.length() != n)\n      LogicError(\"solve: dimension mismatch\");\n\n   if (n == 0) {\n      set(d);\n      X.SetLength(0);\n      return;\n   }\n\n   ZZ t1, t2;\n\n   const ZZ& p = ZZ_p::modulus();\n\n   Vec<ZZVec> M;\n   sqr(t1, p);\n   mul(t1, t1, n);\n\n   M.SetLength(n);\n\n   for (long i = 0; i < n; i++) {\n      M[i].SetSize(n+1, t1.size());\n\n      if (trans) \n         for (long j = 0; j < n; j++) M[i][j] = rep(A[j][i]);\n      else\n         for (long j = 0; j < n; j++) M[i][j] = rep(A[i][j]);\n\n      M[i][n] = rep(b[i]);\n   }\n\n   ZZ det;\n   set(det);\n\n   for (long k = 0; k < n; k++) {\n      long pos = -1;\n      for (long i = k; i < n; i++) {\n         rem(t1, M[i][k], p);\n         M[i][k] = t1;\n         if (pos == -1 && !IsZero(t1)) {\n            pos = i;\n         }\n      }\n\n      if (pos != -1) {\n         if (k != pos) {\n            swap(M[pos], M[k]);\n            NegateMod(det, det, p);\n         }\n\n         MulMod(det, det, M[k][k], p);\n\n         // make M[k, k] == -1 mod p, and make row k reduced\n\n         InvMod(t1, M[k][k], p);\n         NegateMod(t1, t1, p);\n         for (long j = k+1; j <= n; j++) {\n            rem(t2, M[k][j], p);\n            MulMod(M[k][j], t2, t1, p);\n         }\n\n         bool seq =\n            double(n-(k+1))*(n-(k+1))*double(p.size())*double(p.size()) < PAR_THRESH;\n         NTL_GEXEC_RANGE(seq, n-(k+1), first, last)\n         NTL_IMPORT(n)\n         NTL_IMPORT(k)\n\n         ZZ t1, t2;\n\n         for (long ii = first; ii < last; ii++) {\n            long i = ii + k+1;\n\n            // M[i] = M[i] + M[k]*M[i,k]\n\n            t1 = M[i][k];   // this is already reduced\n\n            ZZ *x = M[i].elts() + (k+1);\n            ZZ *y = M[k].elts() + (k+1);\n\n            for (long j = k+1; j <= n; j++, x++, y++) {\n               // *x = *x + (*y)*t1\n\n               mul(t2, *y, t1);\n               add(*x, *x, t2);\n            }\n         }\n\n         NTL_GEXEC_RANGE_END\n\n      }\n      else {\n         clear(d);\n         return;\n      }\n   }\n\n   X.SetLength(n);\n   for (long i = n-1; i >= 0; i--) {\n      clear(t1);\n      for (long j = i+1; j < n; j++) {\n         mul(t2, rep(X[j]), M[i][j]);\n         add(t1, t1, t2);\n      }\n      sub(t1, t1, M[i][n]);\n      conv(X[i], t1);\n   }\n\n   conv(d, det);\n}\n\n\nvoid solve(ZZ_p& d, vec_ZZ_p& x, const mat_ZZ_p& A, const vec_ZZ_p& b)\n{\n   solve_impl(d, x, A, b, true);\n}\n\nvoid solve(ZZ_p& d, const mat_ZZ_p& A, vec_ZZ_p& x,  const vec_ZZ_p& b)\n{\n   solve_impl(d, x, A, b, false);\n}\n\nvoid inv(ZZ_p& d, mat_ZZ_p& X, const mat_ZZ_p& A)\n{\n   long n = A.NumRows();\n\n   if (A.NumCols() != n)\n      LogicError(\"inv: nonsquare matrix\");\n\n   if (n == 0) {\n      set(d);\n      X.SetDims(0, 0);\n      return;\n   }\n\n   const ZZ& p = ZZ_p::modulus();\n\n   ZZ t1, t2;\n   ZZ pivot;\n   ZZ pivot_inv;\n\n   Vec<ZZVec> M;\n   // scratch space\n\n   sqr(t1, p);\n   mul(t1, t1, n);\n\n   M.SetLength(n);\n   for (long i = 0; i < n; i++) {\n      M[i].SetSize(n, t1.size());\n      for (long j = 0; j < n; j++) \n         M[i][j] = rep(A[i][j]);\n   }\n\n   ZZ det;\n   det = 1;\n\n\n   Vec<long> P;\n   P.SetLength(n);\n   for (long k = 0; k < n; k++) P[k] = k;\n   // records swap operations\n   \n\n   bool seq = \n      double(n)*double(n)*double(p.size())*double(p.size()) < PAR_THRESH;\n\n   bool pivoting = false;\n\n   for (long k = 0; k < n; k++) {\n\n      long pos = -1;\n\n      for (long i = k; i < n; i++) {\n         rem(pivot, M[i][k], p);\n         if (pivot != 0) {\n            InvMod(pivot_inv, pivot, p);\n            pos = i;\n            break;\n         }\n      }\n\n      if (pos != -1) {\n         if (k != pos) {\n            swap(M[pos], M[k]);\n            NegateMod(det, det, p);\n            P[k] = pos;\n            pivoting = true;\n         }\n\n         MulMod(det, det, pivot, p);\n\n         {\n            // multiply row k by pivot_inv\n            ZZ *y = &M[k][0];\n            for (long j = 0; j < n; j++) {\n               rem(t2, y[j], p);\n               MulMod(y[j], t2, pivot_inv, p);\n            }\n            y[k] = pivot_inv;\n         }\n\n\n         NTL_GEXEC_RANGE(seq, n, first, last)  \n         NTL_IMPORT(n)\n         NTL_IMPORT(k)\n\n         ZZ *y = &M[k][0]; \n         ZZ t1, t2;\n\n         for (long i = first; i < last; i++) {\n            if (i == k) continue; // skip row k\n\n            ZZ *x = &M[i][0]; \n            rem(t1, x[k], p);\n            NegateMod(t1, t1, p);\n            x[k] = 0;\n            if (t1 == 0) continue;\n\n            // add t1 * row k to row i\n            for (long j = 0; j < n; j++) {\n               mul(t2, y[j], t1);\n               add(x[j], x[j], t2);\n            }\n         }\n         NTL_GEXEC_RANGE_END\n      }\n      else {\n         clear(d);\n         return;\n      }\n   }\n\n   if (pivoting) {\n      // pivot colums, using reverse swap sequence\n\n      for (long i = 0; i < n; i++) {\n         ZZ *x = &M[i][0]; \n\n         for (long k = n-1; k >= 0; k--) {\n            long pos = P[k];\n            if (pos != k) swap(x[pos], x[k]);\n         }\n      }\n   }\n\n   X.SetDims(n, n);\n   for (long i = 0; i < n; i++)\n      for (long j = 0; j < n; j++)\n         conv(X[i][j], M[i][j]);\n\n   conv(d, det);\n}\n\n\n\n\nlong gauss(mat_ZZ_p& M_in, long w)\n{\n   ZZ t1, t2;\n   ZZ piv;\n\n   long n = M_in.NumRows();\n   long m = M_in.NumCols();\n\n   if (w < 0 || w > m)\n      LogicError(\"gauss: bad args\");\n\n   const ZZ& p = ZZ_p::modulus();\n\n   Vec<ZZVec> M;\n   sqr(t1, p);\n   mul(t1, t1, n);\n\n   M.SetLength(n);\n   for (long i = 0; i < n; i++) {\n      M[i].SetSize(m, t1.size());\n      for (long j = 0; j < m; j++) {\n         M[i][j] = rep(M_in[i][j]);\n      }\n   }\n\n   long l = 0;\n   for (long k = 0; k < w && l < n; k++) {\n\n      long pos = -1;\n      for (long i = l; i < n; i++) {\n         rem(t1, M[i][k], p);\n         M[i][k] = t1;\n         if (pos == -1 && !IsZero(t1)) {\n            pos = i;\n         }\n      }\n\n      if (pos != -1) {\n         swap(M[pos], M[l]);\n\n         InvMod(piv, M[l][k], p);\n         NegateMod(piv, piv, p);\n\n         for (long j = k+1; j < m; j++) {\n            rem(M[l][j], M[l][j], p);\n         }\n\n         bool seq =\n            double(n-(l+1))*double(m-(k+1))*double(p.size())*double(p.size()) < PAR_THRESH;\n\n         NTL_GEXEC_RANGE(seq, n-(l+1), first, last)\n         NTL_IMPORT(m)\n         NTL_IMPORT(k)\n         NTL_IMPORT(l)\n\n         ZZ t1, t2;\n\n\n         for (long ii = first; ii < last; ii++) {\n            long i = ii + l+1;\n\n            // M[i] = M[i] + M[l]*M[i,k]*piv\n\n            MulMod(t1, M[i][k], piv, p);\n\n            clear(M[i][k]);\n\n            ZZ *x = M[i].elts() + (k+1);\n            ZZ *y = M[l].elts() + (k+1);\n\n            for (long j = k+1; j < m; j++, x++, y++) {\n               // *x = *x + (*y)*t1\n\n               mul(t2, *y, t1);\n               add(t2, t2, *x);\n               *x = t2;\n            }\n         }\n\n         NTL_GEXEC_RANGE_END\n\n         l++;\n      }\n   }\n   \n   for (long i = 0; i < n; i++)\n      for (long j = 0; j < m; j++)\n         conv(M_in[i][j], M[i][j]);\n\n   return l;\n}\n\n\n\n\n\n\n\nlong gauss(mat_ZZ_p& M)\n{\n   return gauss(M, M.NumCols());\n}\n\nvoid image(mat_ZZ_p& X, const mat_ZZ_p& A)\n{\n   mat_ZZ_p M;\n   M = A;\n   long r = gauss(M);\n   M.SetDims(r, M.NumCols());\n   X = M;\n}\n\n\n\nvoid kernel(mat_ZZ_p& X, const mat_ZZ_p& A)\n{\n   long m = A.NumRows();\n   long n = A.NumCols();\n\n   const ZZ& p = ZZ_p::modulus();\n\n   mat_ZZ_p M;\n\n   transpose(M, A);\n   long r = gauss(M);\n\n   if (r == 0) {\n      ident(X, m);\n      return;\n   }\n\n   X.SetDims(m-r, m);\n\n   if (m-r == 0 || m == 0) return;\n\n\n   Vec<long> D;\n   D.SetLength(m);\n   for (long j = 0; j < m; j++) D[j] = -1;\n\n   Vec<ZZ_p> inverses;\n   inverses.SetLength(m);\n\n   for (long i = 0, j = -1; i < r; i++) {\n      do {\n         j++;\n      } while (IsZero(M[i][j]));\n\n      D[j] = i;\n      inv(inverses[j], M[i][j]); \n   }\n\n   bool seq = \n      double(m-r)*double(r)*double(r)*double(p.size())*double(p.size()) < PAR_THRESH;\n\n   NTL_GEXEC_RANGE(seq, m-r, first, last)\n   NTL_IMPORT(m)\n   NTL_IMPORT(r)\n\n   ZZ t1, t2;\n   ZZ_p T3;\n\n   for (long k = first; k < last; k++) {\n      vec_ZZ_p& v = X[k];\n      long pos = 0;\n      for (long j = m-1; j >= 0; j--) {\n         if (D[j] == -1) {\n            if (pos == k)\n               set(v[j]);\n            else\n               clear(v[j]);\n            pos++;\n         }\n         else {\n            long i = D[j];\n\n            clear(t1);\n\n            for (long s = j+1; s < m; s++) {\n               mul(t2, rep(v[s]), rep(M[i][s]));\n               add(t1, t1, t2);\n            }\n\n            conv(T3, t1);\n            mul(T3, T3, inverses[j]);\n            negate(v[j], T3); \n         }\n      }\n   }\n\n   NTL_GEXEC_RANGE_END\n}\n\n   \nvoid mul(mat_ZZ_p& X, const mat_ZZ_p& A, const ZZ_p& b_in)\n{\n   NTL_ZZ_pRegister(b);\n   b = b_in;\n   long n = A.NumRows();\n   long m = A.NumCols();\n\n   X.SetDims(n, m);\n\n   long i, j;\n   for (i = 0; i < n; i++)\n      for (j = 0; j < m; j++)\n         mul(X[i][j], A[i][j], b);\n}\n   \nvoid mul(mat_ZZ_p& X, const mat_ZZ_p& A, long b_in)\n{\n   NTL_ZZ_pRegister(b);\n   b = b_in;\n   long n = A.NumRows();\n   long m = A.NumCols();\n\n   X.SetDims(n, m);\n\n   long i, j;\n   for (i = 0; i < n; i++)\n      for (j = 0; j < m; j++)\n         mul(X[i][j], A[i][j], b);\n}\n\nvoid diag(mat_ZZ_p& X, long n, const ZZ_p& d_in)  \n{  \n   ZZ_p d = d_in;\n   X.SetDims(n, n);  \n   long i, j;  \n  \n   for (i = 1; i <= n; i++)  \n      for (j = 1; j <= n; j++)  \n         if (i == j)  \n            X(i, j) = d;  \n         else  \n            clear(X(i, j));  \n} \n\nlong IsDiag(const mat_ZZ_p& A, long n, const ZZ_p& d)\n{\n   if (A.NumRows() != n || A.NumCols() != n)\n      return 0;\n\n   long i, j;\n\n   for (i = 1; i <= n; i++)\n      for (j = 1; j <= n; j++)\n         if (i != j) {\n            if (!IsZero(A(i, j))) return 0;\n         }\n         else {\n            if (A(i, j) != d) return 0;\n         }\n\n   return 1;\n}\n\n\nlong IsZero(const mat_ZZ_p& a)\n{\n   long n = a.NumRows();\n   long i;\n\n   for (i = 0; i < n; i++)\n      if (!IsZero(a[i]))\n         return 0;\n\n   return 1;\n}\n\nvoid clear(mat_ZZ_p& x)\n{\n   long n = x.NumRows();\n   long i;\n   for (i = 0; i < n; i++)\n      clear(x[i]);\n}\n\n\nmat_ZZ_p operator+(const mat_ZZ_p& a, const mat_ZZ_p& b)\n{\n   mat_ZZ_p res;\n   add(res, a, b);\n   NTL_OPT_RETURN(mat_ZZ_p, res);\n}\n\nmat_ZZ_p operator*(const mat_ZZ_p& a, const mat_ZZ_p& b)\n{\n   mat_ZZ_p res;\n   mul(res, a, b);\n   NTL_OPT_RETURN(mat_ZZ_p, res);\n}\n\nmat_ZZ_p operator-(const mat_ZZ_p& a, const mat_ZZ_p& b)\n{\n   mat_ZZ_p res;\n   sub(res, a, b);\n   NTL_OPT_RETURN(mat_ZZ_p, res);\n}\n\n\nmat_ZZ_p operator-(const mat_ZZ_p& a)\n{\n   mat_ZZ_p res;\n   negate(res, a);\n   NTL_OPT_RETURN(mat_ZZ_p, res);\n}\n\n\nvec_ZZ_p operator*(const mat_ZZ_p& a, const vec_ZZ_p& b)\n{\n   vec_ZZ_p res;\n   mul_aux(res, a, b);\n   NTL_OPT_RETURN(vec_ZZ_p, res);\n}\n\nvec_ZZ_p operator*(const vec_ZZ_p& a, const mat_ZZ_p& b)\n{\n   vec_ZZ_p res;\n   mul_aux(res, a, b);\n   NTL_OPT_RETURN(vec_ZZ_p, res);\n}\n\nvoid inv(mat_ZZ_p& X, const mat_ZZ_p& A)\n{\n   ZZ_p d;\n   inv(d, X, A);\n   if (d == 0) ArithmeticError(\"inv: non-invertible matrix\");\n}\n\nvoid power(mat_ZZ_p& X, const mat_ZZ_p& A, const ZZ& e)\n{\n   if (A.NumRows() != A.NumCols()) LogicError(\"power: non-square matrix\");\n\n   if (e == 0) {\n      ident(X, A.NumRows());\n      return;\n   }\n\n   mat_ZZ_p T1, T2;\n   long i, k;\n\n   k = NumBits(e);\n   T1 = A;\n\n   for (i = k-2; i >= 0; i--) {\n      sqr(T2, T1);\n      if (bit(e, i))\n         mul(T1, T2, A);\n      else\n         T1 = T2;\n   }\n\n   if (e < 0)\n      inv(X, T1);\n   else\n      X = T1;\n}\n\nvoid random(mat_ZZ_p& x, long n, long m)\n{\n   x.SetDims(n, m);\n   for (long i = 0; i < n; i++) random(x[i], m);\n}\n\nNTL_END_IMPL\n", "meta": {"hexsha": "c9be3064ac283ac4718ee5d937e6e6f978a1b487", "size": 30644, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "android/jni/ntl/src/mat_ZZ_p.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/mat_ZZ_p.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/mat_ZZ_p.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": 20.4157228514, "max_line_length": 93, "alphanum_fraction": 0.481954053, "num_tokens": 10399, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6297746213017459, "lm_q2_score": 0.5389832206876841, "lm_q1q2_score": 0.3394379536965816}}
{"text": "/* ----------------------------------------------------------------------- *//**\n *\n * @file metric.cpp\n *\n * @brief Metric operations\n *\n *//* ----------------------------------------------------------------------- */\n\n#include <dbconnector/dbconnector.hpp>\n#include <limits>\n#include <string>\n#include <vector>\n#include <set>\n#include <algorithm>\n#include <sstream>\n#include <cmath>\n#include <boost/algorithm/string.hpp>\n\n#include \"metric.hpp\"\n\nusing std::string;\n\nnamespace madlib {\n\nusing namespace dbconnector::postgres;\n\nnamespace modules {\n\nnamespace linalg {\n\nnamespace {\n\ntemplate <class TupleType>\nstruct ReverseLexicographicComparator {\n    /**\n     * @brief Return true if the first argument is less than the second\n     */\n    bool operator()(const TupleType& inTuple1, const TupleType& inTuple2) {\n        // This could be a real reverse lexicographic comparator in C++11, but\n        // lacking variadic template arguments, we simply pretend here that\n        // all tuples contain only 2 elements.\n        return std::get<1>(inTuple1) < std::get<1>(inTuple2) ||\n            (std::get<1>(inTuple1) == std::get<1>(inTuple2) &&\n                std::get<0>(inTuple1) < std::get<0>(inTuple2));\n    }\n};\n\n} // anonymous namespace\n\n/**\n * @brief Compute the k columns of a matrix that are closest to a vector\n *\n * @tparam DistanceFunction Type of the distance function. This can be a\n *     function pointer, or a class with method <tt>operator()</tt> (like\n *     \\c FunctionHandle)\n * @tparam NumClosestColumns The number of closest columns to compute. We assume\n *     that \\c outIndicesAndDistances is of size \\c NumClosestColumns.\n *\n * @param inMatrix Matrix \\f$ M \\f$\n * @param inVector Vector \\f$ \\vec x \\f$\n * @param[out] outClosestColumns A list of \\c NumClosestColumns pairs\n *     \\f$ (i, d) \\f$ sorted in ascending order of \\f$ d \\f$, where $i$ is a\n *     0-based column index in \\f$ M \\f$ and\n *     \\f$ d \\f$ is the distance (using \\c inMetric) between \\f$ M_i \\f$ and\n *     \\f$ x \\f$.\n */\ntemplate <class DistanceFunction, class RandomAccessIterator>\nvoid\nclosestColumnsAndDistances(\n    const MappedMatrix& inMatrix,\n    const MappedColumnVector& inVector,\n    DistanceFunction& inMetric,\n    RandomAccessIterator ioFirst,\n    RandomAccessIterator ioLast)\n{\n\n    ReverseLexicographicComparator<\n        typename std::iterator_traits<RandomAccessIterator>::value_type>\n            comparator;\n\n    std::fill(ioFirst, ioLast,\n        std::make_tuple(0, std::numeric_limits<double>::infinity()));\n    for (Index i = 0; i < inMatrix.cols(); ++i) {\n        double currentDist;\n        currentDist\n            = AnyType_cast<double>(\n                    inMetric(MappedColumnVector(inMatrix.col(i)), inVector)\n                    );\n\n        // outIndicesAndDistances is a heap, so the first element is maximal\n        if (currentDist < std::get<1>(*ioFirst)) {\n            // Unfortunately, the STL does not have a decrease-key function,\n            // so we are wasting a bit of performance here\n            std::pop_heap(ioFirst, ioLast, comparator);\n            *(ioLast - 1) = std::make_tuple(i, currentDist);\n            std::push_heap(ioFirst, ioLast, comparator);\n        }\n    }\n    std::sort_heap(ioFirst, ioLast, comparator);\n}\n\n\ntemplate <class RandomAccessIterator>\nvoid\nclosestColumnsAndDistancesUDF(\n    const MappedMatrix& inMatrix,\n    const MappedColumnVector& inVector,\n    RandomAccessIterator ioFirst,\n    RandomAccessIterator ioLast,\n    Oid oid)\n{\n\n    ReverseLexicographicComparator<\n        typename std::iterator_traits<RandomAccessIterator>::value_type>\n            comparator;\n\n    std::fill(ioFirst, ioLast,\n        std::make_tuple(0, std::numeric_limits<double>::infinity()));\n    for (Index i = 0; i < inMatrix.cols(); ++i) {\n        double currentDist;\n        currentDist = static_cast<double>(DatumGetFloat8(OidFunctionCall2(\n                        oid,\n                        PointerGetDatum(VectorToNativeArray(inMatrix.col(i))),\n                        PointerGetDatum(VectorToNativeArray(inVector))\n                        )));\n\n        // outIndicesAndDistances is a heap, so the first element is maximal\n        if (currentDist < std::get<1>(*ioFirst)) {\n            // Unfortunately, the STL does not have a decrease-key function,\n            // so we are wasting a bit of performance here\n            std::pop_heap(ioFirst, ioLast, comparator);\n            *(ioLast - 1) = std::make_tuple(i, currentDist);\n            std::push_heap(ioFirst, ioLast, comparator);\n        }\n    }\n    std::sort_heap(ioFirst, ioLast, comparator);\n}\n\ndouble\ndistPNorm(const MappedColumnVector& inX, const MappedColumnVector& inY, double p) {\n    if (inX.size() != inY.size()) {\n        throw std::runtime_error(\"Found input arrays of \"\n                \"different lengths unexpectedly.\");\n    }\n    if (p <= 0 || std::isnan(p)) {\n        throw std::runtime_error(\"Expect input p to be positive.\");\n    }\n\n    if (!std::isfinite(p)) {\n        return (inX - inY).lpNorm<Eigen::Infinity>();\n    } else {\n        double res = 0.0;\n        for (int i = 0; i < inX.size(); i++) {\n            res += std::pow(std::abs(inX(i) - inY(i)), p);\n        }\n        return std::pow(res, 1./p);\n    }\n}\n\ndouble\ndistNorm1(const MappedColumnVector& inX, const MappedColumnVector& inY) {\n    if (inX.size() != inY.size()) {\n        throw std::runtime_error(\"Found input arrays of \"\n                \"different lengths unexpectedly.\");\n    }\n\n    return (inX - inY).lpNorm<1>();\n}\n\ndouble\ndistNorm2(const MappedColumnVector& inX, const MappedColumnVector& inY) {\n    if (inX.size() != inY.size()) {\n        throw std::runtime_error(\"Found input arrays of \"\n                \"different lengths unexpectedly.\");\n    }\n\n    return (inX - inY).norm();\n}\n\ndouble\ncosineSimilarity(const MappedColumnVector& inX, const MappedColumnVector& inY) {\n    if (inX.size() != inY.size()) {\n        throw std::runtime_error(\"Found input arrays of \"\n                \"different lengths unexpectedly.\");\n    }\n\n\tdouble xnorm = inX.norm(), ynorm = inY.norm();\n\tif (xnorm < std::numeric_limits<double>::denorm_min()\n\t\t|| ynorm < std::numeric_limits<double>::denorm_min()) {\n        return -1;\n    }\n\n    return inX.dot(inY) / (xnorm * ynorm);\n}\n\ndouble\nsquaredDistNorm2(const MappedColumnVector& inX, const MappedColumnVector& inY) {\n    if (inX.size() != inY.size()) {\n        throw std::runtime_error(\"Found input arrays of \"\n                \"different lengths unexpectedly.\");\n    }\n\n    return (inX - inY).squaredNorm();\n}\n\ndouble\ndistAngle(const MappedColumnVector& inX, const MappedColumnVector& inY) {\n    if (inX.size() != inY.size()) {\n        throw std::runtime_error(\"Found input arrays of \"\n                \"different lengths unexpectedly.\");\n    }\n\n\t// Deal with the undefined case where one of the norm is zero\n\t// Angle is not defined. Just return \\pi.\n\tdouble xnorm = inX.norm(), ynorm = inY.norm();\n\tif (xnorm < std::numeric_limits<double>::denorm_min()\n\t\t|| ynorm < std::numeric_limits<double>::denorm_min())\n\t\treturn std::acos(-1);\n\n    double cosine = dot(inX, inY) / (xnorm * ynorm);\n    if (cosine > 1)\n        cosine = 1;\n    else if (cosine < -1)\n        cosine = -1;\n    return std::acos(cosine);\n}\n\ndouble\ndistTanimoto(const MappedColumnVector& inX, const MappedColumnVector& inY) {\n    if (inX.size() != inY.size()) {\n        throw std::runtime_error(\"Found input arrays of \"\n                \"different lengths unexpectedly.\");\n    }\n\n    // Note that this is not a metric in general!\n    double dotProduct = dot(inX, inY);\n    double tanimoto = inX.squaredNorm() + inY.squaredNorm();\n    return (tanimoto - 2 * dotProduct) / (tanimoto - dotProduct);\n}\n\ndouble\ndistJaccard(const ArrayHandle<text*>& inX, const ArrayHandle<text*>& inY) {\n    if (inX.size() == 0 && inY.size() == 0)\n        return 0.0;  // both empty are treated as zero distance\n    if (inX.size() == 0 || inY.size() == 0)\n        return 1.0;   // one of the sets being empty is treated as max distance\n\n    std::set<string> x_set;\n    for (size_t i = 0; i < inX.size(); i++){\n        x_set.insert(std::string(VARDATA_ANY(inX[i]),\n                                 VARSIZE_ANY(inX[i]) - VARHDRSZ));\n    }\n\n    size_t n_intersection = 0;\n    size_t n_union = x_set.size();\n    std::set<string> y_set;\n    for (size_t i = 0; i < inY.size(); i++){\n        string y_elem = std::string(VARDATA_ANY(inY[i]),\n                                    VARSIZE_ANY(inY[i]) - VARHDRSZ);\n        if (y_set.count(y_elem) == 0){\n            // for sets, count returns 1 if an element with that value\n            // exists in the container, and zero otherwise.\n\n            if (x_set.count(y_elem) == 1){\n                // element present in both sets (already counted for union)\n                n_intersection++;\n            }\n            else{\n                // element only in inY, not yet counted for union\n                n_union++;\n            }\n        }\n        y_set.insert(y_elem);\n    }\n    return 1.0 - static_cast<double>(n_intersection) / static_cast<double>(n_union);\n}\n\n/**\n * @brief Compute the k columns of a matrix that are closest to a vector\n *\n * For performance, we cheat here: For the following four distance functions, we\n * take a special shortcut.\n * FIXME: FunctionHandle should be tuned so that this shortcut no longer\n * impacts performance by more than, say, ~10%.\n */\n\nstd::string dist_fn_name(string s)\n{\n    std::istringstream ss(s);\n    std::string token, fname;\n    if (std::getline(ss, token, '.')) fname = token; // suppose there is no schema name\n    if (std::getline(ss, token, '.')) fname = token; // previous part is schema name\n    return fname;\n}\n\n\ntemplate <class RandomAccessIterator>\ninline\nvoid\nclosestColumnsAndDistancesShortcut(\n    const MappedMatrix& inMatrix,\n    const MappedColumnVector& inVector,\n    FunctionHandle &inDist,\n    std::string fname,\n    RandomAccessIterator ioFirst,\n    RandomAccessIterator ioLast) {\n\n    // Sorted in the order of expected use\n    if (fname.compare(\"squared_dist_norm2\") == 0)\n        closestColumnsAndDistances(inMatrix, inVector, squaredDistNorm2,\n            ioFirst, ioLast);\n    else if (fname.compare(\"dist_norm2\") == 0)\n        closestColumnsAndDistances(inMatrix, inVector, distNorm2,\n            ioFirst, ioLast);\n    else if (fname.compare(\"dist_norm1\") == 0)\n        closestColumnsAndDistances(inMatrix, inVector, distNorm1,\n            ioFirst, ioLast);\n    else if (fname.compare(\"dist_angle\") == 0)\n        closestColumnsAndDistances(inMatrix, inVector, distAngle,\n            ioFirst, ioLast);\n    else if (fname.compare(\"dist_tanimoto\") == 0) {\n        closestColumnsAndDistances(inMatrix, inVector, distTanimoto,\n            ioFirst, ioLast);\n    } else {\n        closestColumnsAndDistancesUDF(inMatrix, inVector, ioFirst,\n                ioLast, inDist.funcID());\n    }\n}\n\n\n/**\n * @brief Compute the minimum distance between a vector and any column of a\n *     matrix\n *\n * This function calls a user-supplied function, for which it does not do\n * garbage collection. It is therefore meant to be called only constantly many\n * times before control is returned to the backend.\n */\nAnyType\nclosest_column::run(AnyType& args) {\n    //if (true) throw std::runtime_error(\"Begin cc run\\n\");\n    try{\n        MappedMatrix M = args[0].getAs<MappedMatrix>();\n        MappedColumnVector x = args[1].getAs<MappedColumnVector>();\n        FunctionHandle dist = args[2].getAs<FunctionHandle>()\n            .unsetFunctionCallOptions(FunctionHandle::GarbageCollectionAfterCall);\n        string dist_fname = args[3].getAs<char *>();\n        std::string fname = dist_fn_name(dist_fname);\n        std::tuple<Index, double> result;\n        closestColumnsAndDistancesShortcut(M, x, dist, fname, &result, &result + 1);\n\n        AnyType tuple;\n        return tuple\n            << static_cast<int32_t>(std::get<0>(result))\n            << std::get<1>(result);\n    }catch (const ArrayWithNullException &e) {\n        return Null();\n    }\n}\n\nAnyType\nclosest_column_hawq::run(AnyType& args) {\n    MappedMatrix M = args[0].getAs<MappedMatrix>();\n    MappedColumnVector x = args[1].getAs<MappedColumnVector>();\n    string distance_metric_str = args[2].getAs<char *>();\n    boost::trim(distance_metric_str);\n\n    double (*distance_metric)(const MappedColumnVector&, const MappedColumnVector&);\n\n    // we hard-code comparision and selection of the distance function since\n    // we are currently limited in not being able to access the catalog\n    // in a function executed at the segments. This is a limitation in HAWQ\n    // and will probably be eliminated in a future HAWQ release\n    if ((distance_metric_str.compare(\"squared_dist_norm2\") == 0) ||\n            (distance_metric_str.compare(\"madlib.squared_dist_norm2\") == 0)){\n        distance_metric = squaredDistNorm2;\n    } else if ((distance_metric_str.compare(\"dist_norm2\") == 0) ||\n            (distance_metric_str.compare(\"madlib.dist_norm2\") == 0)){\n        distance_metric = distNorm2;\n    } else if ((distance_metric_str.compare(\"dist_norm1\") == 0) ||\n            (distance_metric_str.compare(\"madlib.dist_norm1\") == 0)){\n        distance_metric = distNorm1;\n    } else if ((distance_metric_str.compare(\"dist_angle\") == 0) ||\n            (distance_metric_str.compare(\"madlib.dist_angle\") == 0)){\n        distance_metric = distAngle;\n    } else if ((distance_metric_str.compare(\"dist_tanimoto\") == 0) ||\n            (distance_metric_str.compare(\"madlib.dist_tanimoto\") == 0)){\n        distance_metric = distTanimoto;\n    } else{\n        string errorMessage = string(\"Invalid distance metric provided: \") + \\\n                                distance_metric_str + \\\n                                string(\". Currently only madlib provided distance functions are supported.\");\n        throw std::invalid_argument(errorMessage);\n    }\n\n    std::tuple<Index, double> result;\n    closestColumnsAndDistances(M, x, distance_metric, &result, &result + 1);\n\n    AnyType tuple;\n    return tuple\n        << static_cast<int32_t>(std::get<0>(result))\n        << std::get<1>(result);\n}\n\n/**\n * @brief Compute the minimum distance between a vector and any column of a\n *     matrix\n *\n * This function calls a user-supplied function, for which it does not do\n * garbage collection. It is therefore meant to be called only constantly many\n * times before control is returned to the backend.\n */\nAnyType\nclosest_columns::run(AnyType& args) {\n    MappedMatrix M = args[0].getAs<MappedMatrix>();\n    MappedColumnVector x = args[1].getAs<MappedColumnVector>();\n    uint32_t num = args[2].getAs<uint32_t>();\n    FunctionHandle dist = args[3].getAs<FunctionHandle>()\n        .unsetFunctionCallOptions(FunctionHandle::GarbageCollectionAfterCall);\n    string dist_fname = args[4].getAs<char *>();\n\n    std::string fname = dist_fn_name(dist_fname);\n\n    std::vector<std::tuple<Index, double> > result(num);\n    closestColumnsAndDistancesShortcut(M, x, dist, fname, result.begin(),\n        result.end());\n\n    MutableArrayHandle<int32_t> indices = allocateArray<int32_t,\n        dbal::FunctionContext, dbal::DoNotZero, dbal::ThrowBadAlloc>(num);\n    MutableArrayHandle<double> distances = allocateArray<double,\n        dbal::FunctionContext, dbal::DoNotZero, dbal::ThrowBadAlloc>(num);\n    for (uint32_t i = 0; i < num; ++i)\n        std::tie(indices[i], distances[i]) = result[i];\n\n    AnyType tuple;\n    return tuple << indices << distances;\n}\n\nAnyType\nclosest_columns_hawq::run(AnyType& args) {\n    MappedMatrix M = args[0].getAs<MappedMatrix>();\n    MappedColumnVector x = args[1].getAs<MappedColumnVector>();\n    uint32_t num = args[2].getAs<uint32_t>();\n    string distance_metric_str = args[3].getAs<char *>();\n    boost::trim(distance_metric_str);\n\n    if (0 == num) {\n        throw std::invalid_argument(\"the parameter number should be a positive integer\");\n    }\n\n    double (*distance_metric)(const MappedColumnVector&, const MappedColumnVector&);\n\n    if ((distance_metric_str.compare(\"squared_dist_norm2\") == 0) ||\n            (distance_metric_str.compare(\"madlib.squared_dist_norm2\") == 0)){\n        distance_metric = squaredDistNorm2;\n    } else if ((distance_metric_str.compare(\"dist_norm2\") == 0) ||\n            (distance_metric_str.compare(\"madlib.dist_norm2\") == 0)){\n        distance_metric = distNorm2;\n    } else if ((distance_metric_str.compare(\"dist_norm1\") == 0) ||\n            (distance_metric_str.compare(\"madlib.dist_norm1\") == 0)){\n        distance_metric = distNorm1;\n    } else if ((distance_metric_str.compare(\"dist_angle\") == 0) ||\n            (distance_metric_str.compare(\"madlib.dist_angle\") == 0)){\n        distance_metric = distAngle;\n    } else if ((distance_metric_str.compare(\"dist_tanimoto\") == 0) ||\n            (distance_metric_str.compare(\"madlib.dist_tanimoto\") == 0)){\n        distance_metric = distTanimoto;\n    } else{\n        string errorMessage = string(\"Invalid distance metric provided: \") + \\\n                                distance_metric_str + \\\n                                string(\". Currently only madlib provided distance functions are supported.\");\n        throw std::invalid_argument(errorMessage);\n    }\n\n    std::vector<std::tuple<Index, double> > result(num);\n    closestColumnsAndDistances(M, x, distance_metric, result.begin(), result.end());\n\n    MutableArrayHandle<int32_t> indices = allocateArray<int32_t,\n        dbal::FunctionContext, dbal::DoNotZero, dbal::ThrowBadAlloc>(num);\n    MutableArrayHandle<double> distances = allocateArray<double,\n        dbal::FunctionContext, dbal::DoNotZero, dbal::ThrowBadAlloc>(num);\n    for (uint32_t i = 0; i < num; ++i)\n        std::tie(indices[i], distances[i]) = result[i];\n\n    AnyType tuple;\n    return tuple << indices << distances;\n}\n\nAnyType\nnorm1::run(AnyType& args) {\n    return static_cast<double>(args[0].getAs<MappedColumnVector>().lpNorm<1>());\n}\n\nAnyType\nnorm2::run(AnyType& args) {\n    return static_cast<double>(args[0].getAs<MappedColumnVector>().norm());\n}\n\nAnyType\ndist_inf_norm::run(AnyType& args) {\n    return distPNorm(\n        args[0].getAs<MappedColumnVector>(),\n        args[1].getAs<MappedColumnVector>(),\n        std::numeric_limits<double>::infinity()\n    );\n}\n\nAnyType\ndist_pnorm::run(AnyType& args) {\n    return distPNorm(\n        args[0].getAs<MappedColumnVector>(),\n        args[1].getAs<MappedColumnVector>(),\n        args[2].getAs<double>()\n    );\n}\n\nAnyType\ndist_norm1::run(AnyType& args) {\n    return distNorm1(\n        args[0].getAs<MappedColumnVector>(),\n        args[1].getAs<MappedColumnVector>()\n    );\n}\n\nAnyType\ndist_norm2::run(AnyType& args) {\n    // FIXME: it would be nice to declare this as a template function (so it\n    // works for dense and sparse vectors), and the C++ AL takes care of the\n    // rest...\n    return distNorm2(\n        args[0].getAs<MappedColumnVector>(),\n        args[1].getAs<MappedColumnVector>()\n    );\n}\n\nAnyType\ncosine_similarity::run(AnyType& args) {\n    return cosineSimilarity(\n        args[0].getAs<MappedColumnVector>(),\n        args[1].getAs<MappedColumnVector>()\n    );\n}\n\nAnyType\nsquared_dist_norm2::run(AnyType& args) {\n    return squaredDistNorm2(\n        args[0].getAs<MappedColumnVector>(),\n        args[1].getAs<MappedColumnVector>()\n    );\n}\n\nAnyType\ndist_angle::run(AnyType& args) {\n    return distAngle(\n        args[0].getAs<MappedColumnVector>(),\n        args[1].getAs<MappedColumnVector>()\n    );\n}\n\nAnyType\ndist_tanimoto::run(AnyType& args) {\n    return distTanimoto(\n        args[0].getAs<MappedColumnVector>(),\n        args[1].getAs<MappedColumnVector>()\n    );\n}\n\nAnyType\ndist_jaccard::run(AnyType& args) {\n    return distJaccard(\n        args[0].getAs<ArrayHandle<text*> >(),\n        args[1].getAs<ArrayHandle<text*> >()\n    );\n}\n\n} // namespace linalg\n\n} // namespace modules\n\n} // namespace regress\n", "meta": {"hexsha": "bfac611ef314ab17b3f6b70133bce69196a624a2", "size": 19798, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/modules/linalg/metric.cpp", "max_stars_repo_name": "madlib/archived_madlib", "max_stars_repo_head_hexsha": "5b964cb50c562f8f8fd4bc47556cd2bbb49d27e4", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2018-09-18T07:44:22.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-14T19:45:18.000Z", "max_issues_repo_path": "src/modules/linalg/metric.cpp", "max_issues_repo_name": "madlib/archived_madlib", "max_issues_repo_head_hexsha": "5b964cb50c562f8f8fd4bc47556cd2bbb49d27e4", "max_issues_repo_licenses": ["Apache-2.0"], "max_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/linalg/metric.cpp", "max_forks_repo_name": "madlib/archived_madlib", "max_forks_repo_head_hexsha": "5b964cb50c562f8f8fd4bc47556cd2bbb49d27e4", "max_forks_repo_licenses": ["Apache-2.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.0757314974, "max_line_length": 109, "alphanum_fraction": 0.6353672088, "num_tokens": 4982, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6297746074044134, "lm_q2_score": 0.5389832206876841, "lm_q1q2_score": 0.3394379462061526}}
{"text": "#include \"panoramic_stitching.h\"\n\n#include <unordered_map>\n#include <algorithm>\n#include <iostream>\n#include <stdlib.h>\n#include <cmath>\n#include <unordered_set>\n#include <unsupported/Eigen/NonLinearOptimization>\n#include <Eigen/src/Core/util/DisableStupidWarnings.h>\n\nnamespace panSti {\npanoramicStitching::panoramicStitching(int base, const std::vector<std::string>& name,\n                                       std::vector<std::pair<int, int>>& image_pairs, featureMethod method): m_image_pairs(image_pairs),\n    m_base_index(base)\t{\n    for(int i = 0; i < name.size(); i++) {\n        m_images.push_back(cv::imread(name[i]));\n        if (!m_images.back().data) {\n            std::cout << \"cannot read image\" << std::endl;\n            return;\n        }\n        cv::Mat gray_image;\n        cv::cvtColor(m_images.back(), gray_image, CV_RGB2GRAY);\n        m_gray_images.push_back(gray_image);\n    }\n    if (method == featureMethod::SIFT) {\n        bool result = siftMatchExtract();\n        if (!result) {\n            std::cout << \"sift extract fails\" << std::endl;\n\t\t\treturn;\n        }\n    } else {\n\t\tstd::cout << \"At present only SIFT provided\" << std::endl;\n\t}\n}\ncv::Mat panoramicStitching::stitch_image() {\n    calculateHomography();\n    //-- step 1: calculate all the homography with the base\n    std::unordered_map<int, int> hash_map; // record the\n    int pair_index = 0;\n    std::vector<std::pair<std::pair<int, int>, int>> unsolved_pairs;\n    for (std::pair<int, int>& image_pair : m_image_pairs) {\n        if (image_pair.first == m_base_index) {\n            if (hash_map.find(image_pair.second) != hash_map.end()) {\n                pair_index++;\n                continue;\n            }\n            hash_map.insert({image_pair.second, pair_index});\n            pair_index++;\n        } else if (image_pair.second == m_base_index) {\n            if (hash_map.find(image_pair.first) != hash_map.end()) {\n                pair_index++;\n                continue;\n            }\n            hash_map.insert({image_pair.first, pair_index});\n            // invert the homography\n            m_homographies[pair_index] = m_homographies[pair_index].inv();\n            image_pair.second = image_pair.first;\n            image_pair.first = m_base_index;\n            pair_index++;\n        } else {\n            if (hash_map.find(image_pair.first) != hash_map.end()) {\n                if (hash_map.find(image_pair.second) != hash_map.end()) {\n                    pair_index++;\n                    continue;\n                }\n                m_homographies[pair_index] = m_homographies[hash_map.at(image_pair.first)] * \n\t\t\t\t\tm_homographies[pair_index];\n                //image_pair.second = image_pair.first;\n                image_pair.first = m_base_index;\n                hash_map.insert({image_pair.second, pair_index});\n                pair_index++;\n            } else if (hash_map.find(image_pair.second) != hash_map.end()) {\n                if (hash_map.find(image_pair.first) != hash_map.end()) {\n                    pair_index++;\n                    continue;\n                }\n                m_homographies[pair_index] = m_homographies[hash_map.at(image_pair.second)] * \n\t\t\t\t\tm_homographies[pair_index].inv();\n\t\t\t\timage_pair.second = image_pair.first;\n                image_pair.first = m_base_index;\n                hash_map.insert({image_pair.second, pair_index});\n                pair_index++;\n            } else {\n                // two images are all not in the\n                unsolved_pairs.push_back({image_pair, pair_index});\n                pair_index++;\n            }\n        }\n    }\n    int max_iter = 3;\n    while (!unsolved_pairs.empty() && max_iter >= 0) {\n        for (auto i = unsolved_pairs.begin(); i != unsolved_pairs.end();) {\n            if (hash_map.find(i->first.first) != hash_map.end() ||\n                    hash_map.find(i->first.second) != hash_map.end()) {\n                if (hash_map.find(i->first.first) != hash_map.end() &&\n                        hash_map.find(i->first.second) == hash_map.end()) {\n                    m_homographies[i->second] = m_homographies[i->second] *\n                                                m_homographies[hash_map.at(i->first.first)];\n                    hash_map.insert({i->first.second, i->second});\n                } else if (hash_map.find(i->first.first) == hash_map.end() &&\n                           hash_map.find(i->first.second) != hash_map.end()) {\n                    m_homographies[i->second] = m_homographies[i->second].inv() *\n                                                m_homographies[hash_map.at(i->first.second)];\n                    hash_map.insert({i->first.first, i->second});\n                }\n                unsolved_pairs.erase(i++); // erase this element and let i plus one\n            } else {\n                i++;\n            }\n        }\n        max_iter--;\n    }\n    if (max_iter < 0) {\n        std::cout << \"there is no enough link between images\" << std::endl;\n        cv::Mat tmp;\n        return tmp;\n    }\n    //-- step 2: calculate four edge points of the source image to find the size of the image\n    // first of all, calculate the size of the big image\n    int left_most = 0;\n    int right_most = m_gray_images[m_base_index].cols - 1;\n    int down_most = m_gray_images[m_base_index].rows - 1;\n    int up_most = 0;\n    // the interval of every_image before adding the left_most and up_most\n    std::unordered_map<int, std::pair<int, int>> x_interval;\n    std::unordered_map<int, std::pair<int, int>> y_interval;\n    x_interval.insert({m_base_index, {left_most, right_most}});\n    y_interval.insert({m_base_index, {up_most, down_most}});\n    for (auto i = hash_map.begin(); i != hash_map.end(); i++) {\n        int image_index = i->first;\n        int homo_index = i->second;\n        m_homographies[homo_index] = m_homographies[homo_index] /\n                                     m_homographies[homo_index].at<double>(2, 2);\n        int x[4] = {0, 0,\n                    m_gray_images[image_index].cols - 1, m_gray_images[image_index]. cols - 1\n                   };\n        int y[4] = {0, m_gray_images[image_index].rows - 1,\n                    0, m_gray_images[image_index]. rows - 1\n                   };\n        int this_left = INT_MAX;\n        int this_right = INT_MIN;\n        int this_up = INT_MAX;\n        int this_down = INT_MIN;\n        for (int j = 0; j < 4; j++) {\n            cv::Mat coor = m_homographies[homo_index].col(0) * x[j] +\n                           m_homographies[homo_index].col(1) * y[j] +\n                           m_homographies[homo_index].col(2);\n            double x = coor.at<double>(0, 0) / coor.at<double>(2, 0);\n            double y = coor.at<double>(1, 0) / coor.at<double>(2, 0);\n            left_most = std::min(left_most, int(std::floor(x)));\n            right_most = std::max(right_most, int(std::ceil(x)));\n            up_most = std::min(up_most, int(std::floor(y)));\n            down_most = std::max(down_most, int(std::ceil(y)));\n            this_left = std::min(this_left, int(std::floor(x)));\n            this_right = std::max(this_right, int(std::ceil(x)));\n            this_up = std::min(this_up, int(std::floor(y)));\n            this_down = std::max(this_down, int(std::ceil(y)));\n        }\n        x_interval.insert({image_index, {this_left, this_right}});\n        y_interval.insert({image_index, {this_up, this_down}});\n    }\n    // all images should be translated with (fabs(left_most), fabs(up_most))\n    // and then get the warped_images\n    cv::Mat base_homo = (cv::Mat_<double>(3, 3) <<\n                         1, 0, std::abs(left_most),\n                         0, 1, std::abs(up_most),\n                         0, 0, 1);\n    std::vector<cv::Mat> warped_images;\n    int new_width = right_most - left_most + 1;\n    int new_height = down_most - up_most + 1;\n    for (int i = 0; i < m_gray_images.size(); i++) {\n        if (i != m_base_index) {\n            int homo_index = hash_map.at(i);\n            m_homographies[homo_index] = base_homo * m_homographies[homo_index];\n            cv::Mat warped_image;\n            cv::warpPerspective(m_images[i], warped_image,\n                                m_homographies[homo_index], cv::Size2i(new_width, new_height));\n            warped_images.push_back(warped_image);\n        } else {\n            cv::Mat warped_image;\n            cv::warpPerspective(m_images[m_base_index], warped_image,\n                                base_homo, cv::Size2i(new_width, new_height));\n            warped_images.push_back(warped_image);\n        }\n    }\n    // secondly, combine the corresponding warpped image\n    // for every pixel, set the pixel-value of image whose center is nearest the the pixel\n    // calculate every center coordinate first of all\n    std::unordered_map<int, std::pair<int, int>> center_coor; // the coordinate is (y, x)\n    center_coor.insert({ m_base_index, {m_gray_images[m_base_index].rows / 2 + std::abs(up_most),\n                                        m_gray_images[m_base_index].cols / 2 + std::abs(left_most)\n                                       }\n                       });\n    for (int i = 0; i < m_images.size(); i++) {\n        if (i == m_base_index)\n            continue;\n        cv::Mat tmp_H = m_homographies[hash_map.at(i)];\n        int mid_col = m_gray_images[i].cols >> 1;\n        int mid_row = m_gray_images[i].rows >> 1;\n        int mid_x = tmp_H.at<double>(0, 0) * mid_col + tmp_H.at<double>(0, 1) * mid_row + tmp_H.at<double>(0, 2);\n        int mid_y = tmp_H.at<double>(1, 0) * mid_col + tmp_H.at<double>(1, 1) * mid_row + tmp_H.at<double>(1, 2);\n        double ww = tmp_H.at<double>(2, 0) * mid_col + tmp_H.at<double>(2, 1) * mid_row + tmp_H.at<double>(2, 2);\n        mid_x /= ww;\n        mid_y /= ww;\n        center_coor.insert({ i, {mid_y, mid_x} });\n    }\n    // set pixel value for new image\n    cv::Mat result = warped_images[m_base_index];\n    for (int i = 0; i < new_height; i++) {\n        for (int j = 0; j < new_width; j++) {\n            int nearest_value[3] = { -1, -1, -1 };\n            int nearest_dst = INT_MAX;\n            for (int k = 0; k < m_images.size(); k++) {\n                if (j < x_interval.at(k).second + std::abs(left_most) && j > x_interval.at(k).first + std::abs(left_most) &&\n                        i < y_interval.at(k).second + std::abs(up_most)&& i > y_interval.at(k).first + std::abs(up_most)) {\n                    if (warped_images[k].at<cv::Vec3b>(i, j)[0] == 0 &&\n                            warped_images[k].at<cv::Vec3b>(i, j)[1] == 0 &&\n                            warped_images[k].at<cv::Vec3b>(i, j)[2] == 0)\n                        continue;\n                    else {\n                        int dist = std::fabs(i - center_coor.at(k).first) + std::fabs(j - center_coor.at(k).second);\n                        if (dist < nearest_dst) {\n                            nearest_dst = dist;\n                            nearest_value[0] = warped_images[k].at<cv::Vec3b>(i, j)[0];\n                            nearest_value[1] = warped_images[k].at<cv::Vec3b>(i, j)[1];\n                            nearest_value[2] = warped_images[k].at<cv::Vec3b>(i, j)[2];\n                        }\n                    }\n                }\n            }\n            if (nearest_value[0] == -1)\n                continue;\n            else {\n                result.at<cv::Vec3b>(i, j)[0] = nearest_value[0];\n                result.at<cv::Vec3b>(i, j)[1] = nearest_value[1];\n                result.at<cv::Vec3b>(i, j)[2] = nearest_value[2];\n            }\n        }\n    }\n    return result;\n}\n\nbool panoramicStitching::siftMatchExtract() {\n    cv::SiftFeatureDetector detector;\n    cv::SiftDescriptorExtractor extractor;\n    std::vector<cv::Mat> descriptor_vec;\n    for (const cv::Mat& image : m_gray_images) {\n        if (!image.data) {\n            std::cout << \"image data wrong\" << std::endl;\n            return false;\n        }\n        //-- Step 1: detect the feature points with the Sift Detector\n        std::vector<cv::KeyPoint> keypoints;\n        detector.detect(image, keypoints);\n        m_keyPoints.push_back(keypoints);\n        //-- Step 2: calculate the descriptor\n        cv::Mat descriptor;\n        extractor.compute(image, keypoints, descriptor);\n        descriptor_vec.push_back(descriptor);\n    }\n    double good_match_threshold = 0.02;\n    for (const std::pair<int, int>& pair_index : m_image_pairs) {\n        //-- Step 3: Match the descriptor vectors using FLANN matcher\n        cv::Mat l_descriptor = descriptor_vec[pair_index.first];\n        cv::Mat r_descriptor = descriptor_vec[pair_index.second];\n        cv::FlannBasedMatcher matcher;\n        std::vector<cv::DMatch> matches;\n        matcher.match(l_descriptor, r_descriptor, matches);\n        //-- Calculate good matches whose distance is less than 2*min_dist\n        //-- or a small arbitary value (0.02) when min_dist is very small\n        double min_dist = 100, max_dist = 0;\n        for (const cv::DMatch& match : matches) {\n            min_dist = std::min(min_dist, double(match.distance));\n            max_dist = std::max(max_dist, double(match.distance));\n        }\n        std::vector<cv::DMatch> good_matches;\n        for (const cv::DMatch& match : matches) {\n            if (match.distance <= std::max(2 * min_dist, good_match_threshold))\n                good_matches.push_back(match);\n        }\n        m_matches.push_back(good_matches);\n    }\n    return true;\n}\n\nbool panoramicStitching::calculateHomography() {\n    const double confidence = 0.95;\n    const int maxIter = 2000;\n    const double ransac_threshold = 3;\n    bool result = false;\n    for (int index = 0; index < m_matches.size(); index++) {\n        int left_index = m_image_pairs[index].first;\n        int right_index = m_image_pairs[index].second;\n        int inlier_number = 0;\n        cv::Mat inlier_mask = runRansac(m_keyPoints[left_index], m_keyPoints[right_index], m_matches[index],\n                                        ransac_threshold, confidence, maxIter, result, inlier_number);\n        if (!result) {\n            std::cout << \"ransac fails\" << std::endl;\n            return false;\n        } else {\n            std::cout << \"ransac succeeds\" << std::endl;\n        }\n        cv::Mat left_points(2, inlier_number, CV_64F);\n        cv::Mat right_points(2, inlier_number, CV_64F);\n        double *p2lx = left_points.ptr<double>(0);\n        double *p2ly = left_points.ptr<double>(1);\n        double *p2rx = right_points.ptr<double>(0);\n        double *p2ry = right_points.ptr<double>(1);\n        int *p2mask = inlier_mask.ptr<int>(0);\n        int tmp_index = 0; // the tmp index of the point matrix\n        for (int i = 0; i < inlier_mask.cols; i++) {\n            if (*(p2mask + i) == 1) {\n                *(p2lx + tmp_index) = m_keyPoints[left_index][m_matches[index][i].queryIdx].pt.x;\n                *(p2ly + tmp_index) = m_keyPoints[left_index][m_matches[index][i].queryIdx].pt.y;\n                *(p2rx + tmp_index) = m_keyPoints[right_index][m_matches[index][i].trainIdx].pt.x;\n                *(p2ry + tmp_index) = m_keyPoints[right_index][m_matches[index][i].trainIdx].pt.y;\n                tmp_index++;\n            }\n        }\n        // use the inlier mask to get the initial homography with DLT\n        cv::Mat homo = runKernel(left_points, right_points);\n        // use the iteration to refine the homography\n        homo = refine(left_points, right_points, homo);\n        m_homographies.push_back(homo);\n    }\n    return true;\n}\n\ncv::Mat panoramicStitching::runRansac(const std::vector<cv::KeyPoint>& l_point,\n                                      const std::vector<cv::KeyPoint>& r_point,\n                                      const std::vector<cv::DMatch>& match,\n                                      double reproj_threshold, double confidence,\n                                      int maxIter, bool & succeed, int &max_inlier_number) {\n    const int least_point = 4; // the least number points needed to calculate the homography\n    const int n_points = match.size();\n    cv::Mat l_pointsM(3, n_points, CV_64F);\n    cv::Mat r_pointsM(3, n_points, CV_64F);\n    // get the coordinate matrix for all points\n    for (int i = 0 ; i < n_points; i++) {\n        l_pointsM.at<double>(0, i) = l_point[match[i].queryIdx].pt.x;\n        l_pointsM.at<double>(1, i) = l_point[match[i].queryIdx].pt.y;\n        l_pointsM.at<double>(2, i) = 1;\n        r_pointsM.at<double>(0, i) = r_point[match[i].trainIdx].pt.x;\n        r_pointsM.at<double>(1, i) = r_point[match[i].trainIdx].pt.y;\n        r_pointsM.at<double>(2, i) = 1;\n    }\n    int iter_times = 0;\n    max_inlier_number = 0;\n    cv::Mat most_inlier_mask;\n    while (iter_times <= maxIter) {\n        std::unordered_set<int> hash_set; // use hash_set to ensure no duplicate points in the example points\n        cv::Mat l_pointSample(3, least_point, CV_64F);\n        cv::Mat r_pointSample(3, least_point, CV_64F);\n        int exist_points = 0;\n        //-- step 1:get 4 points randomly\n        while (exist_points < least_point) {\n            int next_index = rand() % n_points;\n            if (hash_set.find(next_index) != hash_set.end())\n                continue;\n            hash_set.insert(next_index);\n            l_pointsM.col(next_index).copyTo(l_pointSample.col(exist_points));\n            r_pointsM.col(next_index).copyTo(r_pointSample.col(exist_points));\n            exist_points++;\n            if (exist_points >= 3 &&\n                    (isColinear(l_pointSample, exist_points) ||\n                     isColinear(r_pointSample, exist_points)))\n                exist_points--;\n        }\n        //-- step 2: use 4 points to get one homography\n        cv::Mat model = runKernel(l_pointSample, r_pointSample);\n        //-- step 3: find the inlines\n        int tmp_inlier_number = 0;\n        cv::Mat tmp_mask = findInliers(l_pointsM, r_pointsM, model,\n                                       reproj_threshold, tmp_inlier_number);\n        //-- change the iteration times according to the confidence and the inlier number\n        if (tmp_inlier_number > max_inlier_number) {\n            most_inlier_mask = tmp_mask;\n            max_inlier_number = tmp_inlier_number;\n            maxIter = std::min(maxIter,\n                               updateMaxIter(max_inlier_number, n_points, confidence));\n        }\n        iter_times++;\n    }\n    if (max_inlier_number > least_point) {\n        succeed = true;\n        return most_inlier_mask;\n    } else {\n        succeed = false;\n        return most_inlier_mask;\n    }\n}\n\n// In order to increase the speed, we use the knowledge that everytime we will\n// only add one point, and the previous point is guaranted to be not colinear\nbool panoramicStitching::isColinear(cv::Mat points, int number) {\n    if (number < 3) return false;\n    // choose every possible 2 points\n    int k = number - 1;\n    for (int i = 0; i < number - 2; i++) {\n        for (int j = i + 1; j < number - 1; j++) {\n            double x1 = points.at<double>(0, i);\n            double y1 = points.at<double>(1, i);\n            double x2 = points.at<double>(0, j);\n            double y2 = points.at<double>(1, j);\n            double x3 = points.at<double>(0, k);\n            double y3 = points.at<double>(1, k);\n            double dx1 = x1 - x2;\n            double dy1 = y1 - y2;\n            double dx2 = x1 - x3;\n            double dy2 = y1 - y3;\n            // DBL_EPSILON: is used to compare double precision with 0\n            // the equation is derived from the distance from one point to one line\n            if (fabs(dx1 * dy2 - dx2 * dy1) <\n                    DBL_EPSILON * (fabs(dx1) + fabs(dy1) + fabs(dx2) + fabs(dy2)))\n                return true;\n        }\n    }\n    return false;\n}\n\ncv::Mat panoramicStitching::runKernel(cv::Mat l_points, cv::Mat r_points) {\n    //-- Step 1: Normalize, center is 0, and average distance to center is sqrt(2)\n    // the detailed algorithm explain can be seen in Multiview Geometry in Computer Vision P109\n    int data_number = l_points.cols;\n    double *p2lx = l_points.ptr<double>(0);\n    double *p2ly = l_points.ptr<double>(1);\n    double *p2rx = r_points.ptr<double>(0);\n    double *p2ry = r_points.ptr<double>(1);\n    double l_center[2] = {0, 0};\n    double r_center[2] = {0, 0};\n    for (int i = 0; i < data_number; i++) {\n        l_center[0] += *(p2lx + i);\n        l_center[1] += *(p2ly + i);\n        r_center[0] += *(p2rx + i);\n        r_center[1] += *(p2ry + i);\n    }\n    l_center[0] /= data_number;\n    l_center[1] /= data_number;\n    r_center[0] /= data_number;\n    r_center[1] /= data_number;\n    double sum_l[2] = {0, 0};\n    double sum_r[2] = {0, 0};\n    // use the sum of absolute value to approximate the distance between points and center\n    for (int i = 0; i < data_number; i++) {\n        sum_l[0] += fabs(*(p2lx + i) - l_center[0]);\n        sum_l[1] += fabs(*(p2ly + i) - l_center[1]);\n        sum_r[0] += fabs(*(p2rx + i) - r_center[0]);\n        sum_r[1] += fabs(*(p2ry + i) - r_center[1]);\n    }\n    if (fabs(sum_l[0]) < DBL_EPSILON || fabs(sum_l[1]) < DBL_EPSILON ||\n            fabs(sum_r[0]) < DBL_EPSILON || fabs(sum_r[1]) < DBL_EPSILON) {\n        std::cout << \"the inlier points have something wrong\" << std::endl;\n        return cv::Mat(0, 0, CV_64F);\n    }\n    sum_l[0] = data_number / sum_l[0];\n    sum_l[1] = data_number / sum_l[1];\n    sum_r[0] = data_number / sum_r[0];\n    sum_r[1] = data_number / sum_r[1];\n    // final homography is T'^(-1) * H_normalize * T\n    // Be careful that the Homography is used to transfer the right to the left\n    cv::Mat T1_inv = (cv::Mat_<double>(3, 3) <<\n                      1 / sum_l[0], 0, l_center[0],\n                      0, 1 / sum_l[1], l_center[1],\n                      0, 0, 1);\n    cv::Mat T2 = (cv::Mat_<double>(3, 3) <<\n                  sum_r[0], 0, -sum_r[0] * r_center[0],\n                  0, sum_r[1], -sum_r[1] * r_center[1],\n                  0, 0, 1);\n    //--Step 2: use the normalized coordinate to calculate DLT\n    cv::Mat L(cv::Mat::zeros(2 * data_number, 9, CV_64F));\n    for (int i = 0; i < data_number; i++) {\n        double lx = (*(p2lx + i) - l_center[0]) * sum_l[0];\n        double ly = (*(p2ly + i) - l_center[1]) * sum_l[1];\n        double rx = (*(p2rx + i) - r_center[0]) * sum_r[0];\n        double ry = (*(p2ry + i) - r_center[1]) * sum_r[1];\n        double *p2up = L.ptr<double>(i * 2);\n        double *p2down = L.ptr<double>(i * 2 + 1);\n        *(p2up + 3) = -rx;\n        *(p2up + 4) = -ry;\n        *(p2up + 5) = -1;\n        *(p2up + 6) = ly * rx;\n        *(p2up + 7) = ly * rx;\n        *(p2up + 8) = ly;\n        *p2down = rx;\n        *(p2down + 1) = ry;\n        *(p2down + 2) = 1;\n        *(p2down + 6) = -lx * rx;\n        *(p2down + 7) = -lx * ry;\n        *(p2down + 8) = -lx;\n    }\n    cv::Mat LtL = L.t() * L;\n    cv::Mat eigenValue, eigenVector;\n    cv::eigen(LtL, eigenValue, eigenVector);\n    cv::Mat result = eigenVector.row(8);\n    // we need to clone the result here because the reshape needs that matrix data is continuous\n    result = T1_inv * result.clone().reshape(0, 3) * T2;\n    result = result / result.at<double>(2, 2);\n    // return the 3*3 H matrix\n    return result;\n}\n\ncv::Mat panoramicStitching::findInliers(cv::Mat l_points, cv::Mat r_points,\n                                        cv::Mat homography,\n                                        const double threshold, int& inlier_number) {\n    int n = l_points.cols; // number of points\n    cv::Mat result_mask(1, n, CV_32S);\n    // calculate the geometry error\n    double h[9];\n    for (int i = 0; i < 9; i++) {\n        h[i] = homography.at<double>(i / 3, i - 3 * (i / 3));\n    }\n    double* p2rx = r_points.ptr<double>(0);\n    double* p2ry = r_points.ptr<double>(1);\n    double* p2rw = r_points.ptr<double>(2);\n    double* p2lx = l_points.ptr<double>(0);\n    double* p2ly = l_points.ptr<double>(1);\n    double* p2lw = l_points.ptr<double>(2);\n    double threshold_square = threshold * threshold;\n    int *p2result = result_mask.ptr<int>(0);\n    int count = 0;\n    for (int i = 0; i < n; i++) {\n        double ww = 1.0 / (h[6] * (*(p2rx + i)) + h[7] * (*(p2ry + i)) + h[8] * (*(p2rw + i)));\n        double xx = ww * (h[0] * (*(p2rx + i)) + h[1] * (*(p2ry + i)) + h[2] * (*(p2rw + i)))\n                    - (*(p2lx + i)) / (*(p2lw + i));\n        double yy = ww * (h[3] * (*(p2rx + i)) + h[4] * (*(p2ry + i)) + h[5] * (*(p2rw + i)))\n                    - (*(p2ly + i)) / (*(p2lw + i));\n        if ((xx * xx + yy * yy) <= threshold_square) {\n            *(p2result + i) = 1;\n            count++;\n        } else {\n            *(p2result + i) = 0;\n        }\n    }\n    inlier_number = count;\n    return result_mask;\n}\n\nint panoramicStitching::updateMaxIter(int inlier_number, int total_number, double confidence) {\n    int model_points = 4; // we need 4 points to calculate one homography\n    double e_p = 1 - double(inlier_number) / total_number;\n    if (e_p > 1) {\n        std::cout << \"the error rate is greater than 1\" << std::endl;\n        return -1;\n    }\n    double num = std::max(1.0 - confidence, DBL_MIN); // avoid inf\n    double denom = 1.0 - pow(1.0 - e_p, model_points);\n    if (denom < DBL_MIN) return 0; // all points are inliers\n    num = std::log(num) / std::log(denom);\n\t// prevent the overflow\n\tif (num > 10000)\n\t\treturn 10000;\n    return std::round(num);\n}\n\ncv::Mat panoramicStitching::refine(cv::Mat left_points, cv::Mat right_points, cv::Mat ini_homo) {\n    Eigen::VectorXd x(8);\n    double h8 = ini_homo.at<double>(2, 2);\n    for (int i = 0; i <= 7; i++) {\n        x[i] = ini_homo.at<double>(i / 3, i - 3 * (i / 3)) / h8;\n    }\n    //Eigen::VectorXd x_previous = x.replicate(1, 1);\n    geometricError functor(left_points, right_points);\n    Eigen::NumericalDiff<geometricError> num_diff(functor);\n    Eigen::LevenbergMarquardt<Eigen::NumericalDiff<geometricError>> lm(num_diff);\n    int ret = lm.minimize(x);\n    //std::cout << x - x_previous << std::endl;\n    for (int i = 0; i <= 7; i++) {\n        ini_homo.at<double>(i / 3, i - 3 * (i / 3)) = x[i];\n    }\n    ini_homo.at<double>(2, 2) = 1;\n    return ini_homo;\n}\n\ngeometricError::geometricError(cv::Mat left_points, cv::Mat right_points):\n    Functor<double>(8, 2 * left_points.cols),\n    left_points(left_points),\n    right_points(right_points) {\n}\n\nint geometricError::operator()(const Eigen::VectorXd & x, Eigen::VectorXd & fvec) const {\n    double* p2lx = const_cast<double*>(left_points.ptr<double>(0));\n    double* p2ly = const_cast<double*>(left_points.ptr<double>(1));\n    double* p2rx = const_cast<double*>(right_points.ptr<double>(0));\n    double* p2ry = const_cast<double*>(right_points.ptr<double>(1));\n    for (int i = 0; i < values() / 2; i++) {\n        double lx = *(p2lx + i);\n        double ly = *(p2ly + i);\n        double rx = *(p2rx + i);\n        double ry = *(p2ry + i);\n        double ww = x[6] * rx + x[7] * ry + 1;\n        ww = std::fabs(ww) > DBL_EPSILON ? 1. / ww : 0;\n        double lx_est = ww * (x[0] * rx + x[1] * ry + x[2]);\n        double ly_est = ww * (x[3] * rx + x[4] * ry + x[5]);\n        fvec[i * 2] = lx - lx_est;\n        fvec[i * 2 + 1] = ly - ly_est;\n    }\n    return 0;\n}\n\nint geometricError::df(const Eigen::VectorXd & x, Eigen::MatrixXd & fjac) const {\n    double* p2lx = const_cast<double*>(left_points.ptr<double>(0));\n    double* p2ly = const_cast<double*>(left_points.ptr<double>(1));\n    double* p2rx = const_cast<double*>(right_points.ptr<double>(0));\n    double* p2ry = const_cast<double*>(right_points.ptr<double>(1));\n    for (int i = 0; i < values() >> 1; i++) {\n        double rx = *(p2rx + i);\n        double ry = *(p2ry + i);\n        double ww = x[6] * rx + x[7] * ry + 1;\n        ww = std::fabs(ww) > DBL_EPSILON ? 1. / ww : 0;\n        double lx_est = ww * (x[0] * rx + x[1] * ry + x[2]);\n        double ly_est = ww * (x[3] * rx + x[4] * ry + x[3]);\n        fjac(i * 2, 0) = rx * ww;\n        fjac(i * 2, 1) = ry * ww;\n        fjac(i * 2, 2) = ww;\n        fjac(i * 2, 3) = 0;\n        fjac(i * 2, 4) = 0;\n        fjac(i * 2, 5) = 0;\n        fjac(i * 2, 6) = -rx * lx_est * ww;\n        fjac(i * 2, 7) = -ry * lx_est * ww;\n        fjac(i * 2 + 1, 0) = 0;\n        fjac(i * 2 + 1, 1) = 0;\n        fjac(i * 2 + 1, 2) = 0;\n        fjac(i * 2 + 1, 3) = rx * ww;\n        fjac(i * 2 + 1, 4) = ry * ww;\n        fjac(i * 2 + 1, 5) = ww;\n        fjac(i * 2 + 1, 6) = -rx * ly_est * ww;\n        fjac(i * 2 + 1, 7) = -ry * ly_est * ww;\n    }\n    return 0;\n}\n\n}\n", "meta": {"hexsha": "6fe8ee6242854a1d280155d0010a7c447418d7dc", "size": 28375, "ext": "cc", "lang": "C++", "max_stars_repo_path": "panoramic_stitching.cc", "max_stars_repo_name": "XinyuanGui/panaromicStitching", "max_stars_repo_head_hexsha": "b0fa3e5b0f7ca7de268257b01c80fca77f2fee4b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2019-01-16T21:34:53.000Z", "max_stars_repo_stars_event_max_datetime": "2019-10-16T07:59:25.000Z", "max_issues_repo_path": "panoramic_stitching.cc", "max_issues_repo_name": "XinyuanGui/panaromicStitching", "max_issues_repo_head_hexsha": "b0fa3e5b0f7ca7de268257b01c80fca77f2fee4b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "panoramic_stitching.cc", "max_forks_repo_name": "XinyuanGui/panaromicStitching", "max_forks_repo_head_hexsha": "b0fa3e5b0f7ca7de268257b01c80fca77f2fee4b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-04-12T05:50:28.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-03T12:16:53.000Z", "avg_line_length": 44.7555205047, "max_line_length": 136, "alphanum_fraction": 0.545938326, "num_tokens": 7902, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6297746074044134, "lm_q2_score": 0.5389832206876841, "lm_q1q2_score": 0.3394379462061526}}
{"text": "/*\n   Copyright 2020 The Silkworm Authors\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 \"snark.hpp\"\n\n#include <algorithm>\n#include <boost/endian/conversion.hpp>\n#include <cassert>\n#include <cstring>\n#include <libff/algebra/curves/alt_bn128/alt_bn128_pp.hpp>\n#include <libff/common/profiling.hpp>\n\nnamespace silkworm::snark {\n\nvoid init_libff() noexcept {\n    // magic static\n    [[maybe_unused]] static bool initialized = []() noexcept {\n        libff::inhibit_profiling_info = true;\n        libff::inhibit_profiling_counters = true;\n        libff::alt_bn128_pp::init_public_params();\n        return true;\n    }();\n}\n\nScalar to_scalar(ByteView be) noexcept {\n    mpz_t m;\n    mpz_init(m);\n    mpz_import(m, be.size(), /*order=*/1, /*size=*/1, /*endian=*/0, /*nails=*/0, &be[0]);\n    Scalar out{m};\n    mpz_clear(m);\n    return out;\n}\n\n// Notation warning: Yellow Paper's p is the same libff's q.\n// Returns x < p (YP notation).\nstatic bool valid_element_of_fp(const Scalar& x) noexcept {\n    return mpn_cmp(x.data, libff::alt_bn128_modulus_q.data, libff::alt_bn128_q_limbs) < 0;\n}\n\nstd::optional<libff::alt_bn128_G1> decode_g1_element(ByteView bytes64_be) noexcept {\n    assert(bytes64_be.size() == 64);\n\n    Scalar x{to_scalar(bytes64_be.substr(0, 32))};\n    if (!valid_element_of_fp(x)) {\n        return {};\n    }\n\n    Scalar y{to_scalar(bytes64_be.substr(32, 32))};\n    if (!valid_element_of_fp(y)) {\n        return {};\n    }\n\n    if (x.is_zero() && y.is_zero()) {\n        return libff::alt_bn128_G1::zero();\n    }\n\n    libff::alt_bn128_G1 point{x, y, libff::alt_bn128_Fq::one()};\n    if (!point.is_well_formed()) {\n        return {};\n    }\n    return point;\n}\n\nstatic std::optional<libff::alt_bn128_Fq2> decode_fp2_element(ByteView bytes64_be) noexcept {\n    assert(bytes64_be.size() == 64);\n\n    // big-endian encoding\n    Scalar c0{to_scalar(bytes64_be.substr(32, 32))};\n    Scalar c1{to_scalar(bytes64_be.substr(0, 32))};\n\n    if (!valid_element_of_fp(c0) || !valid_element_of_fp(c1)) {\n        return {};\n    }\n\n    return libff::alt_bn128_Fq2{c0, c1};\n}\n\nstd::optional<libff::alt_bn128_G2> decode_g2_element(ByteView bytes128_be) noexcept {\n    assert(bytes128_be.size() == 128);\n\n    std::optional<libff::alt_bn128_Fq2> x{decode_fp2_element(bytes128_be.substr(0, 64))};\n    if (!x) {\n        return {};\n    }\n\n    std::optional<libff::alt_bn128_Fq2> y{decode_fp2_element(bytes128_be.substr(64, 64))};\n    if (!y) {\n        return {};\n    }\n\n    if (x->is_zero() && y->is_zero()) {\n        return libff::alt_bn128_G2::zero();\n    }\n\n    libff::alt_bn128_G2 point{*x, *y, libff::alt_bn128_Fq2::one()};\n    if (!point.is_well_formed()) {\n        return {};\n    }\n\n    if (!(libff::alt_bn128_G2::order() * point).is_zero()) {\n        // wrong order, doesn't belong to the subgroup G2\n        return {};\n    }\n\n    return point;\n}\n\nBytes encode_g1_element(libff::alt_bn128_G1 p) noexcept {\n    Bytes out(64, '\\0');\n    if (p.is_zero()) {\n        return out;\n    }\n\n    p.to_affine_coordinates();\n\n    auto x{p.X.as_bigint()};\n    auto y{p.Y.as_bigint()};\n\n    // Here we convert little-endian data to big-endian output\n    static_assert(boost::endian::order::native == boost::endian::order::little);\n    static_assert(sizeof(x.data) == 32);\n\n    std::memcpy(&out[0], y.data, 32);\n    std::memcpy(&out[32], x.data, 32);\n\n    std::reverse(out.begin(), out.end());\n    return out;\n}\n}  // namespace silkworm::snark\n", "meta": {"hexsha": "0f214fe9f825066699f3f1deb3b873e1d5700936", "size": 3936, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "silkworm/crypto/snark.cpp", "max_stars_repo_name": "gcolvin/silkworm", "max_stars_repo_head_hexsha": "11cb3ea2aa215185eb96a460f87c67f83bdc6620", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-01-30T10:17:23.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-30T10:17:23.000Z", "max_issues_repo_path": "silkworm/crypto/snark.cpp", "max_issues_repo_name": "root-servers/silkworm", "max_issues_repo_head_hexsha": "2657eeeab8876f073c30604f5186c2539dc862ac", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "silkworm/crypto/snark.cpp", "max_forks_repo_name": "root-servers/silkworm", "max_forks_repo_head_hexsha": "2657eeeab8876f073c30604f5186c2539dc862ac", "max_forks_repo_licenses": ["Apache-2.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.5244755245, "max_line_length": 93, "alphanum_fraction": 0.6493902439, "num_tokens": 1118, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7122321964553657, "lm_q2_score": 0.47657965106367595, "lm_q1q2_score": 0.3394353716630137}}
{"text": "/*\n * MIT License\n *\n * Copyright (c) 2020 Robert Grupp\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\n#include \"xregImgSimMetric2DPatchNCCOCL.h\"\n\n// ITK pollutes the global namespace with a macro, and causes\n// a compile failure with vienna cl\n#ifdef vcl_size_t\n#undef vcl_size_t\n#endif\n#ifdef vcl_ptrdiff_t\n#undef vcl_ptrdiff_t\n#endif\n\n#include <boost/compute/utility/source.hpp>\n\n#include <viennacl/matrix.hpp>\n#include <viennacl/vector.hpp>\n#include <viennacl/linalg/prod.hpp>\n\n#include \"xregAssert.h\"\n#include \"xregITKOpenCVUtils.h\"\n\nnamespace\n{\n\nconst char* kPATCH_NCC_OPENCL_SRC = BOOST_COMPUTE_STRINGIZE_SOURCE(\n\nfloat2 xregComputePatchStats(__global const float* patch,\n                             const ulong patch_stride,\n                             const uint patch_num_cols,\n                             const uint patch_num_rows)\n{\n  __global const float* patch_cur_row = patch;\n\n  const uint num_pix_in_patch = patch_num_cols * patch_num_rows;\n\n  float2 mean_and_std_dev = (float2) (0, 0);\n\n  for (uint r = 0; r < patch_num_rows; ++r, patch_cur_row += patch_stride)\n  {\n    for (uint c = 0; c < patch_num_cols; ++c)\n    {\n      mean_and_std_dev.x += patch_cur_row[c];\n    }\n  }\n\n  mean_and_std_dev.x /= num_pix_in_patch;\n\n  patch_cur_row = patch;\n\n  float tmp_diff = 0;\n\n  for (uint r = 0; r < patch_num_rows; ++r, patch_cur_row += patch_stride)\n  {\n    for (uint c = 0; c < patch_num_cols; ++c)\n    {\n      tmp_diff = mean_and_std_dev.x - patch_cur_row[c];\n      mean_and_std_dev.y += tmp_diff * tmp_diff;\n    }\n  }\n  \n  mean_and_std_dev.y = max(sqrt(mean_and_std_dev.y / (num_pix_in_patch - 1)), 1.0e-6f);\n\n  return mean_and_std_dev;\n}\n\n__kernel void FixedImagePatchStats(__global const float* fixed_img,\n                                   const ulong  img_num_cols,\n                                   const ulong num_patches,\n                                   __global float2* fixed_img_patch_means_and_std_devs,\n                                   __global const uint4* patch_start_stop_infos)\n{\n  const uint patch_idx = get_global_id(0);\n\n  if (patch_idx < num_patches)\n  {\n    const uint4 cur_patch_info = patch_start_stop_infos[patch_idx];\n\n    const uint patch_start_row = cur_patch_info.x;\n    const uint patch_start_col = cur_patch_info.y;\n    const uint patch_stop_row  = cur_patch_info.z;\n    const uint patch_stop_col  = cur_patch_info.w;\n\n    fixed_img_patch_means_and_std_devs[patch_idx] = xregComputePatchStats(\n                                                     fixed_img + (img_num_cols * patch_start_row) + patch_start_col,\n                                                     img_num_cols,\n                                                     patch_stop_row - patch_start_row + 1,\n                                                     patch_stop_col - patch_start_col + 1);\n  }\n}\n\n__kernel void ProcFixedImagePatches(__global const float* fixed_img,\n                                    __global float* proc_fixed_img_patches, \n                                    const ulong  img_num_cols,\n                                    const ulong  proc_patch_stride,\n                                    const ulong num_patches,\n                                    __global const float2* fixed_img_patch_means_and_std_devs,\n                                    __global const uint4* patch_start_stop_infos)\n{\n  const uint patch_idx = get_global_id(0);\n\n  if (patch_idx < num_patches)\n  {\n    const uint4 cur_patch_info = patch_start_stop_infos[patch_idx];\n\n    const uint patch_start_row = cur_patch_info.x;\n    const uint patch_start_col = cur_patch_info.y;\n    const uint patch_stop_row  = cur_patch_info.z;\n    const uint patch_stop_col  = cur_patch_info.w;\n  \n    const uint nr = patch_stop_row - patch_start_row + 1;\n    const uint nc = patch_stop_col - patch_start_col + 1;\n\n    __global const float* cur_fixed_row = fixed_img + (patch_start_row * img_num_cols) + patch_start_col;\n\n    __global float* cur_proc_row = proc_fixed_img_patches + (patch_idx * proc_patch_stride);\n\n    const float2 mean_and_std_dev = fixed_img_patch_means_and_std_devs[patch_idx];\n\n    const float s = mean_and_std_dev.y * nr * nc;\n\n    for (uint r = 0; r < nr; ++r, cur_proc_row += nc, cur_fixed_row += img_num_cols)\n    {\n      for (uint c = 0; c < nc; ++c)\n      {\n        cur_proc_row[c] = (cur_fixed_row[c] - mean_and_std_dev.x) / s;\n      }\n    }\n  }\n}\n\n__kernel void ProcMovImagePatches(__global const  float* proc_fixed_img_patches,\n                                  const ulong proc_fixed_patch_stride,\n                                  const ulong num_patches,\n                                  const uint num_imgs,\n                                  const uint mov_proj_off,\n                                  const ulong img_num_cols,\n                                  const ulong img_num_rows,\n                                  __global const uint4* patch_start_stop_infos,\n                                  __global const float* mov_imgs,\n                                  __global float* patch_nccs,\n                                  __global const ulong* global_patch_idx_lut)\n{\n  const uint patch_idx_inc = get_global_size(0);\n  const uint img_idx       = get_global_id(1);\n\n  if (img_idx < num_imgs)\n  {\n    __global const float* cur_mov_img  = mov_imgs + ((mov_proj_off + img_idx) * img_num_rows * img_num_cols);\n    __global       float* cur_img_nccs = patch_nccs + (img_idx * num_patches);\n\n    for (uint local_patch_idx = get_global_id(0); local_patch_idx < num_patches; local_patch_idx += patch_idx_inc)\n    {\n      const ulong global_patch_idx = global_patch_idx_lut[local_patch_idx];\n\n      __global const float* cur_proc_fixed_patch = proc_fixed_img_patches + (global_patch_idx * proc_fixed_patch_stride);\n    \n      const uint4 cur_patch_info = patch_start_stop_infos[global_patch_idx];\n    \n      const uint patch_start_row = cur_patch_info.x;\n      const uint patch_start_col = cur_patch_info.y;\n      const uint patch_stop_row  = cur_patch_info.z;\n      const uint patch_stop_col  = cur_patch_info.w;\n\n      const uint nr = patch_stop_row - patch_start_row + 1;\n      const uint nc = patch_stop_col - patch_start_col + 1;\n  \n      __global const float* cur_mov_patch_row = cur_mov_img + (img_num_cols * patch_start_row) + patch_start_col;\n\n      const float2 mov_patch_mean_std_dev = xregComputePatchStats(cur_mov_patch_row, img_num_cols, nr, nc);\n\n      float ncc = 0;\n\n      for (uint r = 0; r < nr; ++r, cur_mov_patch_row += img_num_cols, cur_proc_fixed_patch += nc)\n      {\n        for (uint c = 0; c < nc; ++c)\n        {\n          ncc += cur_proc_fixed_patch[c] * (cur_mov_patch_row[c] - mov_patch_mean_std_dev.x);\n        }\n      }\n\n      ncc /= mov_patch_mean_std_dev.y;\n\n      cur_img_nccs[local_patch_idx] = 1 - ncc;\n    }\n  }\n}\n\n);\n\n}  // un-named\n\nxreg::ImgSimMetric2DPatchNCCOCL::ImgSimMetric2DPatchNCCOCL(const boost::compute::device& dev)\n  : ImgSimMetric2DOCL(dev)\n{ }\n\nxreg::ImgSimMetric2DPatchNCCOCL::ImgSimMetric2DPatchNCCOCL(const boost::compute::context& ctx,\n                                                           const boost::compute::command_queue& queue)\n  : ImgSimMetric2DOCL(ctx, queue)\n{ }\n\nvoid xreg::ImgSimMetric2DPatchNCCOCL::allocate_resources()\n{\n  namespace bc = boost::compute;\n  \n  xregASSERT(this->patch_radius_ > 0);\n\n  // unsupported options when running on the GPU:\n  xregASSERT(!this->use_mask_for_patch_stats_);\n \n  auto itk_size = this->fixed_img_->GetLargestPossibleRegion().GetSize();\n\n  img_num_rows_ = itk_size[1];\n  img_num_cols_ = itk_size[0];\n\n  // create the initial, full, set of patches\n\n  // the mask is only used here to compute initial weights on the CPU, so we do not require\n  // any other previous processing done to it\n  const bool use_mask = this->mask_;\n\n\tcv::Mat ocv_mask;\n  if (this->mask_)\n  {\n    ocv_mask = ShallowCopyItkToOpenCV(this->mask_.GetPointer());\n  }\n  this->setup_patches(img_num_rows_, img_num_cols_,\n                      use_mask ? &ocv_mask : nullptr,\n                      this->num_mov_imgs_);\n  \n  const size_type num_patches = this->patch_infos_.size();\n\n  // compute the patch bounds on the gpu device\n  {\n    patch_start_stops_dev_.reset(new DevBufUInt4(this->ctx_));\n  \n    std::vector<bc::uint4_> patch_start_stops_host(num_patches);\n\n    fixed_img_proc_patches_max_len_ = 0;\n\n    for (size_type patch_idx = 0; patch_idx < num_patches; ++patch_idx)\n    {\n      const auto& cur_patch_info = this->patch_infos_[patch_idx];\n\n      auto& cur_start_stop = patch_start_stops_host[patch_idx];\n      \n      cur_start_stop[0] = cur_patch_info.start_row;\n      cur_start_stop[1] = cur_patch_info.start_col;\n      cur_start_stop[2] = cur_patch_info.stop_row;\n      cur_start_stop[3] = cur_patch_info.stop_col;\n    \n      fixed_img_proc_patches_max_len_ = std::max(fixed_img_proc_patches_max_len_,\n                                             (cur_patch_info.stop_row - cur_patch_info.start_row + 1) *\n                                             (cur_patch_info.stop_col - cur_patch_info.start_col + 1));\n    }\n    \n    patch_start_stops_dev_->assign(patch_start_stops_host.begin(), patch_start_stops_host.end(), this->queue_);\n  }\n\n  // compile, and create custom kernels\n  bc::program prog = bc::program::create_with_source(kPATCH_NCC_OPENCL_SRC, this->ctx_);\n  \n  try\n  {\n    prog.build();\n  }\n  catch (bc::opencl_error &)\n  {\n    std::cerr << \"OpenCL Kernel Compile Error (ImgSimMetric2DPatchNCCOCL):\\n\"\n              << prog.build_log() << std::endl;\n    throw;\n  }\n  \n  fixed_img_stats_krnl_        = prog.create_kernel(\"FixedImagePatchStats\");\n  fixed_img_proc_patches_krnl_ = prog.create_kernel(\"ProcFixedImagePatches\");\n  proc_mov_img_patches_krnl_   = prog.create_kernel(\"ProcMovImagePatches\");\n\n  fixed_img_stats_proc_done_ = false;\n  \n  // this will result in the process_mask method being called, which may trigger some weight recomputation,\n  // and also fixed image statistics/pre-processing, which is why we have previously setup patches\n  ImgSimMetric2DOCL::allocate_resources();\n}\n\nvoid xreg::ImgSimMetric2DPatchNCCOCL::compute()\n{\n  namespace bc  = boost::compute;\n  namespace vcl = viennacl;\n  \n  this->pre_compute();\n\n  // this is the current number patches to be used, e.g. if a random subset of 10 patches should be used\n  // this number is 10\n  const size_type num_patches = this->num_patches();\n\n  const bool use_mask = this->mask_;\n\n  cv::Mat ocv_mask;\n  if (this->mask_)\n  {\n    ocv_mask = ShallowCopyItkToOpenCV(this->mask_.GetPointer());\n  }\n\n  // This uses some state to determine if the weights actually need to be recomputed\n  this->compute_weights(this->mask_ ? &ocv_mask : nullptr);\n\n  if (!this->do_not_update_patch_inds_to_use_)\n  {\n    // this is where random patches are sampled\n    this->patch_inds_to_use_ = this->patch_indices_to_use();\n  }\n \n  // copy the patch indices and weights to use onto the GPU\n  patch_inds_to_use_host_.clear();\n\n  for (const auto& p : this->patch_inds_to_use_)\n  {\n    patch_inds_to_use_host_.push_back(p);\n  }\n\n  bc::copy(patch_inds_to_use_host_.begin(), patch_inds_to_use_host_.end(),\n           patch_inds_to_use_dev_->begin(), this->queue_);\n  \n  wgts_to_use_host_.clear();\n \n  Scalar tot_wgt = 0;\n  if (this->weight_patch_sims_in_combine_)\n  {\n    for (const auto& p : this->patch_inds_to_use_)\n    {\n      const auto& w = this->patch_infos_[p].weight;\n\n      tot_wgt += w;\n\n      wgts_to_use_host_.push_back(w);\n    }\n  }\n  else\n  {\n    wgts_to_use_host_.assign(num_patches, 1);\n    tot_wgt = num_patches;\n  }\n\n  if (this->compute_mean_of_patch_sims_ || this->weight_patch_sims_in_combine_)\n  {\n    for (auto& w : wgts_to_use_host_)\n    {\n      w /= tot_wgt;\n    }\n  }\n\n  bc::copy(wgts_to_use_host_.begin(), wgts_to_use_host_.end(),\n           wgts_to_use_dev_->begin(), this->queue_);\n\n  // TODO: it would be really nice to have to some state that avoids transferring the \n  //       patches used and/or weights when they are unchanged.\n\n  proc_mov_img_patches_krnl_.set_arg(0, *proc_fixed_img_patches_dev_);\n  proc_mov_img_patches_krnl_.set_arg(1, bc::ulong_(fixed_img_proc_patches_max_len_));\n  proc_mov_img_patches_krnl_.set_arg(2, bc::ulong_(num_patches));\n  proc_mov_img_patches_krnl_.set_arg(3, bc::uint_(this->num_mov_imgs_));\n  proc_mov_img_patches_krnl_.set_arg(4, bc::uint_(this->proj_off_));\n  proc_mov_img_patches_krnl_.set_arg(5, bc::ulong_(img_num_cols_));\n  proc_mov_img_patches_krnl_.set_arg(6, bc::ulong_(img_num_rows_));\n  proc_mov_img_patches_krnl_.set_arg(7, *patch_start_stops_dev_);\n  proc_mov_img_patches_krnl_.set_arg(8, *this->mov_imgs_buf_);\n  proc_mov_img_patches_krnl_.set_arg(9, *patch_nccs_dev_);\n  proc_mov_img_patches_krnl_.set_arg(10, *patch_inds_to_use_dev_);\n\n  std::array<std::size_t,2> global_size = { num_patches, this->num_mov_imgs_ };\n  this->queue_.enqueue_nd_range_kernel(proc_mov_img_patches_krnl_, 2, nullptr, global_size.data(), nullptr).wait();\n\n  // compute weighted sums, averages, whichever\n\n  vcl::matrix<float> patch_nccs_mat(patch_nccs_dev_->get_buffer().get(),\n                                    this->num_mov_imgs_, num_patches);\n\n  vcl::vector<float> wgts_vec(wgts_to_use_dev_->get_buffer().get(), num_patches);\n\n  vcl::vector<float> sims_vec(sim_vals_dev_->get_buffer().get(), this->num_mov_imgs_);\n\n  vcl::linalg::prod_impl(patch_nccs_mat, wgts_vec, sims_vec);\n\n  bc::copy(sim_vals_dev_->begin(), sim_vals_dev_->end(), this->sim_vals_.begin(), this->queue_);\n}\n\nvoid xreg::ImgSimMetric2DPatchNCCOCL::process_mask()\n{\n  namespace bc = boost::compute;\n  \n  // NOTE: this call is commented out, because we do not need the mask represented as a float image\n  // and moved to the GPU for this sim metric\n  //ImgSimMetric2DOCL::process_mask();\n  \n  const size_type num_patches = this->patch_infos_.size();\n  \n  if (!fixed_img_stats_proc_done_)\n  {\n    // mean and std. devs of fixed image patches\n    fixed_img_patch_stats_dev_.reset(new DevBufFloat2(this->ctx_));\n    fixed_img_patch_stats_dev_->resize(num_patches, this->queue_);\n\n    fixed_img_stats_krnl_.set_arg(0, *this->fixed_img_ocl_buf_);\n    fixed_img_stats_krnl_.set_arg(1, bc::ulong_(img_num_cols_));\n    fixed_img_stats_krnl_.set_arg(2, bc::ulong_(num_patches));\n    fixed_img_stats_krnl_.set_arg(3, *fixed_img_patch_stats_dev_);\n    fixed_img_stats_krnl_.set_arg(4, *patch_start_stops_dev_);\n\n    std::size_t global_size = num_patches;\n\n    this->queue_.enqueue_nd_range_kernel(fixed_img_stats_krnl_, 1, nullptr, &global_size, nullptr).wait();\n\n    // pre-process the fixed image patches using the mean and std. devs.\n    proc_fixed_img_patches_dev_.reset(new DevBuf(this->ctx_));\n    proc_fixed_img_patches_dev_->resize(num_patches * fixed_img_proc_patches_max_len_, this->queue_);\n\n\n    fixed_img_proc_patches_krnl_.set_arg(0, *this->fixed_img_ocl_buf_);\n    fixed_img_proc_patches_krnl_.set_arg(1, *proc_fixed_img_patches_dev_);\n    fixed_img_proc_patches_krnl_.set_arg(2, bc::ulong_(img_num_cols_));\n    fixed_img_proc_patches_krnl_.set_arg(3, bc::ulong_(fixed_img_proc_patches_max_len_));\n    fixed_img_proc_patches_krnl_.set_arg(4, bc::ulong_(num_patches));\n    fixed_img_proc_patches_krnl_.set_arg(5, *fixed_img_patch_stats_dev_);\n    fixed_img_proc_patches_krnl_.set_arg(6, *patch_start_stops_dev_);\n\n    this->queue_.enqueue_nd_range_kernel(fixed_img_proc_patches_krnl_, 1, nullptr, &global_size, nullptr).wait();\n\n    // allocate maximum capacity buffers for storing which patches to use\n    // and the patch weights\n\n    patch_inds_to_use_host_.reserve(num_patches);\n    patch_inds_to_use_dev_.reset(new DevBufULong(this->ctx_));\n    patch_inds_to_use_dev_->resize(num_patches, this->queue_);\n\n    wgts_to_use_host_.reserve(num_patches);\n    wgts_to_use_dev_.reset(new DevBuf(this->ctx_));\n    wgts_to_use_dev_->resize(num_patches, this->queue_);\n\n    patch_nccs_dev_.reset(new DevBuf(this->ctx_));\n    patch_nccs_dev_->resize(num_patches * this->num_mov_imgs_, this->queue_);\n    \n    sim_vals_dev_.reset(new DevBuf(this->ctx_));\n    sim_vals_dev_->resize(this->num_mov_imgs_, this->queue_);\n\n    fixed_img_stats_proc_done_ = true;\n  }\n\n  // TODO: check about using the fixed image patch std. devs as weights\n \n  const bool use_mask = this->mask_;\n\n  cv::Mat ocv_mask;\n  if (this->mask_)\n  {\n    ocv_mask = ShallowCopyItkToOpenCV(this->mask_.GetPointer());\n  }\n\n  // the mask has changed, we need to make sure the weights are recomputed\n  this->need_to_recompute_weights_ = true;\n  this->compute_weights(use_mask ? &ocv_mask : nullptr);\n}\n\n", "meta": {"hexsha": "cb9aa7414c409a9676289914fc0626c2416e5df9", "size": 17497, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lib/regi/sim_metrics_2d/xregImgSimMetric2DPatchNCCOCL.cpp", "max_stars_repo_name": "rg2/xreg", "max_stars_repo_head_hexsha": "c06440d7995f8a441420e311bb7b6524452843d3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 30.0, "max_stars_repo_stars_event_min_datetime": "2020-09-29T18:36:13.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T09:25:13.000Z", "max_issues_repo_path": "lib/regi/sim_metrics_2d/xregImgSimMetric2DPatchNCCOCL.cpp", "max_issues_repo_name": "gaocong13/Orthopedic-Robot-Navigation", "max_issues_repo_head_hexsha": "bf36f7de116c1c99b86c9ba50f111c3796336af0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2020-10-09T01:21:27.000Z", "max_issues_repo_issues_event_max_datetime": "2020-12-10T15:39:44.000Z", "max_forks_repo_path": "lib/regi/sim_metrics_2d/xregImgSimMetric2DPatchNCCOCL.cpp", "max_forks_repo_name": "rg2/xreg", "max_forks_repo_head_hexsha": "c06440d7995f8a441420e311bb7b6524452843d3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2021-05-25T05:14:48.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-26T12:29:50.000Z", "avg_line_length": 36.0762886598, "max_line_length": 121, "alphanum_fraction": 0.6853746357, "num_tokens": 4447, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7122321842389469, "lm_q2_score": 0.476579651063676, "lm_q1q2_score": 0.3394353658409171}}
{"text": "/**\n * @author Manuel Guenther <manuel.guenther@idiap.ch>\n * @date Thu Jun  5 17:47:55 CEST 2014\n *\n * @brief The C++ implementations of the Gabor jet similarities and disparity computation\n *\n * Copyright (C) 2011-2014 Idiap Research Institute, Martigny, Switzerland\n */\n\n#include <bob.ip.gabor/Similarity.h>\n#include <boost/assign.hpp>\n\n\nstatic const std::map<bob::ip::gabor::Similarity::SimilarityType, std::string> type_map = boost::assign::map_list_of\n  (bob::ip::gabor::Similarity::SCALAR_PRODUCT, \"ScalarProduct\")\n  (bob::ip::gabor::Similarity::CANBERRA, \"Canberra\")\n  (bob::ip::gabor::Similarity::ABS_PHASE, \"AbsPhase\")\n  (bob::ip::gabor::Similarity::DISPARITY, \"Disparity\")\n  (bob::ip::gabor::Similarity::PHASE_DIFF, \"PhaseDiff\")\n  (bob::ip::gabor::Similarity::PHASE_DIFF_PLUS_CANBERRA, \"PhaseDiffPlusCanberra\")\n  ;\n\nconst std::string& bob::ip::gabor::Similarity::type_to_name(bob::ip::gabor::Similarity::SimilarityType type){\n  return type_map.find(type)->second;\n}\n\nbob::ip::gabor::Similarity::SimilarityType bob::ip::gabor::Similarity::name_to_type(const std::string& type){\n  for (auto it = type_map.begin(); it != type_map.end(); ++it)\n    if (it->second == type)\n      return it->first;\n  throw std::runtime_error(\"The given similarity name '\" + type + \"' does not name an appropriate similarity function type.\");\n}\n\nbob::ip::gabor::Similarity::Similarity(SimilarityType type, boost::shared_ptr<Transform> gwt)\n:\n  m_type(type),\n  m_gwt(gwt),\n  m_disparity(std::numeric_limits<double>::quiet_NaN(), std::numeric_limits<double>::quiet_NaN())\n{\n  // initialize, when required\n  if (m_type >= DISPARITY){\n    if (!m_gwt)\n      throw std::runtime_error(\"The given similarity function type '\" + type_to_name(m_type) + \"' required to specify the Gabor wavelet transform!\");\n    init();\n  }\n}\n\nbob::ip::gabor::Similarity::Similarity(bob::io::base::HDF5File& file)\n{\n  // load configuration from file\n  load(file);\n}\n\nstatic double sqr(double x){return x*x;}\n\nvoid bob::ip::gabor::Similarity::init(){\n  m_confidences.resize(m_gwt->numberOfWavelets());\n  m_confidences = 0.;\n  m_phase_differences.resize(m_gwt->numberOfWavelets());\n  m_phase_differences = 0.;\n}\n\ndouble bob::ip::gabor::Similarity::similarity(const Jet& jet1, const Jet& jet2) const{\n  // compute the disparity, if required\n  if (m_type < DISPARITY){\n    switch (m_type){\n      case SCALAR_PRODUCT:\n        // normalized scalar product (we assume normalized Gabor jets here!)\n        return blitz::dot(jet1.abs(), jet2.abs());\n      case CANBERRA:{\n        // Canberra similarity\n        double sim = 0.;\n        const auto& a1 = jet1.abs(),& a2 = jet2.abs();\n        int size = jet1.length();\n        for (int j = 0; j < size; ++j){\n          sim += 1. - std::abs(a1(j) - a2(j)) / (a1(j) + a2(j));\n        }\n        return sim / size;\n      }\n      case ABS_PHASE:{\n        // similarity with absloute values and cosine of phase differences\n        double sim = 0.;\n        const auto& a1 = jet1.abs(),& a2 = jet2.abs();\n        const auto& p1 = jet1.phase(),& p2 = jet2.phase();\n        int size = jet1.length();\n        for (int j = 0; j < size; ++j){\n          sim += a1(j) * a2(j) * cos(p1(j) - p2(j));\n        }\n        return sim;\n      }\n      default:\n        throw std::runtime_error(\"This should not have happened. Please assure that newly generated Gabor jet similarity functions are actually implemented!\");\n    }\n\n  } else {\n    // here only the disparity-related functions should be computed\n    // compute disparity\n    disparity(jet1, jet2);\n\n    const std::vector<blitz::TinyVector<double,2> >& kernels = m_gwt->waveletFrequencies();\n\n    switch (m_type){\n      case DISPARITY:{\n        // compute the similarity using the estimated disparity\n        double sum = 0.;\n        for (int j = 0; j < m_confidences.extent(0); ++j){\n          sum += m_confidences(j) * cos(m_phase_differences(j) - m_disparity[0] * kernels[j][0] - m_disparity[1] * kernels[j][1]);\n        }\n        return sum;\n      } // DISPARITY\n\n      case PHASE_DIFF:{\n        // compute the similarity using the estimated disparity\n        double sum = 0.;\n        for (int j = 0; j < m_phase_differences.extent(0); ++j){\n          sum += cos(m_phase_differences(j) - m_disparity[0] * kernels[j][0] - m_disparity[1] * kernels[j][1]);\n        }\n        return sum / jet1.length();\n      } // PHASE_DIFF\n\n      case PHASE_DIFF_PLUS_CANBERRA:{\n        // compute the similarity using the estimated disparity\n        double sum = 0.;\n        const auto& a1 = jet1.abs(),& a2 = jet2.abs();\n        for (int j = 0; j < m_phase_differences.extent(0); ++j){\n          // add disparity term\n          sum += cos(m_phase_differences(j) - m_disparity[0] * kernels[j][0] - m_disparity[1] * kernels[j][1]);\n          // add Canberra term\n          sum += 1. - std::abs(a1(j) - a2(j)) / (a1(j) + a2(j));\n        }\n        return sum / (2. * jet1.length());\n      }\n\n      default:\n        // this should never happen\n        throw std::runtime_error(\"This should not have happened. Please check the implementation of the similarity() functions.\");\n    }\n  }\n}\n\n\n/////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n////////////////  Disparity estimation  /////////////////////////////////////////////////////////////////////////\n/////////////////////////////////////////////////////////////////////////////////////////////////////////////////\nblitz::TinyVector<double,2> bob::ip::gabor::Similarity::disparity(const Jet& jet1, const Jet& jet2) const{\n\n  // Here, only the disparity based similarity functions are executed\n  bob::core::array::assertCZeroBaseContiguous(jet1.jet());\n  bob::core::array::assertCZeroBaseContiguous(jet2.jet());\n  bob::core::array::assertSameShape(jet1.jet(),jet2.jet());\n\n  // compute confidence vectors\n  compute_confidences(jet1, jet2);\n\n  // now, compute the disparity\n  compute_disparity();\n\n  // return the disparity\n  return m_disparity;\n}\n\nstatic double adjustPhase(double phase){\n  return phase - (2.*M_PI)*round(phase / (2.*M_PI));\n}\n\nvoid bob::ip::gabor::Similarity::shift_phase(const Jet& jet, const Jet& reference, Jet& shifted) const{\n  bob::core::array::assertSameShape(jet.jet(),reference.jet());\n  bob::core::array::assertSameShape(jet.jet(),shifted.jet());\n\n  // compute disparity between jet and reference jet\n  disparity(jet, reference);\n\n  // compute phase shift for each jet entry based on disparity vector\n  const std::vector<blitz::TinyVector<double,2>>& kernels = m_gwt->waveletFrequencies();\n  auto& data = shifted.jet();\n  // copy data from original jet\n  data = jet.jet();\n  // shift phases according to the computed disparity\n  for (int j = 0; j < m_phase_differences.extent(0); ++j){\n    data(1,j) = adjustPhase(data(1,j) - m_disparity[0] * kernels[j][0] - m_disparity[1] * kernels[j][1]);\n  }\n}\n\nvoid bob::ip::gabor::Similarity::compute_confidences(const Jet& jet1, const Jet& jet2) const{\n  if (m_type < DISPARITY){\n    throw std::runtime_error(\"The disparity computation is not supported for similarity type \" + type());\n  }\n  if (jet1.length() != m_confidences.extent(0)){\n    throw std::runtime_error((boost::format(\"The size of the Gabor jet (%d) and the number of wavelets in the Gabor wavelet transform (%d) differ!\") % jet1.length() % m_confidences.extent(0)).str());\n  }\n  // first, fill confidence and phase difference vectors\n  const auto& a1 = jet1.abs(),& a2 = jet2.abs(),& p1 = jet1.phase(),& p2 = jet2.phase();\n  for (int j = 0; j < m_confidences.extent(0); ++j){\n    m_confidences(j) = a1(j) * a2(j);\n    m_phase_differences(j) = adjustPhase(p1(j) - p2(j));\n  }\n}\n\nvoid bob::ip::gabor::Similarity::compute_disparity() const{\n  // approximate the disparity from the phase differences\n  double gamma_x_x = 0., gamma_x_y = 0., gamma_y_y = 0., phi_x = 0., phi_y = 0.;\n  // initialize the disparity with 0\n  m_disparity = 0.;\n\n  const std::vector<blitz::TinyVector<double,2> >& kernels = m_gwt->waveletFrequencies();\n  // iterate backwards through the vector to start with the lowest frequency wavelets\n  for (int j = m_confidences.extent(0)-1, level = m_gwt->numberOfScales()-1; level >= 0; --level){\n    for (int direction = m_gwt->numberOfDirections()-1; direction >= 0; --direction, --j){\n      double\n          kjx = kernels[j][1],\n          kjy = kernels[j][0],\n          conf = m_confidences(j),\n          diff = m_phase_differences(j);\n\n      // totalize gamma matrix\n      gamma_x_x += kjx * kjx * conf;\n      gamma_x_y += kjx * kjy * conf;\n      gamma_y_y += kjy * kjy * conf;\n\n      // totalize phi vector\n      // estimate the number of cycles that we are off\n      double nL = round((diff - m_disparity[1] * kjx - m_disparity[0] * kjy) / (2.*M_PI));\n      // totalize corrected phi vector elements\n      phi_x += (diff - nL * 2. * M_PI) * conf * kjx;\n      phi_y += (diff - nL * 2. * M_PI) * conf * kjy;\n    } // for direction\n\n    // re-calculate disparity as d=\\Gamma^{-1}\\Phi of the (low frequency) wavelet scales that we used up to now\n    double gamma_det = gamma_x_x * gamma_y_y - sqr(gamma_x_y);\n    m_disparity[1] = (gamma_y_y * phi_x - gamma_x_y * phi_y) / gamma_det;\n    m_disparity[0] = (gamma_x_x * phi_y - gamma_x_y * phi_x) / gamma_det;\n  } // for level\n}\n\n\nvoid bob::ip::gabor::Similarity::save(bob::io::base::HDF5File& file) const{\n\n  file.set(\"Type\", type_to_name(m_type));\n  if (m_type >= DISPARITY){\n    file.createGroup(\"Transform\");\n    file.cd(\"Transform\");\n    m_gwt->save(file);\n    file.cd(\"..\");\n  }\n}\n\n\nvoid bob::ip::gabor::Similarity::load(bob::io::base::HDF5File& file){\n  // read value\n  m_type = name_to_type(file.read<std::string>(\"Type\"));\n\n  if (m_type >= DISPARITY){\n    file.cd(\"Transform\");\n    m_gwt.reset(new Transform(file));\n    file.cd(\"..\");\n\n    init();\n  }\n}\n\n", "meta": {"hexsha": "7ad6b1282c17555fb42aabfb78817d10add0fe9e", "size": 9790, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "bob/ip/gabor/cpp/Similarity.cpp", "max_stars_repo_name": "bioidiap/bob.ip.gabor", "max_stars_repo_head_hexsha": "262605112403dd35569b2e36760456649396d6fa", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2015-02-19T22:45:22.000Z", "max_stars_repo_stars_event_max_datetime": "2019-08-14T23:58:48.000Z", "max_issues_repo_path": "bob/ip/gabor/cpp/Similarity.cpp", "max_issues_repo_name": "bioidiap/bob.ip.gabor", "max_issues_repo_head_hexsha": "262605112403dd35569b2e36760456649396d6fa", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "bob/ip/gabor/cpp/Similarity.cpp", "max_forks_repo_name": "bioidiap/bob.ip.gabor", "max_forks_repo_head_hexsha": "262605112403dd35569b2e36760456649396d6fa", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2015-03-22T09:50:01.000Z", "max_forks_repo_forks_event_max_datetime": "2016-03-08T11:16:07.000Z", "avg_line_length": 37.5095785441, "max_line_length": 199, "alphanum_fraction": 0.6208375894, "num_tokens": 2726, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6893056295505783, "lm_q2_score": 0.49218813572079556, "lm_q1q2_score": 0.33926805275034844}}
{"text": "﻿/**\r\n * Copyright 2020 Monchack Audio\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 <iostream>\r\n\r\n#include <Windows.h>\r\n\r\n// reomve comment out below to use Boost\r\n//#include <boost/multiprecision/cpp_dec_float.hpp>\r\n\r\n// Tap size; change this number if necessary. Must be an odd number\r\n#define TAP_SIZE 16383\r\n\r\n// remove comment out below to enable high precision mode\r\n//#define HIGH_PRECISION 1\r\n\r\n#define DATA_UNIT_SIZE (1024 * 1024)\r\n\r\n// 16(15+1)bit  X  scale: 48(47+1)bit =  63(62+1)bit -> 32bit (31bit shift)\r\n#define COEFF_SCALE 47\r\n#define SCALE_SHIFT 31\r\n\r\n#if !defined(BOOST_VERSION)\r\n\r\nvoid createHannCoeff(int tapNum, long long* dest, double* dest2)\r\n{\r\n\tint coeffNum = (tapNum + 1) / 2;\r\n\tdouble* coeff1 = (double*)::GlobalAlloc(GPTR, sizeof(double) * coeffNum);\r\n\tdouble* coeff2 = (double*)::GlobalAlloc(GPTR, sizeof(double) * coeffNum);\r\n\tdouble* coeff3 = (double*)::GlobalAlloc(GPTR, sizeof(double) * coeffNum);\r\n\tdouble pi = 3.141592653589793;\r\n\r\n\tcoeff1[0] = 2.0f * (22050.0f / 352800.0f);\r\n\tfor (int i = 1; i < coeffNum; ++i)\r\n\t{\r\n\t\tdouble x = i * 2.0f * pi * (22050.0f / 352800.0f);\r\n\t\tcoeff1[i] = sin(x) / (pi * i);\r\n\t}\r\n\r\n\tfor (int i = 0; i < coeffNum; ++i)\r\n\t{\r\n\t\tdouble x = 2.0f * pi * i / (double)(tapNum - 1);\r\n\t\tcoeff2[i] = 0.5f + 0.5f * cos(x);\r\n\t}\r\n\tcoeff2[coeffNum - 1] = 0;\r\n\r\n\tlong long scale = 1LL << (COEFF_SCALE + 3);\r\n\r\n\tfor (int i = 0; i < coeffNum; ++i)\r\n\t{\r\n\t\tcoeff3[i] = coeff1[i] * coeff2[i] * scale;\r\n\t}\r\n\r\n\tdest[coeffNum - 1] = (long long)round(coeff3[0]);\r\n\tdest2[coeffNum - 1] = (double)(coeff3[0] - round(coeff3[0]));\r\n\tfor (int i = 1; i < coeffNum; ++i)\r\n\t{\r\n\t\tdest[coeffNum - 1 + i] = (long long)round(coeff3[i]);\r\n\t\tdest[coeffNum - 1 - i] = (long long)round(coeff3[i]);\r\n\t\tdest2[coeffNum - 1 + i] = (double)(coeff3[i] - round(coeff3[i]));\r\n\t\tdest2[coeffNum - 1 - i] = (double)(coeff3[i] - round(coeff3[i]));\r\n\t}\r\n\t::GlobalFree(coeff1);\r\n\t::GlobalFree(coeff2);\r\n\t::GlobalFree(coeff3);\r\n}\r\n\r\n#else\r\n\r\nusing namespace boost::multiprecision;\r\nusing boost::math::constants::pi;\r\n\r\nvoid createHannCoeff(int tapNum, long long* dest, double* dest2)\r\n{\r\n\tint coeffNum = (tapNum + 1) / 2;\r\n\tcpp_dec_float_100* coeff1 = (cpp_dec_float_100*)::GlobalAlloc(GPTR, sizeof(cpp_dec_float_100) * coeffNum);\r\n\tcpp_dec_float_100* coeff2 = (cpp_dec_float_100*)::GlobalAlloc(GPTR, sizeof(cpp_dec_float_100) * coeffNum);\r\n\tcpp_dec_float_100* coeff3 = (cpp_dec_float_100*)::GlobalAlloc(GPTR, sizeof(cpp_dec_float_100) * coeffNum);\r\n\r\n\tcpp_dec_float_100 piq = pi<cpp_dec_float_100>();\r\n\r\n\tcoeff1[0] = cpp_dec_float_100(2) * 22050 / 352800;\r\n\tfor (int i = 1; i < coeffNum; ++i)\r\n\t{\r\n\t\tcpp_dec_float_100 x = cpp_dec_float_100(i) * 2 * piq * 22050 / 352800;\r\n\t\tcoeff1[i] = boost::multiprecision::sin(x) / (piq * i);\r\n\t}\r\n\r\n\tfor (int i = 0; i < coeffNum; ++i)\r\n\t{\r\n\t\tcpp_dec_float_100 x = cpp_dec_float_100(2) * piq * i / (tapNum - 1);\r\n\t\tcoeff2[i] = cpp_dec_float_100(\"0.5\") + cpp_dec_float_100(\"0.5\") * boost::multiprecision::cos(x);\r\n\t}\r\n\tcoeff2[coeffNum - 1] = 0;\r\n\r\n\tlong long scale = 1LL << (COEFF_SCALE + 3);\r\n\r\n\tfor (int i = 0; i < coeffNum; ++i)\r\n\t{\r\n\t\tcoeff3[i] = coeff1[i] * coeff2[i] * scale;\r\n\t\t//coeff3[i] = boost::multiprecision::round(coeff1[i] * coeff2[i] * scale);\r\n\t}\r\n\r\n\tdest[coeffNum - 1] = (long long)boost::multiprecision::round(coeff3[0]);\r\n\tdest2[coeffNum - 1] = (double)(coeff3[0] - boost::multiprecision::round(coeff3[0]));\r\n\tfor (int i = 1; i < coeffNum; ++i)\r\n\t{\r\n\t\tcpp_dec_float_100 x = boost::multiprecision::round(coeff3[i]);\r\n\t\tdest[coeffNum - 1 + i] = (long long)x;\r\n\t\tdest[coeffNum - 1 - i] = (long long)x;\r\n\t\tdest2[coeffNum - 1 + i] = (double)(coeff3[i] - x);\r\n\t\tdest2[coeffNum - 1 - i] = (double)(coeff3[i] - x);\r\n\t}\r\n\t::GlobalFree(coeff1);\r\n\t::GlobalFree(coeff2);\r\n\t::GlobalFree(coeff3);\r\n}\r\n\r\n#endif\r\n\r\nstatic void writeRaw32bitPCM(long long left, long long right, int* buffer)\r\n{\r\n\tint shift = SCALE_SHIFT;\r\n\r\n\tint add = 1 << (shift - 1);\r\n\tleft += add;\r\n\tright += add;\r\n\r\n\tif (left >= 4611686018427387904) left = 4611686018427387904 - 1; // over 63bit : limitted to under [1 << 62]   62bit + 1bit\r\n\tif (right >= 4611686018427387904) right = 4611686018427387904 - 1;\r\n\r\n\tif (left < -4611686018427387904) left = -4611686018427387904;\r\n\tif (right < -4611686018427387904) right = -4611686018427387904;\r\n\r\n\tleft = left >> shift;\r\n\tright = right >> shift;\r\n\r\n\tbuffer[0] = (int)left;\r\n\tbuffer[1] = (int)right;\r\n}\r\n\r\nint  oversample(short* src, unsigned int length, long long* coeff, double* coeff2, int tapNum, int* dest, unsigned int option)\r\n{\r\n\tint half_size = (tapNum - 1) / 2;\r\n\tif (option == 0) option = 0xffff;\r\n\r\n\tfor (unsigned int i = 0; i < length; ++i)\r\n\t{\r\n\t\tshort *srcLeft = src;\r\n\t\tshort *srcRight = src + 1;\r\n\t\tlong long tmpLeft, tmpRight;\r\n\t\tdouble tmpLeft2, tmpRight2;\r\n\r\n\t\tif (option & 0x0001)\r\n\t\t{\r\n\t\t\t// 1st \r\n\t\t\ttmpLeft = *srcLeft * coeff[half_size];\r\n\t\t\ttmpRight = *srcRight * coeff[half_size];\r\n\t\t\twriteRaw32bitPCM(tmpLeft, tmpRight, dest);\r\n\t\t}\r\n\r\n\t\tif (option & 0x0002)\r\n\t\t{\r\n\t\t\t// 2nd \r\n\t\t\ttmpLeft = 0;\r\n\t\t\ttmpRight = 0;\r\n\t\t\ttmpLeft2 = 0.0;\r\n\t\t\ttmpRight2 = 0.0;\r\n\t\t\t// src[1] * coeff[ 7]  +  src[ 2] * coeff[15]  +  src[ 3] * coeff[ 23]  + ...    \r\n\t\t\t// src[0] * coeff[-1]  +  src[-1] * coeff[-9]  +  src[-2] * coeff[-17]  + ...\r\n\t\t\tfor (int j = 1; (j * 8 - 1) <= half_size; ++j)\r\n\t\t\t{\r\n\t\t\t\ttmpLeft += (long long)*(srcLeft + j * 2) * coeff[half_size + j * 8 - 1];\r\n\t\t\t\ttmpRight += (long long)*(srcRight + j * 2) *coeff[half_size + j * 8 - 1];\r\n\r\n\t\t\t\t#if defined(HIGH_PRECISION)\r\n\t\t\t\ttmpLeft2 += (double)*(srcLeft + j * 2) * coeff2[half_size + j * 8 - 1];\r\n\t\t\t\ttmpRight2 += (double)*(srcRight + j * 2) *coeff2[half_size + j * 8 - 1];\r\n\t\t\t\t#endif\r\n\t\t\t}\r\n\t\t\tfor (int j = 0; (j * 8 + 1) <= half_size; ++j)\r\n\t\t\t{\r\n\t\t\t\ttmpLeft += (long long)*(srcLeft - j * 2) * coeff[half_size - j * 8 - 1];\r\n\t\t\t\ttmpRight += (long long)*(srcRight - j * 2) * coeff[half_size - j * 8 - 1];\r\n\r\n\t\t\t\t#if defined(HIGH_PRECISION)\r\n\t\t\t\ttmpLeft2 += (double)*(srcLeft - j * 2) * coeff2[half_size - j * 8 - 1];\r\n\t\t\t\ttmpRight2 += (double)*(srcRight - j * 2) *coeff2[half_size - j * 8 - 1];\r\n\t\t\t\t#endif\r\n\t\t\t}\r\n\t\t\ttmpLeft += (long long)tmpLeft2;\r\n\t\t\ttmpRight += (long long)tmpRight2;\r\n\t\t\twriteRaw32bitPCM(tmpLeft, tmpRight, dest + 2);\r\n\t\t}\r\n\r\n\t\tif (option & 0x0004)\r\n\t\t{\r\n\t\t\t// 3rd \r\n\t\t\ttmpLeft = 0;\r\n\t\t\ttmpRight = 0;\r\n\t\t\ttmpLeft2 = 0.0;\r\n\t\t\ttmpRight2 = 0.0;\r\n\t\t\t// src[1] * coeff[ 6]  +  src[ 2] * coeff[ 14]  +  src[ 3] * coeff[ 22]  + ...    \r\n\t\t\t// src[0] * coeff[-2]  +  src[-1] * coeff[-10]  +  src[-2] * coeff[-18]  + ...\r\n\t\t\tfor (int j = 1; (j * 8 - 2) <= half_size; ++j)\r\n\t\t\t{\r\n\t\t\t\ttmpLeft += (long long)*(srcLeft + j * 2) * coeff[half_size + j * 8 - 2];\r\n\t\t\t\ttmpRight += (long long)*(srcRight + j * 2) * coeff[half_size + j * 8 - 2];\r\n\t\t\t\t#if defined(HIGH_PRECISION)\r\n\t\t\t\ttmpLeft2 += (double)*(srcLeft + j * 2) * coeff2[half_size + j * 8 - 2];\r\n\t\t\t\ttmpRight2 += (double)*(srcRight + j * 2) *coeff2[half_size + j * 8 - 2];\r\n\t\t\t\t#endif\r\n\t\t\t}\r\n\t\t\tfor (int j = 0; (j * 8 + 2) <= half_size; ++j)\r\n\t\t\t{\r\n\t\t\t\ttmpLeft += (long long)*(srcLeft - j * 2) * coeff[half_size - j * 8 - 2];\r\n\t\t\t\ttmpRight += (long long)*(srcRight - j * 2) * coeff[half_size - j * 8 - 2];\r\n\t\t\t\t#if defined(HIGH_PRECISION)\r\n\t\t\t\ttmpLeft2 += (double)*(srcLeft - j * 2) * coeff2[half_size - j * 8 - 2];\r\n\t\t\t\ttmpRight2 += (double)*(srcRight - j * 2) *coeff2[half_size - j * 8 - 2];\r\n\t\t\t\t#endif\r\n\t\t\t}\r\n\t\t\ttmpLeft += (long long)tmpLeft2;\r\n\t\t\ttmpRight += (long long)tmpRight2;\r\n\t\t\twriteRaw32bitPCM(tmpLeft, tmpRight, dest + 4);\r\n\t\t}\r\n\r\n\t\tif (option & 0x0008)\r\n\t\t{\r\n\t\t\t// 4th\r\n\t\t\ttmpLeft = 0;\r\n\t\t\ttmpRight = 0;\r\n\t\t\ttmpLeft2 = 0.0;\r\n\t\t\ttmpRight2 = 0.0;\r\n\t\t\tfor (int j = 1; (j * 8 - 3) <= half_size; ++j)\r\n\t\t\t{\r\n\t\t\t\ttmpLeft += (long long)*(srcLeft + j * 2) * coeff[half_size + j * 8 - 3];\r\n\t\t\t\ttmpRight += (long long)*(srcRight + j * 2) * coeff[half_size + j * 8 - 3];\r\n\t\t\t\t#if defined(HIGH_PRECISION)\r\n\t\t\t\ttmpLeft2 += (double)*(srcLeft + j * 2) * coeff2[half_size + j * 8 - 3];\r\n\t\t\t\ttmpRight2 += (double)*(srcRight + j * 2) *coeff2[half_size + j * 8 - 3];\r\n\t\t\t\t#endif\r\n\t\t\t}\r\n\t\t\tfor (int j = 0; (j * 8 + 3) <= half_size; ++j)\r\n\t\t\t{\r\n\t\t\t\ttmpLeft += (long long)*(srcLeft - j * 2) * coeff[half_size - j * 8 - 3];\r\n\t\t\t\ttmpRight += (long long)*(srcRight - j * 2) * coeff[half_size - j * 8 - 3];\r\n\t\t\t\t#if defined(HIGH_PRECISION)\r\n\t\t\t\ttmpLeft2 += (double)*(srcLeft - j * 2) * coeff2[half_size - j * 8 - 3];\r\n\t\t\t\ttmpRight2 += (double)*(srcRight - j * 2) *coeff2[half_size - j * 8 - 3];\r\n\t\t\t\t#endif\r\n\t\t\t}\r\n\t\t\ttmpLeft += (long long)tmpLeft2;\r\n\t\t\ttmpRight += (long long)tmpRight2;\r\n\t\t\twriteRaw32bitPCM(tmpLeft, tmpRight, dest + 6);\r\n\t\t}\r\n\r\n\t\tif (option & 0x0010)\r\n\t\t{\r\n\t\t\t//5th\r\n\t\t\ttmpLeft = 0;\r\n\t\t\ttmpRight = 0;\r\n\t\t\ttmpLeft2 = 0.0;\r\n\t\t\ttmpRight2 = 0.0;\r\n\t\t\tfor (int j = 1; (j * 8 - 4) <= half_size; ++j)\r\n\t\t\t{\r\n\t\t\t\ttmpLeft += (long long)*(srcLeft + j * 2) * coeff[half_size + j * 8 - 4];\r\n\t\t\t\ttmpRight += (long long)*(srcRight + j * 2) * coeff[half_size + j * 8 - 4];\r\n\t\t\t\t#if defined(HIGH_PRECISION)\r\n\t\t\t\ttmpLeft2 += (double)*(srcLeft + j * 2) * coeff2[half_size + j * 8 - 4];\r\n\t\t\t\ttmpRight2 += (double)*(srcRight + j * 2) *coeff2[half_size + j * 8 - 4];\r\n\t\t\t\t#endif\r\n\t\t\t}\r\n\t\t\tfor (int j = 0; (j * 8 + 4) <= half_size; ++j)\r\n\t\t\t{\r\n\t\t\t\ttmpLeft += (long long)*(srcLeft - j * 2) * coeff[half_size - j * 8 - 4];\r\n\t\t\t\ttmpRight += (long long)*(srcRight - j * 2) * coeff[half_size - j * 8 - 4];\r\n\t\t\t\t#if defined(HIGH_PRECISION)\r\n\t\t\t\ttmpLeft2 += (double)*(srcLeft - j * 2) * coeff2[half_size - j * 8 - 4];\r\n\t\t\t\ttmpRight2 += (double)*(srcRight - j * 2) *coeff2[half_size - j * 8 - 4];\r\n\t\t\t\t#endif\r\n\t\t\t}\r\n\t\t\ttmpLeft += (long long)tmpLeft2;\r\n\t\t\ttmpRight += (long long)tmpRight2;\r\n\t\t\twriteRaw32bitPCM(tmpLeft, tmpRight, dest + 8);\r\n\t\t}\r\n\r\n\t\tif (option & 0x0020)\r\n\t\t{\r\n\t\t\t//6th\r\n\t\t\ttmpLeft = 0;\r\n\t\t\ttmpRight = 0;\r\n\t\t\ttmpLeft2 = 0.0;\r\n\t\t\ttmpRight2 = 0.0;\r\n\t\t\tfor (int j = 1; (j * 8 - 5) <= half_size; ++j)\r\n\t\t\t{\r\n\t\t\t\ttmpLeft += (long long)*(srcLeft + j * 2) * coeff[half_size + j * 8 - 5];\r\n\t\t\t\ttmpRight += (long long)*(srcRight + j * 2) * coeff[half_size + j * 8 - 5];\r\n\t\t\t\t#if defined(HIGH_PRECISION)\r\n\t\t\t\ttmpLeft2 += (double)*(srcLeft + j * 2) * coeff2[half_size + j * 8 - 5];\r\n\t\t\t\ttmpRight2 += (double)*(srcRight + j * 2) *coeff2[half_size + j * 8 - 5];\r\n\t\t\t\t#endif\r\n\t\t\t}\r\n\t\t\tfor (int j = 0; (j * 8 + 5) <= half_size; ++j)\r\n\t\t\t{\r\n\t\t\t\ttmpLeft += (long long)*(srcLeft - j * 2) * coeff[half_size - j * 8 - 5];\r\n\t\t\t\ttmpRight += (long long)*(srcRight - j * 2) * coeff[half_size - j * 8 - 5];\r\n\t\t\t\t#if defined(HIGH_PRECISION)\r\n\t\t\t\ttmpLeft2 += (double)*(srcLeft - j * 2) * coeff2[half_size - j * 8 - 5];\r\n\t\t\t\ttmpRight2 += (double)*(srcRight - j * 2) *coeff2[half_size - j * 8 - 5];\r\n\t\t\t\t#endif\r\n\t\t\t}\r\n\t\t\ttmpLeft += (long long)tmpLeft2;\r\n\t\t\ttmpRight += (long long)tmpRight2;\r\n\t\t\twriteRaw32bitPCM(tmpLeft, tmpRight, dest + 10);\r\n\t\t}\r\n\r\n\t\tif (option & 0x0040)\r\n\t\t{\r\n\t\t\t//7th\r\n\t\t\ttmpLeft = 0;\r\n\t\t\ttmpRight = 0;\r\n\t\t\ttmpLeft2 = 0.0;\r\n\t\t\ttmpRight2 = 0.0;\r\n\t\t\tfor (int j = 1; (j * 8 - 6) <= half_size; ++j)\r\n\t\t\t{\r\n\t\t\t\ttmpLeft += (long long)*(srcLeft + j * 2) * coeff[half_size + j * 8 - 6];\r\n\t\t\t\ttmpRight += (long long)*(srcRight + j * 2) * coeff[half_size + j * 8 - 6];\r\n\t\t\t\t#if defined(HIGH_PRECISION)\r\n\t\t\t\ttmpLeft2 += (double)*(srcLeft + j * 2) * coeff2[half_size + j * 8 - 6];\r\n\t\t\t\ttmpRight2 += (double)*(srcRight + j * 2) *coeff2[half_size + j * 8 - 6];\r\n\t\t\t\t#endif\r\n\t\t\t}\r\n\t\t\tfor (int j = 0; (j * 8 + 6) <= half_size; ++j)\r\n\t\t\t{\r\n\t\t\t\ttmpLeft += (long long)*(srcLeft - j * 2) * coeff[half_size - j * 8 - 6];\r\n\t\t\t\ttmpRight += (long long)*(srcRight - j * 2) * coeff[half_size - j * 8 - 6];\r\n\t\t\t\t#if defined(HIGH_PRECISION)\r\n\t\t\t\ttmpLeft2 += (double)*(srcLeft - j * 2) * coeff2[half_size - j * 8 - 6];\r\n\t\t\t\ttmpRight2 += (double)*(srcRight - j * 2) *coeff2[half_size - j * 8 - 6];\r\n\t\t\t\t#endif\r\n\t\t\t}\r\n\t\t\ttmpLeft += (long long)tmpLeft2;\r\n\t\t\ttmpRight += (long long)tmpRight2;\r\n\t\t\twriteRaw32bitPCM(tmpLeft, tmpRight, dest + 12);\r\n\t\t}\r\n\t\r\n\t\tif (option & 0x0080)\r\n\t\t{\r\n\t\t\t//8th\r\n\t\t\ttmpLeft = 0;\r\n\t\t\ttmpRight = 0;\r\n\t\t\ttmpLeft2 = 0.0;\r\n\t\t\ttmpRight2 = 0.0;\r\n\t\t\tfor (int j = 1; (j * 8 - 7) <= half_size; ++j)\r\n\t\t\t{\r\n\t\t\t\ttmpLeft += (long long)*(srcLeft + j * 2) * coeff[half_size + j * 8 - 7];\r\n\t\t\t\ttmpRight += (long long)*(srcRight + j * 2) * coeff[half_size + j * 8 - 7];\r\n\t\t\t\t#if defined(HIGH_PRECISION)\r\n\t\t\t\ttmpLeft2 += (double)*(srcLeft + j * 2) * coeff2[half_size + j * 8 - 7];\r\n\t\t\t\ttmpRight2 += (double)*(srcRight + j * 2) *coeff2[half_size + j * 8 - 7];\r\n\t\t\t\t#endif\r\n\t\t\t}\r\n\t\t\tfor (int j = 0; (j * 8 + 7) <= half_size; ++j)\r\n\t\t\t{\r\n\t\t\t\ttmpLeft += (long long)*(srcLeft - j * 2) * coeff[half_size - j * 8 - 7];\r\n\t\t\t\ttmpRight += (long long)*(srcRight - j * 2) * coeff[half_size - j * 8 - 7];\r\n\t\t\t\t#if defined(HIGH_PRECISION)\r\n\t\t\t\ttmpLeft2 += (double)*(srcLeft - j * 2) * coeff2[half_size - j * 8 - 7];\r\n\t\t\t\ttmpRight2 += (double)*(srcRight - j * 2) *coeff2[half_size - j * 8 - 7];\r\n\t\t\t\t#endif\r\n\t\t\t}\r\n\t\t\ttmpLeft += (long long)tmpLeft2;\r\n\t\t\ttmpRight += (long long)tmpRight2;\r\n\t\t\twriteRaw32bitPCM(tmpLeft, tmpRight, dest + 14);\r\n\t\t}\r\n\r\n\t\tsrc += 2;\r\n\t\tdest += 8 * 2;\r\n\t}\r\n\r\n\treturn 0;\r\n}\r\n\r\nstruct oversample_info\r\n{\r\n\tshort* src;\r\n\tunsigned int length;\r\n\tlong long* coeff;\r\n\tdouble* coeff2;\r\n\tint tapNum;\r\n\tint* dest;\r\n\tunsigned int option;\r\n};\r\n\r\nDWORD WINAPI ThreadFunc(LPVOID arg)\r\n{\r\n\tstruct oversample_info* info = (struct oversample_info*)arg;\r\n\toversample(info->src, info->length, info->coeff, info->coeff2, info->tapNum, info->dest, info->option);\r\n\treturn 0;\r\n}\r\n\r\nunsigned int searchFmtDataChunk(wchar_t* fileName, WAVEFORMATEX* wf, DWORD* offset, DWORD* size)\r\n{\r\n\tHANDLE fileHandle;\r\n\tfileHandle = CreateFileW(fileName, GENERIC_READ, 0, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);\r\n\tif (fileHandle == INVALID_HANDLE_VALUE)\r\n\t{\r\n\t\treturn 0;\r\n\t}\r\n\r\n\tDWORD header[2];\r\n\tDWORD readSize;\r\n\tWORD  wav[8];\r\n\tDWORD riffSize, pos = 0;\r\n\tDWORD dataOffset, dataSize;\r\n\t::ReadFile(fileHandle, header, 8, &readSize, NULL);\r\n\tbool fmtFound = false, dataFound = false;\r\n\r\n\tif (readSize != 8)\r\n\t{\r\n\t\tCloseHandle(fileHandle);\r\n\t\treturn 0;\r\n\t}\r\n\r\n\tif (header[0] != 0x46464952)\r\n\t{\r\n\t\t// not \"RIFF\"\r\n\t\tCloseHandle(fileHandle);\r\n\t\treturn 0;\r\n\t}\r\n\triffSize = header[1];\r\n\r\n\t::ReadFile(fileHandle, header, 4, &readSize, NULL);\r\n\tif (readSize != 4)\r\n\t{\r\n\t\tCloseHandle(fileHandle);\r\n\t\treturn 0;\r\n\t}\r\n\tif (header[0] != 0x45564157)\r\n\t{\r\n\t\t// not \"WAVE\"\r\n\t\tCloseHandle(fileHandle);\r\n\t\treturn 0;\r\n\t}\r\n\tpos += 4;\r\n\r\n\twhile (pos < riffSize)\r\n\t{\r\n\t\t::ReadFile(fileHandle, header, 8, &readSize, NULL);\r\n\t\tif (readSize != 8)\r\n\t\t{\r\n\t\t\tbreak;\r\n\t\t}\r\n\t\tpos += 8;\r\n\r\n\t\tif (header[0] == 0x20746d66)\r\n\t\t{\r\n\t\t\t// \"fmt \"\r\n\t\t\tif (header[1] >= 16)\r\n\t\t\t{\r\n\t\t\t\t::ReadFile(fileHandle, wav, 16, &readSize, NULL);\r\n\t\t\t\tif (readSize != 16)\r\n\t\t\t\t{\r\n\t\t\t\t\tbreak;\r\n\t\t\t\t}\r\n\t\t\t\tfmtFound = true;\r\n\t\t\t\tif (header[1] > 16)\r\n\t\t\t\t{\r\n\t\t\t\t\t::SetFilePointer(fileHandle, header[1] - 16, 0, FILE_CURRENT);\r\n\t\t\t\t}\r\n\t\t\t\tpos += header[1];\r\n\t\t\t}\r\n\t\t\telse\r\n\t\t\t{\r\n\t\t\t\t::SetFilePointer(fileHandle, header[1], 0, FILE_CURRENT);\r\n\t\t\t\tpos += header[1];\r\n\t\t\t}\r\n\t\t}\r\n\t\telse if (header[0] == 0x61746164)\r\n\t\t{\r\n\t\t\t// \"data\"\r\n\t\t\tdataFound = true;\r\n\t\t\tdataOffset = ::SetFilePointer(fileHandle, 0, 0, FILE_CURRENT);\r\n\t\t\tdataSize = header[1];\r\n\t\t\t::SetFilePointer(fileHandle, header[1], 0, FILE_CURRENT);\r\n\t\t\tpos += header[1];\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\t::SetFilePointer(fileHandle, header[1], 0, FILE_CURRENT);\r\n\t\t\tpos += header[1];\r\n\t\t}\r\n\t\tif (GetLastError() != NO_ERROR)\r\n\t\t{\r\n\t\t\tbreak;\r\n\t\t}\r\n\t}\r\n\tCloseHandle(fileHandle);\r\n\r\n\tif (dataFound && fmtFound)\r\n\t{\r\n\t\t*offset = dataOffset;\r\n\t\t*size = dataSize;\r\n\t\twf->wFormatTag = wav[0]; //  1:LPCM   3:IEEE float\r\n\t\twf->nChannels = wav[1]; //  1:Mono  2:Stereo\r\n\t\twf->nSamplesPerSec = *(DWORD*)(wav + 2);  // 44100, 48000, 176400, 19200, 352800, 384000...\r\n\t\twf->nAvgBytesPerSec = *(DWORD*)(wav + 4);\r\n\t\twf->nBlockAlign = wav[6]; // 4@16bit/2ch,  6@24bit/2ch,   8@32bit/2ch   \r\n\t\twf->wBitsPerSample = wav[7]; // 16bit, 24bit, 32bit\r\n\t\twf->cbSize = 0;\r\n\t\treturn 1;\r\n\t}\r\n\treturn 0;\r\n}\r\n\r\nDWORD readWavFile(wchar_t* fileName, void* readMem, DWORD readPos, DWORD readLength)\r\n{\r\n\tHANDLE fileHandle;\r\n\tDWORD wavDataOffset, wavDataSize, readSize = 0;\r\n\tWAVEFORMATEX wf;\r\n\r\n\tif (!searchFmtDataChunk(fileName, &wf, &wavDataOffset, &wavDataSize))\r\n\t{\r\n\t\treturn 0;\r\n\t}\r\n\r\n\tfileHandle = CreateFileW(fileName, GENERIC_READ, 0, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);\r\n\tif (fileHandle == INVALID_HANDLE_VALUE)\r\n\t{\r\n\t\treturn 0;\r\n\t}\r\n\r\n\tif (::SetFilePointer(fileHandle, wavDataOffset + readPos, 0, FILE_BEGIN) == INVALID_SET_FILE_POINTER)\r\n\t{\r\n\t\tif (GetLastError() != NO_ERROR)\r\n\t\t{\r\n\t\t\t// fail\r\n\t\t\treturn 0;\r\n\t\t}\r\n\t}\r\n\t::ReadFile(fileHandle, readMem, readLength, &readSize, NULL);\r\n\t::CloseHandle(fileHandle);\r\n\r\n\treturn readSize;\r\n}\r\n\r\nstatic int writePCM352_32_header(HANDLE fileHandle, unsigned long dataSize)\r\n{\r\n\tWAVEFORMATEX wf;\r\n\twf.wFormatTag = 0x01;\r\n\twf.nChannels = 2;\r\n\twf.nSamplesPerSec = 352800;\r\n\twf.nAvgBytesPerSec = 352800 * 8; // 352800 * 4byte(32bit) * 2ch\r\n\twf.nBlockAlign = 8; // 8bytes (32bit, 2ch) per sample\r\n\twf.wBitsPerSample = 32;\r\n\twf.cbSize = 0; // ignored. not written.\r\n\r\n\tDWORD writtenSize = 0;\r\n\tWriteFile(fileHandle, \"RIFF\", 4, &writtenSize, NULL);\r\n\tDWORD size = (dataSize + 44) - 8;\r\n\tWriteFile(fileHandle, &size, 4, &writtenSize, NULL);\r\n\tWriteFile(fileHandle, \"WAVE\", 4, &writtenSize, NULL);\r\n\tWriteFile(fileHandle, \"fmt \", 4, &writtenSize, NULL);\r\n\tsize = 16;\r\n\tWriteFile(fileHandle, &size, 4, &writtenSize, NULL);\r\n\tWriteFile(fileHandle, &wf, size, &writtenSize, NULL);\r\n\tWriteFile(fileHandle, \"data\", 4, &writtenSize, NULL);\r\n\tsize = (DWORD)dataSize;\r\n\tWriteFile(fileHandle, &size, 4, &writtenSize, NULL);\r\n\r\n\treturn 0;\r\n}\r\n\r\nint wmain(int argc, wchar_t *argv[], wchar_t *envp[])\r\n{\r\n\tDWORD wavDataOffset, wavDataSize, writtenSize, length, readSize = 0;\r\n\tWAVEFORMATEX wf;\r\n\twchar_t* fileName;\r\n\twchar_t* destFileName;\r\n\r\n\tif (argc < 2) return 0;\r\n\tfileName = argv[1];\r\n\tdestFileName = argv[2];\r\n\r\n\tULONGLONG elapsedTime = GetTickCount64();\r\n\r\n\tif (!searchFmtDataChunk(fileName, &wf, &wavDataOffset, &wavDataSize))\r\n\t{\r\n\t\treturn 0;\r\n\t}\r\n\tint part = wavDataSize / DATA_UNIT_SIZE;\r\n\tif ((wavDataSize %  DATA_UNIT_SIZE) != 0) part += 1;\r\n\r\n\tvoid* mem1 = ::GlobalAlloc(GPTR, DATA_UNIT_SIZE * 3);\r\n\tvoid* mem2 = (char*)mem1 + DATA_UNIT_SIZE;\r\n\tvoid* mem3 = (char*)mem2 + DATA_UNIT_SIZE;\r\n\r\n\tvoid* memOut = ::GlobalAlloc(GPTR, DATA_UNIT_SIZE * 8 * 2);\r\n\r\n\tHANDLE fileOut = CreateFileW(destFileName, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS /*CREATE_NEW*/, FILE_ATTRIBUTE_NORMAL, NULL);\r\n\twritePCM352_32_header(fileOut, wavDataSize * 8 * 2);\r\n\r\n\tlong long* firCoeff = (long long*)::GlobalAlloc(GPTR, sizeof(long long) * TAP_SIZE);\r\n\tdouble* firCoeff2 = (double*)::GlobalAlloc(GPTR, sizeof(double) * TAP_SIZE);\r\n\tcreateHannCoeff(TAP_SIZE, firCoeff, firCoeff2);\r\n\r\n\tfor (int i = 0; i <= part; ++i)\r\n\t{\r\n\t\t::SetThreadExecutionState(ES_SYSTEM_REQUIRED);\r\n\t\t\r\n\t\tlength = readSize;\r\n\t\t::CopyMemory(mem1, mem2, DATA_UNIT_SIZE);\r\n\t\t::CopyMemory(mem2, mem3, DATA_UNIT_SIZE);\r\n\t\t::SecureZeroMemory(mem3, DATA_UNIT_SIZE);\r\n\t\tif (i != part) readSize = readWavFile(fileName, mem3, DATA_UNIT_SIZE * i, DATA_UNIT_SIZE);\r\n\t\tif (i == 0) continue;\r\n\t\r\n\t\tstruct oversample_info info[8];\r\n\t\tinfo[0].src = (short* )mem2;\r\n\t\tinfo[0].length = length / 4;\r\n\t\tinfo[0].coeff = firCoeff;\r\n\t\tinfo[0].coeff2 = firCoeff2;\r\n\t\tinfo[0].tapNum = TAP_SIZE;\r\n\t\tinfo[0].dest = (int* )memOut;\r\n\t\tinfo[0].option = 0;\r\n\t\t\r\n\t\t// Single thread\r\n\t\tThreadFunc((LPVOID)&info[0]);\r\n\t\t\r\n\t\t// Multi thread (use code below instead of above)\r\n\t\t/*\r\n\t\tHANDLE thread[8];\r\n\t\tDWORD threadId[8];\r\n\t\tfor (int j = 0; j < 8; ++j)\r\n\t\t{\r\n\t\t\tinfo[j] = info[0];\r\n\t\t\tinfo[j].option = 1 << j;\r\n\t\t\tthread[j] = CreateThread(NULL, 0, ThreadFunc, (LPVOID)&info[j], 0, &threadId[j]);\r\n\t\t}\r\n\t\t::WaitForMultipleObjects(8, thread, TRUE, INFINITE);\r\n\t\t*/\r\n\r\n\t\t::WriteFile(fileOut, memOut, length * 8 * 2, &writtenSize, NULL);\r\n\t\tstd::cout << \"WavOverSampling: Progress  \" << (i * 100) / part << \" %\\r\";\r\n\t}\r\n\telapsedTime = GetTickCount64() - elapsedTime;\r\n\tstd::cout << \"\\nWavOverSampling: Completed.   \" << (elapsedTime/1000) << \".\" << (elapsedTime % 1000) <<  \" sec  \\n\";\r\n\r\n\t::FlushFileBuffers(fileOut);\r\n\t::CloseHandle(fileOut);\r\n\r\n\t::GlobalFree(mem1);\r\n\t::GlobalFree(memOut);\r\n\t::GlobalFree(firCoeff);\r\n\t::GlobalFree(firCoeff2);\r\n\treturn 0;\r\n}\r\n", "meta": {"hexsha": "cc8f8cbb9b113390cba74e939a86b536da72989e", "size": 20678, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "WavOverSampling/WavOverSampling.cpp", "max_stars_repo_name": "smallhh123/ae", "max_stars_repo_head_hexsha": "f567f3c9de5a29ba0c7390f12667602c3af9cefa", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "WavOverSampling/WavOverSampling.cpp", "max_issues_repo_name": "smallhh123/ae", "max_issues_repo_head_hexsha": "f567f3c9de5a29ba0c7390f12667602c3af9cefa", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-03-27T11:49:33.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-27T11:49:33.000Z", "max_forks_repo_path": "WavOverSampling/WavOverSampling.cpp", "max_forks_repo_name": "smallhh123/ae", "max_forks_repo_head_hexsha": "f567f3c9de5a29ba0c7390f12667602c3af9cefa", "max_forks_repo_licenses": ["Apache-2.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.7708333333, "max_line_length": 128, "alphanum_fraction": 0.5910629655, "num_tokens": 7395, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6893056040203135, "lm_q2_score": 0.49218813572079556, "lm_q1q2_score": 0.339268040184655}}
{"text": "// --------------------------------------------------------------------------\n//                   OpenMS -- Open-Source Mass Spectrometry\n// --------------------------------------------------------------------------\n// Copyright The OpenMS Team -- Eberhard Karls University Tuebingen,\n// ETH Zurich, and Freie Universitaet Berlin 2002-2013.\n//\n// This software is released under a three-clause BSD license:\n//  * Redistributions of source code must retain the above copyright\n//    notice, this list of conditions and the following disclaimer.\n//  * Redistributions in binary form must reproduce the above copyright\n//    notice, this list of conditions and the following disclaimer in the\n//    documentation and/or other materials provided with the distribution.\n//  * Neither the name of any author or any participating institution\n//    may be used to endorse or promote products derived from this software\n//    without specific prior written permission.\n// For a full list of authors, refer to the file AUTHORS.\n// --------------------------------------------------------------------------\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n// ARE DISCLAIMED. IN NO EVENT SHALL ANY OF THE AUTHORS OR THE CONTRIBUTING\n// INSTITUTIONS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;\n// OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR\n// OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF\n// ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n//\n// --------------------------------------------------------------------------\n// $Maintainer: Alexandra Zerck $\n// $Authors: Eva Lange $\n// --------------------------------------------------------------------------\n\n#include <cmath>\n#include <boost/math/special_functions/acosh.hpp>\n#include <boost/math/special_functions/fpclassify.hpp>\n\n#include <OpenMS/TRANSFORMATIONS/RAW2PEAK/OptimizePick.h>\n#include <OpenMS/MATH/MISC/MathFunctions.h>\n\n\nnamespace OpenMS\n{\n  namespace OptimizationFunctions\n  {\n\n\n\n    // Print the computed signal\n    void printSignal(const gsl_vector * x, void * param, float resolution)\n    {\n\n      std::vector<DoubleReal> & positions = static_cast<OptimizePick::Data *>(param)->positions;\n      std::vector<PeakShape> & peaks = static_cast<OptimizePick::Data *>(param)->peaks;\n      std::cout << \"Printing Signal\" << std::endl;\n      if (resolution == 1.)\n      {\n        // iterate over all points of the signal\n        for (size_t current_point = 0; current_point < positions.size(); current_point++)\n        {\n          double computed_signal     = 0.;\n          double current_position    = positions[current_point];\n\n          // iterate over all peaks\n          for (size_t current_peak = 0; current_peak < peaks.size(); current_peak++)\n          {\n            // Store the current parameters for this peak\n            double p_height          = gsl_vector_get(x, 4 * current_peak);\n            double p_position    = gsl_vector_get(x, 4 * current_peak + 3);\n            double p_width           = (current_position <= p_position) ? gsl_vector_get(x, 4 * current_peak + 1)\n                                       : gsl_vector_get(x, 4 * current_peak + 2);\n\n            // is it a Lorentz or a Sech - Peak?\n            if (peaks[current_peak].type == PeakShape::LORENTZ_PEAK)\n            {\n              computed_signal += p_height / (1. + pow(p_width * (current_position - p_position), 2));\n            }\n            else // It's a Sech - Peak\n            {\n              computed_signal += p_height / pow(cosh(p_width * (current_position - p_position)), 2);\n            }\n          }\n          std::cerr << positions[current_point] << \" \" << computed_signal << std::endl;\n        }\n      }\n      else\n      {\n        // Compute step width\n        float sw = (positions[1] - positions[0]) / resolution;\n        for (int i = 0; i < positions.size() * resolution; i++)\n        {\n          double computed_signal     = 0.;\n          double current_position    = positions[0] + i * sw;\n\n          // iterate over all peaks\n          for (size_t current_peak = 0; current_peak < peaks.size(); current_peak++)\n          {\n            // Store the current parameters for this peak\n            double p_height          = gsl_vector_get(x, 4 * current_peak);\n            double p_position    = gsl_vector_get(x, 4 * current_peak + 3);\n            double p_width           = (current_position <= p_position) ? gsl_vector_get(x, 4 * current_peak + 1)\n                                       : gsl_vector_get(x, 4 * current_peak + 2);\n\n            // is it a Lorentz or a Sech - Peak?\n            if (peaks[current_peak].type == PeakShape::LORENTZ_PEAK)\n            {\n              computed_signal += p_height / (1. + pow(p_width * (current_position - p_position), 2));\n            }\n            else // It's a Sech - Peak\n            {\n              computed_signal += p_height / pow(cosh(p_width * (current_position - p_position)), 2);\n            }\n          }\n\n          std::cerr.precision(writtenDigits<DoubleReal>(0.0));\n\n          std::cerr << positions[0] + i * sw << \" \" << computed_signal << std::endl;\n        }\n      }\n    }\n\n    // Evaluation of the target function for nonlinear optimization.\n    int residual(const gsl_vector * x, void * params, gsl_vector * f)\n    {\n      // According to the gsl conventions, x contains the parameters to be optimized.\n      // In our case, this means that we store for each peak four consecutive values:\n      //  - its height\n      //  - its left width\n      //  - its right width\n      //  - its position\n      //\n      // Params might contain any additional parameters. We handle these using class members\n      // instead.\n      // The vector f is supposed to contain the result when we return from this function.\n      // Note: GSL wants the values for each data point i as one component of the results vector\n      std::vector<DoubleReal> & signal = static_cast<OptimizePick::Data *>(params)->signal;\n      std::vector<DoubleReal> & positions = static_cast<OptimizePick::Data *>(params)->positions;\n      std::vector<PeakShape> & peaks = static_cast<OptimizePick::Data *>(params)->peaks;\n      OptimizationFunctions::PenaltyFactors & penalties = static_cast<OptimizePick::Data *>(params)->penalties;\n      // iterate over all points of the signal\n      for (size_t current_point = 0; current_point < positions.size(); current_point++)\n      {\n        double computed_signal     = 0.;\n        double current_position    = positions[current_point];\n        double experimental_signal = signal[current_point];\n\n        // iterate over all peaks\n        for (size_t current_peak = 0; current_peak < peaks.size(); current_peak++)\n        {\n          // Store the current parameters for this peak\n          double p_height        = gsl_vector_get(x, 4 * current_peak);\n          double p_position    = gsl_vector_get(x, 4 * current_peak + 3);\n          double p_width         = (current_position <= p_position) ? gsl_vector_get(x, 4 * current_peak + 1)\n                                   : gsl_vector_get(x, 4 * current_peak + 2);\n\n          // is it a Lorentz or a Sech - Peak?\n          if (peaks[current_peak].type == PeakShape::LORENTZ_PEAK)\n          {\n            computed_signal += p_height / (1. + pow(p_width * (current_position - p_position), 2));\n          }\n          else // It's a Sech - Peak\n          {\n            computed_signal += p_height / pow(cosh(p_width * (current_position - p_position)), 2);\n          }\n        }\n        gsl_vector_set(f, current_point, computed_signal - experimental_signal);\n      }\n\n      double penalty = 0.;\n//      struct PenaltyFactors* penalties = (struct PenaltyFactors *)params;\n      double penalty_pos    = penalties.pos;\n      double penalty_lwidth = penalties.lWidth;\n      double penalty_rwidth = penalties.rWidth;\n\n      // iterate over all peaks again to compute the penalties\n      for (size_t current_peak = 0; current_peak < peaks.size(); current_peak++)\n      {\n        double old_position = peaks[current_peak].mz_position;\n        double old_width_l  = peaks[current_peak].left_width;\n        double old_width_r  = peaks[current_peak].right_width;\n        double p_position   = gsl_vector_get(x, 4 * current_peak + 3);\n        double p_width_l        = gsl_vector_get(x, 4 * current_peak + 1);\n        double p_width_r    = gsl_vector_get(x, 4 * current_peak + 2);\n\n        //penalty += pow(p_position - old_position, 2) + pow(p_width_l - old_width_l, 2) + pow(p_width_r - old_width_r, 2);\n        penalty +=      penalty_pos    * pow(p_position - old_position, 2)\n                   + penalty_lwidth * pow(p_width_l - old_width_l, 2)\n                   + penalty_rwidth * pow(p_width_r - old_width_r, 2);\n      }\n\n      gsl_vector_set(f, positions.size(), 100 * penalty);\n\n      return GSL_SUCCESS;\n    }\n\n    /** Compute the Jacobian of the residual, where each row of the matrix corresponds to a\n     *  point in the data.\n     */\n    int jacobian(const gsl_vector * x, void * params, gsl_matrix * J)\n    {\n      // For the conventions on x and params c.f. the commentary in residual()\n      //\n      // The matrix J is supposed to contain the result when we return from this function.\n      // Note: GSL expects the Jacobian as follows:\n      // - each row corresponds to one data point\n      // - each column corresponds to one parameter\n      // std::vector<DoubleReal>& signal = static_cast<OptimizePick::Data*> (params) ->signal;\n      std::vector<DoubleReal> & positions = static_cast<OptimizePick::Data *>(params)->positions;\n      std::vector<PeakShape> & peaks = static_cast<OptimizePick::Data *>(params)->peaks;\n      OptimizationFunctions::PenaltyFactors & penalties = static_cast<OptimizePick::Data *>(params)->penalties;\n      // iterate over all points of the signal\n      for (size_t current_point = 0; current_point < positions.size(); current_point++)\n      {\n        double current_position    = positions[current_point];\n\n        // iterate over all peaks\n        for (size_t current_peak = 0; current_peak < peaks.size(); current_peak++)\n        {\n          // Store the current parameters for this peak\n          double p_height        = gsl_vector_get(x, 4 * current_peak);\n          double p_position    = gsl_vector_get(x, 4 * current_peak + 3);\n          double p_width         = (current_position <= p_position) ? gsl_vector_get(x, 4 * current_peak + 1)\n                                   : gsl_vector_get(x, 4 * current_peak + 2);\n\n          // is it a Lorentz or a Sech - Peak?\n          if (peaks[current_peak].type == PeakShape::LORENTZ_PEAK)\n          {\n            double diff      = current_position - p_position;\n            double denom_inv = 1. / (1. + pow(p_width * diff, 2));\n\n            double ddl_left  = (current_position <= p_position)\n                               ? -2 * p_height * pow(diff, 2) * p_width * pow(denom_inv, 2) :\n                                 0;\n\n            double ddl_right = (current_position  > p_position)\n                               ? -2 * p_height * pow(diff, 2) * p_width * pow(denom_inv, 2) :\n                                 0;\n\n            double ddx0          = -2 * p_height * pow(p_width, 2) * diff * pow(denom_inv, 2);\n\n            gsl_matrix_set(J, current_point, 4 * current_peak, denom_inv);\n            gsl_matrix_set(J, current_point, 4 * current_peak + 1, ddl_left);\n            gsl_matrix_set(J, current_point, 4 * current_peak + 2, ddl_right);\n            gsl_matrix_set(J, current_point, 4 * current_peak + 3, ddx0);\n          }\n          else // It's a Sech - Peak\n          {\n            double diff      = current_position - p_position;\n            double denom_inv = 1. / cosh(p_width * diff);\n\n            // The remaining computations are not stable if denom_inv == 0. In that case, we are far away from the peak\n            // and can assume that all derivatives vanish\n            double sinh_term = (fabs(denom_inv) < 1e-6) ? 0.0 : sinh(p_width * diff);\n            double ddl_left  = (current_position <= p_position)\n                               ? -2 * p_height * sinh_term * diff * pow(denom_inv, 3) :\n                                 0;\n            double ddl_right = (current_position  > p_position)\n                               ? -2 * p_height * sinh_term * diff * pow(denom_inv, 3) :\n                                 0;\n            double ddx0      = 2 * p_height * p_width * sinh_term * pow(denom_inv, 3);\n\n            gsl_matrix_set(J, current_point, 4 * current_peak, pow(denom_inv, 2));\n            gsl_matrix_set(J, current_point, 4 * current_peak + 1, ddl_left);\n            gsl_matrix_set(J, current_point, 4 * current_peak + 2, ddl_right);\n            gsl_matrix_set(J, current_point, 4 * current_peak + 3, ddx0);\n          }\n        }\n      }\n\n      // Now iterate over all peaks again to compute the penalties.\n//   struct PenaltyFactors* penalties = (struct PenaltyFactors *)params;\n      for (size_t current_peak = 0; current_peak < peaks.size(); current_peak++)\n      {\n        double p_width_left = gsl_vector_get(x, 4 * current_peak + 1);\n        double p_width_right = gsl_vector_get(x, 4 * current_peak + 2);\n        double p_position   = gsl_vector_get(x, 4 * current_peak + 3);\n\n        double old_width_left  = peaks[current_peak].left_width;\n        double old_width_right = peaks[current_peak].right_width;\n        double old_position    = peaks[current_peak].mz_position;\n\n\n        double penalty_l = 2. * penalties.lWidth * (p_width_left - old_width_left);\n        double penalty_r = 2. * penalties.rWidth * (p_width_right - old_width_right);\n        double penalty_p = 0;\n        if (fabs(p_position - old_position) < 0.2)\n        {\n          penalty_p = 2. * penalties.pos * (p_position - old_position);\n        }\n\n        gsl_matrix_set(J, positions.size(), 4 * current_peak, 0.);\n        gsl_matrix_set(J, positions.size(), 4 * current_peak + 1, 100 * penalty_l);\n        gsl_matrix_set(J, positions.size(), 4 * current_peak + 2, 100 * penalty_r);\n        gsl_matrix_set(J, positions.size(), 4 * current_peak + 3, 100 * penalty_p);\n      }\n\n      return GSL_SUCCESS;\n    }\n\n    // Driver function for the evaluation of function and jacobian.\n    int evaluate(const gsl_vector * x, void * params, gsl_vector * f, gsl_matrix * J)\n    {\n      residual(x, params, f);\n      jacobian(x, params, J);\n\n      return GSL_SUCCESS;\n    }\n\n  }\n\n\n  OptimizePick::OptimizePick(const struct OptimizationFunctions::PenaltyFactors & penalties,\n                             const int max_iteration,\n                             const double eps_abs,\n                             const double eps_rel)\n  {\n\n    penalties_ = penalties;\n\n    max_iteration_ = max_iteration;\n    eps_abs_ = eps_abs;\n    eps_rel_ = eps_rel;\n\n#ifdef DEBUG_PEAK_PICKING\n    std::cout << \"max iteration \" << max_iteration_\n              << \"\\n eps abs \" << eps_abs\n              << \"\\n eps rel \" << eps_rel\n              << \"\\n penalty factor pos \" << penalties.pos\n              << \"\\n penalty factor left width \" << penalties.lWidth\n              << \"\\n penalty factor right width \" << penalties.rWidth\n              << std::endl;\n#endif\n\n  }\n\n  OptimizePick::~OptimizePick()\n  {\n  }\n\n  void OptimizePick::optimize(std::vector<PeakShape> & peaks, Data & data)\n  {\n    if (peaks.empty())\n      return;\n\n    size_t global_peak_number = 0;\n    data.peaks.assign(peaks.begin(), peaks.end());\n\n    gsl_vector * start_value = gsl_vector_alloc(4 * data.peaks.size());\n    // We have to initialize the parameters for the optimization\n    for (size_t i = 0; i < data.peaks.size(); i++)\n    {\n      PeakShape current_peak = data.peaks[i];\n      double h  = current_peak.height;\n      double wl = current_peak.left_width;\n      double wr = current_peak.right_width;\n      double p  = current_peak.mz_position;\n      if (boost::math::isnan(wl))\n      {\n        data.peaks[i].left_width = 1;\n        wl = 1.;\n      }\n      if (boost::math::isnan(wr))\n      {\n        data.peaks[i].right_width = 1;\n        wr = 1.;\n      }\n\n      gsl_vector_set(start_value, 4 * i, h);\n      gsl_vector_set(start_value, 4 * i + 1, wl);\n      gsl_vector_set(start_value, 4 * i + 2, wr);\n      gsl_vector_set(start_value, 4 * i + 3, p);\n    }\n\n\n    // The gsl algorithms require us to provide function pointers for the evaluation of\n    // the target function.\n    gsl_multifit_function_fdf fit_function;\n    fit_function.f      = OptimizationFunctions::residual;\n    fit_function.df       = OptimizationFunctions::jacobian;\n    fit_function.fdf        = OptimizationFunctions::evaluate;\n    fit_function.n          = std::max(data.positions.size() + 1, 4 * data.peaks.size());\n    fit_function.p          = 4 * data.peaks.size();\n//    fit_function.params = &penalties_;\n    data.penalties = penalties_;\n    fit_function.params = &data;\n\n    const gsl_multifit_fdfsolver_type * type = gsl_multifit_fdfsolver_lmsder;\n\n    gsl_multifit_fdfsolver * fit = gsl_multifit_fdfsolver_alloc(type, std::max(data.positions.size() + 1, 4 * data.peaks.size()), 4 * data.peaks.size());\n\n    gsl_multifit_fdfsolver_set(fit, &fit_function, start_value);\n\n    // initial norm\n    // std::cout << \"Before optimization: ||f|| = \" << gsl_blas_dnrm2(fit->f) << std::endl;\n\n    // Iteration\n    unsigned int iteration = 0;\n    int status;\n\n    do\n    {\n      iteration++;\n      status = gsl_multifit_fdfsolver_iterate(fit);\n#ifdef DEBUG_PEAK_PICKING\n      std::cout << \"Iteration \" << iteration << \"; Status \" << gsl_strerror(status) << \"; \" << std::endl;\n      std::cout << \"||f|| = \" << gsl_blas_dnrm2(fit->f) << std::endl;\n      std::cout << \"Number of parms: \" << data.peaks.size() * 4 << std::endl;\n      std::cout << \"Delta: \" << gsl_blas_dnrm2(fit->dx) << std::endl;\n#endif\n      if (boost::math::isnan(gsl_blas_dnrm2(fit->dx)))\n        break;\n\n      // We use the gsl function gsl_multifit_test_delta to decide if we can finish the iteration.\n      // We only finish if all new parameters deviates only by a small amount from the parameters of the last iteration\n      status = gsl_multifit_test_delta(fit->dx, fit->x, eps_abs_, eps_rel_);\n      if (status != GSL_CONTINUE)\n        break;\n\n    }\n    while (status == GSL_CONTINUE && iteration < max_iteration_);\n\n#ifdef DEBUG_PEAK_PICKING\n    std::cout << \"Finished!\" << std::endl;\n    std::cout << \"Delta: \" << gsl_blas_dnrm2(fit->dx) << std::endl;\n    double chi = gsl_blas_dnrm2(fit->f);\n    std::cout << \"chisq/dof = \" << pow(chi, 2.0) / (data.positions.size() - 4 * data.peaks.size());\n#endif\n\n    // OptimizationFunctions::printSignal(fit->x, 5.,param);\n\n    // iterate over all peaks and store the optimized values in peaks\n    for (size_t current_peak = 0; current_peak < data.peaks.size(); current_peak++)\n    {\n      // Store the current parameters for this peak\n      peaks[global_peak_number + current_peak].height          = gsl_vector_get(fit->x, 4 * current_peak);\n      peaks[global_peak_number + current_peak].mz_position = gsl_vector_get(fit->x, 4 * current_peak + 3);\n      peaks[global_peak_number + current_peak].left_width  = gsl_vector_get(fit->x, 4 * current_peak + 1);\n      peaks[global_peak_number + current_peak].right_width = gsl_vector_get(fit->x, 4 * current_peak + 2);\n\n      // compute the area\n      // is it a Lorentz or a Sech - Peak?\n      if (peaks[global_peak_number + current_peak].type == PeakShape::LORENTZ_PEAK)\n      {\n        PeakShape p = peaks[global_peak_number + current_peak];\n        double x_left_endpoint = p.mz_position - 1 / p.left_width * sqrt(p.height / 1 - 1);\n        double x_rigth_endpoint = p.mz_position + 1 / p.right_width * sqrt(p.height / 1 - 1);\n        double area_left = -p.height / p.left_width * atan(p.left_width * (x_left_endpoint - p.mz_position));\n        double area_right = -p.height / p.right_width * atan(p.right_width * (p.mz_position - x_rigth_endpoint));\n        peaks[global_peak_number + current_peak].area = area_left + area_right;\n#ifdef DEBUG_PEAK_PICKING\n        std::cout << \"Lorentz \" << area_left << \" \" << area_right\n                  << \" \" << peaks[global_peak_number + current_peak].area << std::endl;\n#endif\n      }\n      else  //It's a Sech - Peak\n      {\n        PeakShape p = peaks[global_peak_number + current_peak];\n        double x_left_endpoint = p.mz_position - 1 / p.left_width * boost::math::acosh(sqrt(p.height / 0.001));\n        double x_rigth_endpoint = p.mz_position + 1 / p.right_width * boost::math::acosh(sqrt(p.height / 0.001));\n        double area_left = p.height / p.left_width * (sinh(p.left_width * (p.mz_position - x_left_endpoint)) / cosh(p.left_width * (p.mz_position - x_left_endpoint)));\n        double area_right = -p.height / p.right_width * (sinh(p.right_width * (p.mz_position - x_rigth_endpoint)) / cosh(p.right_width * (p.mz_position - x_rigth_endpoint)));\n        peaks[global_peak_number + current_peak].area = area_left + area_right;\n#ifdef DEBUG_PEAK_PICKING\n        std::cout << \"Sech \" << area_left << \" \" << area_right\n                  << \" \" << peaks[global_peak_number + current_peak].area << std::endl;\n        std::cout << p.mz_position << \" \" << x_left_endpoint << \" \" << x_rigth_endpoint << std::endl;\n#endif\n      }\n    }\n    global_peak_number += data.peaks.size();\n\n    gsl_multifit_fdfsolver_free(fit);\n    gsl_vector_free(start_value);\n  }\n\n  // double OptimizePick::correlate_(const PeakShape& peak,\n//                                  double left_endpoint,\n//                                                                  double right_endpoint,Data& data)\n//   {\n//     double SSxx = 0., SSyy = 0., SSxy = 0.;\n\n//     // compute the averages\n//     double data_average=0., fit_average=0.;\n//     double data_sqr=0., fit_sqr=0.;\n//     double cross=0.;\n\n//     int number_of_points = 0;\n\n//     int first=0;\n//     int last=data.positions.size()-1;\n\n//     // search for the left endpoint position\n//     while (data.positions[first] < left_endpoint)\n//     {\n//       ++first;\n//     }\n\n//     // search for the right endpoint position\n//     while (data.positions[last] > right_endpoint)\n//     {\n//       --last;\n//     }\n\n\n//     // for separate overlapping peak correlate until the max position...\n//     for (int i=first; i <= last; i++)\n//     {\n//       double data_val = data.signal[i];\n//       double peak_val = peak(data.positions[i]);\n\n//       data_average += data_val;\n//       fit_average  += peak_val;\n\n//       data_sqr += data_val * data_val;\n//       fit_sqr  += peak_val * peak_val;\n\n//       cross += data_val * peak_val;\n\n//       number_of_points++;\n//     }\n\n//     if (number_of_points == 0)\n//       return 0.;\n\n//     data_average /= number_of_points;\n//     fit_average  /= number_of_points;\n\n//     SSxx = data_sqr - number_of_points * (data_average * data_average);\n//     SSyy = fit_sqr - number_of_points * (fit_average * fit_average);\n//     SSxy = cross - number_of_points * (data_average * fit_average);\n\n//     return (SSxy * SSxy) / (SSxx * SSyy);\n//   }\n\n}\n", "meta": {"hexsha": "b0ae09f648d16fd4c823af0521f0ff15976a580f", "size": 23392, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/openms/source/TRANSFORMATIONS/RAW2PEAK/OptimizePick.cpp", "max_stars_repo_name": "kreinert/OpenMS", "max_stars_repo_head_hexsha": "45455356482ce5ab35e32e445609b291ec78a6d6", "max_stars_repo_licenses": ["Zlib", "Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2016-12-09T01:45:03.000Z", "max_stars_repo_stars_event_max_datetime": "2016-12-09T01:45:03.000Z", "max_issues_repo_path": "src/openms/source/TRANSFORMATIONS/RAW2PEAK/OptimizePick.cpp", "max_issues_repo_name": "kreinert/OpenMS", "max_issues_repo_head_hexsha": "45455356482ce5ab35e32e445609b291ec78a6d6", "max_issues_repo_licenses": ["Zlib", "Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/openms/source/TRANSFORMATIONS/RAW2PEAK/OptimizePick.cpp", "max_forks_repo_name": "kreinert/OpenMS", "max_forks_repo_head_hexsha": "45455356482ce5ab35e32e445609b291ec78a6d6", "max_forks_repo_licenses": ["Zlib", "Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 43.5605214153, "max_line_length": 174, "alphanum_fraction": 0.602000684, "num_tokens": 5681, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7549149758396752, "lm_q2_score": 0.44939263446475963, "lm_q1q2_score": 0.33925322978949196}}
{"text": "/*\n * Copyright 2020 California  Institute  of Technology (“Caltech”)\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 <x/vio/msckf_update.h>\n#include <x/vio/tools.h>\n#include <x/ekf/state.h>\n#include <boost/math/distributions.hpp>\n\nusing namespace x;\nusing namespace Eigen;\n\nMsckfUpdate::MsckfUpdate(const x::TrackList& trks,\n                         const x::AttitudeList& quats,\n                         const x::TranslationList& pos,\n                         const Triangulation& triangulator,\n                         const MatrixXd& cov_s,\n                         const int n_poses_max,\n                         const double sigma_img)\n{\n  // Number of features\n  const size_t n_trks = trks.size();\n\n  // Number of feature observations\n  size_t n_obs = 0;\n  for(size_t i=0; i < n_trks; i++)\n    n_obs += trks[i].size();\n\n  // Initialize Kalman update matrices\n  const size_t rows = 2 * n_obs - n_trks * 3;\n  const size_t cols = cov_s.cols();\n  jac_ = MatrixXd::Zero(rows, cols);\n  cov_m_diag_ = VectorXd::Ones(rows);\n  res_ = MatrixXd::Zero(rows, 1);\n  \n  // For each track, compute residual, Jacobian and covariance block\n  const double var_img = sigma_img * sigma_img;\n  for (size_t i = 0, row_h = 0; i < n_trks; ++i) {\n    processOneTrack(trks[i], \n                    quats,\n                    pos,\n                    triangulator,\n                    cov_s,\n                    n_poses_max,\n                    var_img,\n                    i,\n                    row_h);\n  }\n}\n\nvoid MsckfUpdate::processOneTrack(const x::Track& track,\n                                  const x::AttitudeList& C_q_G,\n                                  const x::TranslationList& G_p_C,\n                                  const Triangulation& triangulator,\n                                  const MatrixXd& P,\n                                  const int n_poses_max,\n                                  const double var_img,\n                                  const size_t& j,\n                                  size_t& row_h)\n{\n  // Initialization\n  const size_t track_size = track.size();\n  unsigned int rows_track_j = track_size * 2;\n  const size_t cols = P.cols();\n  MatrixXd jac_j(MatrixXd::Zero(rows_track_j, cols));\n  MatrixXd Hf_j(MatrixXd::Zero(jac_j.rows(), kJacCols));\n  MatrixXd res_j(MatrixXd::Zero(rows_track_j, 1));\n\n  // Triangulate feature j\n  // Inverse-depth parameters in last observation frame\n  Vector3d feature; // inverse-depth parameters in last observation frame\n  triangulator.triangulateGN(track, feature);\n  const double alpha = feature(0);\n  const double beta  = feature(1);\n  const double rho   = feature(2);\n\n  // Coordinate of feature in global frame\n  x::Quaternion Cn_q_G;\n  Cn_q_G.x() = C_q_G.back().ax;\n  Cn_q_G.y() = C_q_G.back().ay;\n  Cn_q_G.z() = C_q_G.back().az;\n  Cn_q_G.w() = C_q_G.back().aw;\n\n  Vector3d G_p_Cn(G_p_C.back().tx, G_p_C.back().ty, G_p_C.back().tz);\n\n  Vector3d G_p_fj = 1 / (rho)*Cn_q_G.normalized().toRotationMatrix() * Vector3d(alpha, beta, 1) + G_p_Cn;\n\n  x::Quatern attitude_to_quaternion;\n\n  // LOOP OVER ALL FEATURE OBSERVATIONS\n  for (size_t i = 0; i < track_size; ++i)\n  {\n    const unsigned int pos = C_q_G.size() - track_size + i;\n\n    Quaterniond Ci_q_G_ = attitude_to_quaternion(C_q_G[pos]);\n    Vector3d G_p_Ci_(G_p_C[pos].tx, G_p_C[pos].ty, G_p_C[pos].tz);\n\n    // Feature position expressed in camera frame.\n    Vector3d Ci_p_fj;\n    Ci_p_fj << Ci_q_G_.normalized().toRotationMatrix().transpose() * (G_p_fj - G_p_Ci_);\n\n    // eq. 20(a)\n    Vector2d z;\n    z(0) = track[i].getX();\n    z(1) = track[i].getY();\n\n    Vector2d z_hat(z);\n    assert(Ci_p_fj(2));\n    z_hat(0) = Ci_p_fj(0) / Ci_p_fj(2);\n    z_hat(1) = Ci_p_fj(1) / Ci_p_fj(2);\n\n    // eq. 20(b)\n    res_j(i * 2, 0) = z(0) - z_hat(0);\n    res_j(i * 2 + 1, 0) = z(1) - z_hat(1);\n\n    // Set Jacobian of pose for i'th measurement of feature j (eq.22, 23)\n    VisJacBlock J_i = VisJacBlock::Zero();\n    // first row\n    J_i(0, 0) = 1.0 / Ci_p_fj(2);\n    J_i(0, 1) = 0.0;\n    J_i(0, 2) = -Ci_p_fj(0) / std::pow((double)Ci_p_fj(2), 2);\n    // second row\n    J_i(1, 0) = 0.0;\n    J_i(1, 1) = 1.0 / Ci_p_fj(2);\n    J_i(1, 2) = -Ci_p_fj(1) / std::pow((double)Ci_p_fj(2), 2);\n\n    unsigned int row = i * kVisJacRows;\n\n    // Measurement Jacobians wrt attitude, position and feature\n    // Position\n    VisJacBlock J_position = -J_i * Ci_q_G_.normalized().toRotationMatrix().transpose();\n\n    Vector3d dP = Ci_q_G_.normalized().toRotationMatrix().transpose() * (G_p_fj - G_p_Ci_);\n\n    // Attitude\n    VisJacBlock J_attitude = J_i * x::Skew(dP(0), dP(1), dP(2)).matrix;\n\n    // Feature\n    Hf_j.block<kVisJacRows, kJacCols>(row, 0) = -J_position;\n\n    // Update stacked Jacobian matrix associated to the current feature\n    unsigned int col = pos * kJacCols;\n    jac_j.block<kVisJacRows, kJacCols>(row, kSizeCoreErr + col) = J_position;\n\n    col += n_poses_max * kJacCols;\n\n    jac_j.block<kVisJacRows, kJacCols>(row, kSizeCoreErr + col) = J_attitude;\n  }  // LOOP OVER ALL FEATURE OBSERVATIONS\n\n  //========================================================================\n  // Left nullspace projection\n  //========================================================================\n  // Nullspace computation\n  MatrixXd q = Hf_j.householderQr().householderQ();\n  MatrixXd A = x::MatrixBlock(q, 0, 3);\n\n  // Projections\n  MatrixXd res0_j = A.transpose() * res_j;\n  MatrixXd jac0_j = A.transpose() * jac_j;\n\n  // Noise measurement matrix\n  const VectorXd r0_j_diag = var_img * VectorXd::Ones(rows_track_j - 3);\n  const MatrixXd r0_j = r0_j_diag.asDiagonal();\n\n  //==========================================================================\n  // Outlier rejection\n  //==========================================================================\n  MatrixXd S_inv = (jac0_j * P * jac0_j.transpose() + r0_j).inverse();\n  MatrixXd gamma = res0_j.transpose() * S_inv * res0_j;\n  boost::math::chi_squared_distribution<> my_chisqr(2 * track_size - 3); // 2*Mj-3 DOFs\n  double chi = quantile(my_chisqr, 0.95); // 95-th percentile\n\n  if (gamma(0, 0) < chi)  // Inlier\n  {\n#ifdef VERBOSE\n    inliers_.push_back(G_p_fj);\n#endif\n\n    jac_.block(row_h,            // startRow\n             0,                 // startCol\n             rows_track_j - 3,  // numRows\n             cols) = jac0_j;    // numCols\n\n    // Residual vector (for this track)\n    res_.block(row_h, 0, rows_track_j - 3, 1) = res0_j;\n\n    // Measurement covariance matrix diagonal\n    cov_m_diag_.segment(row_h, rows_track_j - 3) = r0_j_diag;\n\n    row_h += rows_track_j - 3;\n  }\n  else  // outlier\n  {\n#ifdef VERBOSE\n    outliers_.push_back(G_p_fj);\n#endif\n  }\n}\n", "meta": {"hexsha": "5cc4954fba1b266570f0c6e55f3ef4cef2816370", "size": 7147, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/x/vio/msckf_update.cpp", "max_stars_repo_name": "jpl-x/x_events", "max_stars_repo_head_hexsha": "e9d0b6e578f045eb7b57acadf75b77d8a323f51d", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 57.0, "max_stars_repo_stars_event_min_datetime": "2020-10-20T18:01:14.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T18:44:43.000Z", "max_issues_repo_path": "src/x/vio/msckf_update.cpp", "max_issues_repo_name": "jpl-x/x_events", "max_issues_repo_head_hexsha": "e9d0b6e578f045eb7b57acadf75b77d8a323f51d", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2022-03-11T15:53:17.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-11T15:53:17.000Z", "max_forks_repo_path": "src/x/vio/msckf_update.cpp", "max_forks_repo_name": "jpl-x/x_events", "max_forks_repo_head_hexsha": "e9d0b6e578f045eb7b57acadf75b77d8a323f51d", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 11.0, "max_forks_repo_forks_event_min_datetime": "2020-10-17T00:36:02.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T18:44:45.000Z", "avg_line_length": 33.8720379147, "max_line_length": 105, "alphanum_fraction": 0.5847208619, "num_tokens": 2050, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7057850402140659, "lm_q2_score": 0.48047867804790706, "lm_q1q2_score": 0.3391146631080433}}
{"text": "#include \"camera_model/camera_models/ScaramuzzaCamera.h\"\n\n#include <boost/algorithm/string.hpp>\n#include <boost/lexical_cast.hpp>\n#include <cmath>\n#include <cstdio>\n#include <eigen3/Eigen/Dense>\n#include <eigen3/Eigen/SVD>\n#include <iomanip>\n#include <iostream>\n#include <opencv2/calib3d/calib3d.hpp>\n#include <opencv2/core/eigen.hpp>\n#include <opencv2/imgproc/imgproc.hpp>\n\n#include \"camera_model/gpl/gpl.h\"\n\nEigen::VectorXd\npolyfit( Eigen::VectorXd& xVec, Eigen::VectorXd& yVec, int poly_order )\n{\n    assert( poly_order > 0 );\n    assert( xVec.size( ) > poly_order );\n    assert( xVec.size( ) == yVec.size( ) );\n\n    Eigen::MatrixXd A( xVec.size( ), poly_order + 1 );\n    Eigen::VectorXd B( xVec.size( ) );\n\n    for ( int i = 0; i < xVec.size( ); ++i )\n    {\n        const double x = xVec( i );\n        const double y = yVec( i );\n\n        double x_pow_k = 1.0;\n\n        for ( int k = 0; k <= poly_order; ++k )\n        {\n            A( i, k ) = x_pow_k;\n            x_pow_k *= x;\n        }\n\n        B( i ) = y;\n    }\n\n    Eigen::JacobiSVD< Eigen::MatrixXd > svd( A, Eigen::ComputeThinU | Eigen::ComputeThinV );\n    Eigen::VectorXd x = svd.solve( B );\n\n    return x;\n}\n\nnamespace camera_model\n{\n\nOCAMCamera::Parameters::Parameters( )\n: Camera::Parameters( SCARAMUZZA )\n, m_C( 0.0 )\n, m_D( 0.0 )\n, m_E( 0.0 )\n, m_center_x( 0.0 )\n, m_center_y( 0.0 )\n{\n    memset( m_poly, 0, sizeof( double ) * SCARAMUZZA_POLY_SIZE );\n    memset( m_inv_poly, 0, sizeof( double ) * SCARAMUZZA_INV_POLY_SIZE );\n}\n\nbool\nOCAMCamera::Parameters::readFromYamlFile( const std::string& filename )\n{\n    cv::FileStorage fs( filename, cv::FileStorage::READ );\n\n    if ( !fs.isOpened( ) )\n    {\n        return false;\n    }\n\n    if ( !fs[\"model_type\"].isNone( ) )\n    {\n        std::string sModelType;\n        fs[\"model_type\"] >> sModelType;\n\n        if ( !boost::iequals( sModelType, \"scaramuzza\" ) )\n        {\n            return false;\n        }\n    }\n\n    m_modelType = SCARAMUZZA;\n    fs[\"camera_name\"] >> m_cameraName;\n    m_imageWidth  = static_cast< int >( fs[\"image_width\"] );\n    m_imageHeight = static_cast< int >( fs[\"image_height\"] );\n\n    cv::FileNode n = fs[\"poly_parameters\"];\n    for ( int i   = 0; i < SCARAMUZZA_POLY_SIZE; i++ )\n        m_poly[i] = static_cast< double >( n[std::string( \"p\" ) + boost::lexical_cast< std::string >( i )] );\n\n    n = fs[\"inv_poly_parameters\"];\n    for ( int i       = 0; i < SCARAMUZZA_INV_POLY_SIZE; i++ )\n        m_inv_poly[i] = static_cast< double >( n[std::string( \"p\" ) + boost::lexical_cast< std::string >( i )] );\n\n    n   = fs[\"affine_parameters\"];\n    m_C = static_cast< double >( n[\"ac\"] );\n    m_D = static_cast< double >( n[\"ad\"] );\n    m_E = static_cast< double >( n[\"ae\"] );\n\n    m_center_x = static_cast< double >( n[\"cx\"] );\n    m_center_y = static_cast< double >( n[\"cy\"] );\n\n    return true;\n}\n\nvoid\nOCAMCamera::Parameters::writeToYamlFile( const std::string& filename ) const\n{\n    cv::FileStorage fs( filename, cv::FileStorage::WRITE );\n\n    fs << \"model_type\"\n       << \"scaramuzza\";\n    fs << \"camera_name\" << m_cameraName;\n    fs << \"image_width\" << m_imageWidth;\n    fs << \"image_height\" << m_imageHeight;\n\n    fs << \"poly_parameters\";\n    fs << \"{\";\n    for ( int i = 0; i < SCARAMUZZA_POLY_SIZE; i++ )\n        fs << std::string( \"p\" ) + boost::lexical_cast< std::string >( i ) << m_poly[i];\n    fs << \"}\";\n\n    fs << \"inv_poly_parameters\";\n    fs << \"{\";\n    for ( int i = 0; i < SCARAMUZZA_INV_POLY_SIZE; i++ )\n        fs << std::string( \"p\" ) + boost::lexical_cast< std::string >( i ) << m_inv_poly[i];\n    fs << \"}\";\n\n    fs << \"affine_parameters\";\n    fs << \"{\"\n       << \"ac\" << m_C << \"ad\" << m_D << \"ae\" << m_E << \"cx\" << m_center_x << \"cy\" << m_center_y << \"}\";\n\n    fs.release( );\n}\n\nOCAMCamera::Parameters&\nOCAMCamera::Parameters::operator=( const OCAMCamera::Parameters& other )\n{\n    if ( this != &other )\n    {\n        m_modelType   = other.m_modelType;\n        m_cameraName  = other.m_cameraName;\n        m_imageWidth  = other.m_imageWidth;\n        m_imageHeight = other.m_imageHeight;\n        m_C           = other.m_C;\n        m_D           = other.m_D;\n        m_E           = other.m_E;\n        m_center_x    = other.m_center_x;\n        m_center_y    = other.m_center_y;\n\n        memcpy( m_poly, other.m_poly, sizeof( double ) * SCARAMUZZA_POLY_SIZE );\n        memcpy( m_inv_poly, other.m_inv_poly, sizeof( double ) * SCARAMUZZA_INV_POLY_SIZE );\n    }\n\n    return *this;\n}\n\nstd::ostream&\noperator<<( std::ostream& out, const OCAMCamera::Parameters& params )\n{\n    out << \"Camera Parameters:\" << std::endl;\n    out << \"    model_type \"\n        << \"scaramuzza\" << std::endl;\n    out << \"   camera_name \" << params.m_cameraName << std::endl;\n    out << \"   image_width \" << params.m_imageWidth << std::endl;\n    out << \"  image_height \" << params.m_imageHeight << std::endl;\n\n    out << std::fixed << std::setprecision( 10 );\n\n    out << \"Poly Parameters\" << std::endl;\n    for ( int i = 0; i < SCARAMUZZA_POLY_SIZE; i++ )\n        out << std::string( \"p\" ) + boost::lexical_cast< std::string >( i ) << \": \" << params.m_poly[i] << std::endl;\n\n    out << \"Inverse Poly Parameters\" << std::endl;\n    for ( int i = 0; i < SCARAMUZZA_INV_POLY_SIZE; i++ )\n        out << std::string( \"p\" ) + boost::lexical_cast< std::string >( i ) << \": \" << params.m_inv_poly[i] << std::endl;\n\n    out << \"Affine Parameters\" << std::endl;\n    out << \"            ac \" << params.m_C << std::endl\n        << \"            ad \" << params.m_D << std::endl\n        << \"            ae \" << params.m_E << std::endl;\n    out << \"            cx \" << params.m_center_x << std::endl\n        << \"            cy \" << params.m_center_y << std::endl;\n\n    return out;\n}\n\nOCAMCamera::OCAMCamera( )\n: m_inv_scale( 0.0 )\n{\n}\n\nOCAMCamera::OCAMCamera( const OCAMCamera::Parameters& params )\n: mParameters( params )\n{\n    m_inv_scale = 1.0 / ( params.C( ) - params.D( ) * params.E( ) );\n}\n\nCamera::ModelType\nOCAMCamera::modelType( void ) const\n{\n    return mParameters.modelType( );\n}\n\nconst std::string&\nOCAMCamera::cameraName( void ) const\n{\n    return mParameters.cameraName( );\n}\n\nint\nOCAMCamera::imageWidth( void ) const\n{\n    return mParameters.imageWidth( );\n}\n\nint\nOCAMCamera::imageHeight( void ) const\n{\n    return mParameters.imageHeight( );\n}\n\nvoid\nOCAMCamera::estimateIntrinsics( const cv::Size& boardSize,\n                                const std::vector< std::vector< cv::Point3f > >& objectPoints,\n                                const std::vector< std::vector< cv::Point2f > >& imagePoints )\n{\n    // std::cout << \"OCAMCamera::estimateIntrinsics - NOT IMPLEMENTED\" <<\n    // std::endl;\n    // throw std::string(\"OCAMCamera::estimateIntrinsics - NOT IMPLEMENTED\");\n\n    // Reference: Page 30 of\n    // \" Scaramuzza, D. Omnidirectional Vision: from Calibration to Robot Motion\n    // Estimation, ETH Zurich. Thesis no. 17635.\"\n    // http://e-collection.library.ethz.ch/eserv/eth:30301/eth-30301-02.pdf\n    // Matlab code: calibrate.m\n\n    // First, estimate every image's extrinsics parameters\n    std::vector< Eigen::Matrix3d > RList;\n    std::vector< Eigen::Vector3d > TList;\n\n    RList.reserve( imagePoints.size( ) );\n    TList.reserve( imagePoints.size( ) );\n\n    // i-th image\n    for ( size_t image_index = 0; image_index < imagePoints.size( ); ++image_index )\n    {\n        const std::vector< cv::Point3f >& objPts = objectPoints.at( image_index );\n        const std::vector< cv::Point2f >& imgPts = imagePoints.at( image_index );\n\n        assert( objPts.size( ) == imgPts.size( ) );\n        assert( objPts.size( ) == static_cast< unsigned int >( boardSize.width * boardSize.height ) );\n\n        Eigen::MatrixXd M( objPts.size( ), 6 );\n\n        for ( size_t corner_index = 0; corner_index < objPts.size( ); ++corner_index )\n        {\n            double X = objPts.at( corner_index ).x;\n            double Y = objPts.at( corner_index ).y;\n            assert( objPts.at( corner_index ).z == 0.0 );\n\n            double u = imgPts.at( corner_index ).x;\n            double v = imgPts.at( corner_index ).y;\n\n            M( corner_index, 0 ) = -v * X;\n            M( corner_index, 1 ) = -v * Y;\n            M( corner_index, 2 ) = u * X;\n            M( corner_index, 3 ) = u * Y;\n            M( corner_index, 4 ) = -v;\n            M( corner_index, 5 ) = u;\n        }\n\n        Eigen::JacobiSVD< Eigen::MatrixXd > svd( M, Eigen::ComputeFullU | Eigen::ComputeFullV );\n        assert( svd.matrixV( ).cols( ) == 6 );\n        Eigen::VectorXd h = -svd.matrixV( ).col( 5 );\n\n        // scaled version of R and T\n        const double sr11 = h( 0 );\n        const double sr12 = h( 1 );\n        const double sr21 = h( 2 );\n        const double sr22 = h( 3 );\n        const double st1  = h( 4 );\n        const double st2  = h( 5 );\n\n        const double AA = square( sr11 * sr12 + sr21 * sr22 );\n        const double BB = square( sr11 ) + square( sr21 );\n        const double CC = square( sr12 ) + square( sr22 );\n\n        const double sr32_squared_1 = ( -( CC - BB ) + sqrt( square( CC - BB ) + 4.0 * AA ) ) / 2.0;\n        const double sr32_squared_2 = ( -( CC - BB ) - sqrt( square( CC - BB ) + 4.0 * AA ) ) / 2.0;\n\n        // printf(\"rst = %.12f\\n\", sr32_squared_1*sr32_squared_1 +\n        // (CC-BB)*sr32_squared_1 - AA);\n\n        std::vector< double > sr32_squared_values;\n        if ( sr32_squared_1 > 0 )\n            sr32_squared_values.push_back( sr32_squared_1 );\n        if ( sr32_squared_2 > 0 )\n            sr32_squared_values.push_back( sr32_squared_2 );\n        assert( !sr32_squared_values.empty( ) );\n\n        std::vector< double > sr32_values;\n        std::vector< double > sr31_values;\n        for ( auto sr32_squared : sr32_squared_values )\n        {\n            for ( int sign = -1; sign <= 1; sign += 2 )\n            {\n                const double sr32 = static_cast< double >( sign ) * std::sqrt( sr32_squared );\n                sr32_values.push_back( sr32 );\n                if ( sr32_squared == 0.0 )\n                {\n                    // sr31 can be calculated through norm equality,\n                    // but it has positive and negative posibilities\n                    // positive one\n                    sr31_values.push_back( std::sqrt( CC - BB ) );\n                    // negative one\n                    sr32_values.push_back( sr32 );\n                    sr31_values.push_back( -std::sqrt( CC - BB ) );\n\n                    break; // skip the same situation\n                }\n                else\n                {\n                    // sr31 can be calculated throught dot product == 0\n                    sr31_values.push_back( -( sr11 * sr12 + sr21 * sr22 ) / sr32 );\n                }\n            }\n        }\n\n        // std::cout << \"h= \" << std::setprecision(12) << h.transpose() <<\n        // std::endl;\n        // std::cout << \"length: \" << sr32_values.size() << \" & \" <<\n        // sr31_values.size() << std::endl;\n\n        assert( !sr31_values.empty( ) );\n        assert( sr31_values.size( ) == sr32_values.size( ) );\n\n        std::vector< Eigen::Matrix3d > H_values;\n        for ( size_t i = 0; i < sr31_values.size( ); ++i )\n        {\n            const double sr31   = sr31_values.at( i );\n            const double sr32   = sr32_values.at( i );\n            const double lambda = 1.0 / sqrt( sr11 * sr11 + sr21 * sr21 + sr31 * sr31 );\n            Eigen::Matrix3d H;\n            H.setZero( );\n            H( 0, 0 ) = sr11;\n            H( 0, 1 ) = sr12;\n            H( 0, 2 ) = st1;\n            H( 1, 0 ) = sr21;\n            H( 1, 1 ) = sr22;\n            H( 1, 2 ) = st2;\n            H( 2, 0 ) = sr31;\n            H( 2, 1 ) = sr32;\n            H( 2, 2 ) = 0;\n\n            H_values.push_back( lambda * H );\n            H_values.push_back( -lambda * H );\n        }\n\n        for ( auto& H : H_values )\n        {\n            // std::cout << \"H=\\n\" << H << std::endl;\n            Eigen::Matrix3d R;\n            R.col( 0 ) = H.col( 0 );\n            R.col( 1 ) = H.col( 1 );\n            R.col( 2 ) = H.col( 0 ).cross( H.col( 1 ) );\n            // std::cout << \"R33 = \" << R(2,2) << std::endl;\n        }\n\n        std::vector< Eigen::Matrix3d > H_candidates;\n\n        for ( auto& H : H_values )\n        {\n            Eigen::MatrixXd A_mat( 2 * imagePoints.at( image_index ).size( ), 4 );\n            Eigen::VectorXd B_vec( 2 * imagePoints.at( image_index ).size( ) );\n            A_mat.setZero( );\n            B_vec.setZero( );\n\n            size_t line_index = 0;\n\n            // iterate images\n            const double& r11 = H( 0, 0 );\n            const double& r12 = H( 0, 1 );\n            // const double& r13 = H(0,2);\n            const double& r21 = H( 1, 0 );\n            const double& r22 = H( 1, 1 );\n            // const double& r23 = H(1,2);\n            const double& r31 = H( 2, 0 );\n            const double& r32 = H( 2, 1 );\n            // const double& r33 = H(2,2);\n            const double& t1 = H( 0 );\n            const double& t2 = H( 1 );\n\n            // iterate chessboard corners in the image\n            for ( size_t j = 0; j < imagePoints.at( image_index ).size( ); ++j )\n            {\n                assert( line_index == 2 * j );\n\n                const double& X = objectPoints.at( image_index ).at( j ).x;\n                const double& Y = objectPoints.at( image_index ).at( j ).y;\n                const double& u = imagePoints.at( image_index ).at( j ).x;\n                const double& v = imagePoints.at( image_index ).at( j ).y;\n\n                double A   = r21 * X + r22 * Y + t2;\n                double B   = v * ( r31 * X + r32 * Y );\n                double C   = r11 * X + r12 * Y + t1;\n                double D   = u * ( r31 * X + r32 * Y );\n                double rou = std::sqrt( u * u + v * v );\n\n                A_mat( line_index + 0, 0 ) = A;\n                A_mat( line_index + 1, 0 ) = C;\n                A_mat( line_index + 0, 1 ) = A * rou;\n                A_mat( line_index + 1, 1 ) = C * rou;\n                A_mat( line_index + 0, 2 ) = A * rou * rou;\n                A_mat( line_index + 1, 2 ) = C * rou * rou;\n\n                A_mat( line_index + 0, 3 ) = -v;\n                A_mat( line_index + 1, 3 ) = -u;\n                B_vec( line_index + 0 ) = B;\n                B_vec( line_index + 1 ) = D;\n\n                line_index += 2;\n            }\n\n            assert( line_index == static_cast< unsigned int >( A_mat.rows( ) ) );\n\n            // pseudo-inverse for polynomial parameters and all t3s\n            {\n                Eigen::JacobiSVD< Eigen::MatrixXd > svd( A_mat, Eigen::ComputeThinU | Eigen::ComputeThinV );\n\n                Eigen::VectorXd x = svd.solve( B_vec );\n\n                // std::cout << \"x(poly and t3) = \" << x << std::endl;\n\n                if ( x( 2 ) > 0 && x( 3 ) > 0 )\n                {\n                    H_candidates.push_back( H );\n                }\n            }\n        }\n\n        // printf(\"H_candidates.size()=%zu\\n\", H_candidates.size());\n        assert( H_candidates.size( ) == 1 );\n\n        Eigen::Matrix3d& H = H_candidates.front( );\n\n        Eigen::Matrix3d R;\n        R.col( 0 ) = H.col( 0 );\n        R.col( 1 ) = H.col( 1 );\n        R.col( 2 ) = H.col( 0 ).cross( H.col( 1 ) );\n\n        Eigen::Vector3d T = H.col( 2 );\n        RList.push_back( R );\n        TList.push_back( T );\n\n        // std::cout << \"#\" << image_index << \" frame\" << \" R =\" << R << \" \\nT =\n        // \" << T.transpose() << std::endl;\n    }\n\n    // Second, estimate camera intrinsic parameters and all t3\n    Eigen::MatrixXd A_mat( 2 * imagePoints.size( ) * imagePoints.at( 0 ).size( ),\n                           SCARAMUZZA_POLY_SIZE - 1 + imagePoints.size( ) );\n    Eigen::VectorXd B_vec( 2 * imagePoints.size( ) * imagePoints.at( 0 ).size( ) );\n    A_mat.setZero( );\n    B_vec.setZero( );\n\n    size_t line_index = 0;\n\n    // iterate images\n    for ( size_t i = 0; i < imagePoints.size( ); ++i )\n    {\n        const double& r11 = RList.at( i )( 0, 0 );\n        const double& r12 = RList.at( i )( 0, 1 );\n        // const double& r13 = RList.at(i)(0,2);\n        const double& r21 = RList.at( i )( 1, 0 );\n        const double& r22 = RList.at( i )( 1, 1 );\n        // const double& r23 = RList.at(i)(1,2);\n        const double& r31 = RList.at( i )( 2, 0 );\n        const double& r32 = RList.at( i )( 2, 1 );\n        // const double& r33 = RList.at(i)(2,2);\n        const double& t1 = TList.at( i )( 0 );\n        const double& t2 = TList.at( i )( 1 );\n\n        // iterate chessboard corners in the image\n        for ( size_t j = 0; j < imagePoints.at( i ).size( ); ++j )\n        {\n            assert( line_index == 2 * ( i * imagePoints.at( 0 ).size( ) + j ) );\n\n            const double& X = objectPoints.at( i ).at( j ).x;\n            const double& Y = objectPoints.at( i ).at( j ).y;\n            const double& u = imagePoints.at( i ).at( j ).x;\n            const double& v = imagePoints.at( i ).at( j ).y;\n\n            double A   = r21 * X + r22 * Y + t2;\n            double B   = v * ( r31 * X + r32 * Y );\n            double C   = r11 * X + r12 * Y + t1;\n            double D   = u * ( r31 * X + r32 * Y );\n            double rou = std::sqrt( u * u + v * v );\n\n            for ( int k = 1; k <= SCARAMUZZA_POLY_SIZE - 1; ++k )\n            {\n                double pow_rou = 0.0;\n                if ( k == 1 )\n                {\n                    pow_rou = 1.0;\n                }\n                else\n                {\n                    pow_rou = std::pow( rou, k );\n                }\n\n                A_mat( line_index + 0, k - 1 ) = A * pow_rou;\n                A_mat( line_index + 1, k - 1 ) = C * pow_rou;\n            }\n\n            A_mat( line_index + 0, SCARAMUZZA_POLY_SIZE - 1 + i ) = -v;\n            A_mat( line_index + 1, SCARAMUZZA_POLY_SIZE - 1 + i ) = -u;\n            B_vec( line_index + 0 ) = B;\n            B_vec( line_index + 1 ) = D;\n\n            line_index += 2;\n        }\n    }\n\n    assert( line_index == static_cast< unsigned int >( A_mat.rows( ) ) );\n\n    Eigen::Matrix< double, SCARAMUZZA_POLY_SIZE, 1 > poly_coeff;\n    // pseudo-inverse for polynomial parameters and all t3s\n    {\n        Eigen::JacobiSVD< Eigen::MatrixXd > svd( A_mat, Eigen::ComputeThinU | Eigen::ComputeThinV );\n\n        Eigen::VectorXd x = svd.solve( B_vec );\n\n        poly_coeff[0] = x( 0 );\n        poly_coeff[1] = 0.0;\n        for ( int i = 1; i < poly_coeff.size( ) - 1; ++i )\n        {\n            poly_coeff[i + 1] = x( i );\n        }\n        assert( x.size( ) == static_cast< unsigned int >( SCARAMUZZA_POLY_SIZE - 1 + TList.size( ) ) );\n    }\n\n    Parameters params = getParameters( );\n\n    // Affine matrix A is constructed as [C D; E 1]\n    params.C( ) = 1.0;\n    params.D( ) = 0.0;\n    params.E( ) = 0.0;\n\n    params.center_x( ) = params.imageWidth( ) / 2.0;\n    params.center_y( ) = params.imageHeight( ) / 2.0;\n\n    for ( size_t i = 0; i < SCARAMUZZA_POLY_SIZE; ++i )\n    {\n        params.poly( i ) = poly_coeff[i];\n    }\n\n    // params.poly(0) = -216.9657476318;\n    // params.poly(1) = 0.0;\n    // params.poly(2) = 0.0017866911;\n    // params.poly(3) = -0.0000019866;\n    // params.poly(4) =  0.0000000077;\n\n    // inv_poly\n    {\n        std::vector< double > rou_vec;\n        std::vector< double > z_vec;\n        for ( double rou = 0.0; rou <= ( params.imageWidth( ) + params.imageHeight( ) ) / 2; rou += 0.1 )\n        {\n            double rou_pow_k = 1.0;\n            double z         = 0.0;\n\n            for ( int k = 0; k < SCARAMUZZA_POLY_SIZE; k++ )\n            {\n                z += rou_pow_k * params.poly( k );\n                rou_pow_k *= rou;\n            }\n\n            rou_vec.push_back( rou );\n            z_vec.push_back( z );\n        }\n\n        assert( rou_vec.size( ) == z_vec.size( ) );\n        Eigen::VectorXd xVec( rou_vec.size( ) );\n        Eigen::VectorXd yVec( rou_vec.size( ) );\n\n        for ( size_t i = 0; i < rou_vec.size( ); ++i )\n        {\n            xVec( i ) = std::atan2( -z_vec.at( i ), rou_vec.at( i ) );\n            yVec( i ) = rou_vec.at( i );\n        }\n\n        // use lower order poly to eliminate over-fitting cause by\n        // noisy/inaccurate data\n        const int poly_fit_order       = 4;\n        Eigen::VectorXd inv_poly_coeff = polyfit( xVec, yVec, poly_fit_order );\n\n        for ( int i = 0; i <= poly_fit_order; ++i )\n        {\n            params.inv_poly( i ) = inv_poly_coeff( i );\n        }\n    }\n\n    setParameters( params );\n\n    std::cout << \"initial params:\\n\" << params << std::endl;\n}\n\n/**\n * \\brief Lifts a point from the image plane to the unit sphere\n *\n * \\param p image coordinates\n * \\param P coordinates of the point on the sphere\n */\nvoid\nOCAMCamera::liftSphere( const Eigen::Vector2d& p, Eigen::Vector3d& P ) const\n{\n    liftProjective( p, P );\n    P.normalize( );\n}\n\n/**\n * \\brief Lifts a point from the image plane to its projective ray\n *\n * \\param p image coordinates\n * \\param P coordinates of the projective ray\n */\nvoid\nOCAMCamera::liftProjective( const Eigen::Vector2d& p, Eigen::Vector3d& P ) const\n{\n    // Relative to Center\n    Eigen::Vector2d xc( p[0] - mParameters.center_x( ), p[1] - mParameters.center_y( ) );\n\n    // Affine Transformation\n    // xc_a = inv(A) * xc;\n    Eigen::Vector2d xc_a( m_inv_scale * ( xc[0] - mParameters.D( ) * xc[1] ),\n                          m_inv_scale * ( -mParameters.E( ) * xc[0] + mParameters.C( ) * xc[1] ) );\n\n    double phi   = std::sqrt( xc_a[0] * xc_a[0] + xc_a[1] * xc_a[1] );\n    double phi_i = 1.0;\n    double z     = 0.0;\n\n    for ( int i = 0; i < SCARAMUZZA_POLY_SIZE; i++ )\n    {\n        z += phi_i * mParameters.poly( i );\n        phi_i *= phi;\n    }\n\n    P << xc[0], xc[1], -z;\n}\n\nvoid\nOCAMCamera::liftProjective( const Eigen::Vector2d& p, Eigen::Vector3d& P, float image_scale ) const\n{\n    Eigen::Vector2d p_tmp = p / image_scale; // p_tmp is without resize, p is with resize\n    liftProjective( p_tmp, P );              // p_tmp is without resize\n}\n\n/**\n * \\brief Project a 3D point (\\a x,\\a y,\\a z) to the image plane in (\\a u,\\a v)\n *\n * \\param P 3D point coordinates\n * \\param p return value, contains the image point coordinates\n */\nvoid\nOCAMCamera::spaceToPlane( const Eigen::Vector3d& P, Eigen::Vector2d& p ) const\n{\n    double norm    = std::sqrt( P[0] * P[0] + P[1] * P[1] );\n    double theta   = std::atan2( -P[2], norm );\n    double rho     = 0.0;\n    double theta_i = 1.0;\n\n    for ( int i = 0; i < SCARAMUZZA_INV_POLY_SIZE; i++ )\n    {\n        rho += theta_i * mParameters.inv_poly( i );\n        theta_i *= theta;\n    }\n\n    double invNorm = 1.0 / norm;\n    Eigen::Vector2d xn( P[0] * invNorm * rho, P[1] * invNorm * rho );\n\n    p << xn[0] * mParameters.C( ) + xn[1] * mParameters.D( ) + mParameters.center_x( ),\n    xn[0] * mParameters.E( ) + xn[1] + mParameters.center_y( );\n}\n\nvoid\nOCAMCamera::spaceToPlane( const Eigen::Vector3d& P, Eigen::Vector2d& p, float image_scalse ) const\n{\n    Eigen::Vector2d p_tmp;\n    spaceToPlane( P, p_tmp );\n    p = p_tmp * image_scalse;\n}\n\nvoid\nOCAMCamera::spaceToPlane( const Eigen::Vector3d& P, Eigen::Vector2d& p, Eigen::Matrix< double, 2, 3 >& J ) const\n{\n    double norm    = std::sqrt( P[0] * P[0] + P[1] * P[1] );\n    double theta   = std::atan2( -P[2], norm );\n    double rho     = 0.0;\n    double theta_i = 1.0;\n\n    for ( int i = 0; i < SCARAMUZZA_INV_POLY_SIZE; i++ )\n    {\n        rho += theta_i * mParameters.inv_poly( i );\n        theta_i *= theta;\n    }\n\n    double invNorm = 1.0 / norm;\n    Eigen::Vector2d xn( P[0] * invNorm * rho, P[1] * invNorm * rho );\n\n    p << xn[0] * mParameters.C( ) + xn[1] * mParameters.D( ) + mParameters.center_x( ),\n    xn[0] * mParameters.E( ) + xn[1] + mParameters.center_y( );\n}\n/**\n * \\brief Projects an undistorted 2D point p_u to the image plane\n *\n * \\param p_u 2D point coordinates\n * \\return image point coordinates\n */\nvoid\nOCAMCamera::undistToPlane( const Eigen::Vector2d& p_u, Eigen::Vector2d& p ) const\n{\n    Eigen::Vector3d P( p_u[0], p_u[1], 1.0 );\n    spaceToPlane( P, p );\n}\n\nvoid\nOCAMCamera::initUndistortMap( cv::Mat& map1, cv::Mat& map2, double fScale ) const\n{\n    //    cv::Size imageSize(mParameters.imageWidth(),\n    //    mParameters.imageHeight());\n\n    //    cv::Mat mapX = cv::Mat::zeros(imageSize, CV_32F);\n    //    cv::Mat mapY = cv::Mat::zeros(imageSize, CV_32F);\n\n    //    for (int v = 0; v < imageSize.height; ++v)\n    //    {\n    //        for (int u = 0; u < imageSize.width; ++u)\n    //        {\n    //            double mx_u = m_inv_K11 / fScale * u + m_inv_K13 / fScale;\n    //            double my_u = m_inv_K22 / fScale * v + m_inv_K23 / fScale;\n\n    //            double xi = mParameters.xi();\n    //            double d2 = mx_u * mx_u + my_u * my_u;\n\n    //            Eigen::Vector3d P;\n    //            P << mx_u, my_u, 1.0 - xi * (d2 + 1.0) / (xi + sqrt(1.0 + (1.0\n    //            - xi * xi) * d2));\n\n    //            Eigen::Vector2d p;\n    //            spaceToPlane(P, p);\n\n    //            mapX.at<float>(v,u) = p(0);\n    //            mapY.at<float>(v,u) = p(1);\n    //        }\n    //    }\n\n    //    cv::convertMaps(mapX, mapY, map1, map2, CV_32FC1, false);\n}\n\ncv::Mat\nOCAMCamera::initUndistortRectifyMap(\ncv::Mat& map1, cv::Mat& map2, float fx, float fy, cv::Size imageSize, float cx, float cy, cv::Mat rmat ) const\n{\n    if ( imageSize == cv::Size( 0, 0 ) )\n    {\n        imageSize = cv::Size( mParameters.imageWidth( ), mParameters.imageHeight( ) );\n    }\n\n    cv::Mat mapX = cv::Mat::zeros( imageSize.height, imageSize.width, CV_32F );\n    cv::Mat mapY = cv::Mat::zeros( imageSize.height, imageSize.width, CV_32F );\n\n    Eigen::Matrix3f K_rect;\n\n    K_rect << fx, 0, cx < 0 ? imageSize.width / 2 : cx, 0, fy, cy < 0 ? imageSize.height / 2 : cy, 0, 0, 1;\n\n    if ( fx < 0 || fy < 0 )\n    {\n        throw std::string( std::string( __FUNCTION__ ) + \": Focal length must be specified\" );\n    }\n\n    Eigen::Matrix3f K_rect_inv = K_rect.inverse( );\n\n    Eigen::Matrix3f R, R_inv;\n    cv::cv2eigen( rmat, R );\n    R_inv = R.inverse( );\n\n    for ( int v = 0; v < imageSize.height; ++v )\n    {\n        for ( int u = 0; u < imageSize.width; ++u )\n        {\n            Eigen::Vector3f xo;\n            xo << u, v, 1;\n\n            Eigen::Vector3f uo = R_inv * K_rect_inv * xo;\n\n            Eigen::Vector2d p;\n            spaceToPlane( uo.cast< double >( ), p );\n\n            mapX.at< float >( v, u ) = p( 0 );\n            mapY.at< float >( v, u ) = p( 1 );\n        }\n    }\n\n    cv::convertMaps( mapX, mapY, map1, map2, CV_32FC1, false );\n\n    cv::Mat K_rect_cv;\n    cv::eigen2cv( K_rect, K_rect_cv );\n    return K_rect_cv;\n}\n\nint\nOCAMCamera::parameterCount( void ) const\n{\n    return SCARAMUZZA_CAMERA_NUM_PARAMS;\n}\n\nconst OCAMCamera::Parameters&\nOCAMCamera::getParameters( void ) const\n{\n    return mParameters;\n}\n\nvoid\nOCAMCamera::setParameters( const OCAMCamera::Parameters& parameters )\n{\n    mParameters = parameters;\n\n    m_inv_scale = 1.0 / ( parameters.C( ) - parameters.D( ) * parameters.E( ) );\n}\n\nvoid\nOCAMCamera::readParameters( const std::vector< double >& parameterVec )\n{\n    if ( ( int )parameterVec.size( ) != parameterCount( ) )\n    {\n        return;\n    }\n\n    Parameters params = getParameters( );\n\n    params.C( )        = parameterVec.at( 0 );\n    params.D( )        = parameterVec.at( 1 );\n    params.E( )        = parameterVec.at( 2 );\n    params.center_x( ) = parameterVec.at( 3 );\n    params.center_y( ) = parameterVec.at( 4 );\n    for ( int i          = 0; i < SCARAMUZZA_POLY_SIZE; i++ )\n        params.poly( i ) = parameterVec.at( 5 + i );\n    for ( int i              = 0; i < SCARAMUZZA_INV_POLY_SIZE; i++ )\n        params.inv_poly( i ) = parameterVec.at( 5 + SCARAMUZZA_POLY_SIZE + i );\n\n    setParameters( params );\n}\n\nvoid\nOCAMCamera::writeParameters( std::vector< double >& parameterVec ) const\n{\n    parameterVec.resize( parameterCount( ) );\n    parameterVec.at( 0 ) = mParameters.C( );\n    parameterVec.at( 1 ) = mParameters.D( );\n    parameterVec.at( 2 ) = mParameters.E( );\n    parameterVec.at( 3 ) = mParameters.center_x( );\n    parameterVec.at( 4 ) = mParameters.center_y( );\n    for ( int i                  = 0; i < SCARAMUZZA_POLY_SIZE; i++ )\n        parameterVec.at( 5 + i ) = mParameters.poly( i );\n    for ( int i                                         = 0; i < SCARAMUZZA_INV_POLY_SIZE; i++ )\n        parameterVec.at( 5 + SCARAMUZZA_POLY_SIZE + i ) = mParameters.inv_poly( i );\n}\n\nvoid\nOCAMCamera::writeParametersToYamlFile( const std::string& filename ) const\n{\n    mParameters.writeToYamlFile( filename );\n}\n\nstd::string\nOCAMCamera::parametersToString( void ) const\n{\n    std::ostringstream oss;\n    oss << mParameters;\n\n    return oss.str( );\n}\n}\n", "meta": {"hexsha": "185beedaa4070f581aa297237e3a003ae098d061", "size": 28518, "ext": "cc", "lang": "C++", "max_stars_repo_path": "3_estimator/camera_model/src/camera_models/ScaramuzzaCamera.cc", "max_stars_repo_name": "huying163/ros_environment", "max_stars_repo_head_hexsha": "bac3343bf92e6fa2bd852baf261e80712564f990", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2018-01-30T11:40:31.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-03T05:52:47.000Z", "max_issues_repo_path": "3_estimator/camera_model/src/camera_models/ScaramuzzaCamera.cc", "max_issues_repo_name": "huying163/ros_environment", "max_issues_repo_head_hexsha": "bac3343bf92e6fa2bd852baf261e80712564f990", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "3_estimator/camera_model/src/camera_models/ScaramuzzaCamera.cc", "max_forks_repo_name": "huying163/ros_environment", "max_forks_repo_head_hexsha": "bac3343bf92e6fa2bd852baf261e80712564f990", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-12-23T08:14:57.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-23T08:14:57.000Z", "avg_line_length": 32.1148648649, "max_line_length": 121, "alphanum_fraction": 0.5255277369, "num_tokens": 8643, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6477982179521103, "lm_q2_score": 0.523420348936324, "lm_q1q2_score": 0.33907076928082247}}
{"text": "#include <GL/freeglut.h>\n#include <vector>\n#include <Eigen/Eigen>\n#include <iostream>\n#include <iomanip>\n#include <fstream>\n#include <iostream>\n#include <thread>\n\n#include <pcl/point_types.h>\n#include <pcl/point_cloud.h>\n#include <pcl/io/pcd_io.h>\n#include <pcl/kdtree/kdtree_flann.h>\n\n#include \"structures.h\"\n#include \"transformations.h\"\n#include \"cauchy.h\"\n\n#include \"point_to_point_tait_bryan_wc_jacobian.h\"\n#include \"point_to_point_source_to_target_tait_bryan_wc_jacobian.h\"\n\n#include \"rgd.h\"\n\nstruct ScanPose{\n\tEigen::Affine3d m;\n\tpcl::PointCloud<pcl::PointXYZ> pc;\n};\n\npcl::PointCloud<pcl::PointXYZ> pc_ground_truth;\nstd::vector<ScanPose> scan_poses;\nint current_scan_index = 0;\n\nfloat sradius = 1.0;\nbool show_ground_truth = true;\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();\nvoid set_initial_guess(std::vector<ScanPose>& scan_poses);\n\nvoid split(std::string &str, char delim, std::vector<std::string> &out)\n{\n\tsize_t start;\n\tsize_t end = 0;\n\n\twhile ((start = str.find_first_not_of(delim, end)) != std::string::npos)\n\t{\n\t\tend = str.find(delim, start);\n\t\tout.push_back(str.substr(start, end - start));\n\t}\n}\n\nstd::vector<std::pair<int,int>> nns(ScanPose &sp1, ScanPose &sp2, float radius);\n\nstd::vector<std::pair<int,int>> pairs_temp;\nstd::vector<Bucket> buckets_render;\nbool show_ndt_covariances = true;\n\nint main(int argc, char *argv[]){\n\n\tstd::vector<std::string> pcd_file_names;\n\tpcd_file_names.push_back(\"../data/pcd/scan000.pcd\");\n\tpcd_file_names.push_back(\"../data/pcd/scan001.pcd\");\n\tpcd_file_names.push_back(\"../data/pcd/scan002.pcd\");\n\tpcd_file_names.push_back(\"../data/pcd/scan003.pcd\");\n\tpcd_file_names.push_back(\"../data/pcd/scan004.pcd\");\n\tpcd_file_names.push_back(\"../data/pcd/scan005.pcd\");\n\tpcd_file_names.push_back(\"../data/pcd/scan006.pcd\");\n\tpcd_file_names.push_back(\"../data/pcd/scan007.pcd\");\n\tpcd_file_names.push_back(\"../data/pcd/scan008.pcd\");\n\tpcd_file_names.push_back(\"../data/pcd/scan009.pcd\");\n\tpcd_file_names.push_back(\"../data/pcd/scan010.pcd\");\n\tpcd_file_names.push_back(\"../data/pcd/scan011.pcd\");\n\tpcd_file_names.push_back(\"../data/pcd/scan012.pcd\");\n\n\tfor(size_t i = 0; i < pcd_file_names.size(); i++){\n\t\tstd::cout << \"loading file: \" << pcd_file_names[i] << std::endl;\n\t\tScanPose sp;\n\t\tsp.m = Eigen::Affine3d::Identity();\n\t\tpcl::PointCloud<pcl::PointXYZ> pc;\n\t\tif (pcl::io::loadPCDFile(pcd_file_names[i], pc) == -1) {\n\t\t\tstd::cout << \"PROBLEM WITH LODAING pcd: \" << pcd_file_names[i] << std::endl;\n\t\t\treturn 1;\n\t\t}else{\n\t\t\tsp.pc = pc;\n\t\t\tscan_poses.push_back(sp);\n\t\t}\n\t}\n\n\tif (pcl::io::loadPCDFile(\"../data/pcd/ground_truth.pcd\", pc_ground_truth) == -1) {\n\t\tstd::cout << \"PROBLEM WITH LODAING pcd: ../data/pcd/ground_truth.pcd\" << std::endl;\n\t\treturn 1;\n\t}\n\n\tset_initial_guess(scan_poses);\n\n\tif (false == initGL(&argc, argv)) {\n\t\treturn 4;\n\t}\n\n\tprintHelp();\n\tglutDisplayFunc(display);\n\tglutKeyboardFunc(keyboard);\n\tglutMouseFunc(mouse);\n\tglutMotionFunc(motion);\n\tglutMainLoop();\n\n\treturn 0;\n}\n\nbool initGL(int *argc, char **argv) {\n\tglutInit(argc, argv);\n\tglutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE);\n\tglutInitWindowSize(window_width, window_height);\n\tglutCreateWindow(\"point_cloud_registration\");\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 draw_ellipse(const Eigen::Matrix3d& covar, Eigen::Vector3d& mean, Eigen::Vector3f color, float nstd  = 3)\n{\n\n    Eigen::LLT<Eigen::Matrix<double,3,3> > cholSolver(covar);\n    Eigen::Matrix3d transform = cholSolver.matrixL();\n\n    const double pi = 3.141592;\n    const double di =0.02;\n    const double dj =0.04;\n    const double du =di*2*pi;\n    const double dv =dj*pi;\n    glColor3f(color.x(), color.y(),color.z());\n\n    for (double i = 0; i < 1.0; i+=di)  //horizonal\n    {\n        for (double j = 0; j < 1.0; j+=dj)  //vertical\n        {\n            double u = i*2*pi;      //0     to  2pi\n            double v = (j-0.5)*pi;  //-pi/2 to pi/2\n\n            const Eigen::Vector3d pp0( cos(v)* cos(u),cos(v) * sin(u),sin(v));\n            const Eigen::Vector3d pp1(cos(v) * cos(u + du) ,cos(v) * sin(u + du) ,sin(v));\n            const Eigen::Vector3d pp2(cos(v + dv)* cos(u + du) ,cos(v + dv)* sin(u + du) ,sin(v + dv));\n            const Eigen::Vector3d pp3( cos(v + dv)* cos(u),cos(v + dv)* sin(u),sin(v + dv));\n            Eigen::Vector3d tp0 = transform * (nstd*pp0) + mean;\n            Eigen::Vector3d tp1 = transform * (nstd*pp1) + mean;\n            Eigen::Vector3d tp2 = transform * (nstd*pp2) + mean;\n            Eigen::Vector3d tp3 = transform * (nstd*pp3) + mean;\n\n            glBegin(GL_LINE_LOOP);\n            glVertex3dv(tp0.data());\n            glVertex3dv(tp1.data());\n            glVertex3dv(tp2.data());\n            glVertex3dv(tp3.data());\n            glEnd();\n        }\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\tglBegin(GL_POINTS);\n\tglColor3f(1.0, 0.0, 0.0);\n\tfor(size_t i = 0; i < scan_poses.size(); i++){\n\t\tif(i == current_scan_index){\n\t\t\tglColor3f(0.0, 1.0, 0.0);\n\t\t}else{\n\t\t\tglColor3f(1.0, 0.0, 0.0);\n\t\t}\n\t\tif(i+1 == current_scan_index){\n\t\t\tglColor3f(0.0, 0.0, 1.0);\n\t\t}\n\t\tfor(size_t j = 0; j < scan_poses[i].pc.size(); j++){\n\t\t\tEigen::Vector3d v(scan_poses[i].pc[j].x, scan_poses[i].pc[j].y, scan_poses[i].pc[j].z);\n\t\t\tEigen::Vector3d vt = scan_poses[i].m * v;\n\t\t\tglVertex3f(vt.x(), vt.y(), vt.z());\n\t\t}\n\t}\n\tglEnd();\n\n\tglColor3f(0,0,0);\n\tglBegin(GL_LINES);\n\tfor(size_t i = 0 ; i < pairs_temp.size(); i++){\n\t\tpcl::PointXYZ p1 = scan_poses[0].pc[pairs_temp[i].first];\n\t\tpcl::PointXYZ p2 = scan_poses[1].pc[pairs_temp[i].second];\n\n\t\tEigen::Vector3d v1(p1.x, p1.y, p1.z);\n\t\tEigen::Vector3d v1t = scan_poses[0].m * v1;\n\n\t\tglVertex3f(v1t.x(), v1t.y(), v1t.z());\n\n\t\tEigen::Vector3d v2(p2.x, p2.y, p2.z);\n\t\tEigen::Vector3d v2t = scan_poses[1].m * v2;\n\n\t\tglVertex3f(v2t.x(), v2t.y(), v2t.z());\n\n\t}\n\tglEnd();\n\n\tif(show_ground_truth){\n\t\tglColor3f(0.7, 0.7, 0.7);\n\t\tglBegin(GL_POINTS);\n\t\tfor(size_t i = 0; i < pc_ground_truth.size(); i++){\n\t\t\tglVertex3f(pc_ground_truth[i].x, pc_ground_truth[i].y, pc_ground_truth[i].z);\n\t\t}\n\t\tglEnd();\n\t}\n\n\tif(show_ndt_covariances){\n\t\tfor(size_t i = 0 ; i < buckets_render.size(); i++){\n\t\t\tif(buckets_render[i].number_of_points > 10){\n\t\t\t\tdraw_ellipse(buckets_render[i].cov, buckets_render[i].mean, Eigen::Vector3f(0.0, 0.0, 1.0), 1);\n\t\t\t}\n\t\t}\n\t}\n\n\tglutSwapBuffers();\n}\n\nvoid ndt_job(int i, Job* job, std::vector<Bucket>* buckets, Eigen::SparseMatrix<double > *AtPA,\n\t\tEigen::SparseMatrix<double > *AtPB, std::vector<PointBucketIndexPair> *index_pair_internal, std::vector<Point3D> *pp,\n\t\tstd::vector<TaitBryanPose> *poses, std::vector<Eigen::Affine3d> *mposes_inv, size_t trajectory_size) {\n\n\tstd::vector<Eigen::Triplet<double>> tripletListA;\n\tstd::vector<Eigen::Triplet<double>> tripletListP;\n\tstd::vector<Eigen::Triplet<double>> tripletListB;\n\n\tfor (size_t ii = job->index_begin_inclusive; ii < job->index_end_exclusive; ii++) {\n\t\tBucket& b = (*buckets)[ii];\n\t\tif (b.number_of_points < 5)continue;\n\n\t\tEigen::Vector3d mean(0, 0, 0);\n\t\tEigen::Matrix3d cov;\n\t\tcov.setZero();\n\n\t\tfor (int index = b.index_begin; index < b.index_end; index++) {\n\t\t\tconst auto& p = (*pp)[(*index_pair_internal)[index].index_of_point];\n\t\t\tmean += Eigen::Vector3d(p.x, p.y, p.z);\n\t\t}\n\t\tmean /= b.number_of_points;\n\n\t\tfor (int index = b.index_begin; index < b.index_end; index++) {\n\t\t\tconst auto& p = (*pp)[(*index_pair_internal)[index].index_of_point];\n\t\t\tcov(0, 0) += (mean.x() - p.x) * (mean.x() - p.x);\n\t\t\tcov(0, 1) += (mean.x() - p.x) * (mean.y() - p.y);\n\t\t\tcov(0, 2) += (mean.x() - p.x) * (mean.z() - p.z);\n\t\t\tcov(1, 0) += (mean.y() - p.y) * (mean.x() - p.x);\n\t\t\tcov(1, 1) += (mean.y() - p.y) * (mean.y() - p.y);\n\t\t\tcov(1, 2) += (mean.y() - p.y) * (mean.z() - p.z);\n\t\t\tcov(2, 0) += (mean.z() - p.z) * (mean.x() - p.x);\n\t\t\tcov(2, 1) += (mean.z() - p.z) * (mean.y() - p.y);\n\t\t\tcov(2, 2) += (mean.z() - p.z) * (mean.z() - p.z);\n\t\t}\n\t\tcov /= b.number_of_points;\n\n\t\t(*buckets)[ii].mean = mean;\n\t\t(*buckets)[ii].cov = cov;\n\n\n\t\tEigen::Matrix3d infm = cov.inverse();\n\n\t\tif (!(infm(0, 0) == infm(0, 0)))continue;\n\t\tif (!(infm(0, 1) == infm(0, 1)))continue;\n\t\tif (!(infm(0, 2) == infm(0, 2)))continue;\n\n\t\tif (!(infm(1, 0) == infm(1, 0)))continue;\n\t\tif (!(infm(1, 1) == infm(1, 1)))continue;\n\t\tif (!(infm(1, 2) == infm(1, 2)))continue;\n\n\t\tif (!(infm(2, 0) == infm(2, 0)))continue;\n\t\tif (!(infm(2, 1) == infm(2, 1)))continue;\n\t\tif (!(infm(2, 2) == infm(2, 2)))continue;\n\n\n\n\t\tfor (int index = b.index_begin; index < b.index_end; index++) {\n\t\t\tconst auto& p = (*pp)[(*index_pair_internal)[index].index_of_point];\n\n\t\t\tEigen::Vector3d point_local(p.x, p.y, p.z);\n\t\t\tpoint_local = (*mposes_inv)[p.index_pose] * point_local;\n\n\n\t\t\tTaitBryanPose pose_s = (*poses)[p.index_pose];\n\t\t\tdouble delta_x;\n\t\t\tdouble delta_y;\n\t\t\tdouble delta_z;\n\n\t\t\tpoint_to_point_source_to_target_tait_bryan_wc(delta_x, delta_y, delta_z,\n\t\t\t\tpose_s.px, pose_s.py, pose_s.pz, pose_s.om, pose_s.fi, pose_s.ka,\n\t\t\t\tpoint_local.x(), point_local.y(), point_local.z(), mean.x(), mean.y(), mean.z());\n\n\t\t\tEigen::Matrix<double, 3, 6, Eigen::RowMajor> jacobian;\n\t\t\tpoint_to_point_source_to_target_tait_bryan_wc_jacobian(jacobian,\n\t\t\t\tpose_s.px, pose_s.py, pose_s.pz, pose_s.om, pose_s.fi, pose_s.ka,\n\t\t\t\tpoint_local.x(), point_local.y(), point_local.z());\n\n\n\t\t\tint ir = tripletListB.size();\n\t\t\tint c = p.index_pose * 6;\n\n\t\t\tfor (int row = 0; row < 3; row++) {\n\t\t\t\tfor (int col = 0; col < 6; col++) {\n\t\t\t\t\tif (jacobian(row, col) != 0.0) {\n\t\t\t\t\t\ttripletListA.emplace_back(ir + row, c + col, -jacobian(row, col));\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\ttripletListP.emplace_back(ir, ir, infm(0, 0));\n\t\t\ttripletListP.emplace_back(ir, ir + 1, infm(0, 1));\n\t\t\ttripletListP.emplace_back(ir, ir + 2, infm(0, 2));\n\t\t\ttripletListP.emplace_back(ir + 1, ir, infm(1, 0));\n\t\t\ttripletListP.emplace_back(ir + 1, ir + 1, infm(1, 1));\n\t\t\ttripletListP.emplace_back(ir + 1, ir + 2, infm(1, 2));\n\t\t\ttripletListP.emplace_back(ir + 2, ir, infm(2, 0));\n\t\t\ttripletListP.emplace_back(ir + 2, ir + 1, infm(2, 1));\n\t\t\ttripletListP.emplace_back(ir + 2, ir + 2, infm(2, 2));\n\n\t\t\ttripletListB.emplace_back(ir, 0, delta_x);\n\t\t\ttripletListB.emplace_back(ir + 1, 0, delta_y);\n\t\t\ttripletListB.emplace_back(ir + 2, 0, delta_z);\n\t\t}\n\t}\n\n\tEigen::SparseMatrix<double> matA(tripletListB.size(), trajectory_size * 6);\n\tEigen::SparseMatrix<double> matP(tripletListB.size(), tripletListB.size());\n\tEigen::SparseMatrix<double> matB(tripletListB.size(), 1);\n\n\tmatA.setFromTriplets(tripletListA.begin(), tripletListA.end());\n\tmatP.setFromTriplets(tripletListP.begin(), tripletListP.end());\n\tmatB.setFromTriplets(tripletListB.begin(), tripletListB.end());\n\n\n\tEigen::SparseMatrix<double> AtPAt(trajectory_size * 6, trajectory_size * 6);\n\tEigen::SparseMatrix<double> AtPBt(trajectory_size * 6, 1);\n\n\t{\n\t\tEigen::SparseMatrix<double> AtP = matA.transpose() * matP;\n\t\tAtPAt = AtP * matA;\n\t\tAtPBt = AtP * matB;\n\n\t\t(*AtPA) = AtPAt;\n\t\t(*AtPB) = AtPBt;\n\t}\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\t\t\tcurrent_scan_index --;\n\t\t\tif(current_scan_index < 0)current_scan_index = 0;\n\t\t\tbreak;\n\t\t}\n\t\tcase '=':{\n\t\t\tcurrent_scan_index ++;\n\t\t\tif(current_scan_index >= scan_poses.size())current_scan_index = scan_poses.size() - 1;\n\t\t\tbreak;\n\t\t}\n\t\tcase 'a':{\n\t\t\tTaitBryanPose pose;\n\t\t\tpose.px = 0;\n\t\t\tpose.py = -0.1;\n\t\t\tpose.pz = 0;\n\t\t\tpose.om = 0;\n\t\t\tpose.fi = 0;\n\t\t\tpose.ka = 0;\n\t\t\tscan_poses[current_scan_index].m = scan_poses[current_scan_index].m * affine_matrix_from_pose_tait_bryan(pose);\n\t\t\tbreak;\n\t\t}\n\t\tcase 'd':{\n\t\t\tTaitBryanPose pose;\n\t\t\tpose.px = 0;\n\t\t\tpose.py = 0.1;\n\t\t\tpose.pz = 0;\n\t\t\tpose.om = 0;\n\t\t\tpose.fi = 0;\n\t\t\tpose.ka = 0;\n\t\t\tscan_poses[current_scan_index].m = scan_poses[current_scan_index].m * affine_matrix_from_pose_tait_bryan(pose);\n\t\t\tbreak;\n\t\t}\n\t\tcase 'w':{\n\t\t\tTaitBryanPose pose;\n\t\t\tpose.px = 0.1;\n\t\t\tpose.py = 0;\n\t\t\tpose.pz = 0;\n\t\t\tpose.om = 0;\n\t\t\tpose.fi = 0;\n\t\t\tpose.ka = 0;\n\t\t\tscan_poses[current_scan_index].m = scan_poses[current_scan_index].m * affine_matrix_from_pose_tait_bryan(pose);\n\t\t\tbreak;\n\t\t}\n\t\tcase 's':{\n\t\t\tTaitBryanPose pose;\n\t\t\tpose.px = -0.1;\n\t\t\tpose.py = 0;\n\t\t\tpose.pz = 0;\n\t\t\tpose.om = 0;\n\t\t\tpose.fi = 0;\n\t\t\tpose.ka = 0;\n\t\t\tscan_poses[current_scan_index].m = scan_poses[current_scan_index].m * affine_matrix_from_pose_tait_bryan(pose);\n\t\t\tbreak;\n\t\t}\n\t\tcase 'z':{\n\t\t\tTaitBryanPose pose;\n\t\t\tpose.px = 0;\n\t\t\tpose.py = 0;\n\t\t\tpose.pz = 0;\n\t\t\tpose.om = 0;\n\t\t\tpose.fi = 0;\n\t\t\tpose.ka = -0.01;\n\t\t\tscan_poses[current_scan_index].m = scan_poses[current_scan_index].m * affine_matrix_from_pose_tait_bryan(pose);\n\t\t\tbreak;\n\t\t}\n\t\tcase 'x':{\n\t\t\tTaitBryanPose pose;\n\t\t\tpose.px = 0;\n\t\t\tpose.py = 0;\n\t\t\tpose.pz = 0;\n\t\t\tpose.om = 0;\n\t\t\tpose.fi = 0;\n\t\t\tpose.ka = 0.01;\n\t\t\tscan_poses[current_scan_index].m = scan_poses[current_scan_index].m * affine_matrix_from_pose_tait_bryan(pose);\n\t\t\tbreak;\n\t\t}\n\t\tcase 'p':{\n\t\t\tfor(size_t i = 0; i < scan_poses.size(); i++){\n\t\t\t\tstd::cout << \"scan: \" << i << std::endl;\n\t\t\t\tstd::cout << scan_poses[i].m.matrix() << std::endl;\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t\tcase 'n':{\n\t\t\tpairs_temp = nns(scan_poses[0], scan_poses[1], sradius);\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\tfor(size_t i = 0 ; i < scan_poses.size() ; i++){\n\t\t\t\tfor(size_t j = i+1 ; j < scan_poses.size() ; j++){\n\t\t\t\t\t//if(i == j)continue;\n\t\t\t\t\tstd::vector<std::pair<int,int>> nn = nns(scan_poses[i], scan_poses[j], sradius);\n\t\t\t\t\tstd::cout << nn.size() << \",\" << scan_poses[i].pc.size() << \",\" << scan_poses[j].pc.size() << std::endl;\n\n\t\t\t\t\tTaitBryanPose pose_1 = pose_tait_bryan_from_affine_matrix(scan_poses[i].m);\n\t\t\t\t\tTaitBryanPose pose_2 = pose_tait_bryan_from_affine_matrix(scan_poses[j].m);\n\n\t\t\t\t\tfor(size_t k = 0 ; k < nn.size(); k+=1){\n\t\t\t\t\t\tpcl::PointXYZ &p_1 = scan_poses[i].pc[nn[k].first];\n\t\t\t\t\t\tpcl::PointXYZ &p_2 = scan_poses[j].pc[nn[k].second];\n\t\t\t\t\t\tdouble delta_x;\n\t\t\t\t\t\tdouble delta_y;\n\t\t\t\t\t\tdouble delta_z;\n\t\t\t\t\t\tpoint_to_point_tait_bryan_wc(delta_x, delta_y, delta_z, pose_1.px, pose_1.py, pose_1.pz, pose_1.om, pose_1.fi, pose_1.ka, pose_2.px, pose_2.py, pose_2.pz, pose_2.om, pose_2.fi, pose_2.ka, p_1.x, p_1.y, p_1.z, p_2.x, p_2.y, p_2.z);\n\n\t\t\t\t\t\tEigen::Matrix<double, 3, 12, Eigen::RowMajor> jacobian;\n\t\t\t\t\t\tpoint_to_point_tait_bryan_wc_jacobian(jacobian, pose_1.px, pose_1.py, pose_1.pz, pose_1.om, pose_1.fi, pose_1.ka, pose_2.px, pose_2.py, pose_2.pz, pose_2.om, pose_2.fi, pose_2.ka, p_1.x, p_1.y, p_1.z, p_2.x, p_2.y, p_2.z);\n\n\t\t\t\t\t\tint ir = tripletListB.size();\n\t\t\t\t\t\tint ic_1 = i * 6;\n\t\t\t\t\t\tint ic_2 = j * 6;\n\n\t\t\t\t\t\ttripletListA.emplace_back(ir     , ic_1    , -jacobian(0,0));\n\t\t\t\t\t\ttripletListA.emplace_back(ir     , ic_1 + 1, -jacobian(0,1));\n\t\t\t\t\t\ttripletListA.emplace_back(ir     , ic_1 + 2, -jacobian(0,2));\n\t\t\t\t\t\ttripletListA.emplace_back(ir     , ic_1 + 3, -jacobian(0,3));\n\t\t\t\t\t\ttripletListA.emplace_back(ir     , ic_1 + 4, -jacobian(0,4));\n\t\t\t\t\t\ttripletListA.emplace_back(ir     , ic_1 + 5, -jacobian(0,5));\n\n\t\t\t\t\t\ttripletListA.emplace_back(ir     , ic_2    , -jacobian(0,6));\n\t\t\t\t\t\ttripletListA.emplace_back(ir     , ic_2 + 1, -jacobian(0,7));\n\t\t\t\t\t\ttripletListA.emplace_back(ir     , ic_2 + 2, -jacobian(0,8));\n\t\t\t\t\t\ttripletListA.emplace_back(ir     , ic_2 + 3, -jacobian(0,9));\n\t\t\t\t\t\ttripletListA.emplace_back(ir     , ic_2 + 4, -jacobian(0,10));\n\t\t\t\t\t\ttripletListA.emplace_back(ir     , ic_2 + 5, -jacobian(0,11));\n\n\t\t\t\t\t\ttripletListA.emplace_back(ir + 1 , ic_1    , -jacobian(1,0));\n\t\t\t\t\t\ttripletListA.emplace_back(ir + 1 , ic_1 + 1, -jacobian(1,1));\n\t\t\t\t\t\ttripletListA.emplace_back(ir + 1 , ic_1 + 2, -jacobian(1,2));\n\t\t\t\t\t\ttripletListA.emplace_back(ir + 1 , ic_1 + 3, -jacobian(1,3));\n\t\t\t\t\t\ttripletListA.emplace_back(ir + 1 , ic_1 + 4, -jacobian(1,4));\n\t\t\t\t\t\ttripletListA.emplace_back(ir + 1 , ic_1 + 5, -jacobian(1,5));\n\n\t\t\t\t\t\ttripletListA.emplace_back(ir + 1 , ic_2    , -jacobian(1,6));\n\t\t\t\t\t\ttripletListA.emplace_back(ir + 1 , ic_2 + 1, -jacobian(1,7));\n\t\t\t\t\t\ttripletListA.emplace_back(ir + 1 , ic_2 + 2, -jacobian(1,8));\n\t\t\t\t\t\ttripletListA.emplace_back(ir + 1 , ic_2 + 3, -jacobian(1,9));\n\t\t\t\t\t\ttripletListA.emplace_back(ir + 1 , ic_2 + 4, -jacobian(1,10));\n\t\t\t\t\t\ttripletListA.emplace_back(ir + 1 , ic_2 + 5, -jacobian(1,11));\n\n\t\t\t\t\t\ttripletListA.emplace_back(ir + 2 , ic_1    , -jacobian(2,0));\n\t\t\t\t\t\ttripletListA.emplace_back(ir + 2 , ic_1 + 1, -jacobian(2,1));\n\t\t\t\t\t\ttripletListA.emplace_back(ir + 2 , ic_1 + 2, -jacobian(2,2));\n\t\t\t\t\t\ttripletListA.emplace_back(ir + 2 , ic_1 + 3, -jacobian(2,3));\n\t\t\t\t\t\ttripletListA.emplace_back(ir + 2 , ic_1 + 4, -jacobian(2,4));\n\t\t\t\t\t\ttripletListA.emplace_back(ir + 2 , ic_1 + 5, -jacobian(2,5));\n\n\t\t\t\t\t\ttripletListA.emplace_back(ir + 2 , ic_2    , -jacobian(2,6));\n\t\t\t\t\t\ttripletListA.emplace_back(ir + 2 , ic_2 + 1, -jacobian(2,7));\n\t\t\t\t\t\ttripletListA.emplace_back(ir + 2 , ic_2 + 2, -jacobian(2,8));\n\t\t\t\t\t\ttripletListA.emplace_back(ir + 2 , ic_2 + 3, -jacobian(2,9));\n\t\t\t\t\t\ttripletListA.emplace_back(ir + 2 , ic_2 + 4, -jacobian(2,10));\n\t\t\t\t\t\ttripletListA.emplace_back(ir + 2 , ic_2 + 5, -jacobian(2,11));\n\n\t\t\t\t\t\ttripletListP.emplace_back(ir    , ir    ,  1);//cauchy(delta_x, 1));\n\t\t\t\t\t\ttripletListP.emplace_back(ir + 1, ir + 1,  1);//cauchy(delta_y, 1));\n\t\t\t\t\t\ttripletListP.emplace_back(ir + 2, ir + 2,  1);//cauchy(delta_z, 1));\n\n\t\t\t\t\t\ttripletListB.emplace_back(ir    , 0,  delta_x);\n\t\t\t\t\t\ttripletListB.emplace_back(ir + 1, 0,  delta_y);\n\t\t\t\t\t\ttripletListB.emplace_back(ir + 2, 0,  delta_z);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tint ir = tripletListB.size();\n\t\t\ttripletListA.emplace_back(ir     , 0, 1);\n\t\t\ttripletListA.emplace_back(ir + 1 , 1, 1);\n\t\t\ttripletListA.emplace_back(ir + 2 , 2, 1);\n\t\t\ttripletListA.emplace_back(ir + 3 , 3, 1);\n\t\t\ttripletListA.emplace_back(ir + 4 , 4, 1);\n\t\t\ttripletListA.emplace_back(ir + 5 , 5, 1);\n\n\t\t\ttripletListP.emplace_back(ir     , ir,     1000000);\n\t\t\ttripletListP.emplace_back(ir + 1 , ir + 1, 1000000);\n\t\t\ttripletListP.emplace_back(ir + 2 , ir + 2, 1000000);\n\t\t\ttripletListP.emplace_back(ir + 3 , ir + 3, 1000000);\n\t\t\ttripletListP.emplace_back(ir + 4 , ir + 4, 1000000);\n\t\t\ttripletListP.emplace_back(ir + 5 , ir + 5, 1000000);\n\n\t\t\ttripletListB.emplace_back(ir     , 0, 0);\n\t\t\ttripletListB.emplace_back(ir + 1 , 0, 0);\n\t\t\ttripletListB.emplace_back(ir + 2 , 0, 0);\n\t\t\ttripletListB.emplace_back(ir + 3 , 0, 0);\n\t\t\ttripletListB.emplace_back(ir + 4 , 0, 0);\n\t\t\ttripletListB.emplace_back(ir + 5 , 0, 0);\n\n\t\t\tEigen::SparseMatrix<double> matA(tripletListB.size(), scan_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\t\t\tEigen::SparseMatrix<double> AtPA(scan_poses.size() * 6, scan_poses.size() * 6);\n\t\t\tEigen::SparseMatrix<double> AtPB(scan_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\n\t\t\tstd::cout << \"AtPA.size: \" << AtPA.size() << std::endl;\n\t\t\tstd::cout << \"AtPB.size: \" << AtPB.size() << std::endl;\n\n\t\t\tstd::cout << \"start solving AtPA=AtPB\" << std::endl;\n\t\t\tEigen::SimplicialCholesky<Eigen::SparseMatrix<double>> solver(AtPA);\n\n\t\t\tstd::cout << \"x = solver.solve(AtPB)\" << std::endl;\n\t\t\tEigen::SparseMatrix<double> x = solver.solve(AtPB);\n\n\t\t\tstd::vector<double> h_x;\n\n\t\t\tfor (int k=0; k<x.outerSize(); ++k){\n\t\t\t\tfor (Eigen::SparseMatrix<double>::InnerIterator it(x,k); it; ++it){\n\t\t\t\t\th_x.push_back(it.value());\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif(h_x.size() == scan_poses.size() * 6){\n\t\t\t\tfor(size_t i = 0 ; i < h_x.size(); i++){\n\t\t\t\t\tstd::cout << h_x[i] << std::endl;\n\t\t\t\t}\n\t\t\t\tstd::cout << \"AtPA=AtPB SOLVED\" << std::endl;\n\t\t\t\tstd::cout << \"update\" << std::endl;\n\n\t\t\t\tint counter = 0;\n\n\t\t\t\tfor(size_t i = 0; i < scan_poses.size(); i++){\n\t\t\t\t\tTaitBryanPose pose = pose_tait_bryan_from_affine_matrix(scan_poses[i].m);\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\n\t\t\t\t\tscan_poses[i].m = affine_matrix_from_pose_tait_bryan(pose);\n\t\t\t\t}\n\t\t\t}else{\n\t\t\t\tstd::cout << \"AtPA=AtPB FAILED\" << std::endl;\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t\tcase 'l':{\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 < scan_poses.size() ; i++){\n\t\t\t\tEigen::Affine3d pose_source = scan_poses[i].m;\n\n\t\t\t\tfor(size_t j = 0 ; j < scan_poses.size() ; j++){\n\t\t\t\t\tif(i == j)continue;\n\t\t\t\t\tstd::vector<std::pair<int,int>> nn = nns(scan_poses[i], scan_poses[j], sradius);\n\t\t\t\t\tstd::cout << nn.size() << \",\" << scan_poses[i].pc.size() << \",\" << scan_poses[j].pc.size() << std::endl;\n\n\t\t\t\t\tfor(size_t k = 0 ; k < nn.size(); k+=1){\n\t\t\t\t\t\tpcl::PointXYZ &p_1 = scan_poses[i].pc[nn[k].first];\n\t\t\t\t\t\tpcl::PointXYZ &p_2 = scan_poses[j].pc[nn[k].second];\n\n\t\t\t\t\t\tEigen::Vector3d p_t(p_2.x, p_2.y, p_2.z);// = trajectory[j] * p_2;\n\t\t\t\t\t\tEigen::Vector3d p_s(p_1.x, p_1.y, p_1.z);// = p_1;\n\n\t\t\t\t\t\tint ir = tripletListB.size();\n\t\t\t\t\t\tint ic_1 = i * 6;\n\t\t\t\t\t\tEigen::Matrix3d px;\n\t\t\t\t\t\tpx(0,0) = 0;\n\t\t\t\t\t\tpx(0,1) = -p_s.z();\n\t\t\t\t\t\tpx(0,2) =  p_s.y();\n\t\t\t\t\t\tpx(1,0) = p_s.z();\n\t\t\t\t\t\tpx(1,1) = 0;\n\t\t\t\t\t\tpx(1,2) = -p_s.x();\n\t\t\t\t\t\tpx(2,0) = -p_s.y();\n\t\t\t\t\t\tpx(2,1) = p_s.x();\n\t\t\t\t\t\tpx(2,2) = 0;\n\n\t\t\t\t\t\tEigen::Matrix3d R = pose_source.inverse().rotation();\n\t\t\t\t\t\tEigen::Matrix3d Rpx = R*px;\n\n\t\t\t\t\t\ttripletListA.emplace_back(ir     ,ic_1 + 0, R(0,0));\n\t\t\t\t\t\ttripletListA.emplace_back(ir     ,ic_1 + 1, R(0,1));\n\t\t\t\t\t\ttripletListA.emplace_back(ir     ,ic_1 + 2, R(0,2));\n\t\t\t\t\t\ttripletListA.emplace_back(ir     ,ic_1 + 3, -Rpx(0,0));\n\t\t\t\t\t\ttripletListA.emplace_back(ir     ,ic_1 + 4, -Rpx(0,1));\n\t\t\t\t\t\ttripletListA.emplace_back(ir     ,ic_1 + 5, -Rpx(0,2));\n\n\t\t\t\t\t\ttripletListA.emplace_back(ir + 1 ,ic_1 + 0, R(1,0));\n\t\t\t\t\t\ttripletListA.emplace_back(ir + 1 ,ic_1 + 1, R(1,1));\n\t\t\t\t\t\ttripletListA.emplace_back(ir + 1 ,ic_1 + 2, R(1,2));\n\t\t\t\t\t\ttripletListA.emplace_back(ir + 1 ,ic_1 + 3, -Rpx(1,0));\n\t\t\t\t\t\ttripletListA.emplace_back(ir + 1 ,ic_1 + 4, -Rpx(1,1));\n\t\t\t\t\t\ttripletListA.emplace_back(ir + 1 ,ic_1 + 5, -Rpx(1,2));\n\n\t\t\t\t\t\ttripletListA.emplace_back(ir + 2 ,ic_1 + 0, R(2,0));\n\t\t\t\t\t\ttripletListA.emplace_back(ir + 2 ,ic_1 + 1, R(2,1));\n\t\t\t\t\t\ttripletListA.emplace_back(ir + 2 ,ic_1 + 2, R(2,2));\n\t\t\t\t\t\ttripletListA.emplace_back(ir + 2 ,ic_1 + 3, -Rpx(2,0));\n\t\t\t\t\t\ttripletListA.emplace_back(ir + 2 ,ic_1 + 4, -Rpx(2,1));\n\t\t\t\t\t\ttripletListA.emplace_back(ir + 2 ,ic_1 + 5, -Rpx(2,2));\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\tEigen::Vector3d target = scan_poses[i].m.inverse() * (scan_poses[j].m * p_t);\n\n\n\t\t\t\t\t\ttripletListB.emplace_back(ir    , 0,  -(target.x() - p_s.x()));\n\t\t\t\t\t\ttripletListB.emplace_back(ir + 1, 0,  -(target.y() - p_s.y()));\n\t\t\t\t\t\ttripletListB.emplace_back(ir + 2, 0,  -(target.z() - p_s.z()));\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tint ir = tripletListB.size();\n\t\t\ttripletListA.emplace_back(ir     , 0, 1);\n\t\t\ttripletListA.emplace_back(ir + 1 , 1, 1);\n\t\t\ttripletListA.emplace_back(ir + 2 , 2, 1);\n\t\t\ttripletListA.emplace_back(ir + 3 , 3, 1);\n\t\t\ttripletListA.emplace_back(ir + 4 , 4, 1);\n\t\t\ttripletListA.emplace_back(ir + 5 , 5, 1);\n\n\t\t\ttripletListP.emplace_back(ir     , ir,     1000000);\n\t\t\ttripletListP.emplace_back(ir + 1 , ir + 1, 1000000);\n\t\t\ttripletListP.emplace_back(ir + 2 , ir + 2, 1000000);\n\t\t\ttripletListP.emplace_back(ir + 3 , ir + 3, 1000000);\n\t\t\ttripletListP.emplace_back(ir + 4 , ir + 4, 1000000);\n\t\t\ttripletListP.emplace_back(ir + 5 , ir + 5, 1000000);\n\n\t\t\ttripletListB.emplace_back(ir     , 0, 0);\n\t\t\ttripletListB.emplace_back(ir + 1 , 0, 0);\n\t\t\ttripletListB.emplace_back(ir + 2 , 0, 0);\n\t\t\ttripletListB.emplace_back(ir + 3 , 0, 0);\n\t\t\ttripletListB.emplace_back(ir + 4 , 0, 0);\n\t\t\ttripletListB.emplace_back(ir + 5 , 0, 0);\n\n\t\t\tEigen::SparseMatrix<double> matA(tripletListB.size(), scan_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\t\t\tEigen::SparseMatrix<double> AtPA(scan_poses.size() * 6, scan_poses.size() * 6);\n\t\t\tEigen::SparseMatrix<double> AtPB(scan_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\n\t\t\tstd::cout << \"AtPA.size: \" << AtPA.size() << std::endl;\n\t\t\tstd::cout << \"AtPB.size: \" << AtPB.size() << std::endl;\n\n\t\t\tstd::cout << \"start solving AtPA=AtPB\" << std::endl;\n\t\t\tEigen::SimplicialCholesky<Eigen::SparseMatrix<double>> solver(AtPA);\n\n\t\t\tstd::cout << \"x = solver.solve(AtPB)\" << std::endl;\n\t\t\tEigen::SparseMatrix<double> x = solver.solve(AtPB);\n\n\t\t\tstd::vector<double> h_x;\n\n\t\t\tfor (int k=0; k<x.outerSize(); ++k){\n\t\t\t\tfor (Eigen::SparseMatrix<double>::InnerIterator it(x,k); it; ++it){\n\t\t\t\t\th_x.push_back(it.value());\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif(h_x.size() == scan_poses.size() * 6){\n\t\t\t\tfor(size_t i = 0 ; i < h_x.size(); i++){\n\t\t\t\t\tstd::cout << h_x[i] << std::endl;\n\t\t\t\t}\n\t\t\t\tstd::cout << \"AtPA=AtPB SOLVED\" << std::endl;\n\t\t\t\tstd::cout << \"update\" << std::endl;\n\n\t\t\t\tint counter = 0;\n\n\t\t\t\tfor(size_t i = 0; i < scan_poses.size(); i++){\n\t\t\t\t\tRodriguesPose pose_update;\n\t\t\t\t\tpose_update.px = h_x[counter++];\n\t\t\t\t\tpose_update.py = h_x[counter++];\n\t\t\t\t\tpose_update.pz = h_x[counter++];\n\t\t\t\t\tpose_update.sx = h_x[counter++];\n\t\t\t\t\tpose_update.sy = h_x[counter++];\n\t\t\t\t\tpose_update.sz = h_x[counter++];\n\n\t\t\t\t\tscan_poses[i].m = (scan_poses[i].m.inverse() * affine_matrix_from_pose_rodrigues(pose_update)).inverse();\n\t\t\t\t}\n\t\t\t}else{\n\t\t\t\tstd::cout << \"AtPA=AtPB FAILED\" << std::endl;\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t\tcase '1':{\n\t\t\tsradius -= 0.01;\n\t\t\tstd::cout << \"sradius: \" << sradius << std::endl;\n\t\t\tif(sradius < 0)sradius = 0.01;\n\t\t\tbreak;\t\t\n\t\t} \n\t\tcase '2':{\n\t\t\tsradius += 0.01;\n\t\t\tstd::cout << \"sradius: \" << sradius << std::endl;\n\t\t\tbreak;\t\t\n\t\t} \n\t\tcase '3':{\n\t\t\tfor(size_t i = 0; i < scan_poses.size(); i++){\n\t\t\t\tpcl::PointCloud<pcl::PointXYZ> pc;\n\t\t\t\tfor(size_t j = 0; j < scan_poses[i].pc.size(); j++){\n\t\t\t\t\tEigen::Vector3d v(scan_poses[i].pc[j].x, scan_poses[i].pc[j].y, scan_poses[i].pc[j].z);\n\t\t\t\t\tEigen::Vector3d vt = scan_poses[i].m * v;\n\t\t\t\t\tpcl::PointXYZ p;\n\t\t\t\t\tp.x = vt.x();\n\t\t\t\t\tp.y = vt.y();\n\t\t\t\t\tp.z = vt.z();\n\t\t\t\t\tpc.push_back(p);\n\t\t\t\t}\n\t\t\t\tpcl::io::savePCDFileBinary(std::to_string(i) + \".pcd\", pc);\n\t\t\t\tstd::cout << \"file: \" << std::to_string(i) + \".pcd\" << std::endl;\n \t\t\t}\n\t\t\tbreak;\n\t\t}\n\t\tcase 'g':{\n\t\t\tshow_ground_truth =! show_ground_truth;\n\t\t\tbreak;\n\t\t}\n\t\tcase 'o':{\n\t\t\tGridParameters rgd_params;\n\t\t\trgd_params.resolution_X = sradius;\n\t\t\trgd_params.resolution_Y = sradius;\n\t\t\trgd_params.resolution_Z = sradius;\n\t\t\trgd_params.bounding_box_extension = sradius;\n\n\t\t\tstd::vector<Point3D> points_global;\n\t\t\tfor(size_t i = 0; i < scan_poses.size(); i++){\n\t\t\t\tfor(size_t j = 0; j < scan_poses[i].pc.size(); j++){\n\t\t\t\t\tEigen::Vector3d v(scan_poses[i].pc[j].x, scan_poses[i].pc[j].y, scan_poses[i].pc[j].z);\n\t\t\t\t\tEigen::Vector3d vt = scan_poses[i].m * v;\n\t\t\t\t\tPoint3D p;\n\t\t\t\t\tp.x = vt.x();\n\t\t\t\t\tp.y = vt.y();\n\t\t\t\t\tp.z = vt.z();\n\t\t\t\t\tp.index_pose = i;\n\t\t\t\t\tpoints_global.push_back(p);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tstd::vector<PointBucketIndexPair> index_pair;\n\t\t\tstd::vector<Bucket> buckets;\n\n\t\t\tgrid_calculate_params(points_global, rgd_params);\n\t\t\tbuild_rgd(points_global, index_pair, buckets, rgd_params, 8);\n\n\t\t\tstd::vector<Job> jobs = get_jobs(buckets.size(), 8);\n\n\t\t\tstd::vector<std::thread> threads;\n\n\t\t\tstd::vector<Eigen::SparseMatrix<double>> AtPAtmp(jobs.size());\n\t\t\tstd::vector<Eigen::SparseMatrix<double>> AtPBtmp(jobs.size());\n\n\t\t\tfor (size_t i = 0; i < jobs.size(); i++) {\n\t\t\t\tAtPAtmp[i] = Eigen::SparseMatrix<double>(scan_poses.size() * 6, scan_poses.size() * 6);\n\t\t\t\tAtPBtmp[i] = Eigen::SparseMatrix<double>(scan_poses.size() * 6, 1);\n\t\t\t}\n\n\t\t\tstd::vector<TaitBryanPose> poses;\n\t\t\tstd::vector<Eigen::Affine3d> mposes_inv;\n\t\t\tfor(size_t i = 0; i < scan_poses.size(); i++){\n\t\t\t\tposes.push_back(pose_tait_bryan_from_affine_matrix(scan_poses[i].m));\n\t\t\t\tmposes_inv.push_back(scan_poses[i].m.inverse());\n\t\t\t}\n\n\t\t\tfor (size_t k = 0; k < jobs.size(); k++) {\n\t\t\t\tthreads.push_back(std::thread(ndt_job, k, &jobs[k], &buckets, &(AtPAtmp[k]), &(AtPBtmp[k]), &index_pair, &points_global, &poses, &mposes_inv, scan_poses.size()));\n\t\t\t}\n\n\t\t\tfor (size_t j = 0; j < threads.size(); j++) {\n\t\t\t\tthreads[j].join();\n\t\t\t}\n\n\t\t\tbool init = false;\n\t\t\tEigen::SparseMatrix<double> AtPA_ndt(scan_poses.size() * 6, scan_poses.size() * 6);\n\t\t\tEigen::SparseMatrix<double> AtPB_ndt(scan_poses.size() * 6, 1);\n\n\t\t\tfor (size_t k = 0; k < jobs.size(); k++) {\n\t\t\t\tif (!init) {\n\t\t\t\t\tif (AtPBtmp[k].size() > 0) {\n\t\t\t\t\t\tAtPA_ndt = AtPAtmp[k];\n\t\t\t\t\t\tAtPB_ndt = AtPBtmp[k];\n\t\t\t\t\t\tinit = true;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tif (AtPBtmp[k].size() > 0) {\n\n\t\t\t\t\t\tAtPA_ndt += AtPAtmp[k];\n\t\t\t\t\t\tAtPB_ndt += AtPBtmp[k];\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tstd::cout << \"start solving AtPA=AtPB\" << std::endl;\n\t\t\tEigen::SimplicialCholesky<Eigen::SparseMatrix<double>> solver(AtPA_ndt);\n\n\t\t\tstd::cout << \"x = solver.solve(AtPB)\" << std::endl;\n\t\t\tEigen::SparseMatrix<double> x = solver.solve(AtPB_ndt);\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\tif (it.value() == it.value()) {\n\t\t\t\t\t\th_x.push_back(it.value());\n\t\t\t\t\t\tstd::cout << it.value() << std::endl;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif(h_x.size() == scan_poses.size() * 6){\n\t\t\t\tbuckets_render = buckets;\n\t\t\t\tstd::cout << \"AtPA=AtPB SOLVED\" << std::endl;\n\t\t\t\tint counter = 0;\n\t\t\t\tfor (size_t i = 0; i < scan_poses.size(); i++) {\n\n\t\t\t\t\tTaitBryanPose pose = pose_tait_bryan_from_affine_matrix(scan_poses[i].m);\n\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\n\t\t\t\t\tscan_poses[i].m = affine_matrix_from_pose_tait_bryan(pose);\n\t\t\t\t}\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 '4':{\n\t\t\tshow_ndt_covariances = !show_ndt_covariances;\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 << \"-: current_scan_index--\" << std::endl;\n\tstd::cout << \"=: current_scan_index++\" << std::endl;\n\tstd::cout << \"awsdzx: move current_scan (green)\" << std::endl;\n\tstd::cout << \"p: print poses\" << std::endl;\n\tstd::cout << \"t: optimize (Tait-Bryan)\" << std::endl;\n\tstd::cout << \"l: optimize (Lie algebra)\" << std::endl;\n\tstd::cout << \"1: sradius -= 0.01\" << std::endl;\n\tstd::cout << \"2: sradius += 0.01\" << std::endl;\n\tstd::cout << \"3: save current point clouds\" << std::endl;\n\tstd::cout << \"g: show_ground_truth =! show_ground_truth\" << std::endl;\n\tstd::cout << \"o: optimize (NDT)\" << std::endl;\n\tstd::cout << \"n: nns\" << std::endl;\n\tstd::cout << \"4: show ndt covariances on/off\" << std::endl;\n}\n\nvoid set_initial_guess(std::vector<ScanPose>& scan_poses){\n\tscan_poses[0].m(0,0) = 0.380925;\n\tscan_poses[0].m(0,1) = 0.924606;\n\tscan_poses[0].m(0,3) = -6.06303;\n\n\tscan_poses[0].m(1,0) = -0.924606;\n\tscan_poses[0].m(1,1) = 0.380925;\n\tscan_poses[0].m(1,3) = -8.2396;\n\n\tscan_poses[1].m(0,0) = 0.710913;\n\tscan_poses[1].m(0,1) = 0.70328;\n\tscan_poses[1].m(0,3) = -1.03452;\n\n\tscan_poses[1].m(1,0) = -0.70328;\n\tscan_poses[1].m(1,1) = 0.710913;\n\tscan_poses[1].m(1,3) = -7.77656;\n\n\tscan_poses[2].m(0,0) = 0.613745;\n\tscan_poses[2].m(0,1) = 0.789504;\n\tscan_poses[2].m(0,3) = 3.99851;\n\n\tscan_poses[2].m(1,0) = -0.789504;\n\tscan_poses[2].m(1,1) = 0.613745;\n\tscan_poses[2].m(1,3) = -8.18709;\n\n\tscan_poses[3].m(0,0) = 0.751805;\n\tscan_poses[3].m(0,1) = 0.659385;\n\tscan_poses[3].m(0,3) = 9.99224;\n\n\tscan_poses[3].m(1,0) = -0.659385;\n\tscan_poses[3].m(1,1) = 0.751805;\n\tscan_poses[3].m(1,3) = -8.54882;\n\n\tscan_poses[4].m(0,0) = -0.996673;\n\tscan_poses[4].m(0,1) = 0.0815022;\n\tscan_poses[4].m(0,3) = 12.6963;\n\n\tscan_poses[4].m(1,0) = -0.0815022;\n\tscan_poses[4].m(1,1) = -0.996673;\n\tscan_poses[4].m(1,3) = -8.73861;\n\n\tscan_poses[5].m(0,0) = 0.639602;\n\tscan_poses[5].m(0,1) = 0.768705;\n\tscan_poses[5].m(0,3) = 17.8592;\n\n\tscan_poses[5].m(1,0) = -0.768705;\n\tscan_poses[5].m(1,1) = 0.639602;\n\tscan_poses[5].m(1,3) = -2.78423;\n\n\tscan_poses[6].m(0,0) = 0.745174;\n\tscan_poses[6].m(0,1) = 0.66687;\n\tscan_poses[6].m(0,3) = 22.9195;\n\n\tscan_poses[6].m(1,0) = -0.66687;\n\tscan_poses[6].m(1,1) = 0.745174;\n\tscan_poses[6].m(1,3) = -1.98392;\n\n\tscan_poses[7].m(0,0) = -0.0491839;\n\tscan_poses[7].m(0,1) = 0.998789;\n\tscan_poses[7].m(0,3) = 31.7827;\n\n\tscan_poses[7].m(1,0) = -0.998789;\n\tscan_poses[7].m(1,1) = -0.0491839;\n\tscan_poses[7].m(1,3) = -2.2143;\n\n\tscan_poses[8].m(0,0) = -0.128844;\n\tscan_poses[8].m(0,1) = 0.991665;\n\tscan_poses[8].m(0,3) = 39.0272;\n\n\tscan_poses[8].m(1,0) = -0.991665;\n\tscan_poses[8].m(1,1) = -0.128844;\n\tscan_poses[8].m(1,3) = -2.29705;\n\n\tscan_poses[9].m(0,0) = -0.34215;\n\tscan_poses[9].m(0,1) = 0.939646;\n\tscan_poses[9].m(0,3) = 48.1018;\n\n\tscan_poses[9].m(1,0) = -0.939646;\n\tscan_poses[9].m(1,1) = -0.34215;\n\tscan_poses[9].m(1,3) = -1.94245;\n\n\tscan_poses[10].m(0,0) = -0.158532;\n\tscan_poses[10].m(0,1) = 0.987354;\n\tscan_poses[10].m(0,3) = 54.2044;\n\n\tscan_poses[10].m(1,0) = -0.987354;\n\tscan_poses[10].m(1,1) = -0.158532;\n\tscan_poses[10].m(1,3) = -7.96743;\n\n\tscan_poses[11].m(0,0) = -0.197888;\n\tscan_poses[11].m(0,1) = 0.980225;\n\tscan_poses[11].m(0,3) = 65.5777;\n\n\tscan_poses[11].m(1,0) = -0.980225;\n\tscan_poses[11].m(1,1) = -0.197888;\n\tscan_poses[11].m(1,3) = -8.39231;\n\n\tscan_poses[12].m(0,0) = -0.360872;\n\tscan_poses[12].m(0,1) = 0.932615;\n\tscan_poses[12].m(0,3) = 78.1712;\n\n\tscan_poses[12].m(1,0) = -0.932615;\n\tscan_poses[12].m(1,1) = -0.360872;\n\tscan_poses[12].m(1,3) = -7.76261;\n}\n\nstd::vector<std::pair<int,int>> nns(ScanPose &sp1, ScanPose &sp2, float radius)\n{\n\tpcl::PointCloud<pcl::PointXYZ> pc1;\n\tpcl::PointCloud<pcl::PointXYZ> pc2;\n\n\tfor(size_t i = 0; i < sp1.pc.size(); i++){\n\t\tEigen::Vector3d v(sp1.pc[i].x, sp1.pc[i].y, sp1.pc[i].z);\n\t\tEigen::Vector3d vt = sp1.m * v;\n\t\tpc1.push_back(pcl::PointXYZ(vt.x(), vt.y(), vt.z()));\n\t}\n\n\tfor(size_t i = 0 ; i < sp2.pc.size(); i++){\n\t\tEigen::Vector3d v(sp2.pc[i].x, sp2.pc[i].y, sp2.pc[i].z);\n\t\tEigen::Vector3d vt = sp2.m * v;\n\t\tpc2.push_back(pcl::PointXYZ(vt.x(), vt.y(), vt.z()));\n\t}\n\n\n\tstd::vector<std::pair<int,int>> result;\n\n\tpcl::KdTreeFLANN<pcl::PointXYZ> kdtree;\n\tpcl::PointCloud<pcl::PointXYZ>::Ptr cloud(new pcl::PointCloud<pcl::PointXYZ>);\n\tfor(size_t i = 0; i < pc1.size(); i++){\n\t\tcloud->push_back(pc1[i]);\n\t}\n\tint K = 1;\n\t\n\tstd::vector<int> pointIdxRadiusSearch;\n\tstd::vector<float> pointRadiusSquaredDistance;\n\n\tkdtree.setInputCloud (cloud);\n\tfor(size_t k = 0; k < pc2.size(); k++){\n\t\tif ( kdtree.radiusSearch (pc2[k], radius, pointIdxRadiusSearch, pointRadiusSquaredDistance) > 0 ){\n\t\t\tfor (std::size_t i = 0; i < pointIdxRadiusSearch.size (); ++i){\n\t\t\t\tresult.emplace_back(pointIdxRadiusSearch[i], k);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\n\treturn result;\n}\n\n", "meta": {"hexsha": "06cddd3806c431efbe4e88b6cc876d2a159697fa", "size": 37534, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "codes/c++ExamplesRealData/src/point_cloud_registration.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++ExamplesRealData/src/point_cloud_registration.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++ExamplesRealData/src/point_cloud_registration.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": 31.8084745763, "max_line_length": 236, "alphanum_fraction": 0.6182661054, "num_tokens": 14041, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6477982179521103, "lm_q2_score": 0.523420348936324, "lm_q1q2_score": 0.33907076928082247}}
{"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 \"A_ol I_ol\" BA_olI_ol,\n * WITHOUT WARRANTIE_ol OR CONDITION_ol OF ANY KIND, either express or implied.\n * _olee the License for the specific language governing permissions and\n * limitations under the License.\n *\n */\n\n// Third party includes\n#include <boost/math/constants/constants.hpp>\n\n// Local VOTCA includes\n#include \"votca/xtp/aobasis.h\"\n#include \"votca/xtp/aomatrix.h\"\n#include \"votca/xtp/qmmolecule.h\"\n#include \"votca/xtp/radial_euler_maclaurin_rule.h\"\n\nnamespace votca {\nnamespace xtp {\n\nstd::vector<double> EulerMaclaurinGrid::CalculatePruningIntervals(\n    const std::string& element) {\n  std::vector<double> r;\n  // get Bragg-Slater Radius for this element\n  double BSradius = _BraggSlaterRadii.at(element);\n  // row type of element\n  Index RowType = _pruning_set.at(element);\n\n  if (RowType == 1) {\n    r.push_back(0.25 * BSradius);\n    r.push_back(0.5 * BSradius);\n    r.push_back(1.0 * BSradius);\n    r.push_back(4.5 * BSradius);\n  } else if (RowType == 2) {\n    r.push_back(0.1667 * BSradius);\n    r.push_back(0.5 * BSradius);\n    r.push_back(0.9 * BSradius);\n    r.push_back(3.5 * BSradius);\n  } else if (RowType == 3) {\n    r.push_back(0.1 * BSradius);\n    r.push_back(0.4 * BSradius);\n    r.push_back(0.8 * BSradius);\n    r.push_back(2.5 * BSradius);\n  } else {\n    throw std::runtime_error(\n        \"EulerMaclaurinGrid::CalculatePruningIntervals:Pruning unsupported for \"\n        \"RowType\");\n  }\n  return r;\n}\n\nvoid EulerMaclaurinGrid::FillElementRangeMap(const AOBasis& aobasis,\n                                             const QMMolecule& atoms,\n                                             double eps) {\n  std::map<std::string, min_exp>::iterator it;\n  for (const QMAtom& atom : atoms) {\n    std::string name = atom.getElement();\n    // is this element already in map?\n    it = _element_ranges.find(name);\n    // only proceed, if element data does not exist yet\n    if (it == _element_ranges.end()) {\n      min_exp this_atom;\n      double range_max = std::numeric_limits<double>::min();\n      double decaymin = std::numeric_limits<double>::max();\n      Index lvalue = std::numeric_limits<Index>::min();\n      const std::vector<const AOShell*> shells =\n          aobasis.getShellsofAtom(atom.getId());\n      // and loop over all shells to figure out minimum decay constant and\n      // angular momentum of this function\n      for (const AOShell* shell : shells) {\n        Index lmax = Index(shell->getL());\n        if (shell->getMinDecay() < decaymin) {\n          decaymin = shell->getMinDecay();\n          lvalue = lmax;\n        }\n        double range = DetermineCutoff(2 * decaymin, 2 * lvalue + 2, eps);\n        if (range > range_max) {\n          this_atom.alpha = decaymin;\n          this_atom.l = lvalue;\n          this_atom.range = range;\n          range_max = range;\n        }\n      }  // shells\n      _element_ranges[name] = this_atom;\n    }  // new element\n  }    // atoms\n}\n\nvoid EulerMaclaurinGrid::RefineElementRangeMap(const AOBasis& aobasis,\n                                               const QMMolecule& atoms,\n                                               double eps) {\n  AOOverlap overlap;\n  overlap.Fill(aobasis);\n\n  // get collapsed index list\n  std::vector<Index> idxstart;\n  const std::vector<Index>& idxsize = aobasis.getFuncPerAtom();\n  Index start = 0;\n  for (Index size : idxsize) {\n    idxstart.push_back(start);\n    start += size;\n  }\n  // refining by going through all atom combinations\n  for (Index i = 0; i < atoms.size(); ++i) {\n    const QMAtom& atom_a = atoms[i];\n    Index a_start = idxstart[i];\n    Index a_size = idxsize[i];\n    double range_max = std::numeric_limits<double>::min();\n    // get preset values for this atom type\n    double alpha_a = _element_ranges.at(atom_a.getElement()).alpha;\n    Index l_a = _element_ranges.at(atom_a.getElement()).l;\n    const Eigen::Vector3d& pos_a = atom_a.getPos();\n    // Cannot iterate only over j<i because it is not symmetric due to shift_2g\n    for (Index j = 0; j < atoms.size(); ++j) {\n      if (i == j) {\n        continue;\n      }\n      const QMAtom& atom_b = atoms[j];\n      Index b_start = idxstart[j];\n      Index b_size = idxsize[j];\n      const Eigen::Vector3d& pos_b = atom_b.getPos();\n      // find overlap block of these two atoms\n      Eigen::MatrixXd overlapblock =\n          overlap.Matrix().block(a_start, b_start, a_size, b_size);\n      // determine abs max of this block\n      double s_max = overlapblock.cwiseAbs().maxCoeff();\n\n      if (s_max > 1e-5) {\n        double range = DetermineCutoff(\n            alpha_a + _element_ranges.at(atom_b.getElement()).alpha,\n            l_a + _element_ranges.at(atom_b.getElement()).l + 2, eps);\n        // now do some update trickery from Gaussian product formula\n        double dist = (pos_b - pos_a).norm();\n        double shift_2g =\n            dist * alpha_a /\n            (alpha_a + _element_ranges.at(atom_b.getElement()).alpha);\n        range += (shift_2g + dist);\n        if (range > range_max) {\n          range_max = range;\n        }\n      }\n    }\n    if (std::round(range_max) > _element_ranges.at(atom_a.getElement()).range) {\n      _element_ranges.at(atom_a.getElement()).range = std::round(range_max);\n    }\n  }\n}\n\nvoid EulerMaclaurinGrid::CalculateRadialCutoffs(const AOBasis& aobasis,\n                                                const QMMolecule& atoms,\n                                                const std::string& gridtype) {\n\n  double eps = Accuracy[gridtype];\n  FillElementRangeMap(aobasis, atoms, eps);\n  RefineElementRangeMap(aobasis, atoms, eps);\n  return;\n}\n\nstd::map<std::string, GridContainers::radial_grid>\n    EulerMaclaurinGrid::CalculateAtomicRadialGrids(const AOBasis& aobasis,\n                                                   const QMMolecule& atoms,\n                                                   const std::string& type) {\n\n  CalculateRadialCutoffs(aobasis, atoms, type);\n  std::map<std::string, GridContainers::radial_grid> result;\n  for (const auto& element : _element_ranges) {\n    result[element.first] = CalculateRadialGridforAtom(type, element);\n  }\n  return result;\n}\n\nGridContainers::radial_grid EulerMaclaurinGrid::CalculateRadialGridforAtom(\n    const std::string& type, const std::pair<std::string, min_exp>& element) {\n  GridContainers::radial_grid result;\n  Index np = getGridParameters(element.first, type);\n  double cutoff = element.second.range;\n  result.radius = Eigen::VectorXd::Zero(np);\n  result.weight = Eigen::VectorXd::Zero(np);\n  double alpha =\n      -cutoff /\n      (log(1.0 - std::pow((1.0 + double(np)) / (2.0 + double(np)), 3)));\n  double factor = 3.0 / (1.0 + double(np));\n\n  for (Index i = 0; i < np; i++) {\n    double q = double(i + 1) / (double(np) + 1.0);\n    double r = -alpha * std::log(1.0 - std::pow(q, 3));\n    double w = factor * alpha * r * r / (1.0 - std::pow(q, 3)) * std::pow(q, 2);\n    result.radius[i] = r;\n    result.weight[i] = w;\n  }\n  return result;\n}\n\ndouble EulerMaclaurinGrid::DetermineCutoff(double alpha, Index l, double eps) {\n  // determine norm of function\n  /* For a function f(r) = r^k*exp(-alpha*r^2) determine\n     the radial distance r such that the fraction of the\n     function norm that is neglected if the 3D volume\n     integration is terminated at a distance r is less\n     than or equal to eps. */\n\n  double cutoff = 1.0;     // initial value\n  double increment = 0.5;  // increment\n\n  while (increment > 0.01) {\n    double residual = CalcResidual(alpha, l, cutoff);\n    if (residual > eps) {\n      cutoff += increment;\n    } else {\n      cutoff -= increment;\n      if (cutoff < 0.0) {\n        cutoff = 0.0;\n      }\n      increment = 0.5 * increment;\n      cutoff += increment;\n    }\n  }\n  return cutoff;\n}\n\ndouble EulerMaclaurinGrid::CalcResidual(double alpha, Index l, double cutoff) {\n  return RadialIntegral(alpha, l + 2, cutoff) /\n         RadialIntegral(alpha, l + 2, 0.0);\n}\n\ndouble EulerMaclaurinGrid::RadialIntegral(double alpha, Index l,\n                                          double cutoff) {\n  const double pi = boost::math::constants::pi<double>();\n  Index ilo = l % 2;\n  double value = 0.0;\n  double valexp;\n  if (ilo == 0) {\n    double expo = std::sqrt(alpha) * cutoff;\n    if (expo <= 40.0) {\n      value = 0.5 * std::sqrt(pi / alpha) * std::erfc(expo);\n    }\n  }\n  double exponent = alpha * cutoff * cutoff;\n  if (exponent > 500.0) {\n    valexp = 0.0;\n    value = 0.0;\n  } else {\n    valexp = std::exp(-exponent);\n    value = valexp / 2.0 / alpha;\n  }\n  for (Index i = ilo + 2; i <= l; i += 2) {\n    value = (double(i - 1) * value + std::pow(cutoff, i - 1) * valexp) / 2.0 /\n            alpha;\n  }\n  return value;\n}\n\nIndex EulerMaclaurinGrid::getGridParameters(const std::string& element,\n                                            const std::string& type) {\n  if (type == \"medium\") {\n    return MediumGrid.at(element);\n  } else if (type == \"coarse\") {\n    return CoarseGrid.at(element);\n  } else if (type == \"xcoarse\") {\n    return XcoarseGrid.at(element);\n  } else if (type == \"fine\") {\n    return FineGrid.at(element);\n  } else if (type == \"xfine\") {\n    return XfineGrid.at(element);\n  }\n  throw std::runtime_error(\"Grid type \" + type + \" is not implemented\");\n  return -1;\n}\n}  // namespace xtp\n}  // namespace votca\n", "meta": {"hexsha": "d5016c5bcae20fcc2f710f68913007b6ee2473c1", "size": 9717, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/libxtp/grids/radial_euler_maclaurin_rule.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/grids/radial_euler_maclaurin_rule.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/grids/radial_euler_maclaurin_rule.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": 34.4574468085, "max_line_length": 80, "alphanum_fraction": 0.6092415355, "num_tokens": 2645, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6477982179521103, "lm_q2_score": 0.5234203489363239, "lm_q1q2_score": 0.3390707692808224}}
{"text": "//  Copyright John Maddock 2007.\r\n//  Use, modification and distribution are subject to the\r\n//  Boost Software License, Version 1.0. (See accompanying file\r\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\r\n\r\n#ifndef BOOST_MATH_ROUND_HPP\r\n#define BOOST_MATH_ROUND_HPP\r\n\r\n#ifdef _MSC_VER\r\n#pragma once\r\n#endif\r\n\r\n#include <boost/math/tools/config.hpp>\r\n#include <boost/math/policies/error_handling.hpp>\r\n#include <boost/math/special_functions/fpclassify.hpp>\r\n\r\nnamespace boost{ namespace math{\r\n\r\ntemplate <class T, class Policy>\r\ninline T round(const T& v, const Policy& pol)\r\n{\r\n   BOOST_MATH_STD_USING\r\n   if(!(boost::math::isfinite)(v))\r\n      return policies::raise_rounding_error(\"boost::math::round<%1%>(%1%)\", 0, v, v, pol);\r\n   return v < 0 ? static_cast<T>(ceil(v - 0.5f)) : static_cast<T>(floor(v + 0.5f));\r\n}\r\ntemplate <class T>\r\ninline T round(const T& v)\r\n{\r\n   return round(v, policies::policy<>());\r\n}\r\n//\r\n// The following functions will not compile unless T has an\r\n// implicit convertion to the integer types.  For user-defined\r\n// number types this will likely not be the case.  In that case\r\n// these functions should either be specialized for the UDT in\r\n// question, or else overloads should be placed in the same \r\n// namespace as the UDT: these will then be found via argument\r\n// dependent lookup.  See our concept archetypes for examples.\r\n//\r\ntemplate <class T, class Policy>\r\ninline int iround(const T& v, const Policy& pol)\r\n{\r\n   BOOST_MATH_STD_USING\r\n   T 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));\r\n   return static_cast<int>(r);\r\n}\r\ntemplate <class T>\r\ninline int iround(const T& v)\r\n{\r\n   return iround(v, policies::policy<>());\r\n}\r\n\r\ntemplate <class T, class Policy>\r\ninline long lround(const T& v, const Policy& pol)\r\n{\r\n   BOOST_MATH_STD_USING\r\n   T 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));\r\n   return static_cast<long int>(r);\r\n}\r\ntemplate <class T>\r\ninline long lround(const T& v)\r\n{\r\n   return lround(v, policies::policy<>());\r\n}\r\n\r\n#ifdef BOOST_HAS_LONG_LONG\r\n\r\ntemplate <class T, class Policy>\r\ninline boost::long_long_type llround(const T& v, const Policy& pol)\r\n{\r\n   BOOST_MATH_STD_USING\r\n   T 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));\r\n   return static_cast<boost::long_long_type>(r);\r\n}\r\ntemplate <class T>\r\ninline boost::long_long_type llround(const T& v)\r\n{\r\n   return llround(v, policies::policy<>());\r\n}\r\n\r\n#endif\r\n\r\n}} // namespaces\r\n\r\n#endif // BOOST_MATH_ROUND_HPP\r\n", "meta": {"hexsha": "44e0e17ff274cd471af05e4b99002647c6b30e29", "size": 2947, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "trunk/win/Source/Includes/Boost/math/special_functions/round.hpp", "max_stars_repo_name": "dyzmapl/BumpTop", "max_stars_repo_head_hexsha": "1329ea41411c7368516b942d19add694af3d602f", "max_stars_repo_licenses": ["Apache-2.0"], "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": "trunk/win/Source/Includes/Boost/math/special_functions/round.hpp", "max_issues_repo_name": "dyzmapl/BumpTop", "max_issues_repo_head_hexsha": "1329ea41411c7368516b942d19add694af3d602f", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 24.0, "max_issues_repo_issues_event_min_datetime": "2016-11-07T04:59:49.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-14T06:34:12.000Z", "max_forks_repo_path": "trunk/win/Source/Includes/Boost/math/special_functions/round.hpp", "max_forks_repo_name": "dyzmapl/BumpTop", "max_forks_repo_head_hexsha": "1329ea41411c7368516b942d19add694af3d602f", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 148.0, "max_forks_repo_forks_event_min_datetime": "2016-01-17T03:16:43.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-17T12:20:36.000Z", "avg_line_length": 31.688172043, "max_line_length": 131, "alphanum_fraction": 0.6820495419, "num_tokens": 797, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6334102636778401, "lm_q2_score": 0.5350984286266115, "lm_q1q2_score": 0.33893683676997993}}
{"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 \"NewtonEulerDS.hpp\"\n#include \"BlockVector.hpp\"\n#include \"BlockMatrix.hpp\"\n#include <boost/math/quaternion.hpp>\n\n#include <iostream>\n// #define DEBUG_NOCOLOR\n//#define DEBUG_BEGIN_END_ONLY\n// #define DEBUG_STDOUT\n// #define DEBUG_MESSAGES\n#include <debug.h>\n\n\nvoid computeMObjToAbs(SP::SiconosVector q, SP::SimpleMatrix mObjToAbs)\n{\n  DEBUG_BEGIN(\"computeMObjToAbs(SP::SiconosVector q, SP::SimpleMatrix mObjToAbs)\\n\");\n  double q0 = q->getValue(3);\n  double q1 = q->getValue(4);\n  double q2 = q->getValue(5);\n  double q3 = q->getValue(6);\n\n  ::boost::math::quaternion<double>    quatQ(q0, q1, q2, q3);\n  ::boost::math::quaternion<double>    quatcQ(q0, -q1, -q2, -q3);\n  ::boost::math::quaternion<double>    quatx(0, 1, 0, 0);\n  ::boost::math::quaternion<double>    quaty(0, 0, 1, 0);\n  ::boost::math::quaternion<double>    quatz(0, 0, 0, 1);\n  ::boost::math::quaternion<double>    quatBuff;\n  /*See equation with label eq:newton_Mobjtoabs from the DevNote.pdf\n   * Chapter gradient computation, case of NewtonEuler formulation\n   * with quaternion\n   */\n  quatBuff = quatcQ * quatx * quatQ;\n  mObjToAbs->setValue(0, 0, quatBuff.R_component_2());\n  mObjToAbs->setValue(0, 1, quatBuff.R_component_3());\n  mObjToAbs->setValue(0, 2, quatBuff.R_component_4());\n  quatBuff = quatcQ * quaty * quatQ;\n  mObjToAbs->setValue(1, 0, quatBuff.R_component_2());\n  mObjToAbs->setValue(1, 1, quatBuff.R_component_3());\n  mObjToAbs->setValue(1, 2, quatBuff.R_component_4());\n  quatBuff = quatcQ * quatz * quatQ;\n  mObjToAbs->setValue(2, 0, quatBuff.R_component_2());\n  mObjToAbs->setValue(2, 1, quatBuff.R_component_3());\n  mObjToAbs->setValue(2, 2, quatBuff.R_component_4());\n  DEBUG_END(\"computeMObjToAbs(SP::SiconosVector q, SP::SimpleMatrix mObjToAbs)\\n\");\n\n}\n\nvoid computeT(SP::SiconosVector q, SP::SimpleMatrix T)\n{\n  DEBUG_BEGIN(\"computeT(SP::SiconosVector q, SP::SimpleMatrix T)\\n\")\n  //  std::cout <<\"\\n NewtonEulerDS::computeT(SP::SiconosVector q)\\n  \" <<std::endl;\n  double q0 = q->getValue(3) / 2.0;\n  double q1 = q->getValue(4) / 2.0;\n  double q2 = q->getValue(5) / 2.0;\n  double q3 = q->getValue(6) / 2.0;\n  T->setValue(3, 3, -q1);\n  T->setValue(3, 4, -q2);\n  T->setValue(3, 5, -q3);\n  T->setValue(4, 3, q0);\n  T->setValue(4, 4, -q3);\n  T->setValue(4, 5, q2);\n  T->setValue(5, 3, q3);\n  T->setValue(5, 4, q0);\n  T->setValue(5, 5, -q1);\n  T->setValue(6, 3, -q2);\n  T->setValue(6, 4, q1);\n  T->setValue(6, 5, q0);\n  DEBUG_END(\"computeT(SP::SiconosVector q, SP::SimpleMatrix T)\\n\")\n\n}\n\n\n\n\n\n\n// Private function to set linked with members of Dynamical top class\nvoid NewtonEulerDS::connectToDS()\n{\n  // dim\n  _n = 2 * 3;\n\n}\n\n\n\n\n// From a set of data; Mass filled-in directly from a siconosMatrix -\n// This constructor leads to the minimum NewtonEuler System form: \\f$ M\\ddot q = p \\f$\n/*\nQ0 : contains the center of mass coordinate, and the quaternion initial. (dim(Q0)=7)\nVelocity0 : contains the initial velocity of center of mass and the omega initial. (dim(Velocity0)=6)\n*/\nNewtonEulerDS::NewtonEulerDS(): DynamicalSystem(6),\n                                _computeJacobianFIntqByFD(false),\n                                _computeJacobianFIntvByFD(false),\n                                _computeJacobianMIntqByFD(false),\n                                _computeJacobianMIntvByFD(false),\n                                _epsilonFD(sqrt(std::numeric_limits< double >::epsilon()))\n{\n  _p.resize(3);\n  _p[0].reset(new SiconosVector());\n  _p[1].reset(new SiconosVector(_n)); // Needed in NewtonEulerR\n  _p[2].reset(new SiconosVector());\n  zeroPlugin();\n  //assert(0);\n\n  // --- NEWTONEULER INHERITED CLASS MEMBERS ---\n  // -- Memory allocation for vector and matrix members --\n\n  _qDim = 7;\n  _n = 6;\n\n  // Current state\n  _q.reset(new SiconosVector(_qDim));\n  // _deltaq.reset(new SiconosVector(_qDim));\n  _v.reset(new SiconosVector(_n));\n\n  _dotq.reset(new SiconosVector(_qDim));\n  _workspace[freeresidu].reset(new SiconosVector(_n));\n  _workspace[free].reset(new SiconosVector(dimension()));\n  _massMatrix.reset(new SimpleMatrix(_n, _n));\n  _luW.reset(new SimpleMatrix(_n, _n));\n  _massMatrix->zero();\n  _T.reset(new SimpleMatrix(_qDim, _n));\n\n  _scalarMass = 0.;\n}\n\nvoid NewtonEulerDS::internalInit(SP::SiconosVector Q0, SP::SiconosVector Velocity0,\n                                 double mass , SP::SiconosMatrix inertialMatrix)\n{\n  DEBUG_BEGIN(\"NewtonEulerDS::internalInit(SP::SiconosVector Q0, SP::SiconosVector Velocity0, double mass , SP::SiconosMatrix inertialMatrix)\\n\");\n  _p.resize(3);\n  _p[0].reset(new SiconosVector());\n  _p[1].reset(new SiconosVector(_n)); // Needed in NewtonEulerR\n  _p[2].reset(new SiconosVector());\n  zeroPlugin();\n  // --- NEWTONEULER INHERITED CLASS MEMBERS ---\n  // -- Memory allocation for vector and matrix members --\n\n  _scalarMass = mass;\n  _qDim = 7;\n  _n = 6;\n\n  // Initial conditions\n  _q0 = Q0;\n  _v0 = Velocity0;\n\n  _MObjToAbs.reset(new SimpleMatrix(3, 3));\n\n  // Current state\n  _q.reset(new SiconosVector(_qDim));\n  // _deltaq.reset(new SiconosVector(_qDim));\n  _v.reset(new SiconosVector(_n));\n  (*_q) = (*_q0);\n  _dotq.reset(new SiconosVector(_qDim));\n  _massMatrix.reset(new SimpleMatrix(_n, _n));\n  _jacobianFGyrv.reset(new SimpleMatrix(_n, _n));\n  _luW.reset(new SimpleMatrix(_n, _n));\n  _massMatrix->zero();\n  _massMatrix->setValue(0, 0, _scalarMass);\n  _massMatrix->setValue(1, 1, _scalarMass);\n  _massMatrix->setValue(2, 2, _scalarMass);\n  _I = inertialMatrix;\n  Index dimIndex(2);\n  dimIndex[0] = 3;\n  dimIndex[1] = 3;\n  Index startIndex(4);\n  startIndex[0] = 0;\n  startIndex[1] = 0;\n  startIndex[2] = 3;\n  startIndex[3] = 3;\n  setBlock(_I, _massMatrix, dimIndex, startIndex);\n  _workspace[freeresidu].reset(new SiconosVector(_n));\n  _workspace[free].reset(new SiconosVector(dimension()));\n\n  _T.reset(new SimpleMatrix(_qDim, _n));\n  _T->zero();\n  _T->setValue(0, 0, 1.0);\n  _T->setValue(1, 1, 1.0);\n  _T->setValue(2, 2, 1.0);\n  computeT();\n  computeMObjToAbs();\n  initForces();\n  DEBUG_END(\"NewtonEulerDS::internalInit(SP::SiconosVector Q0, SP::SiconosVector Velocity0, double mass , SP::SiconosMatrix inertialMatrix)\\n\");\n}\nNewtonEulerDS::NewtonEulerDS(SP::SiconosVector Q0, SP::SiconosVector Velocity0,\n                             double  mass, SP::SiconosMatrix inertialMatrix):\n  DynamicalSystem(6),\n  _computeJacobianFIntqByFD(false),\n  _computeJacobianFIntvByFD(false),\n  _computeJacobianMIntqByFD(false),\n  _computeJacobianMIntvByFD(false),\n  _epsilonFD(sqrt(std::numeric_limits< double >::epsilon()))\n{\n  internalInit(Q0, Velocity0, mass, inertialMatrix);\n}\n\nvoid NewtonEulerDS::zeroPlugin()\n{\n  _pluginFExt.reset(new PluggedObject());\n  _pluginMExt.reset(new PluggedObject());\n  _pluginFInt.reset(new PluggedObject());\n  _pluginMInt.reset(new PluggedObject());\n  _pluginJacqFInt.reset(new PluggedObject());\n  _pluginJacvFInt.reset(new PluggedObject());\n  _pluginJacqMInt.reset(new PluggedObject());\n  _pluginJacvMInt.reset(new PluggedObject());\n}\n\n// Destructor\nNewtonEulerDS::~NewtonEulerDS()\n{\n}\n\nbool NewtonEulerDS::checkDynamicalSystem()\n{\n  bool output = true;\n  // ndof\n\n  // q0 and velocity0\n  if (! _q0 || ! _v0)\n  {\n    RuntimeException::selfThrow(\"NewtonEulerDS::checkDynamicalSystem - initial conditions are badly set.\");\n    output = false;\n  }\n\n\n  // fInt\n  //   if( ( _fInt && computeFIntPtr) && ( ! _jacobianFIntq || ! _jacobianFIntv ) )\n  //     // ie if fInt is defined and not constant => its Jacobian must be defined (but not necessarily plugged)\n  //     {\n  //       RuntimeException::selfThrow(\"NewtonEulerDS::checkDynamicalSystem - You defined fInt but not its Jacobian (according to q and velocity).\");\n  //       output = false;\n  //     }\n\n\n  if (!output) std::cout << \"NewtonEulerDS Warning: your dynamical system seems to be uncomplete (check = false)\" <<std::endl;\n  return output;\n}\n\nvoid NewtonEulerDS::initializeNonSmoothInput(unsigned int level)\n{\n  DEBUG_PRINTF(\"NewtonEulerDS::initializeNonSmoothInput(unsigned int level) for level = %i\\n\",level);\n\n  if (_p[level]->size() == 0)\n  {\n    if (level == 0)\n    {\n      _p[0]->resize(_qDim);\n    }\n    else\n    {\n      _p[level]->resize(_n);\n    }\n  }\n\n\n#ifdef DEBUG_MESSAGES\n  DEBUG_PRINT(\"display() after initialization\");\n  display();\n#endif\n}\n\nvoid NewtonEulerDS::initForces()\n{\n  DEBUG_BEGIN(\"NewtonEulerDS::initForces()\\n\")\n  _forces.reset(new SiconosVector(_n));\n  _fGyr.reset(new SiconosVector(3,0.0));\n  _jacobianFGyrv.reset(new SimpleMatrix(_n, _n));\n  _jacobianvForces.reset(new SimpleMatrix(_n, _n));\n  DEBUG_END(\"NewtonEulerDS::initForces()\\n\")\n}\n\nvoid NewtonEulerDS::initRhs(double time)\n{\n  //  _workMatrix.resize(sizeWorkMat);\n\n  // Solve Mq[2]=fL+p.\n  //*_q = *(_p[2]); // Warning: r/p update is done in Interactions/Relations\n\n  if (_forces)\n  {\n    computeForces(time);\n    //      *_q += *_forces;\n  }\n\n}\n\nvoid NewtonEulerDS::initialize(double time, unsigned int sizeOfMemory)\n{\n  // set q and q[1] to q0 and velocity0, initialize acceleration.\n  *_q = *_q0;\n  *_v = *_v0;\n\n  // If z has not been set, we initialize it with a null vector of size 1, since z is required in plug-in functions call.\n  if (! _z)\n    _z.reset(new SiconosVector(1));\n\n  if (_pluginFExt->fPtr && !_fExt)\n    _fExt.reset(new SiconosVector(3, 0));\n\n  if (_pluginMExt->fPtr && !_mExt)\n    _mExt.reset(new SiconosVector(3, 0));\n\n  if (_pluginFInt->fPtr && !_fInt)\n    _fInt.reset(new SiconosVector(3, 0));\n\n  if ((_pluginJacqFInt->fPtr  || _computeJacobianFIntqByFD) && !_jacobianFIntq)\n  {\n    _jacobianFIntq.reset(new SimpleMatrix(3, _qDim));\n    if (!_jacobianqForces)\n      _jacobianqForces.reset(new SimpleMatrix(_n, _qDim));\n  }\n\n  if ((_pluginJacvFInt->fPtr || _computeJacobianFIntvByFD) && !_jacobianFIntv)\n    _jacobianFIntv.reset(new SimpleMatrix(3, _n));\n\n  if (_pluginMInt->fPtr && !_mInt)\n    _mInt.reset(new SiconosVector(3, 0));\n\n  if ((_pluginJacqMInt->fPtr || _computeJacobianMIntqByFD) && !_jacobianMIntq)\n  {\n    if (!_jacobianqForces)\n      _jacobianqForces.reset(new SimpleMatrix(_n, _qDim));\n    _jacobianMIntq.reset(new SimpleMatrix(3, _qDim));\n  }\n  if ((_pluginJacvMInt->fPtr || _computeJacobianMIntvByFD) && !_jacobianMIntv)\n    _jacobianMIntv.reset(new SimpleMatrix(3, _n));\n\n\n  // Set links to variables of top-class DynamicalSystem.\n  // Warning: this results only in pointers links.\n  // No more memory allocation for vectors or matrices.\n  connectToDS(); // note that connection can not be done during constructor call, since user can complete the ds after (add plugin or anything else).\n  checkDynamicalSystem();\n\n  initRhs(time);\n\n\n  if (_boundaryConditions)\n  {\n    _reactionToBoundaryConditions.reset(new SiconosVector(_boundaryConditions->velocityIndices()->size()));\n  }\n\n  // Initialize memory vectors\n  initMemory(sizeOfMemory);\n\n}\n\nvoid NewtonEulerDS::computeFExt(double time)\n{\n  if (_pluginFExt->fPtr)\n    ((FExt_NE)_pluginFExt->fPtr)(time, &(*_fExt)(0), _qDim, &(*_q0)(0) ); // parameter z are assumed to be equal to q0\n}\n\nvoid NewtonEulerDS::computeMExt(double time)\n{\n  if (_pluginMExt->fPtr)\n    ((FExt_NE)_pluginFExt->fPtr)(time, &(*_mExt)(0), _qDim, &(*_q0)(0) ); // parameter z are assumed to be equal to q0\n}\n\n\nvoid NewtonEulerDS::computeFInt(double time)\n{\n  computeFInt(time, _q, _v);\n}\n\n\nvoid NewtonEulerDS::computeFInt(double time, SP::SiconosVector q, SP::SiconosVector v)\n{\n  computeFInt(time,  q,  v, _fInt);\n}\n\nvoid NewtonEulerDS::computeFInt(double time, SP::SiconosVector q, SP::SiconosVector v, SP::SiconosVector fInt)\n{\n  if (_pluginFInt->fPtr)\n    ((FInt_NE)_pluginFInt->fPtr)(time, &(*q)(0), &(*v)(0), &(*fInt)(0), _qDim,  &(*_q0)(0));// parameter z are assumed to be equal to q0\n}\n\n\nvoid NewtonEulerDS::computeMInt(double time)\n{\n  computeMInt(time, _q, _v);\n}\n\n\nvoid NewtonEulerDS::computeMInt(double time, SP::SiconosVector q, SP::SiconosVector v)\n{\n  computeMInt(time, q, v, _mInt);\n}\n\nvoid NewtonEulerDS::computeMInt(double time, SP::SiconosVector q, SP::SiconosVector v, SP::SiconosVector mInt)\n{\n  if (_pluginMInt->fPtr)\n    ((FInt_NE)_pluginMInt->fPtr)(time, &(*q)(0), &(*v)(0), &(*mInt)(0), _qDim,  &(*_q0)(0));// parameter z are assumed to be equal to q0\n}\n\nvoid NewtonEulerDS::computeJacobianFIntq(double time)\n{\n  computeJacobianFIntq(time, _q, _v);\n}\nvoid NewtonEulerDS::computeJacobianFIntv(double time)\n{\n  computeJacobianFIntv(time, _q, _v);\n}\n\nvoid NewtonEulerDS::computeJacobianFIntq(double time, SP::SiconosVector q, SP::SiconosVector velocity)\n{\n  DEBUG_PRINT(\"NewtonEulerDS::computeJacobianFIntq(...) starts\");\n  if (_pluginJacqFInt->fPtr)\n    ((FInt_NE)_pluginJacqFInt->fPtr)(time, &(*q)(0), &(*velocity)(0), &(*_jacobianFIntq)(0, 0), _qDim,  &(*_q0)(0));\n  else if (_computeJacobianFIntqByFD)\n    computeJacobianFIntqByFD(time, q, velocity);\n  DEBUG_EXPR(_jacobianFIntq->display(););\n  DEBUG_END(\"NewtonEulerDS::computeJacobianFIntq(...)\");\n}\n\nvoid NewtonEulerDS::computeJacobianFIntqByFD(double time, SP::SiconosVector q, SP::SiconosVector velocity)\n{\n  DEBUG_BEGIN(\"NewtonEulerDS::computeJacobianFIntqByFD(...)\\n\");\n  SP::SiconosVector fInt(new SiconosVector(3));\n  computeFInt(time, q, velocity, fInt);\n\n  double fInt0 = fInt->getValue(0);\n  double fInt1 = fInt->getValue(1);\n  double fInt2 = fInt->getValue(2);\n\n  SP::SiconosVector qeps(new SiconosVector(*q));\n  _jacobianFIntq->zero();\n  (*qeps)(0) += _epsilonFD;\n  for (int j =0; j < 7; j++)\n  {\n    computeFInt(time, qeps, velocity, fInt);\n    _jacobianFIntq->setValue(0,j,  (fInt->getValue(0) - fInt0)/_epsilonFD );\n    _jacobianFIntq->setValue(1,j,  (fInt->getValue(1) - fInt1)/_epsilonFD );\n    _jacobianFIntq->setValue(2,j,  (fInt->getValue(2) - fInt2)/_epsilonFD );\n    (*qeps)(j) -= _epsilonFD;\n    if (j<6) (*qeps)(j+1) += _epsilonFD;\n  }\n  DEBUG_END(\"NewtonEulerDS::computeJacobianFIntqByFD(...)\\n\");\n\n\n}\n\nvoid NewtonEulerDS::computeJacobianFIntv(double time, SP::SiconosVector q, SP::SiconosVector velocity)\n{\n  if (_pluginJacvFInt->fPtr)\n    ((FInt_NE)_pluginJacvFInt->fPtr)(time, &(*q)(0), &(*velocity)(0), &(*_jacobianFIntv)(0, 0), _qDim,  &(*_q0)(0));\n  else if (_computeJacobianFIntvByFD)\n    computeJacobianFIntvByFD(time, q, velocity);\n}\n\nvoid NewtonEulerDS::computeJacobianFIntvByFD(double time, SP::SiconosVector q, SP::SiconosVector velocity)\n{\n  DEBUG_BEGIN(\"NewtonEulerDS::computeJacobianFIntvByFD(...)\\n\");\n  SP::SiconosVector fInt(new SiconosVector(3));\n  computeFInt(time, q, velocity, fInt);\n\n  double fInt0 = fInt->getValue(0);\n  double fInt1 = fInt->getValue(1);\n  double fInt2 = fInt->getValue(2);\n\n  SP::SiconosVector veps(new SiconosVector(*velocity));\n  _jacobianFIntv->zero();\n  \n  (*veps)(0) += _epsilonFD;\n  for (int j =0; j < 6; j++)\n  {\n    computeFInt(time, q, veps, fInt);\n    _jacobianFIntv->setValue(0,j,  (fInt->getValue(0) - fInt0)/_epsilonFD );\n    _jacobianFIntv->setValue(1,j,  (fInt->getValue(1) - fInt1)/_epsilonFD );\n    _jacobianFIntv->setValue(2,j,  (fInt->getValue(2) - fInt2)/_epsilonFD );\n    (*veps)(j) -= _epsilonFD;\n    if (j<5) (*veps)(j+1) += _epsilonFD;\n  }\n  \n  DEBUG_END(\"NewtonEulerDS::computeJacobianFIntvByFD(...)\\n\");\n\n\n}\nvoid NewtonEulerDS::computeJacobianFGyrvByFD(double time, SP::SiconosVector q, SP::SiconosVector velocity)\n{\n  DEBUG_BEGIN(\"NewtonEulerDS::computeJacobianFGyrvByFD(...)\\n\");\n  SP::SiconosVector fGyr(new SiconosVector(3));\n  computeFGyr(velocity, fGyr);\n\n  double fGyr0 = fGyr->getValue(0);\n  double fGyr1 = fGyr->getValue(1);\n  double fGyr2 = fGyr->getValue(2);\n\n  SP::SiconosVector veps(new SiconosVector(*velocity));\n  _jacobianFGyrv->zero();\n\n  \n  (*veps)(0) += _epsilonFD;\n  for (int j =0; j < 6; j++)\n  {\n    computeFGyr(veps, fGyr);\n    _jacobianFGyrv->setValue(3,j,  (fGyr->getValue(0) - fGyr0)/_epsilonFD );\n    _jacobianFGyrv->setValue(4,j,  (fGyr->getValue(1) - fGyr1)/_epsilonFD );\n    _jacobianFGyrv->setValue(5,j,  (fGyr->getValue(2) - fGyr2)/_epsilonFD );\n    (*veps)(j) -= _epsilonFD;\n    if (j<5) (*veps)(j+1) += _epsilonFD;\n  }\n  DEBUG_EXPR(_jacobianFGyrv->display());\n  DEBUG_END(\"NewtonEulerDS::computeJacobianFGyrvByFD(...)\\n\");\n\n\n}\nvoid NewtonEulerDS::computeJacobianMIntq(double time)\n{\n  computeJacobianMIntq(time, _q, _v);\n}\nvoid NewtonEulerDS::computeJacobianMIntv(double time)\n{\n  computeJacobianMIntv(time, _q, _v);\n}\n\nvoid NewtonEulerDS::computeJacobianMIntq(double time, SP::SiconosVector q, SP::SiconosVector velocity)\n{\n  DEBUG_PRINT(\"NewtonEulerDS::computeJacobianMIntq(...) starts\");\n  if (_pluginJacqMInt->fPtr)\n    ((FInt_NE)_pluginJacqMInt->fPtr)(time, &(*q)(0), &(*velocity)(0), &(*_jacobianMIntq)(0, 0), _qDim,  &(*_q0)(0));\n  else if (_computeJacobianMIntqByFD)\n    computeJacobianMIntqByFD(time, q, velocity);\n  DEBUG_EXPR(_jacobianMIntq->display());\n  DEBUG_PRINT(\"NewtonEulerDS::computeJacobianMIntq(...) ends\");\n\n}\n\nvoid NewtonEulerDS::computeJacobianMIntqByFD(double time, SP::SiconosVector q, SP::SiconosVector velocity)\n{\n  DEBUG_PRINT(\"NewtonEulerDS::computeJacobianMIntqByFD(...) starts\\n\");\n\n  SP::SiconosVector mInt(new SiconosVector(3));\n  computeMInt(time, q, velocity, mInt);\n  double mInt0 = mInt->getValue(0);\n  double mInt1 = mInt->getValue(1);\n  double mInt2 = mInt->getValue(2);\n\n  SP::SiconosVector qeps(new SiconosVector(*q));\n\n  (*qeps)(0) += _epsilonFD;\n  for (int j =0; j < 7; j++)\n  {\n    computeMInt(time, qeps, velocity, mInt);\n    _jacobianMIntq->setValue(0,j,  (mInt->getValue(0) - mInt0)/_epsilonFD );\n    _jacobianMIntq->setValue(1,j,  (mInt->getValue(1) - mInt1)/_epsilonFD );\n    _jacobianMIntq->setValue(2,j,  (mInt->getValue(2) - mInt2)/_epsilonFD );\n    (*qeps)(j) -= _epsilonFD;\n    if (j<6) (*qeps)(j+1) += _epsilonFD;\n  }\n  DEBUG_PRINT(\"NewtonEulerDS::computeJacobianMIntqByFD(...) ends\\n\");\n}\n\nvoid NewtonEulerDS::computeJacobianMIntv(double time, SP::SiconosVector q, SP::SiconosVector velocity)\n{\n  if (_pluginJacvMInt->fPtr)\n    ((FInt_NE)_pluginJacvMInt->fPtr)(time, &(*q)(0), &(*velocity)(0), &(*_jacobianMIntv)(0, 0), _qDim,  &(*_q0)(0));\n  else if (_computeJacobianMIntvByFD)\n    computeJacobianMIntvByFD(time,  q, velocity);\n}\n\nvoid NewtonEulerDS::computeJacobianMIntvByFD(double time, SP::SiconosVector q, SP::SiconosVector velocity)\n{\n  DEBUG_PRINT(\"NewtonEulerDS::computeJacobianMIntvByFD(...) starts\\n\");\n\n  SP::SiconosVector mInt(new SiconosVector(3));\n  computeMInt(time, q, velocity, mInt);\n  double mInt0 = mInt->getValue(0);\n  double mInt1 = mInt->getValue(1);\n  double mInt2 = mInt->getValue(2);\n\n  SP::SiconosVector veps(new SiconosVector(*velocity));\n\n  (*veps)(0) += _epsilonFD;\n  for (int j =0; j < 6; j++)\n  {\n    computeMInt(time, q, veps, mInt);\n    _jacobianMIntv->setValue(0,j,  (mInt->getValue(0) - mInt0)/_epsilonFD );\n    _jacobianMIntv->setValue(1,j,  (mInt->getValue(1) - mInt1)/_epsilonFD );\n    _jacobianMIntv->setValue(2,j,  (mInt->getValue(2) - mInt2)/_epsilonFD );\n    (*veps)(j) -= _epsilonFD;\n    if (j<5) (*veps)(j+1) += _epsilonFD;\n  }\n  DEBUG_PRINT(\"NewtonEulerDS::computeJacobianMIntvByFD(...) ends\\n\");\n}\n\n\n\nvoid NewtonEulerDS::computeRhs(double time, bool isDSup)\n{\n  // if isDSup == true, this means that there is no need to re-compute mass ...\n  //  *_q = *(_p[2]); // Warning: r/p update is done in Interactions/Relations\n  if (_forces)\n  {\n    computeForces(time);\n    //*_q += *_forces;\n  }\n}\n\nvoid NewtonEulerDS::computeJacobianRhsx(double time, bool isDSup)\n{\n  RuntimeException::selfThrow(\"NewtonEulerDS::computeJacobianRhsx - not yet implemented.\");\n}\n\nvoid NewtonEulerDS::computeForces(double time)\n{\n  computeForces(time, _q, _v);\n}\n\nvoid NewtonEulerDS::computeFGyr(SP::SiconosVector v, SP::SiconosVector fGyr)\n{\n  /*computation of \\Omega times I \\Omega*/\n  DEBUG_BEGIN(\"NewtonEulerDS::computeFGyr(SP::SiconosVector v, SP::SiconosVector fGyr)\\n\");\n  if (_I)\n  {\n    DEBUG_EXPR( _I->display());\n    DEBUG_EXPR( v->display());\n    SiconosVector bufOmega(3);\n    SiconosVector bufIOmega(3);\n    bufOmega.setValue(0, v->getValue(3));\n    bufOmega.setValue(1, v->getValue(4));\n    bufOmega.setValue(2, v->getValue(5));\n    prod(*_I, bufOmega, bufIOmega, true);\n    cross_product(bufOmega, bufIOmega, *fGyr);\n  }\n  DEBUG_EXPR(fGyr->display());\n  DEBUG_END(\"NewtonEulerDS::computeFGyr(SP::SiconosVector v, SP::SiconosVector fGyr)\\n\");\n\n}\nvoid NewtonEulerDS::computeFGyr(SP::SiconosVector v)\n{\n  /*computation of \\Omega times I \\Omega*/\n  //DEBUG_BEGIN(\"NewtonEulerDS::computeFGyr(SP::SiconosVector v)\\n\");\n  computeFGyr( v, _fGyr);\n  //DEBUG_END(\"NewtonEulerDS::computeFGyr(SP::SiconosVector v)\\n\");\n\n}\n\n\n\n\nvoid NewtonEulerDS::computeForces(double time, SP::SiconosVector q, SP::SiconosVector v)\n{\n  // Warning: an operator (fInt ...) may be set (ie allocated and not NULL) but not plugged, that's why two steps are required here.\n  if (_forces)\n  {\n    _forces->zero();\n    // 1 - Computes the required functions\n    if (_fExt)\n    {\n      computeFExt(time);\n      _forces->setBlock(0, *_fExt);\n    }\n    if (_mExt)\n    {\n      computeMExt(time);\n      SiconosVector aux(3);\n      //computeMObjToAbs();\n      prod( *_mExt, *_MObjToAbs, aux); // aux =  transpose(_MObjToAbs) * _mext\n      *_mExt = aux;\n      _forces->setBlock(3, *_mExt);\n    }\n    if (_fInt)\n    {\n      computeFInt(time, q, v);\n      // std::cout << \"_fInt : \"<< std::endl;\n      // _fInt->display();\n      _forces->setValue(0, _forces->getValue(0) - _fInt->getValue(0));\n      _forces->setValue(1, _forces->getValue(1) - _fInt->getValue(1));\n      _forces->setValue(2, _forces->getValue(2) - _fInt->getValue(2));\n\n    }\n    if (_mInt)\n    {\n      computeMInt(time, q , v);\n      SiconosVector aux(3);\n      //computeMObjToAbs();\n      prod(*_mInt, *_MObjToAbs, aux);// aux =  transpose(_MObjToAbs) * _mInt\n      *_mInt = aux;\n      // std::cout << \"_MObjToAbs \" <<std::endl;\n      // _MObjToAbs->display();\n      //std::cout << \"NewtonEulerDS::computeForces: _mint: \" <<std::endl;\n      //_mInt->display();\n      _forces->setValue(3, _forces->getValue(3) - _mInt->getValue(0));\n      _forces->setValue(4, _forces->getValue(4) - _mInt->getValue(1));\n      _forces->setValue(5, _forces->getValue(5) - _mInt->getValue(2));\n    }\n\n    computeFGyr(v);\n    // std::cout << \"_fGyr \" <<std::endl;\n    // _fGyr->display();\n    _forces->setValue(3, _forces->getValue(3) - _fGyr->getValue(0));\n    _forces->setValue(4, _forces->getValue(4) - _fGyr->getValue(1));\n    _forces->setValue(5, _forces->getValue(5) - _fGyr->getValue(2));\n\n    // std::cout << \"_forces : \"<< std::endl;\n    // _forces->display();\n  }\n  // else nothing.\n}\n\nvoid NewtonEulerDS::computeJacobianqForces(double time)\n{\n  if (_jacobianqForces)\n  {\n    _jacobianqForces->zero();\n    if (_jacobianFIntq)\n    {\n      computeJacobianFIntq(time);\n      _jacobianqForces->setBlock(0,0,-1.0 * *_jacobianFIntq);\n    }\n    if (_jacobianMIntq)\n    {\n      computeJacobianMIntq(time);\n      SP::SimpleMatrix aux (new SimpleMatrix(3,_qDim));\n      SP::SimpleMatrix RT (new SimpleMatrix(3,3));\n      //computeMObjToAbs();\n      RT->trans(*_MObjToAbs);\n      prod(*RT, *_jacobianMIntq, *aux);\n      _jacobianqForces->setBlock(3,0, -1.0* *aux);\n      //_jacobianqForces->setBlock(3,0,-1.0* *_jacobianMIntq);\n    }\n    // std::cout << \"_jacobianqForces : \"<< std::endl;\n    // _jacobianqForces->display();\n  }\n  //else nothing.\n}\n\nvoid NewtonEulerDS::computeJacobianvForces(double time)\n{\n  if (_jacobianvForces)\n  {\n    _jacobianvForces->zero();\n    if (_jacobianFIntv)\n    {\n      computeJacobianFIntv(time);\n      _jacobianvForces->setBlock(0,0,-1.0 * *_jacobianFIntv);\n    }\n    if (_jacobianMIntv)\n    {\n      computeJacobianMIntv(time);\n      _jacobianvForces->setBlock(3,0,-1.0 * *_jacobianMIntv);\n    }\n    if (_jacobianFGyrv)\n    {\n      //computeJacobianFGyrvByFD(time,_q,_v);\n      computeJacobianFGyrv(time);\n      *_jacobianvForces -= *_jacobianFGyrv;\n    }\n    // std::cout << \"_jacobianvForces : \"<< std::endl;\n    // _jacobianvForces->display();\n  }\n  //else nothing.\n}\n\nvoid NewtonEulerDS::computeJacobianFGyrv(double time)\n{\n  DEBUG_BEGIN(\"NewtonEulerDS::computeJacobianFGyrv(double time) \\n\");\n  if (_jacobianFGyrv)\n  {\n    //Omega /\\ I \\Omega:\n    _jacobianFGyrv->zero();\n    SiconosVector omega(3);\n    omega.setValue(0, _v->getValue(3));\n    omega.setValue(1, _v->getValue(4));\n    omega.setValue(2, _v->getValue(5));\n    SiconosVector Iomega(3);\n    prod(*_I, omega, Iomega, true);\n    SiconosVector ei(3);\n    SiconosVector Iei(3);\n    SiconosVector ei_Iomega(3);\n    SiconosVector omega_Iei(3);\n\n    /*See equation of DevNotes.pdf, equation with label eq:NE_nablaFL1*/\n    for (int i = 0; i < 3; i++)\n    {\n      ei.zero();\n      ei.setValue(i, 1.0);\n      prod(*_I, ei, Iei, true);\n      cross_product(omega, Iei, omega_Iei);\n      cross_product(ei, Iomega, ei_Iomega);\n      for (int j = 0; j < 3; j++)\n        _jacobianFGyrv->setValue(3 + j, 3 + i, ei_Iomega.getValue(j) + omega_Iei.getValue(j));\n    }\n    // Check if Jacobian is valid. Warning to the transpose operation in\n    // _jacobianFGyrv->setValue(3 + j, 3 + i, ei_Iomega.getValue(j) + omega_Iei.getValue(j));\n  }\n  //else nothing.\n  DEBUG_EXPR(_jacobianFGyrv->display());\n  DEBUG_END(\"NewtonEulerDS::computeJacobianFGyrv(double time) \\n\");\n}\n\n\nvoid NewtonEulerDS::display() const\n{\n  std::cout << \"=====> NewtonEuler System display (number: \" << _number << \").\" <<std::endl;\n  std::cout << \"- _n : \" << _n <<std::endl;\n  std::cout << \"- q \" <<std::endl;\n  if (_q) _q->display();\n  else std::cout << \"-> NULL\" <<std::endl;\n  std::cout << \"- q0 \" <<std::endl;\n  if (_q0) _q0->display();\n  std::cout << \"- v \" <<std::endl;\n  if (_v) _v->display();\n  else std::cout << \"-> NULL\" <<std::endl;\n  std::cout << \"- v0 \" <<std::endl;\n  if (_v0) _v0->display();\n  else std::cout << \"-> NULL\" <<std::endl;\n  std::cout << \"- dotq \" <<std::endl;\n  if (_dotq) _dotq->display();\n  else std::cout << \"-> NULL\" <<std::endl;\n  std::cout << \"- p[0] \" <<std::endl;\n  if (_p[0]) _p[0]->display();\n  else std::cout << \"-> NULL\" <<std::endl;\n  std::cout << \"- p[1] \" <<std::endl;\n  if (_p[1]) _p[1]->display();\n  else std::cout << \"-> NULL\" <<std::endl;\n  std::cout << \"- p[2] \" <<std::endl;\n  if (_p[2]) _p[2]->display();\n  else std::cout << \"-> NULL\" <<std::endl;\n  std::cout << \"mass :\" <<  _scalarMass <<std::endl;\n  std::cout << \"Inertia :\" <<std::endl;\n  if (_I) _I->display();\n  else std::cout << \"-> NULL\" <<std::endl;\n  std::cout << \"===================================== \" <<std::endl;\n}\n\n// --- Functions for memory handling ---\nvoid NewtonEulerDS::initMemory(unsigned int steps)\n{\n  DynamicalSystem::initMemory(steps);\n\n  if (steps == 0)\n    std::cout << \"Warning : NewtonEulerDS::initMemory with size equal to zero\" <<std::endl;\n  else\n  {\n    _qMemory.reset(new SiconosMemory(steps, _qDim));\n    _vMemory.reset(new SiconosMemory(steps, _n));\n    _forcesMemory.reset(new SiconosMemory(steps, _n));\n    _dotqMemory.reset(new SiconosMemory(steps, _qDim));\n    swapInMemory();\n  }\n}\n\nvoid NewtonEulerDS::swapInMemory()\n{\n  //  _xMemory->swap(_x[0]);\n  _qMemory->swap(*_q);\n  _vMemory->swap(*_v);\n  _dotqMemory->swap(*_dotq);\n  _forcesMemory->swap(*_forces);\n}\n\nvoid NewtonEulerDS::resetAllNonSmoothPart()\n{\n  if (_p[1])\n    _p[1]->zero();\n  else\n    _p[1].reset(new SiconosVector(_n));\n}\nvoid NewtonEulerDS::resetNonSmoothPart(unsigned int level)\n{\n  if (_p[level]->size() > 0)\n    _p[level]->zero();\n}\n\n\nvoid NewtonEulerDS::computeT()\n{\n  ::computeT(_q,_T);\n}\n\n\n\nvoid NewtonEulerDS::computeTdot()\n{\n  if (!_Tdot)\n  {\n    _Tdot.reset(new SimpleMatrix(_qDim, _n));\n    _Tdot->zero();\n  }\n\n  ::computeT(_dotq,_Tdot);\n}\n\n\n\n\n\nvoid NewtonEulerDS::normalizeq()\n{\n  double normq = sqrt(_q->getValue(3) * _q->getValue(3) + _q->getValue(4) * _q->getValue(4) + _q->getValue(5) * _q->getValue(5) + _q->getValue(6) * _q->getValue(6));\n  assert(normq > 0);\n  normq = 1 / normq;\n  _q->setValue(3, _q->getValue(3) * normq);\n  _q->setValue(4, _q->getValue(4) * normq);\n  _q->setValue(5, _q->getValue(5) * normq);\n  _q->setValue(6, _q->getValue(6) * normq);\n}\nvoid NewtonEulerDS::computeMObjToAbs()\n{\n  ::computeMObjToAbs(_q, _MObjToAbs);\n}\n\n\n\nvoid NewtonEulerDS::setComputeJacobianFIntqFunction(const std::string&  pluginPath, const std::string&  functionName)\n{\n  //    Plugin::setFunction(&computeJacobianFIntqPtr, pluginPath,functionName);\n  _pluginJacqFInt->setComputeFunction(pluginPath, functionName);\n}\nvoid NewtonEulerDS::setComputeJacobianFIntvFunction(const std::string&  pluginPath, const std::string&  functionName)\n{\n  //    Plugin::setFunction(&computeJacobianFIntvPtr, pluginPath,functionName);\n  _pluginJacvFInt->setComputeFunction(pluginPath, functionName);\n}\nvoid NewtonEulerDS::setComputeJacobianFIntqFunction(FInt_NE fct)\n{\n  _pluginJacqFInt->setComputeFunction((void *)fct);\n}\nvoid NewtonEulerDS::setComputeJacobianFIntvFunction(FInt_NE fct)\n{\n  _pluginJacvFInt->setComputeFunction((void *)fct);\n}\n\n\nvoid NewtonEulerDS::setComputeJacobianMIntqFunction(const std::string&  pluginPath, const std::string&  functionName)\n{\n  //    Plugin::setFunction(&computeJacobianFIntqPtr, pluginPath,functionName);\n  _pluginJacqMInt->setComputeFunction(pluginPath, functionName);\n}\nvoid NewtonEulerDS::setComputeJacobianMIntvFunction(const std::string&  pluginPath, const std::string&  functionName)\n{\n  //    Plugin::setFunction(&computeJacobianFIntvPtr, pluginPath,functionName);\n  _pluginJacvMInt->setComputeFunction(pluginPath, functionName);\n}\nvoid NewtonEulerDS::setComputeJacobianMIntqFunction(FInt_NE fct)\n{\n  _pluginJacqMInt->setComputeFunction((void *)fct);\n}\nvoid NewtonEulerDS::setComputeJacobianMIntvFunction(FInt_NE fct)\n{\n  _pluginJacvMInt->setComputeFunction((void *)fct);\n}\n\n\ndouble NewtonEulerDS::computeKineticEnergy()\n{\n  DEBUG_BEGIN(\"NewtonEulerDS::computeKineticEnergy()\\n\");\n  assert(_v);\n  assert(_massMatrix);\n  DEBUG_EXPR(_v->display());\n  DEBUG_EXPR(_massMatrix->display());\n\n  SiconosVector tmp(6);\n  prod(*_massMatrix, *_v, tmp, true);\n  double K =0.5*inner_prod(tmp,*_v);\n\n  DEBUG_PRINTF(\"Kinetic Energy = %e\\n\", K);\n  DEBUG_END(\"NewtonEulerDS::computeKineticEnergy()\\n\");\n  return K;\n}\n", "meta": {"hexsha": "494bcc4bcb0bb7edab347b99715ed912495b0289", "size": 30491, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "kernel/src/modelingTools/NewtonEulerDS.cpp", "max_stars_repo_name": "siconos/siconos-deb", "max_stars_repo_head_hexsha": "2739a23f23d797dbfecec79d409e914e13c45c67", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "kernel/src/modelingTools/NewtonEulerDS.cpp", "max_issues_repo_name": "siconos/siconos-deb", "max_issues_repo_head_hexsha": "2739a23f23d797dbfecec79d409e914e13c45c67", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "kernel/src/modelingTools/NewtonEulerDS.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": 30.9867886179, "max_line_length": 165, "alphanum_fraction": 0.6721327605, "num_tokens": 10133, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.63341026367784, "lm_q2_score": 0.5350984286266115, "lm_q1q2_score": 0.3389368367699799}}
{"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 _ALARCON2004OXYGENBASEDCELLCYCLEODESYSTEM_HPP_\n#define _ALARCON2004OXYGENBASEDCELLCYCLEODESYSTEM_HPP_\n\n#include \"ChasteSerialization.hpp\"\n#include <boost/serialization/base_object.hpp>\n\n#include <cmath>\n\n#include \"AbstractOdeSystem.hpp\"\n\n/**\n * Represents the Alarcon et al. (2004) system of ODEs (see ticket #461).\n * [doi:10.1016/j.jtbi.2004.04.016]\n *\n * The variables are\n *\n *  0. x = Cdh1-APC complexes\n *  1. y = cyclin-CDK\n *  2. z = p27\n *  3. m = mass\n *  4. u = RBNP\n *  5. P = oxygen concentration\n */\nclass Alarcon2004OxygenBasedCellCycleOdeSystem : public AbstractOdeSystem\n{\nprivate:\n\n    /**\n     * Constants for the Alarcon et al. (2004) model\n     */\n\n    /** Dimensionless parameter a_1. */\n    double ma1;\n    /** Dimensionless parameter a_2. */\n    double ma2;\n    /** Dimensionless parameter a_3. */\n    double ma3;\n    /** Dimensionless parameter a_4. */\n    double ma4;\n    /** Dimensionless parameter b_3. */\n    double mb3;\n    /** Dimensionless parameter b_4. */\n    double mb4;\n    /** Dimensionless parameter c_1. */\n    double mc1;\n    /** Dimensionless parameter c_2. */\n    double mc2;\n    /** Dimensionless parameter d_1. */\n    double md1;\n    /** Dimensionless parameter d_2. */\n    double md2;\n    /** Dimensionless parameter J_3. */\n    double mJ3;\n    /** Dimensionless parameter J_4. */\n    double mJ4;\n    /** Dimensionless parameter eta. */\n    double mEta;\n    /** Dimensionless parameter m_star. */\n    double mMstar;\n    /** Dimensionless parameter B. */\n    double mB;\n    /** Dimensionless parameter x_THR. */\n    double mxThreshold;\n    /** Dimensionless parameter y_THR. */\n    double myThreshold;\n\n    /** The oxygen concentration (this affects the ODE system). */\n    double mOxygenConcentration;\n\n    /** Whether the cell associated with this cell cycle ODE system is labelled (this affects the ODE system). */\n    bool mIsLabelled;\n\n    friend class boost::serialization::access;\n    /**\n     * Serialize 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<AbstractOdeSystem>(*this);\n    }\n\npublic:\n\n    /**\n     * Constructor.\n     *\n     * @param oxygenConcentration is a non-dimensional oxygen concentration value between 0 and 1\n     * @param isLabelled whether the cell associated with this cell cycle ODE system is labelled (this affects the ODE system)\n     * @param stateVariables optional initial conditions for state variables (only used in archiving)\n     */\n    Alarcon2004OxygenBasedCellCycleOdeSystem(double oxygenConcentration,\n                                             bool isLabelled,\n                                             std::vector<double> stateVariables=std::vector<double>());\n\n    /**\n     * Destructor.\n     */\n    ~Alarcon2004OxygenBasedCellCycleOdeSystem();\n\n    /**\n     * Initialise parameter values.\n     */\n    void Init();\n\n    /**\n     * Compute the RHS of the Alarcon et al. (2004) system of ODEs.\n     *\n     * Returns a vector representing the RHS of the ODEs at each time step, y' = [y1' ... yn'].\n     * An ODE solver will call this function repeatedly to solve for y = [y1 ... yn].\n     *\n     * @param time used to evaluate the RHS.\n     * @param rY value of the solution vector used to evaluate the RHS.\n     * @param rDY filled in with the resulting derivatives (using Alarcons et al. (2004) system of equations).\n     */\n    void EvaluateYDerivatives(double time, const std::vector<double>& rY, std::vector<double>& rDY);\n\n    /**\n     * Calculate whether the conditions for the cell cycle to finish have been met.\n     *\n     * @param time at which to calculate whether the stopping event has occurred\n     * @param rY value of the solution vector used to evaluate the RHS.\n     *\n     * @return whether or not stopping conditions have been met\n     */\n    bool CalculateStoppingEvent(double time, const std::vector<double>& rY);\n\n    /**\n     * Set #mIsLabelled.\n     *\n     * @param isLabelled whether the cell associated with this cell cycle ODE system is labelled (this affects the ODE system)\n     */\n    void SetIsLabelled(bool isLabelled);\n\n    /**\n     * @return #mIsLabelled.\n     */\n    bool IsLabelled() const;\n\n    /**\n     * @return #mOxygenConcentration.\n     */\n    double GetOxygenConcentration() const;\n};\n\n// Declare identifier for the serializer\n#include \"SerializationExportWrapper.hpp\"\nCHASTE_CLASS_EXPORT(Alarcon2004OxygenBasedCellCycleOdeSystem)\n\nnamespace boost\n{\nnamespace serialization\n{\n/**\n * Serialize information required to construct an Alarcon2004OxygenBasedCellCycleOdeSystem.\n */\ntemplate<class Archive>\ninline void save_construct_data(\n    Archive & ar, const Alarcon2004OxygenBasedCellCycleOdeSystem * t, const unsigned int file_version)\n{\n    // Save data required to construct instance\n    const double oxygen_concentration = t->GetOxygenConcentration();\n    ar & oxygen_concentration;\n\n    const bool is_labelled = t->IsLabelled();\n    ar & is_labelled;\n\n    const std::vector<double>& state_variables = t->rGetConstStateVariables();\n    ar & state_variables;\n}\n\n/**\n * De-serialize constructor parameters and initialise an Alarcon2004OxygenBasedCellCycleOdeSystem.\n */\ntemplate<class Archive>\ninline void load_construct_data(\n    Archive & ar, Alarcon2004OxygenBasedCellCycleOdeSystem * t, const unsigned int file_version)\n{\n    // Retrieve data from archive required to construct new instance\n    double oxygen_concentration;\n    ar & oxygen_concentration;\n\n    bool is_labelled;\n    ar & is_labelled;\n\n    std::vector<double> state_variables;\n    ar & state_variables;\n\n    // Invoke inplace constructor to initialise instance\n    ::new(t)Alarcon2004OxygenBasedCellCycleOdeSystem(oxygen_concentration, is_labelled, state_variables);\n}\n}\n} // namespace ...\n\n#endif /*_ALARCON2004OXYGENBASEDCELLCYCLEODESYSTEM_HPP_*/\n", "meta": {"hexsha": "0e7bb645d67891d1e6f847bd3bfe8b4fd3f43050", "size": 7732, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "cell_based/src/odes/Alarcon2004OxygenBasedCellCycleOdeSystem.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": "cell_based/src/odes/Alarcon2004OxygenBasedCellCycleOdeSystem.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": "cell_based/src/odes/Alarcon2004OxygenBasedCellCycleOdeSystem.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": 33.0427350427, "max_line_length": 126, "alphanum_fraction": 0.7084842214, "num_tokens": 1829, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6334102498375401, "lm_q2_score": 0.5350984286266115, "lm_q1q2_score": 0.3389368293640571}}
{"text": "/**\n * @file recurrent_attention.hpp\n * @author Marcus Edel\n *\n * Definition of the RecurrentAttention class.\n *\n * mlpack is free software; you may redistribute it and/or modify it under the\n * terms of the 3-clause BSD license.  You should have received a copy of the\n * 3-clause BSD license along with mlpack.  If not, see\n * http://www.opensource.org/licenses/BSD-3-Clause for more information.\n */\n#ifndef MLPACK_METHODS_ANN_LAYER_RECURRENT_ATTENTION_HPP\n#define MLPACK_METHODS_ANN_LAYER_RECURRENT_ATTENTION_HPP\n\n#include <mlpack/prereqs.hpp>\n#include <boost/ptr_container/ptr_vector.hpp>\n\n#include \"../visitor/delta_visitor.hpp\"\n#include \"../visitor/output_parameter_visitor.hpp\"\n#include \"../visitor/reset_visitor.hpp\"\n#include \"../visitor/weight_size_visitor.hpp\"\n\n#include \"layer_types.hpp\"\n#include \"add_merge.hpp\"\n#include \"sequential.hpp\"\n\nnamespace mlpack {\nnamespace ann /** Artificial Neural Network. */ {\n\n/**\n * This class implements the Recurrent Model for Visual Attention, using a\n * variety of possible layer implementations.\n *\n * For more information, see the following paper.\n *\n * @code\n * @article{MnihHGK14,\n *   title={Recurrent Models of Visual Attention},\n *   author={Volodymyr Mnih, Nicolas Heess, Alex Graves, Koray Kavukcuoglu},\n *   journal={CoRR},\n *   volume={abs/1406.6247},\n *   year={2014}\n * }\n * @endcode\n *\n * @tparam InputDataType Type of the input data (arma::colvec, arma::mat,\n *         arma::sp_mat or arma::cube).\n * @tparam OutputDataType Type of the output data (arma::colvec, arma::mat,\n *         arma::sp_mat or arma::cube).\n */\ntemplate <\n    typename InputDataType = arma::mat,\n    typename OutputDataType = arma::mat\n>\nclass RecurrentAttention\n{\n public:\n  /**\n   * Default constructor: this will not give a usable RecurrentAttention object,\n   * so be sure to set all the parameters before use.\n   */\n  RecurrentAttention();\n\n  /**\n   * Create the RecurrentAttention object using the specified modules.\n   *\n   * @param start The module output size.\n   * @param start The recurrent neural network module.\n   * @param start The action module.\n   * @param rho Maximum number of steps to backpropagate through time (BPTT).\n   */\n  template<typename RNNModuleType, typename ActionModuleType>\n  RecurrentAttention(const size_t outSize,\n                     const RNNModuleType& rnn,\n                     const ActionModuleType& action,\n                     const size_t rho);\n\n  /**\n   * Ordinary feed forward pass of a neural network, evaluating the function\n   * f(x) by propagating the activity forward through f.\n   *\n   * @param input Input data used for evaluating the specified function.\n   * @param output Resulting output activation.\n   */\n  template<typename eT>\n  void Forward(arma::Mat<eT>&& input, arma::Mat<eT>&& output);\n\n  /**\n   * Ordinary feed backward pass of a neural network, calculating the function\n   * f(x) by propagating x backwards trough f. Using the results from the feed\n   * forward pass.\n   *\n   * @param input The propagated input activation.\n   * @param gy The backpropagated error.\n   * @param g The calculated gradient.\n   */\n  template<typename eT>\n  void Backward(const arma::Mat<eT>&& /* input */,\n                arma::Mat<eT>&& gy,\n                arma::Mat<eT>&& g);\n\n  /*\n   * Calculate the gradient using the output delta and the input activation.\n   *\n   * @param input The input parameter used for calculating the gradient.\n   * @param error The calculated error.\n   * @param gradient The calculated gradient.\n   */\n  template<typename eT>\n  void Gradient(arma::Mat<eT>&& /* input */,\n                arma::Mat<eT>&& /* error */,\n                arma::Mat<eT>&& /* gradient */);\n\n  //! Get the model modules.\n  std::vector<LayerTypes<>>& Model() { return network; }\n\n    //! The value of the deterministic parameter.\n  bool Deterministic() const { return deterministic; }\n  //! Modify the value of the deterministic parameter.\n  bool& Deterministic() { return deterministic; }\n\n  //! Get the parameters.\n  OutputDataType const& Parameters() const { return parameters; }\n  //! Modify the parameters.\n  OutputDataType& Parameters() { return parameters; }\n\n  //! Get the input parameter.\n  InputDataType const& InputParameter() const { return inputParameter; }\n  //! Modify the input parameter.\n  InputDataType& InputParameter() { return inputParameter; }\n\n  //! Get the output parameter.\n  OutputDataType const& OutputParameter() const { return outputParameter; }\n  //! Modify the output parameter.\n  OutputDataType& OutputParameter() { return outputParameter; }\n\n  //! Get the delta.\n  OutputDataType const& Delta() const { return delta; }\n  //! Modify the delta.\n  OutputDataType& Delta() { return delta; }\n\n  //! Get the gradient.\n  OutputDataType const& Gradient() const { return gradient; }\n  //! Modify the gradient.\n  OutputDataType& Gradient() { return gradient; }\n\n  /**\n   * Serialize the layer\n   */\n  template<typename Archive>\n  void serialize(Archive& ar, const unsigned int /* version */);\n\n private:\n  //! Calculate the gradient of the attention module.\n  void IntermediateGradient()\n  {\n    intermediateGradient.zeros();\n\n    // Gradient of the action module.\n    if (backwardStep == (rho - 1))\n    {\n      boost::apply_visitor(GradientVisitor(std::move(initialInput),\n          std::move(actionError)), actionModule);\n    }\n    else\n    {\n      boost::apply_visitor(GradientVisitor(std::move(boost::apply_visitor(\n          outputParameterVisitor, actionModule)), std::move(actionError)),\n          actionModule);\n    }\n\n    // Gradient of the recurrent module.\n    boost::apply_visitor(GradientVisitor(std::move(boost::apply_visitor(\n        outputParameterVisitor, rnnModule)), std::move(recurrentError)),\n        rnnModule);\n\n    attentionGradient += intermediateGradient;\n  }\n\n  //! Locally-stored module output size.\n  size_t outSize;\n\n  //! Locally-stored start module.\n  LayerTypes<> rnnModule;\n\n  //! Locally-stored input module.\n  LayerTypes<> actionModule;\n\n  //! Number of steps to backpropagate through time (BPTT).\n  size_t rho;\n\n  //! Locally-stored number of forward steps.\n  size_t forwardStep;\n\n  //! Locally-stored number of backward steps.\n  size_t backwardStep;\n\n  //! If true dropout and scaling is disabled, see notes above.\n  bool deterministic;\n\n  //! Locally-stored weight object.\n  OutputDataType parameters;\n\n  //! Locally-stored model modules.\n  std::vector<LayerTypes<>> network;\n\n  //! Locally-stored weight size visitor.\n  WeightSizeVisitor weightSizeVisitor;\n\n  //! Locally-stored delta visitor.\n  DeltaVisitor deltaVisitor;\n\n  //! Locally-stored output parameter visitor.\n  OutputParameterVisitor outputParameterVisitor;\n\n  //! Locally-stored feedback output parameters.\n  std::vector<arma::mat> feedbackOutputParameter;\n\n  //! List of all module parameters for the backward pass (BBTT).\n  std::vector<arma::mat> moduleOutputParameter;\n\n  //! Locally-stored delta object.\n  OutputDataType delta;\n\n  //! Locally-stored gradient object.\n  OutputDataType gradient;\n\n  //! Locally-stored input parameter object.\n  InputDataType inputParameter;\n\n  //! Locally-stored output parameter object.\n  OutputDataType outputParameter;\n\n  //! Locally-stored recurrent error parameter.\n  arma::mat recurrentError;\n\n  //! Locally-stored action error parameter.\n  arma::mat actionError;\n\n  //! Locally-stored action delta.\n  arma::mat actionDelta;\n\n  //! Locally-stored recurrent delta.\n  arma::mat rnnDelta;\n\n  //! Locally-stored initial action input.\n  arma::mat initialInput;\n\n  //! Locally-stored reset visitor.\n  ResetVisitor resetVisitor;\n\n  //! Locally-stored attention gradient.\n  arma::mat attentionGradient;\n\n  //! Locally-stored intermediate gradient for the attention module.\n  arma::mat intermediateGradient;\n}; // class RecurrentAttention\n\n} // namespace ann\n} // namespace mlpack\n\n// Include implementation.\n#include \"recurrent_attention_impl.hpp\"\n\n#endif\n", "meta": {"hexsha": "b42f4d261b32014e602a6dc86eb978f14b133df3", "size": 7902, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/mlpack/methods/ann/layer/recurrent_attention.hpp", "max_stars_repo_name": "MJ10/mlpack", "max_stars_repo_head_hexsha": "3f87ab1d419493dead8ef59250c02cc7aacc0adb", "max_stars_repo_licenses": ["BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-05-02T21:10:55.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-02T21:10:55.000Z", "max_issues_repo_path": "src/mlpack/methods/ann/layer/recurrent_attention.hpp", "max_issues_repo_name": "MJ10/mlpack", "max_issues_repo_head_hexsha": "3f87ab1d419493dead8ef59250c02cc7aacc0adb", "max_issues_repo_licenses": ["BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/mlpack/methods/ann/layer/recurrent_attention.hpp", "max_forks_repo_name": "MJ10/mlpack", "max_forks_repo_head_hexsha": "3f87ab1d419493dead8ef59250c02cc7aacc0adb", "max_forks_repo_licenses": ["BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.7067669173, "max_line_length": 80, "alphanum_fraction": 0.7007086813, "num_tokens": 1817, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.672331699179286, "lm_q2_score": 0.5039061705290805, "lm_q1q2_score": 0.33879209185874376}}
{"text": "/* ============================================================================\n * Copyright (c) 2010, Michael A. Jackson (BlueQuartz Software)\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 *\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 Michael A. Jackson nor the names of its contributors may\n * 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 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\n\n#include \"InitializationFunctions.h\"\n//-- C Includes\n#include <stdlib.h>\n#include <stdio.h>\n#include <string.h>\n\n\n//-- Boost Includes\n#include <boost/random/mersenne_twister.hpp>\n#include <boost/random/uniform_real.hpp>\n#include <boost/random/variate_generator.hpp>\n\n\n//-- EMMMPM Lib Includes\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\n\n// -----------------------------------------------------------------------------\n//\n// -----------------------------------------------------------------------------\nInitializationFunction::InitializationFunction()\n{\n\n}\n\n// -----------------------------------------------------------------------------\n//\n// -----------------------------------------------------------------------------\nInitializationFunction::~InitializationFunction()\n{\n\n}\n\n// -----------------------------------------------------------------------------\n//\n// -----------------------------------------------------------------------------\nvoid InitializationFunction::initialize(EMMPM_Data::Pointer data)\n{\n\n}\n\n\n\n// -----------------------------------------------------------------------------\n//\n// -----------------------------------------------------------------------------\nBasicInitialization::BasicInitialization()\n{\n\n}\n\n// -----------------------------------------------------------------------------\n//\n// -----------------------------------------------------------------------------\nBasicInitialization::~BasicInitialization()\n{\n\n}\n\n// -----------------------------------------------------------------------------\n//\n// -----------------------------------------------------------------------------\nvoid BasicInitialization::initialize(EMMPM_Data::Pointer data)\n{\n  //FIXME: This needs to be adapted for vector images (dims > 1)\n  unsigned int i, k, l;\n  real_t mu, sigma;\n  char msgbuff[256];\n  unsigned int rows = data->rows;\n  unsigned int cols = data->columns;\n  unsigned int classes = data->classes;\n  unsigned char* y = data->y;\n  size_t total;\n\n  rows = data->rows;\n  cols = data->columns;\n  total = data->rows * data->columns;\n\n\n  memset(msgbuff, 0, 256);\n\n  /* Initialization of parameter estimation */\n  mu = 0;\n  sigma = 0;\n  for (i = 0; i < total; i++) {\n      mu += y[i];\n  }\n\n  mu /= (rows * cols);\n\n  for (i = 0; i < total; i++) {\n      sigma += (y[i] - mu) * (y[i] - mu);\n  }\n\n  sigma /= (rows * cols);\n  sigma = sqrt((real_t)sigma);\n\n  if (classes % 2 == 0)\n  {\n    for (k = 0; k < classes / 2; k++)\n    {\n        data->mean[classes / 2 + k] = mu + (k + 1) * sigma / 2;\n        data->mean[classes / 2 - 1 - k] = mu - (k + 1) * sigma / 2;\n    }\n  }\n  else\n  {\n    data->mean[classes / 2] = mu;\n    for (k = 0; k < classes / 2; k++)\n    {\n      data->mean[classes / 2 + 1 + k] = mu + (k + 1) * sigma / 2;\n      data->mean[classes / 2 - 1 - k] = mu - (k + 1) * sigma / 2;\n    }\n  }\n\n  for (l = 0; l < classes; l++)\n  {\n    data->variance[l] = 20.0;\n  }\n}\n\n\n\n// -----------------------------------------------------------------------------\n//\n// -----------------------------------------------------------------------------\nUserDefinedAreasInitialization::UserDefinedAreasInitialization()\n{\n\n}\n\n// -----------------------------------------------------------------------------\n//\n// -----------------------------------------------------------------------------\nUserDefinedAreasInitialization::~UserDefinedAreasInitialization()\n{\n\n}\n\n// -----------------------------------------------------------------------------\n//\n// -----------------------------------------------------------------------------\nvoid UserDefinedAreasInitialization::initialize(EMMPM_Data::Pointer data)\n{\n\n  unsigned int i, j;\n  size_t index;\n  int c, l;\n  real_t mu, sigma;\n  unsigned int rows = data->rows;\n  unsigned int cols = data->columns;\n  char msgbuff[256];\n  unsigned char* y = data->y;\n  //  unsigned char** xt = data->xt;\n  rows = data->rows;\n  cols = data->columns;\n\n  sigma = 0;\n  mu = 0;\n\n  if (data->dims != 1)\n  {\n    printf(\"User Defined Initialization ONLY works with GrayScale images and not vector images.\\n  %s(%d)\", __FILE__, __LINE__);\n    exit(1);\n  }\n\n  memset(msgbuff, 0, 256);\n\n  for (c = 0; c < data->classes; c++)\n  {\n    int x1 = data->initCoords[c][0];\n    int y1 = data->initCoords[c][1];\n    int x2 = data->initCoords[c][2];\n    int y2 = data->initCoords[c][3];\n    mu = 0;\n    snprintf(msgbuff, 256, \"m[%d] Coords: %d %d %d %d\", c, x1, y1, x2, y2);\n    for (i = data->initCoords[c][1]; i < data->initCoords[c][3]; i++)\n    {\n      for (j = data->initCoords[c][0]; j < data->initCoords[c][2]; j++)\n      {\n        index = (cols * i) + j;\n        mu += y[index];\n      }\n    }\n\n    mu /= (y2 - y1) * (x2 - x1);\n    data->mean[c] = mu;\n    snprintf(msgbuff, 256, \"m[%d]=%f\", c, mu);\n  }\n\n  for (l = 0; l < data->classes; l++)\n  {\n    data->variance[l] = 20.0;\n  }\n\n}\n\n\n// -----------------------------------------------------------------------------\n//\n// -----------------------------------------------------------------------------\nXtArrayInitialization::XtArrayInitialization()\n{\n\n}\n\n// -----------------------------------------------------------------------------\n//\n// -----------------------------------------------------------------------------\nXtArrayInitialization::~XtArrayInitialization()\n{\n\n}\n\n// -----------------------------------------------------------------------------\n//\n// -----------------------------------------------------------------------------\nvoid XtArrayInitialization::initialize(EMMPM_Data::Pointer data)\n{\n  size_t total;\n\n  total = data->rows * data->columns;\n\n  const float rangeMin = 0.0f;\n  const float rangeMax = 1.0f;\n  typedef boost::uniform_real<> 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  /* Initialize classification of each pixel randomly with a uniform disribution */\n  for (size_t i = 0; i < total; i++)\n  {\n      data->xt[i] = numberGenerator() * data->classes;\n  }\n\n}\n\n// -----------------------------------------------------------------------------\n//\n// -----------------------------------------------------------------------------\nGradientVariablesInitialization::GradientVariablesInitialization()\n{\n\n}\n\n// -----------------------------------------------------------------------------\n//\n// -----------------------------------------------------------------------------\nGradientVariablesInitialization::~GradientVariablesInitialization()\n{\n\n}\n\n// -----------------------------------------------------------------------------\n//\n// -----------------------------------------------------------------------------\nvoid GradientVariablesInitialization::initialize(EMMPM_Data::Pointer data)\n{\n  size_t ijd, ij, ijd1;\n\n  size_t nsCols = data->columns - 1;\n  size_t nsRows = data->rows;\n  size_t ewCols = data->columns;\n  size_t ewRows = data->rows - 1;\n  size_t swCols = data->columns - 1;\n  size_t swRows = data->rows - 1;\n  size_t nwCols = data->columns - 1;\n  size_t nwRows = data->rows - 1;\n\n  int dims = data->dims;\n  real_t x;\n\n  /* Allocate for edge images */\n\n  data->ns = (real_t*)malloc(nsCols * nsRows * sizeof(real_t));\n  if (data->ns == NULL) { return; }\n  data->ew = (real_t*)malloc(ewCols * ewRows * sizeof(real_t));\n  if (data->ew == NULL) { return; }\n  data->sw = (real_t*)malloc(swCols * swRows * sizeof(real_t));\n  if (data->sw == NULL) { return; }\n  data->nw = (real_t*)malloc(nwCols * nwRows * sizeof(real_t));\n  if (data->nw == NULL) { return; }\n\n  /* Do edge detection for gradient penalty*/\n  for (uint32_t i = 0; i < data->rows; i++)\n  {\n    for (uint32_t j = 0; j < nwCols; j++)\n    {\n      x = 0;\n      for (int32_t d = 0; d < dims; d++)\n      {\n        ijd = (dims * nwCols * i) + (dims * j) + d;\n        ijd1 = (dims * nwCols * (i)) + (dims * (j + 1)) + d;\n        x += (data->y[ijd] - data->y[ijd1]) * (data->y[ijd] - data->y[ijd1]);\n      }\n      ij = (nwCols * i) + j;\n      data->ns[ij] = data->beta_e * atan((10 - sqrt(x)) / 5);\n    }\n  }\n  for (uint32_t i = 0; i < nwRows; i++)\n  {\n    for (uint32_t j = 0; j < data->columns; j++)\n    {\n      x = 0;\n      for (int32_t d = 0; d < dims; d++)\n      {\n        ijd = (dims * data->columns * i) + (dims * j) + d;\n        ijd1 = (dims * data->columns * (i + 1)) + (dims * (j)) + d;\n        x += (data->y[ijd] - data->y[ijd1]) * (data->y[ijd] - data->y[ijd1]);\n      }\n      ij = (data->columns * i) + j;\n      data->ew[ij] = data->beta_e * atan((10 - sqrt(x)) / 5);\n    }\n  }\n  nwCols = data->columns - 1;\n  nwRows = data->rows - 1;\n  for (uint32_t i = 0; i < nwRows; i++)\n  {\n    for (uint32_t j = 0; j < nwCols; j++)\n    {\n      x = 0;\n      for (uint32_t d = 0; d < data->dims; d++)\n      {\n        ijd = (dims * data->columns * i) + (dims * j) + d;\n        ijd1 = (dims * data->columns * (i + 1)) + (dims * (j + 1)) + d;\n        x += (data->y[ijd] - data->y[ijd1]) * (data->y[ijd] - data->y[ijd1]);\n      }\n      ij = (nwCols * i) + j;\n      data->sw[ij] = data->beta_e * atan((10 - sqrt(0.5 * x)) / 5);\n      x = 0;\n      for (uint32_t d = 0; d < data->dims; d++)\n      {\n        ijd = (dims * data->columns * (i + 1)) + (dims * (j)) + d;\n        ijd1 = (dims * data->columns * (i)) + (dims * (j + 1)) + d;\n        x += (data->y[ijd] - data->y[ijd1]) * (data->y[ijd] - data->y[ijd1]);\n      }\n      ij = (nwCols * i) + j;\n      data->nw[ij] = data->beta_e * atan((10 - sqrt(0.5 * x)) / 5);\n    }\n  }\n\n}\n\n\n\n// -----------------------------------------------------------------------------\n//\n// -----------------------------------------------------------------------------\nCurvatureInitialization::CurvatureInitialization()\n{\n\n}\n\n// -----------------------------------------------------------------------------\n//\n// -----------------------------------------------------------------------------\nCurvatureInitialization::~CurvatureInitialization()\n{\n\n}\n\n// -----------------------------------------------------------------------------\n//\n// -----------------------------------------------------------------------------\nvoid CurvatureInitialization::initialize(EMMPM_Data::Pointer data)\n{\n\n}\n\n\n// -----------------------------------------------------------------------------\n//\n// -----------------------------------------------------------------------------\nvoid CurvatureInitialization::initCurvatureVariables(EMMPM_Data::Pointer data)\n{\n  int l, lij;\n  unsigned int i, j;\n\n  data->ccost = (real_t*)malloc(data->classes * data->rows * data->columns * sizeof(real_t));\n  if (data->ccost == NULL) { return; }\n\n  /* Initialize Curve Costs to zero */\n  for (l = 0; l < data->classes; l++)\n  {\n    for (i = 0; i < data->rows; i++)\n    {\n      for (j = 0; j < data->columns; j++)\n      {\n        {\n          lij = (data->columns * data->rows * l) + (data->columns * i) + j;\n          data->ccost[lij] = 0;\n        }\n      }\n    }\n  }\n}\n\n", "meta": {"hexsha": "9be73425786f5aed0b51a0d06416c9086ce45bf8", "size": 12898, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Code/EMMPMLib/Core/InitializationFunctions.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/InitializationFunctions.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/InitializationFunctions.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": 29.4474885845, "max_line_length": 128, "alphanum_fraction": 0.4518530005, "num_tokens": 3025, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6619228758499943, "lm_q2_score": 0.5117166047041654, "lm_q1q2_score": 0.33871692660597585}}
{"text": "#ifndef ALEPH_PERSISTENT_HOMOLOGY_EXTENDED_PERSISTENCE_HIERARCHY__\n#define ALEPH_PERSISTENT_HOMOLOGY_EXTENDED_PERSISTENCE_HIERARCHY__\n\n#include <algorithm>\n#include <map>\n#include <stdexcept>\n#include <set>\n#include <vector>\n\n#include <boost/bimap.hpp>\n\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/breadth_first_search.hpp>\n\n#include <aleph/persistentHomology/PersistencePairing.hh>\n\n#include <aleph/topology/SimplicialComplex.hh>\n#include <aleph/topology/UnionFind.hh>\n\nnamespace aleph\n{\n\nnamespace detail\n{\n\nusing AdjacencyGraph = boost::adjacency_list<\n  boost::vecS,\n  boost::vecS,\n  boost::undirectedS,\n  boost::no_property,\n  boost::no_property>;\n\nusing SizeType = std::size_t;\n\n/** Extracts the adjacency graph of a simplicial complex */\ntemplate <class Simplex>\nstd::pair<boost::bimap<typename Simplex::VertexType, SizeType>, AdjacencyGraph> extractZeroDimensionalAdjacencyGraph( const topology::SimplicialComplex<Simplex>& S )\n{\n  AdjacencyGraph adjacencyGraph;\n\n  using Vertex           = typename Simplex::VertexType;\n  using VertexDescriptor = boost::graph_traits<AdjacencyGraph>::vertex_descriptor;\n  using bimap_type       = boost::bimap<Vertex, SizeType>;\n\n  bimap_type indices;\n  std::map<Vertex, VertexDescriptor> vdm;\n\n  SizeType vertexIndex = 0;\n\n  for( auto it = S.begin_dimension(); it != S.end_dimension(); ++it )\n  {\n    // Vertices\n    if( it->dimension() == 0 )\n    {\n      indices.insert( typename bimap_type::value_type( *it->begin(), vertexIndex++ ) );\n\n      auto vertex         = boost::add_vertex( adjacencyGraph );\n      vdm[ *it->begin() ] = vertex;\n    }\n\n    // Edges\n    else if( it->dimension() == 1 )\n    {\n      auto&& edge = *it;\n\n      auto u = *( edge.begin()     );\n      auto v = *( edge.begin() + 1 );\n\n      // It is possible that the simplicial complex, being a _part_ of\n      // a larger filtration, contains edges for which no vertices are\n      // available.\n      if( S.contains(u) && S.contains(v) )\n      {\n        boost::add_edge( vdm.at(u),\n                         vdm.at(v),\n                         adjacencyGraph );\n      }\n    }\n  }\n\n  return std::make_pair( indices, adjacencyGraph );\n}\n\n} // namespace detail\n\n/**\n  @class ExtendedPersistenceHierarchy\n  @brief Functor for calculating the extended persistence hierarchy\n\n  This class is a functor that calculates the extended persistence\n  hierarchy of a given simplicial complex. The complex is supposed\n  to be in filtration order. Currently, only features in dimension\n  zero are supported by this functor.\n\n  For more information, please refer to the paper\n\n    Hierarchies and Ranks for Persistence Pairs\n    Bastian Rieck, Heike Leitte, and Filip Sadlo\n    Proceedings of TopoInVis 2017, Japan\n*/\n\ntemplate <class Simplex> class ExtendedPersistenceHierarchy\n{\npublic:\n  using SimplicialComplex = topology::SimplicialComplex<Simplex>;\n  using Vertex            = typename Simplex::VertexType;\n  using SimplexPairing    = PersistencePairing<Vertex>;\n\n  using EdgeType          = std::pair<Vertex, Vertex>;\n  using Edges             = std::vector<EdgeType>;\n\nprivate:\n\n  /**\n    Helper function for 'tagging' all edges in the simplicial complex\n    with the next critical point. This is a very slow---but simple---\n    way of decomposing the domain.\n  */\n\n  std::map<Simplex, Vertex> tagEdges( const SimplicialComplex& S )\n  {\n    std::set<Vertex> vertices;\n    S.vertices( std::inserter( vertices, vertices.begin() ) );\n\n    std::map<Vertex, Vertex>  criticalPointMapVertices;  // critical point map kept along with Union--Find structure\n    std::map<Simplex, Vertex> criticalPointMapSimplices; // critical point map on edge (simplex) basis (return value)\n\n    for( auto&& vertex : vertices )\n      criticalPointMapVertices[vertex] = vertex;\n\n    for( auto&& simplex : S )\n    {\n      if( simplex.dimension() != 1 )\n        continue;\n\n      Vertex u = *( simplex.begin() );\n      Vertex v = *( simplex.begin() + 1 );\n\n      auto youngerComponent = u;\n      auto olderComponent   = v;\n\n      if( youngerComponent != olderComponent )\n      {\n        auto index1 = S.index( Simplex(youngerComponent) );\n        auto index2 = S.index( Simplex(olderComponent)   );\n\n        if( index1 < index2 )\n          std::swap( youngerComponent, olderComponent );\n\n        Simplex creator = *( S.find( Simplex( youngerComponent ) ) );\n\n        if( creator.data() == simplex.data() )\n          criticalPointMapVertices[ youngerComponent ] = criticalPointMapVertices[ olderComponent ];\n      }\n\n      criticalPointMapSimplices[ simplex ] = criticalPointMapVertices[ olderComponent ];\n    }\n\n    return criticalPointMapSimplices;\n  }\n\n  /**\n    Calculates the interlevel set of a given simplicial complex. This\n    means extracting a subset in which the assigned weight of  _each_\n    simplex lies between the upper and lower value.\n\n    The function will return the interlevel set as a simplicial complex,\n    as well as a Union--Find data structure for connectivity queries.\n  */\n\n  std::pair< SimplicialComplex, topology::UnionFind<Vertex> >\n    makeInterlevelSet( typename Simplex::DataType lower, typename Simplex::DataType upper,\n                       const SimplicialComplex& S )\n  {\n    if( lower > upper )\n      std::swap( lower, upper );\n\n    std::vector<Simplex> simplices;\n\n    std::copy_if( S.begin(), S.end(),\n                  std::back_inserter( simplices ),\n                  [&lower, &upper] ( const Simplex& s )\n                  {\n                    return s.data() >= lower && s.data() <= upper && s.dimension() <= 1;\n                  } );\n\n    SimplicialComplex K = SimplicialComplex( simplices.begin(),\n                                             simplices.end() );\n\n    // -----------------------------------------------------------------\n    //\n    // Find all 'proper' vertices in the simplicial complex. It is\n    // possible that not all of them exist as 0-simplices, though.\n\n    std::set<Vertex> vertices;\n\n    for( auto&& simplex : simplices )\n    {\n      if( simplex.dimension() == 0 )\n        vertices.insert( *simplex.begin() );\n    }\n\n    // Traversal -------------------------------------------------------\n\n    topology::UnionFind<Vertex> uf( vertices.begin(), vertices.end()  );\n\n    for( auto&& simplex : K )\n    {\n      if( simplex.dimension() == 1 )\n      {\n        Vertex u = *( simplex.begin() );\n        Vertex v = *( simplex.begin() + 1 );\n\n        if( !uf.contains( u ) || !uf.contains( v ) )\n          continue;\n\n        auto youngerComponent = uf.find( u );\n        auto olderComponent   = uf.find( v );\n\n        if( youngerComponent == olderComponent )\n          continue;\n\n        auto index1 = S.index( Simplex( youngerComponent ) );\n        auto index2 = S.index( Simplex( olderComponent ) );\n\n        if( index1 < index2 )\n          std::swap( youngerComponent, olderComponent );\n\n        uf.merge( youngerComponent, olderComponent );\n      }\n    }\n\n    return std::make_pair( K, uf );\n  }\n\npublic:\n\n  /**\n    Given a simplicial complex, calculates its 0-dimensional persistent\n    homology and the corresponding extended persistence hierarchy. As a\n    result, this will return a simplex pairing and all the edges of the\n    pairing. Edges refer to indices in the original simplicial complex.\n  */\n\n  std::pair<SimplexPairing, Edges> operator()( const SimplicialComplex& simplicialComplex )\n  {\n    using namespace detail;\n\n    // Extract {0,1}-simplices -----------------------------------------\n\n    // Note that there is a range predicate for the simplicial complex class\n    // that does essentially the same. However, the predicate is not stable\n    // with respect to the filtration of the simplicial complex. Thus, to\n    // extract the desired simplices, the internal function cannot be used.\n\n    std::vector<Simplex> simplices;\n\n    std::copy_if( simplicialComplex.begin(), simplicialComplex.end(),\n                  std::back_inserter( simplices ),\n                  [] ( const Simplex& s ) { return s.dimension() <= 1; } );\n\n    SimplicialComplex S = SimplicialComplex( simplices.begin(),\n                                             simplices.end() );\n\n    // Persistence calculation -----------------------------------------\n\n    std::set<Vertex> vertices;\n    S.vertices( std::inserter( vertices,\n                               vertices.begin() ) );\n\n    Edges edges;\n\n    // Pairs indices of critical vertices. This may be used later on to\n    // obtain a persistence diagram. Using a pairing is advantageous as\n    // it does not operate on weights but on indices, which are unique.\n    SimplexPairing pairing;\n\n    // This map contains a simple decomposition of the domain in terms\n    // of the 'next' critical point.\n    //\n    // In a proper---and faster---implementation, Morse--Smale complex\n    // calculations could be used.\n    auto edgeToCriticalPoint = tagEdges( S );\n\n    // Keeps track of the critical points that are created along with\n    // hierarchy. This is the key difference to the regular hierarchy\n    // and permits the hierarchy to distinguish data sets even though\n    // their persistence diagram coincides.\n    std::map<Vertex, Vertex> vertexToCriticalPoint;\n    for( auto&& vertex : vertices )\n      vertexToCriticalPoint[vertex] = vertex;\n\n    // Required in order to obtain persistence pairs along with the\n    // edges of the persistence hierarchy.\n    topology::UnionFind<Vertex> uf( vertices.begin(), vertices.end() );\n\n    for( auto&& simplex : S )\n    {\n      // Only edges can destroy a component\n      if( simplex.dimension() != 1 )\n        continue;\n\n      auto u = *( simplex.begin() );\n      auto v = *( simplex.begin() + 1 );\n\n      // ---------------------------------------------------------------\n      //\n      // Ensure that the younger component is _always_ the first\n      // component. A component is younger if its representative\n      // vertex precedes the other vertex in the filtration.\n      auto youngerComponent = uf.find( u );\n      auto olderComponent   = uf.find( v );\n\n      // If the component has already been merged by some other edge, we are\n      // not interested in it any longer.\n      if( youngerComponent == olderComponent )\n        continue;\n\n      {\n        auto index1 = S.index( Simplex(youngerComponent) );\n        auto index2 = S.index( Simplex(olderComponent)   );\n\n        // The younger component has the _larger_ index as it is born _later_\n        // in the filtration.\n        if( index1 < index2 )\n          std::swap( youngerComponent, olderComponent );\n      }\n\n      // Prepare information about creators ----------------------------\n      //\n      // Creator simplex for the simplex pairing below. I know that this\n      // simplex must exist in the complex so I don't check for iterator\n      // validity here.\n      auto youngerCreator         = *( S.find( Simplex( youngerComponent ) ) );\n      auto olderCreator           = *( S.find( Simplex( olderComponent ) ) );\n      auto youngerCriticalSimplex = *( S.find( Simplex( vertexToCriticalPoint[youngerComponent] ) ) );\n      auto olderCriticalSimplex   = *( S.find( Simplex( vertexToCriticalPoint[olderComponent]   ) ) );\n\n      // Zero-persistence information; assign critical point of the\n      // older component directly. This ensures that we are able to\n      // obtain a proper decomposition.\n      if( youngerCreator.data() == simplex.data() )\n        vertexToCriticalPoint[youngerComponent] = olderComponent;\n      else\n      {\n        // Ensures that the oldest, highest/lowest critical simplex is\n        // being used to calculate the interlevel set. Else, it may be\n        // impossible for a critical point to be reached.\n        if( S.index( youngerCriticalSimplex ) < S.index( olderCriticalSimplex ) )\n          std::swap( youngerCriticalSimplex, olderCriticalSimplex );\n\n        auto clsPair\n          = makeInterlevelSet(\n              olderCriticalSimplex.data(), simplex.data(),\n              S );\n\n        bool inSameComponent\n          =   ( clsPair.second.contains( *olderCriticalSimplex.begin() ) && clsPair.second.contains( *youngerCriticalSimplex.begin() ) )\n           && ( clsPair.second.find( *olderCriticalSimplex.begin() ) == clsPair.second.find( *youngerCriticalSimplex.begin() ) );\n\n        if( inSameComponent )\n        {\n          using V = boost::graph_traits<AdjacencyGraph>::vertex_descriptor;\n\n          boost::bimap<Vertex, SizeType> vim;\n          AdjacencyGraph G;\n\n          std::tie( vim, G )\n            = extractZeroDimensionalAdjacencyGraph( clsPair.first );\n\n          std::vector<V> p( boost::num_vertices( G ) );\n\n          auto u = vim.left.at( *olderCriticalSimplex.begin() );\n          auto v = vim.left.at( *youngerCriticalSimplex.begin() );\n          p[u]   = u;\n\n          boost::breadth_first_search( G,\n                                       boost::vertex( u, G ),\n                                       boost::visitor(\n                                        boost::make_bfs_visitor(\n                                          boost::record_predecessors( &p[0], boost::on_tree_edge() ) ) ) );\n\n          std::set<Vertex> criticalPoints;\n\n          while( true )\n          {\n            auto parent = p.at( v );\n            auto s      = *S.find( Simplex( {vim.right.at(v),vim.right.at(parent)} ) );\n\n            if( parent == v )\n              break;\n\n            v = parent;\n\n            // Find out which critical point the identified edge\n            // belongs to.\n            criticalPoints.insert( edgeToCriticalPoint.at( s ) );\n          }\n\n          // Exactly two critical points (i.e. the ones we were\n          // looking for); hence, insert younger component as a\n          // child of the youngest critical point.\n          if( criticalPoints.size() == 2 )\n          {\n            edges.push_back( std::make_pair(\n              vertexToCriticalPoint[olderComponent],\n              youngerComponent )\n            );\n          }\n\n          // More critical points; connect the critical points\n          // according to the usual persistence hierarchy.\n          else\n          {\n            edges.push_back( std::make_pair(\n              olderComponent,\n              youngerComponent )\n            );\n          }\n        }\n\n        // Not in the same component; connect the critical points\n        // according to the usual persistence hierarchy.\n        else\n        {\n          edges.push_back( std::make_pair(\n            olderComponent,\n            youngerComponent )\n          );\n        }\n\n        // The youngest critical point along the current connected\n        // component has been changed.\n        vertexToCriticalPoint[olderComponent] = youngerComponent;\n      }\n\n      pairing.add( Vertex( S.index( Simplex( youngerCreator ) ) ),\n                   Vertex( S.index( simplex ) ) );\n\n      uf.merge( youngerComponent,\n                olderComponent );\n    }\n\n    // Add features of infinite persistence to the pairing -------------\n\n    std::set<Vertex> roots;\n    uf.roots( std::inserter( roots, roots.begin() ) );\n\n    for( auto&& root : roots )\n      pairing.add( Vertex( S.index( root ) ) );\n\n    return std::make_pair( pairing, edges );\n  }\n};\n\n} // namespace aleph\n\n#endif\n", "meta": {"hexsha": "9290a8f45ab23e5c8a42a289c85baea8f067f04c", "size": 15196, "ext": "hh", "lang": "C++", "max_stars_repo_path": "include/aleph/persistentHomology/ExtendedPersistenceHierarchy.hh", "max_stars_repo_name": "eudoxos/Aleph", "max_stars_repo_head_hexsha": "874882c33a0e8429c74e567eb01525613fee0616", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 56.0, "max_stars_repo_stars_event_min_datetime": "2019-04-24T22:11:15.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T11:37:47.000Z", "max_issues_repo_path": "include/aleph/persistentHomology/ExtendedPersistenceHierarchy.hh", "max_issues_repo_name": "eudoxos/Aleph", "max_issues_repo_head_hexsha": "874882c33a0e8429c74e567eb01525613fee0616", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 48.0, "max_issues_repo_issues_event_min_datetime": "2016-11-30T09:37:13.000Z", "max_issues_repo_issues_event_max_datetime": "2019-01-30T21:43:39.000Z", "max_forks_repo_path": "include/aleph/persistentHomology/ExtendedPersistenceHierarchy.hh", "max_forks_repo_name": "eudoxos/Aleph", "max_forks_repo_head_hexsha": "874882c33a0e8429c74e567eb01525613fee0616", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 11.0, "max_forks_repo_forks_event_min_datetime": "2019-05-02T11:54:31.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-10T14:05:40.000Z", "avg_line_length": 33.1067538126, "max_line_length": 165, "alphanum_fraction": 0.607199263, "num_tokens": 3411, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6619228758499942, "lm_q2_score": 0.5117166047041652, "lm_q1q2_score": 0.33871692660597574}}
{"text": "// --------------------------------------------------------------------------\n//                   OpenMS -- Open-Source Mass Spectrometry\n// --------------------------------------------------------------------------\n// Copyright The OpenMS Team -- Eberhard Karls University Tuebingen,\n// ETH Zurich, and Freie Universitaet Berlin 2002-2015.\n//\n// This software is released under a three-clause BSD license:\n//  * Redistributions of source code must retain the above copyright\n//    notice, this list of conditions and the following disclaimer.\n//  * Redistributions in binary form must reproduce the above copyright\n//    notice, this list of conditions and the following disclaimer in the\n//    documentation and/or other materials provided with the distribution.\n//  * Neither the name of any author or any participating institution\n//    may be used to endorse or promote products derived from this software\n//    without specific prior written permission.\n// For a full list of authors, refer to the file AUTHORS.\n// --------------------------------------------------------------------------\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n// ARE DISCLAIMED. IN NO EVENT SHALL ANY OF THE AUTHORS OR THE CONTRIBUTING\n// INSTITUTIONS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;\n// OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR\n// OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF\n// ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n//\n// --------------------------------------------------------------------------\n// $Maintainer: George Rosenberger $\n// $Authors: George Rosenberger, Hannes Roest $\n// --------------------------------------------------------------------------\n\n#include <OpenMS/MATH/MISC/RANSAC.h>\n#include <OpenMS/MATH/STATISTICS/LinearRegression.h>\n#include <OpenMS/CONCEPT/LogStream.h> // LOG_DEBUG\n\n#include <numeric>\n#include <boost/math/special_functions/erf.hpp>\n#include <algorithm>\n\nnamespace OpenMS\n{\n  std::pair<double, double > Math::RANSAC::llsm_fit_(std::vector<std::pair<double, double> >& pairs)\n  {\n    std::vector<double> x, y;\n\n    for (std::vector<std::pair<double, double> >::iterator it = pairs.begin(); it != pairs.end(); ++it)\n    {\n      x.push_back(it->first);\n      y.push_back(it->second);\n    }\n\n    // GSL implementation\n    //double c0, c1, cov00, cov01, cov11, sumsq;\n    //double* xa = &x[0];\n    //double* ya = &y[0];\n    //gsl_fit_linear(xa, 1, ya, 1, pairs.size(), &c0, &c1, &cov00, &cov01, &cov11, &sumsq);\n\n    // OpenMS::MATH implementation\n    Math::LinearRegression lin_reg;\n    lin_reg.computeRegression(0.95, x.begin(), x.end(), y.begin());\n    double c0, c1;\n    c0 = lin_reg.getIntercept();\n    c1 = lin_reg.getSlope();\n\n    return(std::make_pair(c0,c1));\n  }\n\n  double Math::RANSAC::llsm_rsq(std::vector<std::pair<double, double> >& pairs)\n  {\n    std::vector<double> x, y;\n\n    for (std::vector<std::pair<double, double> >::iterator it = pairs.begin(); it != pairs.end(); ++it)\n    {\n      x.push_back(it->first);\n      y.push_back(it->second);\n    }\n\n    // GSL implementation\n    //double* xa = &x[0];\n    //double* ya = &y[0];\n    //double r = gsl_stats_correlation(xa, 1, ya, 1, pairs.size());\n    //return(r);\n\n    // OpenMS::MATH implementation\n    Math::LinearRegression lin_reg;\n    lin_reg.computeRegression(0.95, x.begin(), x.end(), y.begin());\n\n    return lin_reg.getRSquared();\n  }\n\n  double Math::RANSAC::llsm_rss_(std::vector<std::pair<double, double> >& pairs, std::pair<double, double >& coefficients)\n  {\n    double rss = 0;\n\n    for (std::vector<std::pair<double, double> >::iterator it = pairs.begin(); it != pairs.end(); ++it)\n    {\n      rss += pow(it->second - (coefficients.first + ( coefficients.second * it->first)), 2);\n    }\n\n    return rss;\n  }\n\n  std::vector<std::pair<double, double> > Math::RANSAC::llsm_rss_inliers_(\n      std::vector<std::pair<double, double> >& pairs,\n      std::pair<double, double >& coefficients, double max_threshold)\n  {\n    std::vector<std::pair<double, double> > alsoinliers;\n\n    for (std::vector<std::pair<double, double> >::iterator it = pairs.begin(); it != pairs.end(); ++it)\n    {\n      if (pow(it->second - (coefficients.first + ( coefficients.second * it->first)), 2) < max_threshold)\n      {\n        alsoinliers.push_back(*it);\n      }\n    }\n\n    return alsoinliers;\n  }\n\n  std::vector<std::pair<double, double> > Math::RANSAC::ransac(\n      std::vector<std::pair<double, double> >& pairs, size_t n, size_t k, double t, size_t d, bool test)\n  {\n    // implementation of the RANSAC algorithm according to http://wiki.scipy.org/Cookbook/RANSAC.\n\n    std::vector<std::pair<double, double> > maybeinliers, test_points, alsoinliers, betterdata, bestdata;\n\n    double besterror = std::numeric_limits<double>::max();\n    double bettererror;\n#ifdef DEBUG_MRMRTNORMALIZER\n    std::pair<double, double > bestcoeff;\n    double betterrsq = 0;\n    double bestrsq = 0;\n#endif\n\n    for (size_t ransac_int=0; ransac_int<k; ransac_int++)\n    {\n      std::vector<std::pair<double, double> > pairs_shuffled = pairs;\n\n      if (!test)\n      { // disables random selection in test mode\n        std::random_shuffle(pairs_shuffled.begin(), pairs_shuffled.end());\n      }\n\n      maybeinliers.clear();\n      test_points.clear();\n      std::copy( pairs_shuffled.begin(), pairs_shuffled.begin()+n, std::back_inserter(maybeinliers) );\n      std::copy( pairs_shuffled.begin()+n, pairs_shuffled.end(), std::back_inserter(test_points) );\n\n      std::pair<double, double > coeff = Math::RANSAC::llsm_fit_(maybeinliers);\n\n      alsoinliers = Math::RANSAC::llsm_rss_inliers_(test_points,coeff,t);\n\n      if (alsoinliers.size() > d)\n      {\n        betterdata = maybeinliers;\n        betterdata.insert( betterdata.end(), alsoinliers.begin(), alsoinliers.end() );\n        std::pair<double, double > bettercoeff = Math::RANSAC::llsm_fit_(betterdata);\n        bettererror = Math::RANSAC::llsm_rss_(betterdata,bettercoeff);\n#ifdef DEBUG_MRMRTNORMALIZER\n        betterrsq = Math::RANSAC::llsm_rsq(betterdata);\n#endif\n\n        if (bettererror < besterror)\n        {\n          besterror = bettererror;\n#ifdef DEBUG_MRMRTNORMALIZER\n          bestcoeff = bettercoeff;\n#endif\n          bestdata = betterdata;\n\n#ifdef DEBUG_MRMRTNORMALIZER\n          bestrsq = betterrsq;\n          std::cout << \"RANSAC \" << ransac_int << \": Points: \" << betterdata.size() << \" RSQ: \" << bestrsq << \" Error: \" << besterror << \" c0: \" << bestcoeff.first << \" c1: \" << bestcoeff.second << std::endl;\n#endif\n        }\n      }\n    }\n\n#ifdef DEBUG_MRMRTNORMALIZER\n    std::cout << \"=======STARTPOINTS=======\" << std::endl;\n    for (std::vector<std::pair<double, double> >::iterator it = bestdata.begin(); it != bestdata.end(); ++it)\n    {\n      std::cout << it->first << \"\\t\" << it->second << std::endl;\n    }\n    std::cout << \"=======ENDPOINTS=======\" << std::endl;\n#endif\n\n    return(bestdata);\n  }\n\n}\n", "meta": {"hexsha": "253e494c5fba70f3b64357242bd8acd26be3e66b", "size": 7334, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/openms/source/MATH/MISC/RANSAC.cpp", "max_stars_repo_name": "tomas-pluskal/openms", "max_stars_repo_head_hexsha": "136ec9057435f6d45d65a8e1465b2a6cff9621a8", "max_stars_repo_licenses": ["Zlib", "Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/openms/source/MATH/MISC/RANSAC.cpp", "max_issues_repo_name": "tomas-pluskal/openms", "max_issues_repo_head_hexsha": "136ec9057435f6d45d65a8e1465b2a6cff9621a8", "max_issues_repo_licenses": ["Zlib", "Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/openms/source/MATH/MISC/RANSAC.cpp", "max_forks_repo_name": "tomas-pluskal/openms", "max_forks_repo_head_hexsha": "136ec9057435f6d45d65a8e1465b2a6cff9621a8", "max_forks_repo_licenses": ["Zlib", "Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.6102564103, "max_line_length": 208, "alphanum_fraction": 0.6229888192, "num_tokens": 1859, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6619228625116081, "lm_q2_score": 0.5117166047041654, "lm_q1q2_score": 0.33871691978050217}}
{"text": "#pragma once\n\n#include <iostream>\n#include <stdexcept>\n#include <vector>\n\n#include <Eigen/Core>\n#include <Eigen/Eigenvalues>\n#include <Eigen/StdVector>\n\n#ifdef __SRRG_PARALLEL_KDTREE__\n#include <omp.h>\n#endif\n\nnamespace srrg2_core {\n\n  /**\n     KDTree: implements a KDTree, it requires a type T\n     and a dimension D\n  */\n  template <class T, size_t D>\n  class KDTree {\n  public:\n    EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n    // typedef for defining a vector variable sized points\n    using VectorTD       = Eigen::Matrix<T, D, 1>;\n    using VectorTDVector = std::vector<VectorTD, Eigen::aligned_allocator<VectorTD>>;\n    enum NodeType { Leaf = 0x0, Middle = 0x1 };\n\n    /**\n       TreeNode class. Represents a base class for a node in the search tree.\n\n       if the type is a Middle node\n       it represents a splitting plane, and has 2 child nodes\n       that refer to the set of points to the two sides of the splitting plane.\n       A splitting plane is parameterized as a point on a plane and as a normal\n       to the plane.\n\n       If the type is a leaf\n       it represents a bucket containing points in a neighborhood\n       To avoid copies, the bucket is kept as a range\n       _min_index.._max_indexindices and the points\n       in the _points and _indices\n    */\n    class TreeNode {\n    public:\n      friend class KDTree;\n      //! ctor\n      EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n\n      TreeNode(KDTree<T, D>* tree_, int node_num = 0) :\n        _tree(tree_),\n        _node_num(node_num),\n        _node_type(KDTree<T, D>::Leaf) {\n        _mean.setZero();\n        _normal.setZero();\n        _left_child  = 0;\n        _right_child = 0;\n        _min_index   = -1;\n        _max_index   = -1;\n        _num_points  = 0;\n      }\n\n      TreeNode(KDTree<T, D>* tree_,\n               int node_num,\n               const VectorTD& mean_,\n               const VectorTD& normal_,\n               TreeNode* left_child  = 0,\n               TreeNode* right_child = 0) :\n        _tree(tree_),\n        _node_num(node_num),\n        _node_type(KDTree<T, D>::Middle) {\n        _min_index = _max_index = -1;\n        assert(normal_.rows() == D);\n        assert(mean_.rows() == D);\n        _normal      = normal_;\n        _mean        = mean_;\n        _num_points  = 0;\n        _left_child  = left_child;\n        _right_child = right_child;\n        if (_left_child) {\n          _num_points += _left_child->numPoints();\n        }\n        if (_right_child) {\n          _num_points += _right_child->numPoints();\n        }\n      }\n\n      //! dtor\n      ~TreeNode() {\n        if (_left_child) {\n          delete _left_child;\n          _left_child = 0;\n        }\n        if (_right_child) {\n          delete _right_child;\n          _right_child = 0;\n        }\n      }\n\n      //! function to search for the neighbor\n      //! @param answer: the neighbor found\n      //! @param query: the point to search\n      //! @param maximum distance allowed for a point\n      //! @returns the distance of the closest point. -1 if no point found\n      //! within range\n      T findNeighbor(VectorTD& answer,\n                     int& index,\n                     const VectorTD& query,\n                     const T max_distance) const {\n        switch (_node_type) {\n          case KDTree<T, D>::Leaf: {\n            T d_max                         = std::numeric_limits<T>::max();\n            const VectorTDVector& points    = this->_tree->_points;\n            const std::vector<int>& indices = this->_tree->_indices;\n            for (size_t i = _min_index; i < _max_index; ++i) {\n              T d = (points[i] - query).squaredNorm();\n              if (d < d_max) {\n                answer = points[i];\n                index  = indices[i];\n                d_max  = d;\n              }\n            }\n\n            if (d_max > max_distance * max_distance) {\n              index = -1;\n              return -1;\n            }\n            return d_max;\n          }\n\n          case KDTree<T, D>::Middle: {\n            bool is_left    = side(query);\n            TreeNode* child = is_left ? _left_child : _right_child;\n            if (child) {\n              if (child->_node_type != KDTree<T, D>::Middle &&\n                  child->_node_type != KDTree<T, D>::Leaf) {\n                std::cerr << \"KDTree::findNeighbor|ERROR, calling sanity check (\" << _tree << \")\\n\";\n                std::cerr << \"KDTree::findNeighbor|good queries\" << _tree->good_queries\n                          << std::endl;\n                std::cerr << \"KDTree::findNeighbor|result: \" << _tree->sanityCheck() << std::endl;\n              }\n              return child->findNeighbor(answer, index, query, max_distance);\n            }\n          }\n            return -1;\n          default:\n            std::cerr << \"KDTree::findNeighbor|ERROR, sanity check (\" << _tree\n                      << \") : \" << _tree->sanityCheck() << std::endl;\n            throw std::runtime_error(\"KDTree::findNeighbor|ERROR, unknown node type\");\n        }\n      }\n\n      //! function to search for all the points near to the query point\n      //! @param answer: the neighbors found\n      //! @param query: the point to search\n      //! @param maximum distance allowed for a point\n      //! @returns void\n      void findNeighbors(VectorTDVector& answers,\n                         std::vector<int>& indices,\n                         const VectorTD& query,\n                         const T maximum_squared_distance) const {\n        assert(maximum_squared_distance >= 0);\n        switch (_node_type) {\n          case KDTree<T, D>::Leaf: {\n            // ds return all points in this leaf that satisfy the distance\n            assert(_max_index >= _min_index);\n            const size_t number_of_points = _max_index - _min_index;\n            answers.clear();\n            answers.reserve(number_of_points);\n            indices.clear();\n            indices.reserve(number_of_points);\n            for (size_t i = _min_index; i < _max_index; ++i) {\n              assert(i < _tree->_points.size());\n              const T distance = (_tree->_points[i] - query).squaredNorm();\n              if (distance < maximum_squared_distance) {\n                answers.emplace_back(_tree->_points[i]);\n                indices.emplace_back(_tree->_indices[i]);\n              }\n            }\n            return;\n          }\n\n          case KDTree<T, D>::Middle: {\n            bool is_left    = side(query);\n            TreeNode* child = is_left ? _left_child : _right_child;\n            if (child) {\n              if (child->_node_type != KDTree<T, D>::Middle &&\n                  child->_node_type != KDTree<T, D>::Leaf) {\n                std::cerr << \"KDTree::findNeighbors|ERROR, calling sanity check (\" << _tree << \")\"\n                          << std::endl;\n                std::cerr << \"KDTree::findNeighbors|good queries\" << _tree->good_queries\n                          << std::endl;\n                std::cerr << \"KDTree::findNeighbors|result: \" << _tree->sanityCheck() << std::endl;\n              }\n              child->findNeighbors(answers, indices, query, maximum_squared_distance);\n              return;\n            }\n          }\n            return;\n\n          default:\n            std::cerr << \"KDTree::findNeighbors|ERROR, sanity check (\" << _tree\n                      << \") : \" << _tree->sanityCheck() << std::endl;\n            throw std::runtime_error(\"KDTree::findNeighbors|ERROR, unknown node type\");\n        }\n      }\n\n      size_t numPoints() const {\n        return _num_points;\n      }\n\n      size_t minIndex() const {\n        return _min_index;\n      }\n\n      size_t maxIndex() const {\n        return _max_index;\n      }\n\n      inline void setMinIndex(size_t min_index) {\n        _min_index = min_index;\n      }\n\n      inline void setMaxIndex(size_t max_index) {\n        _max_index = max_index;\n      }\n\n      //! mean const accessor\n      inline const VectorTD& mean() const {\n        return _mean;\n      }\n\n      //! normal const accessor\n      inline const VectorTD& normal() const {\n        return _normal;\n      }\n\n      //! mean left accessor\n      inline TreeNode* leftChild() const {\n        return _left_child;\n      }\n\n      //! mean right accessor\n      inline TreeNode* rightChild() const {\n        return _right_child;\n      }\n\n      inline bool side(const VectorTD& query_point) const {\n        return _normal.dot(query_point - _mean) < 0;\n      }\n\n    protected:\n      KDTree<T, D>* _tree;\n      int _node_num;\n      const KDTree<T, D>::NodeType _node_type;\n      size_t _min_index;\n      size_t _max_index;\n      VectorTD _normal;\n      VectorTD _mean;\n      size_t _num_points;\n      TreeNode* _left_child;\n      TreeNode* _right_child;\n    };\n\n    //! ctor\n    KDTree(const VectorTDVector& points_, T max_leaf_range, size_t min_leaf_points = 20) {\n      good_queries = 0;\n      _num_nodes   = 0;\n      _points      = points_;\n      _aux_points  = points_;\n      _indices.resize(points_.size());\n      _aux_indices.resize(points_.size());\n      _min_leaf_points = min_leaf_points;\n      for (size_t i = 0; i < _indices.size(); ++i) {\n        _indices[i] = i;\n      }\n      _root = _buildTree(0, points_.size(), max_leaf_range, 0);\n    }\n\n    //! dtor\n    ~KDTree() {\n      if (_root) {\n        delete _root;\n      }\n      _root = 0;\n    }\n\n    bool sanityCheck() const {\n      std::vector<int> checked_indices(_points.size());\n      std::fill(checked_indices.begin(), checked_indices.end(), -1);\n      const size_t k = sanityCheck(checked_indices, 0, _root);\n      if (k != _points.size()) {\n        throw std::runtime_error(\"KDTree::sanityCheck(void)|ERROR, illegal size reported\");\n      }\n      std::sort(checked_indices.begin(), checked_indices.end(), std::less<int>());\n      for (size_t i = 0; i < checked_indices.size(); i++) {\n        if (i != static_cast<size_t>(checked_indices[i])) {\n          throw std::runtime_error(\"KDTree::sanityCheck(void)|ERROR, missing indices\");\n        }\n      }\n      return true;\n    }\n\n    int sanityCheck(std::vector<int>& checked_indices, int k, const TreeNode* node) const {\n      if (!node) {\n        return k;\n      }\n      switch (node->_node_type) {\n        case KDTree<T, D>::Leaf:\n          for (size_t i = node->_min_index; i < node->_max_index; i++) {\n            int idx = _indices[i];\n            if (checked_indices[k] != -1) {\n              throw std::runtime_error(\"KDTree::sanityCheck|ERROR, writing on an occupied index\");\n            }\n            checked_indices[k] = idx;\n            k++;\n          }\n          return k;\n        case KDTree<T, D>::Middle:\n          k = sanityCheck(checked_indices, k, node->_left_child);\n          k = sanityCheck(checked_indices, k, node->_right_child);\n          return k;\n        default:\n          throw std::runtime_error(\"KDTree::sanityCheck|ERROR, illegal type index\");\n      }\n    }\n\n    //! num_nodes accessor\n    inline size_t numNodes() const {\n      return _num_nodes;\n    }\n\n    inline size_t numPoints() const {\n      return _points.size();\n    }\n\n    //! function to search for the neighbor\n    //! @param answer: the neighbor found\n    //! @param query: the point to search\n    //! @param maximum distance allowed for a point\n    //! @returns the distance of the closest point. -1 if no point found within\n    //! range\n    inline T\n    findNeighbor(VectorTD& answer, int& index, const VectorTD& query, const T max_distance) const {\n      if (!_root) {\n        throw std::runtime_error(\"KDTree::findNeighbor|ERROR, no root node\");\n      }\n      good_queries++;\n      return _root->findNeighbor(answer, index, query, max_distance);\n    }\n\n    //! function to search for all the points in the same leaf of the query\n    //! point\n    //! @param answers: the neighbors found\n    //! @param indices: the indices of the neighbors found\n    //! @param query: the query point\n    //! @param max_distance: maximum distance allowed for a point\n    //! @returns void\n\n    inline void findNeighbors(VectorTDVector& answers,\n                              std::vector<int>& indices,\n                              const VectorTD& query,\n                              const T max_distance) const {\n      if (!_root) {\n        throw std::runtime_error(\"KDTree::findNeighbors|ERROR, no root node\");\n      }\n\n      good_queries++;\n      _root->findNeighbors(answers, indices, query, max_distance);\n    }\n\n    inline void printKDTree() {\n      _printKDTree(_root);\n    }\n\n    mutable int good_queries;\n\n  protected:\n    /**\n       Partitions a point vector in two vectors, computing the splitting plane\n       as the largest eigenvalue of the point covariance\n       @param mean: the returned mean of the splitting plane\n       @param normal: the normal of the splitting plane\n       @param left: the returned left vector of points\n       @param right: the returned right vector of points\n       @param points: the array of points\n       @returns the distance of the farthest point from the plane\n    */\n    T _splitPoints(VectorTD& mean,\n                   VectorTD& normal,\n                   size_t& num_left_points,\n                   const size_t min_index,\n                   const size_t max_index) {\n      // if points empty, nothing to do\n      if (min_index == max_index) {\n        return 0;\n      }\n\n      const size_t num_points            = max_index - min_index;\n      const T inverse_num_points         = 1.0 / num_points;\n      VectorTD sum                       = VectorTD::Zero();\n      Eigen::Matrix<T, D, D> squared_sum = Eigen::Matrix<T, D, D>::Zero();\n      Eigen::Matrix<T, D, D> covariance  = Eigen::Matrix<T, D, D>::Zero();\n      for (size_t i = min_index; i < max_index; ++i) {\n        sum += _points[i];\n        squared_sum += _points[i] * _points[i].transpose();\n      }\n      mean       = sum * inverse_num_points;\n      covariance = squared_sum * inverse_num_points - mean * mean.transpose();\n\n      // eigenvalue decomposition\n      Eigen::SelfAdjointEigenSolver<Eigen::Matrix<T, D, D>> solver;\n      solver.compute(covariance, Eigen::ComputeEigenvectors);\n      normal = solver.eigenvectors().col(D - 1).normalized();\n\n      // the following var will contain the range of points along the normal\n      // vector\n      T max_distance_from_plane = 0;\n\n      // run through the points and split them in the left or the right set\n      size_t left_index  = min_index;\n      size_t right_index = max_index;\n\n      size_t num_left  = 0;\n      size_t num_right = 0;\n      for (size_t i = min_index; i < max_index; ++i) {\n        T distance_from_plane = normal.dot(_points[i] - mean);\n        if (fabs(distance_from_plane) > max_distance_from_plane) {\n          max_distance_from_plane = fabs(distance_from_plane);\n        }\n\n        bool side = distance_from_plane < 0;\n        if (side) {\n          _aux_points[left_index]  = _points[i];\n          _aux_indices[left_index] = _indices[i];\n          left_index++;\n          num_left++;\n        } else {\n          right_index--;\n          _aux_points[right_index]  = _points[i];\n          _aux_indices[right_index] = _indices[i];\n          num_right++;\n        }\n      }\n      assert(max_index - min_index == num_right + num_left);\n      for (size_t i = min_index; i < max_index; ++i) {\n        _points[i]  = _aux_points[i];\n        _indices[i] = _aux_indices[i];\n      }\n\n      num_left_points = num_left;\n      return max_distance_from_plane;\n    }\n\n    //! function to build the tree\n    //! @param points: the points\n    //! @param max_leaf_range: specify the size of the \"box\" below which a leaf\n    //! node is generated returns the root of the search tree\n    TreeNode*\n    _buildTree(const size_t min_index, const size_t max_index, const T max_leaf_range, int level) {\n      const size_t num_points = max_index - min_index;\n      if (!num_points) {\n        return 0;\n      }\n\n      VectorTD mean;\n      VectorTD normal;\n      size_t num_left_points = 0;\n\n      const T range = _splitPoints(mean, normal, num_left_points, min_index, max_index);\n      assert(range >= 0);\n\n      TreeNode* node = 0;\n      if (range < max_leaf_range || num_points < _min_leaf_points) {\n        node = new TreeNode(this, _num_nodes);\n        node->setMinIndex(min_index);\n        node->setMaxIndex(max_index);\n        node->_num_points = num_points;\n      } else {\n        TreeNode *left_tree, *right_tree;\n\n#ifdef __SRRG_PARALLEL_KDTREE__\n        int num_threads = omp_get_max_threads();\n        int split_level = -1;\n        if (level > 0)\n          split_level = floor(log(num_threads) / log(2));\n\n        if (split_level == level) {\n#pragma omp parallel sections\n          {\n#pragma omp section\n            {\n              left_tree =\n                _buildTree(min_index, min_index + num_left_points, max_leaf_range, level + 1);\n            }\n#pragma omp section\n            {\n              right_tree =\n                _buildTree(min_index + num_left_points, max_index, max_leaf_range, level + 1);\n            }\n          }\n        } else {\n#endif //__SRRG_PARALLEL_KDTREE__\n\n          left_tree = _buildTree(min_index, min_index + num_left_points, max_leaf_range, level + 1);\n          right_tree =\n            _buildTree(min_index + num_left_points, max_index, max_leaf_range, level + 1);\n#ifdef __SRRG_PARALLEL_KDTREE__\n        }\n#endif\n        node = new TreeNode(this, _num_nodes, mean, normal, left_tree, right_tree);\n      }\n      _num_nodes++;\n      return node;\n    }\n\n    void _printKDTree(TreeNode* node) {\n      switch (node->_node_type) {\n        case KDTree<T, D>::Leaf:\n          std::cerr << \"Leaf: \" << std::endl;\n          for (size_t i = node->_min_index; i < node->_max_index; ++i) {\n            std::cerr << _points[i].transpose() << std::endl;\n          }\n          std::cerr << std::endl;\n          break;\n        case KDTree<T, D>::Middle:\n          _printKDTree(node->leftChild());\n          _printKDTree(node->rightChild());\n          break;\n      }\n    }\n\n    size_t _num_nodes;\n    size_t _min_leaf_points;\n    TreeNode* _root;\n    VectorTDVector _aux_points;\n    VectorTDVector _points;\n    std::vector<int> _indices;\n    std::vector<int> _aux_indices;\n  };\n\n} // namespace srrg2_core\n", "meta": {"hexsha": "5454f06e522a787fe2e5f7ad59c04ef8a5273326", "size": 18083, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "srrg2_core/src/srrg_data_structures/kd_tree.hpp", "max_stars_repo_name": "srrg-sapienza/srrg2_core", "max_stars_repo_head_hexsha": "56c1f8305f2a9918b7e7c581d83d394ffb7ea50e", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2020-03-11T14:36:13.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-09T09:01:15.000Z", "max_issues_repo_path": "srrg2_core/src/srrg_data_structures/kd_tree.hpp", "max_issues_repo_name": "srrg-sapienza/srrg2_core", "max_issues_repo_head_hexsha": "56c1f8305f2a9918b7e7c581d83d394ffb7ea50e", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-06-07T17:25:04.000Z", "max_issues_repo_issues_event_max_datetime": "2020-07-15T07:36:10.000Z", "max_forks_repo_path": "srrg2_core/src/srrg_data_structures/kd_tree.hpp", "max_forks_repo_name": "srrg-sapienza/srrg2_core", "max_forks_repo_head_hexsha": "56c1f8305f2a9918b7e7c581d83d394ffb7ea50e", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-11-30T08:17:53.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-19T05:07:07.000Z", "avg_line_length": 33.2408088235, "max_line_length": 100, "alphanum_fraction": 0.564950506, "num_tokens": 4309, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6825737473266735, "lm_q2_score": 0.4960938294709195, "lm_q1q2_score": 0.3386206242076053}}
{"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\nstruct Transform {\n\tll e00;\n\tll e01;\n\tll e10;\n\tll e11;\n};\n\nTransform dot(Transform a, Transform b) {\n\tTransform ret = {a.e00 * b.e00 + a.e01 * b.e10,\n\t\t\t\t\t a.e00 * b.e01 + a.e01 * b.e11,\n\t\t\t\t\t a.e10 * b.e00 + a.e11 * b.e10,\n\t\t\t\t\t a.e10 * b.e01 + a.e11 * b.e11};\n\treturn ret;\n}\n\npair<ll, ll> dot(Transform a, pair<ll, ll> b) {\n\tpair<ll, ll> ret = {b.first * a.e00 + b.second * a.e01,\n\t\t\t\t\t\tb.first * a.e10 + b.second * a.e11};\n\treturn ret;\n}\n\npair<ll, ll> sum(pair<ll, ll> a, pair<ll, ll> b) {\n\treturn make_pair(a.first + b.first, a.second + b.second);\n}\n\nint main() {\n\tint n;\n\tcin >> n;\n\tVLL x(n), y(n);\n\tREP(i, n) { cin >> x[i] >> y[i]; }\n\tint m;\n\tcin >> m;\n\tVI op(m), p(m);\n\tREP(i, m) {\n\t\tcin >> op[i];\n\t\tif(op[i] > 2) {\n\t\t\tcin >> p[i];\n\t\t}\n\t}\n\tint q;\n\tcin >> q;\n\tVI a(q), b(q);\n\tREP(i, q) { cin >> a[i] >> b[i]; }\n\n\tvector<Transform> transforms(m + 1, {1, 0, 0, 1});\n\tvector<pair<ll, ll>> linear(m + 1, {0, 0});\n\tTransform clockwise_rotate = {0, 1, -1, 0};\n\tTransform counter_clockwise_rotate = {0, -1, 1, 0};\n\tREP(i, m) {\n\t\tif(op[i] == 1) {\n\t\t\ttransforms[i + 1] = dot(clockwise_rotate, transforms[i]);\n\t\t\tlinear[i + 1] = dot(clockwise_rotate, linear[i]);\n\t\t} else if(op[i] == 2) {\n\t\t\ttransforms[i + 1] = dot(counter_clockwise_rotate, transforms[i]);\n\t\t\tlinear[i + 1] = dot(counter_clockwise_rotate, linear[i]);\n\t\t} else if(op[i] == 3) {\n\t\t\ttransforms[i + 1] = dot(Transform({-1, 0, 0, 1}), transforms[i]);\n\t\t\tlinear[i + 1] = sum(dot(Transform({-1, 0, 0, 1}), linear[i]),\n\t\t\t\t\t\t\t\tmake_pair(p[i] * 2, 0));\n\t\t} else {\n\t\t\ttransforms[i + 1] = dot(Transform({1, 0, 0, -1}), transforms[i]);\n\t\t\tlinear[i + 1] = sum(dot(Transform({1, 0, 0, -1}), linear[i]),\n\t\t\t\t\t\t\t\tmake_pair(0, p[i] * 2));\n\t\t}\n\t}\n\n\tREP(i, q) {\n\t\tpair<ll, ll> point = make_pair(x[b[i] - 1], y[b[i] - 1]);\n\t\tauto result = sum(dot(transforms[a[i]], point), linear[a[i]]);\n\t\tcout << result.first << \" \" << result.second << endl;\n\t}\n\treturn 0;\n}\n", "meta": {"hexsha": "9a14053b671d77e7c7e23bc73709bbc6272432bf", "size": 4508, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "AtCoder/ABC189/E.cpp", "max_stars_repo_name": "arlechann/atcoder", "max_stars_repo_head_hexsha": "1af08efa6d3a0e8c75e4eaf13e1eda994820b9e2", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "AtCoder/ABC189/E.cpp", "max_issues_repo_name": "arlechann/atcoder", "max_issues_repo_head_hexsha": "1af08efa6d3a0e8c75e4eaf13e1eda994820b9e2", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "AtCoder/ABC189/E.cpp", "max_forks_repo_name": "arlechann/atcoder", "max_forks_repo_head_hexsha": "1af08efa6d3a0e8c75e4eaf13e1eda994820b9e2", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.6338797814, "max_line_length": 76, "alphanum_fraction": 0.60581189, "num_tokens": 1514, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6825737214979746, "lm_q2_score": 0.4960938294709195, "lm_q1q2_score": 0.3386206113941471}}
{"text": "/*Copyright (c) 2020 James Gayvert\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n*/\n\n/*\n * AOCAP.cpp\n */\n#include \"BasisSet.h\"\n#include <numgrid.h>\n#include \"utils.h\"\n#include \"gto_ordering.h\"\n#include \"AOCAP.h\"\n#include <chrono>\n#include <ctime>\n#include <thread>\n#include <math.h>\n#include <vector>\n#include <iostream>\n#include \"opencap_exception.h\"\n#include <Eigen/Dense>\n\nAOCAP::AOCAP(std::vector<Atom> geometry,std::map<std::string, std::string> params)\n{\n\tverify_cap_parameters(params);\n\tdouble capx,capy,capz,rcut,radial,angpts;\n\tstd::stringstream capxss(params[\"cap_x\"]);\n\tstd::stringstream capyss(params[\"cap_y\"]);\n\tstd::stringstream capzss(params[\"cap_z\"]);\n\tstd::stringstream rcutss(params[\"r_cut\"]);\n\tstd::stringstream radialss(params[\"radial_precision\"]);\n\tstd::stringstream angularss(params[\"angular_points\"]);\n\tcapxss >> capx;\n\tcapyss >> capy;\n\tcapzss >> capz;\n\trcutss >> rcut;\n\tradialss >> radial;\n\tangularss >> angpts;\n\t//now fill class members\n\tcap_type = params[\"cap_type\"];\n\tcap_x = capx;\n\tcap_y= capy;\n\tcap_z = capz;\n\tr_cut = rcut;\n\tradial_precision = pow(10,-1.0*radial);\n\tangular_points = angpts;\n\tatoms = geometry;\n}\n\ndouble AOCAP::eval_voronoi_cap(double x, double y, double z)\n{\n    double atom_distances[atoms.size()];\n    double r_closest=1000.0;\n    //find r closest and fill up our distances array\n    for(size_t j=0;j<atoms.size();j++)\n    {\n        if(atoms[j].Z!=0)\n        {\n\t\t\t  double dist_x= (x-atoms[j].coords[0]) * (x-atoms[j].coords[0]);\n\t\t\t  double dist_y= (y-atoms[j].coords[1]) * (y-atoms[j].coords[1]);\n\t\t\t  double dist_z= (z-atoms[j].coords[2]) * (z-atoms[j].coords[2]);\n\t\t\t  double dist=sqrt(dist_x+dist_y+dist_z);\n\t\t\t  if(dist<r_closest)\n\t\t\t\t r_closest=dist;\n\t\t\t  atom_distances[j]=dist;\n        }\n    }\n    double weights[atoms.size()];\n    for(size_t j=0;j<atoms.size();j++)\n    {\n  \t  if(atoms[j].Z!=0)\n  \t\t  weights[j]=1/pow((pow(atom_distances[j],2.0)-pow(r_closest,2.0) +1),2.0);\n  \t  else\n  \t\t  weights[j]=0;\n    }\n    double numerator=0.0;\n    double denominator=0.0;\n    for(size_t j=0;j<atoms.size();j++)\n    {\n  \t  numerator+=atom_distances[j]*atom_distances[j]*weights[j];\n  \t  denominator+=weights[j];\n    }\n    double r=sqrt(numerator/denominator);\n    if(r<r_cut)\n  \t  return 0;\n    else\n  \t  return (r-r_cut)*(r-r_cut);\n}\n\ndouble AOCAP::eval_box_cap(double x, double y, double z)\n{\n    double result = 0;\n    if(abs(x)>cap_x)\n\t result += (abs(x)-cap_x) * (abs(x)-cap_x);\n    if(abs(y)>cap_y)\n   \t result += (abs(y)-cap_y) * (abs(y)-cap_y);\n    if(abs(z)>cap_z)\n   \t result += (abs(z)-cap_z) * (abs(z)-cap_z);\n    return result;\n}\n\ndouble AOCAP::eval_pot(double x, double y, double z)\n{\n\tif(compare_strings(cap_type, \"box\"))\n\t\treturn eval_box_cap(x,y,z);\n\telse if (compare_strings(cap_type,\"voronoi\"))\n\t\treturn eval_voronoi_cap(x,y,z);\n\treturn 0;\n}\n\nvoid AOCAP::compute_ao_cap_mat(Eigen::MatrixXd &cap_mat, BasisSet bs)\n{\n\tdouble x_coords_bohr[atoms.size()];\n\tdouble y_coords_bohr[atoms.size()];\n\tdouble z_coords_bohr[atoms.size()];\n\tint nuc_charges[atoms.size()];\n\tfor(size_t i=0;i<atoms.size();i++)\n\t{\n\t\tx_coords_bohr[i]=atoms[i].coords[0];\n\t\ty_coords_bohr[i]=atoms[i].coords[1];\n\t\tz_coords_bohr[i]=atoms[i].coords[2];\n\t\tnuc_charges[i]=atoms[i].Z;\n\t\tif (atoms[i].Z==0)\n\t\t\tnuc_charges[i]=1; //choose bragg radius for H for ghost atoms\n\t}\n    //double radial_precision = radial_precision;\n    int min_num_angular_points = angular_points;\n    int max_num_angular_points = angular_points;\n\tfor(size_t i=0;i<atoms.size();i++)\n\t{\n\t\t//allocate and create grid\n\t\tcontext_t *context = numgrid_new_atom_grid(radial_precision,\n\t\t                                 min_num_angular_points,\n\t\t                                 max_num_angular_points,\n\t\t                                 nuc_charges[i],\n\t\t                                 bs.alpha_max(atoms[i]),\n\t\t                                 bs.max_L(),\n\t\t                                 &bs.alpha_min(atoms[i])[0]);\n\t\tint num_points = numgrid_get_num_grid_points(context);\n        double *grid_x_bohr = new double[num_points];\n        double *grid_y_bohr = new double[num_points];\n        double *grid_z_bohr = new double[num_points];\n        double *grid_w = new double[num_points];\n        numgrid_get_grid(  context,\n                           atoms.size(),\n                           i,\n                           x_coords_bohr,\n                           y_coords_bohr,\n                           z_coords_bohr,\n                           nuc_charges,\n                           grid_x_bohr,\n                           grid_y_bohr,\n                           grid_z_bohr,\n                           grid_w);\n\t\tevaluate_grid_on_atom(cap_mat,bs,grid_x_bohr,grid_y_bohr,grid_z_bohr,grid_w,num_points);\n\t}\n}\n\nvoid AOCAP::evaluate_grid_on_atom(Eigen::MatrixXd &cap_mat,BasisSet bs,double* grid_x_bohr,\n\t\tdouble *grid_y_bohr,double *grid_z_bohr,double *grid_w,int num_points)\n{\n\t//pre-calculate cap matrix on grid\n\tstd::vector<float> cap_values (num_points);\n\t#pragma omp parallel for\n\tfor (int i=0;i<num_points;i++)\n\t\tcap_values[i]= eval_pot(grid_x_bohr[i],grid_y_bohr[i],grid_z_bohr[i]);\n\tstd::vector<std::vector<float>> bf_values;\n\t//pre-calculate basis functions on grid\n\tfor(size_t i=0;i<bs.basis.size();i++)\n\t{\n\t\tShell my_shell = bs.basis[i];\n\t\tstd::vector<std::array<size_t,3>> order = opencap_carts_ordering(my_shell.l);\n\t\tfor(size_t j=0;j<my_shell.num_carts();j++)\n\t\t{\n\t\t\tstd::vector<float> vec(num_points);\n\t\t\tstd::array<size_t,3> cart = order[j];\n\t\t\t#pragma omp parallel for\n\t\t\tfor (int k=0;k<num_points;k++)\n\t\t\t\tvec[k]= my_shell.evaluate(grid_x_bohr[k],grid_y_bohr[k],grid_z_bohr[k],cart[0],cart[1],cart[2]);\n\t\t\tbf_values.push_back(vec);\n\t\t}\n\t}\n    //now lets evaluate\n\tfor (size_t i=0;i<bs.num_carts();i++)\n\t{\n\t\tfor(size_t j=i;j<bs.num_carts();j++)\n\t\t{\n\t\t\tfor(int k=0;k<num_points;k++)\n\t\t\t{\n\t\t\t\tcap_mat(i,j)+=grid_w[k]*cap_values[k]*bf_values[i][k]*bf_values[j][k];\n\t\t\t\tif (j!=i)\n\t\t\t\t\tcap_mat(j,i)+=grid_w[k]*cap_values[k]*bf_values[i][k]*bf_values[j][k];\n\t\t\t}\n\t\t}\n\t}\n}\n\nvoid AOCAP::verify_cap_parameters(std::map<std::string,std::string> &parameters)\n{\n\tstd::vector<std::string> missing_keys;\n\tif(parameters.find(\"cap_type\")==parameters.end())\n\t\topencap_throw(\"Error: Missing cap_type keyword.\");\n\tif(compare_strings(parameters[\"cap_type\"],\"box\"))\n\t{\n\t\tif(parameters.find(\"cap_x\")==parameters.end())\n\t\t\tmissing_keys.push_back(\"cap_x\");\n\t\tif(parameters.find(\"cap_y\")==parameters.end())\n\t\t\tmissing_keys.push_back(\"cap_y\");\n\t\tif (parameters.find(\"cap_z\")==parameters.end())\n\t\t\tmissing_keys.push_back(\"cap_z\");\n\t}\n\telse if (compare_strings(parameters[\"cap_type\"],\"voronoi\"))\n\t{\n\t\tif(parameters.find(\"r_cut\")==parameters.end())\n\t\t\tmissing_keys.push_back(\"r_cut\");\n\t}\n\telse\n\t\topencap_throw(\"Error: only box and voronoi CAPs supported.\");\n\tif(missing_keys.size()!=0)\n\t{\n\t\tstd::string error_str = \"Missing CAP keywords: \";\n\t\tfor (auto key: missing_keys)\n\t\t\terror_str+=key+\" \";\n\t\topencap_throw(error_str);\n\t}\n\tstd::map<std::string, std::string> defaults = {{\"radial_precision\", \"14\"}, {\"angular_points\", \"590\"}};\n\tfor (const auto &pair:defaults)\n\t{\n\t\tif(parameters.find(pair.first)==parameters.end())\n\t\t\tparameters[pair.first]=pair.second;\n\t}\n}\n\n", "meta": {"hexsha": "7ae5a794ad2161106f081cd962be3a1357ee09b1", "size": 8131, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "opencap/src/AOCAP.cpp", "max_stars_repo_name": "trex47/opencap", "max_stars_repo_head_hexsha": "fd641133b2abaab22c13912d97fe1fe64b132dd7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "opencap/src/AOCAP.cpp", "max_issues_repo_name": "trex47/opencap", "max_issues_repo_head_hexsha": "fd641133b2abaab22c13912d97fe1fe64b132dd7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "opencap/src/AOCAP.cpp", "max_forks_repo_name": "trex47/opencap", "max_forks_repo_head_hexsha": "fd641133b2abaab22c13912d97fe1fe64b132dd7", "max_forks_repo_licenses": ["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.524, "max_line_length": 103, "alphanum_fraction": 0.6549009962, "num_tokens": 2239, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.727975460709318, "lm_q2_score": 0.46490157137338844, "lm_q1q2_score": 0.3384369356050283}}
{"text": "#include <iostream>\n#include <cstdlib>\n#include <cmath>\n#include <boost/pending/disjoint_sets.hpp>\n#include <vector>\n#include <queue>\n#include <map>\nusing namespace std;\n\ntemplate <class T>\nclass AffinityGraphCompare{\n\tprivate:\n\t    const T * mEdgeWeightArray;\n\tpublic:\n\t\tAffinityGraphCompare(const T * EdgeWeightArray){\n\t\t\tmEdgeWeightArray = EdgeWeightArray;\n\t\t}\n\t\tbool operator() (const int& ind1, const int& ind2) const {\n\t\t\treturn (mEdgeWeightArray[ind1] > mEdgeWeightArray[ind2]);\n\t\t}\n};\n\n/*\n * Compute the MALIS loss function and its derivative wrt the affinity graph\n * MAXIMUM spanning tree\n * Author: Srini Turaga (sturaga@mit.edu)\n * All rights reserved\n */\nvoid malis_loss_weights_cpp(const int nVert, const int* seg,\n               const int nEdge, const int* node1, const int* node2, const float* edgeWeight,\n               const int pos,\n               int* nPairPerEdge){\n\n\n    /* Disjoint sets and sparse overlap vectors */\n    vector<map<int,int> > overlap(nVert);\n    vector<int> rank(nVert);\n    vector<int> parent(nVert);\n    boost::disjoint_sets<int*, int*> dsets(&rank[0],&parent[0]);\n    for (int i=0; i<nVert; ++i){\n        dsets.make_set(i);\n        if (0!=seg[i]) {\n            overlap[i].insert(pair<int,int>(seg[i],1));\n        }\n    }\n\n    /* Sort all the edges in increasing order of weight */\n    std::vector< int > pqueue( nEdge );\n    int j = 0;\n    for ( int i = 0; i < nEdge; i++ ){\n        if ((node1[i]>=0) && (node1[i]<nVert) && (node2[i]>=0) && (node2[i]<nVert))\n\t        pqueue[ j++ ] = i;\n    }\n    unsigned long nValidEdge = j;\n    pqueue.resize(nValidEdge);\n    sort( pqueue.begin(), pqueue.end(), AffinityGraphCompare<float>( edgeWeight ) );\n\n\n    /* Start MST */\n    int e;\n    int set1, set2;\n    int nPair = 0;\n    map<int,int>::iterator it1, it2;\n\n    /* Start Kruskal's */\n    for (unsigned int i = 0; i < pqueue.size(); ++i ) {\n        e = pqueue[i];\n\n        set1 = dsets.find_set(node1[e]);\n        set2 = dsets.find_set(node2[e]);\n\n        if (set1!=set2){\n            dsets.link(set1, set2);\n\n            /* compute the number of pairs merged by this MST edge */\n            for (it1 = overlap[set1].begin();\n                    it1 != overlap[set1].end(); ++it1) {\n                for (it2 = overlap[set2].begin();\n                        it2 != overlap[set2].end(); ++it2) {\n\n                    nPair = it1->second * it2->second;\n\n                    if (pos && (it1->first == it2->first)) {\n                        nPairPerEdge[e] += nPair;\n                    } else if ((!pos) && (it1->first != it2->first)) {\n                        nPairPerEdge[e] += nPair;\n                    }\n                }\n            }\n\n            /* move the pixel bags of the non-representative to the representative */\n            if (dsets.find_set(set1) == set2) // make set1 the rep to keep and set2 the rep to empty\n                swap(set1,set2);\n\n            it2 = overlap[set2].begin();\n            while (it2 != overlap[set2].end()) {\n                it1 = overlap[set1].find(it2->first);\n                if (it1 == overlap[set1].end()) {\n                    overlap[set1].insert(pair<int,int>(it2->first,it2->second));\n                } else {\n                    it1->second += it2->second;\n                }\n                overlap[set2].erase(it2++);\n            }\n        } // end link\n\n    } // end while\n}\n\n\nvoid connected_components_cpp(const int nVert,\n               const int nEdge, const int* node1, const int* node2, const int* edgeWeight,\n               int* seg){\n\n    /* Make disjoint sets */\n    vector<int> rank(nVert);\n    vector<int> parent(nVert);\n    boost::disjoint_sets<int*, int*> dsets(&rank[0],&parent[0]);\n    for (int i=0; i<nVert; ++i)\n        dsets.make_set(i);\n\n    /* union */\n    for (int i = 0; i < nEdge; ++i )\n         // check bounds to make sure the nodes are valid\n        if ((edgeWeight[i]!=0) && (node1[i]>=0) && (node1[i]<nVert) && (node2[i]>=0) && (node2[i]<nVert))\n            dsets.union_set(node1[i],node2[i]);\n\n    /* find */\n    for (int i = 0; i < nVert; ++i)\n        seg[i] = dsets.find_set(i);\n}\n\n\nvoid marker_watershed_cpp(const int nVert, const int* marker,\n               const int nEdge, const int* node1, const int* node2, const float* edgeWeight,\n               int* seg){\n\n    /* Make disjoint sets */\n    vector<int> rank(nVert);\n    vector<int> parent(nVert);\n    boost::disjoint_sets<int*, int*> dsets(&rank[0],&parent[0]);\n    for (int i=0; i<nVert; ++i)\n        dsets.make_set(i);\n\n    /* initialize output array and find representatives of each class */\n    std::map<int,int> components;\n    for (int i=0; i<nVert; ++i){\n        seg[i] = marker[i];\n        if (seg[i] > 0)\n            components[seg[i]] = i;\n    }\n\n    // merge vertices labeled with the same marker\n    for (int i=0; i<nVert; ++i)\n        if (seg[i] > 0)\n            dsets.union_set(components[seg[i]],i);\n\n    /* Sort all the edges in decreasing order of weight */\n    std::vector<int> pqueue( nEdge );\n    int j = 0;\n    for (int i = 0; i < nEdge; ++i)\n        if ((edgeWeight[i]!=0) &&\n            (node1[i]>=0) && (node1[i]<nVert) &&\n            (node2[i]>=0) && (node2[i]<nVert) &&\n            (marker[node1[i]]>=0) && (marker[node2[i]]>=0))\n                pqueue[ j++ ] = i;\n    unsigned long nValidEdge = j;\n    pqueue.resize(nValidEdge);\n    sort( pqueue.begin(), pqueue.end(), AffinityGraphCompare<float>( edgeWeight ) );\n\n    /* Start MST */\n    int set1, set2, label_of_set1, label_of_set2;\n    for (unsigned int i = 0; i < pqueue.size(); ++i ) {\n\n        set1=dsets.find_set(node1[i]);\n        set2=dsets.find_set(node2[i]);\n        label_of_set1 = seg[set1];\n        label_of_set2 = seg[set2];\n\n        if ((set1!=set2) &&\n            ( ((label_of_set1==0) && (marker[set1]==0)) ||\n             ((label_of_set2==0) && (marker[set1]==0))) ){\n\n            dsets.link(set1, set2);\n            // either label_of_set1 is 0 or label_of_set2 is 0.\n            seg[dsets.find_set(set1)] = std::max(label_of_set1,label_of_set2);\n            \n        }\n\n    }\n\n    // write out the final coloring\n    for (int i=0; i<nVert; i++)\n        seg[i] = seg[dsets.find_set(i)];\n\n}\n", "meta": {"hexsha": "7dba696326ae988e10f671cba2662211d8dffb71", "size": 6163, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "dataset_06/malis/malis_cpp.cpp", "max_stars_repo_name": "naibaf7/caffe_neural_models", "max_stars_repo_head_hexsha": "9d372c4bc599029902185e19f89e5c39f842fff7", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 28.0, "max_stars_repo_stars_event_min_datetime": "2015-06-11T07:48:29.000Z", "max_stars_repo_stars_event_max_datetime": "2019-06-28T01:29:09.000Z", "max_issues_repo_path": "dataset_06/malis/malis_cpp.cpp", "max_issues_repo_name": "naibaf7/caffe_neural_models", "max_issues_repo_head_hexsha": "9d372c4bc599029902185e19f89e5c39f842fff7", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2015-10-01T13:14:46.000Z", "max_issues_repo_issues_event_max_datetime": "2016-09-28T16:25:35.000Z", "max_forks_repo_path": "dataset_06/malis/malis_cpp.cpp", "max_forks_repo_name": "naibaf7/caffe_neural_models", "max_forks_repo_head_hexsha": "9d372c4bc599029902185e19f89e5c39f842fff7", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 16.0, "max_forks_repo_forks_event_min_datetime": "2015-07-08T18:47:59.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-26T13:48:48.000Z", "avg_line_length": 31.2842639594, "max_line_length": 105, "alphanum_fraction": 0.5351289956, "num_tokens": 1739, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6370307944803832, "lm_q2_score": 0.5312093733737563, "lm_q1q2_score": 0.3383967291557105}}
{"text": "/**\n * @file   Optimizer.cpp\n * @brief  Implementations of Optimizer class for pose & map data optimization.\n * @author Charlie Li\n * @date   2019.09.17\n */\n\n#include \"Optimizer.hpp\"\n\n#include <map>\n#include <memory>\n#include <set>\n#include <vector>\n\n#include <g2o/core/sparse_optimizer.h>\n#include <g2o/core/block_solver.h>\n//#include <g2o/core/factory.h>\n#include <g2o/core/optimization_algorithm_levenberg.h>\n#include <g2o/core/robust_kernel_impl.h> // g2o::RobustKernelHuber, ...\n#include <g2o/core/solver.h>\n//#include <g2o/solvers/cholmod/linear_solver_cholmod.h> // for global BA\n#include <g2o/solvers/csparse/linear_solver_csparse.h> // for global BA\n#include <g2o/solvers/dense/linear_solver_dense.h> // for pose optimization\n#include <g2o/solvers/eigen/linear_solver_eigen.h> // for local BA\n#include <g2o/types/sba/types_six_dof_expmap.h> // g2o::EdgeSE3ProjectXYZ, ...\n#include <opencv2/core.hpp>\n#include <opencv2/core/eigen.hpp> // cv::cv2eigen()\n#include <Eigen/Core>\n#include <Eigen/Geometry> // Eigen::Quaternion\n#include \"Config.hpp\"\n#include \"Frame.hpp\"\n#include \"KeyFrame.hpp\"\n#include \"Map.hpp\"\n#include \"MapPoint.hpp\"\n#include \"Tracker.hpp\"\n\nnamespace SLAM_demo {\n\nusing std::map;\nusing std::make_shared;\nusing std::set;\nusing std::shared_ptr;\nusing std::vector;\nusing cv::Mat;\n\nconst int Optimizer::TH_MIN_NUM_MAPPOINT = 5;\nconst float Optimizer::TH_MAX_CHI2_FACTOR = 9.0f;\n\nOptimizer::Optimizer(const std::shared_ptr<Map>& pMap) : mpMap(pMap) {}\n\nint Optimizer::globalBundleAdjustment(unsigned nKFs, int nIter,\n                                      bool bRobust) const\n{\n    // set definition of solver\n    g2o::BlockSolver_6_3::LinearSolverType* pLinearSolver;\n    pLinearSolver =\n        new g2o::LinearSolverCSparse<g2o::BlockSolver_6_3::PoseMatrixType>();\n    g2o::BlockSolver_6_3* pBlkSolver;\n    pBlkSolver = new g2o::BlockSolver_6_3(pLinearSolver);\n    g2o::OptimizationAlgorithmLevenberg* pSolverLM;\n    pSolverLM = new g2o::OptimizationAlgorithmLevenberg(pBlkSolver);\n    // configure optimizer\n    g2o::SparseOptimizer optimizer;\n    optimizer.setVerbose(false);\n    optimizer.setAlgorithm(pSolverLM);\n    \n    // add vertices: poses\n    vector<shared_ptr<KeyFrame>> vpKFs = mpMap->getLastNKFs(nKFs);\n    unsigned idxKFMax = 0;\n    for (const auto& pKF : vpKFs) {\n        g2o::VertexSE3Expmap* pVSE3 = new g2o::VertexSE3Expmap();\n        Mat Tcw = pKF->mPose.getPose();\n        unsigned idxKF = pKF->index();\n        pVSE3->setEstimate(cvMat2SE3Quat(Tcw));\n        pVSE3->setId(idxKF);\n        bool bFixed = idxKF == 0;\n        pVSE3->setFixed(bFixed);\n        optimizer.addVertex(pVSE3);\n        if (idxKF > idxKFMax) {\n            idxKFMax = idxKF;\n        }\n    }\n    // add vertices: map points, and add edges for each map point\n    vector<shared_ptr<MapPoint>> vpMPts = mpMap->getAllMPts();\n    int nMPts = vpMPts.size();\n    // skip optimization if map points are not enough\n    if (nMPts < TH_MIN_NUM_MAPPOINT) {\n        return 0;\n    }\n    vector<bool> vbMPtOptimized(nMPts, true);\n    vector<vector<g2o::EdgeSE3ProjectXYZ*>> vvpEdges(nMPts);    \n    for (int i = 0; i < nMPts; ++i) {\n        const shared_ptr<MapPoint>& pMPt = vpMPts[i];\n        g2o::VertexSBAPointXYZ* pVPt = new g2o::VertexSBAPointXYZ();\n        pVPt->setEstimate(cvMat2Vector3d(pMPt->X3D()));\n        pVPt->setId(idxKFMax + 1 + i);\n        pVPt->setMarginalized(true); // why?? (to decrease the size of Hessian?)\n        optimizer.addVertex(pVPt);\n        \n        // add edges\n        vector<shared_ptr<KeyFrame>> vpKFsMPt = (nKFs == 0) ?\n            pMPt->getRelatedKFs() : vpKFs;\n        int nKFsMpt = vpKFsMPt.size();\n        vvpEdges[i].resize(nKFsMpt, nullptr);\n        bool bHasEdge = false; // check whether the vertec has edges\n        for (int j = 0; j < nKFsMpt; ++j) {\n            auto& pKF = vpKFsMPt[j];        \n            // check whether the map point is observed by the target keyframe\n            if (!pMPt->isObservedBy(pKF)) {\n                continue;\n            }\n            // form an edge\n            bHasEdge = true;\n            cv::KeyPoint kpt = pMPt->keypoint(pKF);\n            Eigen::Matrix<double, 2, 1> obs;\n            obs << kpt.pt.x, kpt.pt.y;\n            g2o::EdgeSE3ProjectXYZ* pEdge = new g2o::EdgeSE3ProjectXYZ();\n            // vertex 0: map point\n            pEdge->setVertex(0, dynamic_cast<g2o::OptimizableGraph::Vertex*>(\n                                 pVPt));\n            // vertex 1: pose\n            pEdge->setVertex(1, dynamic_cast<g2o::OptimizableGraph::Vertex*>(\n                                 optimizer.vertex(pKF->index())));\n            pEdge->setMeasurement(obs);\n            // set element in information matrix (value = 1 / sigma^2)\n            float sigma = std::pow(Config::scaleFactor(), kpt.octave);\n            float invSigma2 = 1.0f / (sigma * sigma);\n            pEdge->setInformation(Eigen::Matrix2d::Identity() * invSigma2);\n            // set robust kernel\n            if (bRobust) {\n                g2o::RobustKernelHuber* pRK = new g2o::RobustKernelHuber();\n                pEdge->setRobustKernel(pRK);\n                // rho(x) = x^2 if |x| < delta else 2*delta*|x| - delta^2\n                pRK->setDelta(sigma);\n            }\n            // set cam intrinsics\n            pEdge->fx = Config::fx();\n            pEdge->fy = Config::fy();\n            pEdge->cx = Config::cx();\n            pEdge->cy = Config::cy();\n            // record all the edges\n            vvpEdges[i][j] = pEdge;\n            // only optimize outliers at the last iteration\n            if (pMPt->isOutlier()) {\n                pEdge->setLevel(1);\n            }            \n            optimizer.addEdge(pEdge);\n        }\n        if (!bHasEdge) {\n            optimizer.removeVertex(pVPt);\n            vbMPtOptimized[i] = false;\n        }\n    }\n\n    // optimize\n    int nIt = 2;\n    for (int it = 0; it < nIt; ++it) {\n        optimizer.initializeOptimization(0);\n        optimizer.optimize(nIter);\n        // exclude outliers\n        for (int i = 0; i < nMPts; ++i) {\n            auto& pMPt = vpMPts[i];\n            if (vbMPtOptimized[i]) {\n                vector<shared_ptr<KeyFrame>> vpKFsMPt = (nKFs == 0) ?\n                    pMPt->getRelatedKFs() : vpKFs;\n                int nKFsMpt = vpKFsMPt.size();\n                for (int j = 0; j < nKFsMpt; ++j) {\n                    auto& pEdge = vvpEdges[i][j];\n                    if (!pEdge) {\n                        continue;\n                    }\n                    // optimize all edges for the last iteration\n                    // exclude outliers for other iterations\n                    if (it == nIt - 2) {\n                        pEdge->setLevel(0);\n                    } else {\n                        float chi2 = pEdge->chi2();\n                        cv::KeyPoint kpt = pMPt->keypoint(vpKFsMPt[j]);\n                        float sigma = std::pow(Config::scaleFactor(),\n                                               kpt.octave);\n                        if (chi2 > sigma*sigma ||\n                            !pEdge->isDepthPositive()) {\n                            pEdge->setLevel(1);\n                        } else {\n                            pEdge->setLevel(0);\n                        }\n                    }\n                }\n            }\n        }\n    }\n    \n    // update results back to the keyframes/map\n    // pose update via vpKFs\n    for (const auto& pKF : vpKFs) {\n        g2o::VertexSE3Expmap* pVSE3 = dynamic_cast<g2o::VertexSE3Expmap*>(\n            optimizer.vertex(pKF->index()));\n        g2o::SE3Quat T = pVSE3->estimate();\n        pKF->mPose.setPose(SE3Quat2cvMat(T));\n    }\n    // map point data update via vpMPts\n    // count the number of map point outliers after optimization\n    int nInliers = nMPts;\n    for (int i = 0; i < nMPts; ++i) {\n        if (vbMPtOptimized[i]) {\n            shared_ptr<MapPoint>& pMPt = vpMPts[i];\n            g2o::VertexSBAPointXYZ* pVPt = dynamic_cast<\n                g2o::VertexSBAPointXYZ*>(optimizer.vertex(idxKFMax + 1 + i));\n            Eigen::Vector3d X = pVPt->estimate();\n            pMPt->setX3D(Vector3d2cvMat(X));\n            \n            // set outlier status for all map points\n            pMPt->setOutlier(false);\n            vector<shared_ptr<KeyFrame>> vpKFsMPt = (nKFs == 0) ?\n                pMPt->getRelatedKFs() : vpKFs;\n            int nKFsMpt = vpKFsMPt.size();\n            for (int j = 0; j < nKFsMpt; ++j) {\n                auto& pEdge = vvpEdges[i][j];\n                if (!pEdge) {\n                    continue;\n                }\n                float chi2 = pEdge->chi2();\n                cv::KeyPoint kpt = pMPt->keypoint(vpKFsMPt[j]);\n                float sigma = std::pow(Config::scaleFactor(), kpt.octave);\n                if (chi2 > sigma*sigma * TH_MAX_CHI2_FACTOR ||\n                    !pEdge->isDepthPositive()) {\n                    pMPt->setOutlier(true);\n                    --nInliers;\n                    break;\n                }\n            }            \n        }\n    }\n\n    // clean up resources\n    optimizer.clear();\n    optimizer.clearParameters();\n\n    return nInliers;\n}\n\n//int Optimizer::frameBundleAdjustment(unsigned nFrames, int nIter,\n//                                     bool bRobust) const\n//{\n//    // set definition of solver\n//    g2o::BlockSolver_6_3::LinearSolverType* pLinearSolver;\n//    pLinearSolver =\n//        new g2o::LinearSolverCSparse<g2o::BlockSolver_6_3::PoseMatrixType>();\n//    g2o::BlockSolver_6_3* pBlkSolver;\n//    pBlkSolver = new g2o::BlockSolver_6_3(pLinearSolver);\n//    g2o::OptimizationAlgorithmLevenberg* pSolverLM;\n//    pSolverLM = new g2o::OptimizationAlgorithmLevenberg(pBlkSolver);\n//    // configure optimizer\n//    g2o::SparseOptimizer optimizer;\n//    optimizer.setVerbose(false);\n//    optimizer.setAlgorithm(pSolverLM);\n//\n//    // add vertices: poses\n//    vector<shared_ptr<Frame>> vpKFs = mpMap->getLastNKFs(nFrames);\n//    shared_ptr<Frame> pFrameCur = nullptr;\n//\n//    unsigned idxFMax = 0;\n//    for (const auto& pFrame : vpFrames) {\n//        g2o::VertexSE3Expmap* pVSE3 = new g2o::VertexSE3Expmap();\n//        Mat Tcw = pFrame->mPose.getPose();\n//        unsigned idxF = pFrame->index();\n//        pVSE3->setEstimate(cvMat2SE3Quat(Tcw));\n//        pVSE3->setId(idxF);\n//        bool bFixed = idxF != System::nCurrentFrame;\n//        if (!bFixed) {\n//            pFrameCur = pFrame;\n//        }\n//        pVSE3->setFixed(bFixed);\n//        optimizer.addVertex(pVSE3);\n//        if (idxF > idxFMax) {\n//            idxFMax = idxF;\n//        }\n//    }\n//\n//    // no target frame to be optimized\n//    if (!pFrameCur) {\n//        return 0;\n//    }\n//\n//    // add vertices: map points, and add edges for each map point\n//    vector<shared_ptr<MapPoint>> vpMPts = pFrameCur->getpMPtsObserved();\n//    int nMPts = vpMPts.size();\n//    // skip optimization if map points are not enough\n//    if (nMPts < TH_MIN_NUM_MAPPOINT) {\n//        return 0;\n//    }    \n//    vector<vector<g2o::EdgeSE3ProjectXYZ*>> vvpEdges(nMPts);    \n//    for (int i = 0; i < nMPts; ++i) {\n//        const shared_ptr<MapPoint>& pMPt = vpMPts[i];\n//        g2o::VertexSBAPointXYZ* pVPt = new g2o::VertexSBAPointXYZ();\n//        pVPt->setEstimate(cvMat2Vector3d(pMPt->X3D()));\n//        pVPt->setId(idxFMax + 1 + i);\n//        pVPt->setMarginalized(true);\n//        optimizer.addVertex(pVPt);\n//        \n//        // add edges\n//        vvpEdges[i].resize(nFrames, nullptr);\n//        for (unsigned j = 0; j < nFrames; ++j) {\n//            auto& pFrame = vpFrames[j];\n//            // check whether the map point is observed by the target frame\n//            if (!pMPt->isObservedBy(pFrame)) {\n//                continue;\n//            }\n//            cv::KeyPoint kpt = pMPt->keypoint(pFrame);\n//            Eigen::Matrix<double, 2, 1> obs;\n//            obs << kpt.pt.x, kpt.pt.y;\n//            g2o::EdgeSE3ProjectXYZ* pEdge = new g2o::EdgeSE3ProjectXYZ();\n//            // vertex 0: map point\n//            pEdge->setVertex(0, dynamic_cast<g2o::OptimizableGraph::Vertex*>(\n//                                 pVPt));\n//            // vertex 1: pose\n//            pEdge->setVertex(1, dynamic_cast<g2o::OptimizableGraph::Vertex*>(\n//                                 optimizer.vertex(pFrame->index())));\n//            pEdge->setMeasurement(obs);\n//            // set element in information matrix (value = 1 / sigma^2)\n//            float sigma = std::pow(Config::scaleFactor(), kpt.octave);\n//            float invSigma2 = 1.0f / (sigma * sigma);\n//            pEdge->setInformation(Eigen::Matrix2d::Identity() * invSigma2);\n//            // set robust kernel\n//            if (bRobust) {\n//                g2o::RobustKernelHuber* pRK = new g2o::RobustKernelHuber();\n//                pEdge->setRobustKernel(pRK);\n//                // rho(x) = x^2 if |x| < delta else 2*delta*|x| - delta^2\n//                pRK->setDelta(sigma);\n//            }\n//            // set cam intrinsics\n//            pEdge->fx = Config::fx();\n//            pEdge->fy = Config::fy();\n//            pEdge->cx = Config::cx();\n//            pEdge->cy = Config::cy();\n//            // only optimize outliers at the last iteration\n//            if (pMPt->isOutlier()) {\n//                pEdge->setLevel(1);\n//            }\n//            // record all the edges\n//            vvpEdges[i][j] = pEdge;\n//            optimizer.addEdge(pEdge);\n//        }\n//    }\n//\n//    // optimize\n//    //optimizer.initializeOptimization();\n//    //optimizer.optimize(nIter);\n//    int nIt = 3;\n//    for (int it = 0; it < nIt; ++it) {\n//        optimizer.initializeOptimization(0);\n//        optimizer.optimize(nIter);\n//        // exclude outliers\n//        for (int i = 0; i < nMPts; ++i) {\n//            auto& pMPt = vpMPts[i];\n//            for (unsigned j = 0; j < nFrames; ++j) {\n//                auto& pEdge = vvpEdges[i][j];\n//                if (!pEdge) {\n//                    continue;\n//                }\n//                // optimize all edges for the last iteration\n//                // exclude outliers for other iterations\n//                if (it == nIt - 2) {\n//                    pEdge->setLevel(0);\n//                } else {\n//                    float chi2 = pEdge->chi2();\n//                    cv::KeyPoint kpt = pMPt->keypoint(vpFrames[j]);\n//                    float sigma = std::pow(Config::scaleFactor(),\n//                                           kpt.octave);\n//                    if (chi2 > sigma*sigma ||\n//                        !pEdge->isDepthPositive()) {\n//                        pEdge->setLevel(1);\n//                    } else {\n//                        pEdge->setLevel(0);\n//                    }\n//                }\n//            }\n//        }\n//    }\n//    \n//    // update results back to the frames/map\n//    // pose update via vpFrames\n//    g2o::VertexSE3Expmap* pVSE3 = dynamic_cast<g2o::VertexSE3Expmap*>(\n//        optimizer.vertex(System::nCurrentFrame));\n//    g2o::SE3Quat T = pVSE3->estimate();\n//    pFrameCur->mPose.setPose(SE3Quat2cvMat(T));\n//    // map point data update via vpMPts\n//    // count the number of map point outliers after optimization\n//    int nInliers = nMPts;\n//    for (int i = 0; i < nMPts; ++i) {\n//        shared_ptr<MapPoint>& pMPt = vpMPts[i];\n//        g2o::VertexSBAPointXYZ* pVPt = dynamic_cast<g2o::VertexSBAPointXYZ*>(\n//            optimizer.vertex(idxFMax + 1 + i));\n//        Eigen::Vector3d X = pVPt->estimate();\n//        pMPt->setX3D(Vector3d2cvMat(X));\n//        \n//        // set outlier status for all map points\n//        pMPt->setOutlier(false);\n//        for (unsigned j = 0; j < nFrames; ++j) {\n//            auto& pEdge = vvpEdges[i][j];\n//            if (!pEdge) {\n//                continue;\n//            }\n//            float chi2 = pEdge->chi2();\n//            cv::KeyPoint kpt = pMPt->keypoint(vpFrames[j]);\n//            float sigma = std::pow(Config::scaleFactor(), kpt.octave);\n//            if (chi2 > sigma*sigma * TH_MAX_CHI2_FACTOR ||\n//                !pEdge->isDepthPositive()) {\n//                pMPt->setOutlier(true);\n//                --nInliers;\n//                break;\n//            }\n//        }\n//    }\n//\n//    // clean up resources\n//    optimizer.clear();\n//    optimizer.clearParameters();\n//\n//    return nInliers;\n//}\n\nint Optimizer::poseOptimization(const std::shared_ptr<Frame>& pFrame) const\n{\n    // count the number of map point outliers after optimization\n    int nInliers = 0;\n    // set definition of solver\n    g2o::BlockSolver_6_3::LinearSolverType* pLinearSolver;\n    pLinearSolver =\n        new g2o::LinearSolverDense<g2o::BlockSolver_6_3::PoseMatrixType>();\n    g2o::BlockSolver_6_3* pBlkSolver;\n    pBlkSolver = new g2o::BlockSolver_6_3(pLinearSolver);\n    g2o::OptimizationAlgorithmLevenberg* pSolverLM;\n    pSolverLM = new g2o::OptimizationAlgorithmLevenberg(pBlkSolver);\n    // configure optimizer\n    g2o::SparseOptimizer optimizer;\n    optimizer.setVerbose(false);\n    optimizer.setAlgorithm(pSolverLM);\n    \n    // add vertices: the pose to be optimized\n    g2o::VertexSE3Expmap* pVSE3 = new g2o::VertexSE3Expmap();\n    Mat Tcw = pFrame->mPose.getPose();\n    pVSE3->setEstimate(cvMat2SE3Quat(Tcw));\n    pVSE3->setId(0);\n    pVSE3->setFixed(false);\n    optimizer.addVertex(pVSE3);\n    \n    // add edges: unary edge with map point data as measurement\n    map<int, shared_ptr<MapPoint>> mpMPts = pFrame->getMPtsMap();\n    int nMPts = mpMPts.size();\n    // skip optimization if map points are not enough\n    if (nMPts < TH_MIN_NUM_MAPPOINT) {\n        return 0;\n    }\n    vector<g2o::EdgeSE3ProjectXYZOnlyPose*> vpEdges;\n    vpEdges.reserve(nMPts);\n    for (const auto& pair : mpMPts) {\n        const shared_ptr<MapPoint>& pMPt = pair.second;\n        // is it necessary to check whether the frame is valid?\n        cv::KeyPoint kpt = pFrame->keypoint(pair.first);\n        Eigen::Matrix<double, 2, 1> obs;\n        obs << kpt.pt.x, kpt.pt.y;\n        g2o::EdgeSE3ProjectXYZOnlyPose* pEdge =\n            new g2o::EdgeSE3ProjectXYZOnlyPose();\n        // vertex 0: pose\n        pEdge->setVertex(0, dynamic_cast<g2o::OptimizableGraph::Vertex*>(\n                             pVSE3));\n        pEdge->setMeasurement(obs);\n        // set element in information matrix (value = 1 / sigma^2)\n        float sigma = std::pow(Config::scaleFactor(), kpt.octave);\n        float invSigma2 = 1.0f / (sigma * sigma);\n        pEdge->setInformation(Eigen::Matrix2d::Identity() * invSigma2);\n        // set robust kernel\n        g2o::RobustKernelHuber* pRK = new g2o::RobustKernelHuber();\n        pEdge->setRobustKernel(pRK);\n        // rho(x) = x^2 if |x| < delta else 2*delta*|x| - delta^2\n        pRK->setDelta(sigma);\n        // set map point position\n        pEdge->Xw = cvMat2Vector3d(pMPt->X3D());\n        // set cam intrinsics\n        pEdge->fx = Config::fx();\n        pEdge->fy = Config::fy();\n        pEdge->cx = Config::cx();\n        pEdge->cy = Config::cy();\n        vpEdges.push_back(pEdge);\n        // only optimize outliers at the last iteration\n        //if (pMPt->isOutlier()) {\n        //    pEdge->setLevel(1);\n        //}\n        optimizer.addEdge(pEdge);\n    }\n\n    // optimize (multi-pass?)\n    int nIt = 4;\n    for (int it = 0; it < nIt; ++it) {\n        //pVSE3->setEstimate(cvMat2SE3Quat(Tcw));\n        optimizer.initializeOptimization(0); // only optimize level 0 edges\n        optimizer.optimize(10);\n        // exclude outliers\n        auto cit = mpMPts.cbegin();\n        for (int i = 0; i < nMPts; ++i, ++cit) {\n            assert(cit != mpMPts.cend());\n            auto& pEdge = vpEdges[i];\n            // optimize all edges for the last iteration\n            // exclude outliers for other iterations\n            if (it == nIt - 2) {\n                pEdge->setLevel(0);\n            } else {\n                float chi2 = pEdge->chi2();\n                cv::KeyPoint kpt = pFrame->keypoint(cit->first);\n                float sigma = std::pow(Config::scaleFactor(), kpt.octave);\n                if (chi2 > sigma*sigma || !pEdge->isDepthPositive()) {\n                    pEdge->setLevel(1);\n                } else {\n                    pEdge->setLevel(0);\n                }\n            }\n        }\n    }\n\n    // update optimized pose and map point outlier status\n    auto cit = mpMPts.cbegin();\n    for (int i = 0; i < nMPts ; ++i, ++cit) {\n        assert(cit != mpMPts.cend());\n        auto& pMPt = cit->second;\n        auto& pEdge = vpEdges[i];\n        float chi2 = pEdge->chi2();\n        cv::KeyPoint kpt = pFrame->keypoint(cit->first);\n        float sigma = std::pow(Config::scaleFactor(), kpt.octave);\n        if (chi2 > sigma*sigma * TH_MAX_CHI2_FACTOR ||\n            !pEdge->isDepthPositive()) {\n            pMPt->setOutlier(true);\n        } else {\n            pMPt->setOutlier(false);\n            nInliers++;\n        }\n    }\n    g2o::SE3Quat T = pVSE3->estimate();\n    pFrame->mPose.setPose(SE3Quat2cvMat(T));\n\n    // clean up resources\n    optimizer.clear();\n    optimizer.clearParameters();\n\n    return nInliers;\n}\n\nvoid Optimizer::localBundleAdjustment(const std::shared_ptr<KeyFrame>& pKFin,\n                                      int nIter, bool bRobust) const\n{\n    // set definition of solver\n    g2o::BlockSolver_6_3::LinearSolverType* pLinearSolver;\n    pLinearSolver =\n        new g2o::LinearSolverEigen<g2o::BlockSolver_6_3::PoseMatrixType>();\n    g2o::BlockSolver_6_3* pBlkSolver;\n    pBlkSolver = new g2o::BlockSolver_6_3(pLinearSolver);\n    g2o::OptimizationAlgorithmLevenberg* pSolverLM;\n    pSolverLM = new g2o::OptimizationAlgorithmLevenberg(pBlkSolver);\n    // configure optimizer\n    g2o::SparseOptimizer optimizer;\n    optimizer.setVerbose(false);\n    optimizer.setAlgorithm(pSolverLM);\n    \n    // add vertices: poses that can be optimized\n    vector<shared_ptr<KeyFrame>> vpConnectedKFs = pKFin->getConnectedKFs();\n    set<shared_ptr<KeyFrame>> spKFs;\n    spKFs.insert(pKFin);\n    spKFs.insert(vpConnectedKFs.cbegin(), vpConnectedKFs.cend());\n    set<shared_ptr<MapPoint>> spMPts; // temp container for all local map points\n    unsigned idxKFMax = 0;\n    for (const auto& pKF : spKFs) {\n        g2o::VertexSE3Expmap* pVSE3 = new g2o::VertexSE3Expmap();\n        Mat Tcw = pKF->mPose.getPose();\n        unsigned idxKF = pKF->index();\n        pVSE3->setEstimate(cvMat2SE3Quat(Tcw));\n        pVSE3->setId(idxKF);\n        bool bFixed = pKF->index() == 0;\n        pVSE3->setFixed(bFixed);\n        optimizer.addVertex(pVSE3);\n        if (idxKF > idxKFMax) {\n            idxKFMax = idxKF;\n        }\n        // get local map points\n        vector<shared_ptr<MapPoint>> vpMPtsKF = pKF->mappoints();\n        for (const auto& pMPt : vpMPtsKF) {\n            if (pMPt) {\n                spMPts.insert(pMPt);\n            }\n        }\n    }\n    // add vertices: fixed poses\n    vector<shared_ptr<KeyFrame>> vpWeakKFs = pKFin->getWeakKFs();\n    set<shared_ptr<KeyFrame>> spFixedKFs;\n    spFixedKFs.insert(vpWeakKFs.cbegin(), vpWeakKFs.cend());\n    for (const auto& pMPt: spMPts) {\n        vector<shared_ptr<KeyFrame>> vpKFRelated = pMPt->getRelatedKFs();\n        for (const auto& pKF : vpKFRelated) {\n            // add poses that is not in the local map to the fixed pose set\n            if (spKFs.find(pKF) == spKFs.end()) {\n                spFixedKFs.insert(pKF);\n            }\n        }\n    }\n    for (const auto& pKF : spFixedKFs) {\n        g2o::VertexSE3Expmap* pVSE3 = new g2o::VertexSE3Expmap();\n        Mat Tcw = pKF->mPose.getPose();\n        unsigned idxKF = pKF->index();\n        pVSE3->setEstimate(cvMat2SE3Quat(Tcw));\n        pVSE3->setId(idxKF);\n        pVSE3->setFixed(true);\n        optimizer.addVertex(pVSE3);\n        if (idxKF > idxKFMax) {\n            idxKFMax = idxKF;\n        }\n    }\n\n    // add vertices: map points, and add edges for each map point\n    int nMPts = spMPts.size();\n    // skip optimization if map points are not enough\n    if (nMPts < TH_MIN_NUM_MAPPOINT) {\n        return;\n    }\n    // use std::vector for indexing on each map point\n    vector<shared_ptr<MapPoint>> vpMPts(spMPts.cbegin(), spMPts.cend());\n    vector<bool> vbMPtOptimized(nMPts, true);\n    vector<vector<g2o::EdgeSE3ProjectXYZ*>> vvpEdges(nMPts);    \n    for (int i = 0; i < nMPts; ++i) {\n        const shared_ptr<MapPoint>& pMPt = vpMPts[i];\n        g2o::VertexSBAPointXYZ* pVPt = new g2o::VertexSBAPointXYZ();\n        pVPt->setEstimate(cvMat2Vector3d(pMPt->X3D()));\n        pVPt->setId(idxKFMax + 1 + i);\n        pVPt->setMarginalized(true); // why?? (to decrease the size of Hessian?)\n        optimizer.addVertex(pVPt);\n        \n        // add edges\n        vector<shared_ptr<KeyFrame>> vpKFsMPt = pMPt->getRelatedKFs();\n        int nKFsMpt = vpKFsMPt.size();\n        vvpEdges[i].resize(nKFsMpt, nullptr);\n        bool bHasEdge = false; // check whether the vertec has edges\n        for (int j = 0; j < nKFsMpt; ++j) {\n            auto& pKF = vpKFsMPt[j];        \n            // check whether the map point is observed by the target keyframe\n            if (!pMPt->isObservedBy(pKF)) {\n                continue;\n            }\n            // form an edge\n            bHasEdge = true;\n            cv::KeyPoint kpt = pMPt->keypoint(pKF);\n            Eigen::Matrix<double, 2, 1> obs;\n            obs << kpt.pt.x, kpt.pt.y;\n            g2o::EdgeSE3ProjectXYZ* pEdge = new g2o::EdgeSE3ProjectXYZ();\n            // vertex 0: map point\n            pEdge->setVertex(0, dynamic_cast<g2o::OptimizableGraph::Vertex*>(\n                                 pVPt));\n            // vertex 1: pose\n            pEdge->setVertex(1, dynamic_cast<g2o::OptimizableGraph::Vertex*>(\n                                 optimizer.vertex(pKF->index())));\n            pEdge->setMeasurement(obs);\n            // set element in information matrix (value = 1 / sigma^2)\n            float sigma = std::pow(Config::scaleFactor(), kpt.octave);\n            float invSigma2 = 1.0f / (sigma * sigma);\n            pEdge->setInformation(Eigen::Matrix2d::Identity() * invSigma2);\n            // set robust kernel\n            if (bRobust) {\n                g2o::RobustKernelHuber* pRK = new g2o::RobustKernelHuber();\n                pEdge->setRobustKernel(pRK);\n                // rho(x) = x^2 if |x| < delta else 2*delta*|x| - delta^2\n                pRK->setDelta(sigma);\n            }\n            // set cam intrinsics\n            pEdge->fx = Config::fx();\n            pEdge->fy = Config::fy();\n            pEdge->cx = Config::cx();\n            pEdge->cy = Config::cy();\n            // record all the edges\n            vvpEdges[i][j] = pEdge;\n            // only optimize outliers at the last iteration\n            //if (pMPt->isOutlier()) {\n            //    pEdge->setLevel(1);\n            //}            \n            optimizer.addEdge(pEdge);\n        }\n        if (!bHasEdge) {\n            optimizer.removeVertex(pVPt);\n            vbMPtOptimized[i] = false;\n        }\n    }\n\n    // optimize\n    int nIt = 4;\n    for (int it = 0; it < nIt; ++it) {\n        optimizer.initializeOptimization(0);\n        optimizer.optimize(nIter);\n        // exclude outliers\n        for (int i = 0; i < nMPts; ++i) {\n            auto& pMPt = vpMPts[i];\n            if (vbMPtOptimized[i]) {\n                vector<shared_ptr<KeyFrame>> vpKFsMPt = pMPt->getRelatedKFs();\n                int nKFsMpt = vpKFsMPt.size();\n                for (int j = 0; j < nKFsMpt; ++j) {\n                    auto& pEdge = vvpEdges[i][j];\n                    if (!pEdge) {\n                        continue;\n                    }\n                    // optimize all edges for the last iteration\n                    // exclude outliers for other iterations\n                    if (it == nIt - 2) {\n                        pEdge->setLevel(0);\n                    } else {\n                        float chi2 = pEdge->chi2();\n                        cv::KeyPoint kpt = pMPt->keypoint(vpKFsMPt[j]);\n                        float sigma = std::pow(Config::scaleFactor(),\n                                               kpt.octave);\n                        if (chi2 > sigma*sigma ||\n                            !pEdge->isDepthPositive()) {\n                            pEdge->setLevel(1);\n                        } else {\n                            pEdge->setLevel(0);\n                        }\n                    }\n                }\n            }\n        }\n    }\n    \n    // update results back to the keyframes/map\n    // pose update via spKFs\n    for (const auto& pKF : spKFs) {\n        g2o::VertexSE3Expmap* pVSE3 = dynamic_cast<g2o::VertexSE3Expmap*>(\n            optimizer.vertex(pKF->index()));\n        g2o::SE3Quat T = pVSE3->estimate();\n        pKF->mPose.setPose(SE3Quat2cvMat(T));\n    }\n    // map point data update via vpMPts\n    // count the number of map point outliers after optimization\n    for (int i = 0; i < nMPts; ++i) {\n        if (vbMPtOptimized[i]) {\n            shared_ptr<MapPoint>& pMPt = vpMPts[i];\n            g2o::VertexSBAPointXYZ* pVPt = dynamic_cast<\n                g2o::VertexSBAPointXYZ*>(optimizer.vertex(idxKFMax + 1 + i));\n            Eigen::Vector3d X = pVPt->estimate();\n            pMPt->setX3D(Vector3d2cvMat(X));\n            \n            // set outlier status for all map points\n            pMPt->setOutlier(false);\n            vector<shared_ptr<KeyFrame>> vpKFsMPt = pMPt->getRelatedKFs();\n            int nKFsMpt = vpKFsMPt.size();\n            for (int j = 0; j < nKFsMpt; ++j) {\n                auto& pEdge = vvpEdges[i][j];\n                if (!pEdge) {\n                    continue;\n                }\n                float chi2 = pEdge->chi2();\n                cv::KeyPoint kpt = pMPt->keypoint(vpKFsMPt[j]);\n                float sigma = std::pow(Config::scaleFactor(), kpt.octave);\n                if (chi2 > sigma*sigma * TH_MAX_CHI2_FACTOR ||\n                    !pEdge->isDepthPositive()) {\n                    pMPt->setOutlier(true);\n                    break;\n                }\n            }            \n        }\n    }\n\n    // clean up resources\n    optimizer.clear();\n    optimizer.clearParameters();\n}\n\ng2o::SE3Quat Optimizer::cvMat2SE3Quat(const cv::Mat& Tcw) const\n{\n    // pose data must be double for g2o to use!!!\n    Eigen::Matrix<double, 3, 3> R;\n    Eigen::Matrix<double, 3, 1> t;\n    cv::cv2eigen(Tcw.colRange(0, 3).rowRange(0, 3), R); // float -> double\n    cv::cv2eigen(Tcw.col(3), t);\n    return g2o::SE3Quat(R, t);\n}\n\ncv::Mat Optimizer::SE3Quat2cvMat(const g2o::SE3Quat& T) const\n{\n    Mat Tcw(3, 4, CV_32FC1);\n    // Eigen::Quaternion -> Eigen::Matrix3 for R\n    Eigen::Matrix<float, 3, 3> R =\n        T.rotation().toRotationMatrix().cast<float>(); \n    Eigen::Matrix<float, 3, 1> t = T.translation().cast<float>();\n    cv::eigen2cv(R, Tcw.colRange(0, 3).rowRange(0, 3));\n    cv::eigen2cv(t, Tcw.col(3));\n    return Tcw;\n}\n\nEigen::Vector3d Optimizer::cvMat2Vector3d(const cv::Mat& X3D) const\n{\n    Eigen::Matrix<double, 3, 1> X;\n    cv::cv2eigen(X3D, X);\n    return X;\n}\n\ncv::Mat Optimizer::Vector3d2cvMat(const Eigen::Vector3d& X) const\n{\n    Mat X3D(3, 1, CV_32FC1);\n    Eigen::Vector3f Xf = X.cast<float>();\n    cv::eigen2cv(Xf, X3D);\n    return X3D;\n}\n\n} // namespace SLAM_demo\n", "meta": {"hexsha": "952360effdc260d6bb5a023ec69db56b4a34dda8", "size": 31047, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Optimizer.cpp", "max_stars_repo_name": "charlie-lee/slam_demo", "max_stars_repo_head_hexsha": "0bb6cc6d20c6a728eea502a61456f83881144e59", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Optimizer.cpp", "max_issues_repo_name": "charlie-lee/slam_demo", "max_issues_repo_head_hexsha": "0bb6cc6d20c6a728eea502a61456f83881144e59", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Optimizer.cpp", "max_forks_repo_name": "charlie-lee/slam_demo", "max_forks_repo_head_hexsha": "0bb6cc6d20c6a728eea502a61456f83881144e59", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.4245049505, "max_line_length": 80, "alphanum_fraction": 0.5385383451, "num_tokens": 8784, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6370307806984444, "lm_q2_score": 0.5312093733737563, "lm_q1q2_score": 0.33839672183461544}}
{"text": "/** $Id: WeightCalculator.cxx 178081 2019-12-18 19:13:26Z jvansanten $\n * @file\n * @author Jakob van Santen <vansanten@wisc.edu>\n *\n * $Revision: 178081 $\n * $Date: 2019-12-18 12:13:26 -0700 (Wed, 18 Dec 2019) $\n */\n\n#include <MuonGun/WeightCalculator.h>\n#include <MuonGun/Generator.h>\n#include <MuonGun/SamplingSurface.h>\n#include <MuonGun/Cylinder.h>\n#include <MuonGun/Flux.h>\n#include <MuonGun/RadialDistribution.h>\n#include <MuonGun/EnergyDistribution.h>\n#include <MuonGun/I3MuonGun.h>\n#include <MuonGun/Track.h>\n#include <boost/foreach.hpp>\n\n#include <icetray/I3Module.h>\n#include <dataclasses/physics/I3MCTreeUtils.h>\n#include <dataclasses/I3Double.h>\n#include <simclasses/I3MMCTrack.h>\n#include <phys-services/I3Calculator.h>\n#include <boost/make_shared.hpp>\n#include <boost/numeric/ublas/vector.hpp>\n\nnamespace I3MuonGun {\n\ndouble\nWeightCalculator::GetWeight(const I3Particle &axis, const BundleConfiguration &bundlespec) const\n{\n\tstd::pair<double, double> steps = surface_->GetIntersection(axis.GetPos(), axis.GetDir());\n\t// This shower axis doesn't intersect the sampling surface. Bail.\n\tif (!std::isfinite(steps.first))\n\t\treturn 0.;\n\t\n\tdouble h = GetDepth(axis.GetPos().GetZ() + steps.first*axis.GetDir().GetZ());\n\tdouble coszen = cos(axis.GetDir().GetZenith());\n\tunsigned m = unsigned(bundlespec.size());\n\t\n\tdouble rate = flux_->GetLog(h, coszen, m) - generator_->GetLogGeneratedEvents(axis, bundlespec);\n\t\n\tBOOST_FOREACH(const BundleEntry &track, bundlespec){\n\t\tdouble logprob = energy_->GetLog(h, coszen, m, track.radius,\n\t\t    EnergyDistribution::log_value(std::log(track.energy)));\n\t\tif (!std::isfinite(logprob)){\n                    log_warn(\"Log Energy weight of a least one muon is -inf, weight will be 0!\");\n                }\n\t\trate += logprob;\n        }\n\t// assert(std::isfinite(std::exp(rate)));\n\treturn std::exp(rate);\n}\n\n// Possibly throw-away utility function: \"track\" muons to a fixed surface using the\n// same method as WeightCalculatorModule\nstd::vector<I3Particle>\nGetMuonsAtSurface(I3FramePtr frame, I3Surfaces::SurfaceConstPtr surface)\n{\n\tstd::vector<I3Particle> final_states;\n\t\n\tI3MCTreeConstPtr mctree = frame->Get<I3MCTreeConstPtr>();\n\tI3MMCTrackListConstPtr mmctracks = frame->Get<I3MMCTrackListConstPtr>(\"MMCTrackList\");\n\tif (!mctree)\n\t\tlog_fatal(\"I3MCTree missing!\");\n\tif (!mmctracks)\n\t\tlog_fatal(\"I3MMCTrackList missing!\");\n\tBOOST_FOREACH(const Track &track, Track::Harvest(*mctree, *mmctracks)) {\n\t\tstd::pair<double, double> steps =\n\t\t    surface->GetIntersection(track.GetPos(), track.GetDir());\n\t\tdouble energy = track.GetEnergy(steps.first);\n\t\tif (steps.first >= 0 && energy > 0) {\n\t\t\tfinal_states.push_back(track);\n\t\t\tI3Particle &p = final_states.back();\n\t\t\tp.SetEnergy(energy);\n\t\t\tp.SetPos(track.GetPos(steps.first));\n\t\t\tp.SetTime(track.GetTime(steps.first));\n\t\t\tp.SetLength(track.GetLength()-steps.first);\n\t\t}\n\t}\n\t\n\treturn final_states;\n}\n\nnamespace {\n\nnamespace ublas = boost::numeric::ublas;\ntypedef ublas::bounded_vector<double, 3> vector;\n\nvector\nmake_vector(double x, double y, double z)\n{\n\tvector v(3);\n\tv[0] = x; v[1] = y; v[2] = z;\n\t\n\treturn v;\n}\n\nvector\nmake_vector(const I3Direction &dir)\n{\n\treturn make_vector(dir.GetX(), dir.GetY(), dir.GetZ());\n}\n\ninline vector\nsubtract(const I3Position &p1, const I3Position &p2)\n{\n\treturn make_vector(p1.GetX()-p2.GetX(), p1.GetY()-p2.GetY(), p1.GetZ()-p2.GetZ());\n}\n\ninline double\nGetRadius(const I3Particle &axis, const I3Position &pos)\n{\n        vector r = subtract(pos,axis.GetPos());\n\tdouble l = ublas::inner_prod(make_vector(axis.GetDir()), r);\n\t\n\treturn sqrt(std::max(0., ublas::inner_prod(r, r) - l*l));\n}\n\n}\n\nMuonBundleConverter::MuonBundleConverter(size_t maxMultiplicity, SamplingSurfaceConstPtr surface)\n    : maxMultiplicity_(maxMultiplicity),\n    surface_(surface ? surface : boost::make_shared<Cylinder>(1600, 800))\n{}\n\nI3TableRowDescriptionPtr\nMuonBundleConverter::CreateDescription(const I3MCTree&)\n{\n\tI3TableRowDescriptionPtr desc(new I3TableRowDescription());\n\t\n\tdesc->AddField<uint32_t>(\"multiplicity\", \"\", \"Number of muons in the bundle\");\n\tdesc->AddField<float>(\"depth\", \"km\", \"Vertical depth of intersection with the sampling surface\");\n\tdesc->AddField<float>(\"cos_theta\", \"\", \"Cosine of the shower zenith angle\");\n\tdesc->AddField<float>(\"energy\", \"GeV\", \"Muon energy at sampling surface\",\n\t    maxMultiplicity_);\n\tdesc->AddField<float>(\"radius\", \"m\", \"Perpendicular distance from of track \"\n\t    \"from the bundle axis at the sampling surface\", maxMultiplicity_);\n\t\n\treturn desc;\n}\n\nsize_t\nMuonBundleConverter::FillRows(const I3MCTree &mctree, I3TableRowPtr rows)\n{\n\tI3MMCTrackListConstPtr mmctracks = currentFrame_->Get<I3MMCTrackListConstPtr>(\"MMCTrackList\");\n\tif (!mmctracks)\n\t\tlog_fatal(\"I3MMCTrackList missing!\");\n\t\n\tconst I3MCTree::const_iterator primary = mctree.begin();\n\tstd::pair<double, double> primary_steps =\n\t    surface_->GetIntersection(primary->GetPos(), primary->GetDir());\n\tif (primary_steps.first > 0) {\n\t\trows->Set<float>(\"depth\", float(GetDepth(primary->GetPos().GetZ() + primary_steps.first*primary->GetDir().GetZ())));\n\t\trows->Set<float>(\"cos_theta\", float(cos(primary->GetDir().GetZenith())));\n\t}\n\t\n\tuint32_t m = 0;\n\tfloat *energies = rows->GetPointer<float>(\"energy\");\n\tfloat *radii = rows->GetPointer<float>(\"radius\");\n\t\n\tlog_trace(\"%zu total tracks\", Track::Harvest(mctree, *mmctracks).size());\n\t\n\tBOOST_FOREACH(const Track &track, Track::Harvest(mctree, *mmctracks)) {\n\t\t// MuonGun bundles are attached directly to the primary\n\t\tif (mctree.depth(track) > 1)\n\t\t\tcontinue;\n\t\tstd::pair<double, double> steps =\n\t\t    surface_->GetIntersection(track.GetPos(), track.GetDir());\n\t\tfloat energy = float(track.GetEnergy(steps.first));\n\t\tlog_trace(\"energy after %f m: %.1e\", steps.first, energy);\n\t\tif (energy > 0) {\n\t\t\tif (m < maxMultiplicity_) {\n\t\t\t\tenergies[m] = energy;\n\t\t\t\tradii[m] = float(GetRadius(*primary, track.GetPos(steps.first)));\n\t\t\t}\n\t\t\tm++;\n\t\t}\n\t}\n\t\n\trows->Set(\"multiplicity\", m);\n\t\n\treturn 1;\n}\n\n/**\n * @brief Interface between WeightCalculator and IceTray\n *\n * WeightCalculatorModule handles the details of extracting energies and\n * radial offsets of muons from an I3MCTree and MMCTrackList.\n */\nclass WeightCalculatorModule : public I3Module, protected WeightCalculator {\npublic:\n\tWeightCalculatorModule(const I3Context &ctx) : I3Module(ctx)\n\t{\n\t\tAddOutBox(\"OutBox\");\n\t\tAddParameter(\"Model\", \"Muon flux model for which to calculate a weight\", boost::shared_ptr<BundleModel>());\n\t\tAddParameter(\"Generator\", \"Generation spectrum for the bundles to be weighted\", generator_);\n\t}\n\t\n\tvoid Configure()\n\t{\n\t\tboost::shared_ptr<BundleModel> model;\n\t\tGetParameter(\"Model\", model);\n\t\tGetParameter(\"Generator\", generator_);\n\t\t\n\t\tif (!model)\n\t\t\tlog_fatal(\"No flux model configured!\");\n\t\tflux_ = model->flux;\n\t\tradius_ = model->radius;\n\t\tenergy_ = model->energy;\n\t\t\n\t\tif (!generator_)\n\t\t\tlog_fatal(\"No generator configured!\");\n\t\t\n\t\tsurface_ = generator_->GetInjectionSurface();\n\t\tif (!surface_)\n\t\t\tlog_fatal(\"No surface configured!\");\n\t}\n\t\n\tvoid DAQ(I3FramePtr frame)\n\t{\n\t\t// First, harvest the muons in the bundle at their points of injection, storing\n\t\t// everything that's necessary to estimate the energy lost up to an arbitrary point\n\t\tI3MCTreeConstPtr mctree = frame->Get<I3MCTreeConstPtr>();\n\t\tI3MMCTrackListConstPtr mmctracks = frame->Get<I3MMCTrackListConstPtr>(\"MMCTrackList\");\n\t\tif (!mctree)\n\t\t\tlog_fatal(\"I3MCTree missing!\");\n\t\t// if (!mmctracks)\n\t\t// \tlog_fatal(\"I3MMCTrackList missing!\");\n\t\t\n\t\tconst I3MCTree::const_iterator primary = mctree->begin();\n\t\tstd::pair<double, double> steps =\n\t\t    surface_->GetIntersection(primary->GetPos(), primary->GetDir());\n\t\tBundleConfiguration bundlespec;\n\t\t\n\t\tif (mmctracks) {\n\t\t\tstd::list<Track> tracks = Track::Harvest(*mctree, *mmctracks);\n\t\t\tBOOST_FOREACH(const Track &track, tracks) {\n\t\t\t\t// Omit secondary muons\n\t\t\t\tboost::optional<I3Particle> parent = mctree->parent(track);\n\t\t\t\tif (parent && parent->GetType() == I3Particle::NuclInt)\n\t\t\t\t\tcontinue;\n\t\t\t\tbundlespec.push_back(BundleEntry(\n\t\t\t\t    GetRadius(*primary, track.GetPos(steps.first)), track.GetEnergy(steps.first)));\n\t\t\t}\n\t\t} else {\n\t\t\t// log_warn(\"No MMCTrackList found in the frame! Assuming that everything starts on the sampling surface...\");\n\t\t\tBOOST_FOREACH(const I3Particle &track, std::make_pair(mctree->begin(), mctree->end())) {\n\t\t\t\tif (track.GetType() == I3Particle::MuMinus || track.GetType() == I3Particle::MuPlus)\n\t\t\t\t\tbundlespec.push_back(BundleEntry(\n\t\t\t\t\t    GetRadius(*primary, track.GetPos()), track.GetEnergy()));\n\t\t\t}\n\t\t}\n\t\t\n\t\tframe->Put(GetName(), boost::make_shared<I3Double>(GetWeight(*primary, bundlespec)));\n\t\tPushFrame(frame);\n\t}\n\t\n\tvoid Finish();\n};\n\n// Out-of-line virtual method definition to force the vtable into this translation unit\nvoid WeightCalculatorModule::Finish() {}\n\n}\n\nI3_MODULE(I3MuonGun::WeightCalculatorModule);\n", "meta": {"hexsha": "2df45b33444f6b8e6bde8eae17d401cfde3076d2", "size": 8819, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "MuonGun/private/MuonGun/WeightCalculator.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/WeightCalculator.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/WeightCalculator.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": 32.662962963, "max_line_length": 118, "alphanum_fraction": 0.7130060098, "num_tokens": 2392, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6513548782017745, "lm_q2_score": 0.519521321952093, "lm_q1q2_score": 0.3383927473833304}}
{"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\n#ifndef WANGTETER_HPP\n#define\tWANGTETER_HPP\n\n#include <armadillo>\n#include <memory>\n#include \"KEDF.hpp\"\n#include \"FourierGrid.hpp\"\n#include \"HelperFunctions.hpp\"\nusing namespace std;\nusing namespace arma;\n\ntemplate<class GridType>\nclass WangTeter: public KEDF<GridType> {\n    \npublic:\n    \n    WangTeter(GridType* example, const double alpha, const double beta, cube* keKernel)\n    : _alpha(alpha), _beta(beta), _keKernel(keKernel){\n    }\n    \n    ~WangTeter() {\n    }\n    \n    string getMethodDescription() const {\n        return \"Wang-Teter KEDF\";\n    }\n    \n    vector<string> getCitations() const {\n    \n        vector<string> citations(0);\n        citations.push_back(\"L.-W. Wang and M. P. Teter, Phys. Rev. B 45, 13196 (1992).\");\n    \n        return citations;\n    }\n    \n    vector<string> getWorkingEquations() const {\n    \n        vector<string> equations(0);\n        equations.push_back(\"\");\n    \n        //   WTEnergy = cTF * SUM(rhoR_SI**alpha * FFT(FFT(rhoR_SI**beta) * keKernel(:,:,:,1)))*/\n    \n        return equations;\n    }\n    \n    double calcEnergy(const GridType& grid) const {\n\n        unique_ptr<GridType> workGridB = grid.duplicate();\n        \n        workGridB->powGrid(_beta);\n        \n        cx_cube* recB = workGridB->getReciprocalGrid();\n        \n        const uword recElems = recB->n_elem;\n\n        #pragma omp parallel for default(none) shared(recB)\n        for (uword x = 0; x < recElems; ++x) {\n            recB->at(x) *= _keKernel->at(x);\n        }\n        workGridB->completeReciprocal(recB);\n        \n        cube* realB = workGridB->getRealGrid();\n        \n        const uword elems = realB->n_elem;\n\n        const cube* dens = grid.tryReadRealGrid();\n        if (!dens) {\n            // unfortunately, we need to get a copy of the grid\n            unique_ptr<FourierGrid> workGrid = grid.createFourierDuplicate();\n            dens = workGrid->readRealGrid();\n        }\n\n        #pragma omp parallel for default(none) shared(realB,dens)\n        for (uword x = 0; x < elems; ++x) {\n            realB->at(x) *= pow(dens->at(x), _alpha);\n        }\n        workGridB->complete(realB);        \n\n        const double eWT = _CTF * workGridB->integrate();\n\n        return eWT;\n    }\n    \n    double calcPotential(const GridType& grid, GridType& potential) const {\n\n        const cube* dens = grid.tryReadRealGrid();\n        if (!dens) {\n            // unfortunately, we need to get a copy of the grid\n            unique_ptr<GridType> workGrid = grid.duplicate();\n            dens = workGrid->readRealGrid();\n        }\n\n        unique_ptr<GridType> workGridA = grid.duplicate();\n        cube* densityA = workGridA->getRealGrid();\n\n        const uword elems = densityA->n_elem;\n        const size_t nSlices = densityA->n_slices;\n        const size_t nRows = densityA->n_rows;\n        const size_t nCols = densityA->n_cols;\n\n        auto densityB = MemoryFunctions::allocateScratch(nRows, nCols, nSlices);\n        cube* poten = potential.getRealGrid();\n\n        #pragma omp parallel for default(none) shared(densityA,densityB,poten)\n        for (uword x = 0; x < elems; ++x) {\n            const double rho = densityA->at(x);\n            const double rhoPBM = pow(rho, (_beta - 1));\n            densityB->at(x) = rhoPBM; // density B contains rho**(beta-1)\n            poten->at(x) = rhoPBM*rho; // poten contains rho**(beta)\n            densityA->at(x) = pow(rho, _alpha); // density A contains rho**(alpha)\n        }\n        potential.complete(poten);\n        workGridA->complete(densityA);\n        \n        cx_cube* recPot = potential.getReciprocalGrid();\n        \n        const uword recElems = recPot->n_elem;\n\n        #pragma omp parallel for default(none) shared(recPot)\n        for (uword x = 0; x < recElems; ++x) {\n            recPot->at(x) *= _keKernel->at(x);\n        }\n        potential.completeReciprocal(recPot);\n        \n        potential.multiplyElementwise(workGridA.get());\n\n        // get the energy\n        const double eWT = _CTF * potential.integrate();\n\n        // transform what is currently in potential into the first part of the actual potential\n        cube* realPot = potential.getRealGrid();\n\n        const double preAl = _CTF*_alpha;\n        #pragma omp parallel for default(none) shared(realPot,dens)\n        for (uword x = 0; x < elems; ++x) {\n            realPot->at(x) *= preAl / dens->at(x);\n        }\n\n        // now take what is in densityA and FFT it\n        cx_cube* recDensA = workGridA->getReciprocalGrid();\n\n        #pragma omp parallel for default(none) shared(recDensA)\n        for (size_t x = 0; x < recElems; ++x) {\n            recDensA->at(x) *= _keKernel->at(x);\n        }\n        workGridA->completeReciprocal(recDensA);\n\n        densityA = workGridA->getRealGrid();\n\n        const double preBe = _CTF*_beta;\n        #pragma omp parallel for default(none) shared(realPot,densityA,densityB)\n        for (size_t x = 0; x < elems; ++x) {\n            const double pot = densityA->at(x) * preBe * densityB->at(x);\n            realPot->at(x) += pot;\n        }\n        potential.complete(realPot);\n\n        return eWT;\n    }\n    \n    unique_ptr<StressTensor> calcStress(const GridType& grid) const {\n        throw runtime_error(\"not yet implemented\");\n    }\n\nprivate:\n\n    const double _CTF = 2.87123400018819;\n    const double _alpha;\n    const double _beta;\n    const cube * _keKernel;\n};\n\nclass WangTeterKernel {\npublic:\n    WangTeterKernel(const double alpha, const double beta, const double rho0, const double lambdaTF, const double muVW, const double ft = (5.0/3.0));\n    ~WangTeterKernel();\n    \n    void fillWTKernelReciprocal(cube* kernel, const cube* gNorms);\n    \nprivate:\n    double _alpha;\n    double _beta;\n    double _rho0;\n    double _ft;\n    double _lambda;\n    double _mu;\n    double _coeff;\n    double _tkF;\n};\n\n#ifdef LIBKEDF_OCL\n#include \"WangTeterOCL.hpp\"\n#endif\n\n#endif\t/* WANGTETER_HPP */\n\n", "meta": {"hexsha": "5b1732a1c7b67ffe5c79e72706cdc7b35c503968", "size": 7504, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/WangTeter.hpp", "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": "include/WangTeter.hpp", "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": "include/WangTeter.hpp", "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": 33.0572687225, "max_line_length": 149, "alphanum_fraction": 0.6341950959, "num_tokens": 1901, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7401743620390163, "lm_q2_score": 0.4571367168274948, "lm_q1q2_score": 0.3383608777424014}}
{"text": "#ifndef USE_CUDA\n\n#include <Spirit_Defines.h>\n#include <engine/Hamiltonian_Heisenberg_Neighbours.hpp>\n#include <engine/Vectormath.hpp>\n#include <engine/Neighbours.hpp>\n#include <data/Spin_System.hpp>\n#include <utility/Constants.hpp>\n\n#include <Eigen/Dense>\n\nusing namespace Data;\nusing namespace Utility;\nusing Utility::Constants::mu_B;\nusing Utility::Constants::mu_0;\nusing Utility::Constants::Pi;\nusing Engine::Vectormath::check_atom_type;\nusing Engine::Vectormath::idx_from_pair;\n\nnamespace Engine\n{\n    Hamiltonian_Heisenberg_Neighbours::Hamiltonian_Heisenberg_Neighbours(\n        scalarfield mu_s,\n        scalar external_field_magnitude, Vector3 external_field_normal,\n        intfield anisotropy_indices, scalarfield anisotropy_magnitudes, vectorfield anisotropy_normals,\n        scalarfield exchange_magnitudes,\n        scalarfield dmi_magnitudes, int dm_chirality,\n        scalar ddi_radius,\n        std::shared_ptr<Data::Geometry> geometry,\n        intfield boundary_conditions\n    ) :\n        Hamiltonian(boundary_conditions),\n        geometry(geometry),\n        mu_s(mu_s),\n        external_field_magnitude(external_field_magnitude * mu_B), external_field_normal(external_field_normal),\n        anisotropy_indices(anisotropy_indices), anisotropy_magnitudes(anisotropy_magnitudes), anisotropy_normals(anisotropy_normals),\n        exchange_magnitudes(exchange_magnitudes),\n        dmi_magnitudes(dmi_magnitudes),\n        ddi_radius(ddi_radius)\n    {\n        // Generate Exchange neighbours\n        exchange_neighbours = Neighbours::Get_Neighbours_in_Shells(*geometry, exchange_magnitudes.size());\n\n        // Generate DMI neighbours and normals\n        dmi_neighbours = Neighbours::Get_Neighbours_in_Shells(*geometry, dmi_magnitudes.size());\n        for (unsigned int ineigh = 0; ineigh < dmi_neighbours.size(); ++ineigh)\n        {\n            dmi_normals.push_back(Neighbours::DMI_Normal_from_Pair(*geometry, dmi_neighbours[ineigh], dm_chirality));\n        }\n\n        // Generate DDI neighbours, magnitudes and normals\n        this->ddi_neighbours = Engine::Neighbours::Get_Neighbours_in_Radius(*this->geometry, ddi_radius);\n        scalar magnitude;\n        Vector3 normal;\n        for (unsigned int i=0; i<ddi_neighbours.size(); ++i)\n        {\n            Engine::Neighbours::DDI_from_Pair(*this->geometry, ddi_neighbours[i], magnitude, normal);\n            this->ddi_magnitudes.push_back(magnitude);\n            this->ddi_normals.push_back(normal);\n        }\n\n        this->Update_Energy_Contributions();\n    }\n\n    void Hamiltonian_Heisenberg_Neighbours::Update_N_Neighbour_Shells(int n_shells_exchange, int n_shells_dmi)\n    {\n        if (this->exchange_magnitudes.size() != n_shells_exchange)\n        {\n            this->exchange_magnitudes = scalarfield(n_shells_exchange);\n            // Re-calculate exchange neighbour list\n        }\n        if (this->dmi_magnitudes.size() != n_shells_dmi)\n        {\n            this->dmi_magnitudes = scalarfield(n_shells_dmi);\n            // Re-calculate dmi neighbour list\n        }\n    }\n\n    void Hamiltonian_Heisenberg_Neighbours::Update_Energy_Contributions()\n    {\n        this->energy_contributions_per_spin = std::vector<std::pair<std::string, scalarfield>>(0);\n\n        // External field\n        if (this->external_field_magnitude > 0)\n        {\n            this->energy_contributions_per_spin.push_back({\"Zeeman\", scalarfield(0)});\n            this->idx_zeeman = this->energy_contributions_per_spin.size()-1;\n        }\n        else this->idx_zeeman = -1;\n        // Anisotropy\n        if (this->anisotropy_indices.size() > 0)\n        {\n            this->energy_contributions_per_spin.push_back({\"Anisotropy\", scalarfield(0) });\n            this->idx_anisotropy = this->energy_contributions_per_spin.size()-1;\n        }\n        else this->idx_anisotropy = -1;\n        // Exchange\n        if (this->exchange_neighbours.size() > 0)\n        {\n            this->energy_contributions_per_spin.push_back({\"Exchange\", scalarfield(0) });\n            this->idx_exchange = this->energy_contributions_per_spin.size()-1;\n        }\n        else this->idx_exchange = -1;\n        // DMI\n        if (this->dmi_neighbours.size() > 0)\n        {\n            this->energy_contributions_per_spin.push_back({\"DMI\", scalarfield(0) });\n            this->idx_dmi = this->energy_contributions_per_spin.size()-1;\n        }\n        else this->idx_dmi = -1;\n        // Dipole-Dipole\n        if (this->ddi_neighbours.size() > 0)\n        {\n            this->energy_contributions_per_spin.push_back({\"DD\", scalarfield(0) });\n            this->idx_ddi = this->energy_contributions_per_spin.size()-1;\n        }\n        else this->idx_ddi = -1;\n    }\n\n    void Hamiltonian_Heisenberg_Neighbours::Energy_Contributions_per_Spin(const vectorfield & spins, std::vector<std::pair<std::string, scalarfield>> & contributions)\n    {\n        if (contributions.size() != this->energy_contributions_per_spin.size())\n        {\n            contributions = this->energy_contributions_per_spin;\n        }\n\n        int nos = spins.size();\n        for (auto& pair : energy_contributions_per_spin)\n        {\n            // Allocate if not already allocated\n            if (pair.second.size() != nos) pair.second = scalarfield(nos, 0);\n            // Otherwise set to zero\n            else for (auto& pair : energy_contributions_per_spin) Vectormath::fill(pair.second, 0);\n        }\n\n        // External field\n        if (this->idx_zeeman >=0 )     E_Zeeman(spins, energy_contributions_per_spin[idx_zeeman].second);\n        // Anisotropy\n        if (this->idx_anisotropy >=0 ) E_Anisotropy(spins, energy_contributions_per_spin[idx_anisotropy].second);\n\n        // Exchange\n        if (this->idx_exchange >=0 )   E_Exchange(spins,energy_contributions_per_spin[idx_exchange].second);\n        // DMI\n        if (this->idx_dmi >=0 )        E_DMI(spins, energy_contributions_per_spin[idx_dmi].second);\n        // DDI\n        if (this->idx_ddi >=0 )        E_DDI(spins, energy_contributions_per_spin[idx_ddi].second);\n    }\n\n    void Hamiltonian_Heisenberg_Neighbours::E_Zeeman(const vectorfield & spins, scalarfield & Energy)\n    {\n        const int N = geometry->n_cell_atoms;\n\n        #pragma omp parallel for\n        for (int icell = 0; icell < geometry->n_cells_total; ++icell)\n        {\n            for (int ibasis = 0; ibasis < N; ++ibasis)\n            {\n                int ispin = icell*N + ibasis;\n                if (check_atom_type(this->geometry->atom_types[ispin]))\n                    Energy[ispin] -= this->mu_s[ibasis] * this->external_field_magnitude * this->external_field_normal.dot(spins[ispin]);\n            }\n        }\n    }\n\n    void Hamiltonian_Heisenberg_Neighbours::E_Anisotropy(const vectorfield & spins, scalarfield & Energy)\n    {\n        const int N = geometry->n_cell_atoms;\n\n        #pragma omp parallel for\n        for (int icell = 0; icell < geometry->n_cells_total; ++icell)\n        {\n            for (int iani = 0; iani < anisotropy_indices.size(); ++iani)\n            {\n                int ispin = icell*N + anisotropy_indices[iani];\n                if (check_atom_type(this->geometry->atom_types[ispin]))\n                    Energy[ispin] -= this->anisotropy_magnitudes[iani] * std::pow(anisotropy_normals[iani].dot(spins[ispin]), 2.0);\n            }\n        }\n    }\n\n    void Hamiltonian_Heisenberg_Neighbours::E_Exchange(const vectorfield & spins, scalarfield & Energy)\n    {\n        #pragma omp parallel for\n        for (unsigned int ispin = 0; ispin < spins.size(); ++ispin)\n        {\n            // auto translations = Vectormath::translations_from_idx(geometry->n_cells, geometry->n_cell_atoms, ispin);\n            for (unsigned int ineigh = 0; ineigh < exchange_neighbours.size(); ++ineigh)\n            {\n                int jspin = idx_from_pair(ispin, boundary_conditions, geometry->n_cells, geometry->n_cell_atoms, geometry->atom_types, exchange_neighbours[ineigh]);\n                if ( jspin >= 0 )\n                {\n                    auto& ishell = exchange_neighbours[ineigh].idx_shell;\n                    Energy[ispin] -= 0.5 * exchange_magnitudes[ishell] * spins[ispin].dot(spins[jspin]);\n                }\n            }\n        }\n    }\n\n    void Hamiltonian_Heisenberg_Neighbours::E_DMI(const vectorfield & spins, scalarfield & Energy)\n    {\n        #pragma omp parallel for\n        for (unsigned int ispin = 0; ispin < spins.size(); ++ispin)\n        {\n            for (unsigned int ineigh = 0; ineigh < dmi_neighbours.size(); ++ineigh)\n            {\n                int jspin = idx_from_pair(ispin, boundary_conditions, geometry->n_cells, geometry->n_cell_atoms, geometry->atom_types, dmi_neighbours[ineigh]);\n                if ( jspin >= 0 )\n                {\n                    auto& ishell = dmi_neighbours[ineigh].idx_shell;\n                    Energy[ispin] -= 0.5 * dmi_magnitudes[ishell] * dmi_normals[ineigh].dot(spins[ispin].cross(spins[jspin]));\n                }\n            }\n        }\n    }\n\n    void Hamiltonian_Heisenberg_Neighbours::E_DDI(const vectorfield & spins, scalarfield & Energy)\n    {\n        // The translations are in angstr�m, so the |r|[m] becomes |r|[m]*10^-10\n        const scalar mult = mu_0 * std::pow(mu_B, 2) / ( 4*Pi * 1e-30 );\n\n        scalar result = 0.0;\n        const int N = geometry->n_cell_atoms;\n\n        #pragma omp parallel for\n        for (int icell = 0; icell < geometry->n_cells_total; ++icell)\n        {\n            for (int ibasis = 0; ibasis < N; ++ibasis)\n            {\n                int ispin = icell * N + ibasis;\n                for (unsigned int ineigh = 0; ineigh < ddi_neighbours.size(); ++ineigh)\n                {\n                    if (ddi_magnitudes[ineigh] > 0.0)\n                    {\n                        int jbasis = ddi_neighbours[ineigh].j;\n                        int jspin = idx_from_pair(ispin, boundary_conditions, geometry->n_cells, geometry->n_cell_atoms, geometry->atom_types, ddi_neighbours[ineigh]);\n                        if (jspin >= 0)\n                        {\n                            Energy[ispin] -= 0.5 * this->mu_s[ibasis] * this->mu_s[jbasis] * mult / std::pow(ddi_magnitudes[ineigh], 3.0) *\n                                (3 * spins[jspin].dot(ddi_normals[ineigh]) * spins[ispin].dot(ddi_normals[ineigh]) - spins[ispin].dot(spins[jspin]));\n                            Energy[jspin] -= 0.5 * this->mu_s[ibasis] * this->mu_s[jbasis] * mult / std::pow(ddi_magnitudes[ineigh], 3.0) *\n                                (3 * spins[jspin].dot(ddi_normals[ineigh]) * spins[ispin].dot(ddi_normals[ineigh]) - spins[ispin].dot(spins[jspin]));\n                        }\n                    }\n                }\n            }\n        }\n    }// end DipoleDipole\n\n\n\n    void Hamiltonian_Heisenberg_Neighbours::Gradient(const vectorfield & spins, vectorfield & gradient)\n    {\n        // Set to zero\n        Vectormath::fill(gradient, {0,0,0});\n\n        // External field\n        Gradient_Zeeman(gradient);\n\n        // Anisotropy\n        Gradient_Anisotropy(spins, gradient);\n\n        // Exchange\n        this->Gradient_Exchange(spins, gradient);\n        // DMI\n        this->Gradient_DMI(spins, gradient);\n        // DD\n        this->Gradient_DDI(spins, gradient);\n    }\n\n    void Hamiltonian_Heisenberg_Neighbours::Gradient_Zeeman(vectorfield & gradient)\n    {\n        const int N = geometry->n_cell_atoms;\n\n        #pragma omp parallel for\n        for (int icell = 0; icell < geometry->n_cells_total; ++icell)\n        {\n            for (int ibasis = 0; ibasis < N; ++ibasis)\n            {\n                int ispin = icell*N + ibasis;\n                if (check_atom_type(this->geometry->atom_types[ispin]))\n                    gradient[ispin] -= this->mu_s[ibasis] * this->external_field_magnitude * this->external_field_normal;\n            }\n        }\n    }\n\n    void Hamiltonian_Heisenberg_Neighbours::Gradient_Anisotropy(const vectorfield & spins, vectorfield & gradient)\n    {\n        const int N = geometry->n_cell_atoms;\n\n        #pragma omp parallel for\n        for (int icell = 0; icell < geometry->n_cells_total; ++icell)\n        {\n            for (int iani = 0; iani < anisotropy_indices.size(); ++iani)\n            {\n                int ispin = icell*N + anisotropy_indices[iani];\n                if (check_atom_type(this->geometry->atom_types[ispin]))\n                    gradient[ispin] -= 2.0 * this->anisotropy_magnitudes[iani] * this->anisotropy_normals[iani] * anisotropy_normals[iani].dot(spins[ispin]);\n            }\n        }\n    }\n\n    void Hamiltonian_Heisenberg_Neighbours::Gradient_Exchange(const vectorfield & spins, vectorfield & gradient)\n    {\n        #pragma omp parallel for\n        for (unsigned int ispin = 0; ispin < spins.size(); ++ispin)\n        {\n            for (unsigned int ineigh = 0; ineigh < exchange_neighbours.size(); ++ineigh)\n            {\n                int jspin = idx_from_pair(ispin, boundary_conditions, geometry->n_cells, geometry->n_cell_atoms, geometry->atom_types, exchange_neighbours[ineigh]);\n                if ( jspin >= 0 )\n                {\n                    auto& ishell = exchange_neighbours[ineigh].idx_shell;\n                    gradient[ispin] -= exchange_magnitudes[ishell] * spins[jspin];\n                }\n            }\n        }\n    }\n\n    void Hamiltonian_Heisenberg_Neighbours::Gradient_DMI(const vectorfield & spins, vectorfield & gradient)\n    {\n        #pragma omp parallel for\n        for (unsigned int ispin = 0; ispin < spins.size(); ++ispin)\n        {\n            auto translations = Vectormath::translations_from_idx(geometry->n_cells, geometry->n_cell_atoms, ispin);\n            for (unsigned int ineigh = 0; ineigh < dmi_neighbours.size(); ++ineigh)\n            {\n                int jspin = idx_from_pair(ispin, boundary_conditions, geometry->n_cells, geometry->n_cell_atoms, geometry->atom_types, dmi_neighbours[ineigh]);\n                if ( jspin >= 0 )\n                {\n                    auto& ishell = dmi_neighbours[ineigh].idx_shell;\n                    gradient[ispin] -= dmi_magnitudes[ishell] * spins[jspin].cross(dmi_normals[ineigh]);\n                }\n            }\n        }\n    }\n\n    void Hamiltonian_Heisenberg_Neighbours::Gradient_DDI(const vectorfield & spins, vectorfield & gradient)\n    {\n        // The translations are in angstr�m, so the |r|[m] becomes |r|[m]*10^-10\n        const scalar mult = mu_0 * std::pow(mu_B, 2) / ( 4*Pi * 1e-30 );\n\n        const int N = geometry->n_cell_atoms;\n        \n        #pragma omp parallel for\n        for (int icell = 0; icell < geometry->n_cells_total; ++icell)\n        {\n            for (int ibasis = 0; ibasis < N; ++ibasis)\n            {\n                int ispin = icell * N + ibasis;\n                for (unsigned int ineigh = 0; ineigh < ddi_neighbours.size(); ++ineigh)\n                {\n                    if (ddi_magnitudes[ineigh] > 0.0)\n                    {\n                        int jbasis = ddi_neighbours[ineigh].j;\n                        int jspin = idx_from_pair(ispin, boundary_conditions, geometry->n_cells, geometry->n_cell_atoms, geometry->atom_types, ddi_neighbours[ineigh]);\n                        if (jspin >= 0)\n                        {\n                            scalar skalar_contrib = mult / std::pow(ddi_magnitudes[ineigh], 3.0);\n                            gradient[ispin] -= this->mu_s[jbasis] * skalar_contrib * (3 * ddi_normals[ineigh] * spins[jspin].dot(ddi_normals[ineigh]) - spins[jspin]);\n                            gradient[jspin] -= this->mu_s[ibasis] * skalar_contrib * (3 * ddi_normals[ineigh] * spins[ispin].dot(ddi_normals[ineigh]) - spins[ispin]);\n                        }\n                    }\n                }\n            }\n        }\n    }//end Field_DipoleDipole\n\n\n    void Hamiltonian_Heisenberg_Neighbours::Hessian(const vectorfield & spins, MatrixX & hessian)\n    {\n        int nos = spins.size();\n\n        // Set to zero\n        // for (auto& h : hessian) h = 0;\n        hessian.setZero();\n\n        // Single Spin elements\n        for (int alpha = 0; alpha < 3; ++alpha)\n        {\n            for (unsigned int i = 0; i < anisotropy_indices.size(); ++i)\n            {\n                int idx = anisotropy_indices[i];\n                // scalar x = -2.0*this->anisotropy_magnitudes[i] * std::pow(this->anisotropy_normals[i][alpha], 2);\n                hessian(3*idx + alpha, 3*idx + alpha) += -2.0*this->anisotropy_magnitudes[i]*std::pow(this->anisotropy_normals[i][alpha],2);\n            }\n        }\n\n        // std::cerr << \"calculated hessian\" << std::endl;\n\n        // Spin Pair elements\n        // Exchange\n        for (unsigned int ispin = 0; ispin < spins.size(); ++ispin)\n        {\n            auto translations = Vectormath::translations_from_idx(geometry->n_cells, geometry->n_cell_atoms, ispin);\n            for (unsigned int ineigh = 0; ineigh < this->exchange_neighbours.size(); ++ineigh)\n            {\n                for (int alpha = 0; alpha < 3; ++alpha)\n                {\n                    //int idx_i = 3 * exchange_neighbours[i_pair][0] + alpha;\n                    //int idx_j = 3 * exchange_neighbours[i_pair][1] + alpha;\n                    int jspin = Vectormath::idx_from_translations(geometry->n_cells, geometry->n_cell_atoms, translations, exchange_neighbours[ineigh].translations);\n                    int ishell = exchange_neighbours[ineigh].idx_shell;\n                    hessian(ispin, jspin) += -exchange_magnitudes[ineigh];\n                    hessian(jspin, ispin) += -exchange_magnitudes[ineigh];\n                }\n            }\n        }\n        // DMI\n        for (unsigned int ispin = 0; ispin < spins.size(); ++ispin)\n        {\n            auto translations = Vectormath::translations_from_idx(geometry->n_cells, geometry->n_cell_atoms, ispin);\n            for (unsigned int ineigh = 0; ineigh < this->dmi_neighbours.size(); ++ineigh)\n            {\n                for (int alpha = 0; alpha < 3; ++alpha)\n                {\n                    for (int beta = 0; beta < 3; ++beta)\n                    {\n                        int idx_i = 3 * dmi_neighbours[ineigh].i + alpha;\n                        int idx_j = 3 * dmi_neighbours[ineigh].j + beta;\n                        if ((alpha == 0 && beta == 1))\n                        {\n                            hessian(idx_i, idx_j) +=\n                                -dmi_magnitudes[ineigh] * dmi_normals[ineigh][2];\n                            hessian(idx_j, idx_i) +=\n                                -dmi_magnitudes[ineigh] * dmi_normals[ineigh][2];\n                        }\n                        else if ((alpha == 1 && beta == 0))\n                        {\n                            hessian(idx_i, idx_j) +=\n                                dmi_magnitudes[ineigh] * dmi_normals[ineigh][2];\n                            hessian(idx_j, idx_i) +=\n                                dmi_magnitudes[ineigh] * dmi_normals[ineigh][2];\n                        }\n                        else if ((alpha == 0 && beta == 2))\n                        {\n                            hessian(idx_i, idx_j) +=\n                                dmi_magnitudes[ineigh] * dmi_normals[ineigh][1];\n                            hessian(idx_j, idx_i) +=\n                                dmi_magnitudes[ineigh] * dmi_normals[ineigh][1];\n                        }\n                        else if ((alpha == 2 && beta == 0))\n                        {\n                            hessian(idx_i, idx_j) +=\n                                -dmi_magnitudes[ineigh] * dmi_normals[ineigh][1];\n                            hessian(idx_j, idx_i) +=\n                                -dmi_magnitudes[ineigh] * dmi_normals[ineigh][1];\n                        }\n                        else if ((alpha == 1 && beta == 2))\n                        {\n                            hessian(idx_i, idx_j) +=\n                                -dmi_magnitudes[ineigh] * dmi_normals[ineigh][0];\n                            hessian(idx_j, idx_i) +=\n                                -dmi_magnitudes[ineigh] * dmi_normals[ineigh][0];\n                        }\n                        else if ((alpha == 2 && beta == 1))\n                        {\n                            hessian(idx_i, idx_j) +=\n                                dmi_magnitudes[ineigh] * dmi_normals[ineigh][0];\n                            hessian(idx_j, idx_i) +=\n                                dmi_magnitudes[ineigh] * dmi_normals[ineigh][0];\n                        }\n                    }\n                }\n            }\n        }\n        //// Dipole-Dipole\n        //for (unsigned int i_pair = 0; i_pair < this->ddi_neighbours[i_periodicity].size(); ++i_pair)\n        //{\n        //\t// indices\n        //\tint idx_1 = ddi_neighbours[i_periodicity][i_pair][0];\n        //\tint idx_2 = ddi_neighbours[i_periodicity][i_pair][1];\n        //\t// prefactor\n        //\tscalar prefactor = 0.0536814951168\n        //\t\t* this->mu_s[idx_1] * this->mu_s[idx_2]\n        //\t\t/ std::pow(ddi_magnitude[i_periodicity][i_pair], 3);\n        //\t// components\n        //\tfor (int alpha = 0; alpha < 3; ++alpha)\n        //\t{\n        //\t\tfor (int beta = 0; beta < 3; ++beta)\n        //\t\t{\n        //\t\t\tint idx_h = idx_1 + alpha*nos + 3 * nos*(idx_2 + beta*nos);\n        //\t\t\tif (alpha == beta)\n        //\t\t\t\thessian[idx_h] += prefactor;\n        //\t\t\thessian[idx_h] += -3.0*prefactor*DD_normal[i_periodicity][i_pair][alpha] * DD_normal[i_periodicity][i_pair][beta];\n        //\t\t}\n        //\t}\n        //}\n    }\n\n    // Hamiltonian name as string\n    static const std::string name = \"Heisenberg (Neighbours)\";\n    const std::string& Hamiltonian_Heisenberg_Neighbours::Name() { return name; }\n}\n\n#endif", "meta": {"hexsha": "47fc7f676382970c6525183f38f5b93280f07036", "size": 21637, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "core/src/engine/Hamiltonian_Heisenberg_Neighbours.cpp", "max_stars_repo_name": "SpiritSuperUser/spirit", "max_stars_repo_head_hexsha": "fbe69c2a9b7a73e8f47d302c619303aea2a22ace", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-11-12T13:54:22.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-05T09:10:27.000Z", "max_issues_repo_path": "core/src/engine/Hamiltonian_Heisenberg_Neighbours.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/engine/Hamiltonian_Heisenberg_Neighbours.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": 43.7111111111, "max_line_length": 167, "alphanum_fraction": 0.5566390904, "num_tokens": 5466, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7401743620390163, "lm_q2_score": 0.4571367168274948, "lm_q1q2_score": 0.3383608777424014}}
{"text": "#include \"resource.hpp\"\n\n#include \"instance.hpp\"\n#include \"traits.hpp\"\n\n#include <algorithm>\n#include <boost/container/small_vector.hpp>\n#include <cassert> // for assert\n#include <cmath>   // for pow\n#include <iterator>\n#include <memory>\n#include <pstl/glue_algorithm_defs.h>\n#include <stdexcept>\n\n// TODO factor polynomial stuff out into util\ndouble\napply_polynomial(const polynomial & poly, double x)\n{\n\tdouble sum = 0;\n\tfor (auto term : poly) {\n\t\tsum += std::get<0>(term) * std::pow(x, std::get<1>(term));\n\t}\n\treturn sum;\n}\n\npolynomial\nadd_poly(const polynomial & lhs, const polynomial & rhs)\n{\n\tpolynomial result(lhs.begin(), lhs.end());\n\tresult.insert(result.end(), rhs.begin(), rhs.end());\n\tstd::sort(result.begin(), result.end(),\n\t          [](const poly_term & sort_lhs, const poly_term & sort_rhs) {\n\t\t          return sort_lhs.second < sort_rhs.second;\n\t          });\n\n\tsize_t len = result.size();\n\tfor (size_t i = 0; (len > 0) && (i < (len - 1)); ++i) {\n\t\t// TODO float-equal comparison.\n\t\tif (double_eq(result[i].second, result[i + 1].second)) {\n\t\t\t// Equal exponents. Combine, mark for swap-and-delete\n\t\t\tresult[i].first += result[i + 1].first;\n\t\t\tresult[i + 1].first = 0;\n\t\t\ti++;\n\t\t}\n\t}\n\n\tauto new_end =\n\t    std::remove_if(result.begin(), result.end(), [](const poly_term & t) {\n\t\t    return double_eq(t.first, 0.0);\n\t    });\n\tresult.erase(new_end, result.end());\n\n\treturn result;\n}\n// TODO test add_poly\n\nResource::Resource(unsigned int id)\n    : rid(id), availability(0), overshoot_costs({})\n{}\n\nResource\nResource::clone() const\n{\n\tResource cloned(this->rid);\n\tcloned.set_availability(Availability(this->availability));\n\tcloned.set_investment_costs(this->investment_costs);\n\tcloned.set_overshoot_costs(FlexCost(this->overshoot_costs));\n\n\treturn cloned;\n}\n\nvoid\nResource::set_availability(Availability && availability_in)\n{\n\tthis->availability = std::move(availability_in);\n}\n\nconst Availability &\nResource::get_availability() const\n{\n\treturn this->availability;\n}\n\nunsigned int\nResource::get_rid()\n{\n\treturn this->rid;\n}\n\nvoid\nResource::set_id(unsigned int id)\n{\n\tthis->rid = id;\n}\n\nvoid\nResource::set_investment_costs(polynomial costs)\n{\n\tthis->investment_costs = costs;\n}\n\nvoid\nResource::set_overshoot_costs(FlexCost && costs)\n{\n\tthis->overshoot_costs = std::move(costs);\n}\n\nconst polynomial &\nResource::get_investment_costs() const\n{\n\treturn this->investment_costs;\n}\n\nconst polynomial &\nResource::get_overshoot_costs() const\n{\n\treturn this->overshoot_costs.get_base();\n}\n\nconst FlexCost &\nResource::get_flex_overshoot() const\n{\n\treturn this->overshoot_costs;\n}\n\nconst polynomial &\nResource::get_overshoot_costs(unsigned int pos) const\n{\n\treturn this->overshoot_costs.get_at(pos);\n}\n\nbool\nResource::is_overshoot_flat() const\n{\n\treturn this->overshoot_costs.is_flat();\n}\n\nFlexCost::FlexCost(polynomial base_in) : base(std::move(base_in)) {}\n\nbool\nFlexCost::is_flat() const\n{\n\treturn this->points.empty();\n}\n\nconst polynomial &\nFlexCost::get_base() const noexcept\n{\n\treturn this->base;\n}\n\nvoid\nFlexCost::set_flexible(\n    std::vector<std::pair<unsigned int, polynomial>> && new_points)\n{\n\tif (this->base.empty()) {\n\t\tthis->points = std::move(new_points);\n\t} else {\n\t\tthis->points.reserve(new_points.size());\n\t\tthis->points.clear();\n\n\t\tstd::transform(new_points.begin(), new_points.end(),\n\t\t               std::back_inserter(this->points),\n\t\t               [&](const std::pair<unsigned int, polynomial> point) {\n\t\t\t               return std::pair<unsigned int, polynomial>(\n\t\t\t                   point.first, add_poly(this->base, point.second));\n\t\t               });\n\t}\n}\n\nconst polynomial &\nFlexCost::get_at(unsigned int pos) const noexcept\n{\n\tif (this->points.empty()) {\n\t\treturn this->base;\n\t} else {\n\n\t\t/* This comparator inverses comparison s.t. we can just use\n\t\t * lower_bound on the reversed points to find the correct point. */\n\t\tstruct Comp\n\t\t{\n\t\t\tbool\n\t\t\toperator()(const std::pair<unsigned int, polynomial> & lhs,\n\t\t\t           unsigned int rhs) const noexcept\n\t\t\t{\n\t\t\t\treturn lhs.first > rhs;\n\t\t\t}\n\t\t\tbool\n\t\t\toperator()(unsigned int lhs,\n\t\t\t           const std::pair<unsigned int, polynomial> & rhs) const noexcept\n\t\t\t{\n\t\t\t\treturn lhs > rhs.first;\n\t\t\t}\n\t\t};\n\n\t\tauto it = std::lower_bound(this->points.rbegin(), this->points.rend(), pos,\n\t\t                           Comp{});\n\t\tif (it == this->points.rend()) {\n\t\t\treturn this->base;\n\t\t} else {\n\t\t\treturn it->second;\n\t\t}\n\t}\n}\n// TODO test get_at\n\nstd::vector<std::pair<unsigned int, polynomial>>::const_iterator\nFlexCost::begin() const\n{\n\treturn this->points.begin();\n}\nstd::vector<std::pair<unsigned int, polynomial>>::const_iterator\nFlexCost::end() const\n{\n\treturn this->points.end();\n}\n\nAvailability::Availability(double start_amount) : points(1, {0, start_amount})\n{}\n\ndouble\nAvailability::get_at(unsigned int pos) const noexcept\n{\n\tif (this->points.empty()) {\n\t\treturn 0;\n\t} else {\n\n\t\t/* This comparator inverses comparison s.t. we can just use\n\t\t * lower_bound on the reversed points to find the correct point. */\n\t\tstruct Comp\n\t\t{\n\t\t\tbool\n\t\t\toperator()(const std::pair<unsigned int, double> & lhs,\n\t\t\t           unsigned int rhs) const noexcept\n\t\t\t{\n\t\t\t\treturn lhs.first > rhs;\n\t\t\t}\n\t\t\tbool\n\t\t\toperator()(unsigned int lhs,\n\t\t\t           const std::pair<unsigned int, double> & rhs) const noexcept\n\t\t\t{\n\t\t\t\treturn lhs > rhs.first;\n\t\t\t}\n\t\t};\n\n\t\tauto it = std::lower_bound(this->points.rbegin(), this->points.rend(), pos,\n\t\t                           Comp{});\n\t\tif (it == this->points.rend()) {\n\t\t\treturn 0.0;\n\t\t} else {\n\t\t\treturn it->second;\n\t\t}\n\t}\n}\n\nvoid\nAvailability::set(std::vector<std::pair<unsigned int, double>> && new_points)\n{\n\tthis->points = std::move(new_points);\n}\n\nstd::vector<std::pair<unsigned int, double>>::const_iterator\nAvailability::begin() const\n{\n\treturn this->points.begin();\n}\n\nstd::vector<std::pair<unsigned int, double>>::const_iterator\nAvailability::end() const\n{\n\treturn this->points.end();\n}\n\ndouble\nAvailability::get_flat_available() const\n{\n\tassert(this->points.size() == 1);\n\treturn this->points[0].second;\n}\n\nResources::Resources() {}\n\nResources::Resources(double _usage) : usage{_usage} {}\n\nResources::Resources(const Instance * in, const ResVec & u)\n    : instance(in), usage(u)\n{\n\tif (in == NULL && u.size() > 1) {\n\t\tthrow std::invalid_argument(\"Instance in is NULL\");\n\t} else if (u.size() > 1 &&\n\t           !in->get_traits().has_flag(Traits::FLAT_AVAILABILITY)) {\n\t\tthrow TraitUnfulfilledError(\"FLAT_AVAILABILITY required!\");\n\t}\n}\n\nResources::Resources(const Instance * in, const std::vector<double> & u)\n    : instance(in), usage(u.begin(), u.end())\n{\n\tif (in == NULL && u.size() > 1) {\n\t\tthrow std::invalid_argument(\"Instance in is NULL\");\n\t} else if (u.size() > 1 &&\n\t           !in->get_traits().has_flag(Traits::FLAT_AVAILABILITY)) {\n\t\tthrow TraitUnfulfilledError(\"FLAT_AVAILABILITY required!\");\n\t}\n}\n\nResources::Resources(const Instance * in, ResVec && u)\n    : instance(in), usage(std::move(u))\n{\n\tif (in == NULL && u.size() > 1) {\n\t\tthrow std::invalid_argument(\"Instance in is NULL\");\n\t} else if (u.size() > 1 &&\n\t           !in->get_traits().has_flag(Traits::FLAT_AVAILABILITY)) {\n\t\tthrow TraitUnfulfilledError(\"FLAT_AVAILABILITY required!\");\n\t}\n}\n\nResources::Resources(const Instance * in)\n    : instance(in), usage(in->resource_count(), 0.0)\n{}\n\nconst ResVec &\nResources::getUsage() const\n{\n\treturn usage;\n}\n\nResVec &\nResources::getUsage()\n{\n\treturn usage;\n}\n\nResources\nResources::operator+(const Resources & other) const\n{\n\tResources res(*this);\n\tres += other;\n\treturn res;\n}\n\nResources\nResources::operator-(const Resources & other) const\n{\n\tResources res(*this);\n\tres -= other;\n\treturn res;\n}\n\nResources\nResources::operator*(const Resources & other) const\n{\n\tResources res(*this);\n\tres *= other;\n\treturn res;\n}\n\nResources\nResources::operator/(const Resources & other) const\n{\n\tResources res(*this);\n\tres /= other;\n\treturn res;\n}\n\nvoid\nResources::operator+=(const Resources & other)\n{\n\tif (instance == NULL) {\n\t\tinstance = other.instance;\n\t}\n\tif (usage.size() < other.usage.size()) {\n\t\tusage.resize(other.usage.size());\n\t}\n\tfor (size_t i = 0; i < other.usage.size(); i++) {\n\t\tusage[i] += other.usage[i];\n\t}\n}\n\nvoid\nResources::operator*=(const Resources & other)\n{\n\tif (instance == NULL) {\n\t\tinstance = other.instance;\n\t}\n\tif (usage.size() < other.usage.size()) {\n\t\tusage.resize(other.usage.size());\n\t}\n\tfor (size_t i = 0; i < other.usage.size(); i++) {\n\t\tusage[i] *= other.usage[i];\n\t}\n}\n\nvoid\nResources::operator/=(const Resources & other)\n{\n\tif (instance == NULL) {\n\t\tinstance = other.instance;\n\t}\n\tif (usage.size() < other.usage.size()) {\n\t\tusage.resize(other.usage.size());\n\t}\n\tfor (size_t i = 0; i < other.usage.size(); i++) {\n\t\tusage[i] /= other.usage[i];\n\t}\n}\n\nvoid\nResources::operator-=(const Resources & other)\n{\n\tif (instance == NULL) {\n\t\tinstance = other.instance;\n\t}\n\tif (usage.size() < other.usage.size()) {\n\t\tusage.resize(other.usage.size());\n\t}\n\tfor (size_t i = 0; i < other.usage.size(); i++) {\n\t\tusage[i] -= other.usage[i];\n\t}\n}\n\nbool\nResources::operator<(const Resources & other) const\n{\n\treturn this->getCosts() < other.getCosts();\n}\n\nbool\nResources::operator>(const Resources & other) const\n{\n\treturn this->getCosts() > other.getCosts();\n}\n\nbool\nResources::operator<=(const Resources & other) const\n{\n\treturn this->getCosts() <= other.getCosts();\n}\n\nbool\nResources::operator>=(const Resources & other) const\n{\n\treturn this->getCosts() >= other.getCosts();\n}\n\nbool\nResources::operator!=(const Resources & other) const\n{\n\treturn this->usage != other.usage;\n}\n\nbool\nResources::operator==(const Resources & other) const\n{\n\treturn this->usage == other.usage;\n}\n\ndouble\nResources::getCosts() const\n{\n\tif (usage.size() == 0) {\n\t\treturn 0;\n\t} else if (usage.size() == 1) {\n\t\treturn usage[0];\n\t} else if (!cached) {\n\t\tcache = instance->calculate_costs(usage);\n\t\tcached = true;\n\t}\n\treturn cache;\n}\n", "meta": {"hexsha": "38af33fe2104143222d4bfa20f839d5d50325fbf", "size": 9843, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/instance/resource.cpp", "max_stars_repo_name": "kit-algo/TCPSPSuite", "max_stars_repo_head_hexsha": "01499b4fb0f28bda72115a699cd762c70d7fff63", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2018-05-02T11:45:57.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-14T08:35:43.000Z", "max_issues_repo_path": "src/instance/resource.cpp", "max_issues_repo_name": "kit-algo/TCPSPSuite", "max_issues_repo_head_hexsha": "01499b4fb0f28bda72115a699cd762c70d7fff63", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/instance/resource.cpp", "max_forks_repo_name": "kit-algo/TCPSPSuite", "max_forks_repo_head_hexsha": "01499b4fb0f28bda72115a699cd762c70d7fff63", "max_forks_repo_licenses": ["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.898089172, "max_line_length": 78, "alphanum_fraction": 0.6581326831, "num_tokens": 2558, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7401743505760728, "lm_q2_score": 0.4571367168274948, "lm_q1q2_score": 0.33836087250226904}}
{"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_PREFERRED_REASONER_HPP\n#define DUNG_PREFERRED_REASONER_HPP\n\n#include <iostream>\n#include <string>\n#include <utility>   \n#include <algorithm>   \n\n//boost\n#include <boost/graph/graph_traits.hpp> \n#include <boost/graph/adjacency_list.hpp>\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#include \"DungAF.hpp\"\n#include \"Reasoner.hpp\"\n\n\nnamespace argumatrix{\n\nusing namespace std;\n\n/**\n* This reasoner for Dung theories performs inference on the preferred extension.\n* Computes the (unique) grounded extension, i.e., the least fixpoint of \n* the characteristic function.\n*/\nclass PreferredReasoner : public Reasoner {\npublic:\n\tPreferredReasoner(const DungAF& daf, streambuf* osbuff = std::cout.rdbuf())\n\t\t: Reasoner(daf, osbuff) {\n\t\t// m_argNum = m_daf.getNumberOfArguments();\n\t\t// m_BmAtkMtx = m_daf.getAttackMatrix();\n\t\tm_attackedBy = m_BmAtkMtx.transpose();\n\t}\n\n\t/**\n\t * Compute all extensions given a specific semantics. Each extension is a set \n\t * of arguments. Here, we use a bitvector to represent an extension. The results\n\t * are stored in m_extensions. When a new extension bv is computed, it can be added\n\t * to m_extensions by m_extensions.push_back(bv).\n\t * @return no return. The results are stored in m_extensions.\n\t */\n\tvoid computeExtensions();\n\n\t/**\n\t * Get attackers of arguments in _bv, R^-(S) \n\t * R^-(S) = {x|x attacks some argument in S}.\n\t * R^-(S_bv) = D^T*S_bv \n\t * @param _bv the bitvector of a set of arguments S.\n\t * @return a set of arguments in bitvector form.\n\t */\n\tbitvector getAttackers(const bitvector& _bv);\n\nprivate:\n\tenum SELECT_TYPE { TYPE_A, TYPE_B };\n\tenum LABELS { BLANK = 0, _IN_, _OUT_, MUST_OUT, UNDEC, Label_Num };\n\n\t/**\n\t * Before computing the preferred extension, we will preprocess all arguments\n\t * by assigning initial labels to some arguments for reducing search space. \n\t * The preprocessing operations contain (1) setting all self-attacking arguments\n\t * with OUT label; (2) setting all unattacked arguments with IN label; \n\t * (3) setting all arguments attacked by IN-label arguments with OUT label; \n\t * Lastly, all arguments labeled IN or OUT will be removed from BLANK.\n\t */\n\tvoid preprocessing(bitvector& _blank, bitvector& _in, bitvector& _out, bitvector& _undec);\n\n\tvoid findPreferredExtensions(bitvector& _blank, bitvector& _in, \n\t\t\tbitvector& _out, bitvector& _undec, bitvector& _must_out);\n\n\tbool lookAhead(bitvector& _blank_new, bitvector& _tmp_must_out);\n\n\tpair<size_type, SELECT_TYPE> selectArgument(const bitvector& _blank, const bitvector& _in, \n\t\tconst bitvector& _out, const bitvector& _undec, const bitvector& _must_out);\n\nprivate:\n\t/**\n\t * The transpose of the attack matrix, it provides an effective way to\n\t * access all attacked arguments of a given argument. The attacked arguments\n\t * of the argument with index i is m_attackedBy[i].\t\n\t */\n\tbitmatrix m_attackedBy;\n\n};  // class GroundedReasoner\n\nvoid PreferredReasoner::computeExtensions()\n{\n\tm_extensions.clear();\n\n\t// We using five bitvector to encode the labellings of all arguments. \n\t// Each argument is merely labeled with one of the following five labellings.\n\tbitvector _blank = bitvector::UniversalSet(m_argNum);  // At beginning, all arguments are labeled BLANK\n\tbitvector _out = bitvector::EmptySet(m_argNum);   // Empty set\n\tbitvector _in = bitvector::EmptySet(m_argNum);\n\tbitvector _must_out = bitvector::EmptySet(m_argNum);\n\tbitvector _undec = bitvector::EmptySet(m_argNum);\n\n\t// Preprocessing\n\tpreprocessing(_blank, _in, _out, _undec);\n\n\tfindPreferredExtensions(_blank, _in, _out, _undec, _must_out);\n}\n\nvoid PreferredReasoner::preprocessing(bitvector& _blank, bitvector& _in, bitvector& _out, bitvector& _undec)\n{\n\t// setting all self-attacking arguments with OUT label\n\t// _out |= m_attackMatrix.diag();\n\t_undec |= getSelfAttackingArguments();\n\n\t// getting all unattacked arguments by characteristic function\n\t_in |= characteristic(bitvector::EmptySet(m_argNum));\n\n\t// setting all arguments, attacked by IN-label arguments, with OUT label; \n\t_out |= getAttacked(_in);\n\n\t// Removing IN and OUT from BLANK\n\t// _blank ^= (_in|_out);\n\t_blank -= _in;\n\t_blank -= _out;\n\t_blank -= _undec;\n}\n\nvoid PreferredReasoner::findPreferredExtensions(bitvector& _blank, \n\t\tbitvector& _in, bitvector& _out, bitvector& _undec, bitvector& _must_out)\n{\n\tsize_type i;\n\tSELECT_TYPE _s_type;\n\n\tboost::tie(i, _s_type) = selectArgument(_blank, _in, _out, _undec, _must_out);\n\n\twhile (i != bitvector::npos)\n\t{\n\t\tbitvector _blank_new(_blank);\n\t\tbitvector _out_new(_out);\n\t\tbitvector _in_new(_in);\n\t\tbitvector _must_out_new(_must_out);\n\t\tbitvector _undec_new(_undec);\n\n\t\t_in_new[i] = true; _blank_new[i] = false;  // label i with IN\n\n\t\t_out_new |= m_attackedBy[i];\n\t\t_blank_new -= m_attackedBy[i];\n\t\t_undec_new -= m_attackedBy[i];\n\t\t_must_out_new -= m_attackedBy[i];\n\n\t\t// get argument i's attackers which are labeled by BLANK or UNDEC\n\t\tbitvector _tmp_must_out( m_BmAtkMtx[i]&(_blank_new|_undec_new) );\n\t\t_must_out_new |= _tmp_must_out;\n\t\t_blank_new -= _tmp_must_out;\n\t\t_undec_new -= _tmp_must_out;\n\n\t\t//bool forwardCheck = lookAhead(_blank_new, _tmp_must_out);\n\t\tbool forwardCheck = lookAhead(_blank_new, _must_out_new);\n\t\tif ( forwardCheck )\n\t\t{\n\t\t\tfindPreferredExtensions(_blank_new, _in_new, _out_new, _undec_new, _must_out_new);\n\t\t}\n\t\t\n\t\tif (_s_type == TYPE_B)\n\t\t{\n\t\t\t_undec[i] = true;  _blank[i] = false;\n\t\t\tif ( !lookAhead(_blank, _must_out) )\n\t\t\t\treturn;\n\t\t}\n\t\telse   // TYPE_A\n\t\t{\n\t\t\tif ( !forwardCheck )\n\t\t\t\treturn;\n\n\t\t\t_blank = _blank_new;\n\t\t\t_in = _in_new;\n\t\t\t_out = _out_new;\n\t\t\t_must_out = _must_out_new;\n\t\t\t_undec = _undec_new;\n\t\t}\n\n\t\tboost::tie(i, _s_type) = selectArgument(_blank, _in, _out, _undec, _must_out);\n\t}\n\n\t// if there are no argument labeled MUST_OUT, then inserts the argument \n\t// set labeled IN into extensions\n\tif ( _must_out.is_emptyset() )\n\t{\n\t\tstd::set<bitvector>::iterator sa_itr;\n\n\t\tfor (sa_itr = m_extensions.begin(); sa_itr != m_extensions.end(); sa_itr++)\n\t\t{\n\t\t\tif (_in.is_subset_of( *sa_itr ))\n\t\t\t{\n\t\t\t\t//cout << \"duplicate: \" << _in << \"is subset of\" << *sa_itr << endl;\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\n\t\tm_extensions.insert( _in );\n\t}\n}\n\nbool PreferredReasoner::lookAhead(bitvector& _blank_new, bitvector& _tmp_must_out)\n{\n\tfor (size_type i = _tmp_must_out.find_first(); i != bitvector::npos; i = _tmp_must_out.find_next(i))\n\t{\n\t\tif ( !m_BmAtkMtx[i].intersects(_blank_new) )\n\t\t\treturn false;\n\t}\n\n\treturn true;\n}\n\npair<size_type, PreferredReasoner::SELECT_TYPE> PreferredReasoner::selectArgument(\n\tconst bitvector& _blank, const bitvector& _in, const bitvector& _out,\n\tconst bitvector& _undec, const bitvector& _must_out) \n{\n\tsize_type i = bitvector::npos;\n\tfor (size_type j = _blank.find_first(); j != bitvector::npos; j = _blank.find_next(j))\n\t{\n\t\t//bool _m_in = true;\n\t\tif( m_BmAtkMtx[j].is_subset_of(_out|_must_out) )\n\t\t//if ( !m_attackMatrix[j].intersects(_blank|_undec) )\n\t\t{\n\t\t\treturn make_pair(j, TYPE_A);\n\t\t}\n\t\t\n\t\tif ( i == bitvector::npos) \t{\n\t\t\ti = j;\n\t\t} else if (m_attackedBy[j].count()+m_BmAtkMtx[j].count() >\n\t\t\tm_attackedBy[i].count()+m_BmAtkMtx[i].count()) {\n\t\t\ti = j;\n\t\t}\n\t}\n\n\treturn make_pair(i, TYPE_B);\n}\n\nbitvector PreferredReasoner::getAttackers(const bitvector& _bv)\n{\n\tassert( _bv.size() == m_argNum );\n\n\treturn m_attackedBy * _bv;\n}\n\n} // namespace argumatrix\n\n\n\n#endif  //DUNG_PREFERRED_REASONER_HPP", "meta": {"hexsha": "5181774b31bcecf1acec3545802335818922c0d3", "size": 7675, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "dung_theory/PreferredReasoner.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/PreferredReasoner.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/PreferredReasoner.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": 29.8638132296, "max_line_length": 108, "alphanum_fraction": 0.7073615635, "num_tokens": 2202, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.33831087082935035}}
{"text": "/**\n * @file gan_impl.hpp\n * @author Kris Singh\n * @author Shikhar Jaiswal\n *\n * mlpack is free software; you may redistribute it and/or modify it under the\n * terms of the 3-clause BSD license. You should have received a copy of the\n * 3-clause BSD license along with mlpack. If not, see\n * http://www.opensource.org/licenses/BSD-3-Clause for more information.\n */\n#ifndef MLPACK_METHODS_ANN_GAN_GAN_IMPL_HPP\n#define MLPACK_METHODS_ANN_GAN_GAN_IMPL_HPP\n\n#include \"gan.hpp\"\n\n#include <mlpack/core.hpp>\n\n#include <mlpack/methods/ann/ffn.hpp>\n#include <mlpack/methods/ann/init_rules/network_init.hpp>\n#include <mlpack/methods/ann/visitor/output_parameter_visitor.hpp>\n#include <mlpack/methods/ann/activation_functions/softplus_function.hpp>\n#include <boost/serialization/variant.hpp>\n\nnamespace mlpack {\nnamespace ann /** Artifical Neural Network.  */ {\ntemplate<\n  typename Model,\n  typename InitializationRuleType,\n  typename Noise,\n  typename PolicyType\n>\nGAN<Model, InitializationRuleType, Noise, PolicyType>::GAN(\n    arma::mat& predictors,\n    Model generator,\n    Model discriminator,\n    InitializationRuleType& initializeRule,\n    Noise& noiseFunction,\n    const size_t noiseDim,\n    const size_t batchSize,\n    const size_t generatorUpdateStep,\n    const size_t preTrainSize,\n    const double multiplier,\n    const double clippingParameter,\n    const double lambda):\n    generator(std::move(generator)),\n    discriminator(std::move(discriminator)),\n    initializeRule(initializeRule),\n    noiseFunction(noiseFunction),\n    noiseDim(noiseDim),\n    batchSize(batchSize),\n    generatorUpdateStep(generatorUpdateStep),\n    preTrainSize(preTrainSize),\n    multiplier(multiplier),\n    clippingParameter(clippingParameter),\n    lambda(lambda),\n    reset(false)\n{\n  // Insert IdentityLayer for joining the Generator and Discriminator.\n  this->discriminator.network.insert(\n      this->discriminator.network.begin(),\n      new IdentityLayer<>());\n\n  counter = 0;\n  currentBatch = 0;\n\n  this->discriminator.deterministic = this->generator.deterministic = true;\n\n  this->predictors.set_size(predictors.n_rows, predictors.n_cols + batchSize);\n  this->predictors.cols(0, predictors.n_cols - 1) = predictors;\n  this->discriminator.predictors = arma::mat(this->predictors.memptr(),\n      this->predictors.n_rows, this->predictors.n_cols, false, false);\n\n  responses.ones(1, predictors.n_cols + batchSize);\n  responses.cols(predictors.n_cols,\n      predictors.n_cols + batchSize - 1) = arma::zeros(1, batchSize);\n  this->discriminator.responses = arma::mat(this->responses.memptr(),\n      this->responses.n_rows, this->responses.n_cols, false, false);\n\n  numFunctions = predictors.n_cols;\n\n  noise.set_size(noiseDim, batchSize);\n\n  this->generator.predictors.set_size(noiseDim, batchSize);\n  this->generator.responses.set_size(predictors.n_rows, batchSize);\n}\n\ntemplate<\n  typename Model,\n  typename InitializationRuleType,\n  typename Noise,\n  typename PolicyType\n>\nGAN<Model, InitializationRuleType, Noise, PolicyType>::GAN(\n    const GAN& network):\n    predictors(network.predictors),\n    responses(network.responses),\n    generator(network.generator),\n    discriminator(network.discriminator),\n    initializeRule(network.initializeRule),\n    noiseFunction(network.noiseFunction),\n    noiseDim(network.noiseDim),\n    batchSize(network.batchSize),\n    generatorUpdateStep(network.generatorUpdateStep),\n    preTrainSize(network.preTrainSize),\n    multiplier(network.multiplier),\n    clippingParameter(network.clippingParameter),\n    lambda(network.lambda),\n    reset(network.reset),\n    counter(network.counter),\n    currentBatch(network.currentBatch),\n    parameter(network.parameter),\n    numFunctions(network.numFunctions),\n    noise(network.noise)\n{\n  /* Nothing to do here */\n}\n\ntemplate<\n  typename Model,\n  typename InitializationRuleType,\n  typename Noise,\n  typename PolicyType\n>\nGAN<Model, InitializationRuleType, Noise, PolicyType>::GAN(\n    GAN&& network):\n    predictors(std::move(network.predictors)),\n    responses(std::move(network.responses)),\n    generator(std::move(network.generator)),\n    discriminator(std::move(network.discriminator)),\n    initializeRule(std::move(network.initializeRule)),\n    noiseFunction(std::move(network.noiseFunction)),\n    noiseDim(network.noiseDim),\n    batchSize(network.batchSize),\n    generatorUpdateStep(network.generatorUpdateStep),\n    preTrainSize(network.preTrainSize),\n    multiplier(network.multiplier),\n    clippingParameter(network.clippingParameter),\n    lambda(network.lambda),\n    reset(network.reset),\n    counter(network.counter),\n    currentBatch(network.currentBatch),\n    parameter(std::move(network.parameter)),\n    numFunctions(network.numFunctions),\n    noise(std::move(network.noise))\n{\n  /* Nothing to do here */\n}\n\ntemplate<\n  typename Model,\n  typename InitializationRuleType,\n  typename Noise,\n  typename PolicyType\n>\nvoid GAN<Model, InitializationRuleType, Noise, PolicyType>::Reset()\n{\n  size_t genWeights = 0;\n  size_t discWeights = 0;\n\n  NetworkInitialization<InitializationRuleType> networkInit(initializeRule);\n\n  for (size_t i = 0; i < generator.network.size(); ++i)\n  {\n    genWeights += boost::apply_visitor(weightSizeVisitor, generator.network[i]);\n  }\n\n  for (size_t i = 0; i < discriminator.network.size(); ++i)\n  {\n    discWeights += boost::apply_visitor(weightSizeVisitor,\n        discriminator.network[i]);\n  }\n\n  parameter.set_size(genWeights + discWeights, 1);\n  generator.Parameters() = arma::mat(parameter.memptr(), genWeights, 1, false,\n      false);\n  discriminator.Parameters() = arma::mat(parameter.memptr() + genWeights,\n      discWeights, 1, false, false);\n\n  // Initialize the parameters generator\n  networkInit.Initialize(generator.network, parameter);\n  // Initialize the parameters discriminator\n  networkInit.Initialize(discriminator.network, parameter, genWeights);\n\n  reset = true;\n}\n\ntemplate<\n  typename Model,\n  typename InitializationRuleType,\n  typename Noise,\n  typename PolicyType\n>\ntemplate<typename OptimizerType>\ndouble GAN<Model, InitializationRuleType, Noise, PolicyType>::Train(\n    OptimizerType& Optimizer)\n{\n  if (!reset)\n    Reset();\n  return Optimizer.Optimize(*this, parameter);\n}\n\ntemplate<\n  typename Model,\n  typename InitializationRuleType,\n  typename Noise,\n  typename PolicyType\n>\ntemplate<typename Policy>\ntypename std::enable_if<std::is_same<Policy, StandardGAN>::value ||\n                        std::is_same<Policy, DCGAN>::value, double>::type\nGAN<Model, InitializationRuleType, Noise, PolicyType>::Evaluate(\n    const arma::mat& /* parameters */,\n    const size_t i,\n    const size_t /* batchSize */)\n{\n  if (!reset)\n    Reset();\n\n  currentInput = arma::mat(predictors.memptr() + (i * predictors.n_rows),\n      predictors.n_rows, batchSize, false, false);\n  currentTarget = arma::mat(responses.memptr() + i, 1, batchSize, false,\n      false);\n\n  discriminator.Forward(std::move(currentInput));\n  double res = discriminator.outputLayer.Forward(\n      std::move(boost::apply_visitor(\n      outputParameterVisitor,\n      discriminator.network.back())), std::move(currentTarget));\n\n  noise.imbue( [&]() { return noiseFunction();} );\n  generator.Forward(std::move(noise));\n\n  predictors.cols(numFunctions, numFunctions + batchSize - 1) =\n      boost::apply_visitor(outputParameterVisitor, generator.network.back());\n  discriminator.Forward(std::move(predictors.cols(numFunctions,\n      numFunctions + batchSize - 1)));\n  responses.cols(numFunctions, numFunctions + batchSize - 1) =\n      arma::zeros(1, batchSize);\n\n  currentTarget = arma::mat(responses.memptr() + numFunctions,\n      1, batchSize, false, false);\n  res += discriminator.outputLayer.Forward(\n      std::move(boost::apply_visitor(\n      outputParameterVisitor,\n      discriminator.network.back())), std::move(currentTarget));\n\n  return res;\n}\n\ntemplate<\n  typename Model,\n  typename InitializationRuleType,\n  typename Noise,\n  typename PolicyType\n>\ntemplate<typename GradType, typename Policy>\ntypename std::enable_if<std::is_same<Policy, StandardGAN>::value ||\n                        std::is_same<Policy, DCGAN>::value, double>::type\nGAN<Model, InitializationRuleType, Noise, PolicyType>::\nEvaluateWithGradient(const arma::mat& /* parameters */,\n                     const size_t i,\n                     GradType& gradient,\n                     const size_t /* batchSize */)\n{\n  if (!reset)\n    Reset();\n\n  if (gradient.is_empty())\n  {\n    if (parameter.is_empty())\n      Reset();\n    gradient = arma::zeros<arma::mat>(parameter.n_elem, 1);\n  }\n  else\n    gradient.zeros();\n\n  if (noiseGradientDiscriminator.is_empty())\n  {\n    noiseGradientDiscriminator = arma::zeros<arma::mat>(\n        gradientDiscriminator.n_elem, 1);\n  }\n  else\n  {\n    noiseGradientDiscriminator.zeros();\n  }\n\n  gradientGenerator = arma::mat(gradient.memptr(),\n      generator.Parameters().n_elem, 1, false, false);\n\n  gradientDiscriminator = arma::mat(gradient.memptr() +\n      gradientGenerator.n_elem,\n      discriminator.Parameters().n_elem, 1, false, false);\n\n  // Get the gradients of the Discriminator.\n  double res = discriminator.EvaluateWithGradient(discriminator.parameter,\n      i, gradientDiscriminator, batchSize);\n\n  noise.imbue( [&]() { return noiseFunction();} );\n  generator.Forward(std::move(noise));\n  predictors.cols(numFunctions, numFunctions + batchSize - 1) =\n      boost::apply_visitor(outputParameterVisitor, generator.network.back());\n  responses.cols(numFunctions, numFunctions + batchSize - 1) =\n      arma::zeros(1, batchSize);\n\n  // Get the gradients of the Generator.\n  res += discriminator.EvaluateWithGradient(discriminator.parameter,\n      numFunctions, noiseGradientDiscriminator, batchSize);\n  gradientDiscriminator += noiseGradientDiscriminator;\n\n  if (currentBatch % generatorUpdateStep == 0 && preTrainSize == 0)\n  {\n    // Minimize -log(D(G(noise))).\n    // Pass the error from Discriminator to Generator.\n    responses.cols(numFunctions, numFunctions + batchSize - 1) =\n        arma::ones(1, batchSize);\n    discriminator.Gradient(discriminator.parameter, numFunctions,\n        noiseGradientDiscriminator, batchSize);\n    generator.error = boost::apply_visitor(deltaVisitor,\n        discriminator.network[1]);\n\n    generator.Predictors() = noise;\n    generator.ResetGradients(gradientGenerator);\n    generator.Gradient(generator.parameter, 0, gradientGenerator, batchSize);\n\n    gradientGenerator *= multiplier;\n  }\n\n  counter++;\n  currentBatch++;\n\n  // Revert the counter to zero, if the total dataset get's covered.\n  if (counter * batchSize >= numFunctions)\n  {\n    counter = 0;\n  }\n\n  if (preTrainSize > 0)\n  {\n    preTrainSize--;\n  }\n\n  return res;\n}\n\ntemplate<\n  typename Model,\n  typename InitializationRuleType,\n  typename Noise,\n  typename PolicyType\n>\ntemplate<typename Policy>\ntypename std::enable_if<std::is_same<Policy, StandardGAN>::value ||\n                        std::is_same<Policy, DCGAN>::value, void>::type\nGAN<Model, InitializationRuleType, Noise, PolicyType>::\nGradient(const arma::mat& parameters,\n         const size_t i,\n         arma::mat& gradient,\n         const size_t batchSize)\n{\n  this->EvaluateWithGradient(parameters, i, gradient, batchSize);\n}\n\ntemplate<\n  typename Model,\n  typename InitializationRuleType,\n  typename Noise,\n  typename PolicyType\n>\nvoid GAN<Model, InitializationRuleType, Noise, PolicyType>::Shuffle()\n{\n  const arma::uvec ordering = arma::shuffle(arma::linspace<arma::uvec>(0,\n      numFunctions - 1, numFunctions));\n  predictors.cols(0, numFunctions - 1) = predictors.cols(ordering);\n}\n\ntemplate<\n  typename Model,\n  typename InitializationRuleType,\n  typename Noise,\n  typename PolicyType\n>\nvoid GAN<Model, InitializationRuleType, Noise, PolicyType>::Forward(\n    arma::mat&& input)\n{\n  if (!reset)\n    Reset();\n\n  generator.Forward(std::move(input));\n  ganOutput = boost::apply_visitor(\n      outputParameterVisitor,\n      generator.network.back());\n\n  discriminator.Forward(std::move(ganOutput));\n}\n\ntemplate<\n  typename Model,\n  typename InitializationRuleType,\n  typename Noise,\n  typename PolicyType\n>\nvoid GAN<Model, InitializationRuleType, Noise, PolicyType>::\nPredict(arma::mat&& input, arma::mat& output)\n{\n  if (!reset)\n    Reset();\n\n  Forward(std::move(input));\n\n  output = boost::apply_visitor(outputParameterVisitor,\n      discriminator.network.back());\n}\n\ntemplate<\n  typename Model,\n  typename InitializationRuleType,\n  typename Noise,\n  typename PolicyType\n>\ntemplate<typename Archive>\nvoid GAN<Model, InitializationRuleType, Noise, PolicyType>::\nserialize(Archive& ar, const unsigned int /* version */)\n{\n  ar & BOOST_SERIALIZATION_NVP(parameter);\n  ar & BOOST_SERIALIZATION_NVP(generator);\n  ar & BOOST_SERIALIZATION_NVP(discriminator);\n  ar & BOOST_SERIALIZATION_NVP(noiseFunction);\n}\n\n} // namespace ann\n} // namespace mlpack\n# endif\n", "meta": {"hexsha": "cb992f3eed536b0db9b61263bd29b61ec4c6fa56", "size": 12820, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/mlpack/methods/ann/gan/gan_impl.hpp", "max_stars_repo_name": "AYESDIE/mlpack", "max_stars_repo_head_hexsha": "12a50a055ba7f69340598329bd146ee37bec110f", "max_stars_repo_licenses": ["BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-03-12T20:10:39.000Z", "max_stars_repo_stars_event_max_datetime": "2020-03-12T20:10:39.000Z", "max_issues_repo_path": "src/mlpack/methods/ann/gan/gan_impl.hpp", "max_issues_repo_name": "guimuguo/mlpack", "max_issues_repo_head_hexsha": "897b0cddf6ba23733f701b4679fac08f9f90ebb2", "max_issues_repo_licenses": ["BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/mlpack/methods/ann/gan/gan_impl.hpp", "max_forks_repo_name": "guimuguo/mlpack", "max_forks_repo_head_hexsha": "897b0cddf6ba23733f701b4679fac08f9f90ebb2", "max_forks_repo_licenses": ["BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.6073903002, "max_line_length": 80, "alphanum_fraction": 0.7200468019, "num_tokens": 2902, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6926419831347362, "lm_q2_score": 0.48828339529583464, "lm_q1q2_score": 0.33820557924946926}}
{"text": "/*=========================================================================\n\n  Program:   Visualization Toolkit\n  Module:    vtkBoostDividedEdgeBundling.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#include \"vtkBoostDividedEdgeBundling.h\"\n\n#include \"vtkBoostGraphAdapter.h\"\n#include \"vtkDataSetAttributes.h\"\n#include \"vtkDirectedGraph.h\"\n#include \"vtkFloatArray.h\"\n#include \"vtkInformation.h\"\n#include \"vtkInformationVector.h\"\n#include \"vtkMath.h\"\n#include \"vtkNew.h\"\n#include \"vtkObjectFactory.h\"\n#include \"vtkPoints.h\"\n#include \"vtkVectorOperators.h\"\n\n#include <boost/property_map/property_map.hpp>\n#include <boost/graph/johnson_all_pairs_shortest.hpp>\n#include <algorithm>\n\nvtkStandardNewMacro(vtkBoostDividedEdgeBundling);\n\nvtkBoostDividedEdgeBundling::vtkBoostDividedEdgeBundling()\n{\n}\n\nclass vtkBundlingMetadata\n{\npublic:\n  vtkBundlingMetadata(vtkBoostDividedEdgeBundling *alg, vtkDirectedGraph *g)\n    : Outer(alg), Graph(g)\n  {\n    this->Nodes = reinterpret_cast<vtkVector3f*>(\n      vtkArrayDownCast<vtkFloatArray>(g->GetPoints()->GetData())->GetPointer(0));\n    this->Edges.resize(g->GetNumberOfEdges());\n    for (vtkIdType e = 0; e < g->GetNumberOfEdges(); ++e)\n    {\n      this->Edges[e] = std::make_pair(g->GetSourceVertex(e), g->GetTargetVertex(e));\n    }\n    this->VelocityDamping = 0.1f;\n    this->EdgeCoulombConstant = 0.5f;\n    //this->EdgeCoulombConstant = 50.0f;\n    this->EdgeCoulombDecay = 35.0f;\n    this->EdgeSpringConstant = 0.1f;\n    //this->EdgeSpringConstant = 0.0005f;\n    this->EdgeLaneWidth = 25.0f;\n    this->UseNewForce = true;\n  }\n\n  void ProjectOnto(vtkIdType e1, vtkIdType e2, vtkVector3f& s, vtkVector3f& t);\n  void NormalizeNodePositions();\n  void DenormalizeNodePositions();\n  void CalculateNodeDistances();\n  float AngleCompatibility(vtkIdType e1, vtkIdType e2);\n  float ScaleCompatibility(vtkIdType e1, vtkIdType e2);\n  float PositionCompatibility(vtkIdType e1, vtkIdType e2);\n  float VisibilityCompatibility(vtkIdType e1, vtkIdType e2);\n  float ConnectivityCompatibility(vtkIdType e1, vtkIdType e2);\n  void CalculateEdgeLengths();\n  void CalculateEdgeCompatibilities();\n  void InitializeEdgeMesh();\n  void DoubleEdgeMeshResolution();\n  void SimulateEdgeStep();\n  void LayoutEdgePoints();\n  void SmoothEdges();\n\n  float SimulationStep;\n  int CycleIterations;\n  int MeshCount;\n  float VelocityDamping;\n  float EdgeCoulombConstant;\n  float EdgeCoulombDecay;\n  float EdgeSpringConstant;\n  float EdgeLaneWidth;\n  bool UseNewForce;\n  vtkBoostDividedEdgeBundling *Outer;\n  vtkDirectedGraph *Graph;\n  vtkVector3f *Nodes;\n  std::vector<std::pair<vtkIdType, vtkIdType> > Edges;\n  std::vector<std::vector<float> > NodeDistances;\n  std::vector<float> EdgeLengths;\n  std::vector<std::vector<float> > EdgeCompatibilities;\n  std::vector<std::vector<float> > EdgeDots;\n  std::vector<std::vector<vtkVector3f> > EdgeMesh;\n  std::vector<std::vector<vtkVector3f> > EdgeMeshVelocities;\n  std::vector<std::vector<vtkVector3f> > EdgeMeshAccelerations;\n  //std::vector<std::vector<float> > EdgeMeshGroupCounts;\n  vtkVector2f XRange;\n  vtkVector2f YRange;\n  vtkVector2f ZRange;\n  float Scale;\n};\n\nvoid vtkBundlingMetadata::NormalizeNodePositions()\n{\n  this->XRange = vtkVector2f(VTK_FLOAT_MAX, VTK_FLOAT_MIN);\n  this->YRange = vtkVector2f(VTK_FLOAT_MAX, VTK_FLOAT_MIN);\n  this->ZRange = vtkVector2f(VTK_FLOAT_MAX, VTK_FLOAT_MIN);\n  for (vtkIdType i = 0; i < this->Graph->GetNumberOfVertices(); ++i)\n  {\n    vtkVector3f p = this->Nodes[i];\n    this->XRange[0] = std::min(this->XRange[0], p[0]);\n    this->XRange[1] = std::max(this->XRange[1], p[0]);\n    this->YRange[0] = std::min(this->YRange[0], p[1]);\n    this->YRange[1] = std::max(this->YRange[1], p[1]);\n    this->ZRange[0] = std::min(this->ZRange[0], p[2]);\n    this->ZRange[1] = std::max(this->ZRange[1], p[2]);\n  }\n  float dx = this->XRange[1] - this->XRange[0];\n  float dy = this->YRange[1] - this->YRange[0];\n  float dz = this->ZRange[1] - this->ZRange[0];\n  this->Scale = std::max(dx, std::max(dy, dz));\n  for (vtkIdType i = 0; i < this->Graph->GetNumberOfVertices(); ++i)\n  {\n    vtkVector3f p = this->Nodes[i];\n    this->Nodes[i] = vtkVector3f(\n      (p[0] - this->XRange[0])/this->Scale * 1000.0f,\n      (p[1] - this->YRange[0])/this->Scale * 1000.0f,\n      (p[2] - this->ZRange[0])/this->Scale * 1000.0f);\n  }\n}\n\nvoid vtkBundlingMetadata::DenormalizeNodePositions()\n{\n  for (vtkIdType i = 0; i < this->Graph->GetNumberOfVertices(); ++i)\n  {\n    vtkVector3f p = this->Nodes[i];\n    this->Nodes[i] = vtkVector3f(\n      p[0] / 1000.0f * this->Scale + this->XRange[0],\n      p[1] / 1000.0f * this->Scale + this->YRange[0],\n      p[2] / 1000.0f * this->Scale + this->ZRange[0]);\n  }\n  for (vtkIdType i = 0; i < (int)this->EdgeMesh.size(); ++i)\n  {\n    for (vtkIdType j = 0; j < (int)this->EdgeMesh[i].size(); ++j)\n    {\n      vtkVector3f p = this->EdgeMesh[i][j];\n      this->EdgeMesh[i][j] = vtkVector3f(\n        p[0] / 1000.0f * this->Scale + this->XRange[0],\n        p[1] / 1000.0f * this->Scale + this->YRange[0],\n        p[2] / 1000.0f * this->Scale + this->ZRange[0]);\n    }\n  }\n}\n\nvoid vtkBundlingMetadata::CalculateNodeDistances()\n{\n  vtkIdType numVerts = this->Graph->GetNumberOfVertices();\n  vtkIdType numEdges = this->Graph->GetNumberOfEdges();\n  this->NodeDistances.resize(numVerts, std::vector<float>(numVerts, VTK_FLOAT_MAX));\n  std::vector<float> weights(numVerts, 1.0f);\n  vtkNew<vtkFloatArray> weightMap;\n  weightMap->SetNumberOfTuples(numEdges);\n  for (vtkIdType e = 0; e < numEdges; ++e)\n  {\n    weightMap->SetValue(e, 1.0f);\n  }\n  boost::vtkGraphEdgePropertyMapHelper<vtkFloatArray*> weightProp(weightMap);\n  boost::johnson_all_pairs_shortest_paths(\n    this->Graph, this->NodeDistances,\n    boost::weight_map(weightProp));\n}\n\nfloat vtkBundlingMetadata::AngleCompatibility(vtkIdType e1, vtkIdType e2)\n{\n  if (this->EdgeLengths[e1] == 0.0f || this->EdgeLengths[e2] == 0.0f)\n  {\n    return 0.0f;\n  }\n  vtkVector3f s1 = this->Nodes[this->Edges[e1].first];\n  vtkVector3f t1 = this->Nodes[this->Edges[e1].second];\n  vtkVector3f s2 = this->Nodes[this->Edges[e2].first];\n  vtkVector3f t2 = this->Nodes[this->Edges[e2].second];\n  vtkVector3f p1 = s1 - t1;\n  vtkVector3f p2 = s2 - t2;\n  float compatibility = p1.Dot(p2) / (this->EdgeLengths[e1]*this->EdgeLengths[e2]);\n  return fabs(compatibility);\n}\n\nfloat vtkBundlingMetadata::ScaleCompatibility(vtkIdType e1, vtkIdType e2)\n{\n  float len1 = this->EdgeLengths[e1];\n  float len2 = this->EdgeLengths[e2];\n  float average = (len1 + len2) / 2.0f;\n  if (average == 0.0f)\n  {\n    return 0.0f;\n  }\n  return 2.0f / (average / std::min(len1, len2) + std::max(len1, len2) / average);\n}\n\nfloat vtkBundlingMetadata::PositionCompatibility(vtkIdType e1, vtkIdType e2)\n{\n  float len1 = this->EdgeLengths[e1];\n  float len2 = this->EdgeLengths[e2];\n  float average = (len1 + len2) / 2.0f;\n  if (average == 0.0f)\n  {\n    return 0.0f;\n  }\n  vtkVector3f s1 = this->Nodes[this->Edges[e1].first];\n  vtkVector3f t1 = this->Nodes[this->Edges[e1].second];\n  vtkVector3f s2 = this->Nodes[this->Edges[e2].first];\n  vtkVector3f t2 = this->Nodes[this->Edges[e2].second];\n  vtkVector3f mid1 = 0.5*(s1 + t1);\n  vtkVector3f mid2 = 0.5*(s2 + t2);\n  return average / (average + (mid1 - mid2).Norm());\n}\n\nvoid vtkBundlingMetadata::ProjectOnto(vtkIdType e1, vtkIdType e2, vtkVector3f& s, vtkVector3f& t)\n{\n  vtkVector3f s1 = this->Nodes[this->Edges[e1].first];\n  vtkVector3f t1 = this->Nodes[this->Edges[e1].second];\n  vtkVector3f s2 = this->Nodes[this->Edges[e2].first];\n  vtkVector3f t2 = this->Nodes[this->Edges[e2].second];\n  vtkVector3f norm = t2 - s2;\n  norm.Normalize();\n  vtkVector3f toHead = s1 - s2;\n  vtkVector3f toTail = t1 - s2;\n  vtkVector3f headOnOther = norm * norm.Dot(toHead);\n  vtkVector3f tailOnOther = norm * norm.Dot(toTail);\n  s = s2 + headOnOther;\n  t = s2 + tailOnOther;\n}\n\nfloat vtkBundlingMetadata::VisibilityCompatibility(vtkIdType e1, vtkIdType e2)\n{\n  vtkVector3f is;\n  vtkVector3f it;\n  vtkVector3f js;\n  vtkVector3f jt;\n  this->ProjectOnto(e1, e2, is, it);\n  this->ProjectOnto(e2, e1, js, jt);\n  float ilen = (is - it).Norm();\n  float jlen = (js - jt).Norm();\n  if (ilen == 0.0f || jlen == 0.0f)\n  {\n    return 0.0f;\n  }\n  vtkVector3f s1 = this->Nodes[this->Edges[e1].first];\n  vtkVector3f t1 = this->Nodes[this->Edges[e1].second];\n  vtkVector3f s2 = this->Nodes[this->Edges[e2].first];\n  vtkVector3f t2 = this->Nodes[this->Edges[e2].second];\n  vtkVector3f mid1 = 0.5*(s1 + t1);\n  vtkVector3f mid2 = 0.5*(s2 + t2);\n  vtkVector3f imid = 0.5*(is + it);\n  vtkVector3f jmid = 0.5*(js + jt);\n  float midQI = (mid2 - imid).Norm();\n  float vpq = std::max(0.0f, 1.0f - (2.0f * midQI) / ilen);\n  float midPJ = (mid1 - jmid).Norm();\n  float vqp = std::max(0.0f, 1.0f - (2.0f * midPJ) / jlen);\n\n  return std::min(vpq, vqp);\n}\n\nfloat vtkBundlingMetadata::ConnectivityCompatibility(vtkIdType e1, vtkIdType e2)\n{\n  vtkIdType s1 = this->Edges[e1].first;\n  vtkIdType t1 = this->Edges[e1].second;\n  vtkIdType s2 = this->Edges[e2].first;\n  vtkIdType t2 = this->Edges[e2].second;\n  if (s1 == s2 || s1 == t2 || t1 == s2 || t1 == t2)\n  {\n    return 1.0f;\n  }\n  float minPath = std::min(this->NodeDistances[s1][s2], std::min(this->NodeDistances[s1][t2],\n    std::min(this->NodeDistances[t1][s2], this->NodeDistances[t1][t2])));\n  return 1.0f / (minPath + 1.0f);\n}\n\nvoid vtkBundlingMetadata::CalculateEdgeLengths()\n{\n  vtkIdType numEdges = this->Graph->GetNumberOfEdges();\n  this->EdgeLengths.resize(numEdges);\n  for (vtkIdType e = 0; e < numEdges; ++e)\n  {\n    vtkVector3f s = this->Nodes[this->Edges[e].first];\n    vtkVector3f t = this->Nodes[this->Edges[e].second];\n    this->EdgeLengths[e] = (s - t).Norm();\n  }\n}\n\nvoid vtkBundlingMetadata::CalculateEdgeCompatibilities()\n{\n  vtkIdType numEdges = this->Graph->GetNumberOfEdges();\n  this->EdgeCompatibilities.resize(numEdges, std::vector<float>(numEdges, 1.0f));\n  this->EdgeDots.resize(numEdges, std::vector<float>(numEdges, 1.0f));\n  for (vtkIdType e1 = 0; e1 < numEdges; ++e1)\n  {\n    vtkVector3f s1 = this->Nodes[this->Edges[e1].first];\n    vtkVector3f t1 = this->Nodes[this->Edges[e1].second];\n    vtkVector3f r1 = s1 - t1;\n    r1.Normalize();\n    for (vtkIdType e2 = e1 + 1; e2 < numEdges; ++e2)\n    {\n      float compatibility = 1.0f;\n      compatibility *= this->AngleCompatibility(e1, e2);\n      compatibility *= this->ScaleCompatibility(e1, e2);\n      compatibility *= this->PositionCompatibility(e1, e2);\n      compatibility *= this->VisibilityCompatibility(e1, e2);\n      compatibility *= this->ConnectivityCompatibility(e1, e2);\n      this->EdgeCompatibilities[e1][e2] = compatibility;\n      this->EdgeCompatibilities[e2][e1] = compatibility;\n\n      vtkVector3f s2 = this->Nodes[this->Edges[e2].first];\n      vtkVector3f t2 = this->Nodes[this->Edges[e2].second];\n      vtkVector3f r2 = s2 - t2;\n      r2.Normalize();\n      float dot = r1.Dot(r2);\n      this->EdgeDots[e1][e2] = dot;\n      this->EdgeDots[e2][e1] = dot;\n    }\n  }\n}\n\nvoid vtkBundlingMetadata::InitializeEdgeMesh()\n{\n  this->MeshCount = 2;\n  vtkIdType numEdges = this->Graph->GetNumberOfEdges();\n  this->EdgeMesh.resize(numEdges, std::vector<vtkVector3f>(2));\n  this->EdgeMeshVelocities.resize(numEdges, std::vector<vtkVector3f>(2));\n  this->EdgeMeshAccelerations.resize(numEdges, std::vector<vtkVector3f>(2));\n  //this->EdgeMeshGroupCounts.resize(numEdges, std::vector<float>(2, 1.0f));\n  for (vtkIdType e = 0; e < numEdges; ++e)\n  {\n    this->EdgeMesh[e][0] = this->Nodes[this->Edges[e].first];\n    this->EdgeMesh[e][1] = this->Nodes[this->Edges[e].second];\n  }\n}\n\nvoid vtkBundlingMetadata::DoubleEdgeMeshResolution()\n{\n  int newMeshCount = (this->MeshCount - 1)*2 + 1;\n  vtkIdType numEdges = this->Graph->GetNumberOfEdges();\n  std::vector<std::vector<vtkVector3f> > newEdgeMesh(\n      numEdges, std::vector<vtkVector3f>(newMeshCount));\n  std::vector<std::vector<vtkVector3f> > newEdgeMeshVelocities(\n      numEdges, std::vector<vtkVector3f>(newMeshCount, vtkVector3f(0.0f, 0.0f, 0.0f)));\n  std::vector<std::vector<vtkVector3f> > newEdgeMeshAccelerations(\n      numEdges, std::vector<vtkVector3f>(newMeshCount, vtkVector3f(0.0f, 0.0f, 0.0f)));\n  //std::vector<std::vector<float> > newEdgeMeshGroupCounts(\n  //    numEdges, std::vector<float>(newMeshCount, 1.0f));\n  for (vtkIdType e = 0; e < numEdges; ++e)\n  {\n    for (int m = 0; m < newMeshCount; ++m)\n    {\n      float indexFloat = (this->MeshCount - 1.0f)*m/(newMeshCount - 1.0f);\n      int index = static_cast<int>(indexFloat);\n      float alpha = indexFloat - index;\n      vtkVector3f before = this->EdgeMesh[e][index];\n      if (alpha > 0)\n      {\n        vtkVector3f after = this->EdgeMesh[e][index+1];\n        newEdgeMesh[e][m] = before + alpha*(after - before);\n      }\n      else\n      {\n        newEdgeMesh[e][m] = before;\n      }\n    }\n  }\n  this->MeshCount = newMeshCount;\n  this->EdgeMesh = newEdgeMesh;\n  this->EdgeMeshVelocities = newEdgeMeshVelocities;\n  this->EdgeMeshAccelerations = newEdgeMeshAccelerations;\n  //this->EdgeMeshGroupCounts = newEdgeMeshGroupCounts;\n}\n\nvoid vtkBundlingMetadata::SimulateEdgeStep()\n{\n  vtkIdType numEdges = this->Graph->GetNumberOfEdges();\n\n  for (vtkIdType e1 = 0; e1 < numEdges; ++e1)\n  {\n    float weight1 = 1.0f;\n    for (int m1 = 0; m1 < this->MeshCount; ++m1)\n    {\n      // Immovable\n      if (m1 <= 0 || m1 >= this->MeshCount - 1)\n      {\n        continue;\n      }\n\n      // Move the point according to dynamics\n      vtkVector3f position = this->EdgeMesh[e1][m1];\n      vtkVector3f velocity = this->EdgeMeshVelocities[e1][m1];\n      vtkVector3f acceleration = this->EdgeMeshAccelerations[e1][m1];\n      velocity = velocity + acceleration * this->SimulationStep * 0.5f;\n      velocity = velocity * this->VelocityDamping;\n      position = position + velocity * this->SimulationStep;\n      this->EdgeMesh[e1][m1] = position;\n\n      acceleration = vtkVector3f(0.0f, 0.0f, 0.0f);\n\n      // Spring force\n      vtkVector3f prevPosition = this->EdgeMesh[e1][m1-1];\n      vtkVector3f prevDirection = prevPosition - position;\n      float prevDist = prevDirection.Norm();\n      float prevForce = this->EdgeSpringConstant / 1000.0f * (this->MeshCount - 1) * prevDist * weight1;\n      prevDirection.Normalize();\n      acceleration = acceleration + prevForce * prevDirection;\n\n      vtkVector3f nextPosition = this->EdgeMesh[e1][m1+1];\n      vtkVector3f nextDirection = nextPosition - position;\n      float nextDist = nextDirection.Norm();\n      float nextForce = this->EdgeSpringConstant / 1000.0f * (this->MeshCount - 1) * nextDist * weight1;\n      nextDirection.Normalize();\n      acceleration = acceleration + nextForce * nextDirection;\n\n      // Coulomb force\n      float normalizedEdgeCoulombConstant = this->EdgeCoulombConstant / sqrt(static_cast<float>(numEdges));\n\n      for (vtkIdType e2 = 0; e2 < numEdges; ++e2)\n      {\n        if (e1 == e2)\n        {\n          continue;\n        }\n\n        float compatibility = this->EdgeCompatibilities[e1][e2];\n        if (compatibility <= 0.05)\n        {\n          continue;\n        }\n\n        float dot = this->EdgeDots[e1][e2];\n        float weight2 = 1.0f;\n\n        int m2;\n        if (dot >= 0.0f)\n        {\n          m2 = m1;\n        }\n        else\n        {\n          m2 = this->MeshCount - 1 - m1;\n        }\n\n        vtkVector3f position2;\n        // If we're going the same direction is edge1, then the potential minimum is at the point.\n        if (dot >= 0.0f)\n        {\n          position2 = this->EdgeMesh[e2][m2];\n        }\n        // If we're going the opposite direction, the potential minimum is edgeLaneWidth to the \"right.\"\n        else\n        {\n          vtkVector3f tangent = this->EdgeMesh[e2][m2+1] - this->EdgeMesh[e2][m2-1];\n          tangent.Normalize();\n          // This assumes 2D\n          vtkVector3f normal(-tangent[1], tangent[0], 0.0f);\n          position2 = this->EdgeMesh[e2][m2] + normal*this->EdgeLaneWidth;\n        }\n\n        vtkVector3f direction = position2 - position;\n        float distance = direction.Norm();\n\n        // Inverse force.\n        float force;\n        if (!this->UseNewForce)\n        {\n          force = normalizedEdgeCoulombConstant * 30.0f / (this->MeshCount - 1) / (distance + 0.01f);\n        }\n        // New force.\n        else\n        {\n          force = 4.0f * 10000.0f / (this->MeshCount - 1) * this->EdgeCoulombDecay * normalizedEdgeCoulombConstant * distance / (3.1415926f * pow(this->EdgeCoulombDecay * this->EdgeCoulombDecay + distance * distance, 2));\n        }\n        force *= weight2;\n        force *= compatibility;\n\n        if (distance > 0.0f)\n        {\n          direction.Normalize();\n          acceleration = acceleration + force * direction;\n        }\n      }\n\n      velocity = velocity + acceleration * this->SimulationStep * 0.5f;\n      this->EdgeMeshVelocities[e1][m1] = velocity;\n      this->EdgeMeshAccelerations[e1][m1] = acceleration;\n    }\n  }\n}\n\nvoid vtkBundlingMetadata::SmoothEdges()\n{\n  // From Mathematica Total[GaussianMatrix[{3, 3}]]\n  int kernelSize = 3;\n  // Has to sum to 1.0 to be correct.\n  float gaussianKernel[] = {0.10468, 0.139936, 0.166874, 0.177019, 0.166874, 0.139936, 0.10468};\n  vtkIdType numEdges = this->Graph->GetNumberOfEdges();\n  std::vector<std::vector<vtkVector3f> > smoothedEdgeMesh(\n      numEdges, std::vector<vtkVector3f>(this->MeshCount));\n  for (vtkIdType e = 0; e < numEdges; ++e)\n  {\n    for (int m = 1; m < this->MeshCount - 1; ++m)\n    {\n      vtkVector3f smoothed(0.0f, 0.0f, 0.0f);\n      for (int kernelIndex = 0; kernelIndex < kernelSize * 2 + 1; kernelIndex++)\n      {\n        int m2 = m + kernelIndex - kernelSize;\n        m2 = std::max(0, std::min(this->MeshCount - 1, m2));\n\n        vtkVector3f pt = this->EdgeMesh[e][m2];\n        smoothed = smoothed + gaussianKernel[kernelIndex] * pt;\n      }\n      smoothedEdgeMesh[e][m] = smoothed;\n    }\n  }\n  this->EdgeMesh = smoothedEdgeMesh;\n}\n\nvoid vtkBundlingMetadata::LayoutEdgePoints()\n{\n  this->InitializeEdgeMesh();\n  this->SimulationStep = 40.0f;\n  this->CycleIterations = 30;\n  for (int i = 0; i < 5; ++i)\n  {\n    vtkDebugWithObjectMacro(this->Outer, \"vtkBoostDividedEdgeBundling cycle \" << i);\n    this->CycleIterations = this->CycleIterations * 2 / 3;\n    this->SimulationStep = 0.85f*this->SimulationStep;\n    this->DoubleEdgeMeshResolution();\n    for (int j = 0; j < this->CycleIterations; ++j)\n    {\n      vtkDebugWithObjectMacro(this->Outer, \"vtkBoostDividedEdgeBundling iteration \" << j);\n      this->SimulateEdgeStep();\n    }\n  }\n  this->SmoothEdges();\n}\n\nint vtkBoostDividedEdgeBundling::RequestData(\n  vtkInformation *vtkNotUsed(request),\n  vtkInformationVector **inputVector,\n  vtkInformationVector *outputVector)\n{\n  // get the info objects\n  vtkInformation *graphInfo = inputVector[0]->GetInformationObject(0);\n  vtkInformation *outInfo = outputVector->GetInformationObject(0);\n\n  // get the input and output\n  vtkDirectedGraph *g = vtkDirectedGraph::SafeDownCast(\n    graphInfo->Get(vtkDataObject::DATA_OBJECT()));\n  vtkDirectedGraph *output = vtkDirectedGraph::SafeDownCast(\n    outInfo->Get(vtkDataObject::DATA_OBJECT()));\n\n  vtkBundlingMetadata *meta = new vtkBundlingMetadata(this, g);\n\n  meta->NormalizeNodePositions();\n  meta->CalculateEdgeLengths();\n  meta->CalculateNodeDistances();\n  meta->CalculateEdgeCompatibilities();\n  meta->LayoutEdgePoints();\n  meta->DenormalizeNodePositions();\n\n  output->ShallowCopy(g);\n\n  for (vtkIdType e = 0; e < g->GetNumberOfEdges(); ++e)\n  {\n    output->ClearEdgePoints(e);\n    for (int m = 1; m < meta->MeshCount-1; ++m)\n    {\n      vtkVector3f edgePoint = meta->EdgeMesh[e][m];\n      output->AddEdgePoint(e, edgePoint[0], edgePoint[1], edgePoint[2]);\n    }\n  }\n\n  delete meta;\n\n  return 1;\n}\n\nvoid vtkBoostDividedEdgeBundling::PrintSelf(ostream& os, vtkIndent indent)\n{\n  this->Superclass::PrintSelf(os,indent);\n}\n\n", "meta": {"hexsha": "c85a27af91e10a7b5474765d2d10579eebec6f80", "size": 20472, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "Infovis/BoostGraphAlgorithms/vtkBoostDividedEdgeBundling.cxx", "max_stars_repo_name": "satya-arjunan/vtk8", "max_stars_repo_head_hexsha": "ee7ced57de6d382a2d12693c01e2fcdac350b25f", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2015-07-28T18:07:50.000Z", "max_stars_repo_stars_event_max_datetime": "2018-02-28T20:59:58.000Z", "max_issues_repo_path": "Infovis/BoostGraphAlgorithms/vtkBoostDividedEdgeBundling.cxx", "max_issues_repo_name": "satya-arjunan/vtk8", "max_issues_repo_head_hexsha": "ee7ced57de6d382a2d12693c01e2fcdac350b25f", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2018-10-25T09:46:11.000Z", "max_issues_repo_issues_event_max_datetime": "2019-01-17T16:49:17.000Z", "max_forks_repo_path": "Infovis/BoostGraphAlgorithms/vtkBoostDividedEdgeBundling.cxx", "max_forks_repo_name": "satya-arjunan/vtk8", "max_forks_repo_head_hexsha": "ee7ced57de6d382a2d12693c01e2fcdac350b25f", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2016-09-08T02:11:00.000Z", "max_forks_repo_forks_event_max_datetime": "2019-08-15T02:38:39.000Z", "avg_line_length": 34.2914572864, "max_line_length": 221, "alphanum_fraction": 0.6512797968, "num_tokens": 6424, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6926419831347361, "lm_q2_score": 0.4882833952958347, "lm_q1q2_score": 0.33820557924946926}}
{"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#include <cmath>\n#include <iostream>\n#include <boost/math/tools/roots.hpp>\n#include <boost/bind.hpp>\n\n#include \"BoostTolerance.hpp\"\n#include \"LaPradAirwayWall.hpp\"\n#include \"MathsCustomFunctions.hpp\"\n#include \"Exception.hpp\"\n\nLaPradAirwayWall::LaPradAirwayWall() : mTargetPressure(0),\n                                       mRIn(0),\n                                       mROut(0),\n                                       mk1(0),\n                                       mk2(0),\n                                       mk3(0)\n{\n}\n\nLaPradAirwayWall::~LaPradAirwayWall() {}\n\nvoid LaPradAirwayWall::SetTimestep(double dt) {}\n\ndouble LaPradAirwayWall::CalculatePressureRadiusResidual(double radius)\n{\n\n    mTargetPressure = mAirwayPressure - mPleuralPressure;\n\n    double rin = radius;\n\n    double areaOfAirwayWall = M_PI*(mROut*mROut - mRIn*mRIn);\n    double rout = sqrt(rin*rin + areaOfAirwayWall/M_PI);\n    long double functionValues[10000];\n    double rValues[10000];\n    double pressure;\n\n    for (int i = 0; i < 10000; i++)\n    {\n\n        double RVal = mRIn + (double)i*(mROut - mRIn)/(10000. - 1.);\n        rValues[i] = rin + (double)i*(rout - rin)/(10000. - 1.);\n        functionValues[i] = ((rValues[i]/RVal)*(rValues[i]/RVal) - (RVal/rValues[i])*(RVal/rValues[i]))*(mk1*sqrt(1. + (RVal/rValues[i])*(RVal/rValues[i]) + (rValues[i]/RVal)*(rValues[i]/RVal) - 3.) + mk2*sqrt(1 + (RVal/rValues[i])*(RVal/rValues[i]) + (rValues[i]/RVal)*(rValues[i]/RVal) - 3.)*exp(mk3*(1. + (RVal/rValues[i])*(RVal/rValues[i]) + (rValues[i]/RVal)*(rValues[i]/RVal) - 3.)*(1 + (RVal/rValues[i])*(RVal/rValues[i]) + (rValues[i]/RVal)*(rValues[i]/RVal) - 3.)))/rValues[i];\n    }\n\n\n    pressure = (0.5*(functionValues[0] + functionValues[10000 - 1]));\n    for (int i = 1; i < (10000 - 1); i++)\n    {\n        pressure = pressure + functionValues[i];\n    }\n    pressure = pressure*(rValues[1] - rValues[0]);\n\n    double residual = mTargetPressure - pressure;\n\n    return residual;\n\n}\n\nvoid LaPradAirwayWall::SolveAndUpdateState(double tStart, double tEnd)\n{\n\n    double guess = (mRIn + mROut)/2.;\n    double factor = 2.;\n\n    Tolerance tol = 0.000001;\n    boost::uintmax_t maxIterations = 500u;\n\n    std::pair<double, double> found = boost::math::tools::bracket_and_solve_root(boost::bind(&LaPradAirwayWall::CalculatePressureRadiusResidual, this, _1), guess, factor, false, tol, maxIterations);\n    mDeformedAirwayRadius = found.first;\n}\n\nvoid LaPradAirwayWall::SetRIn(double RIn)\n{\n    assert (RIn >= 0.0);\n    mRIn = RIn;\n}\n\nvoid LaPradAirwayWall::SetROut(double ROut)\n{\n    assert (ROut >= 0.0);\n    mROut = ROut;\n}\n\nvoid LaPradAirwayWall::Setk1(double k1)\n{\n    assert (k1 >= 0.0);\n    mk1 = k1;\n}\n\nvoid LaPradAirwayWall::Setk2(double k2)\n{\n    assert (k2 >= 0.);\n    mk2 = k2;\n}\n\nvoid LaPradAirwayWall::Setk3(double k3)\n{\n    assert (k3 >= 0.);\n    mk3 = k3;\n}\n\ndouble LaPradAirwayWall::GetLumenRadius()\n{\n    return mDeformedAirwayRadius;\n}\n\nvoid LaPradAirwayWall::SetAirwayPressure(double pressure)\n{\n    mAirwayPressure = pressure;\n}\n\nvoid LaPradAirwayWall::SetPleuralPressure(double pressure)\n{\n    mPleuralPressure = pressure;\n}\n", "meta": {"hexsha": "b4e8d3a75703a0430f1fbf89e2bfdc8b03f370f5", "size": 4833, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lung/src/ventilation/odes/LaPradAirwayWall.cpp", "max_stars_repo_name": "gonayl/Chaste", "max_stars_repo_head_hexsha": "498c48489a38a8f4c5fa7c01e691cc82df3d2e6b", "max_stars_repo_licenses": ["Apache-2.0", "BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "lung/src/ventilation/odes/LaPradAirwayWall.cpp", "max_issues_repo_name": "gonayl/Chaste", "max_issues_repo_head_hexsha": "498c48489a38a8f4c5fa7c01e691cc82df3d2e6b", "max_issues_repo_licenses": ["Apache-2.0", "BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lung/src/ventilation/odes/LaPradAirwayWall.cpp", "max_forks_repo_name": "gonayl/Chaste", "max_forks_repo_head_hexsha": "498c48489a38a8f4c5fa7c01e691cc82df3d2e6b", "max_forks_repo_licenses": ["Apache-2.0", "BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.0066225166, "max_line_length": 486, "alphanum_fraction": 0.6854955514, "num_tokens": 1330, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6926419831347361, "lm_q2_score": 0.48828339529583464, "lm_q1q2_score": 0.3382055792494692}}
{"text": "#include <math.h>\n#include <float.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <time.h>\n#include <stdbool.h>\n#include \"matrix.h\"\n#include \"omxCsolnp.h\"\n#include <Eigen/Dense>\n//#include <iostream>\n//#include <iomanip>\n//using std::cout;\n//using std::endl;\n\nstruct CSOLNP {\n\n    int flag, flag_NormgZ, minr_rec;\n    Eigen::VectorXd LB_e;\n    Eigen::VectorXd UB_e;\n    Eigen::MatrixXd resP;\n    double resLambda;\n    Eigen::MatrixXd resHessv;\n    Eigen::MatrixXd resY;\n    Eigen::MatrixXd sx_Matrix; // search direction\n    Eigen::RowVectorXd resGrad;\n    int mode;\n    int neq, nineq;\n    bool optimize_initial_inequality_constraints;\n    int numCallsToCSOLNP;\n    GradientOptimizerContext &fit;\n\n\tCSOLNP(GradientOptimizerContext &_fit) : fit(_fit) {};\n    \n\tvoid solnp(double *pars, int verbose);\n\n    template <typename T1, typename T2>\n    void obj_constr_eval(Eigen::MatrixBase<T2>& objVal, Eigen::MatrixBase<T2>& eqval, Eigen::MatrixBase<T2>& ineqval, Eigen::MatrixBase<T1>& fitVal, int verbose);\n    \n    template <typename T1, typename T2>\n    void subnp(Eigen::MatrixBase<T2>& pars, Eigen::MatrixBase<T1>& yy_e, Eigen::MatrixBase<T1>& ob_e, Eigen::MatrixBase<T1>& hessv_e, double lambda, Eigen::MatrixBase<T2>& vscale_e,\n                 const Eigen::Array<double, 4, 1> &ctrl, int verbose);\n\n\tenum indParam {\n\t\tindNumParam=0,\n\t\tindHasGradient,\n\t\tindHasHessian,\n\t\tindHasIneq,\n\t\tindHasJacobianIneq,\n\t\tindHasEq,\n\t\tindHasJacobianEq,\n\t\tindVectorLength  // must be last\n\t};\n\n\tEigen::Array<double, int(indVectorLength), 1> ind;\n};\n\nvoid solnp(double *solPars, GradientOptimizerContext &fit)\n{\n\tCSOLNP context(fit);\n\tfit.setupIneqConstraintBounds();\n\tcontext.solnp(solPars, fit.verbose);\n}\n\nvoid CSOLNP::solnp(double *solPars, int verbose)\n{\n\tfit.informOut = -1;\n    LB_e = fit.solLB;\n    UB_e = fit.solUB;\n    //verbose = 3;\n    \n    flag = 0;\n    flag_NormgZ = 0; minr_rec = 0;\n    \n    double funv;\n    double resultForTT;\n    double solnp_nfn = 0;\n    \n    //time_t sec;\n    //sec = time (NULL);\n    \n    int maxit_trace = 0;\n    //free(matrices.front().t);\n    \n    Eigen::Map< Eigen::RowVectorXd > pars(solPars, LB_e.size());\n\n    const int np = pars.size();\n    \n    ind.setZero();\n    ind[indNumParam] = np;\n    \n    // does not have a function gradient (currently not supported in Rsolnp)\n    ind[indHasGradient] = 0;\n    //# do function checks and return starting value\n    \n    mode = 1;\n    funv = fit.solFun(pars.data(), &mode);\n    \n    // does not have a hessian (currently not supported in Rsolnp)\n    ind[indHasHessian] = 0;\n    // no jacobian (not implemented)\n    ind[indHasJacobianIneq] = 0;\n    \n    neq = fit.equality.size();\n    \n    ind[indHasEq] = neq > 0;\n    ind[indHasJacobianEq] = 0;\n    \n    fit.myineqFun();\n    Eigen::RowVectorXd ineqv_e(fit.inequality.size());\n    ineqv_e= fit.inequality;\n\n    Eigen::MatrixXd hessv_e;\n    \n    if ((ineqv_e.array() < 0).any())\n    {\n        optimize_initial_inequality_constraints = TRUE;\n        numCallsToCSOLNP = 2;\n    }\n    else{\n        optimize_initial_inequality_constraints = FALSE;\n        numCallsToCSOLNP = 1;\n    }\n\n    for ( int i = 1; i <= numCallsToCSOLNP; i++){\n    \n        if (optimize_initial_inequality_constraints){\n            nineq = 0;\n        }\n        else {\n            nineq = fit.inequality.size();\n        }\n        \n        ind[indHasIneq] = nineq > 0;\n\n        if (verbose >= 2){\n            mxLog(\"ind is: \\n\");\n            for (i = 0; i < ind.size(); i++) mxLog(\"%f\",ind[i]);\n        }\n    \n        Eigen::RowVectorXd ineqx0_e(nineq); ineqx0_e.setZero();\n        Eigen::MatrixXd pb_e;\n    \n    if(nineq) {\n        pb_e.setZero(nineq, 2);\n        pb_e.col(1) = Eigen::VectorXd::Constant(pb_e.rows(), INF);\n        Eigen::MatrixXd pb_cont_e;\n        pb_cont_e.setZero(np, 2);\n        pb_cont_e.col(0) = LB_e;\n        pb_cont_e.col(1) = UB_e;\n        pb_e.transposeInPlace();\n        pb_cont_e.transposeInPlace();\n        Eigen::MatrixXd pbJoined(2, nineq + np);\n        pbJoined << pb_e, pb_cont_e;\n        pbJoined.transposeInPlace();\n        pb_e.resize(pbJoined.rows(), pbJoined.cols());\n        pb_e = pbJoined;\n        \n    } else {\n        pb_e.setZero(np, 2);\n        pb_e.col(0) = LB_e;\n        pb_e.col(1) = UB_e;\n    }\n    \n    double rho   = fit.ControlRho;\n    int maxit = fit.ControlMajorLimit;\n    int minit = fit.ControlMinorLimit;\n    double delta = fit.ControlFuncPrecision;\n    double tol   = fit.ControlTolerance;\n    \n    int tc = nineq + neq;\n    \n    double j = funv;\n    Eigen::VectorXd tt_e(3); tt_e.setZero();\n    \n    Eigen::MatrixXd constraint_e;\n    \n    fit.solEqBFun();\n    Eigen::RowVectorXd eqv_e(neq);\n    eqv_e = fit.equality;\n    \n    fit.myineqFun();\n    Eigen::RowVectorXd ineqv_e(nineq);\n    ineqv_e= fit.inequality;\n    \n    Eigen::MatrixXd lambda_e;\n    \n    if (tc > 0){\n        lambda_e.setZero(tc, 1);\n        \n        if (nineq){\n            if(neq)\n            {\n                constraint_e.resize(1, eqv_e.size() + ineqv_e.size());\n                constraint_e << eqv_e, ineqv_e;\n            }\n            else{\n                constraint_e = ineqv_e;\n            }\n        }\n        else\n            constraint_e = eqv_e;\n        \n        if( ind[indHasIneq] > 0 ) {\n            \n            // \ttmpv = cbind(constraint[ (neq[0]):(tc[0]-1) ] - .fit.solIneqLB, .fit.solIneqUB - constraint[ (neq + 1):tc ] )\n            Eigen::MatrixXd diff1 = constraint_e.block(0, neq, 1, tc-neq).transpose();\n            Eigen::MatrixXd diff2 = constraint_e.block(0, neq, 1, tc-neq).transpose();\n            Eigen::VectorXd infVec = Eigen::VectorXd::Constant(diff2.rows(), INF);\n            diff2 = infVec - diff2;\n            Eigen::MatrixXd tmpv_e(nineq, 2);\n            tmpv_e.col(0) = diff1;\n            tmpv_e.col(1) = diff2;\n            Eigen::MatrixXd testMin_e = tmpv_e.rowwise().minCoeff();\n            \n            if ((testMin_e.array() > 0).all()) {\n                ineqx0_e = constraint_e.block(0, neq, 1, tc-neq);\n            }\n            \n            constraint_e.block(0, neq, 1, tc-neq) = constraint_e.block(0, neq, 1, tc-neq) - ineqx0_e;\n        }\n        \n        tt_e[1] = sqrt(constraint_e.squaredNorm());\n        double zeroCheck = tt_e[1] - (10 * tol);\n        if( std::max(zeroCheck, (double)nineq) <= 0 ) {\n            rho = 0;\n        }\n    } // end if tc > 0\n    else {\n        lambda_e.setZero(1, 1);\n    }\n    \n    Eigen::RowVectorXd p_e;\n    \n    if (nineq){\n        p_e.resize(1, ineqx0_e.size() + pars.size());\n        p_e << ineqx0_e, pars;\n    }\n    else{\n        p_e = pars;\n    }\n    \n    hessv_e.resize(np + nineq, np + nineq);\n    hessv_e.setIdentity();\n    \n    double mu = np;\n    \n    int solnp_iter = 0;\n    \n    Eigen::MatrixXd ob_e(1, 1 + neq + nineq);\n    Eigen::RowVectorXd funvMatrix_e(1);\n    funvMatrix_e[0] = funv;\n    fit.solEqBFun();\n    eqv_e = fit.equality;\n        \n    fit.myineqFun();\n    ineqv_e = fit.inequality;\n    \n    obj_constr_eval(funvMatrix_e, eqv_e, ineqv_e, ob_e, verbose);\n\n    Eigen::RowVectorXd vscale_e;\n    \n    while(solnp_iter < maxit){\n        solnp_iter = solnp_iter + 1;\n        Eigen::Array<double, 4, 1> subnp_ctrl;\n        subnp_ctrl[0] = rho;\n        subnp_ctrl[1] = minit;\n        subnp_ctrl[2] = delta;\n        subnp_ctrl[3] = tol;\n        \n        if ( ind[indHasEq] > 0){\n            \n            double max = ob_e.block(0, 1, 1, neq).cwiseAbs().maxCoeff();\n            Eigen::MatrixXd temp2_e(1, neq);\n            temp2_e = temp2_e.setOnes() * max;\n            Eigen::MatrixXd temp1_e(1, 1); temp1_e(0, 0) = ob_e(0, 0);\n            vscale_e.resize(1, temp1_e.cols() + temp2_e.cols());\n            vscale_e << temp1_e, temp2_e;\n        }\n        else{\n            vscale_e.resize(1, 1); vscale_e.setOnes();\n        }\n        Eigen::RowVectorXd onesMatrix(1, p_e.size()); onesMatrix.setOnes();\n        Eigen::RowVectorXd vscale_t = vscale_e;\n        vscale_e.resize(1, vscale_t.cols() + onesMatrix.cols());\n        vscale_e << vscale_t, onesMatrix;\n        \n        minMaxAbs(vscale_e, tol);\n        \n        if (mode == -1)\n        {\n            fit.informOut = 0;\n            memcpy(pars.data(), p_e.data(), pars.size() * sizeof(double));\n            return;\n        }\n        \n        sx_Matrix.setZero(p_e.rows(), p_e.cols());\n        \n        subnp(p_e, lambda_e, ob_e, hessv_e, mu, vscale_e, subnp_ctrl, verbose);\n        \n        p_e = resP;\n        \n        if (flag == 1)\n        {\n            mode = 0;\n            Eigen::MatrixXd temp;\n            temp = p_e.block(0, nineq, 1, np);\n            funv = fit.solFun(temp.data(), &mode);\n            funvMatrix_e[0] = funv;\n            fit.solEqBFun();\n            eqv_e = fit.equality;\n            fit.myineqFun();\n            ineqv_e = fit.inequality;\n            obj_constr_eval(funvMatrix_e, eqv_e, ineqv_e, ob_e, verbose);\n\n            if ( ind[indHasEq] > 0){\n                \n                double max = ob_e.block(0, 1, 1, neq).cwiseAbs().maxCoeff();\n                Eigen::MatrixXd temp2_e(1, neq);\n                temp2_e = temp2_e.setOnes() * max;\n                Eigen::MatrixXd temp1_e(1, 1); temp1_e(0, 0) = ob_e(0, 0);\n                vscale_e.resize(1, temp1_e.cols() + temp2_e.cols());\n                vscale_e << temp1_e, temp2_e;\n            }\n            else{\n                vscale_e.resize(1, 1); vscale_e.setOnes();\n            }\n            Eigen::RowVectorXd onesMatrix(1, p_e.size()); onesMatrix.setOnes();\n            Eigen::RowVectorXd vscale_t = vscale_e;\n            vscale_e.resize(1, vscale_t.cols() + onesMatrix.cols());\n            vscale_e << vscale_t, onesMatrix;\n            \n            lambda_e = resY;\n            hessv_e = resHessv;\n            mu = resLambda;\n            subnp(p_e, lambda_e, ob_e, hessv_e, mu, vscale_e, subnp_ctrl, verbose);\n        }\n        \n        lambda_e = resY;\n        hessv_e = resHessv;\n        mu = resLambda;\n        \n        Eigen::MatrixXd temp;\n        temp = p_e.block(0, nineq, 1, np);\n        \n        mode = 1;\n        funv = fit.solFun(temp.data(), &mode);\n        if (mode == -1)\n        {\n            fit.informOut = 0;\n            memcpy(pars.data(), p_e.data(), pars.size() * sizeof(double));\n            return;\n        }\n        \n        solnp_nfn = solnp_nfn + 1;\n\n        fit.solEqBFun();\n        eqv_e = fit.equality;\n        funvMatrix_e[0] = funv;\n        fit.myineqFun();\n        ineqv_e = fit.inequality;\n\n        obj_constr_eval(funvMatrix_e, eqv_e, ineqv_e, ob_e, verbose);\n        \n        resultForTT = (j - ob_e(0, 0)) / std::max(ob_e.cwiseAbs().maxCoeff(), 1.0);\n        tt_e[0] = resultForTT;\n        if (verbose >= 1){\n            mxLog(\"resultForTT \\n\");\n            mxLog(\"%f\", resultForTT);\n        }\n        j = ob_e(0, 0);\n        \n        if (tc > 0){\n            // constraint = ob[ 2:(tc + 1) ]\n            constraint_e = ob_e.block(0, 1, 1, tc);\n            \n            if ( ind[indHasIneq] > 0.5){\n                //tempv = rbind( constraint[ (neq + 1):tc ] - pb[ 1:nineq, 1 ], pb[ 1:nineq, 2 ] - constraint[ (neq + 1):tc ] )\n                Eigen::MatrixXd subsetOne = constraint_e.block(0, neq, 1, tc-neq) - pb_e.col(0).transpose().block(0, 0, 1, nineq);\n                Eigen::MatrixXd subsetTwo = pb_e.col(1).transpose().block(0, 0, 1, nineq);\n                subsetTwo -= subsetOne;\n                Eigen::MatrixXd tempv(2, nineq);\n                tempv.row(0) = subsetOne;\n                tempv.row(1) = subsetTwo;\n                \n                if (tempv.minCoeff() > 0){\n                    p_e.block(0, 0, 1, nineq) = constraint_e.block(0, neq, 1, tc-neq);\n                }\n                constraint_e.block(0, neq, 1, tc-neq) = constraint_e.block(0, neq, 1, tc-neq) - p_e.block(0, 0, 1, nineq);\n                \n            } // end if (ind[0][3] > 0.5){\n            \n            tt_e[2] = sqrt(constraint_e.squaredNorm());\n            \n            \n            if ( tt_e[2] < (10 *tol)){\n                rho =0;\n                mu = std::min(mu, tol);\n            }\n            \n            if ( tt_e[2] < (5 * tt_e[1])){\n                rho = rho/5;\n            }\n            \n            if ( tt_e[2] > (10 * tt_e[1])){\n                rho = 5 * std::max(rho, sqrt(tol));\n            }\n            \n            Eigen::MatrixXd llist(1, 2);\n            \n            llist(0, 0) = tol + tt_e[0];\n            llist(0, 1) = tt_e[1] - tt_e[2];\n            \n            \n            if (llist.maxCoeff() <= 0){\n                lambda_e.resize(1, 1); lambda_e(0, 0) = 0;\n                hessv_e = hessv_e.diagonal().asDiagonal();\n            }\n            \n            tt_e[1] = tt_e[2];\n            \n        } // end if (tc > 0){\n                \n        Eigen::VectorXd tempTTVals(2);\n        tempTTVals[0] = tt_e[0];\n        tempTTVals[1] = tt_e[1];\n        double vnormValue = sqrt(tempTTVals.squaredNorm());\n        \n        if (vnormValue <= tol){\n            maxit_trace = maxit;\n            maxit = solnp_iter;\n        }\n        \n        if (verbose >= 3)\n        {\n            mxLog(\"vnormValue in while \\n\");\n            mxLog(\"%f\", vnormValue);\n        }\n    } // end while(solnp_iter < maxit){\n    \n    Eigen::RowVectorXd p_e_copy = p_e;\n    p_e.resize(np);\n    p_e = p_e_copy.block(0, nineq, 1, np);\n\n    {\n        Eigen::VectorXd tempTTVals(2);\n        tempTTVals[0] = tt_e[0];\n        tempTTVals[1] = tt_e[1];\n        double vnormValue = sqrt(tempTTVals.squaredNorm());\n\n        if (verbose >= 1) {\n\t\tmxLog(\"vnormValue %.20f, flag_NormgZ=%d, minr_rec=%d\",\n\t\t      vnormValue, flag_NormgZ, minr_rec);\n\t}\n        if (vnormValue <= tol && flag_NormgZ == 1 && minr_rec == 1){\n\t\tdouble iterateConverge = delta * pow(sqrt(sx_Matrix.squaredNorm()),(double)2.0);\n\t\tdouble iterateConvergeCond = sqrt(tol) * ((double)1.0 + pow(sqrt(p_e.squaredNorm()), (double)2.0));\n\t\tif (verbose >= 1) {\n\t\t\tmxLog(\"vnorm(sx_Matrix) is %.20f, iterateConverge is %.20f, iterateConvergeCond is: %.20f\",\n\t\t\t      sqrt(sx_Matrix.squaredNorm()), iterateConverge, iterateConvergeCond);\n\t\t}\n\n            if (iterateConverge <= iterateConvergeCond){\n\t\t    if (verbose >= 1) { mxLog(\"The solution converged in %d iterations\", solnp_iter); }\n\t\t    fit.informOut = INFORM_CONVERGED_OPTIMUM;\n            } else {\n                if (verbose >= 1){\n                    mxLog(\"The final iterate x satisfies the optimality conditions to the accuracy requested, but the sequence of iterates has not yet converged. CSOLNP was terminated because no further improvement could be made in the merit function.\");}\n                fit.informOut = INFORM_UNCONVERGED_OPTIMUM;\n            }\n        }\n        else{\n            if (solnp_iter == maxit_trace) {\n                if (verbose >= 1){\n                    mxLog(\"Exiting after maximum number of iterations. Tolerance not achieved\\n\");}\n                fit.informOut = INFORM_ITERATION_LIMIT;\n            } else {\n                if (verbose >= 1) { mxLog(\"Solution failed to converge.\"); }\n                fit.informOut = INFORM_NOT_AT_OPTIMUM;\n            }\n        }\n    }\n        memcpy(pars.data(), p_e.data(), pars.size() * sizeof(double));\n        optimize_initial_inequality_constraints = FALSE;\n    }\n \n    fit.gradOut.resize(resGrad.size());\n    memcpy(fit.gradOut.data(), resGrad.data(), fit.gradOut.size() * sizeof(double));\n    fit.hessOut.resize(hessv_e.rows(), hessv_e.cols());\n    memcpy(fit.hessOut.data(), hessv_e.data(), fit.hessOut.size() * sizeof(double));\n}\n\ntemplate <typename T1, typename T2>\nvoid CSOLNP::subnp(Eigen::MatrixBase<T2>& pars, Eigen::MatrixBase<T1>& yy_e, Eigen::MatrixBase<T1>& ob_e, Eigen::MatrixBase<T1>& hessv_e,\n                     double lambda, Eigen::MatrixBase<T2>& vscale_e, const Eigen::Array<double, 4, 1> &ctrl, int verbose)\n{\n    int yyRows = yy_e.rows();\n    //int yyCols = yy.cols;\n    double j;\n    \n    //mxLog(\"ctrl is: \");\n    //for (int ilog = 0; ilog < ctrl.cols; ilog++) mxLog(\"%f\",ctrl.t[ilog]);\n    double rho   = ctrl[0];\n    int maxit = ctrl[1];\n    double delta = ctrl[2];\n    double tol =   ctrl[3];\n    \n    int neq =  fit.equality.size();\n    int nineq;\n    if (optimize_initial_inequality_constraints) nineq = 0;\n    else nineq = fit.inequality.size();\n\n    int np = (int)ind[indNumParam];\n    \n    double ch = 1;\n    \n    if (verbose >= 2){\n        mxLog(\"ind inside subnp is: \\n\");\n        for (int i = 0; i < ind.size(); i++) mxLog(\"%f\",ind[i]);\n    }\n    \n    Eigen::Array<double, 3, 1> alp;\n    alp.setZero();\n    \n    int nc = neq + nineq;\n    int npic = np + nineq;\n    \n    Eigen::RowVectorXd p0_e = pars;\n    \n    if (verbose >= 3) {\n\t    mxPrintMat(\"p0\", p0_e);\n    }\n    \n    Eigen::MatrixXd pb_e;\n    /*Eigen::Map< Eigen::VectorXd > LB_e(LB.t, LB.cols);\n    Eigen::Map< Eigen::VectorXd > UB_e(UB.t, UB.cols);*/\n    \n    if(nineq) {\n        pb_e.setZero(nineq, 2);\n        pb_e.col(1) = Eigen::VectorXd::Constant(pb_e.rows(), INF);\n        Eigen::MatrixXd pb_cont_e;\n        pb_cont_e.setZero(np, 2);\n        pb_cont_e.col(0) = LB_e;\n        pb_cont_e.col(1) = UB_e;\n        pb_e.transposeInPlace();\n        pb_cont_e.transposeInPlace();\n        Eigen::MatrixXd pbJoined(2, nineq + np);\n        pbJoined << pb_e, pb_cont_e;\n        pbJoined.transposeInPlace();\n        pb_e.resize(pbJoined.rows(), pbJoined.cols());\n        pb_e = pbJoined;\n    } else {\n        pb_e.setZero(np, 2);\n        pb_e.col(0) = LB_e;\n        pb_e.col(1) = UB_e;\n    }\n    \n    Eigen::Array<double, 3, 1> sob;\n    sob.setZero();\n    \n    //Matrix yyMatrix = duplicateIt(yy);\n    \n    ob_e = ob_e.cwiseQuotient(vscale_e.block(0, 0, 1, nc + 1));\n    p0_e = p0_e.cwiseQuotient(vscale_e.block(0, neq + 1, 1, nc + np - neq));\n    \n    int mm = 0;\n    {\n        mm=npic;\n        Eigen::MatrixXd pbCopied;\n        pbCopied.setZero(pb_e.rows(), pb_e.cols());\n        pbCopied.col(0) = vscale_e.block(0, neq + 1, 1, mm).transpose();\n        pbCopied.col(1) = vscale_e.block(0, neq + 1, 1, mm).transpose();\n        pb_e = pb_e.cwiseQuotient(pbCopied);\n    }\n    \n    // scale the lagrange multipliers and the Hessian\n    if( nc > 0) {\n        // yy [total constraints = nineq + neq]\n        // scale here is [tc] and dot multiplied by yy\n        //yy = vscale[ 2:(nc + 1) ] * yy / vscale[ 1 ]\n        \n        yy_e = vscale_e.block(0, 1, 1, nc).transpose().array() * yy_e.array();\n        yy_e = yy_e / vscale_e[0];\n    }\n    \n    // hessv [ (np+nineq) x (np+nineq) ]\n    // hessv = hessv * (vscale[ (neq + 2):(nc + np + 1) ] %*% t(vscale[ (neq + 2):(nc + np + 1)]) ) / vscale[ 1 ]\n    \n    Eigen::MatrixXd result_e;\n    result_e = vscale_e.block(0, neq + 1, 1, nc + np - neq).transpose() * vscale_e.block(0, neq + 1, 1, nc + np - neq);\n    hessv_e = hessv_e.cwiseProduct(result_e);\n    hessv_e = hessv_e / vscale_e[0];\n\n    j = ob_e(0, 0);\n    if (verbose >= 3){\n        mxLog(\"j j is: \\n\");\n        mxLog(\"%f\", j);\n    }\n    Eigen::MatrixXd a_e;\n    if( ind[indHasIneq] > 0){\n        if ( ind[indHasEq] <= 0)\n        {\n            // arrays, rows, cols\n            Eigen::MatrixXd negDiag;\n            negDiag.setIdentity(nineq, nineq);\n            negDiag.diagonal() *= -1;\n            //std::cout << \"Here is the matrix negDiag:\\n\" << negDiag << std::endl;\n            Eigen::MatrixXd zeroMatrix(nineq, np);\n            zeroMatrix.setZero();\n            //std::cout << \"Here is the matrix  zeroMatrix:\\n\" << zeroMatrix << std::endl;\n            a_e.resize(nineq, np + nineq);\n            a_e << negDiag, zeroMatrix;\n            //std::cout << \"Here is the matrix a_e:\\n\" << a_e << std::endl;\n        }\n        else{\n            // [ (neq+nineq) x (nineq+np)]\n            //a = rbind( cbind( 0 * .ones(neq, nineq), matrix(0, ncol = np, nrow = neq) ),\n            //      cbind( -diag(nineq), matrix(0, ncol = np, nrow = nineq) ) )\n            \n            Eigen::MatrixXd zeroMatrix(nineq, np);\n            zeroMatrix.setZero();\n            //Matrix zeroMatrix = fill(np, nineq, (double)0.0);\n            Eigen::MatrixXd firstHalf_e(neq, nineq + np);\n            firstHalf_e.setZero();\n            //Matrix firstHalf = copy(fill(nineq, neq, (double)0.0), fill(np, neq, (double)0.0));\n            Eigen::MatrixXd negDiag;\n            negDiag.setIdentity(nineq, nineq);\n            negDiag.diagonal() *= -1;\n            //Matrix onesMatrix = fill(nineq, 1, (double)-1.0);\n            //Matrix negDiag = diag(onesMatrix);\n            \n            //Matrix secondHalf = copy(negDiag, zeroMatrix);\n            \n            firstHalf_e.transpose();\n            Eigen::MatrixXd secondHalf_e(nineq, np + nineq);\n            secondHalf_e << negDiag, zeroMatrix;\n            a_e.resize(nineq + np, neq + nineq);\n            a_e << firstHalf_e.transpose(), secondHalf_e.transpose();\n            a_e.transposeInPlace();\n            //a = transpose(copy(transpose(firstHalf), transpose(secondHalf)));\n        }\n    }\t// end \tif(ind[0][3] > 0){\n    \n    if ( (ind[indHasEq] > 0) && ind[indHasIneq] <= 0 ){\n        a_e.resize(neq, np);\n        a_e.setZero();\n        //a = fill(np, neq, (double)0.0);\n    }\n    if (ind[indHasEq]<= 0 && (ind[indHasIneq] <= 0)){\n        a_e.resize(1, np);\n        a_e.setZero();\n        //a = fill(np, 1, (double)0.0);\n    }\n\n    Eigen::RowVectorXd g_e; g_e.setZero(npic);\n    Eigen::RowVectorXd p_e;\n    p_e = p0_e.block(0, 0, 1, npic);\n    \n    Eigen::MatrixXd b_e;\n    double funv;\n    \n    int solnp_nfn = 0;\n    double go, reduce = 1e-300;\n    int minit;\n    double lambdaValue = lambda;\n    \n    Eigen::MatrixXd constraint_e(1, nc);\n    Eigen::MatrixXd y_e;\n    \n    if (nc > 0) {\n        constraint_e = ob_e.block(0, 1, 1, nc);\n\n        for (int i=0; i<np; i++){\n            int index = nineq + i;\n            p0_e[index] = p0_e[index] + delta;\n            Eigen::MatrixXd tmpv_e;\n            tmpv_e = p0_e.block(0, nineq, 1, npic - nineq);\n            tmpv_e = tmpv_e.array() * vscale_e.block(0, nc+1, 1, np).array();\n            if (verbose >= 2){\n                mxLog(\"7th call is \\n\");\n            }\n            funv = fit.solFun(tmpv_e.data(), &mode);\n            \n            fit.solEqBFun();\n            fit.myineqFun();\n            \n            solnp_nfn = solnp_nfn + 1;\n            \n            Eigen::MatrixXd firstPart_e(1, 1 + neq + nineq);\n            \n            Eigen::RowVectorXd funv_e(1); funv_e[0] = funv;\n            Eigen::RowVectorXd eqv_e(neq); eqv_e = fit.equality;\n            Eigen::RowVectorXd ineqv_e(nineq); ineqv_e= fit.inequality;\n            \n            obj_constr_eval(funv_e, eqv_e, ineqv_e, firstPart_e, verbose);\n            \n            Eigen::RowVectorXd secondPart_e;\n            secondPart_e = vscale_e.block(0, 0, 1, nc+1);\n            firstPart_e = firstPart_e.cwiseQuotient(secondPart_e);\n            ob_e = firstPart_e;\n            \n            g_e[index] = (ob_e(0, 0)-j) / delta;\n            \n            if (verbose >= 3){\n\t\t    mxPrintMat(\"g\", g_e);\n            }\n            \n            a_e.col(index) = (ob_e.block(0, 1, 1, nc) - constraint_e).transpose() / delta;\n            p0_e[index] = p0_e[index] - delta;\n        } // end for (int i=0; i<np, i++){\n        \n        if (mode == -1)\n        {\n            funv = 1e24;\n            mode = 0;\n        }\n        \n        if(ind[indHasIneq] > 0){\n            //constraint[ (neq + 1):(neq + nineq) ] = constraint[ (neq + 1):(neq + nineq) ] - p0[ 1:nineq ]\n            constraint_e.block(0, neq, 1, nineq) = (constraint_e.block(0, neq, 1, nineq) - p0_e.block(0, 0, 1, nineq)).block(0, 0, 1, nineq);\n        }\n        \n        if (false && solvecond(a_e) > 1/DBL_EPSILON) { // this can't be the cheapest way to check TODO\n            Rf_error(\"Redundant constraints were found. Poor intermediate results may result. \"\n                     \"Remove redundant constraints and re-OPTIMIZE.\");\n        }\n        \n        b_e = (a_e * p0_e.transpose()).transpose();\n        //  b [nc,1]\n        b_e -= constraint_e;\n        ch = -1;\n        alp[0] = tol - constraint_e.cwiseAbs().maxCoeff();\n        if (alp[0] <= 0){\n            \n            ch = 1;\n            \n        } // end if (alp[0][0] <= 0){\n        \n        if (alp[0] <= 0){\n            int npic_int = npic;\n            Eigen::RowVectorXd onesMatrix_e;\n            onesMatrix_e.setOnes(1, 1);\n            Eigen::RowVectorXd p0_e_copy = p0_e;\n            p0_e.resize(p0_e_copy.rows(), p0_e_copy.cols() + onesMatrix_e.cols());\n            p0_e << p0_e_copy, onesMatrix_e;\n            constraint_e *= (-1.0);\n            Eigen::MatrixXd a_e_copy = a_e;\n            a_e.resize(a_e.rows(), a_e.cols() + constraint_e.transpose().cols());\n            a_e << a_e_copy, constraint_e.transpose();\n            Eigen::MatrixXd firstMatrix_e(1, npic);\n            firstMatrix_e.setZero();\n            Eigen::MatrixXd cx_e(firstMatrix_e.rows(), firstMatrix_e.cols() + onesMatrix_e.cols());\n            cx_e << firstMatrix_e, onesMatrix_e;\n            Eigen::MatrixXd dx_e(npic + 1, 1);\n            dx_e.setOnes();\n            go = 1;\n            minit = 0;\n            \n            while(go >= tol)\n            {\n                minit = minit + 1;\n                Eigen::MatrixXd gap_e(mm, 2);\n                gap_e.setZero();\n                gap_e.col(0) = p0_e.block(0, 0, 1, mm).transpose() - pb_e.col(0);\n                gap_e.col(1) = pb_e.col(1) - p0_e.block(0, 0, 1, mm).transpose();\n                rowSort_e(gap_e);\n                dx_e.transpose().block(0, 0, 1, mm) = gap_e.col(0).transpose().block(0, 0, 1, mm);\n                dx_e(npic_int, 0) = p0_e(0, npic_int);\n                Eigen::MatrixXd argum1_e;\n                argum1_e = a_e * dx_e.asDiagonal();\n                argum1_e.transposeInPlace();\n                Eigen::MatrixXd argum2_e;\n                argum2_e = cx_e.asDiagonal() * dx_e;\n                y_e = QRdsolve(argum1_e, argum2_e);\n                Eigen::MatrixXd cx_e_r;\n                cx_e_r = cx_e.transpose() - (a_e.transpose() * y_e);\n                dx_e = (cx_e_r.asDiagonal() * dx_e).asDiagonal() * dx_e;\n                Eigen::MatrixXd v_e = dx_e.transpose();\n                int indexx = npic;\n                \n                if (v_e(0, indexx) > 0)\n                {\n                    double z = p0_e(indexx)/v_e(0, indexx);\n                    \n                    for (int i=0; i<mm; i++)\n                    {\n                        if(v_e(0, i) < 0)\n                        {\n                            z = std::min(z, -(pb_e(i, 1) - p0_e(i))/v_e(0, i));\n                            \n                        }\n                        else if(v_e(0, i) > 0)\n                        {\n                            \n                            z = std::min(z, (p0_e(i) - pb_e(i, 0))/v_e(0, i));\n                        }\n                    }\n                    \n                    if(z < (p0_e(indexx)/v_e(0, indexx))) {\n                        z *= 0.9;\n                    }\n                    \n                    p0_e -= v_e * z;\n                    go = p0_e(indexx);\n                    if(minit >= 10){\n                        go = 0;\n                    }\n                }\n                else{\n                    go = 0;\n                    minit = 10;\n                }\n            }// end while(go >= tol)\n            \n            if (minit >= 10){\n                mxLog(\"The linearized problem has no feasible solution. The problem may not be feasible.\");\n            }\n            \n            int h;\n            Eigen::MatrixXd a_e_c(nc, npic);\n            \n            for (h = 0; h<a_e.rows(); h++)\n            {\n                a_e_c.row(h) = a_e.row(h).block(0, 0, 1, npic);\n            }\n            a_e.resize(a_e_c.rows(), a_e_c.cols());\n            a_e = a_e_c;\n            b_e = (a_e * p0_e.block(0, 0, 1, npic).transpose()).transpose();\n        }// end if(M(alp, 0, 0) <= 0)\n    } // end if (nc > 0){\n    \n    p_e = p0_e.block(0, 0, 1, npic);\n    \n    if (nc == 0){\n        y_e.resize(1,1);\n        y_e(0, 0) = 0;\n    }\n\n    if (ch > 0){\n        \n        Eigen::MatrixXd tmpv_e;\n        tmpv_e = p_e.block(0, nineq, 1, npic-nineq);\n        tmpv_e = tmpv_e.array() * vscale_e.block(0, nc+1, 1, np).array();\n        funv = fit.solFun(tmpv_e.data(), &mode);\n        if (verbose >= 3){\n            mxLog(\"funv is: \\n\");\n            mxLog(\"%f\", funv);\n        }\n        \n        if (mode == -1)\n        {\n            funv = 1e24;\n            mode = 0;\n        }\n        \n        fit.solEqBFun();\n        \n        fit.myineqFun();\n        \n        solnp_nfn = solnp_nfn + 1;\n        Eigen::MatrixXd firstPart_e(1, 1 + neq + nineq);\n        Eigen::RowVectorXd funv_e(1); funv_e[0] = funv;\n        Eigen::RowVectorXd eqv_e(neq); eqv_e = fit.equality;\n        Eigen::RowVectorXd ineqv_e(nineq); ineqv_e= fit.inequality;\n        \n        obj_constr_eval(funv_e, eqv_e, ineqv_e, firstPart_e, verbose);\n        \n        Eigen::RowVectorXd secondPart_e;\n        secondPart_e = vscale_e.block(0, 0, 1, nc+1);\n        firstPart_e = firstPart_e.cwiseQuotient(secondPart_e);\n        ob_e = firstPart_e;\n        \n    } // end of if (ch>0)\n    \n    j = ob_e(0, 0);\n    \n    if (ind[indHasIneq] > 0){\n        ob_e.block(0, neq+1, 1, nc-neq) -= p_e.block(0, 0, 1, nineq);\n    }\n    \n    if (nc > 0){\n        Eigen::MatrixXd result_e = ob_e.block(0, 1, 1, nc);\n        result_e -= (a_e * p_e.transpose()).transpose();\n        result_e += b_e;\n        ob_e.block(0, 1, 1, nc) = result_e;\n        double vnormTerm = ob_e.block(0, 1, 1, nc).squaredNorm();\n        double dotProductTerm = yy_e.transpose().row(0).dot(ob_e.block(0, 1, 1, nc).row(0));\n        j = ob_e(0, 0) - dotProductTerm + rho * vnormTerm;\n    }\n    \n    minit = 0;\n    Eigen::MatrixXd yg_e;\n    Eigen::MatrixXd yg_rec(1, 2);\n    Eigen::MatrixXd sx_e;\n    sx_e.setZero(p_e.rows(), p_e.cols());\n    Eigen::MatrixXd obm_e;\n    \n    while (minit < maxit){\n        minit = minit + 1;\n        if (ch > 0){\n            \n            for (int i=0; i<np; i++){\n                int index = nineq + i;\n                p_e[index] = p_e[index] + delta;\n                Eigen::MatrixXd tmpv_e = p_e.block(0, nineq, 1, npic - nineq).array() * vscale_e.block(0, nc+1, 1, np).array();\n                if (verbose >= 3){\n                    mxLog(\"9th call is \\n\");\n                }\n                mode = 0;\n                funv = fit.solFun(tmpv_e.data(), &mode);\n                if (verbose >= 3){\n                    mxLog(\"funv is: \\n\");\n                    mxLog(\"%f\", funv);\n                }\n                \n                if (mode == -1)\n                {\n                    funv = 1e24;\n                    mode = 0;\n                }\n                fit.solEqBFun();\n                fit.myineqFun();\n                \n                solnp_nfn = solnp_nfn + 1;\n                \n                Eigen::MatrixXd firstPart_e(1, 1 + neq + nineq);\n                Eigen::RowVectorXd funv_e(1); funv_e[0] = funv;\n                Eigen::RowVectorXd eqv_e(neq); eqv_e = fit.equality;\n                Eigen::RowVectorXd ineqv_e(nineq); ineqv_e= fit.inequality;\n                \n                obj_constr_eval(funv_e, eqv_e, ineqv_e, firstPart_e, verbose);\n                \n                Eigen::RowVectorXd secondPart_e;\n                secondPart_e = vscale_e.block(0, 0, 1, nc+1);\n                \n                firstPart_e = firstPart_e.cwiseQuotient(secondPart_e);\n                obm_e = firstPart_e;\n                \n                if (verbose >= 3){\n                    mxLog(\"j is: \\n\");\n                    mxLog(\"%f\", j);\n                }\n                \n                if (ind[indHasIneq] > 0.5){\n                    obm_e.block(0, neq+1, 1, nc-neq) -= p_e.block(0, 0, 1, nineq);\n                }\n                \n                double obm = obm_e(0, 0);\n                if (nc > 0){\n                    Eigen::MatrixXd result_e = obm_e.block(0, 1, 1, nc);\n                    result_e -= (a_e * p_e.transpose()).transpose();\n                    result_e += b_e;\n                    obm_e.block(0, 1, 1, nc) = result_e;\n                    double vnormTerm = obm_e.block(0, 1, 1, nc).squaredNorm();\n                    double dotProductTerm = yy_e.transpose().row(0).dot(obm_e.block(0, 1, 1, nc).row(0));\n                    obm = obm_e(0, 0) - dotProductTerm + rho * vnormTerm;\n                }\n                \n                if (verbose >= 3)   mxLog(\"obm is: %.20f\", obm);\n                \n                g_e[index] = (obm - j)/delta;\n                p_e[index] = p_e[index] - delta;\n                \n                if (verbose >= 3){\n\t\t\tmxPrintMat(\"g\", g_e);\n\t\t\tmxPrintMat(\"p\", p_e);\n                }\n            } // end for (i=0; i<np; i++){\n            \n            if (ind[indHasIneq] > 0.5){\n                Eigen::RowVectorXd temp;\n                temp.setZero(1, nineq);\n                g_e.block(0, 0, 1, nineq) = temp;\n            }\n        } // end if (ch > 0){\n        \n        if (minit > 1){\n            yg_e = g_e - yg_e;\n            sx_e = p_e - sx_e;\n            Eigen::MatrixXd sc_m1 = (sx_e * hessv_e) * sx_e.transpose();\n            Eigen::MatrixXd sc_m2 = sx_e * yg_e.transpose();\n            Eigen::RowVectorXd sc_e(2);\n            sc_e[0] = sc_m1(0, 0);\n            sc_e[1] = sc_m2(0, 0);\n            if ((sc_e[0] * sc_e[1]) > 0){\n                //hessv  = hessv - ( sx %*% t(sx) ) / sc[ 1 ] + ( yg %*% t(yg) ) / sc[ 2 ]\n                Eigen::MatrixXd sx_t = sx_e.transpose();\n                sx_e.resize(hessv_e.rows(), sx_t.cols());\n                sx_e = hessv_e * sx_t;\n                \n                Eigen::MatrixXd sxMatrix = sx_e * sx_e.transpose();\n                sxMatrix /= sc_e[0];\n                Eigen::MatrixXd ygMatrix = yg_e.transpose() * yg_e;\n                ygMatrix /= sc_e[1];\n                hessv_e -= sxMatrix;\n                hessv_e += ygMatrix;\n            }\n        }\n        \n        Eigen::MatrixXd dx_e(1, npic);\n        dx_e.setOnes();\n        dx_e *= 0.01;\n        \n        {\n            Eigen::MatrixXd gap_e(pb_e.rows(), pb_e.cols());\n            gap_e.setZero();\n            gap_e.col(0) = p_e.block(0, 0, 1, mm).transpose() - pb_e.col(0);\n            gap_e.col(1) = pb_e.col(1) - p_e.block(0, 0, 1, mm).transpose();\n            rowSort_e(gap_e);\n            Eigen::MatrixXd temp(mm, 1);\n            temp.setOnes();\n            Eigen::MatrixXd gap_eTemp(mm, 1);\n            gap_eTemp = gap_e.col(0) + (temp * sqrt(DBL_EPSILON));\n            gap_e.resize(mm, 1);\n            gap_e = gap_eTemp;\n            dx_e.block(0, 0, 1, mm) = temp.cwiseQuotient(gap_e).transpose();\n        }\n        \n        go = -1;\n        lambdaValue = lambdaValue/10.0;\n        \n        if (verbose >= 3){\n            mxLog(\"lambdaValue is: \\n\");\n            mxLog(\"%.20f\", lambdaValue);\n        }\n        \n        while(go <= 0){\n            Eigen::RowVectorXd dxDiagValues(dx_e.cols());\n            dxDiagValues = dx_e.cwiseProduct(dx_e);\n            Eigen::MatrixXd cz_e;\n            cz_e = dxDiagValues.asDiagonal();\n            cz_e = hessv_e + (cz_e * lambdaValue);\n            Eigen::MatrixXd cz_chol = cz_e.llt().matrixL();\n            cz_chol.transposeInPlace();\n\n            if (!R_FINITE((cz_e.maxCoeff())))\n            {\n                if (verbose >= 3){\n                    mxLog(\"here in findMax\");\n                }\n                flag = 1;\n                p_e = p_e.cwiseProduct(vscale_e.block(0, neq+1, 1, nc+np-neq));\n                if (nc > 0){ y_e.resize(1, 1); y_e(0, 0) = 0;}\n                hessv_e = hessv_e.cwiseQuotient(vscale_e.block(0, neq+1, 1, nc+np-neq).transpose() * vscale_e.block(0, neq+1, 1, nc+np-neq)) *vscale_e(0);\n                resP = p_e;\n                resY = y_e;\n                resHessv = hessv_e;\n                resLambda = lambda;\n                resGrad = g_e;\n                return;\n            }\n            \n            Eigen::MatrixXd cz_inv;\n            cz_inv = cz_chol.inverse();\n            \n            if (verbose >= 3){\n                mxLog(\"cz.rows: %d\", cz_chol.rows());\n                mxLog(\"cz.cols: %d\", cz_chol.cols());\n            }\n            \n            yg_e.resize(cz_inv.cols(), g_e.rows());\n            yg_e = cz_inv.transpose() * g_e.transpose();\n            if (minit == 1) yg_rec(0, 0) = yg_e.squaredNorm();\n            \n            Eigen::MatrixXd u_e;\n            if (nc <= 0){\n                u_e = (cz_inv * (-1.0)) * yg_e;\n                u_e.transposeInPlace();\n            }\n            else{\n                //y = qr.solve(t(cz) %*% t(a), yg)\n                Eigen::MatrixXd argum1_e;\n                argum1_e = cz_inv.transpose() * a_e.transpose();\n                Eigen::MatrixXd solution;\n                \n                solution = QRdsolve(argum1_e, yg_e);\n                \n                y_e.resize(solution.cols(), solution.rows());\n                y_e = solution.transpose();\n                u_e = (cz_inv * (-1.0)) * (yg_e - (argum1_e * solution));\n                u_e.transposeInPlace();\n            }\n            \n            p0_e.resize(npic);\n            p0_e = u_e.block(0, 0, 1, npic) + p_e;\n            \n            {\n                Eigen::MatrixXd listPartOne = p0_e.block(0, 0, 1, mm).transpose() - pb_e.col(0);\n                Eigen::MatrixXd listPartTwo = pb_e.col(1) - p0_e.block(0, 0, 1, mm).transpose();\n                Eigen::MatrixXd llist(listPartOne.rows(), listPartOne.cols() + listPartTwo.cols());\n                llist << listPartOne, listPartTwo;\n                go = llist.minCoeff();\n                lambdaValue = 3 * lambdaValue;\n                if (verbose >= 3){\n                    mxLog(\"go is: \\n\");\n                    mxLog(\"%f\", go);\n                    mxLog(\"lambdaValue is: \\n\");\n                    mxLog(\"%f\", lambdaValue);\n                    \n                }\n            }\n        } // end while(go <= 0){\n        \n        alp[0] = 0;\n        Eigen::MatrixXd ob1_e = ob_e;\n        Eigen::MatrixXd ob2_e = ob1_e;\n        sob[0] = j;\n        sob[1] = j;\n        \n        if (verbose >= 3){\n\t\tmxPrintMat(\"sob\", sob);\n        }\n        \n        Eigen::MatrixXd ptt_e(p_e.cols(), p_e.rows() + p_e.rows());\n        ptt_e << p_e.transpose(), p_e.transpose();\n        alp[2] = 1.0;\n        \n        Eigen::MatrixXd ptt_temp(ptt_e.rows(), ptt_e.cols() + p0_e.rows());\n        ptt_temp << ptt_e, p0_e.transpose();\n        ptt_e.resize(ptt_temp.rows(), ptt_temp.cols());\n        ptt_e = ptt_temp;\n        Eigen::MatrixXd pttCol;\n        pttCol = ptt_e.col(2);\n        Eigen::MatrixXd tmpv_e = pttCol.transpose().block(0, nineq, 1, npic - nineq).cwiseProduct(vscale_e.block(0, nc+1, 1, np));\n        \n        mode = 1;\n        funv = fit.solFun(tmpv_e.data(), &mode);\n        if (verbose >= 3){\n\t\tmxPrintMat(\"g\", g_e);\n            mxLog(\"funv is: \\n\");\n            mxLog(\"%f\", funv);\n        }\n        \n        if (mode == -1)\n        {\n            funv = 1e24;\n            mode = 0;\n        }\n        \n        fit.solEqBFun();\n        fit.myineqFun();\n        \n        solnp_nfn = solnp_nfn + 1;\n        \n        Eigen::MatrixXd firstPart_e(1, 1 + neq + nineq);\n        Eigen::RowVectorXd funv_e(1); funv_e[0] = funv;\n        Eigen::RowVectorXd eqv_e(neq); eqv_e = fit.equality;\n        Eigen::RowVectorXd ineqv_e(nineq); ineqv_e= fit.inequality;\n        \n        obj_constr_eval(funv_e, eqv_e, ineqv_e, firstPart_e, verbose);\n        \n        Eigen::RowVectorXd secondPart_e;\n        secondPart_e = vscale_e.block(0, 0, 1, nc+1);\n        firstPart_e = firstPart_e.cwiseQuotient(secondPart_e);\n        Eigen::MatrixXd ob3_e = firstPart_e;\n        sob[2] = ob3_e(0, 0);\n        \n        if (ind[indHasIneq] > 0.5){\n            // ob3[ (neq + 2):(nc + 1) ] = ob3[ (neq + 2):(nc + 1) ] - ptt[ 1:nineq, 3 ]\n            Eigen::MatrixXd partOne = ob3_e.block(0, neq+1, 1, nc-neq);\n            Eigen::MatrixXd partTwo = ptt_e.col(2).transpose().block(0, 0, 1, nineq);\n            ob3_e.block(0, neq+1, 1, nc-neq) = partOne - partTwo;\n        }\n        \n        if (nc > 0){\n            //sob[ 3 ] = ob3[ 1 ] - t(yy) %*% ob3[ 2:(nc + 1) ] + rho * .vnorm(ob3[ 2:(nc + 1) ]) ^ 2\n            Eigen::MatrixXd result_e = ob3_e.block(0, 1, 1, nc);\n            result_e -= (a_e * ptt_e.col(2)).transpose();\n            result_e += b_e;\n            ob3_e.block(0, 1, 1, nc) = result_e;\n            double vnormTerm = ob3_e.block(0, 1, 1, nc).squaredNorm();\n            double dotProductTerm = yy_e.transpose().row(0).dot(ob3_e.block(0, 1, 1, nc).row(0));\n            sob[2] = ob3_e(0, 0) - dotProductTerm + (rho * vnormTerm);\n        }\n\n        go = 1;\n        \n        while(go > tol){\n            alp[1] = (alp[0] + alp[2]) / 2.0;\n            \n            ptt_e.col(1) = (p_e * (1 - alp[1])) + p0_e * alp[1];\n            Eigen::MatrixXd tmpv_e = ptt_e.col(1).transpose().block(0, nineq, 1, npic - nineq).cwiseProduct(vscale_e.block(0, nc+1, 1, np));\n\n            if (verbose >= 3){\n                mxLog(\"11th call is \\n\");\n            }\n            \n            mode = 0;\n            funv = fit.solFun(tmpv_e.data(), &mode);\n            if (verbose >= 3){\n                mxLog(\"funv is: \\n\");\n                mxLog(\"%f\", funv);\n            }\n            \n            if (mode == -1)\n            {\n                funv = 1e24;\n                mode = 0;\n            }\n            \n            fit.solEqBFun();\n            fit.myineqFun();\n            \n            solnp_nfn = solnp_nfn + 1;\n            Eigen::MatrixXd firstPart_e(1, 1 + neq + nineq);\n            Eigen::RowVectorXd funv_e(1); funv_e[0] = funv;\n            Eigen::RowVectorXd eqv_e(neq); eqv_e = fit.equality;\n            Eigen::RowVectorXd ineqv_e(nineq); ineqv_e= fit.inequality;\n\n            obj_constr_eval(funv_e, eqv_e, ineqv_e, firstPart_e, verbose);\n            \n            Eigen::RowVectorXd secondPart_e;\n            secondPart_e = vscale_e.block(0, 0, 1, nc+1);\n            firstPart_e = firstPart_e.cwiseQuotient(secondPart_e);\n            ob2_e = firstPart_e;\n            \n            sob[1] = ob2_e(0, 0);\n            if (verbose >= 3){\n\t\t    mxPrintMat(\"sob\", sob);\n            }\n            if (ind[indHasIneq] > 0.5){\n                Eigen::MatrixXd partOne = ob2_e.block(0, neq+1, 1, nc-neq);\n                Eigen::MatrixXd partTwo = ptt_e.col(1).transpose().block(0, 0, 1, nineq);\n                ob2_e.block(0, neq+1, 1, nc-neq) = partOne - partTwo;\n            }\n            if (nc > 0){\n                Eigen::MatrixXd result_e = ob2_e.block(0, 1, 1, nc);\n                result_e -= (a_e * ptt_e.col(1)).transpose();\n                result_e += b_e;\n                ob2_e.block(0, 1, 1, nc) = result_e;\n                double vnormTerm = ob2_e.block(0, 1, 1, nc).squaredNorm();\n                Eigen::MatrixXd temp = ob2_e.block(0, 1, 1, nc);\n                double dotProductTerm = yy_e.transpose().row(0).dot(temp.row(0));\n                sob[1] = ob2_e(0, 0) - dotProductTerm + (rho * vnormTerm);\n            }\n            \n            const double sobMax = sob.maxCoeff();\n            if (verbose >= 3){\n                mxLog(\"sobMax is: %f\", sobMax);\n            }\n            if (sobMax < j){\n                go = tol * (sobMax - sob.minCoeff()) / (j - sobMax);\n            }\n            \n            const bool condif1 = (sob[1] >= sob[0]);\n            const bool condif2 = (sob[0] <= sob[2]) && (sob[1] < sob[0]);\n            const bool condif3 = (sob[1] <  sob[0]) && (sob[0] > sob[2]);\n            \n            if (condif1){\n                sob[2] = sob[1];\n                ob3_e = ob2_e;\n                alp[2] = alp[1];\n                ptt_e.col(2) = ptt_e.col(1);\n                \n            }\n            \n            if (condif2){\n                sob[2] = sob[1];\n                ob3_e = ob2_e;\n                alp[2] = alp[1];\n                ptt_e.col(2) = ptt_e.col(1);\n            }\n            \n            if (condif3){\n                sob[0] = sob[1];\n                ob1_e = ob2_e;\n                alp[0] = alp[1];\n                ptt_e.col(0) = ptt_e.col(1);\n            }\n            \n            if (go >= tol){\n                go = alp[2] - alp[0];\n                if (verbose >= 3){\n                    mxLog(\"go is: \\n\");\n                    mxLog(\"%f\", go);\n                }\n            }\n            \n        } // \twhile(go > tol){\n        \n        if (verbose >= 3){\n            mxLog(\"go is: \\n\");\n            mxLog(\"%.16f\", go);\n        }\n\n        sx_Matrix = sx_e;\n        sx_e.resize(p_e.rows(), p_e.cols());\n        sx_e = p_e;\n        yg_e.resize(g_e.rows(), g_e.cols());\n        yg_e = g_e;\n        \n        ch = 1;\n        \n        double obn = sob.minCoeff();\n        if (verbose >= 3){\n            mxLog(\"obn is: \\n\");\n            mxLog(\"%f\", obn);\n        }\n        if (j <= obn){\n            maxit = minit;\n        }\n        if (verbose >= 3){\n            mxLog(\"j is: \\n\");\n            mxLog(\"%f\", j);\n        }\n        double reduce = (j - obn) / ((double)1.0 + (double)fabs(j));\n        if (verbose >= 3){\n            mxLog(\"reduce is: \\n\");\n            mxLog(\"%f\", reduce);\n        }\n        if (reduce < tol){\n            maxit = minit;\n        }\n        \n        const bool condif1 = (sob[0] <  sob[1]);\n        const bool condif2 = (sob[2] <  sob[1]) && (sob[0] >= sob[1]);\n        const bool condif3 = (sob[0] >= sob[1]) && (sob[2] >= sob[1]);\n        \n        if (condif1){\n            j = sob[0];\n            p_e = ptt_e.col(0).transpose();\n            ob_e = ob1_e;\n            if (verbose >= 3){\n                mxLog(\"condif1\\n\");\n                mxLog(\"j is: \\n\");\n                mxLog(\"%f\", j);\n            }\n        }\n        \n        if (condif2){\n            \n            j = sob[2];\n            p_e = ptt_e.col(2).transpose();\n            ob_e = ob3_e;\n            if (verbose >= 3){\n                mxLog(\"condif2\\n\");\n                mxLog(\"j is: \\n\");\n                mxLog(\"%f\", j);\n            }\n            \n        }\n        \n        if (condif3){\n            j = sob[1];\n            p_e = ptt_e.col(1).transpose();\n            ob_e = ob2_e;\n            if (verbose >= 3){\n                mxLog(\"condif3\\n\");\n                mxLog(\"j is: \\n\");\n                mxLog(\"%f\", j);\n            }\n        }\n    } // end while (minit < maxit){\n    \n    yg_rec(0, 1) = yg_e.squaredNorm();\n    if(yg_rec(0, 0) / yg_rec(0, 1) > 1000)  flag_NormgZ = 1;\n    \n    minr_rec = minit;\n\n    p_e = p_e.cwiseProduct(vscale_e.block(0, neq+1, 1, nc+np-neq));\n    // I need vscale, p, y, hessv\n    if (nc > 0){\n        y_e *= vscale_e(0);\n        y_e = y_e.cwiseQuotient(vscale_e.block(0, 1, 1, nc));\n    }\n    \n    // hessv = vscale[ 1 ] * hessv / (vscale[ (neq + 2):(nc + np + 1) ] %*%\n    //                                t(vscale[ (neq + 2):(nc + np + 1) ]) )\n    \n    Eigen::MatrixXd transposePart;\n    transposePart = vscale_e.block(0, neq+1, 1, nc+np-neq).transpose() * vscale_e.block(0, neq+1, 1, nc+np-neq);\n    hessv_e = hessv_e.cwiseQuotient(transposePart);\n    hessv_e = hessv_e * vscale_e(0);\n    \n    if (verbose >= 1 && reduce > tol) {\n        mxLog(\"m3 solnp Rf_error message being reported.\");\n    }\n\n    resP = p_e;\n    resY = y_e.block(0, 0, 1, yyRows).transpose();\n    resHessv = hessv_e;\n    resLambda = lambdaValue;\n    resGrad = g_e;\n    \n} // end subnp\n\ntemplate <typename T1, typename T2>\nvoid CSOLNP::obj_constr_eval(Eigen::MatrixBase<T2>& objVal, Eigen::MatrixBase<T2>& eqval, Eigen::MatrixBase<T2>& ineqval, Eigen::MatrixBase<T1>& fitVal, int verbose)\n{\n\tif (!std::isfinite(objVal(0))) {\n\t\tfitVal.setConstant(1e24);\n\t\treturn;\n\t}\n\n    if (optimize_initial_inequality_constraints){\n        double total = ineqval.array().min(0).sum();\n        fitVal << fabs(total) - 1e-4, eqval;\n    }\n    else{\n\t    fitVal << objVal, eqval, ineqval;\n    }\n\n    if (!std::isfinite(fitVal.sum())) {\n\t\tfitVal.setConstant(1e24);\n\t\treturn;\n    }\n    if (verbose >= 4) mxPrintMat(\"fitVal\", fitVal);\n}\n", "meta": {"hexsha": "9da478ed102b1e1d013ab738970e829eef535646", "size": 47698, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/subnp.cpp", "max_stars_repo_name": "JuKa87/OpenMx", "max_stars_repo_head_hexsha": "f055df183ca433abd194e494a433142825666128", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/subnp.cpp", "max_issues_repo_name": "JuKa87/OpenMx", "max_issues_repo_head_hexsha": "f055df183ca433abd194e494a433142825666128", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/subnp.cpp", "max_forks_repo_name": "JuKa87/OpenMx", "max_forks_repo_head_hexsha": "f055df183ca433abd194e494a433142825666128", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.8764204545, "max_line_length": 255, "alphanum_fraction": 0.4757012873, "num_tokens": 14188, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6926419831347361, "lm_q2_score": 0.48828339529583464, "lm_q1q2_score": 0.3382055792494692}}
{"text": "/*\n  Copyright (c) 2019 Matthew H. Reilly (kb1vc)\n  All rights reserved.\n\n  Redistribution and use in source and binary forms, with or without\n  modification, are permitted provided that the following conditions are\n  met:\n\n  Redistributions of source code must retain the above copyright\n  notice, this list of conditions and the following disclaimer.\n\n  Redistributions in binary form must reproduce the above copyright\n  notice, this list of conditions and the following disclaimer in\n  the documentation and/or other materials provided with the\n  distribution.\n\n  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n  \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n  A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n  HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n  SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n  LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n  DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n  THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n  (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n  OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*/\n#include \"Point.hxx\"\n#ifndef __NO_MATH_INLINES\n#define __NO_MATH_INLINES 1\n#endif\n\n#include <boost/format.hpp>\n#include <regex>\n#include <stdexcept>\n#include <iostream>\n#include <cmath>\n#include <math.h>\n#include <limits>\n\nnamespace GeoProf {\n\n  std::regex Point::grid_regexp(\"[A-R][A-R][0-9][0-9][A-X][A-X]\", std::regex_constants::icase);\n\n    // Useful constants\n  const double Point::clarke_66_al = 6378206.4;    /*Clarke 1866 ellipsoid*/\n  const double Point::clarke_66_bl = 6356583.8; \n  const double Point::rad_per_deg = (M_PI / 180.0);\n  \n  double Point::bearingTo(const Point & other) const {\n    double br, rbr, dst; \n    bearingDistanceTo(other, br, rbr, dst);\n    \n    return br; \n  }\n\n  double Point::distanceTo(const Point & other) const {\n    double br, rbr, dst; \n    bearingDistanceTo(other, br, rbr, dst);\n    \n    return dst; \n  }\n\n  // In g++ we get some very bad behavior around generated NANs -- these get handled better with more cautious math.\n  __attribute__((optimize(\"-fno-fast-math\")))\n  void Point::bearingDistanceTo(const Point & other, double & bearing, double & reverse_bearing, double & distance) const {\n    /*Taken directly from:       */\n    /*Thomas, P.D., 1970, Spheroidal Geodesics, reference systems,*/\n    /*    & local geometry, U.S. Naval Oceanographic Office SP-138,*/\n    /*    165 pp.*/\n\n    /*assumes North Latitude and East Longitude are positive*/\n    // Translated from C, translated from fortran as in this comment\n    /* forward.f -- translated by f2c (version 19960717).\n       then hacked up a bit by hand to remove the dependence on \n       the f2c libraries and such. */ \n\n    double BOA, F, P1R, P2R, L1R, L2R, DLR, T1R, T2R, TM, DTM, STM, CTM, SDTM,\n      CDTM, KL, KK, SDLMR, L, CD, DL, SD, T, U, V, D, X, E, Y, A, FF64,\n      TDLPM, HAPBR, HAMBR, A1M2, A2M1;\n\n    if((fabs(other.lat - this->lat) < 1.0e-10) && (fabs(other.lon - this->lon) < 1.0e-10)) {\n      bearing = 0.0;\n      reverse_bearing = 0.0;\n      distance = 0.0;\n      return;\n    }\n    BOA = clarke_66_bl / clarke_66_al;\n    F = 1.0 - BOA;\n    P1R = this->lat * rad_per_deg;\n    P2R = other.lat * rad_per_deg;\n    L1R = this->lon * rad_per_deg;\n    L2R = other.lon * rad_per_deg;\n    DLR = L1R - L2R;\n    T1R = atan(BOA * tan(P1R));\n    T2R = atan(BOA * tan(P2R));\n    TM = (T1R + T2R) / 2.0;\n    DTM = (T2R - T1R) / 2.0;\n    STM = sin(TM);\n    CTM = cos(TM);\n    SDTM = sin(DTM);\n    CDTM = cos(DTM);\n    KL = STM * CDTM;\n    KK = SDTM * CTM;\n    SDLMR = sin(DLR / 2.0);\n    L = SDTM * SDTM + SDLMR * SDLMR * (CDTM * CDTM - STM * STM);\n    CD = 1.0 - 2.0 * L;\n    DL = acos(CD);\n    SD = sin(DL);\n    \n    // Believe it or not, sometimes CD is 1.0 (when L, for instance, is 0)\n    // All this NAN stuff is pretty hazardous. Make sure 0/0 is really\n    // lim x -> 0  x/x = 1.\n    if(fabs(DL - SD) < 1e-25) {\n      T = 1.0;    \n    }\n    else {\n      T = DL / SD;      \n    }\n    U = 2.0 * KL * KL / (1.0 - L);\n    V = 2.0 * KK * KK / L;\n    D = 4.0 * T * T;\n    X = U + V;\n    E = -2.0 * CD;\n    Y = U - V;\n    A = -D * E;\n    FF64 = F * F / 64.0;\n    distance = clarke_66_al * SD * (T -\n\t\t\t\t    F / 4.0 * (T * X - Y) +\n\t\t\t\t    FF64 * (X * (A + (T - (A + E) / 2.0) * X) +\n\t\t\t\t\t    Y * (E * Y - 2.0 * D) + D * X * Y)) / 1000.0;\n\n    double dlrtan = tan(DLR);\n    // At times DLR is 2pi... or pi... then we need to\n    // fixup the atan calculation, as TDLPM is going to be very very large. \n      \n    double tanarg = (DLR - (E * (4.0 - X) + 2.0 * Y)\n\t\t     * (F / 2.0 * T + FF64 * (32.0 * T + (A - 20.0 * T) * X - 2.0 * (D + 2.0) * Y)) / 4.0 * dlrtan) / 2.0;\n\n    TDLPM = tan(tanarg);\n\n    HAPBR = atan2Pt(SDTM, CTM * TDLPM); \n    HAMBR = atan2Pt(CDTM, STM * TDLPM); \n\n    A1M2 = 2.0 * M_PI + HAMBR - HAPBR;\n    A2M1 = 2.0 * M_PI - HAMBR - HAPBR;\n\n    // bring A1M2 into the range 0..2pi\n    A1M2 = inSpan(A1M2);\n    A2M1 = inSpan(A2M1); \n\n    /* these 360 degree corrections were added to\n       fix a disagreement in the semantics of \n       the original implementation of ATAN2, vs\n       the implementation from the gnu c math rtl. */\n    bearing = (A1M2 == 0.0) ? 0.0 : (360.0 - (A1M2 / rad_per_deg));\n    reverse_bearing = (A2M1 == 0.0) ? 0.0 : (360.0 - (A2M1 / rad_per_deg));\n    if((bearing - 360.0) >= 0.0) bearing -= 360.0;\n    if((reverse_bearing - 360.0) >= 0.0) reverse_bearing -= 360.0;\n  }\n\n  bool Point::recCorrectBearingDistanceTo(const Point & other, \n\t\t\t\t\t  const double bearing, \n\t\t\t\t\t  const double distance, \n\t\t\t\t\t  const double b_span,\n\t\t\t\t\t  const double d_span,\n\t\t\t\t\t  double & new_bearing, \n\t\t\t\t\t  double & new_distance\n\t\t\t\t\t  ) const {\n    \n    // minimize distance error;\n    double err_dist = 1e6; // we're closer than that..\n    new_bearing = bearing;\n    new_distance = distance; \n    bool ret = false; \n    // sweep +/- 1 degree\n    for(double b_inc = -1.0 * b_span; b_inc < b_span; b_inc += (b_span * 0.25)) {\n      double az = bearing + b_inc;\n      if(az < 0.0) az = az + 360.0;\n      if(az > 360.0) az = az - 360.0;\n      bool got_better = false; \n      double last_err = 1e6;\n      for(double distinc = -1.0 * d_span; distinc < d_span; distinc += (d_span * 0.25)) {\n\tdouble rng = distance + distinc;\n\tif(rng < 0.1) rng = 0.1; \n\t// now go to the remote point\n\tPoint next; \n\tstepTo(az, rng, next); \n\t// and calculate the distance between that and \"other\"\n\tdouble d_err = other.distanceTo(next);\n\tif(d_err < err_dist) {\n\t  err_dist = d_err; \n\t  new_bearing = az; \n\t  new_distance = rng; \n\t  got_better = true; \n\t  ret = true; \n\t}\n\tif(d_err > last_err) break; // we're getting worse. \n\tlast_err = d_err;\n      }\n      // if we didn't improve on the last azimuth, bail out\n      if(!got_better) break;\n    }\n    return (err_dist < 0.01); // if we're within 10m, let's quit.\n  }\n    \n  void Point::correctBearingDistanceTo(const Point & other, \n\t\t\t\t       const double bearing, \n\t\t\t\t       const double distance, \n\t\t\t\t       double & new_bearing, \n\t\t\t\t       double & new_distance) const {\n    new_bearing = bearing;\n    new_distance = distance;\n    double b_span = 1.0;\n    double d_span = 30.0; \n    for(int i = 0; i < 16; i++) {\n      if(recCorrectBearingDistanceTo(other, new_bearing, new_distance, b_span, d_span, new_bearing, new_distance)) return;\n      b_span = b_span * 0.25;\n      d_span = d_span * 0.25; \n      if((b_span < 0.01) && (d_span < 0.01)) break; \n    }\n  }\n  \n  double Point::inSpan(double ang) const {\n    while((ang < 0.0) || (ang >= (2.0 * M_PI))) {\n      if(ang < 0.0) {\n\tang += 2.0 * M_PI; \n      }\n      else {\n\tang -= 2.0 * M_PI; \n      }\n    }\n    return ang;\n  }\n\n  __attribute__((optimize(\"-fno-fast-math\")))  \n  void Point::stepTo(double bearing, double distance, Point & next) const {\n\n    /* Initialized data */\n    const double eps = 5e-14;\n    const double a = 6378206.4; /* (meters) */\n    const double f = 1.0/298.25722210088; \n\n    /* System generated locals */\n    double d1;\n\n    bool debug = ((bearing < 180.00001) && (bearing > 179.99999)) || \n      (bearing < 0.00001) || (bearing > 359.99999);\n\n    /* Local variables */\n    double c, d, e, r, x, y, cf, sa, cu, sf, cy, cz, su, tu, \n      sy, c2a, s, faz, rbaz;\n\n    double glat1, glon1, glat2, glon2; \n\n    // *** SOLUTION OF THE GEODETIC DIRECT PROBLEM AFTER T.VINCENTY \n    // *** MODIFIED RAINSFORD'S METHOD WITH HELMERT'S ELLIPTICAL TERMS \n    // *** EFFECTIVE IN ANY AZIMUTH AND AT ANY DISTANCE SHORT OF ANTIPODAL \n    // \n    // *** A IS THE SEMI-MAJOR AXIS OF THE REFERENCE ELLIPSOID \n    // *** F IS THE FLATTENING OF THE REFERENCE ELLIPSOID \n    // *** LATITUDES AND LONGITUDES IN RADIANS POSITIVE NORTH AND EAST \n    // *** AZIMUTHS IN RADIANS CLOCKWISE FROM NORTH \n    // *** GEODESIC DISTANCE S ASSUMED IN UNITS OF SEMI-MAJOR AXIS A \n    // \n    // *** PROGRAMMED FOR CDC-6600 BY LCDR L.PFEIFER NGS ROCKVILLE MD 20FEB75 \n    //      \n    // *** MODIFIED FOR SYSTEM 360 BY JOHN G GERGEN NGS ROCKVILLE MD 750608\n    // \n    // *** HACKED TO HELL AND GONE BY F2C (July-17-96 version) and by \n    // *** Matt Reilly (KB1VC) to make it fit with the dem-gridlib routines.\n    // *** Feb 24, 1997. \n    // *** pounded on again by Matt Reilly (kb1vc) June 2019 for the GeoProfII\n    // *** code \n\n    // distance is in Km... */ \n    s = distance * 1000.0;\n    faz = bearing * M_PI / 180.0;\n\n    glat1 = this->lat * M_PI / 180.0;\n    glon1 = this->lon * M_PI / 180.0; \n    \n    r = 1.0 - f;\n    \n    tu = r * sin(glat1) / cos(glat1);\n    \n    sf = sin(faz);\n    cf = cos(faz);\n    rbaz = 0.0;\n    if (cf != 0.0) {\n      rbaz = atan2(tu, cf) * 2.0;\n    }\n\n    cu = 1.0 / sqrt(tu * tu + 1.0);\n    su = tu * cu;\n    sa = cu * sf;\n    c2a = -sa * sa + 1.0;\n    x = sqrt((1.0 / r / r - 1.0) * c2a + 1.0) + (float)\n      1.;\n    x = (x - 2.0) / x;\n    c = 1.0 - x;\n    c = (x * x / 4.0 + 1) / c;\n    d = (x * .375 * x - 1.0) * x;\n    tu = s / r / a / c;\n    y = tu;\n  L100:\n    sy = sin(y);\n    cy = cos(y);\n    cz = cos(rbaz + y);\n    e = cz * cz * 2.0 - 1.0;\n    c = y;\n    x = e * cy;\n    y = e + e - 1.0;\n    y = (((sy * sy * 4.0 - 3.0) * y * cz * d / 6.0 + x) * \n\t d / (float)4. - cz) * sy * d + tu;\n    if (fabs(y - c) > eps) {\n      goto L100;\n    }\n    rbaz = cu * cy * cf - su * sy;\n    c = r * sqrt(sa * sa + rbaz * rbaz);\n    d = su * cy + cu * sy * cf;\n    glat2 = atan2(d, c);\n    c = cu * cy - su * sy * cf;\n    x = atan2(sy * sf, c);\n    c = ((c2a * -3.0 + 4.0) * f + 4.0) * c2a * \n      f / 16.0;\n    d = ((e * cy * c + cz) * sy * c + y) * sa;\n    glon2 = glon1 + x - (1.0 - c) * d * f;\n\n    next.lat = glat2 * 180.0 / M_PI;\n    next.lon = glon2 * 180.0 / M_PI; \n    \n    if(next.lon < 180.0) next.lon = 360.0 + next.lon;\n    if(next.lon > 180.0) next.lon = next.lon - 360.0;\n    return; \n    \n  }\n\n  void Point::pt2Grid(std::string & grid) const {\n    std::string ret(6, ' ');\n\n    // First convert lat and lon to degrees and minutes.\n    // Remember the basis is lon 180 is Grenwich, lat 0 is the pole\n    // so we need to correct;\n    double llon = lon + 180;\n    double llat = lat + 90;\n    \n    int ilat = ((int) floor(llat));\n    int ilat_mins = ((int) floor(60.0 * (llat - floor(llat))));\n\n    int ilon = ((int) floor(llon));\n    int ilon_mins = ((int) floor(60.0 * (llon - floor(llon))));\n\n    // set lon positions\n    ret[0] = 'A' + ((int) (ilon / 20));\n    ilon = ilon % 20;\n    ret[2] = '0' + (ilon / 2);\n    ilon = ilon % 2;\n    ret[4] = 'a' + ((ilon * 60 + ilon_mins) / 5);\n    \n    ret[1] = 'A' + ((int) (ilat / 10));\n    ilat = ilat % 10;\n    ret[3] = '0' + ilat;\n    ret[5] = 'a' + ((ilat_mins * 2) / 5);\n\n    grid = ret; \n\n    return; \n  }\n\n\n  void Point::dms2Pt(double lat_d, double lat_m, double lat_s, char ns,\n\t\t      double lon_d, double lon_m, double lon_s, char ew) {\n    lat = lat_d + (lat_m / 60.0) + (lat_s / 3600.0);\n    if((ns == 'S') || (ns == 's')) lat = -1 * lat;\n    \n    lon = lon_d + (lon_m / 60.0) + (lon_s / 3600.0);    \n    if((ew == 'W') || (ew == 'w')) lon = -1 * lon; \n  }\n\n  double Point::gridDiff(char v, char s, double mul) const {\n    return mul * ((double) (v - s));\n  }\n  \n  void Point::grid2Pt(const std::string & grid) {\n    if(!checkGrid(grid)) {\n      throw std::runtime_error((boost::format(\"Bad grid specifier: [%s] is not in the proper form.\") % grid).str());\n    }\n\n    std::string lgrid = grid;\n\n    // upcase all of it... Is anybody embarrassed by the awkwardness here?\n    std::transform(lgrid.begin(), lgrid.end(), lgrid.begin(), ::toupper);\n\n\n    lon = gridDiff(lgrid[0], 'A', 20.0) + \n      gridDiff(lgrid[2], '0', 2.0);\n\n    if(lgrid.size() > 4) {\n      lon += (gridDiff(lgrid[4], 'A', 5.0) + 2.5) / 60.0; \n    }\n    \n    lon = lon - 180.0; \n\n    \n    lat = gridDiff(lgrid[1], 'A', 10.0) + \n      gridDiff(lgrid[3], '0', 1.0);\n\n    if(lgrid.size() > 5) {\n      lat += (gridDiff(lgrid[5], 'A', 2.5) + 1.25) / 60.0; \n    }\n\n    lat = lat - 90.0; // correct for south pole being 0deg lat.\n  }\n\n  \n  bool Point::checkGrid(const std::string & grid) const\n  {\n    //  verifies that the grid square is legitimate\n    //  return true for a good grid. \n\n    return regex_match(grid, grid_regexp); \n  }\n\n\n  double Point::atan2Pt(double y, double x) const {\n    double retval;\n    \n    retval = atan2(y, x);\n    if(retval < 0.0) retval = ((2.0 * M_PI) + retval);\n    \n    return retval;\n  }\n  \n}\n", "meta": {"hexsha": "4e5784576cec72b00b536ddf87014f7bc00712d5", "size": 13558, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "src/Point.cxx", "max_stars_repo_name": "kb1vc/GeoProfII", "max_stars_repo_head_hexsha": "d943d5777017af72b56ab8440d399e98b8d54e54", "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/Point.cxx", "max_issues_repo_name": "kb1vc/GeoProfII", "max_issues_repo_head_hexsha": "d943d5777017af72b56ab8440d399e98b8d54e54", "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/Point.cxx", "max_forks_repo_name": "kb1vc/GeoProfII", "max_forks_repo_head_hexsha": "d943d5777017af72b56ab8440d399e98b8d54e54", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.0251716247, "max_line_length": 123, "alphanum_fraction": 0.565938929, "num_tokens": 4735, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7461390043208003, "lm_q2_score": 0.45326184801538616, "lm_q1q2_score": 0.33819634397480614}}
{"text": "#include <iostream>\n#include <iomanip>\n#include <fstream>\n#include <list>\n#include <ctime>\n\n#include <boost/numeric/ublas/io.hpp>\n\n#include <flame/constants.h>\n#include <flame/base.h>\n#include <flame/moment.h>\n#include <flame/chg_stripper.h>\n#include <flame/state/vector.h>\n#include <flame/state/matrix.h>\n\n#include <flame/moment_sup.h>\n\n\ntypedef MomentState state_t;\ntypedef state_t::vector_t value_vec;\ntypedef state_t::matrix_t value_mat;\n\nextern int glps_debug;\n\n\nstatic\nvoid PrtVec(const MomentState::vector_t &a)\n{\n    for (size_t k = 0; k < a.size(); k++)\n        std::cout << std::scientific << std::setprecision(10)\n                      << std::setw(18) << a[k];\n    std::cout << \"\\n\";\n}\n\nstatic\nvoid PrtMat(const value_mat &M)\n{\n    for (size_t j = 0; j < M.size1(); j++) {\n        for (size_t k = 0; k < M.size2(); k++)\n            std::cout << std::scientific << std::setprecision(10)\n                      << std::setw(18) << M(j, k);\n        std::cout << \"\\n\";\n    }\n}\n\nvoid PrtState(const state_t& ST)\n{\n    MomentState::vector_t CenofChg, BeamRMS;\n\n    if (true)\n        for (size_t k = 0; k < ST.size(); k++) {\n            std::cout << \"\\nState: \"<<k<<\" s = \"<<std::fixed << std::setprecision(5) << ST.pos << \"\\n\"\n                      <<\"\\n Ref:  \"<<ST.ref\n                     <<\"\\n Real: \"<<ST.real[k]\n                       <<\"\\n moment0\\n\";\n            PrtVec(ST.moment0[k]);\n            std::cout << \" moment1\\n\";\n            PrtMat(ST.moment1[k]);\n        }\n\n    std::cout<<\"\\nCenter:        \"<< std::scientific << std::setprecision(10)\n             << std::setw(18)<<ST.moment0_env<<\"\\n\";\n    std::cout<<\"RMS Beam Size: \"<< std::scientific << std::setprecision(10)\n             << std::setw(18)<<ST.moment0_rms<<\"\\n\";\n    PrtMat(ST.moment1_env);\n}\n\nstatic\nvoid prt_initial_cond(Machine &sim,\n                      state_t &ST)\n{\n    sim.propagate(&ST, 0, 1);\n    PrtState(ST);\n}\n\nstatic\nvoid PrtOut(std::ofstream &outf1, std::ofstream &outf2, std::ofstream &outf3, const state_t& ST)\n{\n    outf1 << std::scientific << std::setprecision(14) << std::setw(22) << ST.pos;\n    for (size_t j = 0; j < ST.size(); j++)\n        for (int k = 0; k < 6; k++)\n            outf1 << std::scientific << std::setprecision(14) << std::setw(22) << ST.moment0[j][k];\n    for (int k = 0; k < 6; k++)\n        outf1 << std::scientific << std::setprecision(14) << std::setw(22) << ST.moment0_env[k];\n    outf1 << \"\\n\";\n\n    outf2 << std::scientific << std::setprecision(14) << std::setw(22) << ST.pos;\n    for (size_t j = 0; j < ST.size(); j++)\n        for (int k = 0; k < 6; k++)\n            outf2 << std::scientific << std::setprecision(14) << std::setw(22) << sqrt(ST.moment1[j](k, k));\n    for (int k = 0; k < 6; k++)\n        outf2 << std::scientific << std::setprecision(14) << std::setw(22) << sqrt(ST.moment1_env(k, k));\n    outf2 << \"\\n\";\n\n    outf3 << std::scientific << std::setprecision(14)\n          << std::setw(22) << ST.pos << std::setw(22) << ST.ref.phis << std::setw(22) << ST.ref.IonEk << \"\\n\";\n}\n\nstatic\nvoid propagate(const Config &conf)\n{\n    // Propagate element-by-element for each charge state.\n    Machine                  sim(conf);\n    std::auto_ptr<StateBase> state(sim.allocState());\n    state_t                  *StatePtr = dynamic_cast<state_t*>(state.get());\n    std::ofstream            outf1, outf2, outf3;\n\n    if(!StatePtr) throw std::runtime_error(\"Only sim_type MomentMatrix is supported\");\n\n    outf1.open(\"moment0.txt\",   std::ios::out);\n    outf2.open(\"moment1.txt\",   std::ios::out);\n    outf3.open(\"ref_orbit.txt\", std::ios::out);\n\n    prt_initial_cond(sim, *StatePtr);\n\n    clock_t tStamp[2];\n\n    tStamp[0] = clock();\n\n    prt_initial_cond(sim, *StatePtr);\n\n    Machine::iterator it = sim.begin()+1;\n    while (it != sim.end()) {\n        ElementVoid* elem = *it;\n\n        elem->advance(*state);\n        ++it;\n\n//        PrtOut(outf1, outf2, outf3, *StatePtr);\n\n//        PrtState(*StatePtr);\n    }\n\n    outf1.close();\n    outf2.close();\n    outf3.close();\n\n    tStamp[1] = clock();\n\n    PrtState(*StatePtr);\n\n    std::cout << std::fixed << std::setprecision(5)\n              << \"\\npropagate: \" << double(tStamp[1]-tStamp[0])/CLOCKS_PER_SEC << \" sec\" << \"\\n\";\n}\n\n\nint main(int argc, char *argv[])\n{\n    try {\n        std::auto_ptr<Config> conf;\n\n        if(argc>2)\n\n        glps_debug = 0; // 0 or 1.\n\n        try {\n            GLPSParser P;\n            conf.reset(P.parse_file(argc>1 ? argv[1] : NULL));\n            fprintf(stderr, \"Parsing succeeds\\n\");\n        } catch(std::exception& e) {\n            fprintf(stderr, \"Parse error: %s\\n\", e.what());\n            return 1;\n        }\n\n//        std::cout<<\"# Reduced lattice\\n\";\n//        GLPSPrint(std::cout, *conf);\n//        std::cout<<\"\\n\";\n\n        registerMoment();\n\n        propagate(*conf);\n\n        return 0;\n    } catch(std::exception& e) {\n        std::cerr << \"Main exception: \" << e.what() << \"\\n\";\n        Machine::registeryCleanup();\n        return 1;\n    }\n}\n", "meta": {"hexsha": "2c66f50094903d83f12796a9a5907f0047f5bce3", "size": 4972, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/test_jb_2.cpp", "max_stars_repo_name": "kryv/FLAME", "max_stars_repo_head_hexsha": "b85ae4fb465c572cee348ee023f73ac4c5864dcd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2016-04-04T20:14:25.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-17T22:37:49.000Z", "max_issues_repo_path": "src/test_jb_2.cpp", "max_issues_repo_name": "kryv/FLAME", "max_issues_repo_head_hexsha": "b85ae4fb465c572cee348ee023f73ac4c5864dcd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 24.0, "max_issues_repo_issues_event_min_datetime": "2016-04-07T19:23:31.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-21T14:31:14.000Z", "max_forks_repo_path": "src/test_jb_2.cpp", "max_forks_repo_name": "kryv/FLAME", "max_forks_repo_head_hexsha": "b85ae4fb465c572cee348ee023f73ac4c5864dcd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 13.0, "max_forks_repo_forks_event_min_datetime": "2016-04-13T13:26:36.000Z", "max_forks_repo_forks_event_max_datetime": "2019-12-20T01:55:24.000Z", "avg_line_length": 27.6222222222, "max_line_length": 110, "alphanum_fraction": 0.5364038616, "num_tokens": 1460, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7154240079185319, "lm_q2_score": 0.4726834766204328, "lm_q1q2_score": 0.3381691073206557}}
{"text": "//------------------------------------------------------------------------------\n// Construct a flaw distribution for a set of nodes according to a Weibull \n// (power-law) distribution.\n//------------------------------------------------------------------------------\n#include <set>\n#include <algorithm>\n#include <limits>\n#include \"boost/unordered_map.hpp\"\n\n#include \"weibullFlawDistribution.hh\"\n#include \"Utilities/globalNodeIDs.hh\"\n#include \"Utilities/mortonOrderIndices.hh\"\n#include \"Utilities/nodeOrdering.hh\"\n#include \"NodeList/FluidNodeList.hh\"\n#include \"Field/Field.hh\"\n#include \"Field/FieldList.hh\"\n#include \"DataBase/DataBase.hh\"\n#include \"Distributed/Communicator.hh\"\n#include \"Utilities/allReduce.hh\"\n\n#include <boost/random.hpp>\n#include <boost/random/uniform_01.hpp>\nusing boost::unordered_map;\n\nusing std::vector;\nusing std::string;\nusing std::pair;\nusing std::make_pair;\nusing std::cout;\nusing std::cerr;\nusing std::endl;\nusing std::min;\nusing std::max;\nusing std::abs;\n\nnamespace Spheral {\n\n//------------------------------------------------------------------------------\n// This version uses the Benz-Asphaug algorithm, stepping up deterministically\n// in flaw energy based on a minimum chosen from the simulation volume.\n//------------------------------------------------------------------------------\ntemplate<typename Dimension>\nField<Dimension, vector<double> >\nweibullFlawDistributionBenzAsphaug(double volume,\n                                   const double volumeStretchFactor,\n                                   const unsigned seed,\n                                   const double kWeibull,\n                                   const double mWeibull,\n                                   const FluidNodeList<Dimension>& nodeList,\n                                   const int minFlawsPerNode,\n                                   const int minTotalFlaws,\n                                   const Field<Dimension, int>& mask) {\n\n  // Pre-conditions.\n  REQUIRE(volume >= 0.0);\n  REQUIRE(volumeStretchFactor >= 1.0);\n  REQUIRE(kWeibull >= 0.0);\n  REQUIRE(mWeibull > 0.0);\n  REQUIRE(minFlawsPerNode > 0);\n  REQUIRE(minTotalFlaws > 0);\n  REQUIRE(mask.nodeListPtr() == &nodeList);\n\n  typedef typename Dimension::Scalar Scalar;\n  typedef typename Dimension::Vector Vector;\n  typedef typename Dimension::SymTensor SymTensor;\n\n  // Prepare the result.\n  Field<Dimension, vector<double> > flaws(\"Weibull flaw distribution\",\n                                          nodeList);\n\n  // Construct unique global IDs for all nodes in the NodeList.\n  const int n = max(1, numGlobalNodes(nodeList));\n  const Field<Dimension, int> globalIDs = globalNodeIDs(nodeList);\n\n  // Prepare a table to faciliate looking local IDs from global.\n  unordered_map<unsigned, unsigned> global2local;\n  for (unsigned i = 0; i != nodeList.numInternalNodes(); ++i) global2local[globalIDs(i)] = i;\n  CHECK(global2local.size() == nodeList.numInternalNodes());\n\n  // Prepare an int per *each* node, so that each process can keep track of how many\n  // flaws are seeded globally (avoiding communication at the expense of memory).\n  vector<int> numFlawsPerNode((size_t) n, 0);\n\n  // Identify the rank and number of domains.\n  const int procID = Process::getRank();\n  const int numProcs = Process::getTotalNumberOfProcesses();\n\n  // Only proceed if there are nodes to initialize!\n  if (n > 0) {\n\n    // If the user did not speicify a volume, we compute it from the information\n    // in the NodeList.\n    if (volume == 0.0) {\n      const Field<Dimension, Scalar>& mass = nodeList.mass();\n      const Field<Dimension, Scalar>& rho = nodeList.massDensity();\n      for (int i = 0; i != nodeList.numInternalNodes(); ++i) {\n        CHECK(rho(i) > 0.0);\n        volume += mass(i)/rho(i);\n      }\n      volume = allReduce(volume, MPI_SUM, Communicator::communicator());\n    }\n    volume = std::max(volume, 1e-100);\n    CHECK(volume > 0.0);\n\n    // Compute the minimum (starting) failure strain.\n    const double mInv = 1.0/(mWeibull + 1.0e-50);\n    const double epsMin = pow(kWeibull*volume*volumeStretchFactor, -mInv);\n    CHECK(epsMin > 0.0);\n\n    // Construct a random number generator.\n    typedef boost::mt19937 base_generator_type;\n    base_generator_type basegen(seed);\n    boost::uniform_01<base_generator_type> generator(basegen);\n\n    // Loop and initialize flaws until:\n    // a) every node has the minimum number of flaws per node, and\n    // b) we meet the minimum number of total flaws.\n    int numCompletedNodes = 0;\n    int ienergy = 1;\n    while ((numCompletedNodes < n) || (ienergy <= minTotalFlaws)) {\n\n      // Randomly select a global node.\n      const int iglobal = int(generator() * n);\n      CHECK(iglobal >= 0 && iglobal < n);\n\n      // Increment the number of flaws for this node, and check if this\n      // completes this node.\n      ++numFlawsPerNode[iglobal];\n      if (numFlawsPerNode[iglobal] == minFlawsPerNode) ++numCompletedNodes;\n\n      // Is this node one of ours?\n      const typename unordered_map<unsigned, unsigned>::const_iterator itr = global2local.find(iglobal);\n      if (itr != global2local.end()) {\n\n        const unsigned i = itr->second;\n        CHECK(i < nodeList.numInternalNodes());\n        if (mask(i) == 1) {\n\n          // The activation energy.\n          const double epsij = epsMin * pow(ienergy*volumeStretchFactor, mInv);\n\n          // Add a flaw with this activation energy to this node.\n          flaws(i).push_back(epsij);\n        }\n      }\n\n      // Increment the energy multiplier.\n      ++ienergy;\n    }\n\n    // Sort the flaws on each node by energy.\n    unsigned minNumFlaws = INT_MAX;\n    unsigned maxNumFlaws = 0;\n    unsigned totalNumFlaws = 0;\n    double epsMax = 0.0;\n    double sumFlaws = 0.0;\n    for (int i = 0; i != nodeList.numInternalNodes(); ++i) {\n      minNumFlaws = min(minNumFlaws, unsigned(flaws(i).size()));\n      maxNumFlaws = max(maxNumFlaws, unsigned(flaws(i).size()));\n      totalNumFlaws += flaws(i).size();\n      if (mask(i) == 1) {\n        sort(flaws(i).begin(), flaws(i).end());\n        epsMax = max(epsMax, flaws(i).back());\n        for (int j = 0; j != flaws(i).size(); ++j) sumFlaws += flaws(i)[j];\n      }\n    }\n\n    // Prepare some diagnostic output.\n    const auto nused = mask.sumElements();\n    minNumFlaws = allReduce(minNumFlaws, MPI_MIN, Communicator::communicator());\n    maxNumFlaws = allReduce(maxNumFlaws, MPI_MAX, Communicator::communicator());\n    totalNumFlaws = allReduce(totalNumFlaws, MPI_SUM, Communicator::communicator());\n    epsMax = allReduce(epsMax, MPI_MAX, Communicator::communicator());\n    sumFlaws = allReduce(sumFlaws, MPI_SUM, Communicator::communicator());\n    if (procID == 0) {\n      cerr << \"weibullFlawDistributionBenzAsphaug: Min num flaws per node: \" << minNumFlaws << endl\n           << \"                                    Max num flaws per node: \" << maxNumFlaws << endl\n           << \"                                    Total num flaws       : \" << totalNumFlaws << endl\n           << \"                                    Avg flaws per node    : \" << totalNumFlaws / nused << endl\n           << \"                                    Min flaw strain       : \" << epsMin << endl\n           << \"                                    Max flaw strain       : \" << epsMax << endl\n           << \"                                    Avg node failure      : \" << sumFlaws / nused << endl;\n    }\n  }\n\n  // That's it.\n  BEGIN_CONTRACT_SCOPE\n  {\n    for (int i = 0; i != nodeList.numInternalNodes(); ++i) {\n      if (mask(i) == 1) {\n        ENSURE(flaws(i).size() >= minFlawsPerNode);\n        for (vector<double>::const_iterator itr = flaws(i).begin() + 1;\n             itr != flaws(i).end();\n             ++itr) ENSURE(*itr >= *(itr - 1));\n      }\n    }\n  }\n  END_CONTRACT_SCOPE\n\n  return flaws;\n}\n\n//------------------------------------------------------------------------------\n// This version uses my own algorithm, stochastically seeding flaws in the range\n// [0, epsmax] where epsmax is chosen per node based on the nodal volume.\n//------------------------------------------------------------------------------\ntemplate<typename Dimension>\nField<Dimension, vector<double> >\nweibullFlawDistributionOwen(const unsigned seed,\n                            const double kWeibull,\n                            const double mWeibull,\n                            const FluidNodeList<Dimension>& nodeList,\n                            const int minFlawsPerNode,\n                            const double volumeMultiplier,\n                            const Field<Dimension, int>& mask) {\n\n  // Pre-conditions.\n  REQUIRE(kWeibull >= 0.0);\n  REQUIRE(mWeibull > 0.0);\n  REQUIRE(minFlawsPerNode > 0);\n  REQUIRE(mask.nodeListPtr() == &nodeList);\n\n  typedef typename Dimension::Scalar Scalar;\n  typedef typename Dimension::Vector Vector;\n  typedef typename Dimension::SymTensor SymTensor;\n  typedef KeyTraits::Key Key;\n\n  // Prepare the result.\n  Field<Dimension, vector<double> > flaws(\"Weibull flaw distribution\",\n                                          nodeList);\n\n  // Assign a unique ordering to the nodes so we can step through them\n  // in a domain independent manner.\n  DataBase<Dimension> db;\n  db.appendNodeList(const_cast<FluidNodeList<Dimension>&>(nodeList));\n  FieldList<Dimension, Key> keyList = mortonOrderIndices(db);\n  FieldList<Dimension, int> orderingList = nodeOrdering(keyList);\n  CHECK(orderingList.numFields() == 1);\n  Field<Dimension, int>& ordering = *orderingList[0];\n  const int n = std::max(0, ordering.max());\n\n  // Is there anything to do?\n  if (n > 0) {\n\n    // Reverse lookup in the ordering.\n    unordered_map<unsigned, unsigned> order2local;\n    for (unsigned i = 0; i != nodeList.numInternalNodes(); ++i) order2local[ordering[i]] = i;\n\n    // Identify the rank and number of domains.\n    const int procID = Process::getRank();\n    const int numProcs = Process::getTotalNumberOfProcesses();\n\n    // State for this NodeList.\n    const Field<Dimension, Scalar>& mass = nodeList.mass();\n    const Field<Dimension, Scalar>& rho = nodeList.massDensity();\n\n    // Construct a random number generator.\n    typedef boost::mt19937 base_generator_type;\n    base_generator_type basegen(seed);\n    boost::uniform_01<base_generator_type> generator(basegen);\n\n    // Find the minimum and maximum node volumes.\n    double Vmin = std::numeric_limits<double>::max(), \n      Vmax = std::numeric_limits<double>::min();\n    for (unsigned i = 0; i != nodeList.numInternalNodes(); ++i) {\n      const double Vi = mass(i)/rho(i);\n      Vmin = min(Vmin, Vi);\n      Vmax = max(Vmax, Vi);\n    }\n    Vmin = allReduce(Vmin*volumeMultiplier, MPI_MIN, Communicator::communicator());\n    Vmax = allReduce(Vmax*volumeMultiplier, MPI_MAX, Communicator::communicator());\n    CHECK(Vmin > 0.0);\n    CHECK(Vmax >= Vmin);\n\n    // Compute the maximum strain we expect for the minimum volume.\n    const double epsMax2m = minFlawsPerNode/(kWeibull*Vmin);  // epsmax ** m\n\n    // Based on this compute the maximum number of flaws any node will have.  We'll use this to\n    // spin the random number generator without extra communiction.\n    const int maxFlawsPerNode = std::max(1, int(kWeibull*Vmax*epsMax2m + 0.5));\n\n    // Iterate over the nodes.\n    const double mInv = 1.0/mWeibull;\n    for (int iorder = 0; iorder != n + 1; ++iorder) {\n\n      // Is this one of our nodes?\n      typename unordered_map<unsigned, unsigned>::const_iterator itr = order2local.find(iorder);\n      if (itr != order2local.end()) {\n\n        // We have the node!\n        const unsigned i = itr->second;\n        CHECK(i < nodeList.numInternalNodes());\n        CHECK(rho(i) > 0.0);\n        const double Vi = mass(i)/rho(i) * volumeMultiplier;\n        CHECK(Vi > 0.0);\n        const int numFlawsi = std::max(1, std::min(maxFlawsPerNode, int(kWeibull*Vi*epsMax2m + 0.5)));\n        const double Ai = numFlawsi/(kWeibull*Vi);\n        CHECK(Ai > 0.0);\n\n        // Are we actually doing this node?\n        if (mask(i) == 1) {\n\n          // Seed flaws on the node.\n          for (int j = 0; j != numFlawsi; ++j) {\n            flaws(i).push_back(pow(Ai * generator(), mInv));\n          }\n\n          // Spin the random number generator to keep in sync with other processors.\n          for (int j = numFlawsi; j != maxFlawsPerNode; ++j) double tmp = generator();\n\n        } else{\n\n          // Spin the random number generator to keep in sync with other processors.\n          for (int j = 0; j != maxFlawsPerNode; ++j) double tmp = generator();\n\n        }\n\n      } else {\n\n        // Other domains just cycle the random number generator so that\n        // we can be domain decomposition independent.\n        for (int j = 0; j != maxFlawsPerNode; ++j) double tmp = generator();\n\n      }\n    }\n\n    // Sort the flaws on each node by energy.\n    unsigned minNumFlaws = std::numeric_limits<int>::max();\n    unsigned maxNumFlaws = 0;\n    unsigned totalNumFlaws = 0;\n    double epsMin = std::numeric_limits<double>::max();\n    double epsMax = std::numeric_limits<double>::min();\n    double sumFlaws = 0.0;\n    for (int i = 0; i != nodeList.numInternalNodes(); ++i) {\n      minNumFlaws = min(minNumFlaws, unsigned(flaws(i).size()));\n      maxNumFlaws = max(maxNumFlaws, unsigned(flaws(i).size()));\n      totalNumFlaws += flaws(i).size();\n      if (mask(i) == 1) {\n        sort(flaws(i).begin(), flaws(i).end());\n        epsMin = min(epsMin, flaws(i).front());\n        epsMax = max(epsMax, flaws(i).back());\n        for (int j = 0; j != flaws(i).size(); ++j) sumFlaws += flaws(i)[j];\n      }\n    }\n\n    // Prepare some diagnostic output.\n    const auto nused = mask.sumElements();\n    if (n > 0) {\n      minNumFlaws = allReduce(minNumFlaws, MPI_MIN, Communicator::communicator());\n      maxNumFlaws = allReduce(maxNumFlaws, MPI_MAX, Communicator::communicator());\n      totalNumFlaws = allReduce(totalNumFlaws, MPI_SUM, Communicator::communicator());\n      epsMin = allReduce(epsMin, MPI_MIN, Communicator::communicator());\n      epsMax = allReduce(epsMax, MPI_MAX, Communicator::communicator());\n      sumFlaws = allReduce(sumFlaws, MPI_SUM, Communicator::communicator());\n    }\n    if (procID == 0) {\n      cerr << \"weibullFlawDistributionOwen: Min num flaws per node: \" << minNumFlaws << endl\n           << \"                             Max num flaws per node: \" << maxNumFlaws << endl\n           << \"                             Total num flaws       : \" << totalNumFlaws << endl\n           << \"                             Avg flaws per node    : \" << totalNumFlaws / nused << endl\n           << \"                             Min flaw strain       : \" << epsMin << endl\n           << \"                             Max flaw strain       : \" << epsMax << endl\n           << \"                             Avg node failure      : \" << sumFlaws / nused << endl;\n    }\n\n    // That's it.\n    BEGIN_CONTRACT_SCOPE\n    {\n      for (int i = 0; i != nodeList.numInternalNodes(); ++i) {\n        if (mask(i) == 1) {\n          for (vector<double>::const_iterator itr = flaws(i).begin() + 1;\n               itr != flaws(i).end();\n               ++itr) ENSURE(*itr >= *(itr - 1));\n        }\n      }\n    }\n    END_CONTRACT_SCOPE\n  }\n\n  return flaws;\n}\n\n}\n\n", "meta": {"hexsha": "4e55e630b70b52e8787af8c6fc36350351aa1a25", "size": 15171, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/Damage/weibullFlawDistribution.cc", "max_stars_repo_name": "markguozhiming/spheral", "max_stars_repo_head_hexsha": "bbb982102e61edb8a1d00cf780bfa571835e1b61", "max_stars_repo_licenses": ["BSD-Source-Code", "BSD-3-Clause-LBNL", "FSFAP"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-10-21T01:56:55.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-21T01:56:55.000Z", "max_issues_repo_path": "src/Damage/weibullFlawDistribution.cc", "max_issues_repo_name": "markguozhiming/spheral", "max_issues_repo_head_hexsha": "bbb982102e61edb8a1d00cf780bfa571835e1b61", "max_issues_repo_licenses": ["BSD-Source-Code", "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/Damage/weibullFlawDistribution.cc", "max_forks_repo_name": "markguozhiming/spheral", "max_forks_repo_head_hexsha": "bbb982102e61edb8a1d00cf780bfa571835e1b61", "max_forks_repo_licenses": ["BSD-Source-Code", "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": 39.4051948052, "max_line_length": 109, "alphanum_fraction": 0.5874365566, "num_tokens": 3712, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7154239957834733, "lm_q2_score": 0.47268347662043286, "lm_q1q2_score": 0.33816910158461405}}
{"text": "#define PY_ARRAY_UNIQUE_SYMBOL superimg_PyArray_API\n#define NO_IMPORT_ARRAY\n\n#include <string>\n#include <cmath>\n\n#include <boost/python/suite/indexing/vector_indexing_suite.hpp>\n\n\n#include <boost/array.hpp>\n\n#include <boost/accumulators/accumulators.hpp>\n\n#include <boost/accumulators/statistics/stats.hpp>\n#include <boost/accumulators/statistics/median.hpp>\n#include <boost/accumulators/statistics/mean.hpp>\n#include <boost/accumulators/statistics/extended_p_square_quantile.hpp>\n#include <boost/accumulators/statistics/tail_quantile.hpp>\n\n#include <vigra/numpy_array.hxx>\n#include <vigra/numpy_array_converters.hxx>\n\n#include \"seglib/cgp2d/cgp2d.hxx\"\n#include \"seglib/cgp2d/cgp2d_python.hxx\"\n\nnamespace python = boost::python;\n\nnamespace cgp2d\n{\n\n\ntemplate <class RAIter, class Compare>\nvoid argsort(RAIter iterBegin, RAIter iterEnd, Compare comp, \n    std::vector<size_t>& indexes) {\n\n    std::vector< std::pair<size_t,RAIter> > pv ;\n    pv.reserve(iterEnd - iterBegin) ;\n\n    RAIter iter ;\n    size_t k ;\n    for (iter = iterBegin, k = 0 ; iter != iterEnd ; iter++, k++) {\n        pv.push_back( std::pair<int,RAIter>(k,iter) ) ;\n    }\n\n    std::sort(pv.begin(), pv.end(), \n        [&comp](const std::pair<size_t,RAIter>& a, const std::pair<size_t,RAIter>& b) -> bool \n        { return comp(*a.second, *b.second) ; }) ;\n\n    indexes.resize(pv.size()) ;\n    std::transform(pv.begin(), pv.end(), indexes.begin(), \n        [](const std::pair<size_t,RAIter>& a) -> size_t { return a.first ; }) ;\n}\n\n//centerCoordinate\ntemplate<class BB>\nfloat bbSize(const BB & bb){\n    float sx = std::abs(bb.first[0]-bb.second[0]+1);\n    float sy = std::abs(bb.first[0]-bb.second[0]+1);\n    sx = (sx+1)/2.0;\n    sy = (sy+1)/2.0;\n\n    return std::sqrt(sx*sx + sy*sy);\n}\n\n\n\n\n\n\n\n\n\ntemplate<class CGP>\nvigra::NumpyAnyArray  countMultiEdges(\n    const CGP & cgp\n){\n\n    typedef vigra::NumpyArray<1,float>  ResultArray;\n    typedef typename ResultArray::difference_type ShapeType;\n    typedef typename CGP::Cells1 Cells1;\n    typedef typename CGP::Cell1  Cell1;\n    typedef typename CGP::Cells2 Cells2;\n    typedef typename CGP::Cell2  Cell2;\n\n\n    typedef typename CGP::CellAdjacencyGraphVectorType CellAdjGraph;\n\n\n\n    const size_t numBoundaries = cgp.numCells(1);\n    const size_t numRegions    = cgp.numCells(2);\n    const Cells1 & cells1=cgp.geometry1();\n    const Cells2 & cells2=cgp.geometry2();\n    // initialize result array\n    ResultArray resultArray = ResultArray(ShapeType(numBoundaries));\n\n\n    // Adj Graph \n    CellAdjGraph cell1AdjGraph;\n    CellAdjGraph cell2AdjGraph;\n\n    // fill adjacency graph\n    cgp.cellAdjacencyGraphVector(1,cell1AdjGraph);\n    cgp.cellAdjacencyGraphVector(2,cell2AdjGraph);\n\n    typedef unsigned long long  KeyType;\n    typedef std::map<KeyType, size_t> MapType;\n    typedef typename MapType::const_iterator MapIter;\n\n\n    MapType counter;\n\n    for(size_t bi=0;bi<numBoundaries;++bi){\n        const Cell1 & cell1  = cells1[bi];\n        const KeyType ri0     = static_cast<KeyType>(cell1.bounds()[0]-1);\n        const KeyType ri1     = static_cast<KeyType>(cell1.bounds()[1]-1);\n        const KeyType key = std::min(ri0,ri1) + std::max(ri0,ri1)*numRegions;\n        counter[key]=0;\n    }\n    for(size_t bi=0;bi<numBoundaries;++bi){\n        const Cell1 & cell1  = cells1[bi];\n        const KeyType ri0     = static_cast<KeyType>(cell1.bounds()[0]-1);\n        const KeyType ri1     = static_cast<KeyType>(cell1.bounds()[1]-1);\n        const KeyType key = std::min(ri0,ri1) + std::max(ri0,ri1)*numRegions;\n        counter[key]=counter[key]+1;\n    }\n    for(size_t bi=0;bi<numBoundaries;++bi){\n        const Cell1 & cell1  = cells1[bi];\n        const KeyType ri0     = static_cast<KeyType>(cell1.bounds()[0]-1);\n        const KeyType ri1     = static_cast<KeyType>(cell1.bounds()[1]-1);\n        const KeyType key = std::min(ri0,ri1) + std::max(ri0,ri1)*numRegions;\n        resultArray(bi)=static_cast<float>(counter[key]);\n    }\n    return resultArray;\n}\n\n\n\ntemplate<class CGP>\nvigra::NumpyAnyArray  cell1TopoFeatures(\n    const CGP & cgp\n){\n\n    typedef vigra::NumpyArray<2,float>  ResultArray;\n    typedef typename ResultArray::difference_type ShapeType;\n    typedef typename CGP::Cells1 Cells1;\n    typedef typename CGP::Cell1  Cell1;\n    typedef typename CGP::Cells2 Cells2;\n    typedef typename CGP::Cell2  Cell2;\n\n\n    typedef typename CGP::CellAdjacencyGraphVectorType CellAdjGraph;\n\n\n\n    const size_t numBoundaries = cgp.numCells(1);\n    const Cells1 & cells1=cgp.geometry1();\n    const Cells2 & cells2=cgp.geometry2();\n    // initialize result array\n    ResultArray resultArray = ResultArray(ShapeType(numBoundaries,5));\n\n\n    // Adj Graph \n    CellAdjGraph cell1AdjGraph;\n    CellAdjGraph cell2AdjGraph;\n\n    // fill adjacency graph\n    cgp.cellAdjacencyGraphVector(1,cell1AdjGraph);\n    cgp.cellAdjacencyGraphVector(2,cell2AdjGraph);\n\n    for(size_t bi=0;bi<numBoundaries;++bi){\n\n        const Cell1 & cell1  = cells1[bi];\n\n        {   // from boundary itself\n            resultArray(bi,0) = cell1AdjGraph[bi].size();\n        }\n\n        {  // from the 2 adj regions\n\n            const size_t ri0     = cell1.bounds()[0]-1;\n            const size_t ri1     = cell1.bounds()[1]-1;\n            const Cell2 & cell20 = cells2[ri0];\n            const Cell2 & cell21 = cells2[ri1];\n            const float nAdj0    = cell2AdjGraph[ri0].size();\n            const float nAdj1    = cell2AdjGraph[ri1].size();\n\n            resultArray(bi,1) =  (nAdj0+nAdj1)/2.0;\n            resultArray(bi,2) =  std::abs(nAdj0-nAdj1)/2.0;\n            resultArray(bi,3) =  std::min(nAdj0,nAdj1);\n            resultArray(bi,4) =  std::max(nAdj0,nAdj1);\n        }\n    }\n    return resultArray;\n}\n\n\ntemplate<class CGP>\nvigra::NumpyAnyArray  cell1GeoFeatures(\n    const CGP & cgp\n){\n\n    typedef vigra::NumpyArray<2,float>  ResultArray;\n    typedef typename ResultArray::difference_type ShapeType;\n    typedef typename CGP::Cells1 Cells1;\n    typedef typename CGP::Cell1  Cell1;\n    typedef typename CGP::Cells2 Cells2;\n    typedef typename CGP::Cell2  Cell2;\n    typedef typename Cell1::FloatPointType FloatPointType;\n    typedef typename Cell1::PointType PointType;\n    typedef std::pair<PointType,PointType> BouningBoxType;\n\n    const size_t numBoundaries = cgp.numCells(1);\n    const Cells1 & cells1=cgp.geometry1();\n    const Cells2 & cells2=cgp.geometry2();\n    // initialize result array\n    ResultArray resultArray = ResultArray(ShapeType(numBoundaries,13));\n    std::fill(resultArray.begin(),resultArray.end(),0.0);\n\n\n\n    for(size_t bi=0;bi<numBoundaries;++bi){\n\n        const Cell1 & cell1  = cells1[bi];\n\n        {   // from boundary itself\n\n            const FloatPointType center = cell1.centerCoordinate();\n            BouningBoxType bBox   = cell1.boundingBox();\n            bBox.second[0]+=1;\n            bBox.second[1]+=1;\n\n            const float lineSize        = cell1.size();\n            const float bbDiagonal      = vigra::norm(bBox.first -bBox.second );\n            const float relBBoxSize     = bbDiagonal/lineSize;\n            const float startEndDist    = vigra::norm(cell1[0]-cell1[lineSize-1]);\n            const float relStartEndSize = startEndDist/lineSize;\n\n            \n            resultArray(bi,0)=lineSize;\n            resultArray(bi,1)=bbDiagonal;\n            resultArray(bi,2)=relBBoxSize;\n            resultArray(bi,3)=startEndDist;\n            resultArray(bi,4)=relStartEndSize;\n        }\n\n        {  // from the 2 adj regions\n\n            const size_t ri0     = cell1.bounds()[0]-1;\n            const size_t ri1     = cell1.bounds()[1]-1;\n            const Cell2 & cell20 = cells2[ri0];\n            const Cell2 & cell21 = cells2[ri1];\n            BouningBoxType bBox0 = cell20.boundingBox();\n            BouningBoxType bBox1 = cell21.boundingBox();\n    \n            const float bbSize0 = bbSize(bBox0);\n            const float bbSize1 = bbSize(bBox1);\n\n            const float size0 = cell20.size();\n            const float size1 = cell21.size();\n\n            const float relSize0 = bbSize0/size0;\n            const float relSize1 = bbSize1/size1;\n\n\n            resultArray(bi,5) = (size0 + size1)/2.0;\n            resultArray(bi,6) = std::abs(size0 - size1);\n            resultArray(bi,7) = std::min(size0 , size1);\n            resultArray(bi,8) = std::max(size0 , size1);\n\n            resultArray(bi,9) = (relSize0 +relSize1)/2.0;\n            resultArray(bi,10) = std::abs(relSize0 -relSize1);\n            resultArray(bi,11) = std::min(relSize0 , relSize1);\n            resultArray(bi,12) = std::max(relSize0 , relSize1);\n        }\n\n\n    \n    }\n    return resultArray;\n}\n\n\n\n\n\ntemplate<class CGP>\nvigra::NumpyAnyArray  relativeCenterDist(\n    const CGP & cgp\n){\n\n    typedef vigra::NumpyArray<1,float>  ResultArray;\n    typedef typename ResultArray::difference_type ShapeType;\n    typedef typename CGP::Cells1 Cells1;\n    typedef typename CGP::Cell1 Cell1;\n    typedef typename Cell1::FloatPointType FloatPointType;\n    const size_t numBoundaries = cgp.numCells(1);\n    const Cells1 & cells1=cgp.geometry1();\n\n    // initialize result array\n    ResultArray resultArray = ResultArray(ShapeType(numBoundaries));\n    std::fill(resultArray.begin(),resultArray.end(),0.0);\n\n\n    FloatPointType imageCenter(0.5,0.5);\n    const float maxDist = vigra::norm(imageCenter - FloatPointType(1.0,1.0));\n\n\n    for(size_t bi=0;bi<numBoundaries;++bi){\n        const Cell1 & cell1   = cells1[bi];\n        FloatPointType centerCoordinate = cell1.centerCoordinate();\n        centerCoordinate[0]/=cgp.shape(0);\n        centerCoordinate[1]/=cgp.shape(1);\n\n        const float distance = vigra::norm(imageCenter -centerCoordinate );\n        resultArray(bi)=distance;\n        \n    }\n    return resultArray;\n}\n\n\ntemplate<class CGP>\nvigra::NumpyAnyArray  boarderTouch(\n    const CGP & cgp\n){\n\n    typedef vigra::NumpyArray<1,float>  ResultArray;\n    typedef typename ResultArray::difference_type ShapeType;\n    typedef typename CGP::Cells1 Cells1;\n    typedef typename CGP::Cell1 Cell1;\n\n    const size_t numBoundaries = cgp.numCells(1);\n    const Cells1 & cells1=cgp.geometry1();\n\n    // initialize result array\n    ResultArray resultArray = ResultArray(ShapeType(numBoundaries));\n    std::fill(resultArray.begin(),resultArray.end(),0.0);\n\n\n    const size_t maxX =cgp.shape(0)-1;\n    const size_t maxY =cgp.shape(1)-1;\n\n    for(size_t bi=0;bi<numBoundaries;++bi){\n        \n        float numBoarderTouch=0.0;\n\n        const Cell1 & cell1   = cells1[bi];\n        const size_t numCoord = cell1.size();\n\n\n        const size_t cxStart = cell1[0][0];\n        const size_t cyStart = cell1[0][1];\n\n        const size_t cxEnd = cell1[numCoord-1][0];\n        const size_t cyEnd = cell1[numCoord-1][1];\n\n        if ( \n            ( cxStart == 0  || cxStart == maxX) || \n            ( cyStart == 0  || cyStart == maxY) \n        ){\n            numBoarderTouch+=1;\n        }\n\n        if ( \n            ( cxEnd == 0  || cxEnd == maxX) || \n            ( cyEnd == 0  || cyEnd == maxY) \n        ){\n            numBoarderTouch+=1;\n        }\n        resultArray(bi)=numBoarderTouch;\n  \n    }\n    return resultArray;\n}\n\n\n\n\ntemplate<class CGP>\nvigra::NumpyAnyArray  cell1GraphStealing(\n    const CGP & cgp,\n    vigra::NumpyArray<1,float> cell1Features,\n    const float frac,\n    const float pl,\n    const float ph\n){\n\n    typedef vigra::NumpyArray<1,float>  ResultArray;\n    typedef typename ResultArray::difference_type ShapeType;\n    typedef typename CGP::Cells0 Cells0;\n    typedef typename CGP::Cells1 Cells1;\n    typedef typename CGP::Cell0 Cell0;\n    typedef typename CGP::Cell1 Cell1;\n    typedef typename CGP::CellAdjacencyGraphVectorType CellAdjGraph;\n\n    const size_t cellType = 1;\n    const size_t numCells = cgp.numCells(cellType);\n\n    using namespace boost::accumulators;\n    typedef accumulator_set<double, stats<\n        tag::min,\n        tag::mean,\n        tag::median(with_p_square_quantile),\n        tag::extended_p_square_quantile\n    > > AccSet;\n\n\n    typedef accumulator_set<double, stats<tag::tail_quantile<right> > > accumulator_t_right;\n    typedef accumulator_set<double, stats<tag::tail_quantile<left> > >  accumulator_t_left;\n\n\n\n     // initialize result array\n    ResultArray resultArray = ResultArray(ShapeType(numCells));\n\n    std::copy(cell1Features.begin(),cell1Features.end(),resultArray.begin());\n\n    // Adj Graph \n    CellAdjGraph cellAdjGraph;\n    // fill adjacency graph\n    cgp.cellAdjacencyGraphVector(cellType,cellAdjGraph);\n\n    boost::array<double,2> probs = { pl,ph};\n\n    for(size_t ci=0;ci<numCells;++ci){\n\n\n        accumulator_t_right accR( right_tail_cache_size = 1000 );\n        accumulator_t_left  accL( left_tail_cache_size = 1000 );\n        AccSet accSet(extended_p_square_probabilities = probs);\n\n        const double ownVal = static_cast<double>(cell1Features(ci));\n        accSet(ownVal);\n\n        const size_t nAdj=cellAdjGraph[ci].size();\n        for(size_t n=0;n<nAdj;++n){\n\n            const double val = cell1Features(cellAdjGraph[ci][n]-1);\n\n            //std::cout<<\"value \"<<val<<\"\\n\";\n            accSet(val);\n            accR(val);\n            accL(val);\n        }\n\n        //const double ql = boost::accumulators::quantile(accSet, quantile_probability = pl);\n        //const double qh = boost::accumulators::quantile(accSet, quantile_probability = ph);\n\n\n        const double ql = boost::accumulators::quantile(accL, quantile_probability = pl);\n        const double qh = boost::accumulators::quantile(accR, quantile_probability = ph);\n\n        //std::cout<<\"ql \"<<ql<<\"\\n\";\n        //std::cout<<\"qh \"<<qh<<\"\\n\";\n\n        /*\n        std::cout<<\"left\\n\";\n        std::cout<<\"ql \"<<boost::accumulators::quantile(accL, quantile_probability = pl)<<\"\\n\";\n        std::cout<<\"qh \"<<boost::accumulators::quantile(accL, quantile_probability = ph)<<\"\\n\";\n\n        std::cout<<\"right\\n\";\n        std::cout<<\"ql \"<<boost::accumulators::quantile(accR, quantile_probability = pl)<<\"\\n\";\n        std::cout<<\"qh \"<<boost::accumulators::quantile(accR, quantile_probability = ph)<<\"\\n\\n\";\n        */\n        size_t nl=0,nh=0;\n\n\n\n\n        if(ownVal <= ql && nAdj!=0){\n\n            for(size_t n=0;n<nAdj;++n){\n                nl+=static_cast<double>(cell1Features(cellAdjGraph[ci][n]-1)) <= ql ? 1 : 0;\n                nh+=static_cast<double>(cell1Features(cellAdjGraph[ci][n]-1)) >= qh ? 1 : 0;\n            }\n            CGP_ASSERT_OP(nh,>=,1);\n            CGP_ASSERT_OP(nl,>=,1);\n\n            const double forOthers = (ownVal*frac)/static_cast<double>(nh);\n            resultArray(ci)-=(ownVal*frac);\n            for(size_t n=0;n<nAdj;++n){\n                if(static_cast<double>(cell1Features(cellAdjGraph[ci][n]-1)) >= qh){\n                    resultArray(cellAdjGraph[ci][n]-1)+=forOthers;\n                }\n            }\n        }\n    }\n    return resultArray;\n}\n\n\n\n\ntemplate<class CGP>\nvigra::NumpyAnyArray  graphBiMean(\n    const CGP & cgp,\n    vigra::NumpyArray<1,float> cell1Features,\n    const float alpha,  // high alpha means a lot of smoothing (alpha in [0,1] )\n    const float gamma   // LOW gamma means a lot of smoothing\n){\n\n    typedef vigra::NumpyArray<1,float>  ResultArray;\n    typedef typename ResultArray::difference_type ShapeType;\n\n    typedef typename CGP::Cells0 Cells0;\n    typedef typename CGP::Cells1 Cells1;\n\n    typedef typename CGP::Cell0 Cell0;\n    typedef typename CGP::Cell1 Cell1;\n\n    const size_t numJunctions  = cgp.numCells(0);\n    const size_t numBoundaries = cgp.numCells(1);\n    const Cells1 & cells1=cgp.geometry1();\n    const Cells0 & cells0=cgp.geometry0();\n\n    // initialize result array\n    ResultArray resultArray = ResultArray(ShapeType(numBoundaries));\n    std::copy(cell1Features.begin(),cell1Features.end(),resultArray.begin());\n\n\n    for(size_t bi=0;bi<numBoundaries;++bi){\n        const Cell1 & cell1 = cells1[bi];\n        const size_t numJB = cell1.boundedBy().size();\n        CGP_ASSERT_OP(numJB,<=,2);\n\n        typedef std::set<size_t> SetType;\n        typedef typename SetType::const_iterator SetIter;\n        SetType adjBounadries;\n\n        // loop over all junctions of a boundarie (most the time 2 junctions sometime 1 and zero (rings,boarder))\n        for(size_t j=0;j<numJB;++j){\n\n            const size_t ji = cell1.boundedBy()[j]-1;\n            const Cell0 & cell0 = cells0[ji];\n            const size_t numBJ = cell0.bounds().size();\n\n            CGP_ASSERT_OP(numBJ,>=,3);\n            CGP_ASSERT_OP(numBJ,<=,4);\n\n            // loop over all 3 or 4 boundaries of the junction and add them to adjacency\n            for(size_t b=0;b<numBJ;++b){\n\n                const size_t otherBi = cell0.bounds()[b]-1; \n                if(otherBi!=bi){\n                    adjBounadries.insert(otherBi);\n                }\n            }\n        }\n\n        // frome here on boundary adj. is known\n        const size_t numAdj = adjBounadries.size();\n        \n        if (numAdj>0){\n            // mix the values\n            float alphaFrac     = alpha/float(numAdj);\n            const float ownVal  = cell1Features(bi);\n            float valSum        = 0.0;\n            float wSum          = 0.0;\n\n            // add onw value\n\n            valSum += (1.0-alpha)*ownVal;\n            wSum   += (1.0-alpha);\n\n\n\n            for(SetIter iter = adjBounadries.begin();iter!=adjBounadries.end();++iter){\n                const size_t otherBi  = *iter;\n                const float  otherVal = cell1Features(otherBi);\n                const float  wColor   = std::exp(-1.0*gamma*std::abs(ownVal-otherVal));\n                const float  wTotal   = wColor*alphaFrac;\n\n                // add other values\n                valSum +=wTotal*otherVal;\n                wSum   +=wTotal;\n            }\n            const float newVal = valSum / wSum;\n            resultArray(bi)=newVal;\n        }\n    }\n\n    return resultArray;\n}\n\n\n\n\ntemplate<class CGP>\nvigra::NumpyAnyArray  graphPropagation(\n    const CGP & cgp,\n    vigra::NumpyArray<1,float> cell1Features\n){\n\n    typedef vigra::NumpyArray<1,float>  ResultArray;\n    typedef typename ResultArray::difference_type ShapeType;\n\n    typedef typename CGP::Cells0 Cells0;\n    typedef typename CGP::Cells1 Cells1;\n\n    typedef typename CGP::Cell0 Cell0;\n    typedef typename CGP::Cell1 Cell1;\n\n    const size_t numJunctions = cgp.numCells(0);\n    const size_t numBoundaries     = cgp.numCells(1);\n    const Cells1 & cells1=cgp.geometry1();\n    const Cells0 & cells0=cgp.geometry0();\n\n    // initialize result array\n    ResultArray resultArray = ResultArray(ShapeType(numBoundaries));\n    std::copy(cell1Features.begin(),cell1Features.end(),resultArray.begin());\n\n\n    float fw[4]={0.0, 0.0, 0.0, 0.0};\n\n\n    int a[] = { 3, 1, 0, 4 } ;\n    std::vector<size_t> indexes ;\n    \n    std::vector<float> reservedVec;\n    reservedVec.reserve(2);\n    std::vector<  std::vector<float>  >  weightCollection(numBoundaries,reservedVec);\n\n\n    for(size_t j=0;j<numJunctions;++j){\n        const Cell0 & cell0 = cells0[j];\n        const size_t numBounds = cell0.bounds().size();\n\n        CGP_ASSERT_OP(numBounds,<=,4);\n        CGP_ASSERT_OP(numBounds,>=,3);\n\n        //std::cout<<\"boundssize \"<<numBounds<<\"\\n\";\n        // get maximum of junction\n        for(size_t b=0;b<numBounds;++b){\n            const size_t faceIndex=cell0.bounds()[b]-1;\n            const float faceWeight= cell1Features(faceIndex);\n            fw[b]=faceWeight;\n        }\n        \n        argsort(fw, fw+numBounds, std::greater<float>(), indexes) ;\n\n        if(numBounds==3){\n            const size_t i0 = indexes[0];\n            const size_t i1 = indexes[1];\n            const size_t i2 = indexes[2];\n\n            const float mean2 = ( fw[i0] + fw[i1] )/2.0;\n            const float toGiveAway =( fw[i2]  )/2.0;\n\n            weightCollection[ cell0.bounds()[i0]-1].push_back(mean2+toGiveAway/2.0);\n            weightCollection[ cell0.bounds()[i1]-1].push_back(mean2+toGiveAway/2.0);\n            weightCollection[ cell0.bounds()[i2]-1].push_back(toGiveAway);\n        }\n        else{\n            const size_t i0 = indexes[0];\n            const size_t i1 = indexes[1];\n            const size_t i2 = indexes[2];\n            const size_t i3 = indexes[3];\n            \n            const float mean2 = ( fw[i0] + fw[i1] )/2.0;\n            const float toGiveAway =( fw[i2] +fw[i3]  )/4.0;\n\n            weightCollection[ cell0.bounds()[i0]-1].push_back(mean2+toGiveAway/2.0);\n            weightCollection[ cell0.bounds()[i1]-1].push_back(mean2+toGiveAway/2.0);\n            weightCollection[ cell0.bounds()[i2]-1].push_back(toGiveAway);\n            weightCollection[ cell0.bounds()[i3]-1].push_back(toGiveAway);\n        }\n    }\n\n    for(size_t i=0;i<numBoundaries;++i){\n        const size_t numWeights=weightCollection[i].size();\n        if(numWeights==0){\n            resultArray(i)=cell1Features(i);\n        }\n        else{\n            float mean=0;\n            for(size_t j=0;j<numWeights;++j){\n                mean+=weightCollection[i][j];\n            }\n            resultArray(i)=mean/numWeights;\n        }\n    }\n\n\n    return resultArray;\n}\n\n\n\n/*\n    - min \n    - max\n    - mean\n    - median\n*/\n\ntemplate<class CGP>\nvigra::NumpyAnyArray  cell1GraphAdjAcc(\n    const CGP & cgp,\n    vigra::NumpyArray<1,float> cell1Features\n){\n\n    typedef vigra::NumpyArray<2,float>  ResultArray;\n    typedef typename ResultArray::difference_type ShapeType;\n    typedef typename CGP::Cells0 Cells0;\n    typedef typename CGP::Cells1 Cells1;\n    typedef typename CGP::Cell0 Cell0;\n    typedef typename CGP::Cell1 Cell1;\n    typedef typename CGP::CellAdjacencyGraphVectorType CellAdjGraph;\n\n    const size_t cellType = 1;\n    const size_t numCells = cgp.numCells(cellType);\n\n    using namespace boost::accumulators;\n    typedef accumulator_set<double, stats<\n        tag::min,\n        tag::max,\n        tag::mean,\n        tag::median(with_p_square_quantile)\n    > > AccSet;\n\n\n     // initialize result array\n    ResultArray resultArray = ResultArray(ShapeType(numCells,4));\n\n    // Adj Graph \n    CellAdjGraph cellAdjGraph;\n    //std::cout<<\"fill adj\\n\";\n    // fill adjacency graph\n    cgp.cellAdjacencyGraphVector(cellType,cellAdjGraph);\n    //std::cout<<\"fill adj done\\n\";\n\n\n    for(size_t ci=0;ci<numCells;++ci){\n\n        AccSet accSet;\n        accSet(static_cast<double>(cell1Features(ci)));\n\n        for(size_t n=0;n<cellAdjGraph[ci].size();++n){\n            accSet(static_cast<double>(cell1Features(cellAdjGraph[ci][n]-1)));\n        }\n\n        resultArray(ci,0)=static_cast<float>(boost::accumulators::min(accSet));\n        resultArray(ci,1)=static_cast<float>(boost::accumulators::max(accSet));\n        resultArray(ci,2)=static_cast<float>(boost::accumulators::mean(accSet));\n        resultArray(ci,3)=static_cast<float>(boost::accumulators::median(accSet));\n    }\n    return resultArray;\n}\n\n\n\n\n\ntemplate<class CGP>\nvigra::NumpyAnyArray  graphMax(\n    const CGP & cgp,\n    vigra::NumpyArray<1,float> cell1Features\n){\n\n    typedef vigra::NumpyArray<1,float>  ResultArray;\n    typedef typename ResultArray::difference_type ShapeType;\n\n    typedef typename CGP::Cells0 Cells0;\n    typedef typename CGP::Cells1 Cells1;\n\n    typedef typename CGP::Cell0 Cell0;\n    typedef typename CGP::Cell1 Cell1;\n\n    const size_t numJunctions = cgp.numCells(0);\n    const size_t numBoundaries     = cgp.numCells(1);\n    const Cells1 & cells1=cgp.geometry1();\n    const Cells0 & cells0=cgp.geometry0();\n\n    // initialize result array\n    ResultArray resultArray = ResultArray(ShapeType(numBoundaries));\n    std::copy(cell1Features.begin(),cell1Features.end(),resultArray.begin());\n\n\n    for(size_t j=0;j<numJunctions;++j){\n        float maxFaceWeight = -1.0*std::numeric_limits<float>::infinity();\n        const Cell0 & cell0 = cells0[j];\n        const size_t numBounds = cell0.bounds().size();\n        //std::cout<<\"boundssize \"<<numBounds<<\"\\n\";\n        // get maximum of junction\n        for(size_t b=0;b<numBounds;++b){\n            const size_t faceIndex=cell0.bounds()[b]-1;\n            const float faceWeight= cell1Features(faceIndex);\n            maxFaceWeight = faceWeight>maxFaceWeight ? faceWeight : maxFaceWeight ;\n        }\n        // get maximum of junction\n        for(size_t b=0;b<numBounds;++b){\n            const size_t faceIndex=cell0.bounds()[b]-1;\n            resultArray(faceIndex)=maxFaceWeight;\n        }\n    }\n    return resultArray;\n}\n\n\n\ntemplate<class CGP>\nvigra::NumpyAnyArray cell1BoundsArray(\n    const CGP & cgp\n){\n    typedef vigra::NumpyArray<2,int>  ResultArray;\n    typedef typename ResultArray::difference_type ShapeType;\n\n    typedef typename CGP::Cells0 Cells0;\n    typedef typename CGP::Cells1 Cells1;\n    typedef typename CGP::Cells2 Cells2;\n\n    typedef typename CGP::Cell0 Cell0;\n    typedef typename CGP::Cell1 Cell1;\n    typedef typename CGP::Cell2 Cell2;\n\n    const size_t numBoundaries = cgp.numCells(1);\n    const size_t numRegion     = cgp.numCells(2);\n    const Cells1 & cells1=cgp.geometry1();\n    CGP_ASSERT_OP(numBoundaries,==,cells1.size());\n\n    ResultArray resultArray = ResultArray(ShapeType(numBoundaries,2));\n\n    for(size_t b=0;b<numBoundaries;++b){\n        const Cell1 & cell1 = cells1[b];\n        const int la = cell1.bounds()[0];\n        const int lb = cell1.bounds()[1];\n        CGP_ASSERT_OP(la,!=,0);\n        CGP_ASSERT_OP(lb,!=,0);\n        resultArray(b,0)=la;\n        resultArray(b,1)=lb;\n    }\n    return resultArray;\n}\n\n\ntemplate<class CELL>\npython::tuple pointNumpyTupe(const CELL & cell){\n    const size_t numPoints=cell.points().size();\n    typedef vigra::NumpyArray<1,vigra::UInt32>  SingleCoordArrayType;\n    typedef typename SingleCoordArrayType::difference_type ShapeType;\n    const ShapeType shape(numPoints);\n\n    SingleCoordArrayType cx(shape),cy(shape);\n    for(size_t i=0;i<numPoints;++i){\n        cx(i)=cell.points()[i][0];\n        cy(i)=cell.points()[i][1];\n    }\n    vigra::NumpyAnyArray ax=cx,ay=cy;\n    return python::make_tuple(ax,ay);\n}\n\n\ntemplate<class TGRID>\nvigra::NumpyAnyArray getCellLabelGrid(\n                                const TGRID & tgrid,\n                                int cellType,\n                                bool useTopologicalShape,\n                                vigra::NumpyArray<2, vigra::Singleband<npy_uint32> > res = vigra::NumpyArray<2,vigra::Singleband<npy_uint32> >()){\n\n    if(useTopologicalShape){\n        res.reshapeIfEmpty(tgrid.tgrid().shape());\n        std::fill(res.begin(),res.end(),0);\n\n        if(cellType==0){\n            for(size_t y=1;y<tgrid.shape(1);y+=2)\n            for(size_t x=1;x<tgrid.shape(0);x+=2){\n                if( tgrid(x,y)!=0 )\n                    res(x,y)=tgrid(x,y);\n            }\n        }\n        else if(cellType==1){\n            for(size_t y=0;y<tgrid.shape(1);++y)\n            for(size_t x=0;x<tgrid.shape(0);++x){\n                if(  (  (x%2==0 && y%2!=0) || (x%2!=0 && y%2==0) ) && tgrid(x,y)!=0 )\n                    res(x,y)=tgrid(x,y);\n            }\n        }\n        else if(cellType==2){\n            for(size_t y=0;y<tgrid.shape(1);y+=2)\n            for(size_t x=0;x<tgrid.shape(0);x+=2){\n                res(x,y)=tgrid(x,y);\n            }\n        }\n    }\n    else{\n        typedef typename TGRID::LabelImageType::difference_type ShapeType;\n        const ShapeType shape( (tgrid.shape(0)+1)/2,(tgrid.shape(1)+1)/2   );\n        res.reshapeIfEmpty(shape);\n        std::fill(res.begin(),res.end(),0);\n\n        if(cellType==0){\n            for(size_t y=1;y<tgrid.shape(1);y+=2)\n            for(size_t x=1;x<tgrid.shape(0);x+=2){\n                if( tgrid(x,y)!=0 ){\n                    // for junction-pixel:\n                    // 1 pixel in t-grid => 4 pixels in grid \n                    res( (x+1)/2,(y+1)/2 )=tgrid(x,y);\n                    res( (x+1)/2,(y-1)/2 )=tgrid(x,y);\n                    res( (x-1)/2,(y+1)/2 )=tgrid(x,y);\n                    res( (x-1)/2,(y+1)/2 )=tgrid(x,y);\n                }\n            }\n        }\n\n        else if(cellType==1){\n            for(size_t y=0;y<tgrid.shape(1);++y)\n            for(size_t x=0;x<tgrid.shape(0);++x){\n\n                if(tgrid(x,y)!=0 ){\n\n                    // - boundary \n                    if( x%2==0 && y%2!=0 ){\n                        // for boundary-pixel:\n                        // 1 pixel in t-grid => 2 pixels in grid \n                        res( x/2,(y+1)/2 )=tgrid(x,y);\n                        res( x/2,(y-1)/2 )=tgrid(x,y);\n                    }\n                    //  |  boundary\n                    else if(x%2!=0 && y%2==0){\n                        // for boundary-pixel:\n                        // 1 pixel in t-grid => 2 pixels in grid \n                        res( (x-1)/2,y/2 )=tgrid(x,y);\n                        res( (x+1)/2,y/2 )=tgrid(x,y);\n                    }\n                }\n            }\n        }\n\n        else if(cellType==2){\n            for(size_t y=0;y<tgrid.shape(1);y+=2)\n            for(size_t x=0;x<tgrid.shape(0);x+=2){\n                // for region-pixel:\n                // 1 pixel in t-grid => 4 pixels in grid \n                res(x/2,y/2)=tgrid(x,y);\n            }\n        }   \n    }\n    return res;\n}\n\n\ntemplate<class CGP>\nvigra::NumpyArray<1, unsigned int> pyCgpSerialize(\n    const CGP& cgp\n) {\n    vigra::NumpyArray<1, unsigned int> result;\n    std::vector<unsigned int> res = cgp.serialize();\n    result.reshape(vigra::Shape1(res.size()));\n    std::copy(res.begin(), res.end(), result.begin());\n    return result;\n}\n\ntemplate<class CGP>\nconst typename CGP::TopologicalGridType * merge2Cells(\n    const CGP & cgp,\n    vigra::NumpyArray<1,npy_uint32> cell1States\n){\n    typename CGP::TopologicalGridType * tgrid = new typename CGP::TopologicalGridType();\n    cgp.merge2Cells(cell1States.begin(),cell1States.end(),*tgrid);\n    return tgrid;\n}\n\n\n\n\n\ntemplate<class CGP>\nvigra::NumpyAnyArray featuresToFeatureImage(\n    const CGP & cgp,\n    int cellType,\n    vigra::NumpyArray<1,float> features,\n    const bool ignoreInactive,\n    const float inactiveValue,\n    const bool useTopologicalShape=true,\n    vigra::NumpyArray<2, vigra::Singleband<float> > res = vigra::NumpyArray<2,vigra::Singleband<float> >()\n){\n    typedef typename  CGP::LabelType LabelType;\n    if(useTopologicalShape)\n        res.reshapeIfEmpty(cgp.tgrid().tgrid().shape());\n    else\n        res.reshapeIfEmpty(cgp.tgrid().shapeLabeling());\n        \n\n    if(ignoreInactive==false)\n        std::fill(res.begin(),res.end(),inactiveValue);\n\n    if(useTopologicalShape){\n        if (cellType==0){\n            for(size_t y=0;y<cgp.shape(1);++y)\n            for(size_t x=0;x<cgp.shape(0);++x){\n                const LabelType cellLabel=cgp(x,y);\n                if(cellType==0)\n                if( (x%2!=0 && y%2!=0) && cellLabel!=0)\n                    res(x,y)=features[cellLabel-1];\n            }\n        }\n        if(cellType==1){\n            for(size_t y=0;y<cgp.shape(1);++y)\n            for(size_t x=0;x<cgp.shape(0);++x){\n                const LabelType cellLabel=cgp(x,y);\n                if( ( (x%2==0 && y%2!=0)  || (x%2!=0 && y%2==0 ) ) && cellLabel!=0)\n                    res(x,y)=features[cellLabel-1];\n            }\n        }\n        else if(cellType==2){\n            for(size_t y=0;y<cgp.shape(1);++y)\n            for(size_t x=0;x<cgp.shape(0);++x){\n                const LabelType cellLabel=cgp(x,y);\n                if( (x%2==0 && y%2==0))\n                    res(x,y)=features[cellLabel-1];\n            }\n        }\n    }\n\n\n    else{\n\n        if(cellType==0){\n            for(size_t y=1;y<cgp.shape(1);y+=2)\n            for(size_t x=1;x<cgp.shape(0);x+=2){\n                if( cgp(x,y)!=0 ){\n                    // for junction-pixel:\n                    // 1 pixel in t-grid => 4 pixels in grid \n                    res( (x+1)/2,(y+1)/2 )=features[cgp(x,y)-1];\n                    res( (x+1)/2,(y-1)/2 )=features[cgp(x,y)-1];\n                    res( (x-1)/2,(y+1)/2 )=features[cgp(x,y)-1];\n                    res( (x-1)/2,(y+1)/2 )=features[cgp(x,y)-1];\n                }\n            }\n        }\n\n        else if(cellType==1){\n            for(size_t y=0;y<cgp.shape(1);++y)\n            for(size_t x=0;x<cgp.shape(0);++x){\n\n                if(cgp(x,y)!=0 ){\n\n                    // - boundary \n                    if( x%2==0 && y%2!=0 ){\n                        // for boundary-pixel:\n                        // 1 pixel in t-grid => 2 pixels in grid \n                        res( x/2,(y+1)/2 )=features[cgp(x,y)-1];\n                        res( x/2,(y-1)/2 )=features[cgp(x,y)-1];\n                    }\n                    //  |  boundary\n                    else if(x%2!=0 && y%2==0){\n                        // for boundary-pixel:\n                        // 1 pixel in t-grid => 2 pixels in grid \n                        res( (x-1)/2,y/2 )=features[cgp(x,y)-1];\n                        res( (x+1)/2,y/2 )=features[cgp(x,y)-1];\n                    }\n                }\n            }\n        }\n\n        else if(cellType==2){\n            for(size_t y=0;y<cgp.shape(1);y+=2)\n            for(size_t x=0;x<cgp.shape(0);x+=2){\n                // for region-pixel:\n                // 1 pixel in t-grid => 4 pixels in grid \n                res(x/2,y/2)=features[cgp(x,y)-1];\n            }\n        }   \n    }\n    return res;\n}\n\n\ntemplate<class CGP>\nvigra::NumpyAnyArray orientedWatershedTransform\n(   \n    const CGP & cgp,\n    vigra::NumpyArray<2 ,vigra::TinyVector< float  ,2 > > gradientImage\n){\n    typedef vigra::NumpyArray<1, float  > NumpyFloat1d;\n    typedef typename NumpyFloat1d::difference_type ShapeType;\n    typedef vigra::TinyVector<float,2> VecType;\n\n    const size_t numBoundaries = cgp.numCells(1);\n    NumpyFloat1d resultWeights=NumpyFloat1d(ShapeType(numBoundaries));\n\n    \n    typedef typename CGP::Cells1 Cells1;\n    typedef typename CGP::Cell1   Cell1;\n\n    const Cells1 & cells1=cgp.geometry1();\n\n    for(size_t i=0;i<numBoundaries;++i){\n        const Cell1 & cell = cells1[i];\n\n        float weight=0.0;\n        for (size_t j =0; j<cell.size(); ++j){\n\n\n            // get \"orientation vector\" of \n            // boundary and transform it into \n            // normal vector\n            VecType normalFace = cell.angles_[j];\n\n            const float gx =  normalFace[0];\n            const float gy =  normalFace[1];\n\n            normalFace/=vigra::norm(normalFace);\n\n            float np= std::sqrt(normalFace[0]*normalFace[0] +normalFace[1]*normalFace[1]);\n            std::cout<<\"np \"<<np<<\"\\n\";\n\n\n\n            //normalFace[0] = -1.0 *gy;\n            //normalFace[1] = gx;\n\n\n            const size_t x=cell[j][0];\n            const size_t y=cell[j][1];\n            //'std::cout << \"x,y \"<<x<<\",\"<<y<<\"\\n\";\n            VecType grad = gradientImage(x,y);\n            grad/=vigra::norm(grad);\n\n            if(grad[1]>0){\n                grad*=-1.0;\n            }\n\n            if(normalFace[1]>0){\n                normalFace*=-1.0;\n            } \n\n\n\n            const float dotP = vigra::dot(grad,normalFace);\n            float theta= std::acos(dotP);\n\n            std::cout<<\"theta \"<< theta<<\" \"<<\"dotP \"<<dotP<<\" gX,gY \"<<grad[0]<<\",\"<<grad[1]<<\" nX,nY \"<<normalFace[0]<<\",\"<<normalFace[1]<<\" \\n\";\n            \n            while(theta>=M_PI/2.0){\n                theta-=M_PI/2.0;\n            }\n            theta/=(M_PI/2.0);\n\n            std::cout<<\"final theta \"<<theta<<\"\\n\";\n\n            if ( std::isnan(theta)){\n                theta=0.5;\n            }\n\n            weight += theta;\n            \n        }\n        weight/=float(cell.size());\n        std::cout<<\"********************************final weight \"<<weight<<\"\\n\";\n        resultWeights(i)=weight;\n    }\n    \n    \n    return resultWeights;\n}\n\ntemplate<class CGP>\nvigra::NumpyAnyArray cellSizes(\n    const CGP & cgp,\n    const size_t cellType,\n    vigra::NumpyArray<1, vigra::UInt32 > res = vigra::NumpyArray<1,vigra::UInt32> ()\n){\n    const size_t nCells = cgp.numCells(cellType);\n    res.reshapeIfEmpty(typename vigra::NumpyArray<1,vigra::UInt32>::difference_type(nCells));\n    for(size_t  c=0;c<nCells;++c){\n        res(c)=cgp.cellSize(cellType,c);\n    }\n    return res;\n}\n\nvoid export_cgp2d()\n{\n    using namespace python;\n    \n    docstring_options doc_options(true, true, false);\n\n\n    ////////////////////////////////////////\n    // Region Graph\n    ////////////////////////////////////////\n    // basic types\n    // tgrid and input image type\n    \n    typedef Cgp<CoordinateType,LabelType> CgpType;\n    typedef CgpType::TopologicalGridType TopologicalGridType;\n\n    typedef  vigra::NumpyArray<2 ,vigra::Singleband < LabelType > > InputLabelImageType;\n    // cgp type and cell types\n    typedef CgpType::PointType PointType;\n    // bound vector\n    typedef std::vector<float> FloatVectorType;\n    typedef std::vector<LabelType> LabelVectorType;\n    // point vector\n    typedef std::vector<PointType> PointVectorType;\n    // geo cells \n    typedef CgpType::Cell0 Cell0Type;\n    typedef CgpType::Cell1 Cell1Type;\n    typedef CgpType::Cell2 Cell2Type;\n\n    typedef CgpType::Cells0 Cell0VectorType;\n    typedef CgpType::Cells1 Cell1VectorType;\n    typedef CgpType::Cells2 Cell2VectorType;\n\n    // cell vectors\n    python::class_<TopologicalGridType>(\"TopologicalGrid\",python::init<const InputLabelImageType & >())\n    .add_property(\"shape\", python::make_function(&TopologicalGridType::shapeTopologicalGrid, python::return_value_policy<return_by_value>()) )\n    .add_property(\"shapeLabeling\", python::make_function(&TopologicalGridType::shapeLabeling, python::return_value_policy<return_by_value>()) )\n    .def(\"numCells\",&TopologicalGridType::numCells)\n    .def(\"labelGrid\",vigra::registerConverters(&getCellLabelGrid<TopologicalGridType> ) ,\n        (\n            arg(\"cellType\"),\n            arg(\"useTopologicalShape\")=true,\n            arg(\"out\")=python::object() \n        )  \n    )\n    ;\n\n    // float vector\n    python::class_<FloatVectorType>(\"FloatVector\",init<>())\n        .def(vector_indexing_suite<FloatVectorType ,true >())\n    ;\n    // bound / bounded by vector\n    python::class_<LabelVectorType> exporter = python::class_<LabelVectorType>(\"LabelVector\",init<>())\n        .def(vector_indexing_suite<LabelVectorType >())\n    ;\n    // point   vector\n    python::class_<PointVectorType>(\"PointVector\",init<>())\n        .def(vector_indexing_suite<PointVectorType ,true>())\n    ;\n\n    /*\n    // cells\n    python::class_<Cell0Type>(\"Cell0\",python::init<>())\n        .def(CellTypeSuite<Cell0Type>())\n        .def(\"getAngles\",&getAngles<Cell0Type>,python::return_value_policy<python::manage_new_object>())\n    ;\n\n    python::class_<Cell1Type>(\"Cell1\",python::init<>())\n        .def(CellTypeSuite<Cell1Type>())\n    ;\n\n    python::class_<Cell2Type>(\"Cell2\",python::init<>())\n        .def(CellTypeSuite<Cell2Type>())\n    ;\n\n    // cells vectors\n    python::class_<Cell0VectorType>(\"Cell0Vector\",init<>())\n        .def(vector_indexing_suite<Cell0VectorType >())\n    ;\n    python::class_<Cell1VectorType>(\"Cell1Vector\",init<>())\n        .def(vector_indexing_suite<Cell1VectorType >())\n    ;\n    python::class_<Cell2VectorType>(\"Cell2Vector\",init<>())\n        .def(vector_indexing_suite<Cell2VectorType >())\n    ;\n    */\n\n    /************************************************************************/\n    /* C e l l B a s e                                                      */\n    /************************************************************************/\n\n    python::class_<CgpType>(\"Cgp\",python::init<const TopologicalGridType & >()[with_custodian_and_ward<1 /*custodian == self*/, 2 /*ward == const TopologicalGridType& */>()] )\n\n        .add_property(\"shape\", python::make_function(&CgpType::shapeTopologicalGrid, python::return_value_policy<return_by_value>()) )\n        .add_property(\"shapeLabeling\", python::make_function(&CgpType::shapeLabeling, python::return_value_policy<return_by_value>()))\n\n        \n        //.def(\"shape\",&CgpType::shape)\n        \n        .add_property(\"tgrid\", python::make_function(&CgpType::tgrid, return_internal_reference<>() ))\n        .add_property(\"cells0\", python::make_function(&CgpType::geometry0, return_internal_reference<>() ))\n        .add_property(\"cells1\", python::make_function(&CgpType::geometry1, return_internal_reference<>() ))\n        .add_property(\"cells2\", python::make_function(&CgpType::geometry2, return_internal_reference<>() ))\n        .def(\"cell1BoundsArray\",vigra::registerConverters(&cell1BoundsArray<CgpType>))\n\n        /*\n        .def(\"_cell1countMultiEdges\",vigra::registerConverters(&countMultiEdges<CgpType>))\n        .def(\"_cell1TopoFeatures\",vigra::registerConverters(&cell1TopoFeatures<CgpType>))\n        .def(\"_cell1GeoFeatures\",vigra::registerConverters(&cell1GeoFeatures<CgpType>))\n        .def(\"_cell1RelativeCenterDist\",vigra::registerConverters(&relativeCenterDist<CgpType>))\n        .def(\"_cell1BoarderTouch\",vigra::registerConverters(&boarderTouch<CgpType>))\n        .def(\"_cell1GraphStealing\",vigra::registerConverters(&cell1GraphStealing<CgpType>))\n        .def(\"_cell1GraphMax\", vigra::registerConverters(&graphMax<CgpType>))\n        .def(\"_cell1GraphPropagation\",vigra::registerConverters(&graphPropagation<CgpType>))\n        .def(\"_cell1GraphBiMean\",vigra::registerConverters(&graphBiMean<CgpType>))\n        .def(\"_cell1GraphAdjAcc\",vigra::registerConverters(&cell1GraphAdjAcc<CgpType>))\n        */\n        .def(\"cellSizes\",vigra::registerConverters(&cellSizes<CgpType>),\n            (\n                arg(\"cellType\"),\n                arg(\"out\")=python::object()\n            )\n        )\n        .def(\"serialize\", &pyCgpSerialize<CgpType>)\n        .def(\"numCells\",&CgpType::numCells)\n        .def(\"featureToImage\",vigra::registerConverters(&featuresToFeatureImage<CgpType>),\n            (\n                arg(\"cellType\"),\n                arg(\"features\"),\n                arg(\"ignoreInactive\")=false,\n                arg(\"inactiveValue\")=0.0f,\n                arg(\"useTopologicalShape\")=true,\n                arg(\"out\")=python::object()\n            )\n        )\n        .def(\"merge2Cells\",vigra::registerConverters( &merge2Cells<CgpType> ) ,python::return_value_policy<python::manage_new_object>(),\n            (\n                arg(\"cell1States\")\n            )\n        )\n        .def(\"owt\", vigra::registerConverters(&orientedWatershedTransform<CgpType> ))\n    ;\n}\n\n} // namespace vigra\n\n", "meta": {"hexsha": "beeda4ba99d66cbe675174ed56b68c65348637ac", "size": 42145, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "src/python/cgp2d/py_cgp2d.cxx", "max_stars_repo_name": "DerThorsten/seglib", "max_stars_repo_head_hexsha": "4655079e390e301dd93e53f5beed6c9737d6df9f", "max_stars_repo_licenses": ["MIT"], "max_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/cgp2d/py_cgp2d.cxx", "max_issues_repo_name": "DerThorsten/seglib", "max_issues_repo_head_hexsha": "4655079e390e301dd93e53f5beed6c9737d6df9f", "max_issues_repo_licenses": ["MIT"], "max_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/cgp2d/py_cgp2d.cxx", "max_forks_repo_name": "DerThorsten/seglib", "max_forks_repo_head_hexsha": "4655079e390e301dd93e53f5beed6c9737d6df9f", "max_forks_repo_licenses": ["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.9522365428, "max_line_length": 175, "alphanum_fraction": 0.5865227192, "num_tokens": 11416, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5813030906443133, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.3379132831926307}}
{"text": "#include \"../include/includes.hpp\"\n#include \"../include/core/config.hpp\"\n#include \"../include/core/utilities.hpp\"\n#include \"../include/waveO1/solver.hpp\"\n#include \"../include/waveO1/sparse_grids_handler.hpp\"\n#include \"../include/mymfem/local_mesh_refinement.hpp\"\n\n#include <iostream>\n#include <Eigen/Core>\n\n\nvoid run_waveFG (const nlohmann::json& config,\n                 std::string base_mesh_dir,\n                 bool load_init_mesh=false)\n{\n    const int lt = config[\"level_t\"];\n    const int lx = config[\"level_x\"];\n    std::string sub_mesh_dir = config[\"mesh_dir\"];\n    const std::string mesh_dir = base_mesh_dir+sub_mesh_dir;\n\n    auto testCase = make_waveO1_test_case(config);\n    WaveO1Solver wave_solverFG(config, testCase,\n                               mesh_dir, lx, lt,\n                               load_init_mesh);\n\n    auto [ndofs, ht_max, hx_max, errSol] = wave_solverFG();\n    std::cout << \"\\n\\nError: \"\n              << errSol.transpose() << std::endl;\n    std::cout << \"tMesh size: \" << ht_max << std::endl;\n    std::cout << \"xMesh size: \" << hx_max << std::endl;\n    std::cout << \"#Dofs: \" << ndofs << std::endl;\n}\n\nvoid run_waveSG (const nlohmann::json& config,\n                 std::string base_mesh_dir,\n                 bool load_init_mesh=false)\n{\n    const int Lx = config[\"sg_max_level_x\"];\n    const int L0x = config[\"sg_min_level_x\"];\n    const int L0t = config[\"sg_min_level_t\"];\n\n    std::string sub_mesh_dir = config[\"mesh_dir\"];\n    const std::string mesh_dir = base_mesh_dir+sub_mesh_dir;\n\n    auto testCase = make_waveO1_test_case(config);\n    SparseGridsHandler heat_solverSG(config, testCase,\n                                     mesh_dir,\n                                     Lx, L0x, L0t,\n                                     load_init_mesh);\n\n    auto [ndofs, ht_max, hx_max, errSol] = heat_solverSG();\n    std::cout << \"\\n\\nError: \"\n              << errSol.transpose() << std::endl;\n    std::cout << \"tMesh size: \" << ht_max << std::endl;\n    std::cout << \"xMesh size: \" << hx_max << std::endl;\n    std::cout << \"#Dofs: \" << ndofs << std::endl;\n}\n\nvoid run_waveProjFG (const nlohmann::json& config,\n                     std::string base_mesh_dir,\n                     bool load_init_mesh=false)\n{\n    const int lt = config[\"level_t\"];\n    const int lx = config[\"level_x\"];\n    std::string sub_mesh_dir = config[\"mesh_dir\"];\n    const std::string mesh_dir = base_mesh_dir+sub_mesh_dir;\n\n    auto testCase = make_waveO1_test_case(config);\n    WaveO1Solver wave_solverFG(config, testCase,\n                               mesh_dir, lx, lt,\n                               load_init_mesh);\n\n    auto [ndofs, ht_max, hx_max, errSol]\n            = wave_solverFG.projection();\n    std::cout << \"\\n\\nError: \"\n              << errSol.transpose() << std::endl;\n    std::cout << \"tMesh size: \" << ht_max << std::endl;\n    std::cout << \"xMesh size: \" << hx_max << std::endl;\n    std::cout << \"#Dofs: \" << ndofs << std::endl;\n}\n\nvoid run_waveProjSG\n(const nlohmann::json& config, std::string base_mesh_dir,\n bool load_init_mesh=false)\n{\n    const int Lx = config[\"sg_max_level_x\"];\n    const int L0x = config[\"sg_min_level_x\"];\n    const int L0t = config[\"sg_min_level_t\"];\n\n    std::string sub_mesh_dir = config[\"mesh_dir\"];\n    const std::string mesh_dir = base_mesh_dir+sub_mesh_dir;\n\n    auto testCase = make_waveO1_test_case(config);\n    SparseGridsHandler heat_solverSG(config, testCase,\n                                     mesh_dir,\n                                     Lx, L0x, L0t,\n                                     load_init_mesh);\n\n    auto [ndofs, ht_max, hx_max, errSol]\n            = heat_solverSG.compute_projection();\n    std::cout << \"\\n\\nError: \"\n              << errSol.transpose() << std::endl;\n    std::cout << \"tMesh size: \" << ht_max << std::endl;\n    std::cout << \"xMesh size: \" << hx_max << std::endl;\n    std::cout << \"#Dofs: \" << ndofs << std::endl;\n}\n\nvoid run_convergence_waveFG (const nlohmann::json& config,\n                             std::string base_mesh_dir,\n                             bool load_init_mesh=false)\n{\n    const int Lt0 = config[\"min_level_t\"];\n    const int Lx0 = config[\"min_level_x\"];\n    const int Lx = config[\"max_level_x\"];\n    std::string sub_mesh_dir = config[\"mesh_dir\"];\n    const std::string mesh_dir = base_mesh_dir+sub_mesh_dir;\n\n    int num_levels = Lx-Lx0+1;\n    Eigen::VectorXi ndofs(num_levels);\n    Eigen::VectorXd h_max(num_levels);\n    Eigen::MatrixXd errSol(2,num_levels);\n    errSol.setZero();\n\n    auto testCase = make_waveO1_test_case(config);\n    WaveO1Solver *solver = nullptr;\n\n    double ht_max, hx_max;\n    Eigen::VectorXd errSol_(2);\n    for (int k=0; k<num_levels; k++)\n    {\n        int lt = Lt0+k;\n        int lx = Lx0+k;\n        solver = new WaveO1Solver(config, testCase,\n                                  mesh_dir, lx, lt,\n                                  load_init_mesh);\n\n        std::tie(ndofs(k), ht_max, hx_max, errSol_)\n                =  (*solver)();\n        h_max(k) = std::max(ht_max, hx_max);\n        errSol.col(k) = errSol_;\n        std::cout << \"Level: \" << lx\n                  << \", ht_max: \" << ht_max\n                  << \", hx_max: \" << hx_max\n                  << \", ndofs: \" << ndofs(k)\n                  << std::endl;\n        std::cout << \"Error: \" << errSol_.transpose()\n                  << \"\\n\" << std::endl;\n        delete solver;\n    }\n    std::cout << \"\\n\\nError:\\n\" << errSol << std::endl;\n\n    write_json_file(\"waveFG\", config, h_max, ndofs, errSol);\n}\n\nvoid run_convergence_waveSG (const nlohmann::json& config,\n                             std::string base_mesh_dir,\n                             bool load_init_mesh=false)\n{\n    const int Lx0 = config[\"min_level_x\"];\n    const int Lx = config[\"max_level_x\"];\n    const int sgL0t = config[\"sg_min_level_t\"];\n    const int sgL0x = config[\"sg_min_level_x\"];\n    std::string sub_mesh_dir = config[\"mesh_dir\"];\n    const std::string mesh_dir = base_mesh_dir+sub_mesh_dir;\n\n    int num_levels = Lx-Lx0+1;\n    Eigen::VectorXi ndofs(num_levels);\n    Eigen::VectorXd h_max(num_levels);\n    Eigen::MatrixXd errSol(2,num_levels);\n    errSol.setZero();\n\n    auto testCase = make_waveO1_test_case(config);\n    SparseGridsHandler *solver = nullptr;\n\n    double ht_max, hx_max;\n    Eigen::VectorXd errSol_(2);\n    for (int k=0; k<num_levels; k++)\n    {\n        int sgLx = Lx0+k;\n        solver = new SparseGridsHandler (config, testCase,\n                                         mesh_dir,\n                                         sgLx, sgL0x, sgL0t,\n                                         load_init_mesh);\n\n        std::tie(ndofs(k), ht_max, hx_max, errSol_)\n                =  (*solver)();\n        h_max(k) = std::max(ht_max, hx_max);\n        errSol.col(k) = errSol_;\n        std::cout << \"Level: \" << sgLx\n                  << \", ht_max: \" << ht_max\n                  << \", hx_max: \" << hx_max\n                  << \", ndofs: \" << ndofs(k)\n                  << std::endl;\n        std::cout << \"Error: \" << errSol_.transpose()\n                  << \"\\n\" << std::endl;\n        delete solver;\n    }\n    std::cout << \"\\n\\nError:\\n\" << errSol << std::endl;\n\n    write_json_file(\"waveSG\", config, h_max, ndofs, errSol);\n}\n\nvoid run_convergence_waveProjFG\n(const nlohmann::json& config, std::string base_mesh_dir,\n bool load_init_mesh=false)\n{\n    const int Lt0 = config[\"min_level_t\"];\n    const int Lx0 = config[\"min_level_x\"];\n    const int Lx = config[\"max_level_x\"];\n    std::string sub_mesh_dir = config[\"mesh_dir\"];\n    const std::string mesh_dir = base_mesh_dir+sub_mesh_dir;\n\n    int num_levels = Lx-Lx0+1;\n    Eigen::VectorXi ndofs(num_levels);\n    Eigen::VectorXd h_max(num_levels);\n    Eigen::MatrixXd errSol(2,num_levels);\n    errSol.setZero();\n\n    auto testCase = make_waveO1_test_case(config);\n    WaveO1Solver *solver = nullptr;\n\n    double ht_max, hx_max;\n    Eigen::VectorXd errSol_(2);\n    for (int k=0; k<num_levels; k++)\n    {\n        int lt = Lt0+k;\n        int lx = Lx0+k;\n        solver = new WaveO1Solver(config, testCase,\n                                  mesh_dir, lx, lt,\n                                  load_init_mesh);\n\n        std::tie(ndofs(k), ht_max, hx_max, errSol_)\n                =  solver->projection();\n        h_max(k) = std::max(ht_max, hx_max);\n        errSol.col(k) = errSol_;\n        std::cout << \"Level: \" << lx\n                  << \", ht_max: \" << ht_max\n                  << \", hx_max: \" << hx_max\n                  << \", ndofs: \" << ndofs(k)\n                  << std::endl;\n        std::cout << \"Error: \" << errSol_.transpose()\n                  << \"\\n\" << std::endl;\n        delete solver;\n    }\n    std::cout << \"\\n\\nError:\\n\" << errSol << std::endl;\n\n    write_json_file(\"waveFG\", config, h_max, ndofs, errSol);\n}\n\nvoid run_convergence_waveProjSG\n(const nlohmann::json& config, std::string base_mesh_dir,\n bool load_init_mesh=false)\n{\n    const int Lx0 = config[\"min_level_x\"];\n    const int Lx = config[\"max_level_x\"];\n    const int sgL0t = config[\"sg_min_level_t\"];\n    const int sgL0x = config[\"sg_min_level_x\"];\n    std::string sub_mesh_dir = config[\"mesh_dir\"];\n    const std::string mesh_dir = base_mesh_dir+sub_mesh_dir;\n\n    int num_levels = Lx-Lx0+1;\n    Eigen::VectorXi ndofs(num_levels);\n    Eigen::VectorXd h_max(num_levels);\n    Eigen::MatrixXd errSol(2,num_levels);\n    errSol.setZero();\n\n    auto testCase = make_waveO1_test_case(config);\n    SparseGridsHandler *solver = nullptr;\n\n    double ht_max, hx_max;\n    Eigen::VectorXd errSol_(2);\n    for (int k=0; k<num_levels; k++)\n    {\n        int sgLx = Lx0+k;\n        solver = new SparseGridsHandler (config, testCase,\n                                         mesh_dir,\n                                         sgLx, sgL0x, sgL0t,\n                                         load_init_mesh);\n\n        std::tie(ndofs(k), ht_max, hx_max, errSol_)\n                =  solver->compute_projection();\n        h_max(k) = std::max(ht_max, hx_max);\n        errSol.col(k) = errSol_;\n        std::cout << \"Level: \" << sgLx\n                  << \", ht_max: \" << ht_max\n                  << \", hx_max: \" << hx_max\n                  << \", ndofs: \" << ndofs(k)\n                  << std::endl;\n        std::cout << \"Error: \" << errSol_.transpose()\n                  << \"\\n\" << std::endl;\n        delete solver;\n    }\n    std::cout << \"\\n\\nError:\\n\" << errSol << std::endl;\n\n    write_json_file(\"waveSG\", config, h_max, ndofs, errSol);\n}\n\nvoid run_localMeshRefinement\n(const nlohmann::json& config, std::string base_mesh_dir,\n bool load_init_mesh=false)\n{\n    const int lx = config[\"level_x\"];\n    int deg = config[\"deg2_x\"];\n\n    int lx0 = 0;\n    std::string sub_mesh_dir = config[\"mesh_dir\"];\n    const std::string mesh_dir = base_mesh_dir+sub_mesh_dir;\n    const std::string mesh_file\n            = mesh_dir+\"/tri_mesh_l\"\n            +std::to_string(lx0)+\".mesh\";\n    std::cout << \"  Initial mesh file: \"\n              << mesh_file << std::endl;\n\n    bool bool_nonConforming = true;\n    if (config.contains(\"nonConforming\")) {\n        bool_nonConforming = config[\"nonConforming\"];\n    }\n\n    auto xMesh\n            = std::make_shared<Mesh>(mesh_file.c_str());\n\n    // geometry\n    std::shared_ptr<Polygon> lShaped\n            = std::make_shared<LShaped>();\n    Array<bool> refineFlags(1);\n    Array<double> refineWeights(1);\n    refineFlags[0] = true;\n    refineWeights[0] = 1-2./3;\n    lShaped->set_refine_flags(refineFlags);\n    lShaped->set_refine_weights(refineWeights);\n\n    // local refinement\n    auto locMeshRef = std::make_unique\n            <LocalMeshRefinement>(lShaped);\n\n    double h = 1/std::pow(2, lx);\n    locMeshRef->uniform(xMesh, h);\n    locMeshRef->local(xMesh, deg, h, bool_nonConforming);\n\n    std::string mesh_name;\n    if (bool_nonConforming) {\n        mesh_name = \"../meshes/lShaped/rg_nc/deg\"\n                +std::to_string(deg)+\"/mesh_l\"\n                +std::to_string(lx)+\".mesh\";\n    }\n    else {\n        mesh_name = \"../meshes/lShaped/rg_nc/deg\"\n                +std::to_string(deg)+\"/mesh_l\"\n                +std::to_string(lx)+\".mesh\";\n    }\n\n    std::cout << mesh_name << std::endl;\n\n    std::ofstream mesh_ofs(mesh_name.c_str());\n    mesh_ofs.precision(12);\n    xMesh->Print(mesh_ofs);\n    mesh_ofs.close();\n}\n\nint main(int argc, char *argv[])\n{   \n    // Read config json\n    auto config = get_global_config(argc, argv);\n    const std::string host = config[\"host\"];\n    const std::string run = config[\"run\"];\n    std::string base_mesh_dir;\n\n    // check if an initial mesh needs to be loaded\n    bool load_init_mesh = false;\n    if (config.contains(\"load_init_mesh\")) {\n        load_init_mesh = config[\"load_init_mesh\"];\n    }\n\n    if (load_init_mesh) {\n        base_mesh_dir.assign(\"../meshes/\");\n    } else {\n        if (host == \"local\") {\n            base_mesh_dir.assign(local_base_mesh_dir);\n        }\n        else if (host == \"cluster\") {\n            base_mesh_dir.assign(cluster_base_mesh_dir);\n        }\n    }\n\n    if (run == \"simulationFG\") {\n        run_waveFG(config, base_mesh_dir, load_init_mesh);\n    }\n    else if (run == \"simulationSG\") {\n        run_waveSG(config, base_mesh_dir, load_init_mesh);\n    }\n    else if (run == \"projectionFG\") {\n        run_waveProjFG\n                (config, base_mesh_dir, load_init_mesh);\n    }\n    else if (run == \"projectionSG\") {\n        run_waveProjSG\n                (config, base_mesh_dir, load_init_mesh);\n    }\n    else if (run == \"convergenceFG\") {\n        run_convergence_waveFG\n                (config, base_mesh_dir, load_init_mesh);\n    }\n    else if (run == \"convergenceSG\") {\n        run_convergence_waveSG\n                (config, base_mesh_dir, load_init_mesh);\n    }\n    else if (run == \"convergenceProjFG\") {\n        run_convergence_waveProjFG\n                (config, base_mesh_dir, load_init_mesh);\n    }\n    else if (run == \"convergenceProjSG\") {\n        run_convergence_waveProjSG\n                (config, base_mesh_dir, load_init_mesh);\n    }\n    else if (run == \"localMeshRefinement\") {\n        run_localMeshRefinement\n                (config, base_mesh_dir, load_init_mesh);\n    }\n\n    return 1;\n}\n\n\n// End of file\n", "meta": {"hexsha": "d5325adf4134a53ae114fc755015a3a39f6b6c5b", "size": 14108, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/waveO1.cpp", "max_stars_repo_name": "pratyuksh/FEMWave", "max_stars_repo_head_hexsha": "9ed0fbe0981d712ce3e531500381589b034fb9f0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-11-05T13:06:38.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-05T13:06:38.000Z", "max_issues_repo_path": "src/waveO1.cpp", "max_issues_repo_name": "pratyuksh/FEMWave", "max_issues_repo_head_hexsha": "9ed0fbe0981d712ce3e531500381589b034fb9f0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/waveO1.cpp", "max_forks_repo_name": "pratyuksh/FEMWave", "max_forks_repo_head_hexsha": "9ed0fbe0981d712ce3e531500381589b034fb9f0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-11-05T13:06:39.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-05T13:06:39.000Z", "avg_line_length": 33.1952941176, "max_line_length": 60, "alphanum_fraction": 0.5627303657, "num_tokens": 3673, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6224593312018546, "lm_q2_score": 0.5428632831725052, "lm_q1q2_score": 0.3379103161776006}}
{"text": "/* Author: Wolfgang Bangerth, University of Heidelberg, 2000 */\n\n/*    $Id: step-9.cc 28462 2013-02-19 15:25:50Z bangerth $       */\n/*                                                                */\n/*    Copyright (C) 2000-2004, 2006-2008, 2010-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// Just as in previous examples, we have to include several files of which the\n// meaning has already been discussed:\n#include <deal.II/base/quadrature_lib.h>\n#include <deal.II/base/function.h>\n#include <deal.II/base/logstream.h>\n#include <deal.II/lac/vector.h>\n#include <deal.II/lac/full_matrix.h>\n#include <deal.II/lac/sparse_matrix.h>\n#include <deal.II/lac/solver_bicgstab.h>\n#include <deal.II/lac/precondition.h>\n#include <deal.II/lac/constraint_matrix.h>\n#include <deal.II/grid/tria.h>\n#include <deal.II/grid/grid_generator.h>\n#include <deal.II/grid/grid_refinement.h>\n#include <deal.II/grid/tria_accessor.h>\n#include <deal.II/grid/tria_iterator.h>\n#include <deal.II/grid/tria_boundary_lib.h>\n#include <deal.II/dofs/dof_handler.h>\n#include <deal.II/dofs/dof_accessor.h>\n#include <deal.II/dofs/dof_tools.h>\n#include <deal.II/fe/fe_values.h>\n#include <deal.II/numerics/vector_tools.h>\n#include <deal.II/numerics/matrix_tools.h>\n#include <deal.II/numerics/data_out.h>\n#include <deal.II/fe/fe_q.h>\n#include <deal.II/grid/grid_out.h>\n\n// The following two files provide classes and information for multi-threaded\n// programs. In the first one, the classes and functions are declared which we\n// need to start new threads and to wait for threads to return (i.e. the\n// <code>Thread</code> class and the <code>new_thread</code> functions). The\n// second file has a class <code>MultithreadInfo</code> (and a global object\n// <code>multithread_info</code> of that type) which can be used to query the\n// number of processors in your system, which is often useful when deciding\n// how many threads to start in parallel.\n#include <deal.II/base/thread_management.h>\n#include <deal.II/base/multithread_info.h>\n\n// The next new include file declares a base class <code>TensorFunction</code>\n// not unlike the <code>Function</code> class, but with the difference that\n// the return value is tensor-valued rather than scalar of vector-valued.\n#include <deal.II/base/tensor_function.h>\n\n#include <deal.II/numerics/error_estimator.h>\n\n// This is C++, as we want to write some output to disk:\n#include <fstream>\n#include <iostream>\n\n\n// The last step is as in previous programs:\nnamespace Step9\n{\n  using namespace dealii;\n\n  // @sect3{AdvectionProblem class declaration}\n\n  // Following we declare the main class of this program. It is very much\n  // alike the main classes of previous examples, so we again only comment on\n  // the differences.\n  template <int dim>\n  class AdvectionProblem\n  {\n  public:\n    AdvectionProblem ();\n    ~AdvectionProblem ();\n    void run ();\n\n  private:\n    void setup_system ();\n    // The next function will be used to assemble the matrix. However, unlike\n    // in the previous examples, the function will not do the work itself, but\n    // rather it will split the range of active cells into several chunks and\n    // then call the following function on each of these chunks. The rationale\n    // is that matrix assembly can be parallelized quite well, as the\n    // computation of the local contributions on each cell is entirely\n    // independent of other cells, and we only have to synchronize when we add\n    // the contribution of a cell to the global matrix. The second function,\n    // doing the actual work, accepts two parameters which denote the first\n    // cell on which it shall operate, and the one past the last.\n    //\n    // The strategy for parallelization we choose here is one of the\n    // possibilities mentioned in detail in the @ref threads module in the\n    // documentation. While it is a straightforward way to distribute the work\n    // for assembling the system onto multiple processor cores. As mentioned\n    // in the module, there are other, and possibly better suited, ways to\n    // achieve the same goal.\n    void assemble_system ();\n    void assemble_system_interval (const typename DoFHandler<dim>::active_cell_iterator &begin,\n                                   const typename DoFHandler<dim>::active_cell_iterator &end);\n\n    // The following functions again are as in previous examples, as are the\n    // subsequent variables.\n    void solve ();\n    void refine_grid ();\n    void output_results (const unsigned int cycle) const;\n\n    Triangulation<dim>   triangulation;\n    DoFHandler<dim>      dof_handler;\n\n    FE_Q<dim>            fe;\n\n    ConstraintMatrix     hanging_node_constraints;\n\n    SparsityPattern      sparsity_pattern;\n    SparseMatrix<double> system_matrix;\n\n    Vector<double>       solution;\n    Vector<double>       system_rhs;\n\n    // When assembling the matrix in parallel, we have to synchronize when\n    // several threads attempt to write the local contributions of a cell to\n    // the global matrix at the same time. This is done using a\n    // <code>Mutex</code>, which is an object that can be owned by only one\n    // thread at a time. If a thread wants to write to the matrix, it has to\n    // acquire this lock (if it is presently owned by another thread, then it\n    // has to wait), then write to the matrix and finally release the\n    // lock. Note that if the library was not compiled to support\n    // multithreading (which you have to specify at the time you call the\n    // <code>./configure</code> script in the top-level directory), then\n    // the actual data type of the typedef\n    // <code>Threads::Mutex</code> is a dummy class that provides all the\n    // functions needed for a mutex, but does nothing when they are called;\n    // this is reasonable, of course, since if only one thread is running at a\n    // time, there is no need to synchronize with other threads.\n    Threads::Mutex     assembler_lock;\n  };\n\n\n\n  // @sect3{Equation data declaration}\n\n  // Next we declare a class that describes the advection field. This, of\n  // course, is a vector field with as many compents as there are space\n  // dimensions. One could now use a class derived from the\n  // <code>Function</code> base class, as we have done for boundary values and\n  // coefficients in previous examples, but there is another possibility in\n  // the library, namely a base class that describes tensor valued\n  // functions. In contrast to the usual <code>Function</code> objects, we\n  // provide the compiler with knowledge on the size of the objects of the\n  // return type. This enables the compiler to generate efficient code, which\n  // is not so simple for usual vector-valued functions where memory has to be\n  // allocated on the heap (thus, the <code>Function::vector_value</code>\n  // function has to be given the address of an object into which the result\n  // is to be written, in order to avoid copying and memory allocation and\n  // deallocation on the heap). In addition to the known size, it is possible\n  // not only to return vectors, but also tensors of higher rank; however,\n  // this is not very often requested by applications, to be honest...\n  //\n  // The interface of the <code>TensorFunction</code> class is relatively\n  // close to that of the <code>Function</code> class, so there is probably no\n  // need to comment in detail the following declaration:\n  template <int dim>\n  class AdvectionField : public TensorFunction<1,dim>\n  {\n  public:\n    AdvectionField () : TensorFunction<1,dim> () {}\n\n    virtual Tensor<1,dim> value (const Point<dim> &p) const;\n\n    virtual void value_list (const std::vector<Point<dim> > &points,\n                             std::vector<Tensor<1,dim> >    &values) const;\n\n    // In previous examples, we have used assertions that throw exceptions in\n    // several places. However, we have never seen how such exceptions are\n    // declared. This can be done as follows:\n    DeclException2 (ExcDimensionMismatch,\n                    unsigned int, unsigned int,\n                    << \"The vector has size \" << arg1 << \" but should have \"\n                    << arg2 << \" elements.\");\n    // The syntax may look a little strange, but is reasonable. The format is\n    // basically as follows: use the name of one of the macros\n    // <code>DeclExceptionN</code>, where <code>N</code> denotes the number of\n    // additional parameters which the exception object shall take. In this\n    // case, as we want to throw the exception when the sizes of two vectors\n    // differ, we need two arguments, so we use\n    // <code>DeclException2</code>. The first parameter then describes the\n    // name of the exception, while the following declare the data types of\n    // the parameters. The last argument is a sequence of output directives\n    // that will be piped into the <code>std::cerr</code> object, thus the\n    // strange format with the leading <code>@<@<</code> operator and the\n    // like. Note that we can access the parameters which are passed to the\n    // exception upon construction (i.e. within the <code>Assert</code> call)\n    // by using the names <code>arg1</code> through <code>argN</code>, where\n    // <code>N</code> is the number of arguments as defined by the use of the\n    // respective macro <code>DeclExceptionN</code>.\n    //\n    // To learn how the preprocessor expands this macro into actual code,\n    // please refer to the documentation of the exception classes in the base\n    // library. Suffice it to say that by this macro call, the respective\n    // exception class is declared, which also has error output functions\n    // already implemented.\n  };\n\n\n\n  // The following two functions implement the interface described above. The\n  // first simply implements the function as described in the introduction,\n  // while the second uses the same trick to avoid calling a virtual function\n  // as has already been introduced in the previous example program. Note the\n  // check for the right sizes of the arguments in the second function, which\n  // should always be present in such functions; it is our experience that\n  // many if not most programming errors result from incorrectly initialized\n  // arrays, incompatible parameters to functions and the like; using\n  // assertion as in this case can eliminate many of these problems.\n  template <int dim>\n  Tensor<1,dim>\n  AdvectionField<dim>::value (const Point<dim> &p) const\n  {\n    Point<dim> value;\n    value[0] = 2;\n    for (unsigned int i=1; i<dim; ++i)\n      value[i] = 1+0.8*std::sin(8*numbers::PI*p[0]);\n\n    return value;\n  }\n\n\n\n  template <int dim>\n  void\n  AdvectionField<dim>::value_list (const std::vector<Point<dim> > &points,\n                                   std::vector<Tensor<1,dim> >    &values) const\n  {\n    Assert (values.size() == points.size(),\n            ExcDimensionMismatch (values.size(), points.size()));\n\n    for (unsigned int i=0; i<points.size(); ++i)\n      values[i] = AdvectionField<dim>::value (points[i]);\n  }\n\n\n\n\n  // Besides the advection field, we need two functions describing the source\n  // terms (<code>right hand side</code>) and the boundary values. First for\n  // the right hand side, which follows the same pattern as in previous\n  // examples. As described in the introduction, the source is a constant\n  // function in the vicinity of a source point, which we denote by the\n  // constant static variable <code>center_point</code>. We set the values of\n  // this center using the same template tricks as we have shown in the step-7\n  // example program. The rest is simple and has been shown previously,\n  // including the way to avoid virtual function calls in the\n  // <code>value_list</code> function.\n  template <int dim>\n  class RightHandSide : public Function<dim>\n  {\n  public:\n    RightHandSide () : Function<dim>() {}\n\n    virtual double value (const Point<dim>   &p,\n                          const unsigned int  component = 0) const;\n\n    virtual void value_list (const std::vector<Point<dim> > &points,\n                             std::vector<double>            &values,\n                             const unsigned int              component = 0) const;\n\n  private:\n    static const Point<dim> center_point;\n  };\n\n\n  template <>\n  const Point<1> RightHandSide<1>::center_point = Point<1> (-0.75);\n\n  template <>\n  const Point<2> RightHandSide<2>::center_point = Point<2> (-0.75, -0.75);\n\n  template <>\n  const Point<3> RightHandSide<3>::center_point = Point<3> (-0.75, -0.75, -0.75);\n\n\n\n  // The only new thing here is that we check for the value of the\n  // <code>component</code> parameter. As this is a scalar function, it is\n  // obvious that it only makes sense if the desired component has the index\n  // zero, so we assert that this is indeed the\n  // case. <code>ExcIndexRange</code> is a global predefined exception\n  // (probably the one most often used, we therefore made it global instead of\n  // local to some class), that takes three parameters: the index that is\n  // outside the allowed range, the first element of the valid range and the\n  // one past the last (i.e. again the half-open interval so often used in the\n  // C++ standard library):\n  template <int dim>\n  double\n  RightHandSide<dim>::value (const Point<dim>   &p,\n                             const unsigned int  component) const\n  {\n    Assert (component == 0, ExcIndexRange (component, 0, 1));\n    const double diameter = 0.1;\n    return ( (p-center_point).square() < diameter*diameter ?\n             .1/std::pow(diameter,dim) :\n             0);\n  }\n\n\n\n  template <int dim>\n  void\n  RightHandSide<dim>::value_list (const std::vector<Point<dim> > &points,\n                                  std::vector<double>            &values,\n                                  const unsigned int              component) const\n  {\n    Assert (values.size() == points.size(),\n            ExcDimensionMismatch (values.size(), points.size()));\n\n    for (unsigned int i=0; i<points.size(); ++i)\n      values[i] = RightHandSide<dim>::value (points[i], component);\n  }\n\n\n\n  // Finally for the boundary values, which is just another class derived from\n  // the <code>Function</code> base class:\n  template <int dim>\n  class BoundaryValues : public Function<dim>\n  {\n  public:\n    BoundaryValues () : Function<dim>() {}\n\n    virtual double value (const Point<dim>   &p,\n                          const unsigned int  component = 0) const;\n\n    virtual void value_list (const std::vector<Point<dim> > &points,\n                             std::vector<double>            &values,\n                             const unsigned int              component = 0) const;\n  };\n\n\n\n  template <int dim>\n  double\n  BoundaryValues<dim>::value (const Point<dim>   &p,\n                              const unsigned int  component) const\n  {\n    Assert (component == 0, ExcIndexRange (component, 0, 1));\n\n    const double sine_term = std::sin(16*numbers::PI*std::sqrt(p.square()));\n    const double weight    = std::exp(-5*p.square()) / std::exp(-5.);\n    return sine_term * weight;\n  }\n\n\n\n  template <int dim>\n  void\n  BoundaryValues<dim>::value_list (const std::vector<Point<dim> > &points,\n                                   std::vector<double>            &values,\n                                   const unsigned int              component) const\n  {\n    Assert (values.size() == points.size(),\n            ExcDimensionMismatch (values.size(), points.size()));\n\n    for (unsigned int i=0; i<points.size(); ++i)\n      values[i] = BoundaryValues<dim>::value (points[i], component);\n  }\n\n\n\n  // @sect3{GradientEstimation class declaration}\n\n  // Now, finally, here comes the class that will compute the difference\n  // approximation of the gradient on each cell and weighs that with a power\n  // of the mesh size, as described in the introduction.  This class is a\n  // simple version of the <code>DerivativeApproximation</code> class in the\n  // library, that uses similar techniques to obtain finite difference\n  // approximations of the gradient of a finite element field, or if higher\n  // derivatives.\n  //\n  // The class has one public static function <code>estimate</code> that is\n  // called to compute a vector of error indicators, and one private function\n  // that does the actual work on an interval of all active cells. The latter\n  // is called by the first one in order to be able to do the computations in\n  // parallel if your computer has more than one processor. While the first\n  // function accepts as parameter a vector into which the error indicator is\n  // written for each cell. This vector is passed on to the second function\n  // that actually computes the error indicators on some cells, and the\n  // respective elements of the vector are written. By the way, we made it\n  // somewhat of a convention to use vectors of floats for error indicators\n  // rather than the common vectors of doubles, as the additional accuracy is\n  // not necessary for estimated values.\n  //\n  // In addition to these two functions, the class declares to exceptions\n  // which are raised when a cell has no neighbors in each of the space\n  // directions (in which case the matrix described in the introduction would\n  // be singular and can't be inverted), while the other one is used in the\n  // more common case of invalid parameters to a function, namely a vector of\n  // wrong size.\n  //\n  // Two annotations to this class are still in order: the first is that the\n  // class has no non-static member functions or variables, so this is not\n  // really a class, but rather serves the purpose of a <code>namespace</code>\n  // in C++. The reason that we chose a class over a namespace is that this\n  // way we can declare functions that are private, i.e. visible to the\n  // outside world but not callable. This can be done with namespaces as well,\n  // if one declares some functions in header files in the namespace and\n  // implements these and other functions in the implementation file. The\n  // functions not declared in the header file are still in the namespace but\n  // are not callable from outside. However, as we have only one file here, it\n  // is not possible to hide functions in the present case.\n  //\n  // The second is that the dimension template parameter is attached to the\n  // function rather than to the class itself. This way, you don't have to\n  // specify the template parameter yourself as in most other cases, but the\n  // compiler can figure its value out itself from the dimension of the DoF\n  // handler object that one passes as first argument.\n  //\n  // Finally note that the <code>IndexInterval</code> typedef is introduced as\n  // a convenient abbreviation for an otherwise lengthy type name.\n  class GradientEstimation\n  {\n  public:\n    template <int dim>\n    static void estimate (const DoFHandler<dim> &dof,\n                          const Vector<double> &solution,\n                          Vector<float>         &error_per_cell);\n\n    DeclException2 (ExcInvalidVectorLength,\n                    int, int,\n                    << \"Vector has length \" << arg1 << \", but should have \"\n                    << arg2);\n    DeclException0 (ExcInsufficientDirections);\n\n  private:\n    typedef std::pair<unsigned int,unsigned int> IndexInterval;\n\n    template <int dim>\n    static void estimate_interval (const DoFHandler<dim> &dof,\n                                   const Vector<double> &solution,\n                                   const IndexInterval   &index_interval,\n                                   Vector<float>         &error_per_cell);\n  };\n\n\n\n  // @sect3{AdvectionProblem class implementation}\n\n\n  // Now for the implementation of the main class. Constructor, destructor and\n  // the function <code>setup_system</code> follow the same pattern that was\n  // used previously, so we need not comment on these three function:\n  template <int dim>\n  AdvectionProblem<dim>::AdvectionProblem () :\n    dof_handler (triangulation),\n    fe(1)\n  {}\n\n\n\n  template <int dim>\n  AdvectionProblem<dim>::~AdvectionProblem ()\n  {\n    dof_handler.clear ();\n  }\n\n\n\n  template <int dim>\n  void AdvectionProblem<dim>::setup_system ()\n  {\n    dof_handler.distribute_dofs (fe);\n\n    hanging_node_constraints.clear ();\n    DoFTools::make_hanging_node_constraints (dof_handler,\n                                             hanging_node_constraints);\n    hanging_node_constraints.close ();\n\n    sparsity_pattern.reinit (dof_handler.n_dofs(),\n                             dof_handler.n_dofs(),\n                             dof_handler.max_couplings_between_dofs());\n    DoFTools::make_sparsity_pattern (dof_handler, sparsity_pattern);\n\n    hanging_node_constraints.condense (sparsity_pattern);\n\n    sparsity_pattern.compress();\n\n    system_matrix.reinit (sparsity_pattern);\n\n    solution.reinit (dof_handler.n_dofs());\n    system_rhs.reinit (dof_handler.n_dofs());\n  }\n\n\n\n  // In the following function, the matrix and right hand side are\n  // assembled. As stated in the documentation of the main class above, it\n  // does not do this itself, but rather delegates to the function following\n  // next, by splitting up the range of cells into chunks of approximately the\n  // same size and assembling on each of these chunks in parallel.\n  template <int dim>\n  void AdvectionProblem<dim>::assemble_system ()\n  {\n    // First, we want to find out how many threads shall assemble the matrix\n    // in parallel. A reasonable choice would be that each processor in your\n    // system processes one chunk of cells; if we were to use this\n    // information, we could use the value of the global variable\n    // <code>multithread_info.n_cpus</code>, which is determined at start-up\n    // time of your program automatically. (Note that if the library was not\n    // configured for multi-threading, then the number of CPUs is set to one.)\n    // However, sometimes there might be reasons to use another value. For\n    // example, you might want to use less processors than there are in your\n    // system in order not to use too many computational ressources. On the\n    // other hand, if there are several jobs running on a computer and you\n    // want to get a higher percentage of CPU time, it might be worth to start\n    // more threads than there are CPUs, as most operating systems assign\n    // roughly the same CPU ressources to all threads presently running. For\n    // this reason, the <code>MultithreadInfo</code> class contains a\n    // read-write variable <code>n_default_threads</code> which is set to\n    // <code>n_cpus</code> by default, but can be set to another value. This\n    // variable is also queried by functions inside the library to determine\n    // how many threads they shall create.\n    const unsigned int n_threads = multithread_info.n_default_threads;\n    // It is worth noting, however, that this setup determines the load\n    // distribution onto processor in a static way: it does not take into\n    // account that some other part of our program may also be running\n    // something in parallel at the same time as we get here (this is not the\n    // case in the current program, but may easily be the case in more complex\n    // applications). A discussion of how to deal with this case can be found\n    // in the @ref threads module.\n    //\n    // Next, we need an object which is capable of keeping track of the\n    // threads we created, and allows us to wait until they all have finished\n    // (to <code>join</code> them in the language of threads). The\n    // Threads::ThreadGroup class does this, which is basically just a\n    // container for objects of type Threads::Thread that represent a single\n    // thread; Threads::Thread is what the Threads::new_thread function below\n    // will return when we start a new thread.\n    //\n    // Note that both Threads::ThreadGroup and Threads::Thread have a template\n    // argument that represents the return type of the function being called\n    // on a separate thread. Since most of the functions that we will call on\n    // different threads have return type <code>void</code>, the template\n    // argument has a default value <code>void</code>, so that in that case it\n    // can be omitted. (However, you still need to write the angle brackets,\n    // even if they are empty.)\n    //\n    // If you did not configure for multi-threading, then the\n    // <code>new_thread</code> function that is supposed to start a new thread\n    // in parallel only executes the function which should be run in parallel,\n    // waits for it to return (i.e. the function is executed sequentially),\n    // and puts the return value into the <code>Thread</code>\n    // object. Likewise, the function <code>join</code> that is supposed to\n    // wait for all spawned threads to return, returns immediately, as there\n    // can't be any threads running.\n    Threads::ThreadGroup<> threads;\n\n    // Now we have to split the range of cells into chunks of approximately\n    // the same size. Each thread will then assemble the local contributions\n    // of the cells within its chunk and transfer these contributions to the\n    // global matrix. As splitting a range of cells is a rather common task\n    // when using multi-threading, there is a function in the\n    // <code>Threads</code> namespace that does exactly this. In fact, it does\n    // this not only for a range of cell iterators, but for iterators in\n    // general, so you could use it for <code>std::vector::iterator</code> or\n    // usual pointers as well.\n    //\n    // The function returns a vector of pairs of iterators, where the first\n    // denotes the first cell of each chunk, while the second denotes the one\n    // past the last (this half-open interval is the usual convention in the\n    // C++ standard library, so we keep to it). Note that we have to specify\n    // the actual data type of the iterators in angle brackets to the\n    // function. This is necessary, since it is a template function which\n    // takes the data type of the iterators as template argument; in the\n    // present case, however, the data types of the two first parameters\n    // differ (<code>begin_active</code> returns an\n    // <code>active_iterator</code>, while <code>end</code> returns a\n    // <code>raw_iterator</code>), and in this case the C++ language requires\n    // us to specify the template type explicitely. For brevity, we first\n    // typedef this data type to an alias.\n    typedef typename DoFHandler<dim>::active_cell_iterator active_cell_iterator;\n    std::vector<std::pair<active_cell_iterator,active_cell_iterator> >\n    thread_ranges\n      = Threads::split_range<active_cell_iterator> (dof_handler.begin_active (),\n                                                    dof_handler.end (),\n                                                    n_threads);\n\n    // Finally, for each of the chunks of iterators we have computed, start\n    // one thread (or if not in multi-thread mode: execute assembly on these\n    // chunks sequentially). This is done using the following sequence of\n    // function calls:\n    for (unsigned int thread=0; thread<n_threads; ++thread)\n      threads += Threads::new_thread (&AdvectionProblem<dim>::assemble_system_interval,\n                                      *this,\n                                      thread_ranges[thread].first,\n                                      thread_ranges[thread].second);\n    // The reasons and internal workings of these functions can be found in\n    // the report on the subject of multi-threading, which is available online\n    // as well. Suffice it to say that we create a new thread that calls the\n    // <code>assemble_system_interval</code> function on the present object\n    // (the <code>this</code> pointer), with the arguments following in the\n    // second set of parentheses passed as parameters. The Threads::new_thread\n    // function returns an object of type Threads::Thread, which we put into\n    // the <code>threads</code> container. If a thread exits, the return value\n    // of the function being called is put into a place such that the thread\n    // objects can access it using their <code>return_value</code> function;\n    // since the function we call doesn't have a return value, this does not\n    // apply here. Note that you can copy around thread objects freely, and\n    // that of course they will still represent the same thread.\n\n    // When all the threads are running, the only thing we have to do is wait\n    // for them to finish. This is necessary of course, as we can't proceed\n    // with our tasks before the matrix and right hand side are\n    // assemblesd. Waiting for all the threads to finish can be done using the\n    // <code>joint_all</code> function in the <code>ThreadGroup</code>\n    // container, which just calls <code>join</code> on each of the thread\n    // objects it stores.\n    //\n    // Again, if the library was not configured to use multi-threading, then\n    // no threads can run in parallel and the function returns immediately.\n    threads.join_all ();\n\n\n    // After the matrix has been assembled in parallel, we stil have to\n    // eliminate hanging node constraints. This is something that can't be\n    // done on each of the threads separately, so we have to do it now.\n    hanging_node_constraints.condense (system_matrix);\n    hanging_node_constraints.condense (system_rhs);\n    // Note also, that unlike in previous examples, there are no boundary\n    // conditions to be applied to the system of equations. This, of course,\n    // is due to the fact that we have included them into the weak formulation\n    // of the problem.\n  }\n\n\n\n  // Now, this is the function that does the actual work. It is not very\n  // different from the <code>assemble_system</code> functions of previous\n  // example programs, so we will again only comment on the differences. The\n  // mathematical stuff follows closely what we have said in the introduction.\n  template <int dim>\n  void\n  AdvectionProblem<dim>::\n  assemble_system_interval (const typename DoFHandler<dim>::active_cell_iterator &begin,\n                            const typename DoFHandler<dim>::active_cell_iterator &end)\n  {\n    // First of all, we will need some objects that describe boundary values,\n    // right hand side function and the advection field. As we will only\n    // perform actions on these objects that do not change them, we declare\n    // them as constant, which can enable the compiler in some cases to\n    // perform additional optimizations.\n    const AdvectionField<dim> advection_field;\n    const RightHandSide<dim>  right_hand_side;\n    const BoundaryValues<dim> boundary_values;\n\n    // Next we need quadrature formula for the cell terms, but also for the\n    // integral over the inflow boundary, which will be a face integral. As we\n    // use bilinear elements, Gauss formulae with two points in each space\n    // direction are sufficient.\n    QGauss<dim>   quadrature_formula(2);\n    QGauss<dim-1> face_quadrature_formula(2);\n\n    // Finally, we need objects of type <code>FEValues</code> and\n    // <code>FEFaceValues</code>. For the cell terms we need the values and\n    // gradients of the shape functions, the quadrature points in order to\n    // determine the source density and the advection field at a given point,\n    // and the weights of the quadrature points times the determinant of the\n    // Jacobian at these points. In contrast, for the boundary integrals, we\n    // don't need the gradients, but rather the normal vectors to the cells.\n    FEValues<dim> fe_values (fe, quadrature_formula,\n                             update_values   | update_gradients |\n                             update_quadrature_points | update_JxW_values);\n    FEFaceValues<dim> fe_face_values (fe, face_quadrature_formula,\n                                      update_values     | update_quadrature_points   |\n                                      update_JxW_values | update_normal_vectors);\n\n    // Then we define some abbreviations to avoid unnecessarily long lines:\n    const unsigned int   dofs_per_cell   = fe.dofs_per_cell;\n    const unsigned int   n_q_points      = quadrature_formula.size();\n    const unsigned int   n_face_q_points = face_quadrature_formula.size();\n\n    // We declare cell matrix and cell right hand side...\n    FullMatrix<double>   cell_matrix (dofs_per_cell, dofs_per_cell);\n    Vector<double>       cell_rhs (dofs_per_cell);\n\n    // ... an array to hold the global indices of the degrees of freedom of\n    // the cell on which we are presently working...\n    std::vector<unsigned int> local_dof_indices (dofs_per_cell);\n\n    // ... and array in which the values of right hand side, advection\n    // direction, and boundary values will be stored, for cell and face\n    // integrals respectively:\n    std::vector<double>         rhs_values (n_q_points);\n    std::vector<Tensor<1,dim> > advection_directions (n_q_points);\n    std::vector<double>         face_boundary_values (n_face_q_points);\n    std::vector<Tensor<1,dim> > face_advection_directions (n_face_q_points);\n\n    // Then we start the main loop over the cells:\n    typename DoFHandler<dim>::active_cell_iterator cell;\n    for (cell=begin; cell!=end; ++cell)\n      {\n        // First clear old contents of the cell contributions...\n        cell_matrix = 0;\n        cell_rhs = 0;\n\n        // ... then initialize the <code>FEValues</code> object...\n        fe_values.reinit (cell);\n\n        // ... obtain the values of right hand side and advection directions\n        // at the quadrature points...\n        advection_field.value_list (fe_values.get_quadrature_points(),\n                                    advection_directions);\n        right_hand_side.value_list (fe_values.get_quadrature_points(),\n                                    rhs_values);\n\n        // ... set the value of the streamline diffusion parameter as\n        // described in the introduction...\n        const double delta = 0.1 * cell->diameter ();\n\n        // ... and assemble the local contributions to the system matrix and\n        // right hand side as also discussed above:\n        for (unsigned int q_point=0; q_point<n_q_points; ++q_point)\n          for (unsigned int i=0; i<dofs_per_cell; ++i)\n            {\n              for (unsigned int j=0; j<dofs_per_cell; ++j)\n                cell_matrix(i,j) += ((advection_directions[q_point] *\n                                      fe_values.shape_grad(j,q_point)   *\n                                      (fe_values.shape_value(i,q_point) +\n                                       delta *\n                                       (advection_directions[q_point] *\n                                        fe_values.shape_grad(i,q_point)))) *\n                                     fe_values.JxW(q_point));\n\n              cell_rhs(i) += ((fe_values.shape_value(i,q_point) +\n                               delta *\n                               (advection_directions[q_point] *\n                                fe_values.shape_grad(i,q_point))        ) *\n                              rhs_values[q_point] *\n                              fe_values.JxW (q_point));\n            };\n\n        // Besides the cell terms which we have build up now, the bilinear\n        // form of the present problem also contains terms on the boundary of\n        // the domain. Therefore, we have to check whether any of the faces of\n        // this cell are on the boundary of the domain, and if so assemble the\n        // contributions of this face as well. Of course, the bilinear form\n        // only contains contributions from the <code>inflow</code> part of\n        // the boundary, but to find out whether a certain part of a face of\n        // the present cell is part of the inflow boundary, we have to have\n        // information on the exact location of the quadrature points and on\n        // the direction of flow at this point; we obtain this information\n        // using the FEFaceValues object and only decide within the main loop\n        // whether a quadrature point is on the inflow boundary.\n        for (unsigned int face=0; face<GeometryInfo<dim>::faces_per_cell; ++face)\n          if (cell->face(face)->at_boundary())\n            {\n              // Ok, this face of the present cell is on the boundary of the\n              // domain. Just as for the usual FEValues object which we have\n              // used in previous examples and also above, we have to\n              // reinitialize the FEFaceValues object for the present face:\n              fe_face_values.reinit (cell, face);\n\n              // For the quadrature points at hand, we ask for the values of\n              // the inflow function and for the direction of flow:\n              boundary_values.value_list (fe_face_values.get_quadrature_points(),\n                                          face_boundary_values);\n              advection_field.value_list (fe_face_values.get_quadrature_points(),\n                                          face_advection_directions);\n\n              // Now loop over all quadrature points and see whether it is on\n              // the inflow or outflow part of the boundary. This is\n              // determined by a test whether the advection direction points\n              // inwards or outwards of the domain (note that the normal\n              // vector points outwards of the cell, and since the cell is at\n              // the boundary, the normal vector points outward of the domain,\n              // so if the advection direction points into the domain, its\n              // scalar product with the normal vector must be negative):\n              for (unsigned int q_point=0; q_point<n_face_q_points; ++q_point)\n                if (fe_face_values.normal_vector(q_point) *\n                    face_advection_directions[q_point]\n                    < 0)\n                  // If the is part of the inflow boundary, then compute the\n                  // contributions of this face to the global matrix and right\n                  // hand side, using the values obtained from the\n                  // FEFaceValues object and the formulae discussed in the\n                  // introduction:\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) -= (face_advection_directions[q_point] *\n                                             fe_face_values.normal_vector(q_point) *\n                                             fe_face_values.shape_value(i,q_point) *\n                                             fe_face_values.shape_value(j,q_point) *\n                                             fe_face_values.JxW(q_point));\n\n                      cell_rhs(i) -= (face_advection_directions[q_point] *\n                                      fe_face_values.normal_vector(q_point) *\n                                      face_boundary_values[q_point]         *\n                                      fe_face_values.shape_value(i,q_point) *\n                                      fe_face_values.JxW(q_point));\n                    };\n            };\n\n\n        // Now go on by transferring the local contributions to the system of\n        // equations into the global objects. The first step was to obtain the\n        // global indices of the degrees of freedom on this cell.\n        cell->get_dof_indices (local_dof_indices);\n\n        // Up until now we have not taken care of the fact that this function\n        // might run more than once in parallel, as the operations above only\n        // work on variables that are local to this function, or if they are\n        // global (such as the information on the grid, the DoF handler, or\n        // the DoF numbers) they are only read. Thus, the different threads do\n        // not disturb each other.\n        //\n        // On the other hand, we would now like to write the local\n        // contributions to the global system of equations into the global\n        // objects. This needs some kind of synchronisation, as if we would\n        // not take care of the fact that multiple threads write into the\n        // matrix at the same time, we might be surprised that one threads\n        // reads data from the matrix that another thread is presently\n        // overwriting, or similar things. Thus, to make sure that only one\n        // thread operates on these objects at a time, we have to lock\n        // it. This is done using a <code>Mutex</code>, which is short for\n        // <code>mutually exclusive</code>: a thread that wants to write to\n        // the global objects acquires this lock, but has to wait if it is\n        // presently owned by another thread. If it has acquired the lock, it\n        // can be sure that no other thread is presently writing to the\n        // matrix, and can do so freely. When finished, we release the lock\n        // again so as to allow other threads to acquire it and write to the\n        // matrix.\n        assembler_lock.acquire ();\n        for (unsigned int i=0; i<dofs_per_cell; ++i)\n          {\n            for (unsigned int j=0; j<dofs_per_cell; ++j)\n              system_matrix.add (local_dof_indices[i],\n                                 local_dof_indices[j],\n                                 cell_matrix(i,j));\n\n            system_rhs(local_dof_indices[i]) += cell_rhs(i);\n          };\n        assembler_lock.release ();\n        // At this point, the locked operations on the global matrix are done,\n        // i.e. other threads can now enter into the protected section by\n        // acquiring the lock. Two final notes are in place here, however:\n        //\n        // 1. If the library was not configured for multi-threading, then\n        // there can't be parallel threads and there is no need to\n        // synchronize. Thus, the <code>lock</code> and <code>release</code>\n        // functions are no-ops, i.e. they return without doing anything.\n        //\n        // 2. In order to work properly, it is essential that all threads try\n        // to acquire the same lock. This, of course, can not be achieved if\n        // the lock is a local variable, as then each thread would acquire its\n        // own lock. Therefore, the lock variable is a member variable of the\n        // class; since all threads execute member functions of the same\n        // object, they have the same <code>this</code> pointer and therefore\n        // also operate on the same <code>lock</code>.\n      };\n  }\n\n\n\n  // Following is the function that solves the linear system of equations. As\n  // the system is no more symmetric positive definite as in all the previous\n  // examples, we can't use the Conjugate Gradients method anymore. Rather, we\n  // use a solver that is tailored to nonsymmetric systems like the one at\n  // hand, the BiCGStab method. As preconditioner, we use the Jacobi method.\n  template <int dim>\n  void AdvectionProblem<dim>::solve ()\n  {\n    SolverControl           solver_control (1000, 1e-12);\n    SolverBicgstab<>        bicgstab (solver_control);\n\n    PreconditionJacobi<> preconditioner;\n    preconditioner.initialize(system_matrix, 1.0);\n\n    bicgstab.solve (system_matrix, solution, system_rhs,\n                    preconditioner);\n\n    hanging_node_constraints.distribute (solution);\n  }\n\n\n  // The following function refines the grid according to the quantity\n  // described in the introduction. The respective computations are made in\n  // the class <code>GradientEstimation</code>. The only difference to\n  // previous examples is that we refine a little more aggressively (0.5\n  // instead of 0.3 of the number of cells).\n  template <int dim>\n  void AdvectionProblem<dim>::refine_grid ()\n  {\n    Vector<float> estimated_error_per_cell (triangulation.n_active_cells());\n\n    GradientEstimation::estimate (dof_handler,\n                                  solution,\n                                  estimated_error_per_cell);\n\n    GridRefinement::refine_and_coarsen_fixed_number (triangulation,\n                                                     estimated_error_per_cell,\n                                                     0.5, 0.03);\n\n    triangulation.execute_coarsening_and_refinement ();\n  }\n\n\n\n  // Writing output to disk is done in the same way as in the previous\n  // examples...\n  template <int dim>\n  void AdvectionProblem<dim>::output_results (const unsigned int cycle) const\n  {\n    std::string filename = \"grid-\";\n    filename += ('0' + cycle);\n    Assert (cycle < 10, ExcInternalError());\n\n    filename += \".eps\";\n    std::ofstream output (filename.c_str());\n\n    GridOut grid_out;\n    grid_out.write_eps (triangulation, output);\n  }\n\n\n  // ... as is the main loop (setup -- solve -- refine)\n  template <int dim>\n  void AdvectionProblem<dim>::run ()\n  {\n    for (unsigned int cycle=0; cycle<6; ++cycle)\n      {\n        std::cout << \"Cycle \" << cycle << ':' << std::endl;\n\n        if (cycle == 0)\n          {\n            GridGenerator::hyper_cube (triangulation, -1, 1);\n            triangulation.refine_global (4);\n          }\n        else\n          {\n            refine_grid ();\n          };\n\n\n        std::cout << \"   Number of active cells:       \"\n                  << triangulation.n_active_cells()\n                  << std::endl;\n\n        setup_system ();\n\n        std::cout << \"   Number of degrees of freedom: \"\n                  << dof_handler.n_dofs()\n                  << std::endl;\n\n        assemble_system ();\n        solve ();\n        output_results (cycle);\n      };\n\n    DataOut<dim> data_out;\n    data_out.attach_dof_handler (dof_handler);\n    data_out.add_data_vector (solution, \"solution\");\n    data_out.build_patches ();\n\n    std::ofstream output (\"final-solution.gmv\");\n    data_out.write_gmv (output);\n  }\n\n\n\n  // @sect3{GradientEstimation class implementation}\n\n  // Now for the implementation of the <code>GradientEstimation</code>\n  // class. The first function does not much except for delegating work to the\n  // other function:\n  template <int dim>\n  void\n  GradientEstimation::estimate (const DoFHandler<dim> &dof_handler,\n                                const Vector<double> &solution,\n                                Vector<float>         &error_per_cell)\n  {\n    // Before starting with the work, we check that the vector into which the\n    // results are written, has the right size. It is a common error that such\n    // parameters have the wrong size, but the resulting damage by not\n    // catching these errors are very subtle as they are usually corruption of\n    // data somewhere in memory. Often, the problems emerging from this are\n    // not reproducible, and we found that it is well worth the effort to\n    // check for such things.\n    Assert (error_per_cell.size() == dof_handler.get_tria().n_active_cells(),\n            ExcInvalidVectorLength (error_per_cell.size(),\n                                    dof_handler.get_tria().n_active_cells()));\n\n    // Next, we subdivide the range of cells into chunks of equal size. Just\n    // as we have used the function <code>Threads::split_range</code> when\n    // assembling above, there is a function that computes intervals of\n    // roughly equal size from a larger interval. This is used here:\n    const unsigned int n_threads = multithread_info.n_default_threads;\n    std::vector<IndexInterval> index_intervals\n      = Threads::split_interval (0, dof_handler.get_tria().n_active_cells(),\n                                 n_threads);\n\n    // In the same way as before, we use a <code>Threads::ThreadGroup</code>\n    // object to collect the descriptor objects of different threads. Note\n    // that as the function called is not a member function, but rather a\n    // static function, we need not (and can not) pass a <code>this</code>\n    // pointer to the <code>new_thread</code> function in this case.\n    //\n    // Taking pointers to templated functions seems to be notoriously\n    // difficult for many compilers (since there are several functions with\n    // the same name -- just as with overloaded functions). It therefore\n    // happens quite frequently that we can't directly insert taking the\n    // address of a function in the call to <code>encapsulate</code> for one\n    // or the other compiler, but have to take a temporary variable for that\n    // purpose. Here, in this case, Compaq's <code>cxx</code> compiler choked\n    // on the code so we use this workaround with the function pointer:\n    Threads::ThreadGroup<> threads;\n    void (*estimate_interval_ptr) (const DoFHandler<dim> &,\n                                   const Vector<double> &,\n                                   const IndexInterval &,\n                                   Vector<float> &)\n      = &GradientEstimation::template estimate_interval<dim>;\n    for (unsigned int i=0; i<n_threads; ++i)\n      threads += Threads::new_thread (estimate_interval_ptr,\n                                      dof_handler, solution,\n                                      index_intervals[i],\n                                      error_per_cell);\n    // Ok, now the threads are at work, and we only have to wait for them to\n    // finish their work:\n    threads.join_all ();\n    // Note that if the value of the variable\n    // <code>multithread_info.n_default_threads</code> was one, or if the\n    // library was not configured to use threads, then the sequence of\n    // commands above reduced to a complicated way to simply call the\n    // <code>estimate_interval</code> function with the whole range of cells\n    // to work on. However, using the way above, we are able to write the\n    // program such that it makes no difference whether we presently work with\n    // multiple threads or in single-threaded mode, thus eliminating the need\n    // to write code included in conditional preprocessor sections.\n  }\n\n\n  // Following now the function that actually computes the finite difference\n  // approximation to the gradient. The general outline of the function is to\n  // loop over all the cells in the range of iterators designated by the third\n  // argument, and on each cell first compute the list of active neighbors of\n  // the present cell and then compute the quantities described in the\n  // introduction for each of the neighbors. The reason for this order is that\n  // it is not a one-liner to find a given neighbor with locally refined\n  // meshes. In principle, an optimized implementation would find neighbors\n  // and the quantities depending on them in one step, rather than first\n  // building a list of neighbors and in a second step their contributions.\n  //\n  // Now for the details:\n  template <int dim>\n  void\n  GradientEstimation::estimate_interval (const DoFHandler<dim> &dof_handler,\n                                         const Vector<double> &solution,\n                                         const IndexInterval   &index_interval,\n                                         Vector<float>         &error_per_cell)\n  {\n    // First we need a way to extract the values of the given finite element\n    // function at the center of the cells. As usual with values of finite\n    // element functions, we use an object of type <code>FEValues</code>, and\n    // we use (or mis-use in this case) the midpoint quadrature rule to get at\n    // the values at the center. Note that the <code>FEValues</code> object\n    // only needs to compute the values at the centers, and the location of\n    // the quadrature points in real space in order to get at the vectors\n    // <code>y</code>.\n    QMidpoint<dim> midpoint_rule;\n    FEValues<dim>  fe_midpoint_value (dof_handler.get_fe(),\n                                      midpoint_rule,\n                                      update_values | update_quadrature_points);\n\n    // Then we need space foe the tensor <code>Y</code>, which is the sum of\n    // outer products of the y-vectors.\n    Tensor<2,dim> Y;\n\n    // Then define iterators into the cells and into the output vector, which\n    // are to be looped over by the present instance of this function. We get\n    // start and end iterators over cells by setting them to the first active\n    // cell and advancing them using the given start and end index. Note that\n    // we can use the <code>advance</code> function of the standard C++\n    // library, but that we have to cast the distance by which the iterator is\n    // to be moved forward to a signed quantity in order to avoid warnings by\n    // the compiler.\n    typename DoFHandler<dim>::active_cell_iterator cell, endc;\n\n    cell = dof_handler.begin_active();\n    advance (cell, static_cast<signed int>(index_interval.first));\n\n    endc = dof_handler.begin_active();\n    advance (endc, static_cast<signed int>(index_interval.second));\n\n    // Getting an iterator into the output array is simpler. We don't need an\n    // end iterator, as we always move this iterator forward by one element\n    // for each cell we are on, but stop the loop when we hit the end cell, so\n    // we need not have an end element for this iterator.\n    Vector<float>::iterator\n    error_on_this_cell = error_per_cell.begin() + index_interval.first;\n\n\n    // Then we allocate a vector to hold iterators to all active neighbors of\n    // a cell. We reserve the maximal number of active neighbors in order to\n    // avoid later reallocations. Note how this maximal number of active\n    // neighbors is computed here.\n    std::vector<typename DoFHandler<dim>::active_cell_iterator> active_neighbors;\n    active_neighbors.reserve (GeometryInfo<dim>::faces_per_cell *\n                              GeometryInfo<dim>::max_children_per_face);\n\n    // Well then, after all these preliminaries, lets start the computations:\n    for (; cell!=endc; ++cell, ++error_on_this_cell)\n      {\n        // First initialize the <code>FEValues</code> object, as well as the\n        // <code>Y</code> tensor:\n        fe_midpoint_value.reinit (cell);\n        Y.clear ();\n\n        // Then allocate the vector that will be the sum over the y-vectors\n        // times the approximate directional derivative:\n        Tensor<1,dim> projected_gradient;\n\n\n        // Now before going on first compute a list of all active neighbors of\n        // the present cell. We do so by first looping over all faces and see\n        // whether the neighbor there is active, which would be the case if it\n        // is on the same level as the present cell or one level coarser (note\n        // that a neighbor can only be once coarser than the present cell, as\n        // we only allow a maximal difference of one refinement over a face in\n        // deal.II). Alternatively, the neighbor could be on the same level\n        // and be further refined; then we have to find which of its children\n        // are next to the present cell and select these (note that if a child\n        // of of neighbor of an active cell that is next to this active cell,\n        // needs necessarily be active itself, due to the one-refinement rule\n        // cited above).\n        //\n        // Things are slightly different in one space dimension, as there the\n        // one-refinement rule does not exist: neighboring active cells may\n        // differ in as many refinement levels as they like. In this case, the\n        // computation becomes a little more difficult, but we will explain\n        // this below.\n        //\n        // Before starting the loop over all neighbors of the present cell, we\n        // have to clear the array storing the iterators to the active\n        // neighbors, of course.\n        active_neighbors.clear ();\n        for (unsigned int face_no=0; face_no<GeometryInfo<dim>::faces_per_cell; ++face_no)\n          if (! cell->at_boundary(face_no))\n            {\n              // First define an abbreviation for the iterator to the face and\n              // the neighbor\n              const typename DoFHandler<dim>::face_iterator\n              face = cell->face(face_no);\n              const typename DoFHandler<dim>::cell_iterator\n              neighbor = cell->neighbor(face_no);\n\n              // Then check whether the neighbor is active. If it is, then it\n              // is on the same level or one level coarser (if we are not in\n              // 1D), and we are interested in it in any case.\n              if (neighbor->active())\n                active_neighbors.push_back (neighbor);\n              else\n                {\n                  // If the neighbor is not active, then check its children.\n                  if (dim == 1)\n                    {\n                      // To find the child of the neighbor which bounds to the\n                      // present cell, successively go to its right child if\n                      // we are left of the present cell (n==0), or go to the\n                      // left child if we are on the right (n==1), until we\n                      // find an active cell.\n                      typename DoFHandler<dim>::cell_iterator\n                      neighbor_child = neighbor;\n                      while (neighbor_child->has_children())\n                        neighbor_child = neighbor_child->child (face_no==0 ? 1 : 0);\n\n                      // As this used some non-trivial geometrical intuition,\n                      // we might want to check whether we did it right,\n                      // i.e. check whether the neighbor of the cell we found\n                      // is indeed the cell we are presently working\n                      // on. Checks like this are often useful and have\n                      // frequently uncovered errors both in algorithms like\n                      // the line above (where it is simple to involuntarily\n                      // exchange <code>n==1</code> for <code>n==0</code> or\n                      // the like) and in the library (the assumptions\n                      // underlying the algorithm above could either be wrong,\n                      // wrongly documented, or are violated due to an error\n                      // in the library). One could in principle remove such\n                      // checks after the program works for some time, but it\n                      // might be a good things to leave it in anyway to check\n                      // for changes in the library or in the algorithm above.\n                      //\n                      // Note that if this check fails, then this is certainly\n                      // an error that is irrecoverable and probably qualifies\n                      // as an internal error. We therefore use a predefined\n                      // exception class to throw here.\n                      Assert (neighbor_child->neighbor(face_no==0 ? 1 : 0)==cell,\n                              ExcInternalError());\n\n                      // If the check succeeded, we push the active neighbor\n                      // we just found to the stack we keep:\n                      active_neighbors.push_back (neighbor_child);\n                    }\n                  else\n                    // If we are not in 1d, we collect all neighbor children\n                    // `behind' the subfaces of the current face\n                    for (unsigned int subface_no=0; subface_no<face->n_children(); ++subface_no)\n                      active_neighbors.push_back (\n                        cell->neighbor_child_on_subface(face_no, subface_no));\n                };\n            };\n\n        // OK, now that we have all the neighbors, lets start the computation\n        // on each of them. First we do some preliminaries: find out about the\n        // center of the present cell and the solution at this point. The\n        // latter is obtained as a vector of function values at the quadrature\n        // points, of which there are only one, of course. Likewise, the\n        // position of the center is the position of the first (and only)\n        // quadrature point in real space.\n        const Point<dim> this_center = fe_midpoint_value.quadrature_point(0);\n\n        std::vector<double> this_midpoint_value(1);\n        fe_midpoint_value.get_function_values (solution, this_midpoint_value);\n\n\n        // Now loop over all active neighbors and collect the data we\n        // need. Allocate a vector just like <code>this_midpoint_value</code>\n        // which we will use to store the value of the solution in the\n        // midpoint of the neighbor cell. We allocate it here already, since\n        // that way we don't have to allocate memory repeatedly in each\n        // iteration of this inner loop (memory allocation is a rather\n        // expensive operation):\n        std::vector<double> neighbor_midpoint_value(1);\n        typename std::vector<typename DoFHandler<dim>::active_cell_iterator>::const_iterator\n        neighbor_ptr = active_neighbors.begin();\n        for (; neighbor_ptr!=active_neighbors.end(); ++neighbor_ptr)\n          {\n            // First define an abbreviation for the iterator to the active\n            // neighbor cell:\n            const typename DoFHandler<dim>::active_cell_iterator\n            neighbor = *neighbor_ptr;\n\n            // Then get the center of the neighbor cell and the value of the\n            // finite element function thereon. Note that for this information\n            // we have to reinitialize the <code>FEValues</code> object for\n            // the neighbor cell.\n            fe_midpoint_value.reinit (neighbor);\n            const Point<dim> neighbor_center = fe_midpoint_value.quadrature_point(0);\n\n            fe_midpoint_value.get_function_values (solution,\n                                                   neighbor_midpoint_value);\n\n            // Compute the vector <code>y</code> connecting the centers of the\n            // two cells. Note that as opposed to the introduction, we denote\n            // by <code>y</code> the normalized difference vector, as this is\n            // the quantity used everywhere in the computations.\n            Point<dim>   y        = neighbor_center - this_center;\n            const double distance = std::sqrt(y.square());\n            y /= distance;\n\n            // Then add up the contribution of this cell to the Y matrix...\n            for (unsigned int i=0; i<dim; ++i)\n              for (unsigned int j=0; j<dim; ++j)\n                Y[i][j] += y[i] * y[j];\n\n            // ... and update the sum of difference quotients:\n            projected_gradient += (neighbor_midpoint_value[0] -\n                                   this_midpoint_value[0]) /\n                                  distance *\n                                  y;\n          };\n\n        // If now, after collecting all the information from the neighbors, we\n        // can determine an approximation of the gradient for the present\n        // cell, then we need to have passed over vectors <code>y</code> which\n        // span the whole space, otherwise we would not have all components of\n        // the gradient. This is indicated by the invertability of the matrix.\n        //\n        // If the matrix should not be invertible, this means that the present\n        // cell had an insufficient number of active neighbors. In contrast to\n        // all previous cases, where we raised exceptions, this is, however,\n        // not a programming error: it is a runtime error that can happen in\n        // optimized mode even if it ran well in debug mode, so it is\n        // reasonable to try to catch this error also in optimized mode. For\n        // this case, there is the <code>AssertThrow</code> macro: it checks\n        // the condition like the <code>Assert</code> macro, but not only in\n        // debug mode; it then outputs an error message, but instead of\n        // terminating the program as in the case of the <code>Assert</code>\n        // macro, the exception is thrown using the <code>throw</code> command\n        // of C++. This way, one has the possibility to catch this error and\n        // take reasonable counter actions. One such measure would be to\n        // refine the grid globally, as the case of insufficient directions\n        // can not occur if every cell of the initial grid has been refined at\n        // least once.\n        AssertThrow (determinant(Y) != 0,\n                     ExcInsufficientDirections());\n\n        // If, on the other hand the matrix is invertible, then invert it,\n        // multiply the other quantity with it and compute the estimated error\n        // using this quantity and the right powers of the mesh width:\n        const Tensor<2,dim> Y_inverse = invert(Y);\n\n        Point<dim> gradient;\n        contract (gradient, Y_inverse, projected_gradient);\n\n        *error_on_this_cell = (std::pow(cell->diameter(),\n                                        1+1.0*dim/2) *\n                               std::sqrt(gradient.square()));\n      };\n  }\n}\n\n\n// @sect3{Main function}\n\n// The <code>main</code> function is exactly like in previous examples, with\n// the only difference in the name of the main class that actually does the\n// computation.\nint main ()\n{\n  try\n    {\n      dealii::deallog.depth_console (0);\n\n      Step9::AdvectionProblem<2> advection_problem_2d;\n      advection_problem_2d.run ();\n    }\n  catch (std::exception &exc)\n    {\n      std::cerr << std::endl << std::endl\n                << \"----------------------------------------------------\"\n                << std::endl;\n      std::cerr << \"Exception on processing: \" << std::endl\n                << exc.what() << std::endl\n                << \"Aborting!\" << std::endl\n                << \"----------------------------------------------------\"\n                << std::endl;\n      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": "1e708f536d1e68295fa2cdbb9a8ab7f4d1992d6b", "size": 66191, "ext": "cc", "lang": "C++", "max_stars_repo_path": "MHD/examples/step-9/step-9.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-9/step-9.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-9/step-9.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": 48.9216555802, "max_line_length": 96, "alphanum_fraction": 0.6417337705, "num_tokens": 14475, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.3379103161776006}}
{"text": "#ifndef TVMTL_TVMINIMIZER_IRLS_HPP\n#define TVMTL_TVMINIMIZER_IRLS_HPP\n\n//System includes\n#include <iostream>\n#include <map>\n#include <vector>\n#include <chrono>\n\n#ifdef TVMTL_TVMIN_DEBUG\n    #include <string>\n#endif\n\n//Eigen includes\n#include <Eigen/Sparse>\n#include <Eigen/Core>\n#include <unsupported/Eigen/Splines>\n\n//CGAL includes For linear Interpolation\n#include <CGAL/Exact_predicates_inexact_constructions_kernel.h>\n#include <CGAL/Delaunay_triangulation_2.h>\n#include <CGAL/Interpolation_traits_2.h>\n#include <CGAL/natural_neighbor_coordinates_2.h>\n#include <CGAL/interpolation_functions.h>\n\n\n//vpp includes\n#include <vpp/vpp.hh>\n\n\nnamespace tvmtl {\n\ntemplate <class FUNCTIONAL, class MANIFOLD, class DATA, enum PARALLEL PAR> \n    class TV_Minimizer< IRLS, FUNCTIONAL, MANIFOLD, DATA, PAR > {\n    \n\tpublic:\n\t    // Manifold typedefs\n\t    typedef typename MANIFOLD::scalar_type scalar_type;\n\t    typedef typename MANIFOLD::value_type value_type;\n\t    typedef typename MANIFOLD::tm_base_type tm_base_type;\n\n\t    // Functional typedefs\n\t    typedef typename FUNCTIONAL::gradient_type gradient_type;\n\t    typedef typename FUNCTIONAL::sparse_hessian_type hessian_type;\n\t    typedef typename FUNCTIONAL::tm_base_mat_type tm_base_mat_type;\n\t    typedef typename Eigen::SparseSelfAdjointView<hessian_type, Eigen::Upper> sa_hessian_type;\n\n\n\t    // Parameters from traits class\n\t    typedef algo_traits< MANIFOLD::MyType > AT;\n\t    static const int runtime = AT::max_runtime;\n    \n\t    typedef double newton_error_type;\n\n\n\t    // Constructor\n\t    TV_Minimizer(FUNCTIONAL& func, DATA& dat):\n\t\tfunc_(func),\n\t\tdata_(dat)\n\t    {\n\t\tmax_runtime_=AT::max_runtime;\n\t\tmax_irls_steps_=AT::max_irls_steps;\n\t\tmax_newton_steps_=AT::max_newton_steps;\n\t\ttolerance_=AT::tolerance;\n\t\tsparse_pattern_analyzed_ = false;\n\t    }\n\n\t    void first_guess();\n\t    void smoothening(int smooth_steps);\n\t    \n\t    newton_error_type newton_step();\n\t    void minimize();\n\t    void output() { std::cout << \"OUTPUT TEST\" << std::endl; }\n\t\n\t    void setMax_runtime(int t) { max_runtime_ = t; }\n\t    void setMax_irls_steps(int n) { max_irls_steps_ = n; }\n\t    void setMax_newton_steps(int n) { max_newton_steps_ = n; }\n\t    void setTolerance(double t) {tolerance_ =t; }\n\t    \n\t    int max_runtime(int t) const { return max_runtime_; }\n\t    int max_irls_steps(int n) const { return max_irls_steps_; }\n\t    int max_newton_steps(int n) const { return max_newton_steps_; }\n\t    int tolerance(double t) const { return tolerance_; }\n\n\tprivate:\n\t    FUNCTIONAL& func_;\n\t    DATA& data_;\n\t \n\t    typename AT::template solver< hessian_type > solver_;\n\t    bool sparse_pattern_analyzed_;\n\n\t    int irls_step_;\n\t    int newton_step_;\n\n\t    int max_runtime_;\n\t    int max_irls_steps_;\n\t    int max_newton_steps_;\n\t    double tolerance_;\n\n\t    std::vector< std::chrono::duration<double> > Ts_;\n\t    std::vector< typename FUNCTIONAL::result_type > Js_;\n\n    };\n\n/*----- IMPLEMENTATION IRLS------*/\n\n//First Guess\ntemplate <class FUNCTIONAL, class MANIFOLD, class DATA, enum PARALLEL PAR> \nvoid TV_Minimizer<IRLS, FUNCTIONAL, MANIFOLD, DATA, PAR>::first_guess(){\n\n    std::cout << \"Starting interpolation of damaged Area\" << std::endl;\n\n    typedef CGAL::Exact_predicates_inexact_constructions_kernel K;\n    typedef CGAL::Delaunay_triangulation_2<K> Delaunay_triangulation;\n    typedef CGAL::Interpolation_traits_2<K> Traits;\n    typedef K::FT Coord_type;\n    typedef K::Point_2 Point;\n\n    typedef typename DATA::inp_type inp_type;\n    int value_dim = FUNCTIONAL::value_dim;\n    int value_rows = value_type::RowsAtCompileTime;\n    int value_cols = value_type::ColsAtCompileTime;\n\n    if(MANIFOLD::non_isometric_embedding)\n\tvpp::pixel_wise(data_.img_) | [&] (value_type& i){ MANIFOLD::interpolation_preprocessing(i); };\n     \n    for(int r=0; r<value_rows; r++)\n\tfor(int c=0; c<value_cols; c++){\n\t    std::cout << \"\\t Channel \" << value_cols*r+c+1 << \" of \" << value_dim << \"...\" << std::endl;\n\t    Delaunay_triangulation T;\n\t    std::map<Point, Coord_type, K::Less_xy_2> function_values;\n\t    typedef CGAL::Data_access< std::map<Point, Coord_type, K::Less_xy_2 > >  Value_access;\n\t    #ifdef TVMTL_TVMIN_DEBUG\n\t\tstd::cout << \"NZ-Entries in inpainting matrix:\" << vpp::sum(data_.inp_) << std::endl;\n\t    #endif\n\n\t    int numnodes=0;\n\t    // Add Interpolation nodes\n\t    vpp::pixel_wise(data_.inp_, data_.img_, data_.img_.domain())(vpp::_no_threads)  | [&] (inp_type inp, const value_type& i, const vpp::vint2& coord) {\n\t\tif(!inp){\n\t\t\tPoint p(coord[0], coord[1]);\n\t\t\tT.insert(p);\n\t\t\tfunction_values.insert(std::make_pair(p,i(r,c)));\n\t\t\tnumnodes++;\n\t\t}\n\t    };\n\t    std::cout << \"\\t\\tNumber of Nodes: \" << numnodes << std::endl;\n\n\t    int numdampix=0;\n\t    // Interpolate missing nodes\n\t    vpp::pixel_wise(data_.inp_, data_.img_, data_.img_.domain())(vpp::_no_threads) | [&] (inp_type inp, value_type& i, const vpp::vint2& coord) {\n\t\tif(inp){\n\t\t    Point p(coord[0], coord[1]);\n\t\t    std::vector< std::pair< Point, Coord_type > > coords;\n                    Coord_type norm =  CGAL::natural_neighbor_coordinates_2(T, p,std::back_inserter(coords)).second;\n\t\t    Coord_type res = CGAL::linear_interpolation(coords.begin(), coords.end(), norm,Value_access(function_values));\n\t\t    i(r,c)=static_cast<scalar_type>(res);\n\t\t    numdampix++;\n\t\t}\n\t    };\n\t    std::cout << \"\\t\\tNumber of interpolated Pixels: \" << numdampix << std::endl;\n\t}\n\n\tif(MANIFOLD::non_isometric_embedding)\n\t    vpp::pixel_wise(data_.img_) | [&] (value_type& i){ MANIFOLD::interpolation_postprocessing(i); };\n\n    \tvpp::pixel_wise(data_.img_) | [&] (value_type& i) { MANIFOLD::projector(i); };\n\n}\n\n//Smoothening\ntemplate <class FUNCTIONAL, class MANIFOLD, class DATA, enum PARALLEL PAR> \nvoid TV_Minimizer<IRLS, FUNCTIONAL, MANIFOLD, DATA, PAR>::smoothening(int smooth_steps){\n    \n    std::cout << \"Start Smoothening with max_steps = \" << smooth_steps << std::endl;\n\n    //TODO: Add Manifold dependent tranformation Before and after smoothening\n    typename FUNCTIONAL::result_type Jnew = func_.evaluateJ();\n    typename FUNCTIONAL::result_type Jold = Jnew + 1;\n    int step = 0;\n\n    typename FUNCTIONAL::img_type temp_img(data_.img_.domain(), vpp::_border=1);\n    typename FUNCTIONAL::nbh_type N(temp_img);\n\n    std::cout << \"Initial functional value J=\" << Jnew << \"\\n\\n\" << std::endl;\n\n    while(Jnew<Jold && step < smooth_steps){\n\t#ifdef TVMTL_TVMIN_DEBUG_SPD\n\t   data_.output_matval_img(\"presmoothend_spd_img.csv\");\n\t#endif\n\tif(MANIFOLD::non_isometric_embedding)\n\t    vpp::pixel_wise(data_.img_) | [&] (value_type& i){ MANIFOLD::interpolation_preprocessing(i); };\n\t\n\t#ifdef TVMTL_TVMIN_DEBUG_SPD\n\t   data_.output_matval_img(\"preprocessedsmoothend_spd_img.csv\");\n\t#endif\n\tvpp::copy(data_.img_, temp_img);\n\tvpp::fill_border_closest(temp_img);\n\n\tstd::cout << \"\\tSmoothen step #\" << step+1 << std::endl;\n\tstd::cout << \"\\t Value of Functional J: \" << Jnew << std::endl;\n\tJold = Jnew;\n\t// Standard smoothening stencil \n\t//\t1\t \n\t//  1\t4   1\t/   8\n\t//\t1      \n\tauto boxfilter = [&] (value_type& i, const auto& nbh) { \n\t    i = (4 * nbh(0,0) + nbh(1,0) + nbh(0,1) + nbh(-1,0) + nbh(0,-1))/8.0; \n\t    MANIFOLD::projector(i);\n\t};\n\n\tvpp::pixel_wise(data_.img_, N)(/*vpp::_no_threads*/) | boxfilter;\n\n\t#ifdef TVMTL_TVMIN_DEBUG_SPD\n\t   data_.output_matval_img(\"boxfiltersmoothend_spd_img.csv\");\n\t#endif\n\t\n\tif(MANIFOLD::non_isometric_embedding)\n\t    vpp::pixel_wise(data_.img_) | [&] (value_type& i){ MANIFOLD::interpolation_postprocessing(i); };\n\t\n        #ifdef TVMTL_TVMIN_DEBUG_SPD\n\t   data_.output_matval_img(\"postsmoothend_spd_img.csv\");\n\t#endif\n\n\tJnew = func_.evaluateJ();\n\tstep++;\n    }\n    \n    std::cout << \"Smoothening completed with J=\" << Jnew << \"\\n\\n\" << std::endl;\n\n}\n\ntemplate <class FUNCTIONAL, class MANIFOLD, class DATA, enum PARALLEL PAR> \ntypename TV_Minimizer<IRLS, FUNCTIONAL, MANIFOLD, DATA, PAR>::newton_error_type TV_Minimizer<IRLS, FUNCTIONAL, MANIFOLD, DATA, PAR>::newton_step(){\n\n    int nr = data_.img_.nrows();\n    int nc = data_.img_.ncols();\n    int value_dim = FUNCTIONAL::value_dim;\n    int manifold_dim = FUNCTIONAL::manifold_dim;\n\n    // Calculate the gradient and hessian \n    #ifdef TVMTL_TVMIN_DEBUG_VERBOSE\n\tstd::cout << \"\\n\\t\\t...Calculate Gradient\" << std::endl;\n    #endif    \n    func_.evaluateDJ();\n   \n\n    #ifdef TVMTL_TVMIN_DEBUG_VERBOSE\n\tstd::cout << \"\\t\\t...Calculate Hessian\" << std::endl;\n    #endif\n    func_.evaluateHJ();\n\n \n\n    // Set up the sparse Linear system\n    gradient_type x;\n    const gradient_type& b = func_.getDJ();\n    const hessian_type& A = func_.getHJ();//.template selfadjointView<Eigen::Upper>();\n\n    #ifdef TVMTL_TVMIN_DEBUG_VERBOSE\n\tstd::cout << \"\\t\\t\\t...Gradient Size: \" << b.size() << std::endl; \n\tstd::cout << \"\\t\\t\\t...Hessian Non-Zeros: \" << A.nonZeros() << std::endl; \n\tstd::cout << \"\\t\\t\\t...Hessian Rows: \" << A.rows() << std::endl; \n\tstd::cout << \"\\t\\t\\t...Hessian Cols: \" << A.cols() << std::endl; \n\tstd::cout << \"\\n\\t\\t...Analyze Sparse Pattern\" << std::endl;\n    #endif\n    if (!sparse_pattern_analyzed_){\n\tsolver_.analyzePattern(A);\n\tsparse_pattern_analyzed_ =  true;\t\n    }\n    \n    #ifdef TVMTL_TVMIN_DEBUG_VERBOSE\n\tstd::cout << \"\\t\\t...Solve System\" << std::endl;\n    #endif\n\n    // Solve the System\n    solver_.factorize(A);\n    x = solver_.solve(b);\n    \n    // Apply Newton correction to picture\n    // TODO: \n    // - Change VectorXd to something parametrized with scalar_type\n    #ifdef TVMTL_TVMIN_DEBUG_VERBOSE\n\tstd::cout << \"\\t\\t...Apply Newton Correction\" << std::endl;\n    #endif\n    const tm_base_mat_type& T = func_.getT();\n    auto newton_correction = [&] (const tm_base_type& t, value_type& i, const vpp::vint2 coord) { \n\tEigen::VectorXd v = -t*x.segment(manifold_dim*(coord[0]+nr*coord[1]), manifold_dim);\n\tMANIFOLD::exp(i, Eigen::Map<value_type>(v.data()), i);\n\t//MANIFOLD::exp(i, -t*x.segment(manifold_dim*(coord[0]+nr*coord[1]), manifold_dim), i);\n    };\n    vpp::pixel_wise(T, data_.img_, data_.img_.domain()) | newton_correction;\n    \n       // Compute the Error\n     #ifdef TVMTL_TVMIN_DEBUG_VERBOSE\n\tstd::cout << \"\\t\\t...Compute Newton error\" << std::endl;\n    #endif\n    newton_error_type error = x.norm();\n\n    return error;\n}\n\n\ntemplate <class FUNCTIONAL, class MANIFOLD, class DATA, enum PARALLEL PAR> \nvoid TV_Minimizer<IRLS, FUNCTIONAL, MANIFOLD, DATA, PAR>::minimize(){\n    std::cout << \"Starting IRLS Algorithm with...\" << std::endl;\n    std::cout << \"\\t Lambda = \\t\" << func_.getlambda() << std::endl;\n    std::cout << \"\\t eps^2 = \\t\" << func_.geteps2() << std::endl;\n    std::cout << \"\\t Tolerance = \\t\" <<  tolerance_ << std::endl;\n    std::cout << \"\\t Max Steps IRLS= \\t\" << max_irls_steps_ << std::endl;\n    std::cout << \"\\t Max Steps Newton = \\t\" << max_newton_steps_ << std::endl;\n    \n    \n    irls_step_ = 0;\n\n    std::chrono::time_point<std::chrono::system_clock> start, end;\n    std::chrono::duration<double> t = std::chrono::duration<double>::zero();\n    start = std::chrono::system_clock::now();\n    \n    // IRLS Iteration Loop\n    while(irls_step_ < max_irls_steps_ && t.count() < max_runtime_){\n\t\n\tstd::cout << \"IRLS Step #\" << irls_step_+1 << std::endl;\n\t// NOTE: evaluation of J automatically calls updateWeights(): separate eventually\n\ttypename FUNCTIONAL::result_type J = func_.evaluateJ();\n\tJs_.push_back(J);\n\tstd::cout << \"\\t Value of Functional J: \" << J << std::endl;\n\t\n\tnewton_step_ = 0;\n\tnewton_error_type error = tolerance_ + 1;\n\n\t// Newton Iteration Loop\n\twhile(tolerance_ < error && t.count() < max_runtime_ && newton_step_ < max_newton_steps_){\n\t    std::cout << \"\\t Newton step #\" << newton_step_+1;\n\t    error = newton_step();\n\t    #ifdef TVMTL_TVMIN_DEBUG\n\t\t    std::string fname(\"step_img.csv\");\n\t\t    fname = std::to_string(irls_step_) + \".\" + std::to_string(newton_step_) + fname;\n\t\t    data_.output_matval_img(fname.c_str());\n\t    #endif\n\n\t    std::cout << \"\\t Error: \" << error << std::endl;\n\t    newton_step_++;\n\t}\n\t\n\tend = std::chrono::system_clock::now();\n\tt = end - start; \n\tstd::cout << \"\\t Elapsed time: \" << t.count() << \" seconds.\" << std::endl;\n\tirls_step_++;\n\tTs_.push_back(t);\n    }\n\n    std::cout << \"Minimization in \" << t.count() << \" seconds.\" << std::endl;\n}\n\n\n} // end namespace tvmtl\n\n\n#endif\n", "meta": {"hexsha": "11117f6d2dfb9cac5da1eb18a1e08bb098417449", "size": 12178, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "mtvmtl/core/tvmin_irls.hpp", "max_stars_repo_name": "pdebus/MTVMTL", "max_stars_repo_head_hexsha": "65a7754b34d1f6a1e86d15e3c2d4346b9418414f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2017-05-08T12:40:46.000Z", "max_stars_repo_stars_event_max_datetime": "2019-06-02T05:11:01.000Z", "max_issues_repo_path": "mtvmtl/core/tvmin_irls.hpp", "max_issues_repo_name": "pdebus/MTVMTL", "max_issues_repo_head_hexsha": "65a7754b34d1f6a1e86d15e3c2d4346b9418414f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "mtvmtl/core/tvmin_irls.hpp", "max_forks_repo_name": "pdebus/MTVMTL", "max_forks_repo_head_hexsha": "65a7754b34d1f6a1e86d15e3c2d4346b9418414f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.7340720222, "max_line_length": 153, "alphanum_fraction": 0.6691574971, "num_tokens": 3570, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.665410572017153, "lm_q2_score": 0.5078118642792044, "lm_q1q2_score": 0.3379033830871223}}
{"text": "#include \"PID.h\"\n\n#include <algorithm>\n#include <iostream>\n#include <fstream>\n#include <vector>\n#include <boost/range/numeric.hpp>\n\nPID::PID() {}\n\nPID::~PID() {}\n\nvoid PID::Init(double Kp_, double Ki_, double Kd_) {\n  Kp = Kp_;\n  Ki = Ki_;\n  Kd = Kd_;\n\n  p_error = 0;\n  i_error = 0;\n  d_error = 0;\n\n  cum_err = 0;\n\n  twiddle_p = {Kp, Ki, Kd};\n  double fdp = 0.1;\n  twiddle_dp = {fdp, fdp, fdp};\n  twiddle_set_large_up = false;\n  twiddle_set_large_down = false;\n  twiddle_check_large_up = false;\n  twiddle_check_large_down = false;\n\n}\n\nvoid PID::UpdateError(double cte) {\n  d_error = cte - p_error; // diff to prev. cte\n  i_error += cte;\n  p_error = cte;\n\n}\n\ndouble PID::TotalError() {\n  /**\n   * TODO: Calculate and return the total error\n   */\n  return 0.0;  // TODO: Add your total error calc here!\n}\n\ndouble PID::SteeringAngle(double max_steer=0.25) {\n  double steer = -Kp * p_error - Ki * i_error - Kd * d_error;\n  return std::max(std::min(steer, max_steer), -max_steer);\n\n}\n\nvoid PID::log_tune(std::ofstream &logfile, double &cte, double &speed, int &step) {\n  logfile << std::max(0,tune_iter) << \",\" << cum_err << \",\"\n          << cte << \",\" << speed << \",\"\n          << Kp << \",\" << Ki << \",\" << Kd << \"\\n\";\n}\n\nvoid PID::log_summary(std::ofstream &summary) {\n  summary << std::max(0,tune_iter) << \",\" << cum_err << \",\" << best_err << \",\"\n          << boost::accumulate(twiddle_dp, 0.) << \",\" << target_speed << \",\"\n          << Kp << \",\" << Ki << \",\" << Kd << \"\\n\";\n}\n\n// Twiddle 'in-line', i.e. this is called after each single run, setting params for next run\nvoid PID::twiddle(std::ofstream &summary) {\n  if (tune_iter == -1) {\n    tune_iter = 0;\n    best_err = cum_err;\n  } \n  if (twiddle_set_large_up == false) {\n    twiddle_set_large_up = true;\n    twiddle_p[twiddle_iter_p] += twiddle_p[twiddle_iter_p] * twiddle_dp[twiddle_iter_p];\n  } else if (twiddle_check_large_up == false) {\n      twiddle_check_large_up = true;\n      if (cum_err < best_err) {\n        twiddle_dp[twiddle_iter_p] *= 1.1;\n      } else if (twiddle_set_large_down == false) {\n          twiddle_set_large_down = true;\n          twiddle_p[twiddle_iter_p] -= 2 * twiddle_p[twiddle_iter_p] *  twiddle_dp[twiddle_iter_p];\n          }\n    } else if (twiddle_check_large_down == false) {\n        twiddle_check_large_down = true;\n        if (cum_err < best_err) {\n          twiddle_dp[twiddle_iter_p] *= 1.1;\n        } else {\n            twiddle_p[twiddle_iter_p] += twiddle_p[twiddle_iter_p] * twiddle_dp[twiddle_iter_p];\n            twiddle_dp[twiddle_iter_p] *= 0.9;\n          }\n      }\n\n  if (cum_err < best_err || (twiddle_check_large_down == true && twiddle_check_large_up == true)) {\n    if (twiddle_iter_p < 2) {\n      if (Ki == 0) { // skip I, for faster PD convergence\n        twiddle_iter_p = 2;\n      } else {\n          twiddle_iter_p++;\n        }\n      } else {\n        twiddle_iter_p = 0;\n        tune_iter++;\n      }\n    if (cum_err < best_err) best_err = cum_err;\n    twiddle_p[twiddle_iter_p] += twiddle_p[twiddle_iter_p] * twiddle_dp[twiddle_iter_p];\n    twiddle_set_large_up = true;\n    twiddle_set_large_down = false;\n    twiddle_check_large_down = false;\n    twiddle_check_large_up = false;\n  }\n  log_summary(summary);\n  // stop updating PID params if twiddle is done\n  if (boost::accumulate(twiddle_dp, 0.) > tune_tolerance) {\n    Kp = twiddle_p[0];\n    Ki = twiddle_p[1];\n    Kd = twiddle_p[2];\n  }\n\n}", "meta": {"hexsha": "7f1a4f458b3090d107b156355b8308f50625b119", "size": 3399, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/PID.cpp", "max_stars_repo_name": "SebastianSchafer/CarND-PID-Control", "max_stars_repo_head_hexsha": "5f86dce04805b3c278b187cca619a60124090380", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/PID.cpp", "max_issues_repo_name": "SebastianSchafer/CarND-PID-Control", "max_issues_repo_head_hexsha": "5f86dce04805b3c278b187cca619a60124090380", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/PID.cpp", "max_forks_repo_name": "SebastianSchafer/CarND-PID-Control", "max_forks_repo_head_hexsha": "5f86dce04805b3c278b187cca619a60124090380", "max_forks_repo_licenses": ["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.5630252101, "max_line_length": 99, "alphanum_fraction": 0.6104736687, "num_tokens": 1044, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5851011542032312, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.33789320471723494}}
{"text": "/*\n * =====================================================================================\n *\n *       Filename:  astron_main_atp.cpp\n *\n *    Description:\n *\n *        Version:  1.0\n *        Created:  06/28/2014 02:04:16 PM\n *       Revision:  none\n *       Compiler:  gcc\n *\n *         Author:  Anup Pillai (), anupgpillai@gmail.com\n *   Organization:  IISER Pune\n *\n * =====================================================================================\n */\n#define DIR1 \"/media/chivda/BigDaddy/\"\n#include <iostream>\n#include <stdlib.h>\n#include <cmath>\n#include <vector>\n//#include \"/home/goofy/DATA/SCRIPTS/CPP/Astron/astron_proj.hpp\"\n#include \"astron_ATPext_model.hpp\"\n//#include \"astron_ip3_model.hpp\"\n//#include \"astron_ip3_atp_model.hpp\"\n//#include \"astron_utility_functions.hpp\"\n//#include \"/opt/boost/boost_1_55_0/boost/numeric/ublas/vector.hpp\" /*  Specifying the full path in qoutes for a header file */\n#include <boost/numeric/odeint.hpp> /*  Specifying the file within < > lets c++ search for it at -I path  */\n\nusing namespace std;\nusing namespace boost::numeric::odeint;\n\ntypedef std::vector< double > state_type;\n\n//-----------------\nint main(int argc, char **argv)\n{\n   ATPext atp_ext(25E-04);\n\n   typedef runge_kutta4 < state_type > stepper_type;\n   stepper_type rk4;\n\n\n   double atp_conc0 = 0.0;\n   double adp_conc0 = 0.0;\n   double amp_conc0 = 0.0;\n   double ado_conc0 = 0.0;\n   double ino_conc0 = 0.0;\n\n   state_type x = {atp_conc0, adp_conc0, amp_conc0, ado_conc0, ino_conc0};\n\n   double dt = 100.0; // 40 in micro sec\n   double atp_pulse = 0.0;\n   int pulse_given=0;\n   for (double t=0.0; t<= (1000 * 1 * 60); t+= dt)\n   {\n      x[0] = x[0] + atp_pulse;\n      if ( t >=3000 & (t < 4000) & (pulse_given == 0) )\n      {\n         atp_pulse = 1000.0;   // micro M\n         pulse_given = 1;\n      }\n      else\n      {\n         atp_pulse = 0.0;\n      }\n      rk4.do_step(boost::ref(atp_ext),std::make_pair(x.begin(),x.end()),t,dt);\n      cout << t << \" \" << x[0] << \" \" << x[1] << \" \" << x[2] << \" \" << x[3] << \" \" << x[4] << \" \" << atp_pulse << \"\\n\";\n      //hh.printparam();\n      //xwrite(x,t);\n      //if (t >=1000) cin.get(); // Press enter key to continue\n      //cin.get();\n   }\n\n   return 0;\n}\n", "meta": {"hexsha": "c4ae2988539dd6080003647f59ef0b3a8d037489", "size": 2224, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/old/src/old/astron_main_atp_test.cpp", "max_stars_repo_name": "anupgp/astron", "max_stars_repo_head_hexsha": "5ef1b113b5025f5e0477a1fb2b5202fadbc5335c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/old/src/old/astron_main_atp_test.cpp", "max_issues_repo_name": "anupgp/astron", "max_issues_repo_head_hexsha": "5ef1b113b5025f5e0477a1fb2b5202fadbc5335c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/old/src/old/astron_main_atp_test.cpp", "max_forks_repo_name": "anupgp/astron", "max_forks_repo_head_hexsha": "5ef1b113b5025f5e0477a1fb2b5202fadbc5335c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.5128205128, "max_line_length": 127, "alphanum_fraction": 0.5373201439, "num_tokens": 701, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6757646140788307, "lm_q2_score": 0.5, "lm_q1q2_score": 0.33788230703941535}}
{"text": "/* Copyright (c) 2015, Julian Straub <jstraub@csail.mit.edu>\n * Licensed under the MIT license. See the license file LICENSE.\n */\n#pragma once\n#include <iostream>\n#include <stdint.h>\n#include <vector>\n#include <Eigen/Dense>\n\n#include <boost/shared_ptr.hpp>\n\n#include <dpMM/dpMM.hpp>\n#include <dpMM/cat.hpp>\n#include <dpMM/dir.hpp>\n#include <dpMM/niw.hpp>\n#include <dpMM/sampler.hpp>\n#include <dpMM/basemeasure.hpp>\n\nusing namespace Eigen;\nusing std::endl; using std::cout;\nusing boost::shared_ptr;\n\n#ifdef CUDA\n  #define SET_CUDA\n  #undef CUDA\n#endif\n\ntemplate<typename T>\nclass DirMM : public DpMM<T>\n{\npublic:\n  DirMM(const Dir<Cat<T>, T>& alpha, const shared_ptr<BaseMeasure<T> >&\n      theta, uint32_t K0);\n  DirMM(const Dir<Cat<T>, T>& alpha, const\n      vector<shared_ptr<BaseMeasure<T> > >& thetas);\n  DirMM(const DirMM<T>& dirMM);\n  virtual ~DirMM();\n\n  virtual void reset();\n  virtual void initialize(const Matrix<T,Dynamic,Dynamic>& x);\n  virtual void initialize(const shared_ptr<ClGMMData<T> >& cld)\n    {cout<<\"not supported\"<<endl; assert(false);};\n\n  virtual void sampleLabels();\n  virtual void sampleParameters();\n  virtual void sampleFromPrior();\n\n  virtual T logJoint();\n  virtual const Matrix<T,Dynamic,Dynamic>& x() const {return x_;};\n  virtual const VectorXu& labels() const {return z_;};\n  virtual const VectorXu& getLabels() {return z_;};\n  virtual void setLabels(const VectorXu& z){z_ = z;};\n  virtual uint32_t getK() const { return K_;};\n  virtual const shared_ptr<BaseMeasure<T> >& getTheta(uint32_t k) const\n    { assert(k<K_); return this->thetas_[k];};\n  virtual const vector<shared_ptr<BaseMeasure<T> > >& getThetas() const\n    { return this->thetas_;};\n  virtual const shared_ptr<BaseMeasure<T> >& getTheta0() const\n    { return this->theta0_;};\n\n  virtual const Dir<Cat<T>, T>& Alpha() const { return dir_;}; \n  virtual const Cat<T>& Pi() const { return pi_;}; \n\n//  virtual MatrixXu mostLikelyInds(uint32_t n);\n  virtual MatrixXu mostLikelyInds(uint32_t n, Matrix<T,Dynamic,Dynamic>& logLikes);\n\n  Matrix<T,Dynamic,1> getCounts();\n\n  bool isInit() const { return sampler_!= NULL;};\n\nprotected: \n  uint32_t K0_;  // that is the number of clusters that are initialized with data at the beginning (K0_ <= K_)\n  uint32_t K_;\n  Dir<Cat<T>, T> dir_;\n  Cat<T> pi_;\n#ifdef CUDA\n  SamplerGpu<T>* sampler_;\n#else \n  Sampler<T>* sampler_;\n#endif\n  Matrix<T,Dynamic,Dynamic> pdfs_;\n//  Cat cat_;\n  shared_ptr<BaseMeasure<T> > theta0_;\n  vector<shared_ptr<BaseMeasure<T> > > thetas_;\n\n  Matrix<T,Dynamic,Dynamic> x_;\n  VectorXu z_;\n};\n\n// --------------------------------------- impl -------------------------------\n\n\ntemplate<typename T>\nDirMM<T>::DirMM(const Dir<Cat<T>,T>& alpha, const\n    shared_ptr<BaseMeasure<T> >& theta, uint32_t K0) :\n  K0_(K0), K_(alpha.K_), dir_(alpha), pi_(dir_.sample()), \n  sampler_(NULL),\n  theta0_(theta)\n{};\n\n\ntemplate<typename T>\nDirMM<T>::DirMM(const Dir<Cat<T>,T>& alpha, \n    const vector<shared_ptr<BaseMeasure<T> > >& thetas) :\n  K_(alpha.K_), dir_(alpha), pi_(dir_.sample()), \n  sampler_(NULL), thetas_(thetas),\n  theta0_(\n      shared_ptr<BaseMeasure<T> >(thetas[0]->copy()))\n{\n//  cout<<thetas_.size()<<endl;\n//  for(uint32_t k=0; k<thetas_.size(); ++k)\n//    cout<< \"   \"<<thetas_[k].get()<<endl;\n//  cout<<thetas_[0].get()<<endl;\n//  cout<<thetas_[0]->copy()<<endl;\n//\n//  theta0_ = shared_ptr<BaseMeasure<T> >(thetas_[0]->copy());\n};\n\ntemplate<typename T>\nDirMM<T>::DirMM(const DirMM<T>& dirMM) \n  : K_(dirMM.getK()), dir_(dirMM.Alpha()), pi_(dirMM.Pi()), \n  sampler_(NULL), \n  theta0_(shared_ptr<BaseMeasure<T> >(\n        dirMM.getTheta0()->copy()))\n{\n  for(uint32_t k=0; k<  dirMM.getK(); ++k)\n  {\n    thetas_.push_back(shared_ptr<BaseMeasure<T> >(\n          dirMM.getTheta(k)->copy())); \n  }\n  if(dirMM.isInit())\n  {\n    x_ = dirMM.x();\n    // bad boy\n    z_ = const_cast<DirMM<T>* >(&dirMM)->labels();\n    pdfs_.setZero(x_.cols(),K_);\n#ifdef CUDA\n    sampler_ = new SamplerGpu<T>(x_.cols(),K_,dir_.pRndGen_);\n#else \n    sampler_ = new Sampler<T>(dir_.pRndGen_);\n#endif\n  }\n};\n\n\ntemplate<typename T>\nDirMM<T>::~DirMM()\n{\n  if (sampler_ != NULL) delete sampler_;\n};\n\ntemplate <typename T>\nMatrix<T,Dynamic,1> DirMM<T>::getCounts()\n{\n  return counts<T,uint32_t>(z_,K_);\n};\n\n\ntemplate<typename T>\nvoid DirMM<T>::initialize(const Matrix<T,Dynamic,Dynamic>& x)\n{\n//  cout<<\"init\"<<endl;\n  x_ = x;\n  // randomly init labels from prior\n  z_.setZero(x.cols());\n//  cout<<\"sample pi\"<<endl;\n  pi_ = dir_.sample(); \n  if (K0_ < K_)\n  {\n    Matrix<T,Dynamic,1> pdf = pi_.pdf();\n    pdf.bottomRows(K_-K0_).setZero();\n    pdf = pdf / pdf.sum(); // renormalize\n    pi_.pdf(pdf);\n  } \n//  cout<<\"init pi=\"<<pi_.pdf().transpose()<<endl;\n  pi_.sample(z_);\n\n  pdfs_.setZero(x.cols(),K_);\n#ifdef CUDA\n  sampler_ = new SamplerGpu<T>(x.cols(),K_,dir_.pRndGen_);\n#else \n  sampler_ = new Sampler<T>(dir_.pRndGen_);\n#endif\n\n  // init the parameters\n//  if(thetas_.size() == 0)\n//  {\n  thetas_.clear(); // destrey eny previous thetas\n//  cout<<\"creating thetas\"<<endl;\n  for (uint32_t k=0; k<K_; ++k)\n    thetas_.push_back(shared_ptr<BaseMeasure<T> >(theta0_->copy()));\n//  }\n//#pragma omp parallel for\n//  for(uint32_t k=0; k<K_; ++k)\n//    thetas_[k]->posterior(x_,z_,k);\n//  for (uint32_t k=0; k<K_; ++k)\n//    thetas_[k].initialize(x_,z_);\n};\n\ntemplate<typename T>\nvoid DirMM<T>::reset()\n{\n  x_ = Matrix<T,Dynamic,Dynamic>::Zero(0,theta0_->getDim());\n  z_ = VectorXu::Zero(0);\n  pi_ = dir_.sample(); \n  pdfs_.setZero(0,K_);\n  delete sampler_;\n  sampler_ = NULL;\n\n  thetas_.clear(); // delete any previous thetas\n  for (uint32_t k=0; k<K_; ++k)\n    thetas_.push_back(shared_ptr<BaseMeasure<T> >(theta0_->copy()));\n};\n\ntemplate<typename T>\nvoid DirMM<T>::sampleLabels()\n{\n  // obtain posterior categorical under labels\n  pi_ = dir_.posterior(z_).sample();\n//  cout<<pi_.pdf().transpose()<<endl;\n  \n#pragma omp parallel for\n  for(int32_t i=0; i<z_.size(); ++i)\n  {\n    //TODO: could buffer this better\n    // compute categorical distribution over label z_i\n    VectorXd logPdf_z = pi_.pdf().array().log();\n    for(uint32_t k=0; k<K_; ++k)\n    {\n//      cout<<thetas_[k]->logLikelihood(x_.col(i))<<\" \";\n      logPdf_z[k] += thetas_[k]->logLikelihood(x_.col(i));\n    }\n//    cout<<endl;\n    // make pdf sum to 1. and exponentiate\n    pdfs_.row(i) = (logPdf_z.array()-logSumExp(logPdf_z)).exp().matrix().transpose();\n//    cout<<pi_.pdf().transpose()<<endl;\n//    cout<<pdfs_.row(i)<<\" |.|=\"<<pdfs_.row(i).sum()<<endl;;\n//    cout<<\" z_i=\"<<z_[i]<<endl;\n  }\n  // sample z_i\n  sampler_->sampleDiscPdf(pdfs_,z_);\n};\n\n\ntemplate<typename T>\nvoid DirMM<T>::sampleParameters()\n{\n//  Matrix<T,Dynamic,1> Ns = getCounts();\n//#pragma omp parallel for \n  for(uint32_t k=0; k<K_; ++k)\n  {\n//    cout<<\"k:\"<<k<<\" \"<<Ns(k)<<\" \";\n    thetas_[k]->posterior(x_,z_,k);\n//    thetas_[k]->print();\n  }\n};\n\ntemplate<typename T>\nvoid DirMM<T>::sampleFromPrior()\n{\n//  Matrix<T,Dynamic,1> Ns = getCounts();\n//#pragma omp parallel for \n//\n// simulate sampling from prior by not giving the posteriors any data\n  Matrix<T,Dynamic,Dynamic> x = Matrix<T,Dynamic,Dynamic>::Zero(1,1);\n  VectorXu z = VectorXu::Ones(1)*(K_+1);\n  for(uint32_t k=0; k<K_; ++k)\n  {\n//    cout<<\"k:\"<<k<<\" \"<<Ns(k)<<\" \";\n    thetas_[k]->posterior(x,z,k);\n//    thetas_[k]->print();\n  }\n};\n\n\ntemplate<typename T>\nT DirMM<T>::logJoint()\n{\n  T logJoint = dir_.logPdf(pi_);\n  cout<<\"  [logJoint=\"<<logJoint<<\" -> \";\n#pragma omp parallel for reduction(+:logJoint)  \n  for (int32_t k=0; k<K_; ++k)\n    logJoint = logJoint + thetas_[k]->logPdfUnderPrior();\n  cout<<\" \"<<logJoint<<\" -> \";\n#pragma omp parallel for reduction(+:logJoint)  \n  for (int32_t i=0; i<z_.size(); ++i)\n    logJoint = logJoint + thetas_[z_[i]]->logLikelihood(x_.col(i));\n  cout<<\" \"<<logJoint<<\"]\"<<endl;\n  return logJoint;\n};\n\n\ntemplate<typename T>\nMatrixXu DirMM<T>::mostLikelyInds(uint32_t n, Matrix<T,Dynamic,Dynamic>& logLikes)\n{\n  MatrixXu inds = MatrixXu::Zero(n,K_);\n  logLikes = Matrix<T,Dynamic,Dynamic>::Ones(n,K_);\n  \n#pragma omp parallel for \n  for (int32_t k=0; k<K_; ++k)\n  {\n    for (uint32_t i=0; i<z_.size(); ++i)\n      if(z_(i) == k)\n      {\n        T logLike = thetas_[z_[i]]->logLikelihood(x_.col(i));\n        for (uint32_t j=0; j<n; ++j)\n          if(logLikes(j,k) < logLike)\n          {\n            for(uint32_t l=n-1; l>j; --l)\n            {\n              logLikes(l,k) = logLikes(l-1,k);\n              inds(l,k) = inds(l-1,k);\n            }\n            logLikes(j,k) = logLike;\n            inds(j,k) = i;\n//            cout<<\"after update \"<<logLike<<endl;\n//            Matrix<T,Dynamic,Dynamic> out(n,K_*2);\n//            out<<logLikes.cast<T>(),inds.cast<T>();\n//            cout<<out<<endl;\n            break;\n          }\n      }\n  } \n  cout<<\"::mostLikelyInds: logLikes\"<<endl;\n  cout<<logLikes<<endl;\n  cout<<\"::mostLikelyInds: inds\"<<endl;\n  cout<<inds<<endl;\n  return inds;\n};\n\n#ifdef SET_CUDA\n  #define CUDA\n#endif\n\n//template<class T>\n//T DirMM<T>::avgIntraClusterDeviation()\n//{\n//  Matrix<T,Dynamic,1> deviates(K_);\n//  deviates.setZero(K_);\n//#pragma omp parallel for \n//  for (uint32_t k=0; k<K_; ++k)\n//  {\n//    T N_k = 0.0;\n//    for (uint32_t i=0; i<N_; ++i)\n//      if(z_(i) == k)\n//      {\n//        T dot = thetas_[k]->transpose()*spx_->col(i);\n//        deviates(k) += acos(min(1.0,max(-1.0,dot)));\n//        N_k ++;\n//      }\n//    if(N_k > 0.0) deviates(k) /= N_k;\n//  }\n//  return deviates.sum()/static_cast<T>(K_);\n//}\n", "meta": {"hexsha": "0c67355275bd6aa8a2a4279a0ab034798ec46a5c", "size": 9426, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/dpMM/dirMM.hpp", "max_stars_repo_name": "jstraub/dpMM", "max_stars_repo_head_hexsha": "538c432d5f98c040d5c1adb072e545e38f97fc69", "max_stars_repo_licenses": ["MIT-feh"], "max_stars_count": 11.0, "max_stars_repo_stars_event_min_datetime": "2015-04-27T15:14:01.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-18T00:19:18.000Z", "max_issues_repo_path": "include/dpMM/dirMM.hpp", "max_issues_repo_name": "jstraub/dpMM", "max_issues_repo_head_hexsha": "538c432d5f98c040d5c1adb072e545e38f97fc69", "max_issues_repo_licenses": ["MIT-feh"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/dpMM/dirMM.hpp", "max_forks_repo_name": "jstraub/dpMM", "max_forks_repo_head_hexsha": "538c432d5f98c040d5c1adb072e545e38f97fc69", "max_forks_repo_licenses": ["MIT-feh"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2015-07-02T12:46:20.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-30T04:39:30.000Z", "avg_line_length": 26.5521126761, "max_line_length": 110, "alphanum_fraction": 0.6125610015, "num_tokens": 2949, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6757646010190476, "lm_q2_score": 0.5, "lm_q1q2_score": 0.3378823005095238}}
{"text": "/*\n Copyright (C) 2020 Quaternion Risk Management Ltd\n All rights reserved.\n\n This file is part of ORE, a free-software/open-source library\n for transparent pricing and risk analysis - http://opensourcerisk.org\n\n ORE is free software: you can redistribute it and/or modify it\n under the terms of the Modified BSD License.  You should have received a\n copy of the license along with this program.\n The license is also available online at <http://opensourcerisk.org>\n\n This program is distributed on the basis that it will form a useful\n contribution to risk analytics and model standardisation, but WITHOUT\n ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n FITNESS FOR A PARTICULAR PURPOSE. See the license for more details.\n*/\n\n#include <orea/aggregation/dimregressioncalculator.hpp>\n#include <ored/utilities/log.hpp>\n#include <ored/utilities/vectorutils.hpp>\n#include <ql/errors.hpp>\n#include <ql/time/calendars/weekendsonly.hpp>\n#include <ql/version.hpp>\n\n#include <ql/math/distributions/normaldistribution.hpp>\n#include <ql/math/generallinearleastsquares.hpp>\n#include <ql/math/kernelfunctions.hpp>\n#include <ql/methods/montecarlo/lsmbasissystem.hpp>\n#include <ql/time/daycounters/actualactual.hpp>\n\n#include <qle/math/nadarayawatson.hpp>\n#include <qle/math/stabilisedglls.hpp>\n\n#include <boost/accumulators/accumulators.hpp>\n#include <boost/accumulators/statistics/error_of_mean.hpp>\n#include <boost/accumulators/statistics/mean.hpp>\n#include <boost/accumulators/statistics/stats.hpp>\n\nusing namespace std;\nusing namespace QuantLib;\n\nusing namespace boost::accumulators;\n\nnamespace ore {\nnamespace analytics {\n\nRegressionDynamicInitialMarginCalculator::RegressionDynamicInitialMarginCalculator(\n    const boost::shared_ptr<Portfolio>& portfolio, const boost::shared_ptr<NPVCube>& cube,\n    const boost::shared_ptr<CubeInterpretation>& cubeInterpretation,\n    const boost::shared_ptr<AggregationScenarioData>& scenarioData, Real quantile, Size horizonCalendarDays,\n    Size regressionOrder, std::vector<std::string> regressors, Size localRegressionEvaluations,\n    Real localRegressionBandWidth, const std::map<std::string, Real>& currentIM)\n    : DynamicInitialMarginCalculator(portfolio, cube, cubeInterpretation, scenarioData, quantile, horizonCalendarDays,\n                                     currentIM),\n      regressionOrder_(regressionOrder), regressors_(regressors),\n      localRegressionEvaluations_(localRegressionEvaluations), localRegressionBandWidth_(localRegressionBandWidth) {\n    Size dates = cube_->dates().size();\n    Size samples = cube_->samples();\n    for (Size i = 0; i < nettingSetIds_.size(); ++i) {\n        regressorArray_[nettingSetIds_[i]] = vector<vector<Array>>(dates, vector<Array>(samples));\n        nettingSetLocalDIM_[nettingSetIds_[i]] = vector<vector<Real>>(dates, vector<Real>(samples, 0.0));\n        nettingSetZeroOrderDIM_[nettingSetIds_[i]] = vector<Real>(dates, 0.0);\n        nettingSetSimpleDIMh_[nettingSetIds_[i]] = vector<Real>(dates, 0.0);\n        nettingSetSimpleDIMp_[nettingSetIds_[i]] = vector<Real>(dates, 0.0);\n    }\n}\n\nconst vector<vector<Real>>&\nRegressionDynamicInitialMarginCalculator::localRegressionResults(const std::string& nettingSet) {\n    if (nettingSetLocalDIM_.find(nettingSet) != nettingSetLocalDIM_.end())\n        return nettingSetLocalDIM_[nettingSet];\n    else\n        QL_FAIL(\"netting set \" << nettingSet << \" not found in Local DIM results\");\n}\n\nconst vector<Real>& RegressionDynamicInitialMarginCalculator::zeroOrderResults(const std::string& nettingSet) {\n    if (nettingSetZeroOrderDIM_.find(nettingSet) != nettingSetZeroOrderDIM_.end())\n        return nettingSetZeroOrderDIM_[nettingSet];\n    else\n        QL_FAIL(\"netting set \" << nettingSet << \" not found in Zero Order DIM results\");\n}\n\nconst vector<Real>& RegressionDynamicInitialMarginCalculator::simpleResultsUpper(const std::string& nettingSet) {\n    if (nettingSetSimpleDIMp_.find(nettingSet) != nettingSetSimpleDIMp_.end())\n        return nettingSetSimpleDIMp_[nettingSet];\n    else\n        QL_FAIL(\"netting set \" << nettingSet << \" not found in Simple DIM (p) results\");\n}\n\nconst vector<Real>& RegressionDynamicInitialMarginCalculator::simpleResultsLower(const std::string& nettingSet) {\n    if (nettingSetSimpleDIMh_.find(nettingSet) != nettingSetSimpleDIMh_.end())\n        return nettingSetSimpleDIMh_[nettingSet];\n    else\n        QL_FAIL(\"netting set \" << nettingSet << \" not found in Simple DIM (c) results\");\n}\n\nvoid RegressionDynamicInitialMarginCalculator::build() {\n    LOG(\"DIM Analysis by polynomial regression\");\n\n    map<string, Real> currentDim = unscaledCurrentDIM();\n\n    Size stopDatesLoop = datesLoopSize_;\n    Size samples = cube_->samples();\n\n    Size polynomOrder = regressionOrder_;\n    LOG(\"DIM regression polynom order = \" << regressionOrder_);\n    LsmBasisSystem::PolynomType polynomType = LsmBasisSystem::Monomial;\n    Size regressionDimension = regressors_.empty() ? 1 : regressors_.size();\n    LOG(\"DIM regression dimension = \" << regressionDimension);\n#if QL_HEX_VERSION > 0x01150000\n    std::vector<ext::function<Real(Array)>> v(\n        LsmBasisSystem::multiPathBasisSystem(regressionDimension, polynomOrder, polynomType));\n#else // QL 1.14 and below\n    std::vector<boost::function1<Real, Array>> v(\n        LsmBasisSystem::multiPathBasisSystem(regressionDimension, polynomOrder, polynomType));\n#endif\n    Real confidenceLevel = QuantLib::InverseCumulativeNormal()(quantile_);\n    LOG(\"DIM confidence level \" << confidenceLevel);\n\n    Size simple_dim_index_h = Size(floor(quantile_ * (samples - 1) + 0.5));\n    Size simple_dim_index_p = Size(floor((1.0 - quantile_) * (samples - 1) + 0.5));\n\n    Size nettingSetCount = 0;\n    for (auto n : nettingSetIds_) {\n        LOG(\"Process netting set \" << n);\n\n        if (currentIM_.find(n) != currentIM_.end()) {\n            Real t0im = currentIM_[n];\n            QL_REQUIRE(currentDim.find(n) != currentDim.end(), \"current DIM not found for netting set \" << n);\n            Real t0dim = currentDim[n];\n            Real t0scaling = t0im / t0dim;\n            LOG(\"t0 scaling for netting set \" << n << \": t0im\" << t0im << \" t0dim=\" << t0dim\n                                              << \" t0scaling=\" << t0scaling);\n            nettingSetScaling_[n] = t0scaling;\n        }\n\n        Real nettingSetDimScaling =\n            nettingSetScaling_.find(n) == nettingSetScaling_.end() ? 1.0 : nettingSetScaling_[n];\n        LOG(\"Netting set DIM scaling factor: \" << nettingSetDimScaling);\n\n        for (Size j = 0; j < stopDatesLoop; ++j) {\n            accumulator_set<double, stats<tag::mean, tag::variance>> accDiff;\n            accumulator_set<double, stats<tag::mean>> accOneOverNumeraire;\n            for (Size k = 0; k < samples; ++k) {\n                Real numDefault = cubeInterpretation_->getDefaultAggrionScenarioData(\n                    scenarioData_, AggregationScenarioDataType::Numeraire, j, k);\n                Real numCloseOut = cubeInterpretation_->getCloseOutAggrionScenarioData(\n                    scenarioData_, AggregationScenarioDataType::Numeraire, j, k);\n                Real npvDefault = nettingSetNPV_[n][j][k];\n                Real flow = nettingSetFLOW_[n][j][k];\n                Real npvCloseOut = nettingSetCloseOutNPV_[n][j][k];\n                accDiff((npvCloseOut * numCloseOut) + (flow * numDefault) - (npvDefault * numDefault));\n                accOneOverNumeraire(1.0 / numDefault);\n            }\n\n            Size mporCalendarDays = cubeInterpretation_->getMporCalendarDays(cube_, j);\n            Real horizonScaling = sqrt(1.0 * horizonCalendarDays_ / mporCalendarDays);\n\n            Real stdevDiff = sqrt(variance(accDiff));\n            Real E_OneOverNumeraire =\n                mean(accOneOverNumeraire); // \"re-discount\" (the stdev is calculated on non-discounted deltaNPVs)\n\n            nettingSetZeroOrderDIM_[n][j] = stdevDiff * horizonScaling * confidenceLevel;\n            nettingSetZeroOrderDIM_[n][j] *= E_OneOverNumeraire;\n\n            vector<Real> rx0(samples, 0.0);\n            vector<Array> rx(samples, Array());\n            vector<Real> ry1(samples, 0.0);\n            vector<Real> ry2(samples, 0.0);\n            for (Size k = 0; k < samples; ++k) {\n                Real numDefault = cubeInterpretation_->getDefaultAggrionScenarioData(\n                    scenarioData_, AggregationScenarioDataType::Numeraire, j, k);\n                Real numCloseOut = cubeInterpretation_->getCloseOutAggrionScenarioData(\n                    scenarioData_, AggregationScenarioDataType::Numeraire, j, k);\n                Real x = nettingSetNPV_[n][j][k] * numDefault;\n                Real f = nettingSetFLOW_[n][j][k] * numDefault;\n                Real y = nettingSetCloseOutNPV_[n][j][k] * numCloseOut;\n                Real z = (y + f - x);\n                rx[k] = regressors_.empty() ? Array(1, nettingSetNPV_[n][j][k]) : regressorArray(n, j, k);\n                rx0[k] = rx[k][0];\n                ry1[k] = z;     // for local regression\n                ry2[k] = z * z; // for least squares regression\n                nettingSetDeltaNPV_[n][j][k] = z;\n                regressorArray_[n][j][k] = rx[k];\n            }\n            vector<Real> delNpvVec_copy = nettingSetDeltaNPV_[n][j];\n            sort(delNpvVec_copy.begin(), delNpvVec_copy.end());\n            Real simpleDim_h = delNpvVec_copy[simple_dim_index_h];\n            Real simpleDim_p = delNpvVec_copy[simple_dim_index_p];\n            simpleDim_h *= horizonScaling;                                  // the usual scaling factors\n            simpleDim_p *= horizonScaling;                                  // the usual scaling factors\n            nettingSetSimpleDIMh_[n][j] = simpleDim_h * E_OneOverNumeraire; // discounted DIM\n            nettingSetSimpleDIMp_[n][j] = simpleDim_p * E_OneOverNumeraire; // discounted DIM\n\n            QL_REQUIRE(rx.size() > v.size(), \"not enough points for regression with polynom order \" << polynomOrder);\n            if (close_enough(stdevDiff, 0.0)) {\n                LOG(\"DIM: Zero std dev estimation at step \" << j);\n                // Skip IM calculation if all samples have zero NPV (e.g. after latest maturity)\n                for (Size k = 0; k < samples; ++k) {\n                    nettingSetDIM_[n][j][k] = 0.0;\n                    nettingSetLocalDIM_[n][j][k] = 0.0;\n                }\n            } else {\n                // Least squares polynomial regression with specified polynom order\n                QuantExt::StabilisedGLLS ls(rx, ry2, v, QuantExt::StabilisedGLLS::MeanStdDev);\n                LOG(\"DIM data normalisation at time step \"\n                    << j << \": \" << scientific << setprecision(6) << \" x-shift = \" << ls.xShift() << \" x-multiplier = \"\n                    << ls.xMultiplier() << \" y-shift = \" << ls.yShift() << \" y-multiplier = \" << ls.yMultiplier());\n                LOG(\"DIM regression coefficients at time step \" << j << \": \" << fixed << setprecision(6)\n                                                                << ls.transformedCoefficients());\n\n                // Local regression versus first regression variable (i.e. we do not perform a\n                // multidimensional local regression):\n                // We evaluate this at a limited number of samples only for validation purposes.\n                // Note that computational effort scales quadratically with number of samples.\n                // NadarayaWatson needs a large number of samples for good results.\n                QuantExt::NadarayaWatson lr(rx0.begin(), rx0.end(), ry1.begin(),\n                                            GaussianKernel(0.0, localRegressionBandWidth_));\n                Size localRegressionSamples = samples;\n                if (localRegressionEvaluations_ > 0)\n                    localRegressionSamples = Size(floor(1.0 * samples / localRegressionEvaluations_ + .5));\n\n                // Evaluate regression function to compute DIM for each scenario\n                for (Size k = 0; k < samples; ++k) {\n                    // Real num1 = scenarioData_->get(j, k, AggregationScenarioDataType::Numeraire);\n                    Real numDefault = cubeInterpretation_->getDefaultAggrionScenarioData(\n                        scenarioData_, AggregationScenarioDataType::Numeraire, j, k);\n                    Array regressor = regressors_.empty() ? Array(1, nettingSetNPV_[n][j][k]) : regressorArray(n, j, k);\n                    Real e = ls.eval(regressor, v);\n                    if (e < 0.0)\n                        LOG(\"Negative variance regression for date \" << j << \", sample \" << k\n                                                                     << \", regressor = \" << regressor);\n\n                    // Note:\n                    // 1) We assume vanishing mean of \"z\", because the drift over a MPOR is usually small,\n                    //    and to avoid a second regression for the conditional mean\n                    // 2) In particular the linear regression function can yield negative variance values in\n                    //    extreme scenarios where an exact analytical or delta VaR calculation would yield a\n                    //    variance aproaching zero. We correct this here by taking the positive part.\n                    Real std = sqrt(std::max(e, 0.0));\n                    Real scalingFactor = horizonScaling * confidenceLevel * nettingSetDimScaling;\n                    // Real dim = std * scalingFactor / num1;\n                    Real dim = std * scalingFactor / numDefault;\n                    dimCube_->set(dim, nettingSetCount, j, k);\n                    nettingSetDIM_[n][j][k] = dim;\n                    nettingSetExpectedDIM_[n][j] += dim / samples;\n\n                    // Evaluate the Kernel regression for a subset of the samples only (performance)\n                    if (localRegressionEvaluations_ > 0 && (k % localRegressionSamples == 0))\n                        // nettingSetLocalDIM_[n][j][k] = lr.standardDeviation(regressor[0]) * scalingFactor / num1;\n                        nettingSetLocalDIM_[n][j][k] = lr.standardDeviation(regressor[0]) * scalingFactor / numDefault;\n                    else\n                        nettingSetLocalDIM_[n][j][k] = 0.0;\n                }\n            }\n        }\n\n        nettingSetCount++;\n    }\n    LOG(\"DIM by polynomial regression done\");\n}\n\nDisposable<Array> RegressionDynamicInitialMarginCalculator::regressorArray(string nettingSet, Size dateIndex,\n                                                                           Size sampleIndex) {\n    Array a(regressors_.size());\n    for (Size i = 0; i < regressors_.size(); ++i) {\n        string variable = regressors_[i];\n        if (boost::to_upper_copy(variable) ==\n            \"NPV\") // this allows possibility to include NPV as a regressor alongside more fundamental risk factors\n            a[i] = nettingSetNPV_[nettingSet][dateIndex][sampleIndex];\n        else if (scenarioData_->has(AggregationScenarioDataType::IndexFixing, variable))\n            a[i] = cubeInterpretation_->getDefaultAggrionScenarioData(\n                scenarioData_, AggregationScenarioDataType::IndexFixing, dateIndex, sampleIndex, variable);\n        else if (scenarioData_->has(AggregationScenarioDataType::FXSpot, variable))\n            a[i] = cubeInterpretation_->getDefaultAggrionScenarioData(\n                scenarioData_, AggregationScenarioDataType::FXSpot, dateIndex, sampleIndex, variable);\n        else if (scenarioData_->has(AggregationScenarioDataType::Generic, variable))\n            a[i] = cubeInterpretation_->getDefaultAggrionScenarioData(\n                scenarioData_, AggregationScenarioDataType::Generic, dateIndex, sampleIndex, variable);\n        else\n            QL_FAIL(\"scenario data does not provide data for \" << variable);\n    }\n    return a;\n}\n\nmap<string, Real> RegressionDynamicInitialMarginCalculator::unscaledCurrentDIM() {\n    // In this function we proxy the model-implied T0 IM by looking at the\n    // cube grid horizon lying closest to t0+mpor. We measure diffs relative\n    // to the mean of the distribution at this same time horizon, thus avoiding\n    // any cashflow-specific jumps\n\n    Date today = cube_->asof();\n    Size relevantDateIdx = 0;\n    Real sqrtTimeScaling = 1.0;\n    for (Size i = 0; i < cube_->dates().size(); ++i) {\n        Size daysFromT0 = (cube_->dates()[i] - today);\n        if (daysFromT0 < horizonCalendarDays_) {\n            // iterate until we straddle t0+mpor\n            continue;\n        } else if (daysFromT0 == horizonCalendarDays_) {\n            // this date corresponds to t0+mpor, so use it\n            relevantDateIdx = i;\n            sqrtTimeScaling = 1.0;\n            break;\n        } else if (daysFromT0 > horizonCalendarDays_) {\n            // the first date greater than t0+MPOR, check if it is closest\n            Size lastIdx = (i == 0) ? 0 : (i - 1);\n            Size lastDaysFromT0 = (cube_->dates()[lastIdx] - today);\n            int daysFromT0CloseOut = daysFromT0 - horizonCalendarDays_;\n            int prevDaysFromT0CloseOut = lastDaysFromT0 - horizonCalendarDays_;\n            if (std::abs(daysFromT0CloseOut) <= std::abs(prevDaysFromT0CloseOut)) {\n                relevantDateIdx = i;\n                sqrtTimeScaling = std::sqrt(Real(horizonCalendarDays_) / Real(daysFromT0));\n            } else {\n                relevantDateIdx = lastIdx;\n                sqrtTimeScaling = std::sqrt(Real(horizonCalendarDays_) / Real(lastDaysFromT0));\n            }\n            break;\n        }\n    }\n    // set some reasonable bounds on the sqrt time scaling, so that we are not looking at a ridiculous time horizon\n    if (sqrtTimeScaling < std::sqrt(0.5) || sqrtTimeScaling > std::sqrt(2.0)) {\n        WLOG(\"T0 IM Estimation - The estimation time horizon from grid is not sufficiently close to t0+MPOR - \"\n             << QuantLib::io::iso_date(cube_->dates()[relevantDateIdx])\n             << \", the T0 IM estimate might be inaccurate. Consider inserting a first grid tenor closer to the dim \"\n                \"horizon\");\n    }\n\n    // TODO: Ensure that the simulation containers read-from below are indeed populated\n\n    Real confidenceLevel = QuantLib::InverseCumulativeNormal()(quantile_);\n    Size simple_dim_index_h = Size(floor(quantile_ * (cube_->samples() - 1) + 0.5));\n    map<string, Real> t0dimReg, t0dimSimple;\n    for (auto it_map = nettingSetNPV_.begin(); it_map != nettingSetNPV_.end(); ++it_map) {\n        string key = it_map->first;\n        vector<Real> t0_dist = it_map->second[relevantDateIdx];\n        Size dist_size = t0_dist.size();\n        QL_REQUIRE(dist_size == cube_->samples(),\n                   \"T0 IM - cube samples size mismatch - \" << dist_size << \", \" << cube_->samples());\n        Real mean_t0_dist = std::accumulate(t0_dist.begin(), t0_dist.end(), 0.0);\n        mean_t0_dist /= dist_size;\n        vector<Real> t0_delMtM_dist(dist_size, 0.0);\n        accumulator_set<double, stats<tag::mean, tag::variance>> acc_delMtm;\n        accumulator_set<double, stats<tag::mean>> acc_OneOverNum;\n        for (Size i = 0; i < dist_size; ++i) {\n            Real numeraire = scenarioData_->get(relevantDateIdx, i, AggregationScenarioDataType::Numeraire);\n            Real deltaMtmFromMean = numeraire * (t0_dist[i] - mean_t0_dist) * sqrtTimeScaling;\n            t0_delMtM_dist[i] = deltaMtmFromMean;\n            acc_delMtm(deltaMtmFromMean);\n            acc_OneOverNum(1.0 / numeraire);\n        }\n        Real E_OneOverNumeraire = mean(acc_OneOverNum);\n        Real variance_t0 = variance(acc_delMtm);\n        Real sqrt_t0 = sqrt(variance_t0);\n        t0dimReg[key] = (sqrt_t0 * confidenceLevel * E_OneOverNumeraire);\n        std::sort(t0_delMtM_dist.begin(), t0_delMtM_dist.end());\n        t0dimSimple[key] = (t0_delMtM_dist[simple_dim_index_h] * E_OneOverNumeraire);\n\n        LOG(\"T0 IM (Reg) - {\" << key << \"} = \" << t0dimReg[key]);\n        LOG(\"T0 IM (Simple) - {\" << key << \"} = \" << t0dimSimple[key]);\n    }\n    LOG(\"T0 IM Calculations Completed\");\n\n    return t0dimReg;\n}\n\nvoid RegressionDynamicInitialMarginCalculator::exportDimEvolution(ore::data::Report& dimEvolutionReport) {\n\n    Size samples = dimCube_->samples();\n    Size stopDatesLoop = datesLoopSize_;\n    Date asof = cube_->asof();\n\n    dimEvolutionReport.addColumn(\"TimeStep\", Size())\n        .addColumn(\"Date\", Date())\n        .addColumn(\"DaysInPeriod\", Size())\n        .addColumn(\"ZeroOrderDIM\", Real(), 6)\n        .addColumn(\"AverageDIM\", Real(), 6)\n        .addColumn(\"AverageFLOW\", Real(), 6)\n        .addColumn(\"SimpleDIM\", Real(), 6)\n        .addColumn(\"NettingSet\", string())\n        .addColumn(\"Time\", Real(), 6);\n\n    for (auto nettingSet : dimCube_->ids()) {\n\n        LOG(\"Export DIM evolution for netting set \" << nettingSet);\n        for (Size i = 0; i < stopDatesLoop; ++i) {\n            Real expectedFlow = 0.0;\n            for (Size j = 0; j < samples; ++j) {\n                expectedFlow += nettingSetFLOW_[nettingSet][i][j] / samples;\n            }\n\n            Date defaultDate = dimCube_->dates()[i];\n            Time t = ActualActual().yearFraction(asof, defaultDate);\n            Size days = cubeInterpretation_->getMporCalendarDays(dimCube_, i);\n            dimEvolutionReport.next()\n                .add(i)\n                .add(defaultDate)\n                .add(days)\n                .add(nettingSetZeroOrderDIM_[nettingSet][i])\n                .add(nettingSetExpectedDIM_[nettingSet][i])\n                .add(expectedFlow)\n                .add(nettingSetSimpleDIMh_[nettingSet][i])\n                .add(nettingSet)\n                .add(t);\n        }\n    }\n    dimEvolutionReport.end();\n    LOG(\"Exporting expected DIM through time done\");\n}\n\nvoid RegressionDynamicInitialMarginCalculator::exportDimRegression(\n    const std::string& nettingSet, const std::vector<Size>& timeSteps,\n    const std::vector<boost::shared_ptr<ore::data::Report>>& dimRegReports) {\n\n    QL_REQUIRE(dimRegReports.size() == timeSteps.size(),\n               \"number of file names (\" << dimRegReports.size() << \") does not match number of time steps (\"\n                                        << timeSteps.size() << \")\");\n    for (Size ii = 0; ii < timeSteps.size(); ++ii) {\n        Size timeStep = timeSteps[ii];\n        LOG(\"Export DIM by sample for netting set \" << nettingSet << \" and time step \" << timeStep);\n\n        Size dates = dimCube_->dates().size();\n        const std::vector<std::string>& ids = dimCube_->ids();\n\n        int index = -1;\n        for (Size i = 0; i < ids.size(); ++i) {\n            if (ids[i] == nettingSet) {\n                index = i;\n                break;\n            }\n        }\n        QL_REQUIRE(index >= 0, \"netting set \" << nettingSet << \" not found in DIM cube\");\n\n        QL_REQUIRE(timeStep < dates - 1, \"selected time step \" << timeStep << \" out of range [0, \" << dates - 1 << \"]\");\n\n        Size samples = cube_->samples();\n        vector<Real> numeraires(samples, 0.0);\n        for (Size k = 0; k < samples; ++k)\n            // numeraires[k] = scenarioData_->get(timeStep, k, AggregationScenarioDataType::Numeraire);\n            numeraires[k] = cubeInterpretation_->getDefaultAggrionScenarioData(\n                scenarioData_, AggregationScenarioDataType::Numeraire, timeStep, k);\n\n        auto p = sort_permutation(regressorArray_[nettingSet][timeStep], lessThan);\n        vector<Array> reg = apply_permutation(regressorArray_[nettingSet][timeStep], p);\n        vector<Real> dim = apply_permutation(nettingSetDIM_[nettingSet][timeStep], p);\n        vector<Real> ldim = apply_permutation(nettingSetLocalDIM_[nettingSet][timeStep], p);\n        vector<Real> delta = apply_permutation(nettingSetDeltaNPV_[nettingSet][timeStep], p);\n        vector<Real> num = apply_permutation(numeraires, p);\n\n        boost::shared_ptr<ore::data::Report> regReport = dimRegReports[ii];\n        regReport->addColumn(\"Sample\", Size());\n        for (Size k = 0; k < reg[0].size(); ++k) {\n            ostringstream o;\n            o << \"Regressor_\" << k << \"_\";\n            o << (regressors_.empty() ? \"NPV\" : regressors_[k]);\n            regReport->addColumn(o.str(), Real(), 6);\n        }\n        regReport->addColumn(\"RegressionDIM\", Real(), 6)\n            .addColumn(\"LocalDIM\", Real(), 6)\n            .addColumn(\"ExpectedDIM\", Real(), 6)\n            .addColumn(\"ZeroOrderDIM\", Real(), 6)\n            .addColumn(\"DeltaNPV\", Real(), 6)\n            .addColumn(\"SimpleDIM\", Real(), 6);\n\n        // Note that RegressionDIM, LocalDIM, DeltaNPV are _not_ reduced by the numeraire in this output,\n        // but ExpectedDIM, ZeroOrderDIM and SimpleDIM _are_ reduced by the numeraire.\n        // This is so that the regression formula can be manually validated\n\n        for (Size j = 0; j < reg.size(); ++j) {\n            regReport->next().add(j);\n            for (Size k = 0; k < reg[j].size(); ++k)\n                regReport->add(reg[j][k]);\n            regReport->add(dim[j] * num[j])\n                .add(ldim[j] * num[j])\n                .add(nettingSetExpectedDIM_[nettingSet][timeStep])\n                .add(nettingSetZeroOrderDIM_[nettingSet][timeStep])\n                .add(delta[j])\n                .add(nettingSetSimpleDIMh_[nettingSet][timeStep]);\n        }\n        regReport->end();\n        LOG(\"Exporting DIM by Sample done for\");\n    }\n}\n\n} // namespace analytics\n} // namespace ore\n", "meta": {"hexsha": "9a317fe4b0b6f3b97455ff78eb59c4380b373eff", "size": 25305, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "OREAnalytics/orea/aggregation/dimregressioncalculator.cpp", "max_stars_repo_name": "mrslezak/Engine", "max_stars_repo_head_hexsha": "c46ff278a2c5f4162db91a7ab500a0bb8cef7657", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 335.0, "max_stars_repo_stars_event_min_datetime": "2016-10-07T16:31:10.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-02T07:12:03.000Z", "max_issues_repo_path": "OREAnalytics/orea/aggregation/dimregressioncalculator.cpp", "max_issues_repo_name": "mrslezak/Engine", "max_issues_repo_head_hexsha": "c46ff278a2c5f4162db91a7ab500a0bb8cef7657", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 59.0, "max_issues_repo_issues_event_min_datetime": "2016-10-31T04:20:24.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-03T16:39:57.000Z", "max_forks_repo_path": "OREAnalytics/orea/aggregation/dimregressioncalculator.cpp", "max_forks_repo_name": "mrslezak/Engine", "max_forks_repo_head_hexsha": "c46ff278a2c5f4162db91a7ab500a0bb8cef7657", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 180.0, "max_forks_repo_forks_event_min_datetime": "2016-10-08T14:23:50.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T10:43:05.000Z", "avg_line_length": 51.8545081967, "max_line_length": 120, "alphanum_fraction": 0.6205097807, "num_tokens": 6223, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6757646010190476, "lm_q2_score": 0.5, "lm_q1q2_score": 0.3378823005095238}}
{"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 \"bayesopt/bayesopt.hpp\"\n\n#include <limits>\n#include <boost/numeric/ublas/matrix_proxy.hpp>\n\n#include \"lhs.hpp\"\n#include \"randgen.hpp\"\n#include \"log.hpp\"\n#include \"boundingbox.hpp\"\n#include \"inneroptimization.hpp\"\n\n\n\nnamespace bayesopt  {\n\n  class CritCallback: public RBOptimizable\n  {\n  public:\n    explicit CritCallback(ContinuousModel* model):mBO(model){};\n    double evaluate(const vectord &query) \n    {\n      return mBO->evaluateCriteria(query);\n    }\n  private:\n    ContinuousModel* mBO;\n  };\n  \n  ContinuousModel::ContinuousModel(size_t dim, Parameters parameters):\n    BayesOptBase(dim,parameters)\n  { \n    mCallback.reset(new CritCallback(this));\n    cOptimizer.reset(new NLOPT_Optimization(mCallback.get(),dim));\n    cOptimizer->setAlgorithm(COMBINED);\n    cOptimizer->setMaxEvals(parameters.n_inner_iterations);\n\n    vectord lowerBound = zvectord(mDims);\n    vectord upperBound = svectord(mDims,1.0);\n    mBB.reset(new utils::BoundingBox<vectord>(lowerBound,upperBound));\n  } // Constructor\n\n  ContinuousModel::~ContinuousModel()\n  {\n    //    delete cOptimizer;\n  } // Default destructor\n\n  void ContinuousModel::setBoundingBox(const vectord &lowerBound,\n\t\t\t\t       const vectord &upperBound)\n  {\n    // We don't change the bounds of the inner optimization because,\n    // thanks to this bounding box model, everything is mapped to the\n    // unit hypercube, thus the default inner optimization are just\n    // right.\n    mBB.reset(new utils::BoundingBox<vectord>(lowerBound,upperBound));\n    \n    FILE_LOG(logINFO) << \"Bounds: \";\n    FILE_LOG(logINFO) << lowerBound;\n    FILE_LOG(logINFO) << upperBound;\n  } //setBoundingBox\n\n\n\n\n\n  //////////////////////////////////////////////////////////////////////\n\n  vectord ContinuousModel::samplePoint()\n  {\t    \n    randFloat drawSample(mEngine,realUniformDist(0,1));\n    vectord Xnext(mDims);    \n    for(vectord::iterator x = Xnext.begin(); x != Xnext.end(); ++x)\n      {\t\n\t*x = drawSample(); \n      }\n    return Xnext;\n  };\n\n  void ContinuousModel::findOptimal(vectord &xOpt)\n  { \n    double minf = cOptimizer->run(xOpt);\n\n    //Let's try some local exploration like spearmint\n    randNFloat drawSample(mEngine,normalDist(0,0.001));\n    for(size_t ii = 0;ii<5; ++ii)\n      {\n\tvectord pert = getPointAtMinimum();\n\tfor(size_t j=0; j<xOpt.size(); ++j)\n\t  {\n\t    pert(j) += drawSample();\n\t  }\n\ttry\n\t  {\n\t    double minf2 = cOptimizer->localTrialAround(pert);\t    \n\t    if (minf2<minf) \n\t      {\n\t\tminf = minf2;\n\t\tFILE_LOG(logDEBUG) << \"Local beats Global\";\n\t\txOpt = pert;\n\t      }\n\t  }\n\tcatch(std::invalid_argument& e)\n\t  {\n\t    //We ignore this one\n\t  }\n      }\n  };\n\n  vectord ContinuousModel::remapPoint(const vectord& x)\n  {\n    return mBB->unnormalizeVector(x);\n  }\n\n  void ContinuousModel::generateInitialPoints(matrixd& xPoints)\n  {   \n    utils::samplePoints(xPoints,mParameters.init_method,mEngine);\n  }\n}  //namespace bayesopt\n", "meta": {"hexsha": "dbdd6056fbd272519c27f150f6e7a9e4615070e2", "size": 3871, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "external/bayesopt/src/bayesoptcont.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/bayesoptcont.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/bayesoptcont.cpp", "max_forks_repo_name": "pchrapka/brain-modelling", "max_forks_repo_head_hexsha": "f232b5a858e45f10b0b0735269010454129ab017", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-11-25T12:22:05.000Z", "max_forks_repo_forks_event_max_datetime": "2019-11-25T12:22:05.000Z", "avg_line_length": 27.8489208633, "max_line_length": 75, "alphanum_fraction": 0.6486695944, "num_tokens": 955, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6757645879592642, "lm_q2_score": 0.5, "lm_q1q2_score": 0.3378822939796321}}
{"text": "///////////////////////////////////////////////////////////////\n//  Copyright 2013 John Maddock. Distributed under the Boost\n//  Software License, Version 1.0. (See accompanying file\n//  LICENSE_1_0.txt or copy at https://www.boost.org/LICENSE_1_0.txt\n\n//[logged_adaptor\n\n#include <boost/multiprecision/mpfi.hpp>\n#include <boost/multiprecision/logged_adaptor.hpp>\n#include <iostream>\n#include <iomanip>\n//\n// Begin by overloading log_postfix_event so we can capture each arithmetic event as it happens:\n//\nnamespace boost{ namespace multiprecision{\n\ntemplate <unsigned D>\ninline void log_postfix_event(const mpfi_float_backend<D>& val, const char* event_description)\n{\n   // Print out the (relative) diameter of the interval:\n   using namespace boost::multiprecision;\n   number<mpfr_float_backend<D> > diam;\n   mpfi_diam(diam.backend().data(), val.data());\n   std::cout << \"Diameter was \" << diam << \" after operation: \" << event_description << std::endl;\n}\ntemplate <unsigned D, class T>\ninline void log_postfix_event(const mpfi_float_backend<D>&, const T&, const char* event_description)\n{\n   // This version is never called in this example.\n}\n\n}}\n\n\nint main()\n{\n   using namespace boost::multiprecision;\n   typedef number<logged_adaptor<mpfi_float_backend<17> > > logged_type;\n   //\n   // Test case deliberately introduces cancellation error, relative size of interval\n   // gradually gets larger after each operation:\n   //\n   logged_type a = 1;\n   a /= 10;\n\n   for(unsigned i = 0; i < 13; ++i)\n   {\n      logged_type b = a * 9;\n      b /= 10;\n      a -= b;\n   }\n   std::cout << \"Final value was: \" << a << std::endl;\n   return 0;\n}\n\n//]\n\n/*\n//[logged_adaptor_output\n\nDiameter was nan after operation: Default construct\nDiameter was 0 after operation: Assignment from arithmetic type\nDiameter was 4.33681e-18 after operation: /=\nDiameter was nan after operation: Default construct\nDiameter was 7.70988e-18 after operation: *\nDiameter was 9.63735e-18 after operation: /=\nDiameter was 1.30104e-16 after operation: -=\nDiameter was nan after operation: Default construct\nDiameter was 1.30104e-16 after operation: *\nDiameter was 1.38537e-16 after operation: /=\nDiameter was 2.54788e-15 after operation: -=\nDiameter was nan after operation: Default construct\nDiameter was 2.54788e-15 after operation: *\nDiameter was 2.54863e-15 after operation: /=\nDiameter was 4.84164e-14 after operation: -=\nDiameter was nan after operation: Default construct\nDiameter was 4.84164e-14 after operation: *\nDiameter was 4.84221e-14 after operation: /=\nDiameter was 9.19962e-13 after operation: -=\nDiameter was nan after operation: Default construct\nDiameter was 9.19962e-13 after operation: *\nDiameter was 9.19966e-13 after operation: /=\nDiameter was 1.74793e-11 after operation: -=\nDiameter was nan after operation: Default construct\nDiameter was 1.74793e-11 after operation: *\nDiameter was 1.74793e-11 after operation: /=\nDiameter was 3.32107e-10 after operation: -=\nDiameter was nan after operation: Default construct\nDiameter was 3.32107e-10 after operation: *\nDiameter was 3.32107e-10 after operation: /=\nDiameter was 6.31003e-09 after operation: -=\nDiameter was nan after operation: Default construct\nDiameter was 6.31003e-09 after operation: *\nDiameter was 6.31003e-09 after operation: /=\nDiameter was 1.19891e-07 after operation: -=\nDiameter was nan after operation: Default construct\nDiameter was 1.19891e-07 after operation: *\nDiameter was 1.19891e-07 after operation: /=\nDiameter was 2.27792e-06 after operation: -=\nDiameter was nan after operation: Default construct\nDiameter was 2.27792e-06 after operation: *\nDiameter was 2.27792e-06 after operation: /=\nDiameter was 4.32805e-05 after operation: -=\nDiameter was nan after operation: Default construct\nDiameter was 4.32805e-05 after operation: *\nDiameter was 4.32805e-05 after operation: /=\nDiameter was 0.00082233 after operation: -=\nDiameter was nan after operation: Default construct\nDiameter was 0.00082233 after operation: *\nDiameter was 0.00082233 after operation: /=\nDiameter was 0.0156243 after operation: -=\nDiameter was nan after operation: Default construct\nDiameter was 0.0156243 after operation: *\nDiameter was 0.0156243 after operation: /=\nDiameter was 0.296861 after operation: -=\nFinal value was: {8.51569e-15,1.14843e-14}\n\n//]\n*/\n", "meta": {"hexsha": "f204cf39f0daf9327ddea74e14aef0b7f7fd6038", "size": 4290, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "3rdParty/boost/1.71.0/libs/multiprecision/example/logged_adaptor.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/multiprecision/example/logged_adaptor.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/multiprecision/example/logged_adaptor.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": 35.75, "max_line_length": 100, "alphanum_fraction": 0.741025641, "num_tokens": 1203, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5888891163376235, "lm_q2_score": 0.5736784074525098, "lm_q1q2_score": 0.3378329704266836}}
{"text": "#ifndef UTIL_HH\n#define UTIL_HH\n\n#include <algorithm>\n#include <vector>\n\n// Visual Studio math.h doesn't have log1p and log1pf functions varjokal 24.3.2010\n// This needs to be defined for VS varjokal 24.3.2010\n#ifdef _MSC_VER\n#include <boost/math/tr1.hpp>\nusing namespace boost::math::tr1;\n#endif\n\n#include <math.h>\n\n/** Common utility functions. */\nnamespace util {\n\n  /** Function evaluation object for search function(s) */\n  class FuncEval {\n  public:\n    virtual double evaluate_function(double p) = 0;\n    virtual ~FuncEval() {}\n  };\n  /** Binary search for finding the parameter value with which the\n   * given function evaluates to max_value within the given accuracy. */\n  double bin_search_param_max_value(double lower_bound, double low_value,\n                                    double upper_bound, double up_value,\n                                    double max_value, double value_acc,\n                                    double param_acc, FuncEval &f);\n\n\n  /** The square of the value. */\n  template <typename T>\n  T sqr(T a)\n  {\n    return a * a;\n  }\n\n  /** Median of the values in a vector. \n   * \\note For odd number (2n + 1) of values, the n'th value is returned.\n   */\n  template <typename T>\n  T\n  median(std::vector<T> v)\n  {\n    std::sort(v.begin(), v.end());\n    return v[v.size() / 2];\n  }\n\n  /** Absolute value. */\n  template <typename T>\n  T\n  abs(const T &value)\n  {\n    if (value < 0)\n      return -value;\n    return value;\n  }\n\n  /** Maximum of two values. */\n  template <typename T>\n  T\n  max(const T &a, const T &b)\n  {\n    if (a < b)\n      return b;\n    return a;\n  }\n\n  inline float\n  log10addf(float a, float b)\n  {\n    // M_LN10 is not part of C++ standard and not defined in every compiler.\n    const float LN10 = 2.30258509299404568402;\n    const float LOG10TOe = LN10;\n    const float LOGeTO10 = 1.0 / LN10;\n\n    a = a * LOG10TOe;\n    b = b * LOG10TOe;\n\n    float delta = a - b;\n    if (delta > 64.0) {\n      b += 64;\n      delta = -delta;\n    }\n    return (b + log1pf(exp(delta))) * LOGeTO10;\n  }\n\n  inline double\n  log10add(double a, double b)\n  {\n    // M_LN10 is not part of C++ standard and not defined in every compiler.\n    const double LN10 = 2.30258509299404568402;\n    const double LOG10TOe = LN10;\n    const double LOGeTO10 = 1.0 / LN10;\n\n    a = a * LOG10TOe;\n    b = b * LOG10TOe;\n\n    double delta = a - b;\n    if (delta > 64.0) {\n      b += 64;\n      delta = -delta;\n    }\n    return (b + log1p(exp(delta))) * LOGeTO10;\n  }\n\n\n  inline float\n  logaddf(float a, float b)\n  {\n    float delta = a - b;\n    if (delta > 0) {\n      b = a;\n      delta = -delta;\n    }\n    return b + log1pf(expf(delta));\n  }\n\n  inline double\n  logadd(double a, double b)\n  {\n    double delta = a - b;\n    if (delta > 0) {\n      b = a;\n      delta = -delta;\n    }\n    return b + log1p(exp(delta));\n  }\n\n  static const double tiny_for_log = 1e-50;\n  inline double safe_log(double x)\n  {\n    if (x < tiny_for_log)\n      return log(tiny_for_log);\n    else\n      return log(x);\n  }\n\n  /** Compute modulo of two values so that negative arguments are\n   * handled correctly. */\n  inline int modulo(int a, int b) \n  {\n    int result = a % b;\n    if (result < 0)\n      result += b;\n    return result;\n  }\n\n  inline float sinc(float x)\n  {\n    // M_PI is not part of C++ standard and not defined in every compiler.\n    const double PI = 3.14159265358979323846;\n    if (fabs(x) < 1e-8)\n      return 1;\n    double y = PI*x;\n    return sin(y)/y;\n  }\n\n};\n\n#endif /* UTIL_HH */\n", "meta": {"hexsha": "f5259c64336e05c240c0f283018f2f4dd5004abc", "size": 3491, "ext": "hh", "lang": "C++", "max_stars_repo_path": "aku/util.hh", "max_stars_repo_name": "lingsoft/AaltoASR", "max_stars_repo_head_hexsha": "40343e215a6cf1b7d5ed41a53095495567b0ab01", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 78.0, "max_stars_repo_stars_event_min_datetime": "2015-01-07T14:33:47.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-15T09:01:30.000Z", "max_issues_repo_path": "aku/util.hh", "max_issues_repo_name": "ufukhurriyetoglu/AaltoASR", "max_issues_repo_head_hexsha": "02b23d374ab9be9b0fd5d8159570b509ede066f3", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2015-05-19T13:00:34.000Z", "max_issues_repo_issues_event_max_datetime": "2016-07-26T12:29:32.000Z", "max_forks_repo_path": "aku/util.hh", "max_forks_repo_name": "ufukhurriyetoglu/AaltoASR", "max_forks_repo_head_hexsha": "02b23d374ab9be9b0fd5d8159570b509ede066f3", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 32.0, "max_forks_repo_forks_event_min_datetime": "2015-01-16T08:16:24.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-02T21:26:22.000Z", "avg_line_length": 21.2865853659, "max_line_length": 82, "alphanum_fraction": 0.5866513893, "num_tokens": 1031, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6406358548398979, "lm_q2_score": 0.5273165233795671, "lm_q1q2_score": 0.33781787172647204}}
{"text": "#include \"ktamura.h\"\n\n#include \"kprogressbar.h\"\n#include \"common.h\"\n#include \"kutility.h\"\n#include \"kpicinfo.h\"\n#include \"kimagecvt.h\" //for image convert\n\n#include <boost/math/special_functions/powm1.hpp>\n#include <boost/math/constants/constants.hpp>\n\n#include <vector>\n#include <map>\n#include <utility>\n#include <limits>\n#include <cmath>\n\n#include <QRegularExpression>\n#include <QCoreApplication>\n#include <QDir>\n\nusing std::vector;\nusing std::map;\nusing std::make_pair;\n\nKTamura::KTamura(QString input)\n    :m_iMaxExtend(32)\n{\n    QRegularExpression re(\"[\\\\\\\\/]\");\n\n    GDALDataset * piDataset = (GDALDataset *) GDALOpen(input.toUtf8().constData(), GA_ReadOnly );\n\n    K_OPEN_ASSERT(piDataset,input.toStdString());\n\n    m_sOutputRoot = getDirRoot(input);\n\n    QString tempName=input.right(input.length()-input.lastIndexOf(re)-1);\n    m_sFileNoExtName=tempName.left(tempName.lastIndexOf(\".\"));\n\n    GDALDataset *poDataset = NULL;\n\n    if((poDataset = KImageCvt::img2gray(piDataset,poDataset,m_sOutputRoot+\"temp\"+QDir::separator()+m_sFileNoExtName+\"-gray\")) == NULL) { std::cout<<\"image convert failed\\a\"<<std::endl; exit(1); }\n\n    m_lXSize = piDataset->GetRasterXSize();\n    m_lYSize = piDataset->GetRasterYSize();\n    m_fOrgArray = (float *) CPLMalloc(sizeof(float)*m_lXSize*m_lYSize);\n    m_fExtArray = (float *) CPLMalloc(sizeof(float)*(m_lXSize+2*m_iMaxExtend)*(m_lYSize+2*m_iMaxExtend));\n\n    // gray only\n    GDALRasterBand * poBand = poDataset->GetRasterBand(1);\n    poBand->RasterIO( GF_Read, 0, 0, m_lXSize, m_lYSize, m_fOrgArray, m_lXSize, m_lYSize, GDT_Float32, 0, 0 );\n\n    KUtility::reflectExtend<float>(m_fOrgArray,m_fExtArray,m_lXSize,m_lYSize,m_iMaxExtend);\n\n    GDALClose(piDataset);\n    GDALClose(poDataset);\n}\n\nKTamura::~KTamura()\n{\n    CPLFree(m_fOrgArray);\n    CPLFree(m_fExtArray);\n}\n\nvoid KTamura::build()\n{\n\n    m_dCoarseness = calCoarseness();\n    m_dContrast = calContrast();\n    m_dDirectionality = calDirectionality();\n}\n\ndouble KTamura::calCoarseness()\n{\n    map<int,std::pair<double,double> > mapAvrGray;\n    double coarseness = 0.;\n    float * tempOut = new float[m_lXSize*m_lYSize];\n\n    unsigned long int lineLength = m_lXSize+2*m_iMaxExtend;\n    KProgressBar progressBar(\"CalCoarseness\",m_lXSize*m_lYSize,80);\n    K_PROGRESS_START(progressBar);\n    long int orgY = m_iMaxExtend;\n    for(unsigned long int desY = 0;orgY<m_lYSize+m_iMaxExtend;++orgY,++desY){\n        long int orgX = m_iMaxExtend;\n        for(unsigned long int desX = 0;orgX<m_lXSize+m_iMaxExtend;++orgX,++desX){\n            mapAvrGray.clear();\n            double hDiff = abs(m_fExtArray[orgY*lineLength+orgX-1]-m_fExtArray[orgY*lineLength+orgX+1]);\n            double vDiff = abs(m_fExtArray[(orgY-1)*lineLength+orgX]-m_fExtArray[(orgY+1)*lineLength+orgX]);\n            mapAvrGray[0] = make_pair(hDiff,vDiff);\n\n            for(int k = 1;k < 6;k++){\n                long binSize = boost::math::powm1(2,k)+1;\n                hDiff = abs(getAverageGray(m_fExtArray,lineLength,orgX-binSize/2,orgY,binSize)-getAverageGray(m_fExtArray,lineLength,orgX+binSize/2,orgY,binSize));\n                vDiff = abs(getAverageGray(m_fExtArray,lineLength,orgX,orgY-binSize/2,binSize)-getAverageGray(m_fExtArray,lineLength,orgX,orgY+binSize/2,binSize));\n                mapAvrGray[k] = make_pair(hDiff,vDiff);\n            }\n\n            double eMax = (std::numeric_limits<double>::min)();\n            int kMax=-1;\n            // find the max E\n            for(map<int,std::pair<double,double> >::iterator it = mapAvrGray.begin();\n                it != mapAvrGray.end(); ++it){\n                double tempMax = std::max(it->second.first,it->second.second);\n                if(eMax<tempMax){ kMax=it->first; eMax=tempMax; }\n            }\n            // find optimal E & k\n            int tempKMax=kMax;\n            for(map<int,std::pair<double,double> >::iterator it = mapAvrGray.begin();\n                it != mapAvrGray.end(); ++it){\n                if(it->first>kMax){\n                    double tempMax = std::max(it->second.first,it->second.second);\n                    if(tempMax>0.9*eMax){\n                        if(tempKMax<it->first) tempKMax = it->first;\n                    }\n                }\n            }\n            kMax=tempKMax;\n            tempOut[desY*m_lXSize+desX] = boost::math::powm1(2,kMax)+1;\n            progressBar.autoUpdate();\n        }\n    }\n    K_PROGRESS_END(progressBar);\n\n    for(long iY = 0;iY<m_lYSize;++iY){\n        for(long iX = 0;iX<m_lXSize;++iX){\n            coarseness += tempOut[iY*m_lXSize+iX];\n        }\n    }\n\n    coarseness = coarseness / (m_lXSize*m_lYSize);\n\n    delete [] tempOut;\n    return coarseness;\n}\n\ndouble KTamura::calContrast()\n{\n    double alpha4 = 0.;\n    double miu4 = 0.;\n    double delta2 = 0.;\n    double delta = 0.;\n    double avr = 0.;\n    double contrast = 0.;\n    /* alpha4 = Sum((Yi - Yavr)^4)/((N-1)*delta^4) */\n    // get Average\n    for(long int iY = 0;iY<m_lYSize;++iY){\n        for(long int iX = 0;iX<m_lXSize;++iX){\n            avr+=m_fOrgArray[iY*m_lXSize+iX];\n        }\n    }\n    avr /= (m_lYSize*m_lXSize);\n    // get Variance and mean fourth\n    for(long int iY = 0;iY<m_lYSize;++iY){\n        for(long int iX = 0;iX<m_lXSize;++iX){\n            double tempValue = m_fOrgArray[iY*m_lXSize+iX];\n            double temp = 0.;\n            temp = abs(tempValue-avr);\n            delta2 += temp * temp;\n            miu4 += delta2 * delta2;\n        }\n    }\n    delta2 /= (m_lYSize*m_lXSize);\n    delta = boost::math::powm1(delta2,0.5)+1;\n    miu4 /= (m_lYSize*m_lXSize - 1);\n    alpha4 = miu4 / (delta2*delta2);\n    contrast = delta/(boost::math::powm1(alpha4,0.25)+1);\n    return contrast;\n}\n\ndouble KTamura::calDirectionality()\n{\n    const int quantizationLevel = 16;\n    const int thresT = 12;\n    double directionality = 0.;\n    float * tempDeltaG = new float[m_lXSize*m_lYSize];\n    float * tempTheta = new float[m_lXSize*m_lYSize];\n    long * histogramD = new long[quantizationLevel];\n    long imageLength = m_lXSize*m_lYSize;\n    unsigned long int lineLength = m_lXSize+2*m_iMaxExtend;\n    //memset(histogramD,0,quantizationLevel);\n    for(int index = 0;index < quantizationLevel;++index){\n        histogramD[index]=0;\n    }\n    long int orgY = m_iMaxExtend;\n    for(unsigned long int desY = 0;orgY<m_lYSize+m_iMaxExtend;++orgY,++desY){\n        long int orgX = m_iMaxExtend;\n        for(unsigned long int desX = 0;orgX<m_lXSize+m_iMaxExtend;++orgX,++desX){\n            float tempDeltaH=0.;\n            float tempDeltaV=0.;\n            tempDeltaH = m_fExtArray[(orgY-1)*lineLength+orgX+1]+m_fExtArray[orgY*lineLength+orgX+1]+m_fExtArray[(orgY+1)*lineLength+orgX+1]-\n                         m_fExtArray[(orgY-1)*lineLength+orgX-1]-m_fExtArray[orgY*lineLength+orgX-1]-m_fExtArray[(orgY+1)*lineLength+orgX-1];\n            tempDeltaV = m_fExtArray[(orgY-1)*lineLength+orgX-1]+m_fExtArray[(orgY-1)*lineLength+orgX]+m_fExtArray[(orgY-1)*lineLength+orgX+1]-\n                         m_fExtArray[(orgY+1)*lineLength+orgX-1]-m_fExtArray[(orgY+1)*lineLength+orgX]-m_fExtArray[(orgY+1)*lineLength+orgX+1];\n            tempDeltaG[desY*m_lXSize+desX] = (abs(tempDeltaV) + abs(tempDeltaH))/2;\n            if(tempDeltaH<0.0001&&tempDeltaH>0.) tempDeltaH=0.0001;\n            if(tempDeltaH>-0.0001&&tempDeltaH<0.) tempDeltaH=-0.0001;\n            if(tempDeltaH==0.) tempDeltaH+=0.00001;\n            tempTheta[desY*m_lXSize+desX] = atan(tempDeltaV/tempDeltaH)+boost::math::constants::pi<float>()/2;\n            //if(tempTheta[desY*m_lXSize+desX]<0) tempTheta[desY*m_lXSize+desX]+=boost::math::constants::pi<float>();\n            //qDebug()<<\"DeltaG\"<<tempDeltaG[desY*m_lXSize+desX]<<\"DeltaH:\"<<tempDeltaH<<\"DeltaV:\"<<tempDeltaV<<\"tempTheta:\"<<tempTheta[desY*m_lXSize+desX];\n        }\n    }\n    // get HistogramD\n    float sumHistogramD = 0.;\n    for(int index = 0;index < quantizationLevel;++index){\n        //qDebug()<<\"start:\"<<histogramD[index];\n        float thetaLow = (2*index)*boost::math::constants::pi<float>()/(2*quantizationLevel);\n        float thetaHigh = (2*index+2)*boost::math::constants::pi<float>()/(2*quantizationLevel);\n        //qDebug()<<\"thetaLow\"<<thetaLow<<\"thetaHigh\"<<thetaHigh;\n\n        for(long imageIndex = 0;imageIndex < imageLength;++imageIndex){\n            //qDebug()<<tempTheta[imageIndex];\n            if(tempDeltaG[imageIndex]>thresT){\n                if(tempTheta[imageIndex]>=thetaLow&&tempTheta[imageIndex]<thetaHigh){\n                    histogramD[index]+=1;\n                }\n            }\n        }\n        //qDebug()<<\"a:\"<<a;\n        //qDebug()<<\"histogramD:\"<<histogramD[index];\n        sumHistogramD += histogramD[index];\n    }\n//    qDebug()<<sumHistogramD;\n//    for(int index = 0;index < quantizationLevel;++index){\n//        //qDebug()<<\"1:\"<<histogramD[index];\n//        histogramD[index]=histogramD[index];\n//        //qDebug()<<\"2:\"<<histogramD[index];\n//    }\n//    QString temp(\"\");\n//    for(int index = 0;index < quantizationLevel;++index){\n//        temp+=QString(\"%1:%2 \").arg(index).arg(histogramD[index]);\n//    }\n//    qDebug()<<temp;\n    // get Directionality\n    // find all the valley and it's position\n    vector<std::pair<int,float> > tempValleyArray;\n    vector<std::pair<int,float> > valleyArray;\n    vector<std::pair<int,float> > finalValley;\n    int firstPeak = getNextValleyPeak(histogramD,0,quantizationLevel,true);\n    int lastPos = firstPeak;\n    tempValleyArray.push_back(make_pair(firstPeak,histogramD[firstPeak]));\n    int tempPeakValley = getNextValleyPeak(histogramD,lastPos,quantizationLevel);\n    while((lastPos>=firstPeak && tempPeakValley>lastPos) || tempPeakValley < firstPeak){\n        tempValleyArray.push_back(make_pair(tempPeakValley, histogramD[tempPeakValley]));\n        lastPos = tempPeakValley;\n        tempPeakValley = getNextValleyPeak(histogramD, lastPos, quantizationLevel);\n    }\n    //qDebug()<<\"tempValleyArray\"<<tempValleyArray.size();\n    //for(unsigned int index = 0;index < tempValleyArray.size();index++){\n    //    qDebug()<<tempValleyArray[index].second;\n    //}\n    float maxPeakRate = (std::numeric_limits<float>::min)();\n    int maxRatePos = -1;\n    // remove the peak and valley which peak/valley<2.0\n    for(unsigned int index = 0;index < tempValleyArray.size();index+=2){\n        float tempRate = tempValleyArray[index].second/tempValleyArray[index+1].second;\n        if(tempRate>maxPeakRate){ maxPeakRate = tempRate; maxRatePos = index; }\n        if(tempRate>2.){\n            if(0==index) valleyArray.push_back(tempValleyArray[tempValleyArray.size()-1]);\n            else valleyArray.push_back(tempValleyArray[index-1]);\n            valleyArray.push_back(tempValleyArray[index]);\n            valleyArray.push_back(tempValleyArray[index+1]);\n        }\n    }\n    if(0 == valleyArray.size() && maxPeakRate>1.){\n        if(0==maxRatePos) valleyArray.push_back(tempValleyArray[tempValleyArray.size()-1]);\n        else valleyArray.push_back(tempValleyArray[maxRatePos-1]);\n        valleyArray.push_back(tempValleyArray[maxRatePos]);\n        valleyArray.push_back(tempValleyArray[maxRatePos+1]);\n    }\n    // get the mian peak and the secondmain peak\n    float maxPeak = (std::numeric_limits<float>::min)();\n    int maxPos = -1;\n    float secondMaxPeak = (std::numeric_limits<float>::min)();\n    int secondMaxPos = -1;\n    //qDebug()<<\"valleySize:\"<<valleyArray.size();\n    for(unsigned int index = 1;index < valleyArray.size();index+=3){\n        if(valleyArray[index].second>maxPeak){ maxPeak = valleyArray[index].second; maxPos=index; }\n    }\n    for(unsigned int index = 1;index < valleyArray.size();index+=3){\n        if(static_cast<int>(index)!=maxPos && valleyArray[index].second>secondMaxPeak){ secondMaxPeak = valleyArray[index].second; secondMaxPos=index; }\n    }\n    //qDebug()<<\"max:\"<<maxPos;\n    if(-1 == maxPos){\n        delete [] tempDeltaG;\n        delete [] tempTheta;\n        delete [] histogramD;\n        return 0.;\n    }\n    //for(unsigned int index = 0;index < tempValleyArray.size();index++)\n    //        qDebug()<<index<<\":\"<<tempValleyArray[index].first;\n    //for(unsigned int index = 0;index < valleyArray.size();index++)\n    //    qDebug()<<index<<\":\"<<valleyArray[index].first;\n    finalValley.push_back(valleyArray[maxPos-1]);\n    finalValley.push_back(valleyArray[maxPos]);\n    finalValley.push_back(valleyArray[maxPos+1]);\n    if(-1 != secondMaxPos){\n        if(maxPeak/secondMaxPeak<5.){\n            finalValley.push_back(valleyArray[secondMaxPos-1]);\n            finalValley.push_back(valleyArray[secondMaxPos]);\n            finalValley.push_back(valleyArray[secondMaxPos+1]);\n        }\n    }\n\n    int nPeaks = finalValley.size()/3;\n//    vector<long> doubleHistogramD;\n//    for(int index = 0;index<2*quantizationLevel;++index){\n//        doubleHistogramD.push_back(histogramD[index%quantizationLevel]);\n//    }\n    for(unsigned int index = 1;index < finalValley.size();index+=3){\n        vector<int> realOrder;\n        int start=0;\n        int peak=0;\n        int end=0;\n        realOrder.push_back(finalValley[index-1].first);\n        realOrder.push_back(finalValley[index-1].first+quantizationLevel);\n        realOrder.push_back(finalValley[index].first);\n        realOrder.push_back(finalValley[index].first+quantizationLevel);\n        realOrder.push_back(finalValley[index+1].first);\n        realOrder.push_back(finalValley[index+1].first+quantizationLevel);\n\n        std::sort(realOrder.begin(),realOrder.end());\n        //for(unsigned int index = 0;index < realOrder.size();index++)\n        //    qDebug()<<realOrder[index];\n        vector<int>::iterator it=realOrder.begin();\n        if((it=std::find(realOrder.begin(),realOrder.end(),finalValley[index].first))!=realOrder.begin()){\n            it--;\n            start = *it++;\n            peak = *it++;\n            end = *it++;\n        }else{\n//            if(realOrder[0]==realOrder[1]){\n//                start = realOrder[0];\n//                peak = realOrder[1];\n//                end = realOrder[2];\n//            }else{\n            it=std::find(realOrder.begin(),realOrder.end(),finalValley[index].first+quantizationLevel);\n            it--;\n            start = *it++;\n            peak = *it++;\n            end = *it++;\n//            }\n        }\n        double tempDir = 0.;\n        for(int position = start;position<end+1;++position){\n            double temp=abs(peak-position);\n            tempDir += temp*temp*histogramD[position%quantizationLevel];\n        }\n\n        directionality+=tempDir;\n    }\n    // calculate sharpness of the peak\n//    int nPeaks = finalValley.size()/3;\n//    for(unsigned int index = 1;index < finalValley.size();index+=3){\n//        double tempDir = 0.;\n//        // first valley after peak\n//        if(finalValley[index-1].first>finalValley[index].first){\n//            for(int position = finalValley[index-1].first;position<quantizationLevel;++position){\n//                double temp=quantizationLevel-position+finalValley[index].first;\n//                tempDir += temp*temp*histogramD[position];\n//            }\n//            for(int position = 0;position<finalValley[index+1].first;++position){\n//                double temp=position-finalValley[index].first;\n//                tempDir += temp*temp*histogramD[position];\n//            }\n//            directionality+=tempDir;\n//            continue;\n//        }\n//        // second valley before peak\n//        if(finalValley[index+1].first<finalValley[index].first){\n//            for(int position = finalValley[index-1].first;position<quantizationLevel;++position){\n//                double temp=position-finalValley[index].first;\n//                tempDir += temp*temp*histogramD[position];\n//            }\n//            for(int position = 0;position<finalValley[index+1].first;++position){\n//                double temp=quantizationLevel+position-finalValley[index].first;\n//                tempDir += temp*temp*histogramD[position];\n//            }\n//            directionality+=tempDir;\n//            continue;\n//        }\n//        for(int position = finalValley[index-1].first;position<finalValley[index+1].first;++position){\n//            double temp=position-finalValley[index].first;\n//            tempDir += temp*temp*histogramD[position];\n//        }\n//        directionality+=tempDir;\n//    }\n\n    delete [] tempDeltaG;\n    delete [] tempTheta;\n    delete [] histogramD;\n    //qDebug()<<nPeaks*directionality*1./sumHistogramD;\n    return nPeaks*directionality*1./sumHistogramD;//*(boost::math::powm1(10,23)+1);\n}\n\nint KTamura::getNextValleyPeak(long *histogram, int start, int length,bool bePeak)\n{\n    static bool bePeakValley = false;\n    if(bePeak) bePeakValley = false;\n    bePeakValley = !bePeakValley;\n    start %= length;\n    int tempPos = start;\n    for (int index = start; index < start + length; ++index){\n        if (bePeakValley){\n            if (histogram[index%length]<histogram[(index + 1) % length]){\n                for (; index < start + length; ++index){\n                    if (histogram[index%length] >= histogram[(index + 1) % length]) break;\n                }\n                tempPos = index;// %length;\n                if (histogram[index%length] == histogram[(index + 1) % length]){\n                    for (; index < start + length; ++index){\n                        if (histogram[index%length]>histogram[(index + 1) % length]) break;\n                    }\n                }\n                tempPos = ((tempPos + index) / 2) % length;\n                break;\n            }\n        }\n        else{\n            if (histogram[index%length]>histogram[(index + 1) % length]){\n                for (; index < start + length; ++index){\n                    if (histogram[index%length] <= histogram[(index + 1) % length]) break;\n                }\n                tempPos = index;//%length;\n                if (histogram[index%length] == histogram[(index + 1) % length]){\n                    for (; index < start + length; ++index){\n                        if (histogram[index%length]<histogram[(index + 1) % length]) break;\n                    }\n                }\n                tempPos = ((tempPos + index) / 2) % length;\n                break;\n            }\n        }\n    }\n    return tempPos;\n}\n\ndouble KTamura::getAverageGray(float * image, unsigned long lineLength, unsigned long lX, unsigned long lY, long size)\n{\n    double sumGray = 0.;\n    for(unsigned long nY = lY-size/2; nY < lY+size/2; ++nY){\n        for(unsigned long nX = lX-size/2; nX < lX+size/2; ++nX){\n            sumGray += image[lineLength*nY+nX];\n        }\n    }\n    sumGray = sumGray/(size*size);\n    return sumGray;\n}\n\nQString KTamura::getDirRoot(QString filename)\n{\n    QString tempRet(\"\");\n    QRegularExpression re(\"[\\\\\\\\/]+\");\n\n    if(filename.contains('\\\\')||filename.contains('/')){\n        QStringList tempList = filename.split(re);\n        for(int pos = 0;pos<tempList.length()-1;++pos)\n        {\n            tempRet+=tempList[pos];\n            tempRet+=QDir::separator();\n        }\n    }else{\n        tempRet=QCoreApplication::applicationDirPath()+QDir::separator();\n    }\n    return tempRet;\n}\n\nQString KTamura::getSVMString(int start)\n{\n    QString temp(\"\");\n    for(int index= start;index<start+3;++index){\n        temp+=QString(\"%1:%%2 \").arg(index).arg(index-start+1);\n    }\n    return QString(temp).arg(m_dCoarseness).arg(m_dContrast).arg(m_dDirectionality);\n}\n", "meta": {"hexsha": "526d0e6486b2b517f97b2efc3b8c3b5c93c19da1", "size": 19320, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ktamura.cpp", "max_stars_repo_name": "PlainSailing/GraduationDesignTest", "max_stars_repo_head_hexsha": "cebcfcdc6d04b24c5e0ba03b962d6896694369ab", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-01-27T07:20:30.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-27T07:20:30.000Z", "max_issues_repo_path": "ktamura.cpp", "max_issues_repo_name": "PlainSailing/GraduationDesignTest", "max_issues_repo_head_hexsha": "cebcfcdc6d04b24c5e0ba03b962d6896694369ab", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ktamura.cpp", "max_forks_repo_name": "PlainSailing/GraduationDesignTest", "max_forks_repo_head_hexsha": "cebcfcdc6d04b24c5e0ba03b962d6896694369ab", "max_forks_repo_licenses": ["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.5882352941, "max_line_length": 195, "alphanum_fraction": 0.6064182195, "num_tokens": 5314, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.640635841117624, "lm_q2_score": 0.5273165233795671, "lm_q1q2_score": 0.3378178644904902}}
{"text": "/* Author: Martin Kronbichler, Uppsala University,\n   Wolfgang Bangerth, Texas A&M University 2007, 2008 */\n\n/*    $Id: step-31.cc 27657 2012-11-21 13:19:08Z bangerth $       */\n/*                                                                */\n/*    Copyright (C) 2007-2012 by the deal.II authors */\n/*                                                                */\n/*    This file is subject to QPL and may not be  distributed     */\n/*    without copyright and license information. Please refer     */\n/*    to the file deal.II/doc/license.html for the  text  and     */\n/*    further information on this license.                        */\n\n// @sect3{Include files}\n\n// The first step, as always, is to include the functionality of these\n// well-known deal.II library files and some C++ header files.\n#include <deal.II/base/quadrature_lib.h>\n#include <deal.II/base/logstream.h>\n#include <deal.II/base/utilities.h>\n\n#include <deal.II/lac/full_matrix.h>\n#include <deal.II/lac/solver_gmres.h>\n#include <deal.II/lac/solver_cg.h>\n#include <deal.II/lac/block_sparsity_pattern.h>\n#include <deal.II/lac/constraint_matrix.h>\n\n#include <deal.II/grid/tria.h>\n#include <deal.II/grid/grid_generator.h>\n#include <deal.II/grid/tria_accessor.h>\n#include <deal.II/grid/tria_iterator.h>\n#include <deal.II/grid/grid_tools.h>\n#include <deal.II/grid/grid_refinement.h>\n\n#include <deal.II/dofs/dof_handler.h>\n#include <deal.II/dofs/dof_renumbering.h>\n#include <deal.II/dofs/dof_accessor.h>\n#include <deal.II/dofs/dof_tools.h>\n\n#include <deal.II/fe/fe_q.h>\n#include <deal.II/fe/fe_system.h>\n#include <deal.II/fe/fe_values.h>\n\n#include <deal.II/numerics/vector_tools.h>\n#include <deal.II/numerics/data_out.h>\n#include <deal.II/numerics/error_estimator.h>\n#include <deal.II/numerics/solution_transfer.h>\n\n// Then we need to include some header files that provide vector, matrix, and\n// preconditioner classes that implement interfaces to the respective Trilinos\n// classes. In particular, we will need interfaces to the matrix and vector\n// classes based on Trilinos as well as Trilinos preconditioners:\n#include <deal.II/lac/trilinos_sparse_matrix.h>\n#include <deal.II/lac/trilinos_block_sparse_matrix.h>\n#include <deal.II/lac/trilinos_vector.h>\n#include <deal.II/lac/trilinos_block_vector.h>\n#include <deal.II/lac/trilinos_precondition.h>\n\n// Finally, here are two C++ headers that haven't been included yet by one of\n// the aforelisted header files:\n#include <fstream>\n#include <sstream>\n#include <limits>\n\n\n// At the end of this top-matter, we import all deal.II names into the global\n// namespace:\nnamespace Step31\n{\n  using namespace dealii;\n\n\n  // @sect3{Equation data}\n\n  // Again, the next stage in the program is the definition of the equation\n  // data, that is, the various boundary conditions, the right hand sides and\n  // the initial condition (remember that we're about to solve a\n  // time-dependent system). The basic strategy for this definition is the\n  // same as in step-22. Regarding the details, though, there are some\n  // differences.\n\n  // The first thing is that we don't set any non-homogenous boundary\n  // conditions on the velocity, since as is explained in the introduction we\n  // will use no-flux conditions $\\mathbf{n}\\cdot\\mathbf{u}=0$. So what is\n  // left are <code>dim-1</code> conditions for the tangential part of the\n  // normal component of the stress tensor, $\\textbf{n} \\cdot [p \\textbf{1} -\n  // \\eta\\varepsilon(\\textbf{u})]$; we assume homogenous values for these\n  // components, i.e. a natural boundary condition that requires no specific\n  // action (it appears as a zero term in the right hand side of the weak\n  // form).\n  //\n  // For the temperature <i>T</i>, we assume no thermal energy flux,\n  // i.e. $\\mathbf{n} \\cdot \\kappa \\nabla T=0$. This, again, is a boundary\n  // condition that does not require us to do anything in particular.\n  //\n  // Secondly, we have to set initial conditions for the temperature (no\n  // initial conditions are required for the velocity and pressure, since the\n  // Stokes equations for the quasi-stationary case we consider here have no\n  // time derivatives of the velocity or pressure). Here, we choose a very\n  // simple test case, where the initial temperature is zero, and all dynamics\n  // are driven by the temperature right hand side.\n  //\n  // Thirdly, we need to define the right hand side of the temperature\n  // equation. We choose it to be constant within three circles (or spheres in\n  // 3d) somewhere at the bottom of the domain, as explained in the\n  // introduction, and zero outside.\n  //\n  // Finally, or maybe firstly, at the top of this namespace, we define the\n  // various material constants we need ($\\eta,\\kappa$, density $\\rho$ and the\n  // thermal expansion coefficient $\\beta$):\n  namespace EquationData\n  {\n    const double eta = 1;\n    const double kappa = 1e-6;\n    const double beta = 10;\n    const double density = 1;\n\n\n    template <int dim>\n    class TemperatureInitialValues : public Function<dim>\n    {\n    public:\n      TemperatureInitialValues () : Function<dim>(1) {}\n\n      virtual double value (const Point<dim>   &p,\n                            const unsigned int  component = 0) const;\n\n      virtual void vector_value (const Point<dim> &p,\n                                 Vector<double>   &value) const;\n    };\n\n\n    template <int dim>\n    double\n    TemperatureInitialValues<dim>::value (const Point<dim> &,\n                                          const unsigned int) const\n    {\n      return 0;\n    }\n\n\n    template <int dim>\n    void\n    TemperatureInitialValues<dim>::vector_value (const Point<dim> &p,\n                                                 Vector<double>   &values) const\n    {\n      for (unsigned int c=0; c<this->n_components; ++c)\n        values(c) = TemperatureInitialValues<dim>::value (p, c);\n    }\n\n\n    template <int dim>\n    class TemperatureRightHandSide : public Function<dim>\n    {\n    public:\n      TemperatureRightHandSide () : Function<dim>(1) {}\n\n      virtual double value (const Point<dim>   &p,\n                            const unsigned int  component = 0) const;\n\n      virtual void vector_value (const Point<dim> &p,\n                                 Vector<double>   &value) const;\n    };\n\n\n    template <int dim>\n    double\n    TemperatureRightHandSide<dim>::value (const Point<dim> &p,\n                                          const unsigned int component) const\n    {\n      Assert (component == 0,\n              ExcMessage (\"Invalid operation for a scalar function.\"));\n\n      Assert ((dim==2) || (dim==3), ExcNotImplemented());\n\n      static const Point<dim> source_centers[3]\n        = { (dim == 2 ? Point<dim>(.3,.1) : Point<dim>(.3,.5,.1)),\n            (dim == 2 ? Point<dim>(.45,.1) : Point<dim>(.45,.5,.1)),\n            (dim == 2 ? Point<dim>(.75,.1) : Point<dim>(.75,.5,.1))\n          };\n      static const double source_radius\n        = (dim == 2 ? 1./32 : 1./8);\n\n      return ((source_centers[0].distance (p) < source_radius)\n              ||\n              (source_centers[1].distance (p) < source_radius)\n              ||\n              (source_centers[2].distance (p) < source_radius)\n              ?\n              1\n              :\n              0);\n    }\n\n\n    template <int dim>\n    void\n    TemperatureRightHandSide<dim>::vector_value (const Point<dim> &p,\n                                                 Vector<double>   &values) const\n    {\n      for (unsigned int c=0; c<this->n_components; ++c)\n        values(c) = TemperatureRightHandSide<dim>::value (p, c);\n    }\n  }\n\n\n\n  // @sect3{Linear solvers and preconditioners}\n\n  // This section introduces some objects that are used for the solution of\n  // the linear equations of the Stokes system that we need to solve in each\n  // time step. Many of the ideas used here are the same as in step-20, where\n  // Schur complement based preconditioners and solvers have been introduced,\n  // with the actual interface taken from step-22 (in particular the\n  // discussion in the \"Results\" section of step-22, in which we introduce\n  // alternatives to the direct Schur complement approach). Note, however,\n  // that here we don't use the Schur complement to solve the Stokes\n  // equations, though an approximate Schur complement (the mass matrix on the\n  // pressure space) appears in the preconditioner.\n  namespace LinearSolvers\n  {\n\n    // @sect4{The <code>InverseMatrix</code> class template}\n\n    // This class is an interface to calculate the action of an \"inverted\"\n    // matrix on a vector (using the <code>vmult</code> operation) in the same\n    // way as the corresponding class in step-22: when the product of an\n    // object of this class is requested, we solve a linear equation system\n    // with that matrix using the CG method, accelerated by a preconditioner\n    // of (templated) class <code>Preconditioner</code>.\n    //\n    // In a minor deviation from the implementation of the same class in\n    // step-22 (and step-20), we make the <code>vmult</code> function take any\n    // kind of vector type (it will yield compiler errors, however, if the\n    // matrix does not allow a matrix-vector product with this kind of\n    // vector).\n    //\n    // Secondly, we catch any exceptions that the solver may have thrown. The\n    // reason is as follows: When debugging a program like this one\n    // occasionally makes a mistake of passing an indefinite or non-symmetric\n    // matrix or preconditioner to the current class. The solver will, in that\n    // case, not converge and throw a run-time exception. If not caught here\n    // it will propagate up the call stack and may end up in\n    // <code>main()</code> where we output an error message that will say that\n    // the CG solver failed. The question then becomes: Which CG solver? The\n    // one that inverted the mass matrix? The one that inverted the top left\n    // block with the Laplace operator? Or a CG solver in one of the several\n    // other nested places where we use linear solvers in the current code? No\n    // indication about this is present in a run-time exception because it\n    // doesn't store the stack of calls through which we got to the place\n    // where the exception was generated.\n    //\n    // So rather than letting the exception propagate freely up to\n    // <code>main()</code> we realize that there is little that an outer\n    // function can do if the inner solver fails and rather convert the\n    // run-time exception into an assertion that fails and triggers a call to\n    // <code>abort()</code>, allowing us to trace back in a debugger how we\n    // got to the current place.\n    template <class Matrix, class Preconditioner>\n    class InverseMatrix : public Subscriptor\n    {\n    public:\n      InverseMatrix (const Matrix         &m,\n                     const Preconditioner &preconditioner);\n\n\n      template <typename VectorType>\n      void vmult (VectorType       &dst,\n                  const VectorType &src) const;\n\n    private:\n      const SmartPointer<const Matrix> matrix;\n      const Preconditioner &preconditioner;\n    };\n\n\n    template <class Matrix, class Preconditioner>\n    InverseMatrix<Matrix,Preconditioner>::\n    InverseMatrix (const Matrix &m,\n                   const Preconditioner &preconditioner)\n      :\n      matrix (&m),\n      preconditioner (preconditioner)\n    {}\n\n\n\n    template <class Matrix, class Preconditioner>\n    template <typename VectorType>\n    void\n    InverseMatrix<Matrix,Preconditioner>::\n    vmult (VectorType       &dst,\n           const VectorType &src) const\n    {\n      SolverControl solver_control (src.size(), 1e-7*src.l2_norm());\n      SolverCG<VectorType> cg (solver_control);\n\n      dst = 0;\n\n      try\n        {\n          cg.solve (*matrix, dst, src, preconditioner);\n        }\n      catch (std::exception &e)\n        {\n          Assert (false, ExcMessage(e.what()));\n        }\n    }\n\n    // @sect4{Schur complement preconditioner}\n\n    // This is the implementation of the Schur complement preconditioner as\n    // described in detail in the introduction. As opposed to step-20 and\n    // step-22, we solve the block system all-at-once using GMRES, and use the\n    // Schur complement of the block structured matrix to build a good\n    // preconditioner instead.\n    //\n    // Let's have a look at the ideal preconditioner matrix\n    // $P=\\left(\\begin{array}{cc} A & 0 \\\\ B & -S \\end{array}\\right)$\n    // described in the introduction. If we apply this matrix in the solution\n    // of a linear system, convergence of an iterative GMRES solver will be\n    // governed by the matrix @f{eqnarray*} P^{-1}\\left(\\begin{array}{cc} A &\n    // B^T \\\\ B & 0 \\end{array}\\right) = \\left(\\begin{array}{cc} I & A^{-1}\n    // B^T \\\\ 0 & I \\end{array}\\right), @f} which indeed is very simple. A\n    // GMRES solver based on exact matrices would converge in one iteration,\n    // since all eigenvalues are equal (any Krylov method takes at most as\n    // many iterations as there are distinct eigenvalues). Such a\n    // preconditioner for the blocked Stokes system has been proposed by\n    // Silvester and Wathen (\"Fast iterative solution of stabilised Stokes\n    // systems part II.  Using general block preconditioners\", SIAM\n    // J. Numer. Anal., 31 (1994), pp. 1352-1367).\n    //\n    // Replacing <i>P</i> by $\\tilde{P}$ keeps that spirit alive: the product\n    // $P^{-1} A$ will still be close to a matrix with eigenvalues 1 with a\n    // distribution that does not depend on the problem size. This lets us\n    // hope to be able to get a number of GMRES iterations that is\n    // problem-size independent.\n    //\n    // The deal.II users who have already gone through the step-20 and step-22\n    // tutorials can certainly imagine how we're going to implement this.  We\n    // replace the exact inverse matrices in $P^{-1}$ by some approximate\n    // inverses built from the InverseMatrix class, and the inverse Schur\n    // complement will be approximated by the pressure mass matrix $M_p$\n    // (weighted by $\\eta^{-1}$ as mentioned in the introduction). As pointed\n    // out in the results section of step-22, we can replace the exact inverse\n    // of <i>A</i> by just the application of a preconditioner, in this case\n    // on a vector Laplace matrix as was explained in the introduction. This\n    // does increase the number of (outer) GMRES iterations, but is still\n    // significantly cheaper than an exact inverse, which would require\n    // between 20 and 35 CG iterations for <em>each</em> outer solver step\n    // (using the AMG preconditioner).\n    //\n    // Having the above explanations in mind, we define a preconditioner class\n    // with a <code>vmult</code> functionality, which is all we need for the\n    // interaction with the usual solver functions further below in the\n    // program code.\n    //\n    // First the declarations. These are similar to the definition of the\n    // Schur complement in step-20, with the difference that we need some more\n    // preconditioners in the constructor and that the matrices we use here\n    // are built upon Trilinos:\n    template <class PreconditionerA, class PreconditionerMp>\n    class BlockSchurPreconditioner : public Subscriptor\n    {\n    public:\n      BlockSchurPreconditioner (\n        const TrilinosWrappers::BlockSparseMatrix     &S,\n        const InverseMatrix<TrilinosWrappers::SparseMatrix,\n        PreconditionerMp>         &Mpinv,\n        const PreconditionerA                         &Apreconditioner);\n\n      void vmult (TrilinosWrappers::BlockVector       &dst,\n                  const TrilinosWrappers::BlockVector &src) const;\n\n    private:\n      const SmartPointer<const TrilinosWrappers::BlockSparseMatrix> stokes_matrix;\n      const SmartPointer<const InverseMatrix<TrilinosWrappers::SparseMatrix,\n            PreconditionerMp > > m_inverse;\n      const PreconditionerA &a_preconditioner;\n\n      mutable TrilinosWrappers::Vector tmp;\n    };\n\n\n\n    template <class PreconditionerA, class PreconditionerMp>\n    BlockSchurPreconditioner<PreconditionerA, PreconditionerMp>::\n    BlockSchurPreconditioner(const TrilinosWrappers::BlockSparseMatrix &S,\n                             const InverseMatrix<TrilinosWrappers::SparseMatrix,\n                             PreconditionerMp>      &Mpinv,\n                             const PreconditionerA                      &Apreconditioner)\n      :\n      stokes_matrix           (&S),\n      m_inverse               (&Mpinv),\n      a_preconditioner        (Apreconditioner),\n      tmp                     (stokes_matrix->block(1,1).m())\n    {}\n\n\n    // Next is the <code>vmult</code> function. We implement the action of\n    // $P^{-1}$ as described above in three successive steps.  In formulas, we\n    // want to compute $Y=P^{-1}X$ where $X,Y$ are both vectors with two block\n    // components.\n    //\n    // The first step multiplies the velocity part of the vector by a\n    // preconditioner of the matrix <i>A</i>, i.e. we compute $Y_0={\\tilde\n    // A}^{-1}X_0$.  The resulting velocity vector is then multiplied by $B$\n    // and subtracted from the pressure, i.e. we want to compute $X_1-BY_0$.\n    // This second step only acts on the pressure vector and is accomplished\n    // by the residual function of our matrix classes, except that the sign is\n    // wrong. Consequently, we change the sign in the temporary pressure\n    // vector and finally multiply by the inverse pressure mass matrix to get\n    // the final pressure vector, completing our work on the Stokes\n    // preconditioner:\n    template <class PreconditionerA, class PreconditionerMp>\n    void\n    BlockSchurPreconditioner<PreconditionerA, PreconditionerMp>::\n    vmult (TrilinosWrappers::BlockVector       &dst,\n           const TrilinosWrappers::BlockVector &src) const\n    {\n      a_preconditioner.vmult (dst.block(0), src.block(0));\n      stokes_matrix->block(1,0).residual(tmp, dst.block(0), src.block(1));\n      tmp *= -1;\n      m_inverse->vmult (dst.block(1), tmp);\n    }\n  }\n\n\n\n  // @sect3{The <code>BoussinesqFlowProblem</code> class template}\n\n  // The definition of the class that defines the top-level logic of solving\n  // the time-dependent Boussinesq problem is mainly based on the step-22\n  // tutorial program. The main differences are that now we also have to solve\n  // for the temperature equation, which forces us to have a second DoFHandler\n  // object for the temperature variable as well as matrices, right hand\n  // sides, and solution vectors for the current and previous time steps. As\n  // mentioned in the introduction, all linear algebra objects are going to\n  // use wrappers of the corresponding Trilinos functionality.\n  //\n  // The member functions of this class are reminiscent of step-21, where we\n  // also used a staggered scheme that first solve the flow equations (here\n  // the Stokes equations, in step-21 Darcy flow) and then update the advected\n  // quantity (here the temperature, there the saturation). The functions that\n  // are new are mainly concerned with determining the time step, as well as\n  // the proper size of the artificial viscosity stabilization.\n  //\n  // The last three variables indicate whether the various matrices or\n  // preconditioners need to be rebuilt the next time the corresponding build\n  // functions are called. This allows us to move the corresponding\n  // <code>if</code> into the respective function and thereby keeping our main\n  // <code>run()</code> function clean and easy to read.\n  template <int dim>\n  class BoussinesqFlowProblem\n  {\n  public:\n    BoussinesqFlowProblem ();\n    void run ();\n\n  private:\n    void setup_dofs ();\n    void assemble_stokes_preconditioner ();\n    void build_stokes_preconditioner ();\n    void assemble_stokes_system ();\n    void assemble_temperature_system (const double maximal_velocity);\n    void assemble_temperature_matrix ();\n    double get_maximal_velocity () const;\n    std::pair<double,double> get_extrapolated_temperature_range () const;\n    void solve ();\n    void output_results () const;\n    void refine_mesh (const unsigned int max_grid_level);\n\n    double\n    compute_viscosity(const std::vector<double>          &old_temperature,\n                      const std::vector<double>          &old_old_temperature,\n                      const std::vector<Tensor<1,dim> > &old_temperature_grads,\n                      const std::vector<Tensor<1,dim> > &old_old_temperature_grads,\n                      const std::vector<double>          &old_temperature_laplacians,\n                      const std::vector<double>          &old_old_temperature_laplacians,\n                      const std::vector<Tensor<1,dim> > &old_velocity_values,\n                      const std::vector<Tensor<1,dim> > &old_old_velocity_values,\n                      const std::vector<double>          &gamma_values,\n                      const double                        global_u_infty,\n                      const double                        global_T_variation,\n                      const double                        cell_diameter) const;\n\n\n    Triangulation<dim>                  triangulation;\n    double                              global_Omega_diameter;\n\n    const unsigned int                  stokes_degree;\n    FESystem<dim>                       stokes_fe;\n    DoFHandler<dim>                     stokes_dof_handler;\n    ConstraintMatrix                    stokes_constraints;\n\n    std::vector<unsigned int>           stokes_block_sizes;\n    TrilinosWrappers::BlockSparseMatrix stokes_matrix;\n    TrilinosWrappers::BlockSparseMatrix stokes_preconditioner_matrix;\n\n    TrilinosWrappers::BlockVector       stokes_solution;\n    TrilinosWrappers::BlockVector       old_stokes_solution;\n    TrilinosWrappers::BlockVector       stokes_rhs;\n\n\n    const unsigned int                  temperature_degree;\n    FE_Q<dim>                           temperature_fe;\n    DoFHandler<dim>                     temperature_dof_handler;\n    ConstraintMatrix                    temperature_constraints;\n\n    TrilinosWrappers::SparseMatrix      temperature_mass_matrix;\n    TrilinosWrappers::SparseMatrix      temperature_stiffness_matrix;\n    TrilinosWrappers::SparseMatrix      temperature_matrix;\n\n    TrilinosWrappers::Vector            temperature_solution;\n    TrilinosWrappers::Vector            old_temperature_solution;\n    TrilinosWrappers::Vector            old_old_temperature_solution;\n    TrilinosWrappers::Vector            temperature_rhs;\n\n\n    double                              time_step;\n    double                              old_time_step;\n    unsigned int                        timestep_number;\n\n    std_cxx1x::shared_ptr<TrilinosWrappers::PreconditionAMG> Amg_preconditioner;\n    std_cxx1x::shared_ptr<TrilinosWrappers::PreconditionIC>  Mp_preconditioner;\n\n    bool                                rebuild_stokes_matrix;\n    bool                                rebuild_temperature_matrices;\n    bool                                rebuild_stokes_preconditioner;\n  };\n\n\n  // @sect3{BoussinesqFlowProblem class implementation}\n\n  // @sect4{BoussinesqFlowProblem::BoussinesqFlowProblem}\n  //\n  // The constructor of this class is an extension of the constructor in\n  // step-22. We need to add the various variables that concern the\n  // temperature. As discussed in the introduction, we are going to use\n  // $Q_2\\times Q_1$ (Taylor-Hood) elements again for the Stokes part, and\n  // $Q_2$ elements for the temperature. However, by using variables that\n  // store the polynomial degree of the Stokes and temperature finite\n  // elements, it is easy to consistently modify the degree of the elements as\n  // well as all quadrature formulas used on them downstream. Moreover, we\n  // initialize the time stepping as well as the options for matrix assembly\n  // and preconditioning:\n  template <int dim>\n  BoussinesqFlowProblem<dim>::BoussinesqFlowProblem ()\n    :\n    triangulation (Triangulation<dim>::maximum_smoothing),\n\n    stokes_degree (1),\n    stokes_fe (FE_Q<dim>(stokes_degree+1), dim,\n               FE_Q<dim>(stokes_degree), 1),\n    stokes_dof_handler (triangulation),\n\n    temperature_degree (2),\n    temperature_fe (temperature_degree),\n    temperature_dof_handler (triangulation),\n\n    time_step (0),\n    old_time_step (0),\n    timestep_number (0),\n    rebuild_stokes_matrix (true),\n    rebuild_temperature_matrices (true),\n    rebuild_stokes_preconditioner (true)\n  {}\n\n\n\n  // @sect4{BoussinesqFlowProblem::get_maximal_velocity}\n\n  // Starting the real functionality of this class is a helper function that\n  // determines the maximum ($L_\\infty$) velocity in the domain (at the\n  // quadrature points, in fact). How it works should be relatively obvious to\n  // all who have gotten to this point of the tutorial. Note that since we are\n  // only interested in the velocity, rather than using\n  // <code>stokes_fe_values.get_function_values</code> to get the values of\n  // the entire Stokes solution (velocities and pressures) we use\n  // <code>stokes_fe_values[velocities].get_function_values</code> to extract\n  // only the velocities part. This has the additional benefit that we get it\n  // as a Tensor<1,dim>, rather than some components in a Vector<double>,\n  // allowing us to process it right away using the <code>norm()</code>\n  // function to get the magnitude of the velocity.\n  //\n  // The only point worth thinking about a bit is how to choose the quadrature\n  // points we use here. Since the goal of this function is to find the\n  // maximal velocity over a domain by looking at quadrature points on each\n  // cell. So we should ask how we should best choose these quadrature points\n  // on each cell. To this end, recall that if we had a single $Q_1$ field\n  // (rather than the vector-valued field of higher order) then the maximum\n  // would be attained at a vertex of the mesh. In other words, we should use\n  // the QTrapez class that has quadrature points only at the vertices of\n  // cells.\n  //\n  // For higher order shape functions, the situation is more complicated: the\n  // maxima and minima may be attained at points between the support points of\n  // shape functions (for the usual $Q_p$ elements the support points are the\n  // equidistant Lagrange interpolation points); furthermore, since we are\n  // looking for the maximum magnitude of a vector-valued quantity, we can\n  // even less say with certainty where the set of potential maximal points\n  // are. Nevertheless, intuitively if not provably, the Lagrange\n  // interpolation points appear to be a better choice than the Gauss points.\n  //\n  // There are now different methods to produce a quadrature formula with\n  // quadrature points equal to the interpolation points of the finite\n  // element. One option would be to use the\n  // FiniteElement::get_unit_support_points() function, reduce the output to a\n  // unique set of points to avoid duplicate function evaluations, and create\n  // a Quadrature object using these points. Another option, chosen here, is\n  // to use the QTrapez class and combine it with the QIterated class that\n  // repeats the QTrapez formula on a number of sub-cells in each coordinate\n  // direction. To cover all support points, we need to iterate it\n  // <code>stokes_degree+1</code> times since this is the polynomial degree of\n  // the Stokes element in use:\n  template <int dim>\n  double BoussinesqFlowProblem<dim>::get_maximal_velocity () const\n  {\n    const QIterated<dim> quadrature_formula (QTrapez<1>(),\n                                             stokes_degree+1);\n    const unsigned int n_q_points = quadrature_formula.size();\n\n    FEValues<dim> fe_values (stokes_fe, quadrature_formula, update_values);\n    std::vector<Tensor<1,dim> > velocity_values(n_q_points);\n    double max_velocity = 0;\n\n    const FEValuesExtractors::Vector velocities (0);\n\n    typename DoFHandler<dim>::active_cell_iterator\n    cell = stokes_dof_handler.begin_active(),\n    endc = stokes_dof_handler.end();\n    for (; cell!=endc; ++cell)\n      {\n        fe_values.reinit (cell);\n        fe_values[velocities].get_function_values (stokes_solution,\n                                                   velocity_values);\n\n        for (unsigned int q=0; q<n_q_points; ++q)\n          max_velocity = std::max (max_velocity, velocity_values[q].norm());\n      }\n\n    return max_velocity;\n  }\n\n\n\n\n  // @sect4{BoussinesqFlowProblem::get_extrapolated_temperature_range}\n\n  // Next a function that determines the minimum and maximum temperature at\n  // quadrature points inside $\\Omega$ when extrapolated from the two previous\n  // time steps to the current one. We need this information in the\n  // computation of the artificial viscosity parameter $\\nu$ as discussed in\n  // the introduction.\n  //\n  // The formula for the extrapolated temperature is\n  // $\\left(1+\\frac{k_n}{k_{n-1}} \\right)T^{n-1} + \\frac{k_n}{k_{n-1}}\n  // T^{n-2}$. The way to compute it is to loop over all quadrature points and\n  // update the maximum and minimum value if the current value is\n  // bigger/smaller than the previous one. We initialize the variables that\n  // store the max and min before the loop over all quadrature points by the\n  // smallest and the largest number representable as a double. Then we know\n  // for a fact that it is larger/smaller than the minimum/maximum and that\n  // the loop over all quadrature points is ultimately going to update the\n  // initial value with the correct one.\n  //\n  // The only other complication worth mentioning here is that in the first\n  // time step, $T^{k-2}$ is not yet available of course. In that case, we can\n  // only use $T^{k-1}$ which we have from the initial temperature. As\n  // quadrature points, we use the same choice as in the previous function\n  // though with the difference that now the number of repetitions is\n  // determined by the polynomial degree of the temperature field.\n  template <int dim>\n  std::pair<double,double>\n  BoussinesqFlowProblem<dim>::get_extrapolated_temperature_range () const\n  {\n    const QIterated<dim> quadrature_formula (QTrapez<1>(),\n                                             temperature_degree);\n    const unsigned int n_q_points = quadrature_formula.size();\n\n    FEValues<dim> fe_values (temperature_fe, quadrature_formula,\n                             update_values);\n    std::vector<double> old_temperature_values(n_q_points);\n    std::vector<double> old_old_temperature_values(n_q_points);\n\n    if (timestep_number != 0)\n      {\n        double min_temperature = std::numeric_limits<double>::max(),\n               max_temperature = -std::numeric_limits<double>::max();\n\n        typename DoFHandler<dim>::active_cell_iterator\n        cell = temperature_dof_handler.begin_active(),\n        endc = temperature_dof_handler.end();\n        for (; cell!=endc; ++cell)\n          {\n            fe_values.reinit (cell);\n            fe_values.get_function_values (old_temperature_solution,\n                                           old_temperature_values);\n            fe_values.get_function_values (old_old_temperature_solution,\n                                           old_old_temperature_values);\n\n            for (unsigned int q=0; q<n_q_points; ++q)\n              {\n                const double temperature =\n                  (1. + time_step/old_time_step) * old_temperature_values[q]-\n                  time_step/old_time_step * old_old_temperature_values[q];\n\n                min_temperature = std::min (min_temperature, temperature);\n                max_temperature = std::max (max_temperature, temperature);\n              }\n          }\n\n        return std::make_pair(min_temperature, max_temperature);\n      }\n    else\n      {\n        double min_temperature = std::numeric_limits<double>::max(),\n               max_temperature = -std::numeric_limits<double>::max();\n\n        typename DoFHandler<dim>::active_cell_iterator\n        cell = temperature_dof_handler.begin_active(),\n        endc = temperature_dof_handler.end();\n        for (; cell!=endc; ++cell)\n          {\n            fe_values.reinit (cell);\n            fe_values.get_function_values (old_temperature_solution,\n                                           old_temperature_values);\n\n            for (unsigned int q=0; q<n_q_points; ++q)\n              {\n                const double temperature = old_temperature_values[q];\n\n                min_temperature = std::min (min_temperature, temperature);\n                max_temperature = std::max (max_temperature, temperature);\n              }\n          }\n\n        return std::make_pair(min_temperature, max_temperature);\n      }\n  }\n\n\n\n  // @sect4{BoussinesqFlowProblem::compute_viscosity}\n\n  // The last of the tool functions computes the artificial viscosity\n  // parameter $\\nu|_K$ on a cell $K$ as a function of the extrapolated\n  // temperature, its gradient and Hessian (second derivatives), the velocity,\n  // the right hand side $\\gamma$ all on the quadrature points of the current\n  // cell, and various other parameters as described in detail in the\n  // introduction.\n  //\n  // There are some universal constants worth mentioning here. First, we need\n  // to fix $\\beta$; we choose $\\beta=0.015\\cdot dim$, a choice discussed in\n  // detail in the results section of this tutorial program. The second is the\n  // exponent $\\alpha$; $\\alpha=1$ appears to work fine for the current\n  // program, even though some additional benefit might be expected from\n  // chosing $\\alpha = 2$. Finally, there is one thing that requires special\n  // casing: In the first time step, the velocity equals zero, and the formula\n  // for $\\nu|_K$ is not defined. In that case, we return $\\nu|_K=5\\cdot 10^3\n  // \\cdot h_K$, a choice admittedly more motivated by heuristics than\n  // anything else (it is in the same order of magnitude, however, as the\n  // value returned for most cells on the second time step).\n  //\n  // The rest of the function should be mostly obvious based on the material\n  // discussed in the introduction:\n  template <int dim>\n  double\n  BoussinesqFlowProblem<dim>::\n  compute_viscosity (const std::vector<double>          &old_temperature,\n                     const std::vector<double>          &old_old_temperature,\n                     const std::vector<Tensor<1,dim> > &old_temperature_grads,\n                     const std::vector<Tensor<1,dim> > &old_old_temperature_grads,\n                     const std::vector<double>          &old_temperature_laplacians,\n                     const std::vector<double>          &old_old_temperature_laplacians,\n                     const std::vector<Tensor<1,dim> > &old_velocity_values,\n                     const std::vector<Tensor<1,dim> > &old_old_velocity_values,\n                     const std::vector<double>          &gamma_values,\n                     const double                        global_u_infty,\n                     const double                        global_T_variation,\n                     const double                        cell_diameter) const\n  {\n    const double beta = 0.015 * dim;\n    const double alpha = 1;\n\n    if (global_u_infty == 0)\n      return 5e-3 * cell_diameter;\n\n    const unsigned int n_q_points = old_temperature.size();\n\n    double max_residual = 0;\n    double max_velocity = 0;\n\n    for (unsigned int q=0; q < n_q_points; ++q)\n      {\n        const Tensor<1,dim> u = (old_velocity_values[q] +\n                                 old_old_velocity_values[q]) / 2;\n\n        const double dT_dt = (old_temperature[q] - old_old_temperature[q])\n                             / old_time_step;\n        const double u_grad_T = u * (old_temperature_grads[q] +\n                                     old_old_temperature_grads[q]) / 2;\n\n        const double kappa_Delta_T = EquationData::kappa\n                                     * (old_temperature_laplacians[q] +\n                                        old_old_temperature_laplacians[q]) / 2;\n\n        const double residual\n          = std::abs((dT_dt + u_grad_T - kappa_Delta_T - gamma_values[q]) *\n                     std::pow((old_temperature[q]+old_old_temperature[q]) / 2,\n                              alpha-1.));\n\n        max_residual = std::max (residual,        max_residual);\n        max_velocity = std::max (std::sqrt (u*u), max_velocity);\n      }\n\n    const double c_R = std::pow (2., (4.-2*alpha)/dim);\n    const double global_scaling = c_R * global_u_infty * global_T_variation *\n                                  std::pow(global_Omega_diameter, alpha - 2.);\n\n    return (beta *\n            max_velocity *\n            std::min (cell_diameter,\n                      std::pow(cell_diameter,alpha) *\n                      max_residual / global_scaling));\n  }\n\n\n\n  // @sect4{BoussinesqFlowProblem::setup_dofs}\n  //\n  // This is the function that sets up the DoFHandler objects we have here\n  // (one for the Stokes part and one for the temperature part) as well as set\n  // to the right sizes the various objects required for the linear algebra in\n  // this program. Its basic operations are similar to what we do in step-22.\n  //\n  // The body of the function first enumerates all degrees of freedom for the\n  // Stokes and temperature systems. For the Stokes part, degrees of freedom\n  // are then sorted to ensure that velocities precede pressure DoFs so that\n  // we can partition the Stokes matrix into a $2\\times 2$ matrix. As a\n  // difference to step-22, we do not perform any additional DoF\n  // renumbering. In that program, it paid off since our solver was heavily\n  // dependent on ILU's, whereas we use AMG here which is not sensitive to the\n  // DoF numbering. The IC preconditioner for the inversion of the pressure\n  // mass matrix would of course take advantage of a Cuthill-McKee like\n  // renumbering, but its costs are low compared to the velocity portion, so\n  // the additional work does not pay off.\n  //\n  // We then proceed with the generation of the hanging node constraints that\n  // arise from adaptive grid refinement for both DoFHandler objects. For the\n  // velocity, we impose no-flux boundary conditions $\\mathbf{u}\\cdot\n  // \\mathbf{n}=0$ by adding constraints to the object that already stores the\n  // hanging node constraints matrix. The second parameter in the function\n  // describes the first of the velocity components in the total dof vector,\n  // which is zero here. The variable <code>no_normal_flux_boundaries</code>\n  // denotes the boundary indicators for which to set the no flux boundary\n  // conditions; here, this is boundary indicator zero.\n  //\n  // After having done so, we count the number of degrees of freedom in the\n  // various blocks:\n  template <int dim>\n  void BoussinesqFlowProblem<dim>::setup_dofs ()\n  {\n    std::vector<unsigned int> stokes_sub_blocks (dim+1,0);\n    stokes_sub_blocks[dim] = 1;\n\n    {\n      stokes_dof_handler.distribute_dofs (stokes_fe);\n      DoFRenumbering::component_wise (stokes_dof_handler, stokes_sub_blocks);\n\n      stokes_constraints.clear ();\n      DoFTools::make_hanging_node_constraints (stokes_dof_handler,\n                                               stokes_constraints);\n      std::set<types::boundary_id> no_normal_flux_boundaries;\n      no_normal_flux_boundaries.insert (0);\n      VectorTools::compute_no_normal_flux_constraints (stokes_dof_handler, 0,\n                                                       no_normal_flux_boundaries,\n                                                       stokes_constraints);\n      stokes_constraints.close ();\n    }\n    {\n      temperature_dof_handler.distribute_dofs (temperature_fe);\n\n      temperature_constraints.clear ();\n      DoFTools::make_hanging_node_constraints (temperature_dof_handler,\n                                               temperature_constraints);\n      temperature_constraints.close ();\n    }\n\n    std::vector<unsigned int> stokes_dofs_per_block (2);\n    DoFTools::count_dofs_per_block (stokes_dof_handler, stokes_dofs_per_block,\n                                    stokes_sub_blocks);\n\n    const unsigned int n_u = stokes_dofs_per_block[0],\n                       n_p = stokes_dofs_per_block[1],\n                       n_T = temperature_dof_handler.n_dofs();\n\n    std::cout << \"Number of active cells: \"\n              << triangulation.n_active_cells()\n              << \" (on \"\n              << triangulation.n_levels()\n              << \" levels)\"\n              << std::endl\n              << \"Number of degrees of freedom: \"\n              << n_u + n_p + n_T\n              << \" (\" << n_u << '+' << n_p << '+'<< n_T <<')'\n              << std::endl\n              << std::endl;\n\n    // The next step is to create the sparsity pattern for the Stokes and\n    // temperature system matrices as well as the preconditioner matrix from\n    // which we build the Stokes preconditioner. As in step-22, we choose to\n    // create the pattern not as in the first few tutorial programs, but by\n    // using the blocked version of CompressedSimpleSparsityPattern.  The\n    // reason for doing this is mainly memory, that is, the SparsityPattern\n    // class would consume too much memory when used in three spatial\n    // dimensions as we intend to do for this program.\n    //\n    // So, we first release the memory stored in the matrices, then set up an\n    // object of type BlockCompressedSimpleSparsityPattern consisting of\n    // $2\\times 2$ blocks (for the Stokes system matrix and preconditioner) or\n    // CompressedSimpleSparsityPattern (for the temperature part). We then\n    // fill these objects with the nonzero pattern, taking into account that\n    // for the Stokes system matrix, there are no entries in the\n    // pressure-pressure block (but all velocity vector components couple with\n    // each other and with the pressure). Similarly, in the Stokes\n    // preconditioner matrix, only the diagonal blocks are nonzero, since we\n    // use the vector Laplacian as discussed in the introduction. This\n    // operator only couples each vector component of the Laplacian with\n    // itself, but not with the other vector components. (Application of the\n    // constraints resulting from the no-flux boundary conditions will couple\n    // vector components at the boundary again, however.)\n    //\n    // When generating the sparsity pattern, we directly apply the constraints\n    // from hanging nodes and no-flux boundary conditions. This approach was\n    // already used in step-27, but is different from the one in early\n    // tutorial programs where we first built the original sparsity pattern\n    // and only then added the entries resulting from constraints. The reason\n    // for doing so is that later during assembly we are going to distribute\n    // the constraints immediately when transferring local to global\n    // dofs. Consequently, there will be no data written at positions of\n    // constrained degrees of freedom, so we can let the\n    // DoFTools::make_sparsity_pattern function omit these entries by setting\n    // the last boolean flag to <code>false</code>. Once the sparsity pattern\n    // is ready, we can use it to initialize the Trilinos matrices. Since the\n    // Trilinos matrices store the sparsity pattern internally, there is no\n    // need to keep the sparsity pattern around after the initialization of\n    // the matrix.\n    stokes_block_sizes.resize (2);\n    stokes_block_sizes[0] = n_u;\n    stokes_block_sizes[1] = n_p;\n    {\n      stokes_matrix.clear ();\n\n      BlockCompressedSimpleSparsityPattern csp (2,2);\n\n      csp.block(0,0).reinit (n_u, n_u);\n      csp.block(0,1).reinit (n_u, n_p);\n      csp.block(1,0).reinit (n_p, n_u);\n      csp.block(1,1).reinit (n_p, n_p);\n\n      csp.collect_sizes ();\n\n      Table<2,DoFTools::Coupling> coupling (dim+1, dim+1);\n\n      for (unsigned int c=0; c<dim+1; ++c)\n        for (unsigned int d=0; d<dim+1; ++d)\n          if (! ((c==dim) && (d==dim)))\n            coupling[c][d] = DoFTools::always;\n          else\n            coupling[c][d] = DoFTools::none;\n\n      DoFTools::make_sparsity_pattern (stokes_dof_handler, coupling, csp,\n                                       stokes_constraints, false);\n\n      stokes_matrix.reinit (csp);\n    }\n\n    {\n      Amg_preconditioner.reset ();\n      Mp_preconditioner.reset ();\n      stokes_preconditioner_matrix.clear ();\n\n      BlockCompressedSimpleSparsityPattern csp (2,2);\n\n      csp.block(0,0).reinit (n_u, n_u);\n      csp.block(0,1).reinit (n_u, n_p);\n      csp.block(1,0).reinit (n_p, n_u);\n      csp.block(1,1).reinit (n_p, n_p);\n\n      csp.collect_sizes ();\n\n      Table<2,DoFTools::Coupling> coupling (dim+1, dim+1);\n      for (unsigned int c=0; c<dim+1; ++c)\n        for (unsigned int d=0; d<dim+1; ++d)\n          if (c == d)\n            coupling[c][d] = DoFTools::always;\n          else\n            coupling[c][d] = DoFTools::none;\n\n      DoFTools::make_sparsity_pattern (stokes_dof_handler, coupling, csp,\n                                       stokes_constraints, false);\n\n      stokes_preconditioner_matrix.reinit (csp);\n    }\n\n    // The creation of the temperature matrix (or, rather, matrices, since we\n    // provide a temperature mass matrix and a temperature stiffness matrix,\n    // that will be added together for time discretization) follows the\n    // generation of the Stokes matrix &ndash; except that it is much easier\n    // here since we do not need to take care of any blocks or coupling\n    // between components. Note how we initialize the three temperature\n    // matrices: We only use the sparsity pattern for reinitialization of the\n    // first matrix, whereas we use the previously generated matrix for the\n    // two remaining reinits. The reason for doing so is that reinitialization\n    // from an already generated matrix allows Trilinos to reuse the sparsity\n    // pattern instead of generating a new one for each copy. This saves both\n    // some time and memory.\n    {\n      temperature_mass_matrix.clear ();\n      temperature_stiffness_matrix.clear ();\n      temperature_matrix.clear ();\n\n      CompressedSimpleSparsityPattern csp (n_T, n_T);\n      DoFTools::make_sparsity_pattern (temperature_dof_handler, csp,\n                                       temperature_constraints, false);\n\n      temperature_matrix.reinit (csp);\n      temperature_mass_matrix.reinit (temperature_matrix);\n      temperature_stiffness_matrix.reinit (temperature_matrix);\n    }\n\n    // Lastly, we set the vectors for the Stokes solutions $\\mathbf u^{n-1}$\n    // and $\\mathbf u^{n-2}$, as well as for the temperatures $T^{n}$,\n    // $T^{n-1}$ and $T^{n-2}$ (required for time stepping) and all the system\n    // right hand sides to their correct sizes and block structure:\n    stokes_solution.reinit (stokes_block_sizes);\n    old_stokes_solution.reinit (stokes_block_sizes);\n    stokes_rhs.reinit (stokes_block_sizes);\n\n    temperature_solution.reinit (temperature_dof_handler.n_dofs());\n    old_temperature_solution.reinit (temperature_dof_handler.n_dofs());\n    old_old_temperature_solution.reinit (temperature_dof_handler.n_dofs());\n\n    temperature_rhs.reinit (temperature_dof_handler.n_dofs());\n  }\n\n\n\n  // @sect4{BoussinesqFlowProblem::assemble_stokes_preconditioner}\n  //\n  // This function assembles the matrix we use for preconditioning the Stokes\n  // system. What we need are a vector Laplace matrix on the velocity\n  // components and a mass matrix weighted by $\\eta^{-1}$ on the pressure\n  // component. We start by generating a quadrature object of appropriate\n  // order, the FEValues object that can give values and gradients at the\n  // quadrature points (together with quadrature weights). Next we create data\n  // structures for the cell matrix and the relation between local and global\n  // DoFs. The vectors <code>grad_phi_u</code> and <code>phi_p</code> are\n  // going to hold the values of the basis functions in order to faster build\n  // up the local matrices, as was already done in step-22. Before we start\n  // the loop over all active cells, we have to specify which components are\n  // pressure and which are velocity.\n  template <int dim>\n  void\n  BoussinesqFlowProblem<dim>::assemble_stokes_preconditioner ()\n  {\n    stokes_preconditioner_matrix = 0;\n\n    const QGauss<dim> quadrature_formula(stokes_degree+2);\n    FEValues<dim>     stokes_fe_values (stokes_fe, quadrature_formula,\n                                        update_JxW_values |\n                                        update_values |\n                                        update_gradients);\n\n    const unsigned int   dofs_per_cell   = stokes_fe.dofs_per_cell;\n    const unsigned int   n_q_points      = quadrature_formula.size();\n\n    FullMatrix<double>   local_matrix (dofs_per_cell, dofs_per_cell);\n    std::vector<unsigned int> local_dof_indices (dofs_per_cell);\n\n    std::vector<Tensor<2,dim> > grad_phi_u (dofs_per_cell);\n    std::vector<double>         phi_p      (dofs_per_cell);\n\n    const FEValuesExtractors::Vector velocities (0);\n    const FEValuesExtractors::Scalar pressure (dim);\n\n    typename DoFHandler<dim>::active_cell_iterator\n    cell = stokes_dof_handler.begin_active(),\n    endc = stokes_dof_handler.end();\n    for (; cell!=endc; ++cell)\n      {\n        stokes_fe_values.reinit (cell);\n        local_matrix = 0;\n\n        // The creation of the local matrix is rather simple. There are only a\n        // Laplace term (on the velocity) and a mass matrix weighted by\n        // $\\eta^{-1}$ to be generated, so the creation of the local matrix is\n        // done in two lines. Once the local matrix is ready (loop over rows\n        // and columns in the local matrix on each quadrature point), we get\n        // the local DoF indices and write the local information into the\n        // global matrix. We do this as in step-27, i.e. we directly apply the\n        // constraints from hanging nodes locally. By doing so, we don't have\n        // to do that afterwards, and we don't also write into entries of the\n        // matrix that will actually be set to zero again later when\n        // eliminating constraints.\n        for (unsigned int q=0; q<n_q_points; ++q)\n          {\n            for (unsigned int k=0; k<dofs_per_cell; ++k)\n              {\n                grad_phi_u[k] = stokes_fe_values[velocities].gradient(k,q);\n                phi_p[k]      = stokes_fe_values[pressure].value (k, q);\n              }\n\n            for (unsigned int i=0; i<dofs_per_cell; ++i)\n              for (unsigned int j=0; j<dofs_per_cell; ++j)\n                local_matrix(i,j) += (EquationData::eta *\n                                      scalar_product (grad_phi_u[i], grad_phi_u[j])\n                                      +\n                                      (1./EquationData::eta) *\n                                      phi_p[i] * phi_p[j])\n                                     * stokes_fe_values.JxW(q);\n          }\n\n        cell->get_dof_indices (local_dof_indices);\n        stokes_constraints.distribute_local_to_global (local_matrix,\n                                                       local_dof_indices,\n                                                       stokes_preconditioner_matrix);\n      }\n  }\n\n\n\n  // @sect4{BoussinesqFlowProblem::build_stokes_preconditioner}\n  //\n  // This function generates the inner preconditioners that are going to be\n  // used for the Schur complement block preconditioner. Since the\n  // preconditioners need only to be regenerated when the matrices change,\n  // this function does not have to do anything in case the matrices have not\n  // changed (i.e., the flag <code>rebuild_stokes_preconditioner</code> has\n  // the value <code>false</code>). Otherwise its first task is to call\n  // <code>assemble_stokes_preconditioner</code> to generate the\n  // preconditioner matrices.\n  //\n  // Next, we set up the preconditioner for the velocity-velocity matrix\n  // <i>A</i>. As explained in the introduction, we are going to use an AMG\n  // preconditioner based on a vector Laplace matrix $\\hat{A}$ (which is\n  // spectrally close to the Stokes matrix <i>A</i>). Usually, the\n  // TrilinosWrappers::PreconditionAMG class can be seen as a good black-box\n  // preconditioner which does not need any special knowledge. In this case,\n  // however, we have to be careful: since we build an AMG for a vector\n  // problem, we have to tell the preconditioner setup which dofs belong to\n  // which vector component. We do this using the function\n  // DoFTools::extract_constant_modes, a function that generates a set of\n  // <code>dim</code> vectors, where each one has ones in the respective\n  // component of the vector problem and zeros elsewhere. Hence, these are the\n  // constant modes on each component, which explains the name of the\n  // variable.\n  template <int dim>\n  void\n  BoussinesqFlowProblem<dim>::build_stokes_preconditioner ()\n  {\n    if (rebuild_stokes_preconditioner == false)\n      return;\n\n    std::cout << \"   Rebuilding Stokes preconditioner...\" << std::flush;\n\n    assemble_stokes_preconditioner ();\n\n    Amg_preconditioner = std_cxx1x::shared_ptr<TrilinosWrappers::PreconditionAMG>\n                         (new TrilinosWrappers::PreconditionAMG());\n\n    std::vector<std::vector<bool> > constant_modes;\n    FEValuesExtractors::Vector velocity_components(0);\n    DoFTools::extract_constant_modes (stokes_dof_handler,\n                                      stokes_fe.component_mask(velocity_components),\n                                      constant_modes);\n    TrilinosWrappers::PreconditionAMG::AdditionalData amg_data;\n    amg_data.constant_modes = constant_modes;\n\n    // Next, we set some more options of the AMG preconditioner. In\n    // particular, we need to tell the AMG setup that we use quadratic basis\n    // functions for the velocity matrix (this implies more nonzero elements\n    // in the matrix, so that a more rubust algorithm needs to be chosen\n    // internally). Moreover, we want to be able to control how the coarsening\n    // structure is build up. The way the Trilinos smoothed aggregation AMG\n    // does this is to look which matrix entries are of similar size as the\n    // diagonal entry in order to algebraically build a coarse-grid\n    // structure. By setting the parameter <code>aggregation_threshold</code>\n    // to 0.02, we specify that all entries that are more than two precent of\n    // size of some diagonal pivots in that row should form one coarse grid\n    // point. This parameter is rather ad-hoc, and some fine-tuning of it can\n    // influence the performance of the preconditioner. As a rule of thumb,\n    // larger values of <code>aggregation_threshold</code> will decrease the\n    // number of iterations, but increase the costs per iteration. A look at\n    // the Trilinos documentation will provide more information on these\n    // parameters. With this data set, we then initialize the preconditioner\n    // with the matrix we want it to apply to.\n    //\n    // Finally, we also initialize the preconditioner for the inversion of the\n    // pressure mass matrix. This matrix is symmetric and well-behaved, so we\n    // can chose a simple preconditioner. We stick with an incomple Cholesky\n    // (IC) factorization preconditioner, which is designed for symmetric\n    // matrices. We could have also chosen an SSOR preconditioner with\n    // relaxation factor around 1.2, but IC is cheaper for our example. We\n    // wrap the preconditioners into a <code>std_cxx1x::shared_ptr</code>\n    // pointer, which makes it easier to recreate the preconditioner next time\n    // around since we do not have to care about destroying the previously\n    // used object.\n    amg_data.elliptic = true;\n    amg_data.higher_order_elements = true;\n    amg_data.smoother_sweeps = 2;\n    amg_data.aggregation_threshold = 0.02;\n    Amg_preconditioner->initialize(stokes_preconditioner_matrix.block(0,0),\n                                   amg_data);\n\n    Mp_preconditioner = std_cxx1x::shared_ptr<TrilinosWrappers::PreconditionIC>\n                        (new TrilinosWrappers::PreconditionIC());\n    Mp_preconditioner->initialize(stokes_preconditioner_matrix.block(1,1));\n\n    std::cout << std::endl;\n\n    rebuild_stokes_preconditioner = false;\n  }\n\n\n\n  // @sect4{BoussinesqFlowProblem::assemble_stokes_system}\n  //\n  // The time lag scheme we use for advancing the coupled Stokes-temperature\n  // system forces us to split up the assembly (and the solution of linear\n  // systems) into two step. The first one is to create the Stokes system\n  // matrix and right hand side, and the second is to create matrix and right\n  // hand sides for the temperature dofs, which depends on the result of the\n  // linear system for the velocity.\n  //\n  // This function is called at the beginning of each time step. In the first\n  // time step or if the mesh has changed, indicated by the\n  // <code>rebuild_stokes_matrix</code>, we need to assemble the Stokes\n  // matrix; on the other hand, if the mesh hasn't changed and the matrix is\n  // already available, this is not necessary and all we need to do is\n  // assemble the right hand side vector which changes in each time step.\n  //\n  // Regarding the technical details of implementation, not much has changed\n  // from step-22. We reset matrix and vector, create a quadrature formula on\n  // the cells, and then create the respective FEValues object. For the update\n  // flags, we require basis function derivatives only in case of a full\n  // assembly, since they are not needed for the right hand side; as always,\n  // choosing the minimal set of flags depending on what is currently needed\n  // makes the call to FEValues::reinit further down in the program more\n  // efficient.\n  //\n  // There is one thing that needs to be commented &ndash; since we have a\n  // separate finite element and DoFHandler for the temperature, we need to\n  // generate a second FEValues object for the proper evaluation of the\n  // temperature solution. This isn't too complicated to realize here: just\n  // use the temperature structures and set an update flag for the basis\n  // function values which we need for evaluation of the temperature\n  // solution. The only important part to remember here is that the same\n  // quadrature formula is used for both FEValues objects to ensure that we\n  // get matching information when we loop over the quadrature points of the\n  // two objects.\n  //\n  // The declarations proceed with some shortcuts for array sizes, the\n  // creation of the local matrix and right hand side as well as the vector\n  // for the indices of the local dofs compared to the global system.\n  template <int dim>\n  void BoussinesqFlowProblem<dim>::assemble_stokes_system ()\n  {\n    std::cout << \"   Assembling...\" << std::flush;\n\n    if (rebuild_stokes_matrix == true)\n      stokes_matrix=0;\n\n    stokes_rhs=0;\n\n    const QGauss<dim> quadrature_formula (stokes_degree+2);\n    FEValues<dim>     stokes_fe_values (stokes_fe, quadrature_formula,\n                                        update_values    |\n                                        update_quadrature_points  |\n                                        update_JxW_values |\n                                        (rebuild_stokes_matrix == true\n                                         ?\n                                         update_gradients\n                                         :\n                                         UpdateFlags(0)));\n\n    FEValues<dim>     temperature_fe_values (temperature_fe, quadrature_formula,\n                                             update_values);\n\n    const unsigned int   dofs_per_cell   = stokes_fe.dofs_per_cell;\n    const unsigned int   n_q_points      = quadrature_formula.size();\n\n    FullMatrix<double>   local_matrix (dofs_per_cell, dofs_per_cell);\n    Vector<double>       local_rhs    (dofs_per_cell);\n\n    std::vector<unsigned int> local_dof_indices (dofs_per_cell);\n\n    // Next we need a vector that will contain the values of the temperature\n    // solution at the previous time level at the quadrature points to\n    // assemble the source term in the right hand side of the momentum\n    // equation. Let's call this vector <code>old_solution_values</code>.\n    //\n    // The set of vectors we create next hold the evaluations of the basis\n    // functions as well as their gradients and symmetrized gradients that\n    // will be used for creating the matrices. Putting these into their own\n    // arrays rather than asking the FEValues object for this information each\n    // time it is needed is an optimization to accelerate the assembly\n    // process, see step-22 for details.\n    //\n    // The last two declarations are used to extract the individual blocks\n    // (velocity, pressure, temperature) from the total FE system.\n    std::vector<double>               old_temperature_values(n_q_points);\n\n    std::vector<Tensor<1,dim> >          phi_u       (dofs_per_cell);\n    std::vector<SymmetricTensor<2,dim> > grads_phi_u (dofs_per_cell);\n    std::vector<double>                  div_phi_u   (dofs_per_cell);\n    std::vector<double>                  phi_p       (dofs_per_cell);\n\n    const FEValuesExtractors::Vector velocities (0);\n    const FEValuesExtractors::Scalar pressure (dim);\n\n    // Now start the loop over all cells in the problem. We are working on two\n    // different DoFHandlers for this assembly routine, so we must have two\n    // different cell iterators for the two objects in use. This might seem a\n    // bit peculiar, since both the Stokes system and the temperature system\n    // use the same grid, but that's the only way to keep degrees of freedom\n    // in sync. The first statements within the loop are again all very\n    // familiar, doing the update of the finite element data as specified by\n    // the update flags, zeroing out the local arrays and getting the values\n    // of the old solution at the quadrature points. Then we are ready to loop\n    // over the quadrature points on the cell.\n    typename DoFHandler<dim>::active_cell_iterator\n    cell = stokes_dof_handler.begin_active(),\n    endc = stokes_dof_handler.end();\n    typename DoFHandler<dim>::active_cell_iterator\n    temperature_cell = temperature_dof_handler.begin_active();\n\n    for (; cell!=endc; ++cell, ++temperature_cell)\n      {\n        stokes_fe_values.reinit (cell);\n        temperature_fe_values.reinit (temperature_cell);\n\n        local_matrix = 0;\n        local_rhs = 0;\n\n        temperature_fe_values.get_function_values (old_temperature_solution,\n                                                   old_temperature_values);\n\n        for (unsigned int q=0; q<n_q_points; ++q)\n          {\n            const double old_temperature = old_temperature_values[q];\n\n            // Next we extract the values and gradients of basis functions\n            // relevant to the terms in the inner products. As shown in\n            // step-22 this helps accelerate assembly.\n            //\n            // Once this is done, we start the loop over the rows and columns\n            // of the local matrix and feed the matrix with the relevant\n            // products. The right hand side is filled with the forcing term\n            // driven by temperature in direction of gravity (which is\n            // vertical in our example).  Note that the right hand side term\n            // is always generated, whereas the matrix contributions are only\n            // updated when it is requested by the\n            // <code>rebuild_matrices</code> flag.\n            for (unsigned int k=0; k<dofs_per_cell; ++k)\n              {\n                phi_u[k] = stokes_fe_values[velocities].value (k,q);\n                if (rebuild_stokes_matrix)\n                  {\n                    grads_phi_u[k] = stokes_fe_values[velocities].symmetric_gradient(k,q);\n                    div_phi_u[k]   = stokes_fe_values[velocities].divergence (k, q);\n                    phi_p[k]       = stokes_fe_values[pressure].value (k, q);\n                  }\n              }\n\n            if (rebuild_stokes_matrix)\n              for (unsigned int i=0; i<dofs_per_cell; ++i)\n                for (unsigned int j=0; j<dofs_per_cell; ++j)\n                  local_matrix(i,j) += (EquationData::eta * 2 *\n                                        (grads_phi_u[i] * grads_phi_u[j])\n                                        - div_phi_u[i] * phi_p[j]\n                                        - phi_p[i] * div_phi_u[j])\n                                       * stokes_fe_values.JxW(q);\n\n            const Point<dim> gravity = -( (dim == 2) ? (Point<dim> (0,1)) :\n                                          (Point<dim> (0,0,1)) );\n            for (unsigned int i=0; i<dofs_per_cell; ++i)\n              local_rhs(i) += (-EquationData::density *\n                               EquationData::beta *\n                               gravity * phi_u[i] * old_temperature)*\n                              stokes_fe_values.JxW(q);\n          }\n\n        // The last step in the loop over all cells is to enter the local\n        // contributions into the global matrix and vector structures to the\n        // positions specified in <code>local_dof_indices</code>.  Again, we\n        // let the ConstraintMatrix class do the insertion of the cell matrix\n        // elements to the global matrix, which already condenses the hanging\n        // node constraints.\n        cell->get_dof_indices (local_dof_indices);\n\n        if (rebuild_stokes_matrix == true)\n          stokes_constraints.distribute_local_to_global (local_matrix,\n                                                         local_rhs,\n                                                         local_dof_indices,\n                                                         stokes_matrix,\n                                                         stokes_rhs);\n        else\n          stokes_constraints.distribute_local_to_global (local_rhs,\n                                                         local_dof_indices,\n                                                         stokes_rhs);\n      }\n\n    rebuild_stokes_matrix = false;\n\n    std::cout << std::endl;\n  }\n\n\n\n\n  // @sect4{BoussinesqFlowProblem::assemble_temperature_matrix}\n  //\n  // This function assembles the matrix in the temperature equation. The\n  // temperature matrix consists of two parts, a mass matrix and the time step\n  // size times a stiffness matrix given by a Laplace term times the amount of\n  // diffusion. Since the matrix depends on the time step size (which varies\n  // from one step to another), the temperature matrix needs to be updated\n  // every time step. We could simply regenerate the matrices in every time\n  // step, but this is not really efficient since mass and Laplace matrix do\n  // only change when we change the mesh. Hence, we do this more efficiently\n  // by generating two separate matrices in this function, one for the mass\n  // matrix and one for the stiffness (diffusion) matrix. We will then sum up\n  // the matrix plus the stiffness matrix times the time step size once we\n  // know the actual time step.\n  //\n  // So the details for this first step are very simple. In case we need to\n  // rebuild the matrix (i.e., the mesh has changed), we zero the data\n  // structures, get a quadrature formula and a FEValues object, and create\n  // local matrices, local dof indices and evaluation structures for the basis\n  // functions.\n  template <int dim>\n  void BoussinesqFlowProblem<dim>::assemble_temperature_matrix ()\n  {\n    if (rebuild_temperature_matrices == false)\n      return;\n\n    temperature_mass_matrix = 0;\n    temperature_stiffness_matrix = 0;\n\n    QGauss<dim>   quadrature_formula (temperature_degree+2);\n    FEValues<dim> temperature_fe_values (temperature_fe, quadrature_formula,\n                                         update_values    | update_gradients |\n                                         update_JxW_values);\n\n    const unsigned int   dofs_per_cell   = temperature_fe.dofs_per_cell;\n    const unsigned int   n_q_points      = quadrature_formula.size();\n\n    FullMatrix<double>   local_mass_matrix (dofs_per_cell, dofs_per_cell);\n    FullMatrix<double>   local_stiffness_matrix (dofs_per_cell, dofs_per_cell);\n\n    std::vector<unsigned int> local_dof_indices (dofs_per_cell);\n\n    std::vector<double>         phi_T       (dofs_per_cell);\n    std::vector<Tensor<1,dim> > grad_phi_T  (dofs_per_cell);\n\n    // Now, let's start the loop over all cells in the triangulation. We need\n    // to zero out the local matrices, update the finite element evaluations,\n    // and then loop over the rows and columns of the matrices on each\n    // quadrature point, where we then create the mass matrix and the\n    // stiffness matrix (Laplace terms times the diffusion\n    // <code>EquationData::kappa</code>. Finally, we let the constraints\n    // object insert these values into the global matrix, and directly\n    // condense the constraints into the matrix.\n    typename DoFHandler<dim>::active_cell_iterator\n    cell = temperature_dof_handler.begin_active(),\n    endc = temperature_dof_handler.end();\n    for (; cell!=endc; ++cell)\n      {\n        local_mass_matrix = 0;\n        local_stiffness_matrix = 0;\n\n        temperature_fe_values.reinit (cell);\n\n        for (unsigned int q=0; q<n_q_points; ++q)\n          {\n            for (unsigned int k=0; k<dofs_per_cell; ++k)\n              {\n                grad_phi_T[k] = temperature_fe_values.shape_grad (k,q);\n                phi_T[k]      = temperature_fe_values.shape_value (k, q);\n              }\n\n            for (unsigned int i=0; i<dofs_per_cell; ++i)\n              for (unsigned int j=0; j<dofs_per_cell; ++j)\n                {\n                  local_mass_matrix(i,j)\n                  += (phi_T[i] * phi_T[j]\n                      *\n                      temperature_fe_values.JxW(q));\n                  local_stiffness_matrix(i,j)\n                  += (EquationData::kappa * grad_phi_T[i] * grad_phi_T[j]\n                      *\n                      temperature_fe_values.JxW(q));\n                }\n          }\n\n        cell->get_dof_indices (local_dof_indices);\n\n        temperature_constraints.distribute_local_to_global (local_mass_matrix,\n                                                            local_dof_indices,\n                                                            temperature_mass_matrix);\n        temperature_constraints.distribute_local_to_global (local_stiffness_matrix,\n                                                            local_dof_indices,\n                                                            temperature_stiffness_matrix);\n      }\n\n    rebuild_temperature_matrices = false;\n  }\n\n\n\n  // @sect4{BoussinesqFlowProblem::assemble_temperature_system}\n  //\n  // This function does the second part of the assembly work on the\n  // temperature matrix, the actual addition of pressure mass and stiffness\n  // matrix (where the time step size comes into play), as well as the\n  // creation of the velocity-dependent right hand side. The declarations for\n  // the right hand side assembly in this function are pretty much the same as\n  // the ones used in the other assembly routines, except that we restrict\n  // ourselves to vectors this time. We are going to calculate residuals on\n  // the temperature system, which means that we have to evaluate second\n  // derivatives, specified by the update flag <code>update_hessians</code>.\n  //\n  // The temperature equation is coupled to the Stokes system by means of the\n  // fluid velocity. These two parts of the solution are associated with\n  // different DoFHandlers, so we again need to create a second FEValues\n  // object for the evaluation of the velocity at the quadrature points.\n  template <int dim>\n  void BoussinesqFlowProblem<dim>::\n  assemble_temperature_system (const double maximal_velocity)\n  {\n    const bool use_bdf2_scheme = (timestep_number != 0);\n\n    if (use_bdf2_scheme == true)\n      {\n        temperature_matrix.copy_from (temperature_mass_matrix);\n        temperature_matrix *= (2*time_step + old_time_step) /\n                              (time_step + old_time_step);\n        temperature_matrix.add (time_step, temperature_stiffness_matrix);\n      }\n    else\n      {\n        temperature_matrix.copy_from (temperature_mass_matrix);\n        temperature_matrix.add (time_step, temperature_stiffness_matrix);\n      }\n\n    temperature_rhs = 0;\n\n    const QGauss<dim> quadrature_formula(temperature_degree+2);\n    FEValues<dim>     temperature_fe_values (temperature_fe, quadrature_formula,\n                                             update_values    |\n                                             update_gradients |\n                                             update_hessians  |\n                                             update_quadrature_points  |\n                                             update_JxW_values);\n    FEValues<dim>     stokes_fe_values (stokes_fe, quadrature_formula,\n                                        update_values);\n\n    const unsigned int   dofs_per_cell   = temperature_fe.dofs_per_cell;\n    const unsigned int   n_q_points      = quadrature_formula.size();\n\n    Vector<double>       local_rhs (dofs_per_cell);\n\n    std::vector<unsigned int> local_dof_indices (dofs_per_cell);\n\n    // Next comes the declaration of vectors to hold the old and older\n    // solution values (as a notation for time levels <i>n-1</i> and\n    // <i>n-2</i>, respectively) and gradients at quadrature points of the\n    // current cell. We also declarate an object to hold the temperature right\n    // hande side values (<code>gamma_values</code>), and we again use\n    // shortcuts for the temperature basis functions. Eventually, we need to\n    // find the temperature extrema and the diameter of the computational\n    // domain which will be used for the definition of the stabilization\n    // parameter (we got the maximal velocity as an input to this function).\n    std::vector<Tensor<1,dim> > old_velocity_values (n_q_points);\n    std::vector<Tensor<1,dim> > old_old_velocity_values (n_q_points);\n    std::vector<double>         old_temperature_values (n_q_points);\n    std::vector<double>         old_old_temperature_values(n_q_points);\n    std::vector<Tensor<1,dim> > old_temperature_grads(n_q_points);\n    std::vector<Tensor<1,dim> > old_old_temperature_grads(n_q_points);\n    std::vector<double>         old_temperature_laplacians(n_q_points);\n    std::vector<double>         old_old_temperature_laplacians(n_q_points);\n\n    EquationData::TemperatureRightHandSide<dim>  temperature_right_hand_side;\n    std::vector<double> gamma_values (n_q_points);\n\n    std::vector<double>         phi_T      (dofs_per_cell);\n    std::vector<Tensor<1,dim> > grad_phi_T (dofs_per_cell);\n\n    const std::pair<double,double>\n    global_T_range = get_extrapolated_temperature_range();\n\n    const FEValuesExtractors::Vector velocities (0);\n\n    // Now, let's start the loop over all cells in the triangulation. Again,\n    // we need two cell iterators that walk in parallel through the cells of\n    // the two involved DoFHandler objects for the Stokes and temperature\n    // part. Within the loop, we first set the local rhs to zero, and then get\n    // the values and derivatives of the old solution functions at the\n    // quadrature points, since they are going to be needed for the definition\n    // of the stabilization parameters and as coefficients in the equation,\n    // respectively. Note that since the temperature has its own DoFHandler\n    // and FEValues object we get the entire solution at the quadrature point\n    // (which is the scalar temperature field only anyway) whereas for the\n    // Stokes part we restrict ourselves to extracting the velocity part (and\n    // ignoring the pressure part) by using\n    // <code>stokes_fe_values[velocities].get_function_values</code>.\n    typename DoFHandler<dim>::active_cell_iterator\n    cell = temperature_dof_handler.begin_active(),\n    endc = temperature_dof_handler.end();\n    typename DoFHandler<dim>::active_cell_iterator\n    stokes_cell = stokes_dof_handler.begin_active();\n\n    for (; cell!=endc; ++cell, ++stokes_cell)\n      {\n        local_rhs = 0;\n\n        temperature_fe_values.reinit (cell);\n        stokes_fe_values.reinit (stokes_cell);\n\n        temperature_fe_values.get_function_values (old_temperature_solution,\n                                                   old_temperature_values);\n        temperature_fe_values.get_function_values (old_old_temperature_solution,\n                                                   old_old_temperature_values);\n\n        temperature_fe_values.get_function_gradients (old_temperature_solution,\n                                                      old_temperature_grads);\n        temperature_fe_values.get_function_gradients (old_old_temperature_solution,\n                                                      old_old_temperature_grads);\n\n        temperature_fe_values.get_function_laplacians (old_temperature_solution,\n                                                       old_temperature_laplacians);\n        temperature_fe_values.get_function_laplacians (old_old_temperature_solution,\n                                                       old_old_temperature_laplacians);\n\n        temperature_right_hand_side.value_list (temperature_fe_values.get_quadrature_points(),\n                                                gamma_values);\n\n        stokes_fe_values[velocities].get_function_values (stokes_solution,\n                                                          old_velocity_values);\n        stokes_fe_values[velocities].get_function_values (old_stokes_solution,\n                                                          old_old_velocity_values);\n\n        // Next, we calculate the artificial viscosity for stabilization\n        // according to the discussion in the introduction using the dedicated\n        // function. With that at hand, we can get into the loop over\n        // quadrature points and local rhs vector components. The terms here\n        // are quite lenghty, but their definition follows the time-discrete\n        // system developed in the introduction of this program. The BDF-2\n        // scheme needs one more term from the old time step (and involves\n        // more complicated factors) than the backward Euler scheme that is\n        // used for the first time step. When all this is done, we distribute\n        // the local vector into the global one (including hanging node\n        // constraints).\n        const double nu\n          = compute_viscosity (old_temperature_values,\n                               old_old_temperature_values,\n                               old_temperature_grads,\n                               old_old_temperature_grads,\n                               old_temperature_laplacians,\n                               old_old_temperature_laplacians,\n                               old_velocity_values,\n                               old_old_velocity_values,\n                               gamma_values,\n                               maximal_velocity,\n                               global_T_range.second - global_T_range.first,\n                               cell->diameter());\n\n        for (unsigned int q=0; q<n_q_points; ++q)\n          {\n            for (unsigned int k=0; k<dofs_per_cell; ++k)\n              {\n                grad_phi_T[k] = temperature_fe_values.shape_grad (k,q);\n                phi_T[k]      = temperature_fe_values.shape_value (k, q);\n              }\n\n            const double T_term_for_rhs\n              = (use_bdf2_scheme ?\n                 (old_temperature_values[q] *\n                  (1 + time_step/old_time_step)\n                  -\n                  old_old_temperature_values[q] *\n                  (time_step * time_step) /\n                  (old_time_step * (time_step + old_time_step)))\n                 :\n                 old_temperature_values[q]);\n\n            const Tensor<1,dim> ext_grad_T\n              = (use_bdf2_scheme ?\n                 (old_temperature_grads[q] *\n                  (1 + time_step/old_time_step)\n                  -\n                  old_old_temperature_grads[q] *\n                  time_step/old_time_step)\n                 :\n                 old_temperature_grads[q]);\n\n            const Tensor<1,dim> extrapolated_u\n              = (use_bdf2_scheme ?\n                 (old_velocity_values[q] *\n                  (1 + time_step/old_time_step)\n                  -\n                  old_old_velocity_values[q] *\n                  time_step/old_time_step)\n                 :\n                 old_velocity_values[q]);\n\n            for (unsigned int i=0; i<dofs_per_cell; ++i)\n              local_rhs(i) += (T_term_for_rhs * phi_T[i]\n                               -\n                               time_step *\n                               extrapolated_u * ext_grad_T * phi_T[i]\n                               -\n                               time_step *\n                               nu * ext_grad_T * grad_phi_T[i]\n                               +\n                               time_step *\n                               gamma_values[q] * phi_T[i])\n                              *\n                              temperature_fe_values.JxW(q);\n          }\n\n        cell->get_dof_indices (local_dof_indices);\n        temperature_constraints.distribute_local_to_global (local_rhs,\n                                                            local_dof_indices,\n                                                            temperature_rhs);\n      }\n  }\n\n\n\n\n  // @sect4{BoussinesqFlowProblem::solve}\n  //\n  // This function solves the linear systems of equations. Following the\n  // introduction, we start with the Stokes system, where we need to generate\n  // our block Schur preconditioner. Since all the relevant actions are\n  // implemented in the class <code>BlockSchurPreconditioner</code>, all we\n  // have to do is to initialize the class appropriately. What we need to pass\n  // down is an <code>InverseMatrix</code> object for the pressure mass\n  // matrix, which we set up using the respective class together with the IC\n  // preconditioner we already generated, and the AMG preconditioner for the\n  // velocity-velocity matrix. Note that both <code>Mp_preconditioner</code>\n  // and <code>Amg_preconditioner</code> are only pointers, so we use\n  // <code>*</code> to pass down the actual preconditioner objects.\n  //\n  // Once the preconditioner is ready, we create a GMRES solver for the block\n  // system. Since we are working with Trilinos data structures, we have to\n  // set the respective template argument in the solver. GMRES needs to\n  // internally store temporary vectors for each iteration (see the discussion\n  // in the results section of step-22) &ndash; the more vectors it can use,\n  // the better it will generally perform. To keep memory demands in check, we\n  // set the number of vectors to 100. This means that up to 100 solver\n  // iterations, every temporary vector can be stored. If the solver needs to\n  // iterate more often to get the specified tolerance, it will work on a\n  // reduced set of vectors by restarting at every 100 iterations.\n  //\n  // With this all set up, we solve the system and distribute the constraints\n  // in the Stokes system, i.e. hanging nodes and no-flux boundary condition,\n  // in order to have the appropriate solution values even at constrained\n  // dofs. Finally, we write the number of iterations to the screen.\n  template <int dim>\n  void BoussinesqFlowProblem<dim>::solve ()\n  {\n    std::cout << \"   Solving...\" << std::endl;\n\n    {\n      const LinearSolvers::InverseMatrix<TrilinosWrappers::SparseMatrix,\n            TrilinosWrappers::PreconditionIC>\n            mp_inverse (stokes_preconditioner_matrix.block(1,1), *Mp_preconditioner);\n\n      const LinearSolvers::BlockSchurPreconditioner<TrilinosWrappers::PreconditionAMG,\n            TrilinosWrappers::PreconditionIC>\n            preconditioner (stokes_matrix, mp_inverse, *Amg_preconditioner);\n\n      SolverControl solver_control (stokes_matrix.m(),\n                                    1e-6*stokes_rhs.l2_norm());\n\n      SolverGMRES<TrilinosWrappers::BlockVector>\n      gmres (solver_control,\n             SolverGMRES<TrilinosWrappers::BlockVector >::AdditionalData(100));\n\n      for (unsigned int i=0; i<stokes_solution.size(); ++i)\n        if (stokes_constraints.is_constrained(i))\n          stokes_solution(i) = 0;\n\n      gmres.solve(stokes_matrix, stokes_solution, stokes_rhs, preconditioner);\n\n      stokes_constraints.distribute (stokes_solution);\n\n      std::cout << \"   \"\n                << solver_control.last_step()\n                << \" GMRES iterations for Stokes subsystem.\"\n                << std::endl;\n    }\n\n    // Once we know the Stokes solution, we can determine the new time step\n    // from the maximal velocity. We have to do this to satisfy the CFL\n    // condition since convection terms are treated explicitly in the\n    // temperature equation, as discussed in the introduction. The exact form\n    // of the formula used here for the time step is discussed in the results\n    // section of this program.\n    //\n    // There is a snatch here. The formula contains a division by the maximum\n    // value of the velocity. However, at the start of the computation, we\n    // have a constant temperature field (we start with a constant\n    // temperature, and it will be non-constant only after the first time step\n    // during which the source acts). Constant temperature means that no\n    // buoyancy acts, and so the velocity is zero. Dividing by it will not\n    // likely lead to anything good.\n    //\n    // To avoid the resulting infinite time step, we ask whether the maximal\n    // velocity is very small (in particular smaller than the values we\n    // encounter during any of the following time steps) and if so rather than\n    // dividing by zero we just divide by a small value, resulting in a large\n    // but finite time step.\n    old_time_step = time_step;\n    const double maximal_velocity = get_maximal_velocity();\n\n    if (maximal_velocity >= 0.01)\n      time_step = 1./(1.6*dim*std::sqrt(1.*dim)) /\n                  temperature_degree *\n                  GridTools::minimal_cell_diameter(triangulation) /\n                  maximal_velocity;\n    else\n      time_step = 1./(1.6*dim*std::sqrt(1.*dim)) /\n                  temperature_degree *\n                  GridTools::minimal_cell_diameter(triangulation) /\n                  .01;\n\n    std::cout << \"   \" << \"Time step: \" << time_step\n              << std::endl;\n\n    temperature_solution = old_temperature_solution;\n\n    // Next we set up the temperature system and the right hand side using the\n    // function <code>assemble_temperature_system()</code>.  Knowing the\n    // matrix and right hand side of the temperature equation, we set up a\n    // preconditioner and a solver. The temperature matrix is a mass matrix\n    // (with eigenvalues around one) plus a Laplace matrix (with eigenvalues\n    // between zero and $ch^{-2}$) times a small number proportional to the\n    // time step $k_n$. Hence, the resulting symmetric and positive definite\n    // matrix has eigenvalues in the range $[1,1+k_nh^{-2}]$ (up to\n    // constants). This matrix is only moderately ill conditioned even for\n    // small mesh sizes and we get a reasonably good preconditioner by simple\n    // means, for example with an incomplete Cholesky decomposition\n    // preconditioner (IC) as we also use for preconditioning the pressure\n    // mass matrix solver. As a solver, we choose the conjugate gradient\n    // method CG. As before, we tell the solver to use Trilinos vectors via\n    // the template argument <code>TrilinosWrappers::Vector</code>.  Finally,\n    // we solve, distribute the hanging node constraints and write out the\n    // number of iterations.\n    assemble_temperature_system (maximal_velocity);\n    {\n\n      SolverControl solver_control (temperature_matrix.m(),\n                                    1e-8*temperature_rhs.l2_norm());\n      SolverCG<TrilinosWrappers::Vector> cg (solver_control);\n\n      TrilinosWrappers::PreconditionIC preconditioner;\n      preconditioner.initialize (temperature_matrix);\n\n      cg.solve (temperature_matrix, temperature_solution,\n                temperature_rhs, preconditioner);\n\n      temperature_constraints.distribute (temperature_solution);\n\n      std::cout << \"   \"\n                << solver_control.last_step()\n                << \" CG iterations for temperature.\"\n                << std::endl;\n\n      // At the end of this function, we step through the vector and read out\n      // the maximum and minimum temperature value, which we also want to\n      // output. This will come in handy when determining the correct constant\n      // in the choice of time step as discuss in the results section of this\n      // program.\n      double min_temperature = temperature_solution(0),\n             max_temperature = temperature_solution(0);\n      for (unsigned int i=0; i<temperature_solution.size(); ++i)\n        {\n          min_temperature = std::min<double> (min_temperature,\n                                              temperature_solution(i));\n          max_temperature = std::max<double> (max_temperature,\n                                              temperature_solution(i));\n        }\n\n      std::cout << \"   Temperature range: \"\n                << min_temperature << ' ' << max_temperature\n                << std::endl;\n    }\n  }\n\n\n\n  // @sect4{BoussinesqFlowProblem::output_results}\n  //\n  // This function writes the solution to a VTK output file for visualization,\n  // which is done every tenth time step. This is usually quite a simple task,\n  // since the deal.II library provides functions that do almost all the job\n  // for us. In this case, the situation is a bit more complicated, since we\n  // want to visualize both the Stokes solution and the temperature as one\n  // data set, but we have done all the calculations based on two different\n  // DoFHandler objects, a situation the DataOut class usually used for output\n  // is not prepared to deal with. The way we're going to achieve this\n  // recombination is to create a joint DoFHandler that collects both\n  // components, the Stokes solution and the temperature solution. This can be\n  // nicely done by combining the finite elements from the two systems to form\n  // one FESystem, and let this collective system define a new DoFHandler\n  // object. To be sure that everything was done correctly, we perform a\n  // sanity check that ensures that we got all the dofs from both Stokes and\n  // temperature even in the combined system.\n  //\n  // Next, we create a vector that will collect the actual solution\n  // values. Since this vector is only going to be used for output, we create\n  // it as a deal.II vector that nicely cooperate with the data output\n  // classes. Remember that we used Trilinos vectors for assembly and solving.\n  template <int dim>\n  void BoussinesqFlowProblem<dim>::output_results ()  const\n  {\n    if (timestep_number % 10 != 0)\n      return;\n\n    const FESystem<dim> joint_fe (stokes_fe, 1,\n                                  temperature_fe, 1);\n    DoFHandler<dim> joint_dof_handler (triangulation);\n    joint_dof_handler.distribute_dofs (joint_fe);\n    Assert (joint_dof_handler.n_dofs() ==\n            stokes_dof_handler.n_dofs() + temperature_dof_handler.n_dofs(),\n            ExcInternalError());\n\n    Vector<double> joint_solution (joint_dof_handler.n_dofs());\n\n    // Unfortunately, there is no straight-forward relation that tells us how\n    // to sort Stokes and temperature vector into the joint vector. The way we\n    // can get around this trouble is to rely on the information collected in\n    // the FESystem. For each dof in a cell, the joint finite element knows to\n    // which equation component (velocity component, pressure, or temperature)\n    // it belongs &ndash; that's the information we need!  So we step through\n    // all cells (with iterators into all three DoFHandlers moving in synch),\n    // and for each joint cell dof, we read out that component using the\n    // FiniteElement::system_to_base_index function (see there for a\n    // description of what the various parts of its return value contain). We\n    // also need to keep track whether we're on a Stokes dof or a temperature\n    // dof, which is contained in\n    // <code>joint_fe.system_to_base_index(i).first.first</code>.  Eventually,\n    // the dof_indices data structures on either of the three systems tell us\n    // how the relation between global vector and local dofs looks like on the\n    // present cell, which concludes this tedious work.\n    //\n    // There's one thing worth remembering when looking at the output: In our\n    // algorithm, we first solve for the Stokes system at time level\n    // <i>n-1</i> in each time step and then for the temperature at time level\n    // <i>n</i> using the previously computed velocity. These are the two\n    // components we join for output, so these two parts of the output file\n    // are actually misaligned by one time step. Since we consider graphical\n    // output as only a qualititative means to understand a solution, we\n    // ignore this $\\mathcal{O}(h)$ error.\n    {\n      std::vector<unsigned int> local_joint_dof_indices (joint_fe.dofs_per_cell);\n      std::vector<unsigned int> local_stokes_dof_indices (stokes_fe.dofs_per_cell);\n      std::vector<unsigned int> local_temperature_dof_indices (temperature_fe.dofs_per_cell);\n\n      typename DoFHandler<dim>::active_cell_iterator\n      joint_cell       = joint_dof_handler.begin_active(),\n      joint_endc       = joint_dof_handler.end(),\n      stokes_cell      = stokes_dof_handler.begin_active(),\n      temperature_cell = temperature_dof_handler.begin_active();\n      for (; joint_cell!=joint_endc; ++joint_cell, ++stokes_cell, ++temperature_cell)\n        {\n          joint_cell->get_dof_indices (local_joint_dof_indices);\n          stokes_cell->get_dof_indices (local_stokes_dof_indices);\n          temperature_cell->get_dof_indices (local_temperature_dof_indices);\n\n          for (unsigned int i=0; i<joint_fe.dofs_per_cell; ++i)\n            if (joint_fe.system_to_base_index(i).first.first == 0)\n              {\n                Assert (joint_fe.system_to_base_index(i).second\n                        <\n                        local_stokes_dof_indices.size(),\n                        ExcInternalError());\n                joint_solution(local_joint_dof_indices[i])\n                  = stokes_solution(local_stokes_dof_indices[joint_fe.system_to_base_index(i).second]);\n              }\n            else\n              {\n                Assert (joint_fe.system_to_base_index(i).first.first == 1,\n                        ExcInternalError());\n                Assert (joint_fe.system_to_base_index(i).second\n                        <\n                        local_temperature_dof_indices.size(),\n                        ExcInternalError());\n                joint_solution(local_joint_dof_indices[i])\n                  = temperature_solution(local_temperature_dof_indices[joint_fe.system_to_base_index(i).second]);\n              }\n        }\n    }\n\n    // Next, we proceed as we've done in step-22. We create solution names\n    // (that are going to appear in the visualization program for the\n    // individual components), and attach the joint dof handler to a DataOut\n    // object. The first <code>dim</code> components are the vector velocity,\n    // and then we have pressure and temperature. This information is read out\n    // using the DataComponentInterpretation helper class. Next, we attach the\n    // solution values together with the names of its components to the output\n    // object, and build patches according to the degree of freedom, which are\n    // (sub-) elements that describe the data for visualization\n    // programs. Finally, we set a file name (that includes the time step\n    // number) and write the vtk file.\n    std::vector<std::string> joint_solution_names (dim, \"velocity\");\n    joint_solution_names.push_back (\"p\");\n    joint_solution_names.push_back (\"T\");\n\n    DataOut<dim> data_out;\n\n    data_out.attach_dof_handler (joint_dof_handler);\n\n    std::vector<DataComponentInterpretation::DataComponentInterpretation>\n    data_component_interpretation\n    (dim+2, DataComponentInterpretation::component_is_scalar);\n    for (unsigned int i=0; i<dim; ++i)\n      data_component_interpretation[i]\n        = DataComponentInterpretation::component_is_part_of_vector;\n\n    data_out.add_data_vector (joint_solution, joint_solution_names,\n                              DataOut<dim>::type_dof_data,\n                              data_component_interpretation);\n    data_out.build_patches (std::min(stokes_degree, temperature_degree));\n\n    std::ostringstream filename;\n    filename << \"solution-\" << Utilities::int_to_string(timestep_number, 4) << \".vtk\";\n\n    std::ofstream output (filename.str().c_str());\n    data_out.write_vtk (output);\n  }\n\n\n\n  // @sect4{BoussinesqFlowProblem::refine_mesh}\n  //\n  // This function takes care of the adaptive mesh refinement. The three tasks\n  // this function performs is to first find out which cells to\n  // refine/coarsen, then to actually do the refinement and eventually\n  // transfer the solution vectors between the two different grids. The first\n  // task is simply achieved by using the well-established Kelly error\n  // estimator on the temperature (it is the temperature we're mainly\n  // interested in for this program, and we need to be accurate in regions of\n  // high temperature gradients, also to not have too much numerical\n  // diffusion). The second task is to actually do the remeshing. That\n  // involves only basic functions as well, such as the\n  // <code>refine_and_coarsen_fixed_fraction</code> that refines those cells\n  // with the largest estimated error that together make up 80 per cent of the\n  // error, and coarsens those cells with the smallest error that make up for\n  // a combined 10 per cent of the error.\n  //\n  // If implemented like this, we would get a program that will not make much\n  // progress: Remember that we expect temperature fields that are nearly\n  // discontinuous (the diffusivity $\\kappa$ is very small after all) and\n  // consequently we can expect that a freely adapted mesh will refine further\n  // and further into the areas of large gradients. This decrease in mesh size\n  // will then be accompanied by a decrease in time step, requiring an\n  // exceedingly large number of time steps to solve to a given final time. It\n  // will also lead to meshes that are much better at resolving\n  // discontinuities after several mesh refinement cycles than in the\n  // beginning.\n  //\n  // In particular to prevent the decrease in time step size and the\n  // correspondingly large number of time steps, we limit the maximal\n  // refinement depth of the mesh. To this end, after the refinement indicator\n  // has been applied to the cells, we simply loop over all cells on the\n  // finest level and unselect them from refinement if they would result in\n  // too high a mesh level.\n  template <int dim>\n  void BoussinesqFlowProblem<dim>::refine_mesh (const unsigned int max_grid_level)\n  {\n    Vector<float> estimated_error_per_cell (triangulation.n_active_cells());\n\n    KellyErrorEstimator<dim>::estimate (temperature_dof_handler,\n                                        QGauss<dim-1>(temperature_degree+1),\n                                        typename FunctionMap<dim>::type(),\n                                        temperature_solution,\n                                        estimated_error_per_cell);\n\n    GridRefinement::refine_and_coarsen_fixed_fraction (triangulation,\n                                                       estimated_error_per_cell,\n                                                       0.8, 0.1);\n    if (triangulation.n_levels() > max_grid_level)\n      for (typename Triangulation<dim>::active_cell_iterator\n           cell = triangulation.begin_active(max_grid_level);\n           cell != triangulation.end(); ++cell)\n        cell->clear_refine_flag ();\n\n    // As part of mesh refinement we need to transfer the solution vectors\n    // from the old mesh to the new one. To this end we use the\n    // SolutionTransfer class and we have to prepare the solution vectors that\n    // should be transferred to the new grid (we will lose the old grid once\n    // we have done the refinement so the transfer has to happen concurrently\n    // with refinement). What we definetely need are the current and the old\n    // temperature (BDF-2 time stepping requires two old solutions). Since the\n    // SolutionTransfer objects only support to transfer one object per dof\n    // handler, we need to collect the two temperature solutions in one data\n    // structure. Moreover, we choose to transfer the Stokes solution, too,\n    // since we need the velocity at two previous time steps, of which only\n    // one is calculated on the fly.\n    //\n    // Consequently, we initialize two SolutionTransfer objects for the Stokes\n    // and temperature DoFHandler objects, by attaching them to the old dof\n    // handlers. With this at place, we can prepare the triangulation and the\n    // data vectors for refinement (in this order).\n    std::vector<TrilinosWrappers::Vector> x_temperature (2);\n    x_temperature[0] = temperature_solution;\n    x_temperature[1] = old_temperature_solution;\n    TrilinosWrappers::BlockVector x_stokes = stokes_solution;\n\n    SolutionTransfer<dim,TrilinosWrappers::Vector>\n    temperature_trans(temperature_dof_handler);\n    SolutionTransfer<dim,TrilinosWrappers::BlockVector>\n    stokes_trans(stokes_dof_handler);\n\n    triangulation.prepare_coarsening_and_refinement();\n    temperature_trans.prepare_for_coarsening_and_refinement(x_temperature);\n    stokes_trans.prepare_for_coarsening_and_refinement(x_stokes);\n\n    // Now everything is ready, so do the refinement and recreate the dof\n    // structure on the new grid, and initialize the matrix structures and the\n    // new vectors in the <code>setup_dofs</code> function. Next, we actually\n    // perform the interpolation of the solutions between the grids. We create\n    // another copy of temporary vectors for temperature (now corresponding to\n    // the new grid), and let the interpolate function do the job. Then, the\n    // resulting array of vectors is written into the respective vector member\n    // variables. For the Stokes vector, everything is just the same &ndash;\n    // except that we do not need another temporary vector since we just\n    // interpolate a single vector. In the end, we have to tell the program\n    // that the matrices and preconditioners need to be regenerated, since the\n    // mesh has changed.\n    triangulation.execute_coarsening_and_refinement ();\n    setup_dofs ();\n\n    std::vector<TrilinosWrappers::Vector> tmp (2);\n    tmp[0].reinit (temperature_solution);\n    tmp[1].reinit (temperature_solution);\n    temperature_trans.interpolate(x_temperature, tmp);\n\n    temperature_solution = tmp[0];\n    old_temperature_solution = tmp[1];\n\n    stokes_trans.interpolate (x_stokes, stokes_solution);\n\n    rebuild_stokes_matrix         = true;\n    rebuild_temperature_matrices  = true;\n    rebuild_stokes_preconditioner = true;\n  }\n\n\n\n  // @sect4{BoussinesqFlowProblem::run}\n  //\n  // This function performs all the essential steps in the Boussinesq\n  // program. It starts by setting up a grid (depending on the spatial\n  // dimension, we choose some different level of initial refinement and\n  // additional adaptive refinement steps, and then create a cube in\n  // <code>dim</code> dimensions and set up the dofs for the first time. Since\n  // we want to start the time stepping already with an adaptively refined\n  // grid, we perform some pre-refinement steps, consisting of all assembly,\n  // solution and refinement, but without actually advancing in time. Rather,\n  // we use the vilified <code>goto</code> statement to jump out of the time\n  // loop right after mesh refinement to start all over again on the new mesh\n  // beginning at the <code>start_time_iteration</code> label.\n  //\n  // Before we start, we project the initial values to the grid and obtain the\n  // first data for the <code>old_temperature_solution</code> vector. Then, we\n  // initialize time step number and time step and start the time loop.\n  template <int dim>\n  void BoussinesqFlowProblem<dim>::run ()\n  {\n    const unsigned int initial_refinement = (dim == 2 ? 4 : 2);\n    const unsigned int n_pre_refinement_steps = (dim == 2 ? 4 : 3);\n\n\n    GridGenerator::hyper_cube (triangulation);\n    global_Omega_diameter = GridTools::diameter (triangulation);\n\n    triangulation.refine_global (initial_refinement);\n\n    setup_dofs();\n\n    unsigned int pre_refinement_step = 0;\n\nstart_time_iteration:\n\n    VectorTools::project (temperature_dof_handler,\n                          temperature_constraints,\n                          QGauss<dim>(temperature_degree+2),\n                          EquationData::TemperatureInitialValues<dim>(),\n                          old_temperature_solution);\n\n    timestep_number           = 0;\n    time_step = old_time_step = 0;\n\n    double time = 0;\n\n    do\n      {\n        std::cout << \"Timestep \" << timestep_number\n                  << \":  t=\" << time\n                  << std::endl;\n\n        // The first steps in the time loop are all obvious &ndash; we\n        // assemble the Stokes system, the preconditioner, the temperature\n        // matrix (matrices and preconditioner do actually only change in case\n        // we've remeshed before), and then do the solve. Before going on with\n        // the next time step, we have to check whether we should first finish\n        // the pre-refinement steps or if we should remesh (every fifth time\n        // step), refining up to a level that is consistent with initial\n        // refinement and pre-refinement steps. Last in the loop is to advance\n        // the solutions, i.e. to copy the solutions to the next \"older\" time\n        // level.\n        assemble_stokes_system ();\n        build_stokes_preconditioner ();\n        assemble_temperature_matrix ();\n\n        solve ();\n\n        output_results ();\n\n        std::cout << std::endl;\n\n        if ((timestep_number == 0) &&\n            (pre_refinement_step < n_pre_refinement_steps))\n          {\n            refine_mesh (initial_refinement + n_pre_refinement_steps);\n            ++pre_refinement_step;\n            goto start_time_iteration;\n          }\n        else if ((timestep_number > 0) && (timestep_number % 5 == 0))\n          refine_mesh (initial_refinement + n_pre_refinement_steps);\n\n        time += time_step;\n        ++timestep_number;\n\n        old_stokes_solution          = stokes_solution;\n        old_old_temperature_solution = old_temperature_solution;\n        old_temperature_solution     = temperature_solution;\n      }\n    // Do all the above until we arrive at time 100.\n    while (time <= 100);\n  }\n}\n\n\n\n// @sect3{The <code>main</code> function}\n//\n// The main function looks almost the same as in all other programs.\n//\n// There is one difference we have to be careful about. This program uses\n// Trilinos and, typically, Trilinos is configured so that it can run in\n// %parallel using MPI. This doesn't mean that it <i>has</i> to run in\n// %parallel, and in fact this program (unlike step-32) makes no attempt at\n// all to do anything in %parallel using MPI. Nevertheless, Trilinos wants the\n// MPI system to be initialized. We do that be creating an object of type\n// Utilities::MPI::MPI_InitFinalize that initializes MPI (if available) using\n// the arguments given to main() (i.e., <code>argc</code> and\n// <code>argv</code>) and de-initializes it again when the object goes out of\n// scope.\nint main (int argc, char *argv[])\n{\n  try\n    {\n      using namespace dealii;\n      using namespace Step31;\n\n      deallog.depth_console (0);\n\n      Utilities::MPI::MPI_InitFinalize mpi_initialization (argc, argv);\n\n      BoussinesqFlowProblem<2> flow_problem;\n      flow_problem.run ();\n    }\n  catch (std::exception &exc)\n    {\n      std::cerr << std::endl << std::endl\n                << \"----------------------------------------------------\"\n                << std::endl;\n      std::cerr << \"Exception on processing: \" << std::endl\n                << exc.what() << std::endl\n                << \"Aborting!\" << std::endl\n                << \"----------------------------------------------------\"\n                << std::endl;\n\n      return 1;\n    }\n  catch (...)\n    {\n      std::cerr << std::endl << std::endl\n                << \"----------------------------------------------------\"\n                << std::endl;\n      std::cerr << \"Unknown exception!\" << std::endl\n                << \"Aborting!\" << std::endl\n                << \"----------------------------------------------------\"\n                << std::endl;\n      return 1;\n    }\n\n  return 0;\n}\n", "meta": {"hexsha": "7253cfb4f9a016a76410fa5f12d5cf37e5e60ad7", "size": 108744, "ext": "cc", "lang": "C++", "max_stars_repo_path": "MHD/examples/step-31/step-31.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-31/step-31.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-31/step-31.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.9331031506, "max_line_length": 113, "alphanum_fraction": 0.6521371294, "num_tokens": 24426, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5698526660244837, "lm_q2_score": 0.5926665999540697, "lm_q1q2_score": 0.33773264204749276}}
{"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 \"Point.h\"\n#include \"Cavity.h\"\n#include \"Verifier.h\"\n\n#include \"galois/Galois.h\"\n#include \"galois/Bag.h\"\n#include \"galois/Timer.h\"\n#include \"galois/graphs/SpatialTree.h\"\n#include \"Lonestar/BoilerPlate.h\"\n#include \"llvm/Support/CommandLine.h\"\n\n#include \"galois/runtime/Profile.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    inputname(cll::Positional, cll::desc(\"<input file>\"), cll::Required);\nstatic cll::opt<std::string>\n    doWriteMesh(\"writemesh\",\n                cll::desc(\"Write the mesh out to files with basename\"),\n                cll::value_desc(\"basename\"));\n\nusing Tree = typename galois::graphs::SpatialTree2d<Point*>;\n\n//! All Point* refer to elements in this bag\nusing basePointBag = typename galois::InsertBag<Point>;\n\n//! [Define Insert Bag]\nusing ptrPointBag = typename galois::InsertBag<Point*>;\n\n//! Our main functor\nstruct Process {\n  Graph& graph;\n  Tree& tree;\n  ptrPointBag& ptrPoints;\n\n  Process(Graph& g, Tree& t, ptrPointBag& p)\n      : graph(g), tree(t), ptrPoints(p) {}\n\n  typedef galois::PerIterAllocTy Alloc;\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** rp = tree.find(p->t().x(), p->t().y());\n    if (!rp)\n      return false;\n\n    (*rp)->get(galois::MethodFlag::WRITE);\n\n    GNode someNode = (*rp)->someElement();\n\n    // Not in mesh yet\n    if (!someNode) {\n      GALOIS_DIE(\"unreachable\");\n      return false;\n    }\n\n    return planarSearch(p, someNode, node);\n  }\n\n  void generateMesh() {\n    typedef galois::worklists::PerThreadChunkLIFO<32> CA;\n    galois::for_each(galois::iterate(ptrPoints),\n                     [&, self = this](Point* p, auto& ctx) {\n                       p->get(galois::MethodFlag::WRITE);\n                       assert(!p->inMesh());\n\n                       GNode node;\n                       if (!self->findContainingElement(p, node)) {\n                         // Someone updated an element while we were searching,\n                         // producing a semi-consistent state ctx.push(p);\n                         // Current version is safe with locking so this\n                         // shouldn't happen\n                         GALOIS_DIE(\"unreachable\");\n                         return;\n                       }\n\n                       assert(self->graph.getData(node).inTriangle(p->t()));\n                       assert(self->graph.containsNode(node));\n\n                       Cavity<Alloc> cav(self->graph, ctx.getPerIterAlloc());\n                       cav.init(node, p);\n                       cav.build();\n                       cav.update();\n                       self->tree.insert(p->t().x(), p->t().y(), p);\n                     },\n                     galois::no_pushes(), galois::per_iter_alloc(),\n                     galois::loopname(\"Main\"), galois::wl<CA>());\n  }\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 (const 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    tree.init(minX, minY, maxX, maxY);\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  Tree& tree;\n\npublic:\n  ReadPoints(PointList& p, Tree& t) : points(p), tree(t) {}\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\nstruct ReadInput {\n  Graph& graph;\n  Tree& tree;\n  basePointBag& basePoints;\n  ptrPointBag& ptrPoints;\n\n  ReadInput(Graph& g, Tree& t, basePointBag& b, ptrPointBag& p)\n      : graph(g), tree(t), basePoints(b), ptrPoints(p) {}\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    tree.insert(p1->t().x(), p1->t().y(), p1);\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  struct centerXCmp {\n    template <typename T>\n    bool operator()(const T& lhs, const T& rhs) const {\n      return lhs.t().x() < rhs.t().x();\n    }\n  };\n\n  struct centerYCmp {\n    template <typename T>\n    bool operator()(const T& lhs, const T& rhs) const {\n      return lhs.t().y() < rhs.t().y();\n    }\n  };\n\n  struct centerYCmpInv {\n    template <typename T>\n    bool operator()(const T& lhs, const T& rhs) const {\n      return rhs.t().y() < lhs.t().y();\n    }\n  };\n\n  template <typename Iter>\n  void divide(const Iter& b, const Iter& e) {\n    if (std::distance(b, e) > 64) {\n      std::sort(b, e, centerXCmp());\n      Iter m = galois::split_range(b, e);\n      std::sort(b, m, centerYCmpInv());\n      std::sort(m, e, centerYCmp());\n      divide(b, galois::split_range(b, m));\n      divide(galois::split_range(b, m), m);\n      divide(m, galois::split_range(m, e));\n      divide(galois::split_range(m, e), e);\n    } else {\n      std::random_shuffle(b, e);\n    }\n  }\n\n  void layoutPoints(PointList& points) {\n    divide(points.begin(), points.end() - 3);\n    galois::do_all(galois::iterate(points.begin(), points.end() - 3),\n                   [&](Point& p) {\n                     Point* pr = &basePoints.push(p);\n                     ptrPoints.push(pr);\n                   });\n    //! [Insert elements into InsertBag]\n    Point* p1 = &basePoints.push(*(points.end() - 1));\n    Point* p2 = &basePoints.push(*(points.end() - 2));\n    Point* p3 = &basePoints.push(*(points.end() - 3));\n    //! [Insert elements into InsertBag]\n    addBoundaryNodes(p1, p2, p3);\n  }\n\n  void operator()(const std::string& filename) {\n    PointList points;\n    ReadPoints(points, tree).from(filename);\n\n    std::cout << \"configuration: \" << points.size() << \" points\\n\";\n\n    galois::preAlloc(2 * 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::pagePoolSize()) // in pages\n    );\n    galois::reportPageAlloc(\"MeminfoPre\");\n\n    layoutPoints(points);\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\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\nint main(int argc, char** argv) {\n  galois::SharedMemSys G;\n  LonestarStart(argc, argv, name, desc, url);\n\n  Graph graph;\n  Tree tree;\n  basePointBag basePoints;\n  ptrPointBag ptrPoints;\n\n  ReadInput(graph, tree, basePoints, ptrPoints)(inputname);\n\n  galois::StatTimer T;\n  T.start();\n  galois::runtime::profileVtune(\n      [&]() { Process(graph, tree, ptrPoints).generateMesh(); },\n      \"MeshGeneration\");\n  T.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, tree).from(inputname);\n    writePoints(base.append(\".node\"), points);\n  }\n\n  return 0;\n}\n", "meta": {"hexsha": "b1bcc1a2497fdf5577d4c3aa00df175d46e27cd7", "size": 16548, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lonestar/delaunaytriangulation/DelaunayTriangulation.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/delaunaytriangulation/DelaunayTriangulation.cpp", "max_issues_repo_name": "rohankadekodi/compilers_project", "max_issues_repo_head_hexsha": "2f9455a5d0c516b9f1766afd1cdac1b86c930ec0", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-07-26T22:09:49.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-26T22:09:49.000Z", "max_forks_repo_path": "lonestar/delaunaytriangulation/DelaunayTriangulation.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": "2021-07-26T14:46:51.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-09T11:32:09.000Z", "avg_line_length": 29.9240506329, "max_line_length": 85, "alphanum_fraction": 0.5817017162, "num_tokens": 4524, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5926665855647395, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.3377326251886422}}
{"text": "// This file is part of LatticeTester.\n//\n// LatticeTester\n// Copyright (C) 2012-2021  The LatNet Builder author's, supervised by Pierre L'Ecuyer, Universite de Montreal.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//     http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\n#include \"netbuilder/Helpers/JoeKuo.h\"\n#include \"netbuilder/Helpers/Path.h\"\n#include <cmath>\n\n#include <string>\n#include <fstream>\n#include <boost/algorithm/string.hpp>\n#include <boost/filesystem.hpp>\n\nusing namespace std;\n\nnamespace NetBuilder { namespace JoeKuo {\n\n//===========================================================================\n\nLatticeTester::Weight Weights::getWeight (const LatticeTester::Coordinates& projection) const\n{\n   if (projection.size()==2)\n   {\n         return std::pow((LatticeTester::Weight).9999, *projection.rbegin());\n   }\n   // fall back to zero\n   return 0.0;\n}\n\n//===========================================================================\n\nvoid Weights::format(ostream& os) const\n{\n   using LatticeTester::operator<<;\n   os << \"Weights()\";\n}\n\n//===========================================================================\n\nconst char* ws = \" \\t\\n\\r\\f\\v\";\n\n// trim from end (right)\ninline std::string& rtrim(std::string& s, const char* t = ws)\n{\n      s.erase(s.find_last_not_of(t) + 1);\n      return s;\n}\n\n// trim from beginning (left)\ninline std::string& ltrim(std::string& s, const char* t = ws)\n{\n      s.erase(0, s.find_first_not_of(t));\n      return s;\n}\n\n// trim from both ends (left & right)\ninline std::string& trim(std::string& s, const char* t = ws)\n{\n      return ltrim(rtrim(s, t), t);\n}    \n\nstd::vector<std::vector<uInteger>> readJoeKuoDirectionNumbers(Dimension dimension)\n{\n      assert(dimension >= 1 && dimension <= 21201);\n      std::string path = PATH_TO_LATNETBUILDER_DIR + \"/../share/latnetbuilder/data/JoeKuoSobolNets.csv\";\n      std::vector<std::vector<uInteger>> res(dimension);\n      if (boost::filesystem::exists(path)){\n            std::ifstream file(path);\n            std::string sent;\n\n            do\n            {\n            getline(file,sent);\n            trim(sent);\n            }\n            while (sent != \"###\");\n\n            getline(file,sent);\n\n            for(unsigned int i = 1; i <= dimension; ++i)\n            {\n                  if(getline(file,sent))\n                  {\n                        std::vector<std::string> fields;\n                        boost::split( fields, sent, boost::is_any_of( \";\" ) );\n                        for( const auto& token : fields)\n                        {\n                              res[i-1].push_back(std::stol(token));\n                        }\n                  }\n                  else\n                  {\n                        break;\n                  }\n            }\n      }\n      else{\n            throw runtime_error(\"Unable to locate data folder. The value of PATH_TO_LATNETBUILDER_DIR is probably incorrect. See netbuilder/Path.h.\");\n      }\n      return res;\n}\n\nstd::vector<DirectionNumbers> getJoeKuoDirectionNumbers(Dimension dimension)\n{\n      std::vector<std::vector<uInteger>> tmp = readJoeKuoDirectionNumbers(dimension);\n      std::vector<DirectionNumbers> genVals(dimension);\n      for(unsigned int j = 0; j < dimension; ++j)\n      {\n            genVals[j] = DirectionNumbers(j,tmp[j]);\n      }\n      return genVals;\n}\n\nDigitalNet<NetConstruction::SOBOL> createJoeKuoSobolNet(Dimension dimension, MatrixSize size)\n{\n      auto genVals = getJoeKuoDirectionNumbers(dimension);\n      return DigitalNet<NetConstruction::SOBOL>(dimension, size, std::move(genVals));\n}\n\nstd::unique_ptr<DigitalNet<NetConstruction::SOBOL>> createPtrToJoeKuoSobolNet(Dimension dimension, MatrixSize size)\n{\n      auto genVals = getJoeKuoDirectionNumbers(dimension);\n      return std::make_unique<DigitalNet<NetConstruction::SOBOL>>(dimension, size, std::move(genVals));\n}\n\n}} // namespace\n", "meta": {"hexsha": "1ff5137ae2409cbb64a6a4d550c767a59749243c", "size": 4336, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/NetBuilder/Helpers/JoeKuo.cc", "max_stars_repo_name": "YochevedDarmon/latnetbuilder", "max_stars_repo_head_hexsha": "7df3a7ba89e10ca51d4af347b75cdb0987e5151c", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2020-01-21T06:08:51.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-24T16:11:31.000Z", "max_issues_repo_path": "src/NetBuilder/Helpers/JoeKuo.cc", "max_issues_repo_name": "YochevedDarmon/latnetbuilder", "max_issues_repo_head_hexsha": "7df3a7ba89e10ca51d4af347b75cdb0987e5151c", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2019-10-31T07:49:28.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-03T12:07:49.000Z", "max_forks_repo_path": "src/NetBuilder/Helpers/JoeKuo.cc", "max_forks_repo_name": "YochevedDarmon/latnetbuilder", "max_forks_repo_head_hexsha": "7df3a7ba89e10ca51d4af347b75cdb0987e5151c", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2016-07-27T19:25:26.000Z", "max_forks_repo_forks_event_max_datetime": "2018-05-22T20:00:47.000Z", "avg_line_length": 30.9714285714, "max_line_length": 150, "alphanum_fraction": 0.5869464945, "num_tokens": 1000, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5926665855647394, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.33773262518864217}}
{"text": "/* Copyright (c) 2015, Julian Straub <jstraub@csail.mit.edu>, Randi Cabezas <rcabezas@csail.mit.edu>\r\n * Licensed under the MIT license. See the license file LICENSE.\r\n */\r\n\r\n#pragma once\r\n#include <iostream>\r\n#include <stdint.h>\r\n#include <vector>\r\n#include <Eigen/Dense>\r\n\r\n#include <boost/shared_ptr.hpp>\r\n\r\n#include <dpMM/dpMM.hpp>\r\n#include <dpMM/cat.hpp>\r\n#include <dpMM/dir.hpp>\r\n#include <dpMM/niw.hpp>\r\n#include <dpMM/sampler.hpp>\r\n#include <dpMM/basemeasure.hpp>\r\n#include <dpMM/niwBaseMeasure.hpp>\r\n#include <dpMM/niwSphere.hpp>\r\n#include <dpMM/dirBaseMeasure.hpp>\r\n#include <mmf/mfBaseMeasure.hpp>\r\n\r\nusing namespace Eigen;\r\nusing std::cout;\r\nusing std::endl;\r\nusing boost::shared_ptr;\r\nusing std::vector;\r\n\r\ntemplate<typename T=double>\r\nclass DirMultiNaiveBayes : public DpMM<T>{\r\n\r\npublic:\r\n  DirMultiNaiveBayes(std::ifstream &in, boost::mt19937 *rng);\r\n  DirMultiNaiveBayes(const Dir<Cat<T>, T>& alpha, const vector<boost::shared_ptr<BaseMeasure<T> > >&thetas);\r\n  DirMultiNaiveBayes(const Dir<Cat<T>, T>& alpha, const vector< vector<boost::shared_ptr<BaseMeasure<T> > > >&thetas);\r\n  virtual ~DirMultiNaiveBayes();\r\n\r\n  virtual void loadData(const vector<vector<Matrix<T,Dynamic,Dynamic> > > &x);//does nothing other than load data\r\n  virtual void initialize(const vector<vector< Matrix<T,Dynamic,Dynamic> > >&x);\r\n  virtual void initializeNoParamSampling(const vector<vector< Matrix<T,Dynamic,Dynamic> > >&x);\r\n  virtual void initialize(const vector<vector< Matrix<T,Dynamic,Dynamic> > >&x, VectorXu &z);\r\n  virtual void initialize(const boost::shared_ptr<ClGMMData<T> >&cld)\r\n    {cout<<\"not supported\"<<endl; assert(false);};\r\n\r\n  virtual void sampleLabels();\r\n  virtual void MAPLabel();\r\n  virtual void sampleParameters();\r\n\r\n  virtual T logJoint(bool verbose=false);\r\n  virtual const VectorXu& labels(){return z_;};\r\n  virtual const VectorXu& getLabels(){return z_;};\r\n  virtual uint32_t getK() const { return K_;};\r\n  virtual uint32_t getM() const { return M_;};\r\n  virtual uint32_t getN() const { return Nd_;};\r\n\r\n//  virtual MatrixXu mostLikelyInds(uint32_t n);\r\n  virtual MatrixXu mostLikelyInds(uint32_t n, Matrix<T,Dynamic,Dynamic>& logLikes);\r\n\r\n  Matrix<T,Dynamic,1> getCounts();\r\n\r\n  virtual void inferAll(uint32_t nIter, bool verbose=false);\r\n\r\n  virtual void dump(std::ofstream& fOutMeans, std::ofstream& fOutCovs);\r\n  virtual void dump_clean(std::ofstream &out);\r\n\r\n  virtual vector<boost::shared_ptr<BaseMeasure<T> > > getThetas(uint32_t m) {\r\n\t  return(thetas_[m]);\r\n  };\r\n  virtual boost::shared_ptr<BaseMeasure<T> > getThetas(uint32_t m, uint32_t k) {\r\n\t  return(thetas_[m][k]);\r\n  };\r\n\r\n  virtual void setTheta(uint32_t m, uint32_t k, boost::shared_ptr<BaseMeasure<T> > newTheta ) {\r\n\t  thetas_[m][k] = newTheta;\r\n  };\r\n\r\n\r\n  virtual vector<T> evalLogLik(const vector<Matrix<T,Dynamic,1> > xnew, const vector<uint32_t> clusterInd, \r\n\t\t\t\t\t\t\t   const vector<uint32_t> comp2eval =vector<uint32_t>());\r\n\r\n  virtual uint32_t sampleLabels(const vector<Matrix<T,Dynamic,1> > xnew,\r\n\t\t\t\t\t\t\t\tconst vector<uint32_t> comp2eval =vector<uint32_t>());\r\n  virtual vector<uint32_t> sampleLabels(const vector<vector<Matrix<T,Dynamic,1> > > xnew,\r\n\t\t\t\t\t\t\t\t\t\tconst vector<uint32_t> comp2eval =vector<uint32_t>());\r\n  virtual uint32_t MAPLabels(const vector<Matrix<T,Dynamic,1> > xnew,\r\n\t\t\t\t\t\t\t const vector<uint32_t> comp2eval =vector<uint32_t>());\r\n  virtual vector<uint32_t> MAPLabels(const vector<vector<Matrix<T,Dynamic,1> > > xnew,\r\n\t\t\t\t\t\t\t\t\t const vector<uint32_t> comp2eval =vector<uint32_t>());\r\n  virtual void updatePDF();\r\n\r\n  vector<uint32_t> getLogEvalItersHist() {return logJointIterEval;}\r\n  vector<T> getLogJointHist() {return logJointHist;}\r\n\r\nprotected:\r\n  virtual T evalLogLik(const vector<Matrix<T,Dynamic,1> > xnew, const uint32_t clusterInd,\r\n\t\t\t\t\t   const vector<uint32_t> comp2eval);\r\n  virtual uint32_t labels_sample_max(const vector<Matrix<T,Dynamic,1> > xnew,\r\n\t\t\t\t\t\t\t\t\t const vector<uint32_t> comp2eval, const bool return_MAP_labels=false);\r\n\r\n  uint32_t Nd_;\r\n  uint32_t K_; //num cluseters\r\n  uint32_t M_; //num data sources\r\n  Dir<Cat<T>, T> dir_;\r\n  Cat<T> pi_;\r\n#ifdef CUDA\r\n  SamplerGpu<T>* sampler_;\r\n#else\r\n  Sampler<T>* sampler_;\r\n#endif\r\n  virtual void initialize_sampler();\r\n  Matrix<T,Dynamic,Dynamic> pdfs_;\r\n//  Cat cat_;\r\n  vector<vector<boost::shared_ptr<BaseMeasure<T> > > > thetas_;  // theta_[M][K]\r\n\r\n  //suffiecient stats\r\n  vector<vector<Matrix<T,Dynamic,Dynamic> > > x_; //x_[M][doc](:,word)\r\n  VectorXu z_;\r\n\r\n  virtual void helper_setDims();\r\n  vector<VectorXu> dataDim;\r\n\r\n  vector<uint32_t> logJointIterEval;\r\n  vector<T> logJointHist;\r\n};\r\n\r\n// --------------------------------------- impl -------------------------------\r\n\r\ntemplate<typename T>\r\nvoid DirMultiNaiveBayes<T>::initialize_sampler() {\r\n\tif (sampler_ != NULL) {\r\n\t\tdelete sampler_;\r\n\t\tsampler_ = NULL;\r\n\t}\r\n\t//initialize sampler\r\n\t#ifdef CUDA\r\n\t  sampler_ = new SamplerGpu<T>(uint32_t(Nd_),K_,dir_.pRndGen_);\r\n\t#else\r\n\t  sampler_ = new Sampler<T>(dir_.pRndGen_);\r\n\t#endif\r\n}\r\n\r\ntemplate<typename T>\r\nDirMultiNaiveBayes<T>::DirMultiNaiveBayes(std::ifstream &in, boost::mt19937 *rng) :\r\n dir_(Matrix<T,2,1>::Ones(),rng), pi_(dir_.sample()),sampler_(NULL)\r\n{\r\n\t//initialize the class from the file pointer given\r\n\tin >> M_;\r\n\tin >> K_;\r\n\tin >> Nd_;\r\n\r\n\tvector<uint32_t> dim;\r\n\tvector<baseMeasureType> type;\r\n\tMatrix<T,Dynamic,1> alpha(K_), pi(K_);\r\n\r\n\tfor(uint32_t m = 0; m<M_; ++m){\r\n\t\tuint32_t temp;\r\n\t\tin >> temp;\r\n\t\tdim.push_back(temp);\r\n\t}\r\n\r\n\tfor(uint32_t m = 0; m<M_; ++m){\r\n\t\tuint32_t temp;\r\n\t\tin >> temp;\r\n\t\ttype.push_back(baseMeasureType(temp));\r\n\t}\r\n\r\n\tz_ = VectorXu(Nd_);\r\n\tfor(uint32_t n=0; n<Nd_; ++n)\r\n\t\tin >> z_(n);\t\r\n\r\n\tfor(uint32_t k=0; k<K_; ++k)\r\n\t\tin >> alpha(k);\r\n\r\n\tfor(uint32_t k=0; k<K_; ++k)\r\n\t\tin >> pi(k);\r\n\r\n\tpdfs_ = Matrix<T,Dynamic,Dynamic>(Nd_,K_);\r\n\t//for(uint32_t n=0; n<Nd_*K_; ++n)\r\n\t//\tin >> pdfs_(n%Nd_, (n-(n%Nd_))/Nd_);\r\n\t//\t//in >> pdfs_((n-(n%Nd_))/Nd_, n%Nd_);\r\n\t////pdfs_ = pdfs_.transpose();\r\n\r\n\t//get parameters\r\n\tfor(uint32_t m=0; m<M_; ++m) {\r\n\t\tbaseMeasureType typeIter = baseMeasureType(type[m]);\r\n\t\tvector<boost::shared_ptr<BaseMeasure<T> > > thetaM;\r\n\t\tif(typeIter==NIW_SAMPLED) {\r\n\t\t\tuint32_t Diter = dim[m];\r\n\t\t\tT nu, kappa;\r\n\t\t\tMatrix<T,Dynamic,Dynamic> scatter(Diter, Diter), sigma(Diter,Diter);\r\n\t\t\tMatrix<T,Dynamic,1> theta(Diter), mu(Diter);\r\n\t\t\tfor(uint32_t k=0; k<K_; ++k) {\r\n\t\t\t\t//get nu and kappa\r\n\t\t\t\t\tin>> nu;\r\n\t\t\t\t\tin>> kappa;\r\n\t\t\t\t//get theta\r\n\t\t\t\t\tfor(uint32_t n=0; n<Diter; ++n)\r\n\t\t\t\t\t\tin >> theta(n);\r\n\t\t\t\t\ttheta = theta.transpose();\r\n\t\t\t\t//get scatter\r\n\t\t\t\t\tfor(uint32_t n=0; n<Diter*Diter; ++n)\r\n\t\t\t\t\t\tin >> scatter((n-(n%Diter))/Diter, n%Diter);\r\n\t\t\t\t//get mean\r\n\t\t\t\t\tfor(uint32_t n=0; n<Diter; ++n)\r\n\t\t\t\t\t\tin >> mu(n);\r\n\t\t\t\t\tmu = mu.transpose();\r\n\t\t\t\t//get sigma\r\n\t\t\t\t\tfor(uint32_t n=0; n<Diter*Diter; ++n)\r\n\t\t\t\t\t\tin >> sigma((n-(n%Diter))/Diter, n%Diter);\r\n\r\n\t\t\t\t//build theta[m][k]\r\n\t\t\t\tNIW<T> niw(scatter,theta,nu,kappa,rng);\r\n\t\t\t\tNormal<T> normal(mu,sigma,rng);\r\n\t\t\t\tboost::shared_ptr<NiwSampled<T> > baseIter( new NiwSampled<T>(niw, normal));\r\n\r\n\t\t\t\t//set\r\n\t\t\t\tthetaM.push_back(boost::shared_ptr<BaseMeasure<T> >(baseIter));\r\n\t\t\t}\r\n\t\t} else if(typeIter==NIW_SPHERE) {\r\n\t\t\tuint32_t Diter = dim[m]-1;\r\n\t\t\tT nu;\r\n\t\t\tT counts;\r\n\t\t\tMatrix<T,Dynamic,Dynamic> scatter(Diter, Diter), sigma(Diter,Diter),delta(Diter,Diter);\r\n\t\t\tMatrix<T,Dynamic,1> mu(Diter+1), mu_prior(Diter), north(Diter+1);\r\n\t\t\tfor(uint32_t k=0; k<K_; ++k) {\r\n\t\t\t\t//get nu\r\n\t\t\t\t\tin>> nu;\r\n\t\t\t\t\tin>> counts;\r\n\t\t\t\t//get prior mean\r\n\t\t\t\t\tfor(uint32_t n=0; n<Diter; ++n)\r\n\t\t\t\t\t\tin>> mu_prior(n);\r\n\t\t\t\t//get scatter\r\n\t\t\t\t\tfor(uint32_t n=0; n<Diter*Diter; ++n)\r\n\t\t\t\t\t\tin >> scatter((n-(n%Diter))/Diter, n%Diter);\r\n\t\t\t\t//get delta\r\n\t\t\t\t\tfor(uint32_t n=0; n<Diter*Diter; ++n)\r\n\t\t\t\t\t\tin >> delta((n-(n%Diter))/Diter, n%Diter);\r\n\t\t\t\t//get mean\r\n\t\t\t\t\tfor(uint32_t n=0; n<(Diter+1); ++n)\r\n\t\t\t\t\t\tin >> mu(n);\r\n\t\t\t\t\tmu = mu.transpose();\r\n\t\t\t\t//get sigma\r\n\t\t\t\t\tfor(uint32_t n=0; n<Diter*Diter; ++n)\r\n\t\t\t\t\t\tin >> sigma((n-(n%Diter))/Diter, n%Diter);\r\n\t\t\t\t//get north\r\n\t\t\t\t\tfor(uint32_t n=0; n<(Diter+1); ++n)\r\n\t\t\t\t\t\tin >> north(n);\r\n\t\t\t\t\tnorth = north.transpose();\r\n\r\n\t\t\t\t//build theta[m][k]\r\n\t\t\t\tIW<T> iw(delta,nu, scatter, mu_prior, counts, rng);\r\n\t\t\t\t//IW<T> iw(delta,nu, rng);\r\n\t\t\t\tNiwSphere<T> niwSp(iw,rng);\r\n\t\t\t\tniwSp.S_ = Sphere<T>(north);\r\n\t\t\t\tniwSp.normalS_ = NormalSphere<T>(mu,sigma,rng);\r\n\t\t\t\t\r\n\r\n\t\t\t\t//set\r\n\t\t\t\tthetaM.push_back(boost::shared_ptr<BaseMeasure<T> >(niwSp.copy()));\r\n\t\t\t\t//boost::shared_ptr<NiwSphere<T> > baseIter( new NiwSphere<T>(iw,rng));\r\n\t\t\t\t//thetaM.push_back(boost::shared_ptr<BaseMeasure<T> >(baseIter));\r\n\t\t\t\t\r\n\t\t\t}\r\n\r\n\t\t} else if(typeIter==DIR_SAMPLED) {\r\n\t\t\tuint32_t Diter = dim[m];\r\n\t\t\tT localCount;\r\n\t\t\tMatrix<T,Dynamic,1> post_alpha(Diter), counts(Diter), pdf(Diter);\r\n\r\n\t\t\tfor(uint32_t k=0; k<K_; ++k) {\r\n\t\t\t\t//get dir alpha\r\n\t\t\t\tfor(uint32_t n=0; n<Diter; ++n)\r\n\t\t\t\t\tin >> post_alpha(n); \t\t\r\n\r\n\t\t\t\t//get dir counts\r\n\t\t\t\tfor(uint32_t n=0; n<Diter; ++n)\r\n\t\t\t\t\tin >> counts(n); \t\t\r\n\r\n\t\t\t\t//get disc pdf\r\n\t\t\t\tfor(uint32_t n=0; n<Diter; ++n)\r\n\t\t\t\t\tin >> pdf(n); \t\t\r\n\r\n\t\t\t\tin >> localCount;\r\n\r\n\t\t\t\t//build theta[m][k]\r\n\t\t\t\tDir<Cat<T>,T> dirBase(post_alpha,counts, rng);\r\n\t\t\t\tDirSampled<Cat<T>,T> dirSamp(dirBase);\r\n\t\t\t\tCat<T> disc(pdf,rng);\r\n\t\t\t\tdirSamp.disc_ = disc;\r\n\t\t\t\tdirSamp.count_\t= localCount;\r\n\r\n\t\t\t\t//set\r\n\t\t\t\tthetaM.push_back(boost::shared_ptr<BaseMeasure<T> >(dirSamp.copy()));\r\n\t\t\t}\r\n\r\n\t\t} else if(typeIter==MF_T) {\r\n\t\t\t//\t\t\tuint32_t Diter = dim[m];\r\n\t\t\t//\t\t\tT localCount;\r\n\t\t\tMatrix<T,Dynamic,1> post_alpha(6), counts(6), pi_pdf(6);\r\n\t\t\tpost_alpha.fill(1);\r\n\t\t\tcounts.fill(0); \r\n\t\t\tpi_pdf.fill(0);\r\n\r\n\t\t\tMatrix<T,3,3>  R;\r\n\t\t\tDir<Cat<T>, T> alpha(post_alpha,rng);\r\n\t\t\tCat<T> pi(pi_pdf,rng);\r\n\t\t\tstd::vector<shared_ptr<BaseMeasure<T> > > iwTs;\r\n\t\t\tstd::vector<NormalSphere<T> > TGs;\r\n\t\t\tuint32_t nIter;\r\n\r\n\t\t\tfor(uint32_t k=0; k<K_; ++k)\r\n\t\t\t{\r\n        in >> nIter;\r\n        //get dir alpha\r\n        for(uint32_t n=0; n<6; ++n) in >> post_alpha(n); \t\t\r\n        //get dir counts\r\n        for(uint32_t n=0; n<6; ++n) in >> counts(n); \t\t\r\n        //get pi pdf\r\n        for(uint32_t n=0; n<6; ++n) in >> pi_pdf(n); \t\t\r\n        alpha.alpha_ = post_alpha;\r\n        alpha.setCounts(counts);\r\n        pi.pdf(pi_pdf);\r\n        // get rotation\r\n        for(uint32_t n=0; n<9; ++n) in >> R(n/3,n%3); \t\t\r\n        for(uint32_t j=0; j<6; ++j)\r\n        {\r\n          // load IW in tangent space\r\n          Matrix<T,Dynamic,Dynamic> Delta(2,2);\r\n          Matrix<T,Dynamic,Dynamic> Scatter(2,2);\r\n          Matrix<T,Dynamic,1> mean(2);\r\n          T nu,count;\r\n          in >> nu;\r\n          for(uint32_t n=0; n<4; ++n) in >> Delta(n/2,n%2); \t\t\r\n          for(uint32_t n=0; n<4; ++n) in >> Scatter(n/2,n%2); \t\t\r\n          for(uint32_t n=0; n<2; ++n) in >> mean(n); \t\t\r\n          in >> count;\r\n          IW<T> iw(Delta,nu,Scatter,mean,count,rng);\r\n          iwTs.push_back(shared_ptr<IwTangent<T> >(\r\n                new IwTangent<T>(iw,rng)));\r\n          // load tangent space gaussians\r\n          Matrix<T,Dynamic,Dynamic> Sigma(2,2);\r\n          Matrix<T,Dynamic,1> mu(3);\r\n          for(uint32_t n=0; n<4; ++n) in >> Sigma(n/2,n%2); \t\t\r\n          for(uint32_t n=0; n<3; ++n) in >> mu(n); \t\t\r\n          TGs.push_back(NormalSphere<T>(mu,Sigma,rng));\r\n          reinterpret_cast<IwTangent<T>* >(\r\n              iwTs[j].get())->normalS_=TGs[j];\r\n        };\r\n        // labels -- not set\r\n        uint32_t Nk = 0;\r\n        in >> Nk;\r\n        VectorXu z(Nk);\r\n        for(uint32_t n=0; n<Nk; ++n) in >> z(n);\r\n        // build model\r\n        DirMM<T> dirMM(alpha,iwTs);\r\n        MfPrior<T> mfPrior(dirMM, nIter);\r\n        MF<T> mf(R,pi,TGs);\r\n\t\t\t\t//set\r\n\t\t\t\tthetaM.push_back(boost::shared_ptr<BaseMeasure<T> >(\r\n              new MfBase<T>(mfPrior, mf)));\r\n\t\t\t}\r\n\r\n\t\t} else {\r\n\t\t\t\tstd::cerr << \"[DirMultiNaiveBayes::dump_clean] error saving...returning\" << endl;\r\n\t\t\t\treturn;\r\n\t\t}\r\n\t\tthetas_.push_back(thetaM);\r\n\t}\r\n\r\n\tdir_ =  Dir<Cat<T>, T>(alpha,rng);\r\n\tpi_ = Cat<T>(pi,rng);\r\n\r\n\r\n\tthis->initialize_sampler();\r\n\r\n\t//cout << \"M:\" << M_ << \" K: \" << K_ << \" nd: \" << Nd_ << endl;\r\n\t//for(uint32_t m = 0; m<M_; ++m){\r\n\t//\tcout << m << \": d=\"<< dim[m] << \", type=\" << type[m] << endl;\r\n\t//}\r\n\t//cout << \"z_ \" << z_.transpose() << endl;\r\n\t//cout << \"alpha \" << alpha.transpose() << endl;\r\n}\r\n\r\ntemplate<typename T>\r\nDirMultiNaiveBayes<T>::DirMultiNaiveBayes(const Dir<Cat<T>,T>& alpha,\r\n    const vector<boost::shared_ptr<BaseMeasure<T> > >& thetas) :\r\n  sampler_(NULL), K_(alpha.K_), dir_(alpha), pi_(dir_.sample()), M_(uint32_t(thetas.size()))\r\n{\r\n\tfor (uint32_t m=0; m<M_; ++m)\r\n\t{\t\r\n\t\tvector<boost::shared_ptr<BaseMeasure<T> > > temp;\r\n\t\tfor (uint32_t k=0; k<K_; ++k)\r\n\t\t{   \t\r\n      \t\ttemp.push_back(boost::shared_ptr<BaseMeasure<T> >(thetas[m]->copy()));\r\n      \t}\r\n      thetas_.push_back(temp);\r\n    }\r\n\r\n#ifndef NDEBUG\r\n\tfor(uint32_t m=0; m<int(M_); ++m) {\r\n\t\tfor(int k=0; k<int(K_); ++k) {\r\n\t\t\t\tthetas_[m][k]->print();\r\n\t\t}\r\n\t}\r\n#endif\r\n\r\n\r\n};\r\n\r\ntemplate<typename T>\r\nDirMultiNaiveBayes<T>::DirMultiNaiveBayes(const Dir<Cat<T>,T>& alpha,\r\n    const vector< vector<boost::shared_ptr<BaseMeasure<T> > > >& theta) :\r\n K_(alpha.K_), M_(uint32_t(theta.size())),dir_(alpha),\r\n  pi_(dir_.sample()), sampler_(NULL),thetas_(theta)\r\n{ };\r\n\r\ntemplate<typename T>\r\nDirMultiNaiveBayes<T>::~DirMultiNaiveBayes()\r\n{\r\n  if (sampler_ != NULL) {\r\n\tdelete sampler_;\r\n\tsampler_ = NULL;\r\n  }\r\n};\r\n\r\ntemplate <typename T>\r\nMatrix<T,Dynamic,1> DirMultiNaiveBayes<T>::getCounts()\r\n{\r\n  return counts<T,uint32_t>(z_,K_);\r\n};\r\n\r\ntemplate<typename T>\r\nvoid DirMultiNaiveBayes<T>::loadData(const vector<vector<Matrix<T,Dynamic,Dynamic> > > &x){\r\n  x_ = x;\r\n  this->helper_setDims();\r\n}\r\n\r\ntemplate<typename T>\r\nvoid DirMultiNaiveBayes<T>::initializeNoParamSampling(const vector< vector< Matrix<T,Dynamic,Dynamic> > > &x)\r\n{\r\n  // randomly init labels from prior\r\n  Nd_= uint32_t(x.front().size());\r\n\r\n  z_ = VectorXu::Zero(Nd_);\r\n  //init data and labels from given \r\n  pi_.sample(z_); \r\n  \r\n  x_ = x;\r\n\r\n  pdfs_.setZero(Nd_,K_);\r\n\r\n  this->initialize_sampler();\r\n  this->helper_setDims();\r\n};\r\n\r\ntemplate<typename T>\r\nvoid DirMultiNaiveBayes<T>::initialize(const vector< vector< Matrix<T,Dynamic,Dynamic> > > &x)\r\n{\r\n  uint32_t Nd= uint32_t(x.front().size());\r\n\r\n  // randomly init labels from prior\r\n  VectorXu z;\r\n  z.setZero(Nd);\r\n  Cat<T> pi = dir_.sample();\r\n  pi.sample(z);\r\n\r\n  //delegate the initialization to the main intitialization function\r\n  this->initialize(x,z);\r\n};\r\n\r\ntemplate<typename T>\r\nvoid DirMultiNaiveBayes<T>::initialize(const vector< vector< Matrix<T,Dynamic,Dynamic> > > &x, VectorXu &z)\r\n{\r\n  Nd_= uint32_t(x.front().size());\r\n\r\n  //init data and labels from given\r\n  x_ = x;\r\n  z_ = z;\r\n\r\n  pi_ = dir_.sample();\r\n\r\n  pdfs_.setZero(Nd_,K_);\r\n\r\n  this->initialize_sampler();\r\n  this->helper_setDims();\r\n  this->sampleParameters();\r\n};\r\n\r\n\r\n\r\ntemplate<typename T>\r\nvoid DirMultiNaiveBayes<T>::helper_setDims()\r\n{\r\n\tdataDim.clear();\r\n\tdataDim.reserve(M_);\r\n\tfor(uint32_t m=0; m<M_; ++m) {\r\n\t\tVectorXu temp(x_[m].size());\r\n\t\tfor(uint32_t t=0; t<x_[m].size(); ++t)\r\n\t\t\ttemp(t) = uint32_t(x_[m][t].cols());\r\n\t\tdataDim.push_back(temp);\r\n\t}\r\n}\r\n\r\ntemplate<typename T>\r\nvoid DirMultiNaiveBayes<T>::sampleLabels()\r\n{\r\n\t// obtain posterior categorical under labels\r\n\tpi_ = dir_.posterior(z_).sample();\r\n\t//  cout<<pi_.pdf().transpose()<<endl;\r\n\tthis->updatePDF();\r\n\t// sample z_i\r\n\tsampler_->sampleDiscPdf(pdfs_,z_);\r\n};\r\n\r\n\r\ntemplate<typename T>\r\nvoid DirMultiNaiveBayes<T>::updatePDF() {\r\n\r\n// compute categorical distribution over label z_i\r\n// no need to re-compute the array and log every iteration)\r\nVectorXd logPdf_z_value = pi_.pdf().array().log();\r\n\r\n#pragma omp parallel for\r\n  for(int32_t d=0; d<int32_t(Nd_); ++d)\r\n  {\r\n\tVectorXd logPdf_z = logPdf_z_value;\r\n\tfor(uint32_t m=0; m<uint32_t(M_); ++m)\r\n\t{\r\n\t\tfor(uint32_t k=0; k<K_; ++k)\r\n\t\t{\r\n\t\t\t//updated to SS\r\n\t\t\tlogPdf_z[k] += thetas_[m][k]->logLikelihoodFromSS(x_[m][d]);\r\n\t\t}\r\n\t}\r\n//    cout<<endl;\r\n    // make pdf sum to 1. and exponentiate\r\n    pdfs_.row(d) = (logPdf_z.array()-logSumExp(logPdf_z)).exp().matrix().transpose();\r\n//    cout<<pi_.pdf().transpose()<<endl;\r\n//    cout<<pdf.transpose()<<\" |.|=\"<<pdf.sum();\r\n//    cout<<\" z_i=\"<<z_[d]<<endl;\r\n  }\r\n\r\n}\r\n\r\n\r\ntemplate<typename T>\r\nvoid DirMultiNaiveBayes<T>::MAPLabel()\r\n{\r\n\t/* it chooses the MAP label rather than sampling */\r\n\tthis->updatePDF();\r\n\r\n\t#pragma omp parallel for\r\n\t for(int32_t d=0; d<int32_t(Nd_); ++d) {\r\n\t\t int r,c;\r\n\t\t pdfs_.row(d).maxCoeff(&r, &c);\r\n\t\t z_(d) = c;\r\n\t }\r\n};\r\n\r\n\r\n\r\ntemplate<typename T>\r\nvoid DirMultiNaiveBayes<T>::sampleParameters()\r\n{\r\n//unpacks the contains here vector<vector<Matrix>> into what the posterior expects Matrix\r\n\tMatrixXu dim(M_,K_);\r\n\tfor(uint32_t m=0; m<M_; ++m) {\r\n\t\t#pragma omp parallel for\r\n\t\tfor(int32_t k=0; k<int32_t(K_); ++k) {\r\n\t\t\tVectorXu temp = (z_.array()==k).select(dataDim[m],0);\r\n\t\t\tdim(m,k) = temp.sum();\t\r\n\t\t}\r\n\t}\r\n\r\n\tfor(int32_t m=0; m<M_; ++m) {\r\n\t#ifdef _WINDOWS\t\r\n\t\t//#pragma omp parallel for\r\n\t\tfor(int32_t k=0; k<int32_t(K_); ++k) {\r\n\t#else\r\n\t\t//#pragma omp parallel for\r\n\t\t#pragma omp parallel for schedule(dynamic)\r\n\t\tfor(int32_t k=0; k<int32_t(K_); ++k) {\r\n\t#endif\r\n\r\n\t\t\tif(dim(m,k)!=0) {\r\n\r\n\t\t\t\t//Matrix<T,Dynamic,1> ssIn = Matrix<T,Dynamic,1>::Zero(x_[m].front().rows());\r\n\t\t\t\tvector< Matrix<T,Dynamic,1> >dataIn;\r\n\t\t\t\tdataIn.reserve(dim(m,k));\r\n\t\t\t\t\r\n\t\t\t\tuint32_t count=0;\r\n\r\n\t\t\t\tfor(int32_t d=0; d<Nd_; ++d) {\r\n\t\t\t\t\tif(z_[d]==k) {\r\n\t\t\t\t\t\tint add_size =int(x_[m][d].cols());\r\n\t\t\t\t\t\t//ssIn += x_[m][d]; //update iteration SS\r\n\t\t\t\t\t\tdataIn.push_back(x_[m][d]);\r\n\t\t\t\t\t\tcount+=add_size;\r\n\r\n\t\t\t\t\t\tif(count==dim(m,k))\r\n\t\t\t\t\t\t\tbreak; //early out if you found them all\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\t//update values\r\n\t\t\t\t//thetas_[m][k]->posteriorFromSS(ssIn);\r\n\r\n//        if(thetas_[m][k]->getBaseMeasureType() == MF_T)\r\n//        {\r\n//          cout<<\"MF \"<<k<<\" ---------------- \"<<endl;\r\n//        }\r\n\t\t\t\t//always sends zeros and look for zeros\r\n\t\t\t\tthetas_[m][k]->posteriorFromSS(dataIn,VectorXu::Zero(dim(m,k)),0);\r\n\t\t\t\t\r\n\t\t\t} else {\r\n\t\t\t\t//Matrix<T,Dynamic,1> ssIn = Matrix<T,Dynamic,1>::Zero(x_[m].front().rows());\r\n\t\t\t\t//ssIn[0]=1; //set counts to 1 to avoid inf\r\n\t\t\t\t//the posterior needs to reset\t\r\n\t\t\t\t//thetas_[m][k]->posteriorFromSS(ssIn);\r\n\t\t\t\t//passing in one data point (all zeros, with 1 index value=0 and looking for 1)\r\n\r\n\t\t\t\tvector<Matrix<T,Dynamic,1> >dataIn;\r\n\t\t\t\tdataIn.push_back(Matrix<T,Dynamic,1>::Zero(x_[m].front().rows(),1));\r\n\t\t\t\t//the posterior needs to reset\r\n        VectorXu zz = VectorXu::Zero(1);\r\n\t\t\t\tthetas_[m][k]->posteriorFromSS(dataIn,zz,1);\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n};\r\n\r\n\r\ntemplate<typename T>\r\nT DirMultiNaiveBayes<T>::logJoint(bool verbose)\r\n{\r\n  T logJoint = dir_.logPdf(pi_);\r\n  if(verbose)\r\n  \tcout<<\"\\tlog p(pi)=\"<< logJoint << endl;\r\n\r\n\r\n  for(int32_t m=0; m<int32_t(M_); ++m) {\r\n\t  T logPriorM = 0;\r\n\t  #pragma omp parallel for reduction(+:logPriorM)\r\n\t  for (int32_t k=0; k<int32_t(K_); ++k) {\r\n\t\tlogPriorM = logPriorM + thetas_[m][k]->logPdfUnderPrior();\r\n\t  }\r\n\t  logJoint+=logPriorM;\r\n\t  if(verbose)\r\n\t  \tcout<<\"\\tlog p(theta_\" << m << \")=\"<< logPriorM << endl;\r\n\r\n  }\r\n\r\n\tfor (int32_t m=0; m<int32_t(M_); ++m) {\r\n\t\tT logThetaM=0;\r\n\t\t#pragma omp parallel for reduction(+:logThetaM)\r\n\t\tfor (int32_t d=0; d<int32_t(Nd_); ++d) {\r\n\t\t\tlogThetaM = logThetaM + thetas_[m][z_[d]]->logLikelihoodFromSS(x_[m][d]);\r\n\t\t}\r\n\t\tlogJoint += logThetaM;\r\n\t\tif(verbose)\r\n\t\t\tcout<<\"\\tlog p(x|z,theta_\" << m << \")=\" << logThetaM << endl;\r\n\t\t\r\n\t}\r\n    if(verbose)\r\n\t\tcout<<\"log p(pi)*p(theta)*p(x|z,theta)=\" << logJoint << endl;\r\n\r\n  return logJoint;\r\n};\r\n\r\n\r\n\r\ntemplate<typename T>\r\nvoid DirMultiNaiveBayes<T>::inferAll(uint32_t nIter, bool verbose)\r\n{\r\n  if(verbose){\r\n  \tcout<<\"[DirMultiNaiveBayes::inferALL] ------ inferingALL (nIter=\" << nIter << \") ------\"<<endl;\r\n  \tif(Nd_<=100) {\r\n\t\tcout <<\"initial labels:\"<< endl;\r\n  \t\tcout<<this->labels().transpose()<<endl;\r\n\t}\r\n  }\r\n\r\n\r\n  logJointIterEval.clear(); logJointHist.clear();\r\n  if(verbose) {\r\n\t//all iterations stored\r\n\tlogJointIterEval.reserve(nIter); logJointHist.reserve(nIter);\r\n  } else {\r\n\t  //only mod 100 stored\r\n\t  logJointIterEval.reserve(int((nIter/100) + 1)); logJointHist.reserve(int((nIter/100) + 1));\r\n  }\r\n\r\n  for(uint32_t t=0; t<nIter; ++t)\r\n  {\r\n    this->sampleLabels();\r\n    this->sampleParameters();\r\n    if(verbose)\r\n    {\r\n      for(int m=0; m<int(M_); ++m) {\r\n        for(int k=0; k<int(K_); ++k) {\r\n          thetas_[m][k]->print();\r\n        }\r\n      }\r\n    }\r\n    if(verbose || t%int(ceil(nIter/100.))==0)\r\n    {\r\n      VectorXu Ns = counts<uint32_t,uint32_t>(\r\n          this->labels(),K_).transpose();\r\n      uint32_t K = K_;\r\n      for(uint32_t k = 0; k<K_; ++k)\r\n        if (Ns(k) == 0) --K;\r\n      cout<<\"@i \"<<t<<\": # \"\r\n        <<K<<\" \"<<std::setw(1)<<Ns.transpose() <<endl;\r\n\r\n      T iterLogJoint = this->logJoint(true) ;\r\n      //log iterJoint Prob\r\n      logJointIterEval.push_back(t);\r\n      logJointHist.push_back(iterLogJoint);\r\n\r\n      if(Nd_<=10) {\r\n        cout << \"[\" << std::setw(3)<< std::setfill('0')\r\n          << t <<\"] label: \"\r\n          << this->labels().transpose()\r\n          << \" [joint= \" << std::setw(6) << iterLogJoint << \"]\"<< endl;\r\n      } else {\r\n        cout << \"[\" << std::setw(3)<< std::setfill('0')\r\n          << t <<\"] joint= \"\r\n          << std::setw(6) << iterLogJoint << endl;\r\n      }\r\n    }\r\n//    if(verbose)\r\n//    {\r\n//      VectorXu Ns = counts<uint32_t,uint32_t>(this->labels(),K_).transpose();\r\n//      uint32_t K = K_;\r\n//      for(uint32_t k = 0; k<K_; ++k)\r\n//        if (Ns(k) == 0) --K;\r\n//      cout<<\"@i \"<<t<<\": # \"<<K<<\" \"<<std::setw(1) <<Ns.transpose() <<endl;\r\n//    }\r\n  }\r\n  //keeps the MAP label in memory\r\n  this->MAPLabel();\r\n  this->sampleParameters();\r\n}\r\n\r\n\r\ntemplate <typename T>\r\nvoid DirMultiNaiveBayes<T>::dump(std::ofstream& fOutMeans, std::ofstream& fOutCovs)\r\n{\r\n\tcout << \"dumping MultiObs naiveBayes\" << endl;\r\n\tcout << \"doc index: \" << endl;\r\n\tcout << this->labels().transpose() << endl;\r\n\t\r\n\tcout << \"printing num components: \" << endl;\r\n\tcout << M_ << endl;\r\n\r\n\tcout << \"printing cluster params: \" << endl;\r\n\tcout << K_ << endl;\r\n\r\n\tfor(uint32_t m=0; m<M_; ++m) {\r\n\t\tcout << \"component: \" << m  << endl;\r\n\t\tfor(uint32_t k=0; k<K_; ++k) {\r\n\t\t\tcout << \"theta: \" << k  << endl;\r\n\t\t\tthetas_[m][k]->print();\r\n\t\t}\r\n\t}\r\n\r\n\tcout << \"printing mixture params: \" << endl;\r\n\tpi_.print();\r\n}\r\n\r\n\r\ntemplate <typename T>\r\nvoid DirMultiNaiveBayes<T>::dump_clean(std::ofstream &out){\r\n\t//clean dump, only data with specific format\r\n//FORMAT:\r\n\t//M 1x1\r\n\t//K\t1x1\r\n\t//Nd 1x1\r\n\t//D[m] 1xM\r\n\t//Type[m] 1xM\r\n\t//labels 1xNd\r\n\t//Dir alpha 1xK\r\n\t//pi pdf 1xK\r\n\t//pdf KxNd\r\n\t// mixture parameters\r\n\t//params Loop over M then K each contains data type for specific type\r\n\t//for type 1 (NIWSampled)\r\n\t\t//---prior--- (NIW)\r\n\t\t\t//nu 1x1\r\n\t\t\t//kappa 1x1\r\n\t\t\t//theta 1xD\r\n\t\t\t//scatter DxD\r\n\t\t//---estimate (normal)\r\n\t\t\t//mu 1xD\r\n\t\t\t//Sigma DxD\r\n\t//for type 2 (NIWSphereFull)\r\n\t\t//----prior--- (IW)\r\n\t\t\t//nu 1x1\r\n\t\t\t//count 1x1\r\n\t\t\t//mean 1x(D-1)\r\n\t\t\t//scatter (D-1)x(D-1)\r\n\t\t\t//Delta\t (D-1)x(D-1)\r\n\t\t//--posterior (NormalSphere)\r\n\t\t\t//mean 1x(D-1)\r\n\t\t\t//Sigma (D-1)x(D-1)\r\n\t\t//--sphere--- (Sphere)\r\n\t\t\t//north 1x(D-1)\r\n\t//for type 3 (DirSampled)\r\n\t\t//--posterior (Dir)\r\n\t\t\t//alpha 1xK\r\n\t\t\t//counts 1xK\r\n\t\t//--distribution (Cat)\r\n\t\t\t//pdf 1xK\r\n\t\t//--counts (scalar)\r\n\t\t\t//counts 1x1\r\n\t//logJoint history\r\n\t\t// Niter 1x1\r\n\t\t// iterValue 1xNiter (iteration corresponding to the logValue)\r\n\t\t// logJoint\t 1xNiter (logJoint)\r\n\r\n\t//this fixes issues with eigen matrices printing (eg, 00-0.7 )\r\n\tint curPres = int(out.precision());\r\n\tout.precision(10);\r\n\tIOFormat fullPresPrint(FullPrecision,DontAlignCols);\r\n\r\n\t//prints headers\r\n\tout << M_ << endl\r\n\t\t << K_ << endl\r\n\t\t << Nd_ << endl;\r\n\r\n\t//print dim\r\n\tfor(uint32_t m=0; m<M_; ++m) {\r\n\t\tvector<boost::shared_ptr<BaseMeasure<T> > >  theta_base = this->getThetas(m);\r\n\t\tuint32_t temp = theta_base.front()->getDim();\r\n\t\tout << temp << \" \";\r\n\t\t//out << x_[m].front().rows() << \" \";\r\n\t}\r\n\tout << endl;\r\n\t//print type\r\n\tfor(uint32_t m=0; m<M_; ++m) {\r\n\t\tout << thetas_[m].front()->getBaseMeasureType() << \" \";\r\n\t}\r\n\tout << endl;\r\n\r\n\t//print labels\r\n\tout << this->labels().transpose() << endl;\r\n\r\n\t//print mixture parameters\r\n\tout << this->dir_.alpha_.transpose() << endl;\r\n\tout << this->pi_.pdf_.transpose().format(fullPresPrint) << endl;\r\n\t//out << this->pdfs_.transpose().format(fullPresPrint) << endl;\r\n\r\n\t//print parameters\r\n\tfor(uint32_t m=0; m<M_; ++m) {\r\n\t\tvector<boost::shared_ptr<BaseMeasure<T> > >  theta_base = this->getThetas(m);\r\n\t\tfor(uint32_t k=0; k<K_; ++k) {\r\n\t\t\tbaseMeasureType type = theta_base[k]->getBaseMeasureType();\r\n\t\t\tif(type==NIW_SAMPLED) {\r\n\t\t\t\tboost::shared_ptr<NiwSampled<T> >  *theta_iter =\r\n\t\t\t\t\t\treinterpret_cast<boost::shared_ptr<NiwSampled<T> >* >( &theta_base[k]);\r\n\t\t\t\t\t//printing prior\r\n\t\t\t\t\tNIW<T> prior = theta_iter->get()->niw0_;\r\n\t\t\t\t\tout << prior.nu_\t\t\t\t << endl <<\r\n\t\t\t\t\t\t    prior.kappa_\t\t\t << endl <<\r\n\t\t\t\t\t\t    prior.theta_.transpose() << endl <<\r\n\t\t\t\t\t\t    prior.Delta_.format(fullPresPrint)\t<<\tendl;\r\n\r\n\t\t\t\t\t//printing posterior\r\n\t\t\t\t\tNormal<T> norm = theta_iter->get()->normal_;\r\n\t\t\t\t\tout << norm.mu_.transpose() << endl;\r\n\t\t\t\t\tout << norm.Sigma().format(fullPresPrint) << endl;\r\n\t\t\t} else if(type==NIW_SPHERE) {\r\n        boost::shared_ptr<NiwSphere<T> >  *theta_iter =\r\n          reinterpret_cast<boost::shared_ptr<NiwSphere<T> >* >(\r\n              &theta_base[k]);\r\n\t\t\t\t//prior\r\n\t\t\t\tIW<T> prior = theta_iter->get()->iw0_;\r\n\t\t\t\tout << prior.nu_ \t\t\t\t << endl\r\n\t\t\t\t\t << prior.count()\t\t\t << endl\r\n\t\t\t\t \t << prior.mean().transpose() << endl\r\n\t\t\t\t\t << prior.scatter().format(fullPresPrint)\t\t\t << endl\r\n\t\t\t\t\t << prior.Delta_.format(fullPresPrint)\t\t\t << endl;\r\n\r\n\t\t\t\t//posterior \t\r\n\t\t\t\tNormalSphere<T> norm = theta_iter->get()->normalS_;\r\n\t\t\t\tout << norm.getMean().transpose().format(fullPresPrint) << endl;\r\n\t\t\t\tout << norm.Sigma().format(fullPresPrint) << endl;\r\n\t\t\t\t//sphere \t\r\n\t\t\t\tSphere<T> sp = theta_iter->get()->S_;\r\n\t\t\t\tout << sp.north().transpose() << endl;\r\n\t\t\t} else if(type==DIR_SAMPLED) {\r\n\t\t\t\tboost::shared_ptr<DirSampled<Cat<T>,T> >  *theta_iter =\r\n\t\t\t\t\t\treinterpret_cast<boost::shared_ptr<DirSampled<Cat<T>,T> >* >( &theta_base[k]);\r\n\t\t\t\t//posterior\r\n\t\t\t\tDir<Catd,T>  post = theta_iter->get()->dir0_;\r\n\t\t\t\tout <<\tpost.alpha_.transpose()\t\t<< endl;\r\n\t\t\t\tout <<\tpost.counts().transpose()\t<< endl;\r\n\r\n\t\t\t\t//distribution\r\n\t\t\t\tCatd dist = theta_iter->get()->disc_;\r\n\t\t\t\tout <<\tdist.pdf_.transpose() << endl;\r\n\t\t\t\t\r\n\t\t\t\t//counts\r\n\t\t\t\tT counts = theta_iter->get()->count_;\r\n\t\t\t\tout << counts << endl;\r\n\r\n\t\t\t} else if(type==MF_T) {\r\n        boost::shared_ptr<MfBase<T> > *theta_iter =\r\n          reinterpret_cast<boost::shared_ptr<MfBase<T> >* >(\r\n              &theta_base[k]);\r\n\r\n        out<< theta_iter->get()->mf0_.T_<<endl;\r\n\r\n\t\t\t\t//posterior\r\n\t\t\t\tDir<Cat<T>, T>  post = theta_iter->get()->mf0_.dirMM().Alpha();\r\n\t\t\t\tout <<\tpost.alpha_.transpose()\t\t<< endl;\r\n\t\t\t\tout <<\tpost.counts().transpose()\t<< endl;\r\n\t\t\t\tCat<T> pi = theta_iter->get()->mf0_.dirMM().Pi();\r\n\t\t\t\tout <<\tpi.pdf().transpose() << endl;\r\n\r\n        out << theta_iter->get()->mf_.R().format(fullPresPrint)<<endl;\r\n        for(uint32_t j=0; j<6; ++j)\r\n        {\r\n          out<< theta_iter->get()->mf0_.theta(j)->iw0_.nu_ << endl;\r\n          out<< theta_iter->get()->mf0_.theta(j)->iw0_.Delta_ << endl;\r\n          out<< theta_iter->get()->mf0_.theta(j)->iw0_.scatter() << endl;\r\n          out<< theta_iter->get()->mf0_.theta(j)->iw0_.mean() << endl;\r\n          out<< theta_iter->get()->mf0_.theta(j)->iw0_.count() << endl;\r\n          out<< theta_iter->get()->mf0_.theta(j)->normalS_.Sigma() << endl;\r\n          out<< theta_iter->get()->mf0_.theta(j)->normalS_.getMean() << endl;\r\n        }\r\n      \r\n        // output the labeling\r\n        out<<theta_iter->get()->mf0_.dirMM().labels().size()<<endl;\r\n\t      out<<theta_iter->get()->mf0_.dirMM().labels().transpose()<<endl;\r\n\t\t\t\t\r\n\t\t\t} else {\r\n\t\t\t\t\tstd::cerr << \"[DirMultiNaiveBayes::dump_clean] error saving...returning\" << endl;\r\n\t\t\t\t\treturn;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\r\n\t//print logHistory\r\n\tout << int(logJointHist.size()) << endl;\r\n\tfor(int i=0; i<logJointIterEval.size(); ++i)\r\n\t\tout << logJointIterEval[i] << \" \";\r\n\tout << endl;\r\n\r\n\tfor(int i=0; i<logJointHist.size(); ++i)\r\n\t\tout << logJointHist[i] << \" \";\r\n\tout << endl;\r\n\r\n\tout.precision(curPres);\r\n\r\n}\r\n\r\n\r\n//template <typename T>\r\n//void DirMultiNaiveBayes<T>::dump_clean(std::ofstream &out){\r\n//\tstreambuf *coutbuf = std::cout.rdbuf(); //save old cout buffer\r\n//\tcout.rdbuf(out.rdbuf()); //redirect std::cout to fout1 buffer\r\n//\tthis->dump_clean(); //write using cout to the specified buffer\r\n//\tstd::cout.rdbuf(coutbuf); //reset to standard output again\r\n//}\r\n\r\n\r\ntemplate <typename T>\r\nT DirMultiNaiveBayes<T>::evalLogLik(const vector<Matrix<T,Dynamic,1> > xnew,\r\n\t\t\t\t\t\t\t  const uint32_t clusterInd, const vector<uint32_t> comp2eval)\r\n{\r\n\t//T logJoint = pi_.pdf_(clusterInd);\r\n\tT logJoint  = 0;\r\n\tfor (int32_t m=0; m<int32_t(comp2eval.size()); ++m)\r\n\t{\r\n\t\tlogJoint += thetas_[comp2eval[m]][clusterInd]->logLikelihoodFromSS(xnew[m]);\r\n\t}\r\n\r\n  return logJoint;\r\n}\r\n\r\n\r\ntemplate <typename T>\r\nvector<T> DirMultiNaiveBayes<T>::evalLogLik(const vector<Matrix<T,Dynamic,1> > xnew,\r\n\t\t\t\t\t\t\t\t\t\t\tconst vector<uint32_t> clusterInd,\r\n\t\t\t\t\t\t\t\t\t\t\tconst vector<uint32_t> comp2eval) {\r\n\t\r\n\tvector<uint32_t> comp2evalLocal = comp2eval;\r\n\tif(comp2evalLocal.empty()) {\r\n\t\tfor(uint32_t m=0; m<M_; ++m)\r\n\t\t\tcomp2evalLocal.push_back(m);\r\n\t}\r\n\r\n\tvector<T> out;\r\n\tfor(uint32_t k=0; k<uint32_t(clusterInd.size()); ++k) {\r\n\t\tout.push_back(this->evalLogLik(xnew,clusterInd[k],comp2evalLocal));\r\n\t}\r\n\treturn(out);\r\n}\r\n\r\n\r\n  template <typename T>\r\nuint32_t DirMultiNaiveBayes<T>::labels_sample_max(const\r\n    vector<Matrix<T,Dynamic,1> > xnew, const vector<uint32_t>\r\n    comp2eval, const bool return_MAP_labels)\r\n{\r\n  /* xnew in the form x[docs][m][SS] */\r\n  VectorXd logPdf_z = pi_.pdf().array().log();\r\n\r\n  for(int32_t m=0; m<comp2eval.size(); ++m)\r\n  {\r\n    for(int32_t k=0; k<int32_t(K_); ++k)\r\n    {\r\n      logPdf_z[k] += thetas_[comp2eval[m]][k]->logLikelihoodFromSS(\r\n          xnew[m]);\r\n    }\r\n  }\r\n\r\n  // make pdf sum to 1. and exponentiate\r\n  Matrix<T,Dynamic,Dynamic> pdfLocal =  Matrix<T,Dynamic,Dynamic>(1,K_);\r\n  pdfLocal = (logPdf_z.array()-logSumExp(logPdf_z)).exp().matrix().transpose();\r\n\r\n  VectorXu zout = VectorXu(1);\r\n\r\n  if(return_MAP_labels) {\r\n    // return MAP label\r\n    int r,c;\r\n    pdfLocal.maxCoeff(&r, &c);\r\n    zout(0) = c;\r\n  } else {\r\n    // sample z_i\r\n    sampler_->sampleDiscPdf(pdfLocal,zout);\r\n  }\r\n\r\n  return(zout(0));\r\n};\r\n\r\n\r\n\r\n\r\ntemplate <typename T>\r\nuint32_t DirMultiNaiveBayes<T>::sampleLabels(const vector<Matrix<T,Dynamic,1> > xnew,\r\n\t\t\t\t\t\t\t\t\t\t\t const vector<uint32_t> comp2eval) {\r\n\treturn(this->labels_sample_max(xnew, comp2eval, false));\r\n}\r\n\r\ntemplate <typename T>\r\nvector<uint32_t> DirMultiNaiveBayes<T>::sampleLabels(const vector<vector<Matrix<T,Dynamic,1> > > xnew,\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t const vector<uint32_t> comp2eval)\r\n{\r\n\t/* xnew in the form x[doc][m][SS] */\r\n\tvector<uint32_t> out;\r\n\tfor(uint32_t d=0; d<xnew.size(); ++d) {\r\n\t\tout.push_back(this->sampleLabels(xnew[d],comp2eval));\r\n\t}\r\n\treturn(out);\r\n}\r\n\r\n\r\ntemplate <typename T>\r\nuint32_t DirMultiNaiveBayes<T>::MAPLabels(const vector<Matrix<T,Dynamic,1> > xnew,\r\n\t\t\t\t\t\t\t\t\t\t  const vector<uint32_t> comp2eval) {\r\n\treturn(this->labels_sample_max(xnew, comp2eval, true));\r\n}\r\n\r\n\r\ntemplate <typename T>\r\nvector<uint32_t> DirMultiNaiveBayes<T>::MAPLabels(const vector<vector<Matrix<T,Dynamic,1> > > xnew,\r\n\t\t\t\t\t\t\t\t\t\t\t\t  const vector<uint32_t> comp2eval) {\r\n\t/* xnew in the form x[docs][m][SS] */\r\n\tvector<uint32_t> out;\r\n\tfor(uint32_t d=0; d<xnew.size(); ++d) {\r\n\t\tout.push_back(this->MAPLabels(xnew[d],comp2eval));\r\n\t}\r\n\treturn(out);\r\n}\r\n\r\ntemplate<typename T>\r\nMatrixXu DirMultiNaiveBayes<T>::mostLikelyInds(uint32_t n, Matrix<T,Dynamic,Dynamic>& logLikes)\r\n{\r\n  MatrixXu inds = MatrixXu::Zero(n,K_);\r\n  logLikes = Matrix<T,Dynamic,Dynamic>::Ones(n,K_);\r\n\r\n#pragma omp parallel for\r\n  for (int32_t k=0; k<K_; ++k)\r\n  {\r\n    for (uint32_t i=0; i<z_.size(); ++i)\r\n      if(z_(i) == k)\r\n      {\r\n        T logLike = 0.;\r\n        // iterate over datasources and sum up their logLikes\r\n        for(uint32_t m=0; m<uint32_t(M_); ++m)\r\n        {\r\n          logLike += thetas_[m][z_[i]]->logLikelihoodFromSS(x_[m][i]);\r\n        }\r\n        // keep only the top n and sorted\r\n        for (uint32_t j=0; j<n; ++j)\r\n          if(logLikes(j,k) < logLike)\r\n          {\r\n            for(uint32_t l=n-1; l>j; --l)\r\n            {\r\n              logLikes(l,k) = logLikes(l-1,k);\r\n              inds(l,k) = inds(l-1,k);\r\n            }\r\n            logLikes(j,k) = logLike;\r\n            inds(j,k) = i;\r\n//            cout<<\"after update \"<<logLike<<endl;\r\n//            Matrix<T,Dynamic,Dynamic> out(n,K_*2);\r\n//            out<<logLikes.cast<T>(),inds.cast<T>();\r\n//            cout<<out<<endl;\r\n            break;\r\n          }\r\n      }\r\n  }\r\n  cout<<\"::mostLikelyInds: logLikes\"<<endl;\r\n  cout<<logLikes<<endl;\r\n  cout<<\"::mostLikelyInds: inds\"<<endl;\r\n  cout<<inds<<endl;\r\n  return inds;\r\n};\r\n", "meta": {"hexsha": "823f251abb82a0a5c8edcec5d8e7a4ea62a4004b", "size": 33051, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/dpMM/dirMultiNaiveBayes.hpp", "max_stars_repo_name": "jstraub/dpMM", "max_stars_repo_head_hexsha": "538c432d5f98c040d5c1adb072e545e38f97fc69", "max_stars_repo_licenses": ["MIT-feh"], "max_stars_count": 11.0, "max_stars_repo_stars_event_min_datetime": "2015-04-27T15:14:01.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-18T00:19:18.000Z", "max_issues_repo_path": "include/dpMM/dirMultiNaiveBayes.hpp", "max_issues_repo_name": "jstraub/dpMM", "max_issues_repo_head_hexsha": "538c432d5f98c040d5c1adb072e545e38f97fc69", "max_issues_repo_licenses": ["MIT-feh"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/dpMM/dirMultiNaiveBayes.hpp", "max_forks_repo_name": "jstraub/dpMM", "max_forks_repo_head_hexsha": "538c432d5f98c040d5c1adb072e545e38f97fc69", "max_forks_repo_licenses": ["MIT-feh"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2015-07-02T12:46:20.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-30T04:39:30.000Z", "avg_line_length": 29.4572192513, "max_line_length": 119, "alphanum_fraction": 0.5897249705, "num_tokens": 10267, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5926665855647394, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.33773262518864217}}
{"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 related to fully analytical 1D RTA solutions.\n\n#include <constants.hpp>\n#include <structures.hpp>\n#include <qpoint_grid.hpp>\n#include <Eigen/Dense>\n\nnamespace alma {\n\nnamespace analytic1D {\n\n/// Class for computing basic thermal properties\n/// (kappa, Cv, diffusivity) and cumulative functions\n/// (resolved for MFP, energy, etc.) along a given transport direction.\n/// Calculations involve appropriate thin film corrections\n/// for both cross-plane and in-plane transport.\n\nclass BasicProperties_calculator {\npublic:\n    /// Constructor: initialise internal variables\n    BasicProperties_calculator(const alma::Crystal_structure* poscar,\n                               const alma::Gamma_grid* grid,\n                               const Eigen::ArrayXXd* w,\n                               double T);\n\n    /// Function setting the thermal transport axis\n    void setDirection(const Eigen::Vector3d unitvector);\n\n    /// Construct a logarithmic grid of MFP bins\n    /// from MFPmin to MFPmax with Nbins elements\n    void setLogMFPbins(double MFPmin, double MFPmax, int Nbins);\n\n    /// Construct a logarithmic grid of MFP bins witn Nbins elements.\n    /// MFPmax is assigned automatically to twice the largest MFP.\n    /// MFPmin is assigned to 1e-6*largest MFP.\n    void setAutoMFPbins(int Nbins);\n\n    /// Construct a logarithmic grid of MFP bins witn Nbins elements.\n    /// MFPmax is assigned automatically to the twice the largest projected MFP.\n    /// MFPmin is assigned to 1e-6*largest projected MFP.\n    void setAutoProjMFPbins(int Nbins);\n\n    /// Construct a logarithmic grid of tau bins\n    /// from taumin to taumax with Nbins elements\n    void setLogRTbins(double taumin, double taumax, int Nbins);\n\n    /// Construct a logarithmic grid of tau bins witn Nbins elements.\n    /// taumax is assigned automatically to the twice the largest relaxation\n    /// time.\n    /// taumin is assigned to 1e-6*largest relaxation time.\n    void setAutoRTbins(int Nbins);\n\n    /// Construct a linear grid of omega bins\n    /// from omegamin to omegamax with Nbins elements\n    void setLinOmegabins(double omegamin, double omegamax, int Nbins);\n\n    /// Construct a linear grid of omega bins witn Nbins elements.\n    /// omegamax is assigned automatically to 1.1*largest angular frequency.\n    /// omegamin is automatically set to 0.\n    void setAutoOmegabins(int Nbins);\n\n    /// Retrieve the MFP bins\n    Eigen::VectorXd getMFPbins();\n\n    /// Retrieve the relaxation time bins\n    Eigen::VectorXd getRTbins();\n\n    /// Retrieve the relaxation time bins\n    Eigen::VectorXd getOmegabins();\n\n    /// Specify that the medium should be treated as\n    /// infinite bulk (default option)\n    void setBulk();\n\n    /// Specify that the medium should be treated as\n    /// a thin film with provided thickness.\n    /// This option corrects MFPs and relaxation times\n    /// in conductivity calculations.\n    void setInPlaneFilm(double filmthickness,\n                        const Eigen::Vector3d normal,\n                        double specularity = 0.0);\n    void setCrossPlaneFilm(double filmthickness);\n\n    /// Retrieve thermal conductivity\n    double getConductivity();\n\n    /// Obtain spectrally computed thermal conductivity\n    double getSpectralConductivity();\n\n    /// Compute the heat capacity and retrieve it\n    double getCapacity();\n\n    /// Compute the Fourier diffusivity and retrieve it\n    double getDiffusivity();\n\n    /// Retrieve the dominant projected MFP as defined below\n    double getDominantProjMFP();\n\n    /// Retrieve the dominant phonon relaxation time\n    double getDominantRT();\n\n    /// Compute the anisotropy index kappa_max/kappa_min and retrieve it.\n    double getAnisotropyIndex();\n\n    /// Choose resolving cumulative curves by MFP\n    void resolveByMFP();\n\n    /// Choose resolving cumulative curves by projected MFP\n    void resolveByProjMFP();\n\n    /// Choose resolving cumulative curves by relaxation time\n    void resolveByRT();\n\n    /// Choose resolving cumulative curves by angular frequency\n    void resolveByOmega();\n\n    /// Compute the cumulative thermal conductivity curve\n    /// with respect to the MFP bins and retrieve it\n    Eigen::VectorXd getCumulativeConductivity();\n\n    /// Compute the cumulative heat capacity curve\n    /// with respect to the MFP bins and retrieve it\n    Eigen::VectorXd getCumulativeCapacity();\n\n\n    /// Compute the cumulative hydrodinamic l2\n    /// using RTA and assuming isotropy\n    Eigen::VectorXd getCumulativel2RTAiso();\n\n    /// Set the number of bins to be used in DOS evaluation\n    void setDOSgridsize(int nbins);\n\n    /// Obtain the DOS energy grid (in meV)\n    Eigen::VectorXd getDOSgrid();\n\n    /// Calculate and obtain the DOS\n    Eigen::VectorXd getDOS();\n\nprivate:\n    /// Pointer to description of the unit cell\n    const alma::Crystal_structure* poscar;\n    /// Pointer to phonon spectrum on a regular q-point grid\n    const alma::Gamma_grid* grid;\n    /// Pointer to scattering rates for all modes irreducible points in the grid\n    const Eigen::ArrayXXd* w;\n    /// Temperature\n    double T;\n\n    /// Unitvector describing 1D thermal transport axis\n    Eigen::Vector3d unitvector;\n    /// Unitvector describing the film normal for in-plane transport\n    Eigen::Vector3d normalvector;\n    /// MFP bins for cumulative curves\n    Eigen::VectorXd MFPbins;\n    /// relaxation time bins for cumulative curves\n    Eigen::VectorXd taubins;\n    /// omega bins for cumulative curves\n    Eigen::VectorXd omegabins;\n    /// Max MFP value present in medium\n    double internal_MFPmax;\n    /// Max proj MFP value present in medium\n    double internal_MFPprojmax;\n    /// Max relaxation time present in medium\n    double internal_taumax;\n    /// Max phonon frequency present in medium\n    double internal_omegamax;\n    /// Thin film specifiers\n    bool thinfilm;\n    bool crossplane;\n    double filmthickness;\n    double specularity; // for in-plane films\n    /// Basic properties\n    double kappa;\n    double Cv;\n    /// \"Dominant\" projected MFP, defined as kappa-weighted average\n    /// <Lambda_proj> = sum[(kappamode/kappabulk)*Lambda_proj]\n    double dominantProjMFP;\n    /// \"Dominant\" relaxation time, defined as kappa-weighted average\n    /// <RT> = sum[(kappamode/kappabulk)*RT_mode]\n    double dominantRT;\n    /// 3D rotation matrix that rotates the cartesian coordinate system such\n    /// that\n    /// the transport axis becomes (1,0,0) and film normal becomes (0,0,1)\n    Eigen::Matrix3d FuchsRotation;\n    /// Precalculate the 3D rotation matrix used for in-plane Fuch corrections.\n    void initFuchsRotation();\n    /// Precalculate thermal properties\n    void updateMe();\n    /// Calculated cumulative conductivity function\n    Eigen::VectorXd kappacumul;\n    /// Calculated cumulative capacity function\n    Eigen::VectorXd Cvcumul;\n    /// Calculated cumulative l**2\n    Eigen::VectorXd l2cumul;\n\n    /// Specifier for kappacumul calculation\n    enum kappacumulID {\n        resolve_by_MFP,\n        resolve_by_ProjMFP,\n        resolve_by_RT,\n        resolve_by_omega\n    };\n    int kappacumulIdentifier;\n    /// Number of bins to be used for DOS evaluation\n    int DOS_Nbins;\n};\n\n/// Class for computing the RTA propagator function psi(xi) of a medium.\n/// The psi function fully determines the analytical single pulse\n/// response of the infinite bulk in weakly quasi-ballistic regime\n/// (time scales exceeding phonon relaxation times):\n/// Energy density in Fourier-Laplace domain = 1/[s + psi(xi)]\n/// Energy density in Fourier-time domain = exp[-psi(xi)*t]\n\nclass psi_calculator {\npublic:\n    /// Constructor: initialise internal variables\n    psi_calculator(const alma::Crystal_structure* poscar,\n                   const alma::Gamma_grid* grid,\n                   const Eigen::ArrayXXd* w,\n                   double T);\n\n    /// Function setting the thermal transport axis\n    void setDirection(const Eigen::Vector3d unitvector);\n\n    /// Construct a linear grid of spatial frequencies\n    /// from ximin to ximax with Nxi elements\n    void setLinGrid(double ximin, double ximax, int Nxi);\n\n    /// Construct a logarithmic grid of spatial frequencies\n    /// from ximin to ximax with Nxi elements\n    void setLogGrid(double ximin, double ximax, int Nxi);\n\n    /// Manually set a grid of spatial frequencies\n    void setXiGrid(const Eigen::Ref<const Eigen::VectorXd> xigrid);\n\n    /// Retrieve the spatial frequency grid\n    Eigen::VectorXd getSpatialFrequencies();\n\n    /// Determine whether computation output should be\n    /// normalised by the Fourier solution Dbulk*xi^2\n    void normaliseOutput(bool norm);\n\n    /// Obtain Fourier diffusivity of the medium\n    double getDiffusivity();\n\n    /// Compute psi function and retrieve it\n    Eigen::VectorXd getPsi();\n\nprivate:\n    /// Pointer to description of the unit cell\n    const alma::Crystal_structure* poscar;\n    /// Pointer to phonon spectrum on a regular q-point grid\n    const alma::Gamma_grid* grid;\n    /// Pointer to scattering rates for all modes irreducible points in the grid\n    const Eigen::ArrayXXd* w;\n    /// Temperature\n    double T;\n\n    /// Unitvector describing 1D thermal transport axis\n    Eigen::Vector3d unitvector;\n    /// Spatial frequency grid\n    Eigen::VectorXd xi;\n    /// Normalisation specifier\n    bool scaleoutput;\n    /// Fourier diffusivity\n    double Dbulk;\n    void updateDiffusivity();\n    /// Calculated psi function\n    Eigen::VectorXd psi;\n};\n\n/////////////////// SPR_calculator_FourierLaplace ///////////////////\n\n/// Class for computing the exact analytical RTA single pulse\n/// energy density response of the infinite bulk medium\n/// in Fourier-Laplace domain. [see PRB 91 085202 (2015)]\n\nclass SPR_calculator_FourierLaplace {\npublic:\n    /// Constructor: initialise internal variables\n    SPR_calculator_FourierLaplace(const alma::Crystal_structure* poscar,\n                                  const alma::Gamma_grid* grid,\n                                  const Eigen::ArrayXXd* w,\n                                  double T);\n\n    /// Function setting the thermal transport axis\n    void setDirection(const Eigen::Vector3d unitvector);\n\n    /// Construct a linear grid of spatial frequencies\n    /// from ximin to ximax with Nxi elements\n    void setLinSpatialGrid(double ximin, double ximax, int Nxi);\n\n    /// Construct a logarithmic grid of spatial frequencies\n    /// from ximin to ximax with Nxi elements\n    void setLogSpatialGrid(double ximin, double ximax, int Nxi);\n\n    /// Construct a linear grid of temporal frequencies\n    /// from fmin to fmax with Nf elements.\n    /// From this a Laplace grid s = 2*pi*1i*f is created.\n    void setLinTemporalGrid(double fmin, double fmax, int Nf);\n\n    /// Construct a logarithmic grid of temporal frequencies\n    /// from fmin to fmax with Nf elements.\n    /// From this a Laplace grid s = 2*pi*1i*f is created.\n    void setLogTemporalGrid(double fmin, double fmax, int Nf);\n\n    /// Retrieve the spatial frequency grid\n    Eigen::VectorXd getSpatialFrequencies();\n\n    /// Retrieve the temporal frequency grid\n    Eigen::VectorXd getTemporalFrequencies();\n\n    /// Compute SPR and retrieve it\n    Eigen::MatrixXcd getSPR();\n\nprivate:\n    /// Pointer to description of the unit cell\n    const alma::Crystal_structure* poscar;\n    /// Pointer to phonon spectrum on a regular q-point grid\n    const alma::Gamma_grid* grid;\n    /// Pointer to scattering rates for all modes irreducible points in the grid\n    const Eigen::ArrayXXd* w;\n    /// Temperature\n    double T;\n\n    /// Unitvector describing 1D thermal transport axis\n    Eigen::Vector3d unitvector;\n    /// Spatial frequency grid\n    Eigen::VectorXd xi;\n    /// Temporal frequency grids\n    Eigen::VectorXd f;\n    Eigen::VectorXcd s;\n    /// Calculated SPR\n    Eigen::MatrixXcd Pxis;\n};\n\n/////////////////// SPR_calculator_RealSpace ///////////////////\n\n/// Class for computing the approximate analytical RTA single pulse\n/// energy density response in real space at a given time.\n///\n/// The approach is only valid in weakly quasiballistic regime\n/// (time scales exceeding phonon relaxation times) so that\n/// P(xi,t) \\approx exp[-psi(xi)*t].\n///\n/// Calculations are performed by evaluating the Fourier inversion\n/// (1/pi)*Integral(exp[-psi(xi)*t]*cos(xi*x),xi=0..infinity)\n/// semi-analytically with 2nd order Filon-type quadrature.\n\nclass SPR_calculator_RealSpace {\npublic:\n    /// Constructor: initialise internal variables\n    SPR_calculator_RealSpace(const alma::Crystal_structure* poscar,\n                             const alma::Gamma_grid* grid,\n                             const Eigen::ArrayXXd* w,\n                             double T);\n\n    /// Function setting the thermal transport axis\n    void setDirection(const Eigen::Vector3d unitvector);\n\n    /// Construct a linear space grid\n    /// from xmin to xmax with Nx elements\n    void setLinGrid(double xmin, double xmax, int Nx);\n\n    /// Construct a logarithmic space grid\n    /// from xmin to xmax with Nx elements\n    void setLogGrid(double xmin, double xmax, int Nx);\n\n    /// Declare whether the space grid is normalised.\n    /// If yes, space grid values are counted in\n    /// Fourier diffusion lengths, i.e.\n    /// x_actual = x_grid*sqrt(2*Dbulk*t)\n    void declareGridNormalised(bool norm);\n\n    // Optional normalisation of calculation output\n    // by sqrt(4*pi*Dbulk*t)\n    void normaliseOutput(bool norm);\n\n    /// Set time value to be used for calculations\n    void setTime(double t);\n\n    /// Set MFP bins to be used for resolveSPRbyMFP()\n    void setLogMFPbins(double MFPmin, double MFPmax, int Nbins);\n\n    /// Retrieve the spatial grid\n    Eigen::VectorXd getGrid();\n    Eigen::VectorXd getNormalisedGrid();\n\n    /// Retrieve time value\n    double getTime();\n\n    /// Retrieve MFP bins\n    Eigen::VectorXd getMFPbins();\n\n    /// Retrieve Fourier diffusivity along thermal transport axis\n    double getDiffusivity();\n\n    /// Compute source transient P(x=0) at the provided times\n    Eigen::VectorXd getSourceTransient(\n        const Eigen::Ref<Eigen::VectorXd> timegrid);\n\n    /// Compute SPR and retrieve it\n    Eigen::VectorXd getSPR();\n\n    /// Compute SPR of individual modes resolved by MFP\n    Eigen::MatrixXd resolveSPRbyMFP();\n\nprivate:\n    /// Pointer to description of the unit cell\n    const alma::Crystal_structure* poscar;\n    /// Pointer to phonon spectrum on a regular q-point grid\n    const alma::Gamma_grid* grid;\n    /// Pointer to scattering rates for all modes irreducible points in the grid\n    const Eigen::ArrayXXd* w;\n    /// Temperature\n    double T;\n\n    /// Unitvector describing 1D thermal transport axis\n    Eigen::Vector3d unitvector;\n    /// Unitvector describing the film normal for inplane transport\n    Eigen::Vector3d filmnormal;\n    /// Spatial grid\n    Eigen::VectorXd x;\n    bool gridIsNormalised;\n    /// Output specifier\n    bool normaliseoutput;\n    /// MFP bins\n    Eigen::VectorXd MFPbins;\n    /// time value\n    double t;\n    /// diffusivity of the medium along the transport axis\n    double Dbulk;\n    void updateDiffusivity();\n    /// Calculated SPR\n    Eigen::VectorXd Pxt;\n    /// Calculated SPR resolved by MFP\n    Eigen::MatrixXd Pmodes;\n};\n\n/////////////////// MSD_calculator_Laplace ///////////////////\n\n/// Class for computing the exact analytical RTA solution for\n/// mean square thermal energy displacement. By definition,\n/// the MSD is the variance of the macroscopic energy density:\n/// MSD = Integral(x^2*P(x,s),x=-infinity..infinity).\n/// Results are valid across all regimes\n/// (from fully ballistic to fully diffusive transport).\n/// Calculations are performed fully analytically by using\n/// the moment generating properties of the energy density\n/// in spatial frequency domain:\n/// MSD = minus second derivative of P(xi,s) at xi = 0.\n\nclass MSD_calculator_Laplace {\npublic:\n    /// Constructor: initialise internal variables\n    MSD_calculator_Laplace(const alma::Crystal_structure* poscar,\n                           const alma::Gamma_grid* grid,\n                           const Eigen::ArrayXXd* w,\n                           double T);\n\n    /// Function setting the thermal transport axis\n    void setDirection(const Eigen::Vector3d unitvector);\n\n    /// Construct a linear temporal frequency grid\n    /// from fmin to fmax with Nf elements\n    void setLinGrid(double fmin, double fmax, int Nf);\n\n    /// Construct a logarithmic temporal frequency grid\n    /// from fmin to fmax with Nf elements\n    void setLogGrid(double fmin, double fmax, int Nf);\n\n    /// Manually set a Laplace grid\n    void setLaplaceGrid(const Eigen::Ref<const Eigen::VectorXcd> sgrid);\n\n    /// Retrieve the temporal frequency grid\n    Eigen::VectorXd getGrid();\n    Eigen::VectorXcd getLaplaceGrid();\n\n    /// Compute MSD and retrieve it\n    Eigen::VectorXcd getMSD();\n\nprivate:\n    /// Pointer to description of the unit cell\n    const alma::Crystal_structure* poscar;\n    /// Pointer to phonon spectrum on a regular q-point grid\n    const alma::Gamma_grid* grid;\n    /// Pointer to scattering rates for all modes irreducible points in the grid\n    const Eigen::ArrayXXd* w;\n    /// Temperature\n    double T;\n\n    /// Unitvector describing 1D thermal transport axis\n    Eigen::Vector3d unitvector;\n    /// Temporal frequency grid\n    Eigen::VectorXd f;\n    /// Laplace grid\n    Eigen::VectorXcd s;\n    /// Calculated MSD function\n    Eigen::VectorXcd MSD;\n};\n\n/////////////////// MSD_calculator_RealTime ///////////////////\n\n/// Class for computing the exact analytical RTA solution for\n/// mean square thermal energy displacement in time domain.\n///\n/// Calculations are performed by numerically inverting\n/// output from MSD_calculator_Laplace to time domain\n/// with a Gaver-Stehfest scheme.\n\nclass MSD_calculator_RealTime {\npublic:\n    /// Constructor: initialise internal variables\n    MSD_calculator_RealTime(const alma::Crystal_structure* poscar,\n                            const alma::Gamma_grid* grid,\n                            const Eigen::ArrayXXd* w,\n                            double T);\n\n    /// Function setting the thermal transport axis\n    void setDirection(const Eigen::Vector3d unitvector);\n\n    /// Construct a linear time grid\n    /// from tmin to tmax with Nt elements\n    void setLinGrid(double tmin, double tmax, int Nt);\n\n    /// Construct a logarithmic time grid\n    /// from tmin to tmax with Nt elements\n    void setLogGrid(double tmin, double tmax, int Nt);\n\n    /// Manually set a time grid\n    void setTimeGrid(const Eigen::Ref<const Eigen::VectorXd> tgrid);\n\n    /// Retrieve the timegrid\n    Eigen::VectorXd getGrid();\n\n    /// Optional choice to normalise calculated results\n    /// by Fourier solution 2*D*t.\n    void normaliseOutput(bool norm);\n\n    /// Retrieve Fourier diffusivity\n    double getDiffusivity();\n\n    /// Compute MSD and retrieve it\n    Eigen::VectorXd getMSD();\n\nprivate:\n    /// Pointer to description of the unit cell\n    const alma::Crystal_structure* poscar;\n    /// Pointer to phonon spectrum on a regular q-point grid\n    const alma::Gamma_grid* grid;\n    /// Pointer to scattering rates for all modes irreducible points in the grid\n    const Eigen::ArrayXXd* w;\n    /// Temperature\n    double T;\n\n    /// Unitvector describing 1D thermal transport axis\n    Eigen::Vector3d unitvector;\n    /// Unitvector describing the film normal for inplane transport\n    Eigen::Vector3d filmnormal;\n    /// Time grid\n    Eigen::VectorXd t;\n    /// Fourier diffusivity\n    double Dbulk;\n    void updateDiffusivity();\n    /// output specifier\n    bool normaliseoutput;\n    /// Calculated MSD function\n    Eigen::VectorXd MSD;\n\n    /// Gaver-Stehfest Laplace inversion coefficients\n    int GS_depth;\n    Eigen::VectorXd GS_coeffs;\n    /// Helper function for Gaver-Stehfest Laplace inversion\n    double factorial(int n);\n};\n} // end namespace analytic1D\n} // end namespace alma\n", "meta": {"hexsha": "3e1e8366c511f48453988517a9544e8a478a954a", "size": 20511, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/analytic1d.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/analytic1d.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/analytic1d.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.3567839196, "max_line_length": 80, "alphanum_fraction": 0.6852420652, "num_tokens": 4712, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6548947290421275, "lm_q2_score": 0.5156199157230156, "lm_q1q2_score": 0.3376767649961489}}
{"text": "//\n// Created by markus on 23.04.21.\n//\n\n#include <random>\n#include <boost/math/distributions/exponential.hpp>\n#include \"ParticleFilter.h\"\n#include \"../Simulator/world/world.h\"\n#include \"../Simulator/interactive_objects/DistanceSensor.h\"\n#include \"helpers.h\"\n#include \"DummyRobot.h\"\n\nParticleFilter::ParticleFilter(RobotControlInterface *robot, std::string map_filename, int initialN, int targetN) {\n    this->particles_world = new World(map_filename, \"Particle filter\");\n    this->particles_world->addMapObject(this->mapLine);\n    this->robot = robot;\n\n    this->N = initialN;\n    this->TARGET_N = targetN;\n\n    // create initial particles distribution and show the simulation map\n    this->particles = ParticleFilter::create_uniform_particles(this->particles_world->get_map_bounds().x,\n                                                               this->particles_world->get_map_bounds().y,\n                                                               this->N);\n    this->estimatedRobot = new MapRobot(robot->get_radius());\n    this->estimatedRobot->setColor(CV_RGB(255, 255, 255));\n    this->particles_world->addMapObject(this->estimatedRobot);\n    ParticleFilter::updateParticleSimulation(this->particles, SHOW_WHATS_GOING_ON);\n}\n\nstd::vector<std::array<double, 3>> ParticleFilter::create_uniform_particles(double x_range, double y_range, int N) {\n    std::vector<std::array<double, 3>> particles;\n    std::default_random_engine generator;\n    generator.seed(std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::system_clock::now().time_since_epoch()).count());\n\n    std::uniform_real_distribution<double> x_distribution(0, x_range);\n    std::uniform_real_distribution<double> y_distribution(0, y_range);\n    std::uniform_real_distribution<double> angle_distribution(-M_PI, M_PI);\n\n    for (int i = 0; i < N; i++) {\n        particles.push_back(std::array<double, 3>({x_distribution(generator),\n                                                   y_distribution(generator),\n                                                   angle_distribution(generator)}));\n    }\n    return particles;\n}\n\nvoid ParticleFilter::updateParticleSimulation(std::vector<std::array<double, 3>> particles, bool showMap, std::vector<double> weights) {\n    // get sensor config to recreate (clone) the same sensors as on the robot\n    std::vector<std::array<double, 2>> sensor_config;\n    for (DistanceSensor *sensor : DistanceSensor::filter_for_distance_sensor(this->robot->get_sensors())) {\n        sensor_config.push_back(std::array<double, 2>({sensor->get_sensor_angle(), sensor->get_sensor_max_distance()}));\n    }\n\n    // If weights are provided they will be visualized on the map. For the color scaling we have to know what the maximum probability of one particle is\n    double maxWeight = 0;\n    bool useCustomWeightColors = false;\n    if (!weights.empty()) {\n        useCustomWeightColors = true;\n        for (double weight : weights) {\n            maxWeight = maxWeight > weight ? maxWeight : weight;\n        }\n    }\n\n\n    // add or delete robots from the world if the amount does not match\n    if (this->particles_world->getRobotsList().size() > particles.size()) {\n        // there are too many particles -> remove some\n        this->particles_world->deleteRobotByIndex(particles.size() - 1, this->particles_world->getRobotsList().size() - particles.size() + 1, true);\n    } else if (this->particles_world->getRobotsList().size() < particles.size()) {\n        // there arent enough particles -> add some\n        for (long i = this->particles_world->getRobotsList().size(); i<particles.size(); ++i) {\n            // create robot\n            auto* dummyRobot = new DummyRobot(\"particle\", this->robot->get_radius(), this->particles_world);\n            // set default visualization options\n            dummyRobot->setDrawOptions(CV_RGB(255, 0, 0), true, 1);\n            // add robot to world\n            this->particles_world->addRobot(dummyRobot);\n\n            // create sensors\n            for (std::array<double, 2> s_config : sensor_config) {\n                DistanceSensor *sensor = new DistanceSensor(this->particles_world, dummyRobot, s_config[0], s_config[1], true);\n                dummyRobot->add_sensor(sensor);\n            }\n        }\n    }\n\n    // update robots\n    std::vector<Robot*> dummyRobotsList = this->particles_world->getRobotsList();\n    for (int i = 0; i < particles.size(); ++i) {\n        std::array<double, 3> particle = particles[i];\n        DummyRobot* dummyRobot = (DummyRobot*) dummyRobotsList[i];\n        dummyRobot->reposition(particle[0], particle[1], particle[2]);\n\n        // set custom visualization options\n        if (useCustomWeightColors) {\n            dummyRobot->setDrawOptions(getColor(weights[i] / maxWeight), true, 1);\n        }\n\n        for (SensorInterface* sensor : dummyRobot->get_sensors()) {\n            sensor->update_sensor_data(true);\n        }\n    }\n\n    // show map if enabled\n    if (showMap) {\n        this->particles_world->show_map(true);\n    }\n}\n\nstd::vector<std::array<double, 3>> ParticleFilter::particles_predict(std::vector<std::array<double, 3>> *oldParticles,\n                                                                     double move_distance,\n                                                                     double move_angle,\n                                                                     double standard_deviation) {\n    std::vector<std::array<double, 3>> updated_particles;\n\n    // init normal_distribution\n    std::random_device rd{};\n    std::mt19937 gen{rd()};\n    std::normal_distribution<> d{0, standard_deviation};\n\n    // update oldParticles\n    for (std::array<double, 3> particle : *oldParticles) {\n        // update moved distance and angle with a norm distribution value (x * ((100 + <norm_dist>) / 100))\n        double distance_with_distribution = move_distance * ((100 + d(gen)) / 100);\n        double angle_with_distribution = move_angle * ((100 + d(gen)) / 100);\n\n        double newRobotAngle = angle_with_distribution + particle[2];\n\n        // update oldParticles with distance and angle\n        updated_particles.push_back(std::array<double, 3>(\n                {\n                        particle[0] + cos(newRobotAngle) * distance_with_distribution,\n                        particle[1] + sin(newRobotAngle) * distance_with_distribution,\n                        newRobotAngle\n                }));\n    }\n\n    return updated_particles;\n}\n\nstd::vector<double> ParticleFilter::particles_update(std::vector<double> robotSensorValues, std::vector<Robot *> simRobots, double lambda) {\n    std::vector<double> updated_weights = std::vector<double>(simRobots.size(), 1.0);\n    auto d = boost::math::exponential_distribution<>{lambda};\n\n    double sumOfWeights = 0;\n\n    for (int i = 0; i < updated_weights.size(); ++i) {\n        // collect sensor values of simulated particles\n        std::vector<DistanceSensor *> sensors = DistanceSensor::filter_for_distance_sensor(simRobots.at(i)->get_sensors());\n        int j = 0;\n        for (DistanceSensor *sensor : sensors) {\n            // calculate correlation\n            updated_weights[i] *= boost::math::pdf(d, abs(sensor->get_simplified_sensor_value() - robotSensorValues[j]));\n            updated_weights[i] += 1.e-300; // prevent rounding to 0\n            j++;\n        }\n\n        sumOfWeights += updated_weights[i];\n    }\n\n    // normalize weights: sum of weights should equal 1\n    for (double &updated_weight : updated_weights) {\n        updated_weight /= sumOfWeights;\n    }\n\n    return updated_weights;\n}\n\nstd::tuple<std::vector<std::array<double, 3>>, std::vector<double>> ParticleFilter::particles_resample(\n        std::vector<std::array<double, 3>> *oldParticles,\n        std::vector<double> *weights,\n        int N,\n        bool enableRandomParticles,\n        double noise,\n        cv::Point2d mapBounds) {\n    // grouping algorithm for resampling is explained here: https://robotics.stackexchange.com/a/481\n    // creates an index list of entries to keep\n    std::vector<double> positions = {};\n    for (int i = 0; i < N; ++i) {\n        positions.push_back((i + ((double) rand() / RAND_MAX)) / N);\n    }\n\n    std::vector<int> indexes(N, 0);\n    std::vector<double> cumulativeSum = {};\n    cumulativeSum.push_back(weights->at(0));\n    for (int i = 1; i < N; ++i) {\n        cumulativeSum.push_back(cumulativeSum.at(i - 1) + weights->at(i));\n    }\n\n    int i = 0;\n    int j = 0;\n    while (i < N && j < N) {\n        if (positions[i] < cumulativeSum[j]) {\n            indexes[i] = j;\n            i += 1;\n        } else {\n            j += 1;\n        }\n    }\n\n    // create a new particles list. It will be based on the previous one. Based on the index list created above some values will be kept, others\n    // will be deleted. There will be many duplicates, which is expected. Each value will be modified by a noise value.\n    std::default_random_engine generator;\n    std::uniform_real_distribution<double> uniformNoise(-noise, noise);\n\n    std::vector<std::array<double, 3>> updatedParticles = {};\n    std::vector<double> updatedWeights = {};\n    double weightSum = 0;\n    for (int i = 0; i < N; ++i) {\n        updatedParticles.push_back(std::array<double, 3>({oldParticles->at(indexes[i])[0] + uniformNoise(generator),\n                                                          oldParticles->at(indexes[i])[1] + uniformNoise(generator),\n                                                          oldParticles->at(indexes[i])[2] + uniformNoise(generator) / 10\n                                                         }));\n        updatedWeights.push_back(weights->at(indexes[i]));\n        weightSum += weights->at(indexes[i]);\n    }\n\n    // normalize weights\n    for (int i = 0; i < N; ++i) {\n        weights->at(indexes[i]) /= weightSum;\n    }\n\n    return std::tuple<std::vector<std::array<double, 3>>, std::vector<double>>(updatedParticles, updatedWeights);\n}\n\n\nParticleEvaluationData ParticleFilter::update() {\n    return this->update(this->robot->get_last_tick_movement_distance(), this->robot->get_last_tick_movement_angle());\n}\n\n\nParticleEvaluationData ParticleFilter::update(double distance, double angle) {\n    // check if in location finding phase\n    int removeElementsCount = N * INITIAL_PHASE_REPLACE_SHARE;;\n    if (!this->initialLocationFinished && this->iterationsCounter > 0) {\n        // check if location is found\n        if (this->locationCertaintyEstimation > CERTAINTY_ESTIMATION_THRESHOLD) {\n            // check uncertainty metric if location seems to be already successful\n            std::cout << \"Found location\" << std::endl;\n            this->initialLocationFinished = true;\n            this->N = TARGET_N;\n            this->useRandomParticles = false;\n        }\n\n        // if location not yet found: select the worst rated particles and replace them with random\n        if (!this->initialLocationFinished) {\n            // bubble sort\n            // could be replaced with a more efficient algorithm if its computationally too expensive\n            bool finished = false;\n            for (int i = 0; !finished && i < this->particles.size(); ++i) {\n                finished = true;\n                for (int j = i + 1; j < this->particles.size(); ++j) {\n                    if (this->weights[i] > this->weights[j]) {\n                        finished = false;\n                        double tmpWeight = this->weights[i];\n                        std::array<double, 3> tmpParticle = this->particles[i];\n                        this->weights[i] = this->weights[j];\n                        this->weights[j] = tmpWeight;\n                        this->particles[i] = this->particles[j];\n                        this->particles[j] = tmpParticle;\n                    }\n                }\n            }\n\n            // drop the first particles (lowest probability)\n            this->weights.erase(this->weights.begin(), this->weights.begin() + removeElementsCount);\n            this->particles.erase(this->particles.begin(), this->particles.begin() + removeElementsCount);\n\n            // generate new particles to replace the removed ones\n            std::vector<std::array<double, 3>> randomParticles = create_uniform_particles(this->particles_world->get_map_bounds().x,\n                                                                                          this->particles_world->get_map_bounds().y,\n                                                                                          removeElementsCount);\n            this->particles.insert(this->particles.end(), randomParticles.begin(), randomParticles.end());\n        }\n    }\n    this->iterationsCounter++;\n\n\n    // Begin of actual particle filter steps\n\n    // Particle Filter Step 1) particle prediction: apply estimated movement distance / angle (currently in this simulator there is no noise for those values)\n    std::vector<std::array<double, 3>> updated_particles = particles_predict(&this->particles,\n                                                                             distance,\n                                                                             angle,\n                                                                             4);\n\n    // Particle Filter Step 2) update weights: update the weight of each particle based on how much the simulated sensor values correspond to the ones of our \"real\" robot\n    // generate vector containing the current sensor values of the \"real\" robot\n    std::vector<double> robotSensorValues = {};\n    for (DistanceSensor *sensor : DistanceSensor::filter_for_distance_sensor(this->robot->get_sensors())) {\n        robotSensorValues.push_back(sensor->get_simplified_sensor_value());\n    }\n\n    // this allows to read the sensor values of all simulated particles in particles_update()\n    this->updateParticleSimulation(updated_particles, false);\n\n    // this will do the actual weights update\n    std::vector<double> updated_weights = this->particles_update(robotSensorValues, this->particles_world->getRobotsList(), 0.01);\n\n    // Particle Filter Step 3) resample: create new particles based on the weights. They will be mostly around the most previous particles with the highest weight.\n    std::tuple<std::vector<std::array<double, 3>>, std::vector<double>> resampledTuple = this->particles_resample(&updated_particles,\n                                                                                                                  &updated_weights,\n                                                                                                                  this->N,\n                                                                                                                  this->useRandomParticles,\n                                                                                                                  5,\n                                                                                                                  this->particles_world->get_map_bounds());\n\n    // END of actual particle filter steps\n\n\n    // calculate estimated position\n    std::array<double, 3> estimatedParticle{};\n    if (!this->initialLocationFinished) {\n        // if in the initial phase: only the first x particles are relevant, the others are random\n        int relevantParticlesCount = N - removeElementsCount;\n        estimatedParticle = weightedAverageParticle(std::vector<std::array<double,3>>(updated_particles.begin(), updated_particles.begin()+relevantParticlesCount), std::vector<double>(updated_weights.begin(), updated_weights.begin()+relevantParticlesCount));\n    } else {\n        estimatedParticle = weightedAverageParticle(updated_particles, updated_weights);\n    }\n\n\n    // estimate whether the prediction is probably already accurate and if yes, add to history, if not: clear history\n    // also visualize it on the map as a line\n    if (!this->estimationHistory.empty()) {\n        // TODO: replace this algorithm with a better one looking further in the past and calculate an uncertainty value\n        double maxAcceptableMovementDistance = pow(this->robot->get_max_move_speed() / GAME_TPS * 2.5, 2); // theoretically maximum possible movement distance * X as square to prevent requirement of sqrt\n        double distanceFromLastEstimation = pow(this->estimationHistory.back()[0] - estimatedParticle[0], 2) + pow(this->estimationHistory.back()[1] - estimatedParticle[1], 2);\n        if (distanceFromLastEstimation >= maxAcceptableMovementDistance) {\n            this->estimationHistory.clear();\n            this->locationCertaintyEstimation = this->locationCertaintyEstimation > 0 ? this->locationCertaintyEstimation - 5 / GAME_TPS : 0;\n            if (SHOW_WHATS_GOING_ON && !this->initialLocationFinished) this->mapLine->clearPoints();\n            std::cout << \"Estimated location jumped too far, this is an indication for a wrong location estimation\" << std::endl;\n        } else {\n            this->locationCertaintyEstimation = this->locationCertaintyEstimation < 10 ? this->locationCertaintyEstimation + 1 / GAME_TPS : 10;\n        }\n    }\n    if (SHOW_WHATS_GOING_ON) this->estimationHistory.push_back(estimatedParticle);\n    this->mapLine->addPoint(cv::Point2i((int) estimatedParticle[0], (int) estimatedParticle[1]));\n\n    // show current particles with their weights and the estimated robot location\n    // nice for visualization but will impact performance!\n    if (SHOW_WHATS_GOING_ON) {\n        this->updateParticleSimulation(updated_particles, false, updated_weights);\n        this->estimatedRobot->reposition(cv::Point2d(estimatedParticle[0], estimatedParticle[1]), estimatedParticle[2]);\n        this->particles_world->show_map(true);\n    }\n\n\n    // save particles and weights\n    this->particles = std::get<0>(resampledTuple);\n    this->weights = std::get<1>(resampledTuple);\n\n\n    return ParticleEvaluationData({cv::Point2d(estimatedParticle[0], estimatedParticle[1]), estimatedParticle[2], locationCertaintyEstimation >= CERTAINTY_ESTIMATION_THRESHOLD});\n}\n\n\n", "meta": {"hexsha": "332f1f51cb4e2ed114f2e0ac75878f8cc184bf05", "size": 18004, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lib/ParticleFilter.cpp", "max_stars_repo_name": "Glutamat42/Robot-Simulator", "max_stars_repo_head_hexsha": "4cec0e3bcb2aeb607f57e83bd545d626ea53af1a", "max_stars_repo_licenses": ["MIT"], "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/ParticleFilter.cpp", "max_issues_repo_name": "Glutamat42/Robot-Simulator", "max_issues_repo_head_hexsha": "4cec0e3bcb2aeb607f57e83bd545d626ea53af1a", "max_issues_repo_licenses": ["MIT"], "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/ParticleFilter.cpp", "max_forks_repo_name": "Glutamat42/Robot-Simulator", "max_forks_repo_head_hexsha": "4cec0e3bcb2aeb607f57e83bd545d626ea53af1a", "max_forks_repo_licenses": ["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.1504178273, "max_line_length": 258, "alphanum_fraction": 0.6094756721, "num_tokens": 3786, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6548947155710233, "lm_q2_score": 0.5156199157230157, "lm_q1q2_score": 0.3376767580501794}}
{"text": "//    Copyright 2019 Jij Inc.\n\n//    Licensed under the Apache License, Version 2.0 (the \"License\");\n//    you may not use this file except in compliance with the License.\n//    You may obtain a copy of the License at\n\n//        http://www.apache.org/licenses/LICENSE-2.0\n\n//    Unless required by applicable law or agreed to in writing, software\n//    distributed under the License is distributed on an \"AS IS\" BASIS,\n//    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n//    See the License for the specific language governing permissions and\n//    limitations under the License.\n\n#ifndef OPENJIJ_UTILITY_EIGEN_HPP__\n#define OPENJIJ_UTILITY_EIGEN_HPP__\n\n#include <graph/all.hpp>\n#include <Eigen/Dense>\n#include <Eigen/Sparse>\n\nnamespace openjij {\n    namespace utility {\n\n        /**\n         * @brief get Eigen Matrix type from Graph Type\n         *\n         * @tparam GraphType\n         * @tparam Options Eigen Options (RowMajor or ColMajor)\n         */\n        template<typename GraphType, int Options=Eigen::ColMajor>\n            struct get_eigen_matrix_type{};\n\n        /**\n         * @brief get Eigen Matrix type from Graph Type\n         *\n         * @tparam GraphType\n         * @tparam Options Eigen Options (RowMajor or ColMajor)\n         */\n        template<typename FloatType, int Options>\n            struct get_eigen_matrix_type<graph::Dense<FloatType>, Options>{\n                using type = Eigen::Matrix<FloatType, Eigen::Dynamic, Eigen::Dynamic, Options>;\n            };\n\n        /**\n         * @brief get Eigen Matrix type from Graph Type\n         *\n         * @tparam GraphType\n         * @tparam Options Eigen Options (RowMajor or ColMajor)\n         */\n        template<typename FloatType, int Options>\n            struct get_eigen_matrix_type<graph::Sparse<FloatType>, Options>{\n                using type = Eigen::SparseMatrix<FloatType, Options>;\n            };\n\n        /**\n         * @brief generate Eigen Vector from std::vector\n         *\n         * @tparam FloatType\n         * @tparam Options Eigen Options (RowMajor or ColMajor)\n         * @param init_spin\n         *\n         * @return generated Eigen Vector (init_spin.size()+1 x 1)\n         */\n        template<typename FloatType, int Options=Eigen::ColMajor>\n            inline static Eigen::Matrix<FloatType, Eigen::Dynamic, 1, Options>\n            gen_vector_from_std_vector(const graph::Spins& init_spin){\n                Eigen::Matrix<FloatType, Eigen::Dynamic, 1, Options> ret_vec(init_spin.size()+1);\n\n                //initialize spin\n                for(size_t i=0; i<init_spin.size(); i++){\n                    ret_vec(i) = init_spin[i];\n                }\n\n                //for local field\n                ret_vec[init_spin.size()] = 1;\n\n                return ret_vec;\n            }\n\n        /**\n         * @brief generate Eigen Matrix from TrotterSpins\n         *\n         * @tparam FloatType\n         * @tparam Options Eigen Options (RowMajor or ColMajor)\n         * @param trotter_spins\n         *\n         * @return generated Eigen Matrix (trotter_spins[0].size()+1 x trotter_spins.size())\n         */\n        template<typename FloatType, int Options=Eigen::ColMajor>\n            inline static Eigen::Matrix<FloatType, Eigen::Dynamic, Eigen::Dynamic, Options>\n            gen_matrix_from_trotter_spins(const std::vector<graph::Spins>& trotter_spins){\n                Eigen::Matrix<FloatType, Eigen::Dynamic, Eigen::Dynamic, Options> ret_mat(trotter_spins[0].size()+1, trotter_spins.size());\n\n                //initialize spin\n                for(size_t j=0; j<trotter_spins.size(); j++){\n                    for(size_t i=0; i<trotter_spins[j].size(); i++){\n                        ret_mat(i,j) = trotter_spins[j][i];\n                    }\n                }\n\n                //dummy spins\n                for(size_t j=0; j<trotter_spins.size(); j++){\n                    ret_mat(trotter_spins[0].size(),j) = 1;\n                }\n\n                return ret_mat;\n            }\n\n        /**\n         * @brief generate Eigen Dense Matrix from Dense graph\n         *\n         * @tparam Options Eigen Options (RowMajor or ColMajor)\n         * @tparam FloatType\n         * @param graph\n         *\n         * @return generated Eigen Dense Matrix (graph.get_num_spins()+1 x graph.get_num_spins()+1)\n         */\n        template<int Options=Eigen::ColMajor, typename FloatType>\n            inline static Eigen::Matrix<FloatType, Eigen::Dynamic, Eigen::Dynamic, Options>\n            gen_matrix_from_graph(const graph::Dense<FloatType>& graph){\n                //initialize interaction\n                Eigen::Matrix<FloatType, Eigen::Dynamic, Eigen::Dynamic, Options> ret_mat(graph.get_num_spins()+1, graph.get_num_spins()+1);\n\n                ret_mat.setZero();\n\n                for(size_t i=0; i<graph.get_num_spins(); i++){\n                    for(size_t j=i+1; j<graph.get_num_spins(); j++){\n                        ret_mat(i,j) = graph.J(i,j);\n                        ret_mat(j,i) = graph.J(i,j);\n                    }\n                }\n\n                //for local field\n                for(size_t i=0; i<graph.get_num_spins(); i++){\n                    ret_mat(i,graph.get_num_spins()) = graph.h(i);\n                    ret_mat(graph.get_num_spins(),i) = graph.h(i);\n                }\n\n                //for local field\n                ret_mat(graph.get_num_spins(),graph.get_num_spins()) = 1;\n\n                return ret_mat;\n            }\n\n        /**\n         * @brief generate Eigen Sparse Matrix from Sparse graph\n         *\n         * @tparam Options Eigen Options (RowMajor or ColMajor)\n         * @tparam FloatType\n         * @param graph\n         *\n         * @return generated Eigen Sparse Matrix (graph.get_num_spins()+1 x graph.get_num_spins()+1)\n         */\n        template<int Options=Eigen::ColMajor, typename FloatType>\n            inline static Eigen::SparseMatrix<FloatType, Options>\n            gen_matrix_from_graph(const graph::Sparse<FloatType>& graph){\n                //initialize interaction\n                Eigen::SparseMatrix<FloatType, Options> ret_mat(graph.get_num_spins()+1, graph.get_num_spins()+1);\n\n                ret_mat.setZero();\n\n                //make triplet list\n                using T = std::vector<Eigen::Triplet<FloatType>>;\n                T t_list;\n\n                for(size_t ind=0; ind<graph.get_num_spins(); ind++){\n                    for(size_t adj_ind : graph.adj_nodes(ind)){\n                        if(ind != adj_ind){\n                            t_list.emplace_back(ind, adj_ind, graph.J(ind, adj_ind));\n                        }\n                        else{\n                            t_list.emplace_back(ind, graph.get_num_spins(), graph.h(ind));\n                            t_list.emplace_back(graph.get_num_spins(), ind, graph.h(ind));\n                        }\n                    }\n                }\n\n                t_list.emplace_back(graph.get_num_spins(), graph.get_num_spins(), 1);\n\n                ret_mat.setFromTriplets(t_list.begin(), t_list.end());\n\n                return ret_mat;\n            }\n\n\n\n    } // namespace utility\n} // namespace openjij\n\n#endif\n", "meta": {"hexsha": "7b02d6158964f38cd8cb21ce67b3b655ff30eb72", "size": 7156, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/utility/eigen.hpp", "max_stars_repo_name": "Atsushi-Machida/OpenJij", "max_stars_repo_head_hexsha": "e4bddebb13536eb26ff0b7b9fc6b1c75659fe934", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/utility/eigen.hpp", "max_issues_repo_name": "Atsushi-Machida/OpenJij", "max_issues_repo_head_hexsha": "e4bddebb13536eb26ff0b7b9fc6b1c75659fe934", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 7.0, "max_issues_repo_issues_event_min_datetime": "2021-07-26T16:12:20.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T16:15:04.000Z", "max_forks_repo_path": "src/utility/eigen.hpp", "max_forks_repo_name": "29rou/OpenJij", "max_forks_repo_head_hexsha": "c2579fba8710cf82b9e6761304f0042b365b595c", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-04-09T09:13:56.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-09T09:13:56.000Z", "avg_line_length": 37.2708333333, "max_line_length": 140, "alphanum_fraction": 0.5505869201, "num_tokens": 1544, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6548947155710234, "lm_q2_score": 0.5156199157230156, "lm_q1q2_score": 0.3376767580501793}}
{"text": "/*\n    Copyright (c) 2011 Alin Marin Elena <alinm.elena@gmail.com>\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 <cmath>\n#include <iostream>\n\n#include <boost/random/normal_distribution.hpp>\n#include <boost/random/uniform_real.hpp>\n#include <boost/random/mersenne_twister.hpp>\n#include <boost/random/variate_generator.hpp>\n\n#include <boost/random/linear_congruential.hpp>\n#include <boost/random/uniform_01.hpp>\n\n#include \"solution.h\"\n#include \"utils.h\"\n#include \"reading.h\"\n#include \"colours.h\"\n#include \"gutenberg.h\"\n#include \"collectivevariable.h\"\n\nusing namespace std;\nusing namespace colours;\n\nvoid solution::InitializeSimulation ( std::vector<atom>& a, const double& temp, const double& box, const int& seed, string const& filename , double const& gamma )\n{\n     InitializeSimulation ( a,temp,box,seed,filename );\n     int k=0;\n     for ( vector<atom>::iterator i=a.begin(); i<a.end(); i++ ) {\n          ( *i ).setGamma ( gamma );\n          ( *i ).setID ( k );\n          k++;\n     }\n}\n\nvoid solution::InitializeSimulation ( std::vector<atom>& a, const double& temp, const double& box, const int& seed, string const& filename )\n{\n// equal spaced in the box\n     boost::mt19937 igen ( seed );\n     boost::variate_generator<boost::mt19937, boost::normal_distribution<> >    rgauss ( igen, boost::normal_distribution<> ( 0.0,1.0 ) );\n     double x,y,z,fact;\n\n     int k=reading::readXYZ ( filename.c_str(),a );\n     for ( int i=0; i<a.size(); i++ ) {\n          a[i].setMass ( 1.0 );\n          a[i].setID ( i );\n          fact=sqrt ( utils::Kb*temp/a[i].getMass() );\n          a[i].setVelocities ( fact*rgauss(),fact*rgauss(),fact*rgauss() );\n          a[i].setForces ( 0.0,0.0,0.0 );\n     }\n\n//remove the movement of the centre of mass\n     centerOfMassV ( a );\n     scaleVelocities ( a,temp );\n}\n\nvoid solution::RandomVelocities ( std::vector<atom>& a, const double& temp, const double& box, const int& seed )\n{\n// equal spaced in the box\n     boost::mt19937 igen ( seed );\n     boost::variate_generator<boost::mt19937, boost::normal_distribution<> >    rgauss ( igen, boost::normal_distribution<> ( 0.0,1.0 ) );\n     double x,y,z,fact;\n\n     for ( int i=0; i<a.size(); i++ ) {\n          fact=sqrt ( utils::Kb*temp/a[i].getMass() );\n          a[i].setVelocities ( fact*rgauss(),fact*rgauss(),fact*rgauss() );\n          a[i].setForces ( 0.0,0.0,0.0 );\n     }\n//remove the movement of the centre of mass\n     centerOfMassV ( a );\n     scaleVelocities ( a,temp );\n}\n\n\nvoid solution::InitializeSimulation ( std::vector<atom>& a, string const& filename )\n{\n     int k=reading::readFull ( filename.c_str(),a );\n     if ( k!=0 ) {\n          utils::Print ( \"Error!!!\",cout,colours::red );\n     }\n}\n\n\nvoid solution::GenerateLattice ( vector< atom >&a, const double&rho,\n                                 const int&mass, const double&nAtoms, double& box, const string& el )\n{\n\n     double volume=nAtoms*mass/rho;\n     box=pow ( volume,1.0/3.0 );\n     int n=int ( pow ( nAtoms,1.0/3.0 ) );\n     if ( n*n*n!=nAtoms ) n++;\n     double h=box/ ( n );\n     double x;\n     double y;\n     double z;\n     int m=0;\n     for ( int i=0; i<n; i++ ) {\n          x=i*h;\n          for ( int j=0; j<n; j++ ) {\n               y=j*h;\n               for ( int k=0; k<n; k++ ) {\n                    z=k*h;\n                    if ( m<nAtoms ) {\n                         a.push_back ( atom() );\n                         a[m].setElement ( el );\n                         a[m].setPositions ( x,y,z );\n                         a[m].setMass ( mass );\n                         a[m].setID ( m );\n                    }\n                    m++;\n               }\n          }\n     }\n\n}\n\n\n\nvoid solution::centerOfMassV ( vector< atom >& a )\n{\n     double vmx=0.0, vmy=0.0, vmz=0.0,mt=0.0;\n     for ( vector<atom>::iterator it=a.begin(); it<a.end(); it++ ) {\n          vmx+= ( *it ).px();\n          vmy+= ( *it ).py();\n          vmz+= ( *it ).pz();\n          mt+= ( *it ).getMass();\n     }\n     vmx=-vmx/mt;\n     vmy=-vmy/mt;\n     vmz=-vmz/mt;\n     for ( vector<atom>::iterator it=a.begin(); it<a.end(); it++ ) {\n          ( *it ).addtoVelocities ( vmx,vmy,vmz );\n     }\n}\n\nvoid solution::scaleVelocities ( vector< atom >& a, const double& T )\n{\n     double tx=0.0,ty=0.0, tz=0.0;\n     if ( T>0.0 ) {\n          for ( vector<atom>::iterator it=a.begin(); it<a.end(); it++ ) {\n               tx+= ( *it ).getMass() * ( *it ).vx2();\n               ty+= ( *it ).getMass() * ( *it ).vy2();\n               tz+= ( *it ).getMass() * ( *it ).vz2();\n          }\n          tx=tx/ ( a.size() *utils::Kb ) ;\n          ty=ty/ ( a.size() *utils::Kb ) ;\n          tz=tz/ ( a.size() *utils::Kb ) ;\n          tx=sqrt ( T/tx );\n          ty=sqrt ( T/ty );\n          tz=sqrt ( T/tz );\n     }\n     for ( vector<atom>::iterator it=a.begin(); it<a.end(); it++ ) {\n          ( *it ).scaleVelocity ( tx,ty,tz );\n     }\n}\n\ndouble solution::computeForces ( vector< atom >& a, const double & rc, const double& box, double& vir )\n{\n     for ( vector<atom>::iterator it=a.begin(); it<a.end(); it++ ) {\n          ( *it ).setForces ( 0.0,0.0,0.0 );\n     }\n\n     double R,fR,fx,fy,fz,energy;\n     vector<double> dR ( 3 );\n     double ec=utils::LennardJones ( rc );\n     energy=0.0;\n     for ( vector<atom>::iterator i=a.begin(); i<a.end()-1; i++ ) {\n          for ( vector<atom>::iterator j=i+1; j<a.end(); j++ ) {\n               R=rdr ( dR,*i,*j,box );\n               if ( R<rc ) {\n                    fR=utils::LennardJonesdR ( R );\n                    fx=-fR*dR[0]/R;\n                    fy=-fR*dR[1]/R;\n                    fz=-fR*dR[2]/R;\n                    ( *i ).addtoForces ( fx,fy,fz );\n                    ( *j ).addtoForces ( -fx,-fy,-fz );\n                    energy+=utils::LennardJones ( R )-ec;\n                    vir+=fR*R;\n               }\n          }\n     }\n     return energy;\n}\n\ndouble solution::velocityVerlet ( vector< atom >& a, const double& rc, const double& box, const double& dt , double& kin, double &vir )\n{\n     kin=0.0;\n     vir=0.0;\n     for ( vector<atom>::iterator i=a.begin(); i<a.end(); i++ ) {\n          ( *i ).updatePositionsVV ( dt );\n          ( *i ).putInBox ( box );\n     }\n     for ( vector<atom>::iterator i=a.begin(); i<a.end(); i++ ) {\n          ( *i ).updateVelocitiesVV ( dt );\n     }\n     double energy = solution::computeForces ( a,rc,box,vir );\n     for ( vector<atom>::iterator i=a.begin(); i<a.end(); i++ ) {\n          ( *i ).updateVelocitiesVV ( dt );\n          kin+= ( *i ).v2() * ( *i ).getMass();\n     }\n     kin=kin/2.0;\n     return energy;\n}\n\n\nvoid solution::MDDriverVV ( vector< atom >& a, generalInputs& in )\n{\n\n     double potEnergy, kinEnergy, vir,pressure;\n     potEnergy = PotentialEnergy ( a,in.cut,in.box, in.shift,vir );\n     kinEnergy = KineticEnergy ( a );\n     double iT,tT;\n     double consQ;\n     double rho=density ( a, in.box );\n     double volume = in.box*in.box*in.box;\n     pressure=rho* ( utils::Kb*in.TBath ) +vir/volume/3.0;\n     consQ=potEnergy+kinEnergy;\n     iT=2.0/3.0*kinEnergy/a.size() /utils::Kb;\n     tT=iT;\n     gutenberg::mdHeader ( cout,in.fancy );\n     gutenberg::mdRepLine ( 0.0,potEnergy/a.size(),kinEnergy/a.size(),iT,tT,pressure,consQ/a.size(),VCM ( a ),in.fancy,cout );\n     gutenberg::printXYZ ( in.xyz,in.name,a,true );\n     gutenberg::printAtoms ( a,in.debug );\n     vector<double> avg ( 2 );\n     int nsamp=0;\n     for ( int k=0; k<avg.size(); k++ ) avg[k]=0.0;\n     for ( int i=1; i<=in.nSteps; i++ ) {\n          potEnergy = solution::velocityVerlet ( a,in.cut,in.box,in.dt,kinEnergy,vir );\n\n          iT=2.0/3.0*kinEnergy/a.size() /utils::Kb;\n          tT+= ( iT-tT ) / ( i+1.0 );\n\n          if ( i%in.frequency==0 ) {\n               gutenberg::printForces ( a,in.log );\n               gutenberg::printXYZ ( in.xyz,in.name,a,true );\n               gutenberg::printAtoms ( a,in.debug );\n          }\n          consQ=potEnergy+kinEnergy;\n          avg[0]+=consQ;\n          avg[1]+=consQ*consQ;\n          nsamp++;\n          pressure=rho* ( utils::Kb*in.TBath ) +vir/volume/3.0;\n          gutenberg::mdRepLine ( i*in.dt,potEnergy/a.size(),kinEnergy/a.size(),iT,tT,pressure,consQ/a.size(),VCM ( a ),in.fancy,cout );\n     }\n     for ( int k=0; k<avg.size(); k++ ) avg[k]=avg[k]/nsamp;\n     utils::Print ( \"CV:\",cout,red );\n     utils::Print ( ( avg[1]-avg[0]*avg[0] ) /utils::Kb/tT/tT,cout, green );\n     cout<<endl;\n\n}\n\ndouble solution::VECIntegrator ( vector< atom >& a, const double&rc , const double& box , const double& dt, const double& s1, const double& s2, double& kin, double& vir )\n{\n\n     kin=0.0;\n     vir = 0.0;\n     for ( vector<atom>::iterator i=a.begin(); i<a.end(); i++ ) {\n          ( *i ).updateVelocitiesVEC ( dt,s2 );\n     }\n\n     for ( vector<atom>::iterator i=a.begin(); i<a.end(); i++ ) {\n          ( *i ).updatePositionsVEC ( dt,s1 );\n     }\n     double energy = solution::computeForces ( a,rc,box, vir );\n     for ( vector<atom>::iterator i=a.begin(); i<a.end(); i++ ) {\n          ( *i ).updateVelocitiesVEC ( dt,s2 );\n          kin+= ( *i ).v2() * ( *i ).getMass();\n     }\n     kin=kin/2.0;\n     return energy;\n}\n\nvoid solution::MDDriverVEC ( vector< atom >& a, generalInputs & in )\n{\n     //set the random generators...\n     boost::mt19937 igen ( in.seeds[0] );\n     boost::variate_generator<boost::mt19937, boost::normal_distribution<> >  xi ( igen, boost::normal_distribution<> ( 0.0,1.0 ) );\n     vector<double> b ( 6 );\n     double potEnergy, kinEnergy, vir;\n\n\n     potEnergy = PotentialEnergy ( a,in.cut,in.box,in.shift,vir );\n     kinEnergy = KineticEnergy ( a );\n\n     double iT,tT;\n     double consQ;\n     double rho=density ( a, in.box );\n     double volume = in.box*in.box*in.box;\n     double pressure=rho* ( utils::Kb*in.TBath ) +vir/volume/3.0;\n     gutenberg::logLine ( \"Volume: \",volume,in.log );\n     gutenberg::logLine ( \"Density: \",rho,in.log );\n     consQ=potEnergy+kinEnergy;\n     iT=2.0/3.0*kinEnergy/a.size() /utils::Kb;\n     tT=iT;\n     gutenberg::mdHeader ( cout,in.fancy );\n     gutenberg::mdRepLine ( 0.0,potEnergy/a.size(),kinEnergy/a.size(),iT,tT,pressure,consQ/a.size(),VCM ( a ),in.fancy,in.log );\n     gutenberg::printXYZ ( in.xyz,in.name,a,true );\n     gutenberg::printAtoms ( a,in.debug );\n\n     double s1=sqrt ( utils::Kb*in.TBath*in.dt/6.0 ) *in.dt;\n     double s2=sqrt ( 2.0*utils::Kb*in.TBath );\n     double v2=0.0;\n\n     vector<double> K,E,vx,vy,vz,P,v;\n//     K.push_back ( kinEnergy/a.size() );\n//     E.push_back ( consQ/a.size() );\n//     P.push_back ( potEnergy/a.size() );\n//     for ( vector<atom>::iterator it=a.begin(); it<a.end(); it++ ) {\n//         vx.push_back ( ( *it ).gvx() );\n//         vy.push_back ( ( *it ).gvy() );\n//         vz.push_back ( ( *it ).gvz() );\n//         v.push_back ( sqrt ( ( *it ).v2() ) );\n//         }\n     double aene=0.0, aene2=0.0,cv;\n     int nsamp=0;\n     for ( int i=1; i<=in.nSteps; i++ ) {\n          for ( vector<atom>::iterator it=a.begin(); it<a.end(); it++ ) {\n               b[0]=xi();\n               b[1]=xi();\n               b[2]=xi();\n               b[3]=xi();\n               b[4]=xi();\n               b[5]=xi();\n               ( *it ).setNoise ( b );\n          }\n          potEnergy = solution::VECIntegrator ( a,in.cut,in.box,in.dt,s1,s2,kinEnergy,vir );\n\n\n\n//         pressure=rho* ( utils::Kb*tT ) +vir/volume/3.0;\n          gutenberg::mdRepLine ( i*in.dt,potEnergy/a.size(),kinEnergy/a.size(),iT,tT,pressure,consQ/a.size(),VCM ( a ),in.fancy,in.log );\n\n          if ( i%in.frequency==0 )  {\n//             gutenberg::printForces ( a,in.log );\n//             gutenberg::printXYZ ( in.xyz,in.name,a,true );\n//             gutenberg::printAtoms ( a,in.debug );\n               iT=2.0*kinEnergy/ ( 3.0*a.size() *utils::Kb );\n\n               consQ=potEnergy+kinEnergy;\n               if ( i == in.nEquil ) {\n                    nsamp=0;\n                    E.erase ( E.begin(),E.end() );\n               }\n               if ( nsamp==0 ) {\n\n                    aene=consQ;\n                    tT=iT;\n                    nsamp=0;\n               } else {\n                    nsamp++;\n                    aene+= ( aene-consQ ) / ( nsamp+1.0 );\n                    tT+= ( iT-tT ) / ( nsamp+1.0 );\n               }\n               E.push_back ( consQ/a.size() );\n\n               cv= utils::sigma2 ( E ) / ( utils::Kb*tT*tT );\n               if ( i>in.nEquil ) {\n                    gutenberg::logInfo ( \"step \",i-in.nEquil,cout );\n\n               } else {\n                    gutenberg::logInfo ( \"step \",i,cout );\n               }\n               gutenberg::logInfo ( \"T \",tT,cout );\n               gutenberg::logInfo ( \"<E> \",aene,cout );\n               gutenberg::logLine ( \"Cv: \", cv*a.size(),cout );\n               gutenberg::logLine ( \"Cv/N: \", cv,cout );\n\n               if ( i>in.nEquil ) {\n\n                    P.push_back ( potEnergy/a.size() );\n                    for ( vector<atom>::iterator it=a.begin(); it<a.end(); it++ ) {\n                         vx.push_back ( ( *it ).gvx() );\n                         vy.push_back ( ( *it ).gvy() );\n                         vz.push_back ( ( *it ).gvz() );\n                         v2= ( *it ).v2();\n                         v.push_back ( sqrt ( v2 ) );\n                         K.push_back ( v2* ( *it ).getMass() /2.0 );\n                    }\n               }\n          }\n     }\n\n     cv=utils::sigma2 ( E );\n     utils::Print ( \"CV:\",cout,red );\n     utils::Print ( cv/ ( utils::Kb*tT*tT ) *a.size(),cout, green );\n     cout<<endl;\n     utils::Print ( \"sigma^2 K\",cout, red );\n     utils::Print ( utils::sigma2 ( K ),cout,green );\n     cout<<endl;\n     utils::Print ( \"sigma^2 E\",cout, red );\n     utils::Print ( cv,cout,green );\n     cout<<endl;\n     solution::histogramWrapper ( K,in.bin,\"Kvec.hist\" );\n     solution::histogramWrapper ( E,in.bin,\"Evec.hist\" );\n     solution::histogramWrapper ( P,in.bin,\"Pvec.hist\" );\n     solution::histogramWrapper ( vx,in.bin,\"vxvec.hist\" );\n     solution::histogramWrapper ( vy,in.bin,\"vyvec.hist\" );\n     solution::histogramWrapper ( vz,in.bin,\"vzvec.hist\" );\n     solution::histogramWrapper ( v,in.bin,\"vvec.hist\" );\n}\n\ndouble solution::computeForcesTAMD ( vector< atom >& a, vector<colVar>& cv,const double & rc, const double& box, double& vir )\n{\n     for ( vector<atom>::iterator it=a.begin(); it<a.end(); it++ ) {\n          ( *it ).setForces ( 0.0,0.0,0.0 );\n     }\n\n     double R,fR,fx,fy,fz,energy;\n     vector<double> dR ( 3 );\n     double ec=utils::LennardJones ( rc );\n     int k=0;\n     energy=0.0;\n     for ( vector<colVar>::iterator i=cv.begin(); i<cv.end(); i++ ) {\n          ( *i ).force ( a,box );\n     }\n     for ( vector<atom>::iterator i=a.begin(); i<a.end(); i++ ) {\n          fx=0.0;\n          fy=0.0;\n          fz=0.0;\n          for ( vector<colVar>::iterator it=cv.begin(); it<cv.end(); it++ ) {\n               ( *it ).dtheta ( dR,k,a,box );\n               fx=fx+ ( *it ).f*dR[0];\n               fy=fy+ ( *it ).f*dR[1];\n               fz=fz+ ( *it ).f*dR[2];\n          }\n          k++;\n          ( *i ).addtoForces ( -fx,-fy,-fz );\n          for ( vector<atom>::iterator j=i+1; j<a.end(); j++ ) {\n               R=rdr ( dR,*i,*j,box );\n               if ( R<rc ) {\n                    fR=utils::LennardJonesdR ( R );\n                    fx=-fR*dR[0]/R;\n                    fy=-fR*dR[1]/R;\n                    fz=-fR*dR[2]/R;\n                    ( *i ).addtoForces ( fx,fy,fz );\n                    ( *j ).addtoForces ( -fx,-fy,-fz );\n                    energy+=utils::LennardJones ( R )-ec;\n                    vir+=fR*R;\n               }\n          }\n     }\n     return energy;\n}\n\ndouble solution::TAMDIntegrator ( vector< atom >& a, vector<colVar>&cv, const double&rc , const double& box , const double& dt, const double& s1,const double& c1, const double& s2, double& kin, double&kinz, double&vir )\n{\n\n     kin=0.0;\n     kinz=0.0;\n     vir =0.0;\n\n     for ( vector<atom>::iterator i=a.begin(); i<a.end(); i++ ) {\n          ( *i ).updateVelocitiesVEC ( dt,s2 );\n     }\n     for ( vector<colVar>::iterator i=cv.begin(); i<cv.end(); i++ ) {\n          ( *i ).updatezvVEC ( dt );\n     }\n\n     for ( vector<atom>::iterator i=a.begin(); i<a.end(); i++ ) {\n          ( *i ).updatePositionsVEC ( dt,s1 );\n     }\n     for ( vector<colVar>::iterator i=cv.begin(); i<cv.end(); i++ ) {\n          ( *i ).updatezpVEC ( dt,c1 );\n     }\n     double energy = solution::computeForcesTAMD ( a,cv,rc,box, vir );\n     for ( vector<atom>::iterator i=a.begin(); i<a.end(); i++ ) {\n          ( *i ).updateVelocitiesVEC ( dt,s2 );\n          kin+= ( *i ).v2() * ( *i ).getMass();\n     }\n\n     for ( vector<colVar>::iterator i=cv.begin(); i<cv.end(); i++ ) {\n          ( *i ).updatezvVEC ( dt );\n          kinz+= ( *i ).v* ( *i ).v* ( *i ).mu;\n     }\n\n     kin=kin/2,0;\n     kinz=kinz/2.0;\n     return energy;\n}\n\n///\n///  @brief the driver for TAMD\n///  @details http://dx.doi.org/10.1016/j.cplett.2006.05.062\n///   it uses the VEC integrator for EOM\n///  @param a a vector of atoms\n///  @param cv the vector of collective variables\n///  @param in contains the input parameters\n///\nvoid solution::MDDriverTAMD ( vector< atom >& a, vector<colVar>& cv, generalInputs & in )\n{\n     //set the random generators...\n\n     boost::mt19937 igen ( in.seeds[0] );\n     boost::variate_generator<boost::mt19937, boost::normal_distribution<> >  xi ( igen, boost::normal_distribution<> ( 0.0,1.0 ) );\n     vector<double> b ( 6 );\n     double potEnergy, kinEnergy, vir;\n\n     potEnergy = PotentialEnergy ( a,in.cut,in.box,in.shift,vir );\n     kinEnergy = KineticEnergy ( a );\n\n     double iT,tT;\n     double iTz,tTz;\n     double consQ;\n     double rho=density ( a, in.box );\n     double volume = in.box*in.box*in.box;\n     double pressure=rho* ( utils::Kb*in.TBath ) +vir/volume/3.0;\n\n     consQ=potEnergy+kinEnergy;\n     iT=2.0*kinEnergy/ ( 3.0*a.size() *utils::Kb );\n     tT=iT;\n     iTz=0.0;\n     tTz=iTz;\n     double kinz=0.0;\n     gutenberg::mdTAMDHeader ( cv,cout,in.fancy );\n     gutenberg::mdTAMDRepLine ( 0.0,potEnergy/a.size(),kinEnergy/a.size(),tT,tTz,pressure,kinz/cv.size(),consQ/a.size(),VCM ( a ),cv,in.fancy,cout );\n     gutenberg::printXYZ ( in.xyz,in.name,a,true );\n     gutenberg::printAtoms ( a,in.debug );\n\n     double s1=sqrt ( utils::Kb*in.TBath*in.dt/6.0 ) *in.dt;\n     double c1=sqrt ( utils::Kb*in.Tcv*in.dt/6.0 ) *in.dt;\n     double s2=sqrt ( 2.0*utils::Kb*in.TBath );\n\n     vector<double> KX,KZ,vxX,vyX,vyZ,vX,vzX,vZ;\n     double v2;\n     for ( vector<colVar>::iterator it=cv.begin(); it<cv.end(); it++ ) {\n          ( *it ).s=sqrt ( 2.0*utils::Kb*in.Tcv* ( *it ).gamma/ ( *it ).mu );\n     }\n     for ( int i=1; i<=in.nSteps; i++ ) {\n          for ( vector<atom>::iterator it=a.begin(); it<a.end(); it++ ) {\n               b[0]=xi();\n               b[1]=xi();\n               b[2]=xi();\n               b[3]=xi();\n               b[4]=xi();\n               b[5]=xi();\n               ( *it ).setNoise ( b );\n          }\n          for ( vector<colVar>::iterator it=cv.begin(); it<cv.end(); it++ ) {\n               b[0]=xi();\n               b[1]=xi();\n               ( *it ).setNoise ( b );\n          }\n          potEnergy = solution::TAMDIntegrator ( a,cv,in.cut,in.box,in.dt,s1,c1,s2,kinEnergy, kinz,vir );\n\n          iT=2.0*kinEnergy/ ( 3.0*a.size() *utils::Kb );\n          tT+= ( iT-tT ) / ( i+1.0 );\n\n          iTz=2.0*kinz/ ( cv.size() *utils::Kb );\n          tTz+= ( iTz-tTz ) / ( i+1.0 );\n          if ( i%in.frequency==0 && i>in.nEquil ) {\n               gutenberg::printForces ( a,in.log );\n               gutenberg::printXYZ ( in.xyz,in.name,a,true );\n               gutenberg::printAtoms ( a,in.debug );\n               for ( vector<atom>::iterator it=a.begin(); it<a.end(); it++ ) {\n                    vxX.push_back ( ( *it ).gvx() );\n                    vyX.push_back ( ( *it ).gvy() );\n                    vzX.push_back ( ( *it ).gvz() );\n                    v2= ( *it ).v2();\n                    vX.push_back ( sqrt ( v2 ) );\n                    KX.push_back ( v2* ( *it ).getMass() /2.0 );\n               }\n               for ( vector<colVar>::iterator it=cv.begin(); it<cv.end(); it++ ) {\n                    vZ.push_back ( ( *it ).v );\n                    KZ.push_back ( ( *it ).mu* ( *it ).v* ( *it ).v/2.0 );\n               }\n          }\n          consQ=potEnergy+kinEnergy;\n          pressure=rho* ( utils::Kb*in.TBath ) +vir/volume/3.0;\n          gutenberg::mdTAMDRepLine ( i*in.dt,potEnergy/a.size(),kinEnergy/a.size(),tT,tTz,pressure,kinz/cv.size(),consQ/a.size(),VCM ( a ),cv,in.fancy,cout );\n     }\n     solution::histogramWrapper ( vxX,in.bin,\"vxX.hist\" );\n     solution::histogramWrapper ( vyX,in.bin,\"vyX.hist\" );\n     solution::histogramWrapper ( vzX,in.bin,\"vzX.hist\" );\n     solution::histogramWrapper ( vX,in.bin,\"vX.hist\" );\n     solution::histogramWrapper ( KX,in.bin,\"KX.hist\" );\n     solution::histogramWrapper ( vZ,in.bin,\"vZ.hist\" );\n     solution::histogramWrapper ( KZ,in.bin,\"KZ.hist\" );\n}\n\n\nvoid solution::optimalDr ( double& d , int& otry, int& ogood, const int& itry, const int& igood, const double& box )\n{\n     if ( itry!=otry ) {\n          double f= ( double ) ( igood-ogood ) / ( double ) ( itry-otry );\n          double od=d;\n          d=d*f/0.5; //0.5 is the target accteptance ratio;\n          if ( d/od>1.5 ) d=od*1.5;\n          if ( d/od<0.5 ) d=od*0.5;\n          if ( d>box/2 ) d=box/2;\n          otry=itry;\n          ogood=igood;\n     }\n\n}\n\n\n///\n///  @brief the driver for a metropolis montecarlo simulation\n///  @param a a vector of atoms\n///  @param in contains the input parameters\n///\nvoid solution::MMCDriver ( vector< atom >& a, generalInputs& in )\n{\n     boost::mt19937 igen ( in.seeds[0] );\n     boost::uniform_01<boost::mt19937> rn ( igen );\n\n     double ei,ef;\n     int rAtom;\n     double rx,ry,rz;\n\n     int itry=0;\n     int igood=0;\n     int otry, ogood;\n     otry=itry;\n     ogood=igood;\n     int nsamp=0;\n     double fact;\n     double et,vt;\n     double aene=0.0, ap=0.0,aene2=0.0;\n     double rho=density ( a,in.box );\n     double volume=in.box*in.box*in.box;\n     double vir, viri,virf;\n     double etot=PotentialEnergy ( a,in.cut,in.box,in.shift,vir );\n     gutenberg::logLine ( \"Volume: \",volume,in.log );\n     gutenberg::logLine ( \"Density: \",rho,in.log );\n     utils::Print ( etot,cout,32,16 );\n     cout<<endl;\n\n     vector<double>ene;\n\n     double pressure;\n     int cycles;\n     int startsamp;\n     pressure=rho* ( utils::Kb*in.TBath ) +vir/volume/3.0;\n     gutenberg::MMCHeader ( cout, in.fancy );\n     gutenberg::MMCRepLine ( 0,etot/a.size(),pressure,in.fancy,cout );\n     gutenberg::logLine ( \"Initial etot \", etot,cout );\n     gutenberg::logLine ( \"Initial etot/N \", etot/a.size(),cout );\n     gutenberg::logLine ( \"Initial virial \", vir,cout );\n     solution::optimalDr ( in.dr,otry,ogood,itry,igood,in.box );\n     for ( int stage=0; stage<2; stage++ ) {\n          if ( stage==0 ) {\n               cycles=in.nEquil;\n               startsamp=cycles/10;\n               utils::Print ( \"Equilibration stage:\", cout, blue );\n               cout<<endl;\n          } else {\n               startsamp=0;\n               cycles=in.mccycles;\n               utils::Print ( \"Production stage:\", cout, blue );\n               cout <<endl;\n               etot=PotentialEnergy ( a,in.cut,in.box,in.shift,vir );\n               ene.push_back ( etot/a.size() );\n               gutenberg::MMCHeader ( cout, in.fancy );\n               gutenberg::MMCRepLine ( 0,etot/a.size(),pressure,in.fancy,cout );\n          }\n          gutenberg::logInfo ( \"old dr:\",in.dr,cout );\n          solution::optimalDr ( in.dr,otry,ogood,itry,igood,in.box );\n          gutenberg::logLine ( \"new dr:\",in.dr,cout );\n          itry=0;\n          igood=0;\n          aene=0.0;\n          aene2=0.0;\n          ap=0.0;\n          nsamp=0;\n          for ( int i=0; i<cycles; i++ ) {\n               // one should compute the optimal dr here...\n               for ( int j=0; j<in.mcsteps; j++ ) {\n                    itry++;\n                    rAtom=int ( rn() *a.size() );\n                    ei=a[rAtom].myPotentialEnergy ( a,in.cut,in.box,in.shift,viri );\n                    a[rAtom].saveOldPositions ( rx,ry,rz );\n                    a[rAtom].randomMove ( in.dr,rn(),rn(),rn() );\n                    ef=a[rAtom].myPotentialEnergy ( a,in.cut,in.box,in.shift,virf );\n                    fact=- ( ef-ei ) / ( utils::Kb*in.TBath );\n                    if ( rn() <exp ( fact ) ) {\n                         igood++;\n                         etot=etot+ef-ei;\n                         vir=vir+virf-viri;\n                         a[rAtom].putInBox ( in.box );\n                    } else { //if rejected\n                         a[rAtom].setPositions ( rx,ry,rz );\n                    }\n               }\n               if ( ( ( i+1 ) %in.frequency==0 ) && ( i+1>startsamp ) ) {\n                    //sampling point...\n                    pressure=rho* ( utils::Kb*in.TBath ) +vir/volume/3.0;\n                    gutenberg::MMCRepLine ( ( i+1 ) *in.mcsteps,etot/a.size(),pressure,in.fancy,in.log );\n//                 gutenberg::printXYZ ( in.xyz,in.name,a,true );\n                    ene.push_back ( etot/a.size() );\n                    aene+=etot;\n                    aene2+=etot*etot;\n                    ap+=pressure;\n                    nsamp++;\n\n                    gutenberg::logInfo ( \"|cycle: \",i+1,in.log );\n                    gutenberg::logInfo ( \"|attempts: \",itry, in.log );\n                    gutenberg::logInfo ( \"|accepted: \",igood, in.log );\n                    gutenberg::logLine ( \"|ratio\", ( double ) ( igood ) / ( double ) ( itry ),in.log );\n               }\n               if ( ( i+1 ) % ( cycles/5 ) ==0 ) {\n                    gutenberg::logInfo ( \"|cycle: \",i+1,cout );\n                    gutenberg::logInfo ( \"|attempts: \",itry-otry, cout );\n                    gutenberg::logInfo ( \"|accepted: \",igood-ogood, cout );\n                    gutenberg::logLine ( \"|ratio\", ( double ) ( igood-ogood ) / ( double ) ( itry-otry ),cout );\n                    gutenberg::logInfo ( \"old dr:\",in.dr,cout );\n                    solution::optimalDr ( in.dr,otry,ogood,itry,igood,in.box );\n                    gutenberg::logInfo ( \"new dr:\",in.dr,cout );\n                    cout<<endl;\n               }\n\n          }\n          gutenberg::logLine ( \"Etot: \",etot,cout );\n          gutenberg::logLine ( \"Erot/N\",etot/a.size(),cout );\n          pressure=rho* ( utils::Kb*in.TBath ) +vir/volume/3.0;\n          gutenberg::logLine ( \"virial: \",vir,cout );\n          gutenberg::logLine ( \"pressure: \",pressure,cout );\n          et=PotentialEnergy ( a,in.cut,in.box,in.shift,vt );\n          gutenberg::logLine ( \"diff energy: \",et-etot,cout );\n          gutenberg::logLine ( \"diff virial: \", vt-vir,cout );\n          gutenberg::logInfo ( \"|cycle: \",cycles,cout );\n          gutenberg::logInfo ( \"|attempts: \",itry, cout );\n          gutenberg::logInfo ( \"|accepted: \",igood, cout );\n          gutenberg::logLine ( \"|ratio\", ( double ) ( igood ) / ( double ) ( itry ),cout );\n          aene2=aene2/nsamp;\n          aene=aene/nsamp;\n          gutenberg::logLine ( \"Avg energy:\", aene,cout );\n          gutenberg::logLine ( \"Avg energy/N:\", aene/a.size(),cout );\n          gutenberg::logLine ( \"Avg pressure:\", ap/nsamp,cout );\n          gutenberg::logLine ( \"CV: \",1.5*utils::Kb*a.size() + ( aene2-aene*aene ) / ( utils::Kb*in.TBath*in.TBath ),cout );\n     }\n\n     solution::histogramWrapper ( ene,in.bin,\"Pmmc.hist\" );\n\n}\n\n\n\n///\n///  @brief the driver for TAMC\n///  @details TAMC paper\n///   it uses the VEC integrator for EOM\n///  @param a a vector of atoms\n///  @param cv the vector of collective variables\n///  @param in contains the input parameters\n///\nvoid solution::MDDriverTAMC ( vector< atom >& a, vector<colVar>& cv, generalInputs & in )\n{\n     //set the random generators...\n\n     boost::mt19937 igen ( in.seeds[0] );\n     boost::variate_generator<boost::mt19937, boost::normal_distribution<> >  xi ( igen, boost::normal_distribution<> ( 0.0,1.0 ) );\n     boost::uniform_01<boost::mt19937> rn ( igen );\n     vector<double> b ( 2 );\n     double potEnergy, vir,fact,etot;\n\n     potEnergy = PotentialEnergy ( a,in.cut,in.box,in.shift,vir ) +zpot ( a,cv,in.box );\n\n     double iT=0.0,tT=0.0;\n     double consQ,kin;\n     double rho=density ( a, in.box );\n     double volume = in.box*in.box*in.box;\n     double pressure=rho* ( utils::Kb*in.TBath ) +vir/volume/3.0;\n\n     int itry=0, otry=0,igood=0, ogood=0;\n     double ei,ef, viri,virf;\n     int rAtom;\n     double rx,ry,rz;\n     double kinz=0.0;\n\n     gutenberg::mdTAMCHeader ( cv,cout,in.fancy );\n     gutenberg::mdTAMCRepLine ( 0.0,potEnergy/a.size(),tT,pressure,kinz,cv,in.fancy,cout );\n     gutenberg::printXYZ ( in.xyz,in.name,a,true );\n\n     double c1=sqrt ( utils::Kb*in.Tcv*in.dt/6.0 ) *in.dt;\n\n\n     double aene=0.0, ap=0.0;\n     int nsamp=0;\n     vector<double> avgfz ( cv.size() ), KZ,vZ;\n     for ( vector<colVar>::iterator it=cv.begin(); it<cv.end(); it++ ) {\n          ( *it ).s=sqrt ( 2.0*utils::Kb*in.Tcv* ( *it ).gamma/ ( *it ).mu );\n     }\n     for ( int step=1; step<=in.nSteps; step++ ) {\n          for ( vector<colVar>::iterator it=cv.begin(); it<cv.end(); it++ ) {\n               b[0]=xi();\n               b[1]=xi();\n               ( *it ).setNoise ( b );\n          }\n          vir =0.0;\n          aene=0.0;\n          ap=0.0;\n          for ( int k=0; k<cv.size(); k++ ) avgfz[k]=0.0;\n          for ( vector<colVar>::iterator i=cv.begin(); i<cv.end(); i++ ) {\n               ( *i ).updatezvVEC ( in.dt );\n          }\n          for ( vector<colVar>::iterator i=cv.begin(); i<cv.end(); i++ ) {\n               ( *i ).updatezpVEC ( in.dt,c1 );\n          }\n          //steps MC\n\n          for ( int i=0; i<in.mccycles; i++ ) {\n               for ( int j=0; j<in.mcsteps; j++ ) {\n                    itry++;\n                    rAtom=int ( rn() *a.size() );\n                    ei=a[rAtom].myPotentialEnergy ( a,in.cut,in.box,in.shift,viri ) +zpot ( a,cv,in.box );\n                    a[rAtom].saveOldPositions ( rx,ry,rz );\n                    a[rAtom].randomMove ( in.dr,rn(),rn(),rn() );\n                    a[rAtom].putInBox ( in.box );\n                    ef=a[rAtom].myPotentialEnergy ( a,in.cut,in.box,in.shift,virf ) +zpot ( a,cv,in.box );\n                    fact=- ( ef-ei ) / ( utils::Kb*in.TBath );\n                    if ( rn() <exp ( fact ) ) {\n                         igood++;\n                         etot=etot+ef-ei;\n                         vir=vir+virf-viri;\n                    } else { //if rejected\n                         a[rAtom].setPositions ( rx,ry,rz );\n                    }\n               }\n               //sampling point...\n\n               pressure=rho* ( utils::Kb*in.TBath ) +vir/volume/3.0;\n               aene+=etot/a.size();\n               ap+=pressure;\n               nsamp++;\n               for ( int k=0; k<cv.size(); k++ ) {\n                    cv[k].force ( a,in.box );\n                    avgfz[k]+=cv[k].f;\n               }\n               solution::optimalDr ( in.dr,otry,ogood,itry,igood,in.box );\n          }\n          for ( int k=0; k<cv.size(); k++ ) {\n               cv[k].f=avgfz[k]/nsamp;\n          }\n          for ( vector<colVar>::iterator i=cv.begin(); i<cv.end(); i++ ) {\n               ( *i ).updatezvVEC ( in.dt );\n          }\n\n          if ( step%in.frequency==0 ) {\n               gutenberg::printXYZ ( in.xyz,in.name,a,true );\n          }\n          kinz=zKin ( cv );\n\n          iT=2.0*kinz/ ( cv.size() *utils::Kb );\n          if ( step>=in.nEquil ) {\n               tT+= ( iT-tT ) / ( step-in.nEquil+1.0 );\n               if ( step%in.frequency==0 ) {\n                    for ( vector<colVar>::iterator it=cv.begin(); it<cv.end(); it++ ) {\n                         vZ.push_back ( ( *it ).v );\n                         KZ.push_back ( ( *it ).mu* ( *it ).v* ( *it ).v/2.0 );\n                    }\n               }\n          }\n          gutenberg::mdTAMCRepLine ( step*in.dt,aene/nsamp,tT,pressure/nsamp,kinz,cv,in.fancy,cout );\n          nsamp=0;\n     }\n\n     solution::histogramWrapper ( vZ,in.bin,\"vZtdmc.hist\" );\n     solution::histogramWrapper ( KZ,in.bin,\"KZtdmc.hist\" );\n\n}\n\n\n///\n///  @brief the driver for TAHMC\n///  @details TAMC paper and HMC paper\n///   it uses the VEC integrator for EOM and velocity verlet for atoms\n///  @param a a vector of atoms\n///  @param cv the vector of collective variables\n///  @param in contains the input parameters\n///\nvoid solution::MDDriverTAHMC ( vector< atom >& a, vector<colVar>& cv, generalInputs & in )\n{\n     //set the random generators...\n\n     boost::mt19937 igen ( in.seeds[0] );\n     boost::variate_generator<boost::mt19937, boost::normal_distribution<> >  xi ( igen, boost::normal_distribution<> ( 0.0,1.0 ) );\n     boost::uniform_01<boost::mt19937> rn ( igen );\n     vector<double> b ( 2 );\n     double aPot, vir,fact,etot;\n     double etoti,etotf;\n\n     aPot = PotentialEnergy ( a,in.cut,in.box,in.shift,vir ) + zpot ( a,cv,in.box );\n\n     double iT=0.0,tT=0.0;\n     double consQ,kin;\n     double rho=density ( a, in.box );\n     double volume = in.box*in.box*in.box;\n     double pressure=rho* ( utils::Kb*in.TBath ) +vir/volume/3.0;\n\n     int itry=0, otry=0,igood=0, ogood=0;\n     double zpoti,zpotf, viri,virf;\n     int irseed;\n\n     double kinz=0.0;\n     double kini,kinf;\n     vector<double> pos ( 3* a.size() );\n     cout << pos.size() <<\" \"<<a.size() <<endl;\n     for ( int i=0; i<a.size(); i++ ) {\n          a[i].saveOldPositions ( pos[3*i],pos[3*i+1],pos[3*i+2] );\n     }\n     gutenberg::mdTAMCHeader ( cv,cout,in.fancy );\n     gutenberg::mdTAMCRepLine ( 0.0,aPot/a.size(),tT,pressure,kinz,cv,in.fancy,cout );\n     gutenberg::printXYZ ( in.xyz,in.name,a,true );\n\n     double c1=sqrt ( utils::Kb*in.Tcv*in.dtz/6.0 ) *in.dt;\n\n\n     double aene=0.0, ap=0.0,acc;\n     int nsamp;\n     vector<double> avgfz ( cv.size() ), KZ,vZ;\n     irseed=rn();\n     solution::zHMCSampler ( a, cv, in, irseed,pos, avgfz );\n     for ( vector<colVar>::iterator it=cv.begin(); it<cv.end(); it++ ) {\n          ( *it ).s=sqrt ( 2.0*utils::Kb*in.Tcv* ( *it ).gamma/ ( *it ).mu );\n     }\n     for ( int step=1; step<=in.Nz; step++ ) {\n          for ( vector<colVar>::iterator it=cv.begin(); it<cv.end(); it++ ) {\n               b[0]=xi();\n               b[1]=xi();\n               ( *it ).setNoise ( b );\n          }\n          for ( vector<colVar>::iterator i=cv.begin(); i<cv.end(); i++ ) {\n               ( *i ).updatezvVEC ( in.dtz );\n          }\n          for ( vector<colVar>::iterator i=cv.begin(); i<cv.end(); i++ ) {\n               ( *i ).updatezpVEC ( in.dtz,c1 );\n          }\n          //steps HMC\n          irseed=rn();\n          solution::zHMCSampler ( a, cv, in, irseed,pos, avgfz );\n//         solution::zSample\n\n\n          for ( vector<colVar>::iterator i=cv.begin(); i<cv.end(); i++ ) {\n               ( *i ).updatezvVEC ( in.dtz );\n          }\n          if ( step%in.frequency==0 ) {\n               gutenberg::printXYZ ( in.xyz,in.name,a,true );\n          }\n          kinz=zKin ( cv );\n\n          iT=2.0*kinz/ ( cv.size() *utils::Kb );\n\n          tT+= ( iT-tT ) / ( step+1.0 );\n          if ( step%in.frequency==0 ) {\n               for ( vector<colVar>::iterator it=cv.begin(); it<cv.end(); it++ ) {\n                    vZ.push_back ( ( *it ).v );\n                    KZ.push_back ( ( *it ).mu* ( *it ).v* ( *it ).v/2.0 );\n               }\n          }\n\n          gutenberg::mdTAMCRepLine ( step*in.dt,aene/nsamp,tT,pressure/nsamp,kinz,cv,in.fancy,cout );\n          nsamp=0;\n     }\n\n//     solution::histogramWrapper ( vZ,in.bin,\"vZtdmc.hist\" );\n//     solution::histogramWrapper ( KZ,in.bin,\"KZtdmc.hist\" );\n\n}\n\n\nvoid solution::zHMCSampler ( vector< atom >& a, vector<colVar>& cv, generalInputs & in, const int& irseed,\n                             vector<double>& pos, vector<double>& avgfz )\n{\n\n     boost::mt19937 igen ( irseed );\n     boost::uniform_01<boost::mt19937> rn ( igen );\n\n     double epoti,epotf,zpoti,zpotf,kini,kinf;\n     int igood,iseed,nsamp;\n     double aHg,aH,dHg,fact,vir,acc;\n\n     aHg=0.0;\n     aH=0.0;\n     nsamp=0;\n     for ( int k=0; k<cv.size(); k++ ) avgfz[k]=0.0;\n     epoti=PotentialEnergy ( a,in.cut,in.box,in.shift,vir );\n     zpoti=zpot ( a,cv,in.box );\n     igood=0;\n     for ( int i=0; i<in.mccycles; i++ ) {\n          iseed=int ( rn() *10000 );\n          utils::Print ( \"Start Mini-Trajectory \",cout,colours::green );\n          utils::Print ( i,cout,colours::green );\n          cout <<endl;\n\n          solution::RandomVelocities ( a, in.TBath, in.box,iseed );\n          kini=KineticEnergy ( a );\n          solution::MDDriverVV ( a,in );\n          epotf=PotentialEnergy ( a,in.cut,in.box,in.shift,vir );\n          zpotf=zpot ( a,cv,in.box );\n          kinf=KineticEnergy ( a );\n          fact=- ( epotf-epoti+zpotf-zpoti+kinf-kini ) / ( utils::Kb*in.TBath );\n          dHg=- ( epotf-epoti+kinf-kini ) / ( utils::Kb*in.TBath );\n          if ( rn() <exp ( fact ) ) {\n               igood++;\n               epoti=epotf;\n               zpoti=zpotf;\n               for ( int j=0; j<a.size(); j++ ) {\n                    a[j].saveOldPositions ( pos[3*j],pos[3*j+1],pos[3*j+2] );\n               }\n          } else { //if rejected\n               for ( int j=0; j<a.size(); j++ ) {\n                    a[j].setPositions ( pos[3*j],pos[3*j+1],pos[3*j+2] );\n               }\n          }\n          utils::Print ( \"End Mini-Trajectory \",cout,colours::green );\n          utils::Print ( i,cout,colours::green );\n          utils::Print ( fact,cout,colours::green );\n          cout <<endl;\n          if ( ( i%in.frequency==0 ) && ( i>=in.nEquil ) ) {\n               nsamp++;\n               for ( int k=0; k<cv.size(); k++ ) {\n                    cv[k].force ( a,in.box );\n                    avgfz[k]+=cv[k].f;\n               }\n               aHg+= ( exp ( dHg )-aHg ) / ( i-in.nEquil+1.0 );\n               aH+= ( exp ( fact )-aH ) / ( i-in.nEquil+1.0 );\n               utils::Print ( \"runing averages \",cout,colours::red );\n               utils::Print ( aHg,cout,colours::red );\n               utils::Print ( aH,cout,colours::red );\n               cout<<endl;\n          }\n     }\n     utils::Print ( \"runing averages \",cout,colours::red );\n     utils::Print ( aHg,cout,colours::red );\n     utils::Print ( aH,cout,colours::red );\n     acc= ( double ) igood/ ( double ) in.mccycles;\n     utils::Print ( \"acceptance \",cout,colours::green );\n     utils::Print ( acc,cout,colours::green );\n     cout <<endl;\n\n     for ( int k=0; k<cv.size(); k++ ) {\n          cv[k].f=avgfz[k]/nsamp;\n     }\n\n}\n\n\n\nvoid solution::histogramWrapper ( std::vector< double >& a, const double& bin, const string& filename )\n{\n\n     vector<double> aHist;\n     double amin;\n     utils::histogram ( a,bin,aHist,amin );\n     utils::NormaliseHistogram ( aHist,bin );\n     gutenberg::printHistogram ( aHist,amin,bin,filename );\n\n}\n\n\n\n\n// kate: indent-mode cstyle; indent-width 5; replace-tabs on; \n", "meta": {"hexsha": "4091308a5ffa706a01d948efd8eb5a52b3ed7dc7", "size": 39888, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "source/solution.cpp", "max_stars_repo_name": "alinelena/mdSMplay", "max_stars_repo_head_hexsha": "1a738bc80615b5e837ed615b519d85836c538dda", "max_stars_repo_licenses": ["MIT"], "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/solution.cpp", "max_issues_repo_name": "alinelena/mdSMplay", "max_issues_repo_head_hexsha": "1a738bc80615b5e837ed615b519d85836c538dda", "max_issues_repo_licenses": ["MIT"], "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/solution.cpp", "max_forks_repo_name": "alinelena/mdSMplay", "max_forks_repo_head_hexsha": "1a738bc80615b5e837ed615b519d85836c538dda", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-08-05T21:18:00.000Z", "max_forks_repo_forks_event_max_datetime": "2018-08-05T21:18:00.000Z", "avg_line_length": 37.0018552876, "max_line_length": 219, "alphanum_fraction": 0.5029081428, "num_tokens": 11908, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6859494421679929, "lm_q2_score": 0.49218813572079556, "lm_q1q2_score": 0.3376161771393841}}
{"text": "//\n// Created by Hamza El-Kebir on 6/18/21.\n//\n\n#ifndef LODESTAR_BUTCHERTABLEAU_HPP\n#define LODESTAR_BUTCHERTABLEAU_HPP\n\n#include <type_traits>\n#include <tuple>\n#include <array>\n#include <string>\n#include <string_view>\n#include <functional>\n#include \"Lodestar/aux/Indices.hpp\"\n#include \"Lodestar/aux/Conjunction.hpp\"\n#include <iostream>\n#include <Eigen/Dense>\n\nnamespace ls {\n    namespace primitives {\n        namespace detail {\n            /**\n             * @brief A Butcher tableau row.\n             *\n             * @details There exist two partial specializations for this type: one for a regular row, which includes\n             * a node and several Runge-Kutta coefficients (the exact number being depending on \\c (TStage + 1)); the\n             * other is a weight row, which only includes an array of \\c TStages for the weights.\n             *\n             * @tparam TScalarType Type of the scalar coefficients.\n             * @tparam TStages Number of stages in the integration scheme.\n             * @tparam TStage Index of the current stage.\n             * @tparam TIsWeights If true, the current row is a weight row.\n             */\n            template<typename TScalarType, size_t TStages, size_t TStage, bool TIsWeights>\n            struct ButcherRowImpl {\n            };\n\n            /**\n             * @brief Butcher tableau specialization for regular row.\n             *\n             * @sa ButcherRowImpl\n             *\n             * @tparam TScalarType Type of the scalar coefficients.\n             * @tparam TStages Number of stages in the integration scheme.\n             * @tparam TStage Index of the current stage.\n             */\n            template<typename TScalarType, size_t TStages, size_t TStage>\n            struct ButcherRowImpl<TScalarType, TStages, TStage, false> {\n                static_assert(TStage >= 0, \"Butcher tableau row number must be non-negative.\");\n                static_assert(TStage < (TStages - 1),\n                              \"Butcher tableau row number must be smaller than the number of stages minus one.\");\n\n                TScalarType node;\n                std::array<TScalarType, TStage + 1> rkCoefficients;\n            };\n\n            /**\n             * @brief Butcher tableau specialization for weight row.\n             *\n             * @sa ButcherRowImpl\n             *\n             * @tparam TScalarType Type of the scalar coefficients.\n             * @tparam TStages Number of stages in the integration scheme.\n             * @tparam TStage Index of the current stage.\n             */\n            template<typename TScalarType, size_t TStages, size_t TStage>\n            struct ButcherRowImpl<TScalarType, TStages, TStage, true> {\n                std::array<TScalarType, TStages> weights;\n            };\n        }\n\n        /**\n         * @brief Implements a compile-time structure for simple/extended Butcher tableaus.\n         *\n         * @details Explicit methods in the Runge-Kutta family of numerical integrators can be described by the\n         * following coefficient:\n         * <ul>\n         *      <li> Runge-Kutta coefficients \\c a_ij;\n         *      <li> Weights \\c b_i;\n         *      <li> Nodes \\c c_i.\n         * </ul>\n         *\n         *\n         * @tparam TStages Number of stages in the integration scheme.\n         * @tparam TExtended If true, an extended Butcher tableau is given.\n         * @tparam TScalarType Type of the scalar coefficients.\n         */\n        template<size_t TStages, bool TExtended = true, typename TScalarType = double>\n        class ButcherTableau {\n            static_assert(TStages > 1, \"Butcher tableau must have more than one stage.\");\n        };\n\n        template<size_t TStages, typename TScalarType>\n        class ButcherTableau<TStages, false, TScalarType> {\n        public:\n            static_assert(TStages > 1, \"Butcher tableau must have more than one stage.\");\n\n            static const size_t stages = TStages; //! Number of stages.\n            using type = TScalarType; //! Coefficient type.\n\n            /**\n             * @brief Alias template for \\c ButcherRow.\n             *\n             * @tparam TStage Index of the current stage.\n             * @tparam TIsWeights If true, the current row is a weight row.\n             */\n            template<size_t TStage, bool TIsWeights = (TStage >= (TStages - 1))>\n            using ButcherRow = detail::ButcherRowImpl<TScalarType, TStages, TStage, TIsWeights>;\n\n            /**\n             * @brief Returns the Runge-Kutta coefficient for the given row number and coefficient index.\n             *\n             * @tparam TRow Row number (related to stage number).\n             * @tparam TCoeffIdx Index of the Runge-Kutta coefficient.\n             *\n             * @return Runge-Kutta coefficient at (\\c TRow, \\c TCoeffIdx).\n             */\n            template<size_t TRow, size_t TCoeffIdx>\n            typename std::enable_if<(TRow < (TStages - 1)) && (TCoeffIdx < (TRow + 1)), TScalarType>::type\n            inline getCoefficient()\n            {\n                return std::get<TCoeffIdx>(std::get<TRow>(rows_).rkCoefficients);\n            }\n\n            /**\n             * @brief Degenerate Runge-Kutta coefficient getter.\n             *\n             * @tparam TRow Row number (related to stage number).\n             * @tparam TCoeffIdx Index of the Runge-Kutta coefficient.\n             *\n             * @return Runge-Kutta coefficient at (\\c TRow, \\c TCoeffIdx).\n             */\n            template<size_t TRow, size_t TCoeffIdx>\n            typename std::enable_if<!((TRow < (TStages - 1)) && (TCoeffIdx < (TRow + 1))), TScalarType>::type\n            inline getCoefficient()\n            {\n                static_assert(TRow < (TStages - 1),\n                              \"Row index must be smaller than the number of stages minus one to access coefficients.\");\n                static_assert(TCoeffIdx < (TRow + 1), \"Coefficient index must be less than or equal to the row index.\");\n\n                return TScalarType{};\n            }\n\n            /**\n             * @brief Sets the Runge-Kutta coefficient at the given row number and coefficient index.\n             *\n             * @tparam TRow Row number (related to stage number).\n             * @tparam TCoeffIdx Index of the Runge-Kutta coefficient.\n             *\n             * @param coeff Coefficient value to be set.\n             */\n            template<size_t TRow, size_t TCoeffIdx>\n            typename std::enable_if<(TRow < (TStages - 1)) && (TCoeffIdx < (TRow + 1)), void>::type\n            inline setCoefficient(TScalarType coeff)\n            {\n                std::get<TCoeffIdx>(std::get<TRow>(rows_).rkCoefficients) = coeff;\n            }\n\n            /**\n             * @brief Degenerate Runge-Kutta coefficient setter.\n             *\n             * @tparam TRow Row number (related to stage number).\n             * @tparam TCoeffIdx Index of the Runge-Kutta coefficient.\n             *\n             * @param coeff Coefficient value to be set.\n             */\n            template<size_t TRow, size_t TCoeffIdx>\n            typename std::enable_if<!((TRow < (TStages - 1)) && (TCoeffIdx < (TRow + 1))), void>::type\n            inline setCoefficient(TScalarType coeff)\n            {\n                static_assert(TRow < (TStages - 1),\n                              \"Row index must be smaller than the number of stages minus one to access coefficients.\");\n                static_assert(TCoeffIdx < (TRow + 1), \"Coefficient index must be less than or equal to the row index.\");\n            }\n\n            /**\n             * @brief Returns the node value for the given row number.\n             *\n             * @tparam TRow Row number (related to stage number).\n             *\n             * @return Node value of \\c TRow.\n             */\n            template<size_t TRow>\n            typename std::enable_if<TRow < (TStages - 1), TScalarType>::type\n            inline getNode()\n            {\n                return std::get<TRow>(rows_).node;\n            }\n\n            /**\n             * @brief Degenerate node getter.\n             *\n             * @tparam TRow Row number (related to stage number).\n             *\n             * @return Node value of \\c TRow.\n             */\n            template<size_t TRow>\n            typename std::enable_if<TRow >= (TStages - 1), TScalarType>::type\n            inline getNode()\n            {\n                static_assert(TRow < (TStages - 1),\n                              \"Row index must be smaller than the number of stages minus one to access coefficients.\");\n\n                return TScalarType{};\n            }\n\n            /**\n             * @brief Sets the node value for the given row number.\n             *\n             * @tparam TRow  Row number (related to stage number).\n             *\n             * @param node Node value to be set.\n             */\n            template<size_t TRow>\n            typename std::enable_if<TRow < (TStages - 1), void>::type\n            inline setNode(TScalarType node)\n            {\n                std::get<TRow>(rows_).node = node;\n            }\n\n            /**\n             * @brief Degenerate node setter.\n             *\n             * @tparam TRow  Row number (related to stage number).\n             *\n             * @param node Node value to be set.\n             */\n            template<size_t TRow>\n            typename std::enable_if<TRow >= (TStages - 1), void>::type\n            inline setNode(TScalarType node)\n            {\n                static_assert(TRow < (TStages - 1),\n                              \"Row index must be smaller than the number of stages minus one to access coefficients.\");\n            }\n\n            /**\n             * @brief Returns the weight value at the given index.\n             *\n             * @tparam TIdx Weight index.\n             *\n             * @return Weight value at \\c TIdx.\n             */\n            template<size_t TIdx>\n            typename std::enable_if<TIdx < TStages, TScalarType>::type\n            inline getWeight()\n            {\n                return std::get<TIdx>(std::get<TStages - 1>(rows_).weights);\n            }\n\n            /**\n             * @brief Degenerate weight getter.\n             *\n             * @tparam TIdx Weight index.\n             *\n             * @return Weight value at \\c TIdx.\n             */\n            template<size_t TIdx>\n            typename std::enable_if<TIdx >= TStages, TScalarType>::type\n            inline getWeight()\n            {\n                static_assert(TIdx < TStages, \"Weight index must be smaller than the number of stages.\");\n\n                return TScalarType{};\n            }\n\n            /**\n             * @brief Sets the weight value for the given index.\n             *\n             * @tparam TIdx Weight index.\n             *\n             * @param weight Weight value to be set.\n             */\n            template<size_t TIdx>\n            typename std::enable_if<TIdx < TStages, void>::type\n            inline setWeight(TScalarType weight)\n            {\n                std::get<TIdx>(std::get<TStages - 1>(rows_).weights) = weight;\n            }\n\n            /**\n             * @brief Degenerate weight setter.\n             *\n             * @tparam TIdx Weight index.\n             *\n             * @param weight Weight value to be set.\n             */\n            template<size_t TIdx>\n            typename std::enable_if<TIdx >= TStages, void>::type\n            inline setWeight(TScalarType weight)\n            {\n                static_assert(TIdx < TStages, \"Weight index must be smaller than the number of stages.\");\n            }\n\n            /**\n             * @brief Executes the explicit Runge-Kutta scheme defined in the Butcher tableau.\n             *\n             * @details The integration scheme integrates y'(t) = f(t, y(t)) from \\c t to \\c (t + h), where \\c y(t) = y.\n             *\n             * This particular function is the entry point to run a single iteration of the Runge-Kutta scheme\n             * encoded in the Butcher tableau.\n             *\n             * @tparam TType State type.\n             * @tparam TStage Index of the current stage.\n             *\n             * @param f Function to be integrated.\n             * @param y Initial state.\n             * @param t Initial time.\n             * @param h Integration step.\n             *\n             * @return Integrated state.\n             */\n            template<typename TType, size_t TStage = 0>\n            typename std::enable_if<TStage == 0, TType>::type\n            inline execute(const std::function<TType(TScalarType, TType)> &f, const TType &y, const TScalarType t,\n                    const TScalarType h)\n            {\n//                TType kCurr;\n//                std::cout << \"f(t,y) in Butcher tableau: \" << f(t, y) << std::endl;\n//                kCurr = f(t, y);\n                auto kCurr = f(t,y);\n\n                return execute<TType, TStage + 1>(f, y, t, h, kCurr);\n            }\n\n            /**\n             * @brief Executes the explicit Runge-Kutta scheme defined in the Butcher tableau.\n             *\n             * @details The integration scheme integrates y'(t) = f(t, y(t)) from \\c t to \\c (t + h), where \\c y(t) = y.\n             *\n             * This particular function deals with the regular stages of the integration scheme.\n             *\n             * @tparam TType State type.\n             * @tparam TStage Index of the current stage.\n             *\n             * @param f Function to be integrated.\n             * @param y Initial state.\n             * @param t Initial time.\n             * @param h Integration step.\n             *\n             * @return Integrated state.\n             */\n            template<typename TType, size_t TStage = 0, typename... TArgs>\n            typename std::enable_if<(TStage > 0) && (TStage < TStages) &&\n                                    (Conjunction<std::is_convertible<TArgs, TType>...>::value), TType>::type\n            inline execute(const std::function<TType(TScalarType, TType)> &f, const TType &y, const TScalarType t,\n                           const TScalarType h,\n                           TArgs... vars)\n            {\n                TType kCurr{}, yCurr = y;\n\n                yCurr += h * sumCoefficients<TType, TStage>(vars...);\n                TScalarType tCurr = t + getNode<TStage - 1>() * h;\n\n                kCurr = f(tCurr, yCurr);\n\n                return execute<TType, TStage + 1>(f, y, t, h, vars..., kCurr);\n//                return execute<TType, TStage + 1>(f, y, t, h, vars..., f(t + getNode<TStage - 1>() * h, y + h * sumCoefficients<TType, TStage>(vars...)));\n            }\n\n            /**\n             * @brief Executes the explicit Runge-Kutta scheme defined in the Butcher tableau.\n             *\n             * @details The integration scheme integrates y'(t) = f(t, y(t)) from \\c t to \\c (t + h), where \\c y(t) = y.\n             *\n             * This particular function deals with the final stage of the integration scheme.\n             *\n             * @tparam TType State type.\n             * @tparam TStage Index of the current stage.\n             *\n             * @param f Function to be integrated.\n             * @param y Initial state.\n             * @param t Initial time.\n             * @param h Integration step.\n             *\n             * @return Integrated state.\n             */\n            template<typename TType, size_t TStage = 0, typename... TArgs>\n            typename std::enable_if<(TStage > 0) && (TStage == TStages) &&\n                                    (Conjunction<std::is_convertible<TArgs, TType>...>::value), TType>::type\n            inline execute(const std::function<TType(TScalarType, TType)> &f, const TType &y, const TScalarType t,\n                           const TScalarType h,\n                           TArgs... vars)\n            {\n                TType yFinal = y;\n                yFinal += h * sumWeights<TType>(vars...);\n\n                return yFinal;\n            }\n\n        protected:\n            /**\n             * Helper struct that will define a tuple of specialized Butcher rows.\n             *\n             * @sa Repeat\n             * @sa Indices\n             *\n             * @tparam TTimes Number of times the generator must be ran.\n             * @tparam TIndices An \\c IndexSequence type.\n             */\n            template<int TTimes, typename TIndices = typename Indices<TTimes>::type>\n            struct Rows;\n\n            /**\n             * @brief Partial specialization of the \\c Rows struct, which defines a tuple of specialized Butcher rows.\n             *\n             * @tparam TTimes Number of times the generator must be ran.\n             * @tparam TIndices Template pack of integers (from 0 to TTimes - 1 by default).\n             */\n            template<int TTimes, int... TIndices>\n            struct Rows<TTimes, IndexSequence<TIndices...>> {\n                using type = std::tuple<ButcherRow<TIndices>...>;\n            };\n\n            typename Rows<TStages>::type rows_; //! Rows of the Butcher tableau.\n\n            /**\n             * @brief Sums Runge-Kutta coefficients multiplied with results from previous stages.\n             *\n             * @details This function computes sum_(j=0)^i a_ij * k_i, where i is \\c TStage.\n             *\n             * @tparam TType State type.\n             * @tparam TStage Index of the current stage.\n             * @tparam TArgs Parameter pack of argument (previous stage result) types.\n             * @tparam TIndex Typename of the \\c Indices object.\n             *\n             * @param vars Variadic argument list of results of previous stages.\n             *\n             * @return Sum.\n             */\n            template<typename TType, size_t TStage = 0, typename... TArgs, typename TIndex = typename Indices<sizeof...(TArgs)>::type>\n            typename std::enable_if<\n                    (TStage > 0) && (TStage < TStages) &&\n                    (Conjunction<std::is_convertible<TArgs, TType>...>::value), TType>::type\n            inline sumCoefficients(TArgs... vars)\n            {\n                return sumCoefficientsImpl<TType, TStage - 1>(TIndex{}, vars...);\n            }\n\n            /**\n             * @brief Implementation of \\c sumCoefficients.\n             *\n             * @note This separate implementation is required to extract the list of indices at compile time.\n             *\n             * @tparam TType State type.\n             * @tparam TStage Index of the current stage.\n             * @tparam TArgs Parameter pack of argument (previous stage result) types.\n             * @tparam TIndices Parameter pack of indices.\n             *\n             * @param vars Variadic argument list of results of previous stages.\n             *\n             * @return Sum.\n             */\n            template<typename TType, size_t TStage = 0, typename... TArgs, int... TIndices>\n            TType\n            inline sumCoefficientsImpl(IndexSequence<TIndices...>, TArgs... vars)\n            {\n                return sum<TType>((getCoefficient<TStage, (size_t) TIndices>() * vars)...);\n            }\n\n            /**\n             * @brief Sums weight coefficients multiplied with results from previous stages.\n             *\n             * @tparam TType State type.\n             * @tparam TArgs Parameter pack of argument (previous stage result) types\n             * @tparam TIndex TIndex Typename of the \\c Indices object.\n             *\n             * @param vars Variadic argument list of results of previous stages.\n             *\n             * @return Sum.\n             */\n            template<typename TType, typename... TArgs, typename TIndex = typename Indices<sizeof...(TArgs)>::type>\n            typename std::enable_if<(Conjunction<std::is_convertible<TArgs, TType>...>::value), TType>::type\n            inline sumWeights(TArgs... vars)\n            {\n                return sumWeightsImpl<TType>(TIndex{}, vars...);\n            }\n\n            /**\n             * @brief Implementation of \\c sumWeights.\n             *\n             * @note This separate implementation is required to extract the list of indices at compile time.\n             *\n             * @tparam TType State type.\n             * @tparam TArgs Parameter pack of argument (previous stage result) types.\n             * @tparam TIndices Parameter pack of indices.\n             *\n             * @param vars Variadic argument list of results of previous stages.\n             *\n             * @return Sum.\n             */\n            template<typename TType, typename... TArgs, int... TIndices>\n            TType\n            inline sumWeightsImpl(IndexSequence<TIndices...>, TArgs... vars)\n            {\n                return sum<TType>((getWeight<(size_t) TIndices>() * vars)...);\n            }\n\n            /**\n             * @brief Helper function that sums arguments.\n             *\n             * @details This particular function is the base case, which simply returns the value that it was given.\n             *\n             * @tparam TType State type.\n             * @tparam TArg Argument type.\n             *\n             * @param var Argument.\n             *\n             * @return Argument.\n             */\n            template<typename TType, typename TArg>\n            typename std::enable_if<std::is_convertible<TArg, TType>::value, TType>::type\n            inline sum(TArg var)\n            {\n                return var;\n            }\n\n            /**\n             * @brief Degenerate case of helper function that sums arguments.\n             *\n             * @details This function checks convertibility of the argument type to \\c TType.\n             *\n             * @tparam TType State type.\n             * @tparam TArg Argument type.\n             *\n             * @param var Argument.\n             */\n            template<typename TType, typename TArg>\n            typename std::enable_if<!std::is_convertible<TArg, TType>::value, TType>::type\n            inline sum(TArg var)\n            {\n                static_assert(std::is_convertible<TArg, TType>::value, \"Summed values must be convertible.\");\n                return var;\n            }\n\n            /**\n             * @brief Helper function that sums arguments.\n             *\n             * @tparam TType State type.\n             * @tparam TArg First argument type.\n             * @tparam TArgs Template pack of variadic argument list typenames.\n             *\n             * @param var First argument.\n             * @param vars Variadic arguments.\n             *\n             * @return Sum.\n             */\n            template<typename TType, typename TArg, typename... TArgs>\n            typename std::enable_if<std::is_convertible<TArg, TType>::value &&\n                    (Conjunction<std::is_convertible<TArgs, TType>...>::value), TType>::type\n            inline sum(TArg var, TArgs... vars)\n            {\n                return var + sum<TType>(vars...);\n            }\n\n            /**\n             * @brief Degenerate case of helper function that sums arguments.\n             *\n             * @tparam TType State type.\n             * @tparam TArg First argument type.\n             * @tparam TArgs Template pack of variadic argument list typenames.\n             *\n             * @param var First argument.\n             * @param vars Variadic arguments.\n             */\n            template<typename TType, typename TArg, typename... TArgs>\n            typename std::enable_if<!(std::is_convertible<TArg, TType>::value &&\n                                      (Conjunction<std::is_convertible<TArgs, TType>...>::value)), TType>::type\n            inline sum(TArg var, TArgs... vars)\n            {\n                static_assert(std::is_convertible<TArg, TType>::value &&\n                              (Conjunction<std::is_convertible<TArgs, TType>...>::value),\n                              \"Summed values must be convertible.\");\n\n                return var + sum<TType>(vars...);\n            }\n        };\n\n// --------------- Extended Butcher tableau -----------------------\n\n        /**\n         * @brief Implements a compile-time structure for extended Butcher tableaus.\n         *\n         * @details Explicit methods in the Runge-Kutta family of numerical integrators can be described by the\n         * following coefficient:\n         * <ul>\n         *      <li> Runge-Kutta coefficients \\c a_ij;\n         *      <li> Weights \\c b_i;\n         *      <li> Nodes \\c c_i.\n         * </ul>\n         *\n         *\n         * @tparam TStages Number of stages in the integration scheme.\n         * @tparam TScalarType Type of the scalar coefficients.\n         */\n        template<size_t TStages, typename TScalarType>\n        class ButcherTableau<TStages, true, TScalarType> {\n        public:\n            static_assert(TStages > 1, \"Butcher tableau must have more than one stage.\");\n\n            static const size_t stages = TStages; //! Number of stages.\n            using type = TScalarType; //! Coefficient type.\n\n            /**\n             * @brief Alias template for \\c ButcherRow.\n             *\n             * @tparam TStage Index of the current stage.\n             * @tparam TIsWeights If true, the current row is a weight row.\n             */\n            template<size_t TStage, bool TIsWeights = (TStage >= (TStages - 1))>\n            using ButcherRow = detail::ButcherRowImpl<TScalarType, TStages, TStage, TIsWeights>;\n\n            /**\n             * @brief Returns the Runge-Kutta coefficient for the given row number and coefficient index.\n             *\n             * @tparam TRow Row number (related to stage number).\n             * @tparam TCoeffIdx Index of the Runge-Kutta coefficient.\n             *\n             * @return Runge-Kutta coefficient at (\\c TRow, \\c TCoeffIdx).\n             */\n            template<size_t TRow, size_t TCoeffIdx>\n            typename std::enable_if<(TRow < (TStages - 1)) && (TCoeffIdx < (TRow + 1)), TScalarType>::type\n            inline getCoefficient()\n            {\n                return std::get<TCoeffIdx>(std::get<TRow>(rows_).rkCoefficients);\n            }\n\n            /**\n             * @brief Degenerate Runge-Kutta coefficient getter.\n             *\n             * @tparam TRow Row number (related to stage number).\n             * @tparam TCoeffIdx Index of the Runge-Kutta coefficient.\n             *\n             * @return Runge-Kutta coefficient at (\\c TRow, \\c TCoeffIdx).\n             */\n            template<size_t TRow, size_t TCoeffIdx>\n            typename std::enable_if<!((TRow < (TStages - 1)) && (TCoeffIdx < (TRow + 1))), TScalarType>::type\n            inline getCoefficient()\n            {\n                static_assert(TRow < (TStages - 1),\n                              \"Row index must be smaller than the number of stages minus one to access coefficients.\");\n                static_assert(TCoeffIdx < (TRow + 1), \"Coefficient index must be less than or equal to the row index.\");\n\n                return TScalarType{};\n            }\n\n            /**\n             * @brief Sets the Runge-Kutta coefficient at the given row number and coefficient index.\n             *\n             * @tparam TRow Row number (related to stage number).\n             * @tparam TCoeffIdx Index of the Runge-Kutta coefficient.\n             *\n             * @param coeff Coefficient value to be set.\n             */\n            template<size_t TRow, size_t TCoeffIdx>\n            typename std::enable_if<(TRow < (TStages - 1)) && (TCoeffIdx < (TRow + 1)), void>::type\n            inline setCoefficient(TScalarType coeff)\n            {\n                std::get<TCoeffIdx>(std::get<TRow>(rows_).rkCoefficients) = coeff;\n            }\n\n            /**\n             * @brief Degenerate Runge-Kutta coefficient setter.\n             *\n             * @tparam TRow Row number (related to stage number).\n             * @tparam TCoeffIdx Index of the Runge-Kutta coefficient.\n             *\n             * @param coeff Coefficient value to be set.\n             */\n            template<size_t TRow, size_t TCoeffIdx>\n            typename std::enable_if<!((TRow < (TStages - 1)) && (TCoeffIdx < (TRow + 1))), void>::type\n            inline setCoefficient(TScalarType coeff)\n            {\n                static_assert(TRow < (TStages - 1),\n                              \"Row index must be smaller than the number of stages minus one to access coefficients.\");\n                static_assert(TCoeffIdx < (TRow + 1), \"Coefficient index must be less than or equal to the row index.\");\n            }\n\n            /**\n             * @brief Returns the node value for the given row number.\n             *\n             * @tparam TRow Row number (related to stage number).\n             *\n             * @return Node value of \\c TRow.\n             */\n            template<size_t TRow>\n            typename std::enable_if<TRow < (TStages - 1), TScalarType>::type\n            inline getNode()\n            {\n                return std::get<TRow>(rows_).node;\n            }\n\n            /**\n             * @brief Degenerate node getter.\n             *\n             * @tparam TRow Row number (related to stage number).\n             *\n             * @return Node value of \\c TRow.\n             */\n            template<size_t TRow>\n            typename std::enable_if<TRow >= (TStages - 1), TScalarType>::type\n            inline getNode()\n            {\n                static_assert(TRow < (TStages - 1),\n                              \"Row index must be smaller than the number of stages minus one to access coefficients.\");\n\n                return TScalarType{};\n            }\n\n            /**\n             * @brief Sets the node value for the given row number.\n             *\n             * @tparam TRow  Row number (related to stage number).\n             *\n             * @param node Node value to be set.\n             */\n            template<size_t TRow>\n            typename std::enable_if<TRow < (TStages - 1), void>::type\n            inline setNode(TScalarType node)\n            {\n                std::get<TRow>(rows_).node = node;\n            }\n\n            /**\n             * @brief Degenerate node setter.\n             *\n             * @tparam TRow  Row number (related to stage number).\n             *\n             * @param node Node value to be set.\n             */\n            template<size_t TRow>\n            typename std::enable_if<TRow >= (TStages - 1), void>::type\n            inline setNode(TScalarType node)\n            {\n                static_assert(TRow < (TStages - 1),\n                              \"Row index must be smaller than the number of stages minus one to access coefficients.\");\n            }\n\n            /**\n             * @brief Returns the weight value at the given index.\n             *\n             * @details This function gets the higher order weight.\n             *\n             * @tparam TIdx Weight index.\n             * @tparam THigherOrder If true, the higher order weights are retrieved.\n             *\n             * @return Weight value at \\c TIdx.\n             */\n            template<size_t TIdx, bool THigherOrder = true>\n            typename std::enable_if<(TIdx < TStages) && THigherOrder, TScalarType>::type\n            inline getWeight()\n            {\n                return std::get<TIdx>(std::get<TStages - 1>(rows_).weights);\n            }\n\n            /**\n             * @brief Returns the weight value at the given index.\n             *\n             * @details This function gets the lower order weight.\n             *\n             * @tparam TIdx Weight index.\n             * @tparam THigherOrder If true, the higher order weights are retrieved.\n             *\n             * @return Weight value at \\c TIdx.\n             */\n            template<size_t TIdx, bool THigherOrder = true>\n            typename std::enable_if<(TIdx < TStages) && !THigherOrder, TScalarType>::type\n            inline getWeight()\n            {\n                return std::get<TIdx>(std::get<TStages>(rows_).weights);\n            }\n\n            /**\n             * @brief Degenerate weight getter.\n             *\n             * @tparam TIdx Weight index.\n             * @tparam THigherOrder If true, the higher order weights are retrieved.\n             *\n             * @return Weight value at \\c TIdx.\n             */\n            template<size_t TIdx, bool THigherOrder = true>\n            typename std::enable_if<TIdx >= TStages, TScalarType>::type\n            inline getWeight()\n            {\n                static_assert(TIdx < TStages, \"Weight index must be smaller than the number of stages.\");\n\n                return TScalarType{};\n            }\n\n            /**\n             * @brief Sets the weight value for the given index.\n             *\n             * @details This function sets the higher order weight.\n             *\n             * @tparam TIdx Weight index.\n             * @tparam THigherOrder If true, the higher order weights are changed.\n             *\n             * @param weight Weight value to be set.\n             */\n            template<size_t TIdx, bool THigherOrder = true>\n            typename std::enable_if<(TIdx < TStages) && THigherOrder, void>::type\n            inline setWeight(TScalarType weight)\n            {\n                std::get<TIdx>(std::get<TStages - 1>(rows_).weights) = weight;\n            }\n\n            /**\n             * @brief Sets the weight value for the given index.\n             *\n             * @details This function sets the lower order weight.\n             *\n             * @tparam TIdx Weight index.\n             * @tparam THigherOrder If true, the higher order weights are changed.\n             *\n             * @param weight Weight value to be set.\n             */\n            template<size_t TIdx, bool THigherOrder = true>\n            typename std::enable_if<(TIdx < TStages) && !THigherOrder, void>::type\n            inline setWeight(TScalarType weight)\n            {\n                std::get<TIdx>(std::get<TStages>(rows_).weights) = weight;\n            }\n\n            /**\n             * @brief Degenerate weight setter.\n             *\n             * @tparam TIdx Weight index.\n             * @tparam THigherOrder If true, the higher order weights are changed.\n             *\n             * @param weight Weight value to be set.\n             */\n            template<size_t TIdx, bool THigherOrder = true>\n            typename std::enable_if<TIdx >= TStages, void>::type\n            inline setWeight(TScalarType weight)\n            {\n                static_assert(TIdx < TStages, \"Weight index must be smaller than the number of stages.\");\n            }\n\n            /**\n             * @brief Executes the explicit Runge-Kutta scheme defined in the Butcher tableau.\n             *\n             * @details The integration scheme integrates y'(t) = f(t, y(t)) from \\c t to \\c (t + h), where \\c y(t) = y.\n             *\n             * This particular function is the entry point to run a single iteration of the Runge-Kutta scheme\n             * encoded in the Butcher tableau.\n             *\n             * @tparam TType State type.\n             * @tparam TStage Index of the current stage.\n             * @tparam TIsEmbedded If true, the execution considers and embedded scheme.\n             *\n             * @param f Function to be integrated.\n             * @param y Initial state.\n             * @param t Initial time.\n             * @param h Integration step.\n             *\n             * @return Integrated state.\n             */\n            template<typename TType, size_t TStage = 0, bool TIsEmbedded = false>\n            typename std::enable_if<(TStage == 0) && !TIsEmbedded, TType>::type\n            inline execute(const std::function<TType(TScalarType, TType)> &f, const TType &y, const TScalarType t,\n                    const TScalarType h)\n            {\n                TType kCurr = f(t, y);\n\n                return execute<TType, TStage + 1, TIsEmbedded>(f, y, t, h, kCurr);\n            }\n\n            /**\n             * @brief Executes the explicit Runge-Kutta scheme defined in the Butcher tableau.\n             *\n             * @details The integration scheme integrates y'(t) = f(t, y(t)) from \\c t to \\c (t + h), where \\c y(t) = y.\n             *\n             * This particular function is the entry point to run a single iteration of the Runge-Kutta scheme\n             * encoded in the Butcher tableau.\n             *\n             * @tparam TType State type.\n             * @tparam TStage Index of the current stage.\n             * @tparam TIsEmbedded If true, the execution considers an embedded scheme.\n             *\n             * @param f Function to be integrated.\n             * @param y Initial state.\n             * @param t Initial time.\n             * @param h Integration step.\n             *\n             * @return Pair of integrated state (with higher-order scheme) and error.\n             */\n            template<typename TType, size_t TStage = 0, bool TIsEmbedded = false>\n            typename std::enable_if<(TStage == 0) && TIsEmbedded, std::pair<TType, TType>>::type\n            inline execute(const std::function<TType(TScalarType, TType)> &f, const TType &y, const TScalarType t,\n                    const TScalarType h)\n            {\n                TType kCurr = f(t, y);\n\n                return execute<TType, TStage + 1, TIsEmbedded>(f, y, t, h, kCurr);\n            }\n\n            /**\n             * @brief Executes the explicit Runge-Kutta scheme defined in the Butcher tableau.\n             *\n             * @details The integration scheme integrates y'(t) = f(t, y(t)) from \\c t to \\c (t + h), where \\c y(t) = y.\n             *\n             * This particular function deals with the regular stages of the integration scheme.\n             *\n             * @tparam TType State type.\n             * @tparam TStage Index of the current stage.\n             * @tparam TIsEmbedded If true, the execution considers an embedded scheme.\n             *\n             * @param f Function to be integrated.\n             * @param y Initial state.\n             * @param t Initial time.\n             * @param h Integration step.\n             *\n             * @return Integrated state.\n             */\n            template<typename TType, size_t TStage = 0, bool TIsEmbedded = false, typename... TArgs>\n            typename std::enable_if<(TStage > 0) && (TStage < TStages) && !TIsEmbedded &&\n                                    (Conjunction<std::is_convertible<TArgs, TType>...>::value), TType>::type\n            inline execute(const std::function<TType(TScalarType, TType)> &f, const TType &y, const TScalarType t,\n                    const TScalarType h,\n                    TArgs... vars)\n            {\n                TType kCurr{}, yCurr = y;\n\n                yCurr += h * sumCoefficients<TType, TStage>(vars...);\n                TScalarType tCurr = t + getNode<TStage - 1>() * h;\n\n                kCurr = f(tCurr, yCurr);\n\n                return execute<TType, TStage + 1, TIsEmbedded>(f, y, t, h, vars..., kCurr);\n            }\n\n            /**\n             * @brief Executes the explicit Runge-Kutta scheme defined in the Butcher tableau.\n             *\n             * @details The integration scheme integrates y'(t) = f(t, y(t)) from \\c t to \\c (t + h), where \\c y(t) = y.\n             *\n             * This particular function deals with the regular stages of the integration scheme.\n             *\n             * @tparam TType State type.\n             * @tparam TStage Index of the current stage.\n             * @tparam TIsEmbedded If true, the execution considers an embedded scheme.\n             *\n             * @param f Function to be integrated.\n             * @param y Initial state.\n             * @param t Initial time.\n             * @param h Integration step.\n             *\n             * @return Pair of integrated state (with higher-order scheme) and error.\n             */\n            template<typename TType, size_t TStage = 0, bool TIsEmbedded = false, typename... TArgs>\n            typename std::enable_if<(TStage > 0) && (TStage < TStages) && TIsEmbedded &&\n                                    (Conjunction<std::is_convertible<TArgs, TType>...>::value), std::pair<TType, TType>>::type\n            inline execute(const std::function<TType(TScalarType, TType)> &f, const TType &y, const TScalarType t,\n                           const TScalarType h,\n                           TArgs... vars)\n            {\n                TType kCurr{}, yCurr = y;\n\n                yCurr += h * sumCoefficients<TType, TStage>(vars...);\n                TScalarType tCurr = t + getNode<TStage - 1>() * h;\n\n                kCurr = f(tCurr, yCurr);\n\n                return execute<TType, TStage + 1, TIsEmbedded>(f, y, t, h, vars..., kCurr);\n            }\n\n            /**\n             * @brief Executes the explicit Runge-Kutta scheme defined in the Butcher tableau.\n             *\n             * @details The integration scheme integrates y'(t) = f(t, y(t)) from \\c t to \\c (t + h), where \\c y(t) = y.\n             *\n             * This particular function deals with the final stage of the integration scheme.\n             *\n             * @tparam TType State type.\n             * @tparam TStage Index of the current stage.\n             * @tparam TIsEmbedded If true, the execution considers an embedded scheme.\n             *\n             * @param f Function to be integrated.\n             * @param y Initial state.\n             * @param t Initial time.\n             * @param h Integration step.\n             *\n             * @return Integrated state.\n             */\n            template<typename TType, size_t TStage = 0, bool TIsEmbedded = false, typename... TArgs>\n            typename std::enable_if<(TStage > 0) && (TStage == TStages) && !TIsEmbedded &&\n                                    (Conjunction<std::is_convertible<TArgs, TType>...>::value), TType>::type\n            inline execute(const std::function<TType(TScalarType, TType)> &f, const TType &y, const TScalarType t,\n                           const TScalarType h,\n                           TArgs... vars)\n            {\n                TType yFinal = y;\n                yFinal += h * sumWeights<TType>(vars...);\n\n                return yFinal;\n            }\n\n            /**\n             * @brief Executes the explicit Runge-Kutta scheme defined in the Butcher tableau.\n             *\n             * @details The integration scheme integrates y'(t) = f(t, y(t)) from \\c t to \\c (t + h), where \\c y(t) = y.\n             *\n             * This particular function deals with the final stage of the integration scheme.\n             *\n             * @tparam TType State type.\n             * @tparam TStage Index of the current stage.\n             * @tparam TIsEmbedded If true, the execution considers an embedded scheme.\n             *\n             * @param f Function to be integrated.\n             * @param y Initial state.\n             * @param t Initial time.\n             * @param h Integration step.\n             *\n             * @return Pair of integrated state (with higher-order scheme) and error.\n             */\n            template<typename TType, size_t TStage = 0, bool TIsEmbedded = false, typename... TArgs>\n            typename std::enable_if<(TStage > 0) && (TStage == TStages) && TIsEmbedded &&\n                                    (Conjunction<std::is_convertible<TArgs, TType>...>::value), std::pair<TType, TType>>::type\n            inline execute(const std::function<TType(TScalarType, TType)> &f, const TType &y, const TScalarType t,\n                           const TScalarType h,\n                           TArgs... vars)\n            {\n                TType yFinal = y;\n                TType summedWeightsHigher = sumWeights<TType, true>(vars...);\n                TType summedWeightsLower = sumWeights<TType, false>(vars...);\n                yFinal += h * summedWeightsHigher;\n\n                std::pair<TType, TType> pair{yFinal, h * (summedWeightsHigher - summedWeightsLower)};\n\n                return pair;\n            }\n\n        protected:\n            /**\n             * Helper struct that will define a tuple of specialized Butcher rows.\n             *\n             * @sa Repeat\n             * @sa Indices\n             *\n             * @tparam TTimes Number of times the generator must be ran.\n             * @tparam TIndices An \\c IndexSequence type.\n             */\n            template<int TTimes, typename TIndices = typename Indices<TTimes>::type>\n            struct Rows;\n\n            /**\n             * @brief Partial specialization of the \\c Rows struct, which defines a tuple of specialized Butcher rows.\n             *\n             * @tparam TTimes Number of times the generator must be ran.\n             * @tparam TIndices Template pack of integers (from 0 to TTimes - 1 by default).\n             */\n            template<int TTimes, int... TIndices>\n            struct Rows<TTimes, IndexSequence<TIndices...>> {\n                using type = std::tuple<ButcherRow<TIndices>...>;\n            };\n\n            typename Rows<TStages + 1>::type rows_; //! Rows of the Butcher tableau.\n\n            /**\n             * @brief Sums Runge-Kutta coefficients multiplied with results from previous stages.\n             *\n             * @details This function computes sum_(j=0)^i a_ij * k_i, where i is \\c TStage.\n             *\n             * @tparam TType State type.\n             * @tparam TStage Index of the current stage.\n             * @tparam TArgs Parameter pack of argument (previous stage result) types.\n             * @tparam TIndex Typename of the \\c Indices object.\n             *\n             * @param vars Variadic argument list of results of previous stages.\n             *\n             * @return Sum.\n             */\n            template<typename TType, size_t TStage = 0, typename... TArgs, typename TIndex = typename Indices<sizeof...(TArgs)>::type>\n            typename std::enable_if<\n                    (TStage > 0) && (TStage < TStages) &&\n                    (Conjunction<std::is_convertible<TArgs, TType>...>::value), TType>::type\n            inline sumCoefficients(TArgs... vars)\n            {\n                return sumCoefficientsImpl<TType, TStage - 1>(TIndex{}, vars...);\n            }\n\n            /**\n             * @brief Implementation of \\c sumCoefficients.\n             *\n             * @note This separate implementation is required to extract the list of indices at compile time.\n             *\n             * @tparam TType State type.\n             * @tparam TStage Index of the current stage.\n             * @tparam TArgs Parameter pack of argument (previous stage result) types.\n             * @tparam TIndices Parameter pack of indices.\n             *\n             * @param vars Variadic argument list of results of previous stages.\n             *\n             * @return Sum.\n             */\n            template<typename TType, size_t TStage = 0, typename... TArgs, int... TIndices>\n            TType\n            inline sumCoefficientsImpl(IndexSequence<TIndices...>, TArgs... vars)\n            {\n                return sum<TType>((getCoefficient<TStage, (size_t) TIndices>() * vars)...);\n            }\n\n            /**\n             * @brief Sums weight coefficients multiplied with results from previous stages.\n             *\n             * @tparam TType State type.\n             * @tparam THigherOrder If true, higher order weights are used.\n             * @tparam TArgs Parameter pack of argument (previous stage result) types\n             * @tparam TIndex TIndex Typename of the \\c Indices object.\n             *\n             * @param vars Variadic argument list of results of previous stages.\n             *\n             * @return Sum.\n             */\n            template<typename TType, bool THigherOrder = true, typename... TArgs, typename TIndex = typename Indices<sizeof...(TArgs)>::type>\n            typename std::enable_if<(Conjunction<std::is_convertible<TArgs, TType>...>::value), TType>::type\n            inline sumWeights(TArgs... vars)\n            {\n                return sumWeightsImpl<TType, THigherOrder>(TIndex{}, vars...);\n            }\n\n            /**\n             * @brief Implementation of \\c sumWeights.\n             *\n             * @note This separate implementation is required to extract the list of indices at compile time.\n             *\n             * @tparam TType State type.\n             * @tparam THigherOrder If true, higher order weights are used.\n             * @tparam TArgs Parameter pack of argument (previous stage result) types.\n             * @tparam TIndices Parameter pack of indices.\n             *\n             * @param vars Variadic argument list of results of previous stages.\n             *\n             * @return Sum.\n             */\n            template<typename TType, bool THigherOrder, typename... TArgs, int... TIndices>\n            typename std::enable_if<THigherOrder, TType>::type\n            inline sumWeightsImpl(IndexSequence<TIndices...>, TArgs... vars)\n            {\n                return sum<TType>((getWeight<(size_t) TIndices, true>() * vars)...);\n            }\n\n            /**\n             * @brief Implementation of \\c sumWeights.\n             *\n             * @note This separate implementation is required to extract the list of indices at compile time.\n             *\n             * @tparam TType State type.\n             * @tparam THigherOrder If true, higher order weights are used.\n             * @tparam TArgs Parameter pack of argument (previous stage result) types.\n             * @tparam TIndices Parameter pack of indices.\n             *\n             * @param vars Variadic argument list of results of previous stages.\n             *\n             * @return Sum.\n             */\n            template<typename TType, bool THigherOrder, typename... TArgs, int... TIndices>\n            typename std::enable_if<!THigherOrder, TType>::type\n            inline sumWeightsImpl(IndexSequence<TIndices...>, TArgs... vars)\n            {\n                return sum<TType>((getWeight<(size_t) TIndices, false>() * vars)...);\n            }\n\n            /**\n             * @brief Helper function that sums arguments.\n             *\n             * @details This particular function is the base case, which simply returns the value that it was given.\n             *\n             * @tparam TType State type.\n             * @tparam TArg Argument type.\n             *\n             * @param var Argument.\n             *\n             * @return Argument.\n             */\n            template<typename TType, typename TArg>\n            typename std::enable_if<std::is_convertible<TArg, TType>::value, TType>::type\n            inline sum(TArg var)\n            {\n                return var;\n            }\n\n            /**\n             * @brief Degenerate case of helper function that sums arguments.\n             *\n             * @details This function checks convertibility of the argument type to \\c TType.\n             *\n             * @tparam TType State type.\n             * @tparam TArg Argument type.\n             *\n             * @param var Argument.\n             */\n            template<typename TType, typename TArg>\n            typename std::enable_if<!std::is_convertible<TArg, TType>::value, TType>::type\n            inline sum(TArg var)\n            {\n                static_assert(std::is_convertible<TArg, TType>::value, \"Summed values must be convertible.\");\n                return var;\n            }\n\n            /**\n             * @brief Helper function that sums arguments.\n             *\n             * @tparam TType State type.\n             * @tparam TArg First argument type.\n             * @tparam TArgs Template pack of variadic argument list typenames.\n             *\n             * @param var First argument.\n             * @param vars Variadic arguments.\n             *\n             * @return Sum.\n             */\n            template<typename TType, typename TArg, typename... TArgs>\n            typename std::enable_if<std::is_convertible<TArg, TType>::value &&\n                    (Conjunction<std::is_convertible<TArgs, TType>...>::value), TType>::type\n            inline sum(TArg var, TArgs... vars)\n            {\n                return var + sum<TType>(vars...);\n            }\n\n            /**\n             * @brief Degenerate case of helper function that sums arguments.\n             *\n             * @tparam TType State type.\n             * @tparam TArg First argument type.\n             * @tparam TArgs Template pack of variadic argument list typenames.\n             *\n             * @param var First argument.\n             * @param vars Variadic arguments.\n             */\n            template<typename TType, typename TArg, typename... TArgs>\n            typename std::enable_if<!(std::is_convertible<TArg, TType>::value &&\n                                      (Conjunction<std::is_convertible<TArgs, TType>...>::value)), TType>::type\n            inline sum(TArg var, TArgs... vars)\n            {\n                static_assert(std::is_convertible<TArg, TType>::value &&\n                              (Conjunction<std::is_convertible<TArgs, TType>...>::value),\n                              \"Summed values must be convertible.\");\n\n                return var + sum<TType>(vars...);\n            }\n        };\n    }\n}\n\n#endif //LODESTAR_BUTCHERTABLEAU_HPP\n", "meta": {"hexsha": "effa9c66e0a06a18fa6b0e572461ce8862bf205f", "size": 53224, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Lodestar/primitives/integrators/ButcherTableau.hpp", "max_stars_repo_name": "helkebir/Lodestar", "max_stars_repo_head_hexsha": "6b325d3e7a388676ed31d44eac1146630ee4bb2c", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2020-06-05T14:08:23.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-26T22:15:31.000Z", "max_issues_repo_path": "Lodestar/primitives/integrators/ButcherTableau.hpp", "max_issues_repo_name": "helkebir/Lodestar", "max_issues_repo_head_hexsha": "6b325d3e7a388676ed31d44eac1146630ee4bb2c", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-06-25T15:14:01.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-01T17:43:20.000Z", "max_forks_repo_path": "Lodestar/primitives/integrators/ButcherTableau.hpp", "max_forks_repo_name": "helkebir/Lodestar", "max_forks_repo_head_hexsha": "6b325d3e7a388676ed31d44eac1146630ee4bb2c", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-06-16T03:15:23.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-16T03:15:23.000Z", "avg_line_length": 42.7158908507, "max_line_length": 156, "alphanum_fraction": 0.5180369758, "num_tokens": 11485, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5964331606115021, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.3375922239117035}}
{"text": "#include <functional>\n#include <iostream>\n#include <map>\n#include <utility>\n\n#include <boost/program_options.hpp>\n\n#include \"LinearProgram.h\"\n#include \"Pivot.h\"\n\nnamespace po = boost::program_options;\n\nstd::map<std::string, std::function<PivotFunctionReturnType(Tableau &tableau)>> pivotFunctions;\nstd::string allowedPivotFunctions;\n\n/*\nTake the pivot function callables from Pivot.h (or elsewhere), and register them with the command-line options parser\n*/\nvoid registerPivotFunctions()\n{\n\tpivotFunctions = decltype(pivotFunctions){\n\t\t{\"bland\", Bland()},\n\t\t{\"random\", Random()},\n\t\t{\"maxincrease\", MaxIncrease()},\n\t\t{\"maxcoef\", MaxCoef()}};\n\tallowedPivotFunctions.clear();\n\tfor (auto &it : pivotFunctions)\n\t{\n\t\tallowedPivotFunctions += it.first;\n\t\tallowedPivotFunctions += ',';\n\t}\n\tallowedPivotFunctions.pop_back();\n}\n\n/*\nParse the command-line options, and return them as a tuple.\n*/\nauto parseOptions(int argc, char **argv)\n{\n\tpo::options_description optionsDescription(\"Allowed options\");\n\tstd::string pivotHelpText = \"the pivot rule that is used. Can be one of {\" + allowedPivotFunctions + \"}\";\n\toptionsDescription.add_options()(\"verbose\", po::value<bool>()->implicit_value(true)->default_value(false), \"verbose output\")(\"pivot\", po::value<std::string>()->default_value(\"maxincrease\"), pivotHelpText.c_str())(\"input\", po::value<std::string>(), \"input linear program\");\n\tpo::positional_options_description positionalOptionsDescription;\n\tpositionalOptionsDescription.add(\"input\", -1);\n\n\tpo::variables_map variablesMap;\n\tpo::store(\n\t\tpo::command_line_parser(argc, argv)\n\t\t\t.options(optionsDescription)\n\t\t\t.positional(positionalOptionsDescription)\n\t\t\t.run(),\n\t\tvariablesMap);\n\tpo::notify(variablesMap);\n\n\tstd::string inputPath;\n\tif (variablesMap.count(\"input\"))\n\t{\n\t\tinputPath = variablesMap[\"input\"].as<std::string>();\n\t}\n\telse\n\t{\n\t\tstd::cout << \"You must provide a valid path\\n\"\n\t\t\t\t  << optionsDescription;\n\t\tstd::exit(1);\n\t}\n\n\tauto verboseOutput = variablesMap[\"verbose\"].as<bool>();\n\tauto pivotAlgorithm = variablesMap[\"pivot\"].as<std::string>();\n\n\tif (pivotFunctions.find(pivotAlgorithm) == pivotFunctions.end())\n\t{\n\t\tstd::cout << \"Invalid pivot algorithm \\\"\" << pivotAlgorithm << \"\\\"\\n\";\n\t\tstd::cout << \"Allowed values are {\" << allowedPivotFunctions << \"}\\n\";\n\t\tstd::exit(1);\n\t}\n\n\treturn std::make_tuple(inputPath, verboseOutput, pivotAlgorithm);\n}\n\nint main(int argc, char **argv)\n{\n\tregisterPivotFunctions();\n\n\tstd::string inputPath, pivotAlgorithm;\n\tbool verboseOutput;\n\n\tstd::tie(inputPath, verboseOutput, pivotAlgorithm) = parseOptions(argc, argv);\n\n\tLinearProgram lp(inputPath, verboseOutput);\n\tlp.printFancyStatement();\n\n\tauto result = lp.solve(pivotFunctions[pivotAlgorithm]);\n\n\tswitch (result)\n\t{\n\tcase LinearProgram::Result::INFEASIBLE:\n\t\tstd::cout << \"The linear program is infeasible\\n\";\n\t\tbreak;\n\tcase LinearProgram::Result::FEASIBLE_UNBOUNDED:\n\t\tstd::cout << \"The linear program is unbounded\\n\";\n\t\tbreak;\n\tcase LinearProgram::Result::FEASIBLE_BOUNDED:\n\t\tstd::cout << \"An optimal solution is: \";\n\t\tlp.printFancySolution();\n\t\tstd::cout << \"\\nThe value of the objective function is: \" << lp.tableau.value();\n\t\tstd::cout << \"\\nThe number of pivots is: \" << lp.numPivots;\n\t\tstd::cout << \"\\nThe pivot rule used: \" << pivotAlgorithm;\n\t}\n\treturn 0;\n}", "meta": {"hexsha": "f76d8b2a19c991c41332d331bf93fab04c04efb8", "size": 3264, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "main.cpp", "max_stars_repo_name": "dancsi/RationaLP", "max_stars_repo_head_hexsha": "e389495935fa7cb3d5972782f2bca22bb3e48b0a", "max_stars_repo_licenses": ["CNRI-Python"], "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": "dancsi/RationaLP", "max_issues_repo_head_hexsha": "e389495935fa7cb3d5972782f2bca22bb3e48b0a", "max_issues_repo_licenses": ["CNRI-Python"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "main.cpp", "max_forks_repo_name": "dancsi/RationaLP", "max_forks_repo_head_hexsha": "e389495935fa7cb3d5972782f2bca22bb3e48b0a", "max_forks_repo_licenses": ["CNRI-Python"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.6727272727, "max_line_length": 273, "alphanum_fraction": 0.7172181373, "num_tokens": 810, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5660185351961015, "lm_q2_score": 0.5964331462646255, "lm_q1q2_score": 0.3375922157911055}}
{"text": "#include <boost/config.hpp>\n#include <iostream>\n#include <fstream>\n#include <string>\n#include <exception>\n#include <vector>\n#include <time.h>\n#include <utility>\n#include <limits>\n#include <tuple>\n#include <list>\n\n#include <boost/math/special_functions/prime.hpp>\n#include <boost/graph/graph_traits.hpp>\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/dijkstra_shortest_paths.hpp>\n#include <boost/property_map/property_map.hpp>\n\nusing namespace boost;\n\n\n\n\n\n\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/breadth_first_search.hpp>\n\n\n\n//typedegs for graph and edges\ntypedef adjacency_list < listS, vecS, undirectedS,no_property, \n\tproperty < edge_weight_t, int > > graph_t;\ntypedef graph_traits < graph_t >::vertex_descriptor vertex_descriptor;\ntypedef std::pair<int, int> Edge;\n\n//edge with weight\ntypedef std::tuple<int,int,int> Edge_wW;\n\n\n// Graph Definitions\n//typedef boost::adjacency_list<boost::vecS,boost::vecS,boost::directedS> Graph;\ntypedef boost::graph_traits<graph_t>::vertex_descriptor Vertex;\ntypedef boost::graph_traits<graph_t>::edge_descriptor EdgeDes;\n\n\n\n\n// Visitor that throw an exception when finishing the destination vertex\nclass my_visitor : boost::default_bfs_visitor{\nprotected:\n  Vertex destination_vertex_m;\npublic:\n  my_visitor(Vertex destination_vertex_l)\n    : destination_vertex_m(destination_vertex_l) {};\n\n  void initialize_vertex(const Vertex &s, const graph_t &g) const {}\n  void discover_vertex(const Vertex &s, const graph_t &g) const {}\n  void examine_vertex(const Vertex &s, const graph_t &g) const {}\n  void examine_edge(const EdgeDes &e, const graph_t &g) const {}\n  void edge_relaxed(const EdgeDes &e, const graph_t &g) const {}\n  void edge_not_relaxed(const EdgeDes &e, const graph_t &g) const {}\n  void finish_vertex(const Vertex &s, const graph_t &g) const {\n    if (destination_vertex_m == s)\n      throw(2);\n  }\n};\n\n\n\n\n\n\n\n\n\n//find the prime vertexes\nint findPrimes(std::vector<int> &primes, int vertNumb){\n\n\t\tstd::ifstream file;\n\t\tfile.open(\"primes1.txt\");\n\t\tint searchingPrimes=true;\n\n\t\tint primesNumb=0;\n\n\t\tstd::string str;\n\t\tgetline(file, str,'\\r');\n\n\n\twhile(searchingPrimes){\n\n\t\tint numsInLine=8;\n\t\tgetline(file, str,'\\r');\n\n\t\tfor(int i=0;i<numsInLine;i++){\n\t\t\t\n\n\t\t\t\n\t\t\tint nextPrime = std::stoi(str.substr(10*i,10+10*i));\n\t\t\t\n\t\t\tif(nextPrime<=vertNumb){\n\t\t\t\tprimes.push_back(nextPrime);\n\t\t\t\tprimesNumb++;\n\t\t\t}\n\t\t\telse{\n\t\t\t\tsearchingPrimes=false;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\t\n\t\t}\n\t\tgetline(file, str,'\\r');\n\t\t\n\t}\n\tfile.close();\n\n\treturn primesNumb;\n}\n\n\n\n\n\n\n\n\n\n// fills the edge array with all the edges from the node array\nvoid createEdgeArray(std::vector<Edge>* nodes,Edge* edge_array,int* weights, int vertNumb ){\n\n\tint count=0;\n\tfor(int i=0;i<vertNumb;i++){\n\t\tint size=nodes[i].size();\n\t\tfor(int j=0;j<size;j++){\n\t\t\tEdge edg=nodes[i].at(j); \n\t\t\n\n\t\t\tedge_array[count]=Edge(i,edg.first);\n\t\t\tweights[count]=edg.second;\n\t\t\tcount++;\n\t\t}\n\t}\n}\n\n\n\n\n\n\n\n// reads in and initialize the edges\nvoid initializeEdges(std::vector<Edge>* nodes,std::vector<int> primes, int vertNumb,int arcNumb,int primeNumb,std::ifstream &file){\n\n\ttry {\n\n\t\tint count=0;\n\n\n\t\t//edges from the source node to 2 with weithg 0\n\t\tnodes[0].push_back(Edge(2,0));\n\t\tcount++;\n\n\n\t\tstd::string str;\n\t\t\n\t\twhile (count<arcNumb-primeNumb+1) {\n\n\t\t\tgetline(file, str, ' ');\n\t\t\tint from = std::stoi(str);\n\n\t\t\tgetline(file, str, ' ');\n\t\t\tint to = std::stoi(str);\n\n\t\t\tgetline(file,str);\n\t\t\tint dist=std::stoi(str);\n\n\t\t\tif(from>to){\n\t\t\t\tint help=from;\n\t\t\t\tfrom = to;\n\t\t\t\tto = help;\n\t\t\t}\n\n\t\t\tnodes[from].push_back(Edge(to,dist));\t\n\n\t\t\tcount++;\n\t\t}\n\n\n\t\t//Edges from all primes except 2 to the sink\n\t\tfor(int i=1;i<primeNumb;i++){\n\n\t\t\tint prime=primes.at(i);\n\t\t\tnodes[prime].push_back(Edge(vertNumb-1,0));\n\t\t}\n\t}\n\tcatch (...) {\n\t}\n}\n\n\n\n\n\n\n\n\n\n\n// removes an Edge out of nodes from vertex to parent\nvoid removeEdge(std::vector<Edge>* nodes, int vertex, int parent){\n\n\tif(parent<vertex){\n\t\tint help=vertex;\n\t\tvertex=parent;\n\t\tparent=help;\n\t}\n\n\n\n\tstd::vector<Edge>::iterator it=nodes[vertex].begin();\n\n\tfor(it;it!=nodes[vertex].end();it++){\n\t\tif((*it).first==parent){\n\t\t\tnodes[vertex].erase(it);\n\t\t\tbreak;\n\t\t}\n\t}\n}\n\n\n\n\n\n\n\n\n// uses boost dijkstra and returns the distance from the graph to the new prime\nint dijkstra(graph_t &g,int vertNumb, bool* steinTree, std::vector<Edge>* nodes){\n\t\n\n\tproperty_map<graph_t, edge_weight_t>::type weightmap = get(edge_weight, g);\n\tstd::vector<vertex_descriptor> p(num_vertices(g));\n\tstd::vector<int> d(num_vertices(g));\n\tvertex_descriptor s = vertex(0, g);\n\tmy_visitor vis(vertNumb-1);\n\n\n   \t//clock_t tStartd1 = clock();\n\n\n   \ttry{\n\t\tdijkstra_shortest_paths(g, s,\n\t                          predecessor_map(boost::make_iterator_property_map(p.begin(), get(boost::vertex_index, g))).\n\t                          distance_map(boost::make_iterator_property_map(d.begin(), get(boost::vertex_index, g))).\n\t                          visitor(vis));\n\t}\n\tcatch(...){\n\t}\n\t\t\t\n\n\t//std::cout <<\"INFORM TIME DIJKSTRA: \"<< (double)(clock() - tStartd1) / CLOCKS_PER_SEC << \" seconds\" << std::endl;\n\n\t///////////// remove edges\n\t//clock_t rem=clock();\n\tint vertex=vertNumb-1;\n\tint parent=p[vertex];\n\n\tremove_edge(vertex,parent,g);\n\tremoveEdge(nodes,vertex,parent);\n\n\twhile(!steinTree[parent]){\n\t \t\t\n\t \t\tsteinTree[parent]=true;\n\n\t \t\t// create a new Edge from source node to parent node with weight 0\n\t \t\tadd_edge(0,parent,0,g);\n\n\t \t\t//removes the Edge from vertex to parent\n\t \t\tremove_edge(vertex,parent,g);\n\t \t\tremoveEdge(nodes,vertex,parent);\n\n\t \t\tvertex=parent;\n\t \t\tparent=p[parent];\n\t}\n\n\tremove_edge(vertex,parent,g);\n\tremoveEdge(nodes,vertex,parent);\n\n\t//std::cout <<\"INFORM TIME REMOVE EDGES: \"<< (double)(clock() - rem) / CLOCKS_PER_SEC << \" seconds\" << std::endl;\n\t//std::cout<< \"RESULT Parent  \"<< p[vertNumb-1]<<std::endl;\n\n\treturn d[vertNumb-1];\n}\n\n\n\n\n\n\n\n\n\n\n\n\n// TODO is not working\nvoid simplifyGraph(graph_t &g,std::vector<Edge>* nodes,bool* steinTree,int vertNumb){\n\tbool hasEdge[vertNumb]={false};\n\n\tfor(int i = 1;i<vertNumb;i++){\n\n\t\tstd::vector<Edge>::iterator it=nodes[i].begin();\n\t\tif(steinTree[i]){\n\n\t\t\t\n\t\t\tfor(it;it!=nodes[i].end();it++){\n\n\t\t\t\tstd::cout<<i<<std::endl;\n\t\t\t\tstd::cout<<((*it).first)<<std::endl;  //This gives out some strange values \n\t\t\t\tstd::cout<<(nodes[i].size())<<std::endl;\n\t\t\t\tif(steinTree[(*it).first]){\t\t//segmentation fault in this line\n\t\t\t\t\t\n\t\t\t\t\tstd::cout<<\"lalala\"<<std::endl;\n\t\t\t\t\tremove_edge(i,(*it).first,g);\n\t\t\t\t\tit=nodes[i].erase(it);\n\t\t\t\t\t\n\t\t\t\t}\n\t\t\t\telse{\n\t\t\t\t\tstd::cout<<\"lululu\"<<std::endl;\n\t\t\t\t\thasEdge[(*it).first]=true;\n\t\t\t\t}\n\t\t\t\tstd::cout<<\"hehehehe\"<<std::endl;\n\t\t\t}\n\t\t}\n\t\telse{\n\n\t\t\tstd::cout<<\"huhuhuhu\"<<std::endl;\n\t\t\tfor(it;it!=nodes[i].end();it++){\n\t\t\t\thasEdge[(*it).first]=true;\n\t\t\t}\n\t\t}\n\n\t\tif(nodes[i].size()==0 && !hasEdge){\n\t\t\tstd::cout<<\"weweweew\"<<std::endl;\n\t\t\tremove_vertex(i,g);\n\t\t}\n\t}\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nint main(int argc, char* argv[]){\n\n\n\tclock_t c=clock();\n\t//////// read input arguments\n\n\tstd::ifstream file;\n\tfile.open(argv[1]);\n\t\t\n\n\tif (!file.is_open()) {\n\t\t\tstd::cerr << \"there is no file of the name \\\"\" << argv[1] << \"\\\" in the directory\" << std::endl;\n\t\t\treturn 0;\n\t}\n\t////////\n\n\n\t// get the Number of vertexes\n  \tstd::string str;\n\tgetline(file, str, ' ');\n\tint vertNumb = std::stoi(str)+2;\n\n\n\t// get the prime nodes\n\tstd::vector<int> primes;\n\tint primeNumb=findPrimes(primes,vertNumb-2);\n\n\n\t//vector for the Edges to the nodes, first node is source last node is sink( this is needed for simplify graph)\n\tstd::vector<Edge> nodes[vertNumb];\n\n\n\t// get the Number of arcs\n\tgetline(file, str);\n\tint arcNumb=std::stoi(str)+primeNumb;\n\n\n\t//the vertexes in the steiner tree\n\tbool steinTree[vertNumb]={false};\n\tsteinTree[0]=true;\n\tsteinTree[2]=true;\n\n\n\t//////// create the graph\n\tinitializeEdges(nodes, primes, vertNumb, arcNumb, primeNumb,file);\n\n\tEdge *edge_array;\n\tedge_array = (Edge*)malloc((arcNumb)* sizeof(Edge));\n\n\tint *weights;\n\tweights = (int*)malloc((arcNumb)* sizeof(int));\n\n\tcreateEdgeArray(nodes,edge_array,weights,vertNumb);\n\n\tgraph_t g(edge_array, edge_array + arcNumb, weights, vertNumb);\n\t////////\n\n\n\n\n\n\t//clock_t cl[primeNumb];\n\t//cl[0]=clock();\n\n\t//weight of steinertree\n\tlong long weightST=0;\n\n\tfor(int i =1; i<primeNumb;i++){\n\t\t\n\t\tweightST= weightST+dijkstra(g, vertNumb, steinTree,nodes);\n\n\n\t/*\n\t \tif(i%100==0){\n\t \t\tsimplifyGraph(g,nodes,steinTree,vertNumb);\n\t \t}\n\n\t*/\n\n\t\t//cl[i]=clock();\n\t\t//std::cout <<\"INFORM TIME STEP: \"<<  i<<\"   \"<< (double)(cl[i] - cl[i-1]) / CLOCKS_PER_SEC << \" seconds\" << std::endl;\n\n\t}\n\n\n\t\tclock_t tStart5 = clock();\n\t\tstd::cout <<\"INFORM WEIGHT OF STEINER TREE: \"<< weightST << std::endl;\n\t\tstd::cout <<\"INFORM TIME: \"<< (double)(tStart5 - c) / CLOCKS_PER_SEC << \" seconds\" << std::endl;\n\n\n\n \treturn 0;\t\n}", "meta": {"hexsha": "0425796ac7073d52e72e0ea25f3de435d67bfd7e", "size": 8671, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Jung/ex8/ex8.cpp", "max_stars_repo_name": "appfs/appfs", "max_stars_repo_head_hexsha": "8cbbfa0e40e4d4a75a498ce8dd894bb2fbc3a9e3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 11.0, "max_stars_repo_stars_event_min_datetime": "2017-04-21T11:39:55.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-11T20:25:18.000Z", "max_issues_repo_path": "Jung/ex8/ex8.cpp", "max_issues_repo_name": "appfs/appfs", "max_issues_repo_head_hexsha": "8cbbfa0e40e4d4a75a498ce8dd894bb2fbc3a9e3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 69.0, "max_issues_repo_issues_event_min_datetime": "2017-04-26T09:30:38.000Z", "max_issues_repo_issues_event_max_datetime": "2017-08-01T11:31:21.000Z", "max_forks_repo_path": "Jung/ex8/ex8.cpp", "max_forks_repo_name": "appfs/appfs", "max_forks_repo_head_hexsha": "8cbbfa0e40e4d4a75a498ce8dd894bb2fbc3a9e3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 53.0, "max_forks_repo_forks_event_min_datetime": "2017-04-20T16:16:11.000Z", "max_forks_repo_forks_event_max_datetime": "2017-07-19T12:53:01.000Z", "avg_line_length": 18.85, "max_line_length": 131, "alphanum_fraction": 0.6504440088, "num_tokens": 2480, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6261241632752916, "lm_q2_score": 0.538983220687684, "lm_q1q2_score": 0.337470418072498}}
{"text": "//============================================================================\n// Name        : minimacro.cpp\n// Author      : wilfeli\n// Version     :\n// Copyright   : Your copyright notice\n// Description : Minimacro model in C++, Ansi-style\n//============================================================================\n\n#include <iostream>\n#include <fstream>\n#include <string>\n#include <map>\n#include <Eigen/Dense>\n\n#include \"W.h\"\n#include \"Parameters.h\"\n#include \"H.h\"\n#include \"F.h\"\n#include \"Market.h\"\n\n\nusing namespace std;\n\n\n\nvoid\nsave_history(W& w, int N, std::string file_path){\n\t//saves history\n\t//parameters of the simulation\n\n\tstd::string file_path_default;\n\tstd::string file_name;\n\n    \n    \n    if (file_path.empty()){\n        file_path = file_path_default;\n    };\n\n\tint i = 0;\n\t//read current number of iterations\n\tfile_name = file_path + \"HF_i.txt\";\n\tstd::ifstream in_file(file_name);\n\n\tstd::string I_NUMBER;\n    \n    if (in_file){\n        std::getline(in_file, I_NUMBER);\n    }else{\n        I_NUMBER = \"0\";\n    };\n\tin_file.close();\n\n\tstd::ofstream out_file(file_name);\n\tout_file << std::to_string(std::stoi(I_NUMBER) + 1) << std::endl;\n    out_file.close();\n\n\n\tfile_name = file_path + \"HF_param_\" + I_NUMBER + \".txt\";\n\tout_file.open(file_name);\n\n\tif (out_file){\n\t\t//save number of H\n\t\t//save number of F\n\t\tout_file << \"number of humans: \"<< w.NH << std::endl;\n\t\tout_file << \"number of firms: \"<< w.NFGC << std::endl;\n\t\tout_file << \"F wm length: \" << w.param->F_wm_LENGTH << std::endl;\n\t\tout_file << \"H wm length: \" << w.param->H_wm_LENGTH << std::endl;\n\t\tout_file << \"F type: \" << w.Fs.back()->param->opt_TYPE << std::endl;\n\t\tout_file << \"H type: \" << w.Hs.back()->param->opt_TYPE << std::endl;\n\t\tout_file << \"seed: \" << w.param->W_SEED << std::endl;\n\t\tout_file << \"F forecasting length: \" << w.param->F_T_MAX << std::endl;\n\t\tout_file << \"H forecasting length: \" << w.param->H_T_MAX << std::endl;\n\t\tout_file << \"F production function parameters: \" << w.param->F_F_F_theta << std::endl;\n\t\tout_file << \"H utility function parameters: \" << w.param->H_GOAL_T_theta << std::endl;\n\t\tout_file << \"F mRe Phi: \" << w.param->F_mRE_PHI << std::endl;\n\t\tout_file << \"H mRe Phi: \" << w.param->H_mRE_PHI << std::endl;\n\t\tout_file << \"F QL L: \" << w.param->F_QL_L << std::endl;\n\t\tout_file << \"H QL L: \" << w.param->H_QL_L << std::endl;\n\t\tout_file << \"F Grid: \" << w.param->F_GRID << std::endl;\n\t\tout_file << \"H Grid: \" << w.param->H_GRID << std::endl;\n        \n\n\t\ti = 0;\n\n\t\tfor (auto a:w.Fs){\n\t\t\tif (a->status > 0.0){\n\t\t\t\ti++;\n\t\t\t};\n\t\t};\n\n\t\tout_file << \"End number of F:\" << i << std::endl;\n\n\t};\n\n\tout_file.close();\n    \n    Eigen::IOFormat CleanFmt(Eigen::StreamPrecision, 0, \", \", \"\\n\");\n\n\tfile_name = file_path + \"HF_data_\" + I_NUMBER + \".txt\";\n\tout_file.open(file_name);\n\t//save prices of the market\n\tEigen::MatrixXd data_all(N, 5);\n\tdata_all = Eigen::MatrixXd::Zero(N, 5);\n\t//employment, sales on goods market, production, price on labor market,\n\t//price on goods market\n\n\n\tfor (auto a:w.Hs){\n\t\tdata_all.col(0) += Eigen::VectorXd::Map(a->account->asCHK_q.data(),(long)a->account->asCHK_q.size());\n\t\tdata_all.col(1) += Eigen::VectorXd::Map(a->account->asGC_q.data(),(long)a->account->asGC_q.size());\n\t};\n\n\tfor (auto a:w.Fs){\n        if (a->status > 0.0){\n            data_all.col(2) += Eigen::VectorXd::Map(a->account->production_q.data(),(long)a->account->production_q.size());\n        };\n\t};\n\n\n\tfor (int j = 0; j < N; ++j){\n\t\tdata_all(j,3) = w.ml->market_price[j]->p;\n\t\tdata_all(j,4) = w.mc->market_price[j]->p;\n\n\t};\n\tif (out_file){\n\t\tout_file << data_all.format(CleanFmt);\n\t};\n\n//\tcout << data_all;\n\tout_file.close();\n\n\n\tfile_name = file_path + \"HF_data_all_H_\" + I_NUMBER + \".txt\";\n\tEigen::MatrixXd h_all(N, w.NH);\n\ti = 0;\n\tfor (auto a:w.Hs){\n\t\th_all.col(i) = Eigen::VectorXd::Map(a->account->g_t.data(),(long)a->account->g_t.size());\n\t\ti++;\n\n\t};\n\n    out_file.open(file_name);\n\tif (out_file){\n\t\tout_file << h_all.format(CleanFmt);;\n\t};\n\tout_file.close();\n\n\tfile_name = file_path + \"HF_data_all_F_\" + I_NUMBER + \".txt\";\n\tEigen::MatrixXd f_all(N, w.NFGC);\n\ti = 0;\n\tfor (auto a:w.Fs){\n\t\tf_all.col(i) = Eigen::VectorXd::Map(a->account->profit.data(),(long)a->account->profit.size());\n\t\ti++;\n\n\t};\n    out_file.open(file_name);\n\tif (out_file){\n\t\tout_file << f_all.format(CleanFmt);\n\t};\n\tout_file.close();\n\n\n};\n\n\nvoid\nread_init(double& seed_, int& N_, std::map <std::string, std::string> &ini, std::string file_name){\n\tstd::string file_path_default;\n\tstd::string file_name_default;\n    \n\n\t//open ini file\n\tfile_name_default = \"minimacro.ini\";\n    \n    if (file_name.empty()){\n        file_name = file_name_default;\n    };\n    \n\tstd::ifstream in_file(file_name);\n    \n\tstd::string s, key, value;\n\n    \n    while (std::getline( in_file, s )){\n        // Extract the key value\n        std::string::size_type begin = s.find_first_not_of( \" \\f\\t\\v\" );\n        std::string::size_type end = s.find( '=', begin );\n        key = s.substr( begin, end - begin );\n        \n        // (No leading or trailing whitespace allowed)\n        key.erase( key.find_last_not_of( \" \\f\\t\\v\" ) + 1 );\n        \n        // No blank keys allowed\n        if (key.empty()) continue;\n        \n        // Extract the value (no leading or trailing whitespace allowed)\n        begin = s.find_first_not_of( \" \\f\\n\\r\\t\\v\", end + 1 );\n        end   = s.find_last_not_of(  \" \\f\\n\\r\\t\\v\" ) + 1;\n        \n        value = s.substr( begin, end - begin );\n        ini[key] = value;\n\n//        std::cout << s << \" \" << key << \" \" << value << std::endl;\n\t};\n    in_file.close();\n\n    //set ini values\n    N_ = std::stoi(ini[\"N\"]);\n    seed_ = std::stoi(ini[\"seed\"]);\n    \n};\n\n\nint main(int argc, char *argv[]) {\n    //path to ini file\n    //argv[1] path to ini file\n    //argv[2] path to save directory\n    \n    std::string file_ini_name;\n    std::string file_path;\n    //path to save directory\n    if (argc > 2){\n        file_path = argv[2];\n    };\n    \n    if (argc > 1){\n        file_ini_name = argv[1];\n    };\n    \n\t//seed\n\tdouble seed = 2013;\n\n    //number of steps\n    int N = 100;\n    std::map <std::string, std::string> simulation_ini;\n\n    read_init(seed, N, simulation_ini, file_ini_name);\n    \n\n\t//create world\n\tW w(seed);\n\n\n\tw.NH = 10;\n\tw.NFGC = 3;\n\tw.NCB = 1;\n\n//\tw.param->F_F_F_theta << ?, ?;\n//\tw.param->H_GOAL_T_theta << ?, ?;\n    \n    w.param->SIMULATION_MODE = simulation_ini[\"SIMULATION_MODE\"];\n    w.param->F_T_MAX = std::stoi(simulation_ini[\"F_T_MAX\"]);\n    w.param->H_T_MAX = std::stoi(simulation_ini[\"H_T_MAX\"]);\n    w.param->F_opt_CS_N = std::stoi(simulation_ini[\"F_opt_CS_N\"]);\n    w.param->H_opt_CS_N = std::stoi(simulation_ini[\"H_opt_CS_N\"]);\n    \n    std::string wm_length;\n    wm_length = simulation_ini[\"F_wm_LENGTH\"];\n    if (wm_length == \"inf\"){\n        w.param->F_wm_LENGTH = std::numeric_limits<double>::infinity();;\n    }else{\n        w.param->F_wm_LENGTH = std::stod(simulation_ini[\"F_wm_LENGTH\"]);\n    };\n    wm_length = simulation_ini[\"H_wm_LENGTH\"];\n    if (wm_length == \"inf\"){\n        w.param->H_wm_LENGTH = std::numeric_limits<double>::infinity();;\n    }else{\n        w.param->H_wm_LENGTH = std::stod(simulation_ini[\"H_wm_LENGTH\"]);\n    };\n        \n\n    w.param->F_GRID = simulation_ini[\"F_GRID\"];\n    w.param->H_GRID = simulation_ini[\"H_GRID\"];\n    \n    //decision type\n    w.param->F_opt_TYPE = simulation_ini[\"F_opt_TYPE\"];\n    w.param->H_opt_TYPE = simulation_ini[\"H_opt_TYPE\"];\n\n    //QL parameters\n    w.param->F_QL_L = std::stod(simulation_ini[\"F_QL_L\"]);\n    w.param->H_QL_L = std::stod(simulation_ini[\"H_QL_L\"]);\n    \n    //mRe parameters\n//    w.param->F_mRE_EPSILON = std::stod(simulation_ini[\"F_mRE_EPSILON\"]);\n//    w.param->H_mRE_EPSILON = std::stod(simulation_ini[\"H_mRE_EPSILON\"]);\n//    w.param->F_mRE_T = std::stod(simulation_ini[\"F_mRE_T\"]);\n//    w.param->H_mRE_T = std::stod(simulation_ini[\"H_mRE_T\"]);\n    w.param->F_mRE_PHI = std::stod(simulation_ini[\"F_mRE_PHI\"]);\n    w.param->H_mRE_PHI = std::stod(simulation_ini[\"H_mRE_PHI\"]);\n    \n    w.param->F_ACCOUNTING_TYPE = simulation_ini[\"F_ACCOUNTING_TYPE\"];\n    \n    \n    if (simulation_ini.find(\"NH\") != simulation_ini.end()){\n        w.NH = std::stoi(simulation_ini[\"NH\"]);\n    };\n\n    if (simulation_ini.find(\"NFGC\") != simulation_ini.end()){\n        w.NFGC = std::stoi(simulation_ini[\"NFGC\"]);\n    };\n\n    if (simulation_ini.find(\"NCB\") != simulation_ini.end()){\n        w.NCB = std::stoi(simulation_ini[\"NCB\"]);\n    };\n\n    \n    \n\tw.init();\n\n\tfor (int i=0; i<N; ++i){\n\t\tw.step();\n//        std::cout << i << \" \";\n//        w.print_step();\n\t};\n\n\n//\tw.print_step();\n\n\tsave_history(w, N, file_path);\n\n\n\treturn 0;\n};\n\n\n\n\n\n\n", "meta": {"hexsha": "143288c9a61342b4a32f45aa91aad99cafa383e2", "size": 8595, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/minimacro.cpp", "max_stars_repo_name": "wilfeli/DMGameBasic", "max_stars_repo_head_hexsha": "ccc5e7ba08ee4e1959c60421692540cafb1faeed", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2017-08-11T23:12:44.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-04T08:54:19.000Z", "max_issues_repo_path": "src/minimacro.cpp", "max_issues_repo_name": "wilfeli/DMGameBasic", "max_issues_repo_head_hexsha": "ccc5e7ba08ee4e1959c60421692540cafb1faeed", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/minimacro.cpp", "max_forks_repo_name": "wilfeli/DMGameBasic", "max_forks_repo_head_hexsha": "ccc5e7ba08ee4e1959c60421692540cafb1faeed", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-08-02T20:23:21.000Z", "max_forks_repo_forks_event_max_datetime": "2020-08-02T20:23:21.000Z", "avg_line_length": 25.9667673716, "max_line_length": 123, "alphanum_fraction": 0.5872018615, "num_tokens": 2525, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.600188359260205, "lm_q2_score": 0.5621765008857981, "lm_q1q2_score": 0.3374117916812903}}
{"text": "#pragma once\n\n#include <Eigen/Dense>\n#include <algorithm>\n\n// own includes -------------------------------------------------\n#include \"base/array_buffer.hpp\"\n#include \"h2n_1d.hpp\"\n\nnamespace boltzmann {\ntemplate <typename BASIS, typename NUMERIC_T = double>\nclass Hermite2Nodal\n{\n public:\n  typedef NUMERIC_T numeric_t;\n  typedef Eigen::Matrix<numeric_t, Eigen::Dynamic, Eigen::Dynamic, Eigen::ColMajor> matrix_t;\n\n public:\n  /**\n   *\n   *\n   * @param basis  Hermite basis\n   * @param K      max poly. degree\n   * @param init   functor to initialize the 1d trafo matrix (initializers can\n   * be found in\n   * h2n_1d.hpp)\n   */\n  template <typename INITIALIZER>\n  Hermite2Nodal(const BASIS &basis, const int K, const INITIALIZER &init);\n\n  /**\n   * @brief Transform from Nodal to Hermite basis.\n   *\n   * Also see @ref to_nodal ,\n   *\n   * @param dst Hermite coefficients ordered according to @ref basis.\n   * @param src Nodal coefficients, \\f$ src(i,j) = f(x_j, y_i) \\f$.\n   * @param transpose defaults to false, true is ``experimental''\n   *\n   *\n   */\n  template <typename MATRIX>\n  void to_hermite(numeric_t *dst, const MATRIX &src, bool transpose = false) const;\n\n  template <typename DERIVED, typename DERIVED2>\n  void to_hermite(Eigen::DenseBase<DERIVED> &dst,\n                  const Eigen::DenseBase<DERIVED2> &src,\n                  bool transpose = false) const;\n\n  /**\n   * @brief Transform from Hermite to Nodal basis.\n   *\n   * @param dst Output Nodal coefficients dst(i,j) correpsonds to nodes \\f$ x_i,\n   * y_j\\f$.\n   * @param c   Hermite coefficients in @ref basis\n   * @param tranpose: defaults to false, true is ``experimental''\n   *\n   *\n   * Internally the Hermite coefficients are arranged like so:\n   * @remark{\n   *\n   *     H[deg(y), deg(x)] = c_(iy, ix)\n   * }\n   *\n   */\n  template <typename MATRIX>\n  void to_nodal(MATRIX &dst, const numeric_t *c, bool transpose = false) const;\n\n  template <typename DERIVED, typename DERIVED2>\n  void to_nodal(Eigen::DenseBase<DERIVED> &dst,\n                const Eigen::DenseBase<DERIVED2> &src,\n                bool transpose = false) const;\n\n  const matrix_t &get_n2h() const { return N2H_; }\n  const matrix_t &get_h2n() const { return H2N_; }\n\n private:\n  std::vector<unsigned int> perm_;\n  int K_;\n\n  matrix_t N2H_;\n  matrix_t H2N_;\n  thread_local static ::ArrayBuffer<> buf_;\n\n  BASIS hbasis_;\n};\n\ntemplate <typename BASIS, typename NUMERIC_T>\nthread_local ::ArrayBuffer<> Hermite2Nodal<BASIS, NUMERIC_T>::buf_;\n\n// ----------------------------------------------------------------------\ntemplate <typename BASIS, typename NUMERIC_T>\ntemplate <typename INITIALIZER>\nHermite2Nodal<BASIS, NUMERIC_T>::Hermite2Nodal(const BASIS &basis,\n                                               const int K,\n                                               const INITIALIZER &init)\n    : K_(K)\n    , hbasis_(basis)\n{\n  buf_.reserve(K * K);\n  // initialize the 1d transformation matrix\n  init(H2N_, N2H_);\n\n  typedef typename BASIS::elem_t elem_t;\n  typedef typename boost::mpl::at_c<typename elem_t::types_t, 0>::type hx_t;\n  typedef typename boost::mpl::at_c<typename elem_t::types_t, 1>::type hy_t;\n\n  typename elem_t::Acc::template get<hx_t> get_hx;\n  typename elem_t::Acc::template get<hy_t> get_hy;\n\n  // max degree\n  unsigned int max_kx =\n      get_hx(*std::max_element(basis.begin(),\n                               basis.end(),\n                               [&](const elem_t &e1, const elem_t &e2) {\n                                 return get_hx(e1).get_id().k < get_hx(e2).get_id().k;\n                               }))\n          .get_id()\n          .k;\n  unsigned int max_ky =\n      get_hy(*std::max_element(basis.begin(),\n                               basis.end(),\n                               [&](const elem_t &e1, const elem_t &e2) {\n                                 return get_hy(e1).get_id().k < get_hy(e2).get_id().k;\n                               }))\n          .get_id()\n          .k;\n\n  assert(max_kx == max_ky);\n\n  unsigned int stride = K;\n  perm_.resize(hbasis_.n_dofs());\n  // build permutation vector\n  unsigned int i = 0;\n  for (auto elem = basis.begin(); elem < basis.end(); ++elem, ++i) {\n    unsigned int kx = get_hx(*elem).get_id().k;\n    unsigned int ky = get_hy(*elem).get_id().k;\n    perm_[i] = kx * stride + ky;\n  }\n}\n\n// ----------------------------------------------------------------------\ntemplate <typename BASIS, typename NUMERIC_T>\ntemplate <typename MATRIX>\nvoid\nHermite2Nodal<BASIS, NUMERIC_T>::to_nodal(MATRIX &dst, const numeric_t *c, bool transpose) const\n{\n  auto TMP = buf_.get<matrix_t>(K_, K_);\n\n  if (!transpose) {\n    TMP.fill(0);\n    numeric_t *data = TMP.data();\n    for (unsigned int i = 0; i < hbasis_.n_dofs(); ++i) {\n      data[perm_[i]] = c[i];\n    }\n    //  const auto& T = h2n_.get_matrix();\n    const auto &T = H2N_;\n    dst = T * TMP * T.transpose();\n  } else {\n    // ATTENTION: untested!\n    TMP.fill(0);\n    numeric_t *data = TMP.data();\n    for (unsigned int i = 0; i < hbasis_.n_dofs(); ++i) {\n      data[perm_[i]] = c[i];\n    }\n    const auto &T = H2N_;\n    dst = T.transpose() * TMP * T;\n  }\n}\n\n// -----------------------------------------------------------------------\ntemplate <typename BASIS, typename NUMERIC_T>\ntemplate <typename DERIVED, typename DERIVED2>\nvoid\nHermite2Nodal<BASIS, NUMERIC_T>::to_nodal(Eigen::DenseBase<DERIVED> &dst,\n                                          const Eigen::DenseBase<DERIVED2> &c,\n                                          bool transpose) const\n{\n  auto TMP = buf_.get<matrix_t>(K_, K_);\n\n  if (!transpose) {\n    TMP.fill(0);\n    numeric_t *data = TMP.data();\n    for (unsigned int i = 0; i < hbasis_.n_dofs(); ++i) {\n      data[perm_[i]] = c[i];\n    }\n    //  const auto& T = h2n_.get_matrix();\n    const auto &T = H2N_;\n    dst = T * TMP * T.transpose();\n  } else {\n    // ATTENTION: untested!\n    TMP.fill(0);\n    numeric_t *data = TMP.data();\n    for (unsigned int i = 0; i < hbasis_.n_dofs(); ++i) {\n      data[perm_[i]] = c[i];\n    }\n    const auto &T = H2N_;\n    dst = T.transpose() * TMP * T;\n  }\n}\n\n// ----------------------------------------------------------------------\ntemplate <typename BASIS, typename NUMERIC_T>\ntemplate <typename MATRIX>\nvoid\nHermite2Nodal<BASIS, NUMERIC_T>::to_hermite(numeric_t *dst, const MATRIX &src, bool transpose) const\n{\n  auto TMP = buf_.get<matrix_t>(K_, K_);\n  if (!transpose) {\n    const auto &T = N2H_;\n    TMP = T * src * T.transpose();\n    // undo permuation\n    for (unsigned int i = 0; i < hbasis_.n_dofs(); ++i) {\n      dst[i] = TMP.data()[perm_[i]];\n    }\n  } else {\n    // ATTENTION: untested!\n    const auto &T = N2H_;\n    TMP = T.transpose() * src * T;\n\n    numeric_t *data = TMP.data();\n    for (unsigned int i = 0; i < hbasis_.n_dofs(); ++i) {\n      dst[i] = data[perm_[i]];\n    }\n  }\n}\n\n// ----------------------------------------------------------------------\ntemplate <typename BASIS, typename NUMERIC_T>\ntemplate <typename DERIVED, typename DERIVED2>\nvoid\nHermite2Nodal<BASIS, NUMERIC_T>::to_hermite(Eigen::DenseBase<DERIVED> &dst,\n                                            const Eigen::DenseBase<DERIVED2> &src,\n                                            bool transpose) const\n{\n  auto TMP = buf_.get<matrix_t>(K_, K_);\n  if (!transpose) {\n    const auto &T = N2H_;\n    TMP = T * src.derived() * T.transpose();\n    // undo permuation\n    for (unsigned int i = 0; i < hbasis_.n_dofs(); ++i) {\n      dst[i] = TMP.data()[perm_[i]];\n    }\n  } else {\n    // ATTENTION: untested!\n    const auto &T = N2H_;\n    TMP = T.transpose() * src.derived() * T;\n\n    numeric_t *data = TMP.data();\n    for (unsigned int i = 0; i < hbasis_.n_dofs(); ++i) {\n      dst[i] = data[perm_[i]];\n    }\n  }\n}\n\n}  // end namespace boltzmann\n", "meta": {"hexsha": "20167bdf54493b880e515a36cdad8431fa54c01a", "size": 7741, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "spectral/hermite_to_nodal.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": "spectral/hermite_to_nodal.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": "spectral/hermite_to_nodal.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": 30.1206225681, "max_line_length": 100, "alphanum_fraction": 0.5552254231, "num_tokens": 2145, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.600188359260205, "lm_q2_score": 0.5621765008857981, "lm_q1q2_score": 0.3374117916812903}}
{"text": "/*\n  Copyright 2012-2014 Joshua Nathaniel Pritikin and contributors\n\n  libifa-rpf 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 <R.h>\n#include <R_ext/BLAS.h>\n#include <stdlib.h>\n#include <math.h>\n#include <string.h>\n#include \"libifa-rpf.h\"\n#include <Eigen/Core>\n\n#ifndef M_LN2\n#define M_LN2           0.693147180559945309417232121458        /* ln(2) */\n#endif\n\n#ifndef M_LN_SQRT_PI\n#define M_LN_SQRT_PI    0.572364942924700087071713675677        /* log(sqrt(pi))\n                                                                   == log(pi)/2 */\n#endif\n\nstatic const double EXP_STABLE_DOMAIN = 35;\nstatic const double SMALLEST_PROB = 6.305116760146989222002e-16;  // exp(-35), need constexpr\n\nstatic void\nirt_rpf_logprob_adapter(const double *spec,\n\t\t\tconst double *param, const double *th,\n\t\t\tdouble *out)\n{\n  (*librpf_model[(int) spec[RPF_ISpecID]].prob)(spec, param, th, out);\n\n  int numOutcomes = spec[RPF_ISpecOutcomes];\n  for (int ox=0; ox < numOutcomes; ox++) {\n    out[ox] = log(out[ox]);\n  }\n}\n\nstatic double\ndotprod(const double *v1, const double *v2, const int len)\n{\n  double dprod = 0;\n  for (int dx=0; dx < len; dx++) {\n    dprod += v1[dx] * v2[dx];\n  }\n  return dprod;\n}\n\nstatic int\nhessianIndex(int numParam, int row, int col)\n{\n  return numParam + row*(row+1)/2 + col;\n}\n\nstatic double antilogit(const double x)\n{\n    if (x == INFINITY) return 1.0;\n    else if(x == -INFINITY) return 0.0;\n    else return 1.0 / (1.0 + exp(-x));\n}\n\nstatic int\nirt_rpf_1dim_drm_numSpec(const double *spec)\n{ return RPF_ISpecCount; }\n\nstatic int\nirt_rpf_1dim_drm_numParam(const double *spec)\n{ return 4; }\n\nstatic void\nirt_rpf_1dim_drm_prob(const double *spec,\n\t\t      const double *param, const double *th,\n\t\t      double *out)\n{\n  double guessing = param[2];\n  double upper = param[3];\n  double athb = -param[0] * (th[0] - param[1]);\n  if (athb < -EXP_STABLE_DOMAIN) athb = -EXP_STABLE_DOMAIN;\n  else if (athb > EXP_STABLE_DOMAIN) athb = EXP_STABLE_DOMAIN;\n  double pp = guessing + (upper-guessing) / (1 + exp(athb));\n  out[0] = 1-pp;\n  out[1] = pp;\n}\n\nstatic void\nset_deriv_nan(const double *spec, double *out)\n{\n  int numParam = (*librpf_model[(int) spec[RPF_ISpecID]].numParam)(spec);\n\n  for (int px=0; px < numParam; px++) {\n    out[px] = nan(\"I\");\n  }\n}\n\nstatic void\nirt_rpf_1dim_drm_rescale(const double *spec, double *param, const int *paramMask,\n\t\t\t const double *mean, const double *cov)\n{\n  double thresh = param[1] * -param[0];\n  if (paramMask[0] >= 0) {\n    param[0] *= cov[0];\n  }\n  if (paramMask[1] >= 0) {\n    thresh += param[0] * mean[0];\n    param[1] = thresh / -param[0];\n  }\n}\n\nstatic int\nirt_rpf_mdim_drm_numSpec(const double *spec)\n{ return RPF_ISpecCount; }\n\nstatic int\nirt_rpf_mdim_drm_numParam(const double *spec)\n{\n\tif (spec[RPF_ISpecDims] == 0) return 1;\n\telse return 3 + spec[RPF_ISpecDims];\n}\n\nstatic void\nirt_rpf_mdim_drm_paramInfo(const double *spec, const int param,\n\t\t\t   const char **type, double *upper, double *lower)\n{\n\tint numDims = spec[RPF_ISpecDims];\n\t*upper = nan(\"unset\");\n\t*lower = nan(\"unset\");\n\tif (numDims == 0) {\n\t\t*type = \"intercept\";\n\t\treturn;\n\t}\n\t*type = NULL;\n\tif (param >= 0 && param < numDims) {\n\t\t*type = \"slope\";\n\t\t*lower = 1e-6;\n\t} else if (param == numDims) {\n\t\t*type = \"intercept\";\n\t} else if (param == numDims+1 || param == numDims+2) {\n\t\t*type = \"bound\";\n\t}\n}\n\nstatic void\nirt_rpf_mdim_drm_prob(const double *spec,\n\t\t      const double *param, const double *th,\n\t\t      double *out)\n{\n  int numDims = spec[RPF_ISpecDims];\n  double dprod = dotprod(param, th, numDims);\n  double diff = param[numDims];\n  double athb = -(dprod + diff);\n  if (athb < -EXP_STABLE_DOMAIN) athb = -EXP_STABLE_DOMAIN;\n  else if (athb > EXP_STABLE_DOMAIN) athb = EXP_STABLE_DOMAIN;\n  double tmp;\n  if (numDims == 0) {\n\t  tmp = 1/(1+exp(athb));\n  } else {\n\t  const double gg = antilogit(param[numDims+1]);\n\t  const double uu = antilogit(param[numDims+2]);\n\t  const double width = uu-gg;\n\t  if (width < 0) tmp = nan(\"I\");\n\t  else {\n\t\t  tmp = gg + width / (1 + exp(athb));\n\t  }\n  }\n  out[0] = 1-tmp;\n  out[1] = tmp;\n}\n\nstatic void\nirt_rpf_mdim_drm_prob2(const double *spec,\n\t\t       const double *param, const double *th,\n\t\t       double *out1, double *out2)\n{\n  int numDims = spec[RPF_ISpecDims];\n  double dprod = dotprod(param, th, numDims);\n  double diff = param[numDims];\n  double athb = -(dprod + diff);\n  if (athb < -EXP_STABLE_DOMAIN) athb = -EXP_STABLE_DOMAIN;\n  else if (athb > EXP_STABLE_DOMAIN) athb = EXP_STABLE_DOMAIN;\n  double tmp = 1 / (1 + exp(athb));\n  out1[0] = 1-tmp;\n  out1[1] = tmp;\n  if (numDims) {\n\t  const double gg = antilogit(param[numDims+1]);\n\t  const double uu = antilogit(param[numDims+2]);\n\t  tmp = gg + (uu-gg) * tmp;\n  }\n  out2[0] = 1-tmp;\n  out2[1] = tmp;\n}\n\nstatic void\nirt_rpf_mdim_drm_deriv1(const double *spec,\n\t\t       const double *param,\n\t\t       const double *where,\n\t\t       const double *weight, double *out)\n{\n  const int numDims = spec[RPF_ISpecDims];\n  double QP[2];\n  double QPstar[2];\n  irt_rpf_mdim_drm_prob2(spec, param, where, QPstar, QP);\n  const double r1 = weight[1];\n  const double r2 = weight[0];\n  const double r1_P = r1/QP[1];\n  const double r1_P2 = r1/(QP[1] * QP[1]);\n  const double r2_Q = r2/QP[0];\n  const double r2_Q2 = r2/(QP[0] * QP[0]);\n  const double r1_Pr2_Q = (r1_P - r2_Q);\n  const double Pstar = QPstar[1];\n  const double Pstar2 = Pstar * Pstar;\n  const double Pstar3 = Pstar2 * Pstar;\n  const double Qstar = QPstar[0];\n  if (numDims == 0) {\n\t  out[0] -= Pstar * Qstar * r1_Pr2_Q;\n\t  double chunk1 = (Pstar - Pstar2);\n\t  out[1] -= (r1_P * ((Pstar - 3*Pstar2 + 2*Pstar3)) -\n\t\t     r1_P2 * chunk1*chunk1 +\n\t\t     r2_Q * ((-Pstar + 3*Pstar2 - 2*Pstar3)) -\n\t\t     r2_Q2 * chunk1*chunk1);   // cc^2\n\t  return;\n  }\n  const double expgg = param[numDims+1];\n  const double expuu = param[numDims+2];\n  const double gg = antilogit(expgg);\n  const double uu = antilogit(expuu);\n  const double difexpgg = gg * (1-gg);\n  const double difexpuu = uu * (1-uu);\n  const double gm1 = (1.0 - gg);\n  const double um1 = (1.0 - uu);\n  const double u_1u = uu * um1;\n  const double g_1g = gg * gm1;\n  const double ugD = (uu-gg);\n  for (int dx=0; dx < numDims; dx++) {\n    out[dx] -= where[dx] * Pstar * Qstar * ugD * r1_Pr2_Q;\n  }\n  out[numDims] -= ugD * Pstar * Qstar * r1_Pr2_Q;\n  out[numDims+1] -= difexpgg * QPstar[0] * r1_Pr2_Q;\n  out[numDims+2] -= difexpuu * QPstar[1] * r1_Pr2_Q;\n\n  int ox = numDims+2;\n\n  for(int ix=0; ix < numDims; ix++) {\n    for(int jx=0; jx <= ix; jx++) {\n      out[++ox] -= (r1_P * (ugD * where[ix] * where[jx] *\n\t\t\t\t   (Pstar - 3*Pstar2 + 2*Pstar3)) -\n\t\t\t   r1_P2 * (ugD * where[ix] * (Pstar - Pstar2) *\n\t\t\t\t    (ugD * where[jx] * (Pstar - Pstar2))) +\n\t\t\t   r2_Q * (ugD * where[ix] * where[jx] *\n\t\t\t\t   (-Pstar + 3*Pstar2 - 2*Pstar3)) -\n\t\t\t   r2_Q2 * (ugD * where[ix] * (-Pstar + Pstar2) *\n\t\t\t\t    (ugD * where[jx] * (-Pstar + Pstar2))));  // aa_k aa_k\n    }\n  }\n  for(int ix=0; ix < numDims; ix++) {\n    out[++ox] -= (r1_P * (ugD * where[ix] * (Pstar - 3*Pstar2 + 2*Pstar3)) -\n\t\t\t r1_P2 * (ugD * where[ix] * (Pstar - Pstar2) *\n\t\t\t\t  (ugD * (Pstar - Pstar2))) +\n\t\t\t r2_Q * (ugD * where[ix] * (-Pstar + 3*Pstar2 - 2*Pstar3)) -\n\t\t\t r2_Q2 * (ugD * where[ix] * (-Pstar + Pstar2) *\n\t\t\t\t  (ugD * (-Pstar + Pstar2))));  // cc aa_k\n  }\n  double chunk1 = ugD * (Pstar - Pstar2);\n  out[++ox] -= (r1_P * (ugD * (Pstar - 3*Pstar2 + 2*Pstar3)) -\n\t\tr1_P2 * chunk1*chunk1 +\n\t\tr2_Q * (ugD * (-Pstar + 3*Pstar2 - 2*Pstar3)) -\n\t\tr2_Q2 * chunk1*chunk1);   // cc^2\n  for(int ix=0; ix < numDims; ix++) {\n\t  out[++ox] -= (r1_P * (g_1g * where[ix] * (-Pstar + Pstar2)) -\n\t\t  r1_P2 * (ugD * where[ix] * (Pstar - Pstar2)) * g_1g * Qstar +\n\t\t  r2_Q * (g_1g * where[ix] * (Pstar - Pstar2)) -\n\t\t  r2_Q2 * (ugD * where[ix] * (-Pstar + Pstar2) ) * g_1g * (Pstar - 1));   // gg aa_k\n  }\n  out[++ox] -= (r1_P * (g_1g * (-Pstar + Pstar2)) -\n\t\tr1_P2 * (ugD * (Pstar - Pstar2)) * g_1g * Qstar +\n\t\tr2_Q * (g_1g * (Pstar - Pstar2)) -\n\t\tr2_Q2 * (ugD * (-Pstar + Pstar2)) * g_1g * -Qstar);  // gg cc\n  out[++ox] -= (r1_P * (g_1g * (2.0*gm1 - 1.0 - 2.0*gm1*Pstar + Pstar)) -\n\t\tr1_P2 * (g_1g * (1.0 - Pstar)) * (g_1g * (1.0 - Pstar)) +\n\t\tr2_Q * (g_1g * (-2.0*gm1 + 1.0 + 2.0*gm1*Pstar - Pstar)) -\n\t\tr2_Q2 * (g_1g * (-1.0 + Pstar)) * (g_1g * (-1.0 + Pstar)));  // gg^2\n\n  for(int ix=0; ix < numDims; ix++) {\n    out[++ox] -= (r1_P * (u_1u * where[ix] * (Pstar - Pstar2)) -\n\t\t  r1_P2 * (ugD * where[ix] * (Pstar - Pstar2)) * u_1u * Pstar +\n\t\t  r2_Q * (u_1u * where[ix] * (-Pstar + Pstar2)) +\n\t\t  r2_Q2 * (ugD * where[ix] * (-Pstar + Pstar2) ) * u_1u * Pstar);  // uu aa_k\n  }\n\n  out[++ox] -= (r1_P * (u_1u * (Pstar - Pstar2)) -\n\t\tr1_P2 * (ugD * (Pstar - Pstar2)) * u_1u * Pstar +\n\t\tr2_Q * (u_1u * (-Pstar + Pstar2)) +\n\t\tr2_Q2 * (ugD * (-Pstar + Pstar2)) * u_1u * Pstar);  // uu cc\n\n  out[++ox] -= (-r1_P2 * (g_1g * (1.0 - Pstar)) * u_1u * Pstar +\n\t\tr2_Q2 * (g_1g * (-1.0 + Pstar)) * u_1u * Pstar);  // uu gg\n  out[++ox] -=  (r1_P * (2.0*u_1u*um1*Pstar) - r1_P * (u_1u*Pstar) - r1_P2 *(u_1u*u_1u*Pstar2) -\n\t\t r2_Q * (2.0*u_1u*um1*Pstar) + r2_Q * (u_1u*Pstar) - r2_Q2 *(u_1u*u_1u*Pstar2));  // uu^2\n}\n\nstatic void\nirt_rpf_mdim_drm_deriv2(const double *spec,\n\t\t\tconst double *param,\n\t\t\tdouble *out)\n{\n  int numDims = spec[RPF_ISpecDims];\n  if (numDims == 0) return;\n  const double *aa = param;\n  double gg = param[numDims+1];\n  double uu = param[numDims+2];\n\n  for (int dx=0; dx < numDims; dx++) {\n    if (aa[dx] < 0) {\n      set_deriv_nan(spec, out);\n      return;\n    }\n  }\n  if (gg == -INFINITY) {\n    out[numDims+1] = nan(\"I\");\n  }\n  if (uu == INFINITY) {\n    out[numDims+2] = nan(\"I\");\n  }\n  if (gg > uu) {\n    out[numDims+1] = nan(\"I\");\n    out[numDims+2] = nan(\"I\");\n  }\n}\n\nstatic void\nirt_rpf_mdim_drm_rescale(const double *spec, double *param, const int *paramMask,\n\t\t\t const double *mean, const double *cov)\n{\n  int numDims = spec[RPF_ISpecDims];\n\n  double madj = dotprod(param, mean, numDims);\n\n  for (int d1=0; d1 < numDims; d1++) {\n    if (paramMask[d1] < 0) continue;\n    param[d1] = dotprod(param+d1, cov + d1 * numDims + d1, numDims-d1);\n  }\n\n  param[numDims] += madj;\n}\n\nstatic void\nirt_rpf_mdim_drm_dTheta(const double *spec, const double *param,\n\t\t\tconst double *where, const double *dir,\n\t\t\tdouble *grad, double *hess)\n{\n  int numDims = spec[RPF_ISpecDims];\n  double PQ[2];\n  double PQstar[2];\n  irt_rpf_mdim_drm_prob2(spec, param, where, PQstar, PQ);\n  double Pstar = PQstar[0];\n  double Qstar = PQstar[1];\n  const double *aa = param;\n  const double guess = antilogit(param[numDims + 1]);\n  const double upper = antilogit(param[numDims + 2]);\n  for (int ax=0; ax < numDims; ax++) {\n    double piece = dir[ax] * (upper-guess) * aa[ax] * (Pstar * Qstar);\n    grad[1] += piece;\n    grad[0] -= piece;\n    piece = dir[ax] * (2 * (upper - guess) * aa[ax]*aa[ax] * (Qstar * Qstar * Pstar) -\n\t\t       (upper - guess) * aa[ax]*aa[ax] * (Pstar * Qstar));\n    hess[1] -= piece;\n    hess[0] += piece;\n  }\n}\n\nstatic void\nirt_rpf_1dim_drm_dTheta(const double *spec, const double *param,\n\t\t\tconst double *where, const double *dir,\n\t\t\tdouble *grad, double *hess)\n{\n  double nparam[4];\n  memcpy(nparam, param, sizeof(double) * 4);\n  nparam[1] = param[1] * -param[0];\n  irt_rpf_mdim_drm_dTheta(spec, nparam, where, dir, grad, hess);\n}\n\nstatic int\nirt_rpf_mdim_grm_numSpec(const double *spec)\n{ return RPF_ISpecCount; }\n\nstatic int\nirt_rpf_mdim_grm_numParam(const double *spec)\n{ return spec[RPF_ISpecOutcomes] + spec[RPF_ISpecDims] - 1; }\n\nstatic void\nirt_rpf_mdim_grm_paramInfo(const double *spec, const int param,\n\t\t\t   const char **type, double *upper, double *lower)\n{\n\tint numDims = spec[RPF_ISpecDims];\n\t*upper = nan(\"unset\");\n\t*lower = nan(\"unset\");\n\t*type = NULL;\n\tif (param >= 0 && param < numDims) {\n\t\t*type = \"slope\";\n\t\t*lower = 1e-6;\n\t} else {\n\t\t*type = \"intercept\";\n\t}\n}\n\nstatic void _grm_fix_crazy_stuff(const double *spec, const int numOutcomes, double *out)\n{\n  int bigk = -1;\n  double big = 0;\n\n  for (int bx=0; bx < numOutcomes; bx++) {\n    if (out[bx] > big) {\n      bigk = bx;\n      big = out[bx];\n    }\n  }\n\n  for (int fx=0; fx < numOutcomes; fx++) {\n    if (out[fx] < SMALLEST_PROB) {\n      double small = SMALLEST_PROB - out[fx];\n      out[bigk] -= small;\n      out[fx] += small;\n    }\n  }\n}\n\nstatic void\nirt_rpf_mdim_grm_prob(const double *spec,\n\t\t      const double *param, const double *th,\n\t\t      double *out)\n{\n  const int numDims = spec[RPF_ISpecDims];\n  const int numOutcomes = spec[RPF_ISpecOutcomes];\n  const double *slope = param;\n  const double dprod = dotprod(slope, th, numDims);\n  const double *kat = param + (int) spec[RPF_ISpecDims];\n\n  double athb = -(dprod + kat[0]);\n  if (athb < -EXP_STABLE_DOMAIN) athb = -EXP_STABLE_DOMAIN;\n  else if (athb > EXP_STABLE_DOMAIN) athb = EXP_STABLE_DOMAIN;\n  double tmp = 1 / (1 + exp(athb));\n  out[0] = 1-tmp;\n  out[1] = tmp;\n\n  for (int kx=2; kx < numOutcomes; kx++) {\n\t  if (1e-6 + kat[kx-1] >= kat[kx-2]) {\n\t\t  for (int ky=0; ky < numOutcomes; ky++) {\n\t\t\t  out[ky] = nan(\"I\");\n\t\t  }\n\t\t  return;\n\t  }\n    double athb = -(dprod + kat[kx-1]);\n    if (athb < -EXP_STABLE_DOMAIN) athb = -EXP_STABLE_DOMAIN;\n    else if (athb > EXP_STABLE_DOMAIN) athb = EXP_STABLE_DOMAIN;\n    double tmp = 1 / (1 + exp(athb));\n    out[kx-1] -= tmp;\n    out[kx] = tmp;\n  }\n\n  for (int kx=0; kx < numOutcomes; kx++) {\n    if (out[kx] <= 0) {\n      _grm_fix_crazy_stuff(spec, numOutcomes, out);\n      return;\n    }\n  }\n}\n\nstatic void\nirt_rpf_mdim_grm_rawprob(const double *spec,\n\t\t\t const double *param, const double *th,\n\t\t\t double *out)\n{\n  int numDims = spec[RPF_ISpecDims];\n  const int numOutcomes = spec[RPF_ISpecOutcomes];\n  const double dprod = dotprod(param, th, numDims);\n  const double *kat = param + (int) spec[RPF_ISpecDims];\n\n  out[0] = 1;\n  for (int kx=0; kx < numOutcomes-1; kx++) {\n    double athb = -(dprod + kat[kx]);\n    if (athb < -EXP_STABLE_DOMAIN) athb = -EXP_STABLE_DOMAIN;\n    else if (athb > EXP_STABLE_DOMAIN) athb = EXP_STABLE_DOMAIN;\n    double tmp = 1 / (1 + exp(athb));\n    out[kx+1] = tmp;\n  }\n  out[numOutcomes] = 0;\n}\n\n// Compare with Cai (2010, p. 54) Appendix B\nstatic void\nirt_rpf_mdim_grm_deriv1(const double *spec,\n\t\t\tconst double *param,\n\t\t\tconst double *where,\n\t\t\tconst double *weight, double *out)\n{\n  int nfact = spec[RPF_ISpecDims];\n  int outcomes = spec[RPF_ISpecOutcomes];\n  int nzeta = spec[RPF_ISpecOutcomes] - 1;\n  Eigen::VectorXd P(nzeta+2);\n  Eigen::VectorXd PQfull(nzeta+2);\n  irt_rpf_mdim_grm_rawprob(spec, param, where, P.data());\n  PQfull[0] = 0;\n  PQfull[outcomes] = 0;\n  for (int kx=1; kx <= nzeta; kx++) PQfull[kx] = P[kx] * (1-P[kx]);\n  for (int jx = 0; jx <= nzeta; jx++) {\n    double Pk_1 = P[jx];\n    double Pk = P[jx + 1];\n    double PQ_1 = PQfull[jx];\n    double PQ = PQfull[jx + 1];\n    double Pk_1Pk = Pk_1 - Pk;\n    if (Pk_1Pk < 1e-10) Pk_1Pk = 1e-10;\n    double dif1 = weight[jx] / Pk_1Pk;\n    double dif1sq = dif1 / Pk_1Pk;\n    if(jx < nzeta) {\n      double Pk_p1 = P[jx + 2];\n      double PQ_p1 = PQfull[jx + 2];\n      double Pk_Pkp1 = Pk - Pk_p1;\n      if(Pk_Pkp1 < 1e-10) Pk_Pkp1 = 1e-10;\n      double dif2 = weight[jx+1] / Pk_Pkp1;\n      double dif2sq = dif2 / Pk_Pkp1;\n      out[nfact + jx] += PQ * (dif1 - dif2);  //gradient for intercepts\n\n      int d2base = hessianIndex(nfact + nzeta, nfact+jx, 0);\n      // hessian for intercept^2\n      double tmp3 = (dif1 - dif2) * (Pk * (1.0 - Pk) * (1.0 - 2.0*Pk));\n      double piece1 = (PQ * PQ * (dif1sq + dif2sq) + tmp3);\n      out[d2base + nfact + jx] += piece1;\n      if (jx < (nzeta - 1)) {\n\t      // hessian for adjacent intercepts\n\t      int d2base1 = hessianIndex(nfact + nzeta, nfact+jx+1, nfact + jx);\n\t      out[d2base1] -= dif2sq * PQ_p1 * PQ;\n      }\n      double tmp1 = -dif2sq * PQ * (PQ - PQ_p1);\n      double tmp2 = dif1sq * PQ * (PQ_1 - PQ);\n      for(int kx = 0; kx < nfact; kx++){\n\t// hessian for slope intercept\n\tout[d2base + kx] -= (tmp1 + tmp2 - tmp3) * where[kx];\n      }\n    }\n    for(int kx = 0; kx < nfact; kx++) {\n      // gradient for slope\n      out[kx] -= dif1 * (PQ_1 - PQ) * where[kx];\n    }\n\n    Eigen::VectorXd temp(nfact);\n    for(int ix = 0; ix < nfact; ix++)\n      temp[ix] = PQ_1 * where[ix] - PQ * where[ix];\n\n    int d2x = nfact + nzeta;\n    double Pk_adj = (Pk_1 * (1.0 - Pk_1) * (1.0 - 2.0 * Pk_1) -\n\t\t     Pk * (1.0 - Pk) * (1.0 - 2.0 * Pk));\n    for(int i = 0; i < nfact; i++) {\n      for(int j = 0; j <= i; j++) {\n\tdouble outer = where[i]*where[j];\n\t// hessian for slope slope\n\tout[d2x++] -= (- dif1sq * temp[i] * temp[j] + (dif1 * outer * Pk_adj));\n      }\n    }\n  }\n}\n\nstatic void\nirt_rpf_mdim_grm_deriv2(const double *spec,\n\t\t\tconst double *param,\n\t\t\tdouble *out)\n{\n  int nfact = spec[RPF_ISpecDims];\n  int nzeta = spec[RPF_ISpecOutcomes] - 1;\n  const double *aa = param;\n  for (int dx=0; dx < nfact; dx++) {\n    if (aa[dx] < 0) {\n      set_deriv_nan(spec, out);\n      return;\n    }\n  }\n  for (int zx=0; zx < nzeta-1; zx++) {\n    if (param[nfact+zx] < param[nfact+zx+1]) {\n      set_deriv_nan(spec, out);\n      return;\n    }\n  }\n}\n\nstatic void\nirt_rpf_mdim_grm_dTheta(const double *spec, const double *param,\n\t\t\tconst double *where, const double *dir,\n\t\t\tdouble *grad, double *hess)\n{\n  int numDims = spec[RPF_ISpecDims];\n  int outcomes = spec[RPF_ISpecOutcomes];\n  const double *aa = param;\n  Eigen::VectorXd P(outcomes+1);\n  irt_rpf_mdim_grm_rawprob(spec, param, where, P.data());\n  for (int jx=0; jx < numDims; jx++) {\n    for (int ix=0; ix < outcomes; ix++) {\n      double w1 = P[ix] * (1-P[ix]) * aa[jx];\n      double w2 = P[ix+1] * (1-P[ix+1]) * aa[jx];\n      grad[ix] += dir[jx] * (w1 - w2);\n      hess[ix] += dir[jx] * (aa[jx]*aa[jx] * (2 * P[ix] * (1 - P[ix])*(1 - P[ix]) -\n\t\t\t\t\t      P[ix] * (1 - P[ix]) -\n\t\t\t\t\t      2 * P[ix+1] * (1 - P[ix+1])*(1 - P[ix+1]) +\n\t\t\t\t\t      P[ix+1] * (1 - P[ix+1])));\n    }\n  }\n}\n\nstatic void\nirt_rpf_mdim_grm_rescale(const double *spec, double *param, const int *paramMask,\n\t\t\t const double *mean, const double *cov)\n{\n  int numDims = spec[RPF_ISpecDims];\n  int nzeta = spec[RPF_ISpecOutcomes] - 1;\n\n  double madj = dotprod(param, mean, numDims);\n\n  for (int d1=0; d1 < numDims; d1++) {\n    if (paramMask[d1] < 0) continue;\n    param[d1] = dotprod(param+d1, cov + d1 * numDims + d1, numDims-d1);\n  }\n\n  for (int tx=0; tx < nzeta; tx++) {\n    int px = numDims + tx;\n    if (paramMask[px] >= 0) param[px] += madj;\n  }\n}\n\nstatic int\nirt_rpf_nominal_numSpec(const double *spec)\n{\n  int outcomes = spec[RPF_ISpecOutcomes];\n  int Tlen = (outcomes - 1) * (outcomes - 1);\n  return RPF_ISpecCount + 4 * Tlen;\n}\n\nstatic int\nirt_rpf_nominal_numParam(const double *spec)\n{\n\tint dims = spec[RPF_ISpecDims];\n\tif (dims == 0) {\n\t\treturn spec[RPF_ISpecOutcomes]-1;\n\t} else {\n\t\treturn dims + 2 * (spec[RPF_ISpecOutcomes]-1);\n\t}\n}\n\n\nstatic void\nirt_rpf_nominal_paramInfo(const double *spec, const int param,\n\t\t\t  const char **type, double *upper, double *lower)\n{\n\tint numDims = spec[RPF_ISpecDims];\n\tconst int numOutcomes = spec[RPF_ISpecOutcomes];\n\t*upper = nan(\"unset\");\n\t*lower = nan(\"unset\");\n\tif (numDims == 0) {\n\t\t*type = \"intercept\";\n\t\treturn;\n\t}\n\t*type = NULL;\n\tif (param >= 0 && param < numDims) {\n\t\t*type = \"slope\";\n\t\t*lower = 1e-6;\n\t} else if (param < numDims + numOutcomes - 1) {\n\t\t*type = \"slope\";\n\t} else {\n\t\t*type = \"intercept\";\n\t}\n}\n\nstatic void\n_nominal_rawprob1(const double *spec,\n\t\t const double *param, const double *th,\n\t\t double discr, double *ak, double *num, double *maxout)\n{\n  int numDims = spec[RPF_ISpecDims];\n  int numOutcomes = spec[RPF_ISpecOutcomes];\n  const double *alpha = param + numDims;\n  const double *gamma;\n  if (numDims == 0) {\n\t  // alpha doesn't matter\n\t  gamma = param + numDims;\n  } else {\n\t  gamma = param + numDims + numOutcomes - 1;\n  }\n  const double *Ta = spec + RPF_ISpecCount;\n  const double *Tc = spec + RPF_ISpecCount + (numOutcomes-1) * (numOutcomes-1);\n\n  double curmax = 1;\n  for (int kx=0; kx < numOutcomes; kx++) {\n    ak[kx] = 0;\n    double ck = 0;\n    if (kx) {\n      for (int tx=0; tx < numOutcomes-1; tx++) {\n\tint Tcell = tx * (numOutcomes-1) + kx-1;\n\tak[kx] += Ta[Tcell] * alpha[tx];\n\tck += Tc[Tcell] * gamma[tx];\n      }\n    }\n\n    double z = discr * ak[kx] + ck;\n    num[kx] = z;\n    if (curmax < z) curmax = z;\n  }\n  *maxout = curmax;\n}\n\nstatic void\n_nominal_rawprob2(const double *spec,\n\t\t  const double *param, const double *th,\n\t\t  double discr, double *ak, double *num)\n{\n  int numOutcomes = spec[RPF_ISpecOutcomes];\n  double maxZ;\n  _nominal_rawprob1(spec, param, th, discr, ak, num, &maxZ);\n  \n  double recenter = 0;\n  if (maxZ > EXP_STABLE_DOMAIN) {\n    recenter = maxZ - EXP_STABLE_DOMAIN;\n  }\n\n  int Kadj = -1;\n  double adj = 0;\n  double den = 0;   // not exact because adj not taken into account\n  for (int kx=0; kx < numOutcomes; kx++) {\n    if (num[kx] == maxZ) Kadj = kx;\n    if (num[kx] - recenter < -EXP_STABLE_DOMAIN) {\n      num[kx] = 0;\n      adj += SMALLEST_PROB;\n      continue;\n    }\n    num[kx] = exp(num[kx] - recenter);\n    den += num[kx];\n  }\n  for (int kx=0; kx < numOutcomes; kx++) {\n    if (kx == Kadj) {\n      num[kx] = num[kx]/den - adj;\n    } else if (num[kx] == 0) {\n      num[kx] = SMALLEST_PROB;\n    } else {\n      num[kx] = num[kx]/den;\n    }\n  }\n}\n\nstatic void\nirt_rpf_nominal_prob(const double *spec,\n\t\t     const double *param, const double *th,\n\t\t     double *out)\n{\n  int numOutcomes = spec[RPF_ISpecOutcomes];\n  int numDims = spec[RPF_ISpecDims];\n  Eigen::VectorXd ak(numOutcomes);\n  double discr = dotprod(param, th, numDims);\n  _nominal_rawprob2(spec, param, th, discr, ak.data(), out);\n}\n\nstatic void\nirt_rpf_nominal_logprob(const double *spec,\n\t\t\tconst double *param, const double *th,\n\t\t\tdouble *out)\n{\n  int numOutcomes = spec[RPF_ISpecOutcomes];\n  int numDims = spec[RPF_ISpecDims];\n  Eigen::VectorXd num(numOutcomes);\n  Eigen::VectorXd ak(numOutcomes);\n  double discr = dotprod(param, th, numDims);\n  double maxZ;\n  _nominal_rawprob1(spec, param, th, discr, ak.data(), num.data(), &maxZ);\n  double den = 0;\n\n  if (maxZ > EXP_STABLE_DOMAIN) {\n    den = maxZ;  // not best approx\n  } else {\n    for (int kx=0; kx < numOutcomes; kx++) {\n      if (num[kx] < -EXP_STABLE_DOMAIN) continue;\n      den += exp(num[kx]);\n    }\n    den = log(den);\n  }\n\n  for (int kx=0; kx < numOutcomes; kx++) {\n    out[kx] = num[kx] - den;\n  }\n}\n\nstatic double makeOffterm(const double *dat, const double p, const double aTheta,\n\t\t\t  const int ncat, const int cat)\n{\n  double ret = 0;\n  for (int CAT = 0; CAT < ncat; CAT++) {\n    if (CAT == cat) continue;\n    ret += dat[CAT] * p * aTheta;\n  }\n  return(ret);\n}\n\nstatic double makeOffterm2(const double *dat, const double p1, const double p2, \n\t\t\t   const double aTheta, const int ncat, const int cat)\n{\n  double ret = 0;\n  for (int CAT = 0; CAT < ncat; CAT++) {\n    if (CAT == cat) continue;\n    ret += dat[CAT] * p1 * p2 * aTheta;\n  }\n  return(ret);\n}\n\nstatic void\nirt_rpf_nominal_deriv1(const double *spec,\n\t\t       const double *param,\n\t\t       const double *where,\n\t\t       const double *weight, double *out)\n{\n  int nfact = spec[RPF_ISpecDims];\n  int ncat = spec[RPF_ISpecOutcomes];\n  double aTheta = dotprod(param, where, nfact);\n  double aTheta2 = aTheta * aTheta;\n\n  Eigen::VectorXd num(ncat);\n  Eigen::VectorXd ak(ncat);\n  _nominal_rawprob2(spec, param, where, aTheta, ak.data(), num.data());\n\n  Eigen::VectorXd P(ncat);\n  Eigen::VectorXd P2(ncat);\n  Eigen::VectorXd P3(ncat);\n  Eigen::VectorXd ak2(ncat);\n  Eigen::VectorXd dat_num(ncat);\n  double numsum = 0;\n  double numakD = 0;\n  double numak2D2 = 0;\n  Eigen::VectorXd numakDTheta_numsum(nfact);\n\n  for (int kx=0; kx < ncat; kx++) {\n    ak2[kx] = ak[kx] * ak[kx];\n    dat_num[kx] = weight[kx]/num[kx];\n    numsum += num[kx];\n    numakD += num[kx] * ak[kx];\n    numak2D2 += num[kx] * ak2[kx];\n  }\n  double numsum2 = numsum * numsum;\n\n  for (int kx=0; kx < ncat; kx++) {\n    P[kx] = num[kx]/numsum;\n    P2[kx] = P[kx] * P[kx];\n    P3[kx] = P2[kx] * P[kx];\n  }\n\n  double sumNumak = dotprod(num.data(), ak.data(), ncat);\n  for (int fx=0; fx < nfact; fx++) {\n    numakDTheta_numsum[fx] = sumNumak * where[fx] / numsum;\n  }\n\n  for (int jx = 0; jx < nfact; jx++) {\n    double tmpvec = 0;\n    for(int i = 0; i < ncat; i++) {\n      tmpvec += dat_num[i] * (ak[i] * where[jx] * P[i] -\n\t\t\t      P[i] * numakDTheta_numsum[jx]) * numsum;\n    }\n    out[jx] -= tmpvec;\n  }\n  int dkoffset;\n  if (nfact == 0) {\n\t  dkoffset = 0;\n  } else {\n\t  dkoffset = ncat - 1;\n  }\n  for(int i = 1; i < ncat; i++) {\n\t  if (nfact) {\n\t\t  double offterm = makeOffterm(weight, P[i], aTheta, ncat, i);\n\t\t  double tmpvec = dat_num[i] * (aTheta * P[i] - P2[i] * aTheta) * numsum - offterm;\n\t\t  out[nfact + i - 1] -= tmpvec;\n\t  }\n    double offterm2 = makeOffterm(weight, P[i], 1, ncat, i);\n    double tmpvec2 = dat_num[i] * (P[i] - P2[i]) * numsum - offterm2;\n    out[nfact + dkoffset + i - 1] -= tmpvec2;\n  }\n\n  int hessbase = nfact + (ncat-1) + dkoffset;\n  int d2ind = 0;\n  //a's\n  for (int j = 0; j < nfact; j++) {\n    for (int k = 0; k <= j; k++) {\n      double tmpvec = 0;\n      for (int i = 0; i < ncat; i++) {\n\ttmpvec += dat_num[i] * (ak2[i] * where[j] * where[k] * P[i] -\n\t\t\t\tak[i] * where[j] * P[i] * numakDTheta_numsum[k] -\n\t\t\t\tak[i] * where[k] * P[i] * numakDTheta_numsum[j] + \n\t\t\t\t2 * P[i] * numakD * where[j] * numakD * where[k] / numsum2 -\n\t\t\t\tP[i] * numak2D2 * where[j] * where[k] / numsum) * numsum - \n\t  dat_num[i] * (ak[i] * where[j] * P[i] - P[i] * numakDTheta_numsum[j]) *\n\t  numsum * ak[i] * where[k] +\n\t  dat_num[i] * (ak[i] * where[j] * P[i] - P[i] * numakDTheta_numsum[j]) *\n\t  numakD * where[k];\n      }\n      out[hessbase + d2ind++] -= tmpvec;\n    }\n  }\n  //a's with ak and d\n  for(int k = 1; k < ncat; k++){\n    int akrow = hessbase + (nfact+k)*(nfact+k-1)/2;\n    int dkrow = hessbase + (nfact+ncat+k-1)*(nfact+ncat+k-2)/2;\n    for(int j = 0; j < nfact; j++){\n      double tmpvec = 0;\n      double tmpvec2 = 0;\n      for(int i = 0; i < ncat; i++){\n\tif(i == k){\n\t  tmpvec += dat_num[i] * (ak[i]*where[j] * aTheta*P[i] -\n\t\t\t\t     aTheta*P[i]*numakDTheta_numsum[j] +\n\t\t\t\t     where[j]*P[i] - 2*ak[i]*where[j]*aTheta*P2[i] +\n\t\t\t\t     2*aTheta*P2[i]*numakDTheta_numsum[j] -\n\t\t\t\t     where[j]*P2[i])*numsum -\n\t    dat_num[i]*(aTheta*P[i] - aTheta*P2[i])*numsum*ak[i]*where[j] +\n\t    dat_num[i]*(aTheta*P[i] - aTheta*P2[i])*(numakD*where[j]);\n\t  tmpvec2 += dat_num[i]*(ak[i]*where[j]*P[i] -\n\t\t\t\t      2*ak[i]*where[j]*P2[i] -\n\t\t\t\t      P[i]*numakDTheta_numsum[j] +\n\t\t\t\t      2*P2[i]*numakDTheta_numsum[j])*numsum -\n\t    dat_num[i]*(P[i] - P2[i])*numsum*ak[i]*where[j] +\n\t    dat_num[i]*(P[i] - P2[i])*(numakD*where[j]);\n\t} else {\n\t  tmpvec += -weight[i]*ak[k]*aTheta*where[j]*P[k] +\n\t    weight[i]*P[k]*aTheta*numakDTheta_numsum[j] -\n\t    weight[i]*P[k]*where[j];\n\t  tmpvec2 += -weight[i]*ak[k]*where[j]*P[k] +\n\t    weight[i]*P[k]*numakDTheta_numsum[j];\n\t}\n      }\n      out[akrow + j] -= tmpvec;\n      out[dkrow + j] -= tmpvec2;\n    }\n  }\n  //ak's and d's\n  for(int j = 1; j < ncat; j++){\n    int akrow = hessbase + (nfact+j)*(nfact+j-1)/2;\n    int dkrow = hessbase + (nfact+dkoffset+j)*(nfact+dkoffset+j-1)/2;\n\n    double tmpvec = makeOffterm(weight, P2[j], aTheta2, ncat, j);\n    double tmpvec2 = makeOffterm(weight, P[j], aTheta2, ncat, j);\n    double offterm = tmpvec - tmpvec2;\n    tmpvec = makeOffterm(weight, P2[j], 1, ncat, j);\n    tmpvec2 = makeOffterm(weight, P[j], 1, ncat, j);\n    double offterm2 = tmpvec - tmpvec2;\n\n    if (nfact) {\n\t    out[akrow + nfact + j - 1] -=\n\t\t    (dat_num[j]*(aTheta2*P[j] - 3*aTheta2*P2[j] +\n\t\t\t\t 2*aTheta2*P3[j])*numsum - weight[j]/num[j] *\n\t\t     (aTheta*P[j] - aTheta*P2[j])*numsum*aTheta + weight[j] *\n\t\t     (aTheta*P[j] - aTheta*P2[j])*aTheta + offterm);\n    }\n\n    out[dkrow + nfact + dkoffset + j - 1] -=\n      (dat_num[j]*(P[j] - 3*P2[j] + 2*P3[j])*numsum - weight[j]/num[j] *\n\t      (P[j] - P2[j])*numsum + weight[j] *\n\t      (P[j] - P2[j]) + offterm2);\n\n    for(int i = 1; i < ncat; i++) {\n      if(j > i) {\n\t      if (nfact) {\n\t\t      offterm = makeOffterm2(weight, P[j], P[i], aTheta2, ncat, i);\n\t\t      tmpvec = dat_num[i] * (-aTheta2*P[i]*P[j] + 2*P2[i] *aTheta2*P[j])*numsum + \n\t\t\t      dat_num[i] * (aTheta*P[i] - P2[i] * aTheta)*aTheta*num[j]+offterm;\n\t\t      out[akrow + nfact + i - 1] -= tmpvec;\n\t      }\n\toffterm2 = makeOffterm2(weight, P[j], P[i], 1, ncat, i);\n\ttmpvec2 = dat_num[i] * (-P[i]*P[j] + 2*P2[i] *P[j]) * numsum +\n\t  dat_num[i] * (P[i] - P2[i]) * num[j] + offterm2;\n\tout[dkrow + nfact + dkoffset + i - 1] -= tmpvec2;\n      }\n      if (nfact == 0) continue;\n      if (abs(j-i) == 0) {\n\ttmpvec = makeOffterm(weight, P2[i], aTheta, ncat, i);\n\ttmpvec2 = makeOffterm(weight, P[i], aTheta, ncat, i);\n\toffterm = tmpvec - tmpvec2;\n\ttmpvec = dat_num[i]*(aTheta*P[i] - 3*aTheta*P2[i] +\n\t\t\t     2*aTheta*P3[i]) * numsum - dat_num[i] *\n\t  (aTheta*P[i] - aTheta*P2[i])*numsum + weight[i] *\n\t  (P[i] - P2[i])*aTheta + offterm;\n\tout[dkrow + nfact + i - 1] -= tmpvec;\n      } else {\n\toffterm = makeOffterm2(weight, P[j], P[i], aTheta, ncat, i);\n\ttmpvec = dat_num[i] * (-aTheta*P[i]*P[j] + 2*P2[i] *aTheta*P[j]) * numsum + \n\t  dat_num[i] * (P[i] - P2[i]) * aTheta * num[j] + offterm;\n\tout[dkrow + nfact + i - 1] -= tmpvec;\n      }\n    }\n  }\n}\n\nstatic void\nirt_rpf_nominal_deriv2(const double *spec,\n\t\t       const double *param,\n\t\t       double *out)\n{\n  int nfact = spec[RPF_ISpecDims];\n  int nzeta = spec[RPF_ISpecOutcomes] - 1;\n  const double *aa = param;\n\n  for (int dx=0; dx < nfact; dx++) {\n    if (aa[dx] < 0) {\n      set_deriv_nan(spec, out);\n      return;\n    }\n  }\n\n  int ckoffset = nzeta;\n  if (nfact == 0) ckoffset = 0;\n\n  const double *Ta = spec + RPF_ISpecCount;\n  const double *Tc = spec + RPF_ISpecCount + nzeta * nzeta;\n  const int numParam = irt_rpf_nominal_numParam(spec);\n  Eigen::VectorXd rawOut(numParam);\n  memcpy(rawOut.data(), out, sizeof(double) * numParam);\n\n  // gradient\n  for (int tx=0; tx < nzeta; tx++) {\n    double ak1=0;\n    double ck1=0;\n    for (int kx=0; kx < nzeta; kx++) {\n      int Tcell = tx * nzeta + kx;\n      ak1 += rawOut[nfact + kx] * Ta[Tcell];\n      ck1 += rawOut[nfact + ckoffset + kx] * Tc[Tcell];\n    }\n    out[nfact + tx] = ak1;\n    out[nfact + ckoffset + tx] = ck1;\n  }\n\n  // don't need to transform the main a parameters TODO\n  double *dmat = Realloc(NULL, 3 * numParam * numParam, double);\n  const int hsize = hessianIndex(0, numParam-1, numParam-1);\n  {\n\t  // unpack triangular storage into a full matrix\n    int row=0;\n    int col=0;\n    for (int dx=0; dx <= hsize; dx++) {\n      dmat[numParam * col + row] = out[numParam + dx];\n      if (row == col) {\n\tcol=0; ++row;\n      } else {\n\tdmat[numParam * row + col] = out[numParam + dx];\n\t++col;\n      }\n    }\n  }\n\n  double *tmat = dmat + numParam * numParam;\n  for (int dx=0; dx < numParam * numParam; dx++) tmat[dx] = 0;\n  for (int dx=0; dx < nfact; dx++) {\n    tmat[dx * numParam + dx] = 1;\n  }\n  for (int rx=0; rx < nzeta; rx++) {\n    for (int cx=0; cx < nzeta; cx++) {\n      tmat[(cx + nfact)*numParam + nfact + rx] = Ta[rx * nzeta + cx];\n      tmat[(cx + nfact + ckoffset)*numParam + nfact + ckoffset + rx] = Tc[rx * nzeta + cx];\n    }\n  }\n\n  double *dest = dmat + 2 * numParam * numParam;\n\n  // It is probably possible to do this more efficiently than dgemm\n  // since we know that we only care about the lower triangle.\n  // I'm not sure whether this is worth optimizing. TODO\n\n  char normal = 'n';\n  char transpose = 't';\n  double one = 1;\n  double zero = 0;\n  F77_CALL(dgemm)(&normal, &normal, &numParam, &numParam, &numParam,\n\t\t  &one, tmat, &numParam, dmat, &numParam, &zero, dest, &numParam);\n  F77_CALL(dgemm)(&normal, &transpose, &numParam, &numParam, &numParam,\n\t\t  &one, dest, &numParam, tmat, &numParam, &zero, dmat, &numParam);\n\n  {\n    int row=0;\n    int col=0;\n    for (int dx=0; dx <= hsize; dx++) {\n      out[numParam + dx] = dmat[numParam * col + row];\n      if (row == col) {\n\tcol=0; ++row;\n      } else {\n\t++col;\n      }\n    }\n  }\n\n  Free(dmat);\n}\n\nstatic void\nirt_rpf_mdim_nrm_dTheta(const double *spec, const double *param,\n\t\t\tconst double *where, const double *dir,\n\t\t\tdouble *grad, double *hess)\n{\n  int numDims = spec[RPF_ISpecDims];\n  int outcomes = spec[RPF_ISpecOutcomes];\n  const double *aa = param;\n  Eigen::VectorXd num(outcomes);\n  Eigen::VectorXd ak(outcomes);\n  double discr = dotprod(param, where, numDims);\n  _nominal_rawprob2(spec, param, where, discr, ak.data(), num.data());\n\n  double den = 0;\n  for (int kx=0; kx < outcomes; kx++) {\n    den += num[kx];\n  }\n\n  Eigen::VectorXd P(outcomes);\n  for (int kx=0; kx < outcomes; kx++) {\n    P[kx] = num[kx]/den;\n  }\n\n  for(int jx=0; jx < numDims; jx++) {\n\t  Eigen::VectorXd jak(outcomes);\n\t  Eigen::VectorXd jak2(outcomes);\n    for (int ax=0; ax < outcomes; ax++) {\n      jak[ax] = ak[ax] * aa[jx];\n      jak2[ax] = jak[ax] * jak[ax];\n    }\n    double numjak = dotprod(num.data(), jak.data(), outcomes);\n    double numjakden2 = numjak / den;\n    numjakden2 *= numjakden2;\n    double numjak2den = dotprod(num.data(), jak2.data(), outcomes) / den;\n\n    for(int ix=0; ix < outcomes; ix++) {\n      grad[ix] += dir[jx] * (ak[ix] * aa[jx] * P[ix] - P[ix] * numjak / den);\n      hess[ix] += dir[jx] * (ak[ix]*ak[ix] * aa[jx]*aa[jx] * P[ix] -\n\t\t\t     2 * ak[ix] * aa[jx] * P[ix] * numjak / den +\n\t\t\t     2 * P[ix] * numjakden2 - P[ix] * numjak2den);\n    }\n  }\n}\n\nstatic void\nirt_rpf_mdim_nrm_rescale(const double *spec, double *param, const int *paramMask,\n\t\t\t const double *mean, const double *cov)\n{\n  int numDims = spec[RPF_ISpecDims];\n  int nzeta = spec[RPF_ISpecOutcomes] - 1;\n  double *alpha = param + numDims;\n  double *gamma = param + numDims + nzeta;\n  const double *Ta  = spec + RPF_ISpecCount;\n  const double *Tc  = spec + RPF_ISpecCount + nzeta * nzeta;\n  const double *iTc = spec + RPF_ISpecCount + 3 * nzeta * nzeta;\n\n  double madj = dotprod(param, mean, numDims);\n\n  for (int d1=0; d1 < numDims; d1++) {\n    if (paramMask[d1] < 0) continue;\n    param[d1] = dotprod(param+d1, cov + d1 * numDims + d1, numDims-d1);\n  }\n\n  Eigen::VectorXd ak(nzeta);\n  ak.setZero();\n  Eigen::VectorXd ck(nzeta);\n  ck.setZero();\n\n  for (int kx=0; kx < nzeta; kx++) {\n    for (int tx=0; tx < nzeta; tx++) {\n      int Tcell = tx * nzeta + kx;\n      ak[kx] += Ta[Tcell] * alpha[tx];\n      ck[kx] += Tc[Tcell] * gamma[tx];\n    }\n  }\n\n  for (int kx=0; kx < nzeta; kx++) {\n    ck[kx] += madj * ak[kx];\n  }\n\n  for (int kx=0; kx < nzeta; kx++) {\n    int px = numDims + nzeta + kx;\n    if (paramMask[px] < 0) continue;\n\n    param[px] = 0;\n\n    for (int tx=0; tx < nzeta; tx++) {\n      int Tcell = tx * nzeta + kx;\n      param[px] += iTc[Tcell] * ck[tx];\n    }\n  }\n}\n\n//static void noop() {}\nstatic void notimplemented_deriv1(const double *spec,\n\t\t\t\t  const double *param,\n\t\t\t\t  const double *where,\n\t\t\t\t  const double *weight, double *out)\n{ error(\"Not implemented\"); }\n\nstatic void notimplemented_deriv2(const double *spec,\n\t\t\t\t  const double *param,\n\t\t\t\t  double *out)\n{ error(\"Not implemented\"); }\n\nconst struct rpf librpf_model[] = {\n  { \"drm1-\",\n    irt_rpf_1dim_drm_numSpec,\n    irt_rpf_1dim_drm_numParam,\n    irt_rpf_mdim_drm_paramInfo,\n    irt_rpf_1dim_drm_prob,\n    irt_rpf_logprob_adapter,\n    notimplemented_deriv1,\n    notimplemented_deriv2,\n    irt_rpf_1dim_drm_dTheta,\n    irt_rpf_1dim_drm_rescale,\n  },\n  { \"drm\",\n    irt_rpf_mdim_drm_numSpec,\n    irt_rpf_mdim_drm_numParam,\n    irt_rpf_mdim_drm_paramInfo,\n    irt_rpf_mdim_drm_prob,\n    irt_rpf_logprob_adapter,\n    irt_rpf_mdim_drm_deriv1,\n    irt_rpf_mdim_drm_deriv2,\n    irt_rpf_mdim_drm_dTheta,\n    irt_rpf_mdim_drm_rescale,\n  },\n  { \"grm\",\n    irt_rpf_mdim_grm_numSpec,\n    irt_rpf_mdim_grm_numParam,\n    irt_rpf_mdim_grm_paramInfo,\n    irt_rpf_mdim_grm_prob,\n    irt_rpf_logprob_adapter,\n    irt_rpf_mdim_grm_deriv1,\n    irt_rpf_mdim_grm_deriv2,\n    irt_rpf_mdim_grm_dTheta,\n    irt_rpf_mdim_grm_rescale,\n  },\n  { \"nominal\",\n    irt_rpf_nominal_numSpec,\n    irt_rpf_nominal_numParam,\n    irt_rpf_nominal_paramInfo,\n    irt_rpf_nominal_prob,\n    irt_rpf_nominal_logprob,\n    irt_rpf_nominal_deriv1,\n    irt_rpf_nominal_deriv2,\n    irt_rpf_mdim_nrm_dTheta,\n    irt_rpf_mdim_nrm_rescale,\n  }\n};\n\nconst int librpf_numModels = (sizeof(librpf_model) / sizeof(struct rpf));\n", "meta": {"hexsha": "e192dcaf313eb5caa965a641ebe887347237f0f9", "size": 36544, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/libifa-rpf.cpp", "max_stars_repo_name": "JuKa87/OpenMx", "max_stars_repo_head_hexsha": "f055df183ca433abd194e494a433142825666128", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/libifa-rpf.cpp", "max_issues_repo_name": "JuKa87/OpenMx", "max_issues_repo_head_hexsha": "f055df183ca433abd194e494a433142825666128", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/libifa-rpf.cpp", "max_forks_repo_name": "JuKa87/OpenMx", "max_forks_repo_head_hexsha": "f055df183ca433abd194e494a433142825666128", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.1652035116, "max_line_length": 96, "alphanum_fraction": 0.5941330998, "num_tokens": 13494, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6001883449573377, "lm_q2_score": 0.5621765008857981, "lm_q1q2_score": 0.33741178364055446}}
{"text": "\n#include \"matrix_product_sparse.h\"\n#include <Eigen/Core>\n#include <Eigen/LU>\n#include <Eigen/SparseLU>\n\ntemplate<typename T>\nusing SparseMatrixType = Eigen::SparseMatrix<T>;\ntemplate<typename T>\nusing MatrixType = Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic, Eigen::ColMajor>;\ntemplate<typename T>\nusing VectorType = Eigen::Matrix<T, Eigen::Dynamic, 1, Eigen::ColMajor>;\ntemplate<typename T>\nusing VectorTypeT = Eigen::Matrix<T, 1, Eigen::Dynamic, Eigen::RowMajor>;\n\nnamespace sparse {\n    std::optional<Eigen::SparseMatrix<double>>                             A_real_sparse  = std::nullopt;\n    std::optional<Eigen::SparseMatrix<std::complex<double>>>               A_cplx_sparse  = std::nullopt;\n    std::optional<Eigen::SparseLU<SparseMatrixType<double>>>               lu_real_sparse = {};\n    std::optional<Eigen::SparseLU<SparseMatrixType<std::complex<double>>>> lu_cplx_sparse = {};\n    std::optional<Eigen::PartialPivLU<MatrixType<double>>>                 lu_real_dense  = std::nullopt;\n    std::optional<Eigen::PartialPivLU<MatrixType<std::complex<double>>>>   lu_cplx_dense  = std::nullopt;\n\n    void reset() {\n        A_real_sparse.reset();\n        A_cplx_sparse.reset();\n        lu_real_sparse.reset();\n        lu_cplx_sparse.reset();\n        lu_real_dense.reset();\n        lu_cplx_dense.reset();\n    }\n\n}\n\ntemplate<typename Scalar, bool sparseLU>\nSparseMatrixProduct<Scalar, sparseLU>::~SparseMatrixProduct(){\n    sparse::reset();\n}\n\n\n\ntemplate<typename Scalar, bool sparseLU>\nSparseMatrixProduct<Scalar, sparseLU>::SparseMatrixProduct(const Scalar *A_, const int L_, const bool copy_data, const eigutils::eigSetting::Form form_, const eigutils::eigSetting::Side side_)\n    : A_ptr(A_), L(L_), form(form_), side(side_) {\n    if (copy_data){\n        A_stl.resize(static_cast<size_t>(L*L));\n        std::copy(A_ptr,A_ptr + static_cast<size_t>(L*L), A_stl.begin());\n        A_ptr = A_stl.data();\n    }\n\n\n    if constexpr(sparseLU) {\n        Eigen::Map<const MatrixType<Scalar>> A_matrix(A_ptr, L, L);\n        if constexpr(std::is_same_v<Scalar, double>) {\n            sparse::A_real_sparse = A_matrix.sparseView();\n            sparse::A_real_sparse.value().makeCompressed();\n        }\n        if constexpr(std::is_same_v<Scalar, std::complex<double>>) {\n            sparse::A_cplx_sparse = A_matrix.sparseView();\n            sparse::A_cplx_sparse.value().makeCompressed();\n        }\n\n    }\n    init_profiling();\n}\n\n// Function definitions\n\ntemplate<typename Scalar, bool sparseLU>\nvoid SparseMatrixProduct<Scalar, sparseLU>::print() const {\n    Eigen::Map<const MatrixType<Scalar>> A_matrix(A_ptr, L, L);\n    std::cout << \"A_matrix: \\n\" << A_matrix << std::endl;\n}\n\ntemplate<typename Scalar, bool sparseLU>\nvoid SparseMatrixProduct<Scalar, sparseLU>::FactorOP()\n\n/*  Sparse decomposition\n *  Factors P(A-sigma*I) = LU\n */\n\n{\n    if(readyFactorOp) { return; }\n    assert(readyShift and \"Shift value sigma has not been set.\");\n    t_factorOp.tic();\n    Eigen::Map<const MatrixType<Scalar>> A_matrix(A_ptr, L, L);\n\n    Scalar sigma;\n    if constexpr(std::is_same_v<Scalar, double>) sigma = sigmaR;\n    if constexpr(std::is_same_v<Scalar, std::complex<double>>) sigma = std::complex<double>(sigmaR, sigmaI);\n    // Real\n    if constexpr(std::is_same_v<Scalar, double> and not sparseLU) {\n        sparse::lu_real_dense = Eigen::PartialPivLU<MatrixType<Scalar>>();\n        sparse::lu_real_dense.value().compute(A_matrix - sigma * Eigen::MatrixXd::Identity(L, L));\n    }\n    if constexpr(std::is_same_v<Scalar, double> and sparseLU) {\n        //        container::lu_real_sparse = Eigen::SparseLU<SparseMatrixType<Scalar>>();\n        sparse::lu_real_sparse.value().compute(sparse::A_real_sparse.value() - sigma * Eigen::MatrixXd::Identity(L, L));\n    }\n    // Complex\n    if constexpr(std::is_same_v<Scalar, std::complex<double>> and not sparseLU) {\n        sparse::lu_cplx_dense = Eigen::PartialPivLU<MatrixType<Scalar>>();\n        sparse::lu_cplx_dense.value().compute(A_matrix - sigma * Eigen::MatrixXd::Identity(L, L));\n    }\n    if constexpr(std::is_same_v<Scalar, std::complex<double>> and sparseLU) {\n        //        container::lu_cplx_sparse = Eigen::SparseLU<SparseMatrixType<Scalar>>();\n        sparse::lu_cplx_sparse.value().compute(sparse::A_cplx_sparse.value() - sigma * Eigen::MatrixXcd::Identity(L, L));\n    }\n\n    t_factorOp.toc();\n    readyFactorOp = true;\n    std::cout << \"Time Factor Op [ms]: \" << std::fixed << std::setprecision(3) << t_factorOp.get_last_time_interval() * 1000 << '\\n';\n}\n\ntemplate<typename Scalar, bool sparseLU>\nvoid SparseMatrixProduct<Scalar, sparseLU>::MultOPv(Scalar *x_in_ptr, Scalar *x_out_ptr) {\n    using namespace eigutils::eigSetting;\n    assert(readyFactorOp and \"FactorOp() has not been run yet.\");\n    using VectorType = Eigen::Matrix<Scalar, Eigen::Dynamic, 1>;\n    Eigen::Map<VectorType> x_in(x_in_ptr, L);\n    Eigen::Map<VectorType> x_out(x_out_ptr, L);\n\n    switch(side) {\n        case Side::R: {\n            if constexpr(std::is_same_v<Scalar, double> and not sparseLU)\n                x_out.noalias() = sparse::lu_real_dense.value().solve(x_in);\n            else if constexpr(std::is_same_v<Scalar, std::complex<double>> and not sparseLU)\n                x_out.noalias() = sparse::lu_cplx_dense.value().solve(x_in);\n            else if constexpr(std::is_same_v<Scalar, double> and sparseLU)\n                x_out.noalias() = sparse::lu_real_sparse.value().solve(x_in);\n            else if constexpr(std::is_same_v<Scalar, std::complex<double>> and sparseLU)\n                x_out.noalias() = sparse::lu_cplx_sparse.value().solve(x_in);\n            break;\n        }\n        case Side::L: {\n            if constexpr(std::is_same_v<Scalar, double> and not sparseLU)\n                x_out.noalias() = x_in * sparse::lu_real_dense.value().inverse();\n            else if constexpr(std::is_same_v<Scalar, std::complex<double>> and not sparseLU)\n                x_out.noalias() = x_in * sparse::lu_cplx_dense.value().inverse();\n            else {\n                throw std::runtime_error(\"Left sided sparse shift invert hasn't been implemented yet...\");\n            }\n            break;\n        }\n    }\n    counter++;\n}\n\ntemplate<typename Scalar, bool sparseLU>\nvoid SparseMatrixProduct<Scalar, sparseLU>::MultAx(Scalar *x_in, Scalar *x_out) {\n    using namespace eigutils::eigSetting;\n    Eigen::Map<const MatrixType<Scalar>> A_matrix(A_ptr, L, L);\n    switch(form) {\n        case Form::NONSYMMETRIC:\n            switch(side) {\n                case Side::R: {\n                    using VectorType = Eigen::Matrix<Scalar, Eigen::Dynamic, 1>;\n                    Eigen::Map<VectorType> x_vec_in(x_in, L);\n                    Eigen::Map<VectorType> x_vec_out(x_out, L);\n                    if constexpr(not sparseLU) x_vec_out.noalias() = A_matrix * x_vec_in;\n                    else if constexpr(std::is_same_v<Scalar,double> and sparseLU) x_vec_out.noalias() = sparse::A_real_sparse.value() * x_vec_in;\n                    else if constexpr(std::is_same_v<Scalar,std::complex<double>> and sparseLU) x_vec_out.noalias() = sparse::A_cplx_sparse.value() * x_vec_in;\n                    break;\n                }\n                case Side::L: {\n                    using VectorTypeT = Eigen::Matrix<Scalar, 1, Eigen::Dynamic>;\n                    Eigen::Map<VectorTypeT> x_vec_in(x_in, L);\n                    Eigen::Map<VectorTypeT> x_vec_out(x_out, L);\n                    if constexpr(not sparseLU) x_vec_out.noalias() = x_vec_in * A_matrix;\n                    else if constexpr(std::is_same_v<Scalar,double> and sparseLU) x_vec_out.noalias() = x_vec_in * sparse::A_real_sparse.value();\n                    else if constexpr(std::is_same_v<Scalar,std::complex<double>> and sparseLU) x_vec_out.noalias() = x_vec_in * sparse::A_cplx_sparse.value();\n                    break;\n                }\n            }\n            break;\n        case Form::SYMMETRIC: {\n            using VectorType = Eigen::Matrix<Scalar, Eigen::Dynamic, 1>;\n            Eigen::Map<VectorType> x_vec_in(x_in, L);\n            Eigen::Map<VectorType> x_vec_out(x_out, L);\n            if constexpr(not sparseLU) x_vec_out.noalias() = A_matrix.template selfadjointView<Eigen::Upper>() * x_vec_in;\n            if constexpr(std::is_same_v<Scalar,double> and sparseLU) x_vec_out.noalias() = sparse::A_real_sparse.value().template selfadjointView<Eigen::Upper>() * x_vec_in;\n            if constexpr(std::is_same_v<Scalar,std::complex<double>> and sparseLU) x_vec_out.noalias() = sparse::A_cplx_sparse.value().template selfadjointView<Eigen::Upper>() * x_vec_in;\n            break;\n        }\n    }\n    counter++;\n}\n\n// Explicit instantiations\ntemplate class SparseMatrixProduct<double, true>;\ntemplate class SparseMatrixProduct<double, false>;\ntemplate class SparseMatrixProduct<std::complex<double>, true>;\ntemplate class SparseMatrixProduct<std::complex<double>, false>;\n", "meta": {"hexsha": "b0187d475452c27ae3210591cb3c598677668467", "size": 8897, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "unused/eigsolver_backup/arpack_extra/matrix_product_sparse.cpp", "max_stars_repo_name": "DavidAce/DMRG", "max_stars_repo_head_hexsha": "e465fd903eade1bf6aa74daacd8e2cf02e9e9332", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9.0, "max_stars_repo_stars_event_min_datetime": "2017-10-31T22:50:28.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-10T15:45:27.000Z", "max_issues_repo_path": "unused/eigsolver_backup/arpack_extra/matrix_product_sparse.cpp", "max_issues_repo_name": "DavidAce/DMRG", "max_issues_repo_head_hexsha": "e465fd903eade1bf6aa74daacd8e2cf02e9e9332", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "unused/eigsolver_backup/arpack_extra/matrix_product_sparse.cpp", "max_forks_repo_name": "DavidAce/DMRG", "max_forks_repo_head_hexsha": "e465fd903eade1bf6aa74daacd8e2cf02e9e9332", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-07-16T00:27:56.000Z", "max_forks_repo_forks_event_max_datetime": "2019-07-16T00:27:56.000Z", "avg_line_length": 45.8608247423, "max_line_length": 192, "alphanum_fraction": 0.6441497134, "num_tokens": 2150, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6001883449573376, "lm_q2_score": 0.5621765008857981, "lm_q1q2_score": 0.3374117836405544}}
{"text": "//---------------------------------------------------------------------------//\n//!\n//! \\file   MonteCarlo_StandardSubshellDopplerBroadenedPhotonEnergyDistribution_def.hpp\n//! \\author Alex Robinson\n//! \\brief  The standard subshell Doppler broadened photon energy distribution\n//!         def.\n//!\n//---------------------------------------------------------------------------//\n\n#ifndef MONTE_CARLO_STANDARD_SUBSHELL_DOPPLER_BROADENED_PHOTON_ENERGY_DISTRIBUTION_DEF_HPP\n#define MONTE_CARLO_STANDARD_SUBSHELL_DOPPLER_BROADENED_PHOTON_ENERGY_DISTRIBUTION_DEF_HPP\n\n// Boost Includes\n#include <boost/function.hpp>\n#include <boost/bind.hpp>\n\n// FRENSIE Includes\n#include \"MonteCarlo_PhotonKinematicsHelpers.hpp\"\n#include \"Utility_GaussKronrodIntegrator.hpp\"\n#include \"Utility_RandomNumberGenerator.hpp\"\n#include \"Utility_ExplicitTemplateInstantiationMacros.hpp\"\n#include \"Utility_DesignByContract.hpp\"\n\nnamespace MonteCarlo{\n\n// Constructor\ntemplate<typename ComptonProfilePolicy>\nStandardSubshellDopplerBroadenedPhotonEnergyDistribution<ComptonProfilePolicy>::StandardSubshellDopplerBroadenedPhotonEnergyDistribution(\n\t\t const Data::SubshellType interaction_subshell,\n\t\t const double subshell_occupancy,\n\t\t const double subshell_binding_energy,\n\t\t const std::shared_ptr<const ComptonProfile>& compton_profile )\n  : SubshellDopplerBroadenedPhotonEnergyDistribution(interaction_subshell,\n                                                     subshell_occupancy,\n                                                     subshell_binding_energy ),\n    d_compton_profile( compton_profile )\n{\n  // Make sure the interaction subshell is valid\n  testPrecondition( interaction_subshell != Data::INVALID_SUBSHELL &&\n                    interaction_subshell !=Data::UNKNOWN_SUBSHELL );\n  // Make sure the subshell occupancy is valid\n  testPrecondition( subshell_occupancy > 0.0 );\n  // Make sure the subshell binding energy is valid\n  testPrecondition( subshell_binding_energy > 0.0 );\n  // Make sure the Compton profile is valid\n  testPrecondition( compton_profile.get() );\n  testPrecondition( ComptonProfilePolicy::isValidProfile( *compton_profile ) );\n}\n\n// Evaluate the distribution\n/*! \\details 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 StandardSubshellDopplerBroadenedPhotonEnergyDistribution<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  // Calculate the max electron momentum projection\n  ComptonProfile::MomentumQuantity max_electron_momentum_projection =\n    calculateMaxElectronMomentumProjection( incoming_energy,\n                                            this->getSubshellBindingEnergy(),\n                                            scattering_angle_cosine )*\n    ComptonProfile::MomentumUnit();\n\n  // Evaluate the Compton profile\n  ComptonProfile::ProfileQuantity compton_profile_quantity = \n    ComptonProfilePolicy::evaluateWithPossibleLimit(\n                   *d_compton_profile,\n                   electron_momentum_projection*ComptonProfile::MomentumUnit(),\n                   max_electron_momentum_projection );\n\n  // Evaluate the cross section\n  const double multiplier = this->evaluateMultiplier(incoming_energy,\n                                                     scattering_angle_cosine );\n\n  const double relativistic_term = this->evaluateRelativisticTerm(\n                                                     incoming_energy,\n                                                     scattering_angle_cosine );\n\n  const double cross_section =\n    multiplier*relativistic_term*this->getSubshellOccupancy()*\n    compton_profile_quantity.value();\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 distribution\n/*! \\details The distribution has units of barns/MeV.\n */\ntemplate<typename ComptonProfilePolicy>\ndouble StandardSubshellDopplerBroadenedPhotonEnergyDistribution<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 scattering angle is valid\n  testPrecondition( scattering_angle_cosine >= -1.0 );\n  testPrecondition( scattering_angle_cosine <= 1.0 );\n\n  // The evaluated double differential cross section\n  double cross_section;\n\n  if( outgoing_energy <= incoming_energy - this->getSubshellBindingEnergy() )\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    // Evaluate the Compton profile\n    ComptonProfile::ProfileQuantity compton_profile_quantity =\n      ComptonProfilePolicy::evaluate( *d_compton_profile,\n                                      electron_momentum_projection );\n\n    // Evaluate the cross section\n    const double multiplier = this->evaluateMultiplierExact(\n                                                     incoming_energy,\n                                                     outgoing_energy,\n                                                     scattering_angle_cosine );\n\n    const double relativistic_term = this->evaluateRelativisticTermExact(\n                                                     incoming_energy,\n                                                     outgoing_energy,\n                                                     scattering_angle_cosine );\n\n    cross_section = multiplier*relativistic_term*this->getSubshellOccupancy()*\n      compton_profile_quantity.value();\n  }\n  else\n    cross_section = 0.0;\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 PDF with electron momentum projection\n/*! \\details 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 PDF\n * will be unitless since the unitless momentum is being used.\n */\ntemplate<typename ComptonProfilePolicy>\ndouble StandardSubshellDopplerBroadenedPhotonEnergyDistribution<ComptonProfilePolicy>::evaluatePDFWithElectronMomentumProjection(\n                              const double incoming_energy,\n                              const double electron_momentum_projection,\n                              const double scattering_angle_cosine,\n                              const double precision ) const\n{\n  const double diff_cross_section =\n    this->evaluateWithElectronMomentumProjection( incoming_energy,\n                                                  electron_momentum_projection,\n                                                  scattering_angle_cosine );\n\n  const double integrated_cross_section =\n    this->evaluateIntegratedCrossSection( incoming_energy,\n                                          scattering_angle_cosine,\n                                          precision );\n\n  if( integrated_cross_section > 0.0 )\n    return diff_cross_section/integrated_cross_section;\n  else\n    return 0.0;\n}\n\n// Evaluate the PDF\n/*! \\details The PDF has units of inverse MeV.\n */\ntemplate<typename ComptonProfilePolicy>\ndouble StandardSubshellDopplerBroadenedPhotonEnergyDistribution<ComptonProfilePolicy>::evaluatePDFExact( \n\t\t\t           const double incoming_energy,\n\t\t\t\t   const double outgoing_energy,\n\t\t\t           const double scattering_angle_cosine,\n                                   const double precision ) const\n{\n  const double diff_cross_section =\n    this->evaluateExact( incoming_energy,\n                         outgoing_energy,\n                         scattering_angle_cosine );\n  \n  const double integrated_cross_section =\n    this->evaluateIntegratedCrossSectionExact( incoming_energy,\n                                               scattering_angle_cosine,\n                                               precision );\n\n  if( integrated_cross_section > 0.0 )\n    return diff_cross_section/integrated_cross_section;\n  else\n    return 0.0;\n}\n\n// Evaluate the integrated cross section (b/mu)\ntemplate<typename ComptonProfilePolicy>\ndouble StandardSubshellDopplerBroadenedPhotonEnergyDistribution<ComptonProfilePolicy>::evaluateIntegratedCrossSection(\n\t\t\t\t\t  const double incoming_energy,\n\t\t\t\t\t  const double scattering_angle_cosine,\n\t\t\t\t\t  const double precision ) const\n{\n  // Make sure the incoming energy is valid\n  testPrecondition( incoming_energy > 0.0 );\n  // 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>( &StandardSubshellDopplerBroadenedPhotonEnergyDistribution::evaluateWithElectronMomentumProjection,\n                         boost::cref( *this ),\n                         incoming_energy,\n                         _1,\n                         scattering_angle_cosine );\n\n  // Get the subshell binding energy\n  const double binding_energy = this->getSubshellBindingEnergy();\n\n  // Calculate the max electron momentum projection\n  double pz_max =\n    calculateMaxElectronMomentumProjection( incoming_energy,\n                                            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                               *d_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 (b/mu)\ntemplate<typename ComptonProfilePolicy>\ndouble StandardSubshellDopplerBroadenedPhotonEnergyDistribution<ComptonProfilePolicy>::evaluateIntegratedCrossSectionExact( \n\t\t\t\t\t  const double incoming_energy,\n\t\t\t\t\t  const double scattering_angle_cosine,\n\t\t\t\t\t  const double precision ) const\n{\n  // Make sure the incoming energy is valid\n  testPrecondition( incoming_energy > 0.0 );\n  // 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>( &StandardSubshellDopplerBroadenedPhotonEnergyDistribution::evaluateExact,\n                         boost::cref( *this ),\n                         incoming_energy,\n                         _1,\n                         scattering_angle_cosine );\n\n  // Calculate the max energy\n  double energy_max = incoming_energy - this->getSubshellBindingEnergy();\n\n  // Calculate the max electron momentum projection\n  double pz_max =\n    calculateMaxElectronMomentumProjection( incoming_energy,\n                                            this->getSubshellBindingEnergy(),\n                                            scattering_angle_cosine );\n\n  // Calculate the max table energy\n  const double pz_table_max =\n    ComptonProfilePolicy::getUpperBoundOfMomentum(*d_compton_profile).value();\n\n  // Don't go above the table max (profile will evaluate to zero beyond it)\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 outgoing energy from the distribution\ntemplate<typename ComptonProfilePolicy>\nvoid StandardSubshellDopplerBroadenedPhotonEnergyDistribution<ComptonProfilePolicy>::sample(\n\t\t\t\t     const double incoming_energy,\n\t\t\t\t     const double scattering_angle_cosine,\n\t\t\t\t     double& outgoing_energy,\n\t\t\t\t     Data::SubshellType& shell_of_interaction ) const\n{\n  Counter trial_dummy;\n\n  this->sampleAndRecordTrials( incoming_energy,\n\t\t\t       scattering_angle_cosine,\n\t\t\t       outgoing_energy,\n\t\t\t       shell_of_interaction,\n\t\t\t       trial_dummy );\n}\n\n// Sample an outgoing energy and record the number of trials\ntemplate<typename ComptonProfilePolicy>\nvoid StandardSubshellDopplerBroadenedPhotonEnergyDistribution<ComptonProfilePolicy>::sampleAndRecordTrials(\n                                      const double incoming_energy,\n                                      const double scattering_angle_cosine,\n                                      double& outgoing_energy,\n\t\t\t\t      Data::SubshellType& shell_of_interaction,\n                                      Counter& trials ) const\n{\n  // Make sure the incoming energy is valid\n  testPrecondition( incoming_energy >= this->getSubshellBindingEnergy() );\n  // Make sure the scattering angle cosine is valid\n  testPrecondition( scattering_angle_cosine >= -1.0 );\n  testPrecondition( scattering_angle_cosine <= 1.0 );\n\n  // Calculate the max electron momentum projection\n  ComptonProfile::MomentumQuantity pz_max = ComptonProfile::MomentumUnit()*\n    calculateMaxElectronMomentumProjection( incoming_energy,\n\t\t\t\t\t    this->getSubshellBindingEnergy(),\n\t\t\t\t\t    scattering_angle_cosine );\n\n  // Calculate the doppler broadened energy\n  bool energetically_possible = false;\n\n  while( !energetically_possible )\n  {\n    double pz;\n\n    this->sampleMomentumAndRecordTrials( incoming_energy,\n                                         scattering_angle_cosine,\n                                         pz,\n                                         shell_of_interaction,\n                                         trials );\n\n    outgoing_energy = calculateDopplerBroadenedEnergy(pz,\n\t\t\t\t\t\t      incoming_energy,\n\t\t\t\t\t\t      scattering_angle_cosine,\n\t\t\t\t\t\t      energetically_possible );\n  }\n\n  // An energy of zero is not allowed in the rest of the code\n  if( outgoing_energy == 0.0 )\n    outgoing_energy = std::numeric_limits<double>::min();\n\n  // Make sure the outgoing energy is valid\n  testPostcondition( energetically_possible );\n  testPostcondition( outgoing_energy >= 0.0 );\n}\n\n// Sample an electron momentum projection and record the number of trials\ntemplate<typename ComptonProfilePolicy>\nvoid StandardSubshellDopplerBroadenedPhotonEnergyDistribution<ComptonProfilePolicy>::sampleMomentumAndRecordTrials(\n                                      const double incoming_energy,\n                                      const double scattering_angle_cosine,\n                                      double& electron_momentum_projection,\n                                      Data::SubshellType& shell_of_interaction,\n                                      Counter& trials ) const\n{\n  // Make sure the incoming energy is valid\n  testPrecondition( incoming_energy >= this->getSubshellBindingEnergy() );\n  // Make sure the scattering angle cosine is valid\n  testPrecondition( scattering_angle_cosine >= -1.0 );\n  testPrecondition( scattering_angle_cosine <= 1.0 );\n\n  ++trials;\n\n  // Calculate the max electron momentum projection\n  ComptonProfile::MomentumQuantity pz_max = ComptonProfile::MomentumUnit()*\n    calculateMaxElectronMomentumProjection( incoming_energy,\n\t\t\t\t\t    this->getSubshellBindingEnergy(),\n\t\t\t\t\t    scattering_angle_cosine );\n\n  // Calculate the doppler broadened energy\n  ComptonProfile::MomentumQuantity pz =\n    ComptonProfilePolicy::sample( *d_compton_profile, pz_max );\n\n  electron_momentum_projection = pz.value();\n\n  shell_of_interaction = this->getSubshell();\n}\n\nEXTERN_EXPLICIT_TEMPLATE_CLASS_INST( StandardSubshellDopplerBroadenedPhotonEnergyDistribution<FullComptonProfilePolicy> );\nEXTERN_EXPLICIT_TEMPLATE_CLASS_INST( StandardSubshellDopplerBroadenedPhotonEnergyDistribution<HalfComptonProfilePolicy> );\nEXTERN_EXPLICIT_TEMPLATE_CLASS_INST( StandardSubshellDopplerBroadenedPhotonEnergyDistribution<DoubledHalfComptonProfilePolicy> );\n\n} // end MonteCarlo namespace\n\n#endif // end MONTE_CARLO_STANDARD_SUBSHELL_DOPPLER_BROADENED_PHOTON_ENERGY_DISTRIBUTION_DEF_HPP\n\n//---------------------------------------------------------------------------//\n// end MonteCarlo_StandardSubshellDopplerBroadenedPhotonEnergyDistribution_def.hpp\n//---------------------------------------------------------------------------//\n", "meta": {"hexsha": "a7e312c5885db72aa810532aa9ea828743a7d353", "size": 18494, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "packages/monte_carlo/collision/photon/src/MonteCarlo_StandardSubshellDopplerBroadenedPhotonEnergyDistribution_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_StandardSubshellDopplerBroadenedPhotonEnergyDistribution_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_StandardSubshellDopplerBroadenedPhotonEnergyDistribution_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": 41.7471783296, "max_line_length": 137, "alphanum_fraction": 0.6532388883, "num_tokens": 3523, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7772998508568416, "lm_q2_score": 0.43398146480389854, "lm_q1q2_score": 0.337333727866704}}
{"text": "//\n// Copyright Jesse Manning 2007\n//\n// Distributed under the Boost Software License, Version 1.0.\n// (See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n//\n\n#ifndef BOOST_NUMERIC_BINDINGS_LAPACK_GELSS_HPP\n#define BOOST_NUMERIC_BINDINGS_LAPACK_GELSS_HPP\n\n#include <algorithm>\n\n#include <boost/numeric/bindings/traits/type.hpp>\n#include <boost/numeric/bindings/traits/traits.hpp>\n#include <boost/numeric/bindings/traits/type_traits.hpp>\n#include <boost/numeric/bindings/lapack/lapack.h>\n#include <boost/numeric/bindings/lapack/workspace.hpp>\n#include <boost/numeric/bindings/traits/detail/array.hpp>\n#include <boost/numeric/bindings/traits/detail/utils.hpp>\n\n\n#ifndef BOOST_NUMERIC_BINDINGS_NO_STRUCTURE_CHECK \n#  include <boost/static_assert.hpp>\n#  include <boost/type_traits.hpp>\n#endif\n\nnamespace boost { namespace numeric { namespace bindings {\n\n    namespace lapack {\n\n        namespace detail {\n\n            inline void gelss(const integer_t m, const integer_t n, const integer_t nrhs,\n                              float *a, const integer_t lda, float *b, const integer_t ldb,\n                              float *s, const float rcond, integer_t *rank, float *work,\n                              const integer_t lwork, integer_t *info)\n            {\n                LAPACK_SGELSS(&m, &n, &nrhs, a, &lda, b, &ldb, s, &rcond, rank, work, &lwork, info);\n            }\n\n            inline void gelss(const integer_t m, const integer_t n, const integer_t nrhs,\n                              double *a, const integer_t lda, double *b, const integer_t ldb,\n                              double *s, const double rcond, integer_t *rank, double *work,\n                              const integer_t lwork, integer_t *info)\n            {\n                LAPACK_DGELSS(&m, &n, &nrhs, a, &lda, b, &ldb, s, &rcond, rank, work, &lwork, info);\n            }\n\n            inline void gelss(const integer_t m, const integer_t n, const integer_t nrhs,\n                              traits::complex_f *a, const integer_t lda, traits::complex_f *b,\n                              const integer_t ldb, float *s, const float rcond, integer_t *rank,\n                              traits::complex_f *work, const integer_t lwork, float *rwork, integer_t *info)\n            {\n                LAPACK_CGELSS(&m, &n, &nrhs, traits::complex_ptr(a),\n                              &lda, traits::complex_ptr(b), &ldb, s,\n                              &rcond, rank, traits::complex_ptr(work),\n                              &lwork, rwork, info);\n            }\n\n            inline void gelss(const integer_t m, const integer_t n, const integer_t nrhs,\n                              traits::complex_d *a, const integer_t lda, traits::complex_d *b,\n                              const integer_t ldb, double *s, const double rcond, integer_t *rank,\n                              traits::complex_d *work, const integer_t lwork, double *rwork, integer_t *info)\n            {\n                LAPACK_ZGELSS(&m, &n, &nrhs, traits::complex_ptr(a),\n                              &lda, traits::complex_ptr(b), &ldb, s,\n                              &rcond, rank, traits::complex_ptr(work),\n                              &lwork, rwork, info);\n            }\n\n            // gelss for real type\n            template <typename MatrA, typename MatrB, typename VecS, typename Work>\n            int gelss(MatrA& A, MatrB& B, VecS& s, Work& work)\n            {\n                typedef typename MatrA::value_type val_t;\n                typedef typename traits::type_traits<val_t>::real_type real_t;\n\n                const std::ptrdiff_t m = traits::matrix_size1(A);\n                const std::ptrdiff_t n = traits::matrix_size2(A);\n                const std::ptrdiff_t nrhs = traits::matrix_size2(B);\n                const std::ptrdiff_t maxmn = std::max(m, n);\n                const std::ptrdiff_t minmn = std::min(m, n);\n\n                // sanity checks\n                assert(m >= 0 && n >= 0);\n                assert(nrhs >= 0);\n                assert(traits::leading_dimension(A) >= std::max<std::ptrdiff_t>(1, m));\n                assert(traits::leading_dimension(B) >= std::max<std::ptrdiff_t>(1, maxmn));\n                assert(traits::vector_size(work) >= 1);\n                assert(traits::vector_size(s) >= std::max<std::ptrdiff_t>(1, minmn));\n\n                integer_t info;\n                const real_t rcond = -1;    // use machine precision\n                integer_t rank;\n\n                detail::gelss(traits::matrix_size1(A),\n                              traits::matrix_size2(A),\n                              traits::matrix_size2(B),\n                              traits::matrix_storage(A),\n                              traits::leading_dimension(A),\n                              traits::matrix_storage(B),\n                              traits::leading_dimension(B),\n                              traits::vector_storage(s),\n                              rcond,\n                              &rank,\n                              traits::vector_storage(work),\n                              traits::vector_size(work),\n                              &info);\n\n                return info;\n            }\n\n            // gelss for complex type\n            template <typename MatrA, typename MatrB, typename VecS, typename Work, typename RWork>\n            int gelss(MatrA& A, MatrB& B, VecS& s, Work& work, RWork& rwork)\n            {\n                typedef typename MatrA::value_type val_t;\n                typedef typename traits::type_traits<val_t>::real_type real_t;\n\n                const std::ptrdiff_t m = traits::matrix_size1(A);\n                const std::ptrdiff_t n = traits::matrix_size2(A);\n                const std::ptrdiff_t nrhs = traits::matrix_size2(B);\n                const std::ptrdiff_t maxmn = std::max(m, n);\n                const std::ptrdiff_t minmn = std::min(m, n);\n\n                // sanity checks\n                assert(m >= 0 && n >= 0);\n                assert(nrhs >= 0);\n                assert(traits::leading_dimension(A) >= std::max<std::ptrdiff_t>(1, m));\n                assert(traits::leading_dimension(B) >= std::max<std::ptrdiff_t>(1, maxmn));\n                assert(traits::vector_size(work) >= 1);\n                assert(traits::vector_size(s) >= std::max<std::ptrdiff_t>(1, minmn));\n\n                integer_t info;\n                const real_t rcond = -1;    // use machine precision\n                integer_t rank;\n\n                detail::gelss(traits::matrix_size1(A),\n                              traits::matrix_size2(A),\n                              traits::matrix_size2(B),\n                              traits::matrix_storage(A),\n                              traits::leading_dimension(A),\n                              traits::matrix_storage(B),\n                              traits::leading_dimension(B),\n                              traits::vector_storage(s),\n                              rcond,\n                              &rank,\n                              traits::vector_storage(work),\n                              traits::vector_size(work),\n                              traits::vector_storage(rwork),\n                              &info);\n\n                return info;\n            }\n\n            // default minimal workspace functor\n            template <int N>\n            struct Gelss { };\n\n            // specialization for gelss (sgelss, dgelss)\n            template <>\n            struct Gelss<1>\n            {\n                template <typename MatrA, typename MatrB, typename VecS>\n                int operator() (MatrA& A, MatrB& B, VecS& s, minimal_workspace) const\n                {\n                    typedef typename traits::matrix_traits<MatrA>::value_type val_t;\n\n                    const std::ptrdiff_t m = traits::matrix_size1(A);\n                    const std::ptrdiff_t n = traits::matrix_size2(A);\n                    const std::ptrdiff_t rhs = traits::matrix_size2(B);\n\n                    const std::ptrdiff_t minmn = std::min(m, n);           // minmn = m < n ? m : n\n                    const std::ptrdiff_t maxmn = std::max(m, n);           // maxmn = m > n ? m : n\n                    const std::ptrdiff_t maxmnr = std::max(maxmn, rhs);    // maxmnr = maxmn > rhs ? maxmn : rhs\n\n                    traits::detail::array<val_t> work(3*minmn + std::max(2*minmn, maxmnr));\n\n                    return gelss(A, B, s, work);\n                }\n\n                template <typename MatrA, typename MatrB, typename VecS>\n                int operator() (MatrA& A, MatrB& B, VecS& s, optimal_workspace) const\n                {\n                    typedef typename traits::matrix_traits<MatrA>::value_type val_t;\n                    typedef typename traits::type_traits<val_t>::real_type real_t;\n\n                    //const std::ptrdiff_t m = traits::matrix_size1(A);\n                    //const std::ptrdiff_t n = traits::matrix_size2(A);\n                    //const std::ptrdiff_t rhs = traits::matrix_size2(B);\n\n                    //const std::ptrdiff_t minmn = std::min(m, n);           // minmn = m < n ? m : n\n                    //const std::ptrdiff_t maxmn = std::max(m, n);           // maxmn = m > n ? m : n\n                    //const std::ptrdiff_t maxmnr = std::max(maxmn, rhs);    // maxmnr = maxmn > rhs ? maxmn : rhs\n\n                    val_t temp_work;\n\n                    const real_t rcond = -1;\n                    integer_t rank;\n                    integer_t info;\n\n                    // query for optimal workspace size\n                    detail::gelss(traits::matrix_size1(A),\n                        traits::matrix_size2(A),\n                        traits::matrix_size2(B),\n                        traits::matrix_storage(A),\n                        traits::leading_dimension(A),\n                        traits::matrix_storage(B),\n                        traits::leading_dimension(B),\n                        traits::vector_storage(s),\n                        rcond,\n                        &rank,\n                        &temp_work, //traits::vector_storage(work),\n                        -1,         //traits::vector_size(work),\n                        &info);\n\n                    assert(info == 0);\n\n                    const integer_t lwork = traits::detail::to_int(temp_work);\n\n                    traits::detail::array<val_t> work(lwork);\n\n                    return gelss(A, B, s, work);\n                }\n\n                template <typename MatrA, typename MatrB, typename VecS, typename Work>\n                int operator() (MatrA& A, MatrB& B, VecS& s, detail::workspace1<Work> workspace) const\n                {\n                    return gelss(A, B, s, workspace.select(typename traits::matrix_traits<MatrA>::value_type()));\n                }\n            };\n\n            // specialization for gelss (cgelss, zgelss)\n            template <>\n            struct Gelss<2>\n            {\n                template <typename MatrA, typename MatrB, typename VecS>\n                int operator() (MatrA& A, MatrB& B, VecS& s, minimal_workspace) const\n                {\n                    typedef typename traits::matrix_traits<MatrA>::value_type val_t;\n                    typedef typename traits::type_traits<val_t>::real_type real_t;\n\n                    const std::ptrdiff_t m = traits::matrix_size1(A);\n                    const std::ptrdiff_t n = traits::matrix_size2(A);\n                    const std::ptrdiff_t rhs = traits::matrix_size2(B);\n\n                    const std::ptrdiff_t minmn = std::min(m, n);           // minmn = m < n ? m : n\n                    const std::ptrdiff_t maxmn = std::max(m, n);           // maxmn = m > n ? m : n\n                    const std::ptrdiff_t maxmnr = std::max(maxmn, rhs);    // maxmnr = maxmn > rhs ? maxmn : rhs\n\n                    traits::detail::array<val_t> work(2*minmn + maxmnr);\n                    traits::detail::array<real_t> rwork(std::max<std::ptrdiff_t>(1, (5*minmn)));\n\n                    return gelss(A, B, s, work, rwork);\n                }\n\n                template <typename MatrA, typename MatrB, typename VecS>\n                int operator() (MatrA& A, MatrB& B, VecS& s, optimal_workspace) const\n                {\n                    typedef typename MatrA::value_type val_t;\n                    typedef typename traits::type_traits<val_t>::real_type real_t;\n\n                    const std::ptrdiff_t m = traits::matrix_size1(A);\n                    const std::ptrdiff_t n = traits::matrix_size2(A);\n                    //const std::ptrdiff_t rhs = traits::matrix_size2(B);\n\n                    const std::ptrdiff_t minmn = std::min(m, n);           // minmn = m < n ? m : n\n                    //const std::ptrdiff_t maxmn = std::max(m, n);           // maxmn = m > n ? m : n\n                    //const std::ptrdiff_t maxmnr = std::max(maxmn, rhs);    // maxmnr = maxmn > rhs ? maxmn : rhs\n\n                    val_t temp_work;\n                    real_t temp_rwork;\n\n                    const real_t rcond = -1;\n                    integer_t rank;\n                    integer_t info;\n\n                    // query for optimal workspace size\n                    detail::gelss(traits::matrix_size1(A),\n                                  traits::matrix_size2(A),\n                                  traits::matrix_size2(B),\n                                  traits::matrix_storage(A),\n                                  traits::leading_dimension(A),\n                                  traits::matrix_storage(B),\n                                  traits::leading_dimension(B),\n                                  traits::vector_storage(s),\n                                  rcond,\n                                  &rank,\n                                  &temp_work,   //traits::vector_storage(work),\n                                  -1,           //traits::vector_size(work),\n                                  &temp_rwork,\n                                  &info);\n\n                    assert(info == 0);\n\n                    const integer_t lwork = traits::detail::to_int(temp_work);\n\n                    traits::detail::array<val_t> work(lwork);\n                    traits::detail::array<real_t> rwork(std::max<std::ptrdiff_t>(1, (5*minmn)));\n\n                    return gelss(A, B, s, work, rwork);\n                }\n\n                template <typename MatrA, typename MatrB, typename VecS, typename Work, typename RWork>\n                int operator() (MatrA& A, MatrB& B, VecS& s, detail::workspace2<Work, RWork> workspace) const\n                {\n                  typedef typename traits::matrix_traits<MatrA>::value_type    value_type ;\n                  typedef typename traits::type_traits<value_type>::real_type real_type ;\n                    return gelss(A, B, s, workspace.select(value_type()), workspace.select(real_type()));\n                }\n            };\n\n        } // detail\n\n        // gelss\n        // Parameters:\n        //  A:          matrix of coefficients\n        //  B:          matrix of solutions (stored column-wise)\n        //  s:          vector to store singular values on output, length >= max(1, min(m,n))\n        //  workspace:  either optimal, minimal, or user supplied\n        //\n        template <typename MatrA, typename MatrB, typename VecS, typename Work>\n        int gelss(MatrA& A, MatrB& B, VecS& s, Work workspace)\n        {\n            typedef typename traits::matrix_traits<MatrA>::value_type val_t;\n\n            return detail::Gelss<n_workspace_args<val_t>::value>() (A, B, s, workspace);\n        }\n\n        // gelss, no singular values are returned\n        // Parameters:\n        //  A:          matrix of coefficients\n        //  B:          matrix of solutions (stored column-wise)\n        //  workspace:  either optimal, minimal, or user supplied\n        //\n        template <typename MatrA, typename MatrB, typename Work>\n        int gelss(MatrA& A, MatrB& B, Work workspace)\n        {\n            typedef typename traits::matrix_traits<MatrA>::value_type val_t;\n            typedef typename traits::type_traits<val_t>::real_type real_t;\n\n            const std::ptrdiff_t m = traits::matrix_size1(A);\n            const std::ptrdiff_t n = traits::matrix_size2(A);\n\n            const std::ptrdiff_t s_size = std::max<std::ptrdiff_t>(1, std::min(m,n));\n            traits::detail::array<real_t> s(s_size);\n\n            return detail::Gelss<n_workspace_args<val_t>::value>() (A, B, s, workspace);\n        }\n\n    } // namespace lapack\n\n}}}\n\n#endif\n", "meta": {"hexsha": "ff110e60faa5ec8c2366c5ac6da56391bb198ffe", "size": 16490, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "PROX/3RDPARTY/BOOST_BINDINGS/boost_bindings/boost/numeric/bindings/lapack/gelss.hpp", "max_stars_repo_name": "diku-dk/PROX", "max_stars_repo_head_hexsha": "c6be72cc253ff75589a1cac28e4e91e788376900", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "PROX/3RDPARTY/BOOST_BINDINGS/boost_bindings/boost/numeric/bindings/lapack/gelss.hpp", "max_issues_repo_name": "diku-dk/PROX", "max_issues_repo_head_hexsha": "c6be72cc253ff75589a1cac28e4e91e788376900", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "PROX/3RDPARTY/BOOST_BINDINGS/boost_bindings/boost/numeric/bindings/lapack/gelss.hpp", "max_forks_repo_name": "diku-dk/PROX", "max_forks_repo_head_hexsha": "c6be72cc253ff75589a1cac28e4e91e788376900", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 46.1904761905, "max_line_length": 114, "alphanum_fraction": 0.4964827168, "num_tokens": 3611, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6442251064863697, "lm_q2_score": 0.523420348936324, "lm_q1q2_score": 0.3372005300306361}}
{"text": "#ifndef _DIAUMPIRE_BSPLINE_HPP_\n#define _DIAUMPIRE_BSPLINE_HPP_\n\n#include <vector>\n#include <fstream>\n#include <boost/math/distributions/chi_squared.hpp>\n#include <boost/algorithm/clamp.hpp>\n#include <boost/range/numeric.hpp>\n#include \"ScanData.hpp\"\n\nnamespace {\n    //implements relative method - do not use for comparing with zero\n    //use this most of the time, tolerance needs to be meaningful in your context\n    template<typename TReal>\n    static bool isApproximatelyEqual(TReal a, TReal b, TReal tolerance = std::numeric_limits<TReal>::epsilon())\n    {\n        TReal diff = std::fabs(a - b);\n        if (diff <= tolerance)\n            return true;\n\n        if (diff < std::fmax(std::fabs(a), std::fabs(b)) * tolerance)\n            return true;\n\n        return false;\n    }\n\n    //supply tolerance that is meaningful in your context\n    //for example, default tolerance may not work if you are comparing double with float\n    template<typename TReal>\n    static bool isApproximatelyZero(TReal a, TReal tolerance = std::numeric_limits<TReal>::epsilon())\n    {\n        if (std::fabs(a) <= tolerance)\n            return true;\n        return false;\n    }\n\n\n    //use this when you want to be on safe side\n    //for example, don't start rover unless signal is above 1\n    template<typename TReal>\n    static bool isDefinitelyLessThan(TReal a, TReal b, TReal tolerance = std::numeric_limits<TReal>::epsilon(), bool orEqualTo = false)\n    {\n        TReal diff = a - b;\n        if (diff < tolerance)\n            return orEqualTo;\n\n        if (diff < std::fmax(std::fabs(a), std::fabs(b)) * tolerance)\n            return true;\n\n        return false;\n    }\n    template<typename TReal>\n    static bool isDefinitelyGreaterThan(TReal a, TReal b, TReal tolerance = std::numeric_limits<TReal>::epsilon(), bool orEqualTo = false)\n    {\n        TReal diff = b - a;\n        if (diff < tolerance)\n            return orEqualTo;\n\n        if (diff < std::fmax(std::fabs(a), std::fabs(b)) * tolerance)\n            return true;\n\n        return false;\n    }\n\n    //implements ULP method\n    //use this when you are only concerned about floating point precision issue\n    //for example, if you want to see if a is 1.0 by checking if its within\n    //10 closest representable floating point numbers around 1.0.\n    template<typename TReal>\n    static bool isWithinPrecisionInterval(TReal a, TReal b, unsigned int interval_size = 1)\n    {\n        TReal min_a = a - (a - std::nextafter(a, std::numeric_limits<TReal>::lowest())) * interval_size;\n        TReal max_a = a + (std::nextafter(a, std::numeric_limits<TReal>::max()) - a) * interval_size;\n\n        return min_a <= b && max_a >= b;\n    }\n}\n\nnamespace DiaUmpire {\n\n#ifdef DIAUMPIRE_DEBUG\n    ofstream bsplineLog(\"bspline-log.txt\");\n    ofstream bsplineOutputLog(\"bspline-output-log.txt\");\n#endif\n\n/**\n * B-spline smoothing\n * @author Chih-Chiang Tsou <chihchiang.tsou@gmail.com>\n */\nclass BSpline\n{\n    std::vector<double> bspline_T_;\n\n    public:\n\n    XYPointCollection Run(const XYPointCollection& data, int PtNum, int smoothDegree, int logId)\n    {\n        XYPointCollection bsplineCollection;\n        int p = smoothDegree;\n        int n = data.Data.size() - 1;\n        int m = data.Data.size() + p;\n        bspline_T_.resize(m + p);\n\n        if (data.Data.size() <= (size_t) p) {\n            return data;\n        }\n\n        for (int i = 0; i <= n; i++) {\n            bspline_T_[i] = 0;\n            bspline_T_[m - i] = 1;\n        }\n        double intv = 1.0 / (m - 2 * p);\n        for (int i = 1; i <= (m - 1); i++) {\n            bspline_T_[p + i] = bspline_T_[p + i - 1] + intv;\n        }\n\n        double t;\n        for (int i = 0; i <= PtNum; i++) {\n            t = ((double)i / PtNum);\n            XYData pt = getbspline(data, t, n, p);\n            bsplineCollection.AddPoint(pt);\n        }\n        if (isDefinitelyLessThan(bsplineCollection.Data.back().getX(), data.Data.back().getX(), 1e-8f)) {\n            bsplineCollection.AddPoint(data.Data[data.PointCount() - 1]);\n        }\n        if (isDefinitelyGreaterThan(bsplineCollection.Data[0].getX(), data.Data[0].getX(), 1e-8f)) {\n            bsplineCollection.AddPoint(data.Data[0]);\n        }\n\n#ifdef DIAUMPIRE_DEBUG\n        if (logId > 0)\n        {\n            bsplineLog << setprecision(10)\n                << (bsplineCollection.Data.back().getX() == data.Data.back().getX())\n                << \" \" << isDefinitelyLessThan(bsplineCollection.Data.back().getX(), data.Data.back().getX(), 1e-8f)\n                << \" \" << (bsplineCollection.Data.back().getX() < data.Data.back().getX())\n                << \" \" << bsplineCollection.Data.back().getX()\n                << \" \" << data.Data.back().getX()\n                << \"\\n\";\n            boost::format pkFormat(\" %.3f\");\n            bsplineOutputLog << logId << \" \" << data.size() << \" \" << bsplineCollection.size();\n            for (auto& pk : bsplineCollection.Data)\n                bsplineOutputLog << (pkFormat % pk.x).str();\n            bsplineOutputLog << \"\\n\";\n        }\n#endif\n\n        return bsplineCollection;\n    }\n\n    XYData getbspline(const XYPointCollection& data, double t, int n, int p)\n    {\n        XYData pt(0, 0);\n\n        int itp = 0;\n        for (int i = 0; i <= n; i++) {\n            pt.x = (pt.getX() + data.Data[itp].getX() * bspline_base(i, p, t));\n            pt.y = (pt.getY() + data.Data[itp].getY() * bspline_base(i, p, t));\n            itp++;\n        }\n        return pt;\n    }\n\n    double bspline_base(int i, int p, double t)\n    {\n        double n, c1, c2;\n        double tn1 = 0;\n        double tn2 = 0;\n        if (p == 0) {\n            if (bspline_T_[i] <= t && t < bspline_T_[i + 1] && bspline_T_[i] < bspline_T_[i + 1]) {\n                n = 1;\n            }\n            else {\n                n = 0;\n            }\n        }\n        else {\n            if ((bspline_T_[i + p] - bspline_T_[i]) == 0) {\n                c1 = 0;\n            }\n            else {\n                tn1 = bspline_base(i, (p - 1), t);\n                c1 = (t - bspline_T_[i]) / (bspline_T_[i + p] - bspline_T_[i]);\n            }\n            if ((bspline_T_[i + p + 1] - bspline_T_[i + 1]) == 0) {\n                c2 = 0;\n            }\n            else {\n                tn2 = bspline_base((i + 1), (p - 1), t);\n                c2 = (bspline_T_[i + p + 1] - t) / (bspline_T_[i + p + 1] - bspline_T_[i + 1]);\n            }\n            n = (c1 * tn1) + (c2 * tn2);\n        }\n        return n;\n    }\n};\n\nclass LinearInterpolation\n{\n    public:\n\n    XYPointCollection Run(const XYPointCollection& data, int PtNum)\n    {\n        std::vector<XYData> Smoothdata(PtNum);\n        float intv = (data.Data[data.PointCount() - 1].getX() - data.Data[0].getX()) / (float)PtNum;\n        float rt = data.Data[0].getX();\n        for (int i = 0; i < PtNum; i++) {\n            Smoothdata[i] = XYData{ intv * i + rt, -1 };\n        }\n        int index = 0;\n        for (const XYData& point : data.Data)\n        {\n            //XYData closet = Smoothdata[index];\n            bool found = false;\n            for (int i = index; i < PtNum - 1; i++) {\n                if (Smoothdata[i].getX() <= point.getX() && Smoothdata[i + 1].getX() > point.getX()) {\n                    Smoothdata[i].y = (point.getY());\n                    index = i;\n                    found = true;\n                    break;\n                }\n            }\n            if (!found) {\n                Smoothdata[PtNum - 1].y = (point.getY());\n                index = PtNum - 1;\n            }\n        }\n\n        bool gapfound = false;\n        int startidx = 0;\n        int endidx = 0;\n        float startintensity = Smoothdata[0].getY();\n        float endintensity = Smoothdata[0].getY();\n\n        for (int i = 1; i < PtNum; i++)\n        {\n            if (gapfound && Smoothdata[i].getY() != -1) {\n                endidx = i;\n                endintensity = Smoothdata[i].getY();\n                Smoothdata[(startidx + endidx) / 2].y = ((startintensity + endintensity) / 2);\n                i = startidx;\n                gapfound = false;\n            }\n            if (!gapfound && Smoothdata[i].getY() == -1) {\n                startidx = i - 1;\n                startintensity = Smoothdata[i - 1].getY();\n                gapfound = true;\n            }\n        }\n        XYPointCollection returndata;\n        swap(returndata.Data, Smoothdata);\n        return returndata;\n    }\n};\n\n\n/*\n *This class implements the Continuous Wavelet Transform (CWT), Mexican Hat,\n * over raw datapoints of a certain spectrum. After get the spectrum in the\n * wavelet's time domain, we use the local maxima to detect possible peaks in\n * the original raw datapoints.\n * Described in Tautenhahn, R., Bottcher, C. & Neumann, S. \n * Highly sensitive feature detection for high resolution LC/MS. \n * BMC Bioinformatics 9, 504 (2008).\n */\nclass WaveletMassDetector\n{\n    /**\n     * Parameters of the wavelet, NPOINTS is the number of wavelet values to use\n     * The WAVELET_ESL & WAVELET_ESL indicates the Effective Support boundaries\n     */\n    double NPOINTS;\n    int WAVELET_ESL = -5;\n    int WAVELET_ESR = 5;\n    #define waveletDebug false\n    const InstrumentParameter& parameter;\n    std::vector<XYData>& DataPoint;\n    double waveletWindow = (double) 0.3;\n    std::vector<float> MEXHAT;\n    double NPOINTS_half;\n\n    public:\n\n    WaveletMassDetector(const InstrumentParameter& parameter, std::vector<XYData>& DataPoint, int NoPoints) : parameter(parameter), DataPoint(DataPoint)\n    {\n        NPOINTS = NoPoints;\n\n        double wstep = ((WAVELET_ESR - WAVELET_ESL) / NPOINTS);\n        MEXHAT.resize(NPOINTS);\n\n        double waveletIndex = WAVELET_ESL;\n        for (int j = 0; j < NPOINTS; j++)\n        {\n            // Pre calculate the values of the wavelet\n            MEXHAT[j] = cwtMEXHATreal(waveletIndex, waveletWindow, 0.0);\n            waveletIndex += wstep;\n        }\n\n        NPOINTS_half = NPOINTS / 2;\n        d = (int) NPOINTS / (WAVELET_ESR - WAVELET_ESL);\n    }\n    int d;\n    //ArrayList<XYData>[] waveletCWT;\n    \n    //List of peak ridge (local maxima)\n    std::vector<std::unique_ptr<std::vector<XYData>>> PeakRidge;\n\n    void Run()\n    {\n        //\"Intensities less than this value are interpreted as noise\",                \n        //\"Scale level\",\n        //\"Number of wavelet'scale (coeficients) to use in m/z peak detection\"\n        //\"Wavelet window size (%)\",\n        //\"Size in % of wavelet window to apply in m/z peak detection\");        \n        int maxscale = (int) (std::max(std::min((DataPoint[DataPoint.size() - 1].getX() - DataPoint[0].getX()), parameter.MaxCurveRTRange), 0.5f) * parameter.NoPeakPerMin / (WAVELET_ESR + WAVELET_ESR));\n\n        //waveletCWT = new ArrayList[15];\n        PeakRidge.resize(maxscale);\n        //XYData maxint = new XYData(0f, 0f);\n        for (int scaleLevel = 0; scaleLevel < maxscale; scaleLevel++)\n        {\n            std::vector<XYData> wavelet = performCWT(scaleLevel * 2 + 5);\n            PeakRidge[scaleLevel] = std::make_unique<std::vector<XYData>>();\n            //waveletCWT[scaleLevel] = wavelet;\n            XYData lastpt = wavelet[0];\n            XYData localmax { 0, 0 };\n            XYData startpt = wavelet[0];\n\n            bool increasing = false;\n            bool decreasing = false;\n            XYData localmaxint { 0, 0 };\n\n            for (size_t cwtidx = 1; cwtidx < wavelet.size(); cwtidx++)\n            {\n                XYData& CurrentPoint = wavelet[cwtidx];\n                if (CurrentPoint.getY() > lastpt.getY()) {//the peak is increasing\n                    if (decreasing) {//first increasing point, last point was a possible local minimum\n                        //check if the peak was symetric\n                        if (localmax.y > 0 && (lastpt.getY() <= startpt.getY() || abs(lastpt.getY() - startpt.getY()) / localmax.getY() < parameter.SymThreshold)) {\n                            PeakRidge[scaleLevel]->push_back(localmax);\n                            localmax = CurrentPoint;\n                            startpt = lastpt;\n                        }\n                    }\n                    increasing = true;\n                    decreasing = false;\n                } else if (CurrentPoint.getY() < lastpt.getY()) {//peak decreasing\n                    if (increasing) {//first point decreasing, last point was a possible local maximum\n                        if (localmax.getY() < lastpt.getY()) {\n                            localmax = lastpt;\n                        }\n                    }\n                    decreasing = true;\n                    increasing = false;\n                }\n                lastpt = CurrentPoint;\n                if (CurrentPoint.getY() > localmaxint.getY()) {\n                    localmaxint = CurrentPoint;\n                }\n                if (cwtidx == wavelet.size() - 1 && decreasing) {\n                    if (localmax.y > 0 && (CurrentPoint.getY() <= startpt.getY() || abs(CurrentPoint.getY() - startpt.getY()) / localmax.getY() < parameter.SymThreshold)) {\n                        PeakRidge[scaleLevel]->push_back(localmax);\n                    }\n                }\n            }\n\n            if (!waveletDebug) {\n                wavelet.clear();\n                //wavelet = null;\n            }\n        }\n    }\n\n    private:\n\n    /**\n     * Perform the CWT over raw data points in the selected scale level\n     *\n     *\n     */\n    std::vector<XYData> performCWT(int scaleLevel)\n    {\n        int length = DataPoint.size();\n        std::vector<XYData> cwtDataPoints(length);\n\n        int a_esl = scaleLevel * WAVELET_ESL;\n        int a_esr = scaleLevel * WAVELET_ESR;\n        int NPOINTS_half = (int) this->NPOINTS_half;\n        int NPOINTS = (int) this->NPOINTS;\n        double sqrtScaleLevel = sqrt(scaleLevel);\n        /*std::vector<float> intensities(length + a_esr);\n        std::vector<float> yValues(DataPoint.size());\n        for(size_t i=0 ;i < yValues.size(); ++i)\n            yValues[i] = DataPoint[i].y;*/\n\n        for (int dx = 0; dx < length; dx++)\n        {\n            /*\n             * Compute wavelet boundaries\n             */\n            int t1 = a_esl + dx;\n            if (t1 < 0) {\n                t1 = 0;\n            }\n            int t2 = a_esr + dx;\n            if (t2 >= length) {\n                t2 = (length - 1);\n            }\n\n            /*\n             * Perform convolution\n             */\n            float intensity = 0;\n            int ind;\n            //float* intensityPtr = &intensities[0];\n            //float* yValuesPtr = &yValues[t1];\n            //float* MEXHATPtr = &MEXHAT[0];\n            for (int i = t1; i <= t2; ++i/*, ++yValuesPtr*/) {\n                ind = NPOINTS_half + (d * (i - dx) / scaleLevel);\n                ind = boost::algorithm::clamp(ind, 0, NPOINTS - 1);\n                intensity += DataPoint[i].y * MEXHAT[ind];\n                //intensity += *yValuesPtr * MEXHATPtr[ind];\n                //intensityPtr[i] = yValuesPtr[i] * MEXHATPtr[ind];\n            }\n            //intensity = std::accumulate(intensities.begin() + t1, intensities.begin() + t2 + 1, 0.f);\n            intensity /= sqrtScaleLevel;\n            // Eliminate the negative part of the wavelet map\n            if (intensity < 0) {\n                intensity = 0;\n            }\n            cwtDataPoints[dx].x = DataPoint[dx].getX();\n            cwtDataPoints[dx].y = intensity;\n        }\n        return cwtDataPoints;\n    }\n\n    /**\n     * This function calculates the wavelets's coefficients in Time domain\n     *\n     * @param double x Step of the wavelet\n     * @param double a Window Width of the wavelet\n     * @param double b Offset from the center of the peak\n     */\n    double cwtMEXHATreal(double x, double window, double b)\n    {\n        /*\n         * c = 2 / ( sqrt(3) * pi^(1/4) )\n         */\n        double c = 0.8673250705840776;\n        double TINY = 1E-200;\n        double x2;\n\n        if (window == 0.0) {\n            window = TINY;\n        }\n        //x-b=t\n        //window=delta\n        x = (x - b) / window;\n        x2 = x * x;\n        return c * (1.0 - x2) * std::exp(-x2 / 2);\n    }\n    /**\n     * This function searches for maximums from wavelet data points\n     */\n};\n\n\nstruct MassDefect\n{\n    bool InMassDefectRange(float mass, float d)\n    {\n        //upper = 0.00052738*x + 0.066015 +0.1 \n        //lower = 0.00042565*x + 0.00038210 -0.1\n\n        double u = GetMassDefect(0.00052738*mass + 0.066015 + d);\n        double l = GetMassDefect(0.00042565*mass + 0.00038210 - d);\n\n        double defect = GetMassDefect(mass);\n        if (u > l) {\n            return (defect >= l && defect <= u);\n        }\n        return (defect >= l || defect <= u);\n    }\n\n    double GetMassDefect(double mass)\n    {\n        return mass - std::floor(mass);\n    }\n};\n\n\nstruct Regression\n{\n    /// <summary>\n    /// Equation class: y=mx+b\n    /// </summary>\n    struct Equation {\n\n        float Bvalue;\n        float Mvalue;\n        float SDvalue;\n        float R2value;\n        int NoPoints;\n        float CorrelationCoffe;\n\n        string GetEquationText() {\n            return \"Y=(\" + lexical_cast<string>(std::round(Mvalue * 1000) / 1000) + \")X+\" + lexical_cast<string>(std::round(Bvalue * 1000) / 1000);\n        }\n    };\n\n    Equation equation;\n    int MinPoint = 3;\n\n    Regression(const XYPointCollection& pointset) : pointset(pointset)\n    {\n        FindEquation();\n    }\n\n    bool valid() {\n        return pointset.PointCount() >= MinPoint;\n    }\n\n    float GetX(float y) {\n        return (y - equation.Bvalue) / equation.Mvalue;\n    }\n\n    float GetY(float x) {\n        return equation.Mvalue * x + equation.Bvalue;\n    }\n\n    float GetR2() {\n        ComputeR2();\n        return equation.R2value;\n    }\n\n    private:\n\n    const XYPointCollection& pointset;\n    float SigXY = 0;\n    float SigX = 0;\n    float SigY = 0;\n    float SigX2 = 0;\n    float SigY2 = 0;\n    float SST;\n    float SSR;\n    float SXX;\n    float SYY;\n    float SXY;\n    float MeanY;\n    float MeanX;\n    float max_x = 0;\n    float min_x = std::numeric_limits<float>::max();\n    float max_y = 0;\n    float min_y = std::numeric_limits<float>::max();\n\n    void FindEquation()\n    {\n        for (int i = 0; i < pointset.PointCount(); i++) {\n            const XYData& point = pointset.Data[i];\n            SigXY += point.getX() * point.getY();\n            SigX += point.getX();\n            SigY += point.getY();\n            SigX2 += point.getX() * point.getX();\n            SigY2 += point.getY() * point.getY();\n            if (point.getX() > max_x) {\n                max_x = point.getX();\n            }\n            if (point.getX() < min_x) {\n                min_x = point.getX();\n            }\n            if (point.getY() > max_y) {\n                max_y = point.getY();\n            }\n            if (point.getY() < min_y) {\n                min_y = point.getY();\n            }\n        }\n        equation.Mvalue = ((pointset.PointCount() * SigXY) - (SigX * SigY)) / ((pointset.PointCount() * SigX2) - (SigX * SigX));\n        equation.Bvalue = (SigY - (equation.Mvalue * SigX)) / pointset.PointCount();\n        equation.NoPoints = pointset.PointCount();\n        MeanY = SigY / pointset.PointCount();\n        MeanX = SigX / pointset.PointCount();\n        //ComputeSD();\n        //ComputeCorrelationCoff();\n    }\n\n    void ComputeCorrelationCoff()\n    {\n        ComputeSXY();\n        ComputeSXX();\n        ComputeSYY();\n        equation.CorrelationCoffe = (float)(SXY / std::pow((double)SXX * SYY, 0.5));\n    }\n\n    void ComputeSXY()\n    {\n        SXY = 0;\n        for (int i = 0; i < pointset.PointCount(); i++) {\n            SXY += (pointset.Data[i].getX() - MeanX) * (pointset.Data[i].getY() - MeanY);\n        }\n    }\n\n    void ComputeSXX()\n    {\n        SXX = 0;\n        for (int i = 0; i < pointset.PointCount(); i++) {\n            SXX += (pointset.Data[i].getX() - MeanX) * (pointset.Data[i].getX() - MeanX);\n        }\n    }\n\n    void ComputeSYY()\n    {\n        SYY = 0;\n        for (int i = 0; i < pointset.PointCount(); i++) {\n            SYY += (pointset.Data[i].getY() - MeanY) * (pointset.Data[i].getY() - MeanY);\n        }\n    }\n\n    void ComputeSD()\n    {\n        equation.SDvalue = (float)std::sqrt((double)((((pointset.PointCount() * SigY2) - (SigY * SigY)) - equation.Mvalue * ((pointset.PointCount() * SigXY) - (SigX * SigY))) / pointset.PointCount()));\n    }\n\n    void ComputeR2()\n    {\n        ComputeSST();\n        ComputeSSR();\n        equation.R2value = (SST - SSR) / SST;\n    }\n\n    void ComputeSST()\n    {\n        SST = 0;\n        for (int i = 0; i < pointset.PointCount(); i++) {\n            SST += (pointset.Data[i].getY() - MeanY) * (pointset.Data[i].getY() - MeanY);\n        }\n    }\n\n    void ComputeSSR()\n    {\n        SSR = 0;\n        for (int i = 0; i < pointset.PointCount(); i++) {\n            SSR += (pointset.Data[i].getY() - (GetY(pointset.Data[i].getX()))) * (pointset.Data[i].getY() - (GetY(pointset.Data[i].getX())));\n        }\n    }\n};\n\n\nstruct PearsonCorr\n{\n    static float CalcCorrNeighborBin(const XYPointCollection& CollectionA, const XYPointCollection& CollectionB)\n    {\n        int num = (int)((std::min(CollectionA.Data.at(CollectionA.PointCount() - 1).getX(), CollectionB.Data.at(CollectionB.PointCount() - 1).getX()) - std::max(CollectionA.Data.at(0).getX(), CollectionB.Data.at(0).getX())) * 100);\n        float timeinterval = 1 / (float) 100.0;\n\n        vector<float> arrayA(num);\n        vector<float> arrayB(num);\n\n        float start = std::max(CollectionA.Data.at(0).getX(), CollectionB.Data.at(0).getX());\n\n        for (int i = 0; i < num - 1; i++) {\n            float low = start + i * timeinterval;\n            float up = start + (i + 1) * timeinterval;\n\n            for (int j = 0; j < CollectionA.PointCount(); j++) {\n                if (CollectionA.Data[j].getX() >= low && CollectionA.Data[j].getX() < up) {\n                    float intenlow = CollectionA.Data[j].getY() * (1 - (CollectionA.Data[j].getX() - low) / timeinterval);\n                    float intenup = CollectionA.Data[j].getY() * (1 - (up - CollectionA.Data[j].getX()) / timeinterval);\n                    if (intenlow > arrayA[i]) {\n                        arrayA[i] = intenlow;\n                    }\n                    if (intenup > arrayA[i + 1]) {\n                        arrayA[i + 1] = intenup;\n                    }\n                }\n                else if (CollectionA.Data[j].getX() > up) {\n                    break;\n                }\n            }\n\n            for (int j = 0; j < CollectionB.PointCount(); j++) {\n                if (CollectionB.Data[j].getX() >= low && CollectionB.Data[j].getX() < up) {\n                    float intenlow = CollectionB.Data[j].getY() * (1 - (CollectionB.Data[j].getX() - low) / timeinterval);\n                    float intenup = CollectionB.Data[j].getY() * (1 - (up - CollectionB.Data[j].getX()) / timeinterval);\n                    if (intenlow > arrayB[i]) {\n                        arrayB[i] = intenlow;\n                    }\n                    if (intenup > arrayB[i + 1]) {\n                        arrayB[i + 1] = intenup;\n                    }\n                }\n                else if (CollectionB.Data[j].getX() > up) {\n                    break;\n                }\n            }\n        }\n\n        XYPointCollection pointset;\n        for (int i = 0; i < num; i++)\n        {\n            if (arrayA[i] > 0 && arrayB[i] > 0) {\n                pointset.AddPoint(arrayA[i], arrayB[i]);\n            }\n        }\n\n        float R2 = 0;\n\n        if (pointset.PointCount() > 5) {\n            Regression regression(pointset);\n            if (regression.equation.Mvalue > 0) {\n                R2 = regression.GetR2();\n            }\n        }\n        return R2;\n    }\n\n    static float CalcCorr(const XYPointCollection& CollectionA, const XYPointCollection& CollectionB, int NoPointPerInterval)\n    {\n        int num = std::max(CollectionA.PointCount(), CollectionB.PointCount()) / 2;\n        float timeinterval = 2 / (float)NoPointPerInterval;\n        if (num < 6) {\n            return 0;\n        }\n\n        vector<float> arrayA(num);\n        vector<float> arrayB(num);\n        int size = 0;\n\n        float start = std::max(CollectionA.Data.at(0).getX(), CollectionB.Data.at(0).getX());\n\n        int i = 0;\n        float low = start;\n        float up = start + timeinterval;\n\n        for (int j = 0; j < CollectionA.PointCount(); j++) {\n            while (CollectionA.Data[j].getX() > up) {\n                i++;\n                low = up;\n                up = low + timeinterval;\n            }\n            if (i >= num) {\n                break;\n            }\n            if (CollectionA.Data[j].getX() >= low && CollectionA.Data[j].getX() < up) {\n                if (CollectionA.Data[j].getY() > arrayA[i]) {\n                    arrayA[i] = CollectionA.Data[j].getY();\n                }\n            }\n        }\n        i = 0;\n        low = start;\n        up = start + timeinterval;\n        for (int j = 0; j < CollectionB.PointCount(); j++) {\n            while (CollectionB.Data[j].getX() > up) {\n                i++;\n                low = up;\n                up = low + timeinterval;\n            }\n            if (i >= num) {\n                break;\n            }\n            if (CollectionB.Data[j].getX() >= low && CollectionB.Data[j].getX() < up) {\n                if (CollectionB.Data[j].getY() > arrayB[i]) {\n                    arrayB[i] = CollectionB.Data[j].getY();\n                    if (arrayA[i] > 0 && arrayB[i] > 0)\n                        ++size;\n                }\n            }\n        }\n\n        for (int idx = 1; idx < num - 1; idx++) {\n            if (arrayA[idx] == 0) {\n                arrayA[idx] = (arrayA[idx - 1] + arrayA[idx + 1]) / 2;\n            }\n            if (arrayB[idx] == 0) {\n                arrayB[idx] = (arrayB[idx - 1] + arrayB[idx + 1]) / 2;\n            }\n        }\n\n        XYPointCollection pointset;\n        pointset.Data.reserve(size);\n        for (int idx = 0; idx < num; idx++) {\n            if (arrayA[idx] > 0 && arrayB[idx] > 0) {\n                pointset.AddPoint(arrayA[idx], arrayB[idx]);\n            }\n        }\n\n        float R2 = 0;\n        if (pointset.PointCount() > 5) {\n            Regression regression(pointset);\n            if (regression.equation.Mvalue > 0) {\n                R2 = regression.GetR2();\n            }\n        }\n        return R2;\n    }\n};\n\n\nclass ChiSquareGOF\n{\n    using chi_squared = boost::math::chi_squared;\n\n    std::vector<chi_squared> chimodels;\n\n    public:\n\n    ChiSquareGOF(int maxpeak)\n    {\n        for (int i = 1; i < maxpeak; i++)\n            chimodels.emplace_back(chi_squared(i));\n    }\n\n    float GetGoodNessOfFitProb(const vector<float>& expected, const vector<float>& observed) const\n    {\n        float gof = 0;\n        int nopeaks = 0;\n        for (size_t i = 0; i < std::min(observed.size(), expected.size()); i++)\n        {\n            if (observed[i] > 0)\n            {\n                float error = expected[i] - observed[i];\n                gof += (error * error) / (expected[i] * expected[i]);\n                nopeaks++;\n            }\n        }\n\n        if (std::isnan(gof) || nopeaks < 2)\n            return 0;\n\n        //if (chimodels[nopeaks - 2] == null)\n        //    std::cout << std::endl;\n\n        float prob = 1 - (float) boost::math::cdf(chimodels[nopeaks - 2], gof);\n        return prob;\n    }\n};\n\n\n} // namespace DiaUmpire\n\n#endif // !_DIAUMPIRE_BSPLINE_HPP_\n", "meta": {"hexsha": "3ac09c2023a288a558486d225de5d42ec80175a8", "size": 27397, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "pwiz/analysis/dia_umpire/DiaUmpireMath.hpp", "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/dia_umpire/DiaUmpireMath.hpp", "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/dia_umpire/DiaUmpireMath.hpp", "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": 32.4994068802, "max_line_length": 231, "alphanum_fraction": 0.505055298, "num_tokens": 7259, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6442251064863697, "lm_q2_score": 0.523420348936324, "lm_q1q2_score": 0.3372005300306361}}
{"text": "//  (C) Copyright Nick Thompson 2018.\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_UNIVARIATE_STATISTICS_HPP\r\n#define BOOST_MATH_TOOLS_UNIVARIATE_STATISTICS_HPP\r\n\r\n#include <algorithm>\r\n#include <iterator>\r\n#include <tuple>\r\n#include <boost/assert.hpp>\r\n#include <boost/config/header_deprecated.hpp>\r\n\r\nBOOST_HEADER_DEPRECATED(\"<boost/math/statistics/univariate_statistics.hpp>\");\r\n\r\nnamespace boost::math::tools {\r\n\r\ntemplate<class ForwardIterator>\r\nauto mean(ForwardIterator first, ForwardIterator last)\r\n{\r\n    using Real = typename std::iterator_traits<ForwardIterator>::value_type;\r\n    BOOST_ASSERT_MSG(first != last, \"At least one sample is required to compute the mean.\");\r\n    if constexpr (std::is_integral<Real>::value)\r\n    {\r\n        double mu = 0;\r\n        double i = 1;\r\n        for(auto it = first; it != last; ++it) {\r\n            mu = mu + (*it - mu)/i;\r\n            i += 1;\r\n        }\r\n        return mu;\r\n    }\r\n    else if constexpr (std::is_same_v<typename std::iterator_traits<ForwardIterator>::iterator_category, std::random_access_iterator_tag>)\r\n    {\r\n        size_t elements = std::distance(first, last);\r\n        Real mu0 = 0;\r\n        Real mu1 = 0;\r\n        Real mu2 = 0;\r\n        Real mu3 = 0;\r\n        Real i = 1;\r\n        auto end = last - (elements % 4);\r\n        for(auto it = first; it != end;  it += 4) {\r\n            Real inv = Real(1)/i;\r\n            Real tmp0 = (*it - mu0);\r\n            Real tmp1 = (*(it+1) - mu1);\r\n            Real tmp2 = (*(it+2) - mu2);\r\n            Real tmp3 = (*(it+3) - mu3);\r\n            // please generate a vectorized fma here\r\n            mu0 += tmp0*inv;\r\n            mu1 += tmp1*inv;\r\n            mu2 += tmp2*inv;\r\n            mu3 += tmp3*inv;\r\n            i += 1;\r\n        }\r\n        Real num1 = Real(elements  - (elements %4))/Real(4);\r\n        Real num2 = num1 + Real(elements % 4);\r\n\r\n        for (auto it = end; it != last; ++it)\r\n        {\r\n            mu3 += (*it-mu3)/i;\r\n            i += 1;\r\n        }\r\n\r\n        return (num1*(mu0+mu1+mu2) + num2*mu3)/Real(elements);\r\n    }\r\n    else\r\n    {\r\n        auto it = first;\r\n        Real mu = *it;\r\n        Real i = 2;\r\n        while(++it != last)\r\n        {\r\n            mu += (*it - mu)/i;\r\n            i += 1;\r\n        }\r\n        return mu;\r\n    }\r\n}\r\n\r\ntemplate<class Container>\r\ninline auto mean(Container const & v)\r\n{\r\n    return mean(v.cbegin(), v.cend());\r\n}\r\n\r\ntemplate<class ForwardIterator>\r\nauto variance(ForwardIterator first, ForwardIterator last)\r\n{\r\n    using Real = typename std::iterator_traits<ForwardIterator>::value_type;\r\n    BOOST_ASSERT_MSG(first != last, \"At least one sample is required to compute mean and variance.\");\r\n    // Higham, Accuracy and Stability, equation 1.6a and 1.6b:\r\n    if constexpr (std::is_integral<Real>::value)\r\n    {\r\n        double M = *first;\r\n        double Q = 0;\r\n        double k = 2;\r\n        for (auto it = std::next(first); it != last; ++it)\r\n        {\r\n            double tmp = *it - M;\r\n            Q = Q + ((k-1)*tmp*tmp)/k;\r\n            M = M + tmp/k;\r\n            k += 1;\r\n        }\r\n        return Q/(k-1);\r\n    }\r\n    else\r\n    {\r\n        Real M = *first;\r\n        Real Q = 0;\r\n        Real k = 2;\r\n        for (auto it = std::next(first); it != last; ++it)\r\n        {\r\n            Real tmp = (*it - M)/k;\r\n            Q += k*(k-1)*tmp*tmp;\r\n            M += tmp;\r\n            k += 1;\r\n        }\r\n        return Q/(k-1);\r\n    }\r\n}\r\n\r\ntemplate<class Container>\r\ninline auto variance(Container const & v)\r\n{\r\n    return variance(v.cbegin(), v.cend());\r\n}\r\n\r\ntemplate<class ForwardIterator>\r\nauto sample_variance(ForwardIterator first, ForwardIterator last)\r\n{\r\n    size_t n = std::distance(first, last);\r\n    BOOST_ASSERT_MSG(n > 1, \"At least two samples are required to compute the sample variance.\");\r\n    return n*variance(first, last)/(n-1);\r\n}\r\n\r\ntemplate<class Container>\r\ninline auto sample_variance(Container const & v)\r\n{\r\n    return sample_variance(v.cbegin(), v.cend());\r\n}\r\n\r\n\r\n// Follows equation 1.5 of:\r\n// https://prod.sandia.gov/techlib-noauth/access-control.cgi/2008/086212.pdf\r\ntemplate<class ForwardIterator>\r\nauto skewness(ForwardIterator first, ForwardIterator last)\r\n{\r\n    using Real = typename std::iterator_traits<ForwardIterator>::value_type;\r\n    BOOST_ASSERT_MSG(first != last, \"At least one sample is required to compute skewness.\");\r\n    if constexpr (std::is_integral<Real>::value)\r\n    {\r\n        double M1 = *first;\r\n        double M2 = 0;\r\n        double M3 = 0;\r\n        double n = 2;\r\n        for (auto it = std::next(first); it != last; ++it)\r\n        {\r\n            double delta21 = *it - M1;\r\n            double tmp = delta21/n;\r\n            M3 = M3 + tmp*((n-1)*(n-2)*delta21*tmp - 3*M2);\r\n            M2 = M2 + tmp*(n-1)*delta21;\r\n            M1 = M1 + tmp;\r\n            n += 1;\r\n        }\r\n\r\n        double var = M2/(n-1);\r\n        if (var == 0)\r\n        {\r\n            // The limit is technically undefined, but the interpretation here is clear:\r\n            // A constant dataset has no skewness.\r\n            return double(0);\r\n        }\r\n        double skew = M3/(M2*sqrt(var));\r\n        return skew;\r\n    }\r\n    else\r\n    {\r\n        Real M1 = *first;\r\n        Real M2 = 0;\r\n        Real M3 = 0;\r\n        Real n = 2;\r\n        for (auto it = std::next(first); it != last; ++it)\r\n        {\r\n            Real delta21 = *it - M1;\r\n            Real tmp = delta21/n;\r\n            M3 += tmp*((n-1)*(n-2)*delta21*tmp - 3*M2);\r\n            M2 += tmp*(n-1)*delta21;\r\n            M1 += tmp;\r\n            n += 1;\r\n        }\r\n\r\n        Real var = M2/(n-1);\r\n        if (var == 0)\r\n        {\r\n            // The limit is technically undefined, but the interpretation here is clear:\r\n            // A constant dataset has no skewness.\r\n            return Real(0);\r\n        }\r\n        Real skew = M3/(M2*sqrt(var));\r\n        return skew;\r\n    }\r\n}\r\n\r\ntemplate<class Container>\r\ninline auto skewness(Container const & v)\r\n{\r\n    return skewness(v.cbegin(), v.cend());\r\n}\r\n\r\n// Follows equation 1.5/1.6 of:\r\n// https://prod.sandia.gov/techlib-noauth/access-control.cgi/2008/086212.pdf\r\ntemplate<class ForwardIterator>\r\nauto first_four_moments(ForwardIterator first, ForwardIterator last)\r\n{\r\n    using Real = typename std::iterator_traits<ForwardIterator>::value_type;\r\n    BOOST_ASSERT_MSG(first != last, \"At least one sample is required to compute the first four moments.\");\r\n    if constexpr (std::is_integral<Real>::value)\r\n    {\r\n        double M1 = *first;\r\n        double M2 = 0;\r\n        double M3 = 0;\r\n        double M4 = 0;\r\n        double n = 2;\r\n        for (auto it = std::next(first); it != last; ++it)\r\n        {\r\n            double delta21 = *it - M1;\r\n            double tmp = delta21/n;\r\n            M4 = M4 + tmp*(tmp*tmp*delta21*((n-1)*(n*n-3*n+3)) + 6*tmp*M2 - 4*M3);\r\n            M3 = M3 + tmp*((n-1)*(n-2)*delta21*tmp - 3*M2);\r\n            M2 = M2 + tmp*(n-1)*delta21;\r\n            M1 = M1 + tmp;\r\n            n += 1;\r\n        }\r\n\r\n        return std::make_tuple(M1, M2/(n-1), M3/(n-1), M4/(n-1));\r\n    }\r\n    else\r\n    {\r\n        Real M1 = *first;\r\n        Real M2 = 0;\r\n        Real M3 = 0;\r\n        Real M4 = 0;\r\n        Real n = 2;\r\n        for (auto it = std::next(first); it != last; ++it)\r\n        {\r\n            Real delta21 = *it - M1;\r\n            Real tmp = delta21/n;\r\n            M4 = M4 + tmp*(tmp*tmp*delta21*((n-1)*(n*n-3*n+3)) + 6*tmp*M2 - 4*M3);\r\n            M3 = M3 + tmp*((n-1)*(n-2)*delta21*tmp - 3*M2);\r\n            M2 = M2 + tmp*(n-1)*delta21;\r\n            M1 = M1 + tmp;\r\n            n += 1;\r\n        }\r\n\r\n        return std::make_tuple(M1, M2/(n-1), M3/(n-1), M4/(n-1));\r\n    }\r\n}\r\n\r\ntemplate<class Container>\r\ninline auto first_four_moments(Container const & v)\r\n{\r\n    return first_four_moments(v.cbegin(), v.cend());\r\n}\r\n\r\n\r\n// Follows equation 1.6 of:\r\n// https://prod.sandia.gov/techlib-noauth/access-control.cgi/2008/086212.pdf\r\ntemplate<class ForwardIterator>\r\nauto kurtosis(ForwardIterator first, ForwardIterator last)\r\n{\r\n    auto [M1, M2, M3, M4] = first_four_moments(first, last);\r\n    if (M2 == 0)\r\n    {\r\n        return M2;\r\n    }\r\n    return M4/(M2*M2);\r\n}\r\n\r\ntemplate<class Container>\r\ninline auto kurtosis(Container const & v)\r\n{\r\n    return kurtosis(v.cbegin(), v.cend());\r\n}\r\n\r\ntemplate<class ForwardIterator>\r\nauto excess_kurtosis(ForwardIterator first, ForwardIterator last)\r\n{\r\n    return kurtosis(first, last) - 3;\r\n}\r\n\r\ntemplate<class Container>\r\ninline auto excess_kurtosis(Container const & v)\r\n{\r\n    return excess_kurtosis(v.cbegin(), v.cend());\r\n}\r\n\r\n\r\ntemplate<class RandomAccessIterator>\r\nauto median(RandomAccessIterator first, RandomAccessIterator last)\r\n{\r\n    size_t num_elems = std::distance(first, last);\r\n    BOOST_ASSERT_MSG(num_elems > 0, \"The median of a zero length vector is undefined.\");\r\n    if (num_elems & 1)\r\n    {\r\n        auto middle = first + (num_elems - 1)/2;\r\n        std::nth_element(first, middle, last);\r\n        return *middle;\r\n    }\r\n    else\r\n    {\r\n        auto middle = first + num_elems/2 - 1;\r\n        std::nth_element(first, middle, last);\r\n        std::nth_element(middle, middle+1, last);\r\n        return (*middle + *(middle+1))/2;\r\n    }\r\n}\r\n\r\n\r\ntemplate<class RandomAccessContainer>\r\ninline auto median(RandomAccessContainer & v)\r\n{\r\n    return median(v.begin(), v.end());\r\n}\r\n\r\ntemplate<class RandomAccessIterator>\r\nauto gini_coefficient(RandomAccessIterator first, RandomAccessIterator last)\r\n{\r\n    using Real = typename std::iterator_traits<RandomAccessIterator>::value_type;\r\n    BOOST_ASSERT_MSG(first != last && std::next(first) != last, \"Computation of the Gini coefficient requires at least two samples.\");\r\n\r\n    std::sort(first, last);\r\n    if constexpr (std::is_integral<Real>::value)\r\n    {\r\n        double i = 1;\r\n        double num = 0;\r\n        double denom = 0;\r\n        for (auto it = first; it != last; ++it)\r\n        {\r\n            num += *it*i;\r\n            denom += *it;\r\n            ++i;\r\n        }\r\n\r\n        // If the l1 norm is zero, all elements are zero, so every element is the same.\r\n        if (denom == 0)\r\n        {\r\n            return double(0);\r\n        }\r\n\r\n        return ((2*num)/denom - i)/(i-1);\r\n    }\r\n    else\r\n    {\r\n        Real i = 1;\r\n        Real num = 0;\r\n        Real denom = 0;\r\n        for (auto it = first; it != last; ++it)\r\n        {\r\n            num += *it*i;\r\n            denom += *it;\r\n            ++i;\r\n        }\r\n\r\n        // If the l1 norm is zero, all elements are zero, so every element is the same.\r\n        if (denom == 0)\r\n        {\r\n            return Real(0);\r\n        }\r\n\r\n        return ((2*num)/denom - i)/(i-1);\r\n    }\r\n}\r\n\r\ntemplate<class RandomAccessContainer>\r\ninline auto gini_coefficient(RandomAccessContainer & v)\r\n{\r\n    return gini_coefficient(v.begin(), v.end());\r\n}\r\n\r\ntemplate<class RandomAccessIterator>\r\ninline auto sample_gini_coefficient(RandomAccessIterator first, RandomAccessIterator last)\r\n{\r\n    size_t n = std::distance(first, last);\r\n    return n*gini_coefficient(first, last)/(n-1);\r\n}\r\n\r\ntemplate<class RandomAccessContainer>\r\ninline auto sample_gini_coefficient(RandomAccessContainer & v)\r\n{\r\n    return sample_gini_coefficient(v.begin(), v.end());\r\n}\r\n\r\ntemplate<class RandomAccessIterator>\r\nauto median_absolute_deviation(RandomAccessIterator first, RandomAccessIterator last, typename std::iterator_traits<RandomAccessIterator>::value_type center=std::numeric_limits<typename std::iterator_traits<RandomAccessIterator>::value_type>::quiet_NaN())\r\n{\r\n    using std::abs;\r\n    using Real = typename std::iterator_traits<RandomAccessIterator>::value_type;\r\n    using std::isnan;\r\n    if (isnan(center))\r\n    {\r\n        center = boost::math::tools::median(first, last);\r\n    }\r\n    size_t num_elems = std::distance(first, last);\r\n    BOOST_ASSERT_MSG(num_elems > 0, \"The median of a zero-length vector is undefined.\");\r\n    auto comparator = [&center](Real a, Real b) { return abs(a-center) < abs(b-center);};\r\n    if (num_elems & 1)\r\n    {\r\n        auto middle = first + (num_elems - 1)/2;\r\n        std::nth_element(first, middle, last, comparator);\r\n        return abs(*middle);\r\n    }\r\n    else\r\n    {\r\n        auto middle = first + num_elems/2 - 1;\r\n        std::nth_element(first, middle, last, comparator);\r\n        std::nth_element(middle, middle+1, last, comparator);\r\n        return (abs(*middle) + abs(*(middle+1)))/abs(static_cast<Real>(2));\r\n    }\r\n}\r\n\r\ntemplate<class RandomAccessContainer>\r\ninline auto median_absolute_deviation(RandomAccessContainer & v, typename RandomAccessContainer::value_type center=std::numeric_limits<typename RandomAccessContainer::value_type>::quiet_NaN())\r\n{\r\n    return median_absolute_deviation(v.begin(), v.end(), center);\r\n}\r\n\r\n}\r\n#endif\r\n", "meta": {"hexsha": "9ca95ce0b0fd8f3a7596382e8da4b53e718ae4d9", "size": 12894, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "deps/boost/include/boost/math/tools/univariate_statistics.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/tools/univariate_statistics.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/tools/univariate_statistics.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": 29.9860465116, "max_line_length": 256, "alphanum_fraction": 0.55917481, "num_tokens": 3350, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5583269943353744, "lm_q2_score": 0.6039318337259584, "lm_q1q2_score": 0.3371914455076654}}
{"text": "#ifndef PARMCB_SVA_SIGNED_HPP_\n#define PARMCB_SVA_SIGNED_HPP_\n\n//    Copyright (C) Dimitrios Michail 2019 - 2021.\n// Distributed under the Boost Software License, Version 1.0.\n//    (See accompanying file LICENSE_1_0.txt or copy at\n//          https://www.boost.org/LICENSE_1_0.txt)\n\n#include <boost/graph/graph_traits.hpp>\n#include <boost/property_map/property_map.hpp>\n#include <boost/tuple/detail/tuple_basic.hpp>\n#include <boost/timer/timer.hpp>\n\n#include <cstddef>\n#include <functional>\n#include <iostream>\n#include <iterator>\n#include <limits>\n#include <set>\n#include <vector>\n\n#include <parmcb/detail/signed_dijkstra.hpp>\n\n#include <parmcb/forestindex.hpp>\n#include <parmcb/spvecgf2.hpp>\n#include <parmcb/util.hpp>\n\nnamespace parmcb {\n\n    template<class Graph, class WeightMap, class CycleOutputIterator>\n    typename boost::property_traits<WeightMap>::value_type mcb_sva_signed(const Graph &g, WeightMap weight_map,\n            CycleOutputIterator out) {\n\n        typedef typename boost::graph_traits<Graph>::edge_descriptor Edge;\n        typedef typename boost::graph_traits<Graph>::vertex_iterator VertexIt;\n        typedef typename boost::property_traits<WeightMap>::value_type WeightType;\n\n        /*\n         * Index the graph\n         */\n        ForestIndex<Graph> forest_index(g);\n        auto csd = forest_index.cycle_space_dimension();\n\n        /*\n         * Initialize support vectors\n         */\n        std::vector<SpVecGF2<std::size_t>> support;\n        for (std::size_t k = 0; k < csd; k++) {\n            support.emplace_back(k);\n        }\n\n        boost::timer::cpu_timer cycle_timer;\n        cycle_timer.stop();\n        boost::timer::cpu_timer support_timer;\n        support_timer.stop();\n\n        /*\n         * Main loop\n         */\n        WeightType mcb_weight = WeightType();\n        for (std::size_t k = 0; k < csd; k++) {\n            /*\n             * Choose the sparsest support heuristic\n             */\n            auto min_support = k;\n            for (auto r = k + 1; r < csd; ++r) {\n                if (support[r].size() < support[min_support].size())\n                    min_support = r;\n                if (support[min_support].size() < 5) {\n                    break;\n                }\n            }\n            if (min_support != k) {  // swap\n                std::swap(support[k], support[min_support]);\n            }\n\n            /*\n             * Compute shortest odd cycle\n             */\n            cycle_timer.resume();\n            std::less<WeightType> compare = std::less<WeightType>();\n            std::tuple<std::set<Edge>, WeightType, bool> best = std::make_tuple(std::set<Edge>(),\n                    (std::numeric_limits<WeightType>::max)(), false);\n            std::set<Edge> signed_edges;\n            convert_edges(support[k], std::inserter(signed_edges, signed_edges.end()), forest_index);\n\n            if (signed_edges.size() >= boost::num_vertices(g)) {\n                VertexIt vi, viend;\n                for (boost::tie(vi, viend) = boost::vertices(g); vi != viend; ++vi) {\n                    auto v = *vi;\n                    const bool use_hidden_edges = false;\n                    auto res = bidirectional_signed_dijkstra(g, weight_map, signed_edges, std::set<Edge> { },\n                            use_hidden_edges, v, true, v, false, std::get<2>(best), std::get<1>(best));\n                    if (std::get<2>(res) && (!std::get<2>(best) || compare(std::get<1>(res), std::get<1>(best)))) {\n                        best = res;\n                        assert(std::get<2>(best));\n                    }\n                }\n            } else {\n                /*\n                 * Heuristic in case number of signed edges is small compared to the number of vertices.\n                 */\n                std::set<Edge> hidden_edges;\n                std::copy(signed_edges.begin(), signed_edges.end(), std::inserter(hidden_edges, hidden_edges.begin()));\n                for (auto sei = signed_edges.begin(); sei != signed_edges.end(); ++sei) {\n                    auto se = *sei;\n                    auto se_v = boost::source(se, g);\n                    auto se_u = boost::target(se, g);\n                    auto res = bidirectional_signed_dijkstra(g, weight_map, signed_edges, hidden_edges, true, se_v,\n                            true, se_u, true, std::get<2>(best), std::get<1>(best));\n                    hidden_edges.erase(hidden_edges.begin());\n                    if (std::get<2>(res) && std::get<0>(res).find(se) == std::get<0>(res).end()) {\n                        std::get<1>(res) += boost::get(weight_map, se);\n                        if (!std::get<2>(best) || compare(std::get<1>(res), std::get<1>(best))) {\n                            std::get<0>(res).insert(se);\n                            best = res;\n                            assert(std::get<2>(best));\n                        }\n                    }\n                }\n            }\n            assert(std::get<2>(best));\n            cycle_timer.stop();\n\n            /*\n             * Update support vectors\n             */\n            support_timer.resume();\n            std::set<std::size_t> cyclek;\n            convert_edges(std::get<0>(best), std::inserter(cyclek, cyclek.end()), forest_index);\n            for (std::size_t l = k + 1; l < csd; l++) {\n                if (support[l] * cyclek == 1) {\n                    support[l] += support[k];\n                }\n            }\n            support_timer.stop();\n\n            /*\n             * Output new cycle\n             */\n            std::list<Edge> cyclek_edgelist;\n            std::copy(std::get<0>(best).begin(), std::get<0>(best).end(), std::back_inserter(cyclek_edgelist));\n            *out++ = cyclek_edgelist;\n            mcb_weight += std::get<1>(best);\n        }\n\n        std::cout << \"cycle   timer\" << cycle_timer.format();\n        std::cout << \"support timer\" << support_timer.format();\n\n        return mcb_weight;\n    }\n\n} // parmcb\n\n#endif\n", "meta": {"hexsha": "a1f5d285dfc45555b93c5793deef7fb732bdfa46", "size": 5940, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/parmcb/parmcb_sva_signed.hpp", "max_stars_repo_name": "d-michail/parmcb", "max_stars_repo_head_hexsha": "19d0b7eb01735600c851b969d9e5a87c78b8c711", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/parmcb/parmcb_sva_signed.hpp", "max_issues_repo_name": "d-michail/parmcb", "max_issues_repo_head_hexsha": "19d0b7eb01735600c851b969d9e5a87c78b8c711", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/parmcb/parmcb_sva_signed.hpp", "max_forks_repo_name": "d-michail/parmcb", "max_forks_repo_head_hexsha": "19d0b7eb01735600c851b969d9e5a87c78b8c711", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.0769230769, "max_line_length": 119, "alphanum_fraction": 0.5168350168, "num_tokens": 1364, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6959583376458152, "lm_q2_score": 0.48438008427698437, "lm_q1q2_score": 0.3371083582421499}}
{"text": "#ifndef STAN_MATH_REV_MAT_FUN_COV_EXP_QUAD_HPP\n#define STAN_MATH_REV_MAT_FUN_COV_EXP_QUAD_HPP\n\n#include <stan/math/rev/core.hpp>\n#include <stan/math/rev/scal/fun/value_of.hpp>\n#include <stan/math/prim/mat/fun/Eigen.hpp>\n#include <stan/math/prim/scal/err/check_not_nan.hpp>\n#include <stan/math/prim/scal/err/check_positive.hpp>\n#include <stan/math/prim/scal/fun/square.hpp>\n#include <stan/math/prim/scal/fun/squared_distance.hpp>\n#include <stan/math/prim/scal/fun/exp.hpp>\n#include <stan/math/prim/scal/meta/scalar_type.hpp>\n#include <boost/math/tools/promotion.hpp>\n#include <boost/utility/enable_if.hpp>\n#include <boost/type_traits.hpp>\n#include <vector>\n#include <cmath>\n\nnamespace stan {\nnamespace math {\n\n/**\n * This is a subclass of the vari class for precomputed\n * gradients of cov_exp_quad.\n *\n * The class stores the double values for the distance\n * matrix, pointers to the varis for the covariance\n * matrix, along with a pointer to the vari for sigma,\n * and the vari for l.\n *\n * @tparam T_x type of std::vector of elements\n * @tparam T_sigma type of sigma\n * @tparam T_l type of length scale\n */\ntemplate <typename T_x, typename T_sigma, typename T_l>\nclass cov_exp_quad_vari : public vari {\n public:\n  const size_t size_;\n  const size_t size_ltri_;\n  const double l_d_;\n  const double sigma_d_;\n  const double sigma_sq_d_;\n  double* dist_;\n  vari* l_vari_;\n  vari* sigma_vari_;\n  vari** cov_lower_;\n  vari** cov_diag_;\n\n  /**\n   * Constructor for cov_exp_quad.\n   *\n   * All memory allocated in\n   * ChainableStack's stack_alloc arena.\n   *\n   * It is critical for the efficiency of this object\n   * that the constructor create new varis that aren't\n   * popped onto the var_stack_, but rather are\n   * popped onto the var_nochain_stack_. This is\n   * controlled to the second argument to\n   * vari's constructor.\n   *\n   * @param x std::vector input that can be used in square distance\n   *    Assumes each element of x is the same size\n   * @param sigma standard deviation\n   * @param l length scale\n   */\n  cov_exp_quad_vari(const std::vector<T_x>& x, const T_sigma& sigma,\n                    const T_l& l)\n      : vari(0.0),\n        size_(x.size()),\n        size_ltri_(size_ * (size_ - 1) / 2),\n        l_d_(value_of(l)),\n        sigma_d_(value_of(sigma)),\n        sigma_sq_d_(sigma_d_ * sigma_d_),\n        dist_(ChainableStack::instance().memalloc_.alloc_array<double>(\n            size_ltri_)),\n        l_vari_(l.vi_),\n        sigma_vari_(sigma.vi_),\n        cov_lower_(ChainableStack::instance().memalloc_.alloc_array<vari*>(\n            size_ltri_)),\n        cov_diag_(\n            ChainableStack::instance().memalloc_.alloc_array<vari*>(size_)) {\n    double inv_half_sq_l_d = 0.5 / (l_d_ * l_d_);\n    size_t pos = 0;\n    for (size_t j = 0; j < size_ - 1; ++j) {\n      for (size_t i = j + 1; i < size_; ++i) {\n        double dist_sq = squared_distance(x[i], x[j]);\n        dist_[pos] = dist_sq;\n        cov_lower_[pos] = new vari(\n            sigma_sq_d_ * std::exp(-dist_sq * inv_half_sq_l_d), false);\n        ++pos;\n      }\n    }\n    for (size_t i = 0; i < size_; ++i)\n      cov_diag_[i] = new vari(sigma_sq_d_, false);\n  }\n\n  virtual void chain() {\n    double adjl = 0;\n    double adjsigma = 0;\n\n    for (size_t i = 0; i < size_ltri_; ++i) {\n      vari* el_low = cov_lower_[i];\n      double prod_add = el_low->adj_ * el_low->val_;\n      adjl += prod_add * dist_[i];\n      adjsigma += prod_add;\n    }\n    for (size_t i = 0; i < size_; ++i) {\n      vari* el = cov_diag_[i];\n      adjsigma += el->adj_ * el->val_;\n    }\n    l_vari_->adj_ += adjl / (l_d_ * l_d_ * l_d_);\n    sigma_vari_->adj_ += adjsigma * 2 / sigma_d_;\n  }\n};\n\n/**\n * This is a subclass of the vari class for precomputed\n * gradients of cov_exp_quad.\n *\n * The class stores the double values for the distance\n * matrix, pointers to the varis for the covariance\n * matrix, along with a pointer to the vari for sigma,\n * and the vari for l.\n *\n * @tparam T_x type of std::vector of elements\n * @tparam T_l type of length scale\n */\ntemplate <typename T_x, typename T_l>\nclass cov_exp_quad_vari<T_x, double, T_l> : public vari {\n public:\n  const size_t size_;\n  const size_t size_ltri_;\n  const double l_d_;\n  const double sigma_d_;\n  const double sigma_sq_d_;\n  double* dist_;\n  vari* l_vari_;\n  vari** cov_lower_;\n  vari** cov_diag_;\n\n  /**\n   * Constructor for cov_exp_quad.\n   *\n   * All memory allocated in\n   * ChainableStack's stack_alloc arena.\n   *\n   * It is critical for the efficiency of this object\n   * that the constructor create new varis that aren't\n   * popped onto the var_stack_, but rather are\n   * popped onto the var_nochain_stack_. This is\n   * controlled to the second argument to\n   * vari's constructor.\n   *\n   * @param x std::vector input that can be used in square distance\n   *    Assumes each element of x is the same size\n   * @param sigma standard deviation\n   * @param l length scale\n   */\n  cov_exp_quad_vari(const std::vector<T_x>& x, double sigma, const T_l& l)\n      : vari(0.0),\n        size_(x.size()),\n        size_ltri_(size_ * (size_ - 1) / 2),\n        l_d_(value_of(l)),\n        sigma_d_(value_of(sigma)),\n        sigma_sq_d_(sigma_d_ * sigma_d_),\n        dist_(ChainableStack::instance().memalloc_.alloc_array<double>(\n            size_ltri_)),\n        l_vari_(l.vi_),\n        cov_lower_(ChainableStack::instance().memalloc_.alloc_array<vari*>(\n            size_ltri_)),\n        cov_diag_(\n            ChainableStack::instance().memalloc_.alloc_array<vari*>(size_)) {\n    double inv_half_sq_l_d = 0.5 / (l_d_ * l_d_);\n    size_t pos = 0;\n    for (size_t j = 0; j < size_ - 1; ++j) {\n      for (size_t i = j + 1; i < size_; ++i) {\n        double dist_sq = squared_distance(x[i], x[j]);\n        dist_[pos] = dist_sq;\n        cov_lower_[pos] = new vari(\n            sigma_sq_d_ * std::exp(-dist_sq * inv_half_sq_l_d), false);\n        ++pos;\n      }\n    }\n    for (size_t i = 0; i < size_; ++i)\n      cov_diag_[i] = new vari(sigma_sq_d_, false);\n  }\n\n  virtual void chain() {\n    double adjl = 0;\n\n    for (size_t i = 0; i < size_ltri_; ++i) {\n      vari* el_low = cov_lower_[i];\n      adjl += el_low->adj_ * el_low->val_ * dist_[i];\n    }\n    l_vari_->adj_ += adjl / (l_d_ * l_d_ * l_d_);\n  }\n};\n\n/**\n * Returns a squared exponential kernel.\n *\n * @param x std::vector input that can be used in square distance\n *    Assumes each element of x is the same size\n * @param sigma standard deviation\n * @param l length scale\n * @return squared distance\n * @throw std::domain_error if sigma <= 0, l <= 0, or\n *   x is nan or infinite\n */\ntemplate <typename T_x>\ninline typename boost::enable_if_c<\n    boost::is_same<typename scalar_type<T_x>::type, double>::value,\n    Eigen::Matrix<var, -1, -1> >::type\ncov_exp_quad(const std::vector<T_x>& x, const var& sigma, const var& l) {\n  check_positive(\"cov_exp_quad\", \"sigma\", sigma);\n  check_positive(\"cov_exp_quad\", \"l\", l);\n  size_t x_size = x.size();\n  for (size_t i = 0; i < x_size; ++i)\n    check_not_nan(\"cov_exp_quad\", \"x\", x[i]);\n\n  Eigen::Matrix<var, -1, -1> cov(x_size, x_size);\n  if (x_size == 0)\n    return cov;\n\n  cov_exp_quad_vari<T_x, var, var>* baseVari\n      = new cov_exp_quad_vari<T_x, var, var>(x, sigma, l);\n\n  size_t pos = 0;\n  for (size_t j = 0; j < x_size - 1; ++j) {\n    for (size_t i = (j + 1); i < x_size; ++i) {\n      cov.coeffRef(i, j).vi_ = baseVari->cov_lower_[pos];\n      cov.coeffRef(j, i).vi_ = cov.coeffRef(i, j).vi_;\n      ++pos;\n    }\n    cov.coeffRef(j, j).vi_ = baseVari->cov_diag_[j];\n  }\n  cov.coeffRef(x_size - 1, x_size - 1).vi_ = baseVari->cov_diag_[x_size - 1];\n  return cov;\n}\n\n/**\n * Returns a squared exponential kernel.\n *\n * @param x std::vector input that can be used in square distance\n *    Assumes each element of x is the same size\n * @param sigma standard deviation\n * @param l length scale\n * @return squared distance\n * @throw std::domain_error if sigma <= 0, l <= 0, or\n *   x is nan or infinite\n */\ntemplate <typename T_x>\ninline typename boost::enable_if_c<\n    boost::is_same<typename scalar_type<T_x>::type, double>::value,\n    Eigen::Matrix<var, -1, -1> >::type\ncov_exp_quad(const std::vector<T_x>& x, double sigma, const var& l) {\n  check_positive(\"cov_exp_quad\", \"marginal variance\", sigma);\n  check_positive(\"cov_exp_quad\", \"length-scale\", l);\n  size_t x_size = x.size();\n  for (size_t i = 0; i < x_size; ++i)\n    check_not_nan(\"cov_exp_quad\", \"x\", x[i]);\n\n  Eigen::Matrix<var, -1, -1> cov(x_size, x_size);\n  if (x_size == 0)\n    return cov;\n\n  cov_exp_quad_vari<T_x, double, var>* baseVari\n      = new cov_exp_quad_vari<T_x, double, var>(x, sigma, l);\n\n  size_t pos = 0;\n  for (size_t j = 0; j < x_size - 1; ++j) {\n    for (size_t i = (j + 1); i < x_size; ++i) {\n      cov.coeffRef(i, j).vi_ = baseVari->cov_lower_[pos];\n      cov.coeffRef(j, i).vi_ = cov.coeffRef(i, j).vi_;\n      ++pos;\n    }\n    cov.coeffRef(j, j).vi_ = baseVari->cov_diag_[j];\n  }\n  cov.coeffRef(x_size - 1, x_size - 1).vi_ = baseVari->cov_diag_[x_size - 1];\n  return cov;\n}\n\n}  // namespace math\n}  // namespace stan\n#endif\n", "meta": {"hexsha": "4b0e16e53a8de7c8b5ae219c95450900d781846d", "size": 9033, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "stan/math/rev/mat/fun/cov_exp_quad.hpp", "max_stars_repo_name": "sakrejda/math", "max_stars_repo_head_hexsha": "3cc99955807cf1f4ea51efd79aa3958b74d24af2", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "stan/math/rev/mat/fun/cov_exp_quad.hpp", "max_issues_repo_name": "sakrejda/math", "max_issues_repo_head_hexsha": "3cc99955807cf1f4ea51efd79aa3958b74d24af2", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "stan/math/rev/mat/fun/cov_exp_quad.hpp", "max_forks_repo_name": "sakrejda/math", "max_forks_repo_head_hexsha": "3cc99955807cf1f4ea51efd79aa3958b74d24af2", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.4738675958, "max_line_length": 77, "alphanum_fraction": 0.639765305, "num_tokens": 2712, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6959583376458152, "lm_q2_score": 0.4843800842769843, "lm_q1q2_score": 0.33710835824214985}}
{"text": "#include \"wrapper.hpp\"\n#include \"piano.hpp\"\n#include \"python_common.hpp\"\n#include <Eigen/Dense>\n#include <numpy/ndarrayobject.h>\n#include <portaudio.h>\n\nstatic PyModuleDef Module = {\n    PyModuleDef_HEAD_INIT,\n    \"spectrum_analyzer\",\n    \"\",\n    -1,\n    nullptr,\n    nullptr,\n    nullptr,\n    nullptr,\n    nullptr\n};\n\nint PaInit(PyObject*, PyObject*, PyObject*) {\n    // We don't acquire GIL here becuase portaudio won't access Python objects.\n    Pa_Initialize();\n    return 0;\n}\n\nvoid PaEnd(PyObject*) {\n    Pa_Terminate();\n}\n\nPyTypeObject PaInitializerType {\n    PyVarObject_HEAD_INIT(NULL, 0)\n    \"_PaInitializer\",          /* tp_name */\n    sizeof(PyObject),          /* tp_basicsize */\n    0,                         /* tp_itemsize */\n    PaEnd,                     /* tp_dealloc */\n    0,                         /* tp_print */\n    0,                         /* tp_getattr */\n    0,                         /* tp_setattr */\n    0,                         /* tp_reserved */\n    0,                         /* tp_repr */\n    0,                         /* tp_as_number */\n    0,                         /* tp_as_sequence */\n    0,                         /* tp_as_mapping */\n    0,                         /* tp_hash  */\n    0,                         /* tp_call */\n    0,                         /* tp_str */\n    0,                         /* tp_getattro */\n    0,                         /* tp_setattro */\n    0,                         /* tp_as_buffer */\n    Py_TPFLAGS_DEFAULT,        /* tp_flags */\n    0,                         /* tp_doc */\n    0,                         /* tp_traverse */\n    0,                         /* tp_clear */\n    0,                         /* tp_richcompare */\n    0,                         /* tp_weaklistoffset */\n    0,                         /* tp_iter */\n    0,                         /* tp_iternext */\n    0,                         /* tp_methods */\n    0,                         /* tp_members */\n    0,                         /* tp_getset */\n    0,                         /* tp_base */\n    0,                         /* tp_dict */\n    0,                         /* tp_descr_get */\n    0,                         /* tp_descr_set */\n    0,                         /* tp_dictoffset */\n    PaInit,                    /* tp_init */\n    0,                         /* tp_alloc */\n    PyType_GenericNew          /* tp_new */\n};\n\nPyObject* get_pitch(PyObject*, PyObject* args) {\n    PyObject* py_wav;\n    unsigned interval;\n    if (!PyArg_ParseTuple(args, \"OI\", &py_wav, &interval))\n        return nullptr;\n    wav_file& wav = *static_cast<py_wav_handle*>(py_wav);\n    const std::size_t len = wav.size_of(interval);\n    Eigen::VectorXd ref(len, 1);\n    if (wav.get(len, ref.data())) {\n        PyErr_SetString(PyExc_IndexError, \"File length exceeded\");\n        return nullptr;\n    }\n    // Fitting form x[i] = sum(a[j] * cos(omega[j] * n) + b[j] * sin(omega[j] * n), j)\n    // where i and n are time, namely n = i / sample_rate\n    //Eigen::MatrixXd cos_sin_consts(len, 88 * 2);\n    //for (int i = 0; i != len; ++i) {\n    //    // first 88 cos, second 88 sin\n    //    for (int j = 0; j != 88; ++j) {\n    //        double tmp = i * piano_omegas[j] / wav.sample_rate;\n    //        cos_sin_consts(i, j) = std::cos(tmp);\n    //        cos_sin_consts(i, 88 + j) = std::sin(tmp);\n    //    }\n    //}\n    Eigen::MatrixXd tmp(2 * 88, 2 * 88); // = cos_sin_consts.transpose() * cos_sin_consts\n    //for (int i = 0; i < 88; ++i) {\n    //    for (int j = 0; j < 88; ++j) {\n    //        double acc1 = 0, acc2 = 0, acc3 = 0, acc4 = 0;\n    //        for (int k = 0; k != len; ++k) {\n    //            double tmp = k * piano_omegas[i] / wav.sample_rate;\n    //            double tmp2 = k * piano_omegas[j] / wav.sample_rate;\n    //            acc1 += std::cos(tmp) * std::cos(tmp2);\n    //            acc2 += std::cos(tmp) * std::sin(tmp2);\n    //            acc3 += std::sin(tmp) * std::cos(tmp2);\n    //            acc4 += std::sin(tmp) * std::sin(tmp2);\n    //        }\n    //        tmp(i, j) = acc1;\n    //        tmp(i, 88 + j) = acc2;\n    //        tmp(88 + i, j) = acc3;\n    //        tmp(88 + i, 88 + j) = acc4;\n    //    }\n    //}\n    // Lagrange's formulae applied and optimized for symmetricity\n    for (int i = 0; i != 88; ++i) {\n        double htmp3 = piano_omegas[i] / wav.sample_rate;\n        double tmp3 = 2 * htmp3;\n        tmp(i, i) = len - 0.5 + std::sin(len * tmp3 + htmp3) / (2 * std::sin(htmp3));\n        tmp(i, 88 + i) = 0.5 * (std::cos(htmp3) - std::cos(len * tmp3 + htmp3)) / std::sin(htmp3);\n        tmp(88 + i, 88 + i) = len + 0.5 - std::sin(len * tmp3 + htmp3) / (2 * std::sin(htmp3));\n        for (int j = i + 1; j != 88; ++j) {\n            double tmp1 = piano_omegas[i] / wav.sample_rate;\n            double tmp2 = piano_omegas[j] / wav.sample_rate;\n            double tmp3 = tmp1 + tmp2, tmp4 = tmp1 - tmp2;\n            double htmp3 = tmp3 * 0.5, htmp4 = tmp4 * 0.5;\n            tmp(i, j) = std::sin(len * tmp3 + htmp3) / (2 * std::sin(htmp3)) + std::sin(len * tmp4 + htmp4) / (2 * std::sin(htmp4)) - 1;\n            tmp(i, 88 + j) = 0.5 * (std::cos(htmp3) - std::cos(len * tmp3 + htmp3)) / std::sin(htmp3) - 0.5 * (std::cos(htmp4) - std::cos(len * tmp4 + htmp4)) / std::sin(htmp4);\n            /* tmp(88 + i, j) */ tmp(j, 88 + i) = 0.5 * (std::cos(htmp3) - std::cos(len * tmp3 + htmp3)) / std::sin(htmp3) + 0.5 * (std::cos(htmp4) - std::cos(len * tmp4 + htmp4)) / std::sin(htmp4);\n            tmp(88 + i, 88 + j) = std::sin(len * tmp4 + htmp4) / (2 * std::sin(htmp4)) - std::sin(len * tmp3 + htmp3) / (2 * std::sin(htmp3));\n        }\n    }\n    tmp /= 2;\n    Eigen::Matrix<double, 88 * 2, 1> rhs; // = cos_sin_consts.tranpose() * ref\n#pragma omp parallel for\n    for (int i = 0; i < 88; ++i) {\n        double acc0 = 0;\n        double acc1 = 0, acc2 = 0;\n        for (int j = 0; j != len; ++j) {\n            acc1 += std::cos(acc0) * ref[j];\n            acc2 += std::sin(acc0) * ref[j];\n            acc0 += piano_omegas[i] / wav.sample_rate;\n        }\n        rhs[i] = acc1;\n        rhs[88 + i] = acc2;\n    }\n    Eigen::Matrix<double, 88 * 2, 1> sol = tmp.selfadjointView<Eigen::Upper>().llt().solve(rhs);\n    Eigen::Map<Eigen::Array<double, 88, 1>> a(sol.data());\n    Eigen::Map<Eigen::Array<double, 88, 1>> b(sol.data() + 88);\n    npy_intp dim[] = { 88 };\n    PyObject* ret = PyArray_SimpleNew(1, dim, NPY_DOUBLE);\n    if (!ret)\n        return nullptr;\n    Eigen::Map<Eigen::Array<double, 88, 1>> power(static_cast<double*>(PyArray_GETPTR1(ret, 0)));\n    power = (a.cwiseAbs2() + b.cwiseAbs2());\n    return ret;\n}\n\nstatic PyMethodDef Methods[] = {\n    { \"get_pitch\", get_pitch, METH_VARARGS, \"\" },\n    { nullptr }\n};\n\nPyMODINIT_FUNC\nPyInit_spectrum_analyzer() {\n    PyObject* m = PyExc(PyModule_Create(&Module), nullptr);\n    import_array();\n    PyModule_AddFunctions(m, Methods);\n    PyOnly(PyType_Ready(&py_wav_handle_type), 0);\n    Py_INCREF(&py_wav_handle_type);\n    PyModule_AddObject(m, \"wav_file\", reinterpret_cast<PyObject*>(&py_wav_handle_type));\n    PyOnly(PyType_Ready(&PaInitializerType), 0);\n    Py_INCREF(&PaInitializerType);\n    PyOnly(PyType_Ready(&pa_stream_handle_type), 0);\n    Py_INCREF(&pa_stream_handle_type);\n    auto empty_arg = PyTuple_New(0);\n    auto init = PyObject_CallObject(reinterpret_cast<PyObject*>(&PaInitializerType), empty_arg);\n    Py_DECREF(empty_arg);\n    PyModule_AddObject(m, \"__Do_NOT_TouchThis\", init);\n    return m;\n}\n", "meta": {"hexsha": "7d754c409cf77f937c061fb307d4de18cefd0099", "size": 7422, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "spectrum_analyzer.cpp", "max_stars_repo_name": "Chengifei/spectrum-analyzer", "max_stars_repo_head_hexsha": "0830d2b833c10d103ea7980f58ccb7f32d09788f", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "spectrum_analyzer.cpp", "max_issues_repo_name": "Chengifei/spectrum-analyzer", "max_issues_repo_head_hexsha": "0830d2b833c10d103ea7980f58ccb7f32d09788f", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "spectrum_analyzer.cpp", "max_forks_repo_name": "Chengifei/spectrum-analyzer", "max_forks_repo_head_hexsha": "0830d2b833c10d103ea7980f58ccb7f32d09788f", "max_forks_repo_licenses": ["Apache-2.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.4636871508, "max_line_length": 198, "alphanum_fraction": 0.485179197, "num_tokens": 2239, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6959583250334526, "lm_q2_score": 0.48438008427698437, "lm_q1q2_score": 0.33710835213297263}}
{"text": "/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */\n/*\n  Copyright (C) 2013 Peter Caspers\n\n  This file is part of QuantLib, a free-software/open-source library\n  for financial quantitative analysts and developers - http://quantlib.org/\n\n  QuantLib is free software: you can redistribute it and/or modify it\n  under the terms of the QuantLib license.  You should have received a\n  copy of the license along with this program; if not, please email\n  <quantlib-dev@lists.sf.net>. The license is also available online at\n  <http://quantlib.org/license.shtml>.\n\n\n  This program is distributed in the hope that it will be useful, but\n  WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY\n  or FITNESS FOR A PARTICULAR PURPOSE. See the license for more details.\n*/\n\n/*! \\file cmsreplicationpricer.cpp\n  \\brief\n*/\n\n#include <ql/cashflows/cmsreplicationpricer.hpp>\n#include <ql/cashflows/fixedratecoupon.hpp>\n#include <ql/cashflows/iborcoupon.hpp>\n#include <ql/cashflows/cmscoupon.hpp>\n#include <ql/termstructures/yieldtermstructure.hpp>\n#include <ql/quotes/simplequote.hpp>\n#include <ql/indexes/iborindex.hpp>\n#include <ql/time/schedule.hpp>\n#include <ql/instruments/vanillaswap.hpp>\n#include <ql/math/solvers1d/brent.hpp>\n#include <ql/pricingengines/blackformula.hpp>\n\n#include <boost/make_shared.hpp>\n#include <ql/termstructures/volatility/atmsmilesection.hpp>\n\nnamespace QuantLib {\n\n    CmsReplicationPricer::CmsReplicationPricer(const Handle<SwaptionVolatilityStructure>& swaptionVol,\n                                               const Handle<Quote>& meanReversion,\n                                               const Handle<YieldTermStructure>& couponDiscountCurve,\n                                               const Settings& settings) : \n        CmsCouponPricer(swaptionVol), meanReversion_(meanReversion), \n        couponDiscountCurve_(couponDiscountCurve), settings_(settings) { \n        \n        registerWith(meanReversion_);\n        if(!couponDiscountCurve_.empty())\n            registerWith(couponDiscountCurve_);\n    }\n\n    void CmsReplicationPricer::initialize(const FloatingRateCoupon& coupon){\n\n        coupon_ =  dynamic_cast<const CmsCoupon*>(&coupon);\n        QL_REQUIRE(coupon_, \"CMS coupon needed\");\n        gearing_ = coupon_->gearing();\n        spread_ = coupon_->spread();\n        Time accrualPeriod = coupon_->accrualPeriod();\n        QL_REQUIRE(accrualPeriod != 0.0, \"null accrual period\");\n\n        fixingDate_ = coupon_->fixingDate();\n        paymentDate_ = coupon_->date();\n        swapIndex_ = coupon_->swapIndex();\n\n        forwardCurve_ = swapIndex_->forwardingTermStructure();\n        if(swapIndex_->exogenousDiscount())\n            discountCurve_ = swapIndex_->discountingTermStructure();\n        else\n            discountCurve_ = forwardCurve_;\n\n    \n        // if no coupon discount curve is given just use the discounting curve from the swap index.\n        // for rate calculation this curve cancels out in the computation, so e.g. the discounting\n        // swap engine will produce correct results, even if the couponDiscountCurve is not set here.\n        // only the price member function in this class will be dependent on the coupon discount curve.\n\n        if(couponDiscountCurve_.empty())\n            couponDiscountCurve_ = discountCurve_;\n\n        today_ = QuantLib::Settings::instance().evaluationDate();\n\n        if(paymentDate_ > today_)\n            discount_ = couponDiscountCurve_->discount(paymentDate_);\n        else discount_= 1.;\n\n        spreadLegValue_ = spread_ * accrualPeriod * discount_;\n\n        if (fixingDate_ > today_) {\n\n            swapTenor_ = swapIndex_->tenor();\n            swap_ = swapIndex_->underlyingSwap(fixingDate_);\n\n            swapRateValue_ = swap_->fairRate();\n            annuity_ = 1.0E4 * std::fabs(swap_->fixedLegBPS());\n\n            boost::shared_ptr<SmileSection> sectionTmp =\n                swaptionVolatility()->smileSection(fixingDate_, swapTenor_);\n\n            // if the section does not provide an atm level, we enhance it to\n            // have one, no need to exit with an exception ...\n\n            if (sectionTmp->atmLevel() == Null<Real>())\n                smileSection_ = boost::make_shared<AtmSmileSection>(\n                    sectionTmp, swapRateValue_);\n            else\n                smileSection_ = sectionTmp;\n\n            const Leg& fixedCoupons = swap_->fixedLeg();\n            fixedLegPaymentDates_ = std::vector<Date>(fixedCoupons.size());\n            fixedLegYearFractions_ = std::vector<Real>(fixedCoupons.size());\n            for(Size i=0; i<fixedCoupons.size(); i++) {\n                boost::shared_ptr<FixedRateCoupon> coupon = \n                    boost::dynamic_pointer_cast<FixedRateCoupon>(fixedCoupons[i]);\n                fixedLegPaymentDates_[i] = coupon->date();\n                fixedLegYearFractions_[i] = coupon->accrualPeriod();\n            }\n\n            const Leg& floatingCoupons = swap_->floatingLeg();\n            floatingLegStartDates_ = floatingLegEndDates_ = floatingLegPaymentDates_ = \n                std::vector<Date>(floatingCoupons.size());\n            for(Size i=0; i<floatingCoupons.size(); i++) {\n                boost::shared_ptr<IborCoupon> coupon = \n                    boost::dynamic_pointer_cast<IborCoupon>(floatingCoupons[i]);\n                floatingLegStartDates_[i] = coupon->accrualStartDate();\n                floatingLegEndDates_[i] = coupon->accrualEndDate();\n                floatingLegPaymentDates_[i] = coupon->date();\n            }\n            \n        }\n    }\n\n    Real CmsReplicationPricer::hullWhiteScenario(Real dt, Real h) const {\n    \n        Real e;\n\n        if(close(meanReversion_->value(),0.0))\n            e = dt;\n        else\n            e = (1.0 - std::exp( -dt * meanReversion_->value() ) ) / meanReversion_->value();\n\n        return std::exp( -h * e );\n\n    }\n\n    Real CmsReplicationPricer::annuity(Real h) const {\n    \n        Real annuity=0.0;\n        for(Size i=0; i<fixedLegYearFractions_.size(); i++) {\n            Real dt = discountCurve_->dayCounter().yearFraction(fixingDate_,fixedLegPaymentDates_[i]);\n            annuity += fixedLegYearFractions_[i] * discountCurve_->discount(fixedLegPaymentDates_[i])\n                / discountCurve_->discount(fixingDate_) * hullWhiteScenario(dt,h);\n        }\n\n        return annuity;\n\n    }\n\n    Real CmsReplicationPricer::floatingLegNpv(Real h) const {\n\n        if(settings_.simplifiedFloatingLeg_) {\n            Real dt1 = discountCurve_->dayCounter().yearFraction(fixingDate_,floatingLegStartDates_.front());\n            Real dt2 = discountCurve_->dayCounter().yearFraction(fixingDate_,floatingLegPaymentDates_.back());\n            return (discountCurve_->discount(floatingLegStartDates_.front()) * hullWhiteScenario(dt1,h) -\n                    discountCurve_->discount(floatingLegPaymentDates_.back()) * hullWhiteScenario(dt2,h)) /\n                discountCurve_->discount(fixingDate_);\n        }\n        else {\n            Real npv=0.0;\n            for(Size i=0; i<floatingLegStartDates_.size();i++) {\n                Real dt1 = forwardCurve_->dayCounter().yearFraction(fixingDate_,floatingLegStartDates_[i]);\n                Real dt2 = forwardCurve_->dayCounter().yearFraction(fixingDate_,floatingLegEndDates_[i]);\n                Real dt3 = discountCurve_->dayCounter().yearFraction(fixingDate_,floatingLegPaymentDates_[i]);\n                // we use that the day counter of the floating leg is equal to that of the float index always for\n                // swapIndex underlying swaps\n                npv += (forwardCurve_->discount(floatingLegStartDates_[i]) *\n                            hullWhiteScenario(dt1, h) /\n                            (forwardCurve_->discount(floatingLegEndDates_[i]) *\n                             hullWhiteScenario(dt2, h)) -\n                        1.0) *\n                       discountCurve_->discount(floatingLegPaymentDates_[i]) /\n                       discountCurve_->discount(fixingDate_) *\n                       hullWhiteScenario(dt3, h);\n            }\n            return npv;\n        }\n\n    }\n\n    Real CmsReplicationPricer::swapRate(Real h) const {\n\n        return floatingLegNpv(h) / annuity(h);\n\n    }\n\n    Real CmsReplicationPricer::h(Real rate) const {\n\n        Real a = -10.0, b = 10.0;\n        HHelper h(this,rate);\n        Brent solver;\n\n        Real c;\n    \n        try {\n            c = solver.solve(h,1.0E-6,0.0,a,b);\n        } catch(QuantLib::Error e) {\n            QL_FAIL(\"can not imply h from rate (\" << rate << \"):\" << e.what()); \n        }\n\n        return c;\n\n    }\n\n\n    Real CmsReplicationPricer::strikeFromVegaRatio(Real ratio, Option::Type optionType, Real referenceStrike) const {\n    \n        Real a,b,min,max,k;\n        if(optionType == Option::Call) {\n            a = swapRateValue_;\n            min = referenceStrike;\n            b = max = k = std::min(smileSection_->maxStrike(), settings_.upperRateBound_);\n        }\n        else {\n            a = min = k = std::max(smileSection_->minStrike(), settings_.lowerRateBound_);\n            b = swapRateValue_;\n            max = referenceStrike;\n        }\n\n        VegaRatioHelper h(&*smileSection_,smileSection_->vega(swapRateValue_)*ratio);\n        Brent solver;\n\n        try {\n            k = solver.solve(h,1.0E-5,(a+b)/2.0,a,b);\n        } catch(...) {\n            // use default value set above      \n        }\n\n        return std::min(std::max(k,min),max);\n\n    }\n\n\n    Real CmsReplicationPricer::strikeFromPrice(Real price, Option::Type optionType, Real referenceStrike) const {\n\n        Real a,b,min,max,k;\n        if(optionType == Option::Call) {\n            a = swapRateValue_;\n            min = referenceStrike;\n            b = max = k = std::min(smileSection_->maxStrike(), settings_.upperRateBound_);\n        }\n        else {\n            a = min = k = std::max(smileSection_->minStrike(), settings_.lowerRateBound_);\n            b = swapRateValue_;\n            max = referenceStrike;\n        }\n\n        PriceHelper h(&*smileSection_, optionType, price);\n        Brent solver;\n\n        try {\n            k = solver.solve(h,1.0E-5,swapRateValue_,a,b);\n        } catch(...) {\n            // use default value set above      \n        }\n\n        return std::min(std::max(k,min),max);\n\n    }\n\n    Real CmsReplicationPricer::optionletPrice(Option::Type optionType, Real strike) const {\n    \n        Real phi = optionType == Option::Call ? 1.0 : -1.0;\n\n        if(optionType == Option::Call && strike >= settings_.upperRateBound_) return 0.0;\n        if(optionType == Option::Put && strike <= settings_.lowerRateBound_) return 0.0;\n    \n        // determine vector of hs corresponding to scenarios;\n\n        std::vector<Real> hs;\n        switch(settings_.strategy_) {\n    \n        case Settings::DiscreteStrikeSpreads : {\n            for(Size i=0;i<settings_.n_;i++) {\n                Real k = strike + phi*settings_.discreteStrikeSpreads_[i];\n                if(k>=smileSection_->minStrike() && k<=smileSection_->maxStrike())\n                    hs.push_back( h(k) );\n            }\n            break;\n        }\n\n        case Settings::RateBound : {\n            Real h1 = h(strike);\n            Real h2 = h(optionType == Option::Call ? settings_.upperRateBound_ : settings_.lowerRateBound_);\n            for(Size i=0;i<settings_.n_;i++) {\n                hs.push_back(h1+((Real)(i+1)/(settings_.n_-1))*(h2-h1));\n            }\n            break;\n        }\n\n        case Settings::VegaRatio : {\n            // strikeFromVegaRatio ensures that returned strike is on the expected side of strike\n            Real effectiveBound = optionType == Option::Call ?\n                std::min(settings_.upperRateBound_ , \n                         strikeFromVegaRatio(settings_.vegaRatio_,optionType,strike)) :\n                std::max(settings_.lowerRateBound_, \n                         strikeFromVegaRatio(settings_.vegaRatio_,optionType,strike));\n            if(close(fabs(effectiveBound-strike),0.0)) return 0.0;\n            Real h1 = h(strike);\n            Real h2 = h(effectiveBound);\n            for(Size i=0;i<settings_.n_;i++) {\n                hs.push_back(h1+((Real)(i+1)/(settings_.n_-1))*(h2-h1));\n            }\n            break;\n        }\n\n        case Settings::PriceThreshold : {\n            // strikeFromPrice ensures that returned strike is on the expected side of strike\n            Real effectiveBound = optionType == Option::Call ?\n                std::min(settings_.upperRateBound_,\n                         strikeFromPrice(settings_.priceThreshold_,optionType,strike)) :\n                std::max(settings_.lowerRateBound_,\n                         strikeFromPrice(settings_.priceThreshold_,optionType,strike));\n            if(close(fabs(effectiveBound-strike),0.0)) return 0.0;\n            Real h1 = h(strike);\n            Real h2 = h(effectiveBound);\n            for(Size i=0;i<settings_.n_;i++) {\n                hs.push_back(h1+((Real)(i+1)/(settings_.n_-1))*(h2-h1));\n            }\n            break;\n        }\n\n        default:\n            QL_FAIL(\"Unknown strategy (\" << settings_.strategy_ << \")\");\n\n        }\n\n        // compute the hedge basket and price it\n        std::vector<Real> weights, strikes;\n\n        Real rate = strike, lastRate;\n        Real price = QL_MAX_REAL, lastPrice, basketPrice = 0.0;\n\n        for(Size i=0;i<hs.size();i++) {\n            lastPrice = price;\n            lastRate = rate;\n            rate = swapRate(hs[i]);\n            strikes.push_back(lastRate);\n            Real ann = annuity(hs[i]);\n            Real npv=0.0;\n            for(Size j=0;j<i;j++) { // this can be done _much_ more efficiently ...\n                npv += weights[j] * phi * (rate - strikes[j]) * ann;\n            }\n            Real dt = discountCurve_->dayCounter().yearFraction(fixingDate_,paymentDate_);\n            weights.push_back( ( phi * discountCurve_->discount(paymentDate_) / \n                                 discountCurve_->discount(fixingDate_) *\n                                 hullWhiteScenario(dt,hs[i]) * (rate - strike) - npv ) /\n                               ( phi * ann * (rate - lastRate) ) );\n            price = blackFormula(optionType,lastRate,swapRateValue_,\n                                 std::sqrt(smileSection_->variance(lastRate)),annuity_);\n            if(settings_.enforceMonotonicPrices_)\n                price = std::min( lastPrice, price );\n            basketPrice += weights.back()*price;\n        }\n\n        // note that fixedLegBPS() is computed w.r.t. discountCurve_, but the coupon discount curve\n        // may be different. We have to take this into account here.\n\n        basketPrice *=  coupon_->accrualPeriod() * discount_ / discountCurve_->discount(paymentDate_);\n\n        return basketPrice;\n\n    }\n\n    Real CmsReplicationPricer::meanReversion() const { return meanReversion_->value();}\n\n    Rate CmsReplicationPricer::swapletRate() const {\n        return swapletPrice()/(coupon_->accrualPeriod()*discount_);\n    }\n\n    Real CmsReplicationPricer::capletPrice(Rate effectiveCap) const {\n        // caplet is equivalent to call option on fixing\n        if (fixingDate_ <= today_) {\n            // the fixing is determined\n            const Rate Rs =\n                std::max(coupon_->swapIndex()->fixing(fixingDate_)-effectiveCap, 0.);\n            Rate price = (gearing_*Rs)*(coupon_->accrualPeriod()*discount_);\n            return price;\n        } else {\n            Real capletPrice = optionletPrice(Option::Call, effectiveCap);\n            return gearing_ * capletPrice;\n        }\n    }\n\n    Rate CmsReplicationPricer::capletRate(Rate effectiveCap) const {\n        return capletPrice(effectiveCap)/(coupon_->accrualPeriod()*discount_);\n    }\n\n    Real CmsReplicationPricer::floorletPrice(Rate effectiveFloor) const {\n        // floorlet is equivalent to put option on fixing\n        if (fixingDate_ <= today_) {\n            // the fixing is determined\n            const Rate Rs =\n                std::max(effectiveFloor-coupon_->swapIndex()->fixing(fixingDate_),0.);\n            Rate price = (gearing_*Rs)*(coupon_->accrualPeriod()*discount_);\n            return price;\n        } else {\n            Real floorletPrice = optionletPrice(Option::Put, effectiveFloor);\n            return gearing_ * floorletPrice;\n        }\n    }\n\n    Rate CmsReplicationPricer::floorletRate(Rate effectiveFloor) const {\n        return floorletPrice(effectiveFloor)/(coupon_->accrualPeriod()*discount_);\n    }\n\n    Real CmsReplicationPricer::swapletPrice() const {\n\n        if (fixingDate_ <= today_) {\n            // the fixing is determined\n            const Rate Rs = coupon_->swapIndex()->fixing(fixingDate_);\n            Rate price = (gearing_*Rs + spread_)*(coupon_->accrualPeriod()*discount_);\n            return price;\n        } else {\n            Real atmCapletPrice = optionletPrice(Option::Call, swapRateValue_);\n            Real atmFloorletPrice = optionletPrice(Option::Put, swapRateValue_);\n            return gearing_ *(coupon_->accrualPeriod()* discount_ * swapRateValue_\n                              + atmCapletPrice - atmFloorletPrice)\n                + spreadLegValue_;\n        }\n    }\n\n}\n", "meta": {"hexsha": "b0441e25f5a3324c3cc8ba24fc731aa2d308225d", "size": 17158, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ql/cashflows/cmsreplicationpricer.cpp", "max_stars_repo_name": "universe1987/QuantLib", "max_stars_repo_head_hexsha": "bbb0145aff285853755b9f6ed013f53a41163acb", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2016-03-28T15:05:23.000Z", "max_stars_repo_stars_event_max_datetime": "2020-02-17T23:05:57.000Z", "max_issues_repo_path": "ql/cashflows/cmsreplicationpricer.cpp", "max_issues_repo_name": "universe1987/QuantLib", "max_issues_repo_head_hexsha": "bbb0145aff285853755b9f6ed013f53a41163acb", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2015-02-02T20:32:43.000Z", "max_issues_repo_issues_event_max_datetime": "2015-02-02T20:32:43.000Z", "max_forks_repo_path": "ql/cashflows/cmsreplicationpricer.cpp", "max_forks_repo_name": "pcaspers/quantlib", "max_forks_repo_head_hexsha": "bbb0145aff285853755b9f6ed013f53a41163acb", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2015-01-26T14:50:24.000Z", "max_forks_repo_forks_event_max_datetime": "2015-10-23T07:41:30.000Z", "avg_line_length": 39.6258660508, "max_line_length": 117, "alphanum_fraction": 0.5962816179, "num_tokens": 4014, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6959583250334525, "lm_q2_score": 0.48438008427698437, "lm_q1q2_score": 0.3371083521329726}}
{"text": "//==============================================================================\n//         Copyright 2003 - 2011 LASMEA UMR 6602 CNRS/Univ. Clermont II\n//         Copyright 2009 - 2011 LRI    UMR 8623 CNRS/Univ Paris Sud XI\n//\n//          Distributed under the Boost Software License, Version 1.0.\n//                 See accompanying file LICENSE.txt or copy at\n//                     http://www.boost.org/LICENSE_1_0.txt\n//==============================================================================\n#ifndef NT2_ELLIPTIC_FUNCTIONS_GENERIC_ELLIPJ_HPP_INCLUDED\n#define NT2_ELLIPTIC_FUNCTIONS_GENERIC_ELLIPJ_HPP_INCLUDED\n\n#include <nt2/elliptic/functions/ellipj.hpp>\n#include <boost/fusion/tuple.hpp>\n#include <nt2/include/constants/eps.hpp>\n#include <nt2/include/functions/simd/am.hpp>\n#include <nt2/include/functions/simd/if_zero_else.hpp>\n#include <nt2/include/functions/simd/is_eqz.hpp>\n#include <nt2/include/functions/simd/multiplies.hpp>\n#include <nt2/include/functions/simd/oneminus.hpp>\n#include <nt2/include/functions/simd/sincos.hpp>\n#include <nt2/include/functions/simd/sqr.hpp>\n#include <nt2/include/functions/simd/sqrt.hpp>\n#include <nt2/sdk/meta/scalar_of.hpp>\n\nnamespace nt2 { namespace ext\n{\n  BOOST_DISPATCH_IMPLEMENT  (ellipj_, tag::cpu_,\n                             (A0)(A1),\n                             (generic_<unspecified_<A0> >)\n                             (generic_<floating_<A1> >)\n\n                            )\n  {\n    typedef boost::fusion::tuple<A0,A0,A0>        result_type;\n\n    inline result_type operator()(A0 const& a0,A1 const & a1) const\n    {\n      typedef typename nt2::meta::scalar_of<A0>::type sA0;\n      A0 s, c, d;\n      nt2::ellipj(a0, a1, nt2::Eps<sA0>(), s, c, d);\n      return result_type(s, c, d);\n    }\n  };\n\n  BOOST_DISPATCH_IMPLEMENT  (ellipj_, tag::cpu_,\n                             (A0)(A1)(A2),\n                             (generic_<unspecified_<A0> >)\n                             (generic_<floating_<A1> >)\n                             (scalar_<floating_<A2> >)\n\n                            )\n  {\n    typedef boost::fusion::tuple<A0,A0,A0>        result_type;\n\n    inline result_type operator()(A0 const& a0,A1 const & a1,A2 const & a2) const\n    {\n      A0 s, c, d;\n      nt2::ellipj(a0, a1, a2, s, c, d);\n      return result_type(s, c, d);\n    }\n  };\n\n  BOOST_DISPATCH_IMPLEMENT  (  ellipj_, tag::cpu_,\n                               (A0)(A1)(A2),\n                               (generic_<unspecified_<A0> >)\n                               (generic_<floating_<A1> >)\n                               (scalar_<floating_<A2> >)\n                               (generic_<unspecified_<A0> >)\n                            )\n  {\n    typedef boost::fusion::tuple<A0,A0>        result_type;\n\n    inline result_type operator()(A0 const& a0,A1 const & a1,A2 const & a2,A0 & a3) const\n    {\n      A0 s, c;\n      nt2::ellipj(a0,a1,a2,s,c,a3);\n      return result_type(s, c);\n    }\n  };\n\n  BOOST_DISPATCH_IMPLEMENT  (  ellipj_, tag::cpu_,\n                               (A0)(A1)(A2),\n                               (generic_<unspecified_<A0> >)\n                               (generic_<floating_<A1> >)\n                               (unspecified_<A2>)               //passing _()\n                               (generic_<unspecified_<A0> >)\n                            )\n  {\n    typedef boost::fusion::tuple<A0,A0>        result_type;\n\n    inline result_type operator()(A0 const& a0,A1 const & a1,A2 const &,A0 & a3) const\n    {\n      typedef typename nt2::meta::scalar_of<A0>::type sA0;\n      A0 s, c;\n      nt2::ellipj(a0,a1,Eps<sA0>(),s,c,a3);\n      return result_type(s, c);\n    }\n  };\n\n  BOOST_DISPATCH_IMPLEMENT  (  ellipj_, tag::cpu_,\n                               (A0)(A1)(A2),\n                               (generic_<unspecified_<A0> >)\n                               (generic_<floating_<A1> >)\n                               (scalar_<floating_<A2> >)\n                               (generic_<unspecified_<A0> >)\n                               (generic_<unspecified_<A0> >)\n                            )\n  {\n    typedef A0 result_type;\n    inline result_type operator()(A0 const& a0,A1 const & a1,A2 const & a2,A0 & a3,A0 & a4) const\n    {\n      A0 s;\n      nt2::ellipj(a0,a1,a2,s,a3,a4);\n      return s;\n    }\n  };\n\n  BOOST_DISPATCH_IMPLEMENT  (  ellipj_, tag::cpu_,\n                               (A0)(A1)(A2),\n                               (generic_<unspecified_<A0> >)\n                               (generic_<floating_<A1> >)\n                               (unspecified_<A2>)         //passing _()\n                               (generic_<unspecified_<A0> >)\n                               (generic_<unspecified_<A0> >)\n                            )\n  {\n    typedef A0 result_type;\n    inline result_type operator()(A0 const& a0,A1 const & a1,A2 const &,A0 & a3,A0 & a4) const\n    {\n      typedef typename nt2::meta::scalar_of<A0>::type sA0;\n      A0 s;\n      nt2::ellipj(a0,a1,Eps<sA0>(),s,a3,a4);\n      return s;\n    }\n  };\n\n  BOOST_DISPATCH_IMPLEMENT  (  ellipj_, tag::cpu_,\n                               (A0)(A1)(A2),\n                               (generic_<floating_<A0> >)\n                               (generic_<floating_<A1> >)\n                               (scalar_<floating_<A2> >)\n                               (generic_<floating_<A0> >)\n                               (generic_<floating_<A0> >)\n                               (generic_<floating_<A0> >)\n                            )\n  {\n    typedef void result_type;\n    inline result_type operator()(A0 const& a0, A1 const & a1, A2 const & a2,\n                                  A0 & a3, A0 & a4, A0 & a5) const\n    {\n      A0 a = am(a0, a1, a2, 'm');\n      a3 = nt2::sincos(a, a4);\n      a5 = nt2::sqrt(oneminus(if_zero_else(is_eqz(a1), a1*nt2::sqr(a3))));\n    }\n  };\n\n  BOOST_DISPATCH_IMPLEMENT  (  ellipj_, tag::cpu_,\n                               (A0)(A1)(A2),\n                               (generic_<floating_<A0> >)\n                               (generic_<floating_<A1> >)\n                               (unspecified_<A2>)       //passing _()\n                               (generic_<floating_<A0> >)\n                               (generic_<floating_<A0> >)\n                               (generic_<floating_<A0> >)\n                            )\n  {\n    typedef void result_type;\n    inline result_type operator()(A0 const& a0, A1 const & a1, A2 const &,\n                                  A0 & a3, A0 & a4, A0 & a5) const\n    {\n      typedef typename nt2::meta::scalar_of<A0>::type sA0;\n      A0 a = am(a0, a1, Eps<sA0>(), 'm');\n      a3 = nt2::sincos(a, a4);\n      a5 = nt2::sqrt(oneminus(if_zero_else(is_eqz(a1), a1*nt2::sqr(a3))));\n    }\n  };\n\n} }\n#endif\n", "meta": {"hexsha": "217d79ef3a2272e3f18f4af20eaf083988cb46d0", "size": 6700, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/core/elliptic/include/nt2/elliptic/functions/generic/ellipj.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/elliptic/include/nt2/elliptic/functions/generic/ellipj.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/elliptic/include/nt2/elliptic/functions/generic/ellipj.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": 37.2222222222, "max_line_length": 97, "alphanum_fraction": 0.4665671642, "num_tokens": 1770, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.668880247169804, "lm_q2_score": 0.5039061705290805, "lm_q1q2_score": 0.3370528838938808}}
{"text": "#include \"icp-ceres.h\"\n\n#include <Eigen/Dense>\n#include <math.h>\n#include <unordered_map>\n#include <vector>\n\n//#include \"Visualize.h\"\n\n\n#include <ceres/local_parameterization.h>\n#include <ceres/autodiff_local_parameterization.h>\n#include <ceres/types.h>\n#include <ceres/rotation.h>\n#include <ceres/ceres.h>\n\n#include <ceres/loss_function.h>\n\n#define useLocalParam\n\n\nnamespace ICP_Ceres {\n\n/*\nCeres Solving FAQ extracted from http://ceres-solver.org/solving_faqs.html:\n\n1. For small (a few hundred parameters) or dense problems use DENSE_QR.\n\n2. For general sparse problems (i.e., the Jacobian matrix has a substantial number of zeros) use SPARSE_NORMAL_CHOLESKY.\nThis requires that you have SuiteSparse or CXSparse installed.\n\n3. For bundle adjustment problems with up to a hundred or so cameras, use DENSE_SCHUR.\n\n4. For larger bundle adjustment problems with sparse Schur Complement/Reduced camera matrices use SPARSE_SCHUR.\nThis requires that you build Ceres with support for SuiteSparse, CXSparse or Eigen’s sparse linear algebra libraries.\nIf you do not have access to these libraries for whatever reason, ITERATIVE_SCHUR with SCHUR_JACOBI is an excellent alternative.\n\n5. For large bundle adjustment problems (a few thousand cameras or more) use the ITERATIVE_SCHUR solver.\nThere are a number of preconditioner choices here. SCHUR_JACOBI offers an excellent balance of speed and accuracy.\nThis is also the recommended option if you are solving medium sized problems for which DENSE_SCHUR is too slow but SuiteSparse is not available.\nNote: If you are solving small to medium sized problems, consider setting Solver::Options::use_explicit_schur_complement to true, it can result in a substantial performance boost.\nIf you are not satisfied with SCHUR_JACOBI‘s performance try CLUSTER_JACOBI and CLUSTER_TRIDIAGONAL in that order. They require that you have SuiteSparse installed.\nBoth of these preconditioners use a clustering algorithm. Use SINGLE_LINKAGE before CANONICAL_VIEWS.\n*/\nceres::Solver::Options getOptions(){\n    // Set a few options\n    ceres::Solver::Options options;\n    //options.use_nonmonotonic_steps = true;\n    //options.preconditioner_type = ceres::IDENTITY;\n    options.linear_solver_type = ceres::DENSE_QR;\n    options.max_num_iterations = 50;\n\n//    options.preconditioner_type = ceres::SCHUR_JACOBI;\n//    options.linear_solver_type = ceres::DENSE_SCHUR;\n//    options.use_explicit_schur_complement=true;\n//    options.max_num_iterations = 100;\n\n    cout << \"Ceres Solver getOptions()\" << endl;\n    cout << \"Ceres preconditioner type: \" << options.preconditioner_type << endl;\n    cout << \"Ceres linear algebra type: \" << options.sparse_linear_algebra_library_type << endl;\n    cout << \"Ceres linear solver type: \" << options.linear_solver_type << endl;\n\n    return options;\n}\n\nceres::Solver::Options getOptionsMedium(){\n    // Set a few options\n    ceres::Solver::Options options;\n\n    #ifdef _WIN32\n        options.sparse_linear_algebra_library_type = ceres::EIGEN_SPARSE;\n        options.linear_solver_type = ceres::ITERATIVE_SCHUR;\n        options.preconditioner_type = ceres::SCHUR_JACOBI;\n    #else\n        //options.sparse_linear_algebra_library_type = ceres::SUITE_SPARSE;\n        options.linear_solver_type = ceres::SPARSE_NORMAL_CHOLESKY;\n    #endif // _WIN32\n\n    //If you are solving small to medium sized problems, consider setting Solver::Options::use_explicit_schur_complement to true, it can result in a substantial performance boost.\n    options.use_explicit_schur_complement=true;\n    options.max_num_iterations = 50;\n\n    cout << \"Ceres Solver getOptionsMedium()\" << endl;\n    cout << \"Ceres preconditioner type: \" << options.preconditioner_type << endl;\n    cout << \"Ceres linear algebra type: \" << options.sparse_linear_algebra_library_type << endl;\n    cout << \"Ceres linear solver type: \" << options.linear_solver_type << endl;\n\n    return options;\n}\n\nvoid solve(ceres::Problem &problem, bool smallProblem=false){\n    ceres::Solver::Summary summary;\n    ceres::Solve(smallProblem ? getOptions() : getOptionsMedium(), &problem, &summary);\n    if(!smallProblem) std::cout << \"Final report:\\n\" << summary.FullReport();\n}\n\nvoid isoToAngleAxis(const Isometry3d& pose, double* cam){\n//    Matrix<const double,3,3> rot(pose.linear());\n//    cout<<\"rotation : \"<<pose.linear().data()<<endl;\n//    auto begin = pose.linear().data();\n    RotationMatrixToAngleAxis(ColumnMajorAdapter4x3(pose.linear().data()), cam);\n    Vector3d t(pose.translation());\n    cam[3]=t.x();\n    cam[4]=t.y();\n    cam[5]=t.z();\n}\n\nIsometry3d axisAngleToIso(const double* cam){\n    Isometry3d poseFinal = Isometry3d::Identity();\n    Matrix3d rot;\n    ceres::AngleAxisToRotationMatrix(cam,rot.data());\n    poseFinal.linear() = rot;\n    poseFinal.translation() = Vector3d(cam[3],cam[4],cam[5]);\n    return poseFinal;//.cast<float>();\n}\n\nIsometry3d eigenQuaternionToIso(const Eigen::Quaterniond& q, const Vector3d& t){\n    Isometry3d poseFinal = Isometry3d::Identity();\n    poseFinal.linear() = q.toRotationMatrix();\n    poseFinal.translation() = t;\n    return poseFinal;//.cast<float>();\n}\n\nSophus::SE3d isoToSophus(const Isometry3d& pose){\n    return Sophus::SE3d(pose);\n}\n\nIsometry3d sophusToIso(Sophus::SE3d soph){\n    //    return Isometry3d(soph.matrix());\n    Isometry3d poseFinal = Isometry3d::Identity();\n    poseFinal.linear() = soph.rotationMatrix();\n    poseFinal.translation() = soph.translation();\n    return poseFinal;\n}\n\n\nIsometry3d pointToPoint_CeresAngleAxis(vector<Vector3d>&src,vector<Vector3d>&dst){\n\n    double cam[6] = {0,0,0,0,0,0};\n\n    ceres::Problem problem;\n\n    for (int i = 0; i < src.size(); ++i) {\n        // first viewpoint : dstcloud, fixed\n        // second viewpoint: srcCloud, moves\n        ceres::CostFunction* cost_function = ICPCostFunctions::PointToPointError_CeresAngleAxis::Create(dst[i],src[i]);\n        problem.AddResidualBlock(cost_function, NULL, cam);\n    }\n\n    solve(problem);\n\n    return axisAngleToIso(cam);\n}\n\nIsometry3d pointToPoint_EigenQuaternion(vector<Vector3d>&src,vector<Vector3d>&dst){\n    Eigen::Quaterniond q = Eigen::Quaterniond::Identity();\n    Eigen::Vector3d t(0,0,0);\n\n    ceres::Problem problem;\n\n    for (int i = 0; i < src.size(); ++i) {\n        // first viewpoint : dstcloud, fixed\n        // second viewpoint: srcCloud, moves\n        ceres::CostFunction* cost_function = ICPCostFunctions::PointToPointError_EigenQuaternion::Create(dst[i],src[i]);\n        problem.AddResidualBlock(cost_function, NULL, q.coeffs().data(), t.data());\n    }\n\n#ifdef useLocalParam\n    ceres::LocalParameterization *quaternion_parameterization = new eigen_quaternion::EigenQuaternionParameterization;\n    problem.SetParameterization(q.coeffs().data(),quaternion_parameterization);\n#endif\n\n    solve(problem);\n\n    return eigenQuaternionToIso(q,t);\n}\n\nIsometry3d pointToPlane_CeresAngleAxis(vector<Vector3d> &src,vector<Vector3d> &dst,vector<Vector3d> &nor){\n\n    double cam[6] = {0,0,0,0,0,0};\n\n    ceres::Problem problem;\n\n    for (int i = 0; i < src.size(); ++i) {\n        // first viewpoint : dstcloud, fixed\n        // second viewpoint: srcCloud, moves\n        // nor is normal of dst\n        ceres::CostFunction* cost_function = ICPCostFunctions::PointToPlaneError_CeresAngleAxis::Create(dst[i],src[i],nor[i]);\n        problem.AddResidualBlock(cost_function, NULL, cam);\n    }\n\n    solve(problem);\n\n    return axisAngleToIso(cam);\n}\n\nIsometry3d pointToPlane_EigenQuaternion(vector<Vector3d>&src,vector<Vector3d>&dst,vector<Vector3d> &nor){\n    Eigen::Quaterniond q = Eigen::Quaterniond::Identity();\n    Eigen::Vector3d t(0,0,0);\n\n    ceres::Problem problem;\n\n    for (int i = 0; i < src.size(); ++i) {\n        // first viewpoint : dstcloud, fixed\n        // second viewpoint: srcCloud, moves\n        ceres::CostFunction* cost_function = ICPCostFunctions::PointToPlaneError_EigenQuaternion::Create(dst[i],src[i],nor[i]);\n        problem.AddResidualBlock(cost_function, NULL, q.coeffs().data(), t.data());\n    }\n\n#ifdef useLocalParam\n    ceres::LocalParameterization *quaternion_parameterization = new eigen_quaternion::EigenQuaternionParameterization;\n    problem.SetParameterization(q.coeffs().data(),quaternion_parameterization);\n#endif\n\n    solve(problem);\n\n    return eigenQuaternionToIso(q,t);\n}\n\nvoid ceresOptimizer(vector< std::shared_ptr<Frame> >& frames, bool pointToPlane, bool robust){\n\n    ceres::Problem problem;\n\n//    double* cameras = new double[frames.size()*7]; //4 quaternion, 3 translation\n\n    vector<Eigen::Quaterniond> qs(frames.size());\n    vector<Eigen::Vector3d> ts(frames.size());\n\n    //extract initial camera poses\n\n    for(int i=0; i<frames.size(); i++){\n      Isometry3d originalPose = frames[i]->pose;\n      Eigen::Quaterniond q;// = Eigen::Map<Eigen::Quaterniond>(cameras+i*7);\n      Eigen::Vector3d t;// = Eigen::Map<Eigen::Vector3d>(cameras+i*7+4);\n\n      q=Eigen::Quaterniond(originalPose.linear());\n      t=Eigen::Vector3d(originalPose.translation());\n\n      qs[i]=q;\n      ts[i]=t;\n\n      if (i==0){\n          frames[i]->fixed=true;\n      }\n    }\n\n    cout<<\"ok ceres\"<<endl;\n\n//    Visualize::spin(1);\n\n    //add edges\n    for(int src_id=0; src_id<frames.size(); src_id++){\n\n        Frame& srcCloud = *frames[src_id];\n        if(srcCloud.fixed) continue;\n\n        Eigen::Quaterniond& srcQ = qs[src_id];\n        Eigen::Vector3d& srcT = ts[src_id];\n\n        for (int j = 0; j < srcCloud.neighbours.size(); ++j) {\n\n            OutgoingEdge& dstEdge = srcCloud.neighbours[j];\n            Frame& dstCloud = *frames.at(dstEdge.neighbourIdx);\n\n            int dst_id=dstEdge.neighbourIdx;\n\n            Eigen::Quaterniond& dstQ = qs[dst_id];\n            Eigen::Vector3d& dstT = ts[dst_id]; //dstCloud\n\n            for(auto corr : dstEdge.correspondances){\n\n                // first viewpoint : dstcloud, fixed\n                // second viewpoint: srcCloud, moves\n\n                ceres::CostFunction* cost_function;\n\n                if(pointToPlane){\n                    cost_function = ICPCostFunctions::PointToPlaneErrorGlobal::Create(dstCloud.pts[corr.second],srcCloud.pts[corr.first],dstCloud.nor[corr.second]);\n                }else{\n                    cost_function = ICPCostFunctions::PointToPointErrorGlobal::Create(dstCloud.pts[corr.second],srcCloud.pts[corr.first]);\n                }\n\n                ceres::LossFunction* loss = NULL;\n                if(robust) loss = new ceres::SoftLOneLoss(dstEdge.weight);\n\n//                cout<<dstEdge.weight<<endl;\n//                problem.AddResidualBlock(cost_function,  srcQ.coeffs().data(),srcT.data(),dstQ.coeffs().data(), dstT.data());\n                problem.AddResidualBlock(cost_function, loss, srcQ.coeffs().data(),srcT.data(),dstQ.coeffs().data(), dstT.data());\n\n//                problem.AddResidualBlock(cost_function, NULL, &cameras[src_id*7],&cameras[src_id*7+4],&cameras[dst_id*7],&cameras[dst_id*7+4]);\n\n            }\n        }\n    }\n\n#ifdef useLocalParam\n    eigen_quaternion::EigenQuaternionParameterization *quaternion_parameterization = new eigen_quaternion::EigenQuaternionParameterization;\n#endif\n\n    for (int i = 0; i < frames.size(); ++i) {\n        #ifdef useLocalParam\n//        problem.SetParameterization(&cameras[i*7],quaternion_parameterization);\n        problem.SetParameterization(qs[i].coeffs().data(),quaternion_parameterization);\n        #endif\n\n        if(frames[i]->fixed){\n            std::cout<<i<<\" fixed\"<<endl;\n//            problem.SetParameterBlockConstant(&cameras[i*7]);\n//            problem.SetParameterBlockConstant(&cameras[i*7+4]);\n            problem.SetParameterBlockConstant(qs[i].coeffs().data());\n            problem.SetParameterBlockConstant(ts[i].data());\n        }\n    }\n\n    solve(problem);\n\n    //update camera poses\n    for (int i = 0; i < frames.size(); ++i) {\n//        poseFinal.linear() = Eigen::Map<Eigen::Quaterniond>(cameras+i*7).toRotationMatrix();\n//        poseFinal.translation() = Eigen::Map<Eigen::Vector3d>(cameras+i*7+4);\n        frames[i]->pose=eigenQuaternionToIso(qs[i],ts[i]);\n    }\n}\n\nvoid ceresOptimizer_ceresAngleAxis(vector< std::shared_ptr<Frame> >& frames, bool pointToPlane,bool robust){\n\n    ceres::Problem problem;\n\n    double* cameras = new double[frames.size()*6];\n\n    //extract initial camera poses\n    for(int i=0; i<frames.size(); i++){\n      isoToAngleAxis(frames[i]->pose,&cameras[i*6]);\n\n//      cout<<\"pose \"<<i<<endl;\n//      cout<<frames[i]->pose.matrix()<<endl;\n//      cout<<\"pose test \"<<i<<endl;\n//      cout<<axisAngleToIso(&cameras[i*6]).matrix()<<endl;\n\n//      Visualize::spin();\n\n      if (i==0){\n          frames[i]->fixed=true;\n      }\n    }\n\n    //add edges\n    for(int src_id=0; src_id<frames.size(); src_id++){\n\n        Frame& srcCloud = *frames[src_id];\n        if(srcCloud.fixed) continue;\n\n        for (int j = 0; j < srcCloud.neighbours.size(); ++j) {\n\n            OutgoingEdge& dstEdge = srcCloud.neighbours[j];\n            Frame& dstCloud = *frames.at(dstEdge.neighbourIdx);\n\n            int dst_id=dstEdge.neighbourIdx;\n\n            for(auto corr : dstEdge.correspondances){\n\n                // first viewpoint : dstcloud, fixed\n                // second viewpoint: srcCloud, moves\n\n                ceres::CostFunction* cost_function;\n\n                if(pointToPlane){\n                    cost_function = ICPCostFunctions::PointToPlaneErrorGlobal_CeresAngleAxis::Create(dstCloud.pts[corr.second],srcCloud.pts[corr.first],dstCloud.nor[corr.second]);\n                }else{\n                    cost_function = ICPCostFunctions::PointToPointErrorGlobal_CeresAngleAxis::Create(dstCloud.pts[corr.second],srcCloud.pts[corr.first]);\n                }\n\n                ceres::LossFunction* loss = NULL;\n                if(robust) loss = new ceres::SoftLOneLoss(dstEdge.weight);\n\n                problem.AddResidualBlock(cost_function, loss, &cameras[src_id*6],&cameras[dst_id*6]);\n\n            }\n        }\n    }\n\n    for (int i = 0; i < frames.size(); ++i) {\n        if(frames[i]->fixed){\n            std::cout<<i<<\" fixed\"<<endl;\n            problem.SetParameterBlockConstant(&cameras[i*6]);\n        }\n    }\n\n    solve(problem);\n\n    //update camera poses\n    for (int i = 0; i < frames.size(); ++i) {\n        frames[i]->pose=axisAngleToIso(&cameras[i*6]);\n    }\n}\n\n\nvoid ceresOptimizer_sophusSE3(vector< std::shared_ptr<Frame> >& frames, bool pointToPlane,bool robust,bool automaticDiff){\n\n    ceres::Problem problem;\n\n    std::vector<Sophus::SE3d> cameras;\n\n    //extract initial camera poses\n    for(int i=0; i<frames.size(); i++){\n      Sophus::SE3d soph = isoToSophus(frames[i]->pose);\n\n//      cout<<\"pose \"<<i<<endl;\n//      cout<<frames[i]->pose.matrix()<<endl;\n//      cout<<\"pose test \"<<i<<endl;\n//      cout<<sophusToIso(soph).matrix()<<endl;\n\n//      Visualize::spin();\n      cameras.push_back(soph);\n\n\n      if (i==0){\n          frames[i]->fixed=true;\n      }\n    }\n\n    //add edges\n    for(int src_id=0; src_id<frames.size(); src_id++){\n\n        Frame& srcCloud = *frames[src_id];\n        if(srcCloud.fixed) continue;\n\n        for (int j = 0; j < srcCloud.neighbours.size(); ++j) {\n\n            OutgoingEdge& dstEdge = srcCloud.neighbours[j];\n            Frame& dstCloud = *frames.at(dstEdge.neighbourIdx);\n\n            int dst_id=dstEdge.neighbourIdx;\n\n            for(auto corr : dstEdge.correspondances){\n\n                // first viewpoint : dstcloud, fixed\n                // second viewpoint: srcCloud, moves\n\n                ceres::CostFunction* cost_function;\n\n                if(pointToPlane){\n                    cost_function = ICPCostFunctions::PointToPlaneErrorGlobal_SophusSE3::Create(dstCloud.pts[corr.second],srcCloud.pts[corr.first],dstCloud.nor[corr.second]);\n                }else{\n                    cost_function = ICPCostFunctions::PointToPointErrorGlobal_SophusSE3::Create(dstCloud.pts[corr.second],srcCloud.pts[corr.first]);\n                }\n\n                ceres::LossFunction* loss = NULL;\n                if(robust) loss = new ceres::SoftLOneLoss(dstEdge.weight);\n\n                problem.AddResidualBlock(cost_function, loss, cameras[src_id].data(),cameras[dst_id].data());\n\n            }\n        }\n    }\n#ifdef useLocalParam\n    ceres::LocalParameterization* param = sophus_se3::getParameterization(automaticDiff);\n#endif\n    for (int i = 0; i < frames.size(); ++i) {\n        #ifdef useLocalParam\n        problem.SetParameterization(cameras[i].data(),param);\n        #endif\n        if(frames[i]->fixed){\n            std::cout<<i<<\" fixed\"<<endl;\n            problem.SetParameterBlockConstant(cameras[i].data());\n        }\n    }\n\n    solve(problem);\n\n    //update camera poses\n    for (int i = 0; i < frames.size(); ++i) {\n        frames[i]->pose=sophusToIso(cameras[i]);\n    }\n}\n\n//Isometry3d pointToPoint_SophusSE3(vector<Vector3d> &src,vector<Vector3d> &dst){\n//    Sophus::SE3d soph = isoToSophus(Isometry3d::Identity());\n//    Sophus::SE3d soph2 = isoToSophus(Isometry3d::Identity());\n\n//    ceres::Problem problem;\n\n//    for (int i = 0; i < src.size(); ++i) {\n//        // first viewpoint : dstcloud, fixed\n//        // second viewpoint: srcCloud, moves\n//        ceres::CostFunction* cost_function = ICPCostFunctions::PointToPointErrorGlobal_SophusSE3::Create(dst[i],src[i]);\n//        problem.AddResidualBlock(cost_function, NULL,soph.data(),soph2.data());\n//    }\n\n//    ceres::LocalParameterization* param = sophus_se3::getParameterization(false);\n\n//    problem.SetParameterization(soph.data(),param);\n//    problem.SetParameterization(soph2.data(),param);\n//    problem.SetParameterBlockConstant(soph2.data());\n\n//    solve(problem);\n\n//    return sophusToIso(soph);\n//}\n\n//Isometry3d pointToPlane_SophusSE3(vector<Vector3d> &src,vector<Vector3d> &dst,vector<Vector3d> &nor){\n//    Sophus::SE3d soph = isoToSophus(Isometry3d::Identity());\n//    Sophus::SE3d soph2 = isoToSophus(Isometry3d::Identity());\n\n//    ceres::Problem problem;\n\n//    for (int i = 0; i < src.size(); ++i) {\n//        // first viewpoint : dstcloud, fixed\n//        // second viewpoint: srcCloud, moves\n//        ceres::CostFunction* cost_function = ICPCostFunctions::PointToPlaneErrorGlobal_SophusSE3::Create(dst[i],src[i],nor[i]);\n//        problem.AddResidualBlock(cost_function, NULL,soph.data(),soph2.data());\n//    }\n\n//    ceres::LocalParameterization* param = sophus_se3::getParameterization(false);\n\n//    problem.SetParameterization(soph.data(),param);\n//    problem.SetParameterization(soph2.data(),param);\n//    problem.SetParameterBlockConstant(soph2.data());\n\n//    solve(problem);\n\n//    return sophusToIso(soph);\n//}\n\nIsometry3d pointToPoint_SophusSE3(vector<Vector3d> &src,vector<Vector3d> &dst,bool autodiff){\n    Sophus::SE3d soph = isoToSophus(Isometry3d::Identity());\n\n    ceres::Problem problem;\n\n    for (int i = 0; i < src.size(); ++i) {\n        // first viewpoint : dstcloud, fixed\n        // second viewpoint: srcCloud, moves\n        ceres::CostFunction* cost_function = ICPCostFunctions::PointToPointError_SophusSE3::Create(dst[i],src[i]);\n        problem.AddResidualBlock(cost_function, NULL,soph.data());\n    }\n#ifdef useLocalParam\n    ceres::LocalParameterization* param = sophus_se3::getParameterization(autodiff);\n    problem.SetParameterization(soph.data(),param);\n#endif\n\n    solve(problem);\n\n    return sophusToIso(soph);\n}\n\nIsometry3d pointToPlane_SophusSE3(vector<Vector3d> &src,vector<Vector3d> &dst,vector<Vector3d> &nor, bool autodiff){\n    Sophus::SE3d soph = isoToSophus(Isometry3d::Identity());\n\n    ceres::Problem problem;\n\n    for (int i = 0; i < src.size(); ++i) {\n        // first viewpoint : dstcloud, fixed\n        // second viewpoint: srcCloud, moves\n        ceres::CostFunction* cost_function = ICPCostFunctions::PointToPlaneError_SophusSE3::Create(dst[i],src[i],nor[i]);\n        problem.AddResidualBlock(cost_function, NULL,soph.data());\n    }\n#ifdef useLocalParam\n    ceres::LocalParameterization* param = sophus_se3::getParameterization(autodiff);\n    problem.SetParameterization(soph.data(),param);\n#endif\n\n    solve(problem);\n\n    return sophusToIso(soph);\n}\n\n\n\n} //end namespace\n\n", "meta": {"hexsha": "5233181723caaafc6c85cb254c858ec1691f8da9", "size": 20041, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/internal/icp-ceres.cpp", "max_stars_repo_name": "mitjap/mv-lm-icp", "max_stars_repo_head_hexsha": "5865c13f4e890dd7c9c1aa13dbfc4a1dd37a2c42", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 174.0, "max_stars_repo_stars_event_min_datetime": "2017-01-17T02:54:01.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T14:24:47.000Z", "max_issues_repo_path": "src/internal/icp-ceres.cpp", "max_issues_repo_name": "mitjap/mv-lm-icp", "max_issues_repo_head_hexsha": "5865c13f4e890dd7c9c1aa13dbfc4a1dd37a2c42", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2017-10-20T14:08:35.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-22T10:52:53.000Z", "max_forks_repo_path": "src/internal/icp-ceres.cpp", "max_forks_repo_name": "mitjap/mv-lm-icp", "max_forks_repo_head_hexsha": "5865c13f4e890dd7c9c1aa13dbfc4a1dd37a2c42", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 49.0, "max_forks_repo_forks_event_min_datetime": "2017-03-03T03:10:25.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-30T11:37:39.000Z", "avg_line_length": 35.0980735552, "max_line_length": 179, "alphanum_fraction": 0.663290255, "num_tokens": 5162, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7310585786300049, "lm_q2_score": 0.46101677931231594, "lm_q1q2_score": 0.33703027140864433}}
{"text": "/*\n * Copyright 2018 James Dyer\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\"); you may not\n * use this file except in compliance with the License. You may obtain a copy of\n * the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n * License for the specific language governing permissions and limitations under\n * the License.\n *\n * This is being developed for the TANGO Project: http://tango-project.eu\n */\n\n#include <sstream>\n#include <NTL/RR.h>\n#include <json/json.h>\n#include \"HE1NEncrypter.h\"\n#include \"Random.h\"\n\n/**\n * Default destructor\n */\nHE1NEncrypter::~HE1NEncrypter()\n{\n\tdelete kappamod;\n}\n\nHE1NEncrypter::HE1NEncrypter(int lambda, int eta, int nu){\n\tkappa = NTL::RandomPrime_ZZ(nu, 20);\n\tgenerateParameters(lambda,eta);\n\tNTL::ZZ_p::init(modulus);\n\tNTL::ZZ_p tmp = to_ZZ_p(kappa);\n\tkappamod = new NTL::ZZ_p(tmp);\n}\n\nHE1NEncrypter::HE1NEncrypter(int n, int d, int rho, int rhoprime)\n{\n\tNTL::RR two(2);\n\tNTL::RR exp1(rho*d);\n\tNTL::RR nplusone(n+1);\n\tNTL::RR exp2(d);\n\tNTL::RR exp3(rho);\n\tNTL::RR kloBound = pow(two,exp1)*pow(nplusone,exp2);\n\tNTL::ZZ kappaLowerBound;\n\tconv(kappaLowerBound,kloBound);\n\tlong nu = NumBits(kappaLowerBound)+1;\n\tkappa = NTL::RandomPrime_ZZ(nu, 20);\n\tNTL::RR kappareal = to_RR(kappa);\n\tNTL::RR ploBound = pow(pow(two,exp3)+pow(kappareal,two),exp2)*pow(nplusone,exp2);\n\tNTL::ZZ pLowerBound;\n\tconv(pLowerBound,ploBound);\n\tlong lambda = NumBits(pLowerBound) + 1;\n\tlong eta = ((lambda * lambda / rhoprime) - lambda);\n\tgenerateParameters(lambda,eta);\n\tNTL::ZZ_p::init(modulus);\n\tNTL::ZZ_p tmp = to_ZZ_p(kappa);\n\tkappamod = new NTL::ZZ_p(tmp);\n};\n\nHE1NEncrypter::HE1NEncrypter(std::string& secrets, std::string& parameters){\n\tJson::Value rootP;\n\tJson::Reader reader;\n\tbool parsingSuccessful = reader.parse(parameters,rootP);\n\tif (parsingSuccessful){\n\t\tmodulus = NTL::conv<NTL::ZZ>(rootP[\"modulus\"].asCString());\n\t\tNTL::ZZ_p::init(modulus);\n\t\tJson::Value rootS;\n\t\tbool parsingSuccessful = reader.parse(secrets,rootS);\n\t\tif (parsingSuccessful){\n\t\t\tp = NTL::conv<NTL::ZZ>(rootS[\"p\"].asCString());\n\t\t\tNTL::ZZ_p ptmp = to_ZZ_p(p);\n\t\t\tpmod = new NTL::ZZ_p(ptmp);\n\t\t\tq = modulus/p;\n\t\t\tkappa = NTL::conv<NTL::ZZ>(rootS[\"kappa\"].asCString());\n\t\t\tNTL::ZZ_p ktmp = to_ZZ_p(kappa);\n\t\t\tkappamod = new NTL::ZZ_p(ktmp);\n\t\t}\n\t}\n}\n\nNTL::vec_ZZ HE1NEncrypter::getKey()\n{\n\tNTL::vec_ZZ ret;\n\tret.append(p);\n\tret.append(kappa);\n    return ret;\n};\n\nNTL::ZZ_p HE1NEncrypter::encrypt(NTL::ZZ& plaintext)\n{\n    NTL::ZZ_p r = to_ZZ_p(rng->nextBigInteger(ONE, q));\n    NTL::ZZ_p s = to_ZZ_p(rng->nextBigInteger(kappa));\n    NTL::ZZ_p ptext = to_ZZ_p(plaintext);\n    return ptext+r*(*pmod)+s*(*kappamod);\n};\n\nstd::string HE1NEncrypter::writeSecretsToJSON()\n{\n\tJson::Value root;\n\tstd::stringstream pStr, kappaStr;\n\tpStr << p;\n\tkappaStr << kappa;\n\troot[\"p\"] = pStr.str();\n\troot[\"kappa\"] = kappaStr.str();\n\tJson::FastWriter writer;\n\treturn writer.write(root);\n};\n", "meta": {"hexsha": "f4cbae139d13bb2bcad6426f1c179a4fdcd227ae", "size": 3123, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/HE1NEncrypter.cpp", "max_stars_repo_name": "TANGO-Project/cryptsdc", "max_stars_repo_head_hexsha": "4428fc289c97818d58a8010593636c64bde56e82", "max_stars_repo_licenses": ["BSD-4-Clause-UC"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/HE1NEncrypter.cpp", "max_issues_repo_name": "TANGO-Project/cryptsdc", "max_issues_repo_head_hexsha": "4428fc289c97818d58a8010593636c64bde56e82", "max_issues_repo_licenses": ["BSD-4-Clause-UC"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/HE1NEncrypter.cpp", "max_forks_repo_name": "TANGO-Project/cryptsdc", "max_forks_repo_head_hexsha": "4428fc289c97818d58a8010593636c64bde56e82", "max_forks_repo_licenses": ["BSD-4-Clause-UC"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.6371681416, "max_line_length": 82, "alphanum_fraction": 0.6948447006, "num_tokens": 1035, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7248702761768248, "lm_q2_score": 0.4649015713733885, "lm_q1q2_score": 0.33699333043646795}}
{"text": "//\n// Created by brad on 1/4/16.\n//\n\n#include \"MFCCs.h\"\n#include \"armadillo\"\n#include <boost/property_tree/xml_parser.hpp>\n#include <boost/property_tree/ptree.hpp>\n//#include <log4cxx/logger.h>\n#include <iostream>\n//#include <boost/foreach.hpp>\n\nusing namespace std;\n\n//initialize everything to default params\nMFCCs::MFCCs(){// :\n//  logger(log4cxx::Logger::getLogger(\"ade.asr.MFCCs\")) {\n  normVolume = false;\n  numDiffs = 2;\n  smoothFactor = .25;\n}\n\nMFCCs::~MFCCs() {\n\n}\n\nvector<vector<double>> MFCCs::getFeatures(std::vector<double> PCMData) {\n  vector<vector<double>> out;\n\n  //TODO: is it worth getting rid of this redundancy?\n  //calculating minimum possible size for PCMData\n  int fs = 16000;\n  int Tw = 25;\n  int Ts = 10;\n\n  int numWindows = (int) round((1E-3) * Tw * fs);  //frame duration in samples\n  int numShift = (int) round((1E-3) * Ts * fs);\n\n  int minSegmentSize = -numShift + numWindows;\n\n  if ((((int) PCMData.size() - numWindows) / numShift + 1) > 0) {\n\n    //normalize volume\n    if (normVolume) PCMData = normalizeVolume(PCMData);\n\n    //caluclate MFCCS\n    //will always smooth, can set smooth PCT to 0 for no smoothing\n    vector<vector<double>> mfccs = smooth(calculateMFCCs(PCMData));\n\n    if (numDiffs > 0) {\n\n      vector<vector<double>> firstDiffs;\n      vector<vector<double>> secondDiffs;\n\n      if (numDiffs >= 1) {\n        firstDiffs = smooth(getDiffs(mfccs));\n      }\n      if (numDiffs >= 2) {\n        secondDiffs = smooth(getDiffs(firstDiffs));\n      }\n      if (numDiffs >= 3) {\n        //LOG4CXX_WARN(logger, \"we only support 2 diffs, and that's probably all you want\");\n        cout<< \"we only support 2 diffs, and that's probably all you want\";\n      }\n\n      //combine into single feature vector\n      for (int i = 0; i < mfccs.size(); i++) {\n        vector<double> combinedFeature;\n        combinedFeature.insert(combinedFeature.end(), mfccs[i].begin(), mfccs[i].end());\n        if (numDiffs >= 1) {\n          combinedFeature.insert(combinedFeature.end(), firstDiffs[i].begin(),\n                                 firstDiffs[i].end());\n        }\n        if (numDiffs >= 2) {\n          combinedFeature.insert(combinedFeature.end(), secondDiffs[i].begin(),\n                                 secondDiffs[i].end());\n        }\n        out.push_back(combinedFeature);\n      }\n    }\n    else {\n      out = mfccs;\n    }\n  }\n  else {\n    //LOG4CXX_WARN(logger,\n    //             \"No MFCCs extracted because input segment is too small.\\n segment size:\"<<\n    //             PCMData.size()<<\" min segment size: \"<<minSegmentSize<<\n    //             \". Try changing filter params\");\n  }\n  //LOG4CXX_DEBUG(logger, \"MFCCs generated: \"<<out.size());\n // cout<<\"MFCCs generated: \"<<out.size();\n  return out;\n}\n\nvector<double> MFCCs::normalizeVolume(vector<double> raw) {\n  vector<double> norm(raw.size(), 0);\n  double maxPCM = 0;\n  for (double r: raw) {\n    if (r > maxPCM)maxPCM = r;\n  }\n  for (int i = 0; i < raw.size(); i++) {\n    norm[i] = raw[i] / maxPCM;\n  }\n  return norm;\n}\n\nvector<vector<double>> MFCCs::smooth(vector<vector<double>> rough) {\n  vector<double> padding(rough[0].size(), 0.0);\n  vector<vector<double>> smoothed;\n  smoothed.push_back(padding);\n\n  //double smoothFactor = .1;\n\n  for (int i = 0; i < rough.size(); i++) {\n    vector<double> smoothedPoint(rough[i].size(), 0);\n    for (int k = 0; k < smoothedPoint.size(); k++) {\n      smoothedPoint[k] +=\n        smoothed[i][k] * (1.0 - smoothFactor) + rough[i][k] * smoothFactor;\n    }\n    smoothed.push_back(smoothedPoint);\n  }\n  smoothed.erase(smoothed.begin());\n  return smoothed;\n}\n\nvector<vector<double>> MFCCs::getDiffs(vector<vector<double>> original) {\n  vector<vector<double>> diffs(original.size(),\n                               vector<double>(original[0].size(), 0));\n  //insert copies of first and last time step\n  vector<double> first = original[0];\n  original.insert(original.begin(), first);\n  vector<double> last = original[original.size() - 1];\n  original.insert(original.end(), last);\n\n  for (int i = 1; i < original.size() - 1; i++) {\n    for (int j = 0; j < original[i].size(); j++) {\n      diffs[i - 1][j] = (original[i + 1][j] - original[i - 1][j]) / 2.0;\n    }\n  }\n  return diffs;\n}\n\n//cepstral lifter routine\ninline vector<double> MFCCs::ceplifter(double n, double l) {\n  vector<double> lift;\n  for (int i = 0; i < n; i++) {\n    lift.push_back(1 + 0.5 * l * sin(M_PI * i / l));\n  }\n  return lift;\n}\n\ninline int MFCCs::NextPowerOf2(int val) {\n  val--;\n  val = (val>>1) | val;\n  val = (val>>2) | val;\n  val = (val>>4) | val;\n  val = (val>>8) | val;\n  val = (val>>16) | val;\n  return ++val;\n}\n\n//htk pre-emphasis function\nvector<double> MFCCs::preEmphasis(double coeff, vector<double> x) {\n  vector<double> y(x.size(), 0);\n  y[0] = x[0];\n  for (int n = 1; n < x.size(); n++) {\n    y[n] = x[n] - coeff * x[n - 1];\n  }\n  return y;\n}\n\n//hamming window a la matlab\nvector<double> MFCCs::window(int windowSize) {\n  vector<double> windowed(windowSize, 0);\n  for (int n = 0; n < windowSize; n++) {\n    windowed[n] = 0.54 - .46 * cos((2 * M_PI) * ((double) n / windowSize - 1));\n  }\n  return windowed;\n}\n\n//based on mike's adaptation of  Kamil Wojcicki's \"HTK MFCC MATLAB CODE\"\n//http://www.mathworks.com/matlabcentral/fileexchange/32849-htk-mfcc-matlab/content/mfcc/mfcc.m\nvector<vector<double>> MFCCs::calculateMFCCs(vector<double> signal) {\n  vector<vector<double>> out;\n  //ofstream fout;\n  //fout.open(\"mfccstuff.txt\");\n\n  //params hard coded for now\n  int fs = 16000;\n  int Tw = 25;\n  int Ts = 10;\n  double alpha = .97;\n  int numFilterBankChannels = 26;\n  int numCC = 13;//12 + 1;// but don't use the first\n  int cepstralSineLifter = 22;\n\n  double fMin = 0; // filter coefficients start at this frequency (Hz)\n  double fLow = 20; //minFreq;//       % 20 lower cutoff frequency (Hz) for the filterbank\n  double fHigh = 4400; //maxFreq;//      % 4400 upper cutoff frequency (Hz) for the filterbank\n  double fMax =\n    0.5 * fs; //     % filter coefficients end at this frequency (Hz)\n\n  int numWindows = (int) round(\n    (1E-3) * Tw * fs);  // % frame duration (in samples)\n  int numShift = (int) round((1E-3) * Ts * fs);   //% frame shift (in samples)\n\n  double power = log2(NextPowerOf2(numWindows));\n  int nfft = pow(2, power);     // %length of FFT analysis\n  int uniqueFFT = (nfft / 2) + 1;    //% length of the unique part of the FFT\n\n  //preemphasize signal (high pass filter)\n\n  //setting up frame buckets for fft\n  //int numFrames = int((filteredSpeech.size() - numWindows) / (numShift) + 1);\n  //vector<vector<double>> frames;\n  //for (int i = 0; i < numFrames; i++) {\n  //  vector<double> nextFrame(filteredSpeech.begin() + (i * numShift),\n  //                           filteredSpeech.begin() + (i * numShift) + numWindows);\n  //  frames.push_back(nextFrame);\n  //}\n  int numFrames = ((int) (signal.size()) - numWindows) / (numShift) + 1;\n  vector<vector<double>> frames;\n  for (int i = 0; i < numFrames; i++) {\n    vector<double> nextFrame(signal.begin() + (i * numShift),\n                             signal.begin() + (i * numShift) + numWindows);\n    //frames.push_back(filter(filterVec,1,nextFrame));\n    frames.push_back(preEmphasis(alpha, nextFrame));\n  }\n\n  //create matrix for application of Hamming Window\n  vector<double> windowed = window(numWindows);\n  arma::vec aWindowed(windowed);\n  arma::mat windowMat = arma::diagmat(aWindowed);\n\n  //convert to armadillo for fft and matrix multiplication\n  arma::mat mFrames(frames[0].size(), frames.size());\n  for (int i = 0; i < frames[0].size(); i++) {\n    for (int j = 0; j < frames.size(); j++) {\n      mFrames(i, j) = frames[j][i];\n    }\n  }\n\n  //Apply hamming window to frame buckets\n  arma::mat wFrames = windowMat * mFrames;\n\n  //get energy\n  double silenceFloor = 50; //50db defaults from HTK\n  double energyScale = .1; //default vlaue from HTK\n  vector<double> energy(wFrames.n_cols, 0);\n\n  for (int i = 0; i < wFrames.n_cols; i++) {\n    double e = 0;\n    for (int j = 0; j < wFrames.n_rows; j++) {\n      e += pow(wFrames(j, i), 2);\n    }\n    energy[i] = log(e);\n  }\n\n  //normalize energy\n  double maxEnergy = 0;\n  for (double e: energy) {\n    if (e > maxEnergy)maxEnergy = e;\n  }\n  double minEnergy = maxEnergy - (silenceFloor * log(10.0)) / 10.0;\n  for (int i = 0; i < energy.size(); i++) {\n    if (energy[i] < minEnergy) energy[i] = minEnergy;\n    energy[i] = 1.0 - (maxEnergy - energy[i]) * energyScale;\n  }\n\n  // Magnitude spectrum computation\n  // could implement HTK's c++ fft here to get results closer to theirs, not sure if its worth it\n  arma::mat MAG = arma::abs(arma::fft(wFrames, nfft));\n\n  //calculate frequency range in Hz, based on sized of unique part fo fft\n  vector<double> fRange(uniqueFFT, 0);\n  for (int i = 0; i < uniqueFFT; i++) {\n    fRange[i] = i * (fMax / (uniqueFFT - 1));\n  }\n\n  double hz2melf_low = 2595 * log10(1 + fLow / 700);\n  double hz2melf_high = 2595 * log10(1 + fHigh / 700);\n\n  vector<double> melChannels;\n  for (int i = 0; i <= numFilterBankChannels + 1; i++) {\n    double temp = hz2melf_low + i * ((hz2melf_high - hz2melf_low) /\n                                     (numFilterBankChannels + 1));\n    double x = 700 * (pow(10, (temp / 2595)) - 1);\n    melChannels.push_back(x);\n  }\n\n  // create filter bank matrix to put magnitude spectrum into Mel Frequency Bands\n  // super contrived, based on doing it in MATLAB but probably doesn't need to be a matrix;\n  arma::mat H = arma::zeros(numFilterBankChannels, uniqueFFT);\n  for (int m = 0; m < numFilterBankChannels; m++) {\n    for (int k = 0; k < uniqueFFT; k++) {\n      if (fRange[k] >= melChannels[m] && fRange[k] < melChannels[m + 1]) {\n        H(m, k) =\n          (fRange[k] - melChannels[m]) / (melChannels[m + 1] - melChannels[m]);\n      }\n      if (fRange[k] >= melChannels[m + 1] && fRange[k] <= melChannels[m + 2]) {\n        H(m, k) = (melChannels[m + 2] - fRange[k]) /\n                  (melChannels[m + 2] - melChannels[m + 1]);\n      }\n    }\n  }\n\n  // GET FREQUENCY BAND ENERGY\n  // Filterbank application to unique part of the magnitude spectrum\n  arma::mat FBE =\n    H * MAG(arma::span(0, uniqueFFT - 1), arma::span(0, frames.size() - 1));\n\n  // DCT Matrix Computation\n  arma::mat DCT = arma::zeros(numCC, numFilterBankChannels);\n  for (int i = 0; i < numCC; i++) {\n    for (int j = 0; j < numFilterBankChannels; j++) {\n      DCT(i, j) = sqrt(2.0 / numFilterBankChannels) *\n                  cos((i) * (M_PI * (j + 1 - .5) / numFilterBankChannels));\n    }\n  }\n\n  // Conversion of logFBEs to cepstral coefficients through DCT\n  arma::mat CC = DCT * arma::log(FBE);\n\n  // Cepstral lifter computation\n  arma::vec lifter(ceplifter(numCC, cepstralSineLifter));\n  arma::mat lifterMat = arma::diagmat(lifter);\n\n  // Cepstral liftering gives liftered cepstral coefficients\n  arma::mat MFCCs = lifterMat * CC;\n\n  //convert back to std::vector\n  typedef vector<double> stdvec;\n  for (int i = 0; i < MFCCs.n_cols; i++) {\n    //vector<double> features(MFCCs.begin_col(i) + 1, MFCCs.end_col(i));\n    //features.push_back(energy[i]);\n\n    //this order for compatability with Mike's code\n    vector<double> features;\n    features.push_back(energy[i]);\n    features.insert(features.end(), MFCCs.begin_col(i) + 1, MFCCs.end_col(i));\n\n    out.push_back(features);\n  }\n\n  //for (int i = 0; i < out.size(); i++) {\n  //  for (double j: out[i]) {\n  //    fout << setw(10) << j << \" \";\n  //  }\n  //  fout << endl;\n  //}\n  //\n  //fout.close();\n  return out;\n}", "meta": {"hexsha": "c169c72fec06d2ae38ad85cf6e91f1bf9fdb4909", "size": 11425, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ZREval/MFCCs.cpp", "max_stars_repo_name": "brad-oosterveld/ZRSTD", "max_stars_repo_head_hexsha": "3d870d93bf513331427f68ff02cec418b21c2640", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2017-12-30T08:58:32.000Z", "max_stars_repo_stars_event_max_datetime": "2018-01-11T21:06:23.000Z", "max_issues_repo_path": "ZREval/MFCCs.cpp", "max_issues_repo_name": "brad-oosterveld/ZRSTD", "max_issues_repo_head_hexsha": "3d870d93bf513331427f68ff02cec418b21c2640", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ZREval/MFCCs.cpp", "max_forks_repo_name": "brad-oosterveld/ZRSTD", "max_forks_repo_head_hexsha": "3d870d93bf513331427f68ff02cec418b21c2640", "max_forks_repo_licenses": ["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.1830985915, "max_line_length": 97, "alphanum_fraction": 0.6069146608, "num_tokens": 3496, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7248702761768248, "lm_q2_score": 0.4649015713733885, "lm_q1q2_score": 0.33699333043646795}}
{"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__OCP_TO_NLP_HPP_\n#define SMOOTH__FEEDBACK__OCP_TO_NLP_HPP_\n\n/**\n * @file\n * @brief Formulate optimal control problem as a nonlinear program\n */\n\n#include <Eigen/Core>\n#include <smooth/lie_group.hpp>\n\n#include \"collocation/mesh.hpp\"\n#include \"collocation/mesh_function.hpp\"\n#include \"nlp.hpp\"\n#include \"ocp.hpp\"\n\nnamespace smooth::feedback {\n\n// \\cond\nnamespace detail {\n\n/// @brief Variable and constraint structure of an OCP NLP\nauto ocp_nlp_structure(const FlatOCPType auto & ocp, const MeshType auto & mesh)\n{\n  std::size_t N = mesh.N_colloc();\n\n  // variable layout\n  std::array<std::size_t, 4> var_len{\n    1,                 // tf\n    ocp.Nq,            // integrals\n    ocp.Nx * (N + 1),  // states\n    ocp.Nu * N,        // inputs\n  };\n\n  // constraint layout\n  std::array<std::size_t, 4> con_len{\n    ocp.Nx * N,   // derivatives\n    ocp.Nq,       // other integrals\n    ocp.Ncr * N,  // running constraints\n    ocp.Nce,      // end constraints\n  };\n\n  std::array<std::size_t, 5> var_beg{0};\n  std::partial_sum(var_len.begin(), var_len.end(), var_beg.begin() + 1);\n\n  std::array<std::size_t, 5> con_beg{0};\n  std::partial_sum(con_len.begin(), con_len.end(), con_beg.begin() + 1);\n\n  return std::make_tuple(var_beg, var_len, con_beg, con_len);\n}\n\n/**\n * @brief NLP representing an OCP.\n *\n * @note This class allocates matrices internally and returns references to those.\n */\ntemplate<FlatOCPType Ocp, MeshType Mesh, diff::Type DT = diff::Type::Default>\nclass OCPNLP\n{\nprivate:\n  static constexpr auto Nx = std::decay_t<Ocp>::Nx;\n  static constexpr auto Nu = std::decay_t<Ocp>::Nu;\n  static constexpr auto Nq = std::decay_t<Ocp>::Nq;\n\n  Ocp ocp_;        // optimal control problem\n  Mesh mesh_;      // discretization mesh\n  std::size_t N_;  // number of collocation points in mesh\n\n  std::size_t tfvar_B, qvar_B, xvar_B, uvar_B, n_;  // variable start indices\n  std::size_t tfvar_L, qvar_L, xvar_L, uvar_L;      // variable lengths\n\n  std::size_t dcon_B, qcon_B, crcon_B, cecon_B, m_;  // constraint start indices\n  std::size_t dcon_L, qcon_L, crcon_L, cecon_L;      // constraint lengths\n\n  // scaling\n  double w_scaling_{1};\n\n  // variable and constraint bounds\n  Eigen::VectorXd xl_, xu_, gl_, gu_;\n\n  // allocated return arguments\n  Eigen::VectorXd g_;\n  Eigen::SparseMatrix<double> df_dx_, dg_dx_, d2f_dx2_, d2g_dx2_;\n\n  // allocated computation\n  MeshValue<0> dyn_out0_, int_out0_, cr_out0_;\n  MeshValue<1> dyn_out1_, int_out1_, cr_out1_;\n  MeshValue<2> dyn_out2_, int_out2_, cr_out2_;\n\npublic:\n  /// @brief Constructor\n  template<typename OcpArg, typename MeshArg>\n  OCPNLP(OcpArg && ocp, MeshArg && mesh)\n      : ocp_(std::forward<OcpArg>(ocp)), mesh_(std::forward<MeshArg>(mesh)), N_(mesh_.N_colloc())\n  {\n    const auto [var_beg, var_len, con_beg, con_len] = detail::ocp_nlp_structure(ocp_, mesh_);\n\n    tfvar_B = var_beg[0];\n    qvar_B  = var_beg[1];\n    xvar_B  = var_beg[2];\n    uvar_B  = var_beg[3];\n    n_      = var_beg[4];\n\n    tfvar_L = var_len[0];\n    qvar_L  = var_len[1];\n    xvar_L  = var_len[2];\n    uvar_L  = var_len[3];\n\n    dcon_B  = con_beg[0];\n    qcon_B  = con_beg[1];\n    crcon_B = con_beg[2];\n    cecon_B = con_beg[3];\n    m_      = con_beg[4];\n\n    dcon_L  = con_len[0];\n    qcon_L  = con_len[1];\n    crcon_L = con_len[2];\n    cecon_L = con_len[3];\n\n    // Mesh weight\n    double max_weight = 1e-6;\n    for (auto w : mesh_.all_weights()) { max_weight = std::max(max_weight, w); }\n    w_scaling_ = 1. / max_weight;\n\n    // VARIABLE BOUNDS\n\n    xl_.setConstant(n_, -std::numeric_limits<double>::infinity());\n    xl_.segment(tfvar_B, tfvar_L).setZero();  // tf lower bounded by zero\n    xu_.setConstant(n_, std::numeric_limits<double>::infinity());\n\n    // CONSTRAINT BOUNDS\n\n    gl_.resize(m_);\n    gu_.resize(m_);\n\n    // derivative constraints are equalities\n    gl_.segment(dcon_B, dcon_L).setZero();\n    gu_.segment(dcon_B, dcon_L).setZero();\n\n    // integral constraints are equalities\n    gl_.segment(qcon_B, qcon_L).setZero();\n    gu_.segment(qcon_B, qcon_L).setZero();\n\n    // running constraints (scaled by quadrature weights)\n    gl_.segment(crcon_B, crcon_L) = ocp.crl.replicate(N_, 1);\n    gu_.segment(crcon_B, crcon_L) = ocp.cru.replicate(N_, 1);\n    for (const auto & [i, w] : utils::zip(std::views::iota(0u, N_), mesh_.all_weights())) {\n      gl_.segment(crcon_B + i * ocp_.Ncr, ocp_.Ncr) *= w_scaling_ * w;\n      gu_.segment(crcon_B + i * ocp_.Ncr, ocp_.Ncr) *= w_scaling_ * w;\n    }\n\n    // end constraints\n    gl_.segment(cecon_B, cecon_L) = ocp.cel;\n    gu_.segment(cecon_B, cecon_L) = ocp.ceu;\n\n    // allocate output args\n    g_.setZero(m_);\n\n    df_dx_.resize(1, n_);\n    df_dx_.reserve(Eigen::VectorXi::Constant(n_, 1));\n\n    d2f_dx2_.resize(n_, n_);\n    dg_dx_.resize(m_, n_);\n    d2g_dx2_.resize(n_, n_);\n\n    /// @todo Allocate nnz's to speed up first call?\n  }\n\n  std::size_t n() const { return n_; }\n  std::size_t m() const { return m_; }\n  const Eigen::VectorXd & xl() const { return xl_; }\n  const Eigen::VectorXd & xu() const { return xu_; }\n\n  double f(const Eigen::Ref<const Eigen::VectorXd> x) const\n  {\n    assert(static_cast<std::size_t>(x.size()) == n_);\n\n    const auto x0var_B = xvar_B;\n    const auto xfvar_B = xvar_B + xvar_L - Nx;\n\n    const double tf                    = x(tfvar_B);\n    const Eigen::Vector<double, Nx> x0 = x.segment(x0var_B, Nx);\n    const Eigen::Vector<double, Nx> xf = x.segment(xfvar_B, Nx);\n    const Eigen::Vector<double, Nq> q  = x.segment(qvar_B, qvar_L);\n\n    return ocp_.theta(tf, x0, xf, q);\n  }\n\n  const Eigen::SparseMatrix<double> & df_dx(const Eigen::Ref<const Eigen::VectorXd> x)\n  {\n    assert(static_cast<std::size_t>(x.size()) == n_);\n\n    const auto x0var_B = xvar_B;\n    const auto xfvar_B = xvar_B + xvar_L - Nx;\n\n    const double tf                    = x(tfvar_B);\n    const Eigen::Vector<double, Nx> x0 = x.segment(x0var_B, Nx);\n    const Eigen::Vector<double, Nx> xf = x.segment(xfvar_B, Nx);\n    const Eigen::Vector<double, Nq> q  = x.segment(qvar_B, qvar_L);\n\n    const auto & [fval, dfval] = diff::dr<1, DT>(ocp_.theta, wrt(tf, x0, xf, q));\n\n    set_zero(df_dx_);\n\n    block_add(df_dx_, 0, tfvar_B, dfval.middleCols(0, 1));           // df / dtf\n    block_add(df_dx_, 0, x0var_B, dfval.middleCols(1, Nx));          // df / dx0\n    block_add(df_dx_, 0, xfvar_B, dfval.middleCols(1 + Nx, Nx));     // df / dxf\n    block_add(df_dx_, 0, qvar_B, dfval.middleCols(1 + 2 * Nx, Nq));  // df / dq\n\n    df_dx_.makeCompressed();\n    return df_dx_;\n  }\n\n  const Eigen::SparseMatrix<double> & d2f_dx2(Eigen::Ref<const Eigen::VectorXd> x)\n  {\n    assert(static_cast<std::size_t>(x.size()) == n_);\n\n    const auto x0var_B = xvar_B;\n    const auto xfvar_B = xvar_B + xvar_L - Nx;\n\n    const double tf                    = x(tfvar_B);\n    const Eigen::Vector<double, Nx> x0 = x.segment(x0var_B, Nx);\n    const Eigen::Vector<double, Nx> xf = x.segment(xfvar_B, Nx);\n    const Eigen::Vector<double, Nq> q  = x.segment(qvar_B, qvar_L);\n\n    const auto & [fval, dfval, d2fval] = diff::dr<2, DT>(ocp_.theta, wrt(tf, x0, xf, q));\n\n    set_zero(d2f_dx2_);\n\n    // clang-format off\n    block_add(d2f_dx2_, tfvar_B, tfvar_B, d2fval.block(         0,          0,  1,  1), 1, true);  // tftf\n    block_add(d2f_dx2_, tfvar_B, x0var_B, d2fval.block(         0,          1,  1, Nx), 1, true);  // tfx0\n    block_add(d2f_dx2_, tfvar_B, xfvar_B, d2fval.block(         0,     1 + Nx,  1, Nx), 1, true);  // tfxf\n    block_add(d2f_dx2_, tfvar_B,  qvar_B, d2fval.block(         0, 1 + 2 * Nx,  1, Nq), 1, true);  // tfq\n\n    block_add(d2f_dx2_, x0var_B, x0var_B, d2fval.block(         1,          1, Nx, Nx), 1, true);  // x0x0\n    block_add(d2f_dx2_, x0var_B, xfvar_B, d2fval.block(         1,     1 + Nx, Nx, Nx), 1, true);  // x0xf\n    block_add(d2f_dx2_, x0var_B,  qvar_B, d2fval.block(         1, 1 + 2 * Nx, Nx, Nq), 1, true);  // x0q\n\n    block_add(d2f_dx2_, xfvar_B, xfvar_B, d2fval.block(    1 + Nx,     1 + Nx, Nx, Nx), 1, true);  // xfxf\n    block_add(d2f_dx2_, xfvar_B,  qvar_B, d2fval.block(    1 + Nx, 1 + 2 * Nx, Nx, Nq), 1, true);  // xfq\n\n    block_add(d2f_dx2_,  qvar_B,  qvar_B, d2fval.block(1 + 2 * Nx, 1 + 2 * Nx, Nq, Nq), 1, true);  // qq\n    // clang-format on\n\n    d2f_dx2_.makeCompressed();\n    return d2f_dx2_;\n  }\n\n  const Eigen::VectorXd & g(const Eigen::Ref<const Eigen::VectorXd> x)\n  {\n    assert(static_cast<std::size_t>(x.size()) == n_);\n\n    const auto x0var_B = xvar_B;\n    const auto xfvar_B = xvar_B + xvar_L - Nx;\n\n    const double t0                    = 0;\n    const double tf                    = x(tfvar_B);\n    const Eigen::Vector<double, Nx> x0 = x.segment(x0var_B, Nx);\n    const Eigen::Vector<double, Nx> xf = x.segment(xfvar_B, Nx);\n    const Eigen::Vector<double, Nq> q  = x.segment(qvar_B, qvar_L);\n\n    const Eigen::Map<const Eigen::Matrix<double, Nx, -1>> X(x.data() + xvar_B, Nx, N_ + 1);\n    const Eigen::Map<const Eigen::Matrix<double, Nu, -1>> U(x.data() + uvar_B, Nu, N_);\n\n    mesh_dyn<0>(dyn_out0_, mesh_, ocp_.f, t0, tf, X.colwise(), U.colwise());\n    mesh_integrate<0>(int_out0_, mesh_, ocp_.g, t0, tf, X.colwise(), U.colwise());\n    mesh_eval<0>(cr_out0_, mesh_, ocp_.cr, t0, tf, X.colwise(), U.colwise(), true);\n\n    g_.segment(dcon_B, dcon_L)   = w_scaling_ * dyn_out0_.F;\n    g_.segment(qcon_B, qcon_L)   = w_scaling_ * (int_out0_.F - q);\n    g_.segment(crcon_B, crcon_L) = w_scaling_ * cr_out0_.F;\n    g_.segment(cecon_B, cecon_L) = ocp_.ce(tf, x0, xf, q);\n\n    return g_;\n  }\n  const Eigen::VectorXd & gl() const { return gl_; }\n  const Eigen::VectorXd & gu() const { return gu_; }\n  const Eigen::SparseMatrix<double> & dg_dx(const Eigen::Ref<const Eigen::VectorXd> x)\n  {\n    assert(static_cast<std::size_t>(x.size()) == n_);\n\n    const auto x0var_B = xvar_B;\n    const auto xfvar_B = xvar_B + xvar_L - Nx;\n\n    const double t0                    = 0;\n    const double tf                    = x(tfvar_B);\n    const Eigen::Vector<double, Nx> x0 = x.segment(x0var_B, Nx);\n    const Eigen::Vector<double, Nx> xf = x.segment(xfvar_B, Nx);\n    const Eigen::Vector<double, Nq> q  = x.segment(qvar_B, qvar_L);\n\n    const Eigen::Map<const Eigen::Matrix<double, Nx, -1>> X(x.data() + xvar_B, Nx, N_ + 1);\n    const Eigen::Map<const Eigen::Matrix<double, Nu, -1>> U(x.data() + uvar_B, Nu, N_);\n\n    mesh_dyn<1, DT>(dyn_out1_, mesh_, ocp_.f, t0, tf, X.colwise(), U.colwise());\n    mesh_integrate<1, DT>(int_out1_, mesh_, ocp_.g, t0, tf, X.colwise(), U.colwise());\n    mesh_eval<1, DT>(cr_out1_, mesh_, ocp_.cr, t0, tf, X.colwise(), U.colwise(), true);\n    const auto & [ceval, dceval] = diff::dr<1, DT>(ocp_.ce, wrt(tf, x0, xf, q));\n\n    dyn_out1_.dF.makeCompressed();\n    int_out1_.dF.makeCompressed();\n    cr_out1_.dF.makeCompressed();\n\n    set_zero(dg_dx_);\n\n    // dynamics constraint\n    block_add(dg_dx_, dcon_B, tfvar_B, dyn_out1_.dF.middleCols(1, 1), w_scaling_);\n    block_add(dg_dx_, dcon_B, xvar_B, dyn_out1_.dF.middleCols(2, xvar_L), w_scaling_);\n    block_add(dg_dx_, dcon_B, uvar_B, dyn_out1_.dF.middleCols(2 + xvar_L, uvar_L), w_scaling_);\n\n    // integral constraint\n    block_add(dg_dx_, qcon_B, tfvar_B, int_out1_.dF.middleCols(1, 1), w_scaling_);\n    block_add(dg_dx_, qcon_B, xvar_B, int_out1_.dF.middleCols(2, xvar_L), w_scaling_);\n    block_add(dg_dx_, qcon_B, uvar_B, int_out1_.dF.middleCols(2 + xvar_L, uvar_L), w_scaling_);\n    block_add_identity(dg_dx_, qcon_B, qvar_B, qvar_L, -w_scaling_);\n\n    // running constraint\n    block_add(dg_dx_, crcon_B, tfvar_B, cr_out1_.dF.middleCols(1, 1), w_scaling_);\n    block_add(dg_dx_, crcon_B, xvar_B, cr_out1_.dF.middleCols(2, xvar_L), w_scaling_);\n    block_add(dg_dx_, crcon_B, uvar_B, cr_out1_.dF.middleCols(2 + xvar_L, uvar_L), w_scaling_);\n\n    // end constraint\n    block_add(dg_dx_, cecon_B, tfvar_B, dceval.middleCols(0, 1));\n    block_add(dg_dx_, cecon_B, xvar_B, dceval.middleCols(1, Nx));\n    block_add(dg_dx_, cecon_B, xvar_B + xvar_L - Nx, dceval.middleCols(1 + Nx, Nx));\n    block_add(dg_dx_, cecon_B, qvar_B, dceval.middleCols(1 + 2 * Nx, Nq));\n\n    dg_dx_.makeCompressed();\n    return dg_dx_;\n  }\n\n  const Eigen::SparseMatrix<double> &\n  d2g_dx2(const Eigen::Ref<const Eigen::VectorXd> x, const Eigen::Ref<const Eigen::VectorXd> lambda)\n  {\n    assert(static_cast<std::size_t>(x.size()) == n_);\n    assert(static_cast<std::size_t>(lambda.size()) == m_);\n\n    const auto x0var_B = xvar_B;\n    const auto xfvar_B = xvar_B + xvar_L - Nx;\n\n    const double t0                    = 0;\n    const double tf                    = x(tfvar_B);\n    const Eigen::Vector<double, Nx> x0 = x.segment(x0var_B, Nx);\n    const Eigen::Vector<double, Nx> xf = x.segment(xfvar_B, Nx);\n    const Eigen::Vector<double, Nq> q  = x.segment(qvar_B, qvar_L);\n\n    const Eigen::Map<const Eigen::Matrix<double, Nx, -1>> X(x.data() + xvar_B, Nx, N_ + 1);\n    const Eigen::Map<const Eigen::Matrix<double, Nu, -1>> U(x.data() + uvar_B, Nu, N_);\n\n    dyn_out2_.lambda = lambda.segment(dcon_B, dcon_L);\n    int_out2_.lambda = lambda.segment(qcon_B, qcon_L);\n    cr_out2_.lambda  = lambda.segment(crcon_B, crcon_L);\n    mesh_dyn<2, DT>(dyn_out2_, mesh_, ocp_.f, t0, tf, X.colwise(), U.colwise());\n    mesh_integrate<2, DT>(int_out2_, mesh_, ocp_.g, t0, tf, X.colwise(), U.colwise());\n    mesh_eval<2, DT>(cr_out2_, mesh_, ocp_.cr, t0, tf, X.colwise(), U.colwise(), true);\n    const auto & [ceval, dceval, d2ceval] = diff::dr<2, DT>(ocp_.ce, wrt(tf, x0, xf, q));\n\n    dyn_out2_.dF.makeCompressed();\n    int_out2_.dF.makeCompressed();\n    cr_out2_.dF.makeCompressed();\n\n    dyn_out2_.d2F.makeCompressed();\n    int_out2_.d2F.makeCompressed();\n    cr_out2_.d2F.makeCompressed();\n\n    set_zero(d2g_dx2_);\n\n    // clang-format off\n    block_add(d2g_dx2_, tfvar_B, tfvar_B, dyn_out2_.d2F.block(1, 1, 1, 1), w_scaling_, true);      // tftf\n    block_add(d2g_dx2_, tfvar_B, tfvar_B, int_out2_.d2F.block(1, 1, 1, 1), w_scaling_, true);      // tftf\n    block_add(d2g_dx2_, tfvar_B, tfvar_B,  cr_out2_.d2F.block(1, 1, 1, 1), w_scaling_, true);      // tftf\n\n    block_add(d2g_dx2_, tfvar_B, xvar_B, dyn_out2_.d2F.block(1, 2, 1, xvar_L), w_scaling_, true);  // tfx\n    block_add(d2g_dx2_, tfvar_B, xvar_B, int_out2_.d2F.block(1, 2, 1, xvar_L), w_scaling_, true);  // tfx\n    block_add(d2g_dx2_, tfvar_B, xvar_B,  cr_out2_.d2F.block(1, 2, 1, xvar_L), w_scaling_, true);  // tfx\n\n    block_add(d2g_dx2_, tfvar_B, uvar_B, dyn_out2_.d2F.block(1, 2 + xvar_L, 1, uvar_L), w_scaling_, true);  // tfu\n    block_add(d2g_dx2_, tfvar_B, uvar_B, int_out2_.d2F.block(1, 2 + xvar_L, 1, uvar_L), w_scaling_, true);  // tfu\n    block_add(d2g_dx2_, tfvar_B, uvar_B,  cr_out2_.d2F.block(1, 2 + xvar_L, 1, uvar_L), w_scaling_, true);  // tfu\n\n    block_add(d2g_dx2_, xvar_B, xvar_B, dyn_out2_.d2F.block(2,          2, xvar_L, xvar_L), w_scaling_, true);  // xx\n    block_add(d2g_dx2_, xvar_B, xvar_B, int_out2_.d2F.block(2,          2, xvar_L, xvar_L), w_scaling_, true);  // xx\n    block_add(d2g_dx2_, xvar_B, xvar_B,  cr_out2_.d2F.block(2,          2, xvar_L, xvar_L), w_scaling_, true);  // xx\n\n    block_add(d2g_dx2_, xvar_B, uvar_B, dyn_out2_.d2F.block(2, 2 + xvar_L, xvar_L, uvar_L), w_scaling_, true);  // xu\n    block_add(d2g_dx2_, xvar_B, uvar_B, int_out2_.d2F.block(2, 2 + xvar_L, xvar_L, uvar_L), w_scaling_, true);  // xu\n    block_add(d2g_dx2_, xvar_B, uvar_B,  cr_out2_.d2F.block(2, 2 + xvar_L, xvar_L, uvar_L), w_scaling_, true);  // xu\n\n    block_add(d2g_dx2_, uvar_B, uvar_B, dyn_out2_.d2F.block(2 + xvar_L, 2 + xvar_L, uvar_L, uvar_L), w_scaling_, true);  // uu\n    block_add(d2g_dx2_, uvar_B, uvar_B, int_out2_.d2F.block(2 + xvar_L, 2 + xvar_L, uvar_L, uvar_L), w_scaling_, true);  // uu\n    block_add(d2g_dx2_, uvar_B, uvar_B,  cr_out2_.d2F.block(2 + xvar_L, 2 + xvar_L, uvar_L, uvar_L), w_scaling_, true);  // uu\n    // clang-format on\n\n    for (auto j = 0u; j < ocp_.Nce; ++j) {\n      const auto b0 = (1 + 2 * Nx + ocp_.Nq) * j;\n      // clang-format off\n      block_add(d2g_dx2_, tfvar_B, tfvar_B, d2ceval.block(         0, b0 +          0,  1,  1), lambda(cecon_B + j), true);  // tftf\n      block_add(d2g_dx2_, tfvar_B, x0var_B, d2ceval.block(         0, b0 +          1,  1, Nx), lambda(cecon_B + j), true);  // tfx0\n      block_add(d2g_dx2_, tfvar_B, xfvar_B, d2ceval.block(         0, b0 +     1 + Nx,  1, Nx), lambda(cecon_B + j), true);  // tfxf\n      block_add(d2g_dx2_, tfvar_B,  qvar_B, d2ceval.block(         0, b0 + 1 + 2 * Nx,  1, Nq), lambda(cecon_B + j), true);  // tfq\n\n      block_add(d2g_dx2_, x0var_B, x0var_B, d2ceval.block(         1, b0 +          1, Nx, Nx), lambda(cecon_B + j), true);  // x0x0\n      block_add(d2g_dx2_, x0var_B, xfvar_B, d2ceval.block(         1, b0 +     1 + Nx, Nx, Nx), lambda(cecon_B + j), true);  // x0xf\n      block_add(d2g_dx2_, x0var_B,  qvar_B, d2ceval.block(         1, b0 + 1 + 2 * Nx, Nx, Nq), lambda(cecon_B + j), true);  // x0q\n\n      block_add(d2g_dx2_, xfvar_B, xfvar_B, d2ceval.block(    1 + Nx, b0 +     1 + Nx, Nx, Nx), lambda(cecon_B + j), true);  // xfxf\n      block_add(d2g_dx2_, xfvar_B,  qvar_B, d2ceval.block(    1 + Nx, b0 + 1 + 2 * Nx, Nx, Nq), lambda(cecon_B + j), true);  // xfq\n\n      block_add(d2g_dx2_,  qvar_B,  qvar_B, d2ceval.block(1 + 2 * Nx, b0 + 1 + 2 * Nx, Nq, Nq), lambda(cecon_B + j), true);  // qq\n      // clang-format on\n    }\n\n    d2g_dx2_.makeCompressed();\n    return d2g_dx2_;\n  }\n};\n\n}  // namespace detail\n// \\endcond\n\n/**\n * @brief Formulate an OCP as a NLP using collocation on a Mesh.\n *\n * @param ocp Optimal control problem definition\n * @param mesh collocation point structure\n * @return encoding of ocp as a nonlinear program\n *\n * @see ocpsol_to_nlpsol(), nlpsol_to_ocpsol()\n */\ntemplate<diff::Type DT = diff::Type::Default>\nauto ocp_to_nlp(FlatOCPType auto && ocp, MeshType auto && mesh)\n  -> detail::OCPNLP<std::decay_t<decltype(ocp)>, std::decay_t<decltype(mesh)>, DT>\n{\n  return detail::OCPNLP<std::decay_t<decltype(ocp)>, std::decay_t<decltype(mesh)>, DT>(\n    std::forward<decltype(ocp)>(ocp), std::forward<decltype(mesh)>(mesh));\n}\n\n/**\n * @brief Convert nonlinear program solution to ocp solution\n */\nauto nlpsol_to_ocpsol(\n  const FlatOCPType auto & ocp, const MeshType auto & mesh, const NLPSolution & nlp_sol)\n{\n  using ocp_t = std::decay_t<decltype(ocp)>;\n\n  static constexpr auto Nx  = ocp_t::Nx;\n  static constexpr auto Nu  = ocp_t::Nu;\n  static constexpr auto Nq  = ocp_t::Nq;\n  static constexpr auto Ncr = ocp_t::Ncr;\n\n  const std::size_t N                             = mesh.N_colloc();\n  const auto [var_beg, var_len, con_beg, con_len] = detail::ocp_nlp_structure(ocp, mesh);\n\n  const auto [tfvar_B, qvar_B, xvar_B, uvar_B, n] = var_beg;\n  const auto [tfvar_L, qvar_L, xvar_L, uvar_L]    = var_len;\n\n  const auto [dcon_B, qcon_B, crcon_B, cecon_B, m] = con_beg;\n  const auto [dcon_L, qcon_L, crcon_L, cecon_L]    = con_len;\n\n  const double t0 = 0;\n  const double tf = nlp_sol.x(tfvar_B);\n\n  const Eigen::Vector<double, Nq> Q = nlp_sol.x.segment(qvar_B, qvar_L);\n\n  // state vector has a value at the endpoint\n\n  Eigen::MatrixXd X(ocp.Nx, N + 1);\n  X = nlp_sol.x.segment(xvar_B, xvar_L).reshaped(ocp.Nx, xvar_L / ocp.Nx);\n\n  auto xfun =\n    [t0 = t0, tf = tf, mesh = mesh, X = std::move(X)](double t) -> Eigen::Vector<double, Nx> {\n    return mesh.template eval<Eigen::Vector<double, Nx>>(\n      (t - t0) / (tf - t0), X.colwise(), 0, true);\n  };\n\n  // for these we repeat last point since there are no values for endpoint\n\n  Eigen::MatrixXd U(ocp.Nu, N);\n  U = nlp_sol.x.segment(uvar_B, uvar_L).reshaped(ocp.Nu, uvar_L / ocp.Nu);\n\n  auto ufun =\n    [t0 = t0, tf = tf, mesh = mesh, U = std::move(U)](double t) -> Eigen::Vector<double, Nu> {\n    return mesh.template eval<Eigen::Vector<double, Nu>>(\n      (t - t0) / (tf - t0), U.colwise(), 0, false);\n  };\n\n  Eigen::MatrixXd Ldyn(ocp.Nx, N);\n  Ldyn = nlp_sol.lambda.segment(dcon_B, dcon_L).reshaped(ocp.Nx, dcon_L / ocp.Nx);\n\n  auto ldfun =\n    [t0 = t0, tf = tf, mesh = mesh, Ldyn = std::move(Ldyn)](double t) -> Eigen::Vector<double, Nx> {\n    return mesh.template eval<Eigen::Vector<double, Nx>>(\n      (t - t0) / (tf - t0), Ldyn.colwise(), 0, false);\n  };\n\n  Eigen::MatrixXd Lcr(ocp.Ncr, N);\n  Lcr = nlp_sol.lambda.segment(crcon_B, crcon_L).reshaped(ocp.Ncr, crcon_L / ocp.Ncr);\n\n  auto lcrfun =\n    [t0 = t0, tf = tf, mesh = mesh, Lcr = std::move(Lcr)](double t) -> Eigen::Vector<double, Ncr> {\n    return mesh.template eval<Eigen::Vector<double, Ncr>>(\n      (t - t0) / (tf - t0), Lcr.colwise(), 0, false);\n  };\n\n  return OCPSolution<typename ocp_t::X, typename ocp_t::U, ocp_t::Nq, ocp_t::Ncr, ocp_t::Nce>{\n    .t0         = t0,\n    .tf         = tf,\n    .Q          = std::move(Q),\n    .u          = std::move(ufun),\n    .x          = std::move(xfun),\n    .lambda_q   = nlp_sol.lambda.segment(qcon_B, qcon_L),\n    .lambda_ce  = nlp_sol.lambda.segment(cecon_B, cecon_L),\n    .lambda_dyn = std::move(ldfun),\n    .lambda_cr  = std::move(lcrfun),\n  };\n}\n\n/**\n * @brief Convert ocp solution to nonlinear program solution\n *\n * @note Allocates memory for return type.\n */\nNLPSolution\nocpsol_to_nlpsol(const FlatOCPType auto & ocp, const MeshType auto & mesh, const auto & ocpsol)\n{\n  const auto N = mesh.N_colloc();\n\n  const auto [var_beg, var_len, con_beg, con_len] = detail::ocp_nlp_structure(ocp, mesh);\n\n  const auto [tfvar_B, qvar_B, xvar_B, uvar_B, n] = var_beg;\n  const auto [tfvar_L, qvar_L, xvar_L, uvar_L]    = var_len;\n\n  const auto [dcon_B, qcon_B, crcon_B, cecon_B, m] = con_beg;\n  const auto [dcon_L, qcon_L, crcon_L, cecon_L]    = con_len;\n\n  const double t0 = 0;\n  const double tf = ocpsol.tf;\n\n  Eigen::VectorXd x(n), lambda(m);\n\n  x(tfvar_B)                = ocpsol.tf;\n  x.segment(qvar_B, qvar_L) = ocpsol.Q;\n\n  lambda.segment(qcon_B, qcon_L)   = ocpsol.lambda_q;\n  lambda.segment(cecon_B, cecon_L) = ocpsol.lambda_ce;\n\n  for (const auto & [i, tau] : utils::zip(std::views::iota(0u), mesh.all_nodes())) {\n    x.segment(xvar_B + i * ocp.Nx, ocp.Nx) = ocpsol.x(t0 + tau * (tf - t0));\n    if (i < N) {\n      x.segment(uvar_B + i * ocp.Nu, ocp.Nu)         = ocpsol.u(t0 + tau * (tf - t0));\n      lambda.segment(dcon_B + i * ocp.Nx, ocp.Nx)    = ocpsol.lambda_dyn(t0 + tau * (tf - t0));\n      lambda.segment(crcon_B + i * ocp.Ncr, ocp.Ncr) = ocpsol.lambda_cr(t0 + tau * (tf - t0));\n    }\n  }\n\n  return {\n    .status = NLPSolution::Status::Unknown,\n    .x      = std::move(x),\n    .zl     = Eigen::VectorXd::Zero(n),\n    .zu     = Eigen::VectorXd::Zero(n),\n    .lambda = std::move(lambda),\n  };\n}\n\n}  // namespace smooth::feedback\n\n#endif  // SMOOTH__FEEDBACK__OCP_TO_NLP_HPP_\n", "meta": {"hexsha": "c64d41b9ca401b457da4a58d109bc40c77ac28e3", "size": 23753, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/smooth/feedback/ocp_to_nlp.hpp", "max_stars_repo_name": "tgurriet/smooth_feedback", "max_stars_repo_head_hexsha": "1f926cb4269741ddc09ba048af5bea5e0390a053", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/smooth/feedback/ocp_to_nlp.hpp", "max_issues_repo_name": "tgurriet/smooth_feedback", "max_issues_repo_head_hexsha": "1f926cb4269741ddc09ba048af5bea5e0390a053", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/smooth/feedback/ocp_to_nlp.hpp", "max_forks_repo_name": "tgurriet/smooth_feedback", "max_forks_repo_head_hexsha": "1f926cb4269741ddc09ba048af5bea5e0390a053", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.0556492411, "max_line_length": 132, "alphanum_fraction": 0.6385298699, "num_tokens": 8309, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6297746213017459, "lm_q2_score": 0.5350984286266115, "lm_q1q2_score": 0.3369914102474836}}
{"text": "//\n// Created by eliane on 06/03/19.\n//\n\n#include \"VinaLikeCovalentReversible.h\"\n\n#include <exception>\n\n#include <Structures/Atom.h>\n\n#include <Engines/Internals/InternalsUtilityFunctions.h>\n\n#include <boost/log/trivial.hpp>\n\n#include \"VinaLikeCommon.h\"\n#include \"VinaExtendedCommon.h\"\n\nnamespace SmolDock::Score {\n\n    const std::array<std::string, VinaLikeCovalentReversible::numCoefficients>\n    VinaLikeCovalentReversible::coefficientsNames =  {\"Gauss1\", \"Gauss2\", \"RepulsionExceptCovalent\", \"Hydrophobic\",\"Hydrogen\", \"CovalentReversible\"};\n\n\n    template<bool OnlyIntermolecular, bool useNonDefaultCoefficients> // default : false\n    double VinaLikeCovalentReversibleIntermolecularScoringFunction(const iConformer &ligand_, iTransform &transform,\n                                                 const iProtein &protein,\n                                                 std::array<double, VinaLikeCovalentReversible_numCoefficients> nonDefaultCoeffs) {\n\n        BOOST_ASSERT(!ligand_.x.empty());\n        BOOST_ASSERT(!protein.x.empty());\n\n        BOOST_ASSERT(transform.bondRotationsAngles.size() == ligand_.num_rotatable_bond);\n\n        if(std::abs(transform.rota.norm() - 1) > 0.1) {\n            transform.rota.normalize();\n        }\n\n\n        double score_raw = 0;\n\n        iConformer ligand = ligand_;\n        applyBondRotationInPlace(ligand, transform);\n\n        Eigen::Vector3d ProtCenterPosition = {protein.center_x, protein.center_y, protein.center_z};\n\n        if constexpr(!OnlyIntermolecular) // C++17\n        {\n            for (unsigned int idxLig = 0; idxLig < ligand.x.size(); idxLig++) {\n                for (unsigned int idxLig2 = idxLig; idxLig2 < ligand.x.size(); idxLig2++) {\n\n                    if(idxLig == idxLig2)\n                        continue;\n\n                    Eigen::Vector3d LigDistance = {ligand.x[idxLig] - ligand.x[idxLig2],\n                                                   ligand.y[idxLig] - ligand.y[idxLig2],\n                                                   ligand.z[idxLig] - ligand.z[idxLig2]};\n\n                    double distance_raw = LigDistance.norm();\n                    const double distance = distanceFromRawDistance(distance_raw, ligand.atomicRadius[idxLig],\n                                                                    ligand.atomicRadius[idxLig2]);\n\n//                score_raw += VinaClassic::coeff_gauss1      * vinaGaussComponent(distance, 0.0, 0.5);\n//                score_raw += VinaClassic::coeff_gauss2      * vinaGaussComponent(distance, 3.0, 2.0);\n                    score_raw += VinaClassic::coeff_repulsion   * vinaRepulsionComponent(distance, 0.0);\n                }\n            }\n        }\n\n\n        for (unsigned int idxLig = 0; idxLig < ligand.x.size(); idxLig++) {\n            for (unsigned int idxProt = 0; idxProt < protein.x.size(); idxProt++) {\n\n\n\n                Eigen::Vector3d LigPosition = {ligand.x[idxLig], ligand.y[idxLig], ligand.z[idxLig]};\n                applyRigidTransformInPlace(LigPosition, transform);\n\n\n                Eigen::Vector3d ProtPosition = {protein.x[idxProt], protein.y[idxProt], protein.z[idxProt]};\n                Eigen::Vector3d distToCenterVector = LigPosition - ProtCenterPosition;\n\n                double distanceToProteinCenter = distToCenterVector.norm();\n\n                if (distanceToProteinCenter > (protein.radius - 1)) {\n                    score_raw += std::pow((distanceToProteinCenter - protein.radius), 4) + 10;\n                    continue;\n                }\n\n                Eigen::Vector3d distVect = ProtPosition - LigPosition;\n\n                double rawDist = distVect.norm();\n\n                if (rawDist >= VinaClassic::interaction_cutoff)\n                    continue;\n\n\n                const double distance = distanceFromRawDistance(rawDist, ligand.atomicRadius[idxLig],\n                                                                protein.atomicRadius[idxProt]);\n\n                const unsigned int atom1AtomicNumber = ligand.type[idxLig];\n                const unsigned int atom1AtomVariant = ligand.variant[idxLig];\n                const unsigned int atom2AtomicNumber = protein.type[idxProt];\n                const unsigned int atom2AtomVariant = protein.variant[idxProt];\n\n\n                if constexpr(useNonDefaultCoefficients)\n                {\n                    score_raw += nonDefaultCoeffs[0]      * vinaGaussComponent(distance, 0.0, 0.5);\n                    score_raw += nonDefaultCoeffs[1]     * vinaGaussComponent(distance, 3.0, 2.0);\n                    score_raw += nonDefaultCoeffs[2]   * vinaRepulsionComponent(distance, 0.0);\n                    score_raw += nonDefaultCoeffs[3] * vinaHydrophobicComponent(distance,\n                                                                               atom1AtomicNumber, atom1AtomVariant,\n                                                                               atom2AtomicNumber, atom2AtomVariant);\n\n                    score_raw += nonDefaultCoeffs[4]    * vinaHydrogenComponent(distance,\n                                                                               atom1AtomicNumber, atom1AtomVariant,\n                                                                               atom2AtomicNumber, atom2AtomVariant);\n                    score_raw += nonDefaultCoeffs[5] * VinaExtended::covalentReversibleComponent(distance,\n                                                                                                                    atom1AtomicNumber, atom1AtomVariant,\n                                                                                                                    atom2AtomicNumber, atom2AtomVariant);\n                }else {\n                    score_raw += VinaClassic::coeff_gauss1      * vinaGaussComponent(distance, 0.0, 0.5);\n                    score_raw += VinaClassic::coeff_gauss2      * vinaGaussComponent(distance, 3.0, 2.0);\n                    score_raw += VinaClassic::coeff_repulsion   * VinaExtended::RepulsionExceptForCovalentComponent(distance, 0.0,\n                                                                                                                    atom1AtomicNumber, atom1AtomVariant,\n                                                                                                                    atom2AtomicNumber, atom2AtomVariant);\n                    score_raw += VinaClassic::coeff_hydrophobic * vinaHydrophobicComponent(distance,\n                                                                                           atom1AtomicNumber, atom1AtomVariant,\n                                                                                           atom2AtomicNumber, atom2AtomVariant);\n\n                    score_raw += VinaClassic::coeff_hydrogen    * vinaHydrogenComponent(distance,\n                                                                                        atom1AtomicNumber, atom1AtomVariant,\n                                                                                        atom2AtomicNumber, atom2AtomVariant);\n\n                    score_raw += VinaExtended::coeff_CovalentReversible * VinaExtended::covalentReversibleComponent(distance,\n                                                                                                                    atom1AtomicNumber, atom1AtomVariant,\n                                                                                                                    atom2AtomicNumber, atom2AtomVariant);\n                }\n\n\n\n            } // for\n        } // for\n\n        double final_score = score_raw / (1 + (VinaClassic::coeff_entropic * ligand.num_rotatable_bond));\n        return final_score;\n    }\n\n\n\n\n    VinaLikeCovalentReversible::VinaLikeCovalentReversible(const iConformer &startingConformation_,\n                       const iProtein &p,\n                       const iTransform &initialTransform_,\n                       double differential_epsilon_,\n                        bool useNonDefaultCoefficient) :\n            useNonDefaultCoefficient(useNonDefaultCoefficient),\n            startingConformation(startingConformation_),\n            prot(p),\n            initialTransform(initialTransform_),\n            differential_epsilon(differential_epsilon_) {\n        this->numberOfRotatableBonds = this->startingConformation.num_rotatable_bond;\n        this->numberOfParamInState = 7 + (this->numberOfRotatableBonds);\n\n        if (this->initialTransform.bondRotationsAngles.size() != this->numberOfRotatableBonds) {\n            BOOST_LOG_TRIVIAL(error)\n                    << \"Discrepency between the number of rotatable bonds in the iConformer and iTransform (\"\n                    << this->numberOfRotatableBonds << \" != \" << this->initialTransform.bondRotationsAngles.size()\n                    << \")\";\n            std::terminate();\n        }\n\n        this->nonDefaultCoefficients = {VinaClassic::coeff_gauss1, VinaClassic::coeff_gauss2,\n                                        VinaClassic::coeff_repulsion, VinaClassic::coeff_hydrophobic,\n                                        VinaClassic::coeff_hydrogen, VinaExtended::coeff_CovalentReversible };\n\n    }\n\n\n    double VinaLikeCovalentReversible::Evaluate(const arma::mat &x) {\n        BOOST_ASSERT(x.n_rows == this->numberOfParamInState);\n\n        iTransform tr = this->internalToExternalRepr(x);\n\n        tr.doHousekeeping();\n\n        double score_ = VinaLikeCovalentReversibleIntermolecularScoringFunction(this->startingConformation, tr, this->prot);\n\n        return score_;\n    }\n\n    double VinaLikeCovalentReversible::EvaluateWithGradient(const arma::mat &x, arma::mat &grad) {\n\n        BOOST_ASSERT(!x.has_nan());\n        BOOST_ASSERT(!grad.has_nan());\n        BOOST_ASSERT(x.n_rows == this->numberOfParamInState);\n        BOOST_ASSERT(grad.n_rows == this->numberOfParamInState);\n\n        iTransform tr = this->internalToExternalRepr(x);\n        tr.doHousekeeping();\n\n\n        double score_ = VinaLikeCovalentReversibleIntermolecularScoringFunction(this->startingConformation, tr, this->prot);\n\n        // Translation\n        {\n            iTransform transform_dx = tr;\n            transform_dx.transl.x() += this->differential_epsilon;\n            const double gradScore = this->useNonDefaultCoefficient ?\n                                     VinaLikeCovalentReversibleIntermolecularScoringFunction<false,true>(this->startingConformation, transform_dx, this->prot, this->nonDefaultCoefficients)\n                                                                    : VinaLikeCovalentReversibleIntermolecularScoringFunction<false,false>(this->startingConformation, transform_dx, this->prot);\n            grad[0] = gradScore - score_;\n        }\n\n        {\n            iTransform transform_dy = tr;\n            transform_dy.transl.y() += this->differential_epsilon;\n            const double gradScore = this->useNonDefaultCoefficient ?\n                                     VinaLikeCovalentReversibleIntermolecularScoringFunction<false,true>(this->startingConformation, transform_dy, this->prot, this->nonDefaultCoefficients)\n                                                                    : VinaLikeCovalentReversibleIntermolecularScoringFunction<false,false>(this->startingConformation, transform_dy, this->prot);\n            grad[1] = gradScore - score_;\n        }\n\n        {\n            iTransform transform_dz = tr;\n            transform_dz.transl.z() += this->differential_epsilon;\n            const double gradScore = this->useNonDefaultCoefficient ?\n                                     VinaLikeCovalentReversibleIntermolecularScoringFunction<false,true>(this->startingConformation, transform_dz, this->prot, this->nonDefaultCoefficients)\n                                                                    : VinaLikeCovalentReversibleIntermolecularScoringFunction<false,false>(this->startingConformation, transform_dz, this->prot);\n            grad[2] = gradScore - score_;\n        }\n\n        // Rotation\n\n        {\n            iTransform transform_dqs = tr;\n            transform_dqs.rota.w() += this->differential_epsilon;\n            transform_dqs.doHousekeeping();\n            const double gradScore = this->useNonDefaultCoefficient ?\n                                     VinaLikeCovalentReversibleIntermolecularScoringFunction<false,true>(this->startingConformation, transform_dqs, this->prot, this->nonDefaultCoefficients)\n                                                                    : VinaLikeCovalentReversibleIntermolecularScoringFunction<false,false>(this->startingConformation, transform_dqs, this->prot);\n            grad[3] = gradScore - score_;\n        }\n\n        {\n            iTransform transform_dqx = tr;\n            transform_dqx.rota.x() += this->differential_epsilon;\n            transform_dqx.doHousekeeping();\n            const double gradScore = this->useNonDefaultCoefficient ?\n                                     VinaLikeCovalentReversibleIntermolecularScoringFunction<false,true>(this->startingConformation, transform_dqx, this->prot, this->nonDefaultCoefficients)\n                                                                    : VinaLikeCovalentReversibleIntermolecularScoringFunction<false,false>(this->startingConformation, transform_dqx, this->prot);\n            grad[4] = gradScore - score_;\n\n        }\n\n        {\n            iTransform transform_dqy = tr;\n            transform_dqy.rota.x() += this->differential_epsilon;\n            transform_dqy.doHousekeeping();\n            const double gradScore = this->useNonDefaultCoefficient ?\n                                     VinaLikeCovalentReversibleIntermolecularScoringFunction<false,true>(this->startingConformation, transform_dqy, this->prot, this->nonDefaultCoefficients)\n                                                                    : VinaLikeCovalentReversibleIntermolecularScoringFunction<false,false>(this->startingConformation, transform_dqy, this->prot);\n            grad[5] = gradScore - score_;\n        }\n\n        {\n            iTransform transform_dqz = tr;\n            transform_dqz.rota.x() += this->differential_epsilon;\n            transform_dqz.doHousekeeping();\n            const double gradScore = this->useNonDefaultCoefficient ?\n                                     VinaLikeCovalentReversibleIntermolecularScoringFunction<false,true>(this->startingConformation, transform_dqz, this->prot, this->nonDefaultCoefficients)\n                                                                    : VinaLikeCovalentReversibleIntermolecularScoringFunction<false,false>(this->startingConformation, transform_dqz, this->prot);\n            grad[6] = gradScore - score_;\n        }\n\n        for (unsigned int i = 0; i < this->numberOfRotatableBonds; i++) {\n            iTransform transform_dbondrot = tr;\n            transform_dbondrot.bondRotationsAngles[i] += this->differential_epsilon;\n            const double gradScore = this->useNonDefaultCoefficient ?\n                                     VinaLikeCovalentReversibleIntermolecularScoringFunction<false,true>(this->startingConformation, transform_dbondrot, this->prot, this->nonDefaultCoefficients)\n                                                                    : VinaLikeCovalentReversibleIntermolecularScoringFunction<false,false>(this->startingConformation, transform_dbondrot, this->prot);\n            grad[7 + i] = gradScore - score_;\n\n        }\n\n        /*\n        BOOST_LOG_TRIVIAL(debug) << \"Transform: \" << x.t();\n        BOOST_LOG_TRIVIAL(debug) << \"Score: \" << score_;\n        BOOST_LOG_TRIVIAL(debug) << \"Gradient\";\n        BOOST_LOG_TRIVIAL(debug) << \"     ds: \" << grad[3];\n        BOOST_LOG_TRIVIAL(debug) << \"     du: \" << grad[4] << \"   dx: \" << grad[0];\n        BOOST_LOG_TRIVIAL(debug) << \"     dv: \" << grad[5] << \"   dy: \" << grad[1];\n        BOOST_LOG_TRIVIAL(debug) << \"     dt: \" << grad[6] << \"   dx: \" << grad[2];\n        //*/\n\n        BOOST_ASSERT(score_ == score_); // catches NaN\n        return score_;\n    }\n\n\n    double VinaLikeCovalentReversible::getDifferentialEpsilon() const {\n        return this->differential_epsilon;\n    }\n\n    arma::mat VinaLikeCovalentReversible::getStartingConditions() const {\n        return this->externalToInternalRepr(this->initialTransform);\n    }\n\n    iConformer VinaLikeCovalentReversible::getConformerForParamMatrix(const arma::mat &x) {\n        BOOST_ASSERT(x.n_rows == this->numberOfParamInState);\n\n        iTransform tr = this->internalToExternalRepr(x);\n        tr.doHousekeeping();\n\n        iConformer ret = this->startingConformation;\n        applyBondRotationInPlace(ret, tr);\n        applyRigidTransformInPlace(ret, tr);\n\n        return ret;\n    }\n\n    unsigned int VinaLikeCovalentReversible::getParamVectorDimension() const {\n        return this->numberOfParamInState;\n    }\n\n    std::vector<std::tuple<std::string, double>> VinaLikeCovalentReversible::EvaluateSubcomponents(const arma::mat &x) {\n\n\n        BOOST_ASSERT(x.n_rows == this->numberOfParamInState);\n\n        iTransform tr = this->internalToExternalRepr(x);\n        tr.doHousekeeping();\n\n\n        return VinaLikeCovalentReversibleIntermolecularComponents(this->startingConformation, tr, this->prot);\n    }\n\n    double VinaLikeCovalentReversible::EvaluateOnlyIntermolecular(const arma::mat &x) {\n        BOOST_ASSERT(x.n_rows == this->numberOfParamInState);\n\n        iTransform tr = this->internalToExternalRepr(x);\n\n        tr.doHousekeeping();\n\n        // Template parameter controls whether onlyIntermolecular interaction are taken into account. Here we want true\n        double score_ = VinaLikeCovalentReversibleIntermolecularScoringFunction<true>(this->startingConformation, tr, this->prot);\n\n        return score_;\n    }\n\n    unsigned int VinaLikeCovalentReversible::getCoefficientsVectorWidth() {\n        return this->numCoefficients;\n    }\n\n    std::vector<std::string> VinaLikeCovalentReversible::getCoefficientsNames() {\n        return std::vector<std::string>(this->coefficientsNames.begin(), this->coefficientsNames.end());\n    }\n\n    std::vector<double> VinaLikeCovalentReversible::getCurrentCoefficients() {\n        if(this->useNonDefaultCoefficient)\n        {\n            return std::vector<double>(this->nonDefaultCoefficients.begin(),this->nonDefaultCoefficients.end());\n        }\n        return {VinaClassic::coeff_gauss1, VinaClassic::coeff_gauss2,\n                VinaClassic::coeff_repulsion, VinaClassic::coeff_hydrophobic,\n                VinaClassic::coeff_hydrogen, VinaExtended::coeff_CovalentReversible };\n\n    }\n\n    bool VinaLikeCovalentReversible::setNonDefaultCoefficients(std::vector<double> coeffs) {\n        if(coeffs.size() != this->numCoefficients)\n        {\n            BOOST_LOG_TRIVIAL(error) << \"Trying to set \" << this->numCoefficients <<\" coefficients with vector of \" << coeffs.size() << \" values.\";\n            return false;\n        }\n        if(this->useNonDefaultCoefficient == false)\n        {\n            BOOST_LOG_TRIVIAL(error) << \"Trying to set non default coefficient, but this scoring function was constructed with default coefficients only.\";\n            BOOST_LOG_TRIVIAL(error) << \"Check the parameters passed to the scoring function constructor.\";\n            return false;\n        }\n        for (unsigned int j = 0; j < this->nonDefaultCoefficients.size(); ++j) {\n            this->nonDefaultCoefficients[j] = coeffs[j];\n        }\n        return true;\n    }\n\n    template<bool useNonDefaultCoefficients> // default : false\n    std::vector<std::tuple<std::string, double>> VinaLikeCovalentReversibleIntermolecularComponents(const iConformer &conformer, iTransform &transform,\n                                                                                                    const iProtein &protein,\n                                                                                                    std::array<double, VinaLikeCovalentReversible_numCoefficients> nonDefaultCoeffs)\n    {\n        BOOST_ASSERT(!conformer.x.empty());\n        BOOST_ASSERT(!protein.x.empty());\n        BOOST_ASSERT(transform.bondRotationsAngles.size() == conformer.num_rotatable_bond);\n\n        if(std::abs(transform.rota.norm() - 1) > 0.1) {\n            transform.rota.normalize();\n        }\n\n        std::vector<std::tuple<std::string, double>> ret;\n\n        double gauss1_total = 0.0;\n        double gauss2_total = 0.0;\n        double repulsion_total = 0.0;\n        double repulsion_VinaClassic_total = 0.0;\n        double hydrogen_total = 0.0;\n        double hydrophobic_total = 0.0;\n        double covrev_total = 0.0;\n        double score_raw = 0.0;\n\n        double intramolecular_repuls_total = 0.0;\n        double intramolecular_score = 0.0;\n\n        iConformer ligand = conformer;\n        applyBondRotationInPlace(ligand, transform);\n\n        Eigen::Vector3d ProtCenterPosition = {protein.center_x, protein.center_y, protein.center_z};\n\n        for (unsigned int idxLig = 0; idxLig < ligand.x.size(); idxLig++) {\n            for (unsigned int idxLig2 = idxLig; idxLig2 < ligand.x.size(); idxLig2++) {\n\n                if(idxLig == idxLig2)\n                    continue;\n\n                Eigen::Vector3d LigDistance = {ligand.x[idxLig] - ligand.x[idxLig2],\n                                               ligand.y[idxLig] - ligand.y[idxLig2],\n                                               ligand.z[idxLig] - ligand.z[idxLig2]};\n\n                double distance_raw = LigDistance.norm();\n                const double distance = distanceFromRawDistance(distance_raw, ligand.atomicRadius[idxLig],\n                                                                ligand.atomicRadius[idxLig2]);\n\n//                score_raw += VinaClassic::coeff_gauss1      * vinaGaussComponent(distance, 0.0, 0.5);\n//                score_raw += VinaClassic::coeff_gauss2      * vinaGaussComponent(distance, 3.0, 2.0);\n                intramolecular_repuls_total +=  vinaRepulsionComponent(distance, 0.0);\n\n            }\n        }\n\n        intramolecular_score = VinaClassic::coeff_repulsion   * intramolecular_repuls_total;\n\n\n        for (unsigned int idxLig = 0; idxLig < ligand.x.size(); idxLig++) {\n            for (unsigned int idxProt = 0; idxProt < protein.x.size(); idxProt++) {\n\n\n\n                Eigen::Vector3d LigPosition = {ligand.x[idxLig], ligand.y[idxLig], ligand.z[idxLig]};\n                applyRigidTransformInPlace(LigPosition, transform);\n\n\n                Eigen::Vector3d ProtPosition = {protein.x[idxProt], protein.y[idxProt], protein.z[idxProt]};\n                Eigen::Vector3d distToCenterVector = LigPosition - ProtCenterPosition;\n\n                double distanceToProteinCenter = distToCenterVector.norm();\n\n                if (distanceToProteinCenter > (protein.radius - 1)) {\n                    score_raw += std::pow((distanceToProteinCenter - protein.radius), 4) + 10;\n                    continue;\n                }\n\n                Eigen::Vector3d distVect = ProtPosition - LigPosition;\n\n                double rawDist = distVect.norm();\n\n                if (rawDist >= VinaClassic::interaction_cutoff)\n                    continue;\n\n                const double distance = distanceFromRawDistance(rawDist, ligand.atomicRadius[idxLig],\n                                                          protein.atomicRadius[idxProt]);\n\n                const unsigned int atom1AtomicNumber = ligand.type[idxLig];\n                const unsigned int atom1AtomVariant = ligand.variant[idxLig];\n                const unsigned int atom2AtomicNumber = protein.type[idxProt];\n                const unsigned int atom2AtomVariant = protein.variant[idxProt];\n\n\n                gauss1_total += vinaGaussComponent(distance, 0.0, 0.5);\n                gauss2_total += vinaGaussComponent(distance, 3.0, 2.0);\n                repulsion_total += VinaExtended::RepulsionExceptForCovalentComponent(distance, 0.0,\n                                                                                     atom1AtomicNumber, atom1AtomVariant,\n                                                                                     atom2AtomicNumber, atom2AtomVariant);\n                hydrophobic_total += vinaHydrophobicComponent(distance,\n                                                           atom1AtomicNumber, atom1AtomVariant,\n                                                           atom2AtomicNumber, atom2AtomVariant);\n                hydrogen_total += vinaHydrogenComponent(distance,\n                                                           atom1AtomicNumber, atom1AtomVariant,\n                                                           atom2AtomicNumber, atom2AtomVariant);\n                covrev_total += VinaExtended::covalentReversibleComponent(distance,\n                                                                          atom1AtomicNumber, atom1AtomVariant,\n                                                                          atom2AtomicNumber, atom2AtomVariant);\n\n                // Not used in the calculation of the score\n                repulsion_VinaClassic_total += vinaRepulsionComponent(distance, 0.0);\n\n\n            } // for\n        } // for\n\n        double score_sum = 0.0;\n        double score_NoCovRev = 0.0;\n        if constexpr(useNonDefaultCoefficients)\n        {\n            ret.emplace_back(std::make_tuple(\"NonDefaultCoeffs\", 1.0));\n            score_sum =   nonDefaultCoeffs[0] * gauss1_total\n                                 + nonDefaultCoeffs[1] * gauss2_total\n                                 + nonDefaultCoeffs[2] * repulsion_total\n                                 + nonDefaultCoeffs[3] * hydrophobic_total\n                                 + nonDefaultCoeffs[4] * hydrogen_total\n                                 + nonDefaultCoeffs[5] * covrev_total;\n\n            score_NoCovRev =   nonDefaultCoeffs[0] * gauss1_total\n                               + nonDefaultCoeffs[1] * gauss2_total\n                               + nonDefaultCoeffs[2] * repulsion_total\n                               + nonDefaultCoeffs[3] * hydrophobic_total\n                               + nonDefaultCoeffs[4] * hydrogen_total;\n        }else {\n            score_sum =   VinaClassic::coeff_gauss1 * gauss1_total\n                                 + VinaClassic::coeff_gauss2 * gauss2_total\n                                 + VinaClassic::coeff_repulsion * repulsion_total\n                                 + VinaClassic::coeff_hydrophobic * hydrophobic_total\n                                 + VinaClassic::coeff_hydrogen * hydrogen_total\n                                 + VinaExtended::coeff_CovalentReversible * covrev_total;\n\n            score_NoCovRev =   VinaClassic::coeff_gauss1 * gauss1_total\n                                      + VinaClassic::coeff_gauss2 * gauss2_total\n                                      + VinaClassic::coeff_repulsion * repulsion_total\n                                      + VinaClassic::coeff_hydrophobic * hydrophobic_total\n                                      + VinaClassic::coeff_hydrogen * hydrogen_total;\n        }\n\n\n\n\n\n        double final_score = score_sum / (1 + (VinaClassic::coeff_entropic * ligand.num_rotatable_bond));\n\n        double final_score_nocovrev = score_NoCovRev / (1 + (VinaClassic::coeff_entropic * ligand.num_rotatable_bond));\n\n\n        ret.emplace_back(std::make_tuple(\"Gauss1\", gauss1_total));\n        ret.emplace_back(std::make_tuple(\"Gauss2\", gauss2_total));\n        ret.emplace_back(std::make_tuple(\"Repulsion_NotUsedInScore\", repulsion_VinaClassic_total));\n        ret.emplace_back(std::make_tuple(\"RepulsionExceptCovalent\", repulsion_total));\n        ret.emplace_back(std::make_tuple(\"Hydrophobic\", hydrophobic_total));\n        ret.emplace_back(std::make_tuple(\"Hydrogen\", hydrogen_total ));\n        ret.emplace_back(std::make_tuple(\"CovalentReversible\", covrev_total));\n        ret.emplace_back(std::make_tuple(\"numRot\", ligand.num_rotatable_bond));\n        ret.emplace_back(std::make_tuple(\"Intra_Repuls\", intramolecular_repuls_total));\n        ret.emplace_back(std::make_tuple(\"Intra_Score\", intramolecular_score));\n        ret.emplace_back(std::make_tuple(\"ScoreRaw_NoCovRev\", score_NoCovRev));\n        ret.emplace_back(std::make_tuple(\"Score_NoCovRev\", final_score_nocovrev));\n        ret.emplace_back(std::make_tuple(\"Score_Raw\", score_sum));\n        ret.emplace_back(std::make_tuple(\"Score\", final_score));\n        return ret;\n    }\n\n}", "meta": {"hexsha": "e1c9690c8690cb5d84b63b09e5b31a91ecd01402", "size": 28317, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Engines/ScoringFunctions/VinaLikeCovalentReversible.cpp", "max_stars_repo_name": "ElianeBriand/SMolDock", "max_stars_repo_head_hexsha": "de0cb746ef995ae0eef0f812ebd61727311c332f", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-05-30T02:33:13.000Z", "max_stars_repo_stars_event_max_datetime": "2019-05-30T02:33:13.000Z", "max_issues_repo_path": "Engines/ScoringFunctions/VinaLikeCovalentReversible.cpp", "max_issues_repo_name": "ElianeBriand/SMolDock", "max_issues_repo_head_hexsha": "de0cb746ef995ae0eef0f812ebd61727311c332f", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Engines/ScoringFunctions/VinaLikeCovalentReversible.cpp", "max_forks_repo_name": "ElianeBriand/SMolDock", "max_forks_repo_head_hexsha": "de0cb746ef995ae0eef0f812ebd61727311c332f", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2020-12-30T19:11:51.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-25T02:45:49.000Z", "avg_line_length": 50.656529517, "max_line_length": 199, "alphanum_fraction": 0.5738249108, "num_tokens": 5972, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7371581510799253, "lm_q2_score": 0.45713671682749485, "lm_q1q2_score": 0.3369820569673035}}
{"text": "/**\n * @file stability.cpp\n *\n */\n\n#include \"stability.h\"\n#include \"forecast_time.h\"\n#include \"level.h\"\n#include \"logger.h\"\n#include \"metutil.h\"\n#include \"plugin_factory.h\"\n#include <algorithm>  // for std::transform\n#include <boost/thread.hpp>\n#include <functional>  // for std::plus\n\n#include \"fetcher.h\"\n#include \"hitool.h\"\n\nusing namespace std;\nusing namespace himan;\nusing namespace himan::plugin;\n\nvector<double> Shear(shared_ptr<const plugin_configuration> conf, const forecast_time& ftime, const param& wantedParam,\n                     double lowerHeight, double upperHeight);\n\n#ifdef DEBUG\nvoid DumpVector(const vector<double>& vec);\n#endif\n\n// Required source and target parameters and levels\n\nconst param TParam(\"T-K\");\nconst param TDParam(\"TD-K\");\nconst param HParam(\"Z-M2S2\");\nconst params PParam({param(\"P-HPA\"), param(\"P-PA\")});\nconst param KIParam(\"KINDEX-N\", 80, 0, 7, 2);\nconst param VTIParam(\"VTI-N\", 4754);\nconst param CTIParam(\"CTI-N\", 4751);\nconst param TTIParam(\"TTI-N\", 4755, 0, 7, 4);\nconst param SIParam(\"SI-N\", 4750, 0, 7, 13);\nconst param LIParam(\"LI-N\", 4751, 0, 7, 192);\nconst param BS01Param(\"WSH-1-KT\", 4771);  // knots!\nconst param BS06Param(\"WSH-KT\", 4770);    // knots!\nconst param SRH01Param(\"HLCY-1-M2S2\", 4773);\nconst param SRH03Param(\"HLCY-M2S2\", 4772, 0, 7, 8);\n\nconst level P850Level(himan::kPressure, 850, \"PRESSURE\");\nconst level P700Level(himan::kPressure, 700, \"PRESSURE\");\nconst level P500Level(himan::kPressure, 500, \"PRESSURE\");\nlevel groundLevel(himan::kHeight, 0, \"HEIGHT\");\n\nvoid T500mSearch(shared_ptr<const plugin_configuration> conf, const forecast_time& ftime, vector<double>& result);\nvoid TD500mSearch(shared_ptr<const plugin_configuration> conf, const forecast_time& ftime, vector<double>& result);\n\nstability::stability() : itsLICalculation(false), itsBSCalculation(false), itsSRHCalculation(false)\n{\n\titsLogger = logger(\"stability\");\n}\n\nvoid stability::Process(std::shared_ptr<const plugin_configuration> conf)\n{\n\tInit(conf);\n\n\tvector<param> theParams;\n\n\t// Kindex\n\ttheParams.push_back(KIParam);\n\n\t// Cross totals index\n\ttheParams.push_back(CTIParam);\n\n\t// Vertical Totals index\n\ttheParams.push_back(VTIParam);\n\n\t// Total Totals index\n\ttheParams.push_back(TTIParam);\n\n\tif (itsConfiguration->Exists(\"li\") && itsConfiguration->GetValue(\"li\") == \"true\")\n\t{\n\t\t// Lifted index\n\n\t\titsLICalculation = true;\n\t\ttheParams.push_back(LIParam);\n\n\t\t// Showalter Index\n\t\ttheParams.push_back(SIParam);\n\t}\n\n\tif (itsConfiguration->Exists(\"bs\") && itsConfiguration->GetValue(\"bs\") == \"true\")\n\t{\n\t\titsBSCalculation = true;\n\n\t\t// Bulk shear 0 .. 1 km\n\t\ttheParams.push_back(BS01Param);\n\n\t\t// Bulk shear 0 .. 6 km\n\n\t\ttheParams.push_back(BS06Param);\n\t}\n\n\tif (itsConfiguration->Exists(\"srh\") && itsConfiguration->GetValue(\"srh\") == \"true\")\n\t{\n\t\t// Storm relative helicity 0 .. 1 km\n\t\ttheParams.push_back(SRH01Param);\n\n\t\t// Storm relative helicity 0 .. 3 km\n\t\ttheParams.push_back(SRH03Param);\n\t}\n\n\tSetParams(theParams);\n\n\tStart();\n}\n\n/*\n * Calculate()\n *\n * This function does the actual calculation.\n */\n\nvoid stability::Calculate(shared_ptr<info> myTargetInfo, unsigned short theThreadIndex)\n{\n\tvector<double> T500mVector, TD500mVector, P500mVector, U01Vector, V01Vector, U06Vector, V06Vector, UidVector,\n\t    VidVector;\n\n\tauto myThreadedLogger = logger(\"stabilityThread #\" + to_string(theThreadIndex));\n\n\tforecast_time forecastTime = myTargetInfo->Time();\n\tlevel forecastLevel = myTargetInfo->Level();\n\n\tinfo_t T850Info, T700Info, T500Info, TD850Info, TD700Info;\n\n\tmyThreadedLogger.Info(\"Calculating time \" + static_cast<string>(forecastTime.ValidDateTime()) + \" level \" +\n\t                      static_cast<string>(forecastLevel));\n\n\tbool LICalculation = itsLICalculation;\n\tbool BSCalculation = itsBSCalculation;\n\tbool SRHCalculation = itsSRHCalculation;\n\n\tif (!GetSourceData(T850Info, T700Info, T500Info, TD850Info, TD700Info, myTargetInfo,\n\t                   itsConfiguration->UseCudaForPacking()))\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\tif (LICalculation)\n\t{\n\t\tif (!GetLISourceData(myTargetInfo, T500mVector, TD500mVector, P500mVector))\n\t\t{\n\t\t\tmyThreadedLogger.Warning(\"Source data not found for param LI\");\n\t\t\tLICalculation = false;\n\t\t}\n\t}\n\n\tif (BSCalculation)\n\t{\n\t\tif (!GetWindShearSourceData(myTargetInfo, U01Vector, V01Vector, U06Vector, V06Vector))\n\t\t{\n\t\t\tmyThreadedLogger.Warning(\"Source data not found for param BulkShear\");\n\t\t\tBSCalculation = false;\n\t\t}\n\t}\n\n\tif (SRHCalculation)\n\t{\n\t\tif (!GetSRHSourceData(myTargetInfo, UidVector, VidVector))\n\t\t{\n\t\t\tmyThreadedLogger.Warning(\"Source data not found for param SRH\");\n\t\t\tSRHCalculation = false;\n\t\t}\n\t}\n\n\tstring deviceType = \"CPU\";\n\n#ifdef HAVE_CUDA\n\n\tif (itsConfiguration->UseCuda())\n\t{\n\t\tdeviceType = \"GPU\";\n\n\t\tunique_ptr<stability_cuda::options> opts(new stability_cuda::options);\n\n\t\topts->t500 = T500Info->ToSimple();\n\t\topts->t700 = T700Info->ToSimple();\n\t\topts->t850 = T850Info->ToSimple();\n\t\topts->td700 = TD700Info->ToSimple();\n\t\topts->td850 = TD850Info->ToSimple();\n\n\t\tmyTargetInfo->Param(param(\"KINDEX-N\"));\n\t\topts->ki = myTargetInfo->ToSimple();\n\n\t\tmyTargetInfo->Param(param(\"VTI-N\"));\n\t\topts->vti = myTargetInfo->ToSimple();\n\n\t\tmyTargetInfo->Param(param(\"CTI-N\"));\n\t\topts->cti = myTargetInfo->ToSimple();\n\n\t\tmyTargetInfo->Param(param(\"TTI-N\"));\n\t\topts->tti = myTargetInfo->ToSimple();\n\n\t\tif (LICalculation)\n\t\t{\n\t\t\topts->t500m = &T500mVector[0];\n\t\t\topts->td500m = &TD500mVector[0];\n\t\t\topts->p500m = &P500mVector[0];\n\n\t\t\tmyTargetInfo->Param(param(\"LI-N\"));\n\t\t\topts->li = myTargetInfo->ToSimple();\n\n\t\t\tmyTargetInfo->Param(param(\"SI-N\"));\n\t\t\topts->si = myTargetInfo->ToSimple();\n\t\t}\n\n\t\tif (BSCalculation)\n\t\t{\n\t\t\topts->u01 = &U01Vector[0];\n\t\t\topts->v01 = &V01Vector[0];\n\t\t\topts->u06 = &U06Vector[0];\n\t\t\topts->v06 = &V06Vector[0];\n\n\t\t\tmyTargetInfo->Param(BS01Param);\n\t\t\topts->bs01 = myTargetInfo->ToSimple();\n\t\t\tmyTargetInfo->Param(BS06Param);\n\t\t\topts->bs06 = myTargetInfo->ToSimple();\n\t\t}\n\n\t\topts->N = opts->t500->size_x * opts->t500->size_y;\n\n\t\tstability_cuda::Process(*opts);\n\t}\n\telse\n#endif\n\t{\n\t\tLOCKSTEP(myTargetInfo, T850Info, T700Info, T500Info, TD850Info, TD700Info)\n\t\t{\n\t\t\tdouble T850 = T850Info->Value();\n\t\t\tdouble T700 = T700Info->Value();\n\t\t\tdouble T500 = T500Info->Value();\n\t\t\tdouble TD850 = TD850Info->Value();\n\t\t\tdouble TD700 = TD700Info->Value();\n\n\t\t\tassert(T850 > 0);\n\t\t\tassert(T700 > 0);\n\t\t\tassert(T500 > 0);\n\t\t\tassert(TD850 > 0);\n\t\t\tassert(TD700 > 0);\n\n\t\t\tdouble value = kFloatMissing;\n\n\t\t\tif (T850 == kFloatMissing || T700 == kFloatMissing || T500 == kFloatMissing || TD850 == kFloatMissing ||\n\t\t\t    TD700 == kFloatMissing)\n\t\t\t{\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tvalue = metutil::KI_(T850, T700, T500, TD850, TD700);\n\t\t\tmyTargetInfo->Param(KIParam);\n\t\t\tmyTargetInfo->Value(value);\n\n\t\t\tvalue = metutil::CTI_(T500, TD850);\n\t\t\tmyTargetInfo->Param(CTIParam);\n\t\t\tmyTargetInfo->Value(value);\n\n\t\t\tvalue = metutil::VTI_(T850, T500);\n\t\t\tmyTargetInfo->Param(VTIParam);\n\t\t\tmyTargetInfo->Value(value);\n\n\t\t\tvalue = metutil::TTI_(T850, T500, TD850);\n\t\t\tmyTargetInfo->Param(TTIParam);\n\t\t\tmyTargetInfo->Value(value);\n\n\t\t\tif (LICalculation)\n\t\t\t{\n\t\t\t\tsize_t locationIndex = myTargetInfo->LocationIndex();\n\n\t\t\t\tdouble T500m = T500mVector[locationIndex];\n\t\t\t\tdouble TD500m = TD500mVector[locationIndex];\n\t\t\t\tdouble P500m = P500mVector[locationIndex];\n\n\t\t\t\tassert(T500m != kFloatMissing);\n\t\t\t\tassert(TD500m != kFloatMissing);\n\t\t\t\tassert(P500m != kFloatMissing);\n\n\t\t\t\tif (T500m != kFloatMissing && TD500m != kFloatMissing && P500m != kFloatMissing)\n\t\t\t\t{\n\t\t\t\t\tvalue = metutil::LI_(T500, T500m, TD500m, P500m);\n\n\t\t\t\t\tmyTargetInfo->Param(LIParam);\n\t\t\t\t\tmyTargetInfo->Value(value);\n\t\t\t\t}\n\n\t\t\t\tvalue = metutil::SI_(T850, T500, TD850);\n\t\t\t\tmyTargetInfo->Param(SIParam);\n\t\t\t\tmyTargetInfo->Value(value);\n\t\t\t}\n\n\t\t\tif (BSCalculation)\n\t\t\t{\n\t\t\t\tsize_t locationIndex = myTargetInfo->LocationIndex();\n\n\t\t\t\tdouble U01 = U01Vector[locationIndex];\n\t\t\t\tdouble V01 = V01Vector[locationIndex];\n\t\t\t\tdouble U06 = U06Vector[locationIndex];\n\t\t\t\tdouble V06 = V06Vector[locationIndex];\n\n\t\t\t\tassert(U01 != kFloatMissing);\n\t\t\t\tassert(V01 != kFloatMissing);\n\n\t\t\t\tassert(U06 != kFloatMissing);\n\t\t\t\tassert(V06 != kFloatMissing);\n\n\t\t\t\tif (U01 != kFloatMissing && V01 != kFloatMissing)\n\t\t\t\t{\n\t\t\t\t\tvalue = metutil::BulkShear_(U01, V01);\n\n\t\t\t\t\tmyTargetInfo->Param(BS01Param);\n\t\t\t\t\tmyTargetInfo->Value(value);\n\t\t\t\t}\n\n\t\t\t\tif (U06 != kFloatMissing && V01 != kFloatMissing)\n\t\t\t\t{\n\t\t\t\t\tvalue = metutil::BulkShear_(U06, V06);\n\n\t\t\t\t\tmyTargetInfo->Param(BS06Param);\n\t\t\t\t\tmyTargetInfo->Value(value);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (SRHCalculation)\n\t\t\t{\n\t\t\t\tsize_t locationIndex = myTargetInfo->LocationIndex();\n\n\t\t\t\tdouble Uid = UidVector[locationIndex];\n\t\t\t\tdouble Vid = VidVector[locationIndex];\n\n\t\t\t\tassert(Uid != kFloatMissing);\n\t\t\t\tassert(Vid != kFloatMissing);\n\n\t\t\t\tif (Uid != kFloatMissing && Vid != kFloatMissing)\n\t\t\t\t{\n\t\t\t\t}\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 T500mSearch(shared_ptr<const plugin_configuration> conf, const forecast_time& ftime, vector<double>& result)\n{\n\tauto h = dynamic_pointer_cast<hitool>(plugin_factory::Instance()->Plugin(\"hitool\"));\n\n\th->Configuration(conf);\n\th->Time(ftime);\n\n\tresult = h->VerticalAverage(param(\"T-K\"), 0, 500);\n\n#ifdef DEBUG\n\tfor (size_t i = 0; i < result.size(); i++)\n\t{\n\t\tassert(result[i] != kFloatMissing);\n\t}\n#endif\n}\n\nvoid TD500mSearch(shared_ptr<const plugin_configuration> conf, const forecast_time& ftime, vector<double>& result)\n{\n\tauto h = dynamic_pointer_cast<hitool>(plugin_factory::Instance()->Plugin(\"hitool\"));\n\n\th->Configuration(conf);\n\th->Time(ftime);\n\n\tresult = h->VerticalAverage(param(\"TD-K\"), 0, 500);\n}\n#if 0\ninline\ndouble stability::StormRelativeHelicity(double UID, double VID, double U_lower, double U_higher, double V_lower, double V_higher)\n{\n\treturn ((UID - U_lower) * (V_lower - V_higher)) - ((VID - V_lower) * (U_lower - U_higher));\n}\n#endif\n\nbool stability::GetSourceData(shared_ptr<info>& T850Info, shared_ptr<info>& T700Info, shared_ptr<info>& T500Info,\n                              shared_ptr<info>& TD850Info, shared_ptr<info>& TD700Info,\n                              const shared_ptr<info>& myTargetInfo, bool useCudaInThisThread)\n{\n\tbool ret = true;\n\n\tif (!T850Info)\n\t{\n\t\tT850Info = Fetch(myTargetInfo->Time(), P850Level, TParam, myTargetInfo->ForecastType(), useCudaInThisThread);\n\t}\n\n\tif (!T700Info)\n\t{\n\t\tT700Info = Fetch(myTargetInfo->Time(), P700Level, TParam, myTargetInfo->ForecastType(), useCudaInThisThread);\n\t}\n\n\tif (!T500Info)\n\t{\n\t\tT500Info = Fetch(myTargetInfo->Time(), P500Level, TParam, myTargetInfo->ForecastType(), useCudaInThisThread);\n\t}\n\n\tif (!TD850Info)\n\t{\n\t\tTD850Info = Fetch(myTargetInfo->Time(), P850Level, TDParam, myTargetInfo->ForecastType(), useCudaInThisThread);\n\t}\n\n\tif (!TD700Info)\n\t{\n\t\tTD700Info = Fetch(myTargetInfo->Time(), P700Level, TDParam, myTargetInfo->ForecastType(), useCudaInThisThread);\n\t}\n\n\tif (!T850Info || !T700Info || !T500Info || !TD850Info || !TD700Info)\n\t{\n\t\tret = false;\n\t}\n\n\treturn ret;\n}\n\nbool stability::GetLISourceData(const shared_ptr<info>& myTargetInfo, vector<double>& T500mVector,\n                                vector<double>& TD500mVector, vector<double>& P500mVector)\n{\n\tauto h = dynamic_pointer_cast<hitool>(plugin_factory::Instance()->Plugin(\"hitool\"));\n\n\th->Configuration(itsConfiguration);\n\th->Time(myTargetInfo->Time());\n\n// Fetch Z uncompressed since it is not transferred to cuda\n#if 0\n\tauto HInfo = Fetch(myTargetInfo->Time(), groundLevel, HParam, false);\n\n\tif (!HInfo)\n\t{\n\t\treturn false;\n\t}\n\n\n\tvector<double> H0mVector = HInfo->Grid()->Data().Values();\n\tvector<double> H500mVector(HInfo->SizeLocations());\n\n\tfor (size_t i = 0; i < H500mVector.size(); i++)\n\t{\n\t\t// H0mVector contains the height of ground (compared to MSL). Height can be negative\n\t\t// (maybe even in real life (Netherlands?)), but in our case we use 0 as smallest height.\n\t\t// TODO: check how it is in smarttools\n\n\t\tif (H0mVector[i] == kFloatMissing)\n\t\t{\n\t\t\tcontinue;\n\t\t}\n\t\t\n\t\tH0mVector[i] *= constants::kIg;\n\t\tH0mVector[i] = fmax(0, H0mVector[i]);\n\n\t\tH500mVector[i] = H0mVector[i] + 500.;\n\t}\n\n#endif\n\n\t// Fetch average values of T, TD and P over vertical height range 0 ... 500m OVER GROUND\n\n\tboost::thread t1(&T500mSearch, itsConfiguration, myTargetInfo->Time(), boost::ref(T500mVector));\n\tboost::thread t2(&TD500mSearch, itsConfiguration, myTargetInfo->Time(), boost::ref(TD500mVector));\n\n\tP500mVector = h->VerticalAverage(PParam, 0., 500.);\n\n\tassert(P500mVector[0] != kFloatMissing);\n\n\tif (P500mVector[0] < 1500)\n\t{\n\t\ttransform(P500mVector.begin(), P500mVector.end(), P500mVector.begin(),\n\t\t          bind1st(multiplies<double>(), 100));  // hPa to Pa\n\t}\n\n\tt1.join();\n\tt2.join();\n\n\treturn true;\n}\n\nbool stability::GetWindShearSourceData(const shared_ptr<info>& myTargetInfo, vector<double>& U01Vector,\n                                       vector<double>& V01Vector, vector<double>& U06Vector, vector<double>& V06Vector)\n{\n\tauto h = dynamic_pointer_cast<hitool>(plugin_factory::Instance()->Plugin(\"hitool\"));\n\n\th->Configuration(itsConfiguration);\n\th->Time(myTargetInfo->Time());\n\n\t// BS 0-6\n\tU06Vector = Shear(itsConfiguration, myTargetInfo->Time(), param(\"U-MS\"), 0, 6000);\n\tV06Vector = Shear(itsConfiguration, myTargetInfo->Time(), param(\"V-MS\"), 0, 6000);\n\n#ifdef DEBUG\n\tDumpVector(U06Vector);\n\tDumpVector(V06Vector);\n#endif\n\n\t// BS 0-1\n\n\tU01Vector = Shear(itsConfiguration, myTargetInfo->Time(), param(\"U-MS\"), 0, 1000);\n\tV01Vector = Shear(itsConfiguration, myTargetInfo->Time(), param(\"V-MS\"), 0, 1000);\n\n#ifdef DEBUG\n\tDumpVector(U01Vector);\n\tDumpVector(V01Vector);\n#endif\n\n\treturn true;\n}\n\nvector<double> Shear(shared_ptr<const plugin_configuration> conf, const forecast_time& ftime, const param& wantedParam,\n                     double lowerHeight, double upperHeight)\n{\n\tauto h = dynamic_pointer_cast<hitool>(plugin_factory::Instance()->Plugin(\"hitool\"));\n\n\tauto lowerValues = h->VerticalValue(wantedParam, lowerHeight);\n\tauto upperValues = h->VerticalValue(wantedParam, upperHeight);\n\n\tvector<double> ret(lowerValues.size(), kFloatMissing);\n\n#ifdef YES_WE_HAVE_GCC_WHICH_SUPPORTS_LAMBDAS\n\ttransform(lowerValues.begin(), lowerValues.end(), upperValues.begin(), back_inserter(U),\n\t          [](double l, double u) { return (u == kFloatMissing || l == kFloatMissing) ? kFloatMissing : u - l; });\n\ttransform(lowerValues.begin(), lowerValues.end(), upperValues.begin(), back_inserter(V),\n\t          [](double l, double u) { return (u == kFloatMissing || l == kFloatMissing) ? kFloatMissing : u - l; });\n#else\n\n\tfor (size_t i = 0; i < lowerValues.size(); i++)\n\t{\n\t\tdouble l = lowerValues[i];\n\t\tdouble u = upperValues[i];\n\n\t\tif (u == kFloatMissing || l == kFloatMissing)\n\t\t{\n\t\t\tcontinue;\n\t\t}\n\n\t\tret[i] = u - l;\n\t}\n#endif\n\n\treturn ret;\n}\n\nbool stability::GetSRHSourceData(const shared_ptr<info>& myTargetInfo, vector<double>& Uid, vector<double>& Vid)\n{\n\t// NOTES COPIED FROM SMARTTOOLS-LIBRARY\n\n\t/* // **********  SRH calculation help from Pieter Groenemeijer ******************\n\n\tSome tips here on how tyo calculate storm-relative helciity\n\n\tHow to calculate storm-relative helicity\n\n\tIntegrate the following from p = p_surface to p = p_top (or in case of height coordinates from h_surface to h_top):\n\n\tstorm_rel_helicity -= ((u_ID-u[p])*(v[p]-v[p+1]))-((v_ID - v[p])*(u[p]-u[p+1]));\n\n\tHere, u_ID and v_ID are the forecast storm motion vectors calculated with the so-called ID-method. These can be calculated as follows:\n\n\twhere\n\n\t/average wind\n\tu0_6 = average 0_6 kilometer u-wind component\n\tv0_6 = average 0_6 kilometer v-wind component\n\t(you should use a pressure-weighted average in case you work with height coordinates)\n\n\t/shear\n\tshr_0_6_u = u_6km - u_surface;\n\tshr_0_6_v = v_6km - v_surface;\n\n\t/ shear unit vector\n\tshr_0_6_u_n = shr_0_6_u / ((shr_0_6_u^2 + shr_0_6_v^2)**0.5);\n\tshr_0_6_v_n = shr_0_6_v / ((shr_0_6_u^2 + shr_0_6_v^2)** 0.5);\n\n\t/id-vector components\n\tu_ID = u0_6 + shr_0_6_v_n * 7.5;\n\tv_ID = v0_6 - shr_0_6_u_n * 7.5;\n\n\t(7.5 are meters per second... watch out when you work with knots instead)\n\n\t*/  // **********  SRH calculation help from Pieter Groenemeijer ******************\n\n\tauto h = dynamic_pointer_cast<hitool>(plugin_factory::Instance()->Plugin(\"hitool\"));\n\n\th->Configuration(itsConfiguration);\n\th->Time(myTargetInfo->Time());\n\n\t// average wind\n\tauto Uavg = h->VerticalAverage(param(\"U-MS\"), 0, 6000);\n\tauto Vavg = h->VerticalAverage(param(\"V-MS\"), 0, 6000);\n\n\t// shear\n\tauto Ushear = Shear(itsConfiguration, myTargetInfo->Time(), param(\"U-MS\"), 0, 6000);\n\tauto Vshear = Shear(itsConfiguration, myTargetInfo->Time(), param(\"V-MS\"), 0, 6000);\n\n\t// shear unit vectors\n\tUid.resize(Ushear.size(), kFloatMissing);\n\tVid.resize(Vshear.size(), kFloatMissing);\n\n\tassert(Uid.size() == Vid.size());\n\tassert(Uid.size() == Uavg.size());\n\n\tfor (size_t i = 0; i < Ushear.size(); i++)\n\t{\n\t\tdouble u = Ushear[i];\n\t\tdouble v = Vshear[i];\n\n\t\tif (u == kFloatMissing || v == kFloatMissing)\n\t\t{\n\t\t\tcontinue;\n\t\t}\n\n\t\tdouble Uunit = u / sqrt(u * u + v * v);\n\t\tdouble Vunit = v / sqrt(u * u + v * v);\n\n\t\tUid[i] = Uavg[i] - Vunit * 7.5;\n\t\tVid[i] = Vavg[i] - Uunit * 7.5;\n\t}\n\n\treturn true;\n}\n\n#ifdef DEBUG\nvoid DumpVector(const vector<double>& vec)\n{\n\tdouble min = 1e38, max = -1e38, sum = 0;\n\tsize_t count = 0, missing = 0;\n\n\tfor (double val : vec)\n\t{\n\t\tif (val == kFloatMissing)\n\t\t{\n\t\t\tmissing++;\n\t\t\tcontinue;\n\t\t}\n\n\t\tmin = (val < min) ? val : min;\n\t\tmax = (val > max) ? val : max;\n\t\tcount++;\n\t\tsum += val;\n\t}\n\n\tdouble mean = numeric_limits<double>::quiet_NaN();\n\n\tif (count > 0)\n\t{\n\t\tmean = sum / static_cast<double>(count);\n\t}\n\n\tcout << \"min \" << min << \" max \" << max << \" mean \" << mean << \" count \" << count << \" missing \" << missing << endl;\n}\n\n#endif\n", "meta": {"hexsha": "104d57d093f7abc4defbc1da48c5fbf397dd57d1", "size": 17838, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "himan-plugins/source/stability.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/stability.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/stability.cpp", "max_forks_repo_name": "jrintala/fmi-data", "max_forks_repo_head_hexsha": "625f0a44919e6406440349425ee0b3f1a64a923d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.0272727273, "max_line_length": 135, "alphanum_fraction": 0.6774302052, "num_tokens": 5344, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.679178699175393, "lm_q2_score": 0.4960938294709195, "lm_q1q2_score": 0.3369363617689983}}
{"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_FRUCHTERMAN_REINGOLD_FORCE_DIRECTED_LAYOUT_HPP\n#define BOOST_GRAPH_FRUCHTERMAN_REINGOLD_FORCE_DIRECTED_LAYOUT_HPP\n\n#include <boost/config/no_tr1/cmath.hpp>\n#include <boost/graph/graph_traits.hpp>\n#include <boost/graph/named_function_params.hpp>\n#include <boost/graph/simple_point.hpp>\n#include <vector>\n#include <list>\n#include <algorithm> // for std::min and std::max\n\nnamespace boost {\n\nstruct square_distance_attractive_force {\n  template<typename Graph, typename T>\n  T\n  operator()(typename graph_traits<Graph>::edge_descriptor,\n             T k,\n             T d,\n             const Graph&) const\n  {\n    return d * d / k;\n  }\n};\n\nstruct square_distance_repulsive_force {\n  template<typename Graph, typename T>\n  T\n  operator()(typename graph_traits<Graph>::vertex_descriptor,\n             typename graph_traits<Graph>::vertex_descriptor,\n             T k,\n             T d,\n             const Graph&) const\n  {\n    return k * k / d;\n  }\n};\n\ntemplate<typename T>\nstruct linear_cooling {\n  typedef T result_type;\n\n  linear_cooling(std::size_t iterations)\n    : temp(T(iterations) / T(10)), step(0.1) { }\n\n  linear_cooling(std::size_t iterations, T temp)\n    : temp(temp), step(temp / T(iterations)) { }\n\n  T operator()()\n  {\n    T old_temp = temp;\n    temp -= step;\n    if (temp < T(0)) temp = T(0);\n    return old_temp;\n  }\n\n private:\n  T temp;\n  T step;\n};\n\nstruct all_force_pairs\n{\n  template<typename Graph, typename ApplyForce >\n  void operator()(const Graph& g, ApplyForce apply_force)\n  {\n    typedef typename graph_traits<Graph>::vertex_iterator vertex_iterator;\n    vertex_iterator v, end;\n    for (tie(v, end) = vertices(g); v != end; ++v) {\n      vertex_iterator u = v;\n      for (++u; u != end; ++u) {\n        apply_force(*u, *v);\n        apply_force(*v, *u);\n      }\n    }\n  }\n};\n\ntemplate<typename Dim, typename PositionMap>\nstruct grid_force_pairs\n{\n  template<typename Graph>\n  explicit\n  grid_force_pairs(Dim width, Dim height, PositionMap position, const Graph& g)\n    : width(width), height(height), position(position)\n  {\n#ifndef BOOST_NO_STDC_NAMESPACE\n    using std::sqrt;\n#endif // BOOST_NO_STDC_NAMESPACE\n    two_k = Dim(2) * sqrt(width*height / num_vertices(g));\n  }\n\n  template<typename Graph, typename ApplyForce >\n  void operator()(const Graph& g, ApplyForce apply_force)\n  {\n    typedef typename graph_traits<Graph>::vertex_iterator vertex_iterator;\n    typedef typename graph_traits<Graph>::vertex_descriptor vertex_descriptor;\n    typedef std::list<vertex_descriptor> bucket_t;\n    typedef std::vector<bucket_t> buckets_t;\n\n    std::size_t columns = std::size_t(width / two_k + Dim(1));\n    std::size_t rows = std::size_t(height / two_k + Dim(1));\n    buckets_t buckets(rows * columns);\n    vertex_iterator v, v_end;\n    for (tie(v, v_end) = vertices(g); v != v_end; ++v) {\n      std::size_t column = std::size_t((position[*v].x + width  / 2) / two_k);\n      std::size_t row    = std::size_t((position[*v].y + height / 2) / two_k);\n\n      if (column >= columns) column = columns - 1;\n      if (row >= rows) row = rows - 1;\n      buckets[row * columns + column].push_back(*v);\n    }\n\n    for (std::size_t row = 0; row < rows; ++row)\n      for (std::size_t column = 0; column < columns; ++column) {\n        bucket_t& bucket = buckets[row * columns + column];\n        typedef typename bucket_t::iterator bucket_iterator;\n        for (bucket_iterator u = bucket.begin(); u != bucket.end(); ++u) {\n          // Repulse vertices in this bucket\n          bucket_iterator v = u;\n          for (++v; v != bucket.end(); ++v) {\n            apply_force(*u, *v);\n            apply_force(*v, *u);\n          }\n\n          std::size_t adj_start_row = row == 0? 0 : row - 1;\n          std::size_t adj_end_row = row == rows - 1? row : row + 1;\n          std::size_t adj_start_column = column == 0? 0 : column - 1;\n          std::size_t adj_end_column = column == columns - 1? column : column + 1;\n          for (std::size_t other_row = adj_start_row; other_row <= adj_end_row;\n               ++other_row)\n            for (std::size_t other_column = adj_start_column; \n                 other_column <= adj_end_column; ++other_column)\n              if (other_row != row || other_column != column) {\n                // Repulse vertices in this bucket\n                bucket_t& other_bucket \n                  = buckets[other_row * columns + other_column];\n                for (v = other_bucket.begin(); v != other_bucket.end(); ++v)\n                  apply_force(*u, *v);\n              }\n        }\n      }\n  }\n\n private:\n  Dim width;\n  Dim height;\n  PositionMap position;\n  Dim two_k;\n};\n\ntemplate<typename Dim, typename PositionMap, typename Graph>\ninline grid_force_pairs<Dim, PositionMap>\nmake_grid_force_pairs(Dim width, Dim height, const PositionMap& position,\n                      const Graph& g)\n{ return grid_force_pairs<Dim, PositionMap>(width, height, position, g); }\n\ntemplate<typename Graph, typename PositionMap, typename Dim>\nvoid\nscale_graph(const Graph& g, PositionMap position,\n            Dim left, Dim top, Dim right, Dim bottom)\n{\n  if (num_vertices(g) == 0) return;\n\n  if (bottom > top) {\n    using std::swap;\n    swap(bottom, top);\n  }\n\n  typedef typename graph_traits<Graph>::vertex_iterator vertex_iterator;\n\n  // Find min/max ranges\n  Dim minX = position[*vertices(g).first].x, maxX = minX;\n  Dim minY = position[*vertices(g).first].y, maxY = minY;\n  vertex_iterator vi, vi_end;\n  for (tie(vi, vi_end) = vertices(g); vi != vi_end; ++vi) {\n    BOOST_USING_STD_MIN();\n    BOOST_USING_STD_MAX();\n    minX = min BOOST_PREVENT_MACRO_SUBSTITUTION (minX, position[*vi].x);\n    maxX = max BOOST_PREVENT_MACRO_SUBSTITUTION (maxX, position[*vi].x);\n    minY = min BOOST_PREVENT_MACRO_SUBSTITUTION (minY, position[*vi].y);\n    maxY = max BOOST_PREVENT_MACRO_SUBSTITUTION (maxY, position[*vi].y);\n  }\n\n  // Scale to bounding box provided\n  for (tie(vi, vi_end) = vertices(g); vi != vi_end; ++vi) {\n    position[*vi].x = ((position[*vi].x - minX) / (maxX - minX))\n                    * (right - left) + left;\n    position[*vi].y = ((position[*vi].y - minY) / (maxY - minY))\n                    * (top - bottom) + bottom;\n  }\n}\n\nnamespace detail {\n  template<typename PositionMap, typename DisplacementMap,\n           typename RepulsiveForce, typename Dim, typename Graph>\n  struct fr_apply_force\n  {\n    typedef typename graph_traits<Graph>::vertex_descriptor vertex_descriptor;\n\n    fr_apply_force(const PositionMap& position,\n                   const DisplacementMap& displacement,\n                   RepulsiveForce repulsive_force, Dim k, const Graph& g)\n      : position(position), displacement(displacement),\n        repulsive_force(repulsive_force), k(k), g(g)\n    { }\n\n    void operator()(vertex_descriptor u, vertex_descriptor v)\n    {\n#ifndef BOOST_NO_STDC_NAMESPACE\n      using std::sqrt;\n#endif // BOOST_NO_STDC_NAMESPACE\n      if (u != v) {\n        Dim delta_x = position[v].x - position[u].x;\n        Dim delta_y = position[v].y - position[u].y;\n        Dim dist = sqrt(delta_x * delta_x + delta_y * delta_y);\n        Dim fr = repulsive_force(u, v, k, dist, g);\n        displacement[v].x += delta_x / dist * fr;\n        displacement[v].y += delta_y / dist * fr;\n      }\n    }\n\n  private:\n    PositionMap position;\n    DisplacementMap displacement;\n    RepulsiveForce repulsive_force;\n    Dim k;\n    const Graph& g;\n  };\n\n} // end namespace detail\n\ntemplate<typename Graph, typename PositionMap, typename Dim,\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  Dim             width,\n  Dim             height,\n  AttractiveForce attractive_force,\n  RepulsiveForce  repulsive_force,\n  ForcePairs      force_pairs,\n  Cooling         cool,\n  DisplacementMap displacement)\n{\n  typedef typename graph_traits<Graph>::vertex_iterator   vertex_iterator;\n  typedef typename graph_traits<Graph>::vertex_descriptor vertex_descriptor;\n  typedef typename graph_traits<Graph>::edge_iterator     edge_iterator;\n\n#ifndef BOOST_NO_STDC_NAMESPACE\n  using std::sqrt;\n#endif // BOOST_NO_STDC_NAMESPACE\n\n  Dim area = width * height;\n  // assume positions are initialized randomly\n  Dim k = sqrt(area / num_vertices(g));\n\n  detail::fr_apply_force<PositionMap, DisplacementMap,\n                         RepulsiveForce, Dim, Graph>\n    apply_force(position, displacement, repulsive_force, k, g);\n\n  Dim temp = cool();\n  if (temp) do {\n    // Calculate repulsive forces\n    vertex_iterator v, v_end;\n    for (tie(v, v_end) = vertices(g); v != v_end; ++v) {\n      displacement[*v].x = 0;\n      displacement[*v].y = 0;\n    }\n    force_pairs(g, apply_force);\n\n    // Calculate attractive forces\n    edge_iterator e, e_end;\n    for (tie(e, e_end) = edges(g); e != e_end; ++e) {\n      vertex_descriptor v = source(*e, g);\n      vertex_descriptor u = target(*e, g);\n      Dim delta_x = position[v].x - position[u].x;\n      Dim delta_y = position[v].y - position[u].y;\n      Dim dist = sqrt(delta_x * delta_x + delta_y * delta_y);\n      Dim fa = attractive_force(*e, k, dist, g);\n\n      displacement[v].x -= delta_x / dist * fa;\n      displacement[v].y -= delta_y / dist * fa;\n      displacement[u].x += delta_x / dist * fa;\n      displacement[u].y += delta_y / dist * fa;\n    }\n\n    // Update positions\n    for (tie(v, v_end) = vertices(g); v != v_end; ++v) {\n      BOOST_USING_STD_MIN();\n      BOOST_USING_STD_MAX();\n      Dim disp_size = sqrt(displacement[*v].x * displacement[*v].x\n                           + displacement[*v].y * displacement[*v].y);\n      position[*v].x += displacement[*v].x / disp_size \n                     * min BOOST_PREVENT_MACRO_SUBSTITUTION (disp_size, temp);\n      position[*v].y += displacement[*v].y / disp_size \n                     * min BOOST_PREVENT_MACRO_SUBSTITUTION (disp_size, temp);\n      position[*v].x = min BOOST_PREVENT_MACRO_SUBSTITUTION \n                         (width / 2, \n                          max BOOST_PREVENT_MACRO_SUBSTITUTION(-width / 2, \n                                                               position[*v].x));\n      position[*v].y = min BOOST_PREVENT_MACRO_SUBSTITUTION\n                         (height / 2, \n                          max BOOST_PREVENT_MACRO_SUBSTITUTION(-height / 2, \n                                                               position[*v].y));\n    }\n  } while (temp = cool());\n}\n\nnamespace detail {\n  template<typename DisplacementMap>\n  struct fr_force_directed_layout\n  {\n    template<typename Graph, typename PositionMap, typename Dim,\n             typename AttractiveForce, typename RepulsiveForce,\n             typename ForcePairs, typename Cooling,\n             typename Param, typename Tag, typename Rest>\n    static void\n    run(const Graph&    g,\n        PositionMap     position,\n        Dim             width,\n        Dim             height,\n        AttractiveForce attractive_force,\n        RepulsiveForce  repulsive_force,\n        ForcePairs      force_pairs,\n        Cooling         cool,\n        DisplacementMap displacement,\n        const bgl_named_params<Param, Tag, Rest>&)\n    {\n      fruchterman_reingold_force_directed_layout\n        (g, position, width, height, attractive_force, repulsive_force,\n         force_pairs, cool, displacement);\n    }\n  };\n\n  template<>\n  struct fr_force_directed_layout<error_property_not_found>\n  {\n    template<typename Graph, typename PositionMap, typename Dim,\n             typename AttractiveForce, typename RepulsiveForce,\n             typename ForcePairs, typename Cooling,\n             typename Param, typename Tag, typename Rest>\n    static void\n    run(const Graph&    g,\n        PositionMap     position,\n        Dim             width,\n        Dim             height,\n        AttractiveForce attractive_force,\n        RepulsiveForce  repulsive_force,\n        ForcePairs      force_pairs,\n        Cooling         cool,\n        error_property_not_found,\n        const bgl_named_params<Param, Tag, Rest>& params)\n    {\n      std::vector<simple_point<Dim> > displacements(num_vertices(g));\n      fruchterman_reingold_force_directed_layout\n        (g, position, width, height, attractive_force, repulsive_force,\n         force_pairs, cool,\n         make_iterator_property_map\n         (displacements.begin(),\n          choose_const_pmap(get_param(params, vertex_index), g,\n                            vertex_index),\n          simple_point<Dim>()));\n    }\n  };\n\n} // end namespace detail\n\ntemplate<typename Graph, typename PositionMap, typename Dim, typename Param,\n         typename Tag, typename Rest>\nvoid\nfruchterman_reingold_force_directed_layout\n  (const Graph&    g,\n   PositionMap     position,\n   Dim             width,\n   Dim             height,\n   const bgl_named_params<Param, Tag, Rest>& params)\n{\n  typedef typename property_value<bgl_named_params<Param,Tag,Rest>,\n                                  vertex_displacement_t>::type D;\n\n  detail::fr_force_directed_layout<D>::run\n    (g, position, width, height,\n     choose_param(get_param(params, attractive_force_t()),\n                  square_distance_attractive_force()),\n     choose_param(get_param(params, repulsive_force_t()),\n                  square_distance_repulsive_force()),\n     choose_param(get_param(params, force_pairs_t()),\n                  make_grid_force_pairs(width, height, position, g)),\n     choose_param(get_param(params, cooling_t()),\n                  linear_cooling<Dim>(100)),\n     get_param(params, vertex_displacement_t()),\n     params);\n}\n\ntemplate<typename Graph, typename PositionMap, typename Dim>\nvoid\nfruchterman_reingold_force_directed_layout(const Graph&    g,\n                                           PositionMap     position,\n                                           Dim             width,\n                                           Dim             height)\n{\n  fruchterman_reingold_force_directed_layout\n    (g, position, width, height,\n     attractive_force(square_distance_attractive_force()));\n}\n\n} // end namespace boost\n\n#endif // BOOST_GRAPH_FRUCHTERMAN_REINGOLD_FORCE_DIRECTED_LAYOUT_HPP\n", "meta": {"hexsha": "f5ea6af7b33075fbd5696f3c08f171d50e4aaea1", "size": 14431, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/boost/graph/fruchterman_reingold.hpp", "max_stars_repo_name": "cpmech/vismatrix", "max_stars_repo_head_hexsha": "a4994864d3592cfa2db24119427fad096303fb4f", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2018-12-06T00:55:34.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-06T03:05:51.000Z", "max_issues_repo_path": "src/boost/graph/fruchterman_reingold.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/graph/fruchterman_reingold.hpp", "max_forks_repo_name": "cpmech/vismatrix", "max_forks_repo_head_hexsha": "a4994864d3592cfa2db24119427fad096303fb4f", "max_forks_repo_licenses": ["BSD-3-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.2779097387, "max_line_length": 82, "alphanum_fraction": 0.628023006, "num_tokens": 3426, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6076631840431539, "lm_q2_score": 0.5544704649604274, "lm_q1q2_score": 0.3369312881957413}}
{"text": "/* Copyright (c) 2019, NVIDIA CORPORATION. All rights reserved.\n * \n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *  * Redistributions of source code must retain the above copyright\n *    notice, this list of conditions and the following disclaimer.\n *  * Redistributions in binary form must reproduce the above copyright\n *    notice, this list of conditions and the following disclaimer in the\n *    documentation and/or other materials provided with the distribution.\n *  * Neither the name of NVIDIA CORPORATION nor the names of its\n *    contributors may be used to endorse or promote products derived\n *    from this software without specific prior written permission.\n * \n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\n * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR\n * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY\n * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\n#include <boost/multiprecision/cpp_int.hpp>\n\n#include \"util/numeric.hpp\"\n\nusing namespace boost::multiprecision;\n\n//------------------------------------\n//              Factors\n//------------------------------------\n\nunsigned long Factors::ISqrt_(unsigned long x)\n{\n  register unsigned long op, res, one;\n\n  op = x;\n  res = 0;\n\n  one = 1 << 30;\n  while (one > op) one >>= 2;\n\n  while (one != 0)\n  {\n    if (op >= res + one)\n    {\n      op -= res + one;\n      res += one << 1;\n    }\n    res >>= 1;\n    one >>= 2;\n  }\n  return res;\n}\n\nvoid Factors::CalculateAllFactors_()\n{\n  all_factors_.clear();\n  for (unsigned long i = 1; i <= ISqrt_(n_); i++)\n  {\n    if (n_ % i == 0)\n    {\n      all_factors_.push_back(i);\n      if (i * i != n_)\n      {\n        all_factors_.push_back(n_ / i);\n      }\n    }\n  }\n}\n\n// Return a vector of all order-way cofactor sets of n.\nstd::vector<std::vector<unsigned long>>\nFactors::MultiplicativeSplitRecursive_(unsigned long n, int order)\n{\n  if (order == 0)\n  {\n    return {{}};\n  }\n  else if (order == 1)\n  {\n    return {{n}};\n  }\n  else\n  {\n    std::vector<std::vector<unsigned long>> retval;\n    for (auto factor = all_factors_.begin(); factor != all_factors_.end(); factor++)\n    {\n      // This factor is only acceptable if the residue is divisible by it.\n      if (n % (*factor) == 0)\n      {\n        // Recursive call.\n        std::vector<std::vector<unsigned long>> subproblem =\n          MultiplicativeSplitRecursive_(n / (*factor), order - 1);\n\n        // Append this factor to the end of each vector returned by the\n        // recursive call.\n        for (auto vector = subproblem.begin(); vector != subproblem.end(); vector++)\n        {\n          vector->push_back(*factor);\n        }\n\n        // Add all these appended vectors to my growing vector of vectors.\n        retval.insert(retval.end(), subproblem.begin(), subproblem.end());\n      }\n      else\n      {\n        // Discard this factor.\n      }\n    }\n    return retval;\n  }\n}\n\nFactors::Factors() :\n    n_(0)\n{\n}\n\nFactors::Factors(const unsigned long n, const int order) :\n    n_(n), cofactors_()\n{\n  CalculateAllFactors_();\n  cofactors_ = MultiplicativeSplitRecursive_(n, order);\n}\n\nFactors::Factors(const unsigned long n, const int order, std::map<unsigned, unsigned long> given) :\n    n_(n), cofactors_()\n{\n  assert(given.size() <= std::size_t(order));\n\n  // If any of the given factors is not a factor of n, forcibly reset that to\n  // be a free variable, otherwise accumulate them into a partial product.\n  unsigned long partial_product = 1;\n  for (auto f = given.begin(); f != given.end(); f++)\n  {\n    auto factor = f->second;\n    if (n % (factor * partial_product) == 0)\n    {\n      partial_product *= factor;\n    }\n    else\n    {\n      std::cerr << \"WARNING: cannot accept \" << factor << \" as a factor of \" << n\n                << \" with current partial product \" << partial_product;\n#define SET_NONFACTOR_TO_FREE_VARIABLE\n#ifdef SET_NONFACTOR_TO_FREE_VARIABLE\n      // Ignore mapping constraint and set the factor to a free variable.\n      std::cerr << \", ignoring mapping constraint and setting to a free variable.\"\n                << std::endl;\n      f = given.erase(f);\n#else       \n      // Try to find the next *lower* integer that is a factor of n.\n      // FIXME: there are multiple exceptions that can cause us to be here:\n      // (a) factor doesn't divide into n.\n      // (b) factor does divide into n but causes partial product to exceed n.\n      // (c) factor does divide into n but causes partial product to not\n      //     divide into n.\n      // The following code only solves case (a).\n      std::cerr << \"FIXME: please fix this code.\" << std::endl;\n      assert(false);\n        \n      for (; factor >= 1 && (n % factor != 0); factor--);\n      std::cerr << \", setting this to \" << factor << \" instead.\" << std::endl;\n      f->second = factor;\n      partial_product *= factor;\n#endif\n    }\n    assert(n % partial_product == 0);\n  }\n\n  CalculateAllFactors_();\n\n  cofactors_ = MultiplicativeSplitRecursive_(n / partial_product, order - given.size());\n\n  // Insert the given factors at the specified indices of each of the solutions.\n  for (auto& cofactors : cofactors_)\n  {\n    for (auto& given_factor : given)\n    {\n      // Insert the given factor, pushing all existing factors back.\n      auto index = given_factor.first;\n      auto value = given_factor.second;\n      assert(index <= cofactors.size());\n      cofactors.insert(cofactors.begin() + index, value);\n    }\n  }\n}\n\nvoid Factors::PruneMax(std::map<unsigned, unsigned long>& max)\n{\n  // Prune the vector of cofactor sets by removing those sets that have factors\n  // outside user-specified min/max range. We should really have done this during\n  // MultiplicativeSplitRecursive. However, the \"given\" map complicates things\n  // because given factors may be scattered, and we'll need a map table to\n  // find the original rank from the \"compressed\" rank seen by\n  // MultiplicativeSplitRecursive. Doing it now is slower but cleaner and less\n  // bug-prone.\n\n  auto cofactors_it = cofactors_.begin();\n  while (cofactors_it != cofactors_.end())\n  {\n    bool illegal = false;\n    for (auto& max_factor : max)\n    {\n      auto index = max_factor.first;\n      auto max = max_factor.second;\n      assert(index <= cofactors_it->size());\n      auto value = cofactors_it->at(index);\n      if (value > max)\n      {\n        illegal = true;\n        break;\n      }\n    }\n      \n    if (illegal)\n      cofactors_it = cofactors_.erase(cofactors_it);\n    else\n      cofactors_it++;\n  }\n}\n\nstd::vector<unsigned long>& Factors::operator[](int index)\n{\n  return cofactors_[index];\n}\n\nstd::size_t Factors::size()\n{\n  return cofactors_.size();\n}\n\nvoid Factors::Print()\n{\n  PrintAllFactors();\n  PrintCoFactors();\n}\n\nvoid Factors::PrintAllFactors()\n{\n  std::cout << \"All factors of \" << n_ << \": \";\n  bool first = true;\n  for (auto f = all_factors_.begin(); f != all_factors_.end(); f++)\n  {\n    if (first)\n    {\n      first = false;\n    }\n    else\n    {\n      std::cout << \", \";\n    }\n    std::cout << (*f);\n  }\n  std::cout << std::endl;\n}\n\nvoid Factors::PrintCoFactors()\n{\n  std::cout << *this;\n}\n\nstd::ostream& operator<<(std::ostream& out, const Factors& f)\n{\n  out << \"Co-factors of \" << f.n_ << \" are: \" << std::endl;\n  for (auto cset = f.cofactors_.begin(); cset != f.cofactors_.end(); cset++)\n  {\n    out << \"    \" << f.n_ << \" = \";\n    bool first = true;\n    for (auto i = cset->begin(); i != cset->end(); i++)\n    {\n      if (first)\n      {\n        first = false;\n      }\n      else\n      {\n        out << \" * \";\n      }\n      out << (*i);\n    }\n    out << std::endl;\n  }\n  return out;\n}\n//------------------------------------\n//              ResidualFactors\n//------------------------------------\n\n\nunsigned long ResidualFactors::ISqrt_(unsigned long x)\n{\n  unsigned long op, res, one;\n\n  op = x;\n  res = 0;\n\n  one = 1 << 30;\n  while (one > op) one >>= 2;\n\n  while (one != 0)\n  {\n    if (op >= res + one)\n    {\n      op -= res + one;\n      res += one << 1;\n    }\n    res >>= 1;\n    one >>= 2;\n  }\n  return res;\n}\n\nvoid ResidualFactors::ClearAllFactors_()\n{\n  all_factors_.clear();\n}\nvoid ResidualFactors::CalculateAllFactors_()\n{\n  for (unsigned long i = 1; i <= ISqrt_(n_); i++)\n  {\n    if (n_ % i == 0)\n    {\n      all_factors_.insert(i);\n      if (i * i != n_)\n      {\n        all_factors_.insert(n_ / i);\n      }\n    }\n  }\n}\n\n\n// Generate all additional potential factors given the remainder bounds  \nvoid ResidualFactors::CalculateAdditionalFactors_()\n{\n  std::vector<unsigned long> reaminder_possible; \n  for (auto& n : remainder_bounds_){\n    for(unsigned long i = 1; i <= n; i++)\n      reaminder_possible.push_back(i);\n  }\n\n  for (auto& n : reaminder_possible){\n    unsigned long g = n * n_ * ceil((double)n_/(double)n);\n    for (unsigned long i = 1; i <= n_; i++)\n    {\n      if (g % i == 0)\n      {\n        if (i < n_)\n        all_factors_.insert(i);\n        if (i * i != g)\n        {\n          if ((g/i) < n_)\n          all_factors_.insert(g / i);\n        }\n      }\n    }\n  }\n}\n\nstd::vector<std::vector<unsigned long>> ResidualFactors::CartProduct_ (const std::vector<std::vector<unsigned long>> v) {\n  std::vector<std::vector<unsigned long>> s = {{}};\n  for (const auto u : v) {\n      std::vector<std::vector<unsigned long>> r;\n      for (const auto x : s) {\n          for (const auto y : u) {\n              r.push_back(x);\n              r.back().push_back(y);\n          }\n      }\n      s = r;\n  }\n  return s;\n}\n\n// Replicate all factors possibilities accross each level n, disregarding sets with that include more than dimension size n * sqrt(n)\nvoid ResidualFactors::GenerateFactorProduct_(const unsigned long n, const int order)\n{\n  for(auto rec = 0; rec < order; rec++){\n    std::vector<std::vector<unsigned long>> inter_factors;\n    std::vector<std::vector<unsigned long>> product_factors;\n    for (auto i = 0; i < order; i++)\n    {\n      std::vector<unsigned long> v2;\n      for(auto a : all_factors_){\n        if (i == 0 && rec == 0){\n          v2.push_back(a);\n        }else if(a <= ((unsigned int)(pow((double)n_, 1.0/(2.0)) + 1.5)) && i > 0){\n          v2.push_back(a);\n        }else if (rec > 0 && i == 0 && a >= ((unsigned int)(pow((double)n_, 1.0/(2.0)) + 1.5))){\n          v2.push_back(a);\n        }\n      }\n      inter_factors.push_back(v2);\n    }\n\n    std::swap(inter_factors[0], inter_factors[rec]);\n\n    product_factors = CartProduct_(inter_factors);\n    replicated_factors_.reserve(replicated_factors_.size() + product_factors.size());\n    replicated_factors_.insert(replicated_factors_.end(), product_factors.begin(), product_factors.end());\n  }\n\n\n\n  for(auto t : replicated_factors_){\n\n      unsigned long product = 1;\n      for(auto p : t){\n        if (p != 1){\n          product *= (p-1);\n        }\n      }\n      if (product <= n){\n          pruned_product_factors_.push_back(t);\n      }\n  }\n  \n\n}\n\n// Replicate all possible residual combiniations, and remove possibilities that sum up to size greater than n\nvoid ResidualFactors::GenerateResidual_(const unsigned long n, const int order)\n{\n  std::vector<std::vector<unsigned long>> residuals;\n\n  for (auto i : remainder_bounds_){\n    std::vector<unsigned long> r;\n    for (unsigned j = 1; j <= i; j++){\n      r.push_back(j);\n    }\n    residuals.push_back(r);\n  }\n\n  residuals = CartProduct_(residuals);\n\n  for(auto t : residuals){\n    unsigned long sum = 0;\n    for(auto p : t){\n      sum += p;\n    }\n    if(sum <= n+(unsigned)order){\n      pruned_residuals_.push_back(t);\n    }\n  }\n\n}\n\n// Replicate all possible residual combiniations, and remove possibilities that sum up to size greater than n\nvoid ResidualFactors::ValidityChecker_(const unsigned long n, std::map<unsigned, unsigned long> given)\n{\n\n  for (unsigned i = pruned_product_factors_.size(); i > 0 ; i--)\n  {\n\n\n    for (auto it = given.begin(); it != given.end(); it++)\n    {\n      // Insert the given factor, pushing all existing factors back.\n      auto index = it->first;\n      auto value = it->second;\n      pruned_product_factors_[i-1].insert(pruned_product_factors_[i-1].begin() + index, value);\n    }\n\n\n  }\n  \n\n  for(auto f : pruned_product_factors_){\n    for(auto r : pruned_residuals_){\n      std::vector<unsigned long> valid_residuals;\n      int s_i = 0;\n      bool valid = true;\n      for(unsigned long i = 0; i < (f.size()); i++){\n        if(std::count(remainder_ix_.begin(),remainder_ix_.end(), i) > 0){\n          valid_residuals.push_back(r.at(s_i));\n          \n          if(f.at(i) > remainder_bounds_[s_i]){\n            valid = false;\n          }\n          s_i++;\n        }else{\n          valid_residuals.push_back(f.at(i));\n        }\n      }\n\n      //Solve for generic is L_{n} = L{n+1}*P{n} + R_{n} - 1\n      unsigned long equation_answer = 0;\n      for(unsigned j = (f.size()); j > 0; j--){ \n          equation_answer = f.at(j-1)*equation_answer + (valid_residuals.at(j-1) - 1);\n      \n          if (f.at(j-1) < valid_residuals.at(j-1))\n            valid = false;\n          if(equation_answer == 0 && valid_residuals.at(j-1) != f.at(j-1))\n            valid = false;\n        }\n\n        if ((equation_answer + 1 == n) and valid){\n\n          cofactors_.push_back(f);\n          rfactors_.push_back(valid_residuals);\n\n      }\n    }\n  }\n\n\n}\n\nvoid ResidualFactors::PruneMax()\n{\n  // Prune the vector of cofactor sets by removing those sets that have factors\n  // outside user-specified min/max range. We should really have done this during\n  // MultiplicativeSplitRecursive. However, the \"given\" map complicates things\n  // because given factors may be scattered, and we'll need a map table to\n  // find the original rank from the \"compressed\" rank seen by\n  // MultiplicativeSplitRecursive. Doing it now is slower but cleaner and less\n  // bug-prone.\n\n}\n\nResidualFactors::ResidualFactors() : n_(0) {}\n\n/***\nFirst, we cacluate all the factors same as Uber\nNext, we add in additional factors based on user defined loop bounds and take the cross product of these (eliminating impossible mappings)\nThen, we calculate all the valid mapspace points that fit the expanded formula L_{n} = L{n+1}*P{n} + R_{n} - 1\n***/\nResidualFactors::ResidualFactors(const unsigned long n, const int order, std::vector<unsigned long> remainder_bounds, \n    std::vector<unsigned long> remainder_ix) : n_(n), remainder_bounds_(remainder_bounds), remainder_ix_(remainder_ix)\n{\n  ClearAllFactors_();\n  CalculateAllFactors_();\n  CalculateAdditionalFactors_();\n  GenerateFactorProduct_(n, order);\n  GenerateResidual_(n, order);\n  std::map<unsigned, unsigned long> given = {{}};\n  ValidityChecker_(n, given);\n\n  for (unsigned i = 0; i < cofactors_.size(); i++)\n  {\n    std::reverse(cofactors_[i].begin(), cofactors_[i].end());\n    std::reverse(rfactors_[i].begin(), rfactors_[i].end());\n  }\n}\n\nResidualFactors::ResidualFactors(const unsigned long n, const int order, std::vector<unsigned long> remainder_bounds, \n    std::vector<unsigned long> remainder_ix, std::map<unsigned, unsigned long> given)\n    : n_(n), remainder_bounds_(remainder_bounds), remainder_ix_(remainder_ix)\n{\n\n  const unsigned int given_size = given.size();\n\n  assert(given_size <= std::size_t(order));\n  // If any of the given factors is not a factor of n, forcibly reset that to\n  // be a free variable, otherwise accumulate them into a partial product.\n  unsigned long partial_product = 1;\n  for (auto f = given.begin(); f != given.end(); f++)\n  {\n    auto factor = f->second;\n    if (n % (factor * partial_product) == 0)\n    {\n      partial_product *= factor;\n    }\n    else\n    {\n      std::cerr << \"WARNING: cannot accept \" << factor << \" as a factor of \" << n\n                << \" with current partial product \" << partial_product;\n#define SET_NONFACTOR_TO_FREE_VARIABLE\n#ifdef SET_NONFACTOR_TO_FREE_VARIABLE\n      // Ignore mapping constraint and set the factor to a free variable.\n      std::cerr << \", ignoring mapping constraint and setting to a free variable.\"\n                << std::endl;\n      f = given.erase(f);\n#else       \n      // Try to find the next *lower* integer that is a factor of n.\n      // FIXME: there are multiple exceptions that can cause us to be here:\n      // (a) factor doesn't divide into n.\n      // (b) factor does divide into n but causes partial product to exceed n.\n      // (c) factor does divide into n but causes partial product to not\n      //     divide into n.\n      // The following code only solves case (a).\n      std::cerr << \"FIXME: please fix this code.\" << std::endl;\n      assert(false);\n      \n      for (; factor >= 1 && (n % factor != 0); factor--);\n      std::cerr << \", setting this to \" << factor << \" instead.\" << std::endl;\n      f->second = factor;\n      partial_product *= factor;\n#endif\n    }\n    assert(n % partial_product == 0);\n  }\n\n  ClearAllFactors_();\n  CalculateAllFactors_();\n  CalculateAdditionalFactors_();\n\n\n\n  GenerateFactorProduct_(n / partial_product, order - given.size());\n\n  GenerateResidual_(n / partial_product, order - given.size());\n  \n\n\n  // Insert the given factors at the specified indices of each of the solutions.\n\n  ValidityChecker_(n, given);\n\n  remainder_bounds_.resize(0);\n  remainder_ix_.resize(0);\n  pruned_product_factors_.resize(0);\n  pruned_residuals_.resize(0);\n  replicated_factors_.resize(0);\n\n}\n\nstd::vector<std::vector<unsigned long>> ResidualFactors::operator[](int index)\n{\n  std::vector<std::vector<unsigned long>> ret;\n  std::vector<unsigned long> cfm = cofactors_.at(index);\n  std::vector<unsigned long> rfm = rfactors_.at(index);\n\n  ret.push_back(cfm);\n  ret.push_back(rfm);\n  return ret;\n}\n\nstd::size_t ResidualFactors::size() { return cofactors_.size(); }\n\n\nvoid ResidualFactors::Print()\n{\n  PrintAllFactors();\n  PrintCoFactors();\n}\n\nvoid ResidualFactors::PrintAllFactors()\n{\n  std::cout << \"All factors of \" << n_ << \": \";\n  bool first = true;\n  for (auto f = all_factors_.begin(); f != all_factors_.end(); f++) {\n    if (first) {\n      first = false;\n    } else {\n      std::cout << \", \";\n    }\n    std::cout << (*f);\n  }\n  std::cout << std::endl;\n}\n\nvoid ResidualFactors::PrintCoFactors() { std::cout << *this; }\n\nstd::ostream& operator<<(std::ostream& out, const ResidualFactors& f) {\n  out << \"Co-factors of \" << f.n_ << \" are: \" << std::endl;\n  for (auto cset = f.cofactors_.begin(); cset != f.cofactors_.end(); cset++) {\n    out << \"    \" << f.n_ << \" = \";\n    bool first = true;\n    for (auto i = cset->begin(); i != cset->end(); i++) {\n      if (first) {\n        first = false;\n      } else {\n        out << \" * \";\n      }\n      out << (*i);\n    }\n    out << std::endl;\n  }\n  return out;\n}\n\n\n//------------------------------------\n//        PatternGenerator128\n//------------------------------------\n\nPatternGenerator128::PatternGenerator128(uint128_t bound) :\n    bound_(bound)\n{\n}\n\nSequenceGenerator128::SequenceGenerator128(uint128_t bound, bool autoloop) :\n    PatternGenerator128(bound),\n    autoloop_(autoloop),\n    cur_(0)\n{\n}\n\nuint128_t SequenceGenerator128::Next()\n{\n  auto retval = cur_;\n  if (cur_ == bound_-1)\n  {\n    assert(autoloop_);\n    cur_ = 0;\n  }\n  else\n  {\n    cur_++;\n  }\n  return retval;\n}\n\n\nRandomGenerator128::RandomGenerator128(uint128_t bound) :\n    PatternGenerator128(bound),\n    use_two_generators_(bound > uint128_t(uint64_max_)),\n    low_gen_(0, use_two_generators_ ? uint64_max_ : (std::uint64_t)(bound - 1)),\n    high_gen_(0, (std::uint64_t)(bound/uint64_max_ - 1))\n{\n}\n\nuint128_t RandomGenerator128::Next()\n{\n  std::uint64_t low = low_gen_(engine_);\n  std::uint64_t high = 0;\n    \n  if (use_two_generators_)\n  {\n    high = high_gen_(engine_);\n  }\n\n  uint128_t rand = low + ((uint128_t)high * uint64_max_);\n  assert(rand < bound_);\n    \n  return rand;\n}\n\n\n//------------------------------------\n//           Miscellaneous\n//------------------------------------\n\n// Returns the smallest factor of an integer and the quotient after\n// division with the smallest factor.\nvoid SmallestFactor(uint64_t n, uint64_t& factor, uint64_t& residue)\n{\n  for (uint64_t i = 2; i < n; i++)\n  {\n    if (n % i == 0)\n    {\n      factor = i;\n      residue = n / i;\n      return;\n    }\n  }\n  factor = n;\n  residue = 1;\n}\n\n// Helper function to get close-to-square layouts of arrays\n// containing a given number of nodes.\nvoid GetTiling(uint64_t num_elems, uint64_t& height, uint64_t& width)\n{\n  std::vector<uint64_t> factors;\n  uint64_t residue = num_elems;\n  uint64_t cur_factor;\n  while (residue > 1)\n  {\n    SmallestFactor(residue, cur_factor, residue);\n    factors.push_back(cur_factor);\n  }\n\n  height = 1;\n  width = 1;\n  for (uint64_t i = 0; i < factors.size(); i++)\n  {\n    if (i % 2 == 0)\n      height *= factors[i];\n    else\n      width *= factors[i];\n  }\n\n  if (height > width)\n  {\n    uint64_t temp = height;\n    height = width;\n    width = temp;\n  }\n}\n\ndouble LinearInterpolate(double x,\n                         double x0, double x1,\n                         double q0, double q1)\n{\n  double slope = (x0 == x1) ? 0 : (q1 - q0) / double(x1 - x0);\n  return q0 + slope * (x - x0);\n}\n\ndouble BilinearInterpolate(double x, double y,\n                           double x0, double x1,\n                           double y0, double y1,\n                           double q00, double q01, double q10, double q11)\n{\n  // Linear interpolate along x dimension.\n  double qx0 = LinearInterpolate(x, x0, x1, q00, q10);\n  double qx1 = LinearInterpolate(x, x0, x1, q01, q11);\n\n  // Linear interpolate along y dimension.\n  return LinearInterpolate(y, y0, y1, qx0, qx1);\n}\n", "meta": {"hexsha": "c294e0a43495f8f462f25dabe6f9d712f1d6d7b4", "size": 22035, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/util/numeric.cpp", "max_stars_repo_name": "MarkHoreni/timeloop", "max_stars_repo_head_hexsha": "f98754e2f61fb1e9ac04db91283813c91a4c815f", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/util/numeric.cpp", "max_issues_repo_name": "MarkHoreni/timeloop", "max_issues_repo_head_hexsha": "f98754e2f61fb1e9ac04db91283813c91a4c815f", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/util/numeric.cpp", "max_forks_repo_name": "MarkHoreni/timeloop", "max_forks_repo_head_hexsha": "f98754e2f61fb1e9ac04db91283813c91a4c815f", "max_forks_repo_licenses": ["BSD-3-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.2037037037, "max_line_length": 138, "alphanum_fraction": 0.6084864988, "num_tokens": 5729, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6076631556226292, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.3369312724373997}}
{"text": "﻿/*******************************************************************\r\nAuthor: David Ge (dge893@gmail.com, aka Wei Ge)\r\nLast modified: 11/16/2020\r\nAllrights reserved by David Ge\r\n\r\nfield source\r\n********************************************************************/\r\n#include \"FieldSourceTss.h\"\r\n#include \"TimeTssBase.h\"\r\n\r\n#include <boost/multiprecision/cpp_dec_float.hpp>\r\n\r\n#define ih(i, h) ((h)*eMax+(i))\r\n\r\nFieldSourceTss::FieldSourceTss()\r\n{\r\n\tf0 = g0 = w0 = u0 = NULL;\r\n\t_initialized = false;\r\n}\r\n\r\n\r\nFieldSourceTss::~FieldSourceTss()\r\n{\r\n\tcleanup();\r\n}\r\n\r\nvoid FieldSourceTss::cleanup()\r\n{\r\n\tif (f0 != NULL)\r\n\t{\r\n\t\tfree(f0); f0 = NULL;\r\n\t}\r\n\tif (g0 != NULL)\r\n\t{\r\n\t\tfree(g0); g0 = NULL;\r\n\t}\r\n\tif (w0 != NULL)\r\n\t{\r\n\t\tfree(w0); w0 = NULL;\r\n\t}\r\n\tif (u0 != NULL)\r\n\t{\r\n\t\tfree(u0); u0 = NULL;\r\n\t}\r\n}\r\n\r\nint FieldSourceTss::initialize(SimStruct *params)\r\n{\r\n\tint ret = ERR_OK;\r\n\t//size_t emMax2;\r\n\tsize_t srcDim2;\r\n\tcleanup();\r\n\tpams = params;\r\n\tnx1 = pams->nx + 1; ny1 = pams->ny + 1; nz1 = pams->nz + 1;\r\n\temMax = 2 * pams->kmax + 3;\r\n\t//emMax2 = emMax * emMax;\r\n\tsrcDim = 2 * pams->kmax + 1;\r\n\tsrcDim2 = srcDim * srcDim;\r\n\tf0 = (double *)malloc(srcDim2*sizeof(double));\r\n\tg0 = (double *)malloc(srcDim2*sizeof(double));\r\n\tw0 = (double *)malloc(srcDim2*sizeof(double));\r\n\tu0 = (double *)malloc(srcDim2*sizeof(double));\r\n\tif (f0 == NULL || g0 == NULL || w0 == NULL || u0 == NULL)\r\n\t{\r\n\t\tret = ERR_OUTOFMEMORY;\r\n\t}\r\n\telse\r\n\t{\r\n\t\tfor (unsigned int k = 0; k < srcDim2; k++)\r\n\t\t{\r\n\t\t\tf0[k] = g0[k] = w0[k] = u0[k] = 0.0;\r\n\t\t}\r\n\t\t\r\n\t}\r\n\t_initialized = true;\r\n\treturn ret;\r\n}\r\n\r\n/*\r\n\tcalculate field fource coefficients\r\n*/\r\nint FieldSourceTss::onInitialized(void *e0, void *m0)\r\n{\r\n\tusing namespace boost::multiprecision;\r\n\tint ret = ERR_OK;\r\n\tsize_t srcDim2 = srcDim * srcDim;\r\n\tcpp_dec_float_100 *f  = (cpp_dec_float_100 *)malloc(srcDim2*sizeof(cpp_dec_float_100));\r\n\tcpp_dec_float_100 *g  = (cpp_dec_float_100 *)malloc(srcDim2*sizeof(cpp_dec_float_100));\r\n\tcpp_dec_float_100 *w  = (cpp_dec_float_100 *)malloc(srcDim2*sizeof(cpp_dec_float_100));\r\n\tcpp_dec_float_100 *u  = (cpp_dec_float_100 *)malloc(srcDim2*sizeof(cpp_dec_float_100));\r\n\tcpp_dec_float_100 *f2 = (cpp_dec_float_100 *)malloc(srcDim2*sizeof(cpp_dec_float_100));\r\n\tcpp_dec_float_100 *g2 = (cpp_dec_float_100 *)malloc(srcDim2*sizeof(cpp_dec_float_100));\r\n\tcpp_dec_float_100 *w2 = (cpp_dec_float_100 *)malloc(srcDim2*sizeof(cpp_dec_float_100));\r\n\tcpp_dec_float_100 *u2 = (cpp_dec_float_100 *)malloc(srcDim2*sizeof(cpp_dec_float_100));\r\n\tcpp_dec_float_100 *f1 = (cpp_dec_float_100 *)malloc(srcDim2*sizeof(cpp_dec_float_100));\r\n\tcpp_dec_float_100 *g1 = (cpp_dec_float_100 *)malloc(srcDim2*sizeof(cpp_dec_float_100));\r\n\tcpp_dec_float_100 *w1 = (cpp_dec_float_100 *)malloc(srcDim2*sizeof(cpp_dec_float_100));\r\n\tcpp_dec_float_100 *u1 = (cpp_dec_float_100 *)malloc(srcDim2*sizeof(cpp_dec_float_100));\r\n\t//\r\n\tcpp_dec_float_100 *sr = (cpp_dec_float_100 *)malloc((emMax + 2)*sizeof(cpp_dec_float_100));\r\n\tif (sr == NULL || f == NULL || g == NULL || w == NULL || u == NULL \r\n\t\t|| f1 == NULL || g1 == NULL || w1 == NULL || u1 == NULL\r\n\t\t|| f2 == NULL || g2 == NULL || w2 == NULL || u2 == NULL)\r\n\t\tret = ERR_OUTOFMEMORY;\r\n\telse\r\n\t{\r\n\t\tcpp_dec_float_100 *e = (cpp_dec_float_100 *)e0;\r\n\t\tcpp_dec_float_100 *m = (cpp_dec_float_100 *)m0;\r\n\t\tfor (unsigned int k = 0; k < srcDim2; k++)\r\n\t\t{\r\n\t\t\tf[k]  = 0.0; g[k]  = 0.0; w[k]  = 0.0; u[k]  = 0.0;\r\n\t\t}\r\n\t\tcpp_dec_float_100 XN = 1.0;\r\n\t\tcpp_dec_float_100 X = 0.0;\r\n\t\tcpp_dec_float_100 dtN = 1.0;\r\n\t\t//sr[k] = (∆_t^k)/ k!\r\n\t\tfor (unsigned int k = 0; k < emMax + 2; k++)\r\n\t\t{\r\n\t\t\tsr[k] = dtN / XN;\r\n\t\t\tX += 1.0;\r\n\t\t\tXN = XN * X;\r\n\t\t\tdtN = dtN * pams->dt;\r\n\t\t}\r\n\t\t/*\r\n\t\tS_m (2k+1)=∑_(h=0)^k▒〖∇^{2(k-h)} ×∑_(i=0)^2h▒〖m_i^{2(k-h)}   (d^(2h-i) J_m)/(dt^(2h-i) )〗〗\r\n\t\t\t      +∑_(h=0)^(k-1)▒〖∇^{2(k-h)-1} ×∑_(i=0)^(2h+1)▒〖e_i^{2(k-h)-1}   (d^(2h-i+1) J_e)/(dt^(2h-i+1) )〗〗\r\n\t\tS_e (2k+1)=∑_(h=0)^k▒〖∇^{2(k-h)} ×∑_(i=0)^2h▒〖e_i^{2(k-h)}   (d^(2h-i) J_e)/(dt^(2h-i) )〗〗\r\n\t\t\t      +∑_(h=0)^(k-1)▒〖∇^{2(k-h)-1} ×∑_(i=0)^(2h+1)▒〖m_i^{2(k-h)-1}   (d^(2h-i+1) J_m)/(dt^(2h-i+1) )〗〗\r\n\t\tS_m (2k)  =∑_(h=0)^(k-1)▒(∇^{2(k-1-h)} ×∑_(i=0)^(2h+1)▒〖m_i^{2(k-1-h)}   (d^(2h+1-i) J_m)/(dt^(2h+1-i) )〗\r\n\t\t\t\t  +∇^{2(k-h)-1} ×∑_(i=0)^2h▒〖e_i^{2(k-h)-1}   (d^(2h-i) J_e)/(dt^(2h-i) )〗)\r\n\t\tS_e (2k)  =∑_(h=0)^(k-1)▒(∇^{2(k-1-h)} ×∑_(i=0)^(2h+1)▒〖e_i^{2(k-1-h)}   (d^(2h+1-i) J_e)/(dt^(2h+1-i) )〗\r\n\t\t\t\t  +∇^{2(k-h)-1} ×∑_(i=0)^2h▒〖m_i^{2(k-h)-1}   (d^(2h-i) J_m)/(dt^(2h-i) )〗)\r\n\r\n\t\tS^h (k,∆_t)=(∆_t^2k)/(2k)! S_m (2k) + (∆_t^(2k+1))/(2k+1)! S_m (2k+1)\r\n\t\tS^e (k,∆_t)=(∆_t^2k)/(2k)! S_e (2k) + (∆_t^(2k+1))/(2k+1)! S_e (2k+1)\r\n\r\n\t\tSH=∑_(k=0)^(k_max)▒〖S^h (k,∆_t ) 〗-> get f and g -> C.F.dJm + C.G.dJe\r\n\t\tSE=∑_(k=0)^(k_max)▒〖S^e (k,∆_t ) 〗-> get u and w -> C.U.dJe + C.W.dJm\r\n\r\n\t\tS_m (2k)   -> f2, g2;  S_m (2k+1) -> f1, g1;\r\n\t\tS_e (2k)   -> u2, w2;  S_e (2k+1) -> u1, w1\r\n\t\tf = sr[2k]*f2 + sr[2k+1]*f1; g = sr[2k]*g2 + sr[2k+1]*g1\r\n\t\tu = sr[2k]*u2 + sr[2k+1]*u1; w = sr[2k]*w2 + sr[2k+1]*w1\r\n\t\t*/\r\n\t\tsize_t t,t1=0;\r\n\t\tunsigned int kmax = pams->kmax;\r\n\t\tt = 0;\r\n\t\tfor (unsigned int k = 0; k <= kmax; k++)\r\n\t\t{\r\n\t\t\t//temporary summation holders\r\n\t\t\tfor (t = 0; t < srcDim2; t++)\r\n\t\t\t{\r\n\t\t\t\tf1[t] = 0.0; g1[t] = 0.0; w1[t] = 0.0; u1[t] = 0.0;\r\n\t\t\t\tf2[t] = 0.0; g2[t] = 0.0; w2[t] = 0.0; u2[t] = 0.0;\r\n\t\t\t}\r\n\t\t\t//H = C.F.dJm + C.G.dJe + ...\r\n\t\t\t//E = C.U.dJe + C.W.dJm + ...\r\n\t\t\tfor (unsigned int h = 0; h <= k; h++)\r\n\t\t\t{\r\n\t\t\t\t//first part of S_m (2k+1)->f1:Jm, S_e (2k+1)->u1:Je\r\n\t\t\t\t//∇^{2(k-h)} -> row number 0...2kmax\r\n\t\t\t\tfor (unsigned int i = 0; i <= 2 * h; i++)\r\n\t\t\t\t{\r\n\t\t\t\t\t//d^(2h-i), column number 2 * h - i \r\n\t\t\t\t\tt = Sr_ih(2 * h - i, 2 * (k - h));  //0...2kmax, 0...,2kmax\r\n\t\t\t\t\tt1 = I_ih(i, 2 * (k - h)); //m_i^{2(k-h)}, e_i^{2(k-h)}\r\n\t\t\t\t\tf1[t] += m[t1];\r\n\t\t\t\t\tu1[t] += e[t1];\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tfor (unsigned int h = 0; h < k; h++)\r\n\t\t\t{\r\n\t\t\t\tfor (unsigned int i = 0; i <= 2 * h + 1; i++)\r\n\t\t\t\t{\r\n\t\t\t\t\t//second part of S_m (2k+1)->g1:Je, S_e (2k+1)->w1:Jm\r\n\t\t\t\t\t//∇^{2(k-h)-1} ->row number\r\n\t\t\t\t\t//column number 2h-i+1\r\n\t\t\t\t\tt = Sr_ih(2 * h - i + 1, 2 * (k - h) - 1);\r\n\t\t\t\t\tt1 = I_ih(i, 2 * (k - h) - 1); //e_i^{2(k-h)-1}, m_i^{2(k-h)-1}\r\n\t\t\t\t\tg1[t] += e[t1];\r\n\t\t\t\t\tw1[t] += m[t1];\r\n\t\t\t\t\t//first part of S_m (2k)->f2:Jm, S_e (2k)->u2:Je\r\n\t\t\t\t\t//∇^{2(k-1-h)} -> row number; column number d^(2h+1-i)\r\n\t\t\t\t\tt = Sr_ih(2 * h + 1 - i, 2 * (k - 1 - h));\r\n\t\t\t\t\tt1 = I_ih(i, 2 * (k - 1 - h)); //m_i^{2(k-1-h)}, e_i^{2(k-1-h)}\r\n\t\t\t\t\tf2[t] += m[t1];\r\n\t\t\t\t\tu2[t] += e[t1];\r\n\t\t\t\t}\r\n\t\t\t\t//second part of  S_m (2k)->g2:Je, S_e (2k)->w2:Jm\r\n\t\t\t\t//∇^{2(k-h)-1} -> row number; column number d^(2h-i)\r\n\t\t\t\tfor (unsigned int i = 0; i <= 2 * h; i++)\r\n\t\t\t\t{\r\n\t\t\t\t\tt = Sr_ih(2 * h - i, 2 * (k - h) - 1);\r\n\t\t\t\t\tt1 = I_ih(i, 2 * (k - h) - 1); //e_i^{2(k-h)-1}, m_i^{2(k-h)-1}\r\n\t\t\t\t\tg2[t] += e[t1];\r\n\t\t\t\t\tw2[t] += m[t1];\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\t//add to the results\r\n\t\t\tfor (t = 0; t < srcDim2; t++)\r\n\t\t\t{\r\n\t\t\t\tf[t] += f2[t] * sr[2 * k] + f1[t] * sr[2 * k + 1];\r\n\t\t\t\tg[t] += g2[t] * sr[2 * k] + g1[t] * sr[2 * k + 1];\r\n\t\t\t\tu[t] += u2[t] * sr[2 * k] + u1[t] * sr[2 * k + 1];\r\n\t\t\t\tw[t] += w2[t] * sr[2 * k] + w1[t] * sr[2 * k + 1];\r\n\t\t\t}\r\n\t\t}\r\n\t\t//convert to double\r\n\t\tfor (t = 0; t < srcDim2; t++)\r\n\t\t{\r\n\t\t\tf0[t] = f[t].convert_to<double>();\r\n\t\t\tg0[t] = g[t].convert_to<double>();\r\n\t\t\tw0[t] = w[t].convert_to<double>();\r\n\t\t\tu0[t] = u[t].convert_to<double>();\r\n\t\t}\r\n\t}\r\n\tif(f != NULL) free(f); \r\n\tif(g != NULL) free(g);\r\n\tif(w != NULL) free(w);\r\n\tif(u != NULL) free(u);\r\n\t//\r\n\tif (f1 != NULL) free(f1);\r\n\tif (g1 != NULL) free(g1);\r\n\tif (w1 != NULL) free(w1);\r\n\tif (u1 != NULL) free(u1);\r\n\t//\r\n\tif (f2 != NULL) free(f2);\r\n\tif (g2 != NULL) free(g2);\r\n\tif (w2 != NULL) free(w2);\r\n\tif (u2 != NULL) free(u2);\r\n\t//\r\n\tif(sr != NULL) free(sr);\r\n\treturn ret;\r\n}\r\n\r\nint FieldSourceTss::applySourceToFields(TimeTssBase *timeModule)\r\n{\r\n\tif (timeModule->FieldType() == Field_type_3D)\r\n\t{\r\n\t\treturn applySources(timeModule->GetTimeValue(), timeModule->GetTimeIndex(), timeModule->GetFieldE(), timeModule->GetFieldH());\r\n\t}\r\n\telse if (timeModule->FieldType() == Field_type_z_rotateSymmetry)\r\n\t{\r\n\t\treturn applyToZrotateSymmetry(timeModule->GetTimeValue(), timeModule->GetTimeIndex(), timeModule->GetFieldZrotateSymmetryE(), timeModule->GetFieldZrotateSymmetryH());\r\n\t}\r\n\telse\r\n\t{\r\n\t\treturn ERR_SOURCE_NOT_SUPPORT;\r\n\t}\r\n}", "meta": {"hexsha": "5dc13b23061412f5ec3b4474199ff1a085ad3e11", "size": 8237, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Source Code V2/Tss/FieldSourceTss.cpp", "max_stars_repo_name": "DavidGeUSA/TSS", "max_stars_repo_head_hexsha": "e364e324948c68efc6362a0db3aa51696227fa60", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 11.0, "max_stars_repo_stars_event_min_datetime": "2020-09-27T07:35:22.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-09T11:01:31.000Z", "max_issues_repo_path": "Source Code V2/Tss/FieldSourceTss.cpp", "max_issues_repo_name": "DavidGeUSA/TSS", "max_issues_repo_head_hexsha": "e364e324948c68efc6362a0db3aa51696227fa60", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-10-28T13:14:58.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-28T21:04:44.000Z", "max_forks_repo_path": "Source Code V2/Tss/FieldSourceTss.cpp", "max_forks_repo_name": "DavidGeUSA/TSS", "max_forks_repo_head_hexsha": "e364e324948c68efc6362a0db3aa51696227fa60", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2020-09-27T07:35:24.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-02T13:53:21.000Z", "avg_line_length": 32.948, "max_line_length": 169, "alphanum_fraction": 0.5169357776, "num_tokens": 3621, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7690802476562643, "lm_q2_score": 0.4378234991142019, "lm_q1q2_score": 0.3367214051284826}}
{"text": "#include <utility>\n#include <iostream>\n#include <algorithm>\n#include <functional>\n\n#include <boost/range/adaptor/filtered.hpp>\n#include <boost/range/algorithm/set_algorithm.hpp>\n\ntemplate<class D, class S>\ntemplate<class Functor, class Iterator>\nvoid\ndionysus::Rips<D,S>::\ngenerate(Dimension k, DistanceType max, const Functor& f, Iterator bg, Iterator end) const\n{\n    auto neighbor = [this, max](Vertex u, Vertex v) { return this->distances()(u,v) <= max; };\n\n    // current      = empty\n    // candidates   = everything\n    VertexContainer current;\n    VertexContainer candidates(bg, end);\n    bron_kerbosch(current, candidates, std::prev(candidates.begin()), k, neighbor, f);\n}\n\ntemplate<class D, class S>\ntemplate<class Functor, class Iterator>\nvoid\ndionysus::Rips<D,S>::\nvertex_cofaces(IndexType v, Dimension k, DistanceType max, const Functor& f, Iterator bg, Iterator end) const\n{\n    auto neighbor = [this, max](Vertex u, Vertex v) { return this->distances()(u,v) <= max; };\n\n    // current      = [v]\n    // candidates   = everything - [v]\n    VertexContainer current; current.push_back(v);\n    VertexContainer candidates;\n    for (Iterator cur = bg; cur != end; ++cur)\n        if (*cur != v && neighbor(v, *cur))\n            candidates.push_back(*cur);\n\n    bron_kerbosch(current, candidates, std::prev(candidates.begin()), k, neighbor, f);\n}\n\ntemplate<class D, class S>\ntemplate<class Functor, class Iterator>\nvoid\ndionysus::Rips<D,S>::\nedge_cofaces(IndexType u, IndexType v, Dimension k, DistanceType max, const Functor& f, Iterator bg, Iterator end) const\n{\n    auto neighbor = [this, max](Vertex u, Vertex v) { return this->distances()(u,v) <= max; };\n\n    // current      = [u,v]\n    // candidates   = everything - [u,v]\n    VertexContainer current; current.push_back(u); current.push_back(v);\n\n    VertexContainer candidates;\n    for (Iterator cur = bg; cur != end; ++cur)\n        if (*cur != u && *cur != v && neighbor(v,*cur) && neighbor(u,*cur))\n            candidates.push_back(*cur);\n\n    bron_kerbosch(current, candidates, std::prev(candidates.begin()), k, neighbor, f);\n}\n\ntemplate<class D, class S>\ntemplate<class Functor, class Iterator>\nvoid\ndionysus::Rips<D,S>::\ncofaces(const Simplex& s, Dimension k, DistanceType max, const Functor& f, Iterator bg, Iterator end) const\n{\n    namespace ba = boost::adaptors;\n\n    auto neighbor = [this, max](Vertex u, Vertex v) { return this->distances()(u,v) <= max; };\n\n    // current      = s\n    VertexContainer current(s.begin(), s.end());\n\n    // candidates   = everything - s     that is a neighbor of every vertex in the simplex\n    VertexContainer candidates;\n    boost::set_difference(std::make_pair(bg, end) |\n                                ba::filtered([this,&s,&neighbor](Vertex cur)\n                                             { for (auto& v : s)\n                                                   if (!neighbor(v, cur))\n                                                       return false;\n                                             }),\n                          s,\n                          std::back_inserter(candidates));\n\n    bron_kerbosch(current, candidates, std::prev(candidates.begin()), k, neighbor, f, false);\n}\n\n\ntemplate<class D, class S>\ntemplate<class Functor, class NeighborTest>\nvoid\ndionysus::Rips<D,S>::\nbron_kerbosch(VertexContainer&                          current,\n              const VertexContainer&                    candidates,\n              typename VertexContainer::const_iterator  excluded,\n              Dimension                                 max_dim,\n              const NeighborTest&                       neighbor,\n              const Functor&                            functor,\n              bool                                      check_initial)\n{\n    if (check_initial && !current.empty())\n        functor(Simplex(current));\n\n    if (current.size() == static_cast<size_t>(max_dim) + 1)\n        return;\n\n    for (auto cur = std::next(excluded); cur != candidates.end(); ++cur)\n    {\n        current.push_back(*cur);\n\n        VertexContainer new_candidates;\n        for (auto ccur = candidates.begin(); ccur != cur; ++ccur)\n            if (neighbor(*ccur, *cur))\n                new_candidates.push_back(*ccur);\n        size_t ex = new_candidates.size();\n        for (auto ccur = std::next(cur); ccur != candidates.end(); ++ccur)\n            if (neighbor(*ccur, *cur))\n                new_candidates.push_back(*ccur);\n        excluded  = new_candidates.begin() + (ex - 1);\n\n        bron_kerbosch(current, new_candidates, excluded, max_dim, neighbor, functor);\n        current.pop_back();\n    }\n}\n\ntemplate<class Distances_, class Simplex_>\ntypename dionysus::Rips<Distances_, Simplex_>::DistanceType\ndionysus::Rips<Distances_, Simplex_>::\ndistance(const Simplex& s1, const Simplex& s2) const\n{\n    DistanceType mx = 0;\n    for (auto a : s1)\n        for (auto b : s2)\n            mx = std::max(mx, distances_(a,b));\n    return mx;\n}\n\ntemplate<class Distances_, class Simplex_>\ntypename dionysus::Rips<Distances_, Simplex_>::DistanceType\ndionysus::Rips<Distances_, Simplex_>::\nmax_distance() const\n{\n    DistanceType mx = 0;\n    for (IndexType a = distances_.begin(); a != distances_.end(); ++a)\n        for (IndexType b = std::next(a); b != distances_.end(); ++b)\n            mx = std::max(mx, distances_(a,b));\n    return mx;\n}\n\ntemplate<class Distances_, class Simplex_>\ntypename dionysus::Rips<Distances_, Simplex_>::DistanceType\ndionysus::Rips<Distances_, Simplex_>::Evaluator::\noperator()(const Simplex& s) const\n{\n    DistanceType mx = 0;\n    for (auto a = s.begin(); a != s.end(); ++a)\n        for (auto b = std::next(a); b != s.end(); ++b)\n            mx = std::max(mx, distances_(*a,*b));\n    return mx;\n}\n", "meta": {"hexsha": "2fdda34a7afb36b805638a66a4aaabf2a26521e1", "size": 5735, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/dionysus/rips.hpp", "max_stars_repo_name": "dlm/dionysus", "max_stars_repo_head_hexsha": "f7768668c6820adb1d49db291270ae3a99e14d18", "max_stars_repo_licenses": ["BSD-3-Clause-LBNL"], "max_stars_count": 114.0, "max_stars_repo_stars_event_min_datetime": "2017-07-19T21:43:20.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T07:54:11.000Z", "max_issues_repo_path": "include/dionysus/rips.hpp", "max_issues_repo_name": "dlm/dionysus", "max_issues_repo_head_hexsha": "f7768668c6820adb1d49db291270ae3a99e14d18", "max_issues_repo_licenses": ["BSD-3-Clause-LBNL"], "max_issues_count": 50.0, "max_issues_repo_issues_event_min_datetime": "2017-07-19T21:39:56.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-02T17:40:19.000Z", "max_forks_repo_path": "include/dionysus/rips.hpp", "max_forks_repo_name": "dlm/dionysus", "max_forks_repo_head_hexsha": "f7768668c6820adb1d49db291270ae3a99e14d18", "max_forks_repo_licenses": ["BSD-3-Clause-LBNL"], "max_forks_count": 27.0, "max_forks_repo_forks_event_min_datetime": "2017-08-17T17:11:49.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-21T09:59:57.000Z", "avg_line_length": 35.1840490798, "max_line_length": 120, "alphanum_fraction": 0.5968613775, "num_tokens": 1407, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6113819732941511, "lm_q2_score": 0.5506073655352404, "lm_q1q2_score": 0.3366314176512292}}
{"text": "/**\n * @file solver.hpp\n * @author Paul Kirth\n * @date 3/20/15\n */\n\n#ifndef _SOLVER_HPP_\n#define _SOLVER_HPP_\n\n#include <string>\n#include <fstream>\n#include <algorithm>\n#include <boost/dynamic_bitset.hpp>\n\nstruct node {\n  size_t count;\n  size_t id;\n  bool val;\n};\n\nstruct clause {\n  int a;\n  int b;\n};\n\nstruct solution {\n  boost::dynamic_bitset<> ans;\n  int value;\n  solution(size_t size = 0, int val = 0) : ans(size) { value = val; };\n  solution(boost::dynamic_bitset<> bs, int val = 0) : ans(bs), value(val) {}\n};\n\n/**\n * Finds solutions for MAX 2 SAT instances\n * has exact solution, and approximate solutions\n *\n */\nclass solver {\npublic:\n  solver(std::string file);\n\n  solution exact();\n  solution approx();\n  void reset()\n  {\n    x.reset();\n  }\n\nprivate:\n  boost::dynamic_bitset<> x;\n  std::vector<clause> clauses;\n  std::vector<node> nodes;\n\n  inline bool check(const clause &c) noexcept {\n    bool a;\n    bool b;\n    int ida = abs(c.a), idb = abs(c.b);\n    a = (c.a > 0) ? x[ida] : !x[ida];\n    b = (c.b > 0) ? x[idb] : !x[idb];\n    return a || b;\n  }\n\n  void increment(boost::dynamic_bitset<> &bitset) {\n    auto len = std::max(bitset.size(), (size_t)1);\n    // printf(\"count:%d\\nlen:  %d\\n\", bitset.count(), len);\n    for (int loop = 0; loop < len; ++loop) {\n      if ((bitset[loop] ^= 0x1) == 0x1) {\n        break;\n      }\n    }\n  }\n\n}; // end class solver\n\n#endif // end solver.hpp\n", "meta": {"hexsha": "a18a9acfd3c5580119a1a00769873b258f76a6e9", "size": 1394, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/solver.hpp", "max_stars_repo_name": "ilovepi/max2sat", "max_stars_repo_head_hexsha": "9fce087dc8af17c853e2e691059ca69ff072df1f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/solver.hpp", "max_issues_repo_name": "ilovepi/max2sat", "max_issues_repo_head_hexsha": "9fce087dc8af17c853e2e691059ca69ff072df1f", "max_issues_repo_licenses": ["MIT"], "max_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.hpp", "max_forks_repo_name": "ilovepi/max2sat", "max_forks_repo_head_hexsha": "9fce087dc8af17c853e2e691059ca69ff072df1f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 18.3421052632, "max_line_length": 76, "alphanum_fraction": 0.5911047346, "num_tokens": 433, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.3366314176512292}}
{"text": "//\n//  common.hpp\n//  Elasticity\n//\n//  Created by Wim van Rees on 2/15/16.\n//  Copyright © 2016 Wim van Rees. All rights reserved.\n//\n\n#ifndef common_hpp\n#define common_hpp\n\n#include <iostream>\n#include <cassert>\n#include <random>\n#include <limits>\n#include <utility>\n#include <vector>\n#include <string>\n#include <fstream>\n#include <iomanip>\n#include <sstream>\n#include <map>\n#include <algorithm>\n#include <chrono>\n#include <cmath>\n#include <array>\n#include <set>\n#include <memory>\n\n#include <Eigen/Dense>\n#include <Eigen/Sparse>\n#include <Eigen/StdVector>\n\n//#include \"ArgumentParser.h\"\n\ntypedef double Real;\ntypedef unsigned long long tUint;\ntypedef std::vector<Eigen::Matrix2d, Eigen::aligned_allocator<Eigen::Matrix2d>> tVecMat2d;\ntypedef std::vector<Eigen::Matrix3d, Eigen::aligned_allocator<Eigen::Matrix3d>> tVecMat3d;\nenum MeshLayer {single, bottom, top};\n\n//#define USETANTHETA\n\n// little helper to avoid unused warnings when something is called in release mode and variable only checked in debug\n#define _unused(x) ((void)(x))\n\nnamespace rnd\n{\n    /*! global random number generator */    \n    static std::mt19937 gen;\n}\n\n\nnamespace helpers\n{\n    \n    /*! convert an integer to a string with a specified number of zeros */\n    inline std::string ToString(int value,int digitsCount)\n    {\n        std::ostringstream os;\n        os<<std::setfill('0')<<std::setw(digitsCount)<<value;\n        return os.str();\n    }\n    \n    /*! check if two numbers are close (within some accuracy) */\n    inline bool isclose(const Real val1, const Real val2, const bool printOnly=false, const Real rtol=1e-5, const Real atol=1e-8)\n    {\n        const Real diff = std::abs(val1-val2) ;\n        bool retval = true;\n        if(diff > (atol + rtol * std::abs(val2)))\n            retval = false;\n        if(diff > (atol + rtol * std::abs(val1)))\n            retval = false;\n\n        if(printOnly && not retval)\n        {\n            std::cout << \"PROBLEM : \" << val1 << \"\\t\" << val2 << \"\\t\" << diff << std::endl;\n            retval = true;\n        }\n        \n        return retval;\n    }\n \n    \n    inline bool isPointInProjectedTriangle(const Real x, const Real y, const Eigen::Vector3d & v0, const Eigen::Vector3d & v1, const Eigen::Vector3d & v2)\n    {\n        // dont use the third dimension\n        const Real xp[3] = {v0(0),v1(0),v2(0)};\n        const Real yp[3] = {v0(1),v1(1),v2(1)};\n        \n        const int npoly = 3; // triangle \n        \n        int i,j,c=0;\n        for (i = 0, j = npoly-1; i < npoly; j = i++) {\n            if ((((yp[i] <= y) && (y < yp[j])) ||\n                 ((yp[j] <= y) && (y < yp[i]))) &&\n                (x < (xp[j] - xp[i]) * (y - yp[i]) / (yp[j] - yp[i]) + xp[i]))\n                c = !c;\n        }\n        return c;\n    }\n    \n    inline Eigen::Vector3d getBaryCentricWeights2D(const Eigen::Vector3d & v0, const Eigen::Vector3d & v1, const Eigen::Vector3d & v2, const Real x, const Real y)\n    {\n        assert(isPointInProjectedTriangle(x, y, v0, v1, v2));\n        \n        Eigen::Vector3d me;\n        me << x, y, 0;\n        // compute my point in barycentric coordinates of undeformed configuration\n        // Compute barycentric coordinates (u, v, w) for\n        // point p with respect to triangle (a, b, c)\n        // http://gamedev.stackexchange.com/questions/23743/whats-the-most-efficient-way-to-find-barycentric-coordinates\n        const Eigen::Vector3d tmp0 = v1 - v0;\n        const Eigen::Vector3d tmp1 = v2 - v0;\n        const Eigen::Vector3d tmp2 = me - v0;\n        const Real d00 = tmp0.dot(tmp0);\n        const Real d01 = tmp0.dot(tmp1);\n        const Real d11 = tmp1.dot(tmp1);\n        const Real d20 = tmp2.dot(tmp0);\n        const Real d21 = tmp2.dot(tmp1);\n        const Real denom = d00 * d11 - d01 * d01;\n        const Real lambda1 = (d11 * d20 - d01 * d21) / denom;\n        const Real lambda2 = (d00 * d21 - d01 * d20) / denom;\n        const Real lambda0 = 1.0 - lambda1 - lambda2;\n        // if me == v0 --> lambda0 = 1\n        // if me == v1 --> lambda1 = 1\n        // if me == v2 --> lambda2 = 1\n        \n        Eigen::Vector3d retval;\n        retval << lambda0, lambda1, lambda2;\n        return retval;\n    }\n    \n    template<int component>\n    inline Real getDisplacementOfPointInRestTriangle(const Eigen::Vector3d & rv0, const Eigen::Vector3d & rv1, const Eigen::Vector3d & rv2, const Eigen::Vector3d & v0, const Eigen::Vector3d & v1, const Eigen::Vector3d & v2, const Real x, const Real y)\n    {\n\n        const Eigen::Vector3d lambdas = getBaryCentricWeights2D(rv0, rv1, rv2, x, y);\n        \n        const Real displ_0 = (v0 - rv0)(component);\n        const Real displ_1 = (v1 - rv1)(component);\n        const Real displ_2 = (v2 - rv2)(component);\n        \n        // get my displacement\n        return -(lambdas(0)*displ_0 + lambdas(1)*displ_1 + lambdas(2)*displ_2);\n    }\n    \n    \n    inline Real interpolateOverTriangle(const Eigen::Vector3d & v0, const Eigen::Vector3d & v1, const Eigen::Vector3d & v2, const Real x, const Real y)\n    {\n        // linear interpolation over the triangle\n        const Real A = v0(1)*(v1(2)-v2(2)) + v1(1)*(v2(2)-v0(2)) + v2(1)*(v0(2)-v1(2));\n        const Real B = v0(2)*(v1(0)-v2(0)) + v1(2)*(v2(0)-v0(0)) + v2(2)*(v0(0)-v1(0));\n        const Real C = v0(0)*(v1(1)-v2(1)) + v1(0)*(v2(1)-v0(1)) + v2(0)*(v0(1)-v1(1));\n        const Real D = v0(0)*(v1(1)*v2(2)-v1(2)*v2(1)) + v1(0)*(v2(1)*v0(2)-v2(2)*v0(1)) + v2(0)*(v0(1)*v1(2)-v0(2)*v1(1));\n        \n        const Real ptZ = (D-A*x-B*y)/C;\n\n        return ptZ;\n    }\n    \n    inline Real computeDistanceToLineSegment(const Eigen::Vector2d & l1, const Eigen::Vector2d & l2, const Eigen::Vector2d & pt)\n    {\n        //http://stackoverflow.com/questions/849211/shortest-distance-between-a-point-and-a-line-segment\n        const Real Lsq = (l1-l2).squaredNorm();\n        if(Lsq < std::numeric_limits<Real>::epsilon())\n            return (l1-pt).norm();\n        \n        const Real t =  std::max(0.0, std::min(1.0, (pt-l1).dot(l2-l1) / Lsq));\n        const Eigen::Vector2d projection = l1 + t * (l2 - l1);\n        return (projection - pt).norm();\n    }\n    \n    inline int getIntersectionPointBetweenVectors(const Eigen::Vector2d & pt1, const Eigen::Vector2d & n1, const Eigen::Vector2d & pt2, const Eigen::Vector2d & n2, Eigen::Vector2d & result)\n    {\n        // return 0 if intersection is found\n        // return 1 if an intersection is found, but beyond the extent of pt1+n1 and pt2+n2\n        // return 2 if no intersection is found (parallel vectors)\n        \n        const Eigen::Vector2d n1_hat = n1.normalized();\n        const Eigen::Vector2d n2_hat = n2.normalized();\n        \n        const Real pt1_vec1 = pt1.dot(n1_hat);\n        const Real pt1_vec2 = pt1.dot(n2_hat);\n        const Real pt2_vec1 = pt2.dot(n1_hat);\n        const Real pt2_vec2 = pt2.dot(n2_hat);\n        const Real vec1_vec2 = n1_hat.dot(n2_hat);\n        \n        // deal with orthogonal\n        if(std::abs(vec1_vec2 - 1) < std::numeric_limits<Real>::epsilon())\n        {\n            if((pt1-pt2).norm()  < std::numeric_limits<Real>::epsilon())\n            {\n                result = pt1;\n                return 0;\n            }\n            else\n            {\n                return 2;\n            }\n        }\n        \n        const Real beta1 = (pt2_vec1 + (pt1_vec2 - pt2_vec2) * vec1_vec2 - pt1_vec1) / (1.0 - std::pow(vec1_vec2,2));\n        const Real beta2 = (pt1_vec2 + (pt2_vec1 - pt1_vec1) * vec1_vec2 - pt2_vec2) / (1.0 - std::pow(vec1_vec2,2));\n        \n        //const Eigen::Vector2d retval1 = pt1 + beta1*n1_hat;\n        const Eigen::Vector2d retval2 = pt2 + beta2*n2_hat;\n        \n        // set the intersection point\n        result = retval2;\n        \n        const bool inRange_1 = (beta1 >= 0 && beta1 <= n1.norm());\n        const bool inRange_2 = (beta2 >= 0 && beta2 <= n2.norm());\n        return (inRange_1 && inRange_2) ? 0 : 1;\n    }\n    \n    inline std::string removeExtension(const std::string input, const std::string extension)\n    {\n        // remove extension from input. Assume extension is given as (eg) .vtp (including the period)\n        // if not found, return input unaltered\n        const std::size_t found_ext = input.rfind(extension);\n        const std::string output = (found_ext != std::string::npos ? input.substr(0, found_ext) : input);\n        return output;\n    }\n    \n    inline void catastrophe(std::string s, const char* file, const int line, const bool isFatal=true)    // write ``error: s and exit program\n    {\n        std::cerr << \"Something went wrong, error: \" << s << std::endl;\n        std::cerr << \"Called from file : \" << file << \" at line number \" << line << std::endl;\n        if(isFatal)\n        {\n            std::cout << \"Exiting...\" << std::endl;\n            std::exit(1);\n        }\n    }\n    \n    template<class Matrix>\n    inline void write_matrix_binary(const std::string & filename, const Matrix& matrix)\n    {\n        // from https://stackoverflow.com/a/25389481\n        std::ofstream out(filename, std::ios::out | std::ios::binary | std::ios::trunc);\n        typename Matrix::Index rows=matrix.rows(), cols=matrix.cols();\n        out.write((char*) (&rows), sizeof(typename Matrix::Index));\n        out.write((char*) (&cols), sizeof(typename Matrix::Index));\n        out.write((char*) matrix.data(), rows*cols*sizeof(typename Matrix::Scalar) );\n        out.close();\n    }\n    \n    template<class Matrix>\n    inline void read_matrix_binary(const std::string & filename, Matrix& matrix)\n    {\n        // from https://stackoverflow.com/a/25389481\n        std::ifstream in(filename, std::ios::in | std::ios::binary);\n        typename Matrix::Index rows=0, cols=0;\n        in.read((char*) (&rows),sizeof(typename Matrix::Index));\n        in.read((char*) (&cols),sizeof(typename Matrix::Index));\n        matrix.resize(rows, cols);\n        in.read( (char *) matrix.data() , rows*cols*sizeof(typename Matrix::Scalar) );\n        in.close();\n    }\n    \n    template<class Matrix>\n    inline void write_vecmat_binary(const std::string & filename, const std::vector<Matrix, Eigen::aligned_allocator<Matrix>> & vecmat)\n    {\n        // from https://stackoverflow.com/a/25389481\n        std::ofstream out(filename, std::ios::out | std::ios::binary | std::ios::trunc);\n        const size_t vecsize = vecmat.size();\n        if(vecsize==0) return;\n        typename Matrix::Index rows=vecmat[0].rows(), cols=vecmat[0].cols();\n        out.write((char*) &vecsize, sizeof(vecsize));\n        out.write((char*) (&rows), sizeof(typename Matrix::Index));\n        out.write((char*) (&cols), sizeof(typename Matrix::Index));\n        out.write((char*)&vecmat[0], vecsize * rows*cols*sizeof(typename Matrix::Scalar));\n        out.close();\n    }\n    \n    template<class Matrix>\n    inline void read_vecmat_binary(const std::string & filename, std::vector<Matrix, Eigen::aligned_allocator<Matrix>> & vecmat)\n    {\n        std::ifstream in(filename, std::ios::in | std::ios::binary);\n        size_t vecsize = 0;\n        typename Matrix::Index rows=0, cols=0;\n        \n        in.read((char*) (&vecsize),sizeof(vecsize));\n        assert(vecsize > 0);\n        \n        in.read((char*) (&rows),sizeof(typename Matrix::Index));\n        in.read((char*) (&cols),sizeof(typename Matrix::Index));\n        \n        assert(rows == Matrix::RowsAtCompileTime);\n        assert(cols == Matrix::ColsAtCompileTime);\n        \n        vecmat.resize(vecsize);\n        in.read( (char *) &vecmat[0] , vecsize * rows*cols*sizeof(typename Matrix::Scalar) );\n        in.close();\n    }\n}\n\nnamespace Eigen\n{\n    /*! typedef vector of booleans */\n    typedef Matrix<bool, 3, 1> Vector3b;\n    \n    /*! typedef vector of booleans */\n    typedef Matrix<bool, Dynamic, 1> VectorXb;\n    typedef Matrix<bool, Dynamic, Dynamic> MatrixXb;\n}\n\n#endif /* common_hpp */\n", "meta": {"hexsha": "eda78e6c1a8c84945195b2938227472db4f8f7ec", "size": 11795, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/libshell/common.hpp", "max_stars_repo_name": "mvlab/growth_SM2018", "max_stars_repo_head_hexsha": "3ad411c4f7082e7bffc2ed3ea9bc96b9a51da73a", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2019-09-05T16:05:59.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-01T10:30:15.000Z", "max_issues_repo_path": "src/libshell/common.hpp", "max_issues_repo_name": "mvlab/growth_SM2018", "max_issues_repo_head_hexsha": "3ad411c4f7082e7bffc2ed3ea9bc96b9a51da73a", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-01-08T17:13:39.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-15T17:11:53.000Z", "max_forks_repo_path": "src/libshell/common.hpp", "max_forks_repo_name": "mvlab/growth_SM2018", "max_forks_repo_head_hexsha": "3ad411c4f7082e7bffc2ed3ea9bc96b9a51da73a", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2020-04-13T13:01:04.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-09T17:03:02.000Z", "avg_line_length": 38.0483870968, "max_line_length": 251, "alphanum_fraction": 0.5850784231, "num_tokens": 3365, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6334102636778401, "lm_q2_score": 0.5312093733737563, "lm_q1q2_score": 0.3364734692568112}}
{"text": "///////////////////////////////////////////////////////////////////////////////\r\n// weighted_tail_variate_means.hpp\r\n//\r\n//  Copyright 2006 Daniel Egloff, Olivier Gygi. Distributed under the Boost\r\n//  Software License, Version 1.0. (See accompanying file\r\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\r\n\r\n#ifndef BOOST_ACCUMULATORS_STATISTICS_WEIGHTED_TAIL_VARIATE_MEANS_HPP_DE_01_01_2006\r\n#define BOOST_ACCUMULATORS_STATISTICS_WEIGHTED_TAIL_VARIATE_MEANS_HPP_DE_01_01_2006\r\n\r\n#include <numeric>\r\n#include <vector>\r\n#include <limits>\r\n#include <functional>\r\n#include <sstream>\r\n#include <stdexcept>\r\n#include <boost/throw_exception.hpp>\r\n#include <boost/parameter/keyword.hpp>\r\n#include <boost/mpl/placeholders.hpp>\r\n#include <boost/type_traits/is_same.hpp>\r\n#include <boost/accumulators/numeric/functional.hpp>\r\n#include <boost/accumulators/framework/accumulator_base.hpp>\r\n#include <boost/accumulators/framework/extractor.hpp>\r\n#include <boost/accumulators/framework/parameters/sample.hpp>\r\n#include <boost/accumulators/statistics_fwd.hpp>\r\n#include <boost/accumulators/statistics/tail.hpp>\r\n#include <boost/accumulators/statistics/tail_variate.hpp>\r\n#include <boost/accumulators/statistics/tail_variate_means.hpp>\r\n#include <boost/accumulators/statistics/weighted_tail_mean.hpp>\r\n#include <boost/accumulators/statistics/parameters/quantile_probability.hpp>\r\n\r\n#ifdef _MSC_VER\r\n# pragma warning(push)\r\n# pragma warning(disable: 4127) // conditional expression is constant\r\n#endif\r\n\r\nnamespace boost\r\n{\r\n    // for _BinaryOperatrion2 in std::inner_product below\r\n    // multiplies two values and promotes the result to double\r\n    namespace numeric { namespace functional\r\n    {\r\n        ///////////////////////////////////////////////////////////////////////////////\r\n        // numeric::functional::multiply_and_promote_to_double\r\n        template<typename T, typename U>\r\n        struct multiply_and_promote_to_double\r\n          : multiplies<T, double const>\r\n        {\r\n        };\r\n    }}\r\n}\r\n\r\nnamespace boost { namespace accumulators\r\n{\r\n\r\nnamespace impl\r\n{\r\n    /**\r\n        @brief Estimation of the absolute and relative weighted tail variate means (for both left and right tails)\r\n\r\n        For all \\f$j\\f$-th variates associated to the\r\n\r\n        \\f[\r\n            \\lambda = \\inf\\left\\{ l \\left| \\frac{1}{\\bar{w}_n}\\sum_{i=1}^{l} w_i \\geq \\alpha \\right. \\right\\}\r\n        \\f]\r\n\r\n        smallest samples (left tail) or the weighted mean of the\r\n\r\n        \\f[\r\n            n + 1 - \\rho = n + 1 - \\sup\\left\\{ r \\left| \\frac{1}{\\bar{w}_n}\\sum_{i=r}^{n} w_i \\geq (1 - \\alpha) \\right. \\right\\}\r\n        \\f]\r\n\r\n        largest samples (right tail), the absolute weighted tail means \\f$\\widehat{ATM}_{n,\\alpha}(X, j)\\f$\r\n        are computed and returned as an iterator range. Alternatively, the relative weighted tail means\r\n        \\f$\\widehat{RTM}_{n,\\alpha}(X, j)\\f$ are returned, which are the absolute weighted tail means\r\n        normalized with the weighted (non-coherent) sample tail mean \\f$\\widehat{NCTM}_{n,\\alpha}(X)\\f$.\r\n\r\n        \\f[\r\n            \\widehat{ATM}_{n,\\alpha}^{\\mathrm{right}}(X, j) =\r\n                \\frac{1}{\\sum_{i=\\rho}^n w_i}\r\n                \\sum_{i=\\rho}^n w_i \\xi_{j,i}\r\n        \\f]\r\n\r\n        \\f[\r\n            \\widehat{ATM}_{n,\\alpha}^{\\mathrm{left}}(X, j) =\r\n                \\frac{1}{\\sum_{i=1}^{\\lambda}}\r\n                \\sum_{i=1}^{\\lambda} w_i \\xi_{j,i}\r\n        \\f]\r\n\r\n        \\f[\r\n            \\widehat{RTM}_{n,\\alpha}^{\\mathrm{right}}(X, j) =\r\n                \\frac{\\sum_{i=\\rho}^n w_i \\xi_{j,i}}\r\n            {\\sum_{i=\\rho}^n w_i \\widehat{NCTM}_{n,\\alpha}^{\\mathrm{right}}(X)}\r\n        \\f]\r\n\r\n        \\f[\r\n            \\widehat{RTM}_{n,\\alpha}^{\\mathrm{left}}(X, j) =\r\n                \\frac{\\sum_{i=1}^{\\lambda} w_i \\xi_{j,i}}\r\n            {\\sum_{i=1}^{\\lambda} w_i \\widehat{NCTM}_{n,\\alpha}^{\\mathrm{left}}(X)}\r\n        \\f]\r\n    */\r\n\r\n    ///////////////////////////////////////////////////////////////////////////////\r\n    // weighted_tail_variate_means_impl\r\n    //  by default: absolute weighted_tail_variate_means\r\n    template<typename Sample, typename Weight, typename Impl, typename LeftRight, typename VariateType>\r\n    struct weighted_tail_variate_means_impl\r\n      : accumulator_base\r\n    {\r\n        typedef typename numeric::functional::average<Weight, Weight>::result_type float_type;\r\n        typedef typename numeric::functional::average<typename numeric::functional::multiplies<VariateType, Weight>::result_type, Weight>::result_type array_type;\r\n        // for boost::result_of\r\n        typedef iterator_range<typename array_type::iterator> result_type;\r\n\r\n        weighted_tail_variate_means_impl(dont_care) {}\r\n\r\n        template<typename Args>\r\n        result_type result(Args const &args) const\r\n        {\r\n            float_type threshold = sum_of_weights(args)\r\n                             * ( ( is_same<LeftRight, left>::value ) ? args[quantile_probability] : 1. - args[quantile_probability] );\r\n\r\n            std::size_t n = 0;\r\n            Weight sum = Weight(0);\r\n\r\n            while (sum < threshold)\r\n            {\r\n                if (n < static_cast<std::size_t>(tail_weights(args).size()))\r\n                {\r\n                    sum += *(tail_weights(args).begin() + n);\r\n                    n++;\r\n                }\r\n                else\r\n                {\r\n                    if (std::numeric_limits<float_type>::has_quiet_NaN)\r\n                    {\r\n                        std::fill(\r\n                            this->tail_means_.begin()\r\n                          , this->tail_means_.end()\r\n                          , std::numeric_limits<float_type>::quiet_NaN()\r\n                        );\r\n                    }\r\n                    else\r\n                    {\r\n                        std::ostringstream msg;\r\n                        msg << \"index n = \" << n << \" is not in valid range [0, \" << tail(args).size() << \")\";\r\n                        boost::throw_exception(std::runtime_error(msg.str()));\r\n                    }\r\n                }\r\n            }\r\n\r\n            std::size_t num_variates = tail_variate(args).begin()->size();\r\n\r\n            this->tail_means_.clear();\r\n            this->tail_means_.resize(num_variates, Sample(0));\r\n\r\n            this->tail_means_ = std::inner_product(\r\n                tail_variate(args).begin()\r\n              , tail_variate(args).begin() + n\r\n              , tail_weights(args).begin()\r\n              , this->tail_means_\r\n              , numeric::functional::plus<array_type const, array_type const>()\r\n              , numeric::functional::multiply_and_promote_to_double<VariateType const, Weight const>()\r\n            );\r\n\r\n            float_type factor = sum * ( (is_same<Impl, relative>::value) ? non_coherent_weighted_tail_mean(args) : 1. );\r\n\r\n            std::transform(\r\n                this->tail_means_.begin()\r\n              , this->tail_means_.end()\r\n              , this->tail_means_.begin()\r\n              , std::bind2nd(numeric::functional::divides<typename array_type::value_type const, float_type const>(), factor)\r\n            );\r\n\r\n            return make_iterator_range(this->tail_means_);\r\n        }\r\n\r\n    private:\r\n\r\n        mutable array_type tail_means_;\r\n\r\n    };\r\n\r\n} // namespace impl\r\n\r\n///////////////////////////////////////////////////////////////////////////////\r\n// tag::absolute_weighted_tail_variate_means\r\n// tag::relative_weighted_tail_variate_means\r\n//\r\nnamespace tag\r\n{\r\n    template<typename LeftRight, typename VariateType, typename VariateTag>\r\n    struct absolute_weighted_tail_variate_means\r\n      : depends_on<non_coherent_weighted_tail_mean<LeftRight>, tail_variate<VariateType, VariateTag, LeftRight>, tail_weights<LeftRight> >\r\n    {\r\n        typedef accumulators::impl::weighted_tail_variate_means_impl<mpl::_1, mpl::_2, absolute, LeftRight, VariateType> impl;\r\n    };\r\n    template<typename LeftRight, typename VariateType, typename VariateTag>\r\n    struct relative_weighted_tail_variate_means\r\n      : depends_on<non_coherent_weighted_tail_mean<LeftRight>, tail_variate<VariateType, VariateTag, LeftRight>, tail_weights<LeftRight> >\r\n    {\r\n        typedef accumulators::impl::weighted_tail_variate_means_impl<mpl::_1, mpl::_2, relative, LeftRight, VariateType> impl;\r\n    };\r\n}\r\n\r\n///////////////////////////////////////////////////////////////////////////////\r\n// extract::weighted_tail_variate_means\r\n// extract::relative_weighted_tail_variate_means\r\n//\r\nnamespace extract\r\n{\r\n    extractor<tag::abstract_absolute_tail_variate_means> const weighted_tail_variate_means = {};\r\n    extractor<tag::abstract_relative_tail_variate_means> const relative_weighted_tail_variate_means = {};\r\n\r\n    BOOST_ACCUMULATORS_IGNORE_GLOBAL(weighted_tail_variate_means)\r\n    BOOST_ACCUMULATORS_IGNORE_GLOBAL(relative_weighted_tail_variate_means)\r\n}\r\n\r\nusing extract::weighted_tail_variate_means;\r\nusing extract::relative_weighted_tail_variate_means;\r\n\r\n// weighted_tail_variate_means<LeftRight, VariateType, VariateTag>(absolute) -> absolute_weighted_tail_variate_means<LeftRight, VariateType, VariateTag>\r\ntemplate<typename LeftRight, typename VariateType, typename VariateTag>\r\nstruct as_feature<tag::weighted_tail_variate_means<LeftRight, VariateType, VariateTag>(absolute)>\r\n{\r\n    typedef tag::absolute_weighted_tail_variate_means<LeftRight, VariateType, VariateTag> type;\r\n};\r\n\r\n// weighted_tail_variate_means<LeftRight, VariateType, VariateTag>(relative) -> relative_weighted_tail_variate_means<LeftRight, VariateType, VariateTag>\r\ntemplate<typename LeftRight, typename VariateType, typename VariateTag>\r\nstruct as_feature<tag::weighted_tail_variate_means<LeftRight, VariateType, VariateTag>(relative)>\r\n{\r\n    typedef tag::relative_weighted_tail_variate_means<LeftRight, VariateType, VariateTag> type;\r\n};\r\n\r\n}} // namespace boost::accumulators\r\n\r\n#ifdef _MSC_VER\r\n# pragma warning(pop)\r\n#endif\r\n\r\n#endif\r\n", "meta": {"hexsha": "884ff4c85099742a4a36418b4c6ec2377e548130", "size": 9911, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "BoostSharp/include/boost/accumulators/statistics/weighted_tail_variate_means.hpp", "max_stars_repo_name": "Icenium/BoostSharp", "max_stars_repo_head_hexsha": "1dd31065fcd65ae6304b182c558bac7c7a738ad5", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2017-05-11T05:30:19.000Z", "max_stars_repo_stars_event_max_datetime": "2019-04-24T05:41:33.000Z", "max_issues_repo_path": "src/third_party/boost/boost/accumulators/statistics/weighted_tail_variate_means.hpp", "max_issues_repo_name": "wugh7125/installwizard", "max_issues_repo_head_hexsha": "42f8aeb78026ff81838528968b1503e73f6c2864", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/third_party/boost/boost/accumulators/statistics/weighted_tail_variate_means.hpp", "max_forks_repo_name": "wugh7125/installwizard", "max_forks_repo_head_hexsha": "42f8aeb78026ff81838528968b1503e73f6c2864", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-03-26T17:00:08.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-26T17:00:08.000Z", "avg_line_length": 40.7860082305, "max_line_length": 163, "alphanum_fraction": 0.6107355464, "num_tokens": 2291, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6334102636778401, "lm_q2_score": 0.5312093733737563, "lm_q1q2_score": 0.3364734692568112}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\n\n// Copyright (c) 2015 Barend Gehrels, Amsterdam, the Netherlands.\n\n// This file was modified by Oracle on 2015, 2019.\n// Modifications copyright (c) 2015-2019, 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_STRATEGIES_CARTESIAN_SIDE_OF_INTERSECTION_HPP\n#define BOOST_GEOMETRY_STRATEGIES_CARTESIAN_SIDE_OF_INTERSECTION_HPP\n\n\n#include <limits>\n\n#include <boost/core/ignore_unused.hpp>\n#include <boost/type_traits/is_integral.hpp>\n#include <boost/type_traits/make_unsigned.hpp>\n\n#include <boost/geometry/arithmetic/determinant.hpp>\n#include <boost/geometry/core/access.hpp>\n#include <boost/geometry/core/assert.hpp>\n#include <boost/geometry/core/coordinate_type.hpp>\n#include <boost/geometry/algorithms/detail/assign_indexed_point.hpp>\n#include <boost/geometry/strategies/cartesian/side_by_triangle.hpp>\n#include <boost/geometry/util/math.hpp>\n\n#ifdef BOOST_GEOMETRY_SIDE_OF_INTERSECTION_DEBUG\n#include <boost/math/common_factor_ct.hpp>\n#include <boost/math/common_factor_rt.hpp>\n#include <boost/multiprecision/cpp_int.hpp>\n#endif\n\nnamespace boost { namespace geometry\n{\n\nnamespace strategy { namespace side\n{\n\nnamespace detail\n{\n\n// A tool for multiplication of integers avoiding overflow\n// It's a temporary workaround until we can use Multiprecision\n// The algorithm is based on Karatsuba algorithm\n// see: http://en.wikipedia.org/wiki/Karatsuba_algorithm\ntemplate <typename T>\nstruct multiplicable_integral\n{\n    // Currently this tool can't be used with non-integral coordinate types.\n    // Also side_of_intersection strategy sign_of_product() and sign_of_compare()\n    // functions would have to be modified to properly support floating-point\n    // types (comparisons and multiplication).\n    BOOST_STATIC_ASSERT(boost::is_integral<T>::value);\n\n    static const std::size_t bits = CHAR_BIT * sizeof(T);\n    static const std::size_t half_bits = bits / 2;\n    typedef typename boost::make_unsigned<T>::type unsigned_type;\n    static const unsigned_type base = unsigned_type(1) << half_bits; // 2^half_bits\n\n    int m_sign;\n    unsigned_type m_ms;\n    unsigned_type m_ls;\n\n    multiplicable_integral(int sign, unsigned_type ms, unsigned_type ls)\n        : m_sign(sign), m_ms(ms), m_ls(ls)\n    {}\n\n    explicit multiplicable_integral(T const& val)\n    {\n        unsigned_type val_u = val > 0 ?\n                                unsigned_type(val)\n                              : val == (std::numeric_limits<T>::min)() ?\n                                  unsigned_type((std::numeric_limits<T>::max)()) + 1\n                                : unsigned_type(-val);\n        // MMLL -> S 00MM 00LL\n        m_sign = math::sign(val);\n        m_ms = val_u >> half_bits; // val_u / base\n        m_ls = val_u - m_ms * base;\n    }\n    \n    friend multiplicable_integral operator*(multiplicable_integral const& a,\n                                            multiplicable_integral const& b)\n    {\n        // (S 00MM 00LL) * (S 00MM 00LL) -> (S Z2MM 00LL)\n        unsigned_type z2 = a.m_ms * b.m_ms;\n        unsigned_type z0 = a.m_ls * b.m_ls;\n        unsigned_type z1 = (a.m_ms + a.m_ls) * (b.m_ms + b.m_ls) - z2 - z0;\n        // z0 may be >= base so it must be normalized to allow comparison\n        unsigned_type z0_ms = z0 >> half_bits; // z0 / base\n        return multiplicable_integral(a.m_sign * b.m_sign,\n                                      z2 * base + z1 + z0_ms,\n                                      z0 - base * z0_ms);\n    }\n\n    friend bool operator<(multiplicable_integral const& a,\n                          multiplicable_integral const& b)\n    {\n        if ( a.m_sign == b.m_sign )\n        {\n            bool u_less = a.m_ms < b.m_ms\n                      || (a.m_ms == b.m_ms && a.m_ls < b.m_ls);\n            return a.m_sign > 0 ? u_less : (! u_less);\n        }\n        else\n        {\n            return a.m_sign < b.m_sign;\n        }\n    }\n\n    friend bool operator>(multiplicable_integral const& a,\n                          multiplicable_integral const& b)\n    {\n        return b < a;\n    }\n\n#ifdef BOOST_GEOMETRY_SIDE_OF_INTERSECTION_DEBUG\n    template <typename CmpVal>\n    void check_value(CmpVal const& cmp_val) const\n    {\n        unsigned_type b = base; // a workaround for MinGW - undefined reference base\n        CmpVal val = CmpVal(m_sign) * (CmpVal(m_ms) * CmpVal(b) + CmpVal(m_ls));\n        BOOST_GEOMETRY_ASSERT(cmp_val == val);\n    }\n#endif // BOOST_GEOMETRY_SIDE_OF_INTERSECTION_DEBUG\n};\n\n} // namespace detail\n\n// Calculates the side of the intersection-point (if any) of\n// of segment a//b w.r.t. segment c\n// This is calculated without (re)calculating the IP itself again and fully\n// based on integer mathematics; there are no divisions\n// It can be used for either integer (rescaled) points, and also for FP\nclass side_of_intersection\n{\nprivate :\n    template <typename T, typename U>\n    static inline\n    int sign_of_product(T const& a, U const& b)\n    {\n        return a == 0 || b == 0 ? 0\n            : a > 0 && b > 0 ? 1\n            : a < 0 && b < 0 ? 1\n            : -1;\n    }\n\n    template <typename T>\n    static inline\n    int sign_of_compare(T const& a, T const& b, T const& c, T const& d)\n    {\n        // Both a*b and c*d are positive\n        // We have to judge if a*b > c*d\n\n        using side::detail::multiplicable_integral;\n        multiplicable_integral<T> ab = multiplicable_integral<T>(a)\n                                     * multiplicable_integral<T>(b);\n        multiplicable_integral<T> cd = multiplicable_integral<T>(c)\n                                     * multiplicable_integral<T>(d);\n        \n        int result = ab > cd ? 1\n                   : ab < cd ? -1\n                   : 0\n                   ;\n\n#ifdef BOOST_GEOMETRY_SIDE_OF_INTERSECTION_DEBUG\n        using namespace boost::multiprecision;\n        cpp_int const lab = cpp_int(a) * cpp_int(b);\n        cpp_int const lcd = cpp_int(c) * cpp_int(d);\n\n        ab.check_value(lab);\n        cd.check_value(lcd);\n\n        int result2 = lab > lcd ? 1\n                    : lab < lcd ? -1\n                    : 0\n                    ;\n        BOOST_GEOMETRY_ASSERT(result == result2);\n#endif\n\n        return result;\n    }\n\n    template <typename T>\n    static inline\n    int sign_of_addition_of_two_products(T const& a, T const& b, T const& c, T const& d)\n    {\n        // sign of a*b+c*d, 1 if positive, -1 if negative, else 0\n        int const ab = sign_of_product(a, b);\n        int const cd = sign_of_product(c, d);\n        if (ab == 0)\n        {\n            return cd;\n        }\n        if (cd == 0)\n        {\n            return ab;\n        }\n\n        if (ab == cd)\n        {\n            // Both positive or both negative\n            return ab;\n        }\n\n        // One is positive, one is negative, both are non zero\n        // If ab is positive, we have to judge if a*b > -c*d (then 1 because sum is positive)\n        // If ab is negative, we have to judge if c*d > -a*b (idem)\n        return ab == 1\n            ? sign_of_compare(a, b, -c, d)\n            : sign_of_compare(c, d, -a, b);\n    }\n\n\npublic :\n\n    // Calculates the side of the intersection-point (if any) of\n    // of segment a//b w.r.t. segment c\n    // This is calculated without (re)calculating the IP itself again and fully\n    // based on integer mathematics\n    template <typename T, typename Segment, typename Point>\n    static inline T side_value(Segment const& a, Segment const& b,\n                Segment const& c, Point const& fallback_point)\n    {\n        // The first point of the three segments is reused several times\n        T const ax = get<0, 0>(a);\n        T const ay = get<0, 1>(a);\n        T const bx = get<0, 0>(b);\n        T const by = get<0, 1>(b);\n        T const cx = get<0, 0>(c);\n        T const cy = get<0, 1>(c);\n\n        T const dx_a = get<1, 0>(a) - ax;\n        T const dy_a = get<1, 1>(a) - ay;\n\n        T const dx_b = get<1, 0>(b) - bx;\n        T const dy_b = get<1, 1>(b) - by;\n\n        T const dx_c = get<1, 0>(c) - cx;\n        T const dy_c = get<1, 1>(c) - cy;\n\n        // Cramer's rule: d (see cart_intersect.hpp)\n        T const d = geometry::detail::determinant<T>\n                    (\n                        dx_a, dy_a,\n                        dx_b, dy_b\n                    );\n\n        T const zero = T();\n        if (d == zero)\n        {\n            // There is no IP of a//b, they are collinear or parallel\n            // Assuming they intersect (this method should be called for\n            // segments known to intersect), they are collinear and overlap.\n            // They have one or two intersection points - we don't know and\n            // have to rely on the fallback intersection point\n\n            Point c1, c2;\n            geometry::detail::assign_point_from_index<0>(c, c1);\n            geometry::detail::assign_point_from_index<1>(c, c2);\n            return side_by_triangle<>::apply(c1, c2, fallback_point);\n        }\n\n        // Cramer's rule: da (see cart_intersect.hpp)\n        T const da = geometry::detail::determinant<T>\n                    (\n                        dx_b,    dy_b,\n                        ax - bx, ay - by\n                    );\n\n        // IP is at (ax + (da/d) * dx_a, ay + (da/d) * dy_a)\n        // Side of IP is w.r.t. c is: determinant(dx_c, dy_c, ipx-cx, ipy-cy)\n        // We replace ipx by expression above and multiply each term by d\n\n#ifdef BOOST_GEOMETRY_SIDE_OF_INTERSECTION_DEBUG\n        T const result1 = geometry::detail::determinant<T>\n                    (\n                        dx_c * d,                   dy_c * d,\n                        d * (ax - cx) + dx_a * da,  d * (ay - cy) + dy_a * da\n                    );\n\n        // Note: result / (d * d)\n        // is identical to the side_value of side_by_triangle\n        // Therefore, the sign is always the same as that result, and the\n        // resulting side (left,right,collinear) is the same\n\n        // The first row we divide again by d because of determinant multiply rule\n        T const result2 = d * geometry::detail::determinant<T>\n                    (\n                        dx_c,                   dy_c,\n                        d * (ax - cx) + dx_a * da,  d * (ay - cy) + dy_a * da\n                    );\n        // Write out:\n        T const result3 = d * (dx_c * (d * (ay - cy) + dy_a * da)\n                             - dy_c * (d * (ax - cx) + dx_a * da));\n        // Write out in braces:\n        T const result4 = d * (dx_c * d * (ay - cy) + dx_c * dy_a * da\n                             - dy_c * d * (ax - cx) - dy_c * dx_a * da);\n        // Write in terms of d * XX + da * YY\n        T const result5 = d * (d * (dx_c * (ay - cy) - dy_c * (ax - cx))\n                             + da * (dx_c * dy_a - dy_c * dx_a));\n\n        boost::ignore_unused(result1, result2, result3, result4, result5);\n        //return result;\n#endif\n\n        // We consider the results separately\n        // (in the end we only have to return the side-value 1,0 or -1)\n\n        // To avoid multiplications we judge the product (easy, avoids *d)\n        // and the sign of p*q+r*s (more elaborate)\n        T const result = sign_of_product\n            (\n                d,\n                sign_of_addition_of_two_products\n                    (\n                        d, dx_c * (ay - cy) - dy_c * (ax - cx),\n                        da, dx_c * dy_a - dy_c * dx_a\n                    )\n                );\n        return result;\n\n\n    }\n\n    template <typename Segment, typename Point>\n    static inline int apply(Segment const& a, Segment const& b,\n            Segment const& c,\n            Point const& fallback_point)\n    {\n        typedef typename geometry::coordinate_type<Segment>::type coordinate_type;\n        coordinate_type const s = side_value<coordinate_type>(a, b, c, fallback_point);\n        coordinate_type const zero = coordinate_type();\n        return math::equals(s, zero) ? 0\n            : s > zero ? 1\n            : -1;\n    }\n\n};\n\n\n}} // namespace strategy::side\n\n}} // namespace boost::geometry\n\n\n#endif // BOOST_GEOMETRY_STRATEGIES_CARTESIAN_SIDE_OF_INTERSECTION_HPP\n", "meta": {"hexsha": "9c0a5f0d3b72f363cd5bd0b4ded1b911726ca023", "size": 12336, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/geometry/strategies/cartesian/side_of_intersection.hpp", "max_stars_repo_name": "cpp-pm/boost", "max_stars_repo_head_hexsha": "38c6c8c07f2fcc42d573b10807fef27ec14930f8", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 12278.0, "max_stars_repo_stars_event_min_datetime": "2015-01-29T17:11:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T21:12:00.000Z", "max_issues_repo_path": "boost/geometry/strategies/cartesian/side_of_intersection.hpp", "max_issues_repo_name": "cpp-pm/boost", "max_issues_repo_head_hexsha": "38c6c8c07f2fcc42d573b10807fef27ec14930f8", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 9469.0, "max_issues_repo_issues_event_min_datetime": "2015-01-30T05:33:07.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T16:17:21.000Z", "max_forks_repo_path": "boost/geometry/strategies/cartesian/side_of_intersection.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.0454545455, "max_line_length": 93, "alphanum_fraction": 0.566309987, "num_tokens": 3085, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6334102636778401, "lm_q2_score": 0.5312093733737563, "lm_q1q2_score": 0.3364734692568112}}
{"text": "#pragma once\n#ifndef OPENGM_SUBGRADIENT_SSVM_LEARNER_HXX\n#define OPENGM_SUBGRADIENT_SSVM_LEARNER_HXX\n\n#include <iomanip>\n#include <vector>\n#include <opengm/inference/inference.hxx>\n#include <opengm/graphicalmodel/weights.hxx>\n#include <opengm/utilities/random.hxx>\n#include <opengm/learning/gradient-accumulator.hxx>\n#include <opengm/learning/weight_averaging.hxx>\n\n#ifdef WITH_OPENMP\n#include <omp.h>\n#endif\n\n#include <boost/circular_buffer.hpp>\n\n\n\nnamespace opengm {\n    namespace learning {\n\n\n\n           \n    template<class DATASET>\n    class SubgradientSSVM\n    {\n    public: \n        typedef DATASET DatasetType;\n        typedef typename DATASET::GMType   GMType; \n        typedef typename DATASET::GMWITHLOSS GMWITHLOSS;\n        typedef typename DATASET::LossType LossType;\n        typedef typename GMType::ValueType ValueType;\n        typedef typename GMType::IndexType IndexType;\n        typedef typename GMType::LabelType LabelType; \n        typedef opengm::learning::Weights<double> WeightsType;\n        typedef typename std::vector<LabelType>::const_iterator LabelIterator;\n        typedef FeatureAccumulator<GMType, LabelIterator> FeatureAcc;\n\n        typedef std::vector<LabelType> ConfType;\n        typedef boost::circular_buffer<ConfType> ConfBuffer;\n        typedef std::vector<ConfBuffer> ConfBufferVec;\n\n        class Parameter{\n        public:\n\n            enum LearningMode{\n                Online = 0,\n                Batch = 1\n            };\n\n\n            Parameter(){\n                eps_ = 0.00001;\n                maxIterations_ = 10000;\n                stopLoss_ = 0.0;\n                learningRate_ = 1.0;\n                C_ = 1.0;\n                learningMode_ = Batch;\n                averaging_ = -1;\n                nConf_ = 0;\n            }       \n\n            double eps_;\n            size_t maxIterations_;\n            double stopLoss_;\n            double learningRate_;\n            double C_;\n            LearningMode learningMode_;\n            int averaging_;\n            int nConf_;\n        };\n\n\n        SubgradientSSVM(DATASET&, const Parameter& );\n\n        template<class INF>\n        void learn(const typename INF::Parameter& para); \n        //template<class INF, class VISITOR>\n        //void learn(typename INF::Parameter para, VITITOR vis);\n\n        const opengm::learning::Weights<double>& getWeights(){return weights_;}\n        Parameter& getLerningParameters(){return para_;}\n\n\n        double getLearningRate( )const{\n            if(para_.decayExponent_<=0.000000001 && para_.decayExponent_>=-0.000000001 ){\n                return 1.0;\n            }\n            else{\n                return std::pow(para_.decayT0_ + static_cast<double>(iteration_),para_.decayExponent_);\n            }\n        }\n\n        double getLoss(const GMType & gm ,const GMWITHLOSS  & gmWithLoss, std::vector<LabelType> & labels){\n\n            double loss = 0 ;\n            std::vector<LabelType> subConf(20,0);\n\n            for(size_t fi=gm.numberOfFactors(); fi<gmWithLoss.numberOfFactors(); ++fi){\n                for(size_t v=0; v<gmWithLoss[fi].numberOfVariables(); ++v){\n                    subConf[v] = labels[ gmWithLoss[fi].variableIndex(v)];\n                }\n                loss +=  gmWithLoss[fi](subConf.begin());\n            }\n            return loss;\n        }\n\n    private:\n\n        double updateWeights();\n\n        DATASET& dataset_;\n        WeightsType  weights_;\n        Parameter para_;\n        size_t iteration_;\n        FeatureAcc featureAcc_;\n        WeightRegularizer<ValueType> wReg_;\n        WeightAveraging<double> weightAveraging_;\n    }; \n\n    template<class DATASET>\n    SubgradientSSVM<DATASET>::SubgradientSSVM(DATASET& ds, const Parameter& p )\n    :   dataset_(ds), \n        para_(p),\n        iteration_(0),\n        featureAcc_(ds.getNumberOfWeights()),\n        wReg_(2, 1.0/p.C_),\n        weightAveraging_(ds.getWeights(),p.averaging_)\n    {\n        featureAcc_.resetWeights();\n        weights_ = opengm::learning::Weights<double>(ds.getNumberOfWeights());\n    }\n\n\n    template<class DATASET>\n    template<class INF>\n    void SubgradientSSVM<DATASET>::learn(const typename INF::Parameter& para){\n\n\n        typedef typename INF:: template RebindGm<GMWITHLOSS>::type InfLossGm;\n        typedef typename InfLossGm::Parameter InfLossGmParam;\n        InfLossGmParam infLossGmParam(para);\n\n\n        const size_t nModels = dataset_.getNumberOfModels();\n        const size_t nWegihts = dataset_.getNumberOfWeights();\n\n        \n        for(size_t wi=0; wi<nWegihts; ++wi){\n            dataset_.getWeights().setWeight(wi, 0.0);\n        }\n        std::cout<<\"PARAM nConf_\"<<para_.nConf_<<\"\\n\";\n        const bool useWorkingSets = para_.nConf_>0;\n\n        ConfBufferVec buffer(useWorkingSets? nModels : 0, ConfBuffer(para_.nConf_));\n\n        std::vector<bool> isViolated(para_.nConf_);\n\n        if(para_.learningMode_ == Parameter::Online){\n            RandomUniform<size_t> randModel(0, nModels);\n            //std::cout<<\"online mode\\n\";\n            for(iteration_=0 ; iteration_<para_.maxIterations_; ++iteration_){\n\n\n\n\n                // get random model\n                const size_t gmi = randModel();\n                // lock the model\n                dataset_.lockModel(gmi);\n                const GMWITHLOSS & gmWithLoss = dataset_.getModelWithLoss(gmi);\n\n                // do inference\n                std::vector<LabelType> arg;\n                opengm::infer<InfLossGm>(gmWithLoss, infLossGmParam, arg);\n                featureAcc_.resetWeights();\n                featureAcc_.accumulateModelFeatures(dataset_.getModel(gmi), dataset_.getGT(gmi).begin(), arg.begin());\n                dataset_.unlockModel(gmi);\n\n                // update weights\n                const double wChange =updateWeights();\n\n                if(iteration_%nModels*2 == 0 ){\n                    std::cout << '\\r'\n                              << std::setw(6) << std::setfill(' ') << iteration_ << ':'\n                              << std::setw(8) << dataset_. template getTotalLossParallel<INF>(para) <<\"  \"<< std::flush;\n\n                }\n\n            }\n        }\n        else if(para_.learningMode_ == Parameter::Batch){\n            //std::cout<<\"batch mode\\n\";\n            for(iteration_=0 ; iteration_<para_.maxIterations_; ++iteration_){\n                // this \n                \n\n                // reset the weights\n                featureAcc_.resetWeights();\n                double totalLoss = 0;\n\n                #ifdef WITH_OPENMP\n                omp_lock_t modelLockUnlock;\n                omp_init_lock(&modelLockUnlock);\n                omp_lock_t featureAccLock;\n                omp_init_lock(&featureAccLock);\n                #pragma omp parallel for reduction(+:totalLoss)  \n                #endif\n                for(size_t gmi=0; gmi<nModels; ++gmi){\n                    \n                    // lock the model\n                    #ifdef WITH_OPENMP\n                    omp_set_lock(&modelLockUnlock);\n                    dataset_.lockModel(gmi);     \n                    omp_unset_lock(&modelLockUnlock);\n                    #else\n                    dataset_.lockModel(gmi);     \n                    #endif\n                        \n                    \n\n                    const GMWITHLOSS & gmWithLoss = dataset_.getModelWithLoss(gmi);\n                    const GMType     & gm = dataset_.getModel(gmi);\n                    //run inference\n                    std::vector<LabelType> arg;\n                    opengm::infer<InfLossGm>(gmWithLoss, infLossGmParam, arg);\n\n                    totalLoss = totalLoss + getLoss(gm, gmWithLoss, arg);\n\n             \n                    if(useWorkingSets){\n                        // append current solution\n                        buffer[gmi].push_back(arg);\n\n                        size_t vCount=0;\n                        // check which violates\n                        for(size_t cc=0; cc<buffer[gmi].size(); ++cc){\n                            const double mLoss = dataset_.getLoss(buffer[gmi][cc], gmi);\n                            const double argVal = gm.evaluate(buffer[gmi][cc]);\n                            const double gtVal =  gm.evaluate(dataset_.getGT(gmi));\n                            const double ll = (argVal - mLoss) - gtVal;\n                            //std::cout<<\" argVal \"<<argVal<<\" gtVal \"<<gtVal<<\" mLoss \"<<mLoss<<\"   VV \"<<ll<<\"\\n\";\n                            if(ll<0){\n                                isViolated[cc] = true;\n                                ++vCount;\n                            }\n                        }\n                        FeatureAcc featureAcc(nWegihts);\n                        for(size_t cc=0; cc<buffer[gmi].size(); ++cc){\n                            if(isViolated[cc]){\n\n                                featureAcc.accumulateModelFeatures(gm, dataset_.getGT(gmi).begin(), buffer[gmi][cc].begin(),1.0/double(vCount));\n\n                            }\n                        }\n                        #ifdef WITH_OPENMP\n                        omp_set_lock(&featureAccLock);\n                        featureAcc_.accumulateFromOther(featureAcc);\n                        omp_unset_lock(&featureAccLock);\n                        #else\n                        featureAcc_.accumulateFromOther(featureAcc);\n                        #endif\n                    }\n                    else{\n                        FeatureAcc featureAcc(nWegihts);\n                        featureAcc.accumulateModelFeatures(gm, dataset_.getGT(gmi).begin(), arg.begin());\n                        #ifdef WITH_OPENMP\n                        omp_set_lock(&featureAccLock);\n                        featureAcc_.accumulateFromOther(featureAcc);\n                        omp_unset_lock(&featureAccLock);\n                        #else\n                        featureAcc_.accumulateFromOther(featureAcc);\n                        #endif\n                    }\n\n\n\n                    // acc features\n                    //omp_set_lock(&featureAccLock);\n                    //featureAcc_.accumulateFromOther(featureAcc);\n                    //omp_unset_lock(&featureAccLock);\n\n                    // unlock the model\n                    #ifdef WITH_OPENMP\n                    omp_set_lock(&modelLockUnlock);\n                    dataset_.unlockModel(gmi);     \n                    omp_unset_lock(&modelLockUnlock);\n                    #else\n                    dataset_.unlockModel(gmi);     \n                    #endif\n\n\n                }\n\n                //const double wRegVal = wReg_(dataset_.getWeights());\n                //const double tObj = std::abs(totalLoss) + wRegVal;\n                if(iteration_%1==0){\n                    std::cout << '\\r'\n                              << std::setw(6) << std::setfill(' ') << iteration_ << ':'\n                              << std::setw(8) << -1.0*totalLoss <<\"  \"<< std::flush;\n                }\n                // update the weights\n                const double wChange =updateWeights();\n                \n            }\n        }\n        weights_ = dataset_.getWeights();\n    }\n\n\n    template<class DATASET>\n    double SubgradientSSVM<DATASET>::updateWeights(){\n\n        const size_t nWegihts = dataset_.getNumberOfWeights();\n\n        WeightsType p(nWegihts);\n        WeightsType newWeights(nWegihts);\n\n        if(para_.learningMode_ == Parameter::Batch){\n            for(size_t wi=0; wi<nWegihts; ++wi){\n                p[wi] =  dataset_.getWeights().getWeight(wi);\n                p[wi] += para_.C_ * featureAcc_.getWeight(wi)/double(dataset_.getNumberOfModels());\n            }\n        }\n        else{\n            for(size_t wi=0; wi<nWegihts; ++wi){\n                p[wi] =  dataset_.getWeights().getWeight(wi);\n                p[wi] += para_.C_ * featureAcc_.getWeight(wi);\n            }\n        }\n\n\n        double wChange = 0.0;\n        \n        for(size_t wi=0; wi<nWegihts; ++wi){\n            const double wOld = dataset_.getWeights().getWeight(wi);\n            const double wNew = wOld - (para_.learningRate_/double(iteration_+1))*p[wi];\n            newWeights[wi] = wNew;\n        }\n\n        weightAveraging_(newWeights);\n\n\n\n        weights_ = dataset_.getWeights();\n        return wChange;\n    }\n}\n}\n#endif\n", "meta": {"hexsha": "67514f936042ca780cdfe222f317e9ee5d958f5e", "size": 12169, "ext": "hxx", "lang": "C++", "max_stars_repo_path": "include/opengm/learning/subgradient_ssvm.hxx", "max_stars_repo_name": "chaubold/opengm", "max_stars_repo_head_hexsha": "acc42b98b713db33f2b35aad05a7a1cf9752e862", "max_stars_repo_licenses": ["MIT"], "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/learning/subgradient_ssvm.hxx", "max_issues_repo_name": "chaubold/opengm", "max_issues_repo_head_hexsha": "acc42b98b713db33f2b35aad05a7a1cf9752e862", "max_issues_repo_licenses": ["MIT"], "max_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/learning/subgradient_ssvm.hxx", "max_forks_repo_name": "chaubold/opengm", "max_forks_repo_head_hexsha": "acc42b98b713db33f2b35aad05a7a1cf9752e862", "max_forks_repo_licenses": ["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.3757062147, "max_line_length": 144, "alphanum_fraction": 0.5160654121, "num_tokens": 2652, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6334102636778401, "lm_q2_score": 0.5312093733737562, "lm_q1q2_score": 0.33647346925681115}}
{"text": "/*\n * Copyright 2018 James Dyer\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\"); you may not\n * use this file except in compliance with the License. You may obtain a copy of\n * the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n * License for the specific language governing permissions and limitations under\n * the License.\n *\n * This is being developed for the TANGO Project: http://tango-project.eu\n */\n\n#include <sstream>\n#include <NTL/RR.h>\n#include <json/json.h>\n#include \"HE2Encrypter.h\"\n#include \"Random.h\"\n\nHE2Encrypter::HE2Encrypter(int lambda, int eta){\n\tgenerateParameters(lambda,eta);\n}\n\nHE2Encrypter::HE2Encrypter(int n, int d, int rho)\n{\n    /* Compute lower bound for p */\n\tNTL::RR rtwo(2);\n\tNTL::RR exp1(rho*d);\n\tNTL::RR nplusone(n+1);\n\tNTL::RR exp2(d);\n\tNTL::RR ploBound = pow(rtwo,exp1)*pow(nplusone,exp2);\n\tNTL::ZZ pLowerBound = to_ZZ(ploBound);\n\n\t/* Derive lambda and eta */\n\tlong lambda = NumBits(pLowerBound) + 1;\n\tlong eta = ((lambda * lambda / rho) - lambda);\n\tgenerateParameters(lambda,eta);\n}\n\nNTL::vec_ZZ_p HE2Encrypter::encrypt(NTL::ZZ& plaintext)\n{\n    NTL::ZZ_p r = to_ZZ_p(rng->nextBigInteger(q));\n    NTL::ZZ_p s = to_ZZ_p(rng->nextBigInteger(modulus));\n    NTL::ZZ_p ptext = to_ZZ_p(plaintext);\n    NTL::ZZ_p c = ptext + r*(*pmod);\n    return ONE_VECTOR*c + (*a)*s;\n}\n\nstd::string HE2Encrypter::writeSecretsToJSON()\n{\n\tJson::Value root;\n\tstd::ostringstream pStr,modStr,gammaStr;\n\tpStr << p;\n\troot[\"p\"] = pStr.str();\n\tmodStr << modulus;\n\troot[\"modulus\"] = modStr.str();\n\tgammaStr << (*gamma);\n    root[\"gamma\"]=gammaStr.str();\n\tJson::FastWriter writer;\n\treturn writer.write(root);\n}\n", "meta": {"hexsha": "f846eba120112084585a9380bdf8fce61706e3b4", "size": 1877, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/HE2Encrypter.cpp", "max_stars_repo_name": "TANGO-Project/cryptsdc", "max_stars_repo_head_hexsha": "4428fc289c97818d58a8010593636c64bde56e82", "max_stars_repo_licenses": ["BSD-4-Clause-UC"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/HE2Encrypter.cpp", "max_issues_repo_name": "TANGO-Project/cryptsdc", "max_issues_repo_head_hexsha": "4428fc289c97818d58a8010593636c64bde56e82", "max_issues_repo_licenses": ["BSD-4-Clause-UC"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/HE2Encrypter.cpp", "max_forks_repo_name": "TANGO-Project/cryptsdc", "max_forks_repo_head_hexsha": "4428fc289c97818d58a8010593636c64bde56e82", "max_forks_repo_licenses": ["BSD-4-Clause-UC"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.0149253731, "max_line_length": 80, "alphanum_fraction": 0.695258391, "num_tokens": 551, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6334102636778401, "lm_q2_score": 0.5312093733737562, "lm_q1q2_score": 0.33647346925681115}}
{"text": "#include \"VisionSolverMPC.h\"\n#include \"../convexMPC/common_types.h\"\n#include \"VisionMPC_interface.h\"\n#include \"VisionRobotState.h\"\n#include <Eigen/Dense>\n#include <cmath>\n#include <unsupported/Eigen/MatrixFunctions>\n#include <qpOASES.hpp>\n#include <stdio.h>\n#include <sys/time.h>\n\n#define V_BIG_NUMBER 5e10\n//big enough to act like infinity, small enough to avoid numerical weirdness.\n\nVisionRobotState v_rs;\nusing std::cout;\nusing std::endl;\nusing Eigen::Dynamic;\n\nMatrix<fpt,Dynamic,13> vA_qp;\nMatrix<fpt,Dynamic,Dynamic> vB_qp;\nMatrix<fpt,13,12> vBdt;\nMatrix<fpt,13,13> vAdt;\nMatrix<fpt,25,25> vABc,v_expmm;\nMatrix<fpt,Dynamic,Dynamic> vS;\nMatrix<fpt,Dynamic,1> vX_d;\nMatrix<fpt,Dynamic,1> vU_b;\nMatrix<fpt,Dynamic,Dynamic> v_fmat;\n\nMatrix<fpt,Dynamic,Dynamic> v_qH;\nMatrix<fpt,Dynamic,1> v_qg;\n\nMatrix<fpt,Dynamic,Dynamic> v_eye_12h;\n\nqpOASES::real_t* vH_qpoases;\nqpOASES::real_t* vg_qpoases;\nqpOASES::real_t* vA_qpoases;\nqpOASES::real_t* vlb_qpoases;\nqpOASES::real_t* vub_qpoases;\nqpOASES::real_t* vq_soln;\n\nqpOASES::real_t* vH_red;\nqpOASES::real_t* vg_red;\nqpOASES::real_t* vA_red;\nqpOASES::real_t* vlb_red;\nqpOASES::real_t* vub_red;\nqpOASES::real_t* vq_red;\nu8 v_real_allocated = 0;\n\n\nchar v_var_elim[2000];\nchar v_con_elim[2000];\n\nmfp* vision_get_q_soln() {\n  return vq_soln;\n}\n\ns8 v_near_zero(fpt a)\n{\n  return (a < 0.01 && a > -.01) ;\n}\n\ns8 v_near_one(fpt a)\n{\n  return v_near_zero(a-1);\n}\nvoid v_matrix_to_real(qpOASES::real_t* dst, Matrix<fpt,Dynamic,Dynamic> src, s16 rows, s16 cols)\n{\n  s32 a = 0;\n  for(s16 r = 0; r < rows; r++)\n  {\n    for(s16 c = 0; c < cols; c++)\n    {\n      dst[a] = src(r,c);\n      a++;\n    }\n  }\n}\n\n\nvoid vision_c2qp(Matrix<fpt,13,13> Ac, Matrix<fpt,13,12> Bc,fpt dt,s16 horizon)\n{\n  vABc.setZero();\n  vABc.block(0,0,13,13) = Ac;\n  vABc.block(0,13,13,12) = Bc;\n  vABc = dt*vABc;\n  v_expmm = vABc.exp();\n  vAdt = v_expmm.block(0,0,13,13);\n  vBdt = v_expmm.block(0,13,13,12);\n  if(horizon > 19) {\n    throw std::runtime_error(\"horizon is too long!\");\n  }\n\n  Matrix<fpt,13,13> powerMats[20];\n  powerMats[0].setIdentity();\n  for(int i = 1; i < horizon+1; i++) {\n    powerMats[i] = vAdt * powerMats[i-1];\n  }\n\n  for(s16 r = 0; r < horizon; r++)\n  {\n    vA_qp.block(13*r,0,13,13) = powerMats[r+1];\n    for(s16 c = 0; c < horizon; c++)\n    {\n      if(r >= c)\n      {\n        s16 a_num = r-c;\n        vB_qp.block(13*r,12*c,13,12) = powerMats[a_num] * vBdt;\n      }\n    }\n  }\n\n}\n\nvoid vision_resize_qp_mats(s16 horizon)\n{\n  int mcount = 0;\n  int h2 = horizon*horizon;\n\n  vA_qp.resize(13*horizon, Eigen::NoChange);\n  mcount += 13*horizon*1;\n\n  vB_qp.resize(13*horizon, 12*horizon);\n  mcount += 13*h2*12;\n\n  vS.resize(13*horizon, 13*horizon);\n  mcount += 13*13*h2;\n\n  vX_d.resize(13*horizon, Eigen::NoChange);\n  mcount += 13*horizon;\n\n  vU_b.resize(20*horizon, Eigen::NoChange);\n  mcount += 20*horizon;\n\n  v_fmat.resize(20*horizon, 12*horizon);\n  mcount += 20*12*h2;\n\n  v_qH.resize(12*horizon, 12*horizon);\n  mcount += 12*12*h2;\n\n  v_qg.resize(12*horizon, Eigen::NoChange);\n  mcount += 12*horizon;\n\n  v_eye_12h.resize(12*horizon, 12*horizon);\n  mcount += 12*12*horizon;\n\n  //printf(\"realloc'd %d floating point numbers.\\n\",mcount);\n  mcount = 0;\n\n  vA_qp.setZero();\n  vB_qp.setZero();\n  vS.setZero();\n  vX_d.setZero();\n  vU_b.setZero();\n  v_fmat.setZero();\n  v_qH.setZero();\n  v_eye_12h.setIdentity();\n\n  //TODO: use realloc instead of free/malloc on size changes\n\n  if(v_real_allocated)\n  {\n\n    free(vH_qpoases);\n    free(vg_qpoases);\n    free(vA_qpoases);\n    free(vlb_qpoases);\n    free(vub_qpoases);\n    free(vq_soln);\n    free(vH_red);\n    free(vg_red);\n    free(vA_red);\n    free(vlb_red);\n    free(vub_red);\n    free(vq_red);\n  }\n\n  vH_qpoases = (qpOASES::real_t*)malloc(12*12*horizon*horizon*sizeof(qpOASES::real_t));\n  mcount += 12*12*h2;\n  vg_qpoases = (qpOASES::real_t*)malloc(12*1*horizon*sizeof(qpOASES::real_t));\n  mcount += 12*horizon;\n  vA_qpoases = (qpOASES::real_t*)malloc(12*20*horizon*horizon*sizeof(qpOASES::real_t));\n  mcount += 12*20*h2;\n  vlb_qpoases = (qpOASES::real_t*)malloc(20*1*horizon*sizeof(qpOASES::real_t));\n  mcount += 20*horizon;\n  vub_qpoases = (qpOASES::real_t*)malloc(20*1*horizon*sizeof(qpOASES::real_t));\n  mcount += 20*horizon;\n  vq_soln = (qpOASES::real_t*)malloc(12*horizon*sizeof(qpOASES::real_t));\n  mcount += 12*horizon;\n\n  vH_red = (qpOASES::real_t*)malloc(12*12*horizon*horizon*sizeof(qpOASES::real_t));\n  mcount += 12*12*h2;\n  vg_red = (qpOASES::real_t*)malloc(12*1*horizon*sizeof(qpOASES::real_t));\n  mcount += 12*horizon;\n  vA_red = (qpOASES::real_t*)malloc(12*20*horizon*horizon*sizeof(qpOASES::real_t));\n  mcount += 12*20*h2;\n  vlb_red = (qpOASES::real_t*)malloc(20*1*horizon*sizeof(qpOASES::real_t));\n  mcount += 20*horizon;\n  vub_red = (qpOASES::real_t*)malloc(20*1*horizon*sizeof(qpOASES::real_t));\n  mcount += 20*horizon;\n  vq_red = (qpOASES::real_t*)malloc(12*horizon*sizeof(qpOASES::real_t));\n  mcount += 12*horizon;\n  v_real_allocated = 1;\n\n  //printf(\"malloc'd %d floating point numbers.\\n\",mcount);\n\n\n\n#ifdef K_DEBUG\n  printf(\"RESIZED MATRICES FOR HORIZON: %d\\n\",horizon);\n#endif\n}\n\ninline Matrix<fpt,3,3> cross_mat(Matrix<fpt,3,3> I_inv, Matrix<fpt,3,1> r)\n{\n  Matrix<fpt,3,3> cm;\n  cm << 0.f, -r(2), r(1),\n     r(2), 0.f, -r(0),\n     -r(1), r(0), 0.f;\n  return I_inv * cm;\n}\n//continuous time state space matrices.\nvoid vision_ct_ss_mats(Matrix<fpt,3,3> vI_world, fpt m, Matrix<fpt,3,4> r_feet, \n    Matrix<fpt,3,3> R_yaw, Matrix<fpt,13,13>& A, Matrix<fpt,13,12>& B, float x_drag)\n{\n  A.setZero();\n  A(3,9) = 1.f;\n  A(9,9) = x_drag;\n  A(4,10) = 1.f;\n  A(5,11) = 1.f;\n\n  A(11,12) = 1.f;\n  A.block(0,6,3,3) = R_yaw.transpose();\n\n  B.setZero();\n  Matrix<fpt,3,3> I_inv = vI_world.inverse();\n\n  for(s16 b = 0; b < 4; b++)\n  {\n    B.block(6,b*3,3,3) = cross_mat(I_inv,r_feet.col(b));\n    B.block(9,b*3,3,3) = Matrix<fpt,3,3>::Identity() / m;\n  }\n}\n\n\nvoid vision_quat_to_rpy(Quaternionf q, Matrix<fpt,3,1>& rpy)\n{\n  //from my MATLAB implementation\n\n  //edge case!\n  fpt as = vision_t_min(-2.*(q.x()*q.z()-q.w()*q.y()),.99999);\n  rpy(0) = atan2(2.f*(q.x()*q.y()+q.w()*q.z()),vision_sq(q.w()) + vision_sq(q.x()) - vision_sq(q.y()) - vision_sq(q.z()));\n  rpy(1) = asin(as);\n  rpy(2) = atan2(2.f*(q.y()*q.z()+q.w()*q.x()),vision_sq(q.w()) - vision_sq(q.x()) - vision_sq(q.y()) + vision_sq(q.z()));\n\n}\n\nMatrix<fpt,13,1> v_x_0;\nMatrix<fpt,3,3> vI_world;\nMatrix<fpt,13,13> vA_ct;\nMatrix<fpt,13,12> vB_ct_r;\n\n\nvoid vision_solve_mpc(vision_mpc_update_data_t* update, vision_mpc_problem_setup* setup)\n{\n  v_rs.set(update->p, update->v, update->q, update->w, update->r, update->yaw);\n\n  //roll pitch yaw\n  Matrix<fpt,3,1> rpy;\n  vision_quat_to_rpy(v_rs.q,rpy);\n\n  //initial state (13 state representation)\n  v_x_0 << rpy(2), rpy(1), rpy(0), v_rs.p , v_rs.w, v_rs.v, -9.8f;\n  vI_world = v_rs.R_yaw * v_rs.I_body * v_rs.R_yaw.transpose(); //original\n  vision_ct_ss_mats(vI_world,v_rs.m,v_rs.r_feet,v_rs.R_yaw,vA_ct,vB_ct_r, update->x_drag);\n\n\n  //QP matrices\n  vision_c2qp(vA_ct,vB_ct_r,setup->dt,setup->horizon);\n\n  //weights\n  Matrix<fpt,13,1> full_weight;\n  for(u8 i = 0; i < 12; i++)\n    full_weight(i) = update->weights[i];\n  full_weight(12) = 0.f;\n  vS.diagonal() = full_weight.replicate(setup->horizon,1);\n\n  //trajectory\n  for(s16 i = 0; i < setup->horizon; i++)\n  {\n    for(s16 j = 0; j < 12; j++)\n      vX_d(13*i+j,0) = update->traj[12*i+j];\n  }\n  //cout<<\"XD:\\n\"<<vX_d<<endl;\n\n\n\n  //note - I'm not doing the shifting here.\n  s16 k = 0;\n  for(s16 i = 0; i < setup->horizon; i++)\n  {\n    for(s16 j = 0; j < 4; j++)\n    {\n      vU_b(5*k + 0) = V_BIG_NUMBER;\n      vU_b(5*k + 1) = V_BIG_NUMBER;\n      vU_b(5*k + 2) = V_BIG_NUMBER;\n      vU_b(5*k + 3) = V_BIG_NUMBER;\n      vU_b(5*k + 4) = update->gait[i*4 + j] * setup->f_max;\n      k++;\n    }\n  }\n\n  fpt mu = 1.f/setup->mu;\n  Matrix<fpt,5,3> f_block;\n\n  f_block <<  mu, 0,  1.f,\n          -mu, 0,  1.f,\n          0,  mu, 1.f,\n          0, -mu, 1.f,\n          0,   0, 1.f;\n\n  for(s16 i = 0; i < setup->horizon*4; i++)\n  {\n    v_fmat.block(i*5,i*3,5,3) = f_block;\n  }\n\n  v_qH = 2*(vB_qp.transpose()*vS*vB_qp + update->alpha*v_eye_12h);\n  v_qg = 2*vB_qp.transpose()*vS*(vA_qp*v_x_0 - vX_d);\n\n\n  v_matrix_to_real(vH_qpoases,v_qH,setup->horizon*12, setup->horizon*12);\n  v_matrix_to_real(vg_qpoases,v_qg,setup->horizon*12, 1);\n  v_matrix_to_real(vA_qpoases,v_fmat,setup->horizon*20, setup->horizon*12);\n  v_matrix_to_real(vub_qpoases,vU_b,setup->horizon*20, 1);\n\n  for(s16 i = 0; i < 20*setup->horizon; i++)\n    vlb_qpoases[i] = 0.0f;\n\n  s16 num_constraints = 20*setup->horizon;\n  s16 num_variables = 12*setup->horizon;\n\n\n  qpOASES::int_t nWSR = 100;\n\n\n  int new_vars = num_variables;\n  int new_cons = num_constraints;\n\n  for(int i =0; i < num_constraints; i++)\n    v_con_elim[i] = 0;\n\n  for(int i = 0; i < num_variables; i++)\n    v_var_elim[i] = 0;\n\n\n  for(int i = 0; i < num_constraints; i++)\n  {\n    if(! (v_near_zero(vlb_qpoases[i]) && v_near_zero(vub_qpoases[i]))) continue;\n    double* c_row = &vA_qpoases[i*num_variables];\n    for(int j = 0; j < num_variables; j++)\n    {\n      if(v_near_one(c_row[j]))\n      {\n        new_vars -= 3;\n        new_cons -= 5;\n        int cs = (j*5)/3 -3;\n        v_var_elim[j-2] = 1;\n        v_var_elim[j-1] = 1;\n        v_var_elim[j  ] = 1;\n        v_con_elim[cs] = 1;\n        v_con_elim[cs+1] = 1;\n        v_con_elim[cs+2] = 1;\n        v_con_elim[cs+3] = 1;\n        v_con_elim[cs+4] = 1;\n      }\n    }\n  }\n  //if(new_vars != num_variables)\n  if(1==1)\n  {\n    int var_ind[new_vars];\n    int v_con_ind[new_cons];\n    int vc = 0;\n    for(int i = 0; i < num_variables; i++)\n    {\n      if(!v_var_elim[i])\n      {\n        if(!(vc<new_vars))\n        {\n          printf(\"BAD ERROR 1\\n\");\n        }\n        var_ind[vc] = i;\n        vc++;\n      }\n    }\n    vc = 0;\n    for(int i = 0; i < num_constraints; i++)\n    {\n      if(!v_con_elim[i])\n      {\n        if(!(vc<new_cons))\n        {\n          printf(\"BAD ERROR 1\\n\");\n        }\n        v_con_ind[vc] = i;\n        vc++;\n      }\n    }\n    for(int i = 0; i < new_vars; i++)\n    {\n      int olda = var_ind[i];\n      vg_red[i] = vg_qpoases[olda];\n      for(int j = 0; j < new_vars; j++)\n      {\n        int oldb = var_ind[j];\n        vH_red[i*new_vars + j] = vH_qpoases[olda*num_variables + oldb];\n      }\n    }\n\n    for (int con = 0; con < new_cons; con++)\n    {\n      for(int st = 0; st < new_vars; st++)\n      {\n        float cval = vA_qpoases[(num_variables*v_con_ind[con]) + var_ind[st] ];\n        vA_red[con*new_vars + st] = cval;\n      }\n    }\n    for(int i = 0; i < new_cons; i++)\n    {\n      int old = v_con_ind[i];\n      vub_red[i] = vub_qpoases[old];\n      vlb_red[i] = vlb_qpoases[old];\n    }\n\n    qpOASES::QProblem problem_red (new_vars, new_cons);\n    qpOASES::Options op;\n    op.setToMPC();\n    op.printLevel = qpOASES::PL_NONE;\n    problem_red.setOptions(op);\n    //int_t nWSR = 50000;\n\n\n    int rval = problem_red.init(vH_red, vg_red, vA_red, NULL, NULL, vlb_red, vub_red, nWSR);\n    (void)rval;\n    int rval2 = problem_red.getPrimalSolution(vq_red);\n    if(rval2 != qpOASES::SUCCESSFUL_RETURN)\n      printf(\"failed to solve!\\n\");\n\n    // printf(\"solve time: %.3f ms, size %d, %d\\n\", solve_timer.getMs(), new_vars, new_cons);\n\n\n    vc = 0;\n    for(int i = 0; i < num_variables; i++)\n    {\n      if(v_var_elim[i])\n      {\n        vq_soln[i] = 0.0f;\n      }\n      else\n      {\n        vq_soln[i] = vq_red[vc];\n        vc++;\n      }\n    }\n  }\n}\n", "meta": {"hexsha": "046be77e3d5494c50397cb3cea0a1b51612e7c00", "size": 11364, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "user/MIT_Controller/Controllers/VisionMPC/VisionSolverMPC.cpp", "max_stars_repo_name": "zbwu/Cheetah-Software", "max_stars_repo_head_hexsha": "286ca1eac576c61df76c71979f4e8940537ee084", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-11-18T03:36:47.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-18T03:36:47.000Z", "max_issues_repo_path": "user/MIT_Controller/Controllers/VisionMPC/VisionSolverMPC.cpp", "max_issues_repo_name": "zbwu/Cheetah-Software", "max_issues_repo_head_hexsha": "286ca1eac576c61df76c71979f4e8940537ee084", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "user/MIT_Controller/Controllers/VisionMPC/VisionSolverMPC.cpp", "max_forks_repo_name": "zbwu/Cheetah-Software", "max_forks_repo_head_hexsha": "286ca1eac576c61df76c71979f4e8940537ee084", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.3340471092, "max_line_length": 122, "alphanum_fraction": 0.6062126012, "num_tokens": 4373, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7057850154599563, "lm_q2_score": 0.47657965106367595, "lm_q1q2_score": 0.3363627763938771}}
{"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 <iostream>\n#include <limits>\n#include <cmath>\n#include \"galois/DistGalois.h\"\n#include \"galois/gstl.h\"\n#include \"DistBenchStart.h\"\n\n#include \"galois/DReducible.h\"\n#include \"galois/AtomicWrapper.h\"\n#include \"galois/ArrayWrapper.h\"\n#include \"galois/runtime/Tracer.h\"\n\n#include \"galois/graphs/DistributedGraphLoader.h\"\n#include <boost/serialization/vector.hpp>\n#include <boost/serialization/array.hpp>\n#include <boost/archive/binary_oarchive.hpp>\n#include <boost/archive/binary_iarchive.hpp>\nusing namespace boost::archive;\n// For resilience\n#include \"resilience.h\"\n\n#ifdef __GALOIS_HET_CUDA__\n#include \"galois/cuda/cuda_device.h\"\n#include \"gen_cuda.h\"\nstruct CUDA_Context* cuda_ctx;\n#endif\n\nconstexpr static const char* const regionname = \"SGD\";\n\n/******************************************************************************/\n/* Declaration of command line arguments */\n/******************************************************************************/\n\nnamespace cll = llvm::cl;\n\nstatic cll::opt<unsigned int>\n    maxIterations(\"maxIterations\",\n                  cll::desc(\"Maximum iterations: Default 10000\"),\n                  cll::init(10000));\nstatic cll::opt<bool> bipartite(\n    \"bipartite\",\n    cll::desc(\"Is graph bipartite? if yes, it expects first N nodes to have \"\n              \"edges.\"),\n    cll::init(false));\nstatic cll::opt<double>\n    LEARNING_RATE(\"LEARNING_RATE\",\n                  cll::desc(\"Learning rate (GAMMA): Default 0.00001\"),\n                  cll::init(0.00001));\nstatic cll::opt<double> LAMBDA(\"LAMBDA\", cll::desc(\"LAMBDA: Default 0.0001\"),\n                               cll::init(0.0001));\nstatic cll::opt<double>\n    DECAY_RATE(\"DECAY_RATE\",\n               cll::desc(\"Decay rate to be used in step size function \"\n                         \"(DECAY_RATE): Default 0.9\"),\n               cll::init(0.9));\nstatic cll::opt<double> tolerance(\n    \"tolerance\",\n    cll::desc(\"rms normalized tolerance for convergence:Default 0.01\"),\n    cll::init(0.01));\n\n/******************************************************************************/\n/* Graph structure declarations + helper functions + other initialization */\n/******************************************************************************/\n\n#define LATENT_VECTOR_SIZE 20\n// static const double LEARNING_RATE = 0.00001; // GAMMA, Purdue: 0.01 Intel:\n// 0.001 static const double DECAY_RATE = 0.9; // STEP_DEC, Purdue: 0.1 Intel:\n// 0.9 static const double LAMBDA = 0.0001; // Purdue: 1.0 Intel: 0.001\nstatic const double MINVAL = -1e+100;\nstatic const double MAXVAL = 1e+100;\n\nconst unsigned int infinity = std::numeric_limits<unsigned int>::max() / 4;\n\nstruct NodeData {\n\n  // galois::CopyableArray<galois::CopyableAtomic<double>, LATENT_VECTOR_SIZE>\n  // residual_latent_vector; galois::CopyableArray<double, LATENT_VECTOR_SIZE>\n  // latent_vector;\n\n  std::vector<double> latent_vector;\n  std::vector<galois::CopyableAtomic<double>> residual_latent_vector;\n\n  template <class Archive>\n  void serialize(Archive& ar, const unsigned int version) {\n    ar& boost::serialization::make_array(latent_vector.data(),\n                                         LATENT_VECTOR_SIZE);\n    // ar & boost::serialization::make_array(residual_latent_vector.data(),\n    // LATENT_VECTOR_SIZE);\n  }\n};\n\ngalois::DynamicBitSet bitset_latent_vector;\ngalois::DynamicBitSet bitset_residual_latent_vector;\n\ntypedef galois::graphs::DistGraph<NodeData, double> Graph;\n// typedef galois::graphs::DistGraph<NodeData, uint32_t> Graph;\ntypedef typename Graph::GraphNode GNode;\n\n#include \"gen_sync.hh\"\n// TODO: Set seed\nstatic double genRand() {\n  // generate a random double in (-1,1)\n  return 2.0 * ((double)std::rand() / (double)RAND_MAX) - 1.0;\n}\n\nstatic double genVal(uint32_t n) {\n  return 2.0 * ((double)n / (double)RAND_MAX) - 1.0;\n}\n\n// Purdue learning function\ndouble getstep_size(unsigned int round) {\n  return LEARNING_RATE * 1.5 / (1.0 + DECAY_RATE * pow(round + 1, 1.5));\n}\n\n/**\n * Prediction of edge weight based on 2 latent vectors\n */\ndouble calcPrediction(const NodeData& movie_data, const NodeData& user_data) {\n  double pred = galois::innerProduct(movie_data.latent_vector,\n                                     user_data.latent_vector, 0.0);\n  double p    = pred;\n\n  pred = std::min(MAXVAL, pred);\n  pred = std::max(MINVAL, pred);\n\n#ifndef NDEBUG\n  if (p != pred)\n    std::cerr << \"clamped \" << p << \" to \" << pred << \"\\n\";\n#endif\n\n  return pred;\n}\n\n/******************************************************************************/\n/* Algorithm structures */\n/******************************************************************************/\n\nstruct InitializeGraph {\n  Graph* graph;\n\n  InitializeGraph(Graph* _graph) : graph(_graph) {}\n\n  void static go(Graph& _graph) {\n    auto& allNodes = _graph.allNodesRange();\n\n#ifdef __GALOIS_HET_CUDA__\n    if (personality == GPU_CUDA) {\n      std::string impl_str(_graph.get_run_identifier(\"InitializeGraph\"));\n      galois::StatTimer StatTimer_cuda(impl_str.c_str());\n      StatTimer_cuda.start();\n      InitializeGraph_cuda(*allNodes.begin(), *allNodes.end(), cuda_ctx);\n      StatTimer_cuda.stop();\n    } else if (personality == CPU)\n#endif\n      galois::do_all(galois::iterate(allNodes.begin(), allNodes.end()),\n                     InitializeGraph{&_graph},\n                     galois::loopname(\"InitializeGraph\"));\n\n    // due to latent_vector being generated randomly, it should be sync'd\n    // to 1 consistent version across all hosts\n    _graph.sync<writeSource, readAny, Reduce_set_latent_vector,\n                Broadcast_latent_vector>(\"InitializeGraph\");\n  }\n\n  void operator()(GNode src) const {\n    NodeData& sdata = graph->getData(src);\n\n    // resize vectors\n    sdata.latent_vector.resize(LATENT_VECTOR_SIZE);\n    sdata.residual_latent_vector.resize(LATENT_VECTOR_SIZE);\n\n    for (int i = 0; i < LATENT_VECTOR_SIZE; i++) {\n      sdata.latent_vector[i] = genVal(src); // randomly create latent vector\n      sdata.residual_latent_vector[i] = 0;  // randomly create latent vector\n\n#ifndef NDEBUG\n      if (!std::isnormal(sdata.latent_vector[i]))\n        galois::gDebug(\"GEN for \", i, \" \", sdata.latent_vector[i]);\n#endif\n    }\n  }\n};\n\nstruct setMasterBitset {\n  Graph* graph;\n\n  setMasterBitset(Graph* _graph) : graph(_graph) {}\n\n  void static go(Graph& _graph) {\n    galois::do_all(galois::iterate(_graph.masterNodesRange().begin(),\n                                   _graph.masterNodesRange().end()),\n                   setMasterBitset{&_graph},\n                   galois::loopname(\"InitializeGraph_crashed_setMasterBiset\"));\n  }\n\n  void operator()(GNode src) const { bitset_latent_vector.set(src); }\n};\n\nstruct InitializeGraph_crashed {\n  Graph* graph;\n\n  InitializeGraph_crashed(Graph* _graph) : graph(_graph) {}\n\n  void static go(Graph& _graph) {\n\n    setMasterBitset::go(_graph);\n\n    auto& allNodes = _graph.allNodesRange();\n\n#ifdef __GALOIS_HET_CUDA__\n    if (personality == GPU_CUDA) {\n      std::string impl_str(_graph.get_run_identifier(\"InitializeGraph\"));\n      galois::StatTimer StatTimer_cuda(impl_str.c_str());\n      StatTimer_cuda.start();\n      InitializeGraph_cuda(*allNodes.begin(), *allNodes.end(), cuda_ctx);\n      StatTimer_cuda.stop();\n    } else if (personality == CPU)\n#endif\n      galois::do_all(galois::iterate(allNodes.begin(), allNodes.end()),\n                     InitializeGraph_crashed{&_graph},\n                     galois::loopname(\"InitializeGraph_crashed\"));\n\n    _graph.sync<writeAny, readAny, Reduce_set_latent_vector,\n                Broadcast_latent_vector, Bitset_latent_vector>(\n        \"InitializeGraph_crashed\");\n  }\n\n  void operator()(GNode src) const {\n    NodeData& sdata = graph->getData(src);\n\n    // resize vectors\n    sdata.latent_vector.resize(LATENT_VECTOR_SIZE);\n    sdata.residual_latent_vector.resize(LATENT_VECTOR_SIZE);\n\n    for (int i = 0; i < LATENT_VECTOR_SIZE; i++) {\n      sdata.latent_vector[i] = genVal(src); // randomly create latent vector\n      sdata.residual_latent_vector[i] = 0;  // randomly create latent vector\n\n#ifndef NDEBUG\n      if (!std::isnormal(sdata.latent_vector[i]))\n        galois::gDebug(\"GEN for \", i, \" \", sdata.latent_vector[i]);\n#endif\n    }\n  }\n};\n\nstruct InitializeGraph_healthy {\n  Graph* graph;\n\n  InitializeGraph_healthy(Graph* _graph) : graph(_graph) {}\n\n  void static go(Graph& _graph) {\n    auto& allNodes = _graph.allNodesRange();\n\n#ifdef __GALOIS_HET_CUDA__\n    if (personality == GPU_CUDA) {\n      std::string impl_str(_graph.get_run_identifier(\"InitializeGraph\"));\n      galois::StatTimer StatTimer_cuda(impl_str.c_str());\n      StatTimer_cuda.start();\n      InitializeGraph_cuda(*allNodes.begin(), *allNodes.end(), cuda_ctx);\n      StatTimer_cuda.stop();\n    } else if (personality == CPU)\n#endif\n      galois::do_all(galois::iterate(allNodes.begin(), allNodes.end()),\n                     InitializeGraph_healthy{&_graph},\n                     galois::loopname(\"InitializeGraph_healthy\"));\n\n    _graph.sync<writeAny, readAny, Reduce_set_latent_vector,\n                Broadcast_latent_vector, Bitset_latent_vector>(\n        \"InitializeGraph_healthy\");\n  }\n\n  void operator()(GNode src) const {\n    NodeData& sdata = graph->getData(src);\n\n    for (int i = 0; i < LATENT_VECTOR_SIZE; i++) {\n      sdata.residual_latent_vector[i] = 0; // randomly create latent vector\n    }\n    bitset_latent_vector.set(src);\n  }\n};\n\n/* Recovery to be called by resilience based fault tolerance\n * It is a NoOp\n */\nstruct recovery {\n  Graph* graph;\n\n  recovery(Graph* _graph) : graph(_graph) {}\n\n  void static go(Graph& _graph) {}\n};\n\nstruct SGD_mergeResidual {\n  Graph* graph;\n\n  SGD_mergeResidual(Graph* _graph) : graph(_graph) {}\n\n  void static go(Graph& _graph) {\n\n    auto& allNodes = _graph.allNodesRange();\n\n#ifdef __GALOIS_HET_CUDA__\n    if (personality == GPU_CUDA) {\n      std::string impl_str(\"SGD_\" + (_graph.get_run_identifier()));\n      galois::StatTimer StatTimer_cuda(impl_str.c_str());\n      StatTimer_cuda.start();\n      int __retval = 0;\n      SGD_all_cuda(__retval, cuda_ctx);\n      // DGAccumulator_accum += __retval;\n      StatTimer_cuda.stop();\n    } else if (personality == CPU)\n#endif\n\n      galois::do_all(\n          galois::iterate(allNodes.begin(), allNodes.end()),\n          SGD_mergeResidual{&_graph},\n          galois::loopname(_graph.get_run_identifier(\"SGD_merge\").c_str()),\n          galois::steal(), galois::no_stats());\n  }\n\n  void operator()(GNode src) const {\n    NodeData& sdata              = graph->getData(src);\n    auto& latent_vector          = sdata.latent_vector;\n    auto& residual_latent_vector = sdata.residual_latent_vector;\n\n    for (int i = 0; i < LATENT_VECTOR_SIZE; ++i) {\n      latent_vector[i] += residual_latent_vector[i];\n      residual_latent_vector[i] = 0;\n\n#ifndef NDEBUG\n      if (!std::isnormal(sdata.latent_vector[i]))\n        galois::gDebug(\"GEN for \", i, \" \", sdata.latent_vector[i]);\n#endif\n    }\n  }\n};\n\nstruct SGD {\n  Graph* graph;\n  double step_size;\n  galois::DGAccumulator<double>& DGAccumulator_accum;\n\n  SGD(Graph* _graph, double _step_size, galois::DGAccumulator<double>& _dga)\n      : graph(_graph), step_size(_step_size), DGAccumulator_accum(_dga) {}\n\n  void static go(Graph& _graph, galois::DGAccumulator<double>& dga) {\n    unsigned _num_iterations              = 0;\n    unsigned _num_iterations_stepSize     = 0;\n    unsigned _num_iterations_checkpointed = 0;\n    double rms_normalized                 = 0.0;\n    double last                           = -1.0;\n    double last_checkpointed              = -1.0;\n    auto& nodesWithEdges                  = _graph.allNodesWithEdgesRange();\n    do {\n      // Checkpointing the all the node data\n      if (enableFT && recoveryScheme == CP) {\n        saveCheckpointToDisk(_num_iterations, _graph);\n        // Saving other state variables\n        if (_num_iterations % checkpointInterval == 0) {\n          last_checkpointed            = last;\n          _num_iterations_checkpointed = _num_iterations;\n        }\n      }\n\n      auto step_size = getstep_size(_num_iterations_stepSize);\n      dga.reset();\n      galois::do_all(galois::iterate(nodesWithEdges),\n                     SGD(&_graph, step_size, dga),\n                     galois::loopname(_graph.get_run_identifier(\"SGD\").c_str()),\n                     galois::steal(), galois::no_stats());\n\n      _graph.sync<writeDestination, readAny,\n                  Reduce_pair_wise_add_array_residual_latent_vector,\n                  Broadcast_residual_latent_vector,\n                  Bitset_residual_latent_vector>(\"SGD\");\n\n      SGD_mergeResidual::go(_graph);\n\n      /**************************CRASH SITE : start\n       * *****************************************/\n      if (enableFT && (_num_iterations == crashIteration)) {\n        crashSite<recovery, InitializeGraph_crashed, InitializeGraph_healthy>(\n            _graph);\n        ++_num_iterations;\n        if (recoveryScheme == CP) {\n          _num_iterations_stepSize = _num_iterations_checkpointed;\n          last                     = last_checkpointed;\n        }\n\n        continue;\n      }\n      /**************************CRASH SITE : end\n       * *****************************************/\n\n      // calculate root mean squared error\n      // Divide by 2 since for symmetric graph it is counted twice\n      double error   = dga.reduce() / 2;\n      rms_normalized = std::sqrt(error / _graph.globalSizeEdges());\n\n      double error_change = std::abs((last - error) / last);\n      if (galois::runtime::getSystemNetworkInterface().ID == 0) {\n        galois::gPrint(\"ITERATION : \", _num_iterations, \"\\n\");\n        galois::gDebug(\"RMS Normalized : \", rms_normalized);\n        galois::gPrint(\"RMS : \", rms_normalized, \"\\n\");\n        galois::gPrint(\"abs(last - error/last) : \", error_change, \"\\n\");\n      }\n\n      if (error_change < tolerance) {\n        break;\n      }\n      last = error;\n      ++_num_iterations;\n      ++_num_iterations_stepSize;\n    } while ((_num_iterations < maxIterations));\n\n    if (galois::runtime::getSystemNetworkInterface().ID == 0) {\n      galois::runtime::reportStat_Single(\n          regionname, \"NumIterations_\" + std::to_string(_graph.get_run_num()),\n          (unsigned long)_num_iterations);\n    }\n  }\n\n  void operator()(GNode src) const {\n    NodeData& sdata           = graph->getData(src);\n    auto& movie_node          = sdata.latent_vector;\n    auto& residual_movie_node = sdata.residual_latent_vector;\n\n    for (auto jj = graph->edge_begin(src), ej = graph->edge_end(src); jj != ej;\n         ++jj) {\n      GNode dst   = graph->getEdgeDst(jj);\n      auto& ddata = graph->getData(dst);\n\n      auto& user_node          = ddata.latent_vector;\n      auto& residual_user_node = ddata.residual_latent_vector;\n      // auto& sdata_up = sdata.updates;\n\n      double edge_rating = graph->getEdgeData(jj);\n\n      // doGradientUpdate\n      double old_dp = galois::innerProduct(user_node, movie_node, double(0));\n\n      double cur_error = edge_rating - old_dp;\n      DGAccumulator_accum += (cur_error * cur_error);\n\n      assert(cur_error < 10000 && cur_error > -10000);\n\n      bool setBit = false;\n      // update both vectors based on error derived from 2 previous vectors\n      for (int i = 0; i < LATENT_VECTOR_SIZE; ++i) {\n\n        double prevUser  = user_node[i];\n        double prevMovie = movie_node[i];\n\n        // Only update the destination\n        galois::atomicAdd(\n            residual_user_node[i],\n            double(step_size * (cur_error * prevMovie - LAMBDA * prevUser)));\n        // galois::gPrint(\"val : \", residual_user_node[i], \"\\n\");\n        assert(std::isnormal(residual_user_node[i]));\n        if (!setBit && std::abs(residual_user_node[i]) > 0.1)\n          setBit = true;\n\n        // galois::atomicAdd(residual_movie_node[i],  double(step_size *\n        // (cur_error * prevUser - LAMBDA * prevMovie)));\n        // assert(std::isnormal(residual_movie_node[i]));\n      }\n      if (setBit)\n        bitset_residual_latent_vector.set(dst);\n    }\n  }\n};\n\n/******************************************************************************/\n/* Main */\n/******************************************************************************/\nconstexpr static const char* const name = \"SGD - Distributed Heterogeneous\";\nconstexpr static const char* const desc = \"SGD on Distributed Galois.\";\nconstexpr static const char* const url  = 0;\n\nint main(int argc, char** argv) {\n  galois::DistMemSys G;\n  DistBenchStart(argc, argv, name, desc, url);\n\n  const auto& net = galois::runtime::getSystemNetworkInterface();\n  if (net.ID == 0) {\n    galois::runtime::reportParam(regionname, \"Max Iterations\",\n                                 (unsigned long)maxIterations);\n\n    galois::runtime::reportParam(regionname, \"ENABLE_FT\", (enableFT));\n  }\n\n  galois::StatTimer StatTimer_total(\"TimerTotal\", regionname);\n\n  StatTimer_total.start();\n#ifdef __GALOIS_HET_CUDA__\n  Graph* hg = distGraphInitialization<NodeData, double>(&cuda_ctx);\n#else\n  Graph* hg = distGraphInitialization<NodeData, double>();\n#endif\n\n  // bitset comm setup\n  bitset_latent_vector.resize(hg->size());\n  bitset_residual_latent_vector.resize(hg->size());\n\n  galois::gPrint(\"[\", net.ID, \"] InitializeGraph::go called\\n\");\n\n  galois::StatTimer StatTimer_init(\"TIMER_GRAPH_INIT\", regionname);\n  StatTimer_init.start();\n  InitializeGraph::go((*hg));\n  StatTimer_init.stop();\n\n  galois::runtime::getHostBarrier().wait();\n\n  // accumulators for use in operators\n  galois::DGAccumulator<double> DGAccumulator_accum;\n  // galois::DGAccumulator<uint64_t> DGAccumulator_sum;\n  // galois::DGAccumulator<uint32_t> DGAccumulator_max;\n  // galois::GReduceMax<uint32_t> m;\n\n  for (auto run = 0; run < numRuns; ++run) {\n    galois::gPrint(\"[\", net.ID, \"] SGD::go run \", run, \" called\\n\");\n    std::string timer_str(\"Timer_\" + std::to_string(run));\n    galois::StatTimer StatTimer_main(timer_str.c_str(), regionname);\n\n    StatTimer_main.start();\n    SGD::go((*hg), DGAccumulator_accum);\n    StatTimer_main.stop();\n\n    if ((run + 1) != numRuns) {\n#ifdef __GALOIS_HET_CUDA__\n      if (personality == GPU_CUDA) {\n        // bitset_dist_current_reset_cuda(cuda_ctx);\n      } else\n#endif\n        bitset_latent_vector.reset();\n      bitset_residual_latent_vector.reset();\n\n      (*hg).set_num_run(run + 1);\n      InitializeGraph::go((*hg));\n      galois::runtime::getHostBarrier().wait();\n    }\n  }\n\n  StatTimer_total.stop();\n\n  return 0;\n}\n", "meta": {"hexsha": "8150ec37f826d6c4f012eaaad5e432b324c14799", "size": 19485, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "dist_apps/experimental/resilience/sgd_pull/gen.cpp", "max_stars_repo_name": "vancemiller/Galois", "max_stars_repo_head_hexsha": "e462b92888c073f765e5bc1b77100ccc668fc716", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "dist_apps/experimental/resilience/sgd_pull/gen.cpp", "max_issues_repo_name": "vancemiller/Galois", "max_issues_repo_head_hexsha": "e462b92888c073f765e5bc1b77100ccc668fc716", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "dist_apps/experimental/resilience/sgd_pull/gen.cpp", "max_forks_repo_name": "vancemiller/Galois", "max_forks_repo_head_hexsha": "e462b92888c073f765e5bc1b77100ccc668fc716", "max_forks_repo_licenses": ["BSD-3-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.3045774648, "max_line_length": 85, "alphanum_fraction": 0.6333589941, "num_tokens": 4834, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6150878696277513, "lm_q2_score": 0.5467381519846138, "lm_q1q2_score": 0.33629200514842983}}
{"text": "#define BIORBD_API_EXPORTS\n#include \"RigidBody/Integrator.h\"\n\n#include <Eigen/Dense>\n#include <boost/numeric/odeint.hpp>\n#include <rbdl/Dynamics.h>\n#include \"Utils/Error.h\"\n#include \"Utils/String.h\"\n#include \"RigidBody/GeneralizedCoordinates.h\"\n#include \"RigidBody/Joints.h\"\n\nbiorbd::rigidbody::Integrator::Integrator() :\n    m_nbre(std::shared_ptr<unsigned int>()),\n    m_steps(std::shared_ptr<unsigned int>()),\n    m_model(std::shared_ptr<RigidBodyDynamics::Model>()),\n    m_x_vec(std::shared_ptr<std::vector<state_type>>()),\n    m_times(std::shared_ptr<std::vector<double>>()),\n    m_u(std::shared_ptr<biorbd::utils::Vector>())\n\n{\n\n}\n\nbiorbd::rigidbody::Integrator biorbd::rigidbody::Integrator::DeepCopy() const\n{\n    biorbd::rigidbody::Integrator copy;\n    copy.DeepCopy(*this);\n    return copy;\n}\n\nvoid biorbd::rigidbody::Integrator::DeepCopy(const biorbd::rigidbody::Integrator &other)\n{\n    *m_nbre = *other.m_nbre;\n    *m_steps = *other.m_steps;\n    *m_model = *other.m_model;\n    m_x_vec->resize(other.m_x_vec->size());\n    for (unsigned int i=0; i<other.m_x_vec->size(); ++i)\n        (*m_x_vec)[i] = (*other.m_x_vec)[i];\n    m_times->resize(other.m_times->size());\n    for (unsigned int i=0; i<other.m_times->size(); ++i)\n        (*m_times)[i] = (*other.m_times)[i];\n    *m_u = *other.m_u;\n}\n\nvoid biorbd::rigidbody::Integrator::operator() (\n        const state_type &x ,\n        state_type &dxdt ,\n        double ){\n    // Équation différentielle : x/xdot => xdot/xddot\n    biorbd::rigidbody::GeneralizedCoordinates Q(*m_nbre);\n    biorbd::rigidbody::GeneralizedCoordinates QDot(*m_nbre);\n    biorbd::rigidbody::GeneralizedCoordinates QDDot(biorbd::utils::Vector(*m_nbre).setZero());\n    for (unsigned int i=0; i<*m_nbre; i++){\n        Q(i) = x[i];\n        QDot(i) = x[i+*m_nbre];\n    }\n\n    RigidBodyDynamics::ForwardDynamics (*m_model, Q, QDot, *m_u, QDDot);\n\n    // Faire sortir xdot/xddot\n    for (unsigned int i=0; i<*m_nbre; i++){\n        dxdt[i] = QDot[i];\n        dxdt[i + *m_nbre] = QDDot[i];\n    }\n\n}\n\nvoid biorbd::rigidbody::Integrator::showAll(){\n    std::cout << \"Test:\" << std::endl;\n    for (unsigned int i=0; i<=*m_steps; i++){\n        std::cout << (*m_times)[i];\n        for (unsigned int j=0; j<*m_nbre; j++)\n            std::cout << \" \" << (*m_x_vec)[i][j];\n        std::cout << std::endl;\n    }\n}\n\nunsigned int biorbd::rigidbody::Integrator::steps() const\n{\n    return *m_steps+1;\n}\n\nbiorbd::utils::Vector biorbd::rigidbody::Integrator::getX(\n        unsigned int idx){\n    biorbd::utils::Vector out(*m_nbre*2);\n    biorbd::utils::Error::check(idx <= *m_steps, \"Trying to get Q outside range\");\n    for (unsigned int i=0; i<*m_nbre*2; i++){\n        out(i) = (*m_x_vec)[idx][i];\n        }\n    return out;\n}\n\nvoid biorbd::rigidbody::Integrator::integrate(\n        biorbd::rigidbody::Joints& model,\n        const biorbd::utils::Vector &Q_Qdot,\n        const biorbd::utils::Vector &u,\n        double t0,\n        double tend,\n        double timeStep){\n    // Stocker le nombre d'élément à traiter\n    *m_nbre = static_cast<unsigned int>(Q_Qdot.rows())/2; // Q et Qdot\n    *m_u = u; // Copier les effecteurs\n    *m_model = model;\n\n    // Remplissage de la variable par les positions et vitesse\n    state_type x(*m_nbre*2);\n    for (unsigned int i=0; i<*m_nbre*2; i++)\n        x[i] = Q_Qdot(i);\n\n    // Choix de l'algorithme et intégration\n    boost::numeric::odeint::runge_kutta4< state_type > stepper;\n    *m_steps = static_cast<unsigned int>(boost::numeric::odeint::integrate_const( stepper, (*this), x, t0, tend, timeStep, push_back_state_and_time( *m_x_vec , *m_times )));\n}\n", "meta": {"hexsha": "5f559f1fe23e4c971e7fda96faa04aaac6dad4ca", "size": 3605, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/RigidBody/Integrator.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/RigidBody/Integrator.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/RigidBody/Integrator.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": 31.6228070175, "max_line_length": 173, "alphanum_fraction": 0.6327323162, "num_tokens": 1140, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6723317123102955, "lm_q2_score": 0.5, "lm_q1q2_score": 0.33616585615514777}}
{"text": "#pragma once\n#include \"arpackdef.h\"\n\n#include <Eigen/Dense>\n#include <random>\n#include <vector>\n\nextern \"C\"\n{\n    void dsaupd_(a_int*, const char*, a_int*, const char*, a_int*, double*, double*, a_int*,\n                 double*, a_int*, a_int*, a_int*, double*, double*, a_int*, a_int*);\n\n    void dseupd_(a_int* rvec, const char* howmny, a_int* select, double* d, double* z, a_int* ldz,\n                 double* sigma, const char* bmat, a_int* n, const char* which, a_int* nev,\n                 double* tol, double* resid, a_int* ncv, double* v, a_int* ldv, a_int* iparam,\n                 a_int* inptr, double* workd, double* workl, a_int* lworkl, a_int* info);\n}\n\nnamespace edlib\n{\nenum class ErrorType\n{\n    NormalExit,\n    NotConverged,\n    IncorrectParams,\n    Others\n};\n\ntemplate<typename MatrixVectorOp> class ArpackSolver\n{\nprivate:\n    MatrixVectorOp& op_;\n    const a_int dim_;\n    std::vector<double> d_;\n    std::vector<double> z_;\n\npublic:\n    explicit ArpackSolver(MatrixVectorOp& op) : op_{op}, dim_{static_cast<a_int>(op.rows())}\n    {\n        assert(op.rows() == op.cols());\n    }\n\n    ErrorType solve(a_int nev, uint32_t max_iter = 1024, double tol = 1e-10)\n    {\n        a_int dim = dim_;\n        if(dim <= 0 || nev <= 0)\n        {\n            return ErrorType::IncorrectParams;\n        }\n\n        a_int ido = 0;\n        const char* bmat = \"I\";\n        a_int n = dim;\n        const char* which = \"SA\";\n        std::vector<double> resid(dim);\n\n        a_int ncv = 3 * nev;\n        std::vector<double> v(static_cast<size_t>(ncv * dim));\n\n        a_int ldv = dim;\n        std::array<a_int, 11> iparam = {\n            1, // ishift\n            0, // levec (not used)\n            static_cast<a_int>(max_iter), // maxiter\n            1, // nb\n            0, // nconv\n            0, // iupd (not used)\n            1, // mode (1 is usual eigenvalue problem)\n            0, // np\n            0,\n            0,\n            0 // only for output\n        };\n\n        std::array<a_int, 14> ipntr{};\n        std::vector<double> workd(3 * static_cast<size_t>(dim), 0.);\n\n        int lworkl = 3 * ncv * ncv + 6 * ncv;\n        std::vector<double> workl(lworkl, 0);\n\n        a_int info = 0;\n\n        // first call\n        dsaupd_(&ido, bmat, &n, which, &nev, &tol, resid.data(), &ncv, v.data(), &ldv,\n                iparam.data(), ipntr.data(), workd.data(), workl.data(), &lworkl, &info);\n\n        while(ido == -1 || ido == 1)\n        {\n            op_.perform_op(workd.data() + ipntr[0] - 1, workd.data() + ipntr[1] - 1);\n\n            dsaupd_(&ido, bmat, &n, which, &nev, &tol, resid.data(), &ncv, v.data(), &ldv,\n                    iparam.data(), ipntr.data(), workd.data(), workl.data(), &lworkl, &info);\n        }\n\n        if(info == 1 || iparam[4] != nev)\n        {\n            return ErrorType::NotConverged;\n        }\n        else if(info != 0)\n        {\n            return ErrorType::IncorrectParams;\n        }\n\n        a_int rvec = 1;\n\n        d_.resize(nev + 1);\n        z_.resize(static_cast<size_t>(dim + 1) * static_cast<size_t>(nev + 1));\n        a_int ldz = dim + 1;\n        double sigma = 0.0;\n\n        std::vector<a_int> select(ncv);\n        std::fill(select.begin(), select.end(), 1);\n\n        const char* howmny = \"All\";\n        dseupd_(&rvec, howmny, select.data(), d_.data(), z_.data(), &ldz, &sigma, bmat, &n, which,\n                &nev, &tol, resid.data(), &ncv, v.data(), &ldv, iparam.data(), ipntr.data(),\n                workd.data(), workl.data(), &lworkl, &info);\n\n        return ErrorType::NormalExit;\n    }\n\n    [[nodiscard]] auto eigenvalues() const -> Eigen::Map<const Eigen::VectorXd>\n    {\n        return {d_.data(), static_cast<Eigen::Index>(d_.size() - 1)};\n    }\n\n    [[nodiscard]] auto eigenvectors() const\n        -> Eigen::Map<const Eigen::MatrixXd, 0, Eigen::OuterStride<Eigen::Dynamic>>\n    {\n        return {z_.data(), dim_, static_cast<Eigen::Index>(d_.size() - 1), {dim_ + 1}};\n    }\n};\n} // namespace edlib\n", "meta": {"hexsha": "11a8265f00ebb88abc4053090a876d98a4338821", "size": 3957, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/edlib/Solver/ArpackSolver.hpp", "max_stars_repo_name": "cecri/ExactDiagonalization", "max_stars_repo_head_hexsha": "a168ed2f60149b1c3e5bd9ae46a5d169aea76773", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/edlib/Solver/ArpackSolver.hpp", "max_issues_repo_name": "cecri/ExactDiagonalization", "max_issues_repo_head_hexsha": "a168ed2f60149b1c3e5bd9ae46a5d169aea76773", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/edlib/Solver/ArpackSolver.hpp", "max_forks_repo_name": "cecri/ExactDiagonalization", "max_forks_repo_head_hexsha": "a168ed2f60149b1c3e5bd9ae46a5d169aea76773", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.5298507463, "max_line_length": 98, "alphanum_fraction": 0.5294414961, "num_tokens": 1200, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.672331699179286, "lm_q2_score": 0.5, "lm_q1q2_score": 0.336165849589643}}
{"text": "#ifndef GUNEROTRANSACTIONRECEIVECIRCUIT_H_\n#define GUNEROTRANSACTIONRECEIVECIRCUIT_H_\n\n#include <deque>\n#include <boost/optional.hpp>\n#include <boost/static_assert.hpp>\n#include <libff/common/utils.hpp>\n#include <libsnark/common/default_types/r1cs_gg_ppzksnark_pp.hpp>\n#include <libsnark/common/default_types/r1cs_gg_ppzksnark_pp.hpp>\n#include <libsnark/relations/constraint_satisfaction_problems/r1cs/examples/r1cs_examples.hpp>\n#include <libsnark/zk_proof_systems/ppzksnark/r1cs_gg_ppzksnark/r1cs_gg_ppzksnark.hpp>\n#include <libsnark/zk_proof_systems/ppzksnark/r1cs_ppzksnark/r1cs_ppzksnark.hpp>\n#include <libsnark/zk_proof_systems/ppzksnark/uscs_ppzksnark/uscs_ppzksnark.hpp>\n#include <libff/algebra/fields/field_utils.hpp>\n#include <libff/algebra/scalar_multiplication/multiexp.hpp>\n#include <libsnark/common/default_types/r1cs_ppzksnark_pp.hpp>\n#include <libsnark/zk_proof_systems/ppzksnark/r1cs_ppzksnark/r1cs_ppzksnark.hpp>\n#include <libff/algebra/curves/edwards/edwards_pp.hpp>\n#include <libff/algebra/curves/mnt/mnt4/mnt4_pp.hpp>\n#include <libff/algebra/curves/mnt/mnt6/mnt6_pp.hpp>\n#include <libff/common/utils.hpp>\n\n#include <libsnark/gadgetlib1/gadgets/merkle_tree/merkle_tree_check_read_gadget.hpp>\n#include <libsnark/gadgetlib1/gadgets/merkle_tree/merkle_tree_check_update_gadget.hpp>\n\n#include \"gunerotransactionreceive_gadget.hpp\"\n#include \"GuneroProof.hpp\"\n\nusing namespace libsnark;\n\nnamespace gunero {\n\nclass GuneroTransactionReceiveWitness{\npublic:\n    uint256 W;\n    uint256 T;\n    uint256 V_S;\n    uint256 V_R;\n    uint256 L;\n\n    GuneroTransactionReceiveWitness() {}\n    GuneroTransactionReceiveWitness(\n        const uint256& pW,\n        const uint256& pT,\n        const uint256& pV_S,\n        const uint256& pV_R,\n        const uint256& pL\n    ) : W(pW),\n        T(pT),\n        V_S(pV_S),\n        V_R(pV_R),\n        L(pL)\n    {\n    }\n    ~GuneroTransactionReceiveWitness() {}\n\n    ADD_SERIALIZE_METHODS;\n\n    template <typename Stream, typename Operation>\n    inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) {\n        READWRITE(W);\n        READWRITE(T);\n        READWRITE(V_S);\n        READWRITE(V_R);\n        READWRITE(L);\n    }\n\n    friend std::ostream& operator<<(std::ostream &out, const GuneroTransactionReceiveWitness &witness)\n    {\n        ::Serialize(out, witness, 1, 1);\n\n        return out;\n    }\n\n    friend std::istream& operator>>(std::istream &in, GuneroTransactionReceiveWitness &witness)\n    {\n        ::Unserialize(in, witness, 1, 1);\n\n        return in;\n    }\n};\n\n///// TRANSACTION RECEIVE PROOF /////\n// Public Parameters:\n// Authorization Root Hash (W)\n// Token UID (T)\n// Sender Account View Hash (V_S)\n// Receiver Account View Hash (V_R)\n// Current Transaction Hash (L)\n\n// Private Parameters:\n// Receiver Account Secret Key (s_R)\n// Receiver Account View Randomizer (r_R)\n// Sender Account Address (A_S)\n// Sender Account View Randomizer (r_S)\n// Firearm Serial Number (F)\n// Firearm View Randomizer (j)\n// alt: Receiver Account (A_R)\n// alt: Sender Proof Public Key (P_proof_S)\n\n//1) Obtain A_R from s_R through EDCSA operations\n//1 alt) Obtain P_proof_R from s_R through PRF operations\n//2) Validate V_S == hash(A_S, hash(W, r_S)) (View Hash is consistent for Sender)\n//2 alt) Validate V_S == hash(P_proof_S, hash(W, r_S)) (View Hash is consistent for Sender)\n//3) Validate V_R == hash(A_R, hash(W, r_R) (View Hash is consistent for Receiver)\n//3 alt) Validate V_R == hash(P_proof_R, hash(W, r_R)) (View Hash is consistent for Receiver)\n//4) Validate T == hash(F, j) (Both parties know the serial number)\n//5) Validate L == hash(A_S, hash(s_R, hash(T, W)) (The send proof is consistent, not forged)\ntemplate<typename FieldT, typename BaseT, typename HashT>\nclass GuneroTransactionReceiveCircuit\n{\npublic:\n    GuneroTransactionReceiveCircuit()\n    {}\n    ~GuneroTransactionReceiveCircuit() {}\n\n    void generate(\n        const std::string& r1csPath,\n        const std::string& pkPath,\n        const std::string& vkPath\n    ) {\n        protoboard<FieldT> pb;\n        gunerotransactionreceive_gadget<FieldT, BaseT, HashT> gunero(pb);\n\n        gunero.generate_r1cs_constraints(r1csPath, pkPath, vkPath);\n    }\n\n    bool prove(\n        const uint256& pW,\n        const uint256& pT,\n        const uint256& pV_S,\n        const uint256& pV_R,\n        const uint256& pL,\n        const uint252& ps_R,\n        const uint256& pr_R,\n        const uint160& pA_S,\n        const uint256& pr_S,\n        const uint256& pF,\n        const uint256& pj,\n        const uint160& pA_R,\n        const uint256& pP_proof_S,\n        const r1cs_ppzksnark_proving_key<BaseT>& pk,\n        const r1cs_ppzksnark_verification_key<BaseT>& vk,\n        GuneroProof& proof\n    )\n    {\n#ifdef DEBUG\n        libff::print_header(\"Gunero witness (proof)\");\n#endif\n\n        {\n            r1cs_primary_input<FieldT> primary_input;\n            r1cs_auxiliary_input<FieldT> aux_input;\n            {\n                protoboard<FieldT> pb;\n                {\n#ifdef DEBUG\n                    libff::print_header(\"Gunero gunerotransactionreceive_gadget.load_r1cs_constraints()\");\n#endif\n\n                    gunerotransactionreceive_gadget<FieldT, BaseT, HashT> gunero(pb);\n\n                    gunero.generate_r1cs_witness(\n                        pW,\n                        pT,\n                        pV_S,\n                        pV_R,\n                        pL,\n                        ps_R,\n                        pr_R,\n                        pA_S,\n                        pr_S,\n                        pF,\n                        pj,\n                        pA_R,\n                        pP_proof_S\n                    );\n\n#ifdef DEBUG\n                    printf(\"\\n\"); libff::print_indent(); libff::print_mem(\"after gunerotransactionreceive_gadget.load_r1cs_constraints()\"); libff::print_time(\"after gunerotransactionreceive_gadget.load_r1cs_constraints()\");\n#endif\n                }\n\n                // The constraint system must be satisfied or there is an unimplemented\n                // or incorrect sanity check above. Or the constraint system is broken!\n                assert(pb.is_satisfied());\n\n                // TODO: These are copies, which is not strictly necessary.\n                primary_input = pb.primary_input();\n                aux_input = pb.auxiliary_input();\n\n                // Swap A and B if it's beneficial (less arithmetic in G2)\n                // In our circuit, we already know that it's beneficial\n                // to swap, but it takes so little time to perform this\n                // estimate that it doesn't matter if we check every time.\n                // pb.constraint_system.swap_AB_if_beneficial();\n\n                //Test witness_map()\n                {\n                    r1cs_primary_input<FieldT> primary_input_test = gunerotransactionreceive_gadget<FieldT, BaseT, HashT>::witness_map(\n                        pW,\n                        pT,\n                        pV_S,\n                        pV_R,\n                        pL\n                    );\n                    assert(primary_input == primary_input_test);\n                }\n            }\n\n            r1cs_ppzksnark_proof<BaseT> r1cs_proof = r1cs_ppzksnark_prover<BaseT>(\n                pk,\n                primary_input,\n                aux_input\n            );\n\n            proof = GuneroProof(r1cs_proof);\n\n#ifdef DEBUG\n            printf(\"\\n\"); libff::print_indent(); libff::print_mem(\"after witness (proof)\"); libff::print_time(\"after witness (proof)\");\n#endif\n        }\n\n        //Verify\n        {\n            r1cs_primary_input<FieldT> primary_input = gunerotransactionreceive_gadget<FieldT, BaseT, HashT>::witness_map(\n                pW,\n                pT,\n                pV_S,\n                pV_R,\n                pL\n            );\n\n            return r1cs_ppzksnark_verifier_strong_IC<BaseT>(vk, primary_input, proof.to_libsnark_proof<r1cs_ppzksnark_proof<BaseT>>());\n        }\n    }\n\n    bool verify(\n        const uint256& pW,\n        const uint256& pT,\n        const uint256& pV_S,\n        const uint256& pV_R,\n        const uint256& pL,\n        const GuneroProof& proof,\n        const r1cs_ppzksnark_verification_key<BaseT>& vk,\n        const r1cs_ppzksnark_processed_verification_key<BaseT>& vk_precomp\n        )\n    {\n        try\n        {\n            r1cs_primary_input<FieldT> primary_input = gunerotransactionreceive_gadget<FieldT, BaseT, HashT>::witness_map(\n                pW,\n                pT,\n                pV_S,\n                pV_R,\n                pL\n            );\n\n            r1cs_ppzksnark_proof<BaseT> r1cs_proof = proof.to_libsnark_proof<r1cs_ppzksnark_proof<BaseT>>();\n\n            ProofVerifier<BaseT> verifierEnabled = ProofVerifier<BaseT>::Strict();\n\n            bool verified = verifierEnabled.check(\n                vk,\n                vk_precomp,\n                primary_input,\n                r1cs_proof\n            );\n\n#ifdef DEBUG\n            printf(\"\\n\"); libff::print_indent(); libff::print_mem(\"after verify\"); libff::print_time(\"after verify\");\n#endif\n\n            if (verified)\n            {\n                return true;\n            }\n            else\n            {\n                return false;\n            }\n        }\n        catch (...)\n        {\n            return false;\n        }\n    }\n};\n\n} // end namespace `gunero`\n\n#endif /* GUNEROTRANSACTIONRECEIVECIRCUIT_H_ */", "meta": {"hexsha": "a77a8d65e4c1eacd21c50e6a0ff98255de311639", "size": 9389, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/GuneroTransactionReceiveCircuit.hpp", "max_stars_repo_name": "GunClear/Silencer", "max_stars_repo_head_hexsha": "625b5ce0860af98763aa2ce14d6b406d5ef368e4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-10-17T22:27:54.000Z", "max_stars_repo_stars_event_max_datetime": "2018-10-17T22:27:54.000Z", "max_issues_repo_path": "src/GuneroTransactionReceiveCircuit.hpp", "max_issues_repo_name": "GunClear/Silencer", "max_issues_repo_head_hexsha": "625b5ce0860af98763aa2ce14d6b406d5ef368e4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 9.0, "max_issues_repo_issues_event_min_datetime": "2018-11-09T19:57:52.000Z", "max_issues_repo_issues_event_max_datetime": "2019-01-04T15:49:02.000Z", "max_forks_repo_path": "src/GuneroTransactionReceiveCircuit.hpp", "max_forks_repo_name": "GunClear/Silencer", "max_forks_repo_head_hexsha": "625b5ce0860af98763aa2ce14d6b406d5ef368e4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.154109589, "max_line_length": 223, "alphanum_fraction": 0.6025135797, "num_tokens": 2343, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7606506418255927, "lm_q2_score": 0.4416730056646256, "lm_q1q2_score": 0.3359588552358361}}
{"text": "#pragma once\n\n#include <crest/geometry/indexed_mesh.hpp>\n#include <crest/geometry/patch.hpp>\n#include <crest/geometry/mesh_algorithms.hpp>\n\n#include <boost/range/iterator_range.hpp>\n\n#include <cassert>\n\nnamespace crest\n{\n    namespace detail\n    {\n        template <typename Index>\n        class DescendantMap\n        {\n        public:\n            typedef typename std::vector<Index>::const_iterator          ConstIndexIterator;\n            typedef typename boost::iterator_range<ConstIndexIterator>   ConstIndexIteratorRange;\n\n            template <typename Scalar>\n            explicit DescendantMap(const IndexedMesh<Scalar, Index> & coarse,\n                                   const IndexedMesh<Scalar, Index> & fine)\n            {\n                _map = std::vector<std::vector<Index>>(coarse.num_elements());\n                for (Index k = 0; k < fine.num_elements(); ++k)\n                {\n                    assert(fine.ancestor_for(k) < coarse.num_elements());\n                    _map[fine.ancestor_for(k)].push_back(k);\n                }\n            }\n\n            ConstIndexIteratorRange descendants_for(Index coarse_element) const\n            {\n                assert(coarse_element >= Index(0) && coarse_element <= static_cast<Index>(_map.size()));\n                return boost::make_iterator_range(_map[coarse_element].begin(), _map[coarse_element].end());\n            }\n\n        private:\n            std::vector<std::vector<Index>> _map;\n        };\n    }\n\n    /**\n     * Represents a triangulated domain by a \"coarse\" (usually quasi-uniform) mesh and\n     * a \"fine\" mesh that is formed from the coarse mesh by bisection.\n     */\n    template <typename Scalar, typename Index>\n    class BiscaleMesh\n    {\n    public:\n        struct CoarseTag {};\n        struct FineTag {};\n\n        typedef Patch<Scalar, Index, CoarseTag> CoarsePatch;\n        typedef Patch<Scalar, Index, FineTag>   FinePatch;\n\n        typedef typename detail::DescendantMap<Index>::ConstIndexIteratorRange ConstIndexIteratorRange;\n\n        explicit BiscaleMesh(IndexedMesh<Scalar, Index> coarse_mesh,\n                             IndexedMesh<Scalar, Index> fine_mesh);\n\n        CoarsePatch coarse_element_patch(Index coarse_element, unsigned int max_distance) const;\n        FinePatch fine_patch_from_coarse(const CoarsePatch & coarse_patch) const;\n\n        Index                       ancestor_for(Index fine_element) const;\n        ConstIndexIteratorRange     descendants_for(Index coarse_element) const;\n\n        const IndexedMesh<Scalar, Index> & coarse_mesh() const;\n        const IndexedMesh<Scalar, Index> & fine_mesh() const;\n\n    private:\n        IndexedMesh<Scalar, Index>      _coarse;\n        IndexedMesh<Scalar, Index>      _fine;\n        detail::DescendantMap<Index>    _descendants;\n    };\n\n    template <typename Scalar, typename Index>\n    BiscaleMesh<Scalar, Index>::BiscaleMesh(IndexedMesh<Scalar, Index> coarse_mesh,\n                                            IndexedMesh<Scalar, Index> fine_mesh)\n            :   _descendants(detail::DescendantMap<Index>(coarse_mesh, fine_mesh))\n    {\n        _coarse = std::move(coarse_mesh);\n        _fine = std::move(fine_mesh);\n        // Check that all coarse elements have at least one descendant, otherwise\n        // the fine mesh cannot correspond to a refinement of the coarse mesh.\n        for (Index k = 0; k < _coarse.num_elements(); ++k)\n        {\n            // Since this is a no-op in release mode, the compiler will optimize it away\n            assert(!_descendants.descendants_for(k).empty());\n        }\n    };\n\n    template <typename Scalar, typename Index>\n    typename BiscaleMesh<Scalar, Index>::CoarsePatch\n    BiscaleMesh<Scalar, Index>::coarse_element_patch(Index coarse_element, unsigned int max_distance) const\n    {\n        return patch_for_element<CoarseTag>(coarse_mesh(), coarse_element, max_distance);\n    };\n\n    template <typename Scalar, typename Index>\n    typename BiscaleMesh<Scalar, Index>::FinePatch\n    BiscaleMesh<Scalar, Index>::fine_patch_from_coarse(\n            const BiscaleMesh<Scalar, Index>::CoarsePatch & coarse_patch) const\n    {\n        std::vector<Index> fine_patch;\n        for (const auto coarse_element : coarse_patch)\n        {\n            for (const auto fine_element : descendants_for(coarse_element))\n            {\n                fine_patch.push_back(fine_element);\n            }\n        }\n        fine_patch = algo::sorted_unique(std::move(fine_patch));\n        return FinePatch(fine_mesh(), std::move(fine_patch));\n    };\n\n    template <typename Scalar, typename Index>\n    Index BiscaleMesh<Scalar, Index>::ancestor_for(Index fine_element) const\n    {\n        return _fine.ancestor_for(fine_element);\n    };\n\n    template <typename Scalar, typename Index>\n    typename BiscaleMesh<Scalar, Index>::ConstIndexIteratorRange\n    BiscaleMesh<Scalar, Index>::descendants_for(Index coarse_element) const\n    {\n        return _descendants.descendants_for(coarse_element);\n    };\n\n    template <typename Scalar, typename Index>\n    const IndexedMesh<Scalar, Index> & BiscaleMesh<Scalar, Index>::coarse_mesh() const\n    {\n        return _coarse;\n    };\n\n    template <typename Scalar, typename Index>\n    const IndexedMesh<Scalar, Index> & BiscaleMesh<Scalar, Index>::fine_mesh() const\n    {\n        return _fine;\n    };\n\n\n}\n", "meta": {"hexsha": "adf2b2c726455dc4dee9e508a2b6d267f0c23c3f", "size": 5321, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/crest/geometry/biscale_mesh.hpp", "max_stars_repo_name": "Andlon/crest", "max_stars_repo_head_hexsha": "f79bf5a68f3eb86f5e3422881678bc6f9011730a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/crest/geometry/biscale_mesh.hpp", "max_issues_repo_name": "Andlon/crest", "max_issues_repo_head_hexsha": "f79bf5a68f3eb86f5e3422881678bc6f9011730a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2017-01-24T10:45:27.000Z", "max_issues_repo_issues_event_max_datetime": "2017-01-27T16:21:37.000Z", "max_forks_repo_path": "include/crest/geometry/biscale_mesh.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": 36.4452054795, "max_line_length": 108, "alphanum_fraction": 0.637474159, "num_tokens": 1137, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6187804478040616, "lm_q2_score": 0.5428632831725052, "lm_q1q2_score": 0.33591318545786586}}
{"text": "/* Copyright (C) 2019-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#include <helib/PolyMod.h>\n#include <helib/exceptions.h>\n#include <NTL/ZZX.h>\n#include <NTL/ZZ_p.h>\n#include <vector>\n#include <helib/NumbTh.h>\n\n#include \"io.h\"\n\nnamespace helib {\n\nPolyMod::PolyMod() : ringDescriptor(nullptr) {}\nPolyMod::PolyMod(const std::shared_ptr<PolyModRing>& ringDescriptor) :\n    PolyMod(NTL::ZZX(0), ringDescriptor)\n{}\nPolyMod::PolyMod(long input,\n                 const std::shared_ptr<PolyModRing>& ringDescriptor) :\n    PolyMod(NTL::ZZX(input), ringDescriptor)\n{}\nPolyMod::PolyMod(const std::vector<long>& input,\n                 const std::shared_ptr<PolyModRing>& ringDescriptor) :\n    PolyMod(ringDescriptor)\n{\n  *this = input;\n}\nPolyMod::PolyMod(const NTL::ZZX& input,\n                 const std::shared_ptr<PolyModRing>& ringDescriptor) :\n    ringDescriptor(ringDescriptor), data(input)\n{\n  this->modularReduce();\n}\n\nPolyMod& PolyMod::operator=(long input)\n{\n  assertValidity(*this);\n  this->data = NTL::ZZX(input);\n  this->modularReduce();\n  return *this;\n}\n\nPolyMod& PolyMod::operator=(const std::vector<long>& input)\n{\n  assertValidity(*this);\n  NTL::clear(data); // Make sure higher-degree terms don't remain\n  for (std::size_t i = 0; i < input.size(); ++i)\n    NTL::SetCoeff(data, i, input[i]);\n  this->modularReduce();\n  return *this;\n}\n\nPolyMod& PolyMod::operator=(const std::initializer_list<long>& input)\n{\n  assertValidity(*this);\n  *this = std::vector<long>(input);\n  return *this;\n}\n\nPolyMod& PolyMod::operator=(const NTL::ZZX& input)\n{\n  assertValidity(*this);\n  this->data = input;\n  this->modularReduce();\n  return *this;\n}\n\nPolyMod::operator long() const\n{\n  assertValidity(*this);\n  long ret;\n  NTL::conv(ret, NTL::ConstTerm(this->data));\n  return ret;\n}\n\nPolyMod::operator std::vector<long>() const\n{\n  assertValidity(*this);\n  std::vector<long> ret(NTL::deg(ringDescriptor->G));\n  for (std::size_t i = 0; i < ret.size(); ++i)\n    NTL::conv(ret[i], NTL::coeff(data, i));\n  return ret;\n}\n\nPolyMod::operator NTL::ZZX() const\n{\n  assertValidity(*this);\n  return getData();\n}\n\nbool PolyMod::isValid() const { return ringDescriptor != nullptr; }\n\nlong PolyMod::getp2r() const { return ringDescriptor->p2r; }\n\nNTL::ZZX PolyMod::getG() const { return ringDescriptor->G; }\n\nconst NTL::ZZX& PolyMod::getData() const\n{\n  assertValidity(*this);\n  return this->data;\n}\n\nbool PolyMod::operator==(const PolyMod& rhs) const\n{\n  if (!isValid() && !rhs.isValid())\n    return true;\n  else\n    return isValid() && rhs.isValid() &&\n           *ringDescriptor == *(rhs.ringDescriptor) && data == rhs.data;\n}\n\nbool PolyMod::operator==(long rhs) const { return *this == NTL::ZZX(rhs); }\n\nbool PolyMod::operator==(const std::vector<long>& rhs) const\n{\n  if (!this->isValid()) {\n    return false;\n  } else {\n    PolyMod other(rhs, ringDescriptor);\n    return *this == other;\n  }\n}\n\nbool PolyMod::operator==(const NTL::ZZX& rhs) const\n{\n  if (!this->isValid()) {\n    return false;\n  } else {\n    PolyMod copy(*this);\n    // Using subtraction to ensure modularReduce is called.\n    // We are checking for divisibility of difference by G in Z_p rather than\n    // direct equality\n    copy -= rhs;\n    return copy.data == NTL::ZZX(0);\n  }\n}\n\nPolyMod& PolyMod::negate()\n{\n  assertValidity(*this);\n  *this *= -1;\n  return *this;\n}\n\nPolyMod PolyMod::operator-() const\n{\n  assertValidity(*this);\n  PolyMod poly(*this);\n  poly.negate();\n  return poly;\n}\n\nPolyMod PolyMod::operator*(const PolyMod& rhs) const\n{\n  assertInterop(*this, rhs);\n  PolyMod result = *this;\n  result *= rhs;\n  return result;\n}\n\nPolyMod PolyMod::operator*(long rhs) const { return operator*(NTL::ZZX{rhs}); }\n\nPolyMod PolyMod::operator*(const NTL::ZZX& rhs) const\n{\n  PolyMod result(*this);\n  PolyMod multiplier(*this);\n  multiplier = rhs;\n  return result * multiplier;\n}\n\nPolyMod PolyMod::operator+(const PolyMod& rhs) const\n{\n  assertInterop(*this, rhs);\n  PolyMod result(*this);\n  result += rhs;\n  return result;\n}\n\nPolyMod PolyMod::operator+(long rhs) const { return operator+(NTL::ZZX{rhs}); }\n\nPolyMod PolyMod::operator+(const NTL::ZZX& rhs) const\n{\n  PolyMod result(*this);\n  PolyMod addend(result);\n  addend = rhs;\n  return result + addend;\n}\n\nPolyMod PolyMod::operator-(const PolyMod& rhs) const\n{\n  assertInterop(*this, rhs);\n  PolyMod result = *this;\n  result -= rhs;\n  return result;\n}\n\nPolyMod PolyMod::operator-(long rhs) const { return operator-(NTL::ZZX{rhs}); }\n\nPolyMod PolyMod::operator-(const NTL::ZZX& rhs) const\n{\n  PolyMod result(*this);\n  PolyMod subtrahend(result);\n  subtrahend = rhs;\n  return result - subtrahend;\n}\n\nPolyMod& PolyMod::operator*=(const PolyMod& otherPoly)\n{\n  assertInterop(*this, otherPoly);\n  this->data *= otherPoly.data;\n  this->modularReduce();\n  return *this;\n}\n\nPolyMod& PolyMod::operator*=(long scalar)\n{\n  assertValidity(*this);\n  this->data *= NTL::ZZX(scalar);\n  this->modularReduce();\n  return *this;\n}\n\nPolyMod& PolyMod::operator*=(const NTL::ZZX& otherPoly)\n{\n  assertValidity(*this);\n  this->data *= otherPoly;\n  this->modularReduce();\n  return *this;\n}\n\nPolyMod& PolyMod::operator+=(const PolyMod& otherPoly)\n{\n  assertInterop(*this, otherPoly);\n  this->data += otherPoly.data;\n  this->modularReduce();\n  return *this;\n}\n\nPolyMod& PolyMod::operator+=(long scalar)\n{\n  assertValidity(*this);\n  this->data += NTL::ZZX(scalar);\n  this->modularReduce();\n  return *this;\n}\n\nPolyMod& PolyMod::operator+=(const NTL::ZZX& otherPoly)\n{\n  assertValidity(*this);\n  this->data += otherPoly;\n  this->modularReduce();\n  return *this;\n}\n\nPolyMod& PolyMod::operator-=(const PolyMod& otherPoly)\n{\n  assertInterop(*this, otherPoly);\n  this->data -= otherPoly.data;\n  this->modularReduce();\n  return *this;\n}\n\nPolyMod& PolyMod::operator-=(long scalar)\n{\n  assertValidity(*this);\n  this->data -= NTL::ZZX(scalar);\n  this->modularReduce();\n  return *this;\n}\n\nPolyMod& PolyMod::operator-=(const NTL::ZZX& otherPoly)\n{\n  assertValidity(*this);\n  this->data -= otherPoly;\n  this->modularReduce();\n  return *this;\n}\n\nvoid PolyMod::writeToJSON(std::ostream& os) const\n{\n  PolyMod::assertValidity(*this);\n  executeRedirectJsonError<void>([&]() { os << writeToJSON(); });\n}\n\nJsonWrapper PolyMod::writeToJSON() const\n{\n  PolyMod::assertValidity(*this);\n\n  return executeRedirectJsonError<JsonWrapper>(\n      [&]() { return wrap(this->data); });\n}\n\nPolyMod PolyMod::readFromJSON(\n    std::istream& is,\n    const std::shared_ptr<PolyModRing>& ringDescriptor)\n{\n  PolyMod poly(ringDescriptor);\n  poly.readJSON(is);\n  return poly;\n}\n\nPolyMod PolyMod::readFromJSON(\n    const JsonWrapper& jw,\n    const std::shared_ptr<PolyModRing>& ringDescriptor)\n{\n  PolyMod poly(ringDescriptor);\n  poly.readJSON(jw);\n  return poly;\n}\n\nvoid PolyMod::readJSON(std::istream& is)\n{\n  executeRedirectJsonError<void>([&]() {\n    json j;\n    is >> j;\n    this->readJSON(wrap(j));\n  });\n}\n\nvoid PolyMod::readJSON(const JsonWrapper& jw)\n{\n  auto body = [&]() {\n    PolyMod::assertValidity(*this);\n\n    NTL::ZZX poly = unwrap(jw);\n\n    long g_degree = NTL::deg(this->ringDescriptor->G);\n    if (deg(poly) >= g_degree) {\n      // Too many elements. Raising an error.\n      std::stringstream err_msg;\n      err_msg << \"Cannot deserialize to PolyMod: Degree is too small.  \"\n              << \"Trying to deserialize \" << deg(poly) + 1 << \" coefficients.  \"\n              << \"Slot modulus degree is \" << g_degree << \".\";\n      throw IOError(err_msg.str());\n    }\n\n    NTL::clear(this->data); // Make sure higher-degree terms don't remain\n    this->data = poly;\n\n    // Normalization (removal of leading zeros) is done by modularReduce.\n    this->modularReduce();\n  };\n\n  executeRedirectJsonError<void>(body);\n}\n\nstd::istream& operator>>(std::istream& is, PolyMod& poly)\n{\n  PolyMod::assertValidity(poly);\n\n  poly.readJSON(is);\n  return is;\n}\n\nstd::ostream& operator<<(std::ostream& os, const PolyMod& poly)\n{\n  PolyMod::assertValidity(poly);\n\n  poly.writeToJSON(os);\n  return os;\n}\n\nvoid PolyMod::modularReduce()\n{\n  NTL::ZZ_pContext pContext;\n  pContext.save();\n  NTL::ZZ_p::init(NTL::ZZ(ringDescriptor->p2r));\n  NTL::ZZ_pX poly_mod_p2r;\n  NTL::conv(poly_mod_p2r, this->data);\n  NTL::ZZ_pX G_mod_p2r;\n  NTL::conv(G_mod_p2r, ringDescriptor->G);\n  poly_mod_p2r %= G_mod_p2r;\n  NTL::conv(this->data, poly_mod_p2r);\n  pContext.restore();\n  this->data.normalize();\n}\n\nvoid PolyMod::assertValidity(const PolyMod& poly)\n{\n  if (!poly.isValid()) {\n    throw LogicError(\"Cannot operate on invalid (default constructed) PolyMod\");\n  }\n}\n\nvoid PolyMod::assertInterop(const PolyMod& lhs, const PolyMod& rhs)\n{\n  assertValidity(lhs);\n  assertValidity(rhs);\n  if (*(lhs.ringDescriptor) != *(rhs.ringDescriptor))\n    throw LogicError(\"Ring descriptors are not equal between PolyMod objects\");\n}\n\n} // namespace helib\n", "meta": {"hexsha": "c07c96ee642cb6abe4b7a5827385f3e68be23f3a", "size": 9326, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/PolyMod.cpp", "max_stars_repo_name": "ShixiongQi/HElib", "max_stars_repo_head_hexsha": "9973ccc68a292d5c52388eca40eac08ae11d0263", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 992.0, "max_stars_repo_stars_event_min_datetime": "2019-04-07T01:05:10.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T22:42:36.000Z", "max_issues_repo_path": "src/PolyMod.cpp", "max_issues_repo_name": "maliasadi/HElib", "max_issues_repo_head_hexsha": "7b919ce4ff22a04f1fb394d875172b91ae2c4c11", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 180.0, "max_issues_repo_issues_event_min_datetime": "2019-04-29T20:19:22.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T13:11:15.000Z", "max_forks_repo_path": "src/PolyMod.cpp", "max_forks_repo_name": "maliasadi/HElib", "max_forks_repo_head_hexsha": "7b919ce4ff22a04f1fb394d875172b91ae2c4c11", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 289.0, "max_forks_repo_forks_event_min_datetime": "2019-04-08T15:22:21.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T21:27:52.000Z", "avg_line_length": 23.0841584158, "max_line_length": 80, "alphanum_fraction": 0.6744585031, "num_tokens": 2630, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6187804337438501, "lm_q2_score": 0.5428632831725052, "lm_q1q2_score": 0.3359131778250933}}
{"text": "#include <cstdio>\n#include <cmath>\n#include <cfloat>\n#include <cstdarg>\n#include <iostream>\n#include <fstream>\n#include <sstream>\n#include <vector>\n#include <map>\n#include <Eigen/Dense>\n#include <unsupported/Eigen/CXX11/Tensor>\n#include <boost/filesystem.hpp>\n#include <omp.h>\n#include <H5Cpp.h>\n\n#include \"timer/timer.h\"\n\n/** \\brief Read all files in a directory matching the given extension.\n * \\param[in] directory path to directory\n * \\param[out] files read file paths\n * \\param[in] extension extension to filter for\n */\nvoid read_directory(const boost::filesystem::path directory, std::map<int, boost::filesystem::path>& files, const std::string extension = \".off\") {\n  files.clear();\n  boost::filesystem::directory_iterator end;\n\n  for (boost::filesystem::directory_iterator it(directory); it != end; ++it) {\n    if (it->path().extension().string() == extension) {\n      if (!boost::filesystem::is_empty(it->path()) && !it->path().empty() && it->path().filename().string() != \"\") {\n        int number = std::stoi(it->path().filename().string());\n        files.insert(std::pair<int, boost::filesystem::path>(number, it->path()));\n      }\n    }\n  }\n}\n\n/** \\brief Just encapsulating vertices and faces. */\nclass Mesh {\npublic:\n  /** \\brief Empty constructor. */\n  Mesh() {\n\n  }\n\n  /** \\brief Add a vertex.\n   * \\param[in] vertex vertex to add\n   */\n  void add_vertex(Eigen::Vector3f& vertex) {\n    this->vertices.push_back(vertex);\n  }\n\n  /** \\brief Get the number of vertices.\n   * \\return number of vertices\n   */\n  int num_vertices() const {\n    return static_cast<int>(this->vertices.size());\n  }\n\n  Eigen::Vector3f vertex(int v) {\n    assert(v >= 0 && v < this->vertices.size());\n    return this->vertices[v];\n  }\n\n  /** \\brief Add a face.\n   * \\param[in] face face to add\n   */\n  void add_face(Eigen::Vector3i& face) {\n    this->faces.push_back(face);\n  }\n\n  /** \\brief Get the number of faces.\n   * \\return number of faces\n   */\n  int num_faces() const {\n    return static_cast<int>(this->faces.size());\n  }\n\n  Eigen::Vector3i face(int f) {\n    assert(f >= 0 && f < this->num_faces());\n    return this->faces[f];\n  }\n\n  /** \\brief Rotate the point cloud around the origin.\n   * \\param[in] rotation rotation matrix\n   */\n  void rotate(const Eigen::Matrix3f &rotation) {\n    for (int v = 0; v < this->num_vertices(); ++v) {\n      this->vertices[v] = rotation*this->vertices[v];\n    }\n  }\n\n  /** \\brief Translate the mesh.\n   * \\param[in] translation translation vector\n   */\n  void translate(const Eigen::Vector3f& translation) {\n    for (int v = 0; v < this->num_vertices(); ++v) {\n      for (int i = 0; i < 3; ++i) {\n        this->vertices[v](i) += translation(i);\n      }\n    }\n  }\n\n  /** \\brief Scale the mesh.\n   * \\param[in] scale scale vector\n   */\n  void scale(const Eigen::Vector3f& scale) {\n    for (int v = 0; v < this->num_vertices(); ++v) {\n      for (int i = 0; i < 3; ++i) {\n        this->vertices[v](i) *= scale(i);\n      }\n    }\n  }\n\n  /** \\brief Sample points from the mesh\n   * \\param[in] mesh mesh to sample from\n   * \\param[in] n batch index in points\n   * \\param[in] points pre-initialized tensor holding points\n   */\n  bool sample(const int N, const int k, Eigen::Tensor<float, 3, Eigen::RowMajor> &points) {\n\n    // Stores the areas of faces.\n    std::vector<float> areas(this->num_faces());\n    float sum = 0;\n\n    // Build a probability distribution over faces.\n    for (int f = 0; f < this->num_faces(); f++) {\n      Eigen::Vector3f a = this->vertices[this->faces[f][0]];\n      Eigen::Vector3f b = this->vertices[this->faces[f][1]];\n      Eigen::Vector3f c = this->vertices[this->faces[f][2]];\n\n      // Angle between a->b and a->c.\n      Eigen::Vector3f ab = b - a;\n      Eigen::Vector3f ac = c - a;\n      float cos_angle = ab.dot(ac)/(ab.norm()*ac.norm());\n      float angle = std::acos(cos_angle);\n\n      // Compute triangle area.\n      float area = std::max(0., 0.5*ab.norm()*ac.norm()*std::sin(angle));\n      //std::cout << area << \" \" << std::pow(area, 1./4.) << \" \" << angle << \" \" << ab.norm() << \" \" << ac.norm() << \" \" << std::sin(angle) << std::endl;\n\n      // Accumulate.\n      //area = std::sqrt(area);\n      areas[f] = area;\n      sum += area;\n      //areas.push_back(1);\n      //sum += 1;\n    }\n\n    //std::cout << sum << std::endl;\n    if (sum < 1e-6) {\n      std::cout << \"[Error] face area sum of \" << sum << std::endl;\n      return false;\n    }\n\n    for (int f = 0; f < this->num_faces(); f++) {\n      //std::cout << areas[f] << \" \";\n      areas[f] /= sum;\n      //std::cout << areas[f] << std::endl;\n    }\n\n    std::vector<float> cum_areas(areas.size());\n    cum_areas[0] = areas[0];\n\n    for (int f = 1; f < this->num_faces(); f++) {\n      cum_areas[f] = areas[f] + cum_areas[f - 1];\n    }\n\n    int j = 0;\n    for (int f = 0; f < this->num_faces(); f++) {\n      int n = std::max(static_cast<int>(areas[f]*N), 1);\n\n      for (int i = 0; i < n; i++) {\n        float r1 = 0;\n        float r2 = 0;\n        do {\n          r1 = static_cast<float>(std::rand())/static_cast<float>(RAND_MAX);\n          r2 = static_cast<float>(std::rand())/static_cast<float>(RAND_MAX);\n        }\n        while (r1 + r2 > 1.f);\n\n        int s = std::rand()%3;\n        //std::cout << face << \" \" << areas[face] << std::endl;\n\n        Eigen::Vector3f a = this->vertices[this->faces[f](s)];\n        Eigen::Vector3f b = this->vertices[this->faces[f]((s + 1)%3)];\n        Eigen::Vector3f c = this->vertices[this->faces[f]((s + 2)%3)];\n\n        Eigen::Vector3f ab = b - a;\n        Eigen::Vector3f ac = c - a;\n\n        Eigen::Vector3f point = a + r1*ab + r2*ac;\n        points(k, j, 0) = point(0);\n        points(k, j, 1) = point(1);\n        points(k, j, 2) = point(2);\n        j++;\n      }\n    }\n\n    return true;\n  }\n\n  /** \\brief Reading an off file and returning the vertices x, y, z coordinates and the\n   * face indices.\n   * \\param[in] filepath path to the OFF file\n   * \\param[out] mesh read mesh with vertices and faces\n   * \\return success\n   */\n  static bool from_off(const std::string filepath, Mesh& mesh) {\n\n    std::ifstream* file = new std::ifstream(filepath.c_str());\n    std::string line;\n    std::stringstream ss;\n    int line_nb = 0;\n\n    std::getline(*file, line);\n    ++line_nb;\n\n    if (line != \"off\" && line != \"OFF\") {\n      std::cout << \"[Error] Invalid header: \\\"\" << line << \"\\\", \" << filepath << std::endl;\n      return false;\n    }\n\n    size_t n_edges;\n    std::getline(*file, line);\n    ++line_nb;\n\n    int n_vertices;\n    int n_faces;\n    ss << line;\n    ss >> n_vertices;\n    ss >> n_faces;\n    ss >> n_edges;\n\n    for (size_t v = 0; v < n_vertices; ++v) {\n      std::getline(*file, line);\n      ++line_nb;\n\n      ss.clear();\n      ss.str(\"\");\n\n      Eigen::Vector3f vertex;\n      ss << line;\n      ss >> vertex(0);\n      ss >> vertex(1);\n      ss >> vertex(2);\n\n      mesh.add_vertex(vertex);\n    }\n\n    size_t n;\n    for (size_t f = 0; f < n_faces; ++f) {\n      std::getline(*file, line);\n      ++line_nb;\n\n      ss.clear();\n      ss.str(\"\");\n\n      size_t n;\n      ss << line;\n      ss >> n;\n\n      if(n != 3) {\n        std::cout << \"[Error] Not a triangle (\" << n << \" points) at \" << (line_nb - 1) << std::endl;\n        return false;\n      }\n\n      Eigen::Vector3i face;\n      ss >> face(0);\n      ss >> face(1);\n      ss >> face(2);\n\n      mesh.add_face(face);\n    }\n\n    if (n_vertices != mesh.num_vertices()) {\n      std::cout << \"[Error] Number of vertices in header differs from actual number of vertices.\" << std::endl;\n      return false;\n    }\n\n    if (n_faces != mesh.num_faces()) {\n      std::cout << \"[Error] Number of faces in header differs from actual number of faces.\" << std::endl;\n      return false;\n    }\n\n    file->close();\n    delete file;\n\n    return true;\n  }\n\n  /** \\brief Write mesh to OFF file.\n   * \\param[in] filepath path to OFF file to write\n   * \\return success\n   */\n  bool to_off(const std::string filepath) {\n    std::ofstream* out = new std::ofstream(filepath, std::ofstream::out);\n    if (!static_cast<bool>(*out)) {\n      return false;\n    }\n\n    (*out) << \"OFF\" << std::endl;\n    (*out) << this->vertices.size() << \" \" << this->num_faces() << \" 0\" << std::endl;\n\n    for (unsigned int v = 0; v < this->vertices.size(); v++) {\n      (*out) << this->vertices[v](0) << \" \" << this->vertices[v](1) << \" \" << this->vertices[v](2) << std::endl;\n    }\n\n    for (unsigned int f = 0; f < this->num_faces(); f++) {\n      (*out) << \"3 \" << this->faces[f](0) << \" \" << this->faces[f](1) << \" \" << this->faces[f](2) << std::endl;\n    }\n\n    out->close();\n    delete out;\n\n    return true;\n  }\n\n  /** \\brief Write mesh to obj file.\n   * \\param[in] filepath\n   * \\param[in] mtl_lib\n   * \\param[in] materials\n   * \\return success\n   */\n  bool to_obj(const std::string filepath) {\n\n    std::ofstream* out = new std::ofstream(filepath, std::ofstream::out);\n    if (!static_cast<bool>(out)) {\n      return false;\n    }\n\n    for (unsigned int v = 0; v < this->vertices.size(); v++) {\n      (*out) << \"v \" << this->vertices[v](0) << \" \" << this->vertices[v](1) << \" \" << this->vertices[v](2) << std::endl;\n    }\n\n    for (unsigned int f = 0; f < this->num_faces(); f++) {\n      (*out) << \"f \" << this->faces[f](0) + 1 << \" \" << this->faces[f](1) + 1 << \" \" << this->faces[f](2) + 1 << std::endl;\n    }\n\n    out->close();\n    delete out;\n\n    return true;\n  }\n\nprivate:\n\n  /** \\brief Vertices as (x,y,z)-vectors. */\n  std::vector<Eigen::Vector3f> vertices;\n\n  /** \\brief Faces as list of vertex indices. */\n  std::vector<Eigen::Vector3i> faces;\n};\n\n/** \\brief Write the given set of volumes to h5 file.\n * \\param[in] filepath h5 file to write\n * \\param[in] n number of volumes\n * \\param[in] height height of volumes\n * \\param[in] width width of volumes\n * \\param[in] depth depth of volumes\n * \\param[in] dense volume data\n */\nbool write_hdf5(const std::string filepath, Eigen::Tensor<float, 3, Eigen::RowMajor>& dense) {\n\n  try {\n\n    /*\n     * Turn off the auto-printing when failure occurs so that we can\n     * handle the errors appropriately\n     */\n    H5::Exception::dontPrint();\n\n    /*\n     * Create a new file using H5F_ACC_TRUNC access,\n     * default file creation properties, and default file\n     * access properties.\n     */\n    H5::H5File file(filepath, H5F_ACC_TRUNC);\n\n    /*\n     * Define the size of the array and create the data space for fixed\n     * size dataset.\n     */\n    hsize_t rank = 3;\n    hsize_t dimsf[rank];\n    dimsf[0] = dense.dimension(0);\n    dimsf[1] = dense.dimension(1);\n    dimsf[2] = dense.dimension(2);\n    H5::DataSpace dataspace(rank, dimsf);\n\n    /*\n     * Define datatype for the data in the file.\n     * We will store little endian INT numbers.\n     */\n    H5::IntType datatype(H5::PredType::NATIVE_FLOAT);\n    datatype.setOrder(H5T_ORDER_LE);\n\n    /*\n     * Create a new dataset within the file using defined dataspace and\n     * datatype and default dataset creation properties.\n     */\n    H5::DataSet dataset = file.createDataSet(\"tensor\", datatype, dataspace);\n\n    /*\n     * Write the data to the dataset using default memory space, file\n     * space, and transfer properties.\n     */\n    float* data = static_cast<float*>(dense.data());\n    dataset.write(data, H5::PredType::NATIVE_FLOAT);\n  }  // end of try block\n\n  // catch failure caused by the H5File operations\n  catch(H5::FileIException error) {\n    error.printError();\n    return false;\n  }\n\n  // catch failure caused by the DataSet operations\n  catch(H5::DataSetIException error) {\n    error.printError();\n    return false;\n  }\n\n  // catch failure caused by the DataSpace operations\n  catch(H5::DataSpaceIException error) {\n    error.printError();\n    return false;\n  }\n\n  // catch failure caused by the DataSpace operations\n  catch(H5::DataTypeIException error) {\n    error.printError();\n    return false;\n  }\n\n  return true;\n}\n\n/** \\brief Main entrance point of script.\n * Expects one argument, the path to the config file.\n */\nint main(int argc, char** argv) {\n  if (argc < 2) {\n    std::cout << \"[Error] Usage: sample off_directory h5_file\" << std::endl;\n    exit(1);\n  }\n\n  boost::filesystem::path off_directory(argv[1]);\n  boost::filesystem::path h5_file(argv[2]);\n\n  if (!boost::filesystem::is_directory(off_directory)) {\n    std::cout << \"[Error] directory \" << off_directory << \" not found\" << std::endl;\n    exit(1);\n  }\n\n  std::map<int, boost::filesystem::path> off_files;\n  read_directory(off_directory, off_files);\n  std::cout << \"[ICP] found \" << off_files.size() << \" files\" << std::endl;\n\n  std::vector<int> indices;\n  for (std::map<int, boost::filesystem::path>::iterator it = off_files.begin(); it != off_files.end(); it++) {\n    indices.push_back(it->first);\n  }\n\n  int N_points = 1000000;\n  Eigen::Tensor<float, 3, Eigen::RowMajor> points(indices.size(), N_points, 3);\n  points.setZero();\n\n  float total = 0;\n\n  omp_set_num_threads(16);\n  #pragma omp parallel\n  {\n    #pragma omp for\n    for (unsigned int i = 0; i < indices.size(); i++) {\n      int n = indices[i];\n      std::string off_file = off_files[n].string();\n\n      Mesh mesh;\n      Mesh::from_off(off_file, mesh);\n\n      Timer timer;\n      timer.start();\n      mesh.sample(N_points, i, points);\n      timer.stop();\n\n      float elapsed = timer.getElapsedTimeInMilliSec();\n      std::cout << \"[Sample] sampled \" << off_file << \" (\" << elapsed << \"ms)\" << std::endl;\n\n      #pragma omp critical\n      {\n        total += elapsed;\n      }\n    }\n  }\n\n  write_hdf5(h5_file.string(), points);\n  std::cout << \"[Sample] wrote \" << h5_file.string() << std::endl;\n  std::cout << \"[Sample] took  on average \" << total/indices.size() << \"ms\" << std::endl;\n  exit(0);\n}\n", "meta": {"hexsha": "34839463917c3fa5189d68db749dec5a55759a60", "size": 13627, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "icp/sample.cpp", "max_stars_repo_name": "davidstutz/aml-improved-shape-completion", "max_stars_repo_head_hexsha": "9337a0421994199fa218d564cc34a7e7af1a275f", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 9.0, "max_stars_repo_stars_event_min_datetime": "2018-10-11T08:03:59.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-17T11:16:07.000Z", "max_issues_repo_path": "icp/sample.cpp", "max_issues_repo_name": "jtpils/aml-improved-shape-completion", "max_issues_repo_head_hexsha": "9337a0421994199fa218d564cc34a7e7af1a275f", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-07-08T16:43:53.000Z", "max_issues_repo_issues_event_max_datetime": "2019-11-25T17:08:07.000Z", "max_forks_repo_path": "icp/sample.cpp", "max_forks_repo_name": "jtpils/aml-improved-shape-completion", "max_forks_repo_head_hexsha": "9337a0421994199fa218d564cc34a7e7af1a275f", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2018-07-19T13:06:16.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-09T00:59:56.000Z", "avg_line_length": 27.1996007984, "max_line_length": 153, "alphanum_fraction": 0.5745211712, "num_tokens": 3872, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6187804337438501, "lm_q2_score": 0.5428632831725052, "lm_q1q2_score": 0.3359131778250933}}
{"text": "// Copyright (c) 2020 Kent Hu\n\n/// @author kent hu\n\n#include <algorithm>\n#include <cmath>\n#include <cstdlib>\n#include <exception>\n#include <deque>\n#include <functional>\n#include <iostream>\n#include <limits>\n#include <random>\n#include <string>\n#include <thread>\n#include <utility>\n#include <vector>\n\n#include <boost/lexical_cast.hpp>\n#include <boost/optional/optional.hpp>\n#include <comma/application/command_line_options.h>\n#include <comma/base/exception.h>\n#include <comma/base/types.h>\n#include <comma/csv/ascii.h>\n#include <comma/csv/options.h>\n#include <comma/csv/stream.h>\n#include <comma/string/split.h>\n#include <tbb/blocked_range.h>\n\n#define TBB_PREVIEW_GLOBAL_CONTROL 1 // required to #include <tbb/global_control.h>\n\n#include <tbb/global_control.h>\n#include <tbb/parallel_for.h>\n#include <tbb/parallel_reduce.h>\n#include \"../../visiting/traits.h\"\n\n#ifdef SNARK_USE_CUDA\n\n#include \"math-k-means/device.h\"\n#include \"math-k-means/math_k_means.h\"\n\n#endif\n\nvoid usage( const bool verbose )\n{\n    std::cerr << std::endl;\n    std::cerr << \"run k-means on input data\" << std::endl;\n    std::cerr << std::endl;\n    std::cerr << \"usage: cat sample.csv | math-k-means [<options>]\" << std::endl;\n    std::cerr << std::endl;\n    std::cerr << \"fields\" << std::endl;\n    std::cerr << \"    block: block number; output k-means centroid id for each\" << std::endl;\n    std::cerr << \"           contiguous block of samples with the same block id\" << std::endl;\n    std::cerr << \"    data: vector of size <size>\" << std::endl;\n    std::cerr << \"    default: data\" << std::endl;\n    std::cerr << \"output\" << std::endl;\n    std::cerr << \"    appended fields: centroid/id,centroid/data\" << std::endl;\n    std::cerr << \"    centroids only: if block field present: block,centroid/id,centroid/data\" << std::endl;\n    std::cerr << \"                    if no block field present: centroid/id,centroid/data\" << std::endl;\n    std::cerr << \"    binary format: 64-bit floating-point for centroid/data, 32-bit unsigned integer for centroid/id\" << std::endl;\n    std::cerr << \"options\" << std::endl;\n#ifdef SNARK_USE_CUDA\n    std::cerr << \"    --cuda: use gpu; ATTENTION: only 32-bit float precision currently implemented; if you need 64-bit float precision, run without --cuda\" << std::endl;\n    std::cerr << \"    --cuda-use-pitched,--use-pitched,--pitched: use pitched memory for 2d array (padded 2d array for memory coalescing; faster but uses more memory)\" << std::endl;\n#endif\n    std::cerr << \"    --help,-h: show this help; --help --verbose: more help\" << std::endl;\n    std::cerr << \"    --ignore-tolerance: ignore tolerance value used for early exit\" << std::endl;\n    std::cerr << \"    --max-iterations,--iterations=<n>: number of iterations for Lloyd's algorithm; default: 300\" << std::endl;\n    std::cerr << \"    --max-threads,--threads=<n>: maximum number of threads to run, if 0, set to number of cores in system (\" << std::thread::hardware_concurrency() << ')' << \"; default: 0\" << std::endl;\n    std::cerr << \"    --number-of-clusters,--clusters=<n>: number of k-means cluster per block/all\" << std::endl;\n    std::cerr << \"    --number-of-runs,--runs=<n>: number of times to run k-means, best run is one with lowest inertia (sum of distance of cluster points to cluster centroid); default: 10\" << std::endl;\n    std::cerr << \"    --output-centroids,--centroids: output centroids only\" << std::endl;\n    std::cerr << \"    --seed=[<seed>]: use seed for random initialization of centroids\" << std::endl;\n    std::cerr << \"    --size=[<n>]: a hint of number of elements in the data vector; ignored, if data indices specified, e.g. data[0],data[1],data[2]\" << std::endl;\n    std::cerr << \"    --tolerance=<distance>: difference between two consecutive iteration centroid l2 norms to declare convergence and stop iterating in LLoyd's algorithm; default: 1.0e-4\" << std::endl;\n    if( verbose ) { std::cerr << std::endl << \"csv options\" << std::endl << comma::csv::options::usage() << std::endl; }\n    std::cerr << std::endl;\n    std::cerr << \"examples\" << std::endl;\n    std::cerr << \"    cat sample.csv | math-k-means --number-of-clusters=3\" << std::endl;\n    std::cerr << \"    cat sample.csv | math-k-means --number-of-clusters=3 --fields=data --size=3\" << std::endl;\n    std::cerr << \"    cat sample.csv | math-k-means --number-of-clusters=3 --fields=,,,data[0],,,,data[1],,data[2]\" << std::endl;\n    std::cerr << \"    cat sample.bin | math-k-means --number-of-clusters=3 --fields=block,data --size=3 --binary=ui,3d\" << std::endl;\n    std::cerr << std::endl;\n    exit( 0 );\n}\n\nstatic comma::csv::options csv;\nstatic boost::optional< unsigned int > size = boost::none;\nstatic bool output_centroids = false;\nstatic boost::optional< std::mt19937::result_type > seed = boost::none;\nstatic bool use_block = false;\n#ifdef SNARK_USE_CUDA\nstatic bool use_pitched = false;\n#endif\nstatic bool verbose = false;\n\nnamespace snark {\n\n#ifdef SNARK_USE_CUDA\nnamespace cuda { namespace k_means {\n\nstruct input_t\n{\n    std::vector< float > data;\n    comma::uint32 block = 0;\n\n    input_t() : data( *size ), block( 0 ) {}\n};\n\nclass k_means\n{\npublic:\n    k_means( float tolerance, unsigned int max_iterations, unsigned int number_of_runs,\n             comma::uint32 number_of_clusters, unsigned int size ) noexcept : tolerance_( tolerance ),\n                                                                              max_iterations_( max_iterations ),\n                                                                              number_of_runs_( number_of_runs ),\n                                                                              number_of_clusters_( number_of_clusters ),\n                                                                              ncols_( size ) {}\n\n    template < template < typename > class Matrix >\n    std::tuple< std::vector< float >, std::vector< comma::uint32 > >\n    run_on_block( const std::vector< float >& h_matrix ) const\n    {\n        const size_t nrows = h_matrix.size() / ncols_;\n\n        // device arrays/matrices\n        Matrix< float > d_matrix( nrows, ncols_, h_matrix );\n        Matrix< float > d_means( number_of_clusters_, ncols_ );\n        Matrix< float > d_sums( number_of_clusters_, ncols_ );\n        CUDA_CHECK_ERRORS( d_sums.fill( 0.0f ) )\n\n        device::array< comma::uint32 > d_assignments( nrows );\n        device::array< unsigned int > d_counts( number_of_clusters_ );\n        CUDA_CHECK_ERRORS( d_counts.fill( 0 ) )\n\n        // host vectors\n        std::vector< float > h_means( number_of_clusters_* ncols_ );\n        std::vector< comma::uint32 > h_assignments( nrows );\n\n        // save runs to choose best centroid\n        std::vector< float > all_scores;\n        all_scores.reserve( number_of_runs_ );\n        std::vector< decltype( h_means ) > all_centroids;\n        all_centroids.reserve( number_of_runs_ );\n        std::vector< decltype( h_assignments ) > all_centroid_assignments;\n        all_centroid_assignments.reserve( number_of_runs_ );\n\n        cudaDeviceProp prop{};\n        CUDA_CHECK_ERRORS( cudaGetDeviceProperties( &prop, 0 ) )\n        for( unsigned int run = 0; run < number_of_runs_; ++run )\n        {\n            CUDA_CHECK_ERRORS( d_means.to_device( initialize_centroids( h_matrix ) ) )\n            float difference = std::numeric_limits< float >::max();\n            for( unsigned int iteration = 0; iteration < max_iterations_; ++iteration )\n            {\n                assign_centroids( d_matrix, d_means, d_assignments, d_sums, d_counts, number_of_clusters_, prop.maxThreadsPerBlock );\n                update_centroids( d_means, d_sums, d_counts, number_of_clusters_ );\n                if( tolerance_ < 0 ) { continue; }\n                std::vector< float > new_means( number_of_clusters_* ncols_ ); // temp buffer for calculating tolerance difference\n                CUDA_CHECK_ERRORS( d_means.to_host( new_means ) )\n                difference = tbb::parallel_reduce( tbb::blocked_range< comma::uint32 >( 0, number_of_clusters_ ), 0.0f,\n                                                   [&]( const tbb::blocked_range< comma::uint32 > chunk, float difference ) -> float\n                                                   {\n                                                       for( comma::uint32 i = chunk.begin(); i < chunk.end(); ++i )\n                                                       {\n                                                           difference += squared_euclidean_distance( ncols_, &h_means[i * ncols_], &new_means[i * ncols_] );\n                                                       }\n                                                       return difference;\n                                                   },\n                                                   std::plus< float >()\n                );\n                h_means = std::move( new_means );\n                if( difference < tolerance_ * tolerance_ ) { break; }\n            }\n            CUDA_CHECK_ERRORS( d_assignments.to_host( h_assignments ) )\n            if( tolerance_ < 0 || difference > tolerance_ * tolerance_ ) { CUDA_CHECK_ERRORS( d_means.to_host( h_means ) ) }\n            const float score = tbb::parallel_reduce( tbb::blocked_range< size_t >( 0, nrows ), 0.0f,\n                                                      [&]( const tbb::blocked_range< size_t > chunk, float score ) -> float\n                                                      {\n                                                          for( size_t point = chunk.begin(); point < chunk.end(); ++point )\n                                                          {\n                                                              const auto cluster_assignment = h_assignments[point];\n                                                              score += std::sqrt( squared_euclidean_distance( ncols_, &h_matrix[point * ncols_], &h_means[cluster_assignment * ncols_] ) );\n                                                          }\n                                                          return score;\n                                                      },\n                                                      std::plus< float >()\n            );\n            all_scores.emplace_back( score );\n            all_centroids.emplace_back( h_means );\n            all_centroid_assignments.emplace_back( h_assignments );\n        }\n        const auto& best_index = std::distance( all_scores.begin(), std::min_element( all_scores.begin(), all_scores.end() ) );\n        return std::make_tuple( all_centroids[best_index], all_centroid_assignments[best_index] );\n    }\n\nprivate:\n    std::vector< float > initialize_centroids( const std::vector< float >& h_matrix ) const\n    {\n        static std::mt19937 generator( seed.is_initialized() ? *seed : std::random_device{}() );\n        static std::vector< float > init_centroids( number_of_clusters_* ncols_ );\n        static std::uniform_int_distribution< size_t > indices( 0, h_matrix.size() / ncols_ - 1 );\n        for( size_t cluster = 0; cluster < number_of_clusters_; ++cluster )\n        {\n            for( size_t col = 0; col < ncols_; ++col )\n            {\n                init_centroids[cluster * ncols_ + col] = h_matrix[indices( generator ) * ncols_ + col];\n            }\n        }\n        return init_centroids;\n    }\n\n    const float tolerance_;\n    const unsigned int max_iterations_;\n    const unsigned int number_of_runs_;\n    const unsigned int number_of_clusters_;\n    const unsigned int ncols_;\n};\n\n} } // namespace cuda { namespace k_means {\n\n#endif\n\nnamespace k_means {\n\nstatic double square( const double value ) { return value * value; }\n\nstatic double squared_euclidean_distance( const std::vector< double >& first, const std::vector< double >& second )\n{\n    double ret = 0.0;\n    for( size_t i = 0; i < first.size(); ++i ) { ret += square( first[i] - second[i] ); }\n    return ret;\n}\n\nstruct input_t\n{\n    std::vector< double > data;\n    comma::uint32 block;\n\n    input_t() : data( *size ), block( 0 ) {}\n};\n\nstruct k_means\n{\n    const double tolerance;\n    const unsigned int max_iterations;\n    const unsigned int number_of_runs;\n    const comma::uint32 number_of_clusters;\n\n    k_means( double tolerance, unsigned int max_iterations, unsigned int number_of_runs, comma::uint32 number_of_clusters ) noexcept :\n            tolerance( tolerance ),\n            max_iterations( max_iterations ),\n            number_of_runs( number_of_runs ),\n            number_of_clusters( number_of_clusters ) {}\n\n    std::vector< std::vector< double > > initialize_centroids( const std::deque< std::vector< double > >& dataframe ) const\n    {\n        static std::mt19937 generator( seed.is_initialized() ? *seed : std::random_device{}() );\n        std::vector< std::vector< double > > centroids( number_of_clusters );\n        std::uniform_int_distribution< size_t > indices( 0, dataframe.size() - 1 );\n        std::generate( centroids.begin(), centroids.end(), [&]() { return dataframe[indices( generator )]; } );\n        return centroids;\n    }\n\n    std::vector< comma::uint32 >\n    assign_centroids( const std::vector< std::vector< double > >& centroids, const std::deque< std::vector< double > >& dataframe ) const\n    {\n        std::vector< comma::uint32 > centroid_assignments( dataframe.size() );\n        tbb::parallel_for( tbb::blocked_range< size_t >( 0, centroid_assignments.size() ), [&]( const tbb::blocked_range< size_t >& chunk )\n        {\n            for( size_t point = chunk.begin(); point < chunk.end(); ++point )\n            {\n                auto best_distance = std::numeric_limits< double >::max();\n                comma::uint32 best_centroid = 0;\n                for( comma::uint32 centroid_i = 0; centroid_i < number_of_clusters; ++centroid_i )\n                {\n                    const double distance = squared_euclidean_distance( dataframe[point], centroids[centroid_i] );\n                    if( distance < best_distance ) { best_distance = distance; best_centroid = centroid_i; }\n                }\n                centroid_assignments[point] = best_centroid;\n            }\n        } );\n        return centroid_assignments;\n    }\n\n    std::vector< std::vector< double > >\n    update_centroids( const std::vector< comma::uint32 >& centroid_assignments, const std::deque< std::vector< double > >& dataframe ) const\n    {\n        // for each cluster, calculate sum of data vectors and number of data vectors\n        std::vector< size_t > size_of_centroid( number_of_clusters );\n        std::vector< std::vector< double > > sum_of_points_in_centroid( number_of_clusters, std::vector< double >( *size, 0.0 ) );\n        for( size_t point = 0; point < dataframe.size(); ++point )\n        {\n            const auto centroid_i = centroid_assignments[point];\n            for( size_t point_i = 0;\n                 point_i < dataframe[point].size(); ++point_i ) { sum_of_points_in_centroid[centroid_i][point_i] += dataframe[point][point_i]; }\n            ++size_of_centroid[centroid_i];\n        }\n        // calculate new centroid means\n        std::vector< std::vector< double > > new_centroids( number_of_clusters );\n        tbb::parallel_for( tbb::blocked_range< comma::uint32 >( 0, number_of_clusters ), [&]( const tbb::blocked_range< comma::uint32 >& chunk )\n        {\n            for( comma::uint32 centroid_i = chunk.begin(); centroid_i < chunk.end(); ++centroid_i )\n            {\n                new_centroids[centroid_i].reserve( *size );\n                const auto centroid_size = std::max< size_t >( 1, size_of_centroid[centroid_i] ); // minimum size is at least 1\n                for( size_t point_i = 0; point_i < sum_of_points_in_centroid[centroid_i].size(); ++point_i )\n                {\n                    new_centroids[centroid_i].emplace_back( sum_of_points_in_centroid[centroid_i][point_i] / centroid_size );\n                }\n            }\n        } );\n        return new_centroids;\n    }\n\n    // refer to http://www.goldsborough.me/c++/python/cuda/2017/09/10/20-32-46-exploring_k-means_in_python,_c++_and_cuda/\n    std::tuple< std::vector< std::vector< double > >, std::vector< comma::uint32 > > run_on_block( const std::deque< std::vector< double > >& dataframe ) const\n    {\n        std::vector< double > all_scores( number_of_runs );\n        std::vector< std::vector< std::vector< double > > > all_centroids( number_of_runs );\n        std::vector< std::vector< comma::uint32 > > all_centroid_assignments( number_of_runs );\n        tbb::parallel_for( tbb::blocked_range< unsigned int >( 0, number_of_runs ), [&]( const tbb::blocked_range< unsigned int >& chunk )\n        {\n            for( unsigned int run = chunk.begin(); run < chunk.end(); ++run )\n            {\n                std::vector< comma::uint32 > centroid_assignments;\n                std::vector< std::vector< double > > run_centroids = initialize_centroids( dataframe );\n                for( unsigned int iteration = 0; iteration < max_iterations; ++iteration )\n                {\n                    centroid_assignments = assign_centroids( run_centroids, dataframe );\n                    std::vector< std::vector< double > > new_centroids = update_centroids( centroid_assignments, dataframe );\n                    if( tolerance < 0 ) { run_centroids = std::move( new_centroids ); continue; }\n                    double summed_difference = tbb::parallel_reduce( tbb::blocked_range< comma::uint32 >( 0, number_of_clusters ), 0.0,\n                            [&]( const tbb::blocked_range< comma::uint32 > chunk, double difference ) -> double\n                            {\n                                for( comma::uint32 centroid_i = chunk.begin(); centroid_i < chunk.end(); ++centroid_i )\n                                {\n                                    difference += squared_euclidean_distance( run_centroids[centroid_i], new_centroids[centroid_i] );\n                                }\n                                return difference;\n                            },\n                            std::plus< double >()\n                    );\n                    run_centroids = std::move( new_centroids );\n                    if( summed_difference < tolerance * tolerance ) { break; }\n                }\n                double run_score = tbb::parallel_reduce( tbb::blocked_range< size_t >( 0, dataframe.size() ), 0.0,\n                                                         [&]( const tbb::blocked_range< size_t > chunk, double score ) -> double\n                                                         {\n                                                             for( size_t point = chunk.begin(); point < chunk.end(); ++point )\n                                                             {\n                                                                 score += std::sqrt( squared_euclidean_distance( dataframe[point], run_centroids[centroid_assignments[point]] ) );\n                                                             }\n                                                             return score;\n                                                         },\n                                                         std::plus< double >()\n                );\n                all_scores[run] = run_score;\n                all_centroids[run] = std::move( run_centroids );\n                all_centroid_assignments[run] = std::move( centroid_assignments );\n            }\n        } );\n        const std::vector< double >::iterator& min_element = std::min_element( all_scores.begin(), all_scores.end() );\n        const auto best_index = std::distance( all_scores.begin(), min_element );\n        return std::make_pair( all_centroids[best_index], all_centroid_assignments[best_index] );\n    }\n};\n\n} // namespace k_means {\n\n} // namespace snark {\n\nstatic std::string get_size()\n{\n    std::string first;\n    const std::vector< std::string >& fields = comma::split( csv.fields, ',' );\n    if( csv.has_field( \"data\" ) )\n    {\n        unsigned int count;\n        if( csv.binary() )\n        {\n            count = csv.format().count();\n        }\n        else\n        {\n            while( std::cin.good() && first.empty() ) { std::getline( std::cin, first ); }\n            count = comma::split( first, csv.delimiter ).size(); // quick and dirty, wasteful\n        }\n        size = count - fields.size() + 1;\n    }\n    else\n    {\n        unsigned int max = 0;\n        for( const auto& field : fields )\n        {\n            if( field.substr( 0, 5 ) == \"data[\" && *field.rbegin() == ']' )\n            {\n                const auto k = boost::lexical_cast< unsigned int >( field.substr( 5, field.size() - 6 ) ) + 1;\n                if( k > max ) { max = k; }\n            }\n        }\n        if( max == 0 ) { COMMA_THROW( comma::exception, \"please specify valid data fields\" ) }\n        size = max;\n    }\n    return first;\n}\n\n#ifdef SNARK_USE_CUDA\n\nstatic int run_cuda_( const float tolerance, const unsigned int max_iterations, const unsigned int number_of_runs, const comma::uint32 number_of_clusters )\n{\n    using namespace snark::cuda::k_means;\n    comma::uint32 block = 0;\n    std::vector< float > dataframe;\n    std::vector< std::string > input_lines;\n    auto set_input_values_ = [&]( const input_t& p, const std::string& line )\n    {\n        block = p.block;\n        input_lines.emplace_back( line );\n        dataframe.insert( end( dataframe ), begin( p.data ), end( p.data ) );\n    };\n    if( !size )\n    {\n        const auto& first_line = get_size();\n        if( !first_line.empty() ) { set_input_values_( comma::csv::ascii< input_t >( csv ).get( first_line ), first_line ); }\n    }\n    auto write_centroids_only_ = [number_of_clusters]( const std::vector< float >& centroids, const comma::uint32 block )\n    {\n        for( comma::uint32 i = 0; i < number_of_clusters; ++i )\n        {\n            if( csv.binary() )\n            {\n                if( use_block ) { std::cout.write( reinterpret_cast< const char* >( &block ), sizeof( block ) ); }\n                std::cout.write( reinterpret_cast< const char* >( &i ), sizeof( i ) );\n                for( size_t col = 0; col < *size; ++col )\n                {\n                    const auto point = static_cast< double >( centroids[i * *size + col] );\n                    std::cout.write( reinterpret_cast< const char* >( &point ), sizeof( point ) );\n                }\n            }\n            else\n            {\n                if( use_block ) { std::cout << block << csv.delimiter; }\n                std::cout << i;\n                for( size_t col = 0; col < *size; ++col ) { std::cout << csv.delimiter << static_cast< double >( centroids[i * *size + col] ); }\n                std::cout << std::endl;\n            }\n        }\n    };\n    auto write_lines_ = []( const std::vector< std::string >& input_lines, const std::vector< float >& centroids,\n                            const std::vector< comma::uint32 >& centroid_assignments )\n    {\n        for( size_t i = 0; i < centroid_assignments.size(); ++i )\n        {\n            const comma::uint32 centroid_assignment = centroid_assignments[i];\n            std::cout << input_lines[i];\n            if( csv.binary() )\n            {\n                std::cout.write( reinterpret_cast< const char* >( &centroid_assignment ), sizeof( centroid_assignment ) );\n                for( size_t col = 0; col < *size; ++col )\n                {\n                    const auto point = static_cast< double >( centroids[centroid_assignment * *size + col] );\n                    std::cout.write( reinterpret_cast< const char* >( &point ), sizeof( point ) );\n                }\n            }\n            else\n            {\n                std::cout << csv.delimiter << centroid_assignment;\n                for( size_t col = 0; col < *size; ++col ) { std::cout << csv.delimiter << static_cast< double >( centroids[centroid_assignment * *size + col] ); }\n                std::cout << std::endl;\n            }\n        }\n    };\n    std::vector< float > centroids;\n    std::vector< comma::uint32 > centroid_assignments;\n    k_means operation{ tolerance, max_iterations, number_of_runs, number_of_clusters, *size };\n    comma::csv::input_stream< input_t > istream( std::cin, csv );\n    while( istream.ready() || std::cin.good() )\n    {\n        const input_t* p = istream.read();\n        if( !dataframe.empty() && ( !p || block != p->block ) )\n        {\n            std::tie( centroids, centroid_assignments ) = use_pitched ? operation.run_on_block< snark::cuda::device::pitched_matrix >( dataframe ) : operation.run_on_block< snark::cuda::device::matrix >( dataframe );\n            output_centroids ? write_centroids_only_( centroids, block ) : write_lines_( input_lines, centroids, centroid_assignments );\n            if( csv.flush ) { std::cout.flush(); }\n            dataframe.clear();\n            input_lines.clear();\n        }\n        if( !p ) { break; }\n        set_input_values_( *p, istream.last() );\n    }\n    return 0;\n}\n\n#endif\n\nstatic int run_( const double tolerance, const unsigned int max_iterations, const unsigned int number_of_runs, const comma::uint32 number_of_clusters )\n{\n    using namespace snark::k_means;\n    std::deque< std::vector< double > > dataframe;\n    std::deque< std::string > input_lines;\n    comma::uint32 block = 0;\n    auto set_input_values_ = [&]( const input_t& p, const std::string& line )\n    {\n        block = p.block;\n        input_lines.emplace_back( line );\n        dataframe.emplace_back( p.data );\n    };\n    if( !size )\n    {\n        const auto& first_line = get_size();\n        if( !first_line.empty()) { set_input_values_( comma::csv::ascii< input_t >( csv ).get( first_line ), first_line ); }\n    }\n    auto write_centroids_only_ = [number_of_clusters]( const std::vector< std::vector< double > >& centroids, const comma::uint32 block )\n    {\n        for( comma::uint32 i = 0; i < number_of_clusters; ++i )\n        {\n            if( csv.binary() )\n            {\n                if( use_block ) { std::cout.write( reinterpret_cast< const char* >( &block ), sizeof( block ) ); }\n                std::cout.write( reinterpret_cast< const char* >( &i ), sizeof( i ) );\n                for( const auto point : centroids[i] ) { std::cout.write( reinterpret_cast< const char* >( &point ), sizeof( point ) ); }\n            }\n            else\n            {\n                if( use_block ) { std::cout << block << csv.delimiter; }\n                std::cout << i;\n                for( const auto point : centroids[i] ) { std::cout << csv.delimiter << point; }\n                std::cout << std::endl;\n            }\n        }\n    };\n    auto write_lines_ = []( const std::deque< std::string >& input_lines,\n                            const std::vector< std::vector< double > >& centroids,\n                            const std::vector< comma::uint32 >& centroid_assignments )\n    {\n        for( size_t i = 0; i < centroid_assignments.size(); ++i )\n        {\n            std::cout << input_lines[i];\n            const auto centroid_assignment = centroid_assignments[i];\n            const std::vector< double >& centroid = centroids[centroid_assignment];\n            if( csv.binary() )\n            {\n                std::cout.write( reinterpret_cast< const char* >( &centroid_assignment ), sizeof( centroid_assignment ) );\n                for( const auto point : centroid ) { std::cout.write( reinterpret_cast< const char* >( &point ), sizeof( point ) ); }\n            }\n            else\n            {\n                std::cout << csv.delimiter << centroid_assignment;\n                for( const auto point : centroid ) { std::cout << csv.delimiter << point; }\n                std::cout << std::endl;\n            }\n        }\n    };\n    std::vector< std::vector< double > > centroids;\n    std::vector< comma::uint32 > centroid_assignments;\n    k_means operation{ tolerance, max_iterations, number_of_runs, number_of_clusters };\n    comma::csv::input_stream< input_t > istream( std::cin, csv );\n    while( istream.ready() || std::cin.good() )\n    {\n        const input_t* p = istream.read();\n        if( !dataframe.empty() && ( !p || block != p->block ) )\n        {\n            std::tie( centroids, centroid_assignments ) = operation.run_on_block( dataframe );\n            if( output_centroids ) { write_centroids_only_( centroids, block ); }\n            else { write_lines_( input_lines, centroids, centroid_assignments ); }\n            if( csv.flush ) { std::cout.flush(); }\n            dataframe.clear();\n            input_lines.clear();\n        }\n        if( !p ) { break; }\n        set_input_values_( *p, istream.last() );\n    }\n    return 0;\n}\n\nstatic int run( const comma::command_line_options& options )\n{\n    output_centroids = options.exists( \"--output-centroids,--centroids\" );\n    csv = comma::csv::options( options, \"data\" );\n    std::cout.precision( csv.precision );\n    use_block = csv.has_field( \"block\" );\n    seed = options.optional< std::mt19937::result_type >( \"--seed\" );\n    const auto max_iterations = options.value< unsigned int >( \"--max-iterations,--iterations\", 300 );\n    if( max_iterations == 0 ) { std::cerr << \"math-k-means: got --max-iterations=0, --max-iterations should be at least 1\" << std::endl; return 1; }\n    const auto number_of_clusters = options.value< comma::uint32 >( \"--number-of-clusters,--clusters\" );\n    if( number_of_clusters == 0 ) { std::cerr << \"math-k-means: got --number-of-clusters=0, --number-of-clusters should be at least 1\" << std::endl; return 1; }\n    const auto number_of_runs = options.value< unsigned int >( \"--number-of-runs,--runs\", 10 );\n    if( number_of_runs == 0 ) { std::cerr << \"math-k-means: got --number-of-runs=0, --number-of-runs should be at least 1\" << std::endl; return 1; }\n    size = options.optional< unsigned int >( \"--size\" );\n    auto tolerance = options.value< double >( \"--tolerance\", 1.0e-4 );\n    if( tolerance <= 0 ) { std::cerr << \"math-k-means: got --tolerance=\" << tolerance << \", --tolerance should be greater than 0\" << std::endl; return 1; }\n    if( options.exists( \"--ignore-tolerance\" ) ) { tolerance = -1.0; }\n#ifdef SNARK_USE_CUDA\n    use_pitched = options.exists( \"--cuda-use-pitched,--use-pitched,--pitched\" );\n    return options.exists( \"--cuda\" ) ? run_cuda_( static_cast< float >( tolerance ), max_iterations, number_of_runs, number_of_clusters ) : run_( tolerance, max_iterations, number_of_runs, number_of_clusters );\n#else\n    if( options.exists( \"--cuda\" ) ) { std::cerr << \"math-k-means: given --cuda, but built without cuda support; run anyway, but may be slower than you expect\" << std::endl; }\n    return run_( tolerance, max_iterations, number_of_runs, number_of_clusters );\n#endif\n}\n\nnamespace comma { namespace visiting {\n\ntemplate <>\nstruct traits< snark::k_means::input_t >\n{\n    template < typename K, typename V >\n    static void visit( const K&, snark::k_means::input_t& p, V& v )\n    {\n        v.apply( \"data\", p.data );\n        v.apply( \"block\", p.block );\n    }\n\n    template < typename K, typename V >\n    static void visit( const K&, const snark::k_means::input_t& p, V& v )\n    {\n        v.apply( \"data\", p.data );\n        v.apply( \"block\", p.block );\n    }\n};\n\n#ifdef SNARK_USE_CUDA\ntemplate <>\nstruct traits< snark::cuda::k_means::input_t >\n{\n    template < typename K, typename V >\n    static void visit( const K&, snark::cuda::k_means::input_t& p, V& v )\n    {\n        v.apply( \"data\", p.data );\n        v.apply( \"block\", p.block );\n    }\n\n    template < typename K, typename V >\n    static void visit( const K&, const snark::cuda::k_means::input_t& p, V& v )\n    {\n        v.apply( \"data\", p.data );\n        v.apply( \"block\", p.block );\n    }\n};\n#endif\n\n} } // namespace comma { namespace visiting {\n\nint main( int argc, char** argv )\n{\n    try\n    {\n        comma::command_line_options options( argc, argv, usage );\n        if( options.exists( \"--input-fields\" ) ) { std::cout << \"data\" << std::endl; return 0; }\n        if( options.exists( \"--output-fields\" ) ) { std::cout << \"data,centroid/id,centroid/data\" << std::endl; return 0; }\n        verbose = options.exists( \"--verbose,-v\" );\n        auto max_threads = options.value< unsigned int >( \"--max-threads,--threads\", std::thread::hardware_concurrency() );\n        if( max_threads <= 1 )\n        { \n            std::cerr << \"math-k-means: warning: you set or std::thread::hardware_concurrency returned \" << max_threads << \"; will not explicitly call tbb::global_control::max_allowed_parallelism(); everything still will work, but multithreading may not be set to what you expected\" << std::endl;\n            return run( options );\n        }\n        tbb::global_control gc( tbb::global_control::max_allowed_parallelism, max_threads );\n        return run( options );\n    }\n    catch( std::exception& ex ) { std::cerr << \"math-k-means: \" << ex.what() << std::endl; }\n    catch( ... ) { std::cerr << \"math-k-means: unknown exception\" << std::endl; }\n    return 1;\n}\n", "meta": {"hexsha": "2b36cf75ddfb3ae207c9d7119ef0a01d41a50715", "size": 32843, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "math/applications/math-k-means.cpp", "max_stars_repo_name": "mission-systems-pty-ltd/snark", "max_stars_repo_head_hexsha": "2bc8a20292ee3684d3a9897ba6fee43fed8d89ae", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-03-27T00:24:37.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-27T00:24:37.000Z", "max_issues_repo_path": "math/applications/math-k-means.cpp", "max_issues_repo_name": "NEU-LC/snark", "max_issues_repo_head_hexsha": "db890f73f4c4bbe679405f3a607fd9ea373deb2c", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "math/applications/math-k-means.cpp", "max_forks_repo_name": "NEU-LC/snark", "max_forks_repo_head_hexsha": "db890f73f4c4bbe679405f3a607fd9ea373deb2c", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-10-30T02:11:55.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-30T02:11:55.000Z", "avg_line_length": 49.3138138138, "max_line_length": 296, "alphanum_fraction": 0.5669396827, "num_tokens": 7665, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5774953651858118, "lm_q2_score": 0.5813030906443134, "lm_q1q2_score": 0.3356998406152788}}
{"text": "#include \"SimpleTriMesh.h\"\n\n#include <Eigen/StdVector>\n\n#include <map>\n\nvoid SimpleTriMesh::addVertex(double x, double y, double z)\n{\n\tm_vertices.push_back(Eigen::Vector3d(x, y, z));\n}\nvoid SimpleTriMesh::addTri(int i1, int i2, int i3)\n{\n\tm_triangles.push_back(Eigen::Vector3i(i1, i2, i3));\n}\n\nvoid SimpleTriMesh::setFromMatrices(const Eigen::MatrixXd &vertices, const Eigen::MatrixXi &tris)\n{\n\tm_vertices.resize(vertices.cols());\n\tm_triangles.resize(tris.cols());\n\n\tfor (int i = 0; i < (int)m_vertices.size(); i++)\n\t{\n\t\tm_vertices[i] = vertices.col(i);\n\t}\n\tfor (int i = 0; i < (int)m_triangles.size(); i++)\n\t{\n\t\tm_triangles[i] = tris.col(i);\n\t}\n}\nvoid SimpleTriMesh::toMatrices(Eigen::MatrixXd &vertices, Eigen::MatrixXi &tris) const\n{\n\tvertices.resize(3, m_vertices.size());\n\ttris.resize(3, m_triangles.size());\n\n\tfor (int i = 0; i < (int)m_vertices.size(); i++)\n\t{\n\t\tvertices.col(i) = m_vertices[i];\n\t}\n\tfor (int i = 0; i < (int)m_triangles.size(); i++)\n\t{\n\t\ttris.col(i) = m_triangles[i];\n\t}\n}\nclass TriBaryCoords\n{\npublic:\n\tTriBaryCoords(int triIdx, const Eigen::Vector2d &u)\n\t\t:m_triIdx(triIdx),\n\t\tm_u(u)\n\t{\n\t}\n\n\tint getTriIdx() const\n\t{\n\t\treturn m_triIdx;\n\t}\n\n\tEigen::Vector3d getN() const\n\t{\n\t\tEigen::Vector3d N;\n\t\tN << 1.0 - m_u.sum(), m_u;\n\t\treturn N;\n\t}\n\nprivate:\n\tEigen::Vector2d m_u;\n\tint m_triIdx;\npublic:\n\tEIGEN_MAKE_ALIGNED_OPERATOR_NEW\n};\n\nvoid SimpleTriMesh::upsample(int nAdditionalPointsPerEdge)\n{\n\t//the following implementation removes non used vertices\n\n\tint numPointsPerEdge = nAdditionalPointsPerEdge + 2;\n\tint numTrisPerOldFace = (numPointsPerEdge - 1)*(numPointsPerEdge - 1);\n\tint numTris = numTrisPerOldFace * this->m_triangles.size();\n\n\tstd::vector<TriBaryCoords, Eigen::aligned_allocator<TriBaryCoords> > baryCoords;\n\n\tstd::vector<int> oldVertexToBaryCoords(this->m_vertices.size(), -1);\n\tstd::vector<std::map<int, int> > edgeToBaryCoords(this->m_vertices.size());\n\n\tauto getOldVertexIdx = [&oldVertexToBaryCoords, &baryCoords](int oldTriIdx, int v, const Eigen::Vector2d &u) {\n\t\tif (oldVertexToBaryCoords[v] == -1)\n\t\t{\n\t\t\tbaryCoords.push_back(TriBaryCoords(oldTriIdx, u));\n\t\t\toldVertexToBaryCoords[v] = baryCoords.size() - 1;\n\t\t}\n\t\treturn oldVertexToBaryCoords[v];\n\t};\n\tauto getVertexIdxOnEdge = [numPointsPerEdge, &getOldVertexIdx, &baryCoords, &edgeToBaryCoords](\n\t\tint oldTriIdx, int v0, const Eigen::Vector2d &u0, int v1, const Eigen::Vector2d &u1, int col) {\n\t\tif (col == 0) return getOldVertexIdx(oldTriIdx, v0, u0);\n\t\tif (col == numPointsPerEdge - 1) return getOldVertexIdx(oldTriIdx, v1, u1);\n\n\t\tEigen::Vector2d uCopy0 = u0;\n\t\tEigen::Vector2d uCopy1 = u1;\n\n\t\tif (v0 > v1)\n\t\t{\n\t\t\tstd::swap(v0, v1);\n\t\t\tEigen::Vector2d ut = uCopy0;\n\t\t\tuCopy0 = uCopy1;\n\t\t\tuCopy1 = ut;\n\t\t\tcol = numPointsPerEdge - col - 1;\n\t\t}\n\n\t\tif (edgeToBaryCoords[v0].find(v1) == edgeToBaryCoords[v0].end())\n\t\t{\n\t\t\tdouble lambda = col / double(numPointsPerEdge - 1);\n\t\t\tEigen::Vector2d u = (1.0 - lambda) * uCopy0 + lambda * uCopy1;\n\t\t\tbaryCoords.push_back(TriBaryCoords(oldTriIdx, u));\n\t\t\tedgeToBaryCoords[v0].emplace(v1, baryCoords.size() - 1);\n\t\t}\n\n\t\treturn edgeToBaryCoords[v0].find(v1)->second;\n\t};\n\n\tauto getVertexIdx = [this, &getVertexIdxOnEdge, &baryCoords, numPointsPerEdge](int oldTriIdx, int row, int col) {\n\t\tconst Eigen::Vector3i &tri = this->m_triangles[oldTriIdx];\n\n\t\tEigen::Vector2d u0(0.0, 0.0);\n\t\tEigen::Vector2d u1(1.0, 0.0);\n\t\tEigen::Vector2d u2(0.0, 1.0);\n\n\t\tif (row == 0)\n\t\t{\n\t\t\treturn getVertexIdxOnEdge(oldTriIdx, tri[0], u0, tri[1], u1, col);\n\t\t}\n\t\tif (col == 0)\n\t\t{\n\t\t\treturn getVertexIdxOnEdge(oldTriIdx, tri[0], u0, tri[2], u2, row);\n\t\t}\n\t\tif (row - col == 0)\n\t\t{\n\t\t\treturn getVertexIdxOnEdge(oldTriIdx, tri[1], u1, tri[2], u2, row);\n\t\t}\n\n\t\tint numPointsInRow = numPointsPerEdge - row;\n\n\t\tdouble lambda = row / double(numPointsPerEdge - 1);\n\t\tdouble lambda2 = col / double(numPointsInRow - 1);\n\n\t\t//Eigen::Vector2d p1 = (1.0 - lambda) * u0 + lambda * u2;\n\t\t//Eigen::Vector2d p2 = (1.0 - lambda) * u1 + lambda * u2;\n\n\t\t//Eigen::Vector2d u = (1.0 - lambda2) * p1 + lambda2 * p2;\n\n\t\tEigen::Vector2d u(lambda2 * (1.0 - lambda), lambda);\n\n\t\t//if (numPointsInRow == 1) u = Eigen::Vector2d(0.0, lambda);\n\n\t\tbaryCoords.push_back(TriBaryCoords(oldTriIdx, u));\n\n\t\treturn (int)baryCoords.size() - 1;\n\t};\n\n\tEigen::MatrixXi newFaces(3, numTris);\n\n\tfor (int oldTriIdx = 0; oldTriIdx < this->m_triangles.size(); oldTriIdx++)\n\t{\n\t\tint ciTri = 0;\n\t\tfor (int row = 0; row < numPointsPerEdge - 1; row++)\n\t\t{\n\t\t\tint numTrisInRow = numPointsPerEdge - 2 * row;\n\t\t\tfor (int k = 0, baseVertex = 0; k < numTrisInRow; k++, baseVertex++)\n\t\t\t{\n\t\t\t\tEigen::Vector3i newTri;\n\t\t\t\tnewTri[0] = getVertexIdx(oldTriIdx, row, baseVertex);\n\t\t\t\tnewTri[1] = getVertexIdx(oldTriIdx, row, baseVertex + 1);\n\t\t\t\tnewTri[2] = getVertexIdx(oldTriIdx, row + 1, baseVertex);\n\t\t\t\tnewFaces.col(oldTriIdx * numTrisPerOldFace + ciTri) = newTri;\n\t\t\t\tciTri += 1;\n\n\t\t\t\tk++;\n\t\t\t\tif (k >= numTrisInRow) break;\n\n\t\t\t\tnewTri[0] = getVertexIdx(oldTriIdx, row, baseVertex + 1);\n\t\t\t\tnewTri[1] = getVertexIdx(oldTriIdx, row + 1, baseVertex + 1);\n\t\t\t\tnewTri[2] = getVertexIdx(oldTriIdx, row + 1, baseVertex);\n\t\t\t\tnewFaces.col(oldTriIdx * numTrisPerOldFace + ciTri) = newTri;\n\t\t\t\tciTri += 1;\n\t\t\t}\n\t\t}\n\t\tassert(ciTri == numTrisPerOldFace);\n\t}\n\n\tEigen::MatrixXd newVertices(3, baryCoords.size());\n\tfor (int i = 0; i < baryCoords.size(); i++)\n\t{\n\t\tconst Eigen::Vector3i &tri = this->m_triangles[baryCoords[i].getTriIdx()];\n\t\tEigen::Vector3d N = baryCoords[i].getN();\n\t\tEigen::Vector3d v = Eigen::Vector3d::Zero();\n\t\tfor (int j = 0; j < 3; j++)\n\t\t{\n\t\t\tv += N[j] * this->m_vertices[tri[j]];\n\t\t}\n\t\tnewVertices.col(i) = v;\n\t}\n\n\tsetFromMatrices(newVertices, newFaces);\n}\n\nSimpleTriMesh SimpleTriMesh::icosphere()\n{\n\tdouble t = (1.0 + std::sqrt(5.0)) / 2.0;\n\tdouble normalizationFactor = 1.0 / (1.0 + t*t);\n\tdouble u = t * normalizationFactor;\n\tdouble o = 1.0 * normalizationFactor;\n\tSimpleTriMesh mesh;\n\n\tmesh.addVertex(-o, u, 0);\n\tmesh.addVertex(o, u, 0);\n\tmesh.addVertex(-o, -u, 0);\n\tmesh.addVertex(o, -u, 0);\n\n\tmesh.addVertex(0, -o, u);\n\tmesh.addVertex(0, o, u);\n\tmesh.addVertex(0, -o, -u);\n\tmesh.addVertex(0, o, -u);\n\n\tmesh.addVertex(u, 0, -o);\n\tmesh.addVertex(u, 0, o);\n\tmesh.addVertex(-u, 0, -o);\n\tmesh.addVertex(-u, 0, o);\n\n\tmesh.addTri(0, 5, 1);\n\tmesh.addTri(0, 11, 5);\n\tmesh.addTri(0, 1, 7);\n\tmesh.addTri(0, 10, 11);\n\tmesh.addTri(0, 7, 10);\n\n\tmesh.addTri(3, 9, 4);\n\tmesh.addTri(3, 4, 2);\n\tmesh.addTri(3, 2, 6);\n\tmesh.addTri(3, 6, 8);\n\tmesh.addTri(3, 8, 9);\n\n\tmesh.addTri(1, 5, 9);\n\tmesh.addTri(7, 1, 8);\n\tmesh.addTri(10, 7, 6);\n\tmesh.addTri(5, 11, 4);\n\tmesh.addTri(11, 10, 2);\n\n\tmesh.addTri(4, 9, 5);\n\tmesh.addTri(9, 8, 1);\n\tmesh.addTri(6, 2, 10);\n\tmesh.addTri(2, 4, 11);\n\tmesh.addTri(8, 6, 7);\n\n\treturn mesh;\n}\nSimpleTriMesh SimpleTriMesh::icosphere(int nSubdivisions)\n{\n\tSimpleTriMesh mesh = SimpleTriMesh::icosphere();\n\tfor (int i = 0; i < nSubdivisions; i++)\n\t{\n\t\tmesh.upsample(1);\n\t\tfor (auto &vertex : mesh.vertices())\n\t\t{\n\t\t\tvertex.normalize();\n\t\t}\n\t}\n\treturn mesh;\n}", "meta": {"hexsha": "5c12240e3985a4b117f109e7a960a4a25ed5f3fa", "size": 6942, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/SimpleTriMesh.cpp", "max_stars_repo_name": "JonasZehn/YAPS", "max_stars_repo_head_hexsha": "df1fea7d43e0a7e658086d3be42cc4675e7a547a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/SimpleTriMesh.cpp", "max_issues_repo_name": "JonasZehn/YAPS", "max_issues_repo_head_hexsha": "df1fea7d43e0a7e658086d3be42cc4675e7a547a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/SimpleTriMesh.cpp", "max_forks_repo_name": "JonasZehn/YAPS", "max_forks_repo_head_hexsha": "df1fea7d43e0a7e658086d3be42cc4675e7a547a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.0, "max_line_length": 114, "alphanum_fraction": 0.6560069144, "num_tokens": 2537, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5813030906443133, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.33569984061527874}}
{"text": "#ifndef __PARTICLE_FILTER_HPP\n#define __PARTICLE_FILTER_HPP\n\n\n#include <boost/random/discrete_distribution.hpp>\n\n#include \"particle_filter_base.hpp\"\n\n\ntemplate <size_t Size>\nParticleFilter<Size>::ParticleFilter(const PredictionModel<Size> &pm,\n\t\t\t\t     const LikelihoodModel<Size> &lm,\n\t\t\t\t     unsigned int nParticles,\n\t\t\t\t     const double *initState):\n  pm(pm),\n  lm(lm),\n  particles(std::vector<Particle<Size> >(nParticles)),\n  epoch(0)\n{\n  if (initState)\n  {\n    pm.init(initState, particles);\n  }\n  else\n  {\n    double *_initState = new double[Size];\n    std::fill(_initState, _initState+Size, 0);\n    pm.init(initState, particles);\n    delete []_initState;\n  }\n}\n\n\ntemplate <size_t Size>\nconst std::vector<Particle<Size> > &ParticleFilter<Size>::getParticles() const\n{\n  return particles;\n}\n\ntemplate <size_t Size>\nconst Particle<Size> &ParticleFilter<Size>::getBestParticle() const\n{\n  \n  double bestLikelihood = particles.at(0).likelihood;\n  int bestID = 0;\n\n  for (typename std::vector<Particle<Size> >::const_iterator it=particles.begin()+1;\n       it!=particles.end(); ++it)\n  {\n    const Particle<Size> &p = *it;\n    if (p.likelihood>bestLikelihood)\n    {\n      bestLikelihood = p.likelihood;\n      bestID = it-particles.begin();\n    }\n  }\n\n  return particles.at(bestID);\n}\n\n\ntemplate <size_t Size>\nvoid ParticleFilter<Size>::step(double deltaT)\n{\n  // Create a copy of the current particles\n  std::vector<Particle<Size> > tempParticles(particles.size());\n  std::copy(particles.begin(), particles.end(), tempParticles.begin());\n\n  // Particle filter iteration\n  // - update the particles state using the provided state-update model\n  pm.update(tempParticles, deltaT);\n\n  // - compute the importance weights using the provided likelihood model\n  lm.eval(tempParticles);\n  \n  // Normalize the particles weight (and build the list of normalized weights\n  // used in the next selection step)\n  double wSum = 0.;\n  for (typename std::vector<Particle<Size> >::iterator it=tempParticles.begin();\n       it!=tempParticles.end(); ++it)\n  {\n    const Particle<Size> &p = *it;\n    wSum += p.likelihood;\n  }\n\n  std::vector<double> normW;\n  for (typename std::vector<Particle<Size> >::iterator it=tempParticles.begin();\n       it!=tempParticles.end(); ++it)\n  {\n    Particle<Size> &p = *it;\n    p.likelihood /= wSum;\n    normW.push_back(p.likelihood);\n  }\n\n  // - selection step\n  // TODO: parameterize at which epoch execute selection\n  //if (!(epoch%10))\n  if (true)\n  {\n    boost::random::discrete_distribution<> D(normW.begin(), normW.end());\n\n    std::vector<int> idx;\n    for (int i=0; i<tempParticles.size(); i++) idx.push_back(D(rng));\n  \n    // Copy back the selected particles\n    for (int i=0; i<idx.size(); i++) particles.at(i) = tempParticles.at(idx.at(i));\n  }\n  else\n  {\n    std::copy(tempParticles.begin(), tempParticles.end(), particles.begin());\n  }\n\n  epoch++;\n\n  // Done\n}\n\n#endif // __PARTICLE_FILTER_HPP\n", "meta": {"hexsha": "e6dc3f70ab37262a0c6030bf0401ae488ad3e45b", "size": 2926, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/particle_filter/particle_filter.hpp", "max_stars_repo_name": "mUogoro/hand_rotation_estimation_tutorial", "max_stars_repo_head_hexsha": "98707de67448016e63bb8480090e4fa139dbc896", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2017-09-15T01:05:09.000Z", "max_stars_repo_stars_event_max_datetime": "2017-09-15T01:05:09.000Z", "max_issues_repo_path": "src/particle_filter/particle_filter.hpp", "max_issues_repo_name": "mUogoro/hand_rotation_estimation_tutorial", "max_issues_repo_head_hexsha": "98707de67448016e63bb8480090e4fa139dbc896", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/particle_filter/particle_filter.hpp", "max_forks_repo_name": "mUogoro/hand_rotation_estimation_tutorial", "max_forks_repo_head_hexsha": "98707de67448016e63bb8480090e4fa139dbc896", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2018-11-08T09:15:38.000Z", "max_forks_repo_forks_event_max_datetime": "2019-05-29T07:57:45.000Z", "avg_line_length": 24.5882352941, "max_line_length": 84, "alphanum_fraction": 0.6722488038, "num_tokens": 761, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5774953651858118, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.33569984061527874}}
{"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) 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#include <numeric>\n\n#include <boost/timer/timer.hpp>\n\n#include <dune/common/fmatrix.hh>\n#include \"dune/grid/config.h\"\n\n#include \"linalg/threadedMatrix.hh\"\n\n\nusing namespace Kaskade;\n\n// Create a NxN lower triangular matrix with 1x2 entries \n// as a mockup of the divergence discretization in Stokes problems\ntemplate <class Index>\nvoid divergence(Index const N)\n{\n  std::cout << \"running divergence with N=\" << N << \"\\n\";\n  \n  // First, sparsity pattern creation. We proceed row by row.\n  NumaCRSPatternCreator<Index> creator(N,N,false);\n  \n  boost::timer::cpu_timer timer;\n  std::vector<std::vector<Index>> cols(N), rows(N);\n  for (Index k=0; k<cols.size(); ++k)\n  {\n    cols[k].resize(k+1);\n    rows[k].resize(1);\n    std::iota(begin(cols[k]),end(cols[k]),0);\n    rows[k][0] = k;\n  }\n  std::cerr << \"en bloc filling of indices: \" << timer.format() << \"\\n\";\n  timer.start();\n  creator.addElements(rows,cols);\n  std::cerr << \"en bloc adding elements:    \" << timer.format() << \"\\n\";\n  \n  // Next, create a sparsity pattern from the creator and a matrix.\n  timer.start();\n  creator.balance();\n  std::cerr << \"balance:                    \" << timer.format() << \"\\n\";\n  timer.start();\n  std::shared_ptr<NumaCRSPattern<Index>> pattern(new NumaCRSPattern<Index>(creator));\n  std::cerr << \"pattern creation:           \" << timer.format() << \"\\n\";\n  std::cout << \"nonzero entries: \" << pattern->nonzeroes() << \"\\n\";\n  std::cout << \"storage size:    \" << pattern->storage() << \"\\n\";\n  for (int i=0; i<pattern->nodes(); ++i)\n  {\n    auto const& cp = *pattern->pattern(i);\n    std::cout << \"chunk \" << i << \": [\" << cp.first() << \",\" << cp.last() << \"[  nnz=\" << cp.nonzeroes() << \"  size=\" << cp.storage() << \"\\n\";\n  }\n  timer.start();\n  NumaBCRSMatrix<Dune::FieldMatrix<double,1,2>,Index> matrix(pattern);\n  std::cerr << \"matrix creation:            \" << timer.format() << \"\\n\";\n  \n  // Fill the matrix with ones.\n  for (auto r=matrix.begin(); r!=matrix.end(); ++r)\n    for (auto c=r->begin(); c!=r->end(); ++c)\n      *c = 1.0;\n  \n  Dune::BlockVector<Dune::FieldVector<double,2>> x(N);\n  Dune::BlockVector<Dune::FieldVector<double,1>> y(N);\n  for (int i=0; i<N; ++i)\n  {\n    x[i] = 1;\n    y[i] = 0;\n  }\n  \n  timer.start();\n  // Compute 1000 matrix-vector products\n  for (int i=0; i<1000; ++i) \n    matrix.umv(x,y);\n  std::cout << \"1000 Ax: \" << timer.format() << \"\\n\";\n  \n  timer.start();\n  for (int i=0; i<1000; ++i) \n    matrix.umtv(x,y);\n  std::cout << \"1000 A^Tx: \" << timer.format() << \"\\n\";\n  std::cout << \"-----------------------------\\n\\n\";\n}\n\n\n\n// Create a NxN Toeplitz matrix of bandwidth 5\ntemplate <class Index>\nvoid toeplitz(Index const N, bool symmetric)\n{\n  std::cout << \"running toeplitz with symmetric=\" << symmetric << \"\\n\";\n  \n  // First, sparsity pattern creation. The pattern is a superposition of \n  // 5x5 blocks on the diagonal. To begin with, we add a couple of those blocks\n  // individually.\n  NumaCRSPatternCreator<Index> creator(N,N,symmetric,14);\n  \n  std::vector<int> idx(5);\n  for (int k=0; k<100; ++k)\n  {\n    std::iota(begin(idx),end(idx),k);\n    creator.addElements(begin(idx),end(idx),begin(idx),end(idx));\n  }\n  \n  // The rest is filled en bloc.\n  boost::timer::cpu_timer timer;\n  std::vector<std::vector<Index>> cols(N-104), rows(N-104);\n  for (Index k=0; k<cols.size(); ++k)\n  {\n    cols[k].resize(5);\n    rows[k].resize(5);\n    std::iota(begin(cols[k]),end(cols[k]),k+100);\n    std::iota(begin(rows[k]),end(rows[k]),k+100);\n  }\n  std::cerr << \"en bloc filling of indices: \" << timer.format() << \"\\n\";\n  timer.start();\n  creator.addElements(rows,cols);\n  std::cerr << \"en bloc adding elements:    \" << timer.format() << \"\\n\";\n  \n  // Next, create a sparsity pattern from the creator and a matrix.\n  timer.start();\n  creator.balance();\n  std::cerr << \"balance:                    \" << timer.format() << \"\\n\";\n  timer.start();\n  std::shared_ptr<NumaCRSPattern<Index>> pattern(new NumaCRSPattern<Index>(creator));\n  std::cerr << \"pattern creation:           \" << timer.format() << \"\\n\";\n  std::cout << \"nonzero entries: \" << pattern->nonzeroes() << \"\\n\";\n  std::cout << \"storage size:    \" << pattern->storage() << \"\\n\";\n  for (int i=0; i<pattern->nodes(); ++i)\n  {\n    auto const& cp = *pattern->pattern(i);\n    std::cout << \"chunk \" << i << \": [\" << cp.first() << \",\" << cp.last() << \"[  nnz=\" << cp.nonzeroes() << \"  size=\" << cp.storage() << \"\\n\";\n  }\n  timer.start();\n  NumaBCRSMatrix<Dune::FieldMatrix<double,1,1>,Index> matrix(pattern);\n  std::cerr << \"matrix creation:            \" << timer.format() << \"\\n\";\n  \n  // Fill the matrix with ones.\n  for (auto r=matrix.begin(); r!=matrix.end(); ++r)\n    for (auto c=r->begin(); c!=r->end(); ++c)\n      *c = 1.0;\n  \n  Dune::BlockVector<Dune::FieldVector<double,1>> x(N), y(N);\n  for (int i=0; i<N; ++i)\n    x[i] = 1;\n  \n  timer.start();\n  // Compute maximum eigenvalue by power method\n  double mx = 0;\n  double dp;\n  for (int i=0; i<2000; ++i) \n  {\n    dp = matrix.smv(.125,x,y);\n    if (i%100==0 || i>1995)\n    {\n      mx = 0;\n      for (int i=0; i<N; i+=16)\n        mx += std::abs(y[i][0]);\n      for (int i=0; i<N; ++i)\n        x[i] = y[i]/mx;\n    }\n  }\n  std::cout << \"2000 iterations power method: \" << timer.format() << \"\\n\";\n  std::cout.precision(8);\n  std::cout << \"max eigenvalue: \" << 8*mx << \"\\n\";\n  std::cout << \"dp: \" << dp << \"\\n\";\n  \n  matrix = 1.0;\n  \n  if (!symmetric)\n  {\n    for (int i=0; i<N; ++i)\n      x[i] = 1;\n    timer.start();\n    for (int i=0; i<2000; ++i) \n    {\n      matrix.smtv(.125,x,y);\n      if (i%100==0 || i>1995)\n      {\n        mx = 0;\n        for (int i=0; i<N; i+=16)\n          mx += std::abs(y[i][0]);\n        for (int i=0; i<N; ++i)\n          x[i] = y[i]/mx;\n      }\n    }\n    std::cout << \"2000 iterations power method: \" << timer.format() << \"\\n\";\n    std::cout.precision(8);\n    std::cout << \"max eigenvalue: \" << 8*mx << \"\\n\";\n  }\n  std::cout << \"-----------------------------\\n\\n\";\n}\n\nint main(void) \n{\n  int N = 64000;\n  toeplitz(N,false);\n  toeplitz(static_cast<size_t>(N),true);\n  divergence(2000);\n  return 0;\n}", "meta": {"hexsha": "dbf4c7cc7a97bd25da9b0f0e600b68000031a3df", "size": 6924, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Kaskade/tests/threadedMatrixTest.cpp", "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/tests/threadedMatrixTest.cpp", "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/tests/threadedMatrixTest.cpp", "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": 33.1291866029, "max_line_length": 142, "alphanum_fraction": 0.5095320624, "num_tokens": 2102, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5851011542032312, "lm_q2_score": 0.5736784074525096, "lm_q1q2_score": 0.33565989834193494}}
{"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// by S. Efthymiou, October 2018\n\n#include <Eigen/Dense>\n#include <iostream>\n#include <vector>\n#include \"Utils/all_utils.hpp\"\n#include \"Utils/lookup.hpp\"\n\n#ifndef NETKET_MPS_PERIODIC_HPP\n#define NETKET_MPS_PERIODIC_HPP\n\nnamespace netket {\n\ntemplate <typename T, bool diag>\nclass MPSPeriodic : public AbstractMachine<T> {\n  using VectorType = typename AbstractMachine<T>::VectorType;\n  using MatrixType = typename AbstractMachine<T>::MatrixType;\n  using VectorRefType = typename AbstractMachine<T>::VectorRefType;\n  using VectorConstRefType = typename AbstractMachine<T>::VectorConstRefType;\n  using VisibleConstType = typename AbstractMachine<T>::VisibleConstType;\n\n  const AbstractHilbert &hilbert_;\n\n  // Number of sites\n  int N_;\n  // Physical dimension\n  int d_;\n  // Bond dimension\n  int D_;\n  // Second matrix dimension (D for normal MPS, 1 for diagonal)\n  int Dsec_;\n  // D squared\n  int Dsq_;\n  // Number of variational parameters\n  int npar_;\n  // Period of translational symmetry (has to be a divisor of N)\n  int symperiod_;\n\n  // Used for tree look up\n  int Nleaves_;\n  // Map from site that changes to the corresponding \"leaves\"\n  // Shape (N_, nr of leaves for the corresponding site)\n  std::vector<std::vector<int>> leaves_of_site_;\n  // Contractions needed to produce each leaf\n  // Shape (total leaves, 2)\n  std::vector<std::vector<int>> leaf_contractions_;\n\n  // MPS Matrices (stored as [symperiod, d, D, D] or [symperiod, d, D, 1])\n  std::vector<std::vector<MatrixType>> W_;\n\n  // Map from Hilbert states to MPS indices\n  std::map<double, int> confindex_;\n  // Identity Matrix\n  MatrixType identity_mat_;\n\n public:\n  using StateType = T;\n  using LookupType = Lookup<T>;\n\n  explicit MPSPeriodic(const AbstractHilbert &hilbert, double bond_dim,\n                       int symperiod = -1)\n      : hilbert_(hilbert),\n        N_(hilbert.Size()),\n        d_(hilbert.LocalSize()),\n        D_(bond_dim),\n        symperiod_(symperiod) {\n    if (symperiod_ == -1) {\n      symperiod_ = N_;\n    }\n\n    Init();\n  }\n\n  inline MatrixType prod(const MatrixType &m1, const MatrixType &m2) const {\n    if (diag) {\n      return m1.cwiseProduct(m2);\n    }\n\n    return m1 * m2;\n  }\n\n  inline T trace(const MatrixType &m) const {\n    if (diag) {\n      return m.sum();\n    }\n    return m.trace();\n  }\n\n  inline void setparamsident(MatrixType &m, VectorConstRefType pars) const {\n    if (diag) {\n      for (int i = 0; i < D_; i++) {\n        m(i, 0) = T(1, 0) + pars(i);\n      }\n    } else {\n      for (int i = 0; i < D_; i++) {\n        for (int j = 0; j < D_; j++) {\n          m(i, j) = pars(i * D_ + j);\n          if (i == j) {\n            m(i, j) += T(1, 0);\n          }\n        }\n      }\n    }\n  }\n\n  // Auxiliary function that defines the matrices\n  void Init() {\n    // Initialize parameters\n    std::vector<MatrixType> pushback_vec;\n    if (diag) {\n      Dsec_ = 1;\n      identity_mat_ = MatrixType::Ones(D_, 1);\n    } else {\n      Dsec_ = D_;\n      identity_mat_ = MatrixType::Identity(D_, D_);\n    }\n    MatrixType init_mat = MatrixType::Zero(D_, Dsec_);\n    Dsq_ = D_ * Dsec_;\n    npar_ = symperiod_ * d_ * Dsq_;\n\n    for (int site = 0; site < symperiod_; site++) {\n      W_.push_back(pushback_vec);\n      for (int spin = 0; spin < d_; spin++) {\n        W_[site].push_back(init_mat);\n      }\n    }\n\n    // Initialize tree parameters\n    InitTree();\n\n    // Machine creation messages\n    if (diag) {\n      InfoMessage() << \"Periodic diagonal MPS machine with \" << N_\n                    << \" sites created\" << std::endl;\n    } else {\n      InfoMessage() << \"Periodic MPS machine with \" << N_ << \" sites created\"\n                    << std::endl;\n    }\n    InfoMessage() << \"Physical dimension d = \" << d_\n                  << \" and bond dimension D = \" << D_ << std::endl;\n    if (symperiod_ < N_) {\n      InfoMessage() << \"Translation invariance is used. Number of \"\n                       \"variational parameters is \"\n                    << npar_ << \" instead of \" << npar_ * N_ / symperiod_\n                    << std::endl;\n    } else {\n      InfoMessage() << \"Number of variational parameters is \" << npar_\n                    << std::endl;\n    }\n    // Initialize map from Hilbert space states to MPS indices\n    auto localstates = hilbert_.LocalStates();\n    for (int i = 0; i < d_; i++) {\n      confindex_[localstates[i]] = i;\n    }\n  }\n\n  void InitTree() {\n    // Initializes vectors used for tree look up tables\n    // leaves_of_site_ and leaf_contractions_\n\n    std::vector<int> two_vector(2), empty_vector, level_start;\n    std::vector<std::vector<int>> above;\n    int level = 1, available_ind = 0, available_level = 0;\n    bool available = false;\n\n    level_start.push_back(0);\n    level_start.push_back(N_);\n\n    int length = level_start[level] - level_start[level - 1];\n    while (length > 1 or available) {\n      above.push_back(empty_vector);\n      // Iterate level-1\n      for (int i = 0; i < length - 1; i += 2) {\n        // Construct above for level-1\n        above.back().push_back(level_start[level] + i / 2);\n        above.back().push_back(level_start[level] + i / 2);\n        // Construct leaf_contractions_ for level\n        two_vector[0] = level_start[level - 1] + i;\n        two_vector[1] = level_start[level - 1] + i + 1;\n        leaf_contractions_.push_back(two_vector);\n      }\n      if (length % 2 == 1) {\n        if (available) {\n          // Connect the two odd leaves\n          above.back().push_back(level_start[level] + (length - 1) / 2);\n          above[available_level].push_back(level_start[level] +\n                                           (length - 1) / 2);\n\n          two_vector[0] = level_start[level] - 1;\n          two_vector[1] = available_ind;\n          leaf_contractions_.push_back(two_vector);\n\n          level_start.push_back(level_start.back() + length / 2 + 1);\n          available = false;\n        } else {\n          available = true;\n          available_ind = level_start[level] - 1;\n          available_level = level - 1;\n          level_start.push_back(level_start.back() + length / 2);\n        }\n      } else {\n        level_start.push_back(level_start.back() + length / 2);\n      }\n      level++;\n      length = level_start[level] - level_start[level - 1];\n    }\n    Nleaves_ = level_start.back();\n\n    // Flatten above vector\n    std::vector<int> flat_above;\n    for (std::size_t l = 0; l < above.size(); l++) {\n      for (std::size_t k = 0; k < above[l].size(); k++) {\n        flat_above.push_back(above[l][k]);\n      }\n    }\n\n    // Create leaves_of_site_ from above vector\n    for (int i = 0; i < N_; i++) {\n      std::vector<int> leaves;\n      leaves.push_back(flat_above[i]);\n      while (flat_above[leaves.back()] < Nleaves_ - 1) {\n        leaves.push_back(flat_above[leaves.back()]);\n      }\n      leaves.push_back(Nleaves_ - 1);\n      leaves_of_site_.push_back(leaves);\n      leaves.clear();\n    }\n    Nleaves_ += -N_;\n  }\n\n  int Npar() const override { return npar_; }\n\n  VectorType GetParameters() override {\n    int k = 0;\n    VectorType pars(npar_);\n\n    for (int site = 0; site < symperiod_; site++) {\n      for (int spin = 0; spin < d_; spin++) {\n        for (int i = 0; i < D_; i++) {\n          for (int j = 0; j < Dsec_; j++) {\n            pars(k) = W_[site][spin](i, j);\n            k++;\n          }\n        }\n      }\n    }\n    return pars;\n  }\n\n  void SetParameters(VectorConstRefType pars) override {\n    int k = 0;\n\n    for (int site = 0; site < symperiod_; site++) {\n      for (int spin = 0; spin < d_; spin++) {\n        for (int i = 0; i < D_; i++) {\n          for (int j = 0; j < Dsec_; j++) {\n            W_[site][spin](i, j) = pars(k);\n            k++;\n          }\n        }\n      }\n    }\n  }\n\n  // Auxiliary function used for setting initial random parameters and adding\n  // identities in every matrix\n  void SetParametersIdentity(VectorConstRefType pars) {\n    int k = 0;\n    for (int site = 0; site < symperiod_; site++) {\n      for (int spin = 0; spin < d_; spin++) {\n        setparamsident(W_[site][spin], pars.segment(k, Dsq_));\n        k += Dsq_;\n      }\n    }\n  }\n\n  void InitRandomPars(int seed, double sigma) override {\n    VectorType pars(npar_);\n\n    netket::RandomGaussian(pars, seed, sigma);\n    SetParametersIdentity(pars);\n  }\n\n  int Nvisible() const override { return N_; }\n\n  void InitLookup(VisibleConstType v, LookupType &lt) override {\n    for (int k = 0; k < Nleaves_; k++) {\n      _InitLookup_check(lt, k);\n      if (leaf_contractions_[k][0] < N_) {\n        if (leaf_contractions_[k][1] < N_) {\n          lt.M(k) = prod(W_[leaf_contractions_[k][0] % symperiod_]\n                           [confindex_[v(leaf_contractions_[k][0])]],\n                         W_[leaf_contractions_[k][1] % symperiod_]\n                           [confindex_[v(leaf_contractions_[k][1])]]);\n        } else {\n          lt.M(k) = prod(W_[leaf_contractions_[k][0] % symperiod_]\n                           [confindex_[v(leaf_contractions_[k][0])]],\n                         lt.M(leaf_contractions_[k][1] - N_));\n        }\n\n      } else {\n        if (leaf_contractions_[k][1] < N_) {\n          lt.M(k) = prod(lt.M(leaf_contractions_[k][0] - N_),\n                         W_[leaf_contractions_[k][1] % symperiod_]\n                           [confindex_[v(leaf_contractions_[k][1])]]);\n        } else {\n          lt.M(k) = prod(lt.M(leaf_contractions_[k][0] - N_),\n                         lt.M(leaf_contractions_[k][1] - N_));\n        }\n      }\n    }\n  }\n\n  // Auxiliary function\n  inline void _InitLookup_check(LookupType &lt, int i) {\n    if (lt.MatrixSize() == i) {\n      lt.AddMatrix(D_, Dsec_);\n    } else {\n      lt.M(i).resize(D_, Dsec_);\n    }\n  }\n\n  // Auxiliary function for sorting indeces\n  // (copied from stackexchange - original answer by Lukasz Wiklendt)\n  inline std::vector<std::size_t> sort_indeces(const std::vector<int> &v) {\n    // initialize original index locations\n    std::vector<std::size_t> idx(v.size());\n    std::iota(idx.begin(), idx.end(), 0);\n    // sort indexes based on comparing values in v\n    std::sort(idx.begin(), idx.end(),\n              [&v](std::size_t i1, std::size_t i2) { return v[i1] < v[i2]; });\n    return idx;\n  }\n\n  void UpdateLookup(VisibleConstType v, const std::vector<int> &tochange,\n                    const std::vector<double> &newconf,\n                    LookupType &lt) override {\n    std::size_t nchange = tochange.size();\n    if (nchange <= 0) {\n      return;\n    }\n\n    MatrixType empty_matrix = MatrixType::Zero(D_, Dsec_);\n    std::vector<std::size_t> sorted_ind = sort_indeces(tochange);\n\n    std::set<int> leaves2update;\n    std::size_t set_len = 0;\n    std::map<int, MatrixType *> base_mat;\n\n    for (std::size_t k = 0; k < nchange; k++) {\n      int site = tochange[sorted_ind[k]];\n      // Add changed visible matrices to map\n      base_mat[site] =\n          &(W_[site % symperiod_][confindex_[newconf[sorted_ind[k]]]]);\n      // Add the rest of matrices that affects\n      for (std::size_t l = 0; l < leaves_of_site_[site].size(); l++) {\n        int leaf = leaves_of_site_[site][l];\n        leaves2update.insert(leaf);\n        if (leaves2update.size() > set_len) {\n          set_len++;\n          for (int i = 0; i < 2; i++) {\n            int lc = leaf_contractions_[leaf - N_][i];\n            if (lc < N_) {\n              if (base_mat.count(lc) == 0) {\n                base_mat[lc] = &(W_[lc % symperiod_][confindex_[v(lc)]]);\n              }\n            } else {\n              base_mat[lc] = &(lt.M(lc - N_));\n            }\n          }\n        }\n      }\n    }\n    for (auto leaf : leaves2update) {\n      lt.M(leaf - N_) = prod(*(base_mat[leaf_contractions_[leaf - N_][0]]),\n                             *(base_mat[leaf_contractions_[leaf - N_][1]]));\n    }\n  }\n\n  // Auxiliary function that calculates contractions from site1 to site2\n  inline MatrixType mps_contraction(VisibleConstType v, const int &site1,\n                                    const int &site2) {\n    MatrixType c = identity_mat_;\n    for (int site = site1; site < site2; site++) {\n      c = prod(c, W_[site % symperiod_][confindex_[v(site)]]);\n    }\n    return c;\n  }\n\n  T LogVal(VisibleConstType v) override {\n    return std::log(trace(mps_contraction(v, 0, N_)));\n  }\n\n  T LogVal(VisibleConstType /* v */, const LookupType &lt) override {\n    return std::log(trace(lt.M(Nleaves_ - 1)));\n  }\n\n  VectorType LogValDiff(\n      VisibleConstType v, const std::vector<std::vector<int>> &tochange,\n      const std::vector<std::vector<double>> &newconf) override {\n    const std::size_t nconn = tochange.size();\n\n    std::vector<std::size_t> sorted_ind;\n    VectorType logvaldiffs = VectorType::Zero(nconn);\n    StateType current_psi = trace(mps_contraction(v, 0, N_));\n    MatrixType new_prods(D_, Dsec_);\n\n    for (std::size_t k = 0; k < nconn; k++) {\n      std::size_t nchange = tochange[k].size();\n      if (nchange > 0) {\n        sorted_ind = sort_indeces(tochange[k]);\n        int site = tochange[k][sorted_ind[0]];\n\n        if (site == 0) {\n          new_prods = W_[0][confindex_[newconf[k][sorted_ind[0]]]];\n        } else {\n          new_prods = prod(\n              mps_contraction(v, 0, site),\n              W_[site % symperiod_][confindex_[newconf[k][sorted_ind[0]]]]);\n        }\n\n        for (std::size_t i = 1; i < nchange; i++) {\n          site = tochange[k][sorted_ind[i]];\n          new_prods = prod(\n              new_prods,\n              prod(mps_contraction(v, tochange[k][sorted_ind[i - 1]] + 1, site),\n                   W_[site % symperiod_]\n                     [confindex_[newconf[k][sorted_ind[i]]]]));\n        }\n        site = tochange[k][sorted_ind[nchange - 1]];\n        if (site < N_ - 1) {\n          new_prods = prod(new_prods, mps_contraction(v, site + 1, N_));\n        }\n        logvaldiffs(k) = std::log(trace(new_prods) / current_psi);\n      }\n    }\n    return logvaldiffs;\n  }\n\n  T LogValDiff(VisibleConstType v, const std::vector<int> &toflip,\n               const std::vector<double> &newconf,\n               const LookupType &lt) override {\n    // Assumes number of levels > 1 (?)\n    std::size_t nflip = toflip.size();\n    if (nflip <= 0) {\n      return T(0, 0);\n    }\n\n    MatrixType empty_matrix = MatrixType::Zero(D_, Dsec_);\n    std::vector<std::size_t> sorted_ind = sort_indeces(toflip);\n\n    std::set<int> leaves2update;\n    std::map<int, MatrixType> ltpM;\n    std::size_t set_len = 0;\n\n    std::vector<bool> two_vector(2, false);\n    std::map<int, std::vector<bool>> contractions_change;\n\n    for (std::size_t k = 0; k < nflip; k++) {\n      int site = toflip[sorted_ind[k]];\n      // Add changed visible matrices to map\n      ltpM[site] = W_[site % symperiod_][confindex_[newconf[sorted_ind[k]]]];\n\n      // Add the rest of matrices that affects\n      for (std::size_t l = 0; l < leaves_of_site_[site].size(); l++) {\n        int leaf = leaves_of_site_[site][l];\n        leaves2update.insert(leaf);\n        if (leaves2update.size() > set_len) {\n          set_len++;\n          ltpM[leaf] = empty_matrix;\n        }\n        // Check the contractions of the new matrix (if they change)\n        for (int i = 0; i < 2; i++) {\n          if (std::find(toflip.begin(), toflip.end(),\n                        leaf_contractions_[leaf - N_][i]) != toflip.end()) {\n            two_vector[i] = true;\n          } else if (leaves2update.find(leaf_contractions_[leaf - N_][i]) !=\n                     leaves2update.end()) {\n            two_vector[i] = true;\n          }\n        }\n        contractions_change[leaf] = two_vector;\n        two_vector[0] = false;\n        two_vector[1] = false;\n      }\n    }\n\n    // Calculate products\n    for (auto leaf : leaves2update) {\n      std::vector<MatrixType> m(2);\n      for (int i = 0; i < 2; i++) {\n        int lc = leaf_contractions_[leaf - N_][i];\n        if (contractions_change[leaf][i]) {\n          m[i] = ltpM[lc];\n        } else {\n          if (lc < N_) {\n            m[i] = W_[lc % symperiod_][confindex_[v(lc)]];\n          } else {\n            m[i] = lt.M(lc - N_);\n          }\n        }\n      }\n      ltpM[leaf] = prod(m[0], m[1]);\n    }\n    return std::log(trace(ltpM[Nleaves_ + N_ - 1]) / trace(lt.M(Nleaves_ - 1)));\n  }\n\n  // Derivative with full calculation\n  VectorType DerLog(VisibleConstType v) override {\n    MatrixType temp_product(D_, Dsec_);\n    std::vector<MatrixType> left_prods, right_prods;\n    VectorType der = VectorType::Zero(npar_);\n\n    // Calculate products\n    left_prods.push_back(W_[0][confindex_[v(0)]]);\n    right_prods.push_back(W_[(N_ - 1) % symperiod_][confindex_[v(N_ - 1)]]);\n    for (int site = 1; site < N_ - 1; site++) {\n      left_prods.push_back(prod(left_prods[site - 1],\n                                W_[site % symperiod_][confindex_[v(site)]]));\n      right_prods.push_back(\n          prod(W_[(N_ - 1 - site) % symperiod_][confindex_[v(N_ - 1 - site)]],\n               right_prods[site - 1]));\n    }\n    left_prods.push_back(prod(\n        left_prods[N_ - 2], W_[(N_ - 1) % symperiod_][confindex_[v(N_ - 1)]]));\n    right_prods.push_back(prod(W_[0][confindex_[v(0)]], right_prods[N_ - 2]));\n\n    der.segment(confindex_[v(0)] * Dsq_, Dsq_) +=\n        Eigen::Map<VectorType>(right_prods[N_ - 2].transpose().data(), Dsq_);\n    for (int site = 1; site < N_ - 1; site++) {\n      temp_product = prod(right_prods[N_ - site - 2], left_prods[site - 1]);\n      der.segment((d_ * (site % symperiod_) + confindex_[v(site)]) * Dsq_,\n                  Dsq_) +=\n          Eigen::Map<VectorType>(temp_product.transpose().data(), Dsq_);\n    }\n    der.segment((d_ * ((N_ - 1) % symperiod_) + confindex_[v(N_ - 1)]) * Dsq_,\n                Dsq_) +=\n        Eigen::Map<VectorType>(left_prods[N_ - 2].transpose().data(), Dsq_);\n\n    return der / trace(left_prods[N_ - 1]);\n  }\n\n  const AbstractHilbert &GetHilbert() const noexcept override {\n    return hilbert_;\n  }\n\n  // Json functions\n  void to_json(json &j) const override {\n    j[\"Name\"] = \"MPSperiodic\";\n    j[\"Length\"] = N_;\n    j[\"BondDim\"] = D_;\n    j[\"PhysDim\"] = d_;\n    j[\"Diagonal\"] = diag;\n    j[\"SymmetryPeriod\"] = symperiod_;\n    for (int i = 0; i < symperiod_; i++) {\n      for (int k = 0; k < d_; k++) {\n        j[\"W\" + std::to_string(d_ * i + k)] = W_[i][k];\n      }\n    }\n  }\n\n  void from_json(const json &pars) override {\n    if (pars.at(\"Name\") != \"MPSperiodic\") {\n      throw InvalidInputError(\"Error while constructing MPS from Json input\");\n    }\n\n    if (FieldExists(pars, \"Length\")) {\n      N_ = pars[\"Length\"];\n    }\n    if (N_ != hilbert_.Size()) {\n      throw InvalidInputError(\n          \"Number of spins is incompatible with given Hilbert space\");\n    }\n\n    if (FieldExists(pars, \"PhysDim\")) {\n      d_ = pars[\"PhysDim\"];\n    }\n    if (d_ != hilbert_.LocalSize()) {\n      throw InvalidInputError(\n          \"Number of spins is incompatible with given Hilbert space\");\n    }\n\n    if (FieldExists(pars, \"BondDim\")) {\n      D_ = pars[\"BondDim\"];\n    } else {\n      throw InvalidInputError(\"Unspecified bond dimension\");\n    }\n\n    if (FieldExists(pars, \"SymmetryPeriod\")) {\n      symperiod_ = pars[\"SymmetryPeriod\"];\n    } else {\n      // Default is symperiod = N, resp. no translational symmetry\n      symperiod_ = N_;\n    }\n\n    Init();\n\n    // Loading parameters, if defined in the input\n    from_jsonWeights(pars);\n  }\n\n  inline void from_jsonWeights(const json &pars) {\n    for (int i = 0; i < symperiod_; i++) {\n      for (int k = 0; k < d_; k++) {\n        if (FieldExists(pars, \"W\" + std::to_string(d_ * i + k))) {\n          W_[i][k] = pars[\"W\" + std::to_string(d_ * i + k)];\n        }\n      }\n    }\n  }\n};\n\n}  // namespace netket\n\n#endif\n", "meta": {"hexsha": "f6af9900c3579ab7856345b2e481b400ababd5a3", "size": 20172, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "NetKet/Machine/mps_periodic.hpp", "max_stars_repo_name": "GTorlai/netket", "max_stars_repo_head_hexsha": "0c35bfaadeb1253f611f8052b53c9b3d3d9aec9f", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "NetKet/Machine/mps_periodic.hpp", "max_issues_repo_name": "GTorlai/netket", "max_issues_repo_head_hexsha": "0c35bfaadeb1253f611f8052b53c9b3d3d9aec9f", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "NetKet/Machine/mps_periodic.hpp", "max_forks_repo_name": "GTorlai/netket", "max_forks_repo_head_hexsha": "0c35bfaadeb1253f611f8052b53c9b3d3d9aec9f", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.019047619, "max_line_length": 80, "alphanum_fraction": 0.5678167757, "num_tokens": 5707, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7279754489059775, "lm_q2_score": 0.46101677931231594, "lm_q1q2_score": 0.33560889687307116}}
{"text": "/** \nHaha, not all of this code is written by Aman Agrawal \n (Indian Institute of Technology, Delhi)\n*/\n\n#include <bits/stdc++.h>\n#include <Eigen/Dense>\n#include <Eigen/Core>\n#include <Eigen/LU>\n#include <Eigen/SVD>\n#include <Eigen/QR>\n#include <math.h>\n#include <boost/math/distributions/students_t.hpp>\n\n#include \"time.h\"\n#include <thread>\n#include <chrono>\n\n#include \"global.h\"\n#include \"genotype.h\"\n#include \"mailman.h\"\n#include \"helper.h\"\n#include \"storage.h\"\n#include \"Goptions.hpp\"\n#include \"mailbox.h\"\n#include \"EigenGWAS.hpp\"\n\nusing namespace Eigen;\nusing namespace std;\n\n// Storing in RowMajor Form\ntypedef Matrix<double, Dynamic, Dynamic, RowMajor> MatrixXdr;\n\n//options command_line_opts;\nextern Goptions goptions;\nextern genotype g;\n//MatrixXdr geno_matrix; //(p, n)\n\n//Intermediate Variables\n//\n//How to batch columns:\n//int blocksize;\nextern double **partialsums;\nextern double *sum_op;\n\n// Intermediate computations in E-step.\n// Size = 3^(log_3(n)) * k\nextern double **yint_e;\n// n X k\nextern double ***y_e;\n\n// Intermediate computations in M-step. \n// Size = nthreads X 3^(log_3(n)) * k\nextern double **yint_m;\n//  nthreads X log_3(n) X k\nextern double ***y_m;\n\nstruct timespec t0;\n\nMatrixXdr c; //(p,k)\nMatrixXdr means; //(p,1)\nMatrixXdr stds; //(p,1)\nMatrixXdr eveP; //(n,k) //projection matrix for EigenGWAS\nstd::vector<std::vector<double> > pheVal;\nstring phe_File = \"\";\n\npair<double, double> get_error_norm(MatrixXdr &c) {\n\n\tint k = goptions.GetGenericMailmanBlockSize();\n\tint Nsnp = g.Nsnp;\n\tint Nindv = g.Nindv;\n\tint k_orig = goptions.GetGenericEigenvecNumber();\n\n\tHouseholderQR<MatrixXdr> qr(c);\n\tMatrixXdr Q;\n\tQ = qr.householderQ() * MatrixXdr::Identity(Nsnp, k);\n\tMatrixXdr q_t(k, Nsnp);\n\tq_t = Q.transpose();\n\tMatrixXdr b(k, Nindv);\n\t// Need this for subtracting the correct mean in case of missing data\n\tif (goptions.IsGenericMissing()) {\n\t\tmultiply_y_post(q_t, k, b, false);\n\t\t// Just calculating b from seen data\n\t\tMatrixXdr M_temp(k, 1);\n\t\tM_temp = q_t * means;\n\t\tfor (int j = 0; j < Nindv; j++) {\n\t\t\tMatrixXdr M_to_remove(k, 1);\n\t\t\tM_to_remove = MatrixXdr::Zero(k, 1);\n\t\t\tfor (int i = 0; i < g.not_O_j[j].size(); i++) {\n\t\t\t\tint idx = g.not_O_j[j][i];\n\t\t\t\tM_to_remove = M_to_remove + (Q.row(idx).transpose() * g.get_col_mean(idx));\n\t\t\t}\n\t\t\tb.col(j) -= (M_temp - M_to_remove);\n\t\t}\n\t} else {\n\t\tmultiply_y_post(q_t, k, b, true);\n\t}\n\n\tJacobiSVD<MatrixXdr> b_svd(b, ComputeThinU | ComputeThinV);\n\tMatrixXdr u_l, d_l, v_l;\n\tif (goptions.IsGenericFastMode())\n        u_l = b_svd.matrixU();\n    else\n        u_l = Q * b_svd.matrixU();\n\tv_l = b_svd.matrixV();\n\td_l = MatrixXdr::Zero(k, k);\n\tfor (int kk = 0; kk < k; kk++)\n\t\td_l(kk, kk) = (b_svd.singularValues())(kk);\n\n\tMatrixXdr u_k, v_k, d_k;\n\tu_k = u_l.leftCols(k_orig);\n\tv_k = v_l.leftCols(k_orig);\n\td_k = MatrixXdr::Zero(k_orig, k_orig);\n\tfor (int kk = 0; kk < k_orig; kk++)\n\t\td_k(kk, kk) = (b_svd.singularValues())(kk);\n\n\tMatrixXdr b_l, b_k;\n    b_l = u_l * d_l * (v_l.transpose());\n    b_k = u_k * d_k * (v_k.transpose());\n\n    if (goptions.IsGenericFastMode()) {\n        double temp_k = b_k.cwiseProduct(b).sum();\n        double temp_l = b_l.cwiseProduct(b).sum();\n        double b_knorm = b_k.norm();\n        double b_lnorm = b_l.norm();\n        double norm_k = (b_knorm * b_knorm) - (2 * temp_k);\n        double norm_l = (b_lnorm * b_lnorm) - (2 * temp_l);\t\n        return make_pair(norm_k, norm_l);\n    } else {\n        MatrixXdr e_l(Nsnp, Nindv);\n        MatrixXdr e_k(Nsnp, Nindv);\n        for (int p_iter = 0; p_iter < Nsnp; p_iter++) {\n            for (int n_iter = 0; n_iter < Nindv; n_iter++) {\n                e_l(p_iter, n_iter) = g.get_geno(p_iter, n_iter, goptions.IsGenericVarNorm()) - b_l(p_iter, n_iter);\n                e_k(p_iter, n_iter) = g.get_geno(p_iter, n_iter, goptions.IsGenericVarNorm()) - b_k(p_iter, n_iter);\n            }\n        }\n\n        double ek_norm = e_k.norm();\n        double el_norm = e_l.norm();\n        return make_pair(ek_norm, el_norm);\n    }\n}\n\n/* Run one iteration of EM when genotypes are not missing\n * c_orig : p X k matrix\n * Output: c_new : p X k matrix\n */\nMatrixXdr run_EM_not_missing(MatrixXdr &c_orig) {\n\n\tint k = goptions.GetGenericMailmanBlockSize();\n\tint Nsnp = g.Nsnp;\n\tint Nindv = g.Nindv;\n\n\t#if DEBUG==1\n\t\tif (debug) {\n\t\t\tprint_time();\n\t\t\tcout << \"Enter: run_EM_not_missing\" << endl;\n\t\t}\n\t#endif\n\n \t// c_temp : k X p matrix: (C^T C)^{-1} C^{T}\n\tMatrixXdr c_temp(k, Nsnp);\n\tMatrixXdr c_new(Nsnp, k);\n\tc_temp = ((c_orig.transpose() * c_orig).inverse()) * (c_orig.transpose());\n\n\t#if DEBUG == 1\n\t\tif (debug) {\n\t\t\tprint_timenl();\n\t\t}\n\t#endif\n\n \t/*E-step: Compute X = Z G\n \t* G: p X n genotype matrix\n \t* Z: k X p matrix: (C^T C)^{-1} C^{T}\n \t* X: k X n matrix\n \t* x_fn: X\n \t* c_temp: Z\n \t*/\n\tMatrixXdr x_fn(k, Nindv);\n\tmultiply_y_post(c_temp, k, x_fn, true);\n\n\t#if DEBUG == 1\n\t\tif (debug) {\n\t\t\tprint_timenl();\n\t\t}\n\t#endif\n\n\t//x_temp: n X k matrix X^{T} (XX^{T})^{-1}\n\tMatrixXdr x_temp(Nindv, k);\n\tx_temp = (x_fn.transpose()) * ((x_fn*(x_fn.transpose())).inverse());\n\n\t/* M-step: X = G Z\n \t* G: p X n genotype matrix\n \t* Z: n X k matrix: X^{T}(XX^{T})^{-1}\n \t* X = p X k matrix\n \t* c_new: X\n \t* x_temp: Z\n \t*/\n\tmultiply_y_pre(x_temp, k, c_new, true);\n\n\t#if DEBUG==1\n\t\tif(debug) {\n\t\t\tprint_time();\n\t\t\tcout << \"Exiting: run_EM_not_missing\" << endl;\n\t\t}\n\t#endif\n\treturn c_new;\n}\n\nMatrixXdr run_EM_missing(MatrixXdr &c_orig) {\n\tint k = goptions.GetGenericMailmanBlockSize();\n\tint Nsnp = g.Nsnp;\n\tint Nindv = g.Nindv;\n\tMatrixXdr c_new(Nsnp, k);\n\tMatrixXdr mu(k, Nindv);\n\n\t// E step\n\tMatrixXdr c_temp(k, k);\n\tc_temp = c_orig.transpose() * c_orig;\n\n\tMatrixXdr T(k, Nindv);\n\tMatrixXdr c_fn;\n\tc_fn = c_orig.transpose();\n\tmultiply_y_post(c_fn, k, T, false);\n\n\tMatrixXdr M_temp(k, 1);\n\tM_temp = c_orig.transpose() * means;\n\n\tfor (int j = 0; j < Nindv; j++) {\n\t\tMatrixXdr D(k, k);\n\t\tMatrixXdr M_to_remove(k, 1);\n\t\tD = MatrixXdr::Zero(k, k);\n\t\tM_to_remove = MatrixXdr::Zero(k, 1);\n\t\tfor (int i = 0; i < g.not_O_j[j].size(); i++) {\n\t\t\tint idx = g.not_O_j[j][i];\n\t\t\tD = D + (c_orig.row(idx).transpose() * c_orig.row(idx));\n\t\t\tM_to_remove = M_to_remove + (c_orig.row(idx).transpose() * g.get_col_mean(idx));\n\t\t}\n\t\tmu.col(j) = (c_temp - D).inverse() * (T.col(j) - M_temp + M_to_remove);\n\t}\n\n\t#if DEBUG == 1\n\t\tif (debug) {\n\t\t\tofstream x_file;\n//\t\t\tx_file.open((string(command_line_opts.OUTPUT_PATH)+string(\"x_in_fn_vals.txt\")).c_str());\n\t\t\tx_file.open((goptions.GetGenericOutFile() + string(\"x_in_fn_vals.txt\")).c_str());\n\t\t\tx_file<<std::setprecision(15)<<mu<<endl;\n\t\t\tx_file.close();\n\t\t}\n\t#endif\n\n\t// M step\n\tMatrixXdr mu_temp(k, k);\n\tmu_temp = mu * mu.transpose();\n\tMatrixXdr T1(Nsnp, k);\n\tMatrixXdr mu_fn;\n\tmu_fn = mu.transpose();\n\tmultiply_y_pre(mu_fn, k, T1, false);\n\tMatrixXdr mu_sum(k, 1);\n\tmu_sum = MatrixXdr::Zero(k, 1);\n\tmu_sum = mu.rowwise().sum();\n\n\tfor (int i = 0; i < Nsnp; i++) {\n\t\tMatrixXdr D(k, k);\n\t\tMatrixXdr mu_to_remove(k, 1);\n\t\tD = MatrixXdr::Zero(k, k);\n\t\tmu_to_remove = MatrixXdr::Zero(k, 1);\n\t\tfor (int j = 0; j < g.not_O_i[i].size(); j++) {\n\t\t\tint idx = g.not_O_i[i][j];\n\t\t\tD = D + (mu.col(idx) * mu.col(idx).transpose());\n\t\t\tmu_to_remove = mu_to_remove + (mu.col(idx));\n\t\t}\n\t\tc_new.row(i) = (((mu_temp-D).inverse()) * (T1.row(i).transpose() - (g.get_col_mean(i) * (mu_sum-mu_to_remove)))).transpose();\n\t\tdouble mean;\n\t\tmean = g.get_col_sum(i);\n\t\tmean = mean -  (c_orig.row(i) * (mu_sum-mu_to_remove))(0, 0);\n\t\tmean = mean * 1.0 / (Nindv - g.not_O_i[i].size());\n\t\tg.update_col_mean(i, mean);\n\t}\n\n\t// IMPORTANT: Update the value of means variable present locally, so that for next iteration, updated value of means is used.\n\tfor (int i = 0; i < Nsnp; i++) {\n\t\tmeans(i, 0) = g.get_col_mean(i);\n\t\t// Also updating std, just for consistency, though, it is not used presently.\n\t\tstds(i, 0) = g.get_col_std(i);\n\t}\n\n\treturn c_new;\n}\n\nMatrixXdr run_EM(MatrixXdr &c_orig) {\n\tif (goptions.IsGenericMissing()) {\n\t\treturn run_EM_missing(c_orig);\n\t} else {\n\t\treturn run_EM_not_missing(c_orig);\n\t}\n}\n\nvoid print_vals() {\n\tint k = goptions.GetGenericMailmanBlockSize();\n\tint Nsnp = g.Nsnp;\n\tint Nindv = g.Nindv;\n\tint k_orig = goptions.GetGenericEigenvecNumber();\n\n\tHouseholderQR<MatrixXdr> qr(c);\n\tMatrixXdr Q;\n\tQ = qr.householderQ() * MatrixXdr::Identity(Nsnp, k);\n\tMatrixXdr q_t(k, Nsnp);\n\tq_t = Q.transpose();\n\tMatrixXdr b(k, Nindv);\n\n\t// Need this for subtracting the correct mean in case of missing data\n\tif (goptions.IsGenericMissing()) {\n\t\tmultiply_y_post(q_t, k, b, false);\n\t\t// Just calculating b from seen data\n\t\tMatrixXdr M_temp(k, 1);\n\t\tM_temp = q_t * means;\n\t\tfor (int j = 0; j < Nindv; j++) {\n\t\t\tMatrixXdr M_to_remove(k, 1);\n\t\t\tM_to_remove = MatrixXdr::Zero(k, 1);\n\t\t\tfor (int i = 0; i < g.not_O_j[j].size(); i++) {\n\t\t\t\tint idx = g.not_O_j[j][i];\n\t\t\t\tM_to_remove = M_to_remove + (Q.row(idx).transpose() * g.get_col_mean(idx));\n\t\t\t}\n\t\t\tb.col(j) -= (M_temp - M_to_remove);\n\t\t}\n\t} else {\n\t\tmultiply_y_post(q_t, k, b, true);\n\t}\n\n\tJacobiSVD<MatrixXdr> b_svd(b, ComputeThinU | ComputeThinV);\n\tMatrixXdr u_l;\n\tu_l = b_svd.matrixU();\n\tMatrixXdr v_l;\n\tv_l = b_svd.matrixV();\n\tMatrixXdr u_k;\n\tMatrixXdr v_k, d_k;\n\tu_k = u_l.leftCols(k_orig);\n\tv_k = v_l.leftCols(k_orig);\n\n\tofstream evec_file;\n\tevec_file.open((goptions.GetGenericOutFile() + string(\"evecs.txt\")).c_str());\n\tevec_file << std::setprecision(15) << Q * u_k << endl;\n\tevec_file.close();\n\tofstream eval_file;\n\teval_file.open((goptions.GetGenericOutFile() + string(\"evals.txt\")).c_str());\n\tfor(int kk = 0; kk < k_orig; kk++)\n\t\teval_file << std::setprecision(15) << (b_svd.singularValues())(kk) * (b_svd.singularValues())(kk)/g.Nsnp<<endl;\n\teval_file.close();\n\n\teveP = v_l.leftCols(k_orig);\n\tofstream proj_file;\n\tproj_file.open((goptions.GetGenericOutFile() + string(\"projections.txt\")).c_str());\n\tproj_file << std::setprecision(15)<< v_k << endl;\n\tproj_file.close();\n\n\tif (goptions.IsGenericDebug()) {\n\t\tofstream c_file;\n\t\tc_file.open((goptions.GetGenericOutFile()+string(\"cvals.txt\")).c_str());\n\t\tc_file << std::setprecision(15) << c << endl;\n\t\tc_file.close();\n\n\t\tofstream means_file;\n\t\tmeans_file.open((goptions.GetGenericOutFile()+string(\"means.txt\")).c_str());\n\t\tmeans_file << std::setprecision(15) << means << endl;\n\t\tmeans_file.close();\n\n\t\td_k = MatrixXdr::Zero(k_orig, k_orig);\n\t\tfor (int kk =0; kk < k_orig; kk++)\n\t\t\td_k(kk,kk)  =(b_svd.singularValues())(kk);\n\t\tMatrixXdr x_k;\n\t\tx_k = d_k * (v_k.transpose());\n\t\tofstream x_file;\n\t\tx_file.open((goptions.GetGenericOutFile() + string(\"xvals.txt\")).c_str());\n\t\tx_file << std::setprecision(15) << x_k.transpose() << endl;\n\t\tx_file.close();\n\t}\n}\n\nvoid RHE_read_pheno() {\n   \tifstream ifs(goptions.GetGenericPhenoFile().c_str(), ios::in);\n\tstd::string temp;\n\n\twhile (std::getline(ifs, temp)) {\n    std::istringstream buffer(temp);\n    std::vector<double> line((std::istream_iterator<double>(buffer)),\n                             std::istream_iterator<double>());\n    \tpheVal.push_back(line);\n\t}\n\n\t// for (auto it = numbers.begin(); it != numbers.end(); it++) {\n\t// \tvector<double> n1 = *it;\n\t// \tfor (auto it1 = n1.begin(); it1 != n1.end(); it1++) {\n\t// \t\tcout << (*it1) << \" \";\n\t// \t}\n\t// \tcout << endl;\n\t// }\n}\n\nvoid RHE_reg(int seed, int iter, int phe_idx) {\n\n\tcout << \"Randomized HE (mailman), iteration for \" << iter << \" times\" << endl;\n\tclock_t heReg_begin = clock();\n\n\tMatrixXdr yval(g.Nindv, 1);\n\tint cnt = 0;\n\tfor (int i = 0; i < yval.rows(); i++) {\n\t\tyval(i, 0) = pheVal[i][phe_idx];\n\t}\n\tcout<<yval(0, 0)<<\" \"<<yval(1, 0)<<endl;\n\n\tdouble LB = 0;\n\tMatrixXdr Bz(g.Nindv, iter);\n\tsrand(goptions.GetGenericSeed());\n\tstd::default_random_engine generator(goptions.GetGenericSeed());\n\tstd::normal_distribution<double> norm_dist(0, 1.0);\n\tfor (int i = 0; i < Bz.rows(); i++) {\n\t\tfor (int j = 0; j < Bz.cols(); j++) {\n\t\t\tBz(i, j) = norm_dist(generator);\n\t\t}\n\t}\n\n\t//geno_matrix * Bz; //(p x n) * (n x iter) = p x iter\n\tMatrixXdr T1(g.Nsnp, iter);\n\tcout << \"Here T1=G^T * z\" << endl;\n\tmultiply_y_pre(Bz, iter, T1, true);\n\tMatrixXdr T1_transpose(iter, g.Nsnp);\n\tT1_transpose = T1.transpose(); //iter X p\n\tcout << \"Here T1.transpose\" << endl;\n\n\tMatrixXdr T2(iter, g.Nindv);\n\tcout << \"Here T2=T1^T * G^T\" << endl;\n\tcout << T1_transpose.rows() << \" \" << T1_transpose.cols() << \" \" << endl;\n\tmultiply_y_post(T1_transpose, iter, T2, true);\n\n\tfor (int i = 0; i < T2.rows(); i++) {\n\t\tfor (int j = 0; j < T2.cols(); j++) {\n\t\t\tLB += T2(i, j) * T2(i, j);\n\t\t}\n\t}\n\n\tcout << \"LB \" << LB << endl;\n\tLB = LB / (1.0 * iter * g.Nsnp * g.Nsnp);\n\tcout << \"LB2 \" << LB << endl;\n\tdouble me = (LB - g.Nindv) / (1.0 * g.Nindv * g.Nindv);\n\tcout << \"Me \" << 1/me << endl;\n\tclock_t heReg_end = clock();\n\n\tdouble heReg_time = double(heReg_end - heReg_begin) / CLOCKS_PER_SEC;\n\tcout << \"RHE time \" << heReg_time << endl;\n}\n\nvoid ENC(int seed, int kval) {\n\tcout << \"ENC generates \" << kval << \" tags for \" << g.Nindv <<\" samples\" <<endl;\n\tclock_t ENC_begin = clock();\n\n\tsrand(goptions.GetGenericSeed());\n\tstd::default_random_engine generator(goptions.GetGenericSeed());\n\tstd::normal_distribution<double> norm_dist(0, 1.0);\n\n\tMatrixXdr Bz(kval, g.Nsnp);\n\tfor (int i = 0; i < Bz.rows(); i++)\n\t\tfor (int j = 0; j < Bz.cols(); j++)\n\t\t\tBz(i, j) = norm_dist(generator);\n\n\tMatrixXdr encG(kval, g.Nindv);\n\tmultiply_y_post(Bz, kval, encG, true);\n\n\tofstream e_file;\n\te_file.open((goptions.GetGenericOutFile() + string(\".enc.txt\")).c_str());\n\tfor (int i = 0; i < encG.cols(); i++) {\n\t\tfor (int j = 0; j < encG.rows(); j++) {\n\t\t\te_file<<encG(j, i);\n\t\t\tif (j != (encG.rows() - 1)) e_file << \" \";\n\t\t}\n\t\te_file << endl;\n\t}\n\n\te_file.close();\n\tclock_t ENC_end = clock();\n\tdouble ENC_time = double(ENC_end - ENC_begin) / CLOCKS_PER_SEC;\n\tcout<< \"Save encG to \" <<(goptions.GetGenericOutFile() + string(\".enc.txt\")).c_str() <<endl;\n\tcout << \"ENC time \" << ENC_time << endl;\n}\n\nvoid CLD() {\n\n}\n\n\nvoid ProPC() {\n\n\tint k = goptions.GetGenericMailmanBlockSize();\n\tint Nsnp = g.Nsnp;\n\tclock_t pc_begin = clock();\n\n\tpair<double,double> prev_error = make_pair(0.0, 0.0);\n\tbool toStop = false;\n\t\n\t//\tif (convergence_limit != -1)\n\tif (goptions.GetPropcConvergenceLimit() != -1)\n\t\ttoStop = true;\n\n\tdouble prevnll = 0.0;\n\n\tc.resize(Nsnp, k);\n\tmeans.resize(Nsnp, 1);\n\tstds.resize(Nsnp, 1);\n\tfor (int i = 0; i < Nsnp; i++) {\n\t\tmeans(i, 0) = g.get_col_mean(i);\n\t\tstds(i, 0) = g.get_col_std(i);\n\t}\n\n\tstd::default_random_engine generator(goptions.GetGenericSeed());\n\tstd::normal_distribution<double> norm_dist(0, 1.0);\n\tfor (int i = 0; i < c.rows(); i++)\n\t\tfor (int j = 0; j < c.cols(); j++)\n\t\t\tc(i, j) = norm_dist(generator);\n\t// Initial intermediate data structures\n\t// Operate in blocks to improve caching\n\t//\n\n\tofstream c_file;\n\tif (goptions.IsGenericDebug()) {\n\t\t// c_file.open((string(command_line_opts.OUTPUT_PATH) + string(\"cvals_orig.txt\")).c_str());\n\t\tc_file.open((goptions.GetGenericOutFile() + string(\"cvals_orig.txt\")).c_str());\n\t\tc_file << std::setprecision(15) << c << endl;\n\t\tc_file.close();\n\t\tprintf(\"Read Matrix\\n\");\n\t}\n\n\tcout << \"Running on Dataset of \" << g.Nsnp << \" SNPs and \" << g.Nindv << \" Individuals\" << endl;\n\n\t#if SSE_SUPPORT == 1\n\t\tif (fast_mode)\n\t\t\tcout<<\"Using Optimized SSE FastMultiply\"<<endl;\n\t#endif\n\n\tclock_t it_begin = clock();\n\tfor (int i = 0; i < goptions.GetPropcMaxIteration(); i++) {\n\t\tMatrixXdr c1, c2, cint, r, v;\n\t\tdouble a, nll;\n\t\tif (goptions.IsGenericDebug()) {\n\t\t\tprint_time ();\n\t\t\tcout << \"*********** Begin epoch \" << i << \"***********\" << endl;\n\t\t}\n\n//\t\tif (accelerated_em != 0) {\n\t\tif (goptions.GetPropcAcceleratedEM() != 0) {\n\t\t\t#if DEBUG == 1\n\t\t\tif (debug) {\n\t\t\t\tprint_time();\n\t\t\t\tcout << \"Before EM\" << endl;\n\t\t\t}\n\t\t\t#endif\n\t\t\tc1 = run_EM(c);\n\t\t\tc2 = run_EM(c1);\n\t\t\t#if DEBUG == 1\n\t\t\tif (debug) {\n\t\t\t\tprint_time();\n\t\t\t\tcout << \"After EM but before acceleration\" << endl;\n\t\t\t}\n\t\t\t#endif\n\t\t\tr = c1 - c;\n\t\t\tv = (c2 - c1) - r;\n\t\t\ta = -1.0 * r.norm() / (v.norm()) ;\n\t\t\tif (goptions.GetPropcAcceleratedEM() == 1) {\n\t\t\t\tif (a > -1) {\n\t\t\t\t\ta = -1;\n\t\t\t\t\tcint = c2;\n\t\t\t\t} else {\n\t\t\t\t\tcint = c - 2 * a * r + a * a * v;\n\t\t\t\t\tnll = get_error_norm(cint).second;\n\t\t\t\t\tif ( i > 0 ) {\n\t\t\t\t\t\twhile ( nll>prevnll && a < -1) {\n\t\t\t\t\t\t\ta = 0.5 * (a-1);\n\t\t\t\t\t\t\tcint = c - 2 * a * r + (a * a * v);\n\t\t\t\t\t\t\tnll = get_error_norm(cint).second;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tc = cint;\n\t\t\t} else if (goptions.GetPropcAcceleratedEM() == 2) {\n\t\t\t\tcint = c - 2 * a * r + a * a * v;\n\t\t\t\tc = cint;\n\t\t\t\t// c = run_EM(cint);\n\t\t\t}\n\t\t} else {\n\t\t\tc = run_EM(c);\n\t\t}\n\n\t\tif (goptions.GetPropcAcceleratedEM() == 1 || goptions.IsPropcAccuracy() || toStop) {\n\t\t\tpair<double, double> e = get_error_norm(c);\n\t\t\t\tprevnll = e.second;\n\t\t\t\tif (goptions.IsPropcAccuracy())\n\t\t\t\t\tcout << \"Iteration \" << i+1 << \"  \" << std::setprecision(15) << e.first << \"  \" << e.second << endl;\n\t\t\t\tif (abs(e.first - prev_error.first) <= goptions.GetPropcConvergenceLimit()) {\n\t\t\t\t\tcout << \"Breaking after \" << i+1 << \" iterations\" << endl;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tprev_error = e;\n\t\t}\n\n\t\tif (goptions.IsGenericDebug()) {\n\t\t\t\tprint_time();\n\t\t\t\tcout << \"*********** End epoch \" << i << \"***********\" << endl;\n\t\t}\n\t}\n\n\tclock_t it_end = clock();\n\n\tprint_vals();\n\n\tclock_t pc_end = clock();\n\tdouble avg_it_time = double(it_end - it_begin) / (goptions.GetPropcMaxIteration() * 1.0 * CLOCKS_PER_SEC);\n\tdouble total_time = double(pc_end - pc_begin) / CLOCKS_PER_SEC;\n\tcout << \"\\nAVG Iteration Time: \" << avg_it_time << \"\\nTotal runtime: \" << total_time << endl;\n}\n\nint main(int argc, char const *argv[]) {\n\n\ttry {\n    \tgoptions.ParseOptions(argc, argv);\n//      PrintOptions(goptions);\n\t}\n\tcatch (OptionsExitsProgram){}\n\n\tauto start = std::chrono::system_clock::now();\n\tclock_t io_begin = clock();\n    clock_gettime(CLOCK_REALTIME, &t0);\n\n\tsrand(goptions.GetGenericSeed());\n\n\tg.read_geno(goptions.GetGenericGenoFile(),\n\tgoptions.IsGenericTextMode(),\n\tgoptions.IsGenericFastMode(),\n\tgoptions.IsGenericMissing(),\n\tgoptions.IsGenericMemoryEfficient(),\n\tgoptions.IsGenericVarNorm());\n\n\n\t//TODO: Implement these codes.\n/*\t\n\tif (missing && !fast_mode) {\n\t\tcout << \"Missing version works only with mailman i.e. fast mode\\n EXITING...\" << endl;\n\t\texit(-1);\n\t}\n\tif (fast_mode && memory_efficient) {\n\t\tcout << \"Memory effecient version for mailman EM not yet implemented\" << endl;\n\t\tcout << \"Ignoring Memory effecient Flag\" << endl;\n\t}\n\tif (missing && var_normalize) {\n\t\tcout << \"Missing version works only without variance normalization\\n EXITING...\" << endl;\n\t\texit(-1);\n\t}\n*/\n\n\tif (!goptions.IsGenericFastMode() && !goptions.IsGenericMemoryEfficient()) {\n\t\tcout << \"Genotype standardization...\" << endl;\n\t}\n\n\tclock_t io_end = clock();\n\tdouble io_time = double(io_end - io_begin) / CLOCKS_PER_SEC;\n\tcout << \"IO Time: \" << io_time << endl;\n\n\tif (goptions.CheckPropcMasterOption()) {\n\t\tsetMem();\n\t\tProPC();\n\t\tcleanMem();\n\t} else if (goptions.CheckEigenGWASMasterOption()) {\n\t\tsetMem();\n\t\tProPC();\n\t\tEigenGWAS eg;\n\t\teg.Scan(eveP);\n//\t\tEigenGWAS(eveP);\n\t\tcleanMem();\n\t} else if (goptions.CheckRandHEMasterOption()) {\n//\t\tRHE_read_pheno(command_line_opts.PHENO_FILE);\n//\t\tsetMem(command_line_opts.rhe_it);\n//\t\tRHE_reg(seed, command_line_opts.rhe_it, command_line_opts.pheno_num);\n\t\tRHE_read_pheno();\n\t\tsetMem();\n\t\tRHE_reg(goptions.GetGenericSeed(), goptions.GetGenericIteration(), goptions.GetGenericPhenoNum()[0]);\n\t\tcleanMem();\n\t} else if (goptions.CheckEncMasterOption()) {\n\t\tsetMem();\n\n//\t\tgmanENC(seed, goptions.GetEncK(), gman);\n\t\tENC(goptions.GetGenericSeed(), goptions.GetEncK());\n\t\tcleanMem();\n\t} else if (goptions.CheckCLDMasterOption()) {\n\t\tCLD();\n\t}\n\n\tstd::chrono::duration<double> wctduration = std::chrono::system_clock::now() - start;\n\tcout << \"Wall clock time = \" << wctduration.count() << endl;\n\treturn 0;\n}\n", "meta": {"hexsha": "6c454f39d5756b2f6dbae988a88fcac562c72a33", "size": 19467, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/propca.cpp", "max_stars_repo_name": "zzxiang/proEigenGWAS", "max_stars_repo_head_hexsha": "0c5d319ccfe47cf766d6219b646c95cfe911533f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/propca.cpp", "max_issues_repo_name": "zzxiang/proEigenGWAS", "max_issues_repo_head_hexsha": "0c5d319ccfe47cf766d6219b646c95cfe911533f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/propca.cpp", "max_forks_repo_name": "zzxiang/proEigenGWAS", "max_forks_repo_head_hexsha": "0c5d319ccfe47cf766d6219b646c95cfe911533f", "max_forks_repo_licenses": ["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.81, "max_line_length": 127, "alphanum_fraction": 0.6261879077, "num_tokens": 6419, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7279754489059775, "lm_q2_score": 0.4610167793123159, "lm_q1q2_score": 0.33560889687307116}}
{"text": "#include <pybind11/pybind11.h>\n#include <pybind11/stl.h>\n#include <pybind11/complex.h>\n#include <pybind11/numpy.h>\n\n#include <vector>\n#include <string>\n#include <cstdarg>\n#include <cstring>\n#include <cstddef>\n#include <iterator>\n\n#include <boost/lexical_cast.hpp>\n\n#include <CGAL/Exact_predicates_inexact_constructions_kernel.h>\n#include <CGAL/Delaunay_triangulation_3.h>\n#include <CGAL/Triangulation_vertex_base_with_info_3.h>\n\nnamespace py = pybind11;\n\nusing K = CGAL::Exact_predicates_inexact_constructions_kernel;\nusing Vb = CGAL::Triangulation_vertex_base_with_info_3<unsigned int, K>;\nusing Tds = CGAL::Triangulation_data_structure_3<Vb>;\nusing DT = CGAL::Delaunay_triangulation_3<K, Tds>;\n\nusing Point = K::Point_3;\nusing Vertex_handle = DT::Vertex_handle;\nusing Vi = DT::Finite_vertices_iterator;\n\n\ntemplate <typename T>\nclass TypedInputIterator\n{\npublic:\n    using iterator_category = std::input_iterator_tag;\n    using difference_type = std::ptrdiff_t;\n    using value_type = T;\n    using pointer = T*;\n    using reference = T&;\n\n    explicit TypedInputIterator(py::iterator& py_iter) :\n        py_iter_(py_iter)\n    {\n    }\n\n    explicit TypedInputIterator(py::iterator&& py_iter) :\n        py_iter_(py_iter)\n    {\n    }\n\n    value_type operator*()\n    {\n        return (*py_iter_).template cast<value_type>();\n    }\n\n    TypedInputIterator operator++(int)\n    {\n        auto copy = *this;\n        ++py_iter_;\n        return copy;\n    }\n\n    TypedInputIterator& operator++()\n    {\n        ++py_iter_;\n        return *this;\n    }\n\n    bool operator!=(TypedInputIterator &rhs)\n    {\n        return py_iter_ != rhs.py_iter_;\n    }\n\n    bool operator==(TypedInputIterator &rhs)\n    {\n        return py_iter_ == rhs.py_iter_;\n    }\n\nprivate:\n    py::iterator py_iter_;\n};\n\n\nPYBIND11_MODULE(delaunay_class3, m)\n{\n    py::class_<Point>(m, \"Point\")\n            .def(py::init<int, int, int>(),  py::arg(\"x\"), py::arg(\"y\"), py::arg(\"z\"))\n            .def(py::init<double, double, double>(), py::arg(\"x\"), py::arg(\"y\"), py::arg(\"z\"))\n            .def_property_readonly(\"x\", &Point::x)\n            .def_property_readonly(\"y\", &Point::y)\n            .def_property_readonly(\"z\", &Point::z)\n            .def(\"__repr__\",\n            [](const Point &p) {\n                std::string r(\"Point(\");\n                r += boost::lexical_cast<std::string>(p.x());\n                r += \", \";\n                r += boost::lexical_cast<std::string>(p.y());\n                r += \", \";\n                r += boost::lexical_cast<std::string>(p.z());\n                r += \")\";\n                return r;\n            })\n            ;\n\n    py::class_<Vertex_handle>(m, \"VertexHandle\")\n        .def_property_readonly(\n        \"point\",\n        [](const Vertex_handle& vertex_handle)\n        {\n            return vertex_handle->point();\n        })\n        ;\n\n        py::class_<DT>(m, \"DelaunayTriangulation3\")\n\n            .def(py::init())\n\n            .def(\"insert\", [](DT & dt, const std::vector<double> & p) {\n                  std::vector< std::pair<Point,unsigned> > points;\n                  int num_points = p.size()/3;\n                  // start adding at the end of the current table\n                  int start = dt.number_of_vertices();\n                  for(std::size_t i = 0; i < num_points; ++i)\n                  {\n                    // add index information to form face table later\n                     points.push_back( std::make_pair( Point(p[i*3+0],p[i*3+1], p[i*3+2]), start) );\n                     start += 1;\n                  }\n                  return dt.insert(points.begin(),points.end());\n                })\n\n\n            .def(\"move\", [](DT & dt, const std::vector<unsigned int> & to_move, const std::vector<double> & new_positions){\n                    std::vector<Vertex_handle> handles;\n                    std::vector<Point> new_pos;\n                    int num_to_move= to_move.size();\n                    // store all vertex handles\n                    // Should this be finite_vertices_begin and finite_vertices_end?\n                    for (Vi vi = dt.finite_vertices_begin(); vi != dt.finite_vertices_end(); vi++){\n                        handles.push_back(vi);\n                    }\n                    // store new positions as a vector of Point\n                    for(std::size_t i = 0; i < num_to_move; ++i)\n                    {\n                       new_pos.push_back(Point(new_positions[3*i], new_positions[3*i+1], new_positions[3*i+2]));\n                    }\n                    //\n                    for(std::size_t i = 0; i < num_to_move; ++i)\n                    {\n                       dt.move( handles[to_move[i]], new_pos[i] );\n                    }\n                    return dt;\n                    })\n\n            .def(\"remove\", [](DT & dt, const std::vector<unsigned int> & to_remove) {\n                    int num_to_remove= to_remove.size();\n                    std::vector<Vertex_handle> handles;\n                    for (Vi vi = dt.finite_vertices_begin(); vi != dt.finite_vertices_end(); vi++){\n                        handles.push_back(vi);\n                    }\n                    for(std::size_t i=0; i < num_to_remove; ++i){\n                        dt.remove(handles[to_remove[i]]);\n                    }\n                    return dt;\n                })\n\n\n            .def(\"number_of_vertices\", [](DT & dt){\n                    return dt.number_of_vertices();\n                })\n\n            .def(\"number_of_cells\", [](DT & dt){\n                int count=0;\n                for(DT::Finite_cells_iterator fit = dt.finite_cells_begin();\n                fit != dt.finite_cells_end(); ++fit) {\n                    count += 1;\n                }\n                    return count;\n                })\n\n            .def(\"finite_vertices\", [](DT & dt) -> py::iterator\n             {\n                 return py::make_iterator(dt.finite_vertices_begin(), dt.finite_vertices_end());\n             })\n\n            .def(\"get_finite_cells\", [](DT & dt)\n            {\n              // ouput the cell table\n              // YOU MUST CALL get_finite_vertices before if any incremental operations\n              // were performed\n              std::vector<int> cells;\n              cells.resize(dt.number_of_finite_cells()*4);\n\n              int i=0;\n              for(DT::Finite_cells_iterator fit = dt.finite_cells_begin();\n                fit != dt.finite_cells_end(); ++fit) {\n\n                DT::Cell_handle cell = fit;\n                cells[i*4]=cell->vertex(0)->info();\n                cells[i*4+1]=cell->vertex(1)->info();\n                cells[i*4+2]=cell->vertex(2)->info();\n                cells[i*4+3]=cell->vertex(3)->info();\n                i+=1;\n              }\n              ssize_t              soint      = sizeof(int);\n              ssize_t              num_cells = cells.size()/4;\n              ssize_t              ndim      = 2;\n              std::vector<ssize_t> shape     = {num_cells, 4};\n              std::vector<ssize_t> strides   = {soint*4, soint};\n\n              // return 2-D NumPy array\n              return py::array(py::buffer_info(\n                cells.data(),                           /* data as contiguous array  */\n                sizeof(int),                          /* size of one scalar        */\n                py::format_descriptor<int>::format(), /* data type                 */\n                2,                                    /* number of dimensions      */\n                shape,                                   /* shape of the matrix       */\n                strides                                  /* strides for each axis     */\n              ));\n            })\n\n            .def(\"get_finite_vertices\", [](DT & dt)\n             {\n               // ouput the vertices\n               std::vector<double> vertices;\n               vertices.resize(dt.number_of_vertices()*3);\n\n               int i=0;\n               for(DT::Finite_vertices_iterator fit = dt.finite_vertices_begin();\n                 fit != dt.finite_vertices_end(); ++fit) {\n\n                 Vertex_handle vertex = fit;\n                 // critical! update the point index table so faces comes out correctly\n                 vertex->info() = i;\n                 vertices[i*3]=vertex->point().x();\n                 vertices[i*3+1]=vertex->point().y();\n                 vertices[i*3+2]=vertex->point().z();\n                 i+=1;\n               }\n               ssize_t              sdble   = sizeof(double);\n               ssize_t              num_vertices = vertices.size()/3;\n               ssize_t              ndim      = 2;\n               std::vector<ssize_t> shape     = {num_vertices, 3};\n               std::vector<ssize_t> strides   = {sdble*3, sdble};\n\n               // return 2-D NumPy array\n               return py::array(py::buffer_info(\n                 vertices.data(),                           /* data as contiguous array  */\n                 sizeof(double),                          /* size of one scalar        */\n                 py::format_descriptor<double>::format(), /* data type                 */\n                 2,                                    /* number of dimensions      */\n                 shape,                                   /* shape of the matrix       */\n                 strides                                  /* strides for each axis     */\n               ));\n             })\n            ;\n\n\n    py::class_<DT::Finite_vertices_iterator::value_type>(m, \"Vertex\")\n            .def_property_readonly(\n                \"point\", [](DT::Finite_vertices_iterator::value_type& vertex)\n                {\n                    return vertex.point();\n                }\n            )\n            ;\n\n    py::class_<DT::Finite_cells_iterator::value_type>(m, \"Cell\")\n            .def(\"vertex_handle\",\n                [](DT::Finite_cells_iterator::value_type& cell, int index)\n                {\n                    return cell.vertex(index);\n                },\n                py::arg(\"index\")\n            )\n            ;\n\n}\n", "meta": {"hexsha": "c82986e55c2679d831adc201ff2dcfa92e70fd04", "size": 10008, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "SeismicMesh/generation/cpp/delaunay_class3.cpp", "max_stars_repo_name": "WPringle/SeismicMesh", "max_stars_repo_head_hexsha": "9e73aac63ecc4411163dc4093941af946cffae37", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "SeismicMesh/generation/cpp/delaunay_class3.cpp", "max_issues_repo_name": "WPringle/SeismicMesh", "max_issues_repo_head_hexsha": "9e73aac63ecc4411163dc4093941af946cffae37", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "SeismicMesh/generation/cpp/delaunay_class3.cpp", "max_forks_repo_name": "WPringle/SeismicMesh", "max_forks_repo_head_hexsha": "9e73aac63ecc4411163dc4093941af946cffae37", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.8709677419, "max_line_length": 123, "alphanum_fraction": 0.4674260592, "num_tokens": 2136, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7279754371026367, "lm_q2_score": 0.4610167793123159, "lm_q1q2_score": 0.33560889143153294}}
{"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/// \\file CameraCurve.cc\n///\n/// Functions for deducing the camera response curve by comparing\n/// relative brightness values from several images of the same scene.\n\n#include <vw/Camera/Exif.h>\n#include <vw/HDR/CameraCurve.h>\n#include <vw/Math/LinearAlgebra.h>\n#include <boost/algorithm/string.hpp>\n\nnamespace vw {\nnamespace hdr {\n\n  /// Generate a set of brightness values based on a known ratio of\n  /// exposures between images.  Note that this brightness value will\n  /// only be correct in a relative sense.  Given this, we choose\n  /// (arbitrarily) a set of brightness values that correspond to a\n  /// \"typical\" exposure of 1/60th of a second at ISO 100 and an\n  /// aperture of f/5.6 (B = 235.2 in this case)\n  ///\n  ///\n  std::vector<double> brightness_values_from_exposure_ratio(double exposure_ratio, int size) {\n    const double base_brightness = 235.2; // average luminance for\n                                          // 1/60th s exposure at ISO\n                                          // 100 and f/5.6\n    std::vector<double> brightness_values(size);\n    for ( unsigned i=0; i < brightness_values.size(); ++i ) {\n      brightness_values[i] = base_brightness*pow(exposure_ratio, (double)i);\n    }\n    return brightness_values;\n  }\n\n  /// Generate a list of brightness values from EXIF information\n  /// stored in a list of files.\n  std::vector<double> brightness_values_from_exif(std::vector<std::string> const& filenames) {\n    int num_images = filenames.size();\n    std::vector<double> brightness_values(num_images);\n\n    for (int i = 0; i < num_images; i++) {\n      vw::camera::ExifView exif(filenames[i].c_str());\n      brightness_values[i] = exif.get_average_luminance();\n    }\n    return brightness_values;\n  }\n\n  // A simple gaussian weighting function for use in camera curve\n  // estimation (below)\n  inline double gaussian_weighting_func(double x) {\n    return exp(-pow((x-0.5),2)/(0.07));\n  }\n\n  Vector<double> estimate_camera_curve(vw::Matrix<double> const& pixels,\n                                       std::vector<double> const& brightness_values) {\n\n    const int n = 256;                    // Create a solution with 256 points\n    const int smoothing_factor = 10;      // Smoothing by a factor of 10\n\n    // Initialize storage\n    Matrix<double> A(pixels.rows()*pixels.cols()+n+1, n+pixels.rows());\n    Vector<double> b(A.rows());\n\n    // Include data fitting equations\n    int k = 0;\n    for (unsigned i = 0; i < pixels.rows(); ++i) {\n      for (unsigned j = 0; j < pixels.cols(); ++j) {\n        int idx = int(pixels(i,j)*(n-1));\n        double wij = gaussian_weighting_func(pixels(i,j));\n        A(k,idx) = wij;\n        A(k,n+i) = -wij;\n        b(k) = wij * log(1/brightness_values[j]);\n        ++k;\n      }\n    }\n\n    // Fix the curve by setting its middle value to 0\n    A(k,n/2) = 1;\n    ++k;\n\n    // Include the smoothness equations\n    for (int i = 0; i < n-2; ++i) {\n      double weight = gaussian_weighting_func(double(i+1)/(n-1));\n      A(k,i) = smoothing_factor*weight;\n      A(k,i+1) = -2*smoothing_factor*weight;\n      A(k,i+2) = smoothing_factor*weight;\n      ++k;\n    }\n\n    // Solve the system using linear least squares\n    Vector<double> x = least_squares(A, b);\n    return subvector(x,0,n);\n  }\n\n  void write_curves(std::string const& curves_file,\n                    CameraCurveFn const &curves) {\n\n    FILE* output_file = fopen(curves_file.c_str(), \"w\");\n    if ( !output_file ) vw_throw( IOErr() << \"write_curves: failed to open file for writing.\" );\n    for (unsigned i = 0; i < curves.num_channels(); ++i) {\n      for ( unsigned j = 0; j < curves.lookup_table(0).size(); ++j ) {\n        fprintf(output_file, \"%f \", curves.lookup_table(i)[j]);\n      }\n      fprintf(output_file, \"\\n\");\n    }\n    fclose(output_file);\n  }\n\n  CameraCurveFn read_curves(std::string const& curves_file) {\n    FILE* input_file = fopen(curves_file.c_str(), \"r\");\n    if ( !input_file ) vw_throw( IOErr() << \"read_curves: failed to open file for reading.\" );\n\n    char c_line[10000];\n\n    std::vector<vw::Vector<double> > lookup_tables;\n    while ( !feof(input_file) ) {\n      if ( !fgets(c_line, 10000, input_file) )\n        break;\n      std::string line = c_line;\n      boost::trim_left(line);\n      boost::trim_right(line);\n\n      std::vector< std::string > split_vec; // #2: Search for individual values\n      boost::split( split_vec, line, boost::is_any_of(\" \") );\n      Vector<double> curve(split_vec.size());\n      for ( unsigned i = 0; i < split_vec.size(); ++i ) {\n        curve[i] = atof(split_vec[i].c_str());\n      }\n      lookup_tables.push_back(curve);\n    }\n    fclose(input_file);\n\n    return CameraCurveFn(lookup_tables);\n  }\n\n\n}} // namespace vw::hdr\n", "meta": {"hexsha": "b421f7eb01b617a20d02d1a04b5041bdf093407c", "size": 5508, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/vw/HDR/CameraCurve.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/HDR/CameraCurve.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/HDR/CameraCurve.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": 35.7662337662, "max_line_length": 96, "alphanum_fraction": 0.6377995643, "num_tokens": 1422, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7341195269001831, "lm_q2_score": 0.4571367168274948, "lm_q1q2_score": 0.33559299028610345}}
{"text": "// Copyright 2015 XLGAMES Inc.\n//\n// Distributed under the MIT License (See\n// accompanying file \"LICENSE\" or the website\n// http://www.opensource.org/licenses/mit-license.php)\n\n#include \"DualContour.h\"\n#include \"../Math/Matrix.h\"\n#include \"../Math/Transformations.h\"\n#include \"../Math/Geometry.h\"\n#include \"../Utility/PtrUtils.h\"\n\n#pragma warning(disable:4714)\n#pragma push_macro(\"new\")\n#undef new\n#include <Eigen/Dense>\n#pragma pop_macro(\"new\")\n\n#pragma warning(disable:4127)       // conditional expression is constant\n\nnamespace SceneEngine\n{\n    class EdgeIntersection\n    {\n    public:\n        Float3 _pt;\n        Float3 _normal;\n\n        EdgeIntersection(const Float3& intersectionPt, const Float3& intersectionNormal)\n            : _pt(intersectionPt), _normal(intersectionNormal) {}\n    };\n\n// #define STORE_INTERSECTIONS\n\n    class GridElement\n    {\n    public:\n            //  Store the grid element values that we will\n            //  need to combine together adjacent elements during\n            //  the simplification\n        Float3x3    _Ahat;      // (upper triangular -- maybe we don't have to store all of it?\n        Float3      _Bhat;\n        float       _r;\n        Float3      _massPointAccum;\n        unsigned    _massPointCount;\n\n        #if defined(STORE_INTERSECTIONS)\n            std::vector<EdgeIntersection> _intersectionPts;\n        #endif\n\n        GridElement() \n            : _Ahat(Zero<Float3x3>()), _Bhat(Zero<Float3>()), _r(0.f)\n            , _massPointAccum(Zero<Float3>()), _massPointCount(0) {}\n    };\n\n    static EdgeIntersection  TestEdge(  const Float3& e0, const Float3& e1, float d0, float d1, \n                                        const IVolumeDensityFunction& fn)\n    {\n            //  Test the edge between these points, and attempt to find the point where\n            //  the surface passes through. \n            //\n            //  The caller should have filtered out edges\n            //  that don't pass through the surface.\n        assert((d0 < 0.f) != (d1 < 0.f));\n\n            //      It might be a good idea to further improve the\n            //      result by taking a few steps to try to get to the\n            //      smallest density value. note that a very strange\n            //      density function might behave very non-linearly,\n            //      and so produce strange results when trying to\n            //      find the intersection (particularly if there are\n            //      really multiple intersections).\n\n        float x0 = 0.f, x1 = 1.f;\n        float x = 1.f, d = FLT_MAX;\n        unsigned maxImprovementSteps = 6;\n        for (unsigned c=0; ; ++c) {\n            float prevD = d; float prevX = x;\n            x = LinearInterpolate(x0, x1, -d0 / (d1 - d0));\n            d = fn.GetDensity(LinearInterpolate(e0, e1, x));\n\n                // along noisy edges we could end up getting a worse result after a step\n                //  In these cases, just give up at the last reasonable result\n            if (XlAbs(d) > XlAbs(prevD)) {\n                x = prevX;\n                break;\n            }\n\n            if (XlAbs(d) < 1e-6f) break;   // if we get close enough, just stop\n            if ((c+1)>=maxImprovementSteps) break;\n\n                //  We're going to attempt another improvement.\n                //  Divide the search area again, depending on where\n                //  the origin falls\n            if ((d < 0.f) != (d1 < 0.f)) {\n                x0 = x;\n                d0 = d;\n            } else {\n                x1 = x;\n                d1 = d;\n            }\n        }\n\n        assert(x>=0.f && x <= 1.f);\n        Float3 bestIntersection = LinearInterpolate(e0, e1, x);\n        Float3 normal = fn.GetNormal(bestIntersection);     // note -- we might need to tell the function the sampling density\n        return EdgeIntersection(bestIntersection, normal);\n    }\n\n    static void RotateToUpperTriangle(Eigen::Matrix<float,5,4>& A)\n    {\n        // Eigen::ColPivHouseholderQR<Eigen::Matrix<float,5,4>> qr(A);\n        // A = qr.matrixR().triangularView<Eigen::Upper>();\n        Eigen::HouseholderQR<Eigen::Matrix<float,5,4>> qr2(A);\n        A = qr2.matrixQR().triangularView<Eigen::Upper>();\n    }\n\n    static void MergeInEdgeIntersection(GridElement& gridElement, const EdgeIntersection& intersection, const Float3& gridElementCenter)\n    {\n            //  The edge intersections defines the a plane through the grid element.\n            //  The matrices in the grid element define a set of linear equations for\n            //  calculating the best point for the given planes. We want to merge\n            //  the plane from this new intersection into the equations already in\n            //  the grid element.\n            //  See the original dual contour paper for a description of this.\n            //  Basically, we're using QR decomposition to define an orthogonal\n            //  matrix and a upper triangular matrix. The \"Q\" orthogonal matrix\n            //  gets factored out when solving the linear equations. It leaves only\n            //  the \"R\" upper triangular matrix. \n            //  The original paper describes using \"Given's rotations\" to perform\n            //  the QR decomposition. But I'm using the Householder method, here\n            //  -- which is very similar, but requires fewer operations.\n            //  Also note that everything is translated to end up relative\n            //  to the grid center. This is just to guarantee small & simple numbers.\n\n        typedef Eigen::Matrix<float,5,4> Float5x4;\n        Float5x4 mat = Float5x4::Zero();\n\n            // fill in the existing values from the grid element\n        mat(0, 0) = gridElement._Ahat(0, 0);\n        mat(0, 1) = gridElement._Ahat(0, 1);\n        mat(0, 2) = gridElement._Ahat(0, 2);\n        mat(1, 0) = gridElement._Ahat(1, 0);\n        mat(1, 1) = gridElement._Ahat(1, 1);\n        mat(1, 2) = gridElement._Ahat(1, 2);\n        mat(2, 0) = gridElement._Ahat(2, 0);\n        mat(2, 1) = gridElement._Ahat(2, 1);\n        mat(2, 2) = gridElement._Ahat(2, 2);\n        mat(0, 3) = gridElement._Bhat[0];\n        mat(1, 3) = gridElement._Bhat[1];\n        mat(2, 3) = gridElement._Bhat[2];\n        mat(3, 3) = gridElement._r;\n\n        mat(4, 0) = intersection._normal[0];        // normal can be positive or negative direction; we'll still get the same plane equation\n        mat(4, 1) = intersection._normal[1];\n        mat(4, 2) = intersection._normal[2];\n        mat(4, 3) = Dot(intersection._pt - gridElementCenter, intersection._normal);\n        RotateToUpperTriangle(mat);\n\n            // extract new grid element values\n        gridElement._Ahat(0, 0) = mat(0, 0);\n        gridElement._Ahat(0, 1) = mat(0, 1);\n        gridElement._Ahat(0, 2) = mat(0, 2);\n        gridElement._Ahat(1, 0) = mat(1, 0);\n        gridElement._Ahat(1, 1) = mat(1, 1);\n        gridElement._Ahat(1, 2) = mat(1, 2);\n        gridElement._Ahat(2, 0) = mat(2, 0);\n        gridElement._Ahat(2, 1) = mat(2, 1);\n        gridElement._Ahat(2, 2) = mat(2, 2);\n        gridElement._Bhat[0] = mat(0, 3);\n        gridElement._Bhat[1] = mat(1, 3);\n        gridElement._Bhat[2] = mat(2, 3);\n        gridElement._r = mat(3, 3);\n\n        assert( Equivalent(mat(3, 0), 0.0f, 1e-6f)\n            &&  Equivalent(mat(3, 1), 0.0f, 1e-6f)\n            &&  Equivalent(mat(3, 2), 0.0f, 1e-6f));\n\n        gridElement._massPointAccum += intersection._pt - gridElementCenter;\n        ++gridElement._massPointCount;\n\n        #if defined(STORE_INTERSECTIONS)\n            gridElement._intersectionPts.push_back(\n                EdgeIntersection(intersection._pt - gridElementCenter, intersection._normal));\n        #endif\n    }\n\n    static Float3 CalculateCellPoint(const GridElement& gridElement, const Float3& gridElementSize)\n    {\n        Float3 massPoint = gridElement._massPointAccum / float(gridElement._massPointCount);\n        // assert(XlAbs(massPoint[0]) <= 0.5f*gridElementSize[0] \n        //     && XlAbs(massPoint[1]) <= 0.5f*gridElementSize[1] \n        //     && XlAbs(massPoint[2]) <= 0.5f*gridElementSize[2]);\n\n        #if defined(STORE_INTERSECTIONS)\n            typedef Eigen::Matrix<float,5,4> Float5x4;\n            Float5x4 mat = Float5x4::Zero();\n\n            for (unsigned c=0; c<unsigned(gridElement._intersectionPts.size()); ++c) {\n                mat(4, 0) = gridElement._intersectionPts[c]._normal[0];\n                mat(4, 1) = gridElement._intersectionPts[c]._normal[1];\n                mat(4, 2) = gridElement._intersectionPts[c]._normal[2];\n                mat(4, 3) = Dot(gridElement._intersectionPts[c]._pt, gridElement._intersectionPts[c]._normal);\n\n                assert(XlAbs(gridElement._intersectionPts[c]._pt[0]) <= 0.5f*gridElementSize[0]);\n                assert(XlAbs(gridElement._intersectionPts[c]._pt[1]) <= 0.5f*gridElementSize[1]);\n                assert(XlAbs(gridElement._intersectionPts[c]._pt[2]) <= 0.5f*gridElementSize[2]);\n                RotateToUpperTriangle(mat);\n            }\n\n            Eigen::Matrix<float,3,3> Ahat;\n            Eigen::Matrix<float,3,1> Bhat;\n            for (unsigned c=0; c<3; ++c) {\n                Ahat(c,0) = mat(c,0);\n                Ahat(c,1) = mat(c,1);\n                Ahat(c,2) = mat(c,2);\n                Bhat(c,0) = mat(c,3);\n            }\n\n            Eigen::Matrix<float,3,1> massPointVec;\n            massPointVec(0,0) = massPoint[0];\n            massPointVec(1,0) = massPoint[1];\n            massPointVec(2,0) = massPoint[2];\n\n            Eigen::MatrixXf x(3, 1);\n\n                //  The original dual contour multiplies through with the transpose of A. This might\n                //  reduce the work when calculating the SVD, but the Eigen library doesn't seem to\n                //  support this optimisation, however. So I'm not sure if we need to multiply\n                //  through with AHatTranspose here.\n            static bool useTranspose = true;\n            if (useTranspose) {\n                auto AhatTranspose = Ahat.transpose();\n                Eigen::JacobiSVD<Eigen::MatrixXf> svd(AhatTranspose * Ahat, Eigen::ComputeFullU | Eigen::ComputeFullV);\n                svd.solve(AhatTranspose * Bhat - AhatTranspose * Ahat * massPointVec).evalTo(x);\n            } else {\n                Eigen::JacobiSVD<Eigen::MatrixXf> svd(Ahat, Eigen::ComputeFullU | Eigen::ComputeFullV);\n                svd.solve(Bhat - Ahat * massPointVec).evalTo(x);\n            }\n\n            // assert(XlAbs(x(0,0)) < .5f * gridElementSize[0] \n            //     && XlAbs(x(1,0)) < .5f * gridElementSize[1]\n            //     && XlAbs(x(2,0)) < .5f * gridElementSize[2]);\n\n            auto result = Float3(x(0, 0) + massPoint[0], x(1, 0) + massPoint[1], x(2, 0) + massPoint[2]);\n            return result;\n\n        #else\n\n            Eigen::Matrix<float,3,1> massPointVec;\n            massPointVec(0,0) = massPoint[0];\n            massPointVec(1,0) = massPoint[1];\n            massPointVec(2,0) = massPoint[2];\n\n            Eigen::Matrix<float,3,1> x;\n\n            Eigen::Matrix<float,3,3> Ahat;\n            Eigen::Matrix<float,3,1> Bhat;\n            Ahat(0,0) = gridElement._Ahat(0,0);\n            Ahat(0,1) = gridElement._Ahat(0,1);\n            Ahat(0,2) = gridElement._Ahat(0,2);\n            Ahat(1,0) = gridElement._Ahat(1,0);\n            Ahat(1,1) = gridElement._Ahat(1,1);\n            Ahat(1,2) = gridElement._Ahat(1,2);\n            Ahat(2,0) = gridElement._Ahat(2,0);\n            Ahat(2,1) = gridElement._Ahat(2,1);\n            Ahat(2,2) = gridElement._Ahat(2,2);\n\n            Bhat(0, 0) = gridElement._Bhat[0];\n            Bhat(1, 0) = gridElement._Bhat[1];\n            Bhat(2, 0) = gridElement._Bhat[2];\n\n                //  The original dual contour multiplies through with the transpose of A. This might\n                //  reduce the work when calculating the SVD, but the Eigen library doesn't seem to\n                //  support this optimisation, however. So I'm not sure if we need to multiply\n                //  through with AHatTranspose here.\n            const bool useTranspose = true;\n            if (useTranspose) {\n                auto AhatTranspose = Ahat.transpose();\n                Eigen::JacobiSVD<Eigen::Matrix<float, 3, 3>> svd(AhatTranspose * Ahat, Eigen::ComputeFullU | Eigen::ComputeFullV);\n                svd.solve(AhatTranspose * Bhat - AhatTranspose * Ahat * massPointVec).evalTo(x);\n            } else {\n                    //  note that if we know the mass point when we're calculating Ahat, we can probably\n                    //  just take into account the mass point then. However, if we're using a marching\n                    //  cubes-like algorithm to move through the data field, and so visiting each cube\n                    //  element multiple times, we might not be able to calculate the mass point until \n                    //  after AHat has been fully built. But we can compensate during the solution, \n                    //  as so ---\n                Eigen::JacobiSVD<Eigen::Matrix<float, 3, 3>> svd(Ahat, Eigen::ComputeFullU | Eigen::ComputeFullV);\n                svd.solve(Bhat - Ahat * massPointVec).evalTo(x);\n            }\n\n            auto result = Float3(x(0, 0) + massPoint[0], x(1, 0) + massPoint[1], x(2, 0) + massPoint[2]);\n\n            static bool preventBadResults = true;\n            if (preventBadResults) {\n                Float3 halfSize = 0.5f * gridElementSize;\n                if (result[0] < -halfSize[0] || result[0] > halfSize[0] ||  \n                    result[1] < -halfSize[1] || result[1] > halfSize[1] ||\n                    result[2] < -halfSize[2] || result[2] > halfSize[2]) {\n                    return massPoint;       // got a poor result from the QEF test -- too much curvature in a small area.\n                }\n            }\n\n            return result;\n\n        #endif\n    }\n\n#if 0\n    static void CheckWindingOrder(DualContourMesh::Quad& q, const std::vector<DualContourMesh::Vertex>& vertices)\n    {\n            //  Check the winding order of the given quad, and correct if necessary\n            //  There are various ways we could attempt to find the correct winding order. \n            //  But they all have problems. \n            //\n            //  It's possible that that input quad could have a twist in it. We also have to\n            //  be careful about input quads that are near-degenerate.\n            //\n            //  We want to avoid more queries of the density field to generate more normals. \n            //  So let's use the normals we already have access to. We can take some kind of \n            //  weighted mean of the vertex normals and use this as an approximation of the \n            //  face normal, Then we can test the vertex winding order to see if it agrees \n            //  with the face normal we've picked.\n            //\n            //  How do we weight the normals? We could use the interior angle of the corner.\n\n            //  The vertices in our quads are arranged in a \"Z\" pattern... \n            //  We can't just +1 or -1 to get \"prev\" and \"next\". Use the following table:\n        unsigned prevVertices[] = { 2, 0, 3, 1 };       \n        unsigned nextVertices[] = { 1, 3, 0, 2 };\n\n        const bool useWeightedMean = false;\n        if (constant_expression<useWeightedMean>::result()) {\n\n            Float3 faceNormal(0.f, 0.f, 0.f);\n            for (unsigned c=0; c<4; ++c) {\n                unsigned prevVertex = q._verts[prevVertices[c]];\n                unsigned thisVertex = q._verts[c];\n                unsigned nextVertex = q._verts[nextVertices[c]];\n                float dot = Dot(\n                    vertices[prevVertex]._pt - vertices[thisVertex]._pt,\n                    vertices[nextVertex]._pt - vertices[thisVertex]._pt);\n                float angle = XlACos(dot);  // because it's a quad, angle must be less than 180. An angle of 180 just gives a straight line\n                assert(angle < gPI);\n                faceNormal += angle * vertices[q._verts[c]]._normal;\n            }\n            faceNormal = Normalize(faceNormal);\n\n                //  We can use the cross product to check if the winding is going\n                //  in the correct direction. The cross product gives us directional\n                //  information about the 2 input vectors. We can compare the result\n                //  of the cross product to the direction of the face normal to see\n                //  if the winding order is correct for this normal.\n            unsigned correctCount = 0;\n            for (unsigned c=0; c<4; ++c) {\n                unsigned prevVertex = q._verts[prevVertices[c]];\n                unsigned thisVertex = q._verts[c];\n                unsigned nextVertex = q._verts[nextVertices[c]];\n\n                auto crs = Cross(   \n                    vertices[prevVertex]._pt - vertices[thisVertex]._pt, \n                    vertices[nextVertex]._pt - vertices[thisVertex]._pt);\n                bool correct = Dot(faceNormal, crs) <= 0.f;\n                correctCount += unsigned(correct);\n            }\n\n            if (correctCount < 2) {\n                    //  Some tolerance if only one or two vertices are a problem.\n                    //  But, otherwise, we need to reverse the order. Quads verts are\n                    //  in a \"Z\" pattern... so just swap 1 & 2\n                std::swap(q._verts[1], q._verts[2]);\n            }\n\n        } else {\n\n            unsigned correctCount = 0;\n            for (unsigned c=0; c<4; ++c) {\n                unsigned prevVertex = q._verts[prevVertices[c]];\n                unsigned thisVertex = q._verts[c];\n                unsigned nextVertex = q._verts[nextVertices[c]];\n\n                auto testDirection = Cross(\n                    vertices[prevVertex]._pt - vertices[thisVertex]._pt, \n                    vertices[nextVertex]._pt - vertices[thisVertex]._pt);\n                for (unsigned v=0; v<4; ++v) {\n                    bool correct = Dot(vertices[q._verts[v]]._normal, testDirection) <= 0.f;\n                    correctCount += unsigned(correct);\n                }\n            }\n\n                // if we're correct less than half of the time, then flip\n            if (correctCount < 4*4/2) {\n                std::swap(q._verts[1], q._verts[2]);\n            }\n\n        }\n\n    }\n\n    static bool NeedsFlip(DualContourMesh& mesh, unsigned a, unsigned b, unsigned c, const IVolumeDensityFunction& fn)\n    {\n        auto plane = PlaneFit(mesh._vertices[a]._pt, mesh._vertices[b]._pt, mesh._vertices[c]._pt);\n        auto averagePoint = 0.25f * (mesh._vertices[a]._pt + mesh._vertices[b]._pt + mesh._vertices[c]._pt);\n\n        static float testOffset = 0.1f;\n        \n        float density0 = fn.GetDensity(averagePoint);\n        float density1 = fn.GetDensity(averagePoint + Truncate(plane) * testOffset);\n        return density0 > density1;\n    }\n\n    static void AddQuad(DualContourMesh& mesh, const DualContourMesh::Quad& quad, const IVolumeDensityFunction& fn)\n    {\n        // Our quad should be reasonbly close to coplanear. When we convert it into\n        // triangles, we want the winding order of both triangles to be the same...\n        // so let's do a winding order test on the quad, and apply the result to \n        // both triangles.\n        // Float3 pts[4] = \n        // {\n        //     mesh._vertices[quad._verts[0]]._pt,\n        //     mesh._vertices[quad._verts[1]]._pt,\n        //     mesh._vertices[quad._verts[2]]._pt,\n        //     mesh._vertices[quad._verts[3]]._pt\n        // };\n        // Float3 averagePoint = 0.25f * (pts[0] + pts[1] + pts[2] + pts[3]);\n        // Float4 plane = PlaneFit(pts, dimof(pts));\n        // \n        // // the average point should be almost (if not quite) on both triangles.\n        // static float testOffset = 0.1f;\n        // \n        // auto q = quad;\n        // float density0 = fn.GetDensity(averagePoint);\n        // float density1 = fn.GetDensity(averagePoint + Truncate(plane) * testOffset);\n        // if (density0 > density1)\n        //     std::swap(q._verts[1], q._verts[2]);\n        // \n        // mesh._quads.push_back(q);\n\n        bool flip0 = NeedsFlip(mesh, quad._verts[0], quad._verts[1], quad._verts[2], fn);\n        bool flip1 = NeedsFlip(mesh, quad._verts[2], quad._verts[1], quad._verts[3], fn);\n        // assert(flip0 == flip1);\n\n        auto q = quad;\n        if (flip0 || flip1)\n            std::swap(q._verts[1], q._verts[2]);\n        mesh._quads.push_back(q);\n    }\n\n#endif\n    \n    static void AddQuad(DualContourMesh& mesh, const DualContourMesh::Quad& quad, bool flipDirection)\n    {\n        auto q = quad;\n        if (flipDirection)\n            std::swap(q._verts[1], q._verts[2]);\n        mesh._quads.push_back(q);\n    }\n\n    DualContourMesh     DualContourMesh_Build(  unsigned samplingGridDimensions, \n                                                const IVolumeDensityFunction& fn)\n    {\n            //  Build a mesh of triangles from the given input function\n            //      (using dual contouring method)\n            //\n            //  First we'll build a grid containing information for each\n            //  voxel. Then we'll go through a calculate the QEF's at\n            //  each grid point -- that will give us enough information\n            //  to generate the triangles needed. Note that the algorithm\n            //  should naturally build quads most of the time. They'll need\n            //  to be split up into triangles.\n            //\n            //  Ideally, we would also do simplification before we calculate\n            //  the QEF's and generate the triangles. But currently, no\n            //  simplification.\n        auto boundary = fn.GetBoundary();\n        auto gridElements = std::make_unique<GridElement[]>(\n            samplingGridDimensions*samplingGridDimensions*samplingGridDimensions);\n\n            //  For each grid element, let's fill it in with the values from the\n            //  density function. Note that we could reduce the work here slightly\n            //  by finding a point within the grid that lies on the surface, and\n            //  then marching along the surface, into each new grid that takes us.\n            //\n            //  The current method will create many redundant tests of the volume\n            //  function -- because most grids are probably not on the surface of the \n            //  volume.\n            //\n            //  Let's find and test each edge. When we find a edge that crosses the \n            //  boundary, we can merge that into the QEF's for that adjacent grid\n            //  elements.\n            //\n            //  It's a good idea to calculate the density results at each corner first\n            //  This will help reduce the number of times we need to call the\n            //  GetDensity() function.\n\n        Float3x4 gridToSampleSpace = Zero<Float3x4>();\n        gridToSampleSpace(0,0) = (boundary.second[0] - boundary.first[0]) / float(samplingGridDimensions);\n        gridToSampleSpace(1,1) = (boundary.second[1] - boundary.first[1]) / float(samplingGridDimensions);\n        gridToSampleSpace(2,2) = (boundary.second[2] - boundary.first[2]) / float(samplingGridDimensions);\n        gridToSampleSpace(0,3) = boundary.first[0];\n        gridToSampleSpace(1,3) = boundary.first[1];\n        gridToSampleSpace(2,3) = boundary.first[2];\n        \n        auto densityResults = std::make_unique<float[]>(\n            (samplingGridDimensions+1)*(samplingGridDimensions+1)*(samplingGridDimensions+1));\n        for (int z=0; z<int(samplingGridDimensions+1); ++z)\n            for (int y=0; y<int(samplingGridDimensions+1); ++y)\n                for (int x=0; x<int(samplingGridDimensions+1); ++x) {\n                    Float3 p0 = TransformPoint(gridToSampleSpace, Float3(float(x), float(y), float(z)));\n                    densityResults[(z * (samplingGridDimensions+1) + y) * (samplingGridDimensions+1) + x] = fn.GetDensity(p0);\n                }\n\n            // note --  The order of the cell offsets here is important, because it \n            //          determines the order of the vertices in the quad.\n        Int3 cellOffsetsX[] = { Int3(0, 0, 0), Int3(0, -1, 0), Int3(0, 0, -1), Int3(0, -1, -1) };\n        Int3 cellOffsetsY[] = { Int3(0, 0, 0), Int3(0, 0, -1), Int3(-1, 0, 0), Int3(-1, 0, -1) };\n        Int3 cellOffsetsZ[] = { Int3(0, 0, 0), Int3(-1, 0, 0), Int3(0, -1, 0), Int3(-1, -1, 0) };\n\n        for (int z=0; z<int(samplingGridDimensions); ++z) {\n            for (int y=0; y<int(samplingGridDimensions); ++y) {\n                for (int x=0; x<int(samplingGridDimensions); ++x) {\n\n                        //  For each grid element, we're going to test 3 edges.\n                        //  we'll add the effect of those edges to adjacent grids\n                        //  as well. This means each edges gets tested once.\n                        //  However, some edges on the extreme positive boundary\n                        //  of the sampling area will never be tested. We'll assume \n                        //  that the function doesn't go through these boundary edges.\n\n                    Float3 p0 = TransformPoint(gridToSampleSpace, Float3(float(x), float(y), float(z)));\n                    Float3 p1 = TransformPoint(gridToSampleSpace, Float3(float(x+1), float(y), float(z)));\n                    Float3 p2 = TransformPoint(gridToSampleSpace, Float3(float(x), float(y+1), float(z)));\n                    Float3 p3 = TransformPoint(gridToSampleSpace, Float3(float(x), float(y), float(z+1)));\n\n                    float d0 = densityResults[(z * (samplingGridDimensions+1) + y) * (samplingGridDimensions+1) + x];\n                    float d1 = densityResults[(z * (samplingGridDimensions+1) + y) * (samplingGridDimensions+1) + x + 1];\n                    float d2 = densityResults[(z * (samplingGridDimensions+1) + y + 1) * (samplingGridDimensions+1) + x];\n                    float d3 = densityResults[((z + 1) * (samplingGridDimensions+1) + y) * (samplingGridDimensions+1) + x];\n\n                        //  Look for edges that contain intersections with the surface, and then merge \n                        //  those edge into all of the grid cells that contain them.\n                        //  Note that TestEdge() will do extra calls to GetDensity to improve the \n                        //  intersection point.\n                    \n                    if ((d0 < 0.f) != (d1 < 0.f)) {\n                        auto intersection = TestEdge(p0, p1, d0, d1, fn);\n                        for (unsigned c=0; c<dimof(cellOffsetsX); ++c) {\n                            Int3 g(x + cellOffsetsX[c][0], y + cellOffsetsX[c][1], z + cellOffsetsX[c][2]);\n                            if (g[0] >= 0 && g[1] >= 0 && g[2] >= 0) {\n                                const auto cellCenter = Float3(\n                                    LinearInterpolate(boundary.first[0], boundary.second[0], (float(g[0]) + .5f) / float(samplingGridDimensions)),\n                                    LinearInterpolate(boundary.first[1], boundary.second[1], (float(g[1]) + .5f) / float(samplingGridDimensions)),\n                                    LinearInterpolate(boundary.first[2], boundary.second[2], (float(g[2]) + .5f) / float(samplingGridDimensions)));\n\n                                MergeInEdgeIntersection(\n                                    gridElements[(g[2] * samplingGridDimensions + g[1]) * samplingGridDimensions + g[0]],\n                                    intersection, cellCenter);\n                            }\n                        }\n                    }\n\n                    if ((d0 < 0.f) != (d2 < 0.f)) {\n                        auto intersection = TestEdge(p0, p2, d0, d2, fn);\n                        for (unsigned c=0; c<dimof(cellOffsetsY); ++c) {\n                            Int3 g(x + cellOffsetsY[c][0], y + cellOffsetsY[c][1], z + cellOffsetsY[c][2]);\n                            if (g[0] >= 0 && g[1] >= 0 && g[2] >= 0) {\n                                const auto cellCenter = Float3(\n                                    LinearInterpolate(boundary.first[0], boundary.second[0], (float(g[0]) + .5f) / float(samplingGridDimensions)),\n                                    LinearInterpolate(boundary.first[1], boundary.second[1], (float(g[1]) + .5f) / float(samplingGridDimensions)),\n                                    LinearInterpolate(boundary.first[2], boundary.second[2], (float(g[2]) + .5f) / float(samplingGridDimensions)));\n\n                                MergeInEdgeIntersection(\n                                    gridElements[(g[2] * samplingGridDimensions + g[1]) * samplingGridDimensions + g[0]],\n                                    intersection, cellCenter);\n                            }\n                        }\n                    }\n\n                    if ((d0 < 0.f) != (d3 < 0.f)) {\n                        auto intersection = TestEdge(p0, p3, d0, d3, fn);\n                        for (unsigned c=0; c<dimof(cellOffsetsZ); ++c) {\n                            Int3 g(x + cellOffsetsZ[c][0], y + cellOffsetsZ[c][1], z + cellOffsetsZ[c][2]);\n                            if (g[0] >= 0 && g[1] >= 0 && g[2] >= 0) {\n                                const auto cellCenter = Float3(\n                                    LinearInterpolate(boundary.first[0], boundary.second[0], (float(g[0]) + .5f) / float(samplingGridDimensions)),\n                                    LinearInterpolate(boundary.first[1], boundary.second[1], (float(g[1]) + .5f) / float(samplingGridDimensions)),\n                                    LinearInterpolate(boundary.first[2], boundary.second[2], (float(g[2]) + .5f) / float(samplingGridDimensions)));\n\n                                MergeInEdgeIntersection(\n                                    gridElements[(g[2] * samplingGridDimensions + g[1]) * samplingGridDimensions + g[0]],\n                                    intersection, cellCenter);\n                            }\n                        }\n                    }\n\n                }\n            }\n        }\n\n            //  Now, we've calculated the error functions for all of the grid elements.\n            //  For each grid element, we can calculate the appropriate point for that\n            //  element. Let's make sure we do this only one per grid element (because\n            //  typically each vertex will be used in multiple quads.\n\n        const auto cellSize = Float3(\n            (boundary.second[0] - boundary.first[0]) / float(samplingGridDimensions),\n            (boundary.second[1] - boundary.first[1]) / float(samplingGridDimensions),\n            (boundary.second[2] - boundary.first[2]) / float(samplingGridDimensions));\n\n        std::vector<DualContourMesh::Vertex> vertices;\n        auto vertexIndices = std::make_unique<unsigned[]>(\n            samplingGridDimensions*samplingGridDimensions*samplingGridDimensions);\n        for (int z=0; z<int(samplingGridDimensions); ++z) {\n            for (int y=0; y<int(samplingGridDimensions); ++y) {\n                for (int x=0; x<int(samplingGridDimensions); ++x) {\n                    auto index = (z * samplingGridDimensions + y) * samplingGridDimensions + x;\n                    const auto& g = gridElements[index];\n                    if (!g._massPointCount) {\n                        vertexIndices[index] = 0xffffffff;\n                        continue;\n                    }\n\n                    const auto cellCenter = Float3(\n                        LinearInterpolate(boundary.first[0], boundary.second[0], (float(x) + .5f) / float(samplingGridDimensions)),\n                        LinearInterpolate(boundary.first[1], boundary.second[1], (float(y) + .5f) / float(samplingGridDimensions)),\n                        LinearInterpolate(boundary.first[2], boundary.second[2], (float(z) + .5f) / float(samplingGridDimensions)));\n                    auto pt = CalculateCellPoint(g, cellSize) + cellCenter;\n\n                        //  We need the normal at this location, also.\n                        //  We've lost the locations of the edge intersections -- so we can't\n                        //  just add together the normals from them. However. We can \n                        //  query the density field again to get the normal at this location.\n                    auto normal = fn.GetNormal(pt);\n                    vertices.push_back(DualContourMesh::Vertex(pt, normal));\n                    vertexIndices[index] = unsigned(vertices.size()-1);\n                }\n            }\n        }\n\n            //  We just need to calculate the triangles. \n            //  For each edge with an intersection, we want to create a quad.\n            //  we start at one here, because the edge cells have nothing to join\n            //  on to.\n\n        DualContourMesh mesh;\n        mesh._vertices = std::move(vertices);\n\n        for (int z=1; z<int(samplingGridDimensions); ++z) {\n            for (int y=1; y<int(samplingGridDimensions); ++y) {\n                for (int x=1; x<int(samplingGridDimensions); ++x) {\n\n                    float d0 = densityResults[(z * (samplingGridDimensions+1) + y) * (samplingGridDimensions+1) + x];\n                    float d1 = densityResults[(z * (samplingGridDimensions+1) + y) * (samplingGridDimensions+1) + x + 1];\n                    float d2 = densityResults[(z * (samplingGridDimensions+1) + y + 1) * (samplingGridDimensions+1) + x];\n                    float d3 = densityResults[((z + 1) * (samplingGridDimensions+1) + y) * (samplingGridDimensions+1) + x];\n\n                        //  If the edge has a intersection point. We want to create a \n                        //  quad by joining together all of the cells that use this edge.\n                    if ((d0 < 0.f) != (d1 < 0.f)) {\n                        DualContourMesh::Quad q;\n                        for (unsigned c=0; c<4; ++c) {\n                            Int3 g(x + cellOffsetsX[c][0], y + cellOffsetsX[c][1], z + cellOffsetsX[c][2]);\n                            auto index = (g[2] * samplingGridDimensions + g[1]) * samplingGridDimensions + g[0];\n                            q._verts[c] = vertexIndices[index];\n                            assert(q._verts[c] < mesh._vertices.size());\n                        }\n                        AddQuad(mesh, q, d0 < 0.f);\n                    }\n\n                    if ((d0 < 0.f) != (d2 < 0.f)) {\n                        DualContourMesh::Quad q;\n                        for (unsigned c=0; c<4; ++c) {\n                            Int3 g(x + cellOffsetsY[c][0], y + cellOffsetsY[c][1], z + cellOffsetsY[c][2]);\n                            auto index = (g[2] * samplingGridDimensions + g[1]) * samplingGridDimensions + g[0];\n                            q._verts[c] = vertexIndices[index];\n                            assert(q._verts[c] < mesh._vertices.size());\n                        }\n                        AddQuad(mesh, q, d0 < 0.f);\n                    }\n\n                    if ((d0 < 0.f) != (d3 < 0.f)) {\n                        DualContourMesh::Quad q;\n                        for (unsigned c=0; c<4; ++c) {\n                            Int3 g(x + cellOffsetsZ[c][0], y + cellOffsetsZ[c][1], z + cellOffsetsZ[c][2]);\n                            auto index = (g[2] * samplingGridDimensions + g[1]) * samplingGridDimensions + g[0];\n                            q._verts[c] = vertexIndices[index];\n                            assert(q._verts[c] < mesh._vertices.size());\n                        }\n                        AddQuad(mesh, q, d0 < 0.f);\n                    }\n\n                }\n            }\n        }\n\n        return mesh;\n    }\n\n\n\n    DualContourMesh::DualContourMesh() {}\n    DualContourMesh::DualContourMesh(DualContourMesh&& moveFrom)\n    : _vertices(std::move(moveFrom._vertices))\n    , _quads(std::move(moveFrom._quads))\n    {}\n    DualContourMesh& DualContourMesh::operator=(DualContourMesh&& moveFrom)\n    {\n        _vertices = std::move(moveFrom._vertices);\n        _quads = std::move(moveFrom._quads);\n        return *this;\n    }\n    DualContourMesh::~DualContourMesh() {}\n\n}\n\n", "meta": {"hexsha": "8b4a8d87e3bce66937d1caeb66c5f438a20c84dd", "size": 35914, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "SceneEngine/DualContour.cpp", "max_stars_repo_name": "alexgithubber/XLE-Another-Fork", "max_stars_repo_head_hexsha": "cdd8682367d9e9fdbdda9f79d72bb5b1499cec46", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2016-06-01T10:41:12.000Z", "max_stars_repo_stars_event_max_datetime": "2016-06-01T10:41:12.000Z", "max_issues_repo_path": "SceneEngine/DualContour.cpp", "max_issues_repo_name": "yorung/XLE", "max_issues_repo_head_hexsha": "083ce4c9d3fe32002ff5168e571cada2715bece4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "SceneEngine/DualContour.cpp", "max_forks_repo_name": "yorung/XLE", "max_forks_repo_head_hexsha": "083ce4c9d3fe32002ff5168e571cada2715bece4", "max_forks_repo_licenses": ["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.0892608089, "max_line_length": 147, "alphanum_fraction": 0.5419613521, "num_tokens": 8986, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7341195269001831, "lm_q2_score": 0.45713671682749474, "lm_q1q2_score": 0.3355929902861034}}
{"text": "#pragma once\n\n#include <bitset>\n#include <functional>\n#include <numeric>\n#include <stdexcept>\n#include <vector>\n\n#include <dtl/dtl.hpp>\n#include <dtl/bits.hpp>\n#include <dtl/math.hpp>\n#include <dtl/simd.hpp>\n#include <dtl/filter/blocked_bloomfilter/vector_helper.hpp>\n\n#include \"immintrin.h\"\n\n#include <boost/integer/static_min_max.hpp>\n\n\nnamespace dtl {\n\nnamespace {\n\n//===----------------------------------------------------------------------===//\n// Recursive template to work with multi-word sectors.\n//\n// Specialization for the case where sector count < word_cnt ('sltw'),\n// which results in a random access pattern within the block (and sector).\n// I.e., for every bit to set, the corresponding word needs to be determined\n// and loaded.\n//\n// Same as in the 'sgew' case, we process the block sector by sector,\n// however, a sector consists of more than one word.\n//===----------------------------------------------------------------------===//\ntemplate<\n    typename key_t,               // the key type\n    typename word_t,              // the word type\n    u32 word_cnt,                 // the number of words per sector\n    u32 k,                        // the number of bits to set/test\n    template<typename Ty, u32 i> class hasher,      // the hash function family to use\n    typename hash_value_t,        // the hash value type to use\n\n    u32 hash_fn_idx,              // current hash function index (used for recursion)\n    u32 remaining_hash_bit_cnt,   // the number of remaining hash bits (used for recursion)\n    u32 remaining_k_cnt           // the remaining number of bits to set in the sector (used for recursion)\n>\nstruct multiword_sector {\n\n  //===----------------------------------------------------------------------===//\n  // Static part\n  //===----------------------------------------------------------------------===//\n\n  static constexpr u32 word_cnt_log2 = dtl::ct::log_2<word_cnt>::value;\n  static constexpr u32 word_cnt_log2_mask = (1u << word_cnt_log2) - 1;\n  static_assert(dtl::is_power_of_two(word_cnt), \"Parameter 'word_cnt' must be a power of two.\");\n  static constexpr u32 word_bitlength = sizeof(word_t) * 8;\n  static constexpr u32 word_bitlength_log2 = dtl::ct::log_2<word_bitlength>::value;\n  static constexpr u32 word_bitlength_log2_mask = (1u << word_bitlength_log2) - 1;\n\n\n  static constexpr u32 hash_value_bitlength = sizeof(hash_value_t) * 8;\n\n  static constexpr u32 k_cnt_per_sector = k;\n\n  static constexpr u32 current_k_idx() { return k - remaining_k_cnt; }\n\n  static constexpr u32 hash_bit_cnt_per_k = word_cnt_log2 + word_bitlength_log2;\n\n  static constexpr u1 rehash = remaining_hash_bit_cnt < hash_bit_cnt_per_k;\n  static constexpr u32 remaining_hash_bit_cnt_after_rehash = rehash ? hash_value_bitlength : remaining_hash_bit_cnt;\n  //===----------------------------------------------------------------------===//\n\n\n  //===----------------------------------------------------------------------===//\n  // Insert\n  //===----------------------------------------------------------------------===//\n  __forceinline__\n  static void\n  insert(word_t* __restrict sector_ptr, const key_t key) noexcept {\n\n    hash_value_t hash_val = 0;\n\n    // Call the recursive function\n    static constexpr u32 remaining_hash_bits = 0;\n    multiword_sector<key_t, word_t, word_cnt, k,\n                     hasher, hash_value_t, hash_fn_idx, remaining_hash_bits,\n                     remaining_k_cnt>\n                     ::insert_atomic(sector_ptr, key, hash_val);\n//                     ::insert(sector_ptr, key, hash_val);\n  }\n  //===----------------------------------------------------------------------===//\n\n\n  //===----------------------------------------------------------------------===//\n  // Insert (Recursive)\n  //===----------------------------------------------------------------------===//\n  __forceinline__\n  static void\n  insert(word_t* __restrict sector_ptr, const key_t key, hash_value_t& hash_val) noexcept {\n\n    hash_val = rehash ? hasher<key_t, hash_fn_idx>::hash(key) : hash_val;\n\n    // Determine the word of interest\n    constexpr u32 word_idx_shift = remaining_hash_bit_cnt_after_rehash - word_cnt_log2;\n    $u32 word_idx = ((hash_val >> word_idx_shift) & word_cnt_log2_mask);\n\n    // Load the word of interest\n    word_t word = sector_ptr[word_idx];\n\n    // Set a bit in the given word\n    constexpr u32 bit_idx_shift = remaining_hash_bit_cnt_after_rehash - word_cnt_log2 - word_bitlength_log2;\n    $u32 bit_idx = ((hash_val >> bit_idx_shift) & word_bitlength_log2_mask);\n    word |= word_t(1) << bit_idx;\n\n    // Update the bit vector\n    sector_ptr[word_idx] = word;\n\n    // Process remaining k's recursively, if any\n    multiword_sector<key_t, word_t, word_cnt, k,\n                     hasher, hash_value_t,\n                     rehash ? hash_fn_idx + 1 : hash_fn_idx,\n                     remaining_hash_bit_cnt_after_rehash >= hash_bit_cnt_per_k ? remaining_hash_bit_cnt_after_rehash - hash_bit_cnt_per_k : 0,\n                     remaining_k_cnt - 1>\n      ::insert(sector_ptr, key, hash_val);\n  }\n  //===----------------------------------------------------------------------===//\n\n\n  //===----------------------------------------------------------------------===//\n  // Insert Atomic (Recursive)\n  //===----------------------------------------------------------------------===//\n  __forceinline__\n  static void\n  insert_atomic(word_t* __restrict sector_ptr, const key_t key, hash_value_t& hash_val) noexcept {\n\n    hash_val = rehash ? hasher<key_t, hash_fn_idx>::hash(key) : hash_val;\n\n    // Determine the word of interest\n    constexpr u32 word_idx_shift = remaining_hash_bit_cnt_after_rehash - word_cnt_log2;\n    u32 word_idx = ((hash_val >> word_idx_shift) & word_cnt_log2_mask);\n\n    // Set a bit in the given word\n    constexpr u32 bit_idx_shift = remaining_hash_bit_cnt_after_rehash - word_cnt_log2 - word_bitlength_log2;\n    u32 bit_idx = ((hash_val >> bit_idx_shift) & word_bitlength_log2_mask);\n    const word_t which_bit = word_t(1) << bit_idx;\n\n    word_t* word_ptr = &sector_ptr[word_idx];\n    std::atomic<word_t>* atomic_word_ptr = reinterpret_cast<std::atomic<word_t>*>(word_ptr);\n    $u1 success = false;\n    do {\n      // Load the word of interest\n      word_t word = atomic_word_ptr->load();\n      // Update the bit vector\n      word_t updated_word = word | which_bit;\n      success = atomic_word_ptr->compare_exchange_weak(word, updated_word);\n    } while (!success);\n\n    // Process remaining k's recursively, if any\n    multiword_sector<key_t, word_t, word_cnt, k,\n                     hasher, hash_value_t,\n                     rehash ? hash_fn_idx + 1 : hash_fn_idx,\n                     remaining_hash_bit_cnt_after_rehash >= hash_bit_cnt_per_k ? remaining_hash_bit_cnt_after_rehash - hash_bit_cnt_per_k : 0,\n                     remaining_k_cnt - 1>\n      ::insert_atomic(sector_ptr, key, hash_val);\n  }\n  //===----------------------------------------------------------------------===//\n\n\n  //===----------------------------------------------------------------------===//\n  // Contains\n  //===----------------------------------------------------------------------===//\n  __forceinline__ __unroll_loops__ __host__ __device__\n  static u1\n  contains(const word_t* __restrict sector_ptr, const key_t key) noexcept {\n\n    hash_value_t hash_val = 0;\n\n    // Call the recursive function\n    static constexpr u32 remaining_hash_bits = 0;\n    return multiword_sector<key_t, word_t, word_cnt, k,\n                            hasher, hash_value_t,\n                            hash_fn_idx,\n                            remaining_hash_bits,\n                            remaining_k_cnt>\n      ::contains(sector_ptr, key, hash_val, true);\n  }\n  //===----------------------------------------------------------------------===//\n\n\n  //===----------------------------------------------------------------------===//\n  // Contains (Recursive)\n  //===----------------------------------------------------------------------===//\n  __forceinline__ __unroll_loops__ __host__ __device__\n  static u1\n  contains(const word_t* __restrict sector_ptr, const key_t key, hash_value_t& hash_val, u1 is_contained_in_sector) noexcept {\n\n    hash_val = rehash ? hasher<key_t, hash_fn_idx>::hash(key) : hash_val;\n\n    // Determine the word of interest\n    constexpr u32 word_idx_shift = remaining_hash_bit_cnt_after_rehash - word_cnt_log2;\n    $u32 word_idx = ((hash_val >> word_idx_shift) & word_cnt_log2_mask);\n\n    // Load the word of interest\n    word_t word = sector_ptr[word_idx];\n\n    // Test a bit in the given word\n    constexpr u32 bit_idx_shift = remaining_hash_bit_cnt_after_rehash - word_cnt_log2 - word_bitlength_log2;\n    $u32 bit_idx = ((hash_val >> bit_idx_shift) & word_bitlength_log2_mask);\n    u1 found_in_word = word & (word_t(1) << bit_idx);\n\n    // Process remaining k's recursively, if any\n    return multiword_sector<key_t, word_t, word_cnt, k,\n                            hasher, hash_value_t,\n                            rehash ? hash_fn_idx + 1 : hash_fn_idx,\n                            remaining_hash_bit_cnt_after_rehash >= hash_bit_cnt_per_k ? remaining_hash_bit_cnt_after_rehash - hash_bit_cnt_per_k : 0,\n                            remaining_k_cnt - 1>\n                            ::contains(sector_ptr, key, hash_val, found_in_word & is_contained_in_sector);\n  }\n  //===----------------------------------------------------------------------===//\n\n\n  //===----------------------------------------------------------------------===//\n  // Contains (SIMD)\n  //===----------------------------------------------------------------------===//\n  template<u64 n>\n  __forceinline__ __unroll_loops__\n  static auto\n  contains(const vec<key_t,n>& keys,\n           const word_t* __restrict bitvector_base_address,\n           const vec<key_t,n>& sector_start_word_idxs) noexcept {\n\n    vec<hash_value_t, n> hash_vals(0);\n    auto is_contained_in_sector_mask = vec<word_t,n>::mask::make_all_mask();\n\n    // Call recursive function\n    static constexpr u32 remaining_hash_bits = 0;\n    return multiword_sector<key_t, word_t, word_cnt, k,\n                            hasher, hash_value_t,\n                            hash_fn_idx,\n                            remaining_hash_bits,\n                            remaining_k_cnt>\n      ::contains(keys, hash_vals, bitvector_base_address, sector_start_word_idxs, is_contained_in_sector_mask);\n  }\n\n\n  //===----------------------------------------------------------------------===//\n  // Contains (SIMD, Recursive)\n  //===----------------------------------------------------------------------===//\n  template<u64 n>\n  __forceinline__ __unroll_loops__\n  static auto\n  contains(const vec<key_t,n>& keys,\n           vec<hash_value_t,n>& hash_vals,\n           const word_t* __restrict bitvector_base_address,\n           const vec<hash_value_t,n>& sector_start_word_idxs,\n           const typename vec<word_t,n>::mask is_contained_in_sector_mask) noexcept {\n\n    // Typedef the vector types\n    using key_vt = vec<key_t, n>;\n    using word_vt = vec<word_t, n>;\n\n    hash_vals = rehash ? hasher<key_vt, hash_fn_idx>::hash(keys) : hash_vals;\n\n    // Determine the word of interest\n    constexpr u32 word_idx_shift = remaining_hash_bit_cnt_after_rehash - word_cnt_log2;\n    const auto in_sector_word_idxs = (hash_vals >> word_idx_shift) & static_cast<hash_value_t>(word_cnt_log2_mask);\n    const auto word_idxs = sector_start_word_idxs + in_sector_word_idxs;\n\n    // Gather the words of interest\n    const word_vt words = internal::vector_gather<word_t, hash_value_t, n>::gather(bitvector_base_address, word_idxs);\n\n    // Test a bit in the given word\n    constexpr u32 bit_idx_shift = remaining_hash_bit_cnt_after_rehash - word_cnt_log2 - word_bitlength_log2;\n    const auto bit_idx = (hash_vals >> bit_idx_shift) & static_cast<hash_value_t>(word_bitlength_log2_mask);\n    const word_vt bits_to_test = word_vt(1) << internal::vector_convert<hash_value_t, word_t, n>::convert(bit_idx);\n    const auto found_in_word_mask = (words & bits_to_test) == bits_to_test;\n\n    // Process remaining k's recursively, if any\n    return multiword_sector<key_t, word_t, word_cnt, k,\n                            hasher, hash_value_t,\n                            rehash ? hash_fn_idx + 1 : hash_fn_idx,\n                            remaining_hash_bit_cnt_after_rehash >= hash_bit_cnt_per_k ? remaining_hash_bit_cnt_after_rehash - hash_bit_cnt_per_k : 0,\n                            remaining_k_cnt - 1>\n      ::contains(keys, hash_vals, bitvector_base_address, sector_start_word_idxs, found_in_word_mask & is_contained_in_sector_mask);\n\n  }\n  //===----------------------------------------------------------------------===//\n\n\n  //===----------------------------------------------------------------------===//\n  // The number of required hash functions.\n  //===----------------------------------------------------------------------===//\n  static constexpr u32 hash_fn_idx_end =\n      multiword_sector<key_t, word_t, word_cnt, k,\n                       hasher, hash_value_t,\n                       (rehash ? hash_fn_idx + 1 : hash_fn_idx), // increment the hash function index\n                       remaining_hash_bit_cnt_after_rehash >= hash_bit_cnt_per_k\n                         ? remaining_hash_bit_cnt_after_rehash - hash_bit_cnt_per_k\n                         : 0, // the number of remaining hash bits\n                       remaining_k_cnt - 1> // decrement the remaining k counter\n      ::hash_fn_idx_end;\n  //===----------------------------------------------------------------------===//\n\n\n  //===----------------------------------------------------------------------===//\n  // The number of required hash bits.\n  //===----------------------------------------------------------------------===//\n  static constexpr u32 remaining_hash_bits =\n      multiword_sector<key_t, word_t, word_cnt, k,\n                 hasher, hash_value_t,\n                 (rehash ? hash_fn_idx + 1 : hash_fn_idx), // increment the hash function index\n                 remaining_hash_bit_cnt_after_rehash >= hash_bit_cnt_per_k\n                   ? remaining_hash_bit_cnt_after_rehash - hash_bit_cnt_per_k\n                   : 0, // the number of remaining hash bits\n                 remaining_k_cnt - 1> // decrement the remaining k counter\n      ::remaining_hash_bits;\n  //===----------------------------------------------------------------------===//\n\n};\n\n\ntemplate<\n    typename key_t,               // the key type\n    typename word_t,              // the word type\n    u32 word_cnt,                 // the number of words per sector\n    u32 k,                        // the number of bits to set/test\n    template<typename Ty, u32 i> class hasher,      // the hash function family to use\n    typename hash_value_t,        // the hash value type to use\n\n    u32 hash_fn_idx,              // current hash function index (used for recursion)\n    u32 remaining_hash_bit_cnt    // the number of remaining hash bits (used for recursion)\n>\nstruct multiword_sector<key_t, word_t, word_cnt, k, hasher, hash_value_t, hash_fn_idx, remaining_hash_bit_cnt, 0 /* no more k's */> {\n\n  //===----------------------------------------------------------------------===//\n  // Insert\n  //===----------------------------------------------------------------------===//\n  __forceinline__\n  static void\n  insert(word_t* __restrict sector_ptr, const key_t key, hash_value_t& hash_val) noexcept {\n    // End of recursion.\n  }\n  __forceinline__\n  static void\n  insert_atomic(word_t* __restrict sector_ptr, const key_t key, hash_value_t& hash_val) noexcept {\n    // End of recursion.\n  }\n  //===----------------------------------------------------------------------===//\n\n\n  //===----------------------------------------------------------------------===//\n  // Contains\n  //===----------------------------------------------------------------------===//\n  __forceinline__ __host__ __device__\n  static u1\n  contains(const word_t* __restrict sector_ptr, const key_t key, hash_value_t& hash_val, u1 is_contained_in_sector) noexcept {\n    // End of recursion.\n    return is_contained_in_sector;\n  }\n  //===----------------------------------------------------------------------===//\n\n\n  //===----------------------------------------------------------------------===//\n  // Contains (SIMD)\n  //===----------------------------------------------------------------------===//\n  template<u64 n>\n  __forceinline__ __unroll_loops__\n  static auto\n  contains(const vec<key_t,n>& keys,\n           vec<hash_value_t,n>& hash_vals,\n           const word_t* __restrict bitvector_base_address,\n           const vec<hash_value_t,n>& sector_start_word_idxs,\n           const typename vec<word_t,n>::mask is_contained_in_sector_mask) noexcept {\n    // End of recursion.\n    return is_contained_in_sector_mask;\n  }\n  //===----------------------------------------------------------------------===//\n\n\n  static constexpr u32 hash_fn_idx_end = hash_fn_idx;\n\n  static constexpr u32 remaining_hash_bits = remaining_hash_bit_cnt;\n\n};\n\n\n} // anonymous namespace\n\n//===----------------------------------------------------------------------===//\n// Recursive template to work with multiple multi-word sectors.\n//\n// Specialization for the case where sector count < word_cnt ('sltw'),\n// which results in a random access pattern within the block (and sector).\n// I.e., for every bit to set/test, the corresponding word needs to be determined\n// and loaded.\n//\n// Same as in the 'sgew' case, we process the block sector by sector,\n// however, a sector consists of more than one word.\n//===----------------------------------------------------------------------===//\ntemplate<\n    typename _key_t,              // the key type\n    typename _word_t,             // the word type\n    u32 _word_cnt,                // the number of words per block\n    u32 _s,                       // the numbers of sectors (must be a power of two)\n    u32 _k,                       // the number of bits to set/test\n    template<typename Ty, u32 i> class hasher,      // the hash function family to use\n    typename hash_value_t,        // the hash value type to use\n\n    u32 hash_fn_idx,              // current hash function index (used for recursion)\n    u32 remaining_hash_bit_cnt,   // the number of remaining hash bits (used for recursion)\n    u32 remaining_sector_cnt,     // the remaining number of sector (used for recursion)\n\n    u1 early_out = false          // allows for branching out during lookups (before the next sector is tested)\n>\nstruct multisector_block {\n\n  //===----------------------------------------------------------------------===//\n  // Static part\n  //===----------------------------------------------------------------------===//\n  using key_t = _key_t;\n  using word_t = _word_t;\n\n  static constexpr u32 k = _k;\n  static constexpr u32 word_cnt = _word_cnt;\n  static constexpr u32 sector_cnt = _s;\n  static_assert(dtl::is_power_of_two(sector_cnt), \"Parameter 'sector_cnt' must be a power of two.\");\n  static constexpr u32 sector_cnt_log2 = dtl::ct::log_2<sector_cnt>::value;\n\n  static constexpr u32 current_sector_idx = sector_cnt - remaining_sector_cnt;\n\n  static_assert(dtl::is_power_of_two(word_cnt), \"Parameter 'word_cnt' must be a power of two.\");\n  static constexpr u32 word_cnt_per_sector = word_cnt / sector_cnt;\n  static constexpr u32 k_cnt_per_sector = k / sector_cnt;\n  static_assert(k % sector_cnt == 0, \"Parameter 'k' must be dividable by 's'.\");\n\n\n  //===----------------------------------------------------------------------===//\n  // Insert\n  //===----------------------------------------------------------------------===//\n  __forceinline__\n  static void\n  insert(word_t* __restrict block_ptr, const key_t key) noexcept {\n\n    hash_value_t hash_val = 0;\n\n    // Call the recursive function\n    static constexpr u32 remaining_hash_bits = 0;\n    multisector_block<key_t, word_t, word_cnt, sector_cnt, k,\n                      hasher, hash_value_t, hash_fn_idx, remaining_hash_bits,\n                      remaining_sector_cnt, early_out>\n      ::insert(block_ptr, key, hash_val);\n  }\n  //===----------------------------------------------------------------------===//\n\n\n  //===----------------------------------------------------------------------===//\n  // Insert (Recursive)\n  //===----------------------------------------------------------------------===//\n  __forceinline__\n  static void\n  insert(word_t* __restrict block_ptr, const key_t key, hash_value_t& hash_val) noexcept {\n\n    // Sector pointer\n    word_t* sector_ptr = block_ptr + (word_cnt_per_sector * current_sector_idx);\n\n    // Process remaining k's recursively, if any\n    using sector_t =\n      multiword_sector<key_t, word_t, word_cnt_per_sector, k_cnt_per_sector,\n                       hasher, hash_value_t, hash_fn_idx, remaining_hash_bit_cnt,\n                       k_cnt_per_sector>;\n    sector_t::insert_atomic(sector_ptr, key, hash_val);\n//    sector_t::insert(sector_ptr, key, hash_val);\n\n    multisector_block<key_t, word_t, word_cnt, sector_cnt, k,\n                      hasher, hash_value_t, sector_t::hash_fn_idx_end, sector_t::remaining_hash_bits,\n                      remaining_sector_cnt - 1, early_out>\n      ::insert(block_ptr, key, hash_val);\n  }\n  //===----------------------------------------------------------------------===//\n\n\n  //===----------------------------------------------------------------------===//\n  // Contains\n  //===----------------------------------------------------------------------===//\n  __forceinline__ __unroll_loops__ __host__ __device__\n  static u1\n  contains(const word_t* __restrict block_ptr, const key_t key) noexcept {\n\n    hash_value_t hash_val = 0;\n\n    // Call the recursive function\n    static constexpr u32 remaining_hash_bits = 0;\n    return multisector_block<key_t, word_t, word_cnt, sector_cnt, k,\n                             hasher, hash_value_t, hash_fn_idx, remaining_hash_bits,\n                             remaining_sector_cnt, early_out>\n      ::contains(block_ptr, key, hash_val, true);\n  }\n  //===----------------------------------------------------------------------===//\n\n\n  //===----------------------------------------------------------------------===//\n  // Contains (Recursive)\n  //===----------------------------------------------------------------------===//\n  __forceinline__ __unroll_loops__ __host__ __device__\n  static u1\n  contains(const word_t* __restrict block_ptr, const key_t key, hash_value_t& hash_val, u1 is_contained_in_block) noexcept {\n\n    // Sector pointer\n    const word_t* sector_ptr = block_ptr + (word_cnt_per_sector * current_sector_idx);\n\n    // Process the current sector\n    using sector_t =\n      multiword_sector<key_t, word_t, word_cnt_per_sector, k_cnt_per_sector,\n                       hasher, hash_value_t, hash_fn_idx, remaining_hash_bit_cnt,\n                       k_cnt_per_sector>;\n    auto found_in_sector = sector_t::contains(sector_ptr, key, hash_val, true);\n\n    // Early out\n    if (early_out) {\n      if (likely(!found_in_sector)) return false;\n    }\n\n    // Process remaining sectors recursively, if any\n    return multisector_block<key_t, word_t, word_cnt, sector_cnt, k,\n                      hasher, hash_value_t, sector_t::hash_fn_idx_end, sector_t::remaining_hash_bits,\n                      remaining_sector_cnt - 1, early_out>\n        ::contains(block_ptr, key, hash_val, found_in_sector & is_contained_in_block);\n  }\n  //===----------------------------------------------------------------------===//\n\n\n  //===----------------------------------------------------------------------===//\n  // Contains (SIMD)\n  //===----------------------------------------------------------------------===//\n  template<u64 n>\n  __forceinline__ __unroll_loops__\n  static auto\n  contains(const vec<key_t,n>& keys,\n           const word_t* __restrict bitvector_base_address,\n           const vec<hash_value_t,n>& block_start_word_idxs) noexcept {\n\n    vec<hash_value_t, n> hash_vals(0);\n    const auto is_contained_in_block_mask = vec<word_t,n>::mask::make_all_mask(); // true\n\n    // Call recursive function\n    static constexpr u32 remaining_hash_bits = 0;\n    return multisector_block<key_t, word_t, word_cnt, sector_cnt, k,\n                             hasher, hash_value_t, hash_fn_idx, remaining_hash_bits,\n                             remaining_sector_cnt, early_out>\n      ::contains(keys, hash_vals, bitvector_base_address, block_start_word_idxs, is_contained_in_block_mask);\n\n  }\n  //===----------------------------------------------------------------------===//\n\n\n  //===----------------------------------------------------------------------===//\n  // Contains (SIMD, Recursive)\n  //===----------------------------------------------------------------------===//\n  template<u64 n>\n  __forceinline__ __unroll_loops__\n  static auto\n  contains(const vec<key_t,n>& keys,\n           vec<hash_value_t,n>& hash_vals,\n           const word_t* __restrict bitvector_base_address,\n           const vec<hash_value_t,n>& block_start_word_idxs,\n           const typename vec<word_t,n>::mask is_contained_in_block_mask) noexcept {\n\n    // Sector pointers\n    auto sector_start_word_idxs = block_start_word_idxs + (word_cnt_per_sector * current_sector_idx);\n\n    // Process the current sector\n    using sector_t =\n            multiword_sector<key_t, word_t, word_cnt_per_sector, k_cnt_per_sector,\n                             hasher, hash_value_t, hash_fn_idx, remaining_hash_bit_cnt,\n                             k_cnt_per_sector>;\n    auto found_in_sector_mask = sector_t::contains(keys, hash_vals, bitvector_base_address, sector_start_word_idxs, vec<word_t,n>::mask::make_all_mask());\n\n    // Early out\n    if (early_out) {\n      if (likely(found_in_sector_mask.none())) return found_in_sector_mask;\n    }\n\n    // Process remaining sectors recursively, if any\n    return multisector_block<key_t, word_t, word_cnt, sector_cnt, k,\n                             hasher, hash_value_t, sector_t::hash_fn_idx_end, sector_t::remaining_hash_bits,\n                             remaining_sector_cnt - 1, early_out>\n      ::contains(keys, hash_vals, bitvector_base_address, block_start_word_idxs, found_in_sector_mask & is_contained_in_block_mask);\n  }\n  //===----------------------------------------------------------------------===//\n\n};\n\n\n//===----------------------------------------------------------------------===//\ntemplate<\n    typename key_t,               // the key type\n    typename word_t,              // the word type\n    u32 word_cnt,                 // the number of words per block\n    u32 s,                        // the numbers of sectors (must be a power of two)\n    u32 k,                        // the number of bits to set/test\n    template<typename Ty, u32 i> class hasher,      // the hash function family to use\n    typename hash_value_t,        // the hash value type to use\n\n    u32 hash_fn_idx,              // current hash function index (used for recursion)\n    u32 remaining_hash_bit_cnt,   // the number of remaining hash bits (used for recursion)\n\n    u1 early_out                  // allows for branching out during lookups (before the next sector is tested)\n>\nstruct multisector_block<key_t, word_t, word_cnt, s, k, hasher, hash_value_t, hash_fn_idx, remaining_hash_bit_cnt,\n                         0 /* no more remaining sectors */, early_out>  {\n\n  //===----------------------------------------------------------------------===//\n  // Insert\n  //===----------------------------------------------------------------------===//\n  __forceinline__\n  static void\n  insert(word_t* __restrict block_ptr, const key_t key, hash_value_t& hash_val) noexcept {\n    // End of recursion.\n  }\n  //===----------------------------------------------------------------------===//\n\n\n  //===----------------------------------------------------------------------===//\n  // Contains\n  //===----------------------------------------------------------------------===//\n  __forceinline__ __host__ __device__\n  static u1\n  contains(const word_t* __restrict block_ptr, const key_t key, hash_value_t& hash_val, u1 is_contained_in_block) noexcept {\n    // End of recursion.\n    return is_contained_in_block;\n  }\n  //===----------------------------------------------------------------------===//\n\n\n  //===----------------------------------------------------------------------===//\n  // Contains (SIMD)\n  //===----------------------------------------------------------------------===//\n  template<u64 n>\n  __forceinline__ __unroll_loops__\n  static auto\n  contains(const vec<key_t,n>& keys,\n           vec<hash_value_t,n>& hash_vals,\n           const word_t* __restrict bitvector_base_address,\n           const vec<key_t,n>& block_start_word_idxs,\n           const typename vec<word_t,n>::mask is_contained_in_block_mask) noexcept {\n    // End of recursion.\n    return is_contained_in_block_mask;\n  }\n  //===----------------------------------------------------------------------===//\n\n};\n\n} // namespace dtl\n", "meta": {"hexsha": "4292ac5cfeca9289e6722089f11dd8f81d42a491", "size": 29004, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/dtl/filter/blocked_bloomfilter/blocked_bloomfilter_block_logic_sltw.hpp", "max_stars_repo_name": "peterboncz/bloomfilter-bsd", "max_stars_repo_head_hexsha": "bae83545a091555e48b5495669c7adcb99fd2047", "max_stars_repo_licenses": ["Apache-2.0", "BSD-3-Clause"], "max_stars_count": 15.0, "max_stars_repo_stars_event_min_datetime": "2018-08-26T15:31:49.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-28T06:28:33.000Z", "max_issues_repo_path": "lib/bsd/src/dtl/filter/blocked_bloomfilter/blocked_bloomfilter_block_logic_sltw.hpp", "max_issues_repo_name": "tum-db/partitioned-filters", "max_issues_repo_head_hexsha": "56c20102715a442cbec9ecb732d41de15b31c828", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-12-20T22:56:22.000Z", "max_issues_repo_issues_event_max_datetime": "2019-12-20T22:56:22.000Z", "max_forks_repo_path": "lib/bsd/src/dtl/filter/blocked_bloomfilter/blocked_bloomfilter_block_logic_sltw.hpp", "max_forks_repo_name": "tum-db/partitioned-filters", "max_forks_repo_head_hexsha": "56c20102715a442cbec9ecb732d41de15b31c828", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2018-10-02T09:15:29.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-29T15:45:42.000Z", "avg_line_length": 44.3486238532, "max_line_length": 154, "alphanum_fraction": 0.5399600055, "num_tokens": 6011, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6926419831347361, "lm_q2_score": 0.48438008427698437, "lm_q1q2_score": 0.33550198216458105}}
{"text": "// Copyright (C) 2013 The Regents of the University of California (Regents).\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are\n// met:\n//\n//     * Redistributions of source code must retain the above copyright\n//       notice, this list of conditions and the following disclaimer.\n//\n//     * Redistributions in binary form must reproduce the above\n//       copyright notice, this list of conditions and the following\n//       disclaimer in the documentation and/or other materials provided\n//       with the distribution.\n//\n//     * Neither the name of The Regents or University of California nor the\n//       names of its contributors may be used to endorse or promote products\n//       derived from this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE\n// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n// POSSIBILITY OF SUCH DAMAGE.\n//\n// Please contact the author of this library if you have any questions.\n// Author: Chris Sweeney (cmsweeney@cs.ucsb.edu)\n\n#include \"theia/sfm/pose/perspective_three_point.h\"\n\n#include <Eigen/Dense>\n#include <algorithm>\n#include <complex>\n#include <glog/logging.h>\n#include <math.h>\n\n#include \"theia/math/polynomial.h\"\n#include \"theia/sfm/pose/util.h\"\n\nnamespace theia {\nusing Eigen::Map;\nusing Eigen::Matrix3d;\nusing Eigen::Vector2d;\nusing Eigen::Vector3d;\n\nnamespace {\n\n// Solves for cos(theta) that will describe the rotation of the plane from\n// intermediate world frame to intermediate camera frame. The method returns the\n// roots of a quartic (i.e. solutions to cos(alpha) ) and several factors that\n// are needed for back-substitution.\nint SolvePlaneRotation(const Vector3d normalized_image_points[3],\n                       const Vector3d& intermediate_image_point,\n                       const Vector3d& intermediate_world_point,\n                       const double d_12,\n                       double cos_theta[4],\n                       double cot_alphas[4],\n                       double* b) {\n  // Calculate these parameters ahead of time for reuse and\n  // readability. Notation for these variables is consistent with the notation\n  // from the paper.\n  const double f_1 = intermediate_image_point[0] / intermediate_image_point[2];\n  const double f_2 = intermediate_image_point[1] / intermediate_image_point[2];\n  const double p_1 = intermediate_world_point[0];\n  const double p_2 = intermediate_world_point[1];\n  const double cos_beta =\n      normalized_image_points[0].dot(normalized_image_points[1]);\n  *b = 1.0 / (1.0 - cos_beta * cos_beta) - 1.0;\n\n  if (cos_beta < 0) {\n    *b = -sqrt(*b);\n  } else {\n    *b = sqrt(*b);\n  }\n\n  // Definition of temporary variables for readability in the coefficients\n  // calculation.\n  const double f_1_pw2 = f_1 * f_1;\n  const double f_2_pw2 = f_2 * f_2;\n  const double p_1_pw2 = p_1 * p_1;\n  const double p_1_pw3 = p_1_pw2 * p_1;\n  const double p_1_pw4 = p_1_pw3 * p_1;\n  const double p_2_pw2 = p_2 * p_2;\n  const double p_2_pw3 = p_2_pw2 * p_2;\n  const double p_2_pw4 = p_2_pw3 * p_2;\n  const double d_12_pw2 = d_12 * d_12;\n  const double b_pw2 = (*b) * (*b);\n\n  // Computation of coefficients of 4th degree polynomial.\n  Eigen::VectorXd coefficients(5);\n  coefficients(0) = -f_2_pw2 * p_2_pw4 - p_2_pw4 * f_1_pw2 - p_2_pw4;\n  coefficients(1) = 2.0 * p_2_pw3 * d_12 * (*b) +\n                    2.0 * f_2_pw2 * p_2_pw3 * d_12 * (*b) -\n                    2.0 * f_2 * p_2_pw3 * f_1 * d_12;\n  coefficients(2) =\n      -f_2_pw2 * p_2_pw2 * p_1_pw2 - f_2_pw2 * p_2_pw2 * d_12_pw2 * b_pw2 -\n      f_2_pw2 * p_2_pw2 * d_12_pw2 + f_2_pw2 * p_2_pw4 + p_2_pw4 * f_1_pw2 +\n      2.0 * p_1 * p_2_pw2 * d_12 +\n      2.0 * f_1 * f_2 * p_1 * p_2_pw2 * d_12 * (*b) -\n      p_2_pw2 * p_1_pw2 * f_1_pw2 + 2.0 * p_1 * p_2_pw2 * f_2_pw2 * d_12 -\n      p_2_pw2 * d_12_pw2 * b_pw2 - 2.0 * p_1_pw2 * p_2_pw2;\n  coefficients(3) =\n      2.0 * p_1_pw2 * p_2 * d_12 * (*b) + 2.0 * f_2 * p_2_pw3 * f_1 * d_12 -\n      2.0 * f_2_pw2 * p_2_pw3 * d_12 * (*b) - 2.0 * p_1 * p_2 * d_12_pw2 * (*b);\n  coefficients(4) = -2 * f_2 * p_2_pw2 * f_1 * p_1 * d_12 * (*b) +\n                    f_2_pw2 * p_2_pw2 * d_12_pw2 + 2.0 * p_1_pw3 * d_12 -\n                    p_1_pw2 * d_12_pw2 + f_2_pw2 * p_2_pw2 * p_1_pw2 - p_1_pw4 -\n                    2.0 * f_2_pw2 * p_2_pw2 * p_1 * d_12 +\n                    p_2_pw2 * f_1_pw2 * p_1_pw2 +\n                    f_2_pw2 * p_2_pw2 * d_12_pw2 * b_pw2;\n\n  // Computation of roots.\n  Eigen::VectorXd roots;\n  FindPolynomialRoots(coefficients, &roots, NULL);\n\n  // Calculate cot(alpha) needed for back-substitution.\n  for (int i = 0; i < roots.size(); i++) {\n    cos_theta[i] = roots(i);\n    cot_alphas[i] = (-f_1 * p_1 / f_2 - cos_theta[i] * p_2 + d_12 * (*b)) /\n                    (-f_1 * cos_theta[i] * p_2 / f_2 + p_1 - d_12);\n  }\n\n  return static_cast<int>(roots.size());\n}\n\n// Given the complete transformation between intermediate world and camera\n// frames (parameterized by cos_theta and cot_alpha), back-substitute the\n// solution and get an absolute camera pose.\nvoid Backsubstitute(const Matrix3d& intermediate_world_frame,\n                    const Matrix3d& intermediate_camera_frame,\n                    const Vector3d& world_point_0,\n                    const double cos_theta,\n                    const double cot_alpha,\n                    const double d_12,\n                    const double b,\n                    Vector3d* translation,\n                    Matrix3d* rotation) {\n  const double sin_theta = sqrt(1.0 - cos_theta * cos_theta);\n  const double sin_alpha = sqrt(1.0 / (cot_alpha * cot_alpha + 1.0));\n  double cos_alpha = sqrt(1.0 - sin_alpha * sin_alpha);\n\n  if (cot_alpha < 0) {\n    cos_alpha = -cos_alpha;\n  }\n\n  // Get the camera position in the intermediate world frame\n  // coordinates. (Eq. 5 from the paper).\n  const Vector3d c_nu(\n      d_12 * cos_alpha * (sin_alpha * b + cos_alpha),\n      cos_theta * d_12 * sin_alpha * (sin_alpha * b + cos_alpha),\n      sin_theta * d_12 * sin_alpha * (sin_alpha * b + cos_alpha));\n\n  // Transform c_nu into world coordinates. Use a Map to put the solution\n  // directly into the output.\n  *translation = world_point_0 + intermediate_world_frame.transpose() * c_nu;\n\n  // Construct the transformation from the intermediate world frame to the\n  // intermediate camera frame.\n  Matrix3d intermediate_world_to_camera_rotation;\n  intermediate_world_to_camera_rotation << -cos_alpha, -sin_alpha * cos_theta,\n      -sin_alpha * sin_theta, sin_alpha, -cos_alpha * cos_theta,\n      -cos_alpha * sin_theta, 0, -sin_theta, cos_theta;\n\n  // Construct the rotation matrix.\n  *rotation = (intermediate_world_frame.transpose() *\n               intermediate_world_to_camera_rotation.transpose() *\n               intermediate_camera_frame)\n                  .transpose();\n\n  // Adjust translation to account for rotation.\n  *translation = -(*rotation) * (*translation);\n}\n\n}  // namespace\n\nbool PoseFromThreePoints(const std::vector<Vector2d>& feature_point,\n                         const std::vector<Vector3d>& points_3d,\n                         std::vector<Matrix3d>* solution_rotations,\n                         std::vector<Vector3d>* solution_translations) {\n  Vector3d normalized_image_points[3];\n  // Store points_3d in world_points for ease of use. NOTE: we cannot use a\n  // const ref or a Map because the world_points entries may be swapped later.\n  Vector3d world_points[3];\n  for (int i = 0; i < 3; ++i) {\n    normalized_image_points[i] = feature_point[i].homogeneous().normalized();\n    world_points[i] = points_3d[i];\n  }\n\n  // If the points are collinear, there are no possible solutions.\n  double kTolerance = 1e-6;\n  Vector3d world_1_0 = world_points[1] - world_points[0];\n  Vector3d world_2_0 = world_points[2] - world_points[0];\n  if (world_1_0.cross(world_2_0).squaredNorm() < kTolerance) {\n    VLOG(2) << \"The 3 world points are collinear! No solution for absolute \"\n               \"pose exits.\";\n    return false;\n  }\n\n  // Create intermediate camera frame such that the x axis is in the direction\n  // of one of the normalized image points, and the origin is the same as the\n  // absolute camera frame. This is a rotation defined as the transformation:\n  // T = [tx, ty, tz] where tx = f0, tz = (f0 x f1) / ||f0 x f1||, and\n  // ty = tx x tz and f0, f1, f2 are the normalized image points.\n  Matrix3d intermediate_camera_frame;\n  intermediate_camera_frame.row(0) = normalized_image_points[0];\n  intermediate_camera_frame.row(2) =\n      normalized_image_points[0].cross(normalized_image_points[1]).normalized();\n  intermediate_camera_frame.row(1) =\n      intermediate_camera_frame.row(2).cross(intermediate_camera_frame.row(0));\n\n  // Project the third world point into the intermediate camera frame.\n  Vector3d intermediate_image_point =\n      intermediate_camera_frame * normalized_image_points[2];\n\n  // Enforce that the intermediate_image_point is in front of the intermediate\n  // camera frame. If the point is behind the camera frame, recalculate the\n  // intermediate camera frame by swapping which feature we align the x axis to.\n  if (intermediate_image_point[2] > 0) {\n    std::swap(normalized_image_points[0], normalized_image_points[1]);\n\n    intermediate_camera_frame.row(0) = normalized_image_points[0];\n    intermediate_camera_frame.row(2) = normalized_image_points[0]\n                                           .cross(normalized_image_points[1])\n                                           .normalized();\n    intermediate_camera_frame.row(1) = intermediate_camera_frame.row(2).cross(\n        intermediate_camera_frame.row(0));\n\n    intermediate_image_point =\n        intermediate_camera_frame * normalized_image_points[2];\n\n    std::swap(world_points[0], world_points[1]);\n    world_1_0 = world_points[1] - world_points[0];\n    world_2_0 = world_points[2] - world_points[0];\n  }\n\n  // Create the intermediate world frame transformation that has the\n  // origin at world_points[0] and the x-axis in the direction of\n  // world_points[1]. This is defined by the transformation: N = [nx, ny, nz]\n  // where nx = (p1 - p0) / ||p1 - p0||\n  // nz = nx x (p2 - p0) / || nx x (p2 -p0) || and ny = nz x nx\n  // Where p0, p1, p2 are the world points.\n  Matrix3d intermediate_world_frame;\n  intermediate_world_frame.row(0) = world_1_0.normalized();\n  intermediate_world_frame.row(2) =\n      intermediate_world_frame.row(0).cross(world_2_0).normalized();\n  intermediate_world_frame.row(1) =\n      intermediate_world_frame.row(2).cross(intermediate_world_frame.row(0));\n\n  // Transform world_point[2] to the intermediate world frame coordinates.\n  Vector3d intermediate_world_point = intermediate_world_frame * world_2_0;\n\n  // Distance from world_points[1] to the intermediate world frame origin.\n  double d_12 = world_1_0.norm();\n\n  // Solve for the cos(theta) that will give us the transformation from\n  // intermediate world frame to intermediate camera frame. We also get the\n  // cot(alpha) for each solution necessary for back-substitution.\n  double cos_theta[4];\n  double cot_alphas[4];\n  double b;\n  const int num_solutions = SolvePlaneRotation(normalized_image_points,\n                                               intermediate_image_point,\n                                               intermediate_world_point,\n                                               d_12,\n                                               cos_theta,\n                                               cot_alphas,\n                                               &b);\n\n  // Backsubstitution of each solution\n  solution_translations->resize(num_solutions);\n  solution_rotations->resize(num_solutions);\n  for (int i = 0; i < num_solutions; i++) {\n    Backsubstitute(intermediate_world_frame,\n                   intermediate_camera_frame,\n                   world_points[0],\n                   cos_theta[i],\n                   cot_alphas[i],\n                   d_12,\n                   b,\n                   &solution_translations->at(i),\n                   &solution_rotations->at(i));\n  }\n\n  return num_solutions > 0;\n}\n\n}  // namespace theia\n", "meta": {"hexsha": "b4a38dd47b44926f5c154f83bdef0fc8e965aa1b", "size": 12836, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/theia/sfm/pose/perspective_three_point.cc", "max_stars_repo_name": "urbste/pyTheiaSfM", "max_stars_repo_head_hexsha": "814034c96b602fef1dc76ae6692278d61179ebcc", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2021-11-10T19:50:36.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-03T08:16:54.000Z", "max_issues_repo_path": "src/theia/sfm/pose/perspective_three_point.cc", "max_issues_repo_name": "urbste/pyTheiaSfM", "max_issues_repo_head_hexsha": "814034c96b602fef1dc76ae6692278d61179ebcc", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/theia/sfm/pose/perspective_three_point.cc", "max_forks_repo_name": "urbste/pyTheiaSfM", "max_forks_repo_head_hexsha": "814034c96b602fef1dc76ae6692278d61179ebcc", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-03-14T10:19:04.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-14T10:19:04.000Z", "avg_line_length": 43.6598639456, "max_line_length": 80, "alphanum_fraction": 0.6583826737, "num_tokens": 3400, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6224593312018546, "lm_q2_score": 0.5389832206876841, "lm_q1q2_score": 0.33549513507827744}}
{"text": "#include <algorithm>\n#include <fstream>\n#include <iterator>\n#include <map>\n#include <set>\n#include <sstream>\n#include <string>\n#include <utility>\n\n#include \"utils/profiling.h\"\n\n#include <armadillo>\n\nusing namespace util;\nusing namespace arma;\n\nbool checkMat(int row, int col, mat const &mat) {\n    if(mat.n_rows == row && mat.n_cols == col) return true;\n    return false;\n}\nbool checkVec(int dim, vec const &vec) {\n    if(vec.size() == dim) return true;\n    return false;\n}\n\nint main() {\n\n    auto timer = Timer{};\n    timer.here_then_reset(\"\");\n    \n    int r_dim = 3;\n\n    sp_mat M = sprandu<sp_mat>(1000,1000, 0.1);\n\n    M(0,0) = 10;\n    M(10,10)= 10;\n    M(100,100) = 10;\n    M(102,102) = 100;\n    //M(105,105) = 100;\n    mat U;\n    vec s;\n    mat V;\n\n    svds(U,s,V,M,r_dim);\n\n\n    s.print(\"s = \");\n    return 0;\n}\n", "meta": {"hexsha": "b0a88a85ccab7de477484bd833033ab82c42eea5", "size": 820, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tf-kld/tests/testSVD2.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": "tf-kld/tests/testSVD2.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": "tf-kld/tests/testSVD2.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": 16.4, "max_line_length": 59, "alphanum_fraction": 0.5902439024, "num_tokens": 258, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6224593312018546, "lm_q2_score": 0.5389832206876841, "lm_q1q2_score": 0.33549513507827744}}
{"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/// \\copyright Copyright 2021 Apex.AI, Inc.\n/// All rights reserved.\n\n#ifndef STATE_ESTIMATION_NODES__KALMAN_FILTER_WRAPPER_HPP_\n#define STATE_ESTIMATION_NODES__KALMAN_FILTER_WRAPPER_HPP_\n\n#include <common/types.hpp>\n#include <kalman_filter/esrcf.hpp>\n#include <motion_model/constant_acceleration.hpp>\n#include <nav_msgs/msg/odometry.hpp>\n#include <state_estimation_nodes/history.hpp>\n#include <state_estimation_nodes/measurement.hpp>\n#include <state_estimation_nodes/measurement_typedefs.hpp>\n#include <state_estimation_nodes/steady_time_grid.hpp>\n#include <state_estimation_nodes/visibility_control.hpp>\n\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n\n#include <limits>\n#include <cstdint>\n#include <memory>\n#include <string>\n#include <chrono>\n\nnamespace autoware\n{\nnamespace prediction\n{\n\n///\n/// @brief      This class provides a high level interface to the Kalman Filter allowing to predict\n///             the state of the filter with time and observe it by receiving ROS messages.\n///\n/// @tparam     MotionModelT      An underlying motion model.\n/// @tparam     kNumOfStates      Number of states of the system.\n/// @tparam     kProcessNoiseDim  Dimentionality of the noise.\n///\ntemplate<typename MotionModelT, std::int32_t kNumOfStates, std::int32_t kProcessNoiseDim>\nclass STATE_ESTIMATION_NODES_PUBLIC KalmanFilterWrapper\n{\n  using FilterT = prediction::kalman_filter::Esrcf<kNumOfStates, kProcessNoiseDim>;\n\n  template<std::int32_t kRows, std::int32_t kCols>\n  using RectangularMatrixT = Eigen::Matrix<common::types::float32_t, kRows, kCols>;\n\n  template<std::int32_t kNum>\n  using SquareMatrixT = Eigen::Matrix<common::types::float32_t, kNum, kNum>;\n\n  template<std::int32_t kLength>\n  using VectorT = Eigen::Matrix<common::types::float32_t, kLength, 1>;\n\n  using HistoryT = History<\n    FilterT,\n    kNumOfStates,\n    PredictionEvent,\n    ResetEvent<FilterT>,\n    MeasurementPose,\n    MeasurementSpeed,\n    MeasurementPoseAndSpeed>;\n\npublic:\n  ///\n  /// @brief      Create an EKF wrapper.\n  ///\n  /// @param[in]  initial_covariance_factor  The initial covariances for the state. This is usually\n  ///                                        a diagonal matrix with sigmas for each state dimention\n  ///                                        on the diagonal.\n  /// @param[in]  process_noise              A thin matrix that has as many rows as there are states\n  ///                                        and as many rows as the dimentionality of our space,\n  ///                                        e.g. for state of position, velocity, and acceleration\n  ///                                        in 2D this will be 6x2; for state of position and\n  ///                                        velocity in 1D, it will be 2x1.\n  /// @param[in]  expected_dt                Expected time difference between updates of the filter.\n  /// @param[in]  frame_id                   The frame id in which tracking takes place.\n  /// @param[in]  history_duration           Length of history of events.\n  /// @param[in]  mahalanobis_threshold      The threshold on the Mahalanobis distance for ourlier\n  ///                                        rejection.\n  /// @param[in]  motion_model               The motion model that is to be used. Mostly present\n  ///                                        here to avoid passign the type explicitly.\n  ///\n  KalmanFilterWrapper(\n    const SquareMatrixT<kNumOfStates> & initial_covariance_factor,\n    const RectangularMatrixT<kNumOfStates, kProcessNoiseDim> & process_noise,\n    const std::chrono::nanoseconds & expected_dt,\n    const std::string & frame_id,\n    const std::chrono::nanoseconds & history_duration = std::chrono::milliseconds{5000},\n    common::types::float32_t mahalanobis_threshold =\n    std::numeric_limits<common::types::float32_t>::max(),\n    const MotionModelT & motion_model = MotionModelT{})\n  : m_motion_model{motion_model},\n    m_initial_covariance_factor{initial_covariance_factor},\n    m_frame_id{frame_id},\n    m_mahalanobis_threshold{mahalanobis_threshold},\n    m_expected_prediction_period{expected_dt}\n  {\n    static_assert(\n      motion_model.get_num_states() == kNumOfStates,\n      \"Wrong number of states in the motion model.\");\n\n    SquareMatrixT<kNumOfStates> F;\n    m_motion_model.compute_jacobian(F, expected_dt);\n    m_GQ_left_factor = F * process_noise;\n    m_filter = std::make_unique<FilterT>(m_motion_model, m_GQ_left_factor);\n    m_history = std::make_unique<HistoryT>(\n      *m_filter,\n      static_cast<std::size_t>(history_duration / expected_dt),\n      m_mahalanobis_threshold);\n  }\n\n  ///\n  /// Reset the filter state using the default covariance and state derived from the measurement.\n  ///\n  /// @param[in]  measurement              The measurement from which we initialize the state.\n  ///\n  /// @tparam     MeasurementT             Type of measurement.\n  ///\n  template<typename MeasurementT>\n  void add_reset_event_to_history(const MeasurementT & measurement);\n\n  ///\n  /// Reset the filter state. This must be called at least once to start / tracking.\n  ///\n  /// @param[in]  state                    The full state to set the system to.\n  /// @param[in]  initial_covariance_chol  The initial covariance cholesky factor. For a diagonal\n  ///                                      matrix with squared variances on the diagonal:\n  ///                                      diag([s^2]), its cholesky factor is a diagonal matrix\n  ///                                      with variances on the diagonal: diag([s]).\n  /// @param[in]  event_timestamp          The event timestamp. Ideally this should be in the same\n  ///                                      clock as the one that timestamps the messages.\n  ///\n  void add_reset_event_to_history(\n    const VectorT<kNumOfStates> & state,\n    const SquareMatrixT<kNumOfStates> & initial_covariance_chol,\n    const std::chrono::system_clock::time_point & event_timestamp);\n\n  ///\n  /// Predict state of filter at the next timestep defined by the period of this node.\n  ///\n  /// @return     true if the update was successful and false otherwise. In case false is returned,\n  ///             this update had no effect on the state of the filter.\n  ///\n  common::types::bool8_t add_next_temporal_update_to_history();\n\n  ///\n  /// Update the filter state with a measurement.\n  ///\n  /// @param[in]  measurement            The measurement. It is expected to be a concrete\n  ///                                    instantiation of the Measurement class.\n  ///\n  /// @tparam     MeasurementT           Measurement type that is a concrete template specialization\n  ///                                    of the Measurement class.\n  ///\n  /// @return     true if the observation was successful, false otherwise. In case of an\n  ///             unsuccessful update, the state of the underlying filter has not been changed.\n  ///\n  template<typename MeasurementT>\n  common::types::bool8_t add_observation_to_history(const MeasurementT & measurement);\n\n  /// Check if the filter is is_initialized with a state.\n  inline common::types::bool8_t is_initialized() const noexcept\n  {\n    return (m_history) && (!m_history->empty()) && m_time_grid.is_initialized();\n  }\n\n  /// Get the current state of the system as an odometry message.\n  nav_msgs::msg::Odometry get_state() const;\n\nprivate:\n  /// An implementation of the filter used internally.\n  std::unique_ptr<FilterT> m_filter{};\n  /// Time represented in a frame based on the last measurement timestamp.\n  SteadyTimeGrid m_time_grid{};\n  /// We own our motion model and store it here.\n  MotionModelT m_motion_model;\n  /// We own the left factor of the matrix GQ = m_GQ_left_factor * m_GQ_left_factor.T\n  RectangularMatrixT<kNumOfStates, kProcessNoiseDim> m_GQ_left_factor;\n  /// We own the initial state covariance Cholesky factor. In the most common case, for the diagonal\n  /// covariance matrix  with squared variances on the diagonal: diag([s^2]), it's Cholesky factor\n  /// will be diag([s]). Otherwise this is a lower triangular Cholesky factor of the state\n  /// covariance matrix.\n  SquareMatrixT<kNumOfStates> m_initial_covariance_factor;\n  /// Frame in which the estimation happens, e.g. \"odom\".\n  std::string m_frame_id{};\n  /// The threshold on the Mahalanobis distance used to reject outliers.\n  common::types::float32_t m_mahalanobis_threshold{};\n  /// History of all events is stored here.\n  std::unique_ptr<HistoryT> m_history{};\n  /// What duration passes between prediction events.\n  std::chrono::nanoseconds m_expected_prediction_period{};\n};\n\nusing ConstantAccelerationFilter =\n  KalmanFilterWrapper<motion::motion_model::ConstantAcceleration, 6, 2>;\n\n}  // namespace prediction\n}  // namespace autoware\n\n#endif  // STATE_ESTIMATION_NODES__KALMAN_FILTER_WRAPPER_HPP_\n", "meta": {"hexsha": "b4767b5f795e48048ad37222b9ee85c5536c4bf9", "size": 9360, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/prediction/state_estimation_nodes/include/state_estimation_nodes/kalman_filter_wrapper.hpp", "max_stars_repo_name": "rubis-lab/autoware_rubis", "max_stars_repo_head_hexsha": "498ec5ff4c448d456fa0c6fe2f17e02fbd13ddb9", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/prediction/state_estimation_nodes/include/state_estimation_nodes/kalman_filter_wrapper.hpp", "max_issues_repo_name": "rubis-lab/autoware_rubis", "max_issues_repo_head_hexsha": "498ec5ff4c448d456fa0c6fe2f17e02fbd13ddb9", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/prediction/state_estimation_nodes/include/state_estimation_nodes/kalman_filter_wrapper.hpp", "max_forks_repo_name": "rubis-lab/autoware_rubis", "max_forks_repo_head_hexsha": "498ec5ff4c448d456fa0c6fe2f17e02fbd13ddb9", "max_forks_repo_licenses": ["Apache-2.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.738317757, "max_line_length": 100, "alphanum_fraction": 0.6831196581, "num_tokens": 2118, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7154239957834733, "lm_q2_score": 0.4687906266262437, "lm_q1q2_score": 0.33538406328678555}}
{"text": "#pragma once\n\n#include <armadillo>\n\nclass BoundaryConditions;\n\n/*!\n * \\brief The MatrixEquation class sets up the matrix equation from the system\n * of equations found from the governing equations.\n *\n * The governing equations are discretized using a implicit backward difference\n * method, as detailed in\n *  - <a href=\"https://doi.org/10.1016/j.jngse.2018.03.014\">Gas composition tracking in transient pipeline flow</a>, Chaczykowski et. al., Journal of Natural Gas Science and Engineering 55 (2018)\n *\n * This class supports all combinations of inlet and outlet boundary conditions,\n * so we can for example use flow at the inlet, pressure at the outlet, and\n * temperature at the inlet, or any other combination. Also supports\n * over-determined systems.\n *\n * This class is designed for use together with a Discretizer instance,\n * which sets up the individual elements of the matrix. MatrixEquation just\n * fills in the matrix using results from Discretizer, and solves the matrix\n * equation.\n *\n * The matrix equation is solved using the sparse matrix solver arma::spsolve,\n * which uses superlu internally. This solver only works for critically\n * determined systems, not for over-determined systems. In that case the regular\n * solver is used, and the sparse matrix has to be converted to a regular\n * matrix.\n *\n * Most of the elements in the matrix are zero, so we use sparse matrices. The\n * non-zero elements are all located near the diagonal.\n *\n * \\see Discretizer\n */\nclass MatrixEquation\n{\npublic:\n    //! Declared to avoid the inline compiler-generated default destructor.\n    ~MatrixEquation();\n\n    /*!\n     * \\brief Fill in the coefficient matrix A (MatrixEquation::m_coefficients)\n     * and constants vector b (MatrixEquation::m_constants) in the matrix\n     * equation Ax = b.\n     *\n     * Here `term_i` and `term_ipp` refer to the coefficients of the variables\n     * in the discretized governing equations (flow, pressure and temperature --\n     * \\f$y_i\\f$ in general). See for example eq. (14)-(16) in\n     * <a href=\"https://doi.org/10.1016/j.jngse.2018.03.014\">Gas composition tracking in transient pipeline flow</a>.\n     * These coefficients are calculated by the Discretizer class.\n     *\n     * The boundary terms are the constant terms, the elements of the vector\n     * \\f$b\\f$ in the matrix equation \\f$Ax = b\\f$.\n     *\n     * MatrixEquation supports all combinations of inlet and outlet boundary\n     * conditions, but giving more than 3 boundary conditions lead to an\n     * over-determined system, and giving less than 3 leads to a\n     * under-determined system.\n     *\n     * \\see Discretizer::discretize()\n     *\n     * \\param nGridPoints Number of grid points\n     * \\param nEquationsAndVariables Number of equations and variables\n     * \\param boundaryConditions The boundary conditions\n     * \\param term_i Matrix coefficients at point i (see above)\n     * \\param term_ipp Matrix coefficients at point i+1 (see above)\n     * \\param boundaryTerms The boundary terms (see above)\n     */\n    void fillCoefficientMatrixAndConstantsVector(\n            const arma::uword nGridPoints,\n            const arma::uword nEquationsAndVariables,\n            const BoundaryConditions& boundaryConditions,\n            const arma::cube& term_i,\n            const arma::cube& term_ipp,\n            const arma::mat& boundaryTerms); // fills self matrix and vector\n\n    /*!\n     * \\brief Solve the matrix equation Ax = b.\n     *\n     * This solves the matrix equation, after the coefficient matrix\n     * MatrixEquation::m_coefficients and constant vector\n     * MatrixEquation::m_coefficients has been filled in by\n     * fillCoefficientMatrixAndConstantsVector().\n     *\n     * \\param nGridPoints Number of grid points\n     * \\param nEquationsAndVariables Number of equations and variables\n     * \\param boundaryConditions The boundary conditions\n     * \\return The solution of the matrix equation (x), reshaped to contain\n     * flow, pressure and temperature in separate columns.\n     */\n    arma::mat solve(\n            const arma::uword nGridPoints,\n            const arma::uword nEquationsAndVariables,\n            const BoundaryConditions& boundaryConditions) const;\n\n    //! Get coefficient matrix A. For testing purposes.\n    const arma::sp_mat& coefficients() const { return m_coefficients; }\n    //! Get constants vector b. For testing purposes.\n    const arma::vec& constants() const { return m_constants; }\n\nprivate:\n    arma::sp_mat m_coefficients; //!< Coefficient matrix A\n    arma::vec m_constants; //!< Constants vector b\n\n    /*!\n     * \\brief Reshape output from solving the matrix equation into a matrix\n     * containing flow, pressure and temperature as columns.\n     *\n     * Reshapes the vector x, the solution of the matrix equation Ax = b,\n     * into a matrix with three columns. Also inserts the boundary conditions\n     * where at the correct locations.\n     *\n     * Supports all combinations of inlet/outlet boundary settings.\n     *\n     * \\param x Solution of matrix equation\n     * \\param boundaryConditions Boundary conditions\n     * \\param nGridPoints Number of grid points\n     * \\param nVariables Number of variables\n     * \\return Matrix containing flow, pressure and temperature columns.\n     */\n    arma::mat reshapeSolverOutput(\n            const arma::vec& x,\n            const BoundaryConditions& boundaryConditions,\n            const arma::uword nGridPoints,\n            const arma::uword nVariables) const;\n\n    /*!\n     * \\brief Internal method that solves the matrix equation.\n     *\n     * \\see solve()\n     * \\return Vector x, solution of the matrix equation Ax = b.\n     */\n    arma::vec solveMatrixEquation() const;\n};\n", "meta": {"hexsha": "3d4a3b3e65c6c1b947ae5d2ec5697a7f154cbf65", "size": 5703, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/solver/matrixequation.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/matrixequation.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/matrixequation.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": 41.9338235294, "max_line_length": 195, "alphanum_fraction": 0.6996317728, "num_tokens": 1287, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6406358548398982, "lm_q2_score": 0.523420348936324, "lm_q1q2_score": 0.33532184268141974}}
{"text": "/* ----------------------------------------------------------------------- *//**\n *\n * @file matrix_decomp.cpp\n *\n * @brief Compute decomposition of a matrix in a single node\n *\n *//* ----------------------------------------------------------------------- */\n\n#include <dbconnector/dbconnector.hpp>\n#include <modules/shared/HandleTraits.hpp>\n#include <utils/Math.hpp>\n#include <Eigen/Core>\n#include <Eigen/LU>\n\n#include \"matrix_decomp.hpp\"\n\nnamespace madlib {\n\n// Use Eigen\nusing namespace dbal::eigen_integration;\n\nnamespace modules {\n\nnamespace linalg {\n\n/**\n * @brief Transition state for building a matrix\n *\n * Note: We assume that the DOUBLE PRECISION array is initialized by the\n * database with length 3, and all elemenets are 0. Handle::operator[] will\n * perform bounds checking.\n */\ntemplate <class Handle>\nclass MatrixComposeState {\n    template <class OtherHandle>\n    friend class MatrixComposeState;\n\npublic:\n    MatrixComposeState(const AnyType &inArray)\n            : mStorage(inArray.getAs<Handle>()) {\n        rebind(static_cast<uint64_t>(mStorage[0]), static_cast<uint64_t>(mStorage[1]));\n    }\n\n    operator AnyType() const {\n        return mStorage;\n    }\n\n    void initialize(const Allocator& inAllocator, uint64_t inNumRows, uint64_t inNumCols) {\n        // Allocate the storage for the matrix\n        mStorage = inAllocator.allocateArray<double, dbal::AggregateContext,\n            dbal::DoZero, dbal::ThrowBadAlloc>(stateSize(inNumRows, inNumCols));\n        rebind(inNumRows, inNumCols);\n        numRows = inNumRows;\n        numCols = inNumCols;\n        matrix.fill(0);\n    }\n\n    /**\n     * @brief We need to support assigning the previous state\n     */\n    template <class OtherHandle>\n    MatrixComposeState &operator=(\n        const MatrixComposeState<OtherHandle> &inOtherState) {\n        for (size_t i = 0; i < mStorage.size(); i++)\n            mStorage[i] = inOtherState.mStorage[i];\n        return *this;\n    }\n\n    /**\n     * @brief Merge with another State object\n     */\n    template <class OtherHandle>\n    MatrixComposeState &operator+=(\n        const MatrixComposeState<OtherHandle> &inOtherState) {\n\n        if (mStorage.size() != inOtherState.mStorage.size() ||\n            numRows != inOtherState.numRows ||\n            numCols != inOtherState.numCols)\n            throw std::logic_error(\"Internal error: Incompatible transition \"\n                \"states\");\n        // we assume that the number of rows and number of cols remain the same\n        // between the merged states. We only need to add the matrices together\n        // since each row/element of the matrix is set only once.\n        matrix += inOtherState.matrix;\n        return *this;\n    }\n\nprivate:\n    static inline size_t stateSize(uint64_t inNumRows, uint64_t inNumCols) {\n        return static_cast<size_t>(2 + inNumRows * inNumCols);\n    }\n\n    /**\n     * @brief Rebind to a new storage array\n     *\n     * @param inNumRows The number of rows\n     * @param inNumCols The number of columns\n     *\n     * Array layout (iteration refers to one aggregate-function call):\n     * Inter-iteration components (updated in final function):\n     * - 0: numRows (number of rows)\n     * - 1: numCols (number of columns)\n     * - 2: sumOfPoints (matrix with \\c numRows rows and \\c numCols columns)\n     */\n    void rebind(uint64_t inNumRows, uint64_t inNumCols) {\n        numRows.rebind(&mStorage[0]);\n        numCols.rebind(&mStorage[1]);\n        matrix.rebind(&mStorage[2], static_cast<Index>(inNumRows),\n                      static_cast<Index>(inNumCols));\n\n        madlib_assert(mStorage.size()\n            >= stateSize(inNumRows, inNumCols),\n            std::runtime_error(\"Out-of-bounds array access detected.\"));\n    }\n\n    Handle mStorage;\n\npublic:\n    typename HandleTraits<Handle>::ReferenceToUInt64 numRows;\n    typename HandleTraits<Handle>::ReferenceToUInt64 numCols;\n    typename HandleTraits<Handle>::MatrixTransparentHandleMap matrix;\n};\n\n\nAnyType\nmatrix_compose_dense_transition::run(AnyType& args) {\n    MatrixComposeState<MutableArrayHandle<double> > state = args[0];\n    uint32_t numRows = args[1].getAs<uint32_t>();\n    Index row_id = args[2].getAs<uint32_t>();\n    MappedColumnVector curr_row = args[3].getAs<MappedColumnVector>();\n\n    if (state.numCols == 0)\n        state.initialize(*this, numRows, static_cast<uint32_t>(curr_row.size()));\n    else if (curr_row.size() != state.matrix.cols() ||\n             state.numRows != static_cast<uint32_t>(state.matrix.rows()) ||\n             state.numCols != static_cast<uint32_t>(state.matrix.cols()))\n        throw std::invalid_argument(\"Invalid arguments: Dimensions of vectors \"\n                                    \"not consistent.\");\n    if (row_id < 0 || row_id >= numRows)\n            throw std::runtime_error(\"Invalid row id.\");\n    state.matrix.row(row_id) = curr_row;\n    return state;\n}\n\nAnyType\nmatrix_compose_sparse_transition::run(AnyType& args) {\n    MatrixComposeState<MutableArrayHandle<double> > state = args[0];\n    uint32_t numRows = args[1].getAs<uint32_t>();\n    uint32_t numCols = args[2].getAs<uint32_t>();\n    Index row_id = args[3].getAs<uint32_t>();\n    Index col_id = args[4].getAs<uint32_t>();\n    double element = args[5].getAs<double>();\n\n    if (state.numCols == 0)\n        state.initialize(*this, numRows, numCols);\n    else if (state.numRows != static_cast<uint32_t>(state.matrix.rows()) ||\n             state.numCols != static_cast<uint32_t>(state.matrix.cols()))\n        throw std::invalid_argument(\"Invalid arguments: Dimensions of vectors \"\n                                    \"not consistent.\");\n    if (row_id < 0 || row_id >= numRows)\n            throw std::runtime_error(\"Invalid row id.\");\n    if (col_id < 0 || col_id >= numCols)\n            throw std::runtime_error(\"Invalid col id.\");\n    state.matrix(row_id, col_id) = element;\n    return state;\n}\n\n\n/**\n * @brief Perform the preliminary aggregation function: Merge transition states\n */\nAnyType\nmatrix_compose_merge::run(AnyType &args) {\n    if (args[0].isNull()) { return args[1]; }\n    if (args[1].isNull()) { return args[0]; }\n    MatrixComposeState<MutableArrayHandle<double> > stateLeft = args[0];\n    MatrixComposeState<ArrayHandle<double> > stateRight = args[1];\n\n    // We first handle the trivial case where this function is called with one\n    // of the states being the initial state\n    if (stateLeft.numRows == 0)\n        return stateRight;\n    else if (stateRight.numRows == 0)\n        return stateLeft;\n\n    // Merge states together and return\n    stateLeft += stateRight;\n    return stateLeft;\n}\n\nAnyType\nmatrix_inv::run(AnyType& args){\n    if (args.isNull()) {\n        return Null();\n    }\n    MatrixComposeState<ArrayHandle<double> > state = args[0];\n    // we apply a transpose operation at the end since Eigen matrices are interpreted\n    // as column-major when returned to the database\n    const Matrix m_inverse = state.matrix.inverse().transpose();\n    return m_inverse;\n}\n\nAnyType\nmatrix_eigen::run(AnyType& args) {\n    if (args.isNull()) {\n        return Null();\n    }\n    MatrixComposeState<ArrayHandle<double> > state = args[0];\n    // we apply a transpose operation at the end since Eigen matrices are interpreted\n    // as column-major when returned to the database\n    const VectorXcd eigenvalues = state.matrix.eigenvalues();\n    return MappedVectorXcd(eigenvalues.leftCols(static_cast<Index>(1)));\n}\n\nAnyType\nmatrix_cholesky::run(AnyType& args){\n    if (args.isNull()) {\n        return Null();\n    }\n    MatrixComposeState<ArrayHandle<double> > state = args[0];\n    const MatrixLDLT ldlt = state.matrix.ldlt();\n    if (ldlt.info() != Success) {\n        throw std::invalid_argument(\"Invalida arguments: Cholesky decomposition of input matrix\"\n                \" does not exist\");\n    }\n    // we apply a transpose operation at the end since Eigen matrices are interpreted\n    // as column-major when returned to the database\n    const Matrix m_p(PermutationMatrix(ldlt.transpositionsP()));\n    const Matrix m_l = ldlt.matrixL();\n    const Matrix m_d(ldlt.vectorD().asDiagonal());\n    Matrix m_cholesky(state.matrix.rows(), state.matrix.cols() * 3);\n    m_cholesky.block(0, 0, state.matrix.rows(), state.matrix.cols()) << m_p;\n    m_cholesky.block(0, state.matrix.cols(), state.matrix.rows(), state.matrix.cols()) << m_l;\n    m_cholesky.block(0, state.matrix.cols() * 2, state.matrix.rows(), state.matrix.cols()) << m_d;\n    const Matrix res = m_cholesky.transpose();\n    return res;\n}\n\nAnyType\nmatrix_qr::run(AnyType& args){\n    if (args.isNull()) {\n        return Null();\n    }\n    MatrixComposeState<ArrayHandle<double> > state = args[0];\n    const HouseholderQR qr = state.matrix.householderQr();\n    const Matrix &R = qr.matrixQR().triangularView<Upper>();\n    const Matrix &Q =  qr.householderQ();\n\n    madlib_assert(Q.rows() == Q.cols() && Q.cols() == R.rows(),\n        std::runtime_error(\"Error QR decomposition result.\"));\n    Matrix m(Q.rows(), Q.cols() + R.cols());\n    m.block(0, 0, Q.rows(), Q.cols()) << Q;\n    m.block(0, Q.cols(), R.rows(), R.cols()) << R;\n    // we apply a transpose operation at the end since Eigen matrices are interpreted\n    // as column-major when returned to the database\n    const Matrix & res = m.transpose();\n    return res;\n}\n\nAnyType\nmatrix_rank::run(AnyType& args){\n    if (args.isNull()) {\n        return Null();\n    }\n    MatrixComposeState<ArrayHandle<double> > state = args[0];\n    return static_cast<int64_t>(state.matrix.fullPivLu().rank());\n}\n\nAnyType\nmatrix_lu::run(AnyType& args){\n    if (args.isNull()) {\n        return Null();\n    }\n    MatrixComposeState<ArrayHandle<double> > state = args[0];\n    const FullPivLU &lu = state.matrix.fullPivLu();\n\n    Matrix l = Matrix::Identity(state.numRows, state.numRows);\n    l.block(0, 0, lu.matrixLU().rows(), lu.matrixLU().cols()).triangularView<StrictlyLower>() = lu.matrixLU();\n    const Matrix &u = lu.matrixLU().triangularView<Upper>();\n    const Matrix &p(lu.permutationP());\n    const Matrix &q(lu.permutationQ());\n    Matrix m(static_cast<Index>(std::max(state.numRows, state.numCols)),\n             static_cast<Index>(state.numRows * 2 + state.numCols * 2));\n    m.block(0, 0, state.numRows, state.numRows) << p;\n    m.block(0, state.numRows, state.numRows, state.numRows) << l;\n    m.block(0, state.numRows * 2, state.numRows, state.numCols) << u;\n    m.block(0, state.numRows * 2 + state.numCols, state.numCols, state.numCols) << q;\n\n    // we apply a transpose operation at the end since Eigen matrices are interpreted\n    // as column-major when returned to the database\n    const Matrix res = m.transpose();\n    return res;\n}\n\nAnyType\nmatrix_nuclear_norm::run(AnyType& args){\n    if (args.isNull()) {\n        return Null();\n    }\n    MatrixComposeState<ArrayHandle<double> > state = args[0];\n    const JacobiSVD &svd = state.matrix.jacobiSvd(EigenvaluesOnly);\n    const Matrix u = svd.matrixU();\n    const Matrix v = svd.matrixV();\n    double norm = 0;\n    for (Index i = 0; i < svd.singularValues().rows(); ++i)\n        norm += svd.singularValues()(i);\n    return norm;\n}\n\nAnyType\nmatrix_pinv::run(AnyType& args) {\n    if (args.isNull()) {\n        return Null();\n    }\n    using namespace std;\n    MatrixComposeState<ArrayHandle<double> > state = args[0];\n    const JacobiSVD &svd = state.matrix.jacobiSvd(ComputeFullU|ComputeFullV);\n    const Matrix u = svd.matrixU();\n    const Matrix v = svd.matrixV();\n    Matrix s(svd.singularValues().asDiagonal());\n    double pinvtoler = 1.e-6;\n    for (Index i = 0; i < s.rows(); ++i) {\n        for (Index j = 0; j < s.cols(); ++j) {\n            // for very small singular values we treat the inverse as zero\n            if (s(i, j) > pinvtoler)\n                s(i, j) = 1.0 / s(i, j);\n            else s(i, j) = 0;\n        }\n    }\n    // we apply a transpose operation at the end since Eigen matrices are interpreted\n    // as column-major when returned to the database\n    const Matrix &res = (v * s * u.transpose()).transpose();\n    return res;\n}\n\n} // namespace linalg\n\n} // namespace modules\n\n} // namespace regress\n", "meta": {"hexsha": "66521b0303d70b8d21a6c481a803d39eac4b75d8", "size": 12067, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/modules/linalg/matrix_decomp.cpp", "max_stars_repo_name": "fmcquillan99/apache-madlib", "max_stars_repo_head_hexsha": "e2dea62d1eadc7f662f2d926c71f42332f414ca0", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2018-09-18T07:44:22.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-14T19:45:18.000Z", "max_issues_repo_path": "src/modules/linalg/matrix_decomp.cpp", "max_issues_repo_name": "fmcquillan99/apache-madlib", "max_issues_repo_head_hexsha": "e2dea62d1eadc7f662f2d926c71f42332f414ca0", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-09-06T05:50:17.000Z", "max_issues_repo_issues_event_max_datetime": "2018-09-06T05:50:17.000Z", "max_forks_repo_path": "src/modules/linalg/matrix_decomp.cpp", "max_forks_repo_name": "fmcquillan99/apache-madlib", "max_forks_repo_head_hexsha": "e2dea62d1eadc7f662f2d926c71f42332f414ca0", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-09-03T20:50:13.000Z", "max_forks_repo_forks_event_max_datetime": "2019-09-03T20:50:13.000Z", "avg_line_length": 35.3870967742, "max_line_length": 110, "alphanum_fraction": 0.6419988398, "num_tokens": 3002, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.640635841117624, "lm_q2_score": 0.523420348936324, "lm_q1q2_score": 0.3353218354989022}}
{"text": "#pragma once\n\n#include <cstdlib>\n#include <utility>\n#include <tuple>\n#include <numeric>\n\n#include <boost/unordered_map.hpp>\n#include \"types.hh\"\n\n/*!\n  @brief Generate a region automaton from a timed automaton\n  @tparam NVar the number of variable in TA\n\n  TA to RA adds states with BFS. Initial configuration is the initial states of RA. The RA contain only the states reachable from initial states.\n */\ntemplate <int NVar>\nvoid ta_to_ra (const TimedAutomaton<NVar> &TA,RegionAutomaton &RA)\n{\n  //! number of states of RA\n  State numOfStates;\n  Region initialRegion;\n  initialRegion.integer_parts.resize (NVar);\n  fill(initialRegion.integer_parts.begin(), \n       initialRegion.integer_parts.end(),\n       std::make_pair(0,0));\n  initialRegion.max_constraints = TA.max_constraints;\n\n  // make initial state\n  numOfStates = TA.initialStates.size();\n  RA.edges.resize(numOfStates);\n  RA.initialStates.resize (numOfStates);\n  iota (RA.initialStates.begin(), RA.initialStates.end(),0);\n\n  RA.abstractedStates.reserve (numOfStates);\n  for (const auto &conf : TA.initialStates ) {\n    RA.abstractedStates.push_back (std::make_pair(conf,initialRegion));\n  }\n\n  /*!\n    @brief Current configuration of BFS\n    \n    A configuration consistes of a tuple ((conf,\\alpha),conf,alpha). Remark (conf,\\alpha) is not a pair but just a number representing a state of RA.\n   */\n  std::vector<std::tuple<RAState,TAState,Region> > nextConf;\n  nextConf.resize (RA.abstractedStates.size());\n  for (std::size_t i = 0; i < nextConf.size();i++) {\n    nextConf[i] = std::make_tuple(i,RA.abstractedStates[i].first,RA.abstractedStates[i].second);\n  }\n  \n  /*! \n    @brief translater from TAState and Region to its corresponding state in RA.\n\n    The type is like this.\n    (TAState,([Int,Int],[[Int]],[Int])) -> RAState\n  */\n  boost::unordered_map<std::pair<TAState,std::tuple<std::vector< std::pair<int,int> >, std::list<std::list<int> >, std::vector<int> > >,RAState> regions_in_ra;\n  while (!nextConf.empty ()) {\n    std::vector<std::tuple<State,State,Region> > currentConf = nextConf;\n    nextConf.clear();\n    for (const auto &conf : currentConf) {\n      Region nowRegion,nextRegion;\n      bool self_successor;\n      nowRegion = std::get<2>(conf);\n      const bool existsNextRegion = nowRegion.nextRegion (nextRegion,self_successor);\n\n      nextRegion = self_successor ? nowRegion : nextRegion;\n      if (!existsNextRegion && !self_successor)\n        break;\n      do {\n        nowRegion = std::move(nextRegion);\n        bool tooLarge = true;\n#ifdef DEBUG\n        cout << \"=====================\"<< endl;\n#endif\n        const Region::Interpretation val = nowRegion;\n        for (const auto &edge : TA.edges.at(std::get<1>(conf))) {\n#ifdef DEBUG\n          cout << (int)get<1>(conf) << \":\" \n               << (int)edge.source << \"->\"\n               << (int)edge.target << \" \"\n               << (edge.guard(val) ? \"true\" : \"false\")\n               << endl;\n#endif\n          if (std::all_of(edge.guard.begin(),edge.guard.end(),\n                          [&val] (const Constraint &delta){return delta(val) == Order::EQ;})) {\n            tooLarge = false;\n            Region targetRegion = nowRegion;\n            for (auto x : edge.resetVars) {\n              targetRegion.integer_parts[x] = {0,0};\n              for (auto it = targetRegion.frac_order.begin();\n                   it != targetRegion.frac_order.end(); it++) {\n                const auto initialNum = it->size();\n                it->remove(x);\n                if (initialNum != it->size()) {\n                  if (it->empty() ) {\n                    targetRegion.frac_order.erase(it);\n                  }\n                  break;\n                }\n              }\n            }\n\n#ifdef DEBUG\n            cout << \"nowRegion\" << endl;\n            cout << nowRegion << endl;\n\n            cout << \"targetRegion\" << endl;\n            cout << targetRegion << endl;\n#endif            \n            // nextRegion state is new\n            const auto targetRegionState = std::make_pair(edge.target,std::make_tuple(targetRegion.integer_parts,targetRegion.frac_order,targetRegion.max_constraints));\n            const auto targetStateInRA = regions_in_ra.find(targetRegionState);\n#ifdef DEBUG\n            cout << (targetStateInRA == RA.abstractedStates.end()) << endl;\n            cout << (int)get<0>(conf) << \"-\" << edge.c << \">\" << static_cast<int>(targetStateInRA - RA.abstractedStates.begin()) << endl;\n#endif\n            // targetRegionState is already added\n            if (targetStateInRA != regions_in_ra.end()) {\n              RA.edges[std::get<0>(conf)].push_back ({std::get<0>(conf),targetStateInRA->second,edge.c});\n            } else {\n#ifdef DEBUG\n              cout << \"added \" << (int)numOfStates << \" = \" << targetStateInRA - RA.abstractedStates.begin()<< endl;\n#endif\n              RA.edges[std::get<0>(conf)].push_back ({std::get<0>(conf),static_cast<State>(numOfStates),edge.c});\n              if (binary_search (TA.acceptingStates.begin(), \n                                 TA.acceptingStates.end (),edge.target)) {\n                RA.acceptingStates.push_back (numOfStates);\n              }\n              regions_in_ra[targetRegionState] = numOfStates;\n              RA.abstractedStates.push_back (std::make_pair (edge.target,targetRegion));\n              nextConf.push_back (std::make_tuple (numOfStates,edge.target,targetRegion));\n              numOfStates++;\n              RA.edges.resize(numOfStates);\n            }\n          } else if (std::none_of(edge.guard.begin(), edge.guard.end(),\n                                  [val](const Constraint &delta){return delta (val) == Order::GT;})) {\n            tooLarge = false;\n          }\n        }\n        if (tooLarge) break;\n      } while(nowRegion.nextRegion (nextRegion,self_successor));\n    }\n    //    std::cout << numOfStates << std::endl;\n  }\n\n}\n", "meta": {"hexsha": "6c50fcdccbd4b1253d7319fa6c568781022227dd", "size": 5841, "ext": "hh", "lang": "C++", "max_stars_repo_path": "src/ta_to_ra.hh", "max_stars_repo_name": "MasWag/timed-pattern-matching", "max_stars_repo_head_hexsha": "325d03d2447bdc3b28c391a94f920d708581ad35", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/ta_to_ra.hh", "max_issues_repo_name": "MasWag/timed-pattern-matching", "max_issues_repo_head_hexsha": "325d03d2447bdc3b28c391a94f920d708581ad35", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/ta_to_ra.hh", "max_forks_repo_name": "MasWag/timed-pattern-matching", "max_forks_repo_head_hexsha": "325d03d2447bdc3b28c391a94f920d708581ad35", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.4662162162, "max_line_length": 168, "alphanum_fraction": 0.5942475603, "num_tokens": 1378, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6654105720171531, "lm_q2_score": 0.5039061705290805, "lm_q1q2_score": 0.33530449317472855}}
{"text": "///////////////////////////////////////////////////////////////////////////////\n// rolling_mean.hpp\n// Copyright (C) 2008 Eric Niebler.\n// Copyright (C) 2012 Pieter Bastiaan Ober (Integricom).\n// Distributed under the Boost Software License, Version 1.0.\n// (See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n\n#ifndef BOOST_ACCUMULATORS_STATISTICS_ROLLING_MEAN_HPP_EAN_26_12_2008\n#define BOOST_ACCUMULATORS_STATISTICS_ROLLING_MEAN_HPP_EAN_26_12_2008\n\n#include <boost/mpl/placeholders.hpp>\n#include <boost/accumulators/framework/accumulator_base.hpp>\n#include <boost/accumulators/framework/extractor.hpp>\n#include <boost/accumulators/numeric/functional.hpp>\n#include <boost/accumulators/framework/parameters/sample.hpp>\n#include <boost/accumulators/framework/depends_on.hpp>\n#include <boost/accumulators/statistics_fwd.hpp>\n#include <boost/accumulators/statistics/rolling_sum.hpp>\n#include <boost/accumulators/statistics/rolling_count.hpp>\n\nnamespace boost { namespace accumulators\n{\n   namespace impl\n   {\n      ///////////////////////////////////////////////////////////////////////////////\n      // lazy_rolling_mean_impl\n      //    returns the mean over the rolling window and is calculated only\n      //    when the result is requested\n      template<typename Sample>\n      struct lazy_rolling_mean_impl\n         : accumulator_base\n      {\n         // for boost::result_of\n         typedef typename numeric::functional::fdiv<Sample, std::size_t, void, void>::result_type result_type;\n\n         lazy_rolling_mean_impl(dont_care)\n         {\n         }\n\n         template<typename Args>\n         result_type result(Args const &args) const\n         {\n            return numeric::fdiv(rolling_sum(args), rolling_count(args));\n         }\n      };\n\n      ///////////////////////////////////////////////////////////////////////////////\n      // immediate_rolling_mean_impl\n      //     The non-lazy version computes the rolling mean recursively when a new\n      //     sample is added\n      template<typename Sample>\n      struct immediate_rolling_mean_impl\n         : accumulator_base\n      {\n         // for boost::result_of\n         typedef typename numeric::functional::fdiv<Sample, std::size_t>::result_type result_type;\n\n         template<typename Args>\n         immediate_rolling_mean_impl(Args const &args)\n            : mean_(numeric::fdiv(args[sample | Sample()],numeric::one<std::size_t>::value))\n         {\n         }\n\n         template<typename Args>\n         void operator()(Args const &args)\n         {\n            if(is_rolling_window_plus1_full(args))\n            {\n               mean_ += numeric::fdiv(args[sample]-rolling_window_plus1(args).front(),rolling_count(args));\n            }\n            else\n            {\n               result_type prev_mean = mean_;\n               mean_ += numeric::fdiv(args[sample]-prev_mean,rolling_count(args));\n            }\n         }\n\n         template<typename Args>\n         result_type result(Args const &) const\n         {\n            return mean_;\n         }\n\n      private:\n\n         result_type mean_;\n      };\n   } // namespace impl\n\n   ///////////////////////////////////////////////////////////////////////////////\n   // tag::lazy_rolling_mean\n   // tag::immediate_rolling_mean\n   // tag::rolling_mean\n   //\n   namespace tag\n   {\n      struct lazy_rolling_mean\n         : depends_on< rolling_sum, rolling_count >\n      {\n         /// INTERNAL ONLY\n         ///\n         typedef accumulators::impl::lazy_rolling_mean_impl< mpl::_1 > impl;\n\n#ifdef BOOST_ACCUMULATORS_DOXYGEN_INVOKED\n         /// tag::rolling_window::window_size named parameter\n         static boost::parameter::keyword<tag::rolling_window_size> const window_size;\n#endif\n      };\n\n      struct immediate_rolling_mean\n         : depends_on< rolling_window_plus1, rolling_count>\n      {\n         /// INTERNAL ONLY\n         ///\n         typedef accumulators::impl::immediate_rolling_mean_impl< mpl::_1> impl;\n\n#ifdef BOOST_ACCUMULATORS_DOXYGEN_INVOKED\n         /// tag::rolling_window::window_size named parameter\n         static boost::parameter::keyword<tag::rolling_window_size> const window_size;\n#endif\n      };\n\n      // make immediate_rolling_mean the default implementation\n      struct rolling_mean : immediate_rolling_mean {};\n   } // namespace tag\n\n   ///////////////////////////////////////////////////////////////////////////////\n   // extract::lazy_rolling_mean\n   // extract::immediate_rolling_mean\n   // extract::rolling_mean\n   //\n   namespace extract\n   {\n      extractor<tag::lazy_rolling_mean> const lazy_rolling_mean = {};\n      extractor<tag::immediate_rolling_mean> const immediate_rolling_mean = {};\n      extractor<tag::rolling_mean> const rolling_mean = {};\n\n      BOOST_ACCUMULATORS_IGNORE_GLOBAL(lazy_rolling_mean)\n         BOOST_ACCUMULATORS_IGNORE_GLOBAL(immediate_rolling_mean)\n         BOOST_ACCUMULATORS_IGNORE_GLOBAL(rolling_mean)\n   }\n\n   using extract::lazy_rolling_mean;\n   using extract::immediate_rolling_mean;\n   using extract::rolling_mean;\n\n   // rolling_mean(lazy) -> lazy_rolling_mean\n   template<>\n   struct as_feature<tag::rolling_mean(lazy)>\n   {\n      typedef tag::lazy_rolling_mean type;\n   };\n\n   // rolling_mean(immediate) -> immediate_rolling_mean\n   template<>\n   struct as_feature<tag::rolling_mean(immediate)>\n   {\n      typedef tag::immediate_rolling_mean type;\n   };\n\n   // for the purposes of feature-based dependency resolution,\n   // immediate_rolling_mean provides the same feature as rolling_mean\n   template<>\n   struct feature_of<tag::immediate_rolling_mean>\n      : feature_of<tag::rolling_mean>\n   {\n   };\n\n   // for the purposes of feature-based dependency resolution,\n   // lazy_rolling_mean provides the same feature as rolling_mean\n   template<>\n   struct feature_of<tag::lazy_rolling_mean>\n      : feature_of<tag::rolling_mean>\n   {\n   };\n}} // namespace boost::accumulators\n\n#endif", "meta": {"hexsha": "1439da1e2c9e24bcf0da965a91cbcfd1c84dc1e2", "size": 5919, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "deps/cinder/include/boost/accumulators/statistics/rolling_mean.hpp", "max_stars_repo_name": "multi-os-engine/cinder-natj-binding", "max_stars_repo_head_hexsha": "969b66fdd49e4ca63442baf61ce90ae385ab8178", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 11356.0, "max_stars_repo_stars_event_min_datetime": "2017-12-08T19:42:32.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T16:55:25.000Z", "max_issues_repo_path": "ios/Pods/boost-for-react-native/boost/accumulators/statistics/rolling_mean.hpp", "max_issues_repo_name": "c7yrus/alyson-v3", "max_issues_repo_head_hexsha": "5ad95a8f782f5f5d2fd543d44ca6a8b093395965", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 2402.0, "max_issues_repo_issues_event_min_datetime": "2017-12-08T22:31:01.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-28T19:25:52.000Z", "max_forks_repo_path": "ios/Pods/boost-for-react-native/boost/accumulators/statistics/rolling_mean.hpp", "max_forks_repo_name": "c7yrus/alyson-v3", "max_forks_repo_head_hexsha": "5ad95a8f782f5f5d2fd543d44ca6a8b093395965", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1343.0, "max_forks_repo_forks_event_min_datetime": "2017-12-08T19:47:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-26T11:31:36.000Z", "avg_line_length": 33.0670391061, "max_line_length": 110, "alphanum_fraction": 0.6291603311, "num_tokens": 1248, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.665410572017153, "lm_q2_score": 0.5039061705290805, "lm_q1q2_score": 0.3353044931747285}}
{"text": "// Copyright (c) 2016 Giorgio Marcias & Maurizio Kovacic\n//\n// This source code is part of DopeVector header library\n// and it is subject to Apache 2.0 License.\n//\n// Author: Giorgio Marcias\n// email: marcias.giorgio@gmail.com\n// Author: Maurizio Kovacic\n// email: maurizio.kovacic@gmail.com\n\n#ifndef EigenExpression_hpp\n#define EigenExpression_hpp\n\n#ifdef DOPE_USE_EIGEN\n\n#include <DopeVector/internal/Expression.hpp>\n#include <Eigen/Core>\n\nnamespace dope {\n\n\tnamespace internal {\n\n\t\ttemplate < class Derived, class Er, typename T, SizeType Dimension, typename Op >\n\t\tclass EigenStaticArrayBinaryExpression : public StaticArrayExpression<EigenStaticArrayBinaryExpression<Derived, Er, T, Dimension, Op>, T, Dimension> {\n\t\t\tstatic_assert((Eigen::MatrixBase<Derived>::RowsAtCompileTime == Dimension && Eigen::MatrixBase<Derived>::ColsAtCompileTime == 1) ||\n\t\t\t\t\t\t  (Eigen::MatrixBase<Derived>::RowsAtCompileTime == 1 && Eigen::MatrixBase<Derived>::ColsAtCompileTime == Dimension), \"Eigen object must be a vertical vector.\");\n\t\tprivate:\n\t\t\tconst Eigen::MatrixBase<Derived>                  &_el;\n\t\t\tconst Er\t                                          &_er;\n\t\t\tmutable std::array<std::function<T()>, Dimension>  _values;\n\t\t\tstatic const Op                                    _op;\n\n\t\tpublic:\n\t\t\tinline EigenStaticArrayBinaryExpression(const Eigen::MatrixBase<Derived> &el, const Er &er);\n\n\t\t\tinline T operator[](const SizeType i) const;\n\t\t};\n\n\n\n\t\ttemplate < class El, typename T, SizeType Dimension, class Derived, typename Op >\n\t\tclass StaticArrayBinaryEigenExpression : public StaticArrayExpression<StaticArrayBinaryEigenExpression<El, T, Dimension, Derived, Op>, T, Dimension> {\n\t\t\tstatic_assert((Eigen::MatrixBase<Derived>::RowsAtCompileTime == Dimension && Eigen::MatrixBase<Derived>::ColsAtCompileTime == 1) ||\n\t\t\t\t\t\t  (Eigen::MatrixBase<Derived>::RowsAtCompileTime == 1 && Eigen::MatrixBase<Derived>::ColsAtCompileTime == Dimension), \"Eigen object must be a vertical vector.\");\n\t\tprivate:\n\t\t\tconst El                                          &_el;\n\t\t\tconst Eigen::MatrixBase<Derived>                  &_er;\n\t\t\tmutable std::array<std::function<T()>, Dimension>  _values;\n\t\t\tstatic const Op                                    _op;\n\n\t\tpublic:\n\t\t\tinline StaticArrayBinaryEigenExpression(const El &el, const Eigen::MatrixBase<Derived> &er);\n\n\t\t\tinline T operator[](const SizeType i) const;\n\t\t};\n\n\n\n\t\ttemplate < class Derived, class Er, typename T, SizeType Dimension >\n\t\tinline EigenStaticArrayBinaryExpression<Derived, Er, T, Dimension, std::plus<T>> operator+ (const Eigen::MatrixBase<Derived> &el, const StaticArrayExpression<Er, T, Dimension> &er);\n\n\n\n\t\ttemplate < class Derived, class Er, typename T, SizeType Dimension >\n\t\tinline EigenStaticArrayBinaryExpression<Derived, Er, T, Dimension, std::minus<T>> operator- (const Eigen::MatrixBase<Derived> &el, const StaticArrayExpression<Er, T, Dimension> &er);\n\n\n\n\t\ttemplate < class Derived, class Er, typename T, SizeType Dimension >\n\t\tinline EigenStaticArrayBinaryExpression<Derived, Er, T, Dimension, std::multiplies<T>> operator* (const Eigen::MatrixBase<Derived> &el, const StaticArrayExpression<Er, T, Dimension> &er);\n\n\n\n\t\ttemplate < class Derived, class Er, typename T, SizeType Dimension >\n\t\tinline EigenStaticArrayBinaryExpression<Derived, Er, T, Dimension, std::divides<T>> operator/ (const Eigen::MatrixBase<Derived> &el, const StaticArrayExpression<Er, T, Dimension> &er);\n\n\n\n\t\ttemplate < class Derived, class Er, typename T, SizeType Dimension >\n\t\tinline EigenStaticArrayBinaryExpression<Derived, Er, T, Dimension, std::modulus<T>> operator% (const Eigen::MatrixBase<Derived> &el, const StaticArrayExpression<Er, T, Dimension> &er);\n\n\n\n\t\ttemplate < class El, typename T, SizeType Dimension, class Derived >\n\t\tinline StaticArrayBinaryEigenExpression<El, T, Dimension, Derived, std::plus<T>> operator+ (const StaticArrayExpression<El, T, Dimension> &el, const Eigen::MatrixBase<Derived> &er);\n\n\n\n\t\ttemplate < class El, typename T, SizeType Dimension, class Derived >\n\t\tinline StaticArrayBinaryEigenExpression<El, T, Dimension, Derived, std::minus<T>> operator- (const StaticArrayExpression<El, T, Dimension> &el, const Eigen::MatrixBase<Derived> &er);\n\n\n\n\t\ttemplate < class El, typename T, SizeType Dimension, class Derived >\n\t\tinline StaticArrayBinaryEigenExpression<El, T, Dimension, Derived, std::multiplies<T>> operator* (const StaticArrayExpression<El, T, Dimension> &el, const Eigen::MatrixBase<Derived> &er);\n\n\n\n\t\ttemplate < class El, typename T, SizeType Dimension, class Derived >\n\t\tinline StaticArrayBinaryEigenExpression<El, T, Dimension, Derived, std::divides<T>> operator/ (const StaticArrayExpression<El, T, Dimension> &el, const Eigen::MatrixBase<Derived> &er);\n\n\n\n\t\ttemplate < class El, typename T, SizeType Dimension, class Derived >\n\t\tinline StaticArrayBinaryEigenExpression<El, T, Dimension, Derived, std::modulus<T>> operator% (const StaticArrayExpression<El, T, Dimension> &el, const Eigen::MatrixBase<Derived> &er);\n\n\t}\n\n}\n\n#include <DopeVector/internal/inlines/eigen_support/EigenExpression.inl>\n\n#endif\n\n#endif\n", "meta": {"hexsha": "31db5eb9d23402a34b49a2e1d3f94283975620e9", "size": 5094, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "hackathon/yang/neuronrecon/3rdparty/DopeVector/internal/eigen_support/EigenExpression.hpp", "max_stars_repo_name": "zzhmark/vaa3d_tools", "max_stars_repo_head_hexsha": "3ca418add85a59ac7e805d55a600b78330d7e53d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2016-11-24T10:14:19.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-23T06:28:23.000Z", "max_issues_repo_path": "hackathon/yang/neuronrecon/3rdparty/DopeVector/internal/eigen_support/EigenExpression.hpp", "max_issues_repo_name": "zzhmark/vaa3d_tools", "max_issues_repo_head_hexsha": "3ca418add85a59ac7e805d55a600b78330d7e53d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2016-09-23T18:36:35.000Z", "max_issues_repo_issues_event_max_datetime": "2016-09-23T19:03:10.000Z", "max_forks_repo_path": "hackathon/yang/neuronrecon/3rdparty/DopeVector/internal/eigen_support/EigenExpression.hpp", "max_forks_repo_name": "zzhmark/vaa3d_tools", "max_forks_repo_head_hexsha": "3ca418add85a59ac7e805d55a600b78330d7e53d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2019-01-03T23:37:08.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-18T09:37:38.000Z", "avg_line_length": 43.9137931034, "max_line_length": 189, "alphanum_fraction": 0.7230074598, "num_tokens": 1241, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.665410572017153, "lm_q2_score": 0.5039061705290805, "lm_q1q2_score": 0.3353044931747285}}
{"text": "#ifndef KILLGEN_FIXPOINT_ITERATOR_HPP\n#define KILLGEN_FIXPOINT_ITERATOR_HPP\n\n/**\n  * Specialized fixpoint iterators and domains for kill-gen problems.\n  */\n\n#include <crab/common/stats.hpp>\n#include <crab/common/debug.hpp>\n#include <crab/cfg/cfg_bgl.hpp>\n#include <crab/analysis/graphs/sccg.hpp>\n#include <crab/analysis/graphs/topo_order.hpp>\n\n#include <crab/domains/discrete_domains.hpp>\n#include <crab/domains/patricia_trees.hpp>\n\n#include <boost/optional.hpp>\n\nnamespace crab {\n\n  namespace domains {\n\n    // A wrapper for discrete_domain (i.e,. set of Element)\n    template<class Element>\n    class flat_killgen_domain: public ikos::writeable {\n         \n     private:\n\n      typedef flat_killgen_domain<Element> flat_killgen_domain_t;\n      typedef ikos::discrete_domain<Element> discrete_domain_t;\n      \n     public:\n\n      typedef typename discrete_domain_t::iterator iterator;\n      typedef Element element_t;\n\n     private:\n\n      discrete_domain_t _inv;\n      \n     public:\n      \n      flat_killgen_domain(discrete_domain_t inv)\n          : ikos::writeable(), _inv(inv){ } \n      \n      static flat_killgen_domain_t top() {\n        return flat_killgen_domain(discrete_domain_t::top());\n      }\n      \n      static flat_killgen_domain_t bottom() {\n        return flat_killgen_domain(discrete_domain_t::bottom());\n      }\n      \n      flat_killgen_domain()\n          : ikos::writeable(), _inv(discrete_domain_t::bottom()){ }\n      \n      flat_killgen_domain(Element e)\n          : ikos::writeable(), _inv(e) { }\n      \n      flat_killgen_domain(const flat_killgen_domain_t &o)\n          : ikos::writeable(), _inv(o._inv) { } \n          \n      flat_killgen_domain(flat_killgen_domain_t &&o)\n          : ikos::writeable(), _inv(std::move(o._inv)) { } \n      \n      flat_killgen_domain_t& operator=(const flat_killgen_domain_t &other) {\n        if (this != &other) \n          _inv = other._inv;\n        return *this;\n      }\n      \n      flat_killgen_domain_t& operator=(flat_killgen_domain_t &&other) {\n        _inv = std::move(other._inv);\n        return *this;\n      }\n      \n      iterator begin() { return _inv.begin(); }\n      \n      iterator end() { return _inv.end(); }\n      \n      unsigned size() { return _inv.size(); }\n      \n      bool is_bottom() { return _inv.is_bottom(); }\n         \n      bool is_top() { return _inv.is_top(); }\n\n      bool operator==(flat_killgen_domain_t other) {\n\treturn *this <= other && other <= *this;\n      }\n      \n      bool operator<=(flat_killgen_domain_t other) {\n        if (is_bottom ()) \n          return true;\n        else if (other.is_top ())\n          return true;\n        else\n          return (_inv <= other._inv);\n      }\n      \n      void operator-=(Element x) {\n        if (is_bottom ()) \n          return;\n        _inv -= x;\n      }\n         \n      void operator-=(flat_killgen_domain_t other) {\n        if (is_bottom () || other.is_bottom ()) \n          return;\n        \n        if (!other._inv.is_top()) {\n          for (auto v : other) \n            _inv -= v; \n        }\n      }\n      \n      void operator+=(Element x) {\n        if (is_top ()) \n          return;\n        _inv += x;\n      }\n      \n      void operator+=(flat_killgen_domain_t other) {\n        if (is_top () || other.is_bottom ()) {\n          return;\n        } else if (other.is_top ()) {\n          _inv = discrete_domain_t::top();\n        } else {\n          _inv = (_inv | other._inv);\n        }\n      }\n      \n      flat_killgen_domain_t operator|(flat_killgen_domain_t other) {\n        return (_inv | other._inv);\n      }\n      \n      flat_killgen_domain_t operator&(flat_killgen_domain_t other) {\n        return (_inv & other._inv);\n      }\n         \n      void write(crab_os& o) { _inv.write(o); }\n      \n    };\n\n    // To represent sets of pairs (Key,Value). \n    // Bottom means empty set rather than failure.\n    template <typename Key, typename Value>\n    class separate_killgen_domain: public ikos::writeable {\n      \n    private:\n      typedef ikos::patricia_tree<Key,Value> patricia_tree_t;\n      typedef typename patricia_tree_t::unary_op_t unary_op_t;\n      typedef typename patricia_tree_t::binary_op_t binary_op_t;\n      typedef typename patricia_tree_t::partial_order_t partial_order_t;\n\n    public:\n      typedef separate_killgen_domain<Key,Value > separate_killgen_domain_t;\n      typedef typename patricia_tree_t::iterator iterator;\n      typedef Key key_type;\n      typedef Value value_type;\n      \n    private:\n      bool _is_top;\n      patricia_tree_t _tree;\n    \n    public: \n      class bottom_found { };\n      \n      class join_op: public binary_op_t {\n\tboost::optional< Value > apply(Value x, Value y) {\n\t  Value z = x.operator|(y);\n\t  if (z.is_top()) {\n\t    return boost::optional<Value>();\n\t  } else {\n\t    return boost::optional<Value>(z);\n\t  }\n\t}\n\tbool default_is_absorbing() { return false; }\n      }; // class join_op\n\n      class meet_op: public binary_op_t {\n\tboost::optional< Value > apply(Value x, Value y) {\n\t  Value z = x.operator&(y);\n\t  if (z.is_bottom()) {\n\t    throw bottom_found();\n\t  } else {\n\t    return boost::optional<Value>(z);\n\t  }\n\t};\n\tbool default_is_absorbing() { return true; }\n      }; // class meet_op\n    \n      class domain_po: public partial_order_t {\n\tbool leq(Value x, Value y) { return x.operator<=(y); }\n\tbool default_is_top() { return false; }\n      }; // class domain_po\n    \n   public:\n      \n      static separate_killgen_domain_t top() {\n\treturn separate_killgen_domain_t (true);\n      }\n      \n      static separate_killgen_domain_t bottom() {\n\treturn separate_killgen_domain_t (false);\n      }\n    \n   private:\n      \n      static patricia_tree_t apply_operation(binary_op_t& o, \n\t\t\t\t\t     patricia_tree_t t1, \n\t\t\t\t\t     patricia_tree_t t2) {\n\tt1.merge_with(t2, o);\n\treturn t1;\n      }\n    \n      separate_killgen_domain(patricia_tree_t t)\n\t: _is_top(false), _tree(t) { }\n      \n      separate_killgen_domain(bool b)\n\t: _is_top(b) { }\n    \n    public:\n      \n      separate_killgen_domain()\n\t: _is_top(false), _tree (patricia_tree_t()) { }\n\n      separate_killgen_domain(const separate_killgen_domain_t& o)\n\t: _is_top(o._is_top), _tree(o._tree) { }\n    \n      separate_killgen_domain_t& operator=(separate_killgen_domain_t o) {\n\tthis->_is_top = o._is_top;\n\tthis->_tree = o._tree;\n\treturn *this;\n      }\n\n      iterator begin() const {\n\tif (this->is_top()) {\n\t  CRAB_ERROR(\"Separate killgen domain: trying to invoke iterator on top\");\n\t} else {\n\t  return this->_tree.begin();\n\t}\n      }\n    \n      iterator end() const {\n\tif (this->is_top()) {\n\t  CRAB_ERROR(\"Separate killgen domain: trying to invoke iterator on top\");\n\t} else {\n\t  return this->_tree.end();\n\t}\n      }\n\n      bool is_top() const {\n\treturn _is_top;\n      }\n      \n      bool is_bottom() const {\n\treturn (!is_top () && _tree.empty ());\n      }\n    \n    \n      bool operator<=(separate_killgen_domain_t o) {\n\tdomain_po po; \n\treturn (o.is_top() || (!is_top() && (_tree.leq (o._tree, po))));\n      }\n    \n      separate_killgen_domain_t operator|(separate_killgen_domain_t o) {\n\tif (is_top() || o.is_top ()) {\n\t  return separate_killgen_domain_t::top();\n\t} else {\n\t  join_op op;\n\t  return separate_killgen_domain_t(apply_operation(op, _tree, o._tree));\n\t}\n      }\n    \n      separate_killgen_domain_t operator&(separate_killgen_domain_t o) {\n\tif (is_top ()) {\n\t  return o;\n\t} else if (o.is_top()) {\n\t  return *this;\n\t} else {\n\t  try {\n\t    meet_op op;\n\t    return separate_killgen_domain_t(apply_operation(op, _tree, o._tree));\n\t  }\n\t  catch (bottom_found& exc) {\n\t    return separate_killgen_domain_t::bottom ();\n\t  }\n\t}\n      }\n\n      void set(Key k, Value v) {\n\tif (!is_top ()) {\n\t  // if (v.is_bottom()) {\n\t  //   this->_tree.remove(k);\n\t  // } else {\n\t  //   this->_tree.insert(k, v);\n\t  // }\n\t  this->_tree.insert(k, v);\t  \n\t}\n      }\n    \n      separate_killgen_domain_t& operator-=(Key k) {\n\tif (!is_top ()) {\n\t  _tree.remove(k);\n\t}\n\treturn *this;\n      }\n    \n      Value operator[](Key k) {\n\tif (is_top ())\n\t  return Value::top ();\n\telse {\n\t  boost::optional< Value > v = _tree.lookup(k);\n\t  if (v) {\n\t    return *v;\n\t  } else {\n\t    return Value::bottom();\n\t  }\n\t}\n      }\n    \n      void write(crab::crab_os& o) {\n\tif (this->is_top()) {\n\t  o << \"{...}\";\n\t} if (_tree.empty ()) {\n\t  o << \"_|_\";\n\t}\n\telse {\n\t  o << \"{\";\n\t  for (typename patricia_tree_t::iterator it = this->_tree.begin(); \n\t       it != this->_tree.end(); ) {\n\t    Key k = it->first;\n\t    k.write(o);\n\t    o << \" -> \";\n          Value v = it->second;\n          v.write(o);\n          ++it;\n          if (it != this->_tree.end()) {\n            o << \"; \";\n\t  }\n\t  }\n\t  o << \"}\";\n\t}\n      }\n    }; // class separate_killgen_domain\n    \n  } // end namespace domains\n\n  \n  namespace iterators {\n    \n    // API for a kill-gen analysis operations\n    template<class CFG, class Dom>\n    class killgen_operations_api {\n\n     public:\n      \n      typedef typename CFG::basic_block_label_t basic_block_label_t;    \n      typedef Dom killgen_domain_t;\n\n     protected:\n\n      CFG _cfg;\n\n     public:\n\n      killgen_operations_api (CFG cfg): _cfg(cfg) { }\n\n      virtual ~killgen_operations_api() { }\n\n      // whether forward or backward analysis\n      virtual bool is_forward () = 0;\n\n      // initial state\n      virtual Dom entry() = 0;\n \n      // (optional) initialization for the fixpoint\n      virtual void init_fixpoint () = 0;\n\n      // confluence operator\n      virtual Dom merge(Dom, Dom) = 0;\n\n      // analyze a basic block\n      virtual Dom analyze (basic_block_label_t, Dom) = 0;\n\n      // analysis name\n      virtual std::string name () = 0;\n    };\n\n    // A simple fixpoint for a killgen analysis\n    template<class CFG, class KgAnalysisOps>\n    class killgen_fixpoint_iterator {\n\n     public:\n      \n      typedef typename CFG::basic_block_label_t basic_block_label_t;\n      typedef typename KgAnalysisOps::killgen_domain_t killgen_domain_t;\n      typedef boost::unordered_map<basic_block_label_t,killgen_domain_t> inv_map_t;\n      typedef typename inv_map_t::iterator iterator;\n      typedef typename inv_map_t::const_iterator const_iterator;\n      \n     protected:\n\n      CFG _cfg;\n      inv_map_t _in_map;\n      inv_map_t _out_map;\n\n     private:\n\n      KgAnalysisOps _analysis;\n\n      /// XXX: run_bwd_fixpo(G) is equivalent to run_fwd_fixpo(reverse(G)).\n      ///      However, weak_rev_topo_sort(G) != weak_topo_sort(reverse(G))\n      /// For instance, for a G=(V,E) where\n      ///   V= {v1,v2, v3, v4, v5}, \n      ///   E= {(v1,v2), (v1,v3), (v2,v4), (v4,v1), (v3,v5)}\n      /// (1) weak_rev_topo_sort(cfg)=[v5,v3,v4,v2,v1] \n      /// (2) weak_topo_sort(reverse(cfg))=[v5,v3,v2,v4,v1] or even\n      ///     worse [v5,v3,v1,v4,v2] if vertices in the same scc are\n      ///     traversed in preorder.\n      /// For a backward analysis, (1) will converge faster.\n      /// For all of this, we decide not to reverse graphs and have\n      /// two dual versions for the forward and backward analyses.\n\n      void run_fwd_fixpo (std::vector<typename CFG::node_t> &order,\n                          unsigned &iterations){\n\n        order = crab::analyzer::graph_algo::weak_topo_sort(_cfg);\n        assert ((int)order.size () == std::distance(_cfg.begin(), _cfg.end()));\n        bool change = true;\n        iterations = 0;\n        while (change) {\n          change = false;\n          ++iterations;\n          for (auto &n: order) {\n            auto in = _analysis.entry();\n            for (auto p: _cfg.prev_nodes (n))\n              in = _analysis.merge(in, _out_map[p]); \n            auto old_out = _out_map[n];\n            auto out = _analysis.analyze(n, in);\n            if (!(out <= old_out)) {\n              _out_map[n] = _analysis.merge(out, old_out);\n              change = true;\n            } else \n              _in_map[n] = in;\n          }\n        }\n      }\n      \n      void run_bwd_fixpo (std::vector<typename CFG::node_t> &order,\n                          unsigned &iterations){\n\n        order = crab::analyzer::graph_algo::weak_rev_topo_sort(_cfg);\n        assert ((int)order.size () == std::distance(_cfg.begin(), _cfg.end()));\n        bool change = true;\n        iterations = 0;\n        while (change) {\n          change = false;\n          ++iterations;\n          for (auto &n: order) {\n            auto out = _analysis.entry();\n            for (auto p: _cfg.next_nodes (n))\n              out = _analysis.merge(out, _in_map[p]); \n            auto old_in = _in_map[n];\n            auto in = _analysis.analyze(n, out);\n            if (!(in <= old_in)) {\n              _in_map[n] = _analysis.merge(in, old_in);\n              change = true;\n            } else \n              _out_map[n] = out;\n          }\n        }\n      }\n\n     public:\n\n      killgen_fixpoint_iterator (CFG cfg)\n\t: _cfg (cfg), _analysis (_cfg) { }\n\n      void release_memory () {\n        _in_map.clear();\n        _out_map.clear();\n      }\n\n      void run() { \n        crab::ScopedCrabStats __st__(_analysis.name());\n\n        _analysis.init_fixpoint(); \n\n        std::vector<typename CFG::node_t> order;\n        unsigned iterations = 0;\n        if (_analysis.is_forward())\n          run_fwd_fixpo(order, iterations);\n        else\n          run_bwd_fixpo(order, iterations);\n\n        CRAB_LOG(_analysis.name(), \n                 crab::outs()  << \"fixpoint ordering={\"; \n                 bool first=true;\n                 for (auto &v : order) {\n                   if (!first) crab::outs() << \",\";\n                   first=false;\n                   crab::outs() << cfg_impl::get_label_str(v); \n                 }\n                 crab::outs() << \"}\\n\";); \n        \n\n        CRAB_LOG(_analysis.name(), \n                 crab::outs() << _analysis.name() << \": \" \n                              << \"fixpoint reached in \" << iterations << \" iterations.\\n\"); \n        \n        CRAB_LOG(_analysis.name(), \n                 crab::outs() << _analysis.name() << \" sets:\\n\";\n                 for (auto n: boost::make_iterator_range (_cfg.label_begin (),\n                                                          _cfg.label_end ())) {\n                   crab::outs() << cfg_impl::get_label_str(n) << \" \"\n                                << \"IN=\"  << _in_map[n]  << \" \"\n                                << \"OUT=\" << _out_map[n] << \"\\n\"; \n                 }\n                 crab::outs() << \"\\n\";);\n      }      \n\n      iterator in_begin() { return _in_map.begin(); }\n      iterator in_end() { return _in_map.end(); } \n      const_iterator in_begin() const { return _in_map.begin(); }\n      const_iterator in_end() const { return _in_map.end(); } \n\n      iterator out_begin() { return _out_map.begin(); } \n      iterator out_end() { return _out_map.end(); }\n      const_iterator out_begin() const { return _out_map.begin(); } \n      const_iterator out_end() const { return _out_map.end(); }\n\n   }; \n\n  } // end namespace iterators\n} // end namespace crab\n\n#endif \n", "meta": {"hexsha": "dbcd40b80b2851c64e52eb29287b39eb32ae004a", "size": 14868, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/crab/iterators/killgen_fixpoint_iterator.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/iterators/killgen_fixpoint_iterator.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/iterators/killgen_fixpoint_iterator.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": 27.5844155844, "max_line_length": 92, "alphanum_fraction": 0.5622814097, "num_tokens": 3703, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.665410558746814, "lm_q2_score": 0.5039061705290805, "lm_q1q2_score": 0.33530448648772276}}
{"text": "#include \"wire_mesh.h\"\n\n#include \"../../list_to_matrix.h\"\n#include \"../../slice.h\"\n#include \"../../PI.h\"\n#include \"convex_hull.h\"\n#include \"mesh_boolean.h\"\n#include <Eigen/Geometry>\n#include <vector>\n\ntemplate <\n  typename DerivedWV,\n  typename DerivedWE,\n  typename DerivedV,\n  typename DerivedF,\n  typename DerivedJ>\nIGL_INLINE void igl::copyleft::cgal::wire_mesh(\n  const Eigen::MatrixBase<DerivedWV> & WV,\n  const Eigen::MatrixBase<DerivedWE> & WE,\n  const double th,\n  const int poly_size,\n  const bool solid,\n  Eigen::PlainObjectBase<DerivedV> & V,\n  Eigen::PlainObjectBase<DerivedF> & F,\n  Eigen::PlainObjectBase<DerivedJ> & J)\n{\n\n  typedef typename DerivedWV::Scalar Scalar;\n  // Canonical polygon to place at each endpoint\n  typedef Eigen::Matrix<Scalar,Eigen::Dynamic,3> MatrixX3S;\n  MatrixX3S PV(poly_size,3);\n  for(int p =0;p<PV.rows();p++)\n  {\n    const Scalar phi = (Scalar(p)/Scalar(PV.rows()))*2.*igl::PI;\n    PV(p,0) = 0.5*cos(phi);\n    PV(p,1) = 0.5*sin(phi);\n    PV(p,2) = 0;\n  }\n\n  V.resize(WV.rows() + PV.rows() * 2 * WE.rows(),3);\n  V.topLeftCorner(WV.rows(),3) = WV;\n  // Signed adjacency list\n  std::vector<std::vector<std::pair<int,int> > > A(WV.rows());\n  // Inputs:\n  //   e  index of edge\n  //   c  index of endpoint [0,1]\n  //   p  index of polygon vertex\n  // Returns index of corresponding vertex in V\n  const auto index = \n    [&PV,&WV](const int e, const int c, const int p)->int\n  {\n    return WV.rows() + e*2*PV.rows() + PV.rows()*c + p;\n  };\n  const auto unindex = \n    [&PV,&WV](int v, int & e, int & c, int & p)\n  {\n    assert(v>=WV.rows());\n    v = v-WV.rows();\n    e = v/(2*PV.rows());\n    v = v-e*(2*PV.rows());\n    c = v/(PV.rows());\n    v = v-c*(PV.rows());\n    p = v;\n  };\n  // loop over all edges\n  for(int e = 0;e<WE.rows();e++)\n  {\n    // Fill in adjacency list as we go\n    A[WE(e,0)].emplace_back(e,0);\n    A[WE(e,1)].emplace_back(e,1);\n    typedef Eigen::Matrix<Scalar,1,3> RowVector3S;\n    const RowVector3S ev = WV.row(WE(e,1))-WV.row(WE(e,0));\n    const Scalar len = ev.norm();\n    // Unit edge vector\n    const RowVector3S uv = ev.normalized();\n    Eigen::Quaternion<Scalar> q;\n    q = q.FromTwoVectors(RowVector3S(0,0,1),uv);\n    // loop over polygon vertices\n    for(int p = 0;p<PV.rows();p++)\n    {\n      RowVector3S qp = q*(PV.row(p)*th);\n      // loop over endpoints\n      for(int c = 0;c<2;c++)\n      {\n        // Direction moving along edge vector\n        const Scalar dir = c==0?1:-1;\n        // Amount (distance) to move along edge vector\n        // Start with factor of thickness;\n        // Max out amount at 1/3 of edge length so that there's always some\n        // amount of edge\n        Scalar dist = std::min(1.*th,len/3.0);\n        // Move to endpoint, offset by amount\n        V.row(index(e,c,p)) = \n          qp+WV.row(WE(e,c)) + dist*dir*uv;\n      }\n    }\n  }\n\n  std::vector<std::vector<typename DerivedF::Index> > vF;\n  std::vector<int> vJ;\n  const auto append_hull = \n    [&V,&vF,&vJ,&unindex,&WV](const Eigen::VectorXi & I, const int j)\n  {\n    MatrixX3S Vv;\n    igl::slice(V,I,1,Vv);\n    Eigen::MatrixXi Fv;\n    convex_hull(Vv,Fv);\n    for(int f = 0;f<Fv.rows();f++)\n    {\n      const Eigen::Array<int,1,3> face(I(Fv(f,0)), I(Fv(f,1)), I(Fv(f,2)));\n      //const bool on_vertex = (face<WV.rows()).any();\n      //if(!on_vertex)\n      //{\n      //  // This correctly prunes fcaes on the \"caps\" of convex hulls around\n      //  // edges, but for convex hulls around vertices this will only work if\n      //  // the incoming edges are not overlapping.\n      //  //\n      //  // Q: For convex hulls around vertices, is the correct thing to do:\n      //  // check if all corners of face lie *on or _outside_* of plane of \"cap\"?\n      //  // \n      //  // H: Maybe, but if there's an intersection then the boundary of the\n      //  // incoming convex hulls around edges is still not going to match up\n      //  // with the boundary on the convex hull around the vertices.\n      //  //\n      //  // Might have to bite the bullet and always call self-union.\n      //  bool all_same = true;\n      //  int e0,c0,p0;\n      //  unindex(face(0),e0,c0,p0);\n      //  for(int i = 1;i<3;i++)\n      //  {\n      //    int ei,ci,pi;\n      //    unindex(face(i),ei,ci,pi);\n      //    all_same = all_same && (e0==ei && c0==ci);\n      //  }\n      //  if(all_same)\n      //  {\n      //    // don't add this face\n      //    continue;\n      //  }\n      //}\n      vF.push_back( { face(0),face(1),face(2)});\n      vJ.push_back(j);\n    }\n  };\n  // loop over each vertex\n  for(int v = 0;v<WV.rows();v++)\n  {\n    // Gather together this vertex and the polygon vertices of all incident\n    // edges\n    Eigen::VectorXi I(1+A[v].size()*PV.rows());\n    // This vertex\n    I(0) = v;\n    for(int n = 0;n<A[v].size();n++)\n    {\n      for(int p = 0;p<PV.rows();p++)\n      {\n        const int e = A[v][n].first;\n        const int c = A[v][n].second;\n        I(1+n*PV.rows()+p) = index(e,c,p);\n      }\n    }\n    append_hull(I,v);\n  }\n  // loop over each edge\n  for(int e = 0;e<WE.rows();e++)\n  {\n    // Gether together polygon vertices of both endpoints\n    Eigen::VectorXi I(PV.rows()*2);\n    for(int c = 0;c<2;c++)\n    {\n      for(int p = 0;p<PV.rows();p++)\n      {\n        I(c*PV.rows()+p) = index(e,c,p);\n      }\n    }\n    append_hull(I,WV.rows()+e);\n  }\n\n  list_to_matrix(vF,F);\n  if(solid)\n  {\n    // Self-union to clean up \n    igl::copyleft::cgal::mesh_boolean(\n      Eigen::MatrixXd(V),Eigen::MatrixXi(F),Eigen::MatrixXd(),Eigen::MatrixXi(),\n      \"union\",\n      V,F,J);\n    for(int j=0;j<J.size();j++) J(j) = vJ[J(j)];\n  }else\n  {\n    list_to_matrix(vJ,J);\n  }\n}\n\ntemplate <\n  typename DerivedWV,\n  typename DerivedWE,\n  typename DerivedV,\n  typename DerivedF,\n  typename DerivedJ>\nIGL_INLINE void igl::copyleft::cgal::wire_mesh(\n  const Eigen::MatrixBase<DerivedWV> & WV,\n  const Eigen::MatrixBase<DerivedWE> & WE,\n  const double th,\n  const int poly_size,\n  Eigen::PlainObjectBase<DerivedV> & V,\n  Eigen::PlainObjectBase<DerivedF> & F,\n  Eigen::PlainObjectBase<DerivedJ> & J)\n{\n  return wire_mesh(WV,WE,th,poly_size,true,V,F,J);\n}\n\n#ifdef IGL_STATIC_LIBRARY\n// Explicit template instantiation \ntemplate void igl::copyleft::cgal::wire_mesh<Eigen::Matrix<double, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, -1, 0, -1, -1>, Eigen::Matrix<double, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, 1, 0, -1, 1> >(Eigen::MatrixBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> > const&, Eigen::MatrixBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> > const&, double, int, Eigen::PlainObjectBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> >&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> >&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, 1, 0, -1, 1> >&);\n#endif\n", "meta": {"hexsha": "0e96095017f75e7672b81d5ad8fcc6d187827c21", "size": 6742, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "isometric-deformation/ext/libigl/include/igl/copyleft/cgal/wire_mesh.cpp", "max_stars_repo_name": "jiayaozhang/CS-370-Mesh-Processing", "max_stars_repo_head_hexsha": "26646d29af8cbc0d461302afa137f12b508b8b1b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 29.0, "max_stars_repo_stars_event_min_datetime": "2019-11-27T00:43:07.000Z", "max_stars_repo_stars_event_max_datetime": "2020-02-25T14:35:54.000Z", "max_issues_repo_path": "isometric-deformation/ext/libigl/include/igl/copyleft/cgal/wire_mesh.cpp", "max_issues_repo_name": "jiayaozhang/CS-370-Mesh-Processing", "max_issues_repo_head_hexsha": "26646d29af8cbc0d461302afa137f12b508b8b1b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "isometric-deformation/ext/libigl/include/igl/copyleft/cgal/wire_mesh.cpp", "max_forks_repo_name": "jiayaozhang/CS-370-Mesh-Processing", "max_forks_repo_head_hexsha": "26646d29af8cbc0d461302afa137f12b508b8b1b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-11-27T05:19:03.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-23T22:49:53.000Z", "avg_line_length": 31.212962963, "max_line_length": 589, "alphanum_fraction": 0.5752002373, "num_tokens": 2195, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6757646140788307, "lm_q2_score": 0.4960938294709195, "lm_q1q2_score": 0.3352426552193052}}
{"text": "/*Copyright (c) 2021 James Gayvert\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n*/\n\n/*\n * molcas_interface.cpp\n */\n\n#include \"molcas_interface.h\"\n\n#include <h5pp/h5pp.h>\n#include <math.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <algorithm>\n#include <Eigen/Dense>\n#include <fstream>\n#include <iostream>\n#include <unsupported/Eigen/CXX11/Tensor>\n\n#include \"BasisSet.h\"\n#include \"gto_ordering.h\"\n#include \"opencap_exception.h\"\n#include \"utils.h\"\n\ntemplate<typename T>\nusing  MatrixType = Eigen::Matrix<T,Eigen::Dynamic, Eigen::Dynamic>;\n\ntemplate<typename Scalar,int rank, typename sizeType>\nauto Tensor_to_Matrix(const Eigen::Tensor<Scalar,rank> &tensor,const sizeType rows,const sizeType cols)\n{\n    return Eigen::Map<const MatrixType<Scalar>> (tensor.data(), rows,cols);\n}\n\nEigen::Map<const Eigen::MatrixXd> reshape (const Eigen::VectorXd& b, const uint n, const uint m) {\n    return Eigen::Map<const Eigen::MatrixXd>(b.data(), n, m);\n}\n\nvoid read_rassi_tdms(std::vector<std::vector<Eigen::MatrixXd>> &alpha_opdms,\n\t\tstd::vector<std::vector<Eigen::MatrixXd>> &beta_opdms,\n\t\tstd::string filename, BasisSet bs,size_t nstates)\n{\n    alpha_opdms = std::vector< std::vector<Eigen::MatrixXd>>(nstates, std::vector<Eigen::MatrixXd> (nstates));\n    beta_opdms = std::vector< std::vector<Eigen::MatrixXd>>(nstates, std::vector<Eigen::MatrixXd> (nstates));\n\th5pp::File file(filename, h5pp::FilePermission::READONLY);\n\t//first lets check if the dimensions are correct\n\tstd::vector<long> nbas_vec = file.readAttribute<std::vector<long>>(\"NBAS\",\"/\");\n\tlong nbas=0;\n\tfor(auto num_bas:nbas_vec)\n\t\tnbas+=num_bas;\n\tif(nbas!=bs.Nbasis)\n\t\topencap_throw(\"Error: dimensions of RASSI basis set does not match specified basis set.\");\n\tauto nsym = file.readAttribute<long>(\"NSYM\", \"/\");\n\t//now lets load the densities\n\tEigen::Tensor<double,3> rass_data, spin_dens;\n\ttry\n\t{\n\t\tfile.readDataset(rass_data,\"SFS_TRANSITION_DENSITIES\");\n\t\tfile.readDataset(spin_dens,\"SFS_TRANSITION_SPIN_DENSITIES\");\n\t}\n\tcatch(exception &e)\n\t{\n\t\topencap_throw(\"Error: SFS_TRANSITION_DENSITIES dataset not found. Use the TRD1 keyword\"\n\t\t\t\t\" in the RASSI module to activate transition densities.\")\n\t}\n    const auto& d = rass_data.dimensions();\n\n    if (nsym>1)\n    {\n    \t//Step 1: get the desymmetrization matrix\n\t\tEigen::VectorXd desym_vec;\n\t\tfile.readDataset(desym_vec,\"DESYM_MATRIX\");\n\t\tEigen::MatrixXd desym_mat;\n\t\tstd::vector<long> nbas_vec = file.readAttribute<std::vector<long>>(\"NBAS\",\"/\");\n\t\tdesym_mat = reshape(desym_vec,nbas,nbas);\n\t\tlong mat_size=0;\n\t\tfor(auto num_bas:nbas_vec)\n\t\t\tmat_size+=num_bas*num_bas;\n\t\t//now lets loop over the matrices\n\t\tfor(long i=0;i<d[0];i++)\n\t\t{\n            if(d[0]!=nstates)\n                opencap_throw(\"Error: Found \" + std::to_string(d[0]) + \" states in RASSI file, but \"\n                          + std::to_string(nstates) + \" states were specified.\");\n\t\t\tstd::vector<Eigen::MatrixXd> alpha_state_row;\n\t\t\tstd::vector<Eigen::MatrixXd> beta_state_row;\n\t\t\tfor (long j=0;j<d[1];j++)\n\t\t\t{\n\t\t\t\t//step 2: get the raw matrices\n\t\t\t\tEigen::array<long,3> offset = {i,j,0};    //Starting point\n\t\t\t\tEigen::array<long,3> extent = {1,1,1}; //end point\n\t\t\t\tEigen::Tensor<double, 2> dmt_slice = rass_data.slice(offset, extent).reshape(Eigen::array<long,2>{mat_size,(long)1});\n\t\t\t\tEigen::MatrixXd  dmt_vec =  Tensor_to_Matrix(dmt_slice,mat_size,(long)1);\n\t\t\t\tEigen::Tensor<double, 2> spin_slice = spin_dens.slice(offset, extent).reshape(Eigen::array<long,2>{mat_size,(long)1});\n\t\t\t\tEigen::MatrixXd  spin_vec =  Tensor_to_Matrix(dmt_slice,mat_size,(long)1);\n\n\t\t\t\t//step 3: turn into bigger matrix by adding zeros\n\t\t\t\tEigen::MatrixXd dmat,spin;\n\t\t\t\tdmat = Eigen::MatrixXd::Zero(nbas,nbas);\n\t\t\t\tspin = Eigen::MatrixXd::Zero(nbas,nbas);\n\t\t\t\t//fill the blocks\n\t\t\t\tsize_t elements_index = 0;\n\t\t\t\tsize_t bf_index = 0;\n\t\t\t\tfor(size_t isym=0;isym<nsym;isym++)\n\t\t\t\t{\n\t\t\t\t\tsize_t n_elements = nbas_vec[isym] * nbas_vec[isym];\n\t\t\t\t\tEigen::VectorXd dmat_block_vec(n_elements),spin_block_vec(n_elements);\n\t\t\t\t\tEigen::MatrixXd dmat_block,spin_block;\n\t\t\t\t\t//grab the elements we need\n\t\t\t\t\tfor(size_t k=0;k<n_elements;k++)\n\t\t\t\t\t{\n\t\t\t\t\t\tdmat_block_vec(k) = dmt_vec(elements_index+k);\n\t\t\t\t\t\tspin_block_vec(k) = spin_vec(elements_index+k);\n\t\t\t\t\t}\n\t\t\t\t\tdmat_block = reshape(dmat_block_vec,nbas_vec[isym],nbas_vec[isym]);\n\t\t\t\t\tspin_block = reshape(spin_block_vec,nbas_vec[isym],nbas_vec[isym]);\n\t\t\t\t\tdmat.block(bf_index,bf_index,nbas_vec[isym],nbas_vec[isym]) = dmat_block;\n\t\t\t\t\tspin.block(bf_index,bf_index,nbas_vec[isym],nbas_vec[isym]) = spin_block;\n\t\t\t\t\t//update our index counters\n\t\t\t\t\telements_index+=n_elements;\n\t\t\t\t\tbf_index+= nbas_vec[isym];\n\t\t\t\t}\n                \n\t\t\t\t//step 4: desymmetrize\n\t\t\t\tEigen::MatrixXd desym_dmat = desym_mat * dmat * desym_mat.transpose();\n\t\t\t\tEigen::MatrixXd desym_spin = desym_mat * spin * desym_mat.transpose();\n\n\t\t\t\t//step 5: save\n\t\t\t\tEigen::MatrixXd alpha_opdm,beta_opdm;\n\t\t\t\talpha_opdm= 0.5*(desym_dmat+desym_spin);\n\t\t\t\tbeta_opdm = 0.5*(desym_dmat-desym_spin);\n\t\t\t\tto_opencap_ordering(alpha_opdm,bs,get_molcas_ids(bs,filename));\n\t\t\t\tto_opencap_ordering(beta_opdm,bs,get_molcas_ids(bs,filename));\n                alpha_opdms[i][j] = alpha_opdm;\n                beta_opdms[i][j] = beta_opdm;\n\t\t\t}\n\t\t}\n\n    }\n    else\n    {\n\t\t//now lets loop over the matrices\n\t\tfor(long i=0;i<d[0];i++)\n\t\t{\n            if(d[0]!=nstates)\n            opencap_throw(\"Error: Found \" + std::to_string(d[0]) + \" states in RASSI file, but \"\n                          + std::to_string(nstates) + \" states were specified.\");\n\t\t\tfor (long j=0;j<d[1];j++)\n\t\t\t{\n\t\t\t\tEigen::array<long,3> offset = {i,j,0};    //Starting point\n\t\t\t\tEigen::array<long,3> extent = {1,1,1}; //end point\n\t\t\t\tEigen::Tensor<double, 2> dmt_slice = rass_data.slice(offset, extent).reshape(Eigen::array<long,2>{nbas,nbas});\n\t\t\t\tEigen::MatrixXd  dmt_mat =  Tensor_to_Matrix(dmt_slice,nbas,nbas);\n\t\t\t\tEigen::Tensor<double, 2> spin_slice = spin_dens.slice(offset, extent).reshape(Eigen::array<long,2>{nbas,nbas});\n\t\t\t\tEigen::MatrixXd  spin_mat =  Tensor_to_Matrix(dmt_slice,nbas,nbas);\n\t\t\t\tEigen::MatrixXd alpha_opdm,beta_opdm;\n\t\t\t\talpha_opdm= 0.5*(dmt_mat+spin_mat);\n\t\t\t\tbeta_opdm = 0.5*(dmt_mat-spin_mat);\n\t\t\t\tto_opencap_ordering(alpha_opdm,bs,get_molcas_ids(bs,filename));\n\t\t\t\tto_opencap_ordering(beta_opdm,bs,get_molcas_ids(bs,filename));\n                alpha_opdms[i][j] = alpha_opdm;\n                beta_opdms[i][j] = beta_opdm;\n\t\t\t}\n\t\t}\n    }\n\n    std::cout << \"Warning: TDM M-->N is assumed to be conjugate transpose of \"\n    << \"TDM N-->M where M>N\" << std::endl;\n    for (size_t i=0;i<nstates;i++)\n    {\n    \tfor(size_t j=i+1;j<nstates;j++)\n    \t{\n    \t\talpha_opdms[j][i]= alpha_opdms[i][j].adjoint();\n    \t\tbeta_opdms[j][i]= beta_opdms[i][j].adjoint();\n    \t}\n    }\n}\n\nEigen::MatrixXd read_rassi_overlap(std::string filename,BasisSet bs)\n{\n\tEigen::VectorXd overlap_vec;\n\th5pp::File file(filename, h5pp::FilePermission::READONLY);\n\tfile.readDataset(overlap_vec,\"AO_OVERLAP_MATRIX\");\n\tauto nsym = file.readAttribute<long>(\"NSYM\", \"/\");\n\tif(nsym >1)\n\t{\n\t\tEigen::VectorXd desym_vec;\n\t\tfile.readDataset(desym_vec,\"DESYM_MATRIX\");\n\t\tEigen::MatrixXd desym_mat;\n\t\tstd::vector<long> nbas_vec = file.readAttribute<std::vector<long>>(\"NBAS\",\"/\");\n\t\tlong nbas=0;\n\t\tfor(auto num_bas:nbas_vec)\n\t\t\tnbas+=num_bas;\n\t\tdesym_mat = reshape(desym_vec,nbas,nbas);\n\t\tEigen::MatrixXd smat;\n\t\tsmat = Eigen::MatrixXd::Zero(nbas,nbas);\n\t\t//fill the blocks\n\t\tsize_t elements_index = 0;\n\t\tsize_t bf_index = 0;\n\t\tfor(size_t isym=0;isym<nsym;isym++)\n\t\t{\n\t\t\tsize_t n_elements = nbas_vec[isym] * nbas_vec[isym];\n\t\t\tEigen::VectorXd block_vec(n_elements);\n\t\t\tEigen::MatrixXd block_mat;\n\t\t\t//grab the elements we need\n\t\t\tfor(size_t i=0;i<n_elements;i++)\n\t\t\t\tblock_vec(i) = overlap_vec(elements_index+i);\n\t\t\tblock_mat = reshape(block_vec,nbas_vec[isym],nbas_vec[isym]);\n\t\t\tsmat.block(bf_index,bf_index,nbas_vec[isym],nbas_vec[isym]) = block_mat;\n\t\t\t//update our index counters\n\t\t\telements_index+=n_elements;\n\t\t\tbf_index+= nbas_vec[isym];\n\t\t}\n\t\tEigen::MatrixXd desym_overlap = desym_mat * smat * desym_mat.transpose();\n\t\tto_opencap_ordering(desym_overlap,bs,get_molcas_ids(bs,filename));\n\t\treturn desym_overlap;\n\t}\n\telse\n\t{\n\t\tint nbas = sqrt(overlap_vec.size());\n\t\tEigen::MatrixXd smat;\n\t\tsmat = reshape(overlap_vec,nbas,nbas);\n\t\tto_opencap_ordering(smat,bs,get_molcas_ids(bs,filename));\n\t\treturn smat;\n\t}\n}\n\nEigen::MatrixXd read_rotation_matrix(size_t nstates, std::ifstream &is)\n{\n\tEigen::MatrixXd rotation_matrix(nstates,nstates);\n\trotation_matrix = Eigen::MatrixXd::Zero(nstates,nstates);\n\tstd::string line, rest;\n\tsize_t num_groups = nstates%5==0 ? nstates/5 : nstates/5+1;\n\tfor (size_t i=1;i<=num_groups;i++)\n\t{\n\t\tstd::getline(is,line);\n        if(i>1)\n            std::getline(is,line);\n\t\tfor (size_t j=1;j<=nstates;j++)\n\t\t{\n\t\t\tstd::getline(is,line);\n\t\t\tstd::vector<std::string> tokens = split(line,' ');\n\t\t\tsize_t row_idx = std::stoul(tokens[0]);\n\t\t\tfor(size_t k=1;k<tokens.size();k++)\n\t\t\t{\n\t\t\t\tsize_t col_idx = k-1+(i-1)*5;\n\t\t\t\tif(col_idx>=rotation_matrix.cols() || row_idx-1 >= rotation_matrix.rows())\n\t\t\t\t\topencap_throw(\"Error: State index of out bounds. There is a problem with the OpenMolcas output file. Exiting...\");\n\t\t\t\trotation_matrix(row_idx-1,col_idx)=std::stod(tokens[k]);\n\t\t\t}\n\t\t}\n\t}\n\treturn rotation_matrix;\n}\n\nEigen::MatrixXd read_mscaspt2_heff(size_t nstates, std::string filename, Eigen::MatrixXd &rotation_matrix)\n{\n\tEigen::MatrixXd ZERO_ORDER_H(nstates,nstates);\n\tZERO_ORDER_H= Eigen::MatrixXd::Zero(nstates,nstates);\n\tstd::ifstream is(filename);\n\tif (is.good())\n\t{\n\t\tstd::string line, rest;\n\t\tstd::getline(is,line);\n\t\twhile (line.find(\"Number of CI roots used\")== std::string::npos && is.peek()!=EOF)\n\t\t\tstd::getline(is,line);\n\t\tsize_t num_states = stoi(split(line,' ').back());\n\t\tif (num_states!=nstates)\n\t\t\topencap_throw(\"Error: \"+std::to_string(num_states)+ \" roots were found in the OpenMolcas \"\n\t\t\t\t\t\"output file, but \" + std::to_string(nstates) +\" states were specified in the input. \"\n\t\t\t\t\t\t\t\"Exiting...\");\n\t\twhile (line.find(\"MULTI-STATE CASPT2 SECTION\")== std::string::npos && is.peek()!=EOF)\n\t\t{\n\t\t\tstd::getline(is,line);\n\t\t\tif (line.find(\"H0 eigenvectors:\")!= std::string::npos)\n\t\t\t\trotation_matrix = read_rotation_matrix(nstates,is);\n\t\t}\n\t\tif (is.peek()==EOF)\n\t\t\topencap_throw(\"Error: Reached end of file before MULTI-STATE CASPT2 SECTION.\");\n\t\t//get diagonal shift\n\t\tfor (size_t i=1;i<=3;i++)\n\t\t\tstd::getline(is,line);\n        double E_shift = 0.0;\n        if(line.find(\"Output diagonal\")!=std::string::npos)\n        {\n            std::vector<std::string> split_line = split(line,' ');\n            E_shift = std::stod(split_line[split_line.size()-1]);\n            for(size_t i=1;i<=2;i++)\n                std::getline(is,line);\n        }\n\t\tsize_t num_groups = nstates%5==0 ? nstates/5 : nstates/5+1;\n\t\tfor (size_t i=1;i<=num_groups;i++)\n\t\t{\n\t\t\tfor (size_t j=1;j<=2;j++)\n\t\t\t\tstd::getline(is,line);\n\t\t\t//now time to start reading in the matrix elements\n\t\t\tsize_t states_in_group = nstates - (i-1)*5;\n\t\t\tfor (size_t j=1;j<=states_in_group;j++)\n\t\t\t{\n\t\t\t\tstd::getline(is,line);\n\t\t\t\tstd::vector<std::string> tokens = split(line,' ');\n\t\t\t\tsize_t row_idx = std::stoul(tokens[0]);\n\t\t\t\tfor(size_t k=1;k<tokens.size();k++)\n\t\t\t\t{\n\t\t\t\t\tsize_t col_idx = k-1+(i-1)*5;\n\t\t\t\t\tif(col_idx>=ZERO_ORDER_H.cols() || row_idx-1 >= ZERO_ORDER_H.rows())\n\t\t\t\t\t\topencap_throw(\"Error: State index of out bounds. There is a problem with the OpenMolcas output file. Exiting...\");\n\t\t\t\t\tZERO_ORDER_H(row_idx-1,col_idx)=std::stod(tokens[k]);\n\t\t\t\t\tZERO_ORDER_H(col_idx,row_idx-1)=std::stod(tokens[k]);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tfor (size_t i=0;i<nstates;i++)\n\t\t\tZERO_ORDER_H(i,i)+=E_shift;\n\t}\n\telse\n\t{\n    \topencap_throw(\"Error: I couldn't read:\" + filename);\n\t}\n\treturn ZERO_ORDER_H;\n}\n\nEigen::MatrixXd read_nevpt2_heff(size_t nstates, std::string filename, std::string method)\n{\n\tstd::string line_to_find;\n\tif(compare_strings(method,\"pc-nevpt2\"))\n\t\tline_to_find = \"Zero + second order effective Hamiltonian (PC)\";\n\telse if(compare_strings(method,\"sc-nevpt2\"))\n\t\tline_to_find = \"Zero + second order Effective Hamiltonian (SC)\";\n\telse\n\t\topencap_throw(\"Either pc-nevpt2 or sc-nevpt2 should be selected.\");\n\tEigen::MatrixXd ZERO_ORDER_H(nstates,nstates);\n\tZERO_ORDER_H= Eigen::MatrixXd::Zero(nstates,nstates);\n\tstd::ifstream is(filename);\n\tif (is.good())\n\t{\n\t\tstd::string line, rest;\n\t\tstd::getline(is,line);\n\t\twhile (line.find(line_to_find)== std::string::npos && is.peek()!=EOF)\n\t\t\tstd::getline(is,line);\n\t\tif(is.peek()==EOF)\n\t\t\topencap_throw(\"Error: Unable to find QD-NEVPT2 effective Hamiltonian.\");\n\t\tstd::getline(is,line);\n\t\tstd::getline(is,line);\n\t\tsize_t num_groups = nstates%5==0 ? nstates/5 : nstates/5+1;\n\t\tfor (size_t i=1;i<=num_groups;i++)\n\t\t{\n\t\t\tstd::getline(is,line);\n\t\t\tfor (size_t j=1;j<=nstates;j++)\n\t\t\t{\n\t\t\t\tstd::getline(is,line);\n\t\t\t\tstd::vector<std::string> tokens = split(line,' ');\n\t\t\t\tsize_t row_idx = std::stoul(tokens[0]);\n\t\t\t\tfor(size_t k=1;k<tokens.size();k++)\n\t\t\t\t{\n\t\t\t\t\tsize_t col_idx = k-1+(i-1)*5;\n\t\t\t\t\tif(col_idx>=ZERO_ORDER_H.cols() || row_idx-1 >= ZERO_ORDER_H.rows())\n\t\t\t\t\t\topencap_throw(\"Error: State index of out bounds. There is a problem with the OpenMolcas output file. Exiting...\");\n\t\t\t\t\tZERO_ORDER_H(row_idx-1,col_idx)=std::stod(tokens[k]);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\telse\n\t{\n    \topencap_throw(\"Error: I couldn't read:\" + filename);\n\t}\n\treturn ZERO_ORDER_H;\n}\n\n\nstd::vector<Atom> read_geometry_from_rassi(std::string filename)\n{\n\th5pp::File file(filename, h5pp::FilePermission::READONLY);\n\tauto nsym = file.readAttribute<long>(\"NSYM\", \"/\");\n\tstd::string atom_nums_tag,coords_tag;\n\tif (nsym>1)\n\t{\n\t\tatom_nums_tag=\"DESYM_CENTER_ATNUMS\";\n\t\tcoords_tag = \"DESYM_CENTER_COORDINATES\";\n\t}\n\telse\n\t{\n\t\tatom_nums_tag=\"CENTER_ATNUMS\";\n\t\tcoords_tag = \"CENTER_COORDINATES\";\n\t}\n\tstd::vector<Atom> atoms;\n\tstd::vector<long> atomic_nums;\n\tEigen::MatrixXd coords_mat;\n\tfile.readDataset(atomic_nums,atom_nums_tag);\n\tfile.readDataset(coords_mat,coords_tag);\n\tfor(size_t i=0;i<coords_mat.rows();i++)\n\t\tatoms.push_back(Atom(atomic_nums[i],coords_mat(i,0),coords_mat(i,1),coords_mat(i,2)));\n\treturn atoms;\n}\n\nBasisSet read_basis_from_rassi(std::string filename,std::vector<Atom> atoms)\n{\n\th5pp::File file(filename, h5pp::FilePermission::READONLY);\n\tEigen::Matrix<long,Eigen::Dynamic,Eigen::Dynamic> prim_ids,basis_ids;\n\tEigen::MatrixXd prims;\n\tauto nsym = file.readAttribute<long>(\"NSYM\", \"/\");\n\tfile.readDataset(prims,\"PRIMITIVES\");\n\tfile.readDataset(prim_ids,\"PRIMITIVE_IDS\");\n\tstd::string bf_ids_tag;\n\tif(nsym>1)\n\t\tbf_ids_tag=\"DESYM_BASIS_FUNCTION_IDS\";\n\telse\n\t\tbf_ids_tag =\"BASIS_FUNCTION_IDS\";\n\tfile.readDataset(basis_ids,bf_ids_tag);\n\tBasisSet bs;\n\tfor(auto atm:atoms)\n\t\tbs.centers.push_back(atm.coords);\n\tfor(size_t i=0;i<basis_ids.rows();i++)\n\t{\n\t\tlong ctr = basis_ids(i,0);\n\t\tlong shell_num = basis_ids(i,1);\n\t\tint l = basis_ids(i,2);\n\t\tshell_id id(ctr,shell_num,l);\n\t\tint bs_idx = bs.get_index_of_shell_id(id);\n\t\tif (bs_idx==-1)\n\t\t{\n\t\t\tShell new_shell(l,bs.centers[ctr-1]);\n\t\t\tnew_shell.l=abs(l);\n\t\t\tif(l<0 && abs(l)>1)\n\t\t\t\tnew_shell.pure=false;\n\t\t\tbs.add_shell(new_shell);\n\t\t}\n\t}\n\tfor(size_t i=0;i<prim_ids.rows();i++)\n\t{\n\t\tlong ctr = prim_ids(i,0);\n\t\tint l = prim_ids(i,1);\n\t\tlong shell_num = prim_ids(i,2);\n\t\tdouble exp = prims(i,0);\n\t\tdouble coeff = prims(i,1);\n\t\tshell_id id(ctr,shell_num,l);\n\t\tint bs_idx = bs.get_index_of_shell_id(id);\n\t\tif (coeff!=0)\n\t\t\tbs.basis[bs_idx].add_primitive(exp,coeff);\n\t}\n\tbs.normalize();\n\treturn bs;\n}\n", "meta": {"hexsha": "ba758d9409ab9d08451bf08e681336501fed0ec0", "size": 16358, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "opencap/src/molcas_interface.cpp", "max_stars_repo_name": "SoubhikM/opencap", "max_stars_repo_head_hexsha": "08706ea07e576c96eed32dc224070201781981b2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "opencap/src/molcas_interface.cpp", "max_issues_repo_name": "SoubhikM/opencap", "max_issues_repo_head_hexsha": "08706ea07e576c96eed32dc224070201781981b2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "opencap/src/molcas_interface.cpp", "max_forks_repo_name": "SoubhikM/opencap", "max_forks_repo_head_hexsha": "08706ea07e576c96eed32dc224070201781981b2", "max_forks_repo_licenses": ["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.4069264069, "max_line_length": 122, "alphanum_fraction": 0.6849859396, "num_tokens": 4878, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7090191337850932, "lm_q2_score": 0.47268347662043286, "lm_q1q2_score": 0.33514162914794565}}
{"text": "/**\n* This file is part of ORB-SLAM3\n*\n* Copyright (C) 2017-2021 Carlos Campos, Richard Elvira, Juan J. Gómez Rodríguez, José M.M. Montiel and Juan D. Tardós, University of Zaragoza.\n* Copyright (C) 2014-2016 Raúl Mur-Artal, José M.M. Montiel and Juan D. Tardós, University of Zaragoza.\n*\n* ORB-SLAM3 is free software: you can redistribute it and/or modify it under the terms of the GNU General Public\n* License as published by the Free Software Foundation, either version 3 of the License, or\n* (at your option) any later version.\n*\n* ORB-SLAM3 is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even\n* the implied warranty of 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 with ORB-SLAM3.\n* If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#include \"KannalaBrandt8.h\"\n\n#include <boost/serialization/export.hpp>\n\n//BOOST_CLASS_EXPORT_IMPLEMENT(ORB_SLAM3::KannalaBrandt8)\n\nnamespace ORB_SLAM3 {\n//BOOST_CLASS_EXPORT_GUID(KannalaBrandt8, \"KannalaBrandt8\")\n\n    cv::Point2f KannalaBrandt8::project(const cv::Point3f &p3D) {\n        const float x2_plus_y2 = p3D.x * p3D.x + p3D.y * p3D.y;\n        const float theta = atan2f(sqrtf(x2_plus_y2), p3D.z);\n        const float psi = atan2f(p3D.y, p3D.x);\n\n        const float theta2 = theta * theta;\n        const float theta3 = theta * theta2;\n        const float theta5 = theta3 * theta2;\n        const float theta7 = theta5 * theta2;\n        const float theta9 = theta7 * theta2;\n        const float r = theta + mvParameters[4] * theta3 + mvParameters[5] * theta5\n                        + mvParameters[6] * theta7 + mvParameters[7] * theta9;\n\n        return cv::Point2f(mvParameters[0] * r * cos(psi) + mvParameters[2],\n                           mvParameters[1] * r * sin(psi) + mvParameters[3]);\n\n    }\n\n    Eigen::Vector2d KannalaBrandt8::project(const Eigen::Vector3d &v3D) {\n        const double x2_plus_y2 = v3D[0] * v3D[0] + v3D[1] * v3D[1];\n        const double theta = atan2f(sqrtf(x2_plus_y2), v3D[2]);\n        const double psi = atan2f(v3D[1], v3D[0]);\n\n        const double theta2 = theta * theta;\n        const double theta3 = theta * theta2;\n        const double theta5 = theta3 * theta2;\n        const double theta7 = theta5 * theta2;\n        const double theta9 = theta7 * theta2;\n        const double r = theta + mvParameters[4] * theta3 + mvParameters[5] * theta5\n                        + mvParameters[6] * theta7 + mvParameters[7] * theta9;\n\n        Eigen::Vector2d res;\n        res[0] = mvParameters[0] * r * cos(psi) + mvParameters[2];\n        res[1] = mvParameters[1] * r * sin(psi) + mvParameters[3];\n\n        return res;\n\n    }\n\n    Eigen::Vector2f KannalaBrandt8::project(const Eigen::Vector3f &v3D) {\n        const float x2_plus_y2 = v3D[0] * v3D[0] + v3D[1] * v3D[1];\n        const float theta = atan2f(sqrtf(x2_plus_y2), v3D[2]);\n        const float psi = atan2f(v3D[1], v3D[0]);\n\n        const float theta2 = theta * theta;\n        const float theta3 = theta * theta2;\n        const float theta5 = theta3 * theta2;\n        const float theta7 = theta5 * theta2;\n        const float theta9 = theta7 * theta2;\n        const float r = theta + mvParameters[4] * theta3 + mvParameters[5] * theta5\n                         + mvParameters[6] * theta7 + mvParameters[7] * theta9;\n\n        Eigen::Vector2f res;\n        res[0] = mvParameters[0] * r * cos(psi) + mvParameters[2];\n        res[1] = mvParameters[1] * r * sin(psi) + mvParameters[3];\n\n        return res;\n\n        /*cv::Point2f cvres = this->project(cv::Point3f(v3D[0],v3D[1],v3D[2]));\n\n        Eigen::Vector2d res;\n        res[0] = cvres.x;\n        res[1] = cvres.y;\n\n        return res;*/\n    }\n\n    Eigen::Vector2f KannalaBrandt8::projectMat(const cv::Point3f &p3D) {\n        cv::Point2f point = this->project(p3D);\n        return Eigen::Vector2f(point.x, point.y);\n    }\n\n    float KannalaBrandt8::uncertainty2(const Eigen::Matrix<double,2,1> &p2D)\n    {\n        /*Eigen::Matrix<double,2,1> c;\n        c << mvParameters[2], mvParameters[3];\n        if ((p2D-c).squaredNorm()>57600) // 240*240 (256)\n            return 100.f;\n        else\n            return 1.0f;*/\n        return 1.f;\n    }\n\n    Eigen::Vector3f KannalaBrandt8::unprojectEig(const cv::Point2f &p2D) {\n        cv::Point3f ray = this->unproject(p2D);\n        return Eigen::Vector3f(ray.x, ray.y, ray.z);\n    }\n\n    cv::Point3f KannalaBrandt8::unproject(const cv::Point2f &p2D) {\n        //Use Newthon method to solve for theta with good precision (err ~ e-6)\n        cv::Point2f pw((p2D.x - mvParameters[2]) / mvParameters[0], (p2D.y - mvParameters[3]) / mvParameters[1]);\n        float scale = 1.f;\n        float theta_d = sqrtf(pw.x * pw.x + pw.y * pw.y);\n        theta_d = fminf(fmaxf(-CV_PI / 2.f, theta_d), CV_PI / 2.f);\n\n        if (theta_d > 1e-8) {\n            //Compensate distortion iteratively\n            float theta = theta_d;\n\n            for (int j = 0; j < 10; j++) {\n                float theta2 = theta * theta, theta4 = theta2 * theta2, theta6 = theta4 * theta2, theta8 =\n                        theta4 * theta4;\n                float k0_theta2 = mvParameters[4] * theta2, k1_theta4 = mvParameters[5] * theta4;\n                float k2_theta6 = mvParameters[6] * theta6, k3_theta8 = mvParameters[7] * theta8;\n                float theta_fix = (theta * (1 + k0_theta2 + k1_theta4 + k2_theta6 + k3_theta8) - theta_d) /\n                                  (1 + 3 * k0_theta2 + 5 * k1_theta4 + 7 * k2_theta6 + 9 * k3_theta8);\n                theta = theta - theta_fix;\n                if (fabsf(theta_fix) < precision)\n                    break;\n            }\n            //scale = theta - theta_d;\n            scale = std::tan(theta) / theta_d;\n        }\n\n        return cv::Point3f(pw.x * scale, pw.y * scale, 1.f);\n    }\n\n    Eigen::Matrix<double, 2, 3> KannalaBrandt8::projectJac(const Eigen::Vector3d &v3D) {\n        double x2 = v3D[0] * v3D[0], y2 = v3D[1] * v3D[1], z2 = v3D[2] * v3D[2];\n        double r2 = x2 + y2;\n        double r = sqrt(r2);\n        double r3 = r2 * r;\n        double theta = atan2(r, v3D[2]);\n\n        double theta2 = theta * theta, theta3 = theta2 * theta;\n        double theta4 = theta2 * theta2, theta5 = theta4 * theta;\n        double theta6 = theta2 * theta4, theta7 = theta6 * theta;\n        double theta8 = theta4 * theta4, theta9 = theta8 * theta;\n\n        double f = theta + theta3 * mvParameters[4] + theta5 * mvParameters[5] + theta7 * mvParameters[6] +\n                  theta9 * mvParameters[7];\n        double fd = 1 + 3 * mvParameters[4] * theta2 + 5 * mvParameters[5] * theta4 + 7 * mvParameters[6] * theta6 +\n                   9 * mvParameters[7] * theta8;\n\n        Eigen::Matrix<double, 2, 3> JacGood;\n        JacGood(0, 0) = mvParameters[0] * (fd * v3D[2] * x2 / (r2 * (r2 + z2)) + f * y2 / r3);\n        JacGood(1, 0) =\n                mvParameters[1] * (fd * v3D[2] * v3D[1] * v3D[0] / (r2 * (r2 + z2)) - f * v3D[1] * v3D[0] / r3);\n\n        JacGood(0, 1) =\n                mvParameters[0] * (fd * v3D[2] * v3D[1] * v3D[0] / (r2 * (r2 + z2)) - f * v3D[1] * v3D[0] / r3);\n        JacGood(1, 1) = mvParameters[1] * (fd * v3D[2] * y2 / (r2 * (r2 + z2)) + f * x2 / r3);\n\n        JacGood(0, 2) = -mvParameters[0] * fd * v3D[0] / (r2 + z2);\n        JacGood(1, 2) = -mvParameters[1] * fd * v3D[1] / (r2 + z2);\n\n        return JacGood;\n    }\n\n    bool KannalaBrandt8::ReconstructWithTwoViews(const std::vector<cv::KeyPoint>& vKeys1, const std::vector<cv::KeyPoint>& vKeys2, const std::vector<int> &vMatches12,\n                                          Sophus::SE3f &T21, std::vector<cv::Point3f> &vP3D, std::vector<bool> &vbTriangulated){\n        if(!tvr){\n            Eigen::Matrix3f K = this->toK_();\n            tvr = new TwoViewReconstruction(K);\n        }\n\n        //Correct FishEye distortion\n        std::vector<cv::KeyPoint> vKeysUn1 = vKeys1, vKeysUn2 = vKeys2;\n        std::vector<cv::Point2f> vPts1(vKeys1.size()), vPts2(vKeys2.size());\n\n        for(size_t i = 0; i < vKeys1.size(); i++) vPts1[i] = vKeys1[i].pt;\n        for(size_t i = 0; i < vKeys2.size(); i++) vPts2[i] = vKeys2[i].pt;\n\n        cv::Mat D = (cv::Mat_<float>(4,1) << mvParameters[4], mvParameters[5], mvParameters[6], mvParameters[7]);\n        cv::Mat R = cv::Mat::eye(3,3,CV_32F);\n        cv::Mat K = this->toK();\n        cv::fisheye::undistortPoints(vPts1,vPts1,K,D,R,K);\n        cv::fisheye::undistortPoints(vPts2,vPts2,K,D,R,K);\n\n        for(size_t i = 0; i < vKeys1.size(); i++) vKeysUn1[i].pt = vPts1[i];\n        for(size_t i = 0; i < vKeys2.size(); i++) vKeysUn2[i].pt = vPts2[i];\n\n        return tvr->Reconstruct(vKeysUn1,vKeysUn2,vMatches12,T21,vP3D,vbTriangulated);\n    }\n\n\n    cv::Mat KannalaBrandt8::toK() {\n        cv::Mat K = (cv::Mat_<float>(3, 3)\n                << mvParameters[0], 0.f, mvParameters[2], 0.f, mvParameters[1], mvParameters[3], 0.f, 0.f, 1.f);\n        return K;\n    }\n    Eigen::Matrix3f KannalaBrandt8::toK_() {\n        Eigen::Matrix3f K;\n        K << mvParameters[0], 0.f, mvParameters[2], 0.f, mvParameters[1], mvParameters[3], 0.f, 0.f, 1.f;\n        return K;\n    }\n\n\n    bool KannalaBrandt8::epipolarConstrain(GeometricCamera* pCamera2, const cv::KeyPoint &kp1, const cv::KeyPoint &kp2,\n                                           const Eigen::Matrix3f& R12, const Eigen::Vector3f& t12, const float sigmaLevel, const float unc) {\n        Eigen::Vector3f p3D;\n        return this->TriangulateMatches(pCamera2,kp1,kp2,R12,t12,sigmaLevel,unc,p3D) > 0.0001f;\n    }\n\n    bool KannalaBrandt8::matchAndtriangulate(const cv::KeyPoint& kp1, const cv::KeyPoint& kp2, GeometricCamera* pOther,\n                                             Sophus::SE3f& Tcw1, Sophus::SE3f& Tcw2,\n                                             const float sigmaLevel1, const float sigmaLevel2,\n                                             Eigen::Vector3f& x3Dtriangulated){\n        Eigen::Matrix<float,3,4> eigTcw1 = Tcw1.matrix3x4();\n        Eigen::Matrix3f Rcw1 = eigTcw1.block<3,3>(0,0);\n        Eigen::Matrix3f Rwc1 = Rcw1.transpose();\n        Eigen::Matrix<float,3,4> eigTcw2 = Tcw2.matrix3x4();\n        Eigen::Matrix3f Rcw2 = eigTcw2.block<3,3>(0,0);\n        Eigen::Matrix3f Rwc2 = Rcw2.transpose();\n\n        cv::Point3f ray1c = this->unproject(kp1.pt);\n        cv::Point3f ray2c = pOther->unproject(kp2.pt);\n\n        Eigen::Vector3f r1(ray1c.x, ray1c.y, ray1c.z);\n        Eigen::Vector3f r2(ray2c.x, ray2c.y, ray2c.z);\n\n        //Check parallax between rays\n        Eigen::Vector3f ray1 = Rwc1 * r1;\n        Eigen::Vector3f ray2 = Rwc2 * r2;\n\n        const float cosParallaxRays = ray1.dot(ray2)/(ray1.norm() * ray2.norm());\n\n        //If parallax is lower than 0.9998, reject this match\n        if(cosParallaxRays > 0.9998){\n            return false;\n        }\n\n        //Parallax is good, so we try to triangulate\n        cv::Point2f p11,p22;\n\n        p11.x = ray1c.x;\n        p11.y = ray1c.y;\n\n        p22.x = ray2c.x;\n        p22.y = ray2c.y;\n\n        Eigen::Vector3f x3D;\n\n        Triangulate(p11,p22,eigTcw1,eigTcw2,x3D);\n\n        //Check triangulation in front of cameras\n        float z1 = Rcw1.row(2).dot(x3D)+Tcw1.translation()(2);\n        if(z1<=0){  //Point is not in front of the first camera\n            return false;\n        }\n\n\n        float z2 = Rcw2.row(2).dot(x3D)+Tcw2.translation()(2);\n        if(z2<=0){ //Point is not in front of the first camera\n            return false;\n        }\n\n        //Check reprojection error in first keyframe\n        //  -Transform point into camera reference system\n        Eigen::Vector3f x3D1 = Rcw1 * x3D + Tcw1.translation();\n        Eigen::Vector2f uv1 = this->project(x3D1);\n\n        float errX1 = uv1(0) - kp1.pt.x;\n        float errY1 = uv1(1) - kp1.pt.y;\n\n        if((errX1*errX1+errY1*errY1)>5.991*sigmaLevel1){   //Reprojection error is high\n            return false;\n        }\n\n        //Check reprojection error in second keyframe;\n        //  -Transform point into camera reference system\n        Eigen::Vector3f x3D2 = Rcw2 * x3D + Tcw2.translation(); // avoid using q\n        Eigen::Vector2f uv2 = pOther->project(x3D2);\n\n        float errX2 = uv2(0) - kp2.pt.x;\n        float errY2 = uv2(1) - kp2.pt.y;\n\n        if((errX2*errX2+errY2*errY2)>5.991*sigmaLevel2){   //Reprojection error is high\n            return false;\n        }\n\n        //Since parallax is big enough and reprojection errors are low, this pair of points\n        //can be considered as a match\n        x3Dtriangulated = x3D;\n\n        return true;\n    }\n\n    float KannalaBrandt8::TriangulateMatches(GeometricCamera *pCamera2, const cv::KeyPoint &kp1, const cv::KeyPoint &kp2, const Eigen::Matrix3f& R12, const Eigen::Vector3f& t12, const float sigmaLevel, const float unc, Eigen::Vector3f& p3D) {\n\n        Eigen::Vector3f r1 = this->unprojectEig(kp1.pt);\n        Eigen::Vector3f r2 = pCamera2->unprojectEig(kp2.pt);\n\n        //Check parallax\n        Eigen::Vector3f r21 = R12 * r2;\n\n        const float cosParallaxRays = r1.dot(r21)/(r1.norm() *r21.norm());\n\n        if(cosParallaxRays > 0.9998){\n            return -1;\n        }\n\n        //Parallax is good, so we try to triangulate\n        cv::Point2f p11,p22;\n\n        p11.x = r1[0];\n        p11.y = r1[1];\n\n        p22.x = r2[0];\n        p22.y = r2[1];\n\n        Eigen::Vector3f x3D;\n        Eigen::Matrix<float,3,4> Tcw1;\n        Tcw1 << Eigen::Matrix3f::Identity(), Eigen::Vector3f::Zero();\n\n        Eigen::Matrix<float,3,4> Tcw2;\n\n        Eigen::Matrix3f R21 = R12.transpose();\n        Tcw2 << R21, -R21 * t12;\n\n\n        Triangulate(p11,p22,Tcw1,Tcw2,x3D);\n        // cv::Mat x3Dt = x3D.t();\n\n        float z1 = x3D(2);\n        if(z1 <= 0){\n            return -2;\n        }\n\n        float z2 = R21.row(2).dot(x3D)+Tcw2(2,3);\n        if(z2<=0){\n            return -3;\n        }\n\n        //Check reprojection error\n        Eigen::Vector2f uv1 = this->project(x3D);\n\n        float errX1 = uv1(0) - kp1.pt.x;\n        float errY1 = uv1(1) - kp1.pt.y;\n\n        if((errX1*errX1+errY1*errY1)>5.991 * sigmaLevel){   //Reprojection error is high\n            return -4;\n        }\n\n        Eigen::Vector3f x3D2 = R21 * x3D + Tcw2.col(3);\n        Eigen::Vector2f uv2 = pCamera2->project(x3D2);\n\n        float errX2 = uv2(0) - kp2.pt.x;\n        float errY2 = uv2(1) - kp2.pt.y;\n\n        if((errX2*errX2+errY2*errY2)>5.991 * unc){   //Reprojection error is high\n            return -5;\n        }\n\n        p3D = x3D;\n\n        return z1;\n    }\n\n    std::ostream & operator<<(std::ostream &os, const KannalaBrandt8 &kb) {\n        os << kb.mvParameters[0] << \" \" << kb.mvParameters[1] << \" \" << kb.mvParameters[2] << \" \" << kb.mvParameters[3] << \" \"\n           << kb.mvParameters[4] << \" \" << kb.mvParameters[5] << \" \" << kb.mvParameters[6] << \" \" << kb.mvParameters[7];\n        return os;\n    }\n\n    std::istream & operator>>(std::istream &is, KannalaBrandt8 &kb) {\n        float nextParam;\n        for(size_t i = 0; i < 8; i++){\n            assert(is.good());  //Make sure the input stream is good\n            is >> nextParam;\n            kb.mvParameters[i] = nextParam;\n\n        }\n        return is;\n    }\n\n    void KannalaBrandt8::Triangulate(const cv::Point2f &p1, const cv::Point2f &p2, const Eigen::Matrix<float,3,4> &Tcw1,\n                                     const Eigen::Matrix<float,3,4> &Tcw2, Eigen::Vector3f &x3D)\n    {\n        Eigen::Matrix<float,4,4> A;\n        A.row(0) = p1.x*Tcw1.row(2)-Tcw1.row(0);\n        A.row(1) = p1.y*Tcw1.row(2)-Tcw1.row(1);\n        A.row(2) = p2.x*Tcw2.row(2)-Tcw2.row(0);\n        A.row(3) = p2.y*Tcw2.row(2)-Tcw2.row(1);\n\n        Eigen::JacobiSVD<Eigen::Matrix4f> svd(A, Eigen::ComputeFullV);\n        Eigen::Vector4f x3Dh = svd.matrixV().col(3);\n        x3D = x3Dh.head(3)/x3Dh(3);\n    }\n\n    bool KannalaBrandt8::IsEqual(GeometricCamera* pCam)\n    {\n        if(pCam->GetType() != GeometricCamera::CAM_FISHEYE)\n            return false;\n\n        KannalaBrandt8* pKBCam = (KannalaBrandt8*) pCam;\n\n        if(abs(precision - pKBCam->GetPrecision()) > 1e-6)\n            return false;\n\n        if(size() != pKBCam->size())\n            return false;\n\n        bool is_same_camera = true;\n        for(size_t i=0; i<size(); ++i)\n        {\n            if(abs(mvParameters[i] - pKBCam->getParameter(i)) > 1e-6)\n            {\n                is_same_camera = false;\n                break;\n            }\n        }\n        return is_same_camera;\n    }\n\n}\n", "meta": {"hexsha": "e5d067defcfb84137616e4f667daffd41880d71c", "size": 16465, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "sensing/slam/vslam/ORB_SLAM3/src/CameraModels/KannalaBrandt8.cpp", "max_stars_repo_name": "robin-shaun/xtdrone", "max_stars_repo_head_hexsha": "f255d001e2b83e2dd54e8086f881c58a4efd53ee", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "sensing/slam/vslam/ORB_SLAM3/src/CameraModels/KannalaBrandt8.cpp", "max_issues_repo_name": "robin-shaun/xtdrone", "max_issues_repo_head_hexsha": "f255d001e2b83e2dd54e8086f881c58a4efd53ee", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "sensing/slam/vslam/ORB_SLAM3/src/CameraModels/KannalaBrandt8.cpp", "max_forks_repo_name": "robin-shaun/xtdrone", "max_forks_repo_head_hexsha": "f255d001e2b83e2dd54e8086f881c58a4efd53ee", "max_forks_repo_licenses": ["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.9377880184, "max_line_length": 242, "alphanum_fraction": 0.5663528697, "num_tokens": 5386, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7090191337850932, "lm_q2_score": 0.47268347662043286, "lm_q1q2_score": 0.33514162914794565}}
{"text": "#ifndef DESCARTES_LIGHT_SOLVERS_BGL_IMPL_BGL_DIJKSTRA_SOLVER_HPP\n#define DESCARTES_LIGHT_SOLVERS_BGL_IMPL_BGL_DIJKSTRA_SOLVER_HPP\n\n#include <descartes_light/bgl/bgl_dijkstra_solver.h>\n#include <descartes_light/bgl/impl/event_visitors.hpp>\n\n#include <descartes_light/descartes_macros.h>\nDESCARTES_IGNORE_WARNINGS_PUSH\n#include <boost/graph/dijkstra_shortest_paths.hpp>\nDESCARTES_IGNORE_WARNINGS_POP\n\nnamespace descartes_light\n{\ntemplate <typename FloatType, typename Visitors>\nstatic VertexDesc<FloatType> solveDijkstra(BGLGraph<FloatType>& graph,\n                                           std::vector<VertexDesc<FloatType>>& predecessors,\n                                           const VertexDesc<FloatType>& source,\n                                           const Visitors& event_visitors,\n                                           const std::vector<std::vector<VertexDesc<FloatType>>>& ladder_rungs)\n{\n  // Internal properties\n  auto index_prop_map = boost::get(boost::vertex_index, graph);\n  auto weight_prop_map = boost::get(boost::edge_weight, graph);\n  auto color_prop_map = boost::get(&Vertex<FloatType>::color, graph);\n  auto distance_prop_map = boost::get(&Vertex<FloatType>::distance, graph);\n\n  predecessors.resize(boost::num_vertices(graph), std::numeric_limits<std::size_t>::max());\n\n  typedef typename boost::property_map<BGLGraph<FloatType>, boost::vertex_index_t>::type IndexMap;\n  typedef boost::iterator_property_map<typename std::vector<VertexDesc<FloatType>>::iterator, IndexMap> PredecessorMap;\n  PredecessorMap predecessor_it_map = boost::make_iterator_property_map(predecessors.begin(), index_prop_map);\n\n  auto visitor = boost::make_dijkstra_visitor(event_visitors);\n\n  // Perform the search\n  try\n  {\n    boost::dijkstra_shortest_paths(graph,\n                                   source,\n                                   predecessor_it_map,\n                                   distance_prop_map,\n                                   weight_prop_map,\n                                   index_prop_map,\n                                   std::less<>(),\n                                   std::plus<>(),\n                                   std::numeric_limits<FloatType>::max(),\n                                   static_cast<FloatType>(0.0),\n                                   visitor,\n                                   color_prop_map);\n\n    // In the case that the visitor does not throw the target vertex descriptor, find the lowest cost vertex in last\n    // rung of the ladder graph\n    auto target = std::min_element(ladder_rungs.back().begin(),\n                                   ladder_rungs.back().end(),\n                                   [&](const VertexDesc<FloatType>& a, const VertexDesc<FloatType>& b) {\n                                     return graph[a].distance < graph[b].distance;\n                                   });\n\n    // Check that the identified lowest cost vertex is valid and has a cost less than inf\n    if (target != ladder_rungs.back().end() && graph[*target].distance < std::numeric_limits<FloatType>::max())\n      throw *target;\n  }\n  catch (const VertexDesc<FloatType>& target)\n  {\n    return target;\n  }\n\n  // If the visitor never threw the vertex descriptor, there was an issue with the search\n  throw std::runtime_error(\"Search failed to encounter vertex associated with the last waypoint in the trajectory\");\n}\n\ntemplate <typename FloatType, typename Visitors>\nBGLDijkstraSVSESolver<FloatType, Visitors>::BGLDijkstraSVSESolver(Visitors event_visitors, unsigned num_threads)\n  : BGLSolverBaseSVSE<FloatType>(num_threads), event_visitors_(std::move(event_visitors))\n{\n}\n\ntemplate <typename FloatType, typename Visitors>\nSearchResult<FloatType> BGLDijkstraSVSESolver<FloatType, Visitors>::search()\n{\n  // Convenience aliases\n  auto& graph_ = BGLSolverBase<FloatType>::graph_;\n  const auto& source_ = BGLSolverBase<FloatType>::source_;\n  auto& predecessors_ = BGLSolverBase<FloatType>::predecessors_;\n  const auto& ladder_rungs_ = BGLSolverBase<FloatType>::ladder_rungs_;\n\n  VertexDesc<FloatType> target =\n      solveDijkstra<FloatType, Visitors>(graph_, predecessors_, source_, event_visitors_, ladder_rungs_);\n\n  SearchResult<FloatType> result;\n\n  // Reconstruct the path from the predecesor map; remove the artificial start state\n  const auto vd_path = BGLSolverBase<FloatType>::reconstructPath(source_, target);\n  result.trajectory = BGLSolverBase<FloatType>::toStates(vd_path);\n  result.trajectory.erase(result.trajectory.begin());\n\n  result.cost = graph_[target].distance;\n\n  return result;\n}\n\ntemplate <typename FloatType, typename Visitors>\nBGLDijkstraSVDESolver<FloatType, Visitors>::BGLDijkstraSVDESolver(Visitors event_visitors, unsigned num_threads)\n  : BGLSolverBaseSVDE<FloatType>(num_threads), event_visitors_(std::move(event_visitors))\n{\n}\n\ntemplate <typename FloatType, typename Visitors>\nSearchResult<FloatType> BGLDijkstraSVDESolver<FloatType, Visitors>::search()\n{\n  // Convenience aliases\n  auto& graph_ = BGLSolverBase<FloatType>::graph_;\n  const auto& source_ = BGLSolverBase<FloatType>::source_;\n  auto& predecessors_ = BGLSolverBase<FloatType>::predecessors_;\n  const auto& ladder_rungs_ = BGLSolverBase<FloatType>::ladder_rungs_;\n\n  // Create the dynamic edge adding event visitor\n  const auto& edge_eval_ = BGLSolverBaseSVDE<FloatType>::edge_eval_;\n  auto vis = std::make_pair(add_all_edges_dynamically<FloatType, boost::on_examine_vertex>(edge_eval_, ladder_rungs_),\n                            event_visitors_);\n\n  VertexDesc<FloatType> target = solveDijkstra(graph_, predecessors_, source_, vis, ladder_rungs_);\n\n  SearchResult<FloatType> result;\n\n  // Reconstruct the path from the predecesor map; remove the artificial start state\n  const auto vd_path = BGLSolverBase<FloatType>::reconstructPath(source_, target);\n  result.trajectory = BGLSolverBase<FloatType>::toStates(vd_path);\n  result.trajectory.erase(result.trajectory.begin());\n\n  result.cost = graph_[target].distance;\n\n  return result;\n}\n\n}  // namespace descartes_light\n\n#endif  // DESCARTES_LIGHT_SOLVERS_BGL_IMPL_BGL_DIJKSTRA_SOLVER_HPP\n", "meta": {"hexsha": "b4e5839a4cf9a59a06114c8304d8e1c4ab2dad49", "size": 6092, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "descartes_light/bgl/include/descartes_light/bgl/impl/bgl_dijkstra_solver.hpp", "max_stars_repo_name": "swri-robotics/descartes_light", "max_stars_repo_head_hexsha": "0eeeaf216677112c24d8ec51b984044e7f62c209", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 24.0, "max_stars_repo_stars_event_min_datetime": "2019-07-23T19:16:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-08T08:53:37.000Z", "max_issues_repo_path": "descartes_light/bgl/include/descartes_light/bgl/impl/bgl_dijkstra_solver.hpp", "max_issues_repo_name": "swri-robotics/descartes_light", "max_issues_repo_head_hexsha": "0eeeaf216677112c24d8ec51b984044e7f62c209", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 50.0, "max_issues_repo_issues_event_min_datetime": "2019-07-23T18:31:45.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-03T14:47:32.000Z", "max_forks_repo_path": "descartes_light/bgl/include/descartes_light/bgl/impl/bgl_dijkstra_solver.hpp", "max_forks_repo_name": "swri-robotics/descartes_light", "max_forks_repo_head_hexsha": "0eeeaf216677112c24d8ec51b984044e7f62c209", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 15.0, "max_forks_repo_forks_event_min_datetime": "2019-07-23T18:28:02.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-27T08:16:13.000Z", "avg_line_length": 43.8273381295, "max_line_length": 119, "alphanum_fraction": 0.6909061064, "num_tokens": 1326, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7090191337850932, "lm_q2_score": 0.47268347662043286, "lm_q1q2_score": 0.33514162914794565}}
{"text": "#include \"tracer.hpp\"\n#include \"initial_conditions/initial_conditions.hpp\"\n#include \"ode_state.hpp\"\n#include \"dynamics/ray_dynamics.hpp\"\n#include <future>\n#include <chrono>\n\n#include <boost/numeric/odeint/integrate/integrate_const.hpp>\n#include <boost/numeric/odeint/stepper/runge_kutta4.hpp>\n#include <boost/numeric/odeint/stepper/runge_kutta_cash_karp54.hpp>\n#include <boost/numeric/odeint/stepper/controlled_runge_kutta.hpp>\n\n#include <boost/range/combine.hpp>\n#include <boost/range/algorithm/min_element.hpp>\n#include <boost/range/adaptor/transformed.hpp>\n#include <boost/numeric/odeint/stepper/euler.hpp>\n#include \"observers/energy_error_observer.hpp\"\n#include <utility>\n\nTracer::Tracer( const Potential& pot, std::shared_ptr<RayDynamics> dynamics ) :\n\tmDimension( pot.getDimension() ),\n\tmSupport( pot.getSupport() ),\n\tmExtents( pot.getExtents() ),\n\tmDynamics( std::move(dynamics) ),\n    mMasterObserver( pot.getDimension(), mDynamics ),\n\tmEnergyErrorObs(std::make_shared<EnergyErrorObserver>())\n{\n\tusing namespace boost::range;\n\tusing namespace boost::adaptors;\n\n\t// we choose initial step according to the potential length\n\t// scaling = size / support, i.e. dt = support/size\n\n\t// cannot use a lambda as older boost looks for member result_type\n\tstruct ratio\n\t{\n\t\ttypedef double result_type;\n\t\tdouble operator()(const boost::tuple<double, std::size_t>& t) const { return boost::get<0>(t) / boost::get<1>(t); }\n\t};\n\t\n\tauto ratios = combine(pot.getSupport(), pot.getExtents()) | transformed(ratio());\n\tmInitialDeltaT = *min_element(ratios);\n\n\tmMasterObserver.addObserverObject(mEnergyErrorObs);\n}\n\nTracer::~Tracer() = default;\n\nvoid Tracer::setErrorBounds( double abs_err, double rel_err )\n{\n\tmAbsErrorBound = abs_err;\n\tmRelErrorBound = rel_err;\n}\n\nvoid Tracer::addObserver( obs_type observer )\n{\n\tmMasterObserver.addObserverObject(std::move(observer));\n}\n\nTraceResult Tracer::trace(InitCondGenPtr& incoming_wave, InitialConditionConfiguration config)\n{\n\t// fix coordinate transformation for initial condition\n\tauto support = mSupport;\n\tgen_vect offset(mDimension);\n\tfor(unsigned i = 0; i < mDimension; ++i)\n\t{\n\t\toffset[i] = mSupport[i] / mExtents[i];\n\t\tsupport[i] -= 2*offset[i];\n\t}\n    config.setDynamics( mDynamics ).setSupport( support ).setOffset(offset);\n\tincoming_wave->init( config );\n\n\t// set up master observer\n\tmMasterObserver.setPeriodicBoundaries( mDynamics->hasPeriodicBoundary() );\n\tmMasterObserver.startTracing( );\n\n\tunsigned int threadcount = std::min(mMaxThreads, (std::size_t)std::thread::hardware_concurrency());\n\t#ifndef NDEBUG\n\tstd::cout << \"distribute computation to \" << threadcount << \" threads\\n\";\n\t#endif\n\n\tstd::vector<std::future<void>> threads;\n\tauto tf = [this](InitCondGenPtr w, bool is_printer)\n\t{\n\t\treturn this->traceThreadFunction( std::move(w), is_printer );\n\t};\n\n\tfor(unsigned i = 0; i < threadcount; ++i)\n\t{\n\t\t// start threads, only thread zero prints progress\n\t\tthreads.push_back( std::async ( std::launch::async, tf, incoming_wave, i == 0) );\n\t}\n\n\tfor( auto& f : threads)\n\t\tf.get();\n\n\tmMasterObserver.finishTracing();\n\n\treturn TraceResult{mEnergyErrorObs->getMaximumError(), mEnergyErrorObs->getMeanError(), getTracedParticleCount()};\n}\n\nvoid Tracer::traceThreadFunction( InitCondGenPtr incoming_wave, bool printer )\n{\n\t// check that dynamcis are set\n\tif(!mDynamics)\n\t\tTHROW_EXCEPTION( std::runtime_error, \"Cannot perform tracing when no dynamics are set!\" );\n\n\t// setup types for boost odeint solver\n\tusing namespace boost::numeric::odeint;\n\n\tif(mIntegrator == Integrator::RUNGE_KUTTA_CASH_KARP_54_ADAPTIVE) {\n\t\ttypedef runge_kutta_cash_karp54<GState> error_stepper_type;\n\t\ttypedef controlled_runge_kutta<error_stepper_type> controlled_stepper_type;\n\t\ttypedef default_error_checker<double, range_algebra, default_operations> error_checker_type;\n\n\t\t// setup the integrator once!\n\t\tcontrolled_stepper_type stepper(error_checker_type(mAbsErrorBound, mRelErrorBound));\n\n\t\ttraceThreadFunction_imp(stepper, incoming_wave, printer);\n\t} else if (mIntegrator == Integrator::EULER_CONST) {\n\t\ttypedef euler<GState> stepper_type;\n\n\t\t// setup the integrator once!\n\t\tstepper_type stepper{};\n\n\t\ttraceThreadFunction_imp(stepper, incoming_wave, printer);\n\t}\n}\n\ntemplate<class T>\nvoid Tracer::traceThreadFunction_imp( T&& stepper, InitCondGenPtr incoming_wave, bool printer )\n{\n\tMasterObserver thread_observer( mMasterObserver.clone() );\n\tInitialCondition incoming = incoming_wave->next();\n\n\tGState p(mDimension, mDynamics->hasMonodromy());\n\tauto last_time = std::chrono::steady_clock::now();\n\n\tfor(std::size_t i = 0; incoming; ++i, ++incoming)\n\t{\n\t\t\n\t\tif(printer && (std::chrono::steady_clock::now() - last_time) > std::chrono::seconds(10))\n\t\t{\n\t\t    last_time = std::chrono::steady_clock::now();\n\t\t\tstd::cout << \"integrate \" << thread_observer.getTracedParticleCount() <<  \" \\n\";\n\t\t}\n\t\t\n\t\t// generate initial condition and set up state\n\t\tp.position() = incoming.getState().getPosition();\n\t\tp.velocity() = incoming.getState().getVelocity();\n\t\tif( mDynamics->hasMonodromy() )\n\t\t\tp.init_monodromy();\n\n\t\t// notify the observer\n\t\tthread_observer.startTrajectory( incoming );\n\n\t\ttry\n\t\t{\n\t\t\t/// \\todo this can return... do we want to do sth with the return value?\n\t\t\tboost::numeric::odeint::integrate_const(\n\t\t\t\t\tstd::ref(stepper),\n\t\t\t\t\t[this](const GState& s, GState& d, double t) { mDynamics->stateUpdate(s, d, t); },\n\t\t\t\t\tp,\n\t\t\t\t\t0.0, \t\t\t\t// start time\n\t\t\t\t\tmEndTime, \t\t\t// end time\n\t\t\t\t\tmInitialDeltaT, \t// initial time step\n\t\t\t\t\tstd::ref(thread_observer)\n\t\t\t);\n\t\t} catch(int& i) {};\n\n\t\tthread_observer.finishTrajectory( incoming );\n\t}\n}\n\n\nvoid Tracer::setTimeStep(double dt)\n{\n\tmInitialDeltaT = dt;\n}\n\n\nstd::size_t Tracer::getDimension() const\n{\n\treturn mDimension;\n}\n\nvoid Tracer::setMaxThreads( std::size_t threads )\n{\n\tif( threads == 0 )\n\t\tthreads = 1;\n\tmMaxThreads = threads;\n}\n\nstd::size_t Tracer::getMaxThreads( ) const\n{\n\treturn mMaxThreads;\n}\n\nvoid Tracer::setIntegrator(Integrator integrator)\n{\n    mIntegrator = integrator;\n}\n\nconst std::vector<std::shared_ptr<Observer>>& Tracer::getObservers() const\n{\n\treturn mMasterObserver.getObservers();\n}\n\nvoid Tracer::setEndTime( double et )\n{\n\tmEndTime = et;\n}\n\ndouble Tracer::getEndTime() const\n{\n\treturn mEndTime;\n}\n\nstd::size_t Tracer::getTracedParticleCount() const\n{\n\treturn mMasterObserver.getTracedParticleCount();\n}\n", "meta": {"hexsha": "fc66745252829c8659d94da41fe31c60bd0469ac", "size": 6304, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/tracer/tracer.cpp", "max_stars_repo_name": "ngc92/branchedflowsim", "max_stars_repo_head_hexsha": "d38c0e7f892d07d0abd9b63d30570c41b3b83b34", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/tracer/tracer.cpp", "max_issues_repo_name": "ngc92/branchedflowsim", "max_issues_repo_head_hexsha": "d38c0e7f892d07d0abd9b63d30570c41b3b83b34", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/tracer/tracer.cpp", "max_forks_repo_name": "ngc92/branchedflowsim", "max_forks_repo_head_hexsha": "d38c0e7f892d07d0abd9b63d30570c41b3b83b34", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.269058296, "max_line_length": 117, "alphanum_fraction": 0.7336611675, "num_tokens": 1675, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7090191337850932, "lm_q2_score": 0.4726834766204328, "lm_q1q2_score": 0.3351416291479456}}
{"text": "\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\n#include <NTL/tools.h>\n\n#ifdef NTL_ENABLE_AVX_FFT\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 pd_FFT.cpp with -ffast-math!!\"\n#endif\n\n\n\n#include <NTL/PD.h>\n#include <NTL/pd_FFT.h>\n#include <NTL/FFT_impl.h>\n\n#if (defined(__GNUC__) && __FAST_MATH__)\n#error \"do not compile pd_FFT.cpp with -ffast-math!!\"\n#endif\n\n#if (NTL_FMA_DETECTED && !defined(NTL_CONTRACTION_FIXED))\n#error \"contraction not fixed\"\n#endif\n\n\nNTL_START_IMPL\n\n#define NTL_CSR_NEAREST (0x00000000)\n#define NTL_CSR_DOWN    (0x00002000)\n#define NTL_CSR_UP      (0x00004000)\n#define NTL_CSR_TRUNC   (0x00006000)\n#define NTL_CSR_MASK    (0x00006000)\n\nCSRPush::CSRPush()\n{\n   // save current register value\n   reg = _mm_getcsr();\n   // set rounding mode to \"down\"\n   _mm_setcsr((reg & ~NTL_CSR_MASK) | NTL_CSR_DOWN);\n}\n\nCSRPush::~CSRPush()\n{\n   _mm_setcsr(reg);\n}\n\n\n\nvoid\npd_LazyPrepMulModPrecon_impl(double *bninv, const double *b, double n, long len)\n{\n   for (long i = 0; i < len; i++) bninv[i] = b[i]/n;\n}\n\n\n\ntemplate<class pd> pd\npd_LazyReduce1(pd a, double q)\n{\n   return correct_excess(a, q);\n}\n\ntemplate<class pd> pd \npd_LazyReduce2(pd a, double q)\n{\n   return correct_excess(a, 2*q);\n}\n\n// inputs in [0, 2*n), output in [0, 4*n)\ntemplate<class pd> pd\npd_LazyAddMod(pd a, pd b, double n)\n{\n   return a+b;\n}\n\n// inputs in [0, 2*n), output in [0, 4*n)\ntemplate<class pd> pd\npd_LazySubMod(pd a, pd b, double n)\n{\n   return a-b+2*n;\n}\n\n// inputs in [0, 2*n), output in [0, 2*n)\ntemplate<class pd> pd\npd_LazyAddMod2(pd a, pd b, double n)\n{\n   pd r = a+b;\n   return correct_excess(r, 2*n);\n}\n\n// inputs in [0, 2*n), output in [0, 2*n)\ntemplate<class pd> pd \npd_LazySubMod2(pd a, pd b, double n)\n{\n   pd r = a-b;\n   return correct_deficit(r, 2*n);\n}\n\n// inputs in [0, 4*n), output in [0, 4*n)\ntemplate<class pd> pd\npd_LazyAddMod4(pd a, pd b, double n)\n{\n   pd r = a+b;\n   return correct_excess(r, 4*n);\n}\n\n// inputs in [0, 4*n), output in [0, 4*n)\ntemplate<class pd> pd \npd_LazySubMod4(pd a, pd b, double n)\n{\n   pd r = a-b;\n   return correct_deficit(r, 4*n);\n}\n\n\n// Input and output in [0, 4*n)\ntemplate<class pd> pd\npd_LazyDoubleMod4(pd a, double n)\n{\n   return 2 * pd_LazyReduce2(a, n);\n}\n\n// Input and output in [0, 2*n)\ntemplate<class pd> pd\npd_LazyDoubleMod2(pd a, double n)\n{\n   return 2 * pd_LazyReduce1(a, n);\n}\n\n\n\n// n in [0,2^50), b in [0,n), a in [0,4*n), bninv = RoundDown(b/n)\n// returns a*b mod n in [0, 2*n)\ntemplate<class pd> pd\npd_LazyMulModPrecon(pd a, pd b, double n, pd bninv)\n{\n   pd hi = a*b;\n   pd lo = fused_mulsub(a, b, hi);  // hi+lo == a*b (exactly)\n   pd q =  fused_muladd(a, bninv, 1L << 52);\n   q -= (1L << 52);             // q is the correct quotient, or one too small\n   pd d = fused_negmuladd(q, n, hi);   // d == hi - q*n (exactly)\n   pd r = d + lo;           // r is the remainder, or the remainder plus n\n\n   return r;\n}\n\n// return (a[0] + a[1], a[0] - a[1], a[2] + a[3], a[2] - a[3], ...)\n// all inputs and outputs in [0, 2*n)\ntemplate<class pd> pd\npd_fwd_butterfly_packed2(pd a, double n)\n{\n   pd b = swap2(a);\n   pd sum = pd_LazyAddMod(a, b, n);\n   pd diff = pd_LazySubMod(b, a, n);\n   pd res = blend2(sum, diff);\n   res = pd_LazyReduce2(res, n);\n   return res;\n}\n\n// return (a[0] + a[2], a[1] + a[3], (a[0] - a[2]), (a[1] - a[3])*root, ...) \n// all inputs and outputs in [0, 2*n)\n// it is also assumed that w = (1,1,1,root,...) and wninv = RoundDown(w/n)\ntemplate<class pd> pd\npd_fwd_butterfly_packed4(pd a, pd w, double n, pd wninv)\n{\n   pd b = swap4(a);\n   pd sum = pd_LazyAddMod(a, b, n);\n   pd diff = pd_LazySubMod(b, a, n);\n   pd res = blend4(sum, diff);\n   res = pd_LazyMulModPrecon(res, w, n, wninv);\n   return res;\n}\n\n\nstatic double \npd_LazyPrepMulModPrecon(long b, long n)\n{\n   return double(b)/double(n);\n}\n\n\n//===================================\n\n\n#define NTL_PD_FFT_THRESH (11)\n\n#define PDLGSZ NTL_LG2_PDSZ\n#define PDSZ NTL_PDSZ\n\n#if (PDSZ == 8)\ntypedef PD<8> pd_full;\ntypedef PD<4> pd_half;\ntypedef PD<2> pd_qrtr;\n#else\ntypedef PD<4> pd_full;\ntypedef PD<2> pd_half;\n#endif\n\n#define PDLD pd_full::load\n\n\n// this assumes xx0, xx1, w, qinv are pd_half's\n#define fwd_butterfly_half(xx0, xx1, w, q, wqinv)  \\\ndo \\\n{ \\\n   pd_half x0_ = xx0; \\\n   pd_half x1_ = xx1; \\\n   pd_half t_  = pd_LazySubMod(x0_, x1_, q); \\\n   xx0 = pd_LazyAddMod2(x0_, x1_, q); \\\n   xx1 = pd_LazyMulModPrecon(t_, w, q, wqinv); \\\n}  \\\nwhile (0)\n\n// this assumes xx0, xx1, w, qinv are pd_full's\n#define fwd_butterfly_full(xx0, xx1, w, q, wqinv)  \\\ndo \\\n{ \\\n   pd_full x0_ = xx0; \\\n   pd_full x1_ = xx1; \\\n   pd_full t_  = pd_LazySubMod(x0_, x1_, q); \\\n   xx0 = pd_LazyAddMod2(x0_, x1_, q); \\\n   xx1 = pd_LazyMulModPrecon(t_, w, q, wqinv); \\\n}  \\\nwhile (0)\n\n// this assumes xx0_ptr, xx1_ptr, w_ptr, wqinv_ptr are double pointers\n// which are read/written as pd_full's.  \n// In gcc, restrict keyword will help code gen.\n#define fwd_butterfly(xx0_ptr, xx1_ptr, w_ptr, q, wqinv_ptr)  \\\ndo \\\n{ \\\n   pd_full x0_     = PDLD(xx0_ptr); \\\n   pd_full x1_     = PDLD(xx1_ptr); \\\n   pd_full w_      = PDLD(w_ptr); \\\n   pd_full wqinv_  = PDLD(wqinv_ptr); \\\n   pd_full t_      = pd_LazySubMod(x0_, x1_, q); \\\n   store(xx0_ptr, pd_LazyAddMod2(x0_, x1_, q)); \\\n   store(xx1_ptr, pd_LazyMulModPrecon(t_, w_, q, wqinv_)); \\\n}  \\\nwhile (0)\n\n\n#if 0\n#define fwd_butterfly_x4(xx0_ptr, xx1_ptr, w_ptr, q, wqinv_ptr)  \\\ndo  \\\n{  \\\n   pd_full xx0_0_ = PDLD(xx0_ptr+0*PDSZ);  pd_full xx1_0_ = PDLD(xx1_ptr+0*PDSZ);  \\\n   pd_full xx0_1_ = PDLD(xx0_ptr+1*PDSZ);  pd_full xx1_1_ = PDLD(xx1_ptr+1*PDSZ);  \\\n   pd_full xx0_2_ = PDLD(xx0_ptr+2*PDSZ);  pd_full xx1_2_ = PDLD(xx1_ptr+2*PDSZ);  \\\n   pd_full xx0_3_ = PDLD(xx0_ptr+3*PDSZ);  pd_full xx1_3_ = PDLD(xx1_ptr+3*PDSZ);  \\\n   fwd_butterfly_full(xx0_0_, xx1_0_, PDLD(w_ptr+0*PDSZ), q, PDLD(wqinv_ptr+0*PDSZ));  \\\n   fwd_butterfly_full(xx0_1_, xx1_1_, PDLD(w_ptr+1*PDSZ), q, PDLD(wqinv_ptr+1*PDSZ));  \\\n   fwd_butterfly_full(xx0_2_, xx1_2_, PDLD(w_ptr+2*PDSZ), q, PDLD(wqinv_ptr+2*PDSZ));  \\\n   fwd_butterfly_full(xx0_3_, xx1_3_, PDLD(w_ptr+3*PDSZ), q, PDLD(wqinv_ptr+3*PDSZ));  \\\n   store(xx0_ptr+0*PDSZ, xx0_0_);  store(xx1_ptr+0*PDSZ, xx1_0_);  \\\n   store(xx0_ptr+1*PDSZ, xx0_1_);  store(xx1_ptr+1*PDSZ, xx1_1_);  \\\n   store(xx0_ptr+2*PDSZ, xx0_2_);  store(xx1_ptr+2*PDSZ, xx1_2_);  \\\n   store(xx0_ptr+3*PDSZ, xx0_3_);  store(xx1_ptr+3*PDSZ, xx1_3_);  \\\n}  \\\nwhile(0)\n#else\n#define fwd_butterfly_x4(xx0_ptr, xx1_ptr, w_ptr, q, wqinv_ptr)  \\\ndo  \\\n{  \\\n   fwd_butterfly(xx0_ptr+0*PDSZ, xx1_ptr+0*PDSZ, w_ptr+0*PDSZ, q, wqinv_ptr+0*PDSZ);  \\\n   fwd_butterfly(xx0_ptr+1*PDSZ, xx1_ptr+1*PDSZ, w_ptr+1*PDSZ, q, wqinv_ptr+1*PDSZ);  \\\n   fwd_butterfly(xx0_ptr+2*PDSZ, xx1_ptr+2*PDSZ, w_ptr+2*PDSZ, q, wqinv_ptr+2*PDSZ);  \\\n   fwd_butterfly(xx0_ptr+3*PDSZ, xx1_ptr+3*PDSZ, w_ptr+3*PDSZ, q, wqinv_ptr+3*PDSZ);  \\\n}  \\\nwhile(0)\n#endif\n\n\n\n\nstatic inline NTL_ALWAYS_INLINE void\npd_fft_layer_inner_loop(double* NTL_RESTRICT xp0, \n                        double* NTL_RESTRICT xp1,\n                        long size, \n                        const double* NTL_RESTRICT wtab, \n                        const double* NTL_RESTRICT wqinvtab, \n                        double q)\n\n{\n   long j = 0;\n   do {\n     fwd_butterfly_x4(xp0+j, xp1+j, wtab+j, q, wqinvtab+j);\n     j += 4*PDSZ;\n   } while (j < size);\n}\n\n// assumes size >= 8*PDSZ\nstatic inline NTL_ALWAYS_INLINE void \npd_fft_layer(double* xp, long blocks, long size,\n\t     const double* wtab, \n\t     const double* wqinvtab, \n\t     double q)\n{\n   size /= 2;\n\n   do {\n      pd_fft_layer_inner_loop(xp, xp+size, size, wtab, wqinvtab, q);\n      xp += 2 * size;\n   } while (--blocks != 0);\n}\n\n\n// size == 8*PDSZ\nstatic inline NTL_ALWAYS_INLINE void\npd_fft_layer_size8(double* NTL_RESTRICT xp, long blocks,\n\t\t  const double* NTL_RESTRICT wtab, \n\t\t  const double* NTL_RESTRICT wqinvtab, \n\t\t  double q)\n{\n   do {\n      fwd_butterfly_x4(xp+0*PDSZ, xp+4*PDSZ, wtab, q, wqinvtab);\n      xp += 8*PDSZ;\n   } while (--blocks != 0);\n}\n\n// size == 4*PDSZ\nstatic inline NTL_ALWAYS_INLINE void\npd_fft_layer_size4(double* NTL_RESTRICT xp, long blocks,\n\t\t   const double* NTL_RESTRICT wtab, \n\t\t   const double* NTL_RESTRICT wqinvtab, \n\t\t   double q)\n{\n   do {\n      fwd_butterfly(xp+0*PDSZ, xp+2*PDSZ, wtab+0*PDSZ, q, wqinvtab+0*PDSZ);\n      fwd_butterfly(xp+1*PDSZ, xp+3*PDSZ, wtab+1*PDSZ, q, wqinvtab+1*PDSZ);\n\n      fwd_butterfly(xp+4*PDSZ, xp+6*PDSZ, wtab+0*PDSZ, q, wqinvtab+0*PDSZ);\n      fwd_butterfly(xp+5*PDSZ, xp+7*PDSZ, wtab+1*PDSZ, q, wqinvtab+1*PDSZ);\n\n      xp += 8*PDSZ;\n      blocks -= 2;\n   } while (blocks != 0);\n}\n\n// size == 2*PDSZ\nstatic inline NTL_ALWAYS_INLINE void\npd_fft_layer_size2(double* NTL_RESTRICT xp, long blocks,\n\t\t   const double* NTL_RESTRICT wtab, \n\t\t   const double* NTL_RESTRICT wqinvtab, \n\t\t   double q)\n{\n   do {\n      fwd_butterfly(xp+0*PDSZ, xp+1*PDSZ, wtab+0*PDSZ, q, wqinvtab+0*PDSZ);\n      fwd_butterfly(xp+2*PDSZ, xp+3*PDSZ, wtab+0*PDSZ, q, wqinvtab+0*PDSZ);\n      fwd_butterfly(xp+4*PDSZ, xp+5*PDSZ, wtab+0*PDSZ, q, wqinvtab+0*PDSZ);\n      fwd_butterfly(xp+6*PDSZ, xp+7*PDSZ, wtab+0*PDSZ, q, wqinvtab+0*PDSZ);\n\n      xp += 8*PDSZ;\n      blocks -= 4;\n   } while (blocks != 0);\n}\n\n#if (PDSZ == 8)\nstatic inline NTL_ALWAYS_INLINE void\npd_fft_layer_size1_one_block(double* x,\n                   pd_half w8, pd_half w8qinv,\n                   pd_full w4, pd_full w4qinv,\n\t\t   double q)\n{\n   pd_half x0 = pd_half::load(x);\n   pd_half x1 = pd_half::load(x+PDSZ/2);\n   fwd_butterfly_half(x0, x1, w8, q, w8qinv);\n   pd_full y = join(x0, x1);\n\n   y = pd_fwd_butterfly_packed4(y, w4, q, w4qinv);\n   y = pd_fwd_butterfly_packed2(y, q);\n\n   store(x, y);\n}\n\n// size == PDSZ == 8\n// processes last three levels, of size 8, 4, and 2.\nstatic inline NTL_ALWAYS_INLINE void\npd_fft_layer_size1(double* xp, long blocks,\n                   const double **w_pp, const double **wqinv_pp,\n\t\t   double q)\n{\n   const double *w8_ptr = *w_pp;\n   const double *w8qinv_ptr = *wqinv_pp;\n\n   const double *w4_ptr = *(w_pp-1);\n   const double *w4qinv_ptr = *(wqinv_pp-1);\n\n   pd_half w8 = pd_half::load(w8_ptr);\n\n   pd_half w8qinv = pd_half::load(w8qinv_ptr);\n\n   \n   pd_qrtr w4_qrtr = pd_qrtr::load(w4_ptr);\n   pd_half w4_half = join(w4_qrtr, w4_qrtr);\n   pd_full w4      = join(w4_half, w4_half);\n   w4 = blend4(dup2even(w4), w4);\n\n   pd_qrtr w4qinv_qrtr = pd_qrtr::load(w4qinv_ptr);\n   pd_half w4qinv_half = join(w4qinv_qrtr, w4qinv_qrtr);\n   pd_full w4qinv      = join(w4qinv_half, w4qinv_half);\n   w4qinv = blend4(dup2even(w4qinv), w4qinv);\n\n   do {\n      pd_fft_layer_size1_one_block(xp+0*PDSZ, w8, w8qinv, w4, w4qinv, q);\n      pd_fft_layer_size1_one_block(xp+1*PDSZ, w8, w8qinv, w4, w4qinv, q);\n      pd_fft_layer_size1_one_block(xp+2*PDSZ, w8, w8qinv, w4, w4qinv, q);\n      pd_fft_layer_size1_one_block(xp+3*PDSZ, w8, w8qinv, w4, w4qinv, q);\n\n      xp += 4*PDSZ;\n      blocks -= 4;\n   } while (blocks != 0);\n}\n#else\n// PDSZ == 4\n\nstatic inline NTL_ALWAYS_INLINE void\npd_fft_layer_size1_one_block(double* x,\n                   pd_half w4, pd_half w4qinv,\n\t\t   double q)\n{\n   pd_half x0 = pd_half::load(x);\n   pd_half x1 = pd_half::load(x+PDSZ/2);\n   fwd_butterfly_half(x0, x1, w4, q, w4qinv);\n   pd_full y = join(x0, x1);\n\n   y = pd_fwd_butterfly_packed2(y, q);\n\n   store(x, y);\n}\n\n// size == PDSZ == 4\n// processes last two levels, of size 4 and 2.\nstatic inline NTL_ALWAYS_INLINE void\npd_fft_layer_size1(double* xp, long blocks,\n                   const double **w_pp, const double **wqinv_pp,\n\t\t   double q)\n{\n   const double *w4_ptr = *w_pp;\n   const double *w4qinv_ptr = *wqinv_pp;\n\n\n   pd_half w4 = pd_half::load(w4_ptr);\n   pd_half w4qinv = pd_half::load(w4qinv_ptr);\n\n   \n   do {\n      pd_fft_layer_size1_one_block(xp+0*PDSZ, w4, w4qinv, q);\n      pd_fft_layer_size1_one_block(xp+1*PDSZ, w4, w4qinv, q);\n      pd_fft_layer_size1_one_block(xp+2*PDSZ, w4, w4qinv, q);\n      pd_fft_layer_size1_one_block(xp+3*PDSZ, w4, w4qinv, q);\n\n      xp += 4*PDSZ;\n      blocks -= 4;\n   } while (blocks != 0);\n}\n\n#endif\n       \n      \n\n\nvoid \npd_fft_base(double* xp, long lgN, const pd_mod_t& mod)\n{\n  double q = mod.q;\n  const double** wtab = mod.wtab;\n  const double** wqinvtab = mod.wqinvtab;\n\n  long N = 1L << lgN;\n\n  long j, size, blocks;\n  for (j = lgN, size = N, blocks = 1; \n       size > 8*PDSZ; j--, blocks <<= 1, size >>= 1)\n    pd_fft_layer(xp, blocks, size, wtab[j], wqinvtab[j], q);\n\n  pd_fft_layer_size8(xp, blocks, wtab[j], wqinvtab[j], q);  \n  j--, blocks <<= 1, size >>= 1;\n\n  pd_fft_layer_size4(xp, blocks, wtab[j], wqinvtab[j], q);  \n  j--, blocks <<= 1, size >>= 1;\n\n  pd_fft_layer_size2(xp, blocks, wtab[j], wqinvtab[j], q);  \n  j--, blocks <<= 1, size >>= 1;\n\n  pd_fft_layer_size1(xp, blocks, wtab+j, wqinvtab+j, q);  \n\n}\n\nstatic inline NTL_ALWAYS_INLINE void \npd_move(double *x, const long *a)\n{\n   pd_full r;\n   loadu(r, a);\n   store(x, r);\n}\n\nstatic inline NTL_ALWAYS_INLINE void \npd_move(long *x, const double *a)\n{\n   pd_full r;\n   load(r, a);\n   storeu(x, r);\n}\n\nstatic inline NTL_ALWAYS_INLINE void \npd_reduce1_move(long *x, const double *a, double q)\n{\n   pd_full r;\n   load(r, a);\n   r = pd_LazyReduce1(r, q);\n   storeu(x, r);\n}\n\nstatic inline NTL_ALWAYS_INLINE void \npd_reduce2_move(long *x, const double *a, double q)\n{\n   pd_full r;\n   load(r, a);\n   r = pd_LazyReduce2(r, q);\n   r = pd_LazyReduce1(r, q);\n   storeu(x, r);\n}\n\nstatic inline NTL_ALWAYS_INLINE void \npd_mul_move(long *x, const double *a, pd_full b, double q, pd_full bqinv)\n{\n   pd_full r;\n   load(r, a);\n   r = pd_LazyMulModPrecon(r, b, q, bqinv);\n   r = pd_LazyReduce1(r, q);\n   storeu(x, r);\n}\n\n\n\n\nstatic\nvoid pd_fft_short(double* xp, long yn, long xn, long lgN, \n                   const pd_mod_t& mod)\n{\n  long N = 1L << lgN;\n\n  if (yn == N)\n    {\n      if (xn == N && lgN <= NTL_PD_FFT_THRESH)\n\t{\n\t  // no truncation\n\t  pd_fft_base(xp, lgN, mod);\n\t  return;\n\t}\n    }\n\n  // divide-and-conquer algorithm\n\n  long half = N >> 1;\n  double q = mod.q;\n\n  if (yn <= half)\n    {\n      if (xn <= half)\n\t{\n\t  pd_fft_short(xp, yn, xn, lgN - 1, mod);\n\t}\n      else\n\t{\n\t  xn -= half;\n\n\t  // (X, Y) -> X + Y\n\t  for (long j = 0; j < xn; j+=PDSZ)\n\t    store(xp+j, pd_LazyAddMod2(PDLD(xp+j), PDLD(xp+j+half), q));\n\n\t  pd_fft_short(xp, yn, half, lgN - 1, mod);\n\t}\n    }\n  else\n    {\n      yn -= half;\n      \n      double* xp0 = xp;\n      double* xp1 = xp + half;\n      const double* wtab = mod.wtab[lgN];\n      const double* wqinvtab = mod.wqinvtab[lgN];\n\n      if (xn <= half)\n\t{\n\t  // X -> (X, w*X)\n\t  for (long j = 0; j < xn; j+=PDSZ)\n\t    store(xp1+j, pd_LazyMulModPrecon(PDLD(xp0+j), PDLD(wtab+j), q, PDLD(wqinvtab+j)));\n\n\t  pd_fft_short(xp0, half, xn, lgN - 1, mod);\n\t  pd_fft_short(xp1, yn, xn, lgN - 1, mod);\n\t}\n      else\n\t{\n\t  xn -= half;\n\n\t  // (X, Y) -> (X + Y, w*(X - Y))\n          pd_fft_layer_inner_loop(xp0, xp1, xn, wtab, wqinvtab, q);\n\n\t  // X -> (X, w*X)\n\t  for (long j = xn; j < half; j+=PDSZ)\n\t    store(xp1+j, pd_LazyMulModPrecon(PDLD(xp0+j), PDLD(wtab+j), q, PDLD(wqinvtab+j)));\n\n\t  pd_fft_short(xp0, half, half, lgN - 1, mod);\n\t  pd_fft_short(xp1, yn, half, lgN - 1, mod);\n\t}\n    }\n}\n\n\nvoid \npd_fft_trunc_impl(long* A, const long* a, double* xp, long lgN, const pd_mod_t& mod,\n                  long yn, long xn)\n           \n{\n   for (long i = 0; i < xn; i += 4*PDSZ) {\n      pd_move(xp+i+0*PDSZ, a+i+0*PDSZ);\n      pd_move(xp+i+1*PDSZ, a+i+1*PDSZ);\n      pd_move(xp+i+2*PDSZ, a+i+2*PDSZ);\n      pd_move(xp+i+3*PDSZ, a+i+3*PDSZ);\n   }\n\n   pd_fft_short(xp, yn, xn, lgN, mod);\n\n   double q = mod.q;\n   for (long i = 0; i < yn; i += 4*PDSZ) {\n      pd_reduce1_move(A+i+0*PDSZ, xp+i+0*PDSZ, q);\n      pd_reduce1_move(A+i+1*PDSZ, xp+i+1*PDSZ, q);\n      pd_reduce1_move(A+i+2*PDSZ, xp+i+2*PDSZ, q);\n      pd_reduce1_move(A+i+3*PDSZ, xp+i+3*PDSZ, q);\n   }\n}\n\n\nvoid \npd_fft_trunc_impl(long* A, const long* a, double* xp, long lgN, const pd_mod_t& mod,\n                  long yn, long xn, double fac)\n           \n{\n   for (long i = 0; i < xn; i += 4*PDSZ) {\n      pd_move(xp+i+0*PDSZ, a+i+0*PDSZ);\n      pd_move(xp+i+1*PDSZ, a+i+1*PDSZ);\n      pd_move(xp+i+2*PDSZ, a+i+2*PDSZ);\n      pd_move(xp+i+3*PDSZ, a+i+3*PDSZ);\n   }\n\n   pd_fft_short(xp, yn, xn, lgN, mod);\n\n   double q = mod.q;\n   double facqinv = fac/q; \n   for (long i = 0; i < yn; i += 4*PDSZ) {\n      pd_mul_move(A+i+0*PDSZ, xp+i+0*PDSZ, fac, q, facqinv);\n      pd_mul_move(A+i+1*PDSZ, xp+i+1*PDSZ, fac, q, facqinv);\n      pd_mul_move(A+i+2*PDSZ, xp+i+2*PDSZ, fac, q, facqinv);\n      pd_mul_move(A+i+3*PDSZ, xp+i+3*PDSZ, fac, q, facqinv);\n   }\n}\n\n//================ ifft ==============\n\n// return (a[0] + a[1], a[0] - a[1], a[2] + a[3], a[2] - a[3], ...)\n// all inputs and outputs in [0, 4*n)\ntemplate<class pd> pd\npd_inv_butterfly_packed2(pd a, double n)\n{\n   a = pd_LazyReduce2(a, n);\n   pd b = swap2(a);\n   pd sum = pd_LazyAddMod(a, b, n);\n   pd diff = pd_LazySubMod(b, a, n);\n   pd res = blend2(sum, diff);\n   return res;\n}\n\n// return (a[0] + a[2], a[1] + a[3]*root, a[0] - a[2], a[1] - a[3]*root, ...) \n// all inputs and outputs in [0, 4*n)\n// it is also assumed that w = (1,1,1,root,...) and wninv = RoundDown(w/n)\ntemplate<class pd> pd\npd_inv_butterfly_packed4(pd a, pd w, double n, pd wninv)\n{\n   a = pd_LazyMulModPrecon(a, w, n, wninv);\n   pd b = swap4(a);\n   pd sum = pd_LazyAddMod(a, b, n);\n   pd diff = pd_LazySubMod(b, a, n);\n   pd res = blend4(sum, diff);\n   return res;\n}\n\n#define inv_butterfly_half(xx0, xx1, w, q, wqinv)  \\\ndo  \\\n{  \\\n   pd_half x0_ = pd_LazyReduce2(xx0, q);  \\\n   pd_half x1_ = xx1;  \\\n   pd_half t_ = pd_LazyMulModPrecon(x1_, w, q, wqinv);   \\\n   xx0 = pd_LazyAddMod(x0_, t_, q);    \\\n   xx1 = pd_LazySubMod(x0_, t_, q);    \\\n} while (0)\n\n\n#define inv_butterfly(xx0_ptr, xx1_ptr, w_ptr, q, wqinv_ptr)  \\\ndo  \\\n{  \\\n   pd_full x0_ = pd_LazyReduce2(PDLD(xx0_ptr), q);  \\\n   pd_full x1_ = PDLD(xx1_ptr);  \\\n   pd_full t_ = pd_LazyMulModPrecon(x1_, PDLD(w_ptr), q, PDLD(wqinv_ptr));   \\\n   store(xx0_ptr, pd_LazyAddMod(x0_, t_, q));    \\\n   store(xx1_ptr, pd_LazySubMod(x0_, t_, q));    \\\n} while (0)\n\n#define inv_butterfly_x4(xx0_ptr, xx1_ptr, w_ptr, q, wqinv_ptr)  \\\ndo  \\\n{  \\\n   inv_butterfly(xx0_ptr+0*PDSZ, xx1_ptr+0*PDSZ, w_ptr+0*PDSZ, q, wqinv_ptr+0*PDSZ);  \\\n   inv_butterfly(xx0_ptr+1*PDSZ, xx1_ptr+1*PDSZ, w_ptr+1*PDSZ, q, wqinv_ptr+1*PDSZ);  \\\n   inv_butterfly(xx0_ptr+2*PDSZ, xx1_ptr+2*PDSZ, w_ptr+2*PDSZ, q, wqinv_ptr+2*PDSZ);  \\\n   inv_butterfly(xx0_ptr+3*PDSZ, xx1_ptr+3*PDSZ, w_ptr+3*PDSZ, q, wqinv_ptr+3*PDSZ);  \\\n}  \\\nwhile(0)\n\nstatic inline NTL_ALWAYS_INLINE void\npd_ifft_layer_inner_loop(double* NTL_RESTRICT xp0, \n                         double* NTL_RESTRICT xp1,\n                         long size, \n                         const double* NTL_RESTRICT wtab, \n                         const double* NTL_RESTRICT wqinvtab, \n                         double q)\n\n{\n   long j = 0;\n   do {\n     inv_butterfly_x4(xp0+j, xp1+j, wtab+j, q, wqinvtab+j);\n     j += 4*PDSZ;\n   } while (j < size);\n}\n\n// assumes size >= 8*PDSZ\nstatic inline NTL_ALWAYS_INLINE void \npd_ifft_layer(double* xp, long blocks, long size,\n\t      const double* wtab, \n\t      const double* wqinvtab, \n\t      double q)\n{\n   size /= 2;\n\n   do {\n      pd_ifft_layer_inner_loop(xp, xp+size, size, wtab, wqinvtab, q);\n      xp += 2 * size;\n   } while (--blocks != 0);\n}\n\n// size == 8*PDSZ\nstatic inline NTL_ALWAYS_INLINE void\npd_ifft_layer_size8(double* NTL_RESTRICT xp, long blocks,\n\t\t    const double* NTL_RESTRICT wtab, \n\t\t    const double* NTL_RESTRICT wqinvtab, \n\t\t    double q)\n{\n   do {\n      inv_butterfly_x4(xp+0*PDSZ, xp+4*PDSZ, wtab, q, wqinvtab);\n      xp += 8*PDSZ;\n   } while (--blocks != 0);\n}\n\n// size == 4*PDSZ\nstatic inline NTL_ALWAYS_INLINE void\npd_ifft_layer_size4(double* NTL_RESTRICT xp, long blocks,\n\t\t    const double* NTL_RESTRICT wtab, \n\t\t    const double* NTL_RESTRICT wqinvtab, \n\t\t    double q)\n{\n   do {\n      inv_butterfly(xp+0*PDSZ, xp+2*PDSZ, wtab+0*PDSZ, q, wqinvtab+0*PDSZ);\n      inv_butterfly(xp+1*PDSZ, xp+3*PDSZ, wtab+1*PDSZ, q, wqinvtab+1*PDSZ);\n\n      inv_butterfly(xp+4*PDSZ, xp+6*PDSZ, wtab+0*PDSZ, q, wqinvtab+0*PDSZ);\n      inv_butterfly(xp+5*PDSZ, xp+7*PDSZ, wtab+1*PDSZ, q, wqinvtab+1*PDSZ);\n\n      xp += 8*PDSZ;\n      blocks -= 2;\n   } while (blocks != 0);\n}\n\n// size == 2*PDSZ\nstatic inline NTL_ALWAYS_INLINE void\npd_ifft_layer_size2(double* NTL_RESTRICT xp, long blocks,\n\t\t    const double* NTL_RESTRICT wtab, \n\t\t    const double* NTL_RESTRICT wqinvtab, \n\t\t    double q)\n{\n   do {\n      inv_butterfly(xp+0*PDSZ, xp+1*PDSZ, wtab+0*PDSZ, q, wqinvtab+0*PDSZ);\n      inv_butterfly(xp+2*PDSZ, xp+3*PDSZ, wtab+0*PDSZ, q, wqinvtab+0*PDSZ);\n      inv_butterfly(xp+4*PDSZ, xp+5*PDSZ, wtab+0*PDSZ, q, wqinvtab+0*PDSZ);\n      inv_butterfly(xp+6*PDSZ, xp+7*PDSZ, wtab+0*PDSZ, q, wqinvtab+0*PDSZ);\n\n      xp += 8*PDSZ;\n      blocks -= 4;\n   } while (blocks != 0);\n}\n\n#if (PDSZ == 8)\nstatic inline NTL_ALWAYS_INLINE void\npd_ifft_layer_size1_one_block(double* x,\n                   pd_half w8, pd_half w8qinv,\n                   pd_full w4, pd_full w4qinv,\n\t\t   double q)\n{\n   pd_full y = PDLD(x);\n   y = pd_inv_butterfly_packed2(y, q);\n   y = pd_inv_butterfly_packed4(y, w4, q, w4qinv);\n\n   pd_half x0 = get_lo(y);\n   pd_half x1 = get_hi(y);\n   inv_butterfly_half(x0, x1, w8, q, w8qinv);\n   \n   store(x, x0);\n   store(x+PDSZ/2, x1);\n}\n\n// size == PDSZ == 8\n// processes last three levels, of size 8, 4, and 2.\nstatic inline NTL_ALWAYS_INLINE void\npd_ifft_layer_size1(double* xp, long blocks,\n                   const double **w_pp, const double **wqinv_pp,\n\t\t   double q)\n{\n   const double *w8_ptr = *w_pp;\n   const double *w8qinv_ptr = *wqinv_pp;\n\n   const double *w4_ptr = *(w_pp-1);\n   const double *w4qinv_ptr = *(wqinv_pp-1);\n\n   pd_half w8 = pd_half::load(w8_ptr);\n\n   pd_half w8qinv = pd_half::load(w8qinv_ptr);\n\n   \n   pd_qrtr w4_qrtr = pd_qrtr::load(w4_ptr);\n   pd_half w4_half = join(w4_qrtr, w4_qrtr);\n   pd_full w4      = join(w4_half, w4_half);\n   w4 = blend4(dup2even(w4), w4);\n\n   pd_qrtr w4qinv_qrtr = pd_qrtr::load(w4qinv_ptr);\n   pd_half w4qinv_half = join(w4qinv_qrtr, w4qinv_qrtr);\n   pd_full w4qinv      = join(w4qinv_half, w4qinv_half);\n   w4qinv = blend4(dup2even(w4qinv), w4qinv);\n\n   do {\n      pd_ifft_layer_size1_one_block(xp+0*PDSZ, w8, w8qinv, w4, w4qinv, q);\n      pd_ifft_layer_size1_one_block(xp+1*PDSZ, w8, w8qinv, w4, w4qinv, q);\n      pd_ifft_layer_size1_one_block(xp+2*PDSZ, w8, w8qinv, w4, w4qinv, q);\n      pd_ifft_layer_size1_one_block(xp+3*PDSZ, w8, w8qinv, w4, w4qinv, q);\n\n      xp += 4*PDSZ;\n      blocks -= 4;\n   } while (blocks != 0);\n}\n#else\n// PDSZ == 4\n\nstatic inline NTL_ALWAYS_INLINE void\npd_ifft_layer_size1_one_block(double* x,\n                   pd_half w4, pd_half w4qinv,\n\t\t   double q)\n{\n   pd_full y = PDLD(x);\n   y = pd_inv_butterfly_packed2(y, q);\n\n   pd_half x0 = get_lo(y);\n   pd_half x1 = get_hi(y);\n   inv_butterfly_half(x0, x1, w4, q, w4qinv);\n   \n   store(x, x0);\n   store(x+PDSZ/2, x1);\n}\n\n// size == PDSZ == 4\n// processes last two levels, of size 4 and 2.\nstatic inline NTL_ALWAYS_INLINE void\npd_ifft_layer_size1(double* xp, long blocks,\n                   const double **w_pp, const double **wqinv_pp,\n\t\t   double q)\n{\n   const double *w4_ptr = *w_pp;\n   const double *w4qinv_ptr = *wqinv_pp;\n\n\n   pd_half w4 = pd_half::load(w4_ptr);\n   pd_half w4qinv = pd_half::load(w4qinv_ptr);\n\n   \n   do {\n      pd_ifft_layer_size1_one_block(xp+0*PDSZ, w4, w4qinv, q);\n      pd_ifft_layer_size1_one_block(xp+1*PDSZ, w4, w4qinv, q);\n      pd_ifft_layer_size1_one_block(xp+2*PDSZ, w4, w4qinv, q);\n      pd_ifft_layer_size1_one_block(xp+3*PDSZ, w4, w4qinv, q);\n\n      xp += 4*PDSZ;\n      blocks -= 4;\n   } while (blocks != 0);\n}\n\n#endif\n       \nvoid \npd_ifft_base(double* xp, long lgN, const pd_mod_t& mod)\n{\n  double q = mod.q;\n  const double** wtab = mod.wtab;\n  const double** wqinvtab = mod.wqinvtab;\n\n  long N = 1L << lgN;\n\n  long j=PDLGSZ, size=PDSZ, blocks=N/PDSZ;\n\n  pd_ifft_layer_size1(xp, blocks, wtab+j, wqinvtab+j, q);  \n  j++, blocks >>= 1, size <<= 1;\n\n  pd_ifft_layer_size2(xp, blocks, wtab[j], wqinvtab[j], q);  \n  j++, blocks >>= 1, size <<= 1;\n\n  pd_ifft_layer_size4(xp, blocks, wtab[j], wqinvtab[j], q);  \n  j++, blocks >>= 1, size <<= 1;\n\n  pd_ifft_layer_size8(xp, blocks, wtab[j], wqinvtab[j], q);  \n  j++, blocks >>= 1, size <<= 1;\n\n  for (; size <= N; j++, blocks >>= 1, size <<= 1)\n    pd_ifft_layer(xp, blocks, size, wtab[j], wqinvtab[j], q);\n\n}\n\nstatic void \npd_ifft_short2(double* xp, long yn, long lgN, const pd_mod_t& mod);\n\n\nstatic void \npd_ifft_short1(double* xp, long yn, long lgN, const pd_mod_t& mod)\n\n// Implements truncated inverse FFT interface, but with xn==yn.\n// All computations are done in place.\n\n{\n  long N = 1L << lgN;\n\n  if (yn == N && lgN <= NTL_PD_FFT_THRESH)\n    {\n      // no truncation\n      pd_ifft_base(xp, lgN, mod);\n      return;\n    }\n\n  // divide-and-conquer algorithm\n\n  long half = N >> 1;\n  double q = mod.q;\n\n  if (yn <= half)\n    {\n      // X -> 2X\n      for (long j = 0; j < yn; j+=PDSZ)\n      \tstore(xp+j, pd_LazyDoubleMod4(PDLD(xp+j), q));\n\n      pd_ifft_short1(xp, yn, lgN - 1, mod);\n    }\n  else\n    {\n      double* xp0 = xp;\n      double* xp1 = xp + half;\n\n      pd_ifft_short1(xp0, half, lgN - 1, mod);\n\n      yn -= half;\n\n      if (yn < half) {\n        const double* wtab1 = mod.wtab1[lgN];\n        const double* wqinvtab1 = mod.wqinvtab1[lgN];\n\n\t// X -> (2X, w*X)\n\tfor (long j = yn; j < half; j+=PDSZ)\n\t  {\n\t    pd_full x0 = PDLD(xp0+j);\n\t    store(xp0+j, pd_LazyDoubleMod4(x0, q));\n\t    store(xp1+j, pd_LazyMulModPrecon(x0, PDLD(wtab1+j), q, PDLD(wqinvtab1+j)));\n\t  }\n      }\n\n      pd_ifft_short2(xp1, yn, lgN - 1, mod);\n\n      // (X, Y) -> (X + Y/w, X - Y/w)\n      pd_ifft_layer_inner_loop(xp0, xp1, yn, mod.wtab[lgN], mod.wqinvtab[lgN], q); \n    }\n}\n\n\nstatic void \npd_ifft_short2(double* xp, long yn, long lgN, const pd_mod_t& mod)\n\n// Implements truncated inverse FFT interface, but with xn==N.\n// All computations are done in place.\n\n{\n  long N = 1L << lgN;\n\n  if (yn == N && lgN <= NTL_PD_FFT_THRESH)\n    {\n      // no truncation\n      pd_ifft_base(xp, lgN, mod);\n      return;\n    }\n\n  // divide-and-conquer algorithm\n\n  long half = N >> 1;\n  double q = mod.q;\n\n  if (yn <= half)\n    {\n      // X -> 2X\n      for (long j = 0; j < yn; j+=PDSZ)\n     \tstore(xp+j, pd_LazyDoubleMod4(PDLD(xp+j), q));\n\n      // (X, Y) -> X + Y\n      for (long j = yn; j < half; j+=PDSZ)\n\tstore(xp+j, pd_LazyAddMod4(PDLD(xp+j), PDLD(xp+j+half), q));\n\n      pd_ifft_short2(xp, yn, lgN - 1, mod);\n\n      // (X, Y) -> X - Y\n      for (long j = 0; j < yn; j+=PDSZ)\n\tstore(xp+j, pd_LazySubMod4(PDLD(xp+j), PDLD(xp+j+half), q));\n    }\n  else\n    {\n      double* xp0 = xp;\n      double* xp1 = xp + half;\n\n      pd_ifft_short1(xp0, half, lgN - 1, mod);\n\n      yn -= half;\n\n\n      if (yn < half) {\n        const double* wtab1 = mod.wtab1[lgN];\n        const double* wqinvtab1 = mod.wqinvtab1[lgN];\n\n\t// (X, Y) -> (2X - Y, w*(X - Y))\n\tfor (long j = yn; j < half; j+=PDSZ)\n\t  {\n\t    pd_full x0 = PDLD(xp0+j);\n\t    pd_full x1 = PDLD(xp1+j);\n\t    pd_full u  = pd_LazySubMod4(x0, x1, q);\n\t    store(xp0+j, pd_LazyAddMod4(x0, u, q));\n\t    store(xp1+j, pd_LazyMulModPrecon(u, PDLD(wtab1+j), q, PDLD(wqinvtab1+j)));\n\t  }\n      }\n\n      pd_ifft_short2(xp1, yn, lgN - 1, mod);\n\n      // (X, Y) -> (X + Y/w, X - Y/w)\n      pd_ifft_layer_inner_loop(xp0, xp1, yn, mod.wtab[lgN], mod.wqinvtab[lgN], q); \n    }\n}\n\n\nvoid \npd_ifft_trunc_impl(long* A, const long* a, double* xp, long lgN, const pd_mod_t& mod, \n                   long yn, double fac)\n{\n   long N = 1L << lgN;\n\n   for (long i = 0; i < yn; i += 4*PDSZ) {\n      pd_move(xp+i+0*PDSZ, a+i+0*PDSZ);\n      pd_move(xp+i+1*PDSZ, a+i+1*PDSZ);\n      pd_move(xp+i+2*PDSZ, a+i+2*PDSZ);\n      pd_move(xp+i+3*PDSZ, a+i+3*PDSZ);\n   }\n\n   pd_ifft_short1(xp, yn, lgN, mod);\n\n   double q = mod.q;\n   double facqinv = fac/q; \n   for (long i = 0; i < yn; i += 4*PDSZ) {\n      pd_mul_move(A+i+0*PDSZ, xp+i+0*PDSZ, fac, q, facqinv);\n      pd_mul_move(A+i+1*PDSZ, xp+i+1*PDSZ, fac, q, facqinv);\n      pd_mul_move(A+i+2*PDSZ, xp+i+2*PDSZ, fac, q, facqinv);\n      pd_mul_move(A+i+3*PDSZ, xp+i+3*PDSZ, fac, q, facqinv);\n   }\n}\n\n\nvoid \npd_ifft_trunc_impl(long* A, const long* a, double* xp, long lgN, const pd_mod_t& mod, \n                   long yn)\n{\n   long N = 1L << lgN;\n\n   for (long i = 0; i < yn; i += 4*PDSZ) {\n      pd_move(xp+i+0*PDSZ, a+i+0*PDSZ);\n      pd_move(xp+i+1*PDSZ, a+i+1*PDSZ);\n      pd_move(xp+i+2*PDSZ, a+i+2*PDSZ);\n      pd_move(xp+i+3*PDSZ, a+i+3*PDSZ);\n   }\n\n   pd_ifft_short1(xp, yn, lgN, mod);\n\n   double q = mod.q;\n   for (long i = 0; i < yn; i += 4*PDSZ) {\n      pd_reduce2_move(A+i+0*PDSZ, xp+i+0*PDSZ, q);\n      pd_reduce2_move(A+i+1*PDSZ, xp+i+1*PDSZ, q);\n      pd_reduce2_move(A+i+2*PDSZ, xp+i+2*PDSZ, q);\n      pd_reduce2_move(A+i+3*PDSZ, xp+i+3*PDSZ, q);\n   }\n}\n\nNTL_END_IMPL\n\n#else\n\nvoid _ntl_pd_FFT_dummy() { }\n\n#endif\n", "meta": {"hexsha": "ff88f6f3823cd1e277e4da988fd855783ac69c50", "size": 29026, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libNTL/unix.d/src/pd_FFT.cpp", "max_stars_repo_name": "textbrowser/spot-on", "max_stars_repo_head_hexsha": "4cf5628bc588cf2de6bd070abfdc78401a965cc0", "max_stars_repo_licenses": ["PostgreSQL"], "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": "libNTL/unix.d/src/pd_FFT.cpp", "max_issues_repo_name": "kalilearner/spot-on", "max_issues_repo_head_hexsha": "6f2d802c87a88e3001cb8238f65b5d7253bc6f49", "max_issues_repo_licenses": ["PostgreSQL"], "max_issues_count": 7.0, "max_issues_repo_issues_event_min_datetime": "2016-10-18T18:26:11.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-08T14:50:04.000Z", "max_forks_repo_path": "libNTL/unix.d/src/pd_FFT.cpp", "max_forks_repo_name": "kalilearner/spot-on", "max_forks_repo_head_hexsha": "6f2d802c87a88e3001cb8238f65b5d7253bc6f49", "max_forks_repo_licenses": ["PostgreSQL"], "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": 25.5961199295, "max_line_length": 88, "alphanum_fraction": 0.6080066148, "num_tokens": 11473, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7090191214879992, "lm_q2_score": 0.4726834766204328, "lm_q1q2_score": 0.33514162333531244}}
{"text": "// MIT License\n//\n// Copyright (c) 2021 Oliver Schick\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in all\n// copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n// SOFTWARE.\n\n#ifndef MPO19_PCURE_02082020\n#define MPO19_PCURE_02082020\n\n#include <mpo19/typedefs.hpp>\n#include <mpo19/random.hpp>\n#include <mpo19/clustering.hpp>\n#include <mpo19/linkage.hpp>\n#include <mpo19/paillier_wrapper.hpp>\n#include <boost/phoenix.hpp>\n\n#include <iostream>\n#include <type_traits>\n\nnamespace mpo19\n{\n\nconstexpr struct calc_distance_t {\n    size_t operator()(point<int64_t> const& lhs\n                      , point<int64_t> const& rhs) const\n    {\n        using namespace boost::phoenix::placeholders;\n        assert(lhs.dimension() == rhs.dimension());\n        return apply_on_elements(arg1 * arg1, lhs - rhs).fold();\n    }\n\n    double operator()(point<double> const& lhs\n                      , point<int64_t> const& rhs) const\n    {\n        using namespace boost::phoenix::placeholders;\n        assert(lhs.dimension() == rhs.dimension());\n        point<double> res(lhs.dimension());\n        apply_on_elements(res, arg1 - arg2, lhs, rhs);\n        apply_on_elements(res, arg1 * arg1, res);\n        return res.fold();\n    }\n\n} calc_distance;\n\ntemplate<typename T, typename LinkagePolicy>\nstruct cluster_dist_t : public LinkagePolicy {\n\n    template<typename... Args>\n    cluster_dist_t(std::vector<point<T>> const& values, Args&&... args)\n        : LinkagePolicy{std::forward<Args>(args)...}, values_{values} {}\n\n    auto operator()(cluster const& c1, cluster const& c2)\n    {\n        auto c1_indices = get_indices(c1);\n        auto c2_indices = get_indices(c2);\n\n        size_t c1_indices_size = c1_indices.size();\n        size_t c2_indices_size = c2_indices.size();\n\n        assert(0 < c1_indices_size);\n        assert(0 < c2_indices_size);\n\n        auto res = calc_distance(values_[c1_indices[0]], values_[c2_indices[0]]);\n\n        size_t i = 0, j = 1;\n        for(; i != c1_indices_size; ++i, j = 0) {\n            for(; j != c2_indices_size; ++j) {\n                assert( !(i == 0 && j == 0) &&\n                        \"We already calculated the distance for (0, 0)\");\n                res =\n                    LinkagePolicy::cluster_distance(\n                        res, calc_distance(values_[c1_indices[i]], values_[c2_indices[j]]));\n            }\n        }\n\n        return res;\n    }\n\nprivate:\n    std::vector<point<T>> const& values_;\n};\n\ntemplate<typename T>\nstruct pcure_clusters {\n    //We use a vector<vector>, as the rows might have different sizes\n    std::vector<cluster> partition_dendrograms;\n    std::vector<point<T>> values;\n};\n\ntemplate<typename T>\nstd::ostream& operator<<(std::ostream& os, pcure_clusters<T> const& clusters)\n{\n    os << '(';\n    for(cluster const& c : clusters.partition_dendrograms) {\n        os << c;\n    }\n    os << ')';\n    os << '(';\n    for(point<T> const& p : clusters.values) {\n        os << p;\n    }\n    os << ')';\n    return os;\n}\n\ntemplate<typename T>\nstd::istream& operator>>(std::istream& is, pcure_clusters<T>& clusters)\n{\n    clusters.partition_dendrograms.clear();\n    clusters.values.clear();\n\n    char c = is.get();\n    assert(c == '(');\n\n    while(is.peek() != ')') {\n        cluster clust;\n        is >> clust;\n        clusters.partition_dendrograms.emplace_back(std::move(clust));\n    }\n\n    c = is.get();\n    assert(c == ')');\n    c = is.get();\n    assert(c == '(');\n\n    while(is.peek() != ')') {\n        point<T> p;\n        is >> p;\n        clusters.values.emplace_back(std::move(p));\n    }\n\n    return is;\n}\n\ntemplate<template<class> class LinkagePolicy>\nstruct clear_clustering_t {\n\n    template<typename RandomAccessRange>\n    auto operator()(RandomAccessRange const& partition, size_t t)\n    {\n        using dist_table_t = table_t<decltype(calc_distance(partition[0], partition[0]))>;\n        size_t n = partition.size();\n        dist_table_t dist_matrix{boost::extents[n][n]};\n\n        for(index_t  i = 0; i != index_t(n); ++i) {\n            for(index_t j = 0; j != index_t(n); ++j) {\n                dist_matrix[i][j] = calc_distance(partition[i], partition[j]);\n            }\n        }\n\n        return hierarchical_clustering<LinkagePolicy<dist_table_t>> {dist_matrix}(t);\n    }\n\n    template<typename T>\n    auto operator()(pcure_clusters<T> const& clusters, size_t t)\n    {\n        size_t n = clusters.partition_dendrograms.size();\n        table_t<T> dist_matrix{boost::extents[n][n]};\n\n        hierarchical_clustering<cluster_dist_t<T, LinkagePolicy<table_t<T>>>>\n        hc{clusters.values, dist_matrix};\n\n        cluster_dist_t<T, LinkagePolicy<table_t<T>>>& cluster_dist = hc;\n\n        for(index_t i = 0; i != index_t(n); ++i) {\n            for(index_t j = 0; j != index_t(n); ++j) {\n                if(i == j) {\n                    dist_matrix[i][j] = 0;\n                } else {\n                    dist_matrix[i][j] = cluster_dist(\n                                            clusters.partition_dendrograms[i]\n                                            , clusters.partition_dendrograms[j]);\n                }\n            }\n        }\n\n        return hc(t);\n    }\n};\n\ntemplate<typename Range>\nstd::vector<cluster> assign_clusters(\n    Range const& input\n    , std::vector<point<double>> const& centroids)\n{\n    assert(!centroids.empty());\n    std::vector<cluster> res(centroids.size());\n    size_t rank = 0;\n\n    for(size_t i = 0; i != input.size(); ++i) {\n        size_t min_index = 0;\n        double min_distance = calc_distance(centroids[0], input[i]);\n        for(size_t j = 1; j != centroids.size(); ++j) {\n            double distance = calc_distance(centroids[j], input[i]);\n            if(distance < min_distance) {\n                min_index = j;\n                min_distance = distance;\n            }\n        }\n        if(res[min_index].is_cluster()) ++rank;\n        cluster singleton{cluster::leaf_t(i)};\n        merge(res[min_index], singleton, rank);\n        assert(!singleton.is_cluster());\n    }\n    \n    res.erase(std::remove_if(res.begin(), res.end(), [](cluster const& c){\n        return !c.is_cluster();\n    }), res.end());\n\n    return res;\n}\n\ntemplate<typename T>\nvoid transform_pcure_dendrogram(\n    pcure_clusters<T>& clusters\n    , std::vector<cluster>& dendrogram\n    , size_t base_rank)\n{\n    for(cluster& c : dendrogram) {\n        assert(c.is_cluster());\n        std::vector<index_t> indices = get_indices(c);\n        assert(clusters.partition_dendrograms[indices[0]].is_cluster());\n        c = std::move(clusters.partition_dendrograms[indices[0]]);\n\n        for(size_t i = 1, rank = base_rank; i != indices.size(); ++i, ++rank) {\n            index_t idx = indices[i];\n            assert(idx < clusters.partition_dendrograms.size());\n            assert(clusters.partition_dendrograms[idx].is_cluster());\n            merge(c, clusters.partition_dendrograms[idx], rank);\n        }\n\n        assert(c.is_cluster());\n    }\n}\n\ntemplate<typename ClusteringPolicy>\nstruct pcure : public ClusteringPolicy {\n\n    template<typename... Args>\n    pcure(size_t s, size_t p, size_t q, size_t t1, size_t t2, size_t t, Args&&... args)\n        : ClusteringPolicy{std::forward<Args>(args)...}, s{s}, p{p}, q{q}, t1{t1}, t2{t2}, t{t} {}\n\n    template<typename T>\n    pcure_clusters<T> A_clustering(std::vector<point<T>>& input)\n    {\n        using boost::adaptors::sliced;\n        using boost::adaptors::filtered;\n        using boost::range::copy;\n\n        struct add_partition_idx_t : boost::static_visitor<void> {\n\n            add_partition_idx_t(size_t partition_idx)\n                : partition_idx_{partition_idx} {}\n\n            result_type operator()(cluster::union_t& u) const\n            {\n                u.get_left().visit(*this);\n                u.get_right().visit(*this);\n            }\n\n            result_type operator()(cluster::leaf_t& l) const\n            {\n                l += partition_idx_;\n            }\n\n        private:\n            size_t partition_idx_;\n        };\n\n        assert(input.size() > s &&\n               \"Cannot take a sample of size s with s being bigger than the input size\");\n        assert(s > p &&\n               \"Cannot partition s into more than s partitions\");\n        assert(s/(p*q) > 0 &&\n               \"The target clusters shall be grater than zero, i.e. s/(p*q) > 0\");\n\n        size_t const target_clusters = s/(p*q);\n\n        pcure_clusters<T> res;\n\n        res.partition_dendrograms.reserve(s/q);\n\n        //if s is not a multiple of p, then the last s % p items won't be included in any partition\n        auto sample = random_sample(input, s);\n\n        for(size_t i = 0; i != p; ++i) {\n            size_t const slice_first = i * s/p;\n            size_t const slice_last = (i+1) * s/p;\n            assert(slice_first < slice_last);\n\n            auto partition = sample | sliced(slice_first, slice_last);\n\n            auto dendrogram = static_cast<ClusteringPolicy&>(*this)(partition, target_clusters);\n            auto filtered_dendrogram = dendrogram | filtered([&](cluster const& c) -> bool {\n                return get_indices(c).size() >= t1;\n            });\n\n            for(cluster& c : filtered_dendrogram) {\n                if(slice_first != 0)\n                    c.visit(add_partition_idx_t{slice_first});\n                res.partition_dendrograms.emplace_back(std::move(c));\n            }\n        }\n        res.values = std::move(sample);\n\n        return res;\n    }\n\n    template<typename T>\n    pcure_clusters<T> B_clustering(pcure_clusters<T>& clusters)\n    {\n        using boost::range::remove_if;\n\n        assert(clusters.partition_dendrograms.size() <= s/q);\n\n        //The result in this context is the merge history of input clusters,\n        //therefore we need to convert it to a merge history of indices\n        auto dendrogram = static_cast<ClusteringPolicy&>(*this)(clusters, t);\n        size_t base_rank = s/p - s/(p*q) + 1;\n\n        for(cluster& c : dendrogram) {\n            assert(c.is_cluster());\n            std::vector<index_t> indices = get_indices(c);\n            assert(clusters.partition_dendrograms[indices[0]].is_cluster());\n            c = std::move(clusters.partition_dendrograms[indices[0]]);\n\n            for(size_t i = 1, rank = base_rank; i != indices.size(); ++i, ++rank) {\n                assert(clusters.partition_dendrograms[indices[i]].is_cluster());\n                merge(c, clusters.partition_dendrograms[indices[i]], rank);\n            }\n\n            assert(c.is_cluster());\n        }\n\n        dendrogram.erase(remove_if(dendrogram, [&](cluster const& c) {\n            return get_indices(c).size() < t2;\n        })\n        , dendrogram.end());\n\n        clusters.partition_dendrograms = std::move(dendrogram);\n\n        return std::move(clusters);\n    }\n\n    template<typename T>\n    std::vector<point<double>> get_cluster_centroids(std::vector<point<T>> const& input)\n    {\n        using namespace boost::phoenix::placeholders;\n\n        std::vector<point<T>> in{input};\n        auto C_A = A_clustering(in);\n        auto C_B = B_clustering(C_A);\n\n        std::vector<point<double>> centroids;\n        centroids.reserve(C_B.partition_dendrograms.size());\n        for(cluster const& c : C_B.partition_dendrograms) {\n            std::vector<index_t> indices = get_indices(c);\n            point<double> sum(C_B.values.front().dimension(), 0.0);\n            for(index_t i : indices) {\n                apply_on_elements(sum, arg1 + arg2, sum, C_B.values[i]);\n            }\n            apply_on_elements(sum, arg1/indices.size(), sum);\n            centroids.emplace_back(std::move(sum));\n        }\n\n        return centroids;\n    }\n\n    template<typename T>\n    std::vector<cluster> assign_clusters(\n        std::vector<point<T>> const& input\n        , std::vector<point<double>> const& centroids)\n    {\n        return ::mpo19::assign_clusters(input, centroids);\n    }\n\nprivate:\n    size_t s, p, q, t1, t2, t;\n};\n\n}\n\n#endif //MPO19_PCURE_02082020\n", "meta": {"hexsha": "922acf9f9f423685c581035b4486655a64a9d10d", "size": 12861, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "hc_protocols/include/mpo19/pcure.hpp", "max_stars_repo_name": "encryptogroup/SoK_ppClustering", "max_stars_repo_head_hexsha": "6b008a09bfe3f3b8074e24059ac3e2aa6b87f227", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2021-06-18T08:09:46.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-19T05:41:24.000Z", "max_issues_repo_path": "hc_protocols/include/mpo19/pcure.hpp", "max_issues_repo_name": "encryptogroup/SoK_ppClustering", "max_issues_repo_head_hexsha": "6b008a09bfe3f3b8074e24059ac3e2aa6b87f227", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "hc_protocols/include/mpo19/pcure.hpp", "max_forks_repo_name": "encryptogroup/SoK_ppClustering", "max_forks_repo_head_hexsha": "6b008a09bfe3f3b8074e24059ac3e2aa6b87f227", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.1525, "max_line_length": 99, "alphanum_fraction": 0.5944327813, "num_tokens": 3076, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6548947425132314, "lm_q2_score": 0.5117166047041654, "lm_q1q2_score": 0.3351205140774794}}
{"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#include \"theia/sfm/camera/camera.h\"\n\n#include <ceres/rotation.h>\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n#include <glog/logging.h>\n\n#include \"theia/sfm/camera/projection_matrix_utils.h\"\n#include \"theia/sfm/camera/project_point_to_image.h\"\n#include \"theia/sfm/camera/radial_distortion.h\"\n\nnamespace theia {\n\nusing Eigen::AngleAxisd;\nusing Eigen::Map;\nusing Eigen::Matrix;\nusing Eigen::Matrix3d;\nusing Eigen::Vector2d;\nusing Eigen::Vector3d;\nusing Eigen::Vector4d;\n\nCamera::Camera() {\n  // Set rotation and position to zero (i.e. identity).\n  Map<Matrix<double, 1, 6> >(mutable_extrinsics()).setZero();\n\n  SetFocalLength(1.0);\n  SetAspectRatio(1.0);\n  SetSkew(0.0);\n  SetPrincipalPoint(0.0, 0.0);\n  SetRadialDistortion(0.0, 0.0);\n\n  image_size_[0] = 0;\n  image_size_[1] = 0;\n}\n\nbool Camera::InitializeFromProjectionMatrix(\n      const int image_width,\n      const int image_height,\n      const Matrix3x4d projection_matrix) {\n  DCHECK_GT(image_width, 0);\n  DCHECK_GT(image_height, 0);\n  image_size_[0] = image_width;\n  image_size_[1] = image_height;\n\n  Vector3d orientation, position;\n  Matrix3d calibration_matrix;\n  DecomposeProjectionMatrix(projection_matrix,\n                            &calibration_matrix,\n                            &orientation,\n                            &position);\n\n  Map<Vector3d>(mutable_extrinsics() + ORIENTATION) = orientation;\n  Map<Vector3d>(mutable_extrinsics() + POSITION) = position;\n\n  if (calibration_matrix(0, 0) == 0 || calibration_matrix(1, 1) == 0) {\n    LOG(INFO) << \"Cannot set focal lengths to zero!\";\n    return false;\n  }\n\n  CalibrationMatrixToIntrinsics(calibration_matrix,\n                                mutable_intrinsics() + FOCAL_LENGTH,\n                                mutable_intrinsics() + SKEW,\n                                mutable_intrinsics() + ASPECT_RATIO,\n                                mutable_intrinsics() + PRINCIPAL_POINT_X,\n                                mutable_intrinsics() + PRINCIPAL_POINT_Y);\n  return true;\n}\n\nvoid Camera::GetProjectionMatrix(Matrix3x4d* pmatrix) const {\n  Matrix3d calibration_matrix;\n  GetCalibrationMatrix(&calibration_matrix);\n  ComposeProjectionMatrix(calibration_matrix,\n                          GetOrientationAsAngleAxis(),\n                          GetPosition(),\n                          pmatrix);\n}\n\nvoid Camera::GetCalibrationMatrix(Matrix3d* kmatrix) const {\n  IntrinsicsToCalibrationMatrix(FocalLength(),\n                                Skew(),\n                                AspectRatio(),\n                                PrincipalPointX(),\n                                PrincipalPointY(),\n                                kmatrix);\n}\n\ndouble Camera::ProjectPoint(const Vector4d& point, Vector2d* pixel) const {\n  return ProjectPointToImage(extrinsics(),\n                             intrinsics(),\n                             point.data(),\n                             pixel->data());\n}\n\nVector3d Camera::PixelToUnitDepthRay(const Vector2d& pixel) const {\n  // Remove the effect of calibration.\n  const Vector3d undistorted_point = PixelToNormalizedCoordinates(pixel);\n\n  // Apply rotation.\n  const Matrix3d& rotation = GetOrientationAsRotationMatrix();\n  const Vector3d direction = rotation.transpose() * undistorted_point;\n  return direction;\n}\n\nVector3d Camera::PixelToNormalizedCoordinates(const Vector2d& pixel) const {\n  // First, undo the calibration.\n  const double focal_length_y = FocalLength() * AspectRatio();\n  const double y_normalized = (pixel[1] - PrincipalPointY()) / focal_length_y;\n  const double x_normalized =\n      (pixel[0] - PrincipalPointX() - y_normalized * Skew()) / FocalLength();\n\n  // Undo radial distortion.\n  const Vector2d normalized_point(x_normalized, y_normalized);\n  Vector2d undistorted_pixel;\n  RadialUndistortPoint(normalized_point,\n                       RadialDistortion1(),\n                       RadialDistortion2(),\n                       &undistorted_pixel);\n  const Vector3d undistorted_point = undistorted_pixel.homogeneous();\n  return undistorted_point;\n}\n\n  // ----------------------- Getter and Setter methods ---------------------- //\nvoid Camera::SetPosition(const Vector3d& position) {\n  Map<Vector3d>(mutable_extrinsics() + POSITION) = position;\n}\n\nVector3d Camera::GetPosition() const {\n  return Map<const Vector3d>(extrinsics() + POSITION);\n}\n\nvoid Camera::SetOrientationFromRotationMatrix(const Matrix3d& rotation) {\n  ceres::RotationMatrixToAngleAxis(\n      ceres::ColumnMajorAdapter3x3(rotation.data()),\n      mutable_extrinsics() + ORIENTATION);\n}\n\nvoid Camera::SetOrientationFromAngleAxis(const Vector3d& angle_axis) {\n  Map<Vector3d>(mutable_extrinsics() + ORIENTATION) = angle_axis;\n}\n\nMatrix3d Camera::GetOrientationAsRotationMatrix() const {\n  Matrix3d rotation;\n  ceres::AngleAxisToRotationMatrix(\n      extrinsics() + ORIENTATION,\n      ceres::ColumnMajorAdapter3x3(rotation.data()));\n  return rotation;\n}\n\nVector3d Camera::GetOrientationAsAngleAxis() const {\n  return Map<const Vector3d>(extrinsics() + ORIENTATION);\n}\n\nvoid Camera::SetFocalLength(const double focal_length) {\n  mutable_intrinsics()[FOCAL_LENGTH] = focal_length;\n}\n\ndouble Camera::FocalLength() const {\n  return intrinsics()[FOCAL_LENGTH];\n}\n\nvoid Camera::SetAspectRatio(const double aspect_ratio) {\n  mutable_intrinsics()[ASPECT_RATIO] = aspect_ratio;\n}\ndouble Camera::AspectRatio() const {\n  return intrinsics()[ASPECT_RATIO];\n}\n\nvoid Camera::SetSkew(const double skew) {\n  mutable_intrinsics()[SKEW] = skew;\n}\n\ndouble Camera::Skew() const {\n  return intrinsics()[SKEW];\n}\n\nvoid Camera::SetPrincipalPoint(const double principal_point_x,\n                               const double principal_point_y) {\n  mutable_intrinsics()[PRINCIPAL_POINT_X] = principal_point_x;\n  mutable_intrinsics()[PRINCIPAL_POINT_Y] = principal_point_y;\n}\n\ndouble Camera::PrincipalPointX() const {\n  return intrinsics()[PRINCIPAL_POINT_X];\n}\n\ndouble Camera::PrincipalPointY() const {\n  return intrinsics()[PRINCIPAL_POINT_Y];\n}\n\nvoid Camera::SetRadialDistortion(const double radial_distortion_1,\n                                 const double radial_distortion_2) {\n  mutable_intrinsics()[RADIAL_DISTORTION_1] = radial_distortion_1;\n  mutable_intrinsics()[RADIAL_DISTORTION_2] = radial_distortion_2;\n}\n\ndouble Camera::RadialDistortion1() const {\n  return intrinsics()[RADIAL_DISTORTION_1];\n}\n\ndouble Camera::RadialDistortion2() const {\n  return intrinsics()[RADIAL_DISTORTION_2];\n}\n\nvoid Camera::SetImageSize(const int image_width, const int image_height) {\n  image_size_[0] = image_width;\n  image_size_[1] = image_height;\n}\n\n}  // namespace theia\n", "meta": {"hexsha": "d6c19594058ef2c8dec48fb4857cc30f3bb92cab", "size": 8382, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/theia/sfm/camera/camera.cc", "max_stars_repo_name": "LEON-MING/TheiaSfM_Leon", "max_stars_repo_head_hexsha": "8ac187b80100ad7f52fe9af49fa4a0db6db226b9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/theia/sfm/camera/camera.cc", "max_issues_repo_name": "LEON-MING/TheiaSfM_Leon", "max_issues_repo_head_hexsha": "8ac187b80100ad7f52fe9af49fa4a0db6db226b9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/theia/sfm/camera/camera.cc", "max_forks_repo_name": "LEON-MING/TheiaSfM_Leon", "max_forks_repo_head_hexsha": "8ac187b80100ad7f52fe9af49fa4a0db6db226b9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.3524590164, "max_line_length": 80, "alphanum_fraction": 0.6913624433, "num_tokens": 1912, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6548947290421275, "lm_q2_score": 0.5117166047041654, "lm_q1q2_score": 0.33512050718409186}}
{"text": "// based on Eigen unsupported bvh KDTree\n\n#pragma once\n\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n#include <Eigen/StdVector>\n#include <algorithm>\n#include <queue>\n\n#include \"rpxdock/bvh/bvh_algo.hpp\"\n#include \"rpxdock/geom/primitive.hpp\"\n#include \"rpxdock/util/types.hpp\"\n\nnamespace rpxdock {\nnamespace bvh {\n\nusing namespace geom;\nusing namespace Eigen;\n\n// internal pair class for the BVH--used instead of std::pair because of\n// alignment\ntemplate <class F, int DIM>\nstruct VintPair {\n  using first_type = Matrix<F, DIM, 1>;\n  using secont_type = int;\n  EIGEN_MAKE_ALIGNED_OPERATOR_NEW_IF_VECTORIZABLE_FIXED_SIZE(F, DIM)\n  VintPair(const first_type &v, int i) : first(v), second(i) {}\n  first_type first;\n  int second;\n};\n\n// these templates help the tree initializer get the bounding spheres either in\n// from a provided iterator range or using bounding_vol in a unified way\ntemplate <typename Objs, typename Vols, typename Iter>\nstruct get_bvols_helper {\n  void operator()(const Objs &objs, Iter sphbeg, Iter sphend, Vols &out) {\n    out.insert(out.end(), sphbeg, sphend);\n    eigen_assert(out.size() == objs.size());\n  }\n};\n\ntemplate <typename Objs, typename Vols>\nstruct get_bvols_helper<Objs, Vols, int> {\n  void operator()(const Objs &objs, int, int, Vols &out) {\n    out.reserve(objs.size());\n    for (int i = 0; i < (int)objs.size(); ++i)\n      out.push_back(bounding_vol(objs[i]));\n  }\n};\n\ntemplate <class RAiter>\nstruct P1Range {\n  using value_type = typename RAiter::value_type::first_type;\n  RAiter a, b;\n  auto const &operator[](size_t i) const { return (a + i)->first; }\n  auto &operator[](size_t i) { return (a + i)->first; }\n  size_t size() const { return b - a; }\n  auto get_index(size_t i) const { return (a + i)->second; }\n};\ntemplate <class RAiter>\nauto p1range(RAiter a, RAiter b) {\n  P1Range<RAiter> r;\n  r.a = a;\n  r.b = b;\n  return r;\n}\n\ntemplate <typename F, bool idrange = false>\nstruct WelzlBoundingSphere {\n  static Sphere<F> bound(auto subtree_objs) {\n    return welzl_bounding_sphere<true>(subtree_objs);\n  }\n};\n\ntemplate <typename _Scalar, typename _Object, int _DIM = 3,\n          typename _Volume = Sphere<_Scalar>,\n          typename BoundingSphere = WelzlBoundingSphere<_Scalar, true>>\nclass SphereBVH {\n public:\n  static int const DIM = _DIM;\n  typedef _Object Object;\n  typedef std::vector<Object, Eigen::aligned_allocator<Object>> Objs;\n  typedef _Scalar F;\n  // typedef Eigen::AlignedBox<F, DIM> Volume;\n  typedef _Volume Volume;\n  typedef std::vector<Volume, Eigen::aligned_allocator<Volume>> Vols;\n  typedef int Index;\n  typedef const int *VolumeIterator;  // the iterators are just pointers into\n                                      // the tree's vectors\n  typedef const Object *ObjectIterator;\n\n  std::vector<int> child;  // child of x are child[2x] and\n                           // child[2x+1], indices bigger than\n                           // vols.size() index into objs.\n  Vols vols;\n  Objs objs;\n\n  SphereBVH() {}\n\n  template <typename Iter>\n  SphereBVH(Iter begin, Iter end) {\n    init(begin, end, 0, 0);\n  }  // int is recognized by init as not being an iterator type\n\n  template <typename OIter, typename BIter>\n  SphereBVH(OIter begin, OIter end, BIter sphbeg, BIter sphend) {\n    init(begin, end, sphbeg, sphend);\n  }\n\n  size_t size() const { return objs.size(); }\n\n  /** Given an iterator range over \\a Object references, constructs the BVH,\n   * overwriting whatever is in there currently.\n   * Requires that bounding_vol(Object) return a Volume. */\n  template <typename Iter>\n  void init(Iter begin, Iter end) {\n    init(begin, end, 0, 0);\n  }\n\n  /** Given an iterator range over \\a Object references and an iterator range\n   * over their bounding vols,\n   * constructs the BVH, overwriting whatever is in there currently. */\n  template <typename OIter, typename BIter>\n  void init(OIter begin, OIter end, BIter sphbeg, BIter sphend) {\n    objs.clear();\n    vols.clear();\n    child.clear();\n\n    objs.insert(objs.end(), begin, end);\n    int n = static_cast<int>(objs.size());\n\n    // if we have at most one object, we don't need any internal nodes\n    if (n < 2) return;\n\n    Vols ovol;\n    VIPairs ocen;\n\n    // compute the bounding vols depending on BIter type\n    get_bvols_helper<Objs, Vols, BIter>()(objs, sphbeg, sphend, ovol);\n\n    ocen.reserve(n);\n    vols.reserve(n - 1);\n    child.reserve(2 * n - 2);\n\n    for (int i = 0; i < n; ++i) ocen.push_back(VIPair(ovol[i].cen, i));\n\n    // the recursive part of the algorithm\n    build(ocen, 0, n, ovol, 0);\n\n    Objs tmp(n);\n    tmp.swap(objs);\n    for (int i = 0; i < n; ++i) objs[i] = tmp[ocen[i].second];\n  }\n\n  /** \\returns the index of the root of the hierarchy */\n  inline Index getRootIndex() const { return (int)vols.size() - 1; }\n\n  /** Given an \\a index of a node, on exit, \\a vbeg and \\a vend range\n   * over the indices of the volume children of the node\n   * and \\a obeg and \\a oend range over the object children of the node\n   */\n  EIGEN_STRONG_INLINE\n  void getChildren(Index index, VolumeIterator &vbeg, VolumeIterator &vend,\n                   ObjectIterator &obeg, ObjectIterator &oend) const {\n    // inlining this function should open lots of optimization opportunities to\n    // the compiler\n    if (index < 0) {\n      vbeg = vend;\n      if (!objs.empty()) obeg = &(objs[0]);\n      oend = obeg + objs.size();  // output all objs--necessary\n                                  // when the tree has only one\n                                  // object\n      return;\n    }\n\n    int nvol = static_cast<int>(vols.size());\n\n    int idx = index * 2;\n    if (child[idx + 1] < nvol) {  // second index is always bigger\n      vbeg = &(child[idx]);\n      vend = vbeg + 2;\n      obeg = oend;\n    } else if (child[idx] >= nvol) {  // if both child are objs\n      vbeg = vend;\n      obeg = &(objs[child[idx] - nvol]);\n      oend = obeg + 2;\n    } else {  // if the first child is a volume and the second is an object\n      vbeg = &(child[idx]);\n      vend = vbeg + 1;\n      obeg = &(objs[child[idx + 1] - nvol]);\n      oend = obeg + 1;\n    }\n    // std::cout << \" gc\" << vend - vbeg;\n  }\n\n  inline const Volume &getVolume(Index index) const { return vols[index]; }\n\n private:\n  typedef VintPair<F, DIM> VIPair;\n  typedef std::vector<VIPair, Eigen::aligned_allocator<VIPair>> VIPairs;\n  typedef Eigen::Matrix<F, DIM, 1> VectorType;\n\n  struct AxisComparator {\n    int dim;\n    AxisComparator(int inDim) : dim(inDim) {}\n    inline bool operator()(const VIPair &v1, const VIPair &v2) const {\n      return v1.first[dim] < v2.first[dim];\n    }\n  };\n  struct DotComparator {\n    Matrix<F, DIM, 1> normal;\n    DotComparator(Matrix<F, DIM, 1> n) : normal(n) {}\n    template <class Pair>\n    DotComparator(Pair p) : normal(p.second - p.first) {}\n    inline bool operator()(const VIPair &v1, const VIPair &v2) const {\n      return v1.first.dot(normal) < v2.first.dot(normal);\n    }\n  };\n\n  // Build the part of the tree between objs[from] and objs[to] (not\n  // including objs[to]). This routine partitions the ocen in [from, to) along\n  // the dimension dim, recursively constructs the two halves, and adds their\n  // parent node.  TODO: a cache-friendlier layout\n  void build(VIPairs &ocen, int from, int to, Vols const &ovol,\n             int dim) noexcept {\n    eigen_assert(to - from > 1);\n    if (to - from == 2) {\n      auto merge = ovol[ocen[from].second].merged(ovol[ocen[from + 1].second]);\n      vols.push_back(merge);\n      child.push_back(from + (int)objs.size() - 1);\n      child.push_back(from + (int)objs.size());\n    } else if (to - from == 3) {\n      int mid = from + 2;\n      auto subtree_objs = p1range(ocen.begin() + from, ocen.begin() + to);\n      nth_element(ocen.begin() + from, ocen.begin() + mid, ocen.begin() + to,\n                  DotComparator(most_separated_points_on_AABB(subtree_objs)));\n      // AxisComparator(dim));\n      build(ocen, from, mid, ovol, (dim + 1) % DIM);\n      int idx1 = (int)vols.size() - 1;\n      Volume bound = BoundingSphere::bound(subtree_objs);\n      vols.push_back(bound);\n      // Volume merge = vols[idx1].merged(ovol[ocen[mid].second]);\n      // if (merge.rad + 0.0001 < bound.rad)\n      // std::cout << \"!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\" << std::endl;\n      // vols.push_back(bound.rad < merge.rad ? bound : merge);\n      child.push_back(idx1);\n      child.push_back(mid + (int)objs.size() - 1);\n    } else {\n      int mid = from + (to - from) / 2;\n      auto subtree_objs = p1range(ocen.begin() + from, ocen.begin() + to);\n      nth_element(ocen.begin() + from, ocen.begin() + mid, ocen.begin() + to,\n                  DotComparator(most_separated_points_on_AABB(subtree_objs)));\n      // AxisComparator(dim));\n      build(ocen, from, mid, ovol, (dim + 1) % DIM);\n      int idx1 = (int)vols.size() - 1;\n      build(ocen, mid, to, ovol, (dim + 1) % DIM);\n      int idx2 = (int)vols.size() - 1;\n      Volume bound = BoundingSphere::bound(subtree_objs);\n      vols.push_back(bound);\n      // Volume merge = vols[idx1].merged(vols[idx2]);\n      // if (merge.rad + 0.0001 < bound.rad)\n      // std::cout << \"!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\" << std::endl;\n      // vols.push_back(bound.rad < merge.rad ? bound : merge);\n      child.push_back(idx1);\n      child.push_back(idx2);\n    }\n  }\n};\n}  // namespace bvh\n}  // namespace rpxdock\n", "meta": {"hexsha": "0b2ffd9994080d9fdc7ea019174b1d411a897333", "size": 9302, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "rpxdock/bvh/bvh.hpp", "max_stars_repo_name": "quecloud/rpxdock", "max_stars_repo_head_hexsha": "41f7f98f5dacf24fc95897910263a0bec2209e59", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "rpxdock/bvh/bvh.hpp", "max_issues_repo_name": "quecloud/rpxdock", "max_issues_repo_head_hexsha": "41f7f98f5dacf24fc95897910263a0bec2209e59", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "rpxdock/bvh/bvh.hpp", "max_forks_repo_name": "quecloud/rpxdock", "max_forks_repo_head_hexsha": "41f7f98f5dacf24fc95897910263a0bec2209e59", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-04-13T20:07:52.000Z", "max_forks_repo_forks_event_max_datetime": "2020-04-13T20:07:52.000Z", "avg_line_length": 34.1985294118, "max_line_length": 79, "alphanum_fraction": 0.627284455, "num_tokens": 2641, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6548947155710234, "lm_q2_score": 0.5117166047041654, "lm_q1q2_score": 0.33512050029070417}}
{"text": "#include \"Rational.h\"\n\n#include <boost/archive/text_oarchive.hpp>\n#include <boost/archive/text_iarchive.hpp>\n\ntemplate <typename Archive>\nvoid Rational::serialize(Archive & ar, unsigned int const version) {\n  if (version > 0) {\n  } else {\n  }\n  ar & fraction;\n}\n\ntemplate void Rational::serialize<boost::archive::text_oarchive>(boost::archive::text_oarchive&, unsigned int const);\ntemplate void Rational::serialize<boost::archive::text_iarchive>(boost::archive::text_iarchive&, unsigned int const);\n\nRational::Rational() : Rational(std::make_pair(0, 1)) { }\n\nRational::Rational(Fraction const & fraction_set) : fraction(Cancel(fraction_set)){ }\n\nRational::Rational(int numerator, unsigned int denominator) : Rational(std::make_pair(numerator, denominator)) { }\n\nRational::Rational(mpq_class q) : Rational(q.get_num().get_si(), q.get_den().get_ui()) { }\n\nFraction Rational::get_fraction() const { return fraction; }\n\nbool Rational::IsPositive() const { return fraction.first > 0; }\nbool Rational::IsNegative() const { return fraction.first < 0; }\nbool Rational::IsZero()     const { return fraction.first == 0; }\n\nvoid Rational::DivideByTwo() {\n  if (fraction.first % 2 == 0) {\n    fraction.first = fraction.first / 2;\n  } else {\n    fraction.second = fraction.second * 2;\n  }\n}\n\nvoid Rational::Negate() {\n  fraction.first = -1 * fraction.first;\n}\n\nFraction Rational::Cancel(Fraction const & fraction_set) {\n  unsigned int gcd { GreatestCommonDivisor(fraction_set) };\n  return std::make_pair(fraction_set.first / static_cast<int>(gcd), fraction_set.second / gcd);\n}\n\nunsigned int Rational::LeastCommonMultiple(Fraction const & fraction) {\n  if (fraction.first == 0) {\n    return 0;\n  }\n  unsigned int gcd = GreatestCommonDivisor(fraction);\n\n  if (fraction.first < 0) {\n    return (static_cast<unsigned int>(-fraction.first) * fraction.second) / gcd;\n  } else {\n    return (static_cast<unsigned int>(fraction.first) * fraction.second) / gcd;\n  }\n}\n\nunsigned int Rational::GreatestCommonDivisor(Fraction const & fraction) {\n  return (fraction.first < 0 ? GreatestCommonDivisor(std::make_pair(-fraction.first, fraction.second)) : (fraction.second == 0 ? fraction.first : GreatestCommonDivisor(std::make_pair(fraction.second, fraction.first % fraction.second))));\n}\n\nRational Rational::AddOther (Rational const & other) const {\n  return Rational(fraction.first * other.fraction.second + fraction.second * other.fraction.first, fraction.second * other.fraction.second);\n}\n\nRational Rational::SubtractOther (Rational const & other) const {\n  return Rational(fraction.first * other.fraction.second - fraction.second * other.fraction.first, fraction.second * other.fraction.second);\n}\n\nRational Rational::DivideOther (Rational const & other) const {\n  int numerator = fraction.first * static_cast<int>(other.fraction.second);\n  int denominator = static_cast<int>(fraction.second) * other.fraction.first;\n\n  if (numerator * denominator < 0) {\n    return Rational(-1 * std::abs(numerator), static_cast<unsigned int>(std::abs(denominator)));\n  } else {\n    return Rational(std::abs(numerator), static_cast<unsigned int>(std::abs(denominator)));\n  }\n}\n\nRational Rational::MultiplyOther (Rational const & other) const {\n  return Rational(fraction.first * other.fraction.first, fraction.second * other.fraction.second);\n}\n\nstd::string const Rational::ToString(bool plus_sign) const {\n  std::string ret_string = \"\";\n  if (fraction.first == 0) {\n    if (plus_sign) {\n      return \"+ 0\";\n    } else {\n      return \"0\";\n    }\n  } else if (fraction.first > 0) {\n    if (plus_sign) {\n      ret_string += \"+ \";\n    }\n  } else {\n    ret_string += \"- \";\n  }\n\n  ret_string += std::to_string(std::abs(fraction.first));\n\n  if (fraction.second == 1) {\n    return ret_string;\n  }\n\n  ret_string += \"/\";\n  ret_string += std::to_string(fraction.second);\n\n  return ret_string;\n} \n\nbool Rational::operator== (Rational const & other) const { return (fraction.first == other.fraction.first) && (fraction.second == other.fraction.second); }\nbool Rational::operator!= (Rational const & other) const { return !(*this == other); }\nbool Rational::operator< (Rational const & other) const { return this->SubtractOther(other).fraction.first < 0; }\nbool Rational::operator> (Rational const & other) const { return other < *this; }\nbool Rational::operator<= (Rational const & other) const { return !(*this > other); }\nbool Rational::operator>= (Rational const & other) const { return !(*this < other); }\n\n", "meta": {"hexsha": "1332afd595d0cfcef5d755fc51ee4f3fe39e4927", "size": 4460, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Rational.cpp", "max_stars_repo_name": "nilsalex/tensor-algebra", "max_stars_repo_head_hexsha": "e878cb528dea7e17225f9a27c75e978d5a5aa216", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Rational.cpp", "max_issues_repo_name": "nilsalex/tensor-algebra", "max_issues_repo_head_hexsha": "e878cb528dea7e17225f9a27c75e978d5a5aa216", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-01-25T12:17:54.000Z", "max_issues_repo_issues_event_max_datetime": "2018-01-25T12:17:54.000Z", "max_forks_repo_path": "src/Rational.cpp", "max_forks_repo_name": "nilsalex/tensor-algebra", "max_forks_repo_head_hexsha": "e878cb528dea7e17225f9a27c75e978d5a5aa216", "max_forks_repo_licenses": ["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.2601626016, "max_line_length": 237, "alphanum_fraction": 0.7060538117, "num_tokens": 1093, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5583269943353745, "lm_q2_score": 0.6001883592602051, "lm_q1q2_score": 0.33510136266083024}}
{"text": "#include <assert.h>\n#include <stdio.h>\n#include <stdint.h>\n#include <stdlib.h>\n#include <string.h>\n\n#include <NTL/GF2X.h>\n#include <NTL/GF2XFactoring.h>\n#include <NTL/GF2E.h>\n#include <NTL/GF2EX.h>\n#include <NTL/GF2EXFactoring.h>\n\n#include \"gcm.h\"\n\nusing namespace std;\nusing namespace NTL;\n\nint main(int argc, char **argv)\n{\n    struct slice a1, c1, t1, a2, c2, h;\n    struct slice *sp[] = {&a1, &c1, &t1, &a2, &c2, &h};\n    int i;\n    GF2E x, y, z;\n    GF2EX p1, p2;\n    char out[2*blocklen + 1];\n\n    argc -= 1;\n    argv += 1;\n\n    assert(argc == 6);\n\n    for (i = 0; i < argc; i += 1) {\n        hex2bytes(sp[i], argv[i]);\n    }\n\n    initfield();\n\n    block2felem(x, &h);\n    block2felem(y, &t1);\n    buildpoly(p1, &a1, &c1, &t1);\n    eval(z, p1, x);\n\n    buildpoly(p2, &a2, &c2, &t1);\n    add(p2, p2, y);\n    add(p2, p2, z);\n    eval(z, p2, x);\n\n    felem2hex(out, z);\n    printf(\"%s\\n\", out);\n\n    return 0;\n}\n", "meta": {"hexsha": "f959a7003c09c49b8ad5a89f1b44e1c3ff4cd421", "size": 915, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tool/forge.cpp", "max_stars_repo_name": "nonce-disrespect/nonce-disrespect", "max_stars_repo_head_hexsha": "425524519779c27dd74c2b51d436f5d3de8d364d", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 119.0, "max_stars_repo_stars_event_min_datetime": "2016-05-19T15:39:49.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-15T23:01:02.000Z", "max_issues_repo_path": "tool/forge.cpp", "max_issues_repo_name": "nonce-disrespect/nonce-disrespect", "max_issues_repo_head_hexsha": "425524519779c27dd74c2b51d436f5d3de8d364d", "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": "tool/forge.cpp", "max_forks_repo_name": "nonce-disrespect/nonce-disrespect", "max_forks_repo_head_hexsha": "425524519779c27dd74c2b51d436f5d3de8d364d", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2016-05-20T09:26:56.000Z", "max_forks_repo_forks_event_max_datetime": "2019-12-30T08:49:31.000Z", "avg_line_length": 17.2641509434, "max_line_length": 55, "alphanum_fraction": 0.5431693989, "num_tokens": 362, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7520125737597972, "lm_q2_score": 0.44552953503957266, "lm_q1q2_score": 0.3350438123311148}}
{"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#pragma once\n\n#include <functional>\n\n#if HAVE_LIBCLIPPER\n#include <clipper/core/coords.h>\n#endif\n\n#include <boost/math/quaternion.hpp>\n\nnamespace mmcif\n{\n\ntypedef boost::math::quaternion<float>\tQuaternion;\n\nconst double\n\tkPI = 3.141592653589793238462643383279502884;\n\n// --------------------------------------------------------------------\n\n//\tPoint, a location with x, y and z coordinates as floating point.\n//\tThis one is derived from a tuple<float,float,float> so\n//\tyou can do things like:\n//\n//\tfloat x, y, z;\n//\ttie(x, y, z) = atom.loc();\n\ntemplate<typename F>\nstruct PointF\n{\n\ttypedef F FType;\n\n\tFType mX, mY, mZ;\n\t\n\tPointF()\t\t\t\t\t\t\t: mX(0), mY(0), mZ(0) {}\n\tPointF(FType x, FType y, FType z)\t: mX(x), mY(y), mZ(z) {}\n\n\ttemplate<typename PF>\n\tPointF(const PointF<PF>& pt)\n\t\t: mX(static_cast<F>(pt.mX))\n\t\t, mY(static_cast<F>(pt.mY))\n\t\t, mZ(static_cast<F>(pt.mZ)) {}\n\n#if HAVE_LIBCLIPPER\t\n\tPointF(const clipper::Coord_orth& pt): mX(pt[0]), mY(pt[1]), mZ(pt[2]) {}\n\n\tPointF& operator=(const clipper::Coord_orth& rhs)\n\t{\n\t\tmX = rhs[0];\n\t\tmY = rhs[1];\n\t\tmZ = rhs[2];\n\t\treturn *this;\n\t}\n#endif\n\n\ttemplate<typename PF>\n\tPointF& operator=(const PointF<PF>& rhs)\n\t{\n\t\tmX = static_cast<F>(rhs.mX);\n\t\tmY = static_cast<F>(rhs.mY);\n\t\tmZ = static_cast<F>(rhs.mZ);\n\t\treturn *this;\n\t}\n\t\n\tFType& getX()\t\t\t{ return mX; }\n\tFType getX() const\t\t{ return mX; }\n\tvoid setX(FType x)\t\t{ mX = x; }\n\n\tFType& getY()\t\t\t{ return mY; }\n\tFType getY() const\t\t{ return mY; }\n\tvoid setY(FType y)\t\t{ mY = y; }\n\n\tFType& getZ()\t\t\t{ return mZ; }\n\tFType getZ() const\t\t{ return mZ; }\n\tvoid setZ(FType z)\t\t{ mZ = z; }\n\t\n\tPointF& operator+=(const PointF& rhs)\n\t{\n\t\tmX += rhs.mX;\n\t\tmY += rhs.mY;\n\t\tmZ += rhs.mZ;\n\t\t\n\t\treturn *this;\n\t}\n\t\n\tPointF& operator+=(FType d)\n\t{\n\t\tmX += d;\n\t\tmY += d;\n\t\tmZ += d;\n\t\t\n\t\treturn *this;\n\t}\n\n\tPointF& operator-=(const PointF& rhs)\n\t{\n\t\tmX -= rhs.mX;\n\t\tmY -= rhs.mY;\n\t\tmZ -= rhs.mZ;\n\t\t\n\t\treturn *this;\n\t}\n\n\tPointF& operator-=(FType d)\n\t{\n\t\tmX -= d;\n\t\tmY -= d;\n\t\tmZ -= d;\n\t\t\n\t\treturn *this;\n\t}\n\n\tPointF& operator*=(FType rhs)\n\t{\n\t\tmX *= rhs;\n\t\tmY *= rhs;\n\t\tmZ *= rhs;\n\t\treturn *this;\n\t}\n\t\n\tPointF& operator/=(FType rhs)\n\t{\n\t\tmX /= rhs;\n\t\tmY /= rhs;\n\t\tmZ /= rhs;\n\t\treturn *this;\n\t}\n\n\tFType normalize()\n\t{\n\t\tauto length = mX * mX + mY * mY + mZ * mZ;\n\t\tif (length > 0)\n\t\t{\n\t\t\tlength = std::sqrt(length);\n\t\t\toperator/=(length);\n\t\t}\n\t\treturn length;\n\t}\n\t\n\tvoid rotate(const boost::math::quaternion<FType>& q)\n\t{\n\t\tboost::math::quaternion<FType> p(0, mX, mY, mZ);\n\t\t\n\t\tp = q * p * boost::math::conj(q);\n\t\n\t\tmX = p.R_component_2();\n\t\tmY = p.R_component_3();\n\t\tmZ = p.R_component_4();\n\t}\n\t\n#if HAVE_LIBCLIPPER\n\toperator clipper::Coord_orth() const\n\t{\n\t\treturn clipper::Coord_orth(mX, mY, mZ);\n\t}\n#endif\n\n\toperator std::tuple<const FType&, const FType&, const FType&>() const\n\t{\n\t\treturn std::make_tuple(std::ref(mX), std::ref(mY), std::ref(mZ));\n\t}\n\n\toperator std::tuple<FType&,FType&,FType&>()\n\t{\n\t\treturn std::make_tuple(std::ref(mX), std::ref(mY), std::ref(mZ));\n\t}\n\t\n\tbool operator==(const PointF& rhs) const\n\t{\n\t\treturn mX == rhs.mX and mY == rhs.mY and mZ == rhs.mZ;\n\t}\n\t\n\t// consider point as a vector... perhaps I should rename Point?\n\tFType lengthsq() const\n\t{\n\t\treturn mX * mX + mY * mY + mZ * mZ;\n\t}\n\n\tFType length() const\n\t{\n\t\treturn sqrt(mX * mX + mY * mY + mZ * mZ);\n\t}\n};\n\ntypedef PointF<float> Point;\ntypedef PointF<double> DPoint;\n\ntemplate<typename F>\ninline std::ostream& operator<<(std::ostream& os, const PointF<F>& pt)\n{\n\tos << '(' << pt.mX << ',' << pt.mY << ',' << pt.mZ << ')';\n\treturn os; \n}\n\ntemplate<typename F>\ninline PointF<F> operator+(const PointF<F>& lhs, const PointF<F>& rhs)\n{\n\treturn PointF<F>(lhs.mX + rhs.mX, lhs.mY + rhs.mY, lhs.mZ + rhs.mZ);\n}\n\ntemplate<typename F>\ninline PointF<F> operator-(const PointF<F>& lhs, const PointF<F>& rhs)\n{\n\treturn PointF<F>(lhs.mX - rhs.mX, lhs.mY - rhs.mY, lhs.mZ - rhs.mZ);\n}\n\ntemplate<typename F>\ninline PointF<F> operator-(const PointF<F>& pt)\n{\n\treturn PointF<F>(-pt.mX, -pt.mY, -pt.mZ);\n}\n\ntemplate<typename F>\ninline PointF<F> operator*(const PointF<F>& pt, F f)\n{\n\treturn PointF<F>(pt.mX * f, pt.mY * f, pt.mZ * f);\n}\n\ntemplate<typename F>\ninline PointF<F> operator*(F f, const PointF<F>& pt)\n{\n\treturn PointF<F>(pt.mX * f, pt.mY * f, pt.mZ * f);\n}\n\ntemplate<typename F>\ninline PointF<F> operator/(const PointF<F>& pt, F f)\n{\n\treturn PointF<F>(pt.mX / f, pt.mY / f, pt.mZ / f);\n}\n\n// --------------------------------------------------------------------\n// several standard 3d operations\n\ntemplate<typename F>\ninline double DistanceSquared(const PointF<F>& a, const PointF<F>& b)\n{\n\treturn\n\t\t(a.mX - b.mX) * (a.mX - b.mX) +\n\t\t(a.mY - b.mY) * (a.mY - b.mY) +\n\t\t(a.mZ - b.mZ) * (a.mZ - b.mZ);\n}\n\ntemplate<typename F>\ninline double Distance(const PointF<F>& a, const PointF<F>& b)\n{\n\treturn sqrt(\n\t\t(a.mX - b.mX) * (a.mX - b.mX) +\n\t\t(a.mY - b.mY) * (a.mY - b.mY) +\n\t\t(a.mZ - b.mZ) * (a.mZ - b.mZ));\n}\n\ntemplate<typename F>\ninline F DotProduct(const PointF<F>& a, const PointF<F>& b)\n{\n\treturn a.mX * b.mX + a.mY * b.mY + a.mZ * b.mZ;\n}\n\ntemplate<typename F>\ninline PointF<F> CrossProduct(const PointF<F>& a, const PointF<F>& b)\n{\n\treturn PointF<F>(a.mY * b.mZ - b.mY * a.mZ,\n\t\t\t\t  a.mZ * b.mX - b.mZ * a.mX,\n\t\t\t\t  a.mX * b.mY - b.mX * a.mY);\n}\n\ntemplate<typename F>\ndouble Angle(const PointF<F>& p1, const PointF<F>& p2, const PointF<F>& p3)\n{\n\tPointF<F> v1 = p1 - p2;\n\tPointF<F> v2 = p3 - p2;\n\t\n\treturn std::acos(DotProduct(v1, v2) / (v1.length() * v2.length())) * 180 / kPI;\n}\n\ntemplate<typename F>\ndouble DihedralAngle(const PointF<F>& p1, const PointF<F>& p2, const PointF<F>& p3, const PointF<F>& p4)\n{\n\tPointF<F> v12 = p1 - p2;\t// vector from p2 to p1\n\tPointF<F> v43 = p4 - p3;\t// vector from p3 to p4\n\t\n\tPointF<F> z = p2 - p3;\t\t// vector from p3 to p2\n\t\n\tPointF<F> p = CrossProduct(z, v12);\n\tPointF<F> x = CrossProduct(z, v43);\n\tPointF<F> y = CrossProduct(z, x);\n\t\n\tdouble u = DotProduct(x, x);\n\tdouble v = DotProduct(y, y);\n\t\n\tdouble result = 360;\n\tif (u > 0 and v > 0)\n\t{\n\t\tu = DotProduct(p, x) / sqrt(u);\n\t\tv = DotProduct(p, y) / sqrt(v);\n\t\tif (u != 0 or v != 0)\n\t\t\tresult = atan2(v, u) * 180 / kPI;\n\t}\n\t\n\treturn result;\n}\n\ntemplate<typename F>\ndouble CosinusAngle(const PointF<F>& p1, const PointF<F>& p2, const PointF<F>& p3, const PointF<F>& p4)\n{\n\tPointF<F> v12 = p1 - p2;\n\tPointF<F> v34 = p3 - p4;\n\t\n\tdouble result = 0;\n\t\n\tdouble x = DotProduct(v12, v12) * DotProduct(v34, v34);\n\tif (x > 0)\n\t\tresult = DotProduct(v12, v34) / sqrt(x);\n\t\n\treturn result;\n}\n\ntemplate<typename F>\nauto DistancePointToLine(const PointF<F> &l1, const PointF<F> &l2, const PointF<F> &p)\n{\n\tauto line       = l2 - l1;\n    auto p_to_l1    = p - l1;\n    auto p_to_l2    = p - l2;\n    auto cross      = CrossProduct(p_to_l1, p_to_l2);\n    return cross.length() / line.length();\n}\n\n// --------------------------------------------------------------------\n// For e.g. simulated annealing, returns a new point that is moved in\n// a random direction with a distance randomly chosen from a normal\n// distribution with a stddev of offset.\n\ntemplate<typename F>\nPointF<F> Nudge(PointF<F> p, F offset);\n\n// --------------------------------------------------------------------\n// We use quaternions to do rotations in 3d space\n\nQuaternion Normalize(Quaternion q);\n\nstd::tuple<double,Point> QuaternionToAngleAxis(Quaternion q);\nPoint Centroid(std::vector<Point>& Points);\nPoint CenterPoints(std::vector<Point>& Points);\nQuaternion AlignPoints(const std::vector<Point>& a, const std::vector<Point>& b);\ndouble RMSd(const std::vector<Point>& a, const std::vector<Point>& b);\n\n// --------------------------------------------------------------------\n// Helper class to generate evenly divided Points on a sphere\n// we use a fibonacci sphere to calculate even distribution of the dots\n\ntemplate<int N>\nclass SphericalDots\n{\n  public:\n\tenum { P = 2 * N + 1 };\n\ttypedef typename std::array<Point,P>\tarray_type;\n\ttypedef typename array_type::const_iterator\titerator;\n\n\tstatic SphericalDots& instance()\n\t{\n\t\tstatic SphericalDots sInstance;\n\t\treturn sInstance;\n\t}\n\t\n\tsize_t size() const\t\t\t\t\t\t\t{ return mPoints.size(); }\n\tconst Point operator[](uint32_t inIx) const\t{ return mPoints[inIx]; }\n\titerator begin() const\t\t\t\t\t\t{ return mPoints.begin(); }\n\titerator end() const\t\t\t\t\t\t{ return mPoints.end(); }\n\n\tdouble weight() const\t\t\t\t\t\t{ return mWeight; }\n\n\tSphericalDots()\n\t{\n\t\t\t\t\n\t\tconst double\n\t\t\tkGoldenRatio = (1 + std::sqrt(5.0)) / 2;\n\t\t\n\t\tmWeight = (4 * kPI) / P;\n\t\t\n\t\tauto p = mPoints.begin();\n\t\t\n\t\tfor (int32_t i = -N; i <= N; ++i)\n\t\t{\n\t\t\tdouble lat = std::asin((2.0 * i) / P);\n\t\t\tdouble lon = std::fmod(i, kGoldenRatio) * 2 * kPI / kGoldenRatio;\n\t\t\t\n\t\t\tp->mX = sin(lon) * cos(lat);\n\t\t\tp->mY = cos(lon) * cos(lat);\n\t\t\tp->mZ =            sin(lat);\n\n\t\t\t++p;\n\t\t}\n\t}\n\n  private:\n\n\tarray_type\t\t\t\tmPoints;\n\tdouble\t\t\t\t\tmWeight;\n};\n\ntypedef SphericalDots<50> SphericalDots_50;\n\n}\n", "meta": {"hexsha": "c04c07971449b442a1ac0deef420c83af99a2c56", "size": 10221, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/cif++/Point.hpp", "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": "include/cif++/Point.hpp", "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": "include/cif++/Point.hpp", "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": 23.8251748252, "max_line_length": 104, "alphanum_fraction": 0.6154975051, "num_tokens": 3192, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.626124191181315, "lm_q2_score": 0.5350984286266115, "lm_q1q2_score": 0.3350380708262298}}
{"text": "//#include <dirent.h>\r\n//#include <iostream>\r\n//#include <vector>\r\n//#include <string>\r\n//#include <utility>\r\n//\r\n//#include <Eigen/Core>\r\n//#include <Eigen/LU>\r\n//#include <Eigen/Geometry>\r\n//\r\n//#include <opencv2/opencv.hpp>\r\n//#define pi acos(-1)\r\n//\r\n//const int G_land_num = 74;\r\n//const int G_train_pic_id_num = 3300;\r\n//const int G_nShape = 47;\r\n//const int G_nVerts = 11510;\r\n//const int G_nFaces = 11540;\r\n//const int G_test_num = 77;\r\n//const int G_iden_num = 77;\r\n//const int G_inner_land_num = 59;\r\n//const int G_line_num = 50;\r\n//const int G_jaw_land_num = 20;\r\n//#define normalization\r\n//struct Target_type {\r\n//\tEigen::VectorXf exp;\r\n//\tEigen::RowVector3f tslt;\r\n//\tEigen::Matrix3f rot;\r\n//\tEigen::MatrixX2f dis;\r\n//\tEigen::Vector3f angle;\r\n//};\r\n//\r\n//struct DataPoint\r\n//{\r\n//\tcv::Mat image;\r\n//\tcv::Rect face_rect;\r\n//\tstd::vector<cv::Point2d> landmarks;\r\n//\t//std::vector<cv::Point2d> init_shape;\r\n//\tTarget_type shape, init_shape;\r\n//\tEigen::VectorXf user;\r\n//\tEigen::RowVector2f center;\r\n//\tEigen::MatrixX2f land_2d;\r\n//#ifdef posit\r\n//\tfloat f;\r\n//#endif // posit\r\n//#ifdef normalization\r\n//\tEigen::MatrixX3f s;\r\n//#endif\r\n//\r\n//\tEigen::VectorXi land_cor;\r\n//};\r\n//\r\n//\r\n//void load_lv(std::string name, DataPoint &temp) {\r\n//\tstd::cout << \"load coefficients...file:\" << name << \"\\n\";\r\n//\tFILE *fp;\r\n//\tfopen_s(&fp, name.c_str(), \"rb\");\r\n//\r\n//\ttemp.user.resize(G_iden_num);\r\n//\tfor (int j = 0; j < G_iden_num; j++)\r\n//\t\tfread(&temp.user(j), sizeof(float), 1, fp);\r\n//\tstd::cout << temp.user << \"\\n\";\r\n//\t//system(\"pause\");\r\n//\ttemp.land_2d.resize(G_land_num, 2);\r\n//\tfor (int i_v = 0; i_v < G_land_num; i_v++) {\r\n//\t\tfread(&temp.land_2d(i_v, 0), sizeof(float), 1, fp);\r\n//\t\tfread(&temp.land_2d(i_v, 1), sizeof(float), 1, fp);\r\n//\t}\r\n//\r\n//\r\n//\tfread(&temp.center(0), sizeof(float), 1, fp);\r\n//\tfread(&temp.center(1), sizeof(float), 1, fp);\r\n//\r\n//\ttemp.shape.exp.resize(G_nShape);\r\n//\tfor (int i_shape = 0; i_shape < G_nShape; i_shape++)\r\n//\t\tfread(&temp.shape.exp(i_shape), sizeof(float), 1, fp);\r\n//\r\n//\tfor (int i = 0; i < 3; i++) for (int j = 0; j < 3; j++)\r\n//\t\tfread(&temp.shape.rot(i, j), sizeof(float), 1, fp);\r\n//\r\n//\tfor (int i = 0; i < 3; i++) fread(&temp.shape.tslt(i), sizeof(float), 1, fp);\r\n//\r\n//\ttemp.land_cor.resize(G_land_num);\r\n//\tfor (int i_v = 0; i_v < G_land_num; i_v++) fread(&temp.land_cor(i_v), sizeof(int), 1, fp);\r\n//\r\n//\ttemp.s.resize(2, 3);\r\n//\tfor (int i = 0; i < 2; i++) for (int j = 0; j < 3; j++)\r\n//\t\tfread(&temp.s(i, j), sizeof(float), 1, fp);\r\n//\r\n//\ttemp.shape.dis.resize(G_land_num, 2);\r\n//\tfor (int i_v = 0; i_v < G_land_num; i_v++) {\r\n//\t\tfread(&temp.shape.dis(i_v, 0), sizeof(float), 1, fp);\r\n//\t\tfread(&temp.shape.dis(i_v, 1), sizeof(float), 1, fp);\r\n//\t}\r\n//\tstd::cout << temp.shape.dis << \"\\n\";\r\n//\t//system(\"pause\");\r\n//\tfclose(fp);\r\n//\tputs(\"load successful!\");\r\n//}\r\n//\r\n//\r\n////assume the be could not be more than 90\r\n//void cal_uler_angle(Eigen::Matrix3f R) {\r\n//\tEigen::Vector3f x, y, z,t;\r\n//\tx = R.row(0).transpose();\r\n//\ty = R.row(1).transpose();\r\n//\tz = R.row(2).transpose();\r\n//\tfloat al, be, ga, gaw;\r\n//\tif (fabs(1 - z(2)*z(2)) < 1e-3) {\r\n//\t\tga=gaw=be = 0;\r\n//\t\tal = acos(x(0));\r\n//\t\tif (y(0) < 0) al = 2 * pi - al;\r\n//\t}\r\n//\telse {\r\n//\t\t\r\n//\t\tbe = acos(z(2));\r\n//\t\tal = acos(std::max(std::min(float(1.0),z(1) / sqrt(1 - z(2)*z(2))),float(-1.0)));\r\n//\t\t\r\n//\t\tif (z(0) < 0) al = 2 * pi - al;//according to the sin(al)\r\n//\r\n//\r\n//\t\tt(0) = cos(al), t(1) = sin(al), t(2) = 0;\r\n//\t\tt.normalize();\r\n//\t\tx.normalize();\r\n//\t\t//t.normalized();\r\n//\t\tga = acos(t.dot(x));\r\n//\t\tgaw = acos(std::max(std::min(float(1.0), -y(2) / sqrt(1 - z(2)*z(2))), float(-1.0)));\r\n//\r\n//\t\tprintf(\"%.10f %.10f %.10f\\n\", -y(2), sqrt(1 - z(2)*z(2)), -y(2) / sqrt(1 - z(2)*z(2)));\r\n//\t\tif (x(2) < 0) ga = 2 * pi - ga, gaw = 2 * pi - gaw;//according to the sin(ga)\r\n//\t}\r\n//\tstd::cout << R << \"\\n----------------------\\n\";\r\n//\tprintf(\"%.10f %.10f %.10f %.10f %.10f\\n\",z(2), al/pi*180, be / pi * 180, ga / pi * 180, gaw / pi * 180);\r\n//\tsystem(\"pause\");\r\n//}\r\n//\r\n//Eigen::Matrix3f get_r_from_angle(float angle, int axis) {\r\n//\tEigen::Matrix3f ans;\r\n//\tans.setZero();\r\n//\tans(axis, axis) = 1;\r\n//\tint idx_x = 0, idx_y = 1;\r\n//\tif (axis == 0)\r\n//\t\tidx_x = 1, idx_y = 2;\r\n//\telse\r\n//\t\tif (axis == 2)\r\n//\t\t\tidx_x = 0, idx_y = 1;\r\n//\t\telse\r\n//\t\t\tidx_x = 0, idx_y = 2;\r\n//\tans(idx_x, idx_x) = cos(angle), ans(idx_x, idx_y) = -sin(angle), ans(idx_y, idx_x) = sin(angle), ans(idx_y, idx_y) = cos(angle);\r\n//\treturn ans;\r\n//}\r\n//\r\n//\r\n//Eigen::Matrix3f get_r_from_angle(const Eigen::Vector3f &angle) {\r\n//\tEigen::Matrix3f ans;\r\n//\tfloat Sa = sin(angle(0)), Ca = cos(angle(0)), Sb = sin(angle(1)),\r\n//\t\tCb = cos(angle(1)), Sc = sin(angle(2)), Cc = cos(angle(2));\r\n//\r\n//\tans(0, 0) = Ca * Cc - Sa * Cb*Sc;\r\n//\tans(0, 1) = -Sa * Cc - Ca * Cb*Sc;\r\n//\tans(0, 2) = Sb * Sc;\r\n//\tans(1, 0) = Ca * Sc + Sa * Cb*Cc;\r\n//\tans(1, 1) = -Sa * Sc + Ca * Cb*Cc;\r\n//\tans(1, 2) = -Sb * Cc;\r\n//\tans(2, 0) = Sa * Sb;\r\n//\tans(2, 1) = Ca * Sb;\r\n//\tans(2, 2) = Cb;\r\n//\treturn ans;\r\n//}\r\n//\r\n////assume the be could not be more than 90\r\n//Eigen::Vector3f cal_uler_angle_zyx(Eigen::Matrix3f R) {\r\n//\tEigen::Vector3f x, y, z, t;\r\n//\tx = R.row(0).transpose();\r\n//\ty = R.row(1).transpose();\r\n//\tz = R.row(2).transpose();\r\n//\tfloat al, be, ga;\r\n//\tif (fabs(1 - x(2)*x(2)) < 1e-3) {\r\n//\t\tbe = asin(x(2));\r\n//\t\tal = ga = 0;\r\n//\t\texit(1);\r\n//\t}\r\n//\telse {\r\n//\r\n//\t\tbe = asin(std::max(std::min(1.0, double(x(2))), -1.0));\r\n//\t\tal = asin(std::max(std::min(1.0, double(-x(1) / sqrt(1 - x(2)*x(2)))), -1.0));\r\n//\t\tga = asin(std::max(std::min(1.0, double(-y(2) / sqrt(1 - x(2)*x(2)))), -1.0));\r\n//\r\n//\t}\r\n//\tstd::cout << R << \"\\n----------------------\\n\";\r\n//\tprintf(\"%.10f %.10f %.10f %.10f\\n\", x(2), al / pi * 180, be / pi * 180, ga / pi * 180);\r\n//\tEigen::Vector3f ans;\r\n//\tans << al, be, ga;\r\n//\treturn ans;\r\n//\t//system(\"pause\");\r\n//}\r\n//\r\n//Eigen::Matrix3f get_r_from_angle_zyx(const Eigen::Vector3f &angle) {\r\n//\tEigen::Matrix3f ans;\r\n//\tfloat Sa = sin(angle(0)), Ca = cos(angle(0)), Sb = sin(angle(1)),\r\n//\t\tCb = cos(angle(1)), Sc = sin(angle(2)), Cc = cos(angle(2));\r\n//\r\n//\tans(0, 0) = Ca * Cb; \r\n//\tans(0, 1) = -Sa * Cb; \r\n//\tans(0, 2) = Sb;\r\n//\tans(1, 0) = Sa * Cc + Ca * Sb*Sc; \r\n//\tans(1, 1) = Ca * Cc - Sa * Sb*Sc; \r\n//\tans(1, 2) = -Cb * Sc;\r\n//\tans(2, 0) = Sa * Sc - Ca * Sb*Cc;\r\n//\tans(2, 1) = Ca * Sc + Sa * Sb*Cc;\r\n//\tans(2, 2) = Cb * Cc;\r\n//\treturn ans;\r\n//}\r\n//\r\n//\r\n//\r\n//\r\n//void test_r(DataPoint data) {\r\n//\tEigen::Matrix3f rot;\r\n//\t//rot = get_r_from_angle(data.shape.tslt(2), 2)*get_r_from_angle(data.shape.tslt(1), 0)*get_r_from_angle(data.shape.tslt(0), 2);\r\n//\t//std::cout << rot << \"\\n\";\r\n//\tstd::cout << get_r_from_angle_zyx(data.shape.angle) << \"\\n\";\r\n//\tsystem(\"pause\");\r\n//}\r\n//\r\n//int main() {\r\n//\r\n//\tDataPoint data;\r\n//\t/*data.shape.angle << 1, 20, 0.5;\r\n//\ttest_r(data);*/\r\n//\r\n//\r\n//\tload_lv(\"data/lv_mp4_1.lv\",data);//data/test_debug_lv_005_04_03_051_05\r\n//\t//lv_mp4_1.\r\n//\tdata.shape.angle=cal_uler_angle_zyx(data.shape.rot);\r\n//\ttest_r(data);\r\n//\treturn 0;\r\n//}\r\n////g++ -Wall -std=c++11 `pkg-config --cflags opencv` -o deal deal_falut.cpp `pkg-config --libs opencv`", "meta": {"hexsha": "8f314bc7be24b8309a9826d564c4e76b90741714", "size": 7111, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lv2obj/uler_angle.cpp", "max_stars_repo_name": "sublimationAC/DDE", "max_stars_repo_head_hexsha": "fcde429b0db65100b8bd8bf607626b6beff8a431", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "lv2obj/uler_angle.cpp", "max_issues_repo_name": "sublimationAC/DDE", "max_issues_repo_head_hexsha": "fcde429b0db65100b8bd8bf607626b6beff8a431", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-01-05T06:12:34.000Z", "max_issues_repo_issues_event_max_datetime": "2019-01-08T06:20:18.000Z", "max_forks_repo_path": "lv2obj/uler_angle.cpp", "max_forks_repo_name": "sublimationAC/DDE", "max_forks_repo_head_hexsha": "fcde429b0db65100b8bd8bf607626b6beff8a431", "max_forks_repo_licenses": ["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.7531380753, "max_line_length": 132, "alphanum_fraction": 0.531711433, "num_tokens": 2702, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6261241772283034, "lm_q2_score": 0.5350984286266115, "lm_q1q2_score": 0.33503806335999514}}
{"text": "#include <stdio.h>\n#include <cfloat>\n#include <list>\n#include <vector>\n#include <math.h>\n#include <iostream>\n#include <algorithm>\n#include <numeric>\n#include <boost/algorithm/clamp.hpp>\n#include <random>\n#include \"third_party/eigen3/unsupported/Eigen/CXX11/Tensor\"\n#include \"unsupported/Eigen/CXX11/src/Tensor/TensorDeviceCuda.h\"\n//#include \"unsupported/Eigen/CXX11/Tensor\"\n#include \"tensorflow/core/framework/op.h\"\n#include \"tensorflow/core/framework/op_kernel.h\"\n#include \"tensorflow/core/framework/tensor_shape.h\"\n#include \"tensorflow/core/framework/common_shape_fns.h\"\n#include \"tensorflow/core/util/work_sharder.h\"\n#include \"bboxes.h\"\n#include \"bboxes_encode.h\"\n#include \"wtoolkit.h\"\n#include \"wtoolkit_cuda.h\"\n#include <future>\n\nusing namespace tensorflow;\nusing namespace std;\n\ntypedef Eigen::ThreadPoolDevice CPUDevice;\ntypedef Eigen::GpuDevice GPUDevice;\n/*\n * scale_weights:[4](基意义与BoxesEncode的prio_scaling互为倒数\n * boxes:[1,X,4]/[batch_size,X,4](ymin,xmin,ymax,xmax) 候选box,相对坐标\n * gboxes:[batch_size,Y,4](ymin,xmin,ymax,xmax)ground truth box相对坐标\n * labels:[batch_size,X] 0为背景,-1表示忽略\n * indices:[batch_size,X] 与box相对应的gtbox索引\n * output_boxes:[batch_size,X,4] regs(cy,cx,h,w)\n */\nREGISTER_OP(\"GetBoxesDeltas\")\n    .Attr(\"T: {float,double,int32,int64}\")\n \t.Attr(\"scale_weights: list(float)\")\n    .Input(\"boxes: T\")\n    .Input(\"gboxes: T\")\n    .Input(\"labels: int32\")\n    .Input(\"indices: int32\")\n\t.Output(\"output_boxes:T\")\n\t.SetShapeFn([](shape_inference::InferenceContext* c) {\n\t\t\tconst auto batch_size = c->Dim(c->input(1),0);\n\t\t\tconst auto box_nr = c->Dim(c->input(0),1);\n\t\t\tconst auto box_dim = c->Dim(c->input(0),2);\n            auto shape0 = c->MakeShape({batch_size,box_nr,box_dim});\n\n\t\t\tc->set_output(0, shape0);\n\t\t\treturn Status::OK();\n\t\t\t});\n\ntemplate <typename Device, typename T>\nclass GetBoxesDeltasOp: public OpKernel {\n\tpublic:\n\t\tusing tensor_2d = Eigen::Tensor<T,2,Eigen::RowMajor>;\n\tpublic:\n\t\texplicit GetBoxesDeltasOp(OpKernelConstruction* context) : OpKernel(context) {\n\t\t\tOP_REQUIRES_OK(context, context->GetAttr(\"scale_weights\", &scale_weights));\n\t\t\tOP_REQUIRES(context, scale_weights.size() == 4, errors::InvalidArgument(\"scale_weights data must be shape[4]\"));\n\t\t}\n\n\t\tvoid Compute(OpKernelContext* context) override\n\t\t{\n\t\t\tconst Tensor &_bottom_boxes   = context->input(0);\n\t\t\tconst Tensor &_bottom_gboxes  = context->input(1);\n\t\t\tconst Tensor &_bottom_labels  = context->input(2);\n\t\t\tconst Tensor &_bottom_indices = context->input(3);\n\n\t\t\tOP_REQUIRES(context, _bottom_boxes.dims() == 3, errors::InvalidArgument(\"box data must be 3-dimensional\"));\n\t\t\tOP_REQUIRES(context, _bottom_gboxes.dims() == 3, errors::InvalidArgument(\"box data must be 3-dimensional\"));\n\t\t\tOP_REQUIRES(context, _bottom_labels.dims() == 2, errors::InvalidArgument(\"labels data must be 2-dimensional\"));\n\t\t\tOP_REQUIRES(context, _bottom_indices.dims() == 2, errors::InvalidArgument(\"index data must be 1-dimensional\"));\n\n\t\t\tauto          bottom_boxes    = _bottom_boxes.template tensor<T,3>();\n\t\t\tauto          bottom_gboxes   = _bottom_gboxes.template tensor<T,3>();\n\t\t\tauto          bottom_labels   = _bottom_labels.template tensor<int,2>();\n\t\t\tauto          bottom_indices  = _bottom_indices.template tensor<int,2>();\n\t\t\tconst auto    batch_size      = _bottom_gboxes.dim_size(0);\n\t\t\tconst auto    data_nr         = _bottom_boxes.dim_size(1);\n\n\n\t\t\tint dims_3d[] = {batch_size,data_nr,_bottom_boxes.dim_size(2)};\n\t\t\tTensorShape   outshape0 = _bottom_boxes.shape();\n\t\t\tTensor       *output_boxes          = NULL;\n\n\t\t\tTensorShapeUtils::MakeShape(dims_3d, 3, &outshape0);\n\t\t\tOP_REQUIRES_OK(context, context->allocate_output(0, outshape0, &output_boxes));\n\n\t\t\tauto output_boxes_tensor          =  output_boxes->template tensor<T,3>();\n\n\t\t\toutput_boxes_tensor.setZero();\n\n            auto shard = [&](int64 start,int64 limit){\n\t\t\t\tfor(auto i=start; i<limit; ++i) {\n\n\t\t\t\t\tauto boxes   = tensor_2d(bottom_boxes.chip(bottom_boxes.dimension(0)==batch_size?i:0,0));\n\t\t\t\t\tauto gboxes  = tensor_2d(bottom_gboxes.chip(i,0));\n\t\t\t\t\t/*\n\t\t\t\t\t * 计算所有正样本gbox到所对应的box的回归参数\n\t\t\t\t\t */\n\t\t\t\t\tfor(auto j=0; j<data_nr; ++j) {\n\t\t\t\t\t\tif((bottom_labels(i,j)<1)) {\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tEigen::Tensor<T,1,Eigen::RowMajor> box     = boxes.chip(j,0);\n\t\t\t\t\t\tEigen::Tensor<T,1,Eigen::RowMajor> gbox    = gboxes.chip(bottom_indices(i,j),0);\n\t\t\t\t\t\tauto  yxhw    = box_minmax_to_cxywh(box.data());\n\t\t\t\t\t\tauto  yref    = std::get<0>(yxhw);\n\t\t\t\t\t\tauto  xref    = std::get<1>(yxhw);\n\t\t\t\t\t\tauto  href    = std::get<2>(yxhw);\n\t\t\t\t\t\tauto  wref    = std::get<3>(yxhw);\n\n\t\t\t\t\t\tif((href<1E-8) || (wref<1E-8)) {\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tauto gyxhw = box_minmax_to_cxywh(gbox.data());\n\t\t\t\t\t\tauto gcy =  std::get<0>(gyxhw);\n\t\t\t\t\t\tauto gcx =  std::get<1>(gyxhw);\n\t\t\t\t\t\tauto gh  =  std::get<2>(gyxhw);\n\t\t\t\t\t\tauto gw  =  std::get<3>(gyxhw);\n\t\t\t\t\t\tauto feat_cy  =  scale_weights[0]*(gcy-yref)/href;\n\t\t\t\t\t\tauto feat_cx  =  scale_weights[1]*(gcx-xref)/wref;\n\t\t\t\t\t\tauto feat_h   =  log(gh/href)*scale_weights[2];\n\t\t\t\t\t\tauto feat_w   =  log(gw/wref)*scale_weights[3];\n\n\t\t\t\t\t\toutput_boxes_tensor(i,j,0) = feat_cy;\n\t\t\t\t\t\toutput_boxes_tensor(i,j,1) = feat_cx;\n\t\t\t\t\t\toutput_boxes_tensor(i,j,2) = feat_h;\n\t\t\t\t\t\toutput_boxes_tensor(i,j,3) = feat_w;\n\t\t\t\t\t}\n\t\t\t\t}\n            };\n            list<future<void>> results;\n            for(auto i=0; i<batch_size; ++i) {\n                results.emplace_back(async(launch::async,[i,&shard](){ shard(i,i+1);}));\n            }\n        }\n\tprivate:\n\t\tvector<float> scale_weights;\n};\nREGISTER_KERNEL_BUILDER(Name(\"GetBoxesDeltas\").Device(DEVICE_CPU).TypeConstraint<float>(\"T\"), GetBoxesDeltasOp<CPUDevice, float>);\n///////////\n/*\n * prio_scaling:[4]\n * max_overlap_as_pos:是否将与ground truth bbox交叉面积最大的box设置为正样本\n * bottom_boxes:[1,X,4]/[batch_size,X,4](ymin,xmin,ymax,xmax) 候选box,相对坐标\n * bottom_gboxes:[batch_size,Y,4](ymin,xmin,ymax,xmax)ground truth box相对坐标\n * bottom_glabels:[batch_size,Y] 0为背景\n * bottom_glength:[batch_size] 为每一个batch中gboxes的有效数量\n * output_boxes:[batch_size,X,4] regs(cy,cx,h,w)\n * output_labels:[batch_size,X], 当前anchorbox的标签，背景为0,不为背景时为相应最大jaccard得分\n * output_scores:[batch_size,X], 当前anchorbox与groundtruthbox的jaccard得分，当jaccard得分高于threshold时就不为背影\n * output_remove_indict:[batch_size,X], anchorbox是否有效(一般为iou处理中间部分的无效)\n * output_indict:[batch_size,X], 当anchorbox有效时，与它对应的gboxes(从0开始)序号,无效时为-1\n */\nREGISTER_OP(\"BoxesEncode\")\n    .Attr(\"T: {float,double,int32,int64}\")\n\t.Attr(\"pos_threshold:float\")\n\t.Attr(\"neg_threshold:float\")\n \t.Attr(\"prio_scaling: list(float)\")\n    .Attr(\"max_overlap_as_pos:bool\")\n    .Input(\"bottom_boxes: T\")\n    .Input(\"bottom_gboxes: T\")\n    .Input(\"bottom_glabels: int32\")\n    .Input(\"bottom_glength: int32\")\n\t.Output(\"output_boxes:T\")\n\t.Output(\"output_labels:int32\")\n\t.Output(\"output_scores:T\")\n\t.Output(\"remove_indict:bool\")\n\t.Output(\"indict:int32\")\n\t.SetShapeFn([](shape_inference::InferenceContext* c) {\n            const auto input_shape0 = c->input(0);\n            const auto input_shape1 = c->input(1);\n            const auto batch_size = c->Dim(input_shape1,0);\n            const auto boxes_nr  = c->Dim(input_shape0,1);\n            auto shape0 = c->MakeShape({batch_size,boxes_nr,4});\n            auto shape1 = c->MakeShape({batch_size,boxes_nr});\n\n\t\t\tc->set_output(0, shape0);\n            for(auto i=1; i<5; ++i)\n\t\t\t    c->set_output(i, shape1);\n\t\t\treturn Status::OK();\n\t\t\t});\n\ntemplate <typename Device, typename T>\nclass BoxesEncodeOp: public OpKernel {\n};\ntemplate <typename T>\nclass BoxesEncodeOp<CPUDevice,T>: public OpKernel {\n\tpublic:\n\t\texplicit BoxesEncodeOp(OpKernelConstruction* context) : OpKernel(context) {\n\t\t\tOP_REQUIRES_OK(context, context->GetAttr(\"pos_threshold\", &pos_threshold));\n\t\t\tOP_REQUIRES_OK(context, context->GetAttr(\"neg_threshold\", &neg_threshold));\n\t\t\tOP_REQUIRES_OK(context, context->GetAttr(\"prio_scaling\", &prio_scaling));\n\t\t\tOP_REQUIRES_OK(context, context->GetAttr(\"max_overlap_as_pos\", &max_overlap_as_pos_));\n\t\t\tOP_REQUIRES(context, prio_scaling.size() == 4, errors::InvalidArgument(\"prio scaling data must be shape[4]\"));\n\t\t}\n\n\t\tvoid Compute(OpKernelContext* context) override\n\t\t{\n            TIME_THISV1(\"BoxesEncode\");\n\t\t\tconst Tensor &_bottom_boxes   = context->input(0);\n\t\t\tconst Tensor &_bottom_gboxes  = context->input(1);\n\t\t\tconst Tensor &_bottom_glabels = context->input(2);\n\t\t\tconst Tensor &_bottom_gsize   = context->input(3);\n\t\t\tauto          bottom_boxes    = _bottom_boxes.template tensor<T,3>();\n\t\t\tauto          bottom_gboxes   = _bottom_gboxes.template tensor<T,3>();\n\t\t\tauto          bottom_glabels  = _bottom_glabels.template tensor<int,2>();\n\t\t\tauto          bottom_gsize    = _bottom_gsize.template tensor<int,1>();\n\t\t\tconst auto    batch_size      = _bottom_gboxes.dim_size(0);\n\t\t\tconst auto    data_nr         = _bottom_boxes.dim_size(1);\n\n\t\t\tOP_REQUIRES(context, _bottom_boxes.dims() == 3, errors::InvalidArgument(\"box data must be 3-dimensional\"));\n\t\t\tOP_REQUIRES(context, _bottom_gboxes.dims() == 3, errors::InvalidArgument(\"box data must be 3-dimensional\"));\n\t\t\tOP_REQUIRES(context, _bottom_glabels.dims() == 2, errors::InvalidArgument(\"labels data must be 2-dimensional\"));\n\t\t\tOP_REQUIRES(context, _bottom_gsize.dims() == 1, errors::InvalidArgument(\"gsize data must be 1-dimensional\"));\n\n\t\t\tint           dims_3d[3]            = {int(batch_size),int(data_nr),4};\n\t\t\tint           dims_2d[2]            = {int(batch_size),int(data_nr)};\n\t\t\tTensorShape   outshape0;\n\t\t\tTensorShape   outshape1;\n\t\t\tTensor       *output_boxes          = NULL;\n\t\t\tTensor       *output_labels         = NULL;\n\t\t\tTensor       *output_scores         = NULL;\n\t\t\tTensor       *output_remove_indict  = NULL;\n\t\t\tTensor       *output_indict         = NULL;\n\n\t\t\tTensorShapeUtils::MakeShape(dims_3d, 3, &outshape0);\n\t\t\tTensorShapeUtils::MakeShape(dims_2d, 2, &outshape1);\n\n\n\t\t\tOP_REQUIRES_OK(context, context->allocate_output(0, outshape0, &output_boxes));\n\t\t\tOP_REQUIRES_OK(context, context->allocate_output(1, outshape1, &output_labels));\n\t\t\tOP_REQUIRES_OK(context, context->allocate_output(2, outshape1, &output_scores));\n\t\t\tOP_REQUIRES_OK(context, context->allocate_output(3, outshape1, &output_remove_indict));\n\t\t\tOP_REQUIRES_OK(context, context->allocate_output(4, outshape1, &output_indict));\n\n\t\t\tauto output_boxes_tensor          =  output_boxes->template tensor<T,3>();\n\t\t\tauto output_labels_tensor         =  output_labels->template tensor<int,2>();\n\t\t\tauto output_scores_tensor         =  output_scores->template tensor<T,2>();\n\t\t\tauto output_remove_indict_tensor  =  output_remove_indict->template tensor<bool,2>();\n\t\t\tauto output_indict_tensor         =  output_indict->template tensor<int,2>();\n\n            BoxesEncodeUnit<CPUDevice,T> encode_unit(pos_threshold,neg_threshold,prio_scaling,max_overlap_as_pos_);\n            auto shard = [&](int64 start,int64 limit){\n                for(auto i=start; i<limit; ++i) {\n\n                    auto size     = bottom_gsize(i);\n                    auto boxes    = bottom_boxes.chip(bottom_boxes.dimension(0)==batch_size?i:0,0);\n                    auto _gboxes  = bottom_gboxes.chip(i,0);\n                    auto _glabels = bottom_glabels.chip(i,0);\n                    Eigen::array<long,2> offset={0,0};\n                    Eigen::array<long,2> extents={size,4};\n                    Eigen::array<long,1> offset1={0};\n                    Eigen::array<long,1> extents1={size};\n                    auto gboxes             = _gboxes.slice(offset,extents);\n                    auto glabels            = _glabels.slice(offset1,extents1);\n                    auto out_boxes          = output_boxes_tensor.chip(i,0);\n                    auto out_labels         = output_labels_tensor.chip(i,0);\n                    auto out_scores         = output_scores_tensor.chip(i,0);\n                    auto out_remove_indices = output_remove_indict_tensor.chip(i,0);\n                    auto out_indices        = output_indict_tensor.chip(i,0);\n                    auto res                = encode_unit(boxes,gboxes,glabels);\n\n                    out_boxes           =  std::get<0>(res);\n                    out_labels          =  std::get<1>(res);\n                    out_scores          =  std::get<2>(res);\n                    out_remove_indices  =  std::get<3>(res);\n                    out_indices         =  std::get<4>(res);\n                }\n            };\n            list<future<void>> results;\n            for(auto i=0; i<batch_size; ++i) {\n                results.emplace_back(async(launch::async,[i,&shard](){ shard(i,i+1);}));\n            }\n        }\n\tprivate:\n\t\tfloat         pos_threshold;\n\t\tfloat         neg_threshold;\n\t\tvector<float> prio_scaling;\n        bool          max_overlap_as_pos_ = true;\n};\n#ifdef GOOGLE_CUDA\ntemplate <typename T>\nclass BoxesEncodeOp<GPUDevice,T>: public OpKernel {\n\tpublic:\n\t\texplicit BoxesEncodeOp(OpKernelConstruction* context) : OpKernel(context) {\n\t\t\tOP_REQUIRES_OK(context, context->GetAttr(\"pos_threshold\", &pos_threshold));\n\t\t\tOP_REQUIRES_OK(context, context->GetAttr(\"neg_threshold\", &neg_threshold));\n\t\t\tOP_REQUIRES_OK(context, context->GetAttr(\"prio_scaling\", &prio_scaling));\n\t\t\tOP_REQUIRES_OK(context, context->GetAttr(\"max_overlap_as_pos\", &max_overlap_as_pos_));\n\t\t\tOP_REQUIRES(context, prio_scaling.size() == 4, errors::InvalidArgument(\"prio scaling data must be shape[4]\"));\n\t\t}\n\n\t\tvoid Compute(OpKernelContext* context) override\n\t\t{\n            TIME_THISV1(\"BoxesEncodeGPU\");\n\t\t\tconst Tensor &_bottom_boxes   = context->input(0);\n\t\t\tconst Tensor &_bottom_gboxes  = context->input(1);\n\t\t\tconst Tensor &_bottom_glabels = context->input(2);\n\t\t\tconst Tensor &_bottom_gsize   = context->input(3);\n\t\t\tauto          bottom_boxes    = _bottom_boxes.template tensor<T,3>();\n\t\t\tauto          bottom_gboxes   = _bottom_gboxes.template tensor<T,3>();\n\t\t\tauto          bottom_glabels  = _bottom_glabels.template tensor<int,2>();\n\t\t\tauto          d_bottom_gsize  = _bottom_gsize.template tensor<int,1>();\n\t\t\tconst auto    batch_size      = _bottom_gboxes.dim_size(0);\n\t\t\tconst auto    data_nr         = _bottom_boxes.dim_size(1);\n\t\t    Eigen::Tensor<int,1,Eigen::RowMajor> bottom_gsize;\n            assign_tensor<CPUDevice,GPUDevice>(bottom_gsize,d_bottom_gsize);\n\n\t\t\tOP_REQUIRES(context, _bottom_boxes.dims() == 3, errors::InvalidArgument(\"box data must be 3-dimensional\"));\n\t\t\tOP_REQUIRES(context, _bottom_gboxes.dims() == 3, errors::InvalidArgument(\"box data must be 3-dimensional\"));\n\t\t\tOP_REQUIRES(context, _bottom_glabels.dims() == 2, errors::InvalidArgument(\"labels data must be 2-dimensional\"));\n\t\t\tOP_REQUIRES(context, _bottom_gsize.dims() == 1, errors::InvalidArgument(\"gsize data must be 1-dimensional\"));\n\n\t\t\tint           dims_3d[3]            = {int(batch_size),int(data_nr),4};\n\t\t\tint           dims_2d[2]            = {int(batch_size),int(data_nr)};\n\t\t\tTensorShape   outshape0;\n\t\t\tTensorShape   outshape1;\n\t\t\tTensor       *output_boxes          = NULL;\n\t\t\tTensor       *output_labels         = NULL;\n\t\t\tTensor       *output_scores         = NULL;\n\t\t\tTensor       *output_remove_indict  = NULL;\n\t\t\tTensor       *output_indict         = NULL;\n\n\t\t\tTensorShapeUtils::MakeShape(dims_3d, 3, &outshape0);\n\t\t\tTensorShapeUtils::MakeShape(dims_2d, 2, &outshape1);\n\n\t\t\tOP_REQUIRES_OK(context, context->allocate_output(0, outshape0, &output_boxes));\n\t\t\tOP_REQUIRES_OK(context, context->allocate_output(1, outshape1, &output_labels));\n\t\t\tOP_REQUIRES_OK(context, context->allocate_output(2, outshape1, &output_scores));\n\t\t\tOP_REQUIRES_OK(context, context->allocate_output(3, outshape1, &output_remove_indict));\n\t\t\tOP_REQUIRES_OK(context, context->allocate_output(4, outshape1, &output_indict));\n\n\t\t\tauto output_boxes_tensor          =  output_boxes->template tensor<T,3>();\n\t\t\tauto output_labels_tensor         =  output_labels->template tensor<int,2>();\n\t\t\tauto output_scores_tensor         =  output_scores->template tensor<T,2>();\n\t\t\tauto output_remove_indict_tensor  =  output_remove_indict->template tensor<bool,2>();\n\t\t\tauto output_indict_tensor         =  output_indict->template tensor<int,2>();\n\n            BoxesEncodeUnit<GPUDevice,T> encode_unit(pos_threshold,neg_threshold,prio_scaling,max_overlap_as_pos_);\n            for(auto i=0; i<batch_size; ++i) {\n                    \n                    auto size    = bottom_gsize(i);\n                    auto boxes   = bottom_boxes.dimension(0)==batch_size?chip_data(bottom_boxes,i):chip_data(bottom_boxes,0);\n                    auto gboxes  = chip_data(bottom_gboxes,i);\n                    auto glabels = chip_data(bottom_glabels,i);\n                    encode_unit(boxes,gboxes,glabels,\n                            chip_data(output_boxes_tensor,i),\n                            chip_data(output_labels_tensor,i),\n                            chip_data(output_scores_tensor,i),\n                            chip_data(output_remove_indict_tensor,i),\n                            chip_data(output_indict_tensor,i),\n                            size,bottom_boxes.dimension(1)\n                            );\n                }\n        }\n\tprivate:\n\t\tfloat         pos_threshold;\n\t\tfloat         neg_threshold;\n\t\tvector<float> prio_scaling;\n        bool          max_overlap_as_pos_ = true;\n};\n#endif\nREGISTER_KERNEL_BUILDER(Name(\"BoxesEncode\").Device(DEVICE_CPU).TypeConstraint<float>(\"T\"), BoxesEncodeOp<CPUDevice, float>);\n#ifdef GOOGLE_CUDA\nREGISTER_KERNEL_BUILDER(Name(\"BoxesEncode\").Device(DEVICE_GPU).TypeConstraint<float>(\"T\"), BoxesEncodeOp<GPUDevice, float>);\n#endif\n/*\n * prio_scaling:[4]\n * bottom_boxes:[X,4](ymin,xmin,ymax,xmax) 候选box,相对坐标\n * bottom_gboxes:[Y,4](ymin,xmin,ymax,xmax)ground truth box相对坐标\n * bottom_glabels:[Y] 0为背景\n * output_boxes:[X,4] regs(cy,cx,h,w)\n * output_labels:[X], 当前anchorbox的标签，背景为0,不为背景时为相应最大jaccard得分\n * output_scores:[X], 当前anchorbox与groundtruthbox的jaccard得分，当jaccard得分高于threshold时就不为背影\n */\nREGISTER_OP(\"BoxesEncode1\")\n    .Attr(\"T: {float,double,int32,int64}\")\n\t.Attr(\"pos_threshold:float\")\n\t.Attr(\"neg_threshold:float\")\n \t.Attr(\"prio_scaling: list(float)\")\n \t.Attr(\"max_overlap_as_pos: bool\")\n    .Input(\"bottom_boxes: T\")\n    .Input(\"bottom_gboxes: T\")\n    .Input(\"bottom_glabels: int32\")\n\t.Output(\"output_boxes:T\")\n\t.Output(\"output_labels:int32\")\n\t.Output(\"output_scores:T\")\n\t.Output(\"remove_indict:bool\")\n    .SetShapeFn([](shape_inference::InferenceContext* c){\n            auto shape0 = c->input(0);\n            auto shape1 = c->Vector(c->Dim(shape0,0));\n\n            c->set_output(0,shape0);\n\n            for(auto i=1; i<4; ++i) c->set_output(i,shape1);\n\n            return Status::OK();\n            });\n\ntemplate <typename Device, typename T>\nclass BoxesEncode1Op{\n};\ntemplate <typename T>\nclass BoxesEncode1Op<CPUDevice,T>: public OpKernel {\n\tpublic:\n        struct IOUIndex{\n            int index;\n            float iou;\n        };\n\t\texplicit BoxesEncode1Op(OpKernelConstruction* context) : OpKernel(context) {\n\t\t\tOP_REQUIRES_OK(context, context->GetAttr(\"pos_threshold\", &pos_threshold));\n\t\t\tOP_REQUIRES_OK(context, context->GetAttr(\"neg_threshold\", &neg_threshold));\n\t\t\tOP_REQUIRES_OK(context, context->GetAttr(\"prio_scaling\", &prio_scaling));\n\t\t\tOP_REQUIRES_OK(context, context->GetAttr(\"max_overlap_as_pos\", &max_overlap_as_pos_));\n\t\t\tOP_REQUIRES(context, prio_scaling.size() == 4, errors::InvalidArgument(\"prio scaling data must be shape[4]\"));\n\t\t}\n\n\t\tvoid Compute(OpKernelContext* context) override\n\t\t{\n            TIME_THISV1(\"BoxesEncode1\");\n\t\t\tconst Tensor &_bottom_boxes   = context->input(0);\n\t\t\tconst Tensor &_bottom_gboxes  = context->input(1);\n\t\t\tconst Tensor &_bottom_glabels = context->input(2);\n\t\t\tauto          bottom_boxes    = _bottom_boxes.template tensor<T,2>();\n\t\t\tauto          bottom_gboxes   = _bottom_gboxes.template tensor<T,2>();\n\t\t\tauto          bottom_glabels  = _bottom_glabels.template tensor<int,1>();\n\t\t\tconst auto    data_nr         = _bottom_boxes.dim_size(0);\n\n\t\t\tOP_REQUIRES(context, _bottom_boxes.dims() == 2, errors::InvalidArgument(\"box data must be 2-dimensional\"));\n\t\t\tOP_REQUIRES(context, _bottom_gboxes.dims() == 2, errors::InvalidArgument(\"box data must be 2-dimensional\"));\n\t\t\tOP_REQUIRES(context, _bottom_glabels.dims() == 1, errors::InvalidArgument(\"labels data must be 1-dimensional\"));\n\n\t\t\tint           dims_2d[2]            = {int(data_nr),4};\n\t\t\tint           dims_1d[1]            = {int(data_nr)};\n\t\t\tTensorShape   outshape0;\n\t\t\tTensorShape   outshape1;\n\t\t\tTensor       *output_boxes          = NULL;\n\t\t\tTensor       *output_labels         = NULL;\n\t\t\tTensor       *output_scores         = NULL;\n\t\t\tTensor       *output_remove_indict  = NULL;\n\t\t\tvector<IOUIndex>   iou_indexs(data_nr,IOUIndex({-1,0.0})); //默认box不与任何ground truth box相交，iou为0\n\n\t\t\tTensorShapeUtils::MakeShape(dims_2d, 2, &outshape0);\n\t\t\tTensorShapeUtils::MakeShape(dims_1d, 1, &outshape1);\n\n\n\t\t\tOP_REQUIRES_OK(context, context->allocate_output(0, outshape0, &output_boxes));\n\t\t\tOP_REQUIRES_OK(context, context->allocate_output(1, outshape1, &output_labels));\n\t\t\tOP_REQUIRES_OK(context, context->allocate_output(2, outshape1, &output_scores));\n\t\t\tOP_REQUIRES_OK(context, context->allocate_output(3, outshape1, &output_remove_indict));\n\t\t\tauto output_boxes_tensor         = output_boxes->template tensor<T,2>();\n\t\t\tauto output_labels_tensor        = output_labels->template tensor<int,1>();\n\t\t\tauto output_scores_tensor        = output_scores->template tensor<T,1>();\n\t\t\tauto output_remove_indict_tensor = output_remove_indict->template tensor<bool,1>();\n\n\t\t\tBoxesEncodeUnit<CPUDevice,T> encode_unit(pos_threshold,neg_threshold,prio_scaling,max_overlap_as_pos_);\n\t\t\tauto &boxes              = bottom_boxes;\n\t\t\tauto &gboxes             = bottom_gboxes;\n\t\t\tauto &glabels            = bottom_glabels;\n\t\t\tauto &out_boxes          = output_boxes_tensor;\n\t\t\tauto &out_labels         = output_labels_tensor;\n\t\t\tauto &out_scores         = output_scores_tensor;\n\t\t\tauto &out_remove_indices = output_remove_indict_tensor;\n\t\t\tauto  res                = encode_unit(boxes,gboxes,glabels);\n\n\t\t\tout_boxes           =  std::get<0>(res);\n\t\t\tout_labels          =  std::get<1>(res);\n\t\t\tout_scores          =  std::get<2>(res);\n\t\t\tout_remove_indices  =  std::get<3>(res);\n\t\t}\n\tprivate:\n\t\tfloat         pos_threshold;\n\t\tfloat         neg_threshold;\n\t\tvector<float> prio_scaling;\n        bool max_overlap_as_pos_ = true;\n};\ntemplate <typename T>\nclass BoxesEncode1Op<GPUDevice,T>: public OpKernel {\n\tpublic:\n        struct IOUIndex{\n            int index;\n            float iou;\n        };\n\t\texplicit BoxesEncode1Op(OpKernelConstruction* context) : OpKernel(context) {\n\t\t\tOP_REQUIRES_OK(context, context->GetAttr(\"pos_threshold\", &pos_threshold));\n\t\t\tOP_REQUIRES_OK(context, context->GetAttr(\"neg_threshold\", &neg_threshold));\n\t\t\tOP_REQUIRES_OK(context, context->GetAttr(\"prio_scaling\", &prio_scaling));\n\t\t\tOP_REQUIRES_OK(context, context->GetAttr(\"max_overlap_as_pos\", &max_overlap_as_pos_));\n\t\t\tOP_REQUIRES(context, prio_scaling.size() == 4, errors::InvalidArgument(\"prio scaling data must be shape[4]\"));\n\t\t}\n\n\t\tvoid Compute(OpKernelContext* context) override\n        {\n            TIME_THISV1(\"BoxesEncode1\");\n            const Tensor &_bottom_boxes   = context->input(0);\n            const Tensor &_bottom_gboxes  = context->input(1);\n            const Tensor &_bottom_glabels = context->input(2);\n            auto          bottom_boxes    = _bottom_boxes.template tensor<T,2>();\n            auto          bottom_gboxes   = _bottom_gboxes.template tensor<T,2>();\n            auto          bottom_glabels  = _bottom_glabels.template tensor<int,1>();\n            const auto    data_nr         = _bottom_boxes.dim_size(0);\n\n            OP_REQUIRES(context, _bottom_boxes.dims() == 2, errors::InvalidArgument(\"box data must be 2-dimensional\"));\n            OP_REQUIRES(context, _bottom_gboxes.dims() == 2, errors::InvalidArgument(\"box data must be 2-dimensional\"));\n            OP_REQUIRES(context, _bottom_glabels.dims() == 1, errors::InvalidArgument(\"labels data must be 1-dimensional\"));\n\n            int           dims_2d[2]            = {int(data_nr),4};\n            int           dims_1d[1]            = {int(data_nr)};\n            TensorShape   outshape0;\n            TensorShape   outshape1;\n            Tensor       *output_boxes          = NULL;\n            Tensor       *output_labels         = NULL;\n            Tensor       *output_scores         = NULL;\n            Tensor       *output_remove_indict  = NULL;\n            vector<IOUIndex>   iou_indexs(data_nr,IOUIndex({-1,0.0})); //默认box不与任何ground truth box相交，iou为0\n\n            TensorShapeUtils::MakeShape(dims_2d, 2, &outshape0);\n            TensorShapeUtils::MakeShape(dims_1d, 1, &outshape1);\n\n\n            OP_REQUIRES_OK(context, context->allocate_output(0, outshape0, &output_boxes));\n            OP_REQUIRES_OK(context, context->allocate_output(1, outshape1, &output_labels));\n            OP_REQUIRES_OK(context, context->allocate_output(2, outshape1, &output_scores));\n            OP_REQUIRES_OK(context, context->allocate_output(3, outshape1, &output_remove_indict));\n            auto output_boxes_tensor         = output_boxes->template tensor<T,2>();\n            auto output_labels_tensor        = output_labels->template tensor<int,1>();\n            auto output_scores_tensor        = output_scores->template tensor<T,1>();\n            auto output_remove_indict_tensor = output_remove_indict->template tensor<bool,1>();\n\n            BoxesEncodeUnit<GPUDevice,T> encode_unit(pos_threshold,neg_threshold,prio_scaling,max_overlap_as_pos_);\n            auto size    = bottom_gboxes.dimension(0);\n            auto boxes   = bottom_boxes.data();\n            auto gboxes  = bottom_gboxes.data();\n            auto glabels = bottom_glabels.data();\n            encode_unit(boxes,gboxes,glabels,\n                    output_boxes_tensor.data(),\n                    output_labels_tensor.data(),\n                    output_scores_tensor.data(),\n                    output_remove_indict_tensor.data(),\n                    nullptr,\n                    size,bottom_boxes.dimension(0)\n                    );\n        }\n\tprivate:\n\t\tfloat         pos_threshold;\n\t\tfloat         neg_threshold;\n\t\tvector<float> prio_scaling;\n        bool max_overlap_as_pos_ = true;\n};\n\nREGISTER_OP(\"BoxesEncode1Grad\")\n    .Attr(\"T: {float,double,int32,int64}\")\n\t.Attr(\"threshold:float\")\n \t.Attr(\"prio_scaling: list(float)\")\n    .Input(\"bottom_boxes: T\")\n    .Input(\"bottom_gboxes: T\")\n    .Input(\"bottom_glabels: int32\")\n    .Input(\"grad: T\")\n\t.Output(\"output:T\");\ntemplate <typename Device, typename T>\nclass BoxesEncode1GradOp: public OpKernel {\n\tpublic:\n\t\texplicit BoxesEncode1GradOp(OpKernelConstruction* context) : OpKernel(context) {\n\t\t\tOP_REQUIRES_OK(context, context->GetAttr(\"threshold\", &threshold));\n\t\t\tOP_REQUIRES_OK(context, context->GetAttr(\"prio_scaling\", &prio_scaling));\n\t\t\tOP_REQUIRES(context, prio_scaling.size() == 4, errors::InvalidArgument(\"prio scaling data must be shape[4]\"));\n\t\t}\n\n\t\tvoid Compute(OpKernelContext* context) override\n\t\t{\n\t\t\tconst Tensor &bottom_boxes        = context->input(0);\n\n\t\t\tOP_REQUIRES(context, bottom_boxes.dims() == 2, errors::InvalidArgument(\"box data must be 2-dimensional\"));\n\n\t\t\tTensorShape  outshape0   = bottom_boxes.shape();\n\t\t\tTensor      *output_grad = nullptr;\n\n\t\t\tOP_REQUIRES_OK(context, context->allocate_output(0, outshape0, &output_grad));\n\n\t\t\tauto output_grad_flat = output_grad->template flat<T>();\n\t\t\tauto num_elements     = output_grad->NumElements();\n\t\t\t//cout<<\"num elements:\"<<num_elements<<\",\"<<bottom_boxes.dims()<<\",\"<<bottom_boxes.dim_size(0)<<\",\"<<bottom_boxes.dim_size(1)<<endl;\n\n            for(auto i=0; i<num_elements; ++i)\n                output_grad_flat(i) = 0.0f;\n\t\t}\n\tprivate:\n\t\tfloat threshold;\n\t\tvector<float> prio_scaling;\n};\nREGISTER_KERNEL_BUILDER(Name(\"BoxesEncode1\").Device(DEVICE_CPU).TypeConstraint<float>(\"T\"), BoxesEncode1Op<CPUDevice, float>);\nREGISTER_KERNEL_BUILDER(Name(\"BoxesEncode1Grad\").Device(DEVICE_CPU).TypeConstraint<float>(\"T\"), BoxesEncode1GradOp<CPUDevice, float>);\n#ifdef GOOGLE_CUDA\nREGISTER_KERNEL_BUILDER(Name(\"BoxesEncode1\").Device(DEVICE_GPU).TypeConstraint<float>(\"T\"), BoxesEncode1Op<GPUDevice, float>);\n#endif\n/*\n * bottom_boxes:[Nr,4](ymin,xmin,ymax,xmax) proposal box,相对坐标\n * bottom_regs:[Nr,4],(y,x,h,w)\n * prio_scaling:[4]\n * output:[Nr,4] 相对坐标(ymin,xmin,ymax,xmax)\n */\nREGISTER_OP(\"DecodeBoxes1\")\n    .Attr(\"T: {float, double}\")\n\t.Attr(\"prio_scaling:list(float)\")\n    .Input(\"bottom_boxes: T\")\n    .Input(\"bottom_regs: T\")\n\t.Output(\"output:T\")\n    .SetShapeFn(shape_inference::UnchangedShape);\n\ntemplate <typename Device, typename T>\nclass DecodeBoxes1Op{\n};\ntemplate <typename T>\nclass DecodeBoxes1Op<CPUDevice,T>: public OpKernel {\n\tpublic:\n\t\texplicit DecodeBoxes1Op(OpKernelConstruction* context) : OpKernel(context) {\n\t\t\tOP_REQUIRES_OK(context,\n\t\t\t\t\tcontext->GetAttr(\"prio_scaling\", &prio_scaling));\n\t\t}\n\n\t\tvoid Compute(OpKernelContext* context) override\n\t\t{\n            TIME_THISV1(\"DecodeBoxes1\");\n\t\t\tconst Tensor &bottom_boxes       = context->input(0);\n\t\t\tconst Tensor &bottom_regs        = context->input(1);\n\t\t\tauto          bottom_regs_flat   = bottom_regs.flat<T>();\n\t\t\tauto          bottom_boxes_flat  = bottom_boxes.flat<T>();\n\n\t\t\tOP_REQUIRES(context, bottom_regs.dims() == 2, errors::InvalidArgument(\"regs data must be 2-dimensional\"));\n\t\t\tOP_REQUIRES(context, bottom_boxes.dims() == 2, errors::InvalidArgument(\"pos data must be 2-dimensional\"));\n\t\t\tOP_REQUIRES(context, bottom_boxes.dim_size(0)==bottom_regs.dim_size(0), errors::InvalidArgument(\"First dim size must be equal.\"));\n\t\t\tOP_REQUIRES(context, bottom_boxes.dim_size(1)==4, errors::InvalidArgument(\"Boxes second dim size must be 4.\"));\n\t\t\tOP_REQUIRES(context, bottom_regs.dim_size(1)==4, errors::InvalidArgument(\"Regs second dim size must be 4.\"));\n\t\t\tconst auto nr = bottom_regs.dim_size(0);\n\n\t\t\tTensorShape output_shape = bottom_regs.shape();\n\t\t\t// Create output tensors\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\tfor (auto b = 0; b < nr; ++b) {\n\t\t\t\tconst auto base_offset = b *4;\n\t\t\t\tconst auto regs_data   = bottom_regs_flat.data()+base_offset;\n\t\t\t\tconst auto box_data    = bottom_boxes_flat.data()+base_offset;\n\t\t\t\tfloat      y;\n\t\t\t\tfloat      x;\n\t\t\t\tfloat      href;\n\t\t\t\tfloat      wref;\n\n\t\t\t\tstd::tie(y,x,href,wref) = box_minmax_to_cxywh(box_data);\n\n\t\t\t\tauto cy          = boost::algorithm::clamp<T>(regs_data[0]*prio_scaling[0],-10.0f,10.0f)*href+y;\n\t\t\t\tauto cx          = boost::algorithm::clamp<T>(regs_data[1]*prio_scaling[1],-10.0f,10.0f)*wref+x;\n\t\t\t\tauto h           = href *exp(boost::algorithm::clamp<T>(regs_data[2]*prio_scaling[2],-10.0,10.0));\n\t\t\t\tauto w           = wref *exp(boost::algorithm::clamp<T>(regs_data[3]*prio_scaling[3],-10.0,10.0));\n\t\t\t\tauto output_data = output.data() + base_offset;\n\n\t\t\t\tstd::tie(output_data[0],output_data[1],output_data[2],output_data[3]) = box_cxywh_to_minmax(cy,cx,h,w);\n\t\t\t\ttransform(output_data,output_data+4,output_data,[](T& v) { return boost::algorithm::clamp<T>(v,0.0,1.0);});\n\t\t\t\tif(output_data[0]>output_data[2]) \n\t\t\t\t\toutput_data[2] = output_data[0];\n\t\t\t\tif(output_data[1]>output_data[3])\n\t\t\t\t\toutput_data[3] = output_data[1];\n\t\t\t}\n\t\t}\n\tprivate:\n\t\tstd::vector<float> prio_scaling;\n};\ntemplate <typename T>\nclass DecodeBoxes1Op<GPUDevice,T>: public OpKernel {\n\tpublic:\n\t\texplicit DecodeBoxes1Op(OpKernelConstruction* context) : OpKernel(context) {\n\t\t\tOP_REQUIRES_OK(context,\n\t\t\t\t\tcontext->GetAttr(\"prio_scaling\", &prio_scaling));\n\t\t}\n\n\t\tvoid Compute(OpKernelContext* context) override\n\t\t{\n            TIME_THISV1(\"DecodeBoxesGPU1\");\n\t\t\tconst Tensor &bottom_boxes       = context->input(0);\n\t\t\tconst Tensor &bottom_regs        = context->input(1);\n\t\t\tauto          bottom_regs_flat   = bottom_regs.flat<T>();\n\t\t\tauto          bottom_boxes_flat  = bottom_boxes.flat<T>();\n\n\t\t\tOP_REQUIRES(context, bottom_regs.dims() == 2, errors::InvalidArgument(\"regs data must be 2-dimensional\"));\n\t\t\tOP_REQUIRES(context, bottom_boxes.dims() == 2, errors::InvalidArgument(\"pos data must be 2-dimensional\"));\n\t\t\tOP_REQUIRES(context, bottom_boxes.dim_size(0)==bottom_regs.dim_size(0), errors::InvalidArgument(\"First dim size must be equal.\"));\n\t\t\tOP_REQUIRES(context, bottom_boxes.dim_size(1)==4, errors::InvalidArgument(\"Boxes second dim size must be 4.\"));\n\t\t\tOP_REQUIRES(context, bottom_regs.dim_size(1)==4, errors::InvalidArgument(\"Regs second dim size must be 4.\"));\n\t\t\tconst auto nr = bottom_regs.dim_size(0);\n\n\t\t\tTensorShape output_shape = bottom_regs.shape();\n\t\t\t// Create output tensors\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            if(nr>0)\n                bboxes_decode_by_gpu(bottom_boxes_flat.data(),bottom_regs_flat.data(),prio_scaling.data(),output.data(),nr);\n\t\t}\n\tprivate:\n\t\tstd::vector<float> prio_scaling;\n};\nREGISTER_KERNEL_BUILDER(Name(\"DecodeBoxes1\").Device(DEVICE_CPU).TypeConstraint<float>(\"T\"), DecodeBoxes1Op<CPUDevice, float>);\n#ifdef GOOGLE_CUDA\nREGISTER_KERNEL_BUILDER(Name(\"DecodeBoxes1\").Device(DEVICE_GPU).TypeConstraint<float>(\"T\"), DecodeBoxes1Op<GPUDevice, float>);\n#endif\n", "meta": {"hexsha": "f1ae62b30b082aa9a802bba993a5df33bcb4a3bd", "size": 33138, "ext": "cc", "lang": "C++", "max_stars_repo_path": "tfop/bboxes_encode_decode.cc", "max_stars_repo_name": "vghost2008/wml", "max_stars_repo_head_hexsha": "d0c5a1da6c228e321ae59a563e9ac84aa66266ff", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2019-12-10T17:18:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-01T01:00:35.000Z", "max_issues_repo_path": "tfop/bboxes_encode_decode.cc", "max_issues_repo_name": "vghost2008/wml", "max_issues_repo_head_hexsha": "d0c5a1da6c228e321ae59a563e9ac84aa66266ff", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-08-25T16:16:01.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-10T05:21:19.000Z", "max_forks_repo_path": "tfop/bboxes_encode_decode.cc", "max_forks_repo_name": "vghost2008/wml", "max_forks_repo_head_hexsha": "d0c5a1da6c228e321ae59a563e9ac84aa66266ff", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-12-07T09:57:35.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-06T04:58:10.000Z", "avg_line_length": 46.282122905, "max_line_length": 135, "alphanum_fraction": 0.6622306717, "num_tokens": 8862, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6859494678483918, "lm_q2_score": 0.4882833952958347, "lm_q1q2_score": 0.3349377351623838}}
{"text": "/* Copyright (c) 2012, Julian Straub <jstraub@csail.mit.edu>\n * Licensed under the MIT license. See LICENSE.txt or \n * http://www.opensource.org/licenses/mit-license.php */\n\n#include \"hdp_var.hpp\"\n#include \"hdp_gibbs.hpp\"\n\n#include <iostream>\n#include <fstream>\n#include <vector>\n\n#include <armadillo>\n\nusing namespace std;\nusing namespace arma;\n\nint main(int argc, char** argv)\n{\n\n//  cout<<\" ------------------------ Dir base measure online ------------------- \"<<endl;\n//  // inverse normal wishart base measure\n////  mat x_rand(90,1);\n////  x_rand.randu();\n////  x_rand += 12.0;\n//  vector<Mat<uint32_t> > x(12,zeros<Mat<uint32_t> >(1,90));\n//  for (uint32_t d=0; d<12; d+=3)\n//  {\n//    x[d].zeros();\n//    x[d].cols(0,29) += 1;\n//    x[d].cols(30,59) += 2;\n//    x[d+1].zeros();\n//    x[d+1].cols(0,29) += 1;\n//    x[d+1].cols(60,89) += 1;\n//    x[d+2].zeros();\n//    //x[d+2].rows(0,29) += 1;\n//    //x[d+2].rows(60,89) += 1;\n//  }\n//  vector<Mat<uint32_t> > x_te(1,zeros<Mat<uint32_t> >(1,90));\n//  x[0].zeros();\n//  x[0].cols(0,29) += 1;\n//  x[0].cols(30,59) += 2;\n//\n//  uint32_t Nw = 3;\n////  x[2].randn();\n////  x[2].rows(0,29) -= 8;\n////  x[3].randn();\n////  x[3].rows(0,59) += 4;\n////  x[4].randn();\n////  x[4].rows(0,29) += 4;\n//  Row<double> alphas(Nw);\n//  alphas.ones();\n//  //alphas *= 1.1; // smaller alpha means more uncertainty in the where the good distributions are\n//  double alpha =1.0, gamma=100.0;\n//  Dir dir(alphas);\n//  HDP_var<uint32_t> hdp_onl(dir, alpha, gamma);\n//\n//  hdp_onl.addHeldOut(x_te[0]);\n//  hdp_onl.densityEst(x,Nw,0.9,10,2,1);\n//\n//  cout<<\"x:\"<<endl;\n//  for(uint32_t j=0; j<x.size(); ++j)\n//  {\n//    for(uint32_t i=0; i<x[j].n_cols; ++i)\n//      cout<<x[j](i)<<\" \";\n//    cout<<endl;\n//  }\n\n  cout<<\" ---------------------------------- NIW base measure ---------------------------\" <<endl;\n\n  Col<double> vtheta(2);\n  vtheta << 0.0 << 0.0;\n  Mat<double> delta(2,2);\n  delta << 1.0 << 0.0 <<endr\n    << 0.0 << 1.0 <<endr;\n  double alpha =1.0, gamma=100.0;\n\n  NIW niw(vtheta,4.2,delta,2+2+0.2);\n  HDP_var<double> hdp_onl_NIW(niw, alpha, gamma);\n\n  vector<Mat<double> > xc(12,zeros<Mat<double> >(2,100));\n  for (uint32_t d=0; d<12; d+=2)\n  {\n    xc[d].randn(2,100);\n    xc[d+1].randn(2,100);\n    xc[d+1] += 4; \n  }\n  vector<Mat<double> > xc_te(1,zeros<Mat<double> >(2,100));\n  xc_te[0].randn(2,100);\n \n  hdp_onl_NIW.addHeldOut(xc_te[0]);\n  hdp_onl_NIW.densityEst(xc,1,0.9,30,10,1);\n\n\n//  return 0;\n//\n//  cout<<\" ---------------------------------- Dir base measure ---------------------------\" <<endl;\n//  HDP_gibbs<uint32_t> hdp_dir(dir, alpha, gamma);\n//\n//  vector<Row<uint32_t> > z_ji = hdp_dir.densityEst(x,Nw,10,10,100);\n//  uint32_t J=z_ji.size();\n//\n//  cout<<\"z_ji:\"<<endl;\n//  for(uint32_t j=0; j<J; ++j)\n//  {\n//    for(uint32_t i=0; i<z_ji[j].n_elem; ++i)\n//      cout<<z_ji[j](i)<<\" \";\n//    cout<<endl;\n//  }\n//  cout<<\"x:\"<<endl;\n//  for(uint32_t j=0; j<x.size(); ++j)\n//  {\n//    for(uint32_t i=0; i<x[j].n_cols; ++i)\n//      cout<<x[j](i)<<\" \";\n//    cout<<endl;\n//  }\n//\n//  \n//  return 0;\n\n// not working for now - do not see a use for it currently!\n//\n//  cout<<\" ------------------------ inverse normal wishart base measure ------------------- \"<<endl;\n//  // inverse normal wishart base measure\n//  vector<mat> xx(2,zeros<mat>(90,2));\n//  xx[0].randn();\n//  xx[0].rows(0,29) += 8;\n//  xx[0].rows(30,59) -= 8;\n//  xx[1].randn();\n//  xx[1].rows(0,29) += 8;\n////  xx[2].randn();\n////  xx[2].rows(0,29) -= 8;\n////  xx[3].randn();\n////  xx[3].rows(0,59) += 4;\n////  xx[4].randn();\n////  xx[4].rows(0,29) += 4;\n////\n//  colvec vtheta;\n//  vtheta << 0.0 << 0.0;\n//  mat Delta;\n//  Delta << 2.0 << 0.0 <<endr\n//        << 0.0 << 2.0 <<endr;\n//  double kappa=1.0, nu=3.1;\n//  alpha=1.0;\n//  gamma=1.0;\n//  InvNormWishart inw(vtheta, kappa,Delta, nu);\n//  HDP_gibbs<double> hdp_inw(inw, alpha, gamma);\n//\n//  z_ji = hdp_inw.densityEst(xx,10,10,20);\n//  J=z_ji.size();\n//  cout<<\"z_ji:\"<<endl;\n//  for(uint32_t j=0; j<J; ++j)\n//  {\n//    for(uint32_t i=0; i<z_ji[j].n_elem; ++i)\n//      cout<<z_ji[j](i)<<\" \";\n//    cout<<endl;\n//  }\n\n\n  return 0;\n}\n", "meta": {"hexsha": "6af22272e796dabd211c5312be3b60cecb871d4b", "size": 4108, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/testHdp.cpp", "max_stars_repo_name": "jstraub/bnp", "max_stars_repo_head_hexsha": "11cd28b49e9cf1db96f349181aff57a17672b6a4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 12.0, "max_stars_repo_stars_event_min_datetime": "2015-01-13T01:18:39.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-16T20:16:54.000Z", "max_issues_repo_path": "src/testHdp.cpp", "max_issues_repo_name": "jstraub/bnp", "max_issues_repo_head_hexsha": "11cd28b49e9cf1db96f349181aff57a17672b6a4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2015-07-12T12:58:14.000Z", "max_issues_repo_issues_event_max_datetime": "2015-07-12T12:58:14.000Z", "max_forks_repo_path": "src/testHdp.cpp", "max_forks_repo_name": "jstraub/bnp", "max_forks_repo_head_hexsha": "11cd28b49e9cf1db96f349181aff57a17672b6a4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2017-07-22T05:37:10.000Z", "max_forks_repo_forks_event_max_datetime": "2018-08-26T07:11:34.000Z", "avg_line_length": 25.5155279503, "max_line_length": 101, "alphanum_fraction": 0.5068159688, "num_tokens": 1637, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6859494550081926, "lm_q2_score": 0.4882833952958347, "lm_q1q2_score": 0.33493772889272766}}
{"text": "/* Author: Moritz Allmaras, Texas A&M University, 2007 */\n\n/* $Id: step-29.cc 27661 2012-11-21 14:38:52Z bangerth $ */\n/*    Copyright (C) 2007-2008, 2010-2012 by the deal.II authors and M. Allmaras   */\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// @sect3{Include files}\n\n// The following header files are unchanged from step-7 and have been\n// discussed before:\n\n#include <deal.II/base/quadrature_lib.h>\n#include <deal.II/base/function.h>\n#include <deal.II/base/logstream.h>\n\n#include <deal.II/lac/vector.h>\n#include <deal.II/lac/full_matrix.h>\n#include <deal.II/lac/sparse_matrix.h>\n\n#include <deal.II/grid/tria.h>\n#include <deal.II/grid/grid_generator.h>\n#include <deal.II/grid/tria_accessor.h>\n#include <deal.II/grid/tria_iterator.h>\n#include <deal.II/grid/tria_boundary_lib.h>\n\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\n#include <deal.II/fe/fe_q.h>\n#include <deal.II/fe/fe_values.h>\n\n#include <deal.II/numerics/matrix_tools.h>\n#include <deal.II/numerics/data_out.h>\n#include <deal.II/numerics/vector_tools.h>\n\n#include <fstream>\n\n// This header file contains the necessary declarations for the\n// ParameterHandler class that we will use to read our parameters from a\n// configuration file:\n#include <deal.II/base/parameter_handler.h>\n\n// For solving the linear system, we'll use the sparse LU-decomposition\n// provided by UMFPACK (see the SparseDirectUMFPACK class), for which the\n// following header file is needed.  Note that in order to compile this\n// tutorial program, the deal.II-library needs to be built with UMFPACK\n// support, which can be most easily achieved by giving the <code>\n// --with-umfpack</code> switch when configuring the library:\n#include <deal.II/lac/sparse_direct.h>\n\n// The FESystem class allows us to stack several FE-objects to one compound,\n// vector-valued finite element field. The necessary declarations for this\n// class are provided in this header file:\n#include <deal.II/fe/fe_system.h>\n\n// Finally, include the header file that declares the Timer class that we will\n// use to determine how much time each of the operations of our program takes:\n#include <deal.II/base/timer.h>\n\n// As the last step at the beginning of this program, we put everything that\n// is in this program into its namespace and, within it, make everything that\n// is in the deal.II namespace globally available, without the need to prefix\n// everything with <code>dealii</code><code>::</code>:\nnamespace Step29\n{\n  using namespace dealii;\n\n\n  // @sect3{The <code>DirichletBoundaryValues</code> class}\n\n  // First we define a class for the function representing the Dirichlet\n  // boundary values. This has been done many times before and therefore does\n  // not need much explanation.\n  //\n  // Since there are two values $v$ and $w$ that need to be prescribed at the\n  // boundary, we have to tell the base class that this is a vector-valued\n  // function with two components, and the <code>vector_value</code> function\n  // and its cousin <code>vector_value_list</code> must return vectors with\n  // two entries. In our case the function is very simple, it just returns 1\n  // for the real part $v$ and 0 for the imaginary part $w$ regardless of the\n  // point where it is evaluated.\n  template <int dim>\n  class DirichletBoundaryValues : public Function<dim>\n  {\n  public:\n    DirichletBoundaryValues() : Function<dim> (2) {};\n\n    virtual void vector_value (const Point<dim> &p,\n                               Vector<double>   &values) const;\n\n    virtual void vector_value_list (const std::vector<Point<dim> > &points,\n                                    std::vector<Vector<double> >   &value_list) const;\n  };\n\n\n  template <int dim>\n  inline\n  void DirichletBoundaryValues<dim>::vector_value (const Point<dim> & /*p*/,\n                                                   Vector<double>   &values) const\n  {\n    Assert (values.size() == 2, ExcDimensionMismatch (values.size(), 2));\n\n    values(0) = 1;\n    values(1) = 0;\n  }\n\n\n  template <int dim>\n  void DirichletBoundaryValues<dim>::vector_value_list (const std::vector<Point<dim> > &points,\n                                                        std::vector<Vector<double> >   &value_list) const\n  {\n    Assert (value_list.size() == points.size(),\n            ExcDimensionMismatch (value_list.size(), points.size()));\n\n    for (unsigned int p=0; p<points.size(); ++p)\n      DirichletBoundaryValues<dim>::vector_value (points[p], value_list[p]);\n  }\n\n  // @sect3{The <code>ParameterReader</code> class}\n\n  // The next class is responsible for preparing the ParameterHandler object\n  // and reading parameters from an input file.  It includes a function\n  // <code>declare_parameters</code> that declares all the necessary\n  // parameters and a <code>read_parameters</code> function that is called\n  // from outside to initiate the parameter reading process.\n  class ParameterReader : public Subscriptor\n  {\n  public:\n    ParameterReader(ParameterHandler &);\n    void read_parameters(const std::string);\n\n  private:\n    void declare_parameters();\n    ParameterHandler &prm;\n  };\n\n  // The constructor stores a reference to the ParameterHandler object that is\n  // passed to it:\n  ParameterReader::ParameterReader(ParameterHandler &paramhandler)\n    :\n    prm(paramhandler)\n  {}\n\n  // @sect4{<code>ParameterReader::declare_parameters</code>}\n\n  // The <code>declare_parameters</code> function declares all the parameters\n  // that our ParameterHandler object will be able to read from input files,\n  // along with their types, range conditions and the subsections they appear\n  // in. We will wrap all the entries that go into a section in a pair of\n  // braces to force the editor to indent them by one level, making it simpler\n  // to read which entries together form a section:\n  void ParameterReader::declare_parameters()\n  {\n    // Parameters for mesh and geometry include the number of global\n    // refinement steps that are applied to the initial coarse mesh and the\n    // focal distance $d$ of the transducer lens. For the number of refinement\n    // steps, we allow integer values in the range $[0,\\infty)$, where the\n    // omitted second argument to the Patterns::Integer object denotes the\n    // half-open interval.  For the focal distance any number greater than\n    // zero is accepted:\n    prm.enter_subsection (\"Mesh & geometry parameters\");\n    {\n      prm.declare_entry(\"Number of refinements\", \"6\",\n                        Patterns::Integer(0),\n                        \"Number of global mesh refinement steps \"\n                        \"applied to initial coarse grid\");\n\n      prm.declare_entry(\"Focal distance\", \"0.3\",\n                        Patterns::Double(0),\n                        \"Distance of the focal point of the lens \"\n                        \"to the x-axis\");\n    }\n    prm.leave_subsection ();\n\n    // The next subsection is devoted to the physical parameters appearing in\n    // the equation, which are the frequency $\\omega$ and wave speed\n    // $c$. Again, both need to lie in the half-open interval $[0,\\infty)$\n    // represented by calling the Patterns::Double class with only the left\n    // end-point as argument:\n    prm.enter_subsection (\"Physical constants\");\n    {\n      prm.declare_entry(\"c\", \"1.5e5\",\n                        Patterns::Double(0),\n                        \"Wave speed\");\n\n      prm.declare_entry(\"omega\", \"5.0e7\",\n                        Patterns::Double(0),\n                        \"Frequency\");\n    }\n    prm.leave_subsection ();\n\n\n    // Last but not least we would like to be able to change some properties\n    // of the output, like filename and format, through entries in the\n    // configuration file, which is the purpose of the last subsection:\n    prm.enter_subsection (\"Output parameters\");\n    {\n      prm.declare_entry(\"Output file\", \"solution\",\n                        Patterns::Anything(),\n                        \"Name of the output file (without extension)\");\n\n      // Since different output formats may require different parameters for\n      // generating output (like for example, postscript output needs\n      // viewpoint angles, line widths, colors etc), it would be cumbersome if\n      // we had to declare all these parameters by hand for every possible\n      // output format supported in the library. Instead, each output format\n      // has a <code>FormatFlags::declare_parameters</code> function, which\n      // declares all the parameters specific to that format in an own\n      // subsection. The following call of\n      // DataOutInterface<1>::declare_parameters executes\n      // <code>declare_parameters</code> for all available output formats, so\n      // that for each format an own subsection will be created with\n      // parameters declared for that particular output format. (The actual\n      // value of the template parameter in the call, <code>@<1@></code>\n      // above, does not matter here: the function does the same work\n      // independent of the dimension, but happens to be in a\n      // template-parameter-dependent class.)  To find out what parameters\n      // there are for which output format, you can either consult the\n      // documentation of the DataOutBase class, or simply run this program\n      // without a parameter file present. It will then create a file with all\n      // declared parameters set to their default values, which can\n      // conveniently serve as a starting point for setting the parameters to\n      // the values you desire.\n      DataOutInterface<1>::declare_parameters (prm);\n    }\n    prm.leave_subsection ();\n  }\n\n  // @sect4{<code>ParameterReader::read_parameters</code>}\n\n  // This is the main function in the ParameterReader class.  It gets called\n  // from outside, first declares all the parameters, and then reads them from\n  // the input file whose filename is provided by the caller. After the call\n  // to this function is complete, the <code>prm</code> object can be used to\n  // retrieve the values of the parameters read in from the file:\n  void ParameterReader::read_parameters (const std::string parameter_file)\n  {\n    declare_parameters();\n\n    prm.read_input (parameter_file);\n  }\n\n\n\n  // @sect3{The <code>ComputeIntensity</code> class}\n\n  // As mentioned in the introduction, the quantity that we are really after\n  // is the spatial distribution of the intensity of the ultrasound wave,\n  // which corresponds to $|u|=\\sqrt{v^2+w^2}$. Now we could just be content\n  // with having $v$ and $w$ in our output, and use a suitable visualization\n  // or postprocessing tool to derive $|u|$ from the solution we\n  // computed. However, there is also a way to output data derived from the\n  // solution in deal.II, and we are going to make use of this mechanism here.\n\n  // So far we have always used the DataOut::add_data_vector function to add\n  // vectors containing output data to a DataOut object.  There is a special\n  // version of this function that in addition to the data vector has an\n  // additional argument of type DataPostprocessor. What happens when this\n  // function is used for output is that at each point where output data is to\n  // be generated, the DataPostprocessor::compute_derived_quantities_scalar or\n  // DataPostprocessor::compute_derived_quantities_vector function of the\n  // specified DataPostprocessor object is invoked to compute the output\n  // quantities from the values, the gradients and the second derivatives of\n  // the finite element function represented by the data vector (in the case\n  // of face related data, normal vectors are available as well). Hence, this\n  // allows us to output any quantity that can locally be derived from the\n  // values of the solution and its derivatives.  Of course, the ultrasound\n  // intensity $|u|$ is such a quantity and its computation doesn't even\n  // involve any derivatives of $v$ or $w$.\n\n  // In practice, the DataPostprocessor class only provides an interface to\n  // this functionality, and we need to derive our own class from it in order\n  // to implement the functions specified by the interface. In the most\n  // general case one has to implement several member functions but if the\n  // output quantity is a single scalar then some of this boilerplate code can\n  // be handled by a more specialized class, DataPostprocessorScalar and we\n  // can derive from that one instead. This is what the\n  // <code>ComputeIntensity</code> class does:\n  template <int dim>\n  class ComputeIntensity : public DataPostprocessorScalar<dim>\n  {\n  public:\n    ComputeIntensity ();\n\n    virtual\n    void\n    compute_derived_quantities_vector (const std::vector< Vector< double > > &uh,\n                                       const std::vector< std::vector< Tensor< 1, dim > > > &duh,\n                                       const std::vector< std::vector< Tensor< 2, dim > > > &dduh,\n                                       const std::vector< Point< dim > > &normals,\n                                       const std::vector<Point<dim> > &evaluation_points,\n                                       std::vector< Vector< double > > &computed_quantities) const;\n  };\n\n  // In the constructor, we need to call the constructor of the base class\n  // with two arguments. The first denotes the name by which the single scalar\n  // quantity computed by this class should be represented in output files. In\n  // our case, the postprocessor has $|u|$ as output, so we use \"Intensity\".\n  //\n  // The second argument is a set of flags that indicate which data is needed\n  // by the postprocessor in order to compute the output quantities.  This can\n  // be any subset of update_values, update_gradients and update_hessians\n  // (and, in the case of face data, also update_normal_vectors), which are\n  // documented in UpdateFlags.  Of course, computation of the derivatives\n  // requires additional resources, so only the flags for data that is really\n  // needed should be given here, just as we do when we use FEValues objects.\n  // In our case, only the function values of $v$ and $w$ are needed to\n  // compute $|u|$, so we're good with the update_values flag.\n  template <int dim>\n  ComputeIntensity<dim>::ComputeIntensity ()\n    :\n    DataPostprocessorScalar<dim> (\"Intensity\",\n                                  update_values)\n  {}\n\n\n  // The actual prostprocessing happens in the following function.  Its inputs\n  // are a vector representing values of the function (which is here\n  // vector-valued) representing the data vector given to\n  // DataOut::add_data_vector, evaluated at all evaluation points where we\n  // generate output, and some tensor objects representing derivatives (that\n  // we don't use here since $|u|$ is computed from just $v$ and $w$, and for\n  // which we assign no name to the corresponding function argument).  The\n  // derived quantities are returned in the <code>computed_quantities</code>\n  // vector.  Remember that this function may only use data for which the\n  // respective update flag is specified by\n  // <code>get_needed_update_flags</code>. For example, we may not use the\n  // derivatives here, since our implementation of\n  // <code>get_needed_update_flags</code> requests that only function values\n  // are provided.\n  template <int dim>\n  void\n  ComputeIntensity<dim>::compute_derived_quantities_vector (\n    const std::vector< Vector< double > >                  &uh,\n    const std::vector< std::vector< Tensor< 1, dim > > >  & /*duh*/,\n    const std::vector< std::vector< Tensor< 2, dim > > >  & /*dduh*/,\n    const std::vector< Point< dim > >                     & /*normals*/,\n    const std::vector<Point<dim> >                        & /*evaluation_points*/,\n    std::vector< Vector< double > >                        &computed_quantities\n  ) const\n  {\n    Assert(computed_quantities.size() == uh.size(),\n           ExcDimensionMismatch (computed_quantities.size(), uh.size()));\n\n    // The computation itself is straightforward: We iterate over each entry\n    // in the output vector and compute $|u|$ from the corresponding values of\n    // $v$ and $w$:\n    for (unsigned int i=0; i<computed_quantities.size(); i++)\n      {\n        Assert(computed_quantities[i].size() == 1,\n               ExcDimensionMismatch (computed_quantities[i].size(), 1));\n        Assert(uh[i].size() == 2, ExcDimensionMismatch (uh[i].size(), 2));\n\n        computed_quantities[i](0) = sqrt(uh[i](0)*uh[i](0) + uh[i](1)*uh[i](1));\n      }\n  }\n\n\n  // @sect3{The <code>UltrasoundProblem</code> class}\n\n  // Finally here is the main class of this program.  It's member functions\n  // are very similar to the previous examples, in particular step-4, and the\n  // list of member variables does not contain any major surprises either.\n  // The ParameterHandler object that is passed to the constructor is stored\n  // as a reference to allow easy access to the parameters from all functions\n  // of the class.  Since we are working with vector valued finite elements,\n  // the FE object we are using is of type FESystem.\n  template <int dim>\n  class UltrasoundProblem\n  {\n  public:\n    UltrasoundProblem (ParameterHandler &);\n    ~UltrasoundProblem ();\n    void run ();\n\n  private:\n    void make_grid ();\n    void setup_system ();\n    void assemble_system ();\n    void solve ();\n    void output_results () const;\n\n    ParameterHandler      &prm;\n\n    Triangulation<dim>     triangulation;\n    DoFHandler<dim>        dof_handler;\n    FESystem<dim>          fe;\n\n    SparsityPattern        sparsity_pattern;\n    SparseMatrix<double>   system_matrix;\n    Vector<double>         solution, system_rhs;\n  };\n\n\n\n  // The constructor takes the ParameterHandler object and stores it in a\n  // reference. It also initializes the DoF-Handler and the finite element\n  // system, which consists of two copies of the scalar Q1 field, one for $v$\n  // and one for $w$:\n  template <int dim>\n  UltrasoundProblem<dim>::UltrasoundProblem (ParameterHandler &param)\n    :\n    prm(param),\n    dof_handler(triangulation),\n    fe(FE_Q<dim>(1), 2)\n  {}\n\n\n  template <int dim>\n  UltrasoundProblem<dim>::~UltrasoundProblem ()\n  {\n    dof_handler.clear();\n  }\n\n  // @sect4{<code>UltrasoundProblem::make_grid</code>}\n\n  // Here we setup the grid for our domain.  As mentioned in the exposition,\n  // the geometry is just a unit square (in 2d) with the part of the boundary\n  // that represents the transducer lens replaced by a sector of a circle.\n  template <int dim>\n  void UltrasoundProblem<dim>::make_grid ()\n  {\n    // First we generate some logging output and start a timer so we can\n    // compute execution time when this function is done:\n    deallog << \"Generating grid... \";\n    Timer timer;\n    timer.start ();\n\n    // Then we query the values for the focal distance of the transducer lens\n    // and the number of mesh refinement steps from our ParameterHandler\n    // object:\n    prm.enter_subsection (\"Mesh & geometry parameters\");\n\n    const double                focal_distance = prm.get_double(\"Focal distance\");\n    const unsigned int  n_refinements  = prm.get_integer(\"Number of refinements\");\n\n    prm.leave_subsection ();\n\n    // Next, two points are defined for position and focal point of the\n    // transducer lens, which is the center of the circle whose segment will\n    // form the transducer part of the boundary. We compute the radius of this\n    // circle in such a way that the segment fits in the interval [0.4,0.6] on\n    // the x-axis.  Notice that this is the only point in the program where\n    // things are slightly different in 2D and 3D.  Even though this tutorial\n    // only deals with the 2D case, the necessary additions to make this\n    // program functional in 3D are so minimal that we opt for including them:\n    const Point<dim>    transducer = (dim == 2) ?\n                                     Point<dim> (0.5, 0.0) :\n                                     Point<dim> (0.5, 0.5, 0.0),\n                                     focal_point = (dim == 2) ?\n                                                   Point<dim> (0.5, focal_distance) :\n                                                   Point<dim> (0.5, 0.5, focal_distance);\n\n    const double radius = std::sqrt( (focal_point.distance(transducer) *\n                                      focal_point.distance(transducer)) +\n                                     ((dim==2) ? 0.01 : 0.02));\n\n\n    // As initial coarse grid we take a simple unit square with 5 subdivisions\n    // in each direction. The number of subdivisions is chosen so that the\n    // line segment $[0.4,0.6]$ that we want to designate as the transducer\n    // boundary is spanned by a single face. Then we step through all cells to\n    // find the faces where the transducer is to be located, which in fact is\n    // just the single edge from 0.4 to 0.6 on the x-axis. This is where we\n    // want the refinements to be made according to a circle shaped boundary,\n    // so we mark this edge with a different boundary indicator.\n    GridGenerator::subdivided_hyper_cube (triangulation, 5, 0, 1);\n\n    typename Triangulation<dim>::cell_iterator\n    cell = triangulation.begin (),\n    endc = triangulation.end();\n\n    for (; cell!=endc; ++cell)\n      for (unsigned int face=0; face<GeometryInfo<dim>::faces_per_cell; ++face)\n        if ( cell->face(face)->at_boundary() &&\n             ((cell->face(face)->center() - transducer).square() < 0.01) )\n\n          cell->face(face)->set_boundary_indicator (1);\n\n    // For the circle part of the transducer lens, a hyper-ball object is used\n    // (which, of course, in 2D just represents a circle), with radius and\n    // center as computed above. By marking this object as\n    // <code>static</code>, we ensure that it lives until the end of the\n    // program and thereby longer than the triangulation object we will\n    // associated with it. We then assign this boundary-object to the part of\n    // the boundary with boundary indicator 1:\n    static const HyperBallBoundary<dim> boundary(focal_point, radius);\n    triangulation.set_boundary(1, boundary);\n\n    // Now global refinement is executed. Cells near the transducer location\n    // will be automatically refined according to the circle shaped boundary\n    // of the transducer lens:\n    triangulation.refine_global (n_refinements);\n\n    // Lastly, we generate some more logging output. We stop the timer and\n    // query the number of CPU seconds elapsed since the beginning of the\n    // function:\n    timer.stop ();\n    deallog << \"done (\"\n            << timer()\n            << \"s)\"\n            << std::endl;\n\n    deallog << \"  Number of active cells:  \"\n            << triangulation.n_active_cells()\n            << std::endl;\n  }\n\n\n  // @sect4{<code>UltrasoundProblem::setup_system</code>}\n  //\n  // Initialization of the system matrix, sparsity patterns and vectors are\n  // the same as in previous examples and therefore do not need further\n  // comment. As in the previous function, we also output the run time of what\n  // we do here:\n  template <int dim>\n  void UltrasoundProblem<dim>::setup_system ()\n  {\n    deallog << \"Setting up system... \";\n    Timer timer;\n    timer.start();\n\n    dof_handler.distribute_dofs (fe);\n\n    sparsity_pattern.reinit (dof_handler.n_dofs(),\n                             dof_handler.n_dofs(),\n                             dof_handler.max_couplings_between_dofs());\n\n    DoFTools::make_sparsity_pattern (dof_handler, sparsity_pattern);\n    sparsity_pattern.compress();\n\n    system_matrix.reinit (sparsity_pattern);\n    system_rhs.reinit (dof_handler.n_dofs());\n    solution.reinit (dof_handler.n_dofs());\n\n    timer.stop ();\n    deallog << \"done (\"\n            << timer()\n            << \"s)\"\n            << std::endl;\n\n    deallog << \"  Number of degrees of freedom: \"\n            << dof_handler.n_dofs()\n            << std::endl;\n  }\n\n\n  // @sect4{<code>UltrasoundProblem::assemble_system</code>}\n\n  // As before, this function takes care of assembling the system matrix and\n  // right hand side vector:\n  template <int dim>\n  void UltrasoundProblem<dim>::assemble_system ()\n  {\n    deallog << \"Assembling system matrix... \";\n    Timer timer;\n    timer.start ();\n\n    // First we query wavespeed and frequency from the ParameterHandler object\n    // and store them in local variables, as they will be used frequently\n    // throughout this function.\n\n    prm.enter_subsection (\"Physical constants\");\n\n    const double omega = prm.get_double(\"omega\"),\n                 c     = prm.get_double(\"c\");\n\n    prm.leave_subsection ();\n\n    // As usual, for computing integrals ordinary Gauss quadrature rule is\n    // used. Since our bilinear form involves boundary integrals on\n    // $\\Gamma_2$, we also need a quadrature rule for surface integration on\n    // the faces, which are $dim-1$ dimensional:\n    QGauss<dim>    quadrature_formula(2);\n    QGauss<dim-1>  face_quadrature_formula(2);\n\n    const unsigned int n_q_points       = quadrature_formula.size(),\n                       n_face_q_points  = face_quadrature_formula.size(),\n                       dofs_per_cell    = fe.dofs_per_cell;\n\n    // The FEValues objects will evaluate the shape functions for us.  For the\n    // part of the bilinear form that involves integration on $\\Omega$, we'll\n    // need the values and gradients of the shape functions, and of course the\n    // quadrature weights.  For the terms involving the boundary integrals,\n    // only shape function values and the quadrature weights are necessary.\n    FEValues<dim>  fe_values (fe, quadrature_formula,\n                              update_values | update_gradients |\n                              update_JxW_values);\n\n    FEFaceValues<dim> fe_face_values (fe, face_quadrature_formula,\n                                      update_values | update_JxW_values);\n\n    // As usual, the system matrix is assembled cell by cell, and we need a\n    // matrix for storing the local cell contributions as well as an index\n    // vector to transfer the cell contributions to the appropriate location\n    // in the global system matrix after.\n    FullMatrix<double> cell_matrix (dofs_per_cell, dofs_per_cell);\n    std::vector<unsigned int> local_dof_indices (dofs_per_cell);\n\n    typename DoFHandler<dim>::active_cell_iterator\n    cell = dof_handler.begin_active(),\n    endc = dof_handler.end();\n\n    for (; cell!=endc; ++cell)\n      {\n\n        // On each cell, we first need to reset the local contribution matrix\n        // and request the FEValues object to compute the shape functions for\n        // the current cell:\n        cell_matrix = 0;\n        fe_values.reinit (cell);\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              {\n\n                // At this point, it is important to keep in mind that we are\n                // dealing with a finite element system with two\n                // components. Due to the way we constructed this FESystem,\n                // namely as the cartesian product of two scalar finite\n                // element fields, each shape function has only a single\n                // nonzero component (they are, in deal.II lingo, @ref\n                // GlossPrimitive \"primitive\").  Hence, each shape function\n                // can be viewed as one of the $\\phi$'s or $\\psi$'s from the\n                // introduction, and similarly the corresponding degrees of\n                // freedom can be attributed to either $\\alpha$ or $\\beta$.\n                // As we iterate through all the degrees of freedom on the\n                // current cell however, they do not come in any particular\n                // order, and so we cannot decide right away whether the DoFs\n                // with index $i$ and $j$ belong to the real or imaginary part\n                // of our solution.  On the other hand, if you look at the\n                // form of the system matrix in the introduction, this\n                // distinction is crucial since it will determine to which\n                // block in the system matrix the contribution of the current\n                // pair of DoFs will go and hence which quantity we need to\n                // compute from the given two shape functions.  Fortunately,\n                // the FESystem object can provide us with this information,\n                // namely it has a function\n                // FESystem::system_to_component_index, that for each local\n                // DoF index returns a pair of integers of which the first\n                // indicates to which component of the system the DoF\n                // belongs. The second integer of the pair indicates which\n                // index the DoF has in the scalar base finite element field,\n                // but this information is not relevant here. If you want to\n                // know more about this function and the underlying scheme\n                // behind primitive vector valued elements, take a look at\n                // step-8 or the @ref vector_valued module, where these topics\n                // are explained in depth.\n                if (fe.system_to_component_index(i).first ==\n                    fe.system_to_component_index(j).first)\n                  {\n\n                    // If both DoFs $i$ and $j$ belong to same component,\n                    // i.e. their shape functions are both $\\phi$'s or both\n                    // $\\psi$'s, the contribution will end up in one of the\n                    // diagonal blocks in our system matrix, and since the\n                    // corresponding entries are computed by the same formula,\n                    // we do not bother if they actually are $\\phi$ or $\\psi$\n                    // shape functions. We can simply compute the entry by\n                    // iterating over all quadrature points and adding up\n                    // their contributions, where values and gradients of the\n                    // shape functions are supplied by our FEValues object.\n\n                    for (unsigned int q_point=0; q_point<n_q_points; ++q_point)\n                      cell_matrix(i,j) += (((fe_values.shape_value(i,q_point) *\n                                             fe_values.shape_value(j,q_point)) *\n                                            (- omega * omega)\n                                            +\n                                            (fe_values.shape_grad(i,q_point) *\n                                             fe_values.shape_grad(j,q_point)) *\n                                            c * c) *\n                                           fe_values.JxW(q_point));\n\n                    // You might think that we would have to specify which\n                    // component of the shape function we'd like to evaluate\n                    // when requesting shape function values or gradients from\n                    // the FEValues object. However, as the shape functions\n                    // are primitive, they have only one nonzero component,\n                    // and the FEValues class is smart enough to figure out\n                    // that we are definitely interested in this one nonzero\n                    // component.\n                  }\n              }\n          }\n\n\n        // We also have to add contributions due to boundary terms. To this\n        // end, we loop over all faces of the current cell and see if first it\n        // is at the boundary, and second has the correct boundary indicator\n        // associated with $\\Gamma_2$, the part of the boundary where we have\n        // absorbing boundary conditions:\n        for (unsigned int face=0; face<GeometryInfo<dim>::faces_per_cell; ++face)\n          if (cell->face(face)->at_boundary() &&\n              (cell->face(face)->boundary_indicator() == 0) )\n            {\n\n\n              // These faces will certainly contribute to the off-diagonal\n              // blocks of the system matrix, so we ask the FEFaceValues\n              // object to provide us with the shape function values on this\n              // face:\n              fe_face_values.reinit (cell, face);\n\n\n              // Next, we loop through all DoFs of the current cell to find\n              // pairs that belong to different components and both have\n              // support on the current face:\n              for (unsigned int i=0; i<dofs_per_cell; ++i)\n                for (unsigned int j=0; j<dofs_per_cell; ++j)\n                  if ((fe.system_to_component_index(i).first !=\n                       fe.system_to_component_index(j).first) &&\n                      fe.has_support_on_face(i, face) &&\n                      fe.has_support_on_face(j, face))\n                    // The check whether shape functions have support on a\n                    // face is not strictly necessary: if we don't check for\n                    // it we would simply add up terms to the local cell\n                    // matrix that happen to be zero because at least one of\n                    // the shape functions happens to be zero. However, we can\n                    // save that work by adding the checks above.\n\n                    // In either case, these DoFs will contribute to the\n                    // boundary integrals in the off-diagonal blocks of the\n                    // system matrix. To compute the integral, we loop over\n                    // all the quadrature points on the face and sum up the\n                    // contribution weighted with the quadrature weights that\n                    // the face quadrature rule provides.  In contrast to the\n                    // entries on the diagonal blocks, here it does matter\n                    // which one of the shape functions is a $\\psi$ and which\n                    // one is a $\\phi$, since that will determine the sign of\n                    // the entry.  We account for this by a simple conditional\n                    // statement that determines the correct sign. Since we\n                    // already checked that DoF $i$ and $j$ belong to\n                    // different components, it suffices here to test for one\n                    // of them to which component it belongs.\n                    for (unsigned int q_point=0; q_point<n_face_q_points; ++q_point)\n                      cell_matrix(i,j) += ((fe.system_to_component_index(i).first == 0) ? -1 : 1) *\n                                          fe_face_values.shape_value(i,q_point) *\n                                          fe_face_values.shape_value(j,q_point) *\n                                          c *\n                                          omega *\n                                          fe_face_values.JxW(q_point);\n            }\n\n        // Now we are done with this cell and have to transfer its\n        // contributions from the local to the global system matrix. To this\n        // end, we first get a list of the global indices of the this cells\n        // DoFs...\n        cell->get_dof_indices (local_dof_indices);\n\n\n        // ...and then add the entries to the system matrix one by one:\n        for (unsigned int i=0; i<dofs_per_cell; ++i)\n          for (unsigned int j=0; j<dofs_per_cell; ++j)\n            system_matrix.add (local_dof_indices[i],\n                               local_dof_indices[j],\n                               cell_matrix(i,j));\n      }\n\n\n    // The only thing left are the Dirichlet boundary values on $\\Gamma_1$,\n    // which is characterized by the boundary indicator 1. The Dirichlet\n    // values are provided by the <code>DirichletBoundaryValues</code> class\n    // we defined above:\n    std::map<unsigned int,double> boundary_values;\n    VectorTools::interpolate_boundary_values (dof_handler,\n                                              1,\n                                              DirichletBoundaryValues<dim>(),\n                                              boundary_values);\n\n    MatrixTools::apply_boundary_values (boundary_values,\n                                        system_matrix,\n                                        solution,\n                                        system_rhs);\n\n    timer.stop ();\n    deallog << \"done (\"\n            << timer()\n            << \"s)\"\n            << std::endl;\n  }\n\n\n\n  // @sect4{<code>UltrasoundProblem::solve</code>}\n\n  // As already mentioned in the introduction, the system matrix is neither\n  // symmetric nor definite, and so it is not quite obvious how to come up\n  // with an iterative solver and a preconditioner that do a good job on this\n  // matrix.  We chose instead to go a different way and solve the linear\n  // system with the sparse LU decomposition provided by UMFPACK. This is\n  // often a good first choice for 2D problems and works reasonably well even\n  // for a large number of DoFs.  The deal.II interface to UMFPACK is given by\n  // the SparseDirectUMFPACK class, which is very easy to use and allows us to\n  // solve our linear system with just 3 lines of code.\n\n  // Note again that for compiling this example program, you need to have the\n  // deal.II library built with UMFPACK support, which can be achieved by\n  // providing the <code> --with-umfpack</code> switch to the configure script\n  // prior to compilation of the library.\n  template <int dim>\n  void UltrasoundProblem<dim>::solve ()\n  {\n    deallog << \"Solving linear system... \";\n    Timer timer;\n    timer.start ();\n\n    // The code to solve the linear system is short: First, we allocate an\n    // object of the right type. The following <code>initialize</code> call\n    // provides the matrix that we would like to invert to the\n    // SparseDirectUMFPACK object, and at the same time kicks off the\n    // LU-decomposition. Hence, this is also the point where most of the\n    // computational work in this program happens.\n    SparseDirectUMFPACK  A_direct;\n    A_direct.initialize(system_matrix);\n\n    // After the decomposition, we can use <code>A_direct</code> like a matrix\n    // representing the inverse of our system matrix, so to compute the\n    // solution we just have to multiply with the right hand side vector:\n    A_direct.vmult (solution, system_rhs);\n\n    timer.stop ();\n    deallog << \"done (\"\n            << timer ()\n            << \"s)\"\n            << std::endl;\n  }\n\n\n\n  // @sect4{<code>UltrasoundProblem::output_results</code>}\n\n  // Here we output our solution $v$ and $w$ as well as the derived quantity\n  // $|u|$ in the format specified in the parameter file. Most of the work for\n  // deriving $|u|$ from $v$ and $w$ was already done in the implementation of\n  // the <code>ComputeIntensity</code> class, so that the output routine is\n  // rather straightforward and very similar to what is done in the previous\n  // tutorials.\n  template <int dim>\n  void UltrasoundProblem<dim>::output_results () const\n  {\n    deallog << \"Generating output... \";\n    Timer timer;\n    timer.start ();\n\n    // Define objects of our <code>ComputeIntensity</code> class and a DataOut\n    // object:\n    ComputeIntensity<dim> intensities;\n    DataOut<dim> data_out;\n\n    data_out.attach_dof_handler (dof_handler);\n\n    // Next we query the output-related parameters from the ParameterHandler.\n    // The DataOut::parse_parameters call acts as a counterpart to the\n    // DataOutInterface<1>::declare_parameters call in\n    // <code>ParameterReader::declare_parameters</code>. It collects all the\n    // output format related parameters from the ParameterHandler and sets the\n    // corresponding properties of the DataOut object accordingly.\n    prm.enter_subsection(\"Output parameters\");\n\n    const std::string output_file    = prm.get(\"Output file\");\n    data_out.parse_parameters(prm);\n\n    prm.leave_subsection ();\n\n    // Now we put together the filename from the base name provided by the\n    // ParameterHandler and the suffix which is provided by the DataOut class\n    // (the default suffix is set to the right type that matches the one set\n    // in the .prm file through parse_parameters()):\n    const std::string filename = output_file +\n                                 data_out.default_suffix();\n\n    std::ofstream output (filename.c_str());\n\n    // The solution vectors $v$ and $w$ are added to the DataOut object in the\n    // usual way:\n    std::vector<std::string> solution_names;\n    solution_names.push_back (\"Re_u\");\n    solution_names.push_back (\"Im_u\");\n\n    data_out.add_data_vector (solution, solution_names);\n\n    // For the intensity, we just call <code>add_data_vector</code> again, but\n    // this with our <code>ComputeIntensity</code> object as the second\n    // argument, which effectively adds $|u|$ to the output data:\n    data_out.add_data_vector (solution, intensities);\n\n    // The last steps are as before. Note that the actual output format is now\n    // determined by what is stated in the input file, i.e. one can change the\n    // output format without having to re-compile this program:\n    data_out.build_patches ();\n    data_out.write (output);\n\n    timer.stop ();\n    deallog << \"done (\"\n            << timer()\n            << \"s)\"\n            << std::endl;\n  }\n\n\n\n  // @sect4{<code>UltrasoundProblem::run</code>}\n\n  // Here we simply execute our functions one after the other:\n  template <int dim>\n  void UltrasoundProblem<dim>::run ()\n  {\n    make_grid ();\n    setup_system ();\n    assemble_system ();\n    solve ();\n    output_results ();\n  }\n}\n\n\n// @sect4{The <code>main</code> function}\n\n// Finally the <code>main</code> function of the program. It has the same\n// structure as in almost all of the other tutorial programs. The only\n// exception is that we define ParameterHandler and\n// <code>ParameterReader</code> objects, and let the latter read in the\n// parameter values from a textfile called <code>step-29.prm</code>. The\n// values so read are then handed over to an instance of the UltrasoundProblem\n// class:\nint main ()\n{\n  try\n    {\n      using namespace dealii;\n      using namespace Step29;\n\n      ParameterHandler  prm;\n      ParameterReader   param(prm);\n      param.read_parameters(\"step-29.prm\");\n\n      UltrasoundProblem<2>  ultrasound_problem (prm);\n      ultrasound_problem.run ();\n    }\n  catch (std::exception &exc)\n    {\n      std::cerr << std::endl << std::endl\n                << \"----------------------------------------------------\"\n                << std::endl;\n      std::cerr << \"Exception on processing: \" << std::endl\n                << exc.what() << std::endl\n                << \"Aborting!\" << std::endl\n                << \"----------------------------------------------------\"\n                << std::endl;\n      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  return 0;\n}\n", "meta": {"hexsha": "00ddf2f3e54d1a409bfd0f584bbabe1bd537f5db", "size": 43242, "ext": "cc", "lang": "C++", "max_stars_repo_path": "MHD/examples/step-29/step-29.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-29/step-29.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-29/step-29.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": 44.4419321686, "max_line_length": 105, "alphanum_fraction": 0.6317237871, "num_tokens": 9613, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5544704796847396, "lm_q2_score": 0.6039318337259584, "lm_q1q2_score": 0.33486237354291654}}
{"text": "/* statistic_tests.hpp header file\n *\n * Copyright Jens Maurer 2000\n * Distributed under the Boost Software License, Version 1.0. (See\n * accompanying file LICENSE_1_0.txt or copy at\n * http://www.boost.org/LICENSE_1_0.txt)\n *\n * $Id$\n *\n */\n\n#ifndef STATISTIC_TESTS_HPP\n#define STATISTIC_TESTS_HPP\n\n#include <stdexcept>\n#include <iterator>\n#include <vector>\n#include <boost/limits.hpp>\n#include <algorithm>\n#include <cmath>\n\n#include <boost/config.hpp>\n#include <boost/bind.hpp>\n#include <boost/random/uniform_01.hpp>\n#include <boost/random/variate_generator.hpp>\n\n#include \"integrate.hpp\"\n\n#if defined(BOOST_MSVC) && BOOST_MSVC <= 1300\nnamespace std\n{\n  inline double pow(double a, double b) { return ::pow(a,b); }\n  inline double ceil(double x) { return ::ceil(x); }\n} // namespace std\n#endif\n\n\ntemplate<class T>\ninline T fac(int k)\n{\n  T result = 1;\n  for(T i = 2; i <= k; ++i)\n    result *= i;\n  return result;\n}\n\ntemplate<class T>\nT binomial(int n, int k)\n{\n  if(k < n/2)\n    k = n-k;\n  T result = 1;\n  for(int i = k+1; i<= n; ++i)\n    result *= i;\n  return result / fac<T>(n-k);\n}\n\ntemplate<class T>\nT stirling2(int n, int m)\n{\n  T sum = 0;\n  for(int k = 0; k <= m; ++k)\n    sum += binomial<T>(m, k) * std::pow(double(k), n) *\n      ( (m-k)%2 == 0 ? 1 : -1);\n  return sum / fac<T>(m);\n}\n\n/*\n * Experiments which create an empirical distribution in classes,\n * suitable for the chi-square test.\n */\n// std::floor(gen() * classes)\n\nclass experiment_base\n{\npublic:\n  experiment_base(int cls) : _classes(cls) { }\n  unsigned int classes() const { return _classes; }\nprotected:\n  unsigned int _classes;\n};\n\nclass equidistribution_experiment : public experiment_base\n{\npublic:\n  explicit equidistribution_experiment(unsigned int classes) \n    : experiment_base(classes) { }\n  \n  template<class NumberGenerator, class Counter>\n  void run(NumberGenerator & f, Counter & count, int n) const\n  {\n    assert((f.min)() == 0 &&\n           static_cast<unsigned int>((f.max)()) == classes()-1);\n    for(int i = 0; i < n; ++i)\n      count(f());\n  }\n  double probability(int /*i*/) const { return 1.0/classes(); }\n};\n\n// two-dimensional equidistribution experiment\nclass equidistribution_2d_experiment : public equidistribution_experiment\n{\npublic:\n  explicit equidistribution_2d_experiment(unsigned int classes) \n    : equidistribution_experiment(classes) { }\n\n  template<class NumberGenerator, class Counter>\n  void run(NumberGenerator & f, Counter & count, int n) const\n  {\n    unsigned int range = (f.max)()+1;\n    assert((f.min)() == 0 && range*range == classes());\n    for(int i = 0; i < n; ++i) {\n      int y1 = f();\n      int y2 = f();\n      count(y1 + range * y2);\n    }\n  }\n};\n\n// distribution experiment: assume a probability density and \n// count events so that an equidistribution results.\nclass distribution_experiment : public equidistribution_experiment\n{\npublic:\n  template<class Distribution>\n  distribution_experiment(Distribution dist , unsigned int classes)\n    : equidistribution_experiment(classes), limit(classes)\n  {\n    for(unsigned int i = 0; i < classes-1; ++i)\n      limit[i] = quantile(dist, (i+1)*0.05);\n    limit[classes-1] = std::numeric_limits<double>::infinity();\n    if(limit[classes-1] < (std::numeric_limits<double>::max)())\n      limit[classes-1] = (std::numeric_limits<double>::max)();\n#if 0\n    std::cout << __PRETTY_FUNCTION__ << \": \";\n    for(unsigned int i = 0; i < classes; ++i)\n      std::cout << limit[i] << \" \";\n    std::cout << std::endl;\n#endif\n  }\n\n  template<class NumberGenerator, class Counter>\n  void run(NumberGenerator & f, Counter & count, int n) const\n  {\n    for(int i = 0; i < n; ++i) {\n      limits_type::const_iterator it =\n        std::lower_bound(limit.begin(), limit.end(), f());\n      count(it-limit.begin());\n    }\n  }\nprivate:\n  typedef std::vector<double> limits_type;\n  limits_type limit;\n};\n\ntemplate<bool up, bool is_float>\nstruct runs_direction_helper\n{\n  template<class T>\n  static T init(T)\n  {\n    return (std::numeric_limits<T>::max)();\n  }\n};\n\ntemplate<>\nstruct runs_direction_helper<true, true>\n{\n  template<class T>\n  static T init(T)\n  {\n    return -(std::numeric_limits<T>::max)();\n  }\n};\n\ntemplate<>\nstruct runs_direction_helper<true, false>\n{\n  template<class T>\n  static T init(T)\n  {\n    return (std::numeric_limits<T>::min)();\n  }\n};\n\n// runs-up/runs-down experiment\ntemplate<bool up>\nclass runs_experiment : public experiment_base\n{\npublic:\n  explicit runs_experiment(unsigned int classes) : experiment_base(classes) { }\n  \n  template<class NumberGenerator, class Counter>\n  void run(NumberGenerator & f, Counter & count, int n) const\n  {\n    typedef typename NumberGenerator::result_type result_type;\n    result_type init =\n      runs_direction_helper<\n        up,\n        !std::numeric_limits<result_type>::is_integer\n      >::init(result_type());\n    result_type previous = init;\n    unsigned int length = 0;\n    for(int i = 0; i < n; ++i) {\n      result_type val = f();\n      if(up ? previous <= val : previous >= val) {\n        previous = val;\n        ++length;\n      } else {\n        count((std::min)(length, classes())-1);\n        length = 0;\n        previous = init;\n        // don't use this value, so that runs are independent\n      }\n    }\n  }\n  double probability(unsigned int r) const\n  {\n    if(r == classes()-1)\n      return 1.0/fac<double>(classes());\n    else\n      return static_cast<double>(r+1)/fac<double>(r+2);\n  }\n};\n\n// gap length experiment\nclass gap_experiment : public experiment_base\n{\npublic:\n  template<class Dist>\n  gap_experiment(unsigned int classes, const Dist & dist, double alpha, double beta)\n    : experiment_base(classes), alpha(alpha), beta(beta), low(quantile(dist, alpha)), high(quantile(dist, beta)) {}\n  \n  template<class NumberGenerator, class Counter>\n  void run(NumberGenerator & f, Counter & count, int n) const\n  {\n    typedef typename NumberGenerator::result_type result_type;\n    unsigned int length = 0;\n    for(int i = 0; i < n; ) {\n      result_type value = f();\n      if(value < low || value > high)\n        ++length;\n      else {\n        count((std::min)(length, classes()-1));\n        length = 0;\n        ++i;\n      }\n    }\n  }\n  double probability(unsigned int r) const\n  {\n    double p = beta-alpha;\n    if(r == classes()-1)\n      return std::pow(1-p, static_cast<double>(r));\n    else\n      return p * std::pow(1-p, static_cast<double>(r));\n  }\nprivate:\n  double alpha, beta;\n  double low, high;\n};\n\n// poker experiment\nclass poker_experiment : public experiment_base\n{\npublic:\n  poker_experiment(unsigned int d, unsigned int k)\n    : experiment_base(k), range(d)\n  {\n    assert(range > 1);\n  }\n\n  template<class UniformRandomNumberGenerator, class Counter>\n  void run(UniformRandomNumberGenerator & f, Counter & count, int n) const\n  {\n    typedef typename UniformRandomNumberGenerator::result_type result_type;\n    assert(std::numeric_limits<result_type>::is_integer);\n    assert((f.min)() == 0);\n    assert((f.max)() == static_cast<result_type>(range-1));\n    std::vector<result_type> v(classes());\n    for(int i = 0; i < n; ++i) {\n      for(unsigned int j = 0; j < classes(); ++j)\n        v[j] = f();\n      std::sort(v.begin(), v.end());\n      result_type prev = v[0];\n      int r = 1;     // count different values in v\n      for(unsigned int i = 1; i < classes(); ++i) {\n        if(prev != v[i]) {\n          prev = v[i];\n          ++r;\n        }\n      }\n      count(r-1);\n    }\n  }\n\n  double probability(unsigned int r) const\n  {\n    ++r;       // transform to 1 <= r <= 5\n    double result = range;\n    for(unsigned int i = 1; i < r; ++i)\n      result *= range-i;\n    return result / std::pow(range, static_cast<double>(classes())) *\n      stirling2<double>(classes(), r);\n  }\nprivate:\n  unsigned int range;\n};\n\n// coupon collector experiment\nclass coupon_collector_experiment : public experiment_base\n{\npublic:\n  coupon_collector_experiment(unsigned int d, unsigned int cls)\n    : experiment_base(cls), d(d)\n  {\n    assert(d > 1);\n  }\n\n  template<class UniformRandomNumberGenerator, class Counter>\n  void run(UniformRandomNumberGenerator & f, Counter & count, int n) const\n  {\n    typedef typename UniformRandomNumberGenerator::result_type result_type;\n    assert(std::numeric_limits<result_type>::is_integer);\n    assert((f.min)() == 0);\n    assert((f.max)() == static_cast<result_type>(d-1));\n    std::vector<bool> occurs(d);\n    for(int i = 0; i < n; ++i) {\n      occurs.assign(d, false);\n      unsigned int r = 0;            // length of current sequence\n      int q = 0;                     // number of non-duplicates in current set\n      for(;;) {\n        result_type val = f();\n        ++r;\n        if(!occurs[val]) {       // new set element\n          occurs[val] = true;\n          ++q;\n          if(q == d)\n            break;     // one complete set\n        }\n      }\n      count((std::min)(r-d, classes()-1));\n    }\n  }\n  double probability(unsigned int r) const\n  {\n    if(r == classes()-1)\n      return 1-fac<double>(d)/\n        std::pow(static_cast<double>(d), static_cast<double>(d+classes()-2)) *\n        stirling2<double>(d+classes()-2, d);\n    else\n      return fac<double>(d)/\n        std::pow(static_cast<double>(d), static_cast<double>(d+r)) * \n        stirling2<double>(d+r-1, d-1);\n  }\nprivate:\n  int d;\n};\n\n// permutation test\nclass permutation_experiment : public equidistribution_experiment\n{\npublic:\n  permutation_experiment(unsigned int t)\n    : equidistribution_experiment(fac<int>(t)), t(t)\n  {\n    assert(t > 1);\n  }\n\n  template<class UniformRandomNumberGenerator, class Counter>\n  void run(UniformRandomNumberGenerator & f, Counter & count, int n) const\n  {\n    typedef typename UniformRandomNumberGenerator::result_type result_type;\n    std::vector<result_type> v(t);\n    for(int i = 0; i < n; ++i) {\n      for(int j = 0; j < t; ++j) {\n        v[j] = f();\n      }\n      int x = 0;\n      for(int r = t-1; r > 0; r--) {\n        typename std::vector<result_type>::iterator it = \n          std::max_element(v.begin(), v.begin()+r+1);\n        x = (r+1)*x + (it-v.begin());\n        std::iter_swap(it, v.begin()+r);\n      }\n      count(x);\n    }\n  }\nprivate:\n  int t;\n};\n\n// birthday spacing experiment test\nclass birthday_spacing_experiment : public experiment_base\n{\npublic:\n  birthday_spacing_experiment(unsigned int d, int n, int m)\n    : experiment_base(d), n(n), m(m)\n  {\n  }\n\n  template<class UniformRandomNumberGenerator, class Counter>\n  void run(UniformRandomNumberGenerator & f, Counter & count, int n_total) const\n  {\n    typedef typename UniformRandomNumberGenerator::result_type result_type;\n    assert(std::numeric_limits<result_type>::is_integer);\n    assert((f.min)() == 0);\n    assert((f.max)() == static_cast<result_type>(m-1));\n   \n    for(int j = 0; j < n_total; j++) {\n      std::vector<result_type> v(n);\n      std::generate_n(v.begin(), n, f);\n      std::sort(v.begin(), v.end());\n      std::vector<result_type> spacing(n);\n      for(int i = 0; i < n-1; i++)\n        spacing[i] = v[i+1]-v[i];\n      spacing[n-1] = v[0] + m - v[n-1];\n      std::sort(spacing.begin(), spacing.end());\n      unsigned int k = 0;\n      for(int i = 0; i < n-1; ++i) {\n        if(spacing[i] == spacing[i+1])\n          ++k;\n      }\n      count((std::min)(k, classes()-1));\n    }\n  }\n\n  double probability(unsigned int r) const\n  {\n    assert(classes() == 4);\n    assert(m == (1<<25));\n    assert(n == 512);\n    static const double prob[] = { 0.368801577, 0.369035243, 0.183471182,\n                                   0.078691997 };\n    return prob[r];\n  }\nprivate:\n  int n, m;\n};\n/*\n * Misc. helper functions.\n */\n\ntemplate<class Float>\nstruct distribution_function\n{\n  typedef Float result_type;\n  typedef Float argument_type;\n  typedef Float first_argument_type;\n  typedef Float second_argument_type;\n};\n\n// computes P(K_n <= t) or P(t1 <= K_n <= t2).  See Knuth, 3.3.1\nclass kolmogorov_smirnov_probability : public distribution_function<double>\n{\npublic:\n  kolmogorov_smirnov_probability(int n) \n    : approx(n > 50), n(n), sqrt_n(std::sqrt(double(n)))\n  {\n    if(!approx)\n      n_n = std::pow(static_cast<double>(n), n);\n  }\n  \n  double cdf(double t) const\n  {\n    if(approx) {\n      return 1-std::exp(-2*t*t)*(1-2.0/3.0*t/sqrt_n);\n    } else {\n      t *= sqrt_n;\n      double sum = 0;\n      for(int k = static_cast<int>(std::ceil(t)); k <= n; k++)\n        sum += binomial<double>(n, k) * std::pow(k-t, k) * \n          std::pow(t+n-k, n-k-1);\n      return 1 - t/n_n * sum;\n    }\n  }\n  //double operator()(double t1, double t2) const\n  //{ return operator()(t2) - operator()(t1); }\n\nprivate:\n  bool approx;\n  int n;\n  double sqrt_n;\n  double n_n;\n};\n\ninline double cdf(const kolmogorov_smirnov_probability& dist, double val)\n{\n  return dist.cdf(val);\n}\n\ninline double quantile(const kolmogorov_smirnov_probability& dist, double val)\n{\n    return invert_monotone_inc(boost::bind(&cdf, dist, _1), val, 0.0, 1000.0);\n}\n\n/*\n * Experiments for generators with continuous distribution functions\n */\nclass kolmogorov_experiment\n{\npublic:\n  kolmogorov_experiment(int n) : n(n), ksp(n) { }\n  template<class NumberGenerator, class Distribution>\n  double run(NumberGenerator & gen, Distribution distrib) const\n  {\n    const int m = n;\n    typedef std::vector<double> saved_temp;\n    saved_temp a(m,1.0), b(m,0);\n    std::vector<int> c(m,0);\n    for(int i = 0; i < n; ++i) {\n      double val = static_cast<double>(gen());\n      double y = cdf(distrib, val);\n      int k = static_cast<int>(std::floor(m*y));\n      if(k >= m)\n        --k;    // should not happen\n      a[k] = (std::min)(a[k], y);\n      b[k] = (std::max)(b[k], y);\n      ++c[k];\n    }\n    double kplus = 0, kminus = 0;\n    int j = 0;\n    for(int k = 0; k < m; ++k) {\n      if(c[k] > 0) {\n        kminus = (std::max)(kminus, a[k]-j/static_cast<double>(n));\n        j += c[k];\n        kplus = (std::max)(kplus, j/static_cast<double>(n) - b[k]);\n      }\n    }\n    kplus *= std::sqrt(double(n));\n    kminus *= std::sqrt(double(n));\n    // std::cout << \"k+ \" << kplus << \"   k- \" << kminus << std::endl;\n    return kplus;\n  }\n  double probability(double x) const\n  {\n    return cdf(ksp, x);\n  }\nprivate:\n  int n;\n  kolmogorov_smirnov_probability ksp;\n};\n\nstruct power_distribution\n{\n  power_distribution(double t) : t(t) {}\n  double t;\n};\n\ndouble cdf(const power_distribution& dist, double val)\n{\n  return std::pow(val, dist.t);\n}\n\n// maximum-of-t test (KS-based)\ntemplate<class UniformRandomNumberGenerator>\nclass maximum_experiment\n{\npublic:\n  typedef UniformRandomNumberGenerator base_type;\n  maximum_experiment(base_type & f, int n, int t) : f(f), ke(n), t(t)\n  { }\n\n  double operator()() const\n  {\n    generator gen(f, t);\n    return ke.run(gen, power_distribution(t));\n  }\n\nprivate:\n  struct generator {\n    generator(base_type & f, int t) : f(f, boost::uniform_01<>()), t(t) { }\n    double operator()()\n    {\n      double mx = f();\n      for(int i = 1; i < t; ++i)\n        mx = (std::max)(mx, f());\n      return mx;\n    }\n  private:\n    boost::variate_generator<base_type&, boost::uniform_01<> > f;\n    int t;\n  };\n  base_type & f;\n  kolmogorov_experiment ke;\n  int t;\n};\n\n// compute a chi-square value for the distribution approximation error\ntemplate<class ForwardIterator, class UnaryFunction>\ntypename UnaryFunction::result_type\nchi_square_value(ForwardIterator first, ForwardIterator last,\n                 UnaryFunction probability)\n{\n  typedef std::iterator_traits<ForwardIterator> iter_traits;\n  typedef typename iter_traits::value_type counter_type;\n  typedef typename UnaryFunction::result_type result_type;\n  unsigned int classes = std::distance(first, last);\n  result_type sum = 0;\n  counter_type n = 0;\n  for(unsigned int i = 0; i < classes; ++first, ++i) {\n    counter_type count = *first;\n    n += count;\n    sum += (count/probability(i)) * count;  // avoid overflow\n  }\n#if 0\n  for(unsigned int i = 0; i < classes; ++i) {\n    // std::cout << (n*probability(i)) << \" \";\n    if(n * probability(i) < 5)\n      std::cerr << \"Not enough test runs for slot \" << i\n                << \" p=\" << probability(i) << \", n=\" << n\n                << std::endl;\n  }\n#endif\n  // std::cout << std::endl;\n  // throw std::invalid_argument(\"not enough test runs\");\n\n  return sum/n - n;\n}\ntemplate<class RandomAccessContainer>\nclass generic_counter\n{\npublic:\n  explicit generic_counter(unsigned int classes) : container(classes, 0) { }\n  void operator()(int i)\n  {\n    assert(i >= 0);\n    assert(static_cast<unsigned int>(i) < container.size());\n    ++container[i];\n  }\n  typename RandomAccessContainer::const_iterator begin() const \n  { return container.begin(); }\n  typename RandomAccessContainer::const_iterator end() const \n  { return container.end(); }\n\nprivate:\n  RandomAccessContainer container;\n};\n\n// chi_square test\ntemplate<class Experiment, class Generator>\ndouble run_experiment(const Experiment & experiment, Generator & gen, int n)\n{\n  generic_counter<std::vector<int> > v(experiment.classes());\n  experiment.run(gen, v, n);\n  return chi_square_value(v.begin(), v.end(),\n                          boost::bind(&Experiment::probability, \n                                       experiment, boost::placeholders::_1));\n}\n\n// chi_square test\ntemplate<class Experiment, class Generator>\ndouble run_experiment(const Experiment & experiment, const Generator & gen, int n)\n{\n  generic_counter<std::vector<int> > v(experiment.classes());\n  experiment.run(gen, v, n);\n  return chi_square_value(v.begin(), v.end(),\n                          boost::bind(&Experiment::probability, \n                                       experiment, boost::placeholders::_1));\n}\n\n// number generator with experiment results (for nesting)\ntemplate<class Experiment, class Generator>\nclass experiment_generator_t\n{\npublic:\n  experiment_generator_t(const Experiment & exper, Generator & gen, int n)\n    : experiment(exper), generator(gen), n(n) { }\n  double operator()() const { return run_experiment(experiment, generator, n); }\nprivate:\n  const Experiment & experiment;\n  Generator & generator;\n  int n;\n};\n\ntemplate<class Experiment, class Generator>\nexperiment_generator_t<Experiment, Generator>\nexperiment_generator(const Experiment & e, Generator & gen, int n)\n{\n  return experiment_generator_t<Experiment, Generator>(e, gen, n);\n}\n\n\ntemplate<class Experiment, class Generator, class Distribution>\nclass ks_experiment_generator_t\n{\npublic:\n  ks_experiment_generator_t(const Experiment & exper, Generator & gen,\n                            const Distribution & distrib)\n    : experiment(exper), generator(gen), distribution(distrib) { }\n  double operator()() const { return experiment.run(generator, distribution); }\nprivate:\n  const Experiment & experiment;\n  Generator & generator;\n  Distribution distribution;\n};\n\ntemplate<class Experiment, class Generator, class Distribution>\nks_experiment_generator_t<Experiment, Generator, Distribution>\nks_experiment_generator(const Experiment & e, Generator & gen,\n                        const Distribution & distrib)\n{\n  return ks_experiment_generator_t<Experiment, Generator, Distribution>\n    (e, gen, distrib);\n}\n\n\n#endif /* STATISTIC_TESTS_HPP */\n\n", "meta": {"hexsha": "c1feb5559552142553bc9b282c36096d9d133682", "size": 19101, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "3rdParty/boost/1.71.0/libs/random/test/statistic_tests.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/libs/random/test/statistic_tests.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/libs/random/test/statistic_tests.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": 26.9028169014, "max_line_length": 115, "alphanum_fraction": 0.6286058322, "num_tokens": 5048, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6076631698328917, "lm_q2_score": 0.5506073655352404, "lm_q1q2_score": 0.33458381707448187}}
{"text": "#pragma once\n#ifndef OPENGM_SUBGRADIENT_SSVM_LEARNER_HXX\n#define OPENGM_SUBGRADIENT_SSVM_LEARNER_HXX\n\n#include <iomanip>\n#include <vector>\n#include <opengm/inference/inference.hxx>\n#include <opengm/graphicalmodel/weights.hxx>\n#include <opengm/utilities/random.hxx>\n#include <opengm/learning/gradient-accumulator.hxx>\n#include <opengm/learning/weight_averaging.hxx>\n\n#ifdef WITH_OPENMP\n#include <omp.h>\n#endif\n\n#include <boost/circular_buffer.hpp>\n#include <boost/math/distributions/normal.hpp>\n#include <boost/random/normal_distribution.hpp>\n#include <boost/random/mersenne_twister.hpp>\n#include <boost/random/variate_generator.hpp>\n\n\nnamespace opengm {\n    namespace learning {\n\n\n\n    template<class T>\n    double gen_normal_3(T &generator)\n    {\n      return generator();\n    }\n\n    // Version that fills a vector\n    template<class T>\n    void gen_normal_3(T &generator,\n                  std::vector<double> &res)\n    {\n      for(size_t i=0; i<res.size(); ++i)\n        res[i]=generator();\n    }\n\n\n           \n    template<class DATASET>\n    class Rws\n    {\n    public: \n        typedef DATASET DatasetType;\n        typedef typename DATASET::GMType   GMType; \n        typedef typename DATASET::GMWITHLOSS GMWITHLOSS;\n        typedef typename DATASET::LossType LossType;\n        typedef typename GMType::ValueType ValueType;\n        typedef typename GMType::IndexType IndexType;\n        typedef typename GMType::LabelType LabelType; \n        typedef opengm::learning::Weights<double> WeightsType;\n        typedef typename std::vector<LabelType>::const_iterator LabelIterator;\n        typedef FeatureAccumulator<GMType, LabelIterator> FeatureAcc;\n\n        typedef std::vector<LabelType> ConfType;\n        typedef boost::circular_buffer<ConfType> ConfBuffer;\n        typedef std::vector<ConfBuffer> ConfBufferVec;\n\n        class Parameter{\n        public:\n\n\n\n            Parameter(){\n                eps_ = 0.00001;\n                maxIterations_ = 10000;\n                stopLoss_ = 0.0;\n                learningRate_ = 1.0;\n                C_ = 1.0;\n                averaging_ = -1;\n                p_ = 10;\n                sigma_ = 1.0;\n            }       \n\n            double eps_;\n            size_t maxIterations_;\n            double stopLoss_;\n            double learningRate_;\n            double C_;\n            int averaging_;\n            size_t p_;\n            double sigma_;\n        };\n\n\n        Rws(DATASET&, const Parameter& );\n\n        template<class INF>\n        void learn(const typename INF::Parameter& para); \n        //template<class INF, class VISITOR>\n        //void learn(typename INF::Parameter para, VITITOR vis);\n\n        const opengm::learning::Weights<double>& getWeights(){return weights_;}\n        Parameter& getLerningParameters(){return para_;}\n\n\n\n        double getLoss(const GMType & gm ,const GMWITHLOSS  & gmWithLoss, std::vector<LabelType> & labels){\n\n            double loss = 0 ;\n            std::vector<LabelType> subConf(20,0);\n\n            for(size_t fi=gm.numberOfFactors(); fi<gmWithLoss.numberOfFactors(); ++fi){\n                for(size_t v=0; v<gmWithLoss[fi].numberOfVariables(); ++v){\n                    subConf[v] = labels[ gmWithLoss[fi].variableIndex(v)];\n                }\n                loss +=  gmWithLoss[fi](subConf.begin());\n            }\n            return loss;\n        }\n\n    private:\n\n        double updateWeights();\n\n        DATASET& dataset_;\n        WeightsType  weights_;\n        Parameter para_;\n        size_t iteration_;\n        FeatureAcc featureAcc_;\n        WeightRegularizer<ValueType> wReg_;\n        WeightAveraging<double> weightAveraging_;\n    }; \n\n    template<class DATASET>\n    Rws<DATASET>::Rws(DATASET& ds, const Parameter& p )\n    :   dataset_(ds), \n        para_(p),\n        iteration_(0),\n        featureAcc_(ds.getNumberOfWeights()),\n        wReg_(2, 1.0/p.C_),\n        weightAveraging_(ds.getWeights(),p.averaging_)\n    {\n        featureAcc_.resetWeights();\n        weights_ = opengm::learning::Weights<double>(ds.getNumberOfWeights());\n    }\n\n\n    template<class DATASET>\n    template<class INF>\n    void Rws<DATASET>::learn(const typename INF::Parameter& para){\n\n\n        const size_t nModels = dataset_.getNumberOfModels();\n        const size_t nWegihts = dataset_.getNumberOfWeights();\n\n        \n        //for(size_t wi=0; wi<nWegihts; ++wi){\n        //    dataset_.getWeights().setWeight(wi, 0.0);\n        //}\n\n\n\n        RandomUniform<size_t> randModel(0, nModels);\n        boost::math::normal_distribution<ValueType> nDist(0.0, para_.sigma_);\n        std::vector< std::vector<ValueType> > noiseVecs(para_.p_, std::vector<ValueType>(nWegihts));\n        std::vector<ValueType> lossVec(para_.p_);\n\n        std::vector<ValueType> gradient(nWegihts);\n\n        boost::variate_generator<boost::mt19937, boost::normal_distribution<> >\n        generator(boost::mt19937(time(0)),boost::normal_distribution<>(0.0, para_.sigma_));\n\n        std::cout<<\"online mode \"<<nWegihts<<\"\\n\";\n\n        std::cout <<\"start loss\"<< std::setw(6) << std::setfill(' ') << iteration_ << ':'\n                          << std::setw(8) << dataset_. template getTotalLossParallel<INF>(para) <<\"  \\n\\n\\n\\n\";\n\n\n        for(iteration_=0 ; iteration_<para_.maxIterations_; ++iteration_){\n\n\n\n\n            // get random model\n            const size_t gmi = randModel();\n\n            // save the current weights\n            WeightsType currentWeights  = dataset_.getWeights();\n\n\n            featureAcc_.resetWeights();\n\n            // lock the model\n            dataset_.lockModel(gmi);\n\n            for(size_t p=0; p<para_.p_; ++p){\n\n\n                // fill noise \n                gen_normal_3(generator, noiseVecs[p]);\n\n                // add noise to the weights\n                for(size_t wi=0; wi<nWegihts; ++wi){\n                    const ValueType cw = currentWeights[wi];\n                    const ValueType nw = cw + noiseVecs[p][wi];\n                    dataset_.getWeights().setWeight(wi, nw);\n                }\n\n\n                const GMType & gm = dataset_.getModel(gmi);\n                // do inference\n                std::vector<LabelType> arg;\n                opengm::infer<INF>(gm, para, arg);\n                lossVec[p] = dataset_.getLoss(arg, gmi);\n                \n                //featureAcc_.accumulateModelFeatures(gm, dataset_.getGT(gmi).begin(), arg.begin());\n                // update weights\n                //const double wChange =updateWeights();      \n            }\n\n            //for(size_t wi=0; wi<nWegihts; ++wi){\n            //    gradient[wi] = featureAcc_.getWeight(wi);\n            //}\n            std::fill(gradient.begin(), gradient.end(),0.0);\n            for(size_t p=0; p<para_.p_; ++p){\n                for(size_t wi=0; wi<nWegihts; ++wi){\n                    gradient[wi] += (1.0/para_.p_)*(noiseVecs[p][wi])*lossVec[p];\n                }\n            }\n\n            const ValueType actualLearningRate = para_.learningRate_/(1.0 + iteration_);\n            //const ValueType actualLearningRate = para_.learningRate_;///(1.0 + iteration_);\n            // do update\n            for(size_t wi=0; wi<nWegihts; ++wi){\n                const ValueType oldWeight = currentWeights[wi];\n                const ValueType newWeights = (oldWeight - actualLearningRate*gradient[wi])*para_.C_;\n                //std::cout<<\"wi \"<<newWeights<<\"\\n\";\n                dataset_.getWeights().setWeight(wi, newWeights);\n            }\n            std::cout<<\"\\n\";\n            dataset_.unlockModel(gmi);\n\n            if(iteration_%10==0){\n            //if(iteration_%nModels*2 == 0 ){\n                std::cout << '\\n'\n                          << std::setw(6) << std::setfill(' ') << iteration_ << ':'\n                          << std::setw(8) << dataset_. template getTotalLossParallel<INF>(para) <<\"  \"<< std::flush;\n\n            }\n\n        }\n  \n        weights_ = dataset_.getWeights();\n    }\n\n\n    template<class DATASET>\n    double Rws<DATASET>::updateWeights(){\n\n        const size_t nWegihts = dataset_.getNumberOfWeights();\n\n        WeightsType p(nWegihts);\n        WeightsType newWeights(nWegihts);\n\n\n        for(size_t wi=0; wi<nWegihts; ++wi){\n            p[wi] =  dataset_.getWeights().getWeight(wi);\n            p[wi] += para_.C_ * featureAcc_.getWeight(wi);\n        }\n\n\n        double wChange = 0.0;\n        \n        for(size_t wi=0; wi<nWegihts; ++wi){\n            const double wOld = dataset_.getWeights().getWeight(wi);\n            const double wNew = wOld - (para_.learningRate_/double(iteration_+1))*p[wi];\n            newWeights[wi] = wNew;\n        }\n\n        weightAveraging_(newWeights);\n\n\n\n        weights_ = dataset_.getWeights();\n        return wChange;\n    }\n}\n}\n#endif\n", "meta": {"hexsha": "42c7cd0f656a035237f83cfcf3cd3d1d9afe3ffc", "size": 8672, "ext": "hxx", "lang": "C++", "max_stars_repo_path": "include/opengm/learning/rws.hxx", "max_stars_repo_name": "chaubold/opengm", "max_stars_repo_head_hexsha": "acc42b98b713db33f2b35aad05a7a1cf9752e862", "max_stars_repo_licenses": ["MIT"], "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/learning/rws.hxx", "max_issues_repo_name": "chaubold/opengm", "max_issues_repo_head_hexsha": "acc42b98b713db33f2b35aad05a7a1cf9752e862", "max_issues_repo_licenses": ["MIT"], "max_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/learning/rws.hxx", "max_forks_repo_name": "chaubold/opengm", "max_forks_repo_head_hexsha": "acc42b98b713db33f2b35aad05a7a1cf9752e862", "max_forks_repo_licenses": ["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.2160278746, "max_line_length": 116, "alphanum_fraction": 0.56849631, "num_tokens": 2119, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6297746074044134, "lm_q2_score": 0.5312093733737563, "lm_q1q2_score": 0.3345421745660018}}
{"text": "/* jacobian.cpp -- Computation of Jacobian matrix\n\n    Copyright (C) 2012-2014 University of Reading\n    Copyright (C) 2015-2020 European Centre for Medium-Range Weather Forecasts\n\n    Author: Robin Hogan <r.j.hogan@ecmwf.int>\n\n    This file is part of the Adept library.\n\n*/\n\n#ifdef _OPENMP\n#include <omp.h>\n#endif\n\n#include <adept_arrays.h>\n\nnamespace adept {\n\n  namespace internal {\n    static const int MULTIPASS_SIZE = ADEPT_REAL_PACKET_SIZE == 1 ? ADEPT_MULTIPASS_SIZE : ADEPT_REAL_PACKET_SIZE;\n  }\n\n  using namespace internal;\n\n  template <typename T>\n  T _check_long_double() {\n    // The user may have requested Real to be of type \"long double\" by\n    // specifying ADEPT_REAL_TYPE_SIZE=16. If the present system can\n    // only support double then sizeof(long double) will be 8, but\n    // Adept will not be emitting the best code for this, so it is\n    // probably better to fail forcing the user to specify\n    // ADEPT_REAL_TYPE_SIZE=8.\n    ADEPT_STATIC_ASSERT(ADEPT_REAL_TYPE_SIZE != 16 || ADEPT_REAL_TYPE_SIZE == sizeof(Real),\n\t\t\tCOMPILER_DOES_NOT_SUPPORT_16_BYTE_LONG_DOUBLE);\n    return 1;\n  }\n\n#if ADEPT_REAL_PACKET_SIZE > 1\n  void\n  Stack::jacobian_forward_kernel(Real* __restrict gradient_multipass_b) const\n  {\n\n    // Loop forward through the derivative statements\n    for (uIndex ist = 1; ist < n_statements_; ist++) {\n      const Statement& statement = statement_[ist];\n      // We copy the LHS to \"a\" in case it appears on the RHS in any\n      // of the following statements\n      Packet<Real> a; // Zeroed automatically\n      // Loop through operations\n      for (uIndex iop = statement_[ist-1].end_plus_one;\n\t   iop < statement.end_plus_one; iop++) {\n\tPacket<Real> g(gradient_multipass_b+index_[iop]*MULTIPASS_SIZE);\n\tPacket<Real> m(multiplier_[iop]);\n\ta += m * g;\n      }\n      // Copy the results\n      a.put(gradient_multipass_b+statement.index*MULTIPASS_SIZE);\n    } // End of loop over statements\n  }    \n#else\n  void\n  Stack::jacobian_forward_kernel(Real* __restrict gradient_multipass_b) const\n  {\n\n    // Loop forward through the derivative statements\n    for (uIndex ist = 1; ist < n_statements_; ist++) {\n      const Statement& statement = statement_[ist];\n      // We copy the LHS to \"a\" in case it appears on the RHS in any\n      // of the following statements\n      Block<MULTIPASS_SIZE,Real> a; // Zeroed automatically\n      // Loop through operations\n      for (uIndex iop = statement_[ist-1].end_plus_one;\n\t   iop < statement.end_plus_one; iop++) {\n\tfor (uIndex i = 0; i < MULTIPASS_SIZE; i++) {\n\t  a[i] += multiplier_[iop]*gradient_multipass_b[index_[iop]*MULTIPASS_SIZE+i];\n\t}\n      }\n      // Copy the results\n      for (uIndex i = 0; i < MULTIPASS_SIZE; i++) {\n\tgradient_multipass_b[statement.index*MULTIPASS_SIZE+i] = a[i];\n      }\n    } // End of loop over statements\n  }    \n#endif\n\n  void\n  Stack::jacobian_forward_kernel_extra(Real* __restrict gradient_multipass_b,\n\t\t\t\t       uIndex n_extra) const\n  {\n\n    // Loop forward through the derivative statements\n    for (uIndex ist = 1; ist < n_statements_; ist++) {\n      const Statement& statement = statement_[ist];\n      // We copy the LHS to \"a\" in case it appears on the RHS in any\n      // of the following statements\n      Block<MULTIPASS_SIZE,Real> a; // Zeroed automatically\n      // Loop through operations\n      for (uIndex iop = statement_[ist-1].end_plus_one;\n\t   iop < statement.end_plus_one; iop++) {\n\tfor (uIndex i = 0; i < n_extra; i++) {\n\t  a[i] += multiplier_[iop]*gradient_multipass_b[index_[iop]*MULTIPASS_SIZE+i];\n\t}\n      }\n      // Copy the results\n      for (uIndex i = 0; i < n_extra; i++) {\n\tgradient_multipass_b[statement.index*MULTIPASS_SIZE+i] = a[i];\n      }\n    } // End of loop over statements\n  }    \n\n\n\n  // Compute the Jacobian matrix, parallelized using OpenMP. Normally\n  // the user would call the jacobian or jacobian_forward functions,\n  // and the OpenMP version would only be called if OpenMP is\n  // available and the Jacobian matrix is large enough for\n  // parallelization to be worthwhile.  Note that jacobian_out must be\n  // allocated to be at least of size m*n, where m is the number of\n  // dependent variables and n is the number of independents. The\n  // independents and dependents must have already been identified\n  // with the functions \"independent\" and \"dependent\", otherwise this\n  // function will fail with FAILURE_XXDEPENDENT_NOT_IDENTIFIED. The\n  // offsets in memory of the two dimensions are provided by\n  // dep_offset and indep_offset. This is implemented using a forward\n  // pass, appropriate for m>=n.\n  void\n  Stack::jacobian_forward_openmp(Real* jacobian_out,\n\t\t\t\t Index dep_offset, Index indep_offset) const\n  {\n\n    // Number of blocks to cycle through, including a possible last\n    // block containing fewer than MULTIPASS_SIZE variables\n    int n_block = (n_independent() + MULTIPASS_SIZE - 1)\n      / MULTIPASS_SIZE;\n    uIndex n_extra = n_independent() % MULTIPASS_SIZE;\n    \n#pragma omp parallel\n    {\n      //      std::vector<Block<MULTIPASS_SIZE,Real> > \n      //\tgradient_multipass_b(max_gradient_);\n      uIndex gradient_multipass_size = max_gradient_*MULTIPASS_SIZE;\n      Real* __restrict gradient_multipass_b \n\t= alloc_aligned<Real>(gradient_multipass_size);\n      \n#pragma omp for schedule(static)\n      for (int iblock = 0; iblock < n_block; iblock++) {\n\t// Set the index to the dependent variables for this block\n\tuIndex i_independent =  MULTIPASS_SIZE * iblock;\n\t\n\tuIndex block_size = MULTIPASS_SIZE;\n\t// If this is the last iteration and the number of extra\n\t// elements is non-zero, then set the block size to the number\n\t// of extra elements. If the number of extra elements is zero,\n\t// then the number of independent variables is exactly divisible\n\t// by MULTIPASS_SIZE, so the last iteration will be the\n\t// same as all the rest.\n\tif (iblock == n_block-1 && n_extra > 0) {\n\t  block_size = n_extra;\n\t}\n\t\n\t// Set the initial gradients all to zero\n\tfor (uIndex i = 0; i < gradient_multipass_size; i++) {\n\t  gradient_multipass_b[i] = 0.0;\n\t}\n\t// Each seed vector has one non-zero entry of 1.0\n\tfor (uIndex i = 0; i < block_size; i++) {\n\t  gradient_multipass_b[independent_index_[i_independent+i]*MULTIPASS_SIZE+i] = 1.0;\n\t}\n\n\tjacobian_forward_kernel(gradient_multipass_b);\n\n\t// Copy the gradients corresponding to the dependent variables\n\t// into the Jacobian matrix\n\tif (indep_offset == 1) {\n\t  for (uIndex idep = 0; idep < n_dependent(); idep++) {\n\t    for (uIndex i = 0; i < block_size; i++) {\n\t      jacobian_out[idep*dep_offset+i_independent+i]\n\t\t= gradient_multipass_b[dependent_index_[idep]*MULTIPASS_SIZE+i];\n\t    }\n\t  }\n\t}\n\telse {\n\t  for (uIndex idep = 0; idep < n_dependent(); idep++) {\n\t    for (uIndex i = 0; i < block_size; i++) {\n\t      jacobian_out[(i_independent+i)*indep_offset+idep*dep_offset]\n\t\t= gradient_multipass_b[dependent_index_[idep]*MULTIPASS_SIZE+i];\n\t    }\n\t  }\n\t}\n      } // End of loop over blocks\n      free_aligned(gradient_multipass_b);\n    } // End of parallel section\n  } // End of jacobian function\n\n\n  // Compute the Jacobian matrix; note that jacobian_out must be\n  // allocated to be of size m*n, where m is the number of dependent\n  // variables and n is the number of independents. The independents\n  // and dependents must have already been identified with the\n  // functions \"independent\" and \"dependent\", otherwise this function\n  // will fail with FAILURE_XXDEPENDENT_NOT_IDENTIFIED. This is\n  // implemented using a forward pass, appropriate for m>=n.\n  void\n  Stack::jacobian_forward(Real* jacobian_out,\n\t\t\t  Index dep_offset, Index indep_offset) const\n  {\n    if (independent_index_.empty() || dependent_index_.empty()) {\n      throw(dependents_or_independents_not_identified());\n    }\n\n    // If either of the offsets are zero, set them to the size of the\n    // other dimension, which assumes that the full Jacobian matrix is\n    // contiguous in memory.\n    if (dep_offset <= 0) {\n      dep_offset = n_independent();\n    }\n    if (indep_offset <= 0) {\n      indep_offset = n_dependent();\n    }\n\n#ifdef _OPENMP\n    if (have_openmp_ \n\t&& !openmp_manually_disabled_\n\t&& n_independent() > MULTIPASS_SIZE\n\t&& omp_get_max_threads() > 1) {\n      // Call the parallel version\n      jacobian_forward_openmp(jacobian_out, dep_offset, indep_offset);\n      return;\n    }\n#endif\n\n    // For optimization reasons, we process a block of\n    // MULTIPASS_SIZE columns of the Jacobian at once; calculate\n    // how many blocks are needed and how many extras will remain\n    uIndex n_block = n_independent() / MULTIPASS_SIZE;\n    uIndex n_extra = n_independent() % MULTIPASS_SIZE;\n\n    ///gradient_multipass_.resize(max_gradient_);\n    uIndex gradient_multipass_size = max_gradient_*MULTIPASS_SIZE;\n    Real* __restrict gradient_multipass_b \n      = alloc_aligned<Real>(gradient_multipass_size);\n\n    // Loop over blocks of MULTIPASS_SIZE columns\n    for (uIndex iblock = 0; iblock < n_block; iblock++) {\n      // Set the index to the dependent variables for this block\n      uIndex i_independent =  MULTIPASS_SIZE * iblock;\n\n      // Set the initial gradients all to zero\n      ///zero_gradient_multipass();\n      for (uIndex i = 0; i < gradient_multipass_size; i++) {\n\tgradient_multipass_b[i] = 0.0;\n      }\n\n      // Each seed vector has one non-zero entry of 1.0\n      for (uIndex i = 0; i < MULTIPASS_SIZE; i++) {\n\tgradient_multipass_b[independent_index_[i_independent+i]*MULTIPASS_SIZE+i] = 1.0;\n      }\n\n      jacobian_forward_kernel(gradient_multipass_b);\n\n      // Copy the gradients corresponding to the dependent variables\n      // into the Jacobian matrix\n      if (indep_offset == 1) {\n\tfor (uIndex idep = 0; idep < n_dependent(); idep++) {\n\t  for (uIndex i = 0; i < MULTIPASS_SIZE; i++) {\n\t    jacobian_out[idep*dep_offset+i_independent+i]\n\t      = gradient_multipass_b[dependent_index_[idep]*MULTIPASS_SIZE+i];\n\t  }\n\t}\n      }\n      else {\n\tfor (uIndex idep = 0; idep < n_dependent(); idep++) {\n\t  for (uIndex i = 0; i < MULTIPASS_SIZE; i++) {\n\t    jacobian_out[(i_independent+i)*indep_offset+idep*dep_offset] \n\t      = gradient_multipass_b[dependent_index_[idep]*MULTIPASS_SIZE+i];\n\t  }\n\t}\n      }\n      i_independent += MULTIPASS_SIZE;\n    } // End of loop over blocks\n    \n    // Now do the same but for the remaining few columns in the matrix\n    if (n_extra > 0) {\n      uIndex i_independent =  MULTIPASS_SIZE * n_block;\n      ///zero_gradient_multipass();\n      for (uIndex i = 0; i < gradient_multipass_size; i++) {\n\tgradient_multipass_b[i] = 0.0;\n      }\n\n      for (uIndex i = 0; i < n_extra; i++) {\n\tgradient_multipass_b[independent_index_[i_independent+i]*MULTIPASS_SIZE+i] = 1.0;\n      }\n\n      jacobian_forward_kernel_extra(gradient_multipass_b, n_extra);\n\n      if (indep_offset == 1) {\n\tfor (uIndex idep = 0; idep < n_dependent(); idep++) {\n\t  for (uIndex i = 0; i < n_extra; i++) {\n\t    jacobian_out[idep*dep_offset+i_independent+i]\n\t      = gradient_multipass_b[dependent_index_[idep]*MULTIPASS_SIZE+i];\n\t  }\n\t}\n      }\n      else {\n\tfor (uIndex idep = 0; idep < n_dependent(); idep++) {\n\t  for (uIndex i = 0; i < n_extra; i++) {\n\t    jacobian_out[(i_independent+i)*indep_offset+idep*dep_offset] \n\t      = gradient_multipass_b[dependent_index_[idep]*MULTIPASS_SIZE+i];\n\t  }\n\t}\n      }\n    }\n\n    free_aligned(gradient_multipass_b);\n  }\n\n\n  // Compute the Jacobian matrix, parallelized using OpenMP.  Normally\n  // the user would call the jacobian or jacobian_reverse functions,\n  // and the OpenMP version would only be called if OpenMP is\n  // available and the Jacobian matrix is large enough for\n  // parallelization to be worthwhile.  Note that jacobian_out must be\n  // allocated to be at least of size m*n, where m is the number of\n  // dependent variables and n is the number of independents. The\n  // independents and dependents must have already been identified\n  // with the functions \"independent\" and \"dependent\", otherwise this\n  // function will fail with FAILURE_XXDEPENDENT_NOT_IDENTIFIED. The\n  // offsets in memory of the two dimensions are provided by\n  // dep_offset and indep_offset.  This is implemented using a reverse\n  // pass, appropriate for m<n.\n  void\n  Stack::jacobian_reverse_openmp(Real* jacobian_out,\n\t\t\t\t Index dep_offset, Index indep_offset) const\n  {\n\n    // Number of blocks to cycle through, including a possible last\n    // block containing fewer than MULTIPASS_SIZE variables\n    int n_block = (n_dependent() + MULTIPASS_SIZE - 1)\n      / MULTIPASS_SIZE;\n    uIndex n_extra = n_dependent() % MULTIPASS_SIZE;\n    \n    // Inside the OpenMP loop, the \"this\" pointer may be NULL if the\n    // adept::Stack pointer is declared as thread-local and if the\n    // OpenMP memory model uses thread-local storage for private\n    // data. If this is the case then local pointers to or copies of\n    // the following members of the adept::Stack object may need to be\n    // made: dependent_index_ n_statements_ statement_ multiplier_\n    // index_ independent_index_ n_dependent() n_independent().\n    // Limited testing implies this is OK though.\n\n#pragma omp parallel\n    {\n      std::vector<Block<MULTIPASS_SIZE,Real> > \n\tgradient_multipass_b(max_gradient_);\n      \n#pragma omp for schedule(static)\n      for (int iblock = 0; iblock < n_block; iblock++) {\n\t// Set the index to the dependent variables for this block\n\tuIndex i_dependent =  MULTIPASS_SIZE * iblock;\n\t\n\tuIndex block_size = MULTIPASS_SIZE;\n\t// If this is the last iteration and the number of extra\n\t// elements is non-zero, then set the block size to the number\n\t// of extra elements. If the number of extra elements is zero,\n\t// then the number of independent variables is exactly divisible\n\t// by MULTIPASS_SIZE, so the last iteration will be the\n\t// same as all the rest.\n\tif (iblock == n_block-1 && n_extra > 0) {\n\t  block_size = n_extra;\n\t}\n\n\t// Set the initial gradients all to zero\n\tfor (std::size_t i = 0; i < gradient_multipass_b.size(); i++) {\n\t  gradient_multipass_b[i].zero();\n\t}\n\t// Each seed vector has one non-zero entry of 1.0\n\tfor (uIndex i = 0; i < block_size; i++) {\n\t  gradient_multipass_b[dependent_index_[i_dependent+i]][i] = 1.0;\n\t}\n\n\t// Loop backward through the derivative statements\n\tfor (uIndex ist = n_statements_-1; ist > 0; ist--) {\n\t  const Statement& statement = statement_[ist];\n\t  // We copy the RHS to \"a\" in case it appears on the LHS in any\n\t  // of the following statements\n\t  Real a[MULTIPASS_SIZE];\n#if MULTIPASS_SIZE > MULTIPASS_SIZE_ZERO_CHECK\n\t  // For large blocks, we only process the ones where a[i] is\n\t  // non-zero\n\t  uIndex i_non_zero[MULTIPASS_SIZE];\n#endif\n\t  uIndex n_non_zero = 0;\n\t  for (uIndex i = 0; i < block_size; i++) {\n\t    a[i] = gradient_multipass_b[statement.index][i];\n\t    gradient_multipass_b[statement.index][i] = 0.0;\n\t    if (a[i] != 0.0) {\n#if MULTIPASS_SIZE > MULTIPASS_SIZE_ZERO_CHECK\n\t      i_non_zero[n_non_zero++] = i;\n#else\n\t      n_non_zero = 1;\n#endif\n\t    }\n\t  }\n\n\t  // Only do anything for this statement if any of the a values\n\t  // are non-zero\n\t  if (n_non_zero) {\n\t    // Loop through the operations\n\t    for (uIndex iop = statement_[ist-1].end_plus_one;\n\t\t iop < statement.end_plus_one; iop++) {\n\t      // Try to minimize pointer dereferencing by making local\n\t      // copies\n\t      Real multiplier = multiplier_[iop];\n\t      Real* __restrict gradient_multipass \n\t\t= &(gradient_multipass_b[index_[iop]][0]);\n#if MULTIPASS_SIZE > MULTIPASS_SIZE_ZERO_CHECK\n\t      // For large blocks, loop over only the indices\n\t      // corresponding to non-zero a\n\t      for (uIndex i = 0; i < n_non_zero; i++) {\n\t\tgradient_multipass[i_non_zero[i]] += multiplier*a[i_non_zero[i]];\n\t      }\n#else\n\t      // For small blocks, do all indices\n\t      for (uIndex i = 0; i < block_size; i++) {\n\t      //\t      for (uIndex i = 0; i < MULTIPASS_SIZE; i++) {\n\t\tgradient_multipass[i] += multiplier*a[i];\n\t      }\n#endif\n\t    }\n\t  }\n\t} // End of loop over statement\n\t// Copy the gradients corresponding to the independent\n\t// variables into the Jacobian matrix\n\tif (dep_offset == 1) {\n\t  for (uIndex iindep = 0; iindep < n_independent(); iindep++) {\n\t    for (uIndex i = 0; i < block_size; i++) {\n\t      jacobian_out[iindep*indep_offset+i_dependent+i] \n\t\t= gradient_multipass_b[independent_index_[iindep]][i];\n\t    }\n\t  }\n\t}\n\telse {\n\t  for (uIndex iindep = 0; iindep < n_independent(); iindep++) {\n\t    for (uIndex i = 0; i < block_size; i++) {\n\t      jacobian_out[iindep*indep_offset+(i_dependent+i)*dep_offset] \n\t\t= gradient_multipass_b[independent_index_[iindep]][i];\n\t    }\n\t  }\n\t}\n      } // End of loop over blocks\n    } // end #pragma omp parallel\n  } // end jacobian_reverse_openmp\n\n\n  // Compute the Jacobian matrix; note that jacobian_out must be\n  // allocated to be of size m*n, where m is the number of dependent\n  // variables and n is the number of independents. The independents\n  // and dependents must have already been identified with the\n  // functions \"independent\" and \"dependent\", otherwise this function\n  // will fail with FAILURE_XXDEPENDENT_NOT_IDENTIFIED.  This is\n  // implemented using a reverse pass, appropriate for m<n.\n  void\n  Stack::jacobian_reverse(Real* jacobian_out,\n\t\t\t  Index dep_offset, Index indep_offset) const\n  {\n    if (independent_index_.empty() || dependent_index_.empty()) {\n      throw(dependents_or_independents_not_identified());\n    }\n\n    // If either of the offsets are zero, set them to the size of the\n    // other dimension, which assumes that the full Jacobian matrix is\n    // contiguous in memory.\n    if (dep_offset <= 0) {\n      dep_offset = n_independent();\n    }\n    if (indep_offset <= 0) {\n      indep_offset = n_dependent();\n    }\n\n#ifdef _OPENMP\n    if (have_openmp_ \n\t&& !openmp_manually_disabled_\n\t&& n_dependent() > MULTIPASS_SIZE\n\t&& omp_get_max_threads() > 1) {\n      // Call the parallel version\n      jacobian_reverse_openmp(jacobian_out,\n\t\t\t      dep_offset, indep_offset);\n      return;\n    }\n#endif\n\n    //    gradient_multipass_.resize(max_gradient_);\n    std::vector<Block<MULTIPASS_SIZE,Real> > \n      gradient_multipass_b(max_gradient_);\n\n    // For optimization reasons, we process a block of\n    // MULTIPASS_SIZE rows of the Jacobian at once; calculate\n    // how many blocks are needed and how many extras will remain\n    uIndex n_block = n_dependent() / MULTIPASS_SIZE;\n    uIndex n_extra = n_dependent() % MULTIPASS_SIZE;\n    uIndex i_dependent = 0; // uIndex of first row in the block we are\n\t\t\t    // currently computing\n    // Loop over the of MULTIPASS_SIZE rows\n    for (uIndex iblock = 0; iblock < n_block; iblock++) {\n      // Set the initial gradients all to zero\n      //      zero_gradient_multipass();\n      for (std::size_t i = 0; i < gradient_multipass_b.size(); i++) {\n\tgradient_multipass_b[i].zero();\n      }\n\n      // Each seed vector has one non-zero entry of 1.0\n      for (uIndex i = 0; i < MULTIPASS_SIZE; i++) {\n\tgradient_multipass_b[dependent_index_[i_dependent+i]][i] = 1.0;\n      }\n      // Loop backward through the derivative statements\n      for (uIndex ist = n_statements_-1; ist > 0; ist--) {\n\tconst Statement& statement = statement_[ist];\n\t// We copy the RHS to \"a\" in case it appears on the LHS in any\n\t// of the following statements\n\tReal a[MULTIPASS_SIZE];\n#if MULTIPASS_SIZE > MULTIPASS_SIZE_ZERO_CHECK\n\t// For large blocks, we only process the ones where a[i] is\n\t// non-zero\n\tuIndex i_non_zero[MULTIPASS_SIZE];\n#endif\n\tuIndex n_non_zero = 0;\n\tfor (uIndex i = 0; i < MULTIPASS_SIZE; i++) {\n\t  a[i] = gradient_multipass_b[statement.index][i];\n\t  gradient_multipass_b[statement.index][i] = 0.0;\n\t  if (a[i] != 0.0) {\n#if MULTIPASS_SIZE > MULTIPASS_SIZE_ZERO_CHECK\n\t    i_non_zero[n_non_zero++] = i;\n#else\n\t    n_non_zero = 1;\n#endif\n\t  }\n\t}\n\t// Only do anything for this statement if any of the a values\n\t// are non-zero\n\tif (n_non_zero) {\n\t  // Loop through the operations\n\t  for (uIndex iop = statement_[ist-1].end_plus_one;\n\t       iop < statement.end_plus_one; iop++) {\n\t    // Try to minimize pointer dereferencing by making local\n\t    // copies\n\t    Real multiplier = multiplier_[iop];\n\t    Real* __restrict gradient_multipass \n\t      = &(gradient_multipass_b[index_[iop]][0]);\n#if MULTIPASS_SIZE > MULTIPASS_SIZE_ZERO_CHECK\n\t    // For large blocks, loop over only the indices\n\t    // corresponding to non-zero a\n\t    for (uIndex i = 0; i < n_non_zero; i++) {\n\t      gradient_multipass[i_non_zero[i]] += multiplier*a[i_non_zero[i]];\n\t    }\n#else\n\t    // For small blocks, do all indices\n\t    for (uIndex i = 0; i < MULTIPASS_SIZE; i++) {\n\t      gradient_multipass[i] += multiplier*a[i];\n\t    }\n#endif\n\t  }\n\t}\n      } // End of loop over statement\n      // Copy the gradients corresponding to the independent variables\n      // into the Jacobian matrix\n      if (dep_offset == 1) {\n\tfor (uIndex iindep = 0; iindep < n_independent(); iindep++) {\n\t  for (uIndex i = 0; i < MULTIPASS_SIZE; i++) {\n\t    jacobian_out[iindep*indep_offset+i_dependent+i] \n\t      = gradient_multipass_b[independent_index_[iindep]][i];\n\t  }\n\t}\n      }\n      else {\n\tfor (uIndex iindep = 0; iindep < n_independent(); iindep++) {\n\t  for (uIndex i = 0; i < MULTIPASS_SIZE; i++) {\n\t    jacobian_out[iindep*indep_offset+(i_dependent+i)*dep_offset] \n\t      = gradient_multipass_b[independent_index_[iindep]][i];\n\t  }\n\t}\n      }\n      i_dependent += MULTIPASS_SIZE;\n    } // End of loop over blocks\n    \n    // Now do the same but for the remaining few rows in the matrix\n    if (n_extra > 0) {\n      for (std::size_t i = 0; i < gradient_multipass_b.size(); i++) {\n\tgradient_multipass_b[i].zero();\n      }\n      //      zero_gradient_multipass();\n      for (uIndex i = 0; i < n_extra; i++) {\n\tgradient_multipass_b[dependent_index_[i_dependent+i]][i] = 1.0;\n      }\n      for (uIndex ist = n_statements_-1; ist > 0; ist--) {\n\tconst Statement& statement = statement_[ist];\n\tReal a[MULTIPASS_SIZE];\n#if MULTIPASS_SIZE > MULTIPASS_SIZE_ZERO_CHECK\n\tuIndex i_non_zero[MULTIPASS_SIZE];\n#endif\n\tuIndex n_non_zero = 0;\n\tfor (uIndex i = 0; i < n_extra; i++) {\n\t  a[i] = gradient_multipass_b[statement.index][i];\n\t  gradient_multipass_b[statement.index][i] = 0.0;\n\t  if (a[i] != 0.0) {\n#if MULTIPASS_SIZE > MULTIPASS_SIZE_ZERO_CHECK\n\t    i_non_zero[n_non_zero++] = i;\n#else\n\t    n_non_zero = 1;\n#endif\n\t  }\n\t}\n\tif (n_non_zero) {\n\t  for (uIndex iop = statement_[ist-1].end_plus_one;\n\t       iop < statement.end_plus_one; iop++) {\n\t    Real multiplier = multiplier_[iop];\n\t    Real* __restrict gradient_multipass \n\t      = &(gradient_multipass_b[index_[iop]][0]);\n#if MULTIPASS_SIZE > MULTIPASS_SIZE_ZERO_CHECK\n\t    for (uIndex i = 0; i < n_non_zero; i++) {\n\t      gradient_multipass[i_non_zero[i]] += multiplier*a[i_non_zero[i]];\n\t    }\n#else\n\t    for (uIndex i = 0; i < n_extra; i++) {\n\t      gradient_multipass[i] += multiplier*a[i];\n\t    }\n#endif\n\t  }\n\t}\n      }\n      if (dep_offset == 1) {\n\tfor (uIndex iindep = 0; iindep < n_independent(); iindep++) {\n\t  for (uIndex i = 0; i < n_extra; i++) {\n\t    jacobian_out[iindep*indep_offset+i_dependent+i] \n\t      = gradient_multipass_b[independent_index_[iindep]][i];\n\t  }\n\t}\n      }\n      else {\n\tfor (uIndex iindep = 0; iindep < n_independent(); iindep++) {\n\t  for (uIndex i = 0; i < n_extra; i++) {\n\t    jacobian_out[iindep*indep_offset+(i_dependent+i)*dep_offset] \n\t      = gradient_multipass_b[independent_index_[iindep]][i];\n\t  }\n\t}\n      }\n    }\n  }\n  \n  // Return the Jacobian matrix in the matrix \"jac\", using the forward\n  // or reverse method depending which would be faster\n  void Stack::jacobian(Array<2,Real,false> jac) const {\n    if (jac.dimension(0) != n_dependent()\n\t|| jac.dimension(1) != n_independent()) {\n      throw size_mismatch(\"Jacobian matrix has wrong size\");\n    }\n    if (n_independent() <= n_dependent()) {\n      jacobian_forward(jac.data(), jac.offset(0), jac.offset(1));\n    }\n    else {\n      jacobian_reverse(jac.data(), jac.offset(0), jac.offset(1));\n    }\n  }\n\n  // Return the Jacobian matrix in the matrix \"jac\", explicitly\n  // specifying whether to use the forward or reverse method\n  void Stack::jacobian_forward(Array<2,Real,false> jac) const {\n    if (jac.dimension(0) != n_dependent()\n\t|| jac.dimension(1) != n_independent()) {\n      throw size_mismatch(\"Jacobian matrix has wrong size\");\n    }\n    jacobian_forward(jac.data(), jac.offset(0), jac.offset(1));\n  }\n\n  void Stack::jacobian_reverse(Array<2,Real,false> jac) const {\n    if (jac.dimension(0) != n_dependent()\n\t|| jac.dimension(1) != n_independent()) {\n      throw size_mismatch(\"Jacobian matrix has wrong size\");\n    }\n    jacobian_reverse(jac.data(), jac.offset(0), jac.offset(1));\n  }\n\n  // Return the Jacobian matrix using the forward or reverse method\n  // depending which would be faster\n  Array<2,Real,false> Stack::jacobian() const {\n    Array<2,Real,false> jac(n_dependent(), n_independent());\n    if (n_independent() <= n_dependent()) {\n      jacobian_forward(jac.data(), jac.offset(0), jac.offset(1));\n    }\n    else {\n      jacobian_reverse(jac.data(), jac.offset(0), jac.offset(1));\n    }\n    return jac;\n  }\n\n  // Return the Jacobian matrix, explicitly specifying whether to use\n  // the forward or reverse method\n  Array<2,Real,false> Stack::jacobian_forward() const {\n    Array<2,Real,false> jac(n_dependent(), n_independent());\n    jacobian_forward(jac.data(), jac.offset(0), jac.offset(1));\n    return jac;\n  }\n\n  Array<2,Real,false> Stack::jacobian_reverse() const {\n    Array<2,Real,false> jac(n_dependent(), n_independent());\n    jacobian_reverse(jac.data(), jac.offset(0), jac.offset(1));\n    return jac;\n  }\n\n} // End namespace adept\n", "meta": {"hexsha": "2981760f74582d8b83be15ae3769dd5dfc3d5a94", "size": 25506, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "adept/jacobian.cpp", "max_stars_repo_name": "yairchu/Adept-2", "max_stars_repo_head_hexsha": "3b4f898c74139618464ccd8e8df0934aed9ed6a2", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "adept/jacobian.cpp", "max_issues_repo_name": "yairchu/Adept-2", "max_issues_repo_head_hexsha": "3b4f898c74139618464ccd8e8df0934aed9ed6a2", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "adept/jacobian.cpp", "max_forks_repo_name": "yairchu/Adept-2", "max_forks_repo_head_hexsha": "3b4f898c74139618464ccd8e8df0934aed9ed6a2", "max_forks_repo_licenses": ["Apache-2.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.8734177215, "max_line_length": 114, "alphanum_fraction": 0.6766643143, "num_tokens": 7095, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6297746074044134, "lm_q2_score": 0.5312093733737562, "lm_q1q2_score": 0.3345421745660017}}
{"text": "#include \"fluid_solver.h\"\n#include <deal.II/physics/elasticity/kinematics.h>\n#include <deal.II/physics/elasticity/standard_tensors.h>\n\nnamespace Fluid\n{\n  template <int dim>\n  BlockVector<double> FluidSolver<dim>::get_current_solution() const\n  {\n    return present_solution;\n  }\n\n  template <int dim>\n  FluidSolver<dim>::FluidSolver(Triangulation<dim> &tria,\n                                const Parameters::AllParameters &parameters,\n                                std::shared_ptr<Function<dim>> bc)\n    : triangulation(tria),\n      fe(FE_Q<dim>(parameters.fluid_velocity_degree),\n         dim,\n         FE_Q<dim>(parameters.fluid_pressure_degree),\n         1),\n      scalar_fe(parameters.fluid_velocity_degree),\n      dof_handler(triangulation),\n      scalar_dof_handler(triangulation),\n      volume_quad_formula(parameters.fluid_velocity_degree + 1),\n      face_quad_formula(parameters.fluid_velocity_degree + 1),\n      time(parameters.end_time,\n           parameters.time_step,\n           parameters.output_interval,\n           parameters.refinement_interval,\n           parameters.save_interval),\n      timer(std::cout, TimerOutput::never, TimerOutput::wall_times),\n      parameters(parameters),\n      boundary_values(bc)\n  {\n  }\n\n  template <int dim>\n  void FluidSolver<dim>::setup_dofs()\n  {\n    // The first step is to associate DoFs with a given mesh.\n    dof_handler.distribute_dofs(fe);\n    scalar_dof_handler.distribute_dofs(scalar_fe);\n\n    // We renumber the components to have all velocity DoFs come before\n    // the pressure DoFs to be able to split the solution vector in two blocks\n    // which are separately accessed in the block preconditioner.\n    DoFRenumbering::Cuthill_McKee(dof_handler);\n    std::vector<unsigned int> block_component(dim + 1, 0);\n    block_component[dim] = 1;\n    DoFRenumbering::component_wise(dof_handler, block_component);\n\n    dofs_per_block.resize(2);\n    DoFTools::count_dofs_per_block(\n      dof_handler, dofs_per_block, block_component);\n    unsigned int dof_u = dofs_per_block[0];\n    unsigned int dof_p = dofs_per_block[1];\n\n    std::cout << \"   Number of active fluid cells: \"\n              << triangulation.n_active_cells() << std::endl\n              << \"   Number of degrees of freedom: \" << dof_handler.n_dofs()\n              << \" (\" << dof_u << '+' << dof_p << ')' << std::endl;\n  }\n\n  template <int dim>\n  void FluidSolver<dim>::make_constraints()\n  {\n    nonzero_constraints.clear();\n    zero_constraints.clear();\n    DoFTools::make_hanging_node_constraints(dof_handler, nonzero_constraints);\n    DoFTools::make_hanging_node_constraints(dof_handler, zero_constraints);\n    for (auto itr = parameters.fluid_dirichlet_bcs.begin();\n         itr != parameters.fluid_dirichlet_bcs.end();\n         ++itr)\n      {\n        // First get the id, flag and value from the input file\n        unsigned int id = itr->first;\n        unsigned int flag = itr->second.first;\n        std::vector<double> value = itr->second.second;\n\n        // To make VectorTools::interpolate_boundary_values happy,\n        // a vector of bool and a vector of double which are of size\n        // dim + 1 are required.\n        std::vector<bool> mask(dim + 1, false);\n        std::vector<double> augmented_value(dim + 1, 0.0);\n        // 1-x, 2-y, 3-xy, 4-z, 5-xz, 6-yz, 7-xyz\n        switch (flag)\n          {\n          case 1:\n            mask[0] = true;\n            augmented_value[0] = value[0];\n            break;\n          case 2:\n            mask[1] = true;\n            augmented_value[1] = value[0];\n            break;\n          case 3:\n            mask[0] = true;\n            mask[1] = true;\n            augmented_value[0] = value[0];\n            augmented_value[1] = value[1];\n            break;\n          case 4:\n            mask[2] = true;\n            augmented_value[2] = value[0];\n            break;\n          case 5:\n            mask[0] = true;\n            mask[2] = true;\n            augmented_value[0] = value[0];\n            augmented_value[2] = value[1];\n            break;\n          case 6:\n            mask[1] = true;\n            mask[2] = true;\n            augmented_value[1] = value[0];\n            augmented_value[2] = value[1];\n            break;\n          case 7:\n            mask[0] = true;\n            mask[1] = true;\n            mask[2] = true;\n            augmented_value[0] = value[0];\n            augmented_value[1] = value[1];\n            augmented_value[2] = value[2];\n            break;\n          default:\n            AssertThrow(false, ExcMessage(\"Unrecogonized component flag!\"));\n            break;\n          }\n        if (parameters.use_hard_coded_values == 1)\n          {\n            VectorTools::interpolate_boundary_values(\n              MappingQGeneric<dim>(parameters.fluid_velocity_degree),\n              dof_handler,\n              id,\n              *boundary_values,\n              nonzero_constraints,\n              ComponentMask(mask));\n          }\n        else\n          {\n            VectorTools::interpolate_boundary_values(\n              MappingQGeneric<dim>(parameters.fluid_velocity_degree),\n              dof_handler,\n              id,\n              Functions::ConstantFunction<dim>(augmented_value),\n              nonzero_constraints,\n              ComponentMask(mask));\n          }\n        VectorTools::interpolate_boundary_values(\n          MappingQGeneric<dim>(parameters.fluid_velocity_degree),\n          dof_handler,\n          id,\n          Functions::ZeroFunction<dim>(dim + 1),\n          zero_constraints,\n          ComponentMask(mask));\n      }\n    nonzero_constraints.close();\n    zero_constraints.close();\n  }\n\n  template <int dim>\n  void FluidSolver<dim>::setup_cell_property()\n  {\n    cell_property.initialize(\n      triangulation.begin_active(), triangulation.end(), 1);\n    for (auto cell = triangulation.begin_active(); cell != triangulation.end();\n         ++cell)\n      {\n        const std::vector<std::shared_ptr<CellProperty>> p =\n          cell_property.get_data(cell);\n        p[0]->indicator = 0;\n        p[0]->fsi_acceleration = 0;\n        p[0]->fsi_stress = 0;\n      }\n  }\n\n  template <int dim>\n  void FluidSolver<dim>::initialize_system()\n  {\n    system_matrix.clear();\n    mass_matrix.clear();\n    mass_schur.clear();\n\n    BlockDynamicSparsityPattern dsp(dofs_per_block, dofs_per_block);\n    DoFTools::make_sparsity_pattern(dof_handler, dsp, nonzero_constraints);\n    sparsity_pattern.copy_from(dsp);\n\n    system_matrix.reinit(sparsity_pattern);\n    mass_matrix.reinit(sparsity_pattern);\n\n    present_solution.reinit(dofs_per_block);\n    solution_increment.reinit(dofs_per_block);\n    system_rhs.reinit(dofs_per_block);\n\n    // Compute the sparsity pattern for mass schur in advance.\n    // It should be the same as \\f$BB^T\\f$.\n    DynamicSparsityPattern schur_pattern(dofs_per_block[1], dofs_per_block[1]);\n    schur_pattern.compute_mmult_pattern(sparsity_pattern.block(1, 0),\n                                        sparsity_pattern.block(0, 1));\n    mass_schur_pattern.copy_from(schur_pattern);\n    mass_schur.reinit(mass_schur_pattern);\n\n    // Cell property\n    setup_cell_property();\n\n    stress = std::vector<std::vector<Vector<double>>>(\n      dim,\n      std::vector<Vector<double>>(dim,\n                                  Vector<double>(scalar_dof_handler.n_dofs())));\n  }\n\n  template <int dim>\n  void FluidSolver<dim>::refine_mesh(const unsigned int min_grid_level,\n                                     const unsigned int max_grid_level)\n  {\n    TimerOutput::Scope timer_section(timer, \"Refine mesh\");\n\n    Vector<float> estimated_error_per_cell(triangulation.n_active_cells());\n    FEValuesExtractors::Vector velocity(0);\n    using type = std::map<types::boundary_id, const Function<dim, double> *>;\n    KellyErrorEstimator<dim>::estimate(\n      dof_handler,\n      QGauss<dim - 1>(parameters.fluid_velocity_degree),\n      type(),\n      present_solution,\n      estimated_error_per_cell,\n      fe.component_mask(velocity));\n    GridRefinement::refine_and_coarsen_fixed_fraction(\n      triangulation, estimated_error_per_cell, 0.6, 0.4);\n    if (triangulation.n_levels() > max_grid_level)\n      {\n        for (auto cell = triangulation.begin_active(max_grid_level);\n             cell != triangulation.end();\n             ++cell)\n          {\n            cell->clear_refine_flag();\n          }\n      }\n\n    for (auto cell = triangulation.begin_active(min_grid_level);\n         cell != triangulation.end_active(min_grid_level);\n         ++cell)\n      {\n        cell->clear_coarsen_flag();\n      }\n\n    BlockVector<double> buffer(present_solution);\n    SolutionTransfer<dim, BlockVector<double>> solution_transfer(dof_handler);\n\n    triangulation.prepare_coarsening_and_refinement();\n    solution_transfer.prepare_for_coarsening_and_refinement(buffer);\n\n    triangulation.execute_coarsening_and_refinement();\n\n    setup_dofs();\n    make_constraints();\n    initialize_system();\n\n    solution_transfer.interpolate(buffer, present_solution);\n    nonzero_constraints.distribute(present_solution);\n  }\n\n  template <int dim>\n  void FluidSolver<dim>::output_results(const unsigned int output_index) const\n  {\n    TimerOutput::Scope timer_section(timer, \"Output results\");\n\n    std::cout << \"Writing results...\" << std::endl;\n    std::vector<std::string> solution_names(dim, \"velocity\");\n    solution_names.push_back(\"pressure\");\n\n    std::vector<DataComponentInterpretation::DataComponentInterpretation>\n      data_component_interpretation(\n        dim, DataComponentInterpretation::component_is_part_of_vector);\n    data_component_interpretation.push_back(\n      DataComponentInterpretation::component_is_scalar);\n    DataOut<dim> data_out;\n    data_out.attach_dof_handler(dof_handler);\n    data_out.add_data_vector(present_solution,\n                             solution_names,\n                             DataOut<dim>::type_dof_data,\n                             data_component_interpretation);\n\n    // Indicator\n    Vector<float> ind(triangulation.n_active_cells());\n    int i = 0;\n    for (auto cell = triangulation.begin_active(); cell != triangulation.end();\n         ++cell)\n      {\n        auto p = cell_property.get_data(cell);\n        ind[i++] = p[0]->indicator;\n      }\n    data_out.add_data_vector(ind, \"Indicator\");\n\n    // stress\n    data_out.add_data_vector(scalar_dof_handler, stress[0][0], \"Sxx\");\n    data_out.add_data_vector(scalar_dof_handler, stress[0][1], \"Sxy\");\n    data_out.add_data_vector(scalar_dof_handler, stress[1][1], \"Syy\");\n    if (dim == 3)\n      {\n        data_out.add_data_vector(scalar_dof_handler, stress[0][2], \"Sxz\");\n        data_out.add_data_vector(scalar_dof_handler, stress[1][2], \"Syz\");\n        data_out.add_data_vector(scalar_dof_handler, stress[2][2], \"Szz\");\n      }\n\n    data_out.build_patches(parameters.fluid_pressure_degree);\n\n    std::string basename = \"fluid\";\n    std::string filename =\n      basename + \"-\" + Utilities::int_to_string(output_index, 6) + \".vtu\";\n\n    std::ofstream output(filename);\n    data_out.write_vtu(output);\n\n    static std::vector<std::pair<double, std::string>> times_and_names;\n    times_and_names.push_back({time.current(), filename});\n    std::ofstream pvd_output(basename + \".pvd\");\n    DataOutBase::write_pvd_record(pvd_output, times_and_names);\n  }\n\n  template <int dim>\n  void FluidSolver<dim>::update_stress()\n  {\n    for (unsigned int i = 0; i < dim; ++i)\n      {\n        for (unsigned int j = 0; j < dim; ++j)\n          {\n            stress[i][j] = 0.0;\n          }\n      }\n    std::vector<int> surrounding_cells(scalar_dof_handler.n_dofs(), 0);\n    // The stress tensors are stored as 2D vectors of shape dim*dim\n    // at cell and quadrature point level.\n    std::vector<std::vector<Vector<double>>> cell_stress(\n      dim,\n      std::vector<Vector<double>>(dim,\n                                  Vector<double>(scalar_fe.dofs_per_cell)));\n    std::vector<std::vector<Vector<double>>> quad_stress(\n      dim,\n      std::vector<Vector<double>>(dim,\n                                  Vector<double>(volume_quad_formula.size())));\n\n    // The projection matrix from quadrature points to the dofs.\n    FullMatrix<double> qpt_to_dof(scalar_fe.dofs_per_cell,\n                                  volume_quad_formula.size());\n    FETools::compute_projection_from_quadrature_points_matrix(\n      scalar_fe, volume_quad_formula, volume_quad_formula, qpt_to_dof);\n\n    FEValues<dim> fe_values(fe,\n                            volume_quad_formula,\n                            update_values | update_gradients |\n                              update_quadrature_points | update_JxW_values);\n    const unsigned int n_q_points = volume_quad_formula.size();\n    const FEValuesExtractors::Vector velocities(0);\n    const FEValuesExtractors::Scalar pressure(dim);\n    std::vector<SymmetricTensor<2, dim>> sym_grad_v(n_q_points);\n    std::vector<double> p(n_q_points);\n\n    auto cell = dof_handler.begin_active();\n    auto scalar_cell = scalar_dof_handler.begin_active();\n    std::vector<types::global_dof_index> dof_indices(scalar_fe.dofs_per_cell);\n    for (; cell != dof_handler.end(); ++cell, ++scalar_cell)\n      {\n        scalar_cell->get_dof_indices(dof_indices);\n        fe_values.reinit(cell);\n\n        // Fluid symmetric velocity gradient\n        fe_values[velocities].get_function_symmetric_gradients(present_solution,\n                                                               sym_grad_v);\n        // Fluid pressure\n        fe_values[pressure].get_function_values(present_solution, p);\n\n        // Loop over all quadrature points to set FSI forces.\n        for (unsigned int q = 0; q < volume_quad_formula.size(); ++q)\n          {\n            SymmetricTensor<2, dim> sigma =\n              -p[q] * Physics::Elasticity::StandardTensors<dim>::I +\n              2 * parameters.viscosity * sym_grad_v[q];\n            for (unsigned int i = 0; i < dim; ++i)\n              {\n                for (unsigned int j = 0; j < dim; ++j)\n                  {\n                    quad_stress[i][j][q] = sigma[i][j];\n                  }\n              }\n          }\n\n        for (unsigned int i = 0; i < dim; ++i)\n          {\n            for (unsigned int j = 0; j < dim; ++j)\n              {\n                qpt_to_dof.vmult(cell_stress[i][j], quad_stress[i][j]);\n                for (unsigned int k = 0; k < scalar_fe.dofs_per_cell; ++k)\n                  {\n                    stress[i][j][dof_indices[k]] += cell_stress[i][j][k];\n                    if (i == 0 && j == 0)\n                      surrounding_cells[dof_indices[k]]++;\n                  }\n              }\n          }\n      }\n\n    for (unsigned int i = 0; i < dim; ++i)\n      {\n        for (unsigned int j = 0; j < dim; ++j)\n          {\n            for (unsigned int k = 0; k < scalar_dof_handler.n_dofs(); ++k)\n              {\n                stress[i][j][k] /= surrounding_cells[k];\n              }\n          }\n      }\n  }\n\n  template class FluidSolver<2>;\n  template class FluidSolver<3>;\n} // namespace Fluid\n", "meta": {"hexsha": "c1351acf613d32a9775e97df9b4a64f67fa2d380", "size": 14948, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "source/fluid_solver.cpp", "max_stars_repo_name": "AjinkyaDahale/OpenIFEM", "max_stars_repo_head_hexsha": "3b3aac0b5ff9e06c8f74d6b40cbdd4ef33243c47", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-09-03T00:34:05.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-03T00:34:05.000Z", "max_issues_repo_path": "source/fluid_solver.cpp", "max_issues_repo_name": "chenjiatu/OpenIFEM", "max_issues_repo_head_hexsha": "dc0e0081e08827d8f20a3744683ac31ff9e78a55", "max_issues_repo_licenses": ["Apache-2.0"], "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/fluid_solver.cpp", "max_forks_repo_name": "chenjiatu/OpenIFEM", "max_forks_repo_head_hexsha": "dc0e0081e08827d8f20a3744683ac31ff9e78a55", "max_forks_repo_licenses": ["Apache-2.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.5904761905, "max_line_length": 80, "alphanum_fraction": 0.6073053251, "num_tokens": 3457, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6688802603710085, "lm_q2_score": 0.5, "lm_q1q2_score": 0.3344401301855042}}
{"text": "/*\nCopyright 2017. All rights reserved.\nComputer Vision Group, Visual Computing Institute\nRWTH Aachen University, Germany\n\nThis file is part of the rwth_mot framework.\nAuthors: Aljosa Osep (osep -at- vision.rwth-aachen.de)\n\nrwth_mot framework is free software; you can redistribute it and/or modify it under the\nterms of the GNU General Public License as published by the Free Software\nFoundation; either version 3 of the License, or any later version.\n\nrwth_mot framework is distributed in the hope that it will be useful, but WITHOUT ANY\nWARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A\nPARTICULAR PURPOSE. See the GNU General Public License for more details.\n\nYou should have received a copy of the GNU General Public License along with\nrwth_mot framework; if not, write to the Free Software Foundation, Inc., 51 Franklin\nStreet, Fifth Floor, Boston, MA 02110-1301, USA\n*/\n\n#include <tracking/kalman_filter.h>\n\n// eigen\n#include <Eigen/LU>\n\n// std\n#include <iostream>\n#include <fstream>\n\nnamespace GOT {\n    namespace tracking {\n\n        // -------------------------------------------------------------------------------\n        // +++ Implementation: Kalman Filter Base +++\n        // -------------------------------------------------------------------------------\n\n        KalmanFilter::KalmanFilter(const Parameters &params) : state_vector_dim_(0), params_(params)  {\n\n        }\n\n        void KalmanFilter::ComputePrediction(const Eigen::VectorXd &u, Eigen::VectorXd &x_prio,\n                                             Eigen::MatrixXd &P_prio) const {\n            x_prio = A_*x_ + u; // Linear\n\n            // Project covariance ahead\n            P_prio = A_*P_*A_.transpose() + G_ ;\n        }\n\n        void KalmanFilter::Prediction() {\n            assert(this->state_vector_dim_==A_.rows());\n            assert(this->state_vector_dim_==A_.cols());\n            assert(this->state_vector_dim_==G_.rows());\n            assert(this->state_vector_dim_==G_.cols());\n\n            Eigen::VectorXd u_zero, x_prio;\n            Eigen::MatrixXd P_prio;\n            u_zero.setZero(x_.size());\n            this->ComputePrediction(u_zero, x_prio, P_prio);\n\n            if (x_prio.size() != this->params_.state_vector_dim_) {\n                return;\n            }\n\n            x_ = x_prio;\n            P_ = P_prio;\n\n            // Optionally, store whole history. Eg. for visualization.\n            if (params_.store_history_) {\n                this->state_predictions_.push_back(x_);\n                this->cov_predictions_.push_back(P_);\n            }\n        }\n\n        void KalmanFilter::Prediction(const Eigen::VectorXd &u) {\n            assert(this->state_vector_dim_==A_.rows());\n            assert(this->state_vector_dim_==A_.cols());\n            assert(this->state_vector_dim_==G_.rows());\n            assert(this->state_vector_dim_==G_.cols());\n\n            Eigen::VectorXd x_prio;\n            Eigen::MatrixXd P_prio;\n            this->ComputePrediction(u, x_prio, P_prio);\n\n            if (x_prio.size() != this->params_.state_vector_dim_) {\n                return;\n            }\n\n            x_ = x_prio;\n            P_ = P_prio;\n\n            // Optionally, store whole history. Eg. for visualization.\n            if (params_.store_history_) {\n                this->state_predictions_.push_back(x_);\n                this->cov_predictions_.push_back(P_);\n            }\n        }\n\n        /// H is the observation model matrix (residual = z_t - H*x)\n        void KalmanFilter::Correction(const Eigen::VectorXd z_t, const Eigen::MatrixXd &observation_cov_t, const Eigen::MatrixXd &H) {\n            Eigen::MatrixXd H_transposed = H.transpose();\n\n            // Compute Kalman gain\n            Eigen::MatrixXd HPH_plus_obs_cov= (H*P_*H_transposed)+observation_cov_t;\n            Eigen::MatrixXd K = P_*H_transposed*HPH_plus_obs_cov.inverse();\n\n            // Update the estimate\n            Eigen::VectorXd measurement_residual = z_t - H*x_;\n\n            x_ = x_ + K*measurement_residual; //(z_t - H_*x_);\n\n            // Update the covariance\n            Eigen::MatrixXd  KH = K*H;\n            P_ = (Eigen::MatrixXd::Identity(KH.rows(), KH.cols()) - KH)*P_;\n\n            // Optionally, store whole history. Eg. for visualization.\n            if (params_.store_history_) {\n                this->state_corrections_.push_back(x_);\n                this->cov_corrections_.push_back(P_);\n                this->measurements_.push_back(z_t);\n                this->cov_measurements_.push_back(observation_cov_t);\n                this->kalman_gain_.push_back(K);\n            }\n        }\n\n        /// Format: /path/to/dir/name_%s.txt\n        /// Note: state dim. is not stored. At the client side, it is assumed to be simply 'known'.\n        void KalmanFilter::SaveHistoryToFile(const char *filename) const {\n            if (!this->params_.store_history_) {\n                std::cout << \"KalmanFilter::Error: Attempting to save Kalman history, but the params.save_history flag is off! Abort!\" << std::endl;\n                return;\n            }\n\n            /// States\n            char buff[500];\n            snprintf(buff, 500, filename, \"state_predictions\");\n            std::ofstream state_pred_stream(buff);\n\n            snprintf(buff, 500, filename, \"state_corrections\");\n            std::ofstream state_corr_stream(buff);\n\n            snprintf(buff, 500, filename, \"state_measurements\");\n            std::ofstream state_meas_stream(buff);\n\n            for (const auto &vec : state_predictions_)\n                state_pred_stream << vec.transpose() << std::endl;\n\n            for (const auto &vec : state_corrections_)\n                state_corr_stream << vec.transpose() << std::endl;\n\n            for (const auto &vec : measurements_)\n                state_meas_stream << vec.transpose() << std::endl;\n\n            //! Covariances\n            snprintf(buff, 500, filename, \"covariance_predictions\");\n            std::ofstream cov_pred_stream(buff);\n\n            snprintf(buff, 500, filename, \"covariance_corrections\");\n            std::ofstream cov_corr_stream(buff);\n\n            snprintf(buff, 500, filename, \"covariance_measurements\");\n            std::ofstream cov_meas_stream(buff);\n\n            for (const auto &mat : cov_predictions_)\n                cov_pred_stream << mat << std::endl;\n\n            for (const auto &mat : cov_corrections_)\n                cov_corr_stream << mat << std::endl;\n\n            for (const auto &mat : cov_measurements_)\n                cov_meas_stream << mat << std::endl;\n\n            // Close file streams\n            state_pred_stream.close();\n            state_corr_stream.close();\n            state_meas_stream.close();\n\n            cov_pred_stream.close();\n            cov_corr_stream.close();\n            cov_meas_stream.close();\n        }\n\n        // Setters / Getters\n        const Eigen::VectorXd& KalmanFilter::x() const {\n            return x_;\n        }\n\n        void KalmanFilter::set_x(const Eigen::VectorXd &state) {\n            this->x_ = state;\n        }\n\n        const Eigen::MatrixXd& KalmanFilter::P() const {\n            return this->P_;\n        }\n\n        void KalmanFilter::set_G(const Eigen::MatrixXd& G) {\n            this->G_ = G;\n        }\n\n        const Eigen::MatrixXd& KalmanFilter::G() const {\n            return this->G_;\n        }\n\n        const std::vector<Eigen::VectorXd>& KalmanFilter::state_predictions() const {\n            return this->state_predictions_;\n        }\n\n        const std::vector<Eigen::VectorXd>& KalmanFilter::state_corrections() const {\n            return this->state_corrections_;\n        }\n\n        const std::vector<Eigen::MatrixXd>& KalmanFilter::cov_predictions() const {\n            return this->cov_predictions_;\n        }\n\n        const std::vector<Eigen::MatrixXd>& KalmanFilter::cov_corrections() const {\n            return this->cov_corrections_;\n        }\n\n        const std::vector<Eigen::VectorXd>& KalmanFilter::measurements() const {\n            return this->measurements_;\n        }\n\n        const std::vector<Eigen::MatrixXd>& KalmanFilter::cov_measurements() const {\n            return this->cov_measurements_;\n        }\n\n        const KalmanFilter::Parameters KalmanFilter::parameters() const {\n            return params_;\n        }\n\n        void KalmanFilter::set_A(const Eigen::MatrixXd &A) {\n            this->A_ = A;\n        }\n\n        const Eigen::MatrixXd &KalmanFilter::A() const {\n            return this->A_;\n        }\n\n        const std::vector<Eigen::MatrixXd> &KalmanFilter::kalman_gains() const {\n            return this->kalman_gain_;\n        }\n\n        // -------------------------------------------------------------------------------\n        // +++ Implementation: Little example: simple Const-Velocity model +++\n        // -------------------------------------------------------------------------------\n\n        ConstantVelocityKalmanFilter::ConstantVelocityKalmanFilter(const Parameters &params) : params_(params), KalmanFilter(\n                static_cast<KalmanFilter::Parameters>(params)) {\n        }\n\n        void ConstantVelocityKalmanFilter::Init(const Eigen::VectorXd &x_0, const Eigen::MatrixXd &P_0) {\n            // Set params\n            this->state_vector_dim_ = params_.state_vector_dim_;\n            const double dt = params_.dt; // Assume delta_t parameter is given\n\n            assert(this->state_vector_dim_==x_0.size());\n            assert(this->state_vector_dim_==P_0.rows());\n            assert(this->state_vector_dim_==P_0.cols());\n\n            // Set initial state\n            this->x_ = x_0;\n            this->P_ = P_0;\n\n            // Set up transition matrix A (simply adds change in velocity to pos.)\n            A_.setIdentity(state_vector_dim_, state_vector_dim_);\n            A_(0,2) = dt;\n            A_(1,3) = dt;\n\n            G_ = Eigen::Matrix4d::Identity() *0.1*0.1; // Default process noise.\n        }\n    }\n}\n", "meta": {"hexsha": "eb32bbe3f37c8738bf1b26e945414d68900ec639", "size": 9905, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/tracking/kalman_filter.cpp", "max_stars_repo_name": "glc12125/ciwt", "max_stars_repo_head_hexsha": "fb56e43cdfb0856c4609c33cd12905185d42a6e4", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 88.0, "max_stars_repo_stars_event_min_datetime": "2017-05-30T08:26:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-13T04:11:25.000Z", "max_issues_repo_path": "src/tracking/kalman_filter.cpp", "max_issues_repo_name": "OmranKaddah/Multi-Object-Tracking-in-The-Driving-Scene", "max_issues_repo_head_hexsha": "0a2e8092b7e8f4d6317b201be5442e62c4efd240", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": 7.0, "max_issues_repo_issues_event_min_datetime": "2017-07-28T02:43:42.000Z", "max_issues_repo_issues_event_max_datetime": "2019-09-12T03:35:54.000Z", "max_forks_repo_path": "src/tracking/kalman_filter.cpp", "max_forks_repo_name": "OmranKaddah/Multi-Object-Tracking-in-The-Driving-Scene", "max_forks_repo_head_hexsha": "0a2e8092b7e8f4d6317b201be5442e62c4efd240", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 41.0, "max_forks_repo_forks_event_min_datetime": "2017-07-23T06:58:00.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-19T13:59:17.000Z", "avg_line_length": 36.1496350365, "max_line_length": 148, "alphanum_fraction": 0.5688036345, "num_tokens": 2132, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6959583124210896, "lm_q2_score": 0.48047867804790706, "lm_q1q2_score": 0.3343931299285374}}
{"text": "#ifndef STAN_OPTIMIZATION_LBFGS_UPDATE_HPP\n#define STAN_OPTIMIZATION_LBFGS_UPDATE_HPP\n\n#include <stan/math/prim/fun/Eigen.hpp>\n#include <boost/circular_buffer.hpp>\n#include <tuple>\n#include <vector>\n\nnamespace stan {\nnamespace optimization {\n/**\n * Implement a limited memory version of the BFGS update.  This\n * class maintains a circular buffer of inverse Hessian updates\n * which can be applied to compute the search direction.\n **/\ntemplate <typename Scalar = double, int DimAtCompile = Eigen::Dynamic>\nclass LBFGSUpdate {\n public:\n  typedef Eigen::Matrix<Scalar, DimAtCompile, 1> VectorT;\n  typedef Eigen::Matrix<Scalar, DimAtCompile, DimAtCompile> HessianT;\n  // NOLINTNEXTLINE(build/include_what_you_use)\n  typedef std::tuple<Scalar, VectorT, VectorT> UpdateT;\n\n  explicit LBFGSUpdate(size_t L = 5) : _buf(L) {}\n\n  /**\n   * Set the number of inverse Hessian updates to keep.\n   *\n   * @param L New size of buffer.\n   **/\n  void set_history_size(size_t L) { _buf.rset_capacity(L); }\n\n  /**\n   * Add a new set of update vectors to the history.\n   *\n   * @param yk Difference between the current and previous gradient vector.\n   * @param sk Difference between the current and previous state vector.\n   * @param reset Whether to reset the approximation, forgetting about\n   * previous values.\n   * @return In the case of a reset, returns the optimal scaling of the\n   * initial Hessian\n   * approximation which is useful for predicting step-sizes.\n   **/\n  inline Scalar update(const VectorT &yk, const VectorT &sk,\n                       bool reset = false) {\n    Scalar skyk = yk.dot(sk);\n\n    Scalar B0fact;\n    if (reset) {\n      B0fact = yk.squaredNorm() / skyk;\n      _buf.clear();\n    } else {\n      B0fact = 1.0;\n    }\n\n    // New updates are pushed to the \"back\" of the circular buffer\n    Scalar invskyk = 1.0 / skyk;\n    _gammak = skyk / yk.squaredNorm();\n    _buf.push_back();\n    _buf.back() = std::tie(invskyk, yk, sk);\n\n    return B0fact;\n  }\n\n  /**\n   * Compute the search direction based on the current (inverse) Hessian\n   * approximation and given gradient.\n   *\n   * @param[out] pk The negative product of the inverse Hessian and gradient\n   * direction gk.\n   * @param[in] gk Gradient direction.\n   **/\n  inline void search_direction(VectorT &pk, const VectorT &gk) const {\n    std::vector<Scalar> alphas(_buf.size());\n    typename boost::circular_buffer<UpdateT>::const_reverse_iterator buf_rit;\n    typename boost::circular_buffer<UpdateT>::const_iterator buf_it;\n    typename std::vector<Scalar>::const_iterator alpha_it;\n    typename std::vector<Scalar>::reverse_iterator alpha_rit;\n\n    pk.noalias() = -gk;\n    for (buf_rit = _buf.rbegin(), alpha_rit = alphas.rbegin();\n         buf_rit != _buf.rend(); buf_rit++, alpha_rit++) {\n      Scalar alpha;\n      const Scalar &rhoi(std::get<0>(*buf_rit));\n      const VectorT &yi(std::get<1>(*buf_rit));\n      const VectorT &si(std::get<2>(*buf_rit));\n\n      alpha = rhoi * si.dot(pk);\n      pk -= alpha * yi;\n      *alpha_rit = alpha;\n    }\n    pk *= _gammak;\n    for (buf_it = _buf.begin(), alpha_it = alphas.begin(); buf_it != _buf.end();\n         buf_it++, alpha_it++) {\n      Scalar beta;\n      const Scalar &rhoi(std::get<0>(*buf_it));\n      const VectorT &yi(std::get<1>(*buf_it));\n      const VectorT &si(std::get<2>(*buf_it));\n\n      beta = rhoi * yi.dot(pk);\n      pk += (*alpha_it - beta) * si;\n    }\n  }\n\n protected:\n  boost::circular_buffer<UpdateT> _buf;\n  Scalar _gammak;\n};\n}  // namespace optimization\n}  // namespace stan\n\n#endif\n", "meta": {"hexsha": "ba9d7afcb62584fd5d72d19981d011b9a5c5db22", "size": 3519, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/stan/optimization/lbfgs_update.hpp", "max_stars_repo_name": "sthagen/stan-dev-stan", "max_stars_repo_head_hexsha": "38ab6922649f1cf35e66fa812fc28ce693cde345", "max_stars_repo_licenses": ["CC-BY-3.0", "BSD-3-Clause"], "max_stars_count": 2171.0, "max_stars_repo_stars_event_min_datetime": "2015-01-09T01:41:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T12:00:36.000Z", "max_issues_repo_path": "src/stan/optimization/lbfgs_update.hpp", "max_issues_repo_name": "sthagen/stan-dev-stan", "max_issues_repo_head_hexsha": "38ab6922649f1cf35e66fa812fc28ce693cde345", "max_issues_repo_licenses": ["CC-BY-3.0", "BSD-3-Clause"], "max_issues_count": 1885.0, "max_issues_repo_issues_event_min_datetime": "2015-01-02T13:33:12.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T23:00:39.000Z", "max_forks_repo_path": "src/stan/optimization/lbfgs_update.hpp", "max_forks_repo_name": "sthagen/stan-dev-stan", "max_forks_repo_head_hexsha": "38ab6922649f1cf35e66fa812fc28ce693cde345", "max_forks_repo_licenses": ["CC-BY-3.0", "BSD-3-Clause"], "max_forks_count": 393.0, "max_forks_repo_forks_event_min_datetime": "2015-01-16T22:42:33.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-29T23:21:16.000Z", "avg_line_length": 31.1415929204, "max_line_length": 80, "alphanum_fraction": 0.6641091219, "num_tokens": 953, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.658417500561683, "lm_q2_score": 0.5078118642792044, "lm_q1q2_score": 0.33435221843428237}}
{"text": "<<<<<<< HEAD\n/*    Copyright (c) 2010-2018, Delft University of Technology\n=======\n/*    Copyright (c) 2010-2019, Delft University of Technology\n>>>>>>> origin/master\n *    All rigths reserved\n *\n *    This file is part of the Tudat. Redistribution and use in source and\n *    binary forms, with or without modification, are permitted exclusively\n *    under the terms of the Modified BSD license. You should have received\n *    a copy of the license with this file. If not, please or visit:\n *    http://tudat.tudelft.nl/LICENSE.\n *\n *    References\n *      References for deltaV computation function:\n *          Melman J. Trajectory optimization for a mission to Neptune and Triton, MSc thesis\n *              report, Delft University of Technology, 2007.\n *          Musegaas, P., Optimization of Space Trajectories Including Multiple Gravity Assists and\n *              Deep Space Maneuvers, MSc thesis report, Delft University of Technology, 2012.\n *              [unpublished so far].\n *      Reference for unpowered gravity assist propagation function:\n *          Conway, B.A., Spacecraft Trajectory Optimization, Chapter 7, Cambridge University\n *              Press, 2010.\n *      Reference for powered gravity assist propagation function:\n *          Musegaas, P., Optimization of Space Trajectories Including Multiple Gravity Assists and\n *              Deep Space Maneuvers, MSc thesis report, Delft University of Technology, 2012.\n *              [unpublished so far].\n *\n *    Notes\n *      Gravity assist and swing-by are two different words for the same thing. The delta-V that is\n *      computed for a powered swing-by has not been proven to be the optimum (lowest) to achieve\n *      the desired geometry of incoming and outgoing hyperbolic legs. Some literature research will\n *      have to be done to look at the alternatives.\n *\n *      Note that the exact implementation of Newton Raphson as root finder should be updated if\n *      someone would want to use a different root finding technique.\n *\n *      Note that by default a velocity effect deltaV of less than 1 micrometer/second is deemed\n *      negligable in this code. This value can be set though.\n *\n */\n\n#include <cmath>\n\n#include <boost/bind.hpp>\n\n#include <Eigen/Dense>\n\n#include \"Tudat/Mathematics/BasicMathematics/linearAlgebra.h\"\n\n#include \"Tudat/Astrodynamics/MissionSegments/gravityAssist.h\"\n#include \"Tudat/Mathematics/BasicMathematics/functionProxy.h\"\n#include \"Tudat/Mathematics/RootFinders/bisection.h\"\n\n\nnamespace tudat\n{\nnamespace mission_segments\n{\n\nusing namespace root_finders;\n\n//! Calculate deltaV of a gravity assist.\ndouble gravityAssist( const double centralBodyGravitationalParameter,\n                      const Eigen::Vector3d& centralBodyVelocity,\n                      const Eigen::Vector3d& incomingVelocity,\n                      const Eigen::Vector3d& outgoingVelocity,\n                      const double smallestPeriapsisDistance,\n                      const bool useEccentricityInsteadOfPericenter,\n                      const double speedTolerance,\n                      RootFinderPointer rootFinder )\n{\n    using basic_mathematics::UnivariateProxyPointer;\n    using basic_mathematics::UnivariateProxy;\n\n    // Compute incoming and outgoing hyperbolic excess velocity.\n    const Eigen::Vector3d incomingHyperbolicExcessVelocity\n            = incomingVelocity - centralBodyVelocity;\n    const Eigen::Vector3d outgoingHyperbolicExcessVelocity\n            = outgoingVelocity - centralBodyVelocity;\n\n    // Compute absolute values of the hyperbolic excess velocities.\n    const double absoluteIncomingExcessVelocity = incomingHyperbolicExcessVelocity.norm( );\n    const double absoluteOutgoingExcessVelocity = outgoingHyperbolicExcessVelocity.norm( );\n\n    // Compute bending angle.\n    double bendingAngle = linear_algebra::computeAngleBetweenVectors(\n                            incomingHyperbolicExcessVelocity, outgoingHyperbolicExcessVelocity );\n\n    // Compute maximum achievable bending angle.\n    const double maximumBendingAngle =\n            std::asin( 1.0 / ( 1.0 + ( smallestPeriapsisDistance *\n                                       absoluteIncomingExcessVelocity *\n                                       absoluteIncomingExcessVelocity /\n                                       centralBodyGravitationalParameter ) ) ) +\n            std::asin( 1.0 / ( 1.0 + ( smallestPeriapsisDistance *\n                                       absoluteOutgoingExcessVelocity *\n                                       absoluteOutgoingExcessVelocity /\n                                       centralBodyGravitationalParameter ) ) );\n\n    // Initialize bending effect deltaV, which is zero, unless extra bending angle is required.\n    double bendingEffectDeltaV = 0.0;\n\n    // Initialize velocity effect delta V parameter.\n    double velocityEffectDeltaV = 0.0;\n\n    // Check if an additional bending angle is required. If so, the additional bending angle\n    // maneuver has to be performed. Also the pericenter radius will be the minimum pericenter\n    // radius to obtain the largest possible bending angle 'for free'. Hence no root finding is\n    // required for this case. As noted above, this may not be ideal for all cases. (for cases\n    // in which the excess velocities are relatively small)\n    if ( bendingAngle > maximumBendingAngle )\n    {\n        // Compute required extra bending angle that cannot be delivered by an unpowered swing-by.\n        const double extraBendingAngle = bendingAngle - maximumBendingAngle;\n\n        // Compute necessary delta-V due to bending-effect.\n        bendingEffectDeltaV = 2.0 * std::min( absoluteIncomingExcessVelocity,\n                                              absoluteOutgoingExcessVelocity ) *\n                                    std::sin( extraBendingAngle / 2.0 );\n\n        // This means the pericenter radius is now equal to the smallest pericenter radius, to\n        // ensure the largest possible bending angle.\n        const double pericenterRadius = smallestPeriapsisDistance;\n\n        // Compute semi-major axis of hyperbolic legs.\n        const double incomingSemiMajorAxis = -1.0 * centralBodyGravitationalParameter /\n                                             absoluteIncomingExcessVelocity /\n                                             absoluteIncomingExcessVelocity;\n        const double outgoingSemiMajorAxis = -1.0 * centralBodyGravitationalParameter /\n                                             absoluteOutgoingExcessVelocity /\n                                             absoluteOutgoingExcessVelocity;\n\n        // Compute incoming hyperbolic leg eccentricity.\n        const double incomingEccentricity = 1 - pericenterRadius / incomingSemiMajorAxis;\n\n        // Compute outgoing hyperbolic leg eccentricity.\n        const double outgoingEccentricity = 1 - pericenterRadius / outgoingSemiMajorAxis;\n\n        // Compute incoming and outgoing velocities at periapsis.\n        const double incomingVelocityAtPeriapsis = absoluteIncomingExcessVelocity *\n                std::sqrt( ( incomingEccentricity + 1.0 ) / ( incomingEccentricity - 1.0 ) );\n        const double outgoingVelocityAtPeriapsis = absoluteOutgoingExcessVelocity *\n                std::sqrt( ( outgoingEccentricity + 1.0 ) / ( outgoingEccentricity - 1.0 ) );\n\n        // Compute necessary delta-V due to velocity-effect.\n        velocityEffectDeltaV = std::fabs( incomingVelocityAtPeriapsis -\n                                          outgoingVelocityAtPeriapsis );\n    }\n\n    else if ( ( std::fabs( absoluteIncomingExcessVelocity - absoluteOutgoingExcessVelocity )\n                <= speedTolerance ) )\n    {\n        // In this case no maneuver has to be performed. Hence no iteration is performed, and the\n        // delta V is simply kept at 0.0.\n    }\n\n    // Here the required maneuver to patch the incoming and outgoing excess velocities is\n    // calculated. In this implementation, the eccentricity will be used as iteration parameter.\n    else if ( useEccentricityInsteadOfPericenter )\n    {\n        // Compute semi-major axis of hyperbolic legs.\n        const double incomingSemiMajorAxis = -1.0 * centralBodyGravitationalParameter /\n                                             absoluteIncomingExcessVelocity /\n                                             absoluteIncomingExcessVelocity;\n        const double outgoingSemiMajorAxis = -1.0 * centralBodyGravitationalParameter /\n                                             absoluteOutgoingExcessVelocity /\n                                             absoluteOutgoingExcessVelocity;\n\n        // Set the gravity assist function with the variables to perform root finder calculations.\n        EccentricityFindingFunctions eccentricityFindingFunctions( incomingSemiMajorAxis,\n                                                                   outgoingSemiMajorAxis,\n                                                                   bendingAngle );\n\n        // Create an object containing the function of which we whish to obtain the root from.\n        UnivariateProxyPointer rootFunction = std::make_shared< UnivariateProxy >(\n                    std::bind( &EccentricityFindingFunctions::\n                                 computeIncomingEccentricityFunction,\n                                 eccentricityFindingFunctions, std::placeholders::_1 ) );\n\n        // Add the first derivative of the root function.\n        rootFunction->addBinding( -1, std::bind(\n                                      &EccentricityFindingFunctions::\n                                      computeFirstDerivativeIncomingEccentricityFunction,\n                                      eccentricityFindingFunctions, std::placeholders::_1 ) );\n\n        // Initialize incoming eccentricity.\n        double incomingEccentricity = TUDAT_NAN;\n\n        // Set initial guess of the variable computed in Newton-Rapshon method.\n        if ( ( absoluteOutgoingExcessVelocity / absoluteIncomingExcessVelocity ) < 100.0 )\n        {\n            // In these cases the very low estimate (which is given under else) may in some cases\n            // result in no convergence. Hence a higher value of 1.01 is necessary. This will not\n            // result in 'going through' 1.0 as mentioned below, because the eccentricity in these\n            // cases is always high!\n            try\n            {\n                incomingEccentricity = rootFinder->execute( rootFunction, 1.0 + 1.0e-2 );\n            }\n            catch(std::runtime_error)\n            {\n                root_finders::RootFinderPointer rootFinder_temp\n                  = std::make_shared< root_finders::Bisection >( 1.0e-12, 1000 ) ;\n                incomingEccentricity = rootFinder_temp->execute( rootFunction, 1.0 + 1.0e-2 );\n\n            }\n        }\n\n        else\n        {\n            // This is set to a value that is close to 1.0. This is more robust than higher values,\n            // because for those higher values Newton Raphson sometimes 'goes through' 1.0. This\n            // results in NaN values for the derivative of the eccentricity finding function.\n            try\n            {\n                incomingEccentricity = rootFinder->execute( rootFunction, 1.0 + 1.0e-10 );\n            }\n            catch(std::runtime_error)\n            {\n                root_finders::RootFinderPointer rootFinder_temp\n                  = std::make_shared< root_finders::Bisection >( 1.0e-12, 1000 ) ;\n                incomingEccentricity = rootFinder_temp->execute( rootFunction, 1.0 + 1.0e-10 );\n\n            }\n        }\n\n        // Compute outgoing hyperbolic leg eccentricity.\n        const double outgoingEccentricity = 1.0 - ( incomingSemiMajorAxis /\n                                                    outgoingSemiMajorAxis ) *\n                                            ( 1.0 - incomingEccentricity );\n\n        // Compute incoming and outgoing velocities at periapsis.\n        const double incomingVelocityAtPeriapsis = absoluteIncomingExcessVelocity *\n                std::sqrt( ( incomingEccentricity + 1.0 ) / ( incomingEccentricity - 1.0 ) );\n        const double outgoingVelocityAtPeriapsis = absoluteOutgoingExcessVelocity *\n                std::sqrt( ( outgoingEccentricity + 1.0 ) / ( outgoingEccentricity - 1.0 ) );\n\n        // Compute necessary delta-V due to velocity-effect.\n        velocityEffectDeltaV = std::fabs( incomingVelocityAtPeriapsis -\n                                          outgoingVelocityAtPeriapsis );\n    }\n\n    // Here the required maneuver to patch the incoming and outgoing excess velocities is\n    // calculated. In this implementation, the pericenter radius will be used as iteration\n    // parameter.\n    else\n    {\n        // Compute semi-major axis of hyperbolic legs. This is the absolute semi-major axis, because\n        // it will otherwisely result in the root of a negative function for various cases during\n        // the rootfinding process.\n        const double absoluteIncomingSemiMajorAxis = 1.0 * centralBodyGravitationalParameter /\n                                                     absoluteIncomingExcessVelocity /\n                                                     absoluteIncomingExcessVelocity;\n        const double absoluteOutgoingSemiMajorAxis = 1.0 * centralBodyGravitationalParameter /\n                                                     absoluteOutgoingExcessVelocity /\n                                                     absoluteOutgoingExcessVelocity;\n\n        // Set the gravity assist function with the variables to perform root finder calculations.\n        PericenterFindingFunctions pericenterFindingFunctions( absoluteIncomingSemiMajorAxis,\n                                                               absoluteOutgoingSemiMajorAxis,\n                                                               bendingAngle);\n\n        // Create an object containing the function of which we whish to obtain the root from.\n        UnivariateProxyPointer rootFunction = std::make_shared< UnivariateProxy >(\n                    std::bind( &PericenterFindingFunctions::computePericenterRadiusFunction,\n                                 pericenterFindingFunctions, std::placeholders::_1 ) );\n\n        // Add the first derivative of the root function.\n        rootFunction->addBinding( -1, std::bind( &PericenterFindingFunctions::\n                                                   computeFirstDerivativePericenterRadiusFunction,\n                                                   pericenterFindingFunctions, std::placeholders::_1 ) );\n\n        // Set pericenter radius based on result of Newton-Raphson root-finding algorithm.\n        const double pericenterRadius = rootFinder->execute( rootFunction,\n                                                             smallestPeriapsisDistance );\n\n        // Compute incoming hyperbolic leg eccentricity.\n        const double incomingEccentricity = 1.0 + pericenterRadius / absoluteIncomingSemiMajorAxis;\n\n        // Compute outgoing hyperbolic leg eccentricity.\n        const double outgoingEccentricity = 1.0 + pericenterRadius / absoluteOutgoingSemiMajorAxis;\n\n        // Compute incoming and outgoing velocities at periapsis.\n        const double incomingVelocityAtPeriapsis = absoluteIncomingExcessVelocity *\n                std::sqrt( ( incomingEccentricity + 1.0 ) / ( incomingEccentricity - 1.0 ) );\n        const double outgoingVelocityAtPeriapsis = absoluteOutgoingExcessVelocity *\n                std::sqrt( ( outgoingEccentricity + 1.0 ) / ( outgoingEccentricity - 1.0 ) );\n\n        // Compute necessary delta-V due to velocity-effect.\n        velocityEffectDeltaV = std::fabs( incomingVelocityAtPeriapsis -\n                                          outgoingVelocityAtPeriapsis );\n    }\n\n    // Compute and return the total delta-V.\n    return bendingEffectDeltaV + velocityEffectDeltaV;\n}\n\n//! Propagate an unpowered gravity assist.\nEigen::Vector3d gravityAssist( const double centralBodyGravitationalParameter,\n                               const Eigen::Vector3d& centralBodyVelocity,\n                               const Eigen::Vector3d& incomingVelocity,\n                               const double rotationAngle,\n                               const double pericenterRadius )\n{\n    // Calculate the incoming velocity.\n    const Eigen::Vector3d relativeIncomingVelocity = incomingVelocity - centralBodyVelocity;\n    const double absoluteRelativeIncomingVelocity = relativeIncomingVelocity.norm( );\n\n    // Calculate the eccentricity and bending angle.\n    const double eccentricity = 1.0 + pericenterRadius / centralBodyGravitationalParameter *\n                            absoluteRelativeIncomingVelocity * absoluteRelativeIncomingVelocity;\n    const double bendingAngle = 2.0 * std::asin ( 1.0 / eccentricity );\n\n    // Calculate the unit vectors.\n    const Eigen::Vector3d unitVector1 = relativeIncomingVelocity /\n                                        absoluteRelativeIncomingVelocity;\n    const Eigen::Vector3d unitVector2 = unitVector1.cross( centralBodyVelocity ).normalized( );\n    const Eigen::Vector3d unitVector3 = unitVector1.cross( unitVector2 );\n\n    // Calculate the relative outgoing velocity.\n    const Eigen::Vector3d relativeOutgoingVelocity = absoluteRelativeIncomingVelocity *\n            ( std::cos( bendingAngle ) * unitVector1 + std::sin( bendingAngle ) *\n              std::cos( rotationAngle ) * unitVector2 + std::sin( bendingAngle ) *\n              std::sin( rotationAngle ) * unitVector3 );\n\n    // Add the relative outgoing velocity to the swing-by body velocity and return it.\n    return centralBodyVelocity + relativeOutgoingVelocity;\n}\n\n//! Propagate a powered gravity assist.\nEigen::Vector3d gravityAssist( const double centralBodyGravitationalParameter,\n                               const Eigen::Vector3d& centralBodyVelocity,\n                               const Eigen::Vector3d& incomingVelocity,\n                               const double rotationAngle,\n                               const double pericenterRadius,\n                               const double deltaV )\n{\n    // Calculate the incoming velocity.\n    const Eigen::Vector3d relativeIncomingVelocity = incomingVelocity - centralBodyVelocity;\n    const double absoluteRelativeIncomingVelocity = relativeIncomingVelocity.norm( );\n\n    // Calculate the incoming eccentricity and bending angle.\n    const double incomingEccentricity = 1.0 + pericenterRadius /\n                                        centralBodyGravitationalParameter *\n                                        absoluteRelativeIncomingVelocity *\n                                        absoluteRelativeIncomingVelocity;\n    const double incomingBendingAngle = std::asin ( 1.0 / incomingEccentricity );\n\n    // Calculate the pericenter velocities.\n    const double incomingPericenterVelocity = std::sqrt( absoluteRelativeIncomingVelocity *\n                                                         absoluteRelativeIncomingVelocity *\n                                                         ( incomingEccentricity + 1.0 ) /\n                                                         ( incomingEccentricity - 1.0 ) );\n    const double outgoingPericenterVelocity = incomingPericenterVelocity + deltaV;\n\n    // Calculate magnitude of the absolute relative outgoing velocity.\n    const double absoluteRelativeOutgoingVelocity =\n            std::sqrt( outgoingPericenterVelocity * outgoingPericenterVelocity -\n                       2.0 * centralBodyGravitationalParameter / pericenterRadius );\n\n    // Calculate the remaining bending angles.\n    const double outgoingBendingAngle =\n            std::asin ( 1.0 / ( 1.0 + absoluteRelativeOutgoingVelocity *\n                                absoluteRelativeOutgoingVelocity * pericenterRadius /\n                                centralBodyGravitationalParameter ) );\n    const double bendingAngle = incomingBendingAngle + outgoingBendingAngle;\n\n    // Calculate the unit vectors.\n    const Eigen::Vector3d unitVector1 = relativeIncomingVelocity /\n                                        absoluteRelativeIncomingVelocity;\n    const Eigen::Vector3d unitVector2 = unitVector1.cross( centralBodyVelocity ).normalized( );\n    const Eigen::Vector3d unitVector3 = unitVector1.cross( unitVector2 );\n\n    // Calculate the relative outgoing velocity.\n    const Eigen::Vector3d relativeOutgoingVelocity = absoluteRelativeOutgoingVelocity *\n            ( std::cos( bendingAngle ) * unitVector1 + std::sin( bendingAngle ) *\n              std::cos( rotationAngle ) * unitVector2 + std::sin( bendingAngle ) *\n              std::sin( rotationAngle ) * unitVector3 );\n\n    // Add the relative outgoing velocity to the swing-by body velocity and return it.\n    return centralBodyVelocity + relativeOutgoingVelocity;\n}\n\n//! Compute pericenter radius function.\ndouble PericenterFindingFunctions::computePericenterRadiusFunction( const double pericenterRadius )\n{\n    return std::asin( absoluteIncomingSemiMajorAxis_ / ( absoluteIncomingSemiMajorAxis_ +\n                                                         pericenterRadius ) ) +\n           std::asin( absoluteOutgoingSemiMajorAxis_ / ( absoluteOutgoingSemiMajorAxis_ +\n                                                         pericenterRadius ) ) - bendingAngle_;\n}\n\n//! Compute first-derivative of the pericenter radius function.\ndouble PericenterFindingFunctions::computeFirstDerivativePericenterRadiusFunction(\n        const double pericenterRadius )\n{\n    return -absoluteIncomingSemiMajorAxis_ / ( absoluteIncomingSemiMajorAxis_ + pericenterRadius )\n            / std::sqrt( ( pericenterRadius + 2.0 * absoluteIncomingSemiMajorAxis_ )\n                         * pericenterRadius ) -\n           absoluteOutgoingSemiMajorAxis_ / ( absoluteOutgoingSemiMajorAxis_ + pericenterRadius )\n            / std::sqrt( ( pericenterRadius + 2.0 * absoluteOutgoingSemiMajorAxis_ ) *\n                         pericenterRadius );\n}\n\n//! Compute incoming eccentricity function.\ndouble EccentricityFindingFunctions::computeIncomingEccentricityFunction(\n        const double incomingEccentricity )\n{\n    return std::asin( 1.0 / incomingEccentricity )\n            + std::asin( 1.0 / ( 1.0 - incomingSemiMajorAxis_ / outgoingSemiMajorAxis_ *\n                                 ( 1.0 - incomingEccentricity ) ) ) - bendingAngle_;\n}\n\n//! Compute first-derivative of the incoming eccentricity function.\ndouble EccentricityFindingFunctions::computeFirstDerivativeIncomingEccentricityFunction(\n        const double incomingEccentricity )\n{\n    const double eccentricitySquareMinusOne_ = incomingEccentricity * incomingEccentricity - 1.0;\n    const double semiMajorAxisRatio_ = incomingSemiMajorAxis_ / outgoingSemiMajorAxis_ ;\n    const double bParameter_ = 1.0 - semiMajorAxisRatio_ * ( 1.0 - incomingEccentricity );\n\n    return -1.0 / ( incomingEccentricity * std::sqrt( eccentricitySquareMinusOne_ ) ) -\n            semiMajorAxisRatio_ / ( bParameter_ * std::sqrt( bParameter_ * bParameter_ - 1.0 ) );\n}\n\n} // namespace mission_segments\n} // namespace tudat\n", "meta": {"hexsha": "f3627b5264a4fdf54f1a46ff59df6919b0ca228f", "size": 23023, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Tudat/Astrodynamics/MissionSegments/gravityAssist.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/MissionSegments/gravityAssist.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/MissionSegments/gravityAssist.cpp", "max_forks_repo_name": "ViktorJordanov/tudat", "max_forks_repo_head_hexsha": "069ceeab8f12405c356e19f50d6df037914df85c", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 53.6666666667, "max_line_length": 105, "alphanum_fraction": 0.6389262911, "num_tokens": 4696, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6584175005616829, "lm_q2_score": 0.5078118642792044, "lm_q1q2_score": 0.3343522184342823}}
{"text": "#include <vector>\n#include <map>\n#include <random>\n\n#include \"state_reconstructor_simple.h\"\n#include \"rate_model.h\"\n#include \"mcmc.h\"\n#include \"tree.h\"\n#include \"sequence.h\"\n#include \"seq_utils.h\"\n\n#include <armadillo>\nusing namespace arma;\n\nvoid sm0_mcmc(int reps, int sampleiter, Tree * tree, StateReconstructorSimple & sr,\n    RateModel & rm, vector<Sequence> & seqs, vector<Sequence> & sr_seqs,\n    map<string,vector<int> > & codon_pos, mat &bf, mat &K, mat &w, mat &inq) {\n    \n    int sites = (seqs[0].get_sequence().size()/3);\n    double curlike = 0;\n    double sw = 0.5;\n    rm.selection_model = 0;\n    for (int s=0; s < sites; s++) {\n        create_vector_seq_codon_state_reconstructor(seqs, sr_seqs, s, codon_pos);\n        sr.set_tip_conditionals(sr_seqs, s);\n        curlike +=  sr.eval_likelihood(s);\n        rm.set_sameQ(true);\n    }\n    cout << \"start likelihood: \" << curlike << endl;\n\n    std::default_random_engine re;\n    \n    double newlike = 0;\n    double startk = 1.0; //start\n    double startw = 1.0; //startw\n    for (int i=0; i < reps; i++) {\n        std::uniform_real_distribution<double> unif1(startk - sw, startk + sw);\n        std::uniform_real_distribution<double> unif2(startw - sw, startw + sw);\n        double newk = fabs(unif1(re));\n        double neww = fabs(unif2(re));\n        newlike = 0;\n        update_simple_goldman_yang_q(&inq, newk, neww, bf, K, w);\n        rm.setup_Q(inq);\n        sr.clear_map_ps();\n        for (int s=0; s < sites; s++) {\n            //create_vector_seq_codon_state_reconstructor(seqs,sr_seqs,s,codon_pos);\n            //sr.set_tip_conditionals(sr_seqs,s);\n            newlike +=  sr.eval_likelihood(s);\n            rm.set_sameQ(true);\n        }\n        if (newlike < curlike) {\n            curlike = newlike;\n            startk = newk;\n            startw = neww;\n        }\n        if (i%sampleiter == 0) {\n            cout << \"iter: \"<< i << \" like: \" << curlike << \" K: \"<< startk <<\" w: \" << startw << endl;\n        }\n    }\n}\n\n\n/**\n * this should have 5 parameters\n * K = free, w0 = 0,w1 = 1,w2 = free ,p0 = free ,p1 = free ,p2 = free\n */\nvoid sm2a_mcmc(int reps, int sampleiter, Tree * tree, StateReconstructorSimple & sr,\n    RateModel & rm, vector<Sequence> & seqs, vector<Sequence> & sr_seqs,\n    map<string,vector<int> > & codon_pos, mat &bf, mat &K, mat &w, mat & inq0,\n    mat & inq1, mat &inq2) {\n    \n    int sites = (seqs[0].get_sequence().size()/3);\n    double curlike = 0;\n    double sw = 0.2;\n    sr.pp0 = 0.38008; sr.pp1 = 0.28326; sr.pp2 = 0.33666;\n\n    for (int s=0; s < sites; s++) {\n        create_vector_seq_codon_state_reconstructor(seqs, sr_seqs, s, codon_pos);\n        sr.set_tip_conditionals(sr_seqs, s);\n        curlike +=  sr.eval_likelihood(s);\n        rm.set_sameQ(true);\n    }\n    cout << \"start likelihood: \" << curlike << endl;\n\n    std::default_random_engine re;\n    \n    double newlike = 0;\n    double startk = 1.36714; //start\n    double startw0 = 0.0; //start w0\n    double startw2 = 8.0; //start w2\n    double startp0 = 0.38008;\n    double startp1 = 0.28326;\n    double startp2 = 0.33666; //not free\n    for (int i=0; i < reps; i++) {\n        std::uniform_real_distribution<double> unif1(startk - sw, startk + sw);\n        std::uniform_real_distribution<double> unif2(startw0 - sw, startw0 + sw);\n        std::uniform_real_distribution<double> unif3(startw2 - sw, startw2 + sw);\n        std::uniform_real_distribution<double> unif4(startp0 - sw, startp0 + sw);\n        std::uniform_real_distribution<double> unif5(startp1 - sw, startp1 + sw);\n        std::uniform_real_distribution<double> unif6(startp2 - sw, startp2 + sw);\n\n        double newk = fabs(unif1(re));\n        double neww0 = fabs(unif2(re));\n        if (neww0 >= 1) {\n            neww0 = 1 - (neww0-1);\n        }\n        double neww2 = fabs(unif3(re));\n        double newp0 = fabs(unif4(re));\n        double newp1 = fabs(unif5(re));\n        double newp2 = fabs(unif6(re));\n\n        double sum1 = newp0 + newp1 + newp2;\n        newp0 = newp0/sum1; newp1 = newp1/sum1; newp2 = newp2/sum1;\n        sr.pp0 = newp0; sr.pp1 = newp1; sr.pp2 = newp2;\n\n        newlike = 0;\n        //only do it with \n        update_simple_goldman_yang_q(&inq0, newk, neww0, bf, K, w);\n        update_simple_goldman_yang_q(&inq2, newk, neww2, bf, K, w);\n        rm.set_Q_which(inq0, 0);\n        rm.set_Q_which(inq2, 2);\n        sr.clear_map_ps();\n        for (int s=0; s < sites; s++) {\n            //create_vector_seq_codon_state_reconstructor(seqs,sr_seqs,s,codon_pos);\n            //sr.set_tip_conditionals(sr_seqs,s);\n            newlike +=  sr.eval_likelihood(s);\n            rm.set_sameQ(true);\n        }\n        if (newlike < curlike) {\n            curlike = newlike;\n            startk = newk;\n            startw0 = neww0;\n            startw2 = neww2;\n            startp0 = newp0;\n            startp1 = newp1;\n            startp2 = newp2;\n        }\n        if (i % sampleiter == 0) {\n            cout << \"iter: \"<< i << \" like: \" << curlike << \" K: \"<< startk <<\" w0: \"\n            << startw0 << \" w2: \" << startw2 << \" p0: \" << startp0 << \" p1: \" << startp1\n            << \" p2: \"<< startp2 << endl;\n        }\n    }\n}\n", "meta": {"hexsha": "ae3924d78065ca003064b48e9eb31d3400626c47", "size": 5164, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/phyx-1.01/src/mcmc.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/mcmc.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/mcmc.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": 35.6137931034, "max_line_length": 103, "alphanum_fraction": 0.5695197521, "num_tokens": 1604, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6791787121629466, "lm_q2_score": 0.49218813572079556, "lm_q1q2_score": 0.3342837041607315}}
{"text": "#include <iostream>\n#include <vector>\n#include <string>\n#include <cmath>\n#include <fstream> \n#include <sstream>\n#include <boost/format.hpp>\n#include <algorithm>\n\nusing std::cin;\nusing std::cout;\nusing std::endl;\nusing std::vector;\nusing std::string;\nusing std::ifstream;\nusing std::istringstream;\nusing std::stod;\nusing std::stoi;\nusing std::pow;\nusing std::min;\n\nclass dp_matching\n{\n    public:\n        dp_matching() :\n            file_total_number_(100),\n            temp_file_top_num_(0),\n            unk_file_top_num_(0),\n            temp_file_num_store_(1),\n            frame_number_(15),\n            init_flag_(1),\n            min_file_search(1),\n            min_search_num(0),\n            min_file_result_(0),\n            correct_answer_rate_(0),\n            min_search_num_store_(0),\n            vec_one_dimensional_{1,1,1,1,1}\n        {\n            file_number_.emplace_back();\n            file_data_capture_.emplace_back();\n            template_data_.emplace_back();\n            unknown_data_.emplace_back();\n            local_distance_.emplace_back();\n            cumulative_distance_.emplace_back();\n            //word_distance_.emplace_back();\n            minimum_word_distance_.emplace_back();\n        }\n\n        void select_file_number()\n        {\n            cout << \"please select file top number\" << endl;\n            cout << \"menue: 11 12 21 22\" << endl;\n            \n            cin >> temp_file_top_num_ >> unk_file_top_num_;\n\n            cout << \"template_file: \" << temp_file_top_num_ << endl;\n            cout << \"unknown_file:  \" << unk_file_top_num_ << endl;\n            cout << endl << \"start DP_matching processing\" << endl;\n        }\n\n        void file_read(int& file_number_tmp, int& file_number_unk)\n        {\n            const std::string f_te_path = (boost::format(\"./city_mcepdata/city%03d/city%03d_%03d.txt\") %temp_file_top_num_ % temp_file_top_num_ % file_number_tmp).str();\n            const std::string f_un_path = (boost::format(\"./city_mcepdata/city%03d/city%03d_%03d.txt\") % unk_file_top_num_ % unk_file_top_num_ % file_number_unk).str();\n            ifstream f_te(f_te_path,std::ios::in);\n            ifstream f_un(f_un_path,std::ios::in);\n\n            string line,field;\n\n            while (getline(f_te, line)) \n            {\n                istringstream stream(line);\n\n                while (getline(stream, field, ' ') )\n                {\n                    template_data_[vec_one_dimensional_.at(0) - 1].push_back(field );\n                }\n\n                template_data_.resize(++vec_one_dimensional_.at(0) );\n            }\n            template_data_.resize(--vec_one_dimensional_.at(0) );\n\n            while (getline(f_un, line)) \n            {\n                istringstream stream(line);\n                while (getline(stream, field) )\n                {\n                    unknown_data_[vec_one_dimensional_.at(1) - 1].push_back(field );\n                }\n\n                unknown_data_.resize(++vec_one_dimensional_.at(1) );\n            }\n            unknown_data_.resize(--vec_one_dimensional_.at(1) );\n        }\n\n        void local_distance_calculation()\n        {\n            int double_flag = 0;\n            for (auto it_temp = template_data_.begin(); it_temp != template_data_.end(); ++it_temp) \n            {   \n                for (auto it_unk = unknown_data_.begin(); it_unk != unknown_data_.end(); ++it_unk) \n                {   \n                    int tuning_number_outside = 0;\n                    double accumulation = 0;\n                    for (auto it = (*it_temp).begin(); it != (*it_temp).end(); ++it) \n                    {\n                        int tuning_number_inside = 0;\n                        for (auto it_t = (*it_unk).begin(); it_t != (*it_unk).end(); ++it_t) \n                        {\n                            if(tuning_number_outside == tuning_number_inside)\n                            {\n                                double it_d = 0,it_t_d = 0;\n                                try \n                                {\n                                    it_d   = stod(*it);\n                                    it_t_d = stod(*it_t);\n                                    accumulation += pow(it_d - it_t_d,2);\n                                    if(it_d < 10 && it_t_d < 10) double_flag = 1;\n                                    else double_flag = 0;\n                                    ++tuning_number_inside;\n                                } \n                                catch (const std::invalid_argument& e) \n                                {\n                                    double_flag = 0;\n                                }\n                            }\n                            break;\n                        }\n                        ++tuning_number_outside;\n                    } \n                    if(double_flag) local_distance_[vec_one_dimensional_.at(2) - 1].push_back(accumulation);\n                }\n                if(double_flag) local_distance_.resize(++vec_one_dimensional_.at(2));\n            }\n            local_distance_.resize(--vec_one_dimensional_.at(2));  \n        }\n\n        void boundary_condition_calculation()\n        {\n            for (auto it_t = local_distance_.begin(); it_t != local_distance_.end(); ++it_t) \n            {\n                for (auto it = (*it_t).begin(); it != (*it_t).end(); ++it) \n                {\n                    cumulative_distance_[vec_one_dimensional_.at(3) - 1].push_back(*it);\n                } \n                cumulative_distance_.resize(++vec_one_dimensional_.at(3));\n            }\n            cumulative_distance_.resize(--vec_one_dimensional_.at(3));\n\n            for(int i = 1;i < stoi(template_data_[2][0]);i++)\n            {\n                cumulative_distance_.at(i).at(0) = cumulative_distance_.at(i - 1).at(0) + local_distance_.at(i).at(0); \n            }\n\n            for(int i = 1;i < stoi(unknown_data_[2][0]);i++)\n            {\n                cumulative_distance_.at(0).at(i) = cumulative_distance_.at(0).at(i - 1) + local_distance_.at(0).at(i);\n            }\n\n            for (int i = 1; i < stoi(template_data_[2][0]); ++i) \n            {\n                for (int j = 1; j < stoi(unknown_data_[2][0]); ++j) \n                {\n                    double vertical = cumulative_distance_[i][j - 1] + local_distance_[i][j];\n                    double diagonal = cumulative_distance_[i - 1][j - 1] + (1.4142 * local_distance_[i][j]);\n                    double side = cumulative_distance_[i - 1][j] + local_distance_[i][j];\n\n                    double min_num = min ({vertical, diagonal , side});\n\n                    if (vertical == min_num)\n                    {\n                        cumulative_distance_.at(i).at(j) = vertical;\n                    }\n\n                    if (diagonal == min_num)\n                    {\n                        cumulative_distance_.at(i).at(j) = diagonal;\n                    }\n\n                    if (side == min_num)\n                    {\n                        cumulative_distance_.at(i).at(j) = side;\n                    }\n                }\n            }\n\n            word_distance_.push_back(cumulative_distance_[stoi(template_data_[2][0]) - 1][stoi(unknown_data_[2][0]) - 1] / (stoi(template_data_[2][0]) + stoi(unknown_data_[2][0]) ) );    \n        }\n\n        void min_search()\n        {\n            for (auto it_t =  word_distance_.begin(); it_t !=  word_distance_.end(); ++it_t) \n            {\n                min_search_num =  *it_t;\n                if (init_flag_) min_search_num_store_ = min_search_num;\n                double min_num = min ({min_search_num_store_,min_search_num});\n                min_search_num_store_ = min_num;\n                if (min_search_num_store_ == min_search_num) min_file_result_ = min_file_search;\n                ++min_file_search;\n                init_flag_ = 0;\n            }\n        }\n\n        void correct_answer_rate(int& temp_file_num)\n        {\n            \n            if(temp_file_num == min_file_result_) ++correct_answer_rate_;\n            if(temp_file_num == file_total_number_)\n            {\n                correct_answer_rate_ = 100 * (correct_answer_rate_ / file_total_number_);\n                cout << endl << endl << \"正解率は\" << correct_answer_rate_ << \"%です。\" << endl;\n            }\n        }\n\n        void vector_memory_clear(int& temp_file_num)\n        {\n            file_number_.clear();\n            file_data_capture_.clear();\n            template_data_.clear();\n            unknown_data_.clear();\n            local_distance_.clear();\n            cumulative_distance_.clear();\n            if(temp_file_num != temp_file_num_store_) word_distance_.clear();\n\n            file_number_.emplace_back();\n            file_data_capture_.emplace_back();\n            template_data_.emplace_back();\n            unknown_data_.emplace_back();\n            local_distance_.emplace_back();\n            cumulative_distance_.emplace_back();\n            vec_one_dimensional_ = {1,1,1,1,1};\n\n            min_search_num_store_ = 0;\n            min_file_search = 1;\n            init_flag_ = 1;\n            min_search_num = 0;\n            min_file_result_ = 0;\n\n            temp_file_num_store_ = temp_file_num;\n        }\n\n        void progress_bar(int& temp_file_num)\n        {\n            cout << \"[\";\n            for(int j = 1;temp_file_num >= j;j++) cout << \"=\";    \n            cout << \">\";\n            for(int k = 1;file_total_number_ - temp_file_num >= k ;k++) cout << \" \";\n            cout << \"] \" << temp_file_num << \" %\\r\";\n                \n            cout.flush();\n        }\n\n        void run()\n        {\n            select_file_number();\n\n            for(int i = 1;i<= file_total_number_;i++)\n            {\n                for(int j = 1;j <= file_total_number_;j++)\n                {\n                    vector_memory_clear(i);\n                    file_read(i,j);\n                    local_distance_calculation();\n                    boundary_condition_calculation();\n                    min_search();\n                }\n\n                progress_bar(i);\n                correct_answer_rate(i);\n            }\n        }\n\n    private:\n        double file_total_number_;\n        int temp_file_top_num_;\n        int unk_file_top_num_;\n        int temp_file_num_store_;\n        int frame_number_;\n        int init_flag_;\n        int min_file_search;\n        double min_search_num;\n        int min_file_result_;\n        double correct_answer_rate_;\n        double min_search_num_store_;\n        vector<int> vec_one_dimensional_;\n        vector<int> file_number_;\n        vector<double> file_data_capture_;\n        vector<vector<string>> template_data_;\n        vector<vector<string>> unknown_data_;\n        vector<vector<double>> local_distance_;\n        vector<vector<double>> cumulative_distance_;\n        vector<double> word_distance_;\n        vector<double> minimum_word_distance_;\n};\n\nint main()\n{\n    dp_matching dp;\n    dp.run();\n\n    return 0;\n}\n", "meta": {"hexsha": "02dffcdca5a54f2d620df5102498a060348bb477", "size": 10918, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "dp_maching.cpp", "max_stars_repo_name": "uhobeike/dp_matching", "max_stars_repo_head_hexsha": "210d56b2ce5af3674156f553ddc8fbaee629ec20", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-05-20T11:51:11.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-20T11:51:11.000Z", "max_issues_repo_path": "dp_maching.cpp", "max_issues_repo_name": "uhobeike/dp_matching", "max_issues_repo_head_hexsha": "210d56b2ce5af3674156f553ddc8fbaee629ec20", "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": "dp_maching.cpp", "max_forks_repo_name": "uhobeike/dp_matching", "max_forks_repo_head_hexsha": "210d56b2ce5af3674156f553ddc8fbaee629ec20", "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.0330033003, "max_line_length": 187, "alphanum_fraction": 0.4961531416, "num_tokens": 2335, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.679178699175393, "lm_q2_score": 0.49218813572079556, "lm_q1q2_score": 0.3342836977684117}}
{"text": "/*\n * optimize_tnc.cpp\n *\n *  Created on: Feb 9, 2010\n *      Author: smitty\n */\n\n#include \"optimize_state_reconstructor_nlopt.h\"\n#include <iostream>\n#include <stdio.h>\n#include <nlopt.hpp>\n#include <math.h>\n\n#include \"state_reconstructor.h\"\n#include \"rate_model.h\"\n\n#include <armadillo>\nusing namespace arma;\n\n\nStateReconstructor * nloptsr;\nRateModel * nloptrm;\nmat * nloptfree_variables;\n\n//double nlopt_sr(int n, const double *x, void *state) {\n//double nlopt_sr(unsigned n, const double *x, double *grad, void *my_func_data);\ndouble nlopt_sr(unsigned n, const double *x, double *grad, void *my_func_data) {\n    for (unsigned int i=0; i < nloptfree_variables->n_rows; i++) {\n        for (unsigned int j=0; j < nloptfree_variables->n_cols; j++) {\n            if (i != j) {\n                nloptrm->set_Q_cell(i, j,x[int((*nloptfree_variables)(i, j))]);\n                if (nloptrm->get_Q()(i, j) < 0 || nloptrm->get_Q()(i, j) >= 1000) {\n                    return 1000000000000;\n                }\n            }\n        }\n    }\n    double like;\n    nloptrm->set_Q_diag();\n    like = nloptsr->eval_likelihood();\n    if (nloptrm->neg_p == true) {\n        like = 10000000000000;\n    }\n    //cout << like << endl;\n    if (like < 0 || like == std::numeric_limits<double>::infinity()) {\n        like = 10000000000000;\n    }\n    return like;\n}\n\nvoid optimize_sr_nlopt(RateModel * _rm,StateReconstructor * _sr, mat * _free_mask, int _nfree) {\n    nloptsr = _sr;\n    nloptrm = _rm;\n    nloptfree_variables = _free_mask;\n\n    nlopt::opt opt(nlopt::LN_NELDERMEAD, _nfree);\n    //nlopt::opt opt(nlopt::LN_BOBYQA, _nfree);\n    //nlopt::opt opt(nlopt::LN_PRAXIS, _nfree);\n    //nlopt::opt opt(nlopt::LN_SBPLX, _nfree);\n    //nlopt::opt opt(nlopt::LN_COBYLA, _nfree);\n    //nlopt::opt opt(nlopt::LN_NEWUOA, _nfree);\n\n    opt.set_lower_bounds(0.0000);\n    opt.set_upper_bounds(100000);\n    opt.set_min_objective(nlopt_sr, NULL);\n    opt.set_xtol_rel(0.001);\n    opt.set_maxeval(5000);\n\n    vector<double> x(_nfree,0);\n    for (unsigned int i=0; i < _rm->get_Q().n_rows; i++) {\n        for (unsigned int j=0; j < _rm->get_Q().n_cols; j++) {\n            if (i != j) {\n                x[int((*_free_mask)(i, j))] = _rm->get_Q()(i, j);\n                //cout << x[int((*_free_mask)(i, j))] << \" \";\n            }\n        }\n        //cout << endl;\n    }\n\n    //double minf;\n    vector<double> result = opt.optimize(x);\n    for (unsigned int i=0; i < _rm->get_Q().n_rows; i++) {\n        for (unsigned int j=0; j < _rm->get_Q().n_cols; j++) {\n            if (i != j) {\n                (*_free_mask)(i, j) = result[int((*_free_mask)(i, j))];\n                //cout << x[int((*_free_mask)(i, j))] << \" \";\n            }\n        }\n        //cout << endl;\n    }\n    //if ((&minf) < 0) {\n     //   printf(\"nlopt failed!\\n\");\n    //}\n    //else {\n    //    printf(\"found minimum at %0.10g\\n\", x[0], x[1], minf);\n    //}\n}\n\n\n\n", "meta": {"hexsha": "5caa67d9ddab4747f42ff614665dda67a4e0040b", "size": 2895, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/phyx-1.01/src/optimize_state_reconstructor_nlopt.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/optimize_state_reconstructor_nlopt.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/optimize_state_reconstructor_nlopt.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.6633663366, "max_line_length": 96, "alphanum_fraction": 0.5554404145, "num_tokens": 946, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.679178699175393, "lm_q2_score": 0.49218813572079556, "lm_q1q2_score": 0.3342836977684117}}
{"text": "#include <kr_tracker_msgs/TrackerStatus.h>\n#include <kr_trackers/lissajous_generator.h>\n\n#include <Eigen/Geometry>\n#include <cmath>\n#include <iostream>\n\nLissajousGenerator::LissajousGenerator()\n{\n  active_ = false;\n  goal_reached_ = false;\n  goal_set_ = false;\n}\n\nvoid LissajousGenerator::setParams(const kr_tracker_msgs::LissajousTrackerGoal::ConstPtr &msg)\n{\n  x_amp_ = msg->x_amp;\n  y_amp_ = msg->y_amp;\n  z_amp_ = msg->z_amp;\n  yaw_amp_ = msg->yaw_amp;\n  x_num_periods_ = msg->x_num_periods;\n  y_num_periods_ = msg->y_num_periods;\n  z_num_periods_ = msg->z_num_periods;\n  yaw_num_periods_ = msg->yaw_num_periods;\n  period_ = msg->period;\n  num_cycles_ = msg->num_cycles;\n  ramp_time_ = msg->ramp_time;\n\n  // Set goal stuff\n  total_s_ = period_ * num_cycles_;\n\n  // Compute a3_ and a2_\n  double tr = ramp_time_;\n  double tr2 = tr * tr;\n  double tr3 = tr2 * tr;\n  double tr4 = tr3 * tr;\n  double tr5 = tr4 * tr;\n  double tr6 = tr5 * tr;\n  double tr7 = tr6 * tr;\n  double tr8 = tr7 * tr;\n\n  a4_ = 35.0 / tr4;\n  a5_ = -84.0 / tr5;\n  a6_ = 70.0 / tr6;\n  a7_ = -20.0 / tr7;\n\n  // Compute ramp_s_, const_time_\n  ramp_s_ = a7_ * tr8 / 8.0 + a6_ * tr7 / 7.0 + a5_ * tr6 / 6.0 + a4_ * tr5 / 5.0;\n  const_time_ = total_s_ - 2.0 * ramp_s_;\n  total_time_ = 2.0 * ramp_time_ + const_time_;\n\n  // Set the start position and time\n  goal_set_ = true;\n  goal_reached_ = false;\n}\n\nvoid LissajousGenerator::setParams(const kr_tracker_msgs::LissajousAdderGoal::ConstPtr &msg, int num)\n{\n  x_amp_ = msg->x_amp[num];\n  y_amp_ = msg->y_amp[num];\n  z_amp_ = msg->z_amp[num];\n  yaw_amp_ = msg->yaw_amp[num];\n  x_num_periods_ = msg->x_num_periods[num];\n  y_num_periods_ = msg->y_num_periods[num];\n  z_num_periods_ = msg->z_num_periods[num];\n  yaw_num_periods_ = msg->yaw_num_periods[num];\n  period_ = msg->period[num];\n  num_cycles_ = msg->num_cycles[num];\n  ramp_time_ = msg->ramp_time[num];\n\n  // Set goal stuff\n  total_s_ = period_ * num_cycles_;\n\n  // Compute a3_ and a2_\n  double tr = ramp_time_;\n  double tr2 = tr * tr;\n  double tr3 = tr2 * tr;\n  double tr4 = tr3 * tr;\n  double tr5 = tr4 * tr;\n  double tr6 = tr5 * tr;\n  double tr7 = tr6 * tr;\n  double tr8 = tr7 * tr;\n\n  a4_ = 35.0 / tr4;\n  a5_ = -84.0 / tr5;\n  a6_ = 70.0 / tr6;\n  a7_ = -20.0 / tr7;\n\n  // Compute ramp_s_, const_time_\n  ramp_s_ = a7_ * tr8 / 8.0 + a6_ * tr7 / 7.0 + a5_ * tr6 / 6.0 + a4_ * tr5 / 5.0;\n  const_time_ = total_s_ - 2.0 * ramp_s_;\n  total_time_ = 2.0 * ramp_time_ + const_time_;\n\n  // Set the start position and time\n  goal_set_ = true;\n  goal_reached_ = false;\n}\n\nconst kr_mav_msgs::PositionCommand::Ptr LissajousGenerator::getPositionCmd(void)\n{\n  if(!active_)\n  {\n    return kr_mav_msgs::PositionCommand::Ptr();\n  }\n\n  // Set gains\n  kr_mav_msgs::PositionCommand::Ptr cmd(new kr_mav_msgs::PositionCommand);\n\n  // Get elapsed time\n  ros::Time current_time = ros::Time::now();\n  ros::Duration elapsed_time = current_time - start_time_;\n  double t = elapsed_time.toSec();\n  double t2 = t * t;\n  double t3 = t2 * t;\n  double t4 = t3 * t;\n  double t5 = t4 * t;\n  double t6 = t5 * t;\n  double t7 = t6 * t;\n  double t8 = t7 * t;\n  double s, sdot, sddot, sdddot;\n\n  Eigen::Vector3f pos, vel, acc, jrk;\n  double yaw, yaw_dot;\n  if(t > total_time_)\n  {\n    pos = Eigen::Vector3f::Zero();\n    yaw = 0;\n    cmd->position.x = pos(0), cmd->position.y = pos(1), cmd->position.z = pos(2);\n    cmd->velocity.x = 0, cmd->velocity.y = 0, cmd->velocity.z = 0;\n    cmd->acceleration.x = 0, cmd->acceleration.y = 0, cmd->acceleration.z = 0;\n    cmd->jerk.x = 0, cmd->jerk.y = 0, cmd->jerk.z = 0;\n    cmd->yaw = yaw;\n    cmd->yaw_dot = 0;\n    goal_set_ = false;\n    goal_reached_ = true;\n  }\n  else\n  {\n    if(t < ramp_time_)\n    {\n      s = a7_ * t8 / 8.0 + a6_ * t7 / 7.0 + a5_ * t6 / 6.0 + a4_ * t5 / 5.0;\n      sdot = a7_ * t7 + a6_ * t6 + a5_ * t5 + a4_ * t4;\n      sddot = 7.0 * a7_ * t6 + 6.0 * a6_ * t5 + 5.0 * a5_ * t4 + 4.0 * a4_ * t3;\n      sdddot = 42.0 * a7_ * t5 + 30.0 * a6_ * t4 + 20.0 * a5_ * t3 + 12.0 * a4_ * t2;\n    }\n    else if(t < total_time_ - ramp_time_)\n    {\n      s = ramp_s_ + t - ramp_time_;\n      sdot = 1;\n      sddot = 0;\n      sdddot = 0;\n    }\n    else\n    {\n      double te = total_time_ - t;\n      double te2 = te * te;\n      double te3 = te2 * te;\n      double te4 = te3 * te;\n      double te5 = te4 * te;\n      double te6 = te5 * te;\n      double te7 = te6 * te;\n      double te8 = te7 * te;\n\n      s = 2.0 * ramp_s_ + const_time_ - a7_ * te8 / 8.0 - a6_ * te7 / 7.0 - a5_ * te6 / 6.0 - a4_ * te5 / 5.0;\n      sdot = a7_ * te7 + a6_ * te6 + a5_ * te5 + a4_ * te4;\n      sddot = -7.0 * a7_ * te6 - 6.0 * a6_ * te5 - 5.0 * a5_ * te4 - 4.0 * a4_ * te3;\n      sdddot = 42.0 * a7_ * te5 + 30.0 * a6_ * te4 + 20.0 * a5_ * te3 + 12.0 * a4_ * te2;\n    }\n    double T = period_;\n    double T2 = T * T;\n    double T3 = T2 * T;\n    pos(0) = x_amp_ * (1 - std::cos(2 * M_PI * x_num_periods_ * s / T));\n    pos(1) = y_amp_ * std::sin(2 * M_PI * y_num_periods_ * s / T);\n    pos(2) = z_amp_ * std::sin(2 * M_PI * z_num_periods_ * s / T);\n    vel(0) = x_amp_ * 2 * M_PI * x_num_periods_ * std::sin(2 * M_PI * x_num_periods_ * s / T) * sdot / T;\n    vel(1) = y_amp_ * 2 * M_PI * y_num_periods_ * std::cos(2 * M_PI * y_num_periods_ * s / T) * sdot / T;\n    vel(2) = z_amp_ * 2 * M_PI * z_num_periods_ * std::cos(2 * M_PI * z_num_periods_ * s / T) * sdot / T;\n    acc(0) = x_amp_ * (4 * M_PI * M_PI * x_num_periods_ * x_num_periods_ * std::cos(2 * M_PI * x_num_periods_ * s / T) *\n                           sdot * sdot / T2 +\n                       2 * M_PI * x_num_periods_ * std::sin(2 * M_PI * x_num_periods_ * s / T) * sddot / T);\n    acc(1) = y_amp_ * (-4 * M_PI * M_PI * y_num_periods_ * y_num_periods_ *\n                           std::sin(2 * M_PI * y_num_periods_ * s / T) * sdot * sdot / T2 +\n                       2 * M_PI * y_num_periods_ * std::cos(2 * M_PI * y_num_periods_ * s / T) * sddot / T);\n    acc(2) = z_amp_ * (-4 * M_PI * M_PI * z_num_periods_ * z_num_periods_ *\n                           std::sin(2 * M_PI * z_num_periods_ * s / T) * sdot * sdot / T2 +\n                       2 * M_PI * z_num_periods_ * std::cos(2 * M_PI * z_num_periods_ * s / T) * sddot / T);\n    jrk(0) = x_amp_ * (-8 * M_PI * M_PI * M_PI * x_num_periods_ * x_num_periods_ * x_num_periods_ *\n                           std::sin(2 * M_PI * x_num_periods_ * s / T) * sdot * sdot * sdot / T3 +\n                       4 * M_PI * M_PI * x_num_periods_ * x_num_periods_ * std::cos(2 * M_PI * x_num_periods_ * s / T) *\n                           sdot * sddot / T2 +\n                       2 * M_PI * x_num_periods_ * std::sin(2 * M_PI * x_num_periods_ * s / T) * sdddot / T);\n    jrk(1) = y_amp_ * (-8 * M_PI * M_PI * M_PI * y_num_periods_ * y_num_periods_ * y_num_periods_ *\n                           std::cos(2 * M_PI * y_num_periods_ * s / T) * sdot * sdot * sdot / T3 -\n                       4 * M_PI * M_PI * y_num_periods_ * y_num_periods_ * std::sin(2 * M_PI * y_num_periods_ * s / T) *\n                           sdot * sddot / T2 +\n                       2 * M_PI * y_num_periods_ * std::cos(2 * M_PI * y_num_periods_ * s / T) * sdddot / T);\n    jrk(2) = z_amp_ * (-8 * M_PI * M_PI * M_PI * z_num_periods_ * z_num_periods_ * z_num_periods_ *\n                           std::cos(2 * M_PI * z_num_periods_ * s / T) * sdot * sdot * sdot / T3 -\n                       4 * M_PI * M_PI * z_num_periods_ * z_num_periods_ * std::sin(2 * M_PI * z_num_periods_ * s / T) *\n                           sdot * sddot / T2 +\n                       2 * M_PI * z_num_periods_ * std::cos(2 * M_PI * z_num_periods_ * s / T) * sdddot / T);\n    yaw = yaw_amp_ * (1 - std::cos(2 * M_PI * yaw_num_periods_ * s / T));\n    yaw_dot = yaw_amp_ * 2 * M_PI * yaw_num_periods_ * std::sin(2 * M_PI * yaw_num_periods_ * s / T) * sdot / T;\n    cmd->position.x = pos(0), cmd->position.y = pos(1), cmd->position.z = pos(2);\n    cmd->velocity.x = vel(0), cmd->velocity.y = vel(1), cmd->velocity.z = vel(2);\n    cmd->acceleration.x = acc(0), cmd->acceleration.y = acc(1), cmd->acceleration.z = acc(2);\n    cmd->jerk.x = jrk(0), cmd->jerk.y = jrk(1), cmd->jerk.z = jrk(2);\n    cmd->yaw = yaw;\n    cmd->yaw_dot = yaw_dot;\n  }\n  return cmd;\n}\n\nvoid LissajousGenerator::generatePath(nav_msgs::Path &path, geometry_msgs::Point &initial_pt, double dt)\n{\n  if(goal_set_)\n  {\n    double s = 0.0;\n    double T = period_;\n\n    while(s < period_)\n    {\n      geometry_msgs::PoseStamped ps;\n      ps.pose.position.x = x_amp_ * (1 - std::cos(2 * M_PI * x_num_periods_ * s / T)) + initial_pt.x;\n      ps.pose.position.y = y_amp_ * std::sin(2 * M_PI * y_num_periods_ * s / T) + initial_pt.y;\n      ps.pose.position.z = z_amp_ * std::sin(2 * M_PI * z_num_periods_ * s / T) + initial_pt.z;\n\n      path.poses.push_back(ps);\n      s += dt;  // increment by 0.1s\n    }\n  }\n}\n\nbool LissajousGenerator::activate(void)\n{\n  if(goal_set_)\n  {\n    active_ = true;\n    start_time_ = ros::Time::now();\n  }\n  return active_;\n}\n\nvoid LissajousGenerator::deactivate(void)\n{\n  goal_set_ = false;\n  active_ = false;\n}\n\nbool LissajousGenerator::isActive(void)\n{\n  return active_;\n}\n\nbool LissajousGenerator::goalIsSet(void)\n{\n  return goal_set_;\n}\n\nbool LissajousGenerator::status() const\n{\n  return goal_reached_ ? kr_tracker_msgs::TrackerStatus::SUCCEEDED : kr_tracker_msgs::TrackerStatus::ACTIVE;\n}\n\nfloat LissajousGenerator::timeRemaining(void)\n{\n  ros::Time t_now = ros::Time::now();\n  float time_elapsed = (t_now - start_time_).toSec();\n  return total_time_ - time_elapsed;\n}\n\nfloat LissajousGenerator::timeElapsed(void)\n{\n  ros::Time t_now = ros::Time::now();\n  return (t_now - start_time_).toSec();\n}\n", "meta": {"hexsha": "070721af331c333badbbaa649b1abfa1924bc244", "size": 9605, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "trackers/kr_trackers/src/lissajous_generator.cpp", "max_stars_repo_name": "fcladera/kr_mav_control", "max_stars_repo_head_hexsha": "3e4a80f9af469df59628537876fb4e9a8f2fcd14", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 29.0, "max_stars_repo_stars_event_min_datetime": "2021-02-08T17:04:13.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T10:43:50.000Z", "max_issues_repo_path": "trackers/kr_trackers/src/lissajous_generator.cpp", "max_issues_repo_name": "fcladera/kr_mav_control", "max_issues_repo_head_hexsha": "3e4a80f9af469df59628537876fb4e9a8f2fcd14", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2021-02-08T20:28:40.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-29T16:51:24.000Z", "max_forks_repo_path": "trackers/kr_trackers/src/lissajous_generator.cpp", "max_forks_repo_name": "fcladera/kr_mav_control", "max_forks_repo_head_hexsha": "3e4a80f9af469df59628537876fb4e9a8f2fcd14", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 16.0, "max_forks_repo_forks_event_min_datetime": "2021-02-10T09:38:10.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-30T15:55:59.000Z", "avg_line_length": 34.6750902527, "max_line_length": 120, "alphanum_fraction": 0.5815720979, "num_tokens": 3498, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6113819732941511, "lm_q2_score": 0.5467381519846138, "lm_q1q2_score": 0.3342658502355507}}
{"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\n\n#include <votca/xtp/gwbse.h>\n\n#include <boost/format.hpp>\n#include <boost/numeric/ublas/operation.hpp>\n#include <boost/math/constants/constants.hpp>\n#include <boost/numeric/ublas/symmetric.hpp>\n#include <votca/tools/constants.h>\n\n//#include \"mathimf.h\"\n\nusing boost::format;\nusing namespace boost::filesystem;\n\nnamespace votca {\n    namespace xtp {\n        namespace ub = boost::numeric::ublas;\n\n        // +++++++++++++++++++++++++++++ //\n        // MBPT MEMBER FUNCTIONS         //\n        // +++++++++++++++++++++++++++++ //\n\n        \n        \n\n        void GWBSE::FullQPHamiltonian(){\n            \n            // constructing full QP Hamiltonian, storage in vxc\n            _vxc = -_vxc + _sigma_x + _sigma_c;\n            // diagonal elements are given by _qp_energies\n            for (unsigned _m = 0; _m < _vxc.size1(); _m++ ){\n              _vxc( _m,_m ) = _qp_energies( _m + _qpmin );\n            }\n\n             // sigma matrices can be freed\n            _sigma_x.resize(0);\n            _sigma_c.resize(0);\n            \n            \n            \n            if ( _do_qp_diag ){\n                _qp_diag_energies.resize(_vxc.size1());\n                _qp_diag_coefficients.resize(_vxc.size1(), _vxc.size1());\n                linalg_eigenvalues(_vxc, _qp_diag_energies, _qp_diag_coefficients);\n            }\n           return; \n        }\n        \n        \n        void GWBSE::sigma_diag(const TCMatrix& _Mmn){\n            \n            unsigned _levelsum = _Mmn[0].size2(); // total number of bands\n            unsigned _gwsize = _Mmn[0].size1(); // size of the GW basis\n            const double pi = boost::math::constants::pi<double>();\n\n            \n             #pragma omp parallel for\n                for (unsigned _gw_level = 0; _gw_level < _qptotal; _gw_level++) {\n                    const ub::matrix<real_gwbse>& Mmn = _Mmn[ _gw_level + _qpmin ];\n                    double sigma_x=0;\n                        for ( unsigned _i_gw = 0 ; _i_gw < _gwsize ; _i_gw++ ){\n                            // loop over all occupied bands used in screening\n                            for ( unsigned _i_occ = 0 ; _i_occ <= _homo ; _i_occ++ ){\n                                sigma_x-= Mmn( _i_gw , _i_occ ) * Mmn( _i_gw , _i_occ );\n                            } // occupied bands\n                        } // gwbasis functions             \n                    _sigma_x(_gw_level,_gw_level)=( 1.0 - _ScaHFX ) * sigma_x; \n                }\n            \n                if(_g_sc_max_iterations==0) {_g_sc_max_iterations=1;}\n                ub::vector<double>& dftenergies=_orbitals->MOEnergies();\n                // initial _qp_energies are dft energies\n                ub::vector<double>_qp_old=_qp_energies;\n\n                bool energies_converged=false;\n\n            \n\t    // only diagonal elements except for in final iteration\n            for (unsigned _g_iter = 0; _g_iter < _g_sc_max_iterations; _g_iter++) {\n                // loop over all GW levels\n\n                #pragma omp parallel for\n                for (unsigned _gw_level = 0; _gw_level < _qptotal; _gw_level++) {\n                    const ub::matrix<real_gwbse>& Mmn = _Mmn[ _gw_level + _qpmin ];\n                    const double qpmin = _qp_old(_gw_level + _qpmin);\n                    \n                    double sigma_c=0.0;\n                    \n                    // loop over all functions in GW basis\n                    for (unsigned _i_gw = 0; _i_gw < _gwsize; _i_gw++) {\n                        // the ppm_weights smaller 1.e-5 are set to zero in rpa.cc PPM_construct_parameters\n                        if (_ppm_weight(_i_gw) < 1.e-9) { continue;}\n                        const double ppm_freq = _ppm_freq(_i_gw);\n                        const double fac = _ppm_weight(_i_gw) * ppm_freq;\n                        // loop over all bands\n                        for (unsigned _i = 0; _i < _levelsum; _i++) {\n\n                            double occ = 1.0;\n                            if (_i > _homo) occ = -1.0; // sign for empty levels\n\n                            // energy denominator\n                            const double _denom = qpmin - _qp_old(_i) + occ*ppm_freq;\n\n                            double _stab = 1.0;\n                            if (std::abs(_denom) < 0.25) {\n                                 \n                                _stab = 0.5 * (1.0 - std::cos(4.0 * pi * std::abs(_denom)));\n                               \n                            }\n                            \n                            const double _factor =0.5* fac * _stab / _denom; //Hartree\n\n                            // sigma_c diagonal elements\n                            sigma_c += _factor * Mmn(_i_gw, _i) * Mmn(_i_gw, _i);\n                           \n                        }// bands\n\n                    }// GW functions\n                    _sigma_c(_gw_level, _gw_level)=sigma_c;\n                    // update _qp_energies\n                   \n                    _qp_energies(_gw_level + _qpmin) = dftenergies(_gw_level + _qpmin) + sigma_c + _sigma_x(_gw_level, _gw_level) - _vxc(_gw_level, _gw_level);\n\n                }// all bands\n                ub::vector<double> diff= _qp_old - _qp_energies;\n                energies_converged = true;\n                double diff_max=0;\n                unsigned state_max=0;\n                for (unsigned l = 0; l < diff.size(); l++) {\n                    if(std::abs(diff(l))>std::abs(diff_max)){\n                            diff_max=diff(l);\n                            state_max=l;\n                    }\n                    if (std::abs(diff(l))>_g_sc_limit) {\n                        energies_converged = false;   \n                    }\n                }\n                if(tools::globals::verbose){\n                    double _DFTgap =dftenergies(_homo + 1) - dftenergies(_homo);\n                    double _QPgap = _qp_energies( _homo +1 ) - _qp_energies( _homo  );\n                    CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp() << \" QP_Iteration: \" << _g_iter+1 <<\" shift=\"<<_QPgap - _DFTgap <<\" E_diff max=\"<<diff_max<<\" StateNo:\"<<state_max << flush;\n                }\n                double alpha=0.0;\n                _qp_energies=(1-alpha)*_qp_energies+alpha*_qp_old;\n                \n                if (energies_converged) {\n                    CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp() << \" Converged after \" << _g_iter+1 << \" G iterations.\" << flush;\n                    break;\n                }else if(_g_iter==_g_sc_max_iterations-1){\n                        CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp() << \" G-self-consistency cycle not converged after \" << _g_sc_max_iterations << \" iterations.\" << flush;  \n                        break;\n                    \n                } else {\n                    _qp_old = _qp_energies;\n                }\n\n            } // iterations\n\n            return;\n        }\n\n      \n       \n         void GWBSE::sigma_offdiag(const TCMatrix& _Mmn) {\n            unsigned _levelsum = _Mmn[0].size2(); // total number of bands\n            unsigned _gwsize = _Mmn[0].size1(); // size of the GW basis\n            const double pi = boost::math::constants::pi<double>();\n           \n            #pragma omp parallel for\n            for (unsigned _gw_level1 = 0; _gw_level1 < _qptotal; _gw_level1++) {\n                const ub::matrix<real_gwbse>& Mmn1 =  _Mmn[ _gw_level1 + _qpmin ];\n                for (unsigned _gw_level2 = 0; _gw_level2 < _gw_level1; _gw_level2++) {\n                    const ub::matrix<real_gwbse>& Mmn2 =  _Mmn[ _gw_level2 + _qpmin ];\n                    double sigma_x=0;\n                    for ( unsigned _i_gw = 0 ; _i_gw < _gwsize ; _i_gw++ ){\n                        // loop over all occupied bands used in screening\n                        for ( unsigned _i_occ = 0 ; _i_occ <= _homo ; _i_occ++ ){\n                            sigma_x -= Mmn1( _i_gw , _i_occ ) * Mmn2( _i_gw , _i_occ );\n                        } // occupied bands\n                    } // gwbasis functions\n                    _sigma_x(_gw_level1, _gw_level2)=( 1.0 - _ScaHFX ) * sigma_x;\n                }\n            }\n            \n            #pragma omp parallel for\n            for (unsigned _gw_level1 = 0; _gw_level1 < _qptotal; _gw_level1++) {\n                const double qpmin1 = _qp_energies(_gw_level1 + _qpmin);\n                const ub::matrix<real_gwbse>& Mmn1 = _Mmn[ _gw_level1 + _qpmin ];\n                for (unsigned _gw_level2 = 0; _gw_level2 < _gw_level1; _gw_level2++) {\n                    const double qpmin2 = _qp_energies(_gw_level1 + _qpmin);\n                    const ub::matrix<real_gwbse>& Mmn2 = _Mmn[ _gw_level2 + _qpmin ];\n                    double sigma_c = 0;\n                    for (unsigned _i_gw = 0; _i_gw < _gwsize; _i_gw++) {\n                        // the ppm_weights smaller 1.e-5 are set to zero in rpa.cc PPM_construct_parameters\n                        if (_ppm_weight(_i_gw) < 1.e-9) {\n                            continue;\n                        }\n                        const double ppm_freq = _ppm_freq(_i_gw);\n                        const double fac = _ppm_weight(_i_gw) * ppm_freq;\n                        // loop over all screening levels\n                        for (unsigned _i = 0; _i < _levelsum; _i++) {\n\n                            double occ = 1.0;\n                            if (_i > _homo) occ = -1.0; // sign for empty levels\n\n                            // energy denominator\n                            const double _denom1 = qpmin1 - _qp_energies(_i) + occ * ppm_freq;\n                            const double _denom2 = qpmin2 - _qp_energies(_i) + occ * ppm_freq;\n\n                            double _stab1 = 1.0;\n                            if (std::abs(_denom1) < 0.25) {\n                                _stab1 = 0.5 * (1.0 - std::cos(4.0 * pi * std::abs(_denom1)));\n                            }\n                            const double factor1 = 0.5 * fac * _stab1 / _denom1; //Hartree\n                            double _stab2 = 1.0;\n                            if (std::abs(_denom2) < 0.25) {\n                                _stab2 = 0.5 * (1.0 - std::cos(4.0 * pi * std::abs(_denom2)));\n                            }\n                            const double factor2 = 0.5 * fac * _stab2 / _denom2; //Hartree\n                            sigma_c +=Mmn1(_i_gw, _i) * Mmn2(_i_gw, _i)*0.5*(factor1+factor2);\n                        }// screening levels \n                    }// GW functions \n\n                    _sigma_c(_gw_level1, _gw_level2) = sigma_c;\n\n\n                }// GW row             \n            }//GW col\n         \n        return;\n        } \n\n\n        void GWBSE::sigma_prepare_threecenters(TCMatrix& _Mmn){\n            #if (GWBSE_DOUBLE)\n                const ub::matrix<double>& ppm_phi=_ppm_phi;\n            #else\n                const ub::matrix<float> ppm_phi=_ppm_phi;        \n            #endif\n            \n            \n            #pragma omp parallel for\n            for ( int _m_level = 0 ; _m_level < _Mmn.get_mtot(); _m_level++ ){\n                // get Mmn for this _m_level\n                // and multiply with _ppm_phi = eigenvectors of epsilon\n              _Mmn[ _m_level ] = ub::prod(  ppm_phi , _Mmn[_m_level] );\n            }\n            return;\n        }        \n        \n\n\n    }\n    \n \n};\n", "meta": {"hexsha": "4913a3dc3409c4d7da6e43429d7b82207aadb677", "size": 11986, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/libxtp/gwbse/gwa.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/gwa.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/gwa.cc", "max_forks_repo_name": "choudarykvsp/xtp", "max_forks_repo_head_hexsha": "9a249fd34615abcf790d5f0ecd3ddf1ed0ac0e7a", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 43.2707581227, "max_line_length": 195, "alphanum_fraction": 0.4690472218, "num_tokens": 2974, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7310585786300049, "lm_q2_score": 0.4571367168274948, "lm_q1q2_score": 0.3341937184434954}}
{"text": "#include <complex>\n#include <memory>\n#include <fftw3.h>\n#include <armadillo>\nusing namespace std;\nusing namespace arma;\n\n#ifndef __DEFT_HPP__\n#define __DEFT_HPP__\n\nclass deft{\n\npublic:\n\n    // constructors\n    deft(const size_t, const size_t, const size_t, const double*, const double*, const double*);\n    deft(const deft&);\n\n    // read data\n    double at(const size_t, const size_t, const size_t) const;\n    double operator()(const size_t, const size_t, const size_t) const;\n\n    // copy data\n    void copy_data_from(const double*);\n\n    // assignment\n    void equals(const double);\n    void operator=(const double);\n    void equals(const deft);\n    void operator=(const deft);\n\n    // addition\n    void addEquals(const double);\n    void operator+=(const double);\n    void addEquals(const deft);\n    void operator+=(const deft);\n\n    // subtraction\n    void subtractEquals(const double);\n    void operator-=(const double);\n    void subtractEquals(const deft);\n    void operator-=(const deft);\n    // multiplication\n    void multiplyEquals(const double);\n    void operator*=(const double);\n    void multiplyEquals(const deft);\n    void operator*=(const deft);\n\n    // division\n    void divideEquals(const double);\n    void operator/=(const double);\n    void divideEquals(const deft);\n    void operator/=(const deft);\n\n    // elementwise math\n    void pow(const double);\n\n    // fourier transform operations\n    void computeFT();\n    void computeIFT();\n\n    // derivatives (using fourier transforms)\n    void compute_gradient_x();\n    void compute_gradient_y();\n    void compute_gradient_z();\n    void compute_gradient_squared();\n    void compute_laplacian();\n\n    // integrate\n    double integrate() const;\n\n    // update cell geometry and reciprocal lattice vectors\n    void updateGeometry(const double*, const double*, const double*);\n\n    // read cell information\n    double cellVecX(const size_t) const;\n    double cellVecY(const size_t) const;\n    double cellVecZ(const size_t) const;\n    double cellLenX() const;\n    double cellLenY() const;\n    double cellLenZ() const;\n    double vol() const;\n    double dv() const;\n    double kVecX(const size_t) const;\n    double kVecX(const size_t, const size_t, const size_t) const;\n    double kVecY(const size_t) const;\n    double kVecY(const size_t, const size_t, const size_t) const;\n    double kVecZ(const size_t) const;\n    double kVecZ(const size_t, const size_t, const size_t) const;\n    double kVecLen(const size_t) const;\n    double kVecLen(const size_t, const size_t, const size_t) const;\n\n    // interpolate\n    deft* interpolate(const size_t new_x, const size_t new_y, const size_t new_z);\n\n    // sum a function over a lattice\n    void sum_over_lattice(mat loc, double (*func)(double));\n\nprivate:\npublic:\n\n    // real-space dimensions and data\n    const size_t _xDim;\n    const size_t _yDim;\n    const size_t _zDim;\n    const size_t _dimXYZ;\n    // TODO: decide whether this should remain a pointer\n    cube* _data;\n\nprivate:\n\n    // cell geometry\n    shared_ptr<vec> _cellVecX;\n    shared_ptr<vec> _cellVecY;\n    shared_ptr<vec> _cellVecZ;\n    shared_ptr<double> _cellLenX;\n    shared_ptr<double> _cellLenY;\n    shared_ptr<double> _cellLenZ;\n    shared_ptr<double> _vol;\n    shared_ptr<double> _dv;\n\npublic:\n\n    // fourier-space dimensions and data\n    const size_t _xDimFT;\n    const size_t _yDimFT;\n    const size_t _zDimFT;\n    // TODO: add ft_numXYZ\n    cx_cube* _dataFT;\n\nprivate:\n\n    // reciprocal lattice vectors\n    shared_ptr<cube> _kVecX;\n    shared_ptr<cube> _kVecY;\n    shared_ptr<cube> _kVecZ;\n    shared_ptr<cube> _kVecLen;\n\n    // fftw info\n    fftw_plan _planR2C;\n    fftw_plan _planC2R;\n\n};\n\n\n\n#endif  //  __DEFT_HPP__\n\n", "meta": {"hexsha": "38297392a7a425ce30c9f84d2907be6c2f111bbd", "size": 3700, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/deft.hpp", "max_stars_repo_name": "EACcodes/deft", "max_stars_repo_head_hexsha": "e9a7294e54e1a72152be4c36ef11178dbc7e1887", "max_stars_repo_licenses": ["BSD-3-Clause"], "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/deft.hpp", "max_issues_repo_name": "EACcodes/deft", "max_issues_repo_head_hexsha": "e9a7294e54e1a72152be4c36ef11178dbc7e1887", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/deft.hpp", "max_forks_repo_name": "EACcodes/deft", "max_forks_repo_head_hexsha": "e9a7294e54e1a72152be4c36ef11178dbc7e1887", "max_forks_repo_licenses": ["BSD-3-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.8322147651, "max_line_length": 96, "alphanum_fraction": 0.6881081081, "num_tokens": 949, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7371581626286833, "lm_q2_score": 0.45326184801538616, "lm_q1q2_score": 0.3341256710727036}}
{"text": "/*\nPart of the Fluid Corpus Manipulation Project (http://www.flucoma.org/)\nCopyright 2017-2019 University of Huddersfield.\nLicensed under the BSD-3 License.\nSee license.md file in the project root for full license information.\nThis project has received funding from the European Research Council (ERC)\nunder the European Union’s Horizon 2020 research and innovation programme\n(grant agreement No 725899).\n*/\n\n#pragma once\n\n#include \"../util/FluidEigenMappings.hpp\"\n#include \"../../data/FluidDataSet.hpp\"\n#include \"../../data/FluidIndex.hpp\"\n#include \"../../data/FluidTensor.hpp\"\n#include \"../../data/TensorTypes.hpp\"\n#include <Eigen/Core>\n#include <queue>\n#include <memory>\n#include <string>\n\nnamespace fluid {\nnamespace algorithm {\n\nclass KDTree\n{\n\npublic:\n  using string = std::string;\n\n  using DataSet = FluidDataSet<string, double, 1>;\n  using ConstRealVectorView = FluidTensorView<const double, 1>;\n  struct Node;\n  using NodePtr = std::shared_ptr<Node>;\n  using knnCandidate = std::pair<double, const Node*>;\n  using knnQueue = std::priority_queue<knnCandidate, std::vector<knnCandidate>,\n                                       std::less<knnCandidate>>;\n  using iterator = const std::vector<index>::iterator;\n\n  struct Node\n  {\n    const string     id;\n    const RealVector data;\n    NodePtr          left{nullptr}, right{nullptr};\n  };\n\n  struct FlatData\n  {\n    FluidTensor<index, 2>  tree;\n    FluidTensor<string, 1> ids;\n    FluidTensor<double, 2> data;\n    FlatData(index n, index m) : tree(n, 2), ids(n), data(n, m) {}\n  };\n\n  explicit KDTree() = default;\n  ~KDTree() = default;\n\n  KDTree(const DataSet& dataset)\n  {\n    using namespace std;\n    mNPoints = dataset.size();\n    mDims = dataset.pointSize();\n    if (mDims > 0 && mNPoints > 0)\n    {\n      vector<index> indices(asUnsigned(dataset.size()));\n      iota(indices.begin(), indices.end(), 0);\n      mRoot = buildTree(indices, indices.begin(), indices.end(), dataset, 0);\n    }\n    mInitialized = true;\n  }\n\n  void addNode(string id, ConstRealVectorView data)\n  {\n    mRoot = addNode(mRoot.get(), id, data, 0);\n    mNPoints++;\n  }\n\n  DataSet kNearest(ConstRealVectorView data, index k = 1,\n                   double radius = 0) const\n  {\n    assert(data.size() == mDims);\n    knnQueue queue;\n    auto     result = DataSet(1);\n    kNearest(mRoot.get(), data, queue, k, radius, 0);\n    index                     numFound = asSigned(queue.size());\n    std::vector<knnCandidate> sorted(asUnsigned(numFound));\n    for (index i = numFound - 1; i >= 0; i--)\n    {\n      sorted[asUnsigned(i)] = queue.top();\n      queue.pop();\n    }\n    for (index i = 0; i < numFound; i++)\n    {\n      auto dist = FluidTensor<double, 1>{sorted[asUnsigned(i)].first};\n      auto id = sorted[asUnsigned(i)].second->id;\n      result.add(id, dist);\n    }\n    return result;\n  }\n\n  void  print() const { print(mRoot.get(), 0); }\n  index dims() const { return mDims; }\n  index size() const { return mNPoints; }\n  bool  initialized() const { return mInitialized; }\n\n  void clear()\n  {\n    mRoot = nullptr;\n    mInitialized = false;\n  }\n\n  FlatData toFlat() const\n  {\n    FlatData store(mNPoints, mDims);\n    flatten(0, mRoot.get(), store);\n    return store;\n  }\n\n  void fromFlat(FlatData vectors)\n  {\n    mRoot = unflatten(vectors, 0);\n    mNPoints = vectors.data.rows();\n    mDims = vectors.data.cols();\n    mInitialized = true;\n  }\n\nprivate:\n  NodePtr buildTree(std::vector<index>& indices, iterator from, iterator to,\n                    const DataSet& dataset, index depth) const\n  {\n    using namespace std;\n    if (from == to)\n      return nullptr;\n    else if (std::distance(from, to) == 1)\n    {\n      return makeNode(dataset.getIds()(*from), dataset.getData().row(*from));\n    }\n    const index d = depth % mDims;\n    sort(from, to, [&](index a, index b) {\n      return dataset.getData().row(a)(d) < dataset.getData().row(b)(d);\n    });\n    const index range = std::distance(from, to);\n    const index median = range / 2;\n    NodePtr     current = makeNode(dataset.getIds().row(*(from + median)),\n                               dataset.getData().row(*(from + median)));\n    if (median > 0)\n      current->left =\n          buildTree(indices, from, from + median, dataset, depth + 1);\n    if (range - median > 1)\n      current->right =\n          buildTree(indices, from + median + 1, to, dataset, depth + 1);\n    return current;\n  }\n\n  NodePtr makeNode(string id, ConstRealVectorView data) const\n  {\n    return std::make_shared<Node>(Node{id, RealVector{data}, nullptr, nullptr});\n  }\n\n  NodePtr addNode(Node* current, string id, ConstRealVectorView data,\n                  const index depth) const\n  {\n    if (current == nullptr) { return makeNode(id, data); }\n\n    const index d = depth % mDims;\n    if (data(d) < current->data(d))\n    { current->left = addNode(current->left.get(), id, data, depth + 1); }\n    else\n    {\n      current->right = addNode(current->right.get(), id, data, depth + 1);\n    }\n    return NodePtr(current);\n  }\n\n  double distance(ConstRealVectorView p1, ConstRealVectorView p2) const\n  {\n    using namespace Eigen;\n    auto v1 = _impl::asEigen<Array>(p1);\n    auto v2 = _impl::asEigen<Array>(p2);\n    return (v1 - v2).matrix().norm();\n  }\n\n  void print(Node* current, index depth) const\n  {\n    for (index i = 0; i < depth; ++i) std::cout << \"  \";\n    if (current == nullptr)\n    {\n      std::cout << \" null\" << std::endl;\n      return;\n    }\n    std::cout << \" \" << current->id << std::endl;\n    for (index i = 0; i < depth; ++i) std::cout << \"  \";\n    std::cout << \" left\" << std::endl;\n    print(current->left.get(), depth + 1);\n    for (index i = 0; i < depth; ++i) std::cout << \"  \";\n    std::cout << \" right\" << std::endl;\n    print(current->right.get(), depth + 1);\n  }\n\n  void kNearest(const Node* current, ConstRealVectorView data, knnQueue& knn,\n                index k, double radius, index depth) const\n  {\n    if (current == nullptr) return;\n    const double currentDist = distance(current->data, data);\n    bool         withinRadius = radius > 0 ? currentDist < radius : true;\n    if (withinRadius && (knn.size() < asUnsigned(k) || k == 0))\n    { knn.push(std::make_pair(currentDist, current)); }\n    else if (withinRadius && currentDist < knn.top().first)\n    {\n      knn.pop();\n      knn.push(std::make_pair(currentDist, current));\n    }\n    const index  d = depth % mDims;\n    const double dimDif = current->data(d) - data(d);\n    Node*        firstBranch = current->left.get();\n    Node*        secondBranch = current->right.get();\n    if (dimDif <= 0)\n    {\n      firstBranch = current->right.get();\n      secondBranch = current->left.get();\n    }\n    kNearest(firstBranch, data, knn, k, radius, depth + 1);\n    if (k == 0 || knn.size() < asUnsigned(k) ||\n        dimDif < knn.top().first) // ball centered at query with diametre\n                                  // kthDist intersects with current partition\n                                  // (or need to get more neighbors)\n    { kNearest(secondBranch, data, knn, k, radius, depth + 1); }\n  }\n\n  index flatten(index nodeId, const Node* current, FlatData& store) const\n  {\n    if (current == nullptr) { return nodeId; }\n    store.ids(nodeId) = current->id;\n    store.data.row(nodeId) = current->data;\n\n    index nextNodeId = nodeId + 1;\n    if (current->left == nullptr) { store.tree(nodeId, 0) = -1; }\n    else\n    {\n      store.tree(nodeId, 0) = nextNodeId;\n      nextNodeId = flatten(nextNodeId, current->left.get(), store);\n    }\n    if (current->right == nullptr) { store.tree(nodeId, 1) = -1; }\n    else\n    {\n      store.tree(nodeId, 1) = nextNodeId;\n      nextNodeId = flatten(nextNodeId, current->right.get(), store);\n    }\n    return nextNodeId;\n  }\n\n  NodePtr unflatten(const FlatData& store, index index) const\n  {\n    if (index == -1) return nullptr;\n    NodePtr current = makeNode(store.ids[index], store.data[index]);\n    current->left = unflatten(store, store.tree(index, 0));\n    current->right = unflatten(store, store.tree(index, 1));\n    return current;\n  }\n\n  NodePtr mRoot{nullptr};\n  index   mDims;\n  index   mNPoints{0};\n  bool    mInitialized{false};\n};\n} // namespace algorithm\n} // namespace fluid\n", "meta": {"hexsha": "0b452cb7ca9637a4d58e4267686f693a8e3e9359", "size": 8169, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/algorithms/public/KDTree.hpp", "max_stars_repo_name": "chriskiefer/flucoma-core", "max_stars_repo_head_hexsha": "81efe4fe2ad812af5a99adc8aa6013d1da23b297", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 32.0, "max_stars_repo_stars_event_min_datetime": "2020-05-11T15:42:53.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-16T01:51:36.000Z", "max_issues_repo_path": "include/algorithms/public/KDTree.hpp", "max_issues_repo_name": "chriskiefer/flucoma-core", "max_issues_repo_head_hexsha": "81efe4fe2ad812af5a99adc8aa6013d1da23b297", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 90.0, "max_issues_repo_issues_event_min_datetime": "2020-05-13T20:25:43.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-29T18:05:35.000Z", "max_forks_repo_path": "include/algorithms/public/KDTree.hpp", "max_forks_repo_name": "chriskiefer/flucoma-core", "max_forks_repo_head_hexsha": "81efe4fe2ad812af5a99adc8aa6013d1da23b297", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2020-05-11T15:15:27.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-15T12:15:36.000Z", "avg_line_length": 30.3680297398, "max_line_length": 80, "alphanum_fraction": 0.6081527727, "num_tokens": 2201, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7185943925708562, "lm_q2_score": 0.46490157137338844, "lm_q1q2_score": 0.33407566228629665}}
{"text": "//\n// Created by Zhongshi Jiang on 4/20/17.\n//\n#include \"ReWeightedARAP.h\"\n#include \"ScafData.h\"\n#include \"util/triangle_utils.h\"\n\n#include \"igl/arap.h\"\n#include \"igl/cat.h\"\n#include \"igl/doublearea.h\"\n#include \"igl/grad.h\"\n#include \"igl/local_basis.h\"\n#include \"igl/per_face_normals.h\"\n#include \"igl/slice_into.h\"\n#include \"igl/serialize.h\"\n#include <igl/columnize.h>\n\n#include <igl/flip_avoiding_line_search.h>\n#include <igl/boundary_facets.h>\n#include <igl/unique.h>\n#include <igl/slim.h>\n#include <igl/grad.h>\n#include <igl/is_symmetric.h>\n#include <igl/polar_svd.h>\n#include <igl/boundary_loop.h>\n#include <igl/cotmatrix.h>\n#include <igl/edge_lengths.h>\n#include <igl/local_basis.h>\n#include <igl/readOBJ.h>\n#include <igl/repdiag.h>\n#include <igl/vector_area_matrix.h>\n#include <iostream>\n#include <igl/slice.h>\n#include <igl/colon.h>\n#include <igl/min_quad_with_fixed.h>\n\n#include <Eigen/IterativeLinearSolvers>\n#include <Eigen/Sparse>\n#include <Eigen/SparseQR>\n#include <Eigen/SparseCholesky>\n#include <Eigen/IterativeLinearSolvers>\n#include <Eigen/Dense>\n#include <Eigen/Sparse>\n\n#include <map>\n#include <set>\n#include <vector>\n#include <igl/Timer.h>\n#include <igl/edge_flaps.h>\n\nvoid ReWeightedARAP::solve_weighted_arap(Eigen::MatrixXd &uv)\n{\n  using namespace Eigen;\n  using namespace std;\n  int dim = d_.dim;\n  auto v_n = d_.v_num;\n  igl::Timer timer;\n  timer.start();\n\n  const VectorXi &bnd_ids = d_.frame_ids;\n\n  const auto bnd_n = bnd_ids.size();\n  assert(bnd_n > 0);\n  MatrixXd bnd_pos;\n  igl::slice(d_.w_uv, bnd_ids, 1, bnd_pos);\n\n  ArrayXi known_ids(bnd_n * dim);\n  ArrayXi unknown_ids((v_n - bnd_n) * dim);\n\n  { // get the complement of bnd_ids.\n    int assign = 0, i = 0;\n    for (int get = 0; i < v_n && get < bnd_ids.size(); i++)\n    {\n      if (bnd_ids(get) == i)\n        get++;\n      else\n        unknown_ids(assign++) = i;\n    }\n    while (i < v_n)\n      unknown_ids(assign++) = i++;\n    assert(assign + bnd_ids.size() == v_n);\n  }\n\n  VectorXd known_pos(bnd_ids.size() * dim);\n  for (int d = 0; d < dim; d++)\n  {\n    auto n_b = bnd_ids.rows();\n    known_ids.segment(d * n_b, n_b) = bnd_ids.array() + d * v_n;\n    known_pos.segment(d * n_b, n_b) = bnd_pos.col(d);\n    unknown_ids.block(d * (v_n - n_b), 0, v_n - n_b, unknown_ids.cols()) =\n        unknown_ids.topRows(v_n - n_b) + d * v_n;\n  }\n  //std::cout<<\"Slicing Knowns \"<<timer.getElapsedTime()<<std::endl;\n  //timer.start();\n\n  Eigen::SparseMatrix<double> L;\n  Eigen::VectorXd rhs;\n\n  // fixed frame solving:\n  // x_e as the fixed frame, x_u for unknowns (mesh + unknown scaffold)\n  // min ||(A_u*x_u + A_e*x_e) - b||^2\n  // => A_u'*A_u*x_u + A_u'*A_e*x_e = Au'*b\n  // => A_u'*A_u*x_u  = Au'* (b - A_e*x_e) := Au'* b_u\n  // => L * x_u = rhs\n  //\n  // separate matrix build:\n  // min ||A_m x_m - b_m||^2 + ||A_s x_all - b_s||^2 + soft + proximal\n  // First change dimension of A_m to fit for x_all\n  // (Not just at the end, since x_all is flattened along dimensions)\n  // L = A_m'*A_m + A_s'*A_s + soft + proximal\n  // rhs = A_m'* b_m + A_s' * b_s + soft + proximal\n  //\n  using namespace std;\n  Eigen::SparseMatrix<double> L_m, L_s;\n  Eigen::VectorXd rhs_m, rhs_s;\n  build_surface_linear_system(L_m, rhs_m);  // complete Am, with soft\n  build_scaffold_linear_system(L_s, rhs_s); // complete As, without proximal\n  // we don't need proximal term\n\n  L = L_m + L_s;\n  rhs = rhs_m + rhs_s;\n  L.makeCompressed();\n\n  //std::cout<<\"Constructing matrices \"<<timer.getElapsedTime()<<std::endl;\n  //  VectorXd uv_flat(dim * v_n);\n  //  for (int i = 0; i < dim; i++)\n  //    for (int j = 0; j < v_n; j++)\n  //      uv_flat(v_n * i + j) = d_.w_uv(j, i);\n  //\n  //  VectorXd uv_flat_unknown(dim * (v_n - bnd_ids.size()));\n  //  igl::slice(uv_flat, unknown_ids, 1, uv_flat_unknown);\n\n  timer.start();\n  Eigen::VectorXd unknown_Uc((v_n - d_.frame_ids.size()) * dim), Uc(dim * v_n);\n  bool solve_with_cg = (d_.dim == 3);\n  if (solve_with_cg)\n  {\n    for (auto t:{1e-6}) {\n      timer.start();\n      ConjugateGradient<Eigen::SparseMatrix<double>, Eigen::Lower | Upper>\n          CGsolver;\n      CGsolver.setTolerance(t);\n      unknown_Uc = CGsolver.compute(L).solve(rhs);\n      cout << t << \"CGSolve = \" << timer.getElapsedTime() << endl;\n      std::cout << \"#iterations:     \" << CGsolver.iterations() << std::endl;\n      std::cout << \"estimated error: \" << CGsolver.error() << std::endl;\n    }\n  }\n  else\n  {\n    SimplicialLDLT<Eigen::SparseMatrix<double>> solver;\n    unknown_Uc = solver.compute(L).solve(rhs);\n    //cout << \"Direct Solve = \" << timer.getElapsedTime() << endl;\n  }\n  //timer.start();\n  igl::slice_into(unknown_Uc, unknown_ids.matrix(), 1, Uc);\n  igl::slice_into(known_pos, known_ids.matrix(), 1, Uc);\n\n  uv = Map<Matrix<double,-1,-1,Eigen::ColMajor>>(Uc.data(),v_n ,dim); \n  //for (int i = 0; i < dim; i++)\n  //  uv.col(i) = Uc.block(i * v_n, 0, v_n, 1);\n  //cout << \"Slice back = \" << timer.getElapsedTime() << endl;\n}\n\nvoid ReWeightedARAP::build_surface_linear_system(Eigen::SparseMatrix<double> &L,\n                                                 Eigen::VectorXd &rhs) const\n{\n\n  using namespace Eigen;\n  using namespace std;\n\n  const int v_n = d_.v_num - (d_.frame_ids.size());\n  const int dim = d_.dim;\n  const int f_n = d_.mf_num;\n  if (d_.dim == 3 && d_.m_T.cols() == 3)\n  { // arap\n    Eigen::SparseMatrix<double> L_cot = (-arap_energy_p * CotMat).eval();\n    L_cot.conservativeResize(v_n, v_n);\n    igl::repdiag(L_cot, 3, L);\n\n    auto &data = arap_data;\n\n    const int Rdim = data.dim;\n    MatrixXd R(Rdim, data.CSM.rows());\n\n    for (int i = 0; i < arap_rots.size(); i++)\n    {\n      R.block(0, 3 * i, 3, 3) = arap_rots[i];\n    }\n\n    // Number of rotations: #vertices or #elements\n    int num_rots = data.K.cols() / Rdim / Rdim;\n    // distribute group rotations to vertices in each group\n\n    VectorXd Rcol;\n    igl::columnize(R, num_rots, 2, Rcol);\n    VectorXd Bcol = data.K * Rcol;\n    assert(Bcol.size() == data.n * data.dim);\n\n    Map<MatrixXd> arap_Bc(Bcol.data(), data.n, data.dim); //column order\n\n    rhs = Eigen::VectorXd::Zero(v_n * 3);\n    for (int d = 0; d < dim; d++)\n      rhs.segment(d * v_n, data.n) = arap_energy_p * arap_Bc.col(d);\n    return;\n  }\n\n  // to get the  complete A\n  Eigen::VectorXd sqrtM = d_.m_M.array().sqrt();\n  Eigen::SparseMatrix<double> A(dim * dim * f_n, dim * v_n);\n\n  auto decoy_Dx_m = Dx_m; decoy_Dx_m.conservativeResize(W_m.rows(), v_n);\n  auto decoy_Dy_m = Dy_m; decoy_Dy_m.conservativeResize(W_m.rows(), v_n);\n  auto decoy_Dz_m = Dz_m;\n  if (dim == 3) decoy_Dz_m.conservativeResize(W_m.rows(), v_n);\n  buildAm(sqrtM, decoy_Dx_m, decoy_Dy_m, decoy_Dz_m, W_m, A);\n\n  Eigen::SparseMatrix<double> At = A.transpose();\n  At.makeCompressed();\n\n  Eigen::SparseMatrix<double> id_m(At.rows(), At.rows());\n  id_m.setIdentity();\n\n  L = At * A;\n\n  Eigen::VectorXd frhs;\n  buildRhs(sqrtM, W_m, Ri_m, frhs);\n  rhs = At * frhs;\n\n  // add soft constraints.\n  for (auto const &x : d_.soft_cons)\n  {\n    int v_idx = x.first;\n\n    for (int d = 0; d < dim; d++)\n    {\n      rhs(d * (v_n) + v_idx) += d_.soft_const_p * x.second(d); // rhs\n      L.coeffRef(d * v_n + v_idx,\n                 d * v_n + v_idx) += d_.soft_const_p; // diagonal\n    }\n  }\n}\n\nvoid ReWeightedARAP::build_scaffold_linear_system(Eigen::SparseMatrix<double>\n                                                      &L,\n                                                  Eigen::VectorXd &rhs) const\n{\n  using namespace Eigen;\n\n  const int f_n = W_s.rows();\n  const int v_n = Dx_s.cols();\n  const int dim = d_.dim;\n\n  Eigen::VectorXd sqrtM = d_.s_M.array().sqrt();\n  Eigen::SparseMatrix<double> A(dim * dim * f_n, dim * v_n);\n  buildAm(sqrtM, Dx_s, Dy_s, Dz_s, W_s, A);\n\n  const VectorXi &bnd_ids = d_.frame_ids;\n\n  auto bnd_n = bnd_ids.size();\n  assert(bnd_n > 0);\n  MatrixXd bnd_pos;\n  igl::slice(d_.w_uv, bnd_ids, 1, bnd_pos);\n\n  ArrayXi known_ids(bnd_ids.size() * dim);\n  ArrayXi unknown_ids((v_n - bnd_ids.rows()) * dim);\n\n  { // get the complement of bnd_ids.\n    int assign = 0, i = 0;\n    for (int get = 0; i < v_n && get < bnd_ids.size(); i++)\n    {\n      if (bnd_ids(get) == i)\n        get++;\n      else\n        unknown_ids(assign++) = i;\n    }\n    while (i < v_n)\n      unknown_ids(assign++) = i++;\n    assert(assign + bnd_ids.size() == v_n);\n  }\n\n  VectorXd known_pos(bnd_ids.size() * dim);\n  for (int d = 0; d < dim; d++)\n  {\n    auto n_b = bnd_ids.rows();\n    known_ids.segment(d * n_b, n_b) = bnd_ids.array() + d * v_n;\n    known_pos.segment(d * n_b, n_b) = bnd_pos.col(d);\n    unknown_ids.block(d * (v_n - n_b), 0, v_n - n_b, unknown_ids.cols()) =\n        unknown_ids.topRows(v_n - n_b) + d * v_n;\n  }\n  Eigen::VectorXd sqrt_M = d_.s_M.array().sqrt();\n\n  // slice\n  // 'manual slicing for A(:, unknown/known)'\n  Eigen::SparseMatrix<double> Au, Ae;\n  {\n    using TY = double;\n    using TX = double;\n    auto &X = A;\n\n    int xm = X.rows();\n    int xn = X.cols();\n    int ym = xm;\n    int yn = unknown_ids.size();\n    int ykn = known_ids.size();\n\n    std::vector<int> CI(xn, -1);\n    std::vector<int> CKI(xn, -1);\n    // initialize to -1\n    for (int i = 0; i < yn; i++)\n      CI[unknown_ids(i)] = (i);\n    for (int i = 0; i < ykn; i++)\n      CKI[known_ids(i)] = i;\n    Eigen::DynamicSparseMatrix<TY, Eigen::ColMajor> dyn_Y(ym, yn);\n    Eigen::DynamicSparseMatrix<TY, Eigen::ColMajor> dyn_K(ym, ykn);\n    // Take a guess at the number of nonzeros (this assumes uniform distribution\n    // not banded or heavily diagonal)\n    dyn_Y.reserve(A.nonZeros());\n    dyn_K.reserve(A.nonZeros() * ykn / xn);\n    // Iterate over outside\n    for (int k = 0; k < X.outerSize(); ++k)\n    {\n      // Iterate over inside\n      if (CI[k] != -1)\n        for (typename Eigen::SparseMatrix<TX>::InnerIterator it(X, k); it;\n             ++it)\n        {\n          dyn_Y.coeffRef(it.row(), CI[it.col()]) = it.value();\n        }\n      else\n        for (typename Eigen::SparseMatrix<TX>::InnerIterator it(X, k); it;\n             ++it)\n        {\n          dyn_K.coeffRef(it.row(), CKI[it.col()]) = it.value();\n        }\n    }\n    Au = Eigen::SparseMatrix<TY>(dyn_Y);\n    Ae = Eigen::SparseMatrix<double>(dyn_K);\n  }\n\n  Eigen::SparseMatrix<double> Aut = Au.transpose();\n  Aut.makeCompressed();\n\n  Eigen::SparseMatrix<double> id(Aut.rows(), Aut.rows());\n  id.setIdentity();\n\n  L = Aut * Au;\n\n  Eigen::VectorXd frhs;\n  buildRhs(sqrtM, W_s, Ri_s, frhs);\n\n  rhs = Aut * (frhs - Ae * known_pos);\n}\n\nvoid ReWeightedARAP::buildAm(const Eigen::VectorXd &sqrt_M,\n                             const Eigen::SparseMatrix<double> &Dx,\n                             const Eigen::SparseMatrix<double> &Dy,\n                             const Eigen::SparseMatrix<double> &Dz,\n                             const Eigen::MatrixXd &W,\n                             Eigen::SparseMatrix<double> &Am)\n{\n  std::vector<Eigen::Triplet<double>> IJV;\n\n  Eigen::SparseMatrix<double> MDx = sqrt_M.asDiagonal() * Dx;\n  Eigen::SparseMatrix<double> MDy = sqrt_M.asDiagonal() * Dy;\n\n  Eigen::SparseMatrix<double> MDz;\n  if (Dz.rows() != 0) MDz = sqrt_M.asDiagonal() * Dz;\n\n  igl::slim_buildA(MDx, MDy, MDz, W, IJV);\n\n  Am.setFromTriplets(IJV.begin(), IJV.end());\n  Am.makeCompressed();\n }\n\nvoid ReWeightedARAP::buildRhs(const Eigen::VectorXd &sqrt_M,\n                              const Eigen::MatrixXd &W,\n                              const Eigen::MatrixXd &Ri,\n                              Eigen::VectorXd &f_rhs)\n{\n  const int dim = (W.cols() == 4) ? 2 : 3;\n  const int f_n = W.rows();\n  f_rhs.resize(dim * dim * f_n);\n\n  if (dim == 2)\n  {\n    /*b = [W11*R11 + W12*R21; (formula (36))\n         W11*R12 + W12*R22;\n         W21*R11 + W22*R21;\n         W21*R12 + W22*R22];*/\n    for (int i = 0; i < f_n; i++)\n    {\n      auto sqrt_area = sqrt_M(i);\n      f_rhs(i + 0 * f_n) = sqrt_area * (W(i, 0) * Ri(i, 0) + W(i, 1) * Ri(i, 1));\n      f_rhs(i + 1 * f_n) = sqrt_area * (W(i, 0) * Ri(i, 2) + W(i, 1) * Ri(i, 3));\n      f_rhs(i + 2 * f_n) = sqrt_area * (W(i, 2) * Ri(i, 0) + W(i, 3) * Ri(i, 1));\n      f_rhs(i + 3 * f_n) = sqrt_area * (W(i, 2) * Ri(i, 2) + W(i, 3) * Ri(i, 3));\n    }\n  }\n  else\n  {\n    /*b = [W11*R11 + W12*R21 + W13*R31;\n         W11*R12 + W12*R22 + W13*R32;\n         W11*R13 + W12*R23 + W13*R33;\n         W21*R11 + W22*R21 + W23*R31;\n         W21*R12 + W22*R22 + W23*R32;\n         W21*R13 + W22*R23 + W23*R33;\n         W31*R11 + W32*R21 + W33*R31;\n         W31*R12 + W32*R22 + W33*R32;\n         W31*R13 + W32*R23 + W33*R33;];*/\n    for (int i = 0; i < f_n; i++)\n    {\n      auto sqrt_area = sqrt_M(i);\n      f_rhs(i + 0 * f_n) = sqrt_area *\n                           (W(i, 0) * Ri(i, 0) + W(i, 1) * Ri(i, 1) + W(i, 2) * Ri(i, 2));\n      f_rhs(i + 1 * f_n) = sqrt_area *\n                           (W(i, 0) * Ri(i, 3) + W(i, 1) * Ri(i, 4) + W(i, 2) * Ri(i, 5));\n      f_rhs(i + 2 * f_n) = sqrt_area *\n                           (W(i, 0) * Ri(i, 6) + W(i, 1) * Ri(i, 7) + W(i, 2) * Ri(i, 8));\n      f_rhs(i + 3 * f_n) = sqrt_area *\n                           (W(i, 3) * Ri(i, 0) + W(i, 4) * Ri(i, 1) + W(i, 5) * Ri(i, 2));\n      f_rhs(i + 4 * f_n) = sqrt_area *\n                           (W(i, 3) * Ri(i, 3) + W(i, 4) * Ri(i, 4) + W(i, 5) * Ri(i, 5));\n      f_rhs(i + 5 * f_n) = sqrt_area *\n                           (W(i, 3) * Ri(i, 6) + W(i, 4) * Ri(i, 7) + W(i, 5) * Ri(i, 8));\n      f_rhs(i + 6 * f_n) = sqrt_area *\n                           (W(i, 6) * Ri(i, 0) + W(i, 7) * Ri(i, 1) + W(i, 8) * Ri(i, 2));\n      f_rhs(i + 7 * f_n) = sqrt_area *\n                           (W(i, 6) * Ri(i, 3) + W(i, 7) * Ri(i, 4) + W(i, 8) * Ri(i, 5));\n      f_rhs(i + 8 * f_n) = sqrt_area *\n                           (W(i, 6) * Ri(i, 6) + W(i, 7) * Ri(i, 7) + W(i, 8) * Ri(i, 8));\n    }\n  }\n}\n", "meta": {"hexsha": "cc3e85e44d26b8c534f02e6ea9c7d4cc299387e1", "size": 13640, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/ReWeightedARAP_solve.cpp", "max_stars_repo_name": "squarefk/Scaffold-Map", "max_stars_repo_head_hexsha": "6218cbc3ec5b83cb24c5bc65dd21e7b3a52dc76b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 37.0, "max_stars_repo_stars_event_min_datetime": "2018-04-04T19:50:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-02T00:56:10.000Z", "max_issues_repo_path": "src/ReWeightedARAP_solve.cpp", "max_issues_repo_name": "squarefk/Scaffold-Map", "max_issues_repo_head_hexsha": "6218cbc3ec5b83cb24c5bc65dd21e7b3a52dc76b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 14.0, "max_issues_repo_issues_event_min_datetime": "2018-04-27T05:01:58.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-21T19:07:28.000Z", "max_forks_repo_path": "src/ReWeightedARAP_solve.cpp", "max_forks_repo_name": "squarefk/Scaffold-Map", "max_forks_repo_head_hexsha": "6218cbc3ec5b83cb24c5bc65dd21e7b3a52dc76b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2018-04-05T10:50:03.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-10T14:26:09.000Z", "avg_line_length": 31.3563218391, "max_line_length": 90, "alphanum_fraction": 0.5602639296, "num_tokens": 4586, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7185943925708561, "lm_q2_score": 0.4649015713733885, "lm_q1q2_score": 0.3340756622862966}}
{"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 <vector>\n#include <iostream>\n#include <iterator>\n#include <math.h>\n#include <boost/optional.hpp>\n#include <fftw3.h>\n#include <comma/visiting/traits.h>\n#include <comma/application/command_line_options.h>\n#include <comma/application/verbose.h>\n#include <comma/csv/options.h>\n#include <comma/csv/stream.h>\n#include \"detail/shuffle-tied.h\"\n\nstd::size_t input_size=0;\nbool filter_input=true;\nbool logarithmic_output=true;\nbool magnitude=false;\nbool real=false;\nbool split=false;\nstd::size_t bin_size=0;\nboost::optional<double> bin_overlap;\nbool tied=true;\n\nvoid usage(bool detail)\n{\n    std::cerr<<\"    perform fft on input data\" << std::endl;\n    std::cerr << std::endl;\n    std::cerr<< \"usage: \" << comma::verbose.app_name() << \" [ <options> ]\" << std::endl;\n    std::cerr << std::endl;\n    std::cerr<< \"    input fields: data; an array of double, size is specified with --size\"  << std::endl;\n    std::cerr<< \"    output: array of pair (real, complex) of double; use --output-size to get size of array of doubles with the specified options\"  << std::endl;\n    std::cerr << std::endl;\n    std::cerr << \"options\" << std::endl;\n    std::cerr << \"    --help,-h: show help\" << std::endl;\n    std::cerr << \"    --verbose,-v: show detailed messages\" << std::endl;\n    std::cerr << std::endl;\n    std::cerr << \"    --bin-size=[<size>]: cut data into several bins of this size and perform fft on each bin, when not speificed calculates fft on the whole data\" << std::endl;\n    std::cerr << \"    --bin-overlap=[<overlap>]: if specified, each bin will contain this portion of the last bin's data, range: 0 (no overlap) to 1\"<<std::endl;\n    std::cerr << \"    --linear: output as linear; when not specified, output will be scaled to lograithm of 10 for magnitude or real part (phase is not affected)\" << std::endl;\n    std::cerr << \"    --no-filter: when not specified, filters input using a cut window to get limited output\" << std::endl;\n    std::cerr << \"    --size=<size>: size of input vector\" << std::endl;\n    std::cerr << std::endl;\n    std::cerr << \"  output options:\" << std::endl;\n    std::cerr << \"    --magnitude: output magnitude only\" << std::endl;\n    std::cerr<< \"        output is binary array of double with half the size of input\"  << std::endl;\n    std::cerr << \"    --real: output real part only\" << std::endl;\n    std::cerr<< \"        output is binary array of double with half the size of input\"  << std::endl;\n    std::cerr << \"    --split: output array of real followed by array of complex part; when not specified real and complex parts are interleaved\" << std::endl;\n    std::cerr << std::endl;\n    std::cerr << \"    --shuffle,--shuffle-fields,--shuffled-fields=[<csv_fields>]: comma separated list of input fields to be written to stdout; if not specified prepend all input fields to the output\" << std::endl;\n    std::cerr << \"    --untied: only write output (doesn't write input to stdout)\" << std::endl;\n    std::cerr << std::endl;\n    std::cerr << \"  utility options:\" << std::endl;\n    std::cerr << \"    --output-fields: print output fields and exit; depends on input fields and size\" << std::endl;\n    std::cerr << \"    --output-format: print binary format of output and exit; depends on input fields and size\" << std::endl;\n    std::cerr << \"    --output-size: print size of output data array and exit; e.g. if output format is t,ui,256d, then output size is 256\" << std::endl;\n    std::cerr << std::endl;\n    if(detail)\n    {\n        std::cerr << \"csv options:\" << std::endl;\n        std::cerr<< comma::csv::options::usage() << std::endl;\n        std::cerr << std::endl;\n    }\n    else\n    {\n        std::cerr << \"use -v or --verbose to see more detail\" << std::endl;\n        std::cerr << std::endl;\n    }\n    std::cerr << \"example\" << std::endl;\n    std::cerr << \"      \" << comma::verbose.app_name() << \" --binary=\\\"t,16000f\\\" --fields=t,data --size=16000\" << std::endl;\n    std::cerr << std::endl;\n    exit(0);\n}\n\n// math-fft --fields ,,data --format t,ui,16000f\n// math-fft --fields ,,,,,data --format t,ui,s[$(( 16000 * 4  ))],t,ui,16000f\n\nstruct input_t\n{\n    std::vector<double> data;\n    input_t() : data(input_size) {}\n};\n\nstruct output_t\n{\n    std::vector<double> data;\n    output_t()\n    {\n        std::size_t len=bin_size;\n        if(magnitude || real) { len/=2; }\n        data.resize(len);\n    }\n    void reset()\n    {\n        memset(&data[0],0,data.size()*sizeof(data[0]));\n    }\n};\n\nnamespace comma { namespace visiting {\n\ntemplate <> struct traits< input_t >\n{\n    template< typename K, typename V > static void visit( const K& k, input_t& p, V& v )\n    {\n        v.apply( \"data\", p.data );\n    }\n    template< typename K, typename V > static void visit( const K& k, const input_t& p, V& v )\n    {\n        v.apply( \"data\", p.data );\n    }\n};\n\ntemplate <> struct traits< output_t >\n{\n    template< typename K, typename V > static void visit( const K& k, const output_t& p, V& v )\n    {\n        v.apply( \"output\", p.data );\n    }\n};\n\n} } // namespace comma { namespace visiting {\n\ntemplate<typename T>\nT* allocate_fftw_array(std::size_t size)\n{\n    return reinterpret_cast<T*>(fftw_malloc(sizeof(T)*size));\n}\n\n// a quick and dirty helper class\nstruct fft\n{\n    std::vector<double> h;\n    double* input;\n    fftw_complex* output;\n    fftw_plan plan;\n\n    fft(std::size_t size) : h( size ), input(allocate_fftw_array<double>(size)) ,\n        output(allocate_fftw_array<fftw_complex>(size / 2 + 1 )) ,\n        plan( fftw_plan_dft_r2c_1d( size, input, output, 0 ) )\n    {\n        for( std::size_t i = 0; i < size; ++i ) { h[i] = 0.54 - 0.46 * std::cos( M_PI * 2 * i / size ); }\n    }\n    ~fft()\n    {\n        fftw_destroy_plan(plan);\n        fftw_free( input ); // seems that fftw_destroy_plan() releases it\n        fftw_free( output ); // seems that fftw_destroy_plan() releases it\n    }\n    void calculate() { fftw_execute( plan); }\n    std::size_t output_size() const { return h.size() / 2; }\n};\n\nvoid calculate(const double* data, std::size_t size, std::vector<double>& output)\n{\n    fft fft(size);\n    if(filter_input)\n    {\n        for(std::size_t i=0;i<size;i++) { fft.input[i] = fft.h[i] * data[i]; }\n    }\n    else { memcpy(fft.input, data, size * sizeof(double)); }\n    \n    fft.calculate();\n    \n    if(magnitude)\n    {\n        if(fft.output_size()>output.size()) { COMMA_THROW(comma::exception, \"size mismatch, output \"<<output.size()<<\" fft output \"<<fft.output_size()); }\n        for(std::size_t j=0;j<fft.output_size();j++)\n        {\n            double a= std::abs( std::complex<double>( fft.output[j][0], fft.output[j][1] ) );\n            if(logarithmic_output) { a = (a == 0) ? 0 : (std::log10(a)); }\n            output[j]=a;\n        }\n    }\n    else if(real)\n    {\n        if(fft.output_size()>output.size()) { COMMA_THROW(comma::exception, \"size mismatch, output \"<<output.size()<<\" fft output \"<<fft.output_size()); }\n        for(std::size_t j=0;j<fft.output_size();j++)\n        {\n            double a= fft.output[j][0];\n            if(logarithmic_output) { a = (a == 0) ? 0 : (std::log10(a)); }\n            output[j]=a;\n        }\n    }\n    else\n    {\n        std::size_t k=0;\n        std::size_t step=2;\n        std::size_t off=1;\n        if(split)\n        {\n            step=1;\n            off=output.size()/2;\n        }\n        if(2*fft.output_size()>output.size()) { COMMA_THROW(comma::exception, \"size mismatch, output \"<<output.size()<<\" fft output \"<<fft.output_size()); }\n        for(std::size_t j=0; j<fft.output_size(); j++, k+=step)\n        {\n            double a= fft.output[j][0];\n            if(logarithmic_output) { a = (a == 0) ? 0 : (std::log10(a)); }\n            output[k]=a;\n            output[k+off]=fft.output[j][1];\n        }\n    }\n}\n\nstruct app\n{\n    app()\n    {\n    }\n    void process(const comma::csv::options& csv, const boost::optional<std::string>& shuffle_fields)\n    {\n        if(bin_overlap && int(bin_size*(1-*bin_overlap)) <= 0) { COMMA_THROW( comma::exception, \"bin size and overlap don't work\" ); }\n        input_t sample;\n        comma::csv::input_stream<input_t> is(std::cin, csv, sample);\n        comma::csv::output_stream<output_t> os(std::cout, csv.binary(), true);\n        std::string array_sizes=\"data=\";\n        array_sizes+=boost::lexical_cast<std::string>(sample.data.size());\n        ::shuffle_tied<input_t,output_t> shuffle_tied(is, os, csv, shuffle_fields,array_sizes);\n        output_t output;\n        while(std::cin.good())\n        {\n            //read a record\n            const input_t* input=is.read();\n            if(!input) { break; }\n            //calculate\n            for(std::size_t bin_offset=0;bin_offset<input_size;bin_offset+=(bin_overlap ? bin_size*(1-*bin_overlap) : bin_size))\n            {\n                output.reset();\n                calculate(&input->data[bin_offset], std::min(bin_size,input_size-bin_offset), output.data);\n                //write output\n                if(tied)\n                    shuffle_tied.append(output);\n                else\n                    os.write(output);\n            }\n        }\n    }\n    std::size_t get_output_size()\n    {\n        return output_t().data.size();\n    }\n    void output_format()\n    {\n        std::cout<<output_t().data.size()<<\"d\"<<std::endl;\n    }\n    void output_fields()\n    {\n        std::cout<<comma::join(comma::csv::names< output_t >(true),',')<<std::endl;\n    }\n};\n\ntemplate<typename T>\nstd::ostream& operator<< (std::ostream& o, const std::vector<T>& v)\n{\n    std::copy(v.begin(), v.end(), std::ostream_iterator<T>(o, \" \"));\n    return o;\n}\ntemplate<typename T>\nvoid range_check(T value, T min, T max, const char* label)\n{\n    if(value<min || value>max) { COMMA_THROW(comma::exception, label<<\" out of range \"<<min<<\" to \"<<max ); }\n}\n\nint main( int argc, char** argv )\n{\n    comma::command_line_options options( argc, argv, usage );\n    try\n    {\n        comma::csv::options csv(options,\"data\");\n        filter_input= ! options.exists(\"--no-filter\");\n        logarithmic_output= ! options.exists(\"--linear\");\n        input_size=options.value<std::size_t>(\"--size\");\n        magnitude=options.exists(\"--magnitude\");\n        real=options.exists(\"--real\");\n        split=options.exists(\"--split\");\n        bin_size=options.value<std::size_t>(\"--bin-size\", input_size);\n        range_check<std::size_t>(bin_size,0,input_size,\"bin_size\");\n        bin_overlap=options.optional<double>(\"--bin-overlap\");\n        if(bin_overlap) { range_check<double>(*bin_overlap,0,1,\"bin_overlap\"); }\n        boost::optional<std::string> shuffle_fields=options.optional<std::string>(\"--shuffle,--shuffle-fields,--shuffled-fields\");\n        tied=!options.exists(\"--untied\");\n        if(shuffle_fields&&!tied) { COMMA_THROW(comma::exception,\"--shuffle only works with tied stream (can't specify both --untied and --shuffle\"); }\n        std::vector<std::string> unnamed=options.unnamed(\"--verbose,-v,--output-size,--output-format,--output-fields,--no-filter,--linear,--magnitude,--real,--split,--untied\", \n                                                         \"--binary,-b,--fields,-f,--delimiter,-d,--size,--bin-size,--bin-overlap,--shuffle,--shuffle-fields,--shuffled-fields\");\n        if(unnamed.size() != 0) { COMMA_THROW(comma::exception, \"invalid option(s): \" << unnamed ); }\n        app app;\n        if(options.exists(\"--output-size\")) { std::cout<< app.get_output_size() << std::endl; return 0; }\n        if(options.exists(\"--output-format\")) { app.output_format(); return 0; }\n        if(options.exists(\"--output-fields\")) { app.output_fields(); return 0; }\n        app.process(csv,shuffle_fields);\n        return 0;\n    }\n    catch( std::exception& ex )\n    {\n        std::cerr << comma::verbose.app_name() << \": \" << ex.what() << std::endl;\n    }\n    catch( ... )\n    {\n        std::cerr << comma::verbose.app_name() << \": \" << \"unknown exception\" << std::endl;\n    }\n    return 1;\n}\n", "meta": {"hexsha": "980d743b0abc16ca748b9cdcf16467c878e90d45", "size": 13632, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "math/applications/math-fft.cpp", "max_stars_repo_name": "nightfox0909/snark", "max_stars_repo_head_hexsha": "6a6ddc79af9086f13ba0c1287a555c2740fe4e70", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 63.0, "max_stars_repo_stars_event_min_datetime": "2015-01-14T14:38:02.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-01T09:56:03.000Z", "max_issues_repo_path": "math/applications/math-fft.cpp", "max_issues_repo_name": "nightfox0909/snark", "max_issues_repo_head_hexsha": "6a6ddc79af9086f13ba0c1287a555c2740fe4e70", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 39.0, "max_issues_repo_issues_event_min_datetime": "2015-01-21T00:57:38.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-22T04:22:35.000Z", "max_forks_repo_path": "math/applications/math-fft.cpp", "max_forks_repo_name": "nightfox0909/snark", "max_forks_repo_head_hexsha": "6a6ddc79af9086f13ba0c1287a555c2740fe4e70", "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": 41.0602409639, "max_line_length": 215, "alphanum_fraction": 0.6104019953, "num_tokens": 3533, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6477982315512489, "lm_q2_score": 0.5156199157230156, "lm_q1q2_score": 0.3340176695579735}}
{"text": "/**\n * \\file dcs/algorithm/subset.hpp\n *\n * \\brief Generate the power set of a set in lexicographic order.\n *\n * \\author Marco Guazzone (marco.guazzone@gmail.com)\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#ifndef DCS_COMMONS_ALGORITHM_SUBSET_HPP\n#define DCS_COMMONS_ALGORITHM_SUBSET_HPP\n\n#include <algorithm>\n#include <boost/dynamic_bitset.hpp>\n#include <boost/math/special_functions/binomial.hpp>\n#include <cstddef>\n#include <dcs/assert.hpp>\n#include <dcs/debug.hpp>\n#include <dcs/exception.hpp>\n#include <iostream>\n#include <iterator>\n#include <stdexcept>\n#include <vector>\n\n\nnamespace dcs { namespace algorithm {\n\n/**\n * \\brief Traits class for subset types\n *\n * \\tparam ValueT The value type\n *\n * \\author Marco Guazzone (marco.guazzone@gmail.com)\n */\ntemplate <typename ValueT>\nstruct subset_traits\n{\n\ttypedef ValueT value_type;\n\ttypedef ::std::vector<value_type> subset_container;///< DEPRECATED\n\ttypedef typename subset_container::iterator subset_container_iterator;///< DEPRECATED\n\ttypedef typename subset_container::const_iterator subset_container_const_iterator;///< DEPRECATED\n\ttypedef ::std::vector<value_type> element_container;\n\ttypedef typename element_container::iterator element_iterator;\n\ttypedef typename element_container::const_iterator element_const_iterator;\n}; // subset_traits\n\n\n/**\n * \\brief Class to generate in lexicographic order all subsets\n *\n * Given a set N={0,1,...,n-1} of n elements, this class iteratively generates\n * all subset S of N, possibly included the empty set, in lexicographic order,\n * that is, to generate a subset containing the i-th element we generate all\n * subset containing the preceding 0,1,...(i-1)-th elements.\n * For instance, for a set of 4 elements, the subset generation in lexicographic\n * order produces the following sequence:\n * <pre>\n *  \\emptyset,\n *  {0},\n *  {1},\n *  {0,1},\n *  {2},\n *  {0,2},\n *  {1,2},\n *  {0,1,2},\n *  {3},\n *  {0,3},\n *  {1,3},\n *  {2,3},\n *  {0,1,3},\n *  {0,2,3}\n *  {1,2,3},\n *  {0,1,2,3}\n * </pre>\n *\n * \\author Marco Guazzone (marco.guazzone@gmail.com)\n */\nclass lexicographic_subset\n{\n\tpublic: class const_iterator;\n\n\n\tfriend class const_iterator;\n\n\n\tprivate: typedef lexicographic_subset self_type;\n\tprivate: typedef ::boost::dynamic_bitset<> impl_type;\n\tprivate: typedef typename impl_type::size_type size_type;\n\tprivate: typedef unsigned long word_type;\n\n\n\tpublic: explicit lexicographic_subset(::std::size_t n, bool empty_set=true)\n\t: n_(n),\n\t  empty_set_(empty_set),\n\t  bits_(n, empty_set ? 0 : 1),\n\t  has_prev_(false),\n\t  has_next_(n_ > 0 ? true : false)\n\t{\n\t\tDCS_ASSERT(n_ > 0,\n\t\t\t\t   DCS_EXCEPTION_THROW(::std::invalid_argument,\n\t\t\t\t\t\t\t\t\t   \"Number of elements must be positive\"));\n\t}\n\n\tpublic: ::std::size_t max_size() const\n\t{\n\t\treturn n_;\n\t}\n\n\tpublic: ::std::size_t size() const\n\t{\n\t\treturn bits_.count();\n\t}\n\n\tpublic: ::std::size_t count() const\n\t{\n\t\tconst ::std::size_t c = 1 << n_; // 2^n\n\n\t\treturn empty_set_ ? c : (c-1);\n\t}\n\n\tpublic: self_type& operator++()\n\t{\n\t\tDCS_ASSERT(has_next_,\n\t\t\t\t   DCS_EXCEPTION_THROW(::std::overflow_error,\n\t\t\t\t\t\t\t\t\t   \"No following subsets\"));\n\n\t\thas_next_ = bits_.count() < n_;\n\n\t\tif (has_next_)\n\t\t{\n\t\t\tbits_ = impl_type(n_, bits_.to_ulong()+1);\n\t\t}\n\n\t\thas_prev_ = bits_.to_ulong() > (empty_set_ ? 0 : 1);\n\n\t\treturn *this;\n\t}\n\n\tpublic: bool has_next() const\n\t{\n\t\treturn has_next_;\n\t}\n\n\tpublic: self_type& operator--()\n\t{\n\t\tDCS_ASSERT(has_prev_,\n\t\t\t\t   DCS_EXCEPTION_THROW(::std::underflow_error,\n\t\t\t\t\t\t\t\t\t   \"No preceding subsets\"));\n\n\t\thas_prev_ = bits_.to_ulong() > (empty_set_ ? 0 : 1);\n\n\t\tif (has_prev_)\n\t\t{\n\t\t\tbits_ = impl_type(n_, bits_.to_ulong()-1);\n\t\t}\n\n\t\thas_next_ = bits_.to_ulong() < n_;\n\n\t\treturn *this;\n\t}\n\n\tpublic: bool has_prev() const\n\t{\n\t\treturn has_prev_;\n\t}\n\n\tpublic: typename ::std::vector<size_type> operator()() const\n\t{\n\t\t::std::vector<size_type> subset;\n\n\t\tfor (size_type pos = bits_.find_first();\n\t\t\t pos != impl_type::npos;\n\t\t\t pos = bits_.find_next(pos))\n\t\t{\n\t\t\tsubset.push_back(pos);\n\t\t}\n\n\t\treturn subset;\n\t}\n\n\t//public: template <typename ElemT, typename IterT>\n\tpublic: template <typename ElemT>\n\t\t\ttypename subset_traits<ElemT>::element_container operator()(::std::vector<ElemT> const& v) const\n\t{\n\t\tDCS_ASSERT(v.size() == n_,\n\t\t\t\t   DCS_EXCEPTION_THROW(::std::invalid_argument,\n\t\t\t\t\t\t\t\t\t   \"Size does not match\"));\n\n\t\ttypename subset_traits<ElemT>::element_container subset;\n\n\t\tfor (size_type pos = bits_.find_first();\n\t\t\t pos != impl_type::npos;\n\t\t\t pos = bits_.find_next(pos))\n\t\t{\n\t\t\tsubset.push_back(v[pos]);\n\t\t}\n\n\t\treturn subset;\n\t}\n\n\tpublic: template <typename IterT>\n\t\t\ttypename subset_traits< typename ::std::iterator_traits<IterT>::value_type >::element_container operator()(IterT first, IterT last) const\n\t{\n\t\t\treturn this->operator()(::std::vector<typename ::std::iterator_traits<IterT>::value_type>(first, last));\n\t}\n\n\tpublic: const_iterator begin() const\n\t{\n\t\treturn const_iterator(this, bits_.any() ? bits_.find_first() : impl_type::npos);\n\t}\n\n\tpublic: const_iterator end() const\n\t{\n\t\treturn const_iterator(this, impl_type::npos);\n\t}\n\n\n\tpublic: class const_iterator: public ::std::iterator< ::std::bidirectional_iterator_tag,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t typename lexicographic_subset::impl_type::size_type const>\n\t{\n\t\tprivate: typedef ::std::iterator< ::std::bidirectional_iterator_tag,\n\t\t\t\t\t\t\t\t\t\t  typename lexicographic_subset::impl_type::size_type const> base_type;\n\t\tprivate: typedef lexicographic_subset container_type;\n\t\tprivate: typedef typename container_type::impl_type bitset_type;\n\t\tprivate: typedef typename container_type::size_type size_type;\n\t\tpublic: typedef typename base_type::value_type value_type;\n\t\tpublic: typedef typename base_type::difference_type difference_type;\n\t\tpublic: typedef typename base_type::pointer pointer;\n\t\tpublic: typedef typename base_type::reference reference;\n\t\tpublic: typedef typename base_type::iterator_category iterator_category;\n\n\n\t\tpublic: const_iterator(container_type const* p_subset, size_type pos)\n\t\t: p_sub_(p_subset),\n\t\t  pos_(pos)\n\t\t{\n\t\t}\n\n\t\tpublic: reference operator*() const\n\t\t{\n\t\t\treturn pos_;\n\t\t}\n\n\t\tpublic: pointer operator->() const\n\t\t{\n\t\t\treturn &(operator*());\n\t\t}\n\n\t\tpublic: const_iterator& operator++()\n\t\t{\n\t\t\tpos_ = p_sub_->bits_.find_next(pos_);\n\n\t\t\treturn *this;\n\t\t}\n\n\t\tpublic: const_iterator operator++(int)\n\t\t{\n\t\t\tconst_iterator tmp = *this;\n\n\t\t\toperator++();\n\n\t\t\treturn tmp;\n\t\t}\n\n\t\tpublic: const_iterator& operator--()\n\t\t{\n\t\t\tsize_type pos = bitset_type::npos;\n\t\t\tfor (size_type pos2 = p_sub_->bits_.find_first();\n\t\t\t\t pos2 != pos_;\n\t\t\t\t pos2 = p_sub_->bits_.find_next(pos2))\n\t\t\t{\n\t\t\t\tpos = pos2;\n\t\t\t}\n\n\t\t\tpos_ = pos;\n\n\t\t\treturn *this;\n\t\t}\n\n\t\tpublic: const_iterator operator--(int)\n\t\t{\n\t\t\tconst_iterator tmp = *this;\n\n\t\t\toperator--();\n\n\t\t\treturn tmp;\n\t\t}\n\n\t\tpublic: const_iterator operator+(difference_type n) const\n\t\t{\n\t\t\tconst_iterator it = *this;\n\n\t\t\tif (n > 0)\n\t\t\t{\n\t\t\t\twhile (n--)\n\t\t\t\t{\n\t\t\t\t\t++it;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\twhile (n++)\n\t\t\t\t{\n\t\t\t\t\t--it;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn it;\n\t\t}\n\n\t\tpublic: const_iterator operator-(difference_type n) const\n\t\t{\n\t\t\treturn operator+(-n);\n\t\t}\n\n\t\tpublic: const_iterator& operator+=(difference_type n)\n\t\t{\n\t\t\tif (n > 0)\n\t\t\t{\n\t\t\t\twhile (n--)\n\t\t\t\t{\n\t\t\t\t\toperator++();\n\t\t\t\t}\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\twhile (n++)\n\t\t\t\t{\n\t\t\t\t\toperator--();\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn *this;\n\t\t}\n\n\t\tpublic: const_iterator& operator-=(difference_type n)\n\t\t{\n\t\t\treturn operator+=(-n);\n\t\t}\n\n\t\tfriend\n\t\tbool operator==(const_iterator const& lhs, const_iterator const& rhs)\n\t\t{\n\t\t\treturn lhs.p_sub_ == rhs.p_sub_ && lhs.pos_ == rhs.pos_;\n\t\t}\n\n\t\tfriend\n\t\tbool operator!=(const_iterator const& lhs, const_iterator const& rhs)\n\t\t{\n\t\t\treturn !(lhs == rhs);\n\t\t}\n\n\n\t\tprivate: container_type const* p_sub_;\n\t\tprivate: size_type pos_;\n\t}; // const_iterator\n\n\n\tprivate: ::std::size_t n_; ///< The max number of elements\n\tprivate: bool empty_set_; ///< Flag to enable or disable the inclusion of the empty set\n\tprivate: impl_type bits_; ///< The subset implementation\n\tprivate: bool has_prev_;\n\tprivate: bool has_next_;\n}; // lexicographic_subset\n\n\n/**\n * \\brief Class to generate in lexicographic order all subsets of a specific size\n *\n * Given a set N={0,1,...,n-1} of n elements, this class iteratively generates\n * all subset S of N of size 0<=k<=n, in lexicographic order.\n * For instance, for a set of 4 elements, the generation of subset of size 2 in\n * lexicographic order produces the following sequence:\n * <pre>\n *  \\emptyset,\n *  {0,1},\n *  {0,2},\n *  {1,2},\n *  {0,3},\n *  {1,3},\n *  {2,3}\n * </pre>\n *\n * \\author Marco Guazzone (marco.guazzone@gmail.com)\n */\nclass lexicographic_k_subset\n{\n\tpublic: class const_iterator;\n\n\n\tfriend class const_iterator;\n\n\n\tprivate: typedef lexicographic_k_subset self_type;\n\tprivate: typedef ::boost::dynamic_bitset<> impl_type;\n\tprivate: typedef typename impl_type::size_type size_type;\n\tprivate: typedef unsigned long word_type;\n\n\n\tpublic: explicit lexicographic_k_subset(::std::size_t n, ::std::size_t k)\n\t: n_(n),\n\t  k_(k),\n\t  bits_(n, (1 << k_)-1),\n\t  has_prev_(false),\n\t  has_next_(n_ > 0 && k_ > 0 ? true : false)\n\t{\n\t\tDCS_ASSERT(n_ > 0,\n\t\t\t\t   DCS_EXCEPTION_THROW(::std::invalid_argument,\n\t\t\t\t\t\t\t\t\t   \"Number of elements must be positive\"));\n\t\tDCS_ASSERT(n_ >= k,\n\t\t\t\t   DCS_EXCEPTION_THROW(::std::invalid_argument,\n\t\t\t\t\t\t\t\t\t   \"Size of subset must be non negative\"));\n\t}\n\n\tpublic: ::std::size_t max_size() const\n\t{\n\t\treturn k_;\n\t}\n\n\tpublic: ::std::size_t size() const\n\t{\n\t\treturn bits_.count();\n\t}\n\n\tpublic: ::std::size_t count() const\n\t{\n\t\treturn static_cast<std::size_t>(boost::math::binomial_coefficient<double>(n_, k_));\n\t}\n\n\tpublic: self_type& operator++()\n\t{\n\t\tDCS_ASSERT(has_next_,\n\t\t\t\t   DCS_EXCEPTION_THROW(::std::overflow_error,\n\t\t\t\t\t\t\t\t\t   \"No following subsets\"));\n\n\t\tif (k_ > 0)\n\t\t{\n\t\t\tunsigned long v = bits_.to_ulong();\n\n\t\t\tconst unsigned long lo = v & ~(v - 1);       // lowest one bit\n\t\t\tconst unsigned long lz = (v + lo) & ~v;      // lowest zero bit above lo\n\t\t\tv |= lz;                     // add lz to the set\n\t\t\tv &= ~(lz - 1);              // reset bits below lz\n\t\t\tv |= (lz / lo / 2) - 1;      // put back right number of bits at end\n\n\t\t\thas_next_ = !(v & 1 << n_);\n\n\t\t\tif (has_next_)\n\t\t\t{\n\t\t\t\tbits_ = impl_type(n_, v);\n\t\t\t}\n\n\t\t\thas_prev_ = (bits_.to_ulong() != static_cast<unsigned long>((1 << k_)-1));\n\t\t}\n\n\t\treturn *this;\n\t}\n\n\tpublic: bool has_next() const\n\t{\n\t\treturn has_next_;\n\t}\n\n\tpublic: self_type& operator--()\n\t{\n\t\tDCS_ASSERT(has_prev_,\n\t\t\t\t   DCS_EXCEPTION_THROW(::std::underflow_error,\n\t\t\t\t\t\t\t\t\t   \"No preceding subsets\"));\n\n\t\tif (k_ > 0)\n\t\t{\n\t\t\tconst unsigned long w = bits_.to_ulong();\n\t\t\tconst unsigned long min = (1 << k_)-1;\n\t\t\tunsigned long v = min;\n\t\t\tunsigned long p = v;\n\n\t\t\twhile (v != w)\n\t\t\t{\n\t\t\t\tp = v;\n\n\t\t\t\tconst unsigned long lo = v & ~(v - 1);       // lowest one bit\n\t\t\t\tconst unsigned long lz = (v + lo) & ~v;      // lowest zero bit above lo\n\t\t\t\tv |= lz;                     // add lz to the set\n\t\t\t\tv &= ~(lz - 1);              // reset bits below lz\n\t\t\t\tv |= (lz / lo / 2) - 1;      // put back right number of bits at end\n\t\t\t}\n\n\t\t\thas_prev_ = (p != min) || (w != min);\n\n//\t\t\tif (has_prev_)\n//\t\t\t{\n\t\t\t\tbits_ = impl_type(n_, p);\n//\t\t\t}\n\n\t\t\thas_next_ = !(p & 1 << n_);\n\t\t}\n\n\t\treturn *this;\n\t}\n\n\tpublic: bool has_prev() const\n\t{\n\t\treturn has_prev_;\n\t}\n\n\t//public: template <typename ElemT, typename IterT>\n\tpublic: template <typename ElemT>\n\t\t\ttypename subset_traits<ElemT>::element_container operator()(::std::vector<ElemT> const& v) const\n\t{\n\t\tDCS_ASSERT(v.size() == n_,\n\t\t\t\t   DCS_EXCEPTION_THROW(::std::invalid_argument,\n\t\t\t\t\t\t\t\t\t   \"Size does not match\"));\n\n\t\ttypename subset_traits<ElemT>::element_container subset;\n\n\t\tfor (size_type pos = bits_.find_first();\n\t\t\t pos != impl_type::npos;\n\t\t\t pos = bits_.find_next(pos))\n\t\t{\n\t\t\tsubset.push_back(v[pos]);\n\t\t}\n\n\t\treturn subset;\n\t}\n\n\tpublic: template <typename IterT>\n\t\t\ttypename subset_traits< typename ::std::iterator_traits<IterT>::value_type >::element_container operator()(IterT first, IterT last) const\n\t{\n\t\t\treturn this->operator()(::std::vector<typename ::std::iterator_traits<IterT>::value_type>(first, last));\n\t}\n\n\tpublic: const_iterator begin() const\n\t{\n\t\treturn const_iterator(this, bits_.any() ? bits_.find_first() : impl_type::npos);\n\t}\n\n\tpublic: const_iterator end() const\n\t{\n\t\treturn const_iterator(this, impl_type::npos);\n\t}\n\n\n\tpublic: class const_iterator: public ::std::iterator< ::std::bidirectional_iterator_tag,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t typename lexicographic_k_subset::impl_type::size_type const>\n\t{\n\t\tprivate: typedef ::std::iterator< ::std::bidirectional_iterator_tag,\n\t\t\t\t\t\t\t\t\t\t  typename lexicographic_k_subset::impl_type::size_type const> base_type;\n\t\tprivate: typedef lexicographic_k_subset container_type;\n\t\tprivate: typedef typename container_type::impl_type bitset_type;\n\t\tprivate: typedef typename container_type::size_type size_type;\n\t\tpublic: typedef typename base_type::value_type value_type;\n\t\tpublic: typedef typename base_type::difference_type difference_type;\n\t\tpublic: typedef typename base_type::pointer pointer;\n\t\tpublic: typedef typename base_type::reference reference;\n\t\tpublic: typedef typename base_type::iterator_category iterator_category;\n\n\n\t\tpublic: const_iterator(container_type const* p_subset, size_type pos)\n\t\t: p_sub_(p_subset),\n\t\t  pos_(pos)\n\t\t{\n\t\t}\n\n\t\tpublic: reference operator*() const\n\t\t{\n\t\t\treturn pos_;\n\t\t}\n\n\t\tpublic: pointer operator->() const\n\t\t{\n\t\t\treturn &(operator*());\n\t\t}\n\n\t\tpublic: const_iterator& operator++()\n\t\t{\n\t\t\tpos_ = p_sub_->bits_.find_next(pos_);\n\n\t\t\treturn *this;\n\t\t}\n\n\t\tpublic: const_iterator operator++(int)\n\t\t{\n\t\t\tconst_iterator tmp = *this;\n\n\t\t\toperator++();\n\n\t\t\treturn tmp;\n\t\t}\n\n\t\tpublic: const_iterator& operator--()\n\t\t{\n\t\t\tsize_type pos = bitset_type::npos;\n\t\t\tfor (size_type pos2 = p_sub_->bits_.find_first();\n\t\t\t\t pos2 != pos_;\n\t\t\t\t pos2 = p_sub_->bits_.find_next(pos2))\n\t\t\t{\n\t\t\t\tpos = pos2;\n\t\t\t}\n\n\t\t\tpos_ = pos;\n\n\t\t\treturn *this;\n\t\t}\n\n\t\tpublic: const_iterator operator--(int)\n\t\t{\n\t\t\tconst_iterator tmp = *this;\n\n\t\t\toperator--();\n\n\t\t\treturn tmp;\n\t\t}\n\n\t\tpublic: const_iterator operator+(difference_type n) const\n\t\t{\n\t\t\tconst_iterator it = *this;\n\n\t\t\tif (n > 0)\n\t\t\t{\n\t\t\t\twhile (n--)\n\t\t\t\t{\n\t\t\t\t\t++it;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\twhile (n++)\n\t\t\t\t{\n\t\t\t\t\t--it;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn it;\n\t\t}\n\n\t\tpublic: const_iterator operator-(difference_type n) const\n\t\t{\n\t\t\treturn operator+(-n);\n\t\t}\n\n\t\tpublic: const_iterator& operator+=(difference_type n)\n\t\t{\n\t\t\tif (n > 0)\n\t\t\t{\n\t\t\t\twhile (n--)\n\t\t\t\t{\n\t\t\t\t\toperator++();\n\t\t\t\t}\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\twhile (n++)\n\t\t\t\t{\n\t\t\t\t\toperator--();\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn *this;\n\t\t}\n\n\t\tpublic: const_iterator& operator-=(difference_type n)\n\t\t{\n\t\t\treturn operator+=(-n);\n\t\t}\n\n\t\tfriend\n\t\tbool operator==(const_iterator const& lhs, const_iterator const& rhs)\n\t\t{\n\t\t\treturn lhs.p_sub_ == rhs.p_sub_ && lhs.pos_ == rhs.pos_;\n\t\t}\n\n\t\tfriend\n\t\tbool operator!=(const_iterator const& lhs, const_iterator const& rhs)\n\t\t{\n\t\t\treturn !(lhs == rhs);\n\t\t}\n\n\n\t\tprivate: container_type const* p_sub_;\n\t\tprivate: size_type pos_;\n\t}; // const_iterator\n\n\n\tprivate: ::std::size_t n_; ///< The number of elements of the set\n\tprivate: ::std::size_t k_; ///< The max number of elements of the subset\n\tprivate: impl_type bits_; ///< The subset implementation\n\tprivate: bool has_prev_;\n\tprivate: bool has_next_;\n}; // lexicographic_k_subset\n\n\ntemplate <typename CharT, typename CharTraitsT>\n::std::basic_ostream<CharT,CharTraitsT>& operator<<(::std::basic_ostream<CharT,CharTraitsT>& os,\n\t\t\t\t\t\t\t\t\t\t\t\t\tlexicographic_subset const& subset)\n{\n\tos << '(';\n\n\tif (subset.size() > 0)\n\t{\n\t\tif (subset.size() > 1)\n\t\t{\n\t\t\t::std::copy(subset.begin(),\n\t\t\t\t\t\tsubset.end()-1,\n\t\t\t\t\t\t::std::ostream_iterator< ::std::size_t >(os, \" \"));\n\t\t}\n\n\t\tos << *(subset.end()-1);\n\t}\n\n\tos << ')';\n\n\treturn os;\n}\n\ntemplate <typename CharT, typename CharTraitsT>\n::std::basic_ostream<CharT,CharTraitsT>& operator<<(::std::basic_ostream<CharT,CharTraitsT>& os,\n\t\t\t\t\t\t\t\t\t\t\t\t\tlexicographic_k_subset const& subset)\n{\n\tos << '(';\n\n\tif (subset.size() > 0)\n\t{\n\t\tif (subset.size() > 1)\n\t\t{\n\t\t\t::std::copy(subset.begin(),\n\t\t\t\t\t\tsubset.end()-1,\n\t\t\t\t\t\t::std::ostream_iterator< ::std::size_t >(os, \" \"));\n\t\t}\n\n\t\tos << *(subset.end()-1);\n\t}\n\n\tos << ')';\n\n\treturn os;\n}\n\ntemplate <typename BidiIterT, typename SubsetT>\ninline\ntypename subset_traits< typename ::std::iterator_traits<BidiIterT>::value_type >::element_container\nnext_subset(BidiIterT first,\n\t\t\tBidiIterT last,\n\t\t\tSubsetT& subset)\n{\n\ttypedef typename ::std::iterator_traits<BidiIterT>::value_type value_type;\n\ttypedef typename subset_traits<value_type>::element_container element_container;\n\n\telement_container subs = subset(first, last);\n\n\t++subset;\n\n\treturn subs;\n}\n\ntemplate <typename BidiIterT, typename SubsetT>\ninline\ntypename subset_traits< typename ::std::iterator_traits<BidiIterT>::value_type >::element_container\nprev_subset(BidiIterT first,\n\t\t\tBidiIterT last,\n\t\t\tSubsetT& subset)\n{\n\ttypedef typename ::std::iterator_traits<BidiIterT>::value_type value_type;\n\ttypedef typename subset_traits<value_type>::element_container element_container;\n\n\telement_container subs = subset(first, last);\n\n\t--subset;\n\n\treturn subs;\n}\n\n/*\ninline\n::std::size_t count_subsets(n)\n{\n\tconst ::std::size_t m = n >> 1;\n\tconst bool flag = ((m << 1) - n) > 0;\n\n\t::std::size_t c = 0;\n\tfor (std::size_t i = 0; i < m; ++i)\n\t{\n\t\tc += \n\t}\n}\n*/\n\n}} // Namespace dcs::algorithm\n\n#endif // DCS_COMMONS_ALGORITHM_SUBSET_HPP\n", "meta": {"hexsha": "ad35dd7848de1764f932c3c32728c7bab630365a", "size": 17886, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "inc/dcs/algorithm/subset.hpp", "max_stars_repo_name": "sguazt/dcsxx-commons", "max_stars_repo_head_hexsha": "0fc1fd8a38b7c412941b401c00a9293bc5df8b21", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-03-26T19:03:40.000Z", "max_stars_repo_stars_event_max_datetime": "2019-03-26T19:03:40.000Z", "max_issues_repo_path": "include/dcs/algorithm/subset.hpp", "max_issues_repo_name": "sguazt/fog-gt", "max_issues_repo_head_hexsha": "92a01de4f3d71bf89741c7e4af1bebb965c64d28", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/dcs/algorithm/subset.hpp", "max_forks_repo_name": "sguazt/fog-gt", "max_forks_repo_head_hexsha": "92a01de4f3d71bf89741c7e4af1bebb965c64d28", "max_forks_repo_licenses": ["Apache-2.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.2186335404, "max_line_length": 140, "alphanum_fraction": 0.6574974841, "num_tokens": 4992, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.6477982315512488, "lm_q1q2_score": 0.33401766955797346}}
{"text": "///////////////////////////////////////////////////////////////////////////////\r\n/// \\file numeric.hpp\r\n/// Defined the mathematical operator s on time 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_NUMERIC_EAN_04_27_2006\r\n#define BOOST_TIME_SERIES_NUMERIC_NUMERIC_EAN_04_27_2006\r\n\r\n#include <utility>\r\n#include <boost/mpl/assert.hpp>\r\n#include <boost/mpl/placeholders.hpp>\r\n#include <boost/utility/enable_if.hpp>\r\n#include <boost/type_traits/is_same.hpp>\r\n#include <boost/numeric/functional.hpp>\r\n#include <boost/range_run_storage/algorithm/transform.hpp>\r\n#include <boost/time_series/time_series_fwd.hpp>\r\n#include <boost/time_series/concepts.hpp>\r\n#include <boost/time_series/traits/generate_series.hpp>\r\n#include <boost/time_series/traits/promotion.hpp>\r\n#include <boost/time_series/scaled_series.hpp>\r\n#include <boost/time_series/numeric/detail/zero.hpp>\r\n#include <boost/detail/construct.hpp>\r\n\r\nnamespace boost { namespace time_series\r\n{\r\n    namespace detail\r\n    {\r\n        namespace rrs = range_run_storage;\r\n\r\n        using concepts::Run;\r\n        using concepts::TimeSeries;\r\n        using concepts::Mutable_TimeSeries;\r\n\r\n        template<typename Out, typename Left, typename Right, typename BinOp>\r\n        Out &run_bin_op_union(Out &out, Left &left, Right &right, BinOp const &binop)\r\n        {\r\n            typename Mutable_TimeSeries<Out>::ordered_inserter_type\r\n                o(rrs::ordered_inserter(out));\r\n\r\n            rrs::commit(\r\n                rrs::transform(left, right, binop, o)\r\n            );\r\n\r\n            return out;\r\n        }\r\n\r\n        // For operations that are only defined\r\n        template<typename Out, typename Left, typename Right, typename BinOp>\r\n        Out &run_bin_op_intersection(Out &out, Left &left, Right &right, BinOp const &binop)\r\n        {\r\n            typename Mutable_TimeSeries<Out>::ordered_inserter_type\r\n                o(rrs::ordered_inserter(out));\r\n\r\n            rrs::commit(\r\n                rrs::transform(left, right, binop, rrs::skip, rrs::skip, o)\r\n            );\r\n\r\n            return out;\r\n        }\r\n\r\n        // operation traits\r\n        template<typename S1, typename S2, typename Gen, typename Op, typename Disc>\r\n        struct operation_traits_base\r\n        {\r\n            typedef typename TimeSeries<S1>::storage_category storage1_tag;\r\n            typedef typename TimeSeries<S2>::storage_category storage2_tag;\r\n            typedef typename mpl::apply<Gen, storage1_tag, storage2_tag>::type storage_category;\r\n\r\n            typedef typename TimeSeries<S1>::value_type value1_type;\r\n            typedef typename TimeSeries<S2>::value_type value2_type;\r\n            typedef typename result_of<Op(value1_type, value2_type)>::type value_type;\r\n\r\n            typedef typename TimeSeries<S1>::offset_type offset1_type;\r\n            typedef typename TimeSeries<S2>::offset_type offset2_type;\r\n            BOOST_MPL_ASSERT((is_same<offset1_type, offset2_type>)); // is there a better option?\r\n            typedef offset1_type offset_type;\r\n            \r\n            typedef typename traits::generate_series<\r\n                storage_category, value_type, Disc, offset_type\r\n            >::type result_type;\r\n        };\r\n\r\n        template<typename S1, typename S2, typename Gen, typename Op\r\n          , typename Disc1 = typename TimeSeries<S1>::discretization_type\r\n          , typename Disc2 = typename TimeSeries<S2>::discretization_type\r\n        >\r\n        struct operation_traits\r\n        {};\r\n\r\n        template<typename S1, typename S2, typename Gen, typename Op, typename Disc>\r\n        struct operation_traits<S1, S2, Gen, Op, time_series::any, Disc>\r\n          : operation_traits_base<S1, S2, Gen, Op, Disc>\r\n        {};\r\n\r\n        template<typename S1, typename S2, typename Gen, typename Op, typename Disc>\r\n        struct operation_traits<S1, S2, Gen, Op, Disc, time_series::any>\r\n          : operation_traits_base<S1, S2, Gen, Op, Disc>\r\n        {};\r\n\r\n        template<typename S1, typename S2, typename Gen, typename Op>\r\n        struct operation_traits<S1, S2, Gen, Op, time_series::any, time_series::any>\r\n          : operation_traits_base<S1, S2, Gen, Op, time_series::any>\r\n        {};\r\n\r\n        template<typename S1, typename S2, typename Gen, typename Op, typename Disc>\r\n        struct operation_traits<S1, S2, Gen, Op, Disc, Disc>\r\n          : operation_traits_base<S1, S2, Gen, Op, Disc>\r\n        {};\r\n\r\n        template<typename Left, typename Right, typename Op>\r\n        typename result_of<Op(\r\n            typename TimeSeries<Left>::value_type const &\r\n          , typename TimeSeries<Right>::value_type const &\r\n        )>::type\r\n        make_zero(Left &left, Right &right, Op op)\r\n        {\r\n            typename TimeSeries<Left>::value_type const &left_zero = rrs::zero(left);\r\n            typename TimeSeries<Right>::value_type const &right_zero = rrs::zero(right);\r\n            return op(left_zero, right_zero);\r\n        }\r\n\r\n        template<typename Discretization>\r\n        Discretization make_discretization(Discretization left, Discretization right)\r\n        {\r\n            BOOST_ASSERT(left == right);\r\n            return left;\r\n        }\r\n\r\n        template<typename Discretization>\r\n        Discretization make_discretization(Discretization left, time_series::any)\r\n        {\r\n            return left;\r\n        }\r\n\r\n        template<typename Discretization>\r\n        Discretization make_discretization(time_series::any, Discretization right)\r\n        {\r\n            return right;\r\n        }\r\n\r\n        inline time_series::any make_discretization(time_series::any, time_series::any)\r\n        {\r\n            return time_series::any();\r\n        }\r\n\r\n    } // namespace detail\r\n\r\n    using mpl::_;\r\n\r\n    ///////////////////////////////////////////////////////////////////////////\r\n    // operator +\r\n    template<typename Left, typename Right>\r\n    typename detail::operation_traits<Left, Right, traits::plus<_, _>, numeric::op::plus>::result_type\r\n    operator +(time_series_base<Left> const &left, time_series_base<Right> const &right)\r\n    {\r\n        typedef detail::operation_traits<Left, Right, traits::plus<_, _>, numeric::op::plus> op_traits;\r\n        typedef typename op_traits::result_type result_type;\r\n\r\n        result_type result(constructors::construct<result_type>(\r\n            time_series::discretization\r\n              = detail::make_discretization(left.cast().discretization(), right.cast().discretization())\r\n          , time_series::zero\r\n              = detail::make_zero(left.cast(), right.cast(), numeric::plus)\r\n        ));\r\n\r\n        return detail::run_bin_op_union(result, left.cast(), right.cast(), numeric::plus);\r\n    }\r\n\r\n    ///////////////////////////////////////////////////////////////////////////\r\n    // operator -\r\n    template<typename Left, typename Right>\r\n    typename detail::operation_traits<Left, Right, traits::minus<_, _>, numeric::op::minus>::result_type\r\n    operator -(time_series_base<Left> const &left, time_series_base<Right> const &right)\r\n    {\r\n        typedef detail::operation_traits<Left, Right, traits::minus<_, _>, numeric::op::minus> op_traits;\r\n        typedef typename op_traits::result_type result_type;\r\n\r\n        result_type result(constructors::construct<result_type>(\r\n            time_series::discretization\r\n              = detail::make_discretization(left.cast().discretization(), right.cast().discretization())\r\n          , time_series::zero\r\n              = detail::make_zero(left.cast(), right.cast(), numeric::minus)\r\n        ));\r\n\r\n        return detail::run_bin_op_union(result, left.cast(), right.cast(), numeric::minus);\r\n    }\r\n\r\n    ///////////////////////////////////////////////////////////////////////////\r\n    // operator *\r\n    template<typename Left, typename Right>\r\n    typename detail::operation_traits<Left, Right, traits::multiplies<_, _>, numeric::op::multiplies>::result_type\r\n    operator *(time_series_base<Left> const &left, time_series_base<Right> const &right)\r\n    {\r\n        typedef detail::operation_traits<Left, Right, traits::multiplies<_, _>, numeric::op::multiplies> op_traits;\r\n        typedef typename op_traits::result_type result_type;\r\n\r\n        result_type result(constructors::construct<result_type>(\r\n            time_series::discretization\r\n              = detail::make_discretization(left.cast().discretization(), right.cast().discretization())\r\n          , time_series::zero\r\n              = detail::make_zero(left.cast(), right.cast(), numeric::multiplies)\r\n        ));\r\n\r\n        return detail::run_bin_op_intersection(result, left.cast(), right.cast(), numeric::multiplies);\r\n    }\r\n\r\n    ///////////////////////////////////////////////////////////////////////////\r\n    // operator /\r\n    template<typename Left, typename Right>\r\n    typename detail::operation_traits<Left, Right, traits::divides<_, _>, numeric::op::divides>::result_type\r\n    operator /(time_series_base<Left> const &left, time_series_base<Right> const &right)\r\n    {\r\n        typedef detail::operation_traits<Left, Right, traits::divides<_, _>, numeric::op::divides> op_traits;\r\n        typedef typename op_traits::result_type result_type;\r\n\r\n        // BUGBUG possible divide by zero, so use multiplies instead of divides here ...\r\n        result_type result(constructors::construct<result_type>(\r\n            time_series::discretization\r\n              = detail::make_discretization(left.cast().discretization(), right.cast().discretization())\r\n          , time_series::zero\r\n              = detail::make_zero(left.cast(), right.cast(), numeric::multiplies)\r\n        ));\r\n\r\n        return detail::run_bin_op_intersection(result, left.cast(), right.cast(), numeric::divides);\r\n    }\r\n\r\n    ///////////////////////////////////////////////////////////////////////////\r\n    // operator +=\r\n    template<typename Left, typename Right>\r\n    Left &operator +=(time_series_base<Left> &left, time_series_base<Right> const &right)\r\n    {\r\n        BOOST_MPL_ASSERT((is_same<\r\n            typename concepts::TimeSeries<Left>::discretization_type\r\n          , typename concepts::TimeSeries<Right>::discretization_type\r\n        >));\r\n\r\n        // TODO also add the series zero\r\n        BOOST_ASSERT(left.cast().discretization() == right.cast().discretization());\r\n        return detail::run_bin_op_union(left.cast(), left.cast(), right.cast(), numeric::plus);\r\n    }\r\n\r\n    ///////////////////////////////////////////////////////////////////////////\r\n    // operator -=\r\n    template<typename Left, typename Right>\r\n    Left &operator -=(time_series_base<Left> &left, time_series_base<Right> const &right)\r\n    {\r\n        BOOST_MPL_ASSERT((is_same<\r\n            typename concepts::TimeSeries<Left>::discretization_type\r\n          , typename concepts::TimeSeries<Right>::discretization_type\r\n        >));\r\n\r\n        // TODO also subtract the series zero\r\n        BOOST_ASSERT(left.cast().discretization() == right.cast().discretization());\r\n        return detail::run_bin_op_union(left.cast(), left.cast(), right.cast(), numeric::minus);\r\n    }\r\n\r\n    ///////////////////////////////////////////////////////////////////////////\r\n    // operator *=\r\n    template<typename Left, typename Right>\r\n    Left &operator *=(time_series_base<Left> &left, time_series_base<Right> const &right)\r\n    {\r\n        BOOST_MPL_ASSERT((is_same<\r\n            typename concepts::TimeSeries<Left>::discretization_type\r\n          , typename concepts::TimeSeries<Right>::discretization_type\r\n        >));\r\n\r\n        BOOST_ASSERT(left.cast().discretization() == right.cast().discretization());\r\n\r\n        // BUGBUG not optimal\r\n        Left result(constructors::construct<Left>(\r\n            time_series::discretization\r\n              = detail::make_discretization(left.cast().discretization(), right.cast().discretization())\r\n          , time_series::zero\r\n              = detail::make_zero(left.cast(), right.cast(), numeric::multiplies)\r\n        ));\r\n\r\n        left.cast().swap(detail::run_bin_op_intersection(result, left.cast(), right.cast(), numeric::multiplies));\r\n        return left.cast();\r\n    }\r\n\r\n    ///////////////////////////////////////////////////////////////////////////\r\n    // operator /=\r\n    template<typename Left, typename Right>\r\n    Left &operator /=(time_series_base<Left> &left, time_series_base<Right> const &right)\r\n    {\r\n        BOOST_MPL_ASSERT((is_same<\r\n            typename concepts::TimeSeries<Left>::discretization_type\r\n          , typename concepts::TimeSeries<Right>::discretization_type\r\n        >));\r\n\r\n        BOOST_MPL_ASSERT((traits::is_valid_divisor<\r\n            typename concepts::TimeSeries<Right>::storage_category\r\n        >));\r\n\r\n        BOOST_ASSERT(left.cast().discretization() == right.cast().discretization());\r\n\r\n        // BUGBUG not optimal\r\n        // BUGBUG possible divide by zero, so use multiplies instead of divides here ...\r\n        Left result(constructors::construct<Left>(\r\n            time_series::discretization\r\n              = detail::make_discretization(left.cast().discretization(), right.cast().discretization())\r\n          , time_series::zero\r\n              = detail::make_zero(left.cast(), right.cast(), numeric::multiplies)\r\n        ));\r\n\r\n        left.cast().swap(detail::run_bin_op_intersection(result, left.cast(), right.cast(), numeric::divides));\r\n        return left.cast();\r\n    }\r\n\r\n    ///////////////////////////////////////////////////////////////////////////\r\n    // operator * (with scalar)\r\n    template<typename Series, typename Factor>\r\n    typename disable_if<\r\n        traits::is_time_series<Factor>\r\n      , scaled_series<Series const, Factor> const\r\n    >::type\r\n    operator *(time_series_base<Series> const &left, Factor const &right)\r\n    {\r\n        return scaled_series<Series const, Factor>(left.cast(), right);\r\n    }\r\n\r\n    ///////////////////////////////////////////////////////////////////////////\r\n    // operator * (with scalar)\r\n    template<typename Factor, typename Series>\r\n    typename disable_if<\r\n        traits::is_time_series<Factor>\r\n      , scaled_series<Series const, Factor> const\r\n    >::type\r\n    operator *(Factor const &left, time_series_base<Series> const &right)\r\n    {\r\n        return scaled_series<Series const, Factor>(right.cast(), left);\r\n    }\r\n\r\n    ///////////////////////////////////////////////////////////////////////////\r\n    // operator *= (with scalar)\r\n    template<typename Series, typename Factor>\r\n    typename disable_if<\r\n        traits::is_time_series<Factor>\r\n      , Series &\r\n    >::type\r\n    operator *=(time_series_base<Series> &left, Factor const &right)\r\n    {\r\n        left.cast() = left.cast() * right;\r\n        return left.cast();\r\n    }\r\n\r\n}} // namespace boost::time_series\r\n\r\n#endif\r\n", "meta": {"hexsha": "bb583fc571b8f692c0e3a04970e0ddd84bc8b17d", "size": 14909, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/time_series/numeric/numeric.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/numeric.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/numeric.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": 42.2351274788, "max_line_length": 116, "alphanum_fraction": 0.5970219331, "num_tokens": 3101, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6334102636778401, "lm_q2_score": 0.5273165233795671, "lm_q1q2_score": 0.3340076981155336}}
{"text": "#include \"lenslet_graph.h\"\n\n#include <Eigen/Dense>\n\nnamespace lightfields {\n\nnamespace {\n\nstruct Vec2Compare {\n\tbool operator()(const cv::Vec2f& v1, const cv::Vec2f& v2) const {\n\t\tif(v1[0] != v2[0])\n\t\t\treturn v1[0] < v2[0];\n\t\treturn v1[1] < v2[1];\n\t}\n};\n\nstruct Lenslet {\n\tLenslet(const cv::Vec2f& c) : center(c), neighbourCount(0), id(INT_MIN, INT_MIN) {\n\t}\n\n\tvoid addNeighbour(std::size_t index) {\n\t\tif(neighbourCount >= 6)\n\t\t\tthrow std::runtime_error(\n\t\t\t    \"Lenslets should be organized in a hexagonal grid, which does not seem to be the case!\");\n\n\t\tneighbours[neighbourCount] = index;\n\t\t++neighbourCount;\n\t}\n\n\tcv::Vec2f center;\n\tstd::array<std::size_t, 6> neighbours;\n\tunsigned char neighbourCount;\n\tcv::Vec2i id;\n};\n\n}  // namespace\n\n/////////////\n\nstruct LensletGraph::Pimpl {\n\tPimpl() : fitted(false) {\n\t}\n\n\tImath::V2i sensorSize;\n\tint exclusionBorder;\n\n\tstd::vector<Lenslet> lenslets;\n\n\tcv::Matx<double, 3, 3> fittedMatrix;\n\tbool fitted;\n};\n\n/////////////\n\nLensletGraph::LensletGraph(Imath::V2i sensorSize, int exclusionBorder) : m_pimpl(new Pimpl()) {\n\tm_pimpl->sensorSize = sensorSize;\n\tm_pimpl->exclusionBorder = exclusionBorder;\n}\n\nLensletGraph::~LensletGraph() {\n}\n\nvoid LensletGraph::addLenslet(const cv::Vec2f& center) {\n\tm_pimpl->lenslets.push_back(Lenslet(center));\n}\n\nnamespace {\n\n/// computes relative integer offset between two lenslets (assumed to be neighbouring edges of a graph)\ncv::Vec2i offset(const cv::Vec2f& l1, const cv::Vec2f& l2) {\n\tconst float angle = atan2(l2[1] - l1[1], l2[0] - l1[0]) / M_PI * 6.0f;\n\tassert(angle >= -6.0f && angle <= 6.0f);\n\n\tif(angle < -5.0f || angle > 5.0f)\n\t\treturn cv::Vec2i(-1, 0);\n\n\tif(angle < -3.0f)\n\t\treturn cv::Vec2i(0, -1);\n\n\tif(angle > 3.0f)\n\t\treturn cv::Vec2i(-1, 1);\n\n\tif(angle < -1.0f)\n\t\treturn cv::Vec2i(1, -1);\n\n\tif(angle > 1.0f)\n\t\treturn cv::Vec2i(0, 1);\n\n\treturn cv::Vec2i(1, 0);\n}\n\n}  // namespace\n\nvoid LensletGraph::fit() {\n\tassert(!m_pimpl->fitted);\n\n\t// build the subdiv and index\n\tstd::map<cv::Vec2f, std::size_t, Vec2Compare> index;\n\n\tcv::Subdiv2D subdiv(cv::Rect(0, 0, m_pimpl->sensorSize[0], m_pimpl->sensorSize[1]));\n\tfor(auto& l : m_pimpl->lenslets) {\n\t\tsubdiv.insert(cv::Point2f(l.center[0], l.center[1]));\n\t\tindex.insert(std::make_pair(cv::Point2f(l.center[0], l.center[1]), index.size()));\n\t}\n\n\t// collect and process the edges\n\t{\n\t\tstd::vector<cv::Vec4f> srcEdgeList;\n\t\tsubdiv.getEdgeList(srcEdgeList);\n\n\t\tfor(auto eit = srcEdgeList.begin(); eit != srcEdgeList.end(); ++eit) {\n\t\t\tauto& e = *eit;\n\n\t\t\tif(e[0] > m_pimpl->exclusionBorder && e[0] < m_pimpl->sensorSize[0] - m_pimpl->exclusionBorder &&\n\t\t\t   e[1] > m_pimpl->exclusionBorder && e[1] < m_pimpl->sensorSize[1] - m_pimpl->exclusionBorder &&\n\t\t\t   e[2] > m_pimpl->exclusionBorder && e[2] < m_pimpl->sensorSize[0] - m_pimpl->exclusionBorder &&\n\t\t\t   e[3] > m_pimpl->exclusionBorder && e[3] < m_pimpl->sensorSize[1] - m_pimpl->exclusionBorder) {\n\t\t\t\tauto it1 = index.find(cv::Point2f(e[0], e[1]));\n\t\t\t\tauto it2 = index.find(cv::Point2f(e[2], e[3]));\n\t\t\t\tassert(it1 != index.end() && it2 != index.end());\n\n\t\t\t\tm_pimpl->lenslets[it1->second].addNeighbour(it2->second);\n\t\t\t\tm_pimpl->lenslets[it2->second].addNeighbour(it1->second);\n\t\t\t}\n\t\t}\n\t}\n\n\t// propagate IDs\n\t{\n\t\t// find first connected lenslet\n\t\tauto it = m_pimpl->lenslets.begin();\n\t\twhile(it != m_pimpl->lenslets.end() && it->neighbourCount == 0)\n\t\t\t++it;\n\n\t\tif(it != m_pimpl->lenslets.end()) {\n\t\t\t// this lenslet is the \"origin\" now\n\t\t\tit->id = cv::Vec2i(0, 0);\n\n\t\t\t// initialise the edges (to-be-processed) list\n\t\t\tstd::vector<std::pair<std::size_t, std::size_t>> edges;\n\t\t\tfor(std::size_t n = 0; n < it->neighbourCount; ++n)\n\t\t\t\tedges.push_back(std::make_pair(it - m_pimpl->lenslets.begin(), it->neighbours[n]));\n\n\t\t\twhile(!edges.empty()) {\n\t\t\t\t// get the processed edge\n\t\t\t\tauto edge = edges.back();\n\t\t\t\tedges.pop_back();\n\n\t\t\t\tconst Lenslet& source = m_pimpl->lenslets[edge.first];\n\t\t\t\tLenslet& target = m_pimpl->lenslets[edge.second];\n\n\t\t\t\t// assert the \"origin\" lenslet, which should have been processed already\n\t\t\t\tassert(source.id[0] > INT_MIN && source.id[1] > INT_MIN);\n\n\t\t\t\t// get the \"offset\" based on edge direction\n\t\t\t\tconst cv::Vec2i off = offset(source.center, target.center);\n\n\t\t\t\t// either set the target, or assert its value is right\n\t\t\t\tif(target.id[0] > INT_MIN) {\n\t\t\t\t\tassert(target.id[0] == source.id[0] + off[0]);\n\t\t\t\t\tassert(target.id[1] == source.id[1] + off[1]);\n\t\t\t\t}\n\n\t\t\t\telse {\n\t\t\t\t\ttarget.id[0] = source.id[0] + off[0];\n\t\t\t\t\ttarget.id[1] = source.id[1] + off[1];\n\n\t\t\t\t\t// recursively continue around all edges of the target\n\t\t\t\t\tfor(std::size_t n = 0; n < target.neighbourCount; ++n)\n\t\t\t\t\t\tedges.push_back(std::make_pair(edge.second, target.neighbours[n]));\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// least squares fit\n\t// Ref: Fitting a Transformation: Feature-based Alignment, Kristen Grauman, lecture notes for UT Austin\n\t// A = [ ...\n\t//       xi, yi,  0,  0, 1, 0,\n\t//        0,  0, xi, yi, 0, 1,\n\t//       ... ]\n\t// x = [m1, m2, m3, m4, t1, t2]^T\n\t// b = [ ... x'i, y'i, ... ]^T\n\n\t// count the useful lenslets\n\tstd::size_t lensletCount = 0;\n\tfor(auto& l : m_pimpl->lenslets)\n\t\tif(l.id[0] > INT_MIN)\n\t\t\t++lensletCount;\n\n\tEigen::MatrixXd A(2 * lensletCount, 6);\n\tEigen::VectorXd b(2 * lensletCount);\n\tlensletCount = 0;\n\tfor(auto& l : m_pimpl->lenslets)\n\t\tif(l.id[0] > INT_MIN) {\n\t\t\tstd::size_t rowId = lensletCount * 2;\n\n\t\t\tA(rowId, 0) = l.center[0];\n\t\t\tA(rowId, 1) = l.center[1];\n\t\t\tA(rowId, 2) = 0;\n\t\t\tA(rowId, 3) = 0;\n\t\t\tA(rowId, 4) = 1;\n\t\t\tA(rowId, 5) = 0;\n\n\t\t\tb(rowId) = l.id[0];\n\n\t\t\t++rowId;\n\n\t\t\tA(rowId, 0) = 0;\n\t\t\tA(rowId, 1) = 0;\n\t\t\tA(rowId, 2) = l.center[0];\n\t\t\tA(rowId, 3) = l.center[1];\n\t\t\tA(rowId, 4) = 0;\n\t\t\tA(rowId, 5) = 1;\n\n\t\t\tb(rowId) = l.id[1];\n\n\t\t\t++lensletCount;\n\t\t}\n\n\tEigen::VectorXd x = A.bdcSvd(Eigen::ComputeThinU | Eigen::ComputeThinV).solve(b);\n\tassert(x.size() == 6);\n\n\tm_pimpl->fitted = true;\n\tm_pimpl->fittedMatrix = cv::Matx<double, 3, 3>(x[0], x[2], 0, x[1], x[3], 0, x[4], x[5], 1);\n}\n\ndouble LensletGraph::lensPitch() const {\n\tstd::size_t counter = 0;\n\tdouble average = 0.0;\n\n\tfor(auto& l : m_pimpl->lenslets)\n\t\tif(l.id[0] > INT_MIN) {\n\t\t\tfor(unsigned char ni = 0; ni < l.neighbourCount; ++ni) {\n\t\t\t\tconst Lenslet& neighbour = m_pimpl->lenslets[l.neighbours[ni]];\n\t\t\t\tif(neighbour.id[0] > INT_MIN) {\n\t\t\t\t\t++counter;\n\t\t\t\t\taverage += cv::norm(l.center - neighbour.center);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\tassert(counter > 0);\n\n\treturn average / (double)counter;\n}\n\nconst Imath::V2i& LensletGraph::sensorResolution() const {\n\treturn m_pimpl->sensorSize;\n}\n\nconst cv::Matx<double, 3, 3>& LensletGraph::fittedMatrix() const {\n\tassert(m_pimpl->fitted);\n\treturn m_pimpl->fittedMatrix;\n}\n\nvoid LensletGraph::drawCenters(cv::Mat& target) const {\n\tassert(target.rows == m_pimpl->sensorSize[0] && target.cols == m_pimpl->sensorSize[1]);\n\tassert(target.type() == CV_8UC1);\n\n\tfor(auto& l : m_pimpl->lenslets)\n\t\ttarget.at<unsigned char>(l.center[1], l.center[0]) = 255;\n}\n\nvoid LensletGraph::drawEdges(cv::Mat& target) const {\n\tassert(target.rows == m_pimpl->sensorSize[0] && target.cols == m_pimpl->sensorSize[1]);\n\tassert(target.type() == CV_8UC1);\n\n\tfor(auto& l1 : m_pimpl->lenslets) {\n\t\tfor(unsigned char n = 0; n < l1.neighbourCount; ++n) {\n\t\t\tauto& l2 = m_pimpl->lenslets[l1.neighbours[n]];\n\n\t\t\tconst float a = atan((l2.center[1] - l1.center[1]) / (l2.center[0] - l1.center[0])) / M_PI * 2.0;\n\n\t\t\tfloat color = 155.0;\n\t\t\tif(a < -0.33)\n\t\t\t\tcolor = 55.0;\n\t\t\tif(a > 0.33)\n\t\t\t\tcolor = 255;\n\n\t\t\tcv::line(target, cv::Point2i(l1.center[0], l1.center[1]), cv::Point2i(l2.center[0], l2.center[1]),\n\t\t\t         cv::Scalar(color));\n\t\t}\n\t}\n}\n\nvoid LensletGraph::drawFit(cv::Mat& target) const {\n\tassert(target.rows == m_pimpl->sensorSize[0] && target.cols == m_pimpl->sensorSize[1]);\n\tassert(target.type() == CV_8UC1);\n\n\tfor(auto& l : m_pimpl->lenslets)\n\t\tcv::circle(target, cv::Point(l.center[0], l.center[1]), 2, (l.id[0] + 2560) % 256, 2);\n}\n\n}  // namespace lightfields\n", "meta": {"hexsha": "0475cb9de3a4b2cd5aa7710a6340d96cb976926e", "size": 7886, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/libs/lightfields/lenslet_graph.cpp", "max_stars_repo_name": "martin-pr/possumwood", "max_stars_repo_head_hexsha": "0ee3e0fe13ef27cf14795a79fb497e4d700bef63", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 232.0, "max_stars_repo_stars_event_min_datetime": "2017-10-09T11:45:28.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T11:14:46.000Z", "max_issues_repo_path": "src/libs/lightfields/lenslet_graph.cpp", "max_issues_repo_name": "LIUJUN-liujun/possumwood", "max_issues_repo_head_hexsha": "745e48eb44450b0b7f078ece81548812ab1ccc63", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 26.0, "max_issues_repo_issues_event_min_datetime": "2019-01-20T21:38:25.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-16T03:57:17.000Z", "max_forks_repo_path": "src/libs/lightfields/lenslet_graph.cpp", "max_forks_repo_name": "LIUJUN-liujun/possumwood", "max_forks_repo_head_hexsha": "745e48eb44450b0b7f078ece81548812ab1ccc63", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 33.0, "max_forks_repo_forks_event_min_datetime": "2017-10-26T19:20:38.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-16T11:21:43.000Z", "avg_line_length": 26.6418918919, "max_line_length": 104, "alphanum_fraction": 0.6256657367, "num_tokens": 2767, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6334102636778401, "lm_q2_score": 0.5273165233795671, "lm_q1q2_score": 0.3340076981155336}}
{"text": "#include <memory>\n#include <Eigen/MatrixFunctions>\n#include \"Basis.hh\"\n#include \"Dispatcher.hh\"\n#include \"io/manipulators.hh\"\n\nvoid Basis::twoElectron(const Eigen::MatrixXd& D, Eigen::MatrixXd& G) const\n{\n\tif (!_status.test(ELEC_REP_CURRENT))\n\t\tcalcElectronRepulsion();\n\n\tint n = D.rows();\n#ifdef DEBUG\n\tif (D.cols() != n)\n\t\tthrow Li::Exception(\"Density matrix is not square\");\n#endif\n\tG.resize(n, n);\n\tG.setZero();\n\tint idx = 0;\n\tdouble e;\n\tfor (int i = 0; i < n; ++i)\n\t{\n\t\tdouble Dii = D(i,i);\n\t\tfor (int j = 0; j < i; ++j)\n\t\t{\n\t\t\tdouble Dij = D(i,j);\n\t\t\tdouble Djj = D(j,j);\n\t\t\tfor (int k = 0; k < j; ++k)\n\t\t\t{\n\t\t\t\tdouble Dik = D(i,k);\n\t\t\t\tdouble Djk = D(j,k);\n\t\t\t\tfor (int l = 0; l < k; ++l)\n\t\t\t\t{\n\t\t\t\t\te = _elec_rep(idx++);\n\t\t\t\t\tG(i,j) += 2 * D(k,l) * e;\n\t\t\t\t\tG(i,k) -= 0.5 * D(j,l) * e;\n\t\t\t\t\tG(i,l) -= 0.5 * Djk * e;\n\t\t\t\t\tG(j,k) -= 0.5 * D(i,l) * e;\n\t\t\t\t\tG(j,l) -= 0.5 * Dik * e;\n\t\t\t\t\tG(k,l) += 2 * Dij * e;\n\t\t\t\t}\n\t\t\t\te = _elec_rep(idx++);\n\t\t\t\tG(i,j) += D(k,k) * e;\n\t\t\t\tG(i,k) -= 0.5 * Djk * e;\n\t\t\t\tG(j,k) -= 0.5 * Dik * e;\n\t\t\t\tG(k,k) += 2 * Dij * e;\n\t\t\t}\n\t\t\tfor (int l = 0; l < j; ++l)\n\t\t\t{\n\t\t\t\te = _elec_rep(idx++);\n\t\t\t\tG(i,j) += 1.5 * D(j,l) * e;\n\t\t\t\tG(i,l) -= 0.5 * Djj * e;\n\t\t\t\tG(j,j) -= D(i,l) * e;\n\t\t\t\tG(j,l) += 1.5 * Dij * e;\n\t\t\t}\n\t\t\te = _elec_rep(idx++);\n\t\t\tG(i,j) += 0.5 * Djj * e;\n\t\t\tG(j,j) += Dij * e;\n\t\t\tfor (int k = j+1; k < i; ++k)\n\t\t\t{\n\t\t\t\tdouble Dik = D(i,k);\n\t\t\t\tdouble Dkj = D(k,j);\n\t\t\t\tfor (int l = 0; l < j; ++l)\n\t\t\t\t{\n\t\t\t\t\te = _elec_rep(idx++);\n\t\t\t\t\tG(i,j) += 2 * D(k,l) * e;\n\t\t\t\t\tG(i,k) -= 0.5 * D(j,l) * e;\n\t\t\t\t\tG(i,l) -= 0.5 * Dkj * e;\n\t\t\t\t\tG(j,l) -= 0.5 * Dik * e;\n\t\t\t\t\tG(k,j) -= 0.5 * D(i,l) * e;\n\t\t\t\t\tG(k,l) += 2 * Dij * e;\n\t\t\t\t}\n\t\t\t\te = _elec_rep(idx++);\n\t\t\t\tG(i,j) += 1.5 * Dkj * e;\n\t\t\t\tG(i,k) -= 0.5 * Djj * e;\n\t\t\t\tG(j,j) -= Dik * e;\n\t\t\t\tG(k,j) += 1.5 * Dij * e;\n\t\t\t\tfor (int l = j+1; l < k; ++l)\n\t\t\t\t{\n\t\t\t\t\te = _elec_rep(idx++);\n\t\t\t\t\tG(i,j) += 2 * D(k,l) * e;\n\t\t\t\t\tG(i,k) -= 0.5 * D(l,j) * e;\n\t\t\t\t\tG(i,l) -= 0.5 * Dkj * e;\n\t\t\t\t\tG(k,l) += 2 * Dij * e;\n\t\t\t\t\tG(k,j) -= 0.5 * D(i,l) * e;\n\t\t\t\t\tG(l,j) -= 0.5 * Dik * e;\n\t\t\t\t}\n\t\t\t\te = _elec_rep(idx++);\n\t\t\t\tG(i,j) += D(k,k) * e;\n\t\t\t\tG(i,k) -= 0.5 * Dkj * e;\n\t\t\t\tG(k,j) -= 0.5 * Dik * e;\n\t\t\t\tG(k,k) += 2 * Dij * e;\n\t\t\t}\n\t\t\tfor (int l = 0; l < j; ++l)\n\t\t\t{\n\t\t\t\te = _elec_rep(idx++);\n\t\t\t\tG(i,i) -= D(j,l) * e;\n\t\t\t\tG(i,j) += 1.5 * D(i,l) * e;\n\t\t\t\tG(i,l) += 1.5 * Dij * e;\n\t\t\t\tG(j,l) -= 0.5 * Dii * e;\n\t\t\t}\n\t\t\te = _elec_rep(idx++);\n\t\t\tG(i,i) -= 0.5 * Djj * e;\n\t\t\tG(i,j) += 1.5 * Dij * e;\n\t\t\tG(j,j) -= 0.5 * Dii * e;\n\t\t}\n\n\t\tfor (int k = 0; k < i; ++k)\n\t\t{\n\t\t\tdouble Dik = D(i, k);\n\t\t\tfor (int l = 0; l < k; ++l)\n\t\t\t{\n\t\t\t\te = _elec_rep(idx++);\n\t\t\t\tG(i,i) += 2 * D(k,l) * e;\n\t\t\t\tG(i,k) -= 0.5 * D(i,l) * e;\n\t\t\t\tG(i,l) -= 0.5 * Dik * e;\n\t\t\t\tG(k,l) += Dii * e;\n\t\t\t}\n\t\t\te = _elec_rep(idx++);\n\t\t\tG(i,i) += D(k,k) * e;\n\t\t\tG(i,k) -= 0.5 * Dik * e;\n\t\t\tG(k,k) += Dii * e;\n\t\t}\n\t\tfor (int l = 0; l < i; ++l)\n\t\t{\n\t\t\te = _elec_rep(idx++);\n\t\t\tG(i,i) += D(i,l) * e;\n\t\t\tG(i,l) += 0.5 * Dii * e;\n\t\t}\n\t\tG(i,i) += 0.5 * Dii * _elec_rep(idx++);\n\t}\n\n\tfor (int i = 0; i < n; ++i)\n\t{\n\t\tfor (int j = 0; j < i; ++j)\n\t\t\tG(j,i) = G(i,j);\n\t}\n}\n\nvoid Basis::twoElectron(const Eigen::MatrixXd& D, Eigen::MatrixXd& J,\n\tEigen::MatrixXd& K) const\n{\n\tif (!_status.test(ELEC_REP_CURRENT))\n\t\tcalcElectronRepulsion();\n\n\tint n = D.rows();\n#ifdef DEBUG\n\tif (D.cols() != n)\n\t\tthrow Li::Exception(\"Density matrix is not square\");\n#endif\n\tJ.resize(n, n);\n\tJ.setZero();\n\tK.resize(n, n);\n\tK.setZero();\n\tint idx = 0;\n\tdouble e;\n\tfor (int i = 0; i < n; ++i)\n\t{\n\t\tdouble Dii = D(i,i);\n\t\tfor (int j = 0; j < i; ++j)\n\t\t{\n\t\t\tdouble Dij = D(i,j);\n\t\t\tdouble Djj = D(j,j);\n\t\t\tfor (int k = 0; k < j; ++k)\n\t\t\t{\n\t\t\t\tdouble Dik = D(i,k);\n\t\t\t\tdouble Djk = D(j,k);\n\t\t\t\tfor (int l = 0; l < k; ++l)\n\t\t\t\t{\n\t\t\t\t\te = _elec_rep(idx++);\n\t\t\t\t\tJ(i,j) += 2 * D(k,l) * e;\n\t\t\t\t\tJ(k,l) += 2 * Dij * e;\n\t\t\t\t\tK(i,k) += D(j,l) * e;\n\t\t\t\t\tK(i,l) += Djk * e;\n\t\t\t\t\tK(j,k) += D(i,l) * e;\n\t\t\t\t\tK(j,l) += Dik * e;\n\t\t\t\t}\n\t\t\t\te = _elec_rep(idx++);\n\t\t\t\tJ(i,j) += D(k,k) * e;\n\t\t\t\tJ(k,k) += 2 * Dij * e;\n\t\t\t\tK(i,k) += Djk * e;\n\t\t\t\tK(j,k) += Dik * e;\n\t\t\t}\n\t\t\tfor (int l = 0; l < j; ++l)\n\t\t\t{\n\t\t\t\te = _elec_rep(idx++);\n\t\t\t\tJ(i,j) += 2 * D(j,l) * e;\n\t\t\t\tJ(j,l) += 2 * Dij * e;\n\t\t\t\tK(i,j) += D(j,l) * e;\n\t\t\t\tK(i,l) += Djj * e;\n\t\t\t\tK(j,j) += 2 * D(i,l) * e;\n\t\t\t\tK(j,l) += Dij * e;\n\t\t\t}\n\t\t\te = _elec_rep(idx++);\n\t\t\tJ(i,j) += Djj * e;\n\t\t\tJ(j,j) += 2 * Dij * e;\n\t\t\tK(i,j) += Djj * e;\n\t\t\tK(j,j) += 2 * Dij * e;\n\t\t\tfor (int k = j+1; k < i; ++k)\n\t\t\t{\n\t\t\t\tdouble Dik = D(i,k);\n\t\t\t\tdouble Dkj = D(k,j);\n\t\t\t\tfor (int l = 0; l < j; ++l)\n\t\t\t\t{\n\t\t\t\t\te = _elec_rep(idx++);\n\t\t\t\t\tJ(i,j) += 2 * D(k,l) * e;\n\t\t\t\t\tJ(k,l) += 2 * Dij * e;\n\t\t\t\t\tK(i,k) += D(j,l) * e;\n\t\t\t\t\tK(i,l) += Dkj * e;\n\t\t\t\t\tK(j,l) += Dik * e;\n\t\t\t\t\tK(k,j) += D(i,l) * e;\n\t\t\t\t}\n\t\t\t\te = _elec_rep(idx++);\n\t\t\t\tJ(i,j) += 2 * Dkj * e;\n\t\t\t\tJ(k,j) += 2 * Dij * e;\n\t\t\t\tK(i,k) += Djj * e;\n\t\t\t\tK(i,j) += Dkj * e;\n\t\t\t\tK(j,j) += 2 * Dik * e;\n\t\t\t\tK(k,j) += Dij * e;\n\t\t\t\tfor (int l = j+1; l < k; ++l)\n\t\t\t\t{\n\t\t\t\t\te = _elec_rep(idx++);\n\t\t\t\t\tJ(i,j) += 2 * D(k,l) * e;\n\t\t\t\t\tJ(k,l) += 2 * Dij * e;\n\t\t\t\t\tK(i,k) += D(l,j) * e;\n\t\t\t\t\tK(i,l) += Dkj * e;\n\t\t\t\t\tK(k,j) += D(i,l) * e;\n\t\t\t\t\tK(l,j) += Dik * e;\n\t\t\t\t}\n\t\t\t\te = _elec_rep(idx++);\n\t\t\t\tJ(i,j) += D(k,k) * e;\n\t\t\t\tJ(k,k) += 2 * Dij * e;\n\t\t\t\tK(i,k) += Dkj * e;\n\t\t\t\tK(k,j) += Dik * e;\n\t\t\t}\n\t\t\tfor (int l = 0; l < j; ++l)\n\t\t\t{\n\t\t\t\te = _elec_rep(idx++);\n\t\t\t\tJ(i,j) += 2 * D(i,l) * e;\n\t\t\t\tJ(i,l) += 2 * Dij * e;\n\t\t\t\tK(i,i) += 2 * D(j,l) * e;\n\t\t\t\tK(i,j) += D(i,l) * e;\n\t\t\t\tK(i,l) += Dij * e;\n\t\t\t\tK(j,l) += Dii * e;\n\t\t\t}\n\t\t\te = _elec_rep(idx++);\n\t\t\tJ(i,j) += 2 * Dij * e;\n\t\t\tK(i,i) += Djj * e;\n\t\t\tK(i,j) += Dij * e;\n\t\t\tK(j,j) += Dii * e;\n\t\t}\n\t\tfor (int k = 0; k < i; ++k)\n\t\t{\n\t\t\tdouble Dik = D(i,k);\n\t\t\tfor (int l = 0; l < k; ++l)\n\t\t\t{\n\t\t\t\te = _elec_rep(idx++);\n\t\t\t\tJ(i,i) += 2 * D(k,l) * e;\n\t\t\t\tJ(k,l) += Dii * e;\n\t\t\t\tK(i,k) += D(i,l) * e;\n\t\t\t\tK(i,l) += Dik * e;\n\t\t\t}\n\t\t\te = _elec_rep(idx++);\n\t\t\tJ(i,i) += D(k,k) * e;\n\t\t\tJ(k,k) += Dii * e;\n\t\t\tK(i,k) += Dik * e;\n\t\t}\n\t\tfor (int l = 0; l < i; ++l)\n\t\t{\n\t\t\te = _elec_rep(idx++);\n\t\t\tJ(i,i) += 2 * D(i,l) * e;\n\t\t\tJ(i,l) += Dii * e;\n\t\t\tK(i,i) += D(i,l) * e;\n\t\t\tK(i,l) += Dii * e;\n\t\t\tK(i,i) += D(i,l) * e;\n\t\t}\n\t\te = _elec_rep(idx++);\n\t\tJ(i,i) += Dii * e;\n\t\tK(i,i) += Dii * e;\n\t}\n\n\tfor (int i = 0; i < n; ++i)\n\t{\n\t\tfor (int j = 0; j < i; ++j)\n\t\t{\n\t\t\tJ(j,i) = J(i,j);\n\t\t\tK(j,i) = K(i,j);\n\t\t}\n\t}\n}\n\nstd::ostream& Basis::print(std::ostream& os) const\n{\n\tos << \"Basis (\\n\" << indent;\n\tfor (BasisFunList::const_iterator it = _funs.begin();\n\t\tit != _funs.end(); ++it)\n\t{\n\t\tos << **it << \"\\n\";\n\t}\n\tos << dedent << \")\";\n\treturn os;\n}\n\nvoid Basis::setPairs() const\n{\n\tconst Dispatcher& dispatcher = Dispatcher::singleton();\n\n\t_pairs.clear();\n\tfor (BasisFunList::const_iterator iit = _funs.begin(); iit != _funs.end(); ++iit)\n\t{\n\t\tfor (BasisFunList::const_iterator jit = _funs.begin(); jit <= iit; ++jit)\n\t\t{\n\t\t\tAbstractBFPair *pair = dispatcher.pair(**iit, **jit);\n\t\t\t_pairs.push_back(PairPtr(pair));\n\t\t}\n\t}\n\n\t_status.set(PAIRS_CURRENT);\n}\n\nvoid Basis::setQuads() const\n{\n\tif (!_status.test(PAIRS_CURRENT))\n\t\tsetPairs();\n\n\tconst Dispatcher& dispatcher = Dispatcher::singleton();\n\n\t_quads.clear();\n\tfor (PairList::const_iterator iit = _pairs.begin(); iit != _pairs.end(); ++iit)\n\t{\n\t\tfor (PairList::const_iterator jit = _pairs.begin(); jit <= iit; ++jit)\n\t\t{\n\t\t\tAbstractBFQuad *quad = dispatcher.quad(**iit, **jit, _quad_pool);\n\t\t\t_quads.push_back(QuadPtr(quad, _quad_pool.deleter()));\n\t\t}\n\t}\n\t\n\t_status.set(QUADS_CURRENT);\n}\n\nvoid Basis::calcOverlap() const\n{\n\tif (!_status.test(PAIRS_CURRENT))\n\t\tsetPairs();\n\n\tPairList::const_iterator pit = _pairs.begin();\n\tint n = size();\n\t_overlap.resize(n, n);\n\tfor (int i = 0; i < n; ++i)\n\t{\n\t\tfor (int j = 0; j < i; ++j, ++pit)\n\t\t\t_overlap(i, j) = _overlap(j, i) = (*pit)->overlap();\n\t\t_overlap(i, i) = (*pit)->overlap();\n\t\t++pit;\n\t}\n\n\t_status.set(OVERLAP_CURRENT);\n}\n\nvoid Basis::calcKinetic() const\n{\n\tif (!_status.test(PAIRS_CURRENT))\n\t\tsetPairs();\n\n\tPairList::const_iterator pit = _pairs.begin();\n\tint n = size();\n\t_kinetic.resize(n, n);\n\tfor (int i = 0; i < n; ++i)\n\t{\n\t\tfor (int j = 0; j < i; ++j, ++pit)\n\t\t\t_kinetic(i, j) = _kinetic(j, i) = (*pit)->kineticEnergy(); \n\t\t_kinetic(i, i) = (*pit)->kineticEnergy();\n\t\t++pit;\n\t}\n\n\t_status.set(KINETIC_CURRENT);\n}\n\nvoid Basis::calcOneElectron() const\n{\n\tif (!_status.test(PAIRS_CURRENT))\n\t\tsetPairs();\n\n\tPairList::const_iterator pit = _pairs.begin();\n\tint n = size();\n\t_overlap.resize(n, n);\n\t_kinetic.resize(n, n);\n\tfor (int i = 0; i < n; ++i)\n\t{\n\t\tfor (int j = 0; j < i; ++j, ++pit)\n\t\t{\n\t\t\t(*pit)->oneElectron(_overlap(i,j), _kinetic(i,j));\n\t\t\t_overlap(j,i) = _overlap(i,j);\n\t\t\t_kinetic(j,i) = _kinetic(i,j);\n\t\t}\n\t\t(*pit)->oneElectron(_overlap(i,i), _kinetic(i,i));\n\t\t++pit;\n\t}\n\n\t_status.set(OVERLAP_CURRENT);\n\t_status.set(KINETIC_CURRENT);\n}\n\nvoid Basis::calcNuclearAttraction(const Eigen::MatrixXd& nuc_pos,\n\tconst Eigen::VectorXd& nuc_charge) const\n{\n\tif (!_status.test(PAIRS_CURRENT))\n\t\tsetPairs();\n\n\tPairList::const_iterator pit = _pairs.begin();\n\tint n = size();\n\t_nuc_attr.resize(n, n);\n\tfor (int i = 0; i < n; ++i)\n\t{\n\t\tfor (int j = 0; j < i; ++j, ++pit)\n\t\t\t_nuc_attr(i, j) = _nuc_attr(j, i)\n\t\t\t\t= (*pit)->nuclearAttraction(nuc_pos, nuc_charge); \n\t\t_nuc_attr(i, i) = (*pit)->nuclearAttraction(nuc_pos, nuc_charge);\n\t\t++pit;\n\t}\n\n\t_status.set(NUC_ATTR_CURRENT);\n}\n\nvoid Basis::calcElectronRepulsion() const\n{\n\tif (!_status.test(QUADS_CURRENT))\n\t\tsetQuads();\n\t\n\t_elec_rep.resize(_quads.size());\n\tfor (unsigned int i = 0; i < _quads.size(); ++i)\n\t\t_elec_rep[i] = _quads[i]->electronRepulsion();\n\n\t_status.set(ELEC_REP_CURRENT);\n}\n\nvoid Basis::calcOrtho() const\n{\n\tif (!_status.test(OVERLAP_CURRENT))\n\t\tcalcOverlap();\n\t_ortho = _overlap.sqrt().inverse();\n\t_status.set(ORTHO_CURRENT);\n}\n", "meta": {"hexsha": "32a242e628cf5a79f99ea41071c263ca5773b9ae", "size": 9668, "ext": "cc", "lang": "C++", "max_stars_repo_path": "Basis.cc", "max_stars_repo_name": "gvissers/quill2", "max_stars_repo_head_hexsha": "589d7bc3ce20da888547f8f4f6b8da908b3d63a5", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Basis.cc", "max_issues_repo_name": "gvissers/quill2", "max_issues_repo_head_hexsha": "589d7bc3ce20da888547f8f4f6b8da908b3d63a5", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Basis.cc", "max_forks_repo_name": "gvissers/quill2", "max_forks_repo_head_hexsha": "589d7bc3ce20da888547f8f4f6b8da908b3d63a5", "max_forks_repo_licenses": ["Apache-2.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.7747747748, "max_line_length": 82, "alphanum_fraction": 0.465970211, "num_tokens": 4029, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.743168019989179, "lm_q2_score": 0.44939263446475963, "lm_q1q2_score": 0.3339742343528963}}
{"text": "\n\n#include\"main.hpp\"\n#include\"Option.hpp\"\n#include\"Pre.hpp\"\n#include <boost/algorithm/string.hpp>\nusing boost::lexical_cast;\ntypedef multimap<string,Row*>::const_iterator mmit;\ntypedef multimap<string,const Row*>::const_iterator cmmit;\n\n\nclass pred_mc\n{\n    const double d_mc_cut;\n    public:\n    pred_mc(const double mc_cut) : d_mc_cut(mc_cut) { }\n    bool operator() (const Row& tmprow) const { return tmprow.m_cor<d_mc_cut; }\n};\n\n\nclass pred_g\n{\n    const set<string> d_set;\n    public:\n    pred_g(const set<string>& tmpset) : d_set(tmpset) {}\n    bool operator() (const Row& tmprow) const { return d_set.end()==d_set.find(tmprow.pid); }\n};\n\n\nclass pred_nr\n{\n    const int d_nr;\n    public:\n    pred_nr(const int nr) : d_nr(nr) {}\n    bool operator() (const Row& tmpco) const { return tmpco.nrepsi<d_nr; }\n};\n\n\nvoid Pre::setMc()\n{\n    multimap<string,Row*> pid_mm;\n    for (list<Row>::iterator it=d_pdata.begin();it!=d_pdata.end();it++) {\n        pid_mm.insert(make_pair(it->pid,&(*it)));\n    }\n    for (mmit end1,itp=pid_mm.begin();itp!=pid_mm.end();itp=end1) {\n        end1=pid_mm.upper_bound(itp->first);\n        vector<vector<double> > ww;\n        for (mmit it=itp;it!=end1;it++) ww.push_back(it->second->in);\n        if (ww.size()==1) {\n            itp->second->m_cor=1;\n            continue;\n        }\n        mmit it=itp;\n        for (unsigned f=0;f<ww.size();f++,it++) {\n            vector<double> cor;\n            for (unsigned g=0;g<ww.size();g++) if (f != g) {\n                vector<double> center(2);\n                vector<double> sd(center.size());\n                int ncol0=0;\n                for (int l=0;l<op().nc();l++) if (obs(ww.at(f).at(l)) and obs(ww.at(g).at(l))) {\n                    center.at(0) += ww.at(f).at(l);\n                    center.at(1) += ww.at(g).at(l);\n                    ncol0++;\n                }\n                if (ncol0<2) continue;\n                center.at(0) /= ncol0;\n                center.at(1) /= ncol0;\n                for (int l=0;l<op().nc();l++) if (obs(ww.at(f).at(l)) and obs(ww.at(g).at(l))) {\n                    sd.at(0) += pow(ww.at(f).at(l)-center.at(0),2);\n                    sd.at(1) += pow(ww.at(g).at(l)-center.at(1),2);\n                }\n                sd.at(0) = sqrt(sd.at(0));\n                sd.at(1) = sqrt(sd.at(1));\n                double cortmp=0;\n                for (int l=0;l<op().nc();l++) if (obs(ww.at(f).at(l)) and obs(ww.at(g).at(l))) {\n                    cortmp += (ww.at(f).at(l)-center.at(0))*(ww.at(g).at(l)-center.at(1));\n                }\n                if (sd.at(0)==0 or sd.at(1)==0) continue;\n                cortmp /= sd.at(0);\n                cortmp /= sd.at(1);\n                cor.push_back(cortmp);\n            }\n            if (cor.size()==0) {\n                it->second->m_cor=-1;\n            } else {\n                it->second->m_cor=median(cor.begin(),cor.end());\n            }\n        }\n    }\n}\n\n\nvoid Pre::norm_data()\n{\n    if (op().xbool()) {\n        for (int p=0;p<nprot();p++) for (int j=0;j<op().nrep();j++) {//centering by reps\n            vector<double> xvec;\n            for (int t=0; t<op().nt(); t++) if (obs(xx().at(p).at(j*op().nt()+t))) {\n                xvec.push_back(xx().at(p).at(j*op().nt()+t));\n            }\n            double center_x=median(xvec.begin(),xvec.end());\n            for (int t=0; t<op().nt(); t++) if (obs(xx().at(p).at(j*op().nt()+t))) {\n                d_xx.at(p).at(j*op().nt()+t) -= center_x;\n            }\n        }\n    }\n    for (int p=0;p<nprot();p++) {//centering by reps\n        for (unsigned q=0;q<yy().at(p).size();q++) for (int j=0;j<op().nrep();j++) {\n            vector<double> yvec;\n            for (int t=0; t<op().nt(); t++) if (obs(yy().at(p).at(q).at(j*op().nt()+t))) {\n                yvec.push_back(yy().at(p).at(q).at(j*op().nt()+t));\n            }\n            double center_y=median(yvec.begin(),yvec.end());\n            for (int t=0; t<op().nt(); t++) if (obs(yy().at(p).at(q).at(j*op().nt()+t))) {\n                d_yy.at(p).at(q).at(j*op().nt()+t) -= center_y;\n            }\n        }\n    }\n\n}\n\n\nPre::Pre(const Option& op) : d_op(op)\n{\n    read();\n    setAll();\n}\n\n\nvoid Pre::read()\n{\n    ifstream y_ifs(op().filey().c_str());\n    ifstream x_ifs(op().filex().c_str());\n\n    string str0;\n    istringstream iss;\n    getline(y_ifs,str0);\n    split(d_yh, str0, boost::is_any_of(\"\\t\"));\n    if (int(yh().size())<op().nc()) throw runtime_error(\"file_y\");\n\n    getline(x_ifs,str0);\n    split(d_xh, str0, boost::is_any_of(\"\\t\"));\n\n    for (int i=2;getline(x_ifs,str0) and (not str0.empty());i++) {\n        Row tmp_f(op().nc());\n        iss.clear(); iss.str(str0+\"\\t\");\n        getline(iss,tmp_f.pid,'\\t'); //tmp_f.pid+=\"_\"+lexical_cast<string>(i);\n        for (int l=0;l<op().nc();l++) {\n            if (not getline(iss,str0,'\\t')) throw runtime_error(\"FILE_X unequal columns: row \"+lexical_cast<string>(i));\n            if (str0==\"NA\" or str0.empty() or lexical_cast<double>(str0)==0) {\n                tmp_f.in.at(l)=NAN;\n            } else {\n                try {\n                    if (op().log_x()) tmp_f.in.at(l)=log(lexical_cast<double>(str0));\n                    else tmp_f.in.at(l)=(lexical_cast<double>(str0));\n                } catch (boost::bad_lexical_cast& e) {\n                    cerr<<e.what()<<\"FILE_X : row \"<<i<<\", column \"<<l+1+op().level();\n                    exit(1);\n                }\n            }\n        }\n        d_gdata0.push_back(tmp_f);\n    }\n\n    for (int i=2;getline(y_ifs,str0) and (not str0.empty());i++) {\n        Row tmp_f(op().nc());\n        iss.clear(); iss.str(str0+\"\\t\");\n        getline(iss,tmp_f.pid,'\\t'); //tmp_f.pid+=\"_\"+lexical_cast<string>(i);\n        if (op().level()==1) tmp_f.qid=tmp_f.pid;\n        else if (op().level()==2) getline(iss,tmp_f.qid,'\\t');\n        for (int l=0;l<op().nc();l++) {\n            if (not getline(iss,str0,'\\t')) throw runtime_error(\"FILE_Y unequal columns: row \"+lexical_cast<string>(i));\n            if (str0==\"NA\" or lexical_cast<double>(str0)==0 or str0.empty()) {\n                tmp_f.in.at(l)=NAN;\n            } else {\n                try {\n                    if (op().log_y()) tmp_f.in.at(l)=log(lexical_cast<double>(str0));\n                    else tmp_f.in.at(l)=(lexical_cast<double>(str0));\n                } catch (boost::bad_lexical_cast& e) {\n                    cerr<<e.what()<<\"FILE_Y : row \"<<i<<\", column \"<<l+1+op().level();\n                    exit(1);\n                }\n            }\n        }\n        d_pdata0.push_back(tmp_f);\n    }\n}\n\n\nvoid Pre::setAll()\n{\n    multimap<string,const Row*> gid_mm;\n    for (list<Row>::const_iterator it=gdata0().begin();it!=gdata0().end();it++) {\n        gid_mm.insert(make_pair(it->pid,&(*it)));\n    }\n    for (cmmit end1,itp=gid_mm.begin();itp!=gid_mm.end();itp=end1) {\n        end1=gid_mm.upper_bound(itp->first);\n        Row tmp_f(op().nc());\n        tmp_f.pid=itp->first;\n        vector<int> cobs(op().nc());\n        for (cmmit it=itp;it!=end1;it++) {\n            for (int i=0;i<op().nc();i++) {\n                if (obs(it->second->in.at(i))) {\n                    tmp_f.in.at(i)+=it->second->in.at(i);\n                    cobs.at(i)++;\n                }\n            }\n        }\n        for (int i=0;i<op().nc();i++) {\n            if (cobs.at(i)>0) tmp_f.in.at(i) /= cobs.at(i); else tmp_f.in.at(i)=NAN;\n        }\n        d_gdata.push_back(tmp_f);\n    }\n\n    multimap<string,const Row*> pqid_mm;\n    for (list<Row>::const_iterator it=pdata0().begin();it!=pdata0().end();it++) {\n        pqid_mm.insert(make_pair(it->pid+it->qid,&(*it)));\n    }\n    for (cmmit end1,itp=pqid_mm.begin();itp!=pqid_mm.end();itp=end1) {\n        end1=pqid_mm.upper_bound(itp->first);\n        Row tmp_f(op().nc());\n        tmp_f.pid=itp->second->pid;\n        tmp_f.qid=itp->second->qid;\n        vector<int> cobs(op().nc());\n        for (cmmit it=itp;it!=end1;it++) {\n            for (int i=0;i<op().nc();i++) {\n                if (obs(it->second->in.at(i))) {\n                    tmp_f.in.at(i)+=it->second->in.at(i);\n                    cobs.at(i)++;\n                }\n            }\n        }\n        for (int i=0;i<op().nc();i++) {\n            if (cobs.at(i)>0) tmp_f.in.at(i) /= cobs.at(i); else tmp_f.in.at(i)=NAN;\n        }\n        d_pdata.push_back(tmp_f);\n    }\n\n    for (list<Row>::iterator it=d_gdata.begin();it!=d_gdata.end();it++) {\n        for (int l=0;l<op().nc();l++) {\n            if (not obs(it->in.at(l))) {it->nrepsi--; /*break;*/ }\n        }\n    }\n    for (list<Row>::iterator it=d_pdata.begin();it!=d_pdata.end();it++) {\n        for (int l=0;l<op().nc();l++) {\n            if (not obs(it->in.at(l))) {it->nrepsi--; /*break;*/ }\n        }\n    }\n\n    //d_gdata.remove_if(pred_nr(op().nc()-2));\n    //d_pdata.remove_if(pred_nr(op().nc()-2));\n\n    setMc();\n    d_pdata.remove_if(pred_mc(op().min_correl()));\n\n    set<string> gset;\n    for (list<Row>::const_iterator it=gdata().begin();it!=gdata().end();it++) {\n        gset.insert(it->pid);\n    }\n    d_pdata.remove_if(pred_g(gset));\n\n    gset.clear();\n    for (list<Row>::const_iterator it=pdata().begin();it!=pdata().end();it++) {\n        gset.insert(it->pid);\n    }\n    d_gdata.remove_if(pred_g(gset));\n\n    map<string,const Row*> gid_m;\n    for (list<Row>::const_iterator it=gdata().begin();it!=gdata().end();it++) {\n        gid_m[it->pid]=&(*it);\n    }\n\n    multimap<string,const Row*> pid_mm;\n    for (list<Row>::const_iterator it=pdata().begin();it!=pdata().end();it++) {\n        pid_mm.insert(make_pair(it->pid,&(*it)));\n    }\n\n    cout<<\"nprot = \"<<nprot()<<'\\n';\n    d_xid.resize(nprot());\n    d_pid.resize(nprot());\n    d_qid.resize(nprot());\n    d_xx.resize(nprot(),vector<double>(op().nc()));\n    d_yy.resize(nprot());\n    int p=0;\n    multimap<string,const Row*>::const_iterator end1,itp=pid_mm.begin();\n    for (map<string,const Row*>::const_iterator itg=gid_m.begin();itg!=gid_m.end();itg++,itp=end1,p++) {\n        d_xid.at(p)=itg->second->pid;\n        d_pid.at(p)=itp->second->pid;\n        for (int l=0;l<op().nc();l++) d_xx.at(p).at(l)=itg->second->in.at(l);\n        end1=pid_mm.upper_bound(itp->first);\n        for (cmmit it=itp;it!=end1;it++) {\n            d_qid.at(p).push_back(it->second->qid);\n            d_yy.at(p).push_back(it->second->in);\n        }\n    }\n    if (not op().xbool()) {\n        for (int g=0;g<nprot();g++) for (int l=0;l<op().nc();l++) d_xx.at(g).at(l)=0;\n    }\n\n}\n\n\n#include\"Eigen/Dense\"\n\n\ndouble Pre::Kfn(const vector<double>&theta,const double xp,const double xq,const int e=1)\n{\n    if (not op().smooth()) return exp(-pow((xp-xq),2)/2);\n    const static double ll = op().smoothing().at(1);\n    return pow(op().smoothing().at(0),2)*exp(-pow((xp-xq)/ll,2)/2)+e*(xp==xq);\n}\n\n\ndouble Pre::Mfn(const vector<double>& m,const double xs,const vector<double>& adjdiff)\n{\n    if (op().timei().front()>xs or xs>op().timei().back()) throw runtime_error(\"xs range\");\n    int fxs=-1;\n    if (xs==op().timei().back()) return m.back();\n    for (int i=op().nt()-2;i>=0;i--) if (op().timei().at(i)<=xs) {fxs=i; break;}\n    return m.at(fxs)+(m.at(fxs+1)-m.at(fxs))/adjdiff.at(fxs+1)*(xs-op().timei().at(fxs));\n}\n\n\ntypedef multimap<int,int>::const_iterator cmmii;\n\n\n\n\nvoid Pre::impute_x()\n{\n    double** data = new double*[nprot()];\n    int** mask = new int*[nprot()];\n    for (int i = 0; i < nprot(); i++) {\n        data[i] = new double[op().nc()];\n        mask[i] = new int[op().nc()];\n    }\n\n    vector<vector<double> > mvec(nprot(),vector<double>(op().nrep()));\n    vector<vector<double> > vvec(nprot(),vector<double>(op().nrep()));\n    for (int p=0;p<nprot();p++) for (int j=0;j<op().nrep();j++) {\n        int nj=0;\n        const vector<double>& xxp=xx().at(p);\n        for (int t=0;t<op().nt();t++) if (obs(xxp.at(j*op().nt()+t))) {\n            mvec.at(p).at(j)+=xxp.at(j*op().nt()+t);\n            nj++;\n        }\n        mvec.at(p).at(j) /= nj;\n        for (int t=0;t<op().nt();t++) if (obs(xxp.at(j*op().nt()+t))) {\n            vvec.at(p).at(j) += pow(xxp.at(j*op().nt()+t)-mvec.at(p).at(j),2);\n        }\n        vvec.at(p).at(j) /= nj-1;\n        if (vvec.at(p).at(j)==0) vvec.at(p).at(j)=1;\n        for (int t=0;t<op().nt();t++) if (obs(xxp.at(j*op().nt()+t))) {\n            d_xx.at(p).at(j*op().nt()+t) -= mvec.at(p).at(j);\n            d_xx.at(p).at(j*op().nt()+t) /= sqrt(vvec.at(p).at(j));\n        }\n    }\n\n    for (int p=0;p<nprot();p++) for (int l=0; l<op().nc(); l++) {\n        data[p][l]=0;\n        int nq=0;\n        if (obs(xx().at(p).at(l))) {\n            data[p][l] += xx().at(p).at(l);\n            nq++;\n        }\n        if (nq>0) {\n            data[p][l] /= nq;\n            mask[p][l] = 1;\n        } else {\n            data[p][l] = NAN;\n            mask[p][l] = 0;\n        }\n    }\n\n\n    vector<int> clusterid(nprot());\n\n    multimap<int,int> c_mm;\n    for (int p=0;p<nprot();p++) c_mm.insert(make_pair(clusterid[p],p));\n\n    vector<vector<Eigen::VectorXd> > xax,yy_;\n    xax.resize(xx().size());\n    yy_.resize(xx().size());\n    for (int p=0;p<nprot();p++) {\n        xax.at(p).resize(op().nrep());\n        yy_.at(p).resize(op().nrep());\n        for (int j=0;j<op().nrep();j++) {\n            vector<double> x,y;\n            for (int t=0;t<op().nt();t++) {\n                if (obs(xx().at(p).at(j*op().nt()+t))) {\n                    x.push_back(op().timei().at(t));\n                    y.push_back(xx().at(p).at(j*op().nt()+t));\n                }\n            }\n            xax.at(p).at(j).resize(x.size());\n            yy_.at(p).at(j).resize(y.size());\n            for (unsigned i=0;i<x.size();i++) {\n                xax.at(p).at(j)(i)=x.at(i);\n                yy_.at(p).at(j)(i)=y.at(i);\n            }\n        }\n    }\n\n    const int Ns=100;\n    const double step=double(op().timei().back()-op().timei().front())/Ns;\n    Eigen::VectorXd xs(Ns);\n    for (int i=0;i<Ns;i++) xs(i)=op().timei().at(0)+step/2+i*step;\n\n    ofstream ofs1(\"EfsX.txt\");\n    ofs1<<\"p\\tq\\tj\";\n    for (unsigned i=0;i<xs.size();i++) ofs1<<'\\t'<<xs(i);\n    ofs1<<'\\n';\n\n    int ijk=0;\n    vector<double> adjdiff(op().timei().size());\n    adjacent_difference(op().timei().begin(),op().timei().end(),adjdiff.begin());\n\n    for (cmmii end1,itc=c_mm.begin();itc!=c_mm.end()/*,ijk<8*/;itc=end1,ijk++) {\n        end1=c_mm.upper_bound(itc->first);\n\n        vector<vector<double> > m(op().nrep(),vector<double>(op().nt()));\n\n        vector<double> theta(3,1);\n\n        for (cmmii it=itc;it!=end1;it++) {\n            const int p=it->second;\n            for (int j=0;j<op().nrep();j++) {\n                Eigen::VectorXd& y = yy_.at(p).at(j);\n                Eigen::VectorXd& x = xax.at(p).at(j);\n                const int N = y.size();\n                Eigen::MatrixXd Ky(N,N);\n                for (int i=0;i<N;i++) for (int k=0;k<N;k++) Ky(i,k)=Kfn(theta,x(i),x(k));\n                Eigen::VectorXd ym(y);\n                for (int i=0;i<N;i++) ym(i)-=Mfn(m.at(j),x(i),adjdiff);\n                Eigen::MatrixXd invKy=Ky.inverse();\n                ofs1<<p<<\"\\t0\\t\"<<j;\n                for (unsigned i=0;i<xs.size();i++) {\n                    Eigen::VectorXd ks(N);\n                    for (int k=0;k<N;k++) ks(k)=Kfn(theta,xs(i),x(k),0);\n                    const double Efs=ks.transpose()*invKy*ym+Mfn(m.at(j),xs(i),adjdiff);\n                    ofs1<<'\\t'<<Efs*sqrt(vvec.at(p).at(j))+mvec.at(p).at(j);\n                }\n                ofs1<<'\\n';\n\n                for (int t=0;t<op().nt();t++) {\n                    Eigen::VectorXd ks(N);\n                    for (int k=0;k<N;k++) ks(k)=Kfn(theta,op().timei().at(t),x(k),0);\n                    d_xx.at(p).at(j*op().nt()+t)=\n                        ks.transpose()*invKy*ym+Mfn(m.at(j),op().timei().at(t),adjdiff);\n                    d_xx.at(p).at(j*op().nt()+t)*=sqrt(vvec.at(p).at(j));\n                    d_xx.at(p).at(j*op().nt()+t)+=mvec.at(p).at(j);\n                }\n            }\n        }\n    }\n}\n\n\nvoid Pre::impute_y()\n{\n    double** data = new double*[nprot()];\n    int** mask = new int*[nprot()];\n    for (int i = 0; i < nprot(); i++) {\n        data[i] = new double[op().nc()];\n        mask[i] = new int[op().nc()];\n    }\n\n    vector<vector<vector<double> > > mvec(nprot());\n    vector<vector<vector<double> > > vvec(nprot());\n    for (int p=0;p<nprot();p++) {\n        mvec.at(p).resize(yy().at(p).size(),vector<double>(op().nrep()));\n        vvec.at(p).resize(yy().at(p).size(),vector<double>(op().nrep()));\n        for (unsigned q=0;q<yy().at(p).size();q++) for (int j=0;j<op().nrep();j++) {\n            int nj=0;\n            const vector<double>& yypq=yy().at(p).at(q);\n            for (int t=0;t<op().nt();t++) if (obs(yypq.at(j*op().nt()+t))) {\n                mvec.at(p).at(q).at(j)+=yypq.at(j*op().nt()+t);\n                nj++;\n            }\n            mvec.at(p).at(q).at(j) /= nj;\n            for (int t=0;t<op().nt();t++) if (obs(yypq.at(j*op().nt()+t))) {\n                vvec.at(p).at(q).at(j) += pow(yypq.at(j*op().nt()+t)-mvec.at(p).at(q).at(j),2);\n            }\n            vvec.at(p).at(q).at(j) /= nj-1;\n            if (vvec.at(p).at(q).at(j)==0) vvec.at(p).at(q).at(j)=1;\n            for (int t=0;t<op().nt();t++) if (obs(yypq.at(j*op().nt()+t))) {\n                d_yy.at(p).at(q).at(j*op().nt()+t) -= mvec.at(p).at(q).at(j);\n                d_yy.at(p).at(q).at(j*op().nt()+t) /= sqrt(vvec.at(p).at(q).at(j));\n            }\n        }\n    }\n\n\n    for (int p=0;p<nprot();p++) for (int l=0; l<op().nc(); l++) {\n        data[p][l]=0;\n        int nq=0;\n        for (unsigned q=0;q<yy().at(p).size();q++) if (obs(yy().at(p).at(q).at(l))) {\n            data[p][l] += yy().at(p).at(q).at(l);\n            nq++;\n        }\n        if (nq>0) {\n            data[p][l] /= nq;\n            mask[p][l] = 1;\n        } else {\n            data[p][l] = NAN;\n            mask[p][l] = 0;\n        }\n    }\n\n    //double* weight = new double[op().nc()];\n    //for (int i = 0; i < op().nc(); i++) weight[i] = 1.0;\n    //Node* tree = treecluster(nprot(), op().nc(), data, mask, weight, 0, 'c', 'a', 0);\n    //delete[] weight;\n    //if (!tree) { /* Indication that the treecluster routine failed */\n    //    cout<< \"treecluster routine failed due to insufficient memory\\n\";\n    //    return;\n    //}\n    //int* clusterid = new int[nprot()];\n    //cuttree(nprot(), tree, nprot()/100, clusterid);\n    //delete[] tree;\n\n    vector<int> clusterid(nprot());\n\n    multimap<int,int> c_mm;\n    for (int p=0;p<nprot();p++) c_mm.insert(make_pair(clusterid[p],p));\n\n\n    vector<vector<vector<Eigen::VectorXd> > > xax,yy_;\n    xax.resize(yy().size());\n    yy_.resize(yy().size());\n    for (int p=0;p<nprot();p++) {\n        xax.at(p).resize(yy().at(p).size());\n        yy_.at(p).resize(yy().at(p).size());\n        for (unsigned q=0;q<yy().at(p).size();q++) {\n            xax.at(p).at(q).resize(op().nrep());\n            yy_.at(p).at(q).resize(op().nrep());\n            for (int j=0;j<op().nrep();j++) {\n                vector<double> x,y;\n                for (int t=0;t<op().nt();t++) {\n                    if (obs(yy().at(p).at(q).at(j*op().nt()+t))) {\n                        x.push_back(op().timei().at(t));\n                        y.push_back(yy().at(p).at(q).at(j*op().nt()+t));\n                    }\n                }\n                xax.at(p).at(q).at(j).resize(x.size());\n                yy_.at(p).at(q).at(j).resize(y.size());\n                for (unsigned i=0;i<x.size();i++) {\n                    xax.at(p).at(q).at(j)(i)=x.at(i);\n                    yy_.at(p).at(q).at(j)(i)=y.at(i);\n                }\n            }\n        }\n    }\n\n    const int Ns=100;\n    const double step=double(op().timei().back()-op().timei().front())/Ns;\n    Eigen::VectorXd xs(Ns);\n    for (int i=0;i<Ns;i++) xs(i)=op().timei().at(0)+step/2+i*step;\n\n    ofstream ofs1(\"EfsY.txt\");\n    ofs1<<\"p\\tq\\tj\";\n    for (unsigned i=0;i<xs.size();i++) ofs1<<'\\t'<<xs(i);\n    ofs1<<'\\n';\n\n\n    int ijk=0;\n    vector<double> adjdiff(op().timei().size());\n    adjacent_difference(op().timei().begin(),op().timei().end(),adjdiff.begin());\n\n    for (cmmii end1,itc=c_mm.begin();itc!=c_mm.end()/*,ijk<8*/;itc=end1,ijk++) {\n        end1=c_mm.upper_bound(itc->first);\n\n        vector<vector<double> > m(op().nrep(),vector<double>(op().nt()));\n\n        vector<double> theta(3,1);\n\n        for (cmmii it=itc;it!=end1;it++) {\n            const int p=it->second;\n            for (unsigned q=0;q<yy_.at(p).size();q++) for (int j=0;j<op().nrep();j++) {\n                Eigen::VectorXd& y = yy_.at(p).at(q).at(j);\n                Eigen::VectorXd& x = xax.at(p).at(q).at(j);\n                const int N = y.size();\n\n                Eigen::MatrixXd Ky(N,N);\n                for (int i=0;i<N;i++) for (int k=0;k<N;k++) Ky(i,k)=Kfn(theta,x(i),x(k));\n                Eigen::VectorXd ym(y);\n                for (int i=0;i<N;i++) ym(i)-=Mfn(m.at(j),x(i),adjdiff);\n                Eigen::MatrixXd invKy=Ky.inverse();\n                ofs1<<p<<'\\t'<<q<<'\\t'<<j;\n                for (unsigned i=0;i<xs.size();i++) {\n                    Eigen::VectorXd ks(N);\n                    for (int k=0;k<N;k++) ks(k)=Kfn(theta,xs(i),x(k),0);\n                    const double Efs=ks.transpose()*invKy*ym+Mfn(m.at(j),xs(i),adjdiff);\n                    ofs1<<'\\t'<<Efs*sqrt(vvec.at(p).at(q).at(j))+mvec.at(p).at(q).at(j);\n                }\n                ofs1<<'\\n';\n\n\n\n                for (int t=0;t<op().nt();t++) {\n                    Eigen::VectorXd ks(N);\n                    for (int k=0;k<N;k++) ks(k)=Kfn(theta,op().timei().at(t),x(k),0);\n                    d_yy.at(p).at(q).at(j*op().nt()+t)=\n                        ks.transpose()*invKy*ym+Mfn(m.at(j),op().timei().at(t),adjdiff);\n                    d_yy.at(p).at(q).at(j*op().nt()+t)*=sqrt(vvec.at(p).at(q).at(j));\n                    d_yy.at(p).at(q).at(j*op().nt()+t)+=mvec.at(p).at(q).at(j);\n                }\n            }\n        }\n    }\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n", "meta": {"hexsha": "b4b7da8aac2c90473b79f824de8cb1eaa5dd1e62", "size": 21766, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "peca_core/src/Pre.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_core/src/Pre.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_core/src/Pre.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": 34.4944532488, "max_line_length": 120, "alphanum_fraction": 0.4629697694, "num_tokens": 6781, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7431680199891789, "lm_q2_score": 0.4493926344647597, "lm_q1q2_score": 0.3339742343528963}}
{"text": "#include \"engine.hpp\"\n\n#include \"functional.hpp\"\n\n#include <cassert>\n#include <vector>\n\n#include <ranges>\n\n#include <boost/numeric/odeint.hpp>\n#include <boost/numeric/odeint/algebra/fusion_algebra.hpp>\n#include <boost/numeric/odeint/algebra/fusion_algebra_dispatcher.hpp>\n\nnamespace EvolutionaryWalker::Physics\n{\n\nnamespace Impl\n{\n\n    class Engine\n    {\n    public:\n        constexpr static const std::size_t number_of_dimensions = 2;\n        using VelocityVector = LibUtils::Point<VelocityQuantity, number_of_dimensions>;\n        using AccelerationVector = LibUtils::Point<AccelerationQuantity, number_of_dimensions>;\n        using state_type = /*std::vector<*/ boost::fusion::vector<LengthQuantity, VelocityQuantity> /*>*/;\n        using deriv_type = /*std::vector<*/ boost::fusion::vector<VelocityQuantity, AccelerationQuantity> /*>*/;\n        using StepperType = boost::numeric::odeint::runge_kutta_dopri5<state_type, double, deriv_type, TimeQuantity>;\n\n        struct Node\n        {\n            bool is_fixed;\n            MassQuantity mass;\n            Point2d position;\n            VelocityVector speed;\n        };\n\n        struct Spring\n        {\n            std::array<NodeIndex, 2> nodes;\n            SpringCharacteristics characteristics;\n        };\n\n        Engine(AccelerationQuantity gravity)\n            : m_gravity(std::move(gravity))\n        {\n        }\n\n        ~Engine() = default;\n\n        void init()\n        {\n            m_stepper = std::make_unique<StepperType>();\n        }\n\n        void step(TimeQuantity time_step)\n        {\n            assert(numberOfFreeNodes() == 1); // for now\n            assert(m_stepper);\n            auto x = currentState();\n            m_stepper->do_step(std::cref(*this), x, TimeQuantity{}, time_step);\n            applyNewState(x);\n        }\n\n        void operator()(const state_type& x, deriv_type& dxdt, const TimeQuantity& /* t */) const\n        {\n            // assert(x.size() == dxdt.size());\n            // for(std::size_t i = 0; i < x.size(); i++)\n            // {\n            //     // dxdt[i].first = x[i].second;\n            //     // dxdt[i].second = -x[0] - gam * x[1];\n            //\n            //     // fusion::at_c<0>(dxdt) = fusion::at_c<1>(x);\n            //     // fusion::at_c<1>(dxdt) = -m_omega * m_omega * fusion::at_c<0>(x);\n            // }\n            \n            // using boost::fusion::at_c;\n            at_c<0>(dxdt) = at_c<1>(x);\n            at_c<1>(dxdt) = -m_gravity; //-m_omega * m_omega * at_c<0>(x);\n        }\n\n        static VelocityVector nullVelocity()\n        {\n            return {{0 * boost::units::si::meters_per_second, 0 * boost::units::si::meters_per_second}};\n        }\n\n        NodeIndex addFixedNode(Point2d position)\n        {\n            m_nodes.emplace_back(true, 0 * boost::units::si::kilograms, std::move(position), nullVelocity());\n            return NodeIndex{m_nodes.size() - 1};\n        }\n\n        NodeIndex addNode(Point2d position, MassQuantity mass)\n        {\n            m_nodes.emplace_back(false, std::move(mass), std::move(position), nullVelocity());\n            return NodeIndex{m_nodes.size() - 1};\n        }\n\n        SpringIndex addSpring(const NodeIndex node1, const NodeIndex node2, SpringCharacteristics characteristics)\n        {\n            m_springs.push_back({{node1, node2}, std::move(characteristics)});\n            return SpringIndex{m_nodes.size() - 1};\n        }\n\n        Point2d node(const NodeIndex i) const\n        {\n            return m_nodes[i].position;\n        }\n\n        std::size_t numberOfFreeNodes() const\n        {\n            return freeNodes().size();\n        }\n\n    private:\n        const AccelerationQuantity m_gravity;\n        std::vector<Node> m_nodes;\n        std::vector<Spring> m_springs;\n        std::unique_ptr<StepperType> m_stepper = nullptr;\n        \n        state_type currentState() const\n        {\n            // state_type res;\n            // for(const auto& node : m_nodes)\n            // {\n            //     if(node.is_fixed) continue;\n            //     res.emplace_back(node.position, node.speed);\n            // }\n            // return res;\n        \n            const auto nodes = freeNodes();\n            state_type res;\n            at_c<0>(res) = nodes.front().position[1];\n            at_c<1>(res) = nodes.front().speed[1];\n            return res;\n        }\n        \n        void applyNewState(const state_type& state)\n        {\n            // TODO do better\n            m_nodes.back().position[1] = at_c<0>(state);\n            m_nodes.back().speed[1] = at_c<1>(state);\n        }\n\n        std::vector<Node> freeNodes() const\n        {\n            using LibUtils::Functional::Not;\n            // TODO try with ranges?\n            // return m_nodes | std::views::filter(LibUtils::Functional::Not(&Node::is_fixed));\n            decltype(m_nodes) res;\n            std::copy_if(begin(m_nodes), end(m_nodes), std::back_inserter(res), Not(std::mem_fn(&Node::is_fixed)));\n            return res;\n        }\n    };\n\n} // namespace Impl\n\nEngine::Engine(AccelerationQuantity gravity)\n    : m_pimpl(std::make_unique<Impl::Engine>(std::move(gravity)))\n{\n}\n\nEngine::~Engine() = default;\n\nvoid Engine::init()\n{\n    m_pimpl->init();\n}\n\nvoid Engine::step(TimeQuantity time_step)\n{\n    m_pimpl->step(time_step);\n}\n\nNodeIndex Engine::addFixedNode(Point2d position)\n{\n    return m_pimpl->addFixedNode(std::move(position));\n}\n\nNodeIndex Engine::addNode(Point2d position, MassQuantity mass)\n{\n    return m_pimpl->addNode(std::move(position), std::move(mass));\n}\n\nSpringIndex Engine::addSpring(const NodeIndex node1, const NodeIndex node2, SpringCharacteristics characteristics)\n{\n    return m_pimpl->addSpring(node1, node2, std::move(characteristics));\n}\n\nPoint2d Engine::node(const NodeIndex i) const\n{\n    return m_pimpl->node(i);\n}\n\n} // namespace EvolutionaryWalker::Physics\n", "meta": {"hexsha": "7589fdf5e2f8273645800b1c09c11aa69cb1fa0c", "size": 5832, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/physics/engine.cpp", "max_stars_repo_name": "julienlopez/EvolutionaryWalker", "max_stars_repo_head_hexsha": "c29ef7e70ea1346e1a86ed56d43d7f85e3abd1ea", "max_stars_repo_licenses": ["MIT"], "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/physics/engine.cpp", "max_issues_repo_name": "julienlopez/EvolutionaryWalker", "max_issues_repo_head_hexsha": "c29ef7e70ea1346e1a86ed56d43d7f85e3abd1ea", "max_issues_repo_licenses": ["MIT"], "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/physics/engine.cpp", "max_forks_repo_name": "julienlopez/EvolutionaryWalker", "max_forks_repo_head_hexsha": "c29ef7e70ea1346e1a86ed56d43d7f85e3abd1ea", "max_forks_repo_licenses": ["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.7551020408, "max_line_length": 117, "alphanum_fraction": 0.5749314129, "num_tokens": 1409, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7431680086124811, "lm_q2_score": 0.44939263446475963, "lm_q1q2_score": 0.3339742292402921}}
{"text": "///////////////////////////////////////////////////////////////////////////////\n// cells.hpp                                                                 //\n//                                                                           //\n//  Copyright 2010 Erwann Rogard. Distributed under the Boost                //\n//  Software License, Version 1.0. (See accompanying file                    //\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)         //\n///////////////////////////////////////////////////////////////////////////////\n#ifndef BOOST_STATISTICS_DETAIL_NON_PARAMETRIC_CONTINGENCY_TABLE_CELLS_CELLS_HPP_ER_2010\n#define BOOST_STATISTICS_DETAIL_NON_PARAMETRIC_CONTINGENCY_TABLE_CELLS_CELLS_HPP_ER_2010\n#include <boost/type_traits/remove_reference.hpp>\n#include <boost/type_traits/remove_const.hpp>\n\n#include <boost/math/policies/policy.hpp>\n\n#include <boost/fusion/include/at_key.hpp>\n#include <boost/fusion/container/map/detail/extract_keys.hpp> // needed?\n#include <boost/fusion/container/map/detail/subset_traits.hpp>\n#include <boost/fusion/container/map/detail/hashable_map.hpp>\n\n#include <boost/unordered_map.hpp>\n\n#include <boost/accumulators/framework/extractor.hpp>\n#include <boost/accumulators/framework/accumulator_base.hpp>\n#include <boost/accumulators/framework/parameters/sample.hpp>\n#include <boost/accumulators/framework/parameters/accumulator.hpp>\n#include <boost/accumulators/framework/depends_on.hpp>\n#include <boost/accumulators/statistics_fwd.hpp>\n#include <boost/accumulators/framework/parameters/weight.hpp>\n#include <boost/accumulators/framework/detail/unpack_depends_on.hpp>\n#include <boost/accumulators/framework/detail/parameters/policy.hpp>\n\n#include <boost/statistics/detail/non_parametric/contingency_table/detail/raise_domain_error.hpp>\n#include <boost/statistics/detail/non_parametric/contingency_table/factor/levels.hpp>\n#include <boost/statistics/detail/non_parametric/contingency_table/factor/vec_levels.hpp>\n#include <boost/statistics/detail/non_parametric/contingency_table/factor/domain_error_logger.hpp>\n#include <boost/statistics/detail/non_parametric/contingency_table/factor/check_against_domain.hpp>\n\n// Usage:\n//  typedef cells<mpl::vector<X,Y,Z> > cells_\n// This is a Boost.Accumulator feature specifying a contingency table asso-\n// ciated with variables X, Y, and Z.\n\nnamespace boost { \nnamespace statistics{\nnamespace detail{\nnamespace contingency_table{\nnamespace cells_aux{\n\n   template<typename Keys>\n   struct depends_on{\n        typedef typename contingency_table::vec_levels<Keys>::type vec_levels_;\n        typedef typename boost::accumulators::detail::unpack_depends_on<\n            vec_levels_\n        >::type type;\n   };\n\n    template<typename T,typename Keys>\n    struct traits{\n        typedef boost::fusion::detail::map_subset_traits<T,Keys> inner_traits;\n        typedef typename inner_traits::map subsample_;\n        typedef boost::fusion::detail::hashable_map<\n            subsample_> hashable_subsample_;\n        typedef typename boost::unordered_map<\n            hashable_subsample_,std::size_t> map_;\n        \n    };\n}// cells_aux\nnamespace impl{\n\n    template<typename T,typename Keys>\n    class cells : public boost::accumulators::accumulator_base{\n        typedef boost::accumulators::dont_care dont_care_;\n        typedef std::size_t size_;\n                \n        typedef contingency_table::cells_aux::traits<T,Keys> traits_;\n        typedef typename traits_::hashable_subsample_ hashable_subsample_;\n        typedef typename traits_::map_ map_;\n        \n        public:\n\t\t\n        typedef T \t\tsample_type; \n        typedef size_ \tsize_type;\t \n\n        typedef map_& result_type; // not const bec map[] is non-const\n\n        cells(dont_care_){}\n\n        //template<typename A1,typename A2>\n        //void operator()(const A1& a1,const A2& a2){\n        //    \n        //}\n\n        template<typename Args>\n        void operator()(const Args& args){\n            typedef boost::math::policies::policy<> pol_;\n            this->update_if(\n                hashable_subsample_( args[ boost::accumulators::sample ] ),\n                args[ boost::accumulators::accumulator ],\n                args[ boost::accumulators::detail::_policy |  pol_() ],\n                args[ boost::accumulators::weight ]\n            ); \n        }\n\t\t\n        result_type result(dont_care_)const{\n            return this->map;\n        }\n\n\t\tprivate:\n        template<typename V,typename N>\n        void update(\n            const V& s,\n            const N& size\n        ){\n            ( this->map )[ s ] += size;\n        }\n\n        typedef ::boost::math::policies::domain_error< \n             boost::math::policies::ignore_error\n        > ignore_policy_; \n        template<typename V,typename A,typename N>\n        void update_if(\n            const V& s,\n            const A& acc,\n            const ignore_policy_& policy,\n            const N& size\n        ){\n            this->update(s,acc,size);\n        }\n\n        template<typename V,typename A,typename P,typename N>\n        void update_if(\n            const V& s,\n            const A& acc,\n            const P& policy,\n            const N& size\n        ){\n            namespace ct = contingency_table;\n            this->error_logger.reset();\n            boost::fusion::for_each( \n                s, \n                ct::make_check_against_domain( acc, this->error_logger) \n            );\n            if(!this->error_logger.is_error())\n            {\n                this->update( s, size );\n            }else{\n                static const char* fun = \"impl::cells::update_if %1%\";\n                ct::raise_domain_error<V>(\n                  fun,\n                  this->error_logger().c_str(), \n                  policy\n                );\n            }    \n        }\n\n        mutable map_ map;\n        typedef contingency_table::domain_error_logger error_logger_;\n        error_logger_ error_logger; \n\t};\n    \n}// impl\nnamespace tag\n{\n\n    template<typename Keys>\n    struct cells \n        : contingency_table::cells_aux::depends_on<Keys>::type\n    {\n        typedef typename contingency_table::par_spec< Keys >::type par_spec_;\n    \n        struct impl{\n            template<typename T,typename W>\n            struct apply{\n        \t\ttypedef contingency_table::impl::cells<T,Keys> type;    \t\n            };\n        };\n    };\n    \n}// tag\nnamespace result_of{\nnamespace extract{\n\n    template<typename Keys,typename AccSet>\n    struct cells\n    : boost::accumulators::detail::extractor_result<\n        AccSet,\n        contingency_table::tag::cells<Keys>\n    >{};\n\n}// extract\n}// result_of\nnamespace extract\n{\n  \ttemplate<typename Keys,typename AccSet>\n    typename contingency_table::result_of::extract::template \n        cells<Keys,AccSet>::type\n  \tcells(AccSet const& acc)\n    {\n    \ttypedef contingency_table::tag::cells<Keys> the_tag;\n        return boost::accumulators::extract_result<the_tag>(acc);\n  \t}\n\n}// extract\n\nusing extract::cells;\n\n}// contingency_table\n}// detail\n}// statistics\n}// boost\n\n#endif\n", "meta": {"hexsha": "99db2738c7d420b8d8b82edd63d7f0984929e7dc", "size": 7044, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "non_parametric/boost/statistics/detail/non_parametric/backup_once_in_trunk/non_parametric/contingency_table/cells/cells.hpp", "max_stars_repo_name": "rogard/boost_sandbox_statistics", "max_stars_repo_head_hexsha": "16aacbc716a31a9f7bb6c535b1c90dc343282a23", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "non_parametric/boost/statistics/detail/non_parametric/backup_once_in_trunk/non_parametric/contingency_table/cells/cells.hpp", "max_issues_repo_name": "rogard/boost_sandbox_statistics", "max_issues_repo_head_hexsha": "16aacbc716a31a9f7bb6c535b1c90dc343282a23", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "non_parametric/boost/statistics/detail/non_parametric/backup_once_in_trunk/non_parametric/contingency_table/cells/cells.hpp", "max_forks_repo_name": "rogard/boost_sandbox_statistics", "max_forks_repo_head_hexsha": "16aacbc716a31a9f7bb6c535b1c90dc343282a23", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.0704225352, "max_line_length": 99, "alphanum_fraction": 0.6168370244, "num_tokens": 1487, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6150878696277513, "lm_q2_score": 0.5428632831725052, "lm_q1q2_score": 0.3339086203457029}}
{"text": "#include <iostream>\n\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/vector.hpp>\n#include <boost/numeric/ublas/io.hpp>\n#include <boost/timer.hpp>\n\n\n#include <vector>\n#include <cmath>\nusing namespace std;\n\n#include \"NRGclasses.hpp\"\n//#include \"NRGfunctions.hpp\"\n\n\nvoid RotateMatrix(CNRGmatrix* pMat, CNRGbasisarray* pAcut,\n\t\t  CNRGmatrix* pMatRot){\n\n  pMatRot->ClearAll();\n\n  //pMatRot->SyncNRGarray(*pAcut);\n\n  pMatRot->MatBlockMap=pMat->MatBlockMap;\n  pMatRot->UpperTriangular=pMat->UpperTriangular;\n  pMatRot->IsComplex=pMat->IsComplex;\n\n\n  // Same Block strucuture as pAcut (THIS IS CRUCIAL!)\n  pMatRot->NQNumbers=pAcut->NQNumbers;\n  pMatRot->QNumbers=pAcut->QNumbers;\n  if (pAcut->BlockBegEndBC.size()!=0)\n    pMatRot->BlockBegEnd=pAcut->BlockBegEndBC;\n  else\n    pMatRot->BlockBegEnd=pAcut->BlockBegEnd;\n\n\n\n  // Need to Check Sync!!\n  bool ChkSync=pMat->ChkSync(pAcut);\n\n  if (!ChkSync){\n    cout << \"RotateMatrix: pMat and pAcut not in sync\" << endl;\n    return;\n  }\n\n  // Writing the blocks of pMat to the basis in pAcut\n\n  int i1=0;\n  for (int iMatbl=0; iMatbl<pMat->NumMatBlocks(); iMatbl++){\n\n    int ibl1=0;\n    int ibl2=0;\n\n    pMatRot->MatBlockBegEnd.push_back(i1);\n\n    pMat->GetBlocksFromMatBlock(iMatbl,ibl1,ibl2);\n\n    \n \n    int Nst_basis1=pAcut->GetBlockSizeBC(ibl1); // Should work: \n    int Nst_basis2=pAcut->GetBlockSizeBC(ibl2); // ibl1, ibl2 in the current \n                                                // block structure\n\n//      cout << \" Rotating block \" << iMatbl << \" of \" << pMat->NumMatBlocks()-1\n//  \t << \" Final Size: \" << Nst_basis1 << \" x \" << Nst_basis2 << endl; \n\n\n    // Boost matrices\n    boost::numeric::ublas::matrix<double> MatFinal(Nst_basis1,Nst_basis2);\n    boost::numeric::ublas::matrix<complex<double> > cMatFinal(Nst_basis1,Nst_basis2);\n\n\n    if (pMat->IsComplex){\n      //cout << \"pMat is complex \" << endl;\n       cMatFinal=pMat->cRotateBlock2BLAS(pAcut,ibl1,ibl2);\n    }\n    else\n      MatFinal=pMat->RotateBlock2BLAS(pAcut,ibl1,ibl2);\n\n    int j0=0;\n    for (int ii=0;ii<Nst_basis1;ii++){\n      if ( (pMatRot->UpperTriangular)&&(ibl1==ibl2) )\n\tj0=ii;\n      else \n\tj0=0;\n      for (int jj=j0;jj<Nst_basis2;jj++){\n\tif (pMatRot->IsComplex)\n\t  pMatRot->MatElCplx.push_back(cMatFinal(ii,jj));\n\telse\n\t  pMatRot->MatEl.push_back(MatFinal(ii,jj));\n\ti1++;\n      }\n    }\n    // end loop in MatFinal\n    pMatRot->MatBlockBegEnd.push_back(i1-1);\n  }\n  // end loop in MatBlocks\n}\n// end subroutine\n\n\n// Rotate in the UNCUT eigenvector\nvoid RotateMatrix_NoCut(CNRGmatrix* pMat, CNRGarray* pAeig,\n\t\t  CNRGmatrix* pMatRot, bool forward){\n\n  pMatRot->ClearAll();\n\n  //pMatRot->SyncNRGarray(*pAeig);\n\n  pMatRot->MatBlockMap=pMat->MatBlockMap;\n  pMatRot->UpperTriangular=pMat->UpperTriangular;\n  pMatRot->IsComplex=pMat->IsComplex;\n\n  // Same Block strucuture as pAeig (THIS IS CRUCIAL!)\n  pMatRot->NQNumbers=pAeig->NQNumbers;\n  pMatRot->QNumbers=pAeig->QNumbers;\n  pMatRot->BlockBegEnd=pAeig->BlockBegEnd;\n\n\n\n  // Need to Check Sync!!\n  bool ChkSync=pMat->ChkSync(pAeig);\n\n  if (!ChkSync){\n    cout << \"RotateMatrix: pMat and pAeig not in sync\" << endl;\n    return;\n  }\n\n  // Writing the blocks of pMat to the basis in pAeig\n\n//   CNRGbasisarray Acut;\n//   Acut.FalseCut(pAeig);\n//   Acut.PrintAll();\n\n  int i1=0;\n  for (int iMatbl=0; iMatbl<pMat->NumMatBlocks(); iMatbl++){\n\n    int ibl1=0;\n    int ibl2=0;\n\n    pMatRot->MatBlockBegEnd.push_back(i1);\n\n    pMat->GetBlocksFromMatBlock(iMatbl,ibl1,ibl2);\n\n    \n    int Nst_basis1=pAeig->GetBlockSize(ibl1); // Should work: \n    int Nst_basis2=pAeig->GetBlockSize(ibl2); // ibl1, ibl2 in the current \n                                                // block structure\n\n//      cout << \" Rotating block \" << iMatbl << \" of \" << pMat->NumMatBlocks()-1\n//  \t << \" Final Size: \" << Nst_basis1 << \" x \" << Nst_basis2 << endl; \n\n\n    // Boost matrices\n    boost::numeric::ublas::matrix<double> MatFinal(Nst_basis1,Nst_basis2);\n    boost::numeric::ublas::matrix<complex<double> > cMatFinal(Nst_basis1,Nst_basis2);\n\n    //MatFinal=pMat->RotateBlock2BLAS(&Acut,ibl1,ibl2);\n\n    if (pMat->IsComplex){\n      cMatFinal=pMat->cRotateBlock2BLAS_NoCut(pAeig,ibl1,ibl2,forward);\n    }\n    else\n      MatFinal=pMat->RotateBlock2BLAS_NoCut(pAeig,ibl1,ibl2,forward);\n\n//     if ( (ibl1==3)&&(ibl2==6) ){\n    //cout << \" RotMat(ibl1=\"<<ibl1<<\",ibl2=\"<<ibl2<<\")=\"<< MatFinal << endl;\n    //cout << \" RotMat(ibl1=\"<<ibl1<<\",ibl2=\"<<ibl2<<\")=\"<< cMatFinal << endl;\n//     }\n\n    int j0=0;\n    for (int ii=0;ii<Nst_basis1;ii++){\n      if ( (pMatRot->UpperTriangular)&&(ibl1==ibl2) )\n\tj0=ii;\n      else \n\tj0=0;\n      for (int jj=j0;jj<Nst_basis2;jj++){\n\tif (pMatRot->IsComplex){\n\t  pMatRot->MatElCplx.push_back(cMatFinal(ii,jj));\n\t}\n\telse{\n\t  pMatRot->MatEl.push_back(MatFinal(ii,jj));\n\t}\n\ti1++;\n      }\n    }\n    // end loop in MatFinal\n\n    pMatRot->MatBlockBegEnd.push_back(i1-1);\n    \n  }\n  // end loop in MatBlocks\n\n\n}\n// end subroutine\n\n\n///////////////////////////////////////////////////////\n///// Moving all RotateBlock2BLAS to here  ////////////\n///////////////////////////////////////////////////////\n\n", "meta": {"hexsha": "386f7cece60538e57ebba7f3af6812470f254972", "size": 5097, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/RotateMatrix.cpp", "max_stars_repo_name": "lgds/NRG_USP", "max_stars_repo_head_hexsha": "ff66846e92498aa429cce6fc5793bec23ad03eb4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2015-09-21T20:58:45.000Z", "max_stars_repo_stars_event_max_datetime": "2019-03-20T01:21:41.000Z", "max_issues_repo_path": "src/RotateMatrix.cpp", "max_issues_repo_name": "lgds/NRG_USP", "max_issues_repo_head_hexsha": "ff66846e92498aa429cce6fc5793bec23ad03eb4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/RotateMatrix.cpp", "max_forks_repo_name": "lgds/NRG_USP", "max_forks_repo_head_hexsha": "ff66846e92498aa429cce6fc5793bec23ad03eb4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.9852941176, "max_line_length": 85, "alphanum_fraction": 0.6262507357, "num_tokens": 1720, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6893056040203136, "lm_q2_score": 0.48438008427698437, "lm_q1q2_score": 0.33388590656795714}}
{"text": "/*\n Copyright (C) 2016 Quaternion Risk Management Ltd\n All rights reserved.\n\n This file is part of ORE, a free-software/open-source library\n for transparent pricing and risk analysis - http://opensourcerisk.org\n\n ORE is free software: you can redistribute it and/or modify it\n under the terms of the Modified BSD License.  You should have received a\n copy of the license along with this program.\n The license is also available online at <http://opensourcerisk.org>\n\n This program is distributed on the basis that it will form a useful\n contribution to risk analytics and model standardisation, but WITHOUT\n ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n FITNESS FOR A PARTICULAR PURPOSE. See the license for more details.\n*/\n\n#include <qle/models/crossassetanalytics.hpp>\n#include <qle/models/crossassetmodel.hpp>\n\n#include <ql/math/matrixutilities/pseudosqrt.hpp>\n#include <ql/processes/eulerdiscretization.hpp>\n\n#include <boost/make_shared.hpp>\n\nusing namespace QuantLib;\n\nnamespace {\nstatic inline void setValue(Matrix& m, const Real& value, const QuantExt::CrossAssetModel* model,\n                            const QuantExt::CrossAssetModelTypes::AssetType& t1, const Size& i1,\n                            const QuantExt::CrossAssetModelTypes::AssetType& t2, const Size& i2,\n                            const Size& offset1 = 0, const Size& offset2 = 0) {\n    Size i = model->pIdx(t1, i1, offset1);\n    Size j = model->pIdx(t2, i2, offset2);\n    m[i][j] = m[j][i] = value;\n}\n} // anonymous namespace\n\nnamespace QuantExt {\n\nusing namespace CrossAssetAnalytics;\n\nCrossAssetStateProcess::CrossAssetStateProcess(const CrossAssetModel* const model, discretization disc,\n                                               SalvagingAlgorithm::Type salvaging)\n    : StochasticProcess(), model_(model), salvaging_(salvaging) {\n\n    if (disc == euler) {\n        discretization_ = boost::make_shared<EulerDiscretization>();\n    } else {\n        discretization_ = boost::make_shared<CrossAssetStateProcess::ExactDiscretization>(model, salvaging);\n    }\n}\n\nSize CrossAssetStateProcess::size() const { return model_->dimension(); }\n\nvoid CrossAssetStateProcess::flushCache() const {\n    cache_m_.clear();\n    cache_v_.clear();\n    cache_d_.clear();\n    boost::shared_ptr<CrossAssetStateProcess::ExactDiscretization> tmp =\n        boost::dynamic_pointer_cast<CrossAssetStateProcess::ExactDiscretization>(discretization_);\n    if (tmp != NULL) {\n        tmp->flushCache();\n    }\n}\n\nDisposable<Array> CrossAssetStateProcess::initialValues() const {\n    Array res(model_->dimension(), 0.0);\n    /* irlgm1f processes have initial value 0 */\n    for (Size i = 0; i < model_->components(FX); ++i) {\n        /* fxbs processes are in log spot */\n        res[model_->pIdx(FX, i, 0)] = std::log(model_->fxbs(i)->fxSpotToday()->value());\n    }\n    for (Size i = 0; i < model_->components(EQ); ++i) {\n        /* eqbs processes are in log spot */\n        res[model_->pIdx(EQ, i, 0)] = std::log(model_->eqbs(i)->eqSpotToday()->value());\n    }\n    /* infdk, crlgm1f processes have initial value 0 */\n    return res;\n}\n\nDisposable<Array> CrossAssetStateProcess::drift(Time t, const Array& x) const {\n    Array res(model_->dimension(), 0.0);\n    Size n = model_->components(IR);\n    Size n_eq = model_->components(EQ);\n    Real H0 = model_->irlgm1f(0)->H(t);\n    Real Hprime0 = model_->irlgm1f(0)->Hprime(t);\n    Real alpha0 = model_->irlgm1f(0)->alpha(t);\n    Real zeta0 = model_->irlgm1f(0)->zeta(t);\n    boost::unordered_map<double, Array>::const_iterator i = cache_m_.find(t);\n    if (i == cache_m_.end()) {\n        /* z0 has drift 0 */\n        for (Size i = 1; i < n; ++i) {\n            Real Hi = model_->irlgm1f(i)->H(t);\n            Real alphai = model_->irlgm1f(i)->alpha(t);\n            Real sigmai = model_->fxbs(i - 1)->sigma(t);\n            // ir-ir\n            Real rhozz0i = model_->correlation(IR, 0, IR, i);\n            // ir-fx\n            Real rhozx0i = model_->correlation(IR, 0, FX, i - 1);\n            Real rhozxii = model_->correlation(IR, i, FX, i - 1);\n            // ir drifts\n            res[model_->pIdx(IR, i, 0)] =\n                -Hi * alphai * alphai + H0 * alpha0 * alphai * rhozz0i - sigmai * alphai * rhozxii;\n            // log spot fx drifts (z0, zi independent parts)\n            res[model_->pIdx(FX, i - 1, 0)] =\n                H0 * alpha0 * sigmai * rhozx0i + model_->irlgm1f(0)->termStructure()->forwardRate(t, t, Continuous) -\n                model_->irlgm1f(i)->termStructure()->forwardRate(t, t, Continuous) - 0.5 * sigmai * sigmai;\n        }\n        /* log equity spot drifts (the cache-able parts) */\n        for (Size k = 0; k < n_eq; ++k) {\n            Size i = model_->ccyIndex(model_->eqbs(k)->currency());\n            // ir params (for equity currency)\n            Real eps_ccy = (i == 0) ? 0.0 : 1.0;\n            // Real Hi = model_->irlgm1f(i)->H(t);\n            // Real alphai = model_->irlgm1f(i)->alpha(t);\n            // eq vol\n            Real sigmask = model_->eqbs(k)->sigma(t);\n            // fx vol (eq ccy / base ccy)\n            Real sigmaxi = (i == 0) ? 0.0 : model_->fxbs(i - 1)->sigma(t);\n            // ir-eq corr\n            // Real rhozsik = model_->correlation(EQ, k, IR, i); // eq cur\n            Real rhozs0k = model_->correlation(EQ, k, IR, 0); // base cur\n            // fx-eq corr\n            Real rhoxsik = (i == 0) ? 0.0 : // no fx process for base-ccy\n                               model_->correlation(FX, i - 1, EQ, k);\n            // ir instantaneous forward rate (from curve used for eq forward projection)\n            Real fr_i = model_->eqbs(k)->equityIrCurveToday()->forwardRate(t, t, Continuous);\n            // div yield instantaneous forward rate\n            Real fq_k = model_->eqbs(k)->equityDivYieldCurveToday()->forwardRate(t, t, Continuous);\n            res[model_->pIdx(EQ, k, 0)] = fr_i - fq_k + (rhozs0k * H0 * alpha0 * sigmask) -\n                                          (eps_ccy * rhoxsik * sigmaxi * sigmask) - (0.5 * sigmask * sigmask);\n        }\n        cache_m_.insert(std::make_pair(t, res));\n    } else {\n        res = i->second;\n    }\n    // non-cacheable sections of drifts\n    for (Size i = 1; i < n; ++i) {\n        // log spot fx drifts (z0, zi dependent parts)\n        Real Hi = model_->irlgm1f(i)->H(t);\n        Real Hprimei = model_->irlgm1f(i)->Hprime(t);\n        Real zetai = model_->irlgm1f(i)->zeta(t);\n        res[model_->pIdx(FX, i - 1, 0)] += x[model_->pIdx(IR, 0, 0)] * Hprime0 + zeta0 * Hprime0 * H0 -\n                                           x[model_->pIdx(IR, i, 0)] * Hprimei - zetai * Hprimei * Hi;\n    }\n    for (Size k = 0; k < n_eq; ++k) {\n        // log equity spot drifts (path-dependent parts)\n        // notice the assumption in below that dividend yield curve is static\n        Size i = model_->ccyIndex(model_->eqbs(k)->currency());\n        // ir params (for equity currency)\n        Real Hi = model_->irlgm1f(i)->H(t);\n        Real Hprimei = model_->irlgm1f(i)->Hprime(t);\n        Real zetai = model_->irlgm1f(i)->zeta(t);\n        res[model_->pIdx(EQ, k, 0)] += (x[model_->pIdx(IR, i, 0)] * Hprimei) + (zetai * Hprimei * Hi);\n    }\n    /* no drift for infdk, crlgm1f components */\n    return res;\n}\n\nDisposable<Matrix> CrossAssetStateProcess::diffusion(Time t, const Array& x) const {\n    boost::unordered_map<double, Matrix>::const_iterator i = cache_d_.find(t);\n    if (i == cache_d_.end()) {\n        Matrix tmp = pseudoSqrt(diffusionImpl(t, x), salvaging_);\n        cache_d_.insert(std::make_pair(t, tmp));\n        return tmp;\n    } else {\n        // we have to make a copy, otherwise we destroy the map entry\n        // since a disposable is returned\n        Matrix tmp = i->second;\n        return tmp;\n    }\n}\n\nDisposable<Matrix> CrossAssetStateProcess::diffusionImpl(Time t, const Array&) const {\n    Matrix res(model_->dimension(), model_->dimension());\n    Size n = model_->components(IR);\n    Size m = model_->components(FX);\n    Size d = model_->components(INF);\n    Size c = model_->components(CR);\n    Size e = model_->components(EQ);\n    // ir-ir\n    for (Size i = 0; i < n; ++i) {\n        for (Size j = 0; j <= i; ++j) {\n            Real alphai = model_->irlgm1f(i)->alpha(t);\n            Real alphaj = model_->irlgm1f(j)->alpha(t);\n            Real rhozz = model_->correlation(IR, i, IR, j, 0, 0);\n            setValue(res, alphai * alphaj * rhozz, model_, IR, i, IR, j, 0, 0);\n        }\n    }\n    // ir-fx\n    for (Size i = 0; i < n; ++i) {\n        Real alphai = model_->irlgm1f(i)->alpha(t);\n        for (Size j = 0; j < m; ++j) {\n            Real sigmaj = model_->fxbs(j)->sigma(t);\n            Real rhozx = model_->correlation(IR, i, FX, j, 0, 0);\n            setValue(res, alphai * sigmaj * rhozx, model_, IR, i, FX, j, 0, 0);\n        }\n    }\n    // fx-fx\n    for (Size i = 0; i < m; ++i) {\n        Real sigmai = model_->fxbs(i)->sigma(t);\n        for (Size j = 0; j <= i; ++j) {\n            Real sigmaj = model_->fxbs(j)->sigma(t);\n            Real rhoxx = model_->correlation(FX, i, FX, j, 0, 0);\n            setValue(res, sigmai * sigmaj * rhoxx, model_, FX, i, FX, j, 0, 0);\n        }\n    }\n    // ir,fx,inf - inf\n    for (Size j = 0; j < d; ++j) {\n        Real alphaj = model_->infdk(j)->alpha(t);\n        Real Hj = model_->infdk(j)->H(t);\n        for (Size i = 0; i <= j; ++i) {\n            Real alphai = model_->infdk(i)->alpha(t);\n            Real Hi = model_->infdk(i)->H(t);\n            Real rhoyy = model_->correlation(INF, i, INF, j, 0, 0);\n            // infz-infz\n            setValue(res, alphai * alphaj * rhoyy, model_, INF, i, INF, j, 0, 0);\n            // infz-infy\n            setValue(res, alphai * alphaj * Hj * rhoyy, model_, INF, i, INF, j, 0, 1);\n            setValue(res, alphai * Hi * alphaj * rhoyy, model_, INF, i, INF, j, 1, 0);\n            // infy-infy\n            setValue(res, alphai * Hi * alphaj * Hj * rhoyy, model_, INF, i, INF, j, 1, 1);\n        }\n        for (Size i = 0; i < n; ++i) {\n            Real alphai = model_->irlgm1f(i)->alpha(t);\n            Real rhozy = model_->correlation(IR, i, INF, j, 0, 0);\n            // ir-inf\n            setValue(res, alphai * alphaj * rhozy, model_, IR, i, INF, j, 0, 0);\n            setValue(res, alphai * alphaj * Hj * rhozy, model_, IR, i, INF, j, 0, 1);\n        }\n        for (Size i = 0; i < (n - 1); ++i) {\n            Real sigmai = model_->fxbs(i)->sigma(t);\n            Real rhoxy = model_->correlation(FX, i, INF, j, 0, 0);\n            // fx-inf\n            setValue(res, sigmai * alphaj * rhoxy, model_, FX, i, INF, j, 0, 0);\n            setValue(res, sigmai * alphaj * Hj * rhoxy, model_, FX, i, INF, j, 0, 1);\n        }\n    }\n    // ir,fx,inf,cr - cr\n    for (Size j = 0; j < c; ++j) {\n        Real alphaj = model_->crlgm1f(j)->alpha(t);\n        Real Hj = model_->crlgm1f(j)->H(t);\n        for (Size i = 0; i <= j; ++i) {\n            Real alphai = model_->crlgm1f(i)->alpha(t);\n            Real Hi = model_->crlgm1f(i)->H(t);\n            Real rholl = model_->correlation(CR, i, CR, j, 0, 0);\n            // crz-crz\n            setValue(res, alphai * alphaj * rholl, model_, CR, i, CR, j, 0, 0);\n            // crz-cry\n            setValue(res, alphai * alphaj * Hj * rholl, model_, CR, i, CR, j, 0, 1);\n            setValue(res, alphai * Hi * alphaj * rholl, model_, CR, i, CR, j, 1, 0);\n            // cry-cry\n            setValue(res, alphai * alphaj * Hi * Hj * rholl, model_, CR, i, CR, j, 1, 1);\n        }\n        for (Size i = 0; i < n; ++i) {\n            Real alphai = model_->irlgm1f(i)->alpha(t);\n            Real rhozl = model_->correlation(IR, i, CR, j, 0, 0);\n            // ir-cr\n            setValue(res, alphai * alphaj * rhozl, model_, IR, i, CR, j, 0, 0);\n            setValue(res, alphai * alphaj * Hj * rhozl, model_, IR, i, CR, j, 0, 1);\n        }\n        for (Size i = 0; i < (n - 1); ++i) {\n            Real sigmai = model_->fxbs(i)->sigma(t);\n            Real rhoxl = model_->correlation(FX, i, CR, j, 0, 0);\n            // fx-cr\n            setValue(res, sigmai * alphaj * rhoxl, model_, FX, i, CR, j, 0, 0);\n            setValue(res, sigmai * alphaj * Hj * rhoxl, model_, FX, i, CR, j, 0, 1);\n        }\n        for (Size i = 0; i < d; ++i) {\n            Real alphai = model_->infdk(i)->alpha(t);\n            Real Hi = model_->infdk(i)->H(t);\n            Real rhoyl = model_->correlation(INF, i, CR, j, 0, 0);\n            // inf-cr\n            setValue(res, alphai * alphaj * rhoyl, model_, INF, i, CR, j, 0, 0);\n            setValue(res, Hi * alphai * alphaj * rhoyl, model_, INF, i, CR, j, 1, 0);\n            setValue(res, alphai * alphaj * Hj * rhoyl, model_, INF, i, CR, j, 0, 1);\n            setValue(res, alphai * Hi * alphaj * Hj * rhoyl, model_, INF, i, CR, j, 1, 1);\n        }\n    }\n    // ir,fx,inf,cr,eq - eq\n    for (Size j = 0; j < e; ++j) {\n        Real sigmaj = model_->eqbs(j)->sigma(t);\n        // ir-eq\n        for (Size i = 0; i < n; ++i) {\n            Real alphai = model_->irlgm1f(i)->alpha(t);\n            Real rhozs = model_->correlation(IR, i, EQ, j, 0, 0);\n            Real value = alphai * sigmaj * rhozs;\n            setValue(res, value, model_, IR, i, EQ, j, 0, 0);\n        }\n        // fx-eq\n        for (Size i = 0; i < m; ++i) {\n            Real sigmai = model_->fxbs(i)->sigma(t);\n            Real rhoxs = model_->correlation(FX, i, EQ, j, 0, 0);\n            Real value = sigmai * sigmaj * rhoxs;\n            setValue(res, value, model_, FX, i, EQ, j, 0, 0);\n        }\n        // inf-eq\n        for (Size i = 0; i < d; ++i) {\n            Real alphai = model_->infdk(i)->alpha(t);\n            Real Hi = model_->infdk(i)->H(t);\n            Real rhoys = model_->correlation(INF, i, EQ, j, 0, 0);\n            setValue(res, alphai * sigmaj * rhoys, model_, INF, i, EQ, j, 0, 0);\n            setValue(res, Hi * alphai * sigmaj * rhoys, model_, INF, i, EQ, j, 1, 0);\n        }\n        // cr-eq\n        for (Size i = 0; i < c; ++i) {\n            Real alphai = model_->crlgm1f(i)->alpha(t);\n            Real Hi = model_->crlgm1f(i)->H(t);\n            Real rhols = model_->correlation(CR, i, EQ, j, 0, 0);\n            setValue(res, alphai * sigmaj * rhols, model_, CR, i, EQ, j, 0, 0);\n            setValue(res, Hi * alphai * sigmaj * rhols, model_, CR, i, EQ, j, 1, 0);\n        }\n        // eq-eq\n        for (Size i = 0; i <= j; ++i) {\n            Real sigmai = model_->eqbs(i)->sigma(t);\n            Real rhoss = model_->correlation(EQ, i, EQ, j, 0, 0);\n            Real value = sigmai * sigmaj * rhoss;\n            setValue(res, value, model_, EQ, i, EQ, j, 0, 0);\n        }\n    }\n    return res;\n}\n\nCrossAssetStateProcess::ExactDiscretization::ExactDiscretization(const CrossAssetModel* const model,\n                                                                 SalvagingAlgorithm::Type salvaging)\n    : model_(model), salvaging_(salvaging) {}\n\nDisposable<Array> CrossAssetStateProcess::ExactDiscretization::drift(const StochasticProcess& p, Time t0,\n                                                                     const Array& x0, Time dt) const {\n    Array res;\n    cache_key k = { t0, dt };\n    boost::unordered_map<cache_key, Array>::const_iterator i = cache_m_.find(k);\n    if (i == cache_m_.end()) {\n        res = driftImpl1(p, t0, x0, dt);\n        cache_m_.insert(std::make_pair(k, res));\n    } else {\n        res = i->second;\n    }\n    Array res2 = driftImpl2(p, t0, x0, dt);\n    for (Size i = 0; i < res.size(); ++i) {\n        res[i] += res2[i];\n    }\n    return res - x0;\n}\n\nDisposable<Matrix> CrossAssetStateProcess::ExactDiscretization::diffusion(const StochasticProcess& p, Time t0,\n                                                                          const Array& x0, Time dt) const {\n    cache_key k = { t0, dt };\n    boost::unordered_map<cache_key, Matrix>::const_iterator i = cache_d_.find(k);\n    if (i == cache_d_.end()) {\n        Matrix res = pseudoSqrt(covariance(p, t0, x0, dt), salvaging_);\n        // note that covariance actually does not depend on x0\n        cache_d_.insert(std::make_pair(k, res));\n        return res;\n    } else {\n        // see above about the copy\n        Matrix tmp = i->second;\n        return tmp;\n    }\n}\n\nDisposable<Matrix> CrossAssetStateProcess::ExactDiscretization::covariance(const StochasticProcess& p, Time t0,\n                                                                           const Array& x0, Time dt) const {\n    cache_key k = { t0, dt };\n    boost::unordered_map<cache_key, Matrix>::const_iterator i = cache_v_.find(k);\n    if (i == cache_v_.end()) {\n        Matrix res = covarianceImpl(p, t0, x0, dt);\n        cache_v_.insert(std::make_pair(k, res));\n        return res;\n    } else {\n        // see above about the copy\n        Matrix tmp = i->second;\n        return tmp;\n    }\n}\n\nDisposable<Array> CrossAssetStateProcess::ExactDiscretization::driftImpl1(const StochasticProcess&, Time t0,\n                                                                          const Array&, Time dt) const {\n    Size n = model_->components(IR);\n    Size m = model_->components(FX);\n    Size e = model_->components(EQ);\n    Array res(model_->dimension(), 0.0);\n    for (Size i = 0; i < n; ++i) {\n        res[model_->pIdx(IR, i, 0)] = ir_expectation_1(model_, i, t0, dt);\n    }\n    for (Size j = 0; j < m; ++j) {\n        res[model_->pIdx(FX, j, 0)] = fx_expectation_1(model_, j, t0, dt);\n    }\n    for (Size k = 0; k < e; ++k) {\n        res[model_->pIdx(EQ, k, 0)] = eq_expectation_1(model_, k, t0, dt);\n    }\n    return res;\n}\n\nDisposable<Array> CrossAssetStateProcess::ExactDiscretization::driftImpl2(const StochasticProcess&, Time t0,\n                                                                          const Array& x0, Time dt) const {\n    Size n = model_->components(IR);\n    Size m = model_->components(FX);\n    Size e = model_->components(EQ);\n    Array res(model_->dimension(), 0.0);\n    for (Size i = 0; i < n; ++i) {\n        res[model_->pIdx(IR, i, 0)] += ir_expectation_2(model_, i, x0[model_->pIdx(IR, i, 0)]);\n    }\n    for (Size j = 0; j < m; ++j) {\n        res[model_->pIdx(FX, j, 0)] += fx_expectation_2(model_, j, t0, x0[model_->pIdx(FX, j, 0)],\n                                                        x0[model_->pIdx(IR, j + 1, 0)], x0[model_->pIdx(IR, 0, 0)], dt);\n    }\n    for (Size k = 0; k < e; ++k) {\n        Size eqCcyIdx = model_->ccyIndex(model_->eqbs(k)->currency());\n        res[model_->pIdx(EQ, k, 0)] +=\n            eq_expectation_2(model_, k, t0, x0[model_->pIdx(EQ, k, 0)], x0[model_->pIdx(IR, eqCcyIdx, 0)], dt);\n    }\n    /*! inf, cr components have integrated drift 0, we have to return the conditional\n        expected value though, since x0 is subtracted later */\n    Size d = model_->components(INF);\n    for (Size i = 0; i < d; ++i) {\n        res[model_->pIdx(INF, i, 0)] = x0[model_->pIdx(INF, i, 0)];\n        res[model_->pIdx(INF, i, 1)] = x0[model_->pIdx(INF, i, 1)];\n    }\n    Size c = model_->components(CR);\n    for (Size i = 0; i < c; ++i) {\n        res[model_->pIdx(CR, i, 0)] = x0[model_->pIdx(CR, i, 0)];\n        res[model_->pIdx(CR, i, 1)] = x0[model_->pIdx(CR, i, 1)];\n    }\n    return res;\n}\n\nDisposable<Matrix> CrossAssetStateProcess::ExactDiscretization::covarianceImpl(const StochasticProcess&, Time t0,\n                                                                               const Array&, Time dt) const {\n    Matrix res(model_->dimension(), model_->dimension());\n    Size n = model_->components(IR);\n    Size m = model_->components(FX);\n    Size d = model_->components(INF);\n    Size c = model_->components(CR);\n    Size e = model_->components(EQ);\n    // ir-ir\n    for (Size i = 0; i < n; ++i) {\n        for (Size j = 0; j <= i; ++j) {\n            setValue(res, ir_ir_covariance(model_, i, j, t0, dt), model_, IR, i, IR, j, 0, 0);\n        }\n    }\n    // ir-fx\n    for (Size i = 0; i < n; ++i) {\n        for (Size j = 0; j < m; ++j) {\n            setValue(res, ir_fx_covariance(model_, i, j, t0, dt), model_, IR, i, FX, j, 0, 0);\n        }\n    }\n    // fx-fx\n    for (Size i = 0; i < m; ++i) {\n        for (Size j = 0; j <= i; ++j) {\n            setValue(res, fx_fx_covariance(model_, i, j, t0, dt), model_, FX, i, FX, j);\n        }\n    }\n    // ir,fx,inf - inf\n    for (Size j = 0; j < d; ++j) {\n        for (Size i = 0; i <= j; ++i) {\n            // infz-infz\n            setValue(res, infz_infz_covariance(model_, i, j, t0, dt), model_, INF, i, INF, j, 0, 0);\n            // infz-infy\n            setValue(res, infz_infy_covariance(model_, i, j, t0, dt), model_, INF, i, INF, j, 0, 1);\n            setValue(res, infz_infy_covariance(model_, j, i, t0, dt), model_, INF, i, INF, j, 1, 0);\n            // infy-infy\n            setValue(res, infy_infy_covariance(model_, i, j, t0, dt), model_, INF, i, INF, j, 1, 1);\n        }\n        for (Size i = 0; i < n; ++i) {\n            // ir-inf\n            setValue(res, ir_infz_covariance(model_, i, j, t0, dt), model_, IR, i, INF, j, 0, 0);\n            setValue(res, ir_infy_covariance(model_, i, j, t0, dt), model_, IR, i, INF, j, 0, 1);\n        }\n        for (Size i = 0; i < (n - 1); ++i) {\n            // fx-inf\n            setValue(res, fx_infz_covariance(model_, i, j, t0, dt), model_, FX, i, INF, j, 0, 0);\n            setValue(res, fx_infy_covariance(model_, i, j, t0, dt), model_, FX, i, INF, j, 0, 1);\n        }\n    }\n    // ir,fx,inf,cr - cr\n    for (Size j = 0; j < c; ++j) {\n        for (Size i = 0; i <= j; ++i) {\n            // crz-crz\n            setValue(res, crz_crz_covariance(model_, i, j, t0, dt), model_, CR, i, CR, j, 0, 0);\n            // crz-cry\n            setValue(res, crz_cry_covariance(model_, i, j, t0, dt), model_, CR, i, CR, j, 0, 1);\n            setValue(res, crz_cry_covariance(model_, j, i, t0, dt), model_, CR, i, CR, j, 1, 0);\n            // cry-cry\n            setValue(res, cry_cry_covariance(model_, i, j, t0, dt), model_, CR, i, CR, j, 1, 1);\n        }\n        for (Size i = 0; i < n; ++i) {\n            // ir-cr\n            setValue(res, ir_crz_covariance(model_, i, j, t0, dt), model_, IR, i, CR, j, 0, 0);\n            setValue(res, ir_cry_covariance(model_, i, j, t0, dt), model_, IR, i, CR, j, 0, 1);\n        }\n        for (Size i = 0; i < (n - 1); ++i) {\n            // fx-cr\n            setValue(res, fx_crz_covariance(model_, i, j, t0, dt), model_, FX, i, CR, j, 0, 0);\n            setValue(res, fx_cry_covariance(model_, i, j, t0, dt), model_, FX, i, CR, j, 0, 1);\n        }\n        for (Size i = 0; i < d; ++i) {\n            // inf-cr\n            setValue(res, infz_crz_covariance(model_, i, j, t0, dt), model_, INF, i, CR, j, 0, 0);\n            setValue(res, infy_crz_covariance(model_, i, j, t0, dt), model_, INF, i, CR, j, 1, 0);\n            setValue(res, infz_cry_covariance(model_, i, j, t0, dt), model_, INF, i, CR, j, 0, 1);\n            setValue(res, infy_cry_covariance(model_, i, j, t0, dt), model_, INF, i, CR, j, 1, 1);\n        }\n    }\n    // ir,fx,inf,cr,eq - eq\n    for (Size j = 0; j < e; ++j) {\n        for (Size i = 0; i <= j; ++i) {\n            // eq-eq\n            setValue(res, eq_eq_covariance(model_, i, j, t0, dt), model_, EQ, i, EQ, j, 0, 0);\n        }\n        for (Size i = 0; i < n; ++i) {\n            // ir-eq\n            setValue(res, ir_eq_covariance(model_, i, j, t0, dt), model_, IR, i, EQ, j, 0, 0);\n        }\n        for (Size i = 0; i < (n - 1); ++i) {\n            // fx-eq\n            setValue(res, fx_eq_covariance(model_, i, j, t0, dt), model_, FX, i, EQ, j, 0, 0);\n        }\n        for (Size i = 0; i < d; ++i) {\n            // inf-eq\n            setValue(res, infz_eq_covariance(model_, i, j, t0, dt), model_, INF, i, EQ, j, 0, 0);\n            setValue(res, infy_eq_covariance(model_, i, j, t0, dt), model_, INF, i, EQ, j, 1, 0);\n        }\n        for (Size i = 0; i < c; ++i) {\n            // cr-eq\n            setValue(res, crz_eq_covariance(model_, i, j, t0, dt), model_, CR, i, EQ, j, 0, 0);\n            setValue(res, cry_eq_covariance(model_, i, j, t0, dt), model_, CR, i, EQ, j, 1, 0);\n        }\n    }\n    return res;\n}\n\nvoid CrossAssetStateProcess::ExactDiscretization::flushCache() const {\n    cache_m_.clear();\n    cache_v_.clear();\n    cache_d_.clear();\n}\n\n} // namespace QuantExt\n", "meta": {"hexsha": "2d7ebb4559cf02518f378920f56868f8d32350af", "size": 24155, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "QuantExt/qle/processes/crossassetstateprocess.cpp", "max_stars_repo_name": "PiotrSiejda/Engine", "max_stars_repo_head_hexsha": "8360b5de32408f2a37da5ac3ca7b4e913bf67e9f", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "QuantExt/qle/processes/crossassetstateprocess.cpp", "max_issues_repo_name": "PiotrSiejda/Engine", "max_issues_repo_head_hexsha": "8360b5de32408f2a37da5ac3ca7b4e913bf67e9f", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "QuantExt/qle/processes/crossassetstateprocess.cpp", "max_forks_repo_name": "PiotrSiejda/Engine", "max_forks_repo_head_hexsha": "8360b5de32408f2a37da5ac3ca7b4e913bf67e9f", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-02-07T02:04:10.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-07T02:04:10.000Z", "avg_line_length": 44.5664206642, "max_line_length": 120, "alphanum_fraction": 0.5277168288, "num_tokens": 7607, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7690802264851919, "lm_q2_score": 0.43398146480389854, "lm_q1q2_score": 0.33376656324175763}}
{"text": "#include <cassert>\n#include <iostream>\n#include <fstream>\n#include <sstream>\n#include <cmath>\n#include <iomanip>\n#include <armadillo>\n\n#include \"constant.hpp\"\n#include \"mt_random.hpp\"\n\nusing namespace std;\n\nnamespace willow {\n\n// global variables\nconst  int m_natom = 2;\nconst  int m_nnhc  = 4;\nstatic int m_nbead;\nstatic int m_nstep;\nstatic int m_irst;\nstatic int m_nref;\nstatic double m_dt;\nstatic double m_dt_ref;\nstatic double m_gfree_nm;\n\nstatic double m_ZPE;\nstatic double m_omega;\nstatic double m_omega_p2;\nstatic double m_temp_nm;\nstatic double m_beta_nm;\nstatic double m_ekin_nm;\n\nconst  double delt_x = 4.e-3;\n\nstatic arma::vec prob_dx;      // (0:399)\nstatic arma::vec prob_dx_pos1; // (0:399)\nstatic arma::vec prob_dx_pos2; // (0:399)\n\nstatic arma::vec2 m_mass;     // (m_natom)\nstatic double     m_rmass;    // reduced mass\n\nstatic arma::mat  m_tmat_nm;  // (m_nbead, m_nbead)\nstatic arma::mat  m_fict_mass;// (m_natom, m_nbead)\n\nstatic arma::vec  m_rbath_nm; // (m_nnhc)\nstatic arma::vec  m_vbath_nm; //\nstatic arma::vec  m_qmass_nm; //\n\n// one-dimensional system\n// Cartesian Coordinate \nstatic arma::mat  m_pos_qm;   // (m_natom, m_nbead)\nstatic arma::mat  m_grd_qm;   // (m_natom, m_nbead)\n\n// Normal Mode\nstatic arma::mat  m_pos_nm;   // (m_natom, m_nbead)\nstatic arma::mat  m_vel_nm;   // (m_natom, m_nbead)\nstatic arma::mat  m_grd_nm;   // (m_natom, m_nbead)\nstatic arma::mat  m_grd_nm_spr; // (m_natom, m_nbead)\n  \n\nstatic void sample_rho ()\n{\n\n  // QM (beads)\n  \n  for (auto ib = 0; ib < m_nbead; ++ib) {\n\n    // (1) \\rho(x) = \\rho (x2-x1)\n    double dx = m_pos_qm(1,ib) - m_pos_qm(0,ib); \n    int  id1  = (int) round(dx/delt_x) + 200;\n    \n    if (id1 >= 0 && id1 < 400) prob_dx(id1) += 1;\n    \n    //\n    // (2) distribution of beads around pos(0) and pos(1)\n    // \\varrho(x) = \\varrho (x1 - X1)  \n    dx   = m_pos_qm(0,ib); \n    id1  = (int) round(dx/delt_x) + 200;\n    if (id1 >= 0 && id1 < 400) prob_dx_pos1(id1) += 1;\n    \n    // \n    dx   = m_pos_qm(1,ib); \n    id1  = (int) round(dx/delt_x) + 200;\n    if (id1 >= 0 && id1 < 400) prob_dx_pos2(id1) += 1;\n    \n  }\n  \n}\n\n\nvoid nm_nhc_integrate ()\n{\n  // Nose-Hoover Chain Method\n  \n  const double dt_ref  = m_dt_ref;\n  const double dt_ref2 = 0.5*dt_ref;\n  const double dt_ref4 = 0.5*dt_ref2;\n  const double dt_ref8 = 0.5*dt_ref4;\n\n  // m_nnhc = 4\n  arma::vec4 rbath;\n  arma::vec4 vbath;\n  arma::vec4 fbath;\n  arma::vec4 qmass;\n  \n  double ekin_nm = 0.0;\n  \n  for (size_t ib = 1; ib < m_nbead; ++ib) {\n    \n    for (size_t ia = 0; ia < m_natom; ++ia) {\n\n      double mass = m_fict_mass (ia, ib);\n      double v    = m_vel_nm(ia,ib);\n\n      ekin_nm += mass * v * v;\n      \n    }\n\n  }\n  \n  //---\n    \n  vbath = m_vbath_nm;\n  rbath = m_rbath_nm;\n  qmass = m_qmass_nm;\n\n  // ihc = 0\n  fbath(0) = (ekin_nm - m_gfree_nm*m_ekin_nm)/qmass(0);\n    \n  for (size_t ihc = 1; ihc < m_nnhc; ++ihc) {\n    fbath(ihc) =\n      (qmass(ihc-1)*vbath(ihc-1)*vbath(ihc-1) - m_ekin_nm) / qmass(ihc);\n  }\n  \n  // Update Thermostat Velocities\n  \n  vbath(m_nnhc-1) = vbath(m_nnhc-1) + fbath(m_nnhc-1)*dt_ref4;\n    \n  for (auto ihc = 1; ihc < m_nnhc; ++ihc) {\n    const auto jhc     = m_nnhc - ihc;\n    const double vfact = exp (-vbath(jhc)*dt_ref8);\n    const double vtmp  = vbath(jhc-1);\n    vbath(jhc-1) = vtmp*vfact*vfact + fbath(jhc-1)*vfact*dt_ref4;\n  }\n  \n  // Update atomic velocities\n  const double pvfact = exp(-vbath(0)*dt_ref2);\n  \n  ekin_nm  = ekin_nm*pvfact*pvfact;\n  \n  // Update thermostat forces\n  \n  fbath(0) = (ekin_nm - m_gfree_nm*m_ekin_nm)/qmass(0);\n    \n  for (auto ihc = 0; ihc < m_nnhc; ++ihc) {\n    rbath(ihc) += vbath(ihc)*dt_ref2;\n  }\n  \n  // Update Thermostat velocities\n    \n  for (auto ihc = 0; ihc < m_nnhc-1; ++ihc) {\n    const double vfact = exp(-vbath(ihc+1)*dt_ref8);\n    const double vtmp  = vbath(ihc);\n      \n    vbath(ihc) = vtmp*vfact*vfact + fbath(ihc)*vfact*dt_ref4;\n    fbath(ihc+1) =\n      (qmass(ihc)*vbath(ihc)*vbath(ihc) - m_ekin_nm)/qmass(ihc+1);\n  }\n    \n  vbath(m_nnhc-1) += fbath(m_nnhc-1)*dt_ref4;\n\n\n  // backup\n  m_vbath_nm = vbath;\n  m_rbath_nm = rbath;\n    \n  // update velocities of normal modes\n  for (auto ib = 1; ib < m_nbead; ++ib)\n    for (auto ia = 0; ia < m_natom; ++ia) {\n      m_vel_nm(ia,ib) *= pvfact;\n    } // ia\n\n  \n}\n\n\n\nvoid nm_pos_update ()\n{\n  \n  m_pos_nm += m_dt_ref * m_vel_nm;\n\n}\n\n\n\n\nvoid nm_grad_spring ()\n{\n  \n  //\n  // centroid gradient is zero\n  //\n  m_grd_nm_spr.col(0).zeros();\n  \n  //\n  // Gradients from the Springs between 'neighboring' beads\n  //\n  \n  for (size_t ib = 1; ib < m_nbead; ++ib) {\n    \n    for (size_t ia = 0; ia < m_natom; ++ia) {\n    \n      const double fact = m_fict_mass(ia,ib)*m_omega_p2;\n\n      m_grd_nm_spr(ia,ib) = fact * m_pos_nm(ia,ib);\n    }\n  }\n  \n  \n}\n\n\n\n\n\nvoid nm_pos_trans ()\n{\n  //\n  // normal mode (nm) ---> Cartesian (qm)\n  // pos_nm --->  pos_qm\n  \n  for (auto ib = 0; ib < m_nbead; ++ib) {\n    \n    arma::vec pos_x (m_natom, arma::fill::zeros);\n    \n    for (auto jb = 0; jb < m_nbead; ++jb) {\n      pos_x += m_tmat_nm(ib,jb)*m_pos_nm.col(jb);\n    }\n    \n    m_pos_qm.col(ib) = pos_x;\n  }\n\n}\n\n\n\n\nvoid nm_grad_trans ()\n{\n\n  m_grd_nm.zeros();\n  \n  for (size_t ib = 0; ib < m_nbead; ++ib) {\n    for (size_t jb = 0; jb < m_nbead; ++jb) {\n      m_grd_nm.col(ib) += m_tmat_nm(jb,ib)*m_grd_qm.col(jb);\n    }\n  }\n\n}\n\n\n\n\nvoid nm_pos_init () \n{\n\n  {// centroid particle\n    m_pos_nm.col(0).zeros();\n  }\n\n  { // beads : normal mode\n    const double dbead = m_nbead;\n    const double usigma = 0.02*ang2bohr; // sigma_x = 0.02 A\n    \n    \n    for (size_t ib = 1; ib < m_nbead; ++ib) {\n      \n      arma::vec2 pos_nm_ib;\n      for (size_t ia = 0; ia < m_natom; ++ia) {\n\n\tdouble mass05 = sqrt(m_fict_mass(ia,ib));\n\tpos_nm_ib(ia) = usigma*rnd::gaus_dev()/mass05;\n      }\n\n      m_pos_nm.col(ib) = pos_nm_ib;\n      \n    }\n  } // beads\n\n}\n\n\nvoid nm_vel_init ()\n{\n\n  // ---- centroid ----\n  {\n    // Here, vel_nm(ib = 0) zero\n    m_vel_nm.col(0).zeros();\n  }\n  \n  { // velocities for bead particles (or nm-mode particles)\n\n    for (size_t ib = 1; ib < m_nbead; ++ib) {\n      \n      double sum_p    = 0.0; \n      double sum_mass = 0.0;\n      \n      for (size_t ia = 0; ia < m_natom; ++ia) {\n\t\n\tdouble mass   = m_fict_mass(ia,ib);\n\tdouble vsigma = sqrt (m_ekin_nm/mass);\n\n\tdouble v = vsigma*rnd::gaus_dev();\n\n\tm_vel_nm(ia,ib) = v; \n\t\n\tsum_p    += mass*v;\n\tsum_mass += mass;\n      }\n      \n      sum_p /= sum_mass;\n\n      // translational motion is zero\n      for (auto ia = 0; ia < m_natom; ++ia) {\n\tm_vel_nm(ia,ib) -= sum_p;\n      }\n      \n    }\n    \n    //\n    // one-dimensional diatomic molecule\n    // does not have the rotational motion.\n    //\n    \n    // Scale Velocity \n    double ekin_nm = 0.0;\n    \n    for (size_t ib = 1; ib < m_nbead; ++ib) {\n\t\n      for (size_t ia = 0; ia < m_natom; ++ia) {\n\t\n\tdouble mass  = m_fict_mass(ia,ib);\n\tdouble v     = m_vel_nm(ia,ib);\n\tekin_nm += mass * v*v;\n\t\n      }\n      \n    }\n    \n    double temp  = ekin_nm / (m_gfree_nm*boltz);\n    double scale = sqrt(m_temp_nm / temp);\n\n    for (size_t ib = 1; ib < m_nbead; ++ib) {\n\n      for (size_t ia = 0; ia < m_natom; ++ia) {\n\t\n\tm_vel_nm(ia,ib) *= scale;\n\t\n      }\n\t\n    } // ib\n    \n  } // velocities for bead particles\n\n}\n\n\n\nvoid nm_vel_update ()\n{\n\n  // (ib = 0) belongs to the centroid velocity\n\n  \n  //---\n  const double dt2 = 0.5*m_dt;\n  \n  for (size_t ib = 1; ib < m_nbead; ++ib) {\n    for (size_t ia = 0; ia < m_natom; ++ia) {\n      double mass   = m_fict_mass(ia,ib); \n      double factor = dt2/mass;\n      m_vel_nm(ia,ib) -= factor*m_grd_nm(ia,ib);\n    }\n  }\n\n}\n\n\n\n\nvoid nm_vel_spring_update ()\n{\n\n  double dt2 = 0.5*m_dt_ref;\n  \n  for (size_t ib = 1; ib < m_nbead; ++ib) {\n    \n    for (size_t ia = 0; ia < m_natom; ++ia) {\n      double mass   = m_fict_mass(ia,ib); \n      double factor = dt2/mass;\n      m_vel_nm(ia,ib) -=\n\tfactor*m_grd_nm_spr(ia,ib);\n    }\n\n  }\n\n}\n\n\ndouble nm_pot_grad ()\n{\n  \n  // beads: normal mode ---> cartesian\n  //        pos_nm ----> pos_qm\n  nm_pos_trans ();\n  \n  double u_vib = 0.0;\n  m_grd_qm.zeros();\n\n  //\n  // force constant: reduced_mass*omega*omega\n  //\n  \n  double k_val = m_rmass*m_omega*m_omega;\n\n\n  // Harmonic Oscilltor: Diatomic Molecule\n  // U = 0.5 * k * (x2 - x1)**2\n  //\n  for (size_t ib = 0; ib < m_nbead; ib++) {\n    \n    // call your potential.\n    double dx = m_pos_qm(1,ib) - m_pos_qm(0,ib);\n    double en_harm = 0.5*k_val*dx*dx;\n    \n    m_grd_qm(1,ib) =  k_val*dx;\n    m_grd_qm(0,ib) = -k_val*dx;\n    \n    u_vib += en_harm;\n  } // ib\n    \n  \n  // ---\n  double d_nbead = m_nbead;\n  u_vib /= d_nbead;\n  \n  m_grd_qm /= d_nbead;\n  \n  //\n  // cartesian gradient ---> normal mode gradient\n  //\n  nm_grad_trans ();\n  \n  \n  return u_vib;\n  \n}\n\n\nvoid nm_report (const int& istep,\n\t\tconst double& u_vib,\n\t\tdouble& E_eff) \n{\n  // kinetic energy for beads\n  double ekin_nm = 0.0;\n  \n  for (auto ib = 1; ib < m_nbead; ++ib) {\n    for (auto ia = 0; ia < m_natom; ++ia) {\n      double mass = m_fict_mass(ia,ib);\n      double v    = m_vel_nm(ia,ib); \n      ekin_nm += mass*v*v;\n    }\n  }\n\n  ekin_nm = 0.5*ekin_nm;\n  double temp_nm = 2.0*ekin_nm/(m_gfree_nm*boltz);\n\n  // Harmonic Potential of springs between neighboring beads\n\n  double qkin_nm = 0.0;\n  for (auto ib = 1; ib < m_nbead; ++ib)\n    for (auto ia = 0; ia < m_natom; ++ia) {\n      double fact  = 0.5*m_fict_mass(ia,ib)*m_omega_p2;\n      double q     = m_pos_nm(ia,ib);\n      qkin_nm += fact*q*q;\n    }\n\n  double ebath_nm = 0.0;\n\n  arma::vec4 qmass = m_qmass_nm;\n  ebath_nm += 0.5*qmass(0)*m_vbath_nm(0)*m_vbath_nm(0);\n  ebath_nm += m_gfree_nm*m_ekin_nm*m_rbath_nm(0);\n\n  for (auto ihc = 1; ihc < m_nnhc; ++ihc) {\n    ebath_nm += 0.5*qmass(ihc)*m_vbath_nm(ihc)*m_vbath_nm(ihc);\n    ebath_nm += m_ekin_nm*m_rbath_nm(ihc);\n  }\n  \n\n  E_eff = qkin_nm + u_vib; // <E_eff> = E_ZPE\n  double H_sys = ekin_nm + E_eff; // Hamiltonian of the system\n  double H_tot = H_sys + ebath_nm; // Total H.\n\n  // unit convert\n  E_eff *= au_kcal;\n  H_sys *= au_kcal;\n  H_tot *= au_kcal;\n\n  printf (\" %8d %14.6f %14.6f %14.6f %14.6f %10.2f \\n\",\n\t  (istep+1), H_tot, H_sys, E_eff, \n\t  u_vib*au_kcal, temp_nm);\n  \n  fflush (stdout);\n  \n}\n\n\n\nvoid read_restart_nm (int& istep0)\n{\n\n  // read a restart file\n  std::string str_rst;\n\n  std::ifstream ifs_rst (\"pimdrr.sav\");\n  assert (ifs_rst.good());\n  \n  std::ostringstream oss;\n  \n  oss << ifs_rst.rdbuf();\n  \n  str_rst = oss.str();\n\n  \n  std::istringstream is (str_rst);\n\n  std::string line;\n  std::getline (is, line); // istep\n  std::istringstream istep_ss (line);\n  istep_ss >> istep0;\n  \n  // ib = 0 is for centroids\n  for (auto ib = 1; ib < m_nbead; ++ib) {\n    std::getline (is, line);\n    std::istringstream iss_pos (line);\n    \n    iss_pos >> m_pos_nm(0,ib) >> m_pos_nm(1,ib);\n  \n    std::getline (is, line);\n    std::istringstream iss_vel (line);\n\n    iss_vel >> m_vel_nm(0,ib) >> m_vel_nm(1,ib);\n  }\n\n  for (auto ihc = 0; ihc < m_nnhc; ++ihc) {\n    std::getline (is,line);\n    std::istringstream iss (line);\n\n    iss >> m_rbath_nm(ihc) >> m_vbath_nm(ihc);\n  }\n\n  m_pos_nm(0,0) = 0.0; \n  m_pos_nm(1,0) = 0.0; \n  m_vel_nm(0,0) = 0.0; \n  m_vel_nm(1,0) = 0.0; \n  \n}\n\n\nvoid write_restart_nm (const int& istep)\n{\n\n  FILE *ofs_rst = fopen (\"pimdrr.sav\", \"w\");\n\n  fprintf( ofs_rst, \" %10d \\n\", istep+1);\n\n  // ib = 0 is for centroids\n  for (auto ib = 1; ib < m_nbead; ++ib) {\n    fprintf (ofs_rst, \"  %E   %E   \\n\", m_pos_nm(0,ib), m_pos_nm(1,ib));\n    fprintf (ofs_rst, \"  %E   %E   \\n\", m_vel_nm(0,ib), m_vel_nm(1,ib));\n  }\n\n  for (auto ihc = 0; ihc < m_nnhc; ++ihc) {\n    fprintf (ofs_rst, \"  %E   %E   %E \\n\",\n\t     m_rbath_nm(ihc),\n\t     m_vbath_nm(ihc),\n\t     m_qmass_nm(ihc) );\n  }\n  \n  fclose (ofs_rst);\n\n}\n\n\nvoid write_prob_bin (int& nsamp)\n{\n\n  double zeta2   = m_rmass*m_omega; // (unit 1/bohr**2)\n  \n  arma::vec p_dx = prob_dx/(m_nbead*(nsamp+1)*delt_x);\n  \n  std::ofstream ofs_qm (\"prob_bin_qm.dat\");\n  // psi_0\n  // zeta2 = mass*omega*(x*x)\n  // debug\n  const double zt    = sqrt(zeta2/M_PI); \n\n  double ave = 0.0;\n  \n  for (auto ib = 0; ib < 400; ++ib) {\n    double  x  = (ib - 200)*delt_x;\n    double  x2 =  x* x;\n    double rho =  zt*exp(-zeta2*x2);\n    ave += x*p_dx(ib);\n    ofs_qm << x << \"   \"  << p_dx(ib)\n\t   << \"  \" << rho << endl;\n  }\n\n  ofs_qm.close();\n\n  //\n  std::ofstream ofs_rho (\"prob_bin_rho.dat\");\n  arma::vec p_dx1  = prob_dx_pos1/(m_nbead*(nsamp+1)*delt_x);\n  arma::vec p_dx2  = prob_dx_pos2/(m_nbead*(nsamp+1)*delt_x);\n  \n  for (auto ib = 0; ib < 400; ++ib) {\n    double x = (ib - 200)*delt_x;\n    ofs_rho << x << \"   \"  << p_dx1(ib) << \"  \" << p_dx2(ib) << endl;\n  }\n  \n  ofs_rho.close();\n}\n\n\nvoid wpimd_run ()\n{\n\n  //\n  // This is a sample code,\n  // in which WPIMD is running at T (thermal temperature) = 0 K.\n  // \n  \n  int istep0 = 0;\n\n  if (m_irst == 1) {\n    read_restart_nm (istep0);\n  }\n  \n  // initial gradients and potential energy\n  double u_vib = nm_pot_grad ();\n\n  double e_eff = 0.0;\n  double sum_e_eff = 0.0;\n  int    ncount  = 0;\n  \n  nm_grad_spring ();\n\n  if (m_irst == 0)\n    nm_report (istep0-1, u_vib, e_eff);\n\n  for (auto istep = 0; istep < m_nstep; ++istep) {\n\n    nm_vel_update ();\n\n    for (auto iref = 0; iref < m_nref; ++iref) {\n      nm_nhc_integrate ();\n      nm_vel_spring_update();\n      nm_pos_update ();\n      nm_grad_spring();\n      nm_vel_spring_update();\n      nm_nhc_integrate ();\n    }\n\n    u_vib   = nm_pot_grad ();\n    \n    sample_rho ();\n    nm_vel_update ();\n    \n    if ( (istep+1)%500 == 0) {\n      nm_report (istep+istep0, u_vib, e_eff);\n      sum_e_eff += e_eff;\n      ncount++;\n    }\n    \n    if ( (istep+1)%5000 == 0) {\n      write_restart_nm   (istep+istep0);\n      write_prob_bin (istep);\n    }\n    \n  }\n\n  \n  cout << \"AVE E_eff \" << sum_e_eff / ncount << endl;\n\n  \n}\n\n\n\n\nvoid wpimd_init ()\n{\n\n  // one-dimensional system\n  m_gfree_nm = 1*m_nbead; // the vibrational degree of freedom\n  \n  // ZPE = 0.5 * hbar * omega\n  // ZPE(au) = 0.5 * omega\n  m_omega    = 2.0*m_ZPE;\n\n  // Eq. (14)\n  // temperature for the bead motions\n  m_temp_nm  = m_omega/(m_gfree_nm*boltz);\n\n  double dbead = m_nbead;\n  double omega_p = sqrt(dbead)*boltz*m_temp_nm;\n  m_omega_p2 = omega_p * omega_p;\n  m_beta_nm  = 1.0 / (boltz*m_temp_nm);\n  m_ekin_nm  = boltz*m_temp_nm;\n  \n  // mem alloc\n\n  m_tmat_nm   = arma::mat (m_nbead, m_nbead, arma::fill::zeros);\n  m_fict_mass = arma::mat (m_natom, m_nbead, arma::fill::zeros);\n\n  m_rbath_nm  = arma::vec (m_nnhc, arma::fill::zeros);\n  m_vbath_nm  = arma::vec (m_nnhc, arma::fill::zeros);\n  m_qmass_nm  = arma::vec (m_nnhc, arma::fill::zeros);\n\n  // one-dimensional system \n  m_pos_qm    = arma::mat (m_natom, m_nbead, arma::fill::zeros); \n  m_pos_nm    = arma::mat (m_natom, m_nbead, arma::fill::zeros);\n  \n  m_vel_nm    = arma::mat (m_natom, m_nbead, arma::fill::zeros);\n  \n  m_grd_qm    = arma::mat (m_natom, m_nbead, arma::fill::zeros);\n  m_grd_nm    = arma::mat (m_natom, m_nbead, arma::fill::zeros);\n  m_grd_nm_spr= arma::mat (m_natom, m_nbead, arma::fill::zeros);\n\n  // --- initiate the normal mode matrix.\n  for (size_t i = 0; i < m_nbead; ++i) {\n    m_tmat_nm(i, 0) = 1.0;\n  }\n    \n  for (size_t i = 0; i < m_nbead/2; ++i) {\n    m_tmat_nm(2*i,   m_nbead-1) = -1.0;\n    m_tmat_nm(2*i+1, m_nbead-1) =  1.0;\n  }\n\n  double dnorm = sqrt (2.0);\n    \n  for (size_t i = 0; i < m_nbead; ++i) {\n    const double di    = i+1;\n    const double phase = 2.0*di*(M_PI/dbead);\n    for (size_t j = 0; j < (m_nbead-2)/2; ++j) {\n      const double dj    = j+1;\n      m_tmat_nm(i, 2*j+1) = dnorm*cos(phase*dj);\n      m_tmat_nm(i, 2*j+2) = dnorm*sin(phase*dj);\n    }\n  }\n\n  // --- mass init ---\n  for (auto ia = 0; ia < m_natom; ++ia) {\n    double mass = m_mass(ia);\n\n    m_fict_mass(ia,0)         = mass;\n    m_fict_mass(ia,m_nbead-1) = 4.0*dbead*mass;\n\n    for (auto ib = 1; ib < m_nbead/2; ++ib) {\n      double val = 2.0*(1.0 - cos (2.0*ib*(M_PI/dbead)))*dbead*mass;\n      m_fict_mass(ia,2*ib-1) = val;\n      m_fict_mass(ia,2*ib  ) = val;\n    }\n  }\n\n  // reduced mass\n  double rmass = 0.0;\n\n  for (auto ia = 0; ia < m_natom; ++ia) {\n    rmass += 1.0/m_mass(ia);\n  }\n\n  m_rmass = 1.0/rmass;\n\n  // bath init for beads\n  \n    \n  m_qmass_nm(0) = m_gfree_nm*m_ekin_nm/m_omega_p2;\n    \n  for (size_t ihc = 1; ihc < m_nnhc; ++ihc) {\n    m_qmass_nm(ihc) = m_ekin_nm/m_omega_p2;\n  }\n  \n\n  nm_pos_init ();\n  nm_vel_init ();\n  \n  prob_dx      = arma::vec(400, arma::fill::zeros);\n  prob_dx_pos1 = arma::vec(400, arma::fill::zeros);\n  prob_dx_pos2 = arma::vec(400, arma::fill::zeros);\n  \n}\n\n\nvoid read_input (const std::string& fname)\n{\n\n  std::ifstream is_input(fname);\n  std::ostringstream oss;\n  oss << is_input.rdbuf();\n\n  std::istringstream ss (oss.str());\n\n  m_nstep = 1000;\n  m_dt   = 0.5; // fsec\n  m_irst = 0;\n  \n  m_nbead = 8;\n  m_nref  = 10;\n  m_ZPE   = 0.0; // kcal/mol\n\n  for (auto ia = 0; ia < m_natom; ++ia)\n    m_mass(ia)  = 1.0*amu2au; // amu --> au\n  \n  std::string line;\n\n  while(getline(ss, line)) {\n    std::istringstream iss (line);\n    std::string keyword;\n    std::string val;\n    iss >> keyword >> val;\n\n    if (keyword == \"nstep\") {\n      m_nstep = stoi (val);\n    }\n    else if (keyword == \"dt\") {\n      m_dt = stod(val);\n    }\n    else if (keyword == \"l_restart\") {\n      m_irst = stoi(val);\n    }\n    else if (keyword == \"nbead\") {\n      m_nbead = stoi(val);\n    }\n    else if (keyword == \"nref\") {\n      m_nref  = stoi(val);\n    }\n    else if (keyword == \"ZPE\") {\n      m_ZPE  = stod(val)/au_kcal; // kcal/mol ---> au\n    }\n    else if (keyword == \"mass1\") {\n      m_mass(0) = stod(val)*amu2au; // amu --> au\n    }\n    else if (keyword == \"mass2\") {\n      m_mass(1) = stod(val)*amu2au; // amu --> au\n    }\n    \n  }\n\n  // -- time : [fs] ---> [au]\n  m_dt  = m_dt * (1.0e-15/au_time);\n\n  m_dt_ref = m_dt/m_nref;\n  \n}\n\n\n} // namespace willow\n\n\nint main (int argc, char *argv[])\n{\n\n  cout << std::setprecision (6);\n  cout << std::fixed;\n\n\n  //--- read an input file --\n  const std::string fname = (argc > 1) ? argv[1] : \"sample2.inp\";\n\n  willow::read_input (fname);\n\n  willow::wpimd_init ();\n  \n  willow::wpimd_run ();\n\n  return 0;\n  \n}\n", "meta": {"hexsha": "89b7f2fdc242ae597b61ab6328d83326fd8928ce", "size": 17912, "ext": "cc", "lang": "C++", "max_stars_repo_path": "wpimd2.cc", "max_stars_repo_name": "swillow/w-pimd", "max_stars_repo_head_hexsha": "aee1dee3a0e4bfc68e271b00b5116b1b95380cbc", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "wpimd2.cc", "max_issues_repo_name": "swillow/w-pimd", "max_issues_repo_head_hexsha": "aee1dee3a0e4bfc68e271b00b5116b1b95380cbc", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "wpimd2.cc", "max_forks_repo_name": "swillow/w-pimd", "max_forks_repo_head_hexsha": "aee1dee3a0e4bfc68e271b00b5116b1b95380cbc", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-09-30T09:34:32.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-16T13:39:30.000Z", "avg_line_length": 20.0582306831, "max_line_length": 72, "alphanum_fraction": 0.5685015632, "num_tokens": 6739, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7057850278370112, "lm_q2_score": 0.47268347662043286, "lm_q1q2_score": 0.3336129207046475}}
{"text": "/**\n * \\file libsanm/sparse_solver.cpp\n * This file is part of SANM, a symbolic asymptotic numerical solver.\n */\n\n#include \"libsanm/sparse_solver.h\"\n\n#include <mkl_pardiso.h>\n#include <mkl_service.h>\n#include <mkl_spblas.h>\n#include <mkl_types.h>\n\n#include <cmath>\n#include <cstring>\n\n// set to 1 to construct a dense mat and print some statistics for debug\n#define PRINT_MAT 0\n\n#if PRINT_MAT\n#include <Eigen/Dense>\n#include <Eigen/SVD>\n#include <iostream>\n#endif\n\nusing namespace sanm;\n\nnamespace {\n\nclass ScopedMKLThreads {\npublic:\n    explicit ScopedMKLThreads(int nr) {\n        sanm_assert(nr > 0);\n        mkl_set_num_threads_local(nr);\n    }\n\n    ~ScopedMKLThreads() { mkl_set_num_threads_local(0); }\n};\n\n}  // anonymous namespace\n\n// use Intel PARDISO. See examples_core_c.tgz/solverc/source/pardiso_unsym_c.c\n\nclass SparseSolver::Impl final : public NonCopyable {\n    const size_t m_nr_unknown;\n    const int m_nr_threads;\n    bool m_prepared = false;\n\n    class MatBuilder;\n\n    std::vector<MKL_INT> m_ia, m_ja;\n    std::vector<double> m_a;\n\n    //! pointers for A'*A + p*I\n    sparse_matrix_t m_aTapI = nullptr;  //!< A'A\n    MKL_INT *m_aTapI_ia0 = nullptr, *m_aTapI_ia1 = nullptr,\n            *m_aTapI_ja = nullptr;\n    double* m_aTapI_a = nullptr;\n    TensorND m_aTapI_b;\n    sparse_index_base_t m_aTapI_idx{};\n\n    fp_t m_l2_penalty = 0;\n\n    sparse_matrix_t m_a_csr = nullptr;  //!< cached CSR descriptor\n    void* m_pt[64];\n    MKL_INT m_iparm[64];\n    MKL_INT m_mtype = -1;\n    std::vector<std::unique_ptr<MatBuilder>> m_mat_builders;\n\n    TensorND m_solution_cache;\n\n    void call_pardiso(MKL_INT phase, const double* b, double* x) {\n        if (m_mtype == -1) {\n            // initialize at first call\n\n            if (phase == -1) {\n                // destroy before first init\n                return;\n            }\n\n            init_pardiso();\n        }\n        sanm_assert(m_prepared);\n\n        MKL_INT maxfct = 1;  // max number of numerical factorizations\n        MKL_INT mnum = 1;    // 1 <= mnum <= maxfct\n        MKL_INT n = m_nr_unknown;\n        MKL_INT nrhs = 1;  // number of right hand sides\n        MKL_INT msglvl = sm_verbosity;\n        MKL_INT error = 0;\n        double* pa;\n        MKL_INT *ia, *ja;\n        if (m_l2_penalty == 0) {\n            pa = m_a.data();\n            ia = m_ia.data();\n            ja = m_ja.data();\n        } else {\n            pa = m_aTapI_a;\n            ia = m_aTapI_ia0;\n            ja = m_aTapI_ja;\n        }\n        pardiso(m_pt, &maxfct, &mnum, &m_mtype, &phase, &n, pa, ia, ja, nullptr,\n                &nrhs, m_iparm, &msglvl, const_cast<double*>(b), x, &error);\n        sanm_assert(error == 0, \"pardiso phase=%d failed: error=%d\",\n                    static_cast<int>(phase), error);\n    }\n\n    void init_pardiso() {\n        if (m_l2_penalty) {\n            // real and symmetric positive definite\n            m_mtype = 2;\n        } else {\n            // real and nonsymmetric matrix\n            m_mtype = 11;\n        }\n\n        pardisoinit(m_pt, &m_mtype, m_iparm);\n\n        m_iparm[17] = 0; /* I/O: Number of nonzeros in the factor LU */\n        m_iparm[18] = 0; /* I/O: Mflops for LU factorization */\n        m_iparm[34] = 1; /* Zero-based indexing */\n\n        if (m_nr_threads > 1) {\n            // The parallel (OpenMP) version of the nested dissection\n            // algorithm\n            m_iparm[1] = 3;\n        }\n    }\n\n    //! get a descriptor for the coeff matrix\n    sparse_matrix_t a_csr() {\n        if (!m_a_csr) {\n            auto err = mkl_sparse_d_create_csr(&m_a_csr, SPARSE_INDEX_BASE_ZERO,\n                                               m_nr_unknown, m_nr_unknown,\n                                               m_ia.data(), m_ia.data() + 1,\n                                               m_ja.data(), m_a.data());\n            sanm_assert(err == SPARSE_STATUS_SUCCESS,\n                        \"failed to create sparse matrix: err=%d\",\n                        static_cast<int>(err));\n        }\n        return m_a_csr;\n    }\n\npublic:\n    static int sm_verbosity;\n\n    Impl(size_t nr_xs) : m_nr_unknown{nr_xs}, m_nr_threads{get_num_threads()} {\n        sanm_assert(m_nr_threads >= 1);\n    }\n\n    ~Impl();\n\n    void prepare(fp_t l2_penalty);\n\n    TensorND solve(const TensorND& b) {\n        SANM_SCOPED_PROFILER(\"sparse_solve\");\n        ScopedMKLThreads mkl_threads{m_nr_threads};\n        sanm_assert(b.shape().total_nr_elems() == m_nr_unknown);\n        auto bptr = b.ptr();\n        for (size_t i = 0; i < m_nr_unknown; ++i) {\n            sanm_assert(std::isfinite(bptr[i]), \"b[%zu]=%g\", i, bptr[i]);\n        }\n        if (m_l2_penalty) {\n            m_aTapI_b.set_shape({m_nr_unknown});\n            matrix_descr desc{\n                    .type = SPARSE_MATRIX_TYPE_GENERAL,\n                    .mode = SPARSE_FILL_MODE_UPPER,\n                    .diag = SPARSE_DIAG_NON_UNIT,\n            };\n            auto status =\n                    mkl_sparse_d_mv(SPARSE_OPERATION_TRANSPOSE, 1, a_csr(),\n                                    desc, bptr, 0, m_aTapI_b.woptr());\n            sanm_assert(status == SPARSE_STATUS_SUCCESS,\n                        \"failed to compute A'b: status=%d\",\n                        static_cast<int>(status));\n            bptr = m_aTapI_b.ptr();\n        }\n        call_pardiso(33, bptr,\n                     m_solution_cache.set_shape({m_nr_unknown}).woptr());\n        return m_solution_cache;\n    }\n\n    void dump(const TensorND& b, FILE* fout) {\n        sanm_assert(m_prepared);\n        sanm_assert(b.empty() || (b.shape().total_nr_elems() == m_nr_unknown));\n        auto bptr = b.empty() ? nullptr : b.ptr();\n        fprintf(fout, \"======== begin SparseSolver_%p dump ========\\n\", this);\n        for (size_t i = 0; i < m_nr_unknown; ++i) {\n            fprintf(fout, \"<eqn%-3zu>: \", i);\n            for (int j = m_ia[i]; j < m_ia[i + 1]; ++j) {\n                fprintf(fout, \"%3.3fx%-5zu\", m_a[j],\n                        static_cast<size_t>(m_ja[j]));\n            }\n            if (bptr) {\n                fprintf(fout, \" = %g\\n\", bptr[i]);\n            } else {\n                fprintf(fout, \"\\n\");\n            }\n        }\n        fprintf(fout, \"======== end SparseSolver_%p dump ========\\n\", this);\n    }\n\n    TensorND apply(const TensorND& x) {\n        ScopedMKLThreads mkl_threads{m_nr_threads};\n        sanm_assert(m_prepared && x.rank() == 1 && x.shape(0) == m_nr_unknown);\n        auto ret = x.make_same_shape();\n        matrix_descr desc{.type = SPARSE_MATRIX_TYPE_GENERAL,\n                          .mode = SPARSE_FILL_MODE_UPPER,\n                          .diag = SPARSE_DIAG_NON_UNIT};\n        auto err = mkl_sparse_d_mv(SPARSE_OPERATION_NON_TRANSPOSE, 1, a_csr(),\n                                   desc, x.ptr(), 0, ret.woptr());\n        sanm_assert(err == SPARSE_STATUS_SUCCESS,\n                    \"failed to compute sparse mv: err=%d\",\n                    static_cast<int>(err));\n        return ret;\n    }\n\n    fp_t coeff_l2() const {\n        fp_t s = 0;\n        for (fp_t i : m_a) {\n            s += i * i;\n        }\n        return std::sqrt(s);\n    }\n\n    SparseMatBuilder* make_builder(size_t cidx_offset);\n};\nint SparseSolver::Impl::sm_verbosity = 0;\n\nclass SparseSolver::Impl::MatBuilder final\n        : public SparseSolver::SparseMatBuilder {\n    struct CsrRowPair {\n        leastsize_t col;\n        double val;\n\n        CsrRowPair() = default;\n        CsrRowPair(size_t c, double v)\n                : col{static_cast<leastsize_t>(c)}, val{v} {}\n\n        bool operator<(const CsrRowPair& rhs) const { return col < rhs.col; }\n    };\n\n    Impl* const m_owner;\n    const size_t m_offset;\n    size_t m_prev_constraint_cidx;\n    std::vector<CsrRowPair> m_csr_last_row;\n\n    std::vector<MKL_INT> m_ia, m_ja;\n    std::vector<double> m_a;\n\n    void flush_csr_row() {\n        sanm_assert(!m_csr_last_row.empty(), \"empty row %zu\",\n                    m_prev_constraint_cidx);\n        std::sort(m_csr_last_row.begin(), m_csr_last_row.end());\n        size_t jr = 0, jsize = m_csr_last_row.size();\n        m_csr_last_row.emplace_back(m_owner->m_nr_unknown,\n                                    0.);  // sentinel value\n\n        if (size_t tsize = m_a.size() + m_csr_last_row.size();\n            m_a.capacity() < tsize) {\n            tsize = std::max(tsize, m_a.capacity() * 3 / 2);\n            m_a.reserve(tsize);\n            m_ja.reserve(tsize);\n        }\n\n        m_ia.push_back(m_ja.size());\n        while (jr < jsize) {\n            leastsize_t c = m_csr_last_row[jr].col;\n            double v = m_csr_last_row[jr].val;\n            ++jr;\n            while (m_csr_last_row[jr].col == c) {\n                v += m_csr_last_row[jr].val;\n                ++jr;\n            }\n            m_ja.push_back(c);\n            m_a.push_back(v);\n        }\n        m_csr_last_row.clear();\n    }\n\npublic:\n    MatBuilder(Impl* owner, size_t offset)\n            : m_owner{owner},\n              m_offset{offset},\n              m_prev_constraint_cidx{offset} {}\n\n    void add_constraint(size_t cidx, size_t xidx, double coeff) override {\n        sanm_assert(!m_owner->m_prepared);\n        sanm_assert(std::isfinite(coeff), \"coeff[%zu,%zu]=%g\", cidx, xidx,\n                    coeff);\n\n        if (std::fabs(coeff) < 1e-9) {\n            return;\n        }\n\n        sanm_assert(cidx < m_owner->m_nr_unknown &&\n                    xidx < m_owner->m_nr_unknown);\n        if (cidx != m_prev_constraint_cidx) {\n            sanm_assert(cidx == m_prev_constraint_cidx + 1,\n                        \"constraints not added in order: prev=%zu cur=%zu\",\n                        m_prev_constraint_cidx, static_cast<size_t>(cidx));\n            flush_csr_row();\n            m_prev_constraint_cidx = cidx;\n        }\n        m_csr_last_row.emplace_back(xidx, coeff);\n    }\n\n    void prepare() {\n        flush_csr_row();\n        ++m_prev_constraint_cidx;\n    }\n\n    size_t ja_size() const { return m_ja.size(); }\n\n    size_t first_cidx() const { return m_offset; }\n\n    size_t last_cidx() const { return m_prev_constraint_cidx; }\n\n    void copy_into(size_t ia_offset, MKL_INT* ia, MKL_INT* ja, double* a) {\n        for (size_t i = m_offset; i < m_prev_constraint_cidx; ++i) {\n            ia[i] = m_ia[i - m_offset] + ia_offset;\n        }\n        memcpy(ja + ia_offset, m_ja.data(), sizeof(MKL_INT) * m_ja.size());\n        memcpy(a + ia_offset, m_a.data(), sizeof(double) * m_a.size());\n    }\n};\n\nvoid SparseSolver::Impl::prepare(fp_t l2_penalty) {\n    SANM_SCOPED_PROFILER(\"sparse_prep\");\n    sanm_assert(!m_prepared);\n    m_prepared = true;\n    m_l2_penalty = l2_penalty;\n\n    ScopedMKLThreads mkl_threads{m_nr_threads};\n\n    size_t tot_ja_size = 0;\n    for (auto& i : m_mat_builders) {\n        i->prepare();\n        tot_ja_size += i->ja_size();\n    }\n\n    std::sort(m_mat_builders.begin(), m_mat_builders.end(),\n              [](const std::unique_ptr<MatBuilder>& a,\n                 const std::unique_ptr<MatBuilder>& b) {\n                  return a->first_cidx() < b->first_cidx();\n              });\n\n    for (size_t i = 1; i < m_mat_builders.size(); ++i) {\n        sanm_assert(m_mat_builders[i]->first_cidx() ==\n                    m_mat_builders[i - 1]->last_cidx());\n    }\n    sanm_assert(m_mat_builders.back()->last_cidx() == m_nr_unknown);\n\n    m_ia.resize(m_nr_unknown + 1);\n    m_ja.resize(tot_ja_size);\n    m_a.resize(tot_ja_size);\n    m_ia.back() = tot_ja_size;\n    {\n        size_t offset = 0;\n        for (auto& i : m_mat_builders) {\n            i->copy_into(offset, m_ia.data(), m_ja.data(), m_a.data());\n            offset += i->ja_size();\n        }\n    }\n    m_mat_builders.clear();\n\n    if (m_l2_penalty) {\n        SANM_SCOPED_PROFILER(\"sparse_A'A\");\n        auto status =\n                mkl_sparse_syrk(SPARSE_OPERATION_TRANSPOSE, a_csr(), &m_aTapI);\n        sanm_assert(status == SPARSE_STATUS_SUCCESS,\n                    \"failed to compute A'A: status=%d\",\n                    static_cast<int>(status));\n        MKL_INT r, c;\n        status = mkl_sparse_d_export_csr(m_aTapI, &m_aTapI_idx, &r, &c,\n                                         &m_aTapI_ia0, &m_aTapI_ia1,\n                                         &m_aTapI_ja, &m_aTapI_a);\n        sanm_assert(status == SPARSE_STATUS_SUCCESS,\n                    \"failed to export A'A: status=%d\",\n                    static_cast<int>(status));\n\n        sanm_assert(r == c && static_cast<size_t>(r) == m_nr_unknown);\n\n        sanm_assert(m_aTapI_idx == SPARSE_INDEX_BASE_ZERO);\n        sanm_assert(m_aTapI_ia1 == m_aTapI_ia0 + 1);\n        for (int i = 0; i < r; ++i) {\n            int p = m_aTapI_ia0[i], c = m_aTapI_ja[p];\n            sanm_assert(i == c, \"row %d: first col is %d\", i, c);\n            m_aTapI_a[p] += m_l2_penalty;\n        }\n        if (sm_verbosity) {\n            printf(\"Linear solve with L2: n=%zu size_A=%zu size_A'A=%zu\\n\",\n                   m_nr_unknown, static_cast<size_t>(m_ia[m_nr_unknown]),\n                   static_cast<size_t>(m_aTapI_ia1[m_nr_unknown - 1]));\n        }\n    }\n\n#if PRINT_MAT\n    {\n        using Mat = Eigen::Matrix<fp_t, Eigen::Dynamic, Eigen::Dynamic>;\n        Mat M(m_nr_unknown, m_nr_unknown);\n        M.setZero();\n        for (size_t i = 0; i < m_nr_unknown; ++i) {\n            for (int j = m_ia[i]; j < m_ia[i + 1]; ++j) {\n                M(i, m_ja[j]) = m_a[j];\n            }\n        }\n        printf(\"======== dump sparse solver coeff: %zu\\n\", m_nr_unknown);\n        if (m_nr_unknown <= 10) {\n            Eigen::IOFormat fmt(3, 0, \", \", \";\\n\", \"\", \"\", \"[\", \"]\");\n            std::cout << M.format(fmt) << std::endl;\n        }\n        Eigen::BDCSVD<Mat> svd(M);\n        std::cout << \"s: \" << svd.singularValues().transpose() << std::endl;\n        std::cout << \"det=\" << M.determinant() << std::endl;\n        std::cout << \"======================\\n\";\n    }\n#endif  // PRINT_MAT\n\n    // analysis and factorization\n    call_pardiso(12, nullptr, nullptr);\n}\n\nSparseSolver::SparseMatBuilder* SparseSolver::Impl::make_builder(\n        size_t cidx_offset = 0) {\n    auto& ptr = m_mat_builders.emplace_back();\n    ptr.reset(new MatBuilder{this, cidx_offset});\n    return ptr.get();\n}\n\nSparseSolver::Impl::~Impl() {\n    call_pardiso(-1, nullptr, nullptr);\n    if (m_a_csr) {\n        mkl_sparse_destroy(m_a_csr);\n        m_a_csr = nullptr;\n    }\n    if (m_aTapI) {\n        mkl_sparse_destroy(m_aTapI);\n        m_aTapI = nullptr;\n    }\n}\n\nvoid SparseSolver::set_verbosity(int verbosity) {\n    Impl::sm_verbosity = verbosity;\n}\n\nSparseSolver::SparseSolver(size_t nr_xs) {\n    m_pimpl.reset(new Impl{nr_xs});\n}\n\nSparseSolver::~SparseSolver() = default;\n\nSparseSolver::SparseMatBuilder* SparseSolver::make_builder(size_t cidx_offset) {\n    return m_pimpl->make_builder(cidx_offset);\n}\n\nSparseSolver& SparseSolver::prepare(fp_t l2_penalty) {\n    m_pimpl->prepare(l2_penalty);\n    return *this;\n}\n\nTensorND SparseSolver::solve(const TensorND& b) const {\n    return m_pimpl->solve(b);\n}\n\nvoid SparseSolver::dump(const TensorND& b, FILE* fout) const {\n    m_pimpl->dump(b, fout);\n}\n\nTensorND SparseSolver::apply(const TensorND& x) const {\n    return m_pimpl->apply(x);\n}\n\nfp_t SparseSolver::coeff_l2() const {\n    return m_pimpl->coeff_l2();\n}\n\nstatic int g_solver_num_threads = 0;\nvoid SparseSolver::set_num_threads(int nr) {\n    sanm_assert(nr >= 0);\n    g_solver_num_threads = nr;\n}\n\nint SparseSolver::get_num_threads() {\n    if (g_solver_num_threads) {\n        return g_solver_num_threads;\n    }\n    return sanm::get_num_threads();\n}\n", "meta": {"hexsha": "4df8f864626b2e962023064840aaa5646f83fa84", "size": 15414, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libsanm/sparse_solver.cpp", "max_stars_repo_name": "jia-kai/SANM", "max_stars_repo_head_hexsha": "2673ac476b3d2978a52bf47bc12d3402ea20f211", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 25.0, "max_stars_repo_stars_event_min_datetime": "2021-05-19T09:27:52.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-22T15:22:05.000Z", "max_issues_repo_path": "libsanm/sparse_solver.cpp", "max_issues_repo_name": "jia-kai/SANM", "max_issues_repo_head_hexsha": "2673ac476b3d2978a52bf47bc12d3402ea20f211", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-09-03T05:31:47.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-05T01:37:42.000Z", "max_forks_repo_path": "libsanm/sparse_solver.cpp", "max_forks_repo_name": "jia-kai/SANM", "max_forks_repo_head_hexsha": "2673ac476b3d2978a52bf47bc12d3402ea20f211", "max_forks_repo_licenses": ["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.5214723926, "max_line_length": 80, "alphanum_fraction": 0.5562475671, "num_tokens": 4194, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6619228758499943, "lm_q2_score": 0.5039061705290805, "lm_q1q2_score": 0.33354702155516663}}
{"text": "/*\n\tThis file is part of the implementation for the technical paper\n\n\t\tField-Aligned Online Surface Reconstruction\n\t\tNico Schertler, Marco Tarini, Wenzel Jakob, Misha Kazhdan, Stefan Gumhold, Daniele Panozzo\n\t\tACM TOG 36, 4, July 2017 (Proceedings of SIGGRAPH 2017)\n\n\tUse of this source code is granted via a BSD-style license, which can be found\n\tin License.txt in the repository root.\n\n\t@author Wenzel Jakob\n\t@author Nico Schertler\n*/\n\n#include \"osr/field.h\"\n#include \"osr/common.h\"\n\n#include <Eigen/Geometry>\n\nnamespace osr\n{\n\n\tstatic const Float sqrt_3_over_4 = 0.866025403784439f;\n\n\tVector3f rotate180(const Vector3f &q, const Vector3f &/* unused */) {\n\t\treturn -q;\n\t}\n\n\tVector3f rotate180_by(const Vector3f &q, const Vector3f &/* unused */, int amount) {\n\t\treturn (amount & 1) ? Vector3f(-q) : q;\n\t}\n\n\tVector2i rshift180(Vector2i shift, int amount) {\n\t\tif (amount & 1)\n\t\t\tshift = -shift;\n\t\treturn shift;\n\t}\n\n\tVector3f rotate90(const Vector3f &q, const Vector3f &n) {\n\t\treturn n.cross(q);\n\t}\n\n\tVector3f rotate90_by(const Vector3f &q, const Vector3f &n, int amount) {\n\t\treturn ((amount & 1) ? (n.cross(q)) : q) * (amount < 2 ? 1.0f : -1.0f);\n\t}\n\n\tVector2i rshift90(Vector2i shift, int amount) {\n\t\tif (amount & 1)\n\t\t\tshift = Vector2i(-shift.y(), shift.x());\n\t\tif (amount >= 2)\n\t\t\tshift = -shift;\n\t\treturn shift;\n\t}\n\n\tVector3f rotate60(const Vector3f &d, const Vector3f &n) {\n\t\treturn sqrt_3_over_4 * n.cross(d) + 0.5f*(d + n * n.dot(d));\n\t}\n\n\tVector2i rshift60(Vector2i shift, int amount) {\n\t\tfor (int i = 0; i < amount; ++i)\n\t\t\tshift = Vector2i(-shift.y(), shift.x() + shift.y());\n\t\treturn shift;\n\t}\n\n\tVector3f rotate60_by(const Vector3f &d, const Vector3f &n, int amount) {\n\t\tswitch (amount) {\n\t\tcase 0: return d;\n\t\tcase 1: return rotate60(d, n);\n\t\tcase 2: return -rotate60(d, -n);\n\t\tcase 3: return -d;\n\t\tcase 4: return -rotate60(d, n);\n\t\tcase 5: return rotate60(d, -n);\n\t\t}\n\t\tthrow std::runtime_error(\"rotate60: invalid argument\");\n\t}\n\n\tVector3f rotate_vector_into_plane(Vector3f q, const Vector3f &source_normal, const Vector3f &target_normal) {\n\t\tconst Float cosTheta = source_normal.dot(target_normal);\n\t\tif (cosTheta < 0.9999f) {\n\t\t\tVector3f axis = source_normal.cross(target_normal);\n\t\t\tq = q * cosTheta + axis.cross(q) +\n\t\t\t\taxis * (axis.dot(q) * (1.0f - cosTheta) / axis.dot(axis));\n\t\t}\n\t\treturn q;\n\t}\n\n\tinline Vector3f middle_point(const Vector3f &p0, const Vector3f &n0, const Vector3f &p1, const Vector3f &n1) {\n\t\t/* How was this derived?\n\t\t *\n\t\t * Minimize \\|x-p0\\|^2 + \\|x-p1\\|^2, where\n\t\t * dot(n0, x) == dot(n0, p0)\n\t\t * dot(n1, x) == dot(n1, p1)\n\t\t *\n\t\t * -> Lagrange multipliers, set derivative = 0\n\t\t *  Use first 3 equalities to write x in terms of\n\t\t *  lambda_1 and lambda_2. Substitute that into the last\n\t\t *  two equations and solve for the lambdas. Finally,\n\t\t *  add a small epsilon term to avoid issues when n1=n2.\n\t\t */\n\t\tFloat n0p0 = n0.dot(p0), n0p1 = n0.dot(p1),\n\t\t\tn1p0 = n1.dot(p0), n1p1 = n1.dot(p1),\n\t\t\tn0n1 = n0.dot(n1),\n\t\t\tdenom = 1.0f / (1.0f - n0n1*n0n1 + 1e-4f),\n\t\t\tlambda_0 = 2.0f*(n0p1 - n0p0 - n0n1*(n1p0 - n1p1))*denom,\n\t\t\tlambda_1 = 2.0f*(n1p0 - n1p1 - n0n1*(n0p1 - n0p0))*denom;\n\n\t\treturn 0.5f * (p0 + p1) - 0.25f * (n0 * lambda_0 + n1 * lambda_1);\n\t}\n\n\tIOrientationFieldTraits::IOrientationFieldTraits(int rosy)\n\t\t: _rosy(rosy)\n\t{ }\n\n\n\ttemplate<int RoSy>\n\tOrientationFieldTraits<RoSy>::OrientationFieldTraits()\n\t\t: IOrientationFieldTraits(RoSy)\n\t{ }\n\n\ttemplate <>\n\tvoid OrientationFieldTraits<2>::findCompatible(const Vector3f &q0, const Vector3f &n0, const Vector3f &q1, const Vector3f &n1, Vector3f& compat1, Vector3f& compat2)\n\t{\n\t\tcompat1 = q0;\n\t\tcompat2 = q1 * signum(q0.dot(q1));\n\t}\n\n\ttemplate <>\n\tvoid OrientationFieldTraits<2>::findCompatible(const Vector3f &dirField0, const Vector3f &normal0, const Matrix3Xf& principalDirections, Matrix3Xf& compatOut, VectorXf& scoreOut)\n\t{\n\t\tfloat dot = dirField0.dot(principalDirections.col(0));\n\t\tcompatOut.col(0) = dirField0 * signum(dot);\n\t\tscoreOut(0) = std::abs(dot);\n\t}\n\n\ttemplate <>\n\tvoid OrientationFieldTraits<2>::getPrincipalDirections(const Vector3f& dirField, const Vector3f& normal, Matrix3Xf& outDirections)\n\t{\n\t\toutDirections.col(0) = dirField;\n\t}\n\n\ttemplate <>\n\tvoid OrientationFieldTraits<4>::getPrincipalDirections(const Vector3f& dirField, const Vector3f& normal, Matrix3Xf& outDirections)\n\t{\n\t\toutDirections.col(0) = dirField;\n\t\toutDirections.col(1) = normal.cross(dirField);\n\t}\n\n\ttemplate <>\n\tvoid OrientationFieldTraits<4>::findCompatible(const Vector3f &q0, const Vector3f &n0, const Vector3f &q1, const Vector3f &n1, Vector3f& compat1, Vector3f& compat2)\n\t{\n\t\tMatrix3Xf A(3, 2), B(3, 2);\n\t\tgetPrincipalDirections(q0, n0, A);\n\t\tgetPrincipalDirections(q1, n1, B);\n\n\t\tFloat best_score = -std::numeric_limits<Float>::infinity();\n\t\tint best_a = 0, best_b = 0;\n\n\t\tfor (int i = 0; i < 2; ++i) {\n\t\t\tfor (int j = 0; j < 2; ++j) {\n\t\t\t\tFloat score = std::abs(A.col(i).dot(B.col(j)));\n\t\t\t\tif (score > best_score) {\n\t\t\t\t\tbest_a = i;\n\t\t\t\t\tbest_b = j;\n\t\t\t\t\tbest_score = score;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tconst Float dp = A.col(best_a).dot(B.col(best_b));\n\t\tcompat1 = A.col(best_a);\n\t\tcompat2 = B.col(best_b) * signum(dp);\n\t}\n\n\ttemplate <>\n\tvoid OrientationFieldTraits<4>::findCompatible(const Vector3f &dirField0, const Vector3f &normal0, const Matrix3Xf& principalDirections, Matrix3Xf& compatOut, VectorXf& scoreOut)\n\t{\n\t\tMatrix3Xf B(3, 2);\n\t\tgetPrincipalDirections(dirField0, normal0, B);\n\n\t\tfor (int i = 0; i < 2; ++i)\n\t\t{\n\t\t\tFloat best_score = -std::numeric_limits<Float>::infinity();\n\t\t\tint best = 0;\n\n\t\t\tfor (int j = 0; j < 2; ++j)\n\t\t\t{\n\t\t\t\tFloat score = std::abs(principalDirections.col(i).dot(B.col(j)));\n\t\t\t\tif (score > best_score)\n\t\t\t\t{\n\t\t\t\t\tbest = j;\n\t\t\t\t\tbest_score = score;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconst Float dp = principalDirections.col(i).dot(B.col(best));\n\t\t\tcompatOut.col(i) = B.col(best) * signum(dp);\n\t\t\tscoreOut(i) = best_score;\n\t\t}\n\t}\n\n\ttemplate <>\n\tvoid OrientationFieldTraits<6>::getPrincipalDirections(const Vector3f& dirField, const Vector3f& normal, Matrix3Xf& outDirections)\n\t{\n\t\toutDirections.col(0) = rotate60(dirField, -normal);\n\t\toutDirections.col(1) = dirField;\n\t\toutDirections.col(2) = rotate60(dirField, normal);\n\t}\n\n\ttemplate <>\n\tvoid OrientationFieldTraits<6>::findCompatible(const Vector3f &q0, const Vector3f &n0, const Vector3f &q1, const Vector3f &n1, Vector3f& compat1, Vector3f& compat2)\n\t{\n\t\tMatrix3Xf A(3, 3), B(3, 3);\n\t\tgetPrincipalDirections(q0, n0, A);\n\t\tgetPrincipalDirections(q1, n1, B);\n\n\t\tFloat best_score = -std::numeric_limits<Float>::infinity();\n\t\tint best_a = 0, best_b = 0;\n\n\t\tfor (int i = 0; i < 3; ++i) {\n\t\t\tfor (int j = 0; j < 3; ++j) {\n\t\t\t\tFloat score = std::abs(A.col(i).dot(B.col(j)));\n\t\t\t\tif (score > best_score) {\n\t\t\t\t\tbest_a = i;\n\t\t\t\t\tbest_b = j;\n\t\t\t\t\tbest_score = score;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tconst Float dp = A.col(best_a).dot(B.col(best_b));\n\t\tcompat1 = A.col(best_a);\n\t\tcompat2 = B.col(best_b) * signum(dp);\n\t}\n\n\ttemplate <>\n\tvoid OrientationFieldTraits<6>::findCompatible(const Vector3f &dirField0, const Vector3f &normal0, const Matrix3Xf& principalDirections, Matrix3Xf& compatOut, VectorXf& scoreOut)\n\t{\n\t\tMatrix3Xf B(3, 3);\n\t\tgetPrincipalDirections(dirField0, normal0, B);\n\n\t\tfor (int i = 0; i < 3; ++i)\n\t\t{\n\t\t\tFloat best_score = -std::numeric_limits<Float>::infinity();\n\t\t\tint best = 0;\n\t\t\tfor (int j = 0; j < 3; ++j)\n\t\t\t{\n\t\t\t\tFloat score = std::abs(principalDirections.col(i).dot(B.col(j)));\n\t\t\t\tif (score > best_score)\n\t\t\t\t{\n\t\t\t\t\tbest = j;\n\t\t\t\t\tbest_score = score;\n\t\t\t\t}\n\t\t\t}\n\t\t\tconst Float dp = principalDirections.col(i).dot(B.col(best));\n\t\t\tcompatOut.col(i) = B.col(best) * signum(dp);\n\t\t\tscoreOut(i) = best_score;\n\t\t}\n\t}\n\n\tIOrientationFieldTraits * getOrientationFieldTraits(int roSy)\n\t{\n\t\tif (roSy == 2) {\n\t\t\treturn new OrientationFieldTraits<2>();\n\t\t}\n\t\telse if (roSy == 4) {\n\t\t\treturn new OrientationFieldTraits<4>();\n\t\t}\n\t\telse if (roSy == 6) {\n\t\t\treturn new OrientationFieldTraits<6>();\n\t\t}\n\t\telse {\n\t\t\tthrow std::runtime_error(\"Invalid rotation symmetry type \" + std::to_string(roSy) + \"!\");\n\t\t}\n\t}\n\n\t// ---- Position Field ----\n\n\tIPositionFieldTraits::IPositionFieldTraits(int posy)\n\t\t:_posy(posy)\n\t{\n\t}\n\n\ttemplate<int PoSy>\n\tPositionFieldTraits<PoSy>::PositionFieldTraits()\n\t\t: IPositionFieldTraits(PoSy)\n\t{\n\t}\n\n\tIPositionFieldTraits * getPositionFieldTraits(int poSy)\n\t{\n\t\tif (poSy == 4) {\n\t\t\treturn new PositionFieldTraits<4>();\n\t\t}\n\t\telse if (poSy == 6) {\n\t\t\treturn new PositionFieldTraits<6>();\n\t\t}\n\t\telse {\n\t\t\tthrow std::runtime_error(\"Invalid position symmetry type \" + std::to_string(poSy) + \"!\");\n\t\t}\n\t}\n\n\n\tinline Vector2i position_round_index_3(const Vector3f &o, const Vector3f &q,\n\t\tconst Vector3f &n, const Vector3f &p,\n\t\tFloat scale, Float inv_scale)\n\t{\n\t\tVector3f t = rotate60(q, n);\n\t\tVector3f d = p - o;\n\t\tFloat dpq = q.dot(d), dpt = t.dot(d);\n\t\tint u = (int)std::floor((4 * dpq - 2 * dpt) * (1.0f / 3.0f) * inv_scale);\n\t\tint v = (int)std::floor((-2 * dpq + 4 * dpt) * (1.0f / 3.0f) * inv_scale);\n\n\t\tFloat best_cost = std::numeric_limits<Float>::infinity();\n\t\tint best_i = -1;\n\n\t\tfor (int i = 0; i < 4; ++i) {\n\t\t\tVector3f ot = o + (q*(u + (i & 1)) + t * (v + ((i & 2) >> 1))) * scale;\n\t\t\tFloat cost = (ot - p).squaredNorm();\n\t\t\tif (cost < best_cost) {\n\t\t\t\tbest_i = i;\n\t\t\t\tbest_cost = cost;\n\t\t\t}\n\t\t}\n\n\t\treturn Vector2i(\n\t\t\tu + (best_i & 1), v + ((best_i & 2) >> 1)\n\t\t);\n\t}\n\n\tinline Vector2i position_round_index_4(const Vector3f &o, const Vector3f &q,\n\t\tconst Vector3f &n, const Vector3f &p,\n\t\tFloat /* unused */, Float inv_scale)\n\t{\n\t\tVector3f t = n.cross(q);\n\t\tVector3f d = p - o;\n\t\treturn Vector2i(\n\t\t\t(int)std::round(q.dot(d) * inv_scale),\n\t\t\t(int)std::round(t.dot(d) * inv_scale));\n\t}\n\n\tinline Vector3f position_floor_3(const Vector3f &o, const Vector3f &q,\n\t\tconst Vector3f &n, const Vector3f &p,\n\t\tFloat scale, Float inv_scale) {\n\t\tVector3f t = rotate60(q, n);\n\t\tVector3f d = p - o;\n\t\tFloat dpq = q.dot(d), dpt = t.dot(d);\n\t\tFloat u = std::floor((4 * dpq - 2 * dpt) * (1.0f / 3.0f) * inv_scale);\n\t\tFloat v = std::floor((-2 * dpq + 4 * dpt) * (1.0f / 3.0f) * inv_scale);\n\n\t\treturn o + (q*u + t*v) * scale;\n\t}\n\n\tinline Vector3f position_floor_4(const Vector3f &o, const Vector3f &q,\n\t\tconst Vector3f &n, const Vector3f &p,\n\t\tFloat scale, Float inv_scale) {\n\t\tVector3f t = n.cross(q);\n\t\tVector3f d = p - o;\n\t\treturn o +\n\t\t\tq * std::floor(q.dot(d) * inv_scale) * scale +\n\t\t\tt * std::floor(t.dot(d) * inv_scale) * scale;\n\t}\n\n\tinline Vector2i position_floor_index_3(const Vector3f &o, const Vector3f &q,\n\t\tconst Vector3f &n, const Vector3f &p,\n\t\tFloat /* scale */, Float inv_scale) {\n\t\tVector3f t = rotate60(q, n);\n\t\tVector3f d = p - o;\n\t\tFloat dpq = q.dot(d), dpt = t.dot(d);\n\t\tint u = (int)std::floor((4 * dpq - 2 * dpt) * (1.0f / 3.0f) * inv_scale);\n\t\tint v = (int)std::floor((-2 * dpq + 4 * dpt) * (1.0f / 3.0f) * inv_scale);\n\n\t\treturn Vector2i(u, v);\n\t}\n\n\tinline Vector2i position_floor_index_4(const Vector3f &o, const Vector3f &q,\n\t\tconst Vector3f &n, const Vector3f &p,\n\t\tFloat /* unused */, Float inv_scale) {\n\t\tVector3f t = n.cross(q);\n\t\tVector3f d = p - o;\n\t\treturn Vector2i(\n\t\t\t(int)std::floor(q.dot(d) * inv_scale),\n\t\t\t(int)std::floor(t.dot(d) * inv_scale));\n\t}\n\n\ttemplate<>\n\tVector3f PositionFieldTraits<4>::positionRound(const Vector3f &o, const Vector3f &q,\n\t\tconst Vector3f &n, const Vector3f &p,\n\t\tFloat scale, Float inv_scale)\n\t{\n\t\tVector3f t = n.cross(q);\n\t\tVector3f d = p - o;\n\t\treturn o +\n\t\t\tq * std::round(q.dot(d) * inv_scale) * scale +\n\t\t\tt * std::round(t.dot(d) * inv_scale) * scale;\n\t}\n\n\ttemplate<>\n\tVector3f PositionFieldTraits<6>::positionRound(const Vector3f &o, const Vector3f &q,\n\t\tconst Vector3f &n, const Vector3f &p,\n\t\tFloat scale, Float inv_scale)\n\t{\n\t\tVector3f t = rotate60(q, n);\n\t\tVector3f d = p - o;\n\n\t\tFloat dpq = q.dot(d), dpt = t.dot(d);\n\t\tFloat u = std::floor((4 * dpq - 2 * dpt) * (1.0f / 3.0f) * inv_scale);\n\t\tFloat v = std::floor((-2 * dpq + 4 * dpt) * (1.0f / 3.0f) * inv_scale);\n\n\t\tFloat best_cost = std::numeric_limits<Float>::infinity();\n\t\tint best_i = -1;\n\n\t\tfor (int i = 0; i < 4; ++i) {\n\t\t\tVector3f ot = o + (q*(u + (i & 1)) + t*(v + ((i & 2) >> 1))) * scale;\n\t\t\tFloat cost = (ot - p).squaredNorm();\n\t\t\tif (cost < best_cost) {\n\t\t\t\tbest_i = i;\n\t\t\t\tbest_cost = cost;\n\t\t\t}\n\t\t}\n\n\t\treturn o + (q*(u + (best_i & 1)) + t*(v + ((best_i & 2) >> 1))) * scale;\n\t}\n\n\ttemplate <>\n\tvoid PositionFieldTraits<4>::findCompatible(\n\t\tconst Vector3f &p0, const Vector3f &n0, const Vector3f &q0, const Vector3f &o0,\n\t\tconst Vector3f &p1, const Vector3f &n1, const Vector3f &q1, const Vector3f &o1,\n\t\tFloat scale, Float inv_scale, Vector3f& compat1, Vector3f& compat2)\n\t{\n\n\t\tVector3f t0 = n0.cross(q0), t1 = n1.cross(q1);\n\t\tVector3f middle = middle_point(p0, n0, p1, n1);\n\t\tVector3f o0p = position_floor_4(o0, q0, n0, middle, scale, inv_scale);\n\t\tVector3f o1p = position_floor_4(o1, q1, n1, middle, scale, inv_scale);\n\n\t\tFloat best_cost = std::numeric_limits<Float>::infinity();\n\t\tint best_i = -1, best_j = -1;\n\n\t\tfor (int i = 0; i < 4; ++i)\n\t\t{\n\t\t\tVector3f o0t = o0p + (q0 * (i & 1) + t0 * ((i & 2) >> 1)) * scale;\n\t\t\tfor (int j = 0; j < 4; ++j)\n\t\t\t{\n\t\t\t\tVector3f o1t = o1p + (q1 * (j & 1) + t1 * ((j & 2) >> 1)) * scale;\n\t\t\t\tFloat cost = (o0t - o1t).squaredNorm();\n\n\t\t\t\tif (cost < best_cost)\n\t\t\t\t{\n\t\t\t\t\tbest_i = i;\n\t\t\t\t\tbest_j = j;\n\t\t\t\t\tbest_cost = cost;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tcompat1 = o0p + (q0 * (best_i & 1) + t0 * ((best_i & 2) >> 1)) * scale;\n\t\tcompat2 = o1p + (q1 * (best_j & 1) + t1 * ((best_j & 2) >> 1)) * scale;\n\t}\n\n\ttemplate <>\n\tstd::pair<Vector2i, Vector2i> PositionFieldTraits<4>::findCompatibleIndex(\n\t\tconst Vector3f &p0, const Vector3f &n0, const Vector3f &q0, const Vector3f &o0,\n\t\tconst Vector3f &p1, const Vector3f &n1, const Vector3f &q1, const Vector3f &o1,\n\t\tFloat scale, Float inv_scale, Float* error) {\n\t\tVector3f t0 = n0.cross(q0), t1 = n1.cross(q1);\n\t\tVector3f middle = middle_point(p0, n0, p1, n1);\n\t\tVector2i o0p = position_floor_index_4(o0, q0, n0, middle, scale, inv_scale);\n\t\tVector2i o1p = position_floor_index_4(o1, q1, n1, middle, scale, inv_scale);\n\n\t\tFloat best_cost = std::numeric_limits<Float>::infinity();\n\t\tint best_i = -1, best_j = -1;\n\n\t\tfor (int i = 0; i < 4; ++i) {\n\t\t\tVector3f o0t = o0 + (q0 * ((i & 1) + o0p[0]) + t0 * (((i & 2) >> 1) + o0p[1])) * scale;\n\t\t\tfor (int j = 0; j < 4; ++j) {\n\t\t\t\tVector3f o1t = o1 + (q1 * ((j & 1) + o1p[0]) + t1 * (((j & 2) >> 1) + o1p[1])) * scale;\n\t\t\t\tFloat cost = (o0t - o1t).squaredNorm();\n\n\t\t\t\tif (cost < best_cost) {\n\t\t\t\t\tbest_i = i;\n\t\t\t\t\tbest_j = j;\n\t\t\t\t\tbest_cost = cost;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif (error)\n\t\t\t*error = best_cost;\n\n\t\treturn std::make_pair(\n\t\t\tVector2i((best_i & 1) + o0p[0], ((best_i & 2) >> 1) + o0p[1]),\n\t\t\tVector2i((best_j & 1) + o1p[0], ((best_j & 2) >> 1) + o1p[1]));\n\t}\n\n\ttemplate <>\n\tvoid PositionFieldTraits<6>::findCompatible(\n\t\tconst Vector3f &p0, const Vector3f &n0, const Vector3f &q0, const Vector3f &_o0,\n\t\tconst Vector3f &p1, const Vector3f &n1, const Vector3f &q1, const Vector3f &_o1,\n\t\tFloat scale, Float inv_scale, Vector3f& compat1, Vector3f& compat2) {\n\t\tVector3f middle = middle_point(p0, n0, p1, n1);\n\t\tVector3f o0 = position_floor_3(_o0, q0, n0, middle, scale, inv_scale);\n\t\tVector3f o1 = position_floor_3(_o1, q1, n1, middle, scale, inv_scale);\n\n\t\tVector3f t0 = rotate60(q0, n0), t1 = rotate60(q1, n1);\n\t\tFloat best_cost = std::numeric_limits<Float>::infinity();\n\t\tint best_i = -1, best_j = -1;\n\t\tfor (int i = 0; i < 4; ++i) {\n\t\t\tVector3f o0t = o0 + (q0*(i & 1) + t0*((i & 2) >> 1)) * scale;\n\t\t\tfor (int j = 0; j < 4; ++j) {\n\t\t\t\tVector3f o1t = o1 + (q1*(j & 1) + t1*((j & 2) >> 1)) * scale;\n\t\t\t\tFloat cost = (o0t - o1t).squaredNorm();\n\n\t\t\t\tif (cost < best_cost) {\n\t\t\t\t\tbest_i = i;\n\t\t\t\t\tbest_j = j;\n\t\t\t\t\tbest_cost = cost;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tcompat1 = o0 + (q0*(best_i & 1) + t0*((best_i & 2) >> 1)) * scale;\n\t\tcompat2 = o1 + (q1*(best_j & 1) + t1*((best_j & 2) >> 1)) * scale;\n\t}\n\n\ttemplate <>\n\tstd::pair<Vector2i, Vector2i> PositionFieldTraits<6>::findCompatibleIndex(\n\t\tconst Vector3f &p0, const Vector3f &n0, const Vector3f &q0, const Vector3f &o0,\n\t\tconst Vector3f &p1, const Vector3f &n1, const Vector3f &q1, const Vector3f &o1,\n\t\tFloat scale, Float inv_scale, Float* error) {\n\t\tVector3f t0 = rotate60(q0, n0), t1 = rotate60(q1, n1);\n\t\tVector3f middle = middle_point(p0, n0, p1, n1);\n\t\tVector2i o0i = position_floor_index_3(o0, q0, n0, middle, scale, inv_scale);\n\t\tVector2i o1i = position_floor_index_3(o1, q1, n1, middle, scale, inv_scale);\n\n\t\tFloat best_cost = std::numeric_limits<Float>::infinity();\n\t\tint best_i = -1, best_j = -1;\n\t\tfor (int i = 0; i < 4; ++i) {\n\t\t\tVector3f o0t = o0 + (q0*(o0i.x() + (i & 1)) + t0*(o0i.y() + ((i & 2) >> 1))) * scale;\n\t\t\tfor (int j = 0; j < 4; ++j) {\n\t\t\t\tVector3f o1t = o1 + (q1*(o1i.x() + (j & 1)) + t1*(o1i.y() + ((j & 2) >> 1))) * scale;\n\t\t\t\tFloat cost = (o0t - o1t).squaredNorm();\n\n\t\t\t\tif (cost < best_cost) {\n\t\t\t\t\tbest_i = i;\n\t\t\t\t\tbest_j = j;\n\t\t\t\t\tbest_cost = cost;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif (error)\n\t\t\t*error = best_cost;\n\n\t\treturn std::make_pair(\n\t\t\tVector2i(o0i.x() + (best_i & 1), o0i.y() + ((best_i & 2) >> 1)),\n\t\t\tVector2i(o1i.x() + (best_j & 1), o1i.y() + ((best_j & 2) >> 1)));\n\t}\n}", "meta": {"hexsha": "285618c79367ac7b8ec9001d6d5017abe14d1cd1", "size": 16974, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libOSR/src/field.cpp", "max_stars_repo_name": "snowymo/OnlineSurfaceReconstruction", "max_stars_repo_head_hexsha": "2f44e292c69a16a9d8fe1f292a92396a652a8b06", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 142.0, "max_stars_repo_stars_event_min_datetime": "2017-05-16T01:52:25.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-06T07:10:26.000Z", "max_issues_repo_path": "libOSR/src/field.cpp", "max_issues_repo_name": "snowymo/OnlineSurfaceReconstruction", "max_issues_repo_head_hexsha": "2f44e292c69a16a9d8fe1f292a92396a652a8b06", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 9.0, "max_issues_repo_issues_event_min_datetime": "2017-06-27T02:51:39.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-10T19:02:16.000Z", "max_forks_repo_path": "libOSR/src/field.cpp", "max_forks_repo_name": "snowymo/OnlineSurfaceReconstruction", "max_forks_repo_head_hexsha": "2f44e292c69a16a9d8fe1f292a92396a652a8b06", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 38.0, "max_forks_repo_forks_event_min_datetime": "2017-05-18T09:58:50.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-19T06:02:36.000Z", "avg_line_length": 30.4193548387, "max_line_length": 179, "alphanum_fraction": 0.6254860375, "num_tokens": 6269, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.661922862511608, "lm_q2_score": 0.5039061705290805, "lm_q1q2_score": 0.33354701483387145}}
{"text": "/**\n *  @copyright Copyright 2016 The J-PET Framework Authors. All rights reserved.\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 find a copy of the License in the LICENCE file.\n *\n *  Unless required by applicable law or agreed to in writing, 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 JPetSimplePhysSignalReco.cpp\n */\n\n#include <math.h>\n#include <cassert>\n#include \"JPetSimplePhysSignalReco.h\"\n#include \"./JPetWriter/JPetWriter.h\"\n#include \"HelperMathFunctions.h\"\n#include <boost/property_tree/json_parser.hpp>\n\nusing namespace boost::numeric::ublas;\n\nJPetSimplePhysSignalReco::JPetSimplePhysSignalReco():\n  fAlpha(1),\n  fThresholdSel(-1)\n{\n  readConfigFileAndSetAlphaAndThreshParams(\"configParams.json\");\n}\n\nJPetSimplePhysSignalReco::~JPetSimplePhysSignalReco()\n{\n  /**/\n}\n\nbool JPetSimplePhysSignalReco::exec()\n{\n  return true;\n}\n\nvoid JPetSimplePhysSignalReco::savePhysSignal(JPetPhysSignal)\n{\n}\n\nJPetPhysSignal JPetSimplePhysSignalReco::createPhysSignal(JPetRecoSignal& recoSignal)\n{\n  // create a Phys Signal\n  JPetPhysSignal physSignal;\n\n  // use the values from Reco Signal to set the physical properties of signal\n  // here, a dummy example - much more sophisticated procedures should go here\n  physSignal.setPhe( recoSignal.getCharge() * 1.0 + 0.0 );\n  physSignal.setQualityOfPhe(1.0);\n\n  // in the previous module (C2) we have reconstructed one time at arbitrary\n  // threshold - now we retrieve it by getting a map of times vs. thresholds,\n  // and taking its first (and only) element by the begin() iterator. We get\n  // an std::pair, where first is the threshold value, and second is time.\n  double time = recoSignal.getRecoTimesAtThreshold().begin()->second;\n\n  // -----------------------------------------------------------\n  //\n  // Estimate the time of the signal based on raw signal samples\n  JPetRawSignal rawSignal = recoSignal.getRawSignal();\n\n  if (rawSignal.getNumberOfPoints(JPetSigCh::Leading) >= 2\n      && rawSignal.getNumberOfPoints(JPetSigCh::Trailing) >= 2) {\n    // get number of points on leading edge\n    int iNumPoints = rawSignal.getNumberOfPoints(JPetSigCh::Leading);\n\n    std::vector<JPetSigCh> leadingPoints = rawSignal.getPoints(\n        JPetSigCh::Leading, JPetRawSignal::ByThrValue);\n\n    // create vectors\n    vector<float> vecTime(iNumPoints);\n    vector<float> vecVolt(iNumPoints);\n\n    for (int j = 0; j < iNumPoints; j++) {\n      vecTime(j) = leadingPoints.at(j).getValue();\n      vecVolt(j) = leadingPoints.at(j).getThreshold();\n    }\n\n    // To evaluate time below parameters should be specified:\n\n    // the parameter alfa of the below expression need to be specified:\n    // vecVolt = a(t - vecTime)^(alfa);\n    // Here alfa is fixed for the linear case.\n    // Caution! alfa has to be an integer and positive value, negative values are ignored.\n    int alfa = getAlpha();\n\n    // thr_sel specifies the threshold level to read the time value,\n    // and with thr_sel the below equation may be solved:\n    // thr_sel = a(t - time)^(alfa);\n    // Caution! thr_sel has to negative, and for positive values the program will set thr_sel equal to 0.\n    float thr_sel = getThresholdSel();\n\n    // The evaluation of time based on alfa and thr_sel\n    assert(thr_sel < 0);\n    assert(alfa > 0);\n    time = static_cast<double>(polynomialFit(vecTime, vecVolt, alfa, thr_sel));\n  }\n  // ------------------------------------------------------------\n\n  physSignal.setTime(time);\n  physSignal.setQualityOfTime(1.0);\n\n  // store the original JPetRecoSignal in the PhysSignal as a processing history\n  physSignal.setRecoSignal(recoSignal);\n  return physSignal;\n}\n\nvoid JPetSimplePhysSignalReco::readConfigFileAndSetAlphaAndThreshParams(const char* filename)\n{\n  boost::property_tree::ptree content;\n  try {\n    read_json(filename, content);\n    int alpha = content.get<int>(\"alpha\");\n    float thresholdSel = content.get<float>(\"thresholdSel\");\n    setAlpha(alpha);\n    setThresholdSel(thresholdSel);\n  } catch (const std::runtime_error& error) {\n    std::string message = \"Error opening config file. Error = \" + std::string(error.what());\n    std::cerr << message << std::endl;\n  }\n}\n", "meta": {"hexsha": "a371552c271310ce59d7d69ceaadbb832e406cee", "size": 4457, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Tasks/JPetSimplePhysSignalReco/JPetSimplePhysSignalReco.cpp", "max_stars_repo_name": "Alvarness/j-pet-framework", "max_stars_repo_head_hexsha": "899ab32bf9a7f4daecaf8ed2dd7c8bc8922e73bd", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Tasks/JPetSimplePhysSignalReco/JPetSimplePhysSignalReco.cpp", "max_issues_repo_name": "Alvarness/j-pet-framework", "max_issues_repo_head_hexsha": "899ab32bf9a7f4daecaf8ed2dd7c8bc8922e73bd", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Tasks/JPetSimplePhysSignalReco/JPetSimplePhysSignalReco.cpp", "max_forks_repo_name": "Alvarness/j-pet-framework", "max_forks_repo_head_hexsha": "899ab32bf9a7f4daecaf8ed2dd7c8bc8922e73bd", "max_forks_repo_licenses": ["Apache-2.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.094488189, "max_line_length": 105, "alphanum_fraction": 0.7029391968, "num_tokens": 1117, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.672331699179286, "lm_q2_score": 0.4960938294709195, "lm_q1q2_score": 0.3335396073205423}}
{"text": "/**\n * @author Andre Anjos <andre.anjos@idiap.ch>\n * @date Sun 27 Oct 09:02:32 2013\n *\n * @brief Binomial distributions (with integers or floating point numbers)\n */\n\n#define BOB_CORE_RANDOM_MODULE\n#include <bob.core/random_api.h>\n#include <bob.blitz/cppapi.h>\n#include <bob.blitz/cleanup.h>\n#include <bob.extension/documentation.h>\n\n#include <boost/make_shared.hpp>\n#include <bob.core/random.h>\n\nstatic auto binomial_doc = bob::extension::ClassDoc(\n  BOB_EXT_MODULE_PREFIX \".binomial\",\n  \"Models a random binomial distribution\",\n  \"This distribution produces random numbers :math:`x` distributed with the probability density function\\n\\n\"\n  \".. math::\\n\\n   {{t}\\\\choose{k}}p^k(1-p)^{t-k}\\n\\n\"\n  \"where ``t`` and ``p`` are parameters of the distribution.\\n\\n\"\n  \".. warning::\\n\\n\"\n  \"   This distribution requires that :math:`t >= 0` and that :math:`0 <= p <= 1`.\"\n)\n.add_constructor(bob::extension::FunctionDoc(\n  \"binomial\",\n  \"Creates a new binomial distribution object\"\n)\n.add_prototype(\"dtype, [t], [p]\", \"\")\n.add_parameter(\"dtype\", \":py:class:`numpy.dtype`\", \"The data type for the drawn random numbers; only integral types are supported\")\n.add_parameter(\"t\", \"float\", \"[Default: ``1.``] The :math:`t` parameter of the binomial distribution\")\n.add_parameter(\"p\", \"float\", \"[Default: ``0.5``] The :math:`p` parameter of the binomial distribution\")\n);\n\n/* How to create a new PyBoostBinomialObject */\nstatic PyObject* PyBoostBinomial_New(PyTypeObject* type, PyObject*, PyObject*) {\n\n  /* Allocates the python object itself */\n  PyBoostBinomialObject* self = (PyBoostBinomialObject*)type->tp_alloc(type, 0);\n  self->type_num = NPY_NOTYPE;\n  self->distro.reset();\n\n  return Py_BuildValue(\"N\", self);\n}\n\n/* How to delete a PyBoostBinomialObject */\nstatic void PyBoostBinomial_Delete (PyBoostBinomialObject* o) {\n  o->distro.reset();\n  Py_TYPE(o)->tp_free((PyObject*)o);\n}\n\ntemplate <typename T>\nboost::shared_ptr<void> make_binomial(PyObject* t, PyObject* p) {\n  T ct = 1.;\n  if (t) ct = PyBlitzArrayCxx_AsCScalar<T>(t);\n  if (ct < 0) {\n    PyErr_SetString(PyExc_ValueError, \"parameter t must be >= 0\");\n    return boost::shared_ptr<void>();\n  }\n  T cp = 0.5;\n  if (p) cp = PyBlitzArrayCxx_AsCScalar<T>(p);\n  if (cp < 0.0 || cp > 1.0) {\n    PyErr_SetString(PyExc_ValueError, \"parameter p must lie in the interval [0.0, 1.0]\");\n    return boost::shared_ptr<void>();\n  }\n  return boost::make_shared<bob::core::random::binomial_distribution<int64_t,T>>(ct, cp);\n}\n\nPyObject* PyBoostBinomial_SimpleNew (int type_num, PyObject* t, PyObject* p) {\nBOB_TRY\n  PyBoostBinomialObject* retval = (PyBoostBinomialObject*)PyBoostBinomial_New(&PyBoostBinomial_Type, 0, 0);\n  if (!retval) return 0;\n  auto retval_ = make_safe(retval);\n\n  retval->type_num = type_num;\n\n  switch(type_num) {\n    case NPY_FLOAT32:\n      retval->distro = make_binomial<float>(t, p);\n      break;\n    case NPY_FLOAT64:\n      retval->distro = make_binomial<double>(t, p);\n      break;\n    default:\n      PyErr_Format(PyExc_NotImplementedError, \"cannot create %s(T) with T having an unsupported numpy type number of %d (it only supports numpy.float32 or numpy.float64)\", Py_TYPE(retval)->tp_name, retval->type_num);\n      return 0;\n  }\n\n  if (!retval->distro) { // a problem occurred\n    return 0;\n  }\n\n  return Py_BuildValue(\"O\", retval);\nBOB_CATCH_FUNCTION(\"SimpleNew\", 0)\n}\n\n/* Implements the __init__(self) function */\nstatic int PyBoostBinomial_Init(PyBoostBinomialObject* self, PyObject *args, PyObject* kwds) {\nBOB_TRY\n  char** kwlist = binomial_doc.kwlist();\n\n  PyObject* t = 0;\n  PyObject* p = 0;\n\n  if (!PyArg_ParseTupleAndKeywords(args, kwds, \"O&|OO\", kwlist, &PyBlitzArray_TypenumConverter, &self->type_num, &t, &p)) return -1; ///< FAILURE\n\n  switch(self->type_num) {\n    case NPY_FLOAT32:\n      self->distro = make_binomial<float>(t, p);\n      break;\n    case NPY_FLOAT64:\n      self->distro = make_binomial<double>(t, p);\n      break;\n    default:\n      PyErr_Format(PyExc_NotImplementedError, \"cannot create %s(T) with T having an unsupported numpy type number of %d (it only supports numpy.float32 or numpy.float64)\", Py_TYPE(self)->tp_name, self->type_num);\n      return -1;\n  }\n\n  if (!self->distro) { // a problem occurred\n    return -1;\n  }\n\n  return 0; ///< SUCCESS\nBOB_CATCH_MEMBER(\"constructor\", -1)\n}\n\nint PyBoostBinomial_Check(PyObject* o) {\n  if (!o) return 0;\n  return PyObject_IsInstance(o, reinterpret_cast<PyObject*>(&PyBoostBinomial_Type));\n}\n\nint PyBoostBinomial_Converter(PyObject* o, PyBoostBinomialObject** a) {\n  if (!PyBoostBinomial_Check(o)) return 0;\n  Py_INCREF(o);\n  (*a) = reinterpret_cast<PyBoostBinomialObject*>(o);\n  return 1;\n}\n\n\nstatic auto t_doc = bob::extension::VariableDoc(\n  \"t\",\n  \"float\",\n  \"The parameter ``t`` of the distribution\"\n);\ntemplate <typename T> PyObject* get_t(PyBoostBinomialObject* self) {\n  return PyBlitzArrayCxx_FromCScalar(boost::static_pointer_cast<bob::core::random::binomial_distribution<int64_t,T>>(self->distro)->t());\n}\n\nstatic PyObject* PyBoostBinomial_GetT(PyBoostBinomialObject* self) {\nBOB_TRY\n  switch (self->type_num) {\n    case NPY_FLOAT32:\n      return get_t<float>(self);\n    case NPY_FLOAT64:\n      return get_t<double>(self);\n    default:\n      PyErr_Format(PyExc_NotImplementedError, \"cannot get parameter `t` of %s(T) with T having an unsupported numpy type number of %d (DEBUG ME)\", Py_TYPE(self)->tp_name, self->type_num);\n      return 0;\n  }\nBOB_CATCH_MEMBER(\"t\", 0)\n}\n\n\nstatic auto p_doc = bob::extension::VariableDoc(\n  \"p\",\n  \"float\",\n  \"The parameter ``p`` of the distribution\"\n);\ntemplate <typename T> PyObject* get_p(PyBoostBinomialObject* self) {\n  return PyBlitzArrayCxx_FromCScalar(boost::static_pointer_cast<bob::core::random::binomial_distribution<int64_t,T>>(self->distro)->p());\n}\n\nstatic PyObject* PyBoostBinomial_GetP(PyBoostBinomialObject* self) {\nBOB_TRY\n  switch (self->type_num) {\n    case NPY_FLOAT32:\n      return get_p<float>(self);\n    case NPY_FLOAT64:\n      return get_p<double>(self);\n    default:\n      PyErr_Format(PyExc_NotImplementedError, \"cannot get parameter `p` of %s(T) with T having an unsupported numpy type number of %d (DEBUG ME)\", Py_TYPE(self)->tp_name, self->type_num);\n      return 0;\n  }\nBOB_CATCH_MEMBER(\"p\", 0)\n}\n\n\nstatic auto dtype_doc = bob::extension::VariableDoc(\n  \"dtype\",\n  \":py:class:`numpy.dtype`\",\n  \"The type of scalars produced by this binomial distribution\"\n);\nstatic PyObject* PyBoostBinomial_GetDtype(PyBoostBinomialObject* self) {\nBOB_TRY\n  return reinterpret_cast<PyObject*>(PyArray_DescrFromType(self->type_num));\nBOB_CATCH_MEMBER(\"dtype\", 0)\n}\n\n\nstatic PyGetSetDef PyBoostBinomial_getseters[] = {\n    {\n      dtype_doc.name(),\n      (getter)PyBoostBinomial_GetDtype,\n      0,\n      dtype_doc.doc(),\n      0,\n    },\n    {\n      t_doc.name(),\n      (getter)PyBoostBinomial_GetT,\n      0,\n      t_doc.doc(),\n      0,\n    },\n    {\n      p_doc.name(),\n      (getter)PyBoostBinomial_GetP,\n      0,\n      p_doc.doc(),\n      0,\n    },\n    {0}  /* Sentinel */\n};\n\n\nstatic auto reset_doc = bob::extension::FunctionDoc(\n  \"reset\",\n  \"Resets this distribution\",\n  \"After calling this method, subsequent uses of the distribution do not depend on values produced by any random number generator prior to invoking reset\",\n  true\n)\n.add_prototype(\"\")\n;\ntemplate <typename T> PyObject* reset(PyBoostBinomialObject* self) {\n  boost::static_pointer_cast<bob::core::random::binomial_distribution<int64_t,T>>(self->distro)->reset();\n  Py_RETURN_NONE;\n}\n\nstatic PyObject* PyBoostBinomial_Reset(PyBoostBinomialObject* self) {\nBOB_TRY\n  switch (self->type_num) {\n    case NPY_FLOAT32:\n      return reset<float>(self);\n    case NPY_FLOAT64:\n      return reset<double>(self);\n    default:\n      PyErr_Format(PyExc_NotImplementedError, \"cannot reset %s(T) with T having an unsupported numpy type number of %d (DEBUG ME)\", Py_TYPE(self)->tp_name, self->type_num);\n      return 0;\n  }\nBOB_CATCH_MEMBER(\"reset\", 0)\n}\n\n\nstatic auto call_doc = bob::extension::FunctionDoc(\n  \"draw\",\n  \"Draws one random number from this distribution using the given ``rng``\",\n  \".. note:: The :py:meth:`__call__` function is a synonym for this ``draw``.\",\n  true\n)\n.add_prototype(\"rng\", \"value\")\n.add_parameter(\"rng\", \":py:class:`mt19937`\", \"The random number generator to use\")\n.add_return(\"value\", \"dtype\", \"A random value that follows the binomial distribution\")\n;\ntemplate <typename T> PyObject* call(PyBoostBinomialObject* self, PyBoostMt19937Object* rng) {\n  return PyBlitzArrayCxx_FromCScalar(boost::static_pointer_cast<bob::core::random::binomial_distribution<int64_t,T>>(self->distro)->operator()(*rng->rng));\n}\n\nstatic PyObject* PyBoostBinomial_Call(PyBoostBinomialObject* self, PyObject *args, PyObject* kwds) {\nBOB_TRY\n  char** kwlist = call_doc.kwlist();\n\n  PyBoostMt19937Object* rng;\n\n  if (!PyArg_ParseTupleAndKeywords(args, kwds, \"O!\", kwlist, &PyBoostMt19937_Type, &rng)) return 0; ///< FAILURE\n\n  switch(self->type_num) {\n    case NPY_FLOAT32:\n      return call<float>(self, rng);\n      break;\n    case NPY_FLOAT64:\n      return call<double>(self, rng);\n      break;\n    default:\n      PyErr_Format(PyExc_NotImplementedError, \"cannot call %s(T) with T having an unsupported numpy type number of %d (DEBUG ME)\", Py_TYPE(self)->tp_name, self->type_num);\n  }\n\n  return 0; ///< FAILURE\nBOB_CATCH_MEMBER(\"call\", 0)\n}\n\nstatic PyMethodDef PyBoostBinomial_methods[] = {\n    {\n      call_doc.name(),\n      (PyCFunction)PyBoostBinomial_Call,\n      METH_VARARGS|METH_KEYWORDS,\n      call_doc.doc(),\n    },\n    {\n      reset_doc.name(),\n      (PyCFunction)PyBoostBinomial_Reset,\n      METH_NOARGS,\n      reset_doc.doc(),\n    },\n    {0}  /* Sentinel */\n};\n\n\nextern PyObject* scalar_to_bytes(PyObject* s);\n\n/**\n * String representation and print out\n */\nstatic PyObject* PyBoostBinomial_Repr(PyBoostBinomialObject* self) {\nBOB_TRY\n  PyObject* st = scalar_to_bytes(PyBoostBinomial_GetT(self));\n  if (!st) return 0;\n  auto st_ = make_safe(st);\n  PyObject* sp = scalar_to_bytes(PyBoostBinomial_GetP(self));\n  if (!sp) return 0;\n  auto sp_ = make_safe(sp);\n\n  return\n    PyString_FromFormat\n      (\n       \"%s(dtype='%s', t=%s, p=%s)\",\n       Py_TYPE(self)->tp_name, PyBlitzArray_TypenumAsString(self->type_num),\n       PyString_AS_STRING(st), PyString_AS_STRING(sp)\n      );\nBOB_CATCH_MEMBER(\"repr\", 0)\n}\n\n\nPyTypeObject PyBoostBinomial_Type = {\n  PyVarObject_HEAD_INIT(0,0)\n  0\n};\n\nbool init_BoostBinomial(PyObject* module)\n{\n  // initialize the type struct\n  PyBoostBinomial_Type.tp_name = binomial_doc.name();\n  PyBoostBinomial_Type.tp_basicsize = sizeof(PyBoostBinomialObject);\n  PyBoostBinomial_Type.tp_flags = Py_TPFLAGS_DEFAULT;\n  PyBoostBinomial_Type.tp_doc = binomial_doc.doc();\n  PyBoostBinomial_Type.tp_str = reinterpret_cast<reprfunc>(PyBoostBinomial_Repr);\n  PyBoostBinomial_Type.tp_repr = reinterpret_cast<reprfunc>(PyBoostBinomial_Repr);\n\n  // set the functions\n  PyBoostBinomial_Type.tp_new = PyBoostBinomial_New;\n  PyBoostBinomial_Type.tp_init = reinterpret_cast<initproc>(PyBoostBinomial_Init);\n  PyBoostBinomial_Type.tp_dealloc = reinterpret_cast<destructor>(PyBoostBinomial_Delete);\n  PyBoostBinomial_Type.tp_methods = PyBoostBinomial_methods;\n  PyBoostBinomial_Type.tp_getset = PyBoostBinomial_getseters;\n  PyBoostBinomial_Type.tp_call = reinterpret_cast<ternaryfunc>(PyBoostBinomial_Call);\n\n  // check that everything is fine\n  if (PyType_Ready(&PyBoostBinomial_Type) < 0) return false;\n\n  // add the type to the module\n  return PyModule_AddObject(module, \"binomial\", Py_BuildValue(\"O\", &PyBoostBinomial_Type)) >= 0;\n}\n", "meta": {"hexsha": "56a773424689dc5ee46f53b21ef82d6726174ffe", "size": 11513, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "bob/core/random/binomial.cpp", "max_stars_repo_name": "AliKhoda/bob.core", "max_stars_repo_head_hexsha": "fca568183d8466d67022cb8ae06c9cd92715c661", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2018-09-03T06:47:21.000Z", "max_stars_repo_stars_event_max_datetime": "2018-11-05T13:45:40.000Z", "max_issues_repo_path": "bob/core/random/binomial.cpp", "max_issues_repo_name": "AliKhoda/bob.core", "max_issues_repo_head_hexsha": "fca568183d8466d67022cb8ae06c9cd92715c661", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2016-04-08T07:29:42.000Z", "max_issues_repo_issues_event_max_datetime": "2016-08-12T20:35:14.000Z", "max_forks_repo_path": "bob/core/random/binomial.cpp", "max_forks_repo_name": "AliKhoda/bob.core", "max_forks_repo_head_hexsha": "fca568183d8466d67022cb8ae06c9cd92715c661", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2015-08-05T12:08:28.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-03T16:58:13.000Z", "avg_line_length": 31.7162534435, "max_line_length": 216, "alphanum_fraction": 0.7067662642, "num_tokens": 3219, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6187804337438501, "lm_q2_score": 0.5389832206876841, "lm_q1q2_score": 0.3335122710777824}}
{"text": "/**\r\n * Copyright (C) 2013 Roman Hiestand\r\n * \r\n * Permission is hereby granted, free of charge, to any person obtaining a copy of this software\r\n * and associated documentation files (the \"Software\"), to deal in the Software without restriction,\r\n * including without limitation the rights to use, copy, modify, merge, publish, distribute,\r\n * sublicense, and/or sell 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 all copies or substantial\r\n * 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\r\n * LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\r\n * 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\r\n * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\r\n */\r\n\r\n#include \"CommonIncludes.h\"\r\n#include \"CalculatePIBoost.h\"\r\n#include \"ProgressIndicatorInterface.h\"\r\n\r\n//#include <boost/math/constants/info.hpp>\r\n#include <boost/math/constants/constants.hpp>\r\n//#include <boost/multiprecision/detail/functions/trig.hpp>\r\n#include <boost/multiprecision/cpp_dec_float.hpp>\r\n\r\nconst wxString CalculatePIBoost::algoName_ = wxT(\"PI: boost\");\r\nconst wxString CalculatePIBoost::algoDescr_ = wxT(\"Calculates PI using the boost::multiprecision library.\");\r\nconst wxString CalculatePIBoost::copyrightText_ = wxT(\"Boost Software License - Version 1.0 - August 17th, 2003\\n\") \\\r\n\twxT(\"\\n\") \\\r\n\twxT(\"Permission is hereby granted, free of charge, to any person or organization\\n\") \\\r\n\twxT(\"obtaining a copy of the software and accompanying documentation covered by\\n\") \\\r\n\twxT(\"this license (the \\\"Software\\\") to use, reproduce, display, distribute,\\n\") \\\r\n\twxT(\"execute, and transmit the Software, and to prepare derivative works of the\\n\") \\\r\n\twxT(\"Software, and to permit third-parties to whom the Software is furnished to\\n\") \\\r\n\twxT(\"do so, all subject to the following:\\n\") \\\r\n\twxT(\"\\n\") \\\r\n\twxT(\"The copyright notices in the Software and this entire statement, including\\n\") \\\r\n\twxT(\"the above license grant, this restriction and the following disclaimer,\\n\") \\\r\n\twxT(\"must be included in all copies of the Software, in whole or in part, and\\n\") \\\r\n\twxT(\"all derivative works of the Software, unless such copies or derivative\\n\") \\\r\n\twxT(\"works are solely in the form of machine-executable object code generated by\\n\") \\\r\n\twxT(\"a source language processor.\\n\") \\\r\n\twxT(\"\\n\") \\\r\n\twxT(\"THE SOFTWARE IS PROVIDED \\\"AS IS\\\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\\n\") \\\r\n\twxT(\"IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\\n\") \\\r\n\twxT(\"FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT\\n\") \\\r\n\twxT(\"SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE\\n\") \\\r\n\twxT(\"FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,\\n\") \\\r\n\twxT(\"ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\\n\") \\\r\n\twxT(\"DEALINGS IN THE SOFTWARE.\");\r\nconst std::string CalculatePIBoost::maxNumberOfDigits_ = \"1000000\";\r\n\r\nCalculatePIBoost::CalculatePIBoost() :\r\n\tpProgressIndicatorInterface_(NULL)\r\n{\r\n}\r\n\r\nCalculatePIBoost::~CalculatePIBoost()\r\n{\r\n}\r\n\t\r\nbool CalculatePIBoost::isMulticoreCapable()\r\n{\r\n\treturn false;\r\n}\r\n\r\nbool CalculatePIBoost::enableProgressBar()\r\n{\r\n\treturn false;\r\n}\r\n\r\nconst std::string &CalculatePIBoost::getMaxNumberOfDigits()\r\n{\r\n\treturn maxNumberOfDigits_;\r\n}\r\n\r\nconst wxString &CalculatePIBoost::getAlgorithmName()\r\n{\r\n\treturn algoName_;\r\n}\r\n\r\nconst wxString &CalculatePIBoost::getAlgorithmDescription()\r\n{\r\n\treturn algoDescr_;\r\n}\r\n\r\nconst wxString &CalculatePIBoost::getCopyrightText()\r\n{\r\n\treturn copyrightText_;\r\n}\r\n\r\nvoid CalculatePIBoost::setDigits(const wxString &digits)\r\n{\r\n\tdigits_ = digits;\r\n}\r\n\r\nvoid CalculatePIBoost::setCores(int c)\r\n{\r\n\t// Don't do anything: This Calculator is not multithreaded\r\n}\r\n\r\n#define VERSION_1\r\n\r\nvoid CalculatePIBoost::calculate(ProgressIndicatorInterface *pProgressIndicatorInterface)\r\n{\r\n\t// The major drawback of boost::multiprecision::cpp_dec_float is that the number of digits needs\r\n\t// to be known at compile time\r\n\tconst int digits_compile_time = 100000;\r\n\tlong long int d;\r\n\tdigits_.ToLongLong(&d);\r\n\tif(d > digits_compile_time)\r\n\t\td = digits_compile_time;\t// ... or else calc_pi does not terminate\r\n\tlong long int d_bits = 0;\t// The number of bits required for d digits\r\n\tdouble digits_bits_factor = std::log( 10.0 ) / std::log( 2.0 );\t// This is log2(10), approx. 3.32\r\n\td_bits = static_cast<long long int>(std::ceil( digits_bits_factor * static_cast<double>(d) ));\r\n\r\n\t//typedef boost::multiprecision::number<boost::multiprecision::cpp_dec_float<digits_compile_time, boost::int32_t, std::allocator<unsigned int> > > calc_pi_mptype;\r\n\t//typedef boost::multiprecision::number<boost::multiprecision::backends::mpfr_float_backend<digits_compile_time> > calc_pi_mptype;\r\n\ttypedef boost::multiprecision::number<boost::multiprecision::backends::gmp_float<digits_compile_time> > calc_pi_mptype;\r\n\tcalc_pi_mptype pi_boost;\r\n\r\n#if defined(VERSION_1)\r\n\t// Version 1 uses boost::math::constants\r\n//\tboost::math::constants::print_info_on_type<mptype>();\r\n\tpi_boost = boost::math::constants::pi<calc_pi_mptype>();\r\n#else\r\n\t// Version 2 uses an internal and undocumented method of boost::multiprecision which may or may not be present in the future\r\n\tboost::multiprecision::default_ops::calc_pi(pi_boost.backend(), d_bits);\r\n#endif\r\n\r\n\tstd::ostringstream ostr;\r\n\tostr << std::setprecision(d+2);\r\n\tostr << pi_boost;\r\n\tresult_ = ostr.str();\r\n}\r\n", "meta": {"hexsha": "15a5f941eea59dbf7cb671350c2dd3623ce3743a", "size": 5859, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "CalculatePIBoost.cpp", "max_stars_repo_name": "grevutiu-gabriel/calcpi-code", "max_stars_repo_head_hexsha": "4e2cbb9fbeeb8ed54167ee5f98e09ba34c2fa730", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "CalculatePIBoost.cpp", "max_issues_repo_name": "grevutiu-gabriel/calcpi-code", "max_issues_repo_head_hexsha": "4e2cbb9fbeeb8ed54167ee5f98e09ba34c2fa730", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "CalculatePIBoost.cpp", "max_forks_repo_name": "grevutiu-gabriel/calcpi-code", "max_forks_repo_head_hexsha": "4e2cbb9fbeeb8ed54167ee5f98e09ba34c2fa730", "max_forks_repo_licenses": ["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.1510791367, "max_line_length": 164, "alphanum_fraction": 0.7412527735, "num_tokens": 1363, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.577495350642608, "lm_q2_score": 0.5774953651858117, "lm_q1q2_score": 0.3335008884124613}}
{"text": "/* Author: Wolfgang Bangerth, Texas A&M University, 2011 */\n\n/*    $Id: step-46.cc 27737 2012-12-03 19:44:54Z heister $       */\n/*                                                                */\n/*    Copyright (C) 2011-2012 by the deal.II authors */\n/*                                                                */\n/*    This file is subject to QPL and may not be  distributed     */\n/*    without copyright and license information. Please refer     */\n/*    to the file deal.II/doc/license.html for the  text  and     */\n/*    further information on this license.                        */\n\n\n// @sect3{Include files}\n\n// The include files for this program are the same as for many others\n// before. The only new one is the one that declares FE_Nothing as discussed\n// in the introduction. The ones in the hp directory have already been\n// discussed in step-27.\n\n#include <deal.II/base/quadrature_lib.h>\n#include <deal.II/base/logstream.h>\n#include <deal.II/base/function.h>\n#include <deal.II/base/utilities.h>\n\n#include <deal.II/lac/vector.h>\n#include <deal.II/lac/full_matrix.h>\n#include <deal.II/lac/sparse_matrix.h>\n#include <deal.II/lac/sparse_direct.h>\n#include <deal.II/lac/constraint_matrix.h>\n\n#include <deal.II/grid/tria.h>\n#include <deal.II/grid/grid_generator.h>\n#include <deal.II/grid/tria_accessor.h>\n#include <deal.II/grid/tria_iterator.h>\n#include <deal.II/grid/grid_refinement.h>\n\n#include <deal.II/dofs/dof_tools.h>\n#include <deal.II/dofs/dof_accessor.h>\n\n#include <deal.II/fe/fe_q.h>\n#include <deal.II/fe/fe_nothing.h>\n#include <deal.II/fe/fe_system.h>\n#include <deal.II/fe/fe_values.h>\n\n#include <deal.II/hp/dof_handler.h>\n#include <deal.II/hp/fe_collection.h>\n#include <deal.II/hp/fe_values.h>\n\n#include <deal.II/numerics/vector_tools.h>\n#include <deal.II/numerics/data_out.h>\n#include <deal.II/numerics/error_estimator.h>\n\n#include <fstream>\n#include <sstream>\n\n\nnamespace Step46\n{\n  using namespace dealii;\n\n  // @sect3{The <code>FluidStructureProblem</code> class template}\n\n  // This is the main class. It is, if you want, a combination of step-8 and\n  // step-22 in that it has member variables that either address the global\n  // problem (the Triangulation and hp::DoFHandler objects, as well as the\n  // hp::FECollection and various linear algebra objects) or that pertain to\n  // either the elasticity or Stokes sub-problems. The general structure of\n  // the class, however, is like that of most of the other programs\n  // implementing stationary problems.\n  //\n  // There are a few helper functions (<code>cell_is_in_fluid_domain,\n  // cell_is_in_solid_domain</code>) of self-explanatory nature (operating on\n  // the symbolic names for the two subdomains that will be used as\n  // material_ids for cells belonging to the subdomains, as explained in the\n  // introduction) and a few functions (<code>make_grid,\n  // set_active_fe_indices, assemble_interface_terms</code>) that have been\n  // broken out of other functions that can be found in many of the other\n  // tutorial programs and that will be discussed as we get to their\n  // implementation.\n  //\n  // The final set of variables (<code>viscosity, lambda, eta</code>)\n  // describes the material properties used for the two physics models.\n  template <int dim>\n  class FluidStructureProblem\n  {\n  public:\n    FluidStructureProblem (const unsigned int stokes_degree,\n                           const unsigned int elasticity_degree);\n    void run ();\n\n  private:\n    enum\n    {\n      fluid_domain_id,\n      solid_domain_id\n    };\n\n    static bool\n    cell_is_in_fluid_domain (const typename hp::DoFHandler<dim>::cell_iterator &cell);\n\n    static bool\n    cell_is_in_solid_domain (const typename hp::DoFHandler<dim>::cell_iterator &cell);\n\n\n    void make_grid ();\n    void set_active_fe_indices ();\n    void setup_dofs ();\n    void assemble_system ();\n    void assemble_interface_term (const FEFaceValuesBase<dim>          &elasticity_fe_face_values,\n                                  const FEFaceValuesBase<dim>          &stokes_fe_face_values,\n                                  std::vector<Tensor<1,dim> >          &elasticity_phi,\n                                  std::vector<SymmetricTensor<2,dim> > &stokes_symgrad_phi_u,\n                                  std::vector<double>                  &stokes_phi_p,\n                                  FullMatrix<double>                   &local_interface_matrix) const;\n    void solve ();\n    void output_results (const unsigned int refinement_cycle) const;\n    void refine_mesh ();\n\n    const unsigned int    stokes_degree;\n    const unsigned int    elasticity_degree;\n\n    Triangulation<dim>    triangulation;\n    FESystem<dim>         stokes_fe;\n    FESystem<dim>         elasticity_fe;\n    hp::FECollection<dim> fe_collection;\n    hp::DoFHandler<dim>   dof_handler;\n\n    ConstraintMatrix      constraints;\n\n    SparsityPattern       sparsity_pattern;\n    SparseMatrix<double>  system_matrix;\n\n    Vector<double>        solution;\n    Vector<double>        system_rhs;\n\n    const double          viscosity;\n    const double          lambda;\n    const double          mu;\n  };\n\n\n  // @sect3{Boundary values and right hand side}\n\n  // The following classes do as their names suggest. The boundary values for\n  // the velocity are $\\mathbf u=(0, \\sin(\\pi x))^T$ in 2d and $\\mathbf u=(0,\n  // 0, \\sin(\\pi x)\\sin(\\pi y))^T$ in 3d, respectively. The remaining boundary\n  // conditions for this problem are all homogenous and have been discussed in\n  // the introduction. The right hand side forcing term is zero for both the\n  // fluid and the solid.\n  template <int dim>\n  class StokesBoundaryValues : public Function<dim>\n  {\n  public:\n    StokesBoundaryValues () : Function<dim>(dim+1+dim) {}\n\n    virtual double value (const Point<dim>   &p,\n                          const unsigned int  component = 0) const;\n\n    virtual void vector_value (const Point<dim> &p,\n                               Vector<double>   &value) const;\n  };\n\n\n  template <int dim>\n  double\n  StokesBoundaryValues<dim>::value (const Point<dim> &p,\n                                    const unsigned int component) const\n  {\n    Assert (component < this->n_components,\n            ExcIndexRange (component, 0, this->n_components));\n\n    if (component == dim-1)\n      switch (dim)\n        {\n        case 2:\n          return std::sin(numbers::PI*p[0]);\n        case 3:\n          return std::sin(numbers::PI*p[0]) * std::sin(numbers::PI*p[1]);\n        default:\n          Assert (false, ExcNotImplemented());\n        }\n\n    return 0;\n  }\n\n\n  template <int dim>\n  void\n  StokesBoundaryValues<dim>::vector_value (const Point<dim> &p,\n                                           Vector<double>   &values) const\n  {\n    for (unsigned int c=0; c<this->n_components; ++c)\n      values(c) = StokesBoundaryValues<dim>::value (p, c);\n  }\n\n\n\n  template <int dim>\n  class RightHandSide : public Function<dim>\n  {\n  public:\n    RightHandSide () : Function<dim>(dim+1) {}\n\n    virtual double value (const Point<dim>   &p,\n                          const unsigned int  component = 0) const;\n\n    virtual void vector_value (const Point<dim> &p,\n                               Vector<double>   &value) const;\n\n  };\n\n\n  template <int dim>\n  double\n  RightHandSide<dim>::value (const Point<dim>  & /*p*/,\n                             const unsigned int /*component*/) const\n  {\n    return 0;\n  }\n\n\n  template <int dim>\n  void\n  RightHandSide<dim>::vector_value (const Point<dim> &p,\n                                    Vector<double>   &values) const\n  {\n    for (unsigned int c=0; c<this->n_components; ++c)\n      values(c) = RightHandSide<dim>::value (p, c);\n  }\n\n\n\n  // @sect3{The <code>FluidStructureProblem</code> implementation}\n\n  // @sect4{Constructors and helper functions}\n\n  // Let's now get to the implementation of the primary class of this\n  // program. The first few functions are the constructor and the helper\n  // functions that can be used to determine which part of the domain a cell\n  // is in. Given the discussion of these topics in the introduction, their\n  // implementation is rather obvious. In the constructor, note that we have\n  // to construct the hp::FECollection object from the base elements for\n  // Stokes and elasticity; using the hp::FECollection::push_back function\n  // assigns them spots zero and one in this collection, an order that we have\n  // to remember and use consistently in the rest of the program.\n  template <int dim>\n  FluidStructureProblem<dim>::\n  FluidStructureProblem (const unsigned int stokes_degree,\n                         const unsigned int elasticity_degree)\n    :\n    stokes_degree (stokes_degree),\n    elasticity_degree (elasticity_degree),\n    triangulation (Triangulation<dim>::maximum_smoothing),\n    stokes_fe (FE_Q<dim>(stokes_degree+1), dim,\n               FE_Q<dim>(stokes_degree), 1,\n               FE_Nothing<dim>(), dim),\n    elasticity_fe (FE_Nothing<dim>(), dim,\n                   FE_Nothing<dim>(), 1,\n                   FE_Q<dim>(elasticity_degree), dim),\n    dof_handler (triangulation),\n    viscosity (2),\n    lambda (1),\n    mu (1)\n  {\n    fe_collection.push_back (stokes_fe);\n    fe_collection.push_back (elasticity_fe);\n  }\n\n\n\n\n  template <int dim>\n  bool\n  FluidStructureProblem<dim>::\n  cell_is_in_fluid_domain (const typename hp::DoFHandler<dim>::cell_iterator &cell)\n  {\n    return (cell->material_id() == fluid_domain_id);\n  }\n\n\n  template <int dim>\n  bool\n  FluidStructureProblem<dim>::\n  cell_is_in_solid_domain (const typename hp::DoFHandler<dim>::cell_iterator &cell)\n  {\n    return (cell->material_id() == solid_domain_id);\n  }\n\n\n  // @sect4{Meshes and assigning subdomains}\n\n  // The next pair of functions deals with generating a mesh and making sure\n  // all flags that denote subdomains are correct. <code>make_grid</code>, as\n  // discussed in the introduction, generates an $8\\times 8$ mesh (or an\n  // $8\\times 8\\times 8$ mesh in 3d) to make sure that each coarse mesh cell\n  // is completely within one of the subdomains. After generating this mesh,\n  // we loop over its boundary and set the boundary indicator to one at the\n  // top boundary, the only place where we set nonzero Dirichlet boundary\n  // conditions. After this, we loop again over all cells to set the material\n  // indicator &mdash; used to denote which part of the domain we are in, to\n  // either the fluid or solid indicator.\n  template <int dim>\n  void\n  FluidStructureProblem<dim>::make_grid ()\n  {\n    GridGenerator::subdivided_hyper_cube (triangulation, 8, -1, 1);\n\n    for (typename Triangulation<dim>::active_cell_iterator\n         cell = triangulation.begin_active();\n         cell != triangulation.end(); ++cell)\n      for (unsigned int f=0; f<GeometryInfo<dim>::faces_per_cell; ++f)\n        if (cell->face(f)->at_boundary()\n            &&\n            (cell->face(f)->center()[dim-1] == 1))\n          cell->face(f)->set_all_boundary_indicators(1);\n\n\n    for (typename Triangulation<dim>::active_cell_iterator\n         cell = dof_handler.begin_active();\n         cell != dof_handler.end(); ++cell)\n      if (((std::fabs(cell->center()[0]) < 0.25)\n           &&\n           (cell->center()[dim-1] > 0.5))\n          ||\n          ((std::fabs(cell->center()[0]) >= 0.25)\n           &&\n           (cell->center()[dim-1] > -0.5)))\n        cell->set_material_id (fluid_domain_id);\n      else\n        cell->set_material_id (solid_domain_id);\n  }\n\n\n  // The second part of this pair of functions determines which finite element\n  // to use on each cell. Above we have set the material indicator for each\n  // coarse mesh cell, and as mentioned in the introduction, this information\n  // is inherited from mother to child cell upon mesh refinement.\n  //\n  // In other words, whenever we have refined (or created) the mesh, we can\n  // rely on the material indicators to be a correct description of which part\n  // of the domain a cell is in. We then use this to set the active FE index\n  // of the cell to the corresponding element of the hp::FECollection member\n  // variable of this class: zero for fluid cells, one for solid cells.\n  template <int dim>\n  void\n  FluidStructureProblem<dim>::set_active_fe_indices ()\n  {\n    for (typename hp::DoFHandler<dim>::active_cell_iterator\n         cell = dof_handler.begin_active();\n         cell != dof_handler.end(); ++cell)\n      {\n        if (cell_is_in_fluid_domain(cell))\n          cell->set_active_fe_index (0);\n        else if (cell_is_in_solid_domain(cell))\n          cell->set_active_fe_index (1);\n        else\n          Assert (false, ExcNotImplemented());\n      }\n  }\n\n\n  // @sect4{<code>FluidStructureProblem::setup_dofs</code>}\n\n  // The next step is to setup the data structures for the linear system. To\n  // this end, we first have to set the active FE indices with the function\n  // immediately above, then distribute degrees of freedom, and then determine\n  // constraints on the linear system. The latter includes hanging node\n  // constraints as usual, but also the inhomogenous boundary values at the\n  // top fluid boundary, and zero boundary values along the perimeter of the\n  // solid subdomain.\n  template <int dim>\n  void\n  FluidStructureProblem<dim>::setup_dofs ()\n  {\n    set_active_fe_indices ();\n    dof_handler.distribute_dofs (fe_collection);\n\n    {\n      constraints.clear ();\n      DoFTools::make_hanging_node_constraints (dof_handler,\n                                               constraints);\n\n      const FEValuesExtractors::Vector velocities(0);\n      VectorTools::interpolate_boundary_values (dof_handler,\n                                                1,\n                                                StokesBoundaryValues<dim>(),\n                                                constraints,\n                                                fe_collection.component_mask(velocities));\n\n      const FEValuesExtractors::Vector displacements(dim+1);\n      VectorTools::interpolate_boundary_values (dof_handler,\n                                                0,\n                                                ZeroFunction<dim>(dim+1+dim),\n                                                constraints,\n                                                fe_collection.component_mask(displacements));\n    }\n\n    // There are more constraints we have to handle, though: we have to make\n    // sure that the velocity is zero at the interface between fluid and\n    // solid. The following piece of code was already presented in the\n    // introduction:\n    {\n      std::vector<unsigned int> local_face_dof_indices (stokes_fe.dofs_per_face);\n      for (typename hp::DoFHandler<dim>::active_cell_iterator\n           cell = dof_handler.begin_active();\n           cell != dof_handler.end(); ++cell)\n        if (cell_is_in_fluid_domain (cell))\n          for (unsigned int f=0; f<GeometryInfo<dim>::faces_per_cell; ++f)\n            if (!cell->at_boundary(f))\n              {\n                bool face_is_on_interface = false;\n\n                if ((cell->neighbor(f)->has_children() == false)\n                    &&\n                    (cell_is_in_solid_domain (cell->neighbor(f))))\n                  face_is_on_interface = true;\n                else if (cell->neighbor(f)->has_children() == true)\n                  {\n                    for (unsigned int sf=0; sf<cell->face(f)->n_children(); ++sf)\n                      if (cell_is_in_solid_domain (cell->neighbor_child_on_subface\n                                                   (f, sf)))\n                        {\n                          face_is_on_interface = true;\n                          break;\n                        }\n                  }\n\n                if (face_is_on_interface)\n                  {\n                    cell->face(f)->get_dof_indices (local_face_dof_indices, 0);\n                    for (unsigned int i=0; i<local_face_dof_indices.size(); ++i)\n                      if (stokes_fe.face_system_to_component_index(i).first < dim)\n                        constraints.add_line (local_face_dof_indices[i]);\n                  }\n              }\n    }\n\n    // At the end of all this, we can declare to the constraints object that\n    // we now have all constraints ready to go and that the object can rebuild\n    // its internal data structures for better efficiency:\n    constraints.close ();\n\n    std::cout << \"   Number of active cells: \"\n              << triangulation.n_active_cells()\n              << std::endl\n              << \"   Number of degrees of freedom: \"\n              << dof_handler.n_dofs()\n              << std::endl;\n\n    // In the rest of this function we create a sparsity pattern as discussed\n    // extensively in the introduction, and use it to initialize the matrix;\n    // then also set vectors to their correct sizes:\n    {\n      CompressedSimpleSparsityPattern csp (dof_handler.n_dofs(),\n                                           dof_handler.n_dofs());\n\n      Table<2,DoFTools::Coupling> cell_coupling (fe_collection.n_components(),\n                                                 fe_collection.n_components());\n      Table<2,DoFTools::Coupling> face_coupling (fe_collection.n_components(),\n                                                 fe_collection.n_components());\n\n      for (unsigned int c=0; c<fe_collection.n_components(); ++c)\n        for (unsigned int d=0; d<fe_collection.n_components(); ++d)\n          {\n            if (((c<dim+1) && (d<dim+1)\n                 && !((c==dim) && (d==dim)))\n                ||\n                ((c>=dim+1) && (d>=dim+1)))\n              cell_coupling[c][d] = DoFTools::always;\n\n            if ((c>=dim+1) && (d<dim+1))\n              face_coupling[c][d] = DoFTools::always;\n          }\n\n      DoFTools::make_flux_sparsity_pattern (dof_handler, csp,\n                                            cell_coupling, face_coupling);\n      constraints.condense (csp);\n      sparsity_pattern.copy_from (csp);\n    }\n\n    system_matrix.reinit (sparsity_pattern);\n\n    solution.reinit (dof_handler.n_dofs());\n    system_rhs.reinit (dof_handler.n_dofs());\n  }\n\n\n\n  // @sect4{<code>FluidStructureProblem::assemble_system</code>}\n\n  // Following is the central function of this program: the one that assembles\n  // the linear system. It has a long section of setting up auxiliary\n  // functions at the beginning: from creating the quadrature formulas and\n  // setting up the FEValues, FEFaceValues and FESubfaceValues objects\n  // necessary to integrate the cell terms as well as the interface terms for\n  // the case where cells along the interface come together at same size or\n  // with differing levels of refinement...\n  template <int dim>\n  void FluidStructureProblem<dim>::assemble_system ()\n  {\n    system_matrix=0;\n    system_rhs=0;\n\n    const QGauss<dim> stokes_quadrature(stokes_degree+2);\n    const QGauss<dim> elasticity_quadrature(elasticity_degree+2);\n\n    hp::QCollection<dim>  q_collection;\n    q_collection.push_back (stokes_quadrature);\n    q_collection.push_back (elasticity_quadrature);\n\n    hp::FEValues<dim> hp_fe_values (fe_collection, q_collection,\n                                    update_values    |\n                                    update_quadrature_points  |\n                                    update_JxW_values |\n                                    update_gradients);\n\n    const QGauss<dim-1> common_face_quadrature(std::max (stokes_degree+2,\n                                                         elasticity_degree+2));\n\n    FEFaceValues<dim>    stokes_fe_face_values (stokes_fe,\n                                                common_face_quadrature,\n                                                update_JxW_values |\n                                                update_normal_vectors |\n                                                update_gradients);\n    FEFaceValues<dim>    elasticity_fe_face_values (elasticity_fe,\n                                                    common_face_quadrature,\n                                                    update_values);\n    FESubfaceValues<dim> stokes_fe_subface_values (stokes_fe,\n                                                   common_face_quadrature,\n                                                   update_JxW_values |\n                                                   update_normal_vectors |\n                                                   update_gradients);\n    FESubfaceValues<dim> elasticity_fe_subface_values (elasticity_fe,\n                                                       common_face_quadrature,\n                                                       update_values);\n\n    // ...to objects that are needed to describe the local contributions to\n    // the global linear system...\n    const unsigned int        stokes_dofs_per_cell     = stokes_fe.dofs_per_cell;\n    const unsigned int        elasticity_dofs_per_cell = elasticity_fe.dofs_per_cell;\n\n    FullMatrix<double>        local_matrix;\n    FullMatrix<double>        local_interface_matrix (elasticity_dofs_per_cell,\n                                                      stokes_dofs_per_cell);\n    Vector<double>            local_rhs;\n\n    std::vector<unsigned int> local_dof_indices;\n    std::vector<unsigned int> neighbor_dof_indices (stokes_dofs_per_cell);\n\n    const RightHandSide<dim>  right_hand_side;\n\n    // ...to variables that allow us to extract certain components of the\n    // shape functions and cache their values rather than having to recompute\n    // them at every quadrature point:\n    const FEValuesExtractors::Vector     velocities (0);\n    const FEValuesExtractors::Scalar     pressure (dim);\n    const FEValuesExtractors::Vector     displacements (dim+1);\n\n    std::vector<SymmetricTensor<2,dim> > stokes_symgrad_phi_u (stokes_dofs_per_cell);\n    std::vector<double>                  stokes_div_phi_u     (stokes_dofs_per_cell);\n    std::vector<double>                  stokes_phi_p         (stokes_dofs_per_cell);\n\n    std::vector<Tensor<2,dim> >          elasticity_grad_phi (elasticity_dofs_per_cell);\n    std::vector<double>                  elasticity_div_phi  (elasticity_dofs_per_cell);\n    std::vector<Tensor<1,dim> >          elasticity_phi      (elasticity_dofs_per_cell);\n\n    // Then comes the main loop over all cells and, as in step-27, the\n    // initialization of the hp::FEValues object for the current cell and the\n    // extraction of a FEValues object that is appropriate for the current\n    // cell:\n    typename hp::DoFHandler<dim>::active_cell_iterator\n    cell = dof_handler.begin_active(),\n    endc = dof_handler.end();\n    for (; cell!=endc; ++cell)\n      {\n        hp_fe_values.reinit (cell);\n\n        const FEValues<dim> &fe_values = hp_fe_values.get_present_fe_values();\n\n        local_matrix.reinit (cell->get_fe().dofs_per_cell,\n                             cell->get_fe().dofs_per_cell);\n        local_rhs.reinit (cell->get_fe().dofs_per_cell);\n\n        // With all of this done, we continue to assemble the cell terms for\n        // cells that are part of the Stokes and elastic regions. While we\n        // could in principle do this in one formula, in effect implementing\n        // the one bilinear form stated in the introduction, we realize that\n        // our finite element spaces are chosen in such a way that on each\n        // cell, one set of variables (either velocities and pressure, or\n        // displacements) are always zero, and consequently a more efficient\n        // way of computing local integrals is to do only what's necessary\n        // based on an <code>if</code> clause that tests which part of the\n        // domain we are in.\n        //\n        // The actual computation of the local matrix is the same as in\n        // step-22 as well as that given in the @ref vector_valued\n        // documentation module for the elasticity equations:\n        if (cell_is_in_fluid_domain (cell))\n          {\n            const unsigned int dofs_per_cell = cell->get_fe().dofs_per_cell;\n            Assert (dofs_per_cell == stokes_dofs_per_cell,\n                    ExcInternalError());\n\n            for (unsigned int q=0; q<fe_values.n_quadrature_points; ++q)\n              {\n                for (unsigned int k=0; k<dofs_per_cell; ++k)\n                  {\n                    stokes_symgrad_phi_u[k] = fe_values[velocities].symmetric_gradient (k, q);\n                    stokes_div_phi_u[k]     = fe_values[velocities].divergence (k, q);\n                    stokes_phi_p[k]         = fe_values[pressure].value (k, q);\n                  }\n\n                for (unsigned int i=0; i<dofs_per_cell; ++i)\n                  for (unsigned int j=0; j<dofs_per_cell; ++j)\n                    local_matrix(i,j) += (2 * viscosity * stokes_symgrad_phi_u[i] * stokes_symgrad_phi_u[j]\n                                          - stokes_div_phi_u[i] * stokes_phi_p[j]\n                                          - stokes_phi_p[i] * stokes_div_phi_u[j])\n                                         * fe_values.JxW(q);\n              }\n          }\n        else\n          {\n            const unsigned int dofs_per_cell = cell->get_fe().dofs_per_cell;\n            Assert (dofs_per_cell == elasticity_dofs_per_cell,\n                    ExcInternalError());\n\n            for (unsigned int q=0; q<fe_values.n_quadrature_points; ++q)\n              {\n                for (unsigned int k=0; k<dofs_per_cell; ++k)\n                  {\n                    elasticity_grad_phi[k] = fe_values[displacements].gradient (k, q);\n                    elasticity_div_phi[k]  = fe_values[displacements].divergence (k, q);\n                  }\n\n                for (unsigned int i=0; i<dofs_per_cell; ++i)\n                  for (unsigned int j=0; j<dofs_per_cell; ++j)\n                    {\n                      local_matrix(i,j)\n                      +=  (lambda *\n                           elasticity_div_phi[i] * elasticity_div_phi[j]\n                           +\n                           mu *\n                           scalar_product(elasticity_grad_phi[i], elasticity_grad_phi[j])\n                           +\n                           mu *\n                           scalar_product(elasticity_grad_phi[i], transpose(elasticity_grad_phi[j]))\n                          )\n                          *\n                          fe_values.JxW(q);\n                    }\n              }\n          }\n\n        // Once we have the contributions from cell integrals, we copy them\n        // into the global matrix (taking care of constraints right away,\n        // through the ConstraintMatrix::distribute_local_to_global\n        // function). Note that we have not written anything into the\n        // <code>local_rhs</code> variable, though we still need to pass it\n        // along since the elimination of nonzero boundary values requires the\n        // modification of local and consequently also global right hand side\n        // values:\n        local_dof_indices.resize (cell->get_fe().dofs_per_cell);\n        cell->get_dof_indices (local_dof_indices);\n        constraints.distribute_local_to_global (local_matrix, local_rhs,\n                                                local_dof_indices,\n                                                system_matrix, system_rhs);\n\n        // The more interesting part of this function is where we see about\n        // face terms along the interface between the two subdomains. To this\n        // end, we first have to make sure that we only assemble them once\n        // even though a loop over all faces of all cells would encounter each\n        // part of the interface twice. We arbitrarily make the decision that\n        // we will only evaluate interface terms if the current cell is part\n        // of the solid subdomain and if, consequently, a face is not at the\n        // boundary and the potential neighbor behind it is part of the fluid\n        // domain. Let's start with these conditions:\n        if (cell_is_in_solid_domain (cell))\n          for (unsigned int f=0; f<GeometryInfo<dim>::faces_per_cell; ++f)\n            if (cell->at_boundary(f) == false)\n              {\n                // At this point we know that the current cell is a candidate\n                // for integration and that a neighbor behind face\n                // <code>f</code> exists. There are now three possibilities:\n                //\n                // - The neighbor is at the same refinement level and has no\n                //   children.\n                // - The neighbor has children.\n                // - The neighbor is coarser.\n                //\n                // In all three cases, we are only interested in it if it is\n                // part of the fluid subdomain. So let us start with the first\n                // and simplest case: if the neighbor is at the same level,\n                // has no children, and is a fluid cell, then the two cells\n                // share a boundary that is part of the interface along which\n                // we want to integrate interface terms. All we have to do is\n                // initialize two FEFaceValues object with the current face\n                // and the face of the neighboring cell (note how we find out\n                // which face of the neighboring cell borders on the current\n                // cell) and pass things off to the function that evaluates\n                // the interface terms (the third through fifth arguments to\n                // this function provide it with scratch arrays). The result\n                // is then again copied into the global matrix, using a\n                // function that knows that the DoF indices of rows and\n                // columns of the local matrix result from different cells:\n                if ((cell->neighbor(f)->level() == cell->level())\n                    &&\n                    (cell->neighbor(f)->has_children() == false)\n                    &&\n                    cell_is_in_fluid_domain (cell->neighbor(f)))\n                  {\n                    elasticity_fe_face_values.reinit (cell, f);\n                    stokes_fe_face_values.reinit (cell->neighbor(f),\n                                                  cell->neighbor_of_neighbor(f));\n\n                    assemble_interface_term (elasticity_fe_face_values, stokes_fe_face_values,\n                                             elasticity_phi, stokes_symgrad_phi_u, stokes_phi_p,\n                                             local_interface_matrix);\n\n                    cell->neighbor(f)->get_dof_indices (neighbor_dof_indices);\n                    constraints.distribute_local_to_global(local_interface_matrix,\n                                                           local_dof_indices,\n                                                           neighbor_dof_indices,\n                                                           system_matrix);\n                  }\n\n                // The second case is if the neighbor has further children. In\n                // that case, we have to loop over all the children of the\n                // neighbor to see if they are part of the fluid subdomain. If\n                // they are, then we integrate over the common interface,\n                // which is a face for the neighbor and a subface of the\n                // current cell, requiring us to use an FEFaceValues for the\n                // neighbor and an FESubfaceValues for the current cell:\n                else if ((cell->neighbor(f)->level() == cell->level())\n                         &&\n                         (cell->neighbor(f)->has_children() == true))\n                  {\n                    for (unsigned int subface=0;\n                         subface<cell->face(f)->n_children();\n                         ++subface)\n                      if (cell_is_in_fluid_domain (cell->neighbor_child_on_subface\n                                                   (f, subface)))\n                        {\n                          elasticity_fe_subface_values.reinit (cell,\n                                                               f,\n                                                               subface);\n                          stokes_fe_face_values.reinit (cell->neighbor_child_on_subface (f, subface),\n                                                        cell->neighbor_of_neighbor(f));\n\n                          assemble_interface_term (elasticity_fe_subface_values,\n                                                   stokes_fe_face_values,\n                                                   elasticity_phi,\n                                                   stokes_symgrad_phi_u, stokes_phi_p,\n                                                   local_interface_matrix);\n\n                          cell->neighbor_child_on_subface (f, subface)\n                          ->get_dof_indices (neighbor_dof_indices);\n                          constraints.distribute_local_to_global(local_interface_matrix,\n                                                                 local_dof_indices,\n                                                                 neighbor_dof_indices,\n                                                                 system_matrix);\n                        }\n                  }\n\n                // The last option is that the neighbor is coarser. In that\n                // case we have to use an FESubfaceValues object for the\n                // neighbor and a FEFaceValues for the current cell; the rest\n                // is the same as before:\n                else if (cell->neighbor_is_coarser(f)\n                         &&\n                         cell_is_in_fluid_domain(cell->neighbor(f)))\n                  {\n                    elasticity_fe_face_values.reinit (cell, f);\n                    stokes_fe_subface_values.reinit (cell->neighbor(f),\n                                                     cell->neighbor_of_coarser_neighbor(f).first,\n                                                     cell->neighbor_of_coarser_neighbor(f).second);\n\n                    assemble_interface_term (elasticity_fe_face_values,\n                                             stokes_fe_subface_values,\n                                             elasticity_phi,\n                                             stokes_symgrad_phi_u, stokes_phi_p,\n                                             local_interface_matrix);\n\n                    cell->neighbor(f)->get_dof_indices (neighbor_dof_indices);\n                    constraints.distribute_local_to_global(local_interface_matrix,\n                                                           local_dof_indices,\n                                                           neighbor_dof_indices,\n                                                           system_matrix);\n\n                  }\n              }\n      }\n  }\n\n\n\n  // In the function that assembles the global system, we passed computing\n  // interface terms to a separate function we discuss here. The key is that\n  // even though we can't predict the combination of FEFaceValues and\n  // FESubfaceValues objects, they are both derived from the FEFaceValuesBase\n  // class and consequently we don't have to care: the function is simply\n  // called with two such objects denoting the values of the shape functions\n  // on the quadrature points of the two sides of the face. We then do what we\n  // always do: we fill the scratch arrays with the values of shape functions\n  // and their derivatives, and then loop over all entries of the matrix to\n  // compute the local integrals. The details of the bilinear form we evaluate\n  // here are given in the introduction.\n  template <int dim>\n  void\n  FluidStructureProblem<dim>::\n  assemble_interface_term (const FEFaceValuesBase<dim>          &elasticity_fe_face_values,\n                           const FEFaceValuesBase<dim>          &stokes_fe_face_values,\n                           std::vector<Tensor<1,dim> >          &elasticity_phi,\n                           std::vector<SymmetricTensor<2,dim> > &stokes_symgrad_phi_u,\n                           std::vector<double>                  &stokes_phi_p,\n                           FullMatrix<double>                   &local_interface_matrix) const\n  {\n    Assert (stokes_fe_face_values.n_quadrature_points ==\n            elasticity_fe_face_values.n_quadrature_points,\n            ExcInternalError());\n    const unsigned int n_face_quadrature_points\n      = elasticity_fe_face_values.n_quadrature_points;\n\n    const FEValuesExtractors::Vector velocities (0);\n    const FEValuesExtractors::Scalar pressure (dim);\n    const FEValuesExtractors::Vector displacements (dim+1);\n\n    local_interface_matrix = 0;\n    for (unsigned int q=0; q<n_face_quadrature_points; ++q)\n      {\n        const Tensor<1,dim> normal_vector = stokes_fe_face_values.normal_vector(q);\n\n        for (unsigned int k=0; k<stokes_fe_face_values.dofs_per_cell; ++k)\n          stokes_symgrad_phi_u[k] = stokes_fe_face_values[velocities].symmetric_gradient (k, q);\n        for (unsigned int k=0; k<elasticity_fe_face_values.dofs_per_cell; ++k)\n          elasticity_phi[k] = elasticity_fe_face_values[displacements].value (k,q);\n\n        for (unsigned int i=0; i<elasticity_fe_face_values.dofs_per_cell; ++i)\n          for (unsigned int j=0; j<stokes_fe_face_values.dofs_per_cell; ++j)\n            local_interface_matrix(i,j) += -((2 * viscosity *\n                                              (stokes_symgrad_phi_u[j] *\n                                               normal_vector)\n                                              +\n                                              stokes_phi_p[j] *\n                                              normal_vector) *\n                                             elasticity_phi[i] *\n                                             stokes_fe_face_values.JxW(q));\n      }\n  }\n\n\n  // @sect4{<code>FluidStructureProblem::solve</code>}\n\n  // As discussed in the introduction, we use a rather trivial solver here: we\n  // just pass the linear system off to the SparseDirectUMFPACK direct solver\n  // (see, for example, step-29). The only thing we have to do after solving\n  // is ensure that hanging node and boundary value constraints are correct.\n  template <int dim>\n  void\n  FluidStructureProblem<dim>::solve ()\n  {\n    SparseDirectUMFPACK direct_solver;\n    direct_solver.initialize (system_matrix);\n    direct_solver.vmult (solution, system_rhs);\n\n    constraints.distribute (solution);\n  }\n\n\n\n  // @sect4{<code>FluidStructureProblem::output_results</code>}\n\n  // Generating graphical output is rather trivial here: all we have to do is\n  // identify which components of the solution vector belong to scalars and/or\n  // vectors (see, for example, step-22 for a previous example), and then pass\n  // it all on to the DataOut class (with the second template argument equal\n  // to hp::DoFHandler instead of the usual default DoFHandler):\n  template <int dim>\n  void\n  FluidStructureProblem<dim>::\n  output_results (const unsigned int refinement_cycle)  const\n  {\n    std::vector<std::string> solution_names (dim, \"velocity\");\n    solution_names.push_back (\"pressure\");\n    for (unsigned int d=0; d<dim; ++d)\n      solution_names.push_back (\"displacement\");\n\n    std::vector<DataComponentInterpretation::DataComponentInterpretation>\n    data_component_interpretation\n    (dim, DataComponentInterpretation::component_is_part_of_vector);\n    data_component_interpretation\n    .push_back (DataComponentInterpretation::component_is_scalar);\n    for (unsigned int d=0; d<dim; ++d)\n      data_component_interpretation\n      .push_back (DataComponentInterpretation::component_is_part_of_vector);\n\n    DataOut<dim,hp::DoFHandler<dim> > data_out;\n    data_out.attach_dof_handler (dof_handler);\n\n    data_out.add_data_vector (solution, solution_names,\n                              DataOut<dim,hp::DoFHandler<dim> >::type_dof_data,\n                              data_component_interpretation);\n    data_out.build_patches ();\n\n    std::ostringstream filename;\n    filename << \"solution-\"\n             << Utilities::int_to_string (refinement_cycle, 2)\n             << \".vtk\";\n\n    std::ofstream output (filename.str().c_str());\n    data_out.write_vtk (output);\n  }\n\n\n  // @sect4{<code>FluidStructureProblem::refine_mesh</code>}\n\n  // The next step is to refine the mesh. As was discussed in the\n  // introduction, this is a bit tricky primarily because the fluid and the\n  // solid subdomains use variables that have different physical dimensions\n  // and for which the absolute magnitude of error estimates is consequently\n  // not directly comparable. We will therefore have to scale them. At the top\n  // of the function, we therefore first compute error estimates for the\n  // different variables separately (using the velocities but not the pressure\n  // for the fluid domain, and the displacements in the solid domain):\n  template <int dim>\n  void\n  FluidStructureProblem<dim>::refine_mesh ()\n  {\n    Vector<float>\n    stokes_estimated_error_per_cell (triangulation.n_active_cells());\n    Vector<float>\n    elasticity_estimated_error_per_cell (triangulation.n_active_cells());\n\n    const QGauss<dim-1> stokes_face_quadrature(stokes_degree+2);\n    const QGauss<dim-1> elasticity_face_quadrature(elasticity_degree+2);\n\n    hp::QCollection<dim-1> face_q_collection;\n    face_q_collection.push_back (stokes_face_quadrature);\n    face_q_collection.push_back (elasticity_face_quadrature);\n\n    const FEValuesExtractors::Vector velocities(0);\n    KellyErrorEstimator<dim>::estimate (dof_handler,\n                                        face_q_collection,\n                                        typename FunctionMap<dim>::type(),\n                                        solution,\n                                        stokes_estimated_error_per_cell,\n                                        fe_collection.component_mask(velocities));\n\n    const FEValuesExtractors::Vector displacements(dim+1);\n    KellyErrorEstimator<dim>::estimate (dof_handler,\n                                        face_q_collection,\n                                        typename FunctionMap<dim>::type(),\n                                        solution,\n                                        elasticity_estimated_error_per_cell,\n                                        fe_collection.component_mask(displacements));\n\n    // We then normalize error estimates by dividing by their norm and scale\n    // the fluid error indicators by a factor of 4 as discussed in the\n    // introduction. The results are then added together into a vector that\n    // contains error indicators for all cells:\n    stokes_estimated_error_per_cell\n    *= 4. / stokes_estimated_error_per_cell.l2_norm();\n    elasticity_estimated_error_per_cell\n    *= 1. / elasticity_estimated_error_per_cell.l2_norm();\n\n    Vector<float>\n    estimated_error_per_cell (triangulation.n_active_cells());\n\n    estimated_error_per_cell += stokes_estimated_error_per_cell;\n    estimated_error_per_cell += elasticity_estimated_error_per_cell;\n\n    // The second to last part of the function, before actually refining the\n    // mesh, involves a heuristic that we have already mentioned in the\n    // introduction: because the solution is discontinuous, the\n    // KellyErrorEstimator class gets all confused about cells that sit at the\n    // boundary between subdomains: it believes that the error is large there\n    // because the jump in the gradient is large, even though this is entirely\n    // expected and a feature that is in fact present in the exact solution as\n    // well and therefore not indicative of any numerical error.\n    //\n    // Consequently, we set the error indicators to zero for all cells at the\n    // interface; the conditions determining which cells this affects are\n    // slightly awkward because we have to account for the possibility of\n    // adaptively refined meshes, meaning that the neighboring cell can be\n    // coarser than the current one, or could in fact be refined some\n    // more. The structure of these nested conditions is much the same as we\n    // encountered when assembling interface terms in\n    // <code>assemble_system</code>.\n    {\n      unsigned int cell_index = 0;\n      for (typename hp::DoFHandler<dim>::active_cell_iterator\n           cell = dof_handler.begin_active();\n           cell != dof_handler.end(); ++cell, ++cell_index)\n        for (unsigned int f=0; f<GeometryInfo<dim>::faces_per_cell; ++f)\n          if (cell_is_in_solid_domain (cell))\n            {\n              if ((cell->at_boundary(f) == false)\n                  &&\n                  (((cell->neighbor(f)->level() == cell->level())\n                    &&\n                    (cell->neighbor(f)->has_children() == false)\n                    &&\n                    cell_is_in_fluid_domain (cell->neighbor(f)))\n                   ||\n                   ((cell->neighbor(f)->level() == cell->level())\n                    &&\n                    (cell->neighbor(f)->has_children() == true)\n                    &&\n                    (cell_is_in_fluid_domain (cell->neighbor_child_on_subface\n                                              (f, 0))))\n                   ||\n                   (cell->neighbor_is_coarser(f)\n                    &&\n                    cell_is_in_fluid_domain(cell->neighbor(f)))\n                  ))\n                estimated_error_per_cell(cell_index) = 0;\n            }\n          else\n            {\n              if ((cell->at_boundary(f) == false)\n                  &&\n                  (((cell->neighbor(f)->level() == cell->level())\n                    &&\n                    (cell->neighbor(f)->has_children() == false)\n                    &&\n                    cell_is_in_solid_domain (cell->neighbor(f)))\n                   ||\n                   ((cell->neighbor(f)->level() == cell->level())\n                    &&\n                    (cell->neighbor(f)->has_children() == true)\n                    &&\n                    (cell_is_in_solid_domain (cell->neighbor_child_on_subface\n                                              (f, 0))))\n                   ||\n                   (cell->neighbor_is_coarser(f)\n                    &&\n                    cell_is_in_solid_domain(cell->neighbor(f)))\n                  ))\n                estimated_error_per_cell(cell_index) = 0;\n            }\n    }\n\n    GridRefinement::refine_and_coarsen_fixed_number (triangulation,\n                                                     estimated_error_per_cell,\n                                                     0.3, 0.0);\n    triangulation.execute_coarsening_and_refinement ();\n  }\n\n\n\n  // @sect4{<code>FluidStructureProblem::run</code>}\n\n  // This is, as usual, the function that controls the overall flow of\n  // operation. If you've read through tutorial programs step-1 through\n  // step-6, for example, then you are already quite familiar with the\n  // following structure:\n  template <int dim>\n  void FluidStructureProblem<dim>::run ()\n  {\n    make_grid ();\n\n    for (unsigned int refinement_cycle = 0; refinement_cycle<10-2*dim;\n         ++refinement_cycle)\n      {\n        std::cout << \"Refinement cycle \" << refinement_cycle << std::endl;\n\n        if (refinement_cycle > 0)\n          refine_mesh ();\n\n        setup_dofs ();\n\n        std::cout << \"   Assembling...\" << std::endl;\n        assemble_system ();\n\n        std::cout << \"   Solving...\" << std::endl;\n        solve ();\n\n        std::cout << \"   Writing output...\" << std::endl;\n        output_results (refinement_cycle);\n\n        std::cout << std::endl;\n      }\n  }\n}\n\n\n\n// @sect4{The <code>main()</code> function}\n\n// This, final, function contains pretty much exactly what most of the other\n// tutorial programs have:\nint main ()\n{\n  try\n    {\n      using namespace dealii;\n      using namespace Step46;\n\n      deallog.depth_console (0);\n\n      FluidStructureProblem<2> flow_problem(1, 1);\n      flow_problem.run ();\n    }\n  catch (std::exception &exc)\n    {\n      std::cerr << std::endl << std::endl\n                << \"----------------------------------------------------\"\n                << std::endl;\n      std::cerr << \"Exception on processing: \" << std::endl\n                << exc.what() << std::endl\n                << \"Aborting!\" << std::endl\n                << \"----------------------------------------------------\"\n                << std::endl;\n\n      return 1;\n    }\n  catch (...)\n    {\n      std::cerr << std::endl << std::endl\n                << \"----------------------------------------------------\"\n                << std::endl;\n      std::cerr << \"Unknown exception!\" << std::endl\n                << \"Aborting!\" << std::endl\n                << \"----------------------------------------------------\"\n                << std::endl;\n      return 1;\n    }\n\n  return 0;\n}\n", "meta": {"hexsha": "fc5d34574b6d1f40a048069e413589b7ed50637c", "size": 48631, "ext": "cc", "lang": "C++", "max_stars_repo_path": "MHD/examples/step-46/step-46.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-46/step-46.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-46/step-46.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": 43.0362831858, "max_line_length": 107, "alphanum_fraction": 0.5767103288, "num_tokens": 10177, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5736783928749126, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.3334810228140493}}
{"text": "#include \"map/pathfinder.h\"\n\n#include \"database/defines.h\"\n#include \"map/province.h\"\n#include \"util/container_util.h\"\n\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/astar_search.hpp>\n\nnamespace metternich {\n\nclass pathfinder::impl\n{\n\tusing cost = int;\n\tusing graph = boost::adjacency_list<boost::listS, boost::vecS, boost::undirectedS, boost::no_property, boost::property<boost::edge_weight_t, cost>>;\n\tusing vertex = graph::vertex_descriptor;\n\tusing edge = graph::edge_descriptor;\n\npublic:\n\timpl(const std::set<province *> &provinces);\n\n\tfind_trade_path_result find_trade_path(const province *start_province, const province *goal_province) const;\n\nprivate:\n\tsize_t get_province_index(const province *province) const\n\t{\n\t\treturn this->province_to_index.find(province)->second;\n\t}\n\n\tcost get_trade_cost(const edge e) const;\n\nprivate:\n\tstd::vector<province *> provinces;\n\tstd::map<const province *, size_t> province_to_index;\n\tgraph province_graph;\n};\n\ntemplate <class graph, class cost>\nclass trade_path_heuristic final : public boost::astar_heuristic<graph, cost>\n{\npublic:\n\tusing vertex = typename boost::graph_traits<graph>::vertex_descriptor;\n\n\ttrade_path_heuristic(vertex goal, const std::vector<province *> &provinces)\n\t\t: goal(goal), provinces(provinces)\n\t{}\n\n\tcost operator()(vertex v)\n\t{\n\t\treturn this->provinces[v]->get_kilometers_distance_to(this->provinces[this->goal]) * 100 / province::base_distance * defines::get()->get_trade_cost_modifier_per_distance() / 100;\n\t}\n\nprivate:\n\tvertex goal;\n\tconst std::vector<province *> &provinces;\n};\n\ntemplate <class vertex>\nclass astar_visitor final : public boost::default_astar_visitor\n{\npublic:\n\tastar_visitor(vertex goal) : goal(goal)\n\t{}\n\n\ttemplate <class graph>\n\tvoid examine_vertex(vertex v, graph &g) {\n\t\tQ_UNUSED(g)\n\n\t\tif (v == this->goal) {\n\t\t\tthrow found_goal();\n\t\t}\n\t}\n\nprivate:\n\tvertex goal;\n};\n\nstruct found_goal\n{\n};\n\npathfinder::pathfinder(const std::set<province *> &provinces)\n{\n\tthis->implementation = std::make_unique<impl>(provinces);\n}\n\npathfinder::~pathfinder()\n{\n}\n\nfind_trade_path_result pathfinder::find_trade_path(const province *start_province, const province *goal_province) const\n{\n\treturn this->implementation->find_trade_path(start_province, goal_province);\n}\n\npathfinder::impl::impl(const std::set<province *> &provinces)\n\t: provinces(container::to_vector(provinces)), province_graph(provinces.size())\n{\n\tfor (size_t i = 0; i < this->provinces.size(); ++i) {\n\t\tconst province *province = this->provinces[i];\n\t\tthis->province_to_index[province] = i;\n\t}\n\n\tfor (province *province : this->provinces) {\n\t\tfor (metternich::province *border_province : province->get_border_provinces()) {\n\t\t\tedge e;\n\t\t\tbool inserted;\n\t\t\tboost::tie(e, inserted) = boost::add_edge(this->province_to_index[province], this->province_to_index[border_province], this->province_graph);\n\t\t}\n\t}\n}\n\nfind_trade_path_result pathfinder::impl::find_trade_path(const province *start_province, const province *goal_province) const\n{\n\tvertex start = this->get_province_index(start_province);\n\tvertex goal = this->get_province_index(goal_province);\n\n\tstd::vector<vertex> vertex_predecessors(boost::num_vertices(this->province_graph));\n\tstd::vector<cost> vertex_costs(boost::num_vertices(this->province_graph));\n\n\tauto weight_function = boost::make_function_property_map<edge, cost>([this](edge e) {\n\t\treturn this->get_trade_cost(e);\n\t});\n\n\ttry {\n\t\tastar_search_tree(this->province_graph, start, trade_path_heuristic<graph, cost>(goal, this->provinces),\n\t\t\tweight_map(weight_function).\n\t\t\tpredecessor_map(make_iterator_property_map(vertex_predecessors.begin(), get(boost::vertex_index, this->province_graph))).\n\t\t\tdistance_map(make_iterator_property_map(vertex_costs.begin(), get(boost::vertex_index, this->province_graph))).\n\t\t\tvisitor(astar_visitor<vertex>(goal)));\n\t} catch (found_goal) {\n\t\tfind_trade_path_result result(true);\n\t\tfor (vertex v = goal;; v = vertex_predecessors[v]) {\n\t\t\tresult.path.push_back(this->provinces[v]);\n\t\t\tif (vertex_predecessors[v] == v) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tstd::reverse(result.path.begin(), result.path.end());\n\t\tresult.trade_cost = vertex_costs[goal];\n\t\treturn result;\n\t}\n\n\treturn find_trade_path_result(false);\n}\n\npathfinder::impl::cost pathfinder::impl::get_trade_cost(const edge e) const\n{\n\tconst province *source_province = this->provinces[e.m_source];\n\tconst province *target_province = this->provinces[e.m_target];\n\n\tint trade_cost = source_province->get_kilometers_distance_to(target_province) * 100 / province::base_distance * defines::get()->get_trade_cost_modifier_per_distance() / 100;\n\n\tif (source_province->is_water() != target_province->is_water()) {\n\t\ttrade_cost += defines::get()->get_base_port_trade_cost_modifier();\n\t}\n\n\treturn trade_cost;\n}\n\n}\n", "meta": {"hexsha": "db7eff4667592e8d2e88adfb02db890ee31a9d51", "size": 4759, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "map/pathfinder.cpp", "max_stars_repo_name": "Andrettin/Metternich", "max_stars_repo_head_hexsha": "513a7d3cddacad5d5efd2fa5faeed03bc55a190c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 12.0, "max_stars_repo_stars_event_min_datetime": "2019-08-03T05:58:12.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-20T20:46:41.000Z", "max_issues_repo_path": "map/pathfinder.cpp", "max_issues_repo_name": "Andrettin/Metternich", "max_issues_repo_head_hexsha": "513a7d3cddacad5d5efd2fa5faeed03bc55a190c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2019-08-03T11:46:49.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-22T10:20:32.000Z", "max_forks_repo_path": "map/pathfinder.cpp", "max_forks_repo_name": "Andrettin/Metternich", "max_forks_repo_head_hexsha": "513a7d3cddacad5d5efd2fa5faeed03bc55a190c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.3765432099, "max_line_length": 180, "alphanum_fraction": 0.7514183652, "num_tokens": 1153, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7549149758396752, "lm_q2_score": 0.4416730056646256, "lm_q1q2_score": 0.33342556640034754}}
{"text": "#include \"Trajectory.h\"\n#include \"promp.h\"\n#include <iostream>\n\n#include <Eigen/Core>\n#include <Eigen/SVD>\n#include <cmath>\n\n#include <random>\n\nusing namespace promp;\nint example_counter = 0;\n\ntypedef Eigen::Map<Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>> Matrix;\ntypedef Eigen::Map<Eigen::Matrix<double, 1, Eigen::Dynamic, Eigen::RowMajor>> Vector;\ntypedef Eigen::Map<const Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>> constMatrix;\ntypedef Eigen::Map<const Eigen::Matrix<double, 1, Eigen::Dynamic, Eigen::RowMajor>> constVector;\n\nstd::vector<ConditionPoint> ConditionPoint::fromMatrix(MatrixXd pointMatrix)\n{\n  std::vector<ConditionPoint> ret;\n\n  for (int i = 0; i < pointMatrix.rows(); i++)\n  {\n    ret.push_back(ConditionPoint());\n    ret.back().timestamp = pointMatrix(i, 0);\n    ret.back().dimension = pointMatrix(i, 1);\n    ret.back().derivative = pointMatrix(i, 2);\n    ret.back().mean = pointMatrix(i, 3);\n    ret.back().variance = pointMatrix(i, 4);\n  }\n\n  return ret;\n}\n\nTrajectory::Trajectory(const TrajectoryData &data) : numWeights_(data.numBF_), numDim_(data.numDim_), overlap_(data.overlap_)\n{\n  type_ = data.isStroke_ ? Stroke : Periodic;\n  weightMean_ = constVector(data.mean_.data(), data.numDim_ * data.numBF_);\n  weightCovars_ = constMatrix(data.covariance_.data(), data.numDim_ * data.numBF_, data.numDim_ * data.numBF_);\n  conditionPoints_ = ConditionPoint::fromMatrix(constMatrix(data.conditions_.data(), data.conditions_.size() / ConditionPoint::NUM_FIELDS, ConditionPoint::NUM_FIELDS));\n  setBF();\n  condition(weightMean_, weightCovars_);\n}\n\nTrajectory::Trajectory(const int numWeights, const VectorXd &weights, const double overlap, const MatrixXd &covars,\n                       const TrajectoryType type)\n    : numWeights_(numWeights), numDim_(weights.size() / numWeights), overlap_(overlap), weightMean_(weights),\n      weightCovars_(covars),\n      type_(type)\n{\n  setBF();\n}\n\nTrajectory::Trajectory(const std::vector<VectorXd> &timestamps, const std::vector<MatrixXd> &values,\n                       const double overlap, int numWeights,\n                       const int iterationLimit, const TrajectoryType type)\n    : numWeights_(numWeights), numDim_(values.front().cols()), overlap_(overlap), type_(type)\n{\n  setBF();\n  imitate(timestamps, values, iterationLimit);\n}\n\nvoid Trajectory::imitate(const std::vector<VectorXd> &timestamps, const std::vector<MatrixXd> &values, const int iterationLimit)\n{\n  weightMean_ = VectorXd::Zero(numDim_ * numWeights_);\n  weightCovars_ = MatrixXd::Identity(numDim_ * numWeights_, numDim_ * numWeights_);\n  standardDev_ = 1.;\n\n  MatrixXd means(values.size(), numDim_ * numWeights_);\n  std::vector<MatrixXd> covs(values.size(), MatrixXd::Identity(numFunc_ * numWeights_, numFunc_ * numWeights_));\n\n  std::vector<MatrixXd> H(values.size());\n  for (size_t i = 0; i < values.size(); i++)\n  {\n    MatrixXd H_partial = MatrixXd::Identity(values[i].rows(), values[i].rows());\n\n    for (int y = 0; y < values[i].rows(); y++)\n    {\n      for (int preview = 1; preview < 2 && (y + preview) < values[i].rows(); preview++)\n      {\n        H_partial(y, y + preview) = -std::pow(0.7, preview);\n      }\n    }\n\n    H[i] = (MatrixXd::Zero(values[i].size(), values[i].size()));\n    for (int j = 0; j < numDim_; j++)\n      H[i].block(H_partial.rows() * j, H_partial.rows() * j, H_partial.rows(), H_partial.rows()) = H_partial;\n  }\n\n  // value restructuring\n  std::vector<MatrixXd> val(values.size());\n\n  for (size_t i = 0; i < values.size(); i++)\n  {\n    val[i] = MatrixXd(values[i].size(), 1);\n    for (int j = 0; j < numDim_; j++)\n      val[i].block(timestamps[i].size() * j, 0, timestamps[i].size(), 1) = values[i].block(0, j, timestamps[i].size(), 1);\n  }\n\n  std::vector<MatrixXd> BF(values.size());\n\n  for (size_t i = 0; i < values.size(); i++)\n  {\n    BF[i] = basisFunctions_->getValue(timestamps[i], numDim_).transpose();\n  }\n\n  std::vector<MatrixXd> R(values.size());\n\n  for (size_t i = 0; i < values.size(); i++)\n  {\n    R[i] = H[i] * val[i];\n  }\n\n  std::vector<MatrixXd> RR(values.size());\n\n  for (size_t i = 0; i < values.size(); i++)\n  {\n    RR[i] = R[i].transpose() * R[i];\n  }\n\n  std::vector<MatrixXd> BH(values.size());\n\n  for (size_t i = 0; i < values.size(); i++)\n  {\n    BH[i] = BF[i] * H[i].transpose();\n  }\n\n  std::vector<MatrixXd> mean_eStep(values.size());\n\n  for (size_t i = 0; i < values.size(); i++)\n  {\n    mean_eStep[i] = (BH[i] * R[i]);\n  }\n\n  std::vector<MatrixXd> cov_eStep(values.size());\n\n  for (size_t i = 0; i < values.size(); i++)\n  {\n    cov_eStep[i] = (BH[i] * BH[i].transpose());\n  }\n\n  int sampleCount = 0;\n  for (size_t i = 0; i < values.size(); i++)\n  {\n    sampleCount += values[i].rows();\n  }\n\n  int counter = 0;\n  VectorXd weightMean_old;\n  MatrixXd weightCovars_old;\n  do\n  {\n    counter++;\n    weightMean_old = weightMean_;\n    weightCovars_old = weightCovars_;\n\n    for (size_t i = 0; i < values.size(); i++)\n    {\n      E_Step(1. / standardDev_ * mean_eStep[i], 1. / standardDev_ * cov_eStep[i], means.row(i), covs[i]);\n    }\n\n    M_Step(means, covs, RR, mean_eStep, cov_eStep, sampleCount);\n  } while (counter < iterationLimit && !weightMean_old.isApprox(weightMean_) && !weightCovars_old.isApprox(weightCovars_));\n}\n\nMatrixXd Trajectory::getWeightMean() const\n{\n  return weightMean_;\n};\n\nMatrixXd Trajectory::getWeightCovars() const\n{\n  return weightCovars_;\n};\n\nMatrixXd Trajectory::getValueMean(const VectorXd &time) const\n{\n  MatrixXd out(numDim_ * numFunc_, time.size());\n\n  MatrixXd bf = basisFunctions_->getValue(time);\n  MatrixXd bfd = basisFunctions_->getValueDeriv(time);\n  for (int dimension = 0; dimension < numDim_; dimension++)\n  {\n    out.row(numFunc_ * dimension) = bf * weightMean_.segment(numWeights_ * dimension, numWeights_);\n    out.row((numFunc_ * dimension) + 1) = bfd * weightMean_.segment(numWeights_ * dimension, numWeights_);\n  }\n\n  return out;\n}\n\nVectorXd Trajectory::getValueMean(const double time) const\n{\n  VectorXd timeVec(1);\n  timeVec << time;\n  return getValueMean(timeVec).col(0);\n}\n\nMatrixXd Trajectory::getValueCovars(const VectorXd &time) const\n{\n  MatrixXd out(time.size(), numDim_ * numFunc_ * numDim_ * numFunc_);\n  MatrixXd value = basisFunctions_->getValue(time);\n  MatrixXd valueDeriv = basisFunctions_->getValueDeriv(time);\n\n  for (int y = 0; y < numDim_; y++)\n  {\n    for (int x = 0; x < numDim_; x++)\n    {\n\n      out.transpose().row((numFunc_ * y * numDim_ * numFunc_) + (numFunc_ * x)) = (value *\n                                                                                   weightCovars_.block(y * numWeights_, x * numWeights_, numWeights_,\n                                                                                                       numWeights_) *\n                                                                                   value.transpose())\n                                                                                      .diagonal();\n\n      out.transpose().row((numFunc_ * y * numDim_ * numFunc_) + (numFunc_ * x) + 1) = (value *\n                                                                                       weightCovars_.block(y * numWeights_, x * numWeights_, numWeights_,\n                                                                                                           numWeights_) *\n                                                                                       valueDeriv.transpose())\n                                                                                          .diagonal();\n\n      out.transpose().row((numFunc_ * y * numDim_ * numFunc_) + (numFunc_ * x) + (numDim_ * numFunc_)) = (valueDeriv *\n                                                                                                          weightCovars_.block(y * numWeights_, x * numWeights_, numWeights_,\n                                                                                                                              numWeights_) *\n                                                                                                          value.transpose())\n                                                                                                             .diagonal();\n\n      out.transpose().row((numFunc_ * y * numDim_ * numFunc_) + (numFunc_ * x) + (numDim_ * numFunc_) + 1) = (valueDeriv *\n                                                                                                              weightCovars_.block(y * numWeights_, x * numWeights_, numWeights_,\n                                                                                                                                  numWeights_) *\n                                                                                                              valueDeriv.transpose())\n                                                                                                                 .diagonal();\n    }\n  }\n  return out;\n}\n\nVectorXd Trajectory::getValueCovars(const double time) const\n{\n  VectorXd timeVec(1);\n  timeVec << time;\n  return getValueCovars(timeVec).row(0);\n}\n\nvoid Trajectory::condition(VectorXd &weightMean, MatrixXd &weightCovars) const\n{\n  if (conditionPoints_.empty())\n    return;\n  MatrixXd basisFunc_tmp = MatrixXd::Zero(conditionPoints_.size(), numDim_ * numWeights_);\n  VectorXd means(conditionPoints_.size());\n  VectorXd variances(conditionPoints_.size());\n\n  for (unsigned i = 0; i < conditionPoints_.size(); i++)\n  {\n    const ConditionPoint &point = conditionPoints_[i];\n    if (point.derivative == 0)\n    {\n      basisFunc_tmp.block(i, numWeights_ * point.dimension, 1, numWeights_).row(0) = basisFunctions_->getValue(\n                                                                                                        point.timestamp)\n                                                                                         .row(0);\n    }\n    else\n    {\n      basisFunc_tmp.block(i, numWeights_ * point.dimension, 1, numWeights_).row(0) = basisFunctions_->getValueDeriv(point.timestamp).row(0);\n    }\n\n    means(i) = point.mean;\n    variances(i) = point.variance;\n  }\n\n  MatrixXd basisFunc = basisFunc_tmp.transpose();\n\n  MatrixXd cov = variances.asDiagonal();\n  cov = (cov + (basisFunc.transpose() * weightCovars * basisFunc)).inverse();\n\n  VectorXd weightMeanNew =\n      weightMean + weightCovars * basisFunc * cov * (means - (basisFunc.transpose() * weightMean));\n  MatrixXd weightCovarsNew =\n      weightCovars - (weightCovars * basisFunc * cov * basisFunc.transpose() * weightCovars);\n  weightMean = weightMeanNew;\n  weightCovars = weightCovarsNew;\n}\n\nvoid Trajectory::getData(TrajectoryData &data) const\n{\n  std::memcpy(data.mean_.data(), weightMean_.data(), weightMean_.size() * sizeof(double));\n  std::memcpy(data.covariance_.data(), weightCovars_.data(), weightCovars_.size() * sizeof(double));\n}\n\nTrajectory Trajectory::sampleTrajectoty(unsigned &seed) const\n{\n  std::default_random_engine generator(seed);\n  MatrixXd A = weightCovars_.selfadjointView<Lower>().llt().matrixL();\n  VectorXd z(weightMean_.size());\n\n  std::normal_distribution<double> normalDist(0, 1);\n\n  for (int i = 0; i < weightMean_.size(); i++)\n  {\n    z(i) = normalDist(generator);\n  }\n\n  VectorXd newMean = weightMean_ + (A * z);\n  MatrixXd newCovars = MatrixXd::Zero(weightMean_.size(), weightMean_.size());\n  seed = generator();\n  return Trajectory(numWeights_, newMean, overlap_, newCovars, type_);\n  ;\n}\nTrajectory Trajectory::sampleTrajectoty() const\n{\n  unsigned seed = time(0);\n  return sampleTrajectoty(seed);\n}\n\nvoid Trajectory::E_Step(const MatrixXd &mean_eStep, const MatrixXd &cov_eStep, Ref<VectorXd, 0, InnerStride<>> mean,\n                        MatrixXd &cov)\n{\n  cov = (cov_eStep + weightCovars_.inverse()).inverse();\n  mean = (cov * (mean_eStep + (weightCovars_.inverse() * weightMean_))).col(0);\n}\n\nvoid Trajectory::M_Step(const MatrixXd &mean, const std::vector<MatrixXd> &cov, const std::vector<MatrixXd> &RR,\n                        const std::vector<MatrixXd> &RH, const std::vector<MatrixXd> &HH, const int sampleCount)\n{\n\n  weightMean_ = mean.colwise().mean().row(0);\n  MatrixXd centered = mean.rowwise() - mean.colwise().mean();\n  weightCovars_ = centered.transpose() * centered;\n\n  for (int i = 0; i < mean.rows(); i++)\n  {\n    weightCovars_ += cov[i];\n  }\n\n  weightCovars_ /= mean.rows();\n\n  standardDev_ = 0;\n  for (int i = 0; i < mean.rows(); i++)\n  {\n    standardDev_ += (HH[i] * cov[i]).trace();\n    standardDev_ += RR[i](0, 0);\n    standardDev_ -= 2 * (RH[i].transpose() * mean.row(i).transpose())(0, 0);\n    standardDev_ += (mean.row(i) * HH[i] * mean.row(i).transpose())(0, 0);\n  }\n\n  standardDev_ /= mean.norm() * mean.rows() * numDim_ * sampleCount + 2; // magic number from the paper\n}\n\nvoid Trajectory::setBF()\n{\n  if (type_ == Stroke)\n  {\n    basisFunctions_ = std::shared_ptr<BasisFunctions>(new StrokeBasisFunctions(numWeights_, overlap_));\n  }\n  else\n  {\n    basisFunctions_ = std::shared_ptr<BasisFunctions>(new PeriodicBasisFunctions(numWeights_, overlap_));\n  }\n}\n", "meta": {"hexsha": "ad684dfa1c26b135dc9e5ca0ff1452af7c404fbd", "size": 13066, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/representation/promp/implementation/src/Trajectory.cpp", "max_stars_repo_name": "dettmann/bolero", "max_stars_repo_head_hexsha": "fa88be1a1d4ab1e2855d20f5429ac83ed5eb4925", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 51.0, "max_stars_repo_stars_event_min_datetime": "2017-05-19T13:33:29.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-21T10:59:57.000Z", "max_issues_repo_path": "src/representation/promp/implementation/src/Trajectory.cpp", "max_issues_repo_name": "dettmann/bolero", "max_issues_repo_head_hexsha": "fa88be1a1d4ab1e2855d20f5429ac83ed5eb4925", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 94.0, "max_issues_repo_issues_event_min_datetime": "2017-05-19T19:44:07.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-15T13:40:59.000Z", "max_forks_repo_path": "src/representation/promp/implementation/src/Trajectory.cpp", "max_forks_repo_name": "dettmann/bolero", "max_forks_repo_head_hexsha": "fa88be1a1d4ab1e2855d20f5429ac83ed5eb4925", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 31.0, "max_forks_repo_forks_event_min_datetime": "2017-05-19T19:41:39.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-25T14:14:19.000Z", "avg_line_length": 36.2944444444, "max_line_length": 176, "alphanum_fraction": 0.5739323435, "num_tokens": 3273, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.754914975839675, "lm_q2_score": 0.44167300566462553, "lm_q1q2_score": 0.33342556640034743}}
{"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_CONJ_INCLUDE\n#define MTL_CONJ_INCLUDE\n\n#include <complex>\n\n#include <boost/numeric/mtl/mtl_fwd.hpp>\n#include <boost/numeric/mtl/utility/enable_if.hpp>\n#include <boost/numeric/mtl/utility/tag.hpp>\n#include <boost/numeric/mtl/utility/category.hpp>\n#include <boost/numeric/mtl/utility/algebraic_category.hpp>\n#include <boost/numeric/mtl/utility/is_what.hpp>\n#include <boost/numeric/mtl/utility/view_code.hpp>\n#include <boost/numeric/mtl/utility/viewed_collection.hpp>\n#include <boost/numeric/mtl/utility/compose_view.hpp>\n#include <boost/numeric/linear_algebra/identity.hpp>\n#include <boost/numeric/mtl/matrix/view_ref.hpp>\n#include <boost/numeric/mtl/matrix/map_view.hpp>\n#include <boost/numeric/mtl/vector/map_view.hpp>\n\nnamespace mtl {\n\nnamespace sfunctor {\n\n    template <typename Value, typename AlgebraicCategory>\n    struct conj_aux\n    {\n\ttypedef Value result_type;\n\n\tstatic inline result_type apply(const Value& v)\n\t{\n\t    return v;\n\t}\n\n\tresult_type operator() (const Value& v) const\n\t{\n\t    return v;\n\t}\n    };\n\n\n    template <typename Value, typename AlgebraicCategory>\n    struct conj_aux<std::complex<Value>, AlgebraicCategory>\n    {\n\ttypedef std::complex<Value> result_type;\n\n\tstatic inline result_type apply(const std::complex<Value>& v)\n\t{\n\t    return std::conj(v);\n\t}\n\n\tresult_type operator() (const std::complex<Value>& v) const\n\t{\n\t    return std::conj(v);\n\t}\n    };\n\n    // Only declarations here, definitions in mat::map_view (map_view)\n    template <typename Matrix>\n    struct conj_aux<Matrix, tag::matrix>;\n\n    template <typename Vector>\n    struct conj_aux<Vector, tag::vector>;\n\n    // Short cut for result type\n    template <typename Value>\n    struct conj\n\t: public conj_aux<Value, typename mtl::traits::algebraic_category<Value>::type>\n    {};\n\n} // namespace sfunctor\n    \n    namespace vec {\n\n\t/// Conjugate of an vector\n\ttemplate <typename Vector>\n\ttypename mtl::traits::enable_if_vector<Vector, conj_view<Vector> >::type\n\tinline conj(const Vector& v)\n\t{\n\t    return conj_view<Vector>(v);\n\t}\n    } \n\n    namespace mat {\n\n\tnamespace detail {\n\n\t    template <typename Matrix>\n\t    struct conj_trait\n\t    {\n\t\tstatic const unsigned code= mtl::traits::view_toggle_conj<mtl::traits::view_code<Matrix> >::value;\n\t\ttypedef typename mtl::traits::compose_view<code, typename mtl::traits::viewed_collection<Matrix>::type>::type type;\n\t\t\n\t\tstatic inline type apply(const Matrix& A)\n\t\t{\n\t\t    return type(view_ref(A));\n\t\t}\n\t    };\n\n\t}\n\n\t/// Conjugate of a matrix\n\ttemplate <typename Matrix>\n\ttypename mtl::traits::lazy_enable_if_matrix<Matrix, detail::conj_trait<Matrix> >::type\n\tinline conj(const Matrix& A)\n\t{\n\t    return detail::conj_trait<Matrix>::apply(A);\n\t}\n    } \n\n    namespace scalar {\n\n\t// Only scalar values remain here\n\ttemplate <typename Value>\n\ttypename mtl::traits::enable_if_scalar<\n\t    Value\n\t  , typename sfunctor::conj<Value>::result_type\n\t>::type\n\tinline conj(const Value& v)\n\t{\n\t    return mtl::sfunctor::conj<Value>::apply(v);\n\t}\n\n\tfloat inline conj(float v) { return v; }\n\tdouble inline conj(double v) { return v; }\n\tlong double inline conj(long double v) { return v; }\n    }\n\n    /// Conjugate of vector, matrix, or scalar\n    using vec::conj;\n    using mat::conj; \n    using scalar::conj;\n    // using std::conj;\n\n} // namespace mtl\n\n#endif // MTL_CONJ_INCLUDE\n", "meta": {"hexsha": "88156163ee44ce776db0e0f20ad866d054bbe5bc", "size": 3761, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/numeric/mtl/operation/conj.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/conj.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/conj.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": 25.2416107383, "max_line_length": 117, "alphanum_fraction": 0.7035362935, "num_tokens": 952, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5698526368038304, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.33342143551967585}}
{"text": "// Copyright John Maddock 2006, 2007.\r\n// Copyright Paul A. Bristow 2008.\r\n\r\n// Use, modification and distribution are subject to the\r\n// Boost Software License, Version 1.0.\r\n// (See accompanying file LICENSE_1_0.txt\r\n// or copy at http://www.boost.org/LICENSE_1_0.txt)\r\n\r\n#ifndef BOOST_MATH_DISTRIBUTIONS_CHI_SQUARED_HPP\r\n#define BOOST_MATH_DISTRIBUTIONS_CHI_SQUARED_HPP\r\n\r\n#include <boost/math/distributions/fwd.hpp>\r\n#include <boost/math/special_functions/gamma.hpp> // for incomplete beta.\r\n#include <boost/math/distributions/complement.hpp> // complements\r\n#include <boost/math/distributions/detail/common_error_handling.hpp> // error checks\r\n#include <boost/math/special_functions/fpclassify.hpp>\r\n\r\n#include <utility>\r\n\r\nnamespace boost{ namespace math{\r\n\r\ntemplate <class RealType = double, class Policy = policies::policy<> >\r\nclass chi_squared_distribution\r\n{\r\npublic:\r\n   typedef RealType value_type;\r\n   typedef Policy policy_type;\r\n\r\n   chi_squared_distribution(RealType i) : m_df(i)\r\n   {\r\n      RealType result;\r\n      detail::check_df(\r\n         \"boost::math::chi_squared_distribution<%1%>::chi_squared_distribution\", m_df, &result, Policy());\r\n   } // chi_squared_distribution\r\n\r\n   RealType degrees_of_freedom()const\r\n   {\r\n      return m_df;\r\n   }\r\n\r\n   // Parameter estimation:\r\n   static RealType find_degrees_of_freedom(\r\n      RealType difference_from_variance,\r\n      RealType alpha,\r\n      RealType beta,\r\n      RealType variance,\r\n      RealType hint = 100);\r\n\r\nprivate:\r\n   //\r\n   // Data member:\r\n   //\r\n   RealType m_df;  // degrees of freedom are a real number.\r\n}; // class chi_squared_distribution\r\n\r\ntypedef chi_squared_distribution<double> chi_squared;\r\n\r\ntemplate <class RealType, class Policy>\r\ninline const std::pair<RealType, RealType> range(const chi_squared_distribution<RealType, Policy>& /*dist*/)\r\n{ // Range of permissible values for random variable x.\r\n   using boost::math::tools::max_value;\r\n   return std::pair<RealType, RealType>(0, max_value<RealType>()); // 0 to + infinity.\r\n}\r\n\r\ntemplate <class RealType, class Policy>\r\ninline const std::pair<RealType, RealType> support(const chi_squared_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   return std::pair<RealType, RealType>(0, tools::max_value<RealType>()); // 0 to + infinity.\r\n}\r\n\r\ntemplate <class RealType, class Policy>\r\nRealType pdf(const chi_squared_distribution<RealType, Policy>& dist, const RealType& chi_square)\r\n{\r\n   BOOST_MATH_STD_USING  // for ADL of std functions\r\n   RealType degrees_of_freedom = dist.degrees_of_freedom();\r\n   // Error check:\r\n   RealType error_result;\r\n\r\n   static const char* function = \"boost::math::pdf(const chi_squared_distribution<%1%>&, %1%)\";\r\n\r\n   if(false == detail::check_df(\r\n         function, degrees_of_freedom, &error_result, Policy()))\r\n      return error_result;\r\n\r\n   if((chi_square < 0) || !(boost::math::isfinite)(chi_square))\r\n   {\r\n      return policies::raise_domain_error<RealType>(\r\n         function, \"Chi Square parameter was %1%, but must be > 0 !\", chi_square, Policy());\r\n   }\r\n\r\n   if(chi_square == 0)\r\n   {\r\n      // Handle special cases:\r\n      if(degrees_of_freedom < 2)\r\n      {\r\n         return policies::raise_overflow_error<RealType>(\r\n            function, 0, Policy());\r\n      }\r\n      else if(degrees_of_freedom == 2)\r\n      {\r\n         return 0.5f;\r\n      }\r\n      else\r\n      {\r\n         return 0;\r\n      }\r\n   }\r\n\r\n   return gamma_p_derivative(degrees_of_freedom / 2, chi_square / 2, Policy()) / 2;\r\n} // pdf\r\n\r\ntemplate <class RealType, class Policy>\r\ninline RealType cdf(const chi_squared_distribution<RealType, Policy>& dist, const RealType& chi_square)\r\n{\r\n   RealType degrees_of_freedom = dist.degrees_of_freedom();\r\n   // Error check:\r\n   RealType error_result;\r\n   static const char* function = \"boost::math::cdf(const chi_squared_distribution<%1%>&, %1%)\";\r\n\r\n   if(false == detail::check_df(\r\n         function, degrees_of_freedom, &error_result, Policy()))\r\n      return error_result;\r\n\r\n   if((chi_square < 0) || !(boost::math::isfinite)(chi_square))\r\n   {\r\n      return policies::raise_domain_error<RealType>(\r\n         function, \"Chi Square parameter was %1%, but must be > 0 !\", chi_square, Policy());\r\n   }\r\n\r\n   return boost::math::gamma_p(degrees_of_freedom / 2, chi_square / 2, Policy());\r\n} // cdf\r\n\r\ntemplate <class RealType, class Policy>\r\ninline RealType quantile(const chi_squared_distribution<RealType, Policy>& dist, const RealType& p)\r\n{\r\n   RealType degrees_of_freedom = dist.degrees_of_freedom();\r\n   static const char* function = \"boost::math::quantile(const chi_squared_distribution<%1%>&, %1%)\";\r\n   // Error check:\r\n   RealType error_result;\r\n   if(false == detail::check_df(\r\n         function, degrees_of_freedom, &error_result, Policy())\r\n         && detail::check_probability(\r\n            function, p, &error_result, Policy()))\r\n      return error_result;\r\n\r\n   return 2 * boost::math::gamma_p_inv(degrees_of_freedom / 2, p, Policy());\r\n} // quantile\r\n\r\ntemplate <class RealType, class Policy>\r\ninline RealType cdf(const complemented2_type<chi_squared_distribution<RealType, Policy>, RealType>& c)\r\n{\r\n   RealType const& degrees_of_freedom = c.dist.degrees_of_freedom();\r\n   RealType const& chi_square = c.param;\r\n   static const char* function = \"boost::math::cdf(const chi_squared_distribution<%1%>&, %1%)\";\r\n   // Error check:\r\n   RealType error_result;\r\n   if(false == detail::check_df(\r\n         function, degrees_of_freedom, &error_result, Policy()))\r\n      return error_result;\r\n\r\n   if((chi_square < 0) || !(boost::math::isfinite)(chi_square))\r\n   {\r\n      return policies::raise_domain_error<RealType>(\r\n         function, \"Chi Square parameter was %1%, but must be > 0 !\", chi_square, Policy());\r\n   }\r\n\r\n   return boost::math::gamma_q(degrees_of_freedom / 2, chi_square / 2, Policy());\r\n}\r\n\r\ntemplate <class RealType, class Policy>\r\ninline RealType quantile(const complemented2_type<chi_squared_distribution<RealType, Policy>, RealType>& c)\r\n{\r\n   RealType const& degrees_of_freedom = c.dist.degrees_of_freedom();\r\n   RealType const& q = c.param;\r\n   static const char* function = \"boost::math::quantile(const chi_squared_distribution<%1%>&, %1%)\";\r\n   // Error check:\r\n   RealType error_result;\r\n   if(false == detail::check_df(\r\n         function, degrees_of_freedom, &error_result, Policy())\r\n         && detail::check_probability(\r\n            function, q, &error_result, Policy()))\r\n      return error_result;\r\n\r\n   return 2 * boost::math::gamma_q_inv(degrees_of_freedom / 2, q, Policy());\r\n}\r\n\r\ntemplate <class RealType, class Policy>\r\ninline RealType mean(const chi_squared_distribution<RealType, Policy>& dist)\r\n{ // Mean of Chi-Squared distribution = v.\r\n  return dist.degrees_of_freedom();\r\n} // mean\r\n\r\ntemplate <class RealType, class Policy>\r\ninline RealType variance(const chi_squared_distribution<RealType, Policy>& dist)\r\n{ // Variance of Chi-Squared distribution = 2v.\r\n  return 2 * dist.degrees_of_freedom();\r\n} // variance\r\n\r\ntemplate <class RealType, class Policy>\r\ninline RealType mode(const chi_squared_distribution<RealType, Policy>& dist)\r\n{\r\n   RealType df = dist.degrees_of_freedom();\r\n   static const char* function = \"boost::math::mode(const chi_squared_distribution<%1%>&)\";\r\n   // Most sources only define mode for df >= 2,\r\n   // but for 0 <= df <= 2, the pdf maximum actually occurs at random variate = 0;\r\n   // So one could extend the definition of mode thus:\r\n   //if(df < 0)\r\n   //{\r\n   //   return policies::raise_domain_error<RealType>(\r\n   //      function,\r\n   //      \"Chi-Squared distribution only has a mode for degrees of freedom >= 0, but got degrees of freedom = %1%.\",\r\n   //      df, Policy());\r\n   //}\r\n   //return (df <= 2) ? 0 : df - 2;\r\n\r\n   if(df < 2)\r\n      return policies::raise_domain_error<RealType>(\r\n         function,\r\n         \"Chi-Squared distribution only has a mode for degrees of freedom >= 2, but got degrees of freedom = %1%.\",\r\n         df, Policy());\r\n   return df - 2;\r\n}\r\n\r\n//template <class RealType, class Policy>\r\n//inline RealType median(const chi_squared_distribution<RealType, Policy>& dist)\r\n//{ // Median is given by Quantile[dist, 1/2]\r\n//   RealType df = dist.degrees_of_freedom();\r\n//   if(df <= 1)\r\n//      return tools::domain_error<RealType>(\r\n//         BOOST_CURRENT_FUNCTION,\r\n//         \"The Chi-Squared distribution only has a mode for degrees of freedom >= 2, but got degrees of freedom = %1%.\",\r\n//         df);\r\n//   return df - RealType(2)/3;\r\n//}\r\n// Now implemented via quantile(half) in derived accessors.\r\n\r\ntemplate <class RealType, class Policy>\r\ninline RealType skewness(const chi_squared_distribution<RealType, Policy>& dist)\r\n{\r\n   BOOST_MATH_STD_USING // For ADL\r\n   RealType df = dist.degrees_of_freedom();\r\n   return sqrt (8 / df);  // == 2 * sqrt(2 / df);\r\n}\r\n\r\ntemplate <class RealType, class Policy>\r\ninline RealType kurtosis(const chi_squared_distribution<RealType, Policy>& dist)\r\n{\r\n   RealType df = dist.degrees_of_freedom();\r\n   return 3 + 12 / df;\r\n}\r\n\r\ntemplate <class RealType, class Policy>\r\ninline RealType kurtosis_excess(const chi_squared_distribution<RealType, Policy>& dist)\r\n{\r\n   RealType df = dist.degrees_of_freedom();\r\n   return 12 / df;\r\n}\r\n\r\n//\r\n// Parameter estimation comes last:\r\n//\r\nnamespace detail\r\n{\r\n\r\ntemplate <class RealType, class Policy>\r\nstruct df_estimator\r\n{\r\n   df_estimator(RealType a, RealType b, RealType variance, RealType delta)\r\n      : alpha(a), beta(b), ratio(delta/variance) {}\r\n\r\n   RealType operator()(const RealType& df)\r\n   {\r\n      if(df <= tools::min_value<RealType>())\r\n         return 1;\r\n      chi_squared_distribution<RealType, Policy> cs(df);\r\n\r\n      RealType result;\r\n      if(ratio > 0)\r\n      {\r\n         RealType r = 1 + ratio;\r\n         result = cdf(cs, quantile(complement(cs, alpha)) / r) - beta;\r\n      }\r\n      else\r\n      {\r\n         RealType r = 1 + ratio;\r\n         result = cdf(complement(cs, quantile(cs, alpha) / r)) - beta;\r\n      }\r\n      return result;\r\n   }\r\nprivate:\r\n   RealType alpha, beta, ratio;\r\n};\r\n\r\n} // namespace detail\r\n\r\ntemplate <class RealType, class Policy>\r\nRealType chi_squared_distribution<RealType, Policy>::find_degrees_of_freedom(\r\n   RealType difference_from_variance,\r\n   RealType alpha,\r\n   RealType beta,\r\n   RealType variance,\r\n   RealType hint)\r\n{\r\n   static const char* function = \"boost::math::chi_squared_distribution<%1%>::find_degrees_of_freedom(%1%,%1%,%1%,%1%,%1%)\";\r\n   // Check for domain errors:\r\n   RealType error_result;\r\n   if(false == detail::check_probability(\r\n         function, alpha, &error_result, Policy())\r\n         && detail::check_probability(function, beta, &error_result, Policy()))\r\n      return error_result;\r\n\r\n   if(hint <= 0)\r\n      hint = 1;\r\n\r\n   detail::df_estimator<RealType, Policy> f(alpha, beta, variance, difference_from_variance);\r\n   tools::eps_tolerance<RealType> tol(policies::digits<RealType, Policy>());\r\n   boost::uintmax_t max_iter = policies::get_max_root_iterations<Policy>();\r\n   std::pair<RealType, RealType> r = tools::bracket_and_solve_root(f, hint, RealType(2), false, tol, max_iter, Policy());\r\n   RealType result = r.first + (r.second - r.first) / 2;\r\n   if(max_iter >= policies::get_max_root_iterations<Policy>())\r\n   {\r\n      policies::raise_evaluation_error<RealType>(function, \"Unable to locate solution in a reasonable time:\"\r\n         \" either there is no answer to how many degrees of freedom are required\"\r\n         \" or the answer is infinite.  Current best guess is %1%\", result, Policy());\r\n   }\r\n   return result;\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_MATH_DISTRIBUTIONS_CHI_SQUARED_HPP\r\n", "meta": {"hexsha": "4334065361712a1d0d4662afac0bac5793f2eda4", "size": 12006, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Compiler/boost/boost/math/distributions/chi_squared.hpp", "max_stars_repo_name": "davidov541/MiniC", "max_stars_repo_head_hexsha": "d3b16a1568b97a4d801880b110a8be04fe848adb", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2015-12-29T07:21:01.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-29T10:47:38.000Z", "max_issues_repo_path": "LibsExternes/Includes/boost/math/distributions/chi_squared.hpp", "max_issues_repo_name": "benkaraban/anima-games-engine", "max_issues_repo_head_hexsha": "8aa7a5368933f1b82c90f24814f1447119346c3b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "LibsExternes/Includes/boost/math/distributions/chi_squared.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": 35.4159292035, "max_line_length": 125, "alphanum_fraction": 0.6724137931, "num_tokens": 2946, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.588889130767832, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.3333221631901137}}
{"text": "﻿//=======================================================================\n// Copyright 2015 by Ireneusz Szcześniak\n// Authors: Ireneusz Szcześniak <www.irkos.org>\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// This is the implementation of the Yen algorithm:\n//\n// Jin Y. Yen, Finding the k shortest loopless paths in a network,\n// Management Science, vol. 17, no. 11, July 1971, pages 712-716\n//\n// But actually, I found the following explanation better:\n//\n// https://en.wikipedia.org/wiki/Yen%27s_algorithm\n//=======================================================================\n\n#ifndef BOOST_GRAPH_YEN_KSP\n#define BOOST_GRAPH_YEN_KSP\n\n#include <list>\n#include <set>\n#include <map>\n\n#include <boost/graph/dijkstra_shortest_paths.hpp>\n#include <boost/graph/filtered_graph.hpp>\n#include <boost/optional.hpp>\n#include <boost/range/adaptor/reversed.hpp>\n#include <boost/utility/value_init.hpp>\n\n#include \"custom_dijkstra_call.hpp\"\n#include \"exclude_filter.hpp\"\n\nnamespace boost {\n\n  template <typename Graph, typename WeightMap, typename IndexMap>\n  std::list<std::pair<typename WeightMap::value_type,\n                      std::list<typename Graph::edge_descriptor>>>\n  yen_ksp(const Graph& g,\n          typename Graph::vertex_descriptor s,\n          typename Graph::vertex_descriptor t,\n          WeightMap wm, IndexMap im, optional<unsigned> K)\n  {\n    typedef typename Graph::vertex_descriptor vertex_descriptor;\n    typedef typename Graph::edge_descriptor edge_descriptor;\n    typedef typename WeightMap::value_type weight_type;\n    typedef exclude_filter<vertex_descriptor> evf_type;\n    typedef exclude_filter<edge_descriptor> eef_type;\n    typedef std::list<edge_descriptor> path_type;\n    typedef std::pair<weight_type, path_type> kr_type;\n\n    // The results.\n    std::list<kr_type> A;\n    // The tentative results.\n    std::multimap<weight_type, path_type> C;\n\n    // The set of excluded edges.\n    std::set<edge_descriptor> exe;\n    // The set of excluded vertexes.\n    std::set<vertex_descriptor> exv;\n\n    // The filter which excludes edges.\n    eef_type ef(&exe);\n    // The filter which excludes vertexes.\n    evf_type vf(&exv);\n\n    // The filtered graph type.\n    typedef boost::filtered_graph<Graph, eef_type, evf_type> fg_type;\n\n    // The filtered graph.\n    fg_type fg(g, ef, vf);\n\n    optional<kr_type> okr = custom_dijkstra_call(g, s, t, wm, im);\n\n    if (okr)\n      {\n        A.push_back(okr.get());\n\n        for (int k = 1; !K || k < K.get(); ++k)\n          {\n            // The previous shortest result.\n            const kr_type &psr = A.back();\n            const path_type &psp = psr.second;\n\n            // Iterate over the edges of the previous shortest path.\n            for(auto i = psp.begin(); i != psp.end(); ++i)\n              {\n                // The spur vertex.\n                vertex_descriptor sv = source(*i, g);\n                // The root path.\n                path_type rp = path_type(psp.begin(), i);\n\n                // Iterate over the previous shortest paths.\n                for(const auto &kr: A)\n                  {\n                    const path_type &kp = kr.second;\n                    typename path_type::const_iterator i1, i2;\n\n                    // Iterate as long as possible, and as long as\n                    // paths are equal.\n                    for(tie(i1, i2) = std::make_pair(kp.begin(), rp.begin());\n                        i1 != kp.end() && i2 != rp.end() && *i1 == *i2;\n                        ++i1, ++i2);\n\n                    // Make sure we didn't reach the end of kp.  If we\n                    // did, there is no next edge in kp, which we\n                    // could exclude.  Also, make sure we reached the\n                    // end of rp, i.e., the kp begins with rp.\n                    if (i1 != kp.end() && i2 == rp.end())\n                      exe.insert(*i1);\n                  }\n\n                // Remove the vertexes that belong to the root path,\n                // except the last vertex, i.e., the spur node.\n                for (const auto &e: rp)\n                  exv.insert(source(e, g));\n\n                // Optional spur result.\n                optional<kr_type> osr = custom_dijkstra_call(fg, sv, t, wm, im);\n\n                if (osr)\n                  {\n                    // The tentative result.\n                    kr_type tr = osr.get();\n                    for(const auto &e: boost::adaptors::reverse(rp))\n                      {\n                        tr.second.push_front(e);\n                        tr.first += get(wm, e);\n                      }\n                    C.insert(tr);\n                  }\n\n                // Clear the excluded edges and vertexes.\n                exe.clear();\n                exv.clear();\n              }\n\n            // Stop searching when there are no tentative paths.\n            if (C.empty())\n              break;\n\n            // Take the shortest tentative path and make it the next\n            // shortest path.\n            A.push_back(*C.begin());\n            C.erase(C.begin());\n          }\n      }\n\t\n    return A;\n  }\n\n  template <typename Graph>\n  std::list<std::pair<typename property_map<Graph, edge_weight_t>::value_type,\n                      std::list<typename Graph::edge_descriptor>>>\n  yen_ksp(Graph& g,\n          typename Graph::vertex_descriptor s,\n          typename Graph::vertex_descriptor t,\n          optional<unsigned> K = optional<unsigned>())\n  {\n    return yen_ksp(g, s, t, get(edge_weight_t(), g),\n                   get(vertex_index_t(), g), K);\n  }\n\n} // boost\n\n#endif /* BOOST_GRAPH_YEN_KSP */\n", "meta": {"hexsha": "8a8e4c34610a501b41147aa0bf443ebeac014800", "size": 5835, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "yen_ksp.hpp", "max_stars_repo_name": "pride829/OpticalPizza", "max_stars_repo_head_hexsha": "e82d7845a7d6fc8d64e686ed02158a2dd100a80e", "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": "yen_ksp.hpp", "max_issues_repo_name": "pride829/OpticalPizza", "max_issues_repo_head_hexsha": "e82d7845a7d6fc8d64e686ed02158a2dd100a80e", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "yen_ksp.hpp", "max_forks_repo_name": "pride829/OpticalPizza", "max_forks_repo_head_hexsha": "e82d7845a7d6fc8d64e686ed02158a2dd100a80e", "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.3235294118, "max_line_length": 80, "alphanum_fraction": 0.5307626392, "num_tokens": 1273, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5888891163376235, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.33332215502234824}}
{"text": "// Copyright (C) by Josh Blum. See LICENSE.txt for licensing information.\n\n#include <gras/time_tag.hpp>\n#include <PMC/Containers.hpp>\n#include <boost/cstdint.hpp> //uint64\n#include <boost/math/special_functions/round.hpp>\n\n#define TIME_TAG_TPS time_ticks_t(1000000000UL)\n\nusing namespace gras;\n\nstatic TimeTag &normalize(TimeTag &t)\n{\n    int num = int(t._ticks/TIME_TAG_TPS);\n    if (num < 0) num--; //stops negative ticks\n    t._fsecs += num;\n    t._ticks -= num*TIME_TAG_TPS;\n    return t;\n}\n\nTimeTag::TimeTag(void):\n    _fsecs(0), _ticks(0)\n{/*NOP*/}\n\nTimeTag TimeTag::from_ticks(const time_ticks_t ticks)\n{\n    TimeTag t;\n    t._ticks = ticks;\n    return normalize(t);\n}\n\nTimeTag TimeTag::from_ticks(const time_ticks_t ticks, const double rate)\n{\n    TimeTag t;\n    t._fsecs = time_ticks_t(ticks/rate);\n    const double error = ticks - (t._fsecs*rate);\n    t._ticks = boost::math::llround((error*TIME_TAG_TPS)/rate);\n    return normalize(t);\n}\n\nTimeTag TimeTag::from_pmc(const PMCC &p)\n{\n    TimeTag t;\n    const PMCTuple<2> &tuple = p.as<PMCTuple<2> >();\n    t._fsecs = tuple[0].as<boost::uint64_t>();\n    t._ticks = boost::math::llround(tuple[1].as<double>()*TIME_TAG_TPS);\n    return normalize(t);\n}\n\ntime_ticks_t TimeTag::to_ticks(void) const\n{\n    return _fsecs*TIME_TAG_TPS + _ticks;\n}\n\ntime_ticks_t TimeTag::to_ticks(const double rate) const\n{\n    const time_ticks_t full = time_ticks_t(_fsecs*rate);\n    const double error = _fsecs - (full/rate);\n    return full + boost::math::llround(_ticks*rate/TIME_TAG_TPS + error*rate);\n}\n\nPMCC TimeTag::to_pmc(void) const\n{\n    PMCTuple<2> tuple;\n    tuple[0] = PMC_M<boost::uint64_t>(_fsecs);\n    tuple[1] = PMC_M<double>(_ticks/double(TIME_TAG_TPS));\n    return PMC_M(tuple);\n}\n\nTimeTag &TimeTag::operator+=(const TimeTag &rhs)\n{\n    _fsecs += rhs._fsecs;\n    _ticks += rhs._ticks;\n    return normalize(*this);\n}\n\nTimeTag &TimeTag::operator-=(const TimeTag &rhs)\n{\n    _fsecs -= rhs._fsecs;\n    _ticks -= rhs._ticks;\n    return normalize(*this);\n}\n\nbool gras::operator<(const TimeTag &lhs, const TimeTag &rhs)\n{\n    if (lhs._fsecs == rhs._fsecs) return lhs._ticks < rhs._ticks;\n    return lhs._fsecs < rhs._fsecs;\n}\n\nbool gras::operator==(const TimeTag &lhs, const TimeTag &rhs)\n{\n    return (lhs._fsecs == rhs._fsecs) and (lhs._ticks == rhs._ticks);\n}\n", "meta": {"hexsha": "b80e94442d28c5d3166cd43607f58aab8861a5b7", "size": 2308, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lib/time_tag.cpp", "max_stars_repo_name": "guruofquality/gras", "max_stars_repo_head_hexsha": "a93956bfc9884f9a1c53a16e12cd7e7cd86584c4", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 9.0, "max_stars_repo_stars_event_min_datetime": "2015-07-24T15:10:14.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-08T13:18:20.000Z", "max_issues_repo_path": "lib/time_tag.cpp", "max_issues_repo_name": "guruofquality/gras", "max_issues_repo_head_hexsha": "a93956bfc9884f9a1c53a16e12cd7e7cd86584c4", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2015-02-02T01:57:26.000Z", "max_issues_repo_issues_event_max_datetime": "2018-07-20T04:52:09.000Z", "max_forks_repo_path": "lib/time_tag.cpp", "max_forks_repo_name": "guruofquality/gras", "max_forks_repo_head_hexsha": "a93956bfc9884f9a1c53a16e12cd7e7cd86584c4", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2015-01-12T23:12:49.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-23T18:10:58.000Z", "avg_line_length": 24.5531914894, "max_line_length": 78, "alphanum_fraction": 0.6806759099, "num_tokens": 700, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6513548782017745, "lm_q2_score": 0.5117166047041654, "lm_q1q2_score": 0.33330910673090725}}
{"text": "#include <clpoly/clpoly.hh>\n#include <boost/container_hash/hash.hpp>\n#include <iostream>\n#include <fstream>\n#include <string>\n#include <time.h>\nclpoly::polynomial_ZZ read_file(std::string s)\n{\n    long numn,numv;\n    std::ifstream fin(s);\n    if (!fin)\n    {\n        // std::cout<<\"无法读取文件!\\n\";\n        throw \"无法读取文件!\";\n    }\n    fin>>numn>>numv;\n    std::vector<clpoly::variable> var;\n    var.reserve(numv);\n    for (char i='a';i<'a'+numv;var.push_back(std::string(1,i)),++i);\n    std::vector<std::pair<clpoly::variable,int64_t>> m;\n    std::vector<std::pair<clpoly::monomial,clpoly::ZZ>> p;\n    p.reserve(numn);\n    long tmp;\n    for (long i=0;i<numn;++i)\n    {\n        m.reserve(numv);\n        for (auto &j:var)\n        {\n            fin>>tmp;\n            if (tmp!=0)\n                m.push_back(std::pair<clpoly::variable,int64_t>(j,tmp));\n        }\n        fin>>tmp;\n        if (tmp!=0)\n            p.push_back(std::pair<clpoly::monomial,clpoly::ZZ>(std::move(m),clpoly::ZZ(tmp)));\n    }\n    fin.close();\n    return clpoly::polynomial_ZZ(p);\n}\nint main(){\n    clpoly::variable x(\"x\");\n    clpoly::variable y(\"y\");\n    clpoly::variable z(\"z\");\n    clpoly::variable d(\"d\");\n    clpoly::variable r(\"r\");\n    clpoly::variable x1(\"x1\"),x2(\"x2\"),x3(\"x3\");\n    clpoly::variable x7(\"x7\"),x8(\"x8\");\n    clpoly::polynomial_ZZ p={{{{x,1}},1}};\n    clpoly::lex_<clpoly::custom_var_order> mo;\n    mo=clpoly::lex_<clpoly::custom_var_order>(clpoly::custom_var_order({x8,x7,x1}));\n    clpoly::polynomial_<clpoly::ZZ,clpoly::lex_<clpoly::custom_var_order>> p_1(&mo);\n    std::cout<<\"p=\"<< p<<std::endl;\n    p=1;\n    p=2*(2-x1)*x8+x7-2;\n    std::cout<<\"p=\"<< p<<std::endl;\n    p_1=p;\n    std::cout<<\"p_1=\"<< p_1<<std::endl;\n    \n    clpoly::monomial m=pow(x,3);\n    p=z*z;\n    time_t t;\n    std::cout<< p<<std::endl;\n    \n    std::cout<< 2*x*x*y+1<<std::endl;\n    // auto l=p.variables();\n    // for (auto &i:l)\n    //     std::cout<<i.first<<\":\"<<i.second<<\" \";\n    // std::cout<<std::endl;\n    // clpoly::univariate_priority_order comp_z(z);\n    // clpoly::polynomial_<clpoly::ZZ,clpoly::univariate_priority_order> p2(&comp_z);\n    // clpoly::poly_convert(std::move(p),p2);\n    // std::cout<<p2<<std::endl;\n    // l=p2.variables();\n    // for (auto &i:l)\n    //     std::cout<<i.first<<\":\"<<i.second<<\" \";\n    // std::cout<<std::endl;\n    //clpoly::__is_monomial_compression=true;\n    // std::cout<<pow(p2,2)<<std::endl;\n    // std::cout<<\"4*pow(x,4)*pow(y,2)*pow(z,4)+4*pow(x,2)*pow(y,2)*d^3*pow(z,4)+pow(y,2)*d^6*pow(z,4)+4*pow(x,2)*y*pow(z,2)+2*y*d^3*pow(z,2)+1\\n\";\n    // std::cout<< p<<std::endl;\n    clpoly::polynomial_ZZ f=x*pow(y,2);\n    clpoly::polynomial_ZZ g=2*pow(y,3)-pow(y,2)+pow(x,2)*y;\n    \n    f=2*(2-7*x1+pow(x1,2)*x2)-(x3-x1);\n    std::cout<<\"f:=\"<<f<<\":\"<<std::endl;\n    f=-pow(x,2)*pow(z,3) - pow(x,4) - pow(z,4) + pow(x,2) + 2*pow(z,2) - 1;\n    g=-pow(r,2)*pow(x,2) + pow(x,4) + pow(x,2)*pow(z,2) + pow(z,4) +x- 2*pow(z,2) + 1;\n    // clpoly::polynomial_ZZ f=clpoly::random_polynomial<clpoly::ZZ>({x,y,z,d},10,0.2,10,-10);\n    // clpoly::polynomial_ZZ g=clpoly::random_polynomial<clpoly::ZZ>({x,y,z,d},10,0.2,10,-10);\n    clpoly::polynomial_ZZ o;\n     clpoly::polynomial_ZZ o1;\n    std::cout<<\"f:=\"<<f<<\":\"<<std::endl;\n    std::cout<<\"g:=\"<<g<<\":\"<<std::endl;\n    std::cout<<clpoly::coeff(g,z)<<std::endl;\n    // std::cout<<\"o:=\"<<clpoly::prem(g,f,y)<<\":\"<<std::endl;\n    // std::cout<<\"t:=\"<<(double(clock()-t)/CLOCKS_PER_SEC)<<\";\"<<std::endl;\n    // std::cout<<\"st := time():o1:= expand(prem(g, f, y)):time() - st;o1-o;\"<<std::endl;\n    \n \n\n    // std::cout<<\"t=Association[];t2=Association[];\\n\";\n\n\n    // clpoly::polynomial_ZZ p=clpoly::random_polynomial<clpoly::ZZ>({x,y,z,d},5,0.05,10,-10);\n    // std::cout<<\"p=\"<<p<<std::endl;\n    // auto l=p.variables();\n    // for (auto &i:l)\n    //     std::cout<<i.first<<\":\"<<i.second<<\" \";\n    // std::cout<<std::endl<<p.degree()<<std::endl;\n    t=clock();\n    clpoly::polynomial_ZZ PP;\n    try\n    {   \n        PP=read_file(\"j621_data.txt\");\n    }\n    catch(const char* msg)\n    {\n        std::cout<<msg<<std::endl;\n        return 1;\n    }\n    std::cout<<PP.size()<<std::endl;\n    std::cout<<\"( \"<<double(clock()-t)/CLOCKS_PER_SEC<<\"s)\\n\";\n    t=clock();\n    auto ll=PP.variables();\n    for (auto &i:ll)\n        std::cout<<i.first<<\":\"<<i.second<<\" \";\n    std::cout<<std::endl;\n    std::cout<<\"(\"<<double(clock()-t)/CLOCKS_PER_SEC<<\"s)\\n\";\n     t=clock();\n    std::cout<<std::hash<clpoly::polynomial_ZZ>()(PP)<<std::endl;\n    std::cout<<\"(\"<<double(clock()-t)/CLOCKS_PER_SEC<<\"s)\\n\";\n    // t=clock();\n    // std::cout<<PP.degree()<<std::endl;\n    // std::cout<<\"(\"<<double(clock()-t)/CLOCKS_PER_SEC<<\"s)\\n\";\n\n    // clpoly::Zp a(10,7);\n    // clpoly::Zp b(-10,7);\n    // a=-2;\n    // std::cout<<a<<\" \"<<b<<\" \"<<a*b<<\" \"<<a/b<<\" \"<<-a<<std::endl;\n\n    // g=-pow(r,2)*pow(x,2) + pow(x,4) + pow(x,2)*pow(z,2) + pow(z,4) - 2*pow(z,2) + 1;\n    // std::cout<<g<<std::endl;\n    // std::cout<<clpoly::polynomial_mod(std::move(g),7)<<std::endl;\n    // a=std::move(b);\n    // std::cout<<a<<b<<std::endl;\n    // f=pow(x,4)+25*pow(x,3)+145*pow(x,2)-171*x-360;\n    // g=pow(x,5)+14*pow(x,4)+15*pow(x,3)-pow(x,2)-14*x-15;\n    // f=2*pow(x,4)-7*pow(x,3)-4*pow(x,2)-4*x-15;\n    // g=4*pow(x,5)+4*pow(x,3)-7*pow(x,2)-2*pow(x,4)+x-12;\n    \n    // f=9*pow(x,5)+2*pow(x,4)*y*z-189*pow(x,3)*pow(y,3)*z+117*pow(x,3)*y*pow(z,2)+3*pow(x,3)-42*pow(x,2)*pow(y,4)*pow(z,2)\n    //                 +26*pow(x,2)*pow(y,2)*pow(z,3)+18*pow(x,2)-63*x*pow(y,3)*z+39*x*y*pow(z,2)+4*x*y*z+6;\n    // g=6*pow(x,6)-126*pow(x,4)*pow(y,3)*z+78*pow(x,4)*y*pow(z,2)+pow(x,4)*y+pow(x,4)*z+13*pow(x,3)\n    //     -21*pow(x,2)*pow(y,4)*z-21*pow(x,2)*pow(y,3)*pow(z,2)+13*pow(x,2)*pow(y,2)*pow(z,2)+13*pow(x,2)*y*pow(z,3)\n    //     -21*x*pow(y,3)*z+13*x*y*pow(z,2)+2*x*y+2*x*z+2;\n    // g=-3*pow(y,8)*pow(d,2)-2*pow(y,5)*pow(d,5)-2*pow(d,10)+5*pow(y,8)*d+3*pow(y,5)*pow(d,4)\n    //     -7*pow(y,4)*pow(d,5)+5*pow(y,3)*pow(d,6)+10*pow(d,6)+pow(d,5)+3*pow(y,3)+4;\n    // f=-9*pow(x,8)*pow(z,2)+6*pow(x,5)*pow(z,5)+2*pow(x,4)*pow(z,6)+9*pow(x,2)*z-9;\n    // g=-7*pow(x,8)*pow(z,2)+2*pow(x,6)*y*pow(z,3)-3*pow(x,5)*pow(y,3)*pow(z,2)+pow(x,5)*y*pow(z,4)+10*pow(x,5)*pow(z,5)-9*pow(x,4)*pow(y,3)*pow(z,3)-pow(x,2)*pow(y,5)*pow(z,3)-6*pow(x,2)*y*pow(z,7)\n    //   -2*x*pow(z,9)+2*pow(x,5)*pow(y,4)-8*pow(x,2)*pow(y,3)*pow(z,4)-pow(x,2)*pow(z,7)-4*x*pow(y,5)*pow(z,2)+3*x*pow(y,4)*pow(z,2)-2*x*pow(y,2)*pow(z,4)-7*pow(x,5)*z+7*pow(x,3)*pow(y,3)-2*x*pow(y,2)*pow(z,3)+6*y*pow(z,5)+9*pow(x,2)*pow(y,3)-8*x*pow(z,4)+9*pow(x,3)*z+2*pow(x,2)*pow(z,2)+5;\n    // f=-7*pow(x,6)*y*pow(z,3)-8*pow(x,4)*pow(y,5)*z+10*pow(x,3)*pow(y,5)*pow(z,2)-3*pow(x,2)*pow(y,3)*pow(z,5)+pow(x,2)*pow(y,2)*pow(z,6)-2*x*y*pow(z,8)+10*pow(y,5)*pow(z,5)+pow(x,6)*y*pow(z,2)\n    //    +8*pow(x,5)*pow(y,4)-9*pow(y,7)*pow(z,2)+pow(y,5)*pow(z,4)-pow(x,5)*y*pow(z,2)+10*pow(x,4)*pow(z,4)-5*pow(x,2)*pow(y,6)-3*x*pow(y,5)*pow(z,2)-6*pow(x,2)*pow(y,3)*pow(z,2)-x*pow(y,6)-5*pow(y,5)*pow(z,2)\n    //   -9*pow(z,7)+2*pow(x,4)*pow(y,2)+6*pow(x,4)*y*z+7*x*pow(z,5)-pow(y,4)*pow(z,2)+9*pow(x,4)*z+4*pow(x,2)*pow(y,3)-9*x*pow(y,3)*z-3*x*y*pow(z,3)+9*y*pow(z,4)-10*pow(x,4)-6*x*pow(z,3)-9*y*pow(z,3)+6*x*y*z+8;\n    // g=6*pow(x,10)+9*pow(x,8)*pow(y,2)-2*pow(y,4)*pow(z,6)-9*pow(x,4)*pow(z,5)+2*pow(x,3)*pow(y,4)*pow(z,2)+5*pow(x,8)+9*pow(x,6)*pow(z,2)+pow(x,3)*pow(y,5)-2*pow(x,3)*pow(y,2)*pow(z,3)+6*pow(x,2)*pow(z,6)+4*pow(y,6)*pow(z,2)+5*pow(y,4)*pow(z,4)-pow(x,7)-10*pow(x,6)*z+10*pow(x,3)*pow(y,2)*pow(z,2)+8*pow(y,6)*z-4*pow(y,5)*pow(z,2)+10*pow(y,2)*pow(z,5)-5*pow(x,2)*pow(y,2)*pow(z,2)+2*pow(x,2)*y*pow(z,3)-7*x*pow(y,3)*pow(z,2)-10*pow(x,4)+5*pow(y,4)+8;\n    // f=-2*pow(x,5)*pow(y,2)*pow(z,3)-3*x*pow(y,7)*pow(z,2)+10*x*pow(y,5)*pow(z,4)-4*pow(y,10)+4*pow(y,6)*pow(z,4)+7*pow(x,8)*z-5*pow(x,5)*pow(y,4)+4*pow(x,4)*pow(z,5)+7*x*pow(y,2)*pow(z,6)-4*pow(y,5)*pow(z,4)+6*pow(x,6)*y*z+7*pow(x,5)*pow(y,2)*z+5*pow(x,5)*pow(z,3)-7*pow(x,4)*pow(y,3)*z-10*pow(x,2)*pow(z,6)+2*x*pow(y,5)*pow(z,2)-2*pow(x,5)*y*z-10*pow(x,3)*pow(y,3)*z+x*pow(y,4)*z-5*pow(y,4)*pow(z,2)+9*pow(y,3)*pow(z,2)+2*pow(y,2)*pow(z,3)+8*pow(x,3)*y-5*x*y*pow(z,2)+10;\n    // // clpoly::polynomial_<clpoly::ZZ,clpoly::lex> f_,g_;\n    // // clpoly::poly_convert(f,f_);\n    // // clpoly::poly_convert(g,g_);\n    // std::cout<<\"f:\"<<f<<std::endl;\n    // std::cout<<\"g:\"<<g<<std::endl;\n    // // std::cout<<clpoly::polynomial_GCD(f*g,g*g)<<std::endl;\n    // clpoly::lex_<clpoly::custom_var_order> mo(std::vector<clpoly::variable>({z,y,x}));\n    // clpoly::polynomial_<clpoly::ZZ,clpoly::lex_<clpoly::custom_var_order>> p1(&mo);\n    // clpoly::poly_convert(g,p1);\n    // std::cout<< p1<<std::endl;\n    return 0;\n  \n\n}", "meta": {"hexsha": "2e4476fe5cd4d6a5fc4c32d237a7d6edc0ee4b12", "size": 8647, "ext": "cc", "lang": "C++", "max_stars_repo_path": "test/polynomial_test.cc", "max_stars_repo_name": "lihaokun/CLPoly", "max_stars_repo_head_hexsha": "f75d043efbd5994d9e5f046b9a27f6aac4137e62", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2020-09-15T14:15:36.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-14T08:47:00.000Z", "max_issues_repo_path": "test/polynomial_test.cc", "max_issues_repo_name": "lihaokun/CLPoly", "max_issues_repo_head_hexsha": "f75d043efbd5994d9e5f046b9a27f6aac4137e62", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/polynomial_test.cc", "max_forks_repo_name": "lihaokun/CLPoly", "max_forks_repo_head_hexsha": "f75d043efbd5994d9e5f046b9a27f6aac4137e62", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-07-01T02:43:44.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-18T03:07:33.000Z", "avg_line_length": 48.3072625698, "max_line_length": 475, "alphanum_fraction": 0.5307042905, "num_tokens": 3662, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6513548646660543, "lm_q2_score": 0.5117166047041654, "lm_q1q2_score": 0.33330909980445445}}
{"text": "#ifndef STAN_MCMC_CHAINS_HPP\n#define STAN_MCMC_CHAINS_HPP\n\n#include <stan/util/io/stan_csv_reader.hpp>\n#include <stan/math/prim/mat.hpp>\n#include <stan/util/analyze/mcmc/compute_effective_sample_size.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/tail_quantile.hpp>\n#include <boost/accumulators/statistics/p_square_quantile.hpp>\n#include <boost/accumulators/statistics/variance.hpp>\n#include <boost/accumulators/statistics/covariance.hpp>\n#include <boost/accumulators/statistics/variates/covariate.hpp>\n#include <boost/random/uniform_int_distribution.hpp>\n#include <boost/random/additive_combine.hpp>\n#include <algorithm>\n#include <cmath>\n#include <iostream>\n#include <map>\n#include <stdexcept>\n#include <string>\n#include <sstream>\n#include <utility>\n#include <vector>\n#include <cstdlib>\n\nnamespace stan {\n  namespace mcmc {\n    using Eigen::Dynamic;\n\n    /**\n     * An <code>mcmc::chains</code> object stores parameter names and\n     * dimensionalities along with samples from multiple chains.\n     *\n     * <p><b>Synchronization</b>: For arbitrary concurrent use, the\n     * read and write methods need to be read/write locked.  Multiple\n     * writers can be used concurrently if they write to different\n     * chains.  Readers for single chains need only be read/write locked\n     * with writers of that chain.  For reading across chains, full\n     * read/write locking is required.  Thus methods will be classified\n     * as global or single-chain read or write methods.\n     *\n     * <p><b>Storage Order</b>: Storage is column/last-index major.\n     */\n    template <class RNG = boost::random::ecuyer1988>\n    class chains {\n    private:\n      Eigen::Matrix<std::string, Dynamic, 1> param_names_;\n      Eigen::Matrix<Eigen::MatrixXd, Dynamic, 1> samples_;\n      Eigen::VectorXi warmup_;\n\n      static double mean(const Eigen::VectorXd& x) {\n        return (x.array() / x.size()).sum();\n      }\n\n      static double variance(const Eigen::VectorXd& x) {\n        double m = mean(x);\n        return ((x.array() - m) / std::sqrt((x.size() - 1.0))).square().sum();\n      }\n\n      static double sd(const Eigen::VectorXd& x) {\n        return std::sqrt(variance(x));\n      }\n\n\n      static double covariance(const Eigen::VectorXd& x,\n                               const Eigen::VectorXd& y,\n                               std::ostream* err = 0) {\n        if (x.rows() != y.rows() && err)\n          *err << \"warning: covariance of different length chains\";\n        using boost::accumulators::accumulator_set;\n        using boost::accumulators::stats;\n        using boost::accumulators::tag::variance;\n        using boost::accumulators::tag::covariance;\n        using boost::accumulators::tag::covariate1;\n\n        accumulator_set<double, stats<covariance<double, covariate1> > > acc;\n\n        int M = std::min(x.size(), y.size());\n        for (int i = 0; i < M; i++)\n          acc(x(i), boost::accumulators::covariate1 = y(i));\n\n        return boost::accumulators::covariance(acc) * M / (M-1);\n      }\n\n      static double correlation(const Eigen::VectorXd& x,\n                                const Eigen::VectorXd& y,\n                                std::ostream* err = 0) {\n        if (x.rows() != y.rows() && err)\n          *err << \"warning: covariance of different length chains\";\n        using boost::accumulators::accumulator_set;\n        using boost::accumulators::stats;\n        using boost::accumulators::tag::variance;\n        using boost::accumulators::tag::covariance;\n        using boost::accumulators::tag::covariate1;\n\n        accumulator_set<double, stats<variance,\n                                      covariance<double, covariate1> > > acc_xy;\n        accumulator_set<double, stats<variance> > acc_y;\n\n        int M = std::min(x.size(), y.size());\n        for (int i = 0; i < M; i++) {\n          acc_xy(x(i), boost::accumulators::covariate1 = y(i));\n          acc_y(y(i));\n        }\n\n        double cov = boost::accumulators::covariance(acc_xy);\n        if (cov > -1e-8 && cov < 1e-8)\n          return cov;\n        return cov / std::sqrt(boost::accumulators::variance(acc_xy)\n                               * boost::accumulators::variance(acc_y));\n      }\n\n      static double quantile(const Eigen::VectorXd& x, const double prob) {\n        using boost::accumulators::accumulator_set;\n        using boost::accumulators::left;\n        using boost::accumulators::quantile;\n        using boost::accumulators::quantile_probability;\n        using boost::accumulators::right;\n        using boost::accumulators::stats;\n        using boost::accumulators::tag::tail;\n        using boost::accumulators::tag::tail_quantile;\n        double M = x.rows();\n        // size_t cache_size = std::min(prob, 1-prob)*M + 2;\n        size_t cache_size = M;\n\n        if (prob < 0.5) {\n          accumulator_set<double, stats<tail_quantile<left> > >\n            acc(tail<left>::cache_size = cache_size);\n          for (int i = 0; i < M; i++)\n            acc(x(i));\n          return quantile(acc, quantile_probability = prob);\n        }\n        accumulator_set<double, stats<tail_quantile<right> > >\n          acc(tail<right>::cache_size = cache_size);\n        for (int i = 0; i < M; i++)\n          acc(x(i));\n        return quantile(acc, quantile_probability = prob);\n      }\n\n      static Eigen::VectorXd\n      quantiles(const Eigen::VectorXd& x, const Eigen::VectorXd& probs) {\n        using boost::accumulators::accumulator_set;\n        using boost::accumulators::left;\n        using boost::accumulators::quantile_probability;\n        using boost::accumulators::quantile;\n        using boost::accumulators::right;\n        using boost::accumulators::stats;\n        using boost::accumulators::tag::tail;\n        using boost::accumulators::tag::tail_quantile;\n        double M = x.rows();\n\n        // size_t cache_size = M/2 + 2;\n        size_t cache_size = M;  // 2 + 2;\n\n        accumulator_set<double, stats<tail_quantile<left> > >\n          acc_left(tail<left>::cache_size = cache_size);\n        accumulator_set<double, stats<tail_quantile<right> > >\n          acc_right(tail<right>::cache_size = cache_size);\n\n        for (int i = 0; i < M; i++) {\n          acc_left(x(i));\n          acc_right(x(i));\n        }\n\n        Eigen::VectorXd q(probs.size());\n        for (int i = 0; i < probs.size(); i++) {\n          if (probs(i) < 0.5)\n            q(i) = quantile(acc_left,\n                            quantile_probability = probs(i));\n          else\n            q(i) = quantile(acc_right,\n                            quantile_probability = probs(i));\n        }\n        return q;\n      }\n\n      static Eigen::VectorXd autocorrelation(const Eigen::VectorXd& x) {\n        using std::vector;\n        using stan::math::index_type;\n        typedef typename index_type<vector<double> >::type idx_t;\n\n        std::vector<double> ac;\n        std::vector<double> sample(x.size());\n        for (int i = 0; i < x.size(); i++)\n          sample[i] = x(i);\n        stan::math::autocorrelation(sample, ac);\n\n        Eigen::VectorXd ac2(ac.size());\n        for (idx_t i = 0; i < ac.size(); i++)\n          ac2(i) = ac[i];\n        return ac2;\n      }\n\n      static Eigen::VectorXd autocovariance(const Eigen::VectorXd& x) {\n        using std::vector;\n        using stan::math::index_type;\n        typedef typename index_type<vector<double> >::type idx_t;\n\n        std::vector<double> ac;\n        std::vector<double> sample(x.size());\n        for (int i = 0; i < x.size(); i++)\n          sample[i] = x(i);\n        stan::math::autocovariance(sample, ac);\n\n        Eigen::VectorXd ac2(ac.size());\n        for (idx_t i = 0; i < ac.size(); i++)\n          ac2(i) = ac[i];\n        return ac2;\n      }\n\n      /**\n       * Return the split potential scale reduction (split R hat)\n       * for the specified parameter.\n       *\n       * Current implementation takes the minimum number of samples\n       * across chains as the number of samples per chain.\n       *\n       * @param VectorXd\n       * @param Dynamic\n       * @param samples\n       *\n       * @return\n       */\n      double\n      split_potential_scale_reduction(\n                                      const Eigen::Matrix<Eigen::VectorXd,\n                                      Dynamic, 1> &samples) const {\n        int chains = samples.size();\n        int n_samples = samples(0).size();\n        for (int chain = 1; chain < chains; chain++) {\n          n_samples = std::min(n_samples,\n                               static_cast<int>(samples(chain).size()));\n        }\n        if (n_samples % 2 == 1)\n          n_samples--;\n        int n = n_samples / 2;\n\n        Eigen::VectorXd split_chain_mean(2*chains);\n        Eigen::VectorXd split_chain_var(2*chains);\n\n        for (int chain = 0; chain < chains; chain++) {\n          split_chain_mean(2*chain) = mean(samples(chain).topRows(n));\n          split_chain_mean(2*chain+1) = mean(samples(chain).bottomRows(n));\n\n          split_chain_var(2*chain) = variance(samples(chain).topRows(n));\n          split_chain_var(2*chain+1) = variance(samples(chain).bottomRows(n));\n        }\n\n        double var_between = n * variance(split_chain_mean);\n        double var_within = mean(split_chain_var);\n\n        // rewrote [(n-1)*W/n + B/n]/W as (n-1+ B/W)/n\n        return sqrt((var_between/var_within + n-1)/n);\n      }\n\n    public:\n      explicit chains(const Eigen::Matrix<std::string, Dynamic, 1>& param_names)\n        : param_names_(param_names) { }\n\n      explicit chains(const std::vector<std::string>& param_names)\n        : param_names_(param_names.size()) {\n        for (size_t i = 0; i < param_names.size(); i++)\n          param_names_(i) = param_names[i];\n      }\n\n      explicit chains(const stan::io::stan_csv& stan_csv)\n        : param_names_(stan_csv.header) {\n        if (stan_csv.samples.rows() > 0)\n          add(stan_csv);\n      }\n\n      inline int num_chains() const {\n        return samples_.size();\n      }\n\n      inline int num_params() const {\n        return param_names_.size();\n      }\n\n      const Eigen::Matrix<std::string, Dynamic, 1>& param_names() const {\n        return param_names_;\n      }\n\n      const std::string& param_name(int j) const {\n        return param_names_(j);\n      }\n\n      int index(const std::string& name) const {\n        int index = -1;\n        for (int i = 0; i < param_names_.size(); i++)\n          if (param_names_(i) == name)\n            return i;\n        return index;\n      }\n\n      void set_warmup(const int chain, const int warmup) {\n        warmup_(chain) = warmup;\n      }\n\n      void set_warmup(const int warmup) {\n        warmup_.setConstant(warmup);\n      }\n\n      const Eigen::VectorXi& warmup() const {\n        return warmup_;\n      }\n\n      int warmup(const int chain) const {\n        return warmup_(chain);\n      }\n\n      int num_samples(const int chain) const {\n        return samples_(chain).rows();\n      }\n\n      int num_samples() const {\n        int n = 0;\n        for (int chain = 0; chain < num_chains(); chain++)\n          n += num_samples(chain);\n        return n;\n      }\n\n      int num_kept_samples(const int chain) const {\n        return num_samples(chain) - warmup(chain);\n      }\n\n      int num_kept_samples() const {\n        int n = 0;\n        for (int chain = 0; chain < num_chains(); chain++)\n          n += num_kept_samples(chain);\n        return n;\n      }\n\n      void add(const int chain,\n               const Eigen::MatrixXd& sample) {\n        if (sample.cols() != num_params())\n          throw std::invalid_argument(\"add(chain, sample): number of columns\"\n                                      \" in sample does not match chains\");\n        if (num_chains() == 0 || chain >= num_chains()) {\n          int n = num_chains();\n\n          // Need this block for Windows. conservativeResize\n          // does not keep the references.\n          Eigen::Matrix<Eigen::MatrixXd, Dynamic, 1>\n            samples_copy(num_chains());\n          Eigen::VectorXi warmup_copy(num_chains());\n          for (int i = 0; i < n; i++) {\n            samples_copy(i) = samples_(i);\n            warmup_copy(i) = warmup_(i);\n          }\n\n          samples_.resize(chain+1);\n          warmup_.resize(chain+1);\n          for (int i = 0; i < n; i++) {\n            samples_(i) = samples_copy(i);\n            warmup_(i) = warmup_copy(i);\n          }\n          for (int i = n; i < chain+1; i++) {\n            samples_(i) = Eigen::MatrixXd(0, num_params());\n            warmup_(i) = 0;\n          }\n        }\n        int row = samples_(chain).rows();\n        Eigen::MatrixXd new_samples(row+sample.rows(), num_params());\n        new_samples << samples_(chain), sample;\n        samples_(chain) = new_samples;\n      }\n\n      void add(const Eigen::MatrixXd& sample) {\n        if (sample.rows() == 0)\n          return;\n        if (sample.cols() != num_params())\n          throw std::invalid_argument(\"add(sample): number of columns in\"\n                                      \" sample does not match chains\");\n        add(num_chains(), sample);\n      }\n\n      /**\n       * Convert a vector of vector<double> to Eigen::MatrixXd\n       *\n       * This method is added for the benefit of software wrapping\n       * Stan (e.g., PyStan) so that it need not additionally wrap Eigen.\n       *\n       */\n      void add(const std::vector<std::vector<double> >& sample) {\n        int n_row = sample.size();\n        if (n_row == 0)\n          return;\n        int n_col = sample[0].size();\n        Eigen::MatrixXd sample_copy(n_row, n_col);\n        for (int i = 0; i < n_row; i++) {\n          sample_copy.row(i)\n            = Eigen::VectorXd::Map(&sample[i][0], sample[0].size());\n        }\n        add(sample_copy);\n      }\n\n      void add(const stan::io::stan_csv& stan_csv) {\n        if (stan_csv.header.size() != num_params())\n          throw std::invalid_argument(\"add(stan_csv): number of columns in\"\n                                      \" sample does not match chains\");\n        if (!param_names_.cwiseEqual(stan_csv.header).all()) {\n          throw std::invalid_argument(\"add(stan_csv): header does not match\"\n                                      \" chain's header\");\n        }\n        add(stan_csv.samples);\n        if (stan_csv.metadata.save_warmup)\n          set_warmup(num_chains()-1, stan_csv.metadata.num_warmup);\n      }\n\n      Eigen::VectorXd samples(const int chain, const int index) const {\n        return samples_(chain).col(index).bottomRows(num_kept_samples(chain));\n      }\n\n      Eigen::VectorXd samples(const int index) const {\n        Eigen::VectorXd s(num_kept_samples());\n        int start = 0;\n        for (int chain = 0; chain < num_chains(); chain++) {\n          int n = num_kept_samples(chain);\n          s.middleRows(start, n) = samples_(chain).col(index).bottomRows(n);\n          start += n;\n        }\n        return s;\n      }\n\n      Eigen::VectorXd samples(const int chain, const std::string& name) const {\n        return samples(chain, index(name));\n      }\n\n      Eigen::VectorXd samples(const std::string& name) const {\n        return samples(index(name));\n      }\n\n      double mean(const int chain, const int index) const {\n        return mean(samples(chain, index));\n      }\n\n      double mean(const int index) const {\n        return mean(samples(index));\n      }\n\n      double mean(const int chain, const std::string& name) const {\n        return mean(chain, index(name));\n      }\n\n      double mean(const std::string& name) const {\n        return mean(index(name));\n      }\n\n      double sd(const int chain, const int index) const {\n        return sd(samples(chain, index));\n      }\n\n      double sd(const int index) const {\n        return sd(samples(index));\n      }\n\n      double sd(const int chain, const std::string& name) const {\n        return sd(chain, index(name));\n      }\n\n      double sd(const std::string& name) const {\n        return sd(index(name));\n      }\n\n      double variance(const int chain, const int index) const {\n        return variance(samples(chain, index));\n      }\n\n      double variance(const int index) const {\n        return variance(samples(index));\n      }\n\n      double variance(const int chain, const std::string& name) const {\n        return variance(chain, index(name));\n      }\n\n      double variance(const std::string& name) const {\n        return variance(index(name));\n      }\n\n      double\n      covariance(const int chain, const int index1, const int index2) const {\n        return covariance(samples(chain, index1), samples(chain, index2));\n      }\n\n      double covariance(const int index1, const int index2) const {\n        return covariance(samples(index1), samples(index2));\n      }\n\n      double covariance(const int chain, const std::string& name1,\n                        const std::string& name2) const {\n        return covariance(chain, index(name1), index(name2));\n      }\n\n      double\n      covariance(const std::string& name1, const std::string& name2) const {\n        return covariance(index(name1), index(name2));\n      }\n\n      double\n      correlation(const int chain, const int index1, const int index2) const {\n        return correlation(samples(chain, index1), samples(chain, index2));\n      }\n\n      double correlation(const int index1, const int index2) const {\n        return correlation(samples(index1), samples(index2));\n      }\n\n      double correlation(const int chain, const std::string& name1,\n                         const std::string& name2) const {\n        return correlation(chain, index(name1), index(name2));\n      }\n\n      double\n      correlation(const std::string& name1, const std::string& name2) const {\n        return correlation(index(name1), index(name2));\n      }\n\n      double\n      quantile(const int chain, const int index, const double prob) const {\n        return quantile(samples(chain, index), prob);\n      }\n\n      double quantile(const int index, const double prob) const {\n        return quantile(samples(index), prob);\n      }\n\n      double quantile(int chain, const std::string& name, double prob) const {\n        return quantile(chain, index(name), prob);\n      }\n\n      double quantile(const std::string& name, const double prob) const {\n        return quantile(index(name), prob);\n      }\n\n      Eigen::VectorXd\n      quantiles(int chain, int index, const Eigen::VectorXd& probs) const {\n        return quantiles(samples(chain, index), probs);\n      }\n\n      Eigen::VectorXd quantiles(int index, const Eigen::VectorXd& probs) const {\n        return quantiles(samples(index), probs);\n      }\n\n      Eigen::VectorXd\n      quantiles(int chain, const std::string& name,\n                const Eigen::VectorXd& probs) const {\n        return quantiles(chain, index(name), probs);\n      }\n\n      Eigen::VectorXd\n      quantiles(const std::string& name, const Eigen::VectorXd& probs) const {\n        return quantiles(index(name), probs);\n      }\n\n      Eigen::Vector2d central_interval(int chain, int index,\n                                       double prob) const {\n        double low_prob = (1-prob)/2;\n        double high_prob = 1-low_prob;\n\n        Eigen::Vector2d interval;\n        interval\n          << quantile(chain, index, low_prob),\n          quantile(chain, index, high_prob);\n        return interval;\n      }\n\n      Eigen::Vector2d central_interval(int index, double prob) const {\n        double low_prob = (1-prob)/2;\n        double high_prob = 1-low_prob;\n\n        Eigen::Vector2d interval;\n        interval << quantile(index, low_prob), quantile(index, high_prob);\n        return interval;\n      }\n\n      Eigen::Vector2d\n      central_interval(int chain, const std::string& name,\n                       double prob) const {\n        return central_interval(chain, index(name), prob);\n      }\n\n      Eigen::Vector2d central_interval(const std::string& name,\n                                       double prob) const {\n        return central_interval(index(name), prob);\n      }\n\n      Eigen::VectorXd autocorrelation(const int chain, const int index) const {\n        return autocorrelation(samples(chain, index));\n      }\n\n      Eigen::VectorXd autocorrelation(int chain,\n                                      const std::string& name) const {\n        return autocorrelation(chain, index(name));\n      }\n\n      Eigen::VectorXd autocovariance(const int chain, const int index) const {\n        return autocovariance(samples(chain, index));\n      }\n\n      Eigen::VectorXd autocovariance(int chain, const std::string& name) const {\n        return autocovariance(chain, index(name));\n      }\n\n      // FIXME: reimplement using autocorrelation.\n      double effective_sample_size(const int index) const {\n        int n_chains = num_chains();\n        std::vector<const double*> draws(n_chains);\n        std::vector<size_t> sizes(n_chains);\n        int n_kept_samples = 0;\n        for (int chain = 0; chain < n_chains; ++chain) {\n          n_kept_samples = num_kept_samples(chain);\n          draws[chain]\n            = samples_(chain).col(index).bottomRows(n_kept_samples).data();\n          sizes[chain] = n_kept_samples;\n        }\n        return analyze::compute_effective_sample_size(draws, sizes);\n      }\n\n      double effective_sample_size(const std::string& name) const {\n        return effective_sample_size(index(name));\n      }\n\n      double split_effective_sample_size(const int index) const {\n        int n_chains = num_chains();\n        std::vector<const double*> draws(n_chains);\n        std::vector<size_t> sizes(n_chains);\n        int n_kept_samples = 0;\n        for (int chain = 0; chain < n_chains; ++chain) {\n          n_kept_samples = num_kept_samples(chain);\n          draws[chain]\n            = samples_(chain).col(index).bottomRows(n_kept_samples).data();\n          sizes[chain] = n_kept_samples;\n        }\n        return analyze::compute_split_effective_sample_size(draws, sizes);\n      }\n\n      double split_effective_sample_size(const std::string& name) const {\n        return split_effective_sample_size(index(name));\n      }\n\n      double split_potential_scale_reduction(const int index) const {\n        Eigen::Matrix<Eigen::VectorXd, Dynamic, 1>\n          samples(num_chains());\n        for (int chain = 0; chain < num_chains(); chain++) {\n          samples(chain) = this->samples(chain, index);\n        }\n        return split_potential_scale_reduction(samples);\n      }\n\n      double split_potential_scale_reduction(const std::string& name) const {\n        return split_potential_scale_reduction(index(name));\n      }\n    };\n\n  }\n}\n\n#endif\n", "meta": {"hexsha": "130fb5ef9dd8e6d4b61eedf071a258bd9a372401", "size": 22555, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/stan/algorithms/mcmc/chains.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/algorithms/mcmc/chains.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/algorithms/mcmc/chains.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.0196078431, "max_line_length": 80, "alphanum_fraction": 0.5830636223, "num_tokens": 5217, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6513548511303338, "lm_q2_score": 0.5117166047041652, "lm_q1q2_score": 0.3333090928780014}}
{"text": "#include \"mpi_fsi.h\"\n#include \"mpi_scnsim.h\"\n#include \"mpi_shared_hypo_elasticity.h\"\n#include \"parameters.h\"\n#include \"utilities.h\"\n#include <deal.II/grid/grid_in.h>\n#include <deal.II/grid/grid_out.h>\n\nextern template class Fluid::MPI::SCnsIM<3>;\nextern template class Solid::MPI::SharedHypoElasticity<3>;\nextern template class MPI::FSI<3>;\n\nusing namespace dealii;\n\nint main(int argc, char *argv[])\n{\n  using namespace dealii;\n\n  try\n    {\n      Utilities::MPI::MPI_InitFinalize mpi_initialization(argc, argv, 1);\n\n      std::string infile(\"parameters.prm\");\n      if (argc > 1)\n        {\n          infile = argv[1];\n        }\n      Parameters::AllParameters params(infile);\n\n      if (params.dimension == 3)\n        {\n          // Read solid mesh\n          Triangulation<3> tria_solid;\n          dealii::GridGenerator::subdivided_hyper_rectangle(tria_solid,\n                                                            {20u, 20u, 8u},\n                                                            Point<3>(0, 0, 0),\n                                                            Point<3>(1, 1, 0.4),\n                                                            true);\n\n          // Read fluid mesh\n          parallel::distributed::Triangulation<3> tria_fluid(MPI_COMM_WORLD);\n          dealii::GridGenerator::subdivided_hyper_rectangle(tria_fluid,\n                                                            {10u, 10u, 40u},\n                                                            Point<3>(0, 0, 0),\n                                                            Point<3>(1, 1, 4),\n                                                            true);\n          for (auto cell : tria_fluid.active_cell_iterators())\n            {\n              auto center = cell->center();\n              if (center[2] >= 2 && center[2] <= 2.4)\n                cell->set_refine_flag();\n            }\n          tria_fluid.execute_coarsening_and_refinement();\n\n          // Translate solid mesh\n          Tensor<1, 3> offset({0, 0, 2});\n          GridTools::shift(offset, tria_solid);\n\n          Fluid::MPI::SCnsIM<3> fluid(tria_fluid, params);\n          Solid::MPI::SharedHypoElasticity<3> solid(\n            tria_solid, params, 0.05, 1.3);\n          MPI::FSI<3> fsi(fluid, solid, params);\n          fsi.run();\n        }\n      else\n        {\n          AssertThrow(false, ExcNotImplemented());\n        }\n    }\n  catch (std::exception &exc)\n    {\n      std::cerr << std::endl\n                << std::endl\n                << \"----------------------------------------------------\"\n                << std::endl;\n      std::cerr << \"Exception on processing: \" << std::endl\n                << exc.what() << std::endl\n                << \"Aborting!\" << std::endl\n                << \"----------------------------------------------------\"\n                << std::endl;\n      return 1;\n    }\n  catch (...)\n    {\n      std::cerr << std::endl\n                << std::endl\n                << \"----------------------------------------------------\"\n                << std::endl;\n      std::cerr << \"Unknown exception!\" << std::endl\n                << \"Aborting!\" << std::endl\n                << \"----------------------------------------------------\"\n                << std::endl;\n      return 1;\n    }\n  return 0;\n}\n", "meta": {"hexsha": "642fcd82220e058caba65a23a4a17d089755dc94", "size": 3273, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/fsi-wall-3D/fsi-wall-3D.cpp", "max_stars_repo_name": "yufeimi/OpenIFEM", "max_stars_repo_head_hexsha": "51cdd1633e41a3f5a3175e216c8584da43f3dc76", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 20.0, "max_stars_repo_stars_event_min_datetime": "2019-04-08T15:24:52.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-04T16:52:32.000Z", "max_issues_repo_path": "tests/fsi-wall-3D/fsi-wall-3D.cpp", "max_issues_repo_name": "chenjiatu/OpenIFEM", "max_issues_repo_head_hexsha": "dc0e0081e08827d8f20a3744683ac31ff9e78a55", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 18.0, "max_issues_repo_issues_event_min_datetime": "2018-05-10T14:42:23.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-24T18:41:54.000Z", "max_forks_repo_path": "tests/fsi-wall-3D/fsi-wall-3D.cpp", "max_forks_repo_name": "chenjiatu/OpenIFEM", "max_forks_repo_head_hexsha": "dc0e0081e08827d8f20a3744683ac31ff9e78a55", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 20.0, "max_forks_repo_forks_event_min_datetime": "2018-04-16T01:40:28.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-13T05:55:15.000Z", "avg_line_length": 33.7422680412, "max_line_length": 80, "alphanum_fraction": 0.4130766881, "num_tokens": 728, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6825737473266735, "lm_q2_score": 0.4882833952958347, "lm_q1q2_score": 0.33328942688446933}}
{"text": "///////////////////////////////////////////////////////////////////////////////\n// kolmogorov_smirnov::statistic.hpp                                         //\n//                                                                           //\n//  Copyright 2010 Erwann Rogard. Distributed under the Boost                //\n//  Software License, Version 1.0. (See accompanying file                    //\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)         //\n///////////////////////////////////////////////////////////////////////////////\n#ifndef BOOST_STATISTICS_DETAIL_KOLMOGOROV_SMIRNOV_STATISTIC_HPP_ER_2010\n#define BOOST_STATISTICS_DETAIL_KOLMOGOROV_SMIRNOV_STATISTIC_HPP_ER_2010\n#include <boost/type_traits.hpp>\n#include <boost/range.hpp>\n\n#include <boost/mpl/placeholders.hpp>\n#include <boost/mpl/apply.hpp>\n#include <boost/mpl/if.hpp>\n\n#include <boost/foreach.hpp>\n#include <boost/parameter/binding.hpp>\n\n#include <boost/accumulators/framework/extractor.hpp>\n#include <boost/accumulators/framework/accumulator_base.hpp>\n#include <boost/accumulators/framework/parameters/sample.hpp>\n#include <boost/accumulators/framework/parameters/accumulator.hpp>\n#include <boost/accumulators/framework/depends_on.hpp>\n#include <boost/accumulators/statistics/stats.hpp>\n#include <boost/accumulators/statistics/count.hpp>\n\n#include <boost/statistics/detail/non_parametric/empirical_distribution/count.hpp>\n\nnamespace boost { \nnamespace statistics{\nnamespace detail{\nnamespace empirical_distribution{\nnamespace impl{\n\n    // Warning : See empirical_distribution::impl::count\n    template<typename T>\n    class kolmogorov_smirnov : public boost::accumulators::accumulator_base{\n    \t\n        typedef std::size_t size_;\n        typedef boost::accumulators::dont_care dont_care_;\n\n        public:\n\n        kolmogorov_smirnov(dont_care_){};\n\n        typedef size_ size_type;\n        typedef T sample_type;\n        typedef void result_type;\n\n        void operator()(dont_care_)const{}\n\n        template<typename Args>\n        result_type result(dont_care_) const\n        {\n        }\n\t};\n    \n}\nnamespace tag\n{\n    struct kolmogorov_smirnov\n      : boost::accumulators::depends_on<\n      \tstatistics::detail::empirical_distribution::tag::ordered_sample,\n        boost::accumulators::tag::count\n    >\n    {\n        struct impl{\n            template<typename T,typename W>\n            struct apply{\n                typedef detail::kolmogorov_smirnov::impl::kolmogorov_smirnov<T> type;    \t\n            };\n        };\n    };\n}\nnamespace result_of{\n\n    template<typename T1,typename AccSet,typename D>\n    struct kolmogorov_smirnov_statistic\n    {\n        typedef T1 type;\n    };\n\n}\n\n    // Usage : statistic<T1>(acc,dist)\n    template<typename T1,typename AccSet,typename D>\n    typename kolmogorov_smirnov\n        ::result_of::template kolmogorov_smirnov_statistic<T1,AccSet,D>::type\n    kolmogorov_smirnov_statistic(AccSet const& acc,const D& dist)\n    {\n            namespace ed = boost::statistics::detail::empirical_distribution;\n            namespace ks = boost::statistics::detail::kolmogorov_smirnov;\n            typedef T1 val_;\n            typedef std::size_t size_;\n            typedef boost::accumulators::tag::count tag_n_;\n            typedef ed::tag::ordered_sample tag_os_;\n\n            typedef typename ed::result_of::ordered_sample<\n                AccSet>::type ref_os_; \n            typedef typename boost::remove_const< //in case ref changed to cref\n            \ttypename boost::remove_reference<\n                \tref_os_\n                >::type\n            >::type os_;\n            typedef typename boost::range_reference<os_>::type ref_elem_;\n\n            ref_os_ ref_os \n                = boost::accumulators::extract_result<tag_os_>( acc );\n\n            val_ m1 = static_cast<val_>(0);\n            size_ i = 0;\n            size_ n = boost::accumulators::extract::count( acc );\n            \n            BOOST_FOREACH(ref_elem_ e,ref_os){\n                i += e.second; \n                val_ ecdf = static_cast<val_>(i) / static_cast<val_>(n);\n                val_ true_cdf = cdf( dist, e.first );\n                val_ m2 \n                \t= (true_cdf > ecdf)?(true_cdf - ecdf) : (ecdf - true_cdf);\n                if(m2 > m1){ m1 = m2; } \n            }\n            \n            return m1;\n    }\n\n\n}// kolgorov_statistic\n}// empirical_distribution\n}// detail\n}// statistics\n}// boost\n\n#endif", "meta": {"hexsha": "e3f841771be638a21a1a7435f573f0a8b59aa8a1", "size": 4417, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "non_parametric/boost/statistics/detail/non_parametric/backup_once_in_trunk/non_parametric/kolmogorov_smirnov/statistic.hpp", "max_stars_repo_name": "rogard/boost_sandbox_statistics", "max_stars_repo_head_hexsha": "16aacbc716a31a9f7bb6c535b1c90dc343282a23", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "non_parametric/boost/statistics/detail/non_parametric/backup_once_in_trunk/non_parametric/kolmogorov_smirnov/statistic.hpp", "max_issues_repo_name": "rogard/boost_sandbox_statistics", "max_issues_repo_head_hexsha": "16aacbc716a31a9f7bb6c535b1c90dc343282a23", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "non_parametric/boost/statistics/detail/non_parametric/backup_once_in_trunk/non_parametric/kolmogorov_smirnov/statistic.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.9626865672, "max_line_length": 90, "alphanum_fraction": 0.6033506905, "num_tokens": 1000, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6825737473266735, "lm_q2_score": 0.4882833952958347, "lm_q1q2_score": 0.33328942688446933}}
{"text": "#include <cmath>\n#include <cstdio>\n#include <cstdlib>\n#include <cassert>\n#include <cfenv>\n\n#include <complex>\n#include <iomanip>\n#include <iostream>\n#include <vector>\n\n#include <armadillo>\n\n#ifdef HAVE_OMP\n#include <omp.h>\n#endif\n\n#include \"pme.h\"\n#include \"abort_unless.h\"\n#include \"energies.h\"\n\nusing namespace std;\nusing namespace arma;\n\nconst complex<double> I(0.0, 1.0);\n\newald::exclusion_vector exclusions;\n\nstatic bool excluded(size_t i, size_t j);\n\nint main(int argc, char* argv[]) {\n  if (argc < 8) {\n    cout << \"Usage: \" << argv[0]\n         << \" dimension cell-file positions-file charges-file cut-off tolerance num-shells\\n\";\n    return EXIT_FAILURE;\n  }\n\n  const long dim0 = atoi(argv[1]);\n  const long dim1 = dim0;\n  const long dim2 = dim0;\n\n  mat::fixed<3, 3> L;\n  L.load(argv[2]);\n  const mat::fixed<3, 3> LinvT = trans(inv(L));\n  L.print();\n\n  mat r;\n  r.load(argv[3]);\n  abort_unless(r.n_rows == 3);\n  const mat x = inv(L) * r;\n\n  vec qq;\n  qq.load(argv[4]);\n  std::vector<double> q(r.n_cols);\n  {\n    for (size_t k = 0; k < q.size(); ++k)\n      q[k] = qq(k);\n  }\n\n  const size_t num_particles = q.size();\n  clog << \"Read \" << num_particles << \" particles into memory.\\n\";\n\n  std::vector<double> coor_x(num_particles);\n  std::vector<double> coor_y(num_particles);\n  std::vector<double> coor_z(num_particles);\n  {\n    for (size_t k = 0; k < num_particles; ++k) {\n      coor_x[k] = r(0, k);\n      coor_y[k] = r(1, k);\n      coor_z[k] = r(2, k);\n    }\n  }\n\n  const double cut_off = atof(argv[5]);\n  const double cut_off2 = cut_off * cut_off;\n  const double tolerance = atof(argv[6]);\n  clog << \"Real space cut-off: \" << cut_off << \"\\n\"\n       << \"Real space tolerance: \" << tolerance << \"\\n\\n\";\n\n\n  exclusions = ewald::exclusion_vector(num_particles);\n  {                                     // Populate exclusion vector.\n/*\n    for (size_t i = 0; i < num_particles; ++i)\n      for (size_t j = 0; j < num_particles; ++j)\n        // if (i != j && ((i % 2) != (j % 2))) {\n        if (abs(int(i) - int(j)) <= 2) {\n          exclusions[i].push_back(j);\n        }\n*/\n    /*\n    for (size_t i = 0; i < num_particles; ++i) {\n      std::cout << i << \": \";\n      ewald::index_vector const& is = exclusions[i];\n      for (size_t j = 0; j < is.size(); ++j)\n        std::cout << is[j] << \" \";\n      std::cout << std::endl;\n    }\n    */\n  }\n\n  const double max_shell = int(atof(argv[7]));\n\n  mat forces = zeros<mat>(3, num_particles);\n  mat force_cutoff = zeros<mat>(3, num_particles);\n  mat force_direct = zeros<mat>(3, num_particles);\n  mat force_recip = zeros<mat>(3, num_particles);\n  mat force_excluded = zeros<mat>(3, num_particles);\n  mat force_excluded_pme = zeros<mat>(3, num_particles);\n\n  std::vector<double> force_x(num_particles, 0.0);\n  std::vector<double> force_y(num_particles, 0.0);\n  std::vector<double> force_z(num_particles, 0.0);\n  mat force_recip_pme = zeros<mat>(3, num_particles);\n  double LL[3 * 3];\n  for (size_t i = 0; i < 3; ++i)\n    for (size_t j = 0; j < 3; ++j)\n      LL[3*i+j] = L(i, j);\n\n  energies energy_pme, energy_ewald;\n\n  wall_clock timer;\n  timer.tic();\n\n#ifdef HAVE_OMP\n  ewald::pme p(dim0, dim1, dim2, LL, num_particles, &q[0], cut_off, tolerance, omp_get_max_threads());\n#else\n  ewald::pme p(dim0, dim1, dim2, LL, num_particles, &q[0], cut_off, tolerance, 1);\n#endif\n  double seconds = timer.toc();\n\n  clog << \"PME initialization took \" << seconds << \" seconds.\\n\\n\";\n\n  const double t = p.get_threshold();\n  if (std::isnan(t)) {\n    cerr << \"Unable to run PME for the prescribed values of cut off and tolerance.\\n\";\n    return EXIT_FAILURE;\n  }\n\n  timer.tic();\n\n  energy_pme.recip = p.energy(&coor_x[0], &coor_y[0], &coor_z[0],\n                              &force_x[0], &force_y[0], &force_z[0]);\n\n  for (size_t k = 0; k < num_particles; ++k) {\n    force_recip_pme(0, k) = force_x[k];\n    force_recip_pme(1, k) = force_y[k];\n    force_recip_pme(2, k) = force_z[k];\n  }\n\n  seconds = timer.toc();\n  clog << \"PME took \" << seconds << \" seconds.\\n\\n\";\n\n  std::vector<double> force_excl_x(num_particles, 0.0);\n  std::vector<double> force_excl_y(num_particles, 0.0);\n  std::vector<double> force_excl_z(num_particles, 0.0);\n\n  energy_pme.masked = p.excluded(exclusions,\n                                 &coor_x[0],\n                                 &coor_y[0],\n                                 &coor_z[0],\n                                 &force_excl_x[0],\n                                 &force_excl_y[0],\n                                 &force_excl_z[0]);\n\n  for (size_t k = 0; k < num_particles; ++k) {\n    force_excluded_pme(0, k) = force_excl_x[k];\n    force_excluded_pme(1, k) = force_excl_y[k];\n    force_excluded_pme(2, k) = force_excl_z[k];\n  }\n\n  energy_ewald.extra = energy_pme.extra = p.energy_extra();\n  energy_ewald.self = energy_pme.self = p.energy_self();\n\n  double Eexhaustive = 0.0;\n  double Ecutoff = 0.0;\n\n  mat force_ewald, force_pme;\n\n  double elapsed = 0.0;\n\n  for (int n = 0; n <= max_shell; n++) {\n    wall_clock timer;\n    timer.tic();\n    for (int nx = -n; nx <= n; nx++) {\n      for (int ny = -n; ny <= n; ny++) {\n        for (int nz = -n; nz <= n; nz++) {\n          if (abs(nx) != n && abs(ny) != n && abs(nz) != n)\n            continue;\n\n          const bool origin = (n == 0);\n\n          const vec::fixed<3> m = { double(nx), double(ny), double(nz) };\n          const vec::fixed<3> Lm = L * m;\n          const vec::fixed<3> LinvTm = LinvT * m;\n\n          // Compute direct space contribution.\n          for (size_t i = 0; i < num_particles; i++) {\n            for (size_t j = 0; j < num_particles; j++) {\n              if (origin && i == j)\n                continue;\n\n              const vec::fixed<3> v = r.col(i) - r.col(j) + Lm;\n              const double r2 = dot(v, v);\n              const double r6 = r2 * r2 * r2;\n              const double r8 = r6 * r2;\n\n              const double qij = q[i] * q[j];\n\n              const bool is_excluded = excluded(i, j);\n\n              const double ener = 0.5 * qij / r6;\n              const vec::fixed<3> f = 6.0 * qij / r8 * v;\n\n              if (origin) {\n                if (!is_excluded) {     // Unmasked pair.\n                  Eexhaustive  += ener;\n                  forces.col(i) += f;\n\n                  if (r2 < cut_off2) {\n                    Ecutoff += ener;\n                    force_cutoff.col(i) += f;\n\n                    vec::fixed<3> dv;\n                    const double pot = 0.5 * qij\n                        * p.direct_convergence_term(v.memptr(), dv.memptr());\n                    energy_pme.direct += pot;\n                    energy_ewald.direct += pot;\n                    force_direct.col(i) += -qij * dv;\n                  }\n                } else {                // Masked pair.\n                  // Note that we don't do cut offs here because we\n                  // want to cancel the Fourier space contribution,\n                  // which does not involve cut offs.\n                  vec::fixed<3> dv;\n                  energy_ewald.masked += (ener - 0.5 * qij\n                                          * p.direct_convergence_term(v.memptr(),\n                                                                      dv.memptr()));\n                  force_excluded.col(i) += f + qij * dv;\n                }\n              } else {                  // Outer shells.\n                Eexhaustive  += ener;\n                forces.col(i) += f;\n\n                if (r2 < cut_off2) {\n                  Ecutoff += ener;\n                  force_cutoff.col(i) += f;\n\n                  vec::fixed<3> dv;\n                  const double pot = 0.5 * qij\n                      * p.direct_convergence_term(v.memptr(), dv.memptr());\n                  energy_pme.direct += pot;\n                  energy_ewald.direct += pot;\n                  force_direct.col(i) += -qij * dv;\n                }\n              }\n            }\n          }\n\n          // Compute contribution from Fourier space.\n          if (!origin) {\n            complex<double> rho(0.0, 0.0);\n\n            for (size_t i = 0; i < num_particles; i++)\n              rho += q[i] * exp(2.0 * M_PI * I * dot(m, x.col(i)));\n\n            const double h2 = dot(LinvTm, LinvTm);\n            energy_ewald.recip += p.recip_convergence_term(h2, rho);\n\n            // force_recip.col(0) = -4.0 * M_PI * q[0] * q[1] * p.psi(h2) * sin(2.0 * M_PI * dot(LinvTm, r.col(0) - r.col(1))) * (-m);\n            // force_recip.col(1) = -4.0 * M_PI * q[0] * q[1] * p.psi(h2) * sin(2.0 * M_PI * dot(LinvTm, r.col(0) - r.col(1))) * m;\n          }\n        }\n      }\n    }\n\n    elapsed += timer.toc();\n\n    force_ewald = force_direct + force_recip;\n    force_pme   = force_direct + force_recip_pme - force_excluded_pme;\n\n    {\n      const double pme_total   = energy_pme.total();\n      const double ewald_total = energy_ewald.total();\n\n      const double rel_error_ewald_vs_pme    = fabsl(ewald_total - pme_total) / fabsl(ewald_total);\n      const double rel_error_ewald_vs_cutoff = fabsl(ewald_total - Ecutoff) / fabsl(ewald_total);\n\n      const double rel_error_exhaustive_vs_cutoff = fabsl(Eexhaustive - Ecutoff) / fabsl(Eexhaustive);\n      const double rel_error_exhaustive_vs_ewald  = fabsl(Eexhaustive - ewald_total) / fabsl(Eexhaustive);\n      const double rel_error_exhaustive_vs_pme    = fabsl(Eexhaustive - pme_total) / fabsl(Eexhaustive);\n\n      cout << \"==============================================\\n\"\n           << fixed << setprecision(4)\n           << \"Shell \" << n << \" (\" << elapsed << \" seconds)\" << \"\\n\"\n           << \"==============================================\\n\"\n           << scientific << setprecision(9)\n           << \"\\n\"\n           << \"Eexhaustive = \" << Eexhaustive << \"\\n\"\n           << \"Ecutoff     = \" << Ecutoff << \"\\n\"\n           << \"Ewald       = \" << energy_ewald << \"\\n\"\n           << \"PME         = \" << energy_pme << \"\\n\"\n           << \"\\n\"\n           << \"Abs. error in excluded forces = \" << norm(force_excluded - force_excluded_pme, \"inf\") << \"\\n\"\n           << \"\\n\"\n           << \"Abs. error in forces (Exhaustive vs. cutoff) = \" << norm(forces - force_cutoff, \"inf\") << \"\\n\"\n           << \"Abs. error in forces (Exhaustive vs. PME)    = \" << norm(forces - force_pme, \"inf\") << \"\\n\"\n           << \"\\n\"\n           << \"Rel. error in total energies (Ewald vs. cutoff) = \" << rel_error_ewald_vs_cutoff << \"\\n\"\n           << \"Rel. error in total energies (Ewald vs. PME)    = \" << rel_error_ewald_vs_pme << \"\\n\"\n           << \"\\n\"\n           << \"Rel. error in total energies (Exhaustive vs. cutoff) = \" << rel_error_exhaustive_vs_cutoff << \"\\n\"\n           << \"Rel. error in total energies (Exhaustive vs. Ewald)  = \" << rel_error_exhaustive_vs_ewald << \"\\n\"\n           << \"Rel. error in total energies (Exhaustive vs. PME)    = \" << rel_error_exhaustive_vs_pme << \"\\n\"\n           << endl;\n    }\n  }\n\n  return 0;\n}\n\nbool excluded(size_t i, size_t j) {\n  // assert(i < num_particles);\n  // assert(j < num_particles);\n\n  ewald::index_vector const& is = exclusions[i];\n  for (size_t k = 0; k < is.size(); ++k)\n    if (j == is[k])\n      return true;\n\n  return false;\n}\n", "meta": {"hexsha": "6f61af9f13e9a20405a9eb7c639e2f70128c0e5f", "size": 11065, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "dispersive.cpp", "max_stars_repo_name": "jmbr/libpme6", "max_stars_repo_head_hexsha": "2e81cacdf941c8114615363fbae59d7f06742838", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 19.0, "max_stars_repo_stars_event_min_datetime": "2015-07-21T14:46:01.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-25T20:38:43.000Z", "max_issues_repo_path": "dispersive.cpp", "max_issues_repo_name": "jmbr/libpme6", "max_issues_repo_head_hexsha": "2e81cacdf941c8114615363fbae59d7f06742838", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2016-03-13T20:25:19.000Z", "max_issues_repo_issues_event_max_datetime": "2016-03-15T23:08:34.000Z", "max_forks_repo_path": "dispersive.cpp", "max_forks_repo_name": "jmbr/libpme6", "max_forks_repo_head_hexsha": "2e81cacdf941c8114615363fbae59d7f06742838", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2016-03-07T10:58:02.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-03T22:34:01.000Z", "avg_line_length": 33.2282282282, "max_line_length": 134, "alphanum_fraction": 0.5157704474, "num_tokens": 3214, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6992544335934766, "lm_q2_score": 0.476579651063676, "lm_q1q2_score": 0.3332504339667075}}
{"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 \"ComputeUmeyamaTransform.h\"\n\n#include \"SIMPLib/Common/Constants.h\"\n#include \"SIMPLib/FilterParameters/AbstractFilterParametersReader.h\"\n#include \"SIMPLib/FilterParameters/BooleanFilterParameter.h\"\n#include \"SIMPLib/FilterParameters/DataContainerSelectionFilterParameter.h\"\n#include \"SIMPLib/FilterParameters/LinkedPathCreationFilterParameter.h\"\n#include \"SIMPLib/FilterParameters/SeparatorFilterParameter.h\"\n#include \"SIMPLib/FilterParameters/StringFilterParameter.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 <Eigen/Dense>\n#include <Eigen/Geometry>\n\n#include \"DREAM3DReview/DREAM3DReviewConstants.h\"\n#include \"DREAM3DReview/DREAM3DReviewVersion.h\"\n\n/* Create Enumerations to allow the created Attribute Arrays to take part in renaming */\nenum createdPathID : RenameDataPath::DataID_t\n{\n  AttributeMatrixID21 = 21,\n\n  DataArrayID30 = 30,\n  DataArrayID31 = 31,\n};\n\n// -----------------------------------------------------------------------------\n//\n// -----------------------------------------------------------------------------\nComputeUmeyamaTransform::ComputeUmeyamaTransform()\n: m_SourcePointSet(\"\")\n, m_DestPointSet(\"\")\n, m_UseScaling(false)\n, m_TransformationAttributeMatrixName(\"TransformationData\")\n, m_TransformationMatrixName(\"TransformationMatrix\")\n{\n}\n\n// -----------------------------------------------------------------------------\n//\n// -----------------------------------------------------------------------------\nComputeUmeyamaTransform::~ComputeUmeyamaTransform()\n= default;\n\n// -----------------------------------------------------------------------------\n//\n// -----------------------------------------------------------------------------\nvoid ComputeUmeyamaTransform::setupFilterParameters()\n{\n  FilterParameterVectorType parameters;\n  parameters.push_back(SIMPL_NEW_BOOL_FP(\"Use Scaling\", UseScaling, FilterParameter::Parameter, ComputeUmeyamaTransform));\n  DataContainerSelectionFilterParameter::RequirementType dcReq;\n  dcReq.dcGeometryTypes = {IGeometry::Type::Vertex, IGeometry::Type::Edge, IGeometry::Type::Triangle, IGeometry::Type::Quad, IGeometry::Type::Tetrahedral};\n  parameters.push_back(SIMPL_NEW_DC_SELECTION_FP(\"Moving Geometry\", SourcePointSet, FilterParameter::RequiredArray, ComputeUmeyamaTransform, dcReq));\n  parameters.push_back(SIMPL_NEW_DC_SELECTION_FP(\"Fixed Geometry\", DestPointSet, FilterParameter::RequiredArray, ComputeUmeyamaTransform, dcReq));\n  parameters.push_back(SeparatorFilterParameter::New(\"Transformation Data\", FilterParameter::CreatedArray));\n  parameters.push_back(SIMPL_NEW_AM_WITH_LINKED_DC_FP(\"Transformation Attribute Matrix\", TransformationAttributeMatrixName, SourcePointSet, FilterParameter::CreatedArray, ComputeUmeyamaTransform));\n  parameters.push_back(SIMPL_NEW_DA_WITH_LINKED_AM_FP(\"Transformation Matrix\", TransformationMatrixName, SourcePointSet, TransformationAttributeMatrixName, FilterParameter::CreatedArray, ComputeUmeyamaTransform));\n  setFilterParameters(parameters);\n}\n\n// -----------------------------------------------------------------------------\n//\n// -----------------------------------------------------------------------------\nvoid ComputeUmeyamaTransform::readFilterParameters(AbstractFilterParametersReader* reader, int index)\n{\n  reader->openFilterGroup(this, index);\n  setSourcePointSet(reader->readDataArrayPath(\"SourcePointSet\", getSourcePointSet()));\n  setDestPointSet(reader->readDataArrayPath(\"DestPointSet\", getDestPointSet()));\n  setUseScaling(reader->readValue(\"UseScaling\", getUseScaling()));\n  setTransformationAttributeMatrixName(reader->readString(\"TransformationAttributeMatrixName\", getTransformationAttributeMatrixName()));\n  setTransformationMatrixName(reader->readString(\"TransformationMatrixName\", getTransformationMatrixName()));\n  reader->closeFilterGroup();\n}\n\n// -----------------------------------------------------------------------------\n//\n// -----------------------------------------------------------------------------\nvoid ComputeUmeyamaTransform::initialize()\n{\n}\n\n// -----------------------------------------------------------------------------\n//\n// -----------------------------------------------------------------------------\nvoid ComputeUmeyamaTransform::dataCheck()\n{\n  clearErrorCode();\n  clearWarningCode();\n\n  IGeometry::Pointer movingGeom = getDataContainerArray()->getPrereqGeometryFromDataContainer<IGeometry, AbstractFilter>(this, getSourcePointSet());\n  IGeometry::Pointer fixedGeom = getDataContainerArray()->getPrereqGeometryFromDataContainer<IGeometry, AbstractFilter>(this, getDestPointSet());\n\n  if(getErrorCode() < 0)\n  {\n    return;\n  }\n\n  if(!std::dynamic_pointer_cast<IGeometry2D>(movingGeom) && !std::dynamic_pointer_cast<IGeometry3D>(movingGeom) && !std::dynamic_pointer_cast<VertexGeom>(movingGeom) &&\n     !std::dynamic_pointer_cast<EdgeGeom>(movingGeom))\n  {\n    QString ss = QObject::tr(\"Moving Geometry must be an unstructured geometry (Vertex, Edge, Triangle, Quadrilateral, or Tetrahedral), but the type is %1\").arg(movingGeom->getGeometryTypeAsString());\n    setErrorCondition(-702, ss);\n  }\n\n  if(!std::dynamic_pointer_cast<IGeometry2D>(fixedGeom) && !std::dynamic_pointer_cast<IGeometry3D>(fixedGeom) && !std::dynamic_pointer_cast<VertexGeom>(fixedGeom) &&\n     !std::dynamic_pointer_cast<EdgeGeom>(fixedGeom))\n  {\n    QString ss = QObject::tr(\"Fixed Geometry must be an unstructured geometry (Vertex, Edge, Triangle, Quadrilateral, or Tetrahedral), but the type is %1\").arg(fixedGeom->getGeometryTypeAsString());\n    setErrorCondition(-702, ss);\n  }\n\n  size_t numMovingVertices = 0;\n  size_t numFixedVertices = 0;\n\n  if(IGeometry2D::Pointer igeom2D = std::dynamic_pointer_cast<IGeometry2D>(movingGeom))\n  {\n    numMovingVertices = igeom2D->getNumberOfVertices();\n  }\n  else if(IGeometry3D::Pointer igeom3D = std::dynamic_pointer_cast<IGeometry3D>(movingGeom))\n  {\n    numMovingVertices = igeom3D->getNumberOfVertices();\n  }\n  else if(VertexGeom::Pointer vertex = std::dynamic_pointer_cast<VertexGeom>(movingGeom))\n  {\n    numMovingVertices = vertex->getNumberOfVertices();\n  }\n  else if(EdgeGeom::Pointer edge = std::dynamic_pointer_cast<EdgeGeom>(movingGeom))\n  {\n    numMovingVertices = edge->getNumberOfVertices();\n  }\n\n  if(IGeometry2D::Pointer igeom2D = std::dynamic_pointer_cast<IGeometry2D>(fixedGeom))\n  {\n    numFixedVertices = igeom2D->getNumberOfVertices();\n  }\n  else if(IGeometry3D::Pointer igeom3D = std::dynamic_pointer_cast<IGeometry3D>(fixedGeom))\n  {\n    numFixedVertices = igeom3D->getNumberOfVertices();\n  }\n  else if(VertexGeom::Pointer vertex = std::dynamic_pointer_cast<VertexGeom>(fixedGeom))\n  {\n    numFixedVertices = vertex->getNumberOfVertices();\n  }\n  else if(EdgeGeom::Pointer edge = std::dynamic_pointer_cast<EdgeGeom>(fixedGeom))\n  {\n    numFixedVertices = edge->getNumberOfVertices();\n  }\n\n  if(numMovingVertices != numFixedVertices)\n  {\n    QString ss = QObject::tr(\"The moving and fixed Geometries must have the same number of Vertices; the number of moving Vertices is %1 and the number of fixed Vertices is %2\")\n                     .arg(numMovingVertices)\n                     .arg(numFixedVertices);\n    setErrorCondition(-11000, ss);\n  }\n\n  DataContainer::Pointer m = getDataContainerArray()->getPrereqDataContainer(this, getSourcePointSet());\n\n  if(getErrorCode() < 0)\n  {\n    return;\n  }\n\n  std::vector<size_t> tDims(1, 1);\n  m->createNonPrereqAttributeMatrix(this, getTransformationAttributeMatrixName(), tDims, AttributeMatrix::Type::Generic, AttributeMatrixID21);\n\n  std::vector<size_t> cDims(2, 4);\n  DataArrayPath path(getSourcePointSet().getDataContainerName(), getTransformationAttributeMatrixName(), getTransformationMatrixName());\n\n  m_TransformationMatrixPtr = getDataContainerArray()->createNonPrereqArrayFromPath<DataArray<float>, AbstractFilter, float>(this, path, 0, cDims, \"\", DataArrayID31);\n  if(nullptr != m_TransformationMatrixPtr.lock()) /* Validate the Weak Pointer wraps a non-nullptr pointer to a DataArray<T> object */\n  {\n    m_TransformationMatrix = m_TransformationMatrixPtr.lock()->getPointer(0);\n  } /* Now assign the raw pointer to data from the DataArray<T> object */\n}\n\n// -----------------------------------------------------------------------------\n//\n// -----------------------------------------------------------------------------\nvoid ComputeUmeyamaTransform::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 ComputeUmeyamaTransform::execute()\n{\n  clearErrorCode();\n  clearWarningCode();\n  dataCheck();\n  if(getErrorCode() < 0)\n  {\n    return;\n  }\n\n  IGeometry::Pointer movingGeom = getDataContainerArray()->getDataContainer(m_SourcePointSet)->getGeometry();\n  IGeometry::Pointer fixedGeom = getDataContainerArray()->getDataContainer(m_DestPointSet)->getGeometry();\n\n  float* movingPointsPtr = nullptr;\n  float* fixedPointsPtr = nullptr;\n  size_t numMovingVertices = 0;\n  size_t numFixedVertices = 0;\n\n  if(IGeometry2D::Pointer igeom2D = std::dynamic_pointer_cast<IGeometry2D>(movingGeom))\n  {\n    movingPointsPtr = igeom2D->getVertexPointer(0);\n    numMovingVertices = igeom2D->getNumberOfVertices();\n  }\n  else if(IGeometry3D::Pointer igeom3D = std::dynamic_pointer_cast<IGeometry3D>(movingGeom))\n  {\n    movingPointsPtr = igeom3D->getVertexPointer(0);\n    numMovingVertices = igeom3D->getNumberOfVertices();\n  }\n  else if(VertexGeom::Pointer vertex = std::dynamic_pointer_cast<VertexGeom>(movingGeom))\n  {\n    movingPointsPtr = vertex->getVertexPointer(0);\n    numMovingVertices = vertex->getNumberOfVertices();\n  }\n  else if(EdgeGeom::Pointer edge = std::dynamic_pointer_cast<EdgeGeom>(movingGeom))\n  {\n    movingPointsPtr = edge->getVertexPointer(0);\n    numMovingVertices = edge->getNumberOfVertices();\n  }\n\n  if(IGeometry2D::Pointer igeom2D = std::dynamic_pointer_cast<IGeometry2D>(fixedGeom))\n  {\n    fixedPointsPtr = igeom2D->getVertexPointer(0);\n    numFixedVertices = igeom2D->getNumberOfVertices();\n  }\n  else if(IGeometry3D::Pointer igeom3D = std::dynamic_pointer_cast<IGeometry3D>(fixedGeom))\n  {\n    fixedPointsPtr = igeom3D->getVertexPointer(0);\n    numFixedVertices = igeom3D->getNumberOfVertices();\n  }\n  else if(VertexGeom::Pointer vertex = std::dynamic_pointer_cast<VertexGeom>(fixedGeom))\n  {\n    fixedPointsPtr = vertex->getVertexPointer(0);\n    numFixedVertices = vertex->getNumberOfVertices();\n  }\n  else if(EdgeGeom::Pointer edge = std::dynamic_pointer_cast<EdgeGeom>(fixedGeom))\n  {\n    fixedPointsPtr = edge->getVertexPointer(0);\n    numFixedVertices = edge->getNumberOfVertices();\n  }\n\n  // Eigen does best with things in column major, but we'll ultimately want\n  // the matrix as row major; perform the actual computation in column\n  // major and then transpose when we're ready to move it into a DataArray\n  typedef Eigen::Matrix<float, 3, Eigen::Dynamic, Eigen::ColMajor> PointCloud;\n  typedef Eigen::Matrix<float, 4, 4, Eigen::ColMajor> UmeyamaTransform;\n\n  // Map our DataArray pointers directly to Eigen objects in memory to avoid making copies\n  Eigen::Map<PointCloud> moving(movingPointsPtr, 3, numMovingVertices);\n  Eigen::Map<PointCloud> fixed(fixedPointsPtr, 3, numFixedVertices);\n\n  UmeyamaTransform transformMatrix = Eigen::umeyama(moving, fixed, m_UseScaling);\n\n  // The matrix is in column major, transpose it in place to make it row major\n  transformMatrix.transposeInPlace();\n  float* umeyamaArray = &transformMatrix(0);\n\n  // Copy the transformation matrix over to our DataArray\n  // We know the size will be exactly sixteen...\n  for(size_t i = 0; i < 16; i++)\n  {\n    m_TransformationMatrix[i] = umeyamaArray[i];\n  }\n\n}\n\n// -----------------------------------------------------------------------------\n//\n// -----------------------------------------------------------------------------\nAbstractFilter::Pointer ComputeUmeyamaTransform::newFilterInstance(bool copyFilterParameters) const\n{\n  ComputeUmeyamaTransform::Pointer filter = ComputeUmeyamaTransform::New();\n  if(copyFilterParameters)\n  {\n    copyFilterParameterInstanceVariables(filter.get());\n  }\n  return filter;\n}\n\n// -----------------------------------------------------------------------------\n//\n// -----------------------------------------------------------------------------\nconst QString ComputeUmeyamaTransform::getCompiledLibraryName() const\n{\n  return DREAM3DReviewConstants::DREAM3DReviewBaseName;\n}\n\n// -----------------------------------------------------------------------------\n//\n// -----------------------------------------------------------------------------\nconst QString ComputeUmeyamaTransform::getBrandingString() const\n{\n  return \"DREAM3DReview\";\n}\n\n// -----------------------------------------------------------------------------\n//\n// -----------------------------------------------------------------------------\nconst QString ComputeUmeyamaTransform::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// -----------------------------------------------------------------------------\nconst QString ComputeUmeyamaTransform::getGroupName() const\n{\n  return DREAM3DReviewConstants::FilterGroups::DREAM3DReviewFilters;\n}\n\n// -----------------------------------------------------------------------------\n//\n// -----------------------------------------------------------------------------\nconst QUuid ComputeUmeyamaTransform::getUuid()\n{\n  return QUuid(\"{3192d494-d1ec-5ee7-a345-e9963f02aaab}\");\n}\n\n// -----------------------------------------------------------------------------\n//\n// -----------------------------------------------------------------------------\nconst QString ComputeUmeyamaTransform::getSubGroupName() const\n{\n  return DREAM3DReviewConstants::FilterSubGroups::RegistrationFilters;\n}\n\n// -----------------------------------------------------------------------------\n//\n// -----------------------------------------------------------------------------\nconst QString ComputeUmeyamaTransform::getHumanLabel() const\n{\n  return \"Compute Umeyama Transform\";\n}\n", "meta": {"hexsha": "d984affe28e51170e57ca662157959cde0831db4", "size": 16990, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "DREAM3DReviewFilters/ComputeUmeyamaTransform.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/ComputeUmeyamaTransform.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/ComputeUmeyamaTransform.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": 43.7886597938, "max_line_length": 213, "alphanum_fraction": 0.6447321954, "num_tokens": 3604, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6992544335934766, "lm_q2_score": 0.47657965106367595, "lm_q1q2_score": 0.33325043396670745}}
{"text": "/* tsne.cc\n   Jeremy Barnes, 15 January 2010\n   Copyright (c) 2010 Jeremy Barnes.  All rights reserved.\n\n   This file is part of MLDB. Copyright 2015 mldb.ai inc. All rights reserved.\n\n   Implementation of the t-SNE algorithm.\n*/\n\n#include \"tsne.h\"\n#include \"mldb/utils/distribution.h\"\n#include \"mldb/utils/distribution_ops.h\"\n#include \"mldb/utils/distribution_simd.h\"\n#include \"mldb/utils/vector_utils.h\"\n#include \"mldb/utils/pair_utils.h\"\n#include \"mldb/utils/lightweight_hash.h\"\n#include \"mldb/plugins/jml/algebra/matrix_ops.h\"\n#include \"mldb/arch/simd_vector.h\"\n#include \"mldb/arch/spinlock.h\"\n\n#include \"mldb/plugins/jml/algebra/lapack.h\"\n#include <cmath>\n#include <random>\n#include \"mldb/base/parallel.h\"\n#include \"mldb/base/thread_pool.h\"\n#include <boost/timer.hpp>\n#include \"mldb/arch/timers.h\"\n#if MLDB_INTEL_ISA\n# include \"mldb/arch/sse2.h\"\n# include \"mldb/arch/sse2_log.h\"\n#endif\n#include \"mldb/arch/cache.h\"\n#include \"mldb/base/scope.h\"\n#include \"mldb/utils/environment.h\"\n#include \"mldb/utils/quadtree.h\"\n#include \"mldb/utils/vantage_point_tree.h\"\n#include <fstream>\n#include <functional>\n\nusing namespace std;\n\nnamespace ML {\n\ntemplate<typename Float>\nstruct V2D_Job {\n    const boost::multi_array<Float, 2> & X;\n    boost::multi_array<Float, 2> & D;\n    const Float * sum_X;\n    int i0, i1;\n    \n    V2D_Job(const boost::multi_array<Float, 2> & X,\n            boost::multi_array<Float, 2> & D,\n            const Float * sum_X,\n            int i0, int i1)\n        : X(X), D(D), sum_X(sum_X), i0(i0), i1(i1)\n    {\n    }\n\n    void operator () ()\n    {\n        int d = X.shape()[1];\n        \n        if (d == 2) {\n            unsigned i = i0;\n            for (;  i + 4 <= i1;  i += 4) {\n                D[i + 0][i + 0] = 0.0f;\n                D[i + 1][i + 1] = 0.0f;\n                D[i + 2][i + 2] = 0.0f;\n                D[i + 3][i + 3] = 0.0f;\n                \n                for (unsigned j = 0;  j < i;  ++j) {\n                    for (unsigned ii = 0;  ii < 4;  ++ii) {\n                        Float XXT\n                            = (X[i + ii][0] * X[j][0])\n                            + (X[i + ii][1] * X[j][1]);\n                        Float val = sum_X[i + ii] + sum_X[j] - 2.0f * XXT;\n                        D[i + ii][j] = val;\n                    }\n                }\n                \n                // finish off the diagonal\n                for (unsigned ii = 0;  ii < 4;  ++ii) {\n                    for (unsigned j = i;  j < i + ii;  ++j) {\n                        Float XXT\n                            = (X[i + ii][0] * X[j][0])\n                            + (X[i + ii][1] * X[j][1]);\n                        Float val = sum_X[i + ii] + sum_X[j] - 2.0f * XXT;\n                        D[i + ii][j] = val;\n                    }\n                }\n            }\n            for (;  i < i1;  ++i) {\n                D[i][i] = 0.0f;\n                \n                for (unsigned j = 0;  j < i;  ++j) {\n                    Float XXT = (X[i][0] * X[j][0]) + (X[i][1]) * (X[j][1]);\n                    Float val = sum_X[i] + sum_X[j] - 2.0f * XXT;\n                    D[i][j] = val;\n                }\n            }\n        }\n        else if (d < 8) {\n            for (unsigned i = i0;  i < i1;  ++i) {\n                D[i][i] = 0.0f;\n                for (unsigned j = 0;  j < i;  ++j) {\n                    float XXT = 0.0;\n                    for (unsigned k = 0;  k < d;  ++k)\n                        XXT += X[i][k] * X[j][k];\n                    \n                    Float val = sum_X[i] + sum_X[j] - 2.0f * XXT;\n                    D[i][j] = val;\n                }\n            }\n        }\n        else {\n            for (unsigned i = i0;  i < i1;  ++i) {\n                D[i][i] = 0.0f;\n                for (unsigned j = 0;  j < i;  ++j) {\n                    // accum in double precision for accuracy\n                    Float XXT = SIMD::vec_dotprod_dp(&X[i][0], &X[j][0], d);\n                    Float val = sum_X[i] + sum_X[j] - 2.0f * XXT;\n                    D[i][j] = val;\n                }\n            }\n        }\n    }\n};\n\ntemplate<typename Float>\nvoid\nvectors_to_distances(const boost::multi_array<Float, 2> & X,\n                     boost::multi_array<Float, 2> & D,\n                     bool fill_upper)\n{\n    // again, ||y_i - y_j||^2 \n    //     = sum_d ( y_id - y_jd )^2\n    //     = sum_d ( y_id^2 + y_jd^2 - 2 y_id y_jd)\n    //     = sum_d ( y_id^2) + sum_d(y_jd^2) - 2 sum_d(y_id y_jd)\n    //     = ||y_i||^2 + ||y_j||^2 - 2 sum_d(y_id y_jd)\n    \n    int n = X.shape()[0];\n\n    if (D.shape()[0] != n || D.shape()[1] != n)\n        throw Exception(\"D matrix should be square with (n x n) shape\");\n    \n    int d = X.shape()[1];\n\n    distribution<Float> sum_X(n);\n\n    if (d < 16) {\n        for (unsigned i = 0;  i < n;  ++i) {\n            double total = 0.0;  // accum in double precision for accuracy\n            for (unsigned j = 0;  j < d;  ++j)\n                total += X[i][j] * X[i][j];\n            sum_X[i] = total;\n        }\n    }\n    else {\n        for (unsigned i = 0;  i < n;  ++i)\n            sum_X[i] = SIMD::vec_dotprod_dp(&X[i][0], &X[i][0], d);\n    }\n    \n    int chunk_size = 256;\n    auto onJob = [&] (size_t i0, size_t i1)\n        {\n            V2D_Job<Float>(X, D, &sum_X[0], i0, i1)();\n        };\n    \n    // TODO: in original version, we did chunks in reverse order.\n    MLDB::parallelMapChunked(0, n, chunk_size, onJob);\n\n    if (fill_upper)\n        copy_lower_to_upper(D);\n}\n\nvoid\nvectors_to_distances(const boost::multi_array<float, 2> & X,\n                     boost::multi_array<float, 2> & D,\n                     bool fill_upper)\n{\n    return vectors_to_distances<float>(X, D, fill_upper);\n}\n\nvoid\nvectors_to_distances(const boost::multi_array<double, 2> & X,\n                     boost::multi_array<double, 2> & D,\n                     bool fill_upper)\n{\n    return vectors_to_distances<double>(X, D, fill_upper);\n}\n\ntemplate<typename Float>\ndouble\nperplexity(const distribution<Float> & p)\n{\n    double total = 0.0;\n    for (unsigned i = 0;  i < p.size();  ++i)\n        if (p[i] != 0.0) total -= p[i] * log(p[i]);\n    return std::exp(total);\n}\n\n/** Compute the perplexity and the P for a given value of beta. */\ntemplate<typename Float>\nstd::pair<double, distribution<Float> >\nperplexity_and_prob(const distribution<Float> & D, double beta = 1.0,\n                    int i = -1)\n{\n    distribution<Float> P(D.size());\n    SIMD::vec_exp(&D[0], -beta, &P[0], D.size());\n    if (i != -1) P[i] = 0;\n    double tot = P.total();\n\n    if (!isfinite(tot) || tot == 0) {\n        // Perplexity is impossible, since no weights\n        std::fill(P.begin(), P.end(), 1.0);\n        if (i != -1)\n            P.at(i) = 0;\n        P.normalize();\n        return make_pair(INFINITY, P);\n#if 1\n        cerr << \"beta = \" << beta << endl;\n        cerr << \"D = \" << D << endl;\n        cerr << \"tot = \" << tot << endl;\n        cerr << \"i = \" << i << endl;\n        cerr << \"P = \" << P << endl;\n#endif\n        throw Exception(\"non-finite total for perplexity\");\n    }\n\n    double H = log(tot) + beta * D.dotprod(P) / tot;\n    P *= 1.0 / tot;\n\n    if (!isfinite(P.total())) {\n#if 1\n        cerr << \"beta = \" << beta << endl;\n        cerr << \"D = \" << D << endl;\n        cerr << \"tot = \" << tot << endl;\n        cerr << \"i = \" << i << endl;\n#endif\n        throw Exception(\"non-finite total for perplexity\");\n    }\n\n\n    return make_pair(H, P);\n}\n\nstd::pair<double, distribution<float> >\nperplexity_and_prob(const distribution<float> & D, double beta,\n                    int i)\n{\n    return perplexity_and_prob<float>(D, beta, i);\n}\n\nstd::pair<double, distribution<double> >\nperplexity_and_prob(const distribution<double> & D, double beta,\n                    int i)\n{\n    return perplexity_and_prob<double>(D, beta, i);\n}\n\n\n/** Calculate the beta for a single point.\n    \n    \\param Di     The i-th row of the D matrix, for which we want to calculate\n                  the probabilities.\n    \\param i      Which row number it is.\n\n    \\returns      The i-th row of the P matrix, which has the distances in D\n                  converted to probabilities with the given perplexity.\n */\nstd::pair<distribution<float>, double>\nbinary_search_perplexity(const distribution<float> & Di,\n                         double required_perplexity,\n                         int i,\n                         double tolerance)\n{\n    double betamin = -INFINITY, betamax = INFINITY;\n    double beta = 1.0;\n\n    distribution<float> P;\n    double log_perplexity;\n    double log_required_perplexity = log(required_perplexity);\n\n    std::tie(log_perplexity, P) = perplexity_and_prob(Di, beta, i);\n\n    if (log_perplexity == INFINITY) {\n        // Ill conditioned, there is nothing to do\n        return make_pair(P, INFINITY);\n    }\n\n    bool verbose = false;\n\n    if (verbose)\n        cerr << \"iter currperp targperp     diff toleranc   betamin     beta  betamax\" << endl;\n    \n    for (unsigned iter = 0;  iter != 50;  ++iter) {\n        if (verbose) \n            cerr << format(\"%4d %8.4f %8.4f %8.4f %8.4f  %8.4f %8.4f %8.4f\\n\",\n                           iter,\n                           log_perplexity, log_required_perplexity,\n                           fabs(log_perplexity - log_required_perplexity),\n                           tolerance,\n                           betamin, beta, betamax);\n        \n        if (fabs(log_perplexity - log_required_perplexity) < tolerance)\n            break;\n\n        if (log_perplexity > log_required_perplexity) {\n            betamin = beta;\n            if (!isfinite(betamax))\n                beta *= 2;\n            else beta = (beta + betamax) * 0.5;\n        }\n        else {\n            betamax = beta;\n            if (!isfinite(betamin))\n                beta /= 2;\n            else beta = (beta + betamin) * 0.5;\n        }\n        \n        std::tie(log_perplexity, P) = perplexity_and_prob(Di, beta, i);\n    }\n\n    return make_pair(P, beta);\n}\n\nstruct Distance_To_Probabilities_Job {\n\n    boost::multi_array<float, 2> & D;\n    double tolerance;\n    double perplexity;\n    boost::multi_array<float, 2> & P;\n    distribution<float> & beta;\n    int i0;\n    int i1;\n\n    Distance_To_Probabilities_Job(boost::multi_array<float, 2> & D,\n                                  double tolerance,\n                                  double perplexity,\n                                  boost::multi_array<float, 2> & P,\n                                  distribution<float> & beta,\n                                  int i0,\n                                  int i1)\n        : D(D), tolerance(tolerance), perplexity(perplexity),\n          P(P), beta(beta), i0(i0), i1(i1)\n    {\n    }\n\n    void operator () ()\n    {\n        int n = D.shape()[0];\n\n        for (unsigned i = i0;  i < i1;  ++i) {\n            //cerr << \"i = \" << i << endl;\n            //if (i % 250 == 0)\n            //    cerr << \"P-values for point \" << i << \" of \" << n << endl;\n            \n            distribution<float> D_row(&D[i][0], &D[i][0] + n);\n            distribution<float> P_row;\n\n            try {\n                std::tie(P_row, beta[i])\n                    = binary_search_perplexity(D_row, perplexity, i, tolerance);\n            } catch (const std::exception & exc) {\n                P_row = D_row;\n                P_row[i] = 1000000;\n                P_row = (P_row == P_row.min());\n                std::fill(P_row.begin(), P_row.end(), 1.0);\n                P_row[i] = 0.0;\n                P_row.normalize();\n            }\n            \n            if (P_row.size() != n)\n                throw Exception(\"P_row has the wrong size\");\n            if (P_row[i] != 0.0) {\n                cerr << \"i = \" << i << endl;\n                //cerr << \"D_row = \" << D_row << endl;\n                //cerr << \"P_row = \" << P_row << endl;\n                cerr << \"P_row.total() = \" << P_row.total() << endl;\n                cerr << \"P_row[i] = \" << P_row[i] << endl;\n                throw Exception(\"P_row diagonal entry was not zero\");\n            }\n\n            std::copy(P_row.begin(), P_row.end(), &P[i][0]);\n        }\n    }\n};\n\n\n/* Given a matrix of distances, convert to probabilities */\nboost::multi_array<float, 2>\ndistances_to_probabilities(boost::multi_array<float, 2> & D,\n                           double tolerance,\n                           double perplexity)\n{\n    int n = D.shape()[0];\n    if (D.shape()[1] != n)\n        throw Exception(\"D is not square\");\n\n    boost::multi_array<float, 2> P(boost::extents[n][n]);\n    distribution<float> beta(n, 1.0);\n\n    int chunk_size = 256;\n\n    auto onChunk = [&] (size_t i0, size_t i1)\n        {\n            Distance_To_Probabilities_Job\n            (D, tolerance, perplexity, P, beta, i0, i1)();\n        };\n\n    MLDB::parallelMapChunked(0, n, chunk_size, onChunk);\n\n    cerr << \"mean sigma is \" << sqrt(1.0 / beta).mean() << endl;\n\n    return P;\n}\n\nboost::multi_array<float, 2>\npca(boost::multi_array<float, 2> & coords, int num_dims)\n{\n    // TODO: normalize the input coordinates (especially if it seems to be\n    // ill conditioned)\n\n    int nx = coords.shape()[0];\n    int nd = coords.shape()[1];\n\n    int nvalues = std::min(nd, nx);\n\n    int ndr = std::min(nvalues, num_dims);\n\n    if (ndr < num_dims)\n        throw Exception(\"svd_reduction: num_dims not low enough\");\n        \n    distribution<float> svalues(nvalues);\n    boost::multi_array<float, 2> lvectorsT(boost::extents[nvalues][nd]);\n    boost::multi_array<float, 2> rvectors(boost::extents[nx][nvalues]);\n\n    int res = LAPack::gesdd(\"S\", nd, nx,\n                            coords.data(), nd,\n                            &svalues[0],\n                            &lvectorsT[0][0], nd,\n                            &rvectors[0][0], nvalues);\n    \n    // If some vectors are singular, ignore them\n    // TODO: do...\n        \n    if (res != 0)\n        throw Exception(\"gesdd returned non-zero\");\n        \n    boost::multi_array<float, 2> result(boost::extents[nx][ndr]);\n    for (unsigned i = 0;  i < nx;  ++i)\n        std::copy(&rvectors[i][0], &rvectors[i][0] + ndr, &result[i][0]);\n\n    return result;\n}\n\ndouble calc_D_row(float * Di, int n)\n{\n    unsigned i = 0;\n\n    double total = 0.0;\n\n    if (false) ;\n#if MLDB_INTEL_ISA\n    else if (n >= 8) {\n        using namespace SIMD;\n\n        v2df rr = vec_splat(0.0);\n        \n        v4sf one = vec_splat(1.0f);\n\n        __builtin_prefetch(Di + i + 0, 1, 3);\n        __builtin_prefetch(Di + i + 16, 1, 3);\n        __builtin_prefetch(Di + i + 32, 1, 3);\n\n        for (; i + 16 <= n;  i += 16) {\n            __builtin_prefetch(Di + i + 48, 1, 3);\n\n            v4sf xxxx0 = _mm_loadu_ps(Di + i + 0);\n            v4sf xxxx1 = _mm_loadu_ps(Di + i + 4);\n            xxxx0      = xxxx0 + one;\n            xxxx1      = xxxx1 + one;\n            xxxx0      = one / xxxx0;\n            v4sf xxxx2 = _mm_loadu_ps(Di + i + 8);\n            xxxx1      = one / xxxx1;\n            _mm_storeu_ps(Di + i + 0, xxxx0);\n            xxxx2      = xxxx2 + one;\n            v2df xx0a, xx0b;  vec_f2d(xxxx0, xx0a, xx0b);\n            _mm_storeu_ps(Di + i + 4, xxxx1);\n            xx0a       = xx0a + xx0b;\n            rr         = rr + xx0a;\n            v4sf xxxx3 = _mm_loadu_ps(Di + i + 12);\n            v2df xx1a, xx1b;  vec_f2d(xxxx1, xx1a, xx1b);\n            xxxx2      = one / xxxx2;\n            xx1a       = xx1a + xx1b;\n            _mm_storeu_ps(Di + i + 8, xxxx2);\n            rr         = rr + xx1a;\n            v2df xx2a, xx2b;  vec_f2d(xxxx2, xx2a, xx2b);\n            xxxx3      = xxxx3 + one;\n            xx2a       = xx2a + xx2b;\n            xxxx3      = one / xxxx3;\n            rr         = rr + xx2a;\n            v2df xx3a, xx3b;  vec_f2d(xxxx3, xx3a, xx3b);\n            _mm_storeu_ps(Di + i + 12, xxxx3);\n            xx3a       = xx3a + xx3b;\n            rr         = rr + xx3a;\n        }\n\n        for (; i + 4 <= n;  i += 4) {\n            v4sf xxxx0 = _mm_loadu_ps(Di + i + 0);\n            xxxx0      = xxxx0 + one;\n            xxxx0      = one / xxxx0;\n            _mm_storeu_ps(Di + i + 0, xxxx0);\n\n            v2df xx0a, xx0b;\n            vec_f2d(xxxx0, xx0a, xx0b);\n\n            rr      = rr + xx0a;\n            rr      = rr + xx0b;\n        }\n\n        double results[2];\n        *(v2df *)results = rr;\n\n        total = (results[0] + results[1]);\n    }\n#endif // MLDB_INTEL_ISA\n    \n    for (;  i < n;  ++i) {\n        Di[i] = 1.0f / (1.0f + Di[i]);\n        total += Di[i];\n    }\n\n    return total;\n}\n\nnamespace {\n\nEnvOption<bool> PROFILE_TSNE(\"PROFILE_TSNE\", false);\n\ndouble t_v2d = 0.0, t_D = 0.0, t_dY = 0.0, t_update = 0.0;\ndouble t_recenter = 0.0, t_cost = 0.0, t_PmQxD = 0.0, t_clu = 0.0;\ndouble t_stiffness = 0.0;\nstruct AtEnd {\n    ~AtEnd()\n    {\n        if (!PROFILE_TSNE) return;\n\n        cerr << \"tsne core profile:\" << endl;\n        cerr << \"  v2d:        \" << t_v2d << endl;\n        cerr << \"  stiffness:\" << t_stiffness << endl;\n        cerr << \"    D         \" << t_D << endl;\n        cerr << \"    (P-Q)D    \" << t_PmQxD << endl;\n        cerr << \"    clu       \" << t_clu << endl;\n        cerr << \"  dY:         \" << t_dY << endl;\n        cerr << \"  update:     \" << t_update << endl;\n        cerr << \"  recenter:   \" << t_recenter << endl;\n        cerr << \"  cost:       \" << t_cost << endl;\n    }\n} atend;\n\n} // file scope\n\nstruct Calc_D_Job {\n\n    boost::multi_array<float, 2> & D;\n    int i0;\n    int i1;\n    double * d_totals;\n\n    Calc_D_Job(boost::multi_array<float, 2> & D,\n               int i0,\n               int i1,\n               double * d_totals)\n        : D(D), i0(i0), i1(i1), d_totals(d_totals)\n    {\n    }\n\n    void operator () ()\n    {\n        for (unsigned i = i0;  i < i1;  ++i) {\n            d_totals[i] = 2.0 * calc_D_row(&D[i][0], i);\n            D[i][i] = 0.0f;\n        }\n    }\n};\n\ndouble calc_stiffness_row(float * Di, const float * Pi, float qfactor,\n                          float min_prob, int n, bool calc_costs)\n{\n    double cost = 0.0;\n\n    unsigned i = 0;\n\n    if (false) ;\n\n#if MLDB_INTEL_ISA\n    else if (true) {\n        using namespace SIMD;\n\n        v4sf mmmm = vec_splat(min_prob);\n        v4sf ffff = vec_splat(qfactor);\n\n        v2df total = vec_splat(0.0);\n\n        for (; i + 4 <= n;  i += 4) {\n\n            v4sf dddd0 = _mm_loadu_ps(Di + i + 0);\n            v4sf pppp0 = _mm_loadu_ps(Pi + i + 0);\n            v4sf qqqq0 = __builtin_ia32_maxps(mmmm, dddd0 * ffff);\n            v4sf ssss0 = (pppp0 - qqqq0) * dddd0;\n            _mm_storeu_ps(Di + i + 0, ssss0);\n            if (MLDB_LIKELY(!calc_costs)) continue;\n\n            v4sf pqpq0  = pppp0 / qqqq0;\n            v4sf lpq0   = sse2_logf_unsafe(pqpq0);\n            v4sf cccc0  = pppp0 * lpq0;\n            cccc0 = cccc0 + cccc0;\n\n            v2df cc0a, cc0b;\n            vec_f2d(cccc0, cc0a, cc0b);\n\n            total   = total + cc0a;\n            total   = total + cc0b;\n        }\n\n        double results[2];\n        *(v2df *)results = total;\n        \n        cost = results[0] + results[1];\n    }\n#endif // MLDB_INTEL_ISA\n\n    for (;  i < n;  ++i) {\n        float d = Di[i];\n        float p = Pi[i];\n        float q = std::max(min_prob, d * qfactor);\n        Di[i] = (p - q) * d;\n        if (calc_costs) cost += 2.0 * p * logf(p / q);\n    }\n\n    return cost;\n}\n\nstruct Calc_Stiffness_Job {\n\n    boost::multi_array<float, 2> & D;\n    const boost::multi_array<float, 2> & P;\n    float min_prob;\n    float qfactor;\n    double * costs;\n    int i0, i1;\n\n    Calc_Stiffness_Job(boost::multi_array<float, 2> & D,\n                       const boost::multi_array<float, 2> & P,\n                       float min_prob,\n                       float qfactor,\n                       double * costs,\n                       int i0, int i1)\n        : D(D), P(P), min_prob(min_prob),\n          qfactor(qfactor), costs(costs), i0(i0), i1(i1)\n    {\n    }\n\n    void operator () ()\n    {\n        for (unsigned i = i0;  i < i1;  ++i) {\n            double cost \n                = calc_stiffness_row(&D[i][0], &P[i][0],\n                                     qfactor, min_prob, i,\n                                     costs);\n            if (costs) costs[i] = cost;\n        }\n    }\n};\n\ndouble tsne_calc_stiffness(boost::multi_array<float, 2> & D,\n                           const boost::multi_array<float, 2> & P,\n                           float min_prob,\n                           bool calc_cost)\n{\n    boost::timer t;\n\n    int n = D.shape()[0];\n    if (D.shape()[1] != n)\n        throw Exception(\"D has wrong shape\");\n\n    if (P.shape()[0] != n || P.shape()[1] != n)\n        throw Exception(\"P has wrong shape\");\n\n    double d_totals[n];\n\n    int chunk_size = 256;\n        \n    auto onChunk = [&] (size_t i0, size_t i1)\n        {\n            Calc_D_Job(D, i0, i1, d_totals)();\n        };\n\n    // TODO: chunks in reverse?\n    MLDB::parallelMapChunked(0, n, chunk_size, onChunk);\n\n    double d_total_offdiag = SIMD::vec_sum(d_totals, n);\n\n    t_D += t.elapsed();  t.restart();\n    \n    // Cost accumulated for each row\n    double row_costs[n];\n\n    // Q matrix: q_{i,j} = d_{ij} / sum_{k != l} d_{kl}\n    float qfactor = 1.0 / d_total_offdiag;\n\n    int chunk_size2 = 64;\n\n    auto onChunk2 = [&] (size_t i0, size_t i1)\n        {\n            Calc_Stiffness_Job\n            (D, P, min_prob, qfactor,\n             (calc_cost ? row_costs : (double *)0), i0, i1)();\n        };\n\n    // TODO: chunks in reverse?\n    MLDB::parallelMapChunked(0, n, chunk_size2, onChunk2);\n\n    double cost = 0.0;\n    if (calc_cost) cost = SIMD::vec_sum(row_costs, n);\n\n    t_PmQxD += t.elapsed();  t.restart();\n    \n    copy_lower_to_upper(D);\n    \n    t_clu += t.elapsed();  t.restart();\n\n    return cost;\n}\n\ninline void\ncalc_dY_rows_2d(boost::multi_array<float, 2> & dY,\n                const boost::multi_array<float, 2> & PmQxD,\n                const boost::multi_array<float, 2> & Y,\n                int i, int n)\n{\n#if MLDB_INTEL_ISA\n    using namespace SIMD;\n\n    v4sf totals01 = vec_splat(0.0f), totals23 = totals01;\n    v4sf four = vec_splat(4.0f);\n\n    for (unsigned j = 0;  j < n;  ++j) {\n        //v4sf ffff = { PmQxD[i + 0][j], PmQxD[i + 1][j],\n        //              PmQxD[i + 2][j], PmQxD[i + 3][j] };\n        // TODO: expand inplace\n\n        v4sf ffff01 = { PmQxD[i + 0][j], PmQxD[i + 0][j],\n                        PmQxD[i + 1][j], PmQxD[i + 1][j] };\n        v4sf ffff23 = { PmQxD[i + 2][j], PmQxD[i + 2][j],\n                        PmQxD[i + 3][j], PmQxD[i + 3][j] };\n\n        // TODO: load once and shuffle into position\n        v4sf yjyj   = { Y[j][0], Y[j][1], Y[j][0], Y[j][1] };\n\n        ffff01 = ffff01 * four;\n        ffff23 = ffff23 * four;\n        \n        v4sf yi01   = _mm_loadu_ps(&Y[i][0]);\n        v4sf yi23   = _mm_loadu_ps(&Y[i + 2][0]);\n\n        v4sf xxxx01 = ffff01 * (yi01 - yjyj);\n        v4sf xxxx23 = ffff23 * (yi23 - yjyj);\n        \n        totals01 += xxxx01;\n        totals23 += xxxx23;\n    }\n\n    _mm_storeu_ps(&dY[i][0], totals01);\n    _mm_storeu_ps(&dY[i + 2][0], totals23);\n\n#else // MLDB_INTEL_ISA\n    enum { b = 4 };\n\n    float totals[b][2];\n    for (unsigned ii = 0;  ii < b;  ++ii)\n        totals[ii][0] = totals[ii][1] = 0.0f;\n            \n    for (unsigned j = 0;  j < n;  ++j) {\n        float Yj0 = Y[j][0];\n        float Yj1 = Y[j][1];\n        \n        for (unsigned ii = 0;  ii < b;  ++ii) {\n            float factor = 4.0f * PmQxD[i + ii][j];\n            totals[ii][0] += factor * (Y[i + ii][0] - Yj0);\n            totals[ii][1] += factor * (Y[i + ii][1] - Yj1);\n        }\n    }\n    \n    for (unsigned ii = 0;  ii < b;  ++ii) {\n        dY[i + ii][0] = totals[ii][0];\n        dY[i + ii][1] = totals[ii][1];\n    }\n#endif // MLDB_INTEL_ISA\n}\n\ninline void\ncalc_dY_row_2d(float * dYi, const float * PmQxDi,\n               const boost::multi_array<float, 2> & Y,\n               int i,\n               int n)\n{\n    float total0 = 0.0f, total1 = 0.0f;\n    for (unsigned j = 0;  j < n;  ++j) {\n        float factor = 4.0f * PmQxDi[j];\n        total0 += factor * (Y[i][0] - Y[j][0]);\n        total1 += factor * (Y[i][1] - Y[j][1]);\n    }\n    \n    dYi[0] = total0;\n    dYi[1] = total1;\n}\n\n\nstruct Calc_Gradient_Job {\n    boost::multi_array<float, 2> & dY;\n    const boost::multi_array<float, 2> & Y;\n    const boost::multi_array<float, 2> & PmQxD;\n    int i0, i1;\n\n    Calc_Gradient_Job(boost::multi_array<float, 2> & dY,\n                      const boost::multi_array<float, 2> & Y,\n                      const boost::multi_array<float, 2> & PmQxD,\n                      int i0,\n                      int i1)\n        : dY(dY),\n          Y(Y),\n          PmQxD(PmQxD),\n          i0(i0),\n          i1(i1)\n    {\n    }\n    \n    void operator () ()\n    {\n        int n = Y.shape()[0];\n        int d = Y.shape()[1];\n\n        if (d == 2) {\n            unsigned i = i0;\n            \n            for (;  i + 4 <= i1;  i += 4)\n                calc_dY_rows_2d(dY, PmQxD, Y, i, n);\n            \n            for (; i < i1;  ++i)\n                calc_dY_row_2d(&dY[i][0], &PmQxD[i][0], Y, i, n);\n        }\n        else {\n            for (unsigned i = i0;  i < i1;  ++i) {\n                for (unsigned k = 0;  k < d;  ++k) {\n                    float Yik = Y[i][k];\n                    float total = 0.0;\n                    for (unsigned j = 0;  j < n;  ++j) {\n                        float factor = 4.0f * PmQxD[i][j];\n                        float Yjk = Y[j][k];\n                        total += factor * (Yik - Yjk);\n                    }\n                    dY[i][k] = total;\n                }\n            }\n        }\n    }\n};\n\n\nvoid tsne_calc_gradient(boost::multi_array<float, 2> & dY,\n                        const boost::multi_array<float, 2> & Y,\n                        const boost::multi_array<float, 2> & PmQxD)\n{\n    // Gradient\n    // Implements formula 5 in (Van der Maaten and Hinton, 2008)\n    // dC/dy_i = 4 * sum_j ( (p_ij - q_ij)(y_i - y_j)d_ij )\n\n    \n    int n = Y.shape()[0];\n    int d = Y.shape()[1];\n    \n    if (dY.shape()[0] != n || dY.shape()[1] != d)\n        throw Exception(\"dY matrix has wrong shape\");\n\n    if (PmQxD.shape()[0] != n || PmQxD.shape()[1] != n)\n        throw Exception(\"PmQxD matrix has wrong shape\");\n\n    int chunk_size = 64;\n        \n    auto doJob = [&] (size_t i0, size_t i1)\n        {\n            Calc_Gradient_Job(dY, Y, PmQxD, i0, i1)();\n        };\n\n    MLDB::parallelMapChunked(0, n, chunk_size, doJob);\n}\n\nvoid tsne_update(boost::multi_array<float, 2> & Y,\n                 boost::multi_array<float, 2> & dY,\n                 boost::multi_array<float, 2> & iY,\n                 boost::multi_array<float, 2> & gains,\n                 bool first_iter,\n                 float momentum,\n                 float eta,\n                 float min_gain)\n{\n    int n = Y.shape()[0];\n    int d = Y.shape()[1];\n\n    // Implement scheme in Jacobs, 1988.  If we go in the same direction as\n    // last time, we increase the learning speed of the parameter a bit.\n    // If on the other hand the direction changes, we reduce exponentially\n    // the rate.\n    \n    for (unsigned i = 0;  !first_iter && i < n;  ++i) {\n        // We use != here as we gradients in dY are the negatives of what\n        // we want.\n        for (unsigned j = 0;  j < d;  ++j) {\n            if (dY[i][j] * iY[i][j] < 0.0f)\n                gains[i][j] = gains[i][j] + 0.2f;\n            else gains[i][j] = gains[i][j] * 0.8f;\n            gains[i][j] = std::max(min_gain, gains[i][j]);\n        }\n    }\n\n    for (unsigned i = 0;  i < n;  ++i)\n        for (unsigned j = 0;  j < d;  ++j)\n            iY[i][j] = momentum * iY[i][j] - (eta * gains[i][j] * dY[i][j]);\n    Y = Y + iY;\n}\n    \ntemplate<typename Float>\nvoid recenter_about_origin(boost::multi_array<Float, 2> & Y)\n{\n    int n = Y.shape()[0];\n    int d = Y.shape()[1];\n\n    // Recenter Y values about the origin\n    double Y_means[d];\n    std::fill(Y_means, Y_means + d, 0.0);\n    for (unsigned i = 0;  i < n;  ++i)\n        for (unsigned j = 0;  j < d;  ++j)\n            Y_means[j] += Y[i][j];\n    \n    Float n_recip = 1.0f / n;\n    \n    for (unsigned i = 0;  i < n;  ++i)\n        for (unsigned j = 0;  j < d;  ++j)\n            Y[i][j] -= Y_means[j] * n_recip;\n}\n\nboost::multi_array<float, 2>\ntsne_init(int nx, int nd, int randomSeed)\n{\n    mt19937 rng;\n    if (randomSeed)\n        rng.seed(randomSeed);\n    normal_distribution<float> norm;\n\n    std::function<double()> randn(std::bind(norm, rng));\n\n    boost::multi_array<float, 2> Y(boost::extents[nx][nd]);\n    for (unsigned i = 0;  i < nx;  ++i)\n        for (unsigned j = 0;  j < nd;  ++j)\n            Y[i][j] = 0.0001 * randn();\n\n    return Y;\n}\n\nboost::multi_array<float, 2>\ntsne(const boost::multi_array<float, 2> & probs,\n     int num_dims,\n     const TSNE_Params & params,\n     const TSNE_Callback & callback)\n{\n    int n = probs.shape()[0];\n    if (n != probs.shape()[1])\n        throw Exception(\"probabilities were the wrong shape\");\n\n    int d = num_dims;\n\n    // Coordinates\n    boost::multi_array<float, 2> Y = tsne_init(n, d, params.randomSeed);\n\n    // Symmetrize and probabilize P\n    boost::multi_array<float, 2> P = probs + transpose(probs);\n\n    // TODO: symmetric so only need to total the upper diagonal\n    double sumP = 0.0;\n    for (unsigned i = 0;  i < n;  ++i)\n        sumP += 2.0 * SIMD::vec_sum_dp(&P[i][0], i);\n    \n    // Factor that P should be multiplied by in all calculations\n    // We boost it by 4 in early iterations to force the clusters to be\n    // spread apart\n    float pfactor = 4.0 / sumP;\n\n    // TODO: do we need this?   P = Math.maximum(P, 1e-12);\n    for (unsigned i = 0;  i < n;  ++i)\n        for (unsigned j = 0;  j < n;  ++j)\n            P[i][j] = std::max((i != j) * pfactor * P[i][j], 1e-12f);\n\n    double sump0 = 0.0;\n    for (unsigned i = 0;  i < n;  ++i) {\n        sump0 += P[0][i];\n    }\n\n    cerr << \"sump0 = \" << sump0 << endl;\n\n    double sump1 = 0.0;\n    for (unsigned i = 0;  i < n;  ++i) {\n        sump1 += P[1][i];\n    }\n\n    cerr << \"sump1 = \" << sump1 << endl;\n\n    Timer timer;\n\n    // Pseudo-distance array for reduced space.  Q = D * qfactor\n    boost::multi_array<float, 2> D(boost::extents[n][n]);\n\n    // Y delta\n    boost::multi_array<float, 2> dY(boost::extents[n][d]);\n\n    // Last change in Y; so that we can see if we're going in the same dir\n    boost::multi_array<float, 2> iY(boost::extents[n][d]);\n\n    // Per-variable factors to multiply the gradient by to improve convergence\n    boost::multi_array<float, 2> gains(boost::extents[n][d]);\n    std::fill(gains.data(), gains.data() + gains.num_elements(), 1.0f);\n\n\n    double cost = INFINITY;\n    double last_cost = INFINITY;\n    \n    if (callback\n        && !callback(-1, cost, \"init\")) return Y;\n\n    for (int iter = 0;  iter < params.max_iter;  ++iter) {\n\n        boost::timer t;\n\n        /*********************************************************************/\n        // Pairwise affinities Qij\n        // Implements formula 4 in (Van der Maaten and Hinton, 2008)\n        // q_{ij} = d_{ij} / sum_{k,l, k != l} d_{kl}\n        // where d_{ij} = 1 / (1 + ||y_i - y_j||^2)\n\n        // TODO: these will all be symmetric; we could save lots of work by\n        // using upper/lower diagonal matrices.\n\n        vectors_to_distances(Y, D, false /* fill_upper */);\n\n        t_v2d += t.elapsed();  t.restart();\n        \n        if (callback\n            && !callback(iter, cost, \"v2d\")) return Y;\n\n        // Do we calculate the cost?\n        bool calc_cost = iter < 10 || (iter + 1) % 10 == 0 || iter == params.max_iter - 1;\n        \n        double cost2 = tsne_calc_stiffness(D, P, params.min_prob, calc_cost);\n        if (calc_cost) {\n            last_cost = cost;\n            cost = cost2;\n\n            if (isfinite(cost) && cost == last_cost) {\n                // converged\n                break;\n            }\n                \n        }\n\n        if (callback\n            && !callback(iter, cost, \"stiffness\")) return Y;\n\n        t_stiffness += t.elapsed();  t.restart();\n\n        // D is now the stiffness\n        const boost::multi_array<float, 2> & stiffness = D;\n\n        \n        /*********************************************************************/\n        // Gradient\n        // Implements formula 5 in (Van der Maaten and Hinton, 2008)\n        // dC/dy_i = 4 * sum_j ( (p_ij - q_ij)(y_i - y_j)d_ij )\n\n        tsne_calc_gradient(dY, Y, stiffness);\n\n        t_dY += t.elapsed();  t.restart();\n\n        if (callback\n            && !callback(iter, cost, \"gradient\")) return Y;\n\n#if 0\n        cerr << \"C = \" << cost << endl;\n        for (unsigned x = 0;  x < 5;  ++x) {\n\n            cerr << \"P[\" << x << \"][0..5] = \"\n                 << P[x][0]\n                 << \" \" << P[x][1]\n                 << \" \" << P[x][2]\n                 << \" \" << P[x][3]\n                 << \" \" << P[x][4]\n                 << endl;\n\n            for (unsigned i = 0;  i < d;  ++i) {\n                    cerr << \"dY[\" << x << \"][\" << i << \"]: real \" << dY[x][i]\n                         << endl;\n                    cerr << \"Y = \" << Y[x][i] << endl;\n            }\n        }\n\n        return Y;\n#endif\n\n        /*********************************************************************/\n        // Update\n\n        float momentum = (iter < 20\n                          ? params.initial_momentum\n                          : params.final_momentum);\n\n        tsne_update(Y, dY, iY, gains, iter == 0, momentum, params.eta,\n                    params.min_gain);\n\n        if (callback\n            && !callback(iter, cost, \"update\")) return Y;\n\n        t_update += t.elapsed();  t.restart();\n\n\n        /*********************************************************************/\n        // Recenter about the origin\n\n        recenter_about_origin(Y);\n\n        if (callback\n            && !callback(iter, cost, \"recenter\")) return Y;\n\n        t_recenter += t.elapsed();  t.restart();\n\n\n        /*********************************************************************/\n        // Calculate cost\n\n        if ((iter + 1) % 100 == 0 || iter == params.max_iter - 1) {\n            cerr << format(\"iteration %4d cost %6.3f  \",\n                           iter + 1, cost)\n                 << timer.elapsed() << endl;\n            timer.restart();\n        }\n        \n        t_cost += t.elapsed();  t.restart();\n\n        // Stop lying about P values if we're finished\n        if (iter == 100) {\n            for (unsigned i = 0;  i < n;  ++i)\n                for (unsigned j = 0;  j < n;  ++j)\n                    P[i][j] *= 0.25f;\n        }\n    }\n\n    return Y;\n}\n\ndouble sqr(double d)\n{\n    return d * d;\n}\n\nfloat pythag_dist(const float * d1, const float * d2, int nd)\n{\n    float diff[nd];\n    SIMD::vec_add(d1, -1.0f, d2, diff, nd);\n    return sqrtf(SIMD::vec_dotprod_dp(diff, diff, nd));\n}\n\n#if 0\n    // (x - y)^2 = x^2 + y^2 - 2 x y\n\n    // Distance between neighbours.  Must satisfy the triangle inequality,\n    // so the sqrt is important.\n    auto dist1 = [&] (int x1, int x2)\n        {\n            return pythag_dist(&coords[x1][0], &coords[x2][0], nd);\n        };\n\n    float sum_dist[nx];\n    for (unsigned i = 0;  i < nx;  ++i) {\n        sum_dist[i] = SIMD::vec_dotprod_dp(&coords[i][0], &coords[i][0], nd);\n    }\n\n    // Distance between neighbours.  Must satisfy the triangle inequality,\n    // so the sqrt is important.\n    auto dist2 = [&] (int x1, int x2)\n        {\n            if (x1 == x2)\n                return 0.0f;\n            return sqrtf(sum_dist[x1] + sum_dist[x2]\n                         -2.0f * SIMD::vec_dotprod_dp(&coords[x1][0], &coords[x2][0], nd));\n        };\n\n    auto dist = [&] (int x1, int x2)\n        {\n            if (x2 < x1)\n                std::swap(x1, x2);\n\n            //float d1 = dist1(x1, x2);\n            float d2 = dist2(x1, x2);\n\n            //if (d1 != d2)\n            //    cerr << \"d1 = \" << d1 << \" d2 = \" << d2 << endl;\n            return d2;\n        };    \n\n    for (unsigned i = 0;  i < nd;  ++i)\n        if (!isfinite(newExampleCoords[i]))\n            throw MLDB::Exception(\"non-finite coordinates to sparseProbsFromCoords\");\n\n    // Distance between neighbours.  Must satisfy the triangle inequality,\n    // so the sqrt is important.\n    auto dist = [&] (int x2)\n        {\n            return pythag_dist(&newExampleCoords[0], &coords[x2][0], nd);\n        };\n\n#endif\n\nstd::vector<TsneSparseProbs>\nsparseProbsFromCoords(const std::function<float (int, int)> & dist,\n                      int nx,\n                      int numNeighbours,\n                      double perplexity,\n                      double tolerance,\n                      std::unique_ptr<VantagePointTreeT<int> > * treeOut)\n{\n    std::vector<int> examples;\n    for (unsigned i = 0;  i < nx;  ++i)\n        examples.push_back(i);\n\n    std::unique_ptr<VantagePointTreeT<int> > tree\n        (VantagePointTreeT<int>::create(examples, dist));\n\n    // For each one, find the numNeighbours nearest neighbours\n    std::vector<TsneSparseProbs> neighbours(nx);\n\n    Timer timer;\n\n    auto calcExample = [&] (int x)\n        {\n            auto exDist = [&] (int x2)\n            {\n                return dist(x, x2);\n            };\n\n            neighbours[x]\n                = sparseProbsFromCoords(exDist, *tree, numNeighbours,\n                                        perplexity, tolerance, x /* to remove */);\n\n            if (x && x % 10000 == 0)\n                cerr << \"done \" << x << \" in \" << timer.elapsed() << \"s\" << endl;\n        };\n\n    MLDB::parallelMap(0, nx, calcExample);\n\n    if (treeOut)\n        treeOut->reset(tree.release());\n\n    return neighbours;\n}\n\nTsneSparseProbs\nsparseProbsFromCoords(const std::function<float (int)> & dist,\n                      const VantagePointTreeT<int> & tree,\n                      int numNeighbours,\n                      double perplexity,\n                      double tolerance,\n                      int toRemove)\n{\n    TsneSparseProbs result;\n\n    // Check the variant\n    if (toRemove != -1)\n        ExcAssertEqual(dist(toRemove), 0);\n\n    // Find the nearest neighbours\n    std::vector<std::pair<float, int> > exNeighbours\n        = tree.search(dist, numNeighbours, INFINITY);\n\n#if 0\n    if (exNeighbours.empty()) {\n        cerr << \"no neighbours\" << endl;\n        cerr << \"nx = \" << coords.shape()[0];\n        cerr << \"nd = \" << nd << endl;\n\n        for (unsigned i = 0;  i < nd;  ++i) {\n            cerr << \" \" << newExampleCoords[i] << endl;\n        }\n\n        for (unsigned i = 0;  i < 10;  ++i) {\n            cerr << \"dist with \" << i << \" is \" << dist(i) << endl;\n        }\n    }\n#endif\n\n    for (unsigned i = 0;  i < exNeighbours.size();  ++i) {\n        // Ensure distance is finite\n        ExcAssert(isfinite(exNeighbours[i].first));\n\n        // Ensure that distance is positive\n        ExcAssertGreaterEqual(exNeighbours[i].first, 0.0);\n    }\n\n    // Remove the closest one if asked (this is needed when this example itself is\n    // in the tree\n    if (toRemove != -1) {\n        \n        if (exNeighbours.empty() || exNeighbours[0].first != 0.0) {\n            cerr << \"error finding neighbours for point \" << toRemove\n                 << endl;\n\n            cerr << \"dist to self is \" << dist(toRemove) << endl;\n\n            for (unsigned i = 0;  i < exNeighbours.size();  ++i) {\n                cerr << \"item \" << exNeighbours[i].second << \" with distance \"\n                     << dist(exNeighbours[i].second) << \" \" << exNeighbours[i].first\n                     << endl;\n            }\n        }\n\n        // Make sure that at least one neighbour was found\n        ExcAssertGreaterEqual(exNeighbours.size(), 1);\n\n        // Check that it really did have zero distance\n        ExcAssertEqual(exNeighbours[0].first, 0.0);\n\n        int foundAt = -1;\n        for (unsigned i = 0;  i < exNeighbours.size();  ++i) {\n            if (exNeighbours[i].second == toRemove) {\n                foundAt = i;\n                break;\n            }\n        }\n\n        // Check that it really did have zero distance\n        //ExcAssertEqual(exNeighbours[foundAt].first, 0.0);\n\n        if (foundAt == -1 && exNeighbours.back().first != 0.0) {\n            static std::mutex mutex;\n            std::unique_lock<std::mutex> guard(mutex);\n\n            cerr << \"toRemove = \" << toRemove << endl;\n            cerr << \"dist = \" << dist(toRemove) << endl;\n            cerr << \"distfirst = \" << dist(exNeighbours[0].second) << endl;\n            cerr << \"distsecond = \" << dist(exNeighbours[1].second) << endl;\n\n            //for (unsigned i = 0;  i < nd;  ++i)\n            //    cerr << \"incoords[\" << i << \"] = \"\n            //         << coords[0][i] << endl;\n            //for (unsigned i = 0;  i < nd;  ++i)\n            //    cerr << \"coords[\" << i << \"] = \"\n            //         << newExampleCoords[i] << endl;\n            for (unsigned i = 0;  i < exNeighbours.size();  ++i) {\n                cerr << \"  \" << i << \" neighbour \" << exNeighbours[i].second\n                     << \" dist \" << exNeighbours[i].first << endl;\n            }\n        }\n\n        if (exNeighbours.back().first != 0.0)\n            ExcAssertNotEqual(foundAt, -1);\n\n        if (foundAt != -1) {\n            exNeighbours.erase(exNeighbours.begin() + foundAt);\n        }\n    }\n\n    // Sort by index number\n    sort_on_second_ascending(exNeighbours);\n\n    // Extract into separate vectors\n    vector<int> indexes(exNeighbours.size());\n    distribution<float> distances(exNeighbours.size());\n\n    for (unsigned i = 0;  i < exNeighbours.size();  ++i) {\n        std::tie(distances[i], indexes[i]) = exNeighbours[i];\n    }\n \n    // Now calculate the perplexity.  Note that it operates on the\n    // square of distances.\n    std::tie(result.probs, std::ignore)\n        = binary_search_perplexity(distances * distances, perplexity, -1, tolerance);\n\n    // Threshold out zero probabilities.  This is better than removing\n    // them as if we remove, they don't become a constraint.\n    for (auto & p: result.probs) {\n        p = std::max(p, 1e-12f);\n    }\n\n    if ((result.probs == 0.0).any()) {\n        cerr << \"probs \" << result.probs << endl;\n        cerr << \"distances \" << distances << endl;\n        throw MLDB::Exception(\"zero probability from perplexity calculation\");\n    }\n\n    // put it back in the node\n    result.indexes = std::move(indexes);\n    \n    return result;\n}\n\nstd::vector<TsneSparseProbs>\nsymmetrize(const std::vector<TsneSparseProbs> & input)\n{\n    // 1.  Convert to a sparse matrix format, and accumulate\n    std::vector<LightweightHash<int, float> > probs(input.size());\n    \n    for (unsigned j = 0;  j < input.size();  ++j) {\n        const TsneSparseProbs & p = input[j];\n\n        // Check that the neighbour list is not empty\n        ExcAssert(!p.indexes.empty());\n\n        for (unsigned i = 0;  i < p.indexes.size();  ++i) {\n            // Check the input (we can't be our own neighbour)\n            ExcAssertNotEqual(p.indexes[i], j);\n\n            // Check that the probability is non-zero\n            ExcAssertGreater(p.probs[i], 0.0);\n\n            // +1 is to avoid inserting 0 into a lightweight hash\n            probs[p.indexes[i]][j + 1] += p.probs[i];\n            probs[j][p.indexes[i] + 1] += p.probs[i];\n        }\n    }\n    \n    // 2.  Convert back to TsneSparseProbs, normalizing as we go\n    std::vector<TsneSparseProbs> result(input.size());\n\n    for (unsigned j = 0;  j < input.size();  ++j) {\n        std::vector<std::pair<int, float> >\n            sorted(probs[j].begin(), probs[j].end());\n        std::sort(sorted.begin(), sorted.end());\n\n        for (auto & s: sorted) {\n            // Check that we haven't somehow become our own neighbour\n            ExcAssertNotEqual(s.first - 1, j);\n            result[j].indexes.push_back(s.first - 1);\n            result[j].probs.push_back(s.second / (2.0 * input.size()));\n        }\n    }\n\n    return result;\n}\n\nboost::multi_array<float, 2>\ntsneApproxFromCoords(const boost::multi_array<float, 2> & coords,\n                     int num_dims,\n                     const TSNE_Params & params,\n                     const TSNE_Callback & callback,\n                     std::unique_ptr<VantagePointTreeT<int> > * treeOut,\n                     std::unique_ptr<Quadtree> * qtreeOut)\n{\n    PythagDistFromCoords dist(coords);\n\n    std::vector<TsneSparseProbs> neighbours\n        = sparseProbsFromCoords(dist, dist.nx, params.numNeighbours,\n                                params.perplexity, params.tolerance, treeOut);\n\n    std::vector<TsneSparseProbs> symmetricNeighbours\n        = symmetrize(neighbours);\n    \n    boost::multi_array<float, 2> embedding\n        = tsneApproxFromSparse(symmetricNeighbours, num_dims, params, callback, qtreeOut);\n    \n    return embedding;\n}\n\nPythagDistFromCoords::\nPythagDistFromCoords(const boost::multi_array<float, 2> & coords)\n    : coords(coords), sum_dist(coords.shape()[0]),\n      nx(coords.shape()[0]), nd(coords.shape()[1])\n{\n    for (unsigned i = 0;  i < nx;  ++i) {\n        sum_dist[i] = SIMD::vec_dotprod_dp(&coords[i][0], &coords[i][0], nd);\n    }\n}\n\nfloat\nPythagDistFromCoords::\noperator () (int x1, int x2) const\n{\n    ExcAssertLess(x1, nx);\n    ExcAssertLess(x2, nx);\n\n    if (x1 == x2)\n        return 0.0f;\n    if (x2 < x1)\n        std::swap(x1, x2);\n    \n    float dist = sum_dist[x1] + sum_dist[x2]\n        -2.0f * SIMD::vec_dotprod_dp(&coords[x1][0], &coords[x2][0], nd);\n    if (dist < 0.0f)\n        dist = 0.0f;\n\n    return sqrtf(dist);\n}\n\n// Object we keep around to calculate the repulsive force, by iterating over the\n// quadtree.  We primarily use a separate object to avoid the overhead in passing\n// all of these parameters around.\nstruct CalcRepContext {\n    CalcRepContext(const distribution<float> & y,\n                   double * FrepZ,\n                   double & exampleZ,\n                   int & nodesTouched,\n                   int nd,\n                   bool exact,\n                   const std::function<void (const QuadtreeNode & node,\n                                             double qCellZ, const std::vector<int> & poi)> & onNode,\n                   const std::function<const QCoord & (int)> & getPointCoord,\n                   float minDistanceRatio)\n        : y(y), FrepZ(FrepZ), exampleZ(exampleZ), nodesTouched(nodesTouched),\n          nd(nd), exact(exact), onNode(onNode), getPointCoord(getPointCoord),\n          minDistanceRatio(minDistanceRatio)\n    {\n    }\n\n\n    const distribution<float> & y;\n    double * FrepZ;\n    double & exampleZ;\n    int & nodesTouched;\n    int nd;\n    bool exact;\n    const std::function<void (const QuadtreeNode & node,\n                              double qCellZ, const std::vector<int> & poi)> & onNode;\n\n    /// Used to get the coordinate of a point of interest passed in pointsInside\n    const std::function<const QCoord & (int)> & getPointCoord;\n\n    /// Minimum ratio of distance of current cell to distance of further cell to\n    /// skip calculation\n    float minDistanceRatio;\n\n    std::vector<int> NO_POINTS;\n\n    void calc(const QuadtreeNode & node,\n              int depth,\n              bool inside,\n              const std::vector<int> & pointsInside)\n    {\n\n        float com[nd];\n\n        ++nodesTouched;\n\n        float distSq = 0.0f;\n\n        int effectiveNumChildren = node.numChildren - inside;\n\n        if (effectiveNumChildren == 0) {\n\n            // If there is a point of interest that is exactly the same as\n            // y which is exactly the same as the child node, then we have\n            // to call onNode for the point of interest, with a distance of\n            // zero (and hence a Zq of 1 / (1 + 0) = 1).\n            if (!pointsInside.empty()) {\n                onNode(node, 1.0f, pointsInside);\n            }\n            return;\n        }\n\n        float ncr = node.recipNumChildren[inside];\n\n        if (nd == 2) {\n            com[0] = ((node.centerOfMass[0] - inside*y[0]) * ncr) - y[0];\n            com[1] = ((node.centerOfMass[1] - inside*y[1]) * ncr) - y[1];\n            distSq = com[0] * com[0] + com[1] * com[1];\n        }\n        else {\n            for (unsigned i = 0;  i < nd;  ++i) {\n                com[i] = ((node.centerOfMass[i] - inside*y[i]) * ncr) - y[i];\n                distSq += com[i] * com[i];\n            }\n        }\n\n        if (node.type == QuadtreeNode::TERMINAL\n            || effectiveNumChildren == 1\n            || (node.diag < minDistanceRatio * sqrtf(distSq) && !exact)) {\n\n            float qCellZ = 1.0f / (1.0f + distSq);\n\n#if 0\n            if (distSq == 0.0) {\n                cerr << \"DISTANCE OF ZERO\" << endl;\n                cerr << \"effectiveNumChildren = \"\n                     << effectiveNumChildren << endl;\n                cerr << \"node.numChildren = \" << node.numChildren\n                     << endl;\n                cerr << \"inside = \" << inside << endl;\n                cerr << \"node.mins = \" << node.mins << endl;\n                cerr << \"node.maxs = \" << node.maxs << endl;\n                cerr << \"node.center = \" << node.center << endl;\n                cerr << \"node.child = \" << node.child << endl;\n                cerr << \"point = \" << y << endl;\n            }\n#endif\n\n            exampleZ += effectiveNumChildren * qCellZ;\n\n            for (unsigned i = 0;  i < nd;  ++i) {\n                FrepZ[i] += effectiveNumChildren * com[i] * qCellZ * qCellZ;\n            }\n\n            if (onNode) {\n                onNode(node, qCellZ, pointsInside);\n            }\n\n            return;\n        }\n        \n        // If we have points we are bringing along for the ride, then split them\n        // by quadrant.\n        if (!pointsInside.empty()) {\n            std::vector<std::vector<int> > quadrantPoints(1 << nd);\n            for (int p: pointsInside) {\n                QCoord coord = getPointCoord(p);\n                int quad = node.quadrant(coord);\n                ExcAssert(node.quadrants[quad]);\n\n                if (!node.quadrants[quad]) {\n                    // Won't be recursed.  Handle here\n                    cerr << \"not recursed; coord = \" << coord << \" child\" << node.child\n                         << endl;\n                    float qCellZ = 1.0f / (1.0f + distSq);\n                    onNode(node, qCellZ, {p});\n                }\n                else {\n                    quadrantPoints[quad].push_back(p);\n                }\n            }\n\n            int quad = -1;\n            if (inside)\n                quad = node.quadrant(y);\n            for (unsigned i = 0;  i < (1 << nd);  ++i) {\n                if (node.quadrants[i])\n                    calc(*node.quadrants[i], depth + 1, i == quad, quadrantPoints[i]);\n                else\n                    ExcAssert(quadrantPoints[i].empty());\n            }\n        }\n        else {\n            int quad = -1;\n            if (inside)\n                quad = node.quadrant(y);\n            for (unsigned i = 0;  i < (1 << nd);  ++i)\n                if (node.quadrants[i])\n                    calc(*node.quadrants[i], depth + 1, i == quad, NO_POINTS);\n        }\n    }\n};\n\n// Used to traverse the quadtree for the Ys\nvoid calcRep(const QuadtreeNode & node,\n             int depth,\n             bool inside,\n             const distribution<float> & y,\n             double * FrepZ,\n             double & exampleZ,\n             int & nodesTouched,\n             int nd,\n             bool exact,\n             const std::function<void (const QuadtreeNode & node,\n                                       double qCellZ, const std::vector<int> & poi)> & onNode,\n             const std::vector<int> & pointsOfInterest,\n             const std::function<const QCoord & (int)> & getPointCoord,\n             float minDistanceRatio)\n{\n    CalcRepContext context(y, FrepZ, exampleZ, nodesTouched, nd, exact, onNode, getPointCoord,\n                           minDistanceRatio);\n    context.calc(node, depth, inside, pointsOfInterest);\n}\n\nboost::multi_array<float, 2>\ntsneApproxFromSparse(const std::vector<TsneSparseProbs> & exampleNeighbours,\n                     int num_dims,\n                     const TSNE_Params & params,\n                     const TSNE_Callback & callback,\n                     std::unique_ptr<Quadtree> * qtreeOut)\n{\n    // See van der Marten, 2013 http://arxiv.org/pdf/1301.3342.pdf\n    // Barnes-Hut-SNE\n\n    int nx = exampleNeighbours.size();\n    int nd = num_dims;\n\n    // Verify that no point is its own neighbour and that no probability is zero\n    for (unsigned j = 0;  j < nx;  ++j) {\n        if (exampleNeighbours[j].indexes.empty())\n            throw MLDB::Exception(\"tsneApproxFromSparse(): point %d has no\"\n                                \" neighbours\", j);\n        if (exampleNeighbours[j].indexes.size()\n            != exampleNeighbours[j].probs.size())\n            throw MLDB::Exception(\"tsneApproxFromSparse(): point %d index and \"\n                                \"probs sizes don't match: %zd != %zd\",\n                                exampleNeighbours[j].indexes.size(),\n                                exampleNeighbours[j].probs.size());\n\n        for (unsigned i = 0;  i < exampleNeighbours[j].indexes.size();  ++i) {\n            int index = exampleNeighbours[j].indexes[i];\n            //float prob = exampleNeighbours[j].probs[i];\n\n            if (index ==j)\n                throw MLDB::Exception(\"tsneApproxFromSparse: error in input: \"\n                                    \"point %d is its own neighbour\", j);\n            //if (prob == 0.0)\n            //    throw MLDB::Exception(\"tsneApproxFromSparse: error in input: point %d has \"\n            //                        \"zero probability\");\n        }\n    }\n\n    boost::multi_array<float, 2> Y = tsne_init(nx, nd, params.randomSeed);\n\n    // Do we force calculations to be made exactly?\n    bool forceExactSolution = false;\n    //forceExactSolution = true;\n\n    // Z * Frep\n    boost::multi_array<double, 2> FrepZ(boost::extents[nx][nd]);\n\n    // Y delta\n    boost::multi_array<float, 2> dY(boost::extents[nx][nd]);\n\n    // Last change in Y; so that we can see if we're going in the same dir\n    boost::multi_array<float, 2> iY(boost::extents[nx][nd]);\n\n    // Per-variable factors to multiply the gradient by to improve convergence\n    boost::multi_array<float, 2> gains(boost::extents[nx][nd]);\n    std::fill(gains.data(), gains.data() + gains.num_elements(), 1.0f);\n\n    boost::multi_array<double, 2> FattrApprox(boost::extents[nx][nd]);\n    boost::multi_array<double, 2> FrepApprox(boost::extents[nx][nd]);\n\n    boost::multi_array<float, 2> lastNormalizedY(boost::extents[nx][nd]);\n\n    double cost = INFINITY;\n    double last_cost = INFINITY;\n    \n    if (callback\n        && !callback(-1, cost, \"init\")) return Y;\n\n    Timer timer;\n\n    // As described in Hinton et al, start off with a total probability of 4, before moving\n    // back to 1 after 100 iterations.\n    float pFactor = 4.0;\n\n    //cerr << \"exampleNeighbours[0].indexes = \" << exampleNeighbours[0].indexes << endl;\n    //cerr << \"exampleNeighbours[0].probs = \" << exampleNeighbours[0].probs << endl;\n    //cerr << \"exampleNeighbours[0].probs.total() = \" << exampleNeighbours[0].probs.total() << endl;\n    //cerr << \"exampleNeighbours[0].probs.min() = \" << exampleNeighbours[0].probs.min() << endl;\n    //cerr << \"exampleNeighbours[0].probs.max() = \" << exampleNeighbours[0].probs.max() << endl;\n\n    //cerr << \"sump0 = \" << exampleNeighbours[0].probs.total() * pFactor << endl;\n    //cerr << \"sump1 = \" << exampleNeighbours[1].probs.total() * pFactor << endl;\n\n    std::unique_ptr<Quadtree> qtreePtr;\n\n    auto updateQtree = [&] () -> Quadtree &\n        {\n            // Find the bounding box for the quadtree\n            distribution<float> mins(nd), maxs(nd);\n\n            for (unsigned j = 0;  j < nx;  ++j) {\n                distribution<float> y(nd);\n                for (unsigned i = 0;  i < nd;  ++i)\n                    y[i] = Y[j][i];\n            \n                if (j == 0)\n                    mins = maxs = y;\n                else {\n                    y.min_max(mins, maxs);\n                }\n            }\n\n            // Create the quadtree for this iteration\n            QCoord minc(mins.begin(), mins.end()), maxc(maxs.begin(), maxs.end());\n\n            // Bounding boxes are open ended on the max side, so move to the next float\n            for (float & c: maxc) {\n                c = nextafterf(c, (float)INFINITY);\n            }\n\n            qtreePtr.reset(new Quadtree(minc, maxc));\n            Quadtree & qtree = *qtreePtr;\n\n            // Insert the values into the quadtree\n            for (unsigned i = 0;  i < nx;  ++i) {\n                QCoord coord(nd);\n                for (unsigned j = 0;  j < nd;  ++j) {\n                    coord[j] = Y[i][j];\n                }\n\n                qtree.insert(coord);\n            }\n        \n            int numNodes MLDB_UNUSED = qtree.root->finish();\n\n            return qtree;\n        };\n    \n    for (int iter = 0;  iter < params.max_iter;  ++iter) {\n\n        //cerr << \"iter \" << iter << endl;\n\n        //cerr << \"points are in \" << numNodes << \" nodes\" << endl;\n\n#if 0\n        for (unsigned i = 0;  i < 5;  ++i) {\n            for (unsigned j = 0;  j < 2;  ++j) {\n                cerr << \"Y[\" << i << \"][\" << j << \"] = \" << Y[i][j] << \" \";\n            }\n            cerr << endl;\n        }\n#endif     \n   \n        // Create a new coordinate for each neighbour\n        std::vector<QCoord> pointCoords(nx);\n\n        for (unsigned i = 0;  i < nx;  ++i) {\n            pointCoords[i] = QCoord(&Y[i][0], &Y[i][0] + nd);\n        }\n\n        Quadtree & qtree = updateQtree();\n\n        // This accumulates the sum_j p[x][j] log Z*q[x][j] for each example.  From this and\n        // Z, we can calculate the cost of each example.  Only relevant if calcC is true.\n        double exampleCFactor[nx];\n        std::fill(exampleCFactor, exampleCFactor + nx, 0.0);\n        \n        // clang 3.4: lambda can't capture a variable length array\n        auto * exampleCFactorPtr = exampleCFactor;\n        \n\n        // Do we calculate the cost?\n        bool calcC = iter < 10 || (iter + 1) % 100 == 0 || iter == params.max_iter - 1;\n        //calcC = true;\n\n        // Approximation for Z, accumulated here\n        Spinlock Zmutex;\n        std::vector<double> ZApproxValues;\n        ZApproxValues.reserve(nx);\n\n\n        auto calcExample = [&] (int x)\n            {\n                // Clear the updates\n                for (unsigned i = 0;  i < nd;  ++i) {\n                    dY[x][i] = 0.0;\n                    FrepZ[x][i] = 0.0;\n                    FattrApprox[x][i] = 0.0;\n                    FrepApprox[x][i] = 0.0;\n                }\n\n                const TsneSparseProbs & neighbours = exampleNeighbours[x];\n                \n                distribution<float> y(nd);\n                for (unsigned i = 0;  i < nd;  ++i)\n                    y[i] = Y[x][i];\n\n                // For each neighbour, calculate the attractive force.  The\n                // others are defined as zero.\n                for (unsigned q = 0;  q < neighbours.indexes.size();  ++q) {\n                    \n                    unsigned j = neighbours.indexes[q];\n                    ExcAssertNotEqual(j, x);\n\n                    double D = 0.0;\n                    if (nd == 2) {\n                        float d0 = y[0] - Y[j][0];\n                        float d1 = y[1] - Y[j][1];\n                        D = d0 * d0 + d1 * d1;\n                    } else {\n                        for (unsigned i = 0;  i < nd;  ++i) {\n                            D += (y[i] - Y[j][i]) * (y[i] - Y[j][i]);\n                        }\n                    }\n\n                    //if (x == 0 && j == 1) {\n                    //    cerr << \"D[0][1] approx = \" << D << \" prob \"\n                    //         << neighbours.probs[q] << endl;\n                    //}\n\n                    // Note that 1/(1 + D[j]) == Q[j] * Z\n                    // See van der Marten, 2013 http://arxiv.org/pdf/1301.3342.pdf\n                    // Barnes-Hut-SNE\n\n                    double factorAttr = pFactor * neighbours.probs[q] / (1.0 + D);\n\n                    if (nd == 2) {\n                        float dYj0 = y[0] - Y[j][0];\n                        float dYj1 = y[1] - Y[j][1];\n                        FattrApprox[x][0] += dYj0 * factorAttr;\n                        FattrApprox[x][1] += dYj1 * factorAttr;\n                    }\n                    else {\n                        for (unsigned i = 0;  i < nd;  ++i) {\n                            double dYji = y[i] - Y[j][i];\n                            FattrApprox[x][i] += dYji * factorAttr;\n                        }\n                    }\n                }\n\n                // Working storage for onNode\n                distribution<double> com(nd);\n\n                int nodesTouched = 0;\n\n                double exampleZ = 0.0;\n\n                //bool doingTest = false;\n\n                bool exact = forceExactSolution;\n\n                int poiDone = 0;\n                //std::set<int> poiDoneSet;\n\n                auto onNode = [&] (const QuadtreeNode & node,\n                                   double qCellZ,\n                                   const std::vector<int> & pointsOfInterest)\n                {\n                    // If we want to calculate C, we store the log of\n                    // the cell's Q * Z for each point of interest so that\n                    // we can calculate the cost later.\n\n                    // Note that sum_j p[j] log (Zq[j])\n                    //         = sum_j p[j] log Z + sum_j p[j] log q[j]\n                    if (pointsOfInterest.empty())\n                        return;\n\n                    double logqCellZ = log(qCellZ);\n                    for (unsigned p: pointsOfInterest) {\n                        exampleCFactorPtr[x] += pFactor * neighbours.probs[p] * logqCellZ;\n                    }\n\n                    poiDone += pointsOfInterest.size();\n\n                    // For debugging, keep track of a set of them\n                    //for (int p: pointsOfInterest) {\n                    //    ExcAssert(poiDoneSet.insert(p).second);\n                    //}\n                };\n\n                auto getPointCoord = [&] (int point) -> const QCoord &\n                {\n                    return pointCoords.at(neighbours.indexes.at(point));\n                };\n\n                if (calcC) {\n                    // Bring along the points of interest for the ride\n                    vector<int> pointsOfInterest;\n                    pointsOfInterest.reserve(neighbours.indexes.size());\n                    for (unsigned i = 0;  i < neighbours.indexes.size();  ++i)\n                        pointsOfInterest.push_back(i);\n\n                    calcRep(*qtree.root, 0, true /* inside */,\n                            y, &FrepZ[x][0], exampleZ, nodesTouched, nd, exact,\n                            onNode, pointsOfInterest, getPointCoord,\n                            params.min_distance_ratio);\n\n                    //if (poiDone != neighbours.indexes.size()) {\n                    //    cerr << \"Not all POI are done\" << endl;\n                    //    for (int p: pointsOfInterest)\n                    //        if (!poiDoneSet.count(p))\n                    //            cerr << \"point \" << p << \" was not done\"\n                    //                 << endl;\n                    //}\n\n                    ExcAssertEqual(poiDone, neighbours.indexes.size());\n                    //if (!isfinite(exampleCFactor[x]))\n                    //    cerr << \"x = \" << x << \" factor \" << exampleCFactor[x] << endl;\n                    ExcAssert(isfinite(exampleCFactorPtr[x]));\n                } else {\n                    calcRep(*qtree.root, 0, true /* inside */,\n                            y, &FrepZ[x][0], exampleZ, nodesTouched, nd, exact,\n                            nullptr, {}, nullptr, params.min_distance_ratio);\n                }\n\n                {\n                    std::unique_lock<Spinlock> guard(Zmutex);\n                    ZApproxValues.push_back(exampleZ);\n                }\n\n                //if (x == 1026)\n                //    cerr << \"touched \" << nodesTouched << \" of \" << numNodes << \" nodes\"\n                //         << endl;\n            };\n\n#if 1\n        int totalThreads = std::max(1, std::min(16, MLDB::numCpus() / 2));\n\n        auto doThread = [&] (int n)\n            {\n                int perThread = nx / totalThreads;\n                int start = n * perThread;\n                int end = start + perThread;\n                if (n == totalThreads)\n                    end = nx;\n\n                for (unsigned x = start;  x < end;  ++x)\n                    calcExample(x);\n\n                //for (unsigned x = n;  x < nx;  x += totalThreads) {\n                //    calcExample(x);\n                //}\n            };\n\n        MLDB::parallelMap(0, totalThreads, doThread);\n        //parallelMap(0, nx, calcExample);\n#else\n        // Each example proceeds more or less independently\n        for (unsigned x = 0;  x < nx;  ++x) {\n            calcExample(x);\n        }\n#endif\n\n        // Sort from smallest to largest to accumulate.  This minimises\n        // rounding errors and makes the result independent of the order\n        // in which threads finish.\n        std::sort(ZApproxValues.begin(), ZApproxValues.end());\n        double ZApprox = std::accumulate(ZApproxValues.begin(),\n                                         ZApproxValues.end(),\n                                         0.0);\n\n        ExcAssert(isfinite(ZApprox));\n        ExcAssertNotEqual(0.0, ZApprox);\n\n        double Zrecip = 1.0 / ZApprox;\n        ExcAssert(isfinite(Zrecip));\n        \n        for (unsigned x = 0;  x < nx;  ++x) {\n            for (unsigned i = 0;  i < nd;  ++i) {\n                ExcAssert(isfinite(FrepZ[x][i]));\n                FrepApprox[x][i] = FrepZ[x][i] * Zrecip;\n            }\n        }\n\n        double Capprox = 0.0;\n        if (calcC) {\n            //double logZ = log(ZApprox);\n\n            // For a given example x,\n            // C[x] = sum_j P[x][j] log P[x][j] - sum_j P[x][j] log q[x][j]\n            //      = sum_j P[x][j] log P[x][j] - sum_j P[x][j] log Zq[j][j] + sum_j P[x][j] log Z\n            //      = sum_j P[x][j] log Z P[x][j] - exampleCFactor[x]\n\n            double logZapprox = log(ZApprox);\n            double logpFactor = log(pFactor);\n\n            for (unsigned x = 0;  x < nx;  ++x) {\n\n                const TsneSparseProbs & neighbours = exampleNeighbours[x];\n\n                double CExample = -exampleCFactor[x];\n\n                //cerr << \"CExample1 = \" << CExample << endl;\n\n                ExcAssert(isfinite(CExample));\n\n                for (auto & p: neighbours.probs) {\n                    // Be robust to zero probabilities, even though we\n                    // shouldn't have them.\n                    if (p == 0.0)\n                        continue;\n\n                    double CNeighbour =  pFactor * p * (logZapprox + logpFactor + logf(p));\n                    if (!isfinite(CNeighbour)) {\n                        cerr << \"cExample = \" << CExample\n                             << \"cNeighbour = \" << CNeighbour\n                             << \" pFactor = \" << pFactor\n                             << \" p = \" << p\n                             << \" logZapprox = \" << logZapprox\n                             << \" logpFactor = \" << logpFactor\n                             << \" logf(p) = \" << logf(p)\n                             << endl;\n                    }\n                    CExample += CNeighbour;\n                }\n\n                //cerr << \"CExample2 = \" << CExample << endl;\n\n                Capprox += CExample;\n\n                ExcAssert(isfinite(Capprox));\n            }\n        }\n\n#if 0  // exact calculations for verification        \n        double Z = 0.0, C = 0.0;\n\n        boost::multi_array<float, 2> QZ(boost::extents[nx][nx]);\n        boost::multi_array<double, 2> Fattr(boost::extents[nx][nd]);\n        boost::multi_array<double, 2> Frep(boost::extents[nx][nd]);\n        \n        for (unsigned x = 0;  x < nx;  ++x) {\n\n            distribution<float> y(nd);\n            for (unsigned i = 0;  i < nd;  ++i) {\n                y[i] = Y[x][i];\n                Fattr[x][i] = 0.0;\n            }\n\n            for (unsigned j = 0;  j < nx;  ++j) {\n                if (j == x)\n                    continue;\n\n                //if (x == 0 && j == 1) {\n                //    cerr << \"D[0][1] real   = \" << D << \" prob \"\n                //         << P[x][j] << endl;\n                //}\n\n            }\n\n            for (unsigned j = 0;  j < nx;  ++j) {\n                if (j == x)\n                    continue;\n\n                // Distances, used to calculate Q and Z\n                double D = 0.0;\n                if (nd == 2) {\n                    float d0 = y[0] - Y[j][0];\n                    float d1 = y[1] - Y[j][1];\n                    D = d0 * d0 + d1 * d1;\n                } else {\n                    for (unsigned i = 0;  i < nd;  ++i) {\n                        D += (y[i] - Y[j][i]) * (y[i] - Y[j][i]);\n                    }\n                }\n\n                QZ[x][j] = 1.0 / (1.0 + D);\n                Z += QZ[x][j];\n            }\n\n            const TsneSparseProbs & neighbours = exampleNeighbours[x];\n            \n            // For each neighbour, calculate the attractive force.  The\n            // others are defined as zero.\n            for (unsigned q = 0;  q < neighbours.indexes.size();  ++q) {\n                    \n                unsigned j = neighbours.indexes[q];\n                ExcAssertNotEqual(j, x);\n\n                double factorAttr = pFactor * neighbours.probs[q] * QZ[x][j];\n\n                if (nd == 2) {\n                    double dYj0 = y[0] - Y[j][0];\n                    double dYj1 = y[1] - Y[j][1];\n                    Fattr[x][0] += dYj0 * factorAttr;\n                    Fattr[x][1] += dYj1 * factorAttr;\n                }\n                else {\n                    for (unsigned i = 0;  i < nd;  ++i) {\n                        double dYji = y[i] - Y[j][i];\n                        Fattr[x][i] += dYji * factorAttr;\n                    }\n                }\n\n            }\n        }\n\n        //cerr << \"ZApprox = \" << ZApprox << \" Z = \" << Z << endl;\n\n\n        for (unsigned x = 0;  x < nx;  ++x) {\n            distribution<float> y(nd);\n            for (unsigned i = 0;  i < nd;  ++i) {\n                y[i] = Y[x][i];\n                Frep[x][i] = 0;\n            }\n\n            for (unsigned j = 0;  j < nx;  ++j) {\n                if (j == x)\n                    continue;\n\n                double Qxj = QZ[x][j] / Z;\n\n                //Qxj = std::max<double>(params.min_prob, Qxj);\n\n                // Repulsive force\n                float factorRep = Qxj * Z * Qxj;\n\n                if (nd == 2) {\n                    float dYj0 = y[0] - Y[j][0];\n                    float dYj1 = y[1] - Y[j][1];\n                    Frep[x][0] -= dYj0 * factorRep;\n                    Frep[x][1] -= dYj1 * factorRep;\n                }\n                else {\n                    for (unsigned i = 0;  i < nd;  ++i) {\n                        double dYji = y[i] - Y[j][i];\n                        Frep[x][i] -= dYji * factorRep;\n                    }\n                }\n\n            }\n\n            const TsneSparseProbs & neighbours = exampleNeighbours[x];\n            \n            // For each neighbour, calculate the attractive force.  The\n            // others are defined as zero.\n            for (unsigned q = 0;  q < neighbours.indexes.size();  ++q) {\n                    \n                unsigned j = neighbours.indexes[q];\n                ExcAssertNotEqual(j, x);\n\n                double Qxj = QZ[x][j] / Z;\n\n                C += pFactor * neighbours.probs[q] * logf(pFactor * neighbours.probs[q] / Qxj);\n            }\n        }\n\n        cerr << \"Capprox = \" << Capprox << \" C = \" << C << endl;\n#endif\n\n        float maxAbsDy = 0.0;\n        float maxAbsY = 0.0;\n\n        for (unsigned x = 0;  x < nx;  ++x) {\n            for (unsigned i = 0;  i < nd;  ++i) {\n                //dY[x][i] = 4.0 * (Fattr[x][i] + Frep[x][i]);\n                //dY[x][i] = 4.0 * (FattrApprox[x][i] + Frep[x][i]);\n                //dY[x][i] = 4.0 * (Fattr[x][i] + FrepApprox[x][i]);\n                dY[x][i] = 4.0 * (FattrApprox[x][i] + FrepApprox[x][i]);\n\n                ExcAssert(isfinite(FattrApprox[x][i]));\n                ExcAssert(isfinite(FrepApprox[x][i]));\n                ExcAssert(isfinite(dY[x][i]));\n\n                maxAbsDy = std::max(maxAbsDy, fabs(dY[x][i]));\n                maxAbsY = std::max(maxAbsY, Y[x][i]);\n\n#if 0\n                if (x < 5) {\n                    cerr << \"Fattr[\" << x << \"][\" << i << \"]: approx \"\n                         << FattrApprox[x][i] << \" real \" << Fattr[x][i]\n                         << endl;\n                    cerr << \"Frep[\" << x << \"][\" << i << \"]: approx \"\n                         << FrepApprox[x][i] << \" real \" << Frep[x][i]\n                         << endl;\n                }\n\n                if (x < 5) {\n                    cerr << \"dY[\" << x << \"][\" << i << \"]: approx \"\n                         << 4.0 * (FattrApprox[x][i] + FrepApprox[x][i])\n                         << \" real \" << 4.0 * (Fattr[x][i] + Frep[x][i])\n                         << endl;\n                    cerr << \"Y = \" << Y[x][i] << endl;\n                }\n#endif\n            }\n\n        }\n\n#if 0\n        cerr << \"C = \" << Capprox << endl;\n\n        for (unsigned x = 0;  x < 5;  ++x) {\n            cerr << \"P[\" << x << \"][0..5] = \"\n                 << pFactor * exampleNeighbours[x].probs[0]\n                 << \" \" << pFactor * exampleNeighbours[x].probs[1]\n                 << \" \" << pFactor * exampleNeighbours[x].probs[2]\n                 << \" \" << pFactor * exampleNeighbours[x].probs[3]\n                 << \" \" << pFactor * exampleNeighbours[x].probs[4]\n                 << endl;\n\n            cerr << \"P[\" << x << \"][0..5] = \"\n                 << exampleNeighbours[x].indexes[0]\n                 << \" \" << exampleNeighbours[x].indexes[1]\n                 << \" \" << exampleNeighbours[x].indexes[2]\n                 << \" \" << exampleNeighbours[x].indexes[3]\n                 << \" \" << exampleNeighbours[x].indexes[4]\n                 << endl;\n\n                for (unsigned i = 0;  i < nd;  ++i) {\n                    cerr << \"dY[\" << x << \"][\" << i << \"]: real \" << dY[x][i]\n                         << endl;\n                    cerr << \"Y = \" << Y[x][i] << endl;\n                }\n        }\n\n        break;\n#endif\n\n        double cost2 = Capprox;\n        if (calcC) {\n            cerr << \"cost \" << Capprox << endl;\n            ExcAssert(isfinite(Capprox));\n            //cerr << \"Cost approx \" << Capprox << \" real \" << C << endl;\n\n            last_cost = cost;\n            cost = cost2;\n\n            if (isfinite(cost) && cost == last_cost) {\n                // converged\n                break;\n            }\n        }\n\n        /*********************************************************************/\n        // Update\n\n        float momentum = (iter < 20\n                          ? params.initial_momentum\n                          : params.final_momentum);\n\n        tsne_update(Y, dY, iY, gains, iter == 0, momentum, params.eta,\n                    params.min_gain);\n\n        if (callback\n            && !callback(iter, cost, \"update\"))\n            break;\n\n\n        /*********************************************************************/\n        // Recenter about the origin\n\n        recenter_about_origin(Y);\n\n        if (callback\n            && !callback(iter, cost, \"recenter\")) break;\n\n        if (calcC || (iter + 1) % 100 == 0 || iter == params.max_iter - 1) {\n            cerr << format(\"iteration %4d cost %6.3f  \",\n                           iter + 1, cost)\n                 << timer.elapsed() << endl;\n            timer.restart();\n        }\n        \n        float maxAbsCoord[nd];\n        std::fill(maxAbsCoord, maxAbsCoord + nd, 0.0);\n\n        boost::multi_array<float, 2> normalizedY(boost::extents[nx][nd]);\n        for (unsigned x = 0;  x < nx;  ++x) {\n            for (unsigned i = 0;  i < nd;  ++i) {\n                maxAbsCoord[i] = std::max(maxAbsCoord[i], fabs(Y[x][i]));\n            }\n        }\n\n        float maxCoordChange = 0.0;\n\n        for (unsigned x = 0;  x < nx;  ++x) {\n            for (unsigned i = 0;  i < nd;  ++i) {\n                normalizedY[x][i] = Y[x][i] / maxAbsCoord[i];\n                maxCoordChange = std::max(maxCoordChange, fabs(normalizedY[x][i] - lastNormalizedY[x][i]));\n            }\n        }\n\n        lastNormalizedY = normalizedY;\n\n        //cerr << \"maxAbsDy = \" << maxAbsDy << \" maxAbsY = \" << maxAbsY\n        //     << \" ratio \" << 100.0 * maxAbsDy / maxAbsY\n        //     << \" maxCoordChange = \" << maxCoordChange << endl;\n\n        if (maxCoordChange < params.max_coord_change && iter > params.min_iter)\n            break;\n            \n        // Stop lying about P values if we're finished 100 iterations\n        if (iter == 100) {\n            pFactor /= 4.0;\n        }\n    }\n\n    if (qtreeOut) {\n        updateQtree();\n        qtreeOut->reset(qtreePtr.release());\n    }\n\n    return Y;\n}\n\ndistribution<float>\nretsneApproxFromCoords(const distribution<float> & newExampleCoords,\n                       const boost::multi_array<float, 2> & coreCoords,\n                       const boost::multi_array<float, 2> & prevOutput,\n                       const Quadtree & qtree,\n                       const VantagePointTreeT<int> & vpTree,\n                       const TSNE_Params & params)\n{\n    int nd = coreCoords.shape()[1];\n\n    // Distance between neighbours.  Must satisfy the triangle inequality,\n    // so the sqrt is important.\n    auto dist = [&] (int x2)\n        {\n            return pythag_dist(&newExampleCoords[0], &coreCoords[x2][0], nd);\n        };\n\n    TsneSparseProbs neighbours\n        = sparseProbsFromCoords(dist, vpTree,\n                                params.numNeighbours,\n                                params.perplexity,\n                                params.tolerance,\n                                -1 /* don't remove any */);\n    \n    // TODO: do the equivalent of making the probabilities symmetric\n    \n    return retsneApproxFromSparse(neighbours, prevOutput, qtree, params);\n}\n\ndistribution<float>\nretsneApproxFromSparse(const TsneSparseProbs & neighbours,\n                       const boost::multi_array<float, 2> & prevOutput,\n                       const Quadtree & qtree,\n                       const TSNE_Params & params)\n{\n    int nx MLDB_UNUSED = prevOutput.shape()[0];\n    int nd = prevOutput.shape()[1];\n    int nn = neighbours.indexes.size();\n\n    ExcAssert(qtree.root);\n\n    // Extract the coordinate for each neighbour into a dense array\n    std::vector<QCoord> neighbourCoords(nn);\n\n    for (unsigned i = 0;  i < nn;  ++i) {\n        neighbourCoords[i] = QCoord(&prevOutput[neighbours.indexes[i]][0], &prevOutput[neighbours.indexes[i]][0] + nd);\n    }\n\n    distribution<float> y(nd);\n\n    // Start off at the Y of the point with the highest probability, to get faster\n    // convergance\n    double highestProb = -INFINITY;\n    int bestNeighbour = -1;\n    for (unsigned i = 0;  i < nn;  ++i) {\n        if (neighbours.probs[i] > highestProb) {\n            highestProb = neighbours.probs[i];\n            bestNeighbour = i;\n        }\n    }\n\n    // Copy the coordinates in\n    for (unsigned i = 0;  i < nd;  ++i) {\n        y[i] = prevOutput[bestNeighbour][i];\n    }\n\n    //cerr << \"y = \" << y << endl;\n    //cerr << \"total P = \" << neighbours.probs.total() << endl;\n    //cerr << \"max P = \" << neighbours.probs.max() << endl;\n\n    float pFactor = 1.0;// / nx;\n\n    double lastC = INFINITY;\n\n    // Do we force the repulsive force to calculate the exact value?\n    bool exact = false;\n\n    for (unsigned iter = 0;  iter < params.max_iter;  ++iter) {\n\n        // Y gradients\n        double dy[nd];\n        std::fill(dy, dy + nd, 0.0);\n\n        // Y gradients\n        double Fattr[nd];\n        std::fill(Fattr, Fattr + nd, 0.0);\n\n        // Approximate solution to the repulsive force\n        bool calcC = iter % 20 == 0;\n        //calcC = true;\n        double C = 0.0;\n\n        double ZApprox = 0.0;\n        double FrepZApprox[nd];\n        std::fill(FrepZApprox, FrepZApprox + nd, 0.0);\n\n        int poiDone = 0;\n        int nodesTouched = 0;\n\n        double CFactor = 0.0;\n\n        //std::set<int> poiDoneSet;\n\n        auto onNode = [&] (const QuadtreeNode & node,\n                           double qCellZ,\n                           const std::vector<int> & pointsOfInterest)\n            {\n                if (pointsOfInterest.empty())\n                    return;\n                \n                // If we want to calculate C, we store the log of\n                // the cell's Q * Z for each point of interest so that\n                // we can calculate the cost later.\n\n                // Note that sum_j p[j] log (Zq[j])\n                //         = sum_j p[j] log Z + sum_j p[j] log q[j]\n\n                double logqCellZ = log(qCellZ);\n                for (unsigned p: pointsOfInterest) {\n                    CFactor += pFactor * neighbours.probs[p] * logqCellZ;\n                }\n\n                poiDone += pointsOfInterest.size();\n                //poiDoneSet.insert(pointsOfInterest.begin(), pointsOfInterest.end());\n            };\n\n        auto getPointCoord = [&] (int point) -> const QCoord &\n            {\n                return neighbourCoords.at(point);\n            };\n\n        if (calcC) {\n            // Bring along the points of interest for the ride, since we need to\n            // calculate a log QZ score for each\n            vector<int> pointsOfInterest;\n            pointsOfInterest.reserve(neighbours.indexes.size());\n            for (unsigned i = 0;  i < neighbours.indexes.size();  ++i)\n                pointsOfInterest.push_back(i);\n\n            calcRep(*qtree.root, 0, false /* inside */,\n                    y, FrepZApprox, ZApprox, nodesTouched, nd, exact,\n                    onNode, pointsOfInterest, getPointCoord,\n                    params.min_distance_ratio);\n\n#if 0\n            if (poiDone != neighbours.indexes.size()) {\n                for (unsigned i = 0;  i < neighbours.indexes.size();  ++i) {\n                    if (!poiDoneSet.count(i)) {\n                        cerr << \"point \" << i << \" not done\" << endl;\n\n                        static std::mutex mutex;\n                        std::unique_lock<std::mutex> guard(mutex);\n\n                        {\n                            std::ofstream stream(\"debug.txt\");\n                            stream << nx << \" \" << nd << \" \" << i;\n                            for (unsigned i = 0;  i < nd;  ++i) {\n                                stream << MLDB::format(\" %+.16g\", y[i]);\n                            }\n                            stream << endl;\n                            for (unsigned x = 0;  x < nx;  ++x) {\n                                for (unsigned i = 0;  i < nd;  ++i) {\n                                    stream << MLDB::format(\"%+.16g \", prevOutput[x][i]);\n                                }\n                                stream << endl;\n                            }\n                        }\n                        abort();\n                    }\n                }\n            }\n\n#endif\n            ExcAssertEqual(poiDone, neighbours.indexes.size());\n\n            //if (!isfinite(exampleCFactor[x]))\n            //    cerr << \"x = \" << x << \" factor \" << exampleCFactor[x] << endl;\n            ExcAssert(isfinite(CFactor));\n        } else {\n            calcRep(*qtree.root, 0, false /* inside */,\n                    y, FrepZApprox, ZApprox, nodesTouched, nd, exact,\n                    nullptr, {}, nullptr, params.min_distance_ratio);\n        }\n\n\n        double FrepApprox[nd];\n        for (unsigned i = 0;  i < nd;  ++i) {\n            FrepApprox[i] = FrepZApprox[i] / ZApprox;\n        }\n\n        double FattrApprox[nd];\n        std::fill(FattrApprox, FattrApprox + nd, 0.0);\n\n        for (unsigned q = 0;  q < neighbours.indexes.size();  ++q) {\n            // Difference in each dimension\n            float d[nd];\n\n            // Square of total distance\n            double D = 0.0;\n            if (nd == 2) {\n                d[0] = y[0] - neighbourCoords[q][0];\n                d[1] = y[1] - neighbourCoords[q][1];\n                D = d[0] * d[0] + d[1] * d[1];\n            } else {\n                for (unsigned i = 0;  i < nd;  ++i) {\n                    d[i] = (y[i] - neighbourCoords[q][i]);\n                    D += d[i] * d[i];\n                }\n            }\n            \n            // Note that 1/(1 + D[j]) == Q[j] * Z\n\n            float factorAttr = pFactor * neighbours.probs[q] / (1.0f + D);\n\n            if (nd == 2) {\n                FattrApprox[0] += d[0] * factorAttr;\n                FattrApprox[1] += d[1] * factorAttr;\n            }\n            else {\n                for (unsigned i = 0;  i < nd;  ++i) {\n                    FattrApprox[i] += d[i] * factorAttr;\n                }\n            }\n        }\n\n        double Capprox = 0.0;\n        if (calcC) {\n            //double logZ = log(ZApprox);\n\n            // C = sum_j P[j] log P[j] - sum_j P[j] log q[j]\n            //      = sum_j P[j] log P[j] - sum_j P[j] log Zq[j] + sum_j P[j] log Z\n            //      = sum_j P[j] log Z P[j] - CFactor\n            Capprox = -CFactor;\n            \n            for (auto & p: neighbours.probs) {\n                Capprox += pFactor * p * logf(pFactor * p * ZApprox);\n            }\n        }\n\n        C = Capprox;\n\n        for (unsigned i = 0;  i < nd;  ++i) {\n            dy[i] += FrepApprox[i];\n        }\n\n        for (unsigned i = 0;  i < nd;  ++i) {\n            dy[i] += FattrApprox[i];\n        }\n\n        //cerr << \"C = \" << C << \" y = \" << y << \" dY = \" << dy[0] << \" \" << dy[1] << endl;\n\n        if (calcC) {\n            if (fabs(C - lastC) < 0.00001) {\n                //cerr << \"converged after \" << iter << \" iterations\" << endl;\n                break;\n            }\n            lastC = C;\n        }\n\n        for (unsigned i = 0;  i < nd;  ++i)\n            y[i] -= 20.0 * dy[i];\n\n        //y -= 100.0 * dy;\n\n        //cerr << \"dy = \" << dy << \" dy_num = \" << dY_num << \" y now \" << y << endl;\n    }\n\n    return y;\n}\n\n\n\n} // namespace ML\n", "meta": {"hexsha": "28e66e75d5575c1641ffa795f991589e7eddefb7", "size": 85862, "ext": "cc", "lang": "C++", "max_stars_repo_path": "plugins/jml/tsne/tsne.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/tsne/tsne.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/tsne/tsne.cc", "max_forks_repo_name": "matebestek/mldb", "max_forks_repo_head_hexsha": "f78791cd34d01796705c0f173a14359ec1b2e021", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-11-23T20:03:38.000Z", "max_forks_repo_forks_event_max_datetime": "2018-11-23T20:03:38.000Z", "avg_line_length": 32.3032355154, "max_line_length": 119, "alphanum_fraction": 0.4599124176, "num_tokens": 23344, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7745833737577158, "lm_q2_score": 0.43014734858584286, "lm_q1q2_score": 0.3331849844805584}}
{"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 <string>\n#include <map>\n#include <set>\n#include <algorithm>\n#include <math.h>\n#include <sstream>\n#include <Eigen/Dense>\n#include <cassert>\n#include <iostream>\n#include \"Transformation.h\"\n#include \"Transformable.h\"\n#include \"SVD_PROPACK.h\"\n#include \"eigen_tools.h\"\n#include \"Jacobian.h\"\n#include \"QSqrtMatrix.h\"\n#include \"pest_data_structs.h\"\n#include \"debug.h\"\n#include \"Regularization.h\"\n#include \"Serialization.h\"\n#include \"eigen_tools.h\"\n\nusing namespace std;\nusing namespace Eigen;\n\n///////////////// Transformation Methods /////////////////\n\n\n///////////////// TranMapBase Methods /////////////////\nvoid TranMapBase::insert(const string &item_name, double item_value)\n{\n\titems[item_name] = item_value;\n}\n\n\nvoid TranMapBase::insert(const Parameters &pars)\n{\n\tfor (const auto &ipar : pars)\n\t{\n\t\titems[ipar.first] = ipar.second;\n\t}\n}\n\nvoid TranMapBase::reset(const Parameters &pars)\n{\n\titems.clear();\n\tfor (const auto &ipar : pars)\n\t{\n\t\titems[ipar.first] = ipar.second;\n\t}\n}\n\nvoid TranMapBase::print(ostream &os) const\n{\n\tos << \"Transformation name = \" << name << \"; (type=TranMapBase)\" << endl;\n\tfor (map<string,double>::const_iterator b=items.begin(), e=items.end();\n\t\tb!=e; ++b) {\n\t\t\tos << \"  item name = \" << (*b).first << \";  value = \" << (*b).second << endl;\n\t}\n}\n\npair<bool, double> TranMapBase::get_value(const string &name) const\n{\n\tpair<bool, double> ret_val(false, 0.0);\n\tmap<string, double>::const_iterator it;\n\n\tit = items.find(name);\n\tif (it !=items.end()) {\n\t\tret_val = pair<bool, double>(true, (*it).second);\n\t}\n\treturn ret_val;\n}\n\n///////////////// TranSetBase Methods /////////////////\nvoid TranSetBase::insert(const string &item_name)\n{\n\titems.insert(item_name);\n}\n\nvoid TranSetBase::print(ostream &os) const\n{\n\tos << \"Transformation name = \" << name << \"; (type=TranSetBase)\" << endl;\n\tfor (set<string>::const_iterator b=items.begin(), e=items.end();\n\t\tb!=e; ++b) {\n\t\t\tos << \"  item name = \" << *b << endl;\n\t}\n}\n\nbool TranSetBase::has_value(const string &name) const\n{\n\tbool ret_val = false;\n\tset<string>::const_iterator it;\n\n\tit = items.find(name);\n\tif (it !=items.end()) {\n\t\tret_val = true;\n\t}\n\treturn ret_val;\n}\n\n///////////////// TranOffset Methods /////////////////\nvoid TranOffset::forward(Transformable &data)\n{\n\tTransformable::iterator data_iter, data_end = data.end();\n\tfor (map<string,double>::const_iterator b=items.begin(), e=items.end();\n\t\tb!=e; ++b) {\n\t\tdata_iter = data.find(b->first);\n\t\tif (data_iter != data_end)\n\t\t{\n\t\t\t(*data_iter).second += (*b).second;\n\t\t}\n\t}\n}\n\nvoid TranOffset::reverse(Transformable &data)\n{\n\tTransformable::iterator data_iter, data_end = data.end();\n\tfor (map<string,double>::const_iterator b=items.begin(), e=items.end();\n\t\tb!=e; ++b) {\n\t\tdata_iter = data.find(b->first);\n\t\tif (data_iter != data_end)\n\t\t{\n\t\t\t(*data_iter).second -= b->second;\n\t\t}\n\t}\n}\n\nvoid TranOffset::jacobian_forward(Jacobian &jac)\n{\n\tTransformable &data = jac.base_numeric_parameters;\n\tforward(data);\n}\n\nvoid TranOffset::jacobian_reverse(Jacobian &jac)\n{\n\tTransformable &data = jac.base_numeric_parameters;\n\treverse(data);\n}\n\nvoid TranOffset::d2_to_d1(Transformable &del_data, Transformable &data)\n{\n\t// Offset transformation does not affect derivatives.\n\t// Nothing to do.\n\treverse(data);\n}\n\nvoid TranOffset::d1_to_d2(Transformable &del_data, Transformable &data)\n{\n\t// Offset transformation does not affect derivatives.\n\t// Nothing to do.\n\tforward(data);\n}\n\nvoid TranOffset::print(ostream &os) const\n{\n\tos << \"Transformation name = \" << name << \"; (type=TranOffset)\" << endl;\n\tfor (map<string, double>::const_iterator b = items.begin(), e = items.end();\n\t\tb != e; ++b) {\n\t\tos << \"  item name = \" << (*b).first << \";  offset value = \" << (*b).second << endl;\n\t}\n}\n\n///////////////// TranScale Methods /////////////////\nvoid TranScale::forward(Transformable &data)\n{\n\tTransformable::iterator data_iter, data_end = data.end();\n\tfor (map<string,double>::const_iterator b=items.begin(), e=items.end();\n\t\tb!=e; ++b) {\n\t\tdata_iter = data.find(b->first);\n\t\tif (data_iter != data_end)\n\t\t{\n\t\t\t(*data_iter).second *= b->second;\n\t\t}\n\t}\n}\n\n\nvoid TranScale::reverse(Transformable &data)\n{\n\tTransformable::iterator data_iter, data_end = data.end();\n\tfor (map<string,double>::const_iterator b=items.begin(), e=items.end();\n\t\tb!=e; ++b) {\n\t\tdata_iter = data.find(b->first);\n\t\tif (data_iter != data_end)\n\t\t{\n\t\t\t(*data_iter).second /= b->second;\n\t\t}\n\t}\n}\n\nvoid TranScale::jacobian_forward(Jacobian &jac)\n{\n\tsize_t icol = 0;\n\tdouble factor = 0;\n\tTransformable &data = jac.base_numeric_parameters;\n\tunordered_map<string, int> par_2_col_map = jac.get_par2col_map();\n\tauto iter_end = par_2_col_map.end();\n\tfor (const auto &irec : items)\n\t{\n\t\tauto iter = par_2_col_map.find(irec.first);\n\t\tif (iter != iter_end)\n\t\t{\n\t\t\ticol = iter->second;\n\t\t\tfactor = irec.second;\n\t\t\tjac.matrix.col(icol) /= factor;\n\t\t}\n\t}\n\tforward(data);\n}\n\nvoid TranScale::jacobian_reverse(Jacobian &jac)\n{\n\tsize_t icol = 0;\n\tdouble factor = 0;\n\tTransformable &data = jac.base_numeric_parameters;\n\tunordered_map<string, int> par_2_col_map = jac.get_par2col_map();\n\tauto iter_end = par_2_col_map.end();\n\tfor (const auto &irec : items)\n\t{\n\t\tauto iter = par_2_col_map.find(irec.first);\n\t\tif (iter != iter_end)\n\t\t{\n\t\t\ticol = iter->second;\n\t\t\tfactor = irec.second;\n\t\t\tjac.matrix.col(icol) *= factor;\n\t\t}\n\t}\n\treverse(data);\n}\n\nvoid TranScale::d1_to_d2(Transformable &del_data, Transformable &data)\n{\n\tTransformable::iterator del_data_iter, del_data_end = del_data.end();\n\tfor (map<string, double>::const_iterator b = items.begin(), e = items.end();\n\t\tb != e; ++b) {\n\t\tdel_data_iter = del_data.find(b->first);\n\t\tif (del_data_iter != del_data_end)\n\t\t{\n\t\t\t(*del_data_iter).second /= b->second;\n\t\t}\n\t}\n\tforward(data);\n}\n\nvoid TranScale::d2_to_d1(Transformable &del_data, Transformable &data)\n{\n\tTransformable::iterator del_data_iter, del_data_end = del_data.end();\n\tfor (map<string, double>::const_iterator b = items.begin(), e = items.end();\n\t\tb != e; ++b) {\n\t\tdel_data_iter = del_data.find(b->first);\n\t\tif (del_data_iter != del_data_end)\n\t\t{\n\t\t\t(*del_data_iter).second *= b->second;\n\t\t}\n\t}\n\treverse(data);\n}\n\nvoid TranScale::print(ostream &os) const\n{\n\tos << \"Transformation name = \" << name << \"; (type=TranScale)\" << endl;\n\tfor (map<string,double>::const_iterator b=items.begin(), e=items.end();\n\t\tb!=e; ++b) {\n\t\t\tos << \"  item name = \" << (*b).first << \";  scale value = \" << (*b).second << endl;\n\t}\n}\n\n///////////////// TranLog10 Methods /////////////////\nvoid TranLog10::forward(Transformable &data)\n{\n\tTransformable::iterator data_iter, data_end = data.end();\n\tfor (set<string>::const_iterator b=items.begin(), e=items.end(); b!=e; ++b)\n\t{\n\t\tdata_iter = data.find(*b);\n\t\tif (data_iter != data_end)\n\t\t{\n\t\t\t(*data_iter).second = log10((*data_iter).second);\n\t\t}\n\t}\n}\n\nvoid TranLog10::reverse(Transformable &data)\n{\n\tTransformable::iterator data_iter, data_end = data.end();\n\tfor (set<string>::const_iterator b=items.begin(), e=items.end(); b!=e; ++b)\n\t{\n\t\tdata_iter = data.find(*b);\n\t\tif (data_iter != data_end)\n\t\t{\n\t\t\t(*data_iter).second = pow(10.0, (*data_iter).second);\n\t\t}\n\t}\n}\n\n\n\nvoid TranLog10::jacobian_forward(Jacobian &jac)\n{\n\tsize_t icol = 0;\n\tdouble factor = 0;\n\tdouble d = 0;\n\tTransformable &data = jac.base_numeric_parameters;\n\tforward(data);\n\tunordered_map<string, int> par_2_col_map = jac.get_par2col_map();\n\tauto iter_end = par_2_col_map.end();\n\tfor (const auto &ipar : items)\n\t{\n\t\tauto iter = par_2_col_map.find(ipar);\n\t\tif (iter != iter_end)\n\t\t{\n\t\t\td = data.get_rec(ipar);\n\t\t\ticol = iter->second;\n\t\t\tfactor = pow(10, d) * log(10.0);\n\t\t}\n\t\tjac.matrix.col(icol) *= factor;\n\t}\n}\n\nvoid TranLog10::jacobian_reverse(Jacobian &jac)\n{\n\tsize_t icol = 0;\n\tdouble factor = 0;\n\tdouble d = 0;\n\tTransformable &data = jac.base_numeric_parameters;\n\treverse(data);\n\tunordered_map<string, int> par_2_col_map = jac.get_par2col_map();\n\tauto iter_end = par_2_col_map.end();\n\tfor (const auto &ipar : items)\n\t{\n\t\tauto iter = par_2_col_map.find(ipar);\n\t\tif (iter != iter_end)\n\t\t{\n\t\t\td = data.get_rec(ipar);\n\t\t\ticol = iter->second;\n\t\t\tfactor = 1.0 / (d * log(10.0));\n\t\t\tjac.matrix.col(icol) *= factor;\n\t\t}\n\t}\n}\n\n\nvoid TranLog10::d1_to_d2(Transformable &del_data, Transformable &data)\n{\n\tforward(data);\n\tTransformable::iterator del_data_iter, del_data_end = del_data.end();\n\tfor (set<string>::const_iterator b = items.begin(), e = items.end(); b != e; ++b)\n\t{\n\t\tdel_data_iter = del_data.find(*b);\n\t\tif (del_data_iter != del_data_end)\n\t\t{\n\t\t\tdouble d1 = data.get_rec(*b);\n\t\t\tdouble factor = pow(10.0, d1) * log(10.0);\n\t\t\t(*del_data_iter).second *= factor;\n\t\t}\n\t}\n}\n\nvoid TranLog10::d2_to_d1(Transformable &del_data, Transformable &data)\n{\n\treverse(data);\n\tTransformable::iterator del_data_iter, del_data_end = del_data.end();\n\tfor (set<string>::const_iterator b = items.begin(), e = items.end(); b != e; ++b)\n\t{\n\t\tdel_data_iter = del_data.find(*b);\n\t\tif (del_data_iter != del_data_end)\n\t\t{\n\t\t\tdouble d2 = data.get_rec(*b);\n\t\t\tdouble factor = 1.0 / (d2 * log(10.0));\n\t\t\t(*del_data_iter).second *= factor;\n\t\t}\n\t}\n\treverse(data);\n}\n\nvoid TranLog10::print(ostream &os) const\n{\n\tos << \"Transformation name = \" << name << \"; (type=TranLog10)\" << endl;\n\tfor (set<string>::const_iterator b=items.begin(), e=items.end();\n\t\tb!=e; ++b) {\n\t\t\tos << \"  item name = \" << *b << endl;\n\t}\n}\n\n///////////////// TranFixed Methods /////////////////\nvoid TranFixed::forward(Transformable &data)\n{\n\tfor (map<string,double>::iterator b=items.begin(), e=items.end(); b!=e; ++b)\n\t{\n\t\tdata.erase(b->first);\n\t}\n}\n\nvoid TranFixed::reverse(Transformable &data)\n{\n\tfor (map<string,double>::iterator b=items.begin(), e=items.end(); b!=e; ++b)\n\t{\n\t\tdata.insert(b->first, b->second);\n\t}\n}\n\n\nvoid TranFixed::jacobian_forward(Jacobian &jac)\n{\n\tTransformable &data = jac.base_numeric_parameters;\n\tset<string> rm_par_set;\n\tfor (const auto &irec : items)\n\t{\n\t\trm_par_set.insert(irec.first);\n\t}\n\t//remove Fixed parameters from base_parameter_names\n\tjac.remove_cols(rm_par_set);\n\tforward(data);\n}\n\nvoid TranFixed::jacobian_reverse(Jacobian &jac)\n{\n\tTransformable &data = jac.base_numeric_parameters;\n\tset<string> new_pars;\n\tfor (auto &i : items)\n\t{\n\t\tnew_pars.insert(i.first);\n\t}\n\tjac.add_cols(new_pars);\n\treverse(data);\n}\n\n\n\nvoid TranFixed::d1_to_d2(Transformable &del_data, Transformable &data)\n{\n\tfor (map<string, double>::iterator b = items.begin(), e = items.end(); b != e; ++b)\n\t{\n\t\tdel_data.erase(b->first);\n\t}\n\tforward(data);\n}\n\nvoid TranFixed::d2_to_d1(Transformable &del_data, Transformable &data)\n{\n\tfor (map<string, double>::iterator b = items.begin(), e = items.end(); b != e; ++b)\n\t{\n\t\tdel_data.insert(b->first, 0.0);\n\t}\n\treverse(data);\n}\n\n\nvoid TranFixed::print(ostream &os) const\n{\n\tos << \"Transformation name = \" << name << \"; (type=TranFixed)\" << endl;\n\tfor (map<string,double>::const_iterator b=items.begin(), e=items.end();\n\t\tb!=e; ++b) {\n\t\t\tos << \"  item name = \" << (*b).first << \";  imposed value = \" << (*b).second << endl;\n\t}\n}\n\nvoid TranFrozen::print(ostream &os) const\n{\n\tos << \"Transformation name = \" << name << \"; (type=TranFrozen)\" << endl;\n\tfor (map<string,double>::const_iterator b=items.begin(), e=items.end();\n\t\tb!=e; ++b) {\n\t\t\tos << \"  item name = \" << (*b).first << \";  imposed value = \" << (*b).second << endl;\n\t}\n}\n\nvoid TranTied::insert(const string &item_name, const pair<string, double> &item_value)\n{\n\titems[item_name] = item_value;\n}\n\n\nvoid TranTied::forward(Transformable &data)\n{\n\tfor (map<string, pair_string_double>::iterator ii = items.begin(); ii != items.end(); ++ii)\n\t{\n\t\tdata.erase(ii->first);\n\t}\n}\n\n\nvoid TranTied::reverse(Transformable &data)\n{\n\tstring const *base_name;\n\tdouble *factor;\n\tTransformable::iterator base_iter;\n\tfor (map<string, pair_string_double>::iterator b = items.begin(), e = items.end();\n\t\tb != e; ++b)\n\t{\n\t\tbase_name = &(b->second.first);\n\t\tfactor = &(b->second.second);\n\t\tbase_iter = data.find(*base_name);\n\t\tif (base_iter != data.end())\n\t\t{\n\t\t\t//cout << b->first << ',' << data[b->first] <<  ',' << (*base_iter).second << endl;\n\t\t\tdata.erase(b->first);\n\t\t\tdata.insert(b->first, (*base_iter).second * (*factor));\n\t\t\t//cout << b->first << ',' << data[b->first] << ',' << (*base_iter).second << endl;\n\t\t}\n\n\t}\n}\n\nvoid TranTied::jacobian_forward(Jacobian &jac)\n{\n\tthrow(PestError(\"Error: TranTied::jacobian_forward - TranTied does not support Jacobian transformations\"));\n}\n\n\n\nvoid TranTied::jacobian_reverse(Jacobian &jac)\n{\n\tthrow(PestError(\"Error: TranTied::jacobian_forward - TranTied does not support Jacobian transformations\"));\n}\n\nvoid TranTied::d1_to_d2(Transformable &del_data, Transformable &data)\n{\n\tthrow(PestError(\"Error: TranTied::d1_to_d2 - TranTied does not support d1_to_d2 transformations\"));\n}\n\nvoid TranTied::d2_to_d1(Transformable &del_data, Transformable &data)\n{\n\tthrow(PestError(\"Error: TranTied::d2_to_d1 - TranTied does not support d2_to_d1 transformations\"));\n}\n\nvoid TranTied::print(ostream &os) const\n{\n\tos << \"Transformation name = \" << name << \"; (type=TranTied)\" << endl;\n\tfor (map<string, pair_string_double>::const_iterator b=items.begin(), e=items.end();\n\t\tb!=e; ++b) {\n\t\t\tos << \"  item name = \" << (*b).first << \"   tied to \\\"\" << (*b).second.first <<\n\t\t\t\t\"\\\" with factor \" <<  (*b).second.second<<  endl;\n\t}\n}\n\n\nconst  Eigen::SparseMatrix<double>& TranSVD::get_vt() const\n{\n\treturn Vt;\n}\n\n\nTranSVD::TranSVD(int _max_sing, double _eign_thresh, const string &_name) : Transformation(_name)\n{\n\ttran_svd_pack = new SVD_EIGEN(_max_sing, _eign_thresh);\n}\n\n\nTranSVD::TranSVD(const TranSVD &rhs)\n\t: Transformation(rhs), base_parameter_names(rhs.base_parameter_names),\n\tsuper_parameter_names(rhs.super_parameter_names),\n\tobs_names(rhs.obs_names),\n\tSqrtQ_J(rhs.SqrtQ_J),\n\tSigma(rhs.Sigma),\n\tU(rhs.U),\n\tVt(rhs.Vt),\n\tinit_base_numeric_parameters(rhs.init_base_numeric_parameters),\n\tfrozen_derivative_parameters(rhs.frozen_derivative_parameters)\n{\n\ttran_svd_pack = rhs.tran_svd_pack->clone();\n}\n\n\nvoid TranSVD::set_SVD_pack_propack()\n{\n\tint max_sing = tran_svd_pack->get_max_sing();\n\tdouble eigthresh = tran_svd_pack->get_eign_thres();\n\tdelete tran_svd_pack;\n\ttran_svd_pack = new SVD_PROPACK(max_sing, eigthresh);\n}\n\nvoid TranSVD::set_performance_log(PerformanceLog *performance_log)\n{\n\ttran_svd_pack->set_performance_log(performance_log);\n}\n\nvoid TranSVD::calc_svd()\n{\n\tdebug_msg(\"TranSVD::calc_svd begin\");\n\tstringstream sup_name;\n\tVectorXd Sigma_trunc;\n\ttran_svd_pack->solve_ip(SqrtQ_J, Sigma, U, Vt, Sigma_trunc);\n\t// calculate the number of singluar values above the threshold\n\n\tdebug_print(Sigma);\n\tdebug_print(U);\n\tdebug_print(Vt);\n\tdebug_print(Sigma_trunc);\n\n\n\tint n_sing_val = Sigma.size();\n\n\tsuper_parameter_names.clear();\n\tfor(int i=0; i<n_sing_val; ++i) {\n\t\tsup_name.str(\"\");\n\t\tsup_name << \"SUP_\";\n\t\tsup_name << i+1;\n\t\tsuper_parameter_names.push_back(sup_name.str());\n\t}\n\tif (n_sing_val <= 0 )\n\t{\n\t\tthrow PestError(\"TranSVD::update() - super parameter transformation returned 0 super parameters.  Jacobian must equal 0.\");\n\t}\n\tdebug_print(super_parameter_names);\n\tdebug_msg(\"TranSVD::calc_svd end\");\n}\n\nvoid TranSVD::update_reset_frozen_pars(const Jacobian &jacobian, const QSqrtMatrix &Q_sqrt, const Parameters &base_numeric_pars,\n\t\tint maxsing, double _eigthresh, const vector<string> &par_names, const vector<string> &_obs_names,\n\t\tconst Parameters &_frozen_derivative_pars)\n{\n\tdebug_msg(\"TranSVD::update_reset_frozen_pars begin\");\n\tdebug_print(_frozen_derivative_pars);\n\tstringstream sup_name;\n\tsuper_parameter_names.clear();\n\n\ttran_svd_pack->set_max_sing(maxsing);\n\ttran_svd_pack->set_eign_thres(_eigthresh);\n\tobs_names = _obs_names;\n\n\n\n\t//these are where the derivative was computed so they can be different than the frozen values;\n\tinit_base_numeric_parameters = base_numeric_pars;\n\tbase_parameter_names = par_names;\n\t//remove frozen parameters from base_parameter_names\n\tauto end_iter = std::remove_if(base_parameter_names.begin(), base_parameter_names.end(),\n\t\t[&_frozen_derivative_pars](string &str)->bool{return _frozen_derivative_pars.find(str)!=_frozen_derivative_pars.end();});\n\tbase_parameter_names.resize(std::distance(base_parameter_names.begin(), end_iter));\n\tfrozen_derivative_parameters = _frozen_derivative_pars;\n\t//remove frozen derivatives from matrix parameter list\n\tstd::remove_if(base_parameter_names.begin(), base_parameter_names.end(),\n\t\t[this](string &str)->bool{return this->frozen_derivative_parameters.find(str)!=this->frozen_derivative_parameters.end();});\n\n\tSqrtQ_J = Q_sqrt.get_sparse_matrix(obs_names, DynamicRegularization::get_unit_reg_instance()) * jacobian.get_matrix(obs_names, base_parameter_names);\n\n\tcalc_svd();\n\tdebug_print(this->base_parameter_names);\n\tdebug_print(this->frozen_derivative_parameters);\n\tdebug_msg(\"TranSVD::update_reset_frozen_pars end\");\n}\n\nvoid TranSVD::update_add_frozen_pars(const Parameters &frozen_pars)\n{\n\tdebug_msg(\"TranSVD::update_reset_frozen_pars begin\");\n\tdebug_print(frozen_pars);\n\tvector<size_t> del_col_ids;\n\tParameters new_frozen_pars;\n\tfor (auto &ipar : frozen_pars)\n\t{\n\t\tauto iter = frozen_derivative_parameters.find(ipar.first);\n\t\tif (iter == frozen_derivative_parameters.end())\n\t\t{\n\t\t\tnew_frozen_pars.insert(ipar);\n\t\t}\n\t}\n\n\tfrozen_derivative_parameters.insert(new_frozen_pars);\n\n\t// build list of columns that needs to be removed from the matrix\n\tfor (int i=0; i<base_parameter_names.size(); ++i)\n\t{\n\t\tif(new_frozen_pars.find(base_parameter_names[i]) != new_frozen_pars.end())\n\t\t{\n\t\t\tdel_col_ids.push_back(i);\n\t\t}\n\t}\n\n\tif (del_col_ids.size() == base_parameter_names.size())\n\t{\n\t\tthrow PestError(\"TranSVD::update_add_frozen_pars - All parameters are frozen in SVD transformation\");\n\t}\n\t//remove frozen parameters from base_parameter_names\n\tauto end_iter = std::remove_if(base_parameter_names.begin(), base_parameter_names.end(),\n\t\t[&new_frozen_pars](string &str)->bool{return new_frozen_pars.find(str)!=new_frozen_pars.end();});\n\tbase_parameter_names.resize(std::distance(base_parameter_names.begin(), end_iter));\n\tmatrix_del_cols(SqrtQ_J, del_col_ids);\n\tcalc_svd();\n\tdebug_print(this->base_parameter_names);\n\tdebug_print(this->frozen_derivative_parameters);\n\tdebug_msg(\"TranSVD::update_reset_frozen_pars end\");\n}\nvoid TranSVD::reverse(Transformable &data)\n{\n\t// Transform super-parameters to base parameters\n\tassert(Vt.cols() == base_parameter_names.size());\n\tint n_base = Vt.cols();\n\tvector<double> super_par_vec = data.get_data_vec(super_parameter_names);\n\tvector<double>::iterator it;\n\tfor (it=super_par_vec.begin(); it!=super_par_vec.end(); ++it)\n\t{\n\t\t(*it) -= 10.0;\n\t}\n\tTransformable ret_base_pars;\n\tint n_sing_val = Sigma.size();\n\tVectorXd delta_base_mat = Vt.block(0,0,n_sing_val, Vt.cols()).transpose() *  stlvec_2_egienvec(super_par_vec);\n\tfor (int i=0; i<n_base; ++i) {\n\t\tret_base_pars.insert(base_parameter_names[i], delta_base_mat(i) + init_base_numeric_parameters.get_rec(base_parameter_names[i]));\n\t}\n\n\tdata = ret_base_pars;\n}\n\nvoid TranSVD::forward(Transformable &data)\n{\n\t//Transform base parameters to super-parameters\n\tTransformable super_pars;\n\tVectorXd value;\n\n\tTransformable delta_data = init_base_numeric_parameters;\n\tdelta_data *= 0.0;\n\n\tfor (auto &it : data)\n\t{\n\t\tdelta_data[it.first] = it.second - init_base_numeric_parameters.get_rec(it.first);\n\t}\n\tint n_sing_val = Sigma.size();\n\tvalue = Vt * delta_data.get_data_eigen_vec(base_parameter_names);\n\tfor (int i=0; i<n_sing_val; ++i) {\n\t\tsuper_pars.insert(super_parameter_names[i], value(i)+10.0);\n\t}\n\tdata = super_pars;\n}\n\nvoid TranSVD::jacobian_forward(Jacobian &jac)\n{\n\tTransformable &data = jac.base_numeric_parameters;\n\tEigen::SparseMatrix<double> old_matrix = jac.get_matrix(jac.observation_list(), base_parameter_names);\n\tEigen::SparseMatrix<double> super_jacobian;\n\tsuper_jacobian = old_matrix * Vt.transpose();\n\tjac.matrix = super_jacobian;\n\tjac.base_numeric_par_names = super_parameter_names;\n\n\tforward(data);\n}\n\nvoid TranSVD::jacobian_reverse(Jacobian &jac)\n{\n\tTransformable &data = jac.base_numeric_parameters;\n\tEigen::SparseMatrix<double> old_matrix = jac.get_matrix(jac.observation_list(), super_parameter_names);\n\tEigen::SparseMatrix<double> base_jacobian;\n\tbase_jacobian = old_matrix * Vt;\n\tjac.matrix = base_jacobian;\n\tjac.base_numeric_par_names = base_parameter_names;\n\treverse(data);\n}\n\nvoid TranSVD::d1_to_d2(Transformable &del_data, Transformable &data)\n{\n\tTransformable new_data;\n\tVectorXd d1_vec = del_data.get_partial_data_eigen_vec(base_parameter_names);\n\tVectorXd d2_vec = Vt * d1_vec;\n\tfor (int i = 0; i<Sigma.size(); ++i) {\n\t\tnew_data[super_parameter_names[i]] = d2_vec[i];\n\t}\n\tdel_data = new_data;\n\tforward(data);\n}\n\n\nvoid TranSVD::d2_to_d1(Transformable &del_data, Transformable &data)\n{\n\tTransformable new_data;\n\tVectorXd d2_vec = del_data.get_partial_data_eigen_vec(super_parameter_names);\n\tVectorXd d1_vec = Vt.transpose() * d2_vec;\n\tfor (size_t i = 0; i < base_parameter_names.size(); ++i)\n\t{\n\t\tnew_data[base_parameter_names[i]] = d1_vec[i];\n\t}\n\tdel_data = new_data;\n\treverse(data);\n}\n\nvoid TranSVD::save(ostream &fout) const\n{\n\tsize_t size;\n\tvector<int8_t> serial_data;\n\tserial_data = Serialization::serialize(base_parameter_names);\n\tsize = serial_data.size();\n\tfout.write((char*)&size, sizeof(size));\n\tfout.write((char*)serial_data.data(), size);\n\n\tserial_data = Serialization::serialize(super_parameter_names);\n\tsize = serial_data.size();\n\tfout.write((char*)&size, sizeof(size));\n\tfout.write((char*)serial_data.data(), size);\n\n\tserial_data = Serialization::serialize(obs_names);\n\tsize = serial_data.size();\n\tfout.write((char*)&size, sizeof(size));\n\tfout.write((char*)serial_data.data(), size);\n\n\tsave_triplets_bin(SqrtQ_J, fout);\n\tsave_vector_bin(Sigma, fout);\n\tsave_triplets_bin(U, fout);\n\tsave_triplets_bin(Vt, fout);\n\n\tserial_data = Serialization::serialize(init_base_numeric_parameters);\n\tsize = serial_data.size();\n\tfout.write((char*)&size, sizeof(size));\n\tfout.write((char*)serial_data.data(), size);\n\n\tserial_data = Serialization::serialize(frozen_derivative_parameters);\n\tsize = serial_data.size();\n\tfout.write((char*)&size, sizeof(size));\n\tfout.write((char*)serial_data.data(), size);\n}\n\nvoid TranSVD::read(istream &fin)\n{\n\tsize_t size;\n\tvector<int8_t> serial_data;\n\n\tbase_parameter_names.clear();\n\tfin.read((char*)&size, sizeof(size));\n\tserial_data.clear();\n\tserial_data.resize(size);\n\tfin.read((char*)serial_data.data(), size);\n\tSerialization::unserialize(serial_data, base_parameter_names);\n\n\tsuper_parameter_names.clear();\n\tfin.read((char*)&size, sizeof(size));\n\tserial_data.clear();\n\tserial_data.resize(size);\n\tfin.read((char*)serial_data.data(), size);\n\tSerialization::unserialize(serial_data, super_parameter_names);\n\n\tobs_names.clear();\n\tfin.read((char*)&size, sizeof(size));\n\tserial_data.clear();\n\tserial_data.resize(size);\n\tfin.read((char*)serial_data.data(), size);\n\tSerialization::unserialize(serial_data, obs_names);\n\n\tload_triplets_bin(SqrtQ_J, fin);\n\tload_vector_bin(Sigma, fin);\n\tload_triplets_bin(U, fin);\n\tload_triplets_bin(Vt, fin);\n\n\tinit_base_numeric_parameters.clear();\n\tfin.read((char*)&size, sizeof(size));\n\tserial_data.clear();\n\tserial_data.resize(size);\n\tfin.read((char*)serial_data.data(), size);\n\tSerialization::unserialize(serial_data, init_base_numeric_parameters);\n\n\tfrozen_derivative_parameters.clear();\n\tfin.read((char*)&size, sizeof(size));\n\tserial_data.clear();\n\tserial_data.resize(size);\n\tfin.read((char*)serial_data.data(), size);\n\tSerialization::unserialize(serial_data, frozen_derivative_parameters);\n}\n\nParameterGroupInfo TranSVD::build_par_group_info(const ParameterGroupInfo &base_pg_info)\n{\n\tdouble derinc_sup;\n\tdouble derinc_par;\n\tint max_col;\n\tdouble max_val;\n\tParameterGroupInfo pg_info;\n\tstringstream grp_name;\n\tfor (int i_sup=0, n_sup=super_parameter_names.size(); i_sup < n_sup; ++i_sup)\n\t{\n\t\tget_MatrixXd_row_abs_max(Vt, i_sup, &max_col, &max_val);\n\t\tderinc_par = base_pg_info.get_group_rec_ptr(base_parameter_names[max_col])->derinc;\n\t\tderinc_sup = .01;\n\t\tgrp_name.str(\"\");\n\t\tgrp_name << \"g_\" << super_parameter_names[i_sup];\n\t\tParameterGroupRec sup_rec(grp_name.str(), \"ABSOLUTE\", derinc_sup, 0.0, \"SWITCH\", 2.0, \"PARABOLIC\");\n\t\t//add new group\n\t\tpg_info.insert_group(grp_name.str(), sup_rec);\n\t\t// connect super parameter to new group\n\t\tpg_info.insert_parameter_link(super_parameter_names[i_sup], grp_name.str());\n\t}\n\treturn pg_info;\n}\n\n\nParameters TranSVD::map_basepar_to_super(const Parameters &base_pars)\n{\n\tParameters super_pars;\n\tVectorXd base_par_vec = base_pars.get_partial_data_eigen_vec(base_parameter_names);\n\tVectorXd super_par_vec = Vt * base_par_vec;\n\tfor (size_t i=0; i<super_parameter_names.size(); ++i)\n\t{\n\t\tsuper_pars[super_parameter_names[i]] = super_par_vec(i);\n\t}\n\treturn super_pars;\n}\n\nTranSVD::~TranSVD()\n{\n\tdelete tran_svd_pack;\n}\n\nvoid TranSVD::print(ostream &os) const\n{\n\tos << \"Transformation name = \" << name << \"; (type=TranSVD)\" << endl;\n\tos << \"  Singular Values = \" << Sigma << endl;\n}\n\n//void TranNormalize::forward(Transformable &data)\n//{\n//\tTransformable::iterator data_iter, data_end = data.end();\n//\tfor (map<string,NormData>::const_iterator b=items.begin(), e=items.end();\n//\t\tb!=e; ++b) {\n//\t\tdata_iter = data.find(b->first);\n//\t\tif (data_iter != data_end)\n//\t\t{\n//\t\t\t(*data_iter).second += b->second.offset;\n//\t\t\t(*data_iter).second *= b->second.scale;\n//\t\t}\n//\t}\n//}\n//\n//\n//void TranNormalize::reverse(Transformable &data)\n//{\n//\tTransformable::iterator data_iter, data_end = data.end();\n//\tfor (map<string,NormData>::const_iterator b=items.begin(), e=items.end();\n//\t\tb!=e; ++b) {\n//\t\tdata_iter = data.find(b->first);\n//\t\tif (data_iter != data_end)\n//\t\t{\n//\t\t\t(*data_iter).second /= b->second.scale;\n//\t\t\t(*data_iter).second -= b->second.offset;\n//\t\t}\n//\t}\n//}\n//\n//\n//void TranNormalize::jacobian_forward(Jacobian &jac)\n//{\n//\tsize_t icol = 0;\n//\tdouble factor = 0;\n//\tTransformable &data = jac.base_numeric_parameters;\n//\tunordered_map<string, int> par_2_col_map = jac.get_par2col_map();\n//\tauto iter_end = par_2_col_map.end();\n//\tfor (const auto &irec : items)\n//\t{\n//\t\tauto iter = par_2_col_map.find(irec.first);\n//\t\tif (iter != iter_end)\n//\t\t{\n//\t\t\ticol = iter->second;\n//\t\t\tfactor = irec.second.scale;\n//\t\t\tjac.matrix.col(icol) /= factor;\n//\t\t}\n//\t}\n//\tforward(data);\n//}\n//\n//void TranNormalize::jacobian_reverse(Jacobian &jac)\n//{\n//\tsize_t icol = 0;\n//\tdouble factor = 0;\n//\tTransformable &data = jac.base_numeric_parameters;\n//\tunordered_map<string, int> par_2_col_map = jac.get_par2col_map();\n//\tauto iter_end = par_2_col_map.end();\n//\tfor (const auto &irec : items)\n//\t{\n//\t\tauto iter = par_2_col_map.find(irec.first);\n//\t\tif (iter != iter_end)\n//\t\t{\n//\t\t\ticol = iter->second;\n//\t\t\tfactor = irec.second.scale;\n//\t\t\tjac.matrix.col(icol) *= factor;\n//\t\t}\n//\t}\n//\treverse(data);\n//}\n//\n//void TranNormalize::d1_to_d2(Transformable &del_data, Transformable &data)\n//{\n//\tTransformable::iterator del_data_iter, del_data_end = del_data.end();\n//\tfor (map<string, NormData>::const_iterator b = items.begin(), e = items.end();\n//\t\tb != e; ++b) {\n//\t\tdel_data_iter = data.find(b->first);\n//\t\tif (del_data_iter != del_data_end)\n//\t\t{\n//\t\t\t(*del_data_iter).second /= b->second.scale;\n//\t\t}\n//\t}\n//\tforward(data);\n//}\n//\n//void TranNormalize::d2_to_d1(Transformable &del_data, Transformable &data)\n//{\n//\tTransformable::iterator del_data_iter, del_data_end = del_data.end();\n//\tfor (map<string, NormData>::const_iterator b = items.begin(), e = items.end();\n//\t\tb != e; ++b) {\n//\t\tdel_data_iter = del_data.find(b->first);\n//\t\tif (del_data_iter != del_data_end)\n//\t\t{\n//\t\t\t(*del_data_iter).second *= b->second.scale;\n//\t\t}\n//\t}\n//\treverse(data);\n//}\n//\n//void TranNormalize::insert(const string &item_name, double _offset, double _scale)\n//{\n//\titems[item_name] = NormData(_offset, _scale);\n//}\n//\n//void TranNormalize::print(ostream &os) const\n//{\n//\tos << \"Transformation name = \" << name << \"; (type=TranNormalize)\" << endl;\n//\tfor (map<string,NormData>::const_iterator b=items.begin(), e=items.end();\n//\t\tb!=e; ++b) {\n//\t\t\tos << \"  item name = \" << (*b).first << \";  scale value = \" << (*b).second.scale\n//\t\t\t\t<< \";  offset value = \" << (*b).second.offset <<endl;\n//\t}\n//}\n", "meta": {"hexsha": "f53ea78a5e8b397541fe27453464d0eaffa0305d", "size": 28556, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/src_pestpp/libs/pestpp_common/Transformation.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/libs/pestpp_common/Transformation.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/libs/pestpp_common/Transformation.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": 27.6973811833, "max_line_length": 150, "alphanum_fraction": 0.695405519, "num_tokens": 7917, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5926666143434, "lm_q2_score": 0.5621765008857982, "lm_q1q2_score": 0.3331832434434054}}
{"text": "/*\n * added by Shufang ZHU on Jan 10th, 2017\n * translate ltlf formulas to fol, the input of MONA\n*/\n\n#include \"ltlf2fol.h\"\n#include <stdlib.h>\n#include <stdio.h>\n#include <ctype.h>\n#include <set>\n#include <assert.h>\n#include <iostream>\n#include <fstream>\n#include <boost/algorithm/string.hpp>\n\nusing namespace std;\n#define MAXN 1000000\n\n\nvoid ltlf2fol (ltl_formula *root)\n{\n  int c = 1;\n  string res;\n  \n  set<string> P = get_alphabet (root);\n  if(!P.empty()){\n    // cout<<\"var2 ALIVE, \";\n    cout<<\"m2l-str;\"<<endl;\n    cout<<\"var2 \";\n    print_alphabet_no_comma(root);\n    cout<<\";\"<<endl;\n    // cout<<\"allpos ALIVE;\"<<endl;\n    // cout<<\"0 in ALIVE;\"<<endl;\n  }\n  \n  res = trans_fol(root, 0, c);\n  cout<<res<<\";\"<<endl;\n  \n\n}\n\nvoid print_alphabet_no_comma (ltl_formula* root){\n  set<string> P = get_alphabet (root);\n  if(!P.empty()){\n    set<string>::iterator it = P.begin ();\n    // cout<<toupper(*it);\n    cout<<up(*it);\n    it++;\n    while (it != P.end ()){\n      cout<<\", \"<<up(*it);\n      it++;\n    }\n  }\n}\n\nstring alphabet_no_comma (ltl_formula* root){\n  string res = \"\";\n  set<string> P = get_alphabet (root);\n  if(!P.empty()){\n    set<string>::iterator it = P.begin ();\n    // cout<<toupper(*it);\n    res += up(*it);\n    it++;\n    while (it != P.end ()){\n      res += \", \"+up(*it);\n      it++;\n    }\n  }\n  return res;\n}\n\nvoid print_alphabet (ltl_formula* root){\n  set<string> P = get_alphabet (root);\n  if(!P.empty()){\n    set<string>::iterator it = P.begin ();\n    // cout<<toupper(*it);\n    cout<<\", \"<<up(*it);\n    it++;\n    while (it != P.end ()){\n      cout<<\", \"<<up(*it);\n      it++;\n    }\n  }\n}\n\nvoid print_alphabet_not (ltl_formula* root){\n  set<string> P = get_alphabet (root);\n  if(!P.empty()){\n    set<string>::iterator it = P.begin ();\n    // cout<<toupper(*it);\n    cout<<\", \"<<up(*it)<<\"\\\\{p}\";\n    it++;\n    while (it != P.end ()){\n      cout<<\", \"<<up(*it);\n      it++;\n    }\n  }\n}\n\nvoid printvars (ltl_formula* root){\n  set<string> P = get_alphabet (root);\n  if(!P.empty()){\n    set<string>::iterator it = P.begin ();\n    // cout<<toupper(*it);\n    cout<<\", var2 \"<<up(*it);\n    it++;\n    while (it != P.end ()){\n      cout<<\", var2 \"<<up(*it);\n      it++;\n    }\n  }\n}\n\nstring trans_fol(ltl_formula* root, int t, int& c){\n  string curs, ts;\n  string exs, alls;\n  string res;\n  int cur;\n  switch(root->_type)\n  {\n        case eNOT:\n          res = \"~(\";\n          res += trans_fol(root->_right, t, c);\n          res += \")\";\n          break;\n        case eNEXT:\n          exs = \"x\"+to_string(t+1);\n          if (t == 0)\n            ts = to_string(t);\n          else\n            ts = \"x\"+to_string(t);\n          res = \"(ex1 \"+exs+\": (\"+exs+\"=\"+ts+\"+1 & (\";\n          res += trans_fol(root->_right, t+1, c);\n          res += \")))\";\n          break;\n        case eWNEXT:\n          exs = \"x\"+to_string(t+1);\n          if (t == 0)\n            ts = to_string(t);\n          else\n            ts = \"x\"+to_string(t);\n          res = \"((ex1 \"+exs+\": (\"+exs+\"=\"+ts+\"+1 & (\";\n          res += trans_fol(root->_right, t+1, c);\n          res += \"))) | (\"+ts+\" = max $))\";\n          break;\n        case eFUTURE:\n          exs = \"x\"+to_string(t+1);\n          if (t == 0)\n            ts = to_string(t);\n          else\n            ts = \"x\"+to_string(t);\n          res = \"(ex1 \"+exs+\": (\"+ts+\" <= \"+exs+\" & (\";\n          res += trans_fol(root->_right, t+1, c);\n          res += \")))\";\n          break;\n        case eGLOBALLY:\n          alls = \"x\"+to_string(t+1);\n          if (t == 0)\n            ts = to_string(t);\n          else\n            ts = \"x\"+to_string(t);\n          res = \"(all1 \"+alls+\": ((\"+ts+\" <= \"+alls+\") => (\";\n          res += trans_fol(root->_right, t+1, c);\n          res += \")))\";\n          break;\n        case eUNTIL:\n          exs = \"x\"+to_string(t+1);\n          alls = \"x\"+to_string(t+2);\n          if (t == 0)\n            ts = to_string(t);\n          else\n            ts = \"x\"+to_string(t);\n          res = \"(ex1 \"+exs+\": (\"+ts+\" <= \"+exs+\" & (\";\n          res += trans_fol(root->_right, t+1, c);\n          res += \") & (all1 \"+alls+\": (\"+ts+\" <= \"+alls+\" & \"+alls;\n          res += \" < \"+exs+\" => (\";\n          res += trans_fol(root->_left, t+2, c);\n          res += \")))))\";\n          break;\n        case eRELEASE: //New\n          exs = \"x\"+to_string(t+1);\n          alls = \"x\"+to_string(t+2);\n          if (t == 0)\n            ts = to_string(t);\n          else\n            ts = \"x\"+to_string(t);\n          res = \"((ex1 \"+exs+\": (\"+ts+\" <= \"+exs+\" & (\";\n          res += trans_fol(root->_left, t+1, c);\n          res += \") & (all1 \"+alls+\": (\"+ts+\" <= \"+alls+\" & \"+alls;\n          res += \" <= \"+exs+\" => (\";\n          res += trans_fol(root->_right, t+2, c);\n          res += \")))))\";\n          res += \"| (all1 \"+alls+\": ((\"+ts+\" <= \"+alls+\" & \"+alls+\" <= max $) => (\";\n          res += trans_fol(root->_right, t+2, c);\n          res += \"))))\";\n          break;\n        case eOR:\n          res += \"((\"+trans_fol(root->_right, t, c);\n          res += \") | (\";\n          res += trans_fol(root->_left, t, c)+\"))\";\n          break;\n        case eAND:\n          res += \"((\"+trans_fol(root->_right, t, c);\n          res += \") & (\";\n          res += trans_fol(root->_left, t, c)+\"))\";\n          break;\n        case eTRUE:\n          res += \"(true)\";\n          break;\n        case eFALSE:\n          res += \"(false)\";\n          break;\n        case 3:\n          if (t == 0)\n            ts = \"(\"+to_string(t);\n          else\n            ts = \"(x\"+to_string(t);\n          res += ts+\" in \";\n          res += alphabet_no_comma(root);\n          res +=\")\";\n          break;\n        default:\n          break;\n  }\n  // cout<<res<<endl;\n  return res;\n}\n\nstring up(string a){\n  return boost::to_upper_copy<std::string>(a);\n}\n\n\n\nchar in[MAXN];\n\nint main (int argc, char ** argv)\n{\n  \n\t\tstring StrLine;\n\t\tstd::string input;\n    std::string format;\n\t\tif(argc != 3){\n        cout<<\"Usage: ./ltlf2fol format(NNF, BNF) filename\"<<endl;\n        return 0;\n    }\n\t\tinput = argv[2];\n    format = argv[1];\n\t\tifstream myfile(input);\n\t\tif (!myfile.is_open()) //判断文件是否存在及可读\n\t\t{\n\t\t    printf(\"unreadable file!\");\n\t\t    return -1;\n\t\t}\n\t\tgetline(myfile, StrLine);\n\t\tmyfile.close(); //关闭文件\n    strcpy (in, StrLine.c_str());\n    printf (\"#%s\\n\", in);\n    \n    ltl_formula *root = getAST (in);\n    ltl_formula *bnfroot = bnf (root);\n    ltl_formula *newroot;\n    printf (\"#%s\\n\", to_string (bnfroot).c_str ());\n    if(format == \"NNF\"){\n      printf (\"#NNF format\\n\");\n      newroot = nnf (bnfroot) ;   \n    }\n    else{\n      printf (\"#BNF format\\n\");\n      newroot = bnfroot;\n    }\n    \n    printf (\"#%s\\n\", to_string (newroot).c_str ());\n    ltlf2fol (newroot);\n    \n    \n\n    // printf (\"%s\\n\", res.c_str ());\n    destroy_formula (root);\n    destroy_formula (newroot);\n    //destroy_formula (nnfroot);\n}\n\n\n\n\n\n\n", "meta": {"hexsha": "24af56eda1060df3c9ace00deddf4b05a40386cb", "size": 6806, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tool/Gfsynth/src/ltlf2fol/ltlf2fol.cpp", "max_stars_repo_name": "Shufang-Zhu/GFSynth", "max_stars_repo_head_hexsha": "ea6e4a8be2e44d6636172d33cdb61192d6122f45", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2021-02-19T01:51:41.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-22T16:26:02.000Z", "max_issues_repo_path": "src/ltlf2fol/ltlf2fol.cpp", "max_issues_repo_name": "Shufang-Zhu/Syft", "max_issues_repo_head_hexsha": "121a9a1f6ac818138963d92889f44e0f98b59796", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-08-04T03:45:30.000Z", "max_issues_repo_issues_event_max_datetime": "2020-08-04T03:45:30.000Z", "max_forks_repo_path": "src/ltlf2fol/ltlf2fol.cpp", "max_forks_repo_name": "Shufang-Zhu/Syft", "max_forks_repo_head_hexsha": "121a9a1f6ac818138963d92889f44e0f98b59796", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2018-09-17T15:59:05.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-03T13:57:12.000Z", "avg_line_length": 23.5501730104, "max_line_length": 84, "alphanum_fraction": 0.4482809286, "num_tokens": 2061, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5926665999540697, "lm_q2_score": 0.5621765008857981, "lm_q1q2_score": 0.33318323535406197}}
{"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_bnu_base.h\"\n\n#include \"common/network_config.h\"\n#include \"common/network_exception.h\"\n#include \"common/network_random.h\"\n\n#include <boost/optional.hpp>\n#include <boost/numeric/ublas/matrix_proxy.hpp>\n\nnamespace bnu = boost::numeric::ublas;\n\nnamespace neurocl { namespace mlp {\n\nconst std::string dump_mat( const matrixF& mat, 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( matrixF::const_iterator1 it1 = mat.cbegin1(); it1 != mat.cend1(); ++it1 )\n    {\n        for( matrixF::const_iterator2 it2 = it1.begin(); it2 !=it1.end(); ++it2 )\n        {\n            ss << separator << *it2;\n            separator = \" \";\n        }\n        separator = \"\";\n        ss << std::endl;\n    }\n    return ss.str();\n}\n\nconst std::string dump_vec( const vectorF& 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( auto val : vec )\n    {\n            ss << separator << val;\n            separator = \" \";\n    }\n    ss << std::endl;\n    return ss.str();\n}\n\ntemplate<class T>\nvoid random_normal_init( T& container, const float stddev = 1.f )\n{\n    random::rand_gaussian_generator rgg( 0.f, stddev );\n\n    for( auto& element : container.data() )\n    {\n        element = rgg();\n    }\n}\n\nlayer_bnu::layer_bnu()\n{\n}\n\n// WARNING : size is the square side size\nvoid layer_bnu::populate( const layer_size& cur_layer_size, const layer_size& next_layer_size )\n{\n    //LOGGER(info) << \"layer_bnu::populate - populating layer of size \" << cur_layer_size << \" (next size is \" << next_layer_size << \")\" << std::endl;\n\n    if ( next_layer_size.size() ) // non-output layer\n    {\n        m_output_weights = matrixF( 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 = matrixF( next_layer_size.size(), cur_layer_size.size() );\n        m_deltas_weight.clear();\n\n        m_bias = vectorF( next_layer_size.size() );\n        random_normal_init( m_bias, 1.f );\n        m_deltas_bias = vectorF( next_layer_size.size() );\n        m_deltas_bias.clear();\n    }\n\n    m_activations = vectorF( cur_layer_size.size() );\n    m_activations.clear();\n    m_errors = vectorF( cur_layer_size.size() ); // not needed for input layer...?\n    m_errors.clear();\n}\n\nconst std::string layer_bnu::dump_weights() const\n{\n    return dump_mat( m_output_weights );\n}\n\nconst std::string layer_bnu::dump_bias() const\n{\n    return dump_vec( m_bias );\n}\n\nconst std::string layer_bnu::dump_activations() const\n{\n    return dump_vec( m_activations );\n}\n\nnetwork_bnu_base::network_bnu_base() : 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\nvoid network_bnu_base::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_bnu::set_input - input (\" << in << \") size = \" << in_size << std::endl;\n\n    vectorF& input_activations = m_layers[0].activations();\n    std::copy( in, in + in_size, input_activations.begin() );\n}\n\nvoid network_bnu_base::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_bnu::set_output - output (\" << out << \") size = \" << out_size << std::endl;\n\n    std::copy( out, out + out_size, m_training_output.begin() );\n}\n\nvoid network_bnu_base::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    // Initialize training output\n    m_training_output = vectorF( _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_bnu_base::get_layer_ptr( const size_t layer_idx )\n{\n    if ( layer_idx >= m_layers.size() )\n    {\n        LOGGER(error) << \"network_bnu_base::get_layer_ptr - cannot access layer \" << layer_idx << std::endl;\n        throw network_exception( \"invalid layer index\" );\n    }\n\n    matrixF& weights = m_layers[layer_idx].weights();\n    vectorF& bias = m_layers[layer_idx].bias();\n    layer_ptr l( weights.size1() * weights.size2(), bias.size() );\n    std::copy( &weights.data()[0], &weights.data()[0] + ( weights.size1() * weights.size2() ), l.weights.get() );\n    std::copy( &bias[0], &bias[0] + bias.size(), l.bias.get() );\n\n    return l;\n}\n\nvoid network_bnu_base::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_bnu_base::set_layer_ptr - cannot access layer \" << layer_idx << std::endl;\n        throw network_exception( \"invalid layer index\" );\n    }\n\n    LOGGER(info) << \"network_bnu_base::set_layer_ptr - setting layer  \" << layer_idx << std::endl;\n\n    matrixF& weights = m_layers[layer_idx].weights();\n    std::copy( layer.weights.get(), layer.weights.get() + layer.num_weights, &weights.data()[0] );\n    vectorF& bias = m_layers[layer_idx].bias();\n    std::copy( layer.bias.get(), layer.bias.get() + layer.num_bias, &bias.data()[0] );\n}\n\nconst output_ptr network_bnu_base::output()\n{\n    vectorF& output = m_layers.back().activations();\n    output_ptr o( output.size() );\n    std::copy( &output[0], &output[0] + output.size(), o.outputs.get() );\n\n    return o;\n}\n\nvoid network_bnu_base::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().clear();\n        m_layers[i].b_deltas().clear();\n    }\n\n    m_training_samples = 0;\n}\n\nfloat network_bnu_base::loss()\n{\n    vectorF& output = m_layers.back().activations();\n    vectorF loss = bnu::element_prod( output - m_training_output, output - m_training_output );\n\n    float _acc = 0.f;\n    std::for_each( loss.begin(), loss.end(),\n        [&_acc] ( float a ) {\n            _acc += a;\n        });\n\n    return 0.5f * _acc / static_cast<float>( loss.size() );\n}\n\nconst std::string network_bnu_base::dump_weights()\n{\n    std::stringstream ss;\n    ss << \"*************************************************\" << std::endl;\n    for( const auto& layer : m_layers )\n    {\n        ss << layer.dump_weights();\n        ss << \"-------------------------------------------------\" << std::endl;\n    }\n    ss << \"*************************************************\" << std::endl;\n    return ss.str();\n}\n\nconst std::string network_bnu_base::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_bnu_base::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_bnu_base::gradient_check( const output_ptr& out_ref )\n{\n    LOGGER(error) << \"network_bnu_base::gradient_check - not implemented yet for MLP\" << std::endl;\n}\n\n} /*namespace neurocl*/ } /*namespace mlp*/\n", "meta": {"hexsha": "f9106835efa7d546d433cdae6bd0cb3aa8c55f74", "size": 9355, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/mlp/network_bnu_base.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_bnu_base.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_bnu_base.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": 32.8245614035, "max_line_length": 150, "alphanum_fraction": 0.6196686264, "num_tokens": 2313, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6224593312018546, "lm_q2_score": 0.5350984286266115, "lm_q1q2_score": 0.33307701001008394}}
{"text": "\n\n/* --------------------------------------------------------------------- \n * \n * Copyright (C) 2012 - 2021 by the deal.II authors \n * \n * This file is part of the deal.II library. \n * \n * The deal.II library is free software; you can use it, redistribute \n * it, and/or modify it under the terms of the GNU Lesser General \n * Public License as published by the Free Software Foundation; either \n * version 2.1 of the License, or (at your option) any later version. \n * The full text of the license can be found in the file LICENSE.md at \n * the top level directory of deal.II. \n * \n * --------------------------------------------------------------------- \n * \n * Authors: Joerg Frohne, Texas A&M University and \n *                        University of Siegen, 2012, 2013 \n *          Wolfgang Bangerth, Texas A&M University, 2012, 2013 \n *          Timo Heister, Texas A&M University, 2013 \n */ \n\n\n// @sect3{Include files}  这组包含文件在这个时候已经没有什么惊喜了。\n\n#include <deal.II/base/conditional_ostream.h> \n#include <deal.II/base/parameter_handler.h> \n#include <deal.II/base/utilities.h> \n#include <deal.II/base/index_set.h> \n#include <deal.II/base/quadrature_lib.h> \n#include <deal.II/base/function.h> \n#include <deal.II/base/timer.h> \n\n#include <deal.II/lac/vector.h> \n#include <deal.II/lac/full_matrix.h> \n#include <deal.II/lac/sparsity_tools.h> \n#include <deal.II/lac/sparse_matrix.h> \n#include <deal.II/lac/block_sparsity_pattern.h> \n#include <deal.II/lac/solver_bicgstab.h> \n#include <deal.II/lac/precondition.h> \n#include <deal.II/lac/affine_constraints.h> \n#include <deal.II/lac/trilinos_sparse_matrix.h> \n#include <deal.II/lac/trilinos_block_sparse_matrix.h> \n#include <deal.II/lac/trilinos_vector.h> \n#include <deal.II/lac/trilinos_parallel_block_vector.h> \n#include <deal.II/lac/trilinos_precondition.h> \n#include <deal.II/lac/trilinos_solver.h> \n\n#include <deal.II/grid/tria.h> \n#include <deal.II/grid/grid_generator.h> \n#include <deal.II/grid/grid_tools.h> \n#include <deal.II/grid/manifold_lib.h> \n\n#include <deal.II/distributed/tria.h> \n#include <deal.II/distributed/grid_refinement.h> \n#include <deal.II/distributed/solution_transfer.h> \n\n#include <deal.II/dofs/dof_handler.h> \n#include <deal.II/dofs/dof_renumbering.h> \n#include <deal.II/dofs/dof_tools.h> \n\n#include <deal.II/fe/fe_q.h> \n#include <deal.II/fe/fe_system.h> \n#include <deal.II/fe/fe_values.h> \n\n#include <deal.II/numerics/vector_tools.h> \n#include <deal.II/numerics/matrix_tools.h> \n#include <deal.II/numerics/data_out.h> \n#include <deal.II/numerics/error_estimator.h> \n#include <deal.II/numerics/fe_field_function.h> \n\n#include <fstream> \n#include <iostream> \n\n// 最后，我们包括两个系统头文件，让我们为输出文件创建一个目录。第一个头文件提供了 <code>mkdir</code> 的功能，第二个头文件让我们确定在 <code>mkdir</code> 失败时发生了什么。\n\n#include <sys/stat.h> \n#include <cerrno> \n\nnamespace Step42 \n{ \n  using namespace dealii; \n// @sect3{The <code>ConstitutiveLaw</code> class template}  \n\n// 该类提供了一个构成法的接口，即应变  $\\varepsilon(\\mathbf u)$  和应力  $\\sigma$  之间的关系。在这个例子中，我们使用的是具有线性、各向同性硬化的弹塑性材料行为。这种材料的特点是杨氏模量  $E$  ，泊松比  $\\nu$  ，初始屈服应力  $\\sigma_0$  和各向同性硬化参数  $\\gamma$  。 对于 $\\gamma = 0$ ，我们得到完美的弹塑性行为。\n\n// 正如描述这个程序的论文所解释的那样，第一个牛顿步骤是用一个完全弹性材料模型来解决的，以避免同时处理两种非线性（塑性和接触）。为此，这个类有一个函数 <code>set_sigma_0()</code> ，我们在后面使用这个函数，简单地将 $\\sigma_0$ 设置为一个非常大的值--基本上保证了实际应力不会超过它，从而产生一个弹性材料。当我们准备使用塑性模型时，我们使用相同的函数将 $\\sigma_0$ 设置回其适当的值。 由于这种方法，我们需要将 <code>sigma_0</code> 作为这个类的唯一非静态成员变量。\n\n  template <int dim> \n  class ConstitutiveLaw \n  { \n  public: \n    ConstitutiveLaw(const double E, \n                    const double nu, \n                    const double sigma_0, \n                    const double gamma); \n\n    void set_sigma_0(double sigma_zero); \n\n    bool get_stress_strain_tensor( \n      const SymmetricTensor<2, dim> &strain_tensor, \n      SymmetricTensor<4, dim> &      stress_strain_tensor) const; \n\n    void get_linearized_stress_strain_tensors( \n      const SymmetricTensor<2, dim> &strain_tensor, \n      SymmetricTensor<4, dim> &      stress_strain_tensor_linearized, \n      SymmetricTensor<4, dim> &      stress_strain_tensor) const; \n\n  private: \n    const double kappa; \n    const double mu; \n    double       sigma_0; \n    const double gamma; \n\n    const SymmetricTensor<4, dim> stress_strain_tensor_kappa; \n    const SymmetricTensor<4, dim> stress_strain_tensor_mu; \n  }; \n\n// ConstitutiveLaw类的构造函数为我们的可变形体设置所需的材料参数。弹性各向同性介质的材料参数可以用多种方式定义，如一对 $E, \\nu$ （弹性模量和泊松数），使用Lam&eacute;参数 $\\lambda,mu$ 或其他几种常用的约定。在这里，构造器采用 $E,\\nu$ 形式的材料参数描述，但由于这证明这些不是出现在塑性投影仪方程中的系数，我们立即将它们转换为更合适的体模和剪模集合 $\\kappa,\\mu$ 。 此外，构造器以 $\\sigma_0$ （无任何塑性应变的屈服应力）和 $\\gamma$ （硬化参数）作为参数。在这个构造函数中，我们还计算了应力-应变关系的两个主成分及其线性化。\n\n  template <int dim> \n  ConstitutiveLaw<dim>::ConstitutiveLaw(double E, \n                                        double nu, \n                                        double sigma_0, \n                                        double gamma) \n    : kappa(E / (3 * (1 - 2 * nu))) \n    , mu(E / (2 * (1 + nu))) \n    , sigma_0(sigma_0) \n    , gamma(gamma) \n    , stress_strain_tensor_kappa(kappa * \n                                 outer_product(unit_symmetric_tensor<dim>(), \n                                               unit_symmetric_tensor<dim>())) \n    , stress_strain_tensor_mu( \n        2 * mu * \n        (identity_tensor<dim>() - outer_product(unit_symmetric_tensor<dim>(), \n                                                unit_symmetric_tensor<dim>()) / \n                                    3.0)) \n  {} \n\n  template <int dim> \n  void ConstitutiveLaw<dim>::set_sigma_0(double sigma_zero) \n  { \n    sigma_0 = sigma_zero; \n  } \n// @sect4{ConstitutiveLaw::get_stress_strain_tensor}  \n\n// 这是构成法则的主成分。它计算的是四阶对称张量，根据上面给出的投影，当在一个特定的应变点上评估时，该张量将应变与应力联系起来。我们需要这个函数来计算 <code>PlasticityContactProblem::residual_nl_system()</code> 中的非线性残差，我们将这个张量与正交点的应变相乘。计算遵循介绍中列出的公式。在比较那里的公式和下面的实现时，记得 $C_\\mu : \\varepsilon = \\tau_D$ 和 $C_\\kappa : \\varepsilon = \\kappa \\text{trace}(\\varepsilon) I = \\frac 13 \\text{trace}(\\tau) I$  。\n\n// 该函数返回正交点是否是塑性的，以便在下游对有多少正交点是塑性的，有多少是弹性的进行一些统计。\n\n  template <int dim> \n  bool ConstitutiveLaw<dim>::get_stress_strain_tensor( \n    const SymmetricTensor<2, dim> &strain_tensor, \n    SymmetricTensor<4, dim> &      stress_strain_tensor) const \n  { \n    Assert(dim == 3, ExcNotImplemented()); \n\n    SymmetricTensor<2, dim> stress_tensor; \n    stress_tensor = \n      (stress_strain_tensor_kappa + stress_strain_tensor_mu) * strain_tensor; \n\n    const SymmetricTensor<2, dim> deviator_stress_tensor = \n      deviator(stress_tensor); \n    const double deviator_stress_tensor_norm = deviator_stress_tensor.norm(); \n\n    stress_strain_tensor = stress_strain_tensor_mu; \n    if (deviator_stress_tensor_norm > sigma_0) \n      { \n        const double beta = sigma_0 / deviator_stress_tensor_norm; \n        stress_strain_tensor *= (gamma + (1 - gamma) * beta); \n      } \n\n    stress_strain_tensor += stress_strain_tensor_kappa; \n\n    return (deviator_stress_tensor_norm > sigma_0); \n  } \n// @sect4{ConstitutiveLaw::get_linearized_stress_strain_tensors}  \n\n// 该函数返回线性化的应力应变张量，围绕前一个牛顿步骤 $u^{i-1}$ 的解进行线性化  $i-1$  。 参数 <code>strain_tensor</code> （通常表示为 $\\varepsilon(u^{i-1})$ ）必须作为参数传递，并作为线性化点。该函数在变量stress_strain_tensor中返回非线性构成法的导数，在stress_strain_tensor_linearized中返回线性化问题的应力-应变张量。 参见 PlasticityContactProblem::assemble_nl_system ，其中使用了这个函数。\n\n  template <int dim> \n  void ConstitutiveLaw<dim>::get_linearized_stress_strain_tensors( \n    const SymmetricTensor<2, dim> &strain_tensor, \n    SymmetricTensor<4, dim> &      stress_strain_tensor_linearized, \n    SymmetricTensor<4, dim> &      stress_strain_tensor) const \n  { \n    Assert(dim == 3, ExcNotImplemented()); \n\n    SymmetricTensor<2, dim> stress_tensor; \n    stress_tensor = \n      (stress_strain_tensor_kappa + stress_strain_tensor_mu) * strain_tensor; \n\n    stress_strain_tensor            = stress_strain_tensor_mu; \n    stress_strain_tensor_linearized = stress_strain_tensor_mu; \n\n    SymmetricTensor<2, dim> deviator_stress_tensor = deviator(stress_tensor); \n    const double deviator_stress_tensor_norm = deviator_stress_tensor.norm(); \n\n    if (deviator_stress_tensor_norm > sigma_0) \n      { \n        const double beta = sigma_0 / deviator_stress_tensor_norm; \n        stress_strain_tensor *= (gamma + (1 - gamma) * beta); \n        stress_strain_tensor_linearized *= (gamma + (1 - gamma) * beta); \n        deviator_stress_tensor /= deviator_stress_tensor_norm; \n        stress_strain_tensor_linearized -= \n          (1 - gamma) * beta * 2 * mu * \n          outer_product(deviator_stress_tensor, deviator_stress_tensor); \n      } \n\n    stress_strain_tensor += stress_strain_tensor_kappa; \n    stress_strain_tensor_linearized += stress_strain_tensor_kappa; \n  } \n//<h3>Equation data: boundary forces, boundary values, obstacles</h3>\n\n// 下面的内容应该是比较标准的。我们需要边界强迫项（我们在此选择为零）和不属于接触面的边界部分的边界值（在此也选择为零）的类。\n\n  namespace EquationData \n  { \n    template <int dim> \n    class BoundaryForce : public Function<dim> \n    { \n    public: \n      BoundaryForce(); \n\n      virtual double value(const Point<dim> & p, \n                           const unsigned int component = 0) const override; \n\n      virtual void vector_value(const Point<dim> &p, \n                                Vector<double> &  values) const override; \n    }; \n\n    template <int dim> \n    BoundaryForce<dim>::BoundaryForce() \n      : Function<dim>(dim) \n    {} \n\n    template <int dim> \n    double BoundaryForce<dim>::value(const Point<dim> &, \n                                     const unsigned int) const \n    { \n      return 0.; \n    } \n\n    template <int dim> \n    void BoundaryForce<dim>::vector_value(const Point<dim> &p, \n                                          Vector<double> &  values) const \n    { \n      for (unsigned int c = 0; c < this->n_components; ++c) \n        values(c) = BoundaryForce<dim>::value(p, c); \n    } \n\n    template <int dim> \n    class BoundaryValues : public Function<dim> \n    { \n    public: \n      BoundaryValues(); \n\n      virtual double value(const Point<dim> & p, \n                           const unsigned int component = 0) const override; \n    }; \n\n    template <int dim> \n    BoundaryValues<dim>::BoundaryValues() \n      : Function<dim>(dim) \n    {} \n\n    template <int dim> \n    double BoundaryValues<dim>::value(const Point<dim> &, \n                                      const unsigned int) const \n    { \n      return 0.; \n    } \n\n//  @sect4{The <code>SphereObstacle</code> class}  \n\n// 下面这个类是可以从输入文件中选择的两个障碍物中的第一个。它描述了一个以位置 $x=y=0.5, z=z_{\\text{surface}}+0.59$ 和半径 $r=0.6$ 为中心的球体，其中 $z_{\\text{surface}}$ 是可变形体的（平）表面的垂直位置。该函数的 <code>value</code> 返回给定 $x,y$ 值的障碍物位置，如果该点实际位于球体下方，则返回一个不可能干扰变形的大正值，如果它位于球体的 \"阴影 \"之外。\n\n    template <int dim> \n    class SphereObstacle : public Function<dim> \n    { \n    public: \n      SphereObstacle(const double z_surface); \n\n      virtual double value(const Point<dim> & p, \n                           const unsigned int component = 0) const override; \n\n      virtual void vector_value(const Point<dim> &p, \n                                Vector<double> &  values) const override; \n\n    private: \n      const double z_surface; \n    }; \n\n    template <int dim> \n    SphereObstacle<dim>::SphereObstacle(const double z_surface) \n      : Function<dim>(dim) \n      , z_surface(z_surface) \n    {} \n\n    template <int dim> \n    double SphereObstacle<dim>::value(const Point<dim> & p, \n                                      const unsigned int component) const \n    { \n      if (component == 0) \n        return p(0); \n      else if (component == 1) \n        return p(1); \n      else if (component == 2) \n        { \n          if ((p(0) - 0.5) * (p(0) - 0.5) + (p(1) - 0.5) * (p(1) - 0.5) < 0.36) \n            return (-std::sqrt(0.36 - (p(0) - 0.5) * (p(0) - 0.5) - \n                               (p(1) - 0.5) * (p(1) - 0.5)) + \n                    z_surface + 0.59); \n          else \n            return 1000; \n        } \n\n      Assert(false, ExcNotImplemented()); \n      return 1e9; // an unreasonable value; ignored in debug mode because of the \n\n// 前面的断言\n\n    } \n\n    template <int dim> \n    void SphereObstacle<dim>::vector_value(const Point<dim> &p, \n                                           Vector<double> &  values) const \n    { \n      for (unsigned int c = 0; c < this->n_components; ++c) \n        values(c) = SphereObstacle<dim>::value(p, c); \n    } \n// @sect4{The <code>BitmapFile</code> and <code>ChineseObstacle</code> classes}  \n\n// 下面两个类描述了介绍中概述的障碍物，即汉字。两个中的第一个， <code>BitmapFile</code> 负责从一个以pbm ascii格式存储的图片文件中读入数据。这个数据将被双线性插值，从而提供一个描述障碍物的函数。(下面的代码显示了如何通过在给定的数据点之间进行内插来构造一个函数。人们可以使用在这个教程程序写完后引入的 Functions::InterpolatedUniformGridData, ，它正是我们在这里想要的，但看看如何手工操作是有启发的）。)\n\n// 我们从文件中读取的数据将被存储在一个名为 obstacle_data 的双 std::vector 中。 这个向量构成了计算单片双线性函数的基础，作为一个多项式插值。我们将从文件中读取的数据由零（白色）和一（黑色）组成。\n\n//  <code>hx,hy</code> 变量表示 $x$ 和 $y$ 方向的像素之间的间距。  <code>nx,ny</code> 是这些方向上的像素的数量。   <code>get_value()</code> 返回图像在给定位置的值，由相邻像素值插值而成。\n\n    template <int dim> \n    class BitmapFile \n    { \n    public: \n      BitmapFile(const std::string &name); \n\n      double get_value(const double x, const double y) const; \n\n    private: \n      std::vector<double> obstacle_data; \n      double              hx, hy; \n      int                 nx, ny; \n\n      double get_pixel_value(const int i, const int j) const; \n    }; \n\n// 该类的构造函数从给定的文件名中读入描述障碍物的数据。\n\n    template <int dim> \n    BitmapFile<dim>::BitmapFile(const std::string &name) \n      : obstacle_data(0) \n      , hx(0) \n      , hy(0) \n      , nx(0) \n      , ny(0) \n    { \n      std::ifstream f(name); \n      AssertThrow(f, \n                  ExcMessage(std::string(\"Can't read from file <\") + name + \n                             \">!\")); \n\n      std::string temp; \n      f >> temp >> nx >> ny; \n\n      AssertThrow(nx > 0 && ny > 0, ExcMessage(\"Invalid file format.\")); \n\n      for (int k = 0; k < nx * ny; ++k) \n        { \n          double val; \n          f >> val; \n          obstacle_data.push_back(val); \n        } \n\n      hx = 1.0 / (nx - 1); \n      hy = 1.0 / (ny - 1); \n\n      if (Utilities::MPI::this_mpi_process(MPI_COMM_WORLD) == 0) \n        std::cout << \"Read obstacle from file <\" << name << \">\" << std::endl \n                  << \"Resolution of the scanned obstacle picture: \" << nx \n                  << \" x \" << ny << std::endl; \n    } \n\n// 下面两个函数返回坐标为 $i,j$ 的给定像素的值，我们将其与定义在位置 <code>i*hx, j*hy</code> 的函数值和任意坐标 $x,y$ 的函数值相识别，在这里我们对两个函数中第一个函数返回的点值进行双线性内插。在第二个函数中，对于每个 $x,y$ ，我们首先计算离 $x,y$ 左下方最近的像素坐标的（整数）位置，然后计算这个像素内的坐标 $\\xi,\\eta$ 。我们从下方和上方截断这两种变量，以避免在评估函数时超出其定义的范围而可能发生的舍入误差问题。\n\n    template <int dim> \n    double BitmapFile<dim>::get_pixel_value(const int i, const int j) const \n    { \n      assert(i >= 0 && i < nx); \n      assert(j >= 0 && j < ny); \n      return obstacle_data[nx * (ny - 1 - j) + i]; \n    } \n\n    template <int dim> \n    double BitmapFile<dim>::get_value(const double x, const double y) const \n    { \n      const int ix = std::min(std::max(static_cast<int>(x / hx), 0), nx - 2); \n      const int iy = std::min(std::max(static_cast<int>(y / hy), 0), ny - 2); \n\n      const double xi  = std::min(std::max((x - ix * hx) / hx, 1.), 0.); \n      const double eta = std::min(std::max((y - iy * hy) / hy, 1.), 0.); \n\n      return ((1 - xi) * (1 - eta) * get_pixel_value(ix, iy) + \n              xi * (1 - eta) * get_pixel_value(ix + 1, iy) + \n              (1 - xi) * eta * get_pixel_value(ix, iy + 1) + \n              xi * eta * get_pixel_value(ix + 1, iy + 1)); \n    } \n\n// 最后，这是一个实际使用上面的类的类。它有一个BitmapFile对象作为成员，描述障碍物的高度。如上所述，BitmapFile类将为我们提供一个掩码，即要么是0，要么是1的值（如果你要求的是像素之间的位置，则是在0和1之间插值的值）。这个类将其转化为高度，即低于可变形体表面的0.001（如果BitmapFile类在此位置报告为1）或高于障碍物的0.999（如果BitmapFile类报告为0）。那么下面的函数应该是不言自明的。\n\n    template <int dim> \n    class ChineseObstacle : public Function<dim> \n    { \n    public: \n      ChineseObstacle(const std::string &filename, const double z_surface); \n\n      virtual double value(const Point<dim> & p, \n                           const unsigned int component = 0) const override; \n\n      virtual void vector_value(const Point<dim> &p, \n                                Vector<double> &  values) const override; \n\n    private: \n      const BitmapFile<dim> input_obstacle; \n      double                z_surface; \n    }; \n\n    template <int dim> \n    ChineseObstacle<dim>::ChineseObstacle(const std::string &filename, \n                                          const double       z_surface) \n      : Function<dim>(dim) \n      , input_obstacle(filename) \n      , z_surface(z_surface) \n    {} \n\n    template <int dim> \n    double ChineseObstacle<dim>::value(const Point<dim> & p, \n                                       const unsigned int component) const \n    { \n      if (component == 0) \n        return p(0); \n      if (component == 1) \n        return p(1); \n      else if (component == 2) \n        { \n          if (p(0) >= 0.0 && p(0) <= 1.0 && p(1) >= 0.0 && p(1) <= 1.0) \n            return z_surface + 0.999 - input_obstacle.get_value(p(0), p(1)); \n        } \n\n      Assert(false, ExcNotImplemented()); \n      return 1e9; // an unreasonable value; ignored in debug mode because of the \n\n// 前面的断言\n\n    } \n\n    template <int dim> \n    void ChineseObstacle<dim>::vector_value(const Point<dim> &p, \n                                            Vector<double> &  values) const \n    { \n      for (unsigned int c = 0; c < this->n_components; ++c) \n        values(c) = ChineseObstacle<dim>::value(p, c); \n    } \n  } // namespace EquationData \n// @sect3{The <code>PlasticityContactProblem</code> class template}  \n\n// 这是本程序的主类，提供了描述非线性接触问题所需的所有函数和变量。它接近于 step-41 ，但有一些额外的功能，如处理悬挂节点，牛顿方法，使用Trilinos和p4est进行并行分布式计算。处理悬空节点使生活变得有点复杂，因为我们现在需要另一个AffineConstraints对象。我们为接触情况下的主动集合方法创建一个牛顿方法，并处理构成法的非线性算子。\n\n// 这个类的总体布局与其他大多数教程程序非常相似。为了使我们的生活更容易一些，这个类从输入文件中读取一组输入参数。这些参数，使用ParameterHandler类，在 <code>declare_parameters</code> 函数中声明（该函数是静态的，因此它可以在我们创建当前类型的对象之前被调用），然后一个已经用于读取输入文件的ParameterHandler对象将被传递给该类的构造函数。\n\n// 其余的成员函数大体上与我们在其他几个教程程序中看到的一样，虽然为当前的非线性系统增加了一些内容。我们将在下文中对它们的用途进行评论。\n\n  template <int dim> \n  class PlasticityContactProblem \n  { \n  public: \n    PlasticityContactProblem(const ParameterHandler &prm); \n\n    void run(); \n\n    static void declare_parameters(ParameterHandler &prm); \n\n  private: \n    void make_grid(); \n    void setup_system(); \n    void compute_dirichlet_constraints(); \n    void update_solution_and_constraints(); \n    void \n         assemble_mass_matrix_diagonal(TrilinosWrappers::SparseMatrix &mass_matrix); \n    void assemble_newton_system( \n      const TrilinosWrappers::MPI::Vector &linearization_point); \n    void compute_nonlinear_residual( \n      const TrilinosWrappers::MPI::Vector &linearization_point); \n    void solve_newton_system(); \n    void solve_newton(); \n    void refine_grid(); \n    void move_mesh(const TrilinosWrappers::MPI::Vector &displacement) const; \n    void output_results(const unsigned int current_refinement_cycle); \n\n    void output_contact_force() const; \n\n// 就成员变量而言，我们先用一个变量来表示这个程序运行的MPI宇宙，一个我们用来让确切的一个处理器产生输出到控制台的流（见 step-17  ）和一个用来为程序的各个部分计时的变量。\n\n    MPI_Comm           mpi_communicator; \n    ConditionalOStream pcout; \n    TimerOutput        computing_timer; \n\n// 下一组描述网格和有限元空间。特别是，对于这个并行程序，有限元空间有与之相关的变量，表明哪些自由度存在于当前的处理器上（索引集，也见 step-40 和 @ref distributed 文档模块），以及各种约束：那些由悬挂节点，由Dirichlet边界条件，以及由接触节点的活动集施加的约束。在这里定义的三个AffineConstraints变量中，第一个变量只包含悬挂节点的约束，第二个变量也包含与Dirichlet边界条件相关的约束，第三个变量包含这些约束和接触约束。\n\n// 变量 <code>active_set</code> 包括那些由接触约束的自由度，我们用 <code>fraction_of_plastic_q_points_per_cell</code> 来跟踪每个单元上应力等于屈服应力的正交点的分数。后者仅用于创建显示塑性区的图形输出，但不用于任何进一步的计算；该变量是该类的成员变量，因为该信息是作为计算残差的副产品计算的，但仅在很晚的时候使用。(注意，该向量是一个长度等于<i>local mesh</i>上活动单元数量的向量；它从未被用来在处理器之间交换信息，因此可以是一个普通的deal.II向量)。\n\n    const unsigned int                        n_initial_global_refinements; \n    parallel::distributed::Triangulation<dim> triangulation; \n\n    const unsigned int fe_degree; \n    FESystem<dim>      fe; \n    DoFHandler<dim>    dof_handler; \n\n    IndexSet locally_owned_dofs; \n    IndexSet locally_relevant_dofs; \n\n    AffineConstraints<double> constraints_hanging_nodes; \n    AffineConstraints<double> constraints_dirichlet_and_hanging_nodes; \n    AffineConstraints<double> all_constraints; \n\n    IndexSet      active_set; \n    Vector<float> fraction_of_plastic_q_points_per_cell; \n\n// 下一个变量块对应的是解决方案和我们需要形成的线性系统。特别是，这包括牛顿矩阵和右手边；与残差（即牛顿右手边）相对应的向量，但我们没有消除其中的各种约束，该向量用于确定在下一次迭代中需要约束哪些自由度；以及一个与介绍中简要提到的 $B$ 矩阵的对角线相对应的向量，并在随文中讨论。\n\n    TrilinosWrappers::SparseMatrix newton_matrix; \n\n    TrilinosWrappers::MPI::Vector solution; \n    TrilinosWrappers::MPI::Vector newton_rhs; \n    TrilinosWrappers::MPI::Vector newton_rhs_uncondensed; \n    TrilinosWrappers::MPI::Vector diag_mass_matrix_vector; \n\n// 下一个块包含描述材料响应的变量。\n\n    const double         e_modulus, nu, gamma, sigma_0; \n    ConstitutiveLaw<dim> constitutive_law; \n\n// 然后是各种各样的其他变量，用于识别参数文件所选择的要求我们建立的网格，被推入可变形体的障碍物，网格细化策略，是否将解决方案从一个网格转移到下一个网格，以及要执行多少个网格细化循环。在可能的情况下，我们将这些类型的变量标记为 <code>const</code> ，以帮助读者识别哪些变量以后可能会被修改，哪些可能不会被修改（输出目录是一个例外--它在构造函数之外从不被修改，但在构造函数中冒号后面的成员初始化列表中初始化是很尴尬的，因为在那里我们只有一次机会设置它；网格细化准则也是如此）。\n\n    const std::string                          base_mesh; \n    const std::shared_ptr<const Function<dim>> obstacle; \n\n    struct RefinementStrategy \n    { \n      enum value \n      { \n        refine_global, \n        refine_percentage, \n        refine_fix_dofs \n      }; \n    }; \n    typename RefinementStrategy::value refinement_strategy; \n\n    const bool         transfer_solution; \n    std::string        output_dir; \n    const unsigned int n_refinement_cycles; \n    unsigned int       current_refinement_cycle; \n  }; \n// @sect3{Implementation of the <code>PlasticityContactProblem</code> class}  \n// @sect4{PlasticityContactProblem::declare_parameters}  \n\n// 让我们从声明可在输入文件中选择的运行时参数开始。这些值将在本类的构造函数中读回，以初始化本类的成员变量。\n\n  template <int dim> \n  void PlasticityContactProblem<dim>::declare_parameters(ParameterHandler &prm) \n  { \n    prm.declare_entry( \n      \"polynomial degree\", \n      \"1\", \n      Patterns::Integer(), \n      \"Polynomial degree of the FE_Q finite element space, typically 1 or 2.\"); \n    prm.declare_entry(\"number of initial refinements\", \n                      \"2\", \n                      Patterns::Integer(), \n                      \"Number of initial global mesh refinement steps before \" \n                      \"the first computation.\"); \n    prm.declare_entry( \n      \"refinement strategy\", \n      \"percentage\", \n      Patterns::Selection(\"global|percentage\"), \n      \"Mesh refinement strategy:\\n\" \n      \" global: one global refinement\\n\" \n      \" percentage: a fixed percentage of cells gets refined using the Kelly estimator.\"); \n    prm.declare_entry(\"number of cycles\", \n                      \"5\", \n                      Patterns::Integer(), \n                      \"Number of adaptive mesh refinement cycles to run.\"); \n    prm.declare_entry( \n      \"obstacle\", \n      \"sphere\", \n      Patterns::Selection(\"sphere|read from file\"), \n      \"The name of the obstacle to use. This may either be 'sphere' if we should \" \n      \"use a spherical obstacle, or 'read from file' in which case the obstacle \" \n      \"will be read from a file named 'obstacle.pbm' that is supposed to be in \" \n      \"ASCII PBM format.\"); \n    prm.declare_entry( \n      \"output directory\", \n      \"\", \n      Patterns::Anything(), \n      \"Directory for output files (graphical output and benchmark \" \n      \"statistics). If empty, use the current directory.\"); \n    prm.declare_entry( \n      \"transfer solution\", \n      \"false\", \n      Patterns::Bool(), \n      \"Whether the solution should be used as a starting guess \" \n      \"for the next finer mesh. If false, then the iteration starts at \" \n      \"zero on every mesh.\"); \n    prm.declare_entry(\"base mesh\", \n                      \"box\", \n                      Patterns::Selection(\"box|half sphere\"), \n                      \"Select the shape of the domain: 'box' or 'half sphere'\"); \n  } \n// @sect4{The <code>PlasticityContactProblem</code> constructor}  \n\n// 鉴于成员变量的声明以及从输入文件中读取的运行时参数的声明，在这个构造函数中没有任何令人惊讶的地方。在正文中，我们初始化了网格细化策略和输出目录，必要时创建这样一个目录。\n\n  template <int dim> \n  PlasticityContactProblem<dim>::PlasticityContactProblem( \n    const ParameterHandler &prm) \n    : mpi_communicator(MPI_COMM_WORLD) \n    , pcout(std::cout, \n            (Utilities::MPI::this_mpi_process(mpi_communicator) == 0)) \n    , computing_timer(MPI_COMM_WORLD, \n                      pcout, \n                      TimerOutput::never, \n                      TimerOutput::wall_times) \n\n    , n_initial_global_refinements( \n        prm.get_integer(\"number of initial refinements\")) \n    , triangulation(mpi_communicator) \n    , fe_degree(prm.get_integer(\"polynomial degree\")) \n    , fe(FE_Q<dim>(QGaussLobatto<1>(fe_degree + 1)), dim) \n    , dof_handler(triangulation) \n\n    , e_modulus(200000) \n    , nu(0.3) \n    , gamma(0.01) \n    , sigma_0(400.0) \n    , constitutive_law(e_modulus, nu, sigma_0, gamma) \n\n    , base_mesh(prm.get(\"base mesh\")) \n    , obstacle(prm.get(\"obstacle\") == \"read from file\" ? \n                 static_cast<const Function<dim> *>( \n                   new EquationData::ChineseObstacle<dim>( \n                     \"obstacle.pbm\", \n                     (base_mesh == \"box\" ? 1.0 : 0.5))) : \n                 static_cast<const Function<dim> *>( \n                   new EquationData::SphereObstacle<dim>( \n                     base_mesh == \"box\" ? 1.0 : 0.5))) \n\n    , transfer_solution(prm.get_bool(\"transfer solution\")) \n    , n_refinement_cycles(prm.get_integer(\"number of cycles\")) \n    , current_refinement_cycle(0) \n\n  { \n    std::string strat = prm.get(\"refinement strategy\"); \n    if (strat == \"global\") \n      refinement_strategy = RefinementStrategy::refine_global; \n    else if (strat == \"percentage\") \n      refinement_strategy = RefinementStrategy::refine_percentage; \n    else \n      AssertThrow(false, ExcNotImplemented()); \n\n    output_dir = prm.get(\"output directory\"); \n    if (output_dir != \"\" && *(output_dir.rbegin()) != '/') \n      output_dir += \"/\"; \n\n// 如果有必要，为输出创建一个新的目录。\n\n    if (Utilities::MPI::this_mpi_process(mpi_communicator) == 0) \n      { \n        const int ierr = mkdir(output_dir.c_str(), 0777); \n        AssertThrow(ierr == 0 || errno == EEXIST, ExcIO()); \n      } \n\n    pcout << \"    Using output directory '\" << output_dir << \"'\" << std::endl; \n    pcout << \"    FE degree \" << fe_degree << std::endl; \n    pcout << \"    transfer solution \" << (transfer_solution ? \"true\" : \"false\") \n          << std::endl; \n  } \n\n//  @sect4{PlasticityContactProblem::make_grid}  \n\n// 下一个区块是关于构建起始网格的。我们将使用下面的辅助函数和 <code>make_grid()</code> 的第一个块来构造一个对应于半球形的网格。deal.II有一个函数可以创建这样的网格，但是它的位置和方向都是错误的，所以我们需要在使用它之前对它进行一些位移和旋转。\n\n// 供以后参考，如 GridGenerator::half_hyper_ball(), 文件中所述，半球体的平坦表面的边界指标为零，而其余部分的边界指标为一。\n\n  Point<3> rotate_half_sphere(const Point<3> &in) \n  { \n    return {in(2), in(1), -in(0)}; \n  } \n\n  template <int dim> \n  void PlasticityContactProblem<dim>::make_grid() \n  { \n    if (base_mesh == \"half sphere\") \n      { \n        const Point<dim> center(0, 0, 0); \n        const double     radius = 0.8; \n        GridGenerator::half_hyper_ball(triangulation, center, radius); \n\n// 由于我们将在下面附加一个不同的流形，我们立即清除默认的流形描述。\n\n        triangulation.reset_all_manifolds(); \n\n        GridTools::transform(&rotate_half_sphere, triangulation); \n        GridTools::shift(Point<dim>(0.5, 0.5, 0.5), triangulation); \n\n        SphericalManifold<dim> manifold_description(Point<dim>(0.5, 0.5, 0.5)); \n        GridTools::copy_boundary_to_manifold_id(triangulation); \n        triangulation.set_manifold(0, manifold_description); \n      } \n\n// 或者，创建一个超立方体网格。创建后，按如下方式分配边界指标。\n// @code\n//  >     _______\n//  >    /  1    /|\n//  >   /______ / |\n//  >  |       | 8|\n//  >  |   8   | /\n//  >  |_______|/\n//  >      6\n//  @endcode\n  // 换句话说，立方体的边的边界指标是8。底部的边界指标是6，顶部的指标是1。我们通过循环所有面的所有单元并查看单元中心的坐标值来设置这些指标，并在以后评估哪个边界将携带迪里希特边界条件或将受到潜在接触时使用这些指标。(在目前的情况下，网格只包含一个单元，它的所有面都在边界上，所以严格来说，所有单元的循环和查询一个面是否在边界上都是不必要的；我们保留它们只是出于习惯：这种代码可以在许多程序中找到，基本上都是这种形式。)\n\n    else \n      { \n        const Point<dim> p1(0, 0, 0); \n        const Point<dim> p2(1.0, 1.0, 1.0); \n\n        GridGenerator::hyper_rectangle(triangulation, p1, p2); \n\n        for (const auto &cell : triangulation.active_cell_iterators()) \n          for (const auto &face : cell->face_iterators()) \n            if (face->at_boundary()) \n              { \n                if (std::fabs(face->center()[2] - p2[2]) < 1e-12) \n                  face->set_boundary_id(1); \n                if (std::fabs(face->center()[0] - p1[0]) < 1e-12 || \n                    std::fabs(face->center()[0] - p2[0]) < 1e-12 || \n                    std::fabs(face->center()[1] - p1[1]) < 1e-12 || \n                    std::fabs(face->center()[1] - p2[1]) < 1e-12) \n                  face->set_boundary_id(8); \n                if (std::fabs(face->center()[2] - p1[2]) < 1e-12) \n                  face->set_boundary_id(6); \n              } \n      } \n\n    triangulation.refine_global(n_initial_global_refinements); \n  } \n\n//  @sect4{PlasticityContactProblem::setup_system}  \n\n// 谜题的下一块是设置DoFHandler，调整向量大小，并处理其他各种状态变量，如索引集和约束矩阵。\n\n// 在下面的内容中，每一组操作都被放入一个大括号封闭的块中，该块的顶部声明的变量正在进行计时（ TimerOutput::Scope 变量的构造器开始计时部分，在块的末端调用的析构器再次停止计时）。\n\n  template <int dim> \n  void PlasticityContactProblem<dim>::setup_system() \n  { \n\n/* 设置dofs，并为本地拥有的相关dofs获取索引集  */ \n\n    { \n      TimerOutput::Scope t(computing_timer, \"Setup: distribute DoFs\"); \n      dof_handler.distribute_dofs(fe); \n\n      locally_owned_dofs = dof_handler.locally_owned_dofs(); \n      locally_relevant_dofs.clear(); \n      DoFTools::extract_locally_relevant_dofs(dof_handler, \n                                              locally_relevant_dofs); \n    } \n\n/*设置悬挂节点和Dirichlet约束 */ \n\n \n    { \n      TimerOutput::Scope t(computing_timer, \"Setup: constraints\"); \n      constraints_hanging_nodes.reinit(locally_relevant_dofs); \n      DoFTools::make_hanging_node_constraints(dof_handler, \n                                              constraints_hanging_nodes); \n      constraints_hanging_nodes.close(); \n\n      pcout << \"   Number of active cells: \" \n            << triangulation.n_global_active_cells() << std::endl \n            << \"   Number of degrees of freedom: \" << dof_handler.n_dofs() \n            << std::endl; \n\n      compute_dirichlet_constraints(); \n    } \n\n/* 初始化向量和活动集  */ \n\n    { \n      TimerOutput::Scope t(computing_timer, \"Setup: vectors\"); \n      solution.reinit(locally_relevant_dofs, mpi_communicator); \n      newton_rhs.reinit(locally_owned_dofs, mpi_communicator); \n      newton_rhs_uncondensed.reinit(locally_owned_dofs, mpi_communicator); \n      diag_mass_matrix_vector.reinit(locally_owned_dofs, mpi_communicator); \n      fraction_of_plastic_q_points_per_cell.reinit( \n        triangulation.n_active_cells()); \n\n      active_set.clear(); \n      active_set.set_size(dof_handler.n_dofs()); \n    } \n\n// 最后，我们设置了稀疏模式和矩阵。我们暂时（ab）用系统矩阵来同时建立（对角线）矩阵，用于消除与障碍物接触的自由度，但我们随后立即将牛顿矩阵设回零。\n\n    { \n      TimerOutput::Scope                t(computing_timer, \"Setup: matrix\"); \n      TrilinosWrappers::SparsityPattern sp(locally_owned_dofs, \n                                           mpi_communicator); \n\n      DoFTools::make_sparsity_pattern(dof_handler, \n                                      sp, \n                                      constraints_dirichlet_and_hanging_nodes, \n                                      false, \n                                      Utilities::MPI::this_mpi_process( \n                                        mpi_communicator)); \n      sp.compress(); \n      newton_matrix.reinit(sp); \n\n      TrilinosWrappers::SparseMatrix &mass_matrix = newton_matrix; \n\n      assemble_mass_matrix_diagonal(mass_matrix); \n\n      const unsigned int start = (newton_rhs.local_range().first), \n                         end   = (newton_rhs.local_range().second); \n      for (unsigned int j = start; j < end; ++j) \n        diag_mass_matrix_vector(j) = mass_matrix.diag_element(j); \n      diag_mass_matrix_vector.compress(VectorOperation::insert); \n\n      mass_matrix = 0; \n    } \n  } \n// @sect4{PlasticityContactProblem::compute_dirichlet_constraints}  \n\n// 这个函数从前面的函数中分离出来，计算与迪里切特型边界条件相关的约束，并通过与来自悬挂节点的约束合并，将其放入 <code>constraints_dirichlet_and_hanging_nodes</code> 变量。\n\n// 正如在介绍中所阐述的，我们需要区分两种情况。\n\n// - 如果域是一个盒子，我们将底部的位移设置为零，并允许沿侧面的Z方向的垂直运动。如 <code>make_grid()</code> 函数所示，前者对应于边界指标6，后者对应于8。\n\n// - 如果域是一个半球形，那么我们沿边界的弯曲部分施加零位移，与边界指标0相关。\n\n  template <int dim> \n  void PlasticityContactProblem<dim>::compute_dirichlet_constraints() \n  { \n    constraints_dirichlet_and_hanging_nodes.reinit(locally_relevant_dofs); \n    constraints_dirichlet_and_hanging_nodes.merge(constraints_hanging_nodes); \n\n    if (base_mesh == \"box\") \n      { \n\n//插值解决方案的所有组成部分\n\n        VectorTools::interpolate_boundary_values( \n          dof_handler, \n          6, \n          EquationData::BoundaryValues<dim>(), \n          constraints_dirichlet_and_hanging_nodes, \n          ComponentMask()); \n\n//对解决方案的X和Y分量进行插值（这是一个位掩码，所以应用运算器|）。\n\n        const FEValuesExtractors::Scalar x_displacement(0); \n        const FEValuesExtractors::Scalar y_displacement(1); \n        VectorTools::interpolate_boundary_values( \n          dof_handler, \n          8, \n          EquationData::BoundaryValues<dim>(), \n          constraints_dirichlet_and_hanging_nodes, \n          (fe.component_mask(x_displacement) | \n           fe.component_mask(y_displacement))); \n      } \n    else \n      VectorTools::interpolate_boundary_values( \n        dof_handler, \n        0, \n        EquationData::BoundaryValues<dim>(), \n        constraints_dirichlet_and_hanging_nodes, \n        ComponentMask()); \n\n    constraints_dirichlet_and_hanging_nodes.close(); \n  } \n\n//  @sect4{PlasticityContactProblem::assemble_mass_matrix_diagonal}  \n\n// 下一个辅助函数计算（对角线）质量矩阵，用于确定我们在接触算法中使用的主动集合方法的主动集合。这个矩阵是质量矩阵类型的，但与标准质量矩阵不同，我们可以通过使用正交公式使其成为对角线（即使在高阶元素的情况下），该公式的正交点与有限元插值点的位置完全相同。我们通过使用QGaussLobatto正交公式来实现这一点，同时用一组从同一正交公式得出的插值点初始化有限元。该函数的其余部分相对简单：我们将得到的矩阵放入给定的参数中；因为我们知道矩阵是对角线的，所以只需在 $i$ 而不是 $j$ 上有一个循环即可。严格来说，我们甚至可以避免在正交点 <code>q_point</code> 处将形状函数的值与自身相乘，因为我们知道形状值是一个恰好有一个的向量，当与自身相点时产生1。由于这个函数不是时间关键，为了清楚起见，我们添加了这个术语。\n\n  template <int dim> \n  void PlasticityContactProblem<dim>::assemble_mass_matrix_diagonal( \n    TrilinosWrappers::SparseMatrix &mass_matrix) \n  { \n    QGaussLobatto<dim - 1> face_quadrature_formula(fe.degree + 1); \n\n    FEFaceValues<dim> fe_values_face(fe, \n                                     face_quadrature_formula, \n                                     update_values | update_JxW_values); \n\n    const unsigned int dofs_per_cell   = fe.n_dofs_per_cell(); \n    const unsigned int n_face_q_points = face_quadrature_formula.size(); \n\n    FullMatrix<double> cell_matrix(dofs_per_cell, dofs_per_cell); \n    std::vector<types::global_dof_index> local_dof_indices(dofs_per_cell); \n\n    const FEValuesExtractors::Vector displacement(0); \n\n    for (const auto &cell : dof_handler.active_cell_iterators()) \n      if (cell->is_locally_owned()) \n        for (const auto &face : cell->face_iterators()) \n          if (face->at_boundary() && face->boundary_id() == 1) \n            { \n              fe_values_face.reinit(cell, face); \n              cell_matrix = 0; \n\n              for (unsigned int q_point = 0; q_point < n_face_q_points; \n                   ++q_point) \n                for (unsigned int i = 0; i < dofs_per_cell; ++i) \n                  cell_matrix(i, i) += \n                    (fe_values_face[displacement].value(i, q_point) * \n                     fe_values_face[displacement].value(i, q_point) * \n                     fe_values_face.JxW(q_point)); \n\n              cell->get_dof_indices(local_dof_indices); \n\n              for (unsigned int i = 0; i < dofs_per_cell; ++i) \n                mass_matrix.add(local_dof_indices[i], \n                                local_dof_indices[i], \n                                cell_matrix(i, i)); \n            } \n    mass_matrix.compress(VectorOperation::add); \n  } \n// @sect4{PlasticityContactProblem::update_solution_and_constraints}  \n\n// 下面的函数是我们在 <code>solve_newton()</code> 函数中每次牛顿迭代时调用的第一个函数。它的作用是将解决方案投射到可行集上，并更新接触或穿透障碍物的自由度的活动集。\n\n// 为了实现这个功能，我们首先需要做一些记账工作。我们需要写入解决方案向量（我们只能用没有鬼魂元素的完全分布的向量来做），我们需要从各自的向量中读取拉格朗日乘数和对角线质量矩阵的元素（我们只能用有鬼魂元素的向量来做），所以我们创建各自的向量。然后我们还要初始化约束对象，该对象将包含来自接触和所有其他来源的约束，以及一个包含所有属于接触的本地自由度的索引集的对象。\n\n  template <int dim> \n  void PlasticityContactProblem<dim>::update_solution_and_constraints() \n  { \n    std::vector<bool> dof_touched(dof_handler.n_dofs(), false); \n\n    TrilinosWrappers::MPI::Vector distributed_solution(locally_owned_dofs, \n                                                       mpi_communicator); \n    distributed_solution = solution; \n\n    TrilinosWrappers::MPI::Vector lambda(locally_relevant_dofs, \n                                         mpi_communicator); \n    lambda = newton_rhs_uncondensed; \n\n    TrilinosWrappers::MPI::Vector diag_mass_matrix_vector_relevant( \n      locally_relevant_dofs, mpi_communicator); \n    diag_mass_matrix_vector_relevant = diag_mass_matrix_vector; \n\n    all_constraints.reinit(locally_relevant_dofs); \n    active_set.clear(); \n\n// 第二部分是在所有单元格上的循环，在这个循环中，我们看每一个自由度被定义的点的活动集条件是否为真，我们需要把这个自由度加入到接触节点的活动集中。正如我们一直所做的，如果我们想在单个点上评估函数，我们用一个FEValues对象（或者，这里是FEFaceValues对象，因为我们需要检查表面的接触）和一个适当选择的正交对象来做。我们通过选择定义在单元格面上的形状函数的 \"支持点 \"来创建这个面的正交对象（关于支持点的更多信息，请参见这个 @ref GlossSupport \"词汇表条目\"）。因此，我们有多少个正交点，就有多少个面的形状函数，在正交点上循环就相当于在面的形状函数上循环。有了这个，代码看起来如下。\n\n    Quadrature<dim - 1> face_quadrature(fe.get_unit_face_support_points()); \n    FEFaceValues<dim>   fe_values_face(fe, \n                                     face_quadrature, \n                                     update_quadrature_points); \n\n    const unsigned int dofs_per_face   = fe.n_dofs_per_face(); \n    const unsigned int n_face_q_points = face_quadrature.size(); \n\n    std::vector<types::global_dof_index> dof_indices(dofs_per_face); \n\n    for (const auto &cell : dof_handler.active_cell_iterators()) \n      if (!cell->is_artificial()) \n        for (const auto &face : cell->face_iterators()) \n          if (face->at_boundary() && face->boundary_id() == 1) \n            { \n              fe_values_face.reinit(cell, face); \n              face->get_dof_indices(dof_indices); \n\n              for (unsigned int q_point = 0; q_point < n_face_q_points; \n                   ++q_point) \n                { \n\n// 在每个正交点（即位于接触边界上的自由度的每个支持点），我们再询问它是否是z-位移自由度的一部分，如果我们还没有遇到这个自由度（对于那些位于面之间的边缘的自由度可能发生），我们需要评估变形物体与障碍物之间的间隙。如果活动集条件为真，那么我们在AffineConstraints对象中添加一个约束，下一次牛顿更新需要满足这个约束，将求解向量的相应元素设置为正确的值，并将索引添加到IndexSet对象中，该索引存储哪个自由度是接触的一部分。\n\n                  const unsigned int component = \n                    fe.face_system_to_component_index(q_point).first; \n\n                  const unsigned int index_z = dof_indices[q_point]; \n\n                  if ((component == 2) && (dof_touched[index_z] == false)) \n                    { \n                      dof_touched[index_z] = true; \n\n                      const Point<dim> this_support_point = \n                        fe_values_face.quadrature_point(q_point); \n\n                      const double obstacle_value = \n                        obstacle->value(this_support_point, 2); \n                      const double solution_here = solution(index_z); \n                      const double undeformed_gap = \n                        obstacle_value - this_support_point(2); \n\n                      const double c = 100.0 * e_modulus; \n                      if ((lambda(index_z) / \n                               diag_mass_matrix_vector_relevant(index_z) + \n                             c * (solution_here - undeformed_gap) > \n                           0) && \n                          !constraints_hanging_nodes.is_constrained(index_z)) \n                        { \n                          all_constraints.add_line(index_z); \n                          all_constraints.set_inhomogeneity(index_z, \n                                                            undeformed_gap); \n                          distributed_solution(index_z) = undeformed_gap; \n\n                          active_set.add_index(index_z); \n                        } \n                    } \n                } \n            } \n\n// 在这个函数的最后，我们在处理器之间交换数据，更新 <code>solution</code> 变量中那些已经被其他处理器写入的幽灵元素。然后我们将Dirichlet约束和那些来自悬挂节点的约束合并到已经包含活动集的AffineConstraints对象中。我们通过输出主动约束自由度的总数来结束这个函数，对于这个自由度，我们对每个处理器拥有的主动约束自由度的数量进行加总。这个本地拥有的受限自由度的数量当然是活动集和本地拥有的自由度集的交集的元素数量，我们可以通过在两个IndexSets上使用 <code>operator&</code> 得到。\n\n    distributed_solution.compress(VectorOperation::insert); \n    solution = distributed_solution; \n\n    all_constraints.close(); \n    all_constraints.merge(constraints_dirichlet_and_hanging_nodes); \n\n \n          << Utilities::MPI::sum((active_set & locally_owned_dofs).n_elements(), \n                                 mpi_communicator) \n          << std::endl; \n  } \n// @sect4{PlasticityContactProblem::assemble_newton_system}  \n\n// 鉴于问题的复杂性，可能会让人感到惊讶的是，在每次牛顿迭代中组装我们要解决的线性系统实际上是相当简单的。下面的函数建立了牛顿的右手边和牛顿矩阵。它看起来相当简单，因为繁重的工作发生在对 <code>ConstitutiveLaw::get_linearized_stress_strain_tensors()</code> 的调用中，特别是在 AffineConstraints::distribute_local_to_global(), 中使用我们之前计算的约束。\n\n  template <int dim> \n  void PlasticityContactProblem<dim>::assemble_newton_system( \n    const TrilinosWrappers::MPI::Vector &linearization_point) \n  { \n    TimerOutput::Scope t(computing_timer, \"Assembling\"); \n\n    QGauss<dim>     quadrature_formula(fe.degree + 1); \n    QGauss<dim - 1> face_quadrature_formula(fe.degree + 1); \n\n    FEValues<dim> fe_values(fe, \n                            quadrature_formula, \n                            update_values | update_gradients | \n                              update_JxW_values); \n\n    FEFaceValues<dim> fe_values_face(fe, \n                                     face_quadrature_formula, \n                                     update_values | update_quadrature_points | \n                                       update_JxW_values); \n\n    const unsigned int dofs_per_cell   = fe.n_dofs_per_cell(); \n    const unsigned int n_q_points      = quadrature_formula.size(); \n    const unsigned int n_face_q_points = face_quadrature_formula.size(); \n\n    const EquationData::BoundaryForce<dim> boundary_force; \n    std::vector<Vector<double>> boundary_force_values(n_face_q_points, \n                                                      Vector<double>(dim)); \n\n    FullMatrix<double> cell_matrix(dofs_per_cell, dofs_per_cell); \n    Vector<double>     cell_rhs(dofs_per_cell); \n\n    std::vector<types::global_dof_index> local_dof_indices(dofs_per_cell); \n\n    const FEValuesExtractors::Vector displacement(0); \n\n    for (const auto &cell : dof_handler.active_cell_iterators()) \n      if (cell->is_locally_owned()) \n        { \n          fe_values.reinit(cell); \n          cell_matrix = 0; \n          cell_rhs    = 0; \n\n          std::vector<SymmetricTensor<2, dim>> strain_tensor(n_q_points); \n          fe_values[displacement].get_function_symmetric_gradients( \n            linearization_point, strain_tensor); \n\n          for (unsigned int q_point = 0; q_point < n_q_points; ++q_point) \n            { \n              SymmetricTensor<4, dim> stress_strain_tensor_linearized; \n              SymmetricTensor<4, dim> stress_strain_tensor; \n              constitutive_law.get_linearized_stress_strain_tensors( \n                strain_tensor[q_point], \n                stress_strain_tensor_linearized, \n                stress_strain_tensor); \n\n              for (unsigned int i = 0; i < dofs_per_cell; ++i) \n                { \n\n// 在计算了应力-应变张量及其线性化之后，我们现在可以把矩阵和右手边的部分放在一起。在这两部分中，我们需要线性化的应力-应变张量乘以 $\\varphi_i$ 的对称梯度，即 $I_\\Pi\\varepsilon(\\varphi_i)$ 项，因此我们引入这个项的缩写。回顾一下，该矩阵对应于随附出版物的符号中的双线性形式 $A_{ij}=(I_\\Pi\\varepsilon(\\varphi_i),\\varepsilon(\\varphi_j))$ ，而右手边是 $F_i=([I_\\Pi-P_\\Pi C]\\varepsilon(\\varphi_i),\\varepsilon(\\mathbf u))$ ，其中 $u$ 是当前的线性化点（通常是最后的解）。这可能表明，如果材料是完全弹性的（其中 $I_\\Pi=P_\\Pi$ ），右手边将为零，但这忽略了一个事实，即右手边还将包含由于接触而产生的非均质约束的贡献。                \n//接下来的代码块增加了由于边界力的贡献，如果有的话。\n\n                  const SymmetricTensor<2, dim> stress_phi_i = \n                    stress_strain_tensor_linearized * \n                    fe_values[displacement].symmetric_gradient(i, q_point); \n\n                  for (unsigned int j = 0; j < dofs_per_cell; ++j) \n                    cell_matrix(i, j) += \n                      (stress_phi_i * \n                       fe_values[displacement].symmetric_gradient(j, q_point) * \n                       fe_values.JxW(q_point)); \n\n                  cell_rhs(i) += \n                    ((stress_phi_i - \n                      stress_strain_tensor * \n                        fe_values[displacement].symmetric_gradient(i, \n                                                                   q_point)) * \n                     strain_tensor[q_point] * fe_values.JxW(q_point)); \n                } \n            } \n\n          for (const auto &face : cell->face_iterators()) \n            if (face->at_boundary() && face->boundary_id() == 1) \n              { \n                fe_values_face.reinit(cell, face); \n\n                boundary_force.vector_value_list( \n                  fe_values_face.get_quadrature_points(), \n                  boundary_force_values); \n\n                for (unsigned int q_point = 0; q_point < n_face_q_points; \n                     ++q_point) \n                  { \n                    Tensor<1, dim> rhs_values; \n                    rhs_values[2] = boundary_force_values[q_point][2]; \n                    for (unsigned int i = 0; i < dofs_per_cell; ++i) \n                      cell_rhs(i) += \n                        (fe_values_face[displacement].value(i, q_point) * \n                         rhs_values * fe_values_face.JxW(q_point)); \n                  } \n              } \n\n          cell->get_dof_indices(local_dof_indices); \n          all_constraints.distribute_local_to_global(cell_matrix, \n                                                     cell_rhs, \n                                                     local_dof_indices, \n                                                     newton_matrix, \n                                                     newton_rhs, \n                                                     true); \n        } \n\n    newton_matrix.compress(VectorOperation::add); \n    newton_rhs.compress(VectorOperation::add); \n  } \n\n//  @sect4{PlasticityContactProblem::compute_nonlinear_residual}  \n\n// 下面的函数计算给定当前解（或任何其他线性化点）的方程的非线性残差。这在线性搜索算法中是需要的，我们需要尝试之前和当前（试验）解的各种线性组合来计算当前牛顿步骤的（真实的、全局化的）解。\n\n// 说到这里，在稍微滥用函数名称的情况下，它实际上做了很多事情。例如，它还计算出与牛顿残差相对应的矢量，但没有消除受限自由度。我们需要这个向量来计算接触力，并最终计算出下一个活动集。同样，通过跟踪我们在每个单元上遇到的显示塑性屈服的正交点的数量，我们也可以计算出 <code>fraction_of_plastic_q_points_per_cell</code> 矢量，随后我们可以输出这个矢量来可视化塑性区。在这两种情况下，作为线条搜索的一部分，这些结果是不必要的，因此我们可能会浪费少量的时间来计算它们。同时，无论如何，这些信息是我们在这里需要做的事情的自然副产品，而且我们想在每个牛顿步骤结束时收集一次，所以我们不妨在这里做。\n\n// 这个函数的实际实现应该是相当明显的。\n\n  template <int dim> \n  void PlasticityContactProblem<dim>::compute_nonlinear_residual( \n    const TrilinosWrappers::MPI::Vector &linearization_point) \n  { \n    QGauss<dim>     quadrature_formula(fe.degree + 1); \n    QGauss<dim - 1> face_quadrature_formula(fe.degree + 1); \n\n    FEValues<dim> fe_values(fe, \n                            quadrature_formula, \n                            update_values | update_gradients | \n                              update_JxW_values); \n\n    FEFaceValues<dim> fe_values_face(fe, \n                                     face_quadrature_formula, \n                                     update_values | update_quadrature_points | \n                                       update_JxW_values); \n\n    const unsigned int dofs_per_cell   = fe.n_dofs_per_cell(); \n    const unsigned int n_q_points      = quadrature_formula.size(); \n    const unsigned int n_face_q_points = face_quadrature_formula.size(); \n\n    const EquationData::BoundaryForce<dim> boundary_force; \n    std::vector<Vector<double>> boundary_force_values(n_face_q_points, \n                                                      Vector<double>(dim)); \n\n    Vector<double> cell_rhs(dofs_per_cell); \n\n    std::vector<types::global_dof_index> local_dof_indices(dofs_per_cell); \n\n    const FEValuesExtractors::Vector displacement(0); \n\n    newton_rhs             = 0; \n    newton_rhs_uncondensed = 0; \n\n    fraction_of_plastic_q_points_per_cell = 0; \n\n    for (const auto &cell : dof_handler.active_cell_iterators()) \n      if (cell->is_locally_owned()) \n        { \n          fe_values.reinit(cell); \n          cell_rhs = 0; \n\n          std::vector<SymmetricTensor<2, dim>> strain_tensors(n_q_points); \n          fe_values[displacement].get_function_symmetric_gradients( \n            linearization_point, strain_tensors); \n\n          for (unsigned int q_point = 0; q_point < n_q_points; ++q_point) \n            { \n              SymmetricTensor<4, dim> stress_strain_tensor; \n              const bool              q_point_is_plastic = \n                constitutive_law.get_stress_strain_tensor( \n                  strain_tensors[q_point], stress_strain_tensor); \n              if (q_point_is_plastic) \n                ++fraction_of_plastic_q_points_per_cell( \n                  cell->active_cell_index()); \n\n              for (unsigned int i = 0; i < dofs_per_cell; ++i) \n                { \n                  cell_rhs(i) -= \n                    (strain_tensors[q_point] * stress_strain_tensor * \n                     fe_values[displacement].symmetric_gradient(i, q_point) * \n                     fe_values.JxW(q_point)); \n\n                  Tensor<1, dim> rhs_values; \n                  rhs_values = 0; \n                  cell_rhs(i) += (fe_values[displacement].value(i, q_point) * \n                                  rhs_values * fe_values.JxW(q_point)); \n                } \n            } \n\n          for (const auto &face : cell->face_iterators()) \n            if (face->at_boundary() && face->boundary_id() == 1) \n              { \n                fe_values_face.reinit(cell, face); \n\n                boundary_force.vector_value_list( \n                  fe_values_face.get_quadrature_points(), \n                  boundary_force_values); \n\n                for (unsigned int q_point = 0; q_point < n_face_q_points; \n                     ++q_point) \n                  { \n                    Tensor<1, dim> rhs_values; \n                    rhs_values[2] = boundary_force_values[q_point][2]; \n                    for (unsigned int i = 0; i < dofs_per_cell; ++i) \n                      cell_rhs(i) += \n                        (fe_values_face[displacement].value(i, q_point) * \n                         rhs_values * fe_values_face.JxW(q_point)); \n                  } \n              } \n\n          cell->get_dof_indices(local_dof_indices); \n          constraints_dirichlet_and_hanging_nodes.distribute_local_to_global( \n            cell_rhs, local_dof_indices, newton_rhs); \n\n          for (unsigned int i = 0; i < dofs_per_cell; ++i) \n            newton_rhs_uncondensed(local_dof_indices[i]) += cell_rhs(i); \n        } \n\n    fraction_of_plastic_q_points_per_cell /= quadrature_formula.size(); \n    newton_rhs.compress(VectorOperation::add); \n    newton_rhs_uncondensed.compress(VectorOperation::add); \n  } \n\n//  @sect4{PlasticityContactProblem::solve_newton_system}  \n\n// 在我们讨论单个网格上的实际牛顿迭代之前的最后一块是线性系统的求解器。有几个复杂的问题使代码略显模糊，但大多数情况下，它只是设置然后求解。在这些复杂的问题中，包括。\n\n\n\n// 对于悬空节点，我们必须将 AffineConstraints::set_zero 函数应用于newton_rhs。  如果一个求解值为 $x_0$ 的悬空节点有一个与障碍物接触的数值为 $x_1$ 的邻居和一个没有接触的邻居 $x_2$ ，这就有必要。因为前者的更新将是规定的，所以悬挂的节点约束将有一个不均匀性，看起来像  $x_0 = x_1/2 +   \\text{gap}/2$  。所以右侧的相应条目是无意义的非零值。这些值我们必须设置为零。\n\n// - 就像在  step-40  中一样，在求解或使用解决方案时，我们需要在有和没有鬼魂元素的向量之间进行洗牌。\n\n// 该函数的其余部分与 step-40 和 step-41 类似，只是我们使用BiCGStab求解器而不是CG。这是由于对于非常小的硬化参数 $\\gamma$ ，线性系统变得几乎是半无限的，尽管仍然是对称的。BiCGStab似乎更容易处理这种线性系统。\n\n  template <int dim> \n  void PlasticityContactProblem<dim>::solve_newton_system() \n  { \n    TimerOutput::Scope t(computing_timer, \"Solve\"); \n\n    TrilinosWrappers::MPI::Vector distributed_solution(locally_owned_dofs, \n                                                       mpi_communicator); \n    distributed_solution = solution; \n\n    constraints_hanging_nodes.set_zero(distributed_solution); \n    constraints_hanging_nodes.set_zero(newton_rhs); \n\n \n    { \n      TimerOutput::Scope t(computing_timer, \"Solve: setup preconditioner\"); \n\n      std::vector<std::vector<bool>> constant_modes; \n      DoFTools::extract_constant_modes(dof_handler, \n                                       ComponentMask(), \n                                       constant_modes); \n\n      TrilinosWrappers::PreconditionAMG::AdditionalData additional_data; \n      additional_data.constant_modes        = constant_modes; \n      additional_data.elliptic              = true; \n      additional_data.n_cycles              = 1; \n      additional_data.w_cycle               = false; \n      additional_data.output_details        = false; \n      additional_data.smoother_sweeps       = 2; \n      additional_data.aggregation_threshold = 1e-2; \n\n      preconditioner.initialize(newton_matrix, additional_data); \n    } \n\n    { \n      TimerOutput::Scope t(computing_timer, \"Solve: iterate\"); \n\n      TrilinosWrappers::MPI::Vector tmp(locally_owned_dofs, mpi_communicator); \n\n      const double relative_accuracy = 1e-8; \n      const double solver_tolerance = \n        relative_accuracy * \n        newton_matrix.residual(tmp, distributed_solution, newton_rhs); \n\n      SolverControl solver_control(newton_matrix.m(), solver_tolerance); \n      SolverBicgstab<TrilinosWrappers::MPI::Vector> solver(solver_control); \n      solver.solve(newton_matrix, \n                   distributed_solution, \n                   newton_rhs, \n                   preconditioner); \n\n      pcout << \"         Error: \" << solver_control.initial_value() << \" -> \" \n            << solver_control.last_value() << \" in \" \n            << solver_control.last_step() << \" Bicgstab iterations.\" \n            << std::endl; \n    } \n\n    all_constraints.distribute(distributed_solution); \n\n    solution = distributed_solution; \n  } \n// @sect4{PlasticityContactProblem::solve_newton}  \n\n// 最后，这是在当前网格上实现阻尼牛顿方法的函数。这里有两个嵌套的循环：外循环用于牛顿迭代，内循环用于直线搜索，只有在必要时才会使用。为了获得一个好的和合理的起始值，我们在每个网格上的第一个牛顿步骤中解决一个弹性问题（如果我们在网格之间转移解决方案，则只在第一个网格上解决）。我们通过在这些迭代中将屈服应力设置为一个不合理的大值，然后在随后的迭代中将其设置为正确值。\n\n// 除此以外，这个函数的顶部部分应该是相当明显的。我们将变量 <code>previous_residual_norm</code> 初始化为可以用双精度数字表示的最大负值，以便在第一步中比较当前残差是否小于前一步的残差时总是失败。\n\n  template <int dim> \n  void PlasticityContactProblem<dim>::solve_newton() \n  { \n    TrilinosWrappers::MPI::Vector old_solution(locally_owned_dofs, \n                                               mpi_communicator); \n    TrilinosWrappers::MPI::Vector residual(locally_owned_dofs, \n                                           mpi_communicator); \n    TrilinosWrappers::MPI::Vector tmp_vector(locally_owned_dofs, \n                                             mpi_communicator); \n    TrilinosWrappers::MPI::Vector locally_relevant_tmp_vector( \n      locally_relevant_dofs, mpi_communicator); \n    TrilinosWrappers::MPI::Vector distributed_solution(locally_owned_dofs, \n                                                       mpi_communicator); \n\n    double residual_norm; \n    double previous_residual_norm = -std::numeric_limits<double>::max(); \n\n    const double correct_sigma = sigma_0; \n\n    IndexSet old_active_set(active_set); \n\n    for (unsigned int newton_step = 1; newton_step <= 100; ++newton_step) \n      { \n        if (newton_step == 1 && \n            ((transfer_solution && current_refinement_cycle == 0) || \n             !transfer_solution)) \n          constitutive_law.set_sigma_0(1e+10); \n        else if (newton_step == 2 || current_refinement_cycle > 0 || \n                 !transfer_solution) \n          constitutive_law.set_sigma_0(correct_sigma); \n\n        pcout << \" \" << std::endl; \n        pcout << \"   Newton iteration \" << newton_step << std::endl; \n        pcout << \"      Updating active set...\" << std::endl; \n\n        { \n          TimerOutput::Scope t(computing_timer, \"update active set\"); \n          update_solution_and_constraints(); \n        } \n\n        pcout << \"      Assembling system... \" << std::endl; \n        newton_matrix = 0; \n        newton_rhs    = 0; \n        assemble_newton_system(solution); \n\n        pcout << \"      Solving system... \" << std::endl; \n        solve_newton_system(); \n\n// 在我们计算了当前牛顿步骤的试解 $\\tilde{\\mathbf u}$ 之后，情况就变得有点棘手了。我们处理的是一个高度非线性的问题，所以我们必须用直线搜索的方式来抑制牛顿方法。为了理解我们如何做到这一点，请回顾一下，在我们的表述中，我们在每一个牛顿步骤中计算一个试解，而不是在新旧解之间进行更新。由于解集是一个凸集，我们将使用直线搜索，尝试以前的解和试验解的线性组合，以保证阻尼解再次出现在我们的解集中。我们最多应用5个阻尼步骤。\n\n// 在我们使用直线搜索的时候有一些例外情况。首先，如果这是任何网格上的第一个牛顿步骤，那么我们就没有任何点来比较残差，所以我们总是接受一个完整的步骤。同样地，如果这是第一个网格上的第二个牛顿步骤（如果我们不在网格之间转移解决方案，则是任何网格上的第二个牛顿步骤），则我们只用弹性模型计算了其中的第一个步骤（见上文我们如何将屈服应力σ设置为一个不合理的大值）。在这种情况下，第一个牛顿解是一个纯粹的弹性解，第二个牛顿解是一个塑性解，任何线性组合都不一定会位于可行的集合中--所以我们只是接受我们刚刚得到的解。\n\n// 在这两种情况下，我们绕过直线搜索，只是在必要时更新残差和其他向量。\n\n        if ((newton_step == 1) || \n            (transfer_solution && newton_step == 2 && \n             current_refinement_cycle == 0) || \n            (!transfer_solution && newton_step == 2)) \n          { \n            compute_nonlinear_residual(solution); \n            old_solution = solution; \n\n            residual                     = newton_rhs; \n            const unsigned int start_res = (residual.local_range().first), \n                               end_res   = (residual.local_range().second); \n            for (unsigned int n = start_res; n < end_res; ++n) \n              if (all_constraints.is_inhomogeneously_constrained(n)) \n                residual(n) = 0; \n\n            residual.compress(VectorOperation::insert); \n\n            residual_norm = residual.l2_norm(); \n\n            pcout << \"      Accepting Newton solution with residual: \" \n                  << residual_norm << std::endl; \n          } \n        else \n          { \n            for (unsigned int i = 0; i < 5; ++i) \n              { \n                distributed_solution = solution; \n\n                const double alpha = std::pow(0.5, static_cast<double>(i)); \n                tmp_vector         = old_solution; \n                tmp_vector.sadd(1 - alpha, alpha, distributed_solution); \n\n                TimerOutput::Scope t(computing_timer, \"Residual and lambda\"); \n\n                locally_relevant_tmp_vector = tmp_vector; \n                compute_nonlinear_residual(locally_relevant_tmp_vector); \n                residual = newton_rhs; \n\n                const unsigned int start_res = (residual.local_range().first), \n                                   end_res   = (residual.local_range().second); \n                for (unsigned int n = start_res; n < end_res; ++n) \n                  if (all_constraints.is_inhomogeneously_constrained(n)) \n                    residual(n) = 0; \n\n                residual.compress(VectorOperation::insert); \n\n                residual_norm = residual.l2_norm(); \n\n \n                  << \"      Residual of the non-contact part of the system: \" \n                  << residual_norm << std::endl \n                  << \"         with a damping parameter alpha = \" << alpha \n                  << std::endl; \n\n                if (residual_norm < previous_residual_norm) \n                  break; \n              } \n\n            solution     = tmp_vector; \n            old_solution = solution; \n          } \n\n        previous_residual_norm = residual_norm; \n\n// 最后一步是检查收敛情况。如果活动集在所有处理器中都没有变化，并且残差小于阈值 $10^{-10}$  ，那么我们就终止对当前网格的迭代。\n\n        if (Utilities::MPI::sum((active_set == old_active_set) ? 0 : 1, \n                                mpi_communicator) == 0) \n          { \n            pcout << \"      Active set did not change!\" << std::endl; \n            if (residual_norm < 1e-10) \n              break; \n          } \n\n        old_active_set = active_set; \n      } \n  } \n// @sect4{PlasticityContactProblem::refine_grid}  \n\n// 如果你已经在deal.II教程中做到了这一点，下面这个细化网格的函数应该不会再对你构成任何挑战。它对网格进行细化，可以是全局的，也可以是使用Kelly误差估计器的，如果这样要求的话，还可以将上一个网格的解转移到下一个网格。在后一种情况下，我们还需要再次计算活动集和其他数量，为此我们需要由  <code>compute_nonlinear_residual()</code>  计算的信息。\n\n  template <int dim> \n  void PlasticityContactProblem<dim>::refine_grid() \n  { \n    if (refinement_strategy == RefinementStrategy::refine_global) \n      { \n        for (typename Triangulation<dim>::active_cell_iterator cell = \n               triangulation.begin_active(); \n             cell != triangulation.end(); \n             ++cell) \n          if (cell->is_locally_owned()) \n            cell->set_refine_flag(); \n      } \n    else \n      { \n        Vector<float> estimated_error_per_cell(triangulation.n_active_cells()); \n        KellyErrorEstimator<dim>::estimate( \n          dof_handler, \n          QGauss<dim - 1>(fe.degree + 2), \n          std::map<types::boundary_id, const Function<dim> *>(), \n          solution, \n          estimated_error_per_cell); \n\n        parallel::distributed::GridRefinement ::refine_and_coarsen_fixed_number( \n          triangulation, estimated_error_per_cell, 0.3, 0.03); \n      } \n\n    triangulation.prepare_coarsening_and_refinement(); \n\n    parallel::distributed::SolutionTransfer<dim, TrilinosWrappers::MPI::Vector> \n      solution_transfer(dof_handler); \n    if (transfer_solution) \n      solution_transfer.prepare_for_coarsening_and_refinement(solution); \n\n    triangulation.execute_coarsening_and_refinement(); \n\n    setup_system(); \n\n    if (transfer_solution) \n      { \n        TrilinosWrappers::MPI::Vector distributed_solution(locally_owned_dofs, \n                                                           mpi_communicator); \n        solution_transfer.interpolate(distributed_solution); \n\n// 强制执行约束条件，使插值后的解决方案在新的网格上符合要求。\n\n        constraints_hanging_nodes.distribute(distributed_solution); \n\n        solution = distributed_solution; \n        compute_nonlinear_residual(solution); \n      } \n  } \n// @sect4{PlasticityContactProblem::move_mesh}  \n\n// 在我们到达 <code>run()</code> 之前的其余三个函数都与生成输出有关。下面一个是尝试显示变形体的变形构造。为此，这个函数接收一个位移矢量场，通过先前计算的位移来移动网格（局部）的每个顶点。在生成图形输出之前，我们将以当前的位移场调用该函数，在生成图形输出之后，我们将以负的位移场再次调用该函数，以撤销对网格所做的修改。\n\n// 这个函数本身是非常简单的。我们所要做的就是跟踪我们已经接触过的顶点，因为我们在单元格上循环时多次遇到相同的顶点。\n\n  template <int dim> \n  void PlasticityContactProblem<dim>::move_mesh( \n    const TrilinosWrappers::MPI::Vector &displacement) const \n  { \n    std::vector<bool> vertex_touched(triangulation.n_vertices(), false); \n\n    for (const auto &cell : dof_handler.active_cell_iterators()) \n      if (cell->is_locally_owned()) \n        for (const auto v : cell->vertex_indices()) \n          if (vertex_touched[cell->vertex_index(v)] == false) \n            { \n              vertex_touched[cell->vertex_index(v)] = true; \n\n              Point<dim> vertex_displacement; \n              for (unsigned int d = 0; d < dim; ++d) \n                vertex_displacement[d] = \n                  displacement(cell->vertex_dof_index(v, d)); \n\n              cell->vertex(v) += vertex_displacement; \n            } \n  } \n\n//  @sect4{PlasticityContactProblem::output_results}  \n\n// 接下来是我们用来实际生成图形输出的函数。这个函数有点繁琐，但实际上并不特别复杂。它在顶部移动网格（最后再把它移回来），然后计算沿接触面的接触力。我们可以通过取未处理的残差向量，并通过询问它们是否有与之相关的不均匀约束来确定哪些自由度对应于有接触的自由度（如随文所示）。一如既往，我们需要注意的是，我们只能写进完全分布的向量（即没有鬼魂元素的向量），但当我们想产生输出时，我们需要的向量确实对所有局部相关的自由度都有鬼魂项。\n\n  template <int dim> \n  void PlasticityContactProblem<dim>::output_results( \n    const unsigned int current_refinement_cycle) \n  { \n    TimerOutput::Scope t(computing_timer, \"Graphical output\"); \n\n    pcout << \"      Writing graphical output... \" << std::flush; \n\n    move_mesh(solution); \n\n// 接触力的计算\n\n    TrilinosWrappers::MPI::Vector distributed_lambda(locally_owned_dofs, \n                                                     mpi_communicator); \n    const unsigned int start_res = (newton_rhs_uncondensed.local_range().first), \n                       end_res = (newton_rhs_uncondensed.local_range().second); \n    for (unsigned int n = start_res; n < end_res; ++n) \n      if (all_constraints.is_inhomogeneously_constrained(n)) \n        distributed_lambda(n) = \n          newton_rhs_uncondensed(n) / diag_mass_matrix_vector(n); \n    distributed_lambda.compress(VectorOperation::insert); \n    constraints_hanging_nodes.distribute(distributed_lambda); \n\n    TrilinosWrappers::MPI::Vector lambda(locally_relevant_dofs, \n                                         mpi_communicator); \n    lambda = distributed_lambda; \n\n    TrilinosWrappers::MPI::Vector distributed_active_set_vector( \n      locally_owned_dofs, mpi_communicator); \n    distributed_active_set_vector = 0.; \n    for (const auto index : active_set) \n      distributed_active_set_vector[index] = 1.; \n    distributed_lambda.compress(VectorOperation::insert); \n\n    TrilinosWrappers::MPI::Vector active_set_vector(locally_relevant_dofs, \n                                                    mpi_communicator); \n    active_set_vector = distributed_active_set_vector; \n\n    DataOut<dim> data_out; \n\n    data_out.attach_dof_handler(dof_handler); \n\n    const std::vector<DataComponentInterpretation::DataComponentInterpretation> \n      data_component_interpretation( \n        dim, DataComponentInterpretation::component_is_part_of_vector); \n    data_out.add_data_vector(solution, \n                             std::vector<std::string>(dim, \"displacement\"), \n                             DataOut<dim>::type_dof_data, \n                             data_component_interpretation); \n    data_out.add_data_vector(lambda, \n                             std::vector<std::string>(dim, \"contact_force\"), \n                             DataOut<dim>::type_dof_data, \n                             data_component_interpretation); \n    data_out.add_data_vector(active_set_vector, \n                             std::vector<std::string>(dim, \"active_set\"), \n                             DataOut<dim>::type_dof_data, \n                             data_component_interpretation); \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.add_data_vector(fraction_of_plastic_q_points_per_cell, \n                             \"fraction_of_plastic_q_points\"); \n\n    data_out.build_patches(); \n\n// 在函数的其余部分，我们在每个处理器上生成一个VTU文件，以这个处理器的子域ID为索引。在第一个处理器上，我们随后还创建了一个 <code>.pvtu</code> 文件，对VTU文件的<i>all</i>进行索引，这样就可以一次性读取整个输出文件集。这些 <code>.pvtu</code> 被Paraview用来描述整个并行计算的输出文件。然后我们再为Paraview的竞争者--VisIt可视化程序做同样的事情，创建一个匹配的 <code>.visit</code> 文件。\n\n    const std::string pvtu_filename = data_out.write_vtu_with_pvtu_record( \n      output_dir, \"solution\", current_refinement_cycle, mpi_communicator, 2); \n    pcout << pvtu_filename << std::endl; \n\n    TrilinosWrappers::MPI::Vector tmp(solution); \n    tmp *= -1; \n    move_mesh(tmp); \n  } \n// @sect4{PlasticityContactProblem::output_contact_force}  \n\n// 这最后一个辅助函数通过计算接触面积上Z方向的接触压力的积分来计算接触力。为此，我们将所有非活动因子的接触压力lambda设置为0（一个自由度是否是接触的一部分，就像我们在前一个函数中做的那样）。对于所有活动的自由度，lambda包含非线性残差（newton_rhs_uncondensed）和质量矩阵（diag_mass_matrix_vector）的相应对角线条目的商数。因为悬空节点出现在接触区的可能性不小，所以对分布式_lambda向量应用constraints_hanging_nodes.distribution是很重要的。\n\n  template <int dim> \n  void PlasticityContactProblem<dim>::output_contact_force() const \n  { \n    TrilinosWrappers::MPI::Vector distributed_lambda(locally_owned_dofs, \n                                                     mpi_communicator); \n    const unsigned int start_res = (newton_rhs_uncondensed.local_range().first), \n                       end_res = (newton_rhs_uncondensed.local_range().second); \n    for (unsigned int n = start_res; n < end_res; ++n) \n      if (all_constraints.is_inhomogeneously_constrained(n)) \n        distributed_lambda(n) = \n          newton_rhs_uncondensed(n) / diag_mass_matrix_vector(n); \n      else \n        distributed_lambda(n) = 0; \n    distributed_lambda.compress(VectorOperation::insert); \n    constraints_hanging_nodes.distribute(distributed_lambda); \n\n    TrilinosWrappers::MPI::Vector lambda(locally_relevant_dofs, \n                                         mpi_communicator); \n    lambda = distributed_lambda; \n\n    double contact_force = 0.0; \n\n    QGauss<dim - 1>   face_quadrature_formula(fe.degree + 1); \n    FEFaceValues<dim> fe_values_face(fe, \n                                     face_quadrature_formula, \n                                     update_values | update_JxW_values); \n\n    const unsigned int n_face_q_points = face_quadrature_formula.size(); \n\n    const FEValuesExtractors::Vector displacement(0); \n\n    for (const auto &cell : dof_handler.active_cell_iterators()) \n      if (cell->is_locally_owned()) \n        for (const auto &face : cell->face_iterators()) \n          if (face->at_boundary() && face->boundary_id() == 1) \n            { \n              fe_values_face.reinit(cell, face); \n\n              std::vector<Tensor<1, dim>> lambda_values(n_face_q_points); \n              fe_values_face[displacement].get_function_values(lambda, \n                                                               lambda_values); \n\n              for (unsigned int q_point = 0; q_point < n_face_q_points; \n                   ++q_point) \n                contact_force += \n                  lambda_values[q_point][2] * fe_values_face.JxW(q_point); \n            } \n    contact_force = Utilities::MPI::sum(contact_force, MPI_COMM_WORLD); \n\n    pcout << \"Contact force = \" << contact_force << std::endl; \n  } \n// @sect4{PlasticityContactProblem::run}  \n\n// 和其他所有的教程程序一样， <code>run()</code> 函数包含了整体逻辑。这里没有太多的内容：本质上，它在所有的网格细化循环中执行循环，并在每个循环中，将事情交给 <code>solve_newton()</code> 中的牛顿求解器，并调用函数来创建如此计算的解决方案的图形输出。然后输出一些关于运行时间和内存消耗的统计数据，这些数据是在这个网格的计算过程中收集的。\n\n  template <int dim> \n  void PlasticityContactProblem<dim>::run() \n  { \n    computing_timer.reset(); \n    for (; current_refinement_cycle < n_refinement_cycles; \n         ++current_refinement_cycle) \n      { \n        { \n          TimerOutput::Scope t(computing_timer, \"Setup\"); \n\n          pcout << std::endl; \n          pcout << \"Cycle \" << current_refinement_cycle << ':' << std::endl; \n\n          if (current_refinement_cycle == 0) \n            { \n              make_grid(); \n              setup_system(); \n            } \n          else \n            { \n              TimerOutput::Scope t(computing_timer, \"Setup: refine mesh\"); \n              refine_grid(); \n            } \n        } \n\n        solve_newton(); \n\n        output_results(current_refinement_cycle); \n\n        computing_timer.print_summary(); \n        computing_timer.reset(); \n\n        Utilities::System::MemoryStats stats; \n        Utilities::System::get_memory_stats(stats); \n        pcout << \"Peak virtual memory used, resident in kB: \" << stats.VmSize \n              << \" \" << stats.VmRSS << std::endl; \n\n        if (base_mesh == \"box\") \n          output_contact_force(); \n      } \n  } \n} // namespace Step42 \n// @sect3{The <code>main</code> function}  \n\n//  <code>main()</code> 函数真的没有什么内容。看起来他们总是这样做。\n\nint main(int argc, char *argv[]) \n{ \n  using namespace dealii; \n  using namespace Step42; \n\n  try \n    { \n      ParameterHandler prm; \n      PlasticityContactProblem<3>::declare_parameters(prm); \n      if (argc != 2) \n        { \n          std::cerr << \"*** Call this program as <./step-42 input.prm>\" \n                    << std::endl; \n          return 1; \n        } \n\n      prm.parse_input(argv[1]); \n      Utilities::MPI::MPI_InitFinalize mpi_initialization( \n        argc, argv, numbers::invalid_unsigned_int); \n      { \n        PlasticityContactProblem<3> problem(prm); \n        problem.run(); \n      } \n    } \n  catch (std::exception &exc) \n    { \n      std::cerr << std::endl \n                << std::endl \n                << \"----------------------------------------------------\" \n                << std::endl; \n      std::cerr << \"Exception on processing: \" << std::endl \n                << exc.what() << std::endl \n                << \"Aborting!\" << std::endl \n                << \"----------------------------------------------------\" \n                << std::endl; \n\n      return 1; \n    } \n  catch (...) \n    { \n      std::cerr << std::endl \n                << std::endl \n                << \"----------------------------------------------------\" \n                << std::endl; \n      std::cerr << \"Unknown exception!\" << std::endl \n                << \"Aborting!\" << std::endl \n                << \"----------------------------------------------------\" \n                << std::endl; \n      return 1; \n    } \n\n  return 0; \n} \n\n\n", "meta": {"hexsha": "67c580bcc83d1f1fd859bbdb6c7557d5e561b29b", "size": 71687, "ext": "cc", "lang": "C++", "max_stars_repo_path": "Translator_file/examples/step-42/step-42.cc", "max_stars_repo_name": "jiaqiwang969/deal.ii-course-practice", "max_stars_repo_head_hexsha": "0da5ad1537d8152549d8a0e4de5872efe7619c8a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Translator_file/examples/step-42/step-42.cc", "max_issues_repo_name": "jiaqiwang969/deal.ii-course-practice", "max_issues_repo_head_hexsha": "0da5ad1537d8152549d8a0e4de5872efe7619c8a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Translator_file/examples/step-42/step-42.cc", "max_forks_repo_name": "jiaqiwang969/deal.ii-course-practice", "max_forks_repo_head_hexsha": "0da5ad1537d8152549d8a0e4de5872efe7619c8a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.5405405405, "max_line_length": 418, "alphanum_fraction": 0.6168063945, "num_tokens": 23640, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6224593312018545, "lm_q2_score": 0.5350984286266115, "lm_q1q2_score": 0.3330770100100839}}
{"text": "#include \"Solver.hpp\"\n\n#include <spdlog/spdlog.h>\n#include <Eigen/IterativeLinearSolvers>\n#include <boost/range/irange.hpp>\n#ifdef NDEBUG\n#include <boost/preprocessor/stringize.hpp>\n#endif\n\n#include \"Attributes.hpp\"\n#include \"Derivatives.hpp\"\n#include \"MeshFacade.hpp\"\n#include \"internal/Format.hpp\"\t// For logging\n\n#ifdef NDEBUG\n#define FE_PARALLEL_PREAMBLE omp parallel for default(none)\n#define FE_PARALLEL(args) _Pragma(BOOST_PP_STRINGIZE(FE_PARALLEL_PREAMBLE args))\n#else\n#define FE_PARALLEL(args)\n#endif\n\nnamespace FeltElements::Solver\n{\nvoid Base::update_elements_stiffness_and_residual()\n{\n\tauto const num_cells = static_cast<int>(m_mesh.n_cells());\n\n\tFE_PARALLEL(shared(num_cells, m_attrs))\n\tfor (int cell_idx = 0; cell_idx < num_cells; cell_idx++)\n\t{\n\t\tCellh cellh{cell_idx};\n\t\tauto const & cell_vtxhs = m_attrs.vtxhs[cellh];\n\t\tauto const & boundary_faces_vtxh_idxs = m_attrs.boundary_faces_vtxh_idxs[cellh];\n\n\t\tauto const & [K, R] = Derivatives::KR(\n\t\t\tm_attrs.x.for_element(cell_vtxhs),\n\t\t\tboundary_faces_vtxh_idxs,\n\t\t\tm_attrs.x.for_elements(cell_vtxhs, boundary_faces_vtxh_idxs),\n\t\t\tm_attrs.dN_by_dX[cellh],\n\t\t\t*m_attrs.material,\n\t\t\t*m_attrs.forces);\n\t\tm_attrs.K[cellh] = K;\n\t\tm_attrs.R[cellh] = R;\n\t}\n}\n\nScalar Base::find_epsilon() const\n{\n\tScalar total_V = 0;\n\tScalar min_V = std::numeric_limits<Scalar>::max();\n\tScalar max_V = 0;\n\tElement::NodePositions min_X;\n\n\tfor (auto const & X : MeshIters{m_mesh, m_attrs}.Xs())\n\t{\n\t\tauto const V = Derivatives::V(X);\n\t\ttotal_V += V;\n\t\tif (V > max_V)\n\t\t\tmax_V = V;\n\t\tif (V < min_V)\n\t\t{\n\t\t\tmin_X = X;\n\t\t\tmin_V = V;\n\t\t}\n\t}\n\tScalar const avg_V = total_V / static_cast<Scalar>(m_mesh.n_cells());\n\t// Edge length assuming a regular tetrahedron, divided by a constant.\n\tScalar const epsilon = std::pow(6 * std::sqrt(2.0) * min_V, 1.0 / 3.0) * 1e-5;\n\tspdlog::info(\n\t\t\"total V = {}; mean V = {}; max V = {}, min V = {} @\\n{}\\nepsilon = {}\",\n\t\ttotal_V,\n\t\tavg_V,\n\t\tmax_V,\n\t\tmin_V,\n\t\tmin_X,\n\t\tepsilon);\n\treturn epsilon;\n}\n\nnamespace\n{\nvoid log_xs(Mesh const & mesh, Attributes const & attrs)\n{\n#if SPDLOG_ACTIVE_LEVEL <= SPDLOG_LEVEL_DEBUG\n\tstd::string xs_str;\n\tfor (auto const & x : MeshIters{mesh, attrs}.xs()) xs_str += fmt::format(\"{}\\n\", x);\n\n\tspdlog::debug(xs_str);\n#else\n\t(void)mesh;\n\t(void)attrs;\n#endif\n}\n}  // namespace\n\nvoid Matrix::solve()\n{\n\tScalar const epsilon = find_epsilon();\n\t//\tconstexpr Scalar penalty = std::numeric_limits<Scalar>::max() / 100;\n\n\tEigenFixedDOFs const & mat_fixed_dof = ([&attrs = m_attrs,\n\t\t\t\t\t\t\t\t\t\t\t rows = static_cast<Eigen::Index>(m_mesh.n_vertices()),\n\t\t\t\t\t\t\t\t\t\t\t cols = static_cast<Eigen::Index>(Node::dim)]() {\n\t\tEigenMapTensorVertices const & map{attrs.fixed_dof[Vtxh{0}].data(), rows, cols};\n\t\t// Copy to remove per-row alignment.\n\t\tEigenFixedDOFs vec = Eigen::Map<EigenFixedDOFs>{VerticesMatrix{map}.data(), rows * cols};\n\t\treturn vec;\n\t})();\n\n\tEigen::VectorXd mat_R{3 * m_mesh.n_vertices()};\n\tEigen::MatrixXd mat_K{3 * m_mesh.n_vertices(), 3 * m_mesh.n_vertices()};\n\tEigen::VectorXd mat_u{3 * m_mesh.n_vertices()};\n\n\tNode::Force const force_increment = m_attrs.forces->F_by_m / m_params.num_force_increments;\n\tm_attrs.forces->F_by_m = 0;\n\n\tScalar max_norm;\n\n\tfor (std::size_t increment_num = 0; increment_num < m_params.num_force_increments;\n\t\t increment_num++)\n\t{\n\t\tm_attrs.forces->F_by_m += force_increment;\n\t\tstats.force_increment_counter++;\n\n\t\tfor (std::size_t step = 0; step < m_params.num_steps; step++)\n\t\t{\n\t\t\tstats.step_counter++;\n\t\t\tSPDLOG_DEBUG(\"Matrix solver iteration {}:{}\", increment_num, step);\n\n\t\t\tupdate_elements_stiffness_and_residual();\n\n\t\t\tmat_R.setZero();\n\t\t\tmat_K.setZero();\n\n\t\t\tfor (auto vtxh : boost::make_iterator_range(m_mesh.vertices()))\n\t\t\t{\n\t\t\t\tauto const vtx_idx = vtxh.idx();\n\t\t\t\tfor (auto cellh : boost::make_iterator_range(m_mesh.vertex_cells(vtxh)))\n\t\t\t\t{\n\t\t\t\t\tauto const & cell_vtxhs = m_attrs.vtxhs[cellh];\n\t\t\t\t\tauto const & cell_vtx_idx = index_of<Eigen::Index>(cell_vtxhs, vtxh);\n\t\t\t\t\tauto const & cell_R = m_attrs.R[cellh];\n\n\t\t\t\t\t// Forces for node `a`.\n\t\t\t\t\tauto const & Ra =\n\t\t\t\t\t\tEigenConstTensorMap<4, 3>{cell_R.data()}.block<1, 3>(cell_vtx_idx, 0);\n\n\t\t\t\t\t// Update global residual with difference between internal and external forces.\n\t\t\t\t\tmat_R.block<3, 1>(3 * vtx_idx, 0) += Ra;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Compute sum to check equilibrium.\n\t\t\t//\t\tEigen::Vector3d sum; sum.setZero();\n\t\t\t//\t\tEigen::Map<Eigen::Matrix<Scalar, Eigen::Dynamic, 3, Eigen::RowMajor>>\n\t\t\t// mat_R_Nx3{mat_R.data(), mat_R.rows() / 3, 3}; \t\tfor (Eigen::Index const node_idx\n\t\t\t// : boost::irange(mat_R_Nx3.rows())) \t\t\tsum += mat_R_Nx3.row(node_idx);\n\n\t\t\tauto const update_submatrix =\n\t\t\t\t[&mat_K, &attrs = m_attrs](\n\t\t\t\t\tauto const vtxh_src, auto const vtxh_dst, auto const cellh_) {\n\t\t\t\t\tauto const & cell_K = attrs.K[cellh_];\n\t\t\t\t\tauto const & cell_vtxhs = attrs.vtxhs[cellh_];\n\t\t\t\t\tauto const cell_a = index_of(cell_vtxhs, vtxh_src);\n\t\t\t\t\tauto const cell_b = index_of(cell_vtxhs, vtxh_dst);\n\t\t\t\t\tauto const a = vtxh_src.idx();\n\t\t\t\t\tauto const b = vtxh_dst.idx();\n\n\t\t\t\t\tusing Tensor::Func::all;\n\t\t\t\t\tTensor::Matrix<3> const Kab = cell_K(cell_a, all, cell_b, all);\n\n\t\t\t\t\tmat_K.block<3, 3>(3 * a, 3 * b) += EigenConstTensorMap<3, 3>{Kab.data()};\n\t\t\t\t};\n\n\t\t\tfor (auto vtxh : boost::make_iterator_range(m_mesh.vertices()))\n\t\t\t{\n\t\t\t\tfor (auto cellh : boost::make_iterator_range(m_mesh.vertex_cells(vtxh)))\n\t\t\t\t\tupdate_submatrix(vtxh, vtxh, cellh);\n\t\t\t}\n\t\t\tfor (auto heh : boost::make_iterator_range(m_mesh.halfedges()))\n\t\t\t{\n\t\t\t\tauto const & halfedge = m_mesh.halfedge(heh);\n\t\t\t\tauto const & vtxh_src = halfedge.from_vertex();\n\t\t\t\tauto const & vtxh_dst = halfedge.to_vertex();\n\t\t\t\tfor (auto cellh : boost::make_iterator_range(m_mesh.halfedge_cells(heh)))\n\t\t\t\t\tupdate_submatrix(vtxh_src, vtxh_dst, cellh);\n\t\t\t}\n\t\t\t// Inspect matrix to calculate penalty of relative size.\n\t\t\tScalar const penalty = mat_K.lpNorm<Eigen::Infinity>() * 10000;\n\t\t\t// Zero-out penalised degrees of freedom.\n\t\t\tmat_K.diagonal() = mat_K.diagonal().cwiseProduct(\n\t\t\t\tEigen::VectorXd::Ones(mat_fixed_dof.size()) - mat_fixed_dof);\n\t\t\t// Set penalised degrees of freedom to penalty value.\n\t\t\tmat_K += penalty * mat_fixed_dof.asDiagonal();\n\n\t\t\t//\t\t\tSPDLOG_DEBUG(\"K (constrained)\\n{}\", mat_K);\n\t\t\t//\t\t\tauto const detK = mat_K.determinant();\n\t\t\t//\t\t\tif (std::abs(detK) < 0.00001)\n\t\t\t//\t\t\t\tthrow std::invalid_argument(\"Stiffness matrix |K| ~ 0\");\n\t\t\t//\t\tif (!std::isfinite(detK))\n\t\t\t//\t\t\tthrow std::invalid_argument{fmt::format(\n\t\t\t//\t\t\t\t\"Stiffness matrix |K| = {} with max = {}\", detK,\n\n\t\t\t// mat_K.lpNorm<Eigen::Infinity>())};\n\t\t\t//\t\tmat_u = mat_K.ldlt().solve(-mat_R);\n\t\t\t//\t\t\t\tEigen::ConjugateGradient< decltype(mat_K), Eigen::Lower|Eigen::Upper>\n\t\t\t// cg; cg.compute(mat_K); \t\t\t\tmat_u = cg.solve(-mat_R);\n\t\t\tmat_u = mat_K.partialPivLu().solve(-mat_R);\n\n\t\t\t//\t\t\tif (!mat_u.array().isFinite().all())\n\t\t\t//\t\t\t\tthrow std::logic_error(\n\t\t\t//\t\t\t\t\tfmt::format(\"Resulting displacement is not finite u = \\n{}.\",\n\t\t\t// mat_u));\n\n\t\t\tmat_u.array() *= (Eigen::VectorXd::Ones(mat_u.size()) - mat_fixed_dof).array();\n\t\t\t//\t\t\tSPDLOG_DEBUG(\"u (constrained)\\n{}\", mat_u);\n\n\t\t\tfor (auto const & vtxh : boost::make_iterator_range(m_mesh.vertices()))\n\t\t\t\tm_attrs.x[vtxh] += Tensor::Map<3>{mat_u.block<3, 1>(3 * vtxh.idx(), 0).data()};\n\n\t\t\tmax_norm = mat_u.lpNorm<Eigen::Infinity>();\n\t\t\tstats.max_norm = max_norm;\n\t\t\tlog_xs(m_mesh, m_attrs);\n\t\t\tif (max_norm < epsilon)\n\t\t\t\tbreak;\n\t\t}\n\t}\n}\n\nvoid Gauss::solve()\n{\n\tScalar const epsilon = find_epsilon() / 1000;\n\tusing Tensor::Func::all;\n\n\tstd::vector<Node::Pos> u(m_mesh.n_vertices(), {0, 0, 0});\n\tScalar max_norm = 0;\n\n\tNode::Force const force_increment = m_attrs.forces->F_by_m / m_params.num_force_increments;\n\tm_attrs.forces->F_by_m = 0;\n\n\tfor (std::size_t increment_num = 0; increment_num < m_params.num_force_increments;\n\t\t increment_num++)\n\t{\n\t\tm_attrs.forces->F_by_m += force_increment;\n\t\tstats.force_increment_counter++;\n\n\t\tfor (std::size_t step = 0; step < m_params.num_steps; step++)\n\t\t{\n\t\t\tstats.step_counter++;\n\t\t\tpauser.wait_while_paused();\n\n\t\t\tSPDLOG_DEBUG(\"Gauss iteration {}:{}\", increment_num, step);\n\n\t\t\tupdate_elements_stiffness_and_residual();\n\n\t\t\tmax_norm = 0;\n\t\t\tfor (auto & u_a : u) u_a *= 0.99;  //.zeros();\n\n\t\t\tFE_PARALLEL(shared(m_mesh, m_attrs, u, force_increment) reduction(max : max_norm))\n\t\t\tfor (Tensor::Index a = 0; a < m_mesh.n_vertices(); a++)\n\t\t\t{\n\t\t\t\tVtxh vtxh_src{static_cast<int>(a)};\n\t\t\t\tauto const & fixed_dof = m_attrs.fixed_dof[vtxh_src];\n\t\t\t\tif (Tensor::Func::all_of(fixed_dof != 0))\n\t\t\t\t\tcontinue;\n\n\t\t\t\tNode::Force Ra = 0;\n\t\t\t\tTensor::Matrix<3> Kaa = 0;\n\t\t\t\tNode::Force Ka_u = 0;\n\t\t\t\tfor (auto cellh : boost::make_iterator_range(m_mesh.vertex_cells(vtxh_src)))\n\t\t\t\t{\n\t\t\t\t\tauto const & cell_vtxhs = m_attrs.vtxhs[cellh];\n\t\t\t\t\tauto const & cell_a = index_of(cell_vtxhs, vtxh_src);\n\t\t\t\t\tauto const & cell_R = m_attrs.R[cellh];\n\t\t\t\t\tauto const & cell_K = m_attrs.K[cellh];\n\n\t\t\t\t\tRa += cell_R(cell_a, all);\n\t\t\t\t\tKaa += cell_K(cell_a, all, cell_a, all);\n\t\t\t\t}\n\t\t\t\t//\t\t\tdiag(Kaa) += penalty * fixed_dof;\n\n\t\t\t\tfor (auto heh : boost::make_iterator_range(m_mesh.outgoing_halfedges(vtxh_src)))\n\t\t\t\t{\n\t\t\t\t\tTensor::Multi<Node::dim, Node::dim> Kab = 0;\n\t\t\t\t\tauto const & halfedge = m_mesh.halfedge(heh);\n\t\t\t\t\tauto const & vtxh_dst = halfedge.to_vertex();\n\t\t\t\t\tauto const b = static_cast<Tensor::Index>(vtxh_dst.idx());\n\n\t\t\t\t\tfor (auto cellh : boost::make_iterator_range(m_mesh.halfedge_cells(heh)))\n\t\t\t\t\t{\n\t\t\t\t\t\tauto const & cell_K = m_attrs.K[cellh];\n\t\t\t\t\t\tauto const & cell_vtxhs = m_attrs.vtxhs[cellh];\n\t\t\t\t\t\tauto const cell_a = index_of(cell_vtxhs, vtxh_src);\n\t\t\t\t\t\tauto const cell_b = index_of(cell_vtxhs, vtxh_dst);\n\t\t\t\t\t\tKab += cell_K(cell_a, all, cell_b, all);\n\t\t\t\t\t}\n\t\t\t\t\tKa_u += Kab % u[b];\n\t\t\t\t}\n\n\t\t\t\tusing Tensor::Func::inv;\n\t\t\t\tu[a] = inv(Kaa) % (-Ra - Ka_u) * (1.0 - fixed_dof);\n\t\t\t\tm_attrs.x[vtxh_src] += u[a];\n\t\t\t\tusing Tensor::Func::abs;\n\t\t\t\tusing Tensor::Func::max;\n\t\t\t\t// Note: double-reduction in case OpenMP disabled.\n\t\t\t\tmax_norm = std::max(max_norm, max(abs(u[a])));\n\t\t\t\t//\t\t\t\tSPDLOG_DEBUG(\"R[{}] = {}\", a, Ra);\n\t\t\t\t//\t\t\t\tSPDLOG_DEBUG(\"u[{}] = {}\", a, u[a]);\n\t\t\t}\n\n\t\t\tSPDLOG_DEBUG(\"Max norm: {}\", max_norm);\n\t\t\tstats.max_norm = max_norm;\n\n\t\t\tlog_xs(m_mesh, m_attrs);\n\n\t\t\tif (max_norm < epsilon)\n\t\t\t\tbreak;\n\t\t}\n\t}\n}\n}  // namespace FeltElements::Solver\n", "meta": {"hexsha": "7307cca25043fc2e025cf925dd52764732ce04b0", "size": 10202, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/lib/FeltElements/Solver.cpp", "max_stars_repo_name": "feltech/FeltElements", "max_stars_repo_head_hexsha": "8f6374945e46a9c9a2a742482ffe6b923b8b5c25", "max_stars_repo_licenses": ["MIT"], "max_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/FeltElements/Solver.cpp", "max_issues_repo_name": "feltech/FeltElements", "max_issues_repo_head_hexsha": "8f6374945e46a9c9a2a742482ffe6b923b8b5c25", "max_issues_repo_licenses": ["MIT"], "max_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/FeltElements/Solver.cpp", "max_forks_repo_name": "feltech/FeltElements", "max_forks_repo_head_hexsha": "8f6374945e46a9c9a2a742482ffe6b923b8b5c25", "max_forks_repo_licenses": ["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.6832298137, "max_line_length": 92, "alphanum_fraction": 0.6605567536, "num_tokens": 3128, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5964331462646254, "lm_q2_score": 0.5583269943353745, "lm_q1q2_score": 0.33300472587591906}}
{"text": "// Copyright Nick Thompson, 2017\n// Use, modification and distribution are subject to the\n// Boost Software License, Version 1.0.\n// (See accompanying file LICENSE_1_0.txt\n// or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n/*\n * This class performs exp-sinh quadrature on half infinite intervals.\n *\n * References:\n *\n * 1) Tanaka, Ken'ichiro, et al. \"Function classes for double exponential integration formulas.\" Numerische Mathematik 111.4 (2009): 631-655.\n */\n\n#ifndef BOOST_MATH_QUADRATURE_EXP_SINH_HPP\n#define BOOST_MATH_QUADRATURE_EXP_SINH_HPP\n\n#include <cmath>\n#include <limits>\n#include <memory>\n#include <string>\n#include <boost/math/quadrature/detail/exp_sinh_detail.hpp>\n\nnamespace boost{ namespace math{ namespace quadrature {\n\ntemplate<class Real, class Policy = policies::policy<> >\nclass exp_sinh\n{\npublic:\n   exp_sinh(size_t max_refinements = 9)\n      : m_imp(std::make_shared<detail::exp_sinh_detail<Real, Policy>>(max_refinements)) {}\n\n    template<class F>\n    auto integrate(const F& f, Real a, Real b, Real tol = boost::math::tools::root_epsilon<Real>(), Real* error = nullptr, Real* L1 = nullptr, std::size_t* levels = nullptr)->decltype(std::declval<F>()(std::declval<Real>()))  const;\n    template<class F>\n    auto integrate(const F& f, Real tol = boost::math::tools::root_epsilon<Real>(), Real* error = nullptr, Real* L1 = nullptr, std::size_t* levels = nullptr)->decltype(std::declval<F>()(std::declval<Real>()))  const;\n\nprivate:\n    std::shared_ptr<detail::exp_sinh_detail<Real, Policy>> m_imp;\n};\n\ntemplate<class Real, class Policy>\ntemplate<class F>\nauto exp_sinh<Real, Policy>::integrate(const F& f, Real a, Real b, Real tolerance, Real* error, Real* L1, std::size_t* levels)->decltype(std::declval<F>()(std::declval<Real>()))  const\n{\n    typedef decltype(f(a)) K;\n    static_assert(!std::is_integral<K>::value,\n                  \"The return type cannot be integral, it must be either a real or complex floating point type.\");\n    using std::abs;\n    using boost::math::constants::half;\n    using boost::math::quadrature::detail::exp_sinh_detail;\n\n    static const char* function = \"boost::math::quadrature::exp_sinh<%1%>::integrate\";\n\n    // Neither limit may be a NaN:\n    if((boost::math::isnan)(a) || (boost::math::isnan)(b))\n    {\n       return static_cast<K>(policies::raise_domain_error(function, \"NaN supplied as one limit of integration - sorry I don't know what to do\", a, Policy()));\n     }\n    // Right limit is infinite:\n    if ((boost::math::isfinite)(a) && (b >= boost::math::tools::max_value<Real>()))\n    {\n        // If a = 0, don't use an additional level of indirection:\n        if (a == static_cast<Real>(0))\n        {\n            return m_imp->integrate(f, error, L1, function, tolerance, levels);\n        }\n        const auto u = [&](Real t)->K { return f(t + a); };\n        return m_imp->integrate(u, error, L1, function, tolerance, levels);\n    }\n\n    if ((boost::math::isfinite)(b) && a <= -boost::math::tools::max_value<Real>())\n    {\n        const auto u = [&](Real t)->K { return f(b-t);};\n        return m_imp->integrate(u, error, L1, function, tolerance, levels);\n    }\n\n    // Infinite limits:\n    if ((a <= -boost::math::tools::max_value<Real>()) && (b >= boost::math::tools::max_value<Real>()))\n    {\n        return static_cast<K>(policies::raise_domain_error(function, \"Use sinh_sinh quadrature for integration over the whole real line; exp_sinh is for half infinite integrals.\", a, Policy()));\n    }\n    // If we get to here then both ends must necessarily be finite:\n    return static_cast<K>(policies::raise_domain_error(function, \"Use tanh_sinh quadrature for integration over finite domains; exp_sinh is for half infinite integrals.\", a, Policy()));\n}\n\ntemplate<class Real, class Policy>\ntemplate<class F>\nauto exp_sinh<Real, Policy>::integrate(const F& f, Real tolerance, Real* error, Real* L1, std::size_t* levels)->decltype(std::declval<F>()(std::declval<Real>())) const\n{\n    static const char* function = \"boost::math::quadrature::exp_sinh<%1%>::integrate\";\n    using std::abs;\n    if (abs(tolerance) > 1) {\n        std::string msg = std::string(__FILE__) + \":\" + std::to_string(__LINE__) + \":\" + std::string(function) + \": The tolerance provided is unusually large; did you confuse it with a domain bound?\";\n        throw std::domain_error(msg);\n    }\n    return m_imp->integrate(f, error, L1, function, tolerance, levels);\n}\n\n\n}}}\n#endif\n", "meta": {"hexsha": "736acbd11a2d9f60e295a0627dd56cdd7602d72e", "size": 4421, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "AqooleEngine/src/main/cpp/boost/boost/math/quadrature/exp_sinh.hpp", "max_stars_repo_name": "kodai731/Aqoole-Engine-Android-Vulkan-Rendering-Engine-", "max_stars_repo_head_hexsha": "72c8f34b6b6d507319069e681ff8c5008337b7c6", "max_stars_repo_licenses": ["Apache-2.0", "MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "AqooleEngine/src/main/cpp/boost/boost/math/quadrature/exp_sinh.hpp", "max_issues_repo_name": "kodai731/Aqoole-Engine-Android-Vulkan-Rendering-Engine-", "max_issues_repo_head_hexsha": "72c8f34b6b6d507319069e681ff8c5008337b7c6", "max_issues_repo_licenses": ["Apache-2.0", "MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "AqooleEngine/src/main/cpp/boost/boost/math/quadrature/exp_sinh.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": 42.9223300971, "max_line_length": 232, "alphanum_fraction": 0.6724722913, "num_tokens": 1174, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.640635868562172, "lm_q2_score": 0.519521321952093, "lm_q1q2_score": 0.3328239933253469}}
{"text": "/*\n * seqgen.cpp\n *\n *  Created on: Jun 23, 2015\n *      Author: joe\n */\n\n#include <iostream>\n#include <string>\n#include <vector>\n#include <nlopt.hpp>\n#include <armadillo>\n#include <random>\n#include <numeric>\n\nusing namespace std;\n//using namespace arma;\nusing arma::randn;\nusing arma::mat;\nusing arma::expmat;\n\n#include \"seq_gen.h\"\n#include \"utils.h\"\n#include \"node.h\"\n#include \"tree.h\"\n#include \"tree_reader.h\"\n#include \"tree_utils.h\"\n\n// TODO: do we want this order?\n/*Default Rate Matrix looks like this, I don't know why but I always go A,T,C,G\n *\n *    A   T   C   G\n * A -1  .33 .33 .33\n * T .33 -1  .33 .33\n * G .33 .33  -1 .33\n * G .33 .33 .33  -1\n */\n\n\n// this should enable easy changing of order, if desired\n\nmap <char, int> SequenceGenerator::nuc_map_ = {\n   {'A', 0},\n   {'C', 1},\n   {'G', 2},\n   {'T', 3}\n};\n\nstring SequenceGenerator::nucleotides_ = \"ACGT\";\nstring SequenceGenerator::amino_acids_ = \"ARNDCQEGHILKMFPSTWYV\";\n\nmap <char, int> SequenceGenerator::aa_map_ = {\n\n   {'A', 0},\n   {'R', 1},\n   {'N', 2},\n   {'D', 3},\n   {'C', 4},\n   {'Q', 5},\n   {'E', 6},\n   {'G', 7},\n   {'H', 8},\n   {'I', 9},\n   {'L', 10},\n   {'K', 11},\n   {'M', 12},\n   {'F', 13},\n   {'P', 14},\n   {'S', 15},\n   {'T', 16},\n   {'W', 17},\n   {'Y', 18},\n   {'V', 19}\n};\n\n/*\nmap <char, int> SequenceGenerator::nucMap = {\n   {'A', 0},\n   {'T', 1},\n   {'C', 2},\n   {'G', 3}\n};\nstring SequenceGenerator::nucleotides = \"ATCG\";\n*/\n \nSequenceGenerator::SequenceGenerator (int const &seqlength, vector <double> const& basefreq,\n    vector < vector<double> >& rmatrix, Tree * tree, bool const& showancs, \n    int const& nreps, int const& seed, float const& alpha, float const& pinvar, \n    string const& ancseq, bool const& printpost, vector<double> const& multirates,\n    vector <double> const& aabasefreq, bool const& is_dna):tree_(tree),\n    seqlen_(seqlength), nreps_(nreps), seed_(seed), alpha_(alpha), pinvar_(pinvar),\n    root_sequence_(ancseq), base_freqs_(basefreq), aa_freqs_(aabasefreq), rmatrix_(rmatrix), \n    multi_rates_(multirates), show_ancs_(showancs), print_node_labels_(printpost),\n    multi_model_(false), is_dna_(is_dna)  {\n    /*\n     for (unsigned int i = 0; i < rmatrix.size(); i++) {\n        for (unsigned int j = 0; j < rmatrix.size(); j++) {\n            cout << rmatrix[i][j] << \" \";\n        }\n        cout << \"\\n\";\n    }*/\n    initialize();\n    if (is_dna_) {\n        nstates_ = 4;\n    } else {\n        nstates_ = 20;\n    }\n    // Print out the nodes names\n    if (print_node_labels_) {\n        label_internal_nodes();\n        print_node_labels();\n        exit(0);\n    }\n    preorder_tree_traversal();\n}\n\n\n// set all values\nvoid SequenceGenerator::initialize () {\n    // set the number generator being used\n    if (seed_ != -1) { // user provided seed\n        generator_ = mt19937(seed_);\n    } else {\n        generator_ = mt19937(get_clock_seed());\n    }\n    \n    // construct uniform distribution from which random numbers will be generated\n    // this happens to be the default distribution, but good to be explicit\n    uniformDistrib_ = uniform_real_distribution<float>(0.0, 1.0);\n    \n    // construct gamma distribution (if necessary)\n    if (alpha_ != -1.0) {\n        gammaDistrib_ = gamma_distribution<float>(alpha_, (1/alpha_));\n    }\n    \n    if (show_ancs_) {\n        label_internal_nodes();\n    }\n    if (root_sequence_.length() == 0) {\n        root_sequence_ = generate_random_sequence();\n    } else {\n        check_valid_sequence();\n        // if root sequence is provided, set length to this\n        seqlen_ = root_sequence_.size();\n    }\n    // set site-specific rate (pinvar and gamma)\n    site_rates_ = set_site_rates();\n    \n    if (multi_rates_.size() != 0) {\n        multi_model_ = true;\n    }\n}\n\n\n/* Use the P matrix probabilities and randomly draw numbers to see\n * if each individual state will undergo some type of change\n */\nstring SequenceGenerator::simulate_sequence (string const& anc, \n    vector < vector <double> >& QMatrix, float const& brlength) {\n    std::vector<double>::iterator low;\n    vector < vector <double> > PMatrix(nstates_, vector <double>(nstates_, 0.0));\n    //int ancChar = 0;\n    string newstring = anc; // instead of building, set size and replace\n    for (int i = 0; i < seqlen_; i++) {\n        float RandNumb = get_uniform_random_deviate();\n        int ancChar = 0;\n        if (is_dna_) {\n            ancChar = nuc_map_[anc[i]];\n        } else {\n            ancChar = aa_map_[anc[i]];\n            //cout << ancChar << endl;\n        }\n        float brnew = brlength * site_rates_[i];\n        PMatrix = calculate_p_matrix(QMatrix, brnew);\n        for (int i = 0; i < nstates_; i++) {\n            // this calculates a cumulative sum\n            std::partial_sum(PMatrix[i].begin(), PMatrix[i].end(), PMatrix[i].begin(), plus<double>());\n        }\n        low = std::lower_bound (PMatrix[ancChar].begin(), PMatrix[ancChar].end(), RandNumb);\n        \n        if (is_dna_) {\n            newstring[i] = nucleotides_[low - PMatrix[ancChar].begin()];\n        } else {\n            newstring[i] = amino_acids_[low - PMatrix[ancChar].begin()];    \n        }\n    }\n    //cout << newstring << endl;\n    return newstring;\n}\n\n\n/*\n * Calculate the Q Matrix (Substitution rate matrix)\n */\nvector < vector <double> > SequenceGenerator::calculate_q_matrix () {\n\n    vector < vector <double> > bigpi(nstates_, vector <double>(nstates_, 1.0));\n    vector < vector <double> > t(nstates_, vector <double>(nstates_, 0.0));\n    \n    double tscale = 0.0;\n    \n    // doing the same looping multiple times here. simplify?\n    for (unsigned int i = 0; i < rmatrix_.size(); i++) {\n        for (unsigned int j = 0; j < rmatrix_.size(); j++) {\n            if (i != j) {\n                if (is_dna_) {\n                    bigpi[i][j] *= base_freqs_[i] * base_freqs_[j] * rmatrix_[i][j];\n                } else {\n                    bigpi[i][j] *= aa_freqs_[i] * aa_freqs_[j] * rmatrix_[i][j];    \n                }\n                tscale += bigpi[i][j];\n            } else {\n                bigpi[i][j] = 0.0;\n            }\n        }\n    }\n    for (unsigned int i = 0; i < rmatrix_.size(); i++) {\n        for (unsigned int j = 0; j < rmatrix_.size(); j++) {\n            if (i != j) {\n                bigpi[i][j] /= tscale;\n            } else {\n                // set the diagnols to zero *** are they not set to zero above?\n                bigpi[i][j] = 0.0;\n            }\n        }\n    }\n    for (unsigned int i = 0; i < rmatrix_.size(); i++) {\n        double diag = 0.0;\n        for (unsigned int j = 0; j < rmatrix_.size(); j++) {\n            if (i != j) {\n                diag -= bigpi[i][j];\n            }\n        }\n        bigpi[i][i] = diag;\n    }\n    //Divide and Transpose\n    for (unsigned int i = 0; i < rmatrix_.size(); i++) {\n        for (unsigned int j = 0; j < rmatrix_.size(); j++) {\n            if (is_dna_) {\n                bigpi[i][j] /= base_freqs_[i];\n            } else {\n                bigpi[i][j] /= aa_freqs_[i];\n            }\n        }\n    }\n    return bigpi;\n}\n\n\n/* Calculate the P Matrix (Probability Matrix)\n * Changes to armadillos format then back I don't like the way could be more\n * efficient but yeah...\n */\nvector < vector <double> > SequenceGenerator::calculate_p_matrix (vector < vector <double> > const& QMatrix,\n    float br) {\n\n    vector < vector <double> > Pmatrix(nstates_, vector <double>(nstates_, 0.0));\n    mat A = randn<mat>(nstates_, nstates_);\n    mat B = randn<mat>(nstates_, nstates_); // why not just copy A?\n    int count = 0;\n    //Q * t moved into Matrix form for armadillo\n    for (unsigned int i = 0; i < QMatrix.size(); i++) {\n        for (unsigned int j = 0; j < QMatrix.size(); j++) {\n            A[count] = (QMatrix[i][j] * br);\n            count++;\n        }\n    }\n   //exponentiate the matrix\n   B = expmat(A);\n   //cout << B << endl;\n   count = 0;\n   //convert the matrix back to C++ vector\n   for (unsigned int i = 0; i < Pmatrix.size(); i++) {\n        for (unsigned int j = 0; j < Pmatrix.size(); j++) {\n            Pmatrix[i][j] = B[count];\n            count++;\n        }\n   }\n   return Pmatrix;\n}\n\n\n/*\n * Pre-Order traversal works\n * Calculates the JC Matrix\n */\n// TODO: how to name ancestor nodes (sequences)\n//       - if we have this we can add to results (if desired))\nvoid SequenceGenerator::preorder_tree_traversal () {\n\n    double brlength = 0.0;\n    int rate_count = 0;\n    int check = 0;\n    vector < vector <double> > QMatrix(nstates_, vector <double>(nstates_, 0.0));\n    //vector < vector <double> > PMatrix(4, vector <double>(4, 0.0));\n    // NOTE: this uses order: A,T,C,G\n    if (multi_model_) {        \n        rmatrix_[0][2] = multi_rates_[0]; // A->C\n        rmatrix_[2][0] = multi_rates_[0]; // C->A\n        rmatrix_[0][3] = multi_rates_[1]; // A->G\n        rmatrix_[3][0] = multi_rates_[1]; // G->A\n        rmatrix_[0][1] = multi_rates_[2]; // A->T\n        rmatrix_[1][0] = multi_rates_[2]; // T->A\n        rmatrix_[2][3] = multi_rates_[3]; // C->G\n        rmatrix_[3][2] = multi_rates_[3]; // G->C\n        rmatrix_[1][2] = multi_rates_[4]; // C->T\n        rmatrix_[2][1] = multi_rates_[4]; // T->C\n        rmatrix_[1][3] = multi_rates_[5]; // G->T\n        rmatrix_[3][1] = multi_rates_[5]; // T->G\n        rmatrix_[0][0] = (multi_rates_[0]+multi_rates_[1]+multi_rates_[2]) * -1;\n        rmatrix_[1][1] = (multi_rates_[2]+multi_rates_[4]+multi_rates_[5]) * -1;\n        rmatrix_[2][2] = (multi_rates_[0]+multi_rates_[3]+multi_rates_[4]) * -1;\n        rmatrix_[3][3] = (multi_rates_[1]+multi_rates_[3]+multi_rates_[5]) * -1;\n        for (unsigned int i = 0; i < 6; i++) {\n            multi_rates_.erase (multi_rates_.begin() + 0); \n        }\n        //QMatrix = calcQmatrix(rate_matrix);\n        //QMatrix = calculate_q_matrix();\n    }\n    QMatrix = calculate_q_matrix();\n    Node * root = tree_->getRoot();\n    seqs_[root] = root_sequence_;\n    ancq_[root] = QMatrix;\n    \n    if (show_ancs_) {\n        string tname = root->getName();\n        Sequence seq(tname, root_sequence_);\n        res.push_back(seq);\n    }\n    \n    // Pre-Order Traverse the tree\n    for (int k = (tree_->getNodeCount() - 2); k >= 0; k--) {\n        brlength = tree_->getNode(k)->getBL();\n        /*\n        for (unsigned int i = 0; i < QMatrix.size(); i++) {\n            for (unsigned int j = 0; j < QMatrix.size(); j++) {\n                cout << QMatrix[i][j] << \" \";\n            }\n            cout << \"\\n\";\n        }\n        cout << \"\\n\";\n        */\n        if (multi_model_) {\n            check = (int)round(multi_rates_[0]);\n            //cout << check << \" \" << rate_count << endl;\n            if (tree_->getNode(k)->isInternal() == true && multi_rates_.size() != 0) {\n                if (check == rate_count) {\n                    rmatrix_[0][2] = multi_rates_[1];\n                    rmatrix_[2][0] = multi_rates_[1];\n                    rmatrix_[0][3] = multi_rates_[2];\n                    rmatrix_[3][0] = multi_rates_[2];\n                    rmatrix_[0][1] = multi_rates_[3];\n                    rmatrix_[1][0] = multi_rates_[3];\n                    rmatrix_[2][3] = multi_rates_[4];\n                    rmatrix_[3][2] = multi_rates_[4];\n                    rmatrix_[1][2] = multi_rates_[5];\n                    rmatrix_[2][1] = multi_rates_[5];\n                    rmatrix_[1][3] = multi_rates_[6];\n                    rmatrix_[3][1] = multi_rates_[6];\n                    rmatrix_[0][0] = (multi_rates_[1]+multi_rates_[2]+multi_rates_[3]) * -1;\n                    rmatrix_[1][1] = (multi_rates_[3]+multi_rates_[5]+multi_rates_[6]) * -1;\n                    rmatrix_[2][2] = (multi_rates_[1]+multi_rates_[4]+multi_rates_[5]) * -1;\n                    rmatrix_[3][3] = (multi_rates_[2]+multi_rates_[4]+multi_rates_[6]) * -1;\n\n                    for (unsigned int i = 0; i < 7; i++) {\n                        multi_rates_.erase(multi_rates_.begin() + 0);\n                    }\n                    //cout << \"Size \" << multi_rates_.size() << endl;\n                    //cout << multi_rates_[0] << endl;\n                    /*\n                    for (unsigned int i = 0; i < multi_rates_.size(); i++) {\n                        cout << multi_rates_[i] << endl;\n                    }*/        \n                }\n                rate_count++;\n            }\n        }\n        QMatrix = calculate_q_matrix();\n        //PMatrix = calculate_p_matrix(QMatrix, brlength);\n        Node * dec = tree_->getNode(k);\n        Node * parent = tree_->getNode(k)->getParent();\n        //ancq[dec] = QMatrix;\n        vector < vector <double> > Qparent = ancq_[parent];\n        string ancSeq = seqs_[parent];\n        string decSeq = simulate_sequence(ancSeq, Qparent, brlength);\n        /*\n        for (unsigned int i = 0; i < Qparent.size(); i++) {\n            for (unsigned int j = 0; j < Qparent.size(); j++) {\n                cout << Qparent[i][j] << \" \";\n            }\n            cout << \"\\n\";\n        }\n        cout << \"\\n\";*/\n        \n        seqs_[dec] = decSeq;\n        ancq_[dec] = QMatrix; // why store this?\n        if (show_ancs_ && tree_->getNode(k)->isInternal() == true) {\n            string tname = tree_->getNode(k)->getName();\n            Sequence seq(tname, decSeq);\n            res.push_back(seq);\n        }\n        // If its a tip print the name and the sequence\n        if (tree_->getNode(k)->isInternal() != true) {\n            string tname = tree_->getNode(k)->getName();\n            Sequence seq(tname, decSeq);\n            res.push_back(seq);\n        }\n    }\n}\n\n\n// this should probably be returned on its own\nvoid SequenceGenerator::print_node_labels() {\n    cout << getNewickString(tree_) << endl;\n    //cout << tree_->getRoot()->getNewick(true) <<\";\" << endl;\n}\n\n\nvoid SequenceGenerator::label_internal_nodes() {\n\n    int count = 1;\n    string str = \"Node\";\n    string nlabel = \"\";\n    Node * root = tree_->getRoot();\n    root->setName(\"Node_0\");\n    for (int k = (tree_->getNodeCount() - 2); k >= 0; k--) {\n        if (tree_->getNode(k)->isInternal() == true) {\n            //cout << k << endl;\n            str = to_string(count);\n            nlabel = \"Node_\" + str;\n            tree_->getNode(k)->setName(nlabel);\n            count++;\n        }\n    }\n}\n\n\n// involves both gamma and pinvar\nvector <float> SequenceGenerator::set_site_rates () {\n    vector <float> srates(seqlen_, 1.0);\n    \n    // invariable sites\n    if (pinvar_ != 0.0) {\n        int numsample = seqlen_ * pinvar_ + 0.5;\n        // sample invariable sites\n        vector <int> randsites = sample_without_replacement(seqlen_, numsample);\n        // must be a more elegant way of doing this\n        for (int i = 0; i < numsample; i++) {\n            srates[randsites[i]] = 0.0;\n        }\n    }\n    \n    // gamma-distributed rate variation. could explore other distributions...\n    if (alpha_ != -1.0) { // default i.e. no rate variation\n        for (int i = 0; i < seqlen_; i++) {\n            // want to skip over sites that are set to invariable\n            if (srates[i] != 0.0) {\n                srates[i] = get_gamma_random_deviate(alpha_);\n            }\n        }\n    }\n    return srates;\n} \n\n\n// initialized as string of length seqlength, all 'G'\nstring SequenceGenerator::generate_random_sequence () {\n    \n    string ancseq(seqlen_, 'G');\n    if (is_dna_) {\n        //string ancseq(seqlen, 'G');\n        vector <double> cumsum(4);\n        std::vector <double>::iterator low;\n        // cumulative sum\n        std::partial_sum(base_freqs_.begin(), base_freqs_.end(), cumsum.begin(), plus<double>());\n    \n        for (int i = 0; i < seqlen_; i++) {\n            float RandNumb = get_uniform_random_deviate();\n            low = std::lower_bound (cumsum.begin(), cumsum.end(), RandNumb);\n            ancseq[i] = nucleotides_[low - cumsum.begin()];\n        }\n    } else {\n        //string ancseq(seqlen, 'G');\n        vector <double> cumsum(20);\n        std::vector <double>::iterator low;\n        // cumulative sum\n        std::partial_sum(aa_freqs_.begin(), aa_freqs_.end(), cumsum.begin(), plus<double>());\n    \n        for (int i = 0; i < seqlen_; i++) {\n            float RandNumb = get_uniform_random_deviate();\n            low = std::lower_bound (cumsum.begin(), cumsum.end(), RandNumb);\n            ancseq[i] = amino_acids_[low - cumsum.begin()];\n        }    \n    }\n    //cout << ancseq << endl;\n    return ancseq;\n}\n\n\n// rates are in order: A<->C,A<->G,A<->T,C<->G,C<->T,G<->T\nvector < vector <double> > SequenceGenerator::construct_rate_matrix (vector <double> const& rates) {\n    \n    // initialize\n    vector < vector <double> > ratemat(nstates_, vector<double>(4, 0.33));\n    \n    // planning ahead here for potential non-reversible matrices\n    if (rates.size() == 6) {\n        ratemat[0][1] = rates[0];\n        ratemat[1][0] = rates[0];\n        ratemat[0][2] = rates[1];\n        ratemat[2][0] = rates[1];\n        ratemat[0][3] = rates[2];\n        ratemat[3][0] = rates[2];\n        ratemat[1][2] = rates[3];\n        ratemat[2][1] = rates[3];\n        ratemat[1][3] = rates[4];\n        ratemat[3][1] = rates[4];\n        ratemat[2][3] = rates[5];\n        ratemat[3][2] = rates[5];\n        \n        ratemat[0][0] = (rates[0] + rates[1] + rates[2]) * -1;\n        ratemat[1][1] = (rates[0] + rates[3] + rates[4]) * -1;\n        ratemat[2][2] = (rates[1] + rates[3] + rates[5]) * -1;\n        ratemat[3][3] = (rates[2] + rates[4] + rates[5]) * -1;\n        \n    } else {\n        cout << \"Er, we don't deal with \" << rates.size() << \" rates at the moment...\" << endl;\n        exit(0);\n    }\n    return ratemat;\n}\n\n\n// make sure sequence contains only valid nucleotide characters\nvoid SequenceGenerator::check_valid_sequence () {\n    // make sure uppercase\n    root_sequence_ = string_to_upper(root_sequence_);\n    if (is_dna_) {\n        std::size_t found = root_sequence_.find_first_not_of(nucleotides_);\n        if (found != std::string::npos) {\n            cout << \"Error: illegal character '\" << root_sequence_[found] << \"' at position \" \n                << found+1 << \" (only A,C,G,T allowed). Maybe specify AA with -c? Exiting.\" << endl;\n            exit(0);\n        }\n    } else {\n        std::size_t found = root_sequence_.find_first_not_of(amino_acids_);\n        if (found != std::string::npos) {\n            cout << \"Error: illegal character '\" << root_sequence_[found] << \"' at position \" \n                << found+1 << \" (only AA chars allowed). Exiting.\" << endl;\n            exit(0);\n        }        \n        \n    }\n}\n\n\n// not sure of a more elegant way to do this...\nvector<Sequence> SequenceGenerator::get_sequences () {\n    return res;\n}\n\n\n// call this whenever a random float is needed\nfloat SequenceGenerator::get_uniform_random_deviate () {\n    return uniformDistrib_(generator_);\n}\n\n\nfloat SequenceGenerator::get_gamma_random_deviate (float alpha) {\n    return gammaDistrib_(generator_);\n}\n\n//SEQGEN::~SEQGEN() {\n//    // TODO Auto-generated destructor stub\n//}\n", "meta": {"hexsha": "15b041c7647c2829c0815954e77e5fb6ed9d00af", "size": 18873, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/phyx-1.01/src/seq_gen.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/seq_gen.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/seq_gen.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": 32.765625, "max_line_length": 108, "alphanum_fraction": 0.5358448577, "num_tokens": 5363, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6406358548398982, "lm_q2_score": 0.519521321952093, "lm_q1q2_score": 0.332823986196333}}
{"text": "/*\n Copyright (C) 2016 Quaternion Risk Management Ltd\n All rights reserved.\n\n This file is part of ORE, a free-software/open-source library\n for transparent pricing and risk analysis - http://opensourcerisk.org\n\n ORE is free software: you can redistribute it and/or modify it\n under the terms of the Modified BSD License.  You should have received a\n copy of the license along with this program.\n The license is also available online at <http://opensourcerisk.org>\n\n This program is distributed on the basis that it will form a useful\n contribution to risk analytics and model standardisation, but WITHOUT\n ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n FITNESS FOR A PARTICULAR PURPOSE. See the license for more details.\n*/\n\n#include <qle/math/flatextrapolation.hpp>\n#include <qle/termstructures/datedstrippedoptionletadapter.hpp>\n\n#include <ql/math/interpolations/linearinterpolation.hpp>\n#include <ql/termstructures/volatility/interpolatedsmilesection.hpp>\n\n#include <algorithm>\n#include <boost/make_shared.hpp>\n\nusing std::max;\nusing std::min;\n\nnamespace QuantExt {\n\nDatedStrippedOptionletAdapter::DatedStrippedOptionletAdapter(const boost::shared_ptr<DatedStrippedOptionletBase>& s,\n                                                             const bool flatExtrapolation)\n    : OptionletVolatilityStructure(s->referenceDate(), s->calendar(), s->businessDayConvention(), s->dayCounter()),\n      optionletStripper_(s), nInterpolations_(s->optionletMaturities()), strikeInterpolations_(nInterpolations_),\n      flatExtrapolation_(flatExtrapolation) {\n    registerWith(optionletStripper_);\n}\n\nboost::shared_ptr<SmileSection> DatedStrippedOptionletAdapter::smileSectionImpl(Time t) const {\n    \n    // Arbitrarily choose the first row of strikes for the smile section independent variable\n    // Generally a reasonable choice since:\n    // 1) OptionletStripper1: all strike rows are the same\n    // 2) OptionletStripper2: optionletStrikes(i) is a decreasing sequence\n    // Still possibility of arbitrary externally provided strike rows where (0) does not include all\n    vector<Rate> optionletStrikes = optionletStripper_->optionletStrikes(0);\n    vector<Real> stdDevs(optionletStrikes.size());\n    Real tEff = flatExtrapolation_ ? std::min(t, optionletStripper_->optionletFixingTimes().back()) : t;\n    for (Size i = 0; i < optionletStrikes.size(); ++i) {\n        stdDevs[i] = volatilityImpl(tEff, optionletStrikes[i]) * sqrt(tEff);\n    }\n\n    // Use a linear interpolated smile section.\n    // TODO: possibly make this configurable?\n    if (flatExtrapolation_)\n        return boost::make_shared<InterpolatedSmileSection<LinearFlat> >(t, optionletStrikes, stdDevs, Null<Real>(),\n                                                                         LinearFlat(), Actual365Fixed(),\n                                                                         volatilityType(), displacement());\n    else\n        return boost::make_shared<InterpolatedSmileSection<Linear> >(\n            t, optionletStrikes, stdDevs, Null<Real>(), Linear(), Actual365Fixed(), volatilityType(), displacement());\n}\n\nVolatility DatedStrippedOptionletAdapter::volatilityImpl(Time length, Rate strike) const {\n    calculate();\n\n    vector<Volatility> vol(nInterpolations_);\n    for (Size i = 0; i < nInterpolations_; ++i)\n        vol[i] = strikeInterpolations_[i]->operator()(strike, true);\n\n    const vector<Time>& optionletTimes = optionletStripper_->optionletFixingTimes();\n    boost::shared_ptr<LinearInterpolation> timeInterpolator =\n        boost::make_shared<LinearInterpolation>(optionletTimes.begin(), optionletTimes.end(), vol.begin());\n    Real lengthEff = flatExtrapolation_ ? std::max(std::min(length, optionletStripper_->optionletFixingTimes().back()),\n                                                   optionletStripper_->optionletFixingTimes().front())\n                                        : length;\n    return timeInterpolator->operator()(lengthEff, true);\n}\n\nvoid DatedStrippedOptionletAdapter::performCalculations() const {\n    for (Size i = 0; i < nInterpolations_; ++i) {\n        const vector<Rate>& optionletStrikes = optionletStripper_->optionletStrikes(i);\n        const vector<Volatility>& optionletVolatilities = optionletStripper_->optionletVolatilities(i);\n        boost::shared_ptr<Interpolation> tmp = boost::make_shared<LinearInterpolation>(\n            optionletStrikes.begin(), optionletStrikes.end(), optionletVolatilities.begin());\n        if (flatExtrapolation_)\n            strikeInterpolations_[i] = boost::make_shared<FlatExtrapolation>(tmp);\n        else\n            strikeInterpolations_[i] = tmp;\n    }\n}\n\nRate DatedStrippedOptionletAdapter::minStrike() const {\n    Rate minStrike = optionletStripper_->optionletStrikes(0).front();\n    for (Size i = 1; i < nInterpolations_; ++i) {\n        minStrike = min(optionletStripper_->optionletStrikes(i).front(), minStrike);\n    }\n    return minStrike;\n}\n\nRate DatedStrippedOptionletAdapter::maxStrike() const {\n    Rate maxStrike = optionletStripper_->optionletStrikes(0).back();\n    for (Size i = 1; i < nInterpolations_; ++i) {\n        maxStrike = max(optionletStripper_->optionletStrikes(i).back(), maxStrike);\n    }\n    return maxStrike;\n}\n\nDate DatedStrippedOptionletAdapter::maxDate() const { return optionletStripper_->optionletFixingDates().back(); }\n\nVolatilityType DatedStrippedOptionletAdapter::volatilityType() const { return optionletStripper_->volatilityType(); }\n\nReal DatedStrippedOptionletAdapter::displacement() const { return optionletStripper_->displacement(); }\n} // namespace QuantExt\n", "meta": {"hexsha": "334cc5d81d25ee2b6e633fed528b16a710b98071", "size": 5598, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "QuantExt/qle/termstructures/datedstrippedoptionletadapter.cpp", "max_stars_repo_name": "PiotrSiejda/Engine", "max_stars_repo_head_hexsha": "8360b5de32408f2a37da5ac3ca7b4e913bf67e9f", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "QuantExt/qle/termstructures/datedstrippedoptionletadapter.cpp", "max_issues_repo_name": "PiotrSiejda/Engine", "max_issues_repo_head_hexsha": "8360b5de32408f2a37da5ac3ca7b4e913bf67e9f", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "QuantExt/qle/termstructures/datedstrippedoptionletadapter.cpp", "max_forks_repo_name": "PiotrSiejda/Engine", "max_forks_repo_head_hexsha": "8360b5de32408f2a37da5ac3ca7b4e913bf67e9f", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-02-07T02:04:10.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-07T02:04:10.000Z", "avg_line_length": 47.8461538462, "max_line_length": 119, "alphanum_fraction": 0.7081100393, "num_tokens": 1325, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6926419831347361, "lm_q2_score": 0.480478678047907, "lm_q1q2_score": 0.3327997044170587}}
{"text": "/**\n * @file\n * This file is part of SeisSol.\n *\n * @author Carsten Uphoff (c.uphoff AT tum.de, http://www5.in.tum.de/wiki/index.php/Carsten_Uphoff,_M.Sc.)\n * @author Sebastian Wolf (wolf.sebastian AT in.tum.de, https://www5.in.tum.de/wiki/index.php/Sebastian_Wolf,_M.Sc.)\n *\n * @section LICENSE\n * Copyright (c) 2015 - 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#ifndef MODEL_COMMON_HPP_\n#define MODEL_COMMON_HPP_\n\n#include <Eigen/Eigen>\n\n#include \"utils/logger.h\"\n#include \"Initializer/typedefs.hpp\"\n#include \"generated_code/init.h\"\n#include \"Geometry/MeshTools.h\"\n#include \"Numerical_aux/Transformation.h\"\n\n#include \"Model/common_datastructures.hpp\"\n\n\nnamespace seissol {\n  namespace model {\n    using Matrix99 = Eigen::Matrix<double, 9, 9>;\n\n    bool testIfAcoustic(real mu);\n\n    template<typename Tmaterial, typename Tmatrix>\n    void getTransposedCoefficientMatrix( Tmaterial const& i_material,\n                                         unsigned         i_dim,\n                                         Tmatrix&         o_M )\n    { o_M.setZero(); }\n    \n    template<typename Tmaterial, typename T>\n    void getTransposedSourceCoefficientTensor(  Tmaterial const& material,\n                                                T& E);\n\n    template<typename Tmaterial, typename Tloc, typename Tneigh>\n    void getTransposedGodunovState( Tmaterial const&  local,\n                                    Tmaterial const&  neighbor,\n                                    FaceType          faceType,\n                                    Tloc&             QgodLocal,\n                                    Tneigh&           QgodNeighbor );\n\n    template<typename T>\n    void getTransposedFreeSurfaceGodunovState( bool isAcoustic,\n                                               T& QgodLocal,\n                                               T& QgodNeighbor,\n                                               Eigen::Matrix<double, 9, 9>& R);\n\n    template<typename T>\n    void getPlaneWaveOperator( T const& material,\n                               double const n[3],\n                               std::complex<double> Mdata[NUMBER_OF_QUANTITIES*NUMBER_OF_QUANTITIES] );\n\n    template<typename T, typename S>\n    void initializeSpecificLocalData( T const&,\n                                      S* LocalData ) {}\n\n    template<typename T, typename S>\n    void initializeSpecificNeighborData(  T const&,\n                                          S* NeighborData ) {}\n\n    /* \n     * Calculates the so called Bond matrix. Anisotropic materials are characterized by \n     * 21 different material parameters. Due to the directional dependence of anisotropic\n     * materials the parameters are not independet of the choice of the coordinate system.\n     * The Bond matrix transforms materials from one orthogonal coordinate system to\n     * another one.\n     * c.f. 10.1111/j.1365-246X.2007.03381.x\n     */\n    void getBondMatrix( VrtxCoords const i_normal,\n                        VrtxCoords const i_tangent1,\n                        VrtxCoords const i_tangent2,\n                        real* o_N );\n\n    void getFaceRotationMatrix( VrtxCoords const i_normal,\n                                VrtxCoords const i_tangent1,\n                                VrtxCoords const i_tangent2,\n                                init::T::view::type& o_T,\n                                init::Tinv::view::type& o_Tinv );\n  }\n}\n\n\n\n\ntemplate<typename T>\nvoid seissol::model::getPlaneWaveOperator(  T const& material,\n                                            double const n[3],\n                                            std::complex<double> Mdata[NUMBER_OF_QUANTITIES*NUMBER_OF_QUANTITIES] )\n{\n  yateto::DenseTensorView<2,std::complex<double>> M(Mdata, {NUMBER_OF_QUANTITIES, NUMBER_OF_QUANTITIES});\n  M.setZero();\n\n  double data[NUMBER_OF_QUANTITIES * NUMBER_OF_QUANTITIES];\n  yateto::DenseTensorView<2,double> Coeff(data, {NUMBER_OF_QUANTITIES, NUMBER_OF_QUANTITIES});\n\n  for (unsigned d = 0; d < 3; ++d) {\n    Coeff.setZero();\n    getTransposedCoefficientMatrix(material, d, Coeff);\n    \n    for (unsigned i = 0; i < NUMBER_OF_QUANTITIES; ++i) {\n      for (unsigned j = 0; j < NUMBER_OF_QUANTITIES; ++j) {\n        M(i,j) += n[d] * Coeff(j,i);\n      }\n    }\n  }\n}\n\ntemplate<typename T>\nvoid seissol::model::getTransposedFreeSurfaceGodunovState( bool      isAcoustic,\n                                                           T&        QgodLocal,\n                                                           T&        QgodNeighbor,\n                                                           Eigen::Matrix<double, 9, 9>& R)\n{\n  for (int i = 0; i < 9; i++) {\n    for (int j = 0; j < 9; j++) {\n      QgodNeighbor(i,j) = std::numeric_limits<double>::signaling_NaN();\n    }\n  }\n\n  QgodLocal.setZero();\n  if (isAcoustic) {\n    // Acoustic material only has one traction (=pressure) and one velocity comp.\n    // relevant to the Riemann problem\n    QgodLocal(0, 6) = -1 * R(6,0) * 1/R(0,0); // S\n    QgodLocal(6, 6) = 1.0;\n  } else {\n    std::array<int, 3> traction_indices = {0,3,5};\n    std::array<int, 3> velocity_indices = {6,7,8};\n    using Matrix33 = Eigen::Matrix<double, 3, 3>;\n    Matrix33 R11 = R(traction_indices, {0,1,2});\n    Matrix33 R21 = R(velocity_indices, {0,1,2});\n    Matrix33 S = (-(R21 * R11.inverse())).eval();\n\n    //set lower left block\n    int row = 0;\n    for (auto &t: traction_indices) {\n      int col = 0;\n      for (auto &v: velocity_indices) {\n        QgodLocal(t, v) = S(row, col);\n        col++;\n      }\n      row++;\n    }\n\n    //set lower right block\n    for (auto &v : velocity_indices) {\n      QgodLocal(v, v) = 1.0;\n    }\n  }\n}\n  \n#endif\n", "meta": {"hexsha": "645b5b4b39a8d994a23f22d44ceb5a112f5c35ed", "size": 7187, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/Model/common.hpp", "max_stars_repo_name": "VMPW/SeisSol", "max_stars_repo_head_hexsha": "641e6a2d1e49173142f85688fbf8e40828f0c37a", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Model/common.hpp", "max_issues_repo_name": "VMPW/SeisSol", "max_issues_repo_head_hexsha": "641e6a2d1e49173142f85688fbf8e40828f0c37a", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Model/common.hpp", "max_forks_repo_name": "VMPW/SeisSol", "max_forks_repo_head_hexsha": "641e6a2d1e49173142f85688fbf8e40828f0c37a", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-09-09T14:02:59.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-09T14:02:59.000Z", "avg_line_length": 38.0264550265, "max_line_length": 116, "alphanum_fraction": 0.5994156115, "num_tokens": 1686, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6001883735630721, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.3327867265533592}}
{"text": "#include \"hoCuNDArray_utils.h\"\n#include \"radial_utilities.h\"\n#include \"hoNDArray_fileio.h\"\n#include \"cuNDArray.h\"\n#include \"imageOperator.h\"\n#include \"identityOperator.h\"\n#include \"hoPartialDerivativeOperator.h\"\n#include \"cuConebeamProjectionOperator.h\"\n#include \"hoCuConebeamProjectionOperator.h\"\n#include \"cuConvolutionOperator.h\"\n#include \"hoCuNDArray_blas.h\"\n#include \"hoCuNDArray_elemwise.h\"\n#include \"hoCuNDArray_blas.h\"\n#include \"cgSolver.h\"\n#include \"CBCT_acquisition.h\"\n#include \"complext.h\"\n#include \"encodingOperatorContainer.h\"\n#include \"vector_td_io.h\"\n#include \"hoPartialDerivativeOperator.h\"\n#include \"hoCuGPBBSolver.h\"\n#include \"cuTvOperator.h\"\n#include \"cuTvPicsOperator.h\"\n#include \"cuNCGSolver.h\"\n#include \"hoCuCgDescentSolver.h\"\n#include \"hoNDArray_utils.h\"\n#include \"hoCuPartialDerivativeOperator.h\"\n#include \"cuDCTOperator.h\"\n#include \"cuNDArray_fileio.h\"\n#include \"cuATrousOperator.h\"\n#include \"hdf5_utils.h\"\n#include <iostream>\n#include <algorithm>\n#include <sstream>\n#include <math_constants.h>\n#include <boost/program_options.hpp>\n#include <cuTv1dOperator.h>\n#include \"dicomWriter.h\"\n//#include \"cuDWTOperator.h\"\n#include \"cuATvOperator.h\"\n\nusing namespace std;\nusing namespace Gadgetron;\n\nnamespace po = boost::program_options;\n\nboost::shared_ptr<cuNDArray<float> > calculate_prior(boost::shared_ptr<CBCT_binning>  binning,boost::shared_ptr<CBCT_acquisition> ps, hoCuNDArray<float>& projections, std::vector<size_t> is_dims, floatd3 imageDimensions){\n\tstd::cout << \"Calculating FDK prior\" << std::endl;\n\tboost::shared_ptr<CBCT_binning> binning_pics=binning->get_3d_binning();\n\tstd::vector<size_t> is_dims3d = is_dims;\n\tis_dims3d.pop_back();\n\tboost::shared_ptr< hoCuConebeamProjectionOperator >\n\tEp( new hoCuConebeamProjectionOperator() );\n\tEp->setup(ps,binning_pics,imageDimensions);\n\tEp->set_codomain_dimensions(ps->get_projections()->get_dimensions().get());\n\tEp->set_domain_dimensions(&is_dims3d);\n\tEp->set_use_filtered_backprojection(true);\n\tboost::shared_ptr<hoCuNDArray<float> > prior3d(new hoCuNDArray<float>(&is_dims3d));\n\tEp->mult_MH(&projections,prior3d.get());\n\n\thoCuNDArray<float> tmp_proj(*ps->get_projections());\n\tEp->mult_M(prior3d.get(),&tmp_proj);\n\tfloat s = dot(ps->get_projections().get(),&tmp_proj)/dot(&tmp_proj,&tmp_proj);\n\t*prior3d *= s;\n\tboost::shared_ptr<cuNDArray<float> > prior(new cuNDArray<float>(*expand( prior3d.get(), is_dims.back() )));\n\tstd::cout << \"Prior complete\" << std::endl;\n\treturn prior;\n}\n\n\nint main(int argc, char** argv)\n{\n\tstring acquisition_filename;\n\tstring outputFile;\n\tuintd3 imageSize;\n\tfloatd3 voxelSize;\n\tint device;\n\tunsigned int downsamples;\n\tunsigned int iterations;\n\tfloat rho,dct_weight;\n\tpo::options_description desc(\"Allowed options\");\n\n\tdesc.add_options()\n    \t\t(\"help\", \"produce help message\")\n    \t\t(\"acquisition,a\", po::value<string>(&acquisition_filename)->default_value(\"acquisition.hdf5\"), \"Acquisition data\")\n    \t\t(\"samples,n\",po::value<unsigned int>(),\"Number of samples per ray\")\n    \t\t(\"output,f\", po::value<string>(&outputFile)->default_value(\"reconstruction.hdf5\"), \"Output filename\")\n    \t\t(\"size,s\",po::value<uintd3>(&imageSize)->default_value(uintd3(512,512,1)),\"Image size in pixels\")\n    \t\t(\"binning,b\",po::value<string>(),\"Binning file for 4d reconstruction\")\n    \t\t(\"SAG\",\"Use exact SAG correction if present\")\n    \t\t(\"voxelSize,v\",po::value<floatd3>(&voxelSize)->default_value(floatd3(0.488f,0.488f,1.0f)),\"Voxel size in mm\")\n    \t\t(\"dimensions,d\",po::value<floatd3>(),\"Image dimensions in mm. Overwrites voxelSize.\")\n    \t\t(\"iterations,i\",po::value<unsigned int>(&iterations)->default_value(10),\"Number of iterations\")\n    \t\t(\"TV,T\",po::value<float>(),\"TV Weight \")\n\t\t\t\t\t(\"ATV\",po::value<float>(),\"TV Weight \")\n\t\t\t\t\t(\"TV4D\",po::value<float>(),\"Total variation weight in temporal dimensions\")\n    \t\t(\"PICS\",po::value<float>(),\"TV Weight of the prior image (Prior image compressed sensing)\")\n    \t\t(\"device\",po::value<int>(&device)->default_value(0),\"Number of the device to use (0 indexed)\")\n    \t\t(\"downsample,D\",po::value<unsigned int>(&downsamples)->default_value(0),\"Downsample projections this factor\")\n    \t\t(\"rho\",po::value<float>(&rho)->default_value(0.5f),\"Rho-value for line search. Must be between 0 and 1. Smaller value means faster runtime, but less stable algorithm.\")\n    \t\t(\"DCT\",po::value<float>(&dct_weight)->default_value(0),\"DCT regularization\")\n    \t\t(\"use_prior\",\"Use an FDK prior\")\n    \t\t(\"Wavelet,W\",po::value<float>(),\"Wavelet weight\")\n    \t\t(\"3D\",\"Only use binning for selecting valid projections\")\n    \t\t;\n\n\tpo::variables_map vm;\n\tpo::store(po::parse_command_line(argc, argv, desc), vm);\n\tpo::notify(vm);\n\n\tif (vm.count(\"help\")) {\n\t\tcout << desc << \"\\n\";\n\t\treturn 1;\n\t}\n\n\tstd::stringstream command_line_string;\n\tstd::cout << \"Command line options:\" << std::endl;\n\tfor (po::variables_map::iterator it = vm.begin(); it != vm.end(); ++it){\n\t\tboost::any a = it->second.value();\n\t\tcommand_line_string << it->first << \": \";\n\t\tif (a.type() == typeid(std::string)) command_line_string << it->second.as<std::string>();\n\t\telse if (a.type() == typeid(int)) command_line_string << it->second.as<int>();\n\t\telse if (a.type() == typeid(unsigned int)) command_line_string << it->second.as<unsigned int>();\n\t\telse if (a.type() == typeid(float)) command_line_string << it->second.as<float>();\n\t\telse if (a.type() == typeid(vector_td<float,3>)) command_line_string << it->second.as<vector_td<float,3> >();\n\t\telse if (a.type() == typeid(vector_td<int,3>)) command_line_string << it->second.as<vector_td<int,3> >();\n\t\telse if (a.type() == typeid(vector_td<unsigned int,3>)) command_line_string << it->second.as<vector_td<unsigned int,3> >();\n\t\telse command_line_string << \"Unknown type\" << std::endl;\n\t\tcommand_line_string << std::endl;\n\t}\n\n\tstd::cout << command_line_string.str();\n\n\tcudaSetDevice(device);\n\tcudaDeviceReset();\n\n\t//Really weird stuff. Needed to initialize the device?? Should find real bug.\n\tcudaDeviceManager::Instance()->lockHandle();\n\tcudaDeviceManager::Instance()->unlockHandle();\n\n\tboost::shared_ptr<CBCT_acquisition> ps(new CBCT_acquisition());\n\tps->load(acquisition_filename);\n\tps->get_geometry()->print(std::cout);\n\tps->downsample(downsamples);\n\n\n\tboost::shared_ptr<CBCT_binning> binning(new CBCT_binning());\n\tif (vm.count(\"binning\")){\n\t\tstd::cout << \"Loading binning data\" << std::endl;\n\t\tbinning->load(vm[\"binning\"].as<string>());\n\t\tif (vm.count(\"3D\"))\n\t\t\tbinning = binning->get_3d_binning();\n\t} else binning->set_as_default_3d_bin(ps->get_projections()->get_size(2));\n\tbinning->print(std::cout);\n\n\tfloatd3 imageDimensions;\n\tif (vm.count(\"dimensions\")){\n\t\timageDimensions = vm[\"dimensions\"].as<floatd3>();\n\t\tvoxelSize = imageDimensions/imageSize;\n\t}\n\telse imageDimensions = voxelSize*imageSize;\n\n\tstd::vector<size_t> is_dims = to_std_vector((uint64d3)imageSize);\n\n\tstd::cout << \"IS dimensions \" << is_dims[0] << \" \" << is_dims[1] << \" \" << is_dims[2] << std::endl;\n\tstd::cout << \"Image size \" << imageDimensions << std::endl;\n\n\tis_dims.push_back(binning->get_number_of_bins());\n\n\tcuNCGSolver<float> solver;\n\t//gpBbSolver<cuNDArray<float>> solver;\n\n\thoCuNDArray<float>* projections = ps->get_projections().get();\n\tstd::cout << \"Projection nrm\" << nrm2(projections) << std::endl;\n\tboost::shared_ptr<cuNDArray<float>> prior;\n\tif (vm.count(\"use_prior\")){\n\t\tprior = calculate_prior(binning,ps,*projections,is_dims,imageDimensions);\n\t\tsolver.set_x0(prior);\n\t}\n\n\n\t// auto projections2 = ps->get_projections();\n\t//auto result = calculate_prior(binning,ps,*projections2,is_dims,imageDimensions);\n\t// Define encoding matrix\n\tboost::shared_ptr< cuConebeamProjectionOperator >\n\tE( new cuConebeamProjectionOperator() );\n\n\tE->setup(ps,binning,imageDimensions);\n\tE->set_domain_dimensions(&is_dims);\n\tE->set_codomain_dimensions(ps->get_projections()->get_dimensions().get());\n\n\t//hoCuGPBBSolver<float> solver;\n\t//hoCuCgDescentSolver<float> solver;\n\n\tsolver.set_encoding_operator(E);\n\tsolver.set_domain_dimensions(&is_dims);\n\tsolver.set_max_iterations(iterations);\n\tsolver.set_output_mode(hoCuGPBBSolver<float>::OUTPUT_VERBOSE);\n\tsolver.set_non_negativity_constraint(true);\n\tsolver.set_rho(rho);\n\n\n\tcuNDArray<float> cuproj(*projections);\n\tif (E->get_use_offset_correction())\n\t\tE->offset_correct(&cuproj);\n\n\n\n\tif (vm.count(\"TV\")){\n\t\tstd::cout << \"Total variation regularization in use\" << std::endl;\n\t\tboost::shared_ptr<cuTvOperator<float,3> > tv(new cuTvOperator<float,3>);\n\t\ttv->set_weight(vm[\"TV\"].as<float>());\n\t\tsolver.add_nonlinear_operator(tv);\n\t\t/*\n    boost::shared_ptr<hoCuTvOperator<float,4> > tv2(new hoCuTvOperator<float,4>);\n    tv2->set_step(2);\n    tv2->set_weight(vm[\"TV\"].as<float>());\n    solver.add_nonlinear_operator(tv2);\n    boost::shared_ptr<hoCuTvOperator<float,4> > tv3(new hoCuTvOperator<float,4>);\n    tv3->set_step(3);\n    tv3->set_weight(vm[\"TV\"].as<float>());\n    solver.add_nonlinear_operator(tv3);\n\t\t */\n\n\t}\n\n\n\tif (vm.count(\"ATV\")){\n\t\tstd::cout << \"Advanced Total variation regularization in use\" << std::endl;\n\t\tboost::shared_ptr<cuATvOperator<float,3> > tv(new cuATvOperator<float,3>);\n\t\ttv->set_weight(vm[\"ATV\"].as<float>());\n\t\tsolver.add_nonlinear_operator(tv);\n\t\t/*\n    boost::shared_ptr<hoCuTvOperator<float,4> > tv2(new hoCuTvOperator<float,4>);\n    tv2->set_step(2);\n    tv2->set_weight(vm[\"TV\"].as<float>());\n    solver.add_nonlinear_operator(tv2);\n    boost::shared_ptr<hoCuTvOperator<float,4> > tv3(new hoCuTvOperator<float,4>);\n    tv3->set_step(3);\n    tv3->set_weight(vm[\"TV\"].as<float>());\n    solver.add_nonlinear_operator(tv3);\n\t\t */\n\n\t}\n\n\tif (vm.count(\"TV4D\")) {\n\t\tstd::cout << \"Total variation 4d regularization in use\" << std::endl;\n\t\tboost::shared_ptr<cuTv1DOperator<float, 4> > tv4d(new cuTv1DOperator<float, 4>);\n\t\ttv4d->set_weight(vm[\"TV4D\"].as<float>());\n\t\tsolver.add_nonlinear_operator(tv4d);\n\t}\n\n\n\tif (vm.count(\"Wavelet\")){\n\t\t//auto wave=  boost::make_shared<cuATrousOperator<float>>();\n//\t\twave->set_domain_dimensions(&is_dims);\n\t\t//wave->set_levels({2,2,2,2});\n\t\tauto wave=  boost::make_shared<cuDWTOperator<float,3>>();\n\t\twave->set_domain_dimensions(&is_dims);\n\t\twave->set_codomain_dimensions(&is_dims);\n\t\twave->set_levels(3);\n\t\twave->set_weight(vm[\"Wavelet\"].as<float>());\n\t\tsolver.add_regularization_operator(wave,1);\n\t}\n\n\tif (dct_weight > 0){\n\t\tauto dctOp = boost::make_shared<cuDCTOperator<float>>();\n\t\tdctOp->set_domain_dimensions(&is_dims);\n\t\tdctOp->set_weight(dct_weight);\n\t\tsolver.add_regularization_operator(dctOp);\n\t}\n\n\n  if (vm.count(\"PICS\")){\n    std::cout << \"PICS in use\" << std::endl;\n    if (!prior) prior = calculate_prior(binning,ps,*projections,is_dims,imageDimensions);\n    boost::shared_ptr<cuTvPicsOperator<float,3> > pics (new cuTvPicsOperator<float,3>);\n    pics->set_prior(prior);\n    pics->set_weight(vm[\"PICS\"].as<float>());\n    solver.add_nonlinear_operator(pics);\n    solver.set_x0(prior);\n  }\n\n\tauto result = solver.solve(&cuproj);\n\n\twrite_dicom(result.get(),command_line_string.str(),imageDimensions);\n\t//write_nd_array( result.get(), outputFile.c_str());\n\tsaveNDArray2HDF5(result.get(),outputFile,imageDimensions,vector_td<float,3>(0),command_line_string.str(),iterations);\n\n}\n", "meta": {"hexsha": "3d8f691b6ad16ab5d77e4121084a3ecbe4ca3228", "size": 11095, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "xray/cuCB_reconstruct.cpp", "max_stars_repo_name": "ahsanjav/gt-tomography", "max_stars_repo_head_hexsha": "1f53d72672ccda417bc8966d8497af6d786e8935", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2017-06-26T13:41:55.000Z", "max_stars_repo_stars_event_max_datetime": "2019-06-10T11:06:27.000Z", "max_issues_repo_path": "xray/cuCB_reconstruct.cpp", "max_issues_repo_name": "ahsanjav/gt-tomography", "max_issues_repo_head_hexsha": "1f53d72672ccda417bc8966d8497af6d786e8935", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "xray/cuCB_reconstruct.cpp", "max_forks_repo_name": "ahsanjav/gt-tomography", "max_forks_repo_head_hexsha": "1f53d72672ccda417bc8966d8497af6d786e8935", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-09-27T14:37:29.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-27T14:37:29.000Z", "avg_line_length": 38.2586206897, "max_line_length": 221, "alphanum_fraction": 0.7140153222, "num_tokens": 3079, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.734119526900183, "lm_q2_score": 0.4532618480153861, "lm_q1q2_score": 0.3327483734269579}}
{"text": "//#include <sba/sba.h>\n#include <Eigen/SVD>\n#include <Eigen/LU>\n#include <iostream>\n#include <limits>\n#include \"opencv2/core/core.hpp\"\n#include \"opencv2/features2d/features2d.hpp\"\n#include \"opencv2/highgui/highgui.hpp\"\n\nnamespace ndt_feature_reg\n{\n\ntemplate <typename PointSource, typename PointTarget>\nPoseEstimator<PointSource,PointTarget>::PoseEstimator(int NRansac,\n        double maxidx, double maxidd)\n{\n    numRansac = NRansac;\n    maxInlierXDist2 = maxidx*maxidx;\n    maxInlierDDist2 = maxidd*maxidd;\n    rot.setIdentity();\n    trans.setZero();\n\n    // matcher\n    matcher = new cv::BFMatcher(cv::NORM_L2);\n    wx = 92;\n    wy = 48;\n    windowed = false;\n    projectMatches = true;\n\n    maxDist = std::numeric_limits<double>::max();\n    minDist = -1.;\n}\n\ntemplate <typename PointSource, typename PointTarget>\nvoid\nPoseEstimator<PointSource,PointTarget>::matchFrames(const NDTFrame<PointSource>& f0, const NDTFrame<PointTarget>& f1, std::vector<cv::DMatch>& fwd_matches)\n{\n    cv::Mat mask;\n    if (windowed)\n        mask = cv::windowedMatchingMask(f0.kpts, f1.kpts, wx, wy);\n\n    //require at least 3 kpts each\n    if(f0.kpts.size() > 3 && f1.kpts.size() > 3) \n    {\n\tmatcher->match(f0.dtors, f1.dtors, fwd_matches, mask);\n    }\n}\n\n\ntemplate <typename PointSource, typename PointTarget>\nsize_t PoseEstimator<PointSource,PointTarget>::estimate(const NDTFrame<PointSource> &f0, const NDTFrame<PointTarget> &f1)\n{\n    // set up match lists\n    matches.clear();\n    inliers.clear();\n\n//     std::cout<<\"N KPTS: \"<<f0.kpts.size()<<\" \"<<f1.kpts.size()<<std::endl;\n//     std::cout<<\"descriptors: \"<<f0.dtors.size().width<<\"x\"<<f0.dtors.size().height<<\" \"\n//\t\t\t       <<f1.dtors.size().width<<\"x\"<<f1.dtors.size().height<<std::endl;\n    // do forward and reverse matches\n    std::vector<cv::DMatch> fwd_matches, rev_matches;\n    matchFrames(f0, f1, fwd_matches);\n    matchFrames(f1, f0, rev_matches);\n//     printf(\"**** Forward matches: %d, reverse matches: %d ****\\n\", (int)fwd_matches.size(), (int)rev_matches.size());\n\n    // combine unique matches into one list\n    for (int i = 0; i < (int)fwd_matches.size(); ++i)\n    {\n        if (fwd_matches[i].trainIdx >= 0)\n            matches.push_back( cv::DMatch(i, fwd_matches[i].trainIdx, fwd_matches[i].distance) );\n        //matches.push_back( cv::DMatch(fwd_matches[i].queryIdx, fwd_matches[i].trainIdx, fwd_matches[i].distance) );\n    }\n    for (int i = 0; i < (int)rev_matches.size(); ++i)\n    {\n        if (rev_matches[i].trainIdx >= 0 && i != fwd_matches[rev_matches[i].trainIdx].trainIdx)\n            matches.push_back( cv::DMatch(rev_matches[i].trainIdx, i, rev_matches[i].distance) );\n        //matches.push_back( cv::DMatch(rev_matches[i].trainIdx, rev_matches[i].queryIdx, rev_matches[i].distance) );\n    }\n//     printf(\"**** Total unique matches: %d ****\\n\", (int)matches.size());\n\n    // do it\n    return estimate(f0, f1, matches);\n}\n\n\ntemplate <typename PointSource, typename PointTarget>\nsize_t PoseEstimator<PointSource,PointTarget>::estimate(const NDTFrame<PointSource>& f0, const NDTFrame<PointTarget>& f1,\n        const std::vector<cv::DMatch> &matches)\n{\n    // convert keypoints in match to 3d points\n    std::vector<Eigen::Vector4d, Eigen::aligned_allocator<Eigen::Vector4d> > p0; // homogeneous coordinates\n    std::vector<Eigen::Vector4d, Eigen::aligned_allocator<Eigen::Vector4d> > p1;\n\n    int nmatch = matches.size();\n    //srand(getDoubleTime());\n\n    // set up data structures for fast processing\n    // indices to good matches\n    std::vector<int> m0, m1;\n    for (int i=0; i<nmatch; i++)\n    {\n        m0.push_back(matches[i].queryIdx);\n        m1.push_back(matches[i].trainIdx);\n        //std::cout<<m0[i]<<\" \"<<m1[i]<<std::endl;\n    }\n\n    nmatch = m0.size();\n\n    if (nmatch < 3) return 0;   // can't do it...\n\n    int bestinl = 0;\n\n    // RANSAC loop\n//#pragma omp parallel for shared( bestinl )\n    for (int i=0; i<numRansac; i++)\n    {\n        //std::cout << \"ransac loop : \" << i << std::endl;\n        // find a candidate\n        int a=rand()%nmatch;\n        int b = a;\n        while (a==b)\n            b=rand()%nmatch;\n        int c = a;\n        while (a==c || b==c)\n            c=rand()%nmatch;\n\n        int i0a = m0[a];\n        int i0b = m0[b];\n        int i0c = m0[c];\n        int i1a = m1[a];\n        int i1b = m1[b];\n        int i1c = m1[c];\n\n        if (i0a == i0b || i0a == i0c || i0b == i0c ||\n                i1a == i1b || i1a == i1c || i1b == i1c)\n            continue;\n\n        //std::cout<<a<<\" \"<<b<<\" \"<<c<<std::endl;\n        //std::cout<<i0a<<\" \"<<i0b<<\" \"<<i0c<<std::endl;\n        //std::cout<<i1a<<\" \"<<i1b<<\" \"<<i1c<<std::endl;\n\n        // get centroids\n        Eigen::Vector3d p0a = f0.pts[i0a].head(3);\n        Eigen::Vector3d p0b = f0.pts[i0b].head(3);\n        Eigen::Vector3d p0c = f0.pts[i0c].head(3);\n        Eigen::Vector3d p1a = f1.pts[i1a].head(3);\n        Eigen::Vector3d p1b = f1.pts[i1b].head(3);\n        Eigen::Vector3d p1c = f1.pts[i1c].head(3);\n\n        Eigen::Vector3d c0 = (p0a+p0b+p0c)*(1.0/3.0);\n        Eigen::Vector3d c1 = (p1a+p1b+p1c)*(1.0/3.0);\n\n        //std::cout<<c0.transpose()<<std::endl;\n        //std::cout<<c1.transpose()<<std::endl;\n        // subtract out\n        p0a -= c0;\n        p0b -= c0;\n        p0c -= c0;\n        p1a -= c1;\n        p1b -= c1;\n        p1c -= c1;\n\n        Eigen::Matrix3d H = p1a*p0a.transpose() + p1b*p0b.transpose() +\n                            p1c*p0c.transpose();\n\n        // do the SVD thang\n        Eigen::JacobiSVD<Eigen::Matrix3d> svd(H, Eigen::ComputeFullU | Eigen::ComputeFullV);\n        Eigen::Matrix3d V = svd.matrixV();\n        Eigen::Matrix3d R = V * svd.matrixU().transpose();\n        double det = R.determinant();\n        //ntot++;\n        if (det < 0.0)\n        {\n            //nneg++;\n            V.col(2) = V.col(2)*-1.0;\n            R = V * svd.matrixU().transpose();\n        }\n        Eigen::Vector3d tr = c0-R*c1;    // translation\n\n        // transformation matrix, 3x4\n        Eigen::Matrix<double,3,4> tfm;\n        //        tfm.block<3,3>(0,0) = R.transpose();\n        //        tfm.col(3) = -R.transpose()*tr;\n        tfm.block<3,3>(0,0) = R;\n        tfm.col(3) = tr;\n\n#if 0\n        // find inliers, based on image reprojection\n        int inl = 0;\n        for (int i=0; i<nmatch; i++)\n        {\n            Vector3d pt = tfm*f1.pts[m1[i]];\n            Vector3d ipt = f0.cam2pix(pt);\n            const cv::KeyPoint &kp = f0.kpts[m0[i]];\n            double dx = kp.pt.x - ipt.x();\n            double dy = kp.pt.y - ipt.y();\n            double dd = f0.disps[m0[i]] - ipt.z();\n            if (dx*dx < maxInlierXDist2 && dy*dy < maxInlierXDist2 &&\n                    dd*dd < maxInlierDDist2)\n            {\n                inl+=(int)sqrt(ipt.z()); // clever way to weight closer points\n//\t\t inl+=(int)sqrt(ipt.z()/matches[i].distance);\n//\t\t cout << \"matches[i].distance : \" << matches[i].distance << endl;\n//\t\t inl++;\n            }\n        }\n#endif\n        int inl = 0;\n        for (int i=0; i<nmatch; i++)\n        {\n            Eigen::Vector3d pt1 = tfm*f1.pts[m1[i]];\n            Eigen::Vector3d pt0 = f0.pts[m0[i]].head(3);\n\n//\t       double z = fabs(pt1.z() - pt0.z())*0.5;\n            double z = pt1.z();\n            double dx = pt1.x() - pt0.x();\n            double dy = pt1.y() - pt0.y();\n            double dd = pt1.z() - pt0.z();\n\n            if (projectMatches)\n            {\n                // The central idea here is to divide by the distance (this is essentially what cam2pix does).\n                dx = dx / z;\n                dy = dy / z;\n            }\n            if (dx*dx < maxInlierXDist2 && dy*dy < maxInlierXDist2 &&\n                    dd*dd < maxInlierDDist2)\n            {\n//----\t\t    inl+=(int)sqrt(pt0.z()); // clever way to weight closer points\n//\t\t inl+=(int)sqrt(ipt.z()/matches[i].distance);\n//\t\t cout << \"matches[i].distance : \" << matches[i].distance << endl;\n                inl++;\n            }\n        }\n\n//#pragma omp critical\n        if (inl > bestinl)\n        {\n            bestinl = inl;\n            rot = R;\n            trans = tr;\n//\t       std::cout << \"bestinl : \" << bestinl << std::endl;\n        }\n    }\n\n    //printf(\"Best inliers: %d\\n\", bestinl);\n    //printf(\"Total ransac: %d  Neg det: %d\\n\", ntot, nneg);\n\n    // reduce matches to inliers\n    std::vector<cv::DMatch> inls;    // temporary for current inliers\n    inliers.clear();\n    Eigen::Matrix<double,3,4> tfm;\n    tfm.block<3,3>(0,0) = rot;\n    tfm.col(3) = trans;\n\n    //std::cout<<\"f0: \"<<f0.pts.size()<<\" \"<<f0.kpts.size()<<\" \"<<f0.pc_kpts.size()<<std::endl;\n    //std::cout<<\"f1: \"<<f1.pts.size()<<\" \"<<f1.kpts.size()<<\" \"<<f1.pc_kpts.size()<<std::endl;\n\n    nmatch = matches.size();\n    for (int i=0; i<nmatch; i++)\n    {\n        Eigen::Vector3d pt1 = tfm*f1.pts[matches[i].trainIdx];\n        //Eigen::Vector3d pt1_unchanged = f1.pts[matches[i].trainIdx].head(3);\n        //Vector3d pt1 = pt1_unchanged;\n#if 0\n        Vector3d ipt = f0.cam2pix(pt);\n        const cv::KeyPoint &kp = f0.kpts[matches[i].queryIdx];\n        double dx = kp.pt.x - ipt.x();\n        double dy = kp.pt.y - ipt.y();\n        double dd = f0.disps[matches[i].queryIdx] - ipt.z();\n#endif\n        Eigen::Vector3d pt0 = f0.pts[matches[i].queryIdx].head(3);\n\n        //double z = fabs(pt1.z() - pt0.z())*0.5;\n        double z = pt1.z();\n        double dx = pt1.x() - pt0.x();\n        double dy = pt1.y() - pt0.y();\n        double dd = pt1.z() - pt0.z();\n\n        if (projectMatches)\n        {\n            // The central idea here is to divide by the distance (this is essentially what cam2pix does).\n            dx = dx / z;\n            dy = dy / z;\n        }\n\n        if (dx*dx < maxInlierXDist2 && dy*dy < maxInlierXDist2 &&\n                dd*dd < maxInlierDDist2)\n        {\n            if (z < maxDist && z > minDist)\n\n//\t       if (fabs(f0.kpts[matches[i].queryIdx].pt.y - f1.kpts[matches[i].trainIdx].pt.y) > 300)\n            {\n//\t\t   std::cout << \" ---------- \" << dx << \",\" << dy << \",\" << dd << \",\\npt0 \" << pt0.transpose() << \"\\npt1 \" << pt1.transpose() << f0.kpts[matches[i].queryIdx].pt << \",\" <<\n//\t\t\t f1.kpts[matches[i].trainIdx].pt << \"\\n unchanged pt1 \" << pt1_unchanged.transpose() << std::endl;\n                inliers.push_back(matches[i]);\n            }\n        }\n    }\n\n#if 0\n    // Test with the SBA...\n    {\n        // system\n        SysSBA sba;\n        sba.verbose = 0;\n\n#if 0\n        // set up nodes\n        // should have a frame => node function\n        Vector4d v0 = Vector4d(0,0,0,1);\n        Quaterniond q0 = Quaternion<double>(Vector4d(0,0,0,1));\n        sba.addNode(v0, q0, f0.cam, true);\n\n        Quaterniond qr1(rot);   // from rotation matrix\n        Vector4d temptrans = Vector4d(trans(0), trans(1), trans(2), 1.0);\n\n        //        sba.addNode(temptrans, qr1.normalized(), f1.cam, false);\n        qr1.normalize();\n        sba.addNode(temptrans, qr1, f1.cam, false);\n\n        int in = 3;\n        if (in > (int)inls.size())\n            in = inls.size();\n\n        // set up projections\n        for (int i=0; i<(int)inls.size(); i++)\n        {\n            // add point\n            int i0 = inls[i].queryIdx;\n            int i1 = inls[i].trainIdx;\n            Vector4d pt = f0.pts[i0];\n            sba.addPoint(pt);\n\n            // projected point, ul,vl,ur\n            Vector3d ipt;\n            ipt(0) = f0.kpts[i0].pt.x;\n            ipt(1) = f0.kpts[i0].pt.y;\n            ipt(2) = ipt(0)-f0.disps[i0];\n            sba.addStereoProj(0, i, ipt);\n\n            // projected point, ul,vl,ur\n            ipt(0) = f1.kpts[i1].pt.x;\n            ipt(1) = f1.kpts[i1].pt.y;\n            ipt(2) = ipt(0)-f1.disps[i1];\n            sba.addStereoProj(1, i, ipt);\n        }\n\n        sba.huber = 2.0;\n        sba.doSBA(5,10e-4,SBA_DENSE_CHOLESKY);\n        int nbad = sba.removeBad(2.0); // 2.0\n        cout << endl << \"Removed \" << nbad << \" projections > 2 pixels error\" << endl;\n        sba.doSBA(5,10e-5,SBA_DENSE_CHOLESKY);\n\n//        cout << endl << sba.nodes[1].trans.transpose().head(3) << endl;\n\n        // get the updated transform\n        trans = sba.nodes[1].trans.head(3);\n        Quaterniond q1;\n        q1 = sba.nodes[1].qrot;\n        quat = q1;\n        rot = q1.toRotationMatrix();\n\n        // set up inliers\n        inliers.clear();\n        for (int i=0; i<(int)inls.size(); i++)\n        {\n            ProjMap &prjs = sba.tracks[i].projections;\n            if (prjs[0].isValid && prjs[1].isValid) // valid track\n                inliers.push_back(inls[i]);\n        }\n\n        printf(\"Inliers: %d   After polish: %d\\n\", (int)inls.size(), (int)inliers.size());\n#endif\n    }\n#endif\n\n//     std::cout << std::endl << trans.transpose().head(3) << std::endl << std::endl;\n//     std::cout << rot << std::endl;\n\n    return inliers.size();\n}\n}\n", "meta": {"hexsha": "afbca0fad645faf10108a2b601cbd572a114da31", "size": 12740, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "perception_oru-port-kinetic/ndt_feature_reg/include/ndt_feature_reg/impl/ndt_frame.hpp", "max_stars_repo_name": "lllray/ndt-loam", "max_stars_repo_head_hexsha": "331867941e0764b40e1a980dd85d2174f861e9c8", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-11-14T08:21:13.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-14T08:21:13.000Z", "max_issues_repo_path": "perception_oru-port-kinetic/ndt_feature_reg/include/ndt_feature_reg/impl/ndt_frame.hpp", "max_issues_repo_name": "lllray/ndt-loam", "max_issues_repo_head_hexsha": "331867941e0764b40e1a980dd85d2174f861e9c8", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-07-28T04:47:56.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-28T04:47:56.000Z", "max_forks_repo_path": "perception_oru-port-kinetic/ndt_feature_reg/include/ndt_feature_reg/impl/ndt_frame.hpp", "max_forks_repo_name": "lllray/ndt-loam", "max_forks_repo_head_hexsha": "331867941e0764b40e1a980dd85d2174f861e9c8", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-12-18T11:25:53.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-19T12:59:59.000Z", "avg_line_length": 33.1770833333, "max_line_length": 174, "alphanum_fraction": 0.5298273155, "num_tokens": 3972, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7341195152660687, "lm_q2_score": 0.4532618480153861, "lm_q1q2_score": 0.3327483681536577}}
{"text": "/*    Copyright (c) 2010-2019, Delft University of Technology\n *    All rigths reserved\n *\n *    This file is part of the Tudat. Redistribution and use in source and\n *    binary forms, with or without modification, are permitted exclusively\n *    under the terms of the Modified BSD license. You should have received\n *    a copy of the license with this file. If not, please or visit:\n *    http://tudat.tudelft.nl/LICENSE.\n */\n\n#include <boost/make_shared.hpp>\n#include <boost/shared_ptr.hpp>\n\n#include <Eigen/Core>\n\n#include <tudat/astro/basic_astro/physicalConstants.h>\n#include <tudat/basics/testMacros.h>\n#include <tudat/math/basic/mathematicalConstants.h>\n#include \"tudat/astro/basic_astro/unitConversions.h\"\n#include <tudat/astro/basic_astro/orbitalElementConversions.h>\n\n#include <tudat/io/basicInputOutput.h>\n#include <tudat/io/applicationOutput.h>\n\n\n#include \"tudat/astro/ephemerides/approximatePlanetPositions.h\"\n#include \"tudat/astro/trajectory_design/trajectory.h\"\n#include \"tudat/astro/trajectory_design/exportTrajectory.h\"\n#include \"tudat/astro/trajectory_design/planetTrajectory.h\"\n\nint main( )\n{\n    using namespace tudat;\n    using namespace tudat::input_output;\n    using namespace tudat::input_output::parsed_data_vector_utilities;\n    using namespace tudat::transfer_trajectories;\n\n    //////////////////////////////////////////////////////////////////////////\n    ////////////////////////// CASSSINI //////////////////////////////////////\n    //////////////////////////////////////////////////////////////////////////\n\n    // Specify required parameters\n    // Specify the number of legs and type of legs.\n    int numberOfLegs = 6;\n    std::vector< TransferLegType > legTypeVector;\n    legTypeVector.resize( numberOfLegs );\n    legTypeVector[ 0 ] = mga_Departure;\n    legTypeVector[ 1 ] = mga_Swingby;\n    legTypeVector[ 2 ] = mga_Swingby;\n    legTypeVector[ 3 ] = mga_Swingby;\n    legTypeVector[ 4 ] = mga_Swingby;\n    legTypeVector[ 5 ] = capture;\n\n    // Create the ephemeris vector.\n    std::vector< ephemerides::EphemerisPointer >\n            ephemerisVector( numberOfLegs );\n    ephemerisVector[ 0 ] = std::make_shared< ephemerides::ApproximatePlanetPositions >(\n                ephemerides::ApproximatePlanetPositionsBase::BodiesWithEphemerisData::earthMoonBarycenter );\n    ephemerisVector[ 1 ] = std::make_shared< ephemerides::ApproximatePlanetPositions >(\n                ephemerides::ApproximatePlanetPositionsBase::BodiesWithEphemerisData::venus );\n    ephemerisVector[ 2 ] = std::make_shared< ephemerides::ApproximatePlanetPositions >(\n                ephemerides::ApproximatePlanetPositionsBase::BodiesWithEphemerisData::venus );\n    ephemerisVector[ 3 ] = std::make_shared< ephemerides::ApproximatePlanetPositions >(\n                ephemerides::ApproximatePlanetPositionsBase::BodiesWithEphemerisData::earthMoonBarycenter );\n    ephemerisVector[ 4 ] = std::make_shared< ephemerides::ApproximatePlanetPositions >(\n                ephemerides::ApproximatePlanetPositionsBase::BodiesWithEphemerisData::jupiter );\n    ephemerisVector[ 5 ] = std::make_shared< ephemerides::ApproximatePlanetPositions >(\n                ephemerides::ApproximatePlanetPositionsBase::BodiesWithEphemerisData::saturn );\n\n    // Create gravitational parameter vector\n    Eigen::VectorXd gravitationalParameterVector( numberOfLegs );\n    gravitationalParameterVector << 3.9860119e14, 3.24860e14, 3.24860e14, 3.9860119e14, 1.267e17, 3.79e16;\n\n    // Create variable vector.\n    Eigen::VectorXd variableVector( numberOfLegs + 1 );\n    variableVector << -789.8117, 158.302027105278, 449.385873819743, 54.7489684339665,\n            1024.36205846918, 4552.30796805542, 1/*dummy*/;\n    variableVector *= physical_constants::JULIAN_DAY;\n\n    // Create departure and capture variables.\n    Eigen::VectorXd semiMajorAxes( 2 ), eccentricities( 2 );\n    semiMajorAxes << std::numeric_limits< double >::infinity( ), 1.0895e8 / 0.02;\n    eccentricities << 0.0, 0.98;\n\n    // Sun gravitational parameter\n    const double sunGravitationalParameter = 1.32712428e20;\n\n    // Create minimum pericenter radii vector\n    Eigen::VectorXd minimumPericenterRadii( numberOfLegs );\n    minimumPericenterRadii << 6778000.0, 6351800.0, 6351800.0, 6778000.0, 600000000.0, 600000000.0;\n\n    // Create the trajectory problem.\n    Trajectory Cassini1( numberOfLegs, legTypeVector, ephemerisVector,\n                         gravitationalParameterVector, variableVector, sunGravitationalParameter,\n                         minimumPericenterRadii, semiMajorAxes, eccentricities );\n\n    // Vectors for the specific maneuvers and the total delta v\n    std::vector< Eigen::Vector3d > positionVector;\n    std::vector< double > timeVector;\n    std::vector< double > deltaVVector;\n    double resultingDeltaV;\n\n    // Calculate the orbits\n    Cassini1.calculateTrajectory( resultingDeltaV );\n    Cassini1.maneuvers( positionVector, timeVector, deltaVVector );\n\n    std::cout << \" Cassini Mission: \" << std::endl;\n    std::cout << \" Total Delta V needed: \" << resultingDeltaV <<std::endl;\n    std::cout << \" Time of Earth departure: \" << timeVector[ 0 ]\n              << \". Delta V needed at Earth: \" << deltaVVector[ 0 ] << std::endl;\n    std::cout << \" Time of Venus visit: \" << timeVector[ 1 ]\n              << \". Delta V needed at Venus: \" << deltaVVector[ 1 ] << std::endl;\n    std::cout << \" Time of second Venus visit: \" << timeVector[ 2 ]\n              << \". Delta V needed at Venus: \" << deltaVVector[ 2 ] << std::endl;\n    std::cout << \" Time of Earth visit: \" << timeVector[ 3 ]\n              << \". Delta V needed at Earth: \" << deltaVVector[ 3 ] << std::endl;\n    std::cout << \" Time of Jupiter visit: \" << timeVector[ 4 ]\n              << \". Delta V needed at Jupiter: \" << deltaVVector[ 4 ] << std::endl;\n    std::cout << \" Time of Saturn capture: \" << timeVector[ 5 ]\n              << \". Delta V needed at Saturn: \" << deltaVVector[ 5 ] << std::endl;\n\n    std::cout << std::endl << std::endl;\n\n    //////////////////////////////////////////////////////////////////////////\n    ////////////////////////// MESSENGER /////////////////////////////////////\n    //////////////////////////////////////////////////////////////////////////\n\n    // Specify required parameters\n    // Specify the number of legs and type of legs.\n    numberOfLegs = 5;\n    legTypeVector.resize( numberOfLegs );\n    legTypeVector[ 0 ] = mga1DsmVelocity_Departure;\n    legTypeVector[ 1 ] = mga1DsmVelocity_Swingby;\n    legTypeVector[ 2 ] = mga1DsmVelocity_Swingby;\n    legTypeVector[ 3 ] = mga1DsmVelocity_Swingby;\n    legTypeVector[ 4 ] = capture;\n\n    // Create the ephemeris vector.\n    ephemerisVector.resize( numberOfLegs );\n    ephemerisVector[ 0 ] = std::make_shared< ephemerides::ApproximatePlanetPositions >(\n                ephemerides::ApproximatePlanetPositionsBase::BodiesWithEphemerisData::earthMoonBarycenter );\n    ephemerisVector[ 1 ] = std::make_shared< ephemerides::ApproximatePlanetPositions >(\n                ephemerides::ApproximatePlanetPositionsBase::BodiesWithEphemerisData::earthMoonBarycenter );\n    ephemerisVector[ 2 ] = std::make_shared< ephemerides::ApproximatePlanetPositions >(\n                ephemerides::ApproximatePlanetPositionsBase::BodiesWithEphemerisData::venus );\n    ephemerisVector[ 3 ] = std::make_shared< ephemerides::ApproximatePlanetPositions >(\n                ephemerides::ApproximatePlanetPositionsBase::BodiesWithEphemerisData::venus );\n    ephemerisVector[ 4 ] = std::make_shared< ephemerides::ApproximatePlanetPositions >(\n                ephemerides::ApproximatePlanetPositionsBase::BodiesWithEphemerisData::mercury );\n\n    // Create gravitational parameter vector\n    gravitationalParameterVector.resize( numberOfLegs );\n    gravitationalParameterVector << 3.9860119e14, 3.9860119e14, 3.24860e14, 3.24860e14, 2.2321e13;\n\n    // Create variable vector.\n    variableVector.resize( numberOfLegs /*time of flight*/ + 1 /*start epoch*/ +\n                           4 * ( numberOfLegs - 1 ) /*additional variables for model, except the final capture leg*/ );\n\n    // Add the time of flight and start epoch, which are in JD.\n    variableVector << 1171.64503236 * physical_constants::JULIAN_DAY,\n            399.999999715 * physical_constants::JULIAN_DAY,\n            178.372255301 * physical_constants::JULIAN_DAY,\n            299.223139512 * physical_constants::JULIAN_DAY,\n            180.510754824 * physical_constants::JULIAN_DAY,\n            1, // The capture time is irrelevant for the final leg.\n            // Add the additional variables.\n            0.234594654679, 1408.99421278, 0.37992647165 * 2 * 3.14159265358979,\n            std::acos(  2 * 0.498004040298 - 1. ) - 3.14159265358979 / 2, // 1st leg.\n            0.0964769387134, 1.35077257078, 1.80629232251 * 6.378e6, 0.0, // 2nd leg.\n            0.829948744508, 1.09554368115, 3.04129845698 * 6.052e6, 0.0, // 3rd leg.\n            0.317174785637, 1.34317576594, 1.10000000891 * 6.052e6, 0.0; // 4th leg.\n\n    // Create minimum pericenter radii vector\n    minimumPericenterRadii.resize( numberOfLegs );\n    minimumPericenterRadii << TUDAT_NAN, TUDAT_NAN, TUDAT_NAN, TUDAT_NAN, TUDAT_NAN;\n\n    // Create departure and capture variables.\n    semiMajorAxes << std::numeric_limits< double >::infinity( ),\n            std::numeric_limits< double >::infinity( );\n    eccentricities << 0.0, 0.0;\n\n    // Create the trajectory problem.\n    Trajectory Messenger( numberOfLegs, legTypeVector, ephemerisVector,\n                          gravitationalParameterVector, variableVector, sunGravitationalParameter,\n                          minimumPericenterRadii, semiMajorAxes, eccentricities );\n\n    // Vectors for the specific maneuvers and the total delta v\n    std::vector< Eigen::Vector3d > positionVectorMessenger;\n    std::vector< double > timeVectorMessenger;\n    std::vector< double > deltaVVectorMessenger;\n    double resultingDeltaVMessenger;\n\n    // Calculate the orbits\n    Messenger.calculateTrajectory( resultingDeltaVMessenger );\n    Messenger.maneuvers( positionVectorMessenger, timeVectorMessenger, deltaVVectorMessenger );\n\n    std::cout << \" Messenger Mission: \" << std::endl;\n    std::cout << \" Total Delta V: \" << resultingDeltaVMessenger <<std::endl;\n    std::cout << \" Time of Earth departure: \" << timeVectorMessenger[ 0 ]\n              << \". Delta V needed at Earth: \" << deltaVVectorMessenger[ 0 ] << std::endl;\n    std::cout << \" Time of 1st DSM: \" << timeVectorMessenger[ 1 ]\n              << \". Delta V needed for 1st DSM: \" << deltaVVectorMessenger[ 1 ] << std::endl;\n    std::cout << \" Time of second Earth visit: \" << timeVectorMessenger[ 2 ]\n              << \". Delta V needed at Earth: \" << deltaVVectorMessenger[ 2 ] << std::endl;\n    std::cout << \" Time of 2nd DSM: \" << timeVectorMessenger[ 3 ]\n              << \". Delta V needed for 2nd DSM: \" << deltaVVectorMessenger[ 3 ] << std::endl;\n    std::cout << \" Time of Venus visit: \" << timeVectorMessenger[ 4 ]\n              << \". Delta V needed at Venus: \" << deltaVVectorMessenger[ 4 ] << std::endl;\n    std::cout << \" Time of 3d DSM: \" << timeVectorMessenger[ 5 ]\n              << \". Delta V needed for 3d DSM: \" << deltaVVectorMessenger[ 5 ] << std::endl;\n    std::cout << \" Time of second Venus visit: \" << timeVectorMessenger[ 6 ]\n              << \". Delta V needed at Venus: \" << deltaVVectorMessenger[ 6 ] << std::endl;\n    std::cout << \" Time of 4th DSM: \" << timeVectorMessenger[ 7 ]\n              << \". Delta V needed for 4th DSM: \" << deltaVVectorMessenger[ 7 ] << std::endl;\n    std::cout << \" Time of Mercury capture: \" << timeVectorMessenger[ 8 ]\n              << \". Delta V needed at Mercury: \" << deltaVVectorMessenger[ 8 ] << std::endl;\n\n    // Define vectors to calculate intermediate points\n    std::vector< Eigen::Vector3d > interPositionVectorMessenger;\n    std::vector< double > interTimeVectorMessenger;\n\n    // Calculate intermediate points and write to file\n    std::string outputFileTraj = tudat_applications::getOutputPath( ) + \"/messengerTrajectory.dat\";\n    Messenger.intermediatePoints( 1000.0 , interPositionVectorMessenger, interTimeVectorMessenger );\n    writeTrajectoryToFile( interPositionVectorMessenger, interTimeVectorMessenger, outputFileTraj );\n\n    // Define vectors to calculate intermediate points\n    std::vector< Eigen::Vector3d > manPositionVectorMessenger;\n    std::vector< double > manTimeVectorMessenger;\n    std::vector< double > manDeltaVVectorMessenger;\n\n    // Calculate maneuvers and write to file\n    std::string outputFileMan = tudat_applications::getOutputPath( ) + \"/messengerManeuvers.dat\";\n    Messenger.maneuvers( manPositionVectorMessenger, manTimeVectorMessenger, manDeltaVVectorMessenger );\n    writeTrajectoryToFile( manPositionVectorMessenger, manTimeVectorMessenger, outputFileMan );\n\n    // Calculate trajectories of the planets and output to file\n    std::vector< Eigen::Vector3d > positionVectorEarth;\n    std::vector< double > timeVectorEarth;\n    std::vector< Eigen::Vector3d > positionVectorVenus;\n    std::vector< double > timeVectorVenus;\n    std::vector< Eigen::Vector3d > positionVectorMercury;\n    std::vector< double > timeVectorMercury;\n\n    // Earth\n    returnSingleRevolutionPlanetTrajectory(\n                std::make_shared< ephemerides::ApproximatePlanetPositions >(\n                    ephemerides::ApproximatePlanetPositionsBase::BodiesWithEphemerisData::earthMoonBarycenter ),\n                sunGravitationalParameter,\n                1171.64503236,\n                1000.0,\n                positionVectorEarth,\n                timeVectorEarth );\n\n    // Venus\n    returnSingleRevolutionPlanetTrajectory(\n                std::make_shared< ephemerides::ApproximatePlanetPositions >(\n                    ephemerides::ApproximatePlanetPositionsBase::BodiesWithEphemerisData::venus ),\n                sunGravitationalParameter,\n                1171.64503236,\n                1000.0,\n                positionVectorVenus,\n                timeVectorVenus );\n\n    // Mercury\n    returnSingleRevolutionPlanetTrajectory(\n                std::make_shared< ephemerides::ApproximatePlanetPositions >(\n                    ephemerides::ApproximatePlanetPositionsBase::BodiesWithEphemerisData::mercury ),\n                sunGravitationalParameter,\n                1171.64503236,\n                1000.0,\n                positionVectorMercury,\n                timeVectorMercury );\n\n    std::string outputFilePlanetE = tudat_applications::getOutputPath(  ) + \"earthTrajectory.dat\";\n    writeTrajectoryToFile( positionVectorEarth, timeVectorEarth, outputFilePlanetE );\n\n    std::string outputFilePlanetV = tudat_applications::getOutputPath(  ) + \"venusTrajectory.dat\";\n    writeTrajectoryToFile( positionVectorVenus, timeVectorVenus, outputFilePlanetV );\n\n    std::string outputFilePlanetM = tudat_applications::getOutputPath(  ) + \"mercuryTrajectory.dat\";\n    writeTrajectoryToFile( positionVectorMercury, timeVectorMercury, outputFilePlanetM );\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": "e39dd466678ee3d070ae7a6f5f3b4b39cfa01f88", "size": 15099, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/tudat/satellite_propagation/interplanetaryTrajectoryDesign.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/interplanetaryTrajectoryDesign.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/interplanetaryTrajectoryDesign.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": 52.4270833333, "max_line_length": 119, "alphanum_fraction": 0.6669315849, "num_tokens": 3953, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7217432062975979, "lm_q2_score": 0.4610167793123159, "lm_q1q2_score": 0.332735728457863}}
{"text": "#ifndef STAN_MATH_REV_MAT_FUN_DOT_PRODUCT_HPP\n#define STAN_MATH_REV_MAT_FUN_DOT_PRODUCT_HPP\n\n#include <stan/math/prim/mat/fun/Eigen.hpp>\n#include <stan/math/prim/mat/fun/typedefs.hpp>\n#include <stan/math/prim/mat/err/check_vector.hpp>\n#include <stan/math/prim/arr/err/check_matching_sizes.hpp>\n#include <stan/math/prim/scal/fun/value_of.hpp>\n#include <stan/math/rev/core.hpp>\n#include <stan/math/rev/mat/fun/typedefs.hpp>\n#include <stan/math/rev/scal/fun/value_of.hpp>\n#include <boost/utility/enable_if.hpp>\n#include <boost/type_traits.hpp>\n#include <vector>\n\nnamespace stan {\nnamespace math {\n\nnamespace {\ntemplate <typename T>\nstruct dot_product_store_type;\n\ntemplate <>\nstruct dot_product_store_type<var> {\n  typedef vari** type;\n};\n\ntemplate <>\nstruct dot_product_store_type<double> {\n  typedef double* type;\n};\n\ntemplate <typename T1, typename T2>\nclass dot_product_vari : public vari {\n protected:\n  typename dot_product_store_type<T1>::type v1_;\n  typename dot_product_store_type<T2>::type v2_;\n  size_t length_;\n\n  inline static double var_dot(vari** v1, vari** v2, size_t length) {\n    Eigen::VectorXd vd1(length), vd2(length);\n    for (size_t i = 0; i < length; i++) {\n      vd1[i] = v1[i]->val_;\n      vd2[i] = v2[i]->val_;\n    }\n    return vd1.dot(vd2);\n  }\n\n  inline static double var_dot(const T1* v1, const T2* v2, size_t length) {\n    Eigen::VectorXd vd1(length), vd2(length);\n    for (size_t i = 0; i < length; i++) {\n      vd1[i] = value_of(v1[i]);\n      vd2[i] = value_of(v2[i]);\n    }\n    return vd1.dot(vd2);\n  }\n\n  template <typename Derived1, typename Derived2>\n  inline static double var_dot(const Eigen::DenseBase<Derived1>& v1,\n                               const Eigen::DenseBase<Derived2>& v2) {\n    Eigen::VectorXd vd1(v1.size()), vd2(v1.size());\n    for (int i = 0; i < v1.size(); i++) {\n      vd1[i] = value_of(v1[i]);\n      vd2[i] = value_of(v2[i]);\n    }\n    return vd1.dot(vd2);\n  }\n  inline void chain(vari** v1, vari** v2) {\n    for (size_t i = 0; i < length_; i++) {\n      v1[i]->adj_ += adj_ * v2_[i]->val_;\n      v2[i]->adj_ += adj_ * v1_[i]->val_;\n    }\n  }\n  inline void chain(double* v1, vari** v2) {\n    for (size_t i = 0; i < length_; i++) {\n      v2[i]->adj_ += adj_ * v1_[i];\n    }\n  }\n  inline void chain(vari** v1, double* v2) {\n    for (size_t i = 0; i < length_; i++) {\n      v1[i]->adj_ += adj_ * v2_[i];\n    }\n  }\n  inline void initialize(vari**& mem_v, const var* inv, vari** shared = NULL) {\n    if (shared == NULL) {\n      mem_v = reinterpret_cast<vari**>(\n          ChainableStack::memalloc_.alloc(length_ * sizeof(vari*)));\n      for (size_t i = 0; i < length_; i++)\n        mem_v[i] = inv[i].vi_;\n    } else {\n      mem_v = shared;\n    }\n  }\n  template <typename Derived>\n  inline void initialize(vari**& mem_v, const Eigen::DenseBase<Derived>& inv,\n                         vari** shared = NULL) {\n    if (shared == NULL) {\n      mem_v = reinterpret_cast<vari**>(\n          ChainableStack::memalloc_.alloc(length_ * sizeof(vari*)));\n      for (size_t i = 0; i < length_; i++)\n        mem_v[i] = inv(i).vi_;\n    } else {\n      mem_v = shared;\n    }\n  }\n\n  inline void initialize(double*& mem_d, const double* ind,\n                         double* shared = NULL) {\n    if (shared == NULL) {\n      mem_d = reinterpret_cast<double*>(\n          ChainableStack::memalloc_.alloc(length_ * sizeof(double)));\n      for (size_t i = 0; i < length_; i++)\n        mem_d[i] = ind[i];\n    } else {\n      mem_d = shared;\n    }\n  }\n  template <typename Derived>\n  inline void initialize(double*& mem_d, const Eigen::DenseBase<Derived>& ind,\n                         double* shared = NULL) {\n    if (shared == NULL) {\n      mem_d = reinterpret_cast<double*>(\n          ChainableStack::memalloc_.alloc(length_ * sizeof(double)));\n      for (size_t i = 0; i < length_; i++)\n        mem_d[i] = ind(i);\n    } else {\n      mem_d = shared;\n    }\n  }\n\n public:\n  dot_product_vari(typename dot_product_store_type<T1>::type v1,\n                   typename dot_product_store_type<T2>::type v2, size_t length)\n      : vari(var_dot(v1, v2, length)), v1_(v1), v2_(v2), length_(length) {}\n\n  dot_product_vari(const T1* v1, const T2* v2, size_t length,\n                   dot_product_vari<T1, T2>* shared_v1 = NULL,\n                   dot_product_vari<T1, T2>* shared_v2 = NULL)\n      : vari(var_dot(v1, v2, length)), length_(length) {\n    if (shared_v1 == NULL) {\n      initialize(v1_, v1);\n    } else {\n      initialize(v1_, v1, shared_v1->v1_);\n    }\n    if (shared_v2 == NULL) {\n      initialize(v2_, v2);\n    } else {\n      initialize(v2_, v2, shared_v2->v2_);\n    }\n  }\n  template <typename Derived1, typename Derived2>\n  dot_product_vari(const Eigen::DenseBase<Derived1>& v1,\n                   const Eigen::DenseBase<Derived2>& v2,\n                   dot_product_vari<T1, T2>* shared_v1 = NULL,\n                   dot_product_vari<T1, T2>* shared_v2 = NULL)\n      : vari(var_dot(v1, v2)), length_(v1.size()) {\n    if (shared_v1 == NULL) {\n      initialize(v1_, v1);\n    } else {\n      initialize(v1_, v1, shared_v1->v1_);\n    }\n    if (shared_v2 == NULL) {\n      initialize(v2_, v2);\n    } else {\n      initialize(v2_, v2, shared_v2->v2_);\n    }\n  }\n  template <int R1, int C1, int R2, int C2>\n  dot_product_vari(const Eigen::Matrix<T1, R1, C1>& v1,\n                   const Eigen::Matrix<T2, R2, C2>& v2,\n                   dot_product_vari<T1, T2>* shared_v1 = NULL,\n                   dot_product_vari<T1, T2>* shared_v2 = NULL)\n      : vari(var_dot(v1, v2)), length_(v1.size()) {\n    if (shared_v1 == NULL) {\n      initialize(v1_, v1);\n    } else {\n      initialize(v1_, v1, shared_v1->v1_);\n    }\n    if (shared_v2 == NULL) {\n      initialize(v2_, v2);\n    } else {\n      initialize(v2_, v2, shared_v2->v2_);\n    }\n  }\n  virtual void chain() { chain(v1_, v2_); }\n};\n}  // namespace\n\n/**\n * Returns the dot product.\n *\n * @param[in] v1 First column vector.\n * @param[in] v2 Second column vector.\n * @return Dot product of the vectors.\n * @throw std::domain_error if length of v1 is not equal to length of v2.\n */\ntemplate <typename T1, int R1, int C1, typename T2, int R2, int C2>\ninline typename boost::enable_if_c<\n    boost::is_same<T1, var>::value || boost::is_same<T2, var>::value, var>::type\ndot_product(const Eigen::Matrix<T1, R1, C1>& v1,\n            const Eigen::Matrix<T2, R2, C2>& v2) {\n  check_vector(\"dot_product\", \"v1\", v1);\n  check_vector(\"dot_product\", \"v2\", v2);\n  check_matching_sizes(\"dot_product\", \"v1\", v1, \"v2\", v2);\n  return var(new dot_product_vari<T1, T2>(v1, v2));\n}\n/**\n * Returns the dot product.\n *\n * @param[in] v1 First array.\n * @param[in] v2 Second array.\n * @param[in] length Length of both arrays.\n * @return Dot product of the arrays.\n */\ntemplate <typename T1, typename T2>\ninline typename boost::enable_if_c<\n    boost::is_same<T1, var>::value || boost::is_same<T2, var>::value, var>::type\ndot_product(const T1* v1, const T2* v2, size_t length) {\n  return var(new dot_product_vari<T1, T2>(v1, v2, length));\n}\n\n/**\n * Returns the dot product.\n *\n * @param[in] v1 First vector.\n * @param[in] v2 Second vector.\n * @return Dot product of the vectors.\n * @throw std::domain_error if sizes of v1 and v2 do not match.\n */\ntemplate <typename T1, typename T2>\ninline typename boost::enable_if_c<\n    boost::is_same<T1, var>::value || boost::is_same<T2, var>::value, var>::type\ndot_product(const std::vector<T1>& v1, const std::vector<T2>& v2) {\n  check_matching_sizes(\"dot_product\", \"v1\", v1, \"v2\", v2);\n  return var(new dot_product_vari<T1, T2>(&v1[0], &v2[0], v1.size()));\n}\n\n}  // namespace math\n}  // namespace stan\n#endif\n", "meta": {"hexsha": "cb8d93c5d7ce08bf2cbc9cf013808b96f6cc73a7", "size": 7595, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "stan/math/rev/mat/fun/dot_product.hpp", "max_stars_repo_name": "danluu/math", "max_stars_repo_head_hexsha": "a293807aadc0f0d57fa56fec70251ac70f1bd8c4", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "stan/math/rev/mat/fun/dot_product.hpp", "max_issues_repo_name": "danluu/math", "max_issues_repo_head_hexsha": "a293807aadc0f0d57fa56fec70251ac70f1bd8c4", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "stan/math/rev/mat/fun/dot_product.hpp", "max_forks_repo_name": "danluu/math", "max_forks_repo_head_hexsha": "a293807aadc0f0d57fa56fec70251ac70f1bd8c4", "max_forks_repo_licenses": ["BSD-3-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.5145228216, "max_line_length": 80, "alphanum_fraction": 0.6089532587, "num_tokens": 2301, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6757646140788307, "lm_q2_score": 0.49218813572079556, "lm_q1q2_score": 0.3326033255895426}}
{"text": "/*******************************************************************************\n *\n * Resolution of a system of linear constraints over the domain of intervals\n * is based on W. Harvey & P. J. Stuckey's paper: Improving linear constraint\n * propagation by changing constraint representation, in Constraints,\n * 8(2):173–207, 2003.\n *\n * Author: Arnaud J. Venet (arnaud.j.venet@nasa.gov)\n *\n * Contributors: Alexandre C. D. Wimmers (alexandre.c.wimmers@nasa.gov)\n *               Jorge Navas (jorge.navas@sri.com)\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 <map>\n#include <boost/optional.hpp>\n#include <crab/common/types.hpp>\n#include <crab/common/debug.hpp>\n#include <crab/common/stats.hpp>\n#include <crab/common/bignums.hpp>\n#include <crab/common/wrapint.hpp>\n#include <crab/domains/linear_constraints.hpp>\n\nnamespace ikos {\n\n  // Interval traits:\n  // The solver is parametric on the kind of Interval\n  namespace linear_interval_solver_impl {\n    // gamma(i) \\ gamma(j) \n    template<typename Interval>\n    inline Interval trim_interval(Interval i, Interval j);\n    \n    template<typename Interval, typename Number>\n    inline Interval mk_interval(Number n, typename crab::wrapint::bitwidth_t bitwidth) {\n      // default implementation ignores bitwidth\n      return Interval(n);\n    }\n    \n    template<typename Interval>\n    Interval lower_half_line(Interval i, bool is_signed);\n\n    template<typename Interval>\n    Interval upper_half_line(Interval i, bool is_signed);\n  } \n\n  template< typename Number, typename VariableName, typename IntervalCollection >\n  class linear_interval_solver {\n    \n  public:\n    typedef typename IntervalCollection::value_type Interval; \n    typedef variable< Number, VariableName > variable_t;\n    typedef linear_expression< Number, VariableName > linear_expression_t;\n    typedef linear_constraint< Number, VariableName > linear_constraint_t;\n    typedef linear_constraint_system< Number, VariableName > linear_constraint_system_t;\n    typedef typename variable_t::bitwidth_t bitwidth_t;\n    \n  private:\n    typedef std::vector< linear_constraint_t > cst_table_t;\n    typedef std::set< unsigned int > uint_set_t;\n    typedef std::map< variable_t, uint_set_t > trigger_table_t;\n    typedef typename linear_constraint_t::variable_set_t variable_set_t;\n\n  private:\n    class bottom_found { };\n\n  private:\n    std::size_t _max_cycles;\n    std::size_t _max_op;\n    bool _is_contradiction;\n    bool _is_large_system;\n    cst_table_t _cst_table;\n    trigger_table_t _trigger_table;\n    variable_set_t _refined_variables;\n    std::size_t _op_count;\n    \n  private:\n    static const std::size_t _large_system_cst_threshold = 3;\n    // cost of one propagation cycle for a dense 3x3 system of constraints \n    static const std::size_t _large_system_op_threshold = 27; \n\n  private:\n    void refine(variable_t v, Interval i, IntervalCollection& env) {\n      crab::ScopedCrabStats __st__(\"Linear Interval Solver.Solving refinement\");\n      CRAB_LOG(\"integer-solver\",\n\t       crab::outs() << \"\\tRefine \" << v << \" with \" << i << \"\\n\";);\n      Interval old_i = env[v];\n      Interval new_i = old_i & i;\n      CRAB_LOG(\"integer-solver\",\n\t       crab::outs() << \"\\tOld=\" << old_i << \" New=\" << new_i << \"\\n\";);\n      if (new_i.is_bottom()) {\n\tthrow bottom_found();\n      }\n      if (!(old_i == new_i)) {\n\tenv.set(v, new_i);\n\tthis->_refined_variables += v;\n\t++(this->_op_count);\n      }\n    }\n\n    Interval compute_residual(const linear_constraint_t &cst, variable_t pivot, \n                              IntervalCollection& env) {\n      crab::ScopedCrabStats __st__(\"Linear Interval Solver.Solving computing residual\");\n      namespace interval_traits = linear_interval_solver_impl;      \n      bitwidth_t w = pivot.get_bitwidth();\n      Interval residual= interval_traits::mk_interval<Interval>(cst.constant(), w);\n      for (typename linear_constraint_t::iterator it = cst.begin(); it != cst.end(); ++it) {\n\tvariable_t v = it->second;\n\tif (!(v == pivot)) {\n\t  residual = residual - (interval_traits::mk_interval<Interval>(it->first, w) * env[v]);\n\t  ++(this->_op_count);\n\t  if (residual.is_top()) break;\n\t}\n      }\n      return residual;\n    }\n    \n    void propagate(const linear_constraint_t &cst, IntervalCollection& env) {\n      crab::ScopedCrabStats __st__(\"Linear Interval Solver.Solving propagation\");\n      namespace interval_traits = linear_interval_solver_impl;\n\n      CRAB_LOG(\"integer-solver\",\n\t       linear_constraint_t tmp(cst);\n\t       crab::outs() << \"Integer solver processing \" << tmp << \"\\n\";);\n\t       \n      \n      for (typename linear_constraint_t::iterator it = cst.begin(), et = cst.end();\n\t   it != et; ++it) {\n\tNumber c = it->first;\n\tvariable_t pivot = it->second;\n\tInterval res = compute_residual(cst, pivot, env);\n\tInterval rhs = Interval::top();\n\tif (!res.is_top()) {\n\t  Interval ic = interval_traits::mk_interval<Interval>(c, pivot.get_bitwidth());\n\t  rhs = res / ic;\n\t}\n\t\n\tif (cst.is_equality()) {\n\t  refine(pivot, rhs, env);\n\t} else if (cst.is_inequality()) {\n\t  if (c > 0) {\n\t    refine(pivot, interval_traits::lower_half_line(rhs, cst.is_signed()), env);\n\t  } else {\n\t    refine(pivot, interval_traits::upper_half_line(rhs, cst.is_signed()), env);\n\t  }\n\t} else if (cst.is_strict_inequality()) {\n\t  // do nothing\n\t} else {\n\t  // cst is a disequation\n\t  Interval old_i = env[pivot];\n\t  Interval new_i = interval_traits::trim_interval(old_i, rhs);\n\t  if (new_i.is_bottom()) {\n\t    throw bottom_found();\n\t  }\n\t  if (!(old_i == new_i)) {\n\t    env.set(pivot, new_i);\n\t    this->_refined_variables += pivot;\n\t  }\n\t  ++(this->_op_count);\n\t}\n      }\n    }\n    \n    void solve_large_system(IntervalCollection& env) {\n      this->_op_count = 0;\n      this->_refined_variables.clear();\n      for (typename cst_table_t::iterator it = this->_cst_table.begin(); \n           it != this->_cst_table.end(); ++it) {\n\tthis->propagate(*it, env);\n      }\n      do {\n\tvariable_set_t vars_to_process(this->_refined_variables);\n\tthis->_refined_variables.clear();\n\tfor (typename variable_set_t::iterator it = vars_to_process.begin(); \n               it != vars_to_process.end(); ++it) {\n\t  uint_set_t& csts = this->_trigger_table[*it];\n\t  for (typename uint_set_t::iterator cst_it = csts.begin(); \n                 cst_it != csts.end(); ++cst_it) {\n\t    this->propagate(this->_cst_table.at(*cst_it), env);\n\t  }\n\t}\n      }\n      while (!this->_refined_variables.empty() && \n             this->_op_count <= this->_max_op);\n    }\n\n    void solve_small_system(IntervalCollection& env) {\n      std::size_t cycle = 0;\n      do {\n\t++cycle;\n\tthis->_refined_variables.clear();\n\tfor (typename cst_table_t::iterator it = this->_cst_table.begin(); \n               it != this->_cst_table.end(); ++it) {\n\t  this->propagate(*it, env);\n\t}\n      }\n      while (!this->_refined_variables.empty() &&  cycle <= this->_max_cycles);\n    }\n    \n    \n  public:\n\n    linear_interval_solver(const linear_constraint_system_t &csts, std::size_t max_cycles)\n      : _max_cycles(max_cycles), \n        _is_contradiction(false), \n        _is_large_system(false), \n        _op_count(0) {\n\n      crab::ScopedCrabStats __st_a__(\"Linear Interval Solver\");\n      crab::ScopedCrabStats __st_b__(\"Linear Interval Solver.Preprocessing\");      \n      std::size_t op_per_cycle = 0;\n      for (typename linear_constraint_system_t::iterator it = csts.begin(); \n           it != csts.end(); ++it) {\n\tconst linear_constraint_t &cst = *it;\n\tif (cst.is_contradiction()) {\n\t  this->_is_contradiction = true;\n\t  return;\n\t} else if (cst.is_tautology()) {\n\t  continue;\n\t} else {\n\t  std::size_t cst_size = cst.size();\n\t  if (cst.is_strict_inequality()) {\n\t    // convert e < c into {e <= c, e != c}\n\t    linear_constraint_t c1(cst.expression(), linear_constraint_t::kind_t::INEQUALITY);\n\t    linear_constraint_t c2(cst.expression(), linear_constraint_t::kind_t::DISEQUATION);\n\t    this->_cst_table.push_back(c1);\n\t    this->_cst_table.push_back(c2);\n\t    cst_size = c1.size() + c2.size();\n\t  } else {\n\t    this->_cst_table.push_back(cst);\n\t  }\n\t  // cost of one reduction step on the constraint in terms\n\t  // of accesses to the interval collection\n\t  op_per_cycle += cst_size * cst_size; \n\t}\n      }\n\n      this->_is_large_system = (this->_cst_table.size() > \n                                _large_system_cst_threshold) || \n          (op_per_cycle > _large_system_op_threshold);\n      \n      if (!this->_is_contradiction && this->_is_large_system) {\n\tthis->_max_op = op_per_cycle * max_cycles;\n\tfor (unsigned int i = 0; i < this->_cst_table.size(); ++i) {\n\t  const linear_constraint_t& cst = this->_cst_table.at(i);\n\t  variable_set_t vars = cst.variables();\n\t  for (typename variable_set_t::iterator it = vars.begin(); it != vars.end(); ++it) {\n\t    this->_trigger_table[*it].insert(i);\n\t  }\n\t}\n      }\n    }\n    \n    void run(IntervalCollection& env) {\n      crab::ScopedCrabStats __st_a__(\"Linear Interval Solver\");\n      crab::ScopedCrabStats __st_b__(\"Linear Interval Solver.Solving\");\n      if (this->_is_contradiction) {\n        env.set_to_bottom();\n      } else {\n        try {\n          if (this->_is_large_system) {\n\t    this->solve_large_system(env);\n          } else {\n            this->solve_small_system(env);\n          }\n        }\n        catch (bottom_found& e) {\n          env.set_to_bottom();\n        }\n      }\n    }\n    \n  }; // class linear_interval_solver\n\n} // namespace ikos\n\n", "meta": {"hexsha": "d4f587a2052d72e72b7c94ac0b6fd2b06b12d5a2", "size": 11335, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/crab/domains/linear_interval_solver.hpp", "max_stars_repo_name": "aziem/crab", "max_stars_repo_head_hexsha": "e150afd53d6fe49cefaade389542b3f3cfe9dbe5", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/crab/domains/linear_interval_solver.hpp", "max_issues_repo_name": "aziem/crab", "max_issues_repo_head_hexsha": "e150afd53d6fe49cefaade389542b3f3cfe9dbe5", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/crab/domains/linear_interval_solver.hpp", "max_forks_repo_name": "aziem/crab", "max_forks_repo_head_hexsha": "e150afd53d6fe49cefaade389542b3f3cfe9dbe5", "max_forks_repo_licenses": ["Apache-2.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.4469453376, "max_line_length": 92, "alphanum_fraction": 0.6648434054, "num_tokens": 2828, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6261241632752915, "lm_q2_score": 0.5312093733737563, "lm_q1q2_score": 0.33260302442763506}}
{"text": "#include \"Point3f.h\"\n#include <cmath>\n#include <sstream>\n#include <ostream>\n#include <cmath>\n#include \"Constants.h\"\n#include <boost/lexical_cast.hpp>\n\nnamespace ccmc\n{\n\t/**\n\t * @param out\n\t * @param point\n\t * @return\n\t */\n\tstd::ostream& operator<<(std::ostream& out, const Point3f& point)\n\t{\n\t\tout << point.toString();\n\t\treturn out;\n\t}\n\n\t/**\n\t * TODO: finish documentation\n\t * @param component1\n\t * @param component2\n\t * @param component3\n\t */\n\tPoint3f::Point3f(const float& component1, const float& component2, const float& component3)\n\t{\n\t\tthis->component1 = component1;\n\t\tthis->component2 = component2;\n\t\tthis->component3 = component3;\n\t\tcoordinates = Point3f::CARTESIAN;\n\t}\n\n\t/**\n\t * TODO: finish documentation\n\t * @param component1\n\t * @param component2\n\t * @param component3\n\t */\n\tPoint3f::Point3f(const float& component1, const float& component2, const float& component3, Coordinates c)\n\t{\n\t\tthis->component1 = component1;\n\t\tthis->component2 = component2;\n\t\tthis->component3 = component3;\n\t\tcoordinates = c;\n\t}\n\n\tPoint3f::Point3f(const Point3f& p)\n\t{\n\t\tthis->component1 = p.component1;\n\t\tthis->component2 = p.component2;\n\t\tthis->component3 = p.component3;\n\t\tcoordinates = p.coordinates;\n\t}\n\n\t/**\n\t * TODO: finish documentation\n\t */\n\tPoint3f::Point3f()\n\t{\n\t\tthis->component1 = 0.0;\n\t\tthis->component2 = 0.0;\n\t\tthis->component3 = 0.0;\n\t}\n\n\t/**\n\t * TODO: finish documentation\n\t */\n\tPoint3f::Point3f(Coordinates c)\n\t{\n\t\tthis->component1 = 0.0;\n\t\tthis->component2 = 0.0;\n\t\tthis->component3 = 0.0;\n\t\tcoordinates = c;\n\t}\n\n\t/**\n\t * TODO: finish documentation\n\t */\n\tPoint3f::~Point3f()\n\t{\n\n\t}\n\n\t/**\n\t * TODO: finish documentation\n\t */\n\tPoint3f Point3f::operator+(const Point3f& p) const\n\t{\n\t\tPoint3f point;\n\t\tpoint.component1 = component1 + p.component1;\n\t\tpoint.component2 = component2 + p.component2;\n\t\tpoint.component3 = component3 + p.component3;\n\t\tpoint.coordinates = p.coordinates;\n\n\t\treturn point;\n\t}\n\t/**\n\t * Minus operator where sender is on the right\n\t * TODO: test this\n\t */\n\tPoint3f Point3f::operator-(const Point3f& p) const\n\t{\n\t\tPoint3f point;\n\t\tpoint.component1 = component1 - p.component1;\n\t\tpoint.component2 = component2 - p.component2;\n\t\tpoint.component3 = component3 - p.component3;\n\t\tpoint.coordinates = p.coordinates;\n\n\t\treturn point;\n\t}\n\n\n\t/**\n\t * TODO: finish documentation\n\t */\n\tPoint3f Point3f::operator*(float value) const\n\t{\n\t\tPoint3f point;\n\t\tpoint.component1 = component1 * value;\n\t\tpoint.component2 = component2 * value;\n\t\tpoint.component3 = component3 * value;\n\t\tpoint.coordinates = coordinates;\n\t\treturn point;\n\t}\n\n\t/**\n\t * TODO: finish documentation\n\t */\n\tPoint3f Point3f::operator*(double value) const\n\t{\n\t\tPoint3f point;\n\t\tpoint.component1 = component1 * value;\n\t\tpoint.component2 = component2 * value;\n\t\tpoint.component3 = component3 * value;\n\t\tpoint.coordinates = coordinates;\n\t\treturn point;\n\t}\n\n\t/** compute the distance between this point, and Point p **/\n\t/**\n\t * TODO: finish documentation\n\t */\n\tfloat Point3f::distance(const Point3f& p) const\n\t{\n\t\tfloat dist;\n\n\t\tif (coordinates == Point3f::SPHERICAL)\n\t\t{\n\t\t\t//r p t\n\t\t\tfloat sinTheta1 = std::sin(ccmc::constants::DegreesToRadians*(90.f-component2));\n\t\t\tfloat cartesianComponent1 = component1 * sinTheta1 * std::cos(ccmc::constants::DegreesToRadians * component3);\n\t\t\tfloat cartesianComponent2 = component1 * sinTheta1 * std::sin(ccmc::constants::DegreesToRadians * component3);\n\t\t\tfloat cartesianComponent3 = component1 * std::cos(ccmc::constants::DegreesToRadians * (90.f - component2));\n\n\t\t\tfloat sinTheta2 = std::sin(ccmc::constants::DegreesToRadians*(90.f-p.component2));\n\t\t\tfloat pCartesianComponent1 = p.component1 * sinTheta1 * std::cos(ccmc::constants::DegreesToRadians * p.component3);\n\t\t\tfloat pCartesianComponent2 = p.component1 * sinTheta1 * std::sin(ccmc::constants::DegreesToRadians * p.component3);\n\t\t\tfloat pCartesianComponent3 = p.component1 * std::cos(ccmc::constants::DegreesToRadians * (90.f - p.component2));\n\n\n\t\t\tfloat diff1 = cartesianComponent1 - pCartesianComponent1;\n\t\t\tfloat diff2 = cartesianComponent2 - pCartesianComponent2;\n\t\t\tfloat diff3 = cartesianComponent3 - pCartesianComponent3;\n\n\t\t\tdist = std::sqrt(diff1 * diff1 + diff2 * diff2 + diff3 * diff3);\n\t\t} else\n\t\t{\n\t\t\tdist = std::sqrt((component1 - p.component1) * (component1 - p.component1) + (component2 - p.component2)\n\t\t\t\t\t* (component2 - p.component2) + (component3 - p.component3) * (component3 - p.component3));\n\t\t}\n\t\treturn dist;\n\t}\n\n\t/**\n\t * TODO: finish documentation\n\t */\n\tvoid Point3f::normalize()\n\t{\n\n\t\tfloat mag = magnitude();\n\t\tif (std::abs(mag - 0.0) > .0000001)\n\t\t{\n\t\t\tthis->component1 /= mag;\n\t\t\tthis->component2 /= mag;\n\t\t\tthis->component3 /= mag;\n\t\t}\n\t}\n\n\t/**\n\t * Computes the magnitude of the cartesian vector\n\t */\n\tfloat Point3f::magnitude()\n\t{\n\t\treturn sqrt(component1 * component1 + component2 * component2 + component3 * component3);\n\t}\n\n\t/**\n\t * TODO: finish documentation\n\t */\n\tstd::string Point3f::toString() const\n\t{\n/*\t\tstd::string beg = \"(\";\n\t\tstd::string mid = \",\";\n\t\tstd::string end = \")\";\n\t\tstd::ostringstream oss1;\n\t\toss1 << component1;\n\t\tstd::string scomponent1 = oss1.str();\n\t\tstd::ostringstream oss2;\n\t\toss2 << component2;\n\t\tstd::string scomponent2 = oss2.str();\n\t\tstd::ostringstream oss3;\n\t\toss3 << component3;\n\t\tstd::string scomponent3 = oss3.str();\n\t\tstd::string str = beg + scomponent1 + mid + scomponent2 + mid + scomponent3 + end;\n\t\treturn str;\n\t\t*/\n\t\tstd::string temp_string = \"\";\n\t\ttemp_string = \"(\" + boost::lexical_cast<std::string>(component1) + \",\";\n\t\ttemp_string += boost::lexical_cast<std::string>(component2) + \",\";\n\t\ttemp_string += boost::lexical_cast<std::string>(component3) + \")\";\n\t\treturn temp_string;\n\t}\n\n\t/**\n\t * TODO: finish documentation\n\t */\n\tvoid Point3f::setCoordinates(Point3f::Coordinates c)\n\t{\n\t\tcoordinates = c;\n\t}\n\n\t/**\n\t * TODO: finish documentation\n\t */\n\tPoint3f::Coordinates Point3f::getCoordinates()\n\t{\n\t\treturn coordinates;\n\t}\n\n\tPoint3f Point3f::getCartesian()\n\t{\n\t\tPoint3f cartesian;\n\t\tfloat sinTheta1 = std::sin(ccmc::constants::DegreesToRadians*(90.f-component2));\n\t\tcartesian.component1 = component1 * sinTheta1 * std::cos(ccmc::constants::DegreesToRadians * component3);\n\t\tcartesian.component2 = component1 * sinTheta1 * std::sin(ccmc::constants::DegreesToRadians * component3);\n\t\tcartesian.component3 = component1 * std::cos(ccmc::constants::DegreesToRadians * (90.f - component2));\n\t\treturn cartesian;\n\n\t}\n\n}\n", "meta": {"hexsha": "49ca6948cabf723164b209a9cd00011769b1e19d", "size": 6366, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ext/kameleon/src/ccmc/Point3f.cpp", "max_stars_repo_name": "alexanderbock/Kameleon-Converter", "max_stars_repo_head_hexsha": "6c2e66bfea60b17a369a3615bc1a623bba100a6f", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ext/kameleon/src/ccmc/Point3f.cpp", "max_issues_repo_name": "alexanderbock/Kameleon-Converter", "max_issues_repo_head_hexsha": "6c2e66bfea60b17a369a3615bc1a623bba100a6f", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ext/kameleon/src/ccmc/Point3f.cpp", "max_forks_repo_name": "alexanderbock/Kameleon-Converter", "max_forks_repo_head_hexsha": "6c2e66bfea60b17a369a3615bc1a623bba100a6f", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.9647058824, "max_line_length": 118, "alphanum_fraction": 0.6844172165, "num_tokens": 1824, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6548947290421275, "lm_q2_score": 0.5078118642792044, "lm_q1q2_score": 0.33256331326150723}}
{"text": "#include <math.h>\n#include <climits>\n#include <stdlib.h>     /* srand, rand */\n\n#ifndef _WIN32\n#include <pwd.h>\n#include <unistd.h>\n#include <getopt.h>\n#else\n#include <stdlib.h>\n#include <stdio.h>\n#endif\n\n#include <Eigen/Dense>\n#include <Eigen/Geometry>\n\n#include \"pinocchio/algorithm/joint-configuration.hpp\"\n\n#include \"jiminy/core/Utilities.h\"\n#include \"jiminy/core/Engine.h\"     // MIN_SIMULATION_TIMESTEP and MAX_SIMULATION_TIMESTEP\n\n\nnamespace jiminy\n{\n    extern float64_t const MIN_SIMULATION_TIMESTEP;\n    extern float64_t const MAX_SIMULATION_TIMESTEP;\n\n    // *************** Local Mutex/Lock mechanism ******************\n\n    MutexLocal::MutexLocal(void) :\n    isLocked_(new bool_t{false})\n    {\n        // Empty\n    }\n\n    MutexLocal::~MutexLocal(void)\n    {\n        *isLocked_ = false;\n    }\n\n    bool_t const & MutexLocal::isLocked(void) const\n    {\n        return *isLocked_;\n    }\n\n    MutexLocal::LockGuardLocal::LockGuardLocal(MutexLocal & mutexLocal) :\n    mutexFlag_(mutexLocal.isLocked_)\n    {\n        *mutexFlag_ = true;\n    }\n\n    MutexLocal::LockGuardLocal::~LockGuardLocal(void)\n    {\n        *mutexFlag_ = false;\n    }\n\n    // ************************* Timer **************************\n\n    Timer::Timer(void) :\n    t0(),\n    tf(),\n    dt(0)\n    {\n        tic();\n    }\n\n    void Timer::tic(void)\n    {\n        t0 = Time::now();\n    }\n\n    void Timer::toc(void)\n    {\n        tf = Time::now();\n        std::chrono::duration<float64_t> timeDiff = tf - t0;\n        dt = timeDiff.count();\n    }\n\n    // ************ IO file and Directory utilities **************\n\n    #ifndef _WIN32\n    std::string getUserDirectory(void)\n    {\n        struct passwd *pw = getpwuid(getuid());\n        return pw->pw_dir;\n    }\n    #else\n    std::string getUserDirectory(void)\n    {\n        return {getenv(\"USERPROFILE\")};\n    }\n    #endif\n\n    // ***************** Random number generator *****************\n    // Based on Ziggurat generator by Marsaglia and Tsang (JSS, 2000)\n\n    std::mt19937 generator_;\n    std::uniform_real_distribution<float32_t> distUniform_(0.0,1.0);\n\n    uint32_t kn[128];\n    float32_t fn[128];\n    float32_t wn[128];\n\n    void r4_nor_setup(void)\n    {\n        float64_t const m1 = 2147483648.0;\n        float64_t const vn = 9.91256303526217E-03;\n        float64_t dn = 3.442619855899;\n        float64_t tn = 3.442619855899;\n\n        float64_t q = vn / exp (-0.5 * dn * dn);\n\n        kn[0] = (uint32_t) ((dn / q) * m1);\n        kn[1] = 0;\n\n        wn[0] = static_cast<float32_t>(q / m1);\n        wn[127] = static_cast<float32_t>(dn / m1);\n\n        fn[0] = 1.0f;\n        fn[127] = static_cast<float32_t>(exp(-0.5 * dn * dn));\n\n        for (uint8_t i=126; 1 <= i; i--)\n        {\n            dn = sqrt (-2.0 * log(vn / dn + exp(-0.5 * dn * dn)));\n            kn[i+1] = static_cast<uint32_t>((dn / tn) * m1);\n            tn = dn;\n            fn[i] = static_cast<float32_t>(exp(-0.5 * dn * dn));\n            wn[i] = static_cast<float32_t>(dn / m1);\n        }\n    }\n\n    float32_t r4_uni(void)\n    {\n        return distUniform_(generator_);\n    }\n\n    float32_t r4_nor(void)\n    {\n        float32_t const r = 3.442620f;\n        int32_t hz;\n        uint32_t iz;\n        float32_t x;\n        float32_t y;\n\n        hz = static_cast<int32_t>(generator_());\n        iz = (hz & 127U);\n\n        if (fabs(hz) < kn[iz])\n        {\n            return static_cast<float32_t>(hz) * wn[iz];\n        }\n        else\n        {\n            while(true)\n            {\n                if (iz == 0)\n                {\n                    while(true)\n                    {\n                        x = - 0.2904764f * log(r4_uni());\n                        y = - log(r4_uni());\n                        if (x * x <= y + y)\n                        {\n                            break;\n                        }\n                    }\n\n                    if (hz <= 0)\n                    {\n                        return - r - x;\n                    }\n                    else\n                    {\n                        return + r + x;\n                    }\n                }\n\n                x = static_cast<float32_t>(hz) * wn[iz];\n\n                if (fn[iz] + r4_uni() * (fn[iz-1] - fn[iz]) < exp (-0.5f * x * x))\n                {\n                    return x;\n                }\n\n                hz = static_cast<int32_t>(generator_());\n                iz = (hz & 127);\n\n                if (fabs(hz) < kn[iz])\n                {\n                    return static_cast<float32_t>(hz) * wn[iz];\n                }\n            }\n        }\n    }\n\n    // ************** Random number generator utilities ****************\n\n\tvoid resetRandGenerators(uint32_t seed)\n\t{\n\t\tsrand(seed); // Eigen relies on srand for genering random matrix\n        generator_.seed(seed);\n        r4_nor_setup();\n\t}\n\n\tfloat64_t randUniform(float64_t const & lo,\n\t                      float64_t const & hi)\n    {\n        return lo + r4_uni() * (hi - lo);\n    }\n\n\tfloat64_t randNormal(float64_t const & mean,\n\t                     float64_t const & std)\n    {\n        return mean + r4_nor() * std;\n    }\n\n    vectorN_t randVectorNormal(uint32_t  const & size,\n                               float64_t const & mean,\n                               float64_t const & std)\n    {\n        if (std > 0.0)\n        {\n            return vectorN_t::NullaryExpr(size,\n            [&mean, &std] (vectorN_t::Index const &) -> float64_t\n            {\n                return randNormal(mean, std);\n            });\n        }\n        else\n        {\n            return vectorN_t::Constant(size, mean);\n        }\n    }\n\n    vectorN_t randVectorNormal(uint32_t  const & size,\n                               float64_t const & std)\n    {\n        return randVectorNormal(size, 0, std);\n    }\n\n    vectorN_t randVectorNormal(vectorN_t const & mean,\n                               vectorN_t const & std)\n    {\n        return vectorN_t::NullaryExpr(std.size(),\n        [&mean, &std] (vectorN_t::Index const & i) -> float64_t\n        {\n            return randNormal(mean[i], std[i]);\n        });\n    }\n\n    vectorN_t randVectorNormal(vectorN_t const & std)\n    {\n        return vectorN_t::NullaryExpr(std.size(),\n        [&std] (vectorN_t::Index const & i) -> float64_t\n        {\n            return randNormal(0, std[i]);\n        });\n    }\n\n    // ******************* Telemetry utilities **********************\n\n    std::vector<std::string> defaultVectorFieldnames(std::string const & baseName,\n                                                     uint32_t    const & size)\n    {\n        std::vector<std::string> fieldnames;\n        fieldnames.reserve(size);\n        for (uint32_t i=0; i<size; i++)\n        {\n            fieldnames.emplace_back(baseName + std::to_string(i)); // TODO: MR going to support \".\" delimiter\n        }\n        return fieldnames;\n    }\n\n\n    std::string removeFieldnameSuffix(std::string         fieldname,\n                                      std::string const & suffix)\n    {\n        if (fieldname.size() > suffix.size())\n        {\n            if (!fieldname.compare(fieldname.size() - suffix.size(), suffix.size(), suffix))\n            {\n                fieldname.erase(fieldname.size() - suffix.size(), fieldname.size());\n            }\n        }\n        return fieldname;\n    }\n\n    std::vector<std::string> removeFieldnamesSuffix(std::vector<std::string>         fieldnames,\n                                                    std::string              const & suffix)\n    {\n        std::transform(fieldnames.begin(), fieldnames.end(), fieldnames.begin(),\n        [&suffix](std::string const & name) -> std::string\n        {\n            return removeFieldnameSuffix(name, suffix);\n        });\n        return fieldnames;\n    }\n\n    // ********************** Pinocchio utilities **********************\n\n    void computePositionDerivative(pinocchio::Model            const & model,\n                                   Eigen::Ref<vectorN_t const>         q,\n                                   Eigen::Ref<vectorN_t const>         v,\n                                   Eigen::Ref<vectorN_t>               qDot,\n                                   float64_t                           dt)\n    {\n        /* Hack to compute the configuration vector derivative, including the\n           quaternions on SO3 automatically. Note that the time difference must\n           not be too small to avoid failure. */\n\n        dt = std::max(MIN_SIMULATION_TIMESTEP, dt);\n        vectorN_t qNext(q.size());\n        pinocchio::integrate(model, q, v*dt, qNext);\n        qDot = (qNext - q) / dt;\n    }\n\n    result_t getJointNameFromPositionId(pinocchio::Model const & model,\n                                        int32_t          const & idIn,\n                                        std::string            & jointNameOut)\n    {\n        // Iterate over all joints.\n        for (int32_t i = 0; i < model.njoints; i++)\n        {\n            // Get joint starting and ending index in position vector.\n            int32_t startIndex = model.joints[i].idx_q();\n            int32_t endIndex = startIndex + model.joints[i].nq();\n\n            // If inIn is between start and end, we found the joint we were looking for.\n            if(startIndex <= idIn && endIndex > idIn)\n            {\n                jointNameOut = model.names[i];\n                return result_t::SUCCESS;\n            }\n        }\n\n        std::cout << \"Error - Utilities::getJointNameFromVelocityId - Position index out of range.\" << std::endl;\n        return result_t::ERROR_BAD_INPUT;\n    }\n\n    result_t getJointNameFromVelocityId(pinocchio::Model const & model,\n                                        int32_t          const & idIn,\n                                        std::string            & jointNameOut)\n    {\n        // Iterate over all joints.\n        for(int32_t i = 0; i < model.njoints; i++)\n        {\n            // Get joint starting and ending index in velocity vector.\n            int32_t startIndex = model.joints[i].idx_v();\n            int32_t endIndex = startIndex + model.joints[i].nv();\n\n            // If inIn is between start and end, we found the joint we were looking for.\n            if(startIndex <= idIn && endIndex > idIn)\n            {\n                jointNameOut = model.names[i];\n                return result_t::SUCCESS;\n            }\n        }\n\n        std::cout << \"Error - Utilities::getJointNameFromVelocityId - Velocity index out of range.\" << std::endl;\n        return result_t::ERROR_BAD_INPUT;\n    }\n\n    result_t getJointTypeFromId(pinocchio::Model const & model,\n                                int32_t          const & idIn,\n                                joint_t                & jointTypeOut)\n    {\n        if(model.njoints < idIn - 1)\n        {\n            std::cout << \"Error - Utilities::getJointTypeFromId - Joint id out of range.\" << std::endl;\n            return result_t::ERROR_GENERIC;\n        }\n\n        auto const & joint = model.joints[idIn];\n\n        if (joint.shortname() == \"JointModelFreeFlyer\")\n        {\n            jointTypeOut = joint_t::FREE;\n        }\n        else if (joint.shortname() == \"JointModelSpherical\")\n        {\n            jointTypeOut = joint_t::SPHERICAL;\n        }\n        else if (joint.shortname() == \"JointModelPlanar\")\n        {\n            jointTypeOut = joint_t::PLANAR;\n        }\n        else if (joint.shortname() == \"JointModelPX\" ||\n                    joint.shortname() == \"JointModelPY\" ||\n                    joint.shortname() == \"JointModelPZ\")\n        {\n            jointTypeOut = joint_t::LINEAR;\n        }\n        else if (joint.shortname() == \"JointModelRX\" ||\n                    joint.shortname() == \"JointModelRY\" ||\n                    joint.shortname() == \"JointModelRZ\")\n        {\n            jointTypeOut = joint_t::ROTARY;\n        }\n        else\n        {\n            // Unknown joint, throw an error to avoid any wrong manipulation.\n            jointTypeOut = joint_t::NONE;\n            std::cout << \"Error - Utilities::getJointTypeFromId - Unknown joint type.\" << std::endl;\n            return result_t::ERROR_GENERIC;\n        }\n\n        return result_t::SUCCESS;\n    }\n\n    result_t getJointTypePositionSuffixes(joint_t                  const & jointTypeIn,\n                                          std::vector<std::string>       & jointTypeSuffixesOut)\n    {\n        jointTypeSuffixesOut = std::vector<std::string>({std::string(\"\")}); // If no extra discrimination is needed\n        switch (jointTypeIn)\n        {\n        case joint_t::LINEAR:\n            break;\n        case joint_t::ROTARY:\n            break;\n        case joint_t::PLANAR:\n            jointTypeSuffixesOut = std::vector<std::string>({std::string(\"TransX\"),\n                                                             std::string(\"TransY\"),\n                                                             std::string(\"TransZ\")});\n            break;\n        case joint_t::SPHERICAL:\n            jointTypeSuffixesOut = std::vector<std::string>({std::string(\"QuatX\"),\n                                                             std::string(\"QuatY\"),\n                                                             std::string(\"QuatZ\"),\n                                                             std::string(\"QuatW\")});\n            break;\n        case joint_t::FREE:\n            jointTypeSuffixesOut = std::vector<std::string>({std::string(\"TransX\"),\n                                                             std::string(\"TransY\"),\n                                                             std::string(\"TransZ\"),\n                                                             std::string(\"QuatX\"),\n                                                             std::string(\"QuatY\"),\n                                                             std::string(\"QuatZ\"),\n                                                             std::string(\"QuatW\")});\n            break;\n        case joint_t::NONE:\n        default:\n            std::cout << \"Error - Utilities::getJointFieldnamesFromType - Joints of type 'NONE' do not have fieldnames.\" << std::endl;\n            return result_t::ERROR_GENERIC;\n        }\n\n        return result_t::SUCCESS;\n    }\n\n    result_t getJointTypeVelocitySuffixes(joint_t                  const & jointTypeIn,\n                                          std::vector<std::string>       & jointTypeSuffixesOut)\n    {\n        jointTypeSuffixesOut = std::vector<std::string>({std::string(\"\")}); // If no extra discrimination is needed\n        switch (jointTypeIn)\n        {\n        case joint_t::LINEAR:\n            break;\n        case joint_t::ROTARY:\n            break;\n        case joint_t::PLANAR:\n            jointTypeSuffixesOut = std::vector<std::string>({std::string(\"LinX\"),\n                                                             std::string(\"LinY\"),\n                                                             std::string(\"LinZ\")});\n            break;\n        case joint_t::SPHERICAL:\n            jointTypeSuffixesOut = std::vector<std::string>({std::string(\"AngX\"),\n                                                             std::string(\"AngY\"),\n                                                             std::string(\"AngZ\")});\n            break;\n        case joint_t::FREE:\n            jointTypeSuffixesOut = std::vector<std::string>({std::string(\"LinX\"),\n                                                             std::string(\"LinY\"),\n                                                             std::string(\"LinZ\"),\n                                                             std::string(\"AngX\"),\n                                                             std::string(\"AngY\"),\n                                                             std::string(\"AngZ\")});\n            break;\n        case joint_t::NONE:\n        default:\n            std::cout << \"Error - Utilities::getJointFieldnamesFromType - Joints of type 'NONE' do not have fieldnames.\" << std::endl;\n            return result_t::ERROR_GENERIC;\n        }\n\n        return result_t::SUCCESS;\n    }\n\n    result_t getFrameIdx(pinocchio::Model const & model,\n                         std::string      const & frameName,\n                         int32_t                & frameIdx)\n    {\n        if (!model.existFrame(frameName))\n        {\n            std::cout << \"Error - Utilities::getFrameIdx - Frame not found in urdf.\" << std::endl;\n            return result_t::ERROR_BAD_INPUT;\n        }\n\n        frameIdx = model.getFrameId(frameName);\n\n        return result_t::SUCCESS;\n    }\n\n    result_t getFramesIdx(pinocchio::Model         const & model,\n                          std::vector<std::string> const & framesNames,\n                          std::vector<int32_t>           & framesIdx)\n    {\n        result_t returnCode = result_t::SUCCESS;\n\n        framesIdx.resize(0);\n        for (std::string const & name : framesNames)\n        {\n            if (returnCode == result_t::SUCCESS)\n            {\n                int32_t idx;\n                returnCode = getFrameIdx(model, name, idx);\n                framesIdx.push_back(std::move(idx));\n            }\n        }\n\n        return returnCode;\n    }\n\n    result_t getJointPositionIdx(pinocchio::Model     const & model,\n                                 std::string          const & jointName,\n                                 std::vector<int32_t>       & jointPositionIdx)\n    {\n        // It returns all the indices if the joint has multiple degrees of freedom\n\n        if (!model.existJointName(jointName))\n        {\n            std::cout << \"Error - Utilities::getJointPositionIdx - Joint not found in urdf.\" << std::endl;\n            return result_t::ERROR_BAD_INPUT;\n        }\n\n        int32_t const & jointModelIdx = model.getJointId(jointName);\n        int32_t const & jointPositionFirstIdx = model.joints[jointModelIdx].idx_q();\n        int32_t const & jointNq = model.joints[jointModelIdx].nq();\n        jointPositionIdx.resize(jointNq);\n        std::iota(jointPositionIdx.begin(), jointPositionIdx.end(), jointPositionFirstIdx);\n\n        return result_t::SUCCESS;\n    }\n\n    result_t getJointPositionIdx(pinocchio::Model const & model,\n                                 std::string      const & jointName,\n                                 int32_t                & jointPositionFirstIdx)\n    {\n        // It returns the first index even if the joint has multiple degrees of freedom\n\n        if (!model.existJointName(jointName))\n        {\n            std::cout << \"Error - Utilities::getJointPositionIdx - Joint not found in urdf.\" << std::endl;\n            return result_t::ERROR_BAD_INPUT;\n        }\n\n        int32_t const & jointModelIdx = model.getJointId(jointName);\n        jointPositionFirstIdx = model.joints[jointModelIdx].idx_q();\n\n        return result_t::SUCCESS;\n    }\n\n    result_t getJointsPositionIdx(pinocchio::Model         const & model,\n                                  std::vector<std::string> const & jointsNames,\n                                  std::vector<int32_t>           & jointsPositionIdx,\n                                  bool_t                   const & firstJointIdxOnly)\n    {\n        result_t returnCode = result_t::SUCCESS;\n\n        jointsPositionIdx.clear();\n        if (!firstJointIdxOnly)\n        {\n            std::vector<int32_t> jointPositionIdx;\n            for (std::string const & jointName : jointsNames)\n            {\n                if (returnCode == result_t::SUCCESS)\n                {\n                    returnCode = getJointPositionIdx(model, jointName, jointPositionIdx);\n                }\n                if (returnCode == result_t::SUCCESS)\n                {\n                    jointsPositionIdx.insert(jointsPositionIdx.end(), jointPositionIdx.begin(), jointPositionIdx.end());\n                }\n            }\n        }\n        else\n        {\n            int32_t jointPositionIdx;\n            for (std::string const & jointName : jointsNames)\n            {\n                if (returnCode == result_t::SUCCESS)\n                {\n                    returnCode = getJointPositionIdx(model, jointName, jointPositionIdx);\n                }\n                if (returnCode == result_t::SUCCESS)\n                {\n                    jointsPositionIdx.push_back(jointPositionIdx);\n                }\n            }\n        }\n\n        return returnCode;\n    }\n\n    result_t getJointModelIdx(pinocchio::Model const & model,\n                              std::string      const & jointName,\n                              int32_t                & jointModelIdx)\n    {\n        // It returns the first index even if the joint has multiple degrees of freedom\n\n        if (!model.existJointName(jointName))\n        {\n            std::cout << \"Error - Utilities::getJointPositionIdx - Joint not found in urdf.\" << std::endl;\n            return result_t::ERROR_BAD_INPUT;\n        }\n\n        jointModelIdx = model.getJointId(jointName);\n\n        return result_t::SUCCESS;\n    }\n\n    result_t getJointsModelIdx(pinocchio::Model         const & model,\n                               std::vector<std::string> const & jointsNames,\n                               std::vector<int32_t>           & jointsModelIdx)\n    {\n        result_t returnCode = result_t::SUCCESS;\n\n        jointsModelIdx.clear();\n        int32_t jointModelIdx;\n        for (std::string const & jointName : jointsNames)\n        {\n            if (returnCode == result_t::SUCCESS)\n            {\n                returnCode = getJointModelIdx(model, jointName, jointModelIdx);\n            }\n            if (returnCode == result_t::SUCCESS)\n            {\n                jointsModelIdx.push_back(jointModelIdx);\n            }\n        }\n\n        return returnCode;\n    }\n\n    result_t getJointVelocityIdx(pinocchio::Model     const & model,\n                                 std::string          const & jointName,\n                                 std::vector<int32_t>       & jointVelocityIdx)\n    {\n        // It returns all the indices if the joint has multiple degrees of freedom\n\n        if (!model.existJointName(jointName))\n        {\n            std::cout << \"Error - getJointVelocityIdx - Frame not found in urdf.\" << std::endl;\n            return result_t::ERROR_BAD_INPUT;\n        }\n\n        int32_t const & jointModelIdx = model.getJointId(jointName);\n        int32_t const & jointVelocityFirstIdx = model.joints[jointModelIdx].idx_v();\n        int32_t const & jointNv = model.joints[jointModelIdx].nv();\n        jointVelocityIdx.resize(jointNv);\n        std::iota(jointVelocityIdx.begin(), jointVelocityIdx.end(), jointVelocityFirstIdx);\n\n        return result_t::SUCCESS;\n    }\n\n    result_t getJointVelocityIdx(pinocchio::Model const & model,\n                                 std::string      const & jointName,\n                                 int32_t                & jointVelocityFirstIdx)\n    {\n        // It returns the first index even if the joint has multiple degrees of freedom\n\n        if (!model.existJointName(jointName))\n        {\n            std::cout << \"Error - getJointVelocityIdx - Frame not found in urdf.\" << std::endl;\n            return result_t::ERROR_BAD_INPUT;\n        }\n\n        int32_t const & jointModelIdx = model.getJointId(jointName);\n        jointVelocityFirstIdx = model.joints[jointModelIdx].idx_v();\n\n        return result_t::SUCCESS;\n    }\n\n    result_t getJointsVelocityIdx(pinocchio::Model         const & model,\n                                  std::vector<std::string> const & jointsNames,\n                                  std::vector<int32_t>           & jointsVelocityIdx,\n                                  bool_t                   const & firstJointIdxOnly)\n    {\n        result_t returnCode = result_t::SUCCESS;\n\n        jointsVelocityIdx.clear();\n        if (!firstJointIdxOnly)\n        {\n            std::vector<int32_t> jointVelocityIdx;\n            for (std::string const & jointName : jointsNames)\n            {\n                if (returnCode == result_t::SUCCESS)\n                {\n                    returnCode = getJointVelocityIdx(model, jointName, jointVelocityIdx);\n                }\n                if (returnCode == result_t::SUCCESS)\n                {\n                    jointsVelocityIdx.insert(jointsVelocityIdx.end(), jointVelocityIdx.begin(), jointVelocityIdx.end());\n                }\n            }\n        }\n        else\n        {\n            int32_t jointVelocityIdx;\n            for (std::string const & jointName : jointsNames)\n            {\n                if (returnCode == result_t::SUCCESS)\n                {\n                    returnCode = getJointVelocityIdx(model, jointName, jointVelocityIdx);\n                }\n                if (returnCode == result_t::SUCCESS)\n                {\n                    jointsVelocityIdx.push_back(jointVelocityIdx);\n                }\n            }\n        }\n\n        return returnCode;\n    }\n\n    void switchJoints(pinocchio::Model       & modelInOut,\n                      uint32_t         const & firstJointId,\n                      uint32_t         const & secondJointId)\n    {\n        // Only perform swap if firstJointId is less that secondJointId\n        if (firstJointId < secondJointId)\n        {\n            // Update parents for other joints.\n            for(uint32_t i = 0; i < modelInOut.parents.size(); i++)\n            {\n                if(firstJointId == modelInOut.parents[i])\n                {\n                    modelInOut.parents[i] = secondJointId;\n                }\n                else if(secondJointId == modelInOut.parents[i])\n                {\n                    modelInOut.parents[i] = firstJointId;\n                }\n            }\n            // Update frame parents.\n            for(uint32_t i = 0; i < modelInOut.frames.size(); i++)\n            {\n                if(firstJointId == modelInOut.frames[i].parent)\n                {\n                    modelInOut.frames[i].parent = secondJointId;\n                }\n                else if(secondJointId == modelInOut.frames[i].parent)\n                {\n                    modelInOut.frames[i].parent = firstJointId;\n                }\n            }\n            // Update values in subtrees.\n            for(uint32_t i = 0; i < modelInOut.subtrees.size(); i++)\n            {\n                for(uint32_t j = 0; j < modelInOut.subtrees[i].size(); j++)\n                {\n                    if(firstJointId == modelInOut.subtrees[i][j])\n                    {\n                        modelInOut.subtrees[i][j] = secondJointId;\n                    }\n                    else if(secondJointId == modelInOut.subtrees[i][j])\n                    {\n                        modelInOut.subtrees[i][j] = firstJointId;\n                    }\n                }\n            }\n\n            // Update vectors based on joint index: effortLimit, velocityLimit,\n            // lowerPositionLimit and upperPositionLimit.\n            swapVectorBlocks(modelInOut.effortLimit,\n                             modelInOut.joints[firstJointId].idx_v(),\n                             modelInOut.joints[firstJointId].nv(),\n                             modelInOut.joints[secondJointId].idx_v(),\n                             modelInOut.joints[secondJointId].nv());\n            swapVectorBlocks(modelInOut.velocityLimit,\n                             modelInOut.joints[firstJointId].idx_v(),\n                             modelInOut.joints[firstJointId].nv(),\n                             modelInOut.joints[secondJointId].idx_v(),\n                             modelInOut.joints[secondJointId].nv());\n\n            swapVectorBlocks(modelInOut.lowerPositionLimit,\n                             modelInOut.joints[firstJointId].idx_q(),\n                             modelInOut.joints[firstJointId].nq(),\n                             modelInOut.joints[secondJointId].idx_q(),\n                             modelInOut.joints[secondJointId].nq());\n            swapVectorBlocks(modelInOut.upperPositionLimit,\n                             modelInOut.joints[firstJointId].idx_q(),\n                             modelInOut.joints[firstJointId].nq(),\n                             modelInOut.joints[secondJointId].idx_q(),\n                             modelInOut.joints[secondJointId].nq());\n\n            // Switch elements in joint-indexed vectors:\n            // parents, names, subtrees, joints, jointPlacements, inertias.\n            uint32_t tempParent = modelInOut.parents[firstJointId];\n            modelInOut.parents[firstJointId] = modelInOut.parents[secondJointId];\n            modelInOut.parents[secondJointId] = tempParent;\n\n            std::string tempName = modelInOut.names[firstJointId];\n            modelInOut.names[firstJointId] = modelInOut.names[secondJointId];\n            modelInOut.names[secondJointId] = tempName;\n\n            std::vector<pinocchio::Index> tempSubtree = modelInOut.subtrees[firstJointId];\n            modelInOut.subtrees[firstJointId] = modelInOut.subtrees[secondJointId];\n            modelInOut.subtrees[secondJointId] = tempSubtree;\n\n            pinocchio::JointModel jointTemp = modelInOut.joints[firstJointId];\n            modelInOut.joints[firstJointId] = modelInOut.joints[secondJointId];\n            modelInOut.joints[secondJointId] = jointTemp;\n\n            pinocchio::SE3 tempPlacement = modelInOut.jointPlacements[firstJointId];\n            modelInOut.jointPlacements[firstJointId] = modelInOut.jointPlacements[secondJointId];\n            modelInOut.jointPlacements[secondJointId] = tempPlacement;\n\n            pinocchio::Inertia tempInertia = modelInOut.inertias[firstJointId];\n            modelInOut.inertias[firstJointId] = modelInOut.inertias[secondJointId];\n            modelInOut.inertias[secondJointId] = tempInertia;\n\n            /* Recompute all position and velocity indexes, as we may have\n               switched joints that didn't have the same size.\n               Skip 'universe' joint since it is not an actual joint. */\n            uint32_t incrementalNq = 0;\n            uint32_t incrementalNv = 0;\n            for(uint32_t i = 1; i < modelInOut.joints.size(); i++)\n            {\n                modelInOut.joints[i].setIndexes(i, incrementalNq, incrementalNv);\n                incrementalNq += modelInOut.joints[i].nq();\n                incrementalNv += modelInOut.joints[i].nv();\n            }\n        }\n    }\n\n    result_t insertFlexibilityInModel(pinocchio::Model       & modelInOut,\n                                      std::string      const & childJointNameIn,\n                                      std::string      const & newJointNameIn)\n    {\n        if(!modelInOut.existJointName(childJointNameIn))\n        {\n            std::cout << \"Error - insertFlexibilityInModel - Child joint does not exist.\" << std::endl;\n            return result_t::ERROR_GENERIC;\n        }\n\n        int32_t childId = modelInOut.getJointId(childJointNameIn);\n        // Flexible joint is placed at the same position as the child joint, in its parent frame.\n        pinocchio::SE3 jointPosition = modelInOut.jointPlacements[childId];\n\n        // Create joint.\n        int32_t newId = modelInOut.addJoint(modelInOut.parents[childId],\n                                            pinocchio::JointModelSpherical(),\n                                            jointPosition,\n                                            newJointNameIn);\n\n        // Set child joint to be a child of the new joint, at the origin.\n        modelInOut.parents[childId] = newId;\n        modelInOut.jointPlacements[childId] = pinocchio::SE3::Identity();\n\n        // Add new joint to frame list.\n        int32_t childFrameId = modelInOut.getFrameId(childJointNameIn);\n        int32_t newFrameId = modelInOut.addJointFrame(newId, modelInOut.frames[childFrameId].previousFrame);\n\n        // Update child joint previousFrame id.\n        modelInOut.frames[childFrameId].previousFrame = newFrameId;\n\n        // Update new joint subtree to include all the joints below it.\n        for(uint32_t i = 0; i < modelInOut.subtrees[childId].size(); i++)\n        {\n            modelInOut.subtrees[newId].push_back(modelInOut.subtrees[childId][i]);\n        }\n\n        /* Add weightless body.\n            In practice having a zero inertia makes some of pinocchio algorithm crash,\n            so we set a very small value instead: 1g. */\n        std::string bodyName = newJointNameIn + \"Body\";\n        pinocchio::Inertia inertia = pinocchio::Inertia::Identity();\n        inertia.mass() *= 1.0e-3;\n        inertia.FromEllipsoid(inertia.mass(), 1.0, 1.0, 1.0);\n        modelInOut.appendBodyToJoint(newId, inertia, pinocchio::SE3::Identity());\n\n        /* Pinocchio requires that joints are in increasing order as we move to the\n            leaves of the kinematic tree. Here this is no longer the case, as an\n            intermediate joint was appended at the end. We put back this joint at the\n            correct position, by doing successive permutations. */\n        for(int32_t i = childId; i < newId; i++)\n        {\n            switchJoints(modelInOut, i, newId);\n        }\n\n        return result_t::SUCCESS;\n    }\n\n    // ********************** Math utilities *************************\n\n    ///////////////////////////////////////////////////////////////////////////////////////////////\n    ///\n    /// \\brief      Continuously differentiable piecewise-defined saturation function. More\n    ///             precisely, it consists in adding fillets at the two discontinuous points:\n    ///             - It is perfectly linear for `uc` between `-bevelStart` and `bevelStart`.\n    ///             - It is  perfectly constant equal to mi (resp. ma) for `uc` lower than\n    ///               `-bevelStop` (resp. higher than `-bevelStop`).\n    ///             - Then, two arcs of a circle connect those two modes continuously between\n    ///             `bevelStart` and `bevelStop` (resp. `-bevelStop` and `-bevelStart`).\n    ///             See the implementation for details about how `uc`, `bevelStart` and `bevelStop`\n    ///             are computed.\n    ///\n    ///////////////////////////////////////////////////////////////////////////////////////////////\n    float64_t saturateSoft(float64_t const & in,\n                           float64_t const & mi,\n                           float64_t const & ma,\n                           float64_t const & r)\n    {\n        float64_t uc, range, middle, bevelL, bevelXc, bevelYc, bevelStart, bevelStop, out;\n        float64_t const alpha = M_PI/8;\n        float64_t const beta = M_PI/4;\n\n        range = ma - mi;\n        middle = (ma + mi)/2;\n        uc = 2*(in - middle)/range;\n\n        bevelL = r * tan(alpha);\n        bevelStart = 1 - cos(beta)*bevelL;\n        bevelStop = 1 + bevelL;\n        bevelXc = bevelStop;\n        bevelYc = 1 - r;\n\n        if (uc >= bevelStop)\n        {\n            out = ma;\n        }\n        else if (uc <= -bevelStop)\n        {\n            out = mi;\n        }\n        else if (uc <= bevelStart && uc >= -bevelStart)\n        {\n            out = in;\n        }\n        else if (uc > bevelStart)\n        {\n            out = sqrt(r * r - (uc - bevelXc) * (uc - bevelXc)) + bevelYc;\n            out = 0.5 * out * range + middle;\n        }\n        else if (uc < -bevelStart)\n        {\n            out = -sqrt(r * r - (uc + bevelXc) * (uc + bevelXc)) - bevelYc;\n            out = 0.5 * out * range + middle;\n        }\n        else\n        {\n            out = in;\n        }\n        return out;\n    }\n\n    vectorN_t clamp(Eigen::Ref<vectorN_t const>         data,\n                    float64_t                   const & minThr,\n                    float64_t                   const & maxThr)\n    {\n        return data.unaryExpr(\n        [&minThr, &maxThr](float64_t const & x) -> float64_t\n        {\n            return clamp(x, minThr, maxThr);\n        });\n    }\n\n    float64_t clamp(float64_t const & data,\n                    float64_t const & minThr,\n                    float64_t const & maxThr)\n    {\n        if (!isnan(data))\n        {\n            return std::min(std::max(data, minThr), maxThr);\n        }\n        else\n        {\n            return 0.0;\n        }\n    }\n}\n", "meta": {"hexsha": "a9b2a1e0cadb8aa2832ef595f56e29d6e462e775", "size": 35961, "ext": "cc", "lang": "C++", "max_stars_repo_path": "core/src/Utilities.cc", "max_stars_repo_name": "matthieuvigne/jiminy", "max_stars_repo_head_hexsha": "f893b2254a9e695a4154b941b599536756ea3d8b", "max_stars_repo_licenses": ["MIT"], "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/Utilities.cc", "max_issues_repo_name": "matthieuvigne/jiminy", "max_issues_repo_head_hexsha": "f893b2254a9e695a4154b941b599536756ea3d8b", "max_issues_repo_licenses": ["MIT"], "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/Utilities.cc", "max_forks_repo_name": "matthieuvigne/jiminy", "max_forks_repo_head_hexsha": "f893b2254a9e695a4154b941b599536756ea3d8b", "max_forks_repo_licenses": ["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.6948979592, "max_line_length": 134, "alphanum_fraction": 0.4965935319, "num_tokens": 7801, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7662936430859597, "lm_q2_score": 0.4339814648038985, "lm_q1q2_score": 0.3325572376963606}}
{"text": "/*\n * Copyright (c) 2013-2021 Masahide Kashiwagi (kashi@waseda.jp)\n */\n\n#ifndef PSA_HPP\n#define PSA_HPP\n\n// Power Series Arithmetic Type I and II with recording\n\n#include <iostream>\n#include <list>\n#include <algorithm>\n#include <boost/numeric/ublas/vector.hpp>\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/io.hpp>\n#include <kv/convert.hpp>\n\nnamespace kv {\n\nnamespace ub = boost::numeric::ublas;\n\n\ntemplate <class T> class psa;\n\ntemplate <class C, class T> struct convertible<C, psa<T> > {\n\tstatic const bool value = convertible<C, T>::value || boost::is_same<C, psa<T> >::value;\n};\n\ntemplate <class C, class T> struct acceptable_n<C, psa<T> > {\n\tstatic const bool value = convertible<C, T>::value;\n};\n\n\n\ntemplate <class T> class psa {\n\tpublic:\n\tub::vector<T> v;\n\n\ttypedef T base_type;\n\n\tstatic int& mode() {\n\t\tstatic int m = 1;\n\t\t#ifdef _OPENMP\n\t\t#pragma omp threadprivate (m)\n\t\t#endif\n\t\treturn m;\n\t}\n\n\tstatic T& domain() {\n#ifdef _OPENMP // hack for non-POD thread local storage\n\t\tstatic T* d = NULL;\n\t\t#pragma omp threadprivate (d)\n\t\tif (d == NULL) {\n\t\t\td = new T();\n\t\t}\n\t\treturn *d;\n#else\n\t\tstatic T d;\n\t\treturn d;\n#endif\n\t}\n\n\n\tstatic std::list<psa>& history() {\n#ifdef _OPENMP // hack for non-POD thread local storage\n\t\tstatic std::list<psa>* hist = NULL;\n\t\t#pragma omp threadprivate (hist)\n\t\tif (hist == NULL) {\n\t\t\thist = new std::list<psa>();\n\t\t}\n\t\treturn *hist;\n#else\n\t\tstatic std::list<psa> hist;\n\t\treturn hist;\n#endif\n\t}\n\n\tstatic bool& record_history() {\n\t\tstatic bool rh = false;\n\t\t#ifdef _OPENMP\n\t\t#pragma omp threadprivate (rh)\n\t\t#endif\n\t\treturn rh;\n\t}\n\n\tstatic bool& use_history() {\n\t\tstatic bool uh = false;\n\t\t#ifdef _OPENMP\n\t\t#pragma omp threadprivate (uh)\n\t\t#endif\n\t\treturn uh;\n\t}\n\n\tpsa() {\n\t\tv.resize(1);\n\t\tv(0) = 0.;\n\t}\n\n\ttemplate <class C> explicit psa(const C& x, typename boost::enable_if_c< acceptable_n<C, psa>::value >::type* =0) {\n\t\tv.resize(1);\n\t\tv(0) = x;\n\t}\n\n\ttemplate <class C> typename boost::enable_if_c< acceptable_n<C, psa>::value, psa& >::type operator=(const C& x) {\n\t\tv.resize(1);\n\t\tv(0) = x;\n\t\treturn *this;\n\t}\n\n\tfriend psa operator+(const psa& a, const psa& b) {\n\t\tpsa r;\n\n\t\tif (a.v.size() == 1) {\n\t\t\tr.v = b.v;\n\t\t\tr.v(0) += a.v(0);\n\t\t} else if (b.v.size() == 1) {\n\t\t\tr.v = a.v;\n\t\t\tr.v(0) += b.v(0);\n\t\t} else {\n\t\t\tif (use_history() == true) {\n\t\t\t\tr = history().front();\n\t\t\t\tint old_size = r.v.size();\n\t\t\t\tif (mode() == 2) {\n\t\t\t\t\told_size = std::min(old_size, (int)a.v.size() - 1);\n\t\t\t\t}\n\t\t\t\tint i;\n\t\t\t\tr.v.resize(a.v.size(), true);\n\t\t\t\tfor (i=old_size; i<a.v.size(); i++) {\n\t\t\t\t\tr.v(i) = a.v(i) + b.v(i);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tr.v = a.v + b.v;\n\t\t\t}\n\t\t}\n\n\t\tif (use_history() == true) {\n\t\t\thistory().pop_front();\n\t\t}\n\n\t\tif (record_history() == true) {\n\t\t\tif (mode() == 1) {\n\t\t\t\thistory().push_back(r);\n\t\t\t} else {\n\t\t\t\tpsa r2 = r;\n\t\t\t\tr2.v.resize(r.v.size() - 1, true);\n\t\t\t\thistory().push_back(r2);\n\t\t\t}\n\t\t}\n\n\t\treturn r;\n\t}\n\n\ttemplate <class C> friend typename boost::enable_if_c< acceptable_n<C, psa>::value, psa >::type operator+(const psa& a, const C& b) {\n\t\tpsa r;\n\n\t\tr.v = a.v;\n\t\tr.v(0) += b;\n\n\t\treturn r;\n\t}\n\n\ttemplate <class C> friend typename boost::enable_if_c< acceptable_n<C, psa>::value, psa >::type operator+(const C& a, const psa& b) {\n\t\tpsa r;\n\n\t\tr.v = b.v;\n\t\tr.v(0) += a;\n\n\t\treturn r;\n\t}\n\n\tfriend psa& operator+=(psa& a, const psa& b) {\n\t\ta = a + b;\n\t\treturn a;\n\t}\n\n\ttemplate <class C> friend typename boost::enable_if_c< acceptable_n<C, psa>::value, psa& >::type operator+=(psa& a, const C& b) {\n\t\ta.v(0) += b;\n\t\treturn a;\n\t}\n\n\tfriend psa operator-(const psa& a, const psa& b) {\n\t\tpsa r;\n\n\t\tif (a.v.size() == 1) {\n\t\t\tr.v = - b.v;\n\t\t\tr.v(0) += a.v(0);\n\t\t} else if (b.v.size() == 1) {\n\t\t\tr.v = a.v;\n\t\t\tr.v(0) -= b.v(0);\n\t\t} else {\n\t\t\tif (use_history() == true) {\n\t\t\t\tr = history().front();\n\t\t\t\tint old_size = r.v.size();\n\t\t\t\tif (mode() == 2) {\n\t\t\t\t\told_size = std::min(old_size, (int)a.v.size() - 1);\n\t\t\t\t}\n\t\t\t\tint i;\n\t\t\t\tr.v.resize(a.v.size(), true);\n\t\t\t\tfor (i=old_size; i<a.v.size(); i++) {\n\t\t\t\t\tr.v(i) = a.v(i) - b.v(i);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tr.v = a.v - b.v;\n\t\t\t}\n\t\t}\n\n\t\tif (use_history() == true) {\n\t\t\thistory().pop_front();\n\t\t}\n\n\t\tif (record_history() == true) {\n\t\t\tif (mode() == 1) {\n\t\t\t\thistory().push_back(r);\n\t\t\t} else {\n\t\t\t\tpsa r2 = r;\n\t\t\t\tr2.v.resize(r.v.size() - 1, true);\n\t\t\t\thistory().push_back(r2);\n\t\t\t}\n\t\t}\n\n\t\treturn r;\n\t}\n\n\ttemplate <class C> friend typename boost::enable_if_c< acceptable_n<C, psa>::value, psa >::type operator-(const psa& a, const C& b) {\n\t\tpsa r;\n\n\t\tr.v = a.v;\n\t\tr.v(0) -= b;\n\n\t\treturn r;\n\t}\n\n\ttemplate <class C> friend typename boost::enable_if_c< acceptable_n<C, psa>::value, psa >::type operator-(const C& a, const psa& b) {\n\t\tpsa r;\n\n\t\tr.v = - b.v;\n\t\tr.v(0) += a;\n\n\t\treturn r;\n\t}\n\n\tfriend psa& operator-=(psa& a, const psa& b) {\n\t\ta = a - b;\n\t\treturn a;\n\t}\n\n\ttemplate <class C> friend typename boost::enable_if_c< acceptable_n<C, psa>::value, psa& >::type operator-=(psa& a, const C& b) {\n\t\ta.v(0) -= b;\n\t\treturn a;\n\t}\n\n\tfriend psa operator-(const psa& a) {\n\t\tpsa r;\n\n\t\tr.v = - a.v;\n\n\t\treturn r;\n\t}\n\n\tfriend psa operator*(const psa& a, const psa& b) {\n\t\tpsa r;\n\t\tint i, j, s;\n\t\tT sum;\n\t\tint old_size;\n\n\t\tif (a.v.size() == 1) {\n\t\t\tif (use_history() == true) {\n\t\t\t\tr = history().front();\n\t\t\t\told_size = r.v.size();\n\t\t\t\tif (mode() == 2) {\n\t\t\t\t\told_size = std::min(old_size, (int)b.v.size() - 1);\n\t\t\t\t}\n\t\t\t\tr.v.resize(b.v.size(), true);\n\t\t\t\tfor (i=old_size; i<b.v.size(); i++) {\n\t\t\t\t\tr.v(i) = a.v(0) * b.v(i);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tr.v = a.v(0) * b.v;\n\t\t\t}\n\t\t} else if (b.v.size() == 1) {\n\t\t\tif (use_history() == true) {\n\t\t\t\tr = history().front();\n\t\t\t\told_size = r.v.size();\n\t\t\t\tif (mode() == 2) {\n\t\t\t\t\told_size = std::min(old_size, (int)a.v.size() - 1);\n\t\t\t\t}\n\t\t\t\tr.v.resize(a.v.size(), true);\n\t\t\t\tfor (i=old_size; i<a.v.size(); i++) {\n\t\t\t\t\tr.v(i) = a.v(i) * b.v(0);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tr.v = a.v * b.v(0);\n\t\t\t}\n\t\t} else {\n\t\t\ts = a.v.size();\n\t\t\tif (use_history() == true) {\n\t\t\t\tr = history().front();\n\t\t\t\told_size = r.v.size();\n\t\t\t\tif (mode() == 2) {\n\t\t\t\t\told_size = std::min(old_size, (int)s - 1);\n\t\t\t\t}\n\t\t\t\tr.v.resize(s, true);\n\t\t\t} else {\n\t\t\t\told_size = 0;\n\t\t\t\tr.v.resize(s);\n\t\t\t}\n\t\t\tfor (i=old_size; i<s; i++) {\n\t\t\t\tsum = 0.;\n\t\t\t\tfor (j=0; j<=i; j++) {\n\t\t\t\t\tsum += a.v(j) * b.v(i-j);\n\t\t\t\t}\n\t\t\t\tr.v(i) = sum;\n\t\t\t}\n\n\t\t\tif (mode() == 2) {\n\t\t\t\t// history may be able to be used for\n\t\t\t\t// calculating tmp, but we do not use yet.\n\t\t\t\tub::vector<T> tmp(s);\n\t\t\t\ttmp(0) = r.v(s-1);\n\t\t\t\tfor (i=1; i<s; i++) {\n\t\t\t\t\tsum = 0.;\n\t\t\t\t\tfor (j=i; j<s; j++) {\n\t\t\t\t\t\tsum += a.v(j) * b.v(i-j+s-1);\n\t\t\t\t\t}\n\t\t\t\t\ttmp(i) = sum;\n\t\t\t\t}\n\t\t\t\tr.v(s-1) = polyrange(tmp, 0, s-1, domain());\n\t\t\t}\n\t\t}\n\n\t\tif (use_history() == true) {\n\t\t\thistory().pop_front();\n\t\t}\n\n\t\tif (record_history() == true) {\n\t\t\tif (mode() == 1) {\n\t\t\t\thistory().push_back(r);\n\t\t\t} else {\n\t\t\t\tpsa r2 = r;\n\t\t\t\tr2.v.resize(r.v.size() - 1, true);\n\t\t\t\thistory().push_back(r2);\n\t\t\t}\n\t\t}\n\n\t\treturn r;\n\t}\n\n\ttemplate <class C> friend typename boost::enable_if_c< acceptable_n<C, psa>::value, psa >::type operator*(const psa& a, const C& b) {\n\t\tpsa r;\n\n\t\tif (use_history() == true) {\n\t\t\tr = history().front();\n\t\t\tint old_size = r.v.size();\n\t\t\tif (mode() == 2) {\n\t\t\t\told_size = std::min(old_size, (int)a.v.size() - 1);\n\t\t\t}\n\t\t\tint i;\n\t\t\tr.v.resize(a.v.size(), true);\n\t\t\tfor (i=old_size; i<a.v.size(); i++) {\n\t\t\t\tr.v(i) = a.v(i) * b;\n\t\t\t}\n\t\t} else {\n\t\t\t// r.v = a.v * b;\n\t\t\tr.v = a.v * T(b); // assist for VC++\n\t\t}\n\n\t\tif (use_history() == true) {\n\t\t\thistory().pop_front();\n\t\t}\n\n\t\tif (record_history() == true) {\n\t\t\tif (mode() == 1) {\n\t\t\t\thistory().push_back(r);\n\t\t\t} else {\n\t\t\t\tpsa r2 = r;\n\t\t\t\tr2.v.resize(r.v.size() - 1, true);\n\t\t\t\thistory().push_back(r2);\n\t\t\t}\n\t\t}\n\n\t\treturn r;\n\t}\n\n\ttemplate <class C> friend typename boost::enable_if_c< acceptable_n<C, psa>::value, psa >::type operator*(const C& a, const psa& b) {\n\t\tpsa r;\n\n\t\tif (use_history() == true) {\n\t\t\tr = history().front();\n\t\t\tint old_size = r.v.size();\n\t\t\tif (mode() == 2) {\n\t\t\t\told_size = std::min(old_size, (int)b.v.size() - 1);\n\t\t\t}\n\t\t\tint i;\n\t\t\tr.v.resize(b.v.size(), true);\n\t\t\tfor (i=old_size; i<b.v.size(); i++) {\n\t\t\t\tr.v(i) = a * b.v(i);\n\t\t\t}\n\t\t} else {\n\t\t\t// r.v = a * b.v;\n\t\t\tr.v = T(a) * b.v; // assist for VC++\n\t\t}\n\n\t\tif (use_history() == true) {\n\t\t\thistory().pop_front();\n\t\t}\n\n\t\tif (record_history() == true) {\n\t\t\tif (mode() == 1) {\n\t\t\t\thistory().push_back(r);\n\t\t\t} else {\n\t\t\t\tpsa r2 = r;\n\t\t\t\tr2.v.resize(r.v.size() - 1, true);\n\t\t\t\thistory().push_back(r2);\n\t\t\t}\n\t\t}\n\n\t\treturn r;\n\t}\n\n\tfriend psa& operator*=(psa& a, const psa& b) {\n\t\ta = a * b;\n\t\treturn a;\n\t}\n\n\ttemplate <class C> friend typename boost::enable_if_c< acceptable_n<C, psa>::value, psa& >::type operator*=(psa& a, const C& b) {\n\t\ta = a * b;\n\t\treturn a;\n\t}\n\n\tfriend psa operator/(const psa& a, const psa& b) {\n\t\treturn a * inv(b);\n\t}\n\n\ttemplate <class C> friend typename boost::enable_if_c< acceptable_n<C, psa>::value, psa >::type operator/(const psa& a, const C& b) {\n\t\tpsa r;\n\n\t\t// r.v = a.v / b;\n\t\tr.v = a.v / T(b); // assist for VC++\n\n\t\treturn r;\n\t}\n\n\ttemplate <class C> friend typename boost::enable_if_c< acceptable_n<C, psa>::value, psa >::type operator/(const C& a, const psa& b) {\n\t\treturn a * inv(b);\n\t}\n\n\tfriend psa& operator/=(psa& a, const psa& b) {\n\t\ta = a / b;\n\t\treturn a;\n\t}\n\n\ttemplate <class C> friend typename boost::enable_if_c< acceptable_n<C, psa>::value, psa& >::type operator/=(psa& a, const C& b) {\n\t\ta = a / b;\n\t\treturn a;\n\t}\n\n\tfriend psa inv(const psa& x) {\n\t\tT a, xn, xn2, range;\n\t\tpsa h, hn, r;\n\t\tint i;\n\t\tint old_size;\n\t\tbool recover_uh = false;\n\t\tbool recover_rh = false;\n\n\t\ta = x.v(0);\n\t\t// h = x - a;\n\t\th = x; h.v(0) = 0.;\n\n\t\tr = 1./a;\n\t\thn = 1.;\n\t\txn = 1./a;\n\t\tif (mode() == 2) {\n\t\t\trange = evalrange(x);\n\t\t\txn2 = 1./range;\n\t\t}\n\t\tif (use_history() == true) {\n\t\t\told_size = history().front().v.size();\n\t\t}\n\t\tfor (i=1; i<x.v.size(); i++) {\n\t\t\tif (use_history() == true && i >= old_size) {\n\t\t\t\tuse_history() = false;\n\t\t\t\trecover_uh = true;\n\t\t\t}\n\t\t\tif (mode() == 2 && i == x.v.size() - 1) {\n\t\t\t\tif (record_history() == true) {\n\t\t\t\t\trecord_history() = false;\n\t\t\t\t\trecover_rh = true;\n\t\t\t\t}\n\t\t\t\t// scaling: hn->hn/a^i, xn->xn*a^i\n\t\t\t\t// hn *= h;\n\t\t\t\thn *= h / a;\n\t\t\t\t// xn2 = -xn2 / range;\n\t\t\t\txn2 = -xn2 / range * a;\n\t\t\t\tr += xn2 * hn;\n\t\t\t} else {\n\t\t\t\t// hn *= h;\n\t\t\t\thn *= h / a;\n\t\t\t\t// xn = -xn / a;\n\t\t\t\txn = -xn;\n\t\t\t\tif (mode() == 2) {\n\t\t\t\t\t// xn2 = -xn2 / range;\n\t\t\t\t\txn2 = -xn2 / range * a;\n\t\t\t\t}\n\t\t\t\tr += xn * hn;\n\t\t\t}\n\t\t}\n\t\tif (recover_uh) use_history() = true;\n\t\tif (recover_rh) record_history() = true;\n\n\t\t// dirty hack\n\t\t// to ensure that history buffer will be used at least once.\n\t\treturn r * 1.;\n\t}\n\n\tfriend psa sin (const psa& x) {\n\t\tT a, xn, xn2, range, fact_n, table[4], tmp;\n\t\tpsa h, hn, r;\n\t\tint i;\n\t\tint old_size;\n\t\tbool recover_uh = false;\n\t\tbool recover_rh = false;\n\n\t\ta = x.v(0);\n\t\t// h = x - a;\n\t\th = x; h.v(0) = 0.;\n\n\t\tusing std::sin;\n\t\tusing std::cos;\n\n\t\ttable[0] = sin(a);\n\t\ttable[1] = cos(a);\n\t\ttable[2] = -table[0];\n\t\ttable[3] = -table[1];\n\n\t\tr = table[0];\n\t\thn = 1.;\n\t\tfact_n = 1.;\n\t\tif (use_history() == true) {\n\t\t\told_size = history().front().v.size();\n\t\t}\n\t\tfor (i=1; i<x.v.size(); i++) {\n\t\t\tif (use_history() == true && i >= old_size) {\n\t\t\t\tuse_history() = false;\n\t\t\t\trecover_uh = true;\n\t\t\t}\n\t\t\tif (mode() == 2 && i == x.v.size() - 1) {\n\t\t\t\tif (record_history() == true) {\n\t\t\t\t\trecord_history() = false;\n\t\t\t\t\trecover_rh = true;\n\t\t\t\t}\n\t\t\t\thn *= h;\n\t\t\t\tfact_n /= (double)i;\n\t\t\t\trange = evalrange(x);\n\t\t\t\tswitch (i%4) {\n\t\t\t\tcase 0: tmp = sin(range); break;\n\t\t\t\tcase 1: tmp = cos(range); break;\n\t\t\t\tcase 2: tmp = -sin(range); break;\n\t\t\t\tcase 3: tmp = -cos(range); break;\n\t\t\t\t}\n\t\t\t\tr += fact_n * tmp * hn;\n\t\t\t} else {\n\t\t\t\thn *= h;\n\t\t\t\tfact_n /= (double)i;\n\t\t\t\tr += fact_n * table[i % 4] * hn;\n\t\t\t}\n\t\t}\n\t\tif (recover_uh) use_history() = true;\n\t\tif (recover_rh) record_history() = true;\n\n\t\t// dirty hack\n\t\t// to ensure that history buffer will be used at least once.\n\t\treturn r * 1.;\n\t}\n\n\tfriend psa cos (const psa& x) {\n\t\tT a, xn, xn2, range, fact_n, table[4], tmp;\n\t\tpsa h, hn, r;\n\t\tint i;\n\t\tint old_size;\n\t\tbool recover_uh = false;\n\t\tbool recover_rh = false;\n\n\t\ta = x.v(0);\n\t\t// h = x - a;\n\t\th = x; h.v(0) = 0.;\n\n\t\tusing std::sin;\n\t\tusing std::cos;\n\n\t\ttable[0] = cos(a);\n\t\ttable[1] = -sin(a);\n\t\ttable[2] = -table[0];\n\t\ttable[3] = -table[1];\n\n\t\tr = table[0];\n\t\thn = 1.;\n\t\tfact_n = 1.;\n\t\tif (use_history() == true) {\n\t\t\told_size = history().front().v.size();\n\t\t}\n\t\tfor (i=1; i<x.v.size(); i++) {\n\t\t\tif (use_history() == true && i >= old_size) {\n\t\t\t\tuse_history() = false;\n\t\t\t\trecover_uh = true;\n\t\t\t}\n\t\t\tif (mode() == 2 && i == x.v.size() - 1) {\n\t\t\t\tif (record_history() == true) {\n\t\t\t\t\trecord_history() = false;\n\t\t\t\t\trecover_rh = true;\n\t\t\t\t}\n\t\t\t\thn *= h;\n\t\t\t\tfact_n /= (double)i;\n\t\t\t\trange = evalrange(x);\n\t\t\t\tswitch (i%4) {\n\t\t\t\tcase 0: tmp = cos(range); break;\n\t\t\t\tcase 1: tmp = -sin(range); break;\n\t\t\t\tcase 2: tmp = -cos(range); break;\n\t\t\t\tcase 3: tmp = sin(range); break;\n\t\t\t\t}\n\t\t\t\tr += fact_n * tmp * hn;\n\t\t\t} else {\n\t\t\t\thn *= h;\n\t\t\t\tfact_n /= (double)i;\n\t\t\t\tr += fact_n * table[i % 4] * hn;\n\t\t\t}\n\t\t}\n\t\tif (recover_uh) use_history() = true;\n\t\tif (recover_rh) record_history() = true;\n\n\t\t// dirty hack\n\t\t// to ensure that history buffer will be used at least once.\n\t\treturn r * 1.;\n\t}\n\n\tfriend psa exp (const psa& x) {\n\t\tT a, xn, xn2, range, fact_n, ea;\n\t\tpsa h, hn, r;\n\t\tint i;\n\t\tint old_size;\n\t\tbool recover_uh = false;\n\t\tbool recover_rh = false;\n\n\t\ta = x.v(0);\n\t\t// h = x - a;\n\t\th = x; h.v(0) = 0.;\n\n\t\tusing std::exp;\n\n\t\tea = exp(a);\n\n\t\tr = ea;\n\t\thn = 1.;\n\t\tfact_n = 1.;\n\t\tif (use_history() == true) {\n\t\t\told_size = history().front().v.size();\n\t\t}\n\t\tfor (i=1; i<x.v.size(); i++) {\n\t\t\tif (use_history() == true && i >= old_size) {\n\t\t\t\tuse_history() = false;\n\t\t\t\trecover_uh = true;\n\t\t\t}\n\t\t\tif (mode() == 2 && i == x.v.size() - 1) {\n\t\t\t\tif (record_history() == true) {\n\t\t\t\t\trecord_history() = false;\n\t\t\t\t\trecover_rh = true;\n\t\t\t\t}\n\t\t\t\thn *= h;\n\t\t\t\tfact_n /= (double)i;\n\t\t\t\trange = evalrange(x);\n\t\t\t\tr += fact_n * exp(range) * hn;\n\t\t\t}else {\n\t\t\t\thn *= h;\n\t\t\t\tfact_n /= (double)i;\n\t\t\t\tr += fact_n * ea * hn;\n\t\t\t}\n\t\t}\n\t\tif (recover_uh) use_history() = true;\n\t\tif (recover_rh) record_history() = true;\n\n\t\t// dirty hack\n\t\t// to ensure that history buffer will be used at least once.\n\t\treturn r * 1.;\n\t}\n\n\tfriend psa sqrt(const psa& x) {\n\t\tT a, xn, xn2, sqrt_a, range;\n\t\tpsa h, hn, r;\n\t\tint i;\n\t\tint old_size;\n\t\tbool recover_uh = false;\n\t\tbool recover_rh = false;\n\n\t\ta = x.v(0);\n\t\t// h = x - a;\n\t\th = x; h.v(0) = 0.;\n\n\t\tusing std::sqrt;\n\n\t\tsqrt_a = sqrt(a);\n\n\t\tr = sqrt_a;\n\t\thn = 1.;\n\t\txn = 1./(2. * sqrt_a);\n\t\tif (mode() == 2) {\n\t\t\trange = evalrange(x);\n\t\t\txn2 = 1./(2. * sqrt(range));\n\t\t}\n\t\tif (use_history() == true) {\n\t\t\told_size = history().front().v.size();\n\t\t}\n\t\tfor (i=1; i<x.v.size(); i++) {\n\t\t\tif (use_history() == true && i >= old_size) {\n\t\t\t\tuse_history() = false;\n\t\t\t\trecover_uh = true;\n\t\t\t}\n\t\t\tif (mode() == 2 && i == x.v.size() - 1) {\n\t\t\t\tif (record_history() == true) {\n\t\t\t\t\trecord_history() = false;\n\t\t\t\t\trecover_rh = true;\n\t\t\t\t}\n\t\t\t\thn *= h;\n\t\t\t\tr += xn2 * hn;\n\t\t\t} else {\n\t\t\t\thn *= h;\n\t\t\t\tr += xn * hn;\n\t\t\t\txn *= (1./2. - i) / a / (i + 1.);\n\t\t\t\tif (mode() == 2) {\n\t\t\t\t\txn2 *= (1./2. - i) / range / (i + 1.);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif (recover_uh) use_history() = true;\n\t\tif (recover_rh) record_history() = true;\n\n\t\t// dirty hack\n\t\t// to ensure that history buffer will be used at least once.\n\t\treturn r * 1.;\n\t}\n\n\tfriend psa log(const psa& x) {\n\t\tT a, xn, xn2, range;\n\t\tpsa h, hn, r;\n\t\tint i;\n\t\tint old_size;\n\t\tbool recover_uh = false;\n\t\tbool recover_rh = false;\n\n\t\ta = x.v(0);\n\t\t// h = x - a;\n\t\th = x; h.v(0) = 0.;\n\n\t\tusing std::log;\n\n\t\tr = log(a);\n\t\thn = 1.;\n\t\txn = -1.;\n\t\tif (mode() == 2) {\n\t\t\trange = evalrange(x);\n\t\t\txn2 = -1.;\n\t\t}\n\t\tif (use_history() == true) {\n\t\t\told_size = history().front().v.size();\n\t\t}\n\t\tfor (i=1; i<x.v.size(); i++) {\n\t\t\tif (use_history() == true && i >= old_size) {\n\t\t\t\tuse_history() = false;\n\t\t\t\trecover_uh = true;\n\t\t\t}\n\t\t\tif (mode() == 2 && i == x.v.size() - 1) {\n\t\t\t\tif (record_history() == true) {\n\t\t\t\t\trecord_history() = false;\n\t\t\t\t\trecover_rh = true;\n\t\t\t\t}\n\t\t\t\thn *= h;\n\t\t\t\txn2 = -xn2 / range;\n\t\t\t\tr += xn2 / (double)i * hn;\n\t\t\t} else {\n\t\t\t\thn *= h;\n\t\t\t\txn = -xn / a;\n\t\t\t\tif (mode() == 2) {\n\t\t\t\t\txn2 = -xn2 / range;\n\t\t\t\t}\n\t\t\t\tr += xn / (double)i * hn;\n\t\t\t}\n\t\t}\n\t\tif (recover_uh) use_history() = true;\n\t\tif (recover_rh) record_history() = true;\n\n\t\t// dirty hack\n\t\t// to ensure that history buffer will be used at least once.\n\t\treturn r * 1.;\n\t}\n\n\tfriend psa sinh (const psa& x) {\n\t\tT a, xn, xn2, range, fact_n, table[2], tmp;\n\t\tpsa h, hn, r;\n\t\tint i;\n\t\tint old_size;\n\t\tbool recover_uh = false;\n\t\tbool recover_rh = false;\n\n\t\ta = x.v(0);\n\t\t// h = x - a;\n\t\th = x; h.v(0) = 0.;\n\n\t\tusing std::sinh;\n\t\tusing std::cosh;\n\n\t\ttable[0] = sinh(a);\n\t\ttable[1] = cosh(a);\n\n\t\tr = table[0];\n\t\thn = 1.;\n\t\tfact_n = 1.;\n\t\tif (use_history() == true) {\n\t\t\told_size = history().front().v.size();\n\t\t}\n\t\tfor (i=1; i<x.v.size(); i++) {\n\t\t\tif (use_history() == true && i >= old_size) {\n\t\t\t\tuse_history() = false;\n\t\t\t\trecover_uh = true;\n\t\t\t}\n\t\t\tif (mode() == 2 && i == x.v.size() - 1) {\n\t\t\t\tif (record_history() == true) {\n\t\t\t\t\trecord_history() = false;\n\t\t\t\t\trecover_rh = true;\n\t\t\t\t}\n\t\t\t\thn *= h;\n\t\t\t\tfact_n /= (double)i;\n\t\t\t\trange = evalrange(x);\n\t\t\t\tswitch (i%2) {\n\t\t\t\tcase 0: tmp = sinh(range); break;\n\t\t\t\tcase 1: tmp = cosh(range); break;\n\t\t\t\t}\n\t\t\t\tr += fact_n * tmp * hn;\n\t\t\t} else {\n\t\t\t\thn *= h;\n\t\t\t\tfact_n /= (double)i;\n\t\t\t\tr += fact_n * table[i % 2] * hn;\n\t\t\t}\n\t\t}\n\t\tif (recover_uh) use_history() = true;\n\t\tif (recover_rh) record_history() = true;\n\n\t\t// dirty hack\n\t\t// to ensure that history buffer will be used at least once.\n\t\treturn r * 1.;\n\t}\n\n\tfriend psa cosh (const psa& x) {\n\t\tT a, xn, xn2, range, fact_n, table[2], tmp;\n\t\tpsa h, hn, r;\n\t\tint i;\n\t\tint old_size;\n\t\tbool recover_uh = false;\n\t\tbool recover_rh = false;\n\n\t\ta = x.v(0);\n\t\t// h = x - a;\n\t\th = x; h.v(0) = 0.;\n\n\t\tusing std::sinh;\n\t\tusing std::cosh;\n\n\t\ttable[0] = cosh(a);\n\t\ttable[1] = sinh(a);\n\n\t\tr = table[0];\n\t\thn = 1.;\n\t\tfact_n = 1.;\n\t\tif (use_history() == true) {\n\t\t\told_size = history().front().v.size();\n\t\t}\n\t\tfor (i=1; i<x.v.size(); i++) {\n\t\t\tif (use_history() == true && i >= old_size) {\n\t\t\t\tuse_history() = false;\n\t\t\t\trecover_uh = true;\n\t\t\t}\n\t\t\tif (mode() == 2 && i == x.v.size() - 1) {\n\t\t\t\tif (record_history() == true) {\n\t\t\t\t\trecord_history() = false;\n\t\t\t\t\trecover_rh = true;\n\t\t\t\t}\n\t\t\t\thn *= h;\n\t\t\t\tfact_n /= (double)i;\n\t\t\t\trange = evalrange(x);\n\t\t\t\tswitch (i%2) {\n\t\t\t\tcase 0: tmp = cosh(range); break;\n\t\t\t\tcase 1: tmp = sinh(range); break;\n\t\t\t\t}\n\t\t\t\tr += fact_n * tmp * hn;\n\t\t\t} else {\n\t\t\t\thn *= h;\n\t\t\t\tfact_n /= (double)i;\n\t\t\t\tr += fact_n * table[i % 2] * hn;\n\t\t\t}\n\t\t}\n\t\tif (recover_uh) use_history() = true;\n\t\tif (recover_rh) record_history() = true;\n\n\t\t// dirty hack\n\t\t// to ensure that history buffer will be used at least once.\n\t\treturn r * 1.;\n\t}\n\n\tfriend psa asin (const psa& x) {\n\t\tpsa h, hn, r;\n\t\tpsa taylor;\n\t\tint i;\n\t\tint old_size;\n\t\tbool save_uh, save_rh;\n\t\tT save_domain;\n\n\t\tsave_uh = use_history();\n\t\tsave_rh = record_history();\n\t\tsave_domain = domain();\n\n\t\tuse_history() = false;\n\t\trecord_history() = false;\n\n\t\th = x; h.v(0) = 0.;\n\n\t\tif (mode() == 2) {\n\t\t\tdomain() = evalrange(x);\n\t\t}\n\t\ttaylor.v.resize(2);\n\t\ttaylor.v(0) = x.v(0);\n\t\ttaylor.v(1) = 1;\n\t\ttaylor = setorder(taylor, x.v.size()-2);\n\n\t\tusing std::asin;\n\t\tusing std::sqrt;\n\n\t\ttaylor = asin(x.v(0)) + integrate(1 / sqrt(1 - taylor * taylor));\n\n\t\tuse_history() = save_uh;\n\t\trecord_history() = save_rh;\n\t\tif (mode() == 2) {\n\t\t\tdomain() = save_domain;\n\t\t}\n\n\t\tr = taylor.v(0);\n\t\thn = 1.;\n\t\tif (use_history() == true) {\n\t\t\told_size = history().front().v.size();\n\t\t}\n\t\tfor (i=1; i<x.v.size(); i++) {\n\t\t\tif (use_history() == true && i >= old_size) {\n\t\t\t\tuse_history() = false;\n\t\t\t}\n\t\t\tif (mode() == 2 && i == x.v.size() - 1) {\n\t\t\t\tif (record_history() == true) {\n\t\t\t\t\trecord_history() = false;\n\t\t\t\t}\n\t\t\t}\n\t\t\thn *= h;\n\t\t\tr += taylor.v(i) * hn;\n\t\t}\n\n\t\tuse_history() = save_uh;\n\t\trecord_history() = save_rh;\n\n\t\t// dirty hack\n\t\t// to ensure that history buffer will be used at least once.\n\t\treturn r * 1.;\n\t}\n\n\tfriend psa acos (const psa& x) {\n\t\tpsa h, hn, r;\n\t\tpsa taylor;\n\t\tint i;\n\t\tint old_size;\n\t\tbool save_uh, save_rh;\n\t\tT save_domain;\n\n\t\tsave_uh = use_history();\n\t\tsave_rh = record_history();\n\t\tsave_domain = domain();\n\n\t\tuse_history() = false;\n\t\trecord_history() = false;\n\n\t\th = x; h.v(0) = 0.;\n\n\t\tif (mode() == 2) {\n\t\t\tdomain() = evalrange(x);\n\t\t}\n\t\ttaylor.v.resize(2);\n\t\ttaylor.v(0) = x.v(0);\n\t\ttaylor.v(1) = 1;\n\t\ttaylor = setorder(taylor, x.v.size()-2);\n\n\t\tusing std::acos;\n\t\tusing std::sqrt;\n\n\t\ttaylor = acos(x.v(0)) + integrate(-1 / sqrt(1 - taylor * taylor));\n\n\t\tuse_history() = save_uh;\n\t\trecord_history() = save_rh;\n\t\tif (mode() == 2) {\n\t\t\tdomain() = save_domain;\n\t\t}\n\n\t\tr = taylor.v(0);\n\t\thn = 1.;\n\t\tif (use_history() == true) {\n\t\t\told_size = history().front().v.size();\n\t\t}\n\t\tfor (i=1; i<x.v.size(); i++) {\n\t\t\tif (use_history() == true && i >= old_size) {\n\t\t\t\tuse_history() = false;\n\t\t\t}\n\t\t\tif (mode() == 2 && i == x.v.size() - 1) {\n\t\t\t\tif (record_history() == true) {\n\t\t\t\t\trecord_history() = false;\n\t\t\t\t}\n\t\t\t}\n\t\t\thn *= h;\n\t\t\tr += taylor.v(i) * hn;\n\t\t}\n\n\t\tuse_history() = save_uh;\n\t\trecord_history() = save_rh;\n\n\t\t// dirty hack\n\t\t// to ensure that history buffer will be used at least once.\n\t\treturn r * 1.;\n\t}\n\n\tfriend psa atan (const psa& x) {\n\t\tpsa h, hn, r;\n\t\tpsa taylor;\n\t\tint i;\n\t\tint old_size;\n\t\tbool save_uh, save_rh;\n\t\tT save_domain;\n\n\t\tsave_uh = use_history();\n\t\tsave_rh = record_history();\n\t\tsave_domain = domain();\n\n\t\tuse_history() = false;\n\t\trecord_history() = false;\n\n\t\th = x; h.v(0) = 0.;\n\n\t\tif (mode() == 2) {\n\t\t\tdomain() = evalrange(x);\n\t\t}\n\t\ttaylor.v.resize(2);\n\t\ttaylor.v(0) = x.v(0);\n\t\ttaylor.v(1) = 1;\n\t\ttaylor = setorder(taylor, x.v.size()-2);\n\n\t\tusing std::atan;\n\n\t\ttaylor = atan(x.v(0)) + integrate(1 / (1 + taylor * taylor));\n\n\t\tuse_history() = save_uh;\n\t\trecord_history() = save_rh;\n\t\tif (mode() == 2) {\n\t\t\tdomain() = save_domain;\n\t\t}\n\n\t\tr = taylor.v(0);\n\t\thn = 1.;\n\t\tif (use_history() == true) {\n\t\t\told_size = history().front().v.size();\n\t\t}\n\t\tfor (i=1; i<x.v.size(); i++) {\n\t\t\tif (use_history() == true && i >= old_size) {\n\t\t\t\tuse_history() = false;\n\t\t\t}\n\t\t\tif (mode() == 2 && i == x.v.size() - 1) {\n\t\t\t\tif (record_history() == true) {\n\t\t\t\t\trecord_history() = false;\n\t\t\t\t}\n\t\t\t}\n\t\t\thn *= h;\n\t\t\tr += taylor.v(i) * hn;\n\t\t}\n\n\t\tuse_history() = save_uh;\n\t\trecord_history() = save_rh;\n\n\t\t// dirty hack\n\t\t// to ensure that history buffer will be used at least once.\n\t\treturn r * 1.;\n\t}\n\n\tfriend psa asinh (const psa& x) {\n\t\tpsa h, hn, r;\n\t\tpsa taylor;\n\t\tint i;\n\t\tint old_size;\n\t\tbool save_uh, save_rh;\n\t\tT save_domain;\n\n\t\tsave_uh = use_history();\n\t\tsave_rh = record_history();\n\t\tsave_domain = domain();\n\n\t\tuse_history() = false;\n\t\trecord_history() = false;\n\n\t\th = x; h.v(0) = 0.;\n\n\t\tif (mode() == 2) {\n\t\t\tdomain() = evalrange(x);\n\t\t}\n\t\ttaylor.v.resize(2);\n\t\ttaylor.v(0) = x.v(0);\n\t\ttaylor.v(1) = 1;\n\t\ttaylor = setorder(taylor, x.v.size()-2);\n\n\t\t// using std::asinh;\n\t\tusing std::sqrt;\n\n\t\ttaylor = asinh(x.v(0)) + integrate(1 / sqrt(1 + taylor * taylor));\n\n\t\tuse_history() = save_uh;\n\t\trecord_history() = save_rh;\n\t\tif (mode() == 2) {\n\t\t\tdomain() = save_domain;\n\t\t}\n\n\t\tr = taylor.v(0);\n\t\thn = 1.;\n\t\tif (use_history() == true) {\n\t\t\told_size = history().front().v.size();\n\t\t}\n\t\tfor (i=1; i<x.v.size(); i++) {\n\t\t\tif (use_history() == true && i >= old_size) {\n\t\t\t\tuse_history() = false;\n\t\t\t}\n\t\t\tif (mode() == 2 && i == x.v.size() - 1) {\n\t\t\t\tif (record_history() == true) {\n\t\t\t\t\trecord_history() = false;\n\t\t\t\t}\n\t\t\t}\n\t\t\thn *= h;\n\t\t\tr += taylor.v(i) * hn;\n\t\t}\n\n\t\tuse_history() = save_uh;\n\t\trecord_history() = save_rh;\n\n\t\t// dirty hack\n\t\t// to ensure that history buffer will be used at least once.\n\t\treturn r * 1.;\n\t}\n\n\tfriend psa acosh (const psa& x) {\n\t\tpsa h, hn, r;\n\t\tpsa taylor;\n\t\tint i;\n\t\tint old_size;\n\t\tbool save_uh, save_rh;\n\t\tT save_domain;\n\n\t\tsave_uh = use_history();\n\t\tsave_rh = record_history();\n\t\tsave_domain = domain();\n\n\t\tuse_history() = false;\n\t\trecord_history() = false;\n\n\t\th = x; h.v(0) = 0.;\n\n\t\tif (mode() == 2) {\n\t\t\tdomain() = evalrange(x);\n\t\t}\n\t\ttaylor.v.resize(2);\n\t\ttaylor.v(0) = x.v(0);\n\t\ttaylor.v(1) = 1;\n\t\ttaylor = setorder(taylor, x.v.size()-2);\n\n\t\t// using std::acosh;\n\t\tusing std::sqrt;\n\n\t\ttaylor = acosh(x.v(0)) + integrate(1 / sqrt(taylor * taylor - 1));\n\n\t\tuse_history() = save_uh;\n\t\trecord_history() = save_rh;\n\t\tif (mode() == 2) {\n\t\t\tdomain() = save_domain;\n\t\t}\n\n\t\tr = taylor.v(0);\n\t\thn = 1.;\n\t\tif (use_history() == true) {\n\t\t\told_size = history().front().v.size();\n\t\t}\n\t\tfor (i=1; i<x.v.size(); i++) {\n\t\t\tif (use_history() == true && i >= old_size) {\n\t\t\t\tuse_history() = false;\n\t\t\t}\n\t\t\tif (mode() == 2 && i == x.v.size() - 1) {\n\t\t\t\tif (record_history() == true) {\n\t\t\t\t\trecord_history() = false;\n\t\t\t\t}\n\t\t\t}\n\t\t\thn *= h;\n\t\t\tr += taylor.v(i) * hn;\n\t\t}\n\n\t\tuse_history() = save_uh;\n\t\trecord_history() = save_rh;\n\n\t\t// dirty hack\n\t\t// to ensure that history buffer will be used at least once.\n\t\treturn r * 1.;\n\t}\n\n\tfriend psa atanh (const psa& x) {\n\t\tpsa h, hn, r;\n\t\tpsa taylor;\n\t\tint i;\n\t\tint old_size;\n\t\tbool save_uh, save_rh;\n\t\tT save_domain;\n\n\t\tsave_uh = use_history();\n\t\tsave_rh = record_history();\n\t\tsave_domain = domain();\n\n\t\tuse_history() = false;\n\t\trecord_history() = false;\n\n\t\th = x; h.v(0) = 0.;\n\n\t\tif (mode() == 2) {\n\t\t\tdomain() = evalrange(x);\n\t\t}\n\t\ttaylor.v.resize(2);\n\t\ttaylor.v(0) = x.v(0);\n\t\ttaylor.v(1) = 1;\n\t\ttaylor = setorder(taylor, x.v.size()-2);\n\n\t\t// using std::atanh;\n\n\t\ttaylor = atanh(x.v(0)) + integrate(1 / (1 - taylor * taylor));\n\n\t\tuse_history() = save_uh;\n\t\trecord_history() = save_rh;\n\t\tif (mode() == 2) {\n\t\t\tdomain() = save_domain;\n\t\t}\n\n\t\tr = taylor.v(0);\n\t\thn = 1.;\n\t\tif (use_history() == true) {\n\t\t\told_size = history().front().v.size();\n\t\t}\n\t\tfor (i=1; i<x.v.size(); i++) {\n\t\t\tif (use_history() == true && i >= old_size) {\n\t\t\t\tuse_history() = false;\n\t\t\t}\n\t\t\tif (mode() == 2 && i == x.v.size() - 1) {\n\t\t\t\tif (record_history() == true) {\n\t\t\t\t\trecord_history() = false;\n\t\t\t\t}\n\t\t\t}\n\t\t\thn *= h;\n\t\t\tr += taylor.v(i) * hn;\n\t\t}\n\n\t\tuse_history() = save_uh;\n\t\trecord_history() = save_rh;\n\n\t\t// dirty hack\n\t\t// to ensure that history buffer will be used at least once.\n\t\treturn r * 1.;\n\t}\n\n\ttemplate <class C> friend typename boost::enable_if_c< acceptable_n<C, psa>::value && ! boost::is_integral<C>::value, psa >::type pow(const psa& a, const C& b) {\n\t\treturn pow(a, psa(b));\n\t}\n\n\ttemplate <class C> friend typename boost::enable_if_c< acceptable_n<C, psa>::value, psa >::type pow(const C& a, const psa& b) {\n\t\treturn pow(psa(a), b);\n\t}\n\n\tfriend psa pow(const psa& x, int y) {\n\t\tpsa r, xp;\n\t\tint a, tmp;\n\n\t\tif (y == 0) return psa(1.);\n\n\t\ta = (y >= 0) ? y : -y;\n\n\t\ttmp = a;\n\t\tr = 1.;\n\t\txp = x;\n\t\twhile (tmp != 0) {\n\t\t\tif (tmp % 2 != 0) {\n\t\t\t\tr *= xp;\n\t\t\t}\n\t\t\ttmp /= 2;\n\t\t\txp = xp * xp;\n\t\t}\n\n\t\tif (y < 0) {\n\t\t\tr = 1. / r;\n\t\t}\n\n\t\treturn r;\n\t}\n\n\tfriend psa pow(const psa& x, const psa& y) {\n\t\treturn exp(y * log(x));\n\t}\n\n\tfriend psa tan(const psa& x) {\n\t\treturn sin(x) / cos(x);\n\t}\n\n\tfriend psa tanh(const psa& x) {\n\t\treturn sinh(x) / cosh(x);\n\t}\n\n\tfriend std::ostream& operator<<(std::ostream& s, const psa& x) {\n\t\tint i;\n\t\tint n = x.v.size();\n\t\ts << '[';\n\t\ts << x.v(0);\n\t\tfor (i=1; i<n; i++) {\n\t\t\ts << ',';\n\t\t\ts << x.v(i);\n\t\t}\n\t\ts << ']';\n\t\treturn s;\n\t}\n\n\tfriend psa integrate(const psa& x) {\n\t\tint i;\n\t\tint s = x.v.size();\n\t\tpsa r;\n\n\t\tr.v.resize(s+1);\n\n\t\tr.v(0) = 0.;\n\t\tfor (i=1; i<=s; i++) {\n\t\t\tr.v(i) = x.v(i-1) / (double)i;\n\t\t}\n\t\treturn r;\n\t}\n\n\tfriend psa setorder(const psa& x, int n) {\n\t\tint i;\n\t\tint s = x.v.size();\n\t\tpsa r;\n\n\t\tr.v.resize(n+1);\n\n\t\tif (n+1 >= s) {\n\t\t\tfor (i=0; i<s; i++) r.v(i) = x.v(i);\n\t\t\tfor (i=s; i<n+1; i++) r.v(i) = 0.;\n\t\t\treturn r;\n\t\t}\n\n\t\tfor (i=0; i<n; i++) r.v(i) = x.v(i);\n\t\tif (psa::mode() == 1) {\n\t\t\tr.v(n) = x.v(n);\n\t\t} else {\n\t\t\tr.v(n) = polyrange(x.v, n, s-1, psa::domain());\n\t\t}\n\n\t\treturn r;\n\t}\n\n\tfriend T evalrange(const psa& x) {\n\t\tint s = x.v.size();\n\n\t\treturn polyrange(x.v, 0, s-1, psa::domain());\n\t}\n\n\ttemplate <class T1> friend T1 eval(const psa& x, const T1& a) {\n\t\tint s = x.v.size();\n\n\t\treturn polyrange(x.v, 0, s-1, a);\n\t}\n\n\t/*\n\t *  evaluate { p[x] + p[x+1]t + ... p[y]t^(y-x) | a \\in d }\n\t */\n\ttemplate <class T1> static T1 inline polyrange (const ub::vector<T>& p, int x, int y, const T1& d)\n\t{\n\t\tint i;\n\t\tT1 r;\n\n\t\tr = p(y);\n\n\t\tfor (i=y-1; i>=x; i--) {\n\t\t\tr = r * d + p(i);\n\t\t}\n\n\t\treturn r;\n\t}\n};\n\n} // namespace kv\n\n#endif // PSA_HPP\n", "meta": {"hexsha": "88089feef9b76b75956db38367742620e71d2f15", "size": 28178, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "kv/psa.hpp", "max_stars_repo_name": "mskashi/kv", "max_stars_repo_head_hexsha": "960996c667a74d939c1fe8c3c48ec4b54f717506", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 67.0, "max_stars_repo_stars_event_min_datetime": "2017-01-04T15:30:54.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T05:45:02.000Z", "max_issues_repo_path": "kv/psa.hpp", "max_issues_repo_name": "mskashi/kv", "max_issues_repo_head_hexsha": "960996c667a74d939c1fe8c3c48ec4b54f717506", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2017-02-10T02:59:45.000Z", "max_issues_repo_issues_event_max_datetime": "2019-10-10T14:17:08.000Z", "max_forks_repo_path": "kv/psa.hpp", "max_forks_repo_name": "mskashi/kv", "max_forks_repo_head_hexsha": "960996c667a74d939c1fe8c3c48ec4b54f717506", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2021-09-29T02:27:46.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T05:45:04.000Z", "avg_line_length": 20.0555160142, "max_line_length": 162, "alphanum_fraction": 0.5261196678, "num_tokens": 10410, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5506073802837478, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.33252932483780984}}
{"text": "/*******************************************************************************\n * Copyright (c) 2012, Dougal J. Sutherland (dsutherl@cs.cmu.edu).             *\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 Carnegie Mellon University nor the                *\n *       names of the 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 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 \"sdm/basics.hpp\"\n\n#include <algorithm>\n#include <cmath>\n#include <stdexcept>\n\n#include <boost/format.hpp>\n#include <boost/throw_exception.hpp>\n\n#include \"sdm/kernel_projection.hpp\"\n#include \"sdm/log.hpp\"\n#include \"sdm/utils.hpp\"\n\nusing boost::format;\n\nnamespace sdm {\n\n////////////////////////////////////////////////////////////////////////////////\n// General matrix math helpers\n\n// symmetrize a matrix: m = (m + m') / 2\nvoid symmetrize(double* matrix, size_t n) {\n    // loop over half of matrix\n    for (size_t i = 1; i < n; i++) {\n        for (size_t j = 0; j < i; j++) {\n            matrix[i + j*n] = matrix[j + i*n] =\n                (matrix[i + j*n] + matrix[j + i*n]) / 2.;\n        }\n    }\n}\n\n////////////////////////////////////////////////////////////////////////////////\n// Eigenvalues / eigenvectors helpers\n\n// LAPACK: computes the eigenvalues/vectors of a square symmetric dense matrix\nextern \"C\" void dsyev_(char *jobz, char *uplo, int *n, double *a,\n        int *lda, double *w, double *work, int *lwork, int *info);\n// FIXME: figure out how to support ILP64 lapacks, so that matlab interface\n//  works on linux without LD_PRELOAD\n\n/* Takes an n x n symmetric matrix and computes its eigendecomposition.\n *\n * Eigenvalues go in the n-element arre vals (in ascending order).\n *\n * Orthonormal eigenvectors go in the columns of the n^2-element array vecs,\n * in column-major order.\n *\n * jobz determines whether eigenvalues are actually calculated, but use the\n * overload below if you don't want them.\n *\n * Throws std::domain_error if dsyev fails.\n */\nvoid eig(double* matrix, int n, double* vals, double* vecs, char jobz='V') {\n    char uplo = 'U'; // indicate that upper-triangular part of matrix is present\n    int info; // indicates whether the call was successful\n    int lwork = 3*n - 1; // size of the work array  // TODO - tweak?\n    double *work = new double[lwork]; // the work array\n\n    // copy matrix into vecs, since dsyev_ is in-place\n    std::copy(matrix, matrix + n*n, vecs);\n\n    dsyev_(&jobz, &uplo, &n, vecs, &n, vals, work, &lwork, &info);\n\n    delete[] work;\n\n    if (info < 0) {\n        BOOST_THROW_EXCEPTION(std::domain_error(\n            (format(\"problem with dsyev argument %d\") % (-info)).str()));\n    } else if (info > 0) {\n        BOOST_THROW_EXCEPTION(std::domain_error(\"dsyev: failed to converge\"));\n    }\n}\n\n/* Takes an n x n symmetric matrix and stores its eigenvalues in the n-element\n * array vals, in ascending order.\n */\nvoid eig(double* matrix, size_t n, double* vals) {\n    double* vecs = new double[n*n]; // allocate memory for dsyev to destroy\n    eig(matrix, n, vals, vecs, 'N');\n    delete[] vecs;\n}\n\n////////////////////////////////////////////////////////////////////////////////\n// Spectral reconstruction\n\n// BLAS: scales a vector by a constant\nextern \"C\" void dscal_(int *n, double *alpha, double *x, int *incx);\n\n// BLAS: computes generalized matrix product  C := alpha * A * B + beta * C\nextern \"C\" void dgemm_(char *transa, char *transb,\n       int *m, int *n, int *k,\n       double *alpha, double *a, int *lda, void *b, int *ldb, \n       double *beta, void *c, int *ldc);\n\n/* Given an array of eigenvalues and corresponding orthonormal eigenvectors\n * (in column-major format), calculates the reconstructed matrix, optionally\n * throwing away any negative eigenvalues (which projects to the nearest\n * positive semidefinite matrix).\n */\nvoid spectral_reconstruction(int n, double *eigvals, double *eigvecs,\n        double *matrix, bool nonnegative_only = false)\n{\n    // We're calculating  V * max(diag(D), 0) * V'\n\n    int step = 1;\n\n    // First do the left-hand side: V * max(diag(D), 0)\n    // Need to scale each column of V by the corresponding eigenvector\n    double *leftside = new double[n * n];\n    std::copy(eigvecs, eigvecs + n*n, leftside);\n\n    for (size_t j = 0; j < n; j++) {\n        double v = eigvals[j];\n        if (nonnegative_only && v < 0)\n            v = 0.;\n\n        dscal_(&n, &v, eigvecs + j*n, &step);\n    }\n\n    // Now do (V * max(diag(D), 0)) * V'\n    char no = 'N';\n    char trans = 'T';\n    double one = 1.;\n    double zero = 0.;\n    int size = (int) n;\n    dgemm_(&no, &trans, &size, &size, &size,\n            &one, leftside, &size, eigvecs, &size,\n            &zero, matrix, &size);\n\n    delete[] leftside;\n}\n\n\n////////////////////////////////////////////////////////////////////////////////\n\n/* Takes an n x n matrix stored as a flat array, symmetrizes it, and projects\n * in-place to the nearest positive semidefinite matrix.\n */\nvoid project_to_symmetric_psd(double* matrix, size_t n) {\n    double* eigvals = new double[n];\n    double* eigvecs = new double[n*n];\n\n    symmetrize(matrix, n);\n\n    try {\n        FILE_LOG(logDEBUG4) << \"about to get eigenvalues of this matrix:\\n\" <<\n            detail::matrixToString(matrix, n, n);\n\n        eig(matrix, n, eigvals, eigvecs);\n\n        // are any of our eigenvalues actually negative?\n        // (note that we get the values back in ascending order)\n        if (eigvals[0] < 0) {\n            spectral_reconstruction(n, eigvals, eigvecs, matrix, true);\n            symmetrize(matrix, n);\n        }\n\n    } catch (...) { delete[] eigvals; delete[] eigvecs; throw; }\n    delete[] eigvals; delete[] eigvecs;\n}\n\n\n/* Takes an n x n matrix, stored as a flat array, symmetrizes it, and projects\n * it in-place to the nearest positive semidefinite matrix with unit diagonal.\n */\nvoid project_to_covariance(double* matrix, size_t n, size_t steps, double tol) {\n    // The alternating projection method (algorithm 3.3) of \n    //   Nicholas J. Higham, 2002.\n    //   Computing the Nearest Correlation Matrix: a Problem from Finance.\n    //   IMA Journal of Numerical Analysis, pages 329-343.\n\n    double* eigvals = new double[n];\n    double* eigvecs = new double[n*n];\n\n    // Dykstra's correction\n    double *S = new double[n*n];\n    std::fill(S, S+n*n, 0);\n\n    // R is the corrected form of matrix\n    double *R = new double[n*n];\n\n    // X is projected to be symmetric PSD\n    double *X = new double[n*n];\n    std::copy(matrix, matrix + n*n, X);\n\n    // used to check for x's convergence\n    double *prev_X = new double[n*n];\n\n\n    try {\n        symmetrize(matrix, n);\n\n        for (size_t iter = 0; iter < steps; iter++) {\n            // remember the previous x\n            std::copy(X, X + n*n, prev_X);\n\n            // R is the matrix minus the correction\n            for (size_t i = 0; i < n*n; i++)\n                R[i] = matrix[i] - S[i];\n\n            // X is projection of R to symmetric PSD matrix\n            eig(R, n, eigvals, eigvecs);\n            spectral_reconstruction(n, eigvals, eigvecs, X, true);\n            symmetrize(X, n);\n\n            // new correction is the difference between X and R\n            for (size_t i = 0; i < n*n; i++)\n                S[i] = X[i] - R[i];\n\n            // new matrix is X with unit diagonal\n            std::copy(X, X + n*n, matrix);\n            for (size_t i = 0; i < n; i++)\n                matrix[i + i*n] = 1.;\n\n            // have we converged?\n            if (iter > 0) {\n                double biggest_x = 0;\n                double biggest_change = 0;\n                for (size_t i = 0; i < n*n; i++) {\n                    double mag = std::abs(X[i]);\n                    if (mag > biggest_x)\n                        biggest_x = mag;\n\n                    double change = std::abs(X[i] - prev_X[i]);\n                    if (change > biggest_change)\n                        biggest_change = change;\n                }\n\n                if (biggest_change <= 1e-7 * biggest_x) {\n                    break;\n                }\n            }\n        }\n\n        // make sure we don't have any too-negative eigenvalues\n        eig(matrix, n, eigvals);\n        if (eigvals[0] < tol) {\n            BOOST_THROW_EXCEPTION(std::domain_error(\n                    (format(\"Failed to project to kernel matrix: min eig %g\")\n                     % eigvals[0]).str()));\n        }\n\n    } catch (...) { // fake a finally block\n        delete[] eigvals; delete[] eigvecs;\n        delete[] S; delete[] R;\n        delete[] X; delete[] prev_X;\n        throw;\n    }\n    delete[] eigvals; delete[] eigvecs;\n    delete[] S; delete[] R;\n    delete[] X; delete[] prev_X;\n}\n\n} // end namespace\n", "meta": {"hexsha": "b7d639751c274276d71449d987833f186ab7422d", "size": 10699, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "sdm/kernel_projection.cpp", "max_stars_repo_name": "dougalsutherland/sdm", "max_stars_repo_head_hexsha": "2f6a57c5b337649a64f899dd5acba6e4eb35dff9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2015-04-03T11:49:19.000Z", "max_stars_repo_stars_event_max_datetime": "2017-12-22T12:08:02.000Z", "max_issues_repo_path": "sdm/kernel_projection.cpp", "max_issues_repo_name": "dougalsutherland/sdm", "max_issues_repo_head_hexsha": "2f6a57c5b337649a64f899dd5acba6e4eb35dff9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-07-05T00:02:54.000Z", "max_issues_repo_issues_event_max_datetime": "2020-07-05T00:02:54.000Z", "max_forks_repo_path": "sdm/kernel_projection.cpp", "max_forks_repo_name": "dougalsutherland/sdm", "max_forks_repo_head_hexsha": "2f6a57c5b337649a64f899dd5acba6e4eb35dff9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2016-05-20T10:40:40.000Z", "max_forks_repo_forks_event_max_datetime": "2018-05-21T15:50:32.000Z", "avg_line_length": 37.5403508772, "max_line_length": 80, "alphanum_fraction": 0.5485559398, "num_tokens": 2544, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6039318479832804, "lm_q2_score": 0.5506073655352404, "lm_q1q2_score": 0.3325293237809033}}
{"text": "//  Copyright (c)        2012 Zach Byerly\n//  Copyright (c) 2011 - 2012 Bryce Adelstein-Lelbach\n//  Copyright (c) 2012    Jonathan Parziale\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 is a 1 dimensional hydrodynamics code, using a simple first-order\n//  upwind advection scheme (to keep dependencies simple).  1st order in time.\n//  It employs a predictive timestep method in order to eliminate global\n//  barriers after every timestep. No gravity. A dual-energy formalism is also\n//  used to allow for heating in the shocks.\n\n// INCLUDES\n#include <hpx/hpx_init.hpp>\n#include <hpx/runtime/actions/plain_action.hpp>\n#include <hpx/runtime/components/plain_component_factory.hpp>\n#include <hpx/include/async.hpp>\n#include <hpx/include/iostreams.hpp>\n#include <hpx/lcos/future_wait.hpp>\n#include <hpx/lcos/wait_each.hpp>\n\n#include <boost/format.hpp>\n#include <boost/math/constants/constants.hpp>\n\nusing hpx::naming::id_type;\nusing hpx::naming::invalid_id;\n\nusing hpx::lcos::future;\nusing hpx::lcos::wait;\nusing hpx::lcos::wait_each;\nusing hpx::async;\n\nusing hpx::util::high_resolution_timer;\n\nusing boost::program_options::variables_map;\nusing boost::program_options::options_description;\nusing boost::program_options::value;\n\nusing hpx::init;\nusing hpx::finalize;\nusing hpx::find_here;\n\nusing hpx::cout;\nusing hpx::flush;\n\n\n// USING STATEMENTS\n\n////////////////////////////////////////\n// globals\n\n// initialized in hpx_main\nid_type here = invalid_id;\nboost::uint64_t nt = 0;\nboost::uint64_t nx = 0;\nboost::uint64_t n_predict = 0;\ndouble fluid_gamma = 0.0;\ndouble x_min = 0.0;\ndouble x_max = 0.0;\ndouble dx = 0.0;\ndouble cfl_factor = 0.0;\ndouble cfl_predict_factor = 0.0;\ndouble ptime;\n\n// this is the fundimental element of the hydrodynamics code, the\n// individual cell.  It stores all of the variables that the code\n// tracks their changes in time.\nstruct cell{\n  // default constructor\n  cell()\n    : mtx()\n    , rho(0.0)    // mass density\n    , mom(0.0)    // momentum density\n    , etot(0.0)   // total energy density\n    , tau(0.0)   // internal energy density (etot - kinetic energy)\n    , computed(false)\n  {}\n\n  // copy constructor\n  cell(\n       cell const& other\n       )\n    : mtx()\n    , rho(other.rho)\n    , mom(other.mom)\n    , etot(other.etot)\n    , tau(other.tau)\n    , computed(other.computed)\n  {}\n\n  // assignment operator:\n  //\n  //   cell c1, c2;\n  //   c1 = c2; // invoked by this syntax\n  //  Bryce:  I think i'd like to change this so the \"calculated\" is not copied in the assignment op\n  cell& operator=(\n       cell const& other\n       )\n  {\n    // first, we lock both the mutex of this cell, and the mutex of the other\n    // cell\n    //    hpx::lcos::local::mutex::scoped_lock this_lock(mtx), other_lock(other.mtx);\n\n    rho = other.rho;\n    mom = other.mom;\n    etot = other.etot;\n    tau = other.tau;\n    computed = other.computed;\n\n    // return a reference to ourselves\n    return *this;\n  }\n\n  // dummy serialization functionality\n  template <typename Archive>\n  void serialize(Archive &, unsigned) {}\n\n  mutable hpx::lcos::local::mutex mtx;\n  double rho;\n  double mom;\n  double etot;\n  double tau;\n  bool computed;\n};\n// this is a single element of a \"time array\" that will be 1D array\n// containing information about timestep size. the index will be\n// the integer timestep number, so time_array[timestep].dt will be\n// the timestep size at that timestep\nstruct time_element{\n  // default constructor\n  time_element()\n    : dt(0.0)\n    , elapsed_time(0.0)\n    , computed(false),fluid_future(0),fluid(0)\n  {}\n\n  time_element(boost::uint64_t number_of_cells)\n      :fluid_future(number_of_cells)\n      ,fluid(number_of_cells)\n      {}\n  // copy constructor\n  time_element(\n       time_element const& other\n       )\n    : dt(other.dt)                     // timestep size\n    , elapsed_time(other.elapsed_time) // elapsed time\n    , computed(other.computed)\n    ,fluid_future(other.fluid_future)\n    ,fluid(other.fluid)\n    {}\n\n  time_element& operator=(time_element const& rhs)\n  {\n    if (this != &rhs)\n    {\n      dt = rhs.dt;\n      elapsed_time = rhs.elapsed_time;\n      computed = rhs.computed;\n      fluid=rhs.fluid;\n      fluid_future=rhs.fluid_future;\n\n    }\n    return *this;\n  }\n\n  hpx::lcos::local::mutex mtx;\n  double dt;\n  double elapsed_time;\n  bool computed;\n  double physics_time;\n  std::vector<hpx::lcos::shared_future<cell> > fluid_future;//future for each cell\n  std::vector<cell> fluid;\n};\n// declaring time_array\n\n\n\n\n// Object to store the Fluid seperated in cell and computed by a Time Zone of tie Steps\n// Will store the 2d grid created by the division of the fluid into cells and the computation over time\n// Will be able to Retrieve,remove,add a timestep to the grid\n\nclass One_Dimension_Grid\n{\npublic:\n    One_Dimension_Grid():time_array(0)\n    {}\n    // ~One_Dimension_Grid();\n    void remove_bottom_time_step();//takes the timesteps position in the vector\n    void addNewTimeStep();\n\npublic:\n   std::vector<time_element> time_array;//pointer to the Grid we will create whden the user starts a simulation\n\n};\nvoid One_Dimension_Grid::remove_bottom_time_step()\n{\n    time_array.pop_back();\n}\nvoid One_Dimension_Grid::addNewTimeStep()\n{\n    time_array.insert(time_array.begin(),time_array.at(nx-1));\n}\n/*One_Dimension_Grid::~One_Dimension_Grid()\n{\n    for(boost::uint64_t i=0;i<nt;i++)\n    {\n        time_array.pop_back();\n    }\n    delete &time_array;\n}*/\n\n// declaring grid of all cells for all timesteps\nOne_Dimension_Grid grid;\n// forward declaration of the compute function\ncell compute(boost::uint64_t timestep, boost::uint64_t location);\ndouble timestep_size(boost::uint64_t timestep);\ncell initial_sod(boost::uint64_t location);\ndouble get_pressure(cell input);\n\n// Wrapping in plain_action\nHPX_PLAIN_ACTION(compute);\n\ntypedef hpx::lcos::future<cell> compute_future;\n\n// this will return the timestep size.  The timestep index will refer to the\n// timestep where it will be USED rather than the timestep where it was\n// calculated.\ndouble timestep_size(boost::uint64_t timestep)\n{\n  // locking\n\n  hpx::lcos::local::mutex::scoped_lock l(grid.time_array.at(timestep).mtx);\n\n  // if it has already been calculated, then just return the value\n  if (grid.time_array.at(timestep).computed)\n  {return grid.time_array.at(timestep).dt;}\n  //  cout << (boost::format(\"calculating timestep, ts=%1% \\n\") % timestep) << flush;\n\n\n  // if the current timestep is less than n_predict, then we manually\n  // decide the timestep\n  if (timestep < n_predict)\n    {\n      grid.time_array.at(timestep).computed = true;\n      grid.time_array.at(timestep).dt = dx*0.033;// this should be fine unless\n        // the initial conditions are changed\n        if(timestep>0&&grid.time_array.at(timestep-1).computed)\n            grid.time_array[timestep].physics_time = (grid.time_array.at(timestep-1).physics_time+grid.time_array.at(timestep).dt);\n  //    time_array[timestep].dt = cfl_predict_factor*dt_cfl;\n        else if(timestep==0)\n        {\n            grid.time_array.at(timestep).physics_time=grid.time_array.at(timestep).dt;\n        }\n      return grid.time_array.at(timestep).dt;\n    }\n\n  // send back the compute futures for the whole grid\n  // n_predict timesteps previous to the one we want to decide\n  // the timestep for\n  //  cout << (boost::format(\"pushing back futures for ts calc, ts=%1% \\n\") % timestep) << flush;\n  if(timestep>=n_predict)\n  {\n  for (boost::uint64_t i=0;i<nx;i++)\n      grid.time_array.at(timestep).fluid_future.push_back(async<compute_action>(here,timestep-n_predict,i));\n  }\n\n  double dt_cfl = 1000.0;\n\n   wait_each(\n      hpx::util::unwrapped([&](cell const& this_cell)\n      {\n      // look at all of the cells at a timestep, then pick the smallest\n      // dt_cfl = cfl_factor*dx/(soundspeed+absolute_velocity)\n      double abs_velocity = this_cell.mom/this_cell.rho;\n      double pressure = get_pressure(this_cell);\n      double soundspeed = sqrt(fluid_gamma*pressure/this_cell.rho);\n      double dt_cfl_here = cfl_factor*dx/(soundspeed+abs_velocity);\n      if (dt_cfl_here <=  0.0)\n        {\n          cout << (boost::format(\"error: CFL value can't be zero\")) << flush;\n          //error, quit everything\n        }\n      if (dt_cfl_here < dt_cfl)\n        dt_cfl = dt_cfl_here;\n     }),\n     grid.time_array.at(timestep).fluid_future);\n\n  // initialize dt_cfl to some arbitrary high value\n\n\n  // wait for an array of futures\n  /*wait_each(grid.time_array,\n    hpx::util::unwrapped([&](cell const& this_cell)\n    {\n      // look at all of the cells at a timestep, then pick the smallest\n      // dt_cfl = cfl_factor*dx/(soundspeed+absolute_velocity)\n      double abs_velocity = this_cell.mom/this_cell.rho;\n      double pressure = get_pressure(this_cell);\n      double soundspeed = sqrt(fluid_gamma*pressure/this_cell.rho);\n      double dt_cfl_here = cfl_factor*dx/(soundspeed+abs_velocity);\n      if (dt_cfl_here <=  0.0)\n        {\n          cout << (boost::format(\"error: CFL value can't be zero\")) << flush;\n          //error, quit everything\n        }\n      if (dt_cfl_here < dt_cfl)\n        dt_cfl = dt_cfl_here;\n    }));\n*/\n\n\n  if(dt_cfl > 999.0)\n    {\n      cout << (boost::format(\"error: CFL value too high\")) << flush;\n      // error, quit everything\n    }\n\n  // we don't want to let the timestep increase too quickly, so\n  // we only let it increase by 25% each timestep\n  grid.time_array.at(timestep).computed = true;\n  grid.time_array.at(timestep).dt = (std::min)(\n                                     cfl_predict_factor*dt_cfl\n                                     ,\n                                     1.25*grid.time_array.at(timestep-1).dt);\n\n  //  cout << (boost::format(\"timestep = %1%, dt = %2%\\n\") % timestep % time_array[timestep].dt) << flush;\n  return grid.time_array[timestep].dt;\n}\n\ncell compute(boost::uint64_t timestep, boost::uint64_t location)\n{\n    hpx::lcos::local::mutex::scoped_lock l(grid.time_array.at(timestep).fluid.at(location).mtx);\n\n  // if it is already computed then just return the value\n    if (grid.time_array.at(timestep).fluid.at(location).computed == true)\n        return grid.time_array.at(timestep).fluid.at(location);\n\n  //  cout << (boost::format(\"computing new value, loc = %1%,ts=%2% \\n\") % location % timestep) << flush;\n\n  //initial values\n  if (timestep == 0)\n    {\n      //  cout << (boost::format(\"calling initial_sod, loc = %1%,ts=%2% \\n\") % location % timestep) << flush;\n        grid.time_array.at(timestep).fluid.at(location) = initial_sod(location);\n      //  cout << (boost::format(\"returning value, loc = %1%,ts=%2% \\n\") % location % timestep) << flush;\n        grid.time_array.at(timestep).fluid.at(location).computed = true;\n        return grid.time_array.at(timestep).fluid.at(location);\n    }\n\n   //boundary conditions (using sod shock tube boundaries)\n  if ( (location == 0) || (location == nx-1) )\n    {\n      grid.time_array.at(timestep).fluid.at(location) = initial_sod(location);\n      grid.time_array.at(timestep).fluid.at(location).computed = true;\n      return grid.time_array.at(timestep).fluid.at(location);\n    }\n\n  //now we have to actually compute some values.\n\n  //these are the dependencies, or \"stencil\"\n  //if(timestep<0) // unsigned comparision always false\n  //      return grid.time_array.at(timestep).fluid.at(location);\n\n  compute_future nleft = async<compute_action>(here,timestep-1,location-1);\n  compute_future nmiddle = async<compute_action>(here,timestep-1,location);\n  compute_future nright = async<compute_action>(here,timestep-1,location+1);\n\n  // OR is this the correct way to do it?\n  //future<cell> left;\n  //left = async<compute_action>(here,timestep-1,location-1);\n  //future<cell> middle;\n  //middle = async<compute_action>(here,timestep-1,location);\n  //future<cell> right;\n  //right = async<compute_action>(here,timestep-1,location+1);\n\n  cell now;\n\n  cell left   = nleft.get();\n  cell middle = nmiddle.get();\n  cell right  = nright.get();\n\n  // calling this function may or may not make futures\n  double dt = timestep_size(timestep);\n\n  now.rho = middle.rho;\n  now.mom = middle.mom;\n  now.etot = middle.etot;\n  now.tau = middle.tau;\n\n  // now that we have all of the information we need, we can proceed with\n  // the physics part of the update\n\n  double right_pressure = get_pressure(right);\n  double left_pressure = get_pressure(left);\n  double middle_pressure = get_pressure(middle);\n\n  // first we will calculate the advection of all of the variables\n  // through the left face of the cell.\n  // start by calculating the velocity on the left face\n  // if this velocity is positive, then fluid flows from the cell to the left.\n  // if it is negative, fluid flows out of the middle cell.\n  double velocity_left = (left.mom+middle.mom)/(left.rho+middle.rho);\n  if (velocity_left > 0.0)\n    {\n      now.rho +=  left.rho*velocity_left*dt/dx;\n      now.mom +=  left.mom*velocity_left*dt/dx;\n      now.etot += (left.etot+left_pressure)*velocity_left*dt/dx;\n      now.tau +=  left.tau*velocity_left*dt/dx;\n    }\n  else\n    {\n      now.rho +=  middle.rho*velocity_left*dt/dx;\n      now.mom +=  middle.mom*velocity_left*dt/dx;\n      now.etot += (middle.etot+middle_pressure)*velocity_left*dt/dx;\n      now.tau +=  middle.tau*velocity_left*dt/dx;\n    }\n\n  // now repeat the process for the right side\n  double velocity_right = (right.mom+middle.mom)/(right.rho+middle.rho);\n  if (velocity_right < 0.0)\n    {\n      now.rho -=  right.rho*velocity_right*dt/dx;\n      now.mom -=  right.mom*velocity_right*dt/dx;\n      now.etot -= (right.etot+right_pressure)*velocity_right*dt/dx;\n      now.tau -=  right.tau*velocity_right*dt/dx;\n    }\n  else\n    {\n      now.rho -=  middle.rho*velocity_right*dt/dx;\n      now.mom -=  middle.mom*velocity_right*dt/dx;\n      now.etot -= (middle.etot+middle_pressure)*velocity_right*dt/dx;\n      now.tau -=  middle.tau*velocity_right*dt/dx;\n    }\n\n  // source terms\n  now.mom += 0.5*dt*(left_pressure - right_pressure)/(dx);\n\n\n  // check for CFL (courant friedrichs levy) violation (makes code unstable)\n  double soundspeed = std::sqrt(fluid_gamma*middle_pressure/middle.rho);\n  double abs_velocity = (std::max)(velocity_right,velocity_right);\n  double dt_cfl_here = cfl_factor*dx/(soundspeed+abs_velocity);\n  if (dt_cfl_here > timestep)\n    {\n      cout << (boost::format(\"error! cfl violation!\\n\")) << flush;\n      cout << (boost::format(\"loc=%1% ts=%2%\\n\") % location % timestep) << flush;\n      cout << (boost::format(\"dt_cfl_here=%1% dt=%2%\\n\") % dt_cfl_here % dt ) << flush;\n\n      // Bryce: I should add some real error handling. can you help me with this?\n      // error, quit everything\n    }\n\n  double e_kinetic = 0.5*middle.mom*middle.mom/middle.rho;\n  double e_internal = middle.etot - e_kinetic;\n  //dual energy formalism\n  if ( std::abs(e_internal) > 0.1*middle.etot)\n    {\n      //cout << (boost::format(\"gas is shocking!\\n\")) << flush;\n      now.tau = pow(e_internal,(1.0/fluid_gamma));\n    }\n  // cout << (boost::format(\"computing new value, loc = %1%, ts= %2%\\n\") % location % timestep) << flush;\n  // cout << (boost::format(\"loc = %1%, rho = %2%\\n\") % location % left.rho) << flush;\n  // cout << (boost::format(\"loc = %1%, mom = %2%\\n\") % location % left.mom) << flush;\n  // cout << (boost::format(\"loc = %1%, etot = %2%\\n\") % location % left.etot) << flush;\n  // cout << (boost::format(\"loc = %1%, vel left = %2%\\n\") % location % velocity_left) << flush;\n\n  //  if (location == 1)\n  //    cout << (boost::format(\"calculating timestep = %1%\\n\") % timestep) << flush;\n\n  grid.time_array.at(timestep).fluid.at(location) = now;\n  grid.time_array.at(timestep).fluid.at(location).computed = true;\n  bool time_step_complete= false;\n  for(boost::uint64_t i=0;i<nx;i++)\n  {\n      if(grid.time_array[0].fluid.at(i).computed&&grid.time_array[1].fluid.at(i).computed)\n        time_step_complete=true;\n      else\n          time_step_complete=false;\n  }\n  if(time_step_complete&&!(grid.time_array.at(nt-1).physics_time>=ptime))\n  {\n      grid.remove_bottom_time_step();\n      grid.addNewTimeStep();\n  }\n\n  return grid.time_array.at(timestep).fluid.at(location);\n}\n\ndouble get_pressure(cell input)\n{\n  double pressure = 0.0;\n  double e_kinetic = 0.5*input.mom*input.mom/input.rho;\n  double e_internal = input.etot - e_kinetic;\n\n  // dual energy\n  if ( std::abs(e_internal) > 0.001*input.etot )\n    {\n      pressure = (fluid_gamma-1.0)*e_internal;\n    }\n  else\n    {\n      pressure = (fluid_gamma-1.0)*pow(input.tau,fluid_gamma);\n    }\n\n  return pressure;\n}\n\ncell initial_sod(boost::uint64_t location)\n{\n\n  //  cout << (boost::format(\"initial_sod, loc = %1%\\n\") % location) << flush;\n\n  // calculate what the x coordinate is here\n  double x_here = (location-0.5)*dx+x_min;\n\n  cell cell_here;\n  double e_internal = 0.0;\n\n  // This is the Sod Shock Tube problem, which has a known analytical\n  // solution.  A mass and energy contact discontinuity is placed on the grid.\n  // A shockwave then forms and propogates through the grid.\n  if (x_here < -0.1)\n    {\n      cell_here.rho = 1.0;\n      e_internal = 2.5;\n    }\n  else\n    {\n      cell_here.rho = 0.125;\n      e_internal = 0.25;\n    }\n\n  cell_here.mom = 0.0;\n  cell_here.tau = pow(e_internal,(1.0/fluid_gamma));\n  cell_here.etot = e_internal;  // ONLY true when mom=0, not in general!\n\n  //  cout << (boost::format(\"returning from initial_sod, loc = %1%\\n\") % location) << flush;\n  return cell_here;\n}\n\ncell get_analytic(double x_here, double time)\n{\n  cell output;\n\n  // values for analytic solution come from Patrick Motl's dissertation\n\n  //  cout << (boost::format(\"calculating analytic... x=%1% t=%2%\\n\") % x_here % time) << flush;\n\n  double x_0 = -0.1;\n\n  double c_1 = 1.183;\n  double x_head = x_0 - c_1*time;\n\n  double w_3 = 0.9274;\n  double c_3 = 0.9978;\n\n  double x_tail = x_0 + (w_3 - c_3)*time;\n\n  double w_4 = 0.9274;\n\n  double x_contact = x_0 + w_4*time;\n\n  double c_5 = 1.058;\n  double p_4 = 0.3031;\n  double p_5 = 0.1;\n\n  double W = c_5*std::pow( (1.0+(fluid_gamma+1.0)*(p_4 - p_5)/(2.0*fluid_gamma*p_5)), 0.5  );\n\n  double x_shock = x_0 + W*time;\n\n  if (x_here < x_head)  // region 1\n    {\n      output.rho = 1.0;\n      output.tau = 1.924;\n      output.mom = 0.0;\n    }\n  else if (x_here < x_tail) // region 2\n    {\n      double w_2 = 2.0*(c_1+(x_here-x_0)/time)/(fluid_gamma+1.0);\n      double exponent = 2.0/(fluid_gamma-1.0);\n      output.rho = std::pow( (1.0-(fluid_gamma-1.0)*w_2/(2.0*c_1)), exponent);\n      output.mom = output.rho*w_2;\n      output.tau = pow( (1.0-0.5*(fluid_gamma-1)*(w_2/c_1)), exponent)/pow(fluid_gamma-1.0,1.0/fluid_gamma);\n    }\n  else if (x_here < x_contact) // region 3\n    {\n      output.rho = 0.4263;\n      output.mom = 0.9274*output.rho;\n      output.tau = 0.8203;\n    }\n  else if (x_here < x_shock) // region 4\n    {\n      output.rho = 0.2656;\n      output.mom = 0.9274*output.rho;\n      output.tau = 0.8203;\n    }\n  else // region 5\n    {\n      output.rho = 0.125;\n      output.mom = 0.0;\n      output.tau = 0.3715;\n    }\n\n\n  return output;\n}\n\n\n\n///////////////////////////////////////////////////////////////////////////////\nint hpx_main(\n    variables_map& vm\n    )\n{\n    {\n  here = find_here();\n\n  // some physics parameters\n  nx = vm[\"nx-value\"].as<boost::uint64_t>();\n  nt = vm[\"nt-value\"].as<boost::uint64_t>();\n  n_predict = vm[\"npredict-value\"].as<boost::uint64_t>();\n  ptime=vm[\"ptime-value\"].as<double>();\n  fluid_gamma = 1.4;\n\n  x_min = -0.5;\n  x_max = 0.5;\n  dx = (x_max - x_min)/(nx-2);\n\n  cfl_factor = 0.5;\n  cfl_predict_factor = 0.8;\n\n  cout << (boost::format(\"nt = %1%\\n\") % nt) << flush;\n  cout << (boost::format(\"nx = %1%\\n\") % nx) << flush;\n  cout << (boost::format(\"n_predict = %1%\\n\") % n_predict) << flush;\n\n  // allocating the time array\n  grid.time_array = std::vector<time_element>(nt);\n\n  // allocating the grid 2d array of all of the cells for all timesteps\n  for(boost::uint64_t i=0;i<nt;i++)\n  {\n      grid.time_array[i].fluid=std::vector<cell>(nx);\n  }\n    //HPX stuff goes here\n\n    // Keep track of the time required to execute.\n    high_resolution_timer t;\n\n    timestep_size(0);\n    for (boost::uint64_t i=0;i<nx;i++)\n           grid.time_array[0].fluid_future.push_back(async<compute_action>(here,nt-1,i));\n    // open file for output\n    std::ofstream outfile;\n    outfile.open (\"output.dat\");\n\n    wait(grid.time_array[0].fluid_future, [&](std::size_t i, cell n)\n         { double x_here = (i-0.5)*dx+x_min;\n           double pressure_here = get_pressure(n);\n           //double tauoverrho = n.tau/n.rho;\n           double velocity_here = n.mom/n.rho;\n\n           double e_kinetic = 0.5*n.mom*n.mom/n.rho;\n           double e_internal = n.etot - e_kinetic;\n           double tauoverrho =  pow(e_internal,(1.0/fluid_gamma))/n.rho;\n           //           double e_internal2 = pow(n.tau,fluid_gamma);\n\n           outfile << (boost::format(\"%1% %2% %3% %4% %5%\\n\") % x_here % n.rho % pressure_here % tauoverrho % velocity_here) << flush; });\n           //           outfile << (boost::format(\"%1% %2% %3% %4% %5%\\n\") % x_here % n.rho % pressure_here % e_internal % e_internal2) << flush; });\n\n    outfile.close();\n\n    std::ofstream outfile2;\n    outfile2.open (\"time.dat\");\n\n    boost::uint64_t i;\n    // writing the \"time array\" to a file\n    grid.time_array[0].elapsed_time = grid.time_array[0].dt;\n    for (i=1;i<nt;i++)\n      grid.time_array[i].elapsed_time = grid.time_array[i-1].elapsed_time + grid.time_array[i].dt;\n\n    for (i =0;i<nt;i++)\n      {\n        outfile2 << (boost::format(\"%1% %2% %3%\\n\") % i % grid.time_array[i].dt % grid.time_array[i].elapsed_time) << flush;\n      }\n    outfile2.close();\n\n    // writing the analytic solution for the final time to a file\n    std::ofstream analytic_file;\n    analytic_file.open (\"analytic.dat\");\n    double total_mass = 0.0;\n    for (i =0;i<nx;i++)\n      {\n        double x_here = (i-0.5)*dx+x_min;\n        cell analytic = get_analytic(x_here,grid.time_array[nt-1].elapsed_time);\n        double velocity_here = analytic.mom/analytic.rho;\n        double tauoverrho = analytic.tau/analytic.rho;\n        double pressure_here = get_pressure(analytic);\n        analytic_file << (boost::format(\"%1% %2% %3% %4% %5%\\n\") % x_here % analytic.rho % pressure_here % tauoverrho % velocity_here) << flush;\n        total_mass += grid.time_array[nt-1].fluid[i].rho*dx;\n      }\n    analytic_file.close();\n\n    cout << (boost::format(\"total mass = %1%\\n\") % total_mass ) << flush;\n    char const* fmt = \"wall elapsed time: %1% [s]\\n\";\n    std::cout << (boost::format(fmt) % t.elapsed());\n    char const* fmt0 = \"code elapsed time: %1%\\n\";\n    double t_code_time= grid.time_array[0].elapsed_time;\n\n        t_code_time+=grid.time_array[nt-1].elapsed_time;\n\n      std::cout << (boost::format(fmt0) %  t_code_time);\n\n\n  }\n\n  finalize();\n  return 0;\n}\n\n///////////////////////////////////////////////////////////////////////////////\nint main(\n    int argc\n  , char* argv[]\n    )\n{\n  // Configure application-specific options.\n  options_description cmdline(\"usage: \" HPX_APPLICATION_STRING \" [options]\");\n\n  cmdline.add_options()\n    ( \"nx-value\"\n      , value<boost::uint64_t>()->default_value(5)\n      , \"nx parameter of the wave equation\")\n\n    ( \"nt-value\"\n      , value<boost::uint64_t>()->default_value(10)\n      , \"nt parameter of the wave equation\")\n\n    ( \"npredict-value\"\n      , value<boost::uint64_t>()->default_value(10)\n      , \"prediction parameter of the wave equation\")\n\n      ( \"ptime-value\"\n      , value<double>()->default_value(2.50)\n      , \"Physics time to run the simulation to\")\n    ;\n\n\n\n  // Initialize and run HPX.\n  return init(cmdline, argc, argv);\n}\n\n", "meta": {"hexsha": "0ecc1bdb26c28eb0f406b67beebdb8c5036bdfa6", "size": 23683, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/1d_hydro/1d_hydro_upwind.cpp", "max_stars_repo_name": "Titzi90/hpx", "max_stars_repo_head_hexsha": "150fb0de1cfe40c26a722918097199147957b45c", "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/1d_hydro/1d_hydro_upwind.cpp", "max_issues_repo_name": "Titzi90/hpx", "max_issues_repo_head_hexsha": "150fb0de1cfe40c26a722918097199147957b45c", "max_issues_repo_licenses": ["BSL-1.0"], "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/1d_hydro/1d_hydro_upwind.cpp", "max_forks_repo_name": "Titzi90/hpx", "max_forks_repo_head_hexsha": "150fb0de1cfe40c26a722918097199147957b45c", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.4098143236, "max_line_length": 149, "alphanum_fraction": 0.6431195372, "num_tokens": 6726, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6076631840431539, "lm_q2_score": 0.5467381519846138, "lm_q1q2_score": 0.33223264627284027}}
{"text": "#ifndef INVKIN_H_INCLUDED\n#define INVKIN_H_INCLUDED\n\n#include \"pinocchio/math/rpy.hpp\"\n#include \"pinocchio/spatial/explog.hpp\"\n#include <Eigen/Core>\n#include <Eigen/Dense>\n#include <cmath>\n#include <fstream>\n#include <iostream>\n#include <string>\n\nclass InvKin\n{\npublic:\n    InvKin();\n    InvKin(double dt_in);\n\n    Eigen::Matrix<double, 1, 3> cross3(Eigen::Matrix<double, 1, 3> left, Eigen::Matrix<double, 1, 3> right);\n\n    Eigen::MatrixXd refreshAndCompute(const Eigen::MatrixXd& x_cmd, const Eigen::MatrixXd& contacts,\n                                      const Eigen::MatrixXd& goals, const Eigen::MatrixXd& vgoals, const Eigen::MatrixXd& agoals,\n                                      const Eigen::MatrixXd& posf, const Eigen::MatrixXd& vf, const Eigen::MatrixXd& wf, const Eigen::MatrixXd& af,\n                                      const Eigen::MatrixXd& Jf, const Eigen::MatrixXd& posb, const Eigen::MatrixXd& rotb, const Eigen::MatrixXd& vb,\n                                      const Eigen::MatrixXd& ab, const Eigen::MatrixXd& Jb);\n    Eigen::MatrixXd computeInvKin(const Eigen::MatrixXd& posf, const Eigen::MatrixXd& vf, const Eigen::MatrixXd& wf, const Eigen::MatrixXd& af,\n                                  const Eigen::MatrixXd& Jf, const Eigen::MatrixXd& posb, const Eigen::MatrixXd& rotb, const Eigen::MatrixXd& vb, const Eigen::MatrixXd& ab,\n                                  const Eigen::MatrixXd& Jb);\n    Eigen::MatrixXd get_q_step();\n    Eigen::MatrixXd get_dq_cmd();\n\nprivate:\n    // Inputs of the constructor\n    double dt;  // Time step of the contact sequence (time step of the MPC)\n\n    // Matrices initialisation\n    Eigen::Matrix<double, 4, 3> feet_position_ref = Eigen::Matrix<double, 4, 3>::Zero();\n    Eigen::Matrix<double, 4, 3> feet_velocity_ref = Eigen::Matrix<double, 4, 3>::Zero();\n    Eigen::Matrix<double, 4, 3> feet_acceleration_ref = Eigen::Matrix<double, 4, 3>::Zero();\n    Eigen::Matrix<double, 1, 4> flag_in_contact = Eigen::Matrix<double, 1, 4>::Zero();\n    Eigen::Matrix<double, 3, 3> base_orientation_ref = Eigen::Matrix<double, 3, 3>::Zero();\n    Eigen::Matrix<double, 1, 3> base_angularvelocity_ref = Eigen::Matrix<double, 1, 3>::Zero();\n    Eigen::Matrix<double, 1, 3> base_angularacceleration_ref = Eigen::Matrix<double, 1, 3>::Zero();\n    Eigen::Matrix<double, 1, 3> base_position_ref = Eigen::Matrix<double, 1, 3>::Zero();\n    Eigen::Matrix<double, 1, 3> base_linearvelocity_ref = Eigen::Matrix<double, 1, 3>::Zero();\n    Eigen::Matrix<double, 1, 3> base_linearacceleration_ref = Eigen::Matrix<double, 1, 3>::Zero();\n    Eigen::Matrix<double, 6, 1> x_ref = Eigen::Matrix<double, 6, 1>::Zero();\n    Eigen::Matrix<double, 6, 1> x = Eigen::Matrix<double, 6, 1>::Zero();\n    Eigen::Matrix<double, 6, 1> dx_ref = Eigen::Matrix<double, 6, 1>::Zero();\n    Eigen::Matrix<double, 6, 1> dx = Eigen::Matrix<double, 6, 1>::Zero();\n    Eigen::Matrix<double, 18, 18> J = Eigen::Matrix<double, 18, 18>::Zero();\n    Eigen::Matrix<double, 18, 18> invJ = Eigen::Matrix<double, 18, 18>::Zero();\n    Eigen::Matrix<double, 1, 18> acc = Eigen::Matrix<double, 1, 18>::Zero();\n    Eigen::Matrix<double, 1, 18> x_err = Eigen::Matrix<double, 1, 18>::Zero();\n    Eigen::Matrix<double, 1, 18> dx_r = Eigen::Matrix<double, 1, 18>::Zero();\n\n    Eigen::Matrix<double, 4, 3> pfeet_err = Eigen::Matrix<double, 4, 3>::Zero();\n    Eigen::Matrix<double, 4, 3> vfeet_ref = Eigen::Matrix<double, 4, 3>::Zero();\n    Eigen::Matrix<double, 4, 3> afeet = Eigen::Matrix<double, 4, 3>::Zero();\n    Eigen::Matrix<double, 1, 3> e_basispos = Eigen::Matrix<double, 1, 3>::Zero();\n    Eigen::Matrix<double, 1, 3> abasis = Eigen::Matrix<double, 1, 3>::Zero();\n    Eigen::Matrix<double, 1, 3> e_basisrot = Eigen::Matrix<double, 1, 3>::Zero();\n    Eigen::Matrix<double, 1, 3> awbasis = Eigen::Matrix<double, 1, 3>::Zero();\n\n    Eigen::MatrixXd ddq = Eigen::MatrixXd::Zero(18, 1);\n    Eigen::MatrixXd q_step = Eigen::MatrixXd::Zero(18, 1);\n    Eigen::MatrixXd dq_cmd = Eigen::MatrixXd::Zero(18, 1);\n\n    // Gains\n    double Kp_base_orientation = 100.0;\n    double Kd_base_orientation = 2.0 * std::sqrt(Kp_base_orientation);\n\n    double Kp_base_position = 100.0;\n    double Kd_base_position = 2.0 * std::sqrt(Kp_base_position);\n\n    double Kp_flyingfeet = 1000.0;\n    double Kd_flyingfeet = 5.0 * std::sqrt(Kp_flyingfeet);\n};\n\ntemplate <typename _Matrix_Type_>\n_Matrix_Type_ pseudoInverse(const _Matrix_Type_& a, double epsilon = std::numeric_limits<double>::epsilon())\n{\n    Eigen::JacobiSVD<_Matrix_Type_> svd(a, Eigen::ComputeThinU | Eigen::ComputeThinV);\n    double tolerance = epsilon * static_cast<double>(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#endif  // INVKIN_H_INCLUDED\n", "meta": {"hexsha": "d584d939e8b61dbbc27026699ec223e443a2ef8c", "size": 4888, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/qrw/InvKin.hpp", "max_stars_repo_name": "thomascbrs/quadruped-reactive-walking", "max_stars_repo_head_hexsha": "38553b3fd14dab3dd989a3488d4077df73cb2d26", "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/qrw/InvKin.hpp", "max_issues_repo_name": "thomascbrs/quadruped-reactive-walking", "max_issues_repo_head_hexsha": "38553b3fd14dab3dd989a3488d4077df73cb2d26", "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/qrw/InvKin.hpp", "max_forks_repo_name": "thomascbrs/quadruped-reactive-walking", "max_forks_repo_head_hexsha": "38553b3fd14dab3dd989a3488d4077df73cb2d26", "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": 55.5454545455, "max_line_length": 174, "alphanum_fraction": 0.6515957447, "num_tokens": 1447, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.8006919830720203, "lm_q2_score": 0.41489884579676883, "lm_q1q2_score": 0.3322061796153072}}
{"text": "\n\n/* --------------------------------------------------------------------- \n * \n * Copyright (C) 2001 - 2021 by the deal.II authors \n * \n * This file is part of the deal.II library. \n * \n * The deal.II library is free software; you can use it, redistribute \n * it, and/or modify it under the terms of the GNU Lesser General \n * Public License as published by the Free Software Foundation; either \n * version 2.1 of the License, or (at your option) any later version. \n * The full text of the license can be found in the file LICENSE.md at \n * the top level directory of deal.II. \n * \n * --------------------------------------------------------------------- \n * \n * Author: Wolfgang Bangerth, University of Heidelberg, 2001, 2002 \n */ \n\n\n\n// 像所有的程序一样，我们从库中的include文件列表开始，像往常一样，它们的标准顺序是 <code>base</code>  --  <code>lac</code> -- <code>grid</code> -- <code>dofs</code>  --  <code>fe</code> -- <code>numerics</code> （因为每一类大致都是建立在前面的基础上），然后是C++标准头文件。\n\n#include <deal.II/base/quadrature_lib.h> \n#include <deal.II/base/function.h> \n#include <deal.II/base/logstream.h> \n#include <deal.II/base/table_handler.h> \n#include <deal.II/base/thread_management.h> \n#include <deal.II/base/work_stream.h> \n#include <deal.II/lac/vector.h> \n#include <deal.II/lac/full_matrix.h> \n#include <deal.II/lac/sparse_matrix.h> \n#include <deal.II/lac/dynamic_sparsity_pattern.h> \n#include <deal.II/lac/solver_cg.h> \n#include <deal.II/lac/precondition.h> \n#include <deal.II/lac/affine_constraints.h> \n#include <deal.II/grid/tria.h> \n#include <deal.II/grid/grid_generator.h> \n#include <deal.II/grid/grid_refinement.h> \n#include <deal.II/dofs/dof_handler.h> \n#include <deal.II/dofs/dof_tools.h> \n#include <deal.II/fe/fe_q.h> \n#include <deal.II/fe/fe_values.h> \n#include <deal.II/numerics/vector_tools.h> \n#include <deal.II/numerics/matrix_tools.h> \n#include <deal.II/numerics/data_out.h> \n#include <deal.II/numerics/error_estimator.h> \n\n// 现在是C++标准头文件。\n\n#include <iostream> \n#include <fstream> \n#include <list> \n\n// 最后一步和以前所有的程序一样。\n\nnamespace Step13 \n{ \n  using namespace dealii; \n// @sect3{Evaluation of the solution}  \n\n// 至于程序本身，我们首先定义了评估拉普拉斯方程解的类。事实上，它们可以评估每一种解，只要它是由一个 <code>DoFHandler</code> 对象和一个解向量描述的。我们首先在这里定义它们，甚至在实际生成要评估的解的类之前，因为我们需要声明一个抽象的基类，以便解算器类可以引用。\n\n// 从抽象的角度来看，我们声明一个纯粹的基类，它提供了一个评估算子（），它将对解进行评估（无论派生类如何考虑 <code>evaluation</code>  ）。由于这是该基类唯一真正的功能（除了一些簿记机器），我们通常把这样一个只有 <code>operator()</code> 的类称为C++术语中的 <code>functor</code> ，因为它的使用就像一个函数对象。\n\n// 这种函数类型的对象随后将被传递给求解器对象，后者将其应用于刚刚计算出的解决方案。然后，评估对象可以从解决方案中提取他们喜欢的任何数量。将这些评估函数放入一个单独的类的层次结构的好处是，在设计上它们不能使用求解器对象的内部结构，因此独立于求解器工作方式的变化。此外，在不修改求解器类的情况下编写另一个评价类是很容易的，这就加快了编程速度（不能使用另一个类的内部结构也意味着你不必担心它们--对评价器的编程通常是一个相当快的任务），以及编译速度（如果求解器和评价类被放在不同的文件中：求解器只需要看到抽象基类的声明，因此在增加一个新的评价类或修改一个旧的类时不需要被重新编译）。 与此相关的是，你可以在其他项目中重复使用这些评估类，解决不同的方程。\n\n// 为了提高代码在不同模块中的分离度，我们把评估类放到了一个自己的命名空间中。这使得在同一个程序中实际解决不同的方程更加容易，通过现有的构件进行组装。这样做的原因是，用于类似目的的类往往具有相同的名称，尽管它们是在不同的背景下开发的。为了能够在一个程序中一起使用它们，有必要将它们放在不同的命名空间中。我们在这里就是这样做的。\n\n  namespace Evaluation \n  { \n\n// 现在是评估类的抽象基类：它的主要目的是声明一个纯虚函数 <code>operator()</code> ，接收一个 <code>DoFHandler</code> 对象和解向量。为了能够只使用指向这个基类的指针，它还必须声明一个虚拟的析构器，但这个析构器什么也不做。除此之外，它只提供了一点簿记功能：由于我们通常想在后续的细化水平上评估解决方案，我们存储了当前细化周期的编号，并提供了一个函数来改变这个编号。\n\n    template <int dim> \n    class EvaluationBase \n    { \n    public: \n      virtual ~EvaluationBase() = default; \n\n      void set_refinement_cycle(const unsigned int refinement_cycle); \n\n      virtual void operator()(const DoFHandler<dim> &dof_handler, \n                              const Vector<double> & solution) const = 0; \n\n    protected: \n      unsigned int refinement_cycle; \n    }; \n\n    template <int dim> \n    void EvaluationBase<dim>::set_refinement_cycle(const unsigned int step) \n    { \n      refinement_cycle = step; \n    } \n// @sect4{%Point evaluation}  \n\n// 下一件事是实现实际的评估类。正如介绍中指出的，我们想从解决方案中提取一个点值，所以第一个类在它的 <code>operator()</code> 中做这个。实际的点是通过构造函数给这个类的，还有一个表格对象，它将把它的发现放入其中。\n\n// 如果我们不能依靠知道实际使用的有限元，那么找出任意点的有限元域的值是相当困难的，因为这样我们就不能，例如，在节点之间进行插值。因此，为了简单起见，我们在这里假设我们要评估场的点实际上是一个节点。如果在求解的过程中，我们发现我们在所有顶点上循环时没有遇到这个点，那么我们就必须抛出一个异常，以便向调用的函数发出信号，说明出了问题，而不是默默地忽略这个错误。\n\n// 在  step-9  示例程序中，我们已经看到如何使用  <code>DeclExceptionN</code>  宏来声明这样一个异常类。我们在这里再次使用这种机制。\n\n// 由此可见，这个类的实际声明应该是很明显的。请注意，即使我们没有明确地列出一个析构器，编译器也会生成一个隐含的析构器，而且它和基类的析构器一样是虚拟的。\n\n    template <int dim> \n    class PointValueEvaluation : public EvaluationBase<dim> \n    { \n    public: \n      PointValueEvaluation(const Point<dim> &evaluation_point, \n                           TableHandler &    results_table); \n\n      virtual void operator()(const DoFHandler<dim> &dof_handler, \n                              const Vector<double> & solution) const override; \n\n      DeclException1( \n        ExcEvaluationPointNotFound, \n        Point<dim>, \n        << \"The evaluation point \" << arg1 \n        << \" was not found among the vertices of the present grid.\"); \n\n \n      const Point<dim> evaluation_point; \n      TableHandler &   results_table; \n    }; \n\n// 至于定义，构造函数是微不足道的，只是接收数据并将其存储在对象本地的。\n\n    template <int dim> \n    PointValueEvaluation<dim>::PointValueEvaluation( \n      const Point<dim> &evaluation_point, \n      TableHandler &    results_table) \n      : evaluation_point(evaluation_point) \n      , results_table(results_table) \n    {} \n\n// 现在是本类中主要感兴趣的函数，即点值的计算。\n\n    template <int dim> \n    void PointValueEvaluation<dim>:: \n         operator()(const DoFHandler<dim> &dof_handler, \n               const Vector<double> & solution) const \n    { \n\n// 首先分配一个变量，用来保存点值。用一个明显是假的值来初始化它，这样如果我们不能把它设置成一个合理的值，我们就会马上注意到。这在像本函数这样小的函数中可能没有必要，因为我们在这里可以很容易地看到所有可能的执行路径，但事实证明它对更复杂的情况是有帮助的，所以我们在这里也采用了这个策略。\n\n      double point_value = 1e20; \n//然后\n//循环所有单元格及其所有顶点，并检查顶点是否与评估点匹配。如果是这样，就提取点的值，设置一个标志，表示我们已经找到了感兴趣的点，然后退出循环。\n\n      bool evaluation_point_found = false; \n      for (const auto &cell : dof_handler.active_cell_iterators()) \n        if (!evaluation_point_found) \n          for (const auto vertex : GeometryInfo<dim>::vertex_indices()) \n            if (cell->vertex(vertex) == evaluation_point) \n              { \n\n// 为了从全局解决方案矢量中提取点值，挑选属于感兴趣的顶点的那个分量，如果解决方案是矢量值的，则取其第一个分量。\n\n                point_value = solution(cell->vertex_dof_index(vertex, 0)); \n\n// 请注意，我们在这里做了一个假设，这个假设并不总是有效的，如果这是实际应用的代码，而不是一个教程程序，就应该在类的声明中记录下来：我们假设用于我们试图评估的解决方案的有限元实际上有与顶点相关的自由度。例如，这对不连续元素来说是不成立的，因为形状函数的支持点恰好位于顶点，但不与顶点相关，而是与单元内部相关，因为与顶点相关意味着那里的连续性。这对于面向边缘的元素等也是不成立的。            理想情况下，我们会在函数开始时检查这一点，例如通过一个类似<code>Assert (dof_handler.get_fe().dofs_per_vertex  @>  0, ExcNotImplemented())</code>的语句，这应该可以在异常触发时很清楚地说明问题所在。在这种情况下，我们省略了它（这的确是不好的风格），但是知道这一点在这里并没有什么坏处，因为如果我们要求语句 <code>cell-@>vertex_dof_index(vertex,0)</code> 给我们顶点的DoF索引，如果没有的话，语句就会失败。            我们再次强调，这种对允许的有限元的限制应该在类的文档中说明。\n\n// 由于我们找到了正确的点，我们现在设置相应的标志并退出最里面的循环。由于设置了标志，外循环也将被终止。\n\n                evaluation_point_found = true; \n                break; \n              }; \n\n// 最后，我们要确定我们确实已经找到了评估点，因为如果不是这样，我们就不能在那里给出一个合理的解的值，反正剩下的计算也是无用的。所以通过 <code>AssertThrow</code> 程序中已经使用的 step-9 宏，确保我们确实找到了这个点。如果不是这样，这个宏就会抛出一个作为第二个参数给它的类型的异常，但与直接的 <code>throw</code> 语句相比，它在异常对象中填充了一组额外的信息，例如，产生异常的源文件和行号，以及失败的条件。如果你在你的主函数里有一个 <code>catch</code> 子句（就像这个程序一样），你会捕捉到所有没有在中间某个地方捕捉到的、因而已经处理过的异常，这些额外的信息会帮助你找出发生了什么以及哪里出了问题。\n\n      AssertThrow(evaluation_point_found, \n                  ExcEvaluationPointNotFound(evaluation_point)); \n\n// 注意，我们在其他示例程序中也使用了 <code>Assert</code> 宏。它与这里使用的 <code>AssertThrow</code> 宏不同的是，它只是中止程序，而不是抛出一个异常，而且它只在调试模式下这样做。它是用来检查作为参数传递给函数的向量大小的正确宏，以及类似的。\n\n// 然而，这里的情况是不同的：我们是否找到评估点可能会在不同的细化过程中发生变化（例如，如果点周围的四个单元被粗化掉了，那么在细化和粗化之后，点可能会消失）。这是在调试模式下无法预测的事情，但应该经常检查，在生产运行中也是如此。因此，这里使用了 <code>AssertThrow</code> 宏。\n\n// 现在，如果我们确信我们已经找到了评估点，我们可以把结果加入到结果表中。\n\n      results_table.add_value(\"DoFs\", dof_handler.n_dofs()); \n      results_table.add_value(\"u(x_0)\", point_value); \n    } \n\n//  @sect4{Generating output}  \n\n// 一种不同的，也许略显奇怪的 <code>evaluation</code> 的解决方案是将其以图形格式输出到一个文件中。因为在评估函数中，我们得到了一个 <code>DoFHandler</code> 对象和解决方案的向量，我们已经有了做这件事所需要的一切，所以我们可以在评估类中做这件事。实际上这样做而不是把它放到计算解决方案的类中的原因是，这样我们有更多的灵活性：如果我们选择只输出它的某些方面，或者根本不输出它。在任何情况下，我们都不需要修改求解器类，我们只需要修改其中的一个模块，就可以构建这个程序了。如上所述，这种形式的封装可以帮助我们保持程序的每个部分相当简单，因为接口保持简单，不可能访问隐藏的数据。\n\n// 由于这个生成输出的类是从普通的 <code>EvaluationBase</code> 基类派生出来的，它的主要接口是 <code>operator()</code> 函数。此外，它有一个构造函数，接收一个字符串，该字符串将被用作文件名的基本部分，输出将被发送到该文件名中（我们将用一个数字来增加它，表示细化周期的数量--基类手头有这个信息--以及一个后缀），构造函数还接收一个值，表示要求的格式，即我们将为哪个图形程序生成输出（然后我们也将从这个值中生成我们写入的文件名后缀）。\n\n// 关于输出格式，DataOutBase命名空间提供了一个枚举字段 DataOutBase::OutputFormat ，列出了所有支持的输出格式的名称。在编写本程序时，支持的图形格式由枚举值 <code>ucd</code> 、 <code>gnuplot</code>, <code>povray</code>, <code>eps</code> 、 <code>gmv</code>, <code>tecplot</code>, <code>tecplot_binary</code> 、 <code>dx</code>, <code>vtk</code> 等表示，但这个列表肯定会随着时间而增加。现在，在该基类的各种函数中，你可以使用这种类型的值来获得关于这些图形格式的信息（例如每种格式的文件所使用的默认后缀），你可以调用一个通用的 <code>write</code> 函数，然后根据给它的第二个参数的值表示所需的输出格式，将其分支到我们在以前的例子中已经使用的 <code>write_gnuplot</code>, <code>write_ucd</code> 等函数。这种机制使得编写一个可扩展的程序变得很简单，它可以在运行时决定使用哪种输出格式，同时也使得编写程序的方式变得相当简单，它可以利用新实现的输出格式，而不需要改变应用程序。\n\n// 在这两个字段中，即基本名称和输出格式描述符，构造函数取值并存储它们，以便以后由实际的评估函数使用。\n\n    template <int dim> \n    class SolutionOutput : public EvaluationBase<dim> \n    { \n    public: \n      SolutionOutput(const std::string &             output_name_base, \n                     const DataOutBase::OutputFormat output_format); \n\n      virtual void operator()(const DoFHandler<dim> &dof_handler, \n                              const Vector<double> & solution) const override; \n\n    private: \n      const std::string               output_name_base; \n      const DataOutBase::OutputFormat output_format; \n    }; \n\n    template <int dim> \n    SolutionOutput<dim>::SolutionOutput( \n      const std::string &             output_name_base, \n      const DataOutBase::OutputFormat output_format) \n      : output_name_base(output_name_base) \n      , output_format(output_format) \n    {} \n\n// 按照上面的描述，生成实际输出的函数现在相对简单了。与以前的例子程序相比，唯一特别有趣的特征是使用了 DataOutBase::default_suffix 函数，返回给定格式文件的通常后缀（例如，\".eps \"用于封装的postscript文件，\".gnuplot \"用于Gnuplot文件），以及带有第二个参数的通用 DataOut::write() 函数，该函数根据作为第二个参数的格式描述符的值，在内部分支到不同图形格式的实际输出函数。\n\n//还要注意，我们必须在 <code>this-@></code> 前加上前缀，以访问依赖模板的基类的成员变量。这里的原因，以及在程序中更进一步的原因，与 step-7 示例程序中描述的相同（在那里寻找 <code>two-stage name lookup</code> ）。\n\n    template <int dim> \n    void SolutionOutput<dim>::operator()(const DoFHandler<dim> &dof_handler, \n                                         const Vector<double> & solution) const \n    { \n      DataOut<dim> data_out; \n      data_out.attach_dof_handler(dof_handler); \n      data_out.add_data_vector(solution, \"solution\"); \n      data_out.build_patches(); \n\n      std::ofstream out(output_name_base + \"-\" + \n                        std::to_string(this->refinement_cycle) + \n                        data_out.default_suffix(output_format)); \n\n      data_out.write(out, output_format); \n    } \n\n//  @sect4{Other evaluations}  \n\n// 在实际应用中，人们会在这里添加一个其他可能的评价类的列表，代表人们可能感兴趣的数量。对于这个例子，这些就足够了，所以我们关闭命名空间。\n\n  } // namespace Evaluation \n// @sect3{The Laplace solver classes}  \n\n// 在定义了我们想知道的解决方案之后，我们现在应该关心如何去获得它。我们将把所有我们需要的东西都打包到一个自己的命名空间中，原因和上面的评估差不多。\n\n// 由于我们在前面的例子中已经相当详细地讨论了拉普拉斯求解器，所以下面就没有什么新东西了。相反，我们在很大程度上拆解了以前的例子，并以稍微不同的形式把它们放到这个例子程序中。因此，我们将主要讨论与以前的例子的不同之处。\n\n// 基本上，正如在介绍中已经说过的，这个例子中缺乏新的东西是故意的，因为它更多地是为了展示软件设计的实践，而不是数学。因此，下面解释的重点将更多地放在实际的实现上。\n\n  namespace LaplaceSolver \n  { \n// @sect4{An abstract base class}  \n\n// 在定义拉普拉斯求解器时，我们首先声明一个抽象的基类，它本身没有任何功能，只是接受和存储一个指向三角形的指针，以便以后使用。\n\n// 这个基类是非常通用的，也可以用于任何其他静止问题。它提供了一些函数的声明，这些函数将在派生类中分别解决一个问题，用评估对象的列表对解决方案进行后处理，以及细化网格。在基类中，这些函数本身都没有做什么。\n\n// 由于缺乏实际功能，声明非常抽象的基类的编程风格类似于Smalltalk或Java程序中使用的风格，所有的类都是从完全抽象的类派生出来的 <code>Object</code>  ，甚至是数字表示。作者承认，他并不特别喜欢在C++中使用这种风格，因为它将风格置于理性之上。此外，它提倡对一切事物使用虚拟函数（例如，在Java中，所有的函数本身就是虚拟的），然而，这在许多应用中被证明是相当低效的，在这些应用中，函数往往只是访问数据，而不是进行计算，因此很快就会返回；这样，虚拟函数的开销就会很大。笔者的观点是，只要至少有一部分实际实现的代码可以被共享，从而被分离到基类中，就应该有抽象的基类。\n\n// 除了这些理论上的问题，我们在这里还有一个很好的理由，这个理由在下面会让读者更清楚。基本上，我们希望能够有一个不同的拉普拉斯求解器家族，这些求解器的差别很大，以至于无法找到更大的共同功能子集。因此，我们只是声明了这样一个抽象的基类，在构造函数中获取一个指向三角形的指针，并从此存储它。由于这个三角剖分将在所有的计算中使用，我们必须确保这个三角剖分在最后使用之前是有效的。我们通过保留一个 <code>SmartPointer</code> 到这个三角剖分来做到这一点，正如 step-7 中所解释的。\n\n// 注意，虽然指针本身被声明为常数（即在这个对象的整个生命周期中，指针指向同一个对象），但它没有被声明为指向一个常数三角的指针。事实上，通过这种方式，我们允许派生类在 <code>refine_grid</code> 函数中细化或粗化三角结构。\n\n// 最后，我们有一个函数 <code>n_dofs</code> 只是驱动函数的一个工具，用来决定我们是否要继续进行网格细化。它返回当前模拟的自由度数量。\n\n    template <int dim> \n    class Base \n    { \n    public: \n      Base(Triangulation<dim> &coarse_grid); \n      virtual ~Base() = default; \n\n      virtual void solve_problem() = 0; \n      virtual void postprocess( \n        const Evaluation::EvaluationBase<dim> &postprocessor) const = 0; \n      virtual void         refine_grid()                            = 0; \n      virtual unsigned int n_dofs() const                           = 0; \n\n    protected: \n      const SmartPointer<Triangulation<dim>> triangulation; \n    }; \n\n// 仅有的两个非抽象函数的实现就相当无聊了。\n\n    template <int dim> \n    Base<dim>::Base(Triangulation<dim> &coarse_grid) \n      : triangulation(&coarse_grid) \n    {} \n// @sect4{A general solver class}  \n\n// 下面是主类，它实现了组装线性系统的矩阵，解决它，并在解决方案上调用后处理器对象。它实现了基类中声明的  <code>solve_problem</code>  和  <code>postprocess</code>  函数。然而，它并没有实现 <code>refine_grid</code> 方法，因为网格细化将在一些派生类中实现。\n\n// 它还声明了一个新的抽象虚函数， <code>assemble_rhs</code>  ，需要在子类中重载。原因是我们将实现两个不同的类，它们将实现不同的方法来组装右手边的向量。这个函数在以下情况下可能也很有趣：右手边不仅仅取决于一个连续函数，还取决于其他东西，例如另一个离散问题的解，等等。后者经常发生在非线性问题中。\n\n// 正如我们之前提到的，这门课的实际内容并不是新的，而是以前的例子中已经使用过的各种技术的混合。因此，我们将不对它们进行详细讨论，而是让读者参考这些程序。\n\n// 基本上，用几句话来说，这个类的构造函数接收指向一个三角形、一个有限元和一个代表边界值的函数对象的指针。这些东西或者被传递给基类的构造函数，或者被存储起来并在以后用来生成一个 <code>DoFHandler</code> 对象。由于有限元和正交公式应该是匹配的，所以它也被传递给一个正交对象。\n\n//  <code>solve_problem</code> 为实际求解设置数据结构，调用函数来组装线性系统，并求解它。\n\n//  <code>postprocess</code> 函数最后接收一个评估对象并将其应用于计算出的解决方案。\n\n//  <code>n_dofs</code> 函数最后实现了基类的纯虚拟函数。\n\n    template <int dim> \n    class Solver : public virtual Base<dim> \n    { \n    public: \n      Solver(Triangulation<dim> &      triangulation, \n             const FiniteElement<dim> &fe, \n             const Quadrature<dim> &   quadrature, \n             const Function<dim> &     boundary_values); \n      virtual ~Solver() override; \n\n      virtual void solve_problem() override; \n\n      virtual void postprocess(\n        const Evaluation::EvaluationBase<dim> &postprocessor) const override; \n\n      virtual unsigned int n_dofs() const override; \n\n// 在这个类的保护部分，我们首先有一些成员变量，其用途在前面的例子中应该很清楚。\n\n    protected: \n      const SmartPointer<const FiniteElement<dim>> fe; \n      const SmartPointer<const Quadrature<dim>>    quadrature; \n      DoFHandler<dim>                              dof_handler; \n      Vector<double>                               solution; \n      const SmartPointer<const Function<dim>>      boundary_values; \n\n// 然后我们声明一个抽象函数，该函数将用于组装右手边的内容。如上所述，在各种情况下，这个动作的必要性有很大的不同，所以我们将其推迟到派生类中。\n\n      virtual void assemble_rhs(Vector<double> &rhs) const = 0; \n\n// 接下来，在私有部分，我们有一个小类，它代表了整个线性系统，即一个矩阵、一个右手边和一个解向量，以及应用于它的约束，如那些由于悬挂节点而产生的约束。它的构造函数初始化了各种子对象，还有一个函数实现了共轭梯度法作为求解器。\n\n    private: \n      struct LinearSystem \n      { \n        LinearSystem(const DoFHandler<dim> &dof_handler); \n\n        void solve(Vector<double> &solution) const; \n\n        AffineConstraints<double> hanging_node_constraints; \n        SparsityPattern           sparsity_pattern; \n        SparseMatrix<double>      matrix; \n        Vector<double>            rhs; \n      }; \n\n// 最后，有一组函数将被用来组装实际的系统矩阵。这一组的主函数 <code>assemble_linear_system()</code> 使用以下两个辅助函数，在多核系统上并行计算矩阵。这样做的机制与  step-9  示例程序相同，并遵循  @ref threads  中概述的 WorkStream 概念。主函数还调用了组装右手边的虚拟函数。\n\n      struct AssemblyScratchData \n      { \n        AssemblyScratchData(const FiniteElement<dim> &fe, \n                            const Quadrature<dim> &   quadrature); \n        AssemblyScratchData(const AssemblyScratchData &scratch_data); \n\n        FEValues<dim> fe_values;\n      };\n\n \n \n\n      struct AssemblyCopyData \n      { \n        FullMatrix<double>                   cell_matrix; \n        std::vector<types::global_dof_index> local_dof_indices; \n      }; \n\n      void assemble_linear_system(LinearSystem &linear_system); \n\n      void local_assemble_matrix( \n        const typename DoFHandler<dim>::active_cell_iterator &cell, \n        AssemblyScratchData &                                 scratch_data, \n        AssemblyCopyData &                                    copy_data) const; \n\n      void copy_local_to_global(const AssemblyCopyData &copy_data, \n                                LinearSystem &          linear_system) const; \n    }; \n\n// 现在是该类的构造函数。它没有做什么，只是存储了给定对象的指针，并生成了 <code>DoFHandler</code> 对象，初始化了给定的三角形的指针。这使得DoF处理程序存储该指针，但并没有生成有限元编号（我们只在 <code>solve_problem</code> 函数中要求这样做）。\n\n    template <int dim> \n    Solver<dim>::Solver(Triangulation<dim> &      triangulation, \n                        const FiniteElement<dim> &fe, \n                        const Quadrature<dim> &   quadrature, \n                        const Function<dim> &     boundary_values) \n      : Base<dim>(triangulation) \n      , fe(&fe) \n      , quadrature(&quadrature) \n      , dof_handler(triangulation) \n      , boundary_values(&boundary_values) \n    {} \n\n// 解构器很简单，它只是清除存储在DoF处理程序对象中的信息以释放内存。\n\n    template <int dim> \n    Solver<dim>::~Solver() \n    { \n      dof_handler.clear(); \n    } \n\n// 下一个函数是解决这个问题的主要工作：它用给这个对象的构造函数的有限元来设置DoF处理程序对象，创建一个表示线性系统的对象（即矩阵、右手向量和解向量），调用函数来组装它，最后解决它。\n\n    template <int dim> \n    void Solver<dim>::solve_problem() \n    { \n      dof_handler.distribute_dofs(*fe); \n      solution.reinit(dof_handler.n_dofs()); \n\n      LinearSystem linear_system(dof_handler); \n      assemble_linear_system(linear_system); \n      linear_system.solve(solution); \n    } \n\n// 如上所述， <code>postprocess</code> 函数接收一个评估对象，并将其应用于计算的解决方案。这个函数可以被多次调用，对用户要求的每一个解的评估都要调用一次。\n\n    template <int dim> \n    void Solver<dim>::postprocess( \n      const Evaluation::EvaluationBase<dim> &postprocessor) const \n    { \n      postprocessor(dof_handler, solution); \n    } \n\n//  <code>n_dofs</code> 函数应该是不言自明的。\n\n    template <int dim> \n    unsigned int Solver<dim>::n_dofs() const \n    { \n      return dof_handler.n_dofs(); \n    } \n\n// 下面的函数在每一步中组装矩阵和要解决的线性系统的右手边。我们将在几个层面上并行地做事情。首先，请注意，我们需要组装矩阵和右手边。这些都是独立的操作，我们应该并行地进行这些操作。为此，我们使用 @ref threads 文档模块中讨论的 \"任务 \"概念。本质上，我们想说的是 \"这里有一些需要处理的事情，只要有CPU核可用就去做\"，然后再做其他事情，当我们需要第一个操作的结果时，就等待它的完成。在第二层，我们想使用与我们在 step-9 中已经使用过的完全相同的策略来组装矩阵，即WorkStream概念。\n\n// 虽然我们可以考虑在做另一件事的时候在后台组装右侧或组装矩阵，但我们将选择前一种方法，只是因为调用 <code>Solver::assemble_rhs</code> 比调用 WorkStream::run 及其许多参数要简单得多。在任何情况下，代码看起来像这样，以组装整个线性系统。\n\n    template <int dim> \n    void Solver<dim>::assemble_linear_system(LinearSystem &linear_system) \n    { \n      Threads::Task<void> rhs_task = \n        Threads::new_task(&Solver<dim>::assemble_rhs, *this, linear_system.rhs); \n\n      auto worker = \n        [this](const typename DoFHandler<dim>::active_cell_iterator &cell, \n               AssemblyScratchData &scratch_data, \n               AssemblyCopyData &   copy_data) { \n          this->local_assemble_matrix(cell, scratch_data, copy_data); \n        }; \n\n      auto copier = [this, &linear_system](const AssemblyCopyData &copy_data) { \n        this->copy_local_to_global(copy_data, linear_system); \n      }; \n\n      WorkStream::run(dof_handler.begin_active(), \n                      dof_handler.end(), \n                      worker, \n                      copier, \n                      AssemblyScratchData(*fe, *quadrature), \n                      AssemblyCopyData()); \n      linear_system.hanging_node_constraints.condense(linear_system.matrix); \n\n// 上面的语法需要一些解释。 WorkStream::run 有多个版本，期待不同的参数。在  step-9  中，我们使用了一个版本，它需要一对迭代器、一对指向具有非常具体的参数列表的成员函数的指针、一个指向这些成员函数必须工作的对象的指针或引用，以及一个抓取和复制数据对象。这有点限制性，因为这样调用的成员函数的参数列表必须与 WorkStream::run 所期望的完全一致：本地装配函数需要接收一个迭代器、一个抓取对象和一个复制对象；而复制-本地-全局函数需要接收的正是一个复制对象。但是，如果我们想要的东西稍微更通用一些呢？例如，在目前的程序中，copy-local-to-global函数需要知道将本地贡献写入哪个线性系统对象中，也就是说，它还必须接受一个 <code>LinearSystem</code> 参数。这在使用成员函数指针的方法中是行不通的。\n\n// 幸运的是，C++提供了一条出路。这些被称为函数对象。本质上， WorkStream::run 想要做的不是调用一个成员函数。它想调用一些函数，这些函数在第一种情况下需要一个迭代器、一个抓取对象和一个拷贝对象，而在第二种情况下需要一个拷贝对象。不管这些是成员函数、全局函数，还是其他什么，对WorkStream来说，真的不是很关心。因此，有第二个版本的函数只接收函数对象--具有  <code>operator()</code>  的对象，因此可以像函数一样被调用，不管它们真正代表什么。产生这种函数对象的典型方法是使用一个<a href=\"http:en.wikipedia.org/wiki/Anonymous_function\">lambda function</a>，它用固定的值来包装函数调用，包括各个参数。所有属于外层函数签名的参数在lambda函数中被指定为常规的函数参数。固定值使用捕获列表（`[...]`）传递到lambda函数中。可以使用捕获默认值，也可以明确列出所有要绑定到lambda的变量。为了清楚起见，我们决定在这里省略捕获默认值，但是捕获列表同样可以是`[&]`，这意味着所有使用的变量都通过引用复制到lambda中。\n\n// 在这一点上，我们已经组装好了矩阵，并将其浓缩。右手边可能已经完全组装好了，也可能还没有，但是我们接下来想浓缩右手边的向量。我们只有在这个向量的组装完成后才能这样做，所以我们必须等待任务的完成；在计算机科学中，等待任务通常被称为 \"加入 \"任务，解释了我们下面调用的函数的名称。\n\n// 既然这个任务可能已经完成，也可能没有完成，既然我们可能要等它完成，我们不妨试着把其他需要完成的事情装进这个空隙。因此，我们首先插值边界值，然后再等待右手边的工作。当然，另一种可能性是在一个单独的任务中也插值边界值，因为这样做与我们到目前为止在这个函数中所做的其他事情无关。请自由地找到正确的语法，为这个插值创建一个任务，并在这个函数的顶部启动它，同时装配右手边。(你会发现这稍微有点复杂，因为 VectorTools::interpolate_boundary_values(), 有多个版本，所以简单地取地址 <code>&VectorTools::interpolate_boundary_values</code> 会产生一组重载函数，不能马上传递给 Threads::new_task() --你必须通过将地址表达式转换为函数指针类型，选择你想要的这个重载集合中的哪个元素，这是你想在任务中调用的特定版本的函数。)\n\n      std::map<types::global_dof_index, double> boundary_value_map; \n      VectorTools::interpolate_boundary_values(dof_handler, \n                                               0, \n                                               *boundary_values, \n                                               boundary_value_map); \n\n      rhs_task.join(); \n      linear_system.hanging_node_constraints.condense(linear_system.rhs); \n\n// 现在我们有了完整的线性系统，我们也可以处理边界值，需要从矩阵和右手边消除。\n\n      MatrixTools::apply_boundary_values(boundary_value_map, \n                                         linear_system.matrix, \n                                         solution, \n                                         linear_system.rhs); \n    } \n\n// 这组函数的后半部分是处理每个单元上的局部装配，并将局部贡献复制到全局矩阵对象中。这与  step-9  中描述的工作方式完全相同。\n\n    template <int dim> \n    Solver<dim>::AssemblyScratchData::AssemblyScratchData( \n      const FiniteElement<dim> &fe, \n      const Quadrature<dim> &   quadrature) \n      : fe_values(fe, quadrature, update_gradients | update_JxW_values) \n    {} \n\n    template <int dim> \n    Solver<dim>::AssemblyScratchData::AssemblyScratchData( \n      const AssemblyScratchData &scratch_data) \n      : fe_values(scratch_data.fe_values.get_fe(), \n                  scratch_data.fe_values.get_quadrature(), \n                  update_gradients | update_JxW_values) \n    {} \n\n    template <int dim> \n    void Solver<dim>::local_assemble_matrix( \n      const typename DoFHandler<dim>::active_cell_iterator &cell, \n      AssemblyScratchData &                                 scratch_data, \n      AssemblyCopyData &                                    copy_data) const \n    { \n      const unsigned int dofs_per_cell = fe->n_dofs_per_cell(); \n      const unsigned int n_q_points    = quadrature->size(); \n\n      copy_data.cell_matrix.reinit(dofs_per_cell, dofs_per_cell); \n\n      copy_data.local_dof_indices.resize(dofs_per_cell); \n\n      scratch_data.fe_values.reinit(cell); \n\n      for (unsigned int q_point = 0; q_point < n_q_points; ++q_point) \n        for (unsigned int i = 0; i < dofs_per_cell; ++i) \n          for (unsigned int j = 0; j < dofs_per_cell; ++j) \n            copy_data.cell_matrix(i, j) += \n              (scratch_data.fe_values.shape_grad(i, q_point) * \n               scratch_data.fe_values.shape_grad(j, q_point) * \n               scratch_data.fe_values.JxW(q_point)); \n\n      cell->get_dof_indices(copy_data.local_dof_indices); \n    } \n\n    template <int dim> \n    void Solver<dim>::copy_local_to_global(const AssemblyCopyData &copy_data, \n                                           LinearSystem &linear_system) const \n    { \n      for (unsigned int i = 0; i < copy_data.local_dof_indices.size(); ++i) \n        for (unsigned int j = 0; j < copy_data.local_dof_indices.size(); ++j) \n          linear_system.matrix.add(copy_data.local_dof_indices[i], \n                                   copy_data.local_dof_indices[j], \n                                   copy_data.cell_matrix(i, j)); \n    } \n\n// 现在是实现线性系统类中动作的函数。首先，构造函数将所有数据元素初始化为正确的大小，并设置了一些额外的数据结构，例如由于悬挂节点而产生的约束。由于设置悬空节点和找出矩阵的非零元素是独立的，所以我们以并行方式进行（如果库被配置为使用并发，至少是这样；否则，这些动作是按顺序执行的）。注意，我们只启动一个线程，并在主线程中做第二个动作。由于只生成了一个任务，我们在这里不使用 <code>Threads::TaskGroup</code> 类，而是直接使用创建的一个任务对象来等待这个特定任务的退出。\n\n// 注意，占用 <code>DoFTools::make_hanging_node_constraints</code> 函数的地址有点麻烦，因为它实际上有三个，每个支持的空间维度都有一个。在C++中，获取重载函数的地址有些复杂，因为在这种情况下，操作符 <code>&</code> 返回的更像是一组值（所有具有该名称的函数的地址），然后选择正确的函数是下一步的工作。如果上下文决定采取哪一个（例如通过分配给一个已知类型的函数指针），那么编译器可以自己做，但如果这组指针应作为一个采取模板的函数的参数，编译器可以选择所有的，而不偏向于一个。因此，我们必须向编译器说明我们想要哪一个；为此，我们可以使用cast，但为了更清楚，我们把它分配给一个具有正确类型的临时 <code>mhnc_p</code> （简称<code>pointer to make_hanging_node_constraints</code>），并使用这个指针代替。\n\n    template <int dim> \n    Solver<dim>::LinearSystem::LinearSystem(const DoFHandler<dim> &dof_handler) \n    { \n      hanging_node_constraints.clear(); \n\n      void (*mhnc_p)(const DoFHandler<dim> &, AffineConstraints<double> &) = \n        &DoFTools::make_hanging_node_constraints; \n\n// 启动一个辅助任务，然后在主线程上继续进行\n\n      Threads::Task<void> side_task = \n        Threads::new_task(mhnc_p, dof_handler, hanging_node_constraints); \n\n      DynamicSparsityPattern dsp(dof_handler.n_dofs(), dof_handler.n_dofs()); \n      DoFTools::make_sparsity_pattern(dof_handler, dsp); \n\n// 等到边上的任务完成后再继续前进\n\n      side_task.join(); \n\n      hanging_node_constraints.close(); \n      hanging_node_constraints.condense(dsp); \n      sparsity_pattern.copy_from(dsp); \n\n// 最后初始化矩阵和右手边的向量\n\n      matrix.reinit(sparsity_pattern); \n      rhs.reinit(dof_handler.n_dofs()); \n    } \n\n// 该类的第二个函数只是通过预处理的共轭梯度法来解决线性系统。这一点之前已经被广泛讨论过了，所以我们不再赘述了。\n\n    template <int dim> \n    void Solver<dim>::LinearSystem::solve(Vector<double> &solution) const \n    { \n      SolverControl            solver_control(1000, 1e-12); \n      SolverCG<Vector<double>> cg(solver_control); \n\n      PreconditionSSOR<SparseMatrix<double>> preconditioner; \n      preconditioner.initialize(matrix, 1.2); \n\n      cg.solve(matrix, solution, rhs, preconditioner); \n\n      hanging_node_constraints.distribute(solution); \n    } \n\n//  @sect4{A primal solver}  \n\n// 在上一节中，我们实现了一个拉普拉斯求解器的基类，该基类缺乏组装右手边向量的功能，但是，由于其中的原因，我们已经解释了。现在我们实现了一个相应的类，它可以在问题的右边以函数对象的形式给出的情况下完成这一工作。\n\n// 这个类的动作和你在以前的例子中已经看到的差不多，所以简单解释一下就够了：构造函数和底层类的数据相同（它把所有的信息传递给底层类），除了一个表示问题右侧的函数对象。这个对象的指针被存储起来（同样作为一个 <code>SmartPointer</code> ，以确保这个函数对象只要还被这个类使用就不会被删除）。\n\n// 这个类的唯一功能部分是 <code>assemble_rhs</code> 方法，它的作用和它的名字一样。\n\n    template <int dim> \n    class PrimalSolver : public Solver<dim> \n    { \n    public: \n      PrimalSolver(Triangulation<dim> &      triangulation, \n                   const FiniteElement<dim> &fe, \n                   const Quadrature<dim> &   quadrature, \n                   const Function<dim> &     rhs_function, \n                   const Function<dim> &     boundary_values); \n\n    protected: \n      const SmartPointer<const Function<dim>> rhs_function; \n      virtual void assemble_rhs(Vector<double> &rhs) const override; \n    }; \n\n// 这个类的构造函数基本上做了上面宣布的事情......\n\n    template <int dim> \n    PrimalSolver<dim>::PrimalSolver(Triangulation<dim> &      triangulation, \n                                    const FiniteElement<dim> &fe, \n                                    const Quadrature<dim> &   quadrature, \n                                    const Function<dim> &     rhs_function, \n                                    const Function<dim> &     boundary_values) \n      : Base<dim>(triangulation) \n      , Solver<dim>(triangulation, fe, quadrature, boundary_values) \n      , rhs_function(&rhs_function) \n    {} \n\n// ... 和 <code>assemble_rhs</code> 函数一样。因为在前面的几个例子程序中已经解释过了，所以我们就不多说了。\n\n    template <int dim> \n    void PrimalSolver<dim>::assemble_rhs(Vector<double> &rhs) const \n    { \n      FEValues<dim> fe_values(*this->fe, \n                              *this->quadrature, \n                              update_values | update_quadrature_points | \n                                update_JxW_values); \n\n      const unsigned int dofs_per_cell = this->fe->n_dofs_per_cell(); \n      const unsigned int n_q_points    = this->quadrature->size(); \n\n      Vector<double>                       cell_rhs(dofs_per_cell);\n      std::vector<double>                  rhs_values(n_q_points); \n      std::vector<types::global_dof_index> local_dof_indices(dofs_per_cell); \n\n      for (const auto &cell : this->dof_handler.active_cell_iterators()) \n        { \n          cell_rhs = 0; \n          fe_values.reinit(cell); \n          rhs_function->value_list(fe_values.get_quadrature_points(), \n                                   rhs_values); \n\n          for (unsigned int q_point = 0; q_point < n_q_points; ++q_point) \n            for (unsigned int i = 0; i < dofs_per_cell; ++i) \n              cell_rhs(i) += fe_values.shape_value(i, q_point) * // \n                             rhs_values[q_point] *               // \n                             fe_values.JxW(q_point); \n\n          cell->get_dof_indices(local_dof_indices); \n          for (unsigned int i = 0; i < dofs_per_cell; ++i) \n            rhs(local_dof_indices[i]) += cell_rhs(i); \n        }; \n    } \n// @sect4{Global refinement}  \n\n// 至此，除了 <code>refine_grid</code> 函数外，抽象基类的所有函数都已实现。现在我们将有两个类为 <code>PrimalSolver</code> 类实现这个函数，一个做全局细化，一个做局部细化的形式。\n\n// 第一个做全局细化的类相当简单：它的主函数只是调用 <code>triangulation-@>refine_global (1);</code> ，它做所有的工作。\n\n// 注意，由于 <code>Base</code> 类的基类是虚拟的，我们必须声明一个构造函数来初始化直接的基类和抽象的虚拟类。\n\n// 除了这个技术上的复杂性之外，这个类可能很简单，可以不做进一步的评论。\n\n    template <int dim> \n    class RefinementGlobal : public PrimalSolver<dim> \n    { \n    public: \n      RefinementGlobal(Triangulation<dim> &      coarse_grid, \n                       const FiniteElement<dim> &fe, \n                       const Quadrature<dim> &   quadrature, \n                       const Function<dim> &     rhs_function, \n                       const Function<dim> &     boundary_values); \n\n      virtual void refine_grid() override; \n    }; \n\n    template <int dim> \n    RefinementGlobal<dim>::RefinementGlobal( \n      Triangulation<dim> &      coarse_grid, \n      const FiniteElement<dim> &fe, \n      const Quadrature<dim> &   quadrature, \n      const Function<dim> &     rhs_function, \n      const Function<dim> &     boundary_values) \n      : Base<dim>(coarse_grid) \n      , PrimalSolver<dim>(coarse_grid, \n                          fe, \n                          quadrature, \n                          rhs_function, \n                          boundary_values) \n    {} \n\n    template <int dim> \n    void RefinementGlobal<dim>::refine_grid() \n    { \n      this->triangulation->refine_global(1); \n    } \n// @sect4{Local refinement by the Kelly error indicator}  \n\n// 第二个实现细化策略的类使用了之前各种示例程序中使用的凯利细化指标。由于这个指标已经在deal.II库中用自己的类实现了，所以这里没有太多的事情要做，只是调用计算指标的函数，然后用它来选择一些单元进行细化和粗化，并相应地对网格进行细化。\n\n// 同样，现在应该足够标准了，可以省去更多的注释。\n\n    template <int dim> \n    class RefinementKelly : public PrimalSolver<dim> \n    { \n    public: \n      RefinementKelly(Triangulation<dim> &      coarse_grid, \n                      const FiniteElement<dim> &fe, \n                      const Quadrature<dim> &   quadrature, \n                      const Function<dim> &     rhs_function, \n                      const Function<dim> &     boundary_values); \n\n      virtual void refine_grid() override; \n    }; \n\n    template <int dim> \n    RefinementKelly<dim>::RefinementKelly(Triangulation<dim> &      coarse_grid, \n                                          const FiniteElement<dim> &fe, \n                                          const Quadrature<dim> &   quadrature, \n                                          const Function<dim> &rhs_function, \n                                          const Function<dim> &boundary_values) \n      : Base<dim>(coarse_grid) \n      , PrimalSolver<dim>(coarse_grid, \n                          fe, \n                          quadrature, \n                          rhs_function, \n                          boundary_values) \n    {} \n\n    template <int dim> \n    void RefinementKelly<dim>::refine_grid() \n    { \n      Vector<float> estimated_error_per_cell( \n        this->triangulation->n_active_cells()); \n      KellyErrorEstimator<dim>::estimate( \n        this->dof_handler, \n        QGauss<dim - 1>(this->fe->degree + 1), \n        std::map<types::boundary_id, const Function<dim> *>(), \n        this->solution, \n        estimated_error_per_cell); \n      GridRefinement::refine_and_coarsen_fixed_number(*this->triangulation, \n                                                      estimated_error_per_cell, \n                                                      0.3, \n                                                      0.03); \n      this->triangulation->execute_coarsening_and_refinement(); \n    } \n\n  } // namespace LaplaceSolver \n\n//  @sect3{Equation data}  \n\n// 由于这又是一个学术性的例子，我们想对精确解和计算解进行相互比较。为此，我们需要声明代表精确解的函数类（用于比较和Dirichlet边界值），以及一个表示方程右边的类（这只是应用于我们想恢复的精确解的拉普拉斯算子）。\n\n// 在这个例子中，让我们选择函数 $u(x,y)=exp(x+sin(10y+5x^2))$ 作为精确解。在超过两个维度的情况下，只需用 <code>y</code> replaced by <code>z</code> 重复正弦系数，以此类推。鉴于此，以下两类可能是直接从以前的例子中得出的。\n\n  template <int dim> \n  class Solution : public Function<dim> \n  { \n  public: \n    virtual double value(const Point<dim> & p, \n                         const unsigned int component) const override; \n  }; \n\n  template <int dim> \n  double Solution<dim>::value(const Point<dim> & p, \n                              const unsigned int component) const \n  { \n    (void)component; \n    AssertIndexRange(component, 1); \n    double q = p(0); \n    for (unsigned int i = 1; i < dim; ++i) \n      q += std::sin(10 * p(i) + 5 * p(0) * p(0)); \n    const double exponential = std::exp(q); \n    return exponential; \n  } \n\n  template <int dim> \n  class RightHandSide : public Function<dim> \n  { \n  public: \n    virtual double value(const Point<dim> & p, \n                         const unsigned int component) const override; \n  }; \n\n  template <int dim> \n  double RightHandSide<dim>::value(const Point<dim> & p, \n                                   const unsigned int component) const \n  { \n    (void)component; \n    AssertIndexRange(component, 1); \n    double q = p(0); \n    for (unsigned int i = 1; i < dim; ++i) \n      q += std::sin(10 * p(i) + 5 * p(0) * p(0)); \n    const double u  = std::exp(q); \n    double       t1 = 1, t2 = 0, t3 = 0; \n    for (unsigned int i = 1; i < dim; ++i) \n      { \n        t1 += std::cos(10 * p(i) + 5 * p(0) * p(0)) * 10 * p(0); \n        t2 += 10 * std::cos(10 * p(i) + 5 * p(0) * p(0)) - \n              100 * std::sin(10 * p(i) + 5 * p(0) * p(0)) * p(0) * p(0); \n        t3 += 100 * std::cos(10 * p(i) + 5 * p(0) * p(0)) * \n                std::cos(10 * p(i) + 5 * p(0) * p(0)) - \n              100 * std::sin(10 * p(i) + 5 * p(0) * p(0)); \n      }; \n    t1 = t1 * t1; \n\n    return -u * (t1 + t2 + t3); \n  } \n\n//  @sect3{The driver routines}  \n\n// 现在缺少的只是实际选择各种选项的函数，以及在连续的更细的网格上运行模拟，监测网格细化的进展。\n\n// 我们在下面的函数中做到了这一点：它接收一个求解器对象和一个后处理（评估）对象的列表，并在间歇性的网格细化中运行它们。\n\n  template <int dim> \n  void run_simulation( \n    LaplaceSolver::Base<dim> &                          solver, \n    const std::list<Evaluation::EvaluationBase<dim> *> &postprocessor_list) \n  { \n\n// 我们将给出一个我们目前正在计算的步骤的指示器，以便让用户知道一些事情仍在发生，并且程序没有处于无尽的循环中。这就是这个状态行的标题。\n\n    std::cout << \"Refinement cycle: \"; \n\n// 然后开始一个循环，只有当自由度数大于20000时才会结束（当然你可以改变这个限制，如果你需要更多--或者更少--你的程序的准确性）。\n\n    for (unsigned int step = 0; true; ++step) \n      { \n\n// 然后给这个迭代的 <code>alive</code> 指示。注意， <code>std::flush</code> 是需要的，以使文本真正出现在屏幕上，而不是只出现在某个缓冲区中，而这个缓冲区只有在我们下一次发出结束线时才会被刷新。\n\n        std::cout << step << \" \" << std::flush; \n\n// 现在在现在的网格上解决问题，并在其上运行评估器。迭代器进入列表的长类型名称有点烦人，但如果需要的话，可以用别名来缩短。\n\n        solver.solve_problem(); \n\n        for (const auto &postprocessor : postprocessor_list) \n          { \n            postprocessor->set_refinement_cycle(step); \n            solver.postprocess(*postprocessor); \n          }; \n\n// 现在检查是否需要更多的迭代，或者是否应该结束循环。\n\n        if (solver.n_dofs() < 20000) \n          solver.refine_grid(); \n        else \n          break; \n      }; \n\n// 最后结束我们显示状态报告的那一行。\n\n    std::cout << std::endl; \n  } \n\n// 最后一个函数是接受一个求解器的名字（目前允许使用 \"kelly \"和 \"global\"），用一个粗网格（这里是无处不在的单位方格）和一个有限元对象（这里也是无处不在的双线性对象）创建一个求解器对象，并使用该求解器来要求在一连串的细化网格上解决问题。\n\n// 该函数还设置了两个评估函数，一个是在(0.5,0.5)点评估解决方案，另一个是将解决方案写入一个文件。\n\n  template <int dim> \n  void solve_problem(const std::string &solver_name) \n  { \n\n// 第一个小任务：告诉用户将发生什么。因此，写一个标题行，并在下面写上与第一个标题相同长度的所有'-'字符的行。\n\n    const std::string header = \n      \"Running tests with \\\"\" + solver_name + \"\\\" refinement criterion:\"; \n    std::cout << header << std::endl \n              << std::string(header.size(), '-') << std::endl; \n\n// 然后设置三角法、有限元等。\n\n    Triangulation<dim> triangulation; \n    GridGenerator::hyper_cube(triangulation, -1, 1); \n    triangulation.refine_global(2); \n    const FE_Q<dim>    fe(1); \n    const QGauss<dim>  quadrature(4); \n    RightHandSide<dim> rhs_function; \n    Solution<dim>      boundary_values; \n\n// 创建一个由该函数的参数指示的解算器对象。如果该名称不被识别，则抛出一个异常! 各自的求解器对象被存储在一个 `std::unique_ptr` 中，以避免使用后不得不删除指针。\n\n    std::unique_ptr<LaplaceSolver::Base<dim>> solver; \n    if (solver_name == \"global\") \n      solver = std::make_unique<LaplaceSolver::RefinementGlobal<dim>>( \n        triangulation, fe, quadrature, rhs_function, boundary_values); \n    else if (solver_name == \"kelly\") \n      solver = std::make_unique<LaplaceSolver::RefinementKelly<dim>>( \n        triangulation, fe, quadrature, rhs_function, boundary_values); \n    else \n      AssertThrow(false, ExcNotImplemented()); \n\n// 接下来创建一个表对象，其中将存储点（0.5,0.5）的数值解的值，并创建一个相应的评估对象。\n\n    TableHandler                          results_table; \n    Evaluation::PointValueEvaluation<dim> postprocessor1(Point<dim>(0.5, 0.5), \n                                                         results_table); \n\n// 还会生成一个评估器，将解决方案写出来。\n\n    Evaluation::SolutionOutput<dim> postprocessor2(std::string(\"solution-\") + \n                                                     solver_name, \n                                                   DataOutBase::gnuplot); \n\n// 把这两个评价对象放在一个列表中...\n\n    std::list<Evaluation::EvaluationBase<dim> *> postprocessor_list; \n    postprocessor_list.push_back(&postprocessor1); \n    postprocessor_list.push_back(&postprocessor2); \n\n// 然后，我们可以将其传递给在连续细化的网格上实际运行模拟的函数。\n\n    run_simulation(*solver, postprocessor_list); \n\n// 当这一切完成后，写出点评估的结果。\n\n    results_table.write_text(std::cout); \n\n// 在所有结果之后再写上一行空白。\n\n    std::cout << std::endl; \n  } \n} // namespace Step13 \n\n// 关于主函数没有什么可说的。它沿用了之前所有例子中的模式，试图捕捉被抛出的异常，并在我们得到一些信息时尽可能多地显示出来。剩下的就不言自明了。\n\nint main() \n{ \n  try \n    { \n      Step13::solve_problem<2>(\"global\"); \n      Step13::solve_problem<2>(\"kelly\"); \n    } \n  catch (std::exception &exc) \n    { \n      std::cerr << std::endl \n                << std::endl \n                << \"----------------------------------------------------\" \n                << std::endl; \n      std::cerr << \"Exception on processing: \" << std::endl \n                << exc.what() << std::endl \n                << \"Aborting!\" << std::endl \n                << \"----------------------------------------------------\" \n                << std::endl; \n      return 1; \n    } \n  catch (...) \n    { \n      std::cerr << std::endl \n                << std::endl \n                << \"----------------------------------------------------\" \n                << std::endl; \n      std::cerr << \"Unknown exception!\" << std::endl \n                << \"Aborting!\" << std::endl \n                << \"----------------------------------------------------\" \n                << std::endl; \n      return 1; \n    }; \n\n  return 0; \n} \n\n\n", "meta": {"hexsha": "1de80e6ddf129c92bde3f65a2880fc72ebff6fe9", "size": 38946, "ext": "cc", "lang": "C++", "max_stars_repo_path": "Translator_file/examples/step-13/step-13.cc", "max_stars_repo_name": "jiaqiwang969/deal.ii-course-practice", "max_stars_repo_head_hexsha": "0da5ad1537d8152549d8a0e4de5872efe7619c8a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Translator_file/examples/step-13/step-13.cc", "max_issues_repo_name": "jiaqiwang969/deal.ii-course-practice", "max_issues_repo_head_hexsha": "0da5ad1537d8152549d8a0e4de5872efe7619c8a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Translator_file/examples/step-13/step-13.cc", "max_forks_repo_name": "jiaqiwang969/deal.ii-course-practice", "max_forks_repo_head_hexsha": "0da5ad1537d8152549d8a0e4de5872efe7619c8a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.9446153846, "max_line_length": 578, "alphanum_fraction": 0.6503363632, "num_tokens": 16652, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.6442251064863697, "lm_q1q2_score": 0.33217529511315264}}
{"text": "#ifndef _USE_MATH_DEFINES\n#define _USE_MATH_DEFINES\n#endif\n#include <cmath>\n\n#ifndef NOMINMAX\n#define NOMINMAX\n#endif\n\n#include <nlohmann/json.hpp>\n#include <Eigen/Dense>\n#include <cxxopts.hpp>\n#include <opencv2/core/core.hpp>\n#include <opencv2/highgui/highgui.hpp>\n#include <opencv2/imgproc/imgproc.hpp>\n#include <opencv2/imgproc/imgproc_c.h>\n#include <opencv2/calib3d.hpp>\n#include <fstream>\n#include <iostream>\n#include <iomanip>\n#include <string>\n#include <array>\n#include <algorithm>\n#include <exception>\n#include <functional>\n\nusing json = nlohmann::json;\n\nusing mat2x4 = Eigen::Matrix<double, 2, 4>;\nusing mat3x4 = Eigen::Matrix<double, 3, 4>;\nusing mat3 = Eigen::Matrix3d;\nusing mat4 = Eigen::Matrix4d;\nusing vec2 = Eigen::Vector2d;\nusing vec3 = Eigen::Vector3d;\nusing vec4 = Eigen::Vector4d;\n\n// Fixed-size Eigen types' allocation must be aligned\ntemplate<typename T>\nusing e_vec = std::vector<T, Eigen::aligned_allocator<T>>;\n\nvoid parse_camera_intrinsics(json const &camera_intrinsics,\n                             mat3x4& intrinsic_matrix)\n{\n    auto const focal_length_x = camera_intrinsics[\"focalLengthX\"].get<float>();\n    auto const focal_length_y = camera_intrinsics[\"focalLengthY\"].get<float>();\n    auto const principal_point_x = camera_intrinsics[\"principalPointX\"].get<float>();\n    auto const principal_point_y = camera_intrinsics[\"principalPointY\"].get<float>();\n\n    intrinsic_matrix = mat3x4::Zero();\n    intrinsic_matrix(0, 0) = focal_length_x;\n    intrinsic_matrix(1, 1) = focal_length_y;\n    intrinsic_matrix(0, 2) = principal_point_x;\n    intrinsic_matrix(1, 2) = principal_point_y;\n    intrinsic_matrix(2, 2) = 1.0f;\n}\n\ne_vec<mat4> solve_homographies(e_vec<mat3x4> const& Ps, e_vec<mat2x4> const& Ys, mat4 const& Z)\n{\n    auto Cs = e_vec<mat4>{};\n    auto cv_Z = std::vector<cv::Point3d>{\n        cv::Point3d{ Z(0, 0), Z(1, 0), Z(2, 0) },\n        cv::Point3d{ Z(0, 1), Z(1, 1), Z(2, 1) },\n        cv::Point3d{ Z(0, 2), Z(1, 2), Z(2, 2) },\n        cv::Point3d{ Z(0, 3), Z(1, 3), Z(2, 3) },\n    };\n    for (size_t i = 0; i < Ys.size(); ++i)\n    {\n        auto cv_Y = std::vector<cv::Point2d>{\n            cv::Point2d{ Ys[i](0, 0), Ys[i](1, 0) }, // bottom-left\n            cv::Point2d{ Ys[i](0, 1), Ys[i](1, 1) }, // bottom-right\n            cv::Point2d{ Ys[i](0, 2), Ys[i](1, 2) }, // top-right\n            cv::Point2d{ Ys[i](0, 3), Ys[i](1, 3) }, // top-left\n        };\n        cv::Matx33d K = {\n            Ps[i](0, 0), Ps[i](0, 1), Ps[i](0, 2),\n            Ps[i](1, 0), Ps[i](1, 1), Ps[i](1, 2),\n            Ps[i](2, 0), Ps[i](2, 1), Ps[i](2, 2),\n        };\n        cv::Vec3d r;\n        cv::Vec3d T;\n        cv::solvePnP(cv_Z, cv_Y, K, cv::Vec4d{ 0, 0, 0, 0 }, r, T);\n        cv::Matx33d R;\n        cv::Rodrigues(r, R);\n        mat4 C;\n        C << R(0, 0), R(0, 1), R(0, 2), T(0),\n            R(1, 0), R(1, 1), R(1, 2), T(1),\n            R(2, 0), R(2, 1), R(2, 2), T(2),\n            0, 0, 0, 1;\n        Cs.push_back(C);\n    }\n    return Cs;\n}\n\ndouble angle_between_rotations(mat3 const& A, mat3 const& B)\n{\n    mat3 R = A * B.transpose();\n    auto angle = std::acos((R.trace() - 1.0) / 2.0);\n    return std::min(angle, 2.0*M_PI - angle);\n}\n\ndouble radians_to_degrees(double radians)\n{\n    return radians * 360.0 / (2.0 * M_PI);\n}\n\nbool find_sync_from_orientations(\n    Eigen::VectorXd vio_ts, e_vec<mat3> const& vio_rs,\n    Eigen::VectorXd tracker_ts, e_vec<mat3> const& tracker_rs,\n    double& optimal_sync\n    )\n{\n    auto n_vio = (int)vio_ts.size();\n    auto n_tracker = (int)tracker_ts.size();\n    // std::printf(\"n_vio: %d\\nn_tracker: %d\\n\", (int)n_vio, (int)n_tracker);\n\n    auto vio_length = vio_ts[n_vio-1] - vio_ts[0];\n    auto tracker_length = tracker_ts[n_tracker-1] - tracker_ts[0];\n    // std::printf(\"VIO length: %.2fs\\n\", vio_length);\n    // std::printf(\"Tracker length: %.2fs\\n\", tracker_length);\n\n    // Make both start at t=0\n    vio_ts.array() -= vio_ts[0];\n    tracker_ts.array() -= tracker_ts[0];\n    \n    if (vio_length >= tracker_length)\n    {\n        std::fprintf(stderr, \"Error: VIO track should be shorter than tracker track\\n\");\n        return false;\n    }\n\n    // Finding sync (time offset) between the VIO and tracker rotation data:\n    // - sample tracker at vio_t+sync\n    // - compute shortest angle between the VIO rotations and corresponding (according to sync) tracker rotations\n    // - for correct sync, the angle should be almost exactly same throughout the track, therefore we find sync that minimizes deviation from mean\n\n    auto max_sync = tracker_length - vio_length;\n    // auto syncs = Eigen::ArrayXd::LinSpaced(n_vio, 0.0, max_sync);\n    auto syncs = Eigen::ArrayXd::LinSpaced((int)std::ceil(max_sync / 0.1)+1, 0.0, max_sync);\n\n    Eigen::ArrayXd angles = Eigen::ArrayXd(n_vio);\n    auto min_variance = 999999.0;\n    auto min_variance_index = 0;\n    for (auto i_sync = 0; i_sync < syncs.size(); ++i_sync)\n    {\n        auto i_tracker = 0;\n        for (auto i_vio = 0; i_vio < n_vio; ++i_vio)\n        {\n            // Add sync to VIO timestamp; larger sync means later starting time for VIO track\n            auto vio_t = vio_ts[i_vio] + syncs[i_sync];\n            // Seek to first tracker timestamp that is greater-or-equal-to VIO timestamp\n            while ( (tracker_ts[i_tracker] < vio_t) && (i_tracker < n_tracker-1) )\n            {\n                ++i_tracker;\n            }\n            angles[i_vio] = radians_to_degrees(\n                angle_between_rotations(vio_rs[i_vio], tracker_rs[i_tracker]));\n        }\n        auto angle_mean = angles.mean();\n        auto angle_variance = (1. / n_vio) * (angles - angle_mean).square().sum();\n        // std::printf(\"sync=%.2f, angle_mean=%.4f, angle_variance=%.4f\\n\",\n        //             syncs[i_sync], angle_mean, angle_variance);\n        if (angle_variance < min_variance)\n        {\n            min_variance = angle_variance;\n            min_variance_index = i_sync;\n        }\n    }\n\n    optimal_sync = syncs[min_variance_index];\n\n    return true;\n}\n\nauto map_vio_to_tracker_with_sync = [](auto const& vio_ts, auto const& tracker_ts, double sync, auto& map_vio_to_tracker)\n{\n    auto n_vio = (int)vio_ts.size();\n    auto n_tracker = (int)tracker_ts.size();\n\n    // Map VIO indices to tracker indices using this sync\n    // auto map_vio_to_tracker = std::vector<int>(n_vio);\n    auto i_tracker = 0;\n    for (auto i_vio = 0; i_vio < n_vio; ++i_vio)\n    {\n        auto vio_t = vio_ts[i_vio] + sync;\n        while ( (tracker_ts[i_tracker] < vio_t) && (i_tracker < n_tracker-1) )\n        {\n            ++i_tracker;\n        }\n        map_vio_to_tracker[i_vio] = i_tracker;\n    }\n    // return map_vio_to_tracker;\n};\n\nbool find_sync_from_angular_speeds(\n    Eigen::ArrayXd vio_ts, Eigen::ArrayXd vio_vs,\n    Eigen::ArrayXd tracker_ts, Eigen::ArrayXd tracker_vs,\n    double& optimal_sync\n    )\n{\n    auto n_vio = (int)vio_ts.size();\n    auto n_tracker = (int)tracker_ts.size();\n    // std::printf(\"n_vio: %d\\nn_tracker: %d\\n\", (int)n_vio, (int)n_tracker);\n\n    auto vio_length = vio_ts[n_vio-1] - vio_ts[0];\n    auto tracker_length = tracker_ts[n_tracker-1] - tracker_ts[0];\n    // std::printf(\"VIO length: %.2fs\\n\", vio_length);\n    // std::printf(\"Tracker length: %.2fs\\n\", tracker_length);\n\n    // Make both start at t=0\n    vio_ts.array() -= vio_ts[0];\n    tracker_ts.array() -= tracker_ts[0];\n    \n    if (vio_length >= tracker_length)\n    {\n        std::fprintf(stderr, \"Error: VIO track should be shorter than tracker track\\n\");\n        return false;\n    }\n\n    auto max_sync = tracker_length - vio_length;\n    // auto syncs = Eigen::ArrayXd::LinSpaced(n_vio, 0.0, max_sync);\n    auto syncs = Eigen::ArrayXd::LinSpaced((int)std::floor(max_sync / 0.1)+1, 0.0, max_sync);\n\n    auto max_similarity = -999999.0;\n    auto max_similarity_index = 0;\n    auto map_vio_to_tracker = std::vector<int>(n_vio);\n    for (auto i_sync = 0; i_sync < syncs.size(); ++i_sync)\n    {\n        // Map VIO indices to tracker indices using this sync\n        auto i_tracker = 0;\n        for (auto i_vio = 0; i_vio < n_vio; ++i_vio)\n        {\n            auto vio_t = vio_ts[i_vio] + syncs[i_sync];\n            while ( (tracker_ts[i_tracker] < vio_t) && (i_tracker < n_tracker-1) )\n            {\n                ++i_tracker;\n            }\n            map_vio_to_tracker[i_vio] = i_tracker;\n        }\n\n        // Find corresponding tracker speeds\n        Eigen::VectorXd matched_tracker_vs(n_vio-1);\n        for (auto i_vio = 0; i_vio < n_vio-1; ++i_vio)\n        {\n            matched_tracker_vs[i_vio] = tracker_vs[map_vio_to_tracker[i_vio]];\n        }\n\n        // Use cosine similarity to evaluate how good match it is\n        auto similarity = vio_vs.matrix().stableNormalized().dot(matched_tracker_vs.stableNormalized());\n\n        // std::printf(\"sync=%.2f, similarity=%.4f\\n\", syncs[i_sync], similarity);\n        if (similarity > max_similarity)\n        {\n            max_similarity = similarity;\n            max_similarity_index = i_sync;\n        }\n    }\n\n    optimal_sync = syncs[max_similarity_index];\n\n    return true;\n}\n\n// Input in jsonl format (file or stdin) (file not supported currently):\n//\n//      {\n//          \"time\": ...,\n//          \"framePath\": \"/path/to/frames/123.png\",\n//          \"cameraIntrinsics\": {focal lengths, principal point...},\n//          \"markers\": [{\"id\":0,\"corners\":[[p0x,p0y],[p1x,p1y]...]}, {\"id\":1...}]\n//          ... (any other elements, which are not used)\n//      }\n//\nint main(int argc, char* argv[])\n{\n    auto vio_input_file_option = std::string{};\n    auto tracker_input_file_option = std::string{};\n    auto test=false;\n\n    cxxopts::Options options(argv[0], \"\");\n    options.add_options()\n        (\"vio\", \"Path to the VIO input file\", cxxopts::value(vio_input_file_option))\n        (\"tracker\", \"Path to the tracker input file\", cxxopts::value(tracker_input_file_option))\n        (\"test\", \"temp\", cxxopts::value(test))\n        ;\n\n    auto parsed_args = options.parse(argc, argv);\n    if (parsed_args.count(\"help\"))\n    {\n        std::cout << options.help() << std::endl;\n        return 0;\n    }\n\n    if (parsed_args.count(\"vio\") == 0)\n    {\n        std::cerr << \"Missing argument: input.\" << std::endl;\n        std::cerr << options.help() << std::endl;\n        std::cerr << \"See README.md for more instructions.\" << std::endl;\n        return 1;\n    }\n    std::ifstream vio_input(vio_input_file_option);\n\n    if (parsed_args.count(\"tracker\") == 0)\n    {\n        std::cerr << \"Missing argument: tracker.\" << std::endl;\n        std::cerr << options.help() << std::endl;\n        std::cerr << \"See README.md for more instructions.\" << std::endl;\n        return 1;\n    }\n    std::ifstream tracker_input(tracker_input_file_option);\n\n\n    // TODO: cli option\n    auto const s = 0.025; // 2.5 cm\n    mat4 Z;\n    Z.col(0) = vec4{ -s/2, -s/2, 0, 1, }; // bottom-left\n    Z.col(1) = vec4{ s/2, -s/2, 0, 1, }; // bottom-right\n    Z.col(2) = vec4{ s/2, s/2, 0, 1, }; // top-right\n    Z.col(3) = vec4{ -s/2, s/2, 0, 1, }; // top-left\n\n    // This is constant, tag is placed on top of base station in expected way\n    mat4 tag_orientation_in_tracking_space = mat4::Identity();\n    tag_orientation_in_tracking_space.col(0) = vec4{ -1, 0, 0, 0 };\n    tag_orientation_in_tracking_space.col(1) = vec4{ 0, 0, 1, 0 };\n    // Let's say tag faces towards its own Z+ (so it is right-handed)\n    tag_orientation_in_tracking_space.col(2) = vec4{ 0, 1, 0, 0 };\n    // std::printf(\"tag_orientation_in_tracking_space:\\n\");\n    // std::cout << tag_orientation_in_tracking_space << \"\\n\";\n\n    // Read in VIO data, and solve VIO device position in tracking space from Apriltag in frame\n    auto vio_ts = std::vector<double>();\n    auto vio_rs = e_vec<mat3>();\n    auto vio_ps = e_vec<vec3>();\n    std::string line;\n    int total_input_frames = 0;\n    while (std::getline(vio_input, line))\n    {\n        ++total_input_frames;\n        auto j = json::parse(line);\n\n        auto markers = j[\"markers\"];\n\n        if (markers.size() == 1)\n        {\n            mat3x4 P;\n            parse_camera_intrinsics(j[\"cameraIntrinsics\"], P);\n\n            // Find \n            auto Ps = e_vec<mat3x4>();\n            auto cv_Ys = e_vec<mat2x4>{};\n            Ps.push_back(P);\n            mat2x4 cv_Y;\n            auto const& d = markers[0];\n            cv_Y << d[0][0], d[1][0], d[2][0], d[3][0],\n                d[0][1], d[1][1], d[2][1], d[3][1];\n            cv_Ys.push_back(cv_Y);\n            auto Cs = solve_homographies(Ps, cv_Ys, Z);\n            auto C = Cs[0];\n\n            // if (test)\n            if (test && (total_input_frames - 1 == 61))\n            {\n                // std::printf(\"T[%d]: \", total_input_frames-1);\n                // std::cout << C.col(3).head(3).transpose() << \"\\n\";\n                // std::cout << C.col(3).head(3).transpose() << \"    \" << j[\"framePath\"] << \"\\n\";\n                std::cout << \"--- \" << \"R[\" << (total_input_frames-1) << \"]: \" << j[\"framePath\"] << \" ---\\n\";\n                std::cout << C.topLeftCorner(3, 3) << \"\\n\";\n            }\n            // mat3 fix_r = vec3{ 1, 1, 1 }.asDiagonal();\n            // mat3 fix_r = vec3{ -1, -1, -1 }.asDiagonal();\n            // mat3 fix_r = vec3{ -1, -1, 1 }.asDiagonal();\n            // C.topLeftCorner(3, 3) = (fix_r * C.topLeftCorner(3, 3)).eval();\n\n            vio_ts.push_back(j[\"time\"]);\n            vio_rs.push_back(C.topLeftCorner(3, 3)); // TODO: probably this rotation messing things up?\n            vio_ps.push_back(C.col(3).head(3)); // This seemed to be good\n        }\n    }\n\n    // Read in tracker data (timestamps and orientations)\n    auto tracker_ts = std::vector<double>();\n    auto tracker_ps = e_vec<vec3>();\n    auto tracker_rs = e_vec<mat3>();\n    {\n        std::string line;\n        while (std::getline(tracker_input, line))\n        {\n            auto j = json::parse(line);\n            tracker_ts.push_back(j[\"time\"]);\n            mat3 R = mat3();\n            auto x = j[\"rotation\"][\"col0\"].get<std::vector<double>>();\n            auto y = j[\"rotation\"][\"col1\"].get<std::vector<double>>();\n            auto z = j[\"rotation\"][\"col2\"].get<std::vector<double>>();\n            R.col(0) = vec3{ x[0], x[1], x[2] };\n            R.col(1) = vec3{ y[0], y[1], y[2] };\n            R.col(2) = vec3{ z[0], z[1], z[2] };\n            tracker_rs.push_back(R);\n            tracker_ps.push_back(vec3{ j[\"position\"][\"x\"].get<double>(), j[\"position\"][\"y\"].get<double>(), j[\"position\"][\"z\"].get<double>() });\n        }\n    }\n\n    // Find best matching sync, with rotation difference deviation from mean between tracks\n    Eigen::Map<Eigen::VectorXd> eigen_vio_ts(vio_ts.data(), vio_ts.size());\n    Eigen::Map<Eigen::VectorXd> eigen_tracker_ts(tracker_ts.data(), tracker_ts.size());\n\n    // // Note: angle not necessarily intuitive, if it is along a diagonal vector\n    double orientation_diff_optimal_sync = 0.0;\n    find_sync_from_orientations(eigen_vio_ts, vio_rs, eigen_tracker_ts, tracker_rs, orientation_diff_optimal_sync);\n\n    // Find best matching sync, using cosine similarity of rotation speeds\n    // (Seems more robust)\n    auto n_vio = (int)vio_ts.size();\n    auto n_tracker = (int)tracker_ts.size();\n    Eigen::ArrayXd vio_vs(n_vio-1);\n    for (auto i = 0; i < n_vio-1; ++i)\n    {\n        auto delta_angle =\n            radians_to_degrees(angle_between_rotations(vio_rs[i], vio_rs[i+1]));\n        vio_vs[i] = delta_angle / (vio_ts[i+1] - vio_ts[i]);\n    }\n    Eigen::ArrayXd tracker_vs(n_tracker-1);\n    for (auto i = 0; i < n_tracker-1; ++i)\n    {\n        auto delta_angle =\n            radians_to_degrees(angle_between_rotations(tracker_rs[i], tracker_rs[i+1]));\n        tracker_vs[i] = delta_angle / (tracker_ts[i+1] - tracker_ts[i]);\n    }\n    double angular_speed_optimal_sync = 0.0;\n    find_sync_from_angular_speeds(eigen_vio_ts, vio_vs, eigen_tracker_ts, tracker_vs, angular_speed_optimal_sync);\n    std::printf(\"Best sync from minimizing rotation difference deviation from mean: %.2f\\n\",\n                orientation_diff_optimal_sync);\n    std::printf(\"Best sync from angular speeds: %.2f\\n\", angular_speed_optimal_sync);\n\n    // Find 'd' from successive datapoints\n    {\n        // auto optimal_sync = angular_speed_optimal_sync;\n        auto optimal_sync = orientation_diff_optimal_sync;\n\n        auto vio_ts_start0 = vio_ts;\n        auto map_vio_ts = Eigen::Map<Eigen::ArrayXd>(vio_ts_start0.data(), n_vio);\n        map_vio_ts -= vio_ts[0];\n        auto tracker_ts_start0 = tracker_ts;\n        auto map_tracker_ts = Eigen::Map<Eigen::ArrayXd>(tracker_ts_start0.data(), n_tracker);\n        map_tracker_ts -= tracker_ts[0];\n\n        auto vio_to_tracker = Eigen::ArrayXi(n_vio);\n        // map_vio_to_tracker_with_sync(vio_ts, tracker_ts, optimal_sync, vio_to_tracker);\n\n        map_vio_to_tracker_with_sync(map_vio_ts, map_tracker_ts, optimal_sync, vio_to_tracker);\n\n        // std::cout << \"Using sync \" << optimal_sync << \"\\n\";\n\n\n        // Orientation of tag in tracking space (= relative to base station)\n        mat3 R_tag;\n        R_tag.col(0) = vec3{ -1,  0,  0 };\n        R_tag.col(1) = vec3{  0,  0,  1 };\n        R_tag.col(2) = vec3{  0,  1,  0 };\n\n        auto R_vio = vio_rs; // tracking space orientation\n        for (auto i = 0; i < n_vio; ++i)\n        {\n            R_vio[i] = (R_tag * R_vio[i]).eval();\n        }\n\n        // Does not seem to be working at all yet... maybe go through math one more time\n        auto ds = Eigen::MatrixXd(3, n_vio-1);\n        auto x_avg = vec3{ 0, 0, 0 };\n        auto step = 10;\n        auto i = 0;\n        for (; step*(i+1) < n_vio; ++i)\n        {\n            auto i_prev = step*i;\n            auto i_next = step*(i + 1);\n            auto dT_tracker = tracker_ps[vio_to_tracker[i_next]] - tracker_ps[vio_to_tracker[i_prev]];\n            auto dR_vio = R_vio[i_next] - R_vio[i_prev];\n            auto dT_vio = vio_ps[i_next] - vio_ps[i_prev];\n            // std::printf(\"dR_vio max: %.6f    dT_vio max: %.6f\\n\", dR_vio.maxCoeff(), dT_vio.maxCoeff());\n\n            ds.col(i) = dR_vio.inverse() * (dT_tracker - R_tag * dT_vio);\n            // std::printf(\"x: %.4f, %.4f, %.4f\\n\", ds.col(i)[0], ds.col(i)[1], ds.col(i)[2]);\n\n        }\n\n        {\n            auto i_prev = 0;\n            auto i_next = n_vio - 1;\n            auto dT_tracker = tracker_ps[vio_to_tracker[i_next]] - tracker_ps[vio_to_tracker[i_prev]];\n            auto dR_vio = R_vio[i_next] - R_vio[i_prev];\n            auto dT_vio = vio_ps[i_next] - vio_ps[i_prev];\n            vec3 x = dR_vio.inverse() * (dT_tracker - R_tag * dT_vio);\n            std::printf(\"x(first,last), norm: %.4f, %.4f, %.4f,    %.4f\\n\", x[0], x[1], x[2], x.norm());\n        }\n\n        {\n            auto i_prev = 0;\n            auto i_next = n_vio / 2;\n            auto dT_tracker = tracker_ps[vio_to_tracker[i_next]] - tracker_ps[vio_to_tracker[i_prev]];\n            auto dR_vio = R_vio[i_next] - R_vio[i_prev];\n            auto dT_vio = vio_ps[i_next] - vio_ps[i_prev];\n            vec3 x = dR_vio.inverse() * (dT_tracker - R_tag * dT_vio);\n            std::printf(\"x(first,mid), norm: %.4f, %.4f, %.4f,    %.4f\\n\", x[0], x[1], x[2], x.norm());\n        }\n\n        {\n            auto i_prev = n_vio / 2;\n            auto i_next = n_vio - 1;\n            auto dT_tracker = tracker_ps[vio_to_tracker[i_next]] - tracker_ps[vio_to_tracker[i_prev]];\n            auto dR_vio = R_vio[i_next] - R_vio[i_prev];\n            auto dT_vio = vio_ps[i_next] - vio_ps[i_prev];\n            vec3 x = dR_vio.inverse() * (dT_tracker - R_tag * dT_vio);\n            std::printf(\"x(mid,last), norm: %.4f, %.4f, %.4f,    %.4f\\n\", x[0], x[1], x[2], x.norm());\n        }\n\n    //     // TODO actual optimization\n    }\n\n    // TODO check if R_tag is correct, and opencv homography coordinate system (C's translation part mainly)\n\n}\n\n\n// Base station coordinate system:\n// - Y+ points towards ceiling\n// - Z- points towards tracking area\n// - X+ points towards tag's X-\n\n// Orientation of VIO device in tag space\n// OpenCV coordinate system:\n// -   x+ points right in image\n// -   y+ points down in image\n// -   z+ points away from camera ('into' the image)\n\n// // Orientation of OpenCV frame in OpenGL-style coordinate system\n// // OpenGL-style coordinate system:\n// // -   x+ points right in image\n// // -   y+ points up in image\n// // -   z+ points away from image (towards camera)\n\n", "meta": {"hexsha": "43bd8f8d87c1729ab75e2f83189df67451fcf03d", "size": 20266, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/calibrate_vio_tracker/src/main.cpp", "max_stars_repo_name": "AaltoVision/vive-vio-scripts", "max_stars_repo_head_hexsha": "fc1954d2cf4e6940e9d541e86ca8aea8e5031c83", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-09-16T14:18:21.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-16T14:18:21.000Z", "max_issues_repo_path": "libs/calibrate_vio_tracker/src/main.cpp", "max_issues_repo_name": "AaltoVision/vive-vio-scripts", "max_issues_repo_head_hexsha": "fc1954d2cf4e6940e9d541e86ca8aea8e5031c83", "max_issues_repo_licenses": ["Apache-2.0"], "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/calibrate_vio_tracker/src/main.cpp", "max_forks_repo_name": "AaltoVision/vive-vio-scripts", "max_forks_repo_head_hexsha": "fc1954d2cf4e6940e9d541e86ca8aea8e5031c83", "max_forks_repo_licenses": ["Apache-2.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.599257885, "max_line_length": 146, "alphanum_fraction": 0.5844271193, "num_tokens": 6068, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7520125737597972, "lm_q2_score": 0.4416730056646256, "lm_q1q2_score": 0.3321436537500806}}
{"text": "/*********************************************************************\n* Software License Agreement (BSD License)\n*\n*  Copyright (c) 2014, University of Toronto\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 Toronto 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: Jonathan Gammell*/\n\n// The class's header\n#include \"ompl/util/ProlateHyperspheroid.h\"\n// For OMPL exceptions\n#include \"ompl/util/Exception.h\"\n// For OMPL information\n#include \"ompl/util/Console.h\"\n// For geometric equations like prolateHyperspheroidMeasure\n#include \"ompl/util/GeometricEquations.h\"\n\n// For boost::make_shared\n#include <boost/make_shared.hpp>\n\n// Eigen core:\n#include <Eigen/Core>\n// Inversion and determinants\n#include <Eigen/LU>\n// SVD decomposition\n#include <Eigen/SVD>\n\n\n\n\nstruct ompl::ProlateHyperspheroid::PhsData\n{\n    /** \\brief The dimension of the prolate hyperspheroid.*/\n    unsigned int dim_;\n    /** \\brief Whether the transformation is up to date */\n    bool isTransformUpToDate_;\n    /** \\brief The minimum possible transverse diameter of the PHS. Defined as the distance between the two foci*/\n    double minTransverseDiameter_;\n    /** \\brief The transverse diameter of the PHS. */\n    double transverseDiameter_;\n    /** \\brief The measure of the PHS. */\n    double phsMeasure_;\n    /** \\brief The first focus of the PHS (i.e., the start state of the planning problem). Unlike other parts of Eigen, variably sized matrices do not require special allocators. */\n    Eigen::VectorXd xFocus1_;\n    /** \\brief The second focus of the PHS (i.e., the goal state of the planning problem). Unlike other parts of Eigen, variably sized matrices do not require special allocators.  */\n    Eigen::VectorXd xFocus2_;\n    /** \\brief The centre of the PHS. Defined as the average of the foci. Unlike other parts of Eigen, variably sized matrices do not require special allocators. */\n    Eigen::VectorXd xCentre_;\n    /** \\brief The rotation from PHS-frame to world frame. Is only calculated on construction. Unlike other parts of Eigen, variably sized matrices do not require special allocators. */\n    Eigen::MatrixXd rotationWorldFromEllipse_;\n    /** \\brief The transformation from PHS-frame to world frame. Is calculated every time the transverse diameter changes. Unlike other parts of Eigen, variably sized matrices do not require special allocators. */\n    Eigen::MatrixXd transformationWorldFromEllipse_;\n};\n\n\nompl::ProlateHyperspheroid::ProlateHyperspheroid(unsigned int n, const double focus1[], const double focus2[])\n  : dataPtr_ (boost::make_shared<PhsData>())\n{\n    //Initialize the data:\n    dataPtr_->dim_ = n;\n    dataPtr_->transverseDiameter_ = 0.0; // Initialize to something.\n    dataPtr_->isTransformUpToDate_ = false;\n\n    // Copy the arrays into their Eigen containers via the Eigen::Map \"view\"\n    dataPtr_->xFocus1_ = Eigen::Map<const Eigen::VectorXd>(focus1, dataPtr_->dim_);\n    dataPtr_->xFocus2_ = Eigen::Map<const Eigen::VectorXd>(focus2, dataPtr_->dim_);\n\n    // Calculate the minimum transverse diameter\n    dataPtr_->minTransverseDiameter_ = (dataPtr_->xFocus1_ - dataPtr_->xFocus2_).norm();\n\n    // Calculate the centre:\n    dataPtr_->xCentre_ = 0.5 * (dataPtr_->xFocus1_ + dataPtr_->xFocus2_);\n\n    // Calculate the rotation\n    updateRotation();\n}\n\nvoid ompl::ProlateHyperspheroid::setTransverseDiameter(double transverseDiameter)\n{\n    if (transverseDiameter < dataPtr_->minTransverseDiameter_)\n    {\n        OMPL_ERROR(\"%g < %g\", transverseDiameter, dataPtr_->minTransverseDiameter_);\n        throw Exception(\"Transverse diameter cannot be less than the distance between the foci.\");\n    }\n\n    // Store and update if changed\n    if (dataPtr_->transverseDiameter_ != transverseDiameter)\n    {\n        // Mark as out of date\n        dataPtr_->isTransformUpToDate_ = false;\n\n        // Store\n        dataPtr_->transverseDiameter_ = transverseDiameter;\n\n        // Update the transform\n        updateTransformation();\n    }\n    // No else, the diameter didn't change\n}\n\nvoid ompl::ProlateHyperspheroid::transform(const double sphere[], double phs[]) const\n{\n    if (dataPtr_->isTransformUpToDate_ == false)\n    {\n      throw Exception(\"The transformation is not up to date in the PHS class. Has the transverse diameter been set?\");\n    }\n\n    // Calculate the tranformation and offset, using Eigen::Map views of the data\n    Eigen::Map<Eigen::VectorXd>(phs, dataPtr_->dim_) = dataPtr_->transformationWorldFromEllipse_*Eigen::Map<const Eigen::VectorXd>(sphere, dataPtr_->dim_);\n    Eigen::Map<Eigen::VectorXd>(phs, dataPtr_->dim_) += dataPtr_->xCentre_;\n}\n\nbool ompl::ProlateHyperspheroid::isInPhs(const double point[]) const\n{\n    if (dataPtr_->isTransformUpToDate_ == false)\n    {\n        // The transform is not up to date until the transverse diameter has been set\n        throw Exception (\"The transverse diameter has not been set\");\n    }\n\n    return (getPathLength(point) < dataPtr_->transverseDiameter_);\n}\n\nbool ompl::ProlateHyperspheroid::isOnPhs(const double point[]) const\n{\n    if (dataPtr_->isTransformUpToDate_ == false)\n    {\n        // The transform is not up to date until the transverse diameter has been set\n        throw Exception (\"The transverse diameter has not been set\");\n    }\n\n    return (getPathLength(point) == dataPtr_->transverseDiameter_);\n}\n\nunsigned int ompl::ProlateHyperspheroid::getPhsDimension(void) const\n{\n    return dataPtr_->dim_;\n}\n\n\ndouble ompl::ProlateHyperspheroid::getPhsMeasure(void) const\n{\n    if (dataPtr_->isTransformUpToDate_ == false)\n    {\n        // The transform is not up to date until the transverse diameter has been set, therefore we have no transverse diameter and we have infinite measure\n        return std::numeric_limits<double>::infinity();\n    }\n    else\n    {\n        // Calculate and return:\n        return dataPtr_->phsMeasure_;\n    }\n}\n\ndouble ompl::ProlateHyperspheroid::getPhsMeasure(double tranDiam) const\n{\n    return prolateHyperspheroidMeasure(dataPtr_->dim_, dataPtr_->minTransverseDiameter_, tranDiam);\n}\n\ndouble ompl::ProlateHyperspheroid::getMinTransverseDiameter(void) const\n{\n    return dataPtr_->minTransverseDiameter_;\n}\n\ndouble ompl::ProlateHyperspheroid::getPathLength(const double point[]) const\n{\n    return (dataPtr_->xFocus1_ - Eigen::Map<const Eigen::VectorXd>(point, dataPtr_->dim_)).norm() + (Eigen::Map<const Eigen::VectorXd>(point, dataPtr_->dim_) - dataPtr_->xFocus2_).norm();\n}\n\nunsigned int ompl::ProlateHyperspheroid::getDimension() const\n{\n    return dataPtr_->dim_;\n}\n\nvoid ompl::ProlateHyperspheroid::updateRotation(void)\n{\n    // Mark the transform as out of date\n    dataPtr_->isTransformUpToDate_ = false;\n\n    // If the minTransverseDiameter_ is too close to 0, we treat this as a circle.\n    double circleTol = 1E-9;\n    if (dataPtr_->minTransverseDiameter_ < circleTol)\n    {\n        dataPtr_->rotationWorldFromEllipse_.setIdentity(dataPtr_->dim_, dataPtr_->dim_);\n    }\n    else\n    {\n        // Variables\n        // The transverse axis of the PHS expressed in the world frame.\n        Eigen::VectorXd transverseAxis(dataPtr_->dim_);\n        // The matrix representation of the Wahba problem\n        Eigen::MatrixXd wahbaProb(dataPtr_->dim_, dataPtr_->dim_);\n        // The middle diagonal matrix in the SVD solution to the Wahba problem\n        Eigen::VectorXd middleM(dataPtr_->dim_);\n\n        // Calculate the major axis, storing as the first eigenvector\n        transverseAxis = (dataPtr_->xFocus2_ - dataPtr_->xFocus1_ )/dataPtr_->minTransverseDiameter_;\n\n        // Calculate the rotation that will allow us to generate the remaining eigenvectors\n        // Formulate as a Wahba problem, first forming the matrix a_j*a_i' where a_j is the transverse axis if the ellipse in the world frame, and a_i is the first basis vector of the world frame (i.e., [1 0 .... 0])\n        wahbaProb = transverseAxis * Eigen::MatrixXd::Identity(dataPtr_->dim_, dataPtr_->dim_).col(0).transpose();\n\n        // Then run it through the  SVD solver\n        Eigen::JacobiSVD<Eigen::MatrixXd, Eigen::NoQRPreconditioner> svd(wahbaProb, Eigen::ComputeFullV | Eigen::ComputeFullU);\n\n        // Then calculate the rotation matrix from the U and V components of SVD\n        // Calculate the middle diagonal matrix\n        middleM = Eigen::VectorXd::Ones(dataPtr_->dim_);\n        // Make the last value equal to det(U)*det(V) (zero-based indexing remember)\n        middleM(dataPtr_->dim_ - 1) = svd.matrixU().determinant() * svd.matrixV().determinant();\n\n        // Calculate the rotation\n        dataPtr_->rotationWorldFromEllipse_ = svd.matrixU() * middleM.asDiagonal() * svd.matrixV().transpose();\n    }\n}\n\nvoid ompl::ProlateHyperspheroid::updateTransformation(void)\n{\n    // Variables\n    // The radii of the ellipse\n    Eigen::VectorXd diagAsVector(dataPtr_->dim_);\n    // The conjugate diameters:\n    double conjugateDiamater;\n\n    // Calculate the conjugate radius\n    conjugateDiamater = std::sqrt(dataPtr_->transverseDiameter_*dataPtr_->transverseDiameter_ - dataPtr_->minTransverseDiameter_*dataPtr_->minTransverseDiameter_);\n\n    // Store into the diagonal matrix\n    // All the elements but one are the conjugate radius\n    diagAsVector.fill(conjugateDiamater/2.0);\n\n    // The first element in diagonal is the transverse radius\n    diagAsVector(0) = 0.5 * dataPtr_->transverseDiameter_;\n\n    // Calculate the transformation matrix\n    dataPtr_->transformationWorldFromEllipse_ = dataPtr_->rotationWorldFromEllipse_ * diagAsVector.asDiagonal();\n\n    // Calculate the measure:\n    dataPtr_->phsMeasure_ = prolateHyperspheroidMeasure(dataPtr_->dim_, dataPtr_->minTransverseDiameter_, dataPtr_->transverseDiameter_);\n\n    // Mark as up to date\n    dataPtr_->isTransformUpToDate_ = true;\n}\n", "meta": {"hexsha": "028a26580024288f1e88d55430a9e26ccef4b0fb", "size": 11233, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/ompl/util/src/ProlateHyperspheroid.cpp", "max_stars_repo_name": "ivaROS/ivaOmplCore", "max_stars_repo_head_hexsha": "3f5f47bb8f20c5eb82e84564342dd45f39d0c5f9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_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/util/src/ProlateHyperspheroid.cpp", "max_issues_repo_name": "ivaROS/ivaOmplCore", "max_issues_repo_head_hexsha": "3f5f47bb8f20c5eb82e84564342dd45f39d0c5f9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_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/util/src/ProlateHyperspheroid.cpp", "max_forks_repo_name": "ivaROS/ivaOmplCore", "max_forks_repo_head_hexsha": "3f5f47bb8f20c5eb82e84564342dd45f39d0c5f9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-04-16T14:01:10.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-20T09:46:59.000Z", "avg_line_length": 41.2977941176, "max_line_length": 216, "alphanum_fraction": 0.7159262886, "num_tokens": 2780, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6297746074044134, "lm_q2_score": 0.5273165233795671, "lm_q1q2_score": 0.3320905564892271}}
{"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 mcmc {\n\n\n    class photon {\n\n        public:\n            std::array<double, 4> data;\n            photon( 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\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) {\n        this->data = {{E, vx, vy, vz}};\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    // --------------------------------------------------\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, 4>> 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, 4> 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, 4> data = bucket[indx];\n        photon ph(data[0], data[1], data[2], data[3]);\n\n        return ph;\n    };\n\n    /// return i:th photon raw data\n    std::array<double, 4> 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    class electronBucket {\n\n        /// size of the bucket (in terms of photons)\n        size_t nElectrons = 0;\n\n        /// Photon container\n        std::vector<std::array<double, 4>> 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.data );\n        nElectrons++;\n    };\n\n    void electronBucket::replace( size_t indx, electron e ) {\n        bucket[indx] = e.data;\n    };\n\n    electron electronBucket::get( size_t indx ) {\n        std::array<double, 4> data = bucket[indx];\n        electron e(data[0], data[1], data[2], data[3]);\n\n        return e;\n    };\n\n\n\n\n\n\n\n    //-------------------------------------------------- \n    class Slab {\n\n\n        /// Box sizes\n        double xmin, xmax, ymin, ymax, zmin, zmax;\n\n        /// RNG seed\n        uint32_t rngSeed = 1; \n\n        /// RNG engine (Mersenne twister)\n        std::mt19937 rng;\n\n        /// Ready-made distribution for flat variables in [0, 2pi[\n        std::uniform_real_distribution<double> randPhi{0.0, 2.0*pi};\n          \n        /// Ready-made distribution for flat variables in [0,1[\n        std::uniform_real_distribution<double> randmu{0.0, 1.0};\n\n        /// Random spherical direction (r, theta, phi) with Lamberts law\n        vec randSph() {\n            return {{ 1.0, std::acos(std::pow(randmu(rng),0.5)), randPhi(rng) }};\n        };\n\n        /// Random direction in Cartesian (vx, vy, vx) coordinates\n        // done via spherical coordinates (r, theta, phi) and then transforming back\n        vec randHalfSphere() {\n            vec sphDirs = randSph();\n            vec ret = \n            {{\n                sphDirs[0] * std::sin(sphDirs[1]) * std::cos(sphDirs[2]),\n                sphDirs[0] * std::sin(sphDirs[1]) * std::sin(sphDirs[2]),\n                sphDirs[0] * std::cos(sphDirs[1])\n            }};\n\n            return ret;\n        };\n\n\n\n        /// Draw samples from Planck function using series sampling\n        double Planck(double kT) {\n\n            double z1 = randmu(rng);\n            double z2 = randmu(rng);\n            double z3 = randmu(rng);\n            double x = -1.0*log(z1*z2*z3);\n\n            double j = 1.0;\n            double a = 1.0;\n            z1 = randmu(rng);\n            \n            // 90/pi^4 (rounded down to get finite loop)\n            while (1.08232*z1 > a) {\n                j += 1.0;\n                a += 1.0 / std::pow(j, 4.0);\n            }\n            return kT * x/j;\n        };\n\n\n        /// Sampling relativistic Maxwellian using the Sobol method\n        // u = v*gamma\n        double relMaxwellianVel(double Te) {\n            double x4 = randmu(rng);\n            double x5 = randmu(rng);\n            double x6 = randmu(rng);\n            double x7 = randmu(rng);\n\n            double u = -Te*log(x4*x5*x6);\n            double n = -Te*log(x4*x5*x6*x7);\n\n            if (n*n - u*u < 1.0) { return relMaxwellianVel(Te); };\n\n            return u;\n        };\n\n        /// Sampling from non-relativistic Maxwellian with rejection sampling\n        // NOTE: these are coordinate velocities\n        double MaxwellianVel(double Te) {\n            double vmin = -5.0*Te; \n            double vmax =  5.0*Te; \n            double vf = vmin + (vmax-vmin)*randmu(rng);\n\n            double f = vf*vf*std::exp(-(vf*vf)/(2.0*Te));\n            double x = randmu(rng);\n\n            if (x > f) { return MaxwellianVel(Te); };\n\n            return vf;\n        };\n\n\n        /// Isotropic velocity components\n        // using u = abs(u_i) to get cartesian (ux, uy, uz)\n        vec velXYZ(double u ) {\n            double x1 = randmu(rng);\n            double x2 = randmu(rng);\n\n            vec ret = \n            {{\n                    u*(2.0*x1 - 1.0),\n                    2.0*u*sqrt(x1*(1.0-x1))*cos(2.0*pi*x2),\n                    2.0*u*sqrt(x1*(1.0-x1))*sin(2.0*pi*x2)\n            }};\n\n            return ret;\n        };\n        \n\n        public:\n        /// General boosted non-rel/rel Maxwellian\n        // Te: electron temperature in m_e c^2\n        // G:  Bulk Lorentz vector\n        //\n        // Ref: Zenitani 2015\n        // NOTE: these are proper velocities and gamma = sqrt(1+u^2)\n        vec boostedMaxwellian(double Te, vec G) {\n\n            double u;\n            if (Te > 0.2) { // relativistic\n                u = relMaxwellianVel(Te);\n            } else { // non-relativistic\n                u = MaxwellianVel(Te);\n            }\n                \n            // get isotropic velocity components\n            vec ui = velXYZ(u);\n\n            // check if bulk velocity\n            if (G[0] == 0.0 && G[1] == 0.0 && G[2] == 0.0) {\n                return ui;\n            }\n\n            // next boost in X dir; TODO generalize\n            vec beta = \n            {{ \n                1.0/sqrt(1.0 + G[0]*G[0]),\n                1.0/sqrt(1.0 + G[1]*G[1]),\n                1.0/sqrt(1.0 + G[2]*G[2])\n            }};\n\n\n            double x8 = randmu(rng);\n            if (-beta[0]*ui[0] > x8) { ui[0] = -ui[0]; };\n            ui[0] = G[0]*(ui[0] + beta[0]*std::sqrt(1.0 + u*u));\n            // u = std::sqrt(ui[0]*ui[0] + ui[1]*ui[1] + ui[2]*ui[2]);\n\n            return ui;\n        };\n\n\n        /// Compton scattering using Sobol's algorithm\n        std::pair<photon, electron> comptonScatter(photon ph, electron el) {\n\n            // fmt::print(\"v: {}\\n\", el.v());\n            // fmt::print(\"E: {}\\n\", ph.hv());\n\n            Vector3d ve( el.vx(), el.vy(), el.vz() );\n            Vector3d beta = ve.normalized();\n            Vector3d omeg(ph.vx(), ph.vy(), ph.vz());\n\n            double theta = acos( beta.dot(omeg) );\n\n            // Create base vectors and matrix\n            //-------------------------------------------------- \n            // k\n            Vector3d kvec(0.0, -1.0, 0.0);\n\n            // j\n            Vector3d jvec = beta.cross(omeg);\n            jvec = jvec/jvec.norm();\n\n            // i\n            Vector3d ivec = kvec.cross(jvec);\n            ivec = ivec/ivec.norm();\n\n            Matrix3d M;\n            M << ivec, jvec, kvec;\n\n            // --------------------------------------------------\n            \n            // unit vector of electron in scattering coordinates\n            Vector3d v0 = M.transpose() * ve; // rotate electron velocity to scattering plane (i,k)\n            double mu = v0(0)*sin(theta) + v0(2)*cos(theta);\n            double rho = sqrt( pow(v0(0),2.0) + pow(v0(1),2.0) );\n\n            // Compton parameter\n            double y = ph.hv() * el.gamma() * (1.0 - mu*el.v() );\n            \n\n            // Additional scattering angles (v0, w0, t0) that define a frame of reference\n            Vector3d w0(v0(1)/rho,      -v0(0)/rho,        0.0);\n            Vector3d t0(v0(0)*v0(2)/rho, v0(1)*v0(2)/rho, -rho);\n\n\n            // --------------------------------------------------\n            // scatter\n            double OOp, z1, z2, z3, mup, phip, yp, Y; \n            while (true) {\n                z1 = randmu(rng);\n                z2 = randmu(rng);\n                z3 = randmu(rng);\n\n                mup  = (el.v() + 2.0*z1 - 1.0)/(1.0 + el.v()*(2.0*z1 - 1.0));\n                phip = 2.0*pi*z2;\n\n                OOp = mu*mup - sqrt(1.0-mup*mup) * (rho*sin(phip)*cos(theta) \n                      - (1.0/rho)*(v0(1)*cos(phip) + v0(0)*v0(2)*sin(phip))*sin(theta));\n\n                yp = y/(1.0 + ph.hv()*(1.0 - OOp))/(el.gamma() * (1.0-mup*el.v()));\n                Y = yp/y + pow(yp/y,3) + pow(yp/y,2)*\n                    ( pow(1.0/yp - 1.0/y, 2) - 2.0*( 1.0/yp - 1.0/y) );\n\n                if (Y>2.0*z3) { break; };\n            }\n\n            // --------------------------------------------------\n            // we have now scattered successfully\n              \n            // new energy\n            double hvp = yp/( el.gamma()*(1.0 - mup*el.v()) );\n\n            // new direction from ijk base to xyz base\n            Vector3d Op_ijk = mup*v0 \n                          + sqrt(1.0-mup*mup)*( w0*cos(phip) + t0*sin(phip) );\n            Vector3d Op = (M.transpose().inverse() * Op_ijk).normalized();\n\n\n            // pack everything to classes and return\n            photon phs(hvp, Op(0), Op(1), Op(2));\n\n            return std::make_pair(phs, el);\n        };\n\n\n        public:\n         \n            /// photon container\n            photonBucket bucket;\n\n            /// Overflow bucket \n            photonBucket overflow;\n\n\n            /// Simulation time step (in units of c)\n            double dt = 0.1;\n\n            /// Slab height\n            double height = 1.0;\n\n            /// electron number density\n            double ne = 0.0;\n\n            /// Thomson optical depth\n            double tau = 0.0;\n\n\n            /// location containers\n            std::vector<double> xloc, yloc, zloc;\n\n\n            /// Constructor\n            Slab(photonBucket b) {\n                this->bucket = b;\n\n                // prepare location containers\n                xloc.resize( bucket.size() );\n                yloc.resize( bucket.size() );\n                zloc.resize( bucket.size() );\n\n                // Finally seed the rng\n                rng.seed( rngSeed );\n            };\n              \n            /// Number of photons in the slab\n            const size_t size( ) {return this->bucket.size(); };\n\n\n            /// Set slab dimensions; z is implicitly assumed as the height\n            void set_dimensions(double _xmin, double _xmax,\n                                double _ymin, double _ymax,\n                                double _zmin, double _zmax) {\n\n                this->xmin = _xmin;\n                this->xmax = _xmax;\n                this->ymin = _ymin;\n                this->ymax = _ymax;\n                this->zmin = _zmin;\n                this->zmax = _zmax;\n\n                this->height = zmax - zmin;\n            };\n\n\n            /// Set number density and compute Thomson optical depth based on it\n            void set_numberDensity(double _ne) {\n                this->ne = _ne;\n\n                // compute Thomson tau = sigma_T * n_e * H\n                tau = 1.0 * ne * height;\n            };\n\n\n            /// Step in time performing the full radiation interactions\n            void step() {\n\n                push();\n                // wrap();\n                // emergingFlux();\n                \n                // check_scatter();\n                // scatter();\n                // inject();\n\n            };\n\n\n            /// Push photons\n            // TODO: Properly vectorize although this probably implicitly works \n            // already on compiler level\n            void push() {\n\n                size_t N = this->size();\n                std::vector<double> vx, vy, vz;\n                vx.resize(N);\n                vy.resize(N);\n                vz.resize(N);\n\n                // get velocities from bucket\n                for (size_t i=0; i<N; i++) {\n                    auto vel = this->bucket.get_data(i);\n                    vx[i] = vel[1];\n                    vy[i] = vel[2];\n                    vz[i] = vel[3];\n                }\n\n                // step forward in time\n                for (size_t i=0; i<N; i++) {\n                    xloc[i] += vx[i]*dt;\n                    yloc[i] += vy[i]*dt;\n                    zloc[i] += vz[i]*dt;\n                }\n            };\n\n\n\n            /// Inject more from the floor\n            void inject(double flux) {\n\n                // size of the floor\n                double area = (xmax-xmin)*(ymax-ymin);\n\n                // how many to inject based on the flux\n                size_t Ninj = (size_t)flux*area*dt;\n\n                // fmt::print(\"Injecting {} photons...\\n\", Ninj);\n\n                // resize beforehand \n                size_t Ns = size();\n                bucket.resize(Ns + Ninj);\n                xloc.resize(Ns + Ninj);\n                yloc.resize(Ns + Ninj);\n                zloc.resize(Ns + Ninj);\n\n\n                for (size_t i=0; i<Ninj; i++) {\n\n                    // create random photon\n                    double E = Planck(1.0);\n\n                    vec dir = randHalfSphere();\n                    photon ph(E, dir[0], dir[1], dir[2]);\n\n                    bucket.replace( Ns + i, ph );\n\n                    // set location\n                    xloc[Ns + i] = 0.0; // TODO random loc\n                    yloc[Ns + i] = 0.0; // TODO random loc\n                    zloc[Ns + i] = 0.0; // bottom\n                }\n\n            };\n\n\n            /// Scrape photons that are overflowing from the slab\n            void scrape() {\n\n                size_t i = 0;\n                size_t Nspills = 0;\n\n                while ( i<size()-Nspills) {\n                    if (zloc[i] >= height) {\n                        // swamp everything to the end and remove later\n                        // fmt::print(\"{} swapping {} to {} \\n\", i, yloc[i], yloc[size()-Nspills-1]);\n\n                        std::swap( xloc[i], xloc[size() - Nspills - 1] );\n                        std::swap( yloc[i], yloc[size() - Nspills - 1] );\n                        std::swap( zloc[i], zloc[size() - Nspills - 1] );\n                        bucket.swap( i, size()-Nspills - 1 );\n\n                        Nspills++;\n                    } else { \n                        i++;\n                    }\n                }\n\n                // collecting spills\n                // fmt::print(\"Scraping spills: {} // total size: {}\\n\", Nspills, size());\n                for (size_t i=size()-Nspills; i<size(); i++) {\n                    photon ph = bucket.get(i);\n                    // fmt::print(\"  spill {}\\n\", ph.hv() );\n\n                    overflow.push_back(ph);\n                }\n\n                // and finally remove \n                xloc.resize(size() - Nspills); \n                yloc.resize(size() - Nspills); \n                zloc.resize(size() - Nspills); \n                bucket.resize(size() - Nspills);\n\n                //fmt::print(\"after size {}\\n\", size());\n            };\n\n\n            /// inject everything from point in bottom\n            void floor() {\n                for (size_t i=0; i<size(); i++) {\n                    zloc[i] = zmin;\n\n                    // center of floor\n                    xloc[i] = 0.0;\n                    yloc[i] = 0.0;\n                }\n            };\n\n\n            /// Wrap into xy box bounded by [xmin, xmax] x [ymin, ymax]\n            void wrap() {\n\n                for (size_t i=0; i<size(); i++) {\n                    if (xloc[i] < xmin) { xloc[i] += xmax; }\n                    if (xloc[i] > xmax) { xloc[i] -= xmax; }\n\n                    if (yloc[i] < ymin) { yloc[i] += ymax; }\n                    if (yloc[i] > ymax) { yloc[i] -= ymax; }\n                }\n\n            };\n\n            // Check the optical distance and then scatter\n            void scatter(double Te) {\n\n                double x, y, z, z0;\n\n                double etau = std::exp(-dt/ne);\n\n                for (size_t i=0; i<size(); i++) {\n                    z = zloc[i];\n\n                    // scatter if e^-d\\tau < rand()\n                    z0 = randmu(rng);\n                    if (etau < z0) {\n                        photon ph = bucket.get(i);\n\n                        // isotropic mono-energetic electron\n                        // vec ve = velXYZ(0.8); // (beta)\n                        // electron el(1.0, ve[0], ve[1], ve[2]);\n\n                        // isotropic Maxwellian electrons\n                        fmt::print(\"sampling from Maxwellian...\\n\");\n                        vec ve = boostedMaxwellian(Te, {{0.0, 0.0, 0.0}});\n                        electron el(1.0, ve[0], ve[1], ve[2]);\n\n                        fmt::print(\"vx {} / vy {} / vz {}\", el.vx(), el.vy(), el.vz());\n                        fmt::print(\"target electron gamma: {} \\n\", el.gamma() );\n                        fmt::print(\"target electron beta: {} \\n\", el.v() );\n\n\n                        auto ret = comptonScatter(ph, el);\n                        bucket.replace(i, ret.first );\n                    }\n\n                }\n\n            };\n\n\n    };\n\n\n    \n\n\n}\n\n\n\n\n\n\n// --------------------------------------------------\nPYBIND11_MODULE(mcmc, m) {\n\n\n    py::class_<mcmc::photon>(m, \"photon\" )\n        .def(py::init<double, double, double, double >())\n        .def_readwrite(\"data\",      &mcmc::photon::data)\n        .def(\"hv\",  &mcmc::photon::hv)\n        .def(\"vx\",  &mcmc::photon::vx)\n        .def(\"vy\",  &mcmc::photon::vy)\n        .def(\"vz\",  &mcmc::photon::vz);\n\n    py::class_<mcmc::electron>(m, \"electron\" )\n        .def(py::init<double, double, double, double >())\n        .def_readwrite(\"data\",      &mcmc::electron::data)\n        .def(\"v0\",    &mcmc::electron::v0)\n        .def(\"vx\",    &mcmc::electron::vx)\n        .def(\"vy\",    &mcmc::electron::vy)\n        .def(\"vz\",    &mcmc::electron::vz)\n        .def(\"v\",     &mcmc::electron::v)\n        .def(\"gamma\", &mcmc::electron::gamma);\n\n    py::class_<mcmc::photonBucket>(m, \"photonBucket\" )\n        .def(py::init<>())\n        .def(\"size\",      &mcmc::photonBucket::size)\n        .def(\"replace\",   &mcmc::photonBucket::replace)\n        .def(\"get\",       &mcmc::photonBucket::get)\n        .def(\"vecE\",      &mcmc::photonBucket::vecE)\n        .def(\"vecZ\",      &mcmc::photonBucket::vecZ)\n        .def(\"push_back\", &mcmc::photonBucket::push_back);\n\n    py::class_<mcmc::electronBucket>(m, \"electronBucket\" )\n        .def(py::init<>())\n        .def(\"size\",      &mcmc::electronBucket::size)\n        .def(\"replace\",   &mcmc::electronBucket::replace)\n        .def(\"get\",       &mcmc::electronBucket::get)\n        .def(\"push_back\", &mcmc::electronBucket::push_back);\n\n\n    py::class_<mcmc::Slab>(m, \"Slab\" )\n        .def(py::init< mcmc::photonBucket >())\n        .def_readwrite(\"xloc\",    &mcmc::Slab::xloc)\n        .def_readwrite(\"yloc\",    &mcmc::Slab::yloc)\n        .def_readwrite(\"zloc\",    &mcmc::Slab::zloc)\n        .def_readwrite(\"tau\",     &mcmc::Slab::tau)\n        .def_readwrite(\"height\",  &mcmc::Slab::height)\n        .def_readwrite(\"ne\",      &mcmc::Slab::ne)\n        .def_readonly(\"bucket\",   &mcmc::Slab::bucket)\n        .def_readonly(\"overflow\", &mcmc::Slab::overflow)\n        .def(\"size\",              &mcmc::Slab::size)\n        .def(\"push\",              &mcmc::Slab::push)\n        .def(\"inject\",            &mcmc::Slab::inject)\n        .def(\"set_dimensions\",    &mcmc::Slab::set_dimensions)\n        .def(\"set_numberDensity\", &mcmc::Slab::set_numberDensity)\n        .def(\"scrape\",            &mcmc::Slab::scrape)\n        .def(\"wrap\",              &mcmc::Slab::wrap)\n        .def(\"scatter\",           &mcmc::Slab::scatter)\n        .def(\"boostedMaxwellian\", &mcmc::Slab::boostedMaxwellian)\n        .def(\"comptonScatter\",    &mcmc::Slab::comptonScatter)\n        .def(\"floor\",             &mcmc::Slab::floor);\n\n\n\n        // -------------------------------------------------- \n        // Bare bones array interface\n        /*\n        .def(\"__getitem__\", [](const Sequence &s, size_t i) {\n            if (i >= s.size()) throw py::index_error();\n            return s[i];\n        })\n        .def(\"__setitem__\", [](Sequence &s, size_t i, float v) {\n            if (i >= s.size()) throw py::index_error();\n            s[i] = v;\n        })\n        // Slices [optional]\n        .def(\"__getitem__\", [](const Sequence &s, py::slice slice) -> Sequence* {\n            size_t start, stop, step, slicelength;\n            if (!slice.compute(s.size(), &start, &stop, &step, &slicelength))\n                throw py::error_already_set();\n            Sequence *seq = new Sequence(slicelength);\n            for (size_t i = 0; i < slicelength; ++i) {\n                (*seq)[i] = s[start]; start += step;\n            }\n            return seq;\n        })\n        .def(\"__setitem__\", [](Sequence &s, py::slice slice, const Sequence &value) {\n            size_t start, stop, step, slicelength;\n            if (!slice.compute(s.size(), &start, &stop, &step, &slicelength))\n                throw py::error_already_set();\n            if (slicelength != value.size())\n                throw std::runtime_error(\"Left and right hand size of slice assignment have different sizes!\");\n            for (size_t i = 0; i < slicelength; ++i) {\n                s[start] = value[i]; start += step;\n            }\n        })\n        .def(\"__getitem__\", [](const mcmc::vMesh &s, uint64_t i) {\n                return s.__getitem__(i);\n        })\n        .def(\"__setitem__\", [](mcmc::vMesh &s, uint64_t i, vblock_t v) {\n                s.__setitem__(i, v);\n        })\n        // i,j,k indexing based interface\n        .def(\"__getitem__\", [](const mcmc::vMesh &s, py::tuple indx) {\n                size_t i = indx[0].cast<size_t>();\n                size_t j = indx[1].cast<size_t>();\n                size_t k = indx[2].cast<size_t>();\n                return s.__getitem2__( i,j,k );\n        })\n        .def(\"__setitem__\", [](mcmc::vMesh &s, py::tuple indx, vblock_t v) {\n                size_t i = indx[0].cast<size_t>();\n                size_t j = indx[1].cast<size_t>();\n                size_t k = indx[2].cast<size_t>();\n                return s.__setitem2__( i,j,k, v);\n        })\n\n        // .def(\"__setitem__\", [](mcmc::vMesh &s, uint64_t i, vblock_t v) {\n        //         s.__setitem__(i, v);\n        // })\n        */\n\n\n}\n", "meta": {"hexsha": "f519393388df507e07980388d5162059da5ce6f8", "size": 26118, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "prototypes/compton/mcmc_electron_bucket.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/mcmc_electron_bucket.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/mcmc_electron_bucket.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": 30.511682243, "max_line_length": 111, "alphanum_fraction": 0.4411134084, "num_tokens": 6712, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6297746074044134, "lm_q2_score": 0.5273165233795671, "lm_q1q2_score": 0.3320905564892271}}
{"text": "// Distributed under the MIT License.\n// See LICENSE.txt for details.\n\n#include \"Evolution/Systems/NewtonianEuler/Limiters/CharacteristicHelpers.hpp\"\n\n#include <array>\n#include <boost/functional/hash.hpp>  // IWYU pragma: keep\n#include <cstddef>\n#include <limits>\n#include <string>\n#include <type_traits>\n#include <unordered_map>\n#include <utility>\n\n#include \"DataStructures/Tags.hpp\"\n#include \"DataStructures/Tensor/EagerMath/DotProduct.hpp\"\n#include \"DataStructures/Tensor/Tensor.hpp\"\n#include \"DataStructures/Variables.hpp\"\n#include \"Domain/Structure/Element.hpp\"  // IWYU pragma: keep\n#include \"Domain/Tags.hpp\"               // IWYU pragma: keep\n#include \"ErrorHandling/Assert.hpp\"\n#include \"Evolution/Systems/NewtonianEuler/Characteristics.hpp\"\n#include \"Evolution/Systems/NewtonianEuler/SoundSpeedSquared.hpp\"\n#include \"Evolution/Systems/NewtonianEuler/Tags.hpp\"\n#include \"NumericalAlgorithms/Spectral/Mesh.hpp\"\n#include \"Utilities/GenerateInstantiations.hpp\"\n#include \"Utilities/Gsl.hpp\"\n#include \"Utilities/TMPL.hpp\"\n#include \"Utilities/TaggedTuple.hpp\"\n\nnamespace NewtonianEuler::Limiters {\n\ntemplate <size_t VolumeDim, size_t ThermodynamicDim>\nstd::pair<Matrix, Matrix> right_and_left_eigenvectors(\n    const Scalar<double>& mean_density,\n    const tnsr::I<double, VolumeDim>& mean_momentum,\n    const Scalar<double>& mean_energy,\n    const EquationsOfState::EquationOfState<false, ThermodynamicDim>&\n        equation_of_state,\n    const tnsr::i<double, VolumeDim>& unit_normal) noexcept {\n  // Compute fluid primitives from mean conserved state\n  const auto velocity = [&mean_density, &mean_momentum]() noexcept {\n    auto result = mean_momentum;\n    for (size_t i = 0; i < VolumeDim; ++i) {\n      result.get(i) /= get(mean_density);\n    }\n    return result;\n  }();\n  const auto specific_internal_energy = [&mean_density, &mean_energy,\n                                         &mean_momentum]() noexcept {\n    auto result = mean_energy;\n    get(result) /= get(mean_density);\n    get(result) -= 0.5 * get(dot_product(mean_momentum, mean_momentum)) /\n                   square(get(mean_density));\n    return result;\n  }();\n\n  Scalar<double> pressure{};\n  Scalar<double> kappa_over_density{};\n  if constexpr (ThermodynamicDim == 1) {\n    pressure = equation_of_state.pressure_from_density(mean_density);\n    get(kappa_over_density) =\n        get(equation_of_state.kappa_times_p_over_rho_squared_from_density(\n            mean_density)) *\n        get(mean_density) / get(pressure);\n  } else if constexpr (ThermodynamicDim == 2) {\n    pressure = equation_of_state.pressure_from_density_and_energy(\n        mean_density, specific_internal_energy);\n    get(kappa_over_density) =\n        get(equation_of_state\n                .kappa_times_p_over_rho_squared_from_density_and_energy(\n                    mean_density, specific_internal_energy)) *\n        get(mean_density) / get(pressure);\n  }\n\n  const Scalar<double> specific_enthalpy{\n      {{(get(mean_energy) + get(pressure)) / get(mean_density)}}};\n  const Scalar<double> sound_speed_squared =\n      NewtonianEuler::sound_speed_squared(\n          mean_density, specific_internal_energy, equation_of_state);\n\n  return std::make_pair(right_eigenvectors<VolumeDim>(\n                            velocity, sound_speed_squared, specific_enthalpy,\n                            kappa_over_density, unit_normal),\n                        left_eigenvectors<VolumeDim>(\n                            velocity, sound_speed_squared, specific_enthalpy,\n                            kappa_over_density, unit_normal));\n}\n\ntemplate <size_t VolumeDim>\nvoid characteristic_fields(\n    const gsl::not_null<tuples::TaggedTuple<\n        ::Tags::Mean<NewtonianEuler::Tags::VMinus>,\n        ::Tags::Mean<NewtonianEuler::Tags::VMomentum<VolumeDim>>,\n        ::Tags::Mean<NewtonianEuler::Tags::VPlus>>*>\n        char_means,\n    const tuples::TaggedTuple<\n        ::Tags::Mean<NewtonianEuler::Tags::MassDensityCons>,\n        ::Tags::Mean<NewtonianEuler::Tags::MomentumDensity<VolumeDim>>,\n        ::Tags::Mean<NewtonianEuler::Tags::EnergyDensity>>& cons_means,\n    const Matrix& left) noexcept {\n  auto& char_v_minus =\n      get<::Tags::Mean<NewtonianEuler::Tags::VMinus>>(*char_means);\n  auto& char_v_momentum =\n      get<::Tags::Mean<NewtonianEuler::Tags::VMomentum<VolumeDim>>>(\n          *char_means);\n  auto& char_v_plus =\n      get<::Tags::Mean<NewtonianEuler::Tags::VPlus>>(*char_means);\n\n  const auto& cons_mass_density =\n      get<::Tags::Mean<NewtonianEuler::Tags::MassDensityCons>>(cons_means);\n  const auto& cons_momentum_density =\n      get<::Tags::Mean<NewtonianEuler::Tags::MomentumDensity<VolumeDim>>>(\n          cons_means);\n  const auto& cons_energy_density =\n      get<::Tags::Mean<NewtonianEuler::Tags::EnergyDensity>>(cons_means);\n\n  get(char_v_minus) = left(0, 0) * get(cons_mass_density);\n  for (size_t j = 0; j < VolumeDim; ++j) {\n    char_v_momentum.get(j) = left(j + 1, 0) * get(cons_mass_density);\n  }\n  get(char_v_plus) = left(VolumeDim + 1, 0) * get(cons_mass_density);\n\n  for (size_t i = 0; i < VolumeDim; ++i) {\n    get(char_v_minus) += left(0, i + 1) * cons_momentum_density.get(i);\n    for (size_t j = 0; j < VolumeDim; ++j) {\n      char_v_momentum.get(j) +=\n          left(j + 1, i + 1) * cons_momentum_density.get(i);\n    }\n    get(char_v_plus) +=\n        left(VolumeDim + 1, i + 1) * cons_momentum_density.get(i);\n  }\n\n  get(char_v_minus) += left(0, VolumeDim + 1) * get(cons_energy_density);\n  for (size_t j = 0; j < VolumeDim; ++j) {\n    char_v_momentum.get(j) +=\n        left(j + 1, VolumeDim + 1) * get(cons_energy_density);\n  }\n  get(char_v_plus) +=\n      left(VolumeDim + 1, VolumeDim + 1) * get(cons_energy_density);\n}\n\ntemplate <size_t VolumeDim>\nvoid characteristic_fields(\n    const gsl::not_null<Scalar<DataVector>*> char_v_minus,\n    const gsl::not_null<tnsr::I<DataVector, VolumeDim>*> char_v_momentum,\n    const gsl::not_null<Scalar<DataVector>*> char_v_plus,\n    const Scalar<DataVector>& cons_mass_density,\n    const tnsr::I<DataVector, VolumeDim>& cons_momentum_density,\n    const Scalar<DataVector>& cons_energy_density,\n    const Matrix& left) noexcept {\n  get(*char_v_minus) = left(0, 0) * get(cons_mass_density);\n  for (size_t j = 0; j < VolumeDim; ++j) {\n    char_v_momentum->get(j) = left(j + 1, 0) * get(cons_mass_density);\n  }\n  get(*char_v_plus) = left(VolumeDim + 1, 0) * get(cons_mass_density);\n\n  for (size_t i = 0; i < VolumeDim; ++i) {\n    get(*char_v_minus) += left(0, i + 1) * cons_momentum_density.get(i);\n    for (size_t j = 0; j < VolumeDim; ++j) {\n      char_v_momentum->get(j) +=\n          left(j + 1, i + 1) * cons_momentum_density.get(i);\n    }\n    get(*char_v_plus) +=\n        left(VolumeDim + 1, i + 1) * cons_momentum_density.get(i);\n  }\n\n  get(*char_v_minus) += left(0, VolumeDim + 1) * get(cons_energy_density);\n  for (size_t j = 0; j < VolumeDim; ++j) {\n    char_v_momentum->get(j) +=\n        left(j + 1, VolumeDim + 1) * get(cons_energy_density);\n  }\n  get(*char_v_plus) +=\n      left(VolumeDim + 1, VolumeDim + 1) * get(cons_energy_density);\n}\n\ntemplate <size_t VolumeDim>\nvoid characteristic_fields(\n    const gsl::not_null<\n        Variables<tmpl::list<NewtonianEuler::Tags::VMinus,\n                             NewtonianEuler::Tags::VMomentum<VolumeDim>,\n                             NewtonianEuler::Tags::VPlus>>*>\n        char_vars,\n    const Variables<tmpl::list<NewtonianEuler::Tags::MassDensityCons,\n                               NewtonianEuler::Tags::MomentumDensity<VolumeDim>,\n                               NewtonianEuler::Tags::EnergyDensity>>& cons_vars,\n    const Matrix& left) noexcept {\n  characteristic_fields(\n      make_not_null(&get<NewtonianEuler::Tags::VMinus>(*char_vars)),\n      make_not_null(\n          &get<NewtonianEuler::Tags::VMomentum<VolumeDim>>(*char_vars)),\n      make_not_null(&get<NewtonianEuler::Tags::VPlus>(*char_vars)),\n      get<NewtonianEuler::Tags::MassDensityCons>(cons_vars),\n      get<NewtonianEuler::Tags::MomentumDensity<VolumeDim>>(cons_vars),\n      get<NewtonianEuler::Tags::EnergyDensity>(cons_vars), left);\n}\n\ntemplate <size_t VolumeDim>\nvoid conserved_fields_from_characteristic_fields(\n    const gsl::not_null<Scalar<DataVector>*> cons_mass_density,\n    const gsl::not_null<tnsr::I<DataVector, VolumeDim>*> cons_momentum_density,\n    const gsl::not_null<Scalar<DataVector>*> cons_energy_density,\n    const Scalar<DataVector>& char_v_minus,\n    const tnsr::I<DataVector, VolumeDim>& char_v_momentum,\n    const Scalar<DataVector>& char_v_plus, const Matrix& right) noexcept {\n  get(*cons_mass_density) = right(0, 0) * get(char_v_minus);\n  for (size_t j = 0; j < VolumeDim; ++j) {\n    cons_momentum_density->get(j) = right(j + 1, 0) * get(char_v_minus);\n  }\n  get(*cons_energy_density) = right(VolumeDim + 1, 0) * get(char_v_minus);\n\n  for (size_t i = 0; i < VolumeDim; ++i) {\n    get(*cons_mass_density) += right(0, i + 1) * char_v_momentum.get(i);\n    for (size_t j = 0; j < VolumeDim; ++j) {\n      cons_momentum_density->get(j) +=\n          right(j + 1, i + 1) * char_v_momentum.get(i);\n    }\n    get(*cons_energy_density) +=\n        right(VolumeDim + 1, i + 1) * char_v_momentum.get(i);\n  }\n\n  get(*cons_mass_density) += right(0, VolumeDim + 1) * get(char_v_plus);\n  for (size_t j = 0; j < VolumeDim; ++j) {\n    cons_momentum_density->get(j) +=\n        right(j + 1, VolumeDim + 1) * get(char_v_plus);\n  }\n  get(*cons_energy_density) +=\n      right(VolumeDim + 1, VolumeDim + 1) * get(char_v_plus);\n}\n\n#define DIM(data) BOOST_PP_TUPLE_ELEM(0, data)\n#define THERMODIM(data) BOOST_PP_TUPLE_ELEM(1, data)\n\n#define INSTANTIATE(_, data)                                            \\\n  template std::pair<Matrix, Matrix> right_and_left_eigenvectors(       \\\n      const Scalar<double>&, const tnsr::I<double, DIM(data)>&,         \\\n      const Scalar<double>&,                                            \\\n      const EquationsOfState::EquationOfState<false, THERMODIM(data)>&, \\\n      const tnsr::i<double, DIM(data)>&) noexcept;\n\nGENERATE_INSTANTIATIONS(INSTANTIATE, (1, 2, 3), (1, 2))\n\n#undef THERMODIM\n#undef INSTANTIATE\n\n#define INSTANTIATE(_, data)                                               \\\n  template void characteristic_fields(                                     \\\n      const gsl::not_null<tuples::TaggedTuple<                             \\\n          ::Tags::Mean<NewtonianEuler::Tags::VMinus>,                      \\\n          ::Tags::Mean<NewtonianEuler::Tags::VMomentum<DIM(data)>>,        \\\n          ::Tags::Mean<NewtonianEuler::Tags::VPlus>>*>,                    \\\n      const tuples::TaggedTuple<                                           \\\n          ::Tags::Mean<NewtonianEuler::Tags::MassDensityCons>,             \\\n          ::Tags::Mean<NewtonianEuler::Tags::MomentumDensity<DIM(data)>>,  \\\n          ::Tags::Mean<NewtonianEuler::Tags::EnergyDensity>>&,             \\\n      const Matrix&) noexcept;                                             \\\n  template void characteristic_fields(                                     \\\n      const gsl::not_null<Scalar<DataVector>*>,                            \\\n      const gsl::not_null<tnsr::I<DataVector, DIM(data)>*>,                \\\n      const gsl::not_null<Scalar<DataVector>*>, const Scalar<DataVector>&, \\\n      const tnsr::I<DataVector, DIM(data)>&, const Scalar<DataVector>&,    \\\n      const Matrix&) noexcept;                                             \\\n  template void characteristic_fields(                                     \\\n      const gsl::not_null<                                                 \\\n          Variables<tmpl::list<NewtonianEuler::Tags::VMinus,               \\\n                               NewtonianEuler::Tags::VMomentum<DIM(data)>, \\\n                               NewtonianEuler::Tags::VPlus>>*>,            \\\n      const Variables<                                                     \\\n          tmpl::list<NewtonianEuler::Tags::MassDensityCons,                \\\n                     NewtonianEuler::Tags::MomentumDensity<DIM(data)>,     \\\n                     NewtonianEuler::Tags::EnergyDensity>>&,               \\\n      const Matrix&) noexcept;                                             \\\n  template void conserved_fields_from_characteristic_fields(               \\\n      const gsl::not_null<Scalar<DataVector>*>,                            \\\n      const gsl::not_null<tnsr::I<DataVector, DIM(data)>*>,                \\\n      const gsl::not_null<Scalar<DataVector>*>, const Scalar<DataVector>&, \\\n      const tnsr::I<DataVector, DIM(data)>&, const Scalar<DataVector>&,    \\\n      const Matrix&) noexcept;\n\nGENERATE_INSTANTIATIONS(INSTANTIATE, (1, 2, 3))\n\n#undef DIM\n#undef INSTANTIATE\n\n}  // namespace NewtonianEuler::Limiters\n", "meta": {"hexsha": "f5888a284afe91a38241d9520fa50b9799394b03", "size": 12701, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Evolution/Systems/NewtonianEuler/Limiters/CharacteristicHelpers.cpp", "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/Evolution/Systems/NewtonianEuler/Limiters/CharacteristicHelpers.cpp", "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/Evolution/Systems/NewtonianEuler/Limiters/CharacteristicHelpers.cpp", "max_forks_repo_name": "tomwlodarczyk/spectre", "max_forks_repo_head_hexsha": "086aaee002f2f07eb812cf17b8e1ba54052feb71", "max_forks_repo_licenses": ["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.4090909091, "max_line_length": 80, "alphanum_fraction": 0.6245177545, "num_tokens": 3281, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7025300698514777, "lm_q2_score": 0.4726834766204328, "lm_q1q2_score": 0.332074355847792}}
{"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#ifndef CONFORMAL_IDEAL_DELAUNAY_MAPPING_HH\n#define CONFORMAL_IDEAL_DELAUNAY_MAPPING_HH\n\n#include <set>\n#include <iomanip>\n#include <fstream>\n#include <ctime>\n#include <Eigen/Sparse>\n#include \"Angle.hh\"\n#include \"Claussen.hh\"\n#include \"OverlayMesh.hh\"\n\n#include <spdlog/spdlog.h>\n#include <spdlog/fmt/ostr.h>\n\nusing namespace OverlayProblem;\n\nstruct DelaunayStats {\n// Delaunay\n  int n_flips = 0, n_flips_s = 0, n_flips_t = 0, n_flips_q = 0, n_flips_12 = 0, n_nde = -1;\n   bool flip_count = false;          // when true: write out stats for different kinds of flips\n   std::vector<int> flip_seq;\n};\n\ntemplate <typename Scalar>\nstruct SolveStats { \n  int n_solves = 0, n_g = 0, n_checks = 0;\n  Scalar cetm_energy = 0;\n};\n\nstruct StatsParameters{\n  bool flip_count = false;      // when true: collect stats on different types of edge flips\n  std::string name = \"\";        // name of the model that's been tested - for logging purpose\n  std::string output_dir = \"\";  // directory name for genearting all stats\n  bool error_log = false;       // when true: write out per-newton iterations stats\n  bool print_summary = false;   // when true: add final stats of optimization to summary file\n  int log_level = 2;            // controlling detail of console logging\n};\n\nstruct LineSearchParameters { \n  double c1 = 1e-4;                  // c1 for armijo condition\n  double c2 = 0.9;                   // c2 for curvature condition\n  bool energy_samples = false;       // This boolean is only used for generating figure 4 in paper\n  bool energy_cond = false;          // when true: use energy decrease as line search stop criterion\n  bool do_reduction = false;         // when true: reduce step, if the components of descent direction vary too much \n  double descent_dir_max_variation = 1e-10; // threshold for descent direction component max difference to decrease step\n  bool do_grad_norm_decrease = true; // when true: require gradient norm to decrease at each iteration\n  double bound_norm_thres = 1e-10;   // threshold to drop gradient decrease requirement when step lambda is below this\n  double lambda0 = 1.0;              // starting lambda value for the line search, normally 1\n  bool reset_lambda = true;          // when true: start with lambda = lambda0 for each newton iteration; if false, start with lambda from the previous \n};\n\nstruct AlgorithmParameters {\n  int MPFR_PREC = 100;           // precision if done in multiprecision\n  bool initial_ptolemy = false;  // when true: use ptolemey flips for the first MakeDelaunay  Do we really need this?\n  // termination\n  double error_eps = 0;          // max angle error tolerance, terminate if below\n  double min_lambda = 1e-16;     // terminate if lambda drops below this threshold\n  double newton_decr_thres = 0;  // terminate if the newton decrement is above this threshold (it is negative)\n  int max_itr = 500;             // upper bound for newton iterations\n  bool bypass_overlay = false;       // avoid overlay computation\n };\n\n// Scalar: a floating point type, either double or MPFR\ntemplate <typename Scalar>\nclass ConformalIdealDelaunay\n{\npublic:\n  typedef Eigen::Matrix<Scalar, Eigen::Dynamic, 1> VectorX;\n\n  /**\n   * Interior angle and its cotangent computed for the whole mesh given decorated per-vertex u values,\n   * the angles are computed via rescaled conformal edge lengths.\n   * \n   * @param m Mesh data structure\n   * @param u vector of Scalar size equal to number of vertices of mesh, the per-vertex logarithmic scale factors\n   * @param alpha vector of Scalar size equal to number of halfedges of mesh,\n   *              ith entry corresponds to the interior angle opposite to\n   *              ith halfedge.\n   * @param cot_alpha vector of Scalar size equal to number of halfedges of mesh,\n   *              e.g. ith entry corresponds to the cotangent of interior angle opposite to\n   *              ith halfedge.\n   * @return void\n   */\n  static void ComputeAngles(const Mesh<Scalar>& m, const VectorX& u, VectorX& alpha, VectorX& cot_alpha)\n  {\n    \n    alpha.setZero(m.n_halfedges());\n    cot_alpha.setZero(m.n_halfedges());\n\n    const Scalar cot_infty = Scalar(1e10);\n\n    Scalar pi;\n#ifdef WITH_MPFR\n    if (std::is_same<Scalar, mpfr::mpreal>::value)\n      pi = Scalar(mpfr::const_pi());\n    else\n      pi = Scalar(M_PI);\n#else\n      pi = Scalar(M_PI);\n#endif\n\n#pragma omp parallel for\n    for (int f = 0; f < m.n_faces(); f++)\n    {\n      int hi = m.h[f];\n      int hj = m.n[hi];\n      int hk = m.n[hj];\n      int i = m.v_rep[m.to[hj]];\n      int j = m.v_rep[m.to[hk]];\n      int k = m.v_rep[m.to[hi]];\n      Scalar ui = u[i];\n      Scalar uj = u[j];\n      Scalar uk = u[k];\n      Scalar uijk_avg = (ui + uj + uk)/3.0; // Scale lengths for numerical stability\n      Scalar li = ell(m.l[m.e(hi)], uj, uk, uijk_avg);\n      Scalar lj = ell(m.l[m.e(hj)], uk, ui, uijk_avg);\n      Scalar lk = ell(m.l[m.e(hk)], ui, uj, uijk_avg);\n      // (following \"A Cotangent Laplacian for Images as Surfaces\")\n      Scalar s = (li + lj + lk) / 2.0;\n      Scalar Aijk4 = 4.0 * sqrt(std::max<Scalar>(s * (s - li) * (s - lj) * (s - lk), 0.0));\n      Scalar Ijk = (-li * li + lj * lj + lk * lk);\n      Scalar iJk = (li * li - lj * lj + lk * lk);\n      Scalar ijK = (li * li + lj * lj - lk * lk);\n      cot_alpha[hi] = Aijk4 == 0.0 ? copysign(cot_infty, Ijk) : (Ijk / Aijk4);\n      cot_alpha[hj] = Aijk4 == 0.0 ? copysign(cot_infty, iJk) : (iJk / Aijk4);\n      cot_alpha[hk] = Aijk4 == 0.0 ? copysign(cot_infty, ijK) : (ijK / Aijk4);\n\n#define USE_ACOS\n#ifdef USE_ACOS\n      alpha[hi] = acos(std::min<Scalar>(std::max<Scalar>(Ijk / (2.0 * lj * lk), -1.0), 1.0));\n      alpha[hj] = acos(std::min<Scalar>(std::max<Scalar>(iJk / (2.0 * lk * li), -1.0), 1.0));\n      alpha[hk] = acos(std::min<Scalar>(std::max<Scalar>(ijK / (2.0 * li * lj), -1.0), 1.0));\n#else\n      // atan2 is prefered for stability\n      alpha[hi] = 0.0, alpha[hj] = 0.0, alpha[hk] = 0.0;\n      // li: l12, lj: l23, lk: l31\n      Scalar l12 = li, l23 = lj, l31 = lk;\n      const Scalar t31 = +l12+l23-l31,\n                   t23 = +l12-l23+l31,\n                   t12 = -l12+l23+l31;\n      // valid triangle\n      if( t31 > 0 && t23 > 0 && t12 > 0 ){\n        const Scalar l123 = l12+l23+l31;\n        const Scalar denom = sqrt(t12*t23*t31*l123);\n        alpha[hj] = 2*atan2(t12*t31,denom); // a1 l23\n        alpha[hk] = 2*atan2(t23*t12,denom); // a2 l31\n        alpha[hi] = 2*atan2(t31*t23,denom); // a3 l12\n      }else if( t31 <= 0 ) alpha[hk] = pi;\n       else if( t23 <= 0 ) alpha[hj] = pi;\n       else if( t12 <= 0 ) alpha[hi] = pi;\n       else alpha[hj] = pi;\n#endif\n    }\n  }\n  \n  /**\n   * Milnor’s Lobachevsky function, see appendix A in http://www.multires.caltech.edu/pubs/ConfEquiv.pdf\n   */\n  static Scalar Lob(const Scalar angle)\n  {\n    return 0 <= angle && angle <= M_PI ? claussen(double(2 * angle)) / 2 : 0;\n  }\n\n  /**\n   * Compute angle sums at each vertex of given mesh according to per-corner angles\n   * \n   * @param m Mesh data structure\n   * @param alpha vector of Scalar size equal to number of halfedges of mesh,\n   *              ith entry corresponds to the interior angle opposite to\n   *              ith halfedge, e.g. the one computed by function `ComputeAngles`.\n   * @return VectorX vector of Scalar size equal to number of vertices of mesh,\n   *         each entry is the total angle sum at each vertex.\n   */\n  static VectorX Theta(const Mesh<Scalar>& m, const VectorX& alpha)\n  {\n    VectorX t(m.n_ind_vertices());\n    t.setZero();\n    for (int h = 0; h < m.n_halfedges(); h++)\n    {\n      t[m.v_rep[m.to[m.n[h]]]] += alpha[h];\n    }\n    return t;\n  }\n\n  /**\n   * Compute conformal-equivalence-energy (see https://cims.nyu.edu/gcl/papers/2021-Conformal.pdf section 4) \n   * of a given mesh with per-vertex logarithmic scale factors\n   * \n   * @param m Mesh data structure\n   * @param angles vector of Scalar with size equal to number of halfedges, produced by ComputeAngles function\n   * @param u vector of Scalar size equal to number of vertices of mesh, the per-vertex logarithmic scale factors\n   * @return Scalar Energy of the mesh with given conformal metric\n   */\n  static Scalar ConformalEquivalenceEnergy(Mesh<Scalar> &m, const VectorX& angles, const VectorX &u)\n  {\n\n    auto func_f = [](\n      const Scalar l12, const Scalar l23, const Scalar l31,  \n      const Scalar u1,  const Scalar u2,  const Scalar u3, \n      const Scalar a1, const Scalar a2, const Scalar a3\n    ){\n      // h1->hi, h2->hj, h3->hk\n      Scalar s12 = u1 + u2 - 2 * u3;\n      Scalar s23 = u2 + u3 - 2 * u1;\n      Scalar s31 = u3 + u1 - 2 * u2;\n      Scalar lt12 = l12 * exp(1.0 / 6.0 * s12);\n      Scalar lt23 = l23 * exp(1.0 / 6.0 * s23);\n      Scalar lt31 = l31 * exp(1.0 / 6.0 * s31);\n      Scalar lambda12 = 2 * log(l12);\n      Scalar lambda23 = 2 * log(l23);\n      Scalar lambda31 = 2 * log(l31);\n      Scalar lambdat12 = lambda12 + u1 + u2;\n      Scalar lambdat23 = lambda23 + u2 + u3;\n      Scalar lambdat31 = lambda31 + u3 + u1;\n      Scalar T1 = a1 * lambdat23 + a2 * lambdat31 + a3 * lambdat12;\n      Scalar T2 = Lob(a1) + Lob(a2) + Lob(a3);\n      return 0.5 * T1 + T2;\n    };\n\n    Scalar E = 0;\n\n    // first part of the energy on faces\n    Scalar total_f = 0.0;\n    for (int _f = 0; _f < m.n_faces(); _f++)\n    {\n      int h1 = m.h[_f], h2 = m.n[h1], h3 = m.n[h2];\n      int v1 = m.v_rep[m.to[h3]], v2 = m.v_rep[m.to[h1]], v3 = m.v_rep[m.to[h2]];\n      Scalar l12 = m.l[m.e(h1)], l23 = m.l[m.e(h2)], l31 = m.l[m.e(h3)];\n      Scalar u2 = u(m.v_rep[m.to[h1]]), u3 = u(m.v_rep[m.to[h2]]), u1 = u(m.v_rep[m.to[h3]]);\n      Scalar val_f = func_f(l12, l23, l31, u1, u2, u3, angles[h2], angles[h3], angles[h1]);\n      Scalar td_lambda_h1 = 2 * log(m.l[m.e(h1)]) + u[m.v_rep[m.to[h1]]] + u[m.v_rep[m.to[m.opp[h1]]]];\n      Scalar td_lambda_h2 = 2 * log(m.l[m.e(h2)]) + u[m.v_rep[m.to[h2]]] + u[m.v_rep[m.to[m.opp[h2]]]];\n      Scalar td_lambda_h3 = 2 * log(m.l[m.e(h3)]) + u[m.v_rep[m.to[h3]]] + u[m.v_rep[m.to[m.opp[h3]]]];\n      auto e_tri = val_f - (M_PI / 4) * (td_lambda_h1 + td_lambda_h2 + td_lambda_h3);\n      E += e_tri;\n      total_f += val_f;\n    }\n\n    // second part of the energy on vertices\n    Scalar Ex = 0;\n    for (int _v = 0; _v < m.n_ind_vertices(); _v++)\n      Ex += m.Th_hat[_v] * u(_v);\n\n    E = E + 0.5 * Ex;\n\n    return E;\n  }\n\n  /**\n   * Compute the gradient of conformal-equivalence-energy, which is equal to the per-vertex angle defects \n   * \n   * @param m Mesh data structure\n   * @param angles vector of Scalar with size equal to number of halfedges, produced by ComputeAngles function\n   * @param g vector of size equal to number of vertices, the gradient.\n   * @param solve_stats struct collecting info for solvings through out the algorithm\n   * @return void\n   */\n  static void Gradient(const Mesh<Scalar>& m, const VectorX& angles, VectorX& g, SolveStats<Scalar>& solve_stats)\n  {\n    solve_stats.n_g++;\n    g.setZero(m.n_ind_vertices());\n    auto angle_sums = Theta(m, angles);\n    for(int i = 0; i < g.rows(); i++)\n      g[i] = m.Th_hat[i] - angle_sums(i);\n  }\n\n  /**\n   * Compute the Hessian of conformal-equivalence-energy, which is the cotangent laplacian.\n   * \n   * @param m Mesh data structure\n   * @param cot_alpha vector of Scalar with size equal to number of halfedges, produced by ComputeAngles function\n   * @param H (output), Sparse Matrix with size #v*#v.\n   * @return void\n   */\n  static void Hessian(const Mesh<Scalar>& m, const VectorX& cot_alpha, Eigen::SparseMatrix<Scalar>& H)\n  {\n    H.resize(m.n_ind_vertices(), m.n_ind_vertices());\n    typedef Eigen::Triplet<Scalar> Trip;\n    std::vector<Trip> trips;\n    trips.clear();\n    trips.resize(m.n_halfedges() * 2);\n#pragma omp parallel for\n    for (int h = 0; h < m.n_halfedges(); h++)\n    {\n      int v0 = m.v_rep[m.v0(h)];\n      int v1 = m.v_rep[m.v1(h)];\n      Scalar w = (cot_alpha[h] + cot_alpha[m.opp[h]]) / 2;\n      trips[h * 2] = Trip(v0, v1, -w);\n      trips[h * 2 + 1] = Trip(v0, v0, w);\n    }\n\n    H.setFromTriplets(trips.begin(), trips.end());\n  }\n\n  /**\n   * Given original edge length and two scale factors defined on two endpoints, compute the rescaled edge lengths.\n   * \n   * @param l, Scalar, original edge length\n   * @param u0, Scalar, first scale factor \n   * @param u1, Scalar, second scale factor\n   * @param offset, Scalar,  a common factor to be subtracted from the total scale, added for numerical stability.\n   * @return Scalar rescaled edge length\n   */\n  static Scalar ell(Scalar l, Scalar u0, Scalar u1, Scalar offset = 0)\n  {\n    return l * exp((u0 + u1) / 2 - offset);\n  }\n\n  /**\n   * Predicate, checking whether the two neighboring triangles of given halfedge in the mesh \n   * with given scale factor satisfying delaunay condition after rescaling.\n   * \n   * @param m, mesh data structure\n   * @param u, #v vector, per-vertex scale factors\n   * @param e, int, halfedge id\n   * @param solve_stats struct collecting info for solvings through out the algorithm\n   * @return bool, true indicates delaunay condition is violated.\n   */\n  static bool NonDelaunay(Mesh<Scalar>& m, const VectorX& u, int e, SolveStats<Scalar>& solve_stats)\n  {\n    if (m.type[m.h0(e)] == 4)\n      return false; //virtual diagonal of symmetric trapezoid\n    solve_stats.n_checks++;\n    int hij = m.h0(e);\n    int hjk = m.n[hij];\n    int hki = m.n[hjk];\n    int hji = m.h1(e);\n    int him = m.n[hji];\n    int hmj = m.n[him];\n    int i = m.v_rep[m.to[hji]];\n    int j = m.v_rep[m.to[hij]];\n    int k = m.v_rep[m.to[hjk]];\n    int n = m.v_rep[m.to[him]];\n    Scalar ui = u[i];\n    Scalar uj = u[j];\n    Scalar uk = u[k];\n    Scalar um = u[n];\n    Scalar uijk_avg = (ui + uj + uk)/3.0;\n    Scalar ujim_avg = (uj + ui + um)/3.0;\n    Scalar ljk = ell(m.l[m.e(hjk)], uj, uk, uijk_avg);\n    Scalar lki = ell(m.l[m.e(hki)], uk, ui, uijk_avg);\n    Scalar lij = ell(m.l[m.e(hij)], ui, uj, uijk_avg);\n    Scalar lji = ell(m.l[m.e(hji)], uj, ui, ujim_avg);\n    Scalar lmj = ell(m.l[m.e(hmj)], um, uj, ujim_avg);\n    Scalar lim = ell(m.l[m.e(him)], ui, um, ujim_avg);\n    \n    bool pre_flip_check = (ljk / lki + lki / ljk - (lij / ljk) * (lij / lki)) + (lmj / lim + lim / lmj - (lji / lmj) * (lji / lim)) < 0;\n    \n    // additionally check whether delaunay is violated after flip\n    // we consider the configuration to 'violate delaunay condition' only if \n    // it does not satisfy delaunay check AND post-flip configuration satisfies delaunay condition.\n    Scalar umki_avg = (um + uk + ui)/3.0;\n    Scalar ukmj_avg = (uk + um + uj)/3.0;\n    Scalar _lkm_non_scaled = (m.l[m.e(hjk)] * m.l[m.e(him)] + m.l[m.e(hki)] * m.l[m.e(hmj)]) / m.l[m.e(hij)];\n    Scalar _lkm = ell(_lkm_non_scaled , uk, um, ukmj_avg);\n    Scalar _lmj = ell(m.l[m.e(hmj)], um, uj, ukmj_avg);\n    Scalar _ljk = ell(m.l[m.e(hjk)], uj, uk, ukmj_avg);\n    Scalar _lmk = ell(_lkm_non_scaled , um, uk, umki_avg);\n    Scalar _lki = ell(m.l[m.e(hki)] , uk, ui, umki_avg);\n    Scalar _lim = ell(m.l[m.e(him)] , ui, um, umki_avg);\n    bool post_flip_check = (_lki / _lim + _lim / _lki - (_lmk / _lki) * (_lmk / _lim)) + (_ljk / _lmj + _lmj / _ljk - (_lkm / _ljk) * (_lkm / _lmj)) < 0;\n    return pre_flip_check && !post_flip_check;\n  }\n\n  /**\n   * Flip the given halfedge in mesh and update the edge length accordingly.\n   * \n   * @param m, mesh data structure\n   * @param u, #v vector, per-vertex scale factors\n   * @param e, int, halfedge id\n   * @param delaunay_stats struct collecting info for delaunay flips through out the algorithm\n   * @param Ptolemy, bool, when true the edge length is updated via ptolemy formula, otherwise using law of cosine.\n   * @return bool, true indicates flip succeeds.\n   */\n  static bool EdgeFlip(Mesh<Scalar>& m, const VectorX& u, int e, int tag, DelaunayStats& delaunay_stats, bool Ptolemy = true)\n  {\n    Mesh<Scalar>& mc = m.cmesh();\n\n    int hij = mc.h0(e);\n    int hjk = mc.n[hij];\n    int hki = mc.n[hjk];\n    int hji = mc.h1(e);\n    int him = mc.n[hji];\n    int hmj = mc.n[him];\n\n    std::vector<char> &type = mc.type;\n\n    std::vector<int> to_flip;\n    if (type[hij] > 0) // skip in non-symmetric mode for efficiency\n    {\n      int types;\n      bool reverse = true;\n      if (type[hki] <= type[hmj])\n      {\n        types = type[hki] * 100000 + type[hjk] * 10000 + type[hij] * 1000 + type[hji] * 100 + type[him] * 10 + type[hmj];\n        reverse = false;\n      }\n      else\n        types = type[hmj] * 100000 + type[him] * 10000 + type[hji] * 1000 + type[hij] * 100 + type[hjk] * 10 + type[hki];\n\n      if (types == 231123 || types == 231132 || types == 321123)\n        return false; // t1t irrelevant\n      if (types == 132213 || types == 132231 || types == 312213)\n        return false; // t2t irrelevant\n      if (types == 341143)\n        return false; // q1q irrelevant\n      if (types == 342243)\n        return false; // q2q irrelevant\n\n      if (types == 111222 || types == 123312)\n        delaunay_stats.n_flips_s++;\n      if (types == 111123 || types == 111132)\n        delaunay_stats.n_flips_t++;\n      if (types == 213324 || types == 123314 || types == 111143 || types == 413324 || types == 23314)\n        delaunay_stats.n_flips_q++;\n      if (types == 111111)\n        delaunay_stats.n_flips_12++;\n      switch (types)\n      {\n      case 111222: // (1|2)\n        type[hij] = type[hji] = 3;\n        mc.R[hij] = hij;\n        mc.R[hji] = hji;\n        break;\n      case 123312: // (t,_,t)\n        type[hij] = type[hki];\n        type[hji] = type[hmj];\n        mc.R[hij] = hji;\n        mc.R[hji] = hij;\n        break;\n      case 111123: // (1,1,t)\n        type[hij] = type[hji] = 4;\n        mc.R[hij] = hij;\n        mc.R[hji] = hji;\n        break;\n      case 111132: // (1,1,t) mirrored\n        type[hij] = type[hji] = 4;\n        mc.R[hij] = hij;\n        mc.R[hji] = hji;\n        break;\n      case 222214: // (2,2,t) following (1,1,t) mirrored\n        type[hij] = type[hji] = 3;\n        to_flip.push_back(6); // to make sure all fake diagonals are top left to bottom right\n        mc.R[hij] = hij;\n        mc.R[hji] = hji;\n        break;\n      case 142222: // (2,2,t) following (1,1,t)\n        type[hij] = type[hji] = 3;\n        mc.R[hij] = hij;\n        mc.R[hji] = hji;\n        break;\n      case 213324: // (t,_,q)\n        type[hij] = type[hji] = 2;\n        to_flip.push_back(6);\n        break;\n      case 134412: // (t,_,q) 2nd\n        type[hij] = type[hji] = 1;\n        if (!reverse)\n        {\n          mc.R[hji] = hmj;\n          mc.R[hmj] = hji;\n          mc.R[mc.opp[hji]] = mc.opp[hmj];\n          mc.R[mc.opp[hmj]] = mc.opp[hji];\n        }\n        else\n        {\n          mc.R[hij] = hki;\n          mc.R[hki] = hij;\n          mc.R[mc.opp[hij]] = mc.opp[hki];\n          mc.R[mc.opp[hki]] = mc.opp[hij];\n        }\n        break;\n      case 123314: // (q,_,t)\n        type[hij] = type[hji] = 1;\n        to_flip.push_back(6);\n        break;\n      case 124432: // (q,_,t) 2nd\n        type[hij] = type[hji] = 2;\n        if (!reverse)\n        {\n          mc.R[hki] = hij;\n          mc.R[hij] = hki;\n          mc.R[mc.opp[hki]] = mc.opp[hij];\n          mc.R[mc.opp[hij]] = mc.opp[hki];\n        }\n        else\n        {\n          mc.R[hmj] = hji;\n          mc.R[hji] = hmj;\n          mc.R[mc.opp[hmj]] = mc.opp[hji];\n          mc.R[mc.opp[hji]] = mc.opp[hmj];\n        }\n        break;\n      case 111143: // (1,1,q)\n        type[hij] = type[hji] = 4;\n        mc.R[hij] = hij;\n        mc.R[hji] = hji;\n        break;\n      case 222243: // (2,2,q) following (1,1,q)\n        type[hij] = type[hji] = 4;\n        to_flip.push_back(5);\n        mc.R[hij] = hij;\n        mc.R[hji] = hji;\n        break;\n      case 144442: // (1,1,q)+(2,2,q) 3rd\n        type[hij] = type[hji] = 3;\n        mc.R[hij] = hij;\n        mc.R[hji] = hji;\n        break;\n      case 413324: // (q,_,q)\n        type[hij] = type[hji] = 4;\n        to_flip.push_back(6);\n        to_flip.push_back(1);\n        mc.R[hij] = hij;\n        mc.R[hji] = hji;\n        break;\n      case 423314: // (q,_,q) opp\n        type[hij] = type[hji] = 4;\n        to_flip.push_back(1);\n        to_flip.push_back(6);\n        mc.R[hij] = hij;\n        mc.R[hji] = hji;\n        break;\n      case 134414: // (q,_,q) 2nd\n        type[hij] = type[hji] = 1;\n        break;\n      case 234424: // (q,_,q) 3rd\n        type[hij] = type[hji] = 2;\n        if (!reverse)\n        {\n          mc.R[hji] = mc.n[mc.n[mc.opp[mc.n[mc.n[hji]]]]]; // attention: hji is not yet flipped here, hence twice .n[]\n          mc.R[mc.n[mc.n[mc.opp[mc.n[mc.n[hji]]]]]] = hji;\n          mc.R[mc.opp[hji]] = mc.opp[mc.R[hji]];\n          mc.R[mc.opp[mc.R[hji]]] = mc.opp[hji];\n        }\n        else\n        {\n          mc.R[hij] = mc.n[mc.n[mc.opp[mc.n[mc.n[hij]]]]];\n          mc.R[mc.n[mc.n[mc.opp[mc.n[mc.n[hij]]]]]] = hij;\n          mc.R[mc.opp[hij]] = mc.opp[mc.R[hij]];\n          mc.R[mc.opp[mc.R[hij]]] = mc.opp[hij];\n        }\n        break;\n      case 314423: // fake diag switch following (2,2,t) following (1,1,t) mirrored\n        break;\n      case 324413: // fake diag switch (opp) following (2,2,t) following (1,1,t) mirrored\n        break;\n      case 111111:\n        break;\n      case 222222:\n        break;\n      case 000000:\n        type[hij] = type[hji] = 0; // for non-symmetric mode\n        break;\n      default:\n        spdlog::error(\" (attempted to flip edge that should never be non-Delaunay (type{})).\", types);\n        return false;\n      }\n\n      if (reverse)\n      {\n        for (int i = 0; i < to_flip.size(); i++)\n          to_flip[i] = 7 - to_flip[i];\n      }\n    }\n\n    delaunay_stats.n_flips++;\n    if (Ptolemy)\n    {\n      delaunay_stats.flip_seq.push_back(hij);\n    }\n    else\n    {\n      delaunay_stats.flip_seq.push_back(-hij-1);\n    }\n    if (!m.flip_ccw(hij, Ptolemy))\n    {\n      spdlog::error(\" EDGE COULD NOT BE FLIPPED! \");\n    }\n    if (tag == 1)\n    {\n      m.flip_ccw(hij, Ptolemy);\n      m.flip_ccw(hij, Ptolemy);\n      if (Ptolemy)\n      {\n        delaunay_stats.flip_seq.push_back(hij);\n        delaunay_stats.flip_seq.push_back(hij);\n      }\n      else\n      {\n        delaunay_stats.flip_seq.push_back(-hij-1);\n        delaunay_stats.flip_seq.push_back(-hij-1);\n      }\n    } // to make it cw on side 2\n\n    for (int i = 0; i < to_flip.size(); i++)\n    {\n      if (to_flip[i] == 1)\n        EdgeFlip(m, u, mc.e(hki), 2, delaunay_stats, Ptolemy);\n      if (to_flip[i] == 2)\n        EdgeFlip(m, u, mc.e(hjk), 2, delaunay_stats, Ptolemy);\n      if (to_flip[i] == 5)\n        EdgeFlip(m, u, mc.e(him), 2, delaunay_stats, Ptolemy);\n      if (to_flip[i] == 6)\n        EdgeFlip(m, u, mc.e(hmj), 2, delaunay_stats, Ptolemy);\n    }\n\n    return true;\n  }\n  \n  /**\n   * Repeatedly perform edge flip operations until the rescaled triangles edges satisfying delaunay condition for all.\n   * \n   * @param m, mesh data structure\n   * @param u, #v vector, per-vertex scale factors\n   * @param delaunay_stats struct collecting info for delaunay flips through out the algorithm\n   * @param solve_stats struct collecting info for solvings through out the algorithm\n   * @param Ptolemy, bool, when true the edge length is updated via ptolemy formula, otherwise using law of cosine.\n   * @return void.\n   */\n  static void MakeDelaunay(Mesh<Scalar>& m, const VectorX& u, DelaunayStats& delaunay_stats, SolveStats<Scalar>& solve_stats, bool Ptolemy = true)\n  {\n    Mesh<Scalar>& mc = m.cmesh();\n    std::set<int> q;\n    for (int i = 0; i < mc.n_halfedges(); i++)\n    {\n      if (mc.opp[i] < i) // Only consider halfedges with lower index to prevent duplication\n        continue;\n      int type0 = mc.type[mc.h0(i)];\n      int type1 = mc.type[mc.h1(i)];\n      if (type0 == 0 || type0 == 1 || type1 == 1 || type0 == 3) //type 22 edges are flipped below; type 44 edges (virtual diagonals) are never flipped.\n        q.insert(i);\n    }\n    while (!q.empty())\n    {\n      int e = *(q.begin());\n      q.erase(q.begin());\n      int type0 = mc.type[mc.h0(e)];\n      int type1 = mc.type[mc.h1(e)];\n      if (!(type0 == 2 && type1 == 2) && !(type0 == 4) && NonDelaunay(mc, u, e, solve_stats))\n      {\n        int Re = -1;\n        if (type0 == 1 && type1 == 1)\n          Re = mc.e(mc.R[mc.h0(e)]);\n        if (!EdgeFlip(m, u, e, 0, delaunay_stats, Ptolemy))\n          continue;\n        int hn = mc.n[mc.h0(e)];\n        q.insert(mc.e(hn));\n        q.insert(mc.e(mc.n[hn]));\n        hn = mc.n[mc.h1(e)];\n        q.insert(mc.e(hn));\n        q.insert(mc.e(mc.n[hn]));\n        if (type0 == 1 && type1 == 1) // flip mirror edge on sheet 2\n        {\n          int e = Re;\n          if (Re == -1)\n            spdlog::info(\"Negative index\");\n          if (!EdgeFlip(m, u, e, 1, delaunay_stats, Ptolemy))\n            continue;\n          int hn = mc.n[mc.h0(e)];\n          q.insert(mc.e(hn));\n          q.insert(mc.e(mc.n[hn]));\n          hn = mc.n[mc.h1(e)];\n          q.insert(mc.e(hn));\n          q.insert(mc.e(mc.n[hn]));\n        }\n        // checkR();\n      }\n    }\n  }\n\n  static VectorX DescentDirection(const Eigen::SparseMatrix<Scalar>& hessian, const VectorX& grad, int fixed_dof, SolveStats<Scalar>& solve_stats)\n  {\n\n    static Scalar a = 0.0; // Parameter for interpolating from the Newton direction to steepest descent\n\n    auto grad_dof_fixed = grad;\n    auto hessian_dof_fixed = hessian;\n\n    // Set fixed degree of freedom in the gradient and hessian\n    grad_dof_fixed[fixed_dof] = 0;\n    for (int k = 0; k < hessian_dof_fixed.outerSize(); ++k)\n    {\n      for (typename Eigen::SparseMatrix<Scalar>::InnerIterator it(hessian_dof_fixed, k); it; ++it)\n      {\n        if ((it.row() == fixed_dof) || (it.col() == fixed_dof))\n        {\n          it.valueRef() = 0;\n        }\n      }\n    }\n    hessian_dof_fixed.coeffRef(fixed_dof,fixed_dof) = 1;\n \n    // Compute corrected descent direction\n    while (true)\n    {\n      Eigen::SparseMatrix<Scalar> mat;\n      if (a == 0)\n      {\n        mat = hessian_dof_fixed; // Use newton step\n      }\n      else \n      {     \n        // Create identity\n        typedef Eigen::Triplet<Scalar> T;\n        std::vector<T> tripletList;\n        tripletList.reserve(grad.rows());\n        for(int i = 0; i < grad.rows(); ++i)\n        {\n          tripletList.push_back(T(i,i,1));\n        }\n        Eigen::SparseMatrix<Scalar> id(grad.rows(), grad.rows());\n        id.setFromTriplets(tripletList.begin(), tripletList.end());\n        \n        // Create matrix with correction\n        mat = hessian_dof_fixed + a*id;\n      }\n\n      Eigen::SimplicialLDLT<Eigen::SparseMatrix<Scalar>> solver;\n      solver.compute(mat);\n      VectorX d = -solver.solve(grad_dof_fixed);\n      Scalar newton_decr = d.dot(grad_dof_fixed);\n      if (solver.info() == Eigen::Success && newton_decr < 0)\n      {\n        a *= 0.5; // start from lower a on the next step\n        solve_stats.n_solves++;\n        return d;\n      }\n      else if (a == 0)\n      {\n        a = 1; // We did not try the correction yet, start from arbitrary value 1\n        spdlog::info(\" Starting correction.\");\n      }\n      else\n      {\n        a *= 2; // Correction was not enough, increase weight of id\n      }\n    }\n  }\n\n  /**\n   * Backtracking line search function, checking the sign of projected gradient.\n   * @param m, mesh data structure\n   * @param u0, #v vector, per-vertex scale factors\n   * @param d0, #v vector, descent direction\n   * @param lambda, initial step size, will be updated when exit line-search\n   * @param currentg, gradient computed before start doing line-search, will be updated when exit line-search\n   * @param bound_norm, when true: require gradient norm to decrease at each iteration\n   * @param delaunay_stats struct collecting info for delaunay flips through out the algorithm\n   * @param solve_stats struct collecting info for solvings through out the algorithm\n   * @param alg_params, algorithm parameters, for details check the struct definitions on the top\n   * @param ls_params, line search parameters, for details check the struct definitions on the top\n   * @param stats_params, statistics parameters, for details check the struct definitions on the top\n   * @return VectorX, updated per-vertex scale factor along descent direction.\n   */\n  static VectorX LineSearchNewtonDecr(Mesh<Scalar>& m, const VectorX& u0, const VectorX& d0, Scalar& lambda, VectorX& currentg, bool& bound_norm, DelaunayStats& delaunay_stats, SolveStats<Scalar>& solve_stats, const AlgorithmParameters& alg_params, const LineSearchParameters& ls_params, const StatsParameters& stats_params){\n    \n    Mesh<Scalar> &mc = m.cmesh();\n    auto d = d0;\n    auto u = u0;\n    auto newton_decr = d.dot(currentg);\n\n    // Scale the search direction vector by lambda\n    d *= lambda;  \n\n    // To avoid nans/infs\n    if(ls_params.do_reduction){\n      while(d.maxCoeff() - d.minCoeff() > 10)\n      {\n        d /= 2;\n        lambda /=2;\n      }\n    }\n\n    Scalar init_e = 0.0; VectorX init_g = currentg;\n    Scalar l2_g0_sq = currentg.dot(currentg);\n    VectorX alpha, cot_alpha;\n\n    // Line search\n    u += d;\n    MakeDelaunay(m, u, delaunay_stats, solve_stats);\n    ComputeAngles(mc, u, alpha, cot_alpha);\n\n    int count = 0;\n    Gradient(mc, alpha, currentg, solve_stats); // Current gradient value\n    Scalar l2_g_sq = currentg.dot(currentg); // Squared norm of the gradient\n    Scalar proj_grad = d.dot(currentg);  // Projected gradient\n    while ((proj_grad > 0) || (l2_g_sq > l2_g0_sq && bound_norm))\n    {\n      // Backtrack one step\n      d /= 2;\n      lambda /= 2; // record changes in lambda as well\n      u -= d;\n      MakeDelaunay(m, u, delaunay_stats, solve_stats);\n      ComputeAngles(mc, u, alpha, cot_alpha);\n      Gradient(mc, alpha, currentg, solve_stats); // update gradient\n\n      // Line search condition to ensure quadratic convergence\n      if (   (count == 0)\n          && ((l2_g_sq <= l2_g0_sq) || (!bound_norm))\n          && (0.5 * (d.dot(currentg) + proj_grad) <= 0.1 * newton_decr))\n      {\n        u += d; // Use full line step\n        lambda *= 2;\n        MakeDelaunay(m, u, delaunay_stats, solve_stats);\n        ComputeAngles(mc, u, alpha, cot_alpha);\n        Gradient(mc, alpha, currentg, solve_stats); // update gradient\n        break;\n      }\n\n      // Update squared gradient norm and projected gradient\n      l2_g_sq = currentg.dot(currentg);\n      proj_grad = d.dot(currentg);\n\n      count++;\n\n      // Check if gradient norm is below the threshold to drop the bound\n      if ((bound_norm) && (lambda <= ls_params.bound_norm_thres))\n      {\n        bound_norm = false;\n        spdlog::debug(\"Dropping norm bound.\");\n      }\n\n      // Check if lambda is below the termination threshold\n      if (lambda < alg_params.min_lambda) \n        break;\n    }\n    spdlog::debug(\"Used lambda {} \", lambda);\n    return u;\n  }\n\n  /**\n   * Backtracking line search function checking the conformal-equivalence-energy and with armijo condition\n   * @param m, mesh data structure\n   * @param u0, #v vector, per-vertex scale factors\n   * @param d0, #v vector, descent direction\n   * @param lambda, initial step size, will be updated when exit line-search\n   * @param currentg, gradient computed before start doing line-search, will be updated when exit line-search\n   * @param bound_norm, when true: require gradient norm to decrease at each iteration\n   * @param delaunay_stats struct collecting info for delaunay flips through out the algorithm\n   * @param solve_stats struct collecting info for solvings through out the algorithm\n   * @param alg_params, algorithm parameters, for details check the struct definitions on the top\n   * @param ls_params, line search parameters, for details check the struct definitions on the top\n   * @param stats_params, statistics parameters, for details check the struct definitions on the top\n   * @return VectorX, updated per-vertex scale factor along descent direction.\n   */\n  static VectorX LineSearchCETMEnergy(Mesh<Scalar>& m, const VectorX& u0, const VectorX& d0, Scalar& lambda, VectorX& currentg, bool& bound_norm, DelaunayStats& delaunay_stats, SolveStats<Scalar>& solve_stats, const AlgorithmParameters& alg_params, const LineSearchParameters& ls_params, const StatsParameters& stats_params){\n    \n    Mesh<Scalar> &mc = m.cmesh();\n    auto d = d0;\n    auto u = u0;\n    auto newton_decr = d.dot(currentg);\n\n    // Scale the search direction vector by lambda\n    d *= lambda;  \n\n    // To avoid nans/infs\n    if(ls_params.do_reduction){\n      while(d.maxCoeff() - d.minCoeff() > 10)\n      {\n        d /= 2;\n        lambda /=2;\n      }\n    }\n\n    Scalar init_e = 0.0; VectorX init_g = currentg;\n    Scalar l2_g0_sq = currentg.dot(currentg);\n    VectorX alpha, cot_alpha;\n    ComputeAngles(mc, u, alpha, cot_alpha);\n    \n    if(ls_params.energy_samples){\n      DelaunayStats d_stats_placeholder;\n      SolveStats<Scalar> s_stats_placeholder;\n      SampleEnergyAlongDirection(mc, u, stats_params.output_dir+\"/\"+\"energy_sample.csv\", d, 2.0, 200, d_stats_placeholder, s_stats_placeholder, true);\n      SampleNewtonDecrement(mc, u, stats_params.output_dir+\"/\"+\"newton_decrement.csv\", d, 0.0, 2.0, 200, d_stats_placeholder, s_stats_placeholder);\n    }\n    \n    // init energy before line search start\n    init_e = ConformalEquivalenceEnergy(mc, alpha, u);\n\n    // Line search\n    u += d;\n    MakeDelaunay(m, u, delaunay_stats, solve_stats);\n    ComputeAngles(mc, u, alpha, cot_alpha);\n\n    Gradient(mc, alpha, currentg, solve_stats); // Current gradient value\n    Scalar new_e = ConformalEquivalenceEnergy(mc, alpha, u);\n    bool armijo_cond = false, curvature_cond = false;\n    do{\n      \n      armijo_cond = new_e <= (init_e + ls_params.c1 * lambda * init_g.dot(d));\n      curvature_cond = currentg.dot(d) >= ls_params.c2 * init_g.dot(d);\n      \n      if((bound_norm) && (lambda <= ls_params.bound_norm_thres))\n      {\n        bound_norm = false;\n        spdlog::debug(\"Dropping norm bound.\");\n      }\n      if (lambda < alg_params.min_lambda)\n        break;\n\n      if(new_e < init_e && armijo_cond && curvature_cond)\n        break;\n      \n      d /= 2;\n      lambda /= 2; // record backtrack changes in lambda\n      u -= d; // Backtrack\n      MakeDelaunay(m, u, delaunay_stats, solve_stats);\n      ComputeAngles(mc, u, alpha, cot_alpha);\n      Gradient(mc, alpha, currentg, solve_stats);\n      new_e = ConformalEquivalenceEnergy(mc, alpha, u);\n\n    }while(true);\n\n    solve_stats.cetm_energy = new_e;\n\n    spdlog::debug(\"Used lambda {} \", lambda);\n    return u;\n  }\n\n  /**\n   * The top-level conformal-hyperblic-delaunay algorithm\n   * \n   * @param m Mesh data structure\n   * @param u0 vector of Scalar size equal to number of vertices of mesh, the initial values of per-vertex logarithmic scale factors\n   * @param pt_fids list of face ids per sample point on the original mesh surface, will be updated through out the whole algorithm\n   * @param pt_bcs list of barycentric coordinates of each sample point in the correspoinding face, will be updated through out the whole algorithm\n   * @param alg_params, algorithm parameters, for details check the struct definitions on the top\n   * @param ls_params, line search parameters, for details check the struct definitions on the top\n   * @param stats_params, statistics parameters, for details check the struct definitions on the top\n   * @return flip sequence\n   */\n  static std::tuple<VectorX, std::vector<int>> FindConformalMetric(OverlayMesh<Scalar>& m, const VectorX& u0, std::vector<int>& pt_fids, std::vector<Eigen::Matrix<Scalar, 3, 1>>& pt_bcs, const AlgorithmParameters& alg_params, const LineSearchParameters& ls_params, const StatsParameters& stats_params)\n  {\n    switch (stats_params.log_level){\n      case 0: spdlog::set_level(spdlog::level::trace);    break;\n      case 1: spdlog::set_level(spdlog::level::debug);    break;\n      case 2: spdlog::set_level(spdlog::level::info);     break;\n      case 3: spdlog::set_level(spdlog::level::warn);     break;\n      case 4: spdlog::set_level(spdlog::level::err);      break;\n      case 5: spdlog::set_level(spdlog::level::critical); break;\n      default:\n      case 6: spdlog::set_level(spdlog::level::off);      break;\n    }\n    m.bypass_overlay = alg_params.bypass_overlay;\n    Mesh<Scalar>& mc = m.cmesh(); \n    mc.init_pts(pt_fids, pt_bcs);\n\n    DelaunayStats delaunay_stats;\n    SolveStats<Scalar> solve_stats;\n\n    std::clock_t start;\n    start = std::clock();\n\n    // Initialize u to the zero vector\n    VectorX u = u0;\n    VectorX cot_alpha(mc.n_halfedges());\n    VectorX alpha(mc.n_halfedges());\n\n    // Degree of freedom to eliminate to make the Hessian positive definite\n    // Choose first vertex arbitrarily for the fixed_dof for regular meshes\n    int fixed_dof = 0;\n    if (mc.R[0] == 0)\n    {\n      fixed_dof = 0;\n    }\n    // Set the fixed_dof to the first boundary halfedge for symmetric meshes\n    else\n    {\n      for (int i = 0; i < mc.n_vertices(); ++i)\n      {\n        if (mc.v_rep[mc.to[mc.R[mc.out[i]]]] == mc.v_rep[i])\n        {\n          fixed_dof = mc.v_rep[i];\n          break;\n        }\n      }\n    }\n\n    bool bound_norm = (ls_params.lambda0 > ls_params.bound_norm_thres); // prevents the grad norm from increasing\n    if(bound_norm) spdlog::debug(\"Using norm bound.\");\n    \n    double max_curr = 0.0;\n    Scalar pi;\n#ifdef WITH_MPFR\n    if (std::is_same<Scalar, mpfr::mpreal>::value)\n        pi = Scalar(mpfr::const_pi());\n    else\n        pi = Scalar(M_PI);\n#else\n    pi = Scalar(M_PI);\n#endif\n    if (stats_params.flip_count){\n      // need to also collect max boundary curvature error\n      for(int i = 0; i < mc.R.size(); i++){\n        if(mc.R[i] == mc.opp[i]){\n          int v0 = mc.v_rep[mc.to[i]];\n          if(max_curr < std::abs(double(mc.Th_hat[v0])/2-M_PI))\n            max_curr = std::abs(double(mc.Th_hat[v0])/2-M_PI);\n        }\n      }\n    }\n\n    Scalar lambda = ls_params.lambda0;\n\n    // Optionally use Euclidean flips instead of Ptolemy flips for the initial MakeDelaunay\n    if (!alg_params.initial_ptolemy){\n      MakeDelaunay(m, u, delaunay_stats, solve_stats, false);\n      spdlog::debug(\"Finish first delaunay non_ptolemy\");\n      m.garbage_collection();\n      m.bc_original_to_eq(mc.n, mc.to, mc.l);\n    }\n\n    // step1 apply per triangle the bc map to unit equilateral triangle\n    original_to_equilateral(mc.pts, mc.pt_in_f, mc.n, mc.h, mc.l);\n    if (alg_params.initial_ptolemy) {\n      MakeDelaunay(m, u, delaunay_stats, solve_stats, true);\n      spdlog::debug(\"Finish first delaunay ptolemy\");\n    } \n    ComputeAngles(mc, u, alpha, cot_alpha);\n    std::ofstream mf;\n    if(stats_params.error_log){\n      mf.open(stats_params.output_dir+\"/\"+stats_params.name+\".csv\",std::ios_base::out);\n      mf << \"itr, max error, min_u, max_u, lambda, newton_dec, do_reduction, cetm_e\\n\";\n    }\n\n    VectorX currentg;\n    Gradient(mc, alpha, currentg, solve_stats);\n    while (currentg.cwiseAbs().maxCoeff() >= alg_params.error_eps)\n    {\n      // Compute gradient and descent direction from Hessian (with efficient solver)\n      Eigen::SparseMatrix<Scalar> hessian;\n      Hessian(mc, cot_alpha, hessian);\n      VectorX d = DescentDirection(hessian, currentg, fixed_dof, solve_stats);\n\n      // Terminate if newton decrement sufficiently smalll      \n      Scalar newton_decr = d.dot(currentg);\n\n      if(stats_params.error_log){\n        solve_stats.cetm_energy = ConformalEquivalenceEnergy(mc, alpha, u);\n        mf << solve_stats.n_solves << \",\" << std::setprecision(17) << currentg.cwiseAbs().maxCoeff() << \",\" <<u.minCoeff() << \",\" << u.maxCoeff() << \",\" << lambda << \",\" << newton_decr << \",\" << ls_params.do_reduction <<\" , \"<<solve_stats.cetm_energy<< std::endl;\n      }\n      // Alternative termination conditons to error threshold\n      if (lambda < alg_params.min_lambda)\n        break;\n      if (solve_stats.n_solves >= alg_params.max_itr)\n        break;\n      if (newton_decr > alg_params.newton_decr_thres)\n        break;\n      \n      // Determine initial lambda for line search based on method parameters\n      if (ls_params.energy_cond || ls_params.reset_lambda)\n      {\n        lambda = ls_params.lambda0; \n      }\n      else\n      {\n        lambda = std::min<Scalar>(1, 2 * lambda); // adaptive step length\n      }\n      \n      // reset lambda when it goes above norm bound threshold\n      if ((lambda > ls_params.bound_norm_thres) && (!bound_norm))\n      {\n        bound_norm = true;\n        lambda = ls_params.lambda0;\n        spdlog::debug(\"Using norm bound.\");\n      }\n      if(ls_params.energy_cond)\n        u = LineSearchCETMEnergy(m, u, d, lambda, currentg, bound_norm, delaunay_stats, solve_stats, alg_params, ls_params, stats_params);\n      else\n        u = LineSearchNewtonDecr(m, u, d, lambda, currentg, bound_norm, delaunay_stats, solve_stats, alg_params, ls_params, stats_params);\n\n      // Display current iteration information\n      if(ls_params.energy_cond)\n        spdlog::info(\"itr({}) lm({}) flips({}) newton_decr({}) max_error({}), cetm_e({}))\", solve_stats.n_solves, lambda, delaunay_stats.n_flips, newton_decr, currentg.cwiseAbs().maxCoeff(), solve_stats.cetm_energy);\n      else\n        spdlog::info(\"itr({}) lm({}) flips({}) newton_decr({}) max_error({}))\", solve_stats.n_solves, lambda, delaunay_stats.n_flips, newton_decr, currentg.cwiseAbs().maxCoeff());\n\n      ComputeAngles(mc, u, alpha, cot_alpha);\n\n    }\n\n    // Output flip stats\n    if(stats_params.error_log) mf.close();\n    auto total_time = ( std::clock() - start ) / (double) CLOCKS_PER_SEC;\n    if(stats_params.flip_count){\n      auto fname = stats_params.output_dir+\"/flips_stats.csv\";\n      auto header = \"name, flips12, flipsq, flipss,flipst, n_flips, fac, time\";\n      std::stringstream ss;\n      ss << stats_params.name << \", \" << delaunay_stats.n_flips_12 << \", \" << delaunay_stats.n_flips_q << \", \" << delaunay_stats.n_flips_s << \", \" << delaunay_stats.n_flips_t << \", \" << delaunay_stats.n_flips  << \", \" << max_curr/pi <<\", \"<< total_time;\n      std::vector<std::string> content = {ss.str()};\n      WriteLog(fname, content, header, true);\n    }\n\n    if(stats_params.print_summary){\n      auto fname = stats_params.output_dir+\"/summary_delaunay.csv\";\n      auto header = \"name, n_flips, max_error, time\";\n      VectorX currentg;\n      Gradient(mc, alpha, currentg, solve_stats);\n      std::stringstream ss;\n      ss << stats_params.name << \", \" <<delaunay_stats.n_flips << \",\" << currentg.cwiseAbs().maxCoeff()  << \", \" << total_time;\n      std::vector<std::string> content = {ss.str()};\n      WriteLog(fname, content, header, true);\n    }\n\n    // map barycentric coordinates from equilateral to scaled triangle\n    equilateral_to_scaled(mc.pts, mc.pt_in_f, mc.n, mc.h, mc.to, mc.l, u);\n\n    int cnt = 0;\n    for (auto pt : mc.pts)\n    {\n      pt_fids[cnt] = pt.f_id;\n      pt_bcs[cnt] = pt.bc;\n      cnt++;\n    }\n\n    return std::make_tuple(u, delaunay_stats.flip_seq);\n\n  }\n\n   /**\n   * Get the Reverse Map of the FindConformalMetric using the Halfedge-Flip Sequence\n   * @param m_o OverlayMesh computed from FindConformalMetric\n   * @param flip_seq Flip_ccw Sequence used in FindConformalMetric\n   * @return Reverse Overlaymesh m_o_rev and vertices-id map between m_o_rev and m_o\n   */\n  static std::tuple<OverlayMesh<Scalar>, std::vector<int>> GetReverseMap(OverlayMesh<Scalar> & m_o, const std::vector<int> &flip_seq)\n  {\n    auto mc = m_o.cmesh();\n    OverlayMesh<Scalar> m_o_rev(mc);\n    bool do_Ptolemy = true;\n    // do reverse flips\n    for (int ii = flip_seq.size() - 1; ii >= 0; ii--)\n    {\n      if (do_Ptolemy && flip_seq[ii] < 0)\n      {\n        do_Ptolemy = false;\n        m_o_rev.garbage_collection();\n        Eigen::Matrix<Scalar, -1, 1> u_0(m_o_rev.cmesh().out.size());\n        u_0.setZero();\n        m_o_rev.bc_eq_to_scaled(m_o_rev.cmesh().n, m_o_rev.cmesh().to, m_o_rev.cmesh().l,u_0);\n      }\n      if (do_Ptolemy)\n      {\n        m_o_rev.flip_ccw(flip_seq[ii], true);\n        m_o_rev.flip_ccw(flip_seq[ii], true);\n        m_o_rev.flip_ccw(flip_seq[ii], true);\n      }\n      else\n      {\n        m_o_rev.flip_ccw(-flip_seq[ii]-1, false);\n        m_o_rev.flip_ccw(-flip_seq[ii]-1, false);\n        m_o_rev.flip_ccw(-flip_seq[ii]-1, false);\n      }\n      \n    }\n    if(m_o_rev.bypass_overlay){\n      m_o.bypass_overlay = true;\n      return std::make_tuple(m_o_rev, std::vector<int>());\n    }\n    m_o.garbage_collection();\n    m_o_rev.garbage_collection();\n\n    if (do_Ptolemy == false)\n    {\n      m_o_rev.bc_original_to_eq(m_o_rev.cmesh().n, m_o_rev.cmesh().to, m_o_rev.cmesh().l);\n    }\n    spdlog::debug(\"#m_o.out: {}, #m_o_rev.out: {}\", m_o.out.size(), m_o_rev.out.size());\n    spdlog::debug(\"#m_o.n: {}, #m_o_rev.n: {}\", m_o.n.size(), m_o_rev.n.size());\n\n    // get the v_map\n    std::vector<int> v_map(m_o.out.size());\n    // init the original vertices part with Id\n    for (int i = 0; i < mc.out.size(); i++)\n    {\n      v_map[i] = i;\n    }\n    // init the segment vertices part with -1\n    for (int i = mc.out.size(); i < v_map.size(); i++)\n    {\n      v_map[i] = -1;\n    }\n\n    for (int v_start = 0; v_start < mc.out.size(); v_start++)\n    {\n      int h_out0 = m_o.out[v_start];\n      int h_out0_copy = h_out0;\n      int v_end = m_o.find_end_origin(h_out0);\n\n      int h_out0_rev = m_o_rev.out[v_start];\n      bool flag = false;\n      int while_cnt = 0;\n      int caseid = 0;\n\n      while (true)\n      {\n        if (m_o_rev.find_end_origin(h_out0_rev) == v_end && m_o.dist_to_next_origin(h_out0) == m_o_rev.dist_to_next_origin(h_out0_rev))\n        {\n          // test first segment vertex\n          // case 1, no segment vertex\n          if (m_o_rev.to[h_out0_rev] == v_end)\n          {\n            caseid = 0;\n            if (m_o.next_out(h_out0) != h_out0_copy)\n            {\n              h_out0 = m_o.next_out(h_out0);\n              v_end = m_o.find_end_origin(h_out0);\n            }\n            else\n            {\n              flag = true;\n            }\n\n          }\n          else\n          {\n            int h_first = m_o.n[h_out0];\n            int h_first_rev = m_o_rev.n[h_out0_rev];\n\n            if (m_o.find_end_origin(h_first) == m_o_rev.find_end_origin(h_first_rev) && m_o.find_end_origin(m_o.opp[h_first]) == m_o_rev.find_end_origin(m_o_rev.opp[h_first_rev]) && m_o.dist_to_next_origin(h_first) == m_o_rev.dist_to_next_origin(h_first_rev))\n            {\n              caseid = 1;\n              flag = true;\n            }\n          }\n        }\n        \n        if (flag) break;\n\n        h_out0_rev = m_o_rev.next_out(h_out0_rev);\n        while_cnt++;\n\n        if (while_cnt > 99999)\n        {\n          spdlog::error(\"infi loop in finding first match\");\n          break;\n        }\n      }\n\n      int h_out = h_out0;\n      int h_out_rev = h_out0_rev;\n\n      do\n      {\n        int h_current = h_out;\n        int h_current_rev = h_out_rev;\n        \n        while (m_o.vertex_type[m_o.to[h_current]] != ORIGINAL_VERTEX)\n        {\n          \n          if (m_o_rev.vertex_type[m_o_rev.to[h_current_rev]] == ORIGINAL_VERTEX)\n          {\n            spdlog::error(\"out path not matching, case: {}\", caseid);\n            break;  \n          }\n          int v_current = m_o.to[h_current];\n          int v_current_rev = m_o_rev.to[h_current_rev];\n          if (v_map[v_current] == -1)\n          {\n            v_map[v_current] = v_current_rev;\n          }\n          else if (v_map[v_current] != v_current_rev)\n          {\n            spdlog::error(\"the mapping is wrong, case: {}\", caseid);\n          }\n          h_current = m_o.n[m_o.opp[m_o.n[h_current]]];\n          h_current_rev = m_o_rev.n[m_o_rev.opp[m_o_rev.n[h_current_rev]]];\n        }\n        h_out = m_o.next_out(h_out);\n        h_out_rev = m_o_rev.next_out(h_out_rev);\n      } while (h_out != h_out0);\n      \n    }\n    \n    return std::make_tuple(m_o_rev, v_map);\n  }\n\n  /**\n   * Interpolate 3d coordinates to get the OverlayMesh in 3d\n   * @param m_o OverlayMesh computed from FindConformalMetric\n   * @param flip_seq Flip_ccw Sequence used in FindConformalMetric\n   * @param x 3d coordinat of the Original Mesh\n   * @return interpolated OverlayMesh Coordinates\n   */\n  static std::vector<std::vector<Scalar>> Interpolate_3d(OverlayMesh<Scalar> & m_o, const std::vector<int> &flip_seq, const std::vector<std::vector<Scalar>> &x, bool uniform = false)\n  {\n    std::vector<std::vector<Scalar>> z(3);\n\n    if (uniform)\n    {\n      for (int j = 0; j < 3; j++)\n      {\n        z[j] = m_o.interpolate_along_o(x[j]);\n      }\n      return z;\n    }\n    auto rev_map = GetReverseMap(m_o, flip_seq);\n    if(m_o.bypass_overlay) return std::vector<std::vector<Scalar>>();\n    auto m_o_rev = std::get<0>(rev_map);\n    auto v_map = std::get<1>(rev_map);\n\n    Eigen::Matrix<Scalar, -1, 1> u_0(m_o_rev.cmesh().out.size());\n    u_0.setZero();\n\n    m_o_rev.bc_eq_to_scaled(m_o_rev.cmesh().n, m_o_rev.cmesh().to, m_o_rev.cmesh().l, u_0);\n\n    std::vector<std::vector<Scalar>> z_rev(3);\n    for (int j = 0; j < 3; j++)\n    {\n      z_rev[j] = m_o_rev.interpolate_along_o_bc(m_o_rev.cmesh().opp, m_o_rev.cmesh().to, x[j]);\n    }\n\n    for (int j = 0; j < 3; j++)\n    {\n      z[j].resize(z_rev[j].size());\n      for (int i = 0; i < z[j].size(); i++)\n      {\n        z[j][i] = z_rev[j][v_map[i]];\n      }\n    }\n    \n    return z;\n  }\n\n  /**\n   * Start at any configuration that all scaled elements in mesh satisfies delaunay condition, evenly evaluate newton-decrement along \n   * certain direction for a number of samples the series of sampled values will be written to file `fname`.\n   * \n   * @param m0 Mesh data structure\n   * @param u0 vector of Scalar size equal to number of vertices of mesh, the initial values of per-vertex logarithmic scale factors\n   * @param d0 vector of Scalar size eqaul to number of vertices of mesh, a delta vector on u0\n   * @param lambda_max Scalar controlling the maximum step size along the direction d0\n   * @param n_samples Total number of evenly distributed sample points along d0\n   * @param delaunay_stats struct collecting stats for delaunay flips through out the algorithm\n   * @param solve_stats struct collecting info for solvings through out the algorithm\n   * @param rescale Scale (and record) the lambda values by |d0| and the newton decr by 1/|d0|\n   * @return void\n   */\n  static void SampleNewtonDecrement(const Mesh<Scalar>& m0, const VectorX& u0, std::string fname, const VectorX &d, Scalar lambda_min, Scalar lambda_max, int n_sample, DelaunayStats& delaunay_stats, SolveStats<Scalar>& solve_stats, bool rescale=false){\n    \n    if (n_sample == 0)\n      return;\n\n    std::vector<std::string> newton_dec;\n    Scalar step_size = (lambda_max - lambda_min) / n_sample;\n    VectorX alpha, cot_alpha;\n    auto m = m0;\n    auto u = u0;\n\n    spdlog::info(\"n_sample = {}\", n_sample);\n\n    for (int i = 0; i < n_sample; i++)\n    {\n      m = m0;\n      u = u0 + (lambda_min + i * step_size) * d;\n      MakeDelaunay(m, u, delaunay_stats, solve_stats);\n      ComputeAngles(m, u, alpha, cot_alpha);\n      VectorX g;\n      Gradient(m, alpha, g, solve_stats);\n      std::stringstream ss;\n      if (rescale)\n      {\n          ss << std::setprecision(17) << sqrt(d.dot(d))*(lambda_min + i * step_size)\n             << \",\" << d.dot(g)/sqrt(d.dot(d));\n      }\n      else\n      {\n          ss << std::to_string(i) << \",\" <<std::setprecision(17) << d.dot(g);\n      }\n      newton_dec.push_back(ss.str());\n    }\n\n    WriteLog(fname, newton_dec, \"itr, newton_decrement\");\n\n  }\n  /**\n   * @brief Overloaded version of sampleNewtonDecrement function above. Used for python binding. Unlike the above method, this method always computes and uses the Newton descent direction.\n   * @param m0 Mesh data structure\n   * @param u0 vector of Scalar size equal to number of vertices of mesh, the initial values of per-vertex logarithmic scale factors\n   * @param lambda_min Scalar controlling the minimum step size along the direction d0\n   * @param lambda_max Scalar controlling the maximum step size along the direction d0\n   * @param n_samples Total number of evenly distributed sample points along d0\n   * @return void\n   */\n  static void SampleNewtonDecrementStl(Mesh<Scalar>& m0,\n                                       std::vector<Scalar>& u0_vec,\n                                       std::string fname,\n                                       Scalar lambda_min,\n                                       Scalar lambda_max,\n                                       int n_sample) {\n    VectorX u0(u0_vec.size()); \n    for(int i = 0; i < u0_vec.size(); i++)\n      u0(i) = u0_vec[i];\n\n    // Create placeholder stat structures\n    DelaunayStats d_stats_placeholder;\n    SolveStats<Scalar> s_stats_placeholder;\n\n    // Degree of freedom to eliminate to make the Hessian positive definite\n    // Choose first vertex arbitrarily for the fixed_dof for regular meshes\n    int fixed_dof = 0;\n    if (m0.R[0] == 0)\n    {\n      fixed_dof = 0;\n    }\n    // Set the fixed_dof to the first boundary halfedge for symmetric meshes\n    else\n    {\n      for (int i = 0; i < m0.n_vertices(); ++i)\n      {\n        if (m0.to[m0.R[m0.out[i]]] == i)\n        {\n          fixed_dof = i;\n          break;\n        }\n      }\n    }\n\n    // Compute angles and cotangents of angles\n    VectorX cot_alpha(m0.n_halfedges());\n    VectorX alpha(m0.n_halfedges());\n    MakeDelaunay(m0, u0, d_stats_placeholder, s_stats_placeholder, true);\n    ComputeAngles(m0, u0, alpha, cot_alpha);\n\n    // Compute descent direction from gradient and hessian\n    VectorX currentg;\n    Gradient(m0, alpha, currentg, s_stats_placeholder);\n    Eigen::SparseMatrix<Scalar> hessian;\n    Hessian(m0, cot_alpha, hessian);\n    VectorX d = DescentDirection(hessian, currentg, fixed_dof, s_stats_placeholder);\n\n    // Sample newton decrement\n    SampleNewtonDecrement(m0,\n                          u0,\n                          fname,\n                          d,\n                          lambda_min,\n                          lambda_max,\n                          n_sample,\n                          d_stats_placeholder,\n                          s_stats_placeholder,\n                          true);\n  }\n\n  /**\n   * Start at any configuration that all scaled elements in mesh satisfies delaunay condition, evenly evaluate conformal-equivalence-energy along \n   * certain direction for a number of samples the series of sampled values will be written to file `fname`.\n   * \n   * @param m0 Mesh data structure\n   * @param u0 vector of Scalar size equal to number of vertices of mesh, the initial values of per-vertex logarithmic scale factors\n   * @param d0 vector of Scalar size eqaul to number of vertices of mesh, a delta vector on u0\n   * @param lambda_max Scalar controlling the maximum step size along the direction d0\n   * @param n_samples Total number of evenly distributed sample points along d0\n   * @param delaunay_stats struct collecting stats for delaunay flips through out the algorithm\n   * @param solve_stats struct collecting info for solvings through out the algorithm\n   * @return void\n   */\n  static void SampleEnergyAlongDirection(const Mesh<Scalar>& m0, const VectorX& u0, std::string fname, const VectorX &d, Scalar lambda_max, int n_sample, DelaunayStats& delaunay_stats, SolveStats<Scalar>& solve_stats, bool subtract_avg=false){\n\n    if (n_sample == 0) return;\n\n    VectorX alpha, cot_alpha;\n    Scalar step_size = lambda_max / n_sample;\n    Scalar avg_e = 0.0;\n    auto m = m0; auto u = u0;\n    Eigen::Matrix<Scalar, Eigen::Dynamic, 1> E; E.setZero(n_sample);\n    for (int i = 0; i < n_sample; i++){\n      m = m0;\n      u = u0 + i * step_size * d;\n      MakeDelaunay(m, u, delaunay_stats, solve_stats);\n      ComputeAngles(m, u, alpha, cot_alpha);\n      E[i] = ConformalEquivalenceEnergy(m, alpha, u);\n    }\n    if(subtract_avg) avg_e = E.sum() / n_sample;\n    \n    std::vector<std::string> e_samples;\n    for(int i = 0; i < E.size(); i++){\n      std::stringstream ss;\n      ss << std::to_string(i) << \",\" << std::setprecision(17) << E[i]-avg_e;\n      e_samples.push_back(ss.str());\n    }\n\n    std::fstream nf(fname,std::ios::in | std::ios::out);\n    WriteLog(fname, e_samples, \"itr, e-avg_e\");\n\n  }\n\n  /**\n   * Given the prescribed per-vertex angle sum, modify the angle sum at first vertex, \n   * to make sure Gauss-Bonnet is respected up to numerical error.\n   * @param m Mesh data structure\n   * @return void\n   */\n  static void GaussBonnetCorrection(Mesh<Scalar>& m)\n  {\n    \n    Scalar pi;\n#ifdef WITH_MPFR\n    if (std::is_same<Scalar, mpfr::mpreal>::value)\n      pi = Scalar(mpfr::const_pi());\n    else\n      pi = Scalar(M_PI);\n#else\n      pi = Scalar(M_PI);\n#endif\n    int double_genus = 2 - (m.n_vertices() - m.n_edges() + m.n_faces());\n    Scalar targetsum = pi * (2 * m.n_vertices() - 2 * (2 - double_genus));\n    double th_hat_sum = 0.0;\n    for(auto t: m.Th_hat)\n      th_hat_sum += t;\n    m.Th_hat[0] -= (th_hat_sum - targetsum);\n  }\n\n  /**\n   * Logging function, to write list of strings to given file, possibly with header if the file is empty.\n   * @param fname, the filename to write log to.\n   * @param v, vector of strings to be written to file.\n   * @param header, will be written as first line to the file if it's empty.\n   * @param append, toggle between append (true) and out mode (false).\n   * @return void\n   */\n  static void WriteLog(std::string fname, std::vector<std::string>& v, std::string header=\"\", bool append=false){\n    std::fstream mf, nf; nf.open(fname, std::ios_base::in);\n    if(append)\n      mf.open(fname, std::ios_base::app);\n    else\n      mf.open(fname, std::ios_base::out);\n    \n    if(!(append && nf.peek() != std::ifstream::traits_type::eof()))\n      mf << header << \"\\n\";\n    for(int i = 0; i < v.size(); i++){\n      mf << v[i] << \"\\n\";\n    }\n    mf.close();\n  }\n\n};\n#endif\n", "meta": {"hexsha": "aa5156d7453c10e64e34225ab5322da509b36299", "size": 60043, "ext": "hh", "lang": "C++", "max_stars_repo_path": "src/conformal_ideal_delaunay/ConformalIdealDelaunayMapping.hh", "max_stars_repo_name": "hankstag/ConformalIdealDelaunay", "max_stars_repo_head_hexsha": "653a6f62908517df60a3e9f4c311ba6f2f358382", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/conformal_ideal_delaunay/ConformalIdealDelaunayMapping.hh", "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/ConformalIdealDelaunayMapping.hh", "max_forks_repo_name": "hankstag/ConformalIdealDelaunay", "max_forks_repo_head_hexsha": "653a6f62908517df60a3e9f4c311ba6f2f358382", "max_forks_repo_licenses": ["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.1952926209, "max_line_length": 325, "alphanum_fraction": 0.5990040471, "num_tokens": 17071, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6113819874558604, "lm_q2_score": 0.5428632831725052, "lm_q1q2_score": 0.33189683298281974}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\n\n// Copyright (c) 2007-2012 Barend Gehrels, Amsterdam, the Netherlands.\n// Copyright (c) 2008-2012 Bruno Lalande, Paris, France.\n// Copyright (c) 2009-2012 Mateusz Loskot, London, UK.\n\n// Parts of Boost.Geometry are redesigned from Geodan's Geographic Library\n// (geolib/GGL), copyright (c) 1995-2010 Geodan, Amsterdam, the Netherlands.\n\n// Use, modification and distribution is subject to the Boost Software License,\n// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n\n#ifndef BOOST_GEOMETRY_EXTENSIONS_NSPHERE_ALGORITHMS_WITHIN_HPP\n#define BOOST_GEOMETRY_EXTENSIONS_NSPHERE_ALGORITHMS_WITHIN_HPP\n\n\n#include <boost/geometry/algorithms/distance.hpp>\n#include <boost/geometry/algorithms/make.hpp>\n#include <boost/geometry/algorithms/within.hpp>\n#include <boost/geometry/strategies/distance.hpp>\n\n#include <boost/geometry/multi/core/tags.hpp>\n\n#include <boost/geometry/extensions/nsphere/core/access.hpp>\n#include <boost/geometry/extensions/nsphere/core/radius.hpp>\n#include <boost/geometry/extensions/nsphere/core/tags.hpp>\n#include <boost/geometry/extensions/nsphere/algorithms/assign.hpp>\n\n\nnamespace boost { namespace geometry\n{\n\n#ifndef DOXYGEN_NO_DETAIL\nnamespace detail { namespace within\n{\n\n\n\n//-------------------------------------------------------------------------------------------------------\n// Implementation for n-spheres. Supports circles or spheres, in 2 or 3 dimensions, in Euclidian system\n// Circle center might be of other point-type as geometry\n// Todo: implement as strategy\n//-------------------------------------------------------------------------------------------------------\ntemplate<typename P, typename C>\ninline bool point_in_circle(P const& p, C const& c)\n{\n    namespace services = strategy::distance::services;\n\n    assert_dimension<C, 2>();\n\n    typedef typename point_type<C>::type point_type;\n    typedef typename services::default_strategy\n        <\n            point_tag, P, point_type\n        >::type strategy_type;\n    typedef typename services::return_type<strategy_type>::type return_type;\n\n    strategy_type strategy;\n\n    P const center = geometry::make<P>(get<0>(c), get<1>(c));\n    return_type const r = geometry::distance(p, center, strategy);\n    return_type const rad = services::result_from_distance\n        <\n            strategy_type\n        >::apply(strategy, get_radius<0>(c));\n\n    return r < rad;\n}\n/// 2D version\ntemplate<typename T, typename C>\ninline bool point_in_circle(T const& c1, T const& c2, C const& c)\n{\n    typedef typename point_type<C>::type point_type;\n\n    point_type p = geometry::make<point_type>(c1, c2);\n    return point_in_circle(p, c);\n}\n\ntemplate<typename B, typename C>\ninline bool box_in_circle(B const& b, C const& c)\n{\n    typedef typename point_type<B>::type point_type;\n\n    // Currently only implemented for 2d geometries\n    assert_dimension<point_type, 2>();\n    assert_dimension<C, 2>();\n\n    // Box: all four points must lie within circle\n\n    // Check points lower-left and upper-right, then lower-right and upper-left\n    return point_in_circle(get<min_corner, 0>(b), get<min_corner, 1>(b), c)\n        && point_in_circle(get<max_corner, 0>(b), get<max_corner, 1>(b), c)\n        && point_in_circle(get<min_corner, 0>(b), get<max_corner, 1>(b), c)\n        && point_in_circle(get<max_corner, 0>(b), get<min_corner, 1>(b), c);\n}\n\n// Generic \"range-in-circle\", true if all points within circle\ntemplate<typename R, typename C>\ninline bool range_in_circle(R const& range, C const& c)\n{\n    assert_dimension<R, 2>();\n    assert_dimension<C, 2>();\n\n    for (typename boost::range_iterator<R const>::type it = boost::begin(range);\n         it != boost::end(range); ++it)\n    {\n        if (! point_in_circle(*it, c))\n        {\n            return false;\n        }\n    }\n\n    return true;\n}\n\ntemplate<typename Y, typename C>\ninline bool polygon_in_circle(Y const& poly, C const& c)\n{\n    return range_in_circle(exterior_ring(poly), c);\n}\n\n\n\ntemplate<typename I, typename C>\ninline bool multi_polygon_in_circle(I const& m, C const& c)\n{\n    for (typename I::const_iterator i = m.begin(); i != m.end(); i++)\n    {\n        if (! polygon_in_circle(*i, c))\n        {\n            return false;\n        }\n    }\n    return true;\n}\n\n\n\n}} // namespace detail::within\n#endif // DOXYGEN_NO_DETAIL\n\n\n#ifndef DOXYGEN_NO_DISPATCH\nnamespace dispatch\n{\n\n\ntemplate <typename P, typename Circle>\nstruct within<P, Circle, point_tag, nsphere_tag>\n{\n    template <typename Strategy>\n    static inline bool apply(P const& p, Circle const& c, Strategy const&)\n    {\n        return detail::within::point_in_circle(p, c);\n    }\n};\n\ntemplate <typename Box, typename Circle>\nstruct within<Box, Circle, box_tag, nsphere_tag>\n{\n    template <typename Strategy>\n    static inline bool apply(Box const& b, Circle const& c, Strategy const&)\n    {\n        return detail::within::box_in_circle(b, c);\n    }\n};\n\ntemplate <typename Linestring, typename Circle>\nstruct within<Linestring, Circle, linestring_tag, nsphere_tag>\n{\n    template <typename Strategy>\n    static inline bool apply(Linestring const& ln, Circle const& c, Strategy const&)\n    {\n        return detail::within::range_in_circle(ln, c);\n    }\n};\n\ntemplate <typename Ring, typename Circle>\nstruct within<Ring, Circle, ring_tag, nsphere_tag>\n{\n    template <typename Strategy>\n    static inline bool apply(Ring const& r, Circle const& c, Strategy const&)\n    {\n        return detail::within::range_in_circle(r, c);\n    }\n};\n\ntemplate <typename Polygon, typename Circle>\nstruct within<Polygon, Circle, polygon_tag, nsphere_tag>\n{\n    template <typename Strategy>\n    static inline bool apply(Polygon const& poly, Circle const& c, Strategy const&)\n    {\n        return detail::within::polygon_in_circle(poly, c);\n    }\n};\n\ntemplate <typename M, typename C>\nstruct within<M, C, multi_polygon_tag, nsphere_tag>\n{\n    template <typename Strategy>\n    static inline bool apply(M const& m, C const& c, Strategy const&)\n    {\n        return detail::within::multi_polygon_in_circle(m, c);\n    }\n};\n\n\n} // namespace dispatch\n#endif // DOXYGEN_NO_DISPATCH\n\n\n}} // namespace boost::geometry\n\n#endif // BOOST_GEOMETRY_EXTENSIONS_NSPHERE_ALGORITHMS_WITHIN_HPP\n", "meta": {"hexsha": "6a73fcf38ddabb77d65b7dcb0b4ffd102491bfbd", "size": 6267, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/geometry/extensions/nsphere/algorithms/within.hpp", "max_stars_repo_name": "juslee/boost-svn", "max_stars_repo_head_hexsha": "6d5a03c1f5ed3e2b23bd0f3ad98d13ff33d4dcbb", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2016-07-03T22:12:18.000Z", "max_stars_repo_stars_event_max_datetime": "2016-07-03T22:12:18.000Z", "max_issues_repo_path": "boost/geometry/extensions/nsphere/algorithms/within.hpp", "max_issues_repo_name": "graehl/boost", "max_issues_repo_head_hexsha": "37cc4ca77896a86ad10e90dc03e1e825dc0d5492", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "boost/geometry/extensions/nsphere/algorithms/within.hpp", "max_forks_repo_name": "graehl/boost", "max_forks_repo_head_hexsha": "37cc4ca77896a86ad10e90dc03e1e825dc0d5492", "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.8801843318, "max_line_length": 105, "alphanum_fraction": 0.6776767193, "num_tokens": 1496, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6113819874558604, "lm_q2_score": 0.5428632831725052, "lm_q1q2_score": 0.33189683298281974}}
{"text": "/**\n\n *  \\file   postprocessing.hh\n *  \\brief  postprocessing.hh\n **/\n\n#ifndef POSTPROCESSING_HH\n#define POSTPROCESSING_HH\n\n#include <cmake_config.h>\n\n#include <dune/fem/operator/projection/l2projection.hh>\n#include <dune/fem/io/file/vtkio.hh>\n#include <dune/fem/io/file/datawriter.hh>\n#include <dune/fem/misc/l2norm.hh>\n#include <dune/fem/misc/l2error.hh>\n\n#include <dune/stuff/common/logging.hh>\n#include <dune/stuff/common/misc.hh>\n#include <dune/stuff/common/filesystem.hh>\n#include <dune/stuff/common/parameter/configcontainer.hh>\n#include <dune/stuff/fem/customprojection.hh>\n#include <dune/stuff/common/print.hh>\n#include <dune/stuff/fem/functions/transform.hh>\n#include <dune/stuff/fem/functions/integrals.hh>\n\n#include <boost/format.hpp>\n#include <cmath>\n#include <sstream>\n#include <tuple>\n\n//! Error and vtk output wrapper class for Stokes problem/pass\ntemplate <  class OseenLDGMethodImp, class ProblemImp >\nclass PostProcessor\n{\n    public:\n        typedef ProblemImp\n            ProblemType;\n\n        typedef OseenLDGMethodImp\n            OseenLDGMethodType;\n\t\ttypedef typename OseenLDGMethodType::Traits::DiscreteOseenFunctionSpaceWrapperType\n            DiscreteOseenFunctionSpaceWrapperType;\n\t\ttypedef typename OseenLDGMethodType::Traits::DiscreteOseenFunctionWrapperType\n            DiscreteOseenFunctionWrapperType;\n\n        typedef typename ProblemType::VelocityType\n            ContinuousVelocityType;\n        typedef typename ProblemType::PressureType\n            ContinuousPressureType;\n        typedef typename ProblemType::ForceType\n            ForceType;\n        typedef typename ProblemType::DirichletDataType\n            DirichletDataType;\n\n\t\ttypedef typename OseenLDGMethodType::Traits::GridPartType\n            GridPartType;\n        typedef typename GridPartType::GridType\n            GridType;\n\n        typedef Dune::SubsamplingVTKIO<GridPartType>\n            VTKWriterType;\n\n\t\ttypedef typename OseenLDGMethodType::Traits::DiscreteVelocityFunctionType\n            DiscreteVelocityFunctionType;\n\t\ttypedef typename OseenLDGMethodType::Traits::DiscreteVelocityFunctionSpaceType\n            DiscreteVelocityFunctionSpaceType;\n\n\t\ttypedef typename OseenLDGMethodType::Traits::DiscretePressureFunctionType\n            DiscretePressureFunctionType;\n\t\ttypedef typename OseenLDGMethodType::Traits::DiscretePressureFunctionSpaceType\n            DiscretePressureFunctionSpaceType;\n\n\n        PostProcessor( const DiscreteOseenFunctionSpaceWrapperType& wrapper, const ProblemType& prob )\n            :\n            problem_( prob ),\n            spaceWrapper_( wrapper ),\n            gridPart_( wrapper.gridPart() ),\n            velocitySpace_ ( wrapper.discreteVelocitySpace() ),\n            discreteExactVelocity_( \"u_exact\", wrapper.discreteVelocitySpace() ),\n            discreteExactForce_( \"f_exact\", wrapper.discreteVelocitySpace() ),\n            discreteExactDirichlet_( \"gd_exact\", wrapper.discreteVelocitySpace() ),\n            discreteExactPressure_( \"p_exact\", wrapper.discretePressureSpace() ),\n            errorFunc_velocity_( \"err_velocity\", wrapper.discreteVelocitySpace() ),\n            errorFunc_pressure_( \"err_pressure\", wrapper.discretePressureSpace() ),\n            solutionAssembled_( false ),\n            current_refine_level_( std::numeric_limits<int>::min() ),\n            l2_error_pressure_( - std::numeric_limits<double>::max() ),\n            l2_error_velocity_( - std::numeric_limits<double>::max() ),\n            vtkWriter_( wrapper.gridPart() ),\n            datadir_( DSC_CONFIG_GET( \"fem.io.datadir\", std::string(\"data\") ) + \"/\" )\n        {\n            DSC::testCreateDirectory( datadir_ );\n        }\n\n\t\t/** \\brief analytical data is L2 projected\n\t\t\t\\todo only use DSC::CustomProjection when really necessary\n\t\t\t**/\n        void assembleExactSolution()\n        {\n            DSFe::CustomProjection::project( problem_.dirichletData(), discreteExactDirichlet_ );\n\n            typedef Dune::L2Projection< double, double, ContinuousVelocityType, DiscreteVelocityFunctionType > ProjectionV;\n                ProjectionV projectionV;\n            projectionV( problem_.velocity(), discreteExactVelocity_ );\n\n            typedef Dune::L2Projection< double, double, ForceType, DiscreteVelocityFunctionType > ProjectionF;\n                ProjectionF projectionF;\n            projectionF( problem_.force(), discreteExactForce_ );\n\n            typedef Dune::L2Projection< double, double, ContinuousPressureType, DiscretePressureFunctionType > ProjectionP;\n                ProjectionP projectionP;\n            projectionP( problem_.pressure(), discreteExactPressure_ );\n\t\t\tif ( DSC_CONFIG_GET( \"save_matrices\", false ) ) {\n                auto& matlabLogStream = DSC_LOG_ERROR;\n\t\t\t\tDSC::printDiscreteFunctionMatlabStyle( discreteExactVelocity_, \"u_exakt\", matlabLogStream );\n\t\t\t\tDSC::printDiscreteFunctionMatlabStyle( discreteExactPressure_, \"p_exakt\", matlabLogStream );\n\t\t\t}\n        }\n\n\t\t//! output function that 'knows' function output mode; assembles filename\n        template <class Function>\n        void vtk_write( const Function& f ) {\n            if ( Function::FunctionSpaceType::DimRange > 1 ) {\n                vtkWriter_.addVectorVertexData( f );\n                vtkWriter_.addVectorCellData( f );\n            }\n            else {\n                vtkWriter_.addVertexData( f );\n                vtkWriter_.addCellData( f );\n            }\n\n            std::stringstream path;\n            if ( DSC_CONFIG_GET( \"per-run-output\", false ) )\n                path    << datadir_ << \"/ref\"\n                        <<  current_refine_level_ << \"_\" << f.name();\n            else\n                path << datadir_ << \"/\" << f.name();\n\n            vtkWriter_.write( path.str().c_str() );\n            vtkWriter_.clear();\n        }\n\n\t\t//! use this function if no reference (ie. coarser/finer) solution is available, or an analytical one is\n        void save( const GridType& grid, const DiscreteOseenFunctionWrapperType& wrapper, int refine_level )\n        {\n            if ( ProblemType:: hasMeaningfulAnalyticalSolution ) {\n                if ( !solutionAssembled_ || current_refine_level_ != refine_level ) //re-assemble solution if refine level has changed\n                    assembleExactSolution();\n                current_refine_level_ = refine_level;\n\n\t\t\t\tcalcError( wrapper );\n                vtk_write( discreteExactVelocity_ );\n                vtk_write( discreteExactPressure_ );\n                vtk_write( discreteExactForce_ );\n                vtk_write( discreteExactDirichlet_ );\n                vtk_write( errorFunc_pressure_ );\n                vtk_write( errorFunc_velocity_ );\n            }\n\n            save_common( grid, wrapper, refine_level );\n        }\n\n\t\t//! use this save in eoc runs with no analytical solution available\n        void save( const GridType& grid, const DiscreteOseenFunctionWrapperType& wrapper, const DiscreteOseenFunctionWrapperType& reference, int refine_level )\n        {\n            current_refine_level_ = refine_level;\n            calcError( wrapper, reference );\n            vtk_write( discreteExactVelocity_ );\n            vtk_write( discreteExactPressure_ );\n            vtk_write( errorFunc_pressure_ );\n            vtk_write( errorFunc_velocity_ );\n\n            save_common( grid, wrapper, refine_level );\n        }\n\n\t\t//! used by both PostProcessor::save modes, outputs solutions (in grape/vtk form), but no errors or analytical functions\n        void save_common( const GridType& /*grid*/, const DiscreteOseenFunctionWrapperType& wrapper, int refine_level )\n        {\n            current_refine_level_ = refine_level;\n\n            vtk_write( wrapper.discretePressure() );\n            vtk_write( wrapper.discreteVelocity() );\n#ifndef NLOG\n\t\t\tentityColoration();\n#endif\n        }\n\n\t\tvoid calcError( const DiscreteOseenFunctionWrapperType& wrapper )\n\t\t{\n\t\t\tcalcError( wrapper.discretePressure() , wrapper.discreteVelocity() );\n\t\t}\n\n\t\t//! proxy function that is to be used if no analytical solutions are availble to calculate errors against\n        void calcError( const DiscreteOseenFunctionWrapperType& computed, const DiscreteOseenFunctionWrapperType& reference )\n        {\n            discreteExactPressure_.assign( reference.discretePressure() );\n            discreteExactVelocity_.assign( reference.discreteVelocity() );\n\t\t\t//set to to true so calcError call does not try to assemble exact solutions again\n            solutionAssembled_ = true;\n            calcError( computed.discretePressure(), computed.discreteVelocity() );\n        }\n\n\t\t//! print and save L2 error(functions)\n        void calcError( const DiscretePressureFunctionType& pressure, const DiscreteVelocityFunctionType& velocity )\n        {\n            if ( !solutionAssembled_ )\n                assembleExactSolution();\n\n            errorFunc_pressure_.assign( discreteExactPressure_ );\n            errorFunc_pressure_ -= pressure;\n            errorFunc_velocity_.assign( discreteExactVelocity_ );\n            errorFunc_velocity_ -= velocity;\n\n            Dune::L2Norm< GridPartType > l2_Error( gridPart_ );\n\n            l2_error_pressure_ = l2_Error.norm( errorFunc_pressure_ );\n            l2_error_velocity_ = l2_Error.norm( errorFunc_velocity_ );\n\n            const double boundaryInt = DSFe::boundaryIntegral( problem_.dirichletData(), discreteExactVelocity_.space() );\n            const double pressureMean = DSFe::integralAndVolume( pressure, pressure.space() ).first;\n            const double exactPressureMean = DSFe::integralAndVolume( problem_.pressure(), discreteExactPressure_.space() ).first;\n\n            DSC_LOG_INFO.resume();\n            DSC_LOG_INFO << \"L2-Error Pressure: \" << std::setw(8) << l2_error_pressure_ << \"\\n\"\n                            << \"L2-Error Velocity: \" << std::setw(8) << l2_error_velocity_ << \"\\n\"\n\t\t\t\t\t\t\t<< boost::format( \"Pressure volume integral: %f (discrete), %f (exact)\\n\") % pressureMean % exactPressureMean\n\t\t\t\t\t\t\t<< boost::format( \"g_D boundary integral: %f\\n\") % boundaryInt;\n        }\n\n\t\t//! used to sore errors in runinfo structure (for eoc latex output)\n        std::vector<double> getError()\n        {\n            std::vector<double> ret;\n            ret.push_back( l2_error_velocity_ );\n            ret.push_back( l2_error_pressure_ );\n            return ret;\n        }\n\n\t\t//! assign each entity it's 'id' int and save/(vtk)output it in a discrete function\n        void entityColoration()\n        {\n            DiscretePressureFunctionType cl ( \"entitiy-num\", spaceWrapper_.discretePressureSpace() );\n            unsigned long numberOfEntities = 0;\n\n            typedef typename GridPartType::GridType::template Codim< 0 >::Entity\n                EntityType;\n            typedef typename GridPartType::template Codim< 0 >::IteratorType\n                EntityIteratorType;\n            typedef typename GridPartType::IntersectionIteratorType\n                IntersectionIteratorType;\n\n            EntityIteratorType entityItEndLog = velocitySpace_.end();\n            for (   EntityIteratorType entityItLog = velocitySpace_.begin();\n                    entityItLog != entityItEndLog;\n                    ++entityItLog, ++numberOfEntities ) {\n                const EntityType& entity = *entityItLog;\n                typename DiscretePressureFunctionType::LocalFunctionType\n                    lf = cl.localFunction( entity );\n\n                for ( int i = 0; i < lf.numDofs(); ++i ){\n                    lf[i] = numberOfEntities;\n                }\n            }\n            vtk_write( cl );\n        }\n\n    private:\n\n        const ProblemType& problem_;\n        const DiscreteOseenFunctionSpaceWrapperType& spaceWrapper_;\n        const GridPartType& gridPart_;\n        const DiscreteVelocityFunctionSpaceType& velocitySpace_;\n        DiscreteVelocityFunctionType discreteExactVelocity_;\n        DiscreteVelocityFunctionType discreteExactForce_;\n        DiscreteVelocityFunctionType discreteExactDirichlet_;\n        DiscretePressureFunctionType discreteExactPressure_;\n        DiscreteVelocityFunctionType errorFunc_velocity_;\n        DiscretePressureFunctionType errorFunc_pressure_;\n        bool solutionAssembled_;\n        int current_refine_level_;\n        double l2_error_pressure_;\n        double l2_error_velocity_;\n        VTKWriterType vtkWriter_;\n        std::string datadir_;\n};\n\n#undef vtk_write\n\n#endif // end of postprocessing.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\n", "meta": {"hexsha": "70bd0c8db245b6e4fa870454c6618cd76576c82c", "size": 13949, "ext": "hh", "lang": "C++", "max_stars_repo_path": "dune/fem/oseen/postprocessing.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/postprocessing.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/postprocessing.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": 43.3198757764, "max_line_length": 159, "alphanum_fraction": 0.6718761202, "num_tokens": 2984, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5428632683808533, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.33189681625159845}}
{"text": "/*\n * CurrentFlowGroupCloseness.cpp\n *\n *      Author: gstoszek\n */\n#define ARMA_DONT_PRINT_ERRORS\n#include \"CurrentFlowGroupCloseness.h\"\n#include \"Centrality.h\"\n#include \"../algebraic/CSRMatrix.h\"\n#include \"../numerics/LAMG/Lamg.h\"\n#include \"../auxiliary/Log.h\"\n#include <chrono>\n#include <stdlib.h>\n#include <cmath>\n#include <algorithm>\n#include \"EffectiveResistanceDistance.h\"\n#include \"ERDLevel.h\"\n#include \"../components/ConnectedComponents.h\"\n#include <armadillo>\n\nnamespace NetworKit {\n\n   CurrentFlowGroupCloseness::CurrentFlowGroupCloseness(Graph& G,const count k, const count CB,const double epsilon, const bool doInvert)\n    : G(G),k(k),CB(CB),epsilon(epsilon),doInvert(doInvert){\n     if (G.isDirected()) throw std::runtime_error(\"Graph is directed!\");\n     ConnectedComponents cc(G);\n     cc.run();\n     if (cc.getPartition().numberOfSubsets() > 1) throw std::runtime_error(\"Graph has more then one component!\");\n     if(k>=G.numberOfNodes()) throw std::runtime_error(\"Size of Group greater then number of nodes!\");\n     auto start = std::chrono::high_resolution_clock::now();\n     auto end = std::chrono::high_resolution_clock::now();\n     std::chrono::duration<double> diff;\n\n     S.resize(k);\n     n=G.numberOfNodes();\n\n     end = std::chrono::high_resolution_clock::now();\n     diff = end-start;\n     std::cout << \"Constructor finished in \" << diff.count() << \"(s)\" << \"\\n\";\n     std::cout << \"Number of Nodes=\" << G.numberOfNodes() << \"\\n\";\n   }\n\n   void CurrentFlowGroupCloseness::run() {\n     bool coarse;\n     count ID, minDegree;\n     auto start = std::chrono::high_resolution_clock::now();\n     auto end = std::chrono::high_resolution_clock::now();\n     std::chrono::duration<double> diff;\n     std::vector<node> vecOfChosenNodes;\n\n     ID=0;\n     if(CB>0){\n       ID++;\n       minDegree=1;\n       mergePeripheralNodes();\n       ID++;\n       minDegree=updateMinDegree();\n       coarse=true;\n       while((minDegree<CB)&&(coarse)){\n         vecOfChosenNodes=coarsingIndices(minDegree, false);\n         coarseGraph(vecOfChosenNodes,ID);\n         ID++;\n         minDegree=updateMinDegree();\n         if(!(vecOfChosenNodes.size()>1)||!(G.numberOfNodes()>k)){\n           coarse=false;\n         }\n        }\n      }\n      end = std::chrono::high_resolution_clock::now();\n      diff = end-start;\n      std::cout << \"Coarsening of G finished in: \" << diff.count() << \"(s)\" << \"\\n\";\n      std::cout << \"Number of nodes after coarsening: \" << G.numberOfNodes() << \"\\n\";\n\n      /*\n      start = std::chrono::high_resolution_clock::now();\n      if(CB>1){\n        ID=LevelList[LevelList.size()-1].getID();\n        std::cout<<\"ID=\"<<ID<<\"\\n\";\n        while(ID>1){\n          uncoarseEfffectiveResistanceDistanceMatrix(ID);\n          //greedy();\n          //std::cout<<\"Level:\" <<ID<<\" with the value: \" << CFGCC << \"\\n\";\n          ID--;\n        }\n      }\n      end = std::chrono::high_resolution_clock::now();\n      diff = end-start;\n      std::cout << \"Uncoarsening in: \" << diff.count() << \"(s)\" << \"\\n\";\n      */\n      std::cout << \"Starting Greedy-Algorithm\\n\";\n      start = std::chrono::high_resolution_clock::now();\n      if(doInvert)\n        greedy();\n      else{\n        greedyLAMG();\n      }\n      end = std::chrono::high_resolution_clock::now();\n      diff = end-start;\n      std::cout << \"Greedy in: \" << diff.count() << \"(s)\" << \"\\n\\n\";\n    }\n    std::vector<node> CurrentFlowGroupCloseness::getNodesofGroup(){\n      return S;\n    }\n    double CurrentFlowGroupCloseness::getCFGCC() {\n      return CFGCC;\n    }\n    void CurrentFlowGroupCloseness::greedy(){\n      count v_i,w_i;\n      node s,v,w;\n      double centrality,prevCFGCC,bestMarginalGain,distance;\n      std::vector<bool> V,W;\n      std::vector<node> vecOfNodes,vecOfSamples, vecOfPeriphs,cutNodes;\n      std::vector<count> reverse;\n      std::vector<double> mindst, dst, bst, minApprox, bstApprox, marginalGain;\n\n      arma::Mat<double> Pinv;\n      Pinv=computePinvOfLaplacian();\n\n      CFGCC=n*n*n;\n      prevCFGCC=CFGCC;\n      V.resize(G.numberOfNodes(),true);\n      W.resize(G.numberOfNodes(),true);\n      mindst.resize(G.numberOfNodes(),n*n);\n      marginalGain.resize(G.numberOfNodes(),CFGCC);\n\n      vecOfSamples.resize(0);\n      vecOfPeriphs.resize(0);\n      vecOfNodes = G.nodes();\n      reverse.resize(G.upperNodeIdBound());\n      for(count i=0;i<vecOfNodes.size();i++){\n        reverse[vecOfNodes[i]]=i;\n      }\n      for(count i=0;i<vecOfNodes.size();i++){\n        v=vecOfNodes[i];\n        if(std::find(vecOfPeripheralNodes.begin(), vecOfPeripheralNodes.end(), v) != vecOfPeripheralNodes.end())\n          vecOfSamples.push_back(v);\n        else{\n          vecOfPeriphs.push_back(v);\n        }\n      }\n      for(count i=0;i<k;i++){\n        std::random_shuffle (vecOfSamples.begin(), vecOfSamples.end());\n        bestMarginalGain=0.;\n        for (count j=0; j<vecOfSamples.size();j++) {\n          v=vecOfSamples[j];\n          v_i=reverse[v];\n          if(V[v_i] && (bestMarginalGain<marginalGain[v_i])){\n            dst=mindst;\n            centrality = 0.;\n            cutNodes.resize(0);\n            for (count l = 0; l < vecOfSamples.size(); l++) {\n              w=vecOfSamples[l];\n              w_i=reverse[w];\n              if(W[w_i]){\n                distance=Pinv(v_i,v_i)+Pinv(w_i,w_i)-2*Pinv(v_i,w_i);\n                if (distance< mindst[w_i]){\n                  dst[w_i]=distance;\n                  if(distance<bst[w_i])\n                    cutNodes.push_back(w_i);\n                }\n              }\n              centrality +=dst[w_i];\n            }\n            for (count l = 0 ; l < vecOfPeriphs.size(); l++) {\n              w=vecOfPeriphs[l];\n              w_i=reverse[w];\n              if(W[w_i]){\n                distance=Pinv(v_i,v_i)+Pinv(w_i,w_i)-2*Pinv(v_i,w_i);\n                if (distance< mindst[w_i]){\n                  dst[w_i]=distance;\n                  if(distance<bst[w_i])\n                    cutNodes.push_back(w_i);\n                }\n                centrality += dst[w_i];\n              }\n            }\n            marginalGain[v_i]=prevCFGCC-centrality;\n            if (centrality < CFGCC) {\n              CFGCC = centrality;\n              bst=dst;\n              s = v;\n              bestMarginalGain=marginalGain[v_i];\n            }\n          }\n        }\n        S[i]=s;\n        V[s]=false;\n        mindst=bst;\n        prevCFGCC=CFGCC;\n      }\n     CFGCC = (double)(n)/CFGCC;\n    }\n    void CurrentFlowGroupCloseness::greedyLAMG(){\n      count v_i,w_i;\n      node s,v,w;\n      double centrality,prevCFGCC,bestMarginalGain,distance;\n      std::vector<bool> V;\n      std::vector<node> vecOfNodes,vecOfSamples, vecOfPeriphs;\n      std::vector<count> reverse;\n      std::vector<double> mindst, dst, bst, minApprox, bstApprox, marginalGain;\n      std::cout<<\"***************Setup***************\\n\";\n      Lamg<CSRMatrix> lamg;\n      CSRMatrix matrix = CSRMatrix::laplacianMatrix(G);\n      lamg.setupConnected(matrix);\n      std::cout<<\"**************Setup***************\\n\";\n      CFGCC=n*n*n;\n      prevCFGCC=CFGCC;\n      mindst.resize(G.numberOfNodes(),n*n);\n      marginalGain.resize(G.numberOfNodes(),CFGCC);\n      V.resize(G.numberOfNodes(),true);\n      vecOfSamples.resize(0);\n      vecOfPeriphs.resize(0);\n      vecOfNodes = G.nodes();\n      reverse.resize(G.upperNodeIdBound());\n      for(count i=0;i<vecOfNodes.size();i++){\n        reverse[vecOfNodes[i]]=i;\n      }\n      for(count i=0;i<vecOfNodes.size();i++){\n        v=vecOfNodes[i];\n        if(std::find(vecOfPeripheralNodes.begin(), vecOfPeripheralNodes.end(), v) != vecOfPeripheralNodes.end())\n          vecOfSamples.push_back(v);\n        else{\n          vecOfPeriphs.push_back(v);\n        }\n      }\n      Vector result(vecOfNodes.size());\n      Vector rhs(vecOfNodes.size(), 0.);\n      Vector zeroVector(vecOfNodes.size(), 0.);\n      std::cout<<\"********************1***************\\n\";\n      for(count i=0;i<k;i++){\n        std::random_shuffle (vecOfSamples.begin(), vecOfSamples.end());\n        bestMarginalGain=0.;\n        for (count j=0; j<vecOfSamples.size();j++) {\n          v=vecOfSamples[j];\n          v_i=reverse[v];\n          if(V[v_i] && (bestMarginalGain<marginalGain[v_i])){\n            rhs[v_i]=1.;\n            dst=mindst;\n            centrality = 0.;\n            for (count l = 0; l < vecOfSamples.size(); l++) {\n              if(v!=w){\n                w=vecOfSamples[l];\n                w_i=reverse[w];\n                rhs[w_i]=-1.;\n                result=zeroVector;\n                lamg.solve(rhs, result);\n                distance=fabs(result[v_i]-result[w_i]);\n                if (distance< mindst[w_i])\n                  dst[w_i]=distance;\n                centrality +=dst[w_i];\n                rhs[w_i]=0.;\n              }\n            }\n            for (count l = 0 ; l < vecOfPeriphs.size(); l++) {\n              w=vecOfPeriphs[l];\n              w_i=reverse[w];\n              rhs[w_i]=-1.;\n              result=zeroVector;\n              lamg.solve(rhs, result);\n              distance=fabs(result[v_i]-result[w_i]);\n              if (distance< mindst[w_i])\n                dst[w_i]=distance;\n              centrality += dst[w_i];\n              rhs[w_i]=0.;\n            }\n            marginalGain[v_i]=prevCFGCC-centrality;\n            if (centrality < CFGCC) {\n              CFGCC = centrality;\n              bst=dst;\n              s = v;\n              bestMarginalGain=marginalGain[v_i];\n            }\n            rhs[v_i]=0.;\n          }\n        }\n        S[i]=s;\n        V[s]=false;\n        mindst=bst;\n        prevCFGCC=CFGCC;\n      }\n     CFGCC = (double)(n)/CFGCC;\n    }\n    count CurrentFlowGroupCloseness::updateMinDegree(){\n      bool search;\n      count min;\n      count i;\n      std::vector<node> vecOfNodes;\n      node v;\n      search=true;\n      min=n;\n      i=0;\n      vecOfNodes=G.nodes();\n      while((i<vecOfNodes.size())&&(search)){\n        v=vecOfNodes[i];\n        if((G.degree(v)<min) && (G.degree(v)>1)){\n          min=G.degree(v);\n          if(min==2){\n            search=false;\n          }\n        }\n        i++;\n      }\n      return min;\n    }\n\n    std::vector<node> CurrentFlowGroupCloseness::coarsingIndices(count courseningDegree, bool Random){\n        bool search;\n        count l;\n        node c,w;\n        std::vector<node> vecOfNodes, vecOfChosenNodes, vecOfNeighbors,vecOfOccupiedNodes,vecOfCandidates;\n\n        vecOfOccupiedNodes.resize(0);\n        vecOfCandidates.resize(0);\n        vecOfNodes=G.nodes();\n        for(count i=0;i<vecOfNodes.size();i++){\n          c=vecOfNodes[i];\n          if(G.degree(c)==courseningDegree){\n            vecOfCandidates.push_back(c);\n          }\n        }\n        if(Random){\n          std::random_shuffle (vecOfCandidates.begin(), vecOfCandidates.end());\n        }\n        for(count i=0;i<vecOfCandidates.size();i++){\n          c=vecOfCandidates[i];\n          if(std::find(vecOfOccupiedNodes.begin(), vecOfOccupiedNodes.end(), c) == vecOfOccupiedNodes.end()){\n            vecOfNeighbors=G.neighbors(c);\n            search=true;\n            l=0;\n            if((search)&&(l<vecOfNeighbors.size())){\n              w=vecOfNeighbors[l];\n              if(std::find(vecOfOccupiedNodes.begin(), vecOfOccupiedNodes.end(), w) != vecOfOccupiedNodes.end()){\n                search=false;\n              }\n              else{\n                l++;\n              }\n            }\n            if(search){\n              for(count j=0;j<vecOfNeighbors.size();j++){\n                w=vecOfNeighbors[j];\n                vecOfOccupiedNodes.push_back(w);\n              }\n              vecOfChosenNodes.push_back(c);\n            }\n          }\n        }\n        return vecOfChosenNodes;\n      }\n    /**************************************************************************\n    void CurrentFlowGroupCloseness::uncoarseEfffectiveResistanceDistanceMatrix(count ID){\n      bool search;\n      count l,j;\n      node c,s,w;\n      double edgeWeightcs,edgeWeightcw,edgeWeightsw;\n      std::vector<std::tuple<node,node,count,double,double,double>> vecOfTriangles;\n      std::tuple<node,node,count,double,double,double> triangle;\n\n      vecOfTriangles=LevelList[ID-1].getVecOfTriangles();\n      for(count i=0;i<vecOfTriangles.size();i++){\n        j=vecOfTriangles.size()-1-i;\n        triangle=vecOfTriangles[j];\n        ERD.uncoarseTriangle(vecOfNodes,triangle);\n        c=std::get<0>(triangle);\n        s=std::get<1>(triangle);\n        w=std::get<2>(triangle);\n        edgeWeightcs=std::get<3>(triangle);\n        edgeWeightcw=std::get<4>(triangle);\n        edgeWeightsw=1./edgeWeightcs+1./edgeWeightsw;\n        edgeWeightsw=1./edgeWeightsw;\n        //vecOfNodes.push_back(c);\n        //Adj[s].push_back (c);\n        //Adj[c].push_back(s);\n        if(std::get<4>(triangle)>0){\n          //Adj[c].push_back (w);\n          //Adj[w].push_back(c);\n        }\n        if(!(std::get<5>(triangle)==edgeWeightsw)){\n          search = true;\n          l= 0;\n          while((l<Adj[s].size())&&(search)){\n            if(Adj[s][l]==w){\n              Adj[s].erase(Adj[s].begin()+l);\n              search=false;\n            }\n            else{\n              l++;\n            }\n          }//end while\n          search = true;\n          l= 0;\n          while((l<Adj[w].size())&&(search)){\n            if(Adj[w][l]==s){\n                Adj[w].erase(Adj[w].begin()+l);\n                search=false;\n              }\n          else{\n            l++;\n          }\n          }//end while\n        }//end if\n        numberOfCoarsedNodes--;\n      }//end for\n    }\n    /***************************************************************************/\n    void CurrentFlowGroupCloseness::mergePeripheralNodes(){\n      bool search;\n      count l;\n      node c,s,w;\n      double edgeWeightcs,edgeWeightsw;\n      std::vector<node> vecOfNodes,vecOfSupernodes;\n      std::vector<double> vecOfWeights;\n      std::vector<std::pair<node,node>> mapping;\n\n      vecOfSupernodes.resize(0);\n      mapping.resize(0);\n      vecOfNodes=G.nodes();\n      vecOfWeights.resize(1);\n      for(count i=0;i<vecOfNodes.size();i++){\n        c=vecOfNodes[i];\n        if(G.degree(c)==1){\n          s=G.randomNeighbor(c);\n          if(std::find(vecOfSupernodes.begin(), vecOfSupernodes.end(), s) == vecOfSupernodes.end()){\n            vecOfSupernodes.push_back(s);\n            mapping.push_back (std::make_pair(s,c));\n            vecOfPeripheralNodes.push_back(c);\n          }\n          else{\n            search = true;\n            l= 0;\n            while(search){\n              if(vecOfSupernodes[l]==s){\n                w=mapping[l].second;\n                search=false;\n              }\n              l++;\n            }//end while\n            edgeWeightcs=G.weight(c,s);\n            edgeWeightsw=G.weight(s,w);\n            edgeWeightsw=edgeWeightcs+edgeWeightsw;\n            G.setWeight(s,w,edgeWeightsw);\n            vecOfWeights[0]=edgeWeightcs;\n            ERDLevel coarsed(c,G.neighbors(c),vecOfWeights);\n            coarsedNodes.push_back(coarsed);\n            G.removeNode(c);\n          }//end else\n        }\n      }\n    }\n    /***************************************************************************/\n    void CurrentFlowGroupCloseness::coarseGraph(std::vector<node> vecOfChosenNodes,count degree){\n      node c,s,w;\n      double edgeWeightcs,edgeWeightcw,edgeWeightsw;\n      std::vector<node> vecOfNeighbors;\n      std::vector<double> vecOfWeights;\n\n      vecOfWeights.resize(degree);\n      /*Path Coarsenening*/\n      if(degree==2){\n        for(count i=0;i<vecOfChosenNodes.size();i++){\n          c=vecOfChosenNodes[i];\n          vecOfNeighbors=G.neighbors(c);\n          s=vecOfNeighbors[0];\n          w=vecOfNeighbors[1];\n          edgeWeightcs=G.weight(c,s);\n          edgeWeightcw=G.weight(c,w);\n          edgeWeightsw=edgeWeightcs+edgeWeightcw;\n          /*Path Merge*/\n          if(G.weight(s,w)!=0){\n            edgeWeightsw=1./edgeWeightsw;\n            edgeWeightsw+=1./G.weight(s,w);\n            edgeWeightsw=1./edgeWeightsw;\n          }\n          G.setWeight(s,w,edgeWeightsw);\n          for(count j=0;j<vecOfNeighbors.size();j++){\n            vecOfWeights[j]=G.weight(c,vecOfNeighbors[j]);\n          }\n          ERDLevel coarsed(c,vecOfNeighbors,vecOfWeights);\n          G.removeNode(c);\n        }\n      }\n      /*Star*/\n      else{\n        for(count i=0;i<vecOfChosenNodes.size();i++){\n          c=vecOfChosenNodes[i];\n          computeStarCliqueWeights(c);\n          vecOfNeighbors=G.neighbors(c);\n          for(count j=0;j<vecOfNeighbors.size();j++){\n            vecOfWeights[j]=G.weight(c,vecOfNeighbors[j]);\n          }\n\t  //TODO: Here problem when creating coarsed for the second time\n          ERDLevel coarsed(c,vecOfNeighbors,vecOfWeights);\n          G.removeNode(c);\n        }\n      }\n    }\n\n    void CurrentFlowGroupCloseness::computeStarCliqueWeights(node c){\n      node v,w,x,y;\n      double S,S2,weight;\n      std::vector<node> vecOfNeighbors;\n\n      S=0.;\n      vecOfNeighbors=G.neighbors(c);\n      for(count i=0;i<vecOfNeighbors.size();i++){\n        v=vecOfNeighbors[i];\n        S2=0.;\n        for(count j=0;j<vecOfNeighbors.size();j++){\n          w=vecOfNeighbors[j];\n          if(w!=v){\n            S2*=G.weight(v,w);\n          }\n        }\n        S+=S2;\n      }\n      for(count i=0;i<vecOfNeighbors.size();i++){\n        v=vecOfNeighbors[i];\n        for(count j=0;j<vecOfNeighbors.size();j++){\n          w=vecOfNeighbors[j];\n          if(v!=w){\n            weight=0.;\n            for(count k=0;k<vecOfNeighbors.size();k++){\n              x=vecOfNeighbors[k];\n              if((x!=v)&&(x!=w)){\n                for(count l=0;l<vecOfNeighbors.size();l++){\n                  y=vecOfNeighbors[l];\n                  if((y!=v)&&(y!=w)&&(y!=x)){\n                    weight*=G.weight(x,y);\n                  }//if y\n                }//for y\n              }//if x\n            }//for x\n\t    //TODO: Here weight can be zero! Segfault when dividing with zero!!\n\t    // maria's example\n            if(weight > 0.)\n\t      weight = S/weight;\n\t    else weight = 1.; // not sure if you want it one here.\n\t    // maria's example\n\t    \n            if(G.weight(v,w)!=0){\n              weight=1./weight;\n              weight+=1./G.weight(v,w);\n              weight=1./weight;\n            }\n            G.setWeight(x,y,weight);\n          }// if w\n        }// for w\n      }// for v\n    }\n    arma::Mat<double> CurrentFlowGroupCloseness::computePinvOfLaplacian(){\n      node v,w;\n      count w_i;\n      double factor, weight;\n      std::vector<node> vecOfNodes, vecOfNeighbours;\n      std::vector<count> reverse;\n      vecOfNodes=G.nodes();\n      arma::Mat<double> L(G.numberOfNodes(),G.numberOfNodes());\n      L.zeros();\n      reverse.resize(G.upperNodeIdBound());\n      for(count i=0;i<vecOfNodes.size();i++){\n        reverse[vecOfNodes[i]]=i;\n      }\n      for(count i=0;i<G.numberOfNodes();i++){\n        v=vecOfNodes[i];\n        vecOfNeighbours=G.neighbors(v);\n        for(count j=0;j<vecOfNeighbours.size();j++){\n          w=vecOfNeighbours[j];\n          w_i=reverse[w];\n          weight=G.weight(v,w);\n          L(i,w_i)=-weight;\n          L(i,i)+=weight;\n        }\n      }\n      arma::Mat<double> J(L.n_rows,L.n_rows);\n      factor=1./(double)(L.n_rows);\n      J.fill(factor);\n      L= L-J;\n      L=arma::inv(L);\n      L= L+J;\n      return L;\n    }\n} /* namespace NetworKit*/\n", "meta": {"hexsha": "9104d73845283b1aa41b4f630db4df72b059f8b7", "size": 19281, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "networkit/cpp/centrality/CurrentFlowGroupCloseness.cpp", "max_stars_repo_name": "gstoszek/networkit", "max_stars_repo_head_hexsha": "5f4e7b9a0f8a431465911209d41e0c73f9bf0df0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "networkit/cpp/centrality/CurrentFlowGroupCloseness.cpp", "max_issues_repo_name": "gstoszek/networkit", "max_issues_repo_head_hexsha": "5f4e7b9a0f8a431465911209d41e0c73f9bf0df0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "networkit/cpp/centrality/CurrentFlowGroupCloseness.cpp", "max_forks_repo_name": "gstoszek/networkit", "max_forks_repo_head_hexsha": "5f4e7b9a0f8a431465911209d41e0c73f9bf0df0", "max_forks_repo_licenses": ["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.0720411664, "max_line_length": 137, "alphanum_fraction": 0.5219127639, "num_tokens": 4898, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6584175139669998, "lm_q2_score": 0.5039061705290805, "lm_q1q2_score": 0.3317806480723882}}
{"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 \"ray_intersection_observation_equation_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\nstd::vector<Eigen::Affine3d> bundle_of_rays;\nEigen::Vector3d intersection(0,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\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) * 2;\n\t\tpose.fi = ((float(rand()%1000000))/1000000.0f - 0.5) * 2;\n\t\tpose.ka = ((float(rand()%1000000))/1000000.0f - 0.5) * 2;\n\n\t\tbundle_of_rays.push_back(affine_matrix_from_pose_tait_bryan(pose));\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(\"bundle_of_rays_intersection\");\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(0,1,0);\n\tglBegin(GL_LINES);\n\tfor(size_t i = 0; i < bundle_of_rays.size(); i++){\n\t\tEigen::Vector3d z_begin(0, 0,-100);\n\t\tEigen::Vector3d z_end(0, 0, 100);\n\n\t\tEigen::Vector3d z_begin_t = bundle_of_rays[i] * z_begin;\n\t\tEigen::Vector3d z_end_t = bundle_of_rays[i] * z_end;\n\n\t\tglVertex3f(z_begin_t.x(), z_begin_t.y(), z_begin_t.z());\n\t\tglVertex3f(z_end_t.x(), z_end_t.y(), z_end_t.z());\n\t}\n\tglEnd();\n\n\tglPointSize(10);\n\tglColor3f(1,0,0);\n\tglBegin(GL_POINTS);\n\tglVertex3f(intersection.x(), intersection.y(), intersection.z());\n\tglEnd();\n\tglPointSize(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 < bundle_of_rays.size(); i++){\n\t\t\t\tEigen::Vector3d vx(bundle_of_rays[i](0,0), bundle_of_rays[i](1,0), bundle_of_rays[i](2,0));\n\t\t\t\tEigen::Vector3d vy(bundle_of_rays[i](0,1), bundle_of_rays[i](1,1), bundle_of_rays[i](2,1));\n\n\t\t\t\tEigen::Matrix<double, 2, 1> delta;\n\t\t\t\tray_intersection_observation_equation(delta,\n\t\t\t\t\t\tintersection.x(), intersection.y(), intersection.z(),\n\t\t\t\t\t\tbundle_of_rays[i](0,3), bundle_of_rays[i](1,3), bundle_of_rays[i](2,3),\n\t\t\t\t\t\tvx.x(), vx.y(), vx.z(), vy.x(), vy.y(), vy.z());\n\t\t\t\tEigen::Matrix<double, 2, 3> delta_jacobian;\n\t\t\t\tray_intersection_observation_equation_jacobian(delta_jacobian,\n\t\t\t\t\t\tintersection.x(), intersection.y(), intersection.z(),\n\t\t\t\t\t\tbundle_of_rays[i](0,3), bundle_of_rays[i](1,3), bundle_of_rays[i](2,3),\n\t\t\t\t\t\tvx.x(), vx.y(), vx.z(), vy.x(), vy.y(), vy.z());\n\n\t\t\t\tint ir = tripletListB.size();\n\t\t\t\ttripletListA.emplace_back(ir, 0, -delta_jacobian(0,0));\n\t\t\t\ttripletListA.emplace_back(ir, 1, -delta_jacobian(0,1));\n\t\t\t\ttripletListA.emplace_back(ir, 2, -delta_jacobian(0,2));\n\t\t\t\ttripletListA.emplace_back(ir + 1, 0, -delta_jacobian(1,0));\n\t\t\t\ttripletListA.emplace_back(ir + 1, 1, -delta_jacobian(1,1));\n\t\t\t\ttripletListA.emplace_back(ir + 1, 2, -delta_jacobian(1,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\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}\n\n\t\t\tEigen::SparseMatrix<double> matA(tripletListB.size(), 3);\n\t\t\tEigen::SparseMatrix<double> matP(tripletListB.size(), tripletListB.size());\n\t\t\tEigen::SparseMatrix<double> matB(tripletListB.size(), 1);\n\n\t\t\tmatA.setFromTriplets(tripletListA.begin(), tripletListA.end());\n\t\t\tmatP.setFromTriplets(tripletListP.begin(), tripletListP.end());\n\t\t\tmatB.setFromTriplets(tripletListB.begin(), tripletListB.end());\n\n\t\t\tEigen::SparseMatrix<double> AtPA(3, 3);\n\t\t\tEigen::SparseMatrix<double> AtPB(3, 1);\n\n\t\t\t{\n\t\t\tEigen::SparseMatrix<double> AtP = matA.transpose() * matP;\n\t\t\tAtPA = (AtP) * matA;\n\t\t\tAtPB = (AtP) * matB;\n\t\t\t}\n\n\t\t\ttripletListA.clear();\n\t\t\ttripletListP.clear();\n\t\t\ttripletListB.clear();\n\n\n\t\t\tstd::cout << \"AtPA.size: \" << AtPA.size() << std::endl;\n\t\t\tstd::cout << \"AtPB.size: \" << AtPB.size() << std::endl;\n\n\t\t\tstd::cout << \"start solving AtPA=AtPB\" << std::endl;\n\t\t\tEigen::SimplicialCholesky<Eigen::SparseMatrix<double>> solver(AtPA);\n\n\t\t\tstd::cout << \"x = solver.solve(AtPB)\" << std::endl;\n\t\t\tEigen::SparseMatrix<double> x = solver.solve(AtPB);\n\n\t\t\tstd::vector<double> h_x;\n\n\t\t\tfor (int k=0; k<x.outerSize(); ++k){\n\t\t\t\tfor (Eigen::SparseMatrix<double>::InnerIterator it(x,k); it; ++it){\n\t\t\t\t\th_x.push_back(it.value());\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif(h_x.size() == 3){\n\t\t\t\tfor(size_t i = 0 ; i < h_x.size(); i++){\n\t\t\t\t\tstd::cout << h_x[i] << std::endl;\n\t\t\t\t}\n\t\t\t\tstd::cout << \"AtPA=AtPB SOLVED\" << std::endl;\n\t\t\t\tstd::cout << \"update\" << std::endl;\n\n\t\t\t\tintersection.x() += h_x[0];\n\t\t\t\tintersection.y() += h_x[1];\n\t\t\t\tintersection.z() += h_x[2];\n\t\t\t}else{\n\t\t\t\tstd::cout << \"AtPA=AtPB FAILED\" << std::endl;\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t\tcase 'n':{\n\t\t\tfor(size_t i = 0; i < bundle_of_rays.size(); i++){\n\t\t\t\tTaitBryanPose pose;\n\n\t\t\t\tpose.px = ((float(rand()%1000000))/1000000.0f - 0.5) * 2.0 * 0.01;\n\t\t\t\tpose.py = ((float(rand()%1000000))/1000000.0f - 0.5) * 2.0 * 0.01;\n\t\t\t\tpose.pz = ((float(rand()%1000000))/1000000.0f - 0.5) * 2.0 * 0.01;\n\n\t\t\t\tpose.om = ((float(rand()%1000000))/1000000.0f - 0.5) * 2;\n\t\t\t\tpose.fi = ((float(rand()%1000000))/1000000.0f - 0.5) * 2;\n\t\t\t\tpose.ka = ((float(rand()%1000000))/1000000.0f - 0.5) * 2;\n\n\t\t\t\tbundle_of_rays[i] = bundle_of_rays[i] * affine_matrix_from_pose_tait_bryan(pose);\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 rays\" << std::endl;\n\tstd::cout << \"t: optimize\" << std::endl;\n}\n", "meta": {"hexsha": "2c05c8af21d96160cc25ccc939683eb70cc44b52", "size": 8356, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "codes/c++Examples/src/bundle_of_rays_intersection.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/bundle_of_rays_intersection.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/bundle_of_rays_intersection.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": 27.9464882943, "max_line_length": 95, "alphanum_fraction": 0.647438966, "num_tokens": 2951, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6584175139669998, "lm_q2_score": 0.5039061705290805, "lm_q1q2_score": 0.3317806480723882}}
{"text": "#ifndef SIMPLE_SHORTEST_BASIS_HPP\n#define SIMPLE_SHORTEST_BASIS_HPP 1\n/**\n * @file simple_shortest_basis.hpp\n *\n * @brief calculate equidistribution property of the random number generator.\n *\n * calculate shortest basis of lattice. We can get the dimension of\n * equidistribution from the smallest norm of the vectors in lattice\n * basis.\n *\n * @author Mutsuo Saito (Hiroshima University)\n * @author Makoto Matsumoto (The University of Tokyo)\n *\n * Copyright (C) 2011 Mutsuo Saito, Makoto Matsumoto and\n * Hiroshima University. All rights reserved.\n *\n * The 3-clause BSD License is applied to this software, see\n * LICENSE.txt\n */\n#include <tr1/memory>\n#include <stdexcept>\n#include <NTL/GF2.h>\n\nnamespace MTToolBox {\n    /**\n     * @class linear_generator_vector\n     * @brief a pseudo random number generator as a vector\n     *\n     * This class is a pseudo random number\n     * generator as a vector (and polynomial).  As a polynomial, Only\n     * multiple by \\b x is supported.\n     *\n     * @tparam G F2-linear generator\n     * @tparam T the output type of \\b G.\n     */\n    template<typename G, typename T> class linear_generator_vector {\n    public:\n        /**\n         * constructor\n         *\n         * @param rand_ random number generator whose state transition\n         * function is F<sub>2</sub>-linear.\n         */\n        linear_generator_vector<G, T>(const G& rand_) {\n            using namespace std::tr1;\n            shared_ptr<G> r(new G(rand_));\n            rand = r;\n            rand->seeding(1);\n            count = 0;\n            zero = false;\n            next = 0;\n        }\n\n        /**\n         * constructor of a vector in standard basis\n         *\n         * @param rand_ random number generator used as a template\n         * @param bit_pos position of 1 for standard basis.\n         */\n        linear_generator_vector<G, T>(const G& rand_, int bit_pos) {\n            using namespace std::tr1;\n            shared_ptr<G> r(new G(rand_));\n            rand = r;\n            rand->make_zero_status();\n            count = 0;\n            zero = false;\n            next = static_cast<T>(1) << (sizeof(T) * 8 - bit_pos - 1);\n        }\n\n        void add(const linear_generator_vector<G, T>& src);\n        void next_state(int bit_len);\n        void debug_print();\n\n        /**\n         * a pseudo random number generator whose state transition\n         * function is F<sub>2</sub>-linear.\n         */\n        std::tr1::shared_ptr<G> rand;\n\n        /**\n         * The counter which shows how many times next_state() is called.\n         * This is concerned with norm of vector and degree of polynomial.\n         */\n        int count;\n\n        /**\n         * This shows the vector is zero or not.\n         */\n        bool zero;\n\n        /**\n         * This is important.\n         * v-bit MSBs of generator's recent output.\n         * Or, the coefficent of highest degree term of polynomial.\n         */\n        T next;\n    };\n\n    /**\n     * @class shotest_basis\n     * @brief calculate shortest basis of lattice\n     *\n     * This class calculates shortest basis of lattice,\n     * or equidistribution properties of random number generators.\n     * This class is most complex part of this system.\n     *\n     * @tparam G a linear generator vector\n     * @tparam T output type of the generator\n     */\n    template<typename G, typename T> class shortest_basis {\n        typedef linear_generator_vector<G, T> linear_vec;\n    public:\n        /**\n         * constructor\n         *\n         * @param rand a pseudo random number generator whose state\n         * transition function is F<sub>2</sub>-linear.\n         * @param bit_len_ from \\b bit_len to 1 of dimensions of\n         * equidistribution with v-bit accuracy are calculated.\n         */\n        shortest_basis(const G& rand, int bit_len_) {\n            bit_len = bit_len_;\n            size = bit_len + 1;\n            basis = new linear_vec * [size];\n            mexp = rand.get_mexp();\n            for (int i = 0; i < bit_len; i++) {\n                basis[i] = new linear_vec(rand, i);\n            }\n            basis[bit_len] = new linear_vec(rand);\n            basis[bit_len]->next_state(bit_len);\n        }\n        /**\n         * The destructor.\n         */\n        ~shortest_basis() {\n            for (int i = 0; i < size; i++) {\n                delete basis[i];\n            }\n            delete[] basis;\n        }\n\n        int get_all_equidist(int veq[]);\n        int get_equidist(int *sum_equidist);\n    private:\n        int get_equidist_main(int bit_len);\n        void adjust(int new_len);\n        /** basis of lattice plus one vector */\n        linear_vec **basis;\n        /** bit lenght count from MSB */\n        int bit_len;\n        /** Mersenne Exponent, or max value of the dimension of\n         * equidistribution. */\n        int mexp;\n        /** */\n        int size;\n    };\n\n    /**\n     * Adjust bit_len and recalculate the coefficient of the highest\n     * degree term.\n     *\n     * @param new_len a bit length to be changed to.\n     */\n    template<typename G, typename T>\n    void shortest_basis<G, T>::adjust(int new_len) {\n        using namespace std;\n\n        T mask = (~static_cast<T>(0)) << (sizeof(T) * 8 - new_len);\n#if 0\n        if (basis[basis.size() - 1]->zero) {\n            basis.erase(basis.begin() + basis.size() - 1);\n        } else {\n            cerr << \"no zero state\" << endl;\n            throw new logic_error(\"no zero state\");\n        }\n#endif\n        for (int i = 0; i < size; i++) {\n            basis[i]->next = basis[i]->next & mask;\n            if (basis[i]->next == 0) {\n                basis[i]->next_state(new_len);\n            }\n        }\n    }\n\n    /**\n     * print some information for debug.\n     */\n    template<typename G, typename T>\n    void linear_generator_vector<G, T>::debug_print() {\n        using namespace std;\n\n        cout << \"debug ====\" << endl;\n        cout << \"count = \" << dec << count << endl;\n        cout << \"zero = \" << zero << endl;\n        cout << \"next = \" << hex << next << endl;\n        cout << \"debug ====\" << endl;\n        //rand->debug_print();\n    }\n\n    /**\n     * calculate the dimensions of equidistribution with v-bit\n     * accuracy, where v is form 1 to \\b bit_len\n     *\n     * @param[out] veq array of dimensions of equidistribution at v\n     * @return sum of the differences between the theoretical\n     * upper bounds and the dimensions.\n     */\n    template<typename G, typename T>\n    int shortest_basis<G, T>::get_all_equidist(int veq[]) {\n        using namespace std;\n\n        int sum = 0;\n\n        veq[bit_len - 1] = get_equidist_main(bit_len);\n#ifdef DEBUG\n        for (int i = 0; i < size; i++) {\n            basis[i]->debug_print();\n        }\n#endif\n        sum += mexp / bit_len - veq[bit_len - 1];\n        bit_len--;\n        for (; bit_len >= 1; bit_len--) {\n            adjust(bit_len);\n            veq[bit_len - 1] = get_equidist_main(bit_len);\n            sum += mexp / bit_len - veq[bit_len - 1];\n        }\n        return sum;\n    }\n\n    /**\n     * calculate the dimension of equidistribution with \\b bit_len\n     * accuracy, and additionally sum of the differences between the\n     * theoretical upper bounds and veqs from veq is 1 to \\b bit_len -1\n     *\n     * @param sum_equidist sum of the differences\n     * @return the dimension of equidistribution at \\b bit_len\n     */\n    template<typename G, typename T>\n    int shortest_basis<G, T>::get_equidist(int *sum_equidist) {\n        using namespace std;\n\n        int veq = get_equidist_main(bit_len);\n        int sum = 0;\n        bit_len--;\n        for (; bit_len >= 1; bit_len--) {\n            adjust(bit_len);\n            sum += mexp / bit_len - get_equidist_main(bit_len);\n        }\n        *sum_equidist = sum;\n        return veq;\n    }\n\n    /**\n     * addition of vectors\n     * @param src a vector which is added to this.\n     */\n    template<typename G, typename T>\n    void linear_generator_vector<G, T>::add(\n        const linear_generator_vector<G, T>& src) {\n        using namespace std;\n\n        rand->add(*src.rand);\n        next ^= src.next;\n    }\n\n    /**\n     * transfer to the next state or n-th next state so that the\n     * coeffcient of the maximum degree term should be non-zero. If internal\n     * state is all zero, then set zero flag.\n     *\n     * @param bit_len bit length from MSB\n     */\n    template<typename G, typename T>\n    void linear_generator_vector<G, T>::next_state(int bit_len) {\n        using namespace std;\n\n        if (zero) {\n            return;\n        }\n        int zero_count = 0;\n        next = rand->generate(bit_len);\n        count++;\n        while (next == 0) {\n            zero_count++;\n            if (zero_count > rand->get_mexp() * 2) {\n                zero = true;\n                if (rand->is_zero()) {\n                    zero = true;\n                }\n                break;\n            }\n            next = rand->generate(bit_len);\n            count++;\n        }\n    }\n\n    /**\n     * Calculate dimension of equidistirbution with v bit accuracy for\n     * one v.\n     *\n     * In this function, \\b pivot_index is a important variable.  \\b\n     * pivot_index shows the position of the first bit which is one in\n     * \\b next of the vector of the last element of \\b basis. And all\n     * vectors in \\b basis but last are sorted by pivot_index, so the\n     * pivot_index of a vector of \\b basis[0] is zero.\n     *\n     * @param bit_len bit length from MSB, so bit_Len is v.\n     */\n    template<typename G, typename T>\n    int shortest_basis<G, T>::get_equidist_main(int bit_len) {\n        using namespace std;\n        using namespace NTL;\n\n        int pivot_index;\n        int old_pivot = 0;\n\n        pivot_index = calc_1pos(basis[bit_len]->next);\n        while (!basis[bit_len]->zero) {\n#ifdef DEBUG\n            if (pivot_index != calc_1pos(basis[pivot_index]->next)) {\n                cerr << \"pivot error 1\" << endl;\n                cerr << \"pivot_index:\" << dec << pivot_index << endl;\n                cerr << \"calc_1pos:\" << dec\n                     << calc_1pos(basis[pivot_index]->next) << endl;\n                cerr << \"next:\" << hex << basis[pivot_index]->next << endl;\n                throw new std::logic_error(\"pivot error 1\");\n            }\n#endif\n            if (basis[bit_len]->count > basis[pivot_index]->count) {\n                swap(basis[bit_len], basis[pivot_index]);\n            }\n            basis[bit_len]->add(*basis[pivot_index]);\n            if (basis[bit_len]->next == 0) {\n                basis[bit_len]->next_state(bit_len);\n                pivot_index = calc_1pos(basis[bit_len]->next);\n            } else {\n                old_pivot = pivot_index;\n                pivot_index = calc_1pos(basis[bit_len]->next);\n                if (old_pivot <= pivot_index) {\n                    cerr << \"pivot error 2\" << endl;\n                    throw new std::logic_error(\"pivot error 2\");\n                }\n            }\n        }\n        int min_count = basis[0]->count;\n        for (int i = 1; i < bit_len; i++) {\n            if (min_count > basis[i]->count) {\n                min_count = basis[i]->count;\n            }\n        }\n        if (min_count > mexp / bit_len) {\n            cout << \"over theoretical bound \" << bit_len << endl;\n            for(int i = 0; i < size; i++) {\n                basis[i]->debug_print();\n            }\n            throw new std::logic_error(\"over theoretical bound\");\n        }\n        return min_count;\n    }\n}\n//  LocalWords:  equidistribution param endl NTL\n#endif\n\n", "meta": {"hexsha": "ff0df2c81d96ccd9d9ecb00fa11a74bff9b53d15", "size": 11518, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "3rdparty/tinymt/dc/include/simple_shortest_basis.hpp", "max_stars_repo_name": "mwbrown/circa", "max_stars_repo_head_hexsha": "425b4a3042addab813447813cc45888a012b2c2e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 175.0, "max_stars_repo_stars_event_min_datetime": "2015-04-24T05:51:53.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T10:07:45.000Z", "max_issues_repo_path": "3rdparty/tinymt/dc/include/simple_shortest_basis.hpp", "max_issues_repo_name": "mwbrown/circa", "max_issues_repo_head_hexsha": "425b4a3042addab813447813cc45888a012b2c2e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 9.0, "max_issues_repo_issues_event_min_datetime": "2016-04-04T08:15:43.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-06T00:04:20.000Z", "max_forks_repo_path": "3rdparty/tinymt/dc/include/simple_shortest_basis.hpp", "max_forks_repo_name": "mwbrown/circa", "max_forks_repo_head_hexsha": "425b4a3042addab813447813cc45888a012b2c2e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 34.0, "max_forks_repo_forks_event_min_datetime": "2015-09-08T20:37:31.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-17T09:47:04.000Z", "avg_line_length": 31.5561643836, "max_line_length": 77, "alphanum_fraction": 0.5433234937, "num_tokens": 2780, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.658417500561683, "lm_q2_score": 0.5039061705290805, "lm_q1q2_score": 0.3317806413173664}}
{"text": "#ifndef ODEINT_ANYODE_H_6D2AAAD4880011E6AC5C734FA77443A3\n#define ODEINT_ANYODE_H_6D2AAAD4880011E6AC5C734FA77443A3\n\n#include <limits>\n#include <string>\n#include <unordered_map>\n#include <chrono>\n#include <iostream>\n#include <sstream>\n#include <vector>\n\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/odeint.hpp>\n\n#include <anyode/anyode.hpp>\n\n\n#if !defined(PYODEINT_NO_BOOST_CHECK)\n  #if BOOST_VERSION / 100000 == 1\n    #if BOOST_VERSION / 100 % 1000 == 60\n      #error \"Boost v 1.60 has a bug in rosenbrock stepper (see https://github.com/headmyshoulder/odeint-v2/issues/189) set PYODEINT_NO_BOOST_CHECK to ignore\"\n    #endif\n    #if BOOST_VERSION / 100 % 1000 == 61\n      #error \"Boost v 1.61 has a bug in rosenbrock stepper (see https://github.com/headmyshoulder/odeint-v2/issues/189) set PYODEINT_NO_BOOST_CHECK to ignore\"\n    #endif\n    #if BOOST_VERSION / 100 % 1000 == 62\n      #error \"Boost v 1.62 has a bug in rosenbrock stepper (see https://github.com/headmyshoulder/odeint-v2/issues/189) set PYODEINT_NO_BOOST_CHECK to ignore\"\n    #endif\n  #endif\n#endif\n\nnamespace {\n    class StreamFmt\n    {\n        std::stringstream m_s;\n    public:\n        StreamFmt() {}\n        ~StreamFmt() {}\n\n        template <typename T>\n        StreamFmt& operator << (const T& v) {\n            this->m_s << v;\n            return *this;\n        }\n\n        std::string str() const {\n            return this->m_s.str();\n        }\n        operator std::string() const {\n            return this->m_s.str();\n        }\n\n    };\n}\n\n\nnamespace odeint_anyode{\n    using namespace std::placeholders;\n\n    using boost::numeric::odeint::integrate_adaptive;\n    using boost::numeric::odeint::make_dense_output;\n    using boost::numeric::odeint::rosenbrock4;\n    using boost::numeric::odeint::runge_kutta_dopri5;\n    using boost::numeric::odeint::bulirsch_stoer_dense_out;\n\n    // value_type is hardcoded to double at the moment\n    using value_type = double;\n    using vector_type = boost::numeric::ublas::vector<value_type>;\n    using matrix_type = boost::numeric::ublas::matrix<value_type>;\n\n    // using OdeSys_t = AnyODE::OdeSysBase;\n\n    enum class StepType : int { bulirsch_stoer, rosenbrock4, dopri5 };\n\n    StepType styp_from_name(std::string name){\n        if (name == \"bulirsch_stoer\")\n            return StepType::bulirsch_stoer;\n        else if (name == \"rosenbrock4\")\n            return StepType::rosenbrock4;\n        else if (name == \"dopri5\")\n            return StepType::dopri5;\n        else\n            throw std::runtime_error(StreamFmt() << \"Unknown stepper type name: \" << name);\n    }\n\n    bool requires_jacobian(StepType styp){\n        if (styp == StepType::rosenbrock4)\n            return true;\n        else\n            return false;\n    }\n\n    vector_type vec_from_ptr(const value_type * const arr, std::size_t len){\n        vector_type vec(len);\n        for (std::size_t i=0; i<len; ++i)\n            vec[i] = arr[i];\n        return vec;\n    }\n\n\n    // Integr will be specialzed for: rosenbrock, dopri5 and bulrisch-stoer\n    // adaptive and predefined cannot be put here since make_dense_output\n    // is a function and bulirsch_stoer_dense_out is a class\n    template<class OdeSys>\n    struct Integr {\n        OdeSys * m_odesys;\n        double m_time_cpu = -1.0, m_time_wall = -1.0;\n        value_type m_dx0, m_dx_max, m_atol, m_rtol;\n        StepType m_styp;\n        long int m_mxsteps;\n        int m_autorestart;\n        long int m_nsteps;\n        bool m_return_on_error;\n\n        void rhs(const vector_type &yarr, vector_type &dydx, value_type xval);\n        void jac(const vector_type & yarr, matrix_type &Jmat,\n                 const value_type & xval, vector_type &dfdx);\n        Integr(OdeSys * odesys, value_type dx0, value_type dx_max, value_type atol, value_type rtol, StepType styp,\n               long int mxsteps, int autorestart=0, bool return_on_error=false) :\n            m_odesys(odesys), m_dx0(dx0), m_dx_max(dx_max), m_atol(atol), m_rtol(rtol), m_styp(styp),\n            m_mxsteps(mxsteps), m_autorestart(autorestart), m_return_on_error(return_on_error) {}\n\n        std::pair<std::vector<value_type>, std::vector<value_type> >\n        adaptive(const value_type x0,\n                 const value_type xend,\n                 const value_type * const ANYODE_RESTRICT y0){\n            std::time_t cputime0 = std::clock();\n            auto t_start = std::chrono::high_resolution_clock::now();\n            std::pair<std::vector<value_type>, std::vector<value_type> > result;\n            try{\n                if ( m_styp == StepType::bulirsch_stoer ) {\n                    this->adaptive_bulirsch_stoer(x0, xend, y0);\n                } else if ( m_styp == StepType::dopri5 ) {\n                    this->adaptive_dopri5(x0, xend, y0);\n                } else if ( m_styp == StepType::rosenbrock4 ) {\n                    this->adaptive_rosenbrock4(x0, xend, y0);\n                } else {\n                    goto impossible_adaptive;\n                }\n            } catch (const std::exception& e) {\n                if (m_autorestart > 0){\n                    std::cerr << e.what() << std::endl;\n                    if (this->m_xout.size() > 0){\n                        std::cerr << \"odeint_anyode.hpp:\" << __LINE__ << \": Autorestart (\" << m_autorestart\n                                  << \") x=\" << this->m_xout.back() << \"\\n\";\n                        m_autorestart--;\n                        auto c_nsteps = this->m_nsteps;\n                        auto c_xout = this->m_xout;\n                        auto c_yout = this->m_yout;\n                        adaptive(c_xout.back(), xend, &c_yout[c_yout.size() - m_odesys->get_ny()]);\n                        c_xout.insert(c_xout.end(), m_xout.begin(), m_xout.end());\n                        c_yout.insert(c_yout.end(), m_yout.begin(), m_yout.end());\n                        m_xout = c_xout;\n                        m_yout = c_yout;\n                        m_nsteps += c_nsteps;\n                    } else {\n                        std::cerr << \"odeint_anyode.hpp:\" << __LINE__ << \": Autorestart failed.\" << \"\\n\";\n                        if (!m_return_on_error)\n                            throw;\n                    }\n                } else {\n                    if (!m_return_on_error)\n                        throw;\n                }\n            }\n            this->m_time_cpu = (std::clock() - cputime0) / (double)CLOCKS_PER_SEC;\n            this->m_time_wall = std::chrono::duration<double>(\n                std::chrono::high_resolution_clock::now() - t_start).count();\n            return std::make_pair(this->m_xout, this->m_yout);\n        impossible_adaptive:\n            throw std::runtime_error(\"Impossible: unknown StepType!\");\n        }\n\n        int predefined(const int nx,\n                       const value_type * const ANYODE_RESTRICT xout,\n                       const value_type * const ANYODE_RESTRICT y0,\n                       value_type * const ANYODE_RESTRICT yout){\n            int nreached;\n            std::time_t cputime0 = std::clock();\n            auto t_start = std::chrono::high_resolution_clock::now();\n            std::copy(y0, y0 + (this->m_odesys->get_ny()), yout);\n            try {\n                if ( m_styp == StepType::bulirsch_stoer ) {\n                    this->predefined_bulirsch_stoer(nx, xout, y0, yout, &nreached);\n                } else if ( m_styp == StepType::dopri5 ) {\n                    this->predefined_dopri5(nx, xout, y0, yout, &nreached);\n                } else if ( m_styp == StepType::rosenbrock4 ) {\n                    this->predefined_rosenbrock4(nx, xout, y0, yout, &nreached);\n                } else {\n                    goto impossible_predefined;\n                }\n            } catch (const std::exception& e) {\n                if (m_autorestart > 0){\n                    std::cerr << e.what() << std::endl;\n                    if (this->m_xout.size() > 0) {\n                        std::cerr << \"odeint_anyode.hpp:\" << __LINE__ << \": Autorestart (\" << m_autorestart\n                                  << \") x=\" << this->m_xout.back() << \"\\n\";\n                        m_autorestart--;\n                        auto c_nsteps = this->m_nsteps;\n                        nreached += predefined(nx - nreached, xout + nreached,\n                                               yout + nreached*m_odesys->get_ny(),\n                                               yout + nreached*m_odesys->get_ny());\n                        this->m_nsteps += c_nsteps;\n                    } else {\n                        std::cerr << \"odeint_anyode.hpp:\" << __LINE__ << \": Autorestart failed.\" << \"\\n\";\n                        if (!m_return_on_error)\n                            throw;\n                    }\n                } else {\n                    if (!m_return_on_error)\n                        throw;\n                }\n            }\n            this->m_time_cpu = (std::clock() - cputime0) / (double)CLOCKS_PER_SEC;\n            this->m_time_wall = std::chrono::duration<double>(\n                std::chrono::high_resolution_clock::now() - t_start).count();\n            return nreached;\n        impossible_predefined:\n            throw std::runtime_error(\"Impossible: unknown StepType!\");\n        }\n    private:\n        std::vector<value_type> m_xout, m_yout;\n\n        void reset() {\n            this->m_nsteps = 0;\n            this->m_xout.clear();\n            this->m_yout.clear();\n        }\n\n        void obs_adaptive(const vector_type &yarr, value_type xval){\n            this->m_xout.push_back(xval);\n            for(int i=0 ; i < this->m_odesys->get_ny() ; ++i)\n                this->m_yout.push_back(yarr[i]);\n            if (this->m_nsteps == this->m_mxsteps)\n                throw std::runtime_error(StreamFmt() << \"Maximum number of steps reached: \" << this->m_nsteps);\n            m_nsteps++;\n        }\n\n        void obs_predefined(const vector_type & /* yarr */, value_type /* xval */){\n            if (this->m_nsteps == this->m_mxsteps)\n                throw std::runtime_error(StreamFmt() << \"Maximum number of steps reached: \" << this->m_nsteps);\n            m_nsteps++;\n        }\n\n        void adaptive_bulirsch_stoer(const value_type x0,\n                                     const value_type xend,\n                                     const value_type * const ANYODE_RESTRICT y0\n                                     ){\n            const int ny = this->m_odesys->get_ny();\n            auto f = [&](const vector_type &yarr, vector_type &dydx, value_type xval) {\n                this->m_odesys->rhs(xval, &(yarr.data()[0]), &(dydx.data()[0]));\n            };\n            auto stepper = bulirsch_stoer_dense_out< vector_type, value_type >(\n                this->m_atol, this->m_rtol, 1.0, 1.0, this->m_dx_max);\n            auto y_ = vec_from_ptr(y0, ny);\n            this->reset();\n            integrate_adaptive(stepper, f, y_, x0, xend, this->m_dx0,\n                               std::bind(&Integr::obs_adaptive, this, _1, _2));\n        }\n\n        void predefined_bulirsch_stoer(const int nx,\n                                       const value_type * const ANYODE_RESTRICT xout,\n                                       const value_type * const ANYODE_RESTRICT y0,\n                                       value_type * const ANYODE_RESTRICT yout,\n                                       int * nreached){\n            *nreached = 0;\n            const auto ny = this->m_odesys->get_ny();\n            vector_type y_ = vec_from_ptr(y0, ny);\n            vector_type xout_ = vec_from_ptr(xout, nx);\n            auto f = [&](const vector_type &yarr, vector_type &dydx, value_type xval) {\n                this->m_odesys->rhs(xval, &(yarr.data()[0]), &(dydx.data()[0]));\n            };\n            try{\n                auto stepper = bulirsch_stoer_dense_out< vector_type, value_type >(\n                    this->m_atol, this->m_rtol, 1.0, 1.0, this->m_dx_max);\n                for (*nreached=1; *nreached < nx; ++*nreached){\n                    const int ix = *nreached;\n                    this->reset();\n                    integrate_adaptive(stepper, f, y_, xout[ix-1], xout[ix], this->m_dx0,\n                                       std::bind(&Integr::obs_predefined, this, _1, _2));\n                    for (int iy=0; iy < ny; ++iy)\n                        yout[ix*ny + iy] = y_[iy];\n                }\n            } catch (const std::exception& e) {\n                std::cerr << __FILE__ << \":\" << __LINE__ << \":\";\n                std::cerr << e.what() << std::endl;\n                nreached--;\n                if (!m_return_on_error)\n                    throw;\n            }\n        }\n\n        void adaptive_dopri5(const value_type x0,\n                             const value_type xend,\n                             const value_type * const ANYODE_RESTRICT y0){\n            const int ny = this->m_odesys->get_ny();\n            auto f = [&](const vector_type &yarr, vector_type &dydx, value_type xval) {\n                this->m_odesys->rhs(xval, &(yarr.data()[0]), &(dydx.data()[0]));\n            };\n\n            auto stepper = make_dense_output<runge_kutta_dopri5<vector_type, value_type> >(\n                this->m_atol, this->m_rtol, this->m_dx_max);\n            auto y_ = vec_from_ptr(y0, ny);\n            this->reset();\n            integrate_adaptive(stepper, f, y_, x0, xend, this->m_dx0,\n                               std::bind(&Integr::obs_adaptive, this, _1, _2));\n        }\n\n        void predefined_dopri5(const int nx,\n                               const value_type * const ANYODE_RESTRICT xout,\n                               const value_type * const ANYODE_RESTRICT y0,\n                              value_type * const ANYODE_RESTRICT yout,\n                              int * nreached){\n            *nreached = 0;\n            const auto ny = this->m_odesys->get_ny();\n            vector_type y_ = vec_from_ptr(y0, ny);\n            vector_type xout_ = vec_from_ptr(xout, nx);\n            auto f = [&](const vector_type &yarr, vector_type &dydx, value_type xval) {\n                this->m_odesys->rhs(xval, &(yarr.data()[0]), &(dydx.data()[0]));\n            };\n            try {\n                auto stepper = make_dense_output<runge_kutta_dopri5<vector_type, value_type> >(\n                    this->m_atol, this->m_rtol, this->m_dx_max);\n                for (*nreached=1; *nreached < nx; ++*nreached){\n                    const int ix = *nreached;\n                    this->reset();\n                    integrate_adaptive(stepper, f, y_, xout[ix - 1], xout[ix], this->m_dx0,\n                                       std::bind(&Integr::obs_predefined, this, _1, _2));\n                    for (int iy=0; iy < ny; ++iy)\n                        yout[ix*ny + iy] = y_[iy];\n                }\n            } catch (const std::exception& e) {\n                std::cerr << __FILE__ << \":\" << __LINE__ << \":\";\n                std::cerr << e.what() << std::endl;\n                nreached--;\n                if (!m_return_on_error)\n                    throw;\n            }\n        }\n\n        void adaptive_rosenbrock4(const value_type x0,\n                                  const value_type xend,\n                                  const value_type * const ANYODE_RESTRICT y0){\n            const int ny = this->m_odesys->get_ny();\n            auto f = [&](const vector_type &yarr, vector_type &dydx, value_type xval) {\n                this->m_odesys->rhs(xval, &(yarr.data()[0]), &(dydx.data()[0]));\n            };\n            auto j = [&](const vector_type & yarr, matrix_type &Jmat,\n                                     const value_type & xval, vector_type &dfdx) {\n                this->m_odesys->dense_jac_rmaj(xval, &(yarr.data()[0]), nullptr, &(Jmat.data()[0]), ny, &(dfdx.data()[0]));\n            };\n            auto stepper = make_dense_output<rosenbrock4<value_type> >(this->m_atol, this->m_rtol, this->m_dx_max);\n            auto y_ = vec_from_ptr(y0, ny);\n            this->reset();\n            integrate_adaptive(stepper, std::make_pair(f, j), y_, x0, xend, this->m_dx0,\n                                              std::bind(&Integr::obs_adaptive, this, _1, _2));\n        }\n\n        void predefined_rosenbrock4(const int nx,\n                                    const value_type * const ANYODE_RESTRICT xout,\n                                    const value_type * const ANYODE_RESTRICT y0,\n                                    value_type * const ANYODE_RESTRICT yout,\n                                    int * nreached){\n            *nreached = 0;\n            const auto ny = this->m_odesys->get_ny();\n            vector_type y_ = vec_from_ptr(y0, ny);\n            vector_type xout_ = vec_from_ptr(xout, nx);\n            auto f = [&](const vector_type &yarr, vector_type &dydx, value_type xval) {\n                this->m_odesys->rhs(xval, &(yarr.data()[0]), &(dydx.data()[0]));\n            };\n            auto j = [&](const vector_type & yarr, matrix_type &Jmat,\n                                     const value_type & xval, vector_type &dfdx) {\n                this->m_odesys->dense_jac_rmaj(xval, &(yarr.data()[0]), nullptr, &(Jmat.data()[0]), ny, &(dfdx.data()[0]));\n            };\n            try {\n                auto stepper = make_dense_output<rosenbrock4<value_type> >(this->m_atol, this->m_rtol, this->m_dx_max);\n                for (*nreached=1; *nreached < nx; ++*nreached){\n                    const int ix = *nreached;\n                    this->reset();\n                    integrate_adaptive(stepper, std::make_pair(f, j), y_, xout[ix - 1], xout[ix], this->m_dx0,\n                                       std::bind(&Integr::obs_predefined, this, _1, _2));\n                    for (int iy=0; iy < ny; ++iy)\n                        yout[ix*ny + iy] = y_[iy];\n                }\n            } catch (const std::exception& e) {\n                std::cerr << __FILE__ << \":\" << __LINE__ << \":\";\n                std::cerr << e.what() << std::endl;\n                nreached--;\n                if (!m_return_on_error)\n                    throw;\n            }\n        }\n\n    };\n\n    template <class OdeSys>\n    void set_integration_info(OdeSys * odesys, const Integr<OdeSys>& integrator){\n        odesys->current_info.nfo_int[\"n_steps\"] = integrator.m_nsteps;\n        odesys->current_info.nfo_int[\"nfev\"] = odesys->nfev;\n        odesys->current_info.nfo_int[\"njev\"] = odesys->njev;\n        odesys->current_info.nfo_dbl[\"time_wall\"] = integrator.m_time_wall;\n        odesys->current_info.nfo_dbl[\"time_cpu\"] = integrator.m_time_cpu;\n    }\n\n    template <class OdeSys>\n    std::pair<std::vector<double>, std::vector<double> >\n    simple_adaptive(OdeSys * const odesys,\n                    const double atol,\n                    const double rtol,\n                    const StepType styp,\n                    const double * const y0,\n                    const double x0,\n                    const double xend,\n                    long int mxsteps=0,\n                    double dx0=0.0,\n                    double dx_max=0.0,\n                    int autorestart=0,\n                    bool return_on_error=false\n                    )\n                    //,\n                    // const double dx_min=0.0,\n\n                    // long int mxsteps=0)\n    {\n        if (dx0 == 0.0)\n            dx0 = odesys->get_dx0(x0, y0);\n        if (dx0 == 0.0){\n            if (x0 == 0)\n                dx0 = std::numeric_limits<double>::epsilon() * 100;\n            else\n                dx0 = std::numeric_limits<double>::epsilon() * 100 * x0;\n        }\n        if (dx_max == 0.0)\n            dx_max = odesys->get_dx_max(x0, y0);\n        if (mxsteps == 0)\n            mxsteps = 500;\n        auto integr = Integr<OdeSys>(odesys, dx0, dx_max, atol, rtol, styp, mxsteps, autorestart, return_on_error);\n        auto result = integr.adaptive(x0, xend, y0);\n        odesys->current_info.clear();\n        set_integration_info<OdeSys>(odesys, integr);\n        return result;\n    }\n\n    template <class OdeSys>\n    int simple_predefined(OdeSys * const odesys,\n                          const double atol,\n                          const double rtol,\n                          const StepType styp,\n                          const double * const y0,\n                          const int nout,\n                          const double * const xout,\n                          double * const yout,\n                          long int mxsteps=0,\n                          double dx0=0.0,\n                          double dx_max=0.0,\n                          int autorestart=0,\n                          bool return_on_error=false\n                          )\n    // const double dx_min=0.0,\n    {\n        if (dx0 == 0.0)\n            dx0 = odesys->get_dx0(xout[0], y0);\n        if (dx0 == 0.0){\n            if (xout[0] == 0)\n                dx0 = std::numeric_limits<double>::epsilon() * 100;\n            else\n                dx0 = std::numeric_limits<double>::epsilon() * 100 * xout[0];\n        }\n        if (dx_max == 0.0)\n            dx_max = INFINITY;\n        if (mxsteps == 0)\n            mxsteps = 500;\n        auto integr = Integr<OdeSys>(odesys, dx0, dx_max, atol, rtol, styp, mxsteps, autorestart, return_on_error);\n        int nreached = integr.predefined(nout, xout, y0, yout);\n        odesys->current_info.nfo_int.clear();\n        odesys->current_info.nfo_dbl.clear();\n        set_integration_info(odesys, integr);\n        return nreached;\n    }\n\n}\n\n#endif /* ODEINT_ANYODE_H_6D2AAAD4880011E6AC5C734FA77443A3 */\n", "meta": {"hexsha": "7ce822927b5d50b2bcc754ff7b1d130765f9ab2b", "size": 21423, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "pyodeint/include/odeint_anyode.hpp", "max_stars_repo_name": "mikiec84/pyodeint", "max_stars_repo_head_hexsha": "093fa7bfd3bae1a0b1666a491760e527ae6a1fc2", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 22.0, "max_stars_repo_stars_event_min_datetime": "2015-11-03T19:22:27.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-01T15:42:41.000Z", "max_issues_repo_path": "pyodeint/include/odeint_anyode.hpp", "max_issues_repo_name": "mikiec84/pyodeint", "max_issues_repo_head_hexsha": "093fa7bfd3bae1a0b1666a491760e527ae6a1fc2", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2015-10-14T13:41:30.000Z", "max_issues_repo_issues_event_max_datetime": "2018-04-30T15:17:38.000Z", "max_forks_repo_path": "pyodeint/include/odeint_anyode.hpp", "max_forks_repo_name": "mikiec84/pyodeint", "max_forks_repo_head_hexsha": "093fa7bfd3bae1a0b1666a491760e527ae6a1fc2", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2016-07-04T14:38:17.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-11T02:26:51.000Z", "avg_line_length": 44.2623966942, "max_line_length": 158, "alphanum_fraction": 0.5055314382, "num_tokens": 5415, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.658417500561683, "lm_q2_score": 0.5039061705290805, "lm_q1q2_score": 0.3317806413173664}}
{"text": "#pragma once\n\n#include <vector>\n#include <algorithm>\n#include <random>\n#include <Eigen/Dense>\n\nnamespace cilantro {\n    // CRTP base class\n    template <class ModelEstimatorT, class ModelT, typename ResidualScalarT, typename IndexT = size_t>\n    class RandomSampleConsensusBase {\n    public:\n        EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n\n        typedef ModelT Model;\n        typedef ResidualScalarT ResidualScalar;\n        typedef std::vector<ResidualScalarT> ResidualVector;\n        typedef IndexT Index;\n        typedef std::vector<IndexT> IndexVector;\n\n        RandomSampleConsensusBase(size_t sample_size,\n                                  size_t inlier_count_thresh,\n                                  size_t max_iter,\n                                  ResidualScalar inlier_dist_thresh,\n                                  bool re_estimate = true)\n                : sample_size_(sample_size),\n                  inlier_count_thresh_(inlier_count_thresh),\n                  max_iter_(max_iter),\n                  inlier_dist_thresh_(inlier_dist_thresh),\n                  re_estimate_(re_estimate),\n                  iteration_count_(0)\n        {}\n\n        inline size_t getSampleSize() const { return sample_size_; }\n\n        inline ModelEstimatorT& setSampleSize(size_t sample_size) {\n            sample_size_ = sample_size;\n            return *static_cast<ModelEstimatorT*>(this);\n        }\n\n        inline size_t getTargetInlierCount() const { return inlier_count_thresh_; }\n\n        inline ModelEstimatorT& setTargetInlierCount(size_t inlier_count_thres) {\n            inlier_count_thresh_ = inlier_count_thres;\n            return *static_cast<ModelEstimatorT*>(this);\n        }\n\n        inline size_t getMaxNumberOfIterations() const { return max_iter_; }\n\n        inline ModelEstimatorT& setMaxNumberOfIterations(size_t max_iter) {\n            max_iter_ = max_iter;\n            return *static_cast<ModelEstimatorT*>(this);\n        }\n\n        inline ResidualScalar getMaxInlierResidual() const { return inlier_dist_thresh_; }\n\n        inline ModelEstimatorT& setMaxInlierResidual(ResidualScalar inlier_dist_thresh) {\n            inlier_dist_thresh_ = inlier_dist_thresh;\n            return *static_cast<ModelEstimatorT*>(this);\n        }\n\n        inline bool getReEstimationStep() const { return re_estimate_; }\n\n        inline ModelEstimatorT& setReEstimationStep(bool re_estimate) {\n            re_estimate_ = re_estimate;\n            return *static_cast<ModelEstimatorT*>(this);\n        }\n\n        ModelEstimatorT& estimate() {\n            ModelEstimatorT& estimator = *static_cast<ModelEstimatorT*>(this);\n            const size_t num_points = estimator.getDataPointsCount();\n            if (num_points < sample_size_) sample_size_ = num_points;\n            if (inlier_count_thresh_ > num_points) inlier_count_thresh_ = num_points;\n\n            // Initialize index permutation and random engine\n            IndexVector perm(num_points);\n            for (size_t i = 0; i < num_points; i++) perm[i] = static_cast<IndexT>(i);\n            std::mt19937 rng(std::random_device{}());\n\n            // Random sample results\n            Model curr_params;\n            ResidualVector curr_residuals;\n            IndexVector curr_inliers;\n\n            iteration_count_ = 0;\n            while (iteration_count_ < max_iter_) {\n                // Pick a random sample\n                IndexVector sample_ind(sample_size_);\n                size_t prev_size = num_points;\n                for (size_t i = 0; i < sample_size_; i++) {\n                    std::uniform_int_distribution<size_t> dist(0, prev_size - 1);\n                    size_t rand_ind = dist(rng);\n                    sample_ind[i] = perm[rand_ind];\n                    prev_size--;\n                    std::swap(perm[rand_ind], perm[prev_size]);\n                }\n\n                // Fit model to sample and get its inliers\n                estimator.estimateModel(sample_ind, curr_params);\n                estimator.computeResiduals(curr_params, curr_residuals);\n                curr_inliers.resize(num_points);\n                size_t k = 0;\n                for (size_t i = 0; i < num_points; i++) {\n                    if (curr_residuals[i] <= inlier_dist_thresh_) curr_inliers[k++] = static_cast<IndexT>(i);\n                }\n                curr_inliers.resize(k);\n\n                iteration_count_++;\n                if (curr_inliers.size() < sample_size_) continue;\n\n                // Update best found\n                if (curr_inliers.size() > model_inliers_.size()) {\n                    model_params_ = curr_params;\n                    model_residuals_ = std::move(curr_residuals);\n                    model_inliers_ = std::move(curr_inliers);\n                }\n\n                // Check if target inlier count was reached\n                if (model_inliers_.size() >= inlier_count_thresh_) break;\n            }\n\n            // Re-estimate\n            if (re_estimate_) {\n                estimator.estimateModel(model_inliers_, model_params_);\n                estimator.computeResiduals(model_params_, model_residuals_);\n                model_inliers_.resize(num_points);\n                size_t k = 0;\n                for (size_t i = 0; i < num_points; i++){\n                    if (model_residuals_[i] <= inlier_dist_thresh_) model_inliers_[k++] = static_cast<IndexT>(i);\n                }\n                model_inliers_.resize(k);\n            }\n\n            return estimator;\n        }\n\n        inline ModelEstimatorT& estimate(ResidualScalar max_residual,\n                                         size_t target_inlier_count,\n                                         size_t max_iter)\n        {\n            inlier_count_thresh_ = target_inlier_count;\n            max_iter_ = max_iter;\n            inlier_dist_thresh_ = max_residual;\n            return estimate();\n        }\n\n        inline const ModelEstimatorT& getEstimationResults(Model &model_params,\n                                                           ResidualVector &model_residuals,\n                                                           IndexVector &model_inliers) const\n        {\n            model_params = model_params_;\n            model_residuals = model_residuals_;\n            model_inliers = model_inliers_;\n            return *static_cast<ModelEstimatorT*>(this);\n        }\n\n        inline const Model& getModel() const { return model_params_; }\n\n        inline const ModelEstimatorT& getModel(Model &model_params) const {\n            model_params = model_params_;\n            return *static_cast<ModelEstimatorT*>(this);\n        }\n\n        inline const ResidualVector& getModelResiduals() const { return model_residuals_; }\n\n        inline const ModelEstimatorT& getModelResiduals(ResidualVector &model_residuals) const {\n            model_residuals = model_residuals_;\n            return *static_cast<ModelEstimatorT*>(this);\n        }\n\n        inline const IndexVector& getModelInliers() const { return model_inliers_; }\n\n        inline const ModelEstimatorT& getModelInliers(IndexVector &model_inliers) const {\n            model_inliers = model_inliers_;\n            return *static_cast<ModelEstimatorT*>(this);\n        }\n\n        inline bool targetInlierCountAchieved() const { return model_inliers_.size() >= inlier_count_thresh_; }\n\n        inline size_t getNumberOfPerformedIterations() const { return iteration_count_; }\n\n        inline size_t getNumberOfInliers() const { return model_inliers_.size(); }\n\n    protected:\n        // Parameters\n        size_t sample_size_;\n        size_t inlier_count_thresh_;\n        size_t max_iter_;\n        ResidualScalar inlier_dist_thresh_;\n        bool re_estimate_;\n\n        // Object state and results\n        size_t iteration_count_;\n        Model model_params_;\n        ResidualVector model_residuals_;\n        IndexVector model_inliers_;\n    };\n}\n", "meta": {"hexsha": "0fa655e662ea515fcf270904834b18f8086d6801", "size": 7841, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/cilantro/model_estimation/ransac_base.hpp", "max_stars_repo_name": "eecn/cilantro", "max_stars_repo_head_hexsha": "467824bb7551e4537b2b7d1f697156f68f608260", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 719.0, "max_stars_repo_stars_event_min_datetime": "2017-08-07T08:30:39.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T07:08:52.000Z", "max_issues_repo_path": "include/cilantro/model_estimation/ransac_base.hpp", "max_issues_repo_name": "eecn/cilantro", "max_issues_repo_head_hexsha": "467824bb7551e4537b2b7d1f697156f68f608260", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 55.0, "max_issues_repo_issues_event_min_datetime": "2017-09-19T13:40:44.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-16T13:58:32.000Z", "max_forks_repo_path": "include/cilantro/model_estimation/ransac_base.hpp", "max_forks_repo_name": "eecn/cilantro", "max_forks_repo_head_hexsha": "467824bb7551e4537b2b7d1f697156f68f608260", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 152.0, "max_forks_repo_forks_event_min_datetime": "2017-12-13T07:28:14.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-18T07:02:48.000Z", "avg_line_length": 39.4020100503, "max_line_length": 113, "alphanum_fraction": 0.5920163244, "num_tokens": 1592, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6584175005616829, "lm_q2_score": 0.5039061705290805, "lm_q1q2_score": 0.33178064131736634}}
{"text": "/*\n * WaveEquation.cc\n *\n *  Created on: 05.05.2017\n *      Author: thies\n */\n\n/*\n * based on step23.cc from the deal.II tutorials\n */\n\n#include <deal.II/base/exceptions.h>\n#include <deal.II/base/logstream.h>\n#include <deal.II/base/thread_management.h>\n#include <deal.II/base/timer.h>\n#include <deal.II/base/types.h>\n#include <deal.II/base/utilities.h>\n#include <deal.II/dofs/dof_tools.h>\n#include <deal.II/lac/dynamic_sparsity_pattern.h>\n#include <deal.II/lac/precondition.h>\n#include <deal.II/lac/solver_cg.h>\n#include <deal.II/lac/solver_control.h>\n#include <deal.II/numerics/matrix_tools.h>\n#include <deal.II/numerics/vector_tools.h>\n\n#include <forward/WaveEquation.h>\n\n#include <stddef.h>\n#include <iostream>\n#include <map>\n#include <string>\n\n#include <deal.II/base/data_out_base.h>\n#include <deal.II/numerics/data_out.h>\n#include <fstream>\n\nnamespace wavepi {\nnamespace forward {\n\nusing namespace dealii;\nusing namespace wavepi::base;\n\ntemplate<int dim>\nWaveEquation<dim>::WaveEquation(std::shared_ptr<SpaceTimeMesh<dim>> mesh)\n      : AbstractEquation<dim>(mesh), initial_values_u(std::make_shared<Functions::ZeroFunction<dim>>(1)),\n            initial_values_v(std::make_shared<Functions::ZeroFunction<dim>>(1)),\n            boundary_values_u(std::make_shared<Functions::ZeroFunction<dim>>(1)),\n            boundary_values_v(std::make_shared<Functions::ZeroFunction<dim>>(1)) {\n}\n\ntemplate<int dim>\nWaveEquation<dim>::WaveEquation(const WaveEquation<dim> &wave)\n      : AbstractEquation<dim>(wave.get_mesh()), initial_values_u(wave.get_initial_values_u()),\n            initial_values_v(wave.get_initial_values_v()), boundary_values_u(wave.get_boundary_values_u()),\n            boundary_values_v(wave.get_boundary_values_v()) {\n\n   this->set_param_c(wave.get_param_c());\n   this->set_param_nu(wave.get_param_nu());\n   this->set_param_rho(wave.get_param_rho());\n   this->set_param_q(wave.get_param_q());\n   this->set_rho_time_dependent(wave.is_rho_time_dependent());\n\n   this->set_theta(wave.get_theta());\n   this->set_solver_tolerance(wave.get_solver_tolerance());\n   this->set_solver_max_iter(wave.get_solver_max_iter());\n}\n\ntemplate<int dim>\nvoid WaveEquation<dim>::apply_boundary_conditions_u(double time) {\n   boundary_values_u->set_time(time);\n   boundary_values_u->set_time(time);\n\n   std::map<types::global_dof_index, double> boundary_values;\n   VectorTools::interpolate_boundary_values(*dof_handler, 0, *boundary_values_u, boundary_values);\n   MatrixTools::apply_boundary_values(boundary_values, system_matrix, solution_u, system_rhs);\n}\n\ntemplate<int dim>\nvoid WaveEquation<dim>::apply_boundary_conditions_v(double time) {\n   boundary_values_v->set_time(time);\n\n   std::map<types::global_dof_index, double> boundary_values;\n   VectorTools::interpolate_boundary_values(*dof_handler, 0, *boundary_values_v, boundary_values);\n   MatrixTools::apply_boundary_values(boundary_values, system_matrix, solution_v, system_rhs);\n}\n\ntemplate<int dim>\nvoid WaveEquation<dim>::initial_values(double time) {\n   initial_values_u->set_time(time);\n   initial_values_v->set_time(time);\n\n   /* projecting might make more sense, but VectorTools::project\n    leads to a mutex error (deadlock) on my laptop (Core i5 6267U) */\n   //   VectorTools::project(*dof_handler, constraints, QGauss<dim>(3), *initial_values_u, old_solution_u);\n   //   VectorTools::project(*dof_handler, constraints, QGauss<dim>(3), *initial_values_v, old_solution_v);\n   VectorTools::interpolate(*dof_handler, *initial_values_u, solution_u);\n   constraints->distribute(solution_u);\n\n   VectorTools::interpolate(*dof_handler, *initial_values_v, solution_v);\n   constraints->distribute(solution_v);\n}\n\ntemplate<int dim>\nvoid WaveEquation<dim>::assemble_matrices(size_t time_idx) {\n   LogStream::Prefix p(\"assemble_matrices\");\n\n   this->fill_matrices(mesh, time_idx, matrix_A, matrix_B, matrix_C);\n}\n\ntemplate<int dim>\nDiscretizedFunction<dim> WaveEquation<dim>::run(std::shared_ptr<RightHandSide<dim>> right_hand_side,\n      typename AbstractEquation<dim>::Direction direction) {\n   {\n      LogStream::Prefix p(\"WaveEq\");\n      LogStream::Prefix pp(\"BoundChecking\");\n\n      // bound checking for ρ and c (if possible)\n      // (should not take long compared to the rest and can be very tricky to find out otherwise\n      //    -> do it even in release mode)\n      if (this->param_c_disc) {\n         double c_min, c_max;\n         this->param_c_disc->min_max_value(&c_min, &c_max);\n\n         std::stringstream bound_str;\n         bound_str << c_min << \" ≤ c ≤ \" << c_max;\n\n         AssertThrow(c_min > 0, ExcMessage(\"C is not positive, \" + bound_str.str()));\n         AssertThrow(1.0 / (c_max * c_max) >= 1e-4, ExcMessage(\"C is not coercive, \" + bound_str.str()));\n\n         deallog << bound_str.str() << std::endl;\n      }\n\n      if (this->param_rho_disc) {\n         double rho_min, rho_max;\n         this->param_rho_disc->min_max_value(&rho_min, &rho_max);\n\n         std::stringstream bound_str;\n         bound_str << rho_min << \" ≤ ρ ≤ \" << rho_max;\n\n         AssertThrow(rho_min > 0, ExcMessage(\"A and D are not positive, \" + bound_str.str()));\n         AssertThrow(1.0 / rho_max >= 1e-4, ExcMessage(\"A and D are not coercive, \" + bound_str.str()));\n\n         deallog << bound_str.str() << std::endl;\n      }\n   }\n\n   return AbstractEquation<dim>::run(right_hand_side, direction);\n}\n\ntemplate class WaveEquation<1> ;\ntemplate class WaveEquation<2> ;\ntemplate class WaveEquation<3> ;\n\n} /* namespace forward */\n} /* namespace wavepi */\n", "meta": {"hexsha": "db8bdd2a85c66f3ee91c145f4e77a473babb7d07", "size": 5502, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lib/forward/WaveEquation.cpp", "max_stars_repo_name": "thiesgerken/wavepi", "max_stars_repo_head_hexsha": "5af37946dcc1910ad1cccdc76d2e2f546eeafec4", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "lib/forward/WaveEquation.cpp", "max_issues_repo_name": "thiesgerken/wavepi", "max_issues_repo_head_hexsha": "5af37946dcc1910ad1cccdc76d2e2f546eeafec4", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lib/forward/WaveEquation.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.2692307692, "max_line_length": 107, "alphanum_fraction": 0.7150127226, "num_tokens": 1394, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.658417487156366, "lm_q2_score": 0.5039061705290805, "lm_q1q2_score": 0.33178063456234447}}
{"text": "#ifndef GIFS_CONVERSION_H\n#define GIFS_CONVERSION_H\n\n#include <algorithm>\n#include <armadillo>\n\n\n/* Direct conversion! */\nclass Conversion\n{\npublic:\n    // \n    explicit Conversion(double mass, double length, double time);\n    Conversion(const Conversion& rhs) = default;\n    Conversion(Conversion&& rhs) = default;\n    Conversion& operator=(const Conversion& rhs) = default;\n    Conversion& operator=(Conversion&& rhs) = default;\n\n    //\n    template<typename itr1, typename itr2>\n    inline\n    void \n    transform_crd_md2au(itr1 in_begin, itr1 in_end, itr2 result_begin) {\n        std::transform(in_begin, in_end, result_begin, [this](double value){ return this->crd_md2au(value); });\n    };\n    //\n    template<typename itr1, typename itr2>\n    inline \n    void \n    transform_veloc_md2au(itr1 in_begin, itr1 in_end, itr2 result_begin) {\n        std::transform(in_begin, in_end, result_begin, [this](double value){ return this->veloc_md2au(value); });\n    }\n    //\n    template<typename itr1, typename itr2>\n    inline \n    void \n    transform_veloc_au2md(itr1 in_begin, itr1 in_end, itr2 result_begin) {\n        std::transform(in_begin, in_end, result_begin, [this](double value){ return this->veloc_au2md(value); });\n    }\n    //\n    template<typename itr1, typename itr2>\n    inline \n    void \n    transform_gradient_au2md(itr1 in_begin, itr1 in_end, itr2 result_begin) {\n        std::transform(in_begin, in_end, result_begin, [this](double value){ return this->grd_au2md(value); });\n    }\n    //\n    template<typename itr1, typename itr2>\n    inline \n    void \n    transform_gradient_md2au(itr1 in_begin, itr1 in_end, itr2 result_begin) {\n        std::transform(in_begin, in_end, result_begin, [this](double value){ return this->grd_md2au(value); });\n    }\n    //\n    template<typename itr1, typename itr2>\n    inline \n    void \n    transform_masses_md2au(itr1 in_begin, itr1 in_end, itr2 result_begin) {\n        std::transform(in_begin, in_end, result_begin, [this](double value){ return this->mass_md2au(value); });\n    }\n    //\n    inline double energy_au2md(double value) const noexcept {return _energy_au2md*value;}\n    inline double energy_md2au(double value) const noexcept {return _energy_md2au*value;}\n    //\n    inline double crd_au2md(double value) const noexcept {return _crd_au2md*value;}\n    inline double crd_md2au(double value) const noexcept {return _crd_md2au*value;}\n    //\n    inline double veloc_au2md(double value) const noexcept {return _veloc_au2md*value;}\n    inline double veloc_md2au(double value) const noexcept {return _veloc_md2au*value;}\n    //\n    inline double grd_au2md(double value) const noexcept {return _grd_au2md*value;}\n    inline double grd_md2au(double value) const noexcept {return _grd_md2au*value;}\n    //\n    inline double mass_au2md(double value) const noexcept {return _mass_au2md*value;}\n    inline double mass_md2au(double value) const noexcept {return _mass_md2au*value;}\n\nprivate:\n    // energies\n    double _energy_au2md;\n    double _energy_md2au;\n    // coordinates\n    double _crd_au2md;\n    double _crd_md2au;\n    // velocities\n    double _veloc_au2md;\n    double _veloc_md2au;\n    // gradient\n    double _grd_au2md;\n    double _grd_md2au;\n    // mass\n    double _mass_au2md;\n    double _mass_md2au;\n    //\n};\n\n#endif\n", "meta": {"hexsha": "f625beffe8548f2754eff3b21db1627c8b3d1661", "size": 3282, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/conversion.hpp", "max_stars_repo_name": "farajilab/gifs_release", "max_stars_repo_head_hexsha": "ffa674110bcd15de851a8b6a703b4f4bc96fcd2d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2022-03-04T18:56:08.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T16:49:22.000Z", "max_issues_repo_path": "include/conversion.hpp", "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": "include/conversion.hpp", "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": 33.8350515464, "max_line_length": 113, "alphanum_fraction": 0.7001828154, "num_tokens": 900, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.658417487156366, "lm_q2_score": 0.5039061705290805, "lm_q1q2_score": 0.33178063456234447}}
{"text": "/*\n * File:   image_noise_sim.cc\n * Author: ts337\n *\n * Created on 22 March 2011, 18:49\n */\n\n\n#include \"../image_noise_sim.h\"\n#include <boost/random/poisson_distribution.hpp>\n#include<iostream>\n\nnamespace coela {\nnamespace image_noise_simulation {\n\n\nuniform_random_pixel_variate::uniform_random_pixel_variate(\n    const PixelRange& image_outline_,\n    unuran::StreamWrapper& rns)\n    : urv(0.0, image_outline_.n_pix(), rns), range(image_outline_)\n{}\n\nPixelIndex uniform_random_pixel_variate::operator()()\n{\n    int data_vec_index = int(urv()) ;\n    return range.get_PixelIndex_for_data_vector_element(data_vec_index);\n}\n\n\nintensity_map_random_pixel_variate::intensity_map_random_pixel_variate(\n    const PixelArray2d<double>& intensity_map,\n    unuran::StreamWrapper& rns,\n    const size_t /*expected_number_of_uses*/)\n    :gen(NULL), range(intensity_map.range())\n{\n    UNUR_DISTR *distr;    /* distribution object                   */\n    UNUR_PAR   *par;      /* parameter object                      */\n\n    distr = unur_distr_discr_new();\n\n    const vector<double>& prob_vec(intensity_map.get_raw_data());\n\n    unur_distr_discr_set_pv(distr, &prob_vec[0] , prob_vec.size());\n//    par = unur_dgt_new(distr);\n//    unur_dgt_set_guidefactor(par, std::min(3.0/sqrt(prob_vec.size()), 1.0) );\n\n    par = unur_dau_new(distr);\n    unur_set_urng(par, rns.get_stream_pointer());\n    gen = unur_init(par);\n    unur_distr_free(distr);\n\n    if (gen==NULL) { throw std::runtime_error(\"intensity_map_random_pixel_variate::intensity_map_random_pixel_variate - could not construct generator.\"); }\n\n}\n\nPixelIndex intensity_map_random_pixel_variate::operator()()\n{\n    int data_vec_index = unur_sample_discr(gen);\n    return range.get_PixelIndex_for_data_vector_element(data_vec_index);\n}\n\n\nPixelArray2d<int> generate_photon_arrival_map(\n    const PixelArray2d<double>& source_intensity_map,\n    const double mean_total_number_of_source_photons,\n    const double mean_bg_photons_per_pixel,\n    unuran::StreamWrapper& rns)\n{\n    \n    unuran::PoissonRandomVariate source_total_prv(\n        mean_total_number_of_source_photons, rns);\n\n    int n_source_photons = source_total_prv();\n//    return photon_arrival_map_fixed_n_low_flux_optimized(intensity_map, n_photons, rns);\n\n    PixelArray2d<int> source_photon_arrival_map(\n        source_intensity_map.range().x_dim(), source_intensity_map.range().y_dim(), 0);\n\n    intensity_map_random_pixel_variate pixel_picker(source_intensity_map, rns);\n\n    for (int phot_index=0; phot_index!=n_source_photons; ++phot_index) {\n        source_photon_arrival_map(pixel_picker())+=1;\n    }\n\n    if (mean_bg_photons_per_pixel!=0.0) {\n        double mean_bg_sum_flux =\n            source_photon_arrival_map.range().n_pix() * mean_bg_photons_per_pixel;\n        \n        unuran::PoissonRandomVariate bg_total_prv(mean_bg_sum_flux, rns);\n        int n_bg_photons = bg_total_prv();\n        uniform_random_pixel_variate bg_pixel_picker(source_photon_arrival_map.range(),\n                rns);\n        for (int bg_phot_gen=0; bg_phot_gen!=n_bg_photons; ++bg_phot_gen) {\n            source_photon_arrival_map(bg_pixel_picker()) +=1;\n        }\n    }\n    return source_photon_arrival_map;\n\n}\n\n\n\n\n\nPixelArray2d<int> EMCCD_simulated_image(\n    const PixelArray2d<int> & photon_arrival_map,\n    EmccdModel& model_variate,\n    unuran::StreamWrapper& rns)\n{\n    PixelArray2d<int> sim_image(photon_arrival_map.range().x_dim(),\n                                photon_arrival_map.range().y_dim(), 0);\n\n    //Simulate photon events\n    for (PixelIterator i(photon_arrival_map.range()); i!=i.end; ++i) {\n        if (photon_arrival_map(i)) {\n            sim_image(i) +=\n                model_variate.stochastically_multiply_photons(photon_arrival_map(i));\n        }\n    }\n\n    //simulate CIC events\n    if (model_variate.params.serial_CIC_rate!=0) {\n        int n_CIC_events;\n\n        double expected_num_CIC_events = model_variate.params.serial_CIC_rate *\n                                         sim_image.range().n_pix() ;\n\n        unuran::PoissonRandomVariate n_CIC_events_variate(\n            expected_num_CIC_events,\n            rns);\n        n_CIC_events = n_CIC_events_variate();\n        uniform_random_pixel_variate pixel_picker(sim_image.range(), rns);\n\n        for (int i=0; i!=n_CIC_events; ++i) {\n//            int pixel_number = int( pixel_picker() ) + 1;\n//            PixelIndex pix = sim_image.range().get_nth_PixelIndex(pixel_number);\n            PixelIndex pix = pixel_picker();\n            sim_image(pix) += model_variate.CICIR_variate();\n        }\n    }\n    //Simulate readout\n    for (PixelIterator i(sim_image.range()); i!=i.end; ++i) {\n        sim_image(i)+=model_variate.readout_noise_variate();\n    }\n\n    return sim_image;\n}\n\n}//end namespace coela::image_noise_simulation\n}//end namespace coela\n", "meta": {"hexsha": "92e4e373c63869e75c9476aa825a1838d22659ea", "size": 4820, "ext": "cc", "lang": "C++", "max_stars_repo_path": "coela_analysis/src/implementation/image_noise_sim.cc", "max_stars_repo_name": "timstaley/coelacanth", "max_stars_repo_head_hexsha": "d8adc49bac5dac54fdce600ea0260c526ce361af", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-10-22T03:08:45.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-22T03:08:45.000Z", "max_issues_repo_path": "coela_analysis/src/implementation/image_noise_sim.cc", "max_issues_repo_name": "timstaley/coelacanth", "max_issues_repo_head_hexsha": "d8adc49bac5dac54fdce600ea0260c526ce361af", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "coela_analysis/src/implementation/image_noise_sim.cc", "max_forks_repo_name": "timstaley/coelacanth", "max_forks_repo_head_hexsha": "d8adc49bac5dac54fdce600ea0260c526ce361af", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.9205298013, "max_line_length": 155, "alphanum_fraction": 0.6902489627, "num_tokens": 1231, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6959583124210895, "lm_q2_score": 0.476579651063676, "lm_q1q2_score": 0.33167956968850765}}
{"text": "#include <opencv2/opencv.hpp>\n#include <Eigen/Core>\n#include <Eigen/Dense>\n#include <Eigen/Geometry>\n#include <vector>\n#include <iostream>\n#include <memory>\n\n\nint cell = 16;\nint bin_num = 8;\n\nstruct Intrinsics{\n    double fx;\n    double fy;\n    double cx;\n    double cy;\n};\n\nvoid Get3dPointAndIntensity(int cell_size, int cell_row_id, int cell_col_id, const cv::Mat& image, const cv::Mat& depth, std::vector<Eigen::Vector3d, Eigen::aligned_allocator<Eigen::Vector3d> >& points_3d, Eigen::VectorXd& intensity, const Eigen::Matrix4d& T_wc, Intrinsics in);\n\nstd::vector<cv::Mat> ReadGroundtruth(std::string add, std::string dataset);\n\nclass NID{\npublic:\n    EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n    void set_member_size();\n    void ComputeHref();\n    void ComputeH();\n\n    int cell_ = 16;\n    int bin_num_ ;\n    Eigen::VectorXd intensity0_;\n    std::vector<Eigen::Vector3d, Eigen::aligned_allocator<Eigen::Vector3d> > pw0_;\n    Eigen::Matrix4d tf_;\n    cv::Mat image1_;\n    double fx_;\n    double fy_;\n    double cx_;\n    double cy_;\n    std::vector<double> pro_ref_, pro_current_;\n    std::vector<std::vector<double> > pro_joint_;\n    double sigma_ = 1e-30;\n    double H_ref_ = 0.0, H_current_ = 0.0, H_joint_ = 0.0;\n    Eigen::VectorXd intensity_current_;\n    double nid_, MI_;\n\n    inline double get_interpolated_pixel_value ( double x, double y )\n    {\n        int ix = (int)x;\n        int iy = (int)y;\n\n        double dx = x - ix;\n        double dy = y - iy;\n        double dxdy = dx*dy; \n\n        double xx = x - floor ( x );\n        double yy = y - floor ( y );\n\n        return double (\n        dxdy * image1_.ptr<uchar>(iy+1)[ix+1] \n        + (dy - dxdy) * image1_.ptr<uchar>(iy+1)[ix]\n        + (dx - dxdy) * image1_.ptr<uchar>(iy)[ix+1]\n        + (1 - dx - dy + dxdy) * image1_.ptr<uchar>(iy)[ix]\n        );\n    }\n};\n\nint main(int argc, char** argv){\n    if(argc!=2){\n        std::cout<<\"usage './program path_to_config.yaml', image1's timestamp should be smaller than image2\"<<std::endl;\n        exit(0);\n    }\n    \n    std::string config_add = argv[1];\n    cv::FileStorage fc;\n    fc.open(config_add, cv::FileStorage::READ);\n    std::string type0 = fc[\"image0_type\"] , type1 = fc[\"image1_type\"], id0 = fc[\"image0_id\"], id1 = fc[\"image1_id\"], use_gt = fc[\"use_groundtruth\"], dataset = fc[\"dataset\"], im_add = fc[\"im_address\"];\n    double depth_factor = 1.0/(int)fc[\"depth_factor\"], fx = fc[\"fx\"], fy = fc[\"fy\"], cx = fc[\"cx\"], cy = fc[\"cy\"];\n    \n    cv::Mat im0,im1;\n    std::string rgb0_add, rgb1_add;\n    if(dataset == \"eth_cvg\"){\n      rgb0_add = im_add + type0 + \"/\" + id0 + \".png\";\n      rgb1_add = im_add + type1 + \"/\" + id1 + \".png\";\n    }\n\n    cv::Mat im_rgb0 = cv::imread(rgb0_add,CV_LOAD_IMAGE_UNCHANGED);//use cv::IMREAD_GRAYSCALE, the result will be different\n    im0 = im_rgb0;\n    cvtColor(im0,im0,CV_RGB2GRAY);\n\n    cv::Mat im_rgb1 = cv::imread(rgb1_add,CV_LOAD_IMAGE_UNCHANGED);\n    im1 = im_rgb1;\n    cvtColor(im1,im1,CV_RGB2GRAY);\n\n    std::cout<<\"image size \"<<im0.size()<<\",\"<<im1.size()<<std::endl;\n\n    //read corresponding depth\n    cv::Mat depth0;\n    if(dataset == \"eth_cvg\"){\n      std::string depth_add = im_add + \"depth/\" + id0 + \".png\";\n      depth0 = cv::imread(depth_add, CV_LOAD_IMAGE_UNCHANGED);\n      depth0.convertTo(depth0,CV_64F,depth_factor);\n    }\n\n    std::string pose_gt_add;\n    if(dataset == \"eth_cvg\"){\n      pose_gt_add = im_add + \"groundtruth.txt\";\n    }\n    std::vector<cv::Mat> gt = ReadGroundtruth(pose_gt_add, dataset);\n    int pose_id0 = stoi(id0);\n    int pose_id1 = stoi(id1);\n\n    cv::Mat T_wc0_cv,T_wc1_cv, T_cw0_cv, T_cw1_cv;\n\n    //pose id output from slam needs to corresponds to the id input of this program\n    cv::FileStorage fp0, fp1;\n    if(use_gt == \"0\"){\n      if(fp0.open(std::to_string(pose_id0) + \".xml\", cv::FileStorage::READ) && fp1.open(std::to_string(pose_id1) + \".xml\", cv::FileStorage::READ)){\n        std::cout<<\"use the pose from etimation\"<<std::endl;\n        fp0[\"pose\"]>>T_cw0_cv;\n        fp1[\"pose\"]>>T_cw1_cv;\n        T_cw0_cv.convertTo(T_cw0_cv, CV_64F);\n        T_cw1_cv.convertTo(T_cw1_cv, CV_64F);\n        T_wc0_cv = T_cw0_cv.inv();\n        T_wc1_cv = T_cw1_cv.inv();\n      }\n      else{\n        std::cout<<\"no correspoding pose, exit \"<<std::endl;\n        exit(0);\n      }\n    }\n    else if(use_gt == \"1\"){\n        std::cout<<\"use groundtruth pose \"<<std::endl;\n        T_wc0_cv = gt[pose_id0];\n        T_wc1_cv = gt[pose_id1];\n    }\n    else{\n      std::cout<<\"you must have pose provided by groundtruth or SLAM\"<<std::endl;\n    }\n\n    //std::cout<<\"pose id is \"<<pose_id<<std::endl;\n    Intrinsics in;\n    in.fx = fx;\n    in.fy = fy;\n    in.cx = cx;\n    in.cy = cy;\n\n    std::vector<std::shared_ptr<NID> > nid_vec;\n    Eigen::Matrix4d T_wc0, T_wc1;\n    T_wc0<<T_wc0_cv.ptr<double>(0)[0], T_wc0_cv.ptr<double>(0)[1], T_wc0_cv.ptr<double>(0)[2], T_wc0_cv.ptr<double>(0)[3],\n          T_wc0_cv.ptr<double>(1)[0], T_wc0_cv.ptr<double>(1)[1], T_wc0_cv.ptr<double>(1)[2], T_wc0_cv.ptr<double>(1)[3],\n          T_wc0_cv.ptr<double>(2)[0], T_wc0_cv.ptr<double>(2)[1], T_wc0_cv.ptr<double>(2)[2], T_wc0_cv.ptr<double>(2)[3],\n          0                              , 0                              , 0                              , 1;\n    T_wc1<<T_wc1_cv.ptr<double>(0)[0], T_wc1_cv.ptr<double>(0)[1], T_wc1_cv.ptr<double>(0)[2], T_wc1_cv.ptr<double>(0)[3],\n          T_wc1_cv.ptr<double>(1)[0], T_wc1_cv.ptr<double>(1)[1], T_wc1_cv.ptr<double>(1)[2], T_wc1_cv.ptr<double>(1)[3],\n          T_wc1_cv.ptr<double>(2)[0], T_wc1_cv.ptr<double>(2)[1], T_wc1_cv.ptr<double>(2)[2], T_wc1_cv.ptr<double>(2)[3],\n          0                              , 0                              , 0                              , 1;\n\n    std::ofstream of(\"nid_test.csv\", std::ofstream::out | std::ofstream::app);\n\n    const double px_ori = T_wc0(0,3);\n    const Eigen::Matrix4d SE3_ori= T_wc0;\n\n    //calculate entropy of each cell\n    double total_nid = 0.0;\n    for(int i = 0; i<cell; i++){\n        for(int j = 0; j<cell; j++){\n            std::vector<Eigen::Vector3d, Eigen::aligned_allocator<Eigen::Vector3d> > points_3d;\n            Eigen::VectorXd intensity;\n            Get3dPointAndIntensity(cell, i, j, im0, depth0, points_3d, intensity, T_wc0, in);\n            std::shared_ptr<NID> nid = std::make_shared<NID>();\n            nid->cell_ = cell;\n            nid->bin_num_ = bin_num;\n            nid->image1_ = im1;\n            nid->fx_ = in.fx;\n            nid->fy_ = in.fy;\n            nid->cx_ = in.cx;\n            nid->cy_ = in.cy;\n            nid->pw0_ = points_3d;\n            nid->intensity0_ = intensity;\n            nid->tf_ = T_wc1;\n            nid->set_member_size();\n            nid->ComputeHref();\n            nid->ComputeH();\n            total_nid += nid->nid_ * nid->nid_;\n            //exit(0);\n        }\n    }\n\n    std::cout<<\"final nid is \"<<sqrt(total_nid)<<std::endl;\n    \n\n    \n\n    return 0;\n\n}\n\nvoid Get3dPointAndIntensity(int cell_size, int cell_row_id, int cell_col_id, const cv::Mat& image, const cv::Mat& depth, std::vector<Eigen::Vector3d, Eigen::aligned_allocator<Eigen::Vector3d> >& points_3d, Eigen::VectorXd& intensity, const Eigen::Matrix4d& T_wc, Intrinsics in){\n    int row_block = image.rows / cell_size;\n    int col_block = image.cols / cell_size;\n    int row_start = row_block * cell_row_id;\n    int col_start = col_block * cell_col_id;\n    int row_end = row_block * (cell_row_id + 1);\n    int col_end = col_block * (cell_col_id + 1);\n    int counter = 0;\n    \n    std::vector<double> intensity_v;\n    for(int i = row_start; i < row_end; i++)\n        for(int j = col_start; j < col_end; j++){\n            double z_p = depth.ptr<double>(i)[j];\n            counter++;\n            if(z_p <0.01 || z_p > 100)\n                continue;\n\n            double x_p = z_p * (j - in.cx) / in.fx;\n            double y_p = z_p * (i - in.cy) / in.fy;\n\n            Eigen::Vector3d p_world = (T_wc*Eigen::Vector4d(x_p,y_p,z_p,1)).head(3);\n\n            points_3d.push_back(p_world);\n            intensity_v.push_back(image.ptr<uchar>(i)[j]);\n            \n        }\n    \n    intensity = Eigen::Map<Eigen::VectorXd, Eigen::Unaligned>(intensity_v.data(), intensity_v.size());\n\n    return;\n};\n\nstd::vector<cv::Mat> ReadGroundtruth(std::string add, std::string dataset){\n  std::vector<cv::Mat> all_gt;\n\n  std::ifstream groundtruth_file(add.c_str());\n  if(!groundtruth_file){\n      printf(\"cannot find the file that contains groundtruth \\n\");\n      return all_gt;\n  }\n\n  int counter = 0;\n  std::string one_row_gt;\n  \n  while(getline(groundtruth_file,one_row_gt)){\n      std::istringstream temp_one_row_gt(one_row_gt);\n      std::string string_gt;\n      Eigen::Matrix3d rm;\n      double px,py,pz;\n      int sequence = 0;\n      if (dataset == \"eth_cvg\"){\n      double qx,qy,qz,qw;\n      while(getline(temp_one_row_gt, string_gt, ' ')){\n        switch(sequence){\n          case 0:{\n              int msg_timestamp = atoi(string_gt.c_str());\n              sequence++;\n          }\n              break;\n          case 1:{\n              //the case 1,2,3 is position x,y,z\n              px = (double)atof(string_gt.c_str());\n              sequence++;\n          }\n              break;\n          case 2:{\n              py = (double)atof(string_gt.c_str());\n              sequence++;\n          }\n              break;\n          case 3:{\n              pz = (double)atof(string_gt.c_str());\n              sequence++;\n          }\n              break;\n          case 4:{\n              //the case 4,5,6,7 is quternion x,y,z,w\n              qx = (double)atof(string_gt.c_str());\n              sequence++;\n          }\n              break;\n          case 5:{\n              qy = (double)atof(string_gt.c_str());\n              sequence++;\n          }\n              break;\n          case 6:{\n              qz = (double)atof(string_gt.c_str());\n              sequence++;\n          }\n              break;\n          case 7:{\n              qw = (double)atof(string_gt.c_str());\n              sequence++;\n          }\n              break;\n          default:\n              break;\n        }\n      }\n      Eigen::Quaterniond qt(qw,qx,qy,qz);\n      rm = qt.toRotationMatrix();\n    }\n    \n    cv::Mat one_gt(4,4,CV_64FC1);\n    one_gt.ptr<double>(0)[0] = rm(0,0);\n    one_gt.ptr<double>(0)[1] = rm(0,1);\n    one_gt.ptr<double>(0)[2] = rm(0,2);\n    one_gt.ptr<double>(1)[0] = rm(1,0);\n    one_gt.ptr<double>(1)[1] = rm(1,1);\n    one_gt.ptr<double>(1)[2] = rm(1,2);\n    one_gt.ptr<double>(2)[0] = rm(2,0);\n    one_gt.ptr<double>(2)[1] = rm(2,1);\n    one_gt.ptr<double>(2)[2] = rm(2,2);\n    one_gt.ptr<double>(3)[0] = 0.0;\n    one_gt.ptr<double>(3)[1] = 0.0;\n    one_gt.ptr<double>(3)[2] = 0.0;\n    \n    one_gt.ptr<double>(0)[3] = px;\n    one_gt.ptr<double>(1)[3] = py;\n    one_gt.ptr<double>(2)[3] = pz;\n    one_gt.ptr<double>(3)[3] = 1.0;\n\n    all_gt.push_back(one_gt);\n\n  }\n\n  //std::cout<<\"size of all gt \"<<all_gt.size()<<std::endl;\n\n  return all_gt;\n};\n\nvoid NID::set_member_size(){\n    pro_current_ = std::vector<double>(bin_num_,0.0);\n    pro_ref_ = std::vector<double>(bin_num_,0.0);\n    pro_joint_ = std::vector<std::vector<double> >(bin_num_);\n    for(int i = 0; i < bin_num_; i++){\n        pro_joint_[i] = std::vector<double>(bin_num_, 0.0);\n    }\n    intensity_current_ = Eigen::VectorXd::Zero(intensity0_.rows());\n}\n\nvoid NID::ComputeHref(){\n  \n  Eigen::Matrix4d T_cw1 = tf_.inverse();\n  int ob = 0;\n  for(int i = 0 ; i<intensity0_.rows(); i++){\n\n    //decide if there is a valid mapping first, or we won't count this pixel\n    Eigen::Vector4d pw;\n    pw << pw0_[i](0), pw0_[i](1), pw0_[i](2), 1;\n    Eigen::Vector4d p_c = T_cw1 * pw;\n\n    //2d pixel position in current frame\n    double u = fx_ * p_c(0,0) / p_c(2,0) + cx_;\n    double v = fy_ * p_c(1,0) / p_c(2,0) + cy_;\n\n    //bilinear interporlation of pixel. DSO getInterpolatedElement33() function, bilinear interpolation\n    if(u >= 0 && u+3 <= image1_.cols && v >= 0 && v+3 <= image1_.rows){\n      intensity_current_(i,0) = get_interpolated_pixel_value(u,v);\n    }\n    else{\n      ob++;\n      continue;\n    }\n\n    //current frame mutual information probability\n    if(intensity0_(i,0) >= 255)\n      intensity0_(i,0) = 254.999;\n    if(intensity0_(i,0) < 0)\n      intensity0_(i, 0) = 0.0;\n\n    double bin_pos_ref =  intensity0_(i,0) * bin_num_/255.0;\n    \n    int bins_index_ref = floor(bin_pos_ref);\n\n    if(bins_index_ref < 0 || bins_index_ref>bin_num_ -1)\n        std::cout<<\"the intensity is \\n\"<<intensity0_<<std::endl;\n\n    pro_ref_[bins_index_ref] += 1.0;\n\n  }\n\n  for(int i = 0; i < bin_num_ ; i++)\n    pro_ref_[i] /=  (intensity0_.rows()-ob);\n  \n  for(int i = 0; i < bin_num_ ; i++){\n    if(pro_ref_[i] < sigma_)\n      continue;\n    H_ref_ -= pro_ref_[i] * log2(pro_ref_[i]);\n  }\n  \n};\n\n\nvoid NID::ComputeH(){\n  int ob = 0;\n\n  Eigen::Matrix4d T_cw1 = tf_.inverse();\n  for(int i = 0 ; i<intensity0_.rows(); i++){\n\n    Eigen::Vector4d pw;\n    pw << pw0_[i](0), pw0_[i](1), pw0_[i](2), 1;\n    Eigen::Vector4d p_c = T_cw1 * pw;\n\n    if(intensity0_(i,0) >= 255)\n      intensity0_(i,0) = 254.999;\n    if(intensity0_(i,0) < 0)\n      intensity0_(i, 0) = 0.0;\n\n    double bin_pos_ref =  intensity0_(i,0)* bin_num_/255.0;\n    int bins_index_ref = floor(bin_pos_ref);\n    \n    //2d pixel position in current frame\n    double u = fx_ * p_c(0,0) / p_c(2,0) + cx_;\n    double v = fy_ * p_c(1,0) / p_c(2,0) + cy_;\n\n    //bilinear interporlation of pixel. DSO getInterpolatedElement33() function, bilinear interpolation\n    if(u >= 0 && u+3 <= image1_.cols && v >= 0 && v+3 <= image1_.rows){\n      intensity_current_(i,0) = get_interpolated_pixel_value(u,v);\n    }\n    else{\n      ob++;\n      continue;\n    }\n\n    if(intensity_current_(i,0) >= 255)\n      intensity_current_(i,0) = 254.999;\n    if(intensity_current_(i,0) < 0)\n      intensity_current_(i, 0) = 0.0;\n\n    double bin_pos_current = intensity_current_(i,0)* bin_num_/255.0;\n    double pos_cubic_current = bin_pos_current * bin_pos_current * bin_pos_current;\n    double pos_qua_current  = bin_pos_current * bin_pos_current;\n    double bins_index_current = floor(bin_pos_current);\n\n    pro_current_[bins_index_current] += 1.0;\n\n    pro_joint_[bins_index_ref][bins_index_current] += 1.0;\n    \n    \n  }\n\n\n  //if too many points are out of image boundary, we don't use this edge\n  if(intensity0_.rows() - ob < 300){\n    //std::cout<<\"no enough points in the image boundary\"<<std::endl;\n    return;\n  }\n\n  //pro_last_.size() = bin_num\n  for(int i = 0; i < bin_num_ ; i++){\n    pro_current_[i] /= (intensity0_.rows() - ob);\n  }\n\n  for(int i = 0; i < bin_num_; i++)\n    for(int j = 0; j<bin_num_; j++){\n      pro_joint_[i][j] /= (intensity0_.rows() - ob); \n    }\n  \n  for(int i = 0; i < bin_num_ ; i++){\n    if(pro_current_[i] < sigma_)\n      continue;\n    H_current_ -= pro_current_[i] * log2(pro_current_[i]);\n  }\n\n  for(int i = 0; i < bin_num_; i++)\n    for(int j = 0; j<bin_num_; j++){\n      if(pro_joint_[i][j] < sigma_)\n        continue;\n      H_joint_ -= pro_joint_[i][j] * log2(pro_joint_[i][j]);\n    }\n\n    nid_ = (2*H_joint_ - H_ref_ - H_current_)/H_joint_;\n    MI_ = H_ref_ + H_current_ - H_joint_;\n    \n    //if all points from one image is mapped into only one bin so that one of the pro_current_[i] == 1, then H_currrent and H_joint will be 0;\n    //For example, if we have 3 bins, pro_ref is 0 1 0, pro_current is 0 1 0 (or 0 0 1, 1 0 0), then H_ref and current will be 0. Notice we can totally infer one image's state from another. For this perfect matching, we should count the cost as 0\n    if(H_ref_ == 0.0 && H_current_ == 0.0 && H_joint_ == 0.0){\n      MI_ = 0.0;\n      nid_ = 0.0;\n    }\n\n    std::cout<<\"Href, current, joint from standard method is \"<<H_ref_<<\",\"<<H_current_<<\",\"<<H_joint_<<\", MI \"<<MI_<<\", NID \"<<nid_<<std::endl;\n\n}\n\n\n\n\n", "meta": {"hexsha": "ba1de0cb112d037eb8c495dd9a1c126602046ced", "size": 15726, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "NID_standard_property.cpp", "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": "NID_standard_property.cpp", "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": "NID_standard_property.cpp", "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": 32.093877551, "max_line_length": 278, "alphanum_fraction": 0.5724914155, "num_tokens": 4913, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6959583124210896, "lm_q2_score": 0.47657965106367595, "lm_q1q2_score": 0.33167956968850765}}
{"text": "#include <InverseFourierTransform.h>\r\n#include <OpenCLContext.h>\r\n#include <boost/log/trivial.hpp>\r\n\r\nusing namespace neneta;\r\nusing namespace neneta::net;\r\n\r\nInverseFourierTransform::InverseFourierTransform(const std::string& layerId, const conf::ConfigurationReader& confReader, const gpu::OpenCLProgram& program, const gpu::OpenCLContext& oclContext)\r\n    : gpu::OpenCLExecutionPlan(layerId, confReader, program)\r\n    , m_layerParameters(conf::FourierConfiguration(layerId, confReader).getParamSet(layerId))\r\n    , m_oclKernelParameters(m_layerParameters.m_size, m_layerParameters.m_size, getKernelConfiguration().getLWS(1), getKernelConfiguration().getLWS(2))\r\n    , m_clContext(oclContext)\r\n    , m_io()\r\n    , m_reTmp(m_clContext.getContext(), CL_MEM_READ_WRITE, m_layerParameters.m_size*m_layerParameters.m_size*sizeof(cmn::GPUFLOAT))\r\n    , m_imTmp(m_clContext.getContext(), CL_MEM_READ_WRITE, m_layerParameters.m_size*m_layerParameters.m_size*sizeof(cmn::GPUFLOAT))\r\n{\r\n}\r\n\r\nInverseFourierTransform::~InverseFourierTransform()\r\n{\r\n}\r\n\r\nvoid InverseFourierTransform::init()\r\n{\r\n    for(unsigned int channel = 0; channel < m_layerParameters.m_channels; ++channel)\r\n    {\r\n        // plan(\"fftShift\", {m_layerParameters.m_size, m_layerParameters.m_size, m_layerParameters.m_size/2, m_layerParameters.m_size/2}, *reKernelIt, *imKernelIt, (cl_int)m_layerParameters.m_size);\r\n        planFwd(\"rowIndexReverse\", m_oclKernelParameters, m_io.m_reChannels[channel], m_io.m_imChannels[channel], (cl_int)m_layerParameters.m_size, (cl_int)std::log2(m_layerParameters.m_size));\r\n        planFwd(\"columnIndexReverse\", m_oclKernelParameters, m_io.m_reChannels[channel], m_io.m_imChannels[channel], (cl_int)m_layerParameters.m_size, (cl_int)std::log2(m_layerParameters.m_size));\r\n        for(int stage = 1; stage <= std::log2(m_layerParameters.m_size); ++stage)\r\n        {\r\n           planFwd(\"dit_2x2radix_2dfft_1st\", m_oclKernelParameters, m_io.m_reChannels[channel], m_io.m_imChannels[channel], m_reTmp, m_imTmp, (cl_int)m_layerParameters.m_size, (cl_int)stage, (cl_int)1);\r\n           planFwd(\"dit_2x2radix_2dfft_2nd\", m_oclKernelParameters, m_io.m_reChannels[channel], m_io.m_imChannels[channel], m_reTmp, m_imTmp, (cl_int)m_layerParameters.m_size, (cl_int)stage);\r\n        }\r\n        planFwd(\"fftScale\", m_oclKernelParameters, m_io.m_reChannels[channel], m_io.m_imChannels[channel], (cl_int)m_layerParameters.m_size);\r\n    }\r\n}\r\n\r\nvoid InverseFourierTransform::getRe(std::vector<std::vector<cmn::GPUFLOAT>>& re)\r\n{\r\n    cmn::GPUFLOAT* data = new cmn::GPUFLOAT[m_layerParameters.m_size*m_layerParameters.m_size];\r\n    for(unsigned int channel = 0; channel < m_layerParameters.m_channels; ++channel)\r\n    {\r\n        re.emplace_back();\r\n        readFromBuffer(m_clContext.getCommandQueue(), m_io.m_reChannels[channel], m_layerParameters.m_size*m_layerParameters.m_size*sizeof(cmn::GPUFLOAT), data);\r\n        re.back().assign(data, data + m_layerParameters.m_size*m_layerParameters.m_size);\r\n    }\r\n    delete [] data;\r\n}\r\n\r\nvoid InverseFourierTransform::getIm(std::vector<std::vector<cmn::GPUFLOAT>>& im)\r\n{\r\n    cmn::GPUFLOAT* data = new cmn::GPUFLOAT[m_layerParameters.m_size*m_layerParameters.m_size];\r\n    for(unsigned int channel = 0; channel < m_layerParameters.m_channels; ++channel)\r\n    {\r\n        im.emplace_back();\r\n        readFromBuffer(m_clContext.getCommandQueue(), m_io.m_imChannels[channel], m_layerParameters.m_size*m_layerParameters.m_size*sizeof(cmn::GPUFLOAT), data);\r\n        im.back().assign(data, data + m_layerParameters.m_size*m_layerParameters.m_size);\r\n    }\r\n    delete [] data;\r\n}\r\n\r\n\r\nvoid neneta::net::InverseFourierTransform::setInput(gpu::BufferIO input)\r\n{\r\n    m_io = input;\r\n    init();\r\n}\r\n\r\ngpu::BufferIO neneta::net::InverseFourierTransform::getOutput()\r\n{\r\n    return m_io;\r\n}\r\n\r\nvoid InverseFourierTransform::setBkpInput(gpu::BufferIO input)\r\n{\r\n\r\n}\r\n\r\ngpu::BufferIO InverseFourierTransform::getBkpOutput()\r\n{\r\n    return m_io;\r\n}\r\n", "meta": {"hexsha": "8ba168310dc14467d33a349faa82d627b51b0a39", "size": 3969, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "subcomp/neuralnetwork/src/net/InverseFourierTransform.cpp", "max_stars_repo_name": "lekic-ai/neneta", "max_stars_repo_head_hexsha": "45febf7f0edfb03575e30b0f16aa8004470bc3fa", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-12-22T10:07:18.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-22T10:07:18.000Z", "max_issues_repo_path": "subcomp/neuralnetwork/src/net/InverseFourierTransform.cpp", "max_issues_repo_name": "lekic-ai/neneta", "max_issues_repo_head_hexsha": "45febf7f0edfb03575e30b0f16aa8004470bc3fa", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "subcomp/neuralnetwork/src/net/InverseFourierTransform.cpp", "max_forks_repo_name": "lekic-ai/neneta", "max_forks_repo_head_hexsha": "45febf7f0edfb03575e30b0f16aa8004470bc3fa", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-12-22T10:07:23.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-22T10:07:23.000Z", "avg_line_length": 47.25, "max_line_length": 203, "alphanum_fraction": 0.7394809776, "num_tokens": 1022, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.679178699175393, "lm_q2_score": 0.48828339529583464, "lm_q1q2_score": 0.33163168124596915}}
{"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-2013 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 DIRECT_HH\n#define DIRECT_HH\n\n#include <cmath>\n#include <memory>\n#include <type_traits>\n\n#include <boost/timer/timer.hpp>\n\n#include \"dune/istl/operators.hh\"\n#include <dune/istl/solvers.hh>\n\n#include \"fem/istlinterface.hh\"\n#include \"linalg/factorization.hh\"\n\nnamespace Kaskade\n{\n  /// \\internal\n  namespace DirectSolver_Detail\n  {\n    class NoScalar{};\n    class NoFieldType{};\n\n    template <class T>\n    typename T::Scalar hasScalar(typename T::Scalar*);\n    template <class T>\n    NoScalar hasScalar(...);\n\n    template <class T>\n    typename T::field_type hasFieldType(typename T::field_type*);\n    template <class T>\n    NoFieldType hasFieldType(...);\n\n    template <class T>\n    struct HasScalar\n    {\n      typedef decltype(hasScalar<T>(nullptr)) type;\n      static constexpr bool value = !std::is_same<type,NoScalar>::value;\n    };\n\n    template <class T>\n    struct HasFieldType\n    {\n      typedef decltype(hasFieldType<T>(nullptr)) type;\n      static constexpr bool value = !std::is_same<type,NoFieldType>::value;\n    };\n\n\n\n    template <class T>\n    struct ScalarType\n    {\n      typedef typename std::conditional< HasScalar<T>::value, typename HasScalar<T>::type,\n                                           typename std::conditional< HasFieldType<T>::value, typename HasFieldType<T>::type, void>::type >::type type;\n\n    };\n  }\n  /// \\endinternal\n\n  /**\n   * \\ingroup direct\n   * \\brief Dune::InverseOperator and Dune::Preconditioner interface for direct solvers.\n   *\n   * This keeps a factorization during the lifetime of the object, however, due to\n   * shared data, efficient copying is possible.\n   */\n  template <class Domain_, class Range_>\n  class DirectSolver: public Dune::InverseOperator<Domain_,Range_>,\n\t\t      public Dune::Preconditioner<Domain_,Range_>\n  {\n  public:\n    typedef typename DirectSolver_Detail::ScalarType<Domain_>::type Scalar;\n    typedef Domain_ Domain;\n    typedef Range_ Range;\n\n    /**\n     * \\brief Default constructor. \n     * \n     * A default constructed DirectSolver implements a (pretty useless) zero operator.\n     */\n    DirectSolver() {}\n\n    /**\n     * \\brief Constructs a direct solver from an assembled linear operator. \n     * \n     * A copy of the linear operator is held internally, thus the linear\n     * operator object is better not too large.\n     */\n    template <class AssembledGOP>\n    explicit DirectSolver(AssembledGOP const& A, \n                          DirectType directType=DirectType::UMFPACK, MatrixProperties properties=MatrixProperties::GENERAL):\n        solver(getFactorization(directType,properties,A.template get<MatrixAsTriplet<typename AssembledGOP::Scalar> >()))\n    {\n      assert(solver.get()); // make sure the factorization has been successful - otherwise it should have raised an exception\n    }\n\n    /**\n     * \\brief Constructs a direct solver from a triplet matrix. \n     */\n    template <class FieldType>\n    explicit DirectSolver(MatrixAsTriplet<FieldType> const& A, \n                          DirectType directType=DirectType::UMFPACK, MatrixProperties properties=MatrixProperties::GENERAL):\n        solver(getFactorization(directType,properties,A))\n    {\n      assert(solver.get()); // make sure the factorization has been successful - otherwise it should have raised an exception\n    }\n\n    /**\n     * \\brief Constructs a direct solver from a BCRS matrix. \n     * A copy of the linear operator is held internally, thus the linear\n     * operator object is better not too large.\n     */\n    template <class FieldType>\n    explicit DirectSolver(Dune::BCRSMatrix<Dune::FieldMatrix<FieldType,1,1>> const& A, \n                          DirectType directType=DirectType::UMFPACK, MatrixProperties properties=MatrixProperties::GENERAL):\n        solver(getFactorization<FieldType,int>(directType,properties,A))\n    {\n      assert(solver.get()); // make sure the factorization has been successful - otherwise it should have raised an exception\n    }\n\n    /**\n     * \\brief Constructs a direct solver from a NumaBCRS matrix. \n     * A copy of the linear operator is held internally, thus the linear\n     * operator object is better not too large.\n     */\n    template <class FieldType, int n, int m, class Index>\n    explicit DirectSolver(NumaBCRSMatrix<Dune::FieldMatrix<FieldType,n,m>,Index> const& A, \n                          DirectType directType=DirectType::UMFPACK, MatrixProperties properties=MatrixProperties::GENERAL):\n        solver(getFactorization<FieldType,n,m,Index,int>(directType,properties,A))\n    {\n      assert(solver.get()); // make sure the factorization has been successful - otherwise it should have raised an exception\n    }\n\n    /**\n     * \\brief Solves the system for the given right hand side \\arg b.\n     * \n     * The provided right hand side \\arg b is not modified (except possibly via aliasing\n     * \\arg x).\n     */\n    virtual void apply(Domain& x, Range& b, Dune::InverseOperatorResult& res) { apply(x,b,1e-10,res); }\n\n    /**\n     * \\brief Solves the system for the given right hand side \\arg b.\n     * \n     * As an extension to the Dune::InverseOperator interface, we provide const versions of\n     * the apply methods.\n     */\n    void apply(Domain& x, Range& b, Dune::InverseOperatorResult& res) const { apply(x,b,1e-10,res); }\n\n    /**\n     * Solves the system for the given right hand side \\arg b, which is\n     * guaranteed not to be overwritten (except possibly via aliasing\n     * \\arg x).\n     */\n    virtual void apply(Domain& x, Range& b, double reduction, Dune::InverseOperatorResult& res)\n    {\n      const_cast<DirectSolver<Domain,Range> const*>(this)->apply(x,b,res);\n    }\n\n    /**\n     * \\brief Solves the system for the given right hand side \\arg b.\n     * \n     * As an addition to the Dune::InverseOperator interface, we provide const versions of\n     * the apply methods, since the factorization is not modified during the solution phase.\n     */\n    void apply(Domain& x, Range const& b, double reduction, Dune::InverseOperatorResult& res) const\n    {\n      boost::timer::cpu_timer timer;\n\n      std::vector<Scalar> rhs(b.dim());\n      vectorToSequence(b,begin(rhs));\n      apply(rhs,reduction,res);\n      vectorFromSequence(x,begin(rhs));\n    }\n\n    /**\n     * \\brief The input vector v contains the rhs. It will be overwritten by the solution.\n     *\n     * Factorization is not touched by solving. As an addition to the\n     * Dune::InverseOperator interface, we provide const versions of\n     * the apply methods.\n     */\n    void apply(std::vector<Scalar> &v, double reduction, Dune::InverseOperatorResult& res) const\n    {\n      boost::timer::cpu_timer timer;\n\n      // Check for solver availability. Otherwise return zero solution.\n      if (solver) \n      {\n        #ifndef NDEBUG\n        size_t rhsNan = 0, solNan = 0;\n        size_t rhsInf = 0;\n        for (auto const& x: v)\n        {\n          if (std::isnan(x)) ++rhsNan;\n          if (std::isinf(x)) ++rhsInf;\n        }\n        if (rhsNan>0) std::cerr << __FILE__ << ':' << __LINE__ << \": \" << rhsNan << \" rhs entries are nan\\n\";\n        if (rhsInf>0) std::cerr << __FILE__ << ':' << __LINE__ << \": \" << rhsInf << \" rhs entries are inf\\n\";\n        #endif\n        solver->solve(v);\n        #ifndef NDEBUG\n        for (int i=0; i<v.size(); ++i)\n          if (std::isnan(v[i])) ++solNan;\n          if (solNan>0) std::cerr << __FILE__ << ':' << __LINE__ << \": \" << solNan << \" solution entries are nan\\n\";\n          #endif\n      } else\n        std::fill(v.begin(),v.end(),0.0);\n\n      // Write solver statistics. Currently dummy.\n      res.clear();\n      res.iterations = 1;\n      res.reduction = 1e-10; // dummy!\n      res.converged = true;\n      res.conv_rate = 1e-10;\n      res.elapsed = (double)(timer.elapsed().user)/1e9;\n    }\n\n    virtual void  apply (std::vector<Scalar> &v)\n    {\n      Dune::InverseOperatorResult dummy_res;\n      apply(v,1e-10,dummy_res);\n    }\n\n    virtual void pre (Domain &x, Range &b) {}\n\n    virtual void apply (Domain &v, const Range &d)\n    {\n      Dune::InverseOperatorResult dummy_res;\n      apply(v,d, 1e-10,dummy_res);\n    }\n\n    virtual void post (Domain &x) {}\n\n  private:\n    std::shared_ptr<Factorization<Scalar>> solver;\n  };\n\n  //---------------------------------------------------------------------\n  \n  // partial specialization for tiny fixed-size matrices\n  template <class S, int n>\n  class DirectSolver<Dune::FieldVector<S,n>,Dune::FieldVector<S,n>>: public Dune::InverseOperator<Dune::FieldVector<S,n>,Dune::FieldVector<S,n>>,\n                                                                     public Dune::Preconditioner<Dune::FieldVector<S,n>,Dune::FieldVector<S,n>>\n  {\n  public:\n    typedef S Scalar;\n    typedef Dune::FieldVector<S,n> Domain;\n    typedef Dune::FieldVector<S,n> Range;\n\n    /**\n     * \\brief Default constructor. \n     * \n     * A default constructed DirectSolver implements a (pretty useless) zero operator.\n     */\n    DirectSolver() {}\n\n    /**\n     * \\brief Constructs a direct solver from a FieldMatrix matrix. \n     */\n    template <class FieldType>\n    explicit DirectSolver(Dune::FieldMatrix<FieldType,n,n> const& A):\n        inverse(A)\n    {\n      inverse.invert();\n    }\n\n    /**\n     * \\brief Solves the system for the given right hand side \\arg b.\n     * \n     * The provided right hand side \\arg b is not modified (except possibly via aliasing\n     * \\arg x).\n     */\n    virtual void apply(Domain& x, Range& b, Dune::InverseOperatorResult& res) { apply(x,b,1e-10,res); }\n\n    /**\n     * \\brief Solves the system for the given right hand side \\arg b.\n     * \n     * As an extension to the Dune::InverseOperator interface, we provide const versions of\n     * the apply methods.\n     */\n    void apply(Domain& x, Range& b, Dune::InverseOperatorResult& res) const { apply(x,b,1e-10,res); }\n\n    /**\n     * Solves the system for the given right hand side \\arg b, which is\n     * guaranteed not to be overwritten (except possibly via aliasing\n     * \\arg x).\n     */\n    virtual void apply(Domain& x, Range& b, double reduction, Dune::InverseOperatorResult& res)\n    {\n      const_cast<DirectSolver<Domain,Range> const*>(this)->apply(x,b,res);\n    }\n\n    /**\n     * \\brief Solves the system for the given right hand side \\arg b.\n     * \n     * As an addition to the Dune::InverseOperator interface, we provide const versions of\n     * the apply methods, since the factorization is not modified during the solution phase.\n     */\n    void apply(Domain& x, Range const& b, double reduction, Dune::InverseOperatorResult& res) const\n    {\n      x = inverse*b;\n      \n      // Write solver statistics. Currently dummy.\n      res.clear();\n      res.iterations = 1;\n      res.reduction = 1e-10; // dummy!\n      res.converged = true;\n      res.conv_rate = 1e-10;\n      res.elapsed = 0;\n    }\n\n\n    virtual void        pre (Domain &x, Range &b) {}\n\n    virtual void        apply (Domain &v, const Range &d)\n    {\n      v = inverse*d;\n    }\n\n    virtual void        post (Domain &x) {}\n\n  private:\n    Dune::FieldMatrix<Scalar,n,n> inverse;\n  };\n\n  //---------------------------------------------------------------------\n\n  /**\n   * \\ingroup linalgsolution\n   * \\brief Dune::LinearOperator interface for inverse operators.\n   */\n  template <class InverseOperator>\n  class InverseLinearOperator: public Dune::LinearOperator<typename InverseOperator::Range, typename InverseOperator::Domain>\n  {\n  public:\n    typedef typename InverseOperator::Domain Domain;\n    typedef typename InverseOperator::Range Range;\n    typedef typename InverseOperator::Scalar Scalar;\n\n    InverseLinearOperator() = default;\n\n    InverseLinearOperator(InverseOperator const& op_) : op(op_)\n    {}\n\n    virtual void apply(Domain const& x, Range& y) const\n    {\n      Dune::InverseOperatorResult result;\n      Domain rhs(x);\n      op.apply(y,rhs,result);\n    }\n\n    virtual void applyscaleadd(Scalar alpha, Domain const& x, Range& y) const\n    {\n      Range ynew(y);\n      apply(x,ynew);\n      y.axpy(alpha,ynew);\n    }\n\n  private:\n    InverseOperator op;\n  };\n\n  //---------------------------------------------------------------------\n\n  /**\n   * \\ingroup direct\n   * \\brief convenience function for constructing a DirectInverseOperator\n   */\n  template <class GOP, int firstRow, int lastRow, int firstCol, int lastCol>\n  InverseLinearOperator<DirectSolver<typename AssembledGalerkinOperator<GOP,firstRow,lastRow,firstCol,lastCol>::Domain,\n                                     typename AssembledGalerkinOperator<GOP,firstRow,lastRow,firstCol,lastCol>::Range> >\n  directInverseOperator(AssembledGalerkinOperator<GOP,firstRow,lastRow,firstCol,lastCol> const& A,\n                        DirectType directType=DirectType::UMFPACK, MatrixProperties properties=MatrixProperties::GENERAL)\n  {\n    typedef typename AssembledGalerkinOperator<GOP,firstRow,lastRow,firstCol,lastCol>::Domain Domain;\n    typedef typename AssembledGalerkinOperator<GOP,firstRow,lastRow,firstCol,lastCol>::Range Range;\n    return InverseLinearOperator<DirectSolver<Domain,Range> >(DirectSolver<Domain,Range>(A,directType,properties));\n  }\n\n  template <class Matrix, class Domain, class Range>\n  InverseLinearOperator<DirectSolver<Domain,Range> >\n  directInverseOperator(MatrixRepresentedOperator<Matrix,Domain,Range> const& A,\n                        DirectType directType=DirectType::UMFPACK, MatrixProperties properties=MatrixProperties::GENERAL)\n  {\n    return InverseLinearOperator<DirectSolver<Domain,Range> >(DirectSolver<Domain,Range>(A,directType,properties));\n  }\n\n} // namespace Kaskade\n\n//---------------------------------------------------------------------\n\n#endif\n", "meta": {"hexsha": "797a918906bcf8887c44b8bbb1575ac9bd9b5872", "size": 14491, "ext": "hh", "lang": "C++", "max_stars_repo_path": "Kaskade/linalg/direct.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/direct.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/direct.hh", "max_forks_repo_name": "chenzongxiong/streambox", "max_forks_repo_head_hexsha": "76f95780d1bf6c02731e39d8ac73937cea352b95", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-12-03T04:41:18.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-11T21:44:42.000Z", "avg_line_length": 35.6921182266, "max_line_length": 151, "alphanum_fraction": 0.6142433234, "num_tokens": 3466, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6477982179521103, "lm_q2_score": 0.5117166047041652, "lm_q1q2_score": 0.3314891046238627}}
{"text": "#ifndef CMAESAG_HPP\n#define CMAESAG_HPP\n\n#include <vector>\n#include <string>\n#include <type_traits>\n#include <boost/serialization/list.hpp>\n#include <boost/serialization/set.hpp>\n#include <boost/serialization/vector.hpp>\n#include <boost/functional/hash.hpp>\n\n#include \"arch/ARLAgent.hpp\"\n#include \"bib/Seed.hpp\"\n#include \"bib/Utils.hpp\"\n#include <bib/MetropolisHasting.hpp>\n#include <bib/XMLEngine.hpp>\n#include <bib/Combinaison.hpp>\n#include \"nn/MLP.hpp\"\n#include \"nn/DevMLP.hpp\"\n#include \"nn/DODevMLP.hpp\"\n#include \"cmaes_interface.h\"\n\ntemplate<typename NN = MLP>\nclass CMAESAg : public arch::ARLAgent<arch::AgentProgOptions> {\n public:\n  CMAESAg(unsigned int _nb_motors, unsigned int _nb_sensors)\n    : arch::ARLAgent<arch::AgentProgOptions>(_nb_motors, _nb_sensors), nb_sensors(_nb_sensors) {\n\n  }\n\n  virtual ~CMAESAg() {\n    cmaes_exit(evo);\n    delete evo;\n    delete ann;\n    delete hidden_unit_a;\n  }\n\n  const std::vector<double>& _run(double, const std::vector<double>& sensors,\n                                  bool, bool, bool) override {\n\n    vector<double>* next_action = ann->computeOut(sensors);\n\n//  CMA-ES already implement exploration in parameter space\n    last_action.reset(next_action);\n\n    return *next_action;\n  }\n\n\n  void _unique_invoke(boost::property_tree::ptree* pt, boost::program_options::variables_map* vm) override {\n    hidden_unit_a               = bib::to_array<uint>(pt->get<std::string>(\"agent.hidden_unit_a\"));\n    actor_hidden_layer_type     = pt->get<uint>(\"agent.actor_hidden_layer_type\");\n    actor_output_layer_type     = pt->get<uint>(\"agent.actor_output_layer_type\");\n    batch_norm                  = pt->get<uint>(\"agent.batch_norm\");\n    population                  = pt->get<uint>(\"agent.population\");\n    initial_deviation           = pt->get<double>(\"agent.initial_deviation\");\n\n    check_feasible = true;\n    ignore_null_lr = true;\n    racing = false;\n    error_count = 0;\n    xbestever_score = std::numeric_limits<double>::max();\n\n    try {\n      check_feasible = pt->get<bool>(\"agent.check_feasible\");\n    } catch(boost::exception const& ) {\n    }\n\n    try {\n      ignore_null_lr = pt->get<bool>(\"agent.ignore_null_lr\");\n    } catch(boost::exception const& ) {\n    }\n\n    try {\n      racing = pt->get<bool>(\"agent.racing\");\n    } catch(boost::exception const& ) {\n    }\n\n    episode = 0;\n\n    ann = new NN(nb_sensors, *hidden_unit_a, nb_motors, 0.1, 1, actor_hidden_layer_type, actor_output_layer_type,\n                 batch_norm);\n    if(std::is_same<NN, DevMLP>::value)\n      ann->exploit(pt, static_cast<CMAESAg *>(old_ag)->ann);\n    else if(std::is_same<NN, DODevMLP>::value)\n      ann->exploit(pt, nullptr);\n\n//     const uint dimension = (nb_sensors+1)*hidden_unit_a->at(0) + (hidden_unit_a->at(0)+1)*nb_motors;\n    const uint dimension = ann->number_of_parameters(ignore_null_lr);\n    double* startx  = new double[dimension];\n    double* deviation  = new double[dimension];\n    for(uint j=0; j< dimension; j++) {\n      deviation[j] = initial_deviation;\n    }\n    ann->copyWeightsTo(startx, ignore_null_lr);\n\n    evo = new cmaes_t;\n    arFunvals = cmaes_init(evo, dimension, startx, deviation, 0, population, NULL/*\"config.cmaes.ini\"*/);\n    delete[] startx;\n    delete[] deviation;\n//     evo->sp.stopTolFun = 1e-150;\n//     evo->sp.stopTolFunHist = 1e-150;\n//     evo->sp.stopTolUpXFactor = 1e50;\n\n    printf(\"%s\\n\", cmaes_SayHello(evo));\n    new_population();\n    LOG_DEBUG(cmaes_Get(evo, \"lambda\") << \" \" << dimension << \" \" << population << \" \" << cmaes_Get(evo, \"N\"));\n    if (population < 2)\n      LOG_DEBUG(\"population too small, changed to : \" << (4+(int)(3*log((double)dimension))));\n\n    if(vm->count(\"continue\") > 0) {\n      uint continue_save_each          = DEFAULT_AGENT_SAVE_EACH_CONTINUE;\n      try {\n        continue_save_each            = pt->get<uint>(\"simulation.continue_save_each\");\n      } catch(boost::exception const& ) {\n      }\n\n      if(continue_save_each % (int) cmaes_Get(evo, \"lambda\") != 0) {\n        LOG_ERROR(\"continue_save_each must be a multiple of the population size !\");\n        exit(1);\n      }\n    }\n    \n    if(std::is_same<NN, DODevMLP>::value){\n      try {\n        if(pt->get<double>(\"devnn.ewc\") >= 0.){\n          LOG_ERROR(\"CMA-ES doesn't rely on gradient (difficult to compute Fisher Matrix)\");\n          exit(1);\n        }\n      } catch(boost::exception const& ) {\n      }\n    }\n  }\n\n  bool is_feasible(const double* parameters) {\n    for(uint i=0; i < (uint) cmaes_Get(evo, \"dim\"); i++)\n      if(fabs(parameters[i]) >= 500.f) {\n        return false;\n      }\n\n    return true;\n  }\n\n  void new_population() {\n    const char * terminate =  cmaes_TestForTermination(evo);\n    if(terminate) {\n      LOG_INFO(\"mismatch \"<< terminate);\n      error_count++;\n\n      if(error_count > 20 && racing) {\n        LOG_FILE(DEFAULT_END_FILE, \"-1\");\n        exit(0);\n      }\n    }\n    //ASSERT(!cmaes_TestForTermination(evo), \"mismatch \"<< cmaes_TestForTermination(evo));\n\n    current_individual = 0;\n    pop = cmaes_SamplePopulation(evo);\n\n    if(check_feasible) {\n      //check that the population is feasible\n      bool allfeasible = true;\n      for (int i = 0; i < cmaes_Get(evo, \"popsize\"); ++i)\n        while (!is_feasible(pop[i])) {\n          cmaes_ReSampleSingle(evo, i);\n          allfeasible = false;\n        }\n\n      if(!allfeasible)\n        LOG_INFO(\"non feasible solution produced\");\n    }\n  }\n\n  void start_instance(bool learning) override {\n    last_action = nullptr;\n    scores.clear();\n\n    if(std::is_same<NN, DODevMLP>::value && learning) {\n      auto dodevmlp = static_cast<DODevMLP *>(ann);\n      bool reset_operator, changed;\n      std::tie(reset_operator, changed) = dodevmlp->inform(episode, last_sum_weighted_reward);\n      if(reset_operator && changed) {\n        LOG_INFO(\"reset learning catched\");\n\n        if(!dodevmlp->ewc_enabled()){\n          const double* parameters = nullptr;\n          parameters = getBestSolution();\n          loadPolicyParameters(parameters);\n        }\n\n        cmaes_exit(evo);\n        delete evo;\n\n        const uint dimension = ann->number_of_parameters(ignore_null_lr);\n        double* startx  = new double[dimension];\n        double* deviation  = new double[dimension];\n        for(uint j=0; j< dimension; j++) {\n          deviation[j] = initial_deviation;\n        }\n        ann->copyWeightsTo(startx, ignore_null_lr);\n\n        xbestever_score = std::numeric_limits<double>::max();\n        cmaes_UpdateDistribution_done_once = false;\n        evo = new cmaes_t;\n        arFunvals = cmaes_init(evo, dimension, startx, deviation, 0, population, NULL/*\"config.cmaes.ini\"*/);\n        delete[] startx;\n        delete[] deviation;\n        new_population();\n      }\n    }\n\n    if(!justLoaded) {\n      //put individual into NN\n      const double* parameters = nullptr;\n      if(learning || !cmaes_UpdateDistribution_done_once)\n        parameters = pop[current_individual];\n      else\n        parameters = getBestSolution();\n\n      loadPolicyParameters(parameters);\n    }\n\n    if(learning)\n      episode++;\n    //LOG_FILE(\"policy_exploration\", ann->hash());\n  }\n\n  void restoreBest() override {\n    const double* parameters = getBestSolution();\n    loadPolicyParameters(parameters);\n  }\n\n  void end_episode(bool) override {\n    scores.push_back(-sum_weighted_reward + ann->ewc_cost());\n  }\n\n  void end_instance(bool learning) override {\n    if(learning) {\n      arFunvals[current_individual] = std::accumulate(scores.begin(), scores.end(), 0.f) / scores.size();\n      \n      //TODO with instance\n      ann->update_best_param_previous_task(sum_weighted_reward);\n\n      current_individual++;\n      if(current_individual >= cmaes_Get(evo, \"lambda\")) {\n        cmaes_UpdateDistribution(evo, arFunvals);\n        cmaes_UpdateDistribution_done_once=true;\n        new_population();\n      }\n    }\n\n    justLoaded = false;\n  }\n\n  void save(const std::string& path, bool save_best, bool) override {\n    if(!save_best || !cmaes_UpdateDistribution_done_once) {\n      ann->save(path+\".actor\");\n    } else if(save_best && -sum_weighted_reward < xbestever_score ) {\n      xbestever_score = -sum_weighted_reward;\n      ann->save(path+\".actor\");\n    }\n//     else {\n//       //TODO : check this part, apparently it modify the learning\n//       LOG_WARNING(\"be careful it might be a problem here\");\n//       NN* to_be_restaured = new NN(*ann, false);\n//       const double* parameters = getBestSolution();\n//       loadPolicyParameters(parameters);\n//       ann->save(path+\".actor\");\n//       delete ann;\n//       ann = to_be_restaured;\n//     }\n  }\n\n  void load(const std::string& path) override {\n    justLoaded = true;\n    ann->load(path+\".actor\");\n  }\n\n  void save_run() override {\n    if(current_individual == 1) {\n      const double* xbptr_ = getBestSolution();\n      std::vector<double> xbestever_((int)cmaes_Get(evo, \"N\"));\n      xbestever_.assign(xbptr_, xbptr_ + (int)cmaes_Get(evo, \"N\"));\n      double bs = getBestScore();\n\n      struct algo_state st = {scores, justLoaded, cmaes_UpdateDistribution_done_once,\n               current_individual, episode, error_count, bs, xbestever_\n      };\n      bib::XMLEngine::save(st, \"algo_state\", \"continue.algo_state.data\");\n      cmaes_WriteToFile(evo, \"resume\", \"continue.cmaes.data\");\n    }\n  }\n\n  void load_previous_run() override {\n    auto algo_state_ = bib::XMLEngine::load<struct algo_state>(\"algo_state\", \"continue.algo_state.data\");\n    scores = algo_state_->scores;\n    justLoaded = algo_state_->justLoaded;\n    cmaes_UpdateDistribution_done_once = algo_state_->cmaes_UpdateDistribution_done_once;\n    current_individual = algo_state_->current_individual;\n    episode = algo_state_->episode;\n    error_count = algo_state_->error_count;\n    xbestever_score = algo_state_->xbestever_score;\n    xbestever_ptr = algo_state_->xbestever_ptr;\n    delete algo_state_;\n    char file_[] = \"continue.cmaes.data\";\n    cmaes_resume_distribution(evo, file_);\n    new_population();\n  }\n\n  MLP* getNN() {\n    return ann;\n  }\n\n protected:\n  void _display(std::ostream& out) const override {\n    out << std::setw(8) << std::fixed << std::setprecision(5) << sum_weighted_reward << \" \" << ann->ewc_cost();\n  }\n\n  void _dump(std::ostream& out) const override {\n    out << std::setw(8) << std::fixed << std::setprecision(5) << sum_weighted_reward;\n  }\n\n private:\n  void loadPolicyParameters(const double* parameters) {\n    ann->copyWeightsFrom(parameters, ignore_null_lr);\n  }\n\n  const double* getBestSolution() {\n    //TODO:\n//     LOG_DEBUG(cmaes_Get(evo, \"fbestever\")  << \" \" << xbestever_score);\n    if(cmaes_Get(evo, \"fbestever\") < xbestever_score)\n      return cmaes_GetPtr(evo, \"xbestever\");\n    else\n      return xbestever_ptr.data();\n  }\n\n  double getBestScore() {\n    return std::min(cmaes_Get(evo, \"fbestever\"), xbestever_score);\n  }\n\n private:\n  //initilized by constructor\n  uint nb_sensors;\n\n  //initialized by invoke\n  std::vector<uint>* hidden_unit_a;\n  uint population, actor_hidden_layer_type, actor_output_layer_type, batch_norm;\n  double initial_deviation;\n  bool check_feasible;\n  bool ignore_null_lr;\n  bool racing;\n  MLP* ann;\n  cmaes_t* evo;\n  double *arFunvals;\n\n  //internal mecanisms\n  std::shared_ptr<std::vector<double>> last_action;\n  std::list<double> scores;\n  double *const *pop;\n  bool justLoaded = false;\n  bool cmaes_UpdateDistribution_done_once = false;\n  uint current_individual;\n  uint episode;\n  uint error_count;\n  double xbestever_score;\n  std::vector<double> xbestever_ptr;\n\n  struct algo_state {\n    std::list<double> scores;\n    bool justLoaded;\n    bool cmaes_UpdateDistribution_done_once;\n    uint current_individual;\n    uint episode;\n    uint error_count;\n    double xbestever_score;\n    std::vector<double> xbestever_ptr;\n\n    friend class boost::serialization::access;\n    template <typename Archive>\n    void serialize(Archive& ar, const unsigned int) {\n      ar& BOOST_SERIALIZATION_NVP(scores);\n      ar& BOOST_SERIALIZATION_NVP(justLoaded);\n      ar& BOOST_SERIALIZATION_NVP(cmaes_UpdateDistribution_done_once);\n      ar& BOOST_SERIALIZATION_NVP(current_individual);\n      ar& BOOST_SERIALIZATION_NVP(episode);\n      ar& BOOST_SERIALIZATION_NVP(error_count);\n      ar& BOOST_SERIALIZATION_NVP(xbestever_score);\n      ar& BOOST_SERIALIZATION_NVP(xbestever_ptr);\n    }\n  };\n};\n\n#endif\n\n", "meta": {"hexsha": "c1ffbff72f12de79b3bba01e7899a076c215658a", "size": 12302, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "agent/cmaes/include/CMAESAg.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/cmaes/include/CMAESAg.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/cmaes/include/CMAESAg.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": 31.1443037975, "max_line_length": 113, "alphanum_fraction": 0.6533084051, "num_tokens": 3223, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7248702761768248, "lm_q2_score": 0.4571367168274948, "lm_q1q2_score": 0.33136481817731306}}
{"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// Currently needs -DMTL_DEEP_COPY_CONSTRUCTOR !!!\n\n#include <iostream>\n#include <boost/numeric/mtl/mtl.hpp>\n\n\ntemplate <typename T>\nstruct as {};\n\ntemplate <>\nstruct as<int> \n{\n\ttypedef mtl::ashape::scal  type;\n};\n\ntemplate <typename V>\nstruct as<mtl::compressed2D<V> >\n{\n\ttypedef mtl::ashape::mat<typename as<V>::type>   type;\n};\n\ntemplate <typename V>\nstruct as<mtl::dense2D<V> >\n{\n\ttypedef mtl::ashape::mat<typename as<V>::type>   type;\n};\n\nint main(int, char**)\n{\n    using namespace std;\n\n#if 0  \n    cout << typeid(as<int>::type).name() << endl;\n    cout << typeid(as<mtl::compressed2D<int> >::type).name() << endl;\n    cout << typeid(as<mtl::compressed2D<mtl::dense2D<int> > >::type).name() << endl;\n\n    cout << typeid(mtl::ashape::ashape<int>::type).name() << endl;\n    cout << typeid(mtl::ashape::ashape<mtl::compressed2D<int> >::type).name() << endl;\n    cout << typeid(mtl::ashape::ashape<typename mtl::compressed2D<mtl::dense2D<int> >::value_type >::type).name() << endl;\n#endif\n\n    // Define a 6x5 sparse matrix in a 3x3 block-sparse\n    typedef mtl::dense2D<double>    m_t;\n    typedef mtl::compressed2D<m_t>  matrix_t;\n    matrix_t                        A(3, 3);\n    {\n\tmtl::mat::inserter<matrix_t> ins(A);\n\n\t// First block\n\tm_t  b1(1, 1);\n\tb1(0, 0)= 1.0;\n\tins(0, 2) << b1;\n\n\t// Second block\n\tm_t  b2(2, 3);\n\tb2=       0.0;\n\tb2[0][1]= 2.0;\n\tb2[1][2]= 3.0;\n\tins(1, 0) << b2;\n\n\tm_t b3(3, 1);\n\tb3= 0.0;\n\tb3[1][0]= 4.0;\n\tins(2, 1) << b3;\n    }\n    // cout << \"A is \" << A << endl; // doesn't works and before it was completely unreadable anyway\n\n    /* Should be something like this:\n\n       [                   [ 1]] // b1\n       [[  0   2   0]          ] // b2\n       [[  0   0   3]          ]\n       [             [  0]     ] // b3\n       [             [  4]     ]\n       [             [  0]     ]\n\n    */\n\n    // Access blocks (they are read-only) for sparse matrices\n    cout << \"The block A(1, 0) is \\n\" << A(1, 0) << endl;\n    cout << \"The block A[1][0] is \\n\" << A[1][0] << endl;\n\n    // Access elements in blocks \n    cout << \"In block A(1, 0), the element (0, 1) is \" << A(1, 0)(0, 1) << endl;\n    cout << \"In block A(1, 0), the element [0][1] is \" << A(1, 0)[0][1] << endl;\n    cout << \"In block A[1][0], the element [0][1] is \" << A[1][0][0][1] << endl << endl;\n\n\n    typedef mtl::dense_vector<double> v_t;\n    typedef mtl::dense_vector<v_t>    vector_t;\n    vector_t                          x(3), y(3);\n\n    // x= [[0, 5, 3], [1], [8]]^T\n    x[0]= v_t(3, 0.0); x[0][1]= 5.0; x[0][2]= 3.0; // first block of x = [0, 5, 3]^T\n    x[1]= v_t(1, 1.0);                             // second block of x \n    x[2]= v_t(1, 8.0);                             // third block\n\n    cout << \"x is \" << x << endl; \n\n    // For y we would only need the vector sizes [[?], [?, ?], [?, ?, ?]]^T\n    // To avoid valgrind complains we set to 0\n    y[0]= v_t(1, 0.0); y[1]= v_t(2, 0.0); y[2]= v_t(3, 0.0);\n\n    cout << \"y is \" << y << endl; \n\n    // Block-sparse matrix * blocked vector !!!\n    y= A*x;\n\n    cout << \"y after multiplication is \" << y << endl\n\t << \"Should be [[8], [10, 9], [0, 4, 0]]^T.\" << endl; \n\n    return 0;\n}\n", "meta": {"hexsha": "5da82c506110b75b797853b5dd960ffaf9e0a298", "size": 3581, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/mtl/test/variable_size_block_sparse_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/variable_size_block_sparse_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/variable_size_block_sparse_test.cpp", "max_forks_repo_name": "lit-uriy/mtl4-mirror", "max_forks_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_forks_repo_licenses": ["MTLL"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2019-12-01T13:40:30.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-14T08:39:54.000Z", "avg_line_length": 28.4206349206, "max_line_length": 122, "alphanum_fraction": 0.5255515219, "num_tokens": 1267, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5736784074525098, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.3312966214110021}}
{"text": "#include <iostream>\n#include <cmath>\n#include <typeinfo>\n#include <type_traits>\n#include <boost/numeric/mtl/mtl.hpp>\n\n\n// namespace to avoid ambiguities with mtl\nnamespace tst {\n\n    template <typename T>\n    struct is_const\n    {\n\tstatic const bool value= false;\n    };\n\n    template <typename T>\n    struct is_const<const T>\n    {\n\tstatic const bool value= true;\n    };\n\n    template <bool Condition, typename ThenType, typename ElseType>\n    struct conditional\n    {\n\tusing type= ThenType;\n    };\n\n    template <typename ThenType, typename ElseType>\n    struct conditional<false, ThenType, ElseType>\n    {\n\tusing type= ElseType;\n    };\n\n    template <bool Condition, typename ThenType, typename ElseType>\n    using conditional_t= typename conditional<Condition, ThenType, ElseType>::type;\n\n    template <typename T>\n    struct is_matrix\n      : std::false_type\n    {};\n    \n    template <typename Value, typename Para>\n    struct is_matrix<mtl::dense2D<Value, Para> >\n      : std::true_type\n    {};\n\n#if 1\n    template <typename T>\n    struct is_matrix<const T>\n      : is_matrix<T> {};\n#endif\n\n\n#if 0\n    template <typename Matrix>\n    class transposed_view\n    {\n      public:\n\tusing value_type= typename Matrix::value_type;\n\tusing size_type=  typename Matrix::size_type;\n\t\n\t// typedef typename mtl::Collection<Matrix>::value_type  value_type;\n\t// typedef typename mtl::Collection<Matrix>::size_type   size_type;\n\n\texplicit transposed_view(Matrix& A) : ref(A) {}\n\t\n\tvalue_type& operator()(size_type r, size_type c) { return ref(c, r); }\n\tconst value_type& operator()(size_type r, size_type c) const { return ref(c, r); }\n\t\n      private:\n\tMatrix& ref;\n    };\n\n    template <typename Matrix>\n    class const_transposed_view\n    {\n      public:\n\tusing value_type= typename Matrix::value_type;\n\tusing size_type=  typename Matrix::size_type;\n\n\texplicit const_transposed_view(const Matrix& A) : ref(A) {}\n\t\n\tconst value_type& operator()(size_type r, size_type c) const { return ref(c, r); }\n\t\n      private:\n\tconst Matrix& ref;\n    };\n\n    template <typename Matrix>\n    inline const_transposed_view<Matrix> trans(const Matrix& A)\n    {\n\treturn const_transposed_view<Matrix>(A);\n    }\n\n#else\n    template <typename Matrix>\n    class transposed_view\n    {\n\tstatic_assert(is_matrix<Matrix>::value, \"template argument is not a Matrix\");\n      public:\n\tusing value_type= typename Matrix::value_type;\n\tusing size_type=  typename Matrix::size_type;\n\n      private:\n\tusing vref_type= conditional_t<is_const<Matrix>::value,\n\t\t\t\t       const value_type&,\n\t\t\t\t       value_type&>;\n      public:\n\texplicit transposed_view(Matrix& A) : ref(A) {}\n\t\n\tvref_type operator()(size_type r, size_type c) { return ref(c, r); }\n\tconst value_type& operator()(size_type r, size_type c) const { return ref(c, r); }\n\t\n      private:\n\tMatrix& ref;\n    };\n#endif\n\n    template <typename Matrix>\n    transposed_view<Matrix> inline trans(Matrix& A)\n    {\n\treturn transposed_view<Matrix>(A);\n    }\n\n    template <typename Matrix>\n    struct is_matrix<transposed_view<Matrix> >\n      : is_matrix<Matrix>\n    {};\n    \n}\n\ntemplate <int M>\nvoid f()\n{\n    typedef typename tst::conditional<M < 100, double, float>::type & value_type;\n    typedef const typename tst::conditional<M < 100, const double, const float>::type const_value_type;\n    std::cout << \"typeid = \" << typeid(value_type).name() << '\\n';\n}\n\nint main (int argc, char* argv[]) \n{\n    // const double eps= 0.00000001;\n    const int n = 10;\n    typedef tst::conditional<n < 100, double, float>::type& value_type;\n    typedef const tst::conditional<n < 100, double, float>::type const_value_type;\n    std::cout << \"typeid = \" << typeid(value_type).name() << '\\n';\n    f<17>();\n\n    mtl::dense2D<float> A= {{2, 3, 4},\n\t\t\t    {5, 6, 7},\n\t\t\t    {8, 9, 10}};    \n    std::cout << \"trans(A) is\\n\" << trans(A);\n\n    trans(A)[2][0]= 4.5;\n    std::cout << \"trans(A) is\\n\" << trans(A);\n\n    const mtl::dense2D<float> B(A);\n    std::cout << \"trans(B) is\\n\" << trans(B);\n\n    tst::transposed_view<mtl::dense2D<float> >  At(A);\n    At(2, 0)= 4.5;\n\n    std::cout << \"tst::trans(A)(2, 0) = \" << tst::trans(A)(2, 0) << '\\n';\n    tst::trans(A)(2, 0)= 4.6;\n    std::cout << \"trans(A) after modification is\\n\" << trans(A);\n\n    std::cout << \"typeid of trans(A) = \" << typeid(tst::trans(A)).name() << '\\n';\n    std::cout << \"typeid of trans(B) = \" << typeid(tst::trans(B)).name() << '\\n';\n    // int ta= trans(A);\n    // int tb= trans(B);\n    // int tar= trans(A).ref; \n    // int tbr= trans(B).ref;\n\n    std::cout << \"tst::trans(B)(2, 0) = \" << tst::trans(B)(2, 0) << '\\n';\n    // tst::trans(B)(2, 0)= 4.6;\n    \n    const tst::transposed_view<const mtl::dense2D<float> >  Bt(B);\n    std::cout << \"Bt(2, 0) = \" << Bt(2, 0) << '\\n';\n\n    return 0 ;\n}\n", "meta": {"hexsha": "cf984cac33ee5c6f1510f7f7dc243030ac8d1243", "size": 4757, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "DMCpp/GottschlingRepo/c++11/trans_const.cpp", "max_stars_repo_name": "tzaffi/cpp", "max_stars_repo_head_hexsha": "43d99e70d8fa712f90ea0f6147774e4e0f2b11da", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 27.0, "max_stars_repo_stars_event_min_datetime": "2017-12-27T14:35:02.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-31T14:28:17.000Z", "max_issues_repo_path": "DMCpp/GottschlingRepo/c++11/trans_const.cpp", "max_issues_repo_name": "tzaffi/cpp", "max_issues_repo_head_hexsha": "43d99e70d8fa712f90ea0f6147774e4e0f2b11da", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 52.0, "max_issues_repo_issues_event_min_datetime": "2017-12-07T14:54:33.000Z", "max_issues_repo_issues_event_max_datetime": "2018-06-28T02:14:07.000Z", "max_forks_repo_path": "DMCpp/GottschlingRepo/c++11/trans_const.cpp", "max_forks_repo_name": "tzaffi/cpp", "max_forks_repo_head_hexsha": "43d99e70d8fa712f90ea0f6147774e4e0f2b11da", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 13.0, "max_forks_repo_forks_event_min_datetime": "2019-06-29T02:58:27.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-07T08:52:22.000Z", "avg_line_length": 25.9945355191, "max_line_length": 103, "alphanum_fraction": 0.6237124238, "num_tokens": 1341, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5736784074525096, "lm_q2_score": 0.5774953651858117, "lm_q1q2_score": 0.3312966214110019}}
{"text": "#ifndef __Rocket_Flight_DM_HH__\n#define __Rocket_Flight_DM_HH__\n/********************************* TRICK HEADER *******************************\nPURPOSE:\n      (Describe the Rocket Flgiht Dynamics Module Variables and Algorithm)\nLIBRARY DEPENDENCY:\n      ((../src/Rocket_Flight_DM.cpp)\n       (../../math/src/nrutil.cpp))\nPROGRAMMERS:\n      (((Lai Jun Xu) () () () ))\n*******************************************************************************/\n#include <armadillo>\n#include \"Module.hh\"\n#include \"Time_management.hh\"\n#include \"aux.hh\"\n#include \"global_constants.hh\"\n#include \"icf_trx_ctrl.h\"\n#include \"simgen_remote.h\"\n\nclass Rocket_Flight_DM : public Dynamics {\n  TRICK_INTERFACE(Rocket_Flight_DM);\n\n public:\n  Rocket_Flight_DM(Data_exchang &input);\n  Rocket_Flight_DM(const Rocket_Flight_DM &other);\n  Rocket_Flight_DM &operator=(const Rocket_Flight_DM &other);\n  struct icf_ctrlblk_t *dm_icf_info_hook;\n  int enqueue_to_simgen_buffer(struct icf_ctrlblk_t *C, double ext_porlation);\n  int stand_still_motion_data(struct icf_ctrlblk_t *C, double ext_porlation);\n\n  virtual void init();\n  virtual void algorithm(double int_step);\n  void load_location(double lonx_in, double latx_in, double alt_in);\n  void load_geodetic_velocity(double alpha0x, double beta0x, double dvbe);\n  void load_angle(double yaw, double roll, double pitch);\n  void load_angular_velocity(double ppx_in, double qqx_in, double rrx_in);\n  void update_diagnostic_attributes(double int_step);\n  void Interpolation_Extrapolation(double T, double int_step,\n                                   double ext_porlation);\n  void set_reference_point(double rp);\n\n  arma::vec3 get_VBED();\n  void set_liftoff(int in);\n\n  struct TX_data {\n    double SBEE[3];\n    double VBEE[3];\n    double ABEE[3];\n    double JBEE[3];\n    double psibd;\n    double thtbd;\n    double phibd;\n    double WBEB[3];\n  } TX_data_forward;\n\n  void collect_forces_and_propagate();\n  void set_DOF(int ndof);\n  void set_aero_flag(unsigned int in);\n\n private:\n  double get_ppx();\n  double get_qqx();\n  double get_rrx();\n  double get_psibdx();\n  double get_thtbdx();\n  double get_phibdx();\n  double get_dvbe();\n  double get_dbi();\n  double get_dvbi();\n  double get_thtvdx();\n  double get_psivdx();\n  double get_thtbdx_in(double &cthtbd);\n\n  void propagate_position_speed_acceleration(double int_step);\n  void propagate_aeroloss(double int_step);\n  void propagate_gravityloss(double int_step);\n  void propagate_control_loss(double int_step);\n  void vibration(double int_step);\n  void propagate_TBI(double int_step, arma::vec3 WBIB_in);\n  void propagate_TBI_Q(double int_step, arma::vec3 WBIB_in);\n  void propagate_WBIB(double int_step, arma::vec3 FMB_in, arma::mat33 IBBB);\n  void orbital(arma::vec3 SBII_in, arma::vec3 VBII_in, double dbi_in);\n  void build_WEII();\n  void aux_calulate(arma::mat33 TEI, arma::mat33 TBI_in);\n  void RK4F(std::vector<arma::vec> Var_in, std::vector<arma::vec> &Var_out);\n  void Send();\n\n  double calculate_alphaix(arma::vec3 VBIB);\n  double calculate_betaix(arma::vec3 VBIB);\n  double calculate_alppx(arma::vec3 VBAB_in, double dvba);\n  double calculate_phipx(arma::vec3 VBAB_in);\n  double calculate_alphax(arma::vec3 VBAB_in);\n  double calculate_betax(arma::vec3 VBAB, double dvba);\n\n  arma::vec build_VBEB(double _alpha0x, double _beta0x, double dvbe);\n  arma::mat calculate_TBD(double lonx_in, double latx_in, double alt_in);\n  arma::vec3 calculate_WBII(arma::mat33 TBI_in);\n  arma::vec3 calculate_fspb(arma::vec3 FAPB_in, double vmass);\n  arma::vec3 calculate_WBEB(arma::mat33 TBI_in);\n  arma::vec3 euler_angle(arma::mat33 TBD_in);\n\n  void gamma_beta();\n  void Gravity_Q();\n  void AeroDynamics_Q();\n  void calculate_I1();\n  void funcv(int n, double *x, double *ff);\n  void broydn(double x[], int n, int *check);\n  void rsolv(double **a, int n, double d[], double b[]);\n  void fdjac(int n, double x[], double fvec_in[], double **df);\n  double f_min(double x[]);\n  void lnsrch(int n, double xold[], double fold, double g[], double p[],\n              double x[], double *f_in, double stpmax, int *check);\n  void qrdcmp(double **a, int n, double *c, double *d, int *sing);\n  void qrupdt(double **r, double **qt, int n, double u[], double v[]);\n  void rotate(double **r, double **qt, int n, int i, double a, double b);\n\n  MATRIX(TBI, 3, 3); /* *o (--)    Transformation Matrix of body coord wrt\n                    inertia coord */\n\n  MATRIX(TBID, 3, 3); /* *o (--)    Transformation Matrix of body coord wrt\n                     inertia coord derivative */\n\n  VECTOR(TBI_Q, 4); /* *o (--)    Transformation Matrix of body coord wrt\n                      inertia coord (Quaternion) */\n\n  VECTOR(TBID_Q, 4); /* *o (--)    Transformation Matrix of body coord wrt\n                       inertia coord derivative (Quaternion) */\n\n  MATRIX(TBD, 3, 3); /* *o (--)    Transformation Matrix of body coord wrt\n                    geodetic coord */\n  VECTOR(TBDQ, 4);   /* *o  (--)    Quaternion from geodetic to body */\n\n  VECTOR(VBAB, 3); /* *o  (m/s)    Air speed in body frame */\n\n  MATRIX(WEII_skew, 3,\n         3); /* *o  (r/s)    Earth's angular velocity (skew-sym) */\n\n  VECTOR(SBIIP, 3); /* *o  (m)      Vehicle position in inertia coord */\n\n  VECTOR(VBIIP, 3); /* *o  (m/s)    Vehicle inertia velocity */\n\n  VECTOR(SBII, 3); /* *o  (m)      Vehicle position in inertia coord */\n\n  VECTOR(VBII, 3); /* *o  (m/s)    Vehicle inertia velocity */\n\n  VECTOR(ABII, 3); /* *o  (m/s2)   Vehicle inertia acceleration */\n\n  VECTOR(ABIB,\n         3); /* *o  (m/s2)   Vehicle inertia acceleration on body coordinate */\n\n  VECTOR(SBEE, 3); /* *o  (m)     Vehicle position in earth coord  */\n\n  VECTOR(VBEE, 3); /* *o  (m/s)     Vehicle speed in earth coord  */\n\n  VECTOR(ABEE, 3); /* *o  (m/s2)   Vehicle acceleration in ECEF */\n\n  VECTOR(SBEE_old, 3); /* *o  (m)     Vehicle position in earth coord  */\n\n  VECTOR(VBEE_old, 3); /* *o  (m/s)     Vehicle speed in earth coord  */\n\n  VECTOR(ABEE_old, 3); /* *o  (m/s2)   Vehicle acceleration in ECEF */\n\n  VECTOR(JBII, 3); /* *o (m/s3)    Vehicle Jerk in ECI*/\n\n  VECTOR(JBEE, 3); /* *o (m/s3)    Vehicle Jerk in ECEF */\n\n  MATRIX(TDI, 3, 3); /* **  (--)     Transformation Matrix of geodetic wrt\n                    inertial coordinates */\n\n  MATRIX(\n      TGI, 3,\n      3); /* **  (--)     Transformation Matrix geocentric wrt inertia coord */\n\n  VECTOR(VBED, 3); /* *o (m/s)   NED velocity */\n\n  VECTOR(FSPB, 3); /* *o  (m/s2)   Specific force in body coord */\n\n  VECTOR(NEXT_ACC, 3); /* *o (m/s2)   New Inertial acceleration */\n\n  MATRIX(TDE, 3, 3); /* ** (--)  T.M. from ECEF to geodetic */\n\n  VECTOR(VBII_old, 3); /* ** (m/s)  Prior body inertia velocity */\n\n  VECTOR(WEII, 3); /* ** (--)  Earth rate in inertia coordinate */\n\n  VECTOR(WBII, 3); /* *o (r/s)        Vehicle's inertia angular velocity in\n                     inertia coord */\n\n  VECTOR(WBEB, 3); /* *o (r/s)        Angular velocity of vehicle wrt earth in\n                     body coord */\n\n  VECTOR(WBIB, 3); /* *o (r/s)        Augular velocity of vehicle wrt inertia in\n                     body coord */\n\n  VECTOR(WBIBD, 3); /* *o (r/s2)       Angular velocity of vehicle wrt inertia\n                      in body coord - derivative */\n\n  MATRIX(TVD, 3, 3); /* **  (--)     Transformation Matrix of geographic\n                    velocity wrt geodetic coord */\n\n  VECTOR(SBEE_test, 3); /* *o  (m)     Vehicle position in earth coord  */\n\n  VECTOR(VBEE_test, 3); /* *o  (m/s)     Vehicle speed in earth coord  */\n\n  VECTOR(ABEE_test, 3); /* *o  (m/s2)   Vehicle acceleration in ECEF */\n\n  MATRIX(TLI, 3, 3); /* **  (--)  T.M. from inertia to launch site */\n\n  VECTOR(LT_euler, 3); /* ** (rad)  Launch site coordinate Euler angle */\n\n  VECTOR(TBLQ, 4); /* ** (--) Quaternion from launch site to body */\n\n  VECTOR(ABID, 3); /* ** (--) Vehicle inertia body acceleration in geodetic */\n\n  VECTOR(FAPB,\n         3); /* *o (N)      Aerodynamic and propulsion forces in body axes */\n\n  VECTOR(FAP, 3); /* *o (N)      Aerodynamic force in body axes */\n\n  VECTOR(FMB,\n         3); /* *o (N*m)    Aerodynamic and propulsion moment in body axes */\n\n  VECTOR(FMAB,\n         3); /* *o (N*m)    Aerodynamic and propulsion moment in body axes */\n\n  VECTOR(Q_G, 6); /* *o (--)     External force generated by gravity */\n\n  VECTOR(Q_Aero, 6); /* *o (--)  External force generated by aerodynamics */\n\n  VECTOR(rhoC_1, 3); /* *o  (m)  Level arm from reference ponit to CG */\n\n  MATRIX(I1, 3, 3); /* *o (kg*m2)  MOI of vehicle */\n\n  VECTOR(ddrP_1, 3); /* *o  (m/s2)  Vehicle acceleration */\n\n  VECTOR(ddang_1, 3); /* *o  (r/s2)  Vehicle angular acceleration */\n\n  VECTOR(dang_1, 3); /* *o  (r/s)   Vehicle angular rate */\n\n  VECTOR(ddrhoC_1, 3); /* *o  (m/s2)  Centrifugal acceleration and tangential\n                          acceleration term */\n\n  VECTOR(p_b1_ga,\n         3); /* *o (--)   General dynamics equations 1st DoF to 3rd DoF */\n\n  VECTOR(p_b1_be,\n         3); /* *o (--)   General dynamics equations 4th DoF to 6th DoF */\n\n  VECTOR(f, 6); /* *o  (--)  Summation of external force & internal force */\n\n  VECTOR(gamma_b1_q1, 3); /* *o (--)  Vehicle's 1st DoF velocity coefficient */\n\n  VECTOR(gamma_b1_q2, 3); /* *o (--)  Vehicle's 2nd DoF velocity coefficient */\n\n  VECTOR(gamma_b1_q3, 3); /* *o (--)  Vehicle's 3rd DoF velocity coefficient */\n\n  VECTOR(beta_b1_q4,\n         3); /* *o (--)  Vehicle's 4th DoF angular velocity coefficient */\n\n  VECTOR(beta_b1_q5,\n         3); /* *o (--)  Vehicle's 5th DoF angular velocity coefficient */\n\n  VECTOR(beta_b1_q6,\n         3); /* *o (--)  Vehicle's 6th DoF angular velocity coefficient */\n\n  /* Generating Outputs */\n  double\n      ortho_error; /* *o (--)    Direction cosine matrix orthogonality error*/\n  double alphax;   /* *o (d)     Angle of attack */\n  double betax;    /* *o (d)     Sideslip angle */\n  double alppx;    /* *o (d)     Total angle of attack */\n  double phipx;    /* *o (d)     Aerodynamic roll angle*/\n  double alphaix;  /* *o (d)     Angle of attack, inertia velocity*/\n  double betaix;   /* *o (d)     Sideslip angle, inertia velocity*/\n  double psibdx; /* *o (d)     Yaw angle of Vehicle wrt geodetic coord - deg */\n  double\n      thtbdx; /* *o (d)     Pitch angle of Vehicle wrt geodetic coord - deg */\n  double phibdx; /* *o (d)     Roll angle of Vehicle wrt geodetic coord - deg */\n  double psibd;  /* *o (r)     Yaw angle of Vehicle wrt geodetic coord - rad */\n  double thtbd; /* *o (r)     Pitch angle of Vehicle wrt geodetic coord - rad */\n  double phibd; /* *o (r)     Roll angle of Vehicle wrt geodetic coord - rad */\n  double alt;   /* *o  (m)      Vehicle altitude */\n  double lonx;  /* *o  (d)      Vehicle longitude */\n  double latx;  /* *o  (d)      Vehicle latitude */\n  double _aero_loss; /* *o  (m/s)    Velocity loss caused by aerodynamic drag */\n  double gravity_loss; /* *o  (m/s)    Velocity loss caused by gravity */\n  // double t;            /* *o (s)       timer */\n  double _grndtrck; /* *o  (m)     [DIAG] Vehicle ground track on earth */\n  double _gndtrkmx; /* *o  (km)    [DIAG] Ground track - km */\n  double _gndtrnmx; /* **  (nm)    [DIAG] Ground track - nm */\n  double _ayx;      /* *o  (m/s2)  [DIAG] Achieved side acceleration */\n  double _anx;      /* *o  (m/s2)  [DIAG] Achieved normal acceleration */\n  double _dbi;    /* *o  (m)     [DIAG] Vehicle distance from center of earth */\n  double _dvbi;   /* *o  (m/s)   [DIAG] Vehicle inertia speed */\n  double _dvbe;   /* *o  (m/s)   [DIAG] Vehicle geographic speed */\n  double _thtvdx; /* *o  (d)     [DIAG] Vehicle's flight path angle */\n  double _psivdx; /* *o  (d)     [DIAG] Vehicle's heading angle */\n  int liftoff;    /* *i  (--)     To check wether the rocket liftoff or\n                              not: liftoff = 1, not liftoff = 0 */\n  int cadorbin_flag; /* Orbit calculation status flag */\n  double ppx; /* *o (d/s)        Body roll angular velocity wrt earth in body\n                 axes */\n  double qqx; /* *o (d/s)        Body pitch angular velocity wrt earth in body\n                 axes */\n  double rrx; /* *o (d/s)        Body yaw angular velocity wrt earth in body\n                 axes */\n  double control_loss; /* *o (--) Velocity loss due to control effect */\n\n  /* Orbital Logging */\n  double _inclination;  /* *o  (deg)   [DIAG] Orbital inclination is the minimun\n                        angle between reference plane and the orbital plane or\n                        direction of an object in orbit around another object */\n  double _eccentricity; /* *o  (--)    [DIAG] Determines the amount by which its\n                           orbit around another body deviates from a perfect\n                           circle */\n  double _semi_major; /* *o  (m)     [DIAG] the major axis of an ellipse is its\n                         longest diameter */\n  double _ha;         /* *o  (m)     [DIAG] Orbital Apogee */\n  double _hp;         /* *o  (m)     [DIAG] Orbital Perigee */\n  double _lon_anodex; /* *o  (deg)   [DIAG] The longitude of the ascending node\n                         (☊ or Ω) is one of the orbital elements used to specify\n                         the orbit of an object in space. It is the angle from a\n                         reference direction, called the origin of longitude, to\n                         the direction of the ascending node, measured in a\n                         reference plane */\n  double _arg_perix;  /* *o  (deg)   [DIAG] The argument of periapsis (also\n                         called argument of perifocus or argument of pericenter),\n                         symbolized as ω, is one of the orbital elements of an\n                         orbiting body. Parametrically, ω is the angle from the\n                         body's ascending node to its periapsis, measured in the\n                         direction of motion */\n  double _true_anomx; /* *o  (deg)   [DIAG] In celestial mechanics, true anomaly\n                      is an angular parameter that defines the position of a\n                      body moving along a Keplerian orbit. It is the angle\n                      between the direction of periapsis and the current\n                      position of the body, as seen from the main focus of the\n                      ellipse (the point around which the object orbits) */\n  double _ref_alt;    /* *o  (m)     [DIAG] */\n  double reference_point; /* *o (m)    Multibody dynamics reference point */\n  double Roll;\n  double Pitch;\n  double Yaw;\n  unsigned int Interpolation_Extrapolation_flag;\n  // double xp; /* *o (m) Reference point  */\n  int its;                /* *o (--) Number of iterations */\n  int DOF;                /* *o (--)  Number of Degree of Freedom */\n  unsigned int Aero_flag; /* *o (-)  Aerodynamics flag */\n};\n#endif\n", "meta": {"hexsha": "2c8804882b565351ad01a0b00311c31483b5a63e", "size": 14715, "ext": "hh", "lang": "C++", "max_stars_repo_path": "models/dm/include/Rocket_Flight_DM.hh", "max_stars_repo_name": "ultype/Next-simulation", "max_stars_repo_head_hexsha": "0fb59d02b2f88e813792a486d7fcab7242f77c11", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "models/dm/include/Rocket_Flight_DM.hh", "max_issues_repo_name": "ultype/Next-simulation", "max_issues_repo_head_hexsha": "0fb59d02b2f88e813792a486d7fcab7242f77c11", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "models/dm/include/Rocket_Flight_DM.hh", "max_forks_repo_name": "ultype/Next-simulation", "max_forks_repo_head_hexsha": "0fb59d02b2f88e813792a486d7fcab7242f77c11", "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": 42.0428571429, "max_line_length": 81, "alphanum_fraction": 0.6057764186, "num_tokens": 4233, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7185943925708562, "lm_q2_score": 0.4610167793123159, "lm_q1q2_score": 0.3312840724949061}}
{"text": "/* Copyright (C) 2010 Ion Torrent Systems, Inc. All Rights Reserved */\n#include <armadillo>\n#include <iostream>\n#include <vector>\n#include <string>\n#include \"IonErr.h\"\n#include \"Image.h\"\n#include \"Mask.h\"\n#include \"OptArgs.h\"\n#include \"SampleQuantiles.h\"\n\nusing namespace arma;\nusing namespace std;\n\n#define D '\\t'\n#define NUM_SAMPLE 10000\n#define MAX_MILL_SEC 80\nclass CompressReporter {\npublic: \n  virtual void Init() = 0;\n  virtual void Report(int rowStart, int rowEnd, int colStart, int colEnd, \n                      int flow, const std::vector<int> &wellMapping,\n                      Mask &mask,\n                      const Mat<float> &raw, const Mat<float> &compressed) = 0;\n  virtual void Finish() = 0;\n};\n\nclass WellReporter : public CompressReporter {\npublic:\n  WellReporter(const std::string &fileOut) {\n    mFileName = fileOut;\n    mMad.Init(10000);\n    mAutoCor.Init(10000);\n  }\n  void Init() { \n    mOut.open(mFileName.c_str()); \n    mOut << \"well\\trow\\tcol\\tmad\\tabs25\\tabs75\\trms\\tacor\" << endl;\n  }\n\n  void Report(int rowStart, int rowEnd, int colStart, int colEnd, \n              int flow, const std::vector<int> &wellMapping,\n              Mask &mask,\n              const Mat<float> &raw, const Mat<float> &compressed) {\n    Mat<float> diff = raw - compressed;\n    for (size_t row = 0; row < raw.n_rows; row++) {\n      SampleQuantiles<float> q(diff.n_cols);\n      SampleStats<float>  s;\n      SampleStats<float>  m;\n      for (size_t col = 0; col < diff.n_cols; col++) {\n        float val = diff(row, col);\n        m.AddValue(val);\n        q.AddValue(fabs(val));\n        s.AddValue(val*val);\n      }\n      SampleStats<float> a;\n      double mean = m.GetMean();\n      for (size_t col = 1; col < diff.n_cols; col++) {\n        float val1 = diff(row, col);\n        float val2 = diff(row, col-1);\n        a.AddValue((val1 - mean) * (val2 - mean));\n      }\n      double acor = a.GetMean() / m.GetVar();\n      mAutoCor.AddValue(acor);\n      mMad.AddValue(q.GetQuantile(.5));\n      mOut << wellMapping[row] << D << wellMapping[row] / mask.W() << D << wellMapping[row] % mask.W() << D\n           << q.GetQuantile(.5) << D << q.GetQuantile(.25) << D << q.GetQuantile(.75) << D << sqrt(s.GetMean()) << D << acor << endl;\n    }\n  }\n\n  virtual void Finish() { \n    cout << \"Quantiles\\tmad\\tautocor\" << endl;\n    for (int i = 0; i <= 10; i++) {\n      cout << i * 10 << D << mMad.GetQuantile(i / 10.0) << D << mAutoCor.GetQuantile(i / 10.0) << endl;\n    }\n    mOut.close(); \n  }\n  SampleQuantiles<float> mMad;\n  SampleQuantiles<float> mAutoCor;\n  std::string mFileName;\n  std::ofstream mOut;\n};\n\n\nclass RegionIndividualReporter : public CompressReporter {\npublic:\n  RegionIndividualReporter(const std::string &fileOut, int rowStart, int rowEnd, int colStart, int colEnd) {\n    mFileName = fileOut;\n    mRowStart = rowStart;\n    mRowEnd = rowEnd;\n    mColStart = colStart;\n    mColEnd = colEnd;\n    mFirst = true;\n  }\n\n  void Init() { \n    mOut.open(mFileName.c_str()); \n    mOut << \"well\\ttype\";\n  }\n\n  void Report(int rowStart, int rowEnd, int colStart, int colEnd, \n              int flow, const std::vector<int> &wellMapping,\n              Mask &mask,\n              const Mat<float> &raw, const Mat<float> &compressed) {\n    if (rowStart == mRowStart && rowEnd == mRowEnd && colStart == mColStart && colEnd == mColEnd) {\n      if (mFirst) {\n        for (size_t col = 0; col < raw.n_cols; col++) {\n          mOut << D << \"col.\" << col;\n        }\n        mOut << endl;\n        mFirst = false;\n      }\n      for (size_t row = 0; row < raw.n_rows; row++) {\n        mOut << wellMapping[row] << D << \"raw\";\n        for (size_t col = 0; col < raw.n_cols; col++) {\n          mOut << D << raw(row,col);\n        }\n        mOut << endl;\n      }\n      for (size_t row = 0; row < raw.n_rows; row++) {\n        mOut << wellMapping[row] << D << \"compressed\";\n        for (size_t col = 0; col < raw.n_cols; col++) {\n          mOut << D << compressed(row,col);\n        }\n        mOut << endl;\n      }\n    }\n  }\n\n  virtual void Finish() { mOut.close(); }\n  bool mFirst;\n  int mRowStart, mRowEnd, mColStart, mColEnd;\n  std::string mFileName;\n  std::ofstream mOut;\n};\n\n\nclass DeviationSummaryReporter : public CompressReporter {\npublic:\n  DeviationSummaryReporter(const std::string &fileOut, const std::string &runName) {\n    mFileName = fileOut;\n    mRunName = runName;\n  }\n\n  void Init() { \n    mQuantiles.Init(10000);\n    mSample.Clear();\n    mSqSample.Clear();\n  }\n\n  void Report(int rowStart, int rowEnd, int colStart, int colEnd, \n              int flow, const std::vector<int> &wellMapping,\n              Mask &mask,\n              const Mat<float> &raw, const Mat<float> &compressed) {\n    Mat<float> diff = raw - compressed;\n    for (size_t row = 0; row < raw.n_rows; row++) {\n      for (size_t col = 0; col < diff.n_cols; col++) {\n        float val = fabs(diff(row, col));\n        mQuantiles.AddValue(val);\n        mSqSample.AddValue(val*val);\n        mSample.AddValue(val);\n      }\n    }\n  }\n\n  virtual void Finish() { \n    mOut.open(mFileName.c_str()); \n    mOut << \"{\" << endl;;\n    mOut << \"  run_name : \" << mRunName << \",\" << endl;\n    mOut << \"  fabs_mean : \" << mSample.GetMean() << \", \"  << endl;\n    mOut << \"  fabs_sd : \" << mSample.GetSD() << \", \" << endl;\n    mOut << \"  rms : \" << sqrt(mSqSample.GetMean()) << \", \"  << endl;\n    mOut << \"  fabs_median : \" << mQuantiles.GetQuantile(.5) << \", \" << endl;\n    mOut << \"  fabs_iqr : \" << mQuantiles.GetIQR() << \", \"  << endl;\n    mOut << \"  fabs_quantiles: [\";\n    for (size_t i = 0; i < 10; i++) {\n      float q = i / 10.0f;\n      mOut << mQuantiles.GetQuantile(q) << \",\";\n    }\n    mOut << mQuantiles.GetQuantile(1.0) <<  \"], \"  << endl;\n    mOut << \"  fabs_quantiles_100: [\";\n    for (size_t i = 0; i < 100; i++) {\n      float q = i / 100.0f;\n      mOut << mQuantiles.GetQuantile(q) << \",\";\n    }\n    mOut << mQuantiles.GetQuantile(1.0) <<  \"]\"  << endl;\n    mOut << \"}\" << endl;\n    mOut.close(); \n  }\n\n  std::string mFileName;\n  SampleQuantiles<float> mQuantiles;\n  SampleStats<float> mSqSample;\n  SampleStats<float> mSample;\n  std::string mRunName;\n  std::ofstream mOut;\n};\n\n\nclass FrameReporter : public CompressReporter {\npublic:\n  FrameReporter(const std::string &fileOut) {\n    mFileName = fileOut;\n    mStarted = false;\n  }\n  void Init() { \n    mOut.open(mFileName.c_str()); \n    mOut << \"rowStart\\trowEnd\\tcolStart\\tcolEnd\\tnumWells\\tflow\\tstat\";\n    mStarted = false;\n  }\n\n  void Report(int rowStart, int rowEnd, int colStart, int colEnd, \n              int flow, const std::vector<int> &wellMapping,\n              Mask &mask,\n              const Mat<float> &raw, const Mat<float> &compressed) {\n    if (!mStarted) {\n      for (size_t i = 0; i < raw.n_cols; i++) {\n        mOut << D << \"frame.\" << i;\n      }\n      mOut << endl;\n      mQuantiles.resize(raw.n_cols);\n      mStats.resize(raw.n_cols);\n      mStarted = true;\n    }\n    for (size_t i = 0; i < raw.n_cols; i++) {\n      mQuantiles[i].Clear();\n      mQuantiles[i].Init(raw.n_rows);\n      mStats[i].Clear();\n    }\n    Mat<float> diff = raw - compressed;\n    for (size_t row = 0; row < diff.n_rows; row++) {\n      for (size_t col = 0; col < diff.n_cols; col++) {\n        float val = fabs(diff(row, col));\n        mQuantiles[col].AddValue(val);\n        mStats[col].AddValue(val);\n      }\n    }\n    mOut << rowStart << D << rowEnd << D << colStart << D << raw.n_rows << D << flow << D << \"Fabs.Q25\";\n    for (size_t i = 0; i < mQuantiles.size(); i++) { mOut << D << mQuantiles[i].GetQuantile(.25); } \n    mOut << std::endl;\n    mOut << rowStart << D << rowEnd << D << colStart << D << raw.n_rows << D << flow << D << \"Fabs.Q50\";\n    for (size_t i = 0; i < mQuantiles.size(); i++) { mOut << D << mQuantiles[i].GetQuantile(.5); } \n    mOut << std::endl;\n    mOut << rowStart << D << rowEnd << D << colStart << D << raw.n_rows << D << flow << D << \"Fabs.Q75\";\n    for (size_t i = 0; i < mQuantiles.size(); i++) { mOut << D << mQuantiles[i].GetQuantile(.75); } \n    mOut << std::endl;\n    mOut << rowStart << D << rowEnd << D << colStart << D << raw.n_rows << D << flow << D << \"Fabs.IQR\";\n    for (size_t i = 0; i < mQuantiles.size(); i++) { mOut << D << mQuantiles[i].GetQuantile(.75) - mQuantiles[i].GetQuantile(.25); } \n    mOut << std::endl;\n    mOut << rowStart << D << rowEnd << D << colStart << D << raw.n_rows << D << flow << D << \"Fabs.Mean\";\n    for (size_t i = 0; i < mStats.size(); i++) { mOut << D << mStats[i].GetMean(); } \n    mOut << std::endl;\n    mOut << rowStart << D << rowEnd << D << colStart << D << raw.n_rows << D << flow << D << \"Fabs.SD\";\n    for (size_t i = 0; i < mStats.size(); i++) { mOut << D << mStats[i].GetSD(); } \n    mOut << std::endl;\n  }\n\n  virtual void Finish() { mOut.close(); }\n  \n  std::vector<SampleQuantiles<float> > mQuantiles;\n  std::vector<SampleStats<float>  > mStats;\n  bool mStarted;\n  std::string mFileName;\n  std::ofstream mOut;\n};\n\nclass CompressOpts {\npublic:\n  int rowStart, rowEnd, colStart, colEnd;\n  int rowStep, colStep;\n  double minPercent;\n  std::string datIn;\n  std::string maskFile;\n  int flowNum;\n  std::string prefixOut;\n  std::string wellOut;\n  std::string frameOut;\n  std::string runName;\n  int numBasis;\n};\n\nvoid AddMatVector(Mat<float> &M, const Col<float> &vec) {\n  for (size_t i = 0; i < M.n_rows; i++) {\n    for (size_t j = 0; j < M.n_cols; j++) {\n      M(i,j) = M(i,j) + vec(i);\n    }\n  }\n}\n\nvoid Compress(const Mat<float> &raw, int numBasis, Mat<float> &compressed) {\n  Col<float> dc = mean(raw, 1);\n  Mat<float> X = raw;\n  dc = dc * -1;\n  AddMatVector(X, dc);\n  Mat<float> Cov = X.t() * X;    // L x L\n  Mat<float> EVec;\n  Col<float> EVal;\n  eig_sym(EVal, EVec, Cov);\n  Mat<float> V(EVec.n_rows, numBasis );  // L x numBasis\n  int count = 0;\n  for(size_t v = V.n_rows - 1; v >= V.n_rows - numBasis; v--) {\n    copy(EVec.begin_col(v), EVec.end_col(v), V.begin_col(count++));\n  }\n  Mat<float> A = X * V;  // N x numBasis\n  Mat<float> P = A * V.t();  // Prediction N x L \n  dc = dc * -1;\n  AddMatVector(P, dc);\n  compressed = P;\n}\n\nint LoadData(int rowStart, int rowEnd, int colStart, int colEnd,\n              Mask &mask, Image &img, vector<int> &mapping, Mat<float> &raw) {\n  int numOk = 0;\n  for (int row = rowStart; row < rowEnd; row++) {\n    for (int col = colStart; col < colEnd; col++) {\n      if (!mask.Match(col, row, MaskPinned) && !mask.Match(col, row, MaskExclude)) {\n        numOk++;\n        mapping.push_back(mask.ToIndex(row, col));\n      }\n    }\n  }\n  const RawImage *rawImg = img.GetImage(); \n  cout << \"Timestamps:\" << endl;\n  vector<bool> colOk(img.GetFrames(), false);\n  int count = 0;\n  if (rawImg->timestamps[0] < MAX_MILL_SEC) {\n    count++; \n    colOk[0] = true;\n  }\n  for (int i = 1; i < img.GetFrames(); i++) {\n    cout << i << \":\\t\" << rawImg->timestamps[i] << \"\\t\" << rawImg->timestamps[i] - rawImg->timestamps[i-1] << endl;\n    if (rawImg->timestamps[i] - rawImg->timestamps[i-1] < MAX_MILL_SEC) {\n      colOk[i] = true;\n      count++;\n    }\n  }\n  cout << \"Got: \" << count << \" frames with no vfr\" << endl;\n  raw.set_size(numOk, count);\n  for (size_t wIx = 0; wIx < mapping.size(); wIx++) {\n    int idx = mapping[wIx];\n    int cIx = 0;\n    for (int fIx = 0; fIx < img.GetFrames(); fIx++) {\n      if (colOk[fIx]) {\n        raw(wIx,cIx++) = img.At(idx, fIx);\n      }\n    }\n  }\n  return numOk;\n}\n\nint main(int argc, const char * argv[]) {\n\n  OptArgs opts;\n  opts.ParseCmdLine(argc, argv);\n  CompressOpts o;\n  opts.GetOption(o.maskFile, \"\", '-', \"mask\");\n  Mask mask(o.maskFile.c_str());\n  opts.GetOption(o.rowStart, \"0\", '-', \"row-start\");\n  opts.GetOption(o.rowEnd, \"-1\", '-', \"row-end\");\n  if(o.rowEnd < 0) { o.rowEnd = mask.H(); }\n\n  opts.GetOption(o.colStart, \"0\", '-', \"col-start\");\n  opts.GetOption(o.colEnd, \"-1\", '-', \"col-end\");\n  if(o.colEnd < 0) { o.colEnd = mask.W(); }\n\n  opts.GetOption(o.datIn, \"\", '-', \"dat-file\");\n  opts.GetOption(o.prefixOut, \"noise\", '-', \"out-prefix\");\n  opts.GetOption(o.numBasis, \"6\", '-', \"num-basis\");\n  opts.GetOption(o.rowStep, \"100\", '-', \"row-step\");\n  opts.GetOption(o.colStep, \"100\", '-', \"col-step\");\n  opts.GetOption(o.minPercent, \".5\", '-', \"min-percent\");\n  opts.GetOption(o.runName, \"\", '-', \"run-name\");\n  // Load file\n  Image img;\n  img.SetImgLoadImmediate (false);\n  img.SetIgnoreChecksumErrors (false);\n  ION_ASSERT(img.LoadRaw (o.datIn.c_str()), \"Couldn't load: \" + o.datIn);\n\n  // Create reporters\n  vector<CompressReporter *> reporters;\n  WellReporter wRep(o.prefixOut + \".wells.txt\");\n  reporters.push_back(&wRep);\n  FrameReporter frameRep(o.prefixOut + \".frames.txt\");\n  reporters.push_back(&frameRep);\n  DeviationSummaryReporter devRep(o.prefixOut + \".summary.json\", o.runName);\n  reporters.push_back(&devRep);\n  int regRowStart = 0;\n  if (o.rowStep * 5 < mask.H()) {\n    regRowStart = o.rowStep * 4;\n  }\n  int regColStart = 0;\n  if (o.colStep * 5 < mask.H()) {\n    regColStart = o.colStep * 4;\n  }\n  RegionIndividualReporter regionRep(o.prefixOut + \".region.txt\", regRowStart, regRowStart + o.rowStep, regColStart, regColStart + o.colStep);\n  reporters.push_back(&regionRep);\n  for (size_t rIx = 0; rIx < reporters.size(); rIx++) {\n    reporters[rIx]->Init();\n  }\n  // For each region do compression and run report.\n  for (int row = o.rowStart; row < o.rowEnd; row += o.rowStep) {\n    for (int col = o.colStart; col < o.colEnd; col += o.colStep) {\n      int rowStop = min(row + o.rowStep, o.rowEnd);\n      int colStop = min(col + o.colStep, o.colEnd);\n      Mat<float> raw;\n      vector<int> mapping;\n      int numOk = LoadData(row, rowStop, col, colStop, mask, img,  mapping, raw);\n      if (numOk > o.minPercent * (rowStop - row) * (colStop - col)) {\n        Mat<float> compressed(raw.n_rows, raw.n_cols);\n        Compress(raw, o.numBasis, compressed);\n        for (size_t rIx = 0; rIx < reporters.size(); rIx++) {\n          reporters[rIx]->Report(row, rowStop, col, colStop, 0,\n                                 mapping, mask, raw, compressed);\n        }\n      }\n    }\n  }\n  for (size_t rIx = 0; rIx < reporters.size(); rIx++) {\n    reporters[rIx]->Finish();\n  }\n\n  // Spin things down.\n  \n}\n\n\n", "meta": {"hexsha": "3d151945b3ad14898c874b4a8c438f6ca5d9f347", "size": 14078, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Analysis/Separator/CompressDeviation.cpp", "max_stars_repo_name": "konradotto/TS", "max_stars_repo_head_hexsha": "bf088bd8432b1e3f4b8c8c083650a30d9ef2ae2e", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 125.0, "max_stars_repo_stars_event_min_datetime": "2015-01-22T05:43:23.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T17:15:59.000Z", "max_issues_repo_path": "Analysis/Separator/CompressDeviation.cpp", "max_issues_repo_name": "konradotto/TS", "max_issues_repo_head_hexsha": "bf088bd8432b1e3f4b8c8c083650a30d9ef2ae2e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 59.0, "max_issues_repo_issues_event_min_datetime": "2015-02-10T09:13:06.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-11T02:32:38.000Z", "max_forks_repo_path": "Analysis/Separator/CompressDeviation.cpp", "max_forks_repo_name": "konradotto/TS", "max_forks_repo_head_hexsha": "bf088bd8432b1e3f4b8c8c083650a30d9ef2ae2e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 98.0, "max_forks_repo_forks_event_min_datetime": "2015-01-17T01:25:10.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-18T17:29:42.000Z", "avg_line_length": 33.0469483568, "max_line_length": 142, "alphanum_fraction": 0.571885211, "num_tokens": 4362, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7185943925708561, "lm_q2_score": 0.4610167793123159, "lm_q1q2_score": 0.33128407249490605}}
{"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 inf.ethz.ch)\n\n#include \"base/polynomial.h\"\n\n#include <Eigen/Eigenvalues>\n\n#include \"util/logging.h\"\n\nnamespace colmap {\nnamespace {\n\n// Remove leading zero coefficients.\nEigen::VectorXd RemoveLeadingZeros(const Eigen::VectorXd& coeffs) {\n  Eigen::VectorXd::Index num_zeros = 0;\n  for (; num_zeros < coeffs.size(); ++num_zeros) {\n    if (coeffs(num_zeros) != 0) {\n      break;\n    }\n  }\n  return coeffs.tail(coeffs.size() - num_zeros);\n}\n\n// Remove trailing zero coefficients.\nEigen::VectorXd RemoveTrailingZeros(const Eigen::VectorXd& coeffs) {\n  Eigen::VectorXd::Index num_zeros = 0;\n  for (; num_zeros < coeffs.size(); ++num_zeros) {\n    if (coeffs(coeffs.size() - 1 - num_zeros) != 0) {\n      break;\n    }\n  }\n  return coeffs.head(coeffs.size() - num_zeros);\n}\n\n}  // namespace\n\nbool FindLinearPolynomialRoots(const Eigen::VectorXd& coeffs,\n                               Eigen::VectorXd* real, Eigen::VectorXd* imag) {\n  CHECK_EQ(coeffs.size(), 2);\n\n  if (coeffs(0) == 0) {\n    return false;\n  }\n\n  if (real != nullptr) {\n    real->resize(1);\n    (*real)(0) = -coeffs(1) / coeffs(0);\n  }\n\n  if (imag != nullptr) {\n    imag->resize(1);\n    (*imag)(0) = 0;\n  }\n\n  return true;\n}\n\nbool FindQuadraticPolynomialRoots(const Eigen::VectorXd& coeffs,\n                                  Eigen::VectorXd* real,\n                                  Eigen::VectorXd* imag) {\n  CHECK_EQ(coeffs.size(), 3);\n\n  const double a = coeffs(0);\n  if (a == 0) {\n    return FindLinearPolynomialRoots(coeffs.tail(2), real, imag);\n  }\n\n  const double b = coeffs(1);\n  const double c = coeffs(2);\n  if (b == 0 && c == 0) {\n    if (real != nullptr) {\n      real->resize(1);\n      (*real)(0) = 0;\n    }\n    if (imag != nullptr) {\n      imag->resize(1);\n      (*imag)(0) = 0;\n    }\n    return true;\n  }\n\n  const double d = b * b - 4 * a * c;\n\n  if (d >= 0) {\n    const double sqrt_d = std::sqrt(d);\n    if (real != nullptr) {\n      real->resize(2);\n      if (b >= 0) {\n        (*real)(0) = (-b - sqrt_d) / (2 * a);\n        (*real)(1) = (2 * c) / (-b - sqrt_d);\n      } else {\n        (*real)(0) = (2 * c) / (-b + sqrt_d);\n        (*real)(1) = (-b + sqrt_d) / (2 * a);\n      }\n    }\n    if (imag != nullptr) {\n      imag->resize(2);\n      imag->setZero();\n    }\n  } else {\n    if (real != nullptr) {\n      real->resize(2);\n      real->setConstant(-b / (2 * a));\n    }\n    if (imag != nullptr) {\n      imag->resize(2);\n      (*imag)(0) = std::sqrt(-d) / (2 * a);\n      (*imag)(1) = -(*imag)(0);\n    }\n  }\n\n  return true;\n}\n\nbool FindPolynomialRootsDurandKerner(const Eigen::VectorXd& coeffs_all,\n                                     Eigen::VectorXd* real,\n                                     Eigen::VectorXd* imag) {\n  CHECK_GE(coeffs_all.size(), 2);\n\n  const Eigen::VectorXd coeffs = RemoveLeadingZeros(coeffs_all);\n\n  const int degree = coeffs.size() - 1;\n\n  if (degree <= 0) {\n    return false;\n  } else if (degree == 1) {\n    return FindLinearPolynomialRoots(coeffs, real, imag);\n  } else if (degree == 2) {\n    return FindQuadraticPolynomialRoots(coeffs, real, imag);\n  }\n\n  // Initialize roots.\n  Eigen::VectorXcd roots(degree);\n  roots(degree - 1) = std::complex<double>(1, 0);\n  for (int i = degree - 2; i >= 0; --i) {\n    roots(i) = roots(i + 1) * std::complex<double>(1, 1);\n  }\n\n  // Iterative solver.\n  const int kMaxNumIterations = 100;\n  const double kMaxRootChange = 1e-10;\n  for (int iter = 0; iter < kMaxNumIterations; ++iter) {\n    double max_root_change = 0.0;\n    for (int i = 0; i < degree; ++i) {\n      const std::complex<double> root_i = roots(i);\n      std::complex<double> numerator = coeffs[0];\n      std::complex<double> denominator = coeffs[0];\n      for (int j = 0; j < degree; ++j) {\n        numerator = numerator * root_i + coeffs[j + 1];\n        if (i != j) {\n          denominator = denominator * (root_i - roots(j));\n        }\n      }\n      const std::complex<double> root_i_change = numerator / denominator;\n      roots(i) = root_i - root_i_change;\n      max_root_change =\n          std::max(max_root_change, std::abs(root_i_change.real()));\n      max_root_change =\n          std::max(max_root_change, std::abs(root_i_change.imag()));\n    }\n\n    // Break, if roots do not change anymore.\n    if (max_root_change < kMaxRootChange) {\n      break;\n    }\n  }\n\n  if (real != nullptr) {\n    real->resize(degree);\n    *real = roots.real();\n  }\n  if (imag != nullptr) {\n    imag->resize(degree);\n    *imag = roots.imag();\n  }\n\n  return true;\n}\n\nbool FindPolynomialRootsCompanionMatrix(const Eigen::VectorXd& coeffs_all,\n                                        Eigen::VectorXd* real,\n                                        Eigen::VectorXd* imag) {\n  CHECK_GE(coeffs_all.size(), 2);\n\n  Eigen::VectorXd coeffs = RemoveLeadingZeros(coeffs_all);\n\n  const int degree = coeffs.size() - 1;\n\n  if (degree <= 0) {\n    return false;\n  } else if (degree == 1) {\n    return FindLinearPolynomialRoots(coeffs, real, imag);\n  } else if (degree == 2) {\n    return FindQuadraticPolynomialRoots(coeffs, real, imag);\n  }\n\n  // Remove the coefficients where zero is a solution.\n  coeffs = RemoveTrailingZeros(coeffs);\n\n  // Check if only zero is a solution.\n  if (coeffs.size() == 1) {\n    if (real != nullptr) {\n      real->resize(1);\n      (*real)(0) = 0;\n    }\n    if (imag != nullptr) {\n      imag->resize(1);\n      (*imag)(0) = 0;\n    }\n    return true;\n  }\n\n  // Fill the companion matrix.\n  Eigen::MatrixXd C(coeffs.size() - 1, coeffs.size() - 1);\n  C.setZero();\n  for (Eigen::MatrixXd::Index i = 1; i < C.rows(); ++i) {\n    C(i, i - 1) = 1;\n  }\n  C.row(0) = -coeffs.tail(coeffs.size() - 1) / coeffs(0);\n\n  // Solve for the roots of the polynomial.\n  Eigen::EigenSolver<Eigen::MatrixXd> solver(C, false);\n  if (solver.info() != Eigen::Success) {\n    return false;\n  }\n\n  // If there are trailing zeros, we must add zero as a solution.\n  const int effective_degree =\n      coeffs.size() - 1 < degree ? coeffs.size() : coeffs.size() - 1;\n\n  if (real != nullptr) {\n    real->resize(effective_degree);\n    real->head(coeffs.size() - 1) = solver.eigenvalues().real();\n    if (effective_degree > coeffs.size() - 1) {\n      (*real)(real->size() - 1) = 0;\n    }\n  }\n  if (imag != nullptr) {\n    imag->resize(effective_degree);\n    imag->head(coeffs.size() - 1) = solver.eigenvalues().imag();\n    if (effective_degree > coeffs.size() - 1) {\n      (*imag)(imag->size() - 1) = 0;\n    }\n  }\n\n  return true;\n}\n\n}  // namespace colmap\n", "meta": {"hexsha": "be8cd46d3dc828e7cc8bafad2c36bd00cc584321", "size": 8084, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/base/polynomial.cc", "max_stars_repo_name": "sunbirddy/colmap", "max_stars_repo_head_hexsha": "9099ccedd5a1d6ad209f9e37c45f2a3291326528", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2021-11-15T09:56:21.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-28T07:31:37.000Z", "max_issues_repo_path": "src/base/polynomial.cc", "max_issues_repo_name": "sunbirddy/colmap", "max_issues_repo_head_hexsha": "9099ccedd5a1d6ad209f9e37c45f2a3291326528", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-12-28T06:39:57.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-28T06:39:57.000Z", "max_forks_repo_path": "src/base/polynomial.cc", "max_forks_repo_name": "sunbirddy/colmap", "max_forks_repo_head_hexsha": "9099ccedd5a1d6ad209f9e37c45f2a3291326528", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-09-11T20:22:49.000Z", "max_forks_repo_forks_event_max_datetime": "2019-09-11T20:22:49.000Z", "avg_line_length": 29.0791366906, "max_line_length": 78, "alphanum_fraction": 0.5989609104, "num_tokens": 2189, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5813030906443134, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.3312571074789061}}
{"text": "\n//------------------------------------------------------------------\n//  **MEDYAN** - Simulation Package for the Mechanochemical\n//               Dynamics of Active Networks, v4.0\n//\n//  Copyright (2015-2018)  Papoian Lab, University of Maryland\n//\n//                 ALL RIGHTS RESERVED\n//\n//  See the MEDYAN web page for more information:\n//  http://www.medyan.org\n//------------------------------------------------------------------\n\n#include <time.h>\n#include <random>\n#include <math.h>\n#include <algorithm>\n#include <functional>\n#include <numeric>\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/io.hpp>\n#include <boost/numeric/ublas/operation.hpp>\n#include <boost/range/numeric.hpp>\n#include <fstream>\n\n#include \"Filament.h\"\n#include \"Cylinder.h\"\n#include \"Bead.h\"\n\n#include \"SubSystem.h\"\n\n#include \"SysParams.h\"\n#include \"MathFunctions.h\"\n#include \"GController.h\"\n#include \"Rand.h\"\n\n#ifdef CROSSCHECK_CYLINDER\n#include \"CController.h\"\n#endif\n\nusing namespace mathfunc;\n\nHistogram* Filament::_turnoverTimes;\n\nFilament::Filament(SubSystem* s, short filamentType, const vector<floatingpoint>& position,\n                   const vector<floatingpoint>& direction, bool nucleation, bool branch)\n\n    : Trackable(), _subSystem(s), _filType(filamentType) {\n\n    if(getId() >= SysParams::Chemistry().maxStableIndex) {\n        LOG(ERROR) << \"Filament ID assigned (\"<< getId()<<\n                   \") equals/exceeds the maximum permissible value \"\n                   \"(\"<<SysParams::Chemistry().maxStableIndex<<\"). Exiting.\"<<endl;\n        throw std::logic_error(\"Max value reached\");\n    }\n    //create beads\n    Bead* b1 = _subSystem->addTrackable<Bead>(position, this, 0);\n    \n    //choose length\n    floatingpoint length = 0.0;\n    \n    if(branch)          length = SysParams::Geometry().monomerSize[_filType];\n    else if(nucleation) length = SysParams::Geometry().minCylinderSize[_filType];\n    \n    auto pos2 = nextPointProjection(position, length, direction);\n        \n    Bead* b2 = _subSystem->addTrackable<Bead>(pos2, this, 1);\n    \n    //create cylindera\n    Cylinder* c0 = _subSystem->addTrackable<Cylinder>(this, b1, b2, _filType, 0);\n    \n    c0->setPlusEnd(true);\n    c0->setMinusEnd(true);\n    _cylinderVector.push_back(c0);\n        \n    // set cylinder's filID\n    c0->setFilID(getId());\n\n\n    //set plus end marker\n    _plusEndPosition = 1;\n\n    // update reaction rates\n    if(const auto& loadForceFunc = _subSystem->getCylinderLoadForceFunc()) {\n        loadForceFunc(c0, ForceFieldTypes::LoadForceEnd::Plus);\n        loadForceFunc(c0, ForceFieldTypes::LoadForceEnd::Minus);\n        c0->updateReactionRates();\n    }\n}\n\n\nFilament::Filament(SubSystem* s, short filamentType, const vector<vector<floatingpoint> >& position,\n                   int numBeads, string projectionType)\n\n    : Trackable(), _subSystem(s), _filType(filamentType) {\n\n    \n    //create a projection of beads\n    vector<vector<floatingpoint>> tmpBeadsCoord;\n    \n    //straight projection\n    if(projectionType == \"STRAIGHT\")\n        tmpBeadsCoord = straightFilamentProjection(position, numBeads);\n    //zigzag projection\n    else if(projectionType == \"ZIGZAG\")\n        tmpBeadsCoord = zigZagFilamentProjection(position, numBeads);\n    //arc projection\n    else if(projectionType == \"ARC\")\n        tmpBeadsCoord = arcFilamentProjection(position, numBeads);\n        //predefined projection aravind sep 9, 15\n    else if(projectionType == \"PREDEFINED\")\n        tmpBeadsCoord = predefinedFilamentProjection(position, numBeads);\n   \n    //create beads\n    auto direction = twoPointDirection(tmpBeadsCoord[0], tmpBeadsCoord[1]);\n        \n    Bead* b1 = _subSystem->addTrackable<Bead>(tmpBeadsCoord[0], this, 0);\n    Bead* b2 = _subSystem->addTrackable<Bead>(tmpBeadsCoord[1], this, 1);\n    Cylinder* c0 = _subSystem->addTrackable<Cylinder>(this, b1, b2, _filType, 0,\n                                                      false, false, true);\n        \n    c0->setPlusEnd(true);\n    c0->setMinusEnd(true);\n    _cylinderVector.push_back(c0);\n\n    // set cylinder's filID\n    c0->setFilID(getId());\n\n\n    for (int i = 2; i<numBeads; i++)\n        extendPlusEnd(tmpBeadsCoord[i]);\n        \n    //set plus end marker\n    _plusEndPosition = numBeads - 1;\n\n    // update reaction rates\n    if(const auto& loadForceFunc = _subSystem->getCylinderLoadForceFunc()) {\n        loadForceFunc(_cylinderVector.back(), ForceFieldTypes::LoadForceEnd::Plus);\n        _cylinderVector.back()->updateReactionRates();\n        loadForceFunc(_cylinderVector.front(), ForceFieldTypes::LoadForceEnd::Minus);\n        _cylinderVector.front()->updateReactionRates();\n    }\n}\n\n\n\nFilament::~Filament() {\n    \n    //remove cylinders, beads from system\n    for(auto &c : _cylinderVector) {\n\n        _subSystem->removeTrackable<Bead>(c->getFirstBead());\n        \n        if(c->isPlusEnd())\n            _subSystem->removeTrackable<Bead>(c->getSecondBead());\n\n        #ifdef CROSSCHECK_CYLINDER\n        cout<<\"RemoveTrackable Cylinder \"<<c->getId()<<\" \"<<c->getStableIndex() <<endl;\n        #endif\n        _subSystem->removeTrackable<Cylinder>(c);\n    }\n}\n\n\n//Extend front for initialization\nvoid Filament::extendPlusEnd(vector<floatingpoint>& coordinates) {\n    \n    Cylinder* cBack = _cylinderVector.back();\n    cBack->setPlusEnd(false);\n    \n    int lpf = cBack->getPosition();\n    \n    Bead* b2 = cBack->getSecondBead();\n    \n    //create a new bead\n//    auto direction = twoPointDirection(b2->vcoordinate(), coordinates);\n//    auto newBeadCoords = nextPointProjection(b2->vcoordinate(),\n//    twoPointDistance(b2->vcoordinate(), coordinates), direction);\n    auto newBeadCoords=coordinates;\n    //create\n    Bead* bNew = _subSystem->addTrackable<Bead>(newBeadCoords, this, b2->getPosition() + 1);\n    Cylinder* c0 = _subSystem->addTrackable<Cylinder> (this, b2, bNew, _filType,\n                                                       lpf + 1, false, false, true);\n    c0->setPlusEnd(true);\n    _cylinderVector.push_back(c0);\n    \n    // set cylinder's filID\n\n    c0->setFilID(getId());\n\n\n}\n\n//Extend back for initialization\nvoid Filament::extendMinusEnd(vector<floatingpoint>& coordinates) {\n\n    Cylinder* cFront = _cylinderVector.front();\n    cFront->setMinusEnd(false);\n    \n    int lpf = cFront->getPosition();\n    \n    Bead* b2 = cFront->getFirstBead();\n    \n    //create a new bead\n    auto direction = twoPointDirection(b2->vcoordinate(), coordinates);\n    auto newBeadCoords = nextPointProjection(b2->vcoordinate(),\n    SysParams::Geometry().cylinderSize[_filType], direction);\n    \n    //create\n    Bead* bNew = _subSystem->addTrackable<Bead>(newBeadCoords, this, b2->getPosition() - 1);\n    Cylinder* c0 = _subSystem->addTrackable<Cylinder>(this, bNew, b2, _filType,\n                                                  lpf - 1, false, false, true);\n    c0->setMinusEnd(true);\n    _cylinderVector.push_front(c0);\n    \n\n    // set cylinder's filID\n    c0->setFilID(getId());\n\n}\n\n//Initialize for restart\nvoid Filament::initializerestart(vector<Cylinder*> cylinderVector,\n        vector<restartCylData>& _rCDatavec) {\n\n    if(SysParams::RUNSTATE){\n        LOG(ERROR) << \"initializerestart Function from Filament class can only be called \"\n                      \"during restart phase. Exiting.\";\n        throw std::logic_error(\"Illegal function call pattern\");\n    }\n    if(_cylinderVector.size())\n        cout<<_cylinderVector.size()<<endl;\n    for(auto cyl:cylinderVector) {\n        auto rcdata = _rCDatavec[cyl->getStableIndex()];\n        cyl->initializerestart( rcdata.totalmonomers, rcdata.endmonomerpos[0],\n                                rcdata.endmonomerpos[1], rcdata.endstatusvec[0],\n                                rcdata.endstatusvec[1], rcdata.endtypevec[0],\n                                rcdata.endtypevec[1]);\n\t    _cylinderVector.push_back(cyl);\n    }\n\n    //set plus end marker\n    _plusEndPosition = getPlusEndCylinder()->getSecondBead()->getPosition();\n\n\t// update reaction rates\n\tif(const auto& loadForceFunc = _subSystem->getCylinderLoadForceFunc()) {\n\t\tloadForceFunc(_cylinderVector.back(), ForceFieldTypes::LoadForceEnd::Plus);\n\t\t_cylinderVector.back()->updateReactionRates();\n\t\tloadForceFunc(_cylinderVector.front(), ForceFieldTypes::LoadForceEnd::Minus);\n\t\t_cylinderVector.front()->updateReactionRates();\n\t}\n\n}\n\n//extend front at runtime\nvoid Filament::extendPlusEnd(short plusEnd) {\n\n    chrono::high_resolution_clock::time_point mins, mine;\n\n    mins = chrono::high_resolution_clock::now();\n    Cylinder* cBack = _cylinderVector.back();\n    \n    int lpf = cBack->getPosition();\n    \n    Bead* b1 = cBack->getFirstBead();\n    Bead* b2 = cBack->getSecondBead();\n    \n    //move last bead of last cylinder forward\n    auto direction1 = twoPointDirection(b1->vcoordinate(), b2->vcoordinate());\n    \n    auto npp = nextPointProjection(b2->vcoordinate(),\n    SysParams::Geometry().monomerSize[_filType], direction1);\n\n    mine = chrono::high_resolution_clock::now();\n\tchrono::duration<floatingpoint> elapsed_time1(mine - mins);\n\tFilextendPlusendtimer1 += elapsed_time1.count();\n\n    //create a new bead in same place as b2\n    Bead* bNew = _subSystem->addTrackable<Bead>(npp, this, b2->getPosition() + 1);\n    \n#ifdef MECHANICS\n    //transfer the same load force to new bead\n    //(approximation until next minimization)\n    bNew->loadForcesP = b2->loadForcesP;\n    bNew->lfip = b2->lfip + 1;\n#endif\n    \n    Cylinder* c0 = _subSystem->addTrackable<Cylinder>(this, b2, bNew, _filType,\n                                                      lpf + 1, true);\n\n    mins = chrono::high_resolution_clock::now();\n    _cylinderVector.back()->setPlusEnd(false);\n    _cylinderVector.push_back(c0);\n    _cylinderVector.back()->setPlusEnd(true);\n\n    #ifdef CROSSCHECK_CYLINDER\n    CController::_crosscheckdumpFilechem <<\"PlusEnd cylinder set\"<<endl;\n    #endif\n    \n    // set cylinder's filID\n\n    c0->setFilID(getId());\n\n    #ifdef CROSSCHECK_CYLINDER\n    CController::_crosscheckdumpFilechem <<\"Cyl FilID set\"<<endl;\n    #endif\n\n\n#ifdef CHEMISTRY\n    //get last cylinder, mark species\n    CMonomer* m = _cylinderVector.back()->getCCylinder()->getCMonomer(0);\n    m->speciesPlusEnd(plusEnd)->up();\n#endif\n    #ifdef CROSSCHECK_CYLINDER\n    CController::_crosscheckdumpFilechem <<\"Species PlusEnd set\"<<endl;\n    #endif\n#ifdef DYNAMICRATES\n    //update reaction rates\n    _cylinderVector.back()->updateReactionRates();\n#endif\n    #ifdef CROSSCHECK_CYLINDER\n    CController::_crosscheckdumpFilechem <<\"Reaction Rates updated\"<<endl;\n    #endif\n    \n    _deltaPlusEnd++;\n\n/*    cout<<\"Extend minus End Cylinder ID = \"<<cBack->getId()<<endl;\n    cBack->printSelf();*/\n\n    mine = chrono::high_resolution_clock::now();\n\tchrono::duration<floatingpoint> elapsed_time2(mine - mins);\n\tFilextendPlusendtimer2 += elapsed_time2.count();\n    #ifdef CROSSCHECK_CYLINDER\n    CController::_crosscheckdumpFilechem <<\"extendPlusend\"<<endl;\n    #endif\n}\n\n//extend back at runtime\nvoid Filament::extendMinusEnd(short minusEnd) {\n    \n    Cylinder* cFront = _cylinderVector.front();\n    int lpf = cFront->getPosition();\n    \n    Bead* b2 = cFront->getFirstBead();\n    Bead* b1 = cFront->getSecondBead();\n    \n    //move last bead of last cylinder forward\n    auto direction1 = twoPointDirection(b1->vcoordinate(), b2->vcoordinate());\n    \n    auto npp = nextPointProjection(b2->vcoordinate(),\n    SysParams::Geometry().monomerSize[_filType], direction1);\n    \n    //create a new bead in same place as b2\n    Bead* bNew = _subSystem->addTrackable<Bead>(npp, this, b2->getPosition() - 1);\n\n#ifdef MECHANICS\n    //transfer the same load force to new bead\n    //(approximation until next minimization)\n    bNew->loadForcesM = b2->loadForcesM;\n    bNew->lfim = b2->lfim + 1;\n#endif\n    \n    Cylinder* c0 = _subSystem->addTrackable<Cylinder>(this, bNew, b2, _filType,\n                                                      lpf - 1, false, true);\n    _cylinderVector.front()->setMinusEnd(false);\n    _cylinderVector.push_front(c0);\n    _cylinderVector.front()->setMinusEnd(true);\n\n    #ifdef CROSSCHECK_CYLINDER\n    CController::_crosscheckdumpFilechem <<\"MinusEnd cylinder set\"<<endl;\n    #endif\n    \n    // set cylinder's filID\n\n    c0->setFilID(getId());\n\n#ifdef CHEMISTRY\n    //get first cylinder, mark species\n    auto newCCylinder = getCylinderVector().front()->getCCylinder();\n    CMonomer* m = newCCylinder->getCMonomer(newCCylinder->getSize() - 1);\n    \n    m->speciesMinusEnd(minusEnd)->up();\n#ifdef CROSSCHECK_CYLINDER\n    CController::_crosscheckdumpFilechem <<\"MinusEnd species set\"<<endl;\n#endif\n\n#endif\n    \n#ifdef DYNAMICRATES\n    //update reaction rates\n    _cylinderVector.front()->updateReactionRates();\n#endif\n    #ifdef CROSSCHECK_CYLINDER\n    CController::_crosscheckdumpFilechem <<\"Reaction rates updated\"<<endl;\n    #endif\n    _deltaMinusEnd++;\n\n/*    cout<<\"Extend plus End Cylinder ID = \"<<cFront->getId()<<endl;\n    cFront->printSelf();*/\n    #ifdef CROSSCHECK_CYLINDER\n    CController::_crosscheckdumpFilechem <<\"extendMinusend\"<<endl;\n    #endif\n}\n\n//Depolymerize front at runtime\nvoid Filament::retractPlusEnd() {\n    \n    Cylinder* retCylinder = _cylinderVector.back();\n\n/*    cout<<\"Ret plus End Cylinder ID = \"<<retCylinder->getId()<<endl;\n    retCylinder->printSelf();*/\n\n    _cylinderVector.pop_back();\n    \n#ifdef MECHANICS\n    //transfer load forces\n    Bead* bd = _cylinderVector.back()->getSecondBead();\n    bd->loadForcesP = retCylinder->getSecondBead()->loadForcesP;\n    bd->lfip = retCylinder->getSecondBead()->lfip - 1;\n#endif\n    \n    _subSystem->removeTrackable<Bead>(retCylinder->getSecondBead());\n    removeChild(retCylinder->getSecondBead());\n    #ifdef CROSSCHECK_CYLINDER\n    cout<<\"RemoveTrackable Cylinder \"<<retCylinder->getId()<<\" \"\n                                                             \"\"<<retCylinder->getStableIndex()<<endl;\n    #endif\n    _subSystem->removeTrackable<Cylinder>(retCylinder);\n    removeChild(retCylinder);\n    \n    _cylinderVector.back()->setPlusEnd(true);\n\n    \n#ifdef DYNAMICRATES\n    //update rates of new front\n    _cylinderVector.back()->updateReactionRates();\n#endif\n    \n    _deltaPlusEnd--;\n\n    #ifdef CROSSCHECK_CYLINDER\n    CController::_crosscheckdumpFilechem <<\"retractPlusend\"<<endl;\n    #endif\n}\n\nvoid Filament::retractMinusEnd() {\n    \n    Cylinder* retCylinder = _cylinderVector.front();\n\n/*    cout<<\"Ret minus End Cylinder ID = \"<<retCylinder->getId()<<endl;\n    retCylinder->printSelf();*/\n\n    _cylinderVector.pop_front();\n    \n#ifdef MECHANICS\n    //transfer load forces\n    Bead* bd = _cylinderVector.front()->getFirstBead();\n    bd->loadForcesM = retCylinder->getFirstBead()->loadForcesM;\n    bd->lfim = retCylinder->getFirstBead()->lfim - 1;\n#endif\n    \n    _subSystem->removeTrackable<Bead>(retCylinder->getFirstBead());\n    removeChild(retCylinder->getFirstBead());\n    #ifdef CROSSCHECK_CYLINDER\n    cout<<\"RemoveTrackable Cylinder \"<<retCylinder->getId()<<\" \"<<retCylinder->getStableIndex() <<endl;\n    #endif\n    _subSystem->removeTrackable<Cylinder>(retCylinder);\n    removeChild(retCylinder);\n    \n    _cylinderVector.front()->setMinusEnd(true);\n    \n#ifdef DYNAMICRATES\n    //update rates of new back\n    _cylinderVector.front()->updateReactionRates();\n#endif\n    \n    _deltaMinusEnd--;\n    \n    ///If filament has turned over, mark as such\n    if(_plusEndPosition == getMinusEndCylinder()->getFirstBead()->getPosition()) {\n        \n        //reset\n        _plusEndPosition = getPlusEndCylinder()->getSecondBead()->getPosition();\n        _turnoverTime = tau();\n    }\n    #ifdef CROSSCHECK_CYLINDER\n    CController::_crosscheckdumpFilechem <<\"retractMinusEnd\"<<endl;\n    #endif\n}\n\nvoid Filament::polymerizePlusEnd() {\n    \n    Cylinder* cBack = _cylinderVector.back();\n    \n    Bead* b1 = cBack->getFirstBead();\n    Bead* b2 = cBack->getSecondBead();\n    \n    auto direction = twoPointDirection(b1->vcoordinate(), b2->vcoordinate());\n    \n    b2->coordinate() = vector2Vec<3, floatingpoint>(nextPointProjection(b2->vcoordinate(),\n    SysParams::Geometry().monomerSize[_filType], direction));\n\n    // Update cylinder data\n    cBack->getCoordinate() = (floatingpoint)0.5 * (b1->coordinate() + b2->coordinate());\n    \n#ifdef MECHANICS\n    //increment load\n    b2->lfip++;\n    \n    //increase eq length, update\n    floatingpoint newEqLen = cBack->getMCylinder()->getEqLength() +\n                      SysParams::Geometry().monomerSize[_filType];\n    cBack->getMCylinder()->setEqLength(_filType, newEqLen);\n#endif\n    \n#ifdef DYNAMICRATES\n    //update rates of new back\n    _cylinderVector.back()->updateReactionRates();\n#endif\n\n    _polyPlusEnd++;\n\n/*    cout<<\"Poly plus End Cylinder ID = \"<<cBack->getId()<<endl;\n    cBack->printSelf();*/\n    #ifdef CROSSCHECK_CYLINDER\n    CController::_crosscheckdumpFilechem <<\"polymerizePlusend\"<<endl;\n    #endif\n\n}\n\nvoid Filament::polymerizeMinusEnd() {\n    \n    Cylinder* cFront = _cylinderVector.front();\n    \n    Bead* b1 = cFront->getFirstBead();\n    Bead* b2 = cFront->getSecondBead();\n\n    auto direction = twoPointDirection(b2->vcoordinate(), b1->vcoordinate());\n    \n    b1->coordinate() = vector2Vec<3, floatingpoint>(nextPointProjection(b1->vcoordinate(),\n    SysParams::Geometry().monomerSize[_filType], direction));\n\n    // Update cylinder data\n    cFront->getCoordinate() = (floatingpoint)0.5 * (b1->coordinate() + b2->coordinate());\n\n#ifdef MECHANICS\n    \n    //increment load\n    b1->lfim++;\n    \n    //increase eq length, update\n    floatingpoint newEqLen = cFront->getMCylinder()->getEqLength() +\n                      SysParams::Geometry().monomerSize[_filType];\n    cFront->getMCylinder()->setEqLength(_filType, newEqLen);\n#endif\n\n#ifdef DYNAMICRATES\n    //update rates of new back\n    _cylinderVector.front()->updateReactionRates();\n#endif\n\n    _polyMinusEnd++;\n\n/*    cout<<\"Poly minus End Cylinder ID = \"<<cFront->getId()<<endl;\n    cFront->printSelf();*/\n    #ifdef CROSSCHECK_CYLINDER\n    CController::_crosscheckdumpFilechem <<\"polymerizeMinusend\"<<endl;\n    #endif\n\n}\n\nvoid Filament::depolymerizePlusEnd() {\n    \n    Cylinder* cBack = _cylinderVector.back();\n    \n    Bead* b1 = cBack->getFirstBead();\n    Bead* b2 = cBack->getSecondBead();\n\n    auto direction = twoPointDirection(b2->vcoordinate(), b1->vcoordinate());\n    \n    b2->coordinate() = vector2Vec<3, floatingpoint>(nextPointProjection(b2->vcoordinate(),\n    SysParams::Geometry().monomerSize[_filType], direction));\n\n    // Update cylinder data\n    cBack->getCoordinate() = (floatingpoint)0.5 * (b1->coordinate() + b2->coordinate());\n\n#ifdef MECHANICS\n    \n    //increment load\n    b2->lfip--;\n    \n    //decrease eq length, update\n    floatingpoint newEqLen = cBack->getMCylinder()->getEqLength() -\n                      SysParams::Geometry().monomerSize[_filType];\n    cBack->getMCylinder()->setEqLength(_filType, newEqLen);\n#endif\n#ifdef DYNAMICRATES\n    //update rates of new back\n    _cylinderVector.front()->updateReactionRates();\n#endif\n    \n    _depolyPlusEnd++;\n\n/*    cout<<\"DePoly plus End Cylinder ID = \"<<cBack->getId()<<endl;\n    cBack->printSelf();*/\n    #ifdef CROSSCHECK_CYLINDER\n    CController::_crosscheckdumpFilechem <<\"depolymerizePlusend\"<<endl;\n    #endif\n\n}\n\nvoid Filament::depolymerizeMinusEnd() {\n    \n    Cylinder* cFront = _cylinderVector.front();\n    \n    Bead* b1 = cFront->getFirstBead();\n    Bead* b2 = cFront->getSecondBead();\n    \n    auto direction = twoPointDirection(b1->vcoordinate(), b2->vcoordinate());\n    \n    b1->coordinate() = vector2Vec<3, floatingpoint>(nextPointProjection(b1->vcoordinate(),\n    SysParams::Geometry().monomerSize[_filType], direction));\n\n    // Update cylinder data\n    cFront->getCoordinate() = (floatingpoint)0.5 * (b1->coordinate() + b2->coordinate());\n\n#ifdef MECHANICS\n    \n    b1->lfim--;\n    \n    //decrease eq length, update\n    floatingpoint newEqLen = cFront->getMCylinder()->getEqLength() -\n                      SysParams::Geometry().monomerSize[_filType];\n    cFront->getMCylinder()->setEqLength(_filType, newEqLen);\n#endif\n\n#ifdef DYNAMICRATES\n    //update rates of new back\n    _cylinderVector.front()->updateReactionRates();\n#endif\n\n    _depolyMinusEnd++;\n/*    cout<<\"DePoly minus End Cylinder ID = \"<<cFront->getId()<<endl;\n    cFront->printSelf();*/\n    #ifdef CROSSCHECK_CYLINDER\n    CController::_crosscheckdumpFilechem <<\"depolymerizeMinusend\"<<endl;\n    #endif\n}\n\n\nvoid Filament::nucleate(short plusEnd, short filament, short minusEnd) {\n    \n#ifdef CHEMISTRY\n    //chemically initialize species\n    CCylinder* cc = _cylinderVector[0]->getCCylinder();\n    int monomerPosition = SysParams::Geometry().cylinderNumMon[_filType] / 2 + 1;\n    \n    CMonomer* m1 = cc->getCMonomer(monomerPosition - 1);\n    CMonomer* m2 = cc->getCMonomer(monomerPosition);\n    CMonomer* m3 = cc->getCMonomer(monomerPosition + 1);\n    \n    //minus end\n    m1->speciesMinusEnd(minusEnd)->up();\n    \n    //filament\n    m2->speciesFilament(filament)->up();\n    \n    for(auto j : SysParams::Chemistry().bindingIndices[_filType])\n        m2->speciesBound(j)->up();\n    \n    //plus end\n    m3->speciesPlusEnd(plusEnd)->up();\n#endif\n\n    _nucleationReaction++;\n\n}\n\n\nFilament* Filament::sever(int cylinderPosition) {\n    \n    int vectorPosition = 0;\n    \n    //loop through cylinder vector, find position\n    for(auto &c : _cylinderVector) {\n        \n        if(c->getPosition() == cylinderPosition) break;\n        else vectorPosition++;\n    }\n    \n    //if vector position is zero, we can't sever. return null\n    if(vectorPosition == 0) return nullptr;\n    \n#ifdef CHEMISTRY\n    //if any of the cylinders are only one monomer long, we can't sever\n    CCylinder* ccBack  = _cylinderVector[vectorPosition - 1]->getCCylinder();\n    CMonomer* cm = ccBack->getCMonomer(ccBack->getSize() - 1);\n    \n    if(cm->activeSpeciesMinusEnd() != -1) return nullptr;\n#endif\n    \n    //create a new filament\n    Filament* newFilament = _subSystem->addTrackable<Filament>(_subSystem, _filType);\n    \n    //Split the cylinder vector at position, transfer cylinders to new filament\n    for(int i = vectorPosition; i > 0; i--) {\n        \n        Cylinder* c = _cylinderVector.front();\n        _cylinderVector.pop_front();\n\n        newFilament->_cylinderVector.push_back(c);\n        \n        //TRANSFER CHILD\n        unique_ptr<Component> &&tmp = this->getChild(c);\n        this->transferChild(std::move(tmp), (Composite*)newFilament);\n\n        //Add beads and cylinder to new parent\n        if(i == vectorPosition) {\n            unique_ptr<Component> &&tmp2 = this->getChild(c->getFirstBead());\n            this->transferChild(std::move(tmp2), (Composite*)newFilament);\n        }\n        unique_ptr<Component> &&tmp1 = this->getChild(c->getSecondBead());\n        this->transferChild(std::move(tmp1), (Composite*)newFilament);\n    }\n    //new front of new filament, back of old\n    auto c1 = newFilament->_cylinderVector.back();\n    auto c2 = _cylinderVector.front();\n    \n    ///copy bead at severing point, attach to new filament\n    Bead* newB = _subSystem->addTrackable<Bead>(*(c2->getFirstBead()));\n    Bead* oldB = c2->getFirstBead();\n    \n    //offset these beads by a little for safety\n    auto msize = SysParams::Geometry().monomerSize[_filType];\n    \n    vector<floatingpoint> offsetCoord =\n    {(Rand::randInteger(0,1) ? -1 : +1) * Rand::randfloatingpoint(msize, 2 * msize),\n     (Rand::randInteger(0,1) ? -1 : +1) * Rand::randfloatingpoint(msize, 2 * msize),\n     (Rand::randInteger(0,1) ? -1 : +1) * Rand::randfloatingpoint(msize, 2 * msize)};\n    \n    oldB->coordinate()[0] += offsetCoord[0];\n    oldB->coordinate()[1] += offsetCoord[1];\n    oldB->coordinate()[2] += offsetCoord[2];\n    \n    newB->coordinate()[0] += -offsetCoord[0];\n    newB->coordinate()[1] += -offsetCoord[1];\n    newB->coordinate()[2] += -offsetCoord[2];\n    \n    //add bead\n    c1->setSecondBead(newB);\n    newFilament->addChild(unique_ptr<Component>(newB));\n    \n    //set plus and minus ends\n    c1->setPlusEnd(true);\n    c2->setMinusEnd(true);\n    \n#ifdef CHEMISTRY\n    //mark the plus and minus ends of the new and old filament\n    CCylinder* cc1 = c1->getCCylinder();\n    CCylinder* cc2 = c2->getCCylinder();\n    \n    CMonomer* m1 = cc1->getCMonomer(cc1->getSize() - 1);\n    CMonomer* m2 = cc2->getCMonomer(0);\n    \n    short filamentInt1 = m1->activeSpeciesFilament();\n    short filamentInt2 = m2->activeSpeciesFilament();\n    \n    //plus end\n    m1->speciesFilament(filamentInt1)->down();\n    m1->speciesPlusEnd(filamentInt1)->up();\n    \n    for(auto j : SysParams::Chemistry().bindingIndices[_filType])\n        m1->speciesBound(j)->down();\n    \n    //minus end\n    m2->speciesFilament(filamentInt2)->down();\n    m2->speciesMinusEnd(filamentInt2)->up();\n    \n    for(auto j : SysParams::Chemistry().bindingIndices[_filType])\n        m2->speciesBound(j)->down();\n    \n    //remove any cross-cylinder rxns between these two cylinders\n    cc1->removeCrossCylinderReactions(cc2);\n    cc2->removeCrossCylinderReactions(cc1);\n#endif\n    _severingReaction++;\n    _severingID.push_back(newFilament->getId());\n    return newFilament;\n}\n\nvector<vector<floatingpoint>> Filament::straightFilamentProjection(const vector<vector<floatingpoint>>& v, int numBeads) {\n    \n    vector<vector<floatingpoint>> coordinate;\n    vector<floatingpoint> tmpVec (3, 0);\n    vector<floatingpoint> tau (3, 0);\n    floatingpoint invD = 1/twoPointDistance(v[1], v[0]);\n    tau[0] = invD * ( v[1][0] - v[0][0] );\n    tau[1] = invD * ( v[1][1] - v[0][1] );\n    tau[2] = invD * ( v[1][2] - v[0][2] );\n    \n    for (int i = 0; i<numBeads; i++) {\n        \n        tmpVec[0] = v[0][0] + SysParams::Geometry().cylinderSize[_filType] * i * tau[0];\n        tmpVec[1] = v[0][1] + SysParams::Geometry().cylinderSize[_filType] * i * tau[1];\n        tmpVec[2] = v[0][2] + SysParams::Geometry().cylinderSize[_filType] * i * tau[2];\n        \n        coordinate.push_back(tmpVec);\n    }\n    return coordinate;\n}\n\nvector<vector<floatingpoint>> Filament::zigZagFilamentProjection(const vector<vector<floatingpoint>>& v, int numBeads){\n    \n    vector<vector<floatingpoint>> coordinate;\n    vector<floatingpoint> tmpVec (3, 0);\n    vector<floatingpoint> tau (3, 0);\n    floatingpoint invD = 1/twoPointDistance(v[1], v[0]);\n    tau[0] = invD * ( v[1][0] - v[0][0] );\n    tau[1] = invD * ( v[1][1] - v[0][1] );\n    tau[2] = invD * ( v[1][2] - v[0][2] );\n    \n    vector<floatingpoint> perptau = {-tau[1], tau[0], tau[2]};\n    \n    \n    for (int i = 0; i<numBeads; i++) {\n        \n        if(i%2 == 0) {\n            tmpVec[0] = v[0][0] + SysParams::Geometry().cylinderSize[_filType] * i * tau[0];\n            tmpVec[1] = v[0][1] + SysParams::Geometry().cylinderSize[_filType] * i * tau[1];\n            tmpVec[2] = v[0][2] + SysParams::Geometry().cylinderSize[_filType] * i * tau[2];\n        }\n        else {\n            tmpVec[0] = v[0][0] + SysParams::Geometry().cylinderSize[_filType] * i * perptau[0];\n            tmpVec[1] = v[0][1] + SysParams::Geometry().cylinderSize[_filType] * i * perptau[1];\n            tmpVec[2] = v[0][2] + SysParams::Geometry().cylinderSize[_filType] * i * perptau[2];\n        }\n        \n        coordinate.push_back(tmpVec);\n    }\n    return coordinate;\n}\n\n/// Create a projection\n/// @note - created by Aravind 12/2014\nvoid marsagila(vector<floatingpoint>&v) {\n    \n    floatingpoint d1,d2,d3;\n    floatingpoint *x=new floatingpoint[3];\n    d1=2*Rand::randfloatingpoint(0,1)-1;\n    d2=2*Rand::randfloatingpoint(0,1)-1;\n    d3=pow(d1,2)+pow(d2,2);\n    \n    while(d3>=1) {\n        d1=2*Rand::randfloatingpoint(0,1)-1;\n        d2=2*Rand::randfloatingpoint(0,1)-1;\n        d3=pow(d1,2)+pow(d2,2);\n    }\n    \n    x[0]=2.0*d1*pow((1.0-d3),0.5);\n    x[1]=2.0*d2*pow(1.0-d3,0.5);\n    x[2]=1.0-2.0*d3;\n    v[0]=2.0*d1*pow((1.0-d3),0.5);\n    v[1]=2.0*d2*pow(1.0-d3,0.5);\n    v[2]=1.0-2.0*d3;\n}\n\n/// Matrix multiply\n/// @note - created by Aravind 12/2014\nvoid matrix_mul(boost::numeric::ublas::matrix<floatingpoint>&X,\n                boost::numeric::ublas::matrix<floatingpoint>&Y,\n                boost::numeric::ublas::matrix<floatingpoint>&Z,\n                vector<floatingpoint>&x,vector<floatingpoint>&y,\n                vector<floatingpoint>&z,int nbeads,\n                vector<vector<floatingpoint>> &coordinate) {\n    \n    int t,i;\n    floatingpoint dt,length,cyl_length,sum;\n    vector<int> id;\n    vector<floatingpoint> dx,dy,dz,dx2,dy2,dz2,length2,dxdy2,dummyy(3);\n    using namespace boost::numeric::ublas;\n    matrix<floatingpoint> B(4,4),B2(1,4),temp1(4,1),dummy(1,1),temp2(4,1),temp3(4,1);\n    \n    // B\n    B(0,0)=1; B(0,1)=0; B(0,2)=0; B(0,3)=0;\n    B(1,0)=-3; B(1,1)=3; B(1,2)=0; B(1,3)=0;\n    B(2,0)=3; B(2,1)=-6; B(2,2)=3; B(2,3)=0;\n    B(3,0)=-1; B(3,1)=3; B(3,2)=-3; B(3,3)=1;\n    \n    axpy_prod(B,X,temp1);\n    axpy_prod(B,Y,temp2);\n    axpy_prod(B,Z,temp3);\n    B2(0,0)=1;\n    \n    for(t=0;t<=4000;t++) {\n        dt=0.00025*t;\n        B2(0,1)=dt;\n        B2(0,2)=dt*dt;\n        B2(0,3)=dt*dt*dt;\n        axpy_prod(B2,temp1,dummy);\n        x.push_back(dummy(0,0));\n        axpy_prod(B2,temp2,dummy);\n        y.push_back(dummy(0,0));\n        axpy_prod(B2,temp3,dummy);\n        z.push_back(dummy(0,0));\n    }\n    \n    adjacent_difference(x.begin(),x.end(),back_inserter(dx));//dx\n    adjacent_difference(y.begin(),y.end(),back_inserter(dy));//dy\n    adjacent_difference(z.begin(),z.end(),back_inserter(dz));//dz\n    \n    transform(dx.begin(), dx.end(),dx.begin(),\n              back_inserter(dx2), multiplies<floatingpoint>());\n    transform(dy.begin(), dy.end(),dy.begin(),\n              back_inserter(dy2), multiplies<floatingpoint>());\n    transform(dz.begin(), dz.end(),dz.begin(),\n              back_inserter(dz2), multiplies<floatingpoint>());\n    \n    //array of sum(dx^2+dy^2)\n    transform(dx2.begin(),dx2.end(),dy2.begin(),\n              back_inserter(dxdy2),plus<floatingpoint>());\n    //array of sum(dx^2+dy^2+dz^2)\n    transform(dxdy2.begin(),dxdy2.end(),dz2.begin(),\n              back_inserter(length2),plus<floatingpoint>());\n    \n    std::vector<floatingpoint> tempLength;\n    for(auto x: length2) tempLength.push_back(sqrt(x));\n    length2 = tempLength; length2[0]=0.0;\n    \n    length = boost::accumulate(length2, 0.0);//arc length.\n    \n    //making equal divisions.\n    i=0;sum=0.0;id.push_back(0.0);\n    cyl_length=length/(nbeads-1);\n    \n    while(i<=4000) {\n        sum+=length2[i];\n        if(sum>=cyl_length||i==4000) {\n            id.push_back(i);\n            sum=0.0;\n        }\n        i++;\n    }\n    \n    for(i=0;i<id.size();i++) {\n        dummyy[0]=x[id[i]];\n        dummyy[1]=y[id[i]];\n        dummyy[2]=z[id[i]];\n        coordinate.push_back(dummyy);\n    }\n}\n\nvoid arcOutward(vector<floatingpoint>&v1,vector<floatingpoint>&v2, const vector<vector<floatingpoint>>&v) {\n    \n    vector<floatingpoint> center,tempv1,tempv2,temp2,temp3(3),\n                   temp4(3),mid,mid2(3),mid3(3),temp5;\n    \n    center = GController::getCenter();\n    \n    // point v[0]\n    temp3[0]=v[0][0];\n    temp3[1]=v[0][1];\n    temp3[2]=v[0][2];\n    \n    //point v[1]\n    temp4[0]=v[1][0];\n    temp4[1]=v[1][1];\n    temp4[2]=v[1][2];\n    \n    mid=midPointCoordinate(temp3, temp4, 0.5);\n    mid2=midPointCoordinate(mid, temp4, 0.5);\n    mid3=midPointCoordinate(mid, temp3, 0.5);\n    \n    //vector between v[1] and center stored in tempv1\n    std::transform(v[1].begin(), v[1].end(), center.begin(),\n                   std::back_inserter(tempv1), std::minus<floatingpoint>());\n    \n    floatingpoint dist=twoPointDistance(center, temp4);\n    dist=300/dist;\n    \n    std::transform(tempv1.begin(),tempv1.end(),tempv1.begin(),\n                   [&](auto x) { return x * dist; });\n    std::transform(mid.begin(), mid.end(), tempv1.begin(),\n                   std::back_inserter(v1), std::plus<floatingpoint>());\n    \n    //vector between v[0] and center stored in tempv2\n    std::transform(v[0].begin(), v[0].end(), center.begin(),\n                   std::back_inserter(tempv2), std::minus<floatingpoint>());\n    \n    dist=twoPointDistance(center, temp3);\n    dist=100/dist;\n    \n    std::transform(tempv2.begin(),tempv2.end(),tempv2.begin(),\n                   [&](auto x) { return x * dist; });\n    std::transform(mid3.begin(), mid3.end(), tempv2.begin(),\n                   std::back_inserter(v2), std::plus<floatingpoint>());\n}\n\nvector<vector<floatingpoint>> Filament::arcFilamentProjection(const vector<vector<floatingpoint>>& v, int numBeads) {\n    \n    using namespace boost::numeric::ublas;\n\n    std::vector<floatingpoint> X3,x3(3),x4(3),X4,x,y,z;\n    matrix<floatingpoint> C(3,3),B(4,4),X(4,1),Y(4,1),Z(4,1);\n    std::vector< std::vector<floatingpoint> > coordinates;\n\n    arcOutward(X3,X4,v);\n    X(0,0)=v[0][0]; X(1,0)=X3[0]; X(2,0)=X4[0]; X(3,0)=v[1][0];\n    Y(0,0)=v[0][1]; Y(1,0)=X3[1]; Y(2,0)=X4[1]; Y(3,0)=v[1][1];\n    Z(0,0)=v[0][2]; Z(1,0)=X3[2]; Z(2,0)=X4[2]; Z(3,0)=v[1][2];\n    //\n    matrix_mul(X,Y,Z,x,y,z,numBeads,coordinates);\n    return coordinates;\n}\n// predefined projection\nvector<vector<floatingpoint>> Filament::predefinedFilamentProjection(const vector<vector<floatingpoint>>& v, int numBeads) {\n    return v;\n}\n//@\nvoid Filament::printSelf()const {\n    \n    cout << endl;\n    \n    cout << \"Filament: ptr = \" << this << endl;\n    cout << \"Filament ID = \" << getId() << endl;\n    cout << \"Filament type = \" << _filType << endl;\n    \n    cout << endl;\n    cout << \"Cylinder information...\" << endl;\n    \n    for(auto c : _cylinderVector)\n        c->printSelf();\n    \n    cout << endl;\n    \n}\n\nbool Filament::isConsistent() {\n    \n#ifdef CHEMISTRY\n    //check consistency of each individual cylinder\n    for(auto &c : _cylinderVector) {\n        if(!c->getCCylinder()->isConsistent()) {\n         \n            cout << \"Cylinder at position \" << c->getPosition()\n                 << \" is chemically inconsistent\" << endl;\n            return false;\n        }\n    }\n\n    //check that it only has one plus end and one minus end\n    int numPlusEnd = 0;\n    int numMinusEnd = 0;\n        \n    for(auto &c : _cylinderVector) {\n        \n        for(int i = 0; i < c->getCCylinder()->getSize(); i++) {\n            auto m = c->getCCylinder()->getCMonomer(i);\n            \n            if(m->activeSpeciesPlusEnd() != -1) numPlusEnd++;\n            if(m->activeSpeciesMinusEnd() != -1) numMinusEnd++;\n        }\n    }\n    if(numPlusEnd != 1) {\n        cout << \"This filament has more than one plus end species.\" << endl;\n        return false;\n    }\n    if(numMinusEnd != 1) {\n        cout << \"This filament has more than one minus end species.\" << endl;\n        return false;\n    }\n     \n#endif\n    return true;\n}\n\n\nspecies_copy_t Filament::countSpecies(short filamentType, const string& name) {\n    \n    species_copy_t copyNum = 0;\n    \n    for(auto f : getElements()) {\n        \n        if(f->getType() != filamentType) continue;\n        \n        //loop through the filament\n        for(auto c : f->_cylinderVector) {\n            \n            for(int i = 0; i < c->getCCylinder()->getSize(); i++) {\n                auto m = c->getCCylinder()->getCMonomer(i);\n                \n                //filament species\n                int activeIndex = m->activeSpeciesFilament();\n                \n                if(activeIndex != -1) {\n                    \n                    auto s = m->speciesFilament(activeIndex);\n                    string sname = SpeciesNamesDB::removeUniqueFilName(s->getName());\n                    \n                    if(sname == name)\n                        copyNum += s->getN();\n                    \n                    continue;\n                }\n                \n                //plus end species\n                activeIndex = m->activeSpeciesPlusEnd();\n                \n                if(activeIndex != -1) {\n                    \n                    auto s = m->speciesPlusEnd(activeIndex);\n                    string sname = SpeciesNamesDB::removeUniqueFilName(s->getName());\n                    \n                    if(sname == name)\n                        copyNum += s->getN();\n                    \n                    continue;\n                }\n                \n                //minus end species\n                activeIndex = m->activeSpeciesMinusEnd();\n                \n                if(activeIndex != -1) {\n                    \n                    auto s = m->speciesMinusEnd(activeIndex);\n                    string sname = SpeciesNamesDB::removeUniqueFilName(s->getName());\n                    \n                    if(sname == name)\n                        copyNum += s->getN();\n                    \n                    continue;\n                }\n                \n            }\n        }\n    }\n    return copyNum;\n}\n\nfloatingpoint Filament::FilextendPlusendtimer1 = 0.0;\nfloatingpoint Filament::FilextendPlusendtimer2 = 0.0;\nfloatingpoint Filament::FilextendPlusendtimer3 = 0.0;\nfloatingpoint Filament::FilextendMinusendtimer1 = 0.0;\nfloatingpoint Filament::FilextendMinusendtimer2 = 0.0;\nfloatingpoint Filament::FilextendMinusendtimer3 = 0.0;\n\n\n", "meta": {"hexsha": "4d7756c074e4b17d4e684810790565eea5a8027c", "size": 36930, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Structure/Filament.cpp", "max_stars_repo_name": "allen-cell-animated/medyan", "max_stars_repo_head_hexsha": "0b5ef64fb338c3961673361e5632980617937ee6", "max_stars_repo_licenses": ["BSD-4-Clause-UC"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Structure/Filament.cpp", "max_issues_repo_name": "allen-cell-animated/medyan", "max_issues_repo_head_hexsha": "0b5ef64fb338c3961673361e5632980617937ee6", "max_issues_repo_licenses": ["BSD-4-Clause-UC"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Structure/Filament.cpp", "max_forks_repo_name": "allen-cell-animated/medyan", "max_forks_repo_head_hexsha": "0b5ef64fb338c3961673361e5632980617937ee6", "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": 32.1970357454, "max_line_length": 124, "alphanum_fraction": 0.6173571622, "num_tokens": 10374, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.689305616785446, "lm_q2_score": 0.480478678047907, "lm_q1q2_score": 0.33119665152406824}}
{"text": "/* copyright Grant Rostig (c)2019 see LICENSE file */\n#include <iostream>\n#include <iomanip>\n#include <string>\n#include <string_view>\n\n#include <map>\n#include <unordered_map>\n#include <iterator>\n#include <random>\n#include <thread>\n#include <algorithm>\n#include <functional>\n#include <future>\n#include <cassert>\n#include <stdexcept>\n#include <jthread.hpp>  // WARNING c++20 experimental, but std:: namespace anyway!\n#include <boost/math/special_functions/binomial.hpp>\n//#include <boost/log/core.hpp>\n#include <boost/log/trivial.hpp>\n#include <boost/log/expressions.hpp>\n//#include <tr1/cmath>  // to pick up beta()\n#include <eigen3/Eigen/Dense>\nusing std::cout;\nusing std::cerr;\nusing std::cin;\nusing std::endl;\n\nnamespace grostig  {\n\n//   * Bjarne Stroustrup. The C++ Programming Language (4th edition). 2013.\n//   ISBN: 978-0-321-56384-2. Chapter 11.5: Explicit type conversion. page 299.\ntemplate <class Target, class Source>\nTarget narrow_cast_runtime(Source v)\n{\n  auto r = static_cast<Target>(v);  // todo: probably some undefined behavior with float/double\n  if (static_cast<Source>(r)!=v)\n    throw std::runtime_error(\"narrow_cast<>() failed\");\n  return r;\n}\n\nclass thread_guard\n{\n    std::thread& t;\npublic:\n    explicit thread_guard(std::thread& t_):\n        t(t_)\n    {}\n    ~thread_guard()\n    {\n        if(t.joinable())\n        {\n            t.join();\n        }\n    }\n    thread_guard(thread_guard const&)=delete;\n    thread_guard& operator=(thread_guard const&)=delete;\n};\n\n/* std::cout << \"Pascal's triangle:\\n\";  // may be wrong.\nfor(int n = 1; n < 10; ++n) {\n    std::cout << std::string(20-n*2, ' ');\n    for(int k = 1; k < n; ++k)\n        std::cout << std::setw(3) << binomial_coefficient_nCk(n,k) << ' ';\n    std::cout << '\\n';\n}\ndouble binomial_coefficient_nCk(int const n, int const k) {  // THIS IS partly WRONG, use boost.\n    if (n == 0 || n == k) return 1;\n    return 1/ ((n+1) * std::tr1::beta( n-k+1, k+1 ));\n} */\n\n}\nstd::string         PGM_NAME               {\"binomial\"};\nconstexpr size_t    CPU_CORES_QTY =        8;\nconstexpr size_t    THREADS_MIN =          2;\nconstexpr size_t    THREADS_MAX =          CPU_CORES_QTY;\nconstexpr size_t    MAX_ASYNC_FUTURES =    CPU_CORES_QTY;\nconstexpr size_t    BINOMIAL_TRIALS_MAX =  1000;  // bernouli trials max number of them.\nconstexpr size_t    TRIALS_ARRAY_SZ =      (BINOMIAL_TRIALS_MAX+1)*THREADS_MAX;\nusing Histogram = std::array< size_t, BINOMIAL_TRIALS_MAX >;     // todo : gets quite large...\nusing Histogram_Parallel = std::array< size_t, TRIALS_ARRAY_SZ >;     // todo : gets quite large...\n\nvoid boost_log_init() {  // BOOST_LOG_TRIVIAL(trace) << \"A trace severity message\";\n        boost::log::core::get()->set_filter( boost::log::trivial::severity >= boost::log::trivial::info);\n}\n\nauto threads_on_hardware( size_t const operations_qty_total, size_t const operations_qty_min,\n                          size_t const threads_min, size_t const threads_max ) {\n    assert( threads_min <= threads_max);\n    if (operations_qty_min >= operations_qty_total) {\n        return std::tuple< size_t,size_t,size_t > {threads_min, operations_qty_total, operations_qty_total };\n    }\n    size_t threads_hardware_qty = std::thread::hardware_concurrency();\n    size_t threads_calc_max = (operations_qty_total + operations_qty_min-1 ) / operations_qty_min;  // truncation is desired\n    size_t threads_qty { std::min( { 0 != threads_hardware_qty\n                                        ? threads_hardware_qty\n                                        : threads_min\n                                        , threads_calc_max\n                                        , threads_max } ) };\n    size_t chunk_operations_qty = operations_qty_total / threads_qty;  // truncation is desired.\n    size_t chunk_operations_qty_mod = operations_qty_total % threads_qty;  // number with the extra samples.\n    return std::tuple< size_t,size_t,size_t > {threads_qty, chunk_operations_qty, chunk_operations_qty_mod};\n}\n\ndouble binomial_distribution_probability_mass_function( size_t const n_trials, size_t const k_successes, double const probability_of_success) {\n    double bc =           boost::math::binomial_coefficient<double>( 5, 2);\n    double p_k =          std::pow(probability_of_success, k_successes);\n    errno = 0;\n    double p_complement = std::pow(1 - probability_of_success, n_trials - k_successes);\n    if ( 0 != errno ) { std::perror(\"binomial:ERROR: pow() failed.\"); }  // todo: what type do I need to use PGM_NAME\n    return bc * p_k * p_complement;         // todo:  what happens if this cal overflows?  How do we check for that?\n}\n\ndouble print_binomial_dist_PMF(size_t const n_samples_drawn, size_t const k_successes, double const mu_probability_in_bin)\n{\n    try {\n    auto r1 = binomial_distribution_probability_mass_function(n_samples_drawn, k_successes,  mu_probability_in_bin);\n    cout << \"binomial_probability_mass_function(n_trials,k_successes,p): \" << n_samples_drawn << \", \" << k_successes << \", \" << mu_probability_in_bin << endl;\n    cout << r1 << endl;\n    return r1;\n    } catch (std::exception & e) { cerr<<PGM_NAME+\":binomial_rel_freq_histogram:error exception: \"<<e.what()<<endl; throw;\n    } catch (...) { cerr<<PGM_NAME+\":binomial_rel_freq_histogram:error unknown exception: \"<<endl; throw; };\n}\n\nvoid binomial_rel_freq_histogram_map(size_t const trials, double const p_success, size_t const num_samplings ) {\n    try {\n    std::random_device rd;\n    std::mt19937 gen(rd());\n    std::binomial_distribution<size_t> dist(trials, p_success);\n    std::map<size_t, size_t> histogram;\n    cout << \"Probability Mass/Density Function Graph - Binomial Distribution with trials, likelyhood: \" << trials << \", \" << p_success << std::endl;\n    for (size_t n = 0; n < num_samplings; ++n) {\n        ++histogram[dist(gen)];\n    }\n    for (auto p : histogram) {\n        cout << std::setw(4) << p.first << ' '\n                  << std::setw(10) << p.second/static_cast<double>(num_samplings) << ' '\n                  << '\\n';\n    }\n    } catch (std::exception & e) { cerr<<PGM_NAME+\":binomial_rel_freq_histogram:error exception: \"<<e.what()<<endl; throw;\n    } catch (...) { cerr<<PGM_NAME+\":binomial_rel_freq_histogram:error unknown exception: \"<<endl; throw; };\n}\n\nvoid binomial_rel_freq_histogram_vector(size_t const trials, double const p_success, size_t const num_samplings ) {\n    try {\n    std::random_device rd;\n    std::mt19937 gen( rd() );\n    std::binomial_distribution<size_t> dist( trials, p_success );\n    std::vector<size_t> histogram( trials+1, 0);  // create it with full size, init with 0\n    cout << \"Probability Mass/Density Function Graph - Binomial Distribution with trials, likelyhood: \" << trials << \", \" << p_success << std::endl;\n    for (size_t n = 0; n < num_samplings; ++n) {\n        ++histogram[ static_cast<size_t>( dist(gen) )];\n    }\n    size_t i = 0;\n    for (auto p : histogram) {\n        cout << std::setw(4) << i++ << ' '\n                  << std::setw(10) << p/grostig::narrow_cast_runtime<double>(num_samplings) << ' '\n                  << '\\n';\n    }\n    //    std::copy(histogram.begin(), histogram.end(), std::ostream_iterator<int>( cout, \" \\n\" ) );\n    } catch (std::exception & e) { cerr<<PGM_NAME+\":binomial_rel_freq_histogram:error exception: \"<<e.what()<<endl; throw;\n    } catch (...) { cerr<<PGM_NAME+\":binomial_rel_freq_histogram:error unknown exception: \"<<endl; throw; };\n}\n\nclass Sample_the_distribution_fo {\nprivate: \n    Histogram_Parallel & histogram_pll;                     // pll = parallel // this is located at begining of the class for cache performance\npublic:                                                     // todo: data layout for cache performance works for functions too?\n    void operator()()=delete;\n    void operator()(size_t const offset_, bool const is_do_one_more = false) {\n        try {\n        offset =                    offset_;\n//        std::random_device          rd;\n//        std::mt19937                gen ( rd() );\n//        std::binomial_distribution<unsigned long>  dist { trials, p_success };  // assumed not to be thread-safe\n//        gen( rd() );\n\n        size_t                      current_samples { is_do_one_more ? chunk_sample_qty+1 : chunk_sample_qty };  // this loop takes care of one of the additional (mod remainder) operations that are required.\n        if (!p1_done) {current_samples = chunk_sample_qty_p1; p1_done = true; };\n        for (unsigned j=0; j < current_samples; ++j) {\n            ++histogram_pll[ static_cast<size_t>( dist(gen) ) + offset ];\n        }\n        } catch (std::exception & e) { cerr<<PGM_NAME+\":binomial_rel_freq_histogram:error exception: \"<<e.what()<<endl; throw;\n        } catch (...) { cerr<<PGM_NAME+\":binomial_rel_freq_histogram:error unknown exception: \"<<endl; throw; };\n    }\nprivate:\n    size_t offset {};\n    size_t chunk_sample_qty_p1 {};  // number with the extra samples\n    size_t chunk_sample_qty {};\n    size_t trials {};\n    double p_success {};\n    bool   p1_done { false };  // one set of samples has to do the number with the extra samples\n    //  @OFFICER_TUBA: if only the following line is uncommented: compile error on no matching function? inititializer list?\n    //                 unless it is marked static!\n    static std::random_device           rd;     // todo: NOT USED yet!\n    std::binomial_distribution<size_t>  dist( rd() );   // todo: NOT USED yet!\n    std::mt19937                        gen;    // todo: NOT USED yet!\npublic:\n    Sample_the_distribution_fo()=delete;\n                        //        : histogram_pll(histogram_), chunk_sample_qty_p1(chunk_sample_qty_p1_), chunk_sample_qty(chunk_sample_qty_), trials(trials_), p_success(p_success_) {}\n    explicit Sample_the_distribution_fo(Histogram_Parallel & histogram_,\n                               size_t const chunk_sample_qty_p1_, size_t const chunk_sample_qty_, size_t const trials_, double const p_success_)\n        : histogram_pll(histogram_)\n    {\n                                            // histogram = histogram_;      // todo: NOTE: compiler wants this initialization to be done on the \"member intializer list\", probably because it is a \"ref\", why?\n        chunk_sample_qty_p1 = chunk_sample_qty_p1_;\n        chunk_sample_qty = chunk_sample_qty_;\n        trials = trials_;\n        p_success = p_success_;\n        //        std::mt19937                gen ( (this->rd)() );                           // todo: NOT USED yet!\n        //        std::binomial_distribution<unsigned long>  dist ( trials, p_success );      // todo: NOT USED yet!\n        //                  cout << \"Probability Mass/Density Function Graph - Binomial Distribution with trials, likelyhood: \" << trials << \", \" << p_success << std::endl;\n    }\n};\n\nHistogram sample_the_distribution_a( size_t const num_samplings, size_t const trials, double const p_success) {\n    try {\n    Histogram histogram;                                    // todo: data layout?\n    std::random_device          rd;\n    std::mt19937                gen ( rd() );\n    std::binomial_distribution<unsigned long>  dist { trials , p_success };\n    for (unsigned j=0; j < num_samplings; ++j) {\n        ++histogram[ static_cast<size_t>( dist(gen) ) ];\n    }\n    return histogram;\n    } catch (std::exception & e) { cerr<<PGM_NAME+\":binomial_rel_freq_histogram:error exception: \"<<e.what()<<endl; throw;\n    } catch (...) { cerr<<PGM_NAME+\":binomial_rel_freq_histogram:error unknown exception: \"<<endl; throw; };\n};\n\n/* void binomial_rel_freq_histogram_array_async(size_t trials, double const p_success, size_t const num_samplings ) {\n    assert( 1 <= trials && trials <= MAX_BINOMIAL_TRIALS );\n    assert( !(0.0 > p_success || p_success > 1.0) );  // between 0 and 1 ie. [0,1]\n    try {\n    cout << \"Probability Mass/Density Function Graph - Binomial Distribution with trials, likelyhood: \" << trials << \", \" << p_success << std::endl;\n    //    std::random_device                          rd;                           // todo: NOT USED yet! would need to thread-safe the distribution.\n    //    std::mt19937                                gen( rd() );                  // todo: NOT USED yet!\n    //    std::binomial_distribution<size_t>          dist( trials, p_success );    // todo: NOT USED yet!\n    Histogram histogram;\n    size_t                              num_trial_values      { trials+1 };  // include the case for zero successes within the set of trials.\n    std::vector<std::future<Histogram>> futures;\n    for (size_t chunk = 0; chunk < MAX_ASYNC_FUTURES; ++chunk)\n    {\n        std::future<Histogram> future_histogram = std::async( sample_the_distribution_a, num_samplings, trials, p_success);\n        futures.push_back( future_histogram );\n    }\n    std::for_each(futures.begin(), futures.end(), // for (auto this_t : threads) {  // todo: why not?\n                  std::mem_fn( &std::thread::join ));\n    for (auto ff:futures ) {  // don't add the first chuck (ie. = 0) to itself!\n        Histogram histogram_partial = futures.pop_back().get();\n        for (size_t my_trial = 0; my_trial < num_trial_values; my_trial++) {\n            histogram[my_trial] += histogram[my_trial];\n        }\n    }\n    for (size_t i = 0; i < num_trial_values; ++i ) {\n        cout << std::setw(4) << i << ' ' << std::setw(10) << histogram[i]/static_cast<double>(num_samplings) << ' '<< '\\n';\n    }\n} catch (std::exception & e) { cerr<<PGM_NAME+\":binomial_rel_freq_histogram:error exception: \"<<e.what()<<endl;\n} catch (...) { cerr<<PGM_NAME+\":binomial_rel_freq_histogram:error unknown exception: \"<<endl; throw; };\n }\n} */\n\nvoid binomial_rel_freq_histogram_array_thread(size_t trials, double const p_success, size_t const samplings_qty ) {\n    assert( 1 <= trials && trials <= BINOMIAL_TRIALS_MAX );\n    assert( !(0.0 > p_success || p_success > 1.0) );  // between 0 and 1 ie. [0,1]\n    try {  // sorry no indent for whole function.\n\n    cout << \"Probability Mass/Density Function Graph - Binomial Distribution with trials, likelyhood: \" << trials << \", \" << p_success << std::endl;\n    //    std::random_device                          rd;                           // todo: NOT USED yet! would need to thread-safe the distribution.\n    //    std::mt19937                                gen( rd() );                  // todo: NOT USED yet!\n    //    std::binomial_distribution<size_t>          dist( trials, p_success );    // todo: NOT USED yet!\n    Histogram_Parallel              histogram;                  // this is at the top of the function for performance.\n    // size_t const                    chunk_sample_quantity { num_samplings / MAX_THREADS };  // todo: truncation error, off by one error\n    size_t const                    num_trial_values      { trials+1 };  // include the case for zero successes within the set of trials.\n    size_t const                    chunk_stride          { num_trial_values };\n    size_t const                    samplings_qty_min     { 10'000 };\n    size_t                          chunk_offset          { 0 };\n    auto [threads_qty, chunk_sample_quantity, chunk_sample_qty_mod]\n            = threads_on_hardware( samplings_qty, samplings_qty_min, THREADS_MIN, THREADS_MAX);\n\n    std::vector<std::jthread>        threads;\n    Sample_the_distribution_fo sample_chunk_fo2 {histogram, chunk_sample_quantity, chunk_sample_qty_mod, trials, p_success};  // histogram is a reference, so we need to join within this containing function.\n    // must verify that we have more than one thread\n    for (size_t chunk = 0; chunk < threads_qty-1; ++chunk)        //  *** Parallel Section ***\n    {\n        try {\n            bool is_do_one_more {false};\n            if ( 0 != chunk_sample_qty_mod && chunk_sample_qty_mod-- > 0) is_do_one_more = true;  // iff we have a mod qty, then do_one and decrement.\n            std::jthread t = std::jthread( sample_chunk_fo2, chunk_offset, is_do_one_more );\n            threads.push_back( std::move(t) );\n        } catch (...) { cerr << PGM_NAME+\":fatal error: thread creation failed\\n\"<<endl; throw; }; // don't need thread guard due to vector. todo: even with thowing vector will be destructed and so also threads?\n        chunk_offset = chunk_offset + chunk_stride;\n    }\n    assert( 0 == chunk_sample_qty_mod );\n    sample_chunk_fo2( chunk_offset /* is_do_one_more = false (default)*/);  // do put the last thread on the main thread.\n    std::for_each(threads.begin(), threads.end(),               // *** BARRIER *** //for (auto this_t : threads) {  // todo: why not?\n                  std::mem_fn( &std::jthread::join ));\n    chunk_offset = chunk_stride;\n    for (size_t thread = 0; thread < threads_qty; ++thread) {   // *** Combine Results *** // don't add the first chuck (ie. = 0) to itself!\n        size_t trial_offset {0};\n        for (size_t my_trial = 0; my_trial < num_trial_values; my_trial++) {\n            trial_offset = chunk_offset + my_trial;\n            histogram[my_trial] += histogram[trial_offset];\n        }\n        chunk_offset = chunk_offset + chunk_stride;\n    }\n    for (size_t i = 0; i < num_trial_values; ++i ) {\n        cout << std::setw(4) << i << ' ' << std::setw(10) << histogram[i]/grostig::narrow_cast_runtime<double>(samplings_qty) << ' '<< '\\n';\n    }\n    } catch (std::exception & e) { cerr<<PGM_NAME+\":binomial_rel_freq_histogram:error exception: \"<<e.what()<<endl; throw;\n    } catch (...) { cerr<<PGM_NAME+\":binomial_rel_freq_histogram:error unknown exception: \"<<endl; throw; };\n}\n\nvoid poisson_distribution_values(double const mean, long int const num_values = 100 ) { // creates a vector loaded with values from the distribution during its initialization.\n    try {\n    std::random_device rd;\n    std::mt19937 gen( rd() ); // generator\n\n    std::poisson_distribution<int> dist( mean /*4.1*/);       // http://eigen.tuxfamily.org/bz/show_bug.cgi?id=720\n    auto poisson = [&dist, &gen] (size_t) { return dist( gen ); };\n    Eigen::RowVectorXi values = Eigen::RowVectorXi::NullaryExpr(num_values, poisson );\n    std::cout << \"Eigen::RowVextorXi:Poisson( mean ): (\" << mean << \"), \"  << values << \"\\n\";\n    } catch (std::exception & e) { cerr<<PGM_NAME+\":binomial_rel_freq_histogram:error exception: \"<<e.what()<<endl; throw;\n    } catch (...) { cerr<<PGM_NAME+\":binomial_rel_freq_histogram:error unknown exception: \"<<endl; throw; };\n}\n\nvoid binomial_distribution_values(size_t const trials, double const p_success, long int const num_values = 100 ) { // creates a vector loaded with values from the distribution during its initialization.\n    try {\n    std::random_device rd;\n    std::mt19937 gen( rd() ); // generator\n\n    std::binomial_distribution<size_t> dist( trials, p_success );       // http://eigen.tuxfamily.org/bz/show_bug.cgi?id=720\n    auto binomial = [&dist, &gen] (size_t) { return dist( gen ); };\n    Eigen::RowVectorXi values = Eigen::RowVectorXi::NullaryExpr(num_values, binomial );\n    std::cout << \"Eigen::RowVextorXi:Binomial( trials, p_success ): (\" << trials <<\", \"<< p_success <<\"), \"  << values << \"\\n\";\n    } catch (std::exception & e) { cerr<<PGM_NAME+\":binomial_rel_freq_histogram:error exception: \"<<e.what()<<endl; throw;\n    } catch (...) { cerr<<PGM_NAME+\":binomial_rel_freq_histogram:error unknown exception: \"<<endl; throw; };\n}\n\nint main()\n{\n    try {\n        size_t trials = 10;\n        constexpr size_t  num_samplings     = 100'000'000;            // c++17\n        //    binomial_rel_freq_histogram_map(    trials, 0.5, num_samplings );\n        //    binomial_rel_freq_histogram_vector( trials, 0.7, num_samplings );\n        binomial_rel_freq_histogram_array_thread(  trials, 1.0, num_samplings );\n\n        poisson_distribution_values( 4.1, 100 );\n        binomial_distribution_values( trials, 0.5, 100 );\n\n        cout << \"nCk(5,5): \"<<boost::math::binomial_coefficient<double>(5,5)<<endl\n             << \"nCk(5,2): \"<< boost::math::binomial_coefficient<double>(5,2)<<endl\n             << \"nCk(10'000,2): \"<< boost::math::binomial_coefficient<double>(10000,2)<<endl;\n\n\n        double mu_probability_in_bin        = 0.9;\n        size_t n_samples_drawn              = 10;\n        double nu_probability_of_sample     = 0.1;\n        size_t k_successes = grostig::narrow_cast_runtime<size_t>( lround( nu_probability_of_sample * n_samples_drawn ));\n        auto r1 = print_binomial_dist_PMF( n_samples_drawn, k_successes, mu_probability_in_bin );\n\n        mu_probability_in_bin               = 0.9;\n        n_samples_drawn                     = 10;\n        nu_probability_of_sample            = 0;\n        k_successes = grostig::narrow_cast_runtime<size_t>( lround( nu_probability_of_sample * n_samples_drawn ));\n        auto r2 = print_binomial_dist_PMF( n_samples_drawn, k_successes, mu_probability_in_bin );\n        cout << r1+r2 << endl;\n\n        mu_probability_in_bin               = 0.9;\n        n_samples_drawn                     = 10;\n        nu_probability_of_sample            = 0.4;\n        k_successes = grostig::narrow_cast_runtime<size_t>( lround( nu_probability_of_sample * n_samples_drawn ));\n        r1 = print_binomial_dist_PMF( n_samples_drawn, k_successes, mu_probability_in_bin );\n\n\n        mu_probability_in_bin               = 0.6;\n        n_samples_drawn                     = 10;\n        nu_probability_of_sample            = 0;\n        k_successes = grostig::narrow_cast_runtime<size_t>( lround( nu_probability_of_sample * n_samples_drawn ));\n        r1 = print_binomial_dist_PMF( n_samples_drawn, k_successes, mu_probability_in_bin );\n\n        std::cout << \"###\" << std::endl;\n        return 0;\n    } catch (std::exception & e) {\n        cerr << PGM_NAME+\": exception error: \"<<e.what()<<endl;\n        return 1;\n    } catch (...) {\n        cerr << PGM_NAME+\": unknown exception error.\\n\";\n        return 2;\n    }\n}\n\n\n\n", "meta": {"hexsha": "68ddb96f16aa5f234a138560cee9c07210202503", "size": 21747, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "main.cpp", "max_stars_repo_name": "authoff-swordpointstudios/binomial", "max_stars_repo_head_hexsha": "0ec8d460b03aeb7edc572c6adc81ff3ca205f9f1", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-12-02T01:58:32.000Z", "max_stars_repo_stars_event_max_datetime": "2019-12-02T01:58:32.000Z", "max_issues_repo_path": "main.cpp", "max_issues_repo_name": "authoff-swordpointstudios/binomial", "max_issues_repo_head_hexsha": "0ec8d460b03aeb7edc572c6adc81ff3ca205f9f1", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "main.cpp", "max_forks_repo_name": "authoff-swordpointstudios/binomial", "max_forks_repo_head_hexsha": "0ec8d460b03aeb7edc572c6adc81ff3ca205f9f1", "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": 55.0556962025, "max_line_length": 211, "alphanum_fraction": 0.6278567159, "num_tokens": 5469, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5851011542032312, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.3311780982436612}}
{"text": "/******************************************************************************\n * Author:   Laurent Kneip                                                    *\n * Contact:  kneip.laurent@gmail.com                                          *\n * License:  Copyright (c) 2013 Laurent Kneip, ANU. All rights reserved.      *\n *                                                                            *\n * Redistribution and use in source and binary forms, with or without         *\n * modification, are permitted provided that the following conditions         *\n * are met:                                                                   *\n * * Redistributions of source code must retain the above copyright           *\n *   notice, this list of conditions and the following disclaimer.            *\n * * Redistributions in binary form must reproduce the above copyright        *\n *   notice, this list of conditions and the following disclaimer in the      *\n *   documentation and/or other materials provided with the distribution.     *\n * * Neither the name of ANU nor the names of its contributors may be         *\n *   used to endorse or promote products derived from this software without   *\n *   specific prior written permission.                                       *\n *                                                                            *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"*\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE  *\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE *\n * ARE DISCLAIMED. IN NO EVENT SHALL ANU OR THE CONTRIBUTORS BE LIABLE        *\n * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL *\n * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR *\n * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER *\n * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT         *\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY  *\n * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF     *\n * SUCH DAMAGE.                                                               *\n ******************************************************************************/\n\n/**\n * \\file types.hpp\n * \\brief A collection of variables used in geometric vision for the\n *        computation of calibrated absolute and relative pose.\n */\n\n#ifndef OPENGV_TYPES_HPP_\n#define OPENGV_TYPES_HPP_\n\n#include <stdlib.h>\n#include <vector>\n#include <Eigen/Eigen>\n\n/**\n * \\brief The namespace of this library.\n */\nnamespace opengv\n{\n\n/** A 3-vector of unit length used to describe landmark observations/bearings\n *  in camera frames (always expressed in camera frames)\n */\ntypedef Eigen::Vector3d\n    bearingVector_t;\n\n/** An array of bearing-vectors */\ntypedef std::vector<bearingVector_t, Eigen::aligned_allocator<bearingVector_t> >\n    bearingVectors_t;\n\n/** A 3-vector describing a translation/camera position */\ntypedef Eigen::Vector3d\n    translation_t;\n\n/** An array of translations */\ntypedef std::vector<translation_t, Eigen::aligned_allocator<translation_t> >\n    translations_t;\n\n/** A rotation matrix */\ntypedef Eigen::Matrix3d\n    rotation_t;\n\n/** An array of rotation matrices as returned by fivept_kneip [7] */\ntypedef std::vector<rotation_t, Eigen::aligned_allocator<rotation_t> >\n    rotations_t;\n\n/** A 3x4 transformation matrix containing rotation \\f$ \\mathbf{R} \\f$ and\n *  translation \\f$ \\mathbf{t} \\f$ as follows:\n *  \\f$ \\left( \\begin{array}{cc} \\mathbf{R} & \\mathbf{t} \\end{array} \\right) \\f$\n */\ntypedef Eigen::Matrix<double,3,4>\n    transformation_t;\n\n/** An array of transformations */\ntypedef std::vector<transformation_t, Eigen::aligned_allocator<transformation_t> >\n    transformations_t;\n\n/** A 3-vector containing the cayley parameters of a rotation matrix */\ntypedef Eigen::Vector3d\n    cayley_t;\n\n/** A 4-vector containing the quaternion parameters of rotation matrix */\ntypedef Eigen::Vector4d\n    quaternion_t;\n\n/** Essential matrix \\f$ \\mathbf{E} \\f$ between two viewpoints:\n *\n *  \\f$ \\mathbf{E} = \\f$ skew(\\f$\\mathbf{t}\\f$) \\f$ \\mathbf{R} \\f$,\n *\n *  where \\f$ \\mathbf{t} \\f$ describes the position of viewpoint 2 seen from\n *  viewpoint 1, and \\f$\\mathbf{R}\\f$ describes the rotation from viewpoint 2\n *  to viewpoint 1.\n */\ntypedef Eigen::Matrix3d\n    essential_t;\n\n/** An array of essential matrices */\ntypedef std::vector<essential_t, Eigen::aligned_allocator<essential_t> >\n    essentials_t;\n\n/** An essential matrix with complex entires (as returned from\n *  fivept_stewenius [5])\n */\ntypedef Eigen::Matrix3cd\n    complexEssential_t;\n\n/** An array of complex-type essential matrices */\ntypedef std::vector< complexEssential_t, Eigen::aligned_allocator< complexEssential_t> >\n    complexEssentials_t;\n\n/** A 3-vector describing a point in 3D-space */\ntypedef Eigen::Vector3d\n    point_t;\n\n/** An array of 3D-points */\ntypedef std::vector<point_t, Eigen::aligned_allocator<point_t> >\n    points_t;\n\n/** A 3-vector containing the Eigenvalues of matrix \\f$ \\mathbf{M} \\f$ in the\n *  eigensolver-algorithm (described in [11])\n */\ntypedef Eigen::Vector3d\n    eigenvalues_t;\n\n/** A 3x3 matrix containing the eigenvectors of matrix \\f$ \\mathbf{M} \\f$ in the\n *  eigensolver-algorithm (described in [11])\n */\ntypedef Eigen::Matrix3d\n    eigenvectors_t;\n\n/** EigensolverOutput holds the output-parameters of the eigensolver-algorithm\n *  (described in [11])\n */\ntypedef struct EigensolverOutput\n{\n  EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n\n  /** Position of viewpoint 2 seen from viewpoint 1 (unscaled) */\n  translation_t   translation;\n  /** Rotation from viewpoint 2 back to viewpoint 1 */\n  rotation_t      rotation;\n  /** The eigenvalues of matrix \\f$ \\mathbf{M} \\f$ */\n  eigenvalues_t   eigenvalues;\n  /** The eigenvectors of matrix matrix \\f$ \\mathbf{M} \\f$ */\n  eigenvectors_t  eigenvectors;\n} eigensolverOutput_t;\n\n/** GeOutput holds the output-parameters of ge\n */\ntypedef struct GeOutput\n{\n  EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n  \n  /** Homogeneous position of viewpoint 2 seen from viewpoint 1 */\n  Eigen::Vector4d   translation;\n  /** Rotation from viewpoint 2 back to viewpoint 1 */\n  rotation_t        rotation;\n  /** The eigenvalues of matrix \\f$ \\mathbf{G} \\f$ */\n  Eigen::Vector4d   eigenvalues;\n  /** The eigenvectors of matrix matrix \\f$ \\mathbf{G} \\f$ */\n  Eigen::Matrix4d   eigenvectors;\n} geOutput_t;\n\n}\n\n#endif /* OPENGV_TYPES_HPP_ */\n", "meta": {"hexsha": "0486900f59f8ece39c53889210517846db304693", "size": 6515, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/opengv/types.hpp", "max_stars_repo_name": "PXLVision/opengv", "max_stars_repo_head_hexsha": "e48f77da4db7b8cee36ec677ed4ff5c5354571bb", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/opengv/types.hpp", "max_issues_repo_name": "PXLVision/opengv", "max_issues_repo_head_hexsha": "e48f77da4db7b8cee36ec677ed4ff5c5354571bb", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/opengv/types.hpp", "max_forks_repo_name": "PXLVision/opengv", "max_forks_repo_head_hexsha": "e48f77da4db7b8cee36ec677ed4ff5c5354571bb", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.0170454545, "max_line_length": 88, "alphanum_fraction": 0.6503453569, "num_tokens": 1503, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6187804337438501, "lm_q2_score": 0.5350984286266115, "lm_q1q2_score": 0.3311084377612273}}
{"text": "\n/******************************************************************************\n\n  Helper types related to the tangential component of the complex propagation.\n\n  Copyright (c) 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 TANGENTIAL_PROPAGATION_HPP_96CE789E_EA28_11E2_A507_AB62D8EF6274\n#define TANGENTIAL_PROPAGATION_HPP_96CE789E_EA28_11E2_A507_AB62D8EF6274\n\n#include <vector>\n#include <boost/shared_ptr.hpp>\n#include <boost/assert.hpp>\n\n#include \"bo/core/vector.hpp\"\n#include \"bo/math/pca.hpp\"\n\nnamespace bo {\nnamespace surfaces {\nnamespace detail {\n\n// Base class for any tangential propagation.\ntemplate <typename RealType>\nclass BaseTangentialPropagation\n{\npublic:\n    typedef BaseTangentialPropagation<RealType> SelfType;\n    typedef boost::shared_ptr<SelfType> Ptr;\n    typedef Vector<RealType, 3> Point3D;\n\n    BaseTangentialPropagation(RealType weight): weight_(weight)\n    { }\n\n    virtual Point3D get(const Point3D& current, const Point3D& inertial) const = 0;\n\nprotected:\n    RealType weight_;\n};\n\n// Standard tangential propagation. Uses the provided k-d tree to fetch neighbours of\n// the given point and then takes the greatest vector from the PCA launched on\n// neighbours.\ntemplate <typename RealType, typename Tree>\nclass TangentialPropagation: public BaseTangentialPropagation<RealType>\n{\npublic:\n    typedef TangentialPropagation<RealType, Tree> SelfType;\n    typedef boost::shared_ptr<SelfType> Ptr;\n    typedef Vector<RealType, 3> Point3D;\n    typedef std::vector<Point3D> Points3D;\n    typedef boost::shared_ptr<Tree> TreePtr;\n\n    TangentialPropagation(TreePtr tree_ptr, RealType radius, RealType weight):\n        BaseTangentialPropagation<RealType>(weight), tree_ptr_(tree_ptr), radius_(radius)\n    { }\n\n    virtual Point3D get(const Point3D& current, const Point3D& inertial) const\n    {\n        // Initialize collection for neigbours. Reserve gives slightly better performance,\n        // but uses more memory.\n        Points3D neighbours;\n        neighbours.reserve(tree_ptr_->size());\n\n        // Search for nearby points.\n        tree_ptr_->find_within_range(current, radius_, std::back_inserter(neighbours));\n\n        // Employ PCA to extract the tangential propagation vector from the set of\n        // nearby points.\n        typedef math::PCA<RealType, 3> PCAEngine;\n        PCAEngine pca;\n        typename PCAEngine::Result result = pca(neighbours);\n        Point3D tangential = result.template get<1>()[2];\n\n        // Ensure that tangential and inertial components are codirectional.\n        if (tangential * inertial < 0)\n            tangential = - tangential;\n\n        // TODO: remove this block by refactoring bo::Vector class.\n        // Normalize vector.\n        Point3D tangential_normalized(tangential.normalized(), 3);\n\n        return this->weight_ * tangential_normalized;\n    }\n\nprotected:\n    TreePtr tree_ptr_;\n    RealType radius_;\n};\n\n// Tangential propagation that uses neighbouring planes. Calculates and return the\n// weighted sum of standard tangential propagations for the main plane and provided\n// neighbours (which are projected onto the main plane). Note that main plane is assumed\n// to have weight 1.\ntemplate <typename RealType, typename Tree>\nclass NeighbourTangentialPropagation: public BaseTangentialPropagation<RealType>\n{\npublic:\n    typedef TangentialPropagation<RealType, Tree> Tangential;\n    typedef NeighbourTangentialPropagation<RealType, Tree> SelfType;\n    typedef boost::shared_ptr<SelfType> Ptr;\n    typedef Vector<RealType, 3> Point3D;\n\n    typedef boost::shared_ptr<Tree> TreePtr;\n    typedef std::vector<TreePtr> TreePtrs;\n    typedef std::vector<RealType> Weights;\n    typedef std::vector<Tangential> TangentialPropagations;\n\n    NeighbourTangentialPropagation(TreePtr tree_ptr, RealType radius, RealType weight,\n            const TreePtrs& neighbour_trees, const Weights& neighbour_weights):\n        BaseTangentialPropagation<RealType>(weight)\n    {\n        // Make sure neighbour data is consistent.\n        BOOST_ASSERT((neighbour_weights.size() == neighbour_trees.size()) &&\n                     \"Number of provided neighbour planes doesn't correspond to the \"\n                     \"number of weights.\");\n\n        // Cache container sizes and reserve memory.\n        std::size_t neighbour_size = neighbour_weights.size();\n        total_size_ = neighbour_size + 1;\n        tangentials_.reserve(total_size_);\n\n        // Add standard tangential propagation for the main plane.\n        tangentials_.push_back(Tangential(tree_ptr, radius, RealType(1)));\n\n        // Add standard tangential propagations for neighbouring planes.\n        for (std::size_t idx = 0; idx < neighbour_size; ++idx)\n            tangentials_.push_back(Tangential(neighbour_trees[idx], radius,\n                                              neighbour_weights[idx]));\n    }\n\n    virtual Point3D get(const Point3D& current, const Point3D& inertial) const\n    {\n        // Compute weighted tangential propagations for the main and neighbouring planes\n        // and sum them up.\n        Point3D total_tangential;\n        for (std::size_t idx = 0; idx < total_size_; ++idx)\n            total_tangential += tangentials_[idx].get(current, inertial);\n\n        // TODO: remove this block by refactoring bo::Vector class.\n        // Normalize vector.\n        Point3D total_tangential_normalized(total_tangential.normalized(), 3);\n\n        return this->weight_ * total_tangential_normalized;\n    }\n\nprotected:\n    TangentialPropagations tangentials_;\n    std::size_t total_size_;\n};\n\n} // namespace detail\n} // namespace surfaces\n} // namespace bo\n\n#endif // TANGENTIAL_PROPAGATION_HPP_96CE789E_EA28_11E2_A507_AB62D8EF6274\n\n", "meta": {"hexsha": "781c1869b6bcbf4c990610022e12e1324c6be76d", "size": 7051, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Bo/surfaces/detail/tangential_propagation.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/detail/tangential_propagation.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/detail/tangential_propagation.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.7417582418, "max_line_length": 90, "alphanum_fraction": 0.711955751, "num_tokens": 1553, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6187804337438501, "lm_q2_score": 0.5350984286266115, "lm_q1q2_score": 0.3311084377612273}}
{"text": "/* Author: Ivan Christov, Wolfgang Bangerth, Texas A&M University, 2006 */\n\n/*    $Id: step-25.cc 27657 2012-11-21 13:19:08Z bangerth $ */\n/*    Copyright (C) 2006-2009, 2011-2012 by the deal.II authors */\n/*                                                                */\n/*    This file is subject to QPL and may not be  distributed     */\n/*    without copyright and license information. Please refer     */\n/*    to the file deal.II/doc/license.html for the text and       */\n/*    further information on this license.                        */\n\n\n// @sect3{Include files and global variables}\n\n// For an explanation of the include files, the reader should refer to the\n// example programs step-1 through step-4. They are in the standard order,\n// which is <code>base</code> -- <code>lac</code> -- <code>grid</code> --\n// <code>dofs</code> -- <code>fe</code> -- <code>numerics</code> (since each\n// of these categories roughly builds upon previous ones), then a few C++\n// headers for file input/output and string streams.\n#include <deal.II/base/quadrature_lib.h>\n#include <deal.II/base/function.h>\n#include <deal.II/base/logstream.h>\n#include <deal.II/base/utilities.h>\n#include <deal.II/lac/vector.h>\n#include <deal.II/lac/full_matrix.h>\n#include <deal.II/lac/sparse_matrix.h>\n#include <deal.II/lac/solver_cg.h>\n#include <deal.II/lac/precondition.h>\n#include <deal.II/lac/constraint_matrix.h>\n#include <deal.II/grid/tria.h>\n#include <deal.II/grid/grid_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_q.h>\n#include <deal.II/fe/fe_values.h>\n#include <deal.II/numerics/vector_tools.h>\n#include <deal.II/numerics/matrix_tools.h>\n#include <deal.II/numerics/data_out.h>\n\n#include <fstream>\n#include <iostream>\n\n\n// The last step is as in all previous programs:\nnamespace Step25\n{\n  using namespace dealii;\n\n\n  // @sect3{The <code>SineGordonProblem</code> class template}\n\n  // The entire algorithm for solving the problem is encapsulated in this\n  // class. As in previous example programs, the class is declared with a\n  // template parameter, which is the spatial dimension, so that we can solve\n  // the sine-Gordon equation in one, two or three spatial dimensions. For\n  // more on the dimension-independent class-encapsulation of the problem, the\n  // reader should consult step-3 and step-4.\n  //\n  // Compared to step-23 and step-24, there isn't anything newsworthy in the\n  // general structure of the program (though there is of course in the inner\n  // workings of the various functions!). The most notable difference is the\n  // presence of the two new functions <code>compute_nl_term</code> and\n  // <code>compute_nl_matrix</code> that compute the nonlinear contributions\n  // to the system matrix and right-hand side of the first equation, as\n  // discussed in the Introduction. In addition, we have to have a vector\n  // <code>solution_update</code> that contains the nonlinear update to the\n  // solution vector in each Newton step.\n  //\n  // As also mentioned in the introduction, we do not store the velocity\n  // variable in this program, but the mass matrix times the velocity. This is\n  // done in the <code>M_x_velocity</code> variable (the \"x\" is intended to\n  // stand for \"times\").\n  //\n  // Finally, the <code>output_timestep_skip</code> variable stores the number\n  // of time steps to be taken each time before graphical output is to be\n  // generated. This is of importance when using fine meshes (and consequently\n  // small time steps) where we would run lots of time steps and create lots\n  // of output files of solutions that look almost the same in subsequent\n  // files. This only clogs up our visualization procedures and we should\n  // avoid creating more output than we are really interested in. Therefore,\n  // if this variable is set to a value $n$ bigger than one, output is\n  // generated only every $n$th time step.\n  template <int dim>\n  class SineGordonProblem\n  {\n  public:\n    SineGordonProblem ();\n    void run ();\n\n  private:\n    void make_grid_and_dofs ();\n    void assemble_system ();\n    void compute_nl_term (const Vector<double> &old_data,\n                          const Vector<double> &new_data,\n                          Vector<double>       &nl_term) const;\n    void compute_nl_matrix (const Vector<double> &old_data,\n                            const Vector<double> &new_data,\n                            SparseMatrix<double> &nl_matrix) const;\n    unsigned int solve ();\n    void output_results (const unsigned int timestep_number) const;\n\n    Triangulation<dim>   triangulation;\n    FE_Q<dim>            fe;\n    DoFHandler<dim>      dof_handler;\n\n    SparsityPattern      sparsity_pattern;\n    SparseMatrix<double> system_matrix;\n    SparseMatrix<double> mass_matrix;\n    SparseMatrix<double> laplace_matrix;\n\n    const unsigned int n_global_refinements;\n\n    double time;\n    const double final_time, time_step;\n    const double theta;\n\n    Vector<double>       solution, solution_update, old_solution;\n    Vector<double>       M_x_velocity;\n    Vector<double>       system_rhs;\n\n    const unsigned int output_timestep_skip;\n  };\n\n\n  // @sect3{Initial conditions}\n\n  // In the following two classes, we first implement the exact solution for\n  // 1D, 2D, and 3D mentioned in the introduction to this program. This\n  // space-time solution may be of independent interest if one wanted to test\n  // the accuracy of the program by comparing the numerical against the\n  // analytic solution (note however that the program uses a finite domain,\n  // whereas these are analytic solutions for an unbounded domain). This may,\n  // for example, be done using the VectorTools::integrate_difference\n  // function. Note, again (as was already discussed in step-23), how we\n  // describe space-time functions as spatial functions that depend on a time\n  // variable that can be set and queried using the FunctionTime::set_time()\n  // and FunctionTime::get_time() member functions of the FunctionTime base\n  // class of the Function class.\n  template <int dim>\n  class ExactSolution : public Function<dim>\n  {\n  public:\n    ExactSolution (const unsigned int n_components = 1,\n                   const double time = 0.) : Function<dim>(n_components, time) {}\n    virtual double value (const Point<dim> &p,\n                          const unsigned int component = 0) const;\n  };\n\n  template <int dim>\n  double ExactSolution<dim>::value (const Point<dim> &p,\n                                    const unsigned int /*component*/) const\n  {\n    double t = this->get_time ();\n\n    switch (dim)\n      {\n      case 1:\n      {\n        const double m = 0.5;\n        const double c1 = 0.;\n        const double c2 = 0.;\n        return -4.*std::atan (m /\n                              std::sqrt(1.-m*m) *\n                              std::sin(std::sqrt(1.-m*m)*t+c2) /\n                              std::cosh(m*p[0]+c1));\n      }\n\n      case 2:\n      {\n        const double theta  = numbers::PI/4.;\n        const double lambda  = 1.;\n        const double a0  = 1.;\n        const double s   = 1.;\n        const double arg = p[0] * std::cos(theta) +\n                           std::sin(theta) *\n                           (p[1] * std::cosh(lambda) +\n                            t * std::sinh(lambda));\n        return 4.*std::atan(a0*std::exp(s*arg));\n      }\n\n      case 3:\n      {\n        double theta  = numbers::PI/4;\n        double phi = numbers::PI/4;\n        double tau = 1.;\n        double c0  = 1.;\n        double s   = 1.;\n        double arg = p[0]*std::cos(theta) +\n                     p[1]*std::sin(theta) * std::cos(phi) +\n                     std::sin(theta) * std::sin(phi) *\n                     (p[2]*std::cosh(tau)+t*std::sinh(tau));\n        return 4.*std::atan(c0*std::exp(s*arg));\n      }\n\n      default:\n        Assert (false, ExcNotImplemented());\n        return -1e8;\n      }\n  }\n\n  // In the second part of this section, we provide the initial conditions. We\n  // are lazy (and cautious) and don't want to implement the same functions as\n  // above a second time. Rather, if we are queried for initial conditions, we\n  // create an object <code>ExactSolution</code>, set it to the correct time,\n  // and let it compute whatever values the exact solution has at that time:\n  template <int dim>\n  class InitialValues : public Function<dim>\n  {\n  public:\n    InitialValues (const unsigned int n_components = 1,\n                   const double time = 0.)\n      :\n      Function<dim>(n_components, time)\n    {}\n\n    virtual double value (const Point<dim> &p,\n                          const unsigned int component = 0) const;\n  };\n\n  template <int dim>\n  double InitialValues<dim>::value (const Point<dim> &p,\n                                    const unsigned int component) const\n  {\n    return ExactSolution<dim>(1, this->get_time()).value (p, component);\n  }\n\n\n\n  // @sect3{Implementation of the <code>SineGordonProblem</code> class}\n\n  // Let's move on to the implementation of the main class, as it implements\n  // the algorithm outlined in the introduction.\n\n  // @sect4{SineGordonProblem::SineGordonProblem}\n\n  // This is the constructor of the <code>SineGordonProblem</code> class. It\n  // specifies the desired polynomial degree of the finite elements,\n  // associates a <code>DoFHandler</code> to the <code>triangulation</code>\n  // object (just as in the example programs step-3 and step-4), initializes\n  // the current or initial time, the final time, the time step size, and the\n  // value of $\\theta$ for the time stepping scheme. Since the solutions we\n  // compute here are time-periodic, the actual value of the start-time\n  // doesn't matter, and we choose it so that we start at an interesting time.\n  //\n  // Note that if we were to chose the explicit Euler time stepping scheme\n  // ($\\theta = 0$), then we must pick a time step $k \\le h$, otherwise the\n  // scheme is not stable and oscillations might arise in the solution. The\n  // Crank-Nicolson scheme ($\\theta = \\frac{1}{2}$) and the implicit Euler\n  // scheme ($\\theta=1$) do not suffer from this deficiency, since they are\n  // unconditionally stable. However, even then the time step should be chosen\n  // to be on the order of $h$ in order to obtain a good solution. Since we\n  // know that our mesh results from the uniform subdivision of a rectangle,\n  // we can compute that time step easily; if we had a different domain, the\n  // technique in step-24 using GridTools::minimal_cell_diameter would work as\n  // well.\n  template <int dim>\n  SineGordonProblem<dim>::SineGordonProblem ()\n    :\n    fe (1),\n    dof_handler (triangulation),\n    n_global_refinements (6),\n    time (-5.4414),\n    final_time (2.7207),\n    time_step (10*1./std::pow(2.,1.*n_global_refinements)),\n    theta (0.5),\n    output_timestep_skip (1)\n  {}\n\n  // @sect4{SineGordonProblem::make_grid_and_dofs}\n\n  // This function creates a rectangular grid in <code>dim</code> dimensions\n  // and refines it several times. Also, all matrix and vector members of the\n  // <code>SineGordonProblem</code> class are initialized to their appropriate\n  // sizes once the degrees of freedom have been assembled. Like step-24, we\n  // use the <code>MatrixCreator</code> class to generate a mass matrix $M$\n  // and a Laplace matrix $A$ and store them in the appropriate variables for\n  // the remainder of the program's life.\n  template <int dim>\n  void SineGordonProblem<dim>::make_grid_and_dofs ()\n  {\n    GridGenerator::hyper_cube (triangulation, -10, 10);\n    triangulation.refine_global (n_global_refinements);\n\n    std::cout << \"   Number of active cells: \"\n              << triangulation.n_active_cells()\n              << std::endl\n              << \"   Total number of cells: \"\n              << triangulation.n_cells()\n              << std::endl;\n\n    dof_handler.distribute_dofs (fe);\n\n    std::cout << \"   Number of degrees of freedom: \"\n              << dof_handler.n_dofs()\n              << std::endl;\n\n    sparsity_pattern.reinit (dof_handler.n_dofs(),\n                             dof_handler.n_dofs(),\n                             dof_handler.max_couplings_between_dofs());\n    DoFTools::make_sparsity_pattern (dof_handler, sparsity_pattern);\n    sparsity_pattern.compress ();\n\n    system_matrix.reinit  (sparsity_pattern);\n    mass_matrix.reinit    (sparsity_pattern);\n    laplace_matrix.reinit (sparsity_pattern);\n\n    MatrixCreator::create_mass_matrix (dof_handler,\n                                       QGauss<dim>(3),\n                                       mass_matrix);\n    MatrixCreator::create_laplace_matrix (dof_handler,\n                                          QGauss<dim>(3),\n                                          laplace_matrix);\n\n    solution.reinit       (dof_handler.n_dofs());\n    solution_update.reinit     (dof_handler.n_dofs());\n    old_solution.reinit   (dof_handler.n_dofs());\n    M_x_velocity.reinit    (dof_handler.n_dofs());\n    system_rhs.reinit     (dof_handler.n_dofs());\n  }\n\n  // @sect4{SineGordonProblem::assemble_system}\n\n  // This functions assembles the system matrix and right-hand side vector for\n  // each iteration of Newton's method. The reader should refer to the\n  // Introduction for the explicit formulas for the system matrix and\n  // right-hand side.\n  //\n  // Note that during each time step, we have to add up the various\n  // contributions to the matrix and right hand sides. In contrast to step-23\n  // and step-24, this requires assembling a few more terms, since they depend\n  // on the solution of the previous time step or previous nonlinear step. We\n  // use the functions <code>compute_nl_matrix</code> and\n  // <code>compute_nl_term</code> to do this, while the present function\n  // provides the top-level logic.\n  template <int dim>\n  void SineGordonProblem<dim>::assemble_system ()\n  {\n    // First we assemble the Jacobian matrix $F'_h(U^{n,l})$, where $U^{n,l}$\n    // is stored in the vector <code>solution</code> for convenience.\n    system_matrix = 0;\n    system_matrix.copy_from (mass_matrix);\n    system_matrix.add (std::pow(time_step*theta,2), laplace_matrix);\n\n    SparseMatrix<double> tmp_matrix (sparsity_pattern);\n    compute_nl_matrix (old_solution, solution, tmp_matrix);\n    system_matrix.add (-std::pow(time_step*theta,2), tmp_matrix);\n\n    // Then, we compute the right-hand side vector $-F_h(U^{n,l})$.\n    system_rhs = 0;\n\n    tmp_matrix = 0;\n    tmp_matrix.copy_from (mass_matrix);\n    tmp_matrix.add (std::pow(time_step*theta,2), laplace_matrix);\n\n    Vector<double> tmp_vector (solution.size());\n    tmp_matrix.vmult (tmp_vector, solution);\n    system_rhs += tmp_vector;\n\n    tmp_matrix = 0;\n    tmp_matrix.copy_from (mass_matrix);\n    tmp_matrix.add (-std::pow(time_step,2)*theta*(1-theta), laplace_matrix);\n\n    tmp_vector = 0;\n    tmp_matrix.vmult (tmp_vector, old_solution);\n    system_rhs -= tmp_vector;\n\n    system_rhs.add (-time_step, M_x_velocity);\n\n    tmp_vector = 0;\n    compute_nl_term (old_solution, solution, tmp_vector);\n    system_rhs.add (std::pow(time_step,2)*theta, tmp_vector);\n\n    system_rhs *= -1;\n  }\n\n  // @sect4{SineGordonProblem::compute_nl_term}\n\n  // This function computes the vector $S(\\cdot,\\cdot)$, which appears in the\n  // nonlinear term in the both equations of the split formulation. This\n  // function not only simplifies the repeated computation of this term, but\n  // it is also a fundamental part of the nonlinear iterative solver that we\n  // use when the time stepping is implicit (i.e. $\\theta\\ne 0$). Moreover, we\n  // must allow the function to receive as input an \"old\" and a \"new\"\n  // solution. These may not be the actual solutions of the problem stored in\n  // <code>old_solution</code> and <code>solution</code>, but are simply the\n  // two functions we linearize about. For the purposes of this function, let\n  // us call the first two arguments $w_{\\mathrm{old}}$ and $w_{\\mathrm{new}}$\n  // in the documentation of this class below, respectively.\n  //\n  // As a side-note, it is perhaps worth investigating what order quadrature\n  // formula is best suited for this type of integration. Since $\\sin(\\cdot)$\n  // is not a polynomial, there are probably no quadrature formulas that can\n  // integrate these terms exactly. It is usually sufficient to just make sure\n  // that the right hand side is integrated up to the same order of accuracy\n  // as the discretization scheme is, but it may be possible to improve on the\n  // constant in the asympotitic statement of convergence by choosing a more\n  // accurate quadrature formula.\n  template <int dim>\n  void SineGordonProblem<dim>::compute_nl_term (const Vector<double> &old_data,\n                                                const Vector<double> &new_data,\n                                                Vector<double>       &nl_term) const\n  {\n    const QGauss<dim> quadrature_formula (3);\n    FEValues<dim>     fe_values (fe, quadrature_formula,\n                                 update_values |\n                                 update_JxW_values |\n                                 update_quadrature_points);\n\n    const unsigned int dofs_per_cell = fe.dofs_per_cell;\n    const unsigned int n_q_points    = quadrature_formula.size();\n\n    Vector<double> local_nl_term (dofs_per_cell);\n    std::vector<unsigned int> local_dof_indices (dofs_per_cell);\n    std::vector<double> old_data_values (n_q_points);\n    std::vector<double> new_data_values (n_q_points);\n\n    typename DoFHandler<dim>::active_cell_iterator\n    cell = dof_handler.begin_active(),\n    endc = dof_handler.end();\n\n    for (; cell!=endc; ++cell)\n      {\n        // Once we re-initialize our <code>FEValues</code> instantiation to\n        // the current cell, we make use of the\n        // <code>get_function_values</code> routine to get the values of the\n        // \"old\" data (presumably at $t=t_{n-1}$) and the \"new\" data\n        // (presumably at $t=t_n$) at the nodes of the chosen quadrature\n        // formula.\n        fe_values.reinit (cell);\n        fe_values.get_function_values (old_data, old_data_values);\n        fe_values.get_function_values (new_data, new_data_values);\n\n        // Now, we can evaluate $\\int_K \\sin\\left[\\theta w_{\\mathrm{new}} +\n        // (1-\\theta) w_{\\mathrm{old}}\\right] \\,\\varphi_j\\,\\mathrm{d}x$ using\n        // the desired quadrature formula.\n        for (unsigned int q_point=0; q_point<n_q_points; ++q_point)\n          for (unsigned int i=0; i<dofs_per_cell; ++i)\n            local_nl_term(i) += (std::sin(theta * new_data_values[q_point] +\n                                          (1-theta) * old_data_values[q_point]) *\n                                 fe_values.shape_value (i, q_point) *\n                                 fe_values.JxW (q_point));\n\n        // We conclude by adding up the contributions of the integrals over\n        // the cells to the global integral.\n        cell->get_dof_indices (local_dof_indices);\n\n        for (unsigned int i=0; i<dofs_per_cell; ++i)\n          nl_term(local_dof_indices[i]) += local_nl_term(i);\n\n        local_nl_term = 0;\n      }\n  }\n\n  // @sect4{SineGordonProblem::compute_nl_matrix}\n\n  // This is the second function dealing with the nonlinear scheme. It\n  // computes the matrix $N(\\cdot,\\cdot)$, whicih appears in the nonlinear\n  // term in the Jacobian of $F(\\cdot)$. Just as <code>compute_nl_term</code>,\n  // we must allow this function to receive as input an \"old\" and a \"new\"\n  // solution, which we again call $w_{\\mathrm{old}}$ and $w_{\\mathrm{new}}$\n  // below, respectively.\n  template <int dim>\n  void SineGordonProblem<dim>::compute_nl_matrix (const Vector<double> &old_data,\n                                                  const Vector<double> &new_data,\n                                                  SparseMatrix<double> &nl_matrix) const\n  {\n    QGauss<dim>   quadrature_formula (3);\n    FEValues<dim> fe_values (fe, quadrature_formula,\n                             update_values | update_JxW_values | update_quadrature_points);\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> local_nl_matrix (dofs_per_cell, dofs_per_cell);\n    std::vector<unsigned int> local_dof_indices (dofs_per_cell);\n    std::vector<double> old_data_values (n_q_points);\n    std::vector<double> new_data_values (n_q_points);\n\n    typename DoFHandler<dim>::active_cell_iterator\n    cell = dof_handler.begin_active(),\n    endc = dof_handler.end();\n\n    for (; cell!=endc; ++cell)\n      {\n        // Again, first we re-initialize our <code>FEValues</code>\n        // instantiation to the current cell.\n        fe_values.reinit (cell);\n        fe_values.get_function_values (old_data, old_data_values);\n        fe_values.get_function_values (new_data, new_data_values);\n\n        // Then, we evaluate $\\int_K \\cos\\left[\\theta w_{\\mathrm{new}} +\n        // (1-\\theta) w_{\\mathrm{old}}\\right]\\, \\varphi_i\\,\n        // \\varphi_j\\,\\mathrm{d}x$ using the desired quadrature formula.\n        for (unsigned int q_point=0; q_point<n_q_points; ++q_point)\n          for (unsigned int i=0; i<dofs_per_cell; ++i)\n            for (unsigned int j=0; j<dofs_per_cell; ++j)\n              local_nl_matrix(i,j) += (std::cos(theta * new_data_values[q_point] +\n                                                (1-theta) * old_data_values[q_point]) *\n                                       fe_values.shape_value (i, q_point) *\n                                       fe_values.shape_value (j, q_point) *\n                                       fe_values.JxW (q_point));\n\n        // Finally, we add up the contributions of the integrals over the\n        // cells to the global integral.\n        cell->get_dof_indices (local_dof_indices);\n\n        for (unsigned int i=0; i<dofs_per_cell; ++i)\n          for (unsigned int j=0; j<dofs_per_cell; ++j)\n            nl_matrix.add(local_dof_indices[i], local_dof_indices[j],\n                          local_nl_matrix(i,j));\n\n        local_nl_matrix = 0;\n      }\n  }\n\n\n\n  // @sect4{SineGordonProblem::solve}\n\n  // As discussed in the Introduction, this function uses the CG iterative\n  // solver on the linear system of equations resulting from the finite\n  // element spatial discretization of each iteration of Newton's method for\n  // the (nonlinear) first equation of the split formulation. The solution to\n  // the system is, in fact, $\\delta U^{n,l}$ so it is stored in\n  // <code>solution_update</code> and used to update <code>solution</code> in\n  // the <code>run</code> function.\n  //\n  // Note that we re-set the solution update to zero before solving for\n  // it. This is not necessary: iterative solvers can start from any point and\n  // converge to the correct solution. If one has a good estimate about the\n  // solution of a linear system, it may be worthwhile to start from that\n  // vector, but as a general observation it is a fact that the starting point\n  // doesn't matter very much: it has to be a very, very good guess to reduce\n  // the number of iterations by more than a few. It turns out that for this\n  // problem, using the previous nonlinear update as a starting point actually\n  // hurts convergence and increases the number of iterations needed, so we\n  // simply set it to zero.\n  //\n  // The function returns the number of iterations it took to converge to a\n  // solution. This number will later be used to generate output on the screen\n  // showing how many iterations were needed in each nonlinear iteration.\n  template <int dim>\n  unsigned int\n  SineGordonProblem<dim>::solve ()\n  {\n    SolverControl solver_control (1000, 1e-12*system_rhs.l2_norm());\n    SolverCG<> cg (solver_control);\n\n    PreconditionSSOR<> preconditioner;\n    preconditioner.initialize(system_matrix, 1.2);\n\n    solution_update = 0;\n    cg.solve (system_matrix, solution_update,\n              system_rhs,\n              preconditioner);\n\n    return solver_control.last_step();\n  }\n\n  // @sect4{SineGordonProblem::output_results}\n\n  // This function outputs the results to a file. It is pretty much identical\n  // to the respective functions in step-23 and step-24:\n  template <int dim>\n  void\n  SineGordonProblem<dim>::output_results (const unsigned int timestep_number) const\n  {\n    DataOut<dim> data_out;\n\n    data_out.attach_dof_handler (dof_handler);\n    data_out.add_data_vector (solution, \"u\");\n    data_out.build_patches ();\n\n    const std::string filename =  \"solution-\" +\n                                  Utilities::int_to_string (timestep_number, 3) +\n                                  \".vtk\";\n\n    std::ofstream output (filename.c_str());\n    data_out.write_vtk (output);\n  }\n\n  // @sect4{SineGordonProblem::run}\n\n  // This function has the top-level control over everything: it runs the\n  // (outer) time-stepping loop, the (inner) nonlinear-solver loop, and\n  // outputs the solution after each time step.\n  template <int dim>\n  void SineGordonProblem<dim>::run ()\n  {\n    make_grid_and_dofs ();\n\n    // To aknowledge the initial condition, we must use the function $u_0(x)$\n    // to compute $U^0$. To this end, below we will create an object of type\n    // <code>InitialValues</code>; note that when we create this object (which\n    // is derived from the <code>Function</code> class), we set its internal\n    // time variable to $t_0$, to indicate that the initial condition is a\n    // function of space and time evaluated at $t=t_0$.\n    //\n    // Then we produce $U^0$ by projecting $u_0(x)$ onto the grid using\n    // <code>VectorTools::project</code>. We have to use the same construct\n    // using hanging node constraints as in step-21: the VectorTools::project\n    // function requires a hanging node constraints object, but to be used we\n    // first need to close it:\n    {\n      ConstraintMatrix constraints;\n      constraints.close();\n      VectorTools::project (dof_handler,\n                            constraints,\n                            QGauss<dim>(3),\n                            InitialValues<dim> (1, time),\n                            solution);\n    }\n\n    // For completeness, we output the zeroth time step to a file just like\n    // any other other time step.\n    output_results (0);\n\n    // Now we perform the time stepping: at every time step we solve the\n    // matrix equation(s) corresponding to the finite element discretization\n    // of the problem, and then advance our solution according to the time\n    // stepping formulas we discussed in the Introduction.\n    unsigned int timestep_number = 1;\n    for (time+=time_step; time<=final_time; time+=time_step, ++timestep_number)\n      {\n        old_solution = solution;\n\n        std::cout << std::endl\n                  << \"Time step #\" << timestep_number << \"; \"\n                  << \"advancing to t = \" << time << \".\"\n                  << std::endl;\n\n        // At the beginning of each time step we must solve the nonlinear\n        // equation in the split formulation via Newton's method ---\n        // i.e. solve for $\\delta U^{n,l}$ then compute $U^{n,l+1}$ and so\n        // on. The stopping criterion for this nonlinear iteration is that\n        // $\\|F_h(U^{n,l})\\|_2 \\le 10^{-6} \\|F_h(U^{n,0})\\|_2$. Consequently,\n        // we need to record the norm of the residual in the first iteration.\n        //\n        // At the end of each iteration, we output to the console how many\n        // linear solver iterations it took us. When the loop below is done,\n        // we have (an approximation of) $U^n$.\n        double initial_rhs_norm = 0.;\n        bool first_iteration = true;\n        do\n          {\n            assemble_system ();\n\n            if (first_iteration == true)\n              initial_rhs_norm = system_rhs.l2_norm();\n\n            const unsigned int n_iterations\n              = solve ();\n\n            solution += solution_update;\n\n            if (first_iteration == true)\n              std::cout << \"    \" << n_iterations;\n            else\n              std::cout << '+' << n_iterations;\n            first_iteration = false;\n          }\n        while (system_rhs.l2_norm() > 1e-6 * initial_rhs_norm);\n\n        std::cout << \" CG iterations per nonlinear step.\"\n                  << std::endl;\n\n        // Upon obtaining the solution to the first equation of the problem at\n        // $t=t_n$, we must update the auxiliary velocity variable\n        // $V^n$. However, we do not compute and store $V^n$ since it is not a\n        // quantity we use directly in the problem. Hence, for simplicity, we\n        // update $MV^n$ directly:\n        Vector<double> tmp_vector (solution.size());\n        laplace_matrix.vmult (tmp_vector, solution);\n        M_x_velocity.add (-time_step*theta, tmp_vector);\n\n        tmp_vector = 0;\n        laplace_matrix.vmult (tmp_vector, old_solution);\n        M_x_velocity.add (-time_step*(1-theta), tmp_vector);\n\n        tmp_vector = 0;\n        compute_nl_term (old_solution, solution, tmp_vector);\n        M_x_velocity.add (-time_step, tmp_vector);\n\n        // Oftentimes, in particular for fine meshes, we must pick the time\n        // step to be quite small in order for the scheme to be\n        // stable. Therefore, there are a lot of time steps during which\n        // \"nothing interesting happens\" in the solution. To improve overall\n        // efficiency -- in particular, speed up the program and save disk\n        // space -- we only output the solution every\n        // <code>output_timestep_skip</code> time steps:\n        if (timestep_number % output_timestep_skip == 0)\n          output_results (timestep_number);\n      }\n  }\n}\n\n// @sect3{The <code>main</code> function}\n\n// This is the main function of the program. It creates an object of top-level\n// class and calls its principal function. Also, we suppress some of the\n// library output by setting <code>deallog.depth_console</code> to\n// zero. Furthermore, if exceptions are thrown during the execution of the run\n// method of the <code>SineGordonProblem</code> class, we catch and report\n// them here. For more information about exceptions the reader should consult\n// step-6.\nint main ()\n{\n  try\n    {\n      using namespace dealii;\n      using namespace Step25;\n\n      deallog.depth_console (0);\n\n      SineGordonProblem<1> sg_problem;\n      sg_problem.run ();\n    }\n  catch (std::exception &exc)\n    {\n      std::cerr << std::endl << std::endl\n                << \"----------------------------------------------------\"\n                << std::endl;\n      std::cerr << \"Exception on processing: \" << std::endl\n                << exc.what() << std::endl\n                << \"Aborting!\" << std::endl\n                << \"----------------------------------------------------\"\n                << std::endl;\n\n      return 1;\n    }\n  catch (...)\n    {\n      std::cerr << std::endl << std::endl\n                << \"----------------------------------------------------\"\n                << std::endl;\n      std::cerr << \"Unknown exception!\" << std::endl\n                << \"Aborting!\" << std::endl\n                << \"----------------------------------------------------\"\n                << std::endl;\n      return 1;\n    }\n\n  return 0;\n}\n", "meta": {"hexsha": "b10bcfdf1e11c8588c0570cbd95ec88bfe7869e3", "size": 31209, "ext": "cc", "lang": "C++", "max_stars_repo_path": "MHD/examples/step-25/step-25.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-25/step-25.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-25/step-25.cc", "max_forks_repo_name": "wathen/PhD", "max_forks_repo_head_hexsha": "35524f40028541a4d611d8c78574e4cf9ddc3278", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2019-10-28T16:12:13.000Z", "max_forks_repo_forks_event_max_datetime": "2020-01-13T13:59:44.000Z", "avg_line_length": 41.7232620321, "max_line_length": 91, "alphanum_fraction": 0.6361626454, "num_tokens": 7537, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.3311084377612273}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\r\n\r\n// Copyright (c) 2007-2012 Barend Gehrels, Amsterdam, the Netherlands.\r\n\r\n// This file was modified by Oracle on 2014-2017.\r\n// Modifications copyright (c) 2014-2017, Oracle and/or its affiliates.\r\n\r\n// Contributed and/or modified by Vissarion Fysikopoulos, on behalf of Oracle\r\n// Contributed and/or modified by Adam Wulkiewicz, on behalf of Oracle\r\n\r\n// Use, modification and distribution is subject to the Boost Software License,\r\n// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\r\n// http://www.boost.org/LICENSE_1_0.txt)\r\n\r\n#ifndef BOOST_GEOMETRY_STRATEGIES_SPHERICAL_SIDE_BY_CROSS_TRACK_HPP\r\n#define BOOST_GEOMETRY_STRATEGIES_SPHERICAL_SIDE_BY_CROSS_TRACK_HPP\r\n\r\n#include <boost/geometry/core/cs.hpp>\r\n#include <boost/geometry/core/access.hpp>\r\n#include <boost/geometry/core/radian_access.hpp>\r\n\r\n#include <boost/geometry/formulas/spherical.hpp>\r\n\r\n#include <boost/geometry/util/math.hpp>\r\n#include <boost/geometry/util/promote_floating_point.hpp>\r\n#include <boost/geometry/util/select_calculation_type.hpp>\r\n\r\n#include <boost/geometry/strategies/side.hpp>\r\n//#include <boost/geometry/strategies/concepts/side_concept.hpp>\r\n\r\n\r\nnamespace boost { namespace geometry\r\n{\r\n\r\n\r\nnamespace strategy { namespace side\r\n{\r\n\r\n/*!\r\n\\brief Check at which side of a Great Circle segment a point lies\r\n         left of segment (> 0), right of segment (< 0), on segment (0)\r\n\\ingroup strategies\r\n\\tparam CalculationType \\tparam_calculation\r\n */\r\ntemplate <typename CalculationType = void>\r\nclass side_by_cross_track\r\n{\r\n\r\npublic :\r\n    template <typename P1, typename P2, typename P>\r\n    static inline int apply(P1 const& p1, P2 const& p2, P const& p)\r\n    {\r\n        typedef typename promote_floating_point\r\n            <\r\n                typename select_calculation_type_alt\r\n                    <\r\n                        CalculationType,\r\n                        P1, P2, P\r\n                    >::type\r\n            >::type calc_t;\r\n\r\n        calc_t d1 = 0.001; // m_strategy.apply(sp1, p);\r\n\r\n        calc_t lon1 = geometry::get_as_radian<0>(p1);\r\n        calc_t lat1 = geometry::get_as_radian<1>(p1);\r\n        calc_t lon2 = geometry::get_as_radian<0>(p2);\r\n        calc_t lat2 = geometry::get_as_radian<1>(p2);\r\n        calc_t lon = geometry::get_as_radian<0>(p);\r\n        calc_t lat = geometry::get_as_radian<1>(p);\r\n\r\n        calc_t crs_AD = geometry::formula::spherical_azimuth<calc_t, false>\r\n                             (lon1, lat1, lon, lat).azimuth;\r\n\r\n        calc_t crs_AB = geometry::formula::spherical_azimuth<calc_t, false>\r\n                             (lon1, lat1, lon2, lat2).azimuth;\r\n\r\n        calc_t XTD = asin(sin(d1) * sin(crs_AD - crs_AB));\r\n\r\n        return math::equals(XTD, 0) ? 0 : XTD < 0 ? 1 : -1;\r\n    }\r\n};\r\n\r\n}} // namespace strategy::side\r\n\r\n\r\n}} // namespace boost::geometry\r\n\r\n\r\n#endif // BOOST_GEOMETRY_STRATEGIES_SPHERICAL_SIDE_BY_CROSS_TRACK_HPP\r\n", "meta": {"hexsha": "bad640f00de8ea057a03062374b6e8ea55652458", "size": 2953, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "deps/boost/include/boost/geometry/strategies/spherical/side_by_cross_track.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/strategies/spherical/side_by_cross_track.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/strategies/spherical/side_by_cross_track.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.8111111111, "max_line_length": 80, "alphanum_fraction": 0.6616999661, "num_tokens": 740, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.8438950947024555, "lm_q2_score": 0.3923368301671084, "lm_q1q2_score": 0.33109112644913313}}
{"text": "/*****************************************************************************\r\n *\r\n * This file is part of Mapnik (c++ mapping toolkit)\r\n *\r\n * Copyright (C) 2013 Artem Pavlenko\r\n *\r\n * This library is free software; you can redistribute it and/or\r\n * modify it under the terms of the GNU Lesser General Public\r\n * License as published by the Free Software Foundation; either\r\n * version 2.1 of the License, or (at your option) any later version.\r\n *\r\n * This library is distributed in the hope that it will be useful,\r\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\r\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\r\n * Lesser General Public License for more details.\r\n *\r\n * You should have received a copy of the GNU Lesser General Public\r\n * License along with this library; if not, write to the Free Software\r\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA\r\n *\r\n *****************************************************************************/\r\n\r\n#ifndef MAPNIK_WELL_KNOWN_SRS_HPP\r\n#define MAPNIK_WELL_KNOWN_SRS_HPP\r\n\r\n// mapnik\r\n#include <mapnik/global.hpp> // for M_PI on windows\r\n#include <mapnik/enumeration.hpp>\r\n\r\n// boost\r\n#include <boost/optional.hpp>\r\n\r\n// stl\r\n#include <cmath>\r\n\r\nnamespace mapnik {\r\n\r\nenum well_known_srs_enum {\r\n    WGS_84,\r\n    G_MERC,\r\n    well_known_srs_enum_MAX\r\n};\r\n\r\nDEFINE_ENUM( well_known_srs_e, well_known_srs_enum );\r\n\r\nstatic const double EARTH_RADIUS = 6378137.0;\r\nstatic const double EARTH_DIAMETER = EARTH_RADIUS * 2.0;\r\nstatic const double EARTH_CIRCUMFERENCE = EARTH_DIAMETER * M_PI;\r\nstatic const double MAXEXTENT = EARTH_CIRCUMFERENCE / 2.0;\r\nstatic const double M_PI_by2 = M_PI / 2;\r\nstatic const double D2R = M_PI / 180;\r\nstatic const double R2D = 180 / M_PI;\r\nstatic const double M_PIby360 = M_PI / 360;\r\nstatic const double MAXEXTENTby180 = MAXEXTENT / 180;\r\nstatic const double MAX_LATITUDE = R2D * (2 * std::atan(std::exp(180 * D2R)) - M_PI_by2);\r\nstatic const std::string MAPNIK_LONGLAT_PROJ = \"+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs\";\r\nstatic const std::string MAPNIK_GMERC_PROJ = \"+proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0 +x_0=0.0 +y_0=0.0 +k=1.0 +units=m +nadgrids=@null +wktext +no_defs +over\";\r\n\r\nboost::optional<well_known_srs_e> is_well_known_srs(std::string const& srs);\r\n\r\nboost::optional<bool> is_known_geographic(std::string const& srs);\r\n\r\nstatic inline bool lonlat2merc(double * x, double * y , int point_count)\r\n{\r\n    for(int i=0; i<point_count; i++) {\r\n        if (x[i] > 180) x[i] = 180;\r\n        else if (x[i] < -180) x[i] = -180;\r\n        if (y[i] > MAX_LATITUDE) y[i] = MAX_LATITUDE;\r\n        else if (y[i] < -MAX_LATITUDE) y[i] = -MAX_LATITUDE;\r\n        x[i] = x[i] * MAXEXTENTby180;\r\n        y[i] = std::log(std::tan((90 + y[i]) * M_PIby360)) * R2D;\r\n        y[i] = y[i] * MAXEXTENTby180;\r\n    }\r\n    return true;\r\n}\r\n\r\nstatic inline bool merc2lonlat(double * x, double * y , int point_count)\r\n{\r\n    for(int i=0; i<point_count; i++)\r\n    {\r\n        if (x[i] > MAXEXTENT) x[i] = MAXEXTENT;\r\n        else if (x[i] < -MAXEXTENT) x[i] = -MAXEXTENT;\r\n        if (y[i] > MAXEXTENT) y[i] = MAXEXTENT;\r\n        else if (y[i] < -MAXEXTENT) y[i] = -MAXEXTENT;\r\n        x[i] = (x[i] / MAXEXTENT) * 180;\r\n        y[i] = (y[i] / MAXEXTENT) * 180;\r\n        y[i] = R2D * (2 * std::atan(std::exp(y[i] * D2R)) - M_PI_by2);\r\n    }\r\n    return true;\r\n}\r\n\r\n}\r\n\r\n#endif // MAPNIK_WELL_KNOWN_SRS_HPP\r\n", "meta": {"hexsha": "6e2092960cfbbbe26f052102205ad5be4870a849", "size": 3455, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "external/include/mapnik/well_known_srs.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/well_known_srs.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/well_known_srs.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": 36.3684210526, "max_line_length": 177, "alphanum_fraction": 0.6266280753, "num_tokens": 1038, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6619228758499942, "lm_q2_score": 0.5, "lm_q1q2_score": 0.3309614379249971}}
{"text": "// External libraries\n#include <stdio.h>\n#include <boost/property_tree/ptree.hpp>\n\n// Local libraries\n#include <fmath/constants.h>\n#include <fmath/RungeKutta.h>\n#include <fparameters/Dimension.h>\n#include <fparameters/parameters.h>\n#include <fparameters/SpaceIterator.h>\n\n// Local headers\n#include \"comptonScattMatrix.h\"\n#include \"modelParameters.h\"\n#include \"globalVariables.h\"\n#include \"adafFunctions.h\"\n#include \"write.h\"\n#include \"messages.h\"\n\nextern \"C\" {\n\t#include <nrMath/random.h>\n}\n#define RANDOM_GENERATOR gsl_rng_r250 /* R250 random number generator from GNU Scientific Library. */\n\n#define new_max(x,y) ((x) >= (y)) ? (x) : (y)\n#define new_min(x,y) ((x) <= (y)) ? (x) : (y)\n#define new_abs(x,y) ((x) >= (y)) ?(x-y) : (y-x)\n\nvoid comptonScattMatrixWrite()\n{\n\tmatrixWrite(\"scattAA.dat\", scattAA, nR, nR);\n\tmatrixWrite(\"scattDA.dat\", scattDA, nRcd, nR);\n\tmatrixWrite(\"reachAD.dat\", reachAD, nR, nRcd);\n\tmatrixWrite(\"reachDA.dat\", reachDA, nRcd, nR);\n\tmatrixWrite(\"reachAA.dat\", reachAA, nR, nR);\n\tvectorWrite(\"escapeAi.dat\", escapeAi, nR);\n\tvectorWrite(\"escapeDi.dat\", escapeDi, nRcd);\n}\n\nvoid comptonScattMatrix(State& st)\n{\n\tshow_message(msgStart,Module_comptonScattMatrix);\n\n\tsize_t nPhot = GlobalConfig.get<size_t>(\"scatt.nRandomPhot\");\n\tsize_t nTheta = GlobalConfig.get<size_t>(\"scatt.nTheta\");\n    \n\tdouble captureRadius = 0.5*sqrt(27.0)*schwRadius;\n\n\tVector rCellsBoundaries(nR+1,0.0), rCellsBoundariesCD(nRcd+1,0.0);\n\trCellsBoundaries[0] = st.denf_e.ps[DIM_R][0]/sqrt(paso_r);\n\trCellsBoundariesCD[0] = rTr;\n    for(size_t iR=1;iR<=nR;iR++) rCellsBoundaries[iR]=rCellsBoundaries[iR-1]*paso_r;\n\tfor(size_t iRcd=1;iRcd<=nRcd;iRcd++) rCellsBoundariesCD[iRcd]=rCellsBoundariesCD[iRcd-1]*paso_rCD;\n\n\tdouble rBound = max(rCellsBoundaries[nR],rCellsBoundariesCD[nRcd]);\n\tmatrixInit(scattAA,nR,nR,0.0);\n\tmatrixInit(scattDA,nRcd,nR,0.0);\n\tmatrixInit(reachAD,nR,nRcd,0.0);\n\tmatrixInit(reachAA,nR,nR,0.0);\n\tmatrixInit(reachDA,nRcd,nR,0.0);\n    escapeAi.resize(nR,0.0);\n\tescapeDi.resize(nRcd,0.0);\n    \n    InitialiseRandom(RANDOM_GENERATOR);\n\t//ADAF SCATTERING MATRIX\n\t\n\tdouble pasoprim = min(pow(rCellsBoundaries[1]/rCellsBoundaries[0],1.0/10.0),\n\t\t\t\t\t\t1.0+height_fun(st.denf_i.ps[DIM_R][0])/st.denf_i.ps[DIM_R][0]);\n\t\n\t#pragma omp parallel for\n\tfor (int iR=0;iR<nR;iR++) {\n\t\tdouble r0 = st.denf_e.ps[DIM_R][iR];\n\t\tdouble thetaMin;\n\t\tif (height_method == 0)\n\t\t\tthetaMin = st.thetaH.get({0,iR,0});\n\t\telse\n\t\t\tthetaMin = atan(r0/height_fun(r0));\n\t\tdouble dyaux=(1.0-sin(thetaMin))/nTheta;\n        for(size_t kTh=1;kTh<=nTheta;kTh++) {\n            double yaux=sin(thetaMin)+kTh*dyaux;  // Theta distributed uniformly in sin(theta).\n            double theta0=asin(yaux);\n\t\t\tdouble y0,z0;\n\t\t\tif (height_method == 0) {\n\t\t\t\ty0=r0*sin(theta0);\n\t\t\t\tz0=r0*cos(theta0);\n\t\t\t} else {\n\t\t\t\ty0 = r0;\n\t\t\t\tz0 = r0/tan(theta0);\n\t\t\t}\n\t\t\tfor(size_t jPh=1;jPh<=nPhot;jPh++) {\n\t\t\t\tdouble random_number = gsl_rng_uniform(RandomNumberGenerator);\n\t\t\t\tdouble phiprim = 2.0*pi*random_number;\n\t\t\t\trandom_number = gsl_rng_uniform(RandomNumberGenerator);\n\t\t\t\tdouble thetaprim = acos(1.0-2.0*random_number);   // Photon directions\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t  // distributed\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t  // isotropically.\n\t\t\t\tdouble pescap = 1.0;\n\t\t\t\tdouble z1ant = z0;\n\t\t\t\tdouble drprim=r0*(pasoprim-1.0);       // Step.\n\t\t\t\tdouble rprim=drprim;\n\t\t\t\tvector<size_t> countAA(nR,0);\n\t\t\t\tdouble r1 = r0;\n\t\t\t\tdouble z1 = z0;\n\t\t\t\tdouble r1aux = r1;\n                do {\n\t\t\t\t\tdouble xprim=rprim*sin(thetaprim)*cos(phiprim);\n\t\t\t\t\tdouble yprim=rprim*sin(thetaprim)*sin(phiprim);\n\t\t\t\t\tdouble zprim=rprim*cos(thetaprim);\n\t\t\t\t\tdouble x1=xprim;\n\t\t\t\t\tdouble y1=y0+yprim;\n\t\t\t\t\tz1=z0+zprim;\n\t\t\t\t\tr1=sqrt(x1*x1+y1*y1+z1*z1);\n\t\t\t\t\tr1aux = (height_method == 0) ? r1 : sqrt(x1*x1+y1*y1);\n\t\t\t\t\tdouble theta1=atan(sqrt(x1*x1+y1*y1)/abs(z1));\n\t\t\t\t\tdouble ne = electronDensityTheta(r1,theta1);\n\t\t\t\t\tdouble exptau = exp(-ne*thomson*drprim);\n                    double psc = 1.0-exptau;    // Probability of scattering.\n\t\t\t\t\tif (r1aux > rTr && z1*z1ant < 0.0) {\n\t\t\t\t\t\tfor(size_t jRcd=0;jRcd<=nRcd;jRcd++) {\n\t\t\t\t\t\t\tif(r1aux > rCellsBoundariesCD[jRcd] && r1aux < rCellsBoundariesCD[jRcd+1]) {\n\t\t\t\t\t\t\t\treachAD[iR][jRcd] += pescap; \t\t// Add the probability of\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// absorption by the ring\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// jRcd of the thin disk.\n\t\t\t\t\t\t\t\tgoto LOOP;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n                    }\n\t\t\t\t\tz1ant = z1;\n\t\t\t\t\tfor(size_t jR=0;jR<nR;jR++) {\n\t\t\t\t\t\t\n\t\t\t\t\t\tif(r1aux > rCellsBoundaries[jR] && r1aux < rCellsBoundaries[jR+1]) {\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tscattAA[iR][jR] += psc*pescap;\n\t\t\t\t\t\t\tif (countAA[jR] == 0) {\n\t\t\t\t\t\t\t\treachAA[iR][jR] += pescap;\n\t\t\t\t\t\t\t\tcountAA[jR]++;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n                    }\n\t\t\t\t\tpescap *= exptau;\n                    drprim=r1*(pasoprim-1.0);\n                    rprim += drprim;\n                } while(r1aux < rBound && z1 < rBound && r1 > schwRadius);\n\t\t\t\tLOOP:;\n            }\n        }\n        for(size_t jR=0;jR<nR;jR++) {\n            scattAA[iR][jR] /= (nPhot*nTheta);     // Dividing by the number of photons launched.\n\t\t\treachAA[iR][jR] /= (nPhot*nTheta);\n        }\n\t\tfor (size_t jRcd=0;jRcd<nRcd;jRcd++) {\n\t\t\treachAD[iR][jRcd] /= (nPhot*nTheta);\n\t\t}\n\t}\n\t\n\t//////////////////////////////////////////////////////////////////////////////////////\n\t\n\t// ADAF ESCAPE PHOTONS\n\t#pragma omp parallel for\n\tfor (int iR=0;iR<nR;iR++) {\n\t\tdouble r0 = st.thetaH.ps[DIM_R][iR];\n\t\tdouble drprim=r0*(pasoprim-1.0);\n\t\tdouble thetaMin;\n\t\tif (height_method == 0)\n\t\t\tthetaMin = st.thetaH.get({0,iR,0});\n\t\telse\n\t\t\tthetaMin = atan(r0/height_fun(r0));\n\t\tdouble dyaux=(1.0-sin(thetaMin))/nTheta;\n        for(size_t kTh=1;kTh<=nTheta;kTh++) {\n            double yaux=sin(thetaMin)+kTh*dyaux;  // Theta distributed uniformly in sin(theta).\n            double theta0 = (yaux < 1.0 ? asin(yaux) : pi/2.0);\n\t\t\tdouble phi0 = 0.0;\n\t\t\tdouble dPhi = 2.0*pi/nPhot;\n\t\t\t\n\t\t\tdouble x0,y0,z0;\n\t\t\tif (height_method == 0) {\n\t\t\t\tx0 = r0*sin(theta0)*cos(phi0);\n\t\t\t\ty0 = r0*sin(theta0)*cos(phi0);\n\t\t\t\tz0 = r0*cos(theta0);\n\t\t\t} else {\n\t\t\t\tx0 = r0*sin(phi0);\n\t\t\t\ty0 = r0*cos(phi0);\n\t\t\t\tz0 = r0/tan(theta0);\n\t\t\t}\n\t\t\tfor(size_t jPh=1;jPh<=nPhot;jPh++) {\n\t\t\t\tdouble thetaprim = inclination*(pi/180.0);\n\t\t\t\tdouble rprim=drprim;\n\t\t\t\tdouble r1 = r0;\n\t\t\t\tdouble z1 = z0;\n\t\t\t\tdouble r1aux = r1;\n\t\t\t\tdouble pescap = 1.0;\n\t\t\t\tdo {\n\t\t\t\t\tdouble xprim=rprim*sin(thetaprim);\n\t\t\t\t\tdouble zprim=rprim*cos(thetaprim);\n\t\t\t\t\tdouble x1=x0+xprim;\n\t\t\t\t\tz1=z0+zprim;\n\t\t\t\t\tr1=sqrt(x1*x1+y0*y0+z1*z1);\n\t\t\t\t\tdouble theta1=atan(sqrt(x1*x1+y0*y0)/abs(z1));\n\t\t\t\t\tr1aux = (height_method == 0) ? r1 : sqrt(x1*x1+y0*y0);\n\t\t\t\t\tdouble ne = electronDensityTheta(r1,theta1);\n\t\t\t\t\tpescap *= exp(-ne*thomson*drprim);\n\t\t\t\t\tdrprim=r1*(pasoprim-1.0);\n\t\t\t\t\trprim += drprim;\n\t\t\t\t} while (r1aux < rCellsBoundaries[nR] && z1 < rCellsBoundaries[nR]);\n\t\t\t\tescapeAi[iR] += pescap;\n\t\t\t\tphi0 += dPhi;\n            }\n        }\n\t\tescapeAi[iR] /= (nPhot*nTheta);     // Dividing by the number of photons launched.\n\t}\n\n\t//////////////////////////////////////////////////////////////////////////////////////\n\n\t// COLD DISK SCATTERING MATRIX\n\t#pragma omp parallel for\n\tfor (int iRcd=0;iRcd<nRcd;iRcd++) {\n\t\tdouble r0cd = st.denf_e.ps[DIM_Rcd][iRcd];\n\t\tfor(size_t jPh=1;jPh<=nPhot;jPh++) {\n\t\t\tdouble drprim = r0cd*(pasoprim-1.0);             // Step for the photon path.\n\t\t\tdouble random_number = gsl_rng_uniform(RandomNumberGenerator);\n\t\t\tdouble phiprim = 2.0*pi*random_number;\n\t\t\trandom_number = gsl_rng_uniform(RandomNumberGenerator);\n\t\t\tdouble thetaprim = 0.5*acos(1.0-2.0*random_number);   // Photon directions\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t  // distributed\n\t\t\tdouble rprim=drprim; \t                           \t  // proportional to cos(theta)sin(theta).\n\t\t\tdouble pescap = 1.0;\n\t\t\tdouble r1 = r0cd;\n\t\t\tdouble r1aux = r1;\n\t\t\tdouble z1 = 0.0;\n\t\t\tvector<size_t> countDA(nR,0);\n\t\t\tdo {\n\t\t\t\tdouble xprim=rprim*sin(thetaprim)*cos(phiprim);\n\t\t\t\tdouble yprim=rprim*sin(thetaprim)*sin(phiprim);\n\t\t\t\tdouble zprim=rprim*cos(thetaprim);\n\t\t\t\tdouble x1=xprim;\n\t\t\t\tdouble y1=r0cd+yprim;\n\t\t\t\tz1=zprim;\n\t\t\t\tr1=sqrt(x1*x1+y1*y1+z1*z1);\n\t\t\t\tdouble theta1=atan(sqrt(x1*x1+y1*y1)/abs(z1));\n\t\t\t\tr1aux = (height_method == 0) ? r1 : sqrt(x1*x1+y1*y1);\n\t\t\t\tdouble exptau = 1.0;\n\t\t\t\tif (r1aux < rCellsBoundaries[nR]) {\n\t\t\t\t\tdouble ne = electronDensityTheta(r1aux,theta1);\n\t\t\t\t\texptau = exp(-ne*thomson*drprim);\n\t\t\t\t\tdouble psc = 1.0-exptau;    // Probability of scattering.\n\t\t\t\t\tfor(size_t jR=0;jR<=nR;jR++) {\n\t\t\t\t\t\tif(r1aux > rCellsBoundaries[jR] && r1aux < rCellsBoundaries[jR+1]) {\n\t\t\t\t\t\t\tscattDA[iRcd][jR] += psc*pescap;\n\t\t\t\t\t\t\tif (countDA[jR] == 0) {\n\t\t\t\t\t\t\t\treachDA[iRcd][jR] += pescap;\n\t\t\t\t\t\t\t\tcountDA[jR]++;\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\tdrprim=r1aux*(pasoprim-1.0);\n\t\t\t\trprim += drprim;\n\t\t\t\tpescap *= exptau;                // Probability that a photon reaches \n\t\t\t\t\t\t\t\t\t\t\t\t // the previous position.\n\t\t\t} while(r1aux < rBound && z1 < rBound && r1 > schwRadius);\n        }\n        for(size_t jR=0;jR<nR;jR++) {\n            scattDA[iRcd][jR] /= nPhot;     // Dividing by the number of photons launched.\n\t\t\treachDA[iRcd][jR] /= nPhot;\n        }\n\t}\n\n\t//COLD DISK ESCAPE PHOTONS\n\t#pragma omp parallel for\n\tfor (int iRcd=0;iRcd<nRcd;iRcd++) {\n\t\tdouble r0cd = st.denf_e.ps[DIM_Rcd][iRcd];\n\t\tdouble drprim=r0cd*(pasoprim-1.0);\n\t\tfor(size_t jPh=1;jPh<=nPhot;jPh++) {\n\t\t\tdouble random_number = gsl_rng_uniform(RandomNumberGenerator);\n\t\t\tdouble phiprim = 2.0*pi*random_number;\n\t\t\tdouble thetaprim = inclination*(pi/180.0);\n\t\t\tdouble rprim=drprim;\n\t\t\tdouble r1 = r0cd;\n\t\t\tdouble z1 = 0.0;\n\t\t\tdouble r1aux = r1;\n\t\t\tdouble pescap = 1.0;\n\t\t\tdo {\n\t\t\t\tdouble xprim=rprim*sin(thetaprim)*cos(phiprim);\n\t\t\t\tdouble yprim=rprim*sin(thetaprim)*sin(phiprim);\n\t\t\t\tdouble zprim=rprim*cos(thetaprim);\n\t\t\t\tdouble x1=xprim;\n\t\t\t\tdouble y1=r0cd+yprim;\n\t\t\t\tz1=zprim;\n\t\t\t\tr1=sqrt(x1*x1+y1*y1+z1*z1);\n\t\t\t\tdouble theta1=atan(sqrt(x1*x1+y1*y1)/abs(z1));\n\t\t\t\tr1aux = (height_method == 0) ? r1 : sqrt(x1*x1+y1*y1);\n\t\t\t\tdouble ne = electronDensityTheta(r1,theta1);\n\t\t\t\tpescap *= exp(-ne*thomson*drprim);\n\t\t\t\tdrprim=r1*(pasoprim-1.0);\n\t\t\t\trprim += drprim;\n\t\t\t} while(r1aux < rBound && z1 < rBound);     // Escape from the region.\n\t\t\tescapeDi[iRcd] += pescap;\n        }\n        escapeDi[iRcd] /= nPhot;\n\t}\n\n    FinaliseRandom();\n\tcomptonScattMatrixWrite();\n\n\tshow_message(msgEnd,Module_comptonScattMatrix);\n}\n\nvoid comptonScattMatrixRead(State& st)\n{\n\tmatrixInit(scattAA,nR,nR,0.0);\n\tmatrixInit(scattDA,nRcd,nR,0.0);\n\tmatrixInit(reachAD,nR,nRcd,0.0);\n\tmatrixInit(reachAA,nR,nR,0.0);\n\tmatrixInit(reachDA,nRcd,nR,0.0);\n    escapeAi.resize(nR,0.0);\n\tescapeDi.resize(nRcd,0.0);\n\t\n\tmatrixRead(\"scattAA.dat\",scattAA,nR,nR);\n\tmatrixRead(\"scattDA.dat\",scattDA,nRcd,nR);\n\tmatrixRead(\"reachAD.dat\",reachAD,nR,nRcd);\n\tmatrixRead(\"reachAA.dat\",reachAA,nR,nR);\n\tmatrixRead(\"reachDA.dat\",reachDA,nRcd,nR);\n\tvectorRead(\"escapeAi.dat\",escapeAi,nR);\n\tvectorRead(\"escapeDi.dat\",escapeDi,nRcd);\n}", "meta": {"hexsha": "5124cd2b37990dc343d18bb1182853c44dcd821d", "size": 10780, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/adaf/comptonScattMatrix.cpp", "max_stars_repo_name": "eduardomgutierrez/RIAF_radproc", "max_stars_repo_head_hexsha": "0e4166f04cce27fed2cbd2c7078023c10e0e8d12", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-08-30T06:56:03.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-30T06:56:03.000Z", "max_issues_repo_path": "src/adaf/comptonScattMatrix.cpp", "max_issues_repo_name": "eduardomgutierrez/RIAF_radproc", "max_issues_repo_head_hexsha": "0e4166f04cce27fed2cbd2c7078023c10e0e8d12", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/adaf/comptonScattMatrix.cpp", "max_forks_repo_name": "eduardomgutierrez/RIAF_radproc", "max_forks_repo_head_hexsha": "0e4166f04cce27fed2cbd2c7078023c10e0e8d12", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.1692307692, "max_line_length": 101, "alphanum_fraction": 0.6127087199, "num_tokens": 3715, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6370307944803831, "lm_q2_score": 0.5195213219520929, "lm_q1q2_score": 0.33095108047264066}}
{"text": "/* \n// Copyright 2018 University of Liege\n// \n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n// \n//     http://www.apache.org/licenses/LICENSE-2.0\n// \n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//\n// Authors:\n// - Adrien Crovato\n*/\n\n//// Field variables computation\n// Compute variables (velocity, speed of sound, density, mach number) in the field\n//\n// I/O:\n// - Minf: freestream Mach number\n// - vInf: freestream velocity vector\n// - bPan: (network of) body panels (structure)\n// - fPan: field panels (structure)\n// - sp: sub-panel (structure)\n// - b2fAIC: body to field AIC (structure)\n// - f2fAIC: field to field AIC (structure)\n// - spAIC: body to field AIC for subpanels (structure)\n\n#include <iostream>\n#include <Eigen/Dense>\n#include \"compute_fVars.h\"\n#include \"interp_ctv.h\"\n#include \"interp_sp.h\"\n\n#define GAMMA 1.4\n#define NV 4 // number of vertices\n\nusing namespace std;\nusing namespace Eigen;\n\nvoid compute_fVars(double Minf, Vector3d &vInf, Network &bPan, Field &fPan, Subpanel &sp,\n                       Body_AIC &b2fAIC, Field2field_AIC &f2fAIC, Subpanel_AIC &spAIC) {\n\n    //// Initialization\n    // Temporary variables\n    MatrixXd vSing; // corner interpolated singularities\n    vSing.resize(NV,2);\n    MatrixXd sInterp; // sub-panel interoplated singularities\n    sInterp.resize(sp.NS,2);\n\n    //// Potential\n    // Perturbation potential\n    fPan.phi = b2fAIC.B * bPan.tau + b2fAIC.A * bPan.mu + f2fAIC.C * fPan.sigma;\n\n    // Perturbation potential (with sub-paneling technique)\n    // TODO Subpaneling induces small assymmetry. Check why?\n    for (int jj = 0; jj < sp.sI.size(); jj++) {\n        int j = sp.sI[jj]; // panel global index\n        int n = j % bPan.nC_; // panel chordwise index\n        int m = j / bPan.nC_; // panel spanwise index\n        // Interpolation of singularities from centers to vertices\n        vSing = interp_ctv(j, n, m, bPan);\n        // Interpolation of singularities from vertices to sub-panel\n        sInterp = interp_sp(j, bPan, sp,\n                            vSing(0,0), vSing(1,0), vSing(2,0), vSing(3,0),\n                            vSing(0,1), vSing(1,1), vSing(2,1), vSing(3,1));\n\n        for (int ii = 0; ii < sp.fI[jj].size(); ii++) {\n            int i = sp.fI[jj][ii]; // cell index\n            // Velocity induces by each sub-panel\n            for (int k = 0; k < sp.NS; k++) {\n                fPan.phi(i) += spAIC.A[jj](ii,k) * sInterp(k,0) + spAIC.B[jj](ii,k) * sInterp(k,1);\n            }\n        }\n    }\n\n    //// Velocity\n    // Perturbation velocity\n    for (int i = 0; i < fPan.nE; i++) {\n        int f = fPan.eIdx(i);\n\n        // X-derivative\n        double fb=0, ff=0;\n        if (fPan.fbdMap(f,0) && fPan.fwdMap(f,0))\n            fb = (fPan.phi(f) - fPan.phi(f - 1)) / fPan.deltaX;\n        if (fPan.fbdMap(f,1) && fPan.fwdMap(f,1))\n            ff = (fPan.phi(f + 1) - fPan.phi(f)) / fPan.deltaX;\n        if (fPan.fbdMap(f,0) && fPan.fwdMap(f,0) && fPan.fbdMap(f,1) && fPan.fwdMap(f,1))\n            fPan.U(f,0) = 0.5*(fb+ff);\n        else\n            fPan.U(f,0) = fb+ff;\n\n        // Y-derivative\n        fb=0; ff=0;\n        if (fPan.fbdMap(f,2) && fPan.fwdMap(f,2))\n            fb = (fPan.phi(f) - fPan.phi(f - fPan.nX*fPan.nZ)) / fPan.deltaY;\n        if (fPan.fbdMap(f,3) && fPan.fwdMap(f,3))\n            ff = (fPan.phi(f + fPan.nX*fPan.nZ) - fPan.phi(f)) / fPan.deltaY;\n        if (fPan.fbdMap(f,2) && fPan.fwdMap(f,2) && fPan.fbdMap(f,3) && fPan.fwdMap(f,3))\n            fPan.U(f,1) = 0.5*(fb+ff);\n        else\n            fPan.U(f,1) = fb+ff;\n\n        // Z-derivative\n        fb=0; ff=0;\n        if (fPan.fbdMap(f,4) && fPan.fwdMap(f,4))\n            fb = (fPan.phi(f) - fPan.phi(f - fPan.nX)) / fPan.deltaZ;\n        if (fPan.fbdMap(f,5) && fPan.fwdMap(f,5))\n            ff = (fPan.phi(f + fPan.nX) - fPan.phi(f)) / fPan.deltaZ;\n        if (fPan.fbdMap(f,4) && fPan.fwdMap(f,4) && fPan.fbdMap(f,5) && fPan.fwdMap(f,5))\n            fPan.U(f,2) = 0.5*(fb+ff);\n        else\n            fPan.U(f,2) = fb+ff;\n    }\n    // Freestream component\n    for (int i = 0; i < fPan.nE; ++i) {\n        fPan.U.row(fPan.eIdx(i)) += vInf.transpose();\n    }\n\n    //// Thermodynamic variables\n    for (int i = 0; i < fPan.nE; ++i) {\n        int f = fPan.eIdx(i);\n        // Speed of sound\n        fPan.a(f) = sqrt(\n                1/(Minf * Minf) + (GAMMA - 1) / 2 - (GAMMA - 1) / 2 * fPan.U.row(f).dot(fPan.U.row(f)));\n        // Mach number\n        fPan.M(f) = fPan.U.row(f).norm() / fPan.a(f);\n        // Density\n        fPan.rho(f) = pow(\n                1 + (GAMMA - 1) / 2 * Minf * Minf * (1 - fPan.U.row(f).dot(fPan.U.row(f))),\n                1 / (GAMMA - 1));\n    }\n}", "meta": {"hexsha": "95d8ddc2a837b9e70d1e0558480bbc24cf4955e7", "size": 5044, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/compute_fVars.cpp", "max_stars_repo_name": "acrovato/aero", "max_stars_repo_head_hexsha": "310e6840670f5a39ca015c61c9090f123da8cfd6", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2020-11-16T15:24:12.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-15T09:36:09.000Z", "max_issues_repo_path": "src/compute_fVars.cpp", "max_issues_repo_name": "acrovato/aero", "max_issues_repo_head_hexsha": "310e6840670f5a39ca015c61c9090f123da8cfd6", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/compute_fVars.cpp", "max_forks_repo_name": "acrovato/aero", "max_forks_repo_head_hexsha": "310e6840670f5a39ca015c61c9090f123da8cfd6", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.8175182482, "max_line_length": 104, "alphanum_fraction": 0.5598731166, "num_tokens": 1670, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6723316860482763, "lm_q2_score": 0.4921881357207956, "lm_q1q2_score": 0.3309136791421204}}
{"text": "// __BEGIN_LICENSE__\n// Copyright (C) 2006-2010 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#ifdef _MSC_VER\n#pragma warning(disable:4244)\n#pragma warning(disable:4267)\n#pragma warning(disable:4996)\n#endif\n\n#ifdef NDEBUG\n#undef NDEBUG\n#endif\n\n#include <cstdlib>\n\n#include <boost/program_options.hpp>\nnamespace po = boost::program_options;\n\n#include <boost/filesystem/path.hpp>\nnamespace fs = boost::filesystem;\n\n#include <vw/Math/EulerAngles.h>\n#include <vw/Image/ImageView.h>\n#include <vw/Image/Algorithms.h>\n#include <vw/Image/ImageViewRef.h>\n#include <vw/Image/Filter.h>\n#include <vw/Image/PixelMask.h>\n#include <vw/Image/MaskViews.h>\n#include <vw/Image/PerPixelAccessorViews.h>\n#include <vw/FileIO/DiskImageView.h>\n#include <vw/FileIO/DiskImageResourceGDAL.h>\n#include <vw/Cartography/GeoReference.h>\n#include <vw/tools/Common.h>\n\nusing namespace vw;\n\n\n// Global Variables\nstd::string input_file_name, output_file_name = \"\";\ndouble azimuth, elevation, scale;\ndouble nodata_value;\ndouble blur_sigma;\n\n// Allows FileIO to correctly read/write these pixel types\nnamespace vw {\n  template<> struct PixelFormatID<Vector3>   { static const PixelFormatEnum value = VW_PIXEL_XYZ; };\n}\n\n// ---------------------------------------------------------------------------------------------------\n\n//  compute_normals()\n//\n// Compute a vector normal to the surface of a DEM for each given\n// pixel.  The normal is computed by forming a plane with three points\n// in the vicinity of the requested pixel, and then finding the vector\n// normal to that plane.  The user must specify the scale in the [u,v]\n// directions so that the direction of the vector in physical space\n// can be properly ascertained.  This is often contained in the (0,0)\n// and (1,1) entry of the georeference transform.\nclass ComputeNormalsFunc : public ReturnFixedType<PixelMask<Vector3> >\n{\n  double m_u_scale, m_v_scale;\n\npublic:\n  ComputeNormalsFunc(double u_scale, double v_scale) :\n    m_u_scale(u_scale), m_v_scale(v_scale) {}\n\n  BBox2i work_area() const { return BBox2i(Vector2i(0, 0), Vector2i(1, 1)); }\n\n  template <class PixelAccessorT>\n  PixelMask<Vector3> operator() (PixelAccessorT const& accessor_loc) const {\n    PixelAccessorT acc = accessor_loc;\n\n    // Pick out the three altitude values.\n    if (is_transparent(*acc))\n      return PixelMask<Vector3>();\n    double alt1 = *acc;\n\n    acc.advance(1,0);\n    if (is_transparent(*acc))\n      return PixelMask<Vector3>();\n    double alt2 = *acc;\n\n    acc.advance(-1,1);\n    if (is_transparent(*acc))\n      return PixelMask<Vector3>();\n    double alt3 = *acc;\n\n    // Form two orthogonal vectors in the plane containing the three\n    // altitude points\n    Vector3 n1(m_u_scale, 0, alt2-alt1);\n    Vector3 n2(0, m_v_scale, alt3-alt1);\n\n    // Return the vector normal to the local plane.\n    return normalize(cross_prod(n1,n2));\n  }\n};\n\ntemplate <class ViewT>\nUnaryPerPixelAccessorView<EdgeExtensionView<ViewT,ConstantEdgeExtension>, ComputeNormalsFunc> compute_normals(ImageViewBase<ViewT> const& image,\n                                                                                                              double u_scale, double v_scale) {\n  return UnaryPerPixelAccessorView<EdgeExtensionView<ViewT,ConstantEdgeExtension>, ComputeNormalsFunc>(edge_extend(image.impl(), ConstantEdgeExtension()),\n                                                                                                       ComputeNormalsFunc (u_scale, v_scale));\n}\n\nclass DotProdFunc : public ReturnFixedType<PixelMask<PixelGray<double> > > {\n  Vector3 m_vec;\npublic:\n  DotProdFunc(Vector3 const& vec) : m_vec(vec) {}\n  PixelMask<PixelGray<double> > operator() (PixelMask<Vector3> const& pix) const {\n    if (is_transparent(pix))\n      return PixelMask<PixelGray<double> >();\n    else {\n//       std::cout << \"Vec1 : \" << pix.child() << \"   \" << norm_2(pix.child()) << \"\\n\";\n//       std::cout << \"Vec2 : \" << m_vec << \"   \" << norm_2(m_vec) << \"\\n\";\n//       std::cout << \"OVerall: \" << dot_prod(pix.child(),m_vec)/(norm_2(pix.child()) * norm_2(m_vec)) << \"\\n\\n\";\n      return dot_prod(pix.child(),m_vec)/(norm_2(pix.child()) * norm_2(m_vec));\n    }\n  }\n};\n\ntemplate <class ViewT>\nUnaryPerPixelView<ViewT, DotProdFunc> dot_prod(ImageViewBase<ViewT> const& view, Vector3 const& vec) {\n  return UnaryPerPixelView<ViewT, DotProdFunc>(view.impl(), DotProdFunc(vec));\n}\n\n// ---------------------------------------------------------------------------------------------------\n\ntemplate <class PixelT>\nvoid do_hillshade(po::variables_map const& vm) {\n\n  cartography::GeoReference georef;\n  cartography::read_georeference(georef, input_file_name);\n\n  // Select the pixel scale.\n  double u_scale, v_scale;\n  if (scale == 0) {\n    if (georef.is_projected()) {\n      u_scale = georef.transform()(0,0);\n      v_scale = georef.transform()(1,1);\n    } else {\n      double meters_per_degree = 2*M_PI*georef.datum().semi_major_axis()/360.0;\n      u_scale = georef.transform()(0,0) * meters_per_degree;\n      v_scale = georef.transform()(1,1) * meters_per_degree;\n    }\n  } else {\n    u_scale = scale;\n    v_scale = -scale;\n  }\n  // For debugging:\n  //  std::cout << \"\\t--> Scale: \" << u_scale << \"  \" << v_scale << \"\\n\";\n\n  // Set the direction of the light source.\n  Vector3 light_0(1,0,0);\n  Vector3 light = vw::math::euler_to_rotation_matrix(elevation*M_PI/180, azimuth*M_PI/180, 0, \"yzx\") * light_0;\n\n  // Compute the surface normals\n  std::cout << \"Loading: \" << input_file_name << \".\\n\";\n  DiskImageView<PixelT> disk_dem_file(input_file_name);\n  ImageViewRef<PixelGray<double> > input_image = channel_cast<double>(disk_dem_file);\n\n  ImageViewRef<PixelMask<PixelGray<double> > > dem;\n  SrcImageResource *disk_dem_rsrc = DiskImageResource::open(input_file_name);\n  if (vm.count(\"nodata-value\")) {\n    std::cout << \"\\t--> Masking pixel value: \" << nodata_value << \".\\n\";\n    dem = create_mask(input_image, nodata_value);\n  } else if ( disk_dem_rsrc->has_nodata_read() ) {\n    nodata_value = disk_dem_rsrc->nodata_read();\n    std::cout << \"\\t--> Extracted nodata value from file: \" << nodata_value << \".\\n\";\n    dem = create_mask(input_image, nodata_value);\n  } else {\n    dem = pixel_cast<PixelMask<PixelGray<double> > >(input_image);\n  }\n  delete disk_dem_rsrc;\n\n  if (vm.count(\"blur\")) {\n    std::cout << \"\\t--> Blurring pixel with gaussian kernal.  Sigma = \" << blur_sigma << \"\\n\";\n    dem = gaussian_filter(dem, blur_sigma);\n  }\n\n  // The final result is the dot product of the light source with the normals\n  ImageViewRef<PixelMask<PixelGray<uint8> > > shaded_image = channel_cast_rescale<uint8>(clamp(dot_prod(compute_normals(dem, u_scale, v_scale), light)));\n\n  // Save the result\n  std::cout << \"Writing shaded relief image: \" << output_file_name << \"\\n\";\n\n  DiskImageResourceGDAL rsrc(output_file_name, shaded_image.format());\n  rsrc.set_block_write_size(Vector2i(1024,1024));\n  write_georeference(rsrc, georef);\n  write_image(rsrc, shaded_image,\n              TerminalProgressCallback( \"tools.hillshade\", \"Writing:\"));\n}\n\nint main( int argc, char *argv[] ) {\n\n  po::options_description desc(\"Description: Outputs image of a DEM lighted as specified\\n\\nUsage: hillshade [options] <input file> \\n\\nOptions\");\n  desc.add_options()\n    (\"help,h\", \"Display this help message\")\n    (\"input-file\", po::value<std::string>(&input_file_name), \"Explicitly specify the input file\")\n    (\"output-file,o\", po::value<std::string>(&output_file_name), \"Specify the output file\")\n    (\"azimuth,a\", po::value<double>(&azimuth)->default_value(0), \"Sets the direction tha the light source is coming from (in degrees).  Zero degrees is to the right, with positive degree counter-clockwise.\")\n    (\"elevation,e\", po::value<double>(&elevation)->default_value(45), \"Set the elevation of the light source (in degrees).\")\n    (\"scale,s\", po::value<double>(&scale)->default_value(0), \"Set the scale of a pixel (in the same units as the DTM height values.\")\n    (\"nodata-value\", po::value<double>(&nodata_value), \"Remap the DEM default value to the min altitude value.\")\n    (\"blur\", po::value<double>(&blur_sigma), \"Pre-blur the DEM with the specified sigma.\");\n  po::positional_options_description p;\n  p.add(\"input-file\", 1);\n\n  po::variables_map vm;\n  try {\n    po::store( po::command_line_parser( argc, argv ).options(desc).positional(p).run(), vm );\n    po::notify( vm );\n  } catch (po::error &e) {\n    std::cout << \"An error occured while parsing command line arguments.\\n\";\n    std::cout << \"\\t\" << e.what() << \"\\n\\n\";\n    std::cout << desc << std::endl;\n    return 1;\n  }\n\n  if( vm.count(\"help\") ) {\n    std::cout << desc << std::endl;\n    return 1;\n  }\n\n  if( vm.count(\"input-file\") != 1 ) {\n    std::cout << \"Error: Must specify exactly one input file!\\n\" << std::endl;\n    std::cout << desc << std::endl;\n    return 1;\n  }\n\n  if( output_file_name == \"\" ) {\n    output_file_name = fs::path(input_file_name).replace_extension().string() + \"_HILLSHADE.tif\";\n  }\n\n  try {\n    // Get the right pixel/channel type.\n    ImageFormat fmt = tools::taste_image(input_file_name);\n\n    switch(fmt.pixel_format) {\n    case VW_PIXEL_GRAY:\n    case VW_PIXEL_GRAYA:\n    case VW_PIXEL_RGB:\n    case VW_PIXEL_RGBA:\n      switch(fmt.channel_type) {\n      case VW_CHANNEL_UINT8:  do_hillshade<PixelGray<uint8>   >(vm); break;\n      case VW_CHANNEL_INT16:  do_hillshade<PixelGray<int16>   >(vm); break;\n      case VW_CHANNEL_UINT16: do_hillshade<PixelGray<uint16>  >(vm); break;\n      case VW_CHANNEL_FLOAT64:do_hillshade<PixelGray<float64> >(vm); break;\n      default:                do_hillshade<PixelGray<float32> >(vm); break;\n      }\n      break;\n    default:\n      std::cout << \"Error: Unsupported pixel format.\\n\";\n      exit(0);\n    }\n  } catch( Exception& e ) {\n    std::cout << \"Error: \" << e.what() << std::endl;\n  }\n\n  return 0;\n}\n", "meta": {"hexsha": "b3bda80ee9a3142a434802a7870fceff0100d5f9", "size": 9923, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/vw/tools/hillshade.cc", "max_stars_repo_name": "tkeemon/visionworkbench", "max_stars_repo_head_hexsha": "df59fcb31191e1fc4fecfe1901963da1614a52b1", "max_stars_repo_licenses": ["NASA-1.3"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-06-02T04:06:43.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-02T04:06:43.000Z", "max_issues_repo_path": "src/vw/tools/hillshade.cc", "max_issues_repo_name": "tkeemon/visionworkbench", "max_issues_repo_head_hexsha": "df59fcb31191e1fc4fecfe1901963da1614a52b1", "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/tools/hillshade.cc", "max_forks_repo_name": "tkeemon/visionworkbench", "max_forks_repo_head_hexsha": "df59fcb31191e1fc4fecfe1901963da1614a52b1", "max_forks_repo_licenses": ["NASA-1.3"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.3045112782, "max_line_length": 207, "alphanum_fraction": 0.6581678928, "num_tokens": 2586, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7057850154599562, "lm_q2_score": 0.4687906266262437, "lm_q1q2_score": 0.33086539966088596}}
{"text": "﻿#ifndef SIG_POLAR_SPIN_HPP\n#define SIG_POLAR_SPIN_HPP\n\n#include \"signlp.hpp\"\n#include \"SigUtil/lib/functional/fold.hpp\"\n#include \"SigUtil/lib/calculation.hpp\"\n#include <boost/graph/adjacency_list.hpp>\n\nnamespace signlp\n{\n\nclass SpinModel\n{\n\tstruct Node\n\t{\n\t\tstd::wstring word;\n\t\tuint degree;\n\n\t\tbool has_label;\n\t\tdouble label;\n\n\t\tdouble mean_x;\n\t\tdouble tmp_mean_x;\n\t};\n\npublic:\n\tusing Graph = boost::adjacency_list<boost::vecS, boost::vecS, boost::undirectedS,\n\t\tNode,\n\t\tboost::property<boost::edge_weight_t, double>\n\t>;\n\tusing pNode = Graph::vertex_descriptor;\n\tusing pEdge = Graph::edge_descriptor;\n\n\tstatic auto make_node(Graph& g, std::wstring word) ->pNode\n\t{\n\t\tauto v = boost::add_vertex(g);\n\t\tg[v].word = word;\n\t\tg[v].has_label = false;\n\t\treturn v;\n\t}\n\tstatic auto make_node(Graph& g, std::wstring word, bool label) ->pNode\n\t{\n\t\tauto v = boost::add_vertex(g);\n\t\tg[v].word = word;\n\t\tg[v].label = label ? 1 : -1;\n\t\tg[v].has_label = true;\n\t\treturn v;\n\t}\n\tstatic auto make_node(Graph& g, std::wstring word, double label) ->pNode\n\t{\n\t\tauto v = boost::add_vertex(g);\n\t\tg[v].word = word;\n\t\tg[v].label = label;\n\t\tg[v].has_label = true;\n\t\treturn v;\n\t}\n\n\tstatic void make_edge(Graph& g, pNode v1, pNode v2, double weight)\n\t{\n\t\tauto e = add_edge(v1, v2, g);\n\t\tput(boost::edge_weight, g, e.first, weight);\n\t};\n\nprivate:\n\tGraph graph_;\n\n\tconst double alpha_;\t// ラベル(正解)の反映度\n\tconst double beta_;\t\t// 逆温度\n\n\tconst sig::array<int, 2> xs_;\n\tstd::unordered_map<pNode, std::vector<pNode>> adj_;\n\tsig::SimpleRandom<double> rand_d_;\n\nprivate:\n\tvoid init()\n\t{\n\t\tauto nodes = boost::vertices(graph_);\n\n\t\tstd::for_each(\n\t\t\tboost::begin(nodes),\n\t\t\tboost::end(nodes),\n\t\t\t[&](pNode n){\n\t\t\t\tstd::vector<pNode> tmp;\n\t\t\t\tauto adj = adjacent_vertices(n, graph_);\n\t\t\t\tfor (auto it = adj.first, end = adj.second; it != end; ++it){\n\t\t\t\t\ttmp.push_back(*it);\n\t\t\t\t}\n\n\t\t\t\tgraph_[n].degree = tmp.size();\n\t\t\t\tadj_.emplace(n, std::move(tmp));\n\n\t\t\t\tif (graph_[n].has_label){\n\t\t\t\t\tgraph_[n].mean_x = graph_[n].label;\n\t\t\t\t\tgraph_[n].tmp_mean_x = graph_[n].label;\n\t\t\t\t}\n\t\t\t\telse{\n\t\t\t\t\tdouble r = rand_d_();\n\t\t\t\t\tgraph_[n].mean_x = r;\n\t\t\t\t\tgraph_[n].tmp_mean_x = r;\n\t\t\t\t}\n\t\t\t}\n\t\t);\n\n\t\tauto edges = boost::edges(graph_);\n\n\t\tstd::for_each(\n\t\t\tboost::begin(edges),\n\t\t\tboost::end(edges),\n\t\t\t[&](pEdge e){\n\t\t\t\tauto v1 = boost::source(e, graph_);\n\t\t\t\tauto v2 = boost::target(e, graph_);\n\t\t\t\tauto adjn1 = graph_[v1].degree;\n\t\t\t\tauto adjn2 = graph_[v2].degree;\n\t\n\t\t\t\tdouble decay = std::sqrt(adjn1 * adjn2);\n\t\t\t\tauto t = boost::get(boost::get(boost::edge_weight, graph_), e);\n\t\t\t\tboost::get(boost::get(boost::edge_weight, graph_), e) /= decay;\t\t\t\t\n\t\t\t}\n\t\t);\n\t}\n\n\tvoid update(uint k)\n\t{\n\t\tconst double wx_sum = sig::dotProduct(\n\t\t\tstd::plus<double>(),\n\t\t\t[&](uint n){ return graph_[n].mean_x * boost::get(boost::get(boost::edge_weight, graph_), boost::edge(k, n, graph_).first); },\n\t\t\t0, adj_[k]\n\t\t);\n\n\t\tconst auto exp_wx_sum = sig::map([&](int x_i){\treturn std::exp(beta_ * x_i * wx_sum); }, xs_);\n\n\t\tauto t = sig::dotProduct(std::plus<double>(), std::multiplies<double>(), 0, exp_wx_sum, xs_) / sig::sum(exp_wx_sum);\n\n\t\tif (!sig::is_number(t)){\n\t\t\tstd::cout << \"wxsum:\" << wx_sum << std::endl;\n\t\t\tstd::cout << \"exp_wx_sum0:\" << exp_wx_sum[0] << std::endl;\n\t\t\tstd::cout << \"exp_wx_sum1:\" << exp_wx_sum[1] << std::endl;\n\t\t\tgetchar();\n\t\t}\n\n\t\tgraph_[k].tmp_mean_x = t;\n\t}\n\n\tvoid updateL(uint k)\n\t{\n\t\tif (adj_[k].empty()) return;\n\t\t/*const double wx_sum = sig::fold_zipWith(\n\t\t\tstd::multiply<double>(),\n\t\t\tstd::plus<double>(),\n\t\t\t0, w_[k], mean_x_\n\t\t);*/\n\t\tconst double wx_sum = sig::dotProduct(\n\t\t\tstd::plus<double>(),\n\t\t\t[&](uint n){ return graph_[n].mean_x * boost::get(boost::get(boost::edge_weight, graph_), boost::edge(k, n, graph_).first); },\n\t\t\t0, adj_[k]\n\t\t);\n\n\t\tconst auto exp_wx_sum = sig::map([&](int x_i){\treturn std::exp(beta_ * x_i * wx_sum - alpha_ * std::pow(x_i - graph_[k].label, 2)); }, xs_);\n\t\t\n\t\tauto t = sig::dotProduct(std::plus<double>(), std::multiplies<double>(), 0, exp_wx_sum, xs_) / sig::sum(exp_wx_sum);\n\n\t\tif (!sig::is_number(t)){\n\t\t\tstd::cout << \"wxsum:\" << wx_sum << std::endl;\n\t\t\tstd::cout << \"exp_wx_sum0:\" << exp_wx_sum[0] << std::endl;\n\t\t\tstd::cout << \"exp_wx_sum1:\" << exp_wx_sum[1] << std::endl;\n\t\t\tgetchar();\n\t\t}\n\n\t\tgraph_[k].tmp_mean_x = t;\n\t}\n\npublic:\n\tSpinModel(Graph const& graph, double alpha, double beta) : graph_(graph), alpha_(alpha), beta_(beta), xs_({ -1, 1 }), rand_d_(-1.0, 1.0, true)\n\t{\n\t\tinit();\n\t}\n\n\tvoid train(uint iteration_num, std::function<void(SpinModel const*)> callback)\n\t{\n\t\tfor (uint i = 0; i < iteration_num; ++i){\n\t\t\tauto nodes = boost::vertices(graph_);\n\n\t\t\tstd::for_each(\n\t\t\t\tboost::begin(nodes),\n\t\t\t\tboost::end(nodes),\n\t\t\t\t[&](pNode n){ graph_[n].has_label ? updateL(n) : update(n); }\n\t\t\t);\n\n\t\t\tstd::for_each(\n\t\t\t\tboost::begin(nodes),\n\t\t\t\tboost::end(nodes),\n\t\t\t\t[&](pNode n){ graph_[n].mean_x = graph_[n].tmp_mean_x; }\n\t\t\t);\n\n\t\t\tcallback(this);\n\t\t}\n\t}\n\n\tauto getScore(std::wstring word) const->sig::Maybe<double>\n\t{\n\t\tauto nodes = boost::vertices(graph_);\n\n\t\tfor(auto it = nodes.first, end = nodes.second; it != end; ++it){\n\t\t\tif(graph_[*it].word == word) return graph_[*it].mean_x; \n\t\t}\n\t\treturn boost::none;\n\t}\n\n\tauto getScore() const->std::unordered_map<std::wstring, double>\n\t{\n\t\tstd::unordered_map<std::wstring, double> result;\n\t\tauto nodes = boost::vertices(graph_);\n\n\t\tfor (auto it = nodes.first, end = nodes.second; it != end; ++it){\n\t\t\tresult.emplace(graph_[*it].word, graph_[*it].mean_x);\n\t\t}\n\t\treturn result;\n\t}\n\n\t// leave-one-out error\n\tdouble getErrorRate() const\n\t{\n\t\tint ct = 0;\n\t\tdouble sum = 0;\n\t\tauto nodes = boost::vertices(graph_);\n\n\t\tstd::for_each(\n\t\t\tboost::begin(nodes),\n\t\t\tboost::end(nodes),\n\t\t\t[&](pNode n){\n\t\t\t\tif(graph_[n].has_label){\n\t\t\t\t\tsum += (graph_[n].label * graph_[n].mean_x < 0 ? 1 : 0);\n\t\t\t\t\t++ct;\n\t\t\t\t}\n\t\t\t}\n\t\t);\n\n\t\treturn sum / ct;\n\t}\n\n\tdouble getMeanPolar() const\n\t{\n\t\tint ct = 0;\n\t\tdouble sum = 0;\n\t\tauto nodes = boost::vertices(graph_);\n\n\t\tstd::for_each(\n\t\t\tboost::begin(nodes),\n\t\t\tboost::end(nodes),\n\t\t\t[&](pNode n){\n\t\t\t\tsum += graph_[n].mean_x;\n\t\t\t\t++ct;\n\t\t\t}\n\t\t);\n\n\t\treturn sum / ct;\n\t}\n};\n\n}\n#endif", "meta": {"hexsha": "0185caebb83c852b5e5ff4097a441408bd749dcf", "size": 6066, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "SigTM/lib/helper/SigNLP/polar_spin.hpp", "max_stars_repo_name": "regenschauer490/TopicModel", "max_stars_repo_head_hexsha": "d9a2be5801d7e4da7429bca828039accf1b30033", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "SigTM/lib/helper/SigNLP/polar_spin.hpp", "max_issues_repo_name": "regenschauer490/TopicModel", "max_issues_repo_head_hexsha": "d9a2be5801d7e4da7429bca828039accf1b30033", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "SigTM/lib/helper/SigNLP/polar_spin.hpp", "max_forks_repo_name": "regenschauer490/TopicModel", "max_forks_repo_head_hexsha": "d9a2be5801d7e4da7429bca828039accf1b30033", "max_forks_repo_licenses": ["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.2413793103, "max_line_length": 143, "alphanum_fraction": 0.6150675898, "num_tokens": 1965, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.749087201911703, "lm_q2_score": 0.4416730056646256, "lm_q1q2_score": 0.3308515959732461}}
{"text": "#include <armadillo>\n#include <boost/program_options.hpp>\n#include <json.hpp>\n#include <HSMM.hpp>\n#include <ProMPs_emission.hpp>\n\nusing namespace arma;\nusing namespace hsmm;\nusing namespace robotics;\nusing namespace std;\nnamespace po = boost::program_options;\n\nfield<mat> fromMatToField(const mat& obs) {\n    field<mat> ret(obs.n_cols);\n    for(int i = 0; i < obs.n_cols; i++)\n        ret(i) = obs.col(i);\n    return ret;\n}\n\n// Running the Viterbi algorithm.\nvoid ViterbiAlgorithm(HSMM& promp_hsmm, const field<field<mat>>& seq_obs,\n        string filename) {\n    int nseq = seq_obs.n_elem;\n    for(int s = 0; s < nseq; s++) {\n        const field<mat>& obs = seq_obs(s);\n        int nstates = promp_hsmm.nstates_;\n        int nobs = obs.n_elem;\n        imat psi_duration(nstates, nobs, fill::zeros);\n        imat psi_state(nstates, nobs, fill::zeros);\n        mat delta(nstates, nobs, fill::zeros);\n        cout << \"Before pdf\" << endl;\n        cube log_pdf = promp_hsmm.computeEmissionsLogLikelihood(obs);\n        cout << \"After pdf\" << endl;\n        Viterbi(promp_hsmm.transition_, promp_hsmm.pi_, promp_hsmm.duration_,\n                log_pdf, delta, psi_duration, psi_state,\n                promp_hsmm.min_duration_, nobs);\n        cout << \"Delta last column\" << endl;\n        cout << delta.col(nobs - 1) << endl;\n        ivec viterbiStates, viterbiDurations;\n        viterbiPath(psi_duration, psi_state, delta, viterbiStates,\n                viterbiDurations);\n        cout << \"Viterbi states and durations\" << endl;\n        imat states_and_durations = join_horiz(viterbiStates, viterbiDurations);\n        cout << states_and_durations << endl;\n        cout << \"Python states list representation\" << endl;\n        cout << \"[\";\n        for(int i = 0; i < viterbiStates.n_elem; i++)\n            cout << viterbiStates[i] <<\n                    ((i + 1 == viterbiStates.n_elem)? \"]\" : \",\");\n        cout << endl;\n        cout << \"Python duration list representation\" << endl;\n        cout << \"[\";\n        for(int i = 0; i < viterbiDurations.n_elem; i++)\n            cout << viterbiDurations[i] <<\n                    ((i + 1 == viterbiDurations.n_elem)? \"]\" : \",\");\n        cout << endl;\n\n        // Saving the matrix of joint states and durations.\n        string viterbi_filename(filename);\n        if (nseq > 1)\n            viterbi_filename += string(\".\") + to_string(s);\n        states_and_durations.save(viterbi_filename, raw_ascii);\n    }\n}\n\nint main(int argc, char *argv[]) {\n    po::options_description desc(\"Options\");\n    desc.add_options()\n        (\"help,h\", \"Produce help message\")\n        (\"input,i\", po::value<string>(), \"Path to the input obs\")\n        (\"output,o\", po::value<string>(), \"Path to the json output params\")\n        (\"nstates\", po::value<int>(), \"Number of hidden states for the HSMM\")\n        (\"mindur\", po::value<int>(), \"Minimum duration of a segment\")\n        (\"ndur\", po::value<int>(), \"Number of different durations supported\")\n        (\"commitid\", po::value<string>(), \"Git commit id of the experiment\")\n        (\"labels\", po::value<string>(), \"Path to the provided labels\")\n        (\"viterbi,v\", po::value<string>(), \"Path to the output viterbi file\")\n        (\"nfiles\", po::value<int>()->default_value(1),\n                \"Number of files (sequences) to process\")\n        (\"debug\", \"Flag for activating debug mode in HSMM\")\n        (\"nodur\", \"Flag to deactivate the learning of durations\")\n        (\"notrans\", \"Flag to deactivate the learning of transitions\")\n        (\"nopi\", \"Flag to deactivate the learning of initial pmf\")\n        (\"durmomentmatching\", \"Flag to active the Gaussian moment matching\"\n                \" for the duration learning\")\n        (\"polybasisfun\", po::value<int>()->default_value(1), \"Order of the \"\n                \"poly basis functions\")\n        (\"noselftransitions\", \"Flag to deactive self transitions\")\n        (\"initfraction\", po::value<double>()->default_value(0.1), \"Fraction \"\n                \"of the least squares estimates for omega kept for init\")\n        (\"wpriorvar\", po::value<double>(), \"Prior variance for Sigma_w\")\n        (\"alphadurprior\", po::value<int>()->default_value(1),\n                \"Alpha for Dirichlet prior for the duration\")\n        (\"trainingiter\", po::value<int>()->default_value(10), \"Training \"\n                \"iterations\")\n        (\"rbfbasisfun\", po::value<int>()->default_value(3), \"Number of radial\"\n                \" basis functions to use between 0 and 1. 0 and 1 are removed.\")\n        (\"delta\", po::value<double>(), \"If this is given a value, the model \"\n                \"switches to segment agnostic and the samples are generated \"\n                \"according to the provided delta\")\n        (\"leaveoneout\", po::value<int>(), \"Index of the sequence that will be\"\n                \" left out for validation\");\n    vector<string> required_fields = {\"input\", \"output\", \"nstates\", \"mindur\",\n            \"ndur\", \"viterbi\"};\n    po::variables_map vm;\n    po::store(po::parse_command_line(argc, argv, desc), vm);\n    po::notify(vm);\n    if (vm.count(\"help\")) {\n        cout << desc << endl;\n        return 0;\n    }\n    if (vm.count(\"nodur\") && vm.count(\"durmomentmatching\")) {\n        cout << \"Only one choice for duration learning is allowed\" << endl;\n        return 0;\n    }\n    for(auto s: required_fields) {\n        if (!vm.count(s)) {\n            cerr << \"Error: You must provide the argument: \" << s << endl;\n            return 1;\n        }\n    }\n    string input_filename = vm[\"input\"].as<string>();\n    string output_filename = vm[\"output\"].as<string>();\n    field<field<mat>> seq_obs(1);\n    field<Labels> seq_labels(1);\n    int njoints;\n    int nseq = vm[\"nfiles\"].as<int>();\n    seq_obs.set_size(nseq);\n    seq_labels.set_size(nseq);\n    for(int i = 0; i < seq_obs.n_elem; i++) {\n        string name = input_filename;\n        if (nseq != 1)\n            name += string(\".\") + to_string(i);\n        mat obs;\n        obs.load(name, raw_ascii);\n        njoints = obs.n_rows;\n        int nobs = obs.n_cols;\n        cout << \"Time series shape: (\" << njoints << \", \" << nobs <<\n            \").\" << endl;\n        seq_obs(i) = fromMatToField(obs);\n\n        // Reading labels for different obs.\n        if (!vm.count(\"labels\"))\n            continue;\n        string labels_name = vm[\"labels\"].as<string>();\n        if (nseq != 1)\n            labels_name += string(\".\") + to_string(i);\n        mat labels_mat;\n        labels_mat.load(labels_name);\n        for(int j = 0; j < labels_mat.n_rows; j++)\n            seq_labels(i).setLabel(labels_mat(j, 0), labels_mat(j, 1),\n                    labels_mat(j, 2));\n    }\n\n    int min_duration = vm[\"mindur\"].as<int>();\n    int nstates = vm[\"nstates\"].as<int>();\n    int ndurations = vm[\"ndur\"].as<int>();\n    mat transition(nstates, nstates);\n    transition.fill(1.0 / nstates );\n    if (vm.count(\"noselftransitions\")) {\n        transition.fill(1.0 / (nstates - 1));\n        transition.diag().zeros();\n    }\n    vec pi(nstates);\n    pi.fill(1.0/nstates);\n    mat durations(nstates, ndurations);\n    durations.fill(1.0 / ndurations);\n\n    // Setting a combination of polynomial and rbf basis functions.\n    auto poly = make_shared<ScalarPolyBasis>(vm[\"polybasisfun\"].as<int>());\n    auto comb = shared_ptr<ScalarCombBasis>(new ScalarCombBasis({poly}));\n    int nrbf = vm[\"rbfbasisfun\"].as<int>();\n    if (nrbf > 0) {\n        vec centers = linspace<vec>(0, 1.0, nrbf + 2);\n        centers = centers.subvec(1, centers.n_elem - 2);\n        auto rbf = shared_ptr<ScalarGaussBasis>(new ScalarGaussBasis(centers,\n                    0.25));\n        comb = shared_ptr<ScalarCombBasis>(new ScalarCombBasis({rbf, poly}));\n    }\n    int n_basis_functions = comb->dim();\n\n    // Instantiating as many ProMPs as hidden states.\n    vector<FullProMP> promps;\n    for(int i = 0; i < nstates; i++) {\n        vec mu_w(n_basis_functions * njoints);\n        mu_w.randn();\n        mat Sigma_w = eye<mat>(n_basis_functions * njoints,\n                    n_basis_functions * njoints);\n        mat Sigma_y = 0.001 * eye<mat>(njoints, njoints);\n        ProMP promp(mu_w, Sigma_w, Sigma_y);\n        FullProMP poly(comb, promp, njoints);\n        promps.push_back(poly);\n    }\n\n    // Creating the ProMP emission.\n    shared_ptr<ProMPsEmission> ptr_emission(new ProMPsEmission(promps));\n\n    // Creating a prior for Sigma_w.\n    if (vm.count(\"wpriorvar\")) {\n        mat Phi = vm[\"wpriorvar\"].as<double>() * eye<mat>(\n                n_basis_functions * njoints, n_basis_functions * njoints);\n        NormalInverseWishart iw_prior(Phi, Phi.n_rows + 2);\n        ptr_emission->set_Sigma_w_Prior(iw_prior);\n    }\n    if (vm.count(\"delta\"))\n        ptr_emission->setDelta(vm[\"delta\"].as<double>());\n\n    // Settings for the initialization algorithm.\n    ptr_emission->setParamsForInitialization(vm[\"initfraction\"].as<double>());\n\n    HSMM promp_hsmm(std::static_pointer_cast<AbstractEmission>(ptr_emission),\n            transition, pi, durations, min_duration);\n    if (vm.count(\"nodur\"))\n        promp_hsmm.setDurationLearningChoice(\"nodur\");\n    if (vm.count(\"durmomentmatching\"))\n        promp_hsmm.setDurationLearningChoice(\"momentmatching\");\n    if (vm.count(\"alphadurprior\")) {\n        mat alphas = ones<mat>(nstates, ndurations) *\n            vm[\"alphadurprior\"].as<int>();\n        promp_hsmm.setDurationDirichletPrior(alphas);\n    }\n    if (vm.count(\"notrans\"))\n        promp_hsmm.learning_transitions_ = false;\n    if (vm.count(\"nopi\"))\n        promp_hsmm.learning_pi_ = false;\n    if (vm.count(\"debug\"))\n        promp_hsmm.debug_ = true;\n\n    // Initializing the model from data.\n    promp_hsmm.init_params_from_data(seq_obs);\n\n    // Saving the model in a json file.\n    std::ofstream initial_params(output_filename);\n    nlohmann::json initial_model = promp_hsmm.to_stream();\n    if (vm.count(\"commitid\"))\n        initial_model[\"git_commit_id\"] = vm[\"commitid\"].as<string>();\n    initial_params << std::setw(4) << initial_model << std::endl;\n    initial_params.close();\n\n    // Leave one out.\n    field<field<mat>> t_seq;\n    field<Labels> t_labels;\n    if (vm.count(\"leaveoneout\")) {\n        int omitted = vm[\"leaveoneout\"].as<int>();\n        field<field<mat>> left_one_out(seq_obs.n_elem - 1);\n        field<Labels> left_labels(seq_labels.n_elem - 1);\n        int idx = 0;\n        for(int i = 0; i < seq_obs.n_elem; i++)\n            if (i != omitted) {\n                left_one_out(idx) = seq_obs(i);\n                left_labels(idx) = seq_labels(i);\n                idx++;\n            }\n        t_seq = left_one_out;\n        t_labels = left_labels;\n        cout << \"Leaving one out of the training: \" << omitted << endl;\n    }\n    else {\n        t_seq = seq_obs;\n        t_labels = seq_labels;\n    }\n\n    for(int i = 0; i < vm[\"trainingiter\"].as<int>(); i++) {\n\n        // Reading the current parameters.\n        std::ifstream current_params_stream(output_filename);\n        nlohmann::json current_params;\n        current_params_stream >> current_params;\n        promp_hsmm.from_stream(current_params);\n\n        bool convergence_reached = promp_hsmm.fit(t_seq, t_labels, 5, 1e-5);\n\n        // Saving again the parameters after one training iteration.\n        std::ofstream output_params(output_filename);\n        current_params = promp_hsmm.to_stream();\n        if (vm.count(\"commitid\"))\n            current_params[\"git_commit_id\"] = vm[\"commitid\"].as<string>();\n        output_params << std::setw(4) << current_params << std::endl;\n        output_params.close();\n\n        ViterbiAlgorithm(promp_hsmm, seq_obs, vm[\"viterbi\"].as<string>());\n\n        if (convergence_reached)\n            break;\n\n    }\n    cout << \"loglikelihood: \" << promp_hsmm.loglikelihood(t_seq) << endl;\n    if (vm.count(\"leaveoneout\")) {\n        int omitted = vm[\"leaveoneout\"].as<int>();\n        field<field<mat>> test = {seq_obs(omitted)};\n        field<Labels> test_labels = {seq_labels(omitted)};\n        cout << \"loglikelihoodtest: \" << promp_hsmm.loglikelihood(test) << endl;\n    }\n    return 0;\n}\n\n", "meta": {"hexsha": "5dc5c6e3e8657ad898779a8b18ed76bc7fe88c50", "size": 11998, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/promps_hsmm_robot.cpp", "max_stars_repo_name": "DiegoAE/BOSD", "max_stars_repo_head_hexsha": "a7ce88462c64c540ba2922d16eb6f7eba8055b47", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 19.0, "max_stars_repo_stars_event_min_datetime": "2019-05-03T05:31:43.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-08T18:14:31.000Z", "max_issues_repo_path": "examples/promps_hsmm_robot.cpp", "max_issues_repo_name": "DiegoAE/BOSD", "max_issues_repo_head_hexsha": "a7ce88462c64c540ba2922d16eb6f7eba8055b47", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2019-02-14T15:29:34.000Z", "max_issues_repo_issues_event_max_datetime": "2020-06-04T10:14:54.000Z", "max_forks_repo_path": "examples/promps_hsmm_robot.cpp", "max_forks_repo_name": "DiegoAE/BOSD", "max_forks_repo_head_hexsha": "a7ce88462c64c540ba2922d16eb6f7eba8055b47", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-07-01T07:44:09.000Z", "max_forks_repo_forks_event_max_datetime": "2019-07-01T07:44:09.000Z", "avg_line_length": 40.3973063973, "max_line_length": 80, "alphanum_fraction": 0.5974329055, "num_tokens": 3082, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7690802370707281, "lm_q2_score": 0.4301473485858429, "lm_q1q2_score": 0.33081782482574523}}
{"text": "// MIT License\n\n// Copyright (c) 2019 Edward Liu\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 \"registrators/icp_fast.h\"\n\n#include <algorithm>\n#include <cstdlib>\n#include <ctime>\n#include <iostream>\n#include <limits>\n#include <utility>\n#include <vector>\n\n#include <boost/typeof/typeof.hpp>\n\n#include \"common/macro_defines.h\"\n#include \"common/math.h\"\n#include \"common/performance/simple_prof.h\"\n\nnamespace static_map {\nnamespace registrator {\n\nconstexpr int kNormalEstimationKnn = 7;\nconstexpr int kDim = 3;\n\nusing Matrix = Eigen::MatrixXd;\nusing Vector = Eigen::VectorXd;\nusing OutlierWeights = Matrix;\nusing data::EigenPointCloud;\n\nstruct Matches {\n  //!< Squared distances to closest points, dense matrix\n  using Dists = Matrix;\n  //!< Identifiers of closest points, dense matrix of integers\n  using Ids = Eigen::MatrixXi;\n\n  Matches() = default;\n  Matches(const int knn, const int points_count)\n      : dists(Dists(knn, points_count)), ids(Ids(knn, points_count)) {}\n\n  //!< squared distances to closest points\n  Dists dists;\n  //!< identifiers of closest points\n  Ids ids;\n\n  double GetDistsQuantile(const double quantile) const {\n    // REGISTER_FUNC;\n    // build array\n    CHECK(quantile >= 0.0 && quantile <= 1.0);\n    std::vector<double> values;\n    values.reserve(dists.rows() * dists.cols());\n    for (int x = 0; x < dists.cols(); ++x) {\n      for (int y = 0; y < dists.rows(); ++y) {\n        if (dists(y, x) != std::numeric_limits<double>::infinity()) {\n          values.push_back(dists(y, x));\n        }\n      }\n    }\n\n    // BUG\n    // Sometimes this really happens, which should not.\n    CHECK(!values.empty());\n    // get quantile\n    if (quantile == 1.0) {\n      return *std::max_element(values.begin(), values.end());\n    }\n    const int quantile_index = values.size() * quantile;\n    std::nth_element(values.begin(), values.begin() + quantile_index,\n                     values.end());\n    return values[quantile_index];\n  }\n};\n\nstruct ErrorElements {\n  EigenPointCloud reading;    //!< reading point cloud\n  EigenPointCloud reference;  //!< reference point cloud\n  OutlierWeights weights;     //!< weights for every association\n  Matches matches;            //!< associations\n\n  ErrorElements();\n  ErrorElements(const EigenPointCloud& source_points,\n                const EigenPointCloud& target_points,\n                const OutlierWeights& weights, const Matches& matches) {\n    REGISTER_FUNC;\n    CHECK_GT(matches.ids.rows(), 0);\n    CHECK_GT(matches.ids.cols(), 0);\n    CHECK(matches.ids.cols() == source_points.points.cols());  // nbpts\n    CHECK(weights.rows() == matches.ids.rows());               // knn\n    CHECK_EQ(weights.rows(), 1);\n\n    const int dim_points = source_points.points.rows();\n\n    // Count points with no weights\n    const int points_count = (weights.array() != 0.0).count();\n    CHECK_GT(points_count, 0) << \"no point to minimize\";\n\n    Matrix kept_points(dim_points, points_count);\n    std::vector<double> kept_points_factor(points_count);\n    Matches kept_matches(1, points_count);\n    OutlierWeights kept_weights(1, points_count);\n\n    int j = 0;\n    for (int i = 0; i < source_points.points.cols(); ++i) {\n      const auto match_dist = matches.dists(0, i);\n      if (match_dist == NNS::InvalidValue) {\n        continue;\n      }\n\n      if (weights(0, i) != 0.0) {\n        kept_points.col(j) = source_points.points.col(i);\n        kept_points_factor[j] = source_points.factors[i];\n        kept_matches.ids(0, j) = matches.ids(0, i);\n        kept_matches.dists(0, j) = match_dist;\n        kept_weights(0, j) = weights(0, i);\n        ++j;\n      }\n    }\n    CHECK_EQ(j, points_count);\n    CHECK_EQ(dim_points, target_points.points.rows());\n\n    const int dim_target_normals = target_points.normals.rows();\n    Matrix associated_target_normals;\n    if (dim_target_normals > 0) {\n      associated_target_normals = Matrix(dim_target_normals, points_count);\n    }\n\n    Matrix associated_points(dim_points, points_count);\n    // Fetch matched points\n    for (int i = 0; i < points_count; ++i) {\n      const int ref_index(kept_matches.ids(i));\n      associated_points.col(i) =\n          target_points.points.block(0, ref_index, dim_points, 1);\n\n      if (dim_target_normals > 0)\n        associated_target_normals.col(i) =\n            target_points.normals.block(0, ref_index, dim_target_normals, 1);\n    }\n\n    // Copy final data to structure\n    reading.points = kept_points;\n    reading.factors = std::move(kept_points_factor);\n    reference.points = associated_points;\n    reference.normals = associated_target_normals;\n\n    this->weights = kept_weights;\n    this->matches = kept_matches;\n  }\n};\n\nMatches FindClosests(const std::shared_ptr<NNS>& nns_kdtree,\n                     const EigenPointCloud& source_cloud) {\n  REGISTER_FUNC;\n  const int points_count(source_cloud.points.cols());\n  const int search_count = 1;\n  const double epsilon = 3.16;\n  //! A dense integer matrix\n  Matches matches(search_count, points_count);\n  nns_kdtree->knn(source_cloud.points, matches.ids, matches.dists, search_count,\n                  epsilon, NNS::ALLOW_SELF_MATCH);\n  return matches;\n}\n\nEigen::MatrixXd CrossProduct(const Eigen::MatrixXd& A,\n                             const Eigen::MatrixXd& B) {\n  // Expecting matched points\n  CHECK_EQ(A.cols(), B.cols());\n  // Expecting homogenous coord X eucl. coord\n  CHECK_EQ(A.rows(), B.rows());\n\n  constexpr unsigned int x = 0;\n  constexpr unsigned int y = 1;\n  constexpr unsigned int z = 2;\n\n  Eigen::MatrixXd cross(B.rows(), B.cols());\n  cross.row(x) =\n      A.row(y).array() * B.row(z).array() - A.row(z).array() * B.row(y).array();\n  cross.row(y) =\n      A.row(z).array() * B.row(x).array() - A.row(x).array() * B.row(z).array();\n  cross.row(z) =\n      A.row(x).array() * B.row(y).array() - A.row(y).array() * B.row(x).array();\n\n  return cross;\n}\n\nvoid SolvePossiblyUnderdeterminedLinearSystem(const Matrix& A, const Vector& b,\n                                              Vector& x) {  // NOLINT\n  CHECK_EQ(A.cols(), A.rows());\n  CHECK_EQ(b.cols(), 1);\n  CHECK_EQ(b.rows(), A.rows());\n  CHECK_EQ(x.cols(), 1);\n  CHECK_EQ(x.rows(), A.cols());\n\n  // using Matrix = typename Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>;\n\n  BOOST_AUTO(Aqr, A.fullPivHouseholderQr());\n  if (!Aqr.isInvertible()) {\n    // Solve reduced problem R1 x = Q1^T b instead of QR x = b, where Q = [Q1\n    // Q2] and R = [ R1 ; R2 ] such that ||R2|| is small (or zero) and\n    // therefore A = QR ~= Q1 * R1\n    const int rank = Aqr.rank();\n    const int rows = A.rows();\n    const Matrix Q1t = Aqr.matrixQ().transpose().block(0, 0, rank, rows);\n    const Matrix R1 = (Q1t * A * Aqr.colsPermutation()).block(0, 0, rank, rows);\n\n    // The under-determined system R1 x = Q1^T b is made unique ..\n    // by getting the solution of smallest norm (x = R1^T * (R1 * R1^T)^-1\n    // Q1^T b.\n    x = R1.triangularView<Eigen::Upper>().transpose() *\n        (R1 * R1.transpose()).llt().solve(Q1t * b);\n    x = Aqr.colsPermutation() * x;\n\n    BOOST_AUTO(ax, (A * x).eval());\n    if (!b.isApprox(ax, 1e-5)) {\n      x = A.jacobiSvd(Eigen::ComputeThinU | Eigen::ComputeThinV).solve(b);\n      ax = A * x;\n\n      if ((b - ax).norm() > 1e-5 * std::max(A.norm() * x.norm(), b.norm())) {\n        // clang-format off\n        LOG(WARNING)\n            << \"PointMatcher::icp - encountered numerically singular matrix \"\n               \"while minimizing point to plane distance and the current \"\n               \"workaround remained inaccurate.\"\n            << \" b=\" << b.transpose()\n            << \" !~ A * x=\" << (ax).transpose().eval()\n            << \": ||b- ax||=\" << (b - ax).norm()\n            << \", ||b||=\" << b.norm()\n            << \", ||ax||=\" << ax.norm();\n        // clang-format on\n      }\n    }\n  } else {\n    // Cholesky decomposition\n    x = A.llt().solve(b);\n  }\n}\n\nEigen::Matrix4d ComputePointToPlane(const EigenPointCloud& source_cloud,\n                                    const EigenPointCloud& target_cloud,\n                                    const Eigen::MatrixXd& weights,\n                                    const Matches& matches,\n                                    bool compensation = false) {\n  REGISTER_FUNC;\n  const Eigen::MatrixXd target_normals = target_cloud.normals;\n  CHECK_EQ(target_normals.rows(), kDim);\n  CHECK_EQ(target_normals.cols(), target_cloud.points.cols());\n  CHECK_EQ(source_cloud.points.cols(), target_cloud.points.cols());\n\n  // Compute cross product of cross = cross(reading X target_normals)\n  const Matrix cross = CrossProduct(source_cloud.points, target_normals);\n\n  // wF = [weights*cross, weights*normals]\n  // F  = [cross, normals]\n  Matrix wF(target_normals.rows() + cross.rows(), target_normals.cols());\n  Matrix F(target_normals.rows() + cross.rows(), target_normals.cols());\n\n  for (int i = 0; i < cross.rows(); i++) {\n    wF.row(i) = weights.array() * cross.row(i).array();\n    F.row(i) = cross.row(i);\n  }\n  for (int i = 0; i < target_normals.rows(); i++) {\n    wF.row(i + cross.rows()) = weights.array() * target_normals.row(i).array();\n    F.row(i + cross.rows()) = target_normals.row(i);\n  }\n\n  if (compensation) {\n    for (int i = 0; i < target_normals.cols(); ++i) {\n      wF.col(i) *= source_cloud.factors[i];\n      F.col(i) *= source_cloud.factors[i];\n    }\n  }\n\n  // Unadjust covariance A = wF * F'\n  const Matrix A = wF * F.transpose();\n  const Matrix deltas = source_cloud.points - target_cloud.points;\n\n  // dot product of dot = dot(deltas, normals)\n  Matrix dotProd = Matrix::Zero(1, target_normals.cols());\n  for (int i = 0; i < target_normals.rows(); i++) {\n    dotProd += (deltas.row(i).array() * target_normals.row(i).array()).matrix();\n  }\n\n  // b = -(wF' * dot)\n  const Vector b = -(wF * dotProd.transpose());\n  Vector x(A.rows());\n  SolvePossiblyUnderdeterminedLinearSystem(A, b, x);\n\n  // Transform parameters to matrix\n  Eigen::Matrix4d result;\n  Eigen::Transform<double, 3, Eigen::Affine> transform;\n  transform =\n      Eigen::AngleAxis<double>(x.head(3).norm(), x.head(3).normalized());\n\n  transform.translation() = x.segment(3, 3);\n  result = transform.matrix();\n\n  if (result.hasNaN()) {\n    // Degenerate situation. This can happen when the source and reading\n    // clouds are identical, and then b and x above are 0, and the rotation\n    // matrix cannot be determined, it comes out full of NaNs. The correct\n    // rotation is the identity.\n    result.block(0, 0, kDim, kDim) = Matrix::Identity(kDim, kDim);\n  }\n\n  return result;\n}\n\nEigen::Matrix4d ComputePointToPoint(EigenPointCloud& source_cloud,  // NOLINT\n                                    EigenPointCloud& target_cloud,  // NOLINT\n                                    const Eigen::MatrixXd& weights,\n                                    const Matches& matches) {\n  CHECK_EQ(source_cloud.points.cols(), target_cloud.points.cols());\n\n  // const int dimCount(mPts.reading.features.rows());\n  // const int ptsCount(mPts.reading.features.cols()); //Both point clouds\n  // have now the same number of (matched) point\n\n  const Vector w = weights.row(0);\n  const double w_sum_inv = 1. / w.sum();\n  const Vector meanReading =\n      (source_cloud.points.array().rowwise() * w.array().transpose())\n          .rowwise()\n          .sum() *\n      w_sum_inv;\n  const Vector meanReference =\n      (target_cloud.points.array().rowwise() * w.array().transpose())\n          .rowwise()\n          .sum() *\n      w_sum_inv;\n\n  // Remove the mean from the point clouds\n  source_cloud.points.colwise() -= meanReading;\n  target_cloud.points.colwise() -= meanReference;\n\n  // Singular Value Decomposition\n  const Matrix m(target_cloud.points * w.asDiagonal() *\n                 source_cloud.points.transpose());\n  const Eigen::JacobiSVD<Matrix> svd(m,\n                                     Eigen::ComputeThinU | Eigen::ComputeThinV);\n  Matrix rotMatrix(svd.matrixU() * svd.matrixV().transpose());\n  // It is possible to get a reflection instead of a rotation. In this case,\n  // we take the second best solution, guaranteed to be a rotation. For more\n  // details, read the tech report: \"Least-Squares Rigid Motion Using SVD\",\n  // Olga Sorkine http://igl.ethz.ch/projects/ARAP/svd_rot.pdf\n  if (rotMatrix.determinant() < 0.) {\n    Matrix tmpV = svd.matrixV().transpose();\n    tmpV.row(kDim - 1) *= -1.;\n    rotMatrix = svd.matrixU() * tmpV;\n  }\n  const Vector trVector(meanReference - rotMatrix * meanReading);\n\n  Matrix result(Matrix::Identity(4, 4));\n  result.topLeftCorner(kDim, kDim) = rotMatrix;\n  result.topRightCorner(kDim, 1) = trVector;\n\n  return result;\n}\n\nbool CheckConvergence(const std::vector<Eigen::Quaterniond>& rotations,\n                      const std::vector<Eigen::Vector3d>& translations) {\n  constexpr int kSmoothLength = 4;\n  constexpr double kConvergeRotDist = 0.001;\n  constexpr double kConvergeTransDist = 0.01;\n\n  double rotation_dist = 0.;\n  double translation_dist = 0.;\n  bool has_converged = false;\n  if (rotations.size() > kSmoothLength) {\n    for (size_t i = rotations.size() - 1; i >= rotations.size() - kSmoothLength;\n         i--) {\n      // Compute the mean derivative\n      rotation_dist +=\n          std::fabs(rotations[i].angularDistance(rotations[i - 1]));\n      translation_dist +=\n          std::fabs((translations[i] - translations[i - 1]).norm());\n    }\n\n    rotation_dist /= kSmoothLength;\n    translation_dist /= kSmoothLength;\n\n    if (rotation_dist < kConvergeRotDist &&\n        translation_dist < kConvergeTransDist)\n      has_converged = true;\n  }\n\n  return has_converged;\n}\n\nIcpFast::IcpFast() : Interface() {\n  this->type_ = kFastIcp;\n  // TODO(edward) This `knn_normal_estimate` is currently of no use, make it\n  // useful later.\n  REG_REGISTRATOR_INNER_OPTION(\"knn_normal_estimate\",\n                               OptionItemDataType::kInt32,\n                               options_.knn_for_normal_estimate);\n  REG_REGISTRATOR_INNER_OPTION(\"max_iteration\", OptionItemDataType::kInt32,\n                               options_.max_iteration);\n  REG_REGISTRATOR_INNER_OPTION(\"dist_outlier_ratio\",\n                               OptionItemDataType::kFloat32,\n                               options_.dist_outlier_ratio);\n}\n\nvoid IcpFast::SetInputSource(InnerCloudPtr cloud) {\n  CHECK(cloud);\n  CHECK(cloud->GetEigenCloud());\n  source_cloud_.reset(new EigenPointCloud(*cloud->GetEigenCloud()));\n}\n\nvoid IcpFast::SetInputTarget(InnerCloudPtr cloud) {\n  CHECK(cloud);\n  CHECK(cloud->GetEigenCloud());\n  CHECK(cloud->GetEigenCloud()->HasNormals());\n  target_cloud_.reset(new EigenPointCloud(*cloud->GetEigenCloud()));\n\n  // for debug\n  //\n  // pcl::PointCloud<pcl::PointXYZINormal> normal_cloud;\n  // const int cloud_size = target_cloud_->points.cols();\n  // normal_cloud.reserve(cloud_size);\n  // for (int i = 0; i < cloud_size; ++i) {\n  //   pcl::PointXYZINormal point;\n  //   point.x = target_cloud_->points(0, i);\n  //   point.y = target_cloud_->points(1, i);\n  //   point.z = target_cloud_->points(2, i);\n  //   point.normal_x = target_cloud_->normals(0, i);\n  //   point.normal_y = target_cloud_->normals(1, i);\n  //   point.normal_z = target_cloud_->normals(2, i);\n  //   normal_cloud.push_back(point);\n  // }\n  // pcl::io::savePCDFileBinary(\"/tmp/normal.pcd\", normal_cloud);\n\n  // step2 build KDTREE for closeset point searching\n  // nns_kdtree_.reset(\n  //     NNS::create(target_cloud_->points, kDim, NNS::KDTREE_LINEAR_HEAP));\n}\n\nbool IcpFast::Align(const Eigen::Matrix4d& guess,\n                    Eigen::Matrix4d& result) {  // NOLINT\n  const int target_points_count = target_cloud_->points.cols();\n  const Eigen::Vector3d target_mean =\n      target_cloud_->points.rowwise().sum() / target_points_count;\n  Eigen::Matrix4d T_target_mean = Eigen::Matrix4d::Identity();\n  T_target_mean.block(0, 3, 3, 1) = target_mean;\n\n  target_cloud_->points.colwise() -= target_mean;\n  {\n    // REGISTER_BLOCK(\"BuildKdTree\");\n    nns_kdtree_.reset(\n        NNS::create(target_cloud_->points, kDim, NNS::KDTREE_LINEAR_HEAP));\n  }\n  EigenPointCloud init_source_cloud = *source_cloud_;\n  Eigen::Matrix4d T_target_mean_init_guess = T_target_mean.inverse() * guess;\n  init_source_cloud.ApplyTransform(T_target_mean_init_guess);\n\n  // initialise all iter status\n  Eigen::Matrix4d T_iter = Eigen::Matrix4d::Identity();\n  std::vector<Eigen::Quaterniond> rotations_iter;\n  std::vector<Eigen::Vector3d> translations_iter;\n  rotations_iter.reserve(10);\n  translations_iter.reserve(10);\n  rotations_iter.push_back(Eigen::Quaterniond::Identity());\n  translations_iter.push_back(Eigen::Vector3d::Zero());\n\n  int iterator = 0;\n  while (true) {\n    REGISTER_BLOCK(\"Iteration\");\n    // step1 Find Closest points\n    EigenPointCloud step_cloud(init_source_cloud);\n    if (this->inner_compensation_) {\n      step_cloud.ApplyMotionCompensation(T_iter);\n    } else {\n      step_cloud.ApplyTransform(T_iter);\n    }\n\n    const Matches matches(FindClosests(nns_kdtree_, step_cloud));\n\n    // step2 reject outliers (outliers with weight 0)\n    const double limit = matches.GetDistsQuantile(options_.dist_outlier_ratio);\n    const Matrix output_weights =\n        (matches.dists.array() <= limit).cast<double>();\n\n    // step3 solve point-to-plane and update result\n    CHECK_EQ(output_weights.cols(), step_cloud.points.cols());\n\n    ErrorElements error_elements(step_cloud, *target_cloud_, output_weights,\n                                 matches);\n\n    T_iter =\n        ComputePointToPlane(error_elements.reading, error_elements.reference,\n                            error_elements.weights, error_elements.matches,\n                            this->inner_compensation_) *\n        T_iter;\n\n    // step4 check convergence and jump out\n    iterator++;\n    rotations_iter.emplace_back(Eigen::Matrix3d(T_iter.block(0, 0, 3, 3)));\n    translations_iter.push_back(T_iter.block(0, 3, 3, 1));\n    if (CheckConvergence(rotations_iter, translations_iter) ||\n        iterator >= options_.max_iteration) {\n      const double average_dist =\n          error_elements.matches.dists.array().cwiseSqrt().sum() /\n          error_elements.matches.dists.cols();\n      this->final_score_ = std::exp(-average_dist);\n      break;\n    }\n  }\n\n  target_cloud_->points.colwise() += target_mean;\n  result = T_target_mean * T_iter * T_target_mean_init_guess;\n  return true;\n}\n\n}  // namespace registrator\n}  // namespace static_map\n", "meta": {"hexsha": "1f4f30b5e47928fa73b89d17b720d6be6577541e", "size": 19309, "ext": "cc", "lang": "C++", "max_stars_repo_path": "registrators/icp_fast.cc", "max_stars_repo_name": "Gatsby23/StaticMapping", "max_stars_repo_head_hexsha": "71bb3bedfb116c4ea0ad82ab0cdf146f6a9df024", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 264.0, "max_stars_repo_stars_event_min_datetime": "2019-08-08T08:39:39.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-27T09:46:42.000Z", "max_issues_repo_path": "registrators/icp_fast.cc", "max_issues_repo_name": "Gatsby23/StaticMapping", "max_issues_repo_head_hexsha": "71bb3bedfb116c4ea0ad82ab0cdf146f6a9df024", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 26.0, "max_issues_repo_issues_event_min_datetime": "2019-08-26T13:35:05.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-14T10:16:55.000Z", "max_forks_repo_path": "registrators/icp_fast.cc", "max_forks_repo_name": "Gatsby23/StaticMapping", "max_forks_repo_head_hexsha": "71bb3bedfb116c4ea0ad82ab0cdf146f6a9df024", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 62.0, "max_forks_repo_forks_event_min_datetime": "2019-08-20T17:14:14.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-16T12:18:35.000Z", "avg_line_length": 36.2270168856, "max_line_length": 80, "alphanum_fraction": 0.6478326169, "num_tokens": 4860, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6513548646660543, "lm_q2_score": 0.5078118642792044, "lm_q1q2_score": 0.33076572813339794}}
{"text": "//  (C) Copyright John Maddock 2006.\n//  Use, modification and distribution are subject to the\n//  Boost Software License, Version 1.0. (See accompanying file\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n#ifndef BOOST_MATH_TOOLS_RATIONAL_HPP\n#define BOOST_MATH_TOOLS_RATIONAL_HPP\n\n#include <boost/array.hpp>\n#include <boost/math/tools/config.hpp>\n#include <boost/mpl/int.hpp>\n\n#if BOOST_MATH_POLY_METHOD == 1\n#  define BOOST_HEADER() <BOOST_JOIN(boost/math/tools/detail/polynomial_horner1_, BOOST_MATH_MAX_POLY_ORDER).hpp>\n#  include BOOST_HEADER()\n#  undef BOOST_HEADER\n#elif BOOST_MATH_POLY_METHOD == 2\n#  define BOOST_HEADER() <BOOST_JOIN(boost/math/tools/detail/polynomial_horner2_, BOOST_MATH_MAX_POLY_ORDER).hpp>\n#  include BOOST_HEADER()\n#  undef BOOST_HEADER\n#elif BOOST_MATH_POLY_METHOD == 3\n#  define BOOST_HEADER() <BOOST_JOIN(boost/math/tools/detail/polynomial_horner3_, BOOST_MATH_MAX_POLY_ORDER).hpp>\n#  include BOOST_HEADER()\n#  undef BOOST_HEADER\n#endif\n#if BOOST_MATH_RATIONAL_METHOD == 1\n#  define BOOST_HEADER() <BOOST_JOIN(boost/math/tools/detail/rational_horner1_, BOOST_MATH_MAX_POLY_ORDER).hpp>\n#  include BOOST_HEADER()\n#  undef BOOST_HEADER\n#elif BOOST_MATH_RATIONAL_METHOD == 2\n#  define BOOST_HEADER() <BOOST_JOIN(boost/math/tools/detail/rational_horner2_, BOOST_MATH_MAX_POLY_ORDER).hpp>\n#  include BOOST_HEADER()\n#  undef BOOST_HEADER\n#elif BOOST_MATH_RATIONAL_METHOD == 3\n#  define BOOST_HEADER() <BOOST_JOIN(boost/math/tools/detail/rational_horner3_, BOOST_MATH_MAX_POLY_ORDER).hpp>\n#  include BOOST_HEADER()\n#  undef BOOST_HEADER\n#endif\nnamespace boost{ namespace math{ namespace tools{\n\n//\n// Forward declaration to keep two phase lookup happy:\n//\ntemplate <class T, class U>\nU evaluate_polynomial(const T* poly, U const& z, std::size_t count);\n\nnamespace detail{\n\ntemplate <class T, class V, class Tag>\ninline V evaluate_polynomial_c_imp(const T* a, const V& val, const Tag*)\n{\n   return evaluate_polynomial(a, val, Tag::value);\n}\n\n} // namespace detail\n\n//\n// Polynomial evaluation with runtime size.\n// This requires a for-loop which may be more expensive than\n// the loop expanded versions above:\n//\ntemplate <class T, class U>\ninline U evaluate_polynomial(const T* poly, U const& z, std::size_t count)\n{\n   BOOST_ASSERT(count > 0);\n   U sum = static_cast<U>(poly[count - 1]);\n   for(int i = static_cast<int>(count) - 2; i >= 0; --i)\n   {\n      sum *= z;\n      sum += static_cast<U>(poly[i]);\n   }\n   return sum;\n}\n//\n// Compile time sized polynomials, just inline forwarders to the\n// implementations above:\n//\ntemplate <std::size_t N, class T, class V>\ninline V evaluate_polynomial(const T(&a)[N], const V& val)\n{\n   typedef mpl::int_<N> tag_type;\n   return detail::evaluate_polynomial_c_imp(static_cast<const T*>(a), val, static_cast<tag_type const*>(0));\n}\n\ntemplate <std::size_t N, class T, class V>\ninline V evaluate_polynomial(const boost::array<T,N>& a, const V& val)\n{\n   typedef mpl::int_<N> tag_type;\n   return detail::evaluate_polynomial_c_imp(static_cast<const T*>(a.data()), val, static_cast<tag_type const*>(0));\n}\n//\n// Even polynomials are trivial: just square the argument!\n//\ntemplate <class T, class U>\ninline U evaluate_even_polynomial(const T* poly, U z, std::size_t count)\n{\n   return evaluate_polynomial(poly, z*z, count);\n}\n\ntemplate <std::size_t N, class T, class V>\ninline V evaluate_even_polynomial(const T(&a)[N], const V& z)\n{\n   return evaluate_polynomial(a, z*z);\n}\n\ntemplate <std::size_t N, class T, class V>\ninline V evaluate_even_polynomial(const boost::array<T,N>& a, const V& z)\n{\n   return evaluate_polynomial(a, z*z);\n}\n//\n// Odd polynomials come next:\n//\ntemplate <class T, class U>\ninline U evaluate_odd_polynomial(const T* poly, U z, std::size_t count)\n{\n   return poly[0] + z * evaluate_polynomial(poly+1, z*z, count-1);\n}\n\ntemplate <std::size_t N, class T, class V>\ninline V evaluate_odd_polynomial(const T(&a)[N], const V& z)\n{\n   typedef mpl::int_<N-1> tag_type;\n   return a[0] + z * detail::evaluate_polynomial_c_imp(static_cast<const T*>(a) + 1, z*z, static_cast<tag_type const*>(0));\n}\n\ntemplate <std::size_t N, class T, class V>\ninline V evaluate_odd_polynomial(const boost::array<T,N>& a, const V& z)\n{\n   typedef mpl::int_<N-1> tag_type;\n   return a[0] + z * detail::evaluate_polynomial_c_imp(static_cast<const T*>(a.data()) + 1, z*z, static_cast<tag_type const*>(0));\n}\n\ntemplate <class T, class U, class V>\nV evaluate_rational(const T* num, const U* denom, const V& z_, std::size_t count);\n\nnamespace detail{\n\ntemplate <class T, class U, class V, class Tag>\ninline V evaluate_rational_c_imp(const T* num, const U* denom, const V& z, const Tag*)\n{\n   return boost::math::tools::evaluate_rational(num, denom, z, Tag::value);\n}\n\n}\n//\n// Rational functions: numerator and denominator must be\n// equal in size.  These always have a for-loop and so may be less\n// efficient than evaluating a pair of polynomials. However, there\n// are some tricks we can use to prevent overflow that might otherwise\n// occur in polynomial evaluation, if z is large.  This is important\n// in our Lanczos code for example.\n//\ntemplate <class T, class U, class V>\nV evaluate_rational(const T* num, const U* denom, const V& z_, std::size_t count)\n{\n   V z(z_);\n   V s1, s2;\n   if(z <= 1)\n   {\n      s1 = static_cast<V>(num[count-1]);\n      s2 = static_cast<V>(denom[count-1]);\n      for(int i = (int)count - 2; i >= 0; --i)\n      {\n         s1 *= z;\n         s2 *= z;\n         s1 += num[i];\n         s2 += denom[i];\n      }\n   }\n   else\n   {\n      z = 1 / z;\n      s1 = static_cast<V>(num[0]);\n      s2 = static_cast<V>(denom[0]);\n      for(unsigned i = 1; i < count; ++i)\n      {\n         s1 *= z;\n         s2 *= z;\n         s1 += num[i];\n         s2 += denom[i];\n      }\n   }\n   return s1 / s2;\n}\n\ntemplate <std::size_t N, class T, class U, class V>\ninline V evaluate_rational(const T(&a)[N], const U(&b)[N], const V& z)\n{\n   return detail::evaluate_rational_c_imp(a, b, z, static_cast<const mpl::int_<N>*>(0));\n}\n\ntemplate <std::size_t N, class T, class U, class V>\ninline V evaluate_rational(const boost::array<T,N>& a, const boost::array<U,N>& b, const V& z)\n{\n   return detail::evaluate_rational_c_imp(a.data(), b.data(), z, static_cast<mpl::int_<N>*>(0));\n}\n\n} // namespace tools\n} // namespace math\n} // namespace boost\n\n#endif // BOOST_MATH_TOOLS_RATIONAL_HPP\n\n\n\n", "meta": {"hexsha": "81c348af5f549773ab639e1dd9c6f3e0a904783d", "size": 6361, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "vegastrike/boost/1_35/boost/math/tools/rational.hpp", "max_stars_repo_name": "Ezeer/VegaStrike_win32FR", "max_stars_repo_head_hexsha": "75891b9ccbdb95e48e15d3b4a9cd977955b97d1f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-10-04T09:40:26.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-04T09:40:26.000Z", "max_issues_repo_path": "vegastrike/boost/1_35/boost/math/tools/rational.hpp", "max_issues_repo_name": "Ezeer/VegaStrike_win32FR", "max_issues_repo_head_hexsha": "75891b9ccbdb95e48e15d3b4a9cd977955b97d1f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "vegastrike/boost/1_35/boost/math/tools/rational.hpp", "max_forks_repo_name": "Ezeer/VegaStrike_win32FR", "max_forks_repo_head_hexsha": "75891b9ccbdb95e48e15d3b4a9cd977955b97d1f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2019-05-05T22:29:55.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-03T14:18:54.000Z", "avg_line_length": 30.729468599, "max_line_length": 130, "alphanum_fraction": 0.6953309228, "num_tokens": 1773, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6513548646660542, "lm_q2_score": 0.5078118642792044, "lm_q1q2_score": 0.3307657281333979}}
{"text": "//==============================================================================\n//         Copyright 2003 - 2011 LASMEA UMR 6602 CNRS/Univ. Clermont II\n//         Copyright 2009 - 2011 LRI    UMR 8623 CNRS/Univ Paris Sud XI\n//         Copyright 2012 - 2014 MetaScale 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 BOOST_SIMD_ARITHMETIC_FUNCTIONS_SIMD_SSE_AVX_SQRT_HPP_INCLUDED\n#define BOOST_SIMD_ARITHMETIC_FUNCTIONS_SIMD_SSE_AVX_SQRT_HPP_INCLUDED\n#ifdef BOOST_SIMD_HAS_AVX_SUPPORT\n\n#include <boost/simd/arithmetic/functions/sqrt.hpp>\n#include <boost/simd/include/functions/simd/toint.hpp>\n#include <boost/simd/include/functions/simd/touint.hpp>\n#include <boost/simd/include/functions/simd/is_gez.hpp>\n#include <boost/simd/include/functions/simd/tofloat.hpp>\n#include <boost/simd/operator/functions/details/assert_utils.hpp>\n#include <boost/assert.hpp>\n#include <boost/dispatch/attributes.hpp>\n\nnamespace boost { namespace simd { namespace ext\n{\n  BOOST_DISPATCH_IMPLEMENT          ( sqrt_\n                                    , boost::simd::tag::avx_\n                                    , (A0)\n                                    , ((simd_<double_<A0>,boost::simd::tag::avx_>))\n                                    )\n  {\n    typedef A0 result_type;\n    BOOST_FORCEINLINE BOOST_SIMD_FUNCTOR_CALL(1)\n    {\n      return _mm256_sqrt_pd(a0);\n    }\n  };\n\n  BOOST_DISPATCH_IMPLEMENT          ( sqrt_\n                                    , boost::simd::tag::avx_\n                                    , (A0)\n                                    , ((simd_<single_<A0>,boost::simd::tag::avx_>))\n                                    )\n  {\n    typedef A0 result_type;\n    BOOST_FORCEINLINE BOOST_SIMD_FUNCTOR_CALL(1)\n    {\n      return _mm256_sqrt_ps(a0);\n    }\n  };\n\n  BOOST_DISPATCH_IMPLEMENT          ( sqrt_\n                                    , boost::simd::tag::avx_\n                                    , (A0)\n                                    , ((simd_<uint64_<A0>,boost::simd::tag::avx_>))\n                                    )\n  {\n    typedef A0 result_type;\n    BOOST_FORCEINLINE BOOST_SIMD_FUNCTOR_CALL(1)\n    {\n      return boost::simd::touint(boost::simd::sqrt(boost::simd::tofloat(a0)));\n    }\n  };\n\n  BOOST_DISPATCH_IMPLEMENT          ( sqrt_, boost::simd::tag::avx_\n                                    , (A0)\n                                    , ((simd_<int64_<A0>,boost::simd::tag::avx_>))\n                                    )\n  {\n    typedef A0 result_type;\n    BOOST_FORCEINLINE BOOST_SIMD_FUNCTOR_CALL(1)\n    {\n      BOOST_ASSERT_MSG(assert_all(is_gez(a0)), \"sqrt input is negative\");\n      return boost::simd::toint(boost::simd::sqrt(boost::simd::tofloat(a0)));\n    }\n  };\n} } }\n#endif\n#endif\n", "meta": {"hexsha": "97d8780cb34b6ffbbff75b4907ca9ebaf3827df6", "size": 2945, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/boost/simd/base/include/boost/simd/arithmetic/functions/simd/sse/avx/sqrt.hpp", "max_stars_repo_name": "psiha/nt2", "max_stars_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 34.0, "max_stars_repo_stars_event_min_datetime": "2017-05-19T18:10:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-04T02:18:13.000Z", "max_issues_repo_path": "modules/boost/simd/base/include/boost/simd/arithmetic/functions/simd/sse/avx/sqrt.hpp", "max_issues_repo_name": "psiha/nt2", "max_issues_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "modules/boost/simd/base/include/boost/simd/arithmetic/functions/simd/sse/avx/sqrt.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": 37.2784810127, "max_line_length": 83, "alphanum_fraction": 0.5208828523, "num_tokens": 657, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6825737473266735, "lm_q2_score": 0.48438008427698437, "lm_q1q2_score": 0.33062512925535115}}
{"text": "#include \"humanoids/humanoids.hpp\"\n#include \"humanoids/hull2d.hpp\"\n#include \"sco/expr_op_overloads.hpp\"\n#include \"sco/expr_vec_ops.hpp\"\n#include \"sco/modeling_utils.hpp\"\n#include \"osgviewer/osgviewer.hpp\"\n#include \"trajopt/common.hpp\"\n#include \"trajopt/collision_avoidance.hpp\"\n#include \"trajopt/kinematic_terms.hpp\"\n#include \"trajopt/plot_callback.hpp\"\n#include \"trajopt/problem_description.hpp\"\n#include \"trajopt/configuration_space.hpp\"\n#include \"utils/eigen_conversions.hpp\"\n#include \"utils/stl_to_string.hpp\"\n#include \"utils/vector_ops.hpp\"\n#include <boost/assign.hpp>\n#include <boost/foreach.hpp>\n#include <openrave-core.h>\n#include <openrave/openrave.h>\nusing namespace boost::assign;\nusing namespace Eigen;\nusing namespace OpenRAVE;\nusing namespace std;\nusing namespace trajopt;\nusing namespace util;\n\nbool gEnablePlot = true;\nconst float DIST_PEN=.02;\nconst float COLL_COEFF=10;\nconst float VEL_COEFF = .25;\nstring data_dir() {\n  string out = DATA_DIR;\n  return out;\n}\n\n\n/**\nimport openravepy\nenv = openravepy.Environment()\nenv.Load(\"gfe.xml\")\nrobot = env.GetRobots()[0]\nrfoot = robot.GetLink(\"r_foot\")\naabb = rfoot.ComputeLocalAABB(rfoot)\naabb.pos()+aabb.extents()\naabb.pos()-aabb.extents()\n */\nMatrixX2d GetLocalAabbPoly() {\n  MatrixX2d out(4,2);\n  out << 0.17939, 0.062707,\n      0.17939, -0.061646,\n      -0.08246, -0.061646,\n      -0.08246, 0.061646;\n  return out;\n}\nMatrixX2d local_aabb_poly = GetLocalAabbPoly();\n\nMatrixX2d GetLeftPoly(const RobotBase& gfe) {\n  OpenRAVE::Vector v = gfe.GetLink(\"l_foot\")->GetTransform().trans;\n  v.z = 0;\n  return local_aabb_poly.rowwise() + Vector2d(v.x, v.y).transpose();\n}\nMatrixX2d GetRightPoly(const RobotBase& gfe) {\n  OpenRAVE::Vector v = gfe.GetLink(\"r_foot\")->GetTransform().trans;\n  v.z = 0;\n  return local_aabb_poly.rowwise() + Vector2d(v.x, v.y).transpose();\n}\ntemplate <typename MatrixT>\nMatrixT concat0(const MatrixT& x, const MatrixT& y) {\n  MatrixT out(x.rows() + y.rows(), x.cols());\n  out.topRows(x.rows()) = x;\n  out.bottomRows(y.rows()) = y;\n  return out;\n}\ntemplate <typename MatrixT>\nvoid extend0(MatrixT& x, const MatrixT& y) {\n  x.conservativeResize(x.rows()+y.rows(), NoChange);\n  x.bottomRows(y.rows()) = y;\n}\n\nMatrixX2d GetBothPoly(const RobotBase& gfe) {\n  MatrixX2d left = GetLeftPoly(gfe);\n  MatrixX2d right = GetRightPoly(gfe);\n  MatrixX2d verts = concat0(left, right);\n  MatrixX2d hull = hull2d(verts);\n  return hull;\n}\n\n\nvoid SetLeftZMP(TrajOptProb& prob, int t) {\n  RobotAndDOFPtr rad = prob.GetRAD();\n  prob.addConstraint(ConstraintPtr(new ZMP(rad, GetLeftPoly(*rad->GetRobot()), prob.GetVarRow(t))));\n}\nvoid SetRightZMP(TrajOptProb& prob, int t) {\n  RobotAndDOFPtr rad = prob.GetRAD();\n  prob.addConstraint(ConstraintPtr(new ZMP(rad, GetRightPoly(*rad->GetRobot()), prob.GetVarRow(t))));\n}\nvoid SetBothZMP(TrajOptProb& prob, int t) {\n  RobotAndDOFPtr rad = prob.GetRAD();\n  prob.addConstraint(ConstraintPtr(new ZMP(rad, GetBothPoly(*rad->GetRobot()), prob.GetVarRow(t))));\n}\nvoid SetLinkFixed(TrajOptProb& prob, KinBody::LinkPtr link, int t, const OpenRAVE::Transform& tlink) {\n//  BoolVec allbutz(6,true);\n//  allbutz[5] = false;\n  prob.addConstraint(ConstraintPtr(new CartPoseConstraint(prob.GetVarRow(t), tlink, prob.GetRAD(), link)));\n}\nvoid SetLinkFixed(TrajOptProb& prob, KinBody::LinkPtr link, int t) {\n  OpenRAVE::Transform tlink = link->GetTransform();\n  SetLinkFixed(prob, link, t, tlink);\n}\nvoid SetStartFixed(TrajOptProb& prob) {\n  DblVec cur_dofvals = prob.GetRAD()->GetDOFValues();\n  VarArray& vars = prob.GetVars();\n  for (int j=0; j < vars.cols(); ++j) {\n    prob.addLinearConstraint(exprSub(AffExpr(vars(0,j)), cur_dofvals[j]), EQ);\n  }\n}\n\n\nTrajArray Optimize(TrajOptProbPtr prob) {\n  // optimize\n  BasicTrustRegionSQP opt(prob);\n  opt.improve_ratio_threshold_ = .1;\n//  opt.min\n  TrajArray init(prob->GetNumSteps(), prob->GetNumDOF());\n  DblVec cur_dofvals = prob->GetRAD()->GetDOFValues();\n  for (int i=0; i < prob->GetNumSteps(); ++i) init.row(i) = toVectorXd(cur_dofvals);\n  init += DblMatrix::Random(init.rows(), init.cols()) * .01;\n  opt.initialize(DblVec(init.data(), init.data()+init.rows()*init.cols()));\n  if (gEnablePlot) opt.addCallback(PlotCallback(*prob));\n  opt.optimize();\n  return getTraj(opt.x(), prob->GetVars());\n}\n\nvoid LeftRightStep(RobotBasePtr gfe, TrajArray& out) {\n  OpenRAVE::KinBody::LinkPtr lfoot = gfe->GetLink(\"l_foot\"),\n      rfoot = gfe->GetLink(\"r_foot\");\n\n  CollisionCheckerPtr cc = CollisionChecker::GetOrCreate(*gfe->GetEnv());\n  vector<Collision> collisions;\n  cc->AllVsAll(collisions);\n//  cc->IgnoreLink(lfoot);\n//  cc->IgnoreLink(rfoot);\n\n\n  // determine foot placement pose\n  // set up optimization problem\n\n  int n_steps = 5;\n  float step_dist = .3;\n\n  RobotAndDOFPtr rad(new RobotAndDOF(gfe, arange(gfe->GetDOF()), OR::DOF_Transform));\n\n  BoolVec xonly(6, false);\n  xonly[3] = true;\n\n  {\n    TrajOptProbPtr prob(new TrajOptProb(n_steps, rad));\n    SetStartFixed(*prob);\n    prob->addCost(CostPtr(new JointVelCost(prob->GetVars(), VEL_COEFF*VectorXd::Ones(rad->GetDOF()))));\n\n\n    for (int i=1; i < n_steps; ++i) {\n      prob->addCost(CostPtr(new StaticTorqueCost(rad, prob->GetVarRow(i), 1)));\n      prob->addCost(CostPtr(new PECost(rad, prob->GetVarRow(i), .01)));\n      prob->addCost(CostPtr(new CollisionCost(DIST_PEN, COLL_COEFF, rad, prob->GetVarRow(i))));\n//      prob->addConstr(ConstraintPtr(new CartPoseConstraint(prob->GetVarRow(i), Tfoottarg, rad, rfoot, xonly)));\n      SetLinkFixed(*prob, lfoot, i);\n      SetLeftZMP(*prob, i);\n    }\n    OpenRAVE::Transform Tfootnow = rfoot->GetTransform();\n    OpenRAVE::Transform Tfoottarg = Tfootnow;\n    Tfoottarg.trans.x = lfoot->GetTransform().trans.x + step_dist; // 30 cm forward\n//    if (Tfoottarg.trans.x >= -.1 && Tfoottarg.trans.x < .1) Tfoottarg.trans.z += .05;\n    SetLinkFixed(*prob, rfoot, n_steps-1, Tfoottarg);\n\n    TrajArray traj = Optimize(prob);\n    rad->SetDOFValues(toDblVec(traj.row(n_steps-1)));\n    extend0(out,traj);\n\n  }\n\n\n  {\n    TrajOptProbPtr prob(new TrajOptProb(n_steps, rad));\n    SetStartFixed(*prob);\n    prob->addCost(CostPtr(new JointVelCost(prob->GetVars(), VEL_COEFF*VectorXd::Ones(rad->GetDOF()))));\n    for (int i=1; i < n_steps; ++i) {\n      prob->addCost(CostPtr(new StaticTorqueCost(rad, prob->GetVarRow(i), 1)));\n      prob->addCost(CostPtr(new PECost(rad, prob->GetVarRow(i), .01)));\n      prob->addCost(CostPtr(new CollisionCost(DIST_PEN, COLL_COEFF, rad, prob->GetVarRow(i))));\n      SetLinkFixed(*prob, lfoot, i);\n      SetLinkFixed(*prob, rfoot, i);\n      SetBothZMP(*prob, i);\n    }\n    SetRightZMP(*prob, n_steps-1);\n\n    TrajArray traj = Optimize(prob);\n    rad->SetDOFValues(toDblVec(traj.row(n_steps-1)));\n    extend0(out,traj);\n\n  }\n\n  {\n    TrajOptProbPtr prob(new TrajOptProb(n_steps, rad));\n    SetStartFixed(*prob);\n    prob->addCost(CostPtr(new JointVelCost(prob->GetVars(), VEL_COEFF*VectorXd::Ones(rad->GetDOF()))));\n    for (int i=1; i < n_steps; ++i) {\n      prob->addCost(CostPtr(new StaticTorqueCost(rad, prob->GetVarRow(i), 1)));\n      prob->addCost(CostPtr(new PECost(rad, prob->GetVarRow(i), .01)));\n      prob->addCost(CostPtr(new CollisionCost(DIST_PEN, COLL_COEFF, rad, prob->GetVarRow(i))));\n      SetLinkFixed(*prob, rfoot, i);\n      SetRightZMP(*prob, i);\n    }\n    OpenRAVE::Transform Tfootnow = lfoot->GetTransform();\n    OpenRAVE::Transform Tfoottarg = Tfootnow;\n    Tfoottarg.trans.x = rfoot->GetTransform().trans.x + step_dist; // 30 cm forward\n    SetLinkFixed(*prob, lfoot, n_steps-1, Tfoottarg);\n\n    TrajArray traj = Optimize(prob);\n    rad->SetDOFValues(toDblVec(traj.row(n_steps-1)));\n    extend0(out,traj);\n\n  }\n\n\n  {\n    TrajOptProbPtr prob(new TrajOptProb(n_steps, rad));\n    SetStartFixed(*prob);\n    prob->addCost(CostPtr(new JointVelCost(prob->GetVars(), VEL_COEFF*VectorXd::Ones(rad->GetDOF()))));\n    for (int i=1; i < n_steps; ++i) {\n      prob->addCost(CostPtr(new StaticTorqueCost(rad, prob->GetVarRow(i), 1)));\n      prob->addCost(CostPtr(new PECost(rad, prob->GetVarRow(i), .01)));\n      prob->addCost(CostPtr(new CollisionCost(DIST_PEN, COLL_COEFF, rad, prob->GetVarRow(i))));\n      SetLinkFixed(*prob, lfoot, i);\n      SetLinkFixed(*prob, rfoot, i);\n      SetBothZMP(*prob, i);\n    }\n    SetLeftZMP(*prob, n_steps-1);\n\n    TrajArray traj = Optimize(prob);\n    rad->SetDOFValues(toDblVec(traj.row(n_steps-1)));\n    extend0(out,traj);\n\n  }\n\n}\n\nvoid AnimateTrajectory(RobotAndDOFPtr rad, TrajArray& traj, OSGViewerPtr viewer) {\n  for (int i=0; i < traj.rows(); ++i) {\n    cout << \"step \" << i << endl;\n    rad->SetDOFValues(toDblVec(traj.row(i)));\n    viewer->Idle();\n  }\n}\n\nint main(int argc, char* argv[]) {\n  RaveInitialize(false);\n  EnvironmentBasePtr env = RaveCreateEnvironment();\n  env->StopSimulation();\n  env->Load(string(getenv(\"HOME\")) + \"/Proj/darpa-proposal/drclogs.env.xml\");\n  env->Load(string(getenv(\"HOME\")) + \"/Proj/drc/gfe.xml\");\n  vector<RobotBasePtr> robots; env->GetRobots(robots);\n  RobotBasePtr gfe = robots[0];\n  OSGViewerPtr viewer(new OSGViewer(env));\n  env->AddViewer(viewer);\n\n  RobotAndDOFPtr rad(new RobotAndDOF(gfe, arange(gfe->GetDOF()), OR::DOF_Transform));\n\n\n  // translate to starting position\n  {\n    OpenRAVE::Transform T;\n    T.trans.y += 1;\n    T.trans.z = 0.92712;\n    T.trans.x -= .35;\n    gfe->SetTransform(T);\n  }\n\n\n  TrajArray traj(0, rad->GetDOF());\n  LeftRightStep(gfe, traj);\n  LeftRightStep(gfe, traj);\n  LeftRightStep(gfe, traj);\n  LeftRightStep(gfe, traj);\n  LeftRightStep(gfe, traj);\n\n//  AnimateTrajectory(rad, traj, viewer);\n\n\n\n  {\n    gfe->SetDOFValues(DblVec(gfe->GetDOF(), 0));\n    OpenRAVE::Transform T = gfe->GetTransform();\n    T.rot = OR::Vector(1,0,0,.2);\n    T.rot.normalize4();\n    T.trans = OR::Vector(2.4, 1.4, .92712);\n    gfe->SetTransform(T);\n    int n_steps = 5;\n    TrajOptProbPtr prob(new TrajOptProb(n_steps, rad));\n    SetStartFixed(*prob);\n    prob->addCost(CostPtr(new JointVelCost(prob->GetVars(), VEL_COEFF*VectorXd::Ones(rad->GetDOF()))));\n    for (int i=1; i < n_steps; ++i) {\n      SetLinkFixed(*prob, gfe->GetLink(\"l_foot\"), i);\n      SetLinkFixed(*prob, gfe->GetLink(\"r_foot\"), i);\n      SetLeftZMP(*prob, i);\n      SetRightZMP(*prob, i);\n\n//      prob->addCost(CostPtr(new StaticTorqueCost(rad, prob->GetVarRow(i), 1)));\n//      prob->addCost(CostPtr(new PECost(rad, prob->GetVarRow(i), .01)));\n//      prob->addCost(CostPtr(new CollisionCost(DIST_PEN, COLL_COEFF, rad, prob->GetVarRow(i))));\n    }\n    OpenRAVE::Transform buttonpose = env->GetKinBody(\"bigredbutton\")->GetTransform();\n    buttonpose.trans.z += .1;\n    BoolVec justposition(6, false);\n    justposition[3] = justposition[4] = justposition[5] = true;\n    prob->addConstraint(ConstraintPtr(new CartPoseConstraint(prob->GetVarRow(n_steps-1), buttonpose,\n        rad, gfe->GetLink(\"r_hand\"), justposition)));\n    TrajArray traj1 = Optimize(prob);\n    extend0(traj, traj1);\n  }\n\nAnimateTrajectory(rad, traj, viewer);\n\n  viewer->Idle();\nofstream trajfile(\"/tmp/traj.txt\");\ntrajfile << traj << endl;\n\n  RaveDestroy();\n}\n", "meta": {"hexsha": "966ee57b5e32b746d1a8e63fb96ba3c3a54a0480", "size": 10957, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/humanoids/zmp_test.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/humanoids/zmp_test.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/humanoids/zmp_test.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": 33.203030303, "max_line_length": 113, "alphanum_fraction": 0.681847221, "num_tokens": 3443, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6825737344123243, "lm_q2_score": 0.4843800842769844, "lm_q1q2_score": 0.3306251229998976}}
{"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// Overload of uBLAS prod function with MKL/GSL implementations\n#include <votca/tools/linalg.h>\n//for libxc\n#include <votca/xtp/votca_config.h>\n\n#include <votca/xtp/numerical_integrations.h>\n#include <boost/math/constants/constants.hpp>\n#include <votca/xtp/radial_euler_maclaurin_rule.h>\n#include <votca/xtp/sphere_lebedev_rule.h>\n#include <votca/xtp/aoshell.h>\n#include <votca/tools/constants.h>\n#include <numeric>\n\n#include <votca/xtp/aomatrix.h>\n#include <fstream>\n#include <boost/timer/timer.hpp>\n#include <boost/algorithm/string.hpp>\n\n#include <iterator>\n#include <string>\n\n\n\n\nnamespace votca {\n    namespace xtp {\n        namespace ub = boost::numeric::ublas;\n\n        double NumericalIntegration::getExactExchange(const string _functional){\n#ifdef LIBXC            \n        \n            double exactexchange=0.0;\n            Vxc_Functionals map;\n            std::vector<string> strs;\n            \n            boost::split(strs, _functional, boost::is_any_of(\" \"));\n            if (strs.size()>2 ) {\n                throw std::runtime_error(\"Too many functional names\");\n            }\n            else if (strs.size()<1 ) {\n                throw std::runtime_error(\"Specify at least one functional\");\n            }\n            \n            for (unsigned i=0;i<strs.size();i++){\n               \n                int func_id = map.getID(strs[i]); \n                if (func_id<0){\n                    exactexchange=0.0;\n                    break;\n                }\n                xc_func_type func;\n                if (xc_func_init(&func, func_id, XC_UNPOLARIZED) != 0) {\n                    fprintf(stderr, \"Functional '%d' not found\\n\", func_id);\n                    exit(1);\n                }\n                if (exactexchange>0 && func.cam_alpha>0){\n                    throw std::runtime_error(\"You have specified two functionals with exact exchange\");\n                }\n                exactexchange+=func.cam_alpha;\n            \n                \n            \n            }\n            return exactexchange;\n            \n#else\n            return 0.0;\n#endif\n            \n        }\n        \n        ub::matrix<double> NumericalIntegration::IntegrateExternalPotential(const std::vector<double>& Potentialvalues){\n            \n            ub::matrix<double> ExternalMat = ub::zero_matrix<double>(_basis->AOBasisSize(), _basis->AOBasisSize());\n            unsigned nthreads = 1;\n            #ifdef _OPENMP\n               nthreads = omp_get_max_threads();\n            #endif\n               std::vector<ub::matrix<double> >vex_thread;\n               std::vector<double> Exc_thread=std::vector<double>(nthreads,0.0);\n               for(unsigned i=0;i<nthreads;++i){\n                   ub::matrix<double> Vex_thread=ub::zero_matrix<double>(ExternalMat.size1());\n                   vex_thread.push_back(Vex_thread);\n               }\n               \n               \n            #pragma omp parallel for\n            for (unsigned thread=0;thread<nthreads;++thread){\n            for (unsigned i = thread_start[thread]; i < thread_stop[thread]; ++i) {\n                \n                \n                GridBox& box = _grid_boxes[i];\n                \n               \n                \n                ub::matrix<double> Vex_here=ub::zero_matrix<double>(box.Matrixsize());\n                const std::vector<tools::vec>& points=box.getGridPoints();\n                const std::vector<double>& weights=box.getGridWeights();\n                \n                ub::range one=ub::range(0,1);\n                \n                ub::matrix<double> _temp     = ub::zero_matrix<double>(1,box.Matrixsize());\n                \n                ub::matrix<double> ao=ub::matrix<double>(1,box.Matrixsize());\n                \n                \n                \n                //iterate over gridpoints\n                for(unsigned p=0;p<box.size();p++){\n                    ao=ub::zero_matrix<double>(1,box.Matrixsize());\n                    const std::vector<ub::range>& aoranges=box.getAOranges();\n                    const std::vector<const AOShell* > shells=box.getShells();\n                    for(unsigned j=0;j<box.Shellsize();++j){\n                        const AOShell* shell=shells[j];\n                        ub::matrix_range< ub::matrix<double> > aoshell=ub::project(ao,one,aoranges[j]);\n                        shell->EvalAOspace(aoshell,points[p]);\n                    }\n\n                    double weight=weights[p];\n                    ub::matrix<double> _addEX = weight*Potentialvalues[box.getIndexoffirstgridpoint()+p]*ao ;\n                    \n                    Vex_here+=ub::prod( ub::trans(_addEX), ao);\n                }\n                \n                \n                box.AddtoBigMatrix(vex_thread[thread],Vex_here);\n                \n            }\n            }   \n            for(unsigned i=0;i<nthreads;++i){\n                ExternalMat+=vex_thread[i];\n                \n               }   \n         \n         \n            \n            ExternalMat += ub::trans(ExternalMat);\n            return ExternalMat;\n\n        }\n        \n        \n        void NumericalIntegration::setXCfunctional(const string _functional){\n            \n            Vxc_Functionals map;\n            std::vector<string> strs;           \n            boost::split(strs, _functional, boost::is_any_of(\" \"));\n            xfunc_id = 0;\n            \n#ifdef LIBXC\n            _use_votca = false;\n            _use_separate = false;\n            cfunc_id = 0;\n\n            if (strs.size() == 1) {\n                xfunc_id = map.getID(strs[0]);\n                if (xfunc_id < 0) _use_votca = true;\n            }\n\n            else if (strs.size() == 2) {\n                cfunc_id = map.getID(strs[0]);\n                xfunc_id = map.getID(strs[1]);\n                _use_separate = true;\n            }\n            else {\n                cout<<\"LIBXC \"<<strs.size()<<endl;\n                throw std::runtime_error(\"With LIBXC. Please specify one combined or an exchange and a correlation functionals\");\n\n            }\n            \n            if (!_use_votca){\n            if (xc_func_init(&xfunc, xfunc_id, XC_UNPOLARIZED) != 0) {\n                fprintf(stderr, \"Functional '%d' not found\\n\", xfunc_id);\n                exit(1);\n            }\n            \n            xc_func_init(&xfunc, xfunc_id, XC_UNPOLARIZED);\n            if (xfunc.info->kind!=2 && !_use_separate){\n                throw std::runtime_error(\"Your functional misses either correlation or exchange, please specify another functional, separated by whitespace\");\n            }\n            \n            if (_use_separate) {\n                if (xc_func_init(&cfunc, cfunc_id, XC_UNPOLARIZED) != 0) {\n                    fprintf(stderr, \"Functional '%d' not found\\n\", cfunc_id);\n                    exit(1);\n                }\n                xc_func_init(&cfunc, cfunc_id, XC_UNPOLARIZED);\n                xc_func_init(&xfunc, xfunc_id, XC_UNPOLARIZED);\n                if ((xfunc.info->kind+cfunc.info->kind)!=1){\n                    throw std::runtime_error(\"Your functionals are not one exchange and one correlation\");\n                }\n            }\n            }\n#else\n         if (strs.size() == 1) {\n                xfunc_id = map.getID(strs[0]);\n            }   \n         else {\n                throw std::runtime_error(\"Running without LIBXC, Please specify one combined or an exchange and a correlation functionals\");\n         }\n#endif\n            if(_use_votca){\n                cout<<\"Warning: VOTCA_PBE does give correct Vxc but incorrect E_xc\"<<endl;\n            }\n            setXC=true;\n            return;\n        }\n\n        \n        \n        \n        void NumericalIntegration::EvaluateXC(const double rho,const ub::matrix<double>& grad_rho,double& f_xc, double& df_drho, double& df_dsigma){\n            \n                              \n #ifdef LIBXC                   \n                    if (_use_votca) {\n#endif                  \n                        _xc.getXC(xfunc_id, rho, grad_rho(0,0), grad_rho(0,1), grad_rho(0,2), f_xc, df_drho, df_dsigma);\n#ifdef LIBXC\n                    }                        // evaluate via LIBXC, if compiled, otherwise, go via own implementation\n\n                    else {\n                     \n\n                        double sigma = ub::prod(grad_rho,ub::trans(grad_rho))(0,0);\n\n                        double exc[1];\n                        double vsigma[1]; // libxc \n                        double vrho[1]; // libxc df/drho\n                        switch (xfunc.info->family) {\n                            case XC_FAMILY_LDA:\n                                xc_lda_exc_vxc(&xfunc, 1, &rho, exc, vrho);\n                                break;\n                            case XC_FAMILY_GGA:\n                            case XC_FAMILY_HYB_GGA:\n                                xc_gga_exc_vxc(&xfunc, 1, &rho, &sigma, exc, vrho, vsigma);\n                                break;\n                        }\n                        f_xc = exc[0];\n                        df_drho = vrho[0];\n                        df_dsigma = vsigma[0];\n                        if (_use_separate) {\n                            // via libxc correlation part only\n                            switch (cfunc.info->family) {\n                                case XC_FAMILY_LDA:\n                                    xc_lda_exc_vxc(&cfunc, 1, &rho, exc, vrho);\n                                    break;\n                                case XC_FAMILY_GGA:\n                                case XC_FAMILY_HYB_GGA:\n                                    xc_gga_exc_vxc(&cfunc, 1, &rho, &sigma, exc, vrho, vsigma);\n                                    break;\n                            }\n\n                            f_xc += exc[0];\n                            df_drho += vrho[0];\n                            df_dsigma += vsigma[0];\n                        }\n                    }\n#endif\n            \n            return;\n        }\n            \n        double NumericalIntegration::IntegratePotential(const vec& rvector){\n            \n            double result = 0.0;\n            assert(density_set && \"Density not calculated\");\n          \n            for (unsigned i = 0; i < _grid_boxes.size(); i++) {\n\n                const std::vector<tools::vec>& points = _grid_boxes[i].getGridPoints();\n                const std::vector<double>& weights = _grid_boxes[i].getGridWeights();\n                const std::vector<double>& densities = _grid_boxes[i].getGridDensities();\n                for (unsigned j = 0; j < points.size(); j++) {\n                    double dist = abs(points[j] - rvector);\n                    result -= weights[j] * densities[j] / dist;\n                }\n            }\n\n            return result;   \n        }\n               \n        \n        \n        \n        \n        void NumericalIntegration::SortGridpointsintoBlocks(std::vector< std::vector< GridContainers::integration_grid > >& grid){\n            const double boxsize=1;\n            \n            std::vector< std::vector< std::vector< std::vector< GridContainers::integration_grid* > > > >  boxes;\n            \n            tools::vec min=vec(std::numeric_limits<double>::max());\n            tools::vec max=vec(std::numeric_limits<double>::min());\n                   \n            for ( unsigned i = 0 ; i < grid.size(); i++){\n                for ( unsigned j = 0 ; j < grid[i].size(); j++){\n                    const tools::vec& pos= grid[i][j].grid_pos;\n                    if(pos.getX()>max.getX()){\n                        max.x()=pos.getX();\n                    }\n                    else if(pos.getX()<min.getX()){\n                        min.x()=pos.getX();\n                    }\n                    if(pos.getY()>max.getY()){\n                        max.y()=pos.getY();\n                    }\n                    else if(pos.getY()<min.getY()){\n                        min.y()=pos.getY();\n                    }\n                    if(pos.getZ()>max.getZ()){\n                        max.z()=pos.getZ();\n                    }\n                    else if(pos.getZ()<min.getZ()){\n                        min.z()=pos.getZ();\n                        }\n                    }\n                }\n            \n            vec molextension=(max-min);\n            vec numberofboxes=molextension/boxsize;\n            vec roundednumofbox=vec(std::ceil(numberofboxes.getX()),std::ceil(numberofboxes.getY()),std::ceil(numberofboxes.getZ()));\n\n            \n            //creating temparray\n            for (unsigned i=0;i<unsigned(roundednumofbox.getX());i++){\n                std::vector< std::vector< std::vector< GridContainers::integration_grid* > > > boxes_yz;\n                for (unsigned j=0;j<unsigned(roundednumofbox.getY());j++){\n                    std::vector< std::vector< GridContainers::integration_grid* > >  boxes_z;\n                    for (unsigned k=0;k<unsigned(roundednumofbox.getZ());k++){\n                        std::vector< GridContainers::integration_grid* >  box;\n                        box.reserve(100);\n                        boxes_z.push_back(box);\n                    }\n                    boxes_yz.push_back(boxes_z);\n            }\n                boxes.push_back(boxes_yz);\n            }\n            \n             for ( auto & atomgrid : grid){\n                for ( auto & gridpoint : atomgrid){\n                    tools::vec pos= gridpoint.grid_pos-min;\n                    tools::vec index=pos/boxsize;\n                    int i_x=int(index.getX());\n                    int i_y=int(index.getY());\n                    int i_z=int(index.getZ());\n                    boxes[i_x][i_y][i_z].push_back(&gridpoint);\n                }\n             }\n            \n            for ( auto& boxes_xy : boxes){\n                for( auto& boxes_z : boxes_xy){\n                    for ( auto& box : boxes_z){      \n                        if( box.size()<1){\n                            continue;\n                        }\n                        GridBox gridbox;\n                        \n                        for(const auto&point:box){\n                            gridbox.addGridPoint(*point);\n                        }\n                        _grid_boxes.push_back(gridbox);\n                    }\n                }\n            }\n            \n            return;\n        }\n        \n        \n        void NumericalIntegration::FindSignificantShells(){\n\n            for (unsigned i=0;i<_grid_boxes.size();++i){\n                GridBox & box=_grid_boxes[i];\n                for (AOBasis::AOShellIterator _row = _basis->firstShell(); _row != _basis->lastShell(); _row++) {\n                      AOShell* _store=(*_row);\n                      const double decay=(*_row)->getMinDecay();\n                      const tools::vec& shellpos=(*_row)->getPos();\n                      \n                      for(const auto& point : box.getGridPoints()){\n                          tools::vec dist=shellpos-point;\n                          double distsq=dist*dist;\n                          // if contribution is smaller than -ln(1e-10), add atom to list\n                        if ( (decay * distsq) < 20.7 ){\n                            box.addShell(_store);\n                            break;\n                        }\n                      }\n                }\n                //cout<<box.significant_shells.size()<<\" \"<<box.grid_pos.size()<<endl;\n            }\n            \n             std::vector< GridBox > _grid_boxes_copy;\n            \n            int combined=0;\n            std::vector<bool> Compared=std::vector<bool>(_grid_boxes.size(),false);\n            for (unsigned i=0;i<_grid_boxes.size();i++){\n                if(Compared[i]){continue;}\n                GridBox box=_grid_boxes[i];\n                if(box.Shellsize()<1){continue;}\n                Compared[i]=true;\n                for (unsigned j=i+1;j<_grid_boxes.size();j++){                   \n                    if(GridBox::compareGridboxes(_grid_boxes[i],_grid_boxes[j])){\n                        Compared[j]=true;\n                        box.addGridBox(_grid_boxes[j]);\n                        combined++;\n                    }\n                    \n                }\n                _grid_boxes_copy.push_back(box);\n            }\n\n         \n            \n            \n            std::vector<unsigned> sizes;\n            sizes.reserve(_grid_boxes_copy.size());\n            for(auto& box: _grid_boxes_copy){\n                sizes.push_back(box.size()*box.Matrixsize());\n            }\n           \n            \n            std::vector<unsigned> indexes=std::vector<unsigned>(sizes.size());\n            std::iota(indexes.begin(), indexes.end(), 0);\n            std::sort(indexes.begin(), indexes.end(),[&sizes](unsigned i1, unsigned i2) {return sizes[i1] > sizes[i2];});\n            \n             unsigned nthreads = 1;\n            #ifdef _OPENMP\n               nthreads = omp_get_max_threads();\n            #endif\n            \n            std::vector<unsigned> scores=std::vector<unsigned>(nthreads,0);\n            std::vector< std::vector<unsigned> > indices;\n            for (unsigned i=0;i<nthreads;++i){\n                std::vector<unsigned> thread_box_indices;\n                indices.push_back(thread_box_indices);\n            }\n        \n            \n            for(const auto index:indexes){\n                unsigned thread=0;\n                unsigned minimum= std::numeric_limits<unsigned>::max();\n                for(unsigned i=0;i<scores.size();++i){\n                    if(scores[i]<minimum){\n                        minimum=scores[i];\n                        thread=i;\n                    }\n                }\n                indices[thread].push_back(index);\n                scores[thread]+=sizes[index];   \n            }           \n            \n            thread_start=std::vector<unsigned>(0);\n            thread_stop=std::vector<unsigned>(0);\n            unsigned start=0;\n            unsigned stop=0;\n            unsigned indexoffirstgridpoint=0;\n             _grid_boxes.resize(0);\n            for (const std::vector<unsigned>& thread_index:indices){\n                thread_start.push_back(start);\n                stop=start+thread_index.size();\n                thread_stop.push_back(stop);\n                start=stop;\n                for(const unsigned index:thread_index){        \n                        GridBox newbox=_grid_boxes_copy[index];\n                        newbox.setIndexoffirstgridpoint(indexoffirstgridpoint);\n                        indexoffirstgridpoint+=newbox.size();\n                        newbox.PrepareForIntegration();\n                        _grid_boxes.push_back(newbox);                 \n                }\n            }   \n            return;\n        }\n        \n        \n        \n        \n        ub::matrix<double> NumericalIntegration::IntegrateVXC(const ub::matrix<double>& _density_matrix){\n            ub::matrix<double> Vxc=ub::zero_matrix<double>(_density_matrix.size1());\n            EXC = 0;\n            \n            unsigned nthreads = 1;\n            #ifdef _OPENMP\n               nthreads = omp_get_max_threads();\n            #endif\n               std::vector<ub::matrix<double> >vxc_thread;\n               std::vector<double> Exc_thread=std::vector<double>(nthreads,0.0);\n               for(unsigned i=0;i<nthreads;++i){\n                   ub::matrix<double> Vxc_thread=ub::zero_matrix<double>(_density_matrix.size1());\n                   vxc_thread.push_back(Vxc_thread);\n               }\n               \n               \n            #pragma omp parallel for\n             for (unsigned thread=0;thread<nthreads;++thread){\n                for (unsigned i = thread_start[thread]; i < thread_stop[thread]; ++i) {\n                \n                double EXC_box=0.0;\n                GridBox& box = _grid_boxes[i];\n               \n                const ub::matrix<double>  DMAT_here=box.ReadFromBigMatrix(_density_matrix);\n                \n                ub::matrix<double> Vxc_here=ub::zero_matrix<double>(DMAT_here.size1());\n                const std::vector<tools::vec>& points=box.getGridPoints();\n                const std::vector<double>& weights=box.getGridWeights();\n                \n                ub::range one=ub::range(0,1);\n                ub::range three=ub::range(0,3);\n                ub::matrix<double> _temp     = ub::matrix<double>(1,box.Matrixsize());\n                ub::matrix<double> _tempgrad = ub::matrix<double>(3,box.Matrixsize());\n                ub::matrix<double> ao=ub::matrix<double>(1,box.Matrixsize());\n                ub::matrix<double> ao_grad=ub::matrix<double>(3,box.Matrixsize());\n               \n                //iterate over gridpoints\n                for(unsigned p=0;p<box.size();p++){\n                    ao=ub::zero_matrix<double>(1,box.Matrixsize());\n                    ao_grad=ub::zero_matrix<double>(3,box.Matrixsize());\n                    const std::vector<ub::range>& aoranges=box.getAOranges();\n                    const std::vector<const AOShell* >& shells=box.getShells();\n                   \n                    for(unsigned j=0;j<box.Shellsize();++j){\n                        \n                        ub::matrix_range< ub::matrix<double> > aoshell=ub::project(ao,one,aoranges[j]);\n                        ub::matrix_range< ub::matrix<double> > ao_grad_shell=ub::project(ao_grad,three,aoranges[j]);\n                        shells[j]->EvalAOspace(aoshell,ao_grad_shell,points[p]);\n                       \n                    }\n                    \n                    _temp=ub::prod( ao, DMAT_here);\n                   \n                    _tempgrad=ub::prod(ao_grad,DMAT_here);\n                    \n                    double rho=ub::prod(_temp, ub::trans( ao) )(0,0);\n                    \n                    ub::matrix<double> rho_grad=ub::prod(_temp, ub::trans(ao_grad))+ub::prod(ao,ub::trans(_tempgrad));\n                   \n\t\t    if ( rho < 1.e-15 ) continue; // skip the rest, if density is very small\n                    \n                    double f_xc;      // E_xc[n] = int{n(r)*eps_xc[n(r)] d3r} = int{ f_xc(r) d3r }\n                    double df_drho;   // v_xc_rho(r) = df/drho\n                    double df_dsigma; // df/dsigma ( df/dgrad(rho) = df/dsigma * dsigma/dgrad(rho) = df/dsigma * 2*grad(rho))\n                    EvaluateXC( rho,rho_grad,f_xc, df_drho, df_dsigma);\n                    \n                    double weight=weights[p];\n                    ub::matrix<double> _addXC = weight * df_drho * ao *0.5;\n                    \n                    _addXC+=  2.0*df_dsigma * weight * ub::prod(rho_grad,ao_grad);\n\n                    // Exchange correlation energy\n                    EXC_box += weight  * rho * f_xc;\n                  \n                    Vxc_here+=ub::prod( ub::trans(_addXC), ao);\n                  \n                }\n                \n                box.AddtoBigMatrix(vxc_thread[thread],Vxc_here);\n              \n                Exc_thread[thread]+=EXC_box;\n                \n            }\n                \n            }   \n            for(unsigned i=0;i<nthreads;++i){\n                Vxc+=vxc_thread[i];\n                EXC+=Exc_thread[i];\n               }   \n            Vxc+=ub::trans(Vxc);\n            \n            return Vxc;\n        }\n        \n        double NumericalIntegration::IntegrateDensity(const ub::matrix<double>& _density_matrix){\n            \n            double N = 0;\n            \n            unsigned nthreads = 1;\n            #ifdef _OPENMP\n               nthreads = omp_get_max_threads();\n            #endif\n               \n               std::vector<double> N_thread=std::vector<double>(nthreads,0.0);\n               \n               \n               \n            #pragma omp parallel for\n            for (unsigned thread=0;thread<nthreads;++thread){\n             for (unsigned i = thread_start[thread]; i < thread_stop[thread]; ++i) {\n                \n                double N_box=0.0;\n                GridBox& box = _grid_boxes[i];\n                \n                \n                const ub::matrix<double>  DMAT_here=box.ReadFromBigMatrix(_density_matrix);\n                \n                ub::matrix<double> Vxc_here=ub::zero_matrix<double>(DMAT_here.size1());\n                const std::vector<tools::vec>& points=box.getGridPoints();\n                const std::vector<double>& weights=box.getGridWeights();\n                \n                ub::range one=ub::range(0,1);\n                \n                ub::matrix<double> _temp     = ub::zero_matrix<double>(1,box.Matrixsize());\n               \n                ub::matrix<double> ao=ub::matrix<double>(1,box.Matrixsize());\n                \n                box.prepareDensity();\n                \n                //iterate over gridpoints\n                for(unsigned p=0;p<box.size();p++){\n                    ao=ub::zero_matrix<double>(1,box.Matrixsize());\n                   \n                    const std::vector<ub::range>& aoranges=box.getAOranges();\n                    const std::vector<const AOShell* > shells=box.getShells();\n                    for(unsigned j=0;j<box.Shellsize();++j){\n                        const AOShell* shell=shells[j];\n                        ub::matrix_range< ub::matrix<double> > aoshell=ub::project(ao,one,aoranges[j]);\n                        \n                        shell->EvalAOspace(aoshell,points[p]);\n                    }\n                    \n                    _temp=ub::prod( ao, DMAT_here);\n                   \n                    \n                    \n                    double rho=ub::prod(_temp, ub::trans( ao) )(0,0);\n                    box.addDensity(rho);\n                    N_box+=rho*weights[p];\n                    \n                }\n\n                N_thread[thread]+=N_box;\n                \n            }\n            }   \n            for(unsigned i=0;i<nthreads;++i){\n                N+=N_thread[i];\n               }   \n            density_set=true;\n            return N;\n        }\n        \n        \n ub::vector<double> NumericalIntegration::IntegrateGyrationTensor(const ub::matrix<double>& _density_matrix){\n            \n            double N = 0;\n            double centroid_x = 0.0;\n            double centroid_y = 0.0;\n            double centroid_z = 0.0;\n            double gyration_xx = 0.0;\n            double gyration_xy = 0.0;\n            double gyration_xz = 0.0;\n            double gyration_yy = 0.0;\n            double gyration_yz = 0.0;\n            double gyration_zz = 0.0;\n            ub::vector<double> result=ub::zero_vector<double>(10);\n            \n            unsigned nthreads = 1;\n            #ifdef _OPENMP\n               nthreads = omp_get_max_threads();\n            #endif\n               \n               std::vector<double> N_thread=std::vector<double>(nthreads,0.0);\n\n               // centroid\n\t       std::vector<double> centroid_x_thread=std::vector<double>(nthreads,0.0);\n\t       std::vector<double> centroid_y_thread=std::vector<double>(nthreads,0.0);\n\t       std::vector<double> centroid_z_thread=std::vector<double>(nthreads,0.0);\n\n\t       // gyration tensor\n\t       std::vector<double> gyration_xx_thread=std::vector<double>(nthreads,0.0);\n\t       std::vector<double> gyration_xy_thread=std::vector<double>(nthreads,0.0);\n\t       std::vector<double> gyration_xz_thread=std::vector<double>(nthreads,0.0);\n\t       std::vector<double> gyration_yy_thread=std::vector<double>(nthreads,0.0);\n\t       std::vector<double> gyration_yz_thread=std::vector<double>(nthreads,0.0);\n\t       std::vector<double> gyration_zz_thread=std::vector<double>(nthreads,0.0);\n               \n               \n            #pragma omp parallel for\n            for (unsigned thread=0;thread<nthreads;++thread){\n             for (unsigned i = thread_start[thread]; i < thread_stop[thread]; ++i) {\n                \n                double N_box=0.0;\n                double centroid_x_box=0.0;\n                double centroid_y_box=0.0;\n                double centroid_z_box=0.0;\n                double gyration_xx_box=0.0;\n                double gyration_xy_box=0.0;\n                double gyration_xz_box=0.0;\n                double gyration_yy_box=0.0;\n                double gyration_yz_box=0.0;\n                double gyration_zz_box=0.0;\n                \n                GridBox& box = _grid_boxes[i];\n                \n                \n                const ub::matrix<double>  DMAT_here=box.ReadFromBigMatrix(_density_matrix);\n                \n                const std::vector<tools::vec>& points=box.getGridPoints();\n                const std::vector<double>& weights=box.getGridWeights();\n                \n                ub::range one=ub::range(0,1);\n                \n                ub::matrix<double> _temp     = ub::zero_matrix<double>(1,box.Matrixsize());\n               \n                ub::matrix<double> ao=ub::matrix<double>(1,box.Matrixsize());\n                \n                box.prepareDensity();\n                \n                //iterate over gridpoints\n                for(unsigned p=0;p<box.size();p++){\n                    ao=ub::zero_matrix<double>(1,box.Matrixsize());\n                   \n                    const std::vector<ub::range>& aoranges=box.getAOranges();\n                    const std::vector<const AOShell* > shells=box.getShells();\n                    for(unsigned j=0;j<box.Shellsize();++j){\n                        const AOShell* shell=shells[j];\n                        ub::matrix_range< ub::matrix<double> > aoshell=ub::project(ao,one,aoranges[j]);\n                        \n                        shell->EvalAOspace(aoshell,points[p]);\n                    }\n                    \n                    _temp=ub::prod( ao, DMAT_here);\n                   \n                    \n                    \n                    double rho=ub::prod(_temp, ub::trans( ao) )(0,0);\n                    box.addDensity(rho);\n                    N_box+=rho*weights[p];\n                    centroid_x_box+=rho*weights[p]* points[p].getX();\n                    centroid_y_box+=rho*weights[p]* points[p].getY();\n                    centroid_z_box+=rho*weights[p]* points[p].getZ();\n                    gyration_xx_box+=rho*weights[p]* points[p].getX()*points[p].getX();\n                    gyration_xy_box+=rho*weights[p]* points[p].getX()*points[p].getY();\n                    gyration_xz_box+=rho*weights[p]* points[p].getX()*points[p].getZ();\n                    gyration_yy_box+=rho*weights[p]* points[p].getY()*points[p].getY();\n                    gyration_yz_box+=rho*weights[p]* points[p].getY()*points[p].getZ();\n                    gyration_zz_box+=rho*weights[p]* points[p].getZ()*points[p].getZ();\n                    \n                }\n\n                N_thread[thread]+=N_box;\n                centroid_x_thread[thread] += centroid_x_box;\n                centroid_y_thread[thread] += centroid_y_box;\n                centroid_z_thread[thread] += centroid_z_box;\n                gyration_xx_thread[thread] += gyration_xx_box;\n                gyration_xy_thread[thread] += gyration_xy_box;\n                gyration_xz_thread[thread] += gyration_xz_box;\n                gyration_yy_thread[thread] += gyration_yy_box;\n                gyration_yz_thread[thread] += gyration_yz_box;\n                gyration_zz_thread[thread] += gyration_zz_box;\n                \n            }\n            }   \n            for(unsigned i=0;i<nthreads;++i){\n                N+=N_thread[i];\n                centroid_x += centroid_x_thread[i];\n                centroid_y += centroid_y_thread[i];\n                centroid_z += centroid_z_thread[i];\n                gyration_xx += gyration_xx_thread[i];\n                gyration_xy += gyration_xy_thread[i];\n                gyration_xz += gyration_xz_thread[i];\n                gyration_yy += gyration_yy_thread[i];\n                gyration_yz += gyration_yz_thread[i];\n                gyration_zz += gyration_zz_thread[i];\n               }   \n            density_set=true;\n\n            // Normalize\n\t    centroid_x = centroid_x/N;\n\t    centroid_y = centroid_y/N;\n\t    centroid_z = centroid_z/N;\n\n            gyration_xx = gyration_xx/N;\n\t    gyration_xy = gyration_xy/N;\n\t    gyration_xz = gyration_xz/N;\n\t    gyration_yy = gyration_yy/N;\n\t    gyration_yz = gyration_yz/N;\n\t    gyration_zz = gyration_zz/N;\n\n\t      // Copy all elements to result vector\n\t      result(0) = N;\n\t      result(1) = centroid_x;\n\t      result(2) = centroid_y;\n\t      result(3) = centroid_z;\n\t      result(4) = gyration_xx - centroid_x*centroid_x;\n\t      result(5) = gyration_xy - centroid_x*centroid_y;\n\t      result(6) = gyration_xz - centroid_x*centroid_z;\n\t      result(7) = gyration_yy - centroid_y*centroid_y;\n\t      result(8) = gyration_yz - centroid_y*centroid_z;\n\t      result(9) = gyration_zz - centroid_z*centroid_z;\n            \n\n            return result;\n        }\n        \n  \n        \n        \n        std::vector<const vec *> NumericalIntegration::getGridpoints(){\n            \n            std::vector<const vec *> gridpoints;\n            \n            \n            for ( unsigned i = 0 ; i < _grid_boxes.size(); i++){\n                const std::vector<tools::vec>& points=_grid_boxes[i].getGridPoints();\n                for ( unsigned j = 0 ; j < points.size(); j++){\n                    gridpoints.push_back(&points[j]);\n                   \n               }\n                }\n            return gridpoints;\n        }\n        \n        \n               \n        void NumericalIntegration::GridSetup(string type, BasisSet* bs, vector<ctp::QMAtom*> _atoms,AOBasis* basis) {\n            _basis=basis;\n            std::vector< std::vector< GridContainers::integration_grid > > grid;\n            const double pi = boost::math::constants::pi<double>();\n            // get GridContainer\n            GridContainers initialgrids;\n\n            // get radial grid per element\n            EulerMaclaurinGrid _radialgrid;\n            _radialgrid.getRadialGrid(bs, _atoms, type, initialgrids); // this checks out 1:1 with NWChem results! AWESOME\n\n     \n           map<string, GridContainers::radial_grid>::iterator it;\n\n            LebedevGrid _sphericalgrid;\n         \n            for (it = initialgrids._radial_grids.begin(); it != initialgrids._radial_grids.end(); ++it) {\n               _sphericalgrid.getSphericalGrid(_atoms, type, initialgrids);\n       \n            }\n\n            \n            // for the partitioning, we need all inter-center distances later, stored in one-directional list\n            int ij = 0;\n            Rij.push_back(0.0); // 1st center \"self-distance\"\n            \n            vector< ctp::QMAtom* > ::iterator ait;\n            vector< ctp::QMAtom* > ::iterator bit;\n            int i = 1;\n            for (ait = _atoms.begin() + 1; ait != _atoms.end(); ++ait) {\n                // get center coordinates in Bohr\n                vec pos_a = (*ait)->getPos() * tools::conv::ang2bohr;\n                \n                int j = 0;\n                for (bit = _atoms.begin(); bit != ait; ++bit) {\n                    ij++;\n                    // get center coordinates in Bohr\n                    vec pos_b = (*bit)->getPos() * tools::conv::ang2bohr;\n                   \n                    Rij.push_back(1.0 / abs(pos_a-pos_b));\n                                        \n                    j++;\n                } // atoms\n                Rij.push_back(0.0); // self-distance again\n                i++;\n            } // atoms\n            \n            \n\n            int i_atom = 0;\n            _totalgridsize = 0;\n            for (ait = _atoms.begin(); ait < _atoms.end(); ++ait) {\n                // get center coordinates in Bohr\n                std::vector< GridContainers::integration_grid > _atomgrid;\n                const vec atomA_pos =(*ait)->getPos() * tools::conv::ang2bohr;\n             \n                string name = (*ait)->type;\n                \n                // get radial grid information for this atom type\n                GridContainers::radial_grid _radial_grid = initialgrids._radial_grids.at(name);\n\n                \n                // get spherical grid information for this atom type\n                GridContainers::spherical_grid _spherical_grid = initialgrids._spherical_grids.at(name);\n\n                // maximum order (= number of points) in spherical integration grid\n                int maxorder = _sphericalgrid.Type2MaxOrder(name,type);\n                int maxindex = _sphericalgrid.getIndexFromOrder(maxorder);\n\n                // for pruning of integration grid, get interval boundaries for this element\n                std::vector<double> PruningIntervals = _radialgrid.getPruningIntervals( name );\n              //  cout << \" Pruning Intervals: \" << PruningIntervals[0] << \" \" << PruningIntervals[1] << \" \" << PruningIntervals[2] << \" \" << PruningIntervals[3] << endl;\n                \n                int current_order = 0;\n                // get spherical grid\n                std::vector<double> _theta;\n                std::vector<double> _phi;\n                std::vector<double> _weight;\n                \n                // for each radial value\n                for (unsigned _i_rad = 0; _i_rad < _radial_grid.radius.size(); _i_rad++) {\n                    double r = _radial_grid.radius[_i_rad];\n                    int order;\n                    // which Lebedev order for this point?\n                    if ( maxindex == 1 ) {\n                        // smallest possible grid anyway, nothing to do\n                        order = maxorder;\n                    } else if ( maxindex == 2 ) {\n                        // only three intervals\n                        if ( r < PruningIntervals[0] ) {\n                            order = _sphericalgrid.getOrderFromIndex(1);//1;\n                        } else if ( ( r >= PruningIntervals[0] ) && ( r < PruningIntervals[3] )   ){\n                            order = _sphericalgrid.getOrderFromIndex(2);\n                        } else {\n                            order = _sphericalgrid.getOrderFromIndex(1);\n                        } // maxorder == 2\n                    } else {\n                        // five intervals\n                        if ( r < PruningIntervals[0] ) {\n                            order = _sphericalgrid.getOrderFromIndex(int(2));\n                        } else if ( ( r >= PruningIntervals[0]) && ( r < PruningIntervals[1] ) ) {\n                            order = _sphericalgrid.getOrderFromIndex(4);\n                        } else if ( ( r >= PruningIntervals[1]) && ( r < PruningIntervals[2] ) ) {\n                            order = _sphericalgrid.getOrderFromIndex(max(maxindex-1, 4));\n                        } else if ( (r >= PruningIntervals[2]) && ( r < PruningIntervals[3] ) ) {\n                            order = maxorder;\n                        } else {\n                            order = _sphericalgrid.getOrderFromIndex(max(maxindex-1,1));\n                        }\n                    }                        \n\n\n                    \n                    // get new spherical grid, if order changed\n                    if ( order != current_order ){\n                        _theta.clear();\n                        _phi.clear();\n                        _weight.clear();\n                        \n                        _sphericalgrid.getUnitSphereGrid(order,_theta,_phi,_weight);\n                        current_order = order;\n                    }\n                    \n                  \n\n                    for (unsigned _i_sph = 0; _i_sph < _phi.size(); _i_sph++) {\n\n                        double p   = _phi[_i_sph] * pi / 180.0; // back to rad\n                        double t   = _theta[_i_sph] * pi / 180.0; // back to rad\n                        double ws  = _weight[_i_sph];\n\n                        const vec s = vec(sin(p) * cos(t), sin(p) * sin(t),cos(p));\n                     \n\n\n                        GridContainers::integration_grid _gridpoint;\n                        _gridpoint.grid_pos = atomA_pos+r*s;\n\n                        _gridpoint.grid_weight = _radial_grid.weight[_i_rad] * ws;\n\n                        _atomgrid.push_back(_gridpoint);\n\n\n                    } // spherical gridpoints\n                } // radial gridpoint\n                \n\n                // get all distances from grid points to centers\n                std::vector< std::vector<double> > rq;\n                // for each center\n                for (bit = _atoms.begin(); bit < _atoms.end(); ++bit) {\n                    // get center coordinates\n                   const vec atom_pos = (*bit)->getPos() * tools::conv::ang2bohr;\n\n\n                    std::vector<double> temp;\n                    // for each gridpoint\n                    for (std::vector<GridContainers::integration_grid >::iterator git = _atomgrid.begin(); git != _atomgrid.end(); ++git) {\n\n                        temp.push_back(abs(git->grid_pos-atom_pos));\n\n                    } // gridpoint of _atomgrid\n                    rq.push_back(temp); \n\n                } // centers\n                // cout << \" Calculated all gridpoint distances to centers for \" << i_atom << endl;\n                \n                // find nearest-neighbor of this atom\n                double distNN = 1e10;\n\n                vector< ctp::QMAtom* > ::iterator NNit;\n                //int i_NN;\n               \n                // now check all other centers\n                int i_b =0;\n                for (bit = _atoms.begin(); bit != _atoms.end(); ++bit) {\n\n                    if (bit != ait) {\n                        // get center coordinates\n                       \n                        const vec atomB_pos=(*bit)->getPos() * tools::conv::ang2bohr;\n                        double distSQ = (atomA_pos-atomB_pos)*(atomA_pos-atomB_pos);\n\n                        // update NN distance and iterator\n                        if ( distSQ < distNN ) {\n                            distNN = distSQ;\n                            NNit = bit;\n                           \n                        }\n\n                    } // if ( ait != bit) \n                    i_b++;\n                }// bit centers\n                \n                for ( unsigned i_grid = 0; i_grid < _atomgrid.size() ; i_grid++){\n                    // call some shit called grid_ssw0 in NWChem\n                    std::vector<double> _p = SSWpartition( i_grid, _atoms.size(),rq);\n                 \n                    // check weight sum\n                    double wsum = 0.0;\n                    for (unsigned i =0 ; i < _p.size(); i++ ){\n                        wsum += _p[i];\n                    }\n                    //cout << \" sum of partition weights \" << wsum << endl;\n                    if ( wsum != 0.0 ){\n                        \n                        // update the weight of this grid point\n                        _atomgrid[i_grid].grid_weight = _atomgrid[i_grid].grid_weight * _p[i_atom]/wsum;\n                        //cout << \" adjusting gridpoint weight \"  << endl;\n                    } else {\n                        \n                       cerr << \"\\nSum of partition weights of grid point \" << i_grid << \" of atom \" << i_atom << \" is zero! \";\n                       throw std::runtime_error(\"\\nThis should never happen!\"); \n                        \n                    }\n                    \n\n                } // partition weight for each gridpoint\n               \n                // now remove points from the grid with negligible weights\n                \n                for (std::vector<GridContainers::integration_grid >::iterator git = _atomgrid.begin(); git != _atomgrid.end();) {\n                    if (git->grid_weight < 1e-13 ) {\n                        git = _atomgrid.erase(git);\n                    } else {\n                        ++git;\n                    }\n                }\n                \n                _totalgridsize += _atomgrid.size() ;\n\n                grid.push_back(_atomgrid);\n                \n                i_atom++;\n                \n            } // atoms\n            \n            SortGridpointsintoBlocks(grid);\n            FindSignificantShells();\n            return;\n        }\n    \n        std::vector<double> NumericalIntegration::SSWpartition(int igrid, int ncenters, std::vector< std::vector<double> >& rq){\n            const double ass = 0.725;\n            // initialize partition vector to 1.0\n            std::vector<double> p(ncenters,1.0);\n            \n            const double tol_scr = 1e-10;\n            const double leps    = 1e-6; \n            // go through centers\n            for ( int i = 1; i < ncenters; i++ ){\n                \n                int ij = i*(i+1)/2 -1; // indexing magic\n                double rag = rq[i][igrid] ;\n                \n                // through all other centers (one-directional)\n                for (int j = 0; j < i; j++ ){\n                    \n                    ij++;\n                    if ( ( std::abs(p[i]) > tol_scr  ) || ( std::abs(p[j]) > tol_scr  ) ){\n                        \n                      \n                        \n                        double mu = ( rag - rq[j][igrid] )*Rij[ij]; \n                        if ( mu > ass ) {\n                            p[i] = 0.0;\n                        } else if ( mu < -ass ) {\n                            p[j] = 0.0;\n                        } else {\n                            \n                            double sk;\n                            if (std::abs(mu) < leps ) {\n                                sk = -1.88603178008*mu + 0.5;\n                            } else {\n                                sk = erf1c(mu); \n                            }\n                            if ( mu > 0.0 ) sk = 1.0 - sk;\n                            p[j] = p[j] * sk;\n                            p[i] = p[i] * (1.0-sk);\n                                                \n                        }   \n                    }  \n                }\n\n            }\n            \n            return p;\n        }\n\n        double NumericalIntegration::erf1c(double x){\n             \n            const static double alpha_erf1=1.0/0.30;\n            return 0.5*erfcc((x/(1.0-x*x))*alpha_erf1);              \n        }\n              \n        double NumericalIntegration::erfcc(double x){\n            \n            double tau = 1.0/(1.0+0.5*std::abs(x));\n            \n            return tau*exp(-x*x-1.26551223 + 1.00002368*tau + 0.37409196*tau*tau \n            + 0.09678418*pow(tau,3) - 0.18628806*pow(tau,4) + 0.27886807*pow(tau,5) \n            -1.13520398*pow(tau,6) + 1.48851587*pow(tau,7)  -0.82215223*pow(tau,8) \n            + 0.17087277*pow(tau,9));   \n        }\n                                                                                                \n    }\n}\n", "meta": {"hexsha": "3b38d0b13e2e52dc1fbcaa9eb717cfae3b4f588d", "size": 47099, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/libxtp/numerical_integration/numerical_integrations.cc", "max_stars_repo_name": "choudarykvsp/xtp", "max_stars_repo_head_hexsha": "9a249fd34615abcf790d5f0ecd3ddf1ed0ac0e7a", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-03-05T17:36:53.000Z", "max_stars_repo_stars_event_max_datetime": "2018-03-05T17:36:53.000Z", "max_issues_repo_path": "src/libxtp/numerical_integration/numerical_integrations.cc", "max_issues_repo_name": "choudarykvsp/xtp", "max_issues_repo_head_hexsha": "9a249fd34615abcf790d5f0ecd3ddf1ed0ac0e7a", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/libxtp/numerical_integration/numerical_integrations.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": 41.3511852502, "max_line_length": 170, "alphanum_fraction": 0.4528970891, "num_tokens": 9971, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6825737214979745, "lm_q2_score": 0.48438008427698437, "lm_q1q2_score": 0.3306251167444437}}
{"text": "OBSOLETE\r\n\r\n// Boost.Geometry (aka GGL, Generic Geometry Library)\r\n//\r\n// Copyright (c) 2007-2012 Barend Gehrels, Amsterdam, the Netherlands.\r\n// Copyright (c) 2008-2012 Bruno Lalande, Paris, France.\r\n// 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// Doxygen Examples, referred to from the sources\r\n\r\n#include <boost/tuple/tuple.hpp>\r\n\r\n#if defined(_MSC_VER)\r\n// We deliberately mix float/double's here so turn off warning\r\n#pragma warning( disable : 4244 )\r\n#endif // defined(_MSC_VER)\r\n\r\n#include <boost/geometry/geometry.hpp>\r\n#include <boost/geometry/geometries/register/point.hpp>\r\n#include <boost/geometry/geometries/geometries.hpp>\r\n\r\n#include <boost/geometry/io/wkt/wkt.hpp>\r\n\r\n// All functions below are referred to in the documentation of Boost.Geometry\r\n// Don't rename them.\r\nvoid example_area_polygon()\r\n{\r\n    //[area_polygon\r\n    //` Calculate the area of a polygon\r\n    boost::geometry::polygon<boost::geometry::point_xy<double> > poly; /*< Declare >*/\r\n    boost::geometry::read_wkt(\"POLYGON((0 0,0 7,4 2,2 0,0 0))\", poly); /*< Fill, in this case with WKT >*/\r\n    double area = boost::geometry::area(poly); /*< Calculate area >*/\r\n    //]\r\n\r\n    //[area_polygon_spherical\r\n    //` Calculate the area of a *spherical* polygon\r\n    namespace bg = boost::geometry;\r\n    bg::polygon<bg::point<float, 2, bg::cs::spherical<bg::degree> > > sph_poly;\r\n    bg::read_wkt(\"POLYGON((0 0,0 45,45 0,0 0))\", sph_poly);\r\n    double area = bg::area(sph_poly);\r\n    //]\r\n}\r\n\r\nvoid example_as_wkt_point()\r\n{\r\n    typedef boost::geometry::point_xy<double> P;\r\n    P p(5.12, 6.34);\r\n    // Points can be streamed like this:\r\n    std::cout << boost::geometry::dsv<P>(p) << std::endl;\r\n\r\n    // or like this:\r\n    std::cout << boost::geometry::dsv(p) << std::endl;\r\n\r\n    // or (with extension) like this:\r\n    std::cout << boost::geometry::wkt(p) << std::endl;\r\n}\r\n\r\nvoid example_as_wkt_vector()\r\n{\r\n    std::vector<boost::geometry::point_xy<int> > v;\r\n    boost::geometry::read_wkt<boost::geometry::point_xy<int> >(\"linestring(1 1,2 2,3 3,4 4)\", std::back_inserter(v));\r\n\r\n    std::cout << boost::geometry::dsv(std::make_pair(v.begin(), v.end())) << std::endl;\r\n}\r\n\r\n\r\nvoid example_centroid_polygon()\r\n{\r\n    boost::geometry::polygon<boost::geometry::point_xy<double> > poly;\r\n    boost::geometry::read_wkt(\"POLYGON((0 0,0 7,4 2,2 0,0 0))\", poly);\r\n    // Center of polygon might have different type than points of polygon\r\n    boost::geometry::point_xy<float> center;\r\n    boost::geometry::centroid(poly, center);\r\n    std::cout << \"Centroid: \" << boost::geometry::dsv(center) << std::endl;\r\n}\r\n\r\n\r\nvoid example_distance_point_point()\r\n{\r\n    boost::geometry::point_xy<double> p1(1, 1);\r\n    boost::geometry::point_xy<double> p2(2, 3);\r\n    std::cout << \"Distance p1-p2 is \"\r\n        << boost::geometry::distance(p1, p2)\r\n        << \" units\" << std::endl;\r\n\r\n    /*\r\n    Extension, other coordinate system:\r\n    // Read 2 Dutch cities from WKT texts (in decimal degrees)\r\n    boost::geometry::point_ll<double, boost::geometry::cs::geographic<boost::geometry::degree> >  a, r;\r\n    boost::geometry::read_wkt(\"POINT(4.89222 52.3731)\", a);\r\n    boost::geometry::read_wkt(\"POINT(4.47917 51.9308)\", r);\r\n\r\n    std::cout << \"Distance Amsterdam-Rotterdam is \"\r\n        << boost::geometry::distance(a, r) / 1000.0\r\n        << \" kilometers \" << std::endl;\r\n    */\r\n}\r\n\r\nvoid example_distance_point_point_strategy()\r\n{\r\n    /*\r\n    Extension, other coordinate system:\r\n    typedef boost::geometry::point_ll<double, boost::geometry::cs::geographic<boost::geometry::degree> > LL;\r\n    LL a, r;\r\n    boost::geometry::read_wkt(\"POINT(4.89222 52.3731)\", a);\r\n    boost::geometry::read_wkt(\"POINT(4.47917 51.9308)\", r);\r\n\r\n    std::cout << \"Distance Amsterdam-Rotterdam is \"\r\n        << boost::geometry::distance(a, r,\r\n                boost::geometry::strategy::distance::vincenty<LL>() )\r\n                 / 1000.0\r\n        << \" kilometers \" << std::endl;\r\n    */\r\n}\r\n\r\nvoid example_from_wkt_point()\r\n{\r\n    boost::geometry::point_xy<int> point;\r\n    boost::geometry::read_wkt(\"Point(1 2)\", point);\r\n    std::cout << point.x() << \",\" << point.y() << std::endl;\r\n}\r\n\r\nvoid example_from_wkt_output_iterator()\r\n{\r\n    std::vector<boost::geometry::point_xy<int> > v;\r\n    boost::geometry::read_wkt<boost::geometry::point_xy<int> >(\"linestring(1 1,2 2,3 3,4 4)\", std::back_inserter(v));\r\n    std::cout << \"vector has \" << v.size() << \" coordinates\" << std::endl;\r\n}\r\n\r\nvoid example_from_wkt_linestring()\r\n{\r\n    boost::geometry::linestring<boost::geometry::point_xy<double> > line;\r\n    boost::geometry::read_wkt(\"linestring(1 1,2 2,3 3,4 4)\", line);\r\n    std::cout << \"linestring has \" << line.size() << \" coordinates\" << std::endl;\r\n}\r\n\r\nvoid example_from_wkt_polygon()\r\n{\r\n    boost::geometry::polygon<boost::geometry::point_xy<double> > poly;\r\n    boost::geometry::read_wkt(\"POLYGON((0 0,0 1,1 1,1 0,0 0))\", poly);\r\n    std::cout << \"Polygon has \" << poly.outer().size() << \" coordinates in outer ring\" << std::endl;\r\n}\r\n\r\nvoid example_point_ll_convert()\r\n{\r\n    /*\r\n    Extension, other coordinate system:\r\n    boost::geometry::point_ll<double, boost::geometry::cs::geographic<boost::geometry::degree> > deg(boost::geometry::latitude<>(33.0), boost::geometry::longitude<>(-118.0));\r\n    boost::geometry::point_ll<double, boost::geometry::cs::geographic<boost::geometry::radian> > rad;\r\n    boost::geometry::transform(deg, rad);\r\n\r\n    std::cout << \"point in radians: \" << rad << std::endl;\r\n    */\r\n}\r\n\r\nvoid example_clip_linestring1()\r\n{\r\n    typedef boost::geometry::point_xy<double> P;\r\n    boost::geometry::linestring<P> line;\r\n    boost::geometry::read_wkt(\"linestring(1.1 1.1, 2.5 2.1, 3.1 3.1, 4.9 1.1, 3.1 1.9)\", line);\r\n    boost::geometry::box<P> cb(P(1.5, 1.5), P(4.5, 2.5));\r\n    std::cout << \"Clipped linestring(s) \" << std::endl;\r\n\r\n    std::vector<boost::geometry::linestring<P> > intersection;\r\n    boost::geometry::intersection_inserter<boost::geometry::linestring<P> >(cb, line, std::back_inserter(intersection));\r\n}\r\n\r\nvoid example_clip_linestring2()\r\n{\r\n    typedef boost::geometry::point_xy<double> P;\r\n    std::vector<P> vector_in;\r\n    boost::geometry::read_wkt<P>(\"linestring(1.1 1.1, 2.5 2.1, 3.1 3.1, 4.9 1.1, 3.1 1.9)\",\r\n                    std::back_inserter(vector_in));\r\n\r\n    boost::geometry::box<P> cb(P(1.5, 1.5), P(4.5, 2.5));\r\n    typedef std::vector<std::vector<P> > VV;\r\n    VV vector_out;\r\n    boost::geometry::intersection_inserter<std::vector<P>  >(cb, vector_in, std::back_inserter(vector_out));\r\n\r\n    std::cout << \"Clipped vector(s) \" << std::endl;\r\n    for (VV::const_iterator it = vector_out.begin(); it != vector_out.end(); it++)\r\n    {\r\n        std::copy(it->begin(), it->end(), std::ostream_iterator<P>(std::cout, \" \"));\r\n        std::cout << std::endl;\r\n    }\r\n}\r\n\r\n\r\n\r\n\r\n\r\nvoid example_intersection_polygon1()\r\n{\r\n    typedef boost::geometry::point_xy<double> P;\r\n    typedef std::vector<boost::geometry::polygon<P> > PV;\r\n\r\n    boost::geometry::box<P> cb(P(1.5, 1.5), P(4.5, 2.5));\r\n    boost::geometry::polygon<P> poly;\r\n    boost::geometry::read_wkt(\"POLYGON((2 1.3,2.4 1.7,2.8 1.8,3.4 1.2,3.7 1.6,3.4 2,4.1 3,5.3 2.6,5.4 1.2,4.9 0.8,2.9 0.7,2 1.3)\"\r\n            \",(4 2,4.2 1.4,4.8 1.9,4.4 2.2,4 2))\", poly);\r\n\r\n    PV v;\r\n    boost::geometry::intersection_inserter<boost::geometry::polygon<P> >(cb, poly, std::back_inserter(v));\r\n\r\n    std::cout << \"Clipped polygon(s) \" << std::endl;\r\n    for (PV::const_iterator it = v.begin(); it != v.end(); it++)\r\n    {\r\n        std::cout << boost::geometry::dsv(*it) << std::endl;\r\n    }\r\n}\r\n\r\nvoid example_simplify_linestring1()\r\n{\r\n    //[simplify\r\n    //` Simplify a linestring\r\n    boost::geometry::linestring<boost::geometry::point_xy<double> > line, simplified;\r\n    boost::geometry::read_wkt(\"linestring(1.1 1.1, 2.5 2.1, 3.1 3.1, 4.9 1.1, 3.1 1.9)\", line);\r\n    boost::geometry::simplify(line, simplified, 0.5); /*< Simplify it, using distance of 0.5 units >*/\r\n    std::cout\r\n        << \"  original line: \" << boost::geometry::dsv(line) << std::endl\r\n        << \"simplified line: \" << boost::geometry::dsv(simplified) << std::endl;\r\n    //]\r\n}\r\n\r\nvoid example_simplify_linestring2()\r\n{\r\n    //[simplify_inserter\r\n    //` Simplify a linestring using an output iterator\r\n    typedef boost::geometry::point_xy<double> P;\r\n    typedef boost::geometry::linestring<P> L;\r\n    L line;\r\n\r\n    boost::geometry::read_wkt(\"linestring(1.1 1.1, 2.5 2.1, 3.1 3.1, 4.9 1.1, 3.1 1.9)\", line);\r\n\r\n    typedef boost::geometry::strategy::distance::projected_point<P, P> DS;\r\n    typedef boost::geometry::strategy::simplify::douglas_peucker<P, DS> simplification;\r\n    boost::geometry::simplify_inserter(line, std::ostream_iterator<P>(std::cout, \"\\n\"), 0.5, simplification());\r\n    //]\r\n}\r\n\r\n\r\n\r\nvoid example_within()\r\n{\r\n    boost::geometry::polygon<boost::geometry::point_xy<double> > poly;\r\n    boost::geometry::read_wkt(\"POLYGON((0 0,0 7,4 2,2 0,0 0))\", poly);\r\n    boost::geometry::point_xy<float> point(3, 3);\r\n    std::cout << \"Point is \"\r\n        << (boost::geometry::within(point, poly) ? \"IN\" : \"NOT in\")\r\n        << \" polygon\"\r\n        << std::endl;\r\n}\r\n\r\n/*\r\nvoid example_within_strategy()\r\n{\r\n    // TO BE UPDATED/FINISHED\r\n    typedef boost::geometry::point_xy<double> P;\r\n    typedef boost::geometry::polygon<P> POLY;\r\n    P p;\r\n    std::cout << within(p, poly, strategy::within::cross_count<P>) << std::endl;\r\n}\r\n*/\r\n\r\nvoid example_length_linestring()\r\n{\r\n    using namespace boost::geometry;\r\n    linestring<point_xy<double> > line;\r\n    read_wkt(\"linestring(0 0,1 1,4 8,3 2)\", line);\r\n    std::cout << \"linestring length is \"\r\n        << length(line)\r\n        << \" units\" << std::endl;\r\n\r\n    /*\r\n    Extension, other coordinate system:\r\n    // Linestring in latlong, filled with\r\n    // explicit degree-minute-second values\r\n    typedef point_ll<float, boost::geometry::cs::geographic<boost::geometry::degree> > LL;\r\n    linestring<LL> line_ll;\r\n    line_ll.push_back(LL(\r\n        latitude<float>(dms<north, float>(52, 22, 23)),\r\n        longitude<float>(dms<east, float>(4, 53, 32))));\r\n    line_ll.push_back(LL(\r\n        latitude<float>(dms<north, float>(51, 55, 51)),\r\n        longitude<float>(dms<east, float>(4, 28, 45))));\r\n    line_ll.push_back(LL(\r\n        latitude<float>(dms<north, float>(52, 4, 48)),\r\n        longitude<float>(dms<east, float>(4, 18, 0))));\r\n    std::cout << \"linestring length is \"\r\n        << length(line_ll) / 1000\r\n        << \" kilometers \" << std::endl;\r\n        */\r\n}\r\n\r\nvoid example_length_linestring_iterators1()\r\n{\r\n    boost::geometry::linestring<boost::geometry::point_xy<double> > line;\r\n    boost::geometry::read_wkt(\"linestring(0 0,1 1,4 8,3 2)\", line);\r\n    std::cout << \"linestring length is \"\r\n        << boost::geometry::length(line)\r\n        << \" units\" << std::endl;\r\n}\r\n\r\nvoid example_length_linestring_iterators2()\r\n{\r\n    std::vector<boost::geometry::point_xy<double> > line;\r\n    boost::geometry::read_wkt<boost::geometry::point_xy<double> >(\"linestring(0 0,1 1,4 8,3 2)\", std::back_inserter(line));\r\n    std::cout << \"linestring length is \"\r\n        << boost::geometry::length(line)\r\n        << \" units\" << std::endl;\r\n}\r\n\r\nvoid example_length_linestring_iterators3()\r\n{\r\n    /*\r\n    Extension, other coordinate system:\r\n    using namespace boost::geometry;\r\n    typedef point_ll<float, boost::geometry::cs::geographic<boost::geometry::degree> > LL;\r\n    std::deque<LL> line;\r\n    boost::geometry::read_wkt<LL>(\"linestring(0 51,1 51,2 52)\", std::back_inserter(line));\r\n    std::cout << \"linestring length is \"\r\n        << 0.001 * boost::geometry::length(line, boost::geometry::strategy::distance::vincenty<LL>())\r\n        << \" kilometers\" << std::endl;\r\n    */\r\n}\r\n\r\n\r\nvoid example_length_linestring_strategy()\r\n{\r\n    /*\r\n    Extension, other coordinate system:\r\n    using namespace boost::geometry;\r\n    typedef point_ll<float, boost::geometry::cs::geographic<boost::geometry::degree> > LL;\r\n    linestring<LL> line_ll;\r\n    line_ll.push_back(LL(latitude<float>(dms<north, float>(52, 22, 23)), longitude<float>(dms<east, float>(4, 53, 32))));\r\n    line_ll.push_back(LL(latitude<float>(dms<north, float>(51, 55, 51)), longitude<float>(dms<east, float>(4, 28, 45))));\r\n    line_ll.push_back(LL(latitude<float>(dms<north, float>(52, 4, 48)), longitude<float>(dms<east, float>(4, 18, 0))));\r\n    std::cout << \"linestring length is \"\r\n        << length(line_ll, strategy::distance::vincenty<LL, LL>() )/(1000)\r\n        << \" kilometers \" << std::endl;\r\n    */\r\n}\r\n\r\n\r\nvoid example_envelope_linestring()\r\n{\r\n    boost::geometry::linestring<boost::geometry::point_xy<double> > line;\r\n    boost::geometry::read_wkt(\"linestring(0 0,1 1,4 8,3 2)\", line);\r\n    boost::geometry::box<boost::geometry::point_xy<double> > box;\r\n    boost::geometry::envelope(line, box);\r\n\r\n    std::cout << \"envelope is \" << boost::geometry::dsv(box) << std::endl;\r\n}\r\n\r\nvoid example_envelope_polygon()\r\n{\r\n    /*\r\n    Extension, other coordinate system:\r\n    using namespace boost::geometry;\r\n    typedef point_ll<double, boost::geometry::cs::geographic<boost::geometry::degree> >  LL;\r\n\r\n    // Wrangel island, 180 meridian crossing island above Siberia.\r\n    polygon<LL> wrangel;\r\n    wrangel.outer().push_back(LL(latitude<>(dms<north>(70, 47, 7)), longitude<>(dms<west>(178, 47, 9))));\r\n    wrangel.outer().push_back(LL(latitude<>(dms<north>(71, 14, 0)), longitude<>(dms<east>(177, 28, 33))));\r\n    wrangel.outer().push_back(LL(latitude<>(dms<north>(71, 34, 24)), longitude<>(dms<east>(179, 44, 37))));\r\n    // Close it\r\n    wrangel.outer().push_back(wrangel.outer().front());\r\n\r\n    boost::geometry::box<LL> box;\r\n    boost::geometry::envelope(wrangel, box);\r\n\r\n    dms<cd_lat> minlat(box.min_corner().lat());\r\n    dms<cd_lon> minlon(box.min_corner().lon());\r\n\r\n    dms<cd_lat> maxlat(box.max_corner().lat());\r\n    dms<cd_lon> maxlon(box.max_corner().lon());\r\n\r\n    std::cout << wrangel << std::endl;\r\n    std::cout << \"min: \" << minlat.get_dms() << \" , \" << minlon.get_dms() << std::endl;\r\n    std::cout << \"max: \" << maxlat.get_dms() << \" , \" << maxlon.get_dms() << std::endl;\r\n    */\r\n}\r\n\r\n\r\nvoid example_dms()\r\n{\r\n    /*\r\n    Extension, other coordinate system:\r\n    // Construction with degree/minute/seconds\r\n    boost::geometry::dms<boost::geometry::east> d1(4, 53, 32.5);\r\n\r\n    // Explicit conversion to double.\r\n    std::cout << d1.as_value() << std::endl;\r\n\r\n    // Conversion to string, with optional strings\r\n    std::cout << d1.get_dms(\" deg \", \" min \", \" sec\") << std::endl;\r\n\r\n    // Combination with latitude/longitude and cardinal directions\r\n    {\r\n        using namespace boost::geometry;\r\n        point_ll<double, boost::geometry::cs::geographic<boost::geometry::degree> > canberra(\r\n            latitude<>(dms<south>(35, 18, 27)),\r\n            longitude<>(dms<east>(149, 7, 27.9)));\r\n        std::cout << canberra << std::endl;\r\n    }\r\n    */\r\n}\r\n\r\nvoid example_point_ll_construct()\r\n{\r\n    /*\r\n    Extension, other coordinate system:\r\n    using namespace boost::geometry;\r\n    typedef point_ll<double, boost::geometry::cs::geographic<boost::geometry::degree> > ll;\r\n\r\n    // Constructions in both orders possible\r\n    ll juneau(\r\n        latitude<>(dms<north>(58, 21, 5)),\r\n        longitude<>(dms<west>(134, 30, 42)));\r\n    ll wladiwostok(\r\n        longitude<>(dms<east>(131, 54)),\r\n        latitude<>(dms<north>(43, 8))\r\n        );\r\n    */\r\n}\r\n\r\nint main(void)\r\n{\r\n    example_area_polygon();\r\n\r\n    example_centroid_polygon();\r\n\r\n    example_distance_point_point();\r\n    example_distance_point_point_strategy();\r\n\r\n    example_from_wkt_point();\r\n    example_from_wkt_output_iterator();\r\n    example_from_wkt_linestring();\r\n    example_from_wkt_polygon();\r\n\r\n    example_as_wkt_point();\r\n\r\n    example_clip_linestring1();\r\n    example_clip_linestring2();\r\n    example_intersection_polygon1();\r\n\r\n    example_simplify_linestring1();\r\n    example_simplify_linestring2();\r\n\r\n    example_length_linestring();\r\n    example_length_linestring_iterators1();\r\n    example_length_linestring_iterators2();\r\n    example_length_linestring_iterators3();\r\n    example_length_linestring_strategy();\r\n\r\n    example_envelope_linestring();\r\n    example_envelope_polygon();\r\n\r\n    example_within();\r\n\r\n    example_point_ll_convert();\r\n    example_point_ll_construct();\r\n    example_dms();\r\n\r\n    return 0;\r\n}\r\n", "meta": {"hexsha": "7402c44d3a23998dfd180030f6149efddcb8d9ac", "size": 16474, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/geometry/doc/doxy/doxygen_input/sourcecode/doxygen_1.cpp", "max_stars_repo_name": "Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo", "max_stars_repo_head_hexsha": "eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 198.0, "max_stars_repo_stars_event_min_datetime": "2015-01-13T05:47:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-09T04:46:46.000Z", "max_issues_repo_path": "libs/boost/libs/geometry/doc/doxy/doxygen_input/sourcecode/doxygen_1.cpp", "max_issues_repo_name": "flingone/frameworks_base_cmds_remoted", "max_issues_repo_head_hexsha": "4509d9f0468137ed7fd8d100179160d167e7d943", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 9.0, "max_issues_repo_issues_event_min_datetime": "2015-01-28T16:33:19.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-12T23:03:28.000Z", "max_forks_repo_path": "libs/boost/libs/geometry/doc/doxy/doxygen_input/sourcecode/doxygen_1.cpp", "max_forks_repo_name": "flingone/frameworks_base_cmds_remoted", "max_forks_repo_head_hexsha": "4509d9f0468137ed7fd8d100179160d167e7d943", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 139.0, "max_forks_repo_forks_event_min_datetime": "2015-01-15T20:09:31.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-31T15:21:16.000Z", "avg_line_length": 35.0510638298, "max_line_length": 175, "alphanum_fraction": 0.6232851766, "num_tokens": 4759, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.33046813131717984}}
{"text": "/**\n * Copyright 2020, Massachusetts Institute of Technology,\n * Cambridge, MA 02139\n * All Rights Reserved\n * Authors: Jingnan Shi, et al. (see THANKS for the full author list)\n * See LICENSE for the license information\n */\n\n#include <map>\n#include <iostream>\n#include <chrono>\n\n#include \"mex.h\"\n#include <Eigen/Core>\n\n#include \"teaser_mex_utils.h\"\n#include \"teaser/registration.h\"\n\nenum class INPUT_PARAMS : int {\n  src = 0,\n  dst = 1,\n  cbar2 = 2,\n  noise_bound = 3,\n  estimate_scaling = 4,\n  rotation_estimation_algorithm = 5,\n  rotation_gnc_factor = 6,\n  rotation_max_iterations = 7,\n  rotation_cost_threshold = 8,\n};\n\nenum class OUTPUT_PARAMS : int {\n  s_est = 0,\n  R_est = 1,\n  t_est = 2,\n  time_taken = 3,\n};\n\ntypedef bool (*mexTypeCheckFunction)(const mxArray*);\nconst std::map<INPUT_PARAMS, mexTypeCheckFunction> INPUT_PARMS_MAP{\n    {INPUT_PARAMS::src, &isPointCloudMatrix},\n    {INPUT_PARAMS::dst, &isPointCloudMatrix},\n    {INPUT_PARAMS::cbar2, &isRealDoubleScalar},\n    {INPUT_PARAMS::noise_bound, &isRealDoubleScalar},\n    {INPUT_PARAMS::estimate_scaling, &mxIsLogicalScalar},\n    {INPUT_PARAMS::rotation_estimation_algorithm, &isRealDoubleScalar},\n    {INPUT_PARAMS::rotation_gnc_factor, &isRealDoubleScalar},\n    {INPUT_PARAMS::rotation_max_iterations, &isRealDoubleScalar},\n    {INPUT_PARAMS::rotation_cost_threshold, &isRealDoubleScalar},\n};\nconst std::map<OUTPUT_PARAMS, mexTypeCheckFunction> OUTPUT_PARMS_MAP{\n    {OUTPUT_PARAMS::s_est, &isRealDoubleScalar},\n    {OUTPUT_PARAMS::R_est, &isRealDoubleMatrix<3, 3>},\n    {OUTPUT_PARAMS::t_est, &isRealDoubleMatrix<3, 1>},\n    {OUTPUT_PARAMS::time_taken, &isRealDoubleScalar},\n};\n\n/**\n * This is the MATLAB binding for TEASER++.\n *\n * Input:\n * - src: a 3-by-N matrix of 3D points representing points to be transformed\n * - dst: a 3-by-N matrix of 3D points representing points after transformation\n * - cbar2: square of maximum allowed ratio between noise and noise bound (see [1]).\n * - noise_bound: a floating-point number indicating the bound on noise\n * - estimate_scaling: a boolean indicating whether scale needs to be estimated\n * - rotation_max_iterations: maximum iterations for the rotation estimation loop\n * - rotation_cost_threshold: cost threshold for rotation termination\n * - rotation_gnc_factor: gnc factor for rotation estimation\n *                        for GNC-TLS method: it's multiplied on the GNC control parameter\n *                        for FGR method: it's divided on the GNC control parameter\n * - rotation_estimation_algorithm: a number indicating the rotation estimation method used;\n *                                  if it's 0: GNC-TLS\n *                                  if it's 1: FGR\n *\n * Output:\n * - s_est estimated scale (scalar)\n * - R_est estimated rotation matrix (3-by-3 matrix)\n * - t_est estimated translation vector (3-by-1 matrix)\n * - time_taken time it takes for the underlying TEASER++ library to compute a solution.\n *\n * [1] H. Yang, J. Shi, and L. Carlone, “TEASER: Fast and Certifiable Point Cloud Registration,”\n * arXiv:2001.07715 [cs, math], Jan. 2020.\n *\n */\nvoid mexFunction(int nlhs, mxArray* plhs[], int nrhs, const mxArray* prhs[]) {\n\n  // Check for proper number of arguments\n  if (nrhs != INPUT_PARMS_MAP.size()) {\n    mexErrMsgIdAndTxt(\"teaserSolve:nargin\", \"Wrong number of input arguments.\");\n  }\n  if (nlhs != OUTPUT_PARMS_MAP.size()) {\n    mexErrMsgIdAndTxt(\"teaserSolve:nargin\", \"Wrong number of output arguments.\");\n  }\n\n  // Check for proper input types\n  for (const auto& pair : INPUT_PARMS_MAP) {\n    if (!pair.second(prhs[toUType(pair.first)])) {\n      std::stringstream error_msg;\n      error_msg << \"Argument \" << toUType(pair.first) + 1 << \" has the wrong type.\\n\";\n      mexErrMsgIdAndTxt(\"teaserSolve:nargin\", error_msg.str().c_str());\n    }\n  }\n\n  mexPrintf(\"Arguments type checks passed.\\n\");\n  mexEvalString(\"drawnow;\");\n\n  // Prepare parameters\n  // Prepare source and destination Eigen point matrices\n  Eigen::Matrix<double, 3, Eigen::Dynamic> src_eigen, dst_eigen;\n  mexPointMatrixToEigenMatrix(prhs[toUType(INPUT_PARAMS::src)], &src_eigen);\n  mexPointMatrixToEigenMatrix(prhs[toUType(INPUT_PARAMS::dst)], &dst_eigen);\n\n  // Other parameters\n  auto cbar2 = static_cast<double>(*mxGetPr(prhs[toUType(INPUT_PARAMS::cbar2)]));\n  auto noise_bound = static_cast<double>(*mxGetPr(prhs[toUType(INPUT_PARAMS::noise_bound)]));\n  auto estimate_scaling =\n      static_cast<bool>(*mxGetPr(prhs[toUType(INPUT_PARAMS::estimate_scaling)]));\n  auto rotation_estimation_method =\n      static_cast<int>(*mxGetPr(prhs[toUType(INPUT_PARAMS::rotation_estimation_algorithm)]));\n  auto rotation_gnc_factor =\n      static_cast<double>(*mxGetPr(prhs[toUType(INPUT_PARAMS::rotation_gnc_factor)]));\n  auto rotation_max_iterations =\n      static_cast<size_t>(*mxGetPr(prhs[toUType(INPUT_PARAMS::rotation_max_iterations)]));\n  auto rotation_cost_threshold =\n      static_cast<double>(*mxGetPr(prhs[toUType(INPUT_PARAMS::rotation_cost_threshold)]));\n\n  // Prepare the TEASER++ solver for solving registration problem\n  teaser::RobustRegistrationSolver::Params params;\n  params.noise_bound = noise_bound;\n  params.cbar2 = cbar2;\n  params.estimate_scaling = estimate_scaling;\n  params.rotation_max_iterations = rotation_max_iterations;\n  params.rotation_gnc_factor = rotation_gnc_factor;\n  params.rotation_cost_threshold = rotation_cost_threshold;\n\n  switch (rotation_estimation_method) {\n  case 0: { // GNC-TLS method\n    mexPrintf(\"Use GNC-TLS for rotation estimation.\\n\");\n    params.rotation_estimation_algorithm =\n        teaser::RobustRegistrationSolver::ROTATION_ESTIMATION_ALGORITHM::GNC_TLS;\n    break;\n  }\n  case 1: { // FGR method\n    mexPrintf(\"Use FGR for rotation estimation.\\n\");\n    params.rotation_estimation_algorithm =\n        teaser::RobustRegistrationSolver::ROTATION_ESTIMATION_ALGORITHM::FGR;\n    break;\n  }\n  default: {\n    mexPrintf(\"Rotation estimation method given does not exist. Use GNC-TLS instead.\\n\");\n    params.rotation_estimation_algorithm =\n        teaser::RobustRegistrationSolver::ROTATION_ESTIMATION_ALGORITHM::GNC_TLS;\n    break;\n  }\n  }\n  teaser::RobustRegistrationSolver solver(params);\n\n  mexPrintf(\"Start TEASER++ solver.\\n\");\n  mexEvalString(\"drawnow;\");\n\n  // Start the timer\n  auto start = std::chrono::high_resolution_clock::now();\n\n  // Solve\n  assert(src_eigen.size() != 0);\n  assert(dst_eigen.size() != 0);\n  solver.solve(src_eigen, dst_eigen);\n\n  // Stop the timer\n  auto stop = std::chrono::high_resolution_clock::now();\n  auto duration = std::chrono::duration_cast<std::chrono::microseconds>(stop - start);\n  double duration_in_milliseconds = static_cast<double>(duration.count()) / 1000.0;\n\n  auto solution = solver.getSolution();\n\n  mexPrintf(\"TEASER++ has found a solution in %f milliseconds.\\n\", duration_in_milliseconds);\n  mexEvalString(\"drawnow;\");\n\n  // Populate outputs\n  plhs[toUType(OUTPUT_PARAMS::s_est)] = mxCreateDoubleScalar(solution.scale);\n  // Populate output R matrix\n  plhs[toUType(OUTPUT_PARAMS::R_est)] = mxCreateDoubleMatrix(3, 3, mxREAL);\n  Eigen::Map<Eigen::Matrix3d> R_map(mxGetPr(plhs[toUType(OUTPUT_PARAMS::R_est)]), 3, 3);\n  R_map = solution.rotation;\n\n  // Populate output T vector\n  plhs[toUType(OUTPUT_PARAMS::t_est)] = mxCreateDoubleMatrix(3, 1, mxREAL);\n  Eigen::Map<Eigen::Matrix<double, 3, 1>> t_map(mxGetPr(plhs[toUType(OUTPUT_PARAMS::t_est)]), 3, 1);\n  t_map = solution.translation;\n\n  // Populate time output\n  plhs[toUType(OUTPUT_PARAMS::time_taken)] = mxCreateDoubleScalar(duration_in_milliseconds);\n}\n", "meta": {"hexsha": "829db9307957e3f10fde68b08ce60638b725d656", "size": 7522, "ext": "cc", "lang": "C++", "max_stars_repo_path": "matlab/teaser_mex.cc", "max_stars_repo_name": "esteimle/teaser", "max_stars_repo_head_hexsha": "663e77362784020d69ca499c3769505d91d0da65", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-02-13T20:47:08.000Z", "max_stars_repo_stars_event_max_datetime": "2020-02-13T20:47:08.000Z", "max_issues_repo_path": "matlab/teaser_mex.cc", "max_issues_repo_name": "skohlbr/TEASER-plusplus", "max_issues_repo_head_hexsha": "65fc12d4324d68570ee126aff84f0bc84217aeb1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "matlab/teaser_mex.cc", "max_forks_repo_name": "skohlbr/TEASER-plusplus", "max_forks_repo_head_hexsha": "65fc12d4324d68570ee126aff84f0bc84217aeb1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-11-27T15:24:12.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-27T15:24:12.000Z", "avg_line_length": 38.7731958763, "max_line_length": 100, "alphanum_fraction": 0.724408402, "num_tokens": 1956, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6039318479832804, "lm_q2_score": 0.5467381519846138, "lm_q1q2_score": 0.33019258249103145}}
{"text": "//rego: Automatic time series forecasting and missing value imputation.\n//\n//Copyright (C) Davide Altomare and David Loris <channelattribution.io>\n//\n//This source code is licensed under the MIT license found in the\n//LICENSE file in the root directory of this source tree. \n\n#define language_cpp \n//#define language_python\n//#define language_R\n\n#include <iostream>\n#include <vector>\n#include <set>\n#include <math.h>\n#include <time.h>\n#include <stdio.h>\n#include <sstream>\n#include <list>\n#include <string>\n#include <random>\n#include <numeric>\n#include <time.h> \n#include <thread>\n#include <map>\n#include <algorithm>\n#include <list>\n#include <limits> \n#include <functional>\n\n#define uli unsigned long int\n\n// #include <armadillo>\n#ifndef language_R\n //#define OPTIM_ENABLE_ARMA_WRAPPERS\n #include <armadillo>\n#endif\n\n#ifdef language_R\n #define __GXX_EXPERIMENTAL_CXX0X__ 1\n\n //#include <Rcpp.h>\n #include <RcppArmadillo.h>\n\n #define ARMA_USE_CXX11\n #define ARMA_64BIT_WORD\n \n #ifndef BEGIN_RCPP\n #define BEGIN_RCPP\n #endif\n  \n #ifndef END_RCPP\n #define END_RCPP\n #endif\n \n using namespace Rcpp;\n#endif\n\n\n#ifdef language_py\n #include <Python.h>\n#endif\n\n\nusing namespace std;\nusing namespace arma;\n\n\n//------------------------------------------------------------------------------------------------------------------------\n//GENERAL FUNCTIONS\n//------------------------------------------------------------------------------------------------------------------------\n\n\ndouble lfactorial(uli n)\n{\n  \n double x;\n\n x=lgamma(n+1);\n\n return(x);\n\n} //end function\n\n\ndouble lchoose(uli n, uli k)\n{\n  \n  double x;\n  \n  x=lgamma(n+1)-lgamma(k+1)-lgamma(n-k+1);\n\n  return(x);\n\n} //end function\n\n\n\ndouble log_sum(colvec v)\n{\n\n  double lsum; \n \n  if(accu(v>=0)>0){\n   if(max(v)<=700){lsum=log(accu(exp(v)));} else{lsum=max(v);}\n  } else{\n   if(min(v)>=-700){lsum=log(accu(exp(v)));} else {lsum=max(v);} \n  }\n\n  return lsum;\n\n} //end function\n\n\n\nvec sub_elem_eq(vec v, vec w, double x)\n{\n  uvec iw;\n\n  iw=find(w==x);\n  if(!iw.is_empty()){v=v.elem(iw);}else{v=datum::nan;}\n   \n  return v;\n\n} //end function\n\n\nmat sub_mat(mat M, vec vr, vec vc)\n{\n  uli r, c, lvr, lvc;\n  lvr=vr.n_elem;\n  lvc=vc.n_elem;\n  mat Q(lvr,lvc);\n\n  for(c=0; c<lvc; c++){\n   for(r=0; r<lvr; r++){ \n    Q(r,c)=M(vr(r),vc(c)); \n   }\n  }\n\n  return Q;\n\n} //end function\n\n\nmat pow_vec(vec v, vec w)\n{\n\n   uli k, lv; \n   vec vv;\n\n   lv=v.n_elem;\n   vv=zeros<vec>(lv);\n\n   for(k=0; k<lv; k++){\n    vv(k)=pow(v(k),w(k));\n   }\n\n return vv;\n\n}\n\n//------------------------------------------------------------------------------------------------------------------------\n//FUNCTIONS FOR STORING MODELS IN A BINARY TREE\n//------------------------------------------------------------------------------------------------------------------------\n\n//this function add a model \"M\" to \"tree\"\n\nfield<mat> add_to_tree(vec M, double lM, uli nM, mat tree, double ltree)\n{\n\n uli j;\n uli k;\n\n field<mat> Res(2,1);\n\n if(nM==0){\n    \n  for(j=0; j<=lM; j++){\n \n   if(M(j)==1){tree(j,0)=j+1;}\n   else{tree(j,1)=j+1;}\n \n  }\n \n  ltree=lM; \n  tree.row(ltree)=tree.row(ltree)*0+nM;\n\n }\n\n uli z;\n uli h;\n uli iM=datum::nan;\n\n if(nM>0){ //if1\n   \n  z=0;\n  h=ltree+1;\n  \n  for(j=0; j<=lM; j++){ //for1  \n  \n   iM=1-M(j);\n      \n   if(!is_finite(tree(z,iM)) && (j<=lM) ){ //if2\n     \n    tree(z,iM)=h;\n     \n    for(k=(j+1); k<=lM; k++){ //for2\n  \n      if(M(k)==1){tree(h,0)=h+1;} else{tree(h,1)=h+1;}\n      \n      h=h+1;\n    \n    } //end for2    \n\n    iM=1-M(lM);\n    ltree=h-1;\n    break;\n   \n   } //end if2\n \n   if(j==lM){tree(z,iM)=nM; ltree=ltree+1; break;}\n  \n   if(tree(z,iM)>=0){z=tree(z,iM);}\n  \n  } //end for1\n  \n\n  tree(ltree,iM)=tree(ltree,iM)*0+nM;\n\n } //end if1\n\n\n Res(0,0)=tree;\n Res(1,0)=ltree;\n\n return Res;\n\n} //end function\n\n\n//this function returns the possible movements from a model \"M\", given all the previous models visited and stored in \"tree\"\n\nvec mov_tree(mat tree, vec M, uli lM, vec vlM, uli max_lM)\n{\n\n uli q; uli k; uli z; uli h; uli iM2;\n double sumM;\n vec mov(lM+1); uvec imov; uvec umov; vec mov2; vec M2;\n \n \n mov.fill(-1);\n sumM=sum(M);\n q=0;\n\n for(k=0; k<=lM; k++){ //for1\n  \n  M2=M; \n  M2(k)=1-M(k);\n  z=0;\n  \n  for(h=0; h<=lM; h++){ //for2\n    \n   iM2=1-M2(h);\n   if(!is_finite(tree(z,iM2))){mov(q)=k; q=q+1; break;} else{z=tree(z,iM2);}\n   \n    } //end for2\n  \n \n } //end for1\n\n imov=find(mov>-1);\n \n if(!imov.is_empty()){\n \n  mov=mov.elem(imov);\n  umov=conv_to<uvec>::from(mov);\n\n  if(sumM>=max_lM){\n  \n   mov2=zeros<vec>(lM+1);\n   mov2.elem(umov)=ones<vec>(mov.n_elem);\n   mov=(mov2%M)%vlM;\n   imov=find(mov>0);\n   if(!imov.is_empty()){mov=mov.elem(imov); mov=mov-1;} else{mov=datum::nan;}\n  }\n\n } else {mov=datum::nan;}\n \n\n return mov;\n\n} //end function\n\n\n\n//------------------------------------------------------------------------------------------------------------------------\n//FUNCTIONS FOR BAYESIAN STOCHASTIC SEARCH\n//------------------------------------------------------------------------------------------------------------------------\n\n\ndouble log_H_h_i(double mu, double sigma, double h, double i)\n{\n\n double x;\n\n x=lfactorial(2*h)+i*log(sigma)-lfactorial(i)+(2*h-2*i)*log(abs(mu))-lfactorial(2*h-2*i);\n\n return x;\n\n} //end function\n\n\n\ndouble log_FBF_Ga_Gb(vec G_a, vec G_b, uli edge, mat edges, mat YtY, uli add, double n, double h)\n{\n\n  uli e1, e2, iwi;\n  double i, p, b, S2, mu, sigma, logS2, ilogS2, logHhi, ilog4, log_num1, log_den1, log_w_1, log_num0i0, log_den0i0, log_w_0, log_FBF_unpasso;\n  vec V1, V2, G1, V11, pa1, pa0, betah, vv(1), z1;\n  uvec iw, ipa1;\n  mat e, yty, XtX, Xty, invXtX;   \n  \n  e=edges.row(edge);\n  e1=e(0);\n  e2=e(1);\n\n  V1=edges.col(0);\n  V2=edges.col(1);\n    \n  if(add==1){G1=G_a;}else{G1=G_b;}   \n\n  V11=(V1+1)%G1;\n  iw=find(V2==e2); pa1=V11.elem(iw);\n  iw=find(pa1>0); pa1=pa1.elem(iw); pa1=pa1-1;\n \n  iw=find(pa1!=e1); if(!iw.is_empty()){pa0=pa1.elem(iw);}else{pa0=datum::nan;}\n \n  p=pa1.n_elem;\n  b=(p+2*h+1)/n;\n\n  yty=YtY(e2,e2);\n    \n  // //calcolo w1\n   \n  vv(0)=e2; Xty=sub_mat(YtY,pa1,vv);\n  XtX=sub_mat(YtY,pa1,pa1);\n  betah=solve(XtX,Xty);\n  //betah=inv_sympd(XtX)*Xty;\n\n  S2=conv_to<double>::from(yty-(trans(Xty)*betah));\n  \n  iw=find(pa1==e1); mu=conv_to<double>::from(betah.elem(iw));\n  iwi=conv_to<uli>::from(iw); \n  z1=zeros<vec>(pa1.n_elem);\n  z1(iwi)=1;\n  z1=solve(XtX,z1);\n  //z1=inv_sympd(XtX)*z1; \n  \n  sigma=conv_to<double>::from(z1.elem(iw));\n  \n  if(S2>0){\n   log_w_1=(-n*(1-b)/2)*log(datum::pi*b*S2);\n   logS2=log(S2);\n   log_num1=-datum::inf;\n   log_den1=-datum::inf;\n\n   for(i=0; i<=h; i++){\n   \n    ilogS2=i*logS2;\n    logHhi=log_H_h_i(mu,sigma,h,i);\n    ilog4=-i*log(4);\n      \n    log_num1=log_add(log_num1, (ilog4+logHhi+lgamma((n-p-2*i)/2)+ilogS2));\n    log_den1=log_add(log_den1, (ilog4+logHhi+lgamma((n*b-p-2*i)/2)+ilogS2));\n\n   }\n    \n   log_w_1=log_w_1+log_num1-log_den1;\n  }else{\n   log_w_1=datum::inf;\n  }\n     \n  //calcolo w0\n\n  if(!pa0.is_finite()){p=0;}else{p=pa0.n_elem;}\n  \n  log_num0i0=lgamma((n-p)/2);\n  log_den0i0=lgamma((n*b-p)/2);\n\n  if(p==0){S2=conv_to<double>::from(yty);}\n  else{\n   vv(0)=e2; Xty=sub_mat(YtY,pa0,vv);\n   XtX=sub_mat(YtY,pa0,pa0);\n   betah=solve(XtX,Xty);\n   //betah=inv_sympd(XtX)*Xty;\n   S2=conv_to<double>::from(yty-(trans(Xty)*betah));\n  }\n\n  if(S2>0){\n   log_w_0=(-(n*(1-b)/2))*log(datum::pi*b*S2)+log_num0i0-log_den0i0;\n  }else{\n   log_w_0=datum::inf;\n  }\n  \n  //calcolo FBF\n\n  if(add==1){log_FBF_unpasso=log_w_1-log_w_0;}\n  else{log_FBF_unpasso=log_w_0-log_w_1;} \n  \n  if(!is_finite(log_FBF_unpasso)){\n   log_FBF_unpasso=0;\t  \n  }\n\n  return log_FBF_unpasso;\n\n} // end function\n\n\n\n\nfield<mat> FBF_heart(double nt, mat YtY, vec vG_base, double lcv, vec vlcv, mat edges, double n_tot_mod, double C, double maxne, double h, bool univariate)\n{\n    \n   uli t, add, edge, imq, limodR, s;\n   double ltree, lM, sum_log_FBF, log_FBF_G, log_pi_G, log_num_MP_G, sum_log_RSMP, n_mod_r, log_FBF_t, log_FBF1;\n   vec M_log_FBF, log_num_MP, log_sume, G, imod_R, M_log_RSMP, pRSMP, mov, vlM, qh, G_t, M_q, M_P;\n   uvec iw;\n   mat tree, SM, M_G; \n   field<mat> treeRes, Res(4,1);\n   uword i_n_mod_r, imaxe;\n \n   M_G=zeros<mat>(lcv,n_tot_mod);  \n   M_P=zeros<vec>(n_tot_mod); \n   M_log_FBF=zeros<vec>(n_tot_mod); \n   log_num_MP=zeros<vec>(n_tot_mod); \n   M_q=zeros<vec>(lcv); \n   tree=zeros<mat>(n_tot_mod*lcv,2); tree.fill(datum::nan);\n   ltree=datum::nan;\n   lM=lcv-1; \n \n   sum_log_FBF=-datum::inf; \n   log_sume=zeros<vec>(lcv); log_sume.fill(-datum::inf);\n  \n   M_log_RSMP=zeros<vec>(n_tot_mod);\n   sum_log_RSMP=-datum::inf;\n   imod_R=zeros<vec>(n_tot_mod);\n\n   lM=lcv-1;\n\n   Col<uli> vexit(1);\n\n   for(t=0; t<lcv; t++){ //for1\n       \n    G=vG_base;\n    G(t)=1-vG_base(t);\n    add=G(t);\n    edge=t;\n\n    log_FBF_G=log_FBF_Ga_Gb(G,vG_base,edge,edges,YtY,add,nt,h);\n    \n    M_G.col(t)=G;\n    \n    treeRes=add_to_tree(G,lM,t,tree,ltree);\n    tree=treeRes(0,0);\n    ltree=conv_to<double>::from(treeRes(1,0));\n        \n    M_log_FBF(t)=log_FBF_G;\n    log_pi_G=-log(lcv+1)-lchoose(lcv,sum(G));\n    log_num_MP_G=log_FBF_G+log_pi_G;\n    log_num_MP(t)=log_num_MP_G;\n\n    sum_log_FBF=log_add(sum_log_FBF, log_num_MP_G);\n  \n    for(imq=0; imq<lcv; imq++){\n     if(G(imq)==1){log_sume(imq)=log_add(log_sume(imq), log_num_MP_G);}\n    }\n    \n    M_q=exp(log_sume-sum_log_FBF);\n   \n    M_log_RSMP(t)=log_num_MP_G;\n    sum_log_RSMP=log_add(sum_log_RSMP, log_num_MP_G);\n   \n    imod_R(t)=t;\n \n   } //end for1\n\n \n   if(univariate==0){\n   \n    limodR=t-1; \n    s=lcv;\n\n    \n    while(t<n_tot_mod){ //while1\n    //cout << t << \":\" << n_tot_mod << endl;\n\n     pRSMP=exp(M_log_RSMP.subvec(0,limodR)-sum_log_RSMP);\n\t   pRSMP.max(i_n_mod_r);\n     \n     n_mod_r=imod_R(i_n_mod_r);\n         \n     G=M_G.col(n_mod_r);\n     G_t=G;\n     log_FBF_t=M_log_FBF(n_mod_r);\n     \n     \n     vlM=vlcv+1;\n     mov=mov_tree(tree,G,lM,vlM,maxne);\n   \n     if(!is_finite(mov)){ //if1\n      \n      imod_R(i_n_mod_r)=-1;\n      iw=find(imod_R>-1); imod_R=imod_R.elem(iw);\n      M_log_RSMP=M_log_RSMP.elem(iw);\n          \n      limodR=limodR-1;\n      t=t-1;\n        \n     } else{\n        \n       qh=pow_vec((M_q+C)/(1-M_q+C), (2*(1-G))-1);\n       qh=qh.elem(conv_to<uvec>::from(mov));\n    \n        \n       if(mov.n_elem==1){ //if2\n           \n        imod_R(i_n_mod_r)=-1;\n        iw=find(imod_R>-1); imod_R=imod_R.elem(iw);\n        M_log_RSMP=M_log_RSMP.elem(iw);\n      \n         limodR=limodR-1;  \n         edge=mov(0);\n         \n        } else{\n           \n           qh.max(imaxe);\n           edge=mov(imaxe);\n          \n        } // end if2\n    \n        \n        G(edge)=1-G(edge);\n        add=G(edge);   \n       \n        \n\t\t    log_FBF1=log_FBF_Ga_Gb(G,G_t,edge,edges,YtY,add,nt,h);\n\t      log_FBF_G=log_FBF1+log_FBF_t;\n      \n        M_G.col(t)=G;\n        \n        treeRes=add_to_tree(G,lM,t,tree,ltree);\n        tree=treeRes(0,0);\n        ltree=conv_to<double>::from(treeRes(1,0));\n      \n        M_log_FBF(t)=log_FBF_G;\n        log_pi_G=-log(lcv+1)-lchoose(lcv,sum(G));\n        log_num_MP_G=log_FBF_G+log_pi_G;\n        log_num_MP(t)=log_num_MP_G;\n    \n        sum_log_FBF=log_add(sum_log_FBF, log_num_MP_G);\n        \n        for(imq=0; imq<lcv; imq++){\n         if(G(imq)==1){log_sume(imq)=log_add(log_sume(imq), log_num_MP_G);}\n        }\n        M_q=exp(log_sume-sum_log_FBF);\n\t    \n        limodR=limodR+1;\n        imod_R(limodR)=t;\n        M_log_RSMP(limodR)=log_num_MP_G; \n         \n     } //end if1\n    \n     t=t+1;\n     s=s+1;\n    \n    } //end while1 \n\n  }// end if univariate \n\n  t=t-1; \n  s=s-1;\n  \n  M_P.subvec(0,t)=exp(log_num_MP.subvec(0,t)-sum_log_FBF);\n  if(max(M_P.subvec(0,t))>0){\n   M_P.subvec(0,t)=M_P.subvec(0,t)/sum(M_P.subvec(0,t));\n  }else{\n   M_P.subvec(0,t)=zeros<vec>(t+1);\t  \t  \n  }\n  \n  M_G=M_G.submat(0,0,lcv-1,t);\n  \n  Res(0,0)=M_q;\n  Res(1,0)=M_G;\n  Res(2,0)=M_P;\n  Res(3,0)=M_log_FBF.subvec(0,t);\n\n  return Res;\n   \n\n} // end function\n\n\nmat G_fin_fill(mat G, vec vr, uli ic, vec x)\n{\n  uli k, lvr;\n  lvr=vr.n_elem;\n \n  for(k=0; k<lvr; k++){\n    G(vr(k),ic)=x(k); \n  }\n\n  return G;\n\n} //end function\n\n\nfield<mat> FBF_RS(Mat<double> Corr_c, double nobs_c, Col<double> G_base_c, double h_c, double C_c, double n_tot_mod_c, double n_hpp_c, bool univariate)\n{\n\n uli neq, rr; \n double maxne, Mlogbin_sum, lcv, rrmax, q;\n vec V1, V2, vlcv, vG_base, M_q, M_P, iM_P, M_P2;\n mat edges, G_fin, M_G, M_G2;\n field<mat> heartRes;\n \n q=Corr_c.n_cols; \n\n maxne=nobs_c-2*h_c-2;\n\n neq=1;\n\n V1=linspace<vec>(1,q-1,q-1);\n V2=zeros<vec>(q-neq);\n\n edges=join_rows(V1,V2); \n\n //edges.print(\"edges\");\n   \n lcv=V1.n_elem;\n vlcv=linspace<vec>(0,lcv-1,lcv); \n  \n vG_base=flipud(G_base_c);\n   \n rrmax=std::min(maxne,lcv); \n Mlogbin_sum=0;\n   \n for(rr=1; rr<=rrmax; rr++){\n  Mlogbin_sum=log_add(Mlogbin_sum,lchoose(lcv,rr));   \n }\n \n n_tot_mod_c=std::min(Mlogbin_sum,log(n_tot_mod_c));\n n_tot_mod_c=round(exp(n_tot_mod_c)); \n\n heartRes=FBF_heart(nobs_c, Corr_c*nobs_c, vG_base, lcv, vlcv, edges, n_tot_mod_c, C_c, maxne, h_c, univariate);\n \n return(heartRes);\n\n} // end function\n\n\nvoid printA(string msg)\n{\n\n #ifdef language_cpp\n  cout << msg << endl;\n #endif\n \n #ifdef language_py\n  msg=\"print('\" + msg + \"')\";\n  PyRun_SimpleString(msg.c_str());\n #endif\n\n #ifdef language_R\t\n  Rcout << msg << endl;\n #endif \n\t\n}\n\n\nvoid xit(){\n  vector<int> v;\n  printA(\"execution intentionally interrupted\");\n  printA(to_string(v[0]));\n}\n\ntemplate <typename T>\nvoid printV(vector<T> vec,string name){\n  printA(name+\": \");\n  for (auto i: vec){\n    printA(to_string(i));\n  }\n  printA(\"\");\n}\n\ntemplate<typename T>\nstring vec_to_string (T v, uli len){\n    \n    // string type0=typeid(v(0)).name();\n    // bool flg_string=0;\n    // if(type0.find(\"string\")!=string::npos){\n    //   flg_string=1;\n    // }\n    \n    string res;\n    if(len>0){\n     res=to_string(v(0));\n     for(uli t=1; t<len; ++t){\n       res=res+\",\"+to_string(v(t));\n     }\n    }else{\n     res=\"empty\";\n    }\n    return(res);\n}\n\n\ntemplate <typename T>\nstring NumberToString ( T Number )\n{\n   ostringstream ss;\n   ss << Number;\n   return ss.str();\n}\n\nvector<long int> split_string(const string &s, uli order) {\n    \n\tchar delim=' ';\n\tvector<long int> result(order,-1);\n    stringstream ss (s);\n    string item;\n\n\tuli h=0;\n    while (getline (ss, item, delim)) {\n\t\tresult[h]=stoi(item);\n\t\th=h+1;\n    }\n\t\t\n    return result;\n}\n\ntemplate<typename T>\nuli find_consecutive_finite(T* x, uli col){\n   \n   uli max_num=0;\n   uli num=0;\n   for(uli j=0; j<(*x).n_rows; ++j){\n    if(isfinite((*x)(j,col))==1){\n     num=num+1;\n     if(num>max_num){\n       max_num=num;\n     }\n    }else{\n     num=0; \n    } \n   }\n\n  return(max_num);\n\n}\n\ntemplate<typename T>\nuli find_consecutive_nan(T* x, uli col){\n   \n   uli max_num=0;\n   uli num=0;\n   for(uli j=0; j<(*x).n_rows; ++j){\n    if(isfinite((*x)(j,col))==0){\n     num=num+1;\n     if(num>max_num){\n       max_num=num;\n     }\n    }else{\n     num=0; \n    } \n   }\n\n  return(max_num);\n\n}\n\n\nstring f_print_perc(double num){ \n \n string res;\n if(num>=1){\n  res=to_string((double)(floor(num*10000)/100)).substr(0,6);    \n }else if(num>=0.1){ \n  res=to_string((double)(floor(num*10000)/100)).substr(0,5); \n }else{\n  res=to_string((double)(floor(num*10000)/100)).substr(0,4);    \t   \n } \n return(res);\n}\n\n\nvector<string> subvector(vector<string> v, Col<uli> idx){\n vector<string> sub_v;\n for(uli j=0; j<idx.n_rows; ++j){\n  sub_v.push_back(v[idx(j)]);\n }\n return(sub_v);\n}\n\n\nvector< vector<double> >  arma_mat_to_std_mat(mat* A) {\n    \n    vector< vector<double> >  V((*A).n_rows);\n    for (size_t i = 0; i < (*A).n_rows; ++i) {\n        V[i] = arma::conv_to< vector<double> >::from((*A).row(i));\n    };\n    \n    return V;\n}\n\n\n///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n//FUNCTIONS FOR VARIABLE SELECTION AND PREDICTIONS\n///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n\nstruct str_input\n{\n\n  mat MY0;\n  mat MY;\n  mat corY;\n  uli corY_nr;\n  uli corY_nc;\n\n  mat* prt_MY0(){\n   return(&MY0);\n  }\n  \n  mat* prt_MY(){\n   return(&MY);\n  }\n\n};\n\n\nstr_input data_preparation(mat* Y, Col<uli> vretard)\n{\n\n  //varibile target in differenze ritardata\n  \n  mat MY;\n  if(vretard.n_rows>0){\n    MY.resize((*Y).n_rows,vretard.n_rows);\n      \n    for(uli k=0; k<vretard.n_rows; ++k){\n     MY.col(k)=shift((*Y).col(0),vretard(k));\n     if(vretard(k)>0){\n       MY.submat(0,k,vretard(k)-1,k)+=datum::nan;\n     }\n    }\n    //join\n    MY=join_rows((*Y),MY);\n  }else{\n   MY=(*Y);\n  }\n\n  //output\n\n  str_input tab_input;\n  \n  tab_input.MY0=MY;\n\n  MY=MY.rows(find_finite(sum(MY,1)));\n\n  tab_input.MY=MY;\n\n  mat corY=cor(MY);\n\n  tab_input.corY=corY;\n  tab_input.corY_nr=MY.n_rows;\n  tab_input.corY_nc=MY.n_cols;\n\n\n  return(tab_input);\n\n}\n\n\n\nstruct str_output_reg\n{\n    Col<double> vactual;\n    Col<double> vfitted0;\n    Col<double> vresid0;\n    Col<double> vfitted;\n    Col<double> vresid;\n    Col<double> vbeta;\n    double TSS;\n    double RSS;\n    double L;\n    double L_adj;\n\n    Col<double>* prt_vresid(){\n     return(&vresid);\n    }\n};\n\nstr_output_reg reg(mat* MY0, mat* MY)\n{\n     \n    mat X=(*MY).cols(1,(*MY).n_cols-1);\n    vec Y=(*MY).col(0);\n    mat XtX=trans(X)*X;\n    vec Xty=trans(X)*Y; \n    vec vbeta=solve(XtX,Xty);\n    //vec vbeta=inv_sympd(XtX)*Xty;\n\t    \n    vec vactual=Y;\n    vec vfitted=X*vbeta;\n    vec vresid=vactual-vfitted;\n\t\n    vec vactual0=(*MY0).col(0);\n    vec vfitted0=(*MY0).cols(1,(*MY0).n_cols-1)*vbeta;\n    vec vresid0=vactual0-vfitted0;\n     \n    str_output_reg Res;\n\n    Res.vbeta=vbeta;\n    Res.vactual=Y;\n    Res.vfitted0=vfitted0;\n    Res.vresid0=vresid0;\n    Res.vfitted=vfitted;\n    Res.vresid=vresid;\n\n    return(Res);\n}\n\n\nstruct str_out_uni_select\n{\n Col<uli> vars_x_idx;\n Col<uli> vars_ar_idx; \n};\n\nstr_out_uni_select model_univariate_selection(mat* Y, Col<uli>* vretard, double max_lag){\n\n  str_out_uni_select str_out;\n  \n  if((max_lag!=0) | (((*Y).n_cols-1)>0)){\n            \n    uli from_lag=1;\n  \n    double cons_rows;\n    uli max_lag0;\n\n    cons_rows=(double) find_consecutive_finite(Y,0);\n    max_lag0=(uli) min(cons_rows/2,cons_rows/log(cons_rows/10));\n    if(max_lag==-1){\n     max_lag=(double) max_lag0;\n    }else if(max_lag>0){\n     max_lag=(double) min(max_lag,(double)max_lag0);\n    }\n  \n    if(max_lag>0){\n     (*vretard)=linspace<Col<uli>>(from_lag,(uli)max_lag,(uli)max_lag-from_lag+1);\n    }\n\n    double nvars=(*Y).n_cols-1+(*vretard).n_rows;  \n    double h_c=1; \n    if(nvars>50){\n     h_c=2; \n    } \n    double n_tot_mod_c=nvars*100;\n    double C_c=0.01;\n    double threshold; \n    \n    str_input tab_input;\n    field<mat> res;\n  \n    uli nr,nc,nvar_max;\n    Col<double> G_base_c;\n    bool univariate=1;\n    Col<double> M_q;\n    Col<double> M_log_FBF;\n  \n    //estimate threshold\n    \n    nc=(*Y).n_cols;\n    mat Ynorm = randu<mat>((*Y).n_rows,100);  \n\n    mat Y0=Ynorm;\n    Col<uli> vretard0;\n    tab_input=data_preparation(&Y0,vretard0);\n  \n    nr=tab_input.corY_nr;\n    nc=tab_input.corY_nc;\n    nvar_max=(uli)2*std::pow(tab_input.MY.n_rows,0.25);\n    G_base_c=zeros<vec>(nc-1);\n  \n    res=FBF_RS(tab_input.corY,nr,G_base_c,h_c,C_c,Y0.n_cols-1+vretard0.n_rows,Y0.n_cols-1+vretard0.n_rows,univariate);\n    M_log_FBF=res(3,0); \n\n    uli nth=(uli) (0.99*M_log_FBF.size());\n    M_log_FBF=sort(M_log_FBF);\n    threshold=M_log_FBF(nth);\n\n    //univariate  \n  \n    tab_input=data_preparation(Y,*vretard);\n    nr=tab_input.corY_nr;\n    nc=tab_input.corY_nc;\n\n    G_base_c=zeros<vec>(nc-1);  \n    n_tot_mod_c=(*Y).n_cols-1+(*vretard).n_rows;\n    double n_hpp_c=(*Y).n_cols-1+(*vretard).n_rows;\n\n    res=FBF_RS(tab_input.corY,nr,G_base_c,h_c,C_c,n_tot_mod_c,n_hpp_c,univariate);\n\n    M_log_FBF=res(3,0);\n\n    uvec ids=find(M_log_FBF>threshold);\n    if(ids.n_rows>nvar_max){\n     ids = sort_index(M_log_FBF,\"descend\");\n     ids=ids.rows(0,nvar_max-1);\n     ids=sort(ids);\n    }\n\n\n    vec rvals=linspace<vec>(0,M_log_FBF.n_rows-1, M_log_FBF.n_rows).elem(ids);\n\n    vec ids_vars=rvals-((*Y).n_cols-1);\n    vec ids_vars_ar=ids_vars(find(ids_vars>=0));\n\n    uvec fd_ids_vars=find(ids_vars<0);\n    Col<uli> ids_vars_x;\n    if(fd_ids_vars.n_cols>0){\n     ids_vars_x=conv_to< Col<uli> >::from(rvals(fd_ids_vars));\n     ids_vars_x=ids_vars_x+1;\n    }\n  \n\t  Col<uli> tmp=(*vretard)(conv_to< uvec >::from(ids_vars_ar));\n    str_out.vars_x_idx=ids_vars_x;\n    str_out.vars_ar_idx=tmp;\n  \n    (*vretard)=(*vretard)(conv_to< uvec >::from(ids_vars_ar));\n  \n  } \n   \n  \n  return(str_out);\n\n}\n\nstruct str_out_multi_select\n{\n vec resid; \n Col<uli> ids_vars_x;\n Col<uli> ids_vars_ar;\n vec vbeta; \n};\n  \nstr_out_multi_select model_multivariate_selection(mat* Y, Col<uli>* ids_vars_x_uni, Col<uli>* vretard){\n        \n    str_out_multi_select str_out;\n    Col<uli> ids_vars_x,v_ar;\n    vec vbeta_arx;\n    vec vresid((*Y).n_rows,1);\n\n    double nvars=(*Y).n_cols-1+(*vretard).n_rows; \n\n    if(nvars>0){\n\n      double threshold=0.5;\n      double h_c=1; \n      if(nvars>50){\n       h_c=2; \n      } \n      double n_tot_mod_c=nvars*100;\n      double C_c=0.01;\n      double n_hpp_c=1;\n       \n      mat Y0;\n      uvec u_ids_vars_x;\n      if((*ids_vars_x_uni).n_rows>0){\n       u_ids_vars_x=join_cols(zeros<uvec>(1),conv_to< uvec >::from(*ids_vars_x_uni));\n       Y0=(*Y).cols(u_ids_vars_x);\n      }else{\n       Y0=(*Y).cols(0,0);\n      }\n    \n      str_input tab_input=data_preparation(&Y0,(*vretard));\n    \n      uli nvar_max=(uli)std::pow(tab_input.MY.n_rows,0.25);\n      \n      uli nr,nc;\n      Col<double> G_base_c;\n      bool univariate=0;\n      vec M_q;\n      field<mat> res;\n      uvec ids;\n      vec rvals;\n  \n      uli len_ar=(*vretard).n_rows;\n      vec ids_vars;\n  \n      mat M_G;\n      vec M_P;\n    \n      if((len_ar>0) | (Y0.n_cols>1)){\n    \t\n\t      nr=tab_input.corY_nr;\n        nc=tab_input.corY_nc;\n  \n        h_c=1; \n        if((nc-1)>50){\n         h_c=2; \n        } \n    \n        G_base_c=zeros<vec>(nc-1);\n        \n        res=FBF_RS(tab_input.corY,nr,G_base_c,h_c,C_c,n_tot_mod_c,n_hpp_c,univariate);\n        M_q=res(0,0);\n  \n\t      ids=find(M_q>=threshold);\n\t      if(ids.n_rows>nvar_max){\n          ids = sort_index(M_q,\"descend\");\n          ids=ids.rows(0,nvar_max-1);\n          ids=sort(ids);\n        }\n    \n        rvals=linspace<vec>(0,M_q.n_rows-1, M_q.n_rows).elem(ids);\n      \n        ids_vars=rvals-(Y0.n_cols-1);\n        vec ids_vars_ar=ids_vars(find(ids_vars>=0));\n        uvec fd_ids_vars=find(ids_vars<0);\n        if(fd_ids_vars.n_cols>0){\n         ids_vars_x=conv_to< Col<uli> >::from(rvals(fd_ids_vars));\n        }\n    \n\t      if(ids_vars.n_rows>0){\n          if(len_ar>0){\n            uvec u_ids_vars_ar=conv_to< uvec >::from(ids_vars_ar);\n            v_ar=(*vretard).rows(u_ids_vars_ar);\n          }\n          \n          uvec urvals=join_cols(zeros<uvec>(1),conv_to< uvec >::from(rvals+1));\n          tab_input.MY0=tab_input.MY0.cols(urvals);\n          tab_input.MY=tab_input.MY.cols(urvals);\n        \n          str_output_reg tab_out_reg=reg(tab_input.prt_MY0(),tab_input.prt_MY());\n          vbeta_arx=tab_out_reg.vbeta;\n          vresid=tab_out_reg.vresid0;\n        }else{\n\t    \t  vresid=Y0.col(0);\n          double m0=as_scalar(mean(vresid.rows(find_finite(vresid))));\n          for(uli t=0; t<vresid.n_rows; ++t){\n            vresid(t)=vresid(t)-m0;\n\t        }\n        }\n      }else{\n    \n        vresid=Y0.col(0);\n        double m0=as_scalar(mean(vresid.rows(find_finite(vresid))));\n        for(uli t=0; t<vresid.n_rows; ++t){\n         vresid(t)=vresid(t)-m0;\n        }\n      \n      }\n\n      if(ids_vars_x.size()>0){ \n       u_ids_vars_x=conv_to< uvec >::from(ids_vars_x);\n       ids_vars_x=(*ids_vars_x_uni).elem(u_ids_vars_x);\n      }\n    \n    }else{\n\n     vresid=(*Y).col(0);\n\n    }\n\n    str_out.resid=vresid;    \n    str_out.ids_vars_x=ids_vars_x;\n    str_out.ids_vars_ar=v_ar;\n    str_out.vbeta=vbeta_arx;\n\n    return(str_out); \n\n}\n\n\n\nmap<string,double> performances(vec vactual, vec vfitted, uli nvars){\n\n  vec vresid=vactual-vfitted;\n  uvec non_missing=find_finite(vresid);\n  vresid=vresid.elem(non_missing);   \n  //double RSS_=as_scalar(sum(pow(vresid,2)));\n  \n  vactual=vactual.elem(non_missing);\n  double m0=mean(vactual);\n  // Col<double> vTSS=vactual;\n  // for(uli i=0; i<vTSS.n_rows; ++i){\n  //  vTSS(i)=vTSS(i)-m0;\n  // }\n  // vTSS=pow(vTSS,2);\n  // double TSS=sum(vTSS);\n\n  // double R2 = 1 - (RSS/TSS);\n  // double R2_adj = 1 - (((double)vactual.n_rows-1)/((double)vactual.n_rows-(double)nvars-1))*(RSS/TSS); \n \n  //abs dist\n\n\n  double L1=as_scalar(sum(abs(vresid)));\n\n  double L0=0;\n  for(uli i=0; i<vactual.n_rows; ++i){\n   L0=L0+abs(vactual(i)-m0);\n  }  \n\n  double L=1-(L1/L0);\n\n  double L_adj=1 - (((double)vactual.n_rows-1)/((double)vactual.n_rows-(double)nvars-1))*(L1/L0);\n\n  map<string,double> res;\n  res[\"L\"]=L;\n  res[\"L_adj\"]=L_adj;\n\n  return(res);\n    \n}\n\n\n\nstruct str_pred_out\n{\n\n mat predictions;\n double L=datum::nan;   \n double L_adj=datum::nan;\n \n};\n\nstr_pred_out sarimax_pred(mat* Y, Col<uli> ids_vars_x, Col<uli> ids_vars_ar, vec vbeta_arx, Col<uli> ids_vars_ma, vec vbeta_ma, bool flg_sim, vec vfitted, vec probs, uli nsim)\n{\n\n  str_pred_out str_out;\n  vec vresid;   \n\n  if(flg_sim==1){ \n   vresid=(*Y).col(0)-vfitted;\n   vresid=vresid(find_finite(vresid));\n  }else{\n    nsim=1;\n  }\n\n  uli p=ids_vars_ar.n_rows;\n  uli q=ids_vars_ma.n_rows;  \n  uli k=vbeta_arx.n_rows-p; //number of regressors\n\n  uli maxpq=0;\n  if((p==0) & (q!=0)){\n    maxpq=ids_vars_ma.max();\n  }else if((p!=0) & (q==0)){\n    maxpq=ids_vars_ar.max();\n  }else if((p!=0) & (q!=0)){\n    maxpq=max(ids_vars_ar.max(),ids_vars_ma.max());\n  }\n  \n  vec vbeta_x;\n  vec vbeta_ar;\n\n  if(k>0){\n   vbeta_x=vbeta_arx.rows(0,k-1);\n  }\n  if(p>0){\n   vbeta_ar=vbeta_arx.rows(k,vbeta_arx.n_rows-1);\n  }\n  double tar;\n  double tma;\n  \n  mat Mout;\n  if(flg_sim==1){\n   Mout.resize(nsim,(*Y).n_rows);\n   Mout.fill(datum::nan);\n  }else{\n   Mout.resize((*Y).n_rows,2);\n  }\n  \n  double pred_arx=0;\n  double pred_ma=0;\n\n  vec veps((*Y).n_rows);\n\n  vec vy_pred((*Y).n_rows);\n\n  double pred_err;\n\n  uvec ut(1);\n  uvec uids_vars_x=conv_to<uvec>::from(ids_vars_x);\n\n  double eps_tma;\n\n  bool flg_na_ar=0;\n  bool flg_na_ma=0;\n\n  uli ri;\n  random_device rd; \n  //mt19937 gen(rd());\n  mt19937 gen(1234567);\n  uniform_int_distribution<> distrib(0, vresid.n_rows-1);\n\n  uli t0;\n\n  for(uli s=0; s<nsim; ++s){\n\n    vy_pred.fill(datum::nan);\n    veps.fill(datum::nan);\n\n    if(maxpq>0){\n     t0=(maxpq+1);\n    }else{\n     t0=0; \n    }\n    \n    for(uli t=t0; t<(*Y).n_rows; ++t){\n      \n      ut(0)=t;\n \n      //X\n      \n      if(k>0){\n       pred_arx=as_scalar((*Y).submat(ut,uids_vars_x)*vbeta_x);\n      }else{\n       pred_arx=0;\n      }\n\n      flg_na_ar=0;\n      flg_na_ma=0;\n  \n      //AR\n  \n      for(uli p0=0; p0<p; ++p0){\n       \n       tar=(double)t-(double)ids_vars_ar(p0);\n       \n       if(tar>0){\n        if(isfinite((*Y)(tar,0))){ \n         pred_arx=pred_arx+(*Y)(tar,0)*vbeta_ar(p0);\n        }else{\n         pred_arx=pred_arx+vy_pred(tar)*vbeta_ar(p0);\n        }\n        flg_na_ar=0;\n       }else{\n        pred_arx=0; \n        flg_na_ar=1;\n       }\n  \n      }\n\n      //MA\n  \n      if(q>0){\n      \n        pred_ma=0;\n    \n        for(uli q0=0; q0<q; ++q0){\n    \n         tma=(double)t-(double)ids_vars_ma(q0);\n    \n         if(tma>0){\n          eps_tma=veps(tma);\n          if(isfinite(eps_tma)){\n           pred_ma=pred_ma+eps_tma*vbeta_ma(q0);\n          }\n          flg_na_ma=0;\n         }else{\n          pred_ma=0;\n          flg_na_ma=1; \n         }\n    \n        }\n      \n      }\n\n      if((flg_na_ar==0) & (flg_na_ma==0)){\n       vy_pred(t)=pred_arx+pred_ma; \n      }else{\n       vy_pred(t)=datum::nan; \n      }\n      \n      if(flg_sim==1){\n        //vz=randi<uvec>(1,distr_param(0, vresid.n_rows-1)); RcppArmadillo bug\n        //pred_err=vresid(vz(0)); \n        ri=(uli) distrib(gen);\n        pred_err=vresid(ri);\n\n        if(isfinite((*Y)(t,0))){\n          veps(t)=(*Y)(t,0)-pred_arx;\n        }else{\n          veps(t)=pred_ma+pred_err;\n        }\n        \n        if((flg_na_ar==0) & (flg_na_ma==0)){\n         vy_pred(t)=pred_arx+pred_ma+pred_err; \n        }else{\n         vy_pred(t)=datum::nan; \n        }\n        Mout(s,t)=vy_pred(t);\n      }else{            \n        if(isfinite((*Y)(t,0))){\n          veps(t)=(*Y)(t,0)-pred_arx;\n        }else{\n          veps(t)=pred_ma;\n        }\n      }\n    \n    }\n    \n  }\n  \n  if(flg_sim==1){\n  \n   Mout=quantile(Mout,probs);\n   Mout=join_rows(vfitted,Mout.t());\n   Mout=join_rows((*Y).col(0),Mout);\n  \n  }else{\n   \n   Mout.col(0)=(*Y).col(0);\n   Mout.col(1)=vy_pred;\n\n  }\n\n  map<string,double> mp_idx_perf=performances((*Y).col(0), vy_pred, (uli)(ids_vars_x.n_rows+ids_vars_ar.n_rows+ids_vars_ma.n_rows));\n   \n  str_out.predictions=Mout;\n  str_out.L=mp_idx_perf[\"L\"];\n  str_out.L_adj=mp_idx_perf[\"L_adj\"];\n\n  return(str_out);\n\n}\n\n\nstruct str_model_out\n{\n  Col<uli> ids_vars_x;\n  Col<uli> ids_vars_ar;\n  Col<double> vbeta_arx;\n  Col<uli> ids_vars_ma;\n  Col<double> vbeta_ma;\n};  \n\n\nbool CheckVisited(map<vector<uli>,uli>* mv, vector<uli>* v)\n{\n  bool res=0;\n  if ((*mv).find(*v) != (*mv).end()) {\n    res=1;\n  }\n  return(res);\n}\n\npair < pair< vector<str_model_out>, vector<str_pred_out> > , mat > model_selection_prediction(mat* Y, double max_lag, vec probs, uli nsim)\n{\n        \n  pair < pair< vector<str_model_out>, vector<str_pred_out> > , mat > res_out;\n  \n  str_model_out res_out_i;\n  str_pred_out out_pred_i;\n\n  str_out_uni_select out_uni_select_arx;\n  str_out_multi_select out_multi_select_arx;\n\n  str_out_uni_select out_uni_select_ma;\n  str_out_multi_select out_multi_select_ma;\n  \n  map<vector<uli>,uli> visited_models;\n  \n  vec vresid;\n  vec vfitted, vfitted_empty;\n  Col<uli> vretard, vretard_empty, vretard1;\n  vector<uli> vtmp;\n  vector<double> vmin_ids_vars_ar;\n\n  bool flg_x_only=0;\n  if(max_lag==0){\n   flg_x_only=1; \n  }\n  \n  Col<uli> id_regressors;\n  uvec u_id_regressors;\n  \n  //SARIX\n  \n  out_uni_select_arx=model_univariate_selection(Y, &vretard, max_lag);\n  \n  if((flg_x_only==0) & (vretard.n_rows>0)){ //if is a sarimax\n     \n   for(double i=-1; i<(double)(vretard.size()-1); ++i){\n\n    vretard1=vretard;\n    if(i>=0){\n     vretard1.shed_rows(0,(uli)i);\n    }\n\n    out_multi_select_arx=model_multivariate_selection(Y, &out_uni_select_arx.vars_x_idx, &vretard1);\n\n    vtmp=conv_to< vector<uli> >::from(out_multi_select_arx.ids_vars_ar);   \n      \n    if(CheckVisited(&visited_models,&vtmp)==0){\n    \n       visited_models.insert(pair<vector<uli>,uli>(vtmp,0));\n\n       //MA\n\n       vresid=out_multi_select_arx.resid;\n       vretard1.clear();\n  \n       out_uni_select_ma=model_univariate_selection(&vresid, &vretard1, max_lag);\n       out_multi_select_ma=model_multivariate_selection(&vresid, &out_uni_select_ma.vars_x_idx, &vretard1);\n       \n       res_out_i.ids_vars_x=out_multi_select_arx.ids_vars_x;\n       res_out_i.ids_vars_ar=out_multi_select_arx.ids_vars_ar;\n       res_out_i.vbeta_arx=out_multi_select_arx.vbeta;\n       res_out_i.ids_vars_ma=out_multi_select_ma.ids_vars_ar;\n       res_out_i.vbeta_ma=out_multi_select_ma.vbeta;\n\n       res_out.first.first.push_back(res_out_i);\n  \n       if(out_multi_select_arx.ids_vars_ar.n_rows>0){\n        vmin_ids_vars_ar.push_back(out_multi_select_arx.ids_vars_ar.min());\n       }else{\n        vmin_ids_vars_ar.push_back(-1);\n       }\n\n       out_pred_i=sarimax_pred(Y, out_multi_select_arx.ids_vars_x, out_multi_select_arx.ids_vars_ar, out_multi_select_arx.vbeta, out_multi_select_ma.ids_vars_ar, out_multi_select_ma.vbeta, 0, vfitted_empty, probs, nsim);\n       vfitted=out_pred_i.predictions.col(1);\n       out_pred_i=sarimax_pred(Y, out_multi_select_arx.ids_vars_x, out_multi_select_arx.ids_vars_ar, out_multi_select_arx.vbeta, out_multi_select_ma.ids_vars_ar, out_multi_select_ma.vbeta, 1, vfitted, probs, nsim);\n\n       res_out.first.second.push_back(out_pred_i);\n\n       if(out_multi_select_arx.ids_vars_ar.n_rows==0){\n        break; \n       }\n  \n    }\n  \n   }//end for\n\n  }else{\n   \n   flg_x_only=1;\n\n  }\n\n  if(flg_x_only==1){\n    \n    out_multi_select_arx=model_multivariate_selection(Y, &out_uni_select_arx.vars_x_idx, &vretard_empty);\n\n    res_out_i.ids_vars_x=out_multi_select_arx.ids_vars_x;\n    res_out_i.ids_vars_ar=out_multi_select_arx.ids_vars_ar;\n    res_out_i.vbeta_arx=out_multi_select_arx.vbeta;\n    res_out_i.ids_vars_ma=out_multi_select_ma.ids_vars_ar;\n    res_out_i.vbeta_ma=out_multi_select_ma.vbeta;\n\n    res_out.first.first.push_back(res_out_i);\n    \n    out_pred_i=sarimax_pred(Y, out_multi_select_arx.ids_vars_x, out_multi_select_arx.ids_vars_ar, out_multi_select_arx.vbeta, out_multi_select_ma.ids_vars_ar, out_multi_select_ma.vbeta, 0, vfitted_empty, probs, nsim);\n    vfitted=out_pred_i.predictions.col(1);\n    out_pred_i=sarimax_pred(Y, out_multi_select_arx.ids_vars_x, out_multi_select_arx.ids_vars_ar, out_multi_select_arx.vbeta, out_multi_select_ma.ids_vars_ar, out_multi_select_ma.vbeta, 1, vfitted, probs, nsim);\n\n    res_out.first.second.push_back(out_pred_i);\n\n    res_out.second=out_pred_i.predictions;\n\n  }else{\n\n    uvec idx_tmp;\n    uli mod_sel;\n\n    vec vmin_ids_vars_ar_col=conv_to< vec >::from(vmin_ids_vars_ar);\n  \n    mat final_predictions=res_out.first.second[0].predictions;\n\n    double npred=0;\n    for(uli j=0; j<(*Y).n_rows; ++j){\n     \n     if(j>0){\n      if((isfinite((*Y)(j,0))==0) | ((isfinite((*Y)(j,0))==1) & (isfinite((*Y)(j-1,0))==0))){\n       npred=npred+1;\n      }else{\n       npred=0; \n      }\n     }else{\n      if(isfinite((*Y)(j,0))==0){\n       npred=npred+1;\n      }else{\n       npred=0; \n      }\n     } \n   \n     if(npred>1)\n     {\n      \n      if(vmin_ids_vars_ar_col(0)==-1){\n        mod_sel=0;\n      }else{\n        idx_tmp=find(vmin_ids_vars_ar_col>=npred);\n        if(idx_tmp.n_rows>0){\n         mod_sel=(uli) idx_tmp(0);\n        }else{\n         idx_tmp=find(vmin_ids_vars_ar_col<npred);\n         mod_sel=(uli) idx_tmp(idx_tmp.n_rows-1); \n        }\n      }\n      \n      final_predictions.row(j)=res_out.first.second[mod_sel].predictions.row(j);\n     \n     }\n\n    }//end for\n\n    res_out.second=final_predictions;\n  \n  }//end else\n\n  \n  return(res_out);\n\n\n}\n\nstruct str_output\n{\n\n mat predictions;\n double L=datum::nan;\n double L_adj=datum::nan;\n \n mat fw_predictions;\n vector<uli> fw_var_x_idx;\n vector<uli> fw_var_ar_idx;\n vector<uli> fw_var_ma_idx;\n double fw_L=datum::nan;   \n double fw_L_adj=datum::nan;\n\n mat bw_predictions;\n vector<uli> bw_var_x_idx;\n vector<uli> bw_var_ar_idx;\n vector<uli> bw_var_ma_idx;\n double bw_L=datum::nan;\n double bw_L_adj=datum::nan;\n\n};\n\nstr_output regpred_cpp(Mat<double>* Y, double max_lag, double alpha, uli nsim, bool flg_print, string direction=\"<->\")\n{\n    \n  str_model_out tab_model;\n  str_pred_out tab_pred;\n  str_output str_out;\n  \n  double pinf=(alpha/2);\n  double psup=1-(alpha/2);\n\n  vec probs={pinf, 0.5, psup};\n\n  vec vresid_empty;\n  vec vresid;\n  vec vfitted;\n\n  Col<uli> vtmp_uli;\n  map<string,double> mp_idx_perf;\n\n  uli nrows=(*Y).n_rows;\n  \n  mat Yr;\n  if((direction==\"<->\") | (direction==\"<-\")){ //do not move below\n   Yr=reverse((*Y),0);\n  }\n\n  uli bw_k=0, fw_k=0;\n\n  mat predictions, predictions_rev;\n\n  pair < pair< vector<str_model_out>, vector<str_pred_out> > , mat > out_sel_pred;\n\n  if((direction==\"<->\") | (direction==\"->\")){ \n                \n    //model selection\n    if(flg_print==1){\n     printA(\"Forward prediction: making model selection and prediction...\");\n    }\n            \n    out_sel_pred=model_selection_prediction(Y, max_lag, probs, nsim);\n\n    predictions=out_sel_pred.second;\n    \n    str_out.fw_predictions=predictions;\n    \n    str_out.fw_var_x_idx=conv_to< vector<uli> >::from(out_sel_pred.first.first[0].ids_vars_x);\n    \n    for(uli k=0; k<(uli)out_sel_pred.first.first.size(); ++k){\n     vtmp_uli=join_vert(vtmp_uli,out_sel_pred.first.first[k].ids_vars_ar);\n    }\n    str_out.fw_var_ar_idx=conv_to< vector<uli> >::from(unique(vtmp_uli));\n\n    for(uli k=0; k<(uli)out_sel_pred.first.first.size(); ++k){\n     vtmp_uli=join_vert(vtmp_uli,out_sel_pred.first.first[k].ids_vars_ma);\n    }\n    str_out.fw_var_ma_idx=conv_to< vector<uli> >::from(unique(vtmp_uli));\n\n    fw_k=(uli) (str_out.fw_var_x_idx.size() + str_out.fw_var_ar_idx.size() + str_out.fw_var_ma_idx.size());\n    \n    mp_idx_perf=performances(predictions.col(0), predictions.col(3), fw_k);\n\n    str_out.fw_L=mp_idx_perf[\"L\"];\n    str_out.fw_L_adj=mp_idx_perf[\"L_adj\"];\n         \n  }\n \n  if((direction==\"<->\") | (direction==\"<-\")){ \n                    \n    //model selection\n    if(flg_print==1){\n     printA(\"Backward prediction: making model selection and prediction...\");\n    }\n        \n    out_sel_pred=model_selection_prediction(&Yr, max_lag, probs, nsim);\n\n    predictions_rev=reverse(out_sel_pred.second);\n    \n    str_out.bw_predictions=predictions_rev;\n\n    str_out.bw_var_x_idx=conv_to< vector<uli> >::from(out_sel_pred.first.first[0].ids_vars_x);\n    \n    for(uli k=0; k<(uli)out_sel_pred.first.first.size(); ++k){\n     vtmp_uli=join_vert(vtmp_uli,out_sel_pred.first.first[k].ids_vars_ar);\n    }\n    str_out.bw_var_ar_idx=conv_to< vector<uli> >::from(unique(vtmp_uli));\n\n    for(uli k=0; k<(uli)out_sel_pred.first.first.size(); ++k){\n     vtmp_uli=join_vert(vtmp_uli,out_sel_pred.first.first[k].ids_vars_ma);\n    }\n    str_out.bw_var_ma_idx=conv_to< vector<uli> >::from(unique(vtmp_uli));\n\n    bw_k=(uli) (str_out.bw_var_x_idx.size() + str_out.bw_var_ar_idx.size() + str_out.bw_var_ma_idx.size());\n\n    mp_idx_perf=performances(predictions_rev.col(0), predictions_rev.col(3), bw_k);\n\n    str_out.bw_L=mp_idx_perf[\"L\"];\n    str_out.bw_L_adj=mp_idx_perf[\"L_adj\"];\n\n  }\n\n  //collapse\n  \n  if(direction==\"<-\"){\n    predictions=predictions_rev;\n  }\n\n  \n  if(direction==\"<->\"){\n\n   for(uli t=0; t<nrows; ++t){\n    for(uli k=1; k<4; ++k){\n     if(isfinite(predictions(t,1)) & isfinite(predictions_rev(t,1))){\n      predictions(t,1)=(predictions(t,1)+predictions_rev(t,1))/2;\n     }else if(isfinite(predictions_rev(t,1))){\n      predictions(t,1)=predictions_rev(t,1);\n     } \n    }      \n   }\n\n  }\n\n  str_out.predictions=predictions;\n         \n  mp_idx_perf=performances(predictions.col(0), predictions.col(3), max(bw_k,fw_k));\n\n  str_out.L=mp_idx_perf[\"L\"];\n  str_out.L_adj=mp_idx_perf[\"L_adj\"];\n  \n  if(flg_print==1){ \n   printA(\"Process ended successfully!\");\n  }\n  \n  return(str_out);\n\n}\n\n///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n//FUNCTION FOR PASSING RESULTS TO PYTHON AND R \n///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n\nmat  std_mat_to_arma_mat(vector< vector<double> >* A) {\n\n    uli nrows=(*A).size();\n    uli ncols=(*A)[0].size();\n    \n    mat V(nrows,ncols);\n    \n    for (uli j = 0; j < nrows; ++j) {\n     for (uli i = 0; i < ncols; ++i) {\n       V(j,i)=(*A)[j][i];\n     }\n    }\n   \n    return V;\n\n}\n\n\n#ifdef language_py\n\npair < pair < list< vector<uli> >, list< vector<string> > > , pair < list< vector< vector<double> > >, list< double> > > \nregpred_py(vector< vector<double> >& Y, double max_lag, double alpha, uli nsim, bool flg_print, string direction)\n{\n\n  pair < pair < list< vector<uli> >, list< vector<string> > > , pair < list< vector< vector<double> > >, list< double> > > res;\n  mat Y0=std_mat_to_arma_mat(&Y);\n  \n  str_output str_out=regpred_cpp(&Y0, max_lag, alpha, nsim, flg_print, direction);\n\n  res.first.first.push_back(str_out.fw_var_x_idx);\n  res.first.first.push_back(str_out.fw_var_ar_idx);\n  res.first.first.push_back(str_out.fw_var_ma_idx);\n  res.first.first.push_back(str_out.bw_var_x_idx);\n  res.first.first.push_back(str_out.bw_var_ar_idx);\n  res.first.first.push_back(str_out.bw_var_ma_idx);\n\n  // res.first.second.push_back(str_out.fw_var_x_names);\n  // res.first.second.push_back(str_out.bw_var_x_names);\n\n  res.second.first.push_back(arma_mat_to_std_mat(&str_out.predictions));\n  res.second.first.push_back(arma_mat_to_std_mat(&str_out.fw_predictions));\n  res.second.first.push_back(arma_mat_to_std_mat(&str_out.bw_predictions));\n  \n  res.second.second.push_back(str_out.L);\n  res.second.second.push_back(str_out.L_adj);\n  res.second.second.push_back(str_out.fw_L);\n  res.second.second.push_back(str_out.fw_L_adj);\n  res.second.second.push_back(str_out.bw_L);\n  res.second.second.push_back(str_out.bw_L_adj);\n  \n  return(res);\n\n}\n\n#endif\n\n#ifdef language_R\n\nNumericMatrix  arma_mat_to_num_mat(mat* A) {\n    \n  NumericMatrix  V((*A).n_rows,(*A).n_cols);\n    \n\tfor (size_t j = 0; j < (*A).n_rows; ++j) {\n     for (size_t i = 0; i < (*A).n_cols; ++i) {\n        V(j,i) =(*A)(j,i);\n     }\n\t};\n    \n    return V;\n}\n\nRcppExport SEXP regpred_R(SEXP Y_p, SEXP max_lag_p, SEXP alpha_p, SEXP nsim_p, SEXP flg_print_p, SEXP direction_p)\n{\n\n  NumericMatrix Y_0(Y_p); \n  mat Y(Y_0.begin(), Y_0.nrow(), Y_0.ncol(), false);\n  \n  NumericVector max_lag_0(max_lag_p); \n  double max_lag = Rcpp::as<double>(max_lag_0);\n  \n  NumericVector alpha_0(alpha_p); \n  double alpha = Rcpp::as<double>(alpha_0);\n  \n  NumericVector nsim_0(nsim_p); \n  uli nsim = Rcpp::as<uli>(nsim_0);\n  \n  NumericVector flg_print_0(flg_print_p); \n  bool flg_print = Rcpp::as<bool>(flg_print_0);\n\n  CharacterVector direction_0(direction_p); \n  string direction = Rcpp::as<string>(direction_0);\n\n  str_output str_out=regpred_cpp(&Y, max_lag, alpha, nsim, flg_print, direction);\n  \n  NumericMatrix predictions=arma_mat_to_num_mat(&str_out.predictions);\n  NumericMatrix fw_predictions=arma_mat_to_num_mat(&str_out.fw_predictions);\n  NumericMatrix bw_predictions=arma_mat_to_num_mat(&str_out.bw_predictions);\n\n  /*maximum 20 elements admitted for each level*/\n  List res=List::create(\n    Named(\"final\")=List::create(\n      Named(\"predictions\") = predictions,\n      Named(\"L\") = str_out.L,\n      Named(\"L_adj\") = str_out.L_adj\n    ),\n    Named(\"forward\")=List::create(\n      Named(\"predictions\") = fw_predictions,\n      Named(\"var_x_names\") = str_out.fw_var_x_idx, \n      Named(\"var_ar_idx\") = str_out.fw_var_ar_idx, \n      Named(\"var_ma_idx\") = str_out.fw_var_ma_idx,    \n      Named(\"L\") = str_out.fw_L,\n      Named(\"L_adj\") = str_out.fw_L_adj\n    ),\n    Named(\"backward\")=List::create( \n      Named(\"predictions\") = bw_predictions,\n      Named(\"var_x_names\") = str_out.bw_var_x_idx, \n      Named(\"var_ar_idx\") = str_out.bw_var_ar_idx, \n      Named(\"var_ma_idx\") = str_out.bw_var_ma_idx,    \n      Named(\"L\") = str_out.bw_L,\n      Named(\"L_adj\") = str_out.bw_L_adj\n    )\n  );\n\n  return(res);\n\n}\n\n#endif\n \n", "meta": {"hexsha": "6ad489cf93ce3ff1ac7a6f1fb027d6498d812a9b", "size": 42268, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "c++/functions.cpp", "max_stars_repo_name": "valeman/rego", "max_stars_repo_head_hexsha": "4a8b417fe59bb278f8efce5e30e34b56027d8080", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-01-08T21:53:36.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-08T21:53:36.000Z", "max_issues_repo_path": "c++/functions.cpp", "max_issues_repo_name": "valeman/rego", "max_issues_repo_head_hexsha": "4a8b417fe59bb278f8efce5e30e34b56027d8080", "max_issues_repo_licenses": ["MIT"], "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++/functions.cpp", "max_forks_repo_name": "valeman/rego", "max_forks_repo_head_hexsha": "4a8b417fe59bb278f8efce5e30e34b56027d8080", "max_forks_repo_licenses": ["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.9916753382, "max_line_length": 220, "alphanum_fraction": 0.5961247279, "num_tokens": 14004, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6261241772283034, "lm_q2_score": 0.5273165233795671, "lm_q1q2_score": 0.33016562433992086}}
{"text": "/*\n * Copyright 2018 James Dyer\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\"); you may not\n * use this file except in compliance with the License. You may obtain a copy of\n * the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n * License for the specific language governing permissions and limitations under\n * the License.\n *\n * This is being developed for the TANGO Project: http://tango-project.eu\n */\n\n#include \"HE1NDecrypter.h\"\n#include <json/json.h>\n#include <NTL/ZZ_p.h>\n\nvoid HE1NDecrypter::setKey(NTL::vec_ZZ& key)\n{\n    p = key[0];\n    kappa = key[1];\n};\n\nvoid HE1NDecrypter::readSecretsFromJSON(std::string& json)\n{\n\tJson::Value root;   // will contains the root value after parsing.\n\tJson::Reader reader;\n\tbool parsingSuccessful = reader.parse(json,root);\n\tif (parsingSuccessful){\n\t\tp = NTL::conv<NTL::ZZ>(root[\"p\"].asCString());\n\t\tkappa = NTL::conv<NTL::ZZ>(root[\"kappa\"].asCString());\n\t}\n};\n\nNTL::ZZ HE1NDecrypter::decrypt(NTL::ZZ_p& ciphertext)\n{\n\tNTL::ZZ ctext = rep(ciphertext);\n    return (ctext % p) % kappa;\n};\n\n", "meta": {"hexsha": "44d86d8adb968d58aaf0b22aa19330385d6070b3", "size": 1294, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/HE1NDecrypter.cpp", "max_stars_repo_name": "TANGO-Project/cryptsdc", "max_stars_repo_head_hexsha": "4428fc289c97818d58a8010593636c64bde56e82", "max_stars_repo_licenses": ["BSD-4-Clause-UC"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/HE1NDecrypter.cpp", "max_issues_repo_name": "TANGO-Project/cryptsdc", "max_issues_repo_head_hexsha": "4428fc289c97818d58a8010593636c64bde56e82", "max_issues_repo_licenses": ["BSD-4-Clause-UC"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/HE1NDecrypter.cpp", "max_forks_repo_name": "TANGO-Project/cryptsdc", "max_forks_repo_head_hexsha": "4428fc289c97818d58a8010593636c64bde56e82", "max_forks_repo_licenses": ["BSD-4-Clause-UC"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.1304347826, "max_line_length": 80, "alphanum_fraction": 0.7047913447, "num_tokens": 357, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6261241632752915, "lm_q2_score": 0.5273165233795671, "lm_q1q2_score": 0.33016561698226715}}
{"text": "#ifndef CMAESAG_HPP\n#define CMAESAG_HPP\n\n#include <vector>\n#include <string>\n#include <type_traits>\n#include <boost/serialization/list.hpp>\n#include <boost/serialization/set.hpp>\n#include <boost/serialization/vector.hpp>\n#include <boost/functional/hash.hpp>\n\n#include \"arch/ARLAgent.hpp\"\n#include \"bib/Seed.hpp\"\n#include \"bib/Utils.hpp\"\n#include <bib/MetropolisHasting.hpp>\n#include <bib/XMLEngine.hpp>\n#include <bib/Combinaison.hpp>\n#include \"cmaes_interface.h\"\n\ndouble expo_sum(const std::vector<double>& v){\n  double sum = 0.f;\n  for(double q : v)\n    sum += exp(q);\n  return sum;\n}\n\nclass PIDControllerLearn : public arch::ARLAgent<arch::AgentProgOptions> {\n public:\n  PIDControllerLearn(unsigned int _nb_motors, unsigned int _nb_sensors)\n    : arch::ARLAgent<arch::AgentProgOptions>(_nb_motors, _nb_sensors), nb_sensors(_nb_sensors), \n    current_param(dimension_problem())\n    {\n\n  }\n\n  virtual ~PIDControllerLearn() {\n    cmaes_exit(evo);\n    delete evo;\n    delete ac_informed_state;\n  }\n  \n  void print_final_best(){\n    LOG_DEBUG(cmaes_Get(evo, \"fbestever\"));\n    const double* parameters = cmaes_GetPtr(evo, \"xbestever\");\n    bib::Logger::PRINT_ELEMENTS(parameters, dimension_problem());\n  }\n  \n  uint dimension_problem(){\n//     return this->nb_motors * 3;\n//     return this->nb_motors * 2;\n//     return 2;\n    return 3;\n  }\n\n  const std::vector<double>& _run(double, const std::vector<double>& sensors,\n                                  bool, bool goal, bool) override {\n\n    //force a small perturbation\n    vector<double>* next_action = new std::vector<double>(this->nb_motors, 0.f);\n\n//     std::vector<double> test = {-2.53168, -0.20791, 0.15605, 0.35428, -0.02659, 0.32720, -1.81081, -0.28895, -0.18864, -2.23505, -0.37164, 0.78502, -3.05356, -0.38279, -0.68477, -0.50092, -0.57394, -0.45777};//best sum max\n//     std::vector<double> test = {-1.74053, 0.07579, 0.57802, -0.67090, -0.67155, 0.35731, -2.26236, 0.74043, -0.47473, -2.33031, -0.45227, 0.12848, -1.66925, 1.28023, -0.45736, 0.47006, -0.35110, 0.35893};\n    //         std::vector<double> test = {-2.05891, -0.52004, -0.12384};//best old\n//         std::vector<double> test = {-4.56065, -0.87200, 0.07312};//best sum max\n//     std::vector<double> test = {-2.59888, -0.47748, 0.09128};//best sum expo\n    std::vector<double> test = {-2.5, -0.5, 0.1};//best sum expo\n    uint k=0;\n    for(auto d : test)\n      current_param[k++]=d;\n    \n    uint y=0;\n    for(uint i=0; i<this->nb_motors; i++) {\n      uint st_index = ac_informed_state->at(i*2);\n      if(dimension_problem()== this->nb_motors * 2)\n        next_action->at(i) = (2.0f/M_PI) * atan(current_param[y]*sensors[st_index] + current_param[y+1] * sensors[st_index+1]);\n      else if(dimension_problem()== this->nb_motors * 3)\n        next_action->at(i) = (2.0f/M_PI) * atan(current_param[y]*sensors[st_index] + current_param[y+1] * sensors[st_index+1])*current_param[y+2];\n      else if(dimension_problem()==2)\n        next_action->at(i) = (2.0f/M_PI) * atan(current_param[0]*sensors[st_index] + current_param[1] * sensors[st_index+1]);\n      else if(dimension_problem()==3)\n        next_action->at(i) = (2.0f/M_PI) * atan(current_param[0]*sensors[st_index] + current_param[1] * sensors[st_index+1])*current_param[2];\n      \n      if(dimension_problem()==this->nb_motors * 2)\n        y+=2;\n      else if(dimension_problem()==this->nb_motors * 3)\n        y+=3;\n    }\n\n    for(uint i=0; i<ac_informed_state->size(); i++){\n      if(i % 2 == 0 && episode_score_max[i/2] < fabs(sensors[ac_informed_state->at(i)])){\n        episode_score_max[i/2] = fabs(sensors[ac_informed_state->at(i)]) ;\n      }\n      \n      if(i % 2 == 0) // current angles\n        episode_score += fabs(sensors[ac_informed_state->at(i)]);\n//       else // derivative less important\n//         episode_score += fabs(sensors[ac_informed_state->at(i)])*0.1;\n    }\n    \n//     small action noise\n    for (uint i = 0; i < next_action->size(); i++)\n      next_action->at(i) += bib::Utils::randin(-0.05f, 0.05f);\n    \n    if(goal)\n      episode_score += 100000;\n\n//  CMA-ES already implement exploration in parameter space\n    last_action.reset(next_action);\n\n    return *next_action;\n  }\n\n\n  void _unique_invoke(boost::property_tree::ptree* pt, boost::program_options::variables_map*) override {\n    ac_informed_state           = bib::to_array<uint>(pt->get<std::string>(\"devnn.ac_informed_state\"));\n    population                  = pt->get<uint>(\"agent.population\");\n    initial_deviation           = pt->get<double>(\"agent.initial_deviation\");\n\n    check_feasible = true;\n    racing = false;\n    error_count = 0;\n\n    try {\n      check_feasible = pt->get<bool>(\"agent.check_feasible\");\n    } catch(boost::exception const& ) {\n    }\n\n    try {\n      racing = pt->get<bool>(\"agent.racing\");\n    } catch(boost::exception const& ) {\n    }\n\n    episode = 0;\n\n    uint dimension = dimension_problem();\n    double* startx  = new double[dimension];\n    double* deviation  = new double[dimension];\n    for(uint j=0; j< dimension; j++) {\n      deviation[j] = initial_deviation;\n      startx[j] = j % 2 == 0 ? -2.f : -0.05f;\n    }\n\n    evo = new cmaes_t;\n    arFunvals = cmaes_init(evo, dimension, startx, deviation, 0, population, NULL/*\"config.cmaes.ini\"*/);\n    delete[] startx;\n    delete[] deviation;\n//     evo->sp.stopTolFun = 1e-150;\n//     evo->sp.stopTolFunHist = 1e-150;\n//     evo->sp.stopTolUpXFactor = 1e50;\n\n    printf(\"%s\\n\", cmaes_SayHello(evo));\n    new_population();\n    LOG_DEBUG(cmaes_Get(evo, \"lambda\") << \" \" << dimension << \" \" << population << \" \" << cmaes_Get(evo, \"N\"));\n    if (population < 2)\n      LOG_DEBUG(\"population too small, changed to : \" << (4+(int)(3*log((double)dimension))));\n  }\n\n  bool is_feasible(const double* parameters) {\n    for(uint i=0; i < (uint) cmaes_Get(evo, \"dim\"); i++)\n      if(fabs(parameters[i]) >= 50.f) {\n        return false;\n      }\n\n    return true;\n  }\n\n  void new_population() {\n    const char * terminate =  cmaes_TestForTermination(evo);\n    if(terminate) {\n      LOG_INFO(\"mismatch \"<< terminate);\n      error_count++;\n\n      if(error_count > 20 && racing) {\n        LOG_FILE(DEFAULT_END_FILE, \"-1\");\n        exit(0);\n      }\n    }\n    //ASSERT(!cmaes_TestForTermination(evo), \"mismatch \"<< cmaes_TestForTermination(evo));\n\n    current_individual = 0;\n    pop = cmaes_SamplePopulation(evo);\n\n    if(check_feasible) {\n      //check that the population is feasible\n      bool allfeasible = true;\n      for (int i = 0; i < cmaes_Get(evo, \"popsize\"); ++i)\n        while (!is_feasible(pop[i])) {\n          cmaes_ReSampleSingle(evo, i);\n          allfeasible = false;\n        }\n\n      if(!allfeasible)\n        LOG_INFO(\"non feasible solution produced\");\n    }\n  }\n\n  void _start_episode(const std::vector<double>&, bool) override {\n    episode_score = 0;\n    \n    episode_score_max.clear();\n    for(uint i=0; i<ac_informed_state->size(); i++)\n      if(i % 2 == 0){\n        episode_score_max.push_back(std::numeric_limits<double>::lowest());\n      }\n  }\n\n  void start_instance(bool learning) override {\n    last_action = nullptr;\n    scores.clear();\n\n    //put individual into NN\n    const double* parameters = nullptr;\n    if(learning || !cmaes_UpdateDistribution_done_once)\n      parameters = pop[current_individual];\n    else\n      parameters = cmaes_GetPtr(evo, \"xbestever\");\n\n    loadPolicyParameters(parameters);\n\n    if(learning)\n      episode++;\n  }\n\n  void end_episode(bool) override {\n    double sum = std::accumulate(episode_score_max.begin(), episode_score_max.end(), 0.f);\n//     double sum =expo_sum(episode_score_max);\n//     scores.push_back(episode_score);\n    scores.push_back(sum);\n  }\n\n  void end_instance(bool learning) override {\n    if(learning) {\n      arFunvals[current_individual] = std::accumulate(scores.begin(), scores.end(), 0.f) / scores.size();\n\n      current_individual++;\n      if(current_individual >= cmaes_Get(evo, \"lambda\")) {\n        cmaes_UpdateDistribution(evo, arFunvals);\n        cmaes_UpdateDistribution_done_once=true;\n        new_population();\n      }\n    }\n  }\n\n protected:\n  void _display(std::ostream& out) const override {\n    out << std::setw(8) << std::fixed << std::setprecision(5) << episode_score << \" \" << \n    std::accumulate(episode_score_max.begin(), episode_score_max.end(), 0.f) << \" \" << expo_sum(episode_score_max);\n  }\n\n  void _dump(std::ostream& out) const override {\n    out << std::setw(8) << std::fixed << std::setprecision(5) << episode_score << \" \" <<\n    std::accumulate(episode_score_max.begin(), episode_score_max.end(), 0.f) << \" \"<< expo_sum(episode_score_max); \n  }\n\n private:\n  void loadPolicyParameters(const double* parameters) {\n    for(uint i=0; i<current_param.size(); i++)\n      current_param[i]=parameters[i];\n  }\n\n private:\n  //initilized by constructor\n  uint nb_sensors;\n\n  //initialized by invoke\n  std::vector<uint>* ac_informed_state = nullptr;\n  std::vector<double> current_param;\n  uint population;\n  double initial_deviation;\n  bool check_feasible;\n  bool racing;\n  cmaes_t* evo;\n  double *arFunvals;\n  double episode_score;\n  std::vector<double> episode_score_max;\n\n  //internal mecanisms\n  std::shared_ptr<std::vector<double>> last_action;\n  std::list<double> scores;\n  double *const *pop;\n  bool cmaes_UpdateDistribution_done_once = false;\n  uint current_individual;\n  uint episode;\n  uint error_count;\n\n};\n\n#endif\n\n", "meta": {"hexsha": "8b3aa41206df0b3acaf8b223c360db332a31705c", "size": 9363, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "agent/cmaes/include/PIDControllerLearn.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/cmaes/include/PIDControllerLearn.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/cmaes/include/PIDControllerLearn.hpp", "max_forks_repo_name": "matthieu637/ddrl", "max_forks_repo_head_hexsha": "a454d09a3ac9be5db960ff180b3d075c2f9e4a70", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2019-05-16T09:14:15.000Z", "max_forks_repo_forks_event_max_datetime": "2019-08-15T14:35:40.000Z", "avg_line_length": 32.2862068966, "max_line_length": 225, "alphanum_fraction": 0.6374025419, "num_tokens": 2740, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6261241632752915, "lm_q2_score": 0.5273165233795671, "lm_q1q2_score": 0.33016561698226715}}
{"text": "#ifndef STAN_MATH_REV_MAT_FUN_QUAD_FORM_HPP\n#define STAN_MATH_REV_MAT_FUN_QUAD_FORM_HPP\n\n#include <boost/utility/enable_if.hpp>\n#include <boost/type_traits.hpp>\n#include <stan/math/rev/core.hpp>\n#include <stan/math/prim/mat/fun/Eigen.hpp>\n#include <stan/math/prim/mat/fun/typedefs.hpp>\n#include <stan/math/rev/mat/fun/typedefs.hpp>\n#include <stan/math/prim/mat/fun/value_of.hpp>\n#include <stan/math/prim/mat/fun/quad_form.hpp>\n#include <stan/math/prim/mat/err/check_multiplicable.hpp>\n#include <stan/math/prim/mat/err/check_square.hpp>\n#include <stan/math/prim/mat/err/check_symmetric.hpp>\n\nnamespace stan {\n  namespace math {\n\n    namespace {\n      template <typename TA, int RA, int CA, typename TB, int RB, int CB>\n      class quad_form_vari_alloc : public chainable_alloc {\n      private:\n        inline void compute(const Eigen::Matrix<double, RA, CA>& A,\n                            const Eigen::Matrix<double, RB, CB>& B) {\n          Eigen::Matrix<double, CB, CB> Cd(B.transpose()*A*B);\n          for (int j = 0; j < C_.cols(); j++) {\n            for (int i = 0; i < C_.rows(); i++) {\n              if (sym_) {\n                C_(i, j) = var(new vari(0.5*(Cd(i, j) + Cd(j, i)), false));\n              } else {\n                C_(i, j) = var(new vari(Cd(i, j), false));\n              }\n            }\n          }\n        }\n\n      public:\n        quad_form_vari_alloc(const Eigen::Matrix<TA, RA, CA>& A,\n                             const Eigen::Matrix<TB, RB, CB>& B,\n                             bool symmetric = false)\n          : A_(A), B_(B), C_(B_.cols(), B_.cols()), sym_(symmetric) {\n          compute(value_of(A), value_of(B));\n        }\n\n        Eigen::Matrix<TA, RA, CA>  A_;\n        Eigen::Matrix<TB, RB, CB>  B_;\n        Eigen::Matrix<var, CB, CB> C_;\n        bool sym_;\n      };\n\n      template <typename TA, int RA, int CA, typename TB, int RB, int CB>\n      class quad_form_vari : public vari {\n      protected:\n        inline void chainA(Eigen::Matrix<double, RA, CA>& A,\n                           const Eigen::Matrix<double, RB, CB>& Bd,\n                           const Eigen::Matrix<double, CB, CB>& adjC) {}\n        inline void chainB(Eigen::Matrix<double, RB, CB>& B,\n                           const Eigen::Matrix<double, RA, CA>& Ad,\n                           const Eigen::Matrix<double, RB, CB>& Bd,\n                           const Eigen::Matrix<double, CB, CB>& adjC) {}\n\n        inline void chainA(Eigen::Matrix<var, RA, CA>& A,\n                           const Eigen::Matrix<double, RB, CB>& Bd,\n                           const Eigen::Matrix<double, CB, CB>& adjC) {\n          Eigen::Matrix<double, RA, CA>     adjA(Bd*adjC*Bd.transpose());\n          for (int j = 0; j < A.cols(); j++) {\n            for (int i = 0; i < A.rows(); i++) {\n              A(i, j).vi_->adj_ += adjA(i, j);\n            }\n          }\n        }\n        inline void chainB(Eigen::Matrix<var, RB, CB>& B,\n                           const Eigen::Matrix<double, RA, CA>& Ad,\n                           const Eigen::Matrix<double, RB, CB>& Bd,\n                           const Eigen::Matrix<double, CB, CB>& adjC) {\n          Eigen::Matrix<double, RA, CA> adjB(Ad * Bd * adjC.transpose()\n                                             + Ad.transpose()*Bd*adjC);\n          for (int j = 0; j < B.cols(); j++)\n            for (int i = 0; i < B.rows(); i++)\n              B(i, j).vi_->adj_ += adjB(i, j);\n        }\n\n        inline void chainAB(Eigen::Matrix<TA, RA, CA>& A,\n                            Eigen::Matrix<TB, RB, CB>& B,\n                            const Eigen::Matrix<double, RA, CA>& Ad,\n                            const Eigen::Matrix<double, RB, CB>& Bd,\n                            const Eigen::Matrix<double, CB, CB>& adjC) {\n          chainA(A, Bd, adjC);\n          chainB(B, Ad, Bd, adjC);\n        }\n\n      public:\n        quad_form_vari(const Eigen::Matrix<TA, RA, CA>& A,\n                       const Eigen::Matrix<TB, RB, CB>& B,\n                       bool symmetric = false)\n          : vari(0.0) {\n          impl_\n            = new quad_form_vari_alloc<TA, RA, CA, TB, RB, CB>(A, B, symmetric);\n        }\n\n        virtual void chain() {\n          Eigen::Matrix<double, CB, CB> adjC(impl_->C_.rows(),\n                                             impl_->C_.cols());\n\n          for (int j = 0; j < impl_->C_.cols(); j++)\n            for (int i = 0; i < impl_->C_.rows(); i++)\n              adjC(i, j) = impl_->C_(i, j).vi_->adj_;\n\n          chainAB(impl_->A_, impl_->B_,\n                  value_of(impl_->A_), value_of(impl_->B_),\n                  adjC);\n        }\n\n        quad_form_vari_alloc<TA, RA, CA, TB, RB, CB> *impl_;\n      };\n    }\n\n    template <typename TA, int RA, int CA, typename TB, int RB, int CB>\n    inline typename\n    boost::enable_if_c< boost::is_same<TA, var>::value ||\n    boost::is_same<TB, var>::value,\n                        Eigen::Matrix<var, CB, CB> >::type\n      quad_form(const Eigen::Matrix<TA, RA, CA>& A,\n                const Eigen::Matrix<TB, RB, CB>& B) {\n      check_square(\"quad_form\", \"A\", A);\n      check_multiplicable(\"quad_form\",\n                          \"A\", A,\n                          \"B\", B);\n\n      quad_form_vari<TA, RA, CA, TB, RB, CB> *baseVari\n        = new quad_form_vari<TA, RA, CA, TB, RB, CB>(A, B);\n\n      return baseVari->impl_->C_;\n    }\n    template <typename TA, int RA, int CA, typename TB, int RB>\n    inline typename\n    boost::enable_if_c< boost::is_same<TA, var>::value ||\n    boost::is_same<TB, var>::value,\n                        var >::type\n      quad_form(const Eigen::Matrix<TA, RA, CA>& A,\n                const Eigen::Matrix<TB, RB, 1>& B) {\n      check_square(\"quad_form\", \"A\", A);\n      check_multiplicable(\"quad_form\",\n                          \"A\", A,\n                          \"B\", B);\n\n      quad_form_vari<TA, RA, CA, TB, RB, 1> *baseVari\n        = new quad_form_vari<TA, RA, CA, TB, RB, 1>(A, B);\n\n      return baseVari->impl_->C_(0, 0);\n    }\n\n  }\n}\n#endif\n", "meta": {"hexsha": "fca43b65ce0661f944545983ca0028b6801e1682", "size": 5966, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "cmdstan/stan/lib/stan_math/stan/math/rev/mat/fun/quad_form.hpp", "max_stars_repo_name": "yizhang-cae/torsten", "max_stars_repo_head_hexsha": "dc82080ca032325040844cbabe81c9a2b5e046f9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cmdstan/stan/lib/stan_math/stan/math/rev/mat/fun/quad_form.hpp", "max_issues_repo_name": "yizhang-cae/torsten", "max_issues_repo_head_hexsha": "dc82080ca032325040844cbabe81c9a2b5e046f9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cmdstan/stan/lib/stan_math/stan/math/rev/mat/fun/quad_form.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": 38.2435897436, "max_line_length": 80, "alphanum_fraction": 0.4902782434, "num_tokens": 1592, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7279754489059774, "lm_q2_score": 0.45326184801538616, "lm_q1q2_score": 0.32996349728095364}}
{"text": "/*!@file\n * @copyright This code is licensed under the 3-clause BSD license.\n *   Copyright ETH Zurich, Laboratory of Physical Chemistry, Reiher Group.\n *   See LICENSE.txt for details.\n */\n\n#include \"boost/program_options.hpp\"\n\n#include \"Molassembler/Shapes/ContinuousMeasures.h\"\n\n#include \"Molassembler/Shapes/Data.h\"\n#include \"Molassembler/Shapes/PropertyCaching.h\"\n\n#include \"boost/math/tools/minima.hpp\"\n#include \"Molassembler/Temple/constexpr/Numeric.h\"\n#include \"Molassembler/Temple/Adaptors/AllPairs.h\"\n#include \"Molassembler/Temple/Adaptors/Iota.h\"\n#include \"Molassembler/Temple/Functional.h\"\n#include \"Molassembler/Temple/Stringify.h\"\n#include \"Molassembler/Temple/Random.h\"\n#include \"Molassembler/Temple/constexpr/Jsf.h\"\n#include \"Molassembler/Temple/Permutations.h\"\n#include \"Molassembler/Temple/Loops.h\"\n\n#include <Eigen/SparseCore>\n#include <Eigen/Eigenvalues>\n#include <fstream>\n#include <iostream>\n#include <iomanip>\n#include <memory>\n#include <chrono>\n\n/* Summary\n *\n * This file contains a number of methods trying to cheapen finding the correct\n * vertex mapping to evaluate the continuous shape measure.\n *\n * Note that the problem does have some rotational redundancy depending on the\n * number of rotations that the shape has. But exploiting that gets you maybe\n * (N - 1)!. Crasser solutions are necessary.\n */\n\nusing namespace Scine;\nusing namespace Molassembler;\nusing namespace Shapes;\nusing namespace Continuous;\n\nconstexpr unsigned factorial(unsigned x) {\n  if(x <= 1) {\n    return 1;\n  }\n\n  return x * factorial(x - 1);\n}\n\ntemplate<std::size_t ... Inds>\nconstexpr auto makeFactorials(std::index_sequence<Inds ...> /* inds */) {\n  return std::array<unsigned, sizeof...(Inds)> {\n    factorial(Inds + 1)...\n  };\n}\n\nconstexpr auto facs = makeFactorials(std::make_index_sequence<14> {});\n\nContinuous::PositionCollection addOrigin(const Continuous::PositionCollection& vs) {\n  const unsigned N = vs.cols();\n  Continuous::PositionCollection positions(3, N + 1);\n  for(unsigned i = 0; i < N; ++i) {\n    positions.col(i) = vs.col(i);\n  }\n\n  // Add origin point explicitly to consideration\n  positions.col(N) = Eigen::Vector3d::Zero(3);\n  return positions;\n}\n\nvoid distort(Eigen::Ref<Continuous::PositionCollection> positions, const double distortionNorm = 0.01) {\n  const unsigned N = positions.cols();\n  for(unsigned i = 0; i < N; ++i) {\n    positions.col(i) += distortionNorm * Eigen::Vector3d::Random().normalized();\n  }\n}\n\ntemplate<typename Derived>\nbool centroidIsZero(const Eigen::MatrixBase<Derived>& a) {\n  assert(a.rows() == 3);\n  return (a.rowwise().sum() / a.cols()).squaredNorm() < 1e-8;\n}\n\ntemplate<typename DerivedA, typename DerivedB>\nEigen::Matrix3d fitQuaternion(const Eigen::MatrixBase<DerivedA>& stator, const Eigen::MatrixBase<DerivedB>& rotor) {\n  assert(centroidIsZero(stator));\n  assert(centroidIsZero(rotor));\n\n  Eigen::Matrix4d b = Eigen::Matrix4d::Zero();\n  // generate decomposable matrix per atom and add them\n  for (int i = 0; i < rotor.cols(); i++) {\n    auto& rotorCol = rotor.col(i);\n    auto& statorCol = stator.col(i);\n\n    Eigen::Matrix4d a = Eigen::Matrix4d::Zero();\n    a.block<1, 3>(0, 1) = (rotorCol - statorCol).transpose();\n    a.block<3, 1>(1, 0) = statorCol - rotorCol;\n    a.block<3, 3>(1, 1) = Eigen::Matrix3d::Identity().rowwise().cross(statorCol + rotorCol);\n    b += a.transpose() * a;\n  }\n\n  // Decompose b\n  Eigen::SelfAdjointEigenSolver<Eigen::Matrix4d> eigensolver(b);\n\n  // Do not allow improper rotation\n  const Eigen::Vector4d& q = eigensolver.eigenvectors().col(0);\n  return Eigen::Quaterniond(q[0], q[1], q[2], q[3]).toRotationMatrix();\n}\n\nusing Parameters = std::vector<Vertex>;\n\nstruct Energy {\n  const PositionCollection& referencePositions;\n  const PositionCollection& shapePositions;\n\n  double operator() (const Parameters& p) const {\n    const unsigned N = shapePositions.cols();\n\n    static PositionCollection permuted(3, N);\n    for(unsigned i = 0; i < N; ++i) {\n      permuted.col(i) = shapePositions.col(p[i]);\n    }\n\n    auto rotationMatrix = fitQuaternion(referencePositions, permuted);\n    permuted = rotationMatrix * permuted;\n\n    return (referencePositions - permuted).colwise().squaredNorm().sum();\n\n    // // Minimize over isotropic scaling factor\n    // auto scalingMinimizationResult = boost::math::tools::brent_find_minima(\n    //   [&](const double scaling) -> double {\n    //     return (referencePositions - scaling * permuted).colwise().squaredNorm().sum();\n    //   },\n    //   0.5,\n    //   1.1,\n    //   std::numeric_limits<double>::digits\n    // );\n\n    // return scalingMinimizationResult.second;\n  }\n};\n\nstruct OldShapeAlgorithm {\n  virtual ~OldShapeAlgorithm() = default;\n\n  static PositionCollection shapeCoordinates(const Shape shape) {\n    return normalize(addOrigin(coordinates(shape)));\n  }\n\n  virtual double shape(const PositionCollection& positions, Shape shape) = 0;\n  virtual std::string name() const = 0;\n};\n\n/**\n * @brief Abstract base class for algorithms to conform to\n */\nstruct ShapeAlgorithm {\n  virtual ~ShapeAlgorithm() = default;\n\n  using Permutation = std::vector<Vertex>;\n  using ResultPair = std::pair<double, Permutation>;\n\n  static Permutation invert(const Permutation& p) {\n    const unsigned P = p.size();\n    Permutation inverse(P);\n    for(unsigned i = 0; i < P; ++i) {\n      inverse.at(p.at(i)) = i;\n    }\n    return inverse;\n  }\n\n  /* A forwards permutation maps from positions to shape indices,\n   * a backwards permutation maps from shape indices to positions\n   *\n   * Only backwards permutations have the (added) centroid at the back, and\n   * hence their [O, S] = [0, N - 1] = [0, N) ranges can be rotated.\n   */\n  static std::set<ShapeAlgorithm::Permutation> generateRotations(\n    const Permutation& forwardsPermutation,\n    const Shape shape\n  ) {\n    auto backwards = ShapeAlgorithm::invert(forwardsPermutation);\n    Vertex centroid = backwards.back();\n    backwards.pop_back();\n    auto rotations = Properties::generateAllRotations(shape, backwards);\n\n    std::set<ShapeAlgorithm::Permutation> forwardsPermutationRotations;\n    for(auto rotation : rotations) {\n      rotation.push_back(centroid);\n      forwardsPermutationRotations.emplace(\n        ShapeAlgorithm::invert(rotation)\n      );\n    }\n    return forwardsPermutationRotations;\n  }\n\n  static PositionCollection shapeCoordinates(const Shape shape) {\n    return normalize(addOrigin(coordinates(shape)));\n  }\n\n  virtual ResultPair shape(\n    const PositionCollection& positions,\n    Shape shape,\n    const Permutation& correctPermutation\n  ) = 0;\n  virtual std::string name() const = 0;\n};\n\n/**\n * @brief Reference continuous shape measure calculation method\n *\n * Complexity: Theta(N!)\n */\nstruct AllPermutations {\n  ShapeAlgorithm::ResultPair shape(const PositionCollection& positions, Shape shape) {\n    Energy energy {positions, ShapeAlgorithm::shapeCoordinates(shape)};\n    ShapeAlgorithm::Permutation permutation = Temple::iota<Vertex>(Vertex(positions.cols()));\n    ShapeAlgorithm::ResultPair minimal {std::numeric_limits<double>::max(), {}};\n    do {\n      double permutationEnergy = energy(permutation);\n\n      if(permutationEnergy < minimal.first) {\n        minimal = {permutationEnergy, permutation};\n      }\n    } while(Temple::next_permutation(permutation));\n\n    return minimal;\n  }\n\n  std::string name() const {\n    return \"Reference\";\n  }\n};\n\nstruct Cooling {\n  // This works best for annealing and tunneling\n  static double linear(const unsigned step, const unsigned steps) {\n    return 1.0 - (static_cast<double>(step) / steps);\n  }\n\n  // This doesn't work well at all for annealing or tunneling, but it's here\n  static double exponential(const unsigned step, const unsigned steps) {\n    const double alpha = std::exp(std::log(1e-2) / steps);\n    return std::pow(alpha, step);\n  }\n};\n\n/**\n * @brief Simulated annealing method\n *\n * With well tuned temperature, this works pretty well, but it's stochastic in\n * nature and its good results are due to tracking the lowest energy state\n * visited instead of using the final annealing state. The energy surface for\n * small distortion norms is super jagged and the \"correct\" state has no\n * low-energy neighbors, making this type of approach problematic. Behaves\n * better for high distortion norms as there state space can be better sampled.\n *\n * Complexity: Needs at least O((N - 2)!) steps to explore enough state space\n * to encounter the minimum.\n */\nstruct Anneal final : OldShapeAlgorithm {\n  using Permutation = std::vector<Vertex>;\n\n  Temple::JSF64 prng;\n  std::ofstream trace {\"anneal_trace.csv\"};\n\n  Anneal() {\n    prng.seed(0);\n  }\n\n  static double acceptanceProbability(\n    const double energy,\n    const double prospectiveEnergy,\n    const double temperature\n  ) {\n    if(prospectiveEnergy < energy) {\n      return 1.0;\n    }\n\n    return std::exp(-(prospectiveEnergy - energy) / temperature);\n  }\n\n  static double temperature(const unsigned step, const unsigned steps) {\n    return Cooling::linear(step, steps);\n  }\n\n  //! Assumes temperature in 0, 1\n  Permutation generateMove(Permutation state, const double temperature) {\n    const unsigned N = state.size();\n\n    const unsigned nSwaps = 1 + std::round(temperature * Temple::Random::getSingle<unsigned>(0, N - 1, prng));\n    for(unsigned s = 0; s < nSwaps; ++s) {\n      const unsigned i = Temple::Random::getSingle<unsigned>(0, N - 2, prng);\n      std::swap(state.at(i), state.at(i + 1));\n    }\n\n    return state;\n  }\n\n  double shape(const PositionCollection& positions, Shape shape) final {\n    const unsigned steps = facs.at(positions.cols() - 2);\n    Energy energy {positions, shapeCoordinates(shape)};\n\n    auto parameters = Temple::iota<Vertex>(positions.cols());\n    decltype(parameters) prospectiveParameters;\n\n    double temperatureMultiplier = Temple::accumulate(\n      Temple::Adaptors::range(10),\n      0.0,\n      [&](const double carry, unsigned /* i */) -> double {\n        Temple::Random::shuffle(parameters, prng);\n        return carry + energy(parameters);\n      }\n    ) / 10;\n\n    double currentEnergy = energy(parameters);\n    double minimalEnergy = currentEnergy;\n    for(unsigned step = 0; step < steps; ++step) {\n      const double currentTemperature = temperature(step, steps);\n      prospectiveParameters = generateMove(parameters, currentTemperature);\n      const double prospectiveEnergy = energy(prospectiveParameters);\n      const double p = acceptanceProbability(currentEnergy, prospectiveEnergy, temperatureMultiplier * currentTemperature);\n\n      trace << step << \", \" << currentEnergy << \", \" << temperatureMultiplier * currentTemperature << \", \" << prospectiveEnergy << \", \" << p << \"\\n\";\n\n      if(p >= Temple::Random::getSingle(0.0, 1.0, prng)) {\n        std::swap(parameters, prospectiveParameters);\n        currentEnergy = prospectiveEnergy;\n      }\n\n      minimalEnergy = std::min(minimalEnergy, prospectiveEnergy);\n    }\n\n    return minimalEnergy;\n  }\n\n  std::string name() const final {\n    return \"Annealing\";\n  }\n};\n\n/**\n * @brief Stochastic tunneling method\n *\n * This works by transforming the energy function to level out minima that have\n * higher function values than the lowest found. This then should help losing\n * time in unhelpful minima.\n *\n * Works pretty well even when the temperature is not well tuned. You have to\n * adjust the gamma parameter for the particular problem you have, and the\n * value we have now works well for CShMs.\n *\n * But now that simulated annealing is well tuned and since there aren't really\n * and multi-state minima to get stuck in in this energy surface for small\n * distortions, this doesn't perform any better.\n *\n * The move generator for this and for simulated annealing generate multi-swap\n * moves for high temperatures and increase locality as the temperature is\n * lowered, generating only single adjacent swap moves.\n *\n * Complexity: Needs at least O((N - 2)!) steps to explore enough state space\n * to encounter the minimum.\n */\nstruct Tunnel final : OldShapeAlgorithm {\n  using Permutation = std::vector<Vertex>;\n\n  Temple::JSF64 prng;\n  std::ofstream trace {\"tunnel_trace.csv\"};\n  double gamma = 0.1;\n\n  Tunnel() {\n    prng.seed(0);\n  }\n\n  static double acceptanceProbability(\n    const double energy,\n    const double prospectiveEnergy,\n    const double temperature\n  ) {\n    if(prospectiveEnergy < energy) {\n      return 1.0;\n    }\n\n    return std::exp(-(prospectiveEnergy - energy) / temperature);\n  }\n\n  //! Assumes parameters are untransformed!\n  double energyTransformation(const double energy, const double lowestEnergy) const {\n    return 1.0 - std::exp(-gamma * (energy - lowestEnergy));\n  }\n\n  static double temperature(const unsigned step, const unsigned steps) {\n    return Cooling::linear(step, steps);\n  }\n\n  //! Assumes temperature in 0, 1\n  Permutation generateMove(Permutation state, const double temperature) {\n    const unsigned N = state.size();\n\n    const unsigned nSwaps = 1 + std::round(temperature * Temple::Random::getSingle<unsigned>(0, N - 1, prng));\n    for(unsigned s = 0; s < nSwaps; ++s) {\n      const unsigned i = Temple::Random::getSingle<unsigned>(0, N - 2, prng);\n      std::swap(state.at(i), state.at(i + 1));\n    }\n\n    return state;\n  }\n\n  double shape(const PositionCollection& positions, Shape shape) final {\n    const unsigned steps = facs.at(positions.cols() - 2);\n    Energy energy {positions, shapeCoordinates(shape)};\n\n    auto parameters = Temple::iota<Vertex>(positions.cols());\n    decltype(parameters) prospectiveParameters;\n\n    double currentEnergy = energy(parameters);\n    double lowestEnergy = currentEnergy;\n    double transformedCurrentEnergy = energyTransformation(currentEnergy, lowestEnergy);\n\n    for(unsigned step = 0; step < steps; ++step) {\n      const double currentTemperature = temperature(step, steps);\n      prospectiveParameters = generateMove(parameters, currentTemperature);\n      const double prospectiveEnergy = energy(prospectiveParameters);\n      const double transformedProspectiveEnergy = energyTransformation(prospectiveEnergy, lowestEnergy);\n      const double p = acceptanceProbability(transformedCurrentEnergy, transformedProspectiveEnergy, 0.7 * currentTemperature);\n\n      trace << step << \", \" << currentEnergy << \", \" << 0.7 * currentTemperature << \", \" << prospectiveEnergy << \", \" << p << \"\\n\";\n\n      if(p >= Temple::Random::getSingle(0.0, 1.0, prng)) {\n        std::swap(parameters, prospectiveParameters);\n        currentEnergy = prospectiveEnergy;\n        transformedCurrentEnergy = transformedProspectiveEnergy;\n      }\n\n      if(prospectiveEnergy < lowestEnergy) {\n        lowestEnergy = prospectiveEnergy;\n        transformedCurrentEnergy = energyTransformation(currentEnergy, lowestEnergy);\n      }\n    }\n\n    return lowestEnergy;\n  }\n\n  std::string name() const final {\n    return \"Tunneling\";\n  }\n};\n\ntemplate<typename T, std::size_t N>\nstruct CircularBuffer {\n  void insert(T value) {\n    if(size_ < N) {\n      buffer_[size_] = std::move(value);\n      ++size_;\n    } else {\n      buffer_[start_] = std::move(value);\n      start_ = (start_ + 1) % N;\n    }\n  }\n\n  T min() const {\n    assert(size_ > 0);\n    return *std::min_element(\n      std::begin(buffer_),\n      std::end(buffer_)\n    );\n  }\n\n  double average() const {\n    return static_cast<double>(\n      std::accumulate(\n        std::begin(buffer_),\n        std::end(buffer_),\n        T {0},\n        std::plus<>()\n      )\n    ) / size_;\n  }\n\n  double variance(const double average) const {\n    return static_cast<double>(\n      std::accumulate(\n        std::begin(buffer_),\n        std::end(buffer_),\n        T {0},\n        [&](const double carry, const double value) -> double {\n          return carry + std::pow(value - average, 2);\n        }\n      )\n    ) / size_;\n  }\n\n  void clear() {\n    size_ = 0;\n    start_ = 0;\n  }\n\n  std::size_t size() const {\n    return size_;\n  }\n\n  std::array<T, N> buffer_;\n  std::size_t start_ = 0;\n  std::size_t size_ = 0;\n};\n\n/**\n * @brief An attempt at thermodynamic simulated annealing\n *\n * In thermodynamic simulated annealing, you try to exploit statistical\n * mechanics / thermodynamics to drive your cooling schedule optimally.\n *\n * However, I couldn't ever get this to work. The temperature adjustments are\n * always too large and no amount of messing about ever got them right.\n *\n * Complexity: ???\n */\nstruct ThermodynamicAnneal final : OldShapeAlgorithm {\n  Temple::JSF64 prng;\n  using Permutation = std::vector<Vertex>;\n\n  std::unordered_map<unsigned, unsigned> stateIndexReduction;\n  std::vector<double> energies;\n  Eigen::SparseMatrix<unsigned> Q;\n  CircularBuffer<double, 1000> lastEnergies;\n  std::ofstream trace {\"thermo_trace.csv\"};\n\n  ThermodynamicAnneal() {\n    prng.seed(0);\n  }\n\n  static double acceptanceProbability(\n    const double energy,\n    const double prospectiveEnergy,\n    const double temperature\n  ) {\n    if(prospectiveEnergy < energy) {\n      return 1.0;\n    }\n\n    return std::exp(-(prospectiveEnergy - energy) / temperature);\n  }\n\n  //! Assumes temperature in 0, 100\n  Permutation generateMove(Permutation state, const double temperature) {\n    const unsigned N = state.size();\n\n    const unsigned nSwaps = 1 + std::round((temperature / 10) * Temple::Random::getSingle<unsigned>(0, N - 1, prng));\n    for(unsigned s = 0; s < nSwaps; ++s) {\n      const unsigned i = Temple::Random::getSingle<unsigned>(0, N - 2, prng);\n      std::swap(state.at(i), state.at(i + 1));\n    }\n\n    return state;\n  }\n\n  double partitionFunction(const double temperature) const {\n    return Temple::accumulate(\n      energies,\n      0.0,\n      [&](const double carry, const double energy) -> double {\n        return carry + std::exp(-energy / temperature);\n      }\n    );\n  }\n\n  template<typename F>\n  static double centralDifference(F&& f, const double x, const double h) {\n    return (\n      f(x + h) - f(x - h)\n    ) / (2 * h);\n  }\n\n  double averageEnergy(const double temperature) const {\n    // Estimate dln Z/dT by central finite difference\n    return temperature * temperature * centralDifference(\n      [&](const double x) { return std::log(partitionFunction(x)); },\n      temperature,\n      1e-4\n    );\n  }\n\n  double heatCapacity(const double temperature) const {\n    return centralDifference(\n      [&](const double x) { return averageEnergy(x); },\n      temperature,\n      1e-4\n    );\n  }\n\n  double relaxationTime(const double temperature) const {\n    // Q is strictly lower triangular (i.e. always access i > j)\n    Eigen::SparseMatrix<double> G(Q.rows(), Q.cols());\n    for(Eigen::Index k = 0; k < Q.outerSize(); ++k) {\n      // Sum up all values in Q's column\n      double sum = 0;\n      for(Eigen::SparseMatrix<unsigned>::InnerIterator it(Q,k); it; ++it) {\n        sum += it.value();\n      }\n\n      for(Eigen::SparseMatrix<unsigned>::InnerIterator it(Q,k); it; ++it) {\n        if(it.row() != it.col()) {\n          const double energyDiff = energies.at(it.row()) - energies.at(it.col());\n          if(energyDiff > 0) {\n            G.coeffRef(it.row(), it.col()) = it.value() * std::exp(-energyDiff / temperature);\n          } else {\n            G.coeffRef(it.row(), it.col()) = it.value();\n          }\n        }\n      }\n\n      // Diagonal entries of G are 1 - other column's entries\n      sum = 0;\n      for(Eigen::SparseMatrix<double>::InnerIterator it(G,k); it; ++it) {\n        sum += it.value();\n      }\n      G.coeffRef(k, k) = 1 - sum;\n    }\n\n    Eigen::SelfAdjointEigenSolver<Eigen::SparseMatrix<double>> solver(G);\n    return - 1.0 / solver.eigenvalues()(1);\n  }\n\n  double updateTemperature(const double temperature, double minimalEnergy) const {\n    const double hundredEnergiesAverage = lastEnergies.average();\n    const double hundredEnergiesVariance = lastEnergies.variance(hundredEnergiesAverage);\n    const double thermodynamicSpeed = (hundredEnergiesAverage - minimalEnergy) / hundredEnergiesVariance;\n\n    const double epsilon = relaxationTime(temperature);\n    const double C = heatCapacity(temperature);\n\n    double Theta = 1 + temperature * centralDifference([&](double x) { return heatCapacity(x);}, temperature, 1e-4) / (2 * C);\n    auto calculateDelta = [&](const double delta) {\n      double correction = std::sqrt(1 + (Theta * epsilon * delta) / temperature);\n      return - thermodynamicSpeed * temperature / (\n        epsilon * std::sqrt(C) * correction\n      );\n    };\n\n    // NOTE: this can diverge too :(\n    double delta = -1.0;\n    for(unsigned i = 0; i < 10; ++i) {\n      delta = calculateDelta(delta);\n    }\n\n    // NOTE 1e-5 is abitrary, the updates are always too large!\n    return std::max(0.0, temperature + 1e-5 * delta);\n  }\n\n  double shape(const PositionCollection& positions, Shape shape) final {\n    const unsigned steps = 5e5;\n\n    stateIndexReduction.clear();\n    energies.clear();\n    energies.reserve(100);\n    Q.resize(0,0);\n    Q.reserve(100);\n    lastEnergies.clear();\n\n    const unsigned N = positions.cols();\n    Energy energy {positions, shapeCoordinates(shape)};\n\n    auto permutation = Temple::iota<Vertex>(N);\n    decltype(permutation) prospectiveMove;\n    double currentEnergy = energy(permutation);\n    double minimalEnergy = currentEnergy;\n\n    unsigned iop = Temple::permutationIndex(permutation);\n    stateIndexReduction.emplace(iop, 0);\n    energies.push_back(currentEnergy);\n    unsigned currentStateIndex = 0;\n\n    double temperature = 10.0;\n\n    /* First 1000 steps of annealing without changing temperature to collect\n     * statistics we can use to update the temperature\n     */\n    unsigned step = 0;\n    for(; step < 1000; ++step) {\n      prospectiveMove = generateMove(permutation, temperature);\n      const double prospectiveEnergy = energy(prospectiveMove);\n      const double p = acceptanceProbability(currentEnergy, prospectiveEnergy, temperature);\n\n      iop = Temple::permutationIndex(prospectiveMove);\n      unsigned prospectiveStateIndex;\n      auto stateIndexFindIter = stateIndexReduction.find(iop);\n      if(stateIndexFindIter == std::end(stateIndexReduction)) {\n        prospectiveStateIndex = stateIndexReduction.size();\n        stateIndexReduction.emplace(iop, prospectiveStateIndex);\n        energies.push_back(prospectiveEnergy);\n        Q.conservativeResize(energies.size(), energies.size());\n        Q.insert(prospectiveStateIndex, currentStateIndex) = 1;\n      } else {\n        prospectiveStateIndex = stateIndexFindIter->second;\n        unsigned col = prospectiveStateIndex;\n        unsigned row = currentStateIndex;\n        if(col > row) {\n          std::swap(col, row);\n        }\n        Q.coeffRef(row, col) = Q.coeff(row, col) + 1;\n      }\n\n      trace << step << \", \" << currentEnergy << \", \" << temperature << \", \" << prospectiveEnergy << \", \" << p << \"\\n\";\n\n      if(p >= Temple::Random::getSingle(0.0, 1.0, prng)) {\n        std::swap(permutation, prospectiveMove);\n        currentEnergy = prospectiveEnergy;\n        currentStateIndex = prospectiveStateIndex;\n      }\n\n      minimalEnergy = std::min(minimalEnergy, prospectiveEnergy);\n      lastEnergies.insert(currentEnergy);\n    }\n\n    /* Now let temperature freely vary according to update formula */\n    while(temperature > 0.01 && step < steps) {\n      temperature = updateTemperature(temperature, minimalEnergy);\n      prospectiveMove = generateMove(permutation, temperature);\n      const double prospectiveEnergy = energy(prospectiveMove);\n      const double p = acceptanceProbability(currentEnergy, prospectiveEnergy, temperature);\n\n      /* Update tracking state */\n      iop = Temple::permutationIndex(prospectiveMove);\n      unsigned prospectiveStateIndex;\n      auto stateIndexFindIter = stateIndexReduction.find(iop);\n      if(stateIndexFindIter == std::end(stateIndexReduction)) {\n        prospectiveStateIndex = stateIndexReduction.size();\n        stateIndexReduction.emplace(iop, prospectiveStateIndex);\n        energies.push_back(prospectiveEnergy);\n        Q.conservativeResize(energies.size(), energies.size());\n        Q.insert(prospectiveStateIndex, currentStateIndex) = 1;\n      } else {\n        prospectiveStateIndex = stateIndexFindIter->second;\n        unsigned col = prospectiveStateIndex;\n        unsigned row = currentStateIndex;\n        if(col > row) {\n          std::swap(col, row);\n        }\n        Q.coeffRef(row, col) = Q.coeff(row, col) + 1;\n      }\n\n      trace << step << \", \" << currentEnergy << \", \" << temperature << \", \" << prospectiveEnergy << \", \" << p << \"\\n\";\n\n      // Conditionally accept the move\n      if(p >= Temple::Random::getSingle(0.0, 1.0, prng)) {\n        std::swap(permutation, prospectiveMove);\n        currentEnergy = prospectiveEnergy;\n        currentStateIndex = prospectiveStateIndex;\n      }\n\n      minimalEnergy = std::min(minimalEnergy, prospectiveEnergy);\n      lastEnergies.insert(currentEnergy);\n      ++step;\n    }\n\n    return minimalEnergy;\n  }\n\n  std::string name() const final {\n    return \"Thermodyn.\";\n  }\n};\n\n/**\n * @brief Fixed-step number greedy minimization with shuffling\n *\n * This just greedily minimizes the permutation and shuffles when it's at the\n * minimum. Unreliable.\n *\n * Complexity: Needs at least Theta(N - 2)! steps to discover enough state\n * space that it might find the minimum.\n */\nstruct Greedy final : OldShapeAlgorithm {\n  Temple::JSF64 prng;\n\n  double shape(const PositionCollection& positions, Shape shape) final {\n    const unsigned N = positions.cols();\n    const unsigned steps = 4 * facs.at(N - 2);\n\n    Energy energy {positions, shapeCoordinates(shape)};\n    auto permutation = Temple::iota<Vertex>(positions.cols());\n    double lowestEnergy = std::numeric_limits<double>::max();\n\n    bool foundBetterPermutation;\n    for(unsigned m = 0; m < steps; ++m) {\n      Temple::Random::shuffle(permutation, prng);\n      double minimizationEnergy = energy(permutation);\n\n      do {\n        foundBetterPermutation = false;\n\n        // Single swaps\n        for(unsigned i = 0; i < N - 1 && m < steps; ++i) {\n          for(unsigned j = i + 1; j < N && m < steps; ++j) {\n            std::swap(permutation.at(i), permutation.at(j));\n\n            double value = energy(permutation);\n            ++m;\n            if(value < minimizationEnergy) {\n              minimizationEnergy = value;\n              foundBetterPermutation = true;\n              break;\n            }\n\n            // Swap back\n            std::swap(permutation.at(i), permutation.at(j));\n          }\n        }\n\n        // Propose double-swaps\n        for(unsigned i = 0; i < N && !foundBetterPermutation; ++i) {\n          for(unsigned j = i + 1; j < N && !foundBetterPermutation; ++j) {\n            for(unsigned k = 0; k < N && k != i && !foundBetterPermutation; ++k) {\n              for(unsigned l = k + 1; l < N && l != j; ++l) {\n                std::swap(permutation.at(i), permutation.at(j));\n                std::swap(permutation.at(k), permutation.at(l));\n\n                // Calculate the value\n                double value = energy(permutation);\n                if(value < minimizationEnergy) {\n                  minimizationEnergy = value;\n                  foundBetterPermutation = true;\n                  break;\n                }\n                ++m;\n                if(m >= steps) {\n                  return std::min(lowestEnergy, minimizationEnergy);\n                }\n\n                // Swap back\n                std::swap(permutation.at(k), permutation.at(l));\n                std::swap(permutation.at(i), permutation.at(j));\n              }\n            }\n          }\n        }\n\n      } while(foundBetterPermutation);\n\n      lowestEnergy = std::min(lowestEnergy, minimizationEnergy);\n    }\n\n    return lowestEnergy;\n  }\n\n  std::string name() const final {\n    return \"Greedy\";\n  }\n};\n\n/**\n * @brief Fixed steps steepest descent minimizer with shuffles\n *\n * Finds best swap to reduce permutation the most at each position and\n * minimizes. Shuffles when it's at a minimum. Unreliable.\n *\n * Complexity: Needs at least Theta(N - 2)! steps to discover enough state\n * space that it might find the minimum.\n */\nstruct SteepestDescent final : OldShapeAlgorithm {\n  Temple::JSF64 prng;\n\n  double shape(const PositionCollection& positions, Shape shape) final {\n    const unsigned N = positions.cols();\n    const unsigned steps = 4 * facs.at(N - 2);\n\n    Energy energy {positions, shapeCoordinates(shape)};\n    auto bestCandidate = Temple::iota<Vertex>(positions.cols());\n    auto permutation = bestCandidate;\n    double lowestEnergy = std::numeric_limits<double>::max();\n\n    bool foundBetterPermutation;\n    for(unsigned m = 0; m < steps; ++m) {\n      Temple::Random::shuffle(bestCandidate, prng);\n      double minimizationEnergy = energy(bestCandidate);\n      lowestEnergy = std::min(lowestEnergy, minimizationEnergy);\n\n      do {\n        permutation = bestCandidate;\n        foundBetterPermutation = false;\n\n        // Propose double-swaps\n        for(unsigned i = 0; i < N && !foundBetterPermutation; ++i) {\n          for(unsigned j = i + 1; j < N && !foundBetterPermutation; ++j) {\n            for(unsigned k = 0; k < N && !foundBetterPermutation; ++k) {\n              for(unsigned l = k + 1; l < N; ++l) {\n                std::swap(permutation.at(i), permutation.at(j));\n                std::swap(permutation.at(k), permutation.at(l));\n\n                // Calculate the value\n                double value = energy(permutation);\n                ++m;\n                if(value < minimizationEnergy) {\n                  minimizationEnergy = value;\n                  foundBetterPermutation = true;\n                  bestCandidate = permutation;\n                }\n                if(m >= steps) {\n                  return std::min(lowestEnergy, minimizationEnergy);\n                }\n\n                // Swap back\n                std::swap(permutation.at(k), permutation.at(l));\n                std::swap(permutation.at(i), permutation.at(j));\n              }\n            }\n          }\n        }\n      } while(foundBetterPermutation);\n\n      lowestEnergy = std::min(lowestEnergy, minimizationEnergy);\n    }\n\n    return lowestEnergy;\n  }\n\n  std::string name() const final {\n    return \"Steepest\";\n  }\n};\n\n/**\n * @brief Aligns four atoms, then greedily zips the rest\n *\n * For each tuple of four atoms, aligns the positions, then greedily chooses\n * the best next sequence alignment.\n *\n * Really good for small distortions (<= 0.5). Suffers from its greediness\n * afterwards. Some branching might do it good.\n *\n * Complexity: Theta(N! / (N - 5)!) quaternion fits\n *\n * Potentially there is another optimization possible that could reduce the\n * scaling but there is a tradeoff involved that might counteract the formal\n * complexity decrease: Principally, spatial rotations of index mappings from\n * the underlying shape mappings need not be repeated. However, the question is\n * how to store them efficiently.\n */\nstruct AlignFive final : ShapeAlgorithm {\n  using M = Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic>;\n  using IncrementalPermutation = std::unordered_map<unsigned, unsigned>;\n\n  static Eigen::Matrix3d fitQuaternion(\n    const PositionCollection& stator,\n    const PositionCollection& rotor,\n    const IncrementalPermutation& p\n  ) {\n    assert(centroidIsZero(stator));\n    assert(centroidIsZero(rotor));\n\n    Eigen::Matrix4d b = Eigen::Matrix4d::Zero();\n    // generate decomposable matrix per atom and add them\n    for(auto& iterPair : p) {\n      auto& statorCol = stator.col(iterPair.first);\n      auto& rotorCol = rotor.col(iterPair.second);\n\n      Eigen::Matrix4d a = Eigen::Matrix4d::Zero();\n      a.block<1, 3>(0, 1) = (rotorCol - statorCol).transpose();\n      a.block<3, 1>(1, 0) = statorCol - rotorCol;\n      a.block<3, 3>(1, 1) = Eigen::Matrix3d::Identity().rowwise().cross(statorCol + rotorCol);\n      b += a.transpose() * a;\n    }\n\n    // Decompose b\n    Eigen::SelfAdjointEigenSolver<Eigen::Matrix4d> eigensolver(b);\n\n    // Do not allow improper rotation\n    const Eigen::Vector4d& q = eigensolver.eigenvectors().col(0);\n    return Eigen::Quaterniond(q[0], q[1], q[2], q[3]).toRotationMatrix();\n  }\n\n  static Permutation flatten(const IncrementalPermutation& p) {\n    const unsigned P = p.size();\n    Permutation flat(P);\n    for(unsigned i = 0; i < P; ++i) {\n      flat.at(i) = p.at(i);\n    }\n    return flat;\n  }\n\n  ResultPair narrow(\n    const PositionCollection& stator,\n    const PositionCollection& rotor,\n    const std::set<Permutation>& correctRotations,\n    bool inCorrectBranch,\n    std::unordered_map<unsigned, unsigned> permutation,\n    std::vector<unsigned> freeLeftVertices,\n    std::vector<unsigned> freeRightVertices\n  ) {\n    const unsigned N = stator.cols();\n\n    const unsigned V = freeLeftVertices.size();\n    Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> costs (V, V);\n    for(unsigned i = 0; i < V; ++i) {\n      for(unsigned j = 0; j < V; ++j) {\n        costs(i, j) = (\n          stator.col(freeLeftVertices.at(i))\n          - rotor.col(freeRightVertices.at(j))\n        ).squaredNorm();\n      }\n    }\n\n    // Maps freeLeftVertices onto freeRightVertices\n    auto subPermutation = Temple::iota<unsigned>(V);\n\n    auto isCorrectBranch = [&](const auto& s) {\n      return Temple::any_of(\n        correctRotations,\n        [&](const auto& rot) -> bool {\n          // Rotation has to match the current permutation\n          if(!Temple::all_of(\n            permutation,\n            [&](const unsigned left, const unsigned right) -> bool {\n              return rot.at(left) == right;\n            }\n          )) {\n            return false;\n          }\n\n          // Rotation has to match the sub-permutation too\n          for(unsigned i = 0; i < V; ++i) {\n            unsigned left = freeLeftVertices.at(i);\n            unsigned right = freeRightVertices.at(s.at(i));\n            if(rot.at(left) != right) {\n              return false;\n            }\n          }\n\n          return true;\n        }\n      );\n    };\n\n    decltype(subPermutation) bestPermutation;\n    double minimalCost = std::numeric_limits<double>::max();\n    do {\n      double cost = 0.0;\n      for(unsigned i = 0; i < V; ++i) {\n        cost += costs(i, subPermutation.at(i));\n      }\n\n      if(cost < minimalCost) {\n        if(inCorrectBranch && !bestPermutation.empty() && isCorrectBranch(bestPermutation) && !isCorrectBranch(subPermutation)) {\n          std::cerr << \"Excluding correct branch, decreasing cost from \" << minimalCost << \" to \" << cost << \" with non-optimum sub-permutation\\n\";\n        }\n\n        minimalCost = cost;\n        bestPermutation = subPermutation;\n      } else if(inCorrectBranch && isCorrectBranch(subPermutation)) {\n        std::cerr << \"Excluding correct branch due to cost \" << cost << \" > \" << minimalCost << \"\\n\";\n      }\n    } while(Temple::next_permutation(subPermutation));\n\n    // Fuse permutation and subpermutation\n    for(unsigned i = 0; i < V; ++i) {\n      permutation.emplace(freeLeftVertices.at(i), freeRightVertices.at(bestPermutation.at(i)));\n    }\n\n    assert(permutation.size() == N);\n\n    auto R = fitQuaternion(stator, rotor, permutation);\n    auto rotated = R * rotor;\n\n    const double energy = Temple::accumulate(\n      Temple::Adaptors::range(N),\n      0.0,\n      [&](const double carry, const unsigned i) -> double {\n        return carry + (\n          stator.col(i) - rotated.col(permutation.at(i))\n        ).squaredNorm();\n      }\n    );\n\n    return ResultPair {energy, flatten(permutation)};\n  }\n\n  ResultPair shape(\n    const PositionCollection& positions,\n    Shape shape,\n    const Permutation& correctPermutation\n  ) final {\n    const unsigned N = positions.cols();\n    if(N <= 4) {\n      return AllPermutations {}.shape(positions, shape);\n    }\n\n    const auto shapeCoords = shapeCoordinates(shape);\n\n    ResultPair minimal {std::numeric_limits<double>::max(), {}};\n    std::unordered_map<unsigned, unsigned> permutation;\n\n    const auto correctRotations = generateRotations(correctPermutation, shape);\n\n    // i != j != k != l != m with {i, j, k, l, m} in [0, N)\n    Temple::Loops::different(\n      [&](const std::vector<unsigned>& indices) {\n        permutation.clear();\n        for(unsigned i = 0; i < 5; ++i) {\n          permutation.emplace(i, indices[i]);\n        }\n\n        const unsigned i = indices[0];\n        const unsigned j = indices[1];\n        const unsigned k = indices[2];\n        const unsigned l = indices[3];\n        const unsigned m = indices[4];\n\n        Eigen::Matrix3d R = fitQuaternion(positions, shapeCoords, permutation);\n        auto rotatedShape = R * shapeCoords;\n\n        double penalty = (\n          (positions.col(0) - rotatedShape.col(i)).squaredNorm()\n          + (positions.col(1) - rotatedShape.col(j)).squaredNorm()\n          + (positions.col(2) - rotatedShape.col(k)).squaredNorm()\n          + (positions.col(3) - rotatedShape.col(l)).squaredNorm()\n          + (positions.col(4) - rotatedShape.col(m)).squaredNorm()\n        );\n\n        bool inCorrectBranch = Temple::any_of(\n          correctRotations,\n          [&](const auto& rot) {\n            return rot[0] == i && rot[1] == j && rot[2] == k && rot[3] == l && rot[4] == m;\n          }\n        );\n        if(inCorrectBranch) {\n          std::cerr << \"At correct permutation quintuple!\\n\";\n        }\n\n        if(penalty > minimal.first) {\n          return;\n        }\n\n        std::vector<unsigned> freeLeftVertices;\n        freeLeftVertices.reserve(N - 5);\n        for(unsigned a = 5; a < N; ++a) {\n          freeLeftVertices.push_back(a);\n        }\n        std::vector<unsigned> freeRightVertices;\n        freeRightVertices.reserve(N - 5);\n        for(unsigned a = 0; a < N; ++a) {\n          if(a != i && a != j && a != k && a != l && a != m) {\n            freeRightVertices.push_back(a);\n          }\n        }\n\n        auto narrowed = narrow(\n          positions,\n          rotatedShape,\n          correctRotations,\n          inCorrectBranch,\n          permutation,\n          std::move(freeLeftVertices),\n          std::move(freeRightVertices)\n        );\n\n        if(narrowed.first < minimal.first) {\n          minimal = narrowed;\n        }\n      },\n      5,\n      N\n    );\n\n    return minimal;\n  }\n\n  std::string name() const final {\n    return \"AlignFive\";\n  }\n};\n\nvoid writeEnergyStatistics() {\n  /* Write an R file with all of the energy values for a particular shape\n   */\n  std::ofstream rFile(\"energy_statistics.R\");\n  std::vector<Shape> shapes;\n  unsigned shapeNumber = 1;\n  for(const Shape shape : allShapes) {\n    if(size(shape) <= 4) {\n      continue;\n    }\n\n    if(size(shape) > 8) {\n      break;\n    }\n\n    std::cout << \"Number of permutations for \" << name(shape) << \" shape: \" << facs.at(size(shape)) << \"\\n\";\n\n    shapes.push_back(shape);\n\n    auto shapeCoordinates = normalize(addOrigin(coordinates(shape)));\n    const unsigned N = shapeCoordinates.cols();\n\n    auto distorted = shapeCoordinates;\n    const double distortionNorm = 0.2;\n    distort(distorted, distortionNorm);\n\n    Energy energy {shapeCoordinates, distorted};\n\n    rFile << \"shape\" << shapeNumber << \" <- c(\";\n    auto permutation = Temple::iota<Vertex>(N);\n    rFile << energy(permutation);\n    while(Temple::next_permutation(permutation)) {\n      rFile << \", \" << energy(permutation);\n    }\n    rFile << \")\\n\";\n\n    ++shapeNumber;\n  }\n\n  rFile << \"shapeNames <- c(\" << Temple::condense(Temple::map(shapes, [](auto s) { return \"\\\"\" + name(s) + \"\\\"\"; })) << \")\\n\";\n}\n\ntemplate<typename PRNG>\nPositionCollection shuffle(const PositionCollection& positions, PRNG& prng) {\n  const unsigned C = positions.cols();\n  auto permutation = Temple::iota<Vertex>(C);\n  Temple::Random::shuffle(permutation, prng);\n  PositionCollection shuffled(3, C);\n  for(unsigned i = 0; i < C; ++i) {\n    shuffled.col(permutation.at(i)) = positions.col(i);\n  }\n  return shuffled;\n}\n\nnamespace color {\n\nstd::ostream& boldMagenta(std::ostream& os) {\n  os << \"\\033[1;35m\";\n  return os;\n}\n\nstd::ostream& red(std::ostream& os) {\n  os << \"\\033[31m\";\n  return os;\n}\n\nstd::ostream& green(std::ostream& os) {\n  os << \"\\033[32m\";\n  return os;\n}\n\nstd::ostream& reset(std::ostream& os) {\n  os << \"\\033[0m\";\n  return os;\n}\n\n} // namespace color\n\nint main(int argc, char* argv[]) {\n  boost::program_options::options_description options_description(\"Recognized options\");\n  options_description.add_options()\n    (\"help,h\", \"Produce help message\")\n    (\n      \"prng,p\",\n      boost::program_options::value<int>(),\n      \"Seed to initialize PRNG with.\"\n    )\n    (\n      \"shape,s\",\n      boost::program_options::value<unsigned>(),\n      \"Shape to run algorithms with\"\n    )\n    (\n      \"distortion,d\",\n      boost::program_options::value<double>(),\n      \"Distortion norm to apply to shapes.\"\n    )\n    (\n      \"repeats,r\",\n      boost::program_options::value<unsigned>(),\n      \"Number of repetitions\"\n    )\n  ;\n\n  /* Parse */\n  boost::program_options::variables_map options_variables_map;\n  boost::program_options::store(\n    boost::program_options::command_line_parser(argc, argv).\n    options(options_description).\n    style(\n      boost::program_options::command_line_style::unix_style\n      | boost::program_options::command_line_style::allow_long_disguise\n    ).run(),\n    options_variables_map\n  );\n  boost::program_options::notify(options_variables_map);\n\n  if(options_variables_map.count(\"help\") > 0) {\n    std::cout << options_description << \"\\n\";\n    return 0;\n  }\n\n  using namespace std::chrono;\n\n  Temple::JSF64 prng;\n  if(options_variables_map.count(\"seed\")) {\n    const int seed = options_variables_map[\"seed\"].as<int>();\n    prng.seed(seed);\n    std::cout << \"PRNG seeded from parameters: \" << seed << \".\\n\";\n  } else {\n    std::random_device randomDevice;\n    const int seed = std::random_device {}();\n    std::cout << \"PRNG seeded from random_device: \" << seed << \".\\n\";\n    prng.seed(seed);\n  }\n\n  std::vector<std::unique_ptr<ShapeAlgorithm>> algorithmPtrs;\n  // algorithmPtrs.emplace_back(std::make_unique<Anneal>());\n  // algorithmPtrs.emplace_back(std::make_unique<Tunnel>());\n  // algorithmPtrs.emplace_back(std::make_unique<ThermodynamicAnneal>());\n  // algorithmPtrs.emplace_back(std::make_unique<Greedy>());\n  // algorithmPtrs.emplace_back(std::make_unique<SteepestDescent>());\n  // algorithmPtrs.emplace_back(std::make_unique<CentroidElimination>());\n  algorithmPtrs.emplace_back(std::make_unique<AlignFive>());\n\n  const unsigned nameColWidth = 12;\n  const unsigned timeColWidth = 6;\n  const unsigned repeats = (options_variables_map.count(\"repeats\") == 1)\n    ? options_variables_map[\"repeats\"].as<unsigned>()\n    : 10;\n  const double distortionNorm = (options_variables_map.count(\"distortion\") == 1)\n    ? options_variables_map[\"distortion\"].as<double>()\n    : 0.1;\n  Shape shape = Shape::CappedSquareAntiprism;\n  if(options_variables_map.count(\"shape\") == 1) {\n    unsigned shapeIndex = options_variables_map[\"shape\"].as<unsigned>();\n    if(shapeIndex < nShapes) {\n      shape = static_cast<Shape>(shapeIndex);\n    }\n  }\n\n  std::cout << \"For shape \" << name(shape) << \" (size \" << size(shape) << \") with distortion norm \" << distortionNorm << \"\\n\\n\";\n\n  AllPermutations referenceAlgorithm;\n  std::cout << std::setw(nameColWidth) << referenceAlgorithm.name() << std::setw(timeColWidth) << \"msec\";\n\n  for(auto& algorithmPtr : algorithmPtrs) {\n    std::cout << std::setw(nameColWidth) << algorithmPtr->name() << std::setw(timeColWidth) << \"msec\" << std::setw(timeColWidth) << \"S\";\n  }\n  std::cout << \"\\n\";\n\n  const unsigned A = algorithmPtrs.size();\n  std::vector<\n    std::vector<double>\n  > errors (A);\n\n  std::vector<\n    std::vector<double>\n  > latencies (A);\n\n  std::vector<\n    std::vector<double>\n  > speedups (A);\n\n  for(unsigned i = 0; i < repeats; ++i) {\n    auto coordinates = ShapeAlgorithm::shapeCoordinates(shape);\n    distort(coordinates, distortionNorm);\n    coordinates = normalize(shuffle(coordinates, prng));\n\n    time_point<steady_clock> start, end;\n    start = steady_clock::now();\n    const auto referencePair = referenceAlgorithm.shape(coordinates, shape);\n    end = steady_clock::now();\n    const unsigned referenceLatency = duration_cast<microseconds>(end - start).count();\n    std::cout << std::setw(nameColWidth) << referencePair.first << std::setw(timeColWidth) << (referenceLatency / 1000);\n    auto rotations = ShapeAlgorithm::generateRotations(referencePair.second, shape);\n\n    for(unsigned j = 0; j < A; ++j) {\n      auto& algorithmPtr = algorithmPtrs.at(j);\n      start = steady_clock::now();\n      const auto valuePair = algorithmPtr->shape(coordinates, shape, referencePair.second);\n      end = steady_clock::now();\n\n      if(valuePair.second != referencePair.second) {\n        std::cerr << \"\\n\" << std::setw(25) << \"Reference permutation\" << \" \" << Temple::condense(referencePair.second) << \"\\n\"\n          << std::setw(25) << algorithmPtr->name() << \" \" << Temple::condense(valuePair.second) << \"\\n\";\n        if(rotations.count(valuePair.second) == 1) {\n          std::cerr << \"Algorithm result is a shape rotation of the reference permutation\\n\";\n        } else {\n          std::cerr << \"Algorithm result is not a shape rotation of the reference permutation:\\n\";\n          for(const auto& rotation : rotations) {\n            std::cerr << \"Rotation \" << Temple::condense(rotation) << \"\\n\";\n          }\n        }\n      }\n\n      if(valuePair.first < referencePair.first - 1e-5) {\n        std::cout << color::boldMagenta << std::setw(nameColWidth) << valuePair.first << color::reset;\n      } else if(std::fabs(valuePair.first - referencePair.first) < 1e-5) {\n        std::cout << color::green << std::setw(nameColWidth) << valuePair.first << color::reset;\n      } else {\n        std::cout << color::red << std::setw(nameColWidth) << valuePair.first << color::reset;\n      }\n      errors.at(j).push_back(std::fabs(referencePair.first - valuePair.first));\n\n      unsigned latency = duration_cast<microseconds>(end - start).count();\n      std::cout << std::setw(timeColWidth) << (latency / 1000);\n      latencies.at(j).push_back(latency);\n\n      if(latency == 0) {\n        std::cout << std::setw(timeColWidth) << \"inf\";\n      } else {\n        std::cout << std::setw(timeColWidth) << std::round(static_cast<double>(referenceLatency) / latency);\n      }\n      speedups.at(j).push_back(static_cast<double>(referenceLatency) / latency);\n    }\n    std::cout << \"\\n\";\n  }\n\n  std::cout << \"\\n\";\n  std::cout << std::setw(nameColWidth + timeColWidth) << \"averages\";\n  for(unsigned j = 0; j < A; ++j) {\n    const double errorAverage = Temple::average(errors.at(j));\n    if(errorAverage < 1e-10) {\n      std::cout << color::green << std::setw(nameColWidth) << 0 << color::reset;\n    } else {\n      std::cout << color::red << std::setw(nameColWidth) << errorAverage << color::reset;\n    }\n\n    std::cout << std::setw(timeColWidth) << static_cast<unsigned>(Temple::average(latencies.at(j)) / 1000);\n    std::cout << std::setw(timeColWidth) << static_cast<unsigned>(Temple::average(speedups.at(j)));\n  }\n  std::cout << \"\\n\";\n}\n", "meta": {"hexsha": "7e2c785d16b27f0f0557da96b21aa6ad66047b12", "size": 46855, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "analysis/Shapes/shape.cpp", "max_stars_repo_name": "Dom1L/molassembler", "max_stars_repo_head_hexsha": "dafc656b1aa846b65b1fd1e06f3740ceedcf22db", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 17.0, "max_stars_repo_stars_event_min_datetime": "2020-11-27T14:59:34.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T10:31:25.000Z", "max_issues_repo_path": "analysis/Shapes/shape.cpp", "max_issues_repo_name": "Dom1L/molassembler", "max_issues_repo_head_hexsha": "dafc656b1aa846b65b1fd1e06f3740ceedcf22db", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "analysis/Shapes/shape.cpp", "max_forks_repo_name": "Dom1L/molassembler", "max_forks_repo_head_hexsha": "dafc656b1aa846b65b1fd1e06f3740ceedcf22db", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2020-12-09T09:21:53.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-22T15:42:21.000Z", "avg_line_length": 32.719972067, "max_line_length": 149, "alphanum_fraction": 0.6417884964, "num_tokens": 11415, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7279754489059775, "lm_q2_score": 0.4532618480153861, "lm_q1q2_score": 0.32996349728095364}}
{"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 SFERMIONS_H\n#define SFERMIONS_H\n\n#include <Eigen/Core>\n\nnamespace flexiblesusy {\nnamespace sfermions {\n\nenum Sparticles {\n   up = 0,\n   down = 1,\n   neutrino = 2,\n   electron = 3,\n   NUMBER_OF_MSSM_SPARTICLES\n};\n\nextern const double Isospin[NUMBER_OF_MSSM_SPARTICLES];\nextern const double Hypercharge_left[NUMBER_OF_MSSM_SPARTICLES];\nextern const double Hypercharge_right[NUMBER_OF_MSSM_SPARTICLES];\n\n\n/**\n * data needed to fill 2 x 2 sfermion mass matrix \n */ \nstruct Mass_data {\n   double ml2;    ///< soft mass of left-handed sfermion\n   double mr2;    ///< soft mass of right-handed sfermion\n   double yf;     ///< Yukawa coupling\n   double vd, vu; ///< Higgs VEVs\n   double gY, g2; ///< gauge couplings (not GUT normalized)\n   double Tyf;    ///< trilinear coupling\n   double mu;     ///< Superpotential parameter\n   double T3;     ///< weak isospin\n   double Yl;     ///< Hypercharge of left-handed sfermion\n   double Yr;     ///< Hypercharge of right-handed sfermion\n};\n\ndouble diagonalize_sfermions_2x2(const Mass_data&,\n                                 Eigen::Array<double,2,1>&);\n\n} // namespace sfermions\n} // namespace flexiblesusy\n\n#endif\n", "meta": {"hexsha": "f5830e4ed82d4c5dd4a9bebd563d1460a4c578cf", "size": 1995, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "contrib/MassSpectra/flexiblesusy/src/sfermions.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/sfermions.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/sfermions.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.6666666667, "max_line_length": 71, "alphanum_fraction": 0.6551378446, "num_tokens": 497, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7279754489059774, "lm_q2_score": 0.4532618480153861, "lm_q1q2_score": 0.3299634972809536}}
{"text": "/* Copyright 2016 Ramakrishnan Kannan */\n\n#ifndef DISTNMF_AUNMF_HPP_\n#define DISTNMF_AUNMF_HPP_\n\n#include <mpi.h>\n#include <armadillo>\n#include <string>\n#include <vector>\n#include <cstdio>\n#include <cmath>\n#include \"distnmf/distnmf.hpp\"\n#include \"distnmf/mpicomm.hpp\"\n\n/**\n * There are totally prxpc process.\n * Each process will hold the following\n * An A of size \\f$\\frac{globalm}{p_r} \\times \\frac{globaln}{p_c}\\f$\n * Here each process \\f$m=\\frac{globalm}{p_r} and n=\\frac{globaln}{p_c}\\f$\n * H of size \\f$\\frac{globaln}{p} \\times k\\f$\n * W of size \\f${globalm}{p} \\times k\\f$\n * A is \\f$m \\times n\\f$ matrix\n * H is \\f$n \\times k\\f$ matrix\n */\nnamespace planc {\n\ntemplate <class INPUTMATTYPE>\nclass DistAUNMF : public DistNMF<INPUTMATTYPE> {\n  // needed in derived algorithms to\n  // call BPP routines\n protected:\n  MAT HtH;    /// H is of size (globaln/p)*k;\n  MAT WtW;    /// W is of size (globaln/p)*k;\n  MAT AHtij;  /// AHtij is of size k*(globalm/p)\n  MAT WtAij;  /// WtAij is of size k*(globaln/p)\n  MAT Wt;     /// Wt is of size k*(globalm/p)\n  MAT Ht;     /// Ht is of size k*(globaln/p)\n\n  virtual void updateW() = 0;\n  virtual void updateH() = 0;\n\n private:\n  // Things needed while solving for W\n  MAT localHtH;         /// H is of size (globaln/p)*k;\n  MAT Hjt, Hj;          /// Hj is of size n*k;\n  MAT AijHj, AijHjt;    /// AijHj is of size m*k;\n  // INPUTMATTYPE A_ij_t;  /// n*m matrix. Transpose of A_ij\n  // Things needed while solving for H\n  MAT localWtW;        /// W is of size (globalm/p)*k;\n  MAT Wit, Wi;         /// Wi is of size m*k;\n  MAT WitAij, AijWit;  /// WijtAij is of size k*n;\n\n  // needed for error computation\n  MAT prevH;        // used for error computation\n  MAT prevHtH;      // used for error computation\n  MAT WtAijH;       /// global k*k matrix.\n  MAT localWtAijH;  /// local k*k matrix\n  MAT errMtx;\n  MAT A_errMtx;\n\n  // needed for symm regularization\n  MAT crossFac;     // holds the appropriate row of W,H\n  int paired_proc;  // processor to swap factors with\n\n  // needed for block implementation to save memory\n  MAT Ht_blk;\n  MAT AHtij_blk;\n  MAT Wt_blk;\n  MAT WtAij_blk;\n\n  // Gatherv and Reducescatter variables\n  std::vector<int> gatherWtAcnts;\n  std::vector<int> gatherWtAdisp;\n  std::vector<int> scatterWtAcnts;\n\n  std::vector<int> gatherAHcnts;\n  std::vector<int> gatherAHdisp;\n  std::vector<int> scatterAHcnts;\n\n  int num_k_blocks;\n  std::string relative_error_dir;\n  int perk;\n\n  /**\n   * Allocates matrices\n   */\n  void allocateMatrices() {\n    // collective call related initializations.\n    // These initialization are for solving W.\n    DISTPRINTINFO(\"k::\" << this->k << \"::perk::\" << this->perk\n                        << \"::localm::\" << this->m << \"::localn::\" << this->n\n                        << \"::globalm::\" << this->globalm() << \"::globaln::\"\n                        << this->globaln() << \"::MPI_SIZE::\" << MPI_SIZE);\n    HtH.zeros(this->k, this->k);\n    localHtH.zeros(this->k, this->k);\n    Hj.zeros(this->n, this->perk);\n    Hjt.zeros(this->perk, this->n);\n    AijHj.zeros(this->m, this->perk);\n    AijHjt.zeros(this->perk, this->m);\n    AHtij.zeros(this->k, this->W.n_rows);\n    this->scatterAHcnts.resize(NUMCOLPROCS);\n    int fillsize = this->perk * (this->W.n_rows);\n    fillVector<int>(fillsize, &scatterAHcnts);\n    this->gatherAHcnts.resize(NUMROWPROCS);\n    fillVector<int>(0, &gatherAHcnts);\n    this->gatherAHdisp.resize(NUMROWPROCS);\n    fillVector<int>(0, &gatherAHdisp);\n#ifdef MPI_VERBOSE\n    if (ISROOT) {\n      INFO << \"::recvAHsize::\";\n      printVector<int>(recvAHsize);\n    }\n#endif\n    // allocated for block implementation.\n    Ht_blk.zeros(this->perk, (this->W.n_rows));\n    AHtij_blk.zeros(this->perk, this->W.n_rows);\n\n    // These initialization are for solving H.\n    Wt.zeros(this->k, this->W.n_rows);\n    WtW.zeros(this->k, this->k);\n    localWtW.zeros(this->k, this->k);\n    Wi.zeros(this->m, this->perk);\n    Wit.zeros(this->perk, this->m);\n    WitAij.zeros(this->perk, this->n);\n    AijWit.zeros(this->n, this->perk);\n    WtAij.zeros(this->k, this->H.n_rows);\n    this->scatterWtAcnts.resize(NUMROWPROCS);\n    fillsize = this->perk * (this->H.n_rows);\n    fillVector<int>(fillsize, &scatterWtAcnts);\n    this->gatherWtAcnts.resize(NUMCOLPROCS);\n    fillVector<int>(0, &gatherWtAcnts);\n    this->gatherWtAdisp.resize(NUMCOLPROCS);\n    fillVector<int>(0, &gatherWtAdisp);\n\n    // allocated for block implementation\n    Wt_blk.zeros(this->perk, this->W.n_rows);\n    WtAij_blk.zeros(this->perk, this->H.n_rows);\n\n    // allocated for symmetric regularisation\n    if (this->symm_reg() > 0) {\n      crossFac.zeros(this->k, this->H.n_rows);\n    }\n#ifdef MPI_VERBOSE\n    if (ISROOT) {\n      INFO << \"::recvWtAsize::\";\n      printVector<int>(recvWtAsize);\n    }\n#endif\n#ifndef BUILD_SPARSE\n    if (this->is_compute_error()) {\n      errMtx.zeros(this->m, this->n);\n      A_errMtx.zeros(this->m, this->n);\n    }\n#endif\n  }\n\n  void freeMatrices() {\n    HtH.clear();\n    localHtH.clear();\n    Hj.clear();\n    Hjt.clear();\n    AijHj.clear();\n    AijHjt.clear();\n    AHtij.clear();\n    Wt.clear();\n    WtW.clear();\n    localWtW.clear();\n    Wi.clear();\n    Wit.clear();\n    WitAij.clear();\n    AijWit.clear();\n    WtAij.clear();\n    // A_ij_t.clear();\n    if (this->is_compute_error()) {\n      prevH.clear();\n      prevHtH.clear();\n      WtAijH.clear();\n      localWtAijH.clear();\n    }\n    Ht_blk.clear();\n    AHtij_blk.clear();\n    Wt_blk.clear();\n    WtAij_blk.clear();\n    if (this->symm_reg() > 0) {\n      crossFac.clear();\n    }\n    if (this->is_compute_error()) {\n      errMtx.clear();\n      A_errMtx.clear();\n    }\n  }\n\n  /**\n   * Sets up the communication pattern for the matrix multiplies\n  */\n  void setupCommcounts() {\n    // WtA\n    // Allgatherv counts\n    gatherWtAcnts[0] = itersplit(this->A.n_rows, NUMCOLPROCS, 0) * this->perk;\n    gatherWtAdisp[0] = 0;\n    for (int i = 1; i < NUMCOLPROCS; i++) {\n      gatherWtAcnts[i] = itersplit(this->A.n_rows,\n                                   NUMCOLPROCS, i) * this->perk;\n      gatherWtAdisp[i] = gatherWtAdisp[i-1] + gatherWtAcnts[i-1];\n    }\n    // Reducescatter counts\n    for (int i = 0; i < NUMROWPROCS; i++) {\n      scatterWtAcnts[i] = itersplit(this->A.n_cols,\n                                    NUMROWPROCS, i) * this->perk;\n    }\n    // AH\n    // Allgatherv counts\n    gatherAHcnts[0] = itersplit(this->A.n_cols, NUMROWPROCS, 0) * this->perk;\n    gatherAHdisp[0] = 0;\n    for (int i = 1; i < NUMROWPROCS; i++) {\n      gatherAHcnts[i] = itersplit(this->A.n_cols, NUMROWPROCS, i) * this->perk;\n      gatherAHdisp[i] = gatherAHdisp[i-1] + gatherAHcnts[i-1];\n    }\n    // Reducescatter counts\n    for (int i = 0; i < NUMCOLPROCS; i++) {\n      scatterAHcnts[i] = itersplit(this->A.n_rows,\n                                   NUMCOLPROCS, i) * this->perk;\n    }\n  }\n\n public:\n  /**\n   * Public constructor with local input matrix, local factors and communicator\n   * @param[in] local input matrix of size \\f$\\frac{globalm}{p_r} \\times \\frac{globaln}{p_c}\\f$.\n   *            Each process owns \\f$m=\\frac{globalm}{p_r}\\f$ and \\f$n=\\frac{globaln}{p_c}\\f$\n   * @param[in] local left low rank factor of size \\f$\\frac{globalm}{p} \\times k \\f$\n   * @param[in] local right low rank factor of size \\f$\\frac{globaln}{p} \\times k \\f$\n   * @param[in] MPICommunicator that has row and column communicators\n   * @param[in] numkblks. the columns of the local factor can further be\n   *            partitioned into numkblks\n   */\n  DistAUNMF(const INPUTMATTYPE &input, const MAT &leftlowrankfactor,\n            const MAT &rightlowrankfactor, const MPICommunicator &communicator,\n            const int numkblks, const std::string relerr_dir)\n      : DistNMF<INPUTMATTYPE>(input, leftlowrankfactor, rightlowrankfactor,\n                              communicator) {\n    num_k_blocks = numkblks;\n    relative_error_dir = relerr_dir;\n    perk = this->k / num_k_blocks;\n    allocateMatrices();\n    setupCommcounts();\n    this->Wt = leftlowrankfactor.t();\n    this->Ht = rightlowrankfactor.t();\n    // A_ij_t = input.t();\n    if (this->symm_reg() >= 0) {\n      // Get paired processor\n      int coords[2];\n      coords[0] = MPI_COL_RANK;\n      coords[1] = MPI_ROW_RANK;\n      MPI_Cart_rank(this->m_mpicomm.gridComm(), &coords[0], &paired_proc);\n      DISTPRINTINFO(\"rank::\" << MPI_RANK << \"::paired_proc::\" << paired_proc);\n    }\n    PRINTROOT(\"aunmf()::constructor succesful\");\n  }\n  ~DistAUNMF() {\n    // freeMatrices();\n  }\n\n  /**\n   * This is a matrix multiplication routine based on\n   * reduce_scatter.\n   * A is mxn in column major ordering\n   * W is mxk in column major ordering\n   * AtW is nxk in column major ordering\n   * There are totally p processes. Every process has\n   * A_i as m_i * n\n   * W_i as m_i * k\n   * AtW_i as n_i * k\n   * this->m_mpicomm.comm_subs()[0] is column communicator.\n   * this->m_mpicomm.comm_subs()[1] is row communicator.\n   */\n  void distWtA() {\n    for (int i = 0; i < num_k_blocks; i++) {\n      int start_row = i * perk;\n      int end_row = (i + 1) * perk - 1;\n      Wt_blk = Wt.rows(start_row, end_row);\n      distWtABlock();\n      WtAij.rows(start_row, end_row) = WtAij_blk;\n    }\n  }\n  void distWtABlock() {\n#ifdef USE_PACOSS\n    // Perform expand communication using Pacoss.\n    memcpy(Wit.memptr(), Wt_blk.memptr(),\n           Wt_blk.n_rows * Wt_blk.n_cols * sizeof(Wt_blk[0]));\n    MPITIC;\n    this->m_rowcomm->expCommBegin(Wit.memptr(), this->perk);\n    this->m_rowcomm->expCommFinish(Wit.memptr(), this->perk);\n#else\n    int sendcnt = (this->W.n_rows) * this->perk;\n    Wit.zeros();\n    MPITIC;  // allgather WtA\n    MPI_Allgatherv(Wt_blk.memptr(), sendcnt, MPI_DOUBLE, Wit.memptr(),\n                  &(gatherWtAcnts[0]), &(gatherWtAdisp[0]), MPI_DOUBLE,\n                  this->m_mpicomm.commSubs()[1]);\n#endif\n    double temp = MPITOC;  // allgather WtA\n    PRINTROOT(\"n::\" << this->n << \"::k::\" << this->k << PRINTMATINFO(Wt)\n                    << PRINTMATINFO(Wit));\n#ifdef MPI_VERBOSE\n    DISTPRINTINFO(PRINTMAT(Wt_blk));\n    DISTPRINTINFO(PRINTMAT(Wit));\n#endif\n    this->time_stats.communication_duration(temp);\n    this->time_stats.allgather_duration(temp);\n    MPITIC;  // mm WtA\n    this->WitAij = this->Wit * this->A;\n    // #if defined(MKL_FOUND) && defined(BUILD_SPARSE)\n    //     // void ARMAMKLSCSCMM(const SRC &mklMat, const DESTN &Bt, const char\n    //     transa,\n    //     //               DESTN *Ct)\n    //     ARMAMKLSCSCMM(this->A_ij_t, 'N', this->Wit, this->AijWit.memptr());\n    // #ifdef MPI_VERBOSE\n    //     DISTPRINTINFO(PRINTMAT(this->AijWit));\n    // #endif\n    //     this->WitAij = reshape(this->AijWit, this->k, this->n);\n    // #else\n    //     this->WitAij = this->Wit * this->A;\n    // #endif\n    temp = MPITOC;  // mm WtA\n#ifdef MPI_VERBOSE\n    DISTPRINTINFO(PRINTMAT(this->WitAij));\n#endif\n    PRINTROOT(PRINTMATINFO(this->A)\n              << PRINTMATINFO(this->Wit) << PRINTMATINFO(this->WitAij));\n    this->time_stats.compute_duration(temp);\n    this->time_stats.mm_duration(temp);\n    this->reportTime(temp, \"WtA::\");\n#ifdef USE_PACOSS\n    // Perform fold communication using Pacoss.\n    MPITIC;\n    this->m_colcomm->foldCommBegin(WitAij.memptr(), this->perk);\n    this->m_colcomm->foldCommFinish(WitAij.memptr(), this->perk);\n    temp = MPITOC;\n    memcpy(WtAij_blk.memptr(), WitAij.memptr(),\n           WtAij_blk.n_rows * WtAij_blk.n_cols * sizeof(WtAij_blk[0]));\n#else\n    WtAij_blk.zeros();\n    MPITIC;  // reduce_scatter WtA\n    MPI_Reduce_scatter(this->WitAij.memptr(), this->WtAij_blk.memptr(),\n                       &(scatterWtAcnts[0]), MPI_DOUBLE, MPI_SUM,\n                       this->m_mpicomm.commSubs()[0]);\n    temp = MPITOC;  // reduce_scatter WtA\n#endif\n    this->time_stats.communication_duration(temp);\n    this->time_stats.reducescatter_duration(temp);\n  }\n  /**\n   * There are totally prxpc process.\n   * Each process will hold the following\n   * An A of size (m/pr) x (n/pc)\n   * H of size (n/p)xk\n   * find AHt kx(m/p) by reducing and scatter it using MPI_Reduce_scatter call.\n   * That is, p process will hold a kx(m/p) matrix.\n   * this->m_mpicomm.comm_subs()[0] is column communicator.\n   * this->m_mpicomm.comm_subs()[1] is row communicator.\n   * To preserve the memory for Hj, we collect only partial k\n   */\n  void distAH() {\n    for (int i = 0; i < num_k_blocks; i++) {\n      int start_row = i * perk;\n      int end_row = (i + 1) * perk - 1;\n      Ht_blk = Ht.rows(start_row, end_row);\n      distAHBlock();\n      AHtij.rows(start_row, end_row) = AHtij_blk;\n    }\n  }\n  void distAHBlock() {\n    /*\n    DISTPRINTINFO(\"distAH::\" << \"::Acolst::\" \\\n                  Acolst.n_rows<<\"x\"<<Acolst.n_cols \\\n                  << \"::norm::\" << arma::norm(Acolst, \"fro\"));\n    DISTPRINTINFO(\"distAH::\" << \"::H::\" \\\n                  << this->H.n_rows << \"x\" << this->H.n_cols);\n    */\n#ifdef USE_PACOSS\n    // Perform expand communication using Pacoss.\n    memcpy(Hjt.memptr(), Ht_blk.memptr(),\n           Ht_blk.n_rows * Ht_blk.n_cols * sizeof(Ht_blk[0]));\n    MPITIC;\n    this->m_colcomm->expCommBegin(Hjt.memptr(), this->perk);\n    this->m_colcomm->expCommFinish(Hjt.memptr(), this->perk);\n#else\n    int sendcnt = (this->H.n_rows) * this->perk;\n    Hjt.zeros();\n    MPITIC;  // allgather AH\n    MPI_Allgatherv(this->Ht_blk.memptr(), sendcnt, MPI_DOUBLE,\n                  this->Hjt.memptr(), &(gatherAHcnts[0]), &(gatherAHdisp[0]),\n                  MPI_DOUBLE, this->m_mpicomm.commSubs()[0]);\n#endif\n    PRINTROOT(\"n::\" << this->n << \"::k::\" << this->k << PRINTMATINFO(Ht)\n                    << PRINTMATINFO(Hjt));\n    double temp = MPITOC;  // allgather AH\n#ifdef MPI_VERBOSE\n    DISTPRINTINFO(PRINTMAT(Ht_blk));\n    DISTPRINTINFO(PRINTMAT(Hjt));\n    // DISTPRINTINFO(PRINTMAT(this->A_ij_t));\n#endif\n    this->time_stats.communication_duration(temp);\n    this->time_stats.allgather_duration(temp);\n    MPITIC;  // mm AH\n/*\n#ifdef BUILD_SPARSE\n    this->Hj = this->Hjt.t();\n    this->AijHj = this->A * this->Hj;\n    this->AijHjt = this->AijHj.t();\n#else\n    this->AijHjt = this->Hjt * this->A.t();\n#endif\nMore memory efficient to rewrite code as above since A.t() will construct a\ncopy of the A in the sparse case. However sparse x dense matmul is much slower\nthan in dense x sparse. Keeping current version for performance reasons.\n*/\n    this->AijHjt = this->Hjt * this->A.t();\n    // #if defined(MKL_FOUND) && defined(BUILD_SPARSE)\n    //     // void ARMAMKLSCSCMM(const SRC &mklMat, const DESTN &Bt, const char\n    //     transa,\n    //     //               DESTN *Ct)\n    //     ARMAMKLSCSCMM(this->A, 'N', this->Hjt, this->AijHj.memptr());\n    // #ifdef MPI_VERBOSE\n    //     DISTPRINTINFO(PRINTMAT(this->AijHj));\n    // #endif\n    //     this->AijHjt = reshape(this->AijHj, this->k, this->m);\n    // #else\n    //     this->AijHjt = this->Hjt * this->A_ij_t;\n    // #endif\n    // #ifdef MPI_VERBOSE\n    //     DISTPRINTINFO(PRINTMAT(this->AijHjt));\n    // #endif\n    temp = MPITOC;  // mm AH\n    // PRINTROOT(PRINTMATINFO(this->A_ij_t)\n    PRINTROOT(PRINTMATINFO(this->Hjt) << PRINTMATINFO(this->AijHjt));\n    this->time_stats.compute_duration(temp);\n    this->time_stats.mm_duration(temp);\n    this->reportTime(temp, \"AH::\");\n#ifdef USE_PACOSS\n    // Perform fold communication using Pacoss.\n    MPITIC;\n    this->m_rowcomm->foldCommBegin(AijHjt.memptr(), this->perk);\n    this->m_rowcomm->foldCommFinish(AijHjt.memptr(), this->perk);\n    temp = MPITOC;\n    memcpy(AHtij_blk.memptr(), AijHjt.memptr(),\n           AHtij_blk.n_rows * AHtij_blk.n_cols * sizeof(AHtij_blk[0]));\n#else\n    AHtij_blk.zeros();\n    MPITIC;  // reduce_scatter AH\n    MPI_Reduce_scatter(this->AijHjt.memptr(), this->AHtij_blk.memptr(),\n                       &(this->scatterAHcnts[0]), MPI_DOUBLE, MPI_SUM,\n                       this->m_mpicomm.commSubs()[1]);\n    temp = MPITOC;  // reduce_scatter AH\n#endif\n    this->time_stats.communication_duration(temp);\n    this->time_stats.reducescatter_duration(temp);\n  }\n  /**\n   * There are p processes.\n   * Every process i has W in m_i * k\n   * At the end of this call, all process will have\n   * WtW of size k*k is symmetric. So not to worry\n   * about column/row major formats.\n   * @param[in] X is of size m_i x k\n   * @param[out] XtX Every process owns the same kxk global gram matrix of X\n   */\n  void distInnerProduct(const MAT &X, MAT *XtX) {\n    // each process computes its own kxk matrix\n    MPITIC;  // gram\n    localWtW = X.t() * X;\n#ifdef MPI_VERBOSE\n    DISTPRINTINFO(\"W::\" << norm(X, \"fro\")\n                        << \"::localWtW::\" << norm(this->localWtW, \"fro\"));\n#endif\n    double temp = MPITOC;  // gram\n    this->time_stats.compute_duration(temp);\n    this->time_stats.gram_duration(temp);\n    (*XtX).zeros();\n    if (X.n_rows == this->m) {\n      this->reportTime(temp, \"Gram::W::\");\n    } else {\n      this->reportTime(temp, \"Gram::H::\");\n    }\n    MPITIC;  // allreduce gram\n    MPI_Allreduce(localWtW.memptr(), (*XtX).memptr(), this->k * this->k,\n                  MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);\n    temp = MPITOC;  // allreduce gram\n    this->time_stats.communication_duration(temp);\n    this->time_stats.allreduce_duration(temp);\n  }\n  /**\n   * This is the main loop function\n   * Refer Algorithm 1 in Page 3 of\n   * the PPoPP HPC-NMF paper.\n   */\n  void computeNMF() {\n    PRINTROOT(\"computeNMF started\");\n#ifdef MPI_VERBOSE\n    DISTPRINTINFO(PRINTMAT(this->A));\n#endif\n    // error computation\n    if (this->is_compute_error()) {\n      prevH.zeros(size(this->H));\n      prevHtH.zeros(this->k, this->k);\n      WtAijH.zeros(this->k, this->k);\n      localWtAijH.zeros(this->k, this->k);\n    }\n#ifdef __WITH__BARRIER__TIMING__\n    MPI_Barrier(MPI_COMM_WORLD);\n#endif\n    for (unsigned int iter = 0; iter < this->num_iterations(); iter++) {\n      // saving current instance for error computation.\n      if (iter > 0 && this->is_compute_error()) {\n        this->prevH = this->H;\n        this->prevHtH = this->HtH;\n      }\n      MPITIC;  // total_d W&H\n      // update H given WtW and WtA step 4 of the algorithm\n      {\n        // compute WtW\n        this->distInnerProduct(this->W, &this->WtW);\n        PRINTROOT(PRINTMATINFO(this->WtW));\n        this->applyReg(this->regH(), &this->WtW);\n#ifdef MPI_VERBOSE\n        PRINTROOT(PRINTMAT(this->WtW));\n#endif\n        // compute WtA\n        this->distWtA();\n        if (this->symm_reg() > 0) {\n          // Get the appropriate Wt from the transposed processor\n          this->crossFac.zeros(arma::size(this->Ht));\n          int recvsize = this->crossFac.n_elem;\n          int sendsize = this->Wt.n_elem;\n          MPITIC;\n          MPI_Sendrecv(this->Wt.memptr(), sendsize, MPI_DOUBLE, paired_proc, 0,\n              this->crossFac.memptr(), recvsize, MPI_DOUBLE, paired_proc, 0,\n              this->m_mpicomm.gridComm(), MPI_STATUS_IGNORE);\n          double temp = MPITOC;  // sendrecv\n          this->time_stats.communication_duration(temp);\n          this->time_stats.sendrecv_duration(temp);\n\n          this->applySymmetricReg(this->symm_reg(), &this->WtW,\n                  &this->crossFac, &this->WtAij);\n        }\n        // PRINTROOT(PRINTMATINFO(this->WtAij));\n#ifdef MPI_VERBOSE\n        DISTPRINTINFO(PRINTMAT(this->WtAij));\n#endif\n        MPITIC;  // nnls H\n        // ensure both Ht and H are consistent after the update\n        // some function find Ht and some H.\n        updateH();\n#ifdef MPI_VERBOSE\n        DISTPRINTINFO(\"::it=\" << iter << PRINTMAT(this->H));\n#endif\n        double temp = MPITOC;  // nnls H\n        this->time_stats.compute_duration(temp);\n        this->time_stats.nnls_duration(temp);\n        this->reportTime(temp, \"NNLS::H::\");\n      }\n      // Update W given HtH and AH step 3 of the algorithm.\n      {\n        // compute HtH\n        this->distInnerProduct(this->H, &this->HtH);\n        PRINTROOT(\"HtH::\" << PRINTMATINFO(this->HtH));\n        this->applyReg(this->regW(), &this->HtH);\n#ifdef MPI_VERBOSE\n        PRINTROOT(PRINTMAT(this->HtH));\n#endif\n        // compute AH\n        this->distAH();\n        if (this->symm_reg() > 0) {\n          // Get the appropriate Ht from the transposed processor\n          this->crossFac.zeros(arma::size(this->Wt));\n          int recvsize = this->crossFac.n_elem;\n          int sendsize = this->Ht.n_elem;\n          MPITIC;\n          MPI_Sendrecv(this->Ht.memptr(), sendsize, MPI_DOUBLE, paired_proc, 0,\n              this->crossFac.memptr(), recvsize, MPI_DOUBLE, paired_proc, 0,\n              this->m_mpicomm.gridComm(), MPI_STATUS_IGNORE);\n          double temp = MPITOC;  // sendrecv\n          this->time_stats.communication_duration(temp);\n          this->time_stats.sendrecv_duration(temp);\n\n          this->applySymmetricReg(this->symm_reg(), &this->HtH,\n                &this->crossFac, &this->AHtij);\n        }\n        // PRINTROOT(PRINTMATINFO(this->AHtij));\n#ifdef MPI_VERBOSE\n        DISTPRINTINFO(PRINTMAT(this->AHtij));\n#endif\n        MPITIC;  // nnls W\n        // Update W given HtH and AH step 3 of the algorithm.\n        // ensure W and Wt are consistent. As some algorithms\n        // determine W and some Wt.\n        updateW();\n#ifdef MPI_VERBOSE\n        DISTPRINTINFO(\"::it=\" << iter << PRINTMAT(this->W));\n#endif\n        double temp = MPITOC;  // nnls W\n        this->time_stats.compute_duration(temp);\n        this->time_stats.nnls_duration(temp);\n        this->reportTime(temp, \"NNLS::W::\");\n      }\n      this->time_stats.duration(MPITOC);  // total_d W&H\n      if (iter > 0 && this->is_compute_error()) {\n#ifdef BUILD_SPARSE\n        this->computeError(iter);\n#else\n        this->computeError2(iter);\n#endif\n        std::string outfullName = relative_error_dir+\"relerr_at_k\"+std::to_string(this->k);\n        PRINTROOT(\"it=\" << iter << \"::algo::\" << this->m_algorithm << \"::k::\"\n                        << this->k << \"::err::\" << sqrt(this->objective_err)\n                        << \"::relerr::\"\n                        << sqrt(this->objective_err / this->m_globalsqnormA));\n        std::ofstream outfile;\n        if (iter == this->num_iterations()-1 && this->m_mpicomm.rank() == 0) {\n            outfile.open(outfullName.c_str(), std::ios_base::app);\n            outfile<<  sqrt(this->objective_err / this->m_globalsqnormA) <<\"\\n\";\n            //PRINTROOT(sqrt(this->objective_err/this->m_globalsqnormA));\n            outfile.close();\n        }\n        // Compute the difference between factor matrices\n        if (this->symm_reg() > 0) {\n          double localdiff = arma::norm(this->Wt-this->crossFac, \"fro\");\n          double globaldiff = 0.0;\n\n          // Compute global difference\n          localdiff = localdiff * localdiff;\n          MPI_Allreduce(&localdiff, &globaldiff, 1,\n              MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);\n\n          double localWnorm = arma::norm(this->Wt, \"fro\");\n          double globalWnorm = 0.0;\n\n          // Compute global W norm\n          localWnorm = localWnorm * localWnorm;\n          MPI_Allreduce(&localWnorm, &globalWnorm, 1,\n              MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);\n\n          PRINTROOT(\"it=\" << iter << \"::symmdiff::\" << globaldiff\n                    << \"::reldiff::\" << sqrt(globaldiff / globalWnorm));\n        }\n      }\n      PRINTROOT(\"completed it=\" << iter\n                                << \"::taken::\" << this->time_stats.duration());\n    }  // end for loop\n    MPI_Barrier(MPI_COMM_WORLD);\n    this->reportTime(this->time_stats.duration(), \"total_d\");\n    this->reportTime(this->time_stats.communication_duration(), \"total_comm\");\n    this->reportTime(this->time_stats.compute_duration(), \"total_comp\");\n    this->reportTime(this->time_stats.allgather_duration(), \"total_allgather\");\n    this->reportTime(this->time_stats.allreduce_duration(), \"total_allreduce\");\n    this->reportTime(this->time_stats.reducescatter_duration(),\n                     \"total_reducescatter\");\n    this->reportTime(this->time_stats.gram_duration(), \"total_gram\");\n    this->reportTime(this->time_stats.mm_duration(), \"total_mm\");\n    this->reportTime(this->time_stats.nnls_duration(), \"total_nnls\");\n    if (this->symm_reg() > 0) {\n      this->reportTime(this->time_stats.sendrecv_duration(), \"total_sendrecv\");\n    }\n    if (this->is_compute_error()) {\n      this->reportTime(this->time_stats.err_compute_duration(),\n                       \"total_err_compute\");\n      this->reportTime(this->time_stats.err_compute_duration(),\n                       \"total_err_communication\");\n    }\n  }\n\n  /**\n   * We assume this error function will be called in\n   * every iteration before updating the block to\n   * compute the error from previous iteration\n   * \\f$\\|A\\|_F^2 - 2trace(H(A^TW))+trace((W^TW)*(HH^T))\\f$\n   * each process owns globalsqnormA will have \\|A\\|_F^2\n   * each process owns WtAij is of size \\f$k \\times \\frac{globaln}{p}\\f$\n   * each process owns H is of size \\f${globaln}{p} \\times k \\f$\n   * compute WtAij*H and do an MPI_ALL reduce to get the kxk matrix.\n   * every process local computation\n   */\n\n  void computeError(const int it) {\n    MPITIC;  // computeerror\n    this->localWtAijH = this->WtAij * this->prevH;\n#ifdef MPI_VERBOSE\n    DISTPRINTINFO(\"::it=\" << it << PRINTMAT(this->WtAij));\n    DISTPRINTINFO(\"::it=\" << it << PRINTMAT(this->localWtAijH));\n    DISTPRINTINFO(\"::it=\" << it << PRINTMAT(this->prevH));\n    PRINTROOT(\"::it=\" << it << PRINTMAT(this->WtW));\n    PRINTROOT(\"::it=\" << it << PRINTMAT(this->prevHtH));\n#endif\n    double temp = MPITOC;  // computererror\n    this->time_stats.err_compute_duration(temp);\n    MPITIC;  // coommunication error\n    MPI_Allreduce(this->localWtAijH.memptr(), this->WtAijH.memptr(),\n                  this->k * this->k, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);\n    temp = MPITOC;  // communication error\n#ifdef MPI_VERBOSE\n    DISTPRINTINFO(PRINTMAT(WtAijH));\n#endif\n    this->time_stats.err_communication_duration(temp);\n    double tWtAijh = trace(this->WtAijH);\n    double tWtWHtH = trace(this->WtW * this->prevHtH);\n    PRINTROOT(\"::it=\" << it << \"normA::\" << this->m_globalsqnormA\n                      << \"::tWtAijH::\" << 2 * tWtAijh\n                      << \"::tWtWHtH::\" << tWtWHtH);\n    this->objective_err = this->m_globalsqnormA - 2 * tWtAijh + tWtWHtH;\n  }\n  /*\n   * Compute error the old-fashioned way\n   */\n  void computeError2(const int it) {\n    double local_sqerror = 0.0;\n    PRINTROOT(\"::it=\" << it << \"::Calling compute error 2\");\n    MPITIC;\n    // DISTPRINTINFO(\"::norm(Wi,fro)::\" << norm(this->Wit, \"fro\") <<\n    // \"::norm(Hjt, fro)::\" << norm(this->Hjt, \"fro\"));\n    this->Wi = this->Wit.t();\n    errMtx = this->Wi * this->Hjt;\n    A_errMtx = this->A - errMtx;\n    local_sqerror = norm(A_errMtx, \"fro\");\n    local_sqerror *= local_sqerror;\n    double temp = MPITOC;\n    this->time_stats.err_compute_duration(temp);\n    // DISTPRINTINFO(\"::it=\" << it << \"::local_sqerror::\" << local_sqerror);\n    MPITIC;\n    MPI_Allreduce(&local_sqerror, &this->objective_err, 1, MPI_DOUBLE, MPI_SUM,\n                  MPI_COMM_WORLD);\n    temp = MPITOC;\n    this->time_stats.err_communication_duration(temp);\n  }\n\n  // Set the LUC inner iterations for iterative LUC\n  void set_luciters(int max_luciters) {}\n};\n\n}  // namespace planc\n\n#endif  // DISTNMF_AUNMF_HPP_\n", "meta": {"hexsha": "5e5f9f37e0a3eeeca0bc8b5d1c125b3b25925ba4", "size": 27133, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "planc-master/distnmf/aunmf.hpp", "max_stars_repo_name": "lanl/DnMFkCPP", "max_stars_repo_head_hexsha": "a6bca290bf7d57be07f7a80d049d6b7714fbdc61", "max_stars_repo_licenses": ["BSD-3-Clause", "Unlicense"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-07-29T21:56:02.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-29T21:56:02.000Z", "max_issues_repo_path": "planc-master/distnmf/aunmf.hpp", "max_issues_repo_name": "rvangara/DnMFk", "max_issues_repo_head_hexsha": "a6bca290bf7d57be07f7a80d049d6b7714fbdc61", "max_issues_repo_licenses": ["BSD-3-Clause", "Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "planc-master/distnmf/aunmf.hpp", "max_forks_repo_name": "rvangara/DnMFk", "max_forks_repo_head_hexsha": "a6bca290bf7d57be07f7a80d049d6b7714fbdc61", "max_forks_repo_licenses": ["BSD-3-Clause", "Unlicense"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-07-29T21:55:33.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-02T21:30:15.000Z", "avg_line_length": 36.5181695828, "max_line_length": 96, "alphanum_fraction": 0.6090738215, "num_tokens": 8198, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6076631698328917, "lm_q2_score": 0.5428632831725052, "lm_q1q2_score": 0.3298780234384952}}
{"text": "#include <Eigen/Dense>\n#include <Eigen/Sparse>\n#include <math.h>\n#include <omp.h>\n#include <iomanip>\n\n#include \"mvnormal.h\"\n#include \"macau.h\"\n#include \"chol.h\"\n#include \"linop.h\"\n#include \"noisemodels.h\"\n#include \"truncnorm.h\"\nextern \"C\" {\n  #include <sparse.h>\n}\n\nusing namespace std; \nusing namespace Eigen;\n\nvoid ILatentPrior::sample_latents(FixedGaussianNoise & noise, Eigen::MatrixXd &U, const Eigen::SparseMatrix<double> &mat,\n                    double mean_value, const Eigen::MatrixXd &samples, const int num_latent) {\n  this->sample_latents(U, mat, mean_value, samples, noise.alpha, num_latent);\n}\n\nvoid ILatentPrior::sample_latents(AdaptiveGaussianNoise & noise, Eigen::MatrixXd &U, const Eigen::SparseMatrix<double> &mat,\n                    double mean_value, const Eigen::MatrixXd &samples, const int num_latent) {\n  this->sample_latents(U, mat, mean_value, samples, noise.alpha, num_latent);\n}\n\nvoid ILatentPrior::sample_latents(FixedGaussianNoise & noiseModel, MatrixData & matrixData,\n                                std::vector< std::unique_ptr<Eigen::MatrixXd> > & samples, int mode, const int num_latent) {\n  if (mode == 0) {\n    this->sample_latents(noiseModel, *samples[0], matrixData.Yt, matrixData.mean_value, *samples[1], num_latent);\n  } else {\n    this->sample_latents(noiseModel, *samples[1], matrixData.Y,  matrixData.mean_value, *samples[0], num_latent);\n  }\n}\n\nvoid ILatentPrior::sample_latents(AdaptiveGaussianNoise & noiseModel, MatrixData & matrixData,\n                                std::vector< std::unique_ptr<Eigen::MatrixXd> > & samples, int mode, const int num_latent) {\n  if (mode == 0) {\n    this->sample_latents(noiseModel, *samples[0], matrixData.Yt, matrixData.mean_value, *samples[1], num_latent);\n  } else {\n    this->sample_latents(noiseModel, *samples[1], matrixData.Y,  matrixData.mean_value, *samples[0], num_latent);\n  }\n}\n\nvoid ILatentPrior::sample_latents(ProbitNoise & noiseModel, MatrixData & matrixData,\n                                std::vector< std::unique_ptr<Eigen::MatrixXd> > & samples, int mode, const int num_latent) {\n  if (mode == 0) {\n    this->sample_latents(noiseModel, *samples[0], matrixData.Yt, matrixData.mean_value, *samples[1], num_latent);\n  } else {\n    this->sample_latents(noiseModel, *samples[1], matrixData.Y,  matrixData.mean_value, *samples[0], num_latent);\n  }\n}\n\nvoid ILatentPrior::sample_latents(FixedGaussianNoise& noiseModel, TensorData & data,\n                                std::vector< std::unique_ptr<Eigen::MatrixXd> > & samples, int mode, const int num_latent) {\n  sample_latents(noiseModel.alpha, data, samples, mode, num_latent);\n}\n\nvoid ILatentPrior::sample_latents(AdaptiveGaussianNoise& noiseModel, TensorData & data,\n                            std::vector< std::unique_ptr<Eigen::MatrixXd> > & samples, int mode, const int num_latent) {\n  sample_latents(noiseModel.alpha, data, samples, mode, num_latent);\n}\n\n\n/** BPMFPrior */\nvoid BPMFPrior::sample_latents(Eigen::MatrixXd &U, const Eigen::SparseMatrix<double> &mat, double mean_value,\n                    const Eigen::MatrixXd &samples, double alpha, const int num_latent) {\n  const int N = U.cols();\n  \n#pragma omp parallel for schedule(dynamic, 2)\n  for(int n = 0; n < N; n++) {\n    sample_latent_blas(U, n, mat, mean_value, samples, alpha, mu, Lambda, num_latent);\n  }\n}\n\nvoid BPMFPrior::update_prior(const Eigen::MatrixXd &U) {\n  tie(mu, Lambda) = CondNormalWishart(U, mu0, b0, WI, df);\n}\n\n\nvoid BPMFPrior::init(const int num_latent) {\n  mu.resize(num_latent);\n  mu.setZero();\n\n  Lambda.resize(num_latent, num_latent);\n  Lambda.setIdentity();\n  Lambda *= 10;\n\n  // parameters of Inv-Whishart distribution\n  WI.resize(num_latent, num_latent);\n  WI.setIdentity();\n  mu0.resize(num_latent);\n  mu0.setZero();\n  b0 = 2;\n  df = num_latent;\n}\n\nvoid BPMFPrior::sample_latents(ProbitNoise & noise, Eigen::MatrixXd &U, const Eigen::SparseMatrix<double> &mat,\n                               double mean_value, const Eigen::MatrixXd &samples, const int num_latent) {\n  const int N = U.cols();\n\n#pragma omp parallel for schedule(dynamic, 2)\n  for(int n = 0; n < N; n++) {\n    sample_latent_blas_probit(U, n, mat, mean_value, samples, mu, Lambda, num_latent);\n  }\n \n}\n\nvoid BPMFPrior::sample_latents(ProbitNoise& noiseModel, TensorData & data,\n                               std::vector< std::unique_ptr<Eigen::MatrixXd> > & samples, int mode, const int num_latent) {\n  // TODO\n  throw std::runtime_error(\"Unimplemented: sample_latents\");\n}\n\nvoid sample_latent_tensor(std::unique_ptr<Eigen::MatrixXd> &U,\n                          int n,\n                          std::unique_ptr<SparseMode> & sparseMode,\n                          VectorView<Eigen::MatrixXd> & view,\n                          double mean_value,\n                          double alpha,\n                          Eigen::VectorXd & mu,\n                          Eigen::MatrixXd & Lambda) {\n  const int nmodes1 = view.size();\n  const int num_latent = U->rows();\n\n  MatrixXd MM(num_latent, num_latent);\n  MM = Lambda;\n  VectorXd rr = VectorXd::Zero(mu.size());\n\n  Eigen::VectorXi & row_ptr = sparseMode->row_ptr;\n  Eigen::MatrixXi & indices = sparseMode->indices;\n  Eigen::VectorXd & values  = sparseMode->values;\n\n  Eigen::MatrixXd* S0 = view.get(0);\n\n  for (int j = row_ptr(n); j < row_ptr(n + 1); j++) {\n    VectorXd col = S0->col(indices(j, 0));\n    for (int m = 1; m < nmodes1; m++) {\n      col.noalias() = col.cwiseProduct(view.get(m)->col(indices(j, m)));\n    }\n\n    MM.triangularView<Eigen::Lower>() += alpha * col * col.transpose();\n    rr.noalias() += col * ((values(j) - mean_value) * alpha);\n  }\n\n  Eigen::LLT<MatrixXd> chol = MM.llt();\n  if(chol.info() != Eigen::Success) {\n    throw std::runtime_error(\"Cholesky Decomposition failed!\");\n  }\n\n  rr.noalias() += Lambda * mu;\n  chol.matrixL().solveInPlace(rr);\n  for (int i = 0; i < num_latent; i++) {\n    rr[i] += randn0();\n  }\n  chol.matrixU().solveInPlace(rr);\n  U->col(n).noalias() = rr;\n}\n\nvoid BPMFPrior::sample_latents(double noisePrecision,\n                               TensorData & data,\n                               std::vector< std::unique_ptr<Eigen::MatrixXd> > & samples,\n                               const int mode,\n                               const int num_latent) {\n  auto& sparseMode = (*data.Y)[mode];\n  auto& U = samples[mode];\n  const int N = U->cols();\n  VectorView<Eigen::MatrixXd> view(samples, mode);\n\n#pragma omp parallel for schedule(dynamic, 2)\n  for (int n = 0; n < N; n++) {\n    sample_latent_tensor(U, n, sparseMode, view, data.mean_value, noisePrecision, mu, Lambda);\n  }\n}\n\n/** MacauPrior */\ntemplate<class FType>\nvoid MacauPrior<FType>::init(const int num_latent, std::unique_ptr<FType> &Fmat, bool comp_FtF) {\n  mu.resize(num_latent);\n  mu.setZero();\n\n  Lambda.resize(num_latent, num_latent);\n  Lambda.setIdentity();\n  Lambda *= 10;\n\n  // parameters of Inv-Whishart distribution\n  WI.resize(num_latent, num_latent);\n  WI.setIdentity();\n  mu0.resize(num_latent);\n  mu0.setZero();\n  b0 = 2;\n  df = num_latent;\n\n  // side information\n  F = std::move(Fmat);\n  use_FtF = comp_FtF;\n  if (use_FtF) {\n    FtF.resize(F->cols(), F->cols());\n    At_mul_A(FtF, *F);\n  }\n\n  Uhat.resize(num_latent, F->rows());\n  Uhat.setZero();\n\n  beta.resize(num_latent, F->cols());\n  beta.setZero();\n\n  // initial value (should be determined automatically)\n  lambda_beta = 5.0;\n  // Hyper-prior for lambda_beta (mean 1.0, var of 1e+3):\n  lambda_beta_mu0 = 1.0;\n  lambda_beta_nu0 = 1e-3;\n}\n\ntemplate<class FType>\nvoid MacauPrior<FType>::sample_latents(Eigen::MatrixXd &U, const Eigen::SparseMatrix<double> &mat, double mean_value,\n                    const Eigen::MatrixXd &samples, double alpha, const int num_latent) {\n  const int N = U.cols();\n#pragma omp parallel for schedule(dynamic, 2)\n  for(int n = 0; n < N; n++) {\n    // TODO: try moving mu + Uhat.col(n) inside sample_latent for speed\n    sample_latent_blas(U, n, mat, mean_value, samples, alpha, mu + Uhat.col(n), Lambda, num_latent);\n  }\n}\n\ntemplate<class FType>\nvoid MacauPrior<FType>::sample_latents(ProbitNoise& noiseModel, TensorData & data,\n                               std::vector< std::unique_ptr<Eigen::MatrixXd> > & samples, int mode, const int num_latent) {\n  // TODO:\n}\n\ntemplate<class FType>\nvoid MacauPrior<FType>::sample_latents(double noisePrecision,\n                                       TensorData & data,\n                                       std::vector< std::unique_ptr<Eigen::MatrixXd> > & samples,\n                                       int mode,\n                                       const int num_latent) {\n  auto& sparseMode = (*data.Y)[mode];\n  auto& U = samples[mode];\n  const int N = U->cols();\n  VectorView<Eigen::MatrixXd> view(samples, mode);\n\n#pragma omp parallel for schedule(dynamic, 2)\n  for (int n = 0; n < N; n++) {\n    Eigen::VectorXd mu2 = mu + Uhat.col(n);\n    sample_latent_tensor(U, n, sparseMode, view, data.mean_value, noisePrecision, mu2, Lambda);\n  }\n}\n\n\ntemplate<class FType>\nvoid MacauPrior<FType>::update_prior(const Eigen::MatrixXd &U) {\n  // residual (Uhat is later overwritten):\n  Uhat.noalias() = U - Uhat;\n  MatrixXd BBt = A_mul_At_combo(beta);\n  // sampling Gaussian\n  tie(mu, Lambda) = CondNormalWishart(Uhat, mu0, b0, WI + lambda_beta * BBt, df + beta.cols());\n  sample_beta(U);\n  compute_uhat(Uhat, *F, beta);\n  lambda_beta = sample_lambda_beta(beta, Lambda, lambda_beta_nu0, lambda_beta_mu0);\n}\n\ntemplate<class FType>\ndouble MacauPrior<FType>::getLinkNorm() {\n  return beta.norm();\n}\n\n/** Update beta and Uhat */\ntemplate<class FType>\nvoid MacauPrior<FType>::sample_beta(const Eigen::MatrixXd &U) {\n  const int num_feat = beta.cols();\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(Lambda, U.cols())).colwise() - mu;\n  MatrixXd Ft_y = A_mul_B(tmp, *F) + sqrt(lambda_beta) * MvNormal_prec_omp(Lambda, num_feat);\n\n  if (use_FtF) {\n    MatrixXd K(FtF.rows(), FtF.cols());\n    K.triangularView<Eigen::Lower>() = FtF;\n    for (int i = 0; i < K.cols(); i++) {\n      K(i,i) += lambda_beta;\n    }\n    chol_decomp(K);\n    chol_solve_t(K, Ft_y);\n    beta = Ft_y;\n  } else {\n    // BlockCG\n    solve_blockcg(beta, *F, lambda_beta, Ft_y, tol, 32, 8);\n  }\n}\n\ntemplate<class FType>\nvoid MacauPrior<FType>::sample_latents(ProbitNoise & noise, Eigen::MatrixXd &U, const Eigen::SparseMatrix<double> &mat,\n                                       double mean_value, const Eigen::MatrixXd &samples, const int num_latent) {\n    const int N = U.cols();\n#pragma omp parallel for schedule(dynamic, 2)\n  for(int n = 0; n < N; n++) {\n    // TODO: try moving mu + Uhat.col(n) inside sample_latent for speed\n    sample_latent_blas_probit(U, n, mat, mean_value, samples, mu + Uhat.col(n), Lambda, num_latent);\n  }\n\n}\n\nvoid BPMFPrior::saveModel(std::string prefix) {\n  writeToCSVfile(prefix + \"-latentmean.csv\", mu);\n}\n\ntemplate<class FType>\nvoid MacauPrior<FType>::saveModel(std::string prefix) {\n  writeToCSVfile(prefix + \"-latentmean.csv\", mu);\n  writeToCSVfile(prefix + \"-link.csv\", beta);\n}\n\nstd::pair<double,double> posterior_lambda_beta(Eigen::MatrixXd & beta, Eigen::MatrixXd & Lambda_u, double nu, double mu) {\n  const int D = beta.rows();\n  MatrixXd BB(D, D);\n  A_mul_At_combo(BB, beta);\n  double nux = nu + beta.rows() * beta.cols();\n  double mux = mu * nux / (nu + mu * (BB.selfadjointView<Eigen::Lower>() * Lambda_u).trace() );\n  double b   = nux / 2;\n  double c   = 2 * mux / nux;\n  return std::make_pair(b, c);\n}\n\ndouble sample_lambda_beta(Eigen::MatrixXd & beta, Eigen::MatrixXd & Lambda_u, double nu, double mu) {\n  auto gamma_post = posterior_lambda_beta(beta, Lambda_u, nu, mu);\n  return rgamma(gamma_post.first, gamma_post.second);\n}\n\n/** global function */\nvoid sample_latent(MatrixXd &s, int mm, const SparseMatrix<double> &mat, double mean_rating,\n    const MatrixXd &samples, double alpha, const VectorXd &mu_u, const MatrixXd &Lambda_u,\n    const int num_latent)\n{\n  // TODO: add cholesky update version\n  MatrixXd MM = MatrixXd::Zero(num_latent, num_latent);\n  VectorXd rr = VectorXd::Zero(num_latent);\n  for (SparseMatrix<double>::InnerIterator it(mat, mm); it; ++it) {\n    auto col = samples.col(it.row());\n    MM.noalias() += col * col.transpose();\n    rr.noalias() += col * ((it.value() - mean_rating) * alpha);\n  }\n\n  Eigen::LLT<MatrixXd> chol = (Lambda_u + alpha * MM).llt();\n  if(chol.info() != Eigen::Success) {\n    throw std::runtime_error(\"Cholesky Decomposition failed!\");\n  }\n\n  rr.noalias() += Lambda_u * mu_u;\n  chol.matrixL().solveInPlace(rr);\n  for (int i = 0; i < num_latent; i++) {\n    rr[i] += randn0();\n  }\n  chol.matrixU().solveInPlace(rr);\n  s.col(mm).noalias() = rr;\n}\n\nvoid sample_latent_blas(MatrixXd &s, int mm, const SparseMatrix<double> &mat, double mean_rating,\n    const MatrixXd &samples, double alpha, const VectorXd &mu_u, const MatrixXd &Lambda_u,\n    const int num_latent)\n{\n  MatrixXd MM = Lambda_u;\n  VectorXd rr = VectorXd::Zero(num_latent);\n  for (SparseMatrix<double>::InnerIterator it(mat, mm); it; ++it) {\n    auto col = samples.col(it.row());\n    MM.triangularView<Eigen::Lower>() += alpha * col * col.transpose();\n    rr.noalias() += col * ((it.value() - mean_rating) * alpha);\n  }\n\n  Eigen::LLT<MatrixXd> chol = MM.llt();\n  if(chol.info() != Eigen::Success) {\n    throw std::runtime_error(\"Cholesky Decomposition failed!\");\n  }\n\n  rr.noalias() += Lambda_u * mu_u;\n  chol.matrixL().solveInPlace(rr);\n  for (int i = 0; i < num_latent; i++) {\n    rr[i] += randn0();\n  }\n  chol.matrixU().solveInPlace(rr);\n  s.col(mm).noalias() = rr;\n}\n\nvoid sample_latent_blas_probit(MatrixXd &s, int mm, const SparseMatrix<double> &mat, double mean_rating,\n    const MatrixXd &samples, const VectorXd &mu_u, const MatrixXd &Lambda_u,\n    const int num_latent)\n{ \n    MatrixXd MM = Lambda_u;\n    VectorXd rr = VectorXd::Zero(num_latent);\n    double z;\n    auto u = s.col(mm);\n    for (SparseMatrix<double>::InnerIterator it(mat, mm); it; ++it) {\n      auto col = samples.col(it.row());\n      MM.triangularView<Eigen::Lower>() += col * col.transpose();\n\t\t\tdouble y = 2 * it.value() - 1;\n      z = y * rand_truncnorm(y * col.dot(u), 1.0, 0.0);\n      rr.noalias() += col * z;\n    }\n  Eigen::LLT<MatrixXd> chol = MM.llt();\n  if(chol.info() != Eigen::Success) {\n    throw std::runtime_error(\"Cholesky Decomposition failed!\");\n  }\n\n  rr.noalias() += Lambda_u * mu_u;\n  chol.matrixL().solveInPlace(rr);\n  for (int i = 0; i < num_latent; i++) {\n    rr[i] += randn0();\n  }\n  chol.matrixU().solveInPlace(rr);\n  s.col(mm).noalias() = rr;\n}\n\n/**\n * X = A * B\n */\nEigen::MatrixXd A_mul_B(Eigen::MatrixXd & A, Eigen::MatrixXd & B) {\n  MatrixXd out(A.rows(), B.cols());\n  A_mul_B_blas(out, A, B);\n  return out;\n}\n\nEigen::MatrixXd A_mul_B(Eigen::MatrixXd & A, SparseFeat & B) {\n  MatrixXd out(A.rows(), B.cols());\n  A_mul_Bt(out, B.Mt, A);\n  return out;\n}\n\nEigen::MatrixXd A_mul_B(Eigen::MatrixXd & A, SparseDoubleFeat & B) {\n  MatrixXd out(A.rows(), B.cols());\n  A_mul_Bt(out, B.Mt, A);\n  return out;\n}\n\nMacauPrior<Eigen::MatrixXd>* make_dense_prior(int nlatent, double* ptr, int nrows, int ncols, bool colMajor, bool comp_FtF) {\n\tMatrixXd* Fmat = new MatrixXd(0, 0);\n\tif (colMajor) {\n\t\t*Fmat = Map<Matrix<double, Dynamic, Dynamic, ColMajor> >(ptr, nrows, ncols);\n\t} else {\n\t\t*Fmat = Map<Matrix<double, Dynamic, Dynamic, RowMajor> >(ptr, nrows, ncols);\n\t}\n\tunique_ptr<MatrixXd> Fmat_ptr = unique_ptr<MatrixXd>(Fmat);\n\treturn new MacauPrior<MatrixXd>(nlatent, Fmat_ptr, comp_FtF);\n}\n\ntemplate class MacauPrior<SparseFeat>;\ntemplate class MacauPrior<SparseDoubleFeat>;\ntemplate class MacauPrior<Eigen::MatrixXd>;\n\n", "meta": {"hexsha": "e422a4ac9765a74d5b13d4c7512cc8076bac2879", "size": 15646, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lib/macau-cpp/latentprior.cpp", "max_stars_repo_name": "jaak-s/macau", "max_stars_repo_head_hexsha": "99e31452bbc302ab9967070c1d8e44d3008f19cf", "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/latentprior.cpp", "max_issues_repo_name": "potatopaul/macau", "max_issues_repo_head_hexsha": "dadf9d5da67c89d541d972663edc44af7b23d287", "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/latentprior.cpp", "max_forks_repo_name": "potatopaul/macau", "max_forks_repo_head_hexsha": "dadf9d5da67c89d541d972663edc44af7b23d287", "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": 34.6150442478, "max_line_length": 125, "alphanum_fraction": 0.6461715454, "num_tokens": 4456, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7154239957834733, "lm_q2_score": 0.46101677931231594, "lm_q1q2_score": 0.32982246637884477}}
{"text": "#include <memory>\n#include <vector>\n\n#include <boost/shared_ptr.hpp>\n\n#include <CGAL/Straight_skeleton_2.h>\n#include <CGAL/create_offset_polygons_2.h>\n#include <CGAL/create_straight_skeleton_2.h>\n#include <CGAL/create_straight_skeleton_from_polygon_with_holes_2.h>\n\n#include <jlcxx/module.hpp>\n#include <jlcxx/smart_pointers.hpp>\n\n#include <julia.h>\n\n#include \"polygon_2.hpp\"\n#include \"utils.hpp\"\n\nnamespace jlcgal {\n\ntemplate<typename T>\nstd::shared_ptr<T>\nto_std(boost::shared_ptr<T> ptr) {\n  return std::shared_ptr<T>(ptr.get(), [ptr](T*) mutable { ptr.reset(); });\n}\n\ntemplate<typename Polygon>\njlcxx::Array<Polygon>\nto_poly_jlarr(std::vector<boost::shared_ptr<Polygon>> ps) {\n  jlcxx::Array<Polygon> jlarr;\n  for (const auto& poly : ps) jlarr.push_back(Polygon(*poly));\n  return jlarr;\n}\n\nvoid wrap_straight_skeleton_2(jlcxx::Module& cgal) {\n  typedef CGAL::Straight_skeleton_2<Kernel> Skeleton_2;\n\n  typedef CGAL::HalfedgeDS_in_place_list_face<Skeleton_2::Face>         Face;\n  typedef CGAL::HalfedgeDS_in_place_list_halfedge<Skeleton_2::Halfedge> Halfedge;\n  typedef CGAL::HalfedgeDS_in_place_list_vertex<Skeleton_2::Vertex>     Vertex;\n\n  const std::string skel_2_name = \"StraightSkeleton2\";\n\n  auto ssf = cgal.add_type<Face>    (skel_2_name + \"Face\");\n  auto ssh = cgal.add_type<Halfedge>(skel_2_name + \"Halfedge\");\n  auto ssv = cgal.add_type<Vertex>  (skel_2_name + \"Vertex\");\n\n  ssf\n    // Access Functions\n    .method(\"id\", &Face::id)\n    .method(\"halfedge\", [](const Face& f) { return *f.halfedge(); })\n    ;\n\n  ssh\n    // Access Functions\n    .method(\"id\",       &Halfedge::id)\n    .method(\"opposite\", [](const Halfedge& h) { return *h.opposite(); })\n    .method(\"next\",     [](const Halfedge& h) { return *h.next(); })\n    .method(\"prev\",     [](const Halfedge& h) { return *h.prev(); })\n    .method(\"vertex\",   [](const Halfedge& h) { return *h.vertex(); })\n    .method(\"face\",     [](const Halfedge& h) { return *h.face(); })\n    .method(\"defining_contour_edge\", [](const Halfedge& h) {\n      return *h.defining_contour_edge();\n    })\n    // Predicates\n    .method(\"has_null_segment\",  &Halfedge::has_null_segment)\n    .method(\"has_infinite_time\", &Halfedge::has_infinite_time)\n    .method(\"is_border\",         &Halfedge::is_border)\n    .method(\"is_bisector\",       &Halfedge::is_bisector)\n    .method(\"is_inner_bisector\", &Halfedge::is_inner_bisector)\n    .method(\"slope\",             &Halfedge::slope)\n    ;\n\n  ssv\n    // Access Functions\n    .method(\"id\",       &Vertex::id)\n    .method(\"degree\",   &Vertex::degree)\n    .method(\"halfedge\", [](const Vertex& v) { return *v.halfedge(); })\n    .method(\"point\",    &Vertex::point)\n    ;\n  cgal.set_override_module(jl_base_module);\n  ssv\n    .method(\"time\", &Vertex::time)\n    ;\n  cgal.unset_override_module();\n  ssv\n    .method(\"primary_bisector\", [](const Vertex& v) {\n      return *v.primary_bisector();\n    })\n    // Queries\n    .method(\"has_infinite_time\", &Vertex::has_infinite_time)\n    .method(\"has_null_point\",    &Vertex::has_null_point)\n    .method(\"is_contour\",        &Vertex::is_contour)\n    .method(\"is_skeleton\",       &Vertex::is_skeleton)\n    .method(\"is_split\",          &Vertex::is_split)\n    ;\n\n  cgal.add_type<Skeleton_2>(skel_2_name)\n    // Access Member Functions\n    .method(\"size_of_faces\",     &Skeleton_2::size_of_faces)\n    .method(\"size_of_halfedges\", &Skeleton_2::size_of_halfedges)\n    .method(\"size_of_vertices\",  &Skeleton_2::size_of_vertices)\n    .method(\"faces\", [](const Skeleton_2& s) {\n      return collect(s.faces_begin(), s.faces_end());\n    })\n    .method(\"halfedges\", [](const Skeleton_2& s) {\n      return collect(s.halfedges_begin(), s.halfedges_end());\n    })\n    .method(\"vertices\", [](const Skeleton_2& s) {\n      return collect(s.vertices_begin(), s.vertices_end());\n    })\n    // Predicates\n    .method(\"is_valid\", &Skeleton_2::is_valid)\n    ;\n\n  cgal.method(\"create_exterior_straight_skeleton_2\",\n              [](const FT& max_offset, const Polygon_2& poly) {\n    return to_std(CGAL::create_exterior_straight_skeleton_2(max_offset,\n                                                            poly,\n                                                            Kernel()));\n  });\n  cgal.method(\"create_exterior_straight_skeleton_2\",\n              [](const FT& max_offset, jlcxx::ArrayRef<Point_2> ps) {\n    // because `bbox_2` uses operator-> from the input iterator... which\n    // ArrayRef::iterator is missing, so we copy it into a vector.\n    std::vector<Point_2> vps(ps.begin(), ps.end());\n    return to_std(CGAL::create_exterior_straight_skeleton_2(max_offset,\n                                                            vps.begin(),\n                                                            vps.end(),\n                                                            Kernel()));\n  });\n  cgal.method(\"create_interior_straight_skeleton_2\", [](const Polygon_2& poly) {\n    return to_std(CGAL::create_interior_straight_skeleton_2(poly, Kernel()));\n  });\n  cgal.method(\"create_interior_straight_skeleton_2\",\n              [](const Polygon_with_holes_2& poly) {\n    return to_std(CGAL::create_interior_straight_skeleton_2(poly));\n  });\n  cgal.method(\"create_interior_straight_skeleton_2\",\n              [](jlcxx::ArrayRef<Point_2> contour) {\n    return to_std(CGAL::create_interior_straight_skeleton_2(contour.begin(),\n                                                            contour.end(),\n                                                            Kernel()));\n  });\n  cgal.method(\"create_interior_straight_skeleton_2\",\n              [](jlcxx::ArrayRef<Point_2> contour,\n                 jlcxx::ArrayRef<Polygon_2> holes) {\n    return to_std(CGAL::create_interior_straight_skeleton_2(contour.begin(),\n                                                            contour.end(),\n                                                            holes.begin(),\n                                                            holes.end(),\n                                                            Kernel()));\n  });\n\n  cgal.method(\"create_offset_polygons_2\", [](const FT& offset,\n                                             const Skeleton_2& ss) {\n    return to_poly_jlarr(CGAL::create_offset_polygons_2<Polygon_2>(offset,\n                                                                   ss,\n                                                                   Kernel()));\n  });\n}\n\n} // jlcgal\n", "meta": {"hexsha": "e87d0ad04d53a1188ce138e860e57eae57604c88", "size": 6397, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/straight_skeleton_2.cpp", "max_stars_repo_name": "rgcv/libcgal-julia", "max_stars_repo_head_hexsha": "8d5bc5f13d3c9c6160cfff795d2a0bbe1e473d94", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2020-01-22T14:06:29.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-23T11:29:18.000Z", "max_issues_repo_path": "src/straight_skeleton_2.cpp", "max_issues_repo_name": "rgcv/libcgal-julia", "max_issues_repo_head_hexsha": "8d5bc5f13d3c9c6160cfff795d2a0bbe1e473d94", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/straight_skeleton_2.cpp", "max_forks_repo_name": "rgcv/libcgal-julia", "max_forks_repo_head_hexsha": "8d5bc5f13d3c9c6160cfff795d2a0bbe1e473d94", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-02-16T13:56:02.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-14T17:17:30.000Z", "avg_line_length": 39.006097561, "max_line_length": 81, "alphanum_fraction": 0.5827731749, "num_tokens": 1607, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7154239957834733, "lm_q2_score": 0.46101677931231594, "lm_q1q2_score": 0.32982246637884477}}
{"text": "//////////////////////////////////////////////////////////////////////////////\n//////////////////////////////////////////////////////////////////////////////\n//  Quantum Monte Carlo Simulation for Kitaev Models\n//  written by: Tim Eschmann, June 2016\n//  Modified version: February 2019\n//////////////////////////////////////////////////////////////////////////////\n//////////////////////////////////////////////////////////////////////////////\n//\n//  The code skeleton of this file was derived from \"ising_skeleton.cpp\"   \n//  which is part of the ALPS libraries:\n//\n/*****************************************************************************\n *\n * ALPS Project: Algorithms and Libraries for Physics Simulations\n *\n * ALPS Libraries\n *\n * Copyright (C) 2003 by Brigitte Surer\n *                       and Jan Gukelberger\n *\n * This software is part of the ALPS libraries, published under the ALPS\n * Library License; you can use, redistribute it and/or modify it under\n * the terms of the license, either version 1 or (at your option) any later\n * version.\n * \n * You should have received a copy of the ALPS Library License along with\n * the ALPS Libraries; see the file LICENSE.txt. If not, the license is also\n * available from http://alps.comp-phys.org/.\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//  This software incorporates the Armadillo C++ Library\n//  Armadillo C++ Linear Algebra Library\n//  Copyright 2008-2020 Conrad Sanderson (http://conradsanderson.id.au)\n//  Copyright 2008-2016 National ICT Australia (NICTA)\n//  Copyright 2017-2020 Arroyo Consortium\n//  Copyright 2017-2020 Data61, CSIRO\n\n//  This product includes software developed by Conrad Sanderson (http://conradsanderson.id.au)\n//  This product includes software developed at National ICT Australia (NICTA)\n//  This product includes software developed at Arroyo Consortium\n//  This product includes software developed at Data61, CSIRO\n\n//////////////////////////////////////////////////////////////////////////////\n//////////////////////////////////////////////////////////////////////////////\n\n#include <iostream>\n#include <sstream>\n#include <vector>\n#include <complex>\n#include <cmath>\n#include <armadillo>\n#include <mpi.h>\n\n#include <alps/scheduler/montecarlo.h>\n#include <alps/alea.h>\n#include <boost/random.hpp>\n#include <boost/multi_array.hpp>\n#include <boost/filesystem.hpp>\n\n// Include functions package\n#include \"functions.hpp\"\n\n// Include the desired lattice (read in header file from .hpp folder)\n#include \"Lattices/honeycomb_8_sites.hpp\"\n\n#ifndef _temp_hpp_\n#define _temp_hpp_\ndouble calc_temp(double T_min, double T_max, int me, int np, std::string dist);\n#endif\n\nusing namespace arma;\n\nclass Simulation\n{\npublic:\n    Simulation(int np, int me, double T_min, double T_max, double T, std::string dist, std::string output_file)\n    // Define interaction matrix A, parameters and measurable observables:\n    :   eng_(3*me) // Random generator engine (different seed for each replica)\n    ,   rng_(eng_, dist_) // Random generator\n    ,   np_(np) // # of processes\n    ,   me_(me) // process number / parallelization rank\n    ,   T_min(T_min) // minimal temperature\n    ,   T_max(T_max) // maximal temperature\n    ,   dist(dist) // Temperature distribution\n    ,   temp_(T)  // Replica Temperature\n    ,   beta_(1/T) // Inverse replica Temperature\n    ,   ham() // Interaction matrix / Z2 configuration \n    ,   N_() // # system sites (IMPORTANT: THIS HAS CHANGED W.R.T. FORMER VERSIONS !!!)\n    ,   v_() // Vector with coordinates of nonzero matrix entries\n    ,   length_() // Length of this vector\n    ,   eigval() // Eigenvalues of interaction matrix\n    ,   F() // Free energy\n    ,   plaquettes() // matrix with elementary plaquettes\n    ,   energy_(\"E\") // Measurement data: energy\n    ,   e2_(\"E2\") // Measurement data: squared energy\n    //,   e4_(\"E4\") // Measurement data: energy^4\n    ,   dE_db(\"dE_db\") // Measurement data: dE / d(beta) = fermionic part of specific heat\n    //,   p_(\"p\") // Disorder\n    ,   flux_real(\"Flreal\") // Measurement data: average plaquet flux (real part)\n    ,   flux_imag(\"Flimag\") // \"\" (imaginary part)\n    ,   flux_real_squared(\"Flreal2\") // Measurement data: average plaquet flux (real part)\n    ,   flux_imag_squared(\"Flimag2\") // \"\" (imaginary part)\n    ,   spin_corr(\"Spin_corr\")\n    ,   flip_rate() // Single flip acceptance rate\n    ,   filename_(output_file) // Filename for data saving\n      \n    {  \n    \n    // Locate nonzero entries of interaction matrix (.hpp file):\n    v_ = non_zeros();\n    length_ = v_.size();\n    \n    // Fill interaction matrix A with coefficients due to lattice symmetry (.hpp file)\n    ham = randomize(def_matrix());\n\n    N_ = size(ham)[0];\n\n    // Vector of eigenvalues of A\n    eigval = eig_sym(ham);\n\n    F = free_en(eigval, beta_);\n\n    plaquettes = create_plaquettes();\n\n    // Initialize single flip acceptance to 0:\n    flip_rate = 0;\n\n    } \n\n    // Replica Monte Carlo iteration\n    void run(int n, int ntherm, int sweeps_per_swap, int sweeps_per_save)\n    {\n        engine_type loaded, saved; // needed to load and save random engine status\n        sweeps_ = n;\n        thermalization_ = ntherm; // thermalization steps\n\n        double fr;\n        int n_tot = n + ntherm;\n        double tau_en, tau_fl; // autocorrelation times\n        \n        std::stringstream matrix_output; // needed for saving configurations\n        matrix_output << \"matrix_temp_\" << 1/beta_ << \".saved\";\n\n        std::stringstream rng_save; // needed for saving random generator status\n        rng_save << \"rng_\" << me_ << \".saved\";\n         \n        //Load so-far-obtained measurement data (ALPS)\n        if (boost::filesystem::exists(filename_))\n        {\n            load(filename_);\n        }\n        \n        // Load random generator status:\n        std::ifstream rngfile(rng_save.str().c_str(), std::ifstream::in);\n        if(rngfile.good())\n        {\n            rngfile >> loaded;\n            rngfile.close();\n            eng_ = loaded;\n        }\n\n        // Load last Z2 configuration from file (-> skip thermalization)\n        std::ifstream matfile(matrix_output.str().c_str(), std::ifstream::in);\n        if(matfile.good())\n            ham.load(matrix_output.str().c_str());\n\n        // Thermalize for ntherm steps\n        if (me_ == 1)\n            std::cout << \"Thermalizing ...\" << std::endl;\n        \n        while(ntherm--)\n        {\n            step();\n\n            if (ntherm % sweeps_per_swap == 0)\n            {\n                swap(); \n\n                if (((ntherm + n) / sweeps_per_swap) % sweeps_per_save == 0)\n                {    \n                    // Calculate single flip acceptance rate and send it to Master process:\n                    fr = double(flip_rate)/(double(n_tot - n - ntherm)*N_);\n                    MPI_Send(&fr, 1, MPI_DOUBLE, 0, 5, MPI_COMM_WORLD);\n                } \n            }\n            \n            if (ntherm % sweeps_per_save == 0)\n            {\n                // Save Z2 configuration:\n                ham.save(matrix_output.str().c_str());\n\n                // Save random generator status:\n                saved = eng_;\n                std::ofstream file(rng_save.str().c_str(), std::ofstream::trunc);\n                file << saved;\n                \n                // Tell that everything is saved ...\n                if (me_ == 1)\n                    std::cout << \"SAVE \" << ntherm << std::endl; \n\n            }\n        }\n\n        if (me_ == 1)\n        {\n            std::cout << \"###############################\" << std::endl;\n            std::cout << \"Sweeping ...\" << std::endl;\n        }\n\n        // Run n steps\n        while(n--)\n        {   \n            step();\n            \n            // Output eigenvalue and flux configurations:\n            //outputZ2gauge();\n            //output_eigenvalues();\n            //output_flux_confs();\n\n            // Measure observables:\n            measure();\n\n            // Swap:\n            if (n % sweeps_per_swap == 0)\n            {\n                swap();  \n\n                if (((n) / sweeps_per_swap) % sweeps_per_save == 0)\n                {\n                    // Calculate single flip acceptance rate and send it to Master process:\n                    fr = double(flip_rate)/(double(n_tot - n - ntherm)*N_);\n                    MPI_Send(&fr, 1, MPI_DOUBLE, 0, 5, MPI_COMM_WORLD);\n                }\n            }\n                  \n            // Save all simulation data:\n            if (n % sweeps_per_save == 0)\n            {\n                // Save results:\n                save(filename_);\n                \n                // Save Z2 configuration:\n                ham.save(matrix_output.str().c_str());\n\n                // Save random generator status:\n                saved = eng_;\n                std::ofstream file(rng_save.str().c_str(), std::ofstream::trunc);\n                file << saved;\n                \n                // Tell that everything is saved ...\n                if (me_ == 1)\n                    std::cout << \"SAVE \" << n << std::endl; \n            }\n        }\n\n        //Save the observables to file\n        save(filename_);\n\n        tau_en = energy_.tau();\n        tau_fl = flux_real.tau();\n        MPI_Send(&tau_en, 1, MPI_DOUBLE, 0, 6, MPI_COMM_WORLD);\n        MPI_Send(&tau_fl, 1, MPI_DOUBLE, 0, 7, MPI_COMM_WORLD);\n\n     \n        // Print observables      \n\t    /*\n        std::cout << temp_ << std::endl;\n\t    std::cout.precision(17);\n       \tstd::cout << energy_.name() << \":\\t\" << energy_.mean()\n            << \" +- \" << energy_.error() << \";\\ttau = \" << energy_.tau() \n            << \";\\tconverged: \" << alps::convergence_to_text(energy_.converged_errors())     \n            << std::endl;\n        \n\t    std::cout << flux_real.name() << \":\\t\" << flux_real.mean()\n            << \" +- \" << flux_real.error() << \";\\ttau = \" << flux_real.tau() \n            << \";\\tconverged: \" << alps::convergence_to_te        //std::cout << double(counter)/double(tries) << std::endl;xt(flux_real.converged_errors())\n            << std::endl;\n        std::cout << flux_imag.name() << \":\\t\" << flux_imag.mean()\n            << \" +- \" << flux_imag.error() << \";\\ttau = \" << flux_imag.tau() \n            << \";\\tconverged: \" << alps::convergence_to_text(flux_imag.converged_errors())\n            << std::endl;*/\n\n    }\n    \n    // Iteration step (= \"Metropolis sweep\"): \n    void step()\n    {\n        int kk, i, j; // Running indices\n        cx_mat ham_new(N_,N_);\n        vec eigval_new(N_); // Vector for eigenvalues of new matrix (= update proposal)\n        \n        double F_new; // New free energy\n        \n        int coord1, coord2; // Random bond coordinate\n        double alpha, gamma; // Monte Carlo variables\n        \n        int count = 0;\n\n        // One sweep = N tries (# lattice sites)\n        for (kk = 0; kk < N_; kk++)\n        {       \n            // Alternative matrix for sampling:\n            ham_new = ham;\n        \n            // Switch sign of random matrix entry:\n            int die = roll_die(length_);\n            coord1 = v_[die]/(N_);\n            coord2 = v_[die]%(N_);\n            ham_new(coord1, coord2) *= -1;\n            ham_new(coord2, coord1) *= -1;\n            \n            // Measure free energy of changed Hamiltonian:\n            eigval_new = eig_sym(ham_new);    \n            F_new = free_en(eigval_new, beta_);\n\n            // Accept change with probability according to Boltzmann distribution:  \n            //alpha = exp(- beta_ * (F_new - F));\n            // Use Gibbs weights instead of Metropolis weights:\n            alpha = 1./ (1. + exp(beta_ * (F_new - F)));\n            gamma = rng_();\n\n            // Accepted?\n            if (gamma <= alpha) // accept\n            {\n                ham = ham_new;\n                eigval = eigval_new;\n                F = F_new;\n\n                // Single flip acceptance rate + 1\n                flip_rate += 1;\n            }\n\n            count += 1;\n        }\n    }\n    \n    // Does what it says ...\n    void measure()\n    {      \n        std::complex <double> fl;\n        double E_, dE_, s;\n        //double p;\n        double fl_real;\n        double fl_imag;\n        double corr;\n\n        // Measure energy etc.:\n        E_ = en(eigval, beta_);\n        dE_ = diffE(eigval, beta_);\n        \n        // Measure average flux per plaquet / disorder:\n        fl = flux(ham, plaquettes);\n        fl_real = std::real(fl);\n        fl_imag = std::imag(fl);\n        //p = get_p(ham, plaquettes);\n\n        // Measure spin-spin correlation:\n        corr = correlation(ham, v_, beta_);\n\n        // Add sample to observables:\n        energy_ << E_/double(N_); // Energy per site\n        e2_ << E_/double(N_)*E_/double(N_); // Squared energy per site\n        //e4_ << E_/double(N_)*E_/double(N_)*E_/double(N_)*E_/double(N_);\n        dE_db << dE_ / double(N_); // dE/d(beta)\n        //p_ << p;\n        flux_real << fl_real;\n        flux_imag << fl_imag;\n        flux_real_squared << fl_real*fl_real;\n        flux_imag_squared << fl_imag*fl_imag;\n        spin_corr << corr;\n    }\n\n    ///////////////////////////////////////////////////////////////\n    // Output Z2 gauge field configuration:\n    ///////////////////////////////////////////////////////////////\n\n    void outputZ2gauge()\n    {\n        int coord1, coord2;\n        std::stringstream gauge_output; // needed for saving configurations\n        gauge_output << \"gauge_configuration_temp_\" << 1/beta_ << \".saved\";\n\n        std::ofstream gauge(gauge_output.str().c_str(), std::ofstream::app);\n        for (int j = 0; j < v_.size(); j++)\n        {\n            coord1 = v_[j]/N_;\n            coord2 = v_[j]%N_;\n\n            gauge << std::setprecision(17) << std::imag(ham(coord1, coord2) / std::abs(ham(coord1, coord2))) << \"   \";\n        }\n        gauge << std::endl;\n    }\n\n    \n    // Output flux configurations:\n    void output_flux_confs()\n    {\n        cx_vec fl_confs = flux_confs(ham, plaquettes);\n        \n        std::stringstream flux_output; // needed for saving configurations\n        flux_output << \"flux_configuration_temp_\" << 1/beta_ << \".saved\";\n\n        std::ofstream flux(flux_output.str().c_str(), std::ofstream::app);\n        for(int iii = 0; iii < size(plaquettes)[0]; iii++)\n        {\n            // Switch between real and imaginary fluxes:\n            flux << std::setprecision(17) << std::real(fl_confs[iii]) << \"   \";\n            //flux << std::setprecision(17) << std::imag(fl_confs[iii]) << std::endl;\n        }\n        flux << std::endl;\n    }\n\n    // Output eigenvalue configurations:\n    void output_eigenvalues()\n    {        \n        std::stringstream output; // needed for saving energies\n        output << \"eigenvalues_temp_\" << 1/beta_ << \".saved\";\n\n        std::ofstream eig(output.str().c_str(), std::ofstream::app);\n        for(int iii = 0; iii < size(eigval)[0]/2; iii++)\n        {\n            eig << std::setprecision(17) << eigval[iii] << \"   \";\n        }\n        eig << std::endl;\n    }\n    \n    // Swap replica with left neighbour ...\n    void swapleft()\n    {\n        MPI_Status status;\n        int control = 0;\n        int jj,kk;\n        double beta_alt = 1/calc_temp(T_min, T_max, me_ - 1, np_, dist);\n        cx_mat H_a(N_,N_); // receive\n        cx_mat H_b = ham; // send\n\n        double f2 = -beta_alt * free_en(eigval, beta_alt);\n        double f3 = beta_ * F;\n\n        MPI_Send(&f2, 1, MPI_DOUBLE, 0, 2, MPI_COMM_WORLD);\n        MPI_Send(&f3, 1, MPI_DOUBLE, 0, 2, MPI_COMM_WORLD);\n\n        MPI_Recv(&control, 1, MPI_INT, 0, 2, MPI_COMM_WORLD, &status);\n\n        if (control == 1)\n        {\n            // Receive replica from left neighbour\n            for (jj = 0; jj < N_; jj++)\n            {\n                for (kk = 0; kk < N_; kk++)\n                {\n                    MPI_Recv(&H_a(jj,kk), 1, MPI_DOUBLE_COMPLEX, me_- 1, 3, MPI_COMM_WORLD, &status);\n                }\n            }\n            \n            // Send own replica to left neighbour\n            for (jj = 0; jj < N_; jj++)\n            {\n                for (kk = 0; kk < N_; kk++)\n                {\n                    MPI_Send(&H_b(jj,kk), 1, MPI_DOUBLE_COMPLEX, me_- 1, 4, MPI_COMM_WORLD);\n                }\n            }\n\n            ham = H_a;\n            eigval = eig_sym(ham);\n            F = free_en(eigval, beta_);\n        }\n    }\n\n    // Swap replica with right neighbour ...\n    void swapright()\n    {\n        MPI_Status status;\n        int control = 0;\n        int jj, kk;\n        double beta_alt = 1/calc_temp(T_min, T_max, me_ + 1, np_, dist);\n        cx_mat H_b(N_,N_); // receive (here it's the other way round!!!)\n        cx_mat H_a = ham; // send\n\n        double f1 = -beta_alt * free_en(eigval, beta_alt);\n        double f4 = beta_ * F;\n\n        MPI_Send(&f1, 1, MPI_DOUBLE, 0, 1, MPI_COMM_WORLD);\n        MPI_Send(&f4, 1, MPI_DOUBLE, 0, 1, MPI_COMM_WORLD);\n\n        MPI_Recv(&control, 1, MPI_INT, 0, 1, MPI_COMM_WORLD, &status);\n\n        if (control == 1)\n        {\n            // Send own replica to right neighbour\n            for (jj = 0; jj < N_; jj++)\n            {\n                for (kk = 0; kk < N_; kk++)\n                {\n                    MPI_Send(&H_a(jj,kk), 1, MPI_DOUBLE_COMPLEX, me_+ 1, 3, MPI_COMM_WORLD);\n                }\n            }\n\n            // Receive replica from right neighbour\n            for (jj = 0; jj < N_; jj++)\n            {\n                for (kk = 0; kk < N_; kk++)\n                {\n                    MPI_Recv(&H_b(jj,kk), 1, MPI_DOUBLE_COMPLEX, me_+ 1, 4, MPI_COMM_WORLD, &status);\n                }\n            }\n\n            ham = H_b;\n            eigval = eig_sym(ham);\n            F = free_en(eigval, beta_);\n        }\n\n    }\n\n    // Parallel Tempering for each temperature point (= \"Swap\"\")\n    void swap()\n    {\n        if (me_ != 1)   \n            swapleft();\n        if (me_ != np_ - 1)     \n            swapright();\n    }\n\n    // Master process for managing swaps:\n    void master(int therm, int sweeps, int sweeps_per_save, int sweeps_per_swap)\n    {\n        MPI_Status status;\n        engine_type loaded, saved; // needed to load and save random engine status\n        int counts = (therm + sweeps)/sweeps_per_swap; // How many swaps in total?\n        int control = 0;  // Signal for accepting / rejecting swap\n        int sign_[np_];   // needed for ensemble optimization \n        int nplus_[np_];  // n+ histogram\n        int nminus_[np_]; // n- histogram\n        double counter[np_]; // How many accepted swaps?\n        double den = 0;\n        int s_i, s_i_plus_1; // sign for each replica (was it at T_min or T_max latest?)\n        double f1, f2, f3, f4; // free energy variables\n        double alpha_pt, gamma_pt; // Monte Carlo variables\n        \n        double fr; // Single flip acceptance rate\n\n        // Autocorrelation times:\n        double tau_en;\n        double tau_fl;\n\n        std::stringstream rng_save; // needed for saving random generator status\n        rng_save << \"rng_\" << me_ << \".saved\";\n\n        std::stringstream sfar; // needed for saving single flip acceptance rates\n        sfar << \"single_flip_rate.saved\";\n\n        std::stringstream nplus_ratio; // needed for saving ratio function f = n_plus / n_tot\n        nplus_ratio << \"n_plus_ratio.saved\";\n\n        std::stringstream swap_ratio; // needed for saving replica exchange ratio\n        swap_ratio << \"swap_ratio.saved\";\n\n        std::stringstream tau_energy; // needed for saving energy autocorrelation time\n        tau_energy << \"tau_energy.saved\";\n\n        std::stringstream tau_flux; // needed for saving flux autocorrelation time\n        tau_flux << \"tau_flux.saved\";\n\n        // Load random generator status:\n        std::ifstream rngfile(rng_save.str().c_str(), std::ifstream::in);\n        if(rngfile.good())\n        {\n            rngfile >> loaded;\n            rngfile.close();\n            eng_ = loaded;\n        }\n\n        // Initialize sign array and histograms\n        for (int k = 0; k < np_; k++)\n        {\n            sign_[k] = 0;\n            nplus_[k] = 0;\n            nminus_[k] = 0;\n            counter[k] = 0;\n        }\n\n        sign_[1] = 1;\n        sign_[np_ - 1] = -1;\n\n        // PT iteration\n        while(counts--)\n        {\n            den += 2;\n\n            // Regard temperature points from T_min to T_max\n            for (int i = 1; i < np_ - 1; i++)\n            {\n                // Receive free energies from replicas\n                MPI_Recv(&f1, 1, MPI_DOUBLE, i, 1, MPI_COMM_WORLD, &status);\n                MPI_Recv(&f4, 1, MPI_DOUBLE, i, 1, MPI_COMM_WORLD, &status);\n                MPI_Recv(&f2, 1, MPI_DOUBLE, i+1, 2, MPI_COMM_WORLD, &status);\n                MPI_Recv(&f3, 1, MPI_DOUBLE, i+1, 2, MPI_COMM_WORLD, &status);\n\n                // Decide if replicas are swapped\n                alpha_pt = exp(f1 + f2 + f3 + f4);\n\t\t        gamma_pt = rng_();\n\n                if (gamma_pt <= alpha_pt) // accept\n                {                    \n                    control = 1;\n\n                    MPI_Send(&control, 1, MPI_INT, i, 1, MPI_COMM_WORLD);\n                    MPI_Send(&control, 1, MPI_INT, i+1, 2, MPI_COMM_WORLD);\n                    \n                    // Record histogram for ensemble optimization:\n                    s_i = check_sign_i(i, np_,  sign_[i], sign_[i+1]);\n                    s_i_plus_1 = check_sign_i_plus_1(i, np_,  sign_[i], sign_[i+1]);\n                    sign_[i] = s_i;\n                    sign_[i+1] = s_i_plus_1;\n                    if (counts < sweeps + therm - 100) // Start recording after a couple of steps ...\n                    {\n                        if (s_i == 1)\n                            nplus_[i] += 1;\n                        else if (s_i = -1)  \n                            nminus_[i] += 1;\n                        if (s_i_plus_1 == 1)\n                            nplus_[i+1] += 1;\n                        else if (s_i_plus_1 == -1)\n                            nminus_[i+1] += 1;\n                    }\n\n                    // Record replica exchange rate:\n                    counter[i] += 1;\n                    counter[i+1] += 1;\n                \n                }\n                else // refuse\n                {\n                    //std::cout << \"NO SWAP \" << i << \" \" << i + 1 << std::endl;\n                    control = 0;\n                    MPI_Send(&control, 1, MPI_INT, i, 1, MPI_COMM_WORLD);\n                    MPI_Send(&control, 1, MPI_INT, i+1, 2, MPI_COMM_WORLD);\n                }  \n            }   \n\n            if (counts % sweeps_per_save == 0)\n            {\n                // Give single flip acceptance rates as output ...\n                std::ofstream sf__(sfar.str().c_str(), std::ofstream::trunc);\n                for (int jj = 1; jj < np_; jj++)\n                {\n                    MPI_Recv(&fr, 1, MPI_DOUBLE, jj, 5, MPI_COMM_WORLD, &status);\n                    sf__ << std::setprecision(17) << calc_temp(T_min, T_max, jj, np_, dist) << \" \" << fr << std::endl;\n                }\n\n\n                // Give histogram as output ...\n                std::ofstream nplus__(nplus_ratio.str().c_str(), std::ofstream::trunc);\n                for (int kk = 1; kk < np_ ; kk++)\n                {\n                    nplus__ << std::setprecision(17) << calc_temp(T_min, T_max, kk, np_, dist) << \" \" << nplus_[kk] / double(nplus_[kk] + nminus_[kk]) << std::endl;\n                }\n\n                // Give swap ratio as output ...\n                std::ofstream swap_ratio__(swap_ratio.str().c_str(), std::ofstream::trunc);\n                for (int ll = 1; ll < np_ ; ll++)\n                {\n                    swap_ratio__ << std::setprecision(17) << calc_temp(T_min, T_max, ll, np_, dist) << \" \" << counter[ll] / den << std::endl;\n                }\n\n                // Save random generator status:\n                saved = eng_;\n                std::ofstream file(rng_save.str().c_str(), std::ofstream::trunc);\n                file << saved;\n            }         \n        }\n\n        // Give autocorrelation times as output ...\n        std::ofstream tau1(tau_energy.str().c_str(), std::ofstream::trunc);\n        std::ofstream tau2(tau_flux.str().c_str(), std::ofstream::trunc);\n        for (int ll = 1; ll < np_; ll++)\n        {\n            MPI_Recv(&tau_en, 1, MPI_DOUBLE, ll, 6, MPI_COMM_WORLD, &status);\n            tau1 << std::setprecision(17) << calc_temp(T_min, T_max, ll, np_, dist) << \" \" << tau_en << std::endl;\n\n            MPI_Recv(&tau_fl, 1, MPI_DOUBLE, ll, 7, MPI_COMM_WORLD, &status);\n            tau2 << std::setprecision(17) << calc_temp(T_min, T_max, ll, np_, dist) << \" \" << tau_fl << std::endl;\n        }\n    }\n\n\n    void load(std::string const & filename)\n    {\n        alps::hdf5::archive ar(filename, \"a\");\n        ar[\"/simulation/results/\"+energy_.representation()] >> energy_;\n        ar[\"/simulation/results/\"+e2_.representation()] >> e2_;\n        //ar[\"/simulation/results/\"+e4_.representation()] >> e4_;\n        ar[\"/simulation/results/\"+dE_db.representation()] >> dE_db;\n        //ar[\"/simulation/results/\"+p_.representation()] >> p_;\n        ar[\"/simulation/results/\"+flux_real.representation()] >> flux_real;\n        ar[\"/simulation/results/\"+flux_imag.representation()] >> flux_imag;\n        ar[\"/simulation/results/\"+flux_real_squared.representation()] >> flux_real_squared;\n        ar[\"/simulation/results/\"+flux_imag_squared.representation()] >> flux_imag_squared;\n        ar[\"/simulation/results/\"+spin_corr.representation()] >> spin_corr;\n        ar[\"/parameters/T\"] >> temp_;\n        ar[\"/parameters/BETA\"] >> beta_;\n        ar[\"/parameters/SWEEPS\"] >> sweeps_;\n        ar[\"/parameters/THERMALIZATION\"] >> thermalization_;\n    }\n    \n    void save(std::string const & filename)\n    {               \n        alps::hdf5::archive ar(filename, \"a\");\n        ar[\"/simulation/results/\"+energy_.representation()] << energy_;\n        ar[\"/simulation/results/\"+e2_.representation()] << e2_;\n        //ar[\"/simulation/results/\"+e4_.representation()] << e4_;\n        ar[\"/simulation/results/\"+dE_db.representation()] << dE_db;\n        //ar[\"/simulation/results/\"+p_.representation()] << p_;\n        ar[\"/simulation/results/\"+flux_real.representation()] << flux_real;\n        ar[\"/simulation/results/\"+flux_imag.representation()] << flux_imag;\n        ar[\"/simulation/results/\"+flux_real_squared.representation()] << flux_real_squared;\n        ar[\"/simulation/results/\"+flux_imag_squared.representation()] << flux_imag_squared;\n        ar[\"/simulation/results/\"+spin_corr.representation()] << spin_corr;\n        ar[\"/parameters/T\"] << temp_;\n        ar[\"/parameters/BETA\"] << beta_;\n        ar[\"/parameters/SWEEPS\"] << sweeps_;\n        ar[\"/parameters/THERMALIZATION\"] << thermalization_;\n    }\n    \n    /////////////////////////////////////////////////////////////////////\n    // Randomize zz-entries of matrix (likewise: all nonzero entries): //\n    /////////////////////////////////////////////////////////////////////\n    \n    cx_mat randomize(cx_mat ham) \n    {    \n        int N_ = size(ham)[0];\n        int die, coord1, coord2;\n\n        for (int j = 0 ; j < 3*N_/2; j++)\n        {\n            die = roll_die(length_);\n            coord1 = v_[die]/N_;\n            coord2 = v_[die]%N_;\n        \n            // Flip a coin:\n            if (rng_() < 0.5)\n            {\n                ham(coord1, coord2) *= -1;\n                ham(coord2, coord1) *= -1;\n            }\n        }\n\n        return ham;\n    }\n\n    /*cx_mat bond_randomize(cx_mat ham) \n    {    \n        int N_ = size(ham)[0];\n        int die, coord1, coord2;\n        double dJ = 0.8;\n\n        for (int j = 0 ; j < N_/4; j++)\n        {\n            die = roll_die(length_);\n            coord1 = v_[die]/N_;\n            coord2 = v_[die]%N_;\n        \n            // Flip a coin:\n            if (rng_() < 0.5)\n            {\n                ham(coord1, coord2) -= dJ;\n                ham(coord2, coord1) = -ham(coord1, coord2);\n            }\n            else\n            {\n                ham(coord1, coord2) += dJ;\n                ham(coord2, coord1) = -ham(coord1, coord2);\n            }\n        }\n\n        return ham;\n    }*/\n\n    ////////////////////////////////////////////////////////////////\n    \n    protected:\n    \n    // Random int from the interval [0,max)\n    int roll_die(int max) const\n    {\n        return static_cast<int>(max * rng_());\n    }\n\nprivate:\n    typedef boost::mt19937 engine_type; // Mersenne twister\n    typedef boost::uniform_real<> distribution_type;\n    typedef boost::variate_generator<engine_type&, distribution_type> rng_type;\n    engine_type eng_;\n    distribution_type dist_;\n    mutable rng_type rng_;\n\n    size_t sweeps_;\n    size_t thermalization_;\n\n    // Everything here is described above:\n    int np_;\n    int me_;\n    double T_min;\n    double T_max; \n    double temp_;\n    double beta_;\n\n    cx_mat ham;\n    size_t N_;\n\n    std::vector<int> v_;\n    int length_;\n\n    vec eigval;\n\n    double F;\n\n    Mat<int> plaquettes;\n\n    // ALPS Observables:\n\n    alps::RealObservable energy_;\n    alps::RealObservable e2_;\n    //alps::RealObservable e4_;\n    alps::RealObservable dE_db;\n    //alps::RealObservable p_;\n    alps::RealObservable flux_real;\n    alps::RealObservable flux_imag;\n    alps::RealObservable flux_real_squared;\n    alps::RealObservable flux_imag_squared;\n    alps::RealObservable spin_corr;\n\n    int flip_rate;\n\n    signed int sign;\n\n    std::string dist;\n    std::string filename_;\n};\n", "meta": {"hexsha": "357414521be4cd73c4e8e1fb262d4ff8edd47a9c", "size": 29879, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "simulation.hpp", "max_stars_repo_name": "timeschmann/Kitaev_QMC", "max_stars_repo_head_hexsha": "eab9167571507bcbbad35a2c4ff1367b21604d59", "max_stars_repo_licenses": ["MIT"], "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.hpp", "max_issues_repo_name": "timeschmann/Kitaev_QMC", "max_issues_repo_head_hexsha": "eab9167571507bcbbad35a2c4ff1367b21604d59", "max_issues_repo_licenses": ["MIT"], "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.hpp", "max_forks_repo_name": "timeschmann/Kitaev_QMC", "max_forks_repo_head_hexsha": "eab9167571507bcbbad35a2c4ff1367b21604d59", "max_forks_repo_licenses": ["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.1931684335, "max_line_length": 164, "alphanum_fraction": 0.5120987985, "num_tokens": 7270, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7154239957834733, "lm_q2_score": 0.46101677931231594, "lm_q1q2_score": 0.32982246637884477}}
{"text": "// Functions for manipulating circuit values via MNA in Eigen\n// Author: Jeff Trull <edaskel@att.net>\n\n/*\nCopyright (c) 2014 Jeffrey E. Trull\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 <Eigen/Dense>\n\n// \"stamp\" functions for adding components to a circuit\ntemplate<int sz>\nvoid stamp_r(Eigen::Matrix<double, sz, sz>& G,\n             Eigen::Matrix<double, sz, sz> const&,\n             int node1, int node2, double r) {\n    // You can think of this as KCL at the two nodes the resistor connects\n    G(node1, node1) += 1.0/r;\n    G(node1, node2) -= 1.0/r;\n    G(node2, node2) += 1.0/r;\n    G(node2, node1) -= 1.0/r;\n}\n\n// ground lumped variant\ntemplate<int sz>\nvoid stamp_r(Eigen::Matrix<double, sz, sz>& G,\n             Eigen::Matrix<double, sz, sz> const&,\n             int node, double r) {\n    G(node, node) += 1.0/r;\n}\n\n// voltage source inputs and inductors get this treatment:\ntemplate<int sz>\nvoid stamp_i(Eigen::Matrix<double, sz, sz>& G,\n             Eigen::Matrix<double, sz, sz> const&,\n             int node1, int node2, int istate) {\n    G(node1, istate) =  1;\n    G(istate, node1) = -1;\n    G(node2, istate) = -1;\n    G(istate, node2) =  1;\n}\n\ntemplate<int sz>\nvoid stamp_i(Eigen::Matrix<double, sz, sz>& G,\n             Eigen::Matrix<double, sz, sz> const&,\n             int node, int istate) {\n    G(node, istate) =  1;\n    G(istate, node) = -1;\n}\n\ntemplate<int sz>\nvoid stamp_c(Eigen::Matrix<double, sz, sz> const&,\n             Eigen::Matrix<double, sz, sz>& C,\n             int node1, int node2, double c) {\n    C(node1, node1) += c;\n    C(node1, node2) -= c;\n    C(node2, node2) += c;\n    C(node2, node1) -= c;\n}\n\ntemplate<int sz>\nvoid stamp_c(Eigen::Matrix<double, sz, sz> const&,\n             Eigen::Matrix<double, sz, sz>& C,\n             int node, double c) {\n    C(node, node) += c;  // assumes other terminal is ground\n}\n\ntemplate<int sz>\nvoid stamp_l(Eigen::Matrix<double, sz, sz>& G,\n             Eigen::Matrix<double, sz, sz>& C,\n             int node1, int node2, int istate, double l) {\n    C(istate, istate) += l;\n    // For inductors we have an extra state that remembers its current\n    stamp_i(G, C, node1, node2, istate);\n}\n\ntemplate<int sz>\nvoid stamp_l(Eigen::Matrix<double, sz, sz>& G,\n             Eigen::Matrix<double, sz, sz>& C,\n             int node, int istate, double l) {\n    C(istate, istate)  +=  l;\n    stamp_i(G, C, node, istate);\n}\n\ntemplate<class M>\nbool isSingular(const M& m) {\n   // A singular matrix has at least one zero eigenvalue -\n   // in theory, at least... but due to machine precision we can have \"nearly singular\"\n   // matrices that misbehave.  Comparing rank instead is safer because it uses thresholds\n   // for near-zero values.\n\n   assert(m.rows() == m.cols());   // singularity has no meaning for a non-square matrix\n   return (m.fullPivLu().rank() != m.rows());\n\n}\n\n// Calculate moments of given system in MNA form\ntemplate<typename Float, int nrows, int ncols>\nusing MatrixVector = std::vector<Eigen::Matrix<Float, nrows, ncols>,\n                                 Eigen::aligned_allocator<Eigen::Matrix<Float, nrows, ncols> > >;\n\n\ntemplate<int icount, int ocount, int scount, typename Float = double>\nMatrixVector<Float, ocount, icount>\nmoments(Eigen::Matrix<Float, scount, scount> const & G,\n        Eigen::Matrix<Float, scount, scount> const & C,\n        Eigen::Matrix<Float, scount, icount> const & B,\n        Eigen::Matrix<Float, scount, ocount> const & L,\n        Eigen::Matrix<Float, ocount, icount> const & E,\n        size_t count) {\n    using namespace Eigen;\n\n    MatrixVector<Float, ocount, icount> result;\n\n    auto G_QR = G.fullPivHouseholderQr();\n    Matrix<Float, scount, scount> A = -G_QR.solve(C);\n    Matrix<Float, scount, icount> R = G_QR.solve(B);\n\n    result.push_back(L.transpose() * R + E);   // incorporate feedthrough into first moment\n    Matrix<Float, scount, scount> AtotheI = A;\n    for (size_t i = 1; i < count; ++i) {\n        result.push_back(L.transpose() * AtotheI * R);\n        AtotheI = A * AtotheI;\n    }\n\n    return result;\n}\n\n// Implementation of Natarajan regularization\n// Each iteration of this process can produce an input derivative term that we subsequently\n// absorb into the state variable once the process is complete.  This means potentially\n// a series of input derivative coefficients (B's).  We hide that from the users by delegating here:\n\ntemplate<int icount, int ocount, int scount, typename Float = double>\nstd::tuple<Eigen::Matrix<Float, Eigen::Dynamic, Eigen::Dynamic>,   // G result\n           Eigen::Matrix<Float, Eigen::Dynamic, Eigen::Dynamic>,   // C result\n           Eigen::Matrix<Float, Eigen::Dynamic, icount>,    // B result\n           Eigen::Matrix<Float, Eigen::Dynamic, ocount>,    // D result\n           Eigen::Matrix<Float, ocount, icount> >    // E result (feedthrough)\nregularize(Eigen::Matrix<Float, scount, scount> const & G,\n           Eigen::Matrix<Float, scount, scount> const & C,\n           MatrixVector<Float, scount, icount> const & B, // in decreasing order of derived-ness\n           Eigen::Matrix<Float, scount, ocount> const & D) {\n\n    // Implements the algorithm in [Natarajan]\n    // Circuits, Devices and Systems, IEE Proceedings G, June 1991\n\n    using namespace Eigen;\n    typedef Matrix<Float, Dynamic, Dynamic> MatrixD;\n\n    // Step 1: put C into \"Row Echelon\" form by performing LU factorization\n    auto lu = C.fullPivLu();\n    auto k = lu.rank();\n    if (k == C.rows()) {\n        // C is already non-singular\n        Matrix<Float, ocount, icount>   E = Matrix<Float, ocount, icount>::Zero();\n        return std::make_tuple(G, C, B.back(), D, E);\n    }\n\n    MatrixD U = lu.matrixLU().template triangularView<Upper>();\n    MatrixD L = lu.matrixLU().template triangularView<UnitLower>();\n\n    // Step 2: \"perform the same elementary operations on G and B\"\n    // given that C = P.inverse() * L * U * Q.inverse()\n    // (from source it seems that permutationP/Q is inverse)\n    // then to get the new G we reverse those operations:\n    auto Cprime = U;   // note we may have small non-zero values in bottom rows, but they will be ignored\n    auto P = lu.permutationP();\n    auto Q = lu.permutationQ();\n\n    assert(!isSingular(L));\n    MatrixD Gprime = L.fullPivLu().solve(P * G * Q);                   // rows and columns\n    MatrixVector<Float, scount, icount> Bprime;\n    std::transform(B.begin(), B.end(), std::back_inserter(Bprime),\n                   [L, P](Matrix<Float, scount, icount> const& b) -> Matrix<Float, scount, icount> {\n                       return L.fullPivLu().solve(P * b);              // rows only\n                   });\n\n    // The D input is like L in PRIMA but this algorithm uses the transpose\n    Matrix<Float, ocount, scount> Dprime = D.transpose() * Q;          // columns only\n\n    // Step 3: \"Convert [G21 G22] matrix into row echelon form starting from the last row\"\n    MatrixD Cnew, Gnew, Dnew;\n    MatrixVector<Float, scount, icount> Bnew;\n\n    if (Cprime.rows() == (k+1)) {\n        // if G22 is only a single row, there is no point attempting to decompose it\n        Cnew = Cprime; Gnew = Gprime; Bnew = Bprime; Dnew = Dprime;\n    } else {\n        // decompose the bottom rows\n        // Upon close review of the first example in the paper, the author is not only\n        // converting from the last row, but also *from the last column*, i.e., he\n        // performs a standard gaussian elimination on the matrix rotated 180 degrees\n\n        // Plan of attack: reverse G2, perform LU decomposition, reverse result, reverse permutations\n        MatrixD G2R = Gprime.bottomRows(C.rows() - k).reverse();\n\n        auto G2R_LU = G2R.fullPivLu();\n        MatrixD G2R_U = (G2R_LU.matrixLU().template triangularView<Upper>());\n\n        // Since the order of the rows is irrelevant, I'll perform the decomposition, then\n        // combine reversing the rows with the row reordering the LU decomposition produces\n\n        MatrixD exchange_columns = G2R_LU.permutationQ();\n        Gnew = Gprime * exchange_columns.reverse();\n\n        // insert already-permuted rows that came from LU, but in reverse order\n        Gnew.block(k, 0, Gprime.rows() - k, Gprime.cols()) = G2R_U.reverse();\n\n        // Step 4: \"Carry out the same row operations in the B matrix\"\n        // Note: not necessary to do it for C, because all coefficients are zero in those rows\n\n        // 4.1 reverse the rows in B2\n        typedef PermutationMatrix<Dynamic, Dynamic, std::size_t> PermutationD;\n        PermutationD reverse_rows;                // order of rows is completely reversed\n        reverse_rows.setIdentity(G2R.rows());     // start with null permutation\n        for (std::size_t i = 0; i < (G2R.rows() / 2); ++i) {\n            reverse_rows.applyTranspositionOnTheRight(i, (G2R.rows()-1) - i);\n        }\n\n        // 4.2 extract and apply L operation from reversed G2\n        MatrixD G2R_L = G2R_LU.matrixLU().leftCols(G2R.rows()).template triangularView<UnitLower>();\n        std::transform(Bprime.begin(), Bprime.end(), std::back_inserter(Bnew),\n                       [reverse_rows, k, G2R_L, G2R_LU]\n                       (Matrix<Float, scount, icount> const& bp) {\n                           MatrixD B2R = reverse_rows * bp.bottomRows(bp.rows() - k);\n                           Matrix<Float, scount, icount> bn = bp;\n                           bn.block(k, 0, bn.rows() - k, bn.cols()) =\n                               reverse_rows.transpose() * G2R_L.fullPivLu().solve(G2R_LU.permutationP() * B2R);\n                           return bn;\n                       });\n\n        // Step 5: \"Interchange the columns in the G, C, and D matrices... such that G22 is non-singular\"\n        // Since we have done a full pivot factorization of G2 I assume G22 is already non-singular,\n        // so the only thing left to do is reorder the C and D matrices according to the G2 factorization\n        Cnew = Cprime * exchange_columns.reverse();\n        Dnew = Dprime * exchange_columns.reverse();\n    }\n\n    // Step 6: compute reduced matrices using equations given in paper\n    MatrixD G11 = Gnew.topLeftCorner(k, k);\n    MatrixD G12 = Gnew.topRightCorner(k, Gnew.rows() - k);\n    MatrixD G21 = Gnew.bottomLeftCorner(Gnew.rows() - k, k);\n    MatrixD G22 = Gnew.bottomRightCorner(Gnew.rows() - k, Gnew.rows() - k);\n    MatrixD C11 = Cnew.topLeftCorner(k, k);\n    MatrixD C12 = Cnew.topRightCorner(k, Cnew.rows() - k);\n    MatrixD D01 = Dnew.leftCols(k);\n    MatrixD D02 = Dnew.rightCols(Dnew.cols() - k);\n\n    assert(!isSingular(G22));\n    auto    G22_LU = G22.fullPivLu();\n\n    MatrixD Gfinal  = G11 - G12 * G22_LU.solve(G21);\n    MatrixD Cfinal  = C11 - C12 * G22_LU.solve(G21);\n    Matrix<Float, ocount, Dynamic> Dfinal\n                    = D01 - D02 * G22_LU.solve(G21);\n\n    Matrix<Float, Dynamic, icount> B02 = Bnew.back().bottomRows(Bnew.back().rows() - k);\n    Matrix<Float, ocount, icount> E1\n                    =       D02 * G22_LU.solve(B02);\n\n    // reduce the entire series of B's to the new size\n    // Performing the same substitution as in Natarajan beginning with eqn [5]\n    // but with additional input derivatives present.  Adding B11/B12 multiplying a first\n    // derivative of Ws demonstrates that each additional input derivative term contributes:\n    // Bn1 - G12 * G22^-1 * Bn2  to its own term, and\n    //     - C12 * G22^-1 * Bn2  to the derivative n+1 coefficient,\n    // once reduced.\n    MatrixVector<Float, Dynamic, icount> Btrans;\n    // n+1's first (equation 9d)\n    std::transform(Bnew.begin(), Bnew.end(), std::back_inserter(Btrans),\n                   [k, G12, C12, G22_LU](Matrix<Float, scount, icount> const& Bn) {\n                       Matrix<Float, Dynamic, icount> Bn2 = Bn.bottomRows(Bn.rows() - k);\n                       return -C12 * G22_LU.solve(Bn2);\n                   });\n    Btrans.push_back(Matrix<Float, Dynamic, icount>::Zero(k, icount));  // contribution from n-1 is 0 (nonexistent)\n\n    // n's next, shifted by one (equation 9c)\n    std::transform(Bnew.begin(), Bnew.end(), Btrans.begin()+1, Btrans.begin()+1,\n                   [k, G12, G22_LU](Matrix<Float, scount, icount> const& Bn,\n                                         Matrix<Float, Dynamic, icount> const& Bnm1_contribution)\n                   -> Matrix<Float, Dynamic, icount> {  // without explicitly declared return type Eigen\n                                                        // will keep references to these locals:\n                       Matrix<Float, Dynamic, icount> Bn1 = Bn.topRows(k);\n                       Matrix<Float, Dynamic, icount> Bn2 = Bn.bottomRows(Bn.rows() - k);\n\n                       return Bn1 - G12 * G22_LU.solve(Bn2) + Bnm1_contribution;\n                   });\n\n    // If Cfinal is singular, we need to repeat this analysis on the new matrices\n    if (isSingular(Cfinal)) {\n        Matrix<Float, Dynamic, ocount> Dtrans = Dfinal.transpose();   // no implicit conversion on fn tmpl args\n        auto recursive_result = regularize<icount, ocount, Dynamic>(Gfinal, Cfinal, Btrans, Dtrans);\n        return std::make_tuple(std::get<0>(recursive_result),  // G\n                               std::get<1>(recursive_result),  // C\n                               std::get<2>(recursive_result),  // B\n                               std::get<3>(recursive_result),  // D\n                               std::get<4>(recursive_result) + E1);  // combine E\n    }\n\n    // We've found a non-singular Cfinal and a set of B's\n    // We need to apply a transformation suggested by Chen (TCAD July 2012) to eliminate\n    // all input derivative terms.  Chen gives only the simplest case, for B0 * Ws + B1 * Ws' :\n    // Br = B0 - Gr * Cr^-1 * B1\n    // based on a variable substitution of:\n    // Xnew = X - Cr^-1 * B1 * Ws\n    // and mentions the rest should be done \"recursively\".  I believe the general case is:\n    // Br = B0 - Gr * Cr^-1 * (B1 - Gr * Cr^-1 *(B2 - ... ))\n    Matrix<Float, Dynamic, icount> Bfinal = Matrix<Float, Dynamic, icount>::Zero(k, icount);\n    Bfinal = std::accumulate(\n        // starting with the first (most derived) coefficient, compute above expression for Br:\n        Btrans.begin(), Btrans.end(), Bfinal,\n        [Gfinal, Cfinal](Matrix<Float, Dynamic, icount> const& acc,\n                         Matrix<Float, Dynamic, icount> const& B) {\n            return B - Gfinal * Cfinal.fullPivHouseholderQr().solve(acc);\n        });\n\n    // The variable substitution for the 2nd derivative case is:\n    // Xnew = X - Cr^-1 * (B2 * Ws' - (Gr * Cr^-1 * B2 - B1) * Ws)\n    // Making this substitution in the output equation Y = D * X + E * Ws gives\n    // Y = D * Xnew + D * Cr^-1 * (B1 - Gr * Cr^-1 * B2) * Ws + Cr^-1 * B2 * Ws'\n    // however, if the Ws' term is nonzero the system is ill-formed:\n    if (Btrans.size() >= 3) {\n        Matrix<Float, Dynamic, icount> CinvB = Cfinal.fullPivLu().solve(*(Btrans.rbegin()+2));\n        assert(CinvB.isZero());\n    }\n\n    // now I can calculate the new value for E, which can only be:\n    // E = E1 + D * Cr^-1 * B1\n    // because, thanks to the assertion, all other terms must be 0\n    Matrix<Float, ocount, icount> Efinal = E1 + Dfinal * Cfinal.fullPivHouseholderQr().solve(*(Btrans.rbegin()+1));\n\n    return std::make_tuple(Gfinal, Cfinal, Bfinal,\n                           Dfinal.transpose(),  // for PRIMA compatibility\n                           Efinal);\n}\n\n// user-facing function (only one \"B\" parameter)\ntemplate<int icount, int ocount, int scount, typename Float = double>\nstd::tuple<Eigen::Matrix<Float, Eigen::Dynamic, Eigen::Dynamic>,   // G result\n           Eigen::Matrix<Float, Eigen::Dynamic, Eigen::Dynamic>,   // C result\n           Eigen::Matrix<Float, Eigen::Dynamic, icount>,    // B result\n           Eigen::Matrix<Float, Eigen::Dynamic, ocount>,    // D result\n           Eigen::Matrix<Float, ocount, icount> >    // E result (feedthrough)\nregularize(Eigen::Matrix<Float, scount, scount> const & G,\n           Eigen::Matrix<Float, scount, scount> const & C,\n           Eigen::Matrix<Float, scount, icount> const & B,\n           Eigen::Matrix<Float, scount, ocount> const & D) {\n    return regularize(G, C, MatrixVector<Float, scount, icount>(1, B), D);\n}\n", "meta": {"hexsha": "83f52eab24fc5e78edf7f788d2a039472fe8c582", "size": 17145, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "mna.hpp", "max_stars_repo_name": "jefftrull/CktSimLightningTalk", "max_stars_repo_head_hexsha": "3eb582da43149c5efa8930fc0576f025cb7c72fc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2015-01-04T10:52:35.000Z", "max_stars_repo_stars_event_max_datetime": "2019-03-03T00:49:12.000Z", "max_issues_repo_path": "mna.hpp", "max_issues_repo_name": "jefftrull/CktSimLightningTalk", "max_issues_repo_head_hexsha": "3eb582da43149c5efa8930fc0576f025cb7c72fc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "mna.hpp", "max_forks_repo_name": "jefftrull/CktSimLightningTalk", "max_forks_repo_head_hexsha": "3eb582da43149c5efa8930fc0576f025cb7c72fc", "max_forks_repo_licenses": ["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.7166212534, "max_line_length": 115, "alphanum_fraction": 0.6194808982, "num_tokens": 4613, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6442250928250375, "lm_q2_score": 0.5117166047041654, "lm_q1q2_score": 0.32966067716565395}}
{"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// @file Declaration of functionality that runs the R1CS ppzkSNARK for\n// a given R1CS example.\n//---------------------------------------------------------------------------//\n\n#ifndef CRYPTO3_RUN_R1CS_PPZKSNARK_HPP\n#define CRYPTO3_RUN_R1CS_PPZKSNARK_HPP\n\n#include <boost/config.hpp>\n\n#include <nil/crypto3/zk/snark/systems/ppzksnark/r1cs_ppzksnark.hpp>\n\n#include \"../r1cs_examples.hpp\"\n\n#include <nil/crypto3/zk/snark/algorithms/generate.hpp>\n#include <nil/crypto3/zk/snark/algorithms/verify.hpp>\n#include <nil/crypto3/zk/snark/algorithms/prove.hpp>\n\nnamespace nil {\n    namespace crypto3 {\n        namespace zk {\n            namespace snark {\n\n                /*template<typename CurveType>\n                typename std::enable_if<CurveType::has_affine_pairing, void>::type\n                test_affine_verifier(const typename r1cs_ppzksnark<CurveType>::verification_key_type &vk,\n                                     const typename r1cs_ppzksnark<CurveType>::primary_input_type &primary_input,\n                                     const typename r1cs_ppzksnark<CurveType>::proof_type &proof,\n                                     const bool expected_answer) {\n                    const bool answer = r1cs_ppzksnark_affine_verifier_weak_IC<CurveType>(vk, primary_input, proof);\n                    BOOST_CHECK(answer == expected_answer);\n                }\n\n                template<typename CurveType>\n                typename std::enable_if<!CurveType::has_affine_pairing, void>::type\n                test_affine_verifier(const typename r1cs_ppzksnark<CurveType>::verification_key_type &vk,\n                                     const typename r1cs_ppzksnark<CurveType>::primary_input_type &primary_input,\n                                     const typename r1cs_ppzksnark<CurveType>::proof_type &proof,\n                                     const bool expected_answer) {\n                    BOOST_ATTRIBUTE_UNUSED(vk, primary_input, proof, expected_answer);\n                }*/\n\n                /**\n                 * The code below provides an example of all stages of running a R1CS ppzkSNARK.\n                 *\n                 * Of course, in a real-life scenario, we would have three distinct entities,\n                 * mangled into one in the demonstration below. The three entities are as follows.\n                 * (1) The \"generator\", which runs the ppzkSNARK generator on input a given\n                 *     constraint system CS to create a proving and a verification key for CS.\n                 * (2) The \"prover\", which runs the ppzkSNARK prover on input the proving key,\n                 *     a primary input for CS, and an auxiliary input for CS.\n                 * (3) The \"verifier\", which runs the ppzkSNARK verifier on input the verification key,\n                 *     a primary input for CS, and a proof.\n                 */\n                template<typename CurveType>\n                bool run_r1cs_ppzksnark(const r1cs_example<typename CurveType::scalar_field_type> &example) {\n\n                    using basic_proof_system = r1cs_ppzksnark<CurveType>;\n                    using weak_proof_system = r1cs_ppzksnark<CurveType,\n                                          r1cs_ppzksnark_generator<CurveType>,\n                                          r1cs_ppzksnark_prover<CurveType>,\n                                          r1cs_ppzksnark_verifier_weak_input_consistency<CurveType>>;\n\n                    std::cout << \"Starting generator\" << std::endl;\n                    typename basic_proof_system::keypair_type keypair =\n                        generate<basic_proof_system>(example.constraint_system);\n\n                    std::cout << \"Starting verification key processing\" << std::endl;\n\n                    typename basic_proof_system::processed_verification_key_type pvk =\n                        r1cs_ppzksnark_process_verification_key<CurveType>::process(keypair.second);\n\n                    std::cout << \"Starting prover\" << std::endl;\n\n                    typename basic_proof_system::proof_type proof =\n                        prove<basic_proof_system>(keypair.first, example.primary_input, example.auxiliary_input);\n\n                    std::cout << \"Starting verifier\" << std::endl;\n\n                    const bool ans = verify<basic_proof_system>(keypair.second, example.primary_input, proof);\n\n                    std::cout << \"Verifier finished, result: \" << ans << std::endl;\n\n                    std::cout << \"Starting online verifier\" << std::endl;\n\n                    const bool ans2 =\n                        verify<basic_proof_system>(pvk, example.primary_input, proof);\n\n                    std::cout << \"Online verifier finished, result: \" << ans2 << std::endl;\n\n                    BOOST_CHECK(ans == ans2);\n\n                    std::cout << \"Starting weak verifier\" << std::endl;\n\n                    const bool ans3 = verify<weak_proof_system>(keypair.second,\n                    example.primary_input, proof);\n\n                    std::cout << \"Weak verifier finished, result: \" << ans3 << std::endl;\n\n                    BOOST_CHECK(ans == ans3);\n\n                    std::cout << \"Starting online weak verifier\" << std::endl;\n\n                    const bool ans4 = verify<weak_proof_system>(pvk, example.primary_input, proof);\n\n                    std::cout << \"Online weak verifier finished, result: \" << ans4 << std::endl;\n\n                    BOOST_CHECK(ans == ans4);\n\n                    /*test_affine_verifier<CurveType>(keypair.second, example.primary_input, proof, ans);*/\n\n                    return ans;\n                }\n            }    // namespace snark\n        }        // namespace zk\n    }            // namespace crypto3\n}    // namespace nil\n\n#endif    // CRYPTO3_RUN_R1CS_PPZKSNARK_HPP\n", "meta": {"hexsha": "dc5fb85e78f77b5ca6625aaa83d309ad99a1d811", "size": 7151, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "test/systems/ppzksnark/r1cs_ppzksnark/run_r1cs_ppzksnark.hpp", "max_stars_repo_name": "NilFoundation/zk", "max_stars_repo_head_hexsha": "60c63ba8e719620e9fe68d68621c84afded2a809", "max_stars_repo_licenses": ["MIT"], "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/systems/ppzksnark/r1cs_ppzksnark/run_r1cs_ppzksnark.hpp", "max_issues_repo_name": "NilFoundation/zk", "max_issues_repo_head_hexsha": "60c63ba8e719620e9fe68d68621c84afded2a809", "max_issues_repo_licenses": ["MIT"], "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/systems/ppzksnark/r1cs_ppzksnark/run_r1cs_ppzksnark.hpp", "max_forks_repo_name": "NilFoundation/zk", "max_forks_repo_head_hexsha": "60c63ba8e719620e9fe68d68621c84afded2a809", "max_forks_repo_licenses": ["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.006993007, "max_line_length": 116, "alphanum_fraction": 0.5885890085, "num_tokens": 1460, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6297746074044134, "lm_q2_score": 0.5234203489363239, "lm_q1q2_score": 0.32963684475885446}}
{"text": "// Copyright 2014 BVLC and contributors.\n\n#include <boost/math/special_functions/next.hpp>\n#include <boost/random.hpp>\n\n#include <limits>\n\n#include \"caffe/common.hpp\"\n#include \"caffe/util/math_functions.hpp\"\n#include \"caffe/util/rng.hpp\"\n\nstatic const clblasOrder order = clblasColumnMajor;\n#define pi 3.1415926\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_gpu_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    clblasTranspose transA = (TransA == CblasNoTrans)? clblasNoTrans : clblasTrans;\n    clblasTranspose transB = (TransB == CblasNoTrans)? clblasNoTrans : clblasTrans;\n    int lda = (TransA == CblasNoTrans) ? K : M;\n    int ldb = (TransB == CblasNoTrans) ? N : K;\n    int ldc = N;\n    //AMDBLAS_CHECK( clAmdBlasSgemm(amdDevice.col, transB, transA, N, M, K, (cl_float)alpha, (cl_mem)B, ldb, (cl_mem)A, lda, (cl_float)beta, (cl_mem)C, ldc, 1, &(amdDevice.CommandQueue), 0, NULL, NULL) );\n    AMDBLAS_CHECK( clblasSgemm(amdDevice.col, transB, transA, N, M, K, (cl_float)alpha, (cl_mem)B, 0, ldb, (cl_mem)A, 0, lda, (cl_float)beta, (cl_mem)C, 0, ldc, 1, &(amdDevice.CommandQueue), 0, NULL, NULL) );\n}\n\ntemplate <>\nvoid caffe_gpu_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    clblasTranspose transA = (TransA == CblasNoTrans)? clblasNoTrans : clblasTrans;\n    clblasTranspose transB = (TransB == CblasNoTrans)? clblasNoTrans : clblasTrans;\n    int lda = (TransA == CblasNoTrans) ? K : M;\n    int ldb = (TransB == CblasNoTrans) ? N : K;\n    int ldc = N;\n    AMDBLAS_CHECK( clblasDgemm(amdDevice.col, transB, transA, N, M, K, (cl_float)alpha, (cl_mem)B, 0, ldb, (cl_mem)A, 0, lda, (cl_float)beta, (cl_mem)C, 0, ldc, 1, &(amdDevice.CommandQueue), 0, NULL, NULL) );\n}\n\ntemplate <>\ncl_event caffe_gpu_gemm_ex<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 int offA, const float* B, const int offB, const float beta, float* C, const int offC) {\n    cl_event event;\n    clblasTranspose transA = (TransA == CblasNoTrans)? clblasNoTrans : clblasTrans;\n    clblasTranspose transB = (TransB == CblasNoTrans)? clblasNoTrans : clblasTrans;\n    int lda = (TransA == CblasNoTrans) ? K : M;\n    int ldb = (TransB == CblasNoTrans) ? N : K;\n    int ldc = N;\n    AMDBLAS_CHECK( clblasSgemm(amdDevice.col, transB, transA, N, M, K, (cl_float)alpha, (cl_mem)B, offB, ldb, (cl_mem)A, offA, lda, (cl_float)beta, (cl_mem)C, offC, ldc, 1, &(amdDevice.CommandQueue), 0, NULL, &event) );\n    return event;\n}\n\ntemplate <>\ncl_event caffe_gpu_gemm_ex<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 int offA, const double* B, const int offB, const double beta, double* C, const int offC) {\n    cl_event event;\n    clblasTranspose transA = (TransA == CblasNoTrans)? clblasNoTrans : clblasTrans;\n    clblasTranspose transB = (TransB == CblasNoTrans)? clblasNoTrans : clblasTrans;\n    int lda = (TransA == CblasNoTrans) ? K : M;\n    int ldb = (TransB == CblasNoTrans) ? N : K;\n    int ldc = N;\n    AMDBLAS_CHECK( clblasDgemm(amdDevice.col, transB, transA, N, M, K, (cl_float)alpha, (cl_mem)B, offB, ldb, (cl_mem)A, offA, lda, (cl_float)beta, (cl_mem)C, offC, ldc, 1, &(amdDevice.CommandQueue), 0, NULL, &event) );\n    return event;\n}\n\n\ntemplate <>\ncl_event caffe_gpu_gemmex<float>(cl_command_queue *queue, 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 int offA, const float* B, const int offB, const float beta, float* C, const int offC) {\n    cl_event event;\n    clblasTranspose transA = (TransA == CblasNoTrans)? clblasNoTrans : clblasTrans;\n    clblasTranspose transB = (TransB == CblasNoTrans)? clblasNoTrans : clblasTrans;\n    int lda = (TransA == CblasNoTrans) ? K : M;\n    int ldb = (TransB == CblasNoTrans) ? N : K;\n    int ldc = N;\n    //AMDBLAS_CHECK( clAmdBlasSgemmEx(amdDevice.col, transB, transA, N, M, K, (cl_float)alpha, (cl_mem)B, offB, ldb, (cl_mem)A, offA, lda, (cl_float)beta, (cl_mem)C, offC, ldc, 1, queue, 0, NULL, NULL) );\n    AMDBLAS_CHECK( clblasSgemm(amdDevice.col, transB, transA, N, M, K, (cl_float)alpha, (cl_mem)B, offB, ldb, (cl_mem)A, offA, lda, (cl_float)beta, (cl_mem)C, offC, ldc, 1, queue, 0, NULL, &event) );\n    return event;\n }\n\ntemplate <>\ncl_event caffe_gpu_gemmex<double>(cl_command_queue *queue, 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 int offA, const double* B, const int offB, const double beta, double* C, const int offC) {\n    cl_event event;\n    clblasTranspose transA = (TransA == CblasNoTrans)? clblasNoTrans : clblasTrans;\n    clblasTranspose transB = (TransB == CblasNoTrans)? clblasNoTrans : clblasTrans;\n    int lda = (TransA == CblasNoTrans) ? K : M;\n    int ldb = (TransB == CblasNoTrans) ? N : K;\n    int ldc = N;\n    //AMDBLAS_CHECK( clAmdBlasSgemmEx(amdDevice.col, transB, transA, N, M, K, (cl_float)alpha, (cl_mem)B, offB, ldb, (cl_mem)A, offA, lda, (cl_float)beta, (cl_mem)C, offC, ldc, 1, queue, 0, NULL, NULL) );\n    AMDBLAS_CHECK( clblasDgemm(amdDevice.col, transB, transA, N, M, K, (cl_float)alpha, (cl_mem)B, offB, ldb, (cl_mem)A, offA, lda, (cl_float)beta, (cl_mem)C, offC, ldc, 1, queue, 0, NULL, &event) );\n    return event;\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_gpu_gemvv<float>(const CBLAS_TRANSPOSE TransA, const int M,\n    const int N, const float alpha, const float* A, size_t offA, int lda, \n    const float* x, size_t offx, const float beta, int incx, \n    float* y, size_t offy, int incy) {\n    clblasTranspose transA = (TransA == CblasNoTrans)? clblasNoTrans : clblasTrans;\n    AMDBLAS_CHECK( clblasSgemv(amdDevice.row, transA,\n                                  M, N, (cl_float)alpha, (cl_mem)A, offA, lda,\n                                  (cl_mem)x, offx, incx, (cl_float)beta, \n                                  (cl_mem)y, offy, incy,\n                                  1, &(amdDevice.CommandQueue), 0, NULL, NULL) );\n}\n\ntemplate <>\nvoid caffe_gpu_gemvv<double>(const CBLAS_TRANSPOSE TransA, const int M,\n    const int N, const double alpha, const double* A, size_t offA, int lda,\n    const double* x, size_t offx, const double beta, int incx,\n    double* y, size_t offy, int incy) {\n    clblasTranspose transA = (TransA == CblasNoTrans)? clblasNoTrans : clblasTrans;\n    AMDBLAS_CHECK( clblasSgemv(amdDevice.row, transA, M, N, (cl_double)alpha, (cl_mem)A, offA, lda, (cl_mem)x, offx, incx, (cl_double)beta, (cl_mem)y, offy, incy, 1, &(amdDevice.CommandQueue), 0, NULL, NULL) );\n\n}\n\n\ntemplate <>\nvoid caffe_gpu_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}\n\ntemplate <>\nvoid caffe_gpu_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}\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 <>\nvoid caffe_gpu_axpy<float>(const int N, const float alpha, const float* X,\n    float* Y) {\n    AMDBLAS_CHECK( clblasSaxpy(N, alpha, (cl_mem)X, 0, 1, (cl_mem)Y, 0, 1, 1, &(amdDevice.CommandQueue),0, NULL, NULL) );\n}\n\ntemplate <>\nvoid caffe_gpu_axpy<double>(const int N, const double alpha, const double* X,\n    double* Y) {\n    AMDBLAS_CHECK( clblasDaxpy(N, alpha, (cl_mem)X, 0, 1, (cl_mem)Y, 0, 1, 1, &(amdDevice.CommandQueue),0, NULL, NULL) );\n}\n\ntemplate <>\nvoid caffe_set(const int N, const float alpha, float* Y) {\n  if (alpha == 0) {\n    memset(Y, 0, sizeof(float) * N);\n    return;\n  }\n  for (int i = 0; i < N; ++i) {\n    Y[i] = alpha;\n  }\n}\n\ntemplate <>\nvoid caffe_set(const int N, const double alpha, double* Y) {\n  if (alpha == 0) {\n    memset(Y, 0, sizeof(double) * N);\n    return;\n  }\n  for (int i = 0; i < N; ++i) {\n    Y[i] = alpha;\n  }\n}\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 <>\nvoid caffe_copy<float>(const int N, const float* X, float* Y) {\n  cblas_scopy(N, X, 1, Y, 1);\n}\n\ntemplate <>\nvoid caffe_copy<double>(const int N, const double* X, double* Y) {\n  cblas_dcopy(N, X, 1, Y, 1);\n}\n\ntemplate <>\nvoid caffe_gpu_copy<float>(const int N, const float* X, float* Y) {\n  AMDBLAS_CHECK( clblasScopy( N, (cl_mem)X, 0,1, (cl_mem)Y, 0, 1, 1, &(amdDevice.CommandQueue), 0, NULL, NULL) );\n\n}\n\ntemplate <>\nvoid caffe_gpu_copy<double>(const int N, const double* X, double* Y) {\n  AMDBLAS_CHECK( clblasDcopy( N, (cl_mem)X, 0,1, (cl_mem)Y, 0, 1, 1, &(amdDevice.CommandQueue), 0, NULL, NULL) );\n}\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_gpu_scal<float>(const int N, const float alpha, float *X) {\n   AMDBLAS_CHECK(clblasSscal(N, alpha, (cl_mem)X, 0, 1, 1, &(amdDevice.CommandQueue), 0, NULL, NULL));\n}\n\ntemplate <>\nvoid caffe_gpu_scal<double>(const int N, const double alpha, double *X) {\n  AMDBLAS_CHECK(clblasDscal(N, alpha, (cl_mem)X, 0, 1, 1, &(amdDevice.CommandQueue), 0, NULL, NULL));\n}\n\ntemplate <>\nvoid caffe_gpu_axpby<float>(const int N, const float alpha, const float* X,\n    const float beta, float* Y) {\n  caffe_gpu_scal<float>(N, beta, Y);\n  caffe_gpu_axpy<float>(N, alpha, X, Y);\n}\n\ntemplate <>\nvoid caffe_gpu_axpby<double>(const int N, const double alpha, const double* X,\n    const double beta, double* Y) {\n  caffe_gpu_scal<double>(N, beta, Y);\n  caffe_gpu_axpy<double>(N, alpha, X, Y);\n}\n\ntemplate <>\nvoid caffe_cpu_axpby<float>(const int N, const float alpha, const float* X,\n                            const float beta, float* Y) {\n  cblas_saxpby(N, alpha, X, 1, beta, Y, 1);\n}\n\ntemplate <>\nvoid caffe_cpu_axpby<double>(const int N, const double alpha, const double* X,\n                             const double beta, double* Y) {\n  cblas_daxpby(N, alpha, X, 1, beta, Y, 1);\n}\n\ntemplate <>\nvoid caffe_add<float>(const int n, const float* a, const float* b,\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\nunsigned int caffe_rng_rand() {\n  return (*caffe_rng())();\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  //LOG(INFO) << \"caffe_rng_uniform\";\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      //variate_generator(37, random_distribution);\n  for (int i = 0; i < n; ++i) {\n    r[i] = variate_generator();\n  }\n  //LOG(INFO) << \"caffe_rng_guassian\";\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\ntemplate <typename Dtype>\nvoid caffe_rng_bernoulli(const int n, const Dtype p, int* r) {\n  CHECK_GE(n, 0);\n  CHECK(r);\n  CHECK_GE(p, 0);\n  CHECK_LE(p, 1);\n  boost::bernoulli_distribution<Dtype> random_distribution(p);\n  boost::variate_generator<caffe::rng_t*, boost::bernoulli_distribution<Dtype> >\n      variate_generator(caffe_rng(), random_distribution);\n  for (int i = 0; i < n; ++i) {\n    r[i] = variate_generator();\n  }\n  //LOG(INFO) << \"caffe_rng_bernoulli\";\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 <>\nfloat caffe_cpu_dot<float>(const int n, const float* x, const float* y) {\n  return cblas_sdot(n, x, 1, y, 1);\n}\n\ntemplate <>\ndouble caffe_cpu_dot<double>(const int n, const double* x, const double* y) {\n  return cblas_ddot(n, x, 1, y, 1);\n}\n\ntemplate <>\nvoid caffe_gpu_dot<float>(const int n, const float* x, const float* y,\n    float* out) {\n  //need to pass in scratchBuff\n  //AMDBLAS_CHECK(clAmdBlasSdot(n, out, 0, x, 0, 1, y, 0, 1, scratch_buf, 1, &(amdDevice.CommandQueue), 0, NULL, NULL));\n}\n\ntemplate <>\nvoid caffe_gpu_dot<double>(const int n, const double* x, const double* y,\n    double * out) {\n  //need to pass in scratchBuff\n  //AMDBLAS_CHECK(clAmdBlasDdot(n, out, 0, x, 0, 1, y, 0, 1, scratch_buf, 1, &(amdDevice.CommandQueue), 0, NULL, NULL));\n}\n\ntemplate <>\nint caffe_cpu_hamming_distance<float>(const int n, const float* x,\n                                  const float* y) {\n  int dist = 0;\n  for (int i = 0; i < n; ++i) {\n    dist += __builtin_popcount(static_cast<uint32_t>(x[i]) ^\n                               static_cast<uint32_t>(y[i]));\n  }\n  return dist;\n}\n\ntemplate <>\nint caffe_cpu_hamming_distance<double>(const int n, const double* x,\n                                   const double* y) {\n  int dist = 0;\n  for (int i = 0; i < n; ++i) {\n    dist += __builtin_popcountl(static_cast<uint64_t>(x[i]) ^\n                                static_cast<uint64_t>(y[i]));\n  }\n  return dist;\n}\n\ntemplate <>\nfloat caffe_cpu_asum<float>(const int n, const float* x) {\n  return cblas_sasum(n, x, 1);\n}\n\ntemplate <>\ndouble caffe_cpu_asum<double>(const int n, const double* x) {\n  return cblas_dasum(n, x, 1);\n}\n\ntemplate <>\nvoid caffe_gpu_asum<float>(const int n, const float* x, float* y) {\n}\n\ntemplate <>\nvoid caffe_gpu_asum<double>(const int n, const double* x, double* y) {\n}\n\nINSTANTIATE_CAFFE_CPU_UNARY_FUNC(sign);\nINSTANTIATE_CAFFE_CPU_UNARY_FUNC(sgnbit);\nINSTANTIATE_CAFFE_CPU_UNARY_FUNC(fabs);\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\ntemplate <>\nvoid caffe_gpu_scale<float>(const int n, const float alpha, const float *x,\n                            float* y) {\n}\n\ntemplate <>\nvoid caffe_gpu_scale<double>(const int n, const double alpha, const double *x,\n                             double* y) {\n}\n\ntemplate <typename Dtype>\nvoid set_kernel(const int n, const Dtype alpha, Dtype* y) {\n}\n\ntemplate <>\nvoid caffe_gpu_set(const int N, const float alpha, float* Y) {\n  if (alpha == 0) {\n    return;\n  }\n}\n\ntemplate <>\nvoid caffe_gpu_set(const int N, const double alpha, double* Y) {\n  if (alpha == 0) {\n    return;\n  }\n}\n\ntemplate <typename Dtype>\nvoid add_scalar_kernel(const int n, const Dtype alpha, Dtype* y) {\n}\n\ntemplate <>\nvoid caffe_gpu_add_scalar(const int N, const float alpha, float* Y) {\n}\n\ntemplate <>\nvoid caffe_gpu_add_scalar(const int N, const double alpha, double* Y) {\n}\n\ntemplate <typename Dtype>\nvoid mul_kernel(const int n, const Dtype* a,\n    const Dtype* b, Dtype* y) {\n}\n\ntemplate <>\nvoid caffe_gpu_mul<float>(const int N, const float* a,\n    const float* b, float* y) {\n}\n\ntemplate <>\nvoid caffe_gpu_mul<double>(const int N, const double* a,\n    const double* b, double* y) {\n}\n\ntemplate <typename Dtype>\nvoid div_kernel(const int n, const Dtype* a,\n    const Dtype* b, Dtype* y) {\n}\n\ntemplate <>\nvoid caffe_gpu_div<float>(const int N, const float* a,\n    const float* b, float* y) {\n}\n\ntemplate <>\nvoid caffe_gpu_div<double>(const int N, const double* a,\n    const double* b, double* y) {\n}\n\ntemplate <typename Dtype>\nvoid powx_kernel(const int n, const Dtype* a,\n    const Dtype alpha, Dtype* y) {\n}\n\ntemplate <>\nvoid caffe_gpu_powx<float>(const int N, const float* a,\n    const float alpha, float* y) {\n}\n\ntemplate <>\nvoid caffe_gpu_powx<double>(const int N, const double* a,\n    const double alpha, double* y) {\n}\n\n\nvoid popc_kernel(const int n, const float* a,\n    const float* b, uint8_t* y) {\n}\n\nvoid popcll_kernel(const int n, const double* a,\n    const double* b, uint8_t* y) {\n}\n\ntemplate <>\nuint32_t caffe_gpu_hamming_distance<float>(const int n, const float* x,\n                                  const float* y) {\n}\n\ntemplate <>\nuint32_t caffe_gpu_hamming_distance<double>(const int n, const double* x,\n                                   const double* y) {\n}\n\nvoid caffe_gpu_rng_uniform(const int n, unsigned int* r) {\n}\n\ntemplate <>\nvoid caffe_gpu_rng_uniform<float>(const int n, const float a, const float b,\n                                  float* r) {\n}\ntemplate <>\nvoid caffe_gpu_rng_uniform<double>(const int n, const double a, const double b,\n                                   double* r) {\n}\n\ntemplate <>\nvoid caffe_gpu_rng_gaussian(const int n, const float mu, const float sigma,\n                            float* r) {\n}\n\ntemplate <>\nvoid caffe_gpu_rng_gaussian(const int n, const double mu, const double sigma,\n                            double* r) {\n}\n}  // namespace caffe\n", "meta": {"hexsha": "b6c812295183b9edf23d23ff486793f7423b895f", "size": 21475, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/caffe/util/math_functions.cpp", "max_stars_repo_name": "gujunli/OpenCL-CAFFE-Research", "max_stars_repo_head_hexsha": "e8848f727733e503671e0e6a68aa885973b31197", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/caffe/util/math_functions.cpp", "max_issues_repo_name": "gujunli/OpenCL-CAFFE-Research", "max_issues_repo_head_hexsha": "e8848f727733e503671e0e6a68aa885973b31197", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/caffe/util/math_functions.cpp", "max_forks_repo_name": "gujunli/OpenCL-CAFFE-Research", "max_forks_repo_head_hexsha": "e8848f727733e503671e0e6a68aa885973b31197", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.052238806, "max_line_length": 219, "alphanum_fraction": 0.6551338766, "num_tokens": 6646, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7090191214879992, "lm_q2_score": 0.4649015713733885, "lm_q1q2_score": 0.3296241037135503}}
{"text": "/*\nBrian Staber (brian.staber@gmail.com)\n*/\n\n#include \"Epetra_ConfigDefs.h\"\n#ifdef HAVE_MPI\n#include \"mpi.h\"\n#include \"Epetra_MpiComm.h\"\n#else\n#include \"Epetra_SerialComm.h\"\n#endif\n\n#include \"Teuchos_CommandLineProcessor.hpp\"\n#include \"Teuchos_StandardCatchMacros.hpp\"\n#include \"Teuchos_ParameterList.hpp\"\n#include \"Teuchos_XMLParameterListCoreHelpers.hpp\"\n\n#include \"neumannInnerSurface_StochasticPolyconvexHGO.hpp\"\n#include <boost/math/special_functions/gamma.hpp>\n\n#include \"shinozukapp.hpp\"\n\nint main(int argc, char *argv[]){\n\n    std::string    xmlInFileName = \"\";\n    std::string    extraXmlFile = \"\";\n    std::string    xmlOutFileName = \"paramList.out\";\n\n    Teuchos::CommandLineProcessor  clp(false);\n    clp.setOption(\"xml-in-file\",&xmlInFileName,\"The XML file to read into a parameter list\");\n    clp.setDocString(\"TO DO.\");\n\n    Teuchos::CommandLineProcessor::EParseCommandLineReturn\n    parse_return = clp.parse(argc,argv);\n    if( parse_return != Teuchos::CommandLineProcessor::PARSE_SUCCESSFUL ) {\n        std::cout << \"\\nEnd Result: TEST FAILED\" << std::endl;\n        return parse_return;\n    }\n\n#ifdef HAVE_MPI\n    MPI_Init(&argc, &argv);\n    Epetra_MpiComm Comm(MPI_COMM_WORLD);\n#else\n    Epetra_SerialComm Comm;\n#endif\n\n    Teuchos::RCP<Teuchos::ParameterList> paramList = Teuchos::rcp(new Teuchos::ParameterList);\n    if(xmlInFileName.length()) {\n        Teuchos::updateParametersFromXmlFile(xmlInFileName, inoutArg(*paramList));\n    }\n\n    if (Comm.MyPID()==0){\n        paramList->print(std::cout,2,true,true);\n    }\n\n    Teuchos::RCP<neumannInnerSurface_StochasticPolyconvexHGO> interface\n    = Teuchos::rcp(new neumannInnerSurface_StochasticPolyconvexHGO(Comm,*paramList));\n\n    std::ifstream parameters_file_1, parameters_file_2, parameters_file_3, parameters_file_4;\n\n    std::string path1 = \"/Users/Brian/Documents/Thesis/Trilinos_results/arteries/gmrf_neumann/a100_gamma3_delta010/\";\n    parameters_file_1.open(path1+\"w1.txt\");\n    parameters_file_2.open(path1+\"w2.txt\");\n    parameters_file_3.open(path1+\"w3.txt\");\n    parameters_file_4.open(path1+\"w4.txt\");\n\n    unsigned int n_cells_p1_med = 297828;\n    unsigned int n_nodes_p1_med = 58464;\n\n    std::string path = \"/Users/Brian/Documents/Thesis/Trilinos/arteries/mesh/connectivity_p1_media.txt\";\n    interface->get_media(n_cells_p1_med,n_nodes_p1_med,path);\n\n    if (parameters_file_1.is_open() && parameters_file_2.is_open() && parameters_file_3.is_open() && parameters_file_4.is_open()){\n\n        for (unsigned nmc=0; nmc<1; ++nmc){\n            for (int i=0; i<n_nodes_p1_med; ++i){\n                parameters_file_1 >> interface->w1_gmrf(i);\n                parameters_file_2 >> interface->w2_gmrf(i);\n                parameters_file_3 >> interface->w3_gmrf(i);\n                parameters_file_4 >> interface->w4_gmrf(i);\n            }\n        }\n        Comm.Barrier();\n        parameters_file_1.close();\n        parameters_file_2.close();\n        parameters_file_3.close();\n        parameters_file_4.close();\n    }\n    else{\n        std::cout << \"Couldn't open one of the parameters_file.\\n\";\n    }\n\n    int e_gid;\n    int n_local_cells = interface->Mesh->n_local_cells;\n    int n_gauss_cells = interface->Mesh->n_gauss_cells;\n    std::vector<int> local_gauss_points(n_local_cells*n_gauss_cells);\n    for (unsigned int e_lid=0; e_lid<n_local_cells; ++e_lid){\n        e_gid = interface->Mesh->local_cells[e_lid];\n        for (unsigned int gp=0; gp<n_gauss_cells; ++gp){\n            local_gauss_points[e_lid*n_gauss_cells+gp] = e_gid*n_gauss_cells+gp;\n        }\n\n    }\n    Epetra_Map GaussMap(-1,n_local_cells*n_gauss_cells,&local_gauss_points[0],0,Comm);\n\n    Epetra_Vector mu1_gmrf(GaussMap);\n    Epetra_Vector mu2_gmrf(GaussMap);\n    Epetra_Vector mu3_gmrf(GaussMap);\n    Epetra_Vector mu4_gmrf(GaussMap);\n    Epetra_Vector x_coord(GaussMap);\n    Epetra_Vector y_coord(GaussMap);\n    Epetra_Vector z_coord(GaussMap);\n\n    int node;\n    double xi, eta, zeta;\n    Epetra_SerialDenseMatrix matrix_X(3,interface->Mesh->el_type);\n    Epetra_SerialDenseVector vector_X(3);\n    Epetra_SerialDenseVector N(interface->Mesh->el_type);\n    for (unsigned int e_lid=0; e_lid<n_local_cells; ++e_lid){\n        e_gid = interface->Mesh->local_cells[e_lid];\n        for (int inode=0; inode<interface->Mesh->el_type; ++inode){\n            node = interface->Mesh->cells_nodes[interface->Mesh->el_type*e_gid+inode];\n            matrix_X(0,inode) = interface->Mesh->nodes_coord[3*node+0];\n            matrix_X(1,inode) = interface->Mesh->nodes_coord[3*node+1];\n            matrix_X(2,inode) = interface->Mesh->nodes_coord[3*node+2];\n        }\n        for (unsigned int gp=0; gp<n_gauss_cells; ++gp){\n            xi   = interface->Mesh->xi_cells[gp];\n            eta  = interface->Mesh->eta_cells[gp];\n            zeta = interface->Mesh->zeta_cells[gp];\n            tetra10::shape_functions(N,xi,eta,zeta);\n            vector_X.Multiply('N','N',1.0,matrix_X,N,0.0);\n            interface->get_material_parameters(e_lid,gp);\n            mu1_gmrf[GaussMap.LID(int(e_gid*n_gauss_cells+gp))] = interface->mu1;\n            mu2_gmrf[GaussMap.LID(int(e_gid*n_gauss_cells+gp))] = interface->mu2;\n            mu3_gmrf[GaussMap.LID(int(e_gid*n_gauss_cells+gp))] = interface->mu3;\n            mu4_gmrf[GaussMap.LID(int(e_gid*n_gauss_cells+gp))] = interface->mu4;\n            x_coord[GaussMap.LID(int(e_gid*n_gauss_cells+gp))] = vector_X(0);\n            y_coord[GaussMap.LID(int(e_gid*n_gauss_cells+gp))] = vector_X(1);\n            z_coord[GaussMap.LID(int(e_gid*n_gauss_cells+gp))] = vector_X(2);\n         }\n    }\n\n    int error;\n    int NumTargetElements = 0;\n    if (Comm.MyPID()==0){\n        NumTargetElements = interface->Mesh->n_cells*n_gauss_cells;\n    }\n    Epetra_Map MapOnRoot(-1,NumTargetElements,0,Comm);\n    Epetra_Export ExportOnRoot(GaussMap,MapOnRoot);\n    Epetra_MultiVector lhs_root(MapOnRoot,true);\n    lhs_root.Export(mu1_gmrf,ExportOnRoot,Insert);\n    std::string filename = \"/Users/Brian/Documents/Thesis/Trilinos_results/arteries/boost_gmrf/gmrf_gauss/mu1_gmrf.mtx\";\n    error = EpetraExt::MultiVectorToMatrixMarketFile(filename.c_str(),lhs_root,0,0,false);\n\n    lhs_root.PutScalar(0.0);\n    lhs_root.Export(mu2_gmrf,ExportOnRoot,Insert);\n    filename = \"/Users/Brian/Documents/Thesis/Trilinos_results/arteries/boost_gmrf/gmrf_gauss/mu2_gmrf.mtx\";\n    error = EpetraExt::MultiVectorToMatrixMarketFile(filename.c_str(),lhs_root,0,0,false);\n\n    lhs_root.PutScalar(0.0);\n    lhs_root.Export(mu3_gmrf,ExportOnRoot,Insert);\n    filename = \"/Users/Brian/Documents/Thesis/Trilinos_results/arteries/boost_gmrf/gmrf_gauss/mu3_gmrf.mtx\";\n    error = EpetraExt::MultiVectorToMatrixMarketFile(filename.c_str(),lhs_root,0,0,false);\n\n    lhs_root.PutScalar(0.0);\n    lhs_root.Export(mu4_gmrf,ExportOnRoot,Insert);\n    filename = \"/Users/Brian/Documents/Thesis/Trilinos_results/arteries/boost_gmrf/gmrf_gauss/mu4_gmrf.mtx\";\n    error = EpetraExt::MultiVectorToMatrixMarketFile(filename.c_str(),lhs_root,0,0,false);\n\n    lhs_root.PutScalar(0.0);\n    lhs_root.Export(x_coord,ExportOnRoot,Insert);\n    filename = \"/Users/Brian/Documents/Thesis/Trilinos_results/arteries/boost_gmrf/gmrf_gauss/x_coord.mtx\";\n    error = EpetraExt::MultiVectorToMatrixMarketFile(filename.c_str(),lhs_root,0,0,false);\n\n    lhs_root.PutScalar(0.0);\n    lhs_root.Export(y_coord,ExportOnRoot,Insert);\n    filename = \"/Users/Brian/Documents/Thesis/Trilinos_results/arteries/boost_gmrf/gmrf_gauss/y_coord.mtx\";\n    error = EpetraExt::MultiVectorToMatrixMarketFile(filename.c_str(),lhs_root,0,0,false);\n\n    lhs_root.PutScalar(0.0);\n    lhs_root.Export(z_coord,ExportOnRoot,Insert);\n    filename = \"/Users/Brian/Documents/Thesis/Trilinos_results/arteries/boost_gmrf/gmrf_gauss/z_coord.mtx\";\n    error = EpetraExt::MultiVectorToMatrixMarketFile(filename.c_str(),lhs_root,0,0,false);\n\n#ifdef HAVE_MPI\n    MPI_Finalize();\n#endif\n    return 0;\n\n}\n", "meta": {"hexsha": "e2972a2409449d3a70a528a690d00a028dd3c2d4", "size": 7872, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "arteries/boost_gmrf/gmrf_gauss/main.cpp", "max_stars_repo_name": "bstaber/Trilinos", "max_stars_repo_head_hexsha": "12ada5a678338a1da962113a4fad708f93b19e03", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "arteries/boost_gmrf/gmrf_gauss/main.cpp", "max_issues_repo_name": "bstaber/Trilinos", "max_issues_repo_head_hexsha": "12ada5a678338a1da962113a4fad708f93b19e03", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "arteries/boost_gmrf/gmrf_gauss/main.cpp", "max_forks_repo_name": "bstaber/Trilinos", "max_forks_repo_head_hexsha": "12ada5a678338a1da962113a4fad708f93b19e03", "max_forks_repo_licenses": ["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.0, "max_line_length": 130, "alphanum_fraction": 0.7036331301, "num_tokens": 2280, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7090191214879991, "lm_q2_score": 0.46490157137338844, "lm_q1q2_score": 0.32962410371355017}}
{"text": "#include <ctime>\n#include <cmath>\n\n#include <iostream>\n#include <fstream>\n#include <vector>\n#include <algorithm>\n\n#include <boost/unordered_map.hpp> \n#include <boost/functional.hpp>\n#include <boost/lexical_cast.hpp>\n#include <boost/random/mersenne_twister.hpp>\n#include <boost/algorithm/string/join.hpp>\n# include <boost/interprocess/managed_shared_memory.hpp>\n# include <boost/interprocess/allocators/allocator.hpp>\n# include <boost/interprocess/managed_mapped_file.hpp>\n#include <boost/interprocess/containers/vector.hpp>\n#include <boost/math/distributions/binomial.hpp>\n\n#include <Eigen/Dense>\n#include <Eigen/Sparse>\n#include \"maybe_omp.h\"\n#include <tclap/CmdLine.h>\n\n#include \"model.h\"\n#include \"propagator.h\"\n#include \"param.h\"\n#include \"neuralClasses.h\"\n#include \"graphClasses.h\"\n#include \"util.h\"\n#include \"multinomial.h\"\n//#include \"gradientCheck.h\"\n\n//#define EIGEN_DONT_PARALLELIZE\n\nusing namespace std;\nusing namespace TCLAP;\nusing namespace Eigen;\nusing namespace boost;\nusing namespace boost::random;\n\nusing namespace nplm;\n\nnamespace ip = boost::interprocess;\ntypedef unordered_map<Matrix<int,Dynamic,1>, double> vector_map;\n\ntypedef ip::allocator<int, ip::managed_mapped_file::segment_manager> intAllocator;\ntypedef ip::vector<int, intAllocator> vec;\ntypedef ip::allocator<vec, ip::managed_mapped_file::segment_manager> vecAllocator;\n\n\ntypedef long long int data_size_t; // training data can easily exceed 2G instances\n\nint main(int argc, char** argv)\n{ \n    ios::sync_with_stdio(false);\n    bool use_mmap_file, randomize;\n    param myParam;\n    try {\n      // program options //\n      CmdLine cmd(\"Trains a two-layer neural probabilistic language model.\", ' ' , \"0.2\\n\",\n          \"Changes since V0.1: Addition of biases\");\n\n      // The options are printed in reverse order\n\n      ValueArg<string> unigram_probs_file(\"\", \"unigram_probs_file\", \"Unigram model (deprecated and ignored).\" , false, \"\", \"string\", cmd);\n\n      ValueArg<int> num_threads(\"\", \"num_threads\", \"Number of threads. Default: maximum.\", false, 0, \"int\", cmd);\n\n      ValueArg<double> final_momentum(\"\", \"final_momentum\", \"Final value of momentum. Default: 0.9.\", false, 0.9, \"double\", cmd);\n      ValueArg<double> initial_momentum(\"\", \"initial_momentum\", \"Initial value of momentum. Default: 0.9.\", false, 0.9, \"double\", cmd);\n      ValueArg<bool> use_momentum(\"\", \"use_momentum\", \"Use momentum (hidden layer weights only). 1 = yes, 0 = no. Default: 0.\", false, 0, \"bool\", cmd);\n\n      ValueArg<double> normalization_init(\"\", \"normalization_init\", \"Initial normalization parameter. Default: 0.\", false, 0.0, \"double\", cmd);\n      ValueArg<bool> normalization(\"\", \"normalization\", \"Learn individual normalization factors during training. 1 = yes, 0 = no. Default: 0.\", false, 0, \"bool\", cmd);\n\n      ValueArg<bool> mmap_file(\"\", \"mmap_file\", \"Use memory mapped files. This is useful if the entire data cannot fit in memory. prepareNeuralLM can generate memory mapped files\", false, 0, \"bool\", cmd);\n\n      ValueArg<bool> arg_randomize(\"\", \"randomize\", \"Randomize training instances for better training. 1 = yes, 0 = no. Default: 1.\", false, true, \"bool\", cmd);\n\n      ValueArg<int> num_noise_samples(\"\", \"num_noise_samples\", \"Number of noise samples for noise-contrastive estimation. Default: 100.\", false, 100, \"int\", cmd);\n\n      ValueArg<double> L2_reg(\"\", \"L2_reg\", \"L2 regularization strength (hidden layer weights only). Default: 0.\", false, 0.0, \"double\", cmd);\n\n      ValueArg<double> learning_rate(\"\", \"learning_rate\", \"Learning rate for stochastic gradient ascent. Default: 1.\", false, 1., \"double\", cmd);\n\n      ValueArg<double> conditioning_constant(\"\", \"conditioning_constant\", \"Constant to condition the RMS of the expected square of the gradient in ADADELTA. Default: 10E-3.\", false, 10E-3, \"double\", cmd);\n\n      ValueArg<double> decay(\"\", \"decay\", \"Decay for ADADELTA. Default: 0.95\", false, 0.95, \"double\", cmd);\n      ValueArg<double> adagrad_epsilon(\"\", \"adagrad_epsilon\", \"Constant to initialize the L2 squared norm of the gradients with.\\\n          Default: 10E-3\", false, 10E-3, \"double\", cmd);\n      ValueArg<int> validation_minibatch_size(\"\", \"validation_minibatch_size\", \"Minibatch size for validation. Default: 64.\", false, 64, \"int\", cmd);\n      ValueArg<int> minibatch_size(\"\", \"minibatch_size\", \"Minibatch size (for training). Default: 1000.\", false, 1000, \"int\", cmd);\n\n      ValueArg<int> num_epochs(\"\", \"num_epochs\", \"Number of epochs. Default: 10.\", false, 10, \"int\", cmd);\n\n      ValueArg<double> init_range(\"\", \"init_range\", \"Maximum (of uniform) or standard deviation (of normal) for initialization. Default: 0.01\", false, 0.01, \"double\", cmd);\n      ValueArg<bool> init_normal(\"\", \"init_normal\", \"Initialize parameters from a normal distribution. 1 = normal, 0 = uniform. Default: 0.\", false, 0, \"bool\", cmd);\n\n      ValueArg<string> loss_function(\"\", \"loss_function\", \"Loss function (log, nce). Default: nce.\", false, \"nce\", \"string\", cmd);\n      ValueArg<string> activation_function(\"\", \"activation_function\", \"Activation function (identity, rectifier, tanh, hardtanh). Default: rectifier.\", false, \"rectifier\", \"string\", cmd);\n      ValueArg<int> num_hidden(\"\", \"num_hidden\", \"Number of hidden nodes. Default: 100.\", false, 100, \"int\", cmd);\n\t  ValueArg<int> num_second_hidden(\"\", \"num_second_hidden\", \"Number of hidden nodes in the second hidden layer. Default: 100.\", false, 100, \"int\", cmd);\n\n      ValueArg<bool> share_embeddings(\"\", \"share_embeddings\", \"Share input and output embeddings. 1 = yes, 0 = no. Default: 0.\", false, 0, \"bool\", cmd);\n      ValueArg<int> output_embedding_dimension(\"\", \"output_embedding_dimension\", \"Number of output embedding dimensions. Default: 50.\", false, 50, \"int\", cmd);\n      ValueArg<int> input_embedding_dimension(\"\", \"input_embedding_dimension\", \"Number of input embedding dimensions. Default: 50.\", false, 50, \"int\", cmd);\n      ValueArg<int> embedding_dimension(\"\", \"embedding_dimension\", \"Number of input and output embedding dimensions. Default: none.\", false, -1, \"int\", cmd);\n\t  ValueArg<string> input_embeddings_file(\"\",\"input_embeddings_file\", \"Read the input embeddings from the specified file. Default: none\", false,\"\",\"string\",cmd);\n\t  ValueArg<int> context_vector_size(\"\", \"context_vector_size\", \"Size of the context vector. Default: 128.\", false, 128, \"int\", cmd);\n      ValueArg<int> vocab_size(\"\", \"vocab_size\", \"Vocabulary size. Default: auto.\", false, 0, \"int\", cmd);\n      ValueArg<int> input_vocab_size(\"\", \"input_vocab_size\", \"Vocabulary size. Default: auto.\", false, 0, \"int\", cmd);\n      ValueArg<int> output_vocab_size(\"\", \"output_vocab_size\", \"Vocabulary size. Default: auto.\", false, 0, \"int\", cmd);\n      ValueArg<int> ngram_size(\"\", \"ngram_size\", \"Size of n-grams. Default: auto.\", false, 0, \"int\", cmd);\n\n      ValueArg<string> model_prefix(\"\", \"model_prefix\", \"Prefix for output model files.\" , false, \"\", \"string\", cmd);\n      ValueArg<string> words_file(\"\", \"words_file\", \"Vocabulary.\" , false, \"\", \"string\", cmd);\n      ValueArg<string> parameter_update(\"\", \"parameter_update\", \"parameter update type.\\n Stochastic Gradient Descent(SGD)\\n \\\n          ADAGRAD(ADA)\\n \\\n          ADADELTA(ADAD)\" , false, \"SGD\", \"string\", cmd);\n      ValueArg<string> input_words_file(\"\", \"input_words_file\", \"Vocabulary.\" , false, \"\", \"string\", cmd);\n      ValueArg<string> output_words_file(\"\", \"output_words_file\", \"Vocabulary.\" , false, \"\", \"string\", cmd);\n      ValueArg<string> validation_file(\"\", \"validation_file\", \"Validation data (one numberized example per line).\" , false, \"\", \"string\", cmd);\n      ValueArg<string> train_file(\"\", \"train_file\", \"Training data (one numberized example per line).\" , true, \"\", \"string\", cmd);\n\n      ValueArg<string> model_file(\"\", \"model_file\", \"Model file.\", false, \"\", \"string\", cmd);\n      ValueArg<double> hidden1_dropout_value(\"\", \"hidden1_dropout_value\", \"The probability of drop out for hidden layer 1.\\\n          Default: 0.9\", false, 0.9, \"double\", cmd);\n      ValueArg<double> hidden2_dropout_value(\"\", \"hidden2_dropout_value\", \"The probability of drop out for hidden layer 2.\\\n          Default: 0.9\", false, 0.9, \"double\", cmd);\n      ValueArg<double> hidden3_dropout_value(\"\", \"hidden3_dropout_value\", \"The probability of drop out for hidden layer 3.\\\n          Default: 0.9\", false, 0.9, \"double\", cmd);\n\t  ValueArg<string> train_context_vectors_file(\"\", \"train_context_vectors_file\", \"Training context vectors file.\" \n\t\t  , false, \"\", \"string\", cmd);\n\t  ValueArg<string> validation_context_vectors_file(\"\", \"validation_context_vectors_file\", \"Validation context vectors file.\" \n\t\t  , false, \"\", \"string\", cmd);\n\n\n      cmd.parse(argc, argv);\n\n      // define program parameters //\n      use_mmap_file = mmap_file.getValue();\n      randomize = arg_randomize.getValue();\n      myParam.model_file = model_file.getValue();\n      myParam.train_file = train_file.getValue();\n      myParam.validation_file = validation_file.getValue();\n      myParam.input_words_file = input_words_file.getValue();\n      myParam.output_words_file = output_words_file.getValue();\n      if (words_file.getValue() != \"\")\n\t      myParam.input_words_file = myParam.output_words_file = words_file.getValue();\n\n      myParam.model_prefix = model_prefix.getValue();\n\n      myParam.ngram_size = ngram_size.getValue();\n      myParam.vocab_size = vocab_size.getValue();\n      myParam.input_vocab_size = input_vocab_size.getValue();\n      myParam.output_vocab_size = output_vocab_size.getValue();\n      if (vocab_size.getValue() >= 0) {\n\t      myParam.input_vocab_size = myParam.output_vocab_size = vocab_size.getValue();\n      }\n      myParam.num_hidden = num_hidden.getValue();\n\t  myParam.num_second_hidden = num_second_hidden.getValue();\n      myParam.activation_function = activation_function.getValue();\n      myParam.loss_function = loss_function.getValue();\n\n      myParam.num_threads = num_threads.getValue();\n\n      myParam.num_noise_samples = num_noise_samples.getValue();\n\n      myParam.input_embedding_dimension = input_embedding_dimension.getValue();\n      myParam.output_embedding_dimension = output_embedding_dimension.getValue();\n      if (embedding_dimension.getValue() >= 0) {\n\t      myParam.input_embedding_dimension = myParam.output_embedding_dimension = embedding_dimension.getValue();\n      }\n\t  myParam.input_embeddings_file = input_embeddings_file.getValue();\n\t  \n\t  myParam.context_vector_size = context_vector_size.getValue();\n\t  \n      myParam.minibatch_size = minibatch_size.getValue();\n      myParam.validation_minibatch_size = validation_minibatch_size.getValue();\n      myParam.num_epochs= num_epochs.getValue();\n      myParam.learning_rate = learning_rate.getValue();\n      myParam.conditioning_constant = conditioning_constant.getValue();\n      myParam.decay = decay.getValue();\n      myParam.adagrad_epsilon = adagrad_epsilon.getValue();\n      myParam.use_momentum = use_momentum.getValue();\n      myParam.share_embeddings = share_embeddings.getValue();\n      myParam.normalization = normalization.getValue();\n      myParam.initial_momentum = initial_momentum.getValue();\n      myParam.final_momentum = final_momentum.getValue();\n      myParam.L2_reg = L2_reg.getValue();\n      myParam.init_normal= init_normal.getValue();\n      myParam.init_range = init_range.getValue();\n      myParam.normalization_init = normalization_init.getValue();\n      myParam.parameter_update = parameter_update.getValue();\n\t  myParam.hidden1_dropout_value = hidden1_dropout_value.getValue();\n\t  myParam.hidden2_dropout_value = hidden2_dropout_value.getValue();\n\t  myParam.hidden3_dropout_value = hidden3_dropout_value.getValue();\n\t  \n\t  myParam.train_context_vectors_file = train_context_vectors_file.getValue();\n\t  myParam.validation_context_vectors_file = validation_context_vectors_file.getValue();\n\n      cerr << \"Command line: \" << endl;\n      cerr << boost::algorithm::join(vector<string>(argv, argv+argc), \" \") << endl;\n\n      const string sep(\" Value: \");\n      cerr << train_file.getDescription() << sep << train_file.getValue() << endl;\n      cerr << validation_file.getDescription() << sep << validation_file.getValue() << endl;\n      cerr << input_words_file.getDescription() << sep << input_words_file.getValue() << endl;\n      cerr << output_words_file.getDescription() << sep << output_words_file.getValue() << endl;\n      cerr << model_prefix.getDescription() << sep << model_prefix.getValue() << endl;\n\n      cerr << ngram_size.getDescription() << sep << ngram_size.getValue() << endl;\n      cerr << input_vocab_size.getDescription() << sep << input_vocab_size.getValue() << endl;\n      cerr << output_vocab_size.getDescription() << sep << output_vocab_size.getValue() << endl;\n      cerr << mmap_file.getDescription() << sep << mmap_file.getValue() << endl;\n\n      if (embedding_dimension.getValue() >= 0)\n      {\n\t      cerr << embedding_dimension.getDescription() << sep << embedding_dimension.getValue() << endl;\n      }\n      else\n      {\n\t      cerr << input_embedding_dimension.getDescription() << sep << input_embedding_dimension.getValue() << endl;\n\t      cerr << output_embedding_dimension.getDescription() << sep << output_embedding_dimension.getValue() << endl;\n      }\n      cerr << share_embeddings.getDescription() << sep << share_embeddings.getValue() << endl;\n      if (share_embeddings.getValue() && input_embedding_dimension.getValue() != output_embedding_dimension.getValue())\n      {\n\t      cerr << \"error: sharing input and output embeddings requires that input and output embeddings have same dimension\" << endl;\n\t      exit(1);\n      }\n\n      cerr << num_hidden.getDescription() << sep << num_hidden.getValue() << endl;\n\n      if (string_to_activation_function(activation_function.getValue()) == InvalidFunction)\n      {\n\t      cerr << \"error: invalid activation function: \" << activation_function.getValue() << endl;\n\t      exit(1);\n      }\n      cerr << activation_function.getDescription() << sep << activation_function.getValue() << endl;\n\n      if (string_to_loss_function(loss_function.getValue()) == InvalidLoss)\n      {\n\t      cerr << \"error: invalid loss function: \" << loss_function.getValue() << endl;\n\t      exit(1);\n      }\n      cerr << loss_function.getDescription() << sep << loss_function.getValue() << endl;\n\n      cerr << init_normal.getDescription() << sep << init_normal.getValue() << endl;\n      cerr << init_range.getDescription() << sep << init_range.getValue() << endl;\n\n      cerr << num_epochs.getDescription() << sep << num_epochs.getValue() << endl;\n      cerr << minibatch_size.getDescription() << sep << minibatch_size.getValue() << endl;\n      if (myParam.validation_file != \"\") {\n\t     cerr << validation_minibatch_size.getDescription() << sep << validation_minibatch_size.getValue() << endl;\n      }\n      cerr << learning_rate.getDescription() << sep << learning_rate.getValue() << endl;\n      cerr << L2_reg.getDescription() << sep << L2_reg.getValue() << endl;\n\n      cerr << num_noise_samples.getDescription() << sep << num_noise_samples.getValue() << endl;\n\n      cerr << normalization.getDescription() << sep << normalization.getValue() << endl;\n      if (myParam.normalization){\n\t      cerr << normalization_init.getDescription() << sep << normalization_init.getValue() << endl;\n      }\n\n      cerr << use_momentum.getDescription() << sep << use_momentum.getValue() << endl;\n      if (myParam.use_momentum)\n      {\n        cerr << initial_momentum.getDescription() << sep << initial_momentum.getValue() << endl;\n        cerr << final_momentum.getDescription() << sep << final_momentum.getValue() << endl;\n      }\n\n      cerr << num_threads.getDescription() << sep << num_threads.getValue() << endl;\n\n      if (unigram_probs_file.getValue() != \"\")\n      {\n\t      cerr << \"Note: --unigram_probs_file is deprecated and ignored.\" << endl;\n      }\n    }\n    catch (TCLAP::ArgException &e)\n    {\n      cerr << \"error: \" << e.error() <<  \" for arg \" << e.argId() << endl;\n      exit(1);\n    }\n\n    myParam.num_threads = setup_threads(myParam.num_threads);\n    int save_threads;\n\n    //unsigned seed = std::time(0);\n\t//cerr<<\"Seed is \"<<seed<<endl;\n    unsigned seed = 1234; //for testing only\n    mt19937 rng(seed);\n\n    /////////////////////////READING IN THE TRAINING AND VALIDATION DATA///////////////////\n    /////////////////////////////////////////////////////////////////////////////////////\n\n    // Read training data\n\n    vector<int> training_data_flat;\n    vec * training_data_flat_mmap;\n    data_size_t training_data_size; //num_tokens;\n    ip::managed_mapped_file mmap_file;\n    if (use_mmap_file == false) {\n      cerr<<\"Reading data from regular text file \"<<endl;\n      readDataFile(myParam.train_file, myParam.ngram_size, training_data_flat, myParam.minibatch_size);\n      training_data_size = training_data_flat.size()/myParam.ngram_size;\n    } else {\n      cerr<<\"Using mmaped file\"<<endl;\n      mmap_file = ip::managed_mapped_file(ip::open_only,myParam.train_file.c_str());\n      training_data_flat_mmap = mmap_file.find<vec>(\"vector\").first;\n      cerr<<\"Size of mmaped vector is \"<<training_data_flat_mmap->size()<<endl;\n      training_data_size = training_data_flat_mmap->size()/myParam.ngram_size;\n      //randomly shuffle the data for better learning. The shuffling will \n      //be different for a standard stl vector\n      // Randomly shuffle training data to improve learning\n      if (randomize == true) {\n        cerr<<\"Randomly shuffling data...\";\n        data_size_t counter =0;\n        while (counter < training_data_size) {\n          data_size_t upper_limit = counter+5000000;\n          long int vector_size = 5000000;\n          if (counter + 10000000 >= training_data_size) {\n            upper_limit = training_data_size;\n            vector_size = training_data_size - counter;\n          }\n          vector<int> temp(vector_size*myParam.ngram_size,0);\n          for (int i=0;i<vector_size;i++){\n           for (int k=0;k<myParam.ngram_size;k++) {\n             temp[i*myParam.ngram_size+k] = training_data_flat_mmap->at((i+counter)*myParam.ngram_size+k);\n           }\n          }\n          /*\n          for (data_size_t i=upper_limit; i>counter; i--)\n          {\n            if (i %500000 == 0) {\n              cerr<<\"Shuffled \"<<training_data_size-1<<\" instances...\";\n            }\n            data_size_t j = uniform_int_distribution<data_size_t>(0, i-1)(rng);\n            for (int k=0;k<myParam.ngram_size;k++) {\n              int temp_val = training_data_flat_mmap->at(i*myParam.ngram_size+k);\n              training_data_flat_mmap->at(i*myParam.ngram_size+k) =\n                training_data_flat_mmap->at(j*myParam.ngram_size+k);\n              training_data_flat_mmap->at(j*myParam.ngram_size+k) = temp_val;\n            }\n          }\n          */\n          for (data_size_t i=vector_size-1; i>0; i--)\n          {\n            if (i %500000 == 0) {\n              cerr<<\"Shuffled \"<<training_data_size-1<<\" instances...\";\n            }\n            data_size_t j = uniform_int_distribution<data_size_t>(0, i-1)(rng);\n            for (int k=0;k<myParam.ngram_size;k++) {\n              int temp_val = temp.at(i*myParam.ngram_size+k);\n              temp.at(i*myParam.ngram_size+k) =\n                temp.at(j*myParam.ngram_size+k);\n              temp.at(j*myParam.ngram_size+k) = temp_val;\n            }\n          }\n          //Putting it back\n          for (int i=0;i<vector_size;i++){\n           for (int k=0;k<myParam.ngram_size;k++) {\n             training_data_flat_mmap->at((i+counter)*myParam.ngram_size+k) = temp[i*myParam.ngram_size+k];\n           }\n          }\n          counter = upper_limit;\n        }\n        /*\n        for (data_size_t i=training_data_size-1; i>0; i--)\n        {\n          if (i %500000 == 0) {\n            cerr<<\"Shuffled \"<<training_data_size-1<<\" instances...\";\n          }\n          data_size_t j = uniform_int_distribution<data_size_t>(0, i-1)(rng);\n          for (int k=0;k<myParam.ngram_size;k++) {\n            int temp_val = training_data_flat_mmap->at(i*myParam.ngram_size+k);\n            training_data_flat_mmap->at(i*myParam.ngram_size+k) =\n              training_data_flat_mmap->at(j*myParam.ngram_size+k);\n            training_data_flat_mmap->at(j*myParam.ngram_size+k) = temp_val;\n          }\n        }\n        */\n      cerr<<endl;\n      }\n    }\n    //cerr<<\"Num tokens \"<<num_tokens<<endl;\n    //data_size_t training_data_size = num_tokens / myParam.ngram_size;\n    cerr << \"Number of training instances: \"<< training_data_size << endl;\n    \n    Matrix<int,Dynamic,Dynamic> training_data;\n    //(training_data_flat.data(), myParam.ngram_size, training_data_size);\n    \n    #ifdef MAP\n    cerr<<\"Setting up eigen map\"<<endl;\n    if (use_mmap_file == false) {\n      training_data = Map< Matrix<int,Dynamic,Dynamic> >(training_data_flat.data(), myParam.ngram_size, training_data_size);\n    } else {\n      training_data = Map< Matrix<int,Dynamic,Dynamic> >(training_data_flat_mmap->data().get(), myParam.ngram_size, training_data_size);\n    }\n    cerr<<\"Created eigen map\"<<endl;\n    #else \n    if (use_mmap_file == false) {\n      training_data = Map< Matrix<int,Dynamic,Dynamic> >(training_data_flat.data(), myParam.ngram_size, training_data_size);\n    }\n    #endif \n    // If neither --input_vocab_size nor --input_words_file is given, set input_vocab_size to the maximum word index\n    if (myParam.input_vocab_size == 0 and myParam.input_words_file == \"\")\n    {\n        myParam.input_vocab_size = training_data.topRows(myParam.ngram_size-1).maxCoeff()+1;\n    }\n\n    // If neither --output_vocab_size nor --output_words_file is given, set output_vocab_size to the maximum word index\n    if (myParam.output_vocab_size == 0 and myParam.output_words_file == \"\")\n    {\n        myParam.output_vocab_size = training_data.row(myParam.ngram_size-1).maxCoeff()+1;\n    }\n \n\n    // Read validation data\n    vector<int> validation_data_flat;\n    int validation_data_size = 0;\n    \n    if (myParam.validation_file != \"\")\n    {\n      readDataFile(myParam.validation_file, myParam.ngram_size, validation_data_flat);\n      validation_data_size = validation_data_flat.size() / myParam.ngram_size;\n      cerr << \"Number of validation instances: \" << validation_data_size << endl;\n    }\n\n\t// Read train context vectors\n\tvector<double> training_context_vectors_flat;\n\t//int context_size = 128;\n    if (myParam.train_context_vectors_file != \"\")\n    {\n      readContextVectorsFile(myParam.train_context_vectors_file, myParam.context_vector_size, training_context_vectors_flat);\n      int train_context_vectors_flat_size  = training_context_vectors_flat.size() / myParam.context_vector_size;\n\t  if (train_context_vectors_flat_size != training_data_size){\n\t\t  cerr<<\"The nubmer of training context vectors was not equal to the training data!\"<<endl;\n\t\t  exit(1);\n\t  }\n    }\n\n \n\t// Read validation context vectors\n\tvector<double> validation_context_vectors_flat;\n    if (myParam.validation_context_vectors_file != \"\")\n    {\n      readContextVectorsFile(myParam.validation_context_vectors_file, myParam.context_vector_size, validation_context_vectors_flat);\n      int validation_context_vectors_flat_size  = validation_context_vectors_flat.size() / myParam.context_vector_size;\n\t  if (validation_context_vectors_flat_size != validation_data_size){\n\t\t  cerr<<\"The nubmer of validation context vectors was not equal to the validationing data!\"<<endl;\n\t\t  exit(1);\n\t  }\n    }\n\t\n\tMap< Matrix<double,Dynamic,Dynamic> > validation_context_vectors(validation_context_vectors_flat.data(),\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tmyParam.context_vector_size, validation_data_size);\n\n\tMap< Matrix<double,Dynamic,Dynamic> > training_context_vectors(training_context_vectors_flat.data(),\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tmyParam.context_vector_size, training_data_size);\n\n    Map< Matrix<int,Dynamic,Dynamic> > validation_data(validation_data_flat.data(), myParam.ngram_size, validation_data_size);\n\n    if (use_mmap_file == false && randomize == true) {\n      cerr<<\"Randomly shuffling data...\"<<endl;\n      // Randomly shuffle training data to improve learning. Shuffling the context vectors as well\n      for (data_size_t i=training_data_size-1; i>0; i--)\n      {\n        data_size_t j = uniform_int_distribution<data_size_t>(0, i-1)(rng);\n        training_data.col(i).swap(training_data.col(j));\n\t\t//training_context_vectors.col(i).swap(training_context_vectors.col(j));\n      }\n    }\n\t\t\n    ///// Read in vocabulary file. We don't actually use it; it just gets reproduced in the output file\n\n    vector<string> input_words;\n    if (myParam.input_words_file != \"\")\n    {\n        readWordsFile(myParam.input_words_file, input_words);\n\tif (myParam.input_vocab_size == 0)\n\t    myParam.input_vocab_size = input_words.size();\n    }\n\n    vector<string> output_words;\n    if (myParam.output_words_file != \"\")\n    {\n        readWordsFile(myParam.output_words_file, output_words);\n\tif (myParam.output_vocab_size == 0)\n\t    myParam.output_vocab_size = output_words.size();\n    }\n\n    ///// Construct unigram model and sampler that will be used for NCE\n\n    vector<data_size_t> unigram_counts(myParam.output_vocab_size);\n    for (data_size_t train_id=0; train_id < training_data_size; train_id++)\n    {\n        int output_word;\n        if (use_mmap_file == false) {\n          output_word = training_data(myParam.ngram_size-1, train_id);\n        } else {\n\t      //cerr<<\"mmap word is \"<<training_data_flat_mmap->at((train_id+1)*myParam.ngram_size - 1)<<endl;\n          output_word = training_data_flat_mmap->at((train_id+1)*myParam.ngram_size - 1);\n        }\n\t\t//cerr<<\"output word is \"<<output_word<<endl;\n\t    unigram_counts[output_word] += 1;\n    }\n    multinomial<data_size_t> unigram (unigram_counts);\n\n    ///// Create and initialize the neural network and associated propagators.\n    model nn;\n    // IF THE MODEL FILE HAS BEEN DEFINED, THEN \n    // LOAD THE NEURAL NETWORK MODEL\n    //if (myParam.model_file != \"\"){\n    //nn.read(myParam.model_file);\n    // cerr<<\"reading the model\"<<endl;\n    \n\t//} else {\n      nn.resize(myParam.ngram_size,\n          myParam.input_vocab_size,\n          myParam.output_vocab_size,\n          myParam.input_embedding_dimension,\n          myParam.num_hidden,\n\t\t  myParam.num_second_hidden,\n          myParam.output_embedding_dimension,\n\t\t  myParam.context_vector_size);\n\n      nn.initialize(rng,\n          myParam.init_normal,\n          myParam.init_range,\n          -log(myParam.output_vocab_size),\n          myParam.parameter_update,\n          myParam.adagrad_epsilon);\n      nn.set_activation_function(string_to_activation_function(myParam.activation_function));\n\t  // If the input embeddings file has been specified then read from the input embeddings files\n\t  if (myParam.input_embeddings_file != \"\"){\n\t\t  cerr<<\" Reading the input embeddings from file\"<<myParam.input_embeddings_file<<endl;\n\t\t  nn.input_layer.read(myParam.input_embeddings_file);\n\t  }\n      if (myParam.model_file != \"\"){\n        nn.read(myParam.model_file);\n        cerr<<\"reading the model\"<<endl;\n      } \n    //}\n    loss_function_type loss_function = string_to_loss_function(myParam.loss_function);\n\n    propagator prop(nn, myParam.minibatch_size);\n    propagator prop_validation(nn, myParam.validation_minibatch_size);\n    SoftmaxNCELoss<multinomial<data_size_t> > softmax_loss(unigram);\n    // normalization parameters\n    vector_map c_h, c_h_running_gradient;\n    \n    ///////////////////////TRAINING THE NEURAL NETWORK////////////////////////////////////\n    /////////////////////////////////////////////////////////////////////////////////////\n\n    data_size_t num_batches = (training_data_size-1)/myParam.minibatch_size + 1;\n    cerr<<\"Number of training minibatches: \"<<num_batches<<endl;\n\n    int num_validation_batches = 0;\n    if (validation_data_size > 0)\n    {\n        num_validation_batches = (validation_data_size-1)/myParam.validation_minibatch_size+1;\n\tcerr<<\"Number of validation minibatches: \"<<num_validation_batches<<endl;\n    } \n\n    double current_momentum = myParam.initial_momentum;\n    double momentum_delta = (myParam.final_momentum - myParam.initial_momentum)/(myParam.num_epochs-1);\n    double current_learning_rate = myParam.learning_rate;\n    double current_validation_ll = 0.0;\n\tdouble current_validation_accuracy = 0.0;\n\n    int ngram_size = myParam.ngram_size;\n    int input_vocab_size = myParam.input_vocab_size;\n    int output_vocab_size = myParam.output_vocab_size;\n    int minibatch_size = myParam.minibatch_size;\n    int validation_minibatch_size = myParam.validation_minibatch_size;\n    int num_noise_samples = myParam.num_noise_samples;\n\n    if (myParam.normalization)\n    {\n      for (data_size_t i=0;i<training_data_size;i++)\n      {\n          Matrix<int,Dynamic,1> context = training_data.block(0,i,ngram_size-1,1);\n          if (c_h.find(context) == c_h.end())\n          {\n              c_h[context] = -myParam.normalization_init;\n          }\n      }\n    }\n\n\t//Setting up the dropout sampler\n\tboost::random::uniform_real_distribution<> real_01(0, 1);\n\t \n    for (int epoch=0; epoch<myParam.num_epochs; epoch++)\n    { \n\t\tdouble train_correct_labels = 0.;\n        cerr << \"Epoch \" << epoch+1 << endl;\n        cerr << \"Current learning rate: \" << current_learning_rate << endl;\n\t\t\n        if (myParam.use_momentum) \n\t    cerr << \"Current momentum: \" << current_momentum << endl;\n\telse\n            current_momentum = -1;\n\n\tcerr << \"Training minibatches: \";\n\n\tdouble log_likelihood = 0.0;\n\n\tint num_samples = 0;\n\tif (loss_function == LogLoss)\n\t    num_samples = output_vocab_size;\n\telse if (loss_function == NCELoss)\n\t    num_samples = 1+num_noise_samples;\n\n\tMatrix<double,Dynamic,Dynamic> minibatch_weights(num_samples, minibatch_size);\n\tMatrix<int,Dynamic,Dynamic> minibatch_samples(num_samples, minibatch_size);\n\tMatrix<double,Dynamic,Dynamic> scores(num_samples, minibatch_size);\n\tMatrix<double,Dynamic,Dynamic> probs(num_samples, minibatch_size);\n\tMatrix<double,Dynamic,Dynamic> first_hidden_dropout_mask(myParam.num_hidden,minibatch_size);\n\tMatrix<double,Dynamic,Dynamic> second_hidden_dropout_mask(myParam.output_embedding_dimension,minibatch_size);\n\t\n\n  for(data_size_t batch=0;batch<num_batches;batch++)\n        {\n            if (batch > 0 && batch % 10000 == 0)\n            {\n\t        cerr << batch <<\"...\";\n            } \n\n            data_size_t minibatch_start_index = minibatch_size * batch;\n\n      int current_minibatch_size = min(static_cast<data_size_t>(minibatch_size), training_data_size - minibatch_start_index);\n      #ifdef MAP\n\t    Matrix<int,Dynamic,Dynamic> minibatch = training_data.middleCols(minibatch_start_index, current_minibatch_size);\n      #else \n      //ALTERNATIVE OPTION IF YOU'RE NOT USING eigen map interface on the mmapped file\n\t    Matrix<int,Dynamic,Dynamic> minibatch;// = training_data.middleCols(minibatch_start_index, current_minibatch_size);\n\t\t//cerr<<\"Minibatch start index \"<<minibatch_start_index<<endl;\n\t\t//cerr<<\"Minibatch size \"<<current_minibatch_size<<endl;\n            if (use_mmap_file == true) {\n            minibatch.setZero(ngram_size,current_minibatch_size);\n            //now reading the ngrams from the mmaped file\n              for (int k=0; k<ngram_size; k++){\n                for (data_size_t index = 0 ; index<current_minibatch_size; index++) {\n\t\t\t\t  data_size_t current_index = index + minibatch_start_index;\n\t\t\t\t  //cerr<<\"the value in the mmap file \"<<index<<\" \"<<k<<\" is \"<<training_data_flat_mmap->at(current_index*ngram_size+k)<<endl;\n                  minibatch(k,index) = training_data_flat_mmap->at(current_index*ngram_size+k);\n                }\n              }\n            } else {\n              minibatch = training_data.middleCols(minibatch_start_index, current_minibatch_size);\n            }\n      #endif \n            double adjusted_learning_rate = current_learning_rate/current_minibatch_size;\n            //cerr<<\"Adjusted learning rate: \"<<adjusted_learning_rate<<endl;\n\n            /*\n            if (batch == rand() % num_batches)\n            {\n                cerr<<\"we are checking the gradient in batch \"<<batch<<endl;\n                /////////////////////////CHECKING GRADIENTS////////////////////////////////////////\n                gradientChecking(myParam,minibatch_start_index,current_minibatch_size,word_nodes,context_nodes,hidden_layer_node,hidden_layer_to_output_node,\n                              shuffled_training_data,c_h,unif_real_vector,eng_real_vector,unif_int_vector,eng_int_vector,unigram_probs_vector,\n                              q_vector,J_vector,D_prime);\n            }\n            */\n\n\t\t// Generating the dropout mask\n\t\tfor(int q=0; q<current_minibatch_size; q++){\n\t\t\tfor (int p=0; p<myParam.num_hidden; p++){\n\t\t\t\tfirst_hidden_dropout_mask(p,q) = ( real_01(rng) <1.0 - myParam.hidden1_dropout_value ) ? 0: 1; \n\t\t\t}\n\t\t\tfor (int p=0; p<myParam.output_embedding_dimension; p++){\n\t\t\t\tsecond_hidden_dropout_mask(p,q) = ( real_01(rng) < 1.0 - myParam.hidden2_dropout_value) ? 0: 1; \n\t\t\t}\n\n\t\t}\n\t\t//cerr<<\"Current minibatch size is \"<<current_minibatch_size<<endl;\n\t\t//cerr<<\"Shape of dropout mask is \"<<second_hidden_dropout_mask.rows()<<\" \"<<second_hidden_dropout_mask.cols()<<endl;\n\t\t//cerr<<\"Shape of dropout mask is \"<<first_hidden_dropout_mask.rows()<<\" \"<<first_hidden_dropout_mask.cols()<<endl;\n\t\t//cerr<<\"First hidden dropout mask is \"<<first_hidden_dropout_mask<<endl;\n\t\t//cerr<<\"dropout mas is \"<<second_hidden_dropout_mask<<endl;\n\t\t//getchar();\n\n\t\t\t\n        ///// Forward propagation\n        prop.fPropDropout(minibatch.topRows(ngram_size-1),\n\t\t\t\t\tfirst_hidden_dropout_mask,\n\t\t\t\t\tsecond_hidden_dropout_mask);\n\n\t    if (loss_function == NCELoss)\n\t    {\n\t      ///// Noise-contrastive estimation\n\n\t      // Generate noise samples. Gather positive and negative samples into matrix.\n\n\t      start_timer(3);\n\n        minibatch_samples.block(0, 0, 1, current_minibatch_size) = minibatch.bottomRows(1);\n        \n        for (int sample_id = 1; sample_id < num_noise_samples+1; sample_id++)\n            for (int train_id = 0; train_id < current_minibatch_size; train_id++)\n                minibatch_samples(sample_id, train_id) = unigram.sample(rng);\n          \n        stop_timer(3);\n\n        // Final forward propagation step (sparse)\n        start_timer(4);\n        prop.output_layer_node.param->fProp(prop.second_hidden_activation_node.fProp_matrix,\n                    minibatch_samples, scores);\n        stop_timer(4);\n\n        // Apply normalization parameters\n        if (myParam.normalization)\n        {\n            for (int train_id = 0;train_id < current_minibatch_size;train_id++)\n            {\n          Matrix<int,Dynamic,1> context = minibatch.block(0, train_id, ngram_size-1, 1);\n          scores.col(train_id).array() += c_h[context];\n            }\n        }\n\n        double minibatch_log_likelihood;\n        start_timer(5);\n        softmax_loss.fProp(scores.leftCols(current_minibatch_size), \n               minibatch_samples,\n               probs, \n\t\t\t   minibatch_log_likelihood);\n        stop_timer(5);\n        log_likelihood += minibatch_log_likelihood;\n\n        ///// Backward propagation\n\n        start_timer(6);\n        softmax_loss.bProp(probs, minibatch_weights);\n        stop_timer(6);\n        \n        // Update the normalization parameters\n        \n        if (myParam.normalization)\n        {\n          for (int train_id = 0;train_id < current_minibatch_size;train_id++)\n          {\n            Matrix<int,Dynamic,1> context = minibatch.block(0, train_id, ngram_size-1, 1);\n            c_h[context] += adjusted_learning_rate * minibatch_weights.col(train_id).sum();\n          }\n        }\n\n        // Be careful of short minibatch\n        prop.bProp(minibatch.topRows(ngram_size-1),\n             minibatch_samples.leftCols(current_minibatch_size), \n             minibatch_weights.leftCols(current_minibatch_size),\n\t\t\t first_hidden_dropout_mask.leftCols(current_minibatch_size),\n\t\t\t second_hidden_dropout_mask.leftCols(current_minibatch_size),\n             adjusted_learning_rate, \n             current_momentum,\n             myParam.L2_reg,\n             myParam.parameter_update,\n             myParam.conditioning_constant,\n             myParam.decay);\n\t    }\n\t    else if (loss_function == LogLoss)\n\t    {\n\t      ///// Standard log-likelihood\n\t      start_timer(4);\n        prop.output_layer_node.param->fProp(prop.second_hidden_activation_node.fProp_matrix, scores);\n        stop_timer(4);\n\n        double minibatch_log_likelihood;\n        start_timer(5);\n        SoftmaxLogLoss().fProp(scores.leftCols(current_minibatch_size), \n                   minibatch.row(ngram_size-1), \n                   probs, \n                   minibatch_log_likelihood);\n        stop_timer(5);\n        log_likelihood += minibatch_log_likelihood;\n\n        ///// Backward propagation\n        \n        start_timer(6);\n        SoftmaxLogLoss().bProp(minibatch.row(ngram_size-1).leftCols(current_minibatch_size), \n                   probs.leftCols(current_minibatch_size), \n                   minibatch_weights);\n        stop_timer(6);\n        //Computing the training accuracy\n   \t\tfor (int minibatch_instance=0; minibatch_instance < current_minibatch_size; minibatch_instance++){\n   \t\t\tMatrix<double,1,Dynamic>::Index max_index;\n   \t\t\tprobs.col(minibatch_instance).maxCoeff(&max_index);\n   \t\t\tif (max_index == \n   \t\t\t\tminibatch.row(ngram_size-1).leftCols(current_minibatch_size)(minibatch_instance)){\n   \t\t\t\t\ttrain_correct_labels += 1;\n   \t\t\t\t}\n   \t\t}\t\t\n    \t\n\n        prop.bProp(minibatch.topRows(ngram_size-1).leftCols(current_minibatch_size),\n             minibatch_weights,\n\t\t\t first_hidden_dropout_mask,\n\t\t\t second_hidden_dropout_mask,\n             adjusted_learning_rate,\n             current_momentum,\n             myParam.L2_reg,\n             myParam.parameter_update,\n             myParam.conditioning_constant,\n             myParam.decay);\n          }\n      }\n\t  \n\tcerr << \"done.\" << endl;\n\n\tif (loss_function == LogLoss)\n\t{\n\t    cerr << \"Training log-likelihood: \" << log_likelihood << endl;\n        cerr << \"         perplexity:     \"<< exp(-log_likelihood/training_data_size) << endl;\n\t\tcerr << \"         accuracy:       \"<< train_correct_labels/training_data_size <<endl;\n\t}\n\telse if (loss_function == NCELoss)\n\t    cerr << \"Training NCE log-likelihood: \" << log_likelihood << endl;\n\n        current_momentum += momentum_delta;\n\n\t#ifdef USE_CHRONO\n\tcerr << \"Propagation times:\";\n\tfor (int i=0; i<timer.size(); i++)\n\t  cerr << \" \" << timer.get(i);\n\tcerr << endl;\n\t#endif\n\t\n\t//Scaled the model before writing\n\tnn.scale(myParam.hidden1_dropout_value,\n\t\t\tmyParam.hidden2_dropout_value,\n\t\t\tmyParam.hidden3_dropout_value);\n\tif (myParam.model_prefix != \"\")\n\t{\n\t    cerr << \"Writing model\" << endl;\n\t    if (myParam.input_words_file != \"\")\n\t        nn.write(myParam.model_prefix + \".\" + lexical_cast<string>(epoch+1), input_words, output_words);\n\t    else\n\t        nn.write(myParam.model_prefix + \".\" + lexical_cast<string>(epoch+1));\n\t}\n\n        if (epoch % 1 == 0 && validation_data_size > 0)\n        {\n\t\t    //Matrix<int,Dynamic,1> validation_argmaxes;\n\t\t\t//validation_argmaxes.setZero(validation_data_size);\n\t\t\tvector<int> validation_argmaxes;\n\t\t\tstring argmax_file = \"argmax.\"+lexical_cast<string>(epoch+1);\n            //////COMPUTING VALIDATION SET PERPLEXITY///////////////////////\n            ////////////////////////////////////////////////////////////////\n\n            double log_likelihood = 0.0;\n\n\t    Matrix<double,Dynamic,Dynamic> scores(output_vocab_size, validation_minibatch_size);\n\t    Matrix<double,Dynamic,Dynamic> output_probs(output_vocab_size, validation_minibatch_size);\n\t    Matrix<int,Dynamic,Dynamic> minibatch(ngram_size, validation_minibatch_size);\n\t\tdouble validation_correct_labels  =0;\n            for (int validation_batch =0;validation_batch < num_validation_batches;validation_batch++)\n            {\n                int validation_minibatch_start_index = validation_minibatch_size * validation_batch;\n\t\tint current_minibatch_size = min(validation_minibatch_size,\n\t\t\t\t\t\t validation_data_size - validation_minibatch_start_index);\n\t\tminibatch.leftCols(current_minibatch_size) = validation_data.middleCols(validation_minibatch_start_index, \n\t\t\t\t\t\t\t\t\t\t\tcurrent_minibatch_size);\n\t\tprop_validation.fPropContext(minibatch.topRows(ngram_size-1));\n\n\t\t// Do full forward prop through output word embedding layer\n\t\tstart_timer(4);\n\t\tprop_validation.output_layer_node.param->fProp(prop_validation.second_hidden_activation_node.fProp_matrix, scores);\n\t\tstop_timer(4);\n\n\t\t// And softmax and loss. Be careful of short minibatch\n\t\tdouble minibatch_log_likelihood;\n\t\tstart_timer(5);\n\t\tSoftmaxLogLoss().fProp(scores.leftCols(current_minibatch_size), \n\t\t\t\t       minibatch.row(ngram_size-1),\n\t\t\t\t       output_probs,\n\t\t\t\t       minibatch_log_likelihood);\n\t\tstop_timer(5);\n\t\tlog_likelihood += minibatch_log_likelihood;\n\t   \t\tfor (int minibatch_instance=0; minibatch_instance < current_minibatch_size; minibatch_instance++){\n\t   \t\t\tMatrix<double,1,Dynamic>::Index max_index;\n\t   \t\t\toutput_probs.col(minibatch_instance).maxCoeff(&max_index);\n\t\t\t\tvalidation_argmaxes.push_back(max_index);\n\t   \t\t\tif (max_index == \n\t   \t\t\t\tminibatch.row(ngram_size-1)(minibatch_instance)){\n\t   \t\t\t\t\tvalidation_correct_labels += 1;\n\t   \t\t\t\t}\n\t   \t\t}\t\t\n\t    }\n\t\t   /*\n           //CREATING AN EIGEN MATRIX OUT OF THE ARGMAXES\n\t\t   Matrix<int,Dynamic,1> argmaxes_vector(validation_data_size);\n\t\t   for (data_size_t index=0; index<=validation_data_size; validation_data_size++){\n\t\t     argmaxes_vector(index) = validation_argmaxes[index];\n\t\t   }\n\t\t   */\n\t\t   //argmaxes_vector = Map< Matrix<int,Dynamic,1> >(validation_argmaxes.data(),validation_data_size,1);\n            cerr << \"Validation log-likelihood: \"<< log_likelihood << endl;\n            cerr << \"           perplexity:     \"<< exp(-log_likelihood/validation_data_size) << endl;\n\t\t\tcerr << \"           accuracy:       \"<< validation_correct_labels/validation_data_size <<endl;\n            writeVector(validation_argmaxes,argmax_file);\n\t    // If the validation perplexity decreases, halve the learning rate.\n\n            //if (epoch > 0 && validation_correct_labels/validation_data_size < current_validation_accuracy && myParam.parameter_update != \"ADA\" && current_momentum < 0.)\n\t\t\t//\n            if (epoch > 0 && log_likelihood < current_validation_ll && myParam.parameter_update != \"ADA\" && current_momentum < 0.)\n            { \n                current_learning_rate /= 2;\n            }\n            current_validation_ll = log_likelihood;\n\t\t\tcurrent_validation_accuracy = validation_correct_labels/validation_data_size;\n\t\t\t\n\t\t}\n\t\t//Scaled the model back after validation\n\t\tnn.scale(1.0/myParam.hidden1_dropout_value,\n\t\t\t1.0/myParam.hidden2_dropout_value,\n\t\t\t1.0/myParam.hidden3_dropout_value);\n    }\n    return 0;\n}\n\n", "meta": {"hexsha": "b6bd3b6147151e11eb017c5271c1ad9f2cbf79da", "size": 42733, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src_train_dropout_two_hidden/trainNeuralNetwork.cpp", "max_stars_repo_name": "sagae/nndep", "max_stars_repo_head_hexsha": "efa7db1cfe276647bfdd71658ee5b248a51182f4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2016-10-12T13:09:49.000Z", "max_stars_repo_stars_event_max_datetime": "2017-11-16T09:00:26.000Z", "max_issues_repo_path": "src_train_dropout_two_hidden/trainNeuralNetwork.cpp", "max_issues_repo_name": "sagae/nndep", "max_issues_repo_head_hexsha": "efa7db1cfe276647bfdd71658ee5b248a51182f4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src_train_dropout_two_hidden/trainNeuralNetwork.cpp", "max_forks_repo_name": "sagae/nndep", "max_forks_repo_head_hexsha": "efa7db1cfe276647bfdd71658ee5b248a51182f4", "max_forks_repo_licenses": ["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.2478354978, "max_line_length": 204, "alphanum_fraction": 0.6683827487, "num_tokens": 9909, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.685949467848392, "lm_q2_score": 0.480478678047907, "lm_q1q2_score": 0.32958409351946066}}
{"text": "//==============================================================================\n//         Copyright 2003 - 2011 LASMEA UMR 6602 CNRS/Univ. Clermont II\n//         Copyright 2009 - 2011 LRI    UMR 8623 CNRS/Univ Paris Sud XI\n//         Copyright 2012 - 2014 MetaScale 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 BOOST_SIMD_ARITHMETIC_FUNCTIONS_SIMD_COMMON_DIVS_HPP_INCLUDED\n#define BOOST_SIMD_ARITHMETIC_FUNCTIONS_SIMD_COMMON_DIVS_HPP_INCLUDED\n\n#include <boost/simd/arithmetic/functions/divs.hpp>\n#include <boost/simd/include/functions/simd/is_eqz.hpp>\n#include <boost/simd/include/functions/simd/is_nez.hpp>\n#include <boost/simd/include/functions/simd/divides.hpp>\n#include <boost/simd/include/functions/simd/shift_right.hpp>\n#include <boost/simd/include/functions/simd/plus.hpp>\n#include <boost/simd/include/functions/simd/if_zero_else_one.hpp>\n#include <boost/simd/include/functions/simd/bitwise_or.hpp>\n#include <boost/simd/include/functions/simd/bitwise_xor.hpp>\n#include <boost/simd/include/functions/simd/if_else.hpp>\n#include <boost/simd/include/functions/simd/genmask.hpp>\n#include <boost/simd/include/functions/simd/logical_and.hpp>\n#include <boost/simd/include/constants/one.hpp>\n#include <boost/simd/include/constants/valmin.hpp>\n#include <boost/simd/include/constants/valmax.hpp>\n#include <boost/simd/sdk/meta/scalar_of.hpp>\n#include <boost/simd/sdk/meta/as_logical.hpp>\n#include <boost/dispatch/attributes.hpp>\n\n// perhaps divs for signed integral types must invoke correct Valmin entry and invoke  divfix\n// also call simply divfix for unsigned\n// also rdivide has to be defined as divs for float and as divfix for integers\nnamespace boost { namespace simd { namespace ext\n{\n  BOOST_DISPATCH_IMPLEMENT          ( divs_, tag::cpu_, (A0)(X)\n                                    , ((simd_<floating_<A0>,X>))\n                                      ((simd_<floating_<A0>,X>))\n                                    )\n  {\n    typedef A0 result_type;\n    BOOST_FORCEINLINE BOOST_SIMD_FUNCTOR_CALL_REPEAT(2)\n    {\n      return a0/a1;\n    }\n  };\n\n  BOOST_DISPATCH_IMPLEMENT          ( divs_, tag::cpu_, (A0)(X)\n                                    , ((simd_<uint_<A0>,X>))\n                                      ((simd_<uint_<A0>,X>))\n                                    )\n  {\n    typedef A0 result_type;\n    BOOST_FORCEINLINE BOOST_SIMD_FUNCTOR_CALL_REPEAT(2)\n    {\n      typedef typename meta::as_logical<A0>::type bA0;\n\n\n      const bA0 iseqza1 = is_eqz(a1);\n      const A0 aa1 = if_else(iseqza1, One<A0>(), a1);\n      const A0 aa0 = if_else(iseqza1, genmask(a0), a0);\n      return aa0/aa1;\n    }\n  };\n\n  BOOST_DISPATCH_IMPLEMENT          ( divs_, tag::cpu_, (A0)(X)\n                                    , ((simd_<int_<A0>,X>))\n                                      ((simd_<int_<A0>,X>))\n                                    )\n  {\n    typedef A0 result_type;\n\n    BOOST_FORCEINLINE BOOST_SIMD_FUNCTOR_CALL_REPEAT(2)\n    {\n      typedef typename meta::as_logical<A0>::type bA0;\n      typedef typename meta::scalar_of<A0>::type sA0;\n\n      const bA0 iseqza1 = is_eqz(a1);\n\n      // replace valmin/-1 by (valmin+1)/-1\n      A0 x = a0 + if_zero_else_one((a1 + One<A0>()) | (a0 + Valmin<A0>()));\n      // negative -> valmin\n      // positive -> valmax\n      const A0 x2 = bitwise_xor(Valmax<A0>(), shrai(x, sizeof(sA0)*CHAR_BIT-1));\n\n      x = if_else(logical_and(iseqza1, is_nez(x)), x2, x);\n      const A0 y = if_else(iseqza1, One<A0>(), a1);\n      return x/y;\n    }\n  };\n} } }\n\n#endif\n", "meta": {"hexsha": "fbd63830d4ea264f859a2c7561d1a15e1bdcc166", "size": 3730, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/boost/simd/base/include/boost/simd/arithmetic/functions/simd/common/divs.hpp", "max_stars_repo_name": "psiha/nt2", "max_stars_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 34.0, "max_stars_repo_stars_event_min_datetime": "2017-05-19T18:10:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-04T02:18:13.000Z", "max_issues_repo_path": "modules/boost/simd/base/include/boost/simd/arithmetic/functions/simd/common/divs.hpp", "max_issues_repo_name": "psiha/nt2", "max_issues_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "modules/boost/simd/base/include/boost/simd/arithmetic/functions/simd/common/divs.hpp", "max_forks_repo_name": "psiha/nt2", "max_forks_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2017-12-02T12:59:17.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-31T12:46:14.000Z", "avg_line_length": 39.2631578947, "max_line_length": 93, "alphanum_fraction": 0.600536193, "num_tokens": 944, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6859494678483918, "lm_q2_score": 0.480478678047907, "lm_q1q2_score": 0.3295840935194606}}
{"text": "// This file is part of libigl, a simple c++ geometry processing library.\n// \n// Copyright (C) 2015 Alec Jacobson <alecjacobson@gmail.com>\n// \n// This Source Code Form is subject to the terms of the Mozilla Public License \n// v. 2.0. If a copy of the MPL was not distributed with this file, You can \n// obtain one at http://mozilla.org/MPL/2.0/.\n#include \"planarize_quad_mesh.h\"\n#include \"quad_planarity.h\"\n#include <Eigen/Sparse>\n#include <Eigen/Eigenvalues> \n#include <iostream>\n\nnamespace igl\n{\n  template <typename DerivedV, typename DerivedF>\n  class PlanarizerShapeUp\n  {\n  protected:\n    // number of faces, number of vertices\n    long numV, numF;\n    // references to the input faces and vertices\n    const Eigen::MatrixBase<DerivedV> &Vin;\n    const Eigen::MatrixBase<DerivedF> &Fin;\n    \n    // vector consisting of the vertex positions stacked: [x;y;z;x;y;z...]\n    // vector consisting of a weight per face (currently all set to 1)\n    // vector consisting of the projected face vertices (might be different for the same vertex belonging to different faces)\n    Eigen::Matrix<typename DerivedV::Scalar, Eigen::Dynamic, 1> Vv, weightsSqrt, P;\n    \n    // Matrices as in the paper\n    // Q: lhs matrix\n    // Ni: matrix that subtracts the mean of a face from the 4 vertices of a face\n    Eigen::SparseMatrix<typename DerivedV::Scalar > Q, Ni;\n    Eigen::SimplicialLDLT<Eigen::SparseMatrix<typename DerivedV::Scalar > > solver;\n    \n    int maxIter;\n    double threshold;\n    const int ni = 4;\n    \n    // Matrix assemblers\n    inline void assembleQ();\n    inline void assembleP();\n    inline void assembleNi();\n\n    // Selects out of Vv the 4 vertices belonging to face fi\n    inline void assembleSelector(int fi,\n                          Eigen::SparseMatrix<typename DerivedV::Scalar > &S);\n    \n    \n  public:\n    // Init - assemble stacked vector and lhs matrix, factorize\n    inline PlanarizerShapeUp(const Eigen::MatrixBase<DerivedV> &V_,\n                             const Eigen::MatrixBase<DerivedF> &F_,\n                             const int maxIter_,\n                             const double &threshold_);\n    // Planarization - output to Vout\n    inline void planarize(Eigen::PlainObjectBase<DerivedV> &Vout);\n  };\n}\n\n//Implementation\n\ntemplate <typename DerivedV, typename DerivedF>\ninline igl::PlanarizerShapeUp<DerivedV, DerivedF>::PlanarizerShapeUp(const Eigen::MatrixBase<DerivedV> &V_,\n                                                                     const Eigen::MatrixBase<DerivedF> &F_,\n                                                                     const int maxIter_,\n                                                                     const double &threshold_):\nnumV(V_.rows()),\nnumF(F_.rows()),\nVin(V_),\nFin(F_),\nweightsSqrt(Eigen::Matrix<typename DerivedV::Scalar, Eigen::Dynamic, 1>::Ones(numF,1)),\nmaxIter(maxIter_),\nthreshold(threshold_)\n{\n  // assemble stacked vertex position vector\n  Vv.setZero(3*numV,1);\n  for (int i =0;i<numV;++i)\n    Vv.segment(3*i,3) = Vin.row(i);\n  // assemble and factorize lhs matrix\n  assembleQ();\n};\n\ntemplate <typename DerivedV, typename DerivedF>\ninline void igl::PlanarizerShapeUp<DerivedV, DerivedF>::assembleQ()\n{\n  std::vector<Eigen::Triplet<typename DerivedV::Scalar> > tripletList;\n  \n  // assemble the Ni matrix\n  assembleNi();\n  \n  for (int fi = 0; fi< numF; fi++)\n  {\n    Eigen::SparseMatrix<typename DerivedV::Scalar > Sfi;\n    assembleSelector(fi, Sfi);\n    \n    // the final matrix per face\n    Eigen::SparseMatrix<typename DerivedV::Scalar > Qi = weightsSqrt(fi)*Ni*Sfi;\n    // put it in the correct block of Q\n    // todo: this can be made faster by omitting the selector matrix\n    for (int k=0; k<Qi.outerSize(); ++k)\n      for (typename Eigen::SparseMatrix<typename DerivedV::Scalar >::InnerIterator it(Qi,k); it; ++it)\n      {\n        typename DerivedV::Scalar val = it.value();\n        int row = it.row();\n        int col = it.col();\n        tripletList.push_back(Eigen::Triplet<typename DerivedV::Scalar>(row+3*ni*fi,col,val));\n      }\n  }\n  \n  Q.resize(3*ni*numF,3*numV);\n  Q.setFromTriplets(tripletList.begin(), tripletList.end());\n  // the actual lhs matrix is Q'*Q\n  // prefactor that matrix\n  solver.compute(Q.transpose()*Q);\n  if(solver.info()!=Eigen::Success)\n  {\n    std::cerr << \"Cholesky failed - PlanarizerShapeUp.cpp\" << std::endl;\n    assert(0);\n  }\n}\n\ntemplate <typename DerivedV, typename DerivedF>\ninline void igl::PlanarizerShapeUp<DerivedV, DerivedF>::assembleNi()\n{\n  std::vector<Eigen::Triplet<typename DerivedV::Scalar>> tripletList;\n  for (int ii = 0; ii< ni; ii++)\n  {\n    for (int jj = 0; jj< ni; jj++)\n    {\n      tripletList.push_back(Eigen::Triplet<typename DerivedV::Scalar>(3*ii+0,3*jj+0,-1./ni));\n      tripletList.push_back(Eigen::Triplet<typename DerivedV::Scalar>(3*ii+1,3*jj+1,-1./ni));\n      tripletList.push_back(Eigen::Triplet<typename DerivedV::Scalar>(3*ii+2,3*jj+2,-1./ni));\n    }\n    tripletList.push_back(Eigen::Triplet<typename DerivedV::Scalar>(3*ii+0,3*ii+0,1.));\n    tripletList.push_back(Eigen::Triplet<typename DerivedV::Scalar>(3*ii+1,3*ii+1,1.));\n    tripletList.push_back(Eigen::Triplet<typename DerivedV::Scalar>(3*ii+2,3*ii+2,1.));\n  }\n  Ni.resize(3*ni,3*ni);\n  Ni.setFromTriplets(tripletList.begin(), tripletList.end());\n}\n\n//assumes V stacked [x;y;z;x;y;z...];\ntemplate <typename DerivedV, typename DerivedF>\ninline void igl::PlanarizerShapeUp<DerivedV, DerivedF>::assembleSelector(int fi,\n                                                                            Eigen::SparseMatrix<typename DerivedV::Scalar > &S)\n{\n  \n  std::vector<Eigen::Triplet<typename DerivedV::Scalar>> tripletList;\n  for (int fvi = 0; fvi< ni; fvi++)\n  {\n    int vi = Fin(fi,fvi);\n    tripletList.push_back(Eigen::Triplet<typename DerivedV::Scalar>(3*fvi+0,3*vi+0,1.));\n    tripletList.push_back(Eigen::Triplet<typename DerivedV::Scalar>(3*fvi+1,3*vi+1,1.));\n    tripletList.push_back(Eigen::Triplet<typename DerivedV::Scalar>(3*fvi+2,3*vi+2,1.));\n  }\n  \n  S.resize(3*ni,3*numV);\n  S.setFromTriplets(tripletList.begin(), tripletList.end());\n  \n}\n\n//project all faces to their closest planar face\ntemplate <typename DerivedV, typename DerivedF>\ninline void igl::PlanarizerShapeUp<DerivedV, DerivedF>::assembleP()\n{\n  P.setZero(3*ni*numF);\n  for (int fi = 0; fi< numF; fi++)\n  {\n    // todo: this can be made faster by omitting the selector matrix\n    Eigen::SparseMatrix<typename DerivedV::Scalar > Sfi;\n    assembleSelector(fi, Sfi);\n    Eigen::SparseMatrix<typename DerivedV::Scalar > NSi = Ni*Sfi;\n    \n    Eigen::Matrix<typename DerivedV::Scalar, Eigen::Dynamic, 1> Vi = NSi*Vv;\n    Eigen::Matrix<typename DerivedV::Scalar, Eigen::Dynamic, Eigen::Dynamic> CC(3,ni);\n    for (int i = 0; i <ni; ++i)\n      CC.col(i) = Vi.segment(3*i, 3);\n    Eigen::Matrix<typename DerivedV::Scalar, 3, 3> C = CC*CC.transpose();\n    \n    // Alec: Doesn't compile\n    Eigen::EigenSolver<Eigen::Matrix<typename DerivedV::Scalar, 3, 3>> es(C);\n    // the real() is for compilation purposes\n    Eigen::Matrix<typename DerivedV::Scalar, 3, 1> lambda = es.eigenvalues().real();\n    Eigen::Matrix<typename DerivedV::Scalar, 3, 3> U = es.eigenvectors().real();\n    int min_i;\n    lambda.cwiseAbs().minCoeff(&min_i);\n    U.col(min_i).setZero();\n    Eigen::Matrix<typename DerivedV::Scalar, Eigen::Dynamic, Eigen::Dynamic> PP = U*U.transpose()*CC;\n    for (int i = 0; i <ni; ++i)\n     P.segment(3*ni*fi+3*i, 3) =  weightsSqrt[fi]*PP.col(i);\n    \n  }\n}\n\n\ntemplate <typename DerivedV, typename DerivedF>\ninline void igl::PlanarizerShapeUp<DerivedV, DerivedF>::planarize(Eigen::PlainObjectBase<DerivedV> &Vout)\n{\n  Eigen::Matrix<typename DerivedV::Scalar, Eigen::Dynamic, 1> planarity;\n  Vout = Vin;\n  \n  for (int iter =0; iter<maxIter; ++iter)\n  {\n    igl::quad_planarity(Vout, Fin, planarity);\n    typename DerivedV::Scalar nonPlanarity = planarity.cwiseAbs().maxCoeff();\n    //std::cerr<<\"iter #\"<<iter<<\": max non-planarity: \"<<nonPlanarity<<std::endl;\n    if (nonPlanarity<threshold)\n      break;\n    assembleP();\n    Vv = solver.solve(Q.transpose()*P);\n    if(solver.info()!=Eigen::Success)\n    {\n      std::cerr << \"Linear solve failed - PlanarizerShapeUp.cpp\" << std::endl;\n      assert(0);\n    }\n    for (int i =0;i<numV;++i)\n      Vout.row(i) << Vv.segment(3*i,3).transpose();\n  }\n  // set the mean of Vout to the mean of Vin\n  Eigen::Matrix<typename DerivedV::Scalar, 1, 3> oldMean, newMean;\n  oldMean = Vin.colwise().mean();\n  newMean = Vout.colwise().mean();\n  Vout.rowwise() += (oldMean - newMean);\n  \n};\n\n  \n\ntemplate <typename DerivedV, typename DerivedF>\nIGL_INLINE void igl::planarize_quad_mesh(const Eigen::MatrixBase<DerivedV> &Vin,\n                                    const Eigen::MatrixBase<DerivedF> &Fin,\n                                    const int maxIter,\n                                    const double &threshold,\n                                    Eigen::PlainObjectBase<DerivedV> &Vout)\n{\n  PlanarizerShapeUp<DerivedV, DerivedF> planarizer(Vin, Fin, maxIter, threshold);\n  planarizer.planarize(Vout);\n}\n\n#ifdef IGL_STATIC_LIBRARY\n// Explicit template instantiation\ntemplate void igl::planarize_quad_mesh<Eigen::Matrix<double, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, -1, 0, -1, -1> >(Eigen::MatrixBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> > const&, Eigen::MatrixBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> > const&, int, double const&, Eigen::PlainObjectBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> >&);\n#endif\n", "meta": {"hexsha": "24687e9a744b0becd709b0bf3a9a1cc2d427f9c6", "size": 9458, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "third_party/libigl/include/igl/planarize_quad_mesh.cpp", "max_stars_repo_name": "chefmramos85/monster-mash", "max_stars_repo_head_hexsha": "239a41f6f178ca83c4be638331e32f23606b0381", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1125.0, "max_stars_repo_stars_event_min_datetime": "2021-02-01T09:51:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T01:50:40.000Z", "max_issues_repo_path": "third_party/libigl/include/igl/planarize_quad_mesh.cpp", "max_issues_repo_name": "ryan-cranfill/monster-mash", "max_issues_repo_head_hexsha": "c1b906d996885f8a4011bdf7558e62e968e1e914", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 19.0, "max_issues_repo_issues_event_min_datetime": "2021-02-01T12:36:30.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-19T14:02:50.000Z", "max_forks_repo_path": "third_party/libigl/include/igl/planarize_quad_mesh.cpp", "max_forks_repo_name": "ryan-cranfill/monster-mash", "max_forks_repo_head_hexsha": "c1b906d996885f8a4011bdf7558e62e968e1e914", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 148.0, "max_forks_repo_forks_event_min_datetime": "2021-02-13T10:54:31.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T11:55:20.000Z", "avg_line_length": 38.4471544715, "max_line_length": 344, "alphanum_fraction": 0.6429477691, "num_tokens": 2662, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6859494421679929, "lm_q2_score": 0.48047867804790706, "lm_q1q2_score": 0.3295840811805765}}
{"text": "//---------------------------------------------------------------------------//\n// Copyright (c) 2021 Mikhail Komarov <nemo@nil.foundation>\n// Copyright (c) 2021 Ilias Khairullin <ilias@nil.foundation>\n//\n// MIT License\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in all\n// copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n// SOFTWARE.\n//---------------------------------------------------------------------------//\n\n#ifndef CRYPTO3_PUBKEY_ELGAMAL_VERIFIABLE_HPP\n#define CRYPTO3_PUBKEY_ELGAMAL_VERIFIABLE_HPP\n\n#include <tuple>\n#include <type_traits>\n#include <iterator>\n#include <vector>\n\n#include <boost/assert.hpp>\n\n#include <nil/crypto3/algebra/algorithms/pair.hpp>\n\n#include <nil/crypto3/zk/algorithms/prove.hpp>\n#include <nil/crypto3/zk/algorithms/verify.hpp>\n\n#include <nil/crypto3/zk/snark/systems/ppzksnark/r1cs_gg_ppzksnark.hpp>\n\n#include <nil/crypto3/pubkey/keys/private_key.hpp>\n#include <nil/crypto3/pubkey/keys/verification_key.hpp>\n#include <nil/crypto3/pubkey/operations/generate_keypair_op.hpp>\n#include <nil/crypto3/pubkey/operations/encrypt_op.hpp>\n#include <nil/crypto3/pubkey/operations/decrypt_op.hpp>\n#include <nil/crypto3/pubkey/operations/verify_encryption_op.hpp>\n#include <nil/crypto3/pubkey/operations/verify_decryption_op.hpp>\n#include <nil/crypto3/pubkey/operations/rerandomize_op.hpp>\n\nnamespace nil {\n    namespace crypto3 {\n        namespace pubkey {\n            template<typename Curve, std::size_t BlockBits = 4>\n            class elgamal_verifiable {\n                typedef elgamal_verifiable<Curve, BlockBits> self_type;\n                static_assert(BlockBits > 0);\n\n            public:\n                typedef Curve curve_type;\n                static constexpr std::size_t block_bits = BlockBits;\n\n                typedef public_key<self_type> public_key_type;\n                typedef private_key<self_type> private_key_type;\n                typedef verification_key<self_type> verification_key_type;\n                typedef std::tuple<public_key_type, private_key_type, verification_key_type> keypair_type;\n\n                typedef zk::snark::r1cs_gg_ppzksnark<\n                    Curve, zk::snark::r1cs_gg_ppzksnark_generator<Curve, zk::snark::proving_mode::encrypted_input>,\n                    zk::snark::r1cs_gg_ppzksnark_prover<Curve, zk::snark::proving_mode::encrypted_input>,\n                    zk::snark::r1cs_gg_ppzksnark_verifier_strong_input_consistency<\n                        Curve, zk::snark::proving_mode::encrypted_input>,\n                    zk::snark::proving_mode::encrypted_input>\n                    proof_system_type;\n\n                typedef std::pair<std::vector<typename Curve::template g1_type<>::value_type>,\n                                  typename proof_system_type::proof_type>\n                    cipher_type;\n                typedef std::pair<std::vector<typename Curve::scalar_field_type::value_type>,\n                                  typename Curve::template g1_type<>::value_type>\n                    decipher_type;\n            };\n\n            template<typename Curve, std::size_t BlockBits>\n            struct verification_key<elgamal_verifiable<Curve, BlockBits>> {\n                typedef elgamal_verifiable<Curve, BlockBits> scheme_type;\n                typedef typename Curve::template g2_type<> g2_type;\n\n                friend class decrypt_op<scheme_type>;\n                friend class verify_decryption_op<scheme_type>;\n\n                verification_key() = default;\n                verification_key(const typename g2_type::value_type &rho_g2,\n                                 const std::vector<typename g2_type::value_type> &rho_sv_g2,\n                                 const std::vector<typename g2_type::value_type> &rho_rhov_g2) :\n                    rho_g2(rho_g2),\n                    rho_sv_g2(rho_sv_g2), rho_rhov_g2(rho_rhov_g2) {\n                }\n                verification_key(typename g2_type::value_type &&rho_g2,\n                                 std::vector<typename g2_type::value_type> &&rho_sv_g2,\n                                 std::vector<typename g2_type::value_type> &&rho_rhov_g2) :\n                    rho_g2(std::move(rho_g2)),\n                    rho_sv_g2(std::move(rho_sv_g2)), rho_rhov_g2(std::move(rho_rhov_g2)) {\n                }\n\n                // private:\n                typename g2_type::value_type rho_g2;\n                std::vector<typename g2_type::value_type> rho_sv_g2;\n                std::vector<typename g2_type::value_type> rho_rhov_g2;\n            };\n\n            template<typename Curve, std::size_t BlockBits>\n            struct public_key<elgamal_verifiable<Curve, BlockBits>> {\n                typedef elgamal_verifiable<Curve, BlockBits> scheme_type;\n\n                typedef typename Curve::template g1_type<> g1_type;\n                typedef typename Curve::template g2_type<> g2_type;\n\n                public_key() = default;\n                public_key &operator=(const public_key &other) = default;\n                public_key(const public_key &other) = default;\n                public_key(public_key &&other) = default;\n                public_key(const typename g1_type::value_type &delta_g1,\n                           const std::vector<typename g1_type::value_type> &delta_s_g1,\n                           const std::vector<typename g1_type::value_type> &t_g1,\n                           const std::vector<typename g2_type::value_type> &t_g2,\n                           const typename g1_type::value_type &delta_sum_s_g1,\n                           const typename g1_type::value_type &gamma_inverse_sum_s_g1) :\n                    delta_g1(delta_g1),\n                    delta_s_g1(delta_s_g1), t_g1(t_g1), t_g2(t_g2), delta_sum_s_g1(delta_sum_s_g1),\n                    gamma_inverse_sum_s_g1(gamma_inverse_sum_s_g1) {\n                }\n                public_key(typename g1_type::value_type &&delta_g1,\n                           std::vector<typename g1_type::value_type> &&delta_s_g1,\n                           std::vector<typename g1_type::value_type> &&t_g1,\n                           std::vector<typename g2_type::value_type> &&t_g2,\n                           typename g1_type::value_type &&delta_sum_s_g1,\n                           typename g1_type::value_type &&gamma_inverse_sum_s_g1) :\n                    delta_g1(std::move(delta_g1)),\n                    delta_s_g1(std::move(delta_s_g1)), t_g1(std::move(t_g1)), t_g2(std::move(t_g2)),\n                    delta_sum_s_g1(std::move(delta_sum_s_g1)),\n                    gamma_inverse_sum_s_g1(std::move(gamma_inverse_sum_s_g1)) {\n                }\n\n                bool operator==(const public_key &other) const {\n                    return delta_g1 == other.delta_g1 && delta_s_g1 == other.delta_s_g1 && t_g1 == other.t_g1 &&\n                           t_g2 == other.t_g2 && delta_sum_s_g1 == other.delta_sum_s_g1 &&\n                           gamma_inverse_sum_s_g1 == other.gamma_inverse_sum_s_g1;\n                }\n\n                typename g1_type::value_type delta_g1;\n                std::vector<typename g1_type::value_type> delta_s_g1;\n                std::vector<typename g1_type::value_type> t_g1;\n                std::vector<typename g2_type::value_type> t_g2;\n                typename g1_type::value_type delta_sum_s_g1;\n                typename g1_type::value_type gamma_inverse_sum_s_g1;\n            };\n\n            template<typename Curve, std::size_t BlockBits>\n            struct private_key<elgamal_verifiable<Curve, BlockBits>> {\n                typedef elgamal_verifiable<Curve, BlockBits> scheme_type;\n                typedef typename Curve::scalar_field_type scalar_field_type;\n\n                friend class decrypt_op<scheme_type>;\n\n                private_key() = default;\n                private_key(const typename scalar_field_type::value_type &rho) : rho(rho) {\n                }\n\n                // private:\n                typename scalar_field_type::value_type rho;\n            };\n\n            template<typename Curve, std::size_t BlockBits>\n            struct generate_keypair_op<elgamal_verifiable<Curve, BlockBits>> {\n                typedef elgamal_verifiable<Curve, BlockBits> scheme_type;\n                typedef typename scheme_type::proof_system_type proof_system_type;\n\n                typedef typename scheme_type::public_key_type public_key_type;\n                typedef typename scheme_type::private_key_type private_key_type;\n                typedef typename scheme_type::verification_key_type verification_key_type;\n                typedef typename scheme_type::keypair_type keypair_type;\n\n                typedef typename Curve::scalar_field_type scalar_field_type;\n                typedef typename Curve::template g1_type<> g1_type;\n                typedef typename Curve::template g2_type<> g2_type;\n\n                struct init_params_type {\n                    const typename proof_system_type::keypair_type &gg_keypair;\n                    std::size_t msg_size;\n                };\n                struct internal_accumulator_type {\n                    const typename proof_system_type::keypair_type &gg_keypair;\n                    std::size_t msg_size;\n                    std::vector<typename scalar_field_type::value_type> rnd;\n                };\n                typedef keypair_type result_type;\n\n                static inline internal_accumulator_type init_accumulator(const init_params_type &init_params) {\n                    // TODO: check\n                    BOOST_ASSERT_MSG(init_params.gg_keypair.second.gamma_ABC_g1.rest.size() > init_params.msg_size,\n                                     \"Array of gammas in vk should be longer than the message.\");\n                    return {init_params.gg_keypair, init_params.msg_size,\n                            std::vector<typename scalar_field_type::value_type> {}};\n                }\n\n                template<typename InputIterator>\n                static inline void update(internal_accumulator_type &acc, InputIterator first, InputIterator last) {\n                    std::move(first, last, std::back_inserter(acc.rnd));\n                }\n\n                template<typename InputRange>\n                static inline void update(internal_accumulator_type &acc, InputRange range) {\n                    update(acc, std::cbegin(range), std::cend(range));\n                }\n\n                static inline result_type process(internal_accumulator_type &acc) {\n                    // TODO: check\n                    BOOST_ASSERT_MSG(acc.rnd.size() >= 3 * acc.msg_size + 2,\n                                     \"Too few numbers in the source of randomness.\");\n                    auto rnd_iter = std::cbegin(acc.rnd);\n\n                    typename scalar_field_type::value_type s_sum = scalar_field_type::value_type::zero();\n\n                    std::vector<typename g1_type::value_type> delta_s_g1;\n                    typename g1_type::value_type delta_sum_s_g1;\n                    typename g1_type::value_type gamma_inverse_sum_s_g1 = acc.gg_keypair.second.gamma_g1;\n\n                    typename scalar_field_type::value_type rho = *rnd_iter++;\n                    typename g2_type::value_type rho_g2 = rho * g2_type::value_type::one();\n                    std::vector<typename g2_type::value_type> rho_sv_g2;\n                    std::vector<typename g2_type::value_type> rho_rhov_g2;\n\n                    std::vector<typename g1_type::value_type> t_g1;\n                    std::vector<typename g2_type::value_type> t_g2;\n\n                    delta_s_g1.reserve(acc.msg_size);\n                    rho_sv_g2.reserve(acc.msg_size);\n                    rho_rhov_g2.reserve(acc.msg_size);\n                    t_g1.reserve(acc.msg_size);\n                    t_g2.reserve(acc.msg_size + 1);\n\n                    typename scalar_field_type::value_type t = *rnd_iter++;\n                    t_g2.emplace_back(t * g2_type::value_type::one());\n                    delta_sum_s_g1 = t * acc.gg_keypair.second.delta_g1;\n\n                    for (std::size_t i = 0; i < acc.msg_size; ++i) {\n                        typename scalar_field_type::value_type s = *rnd_iter++;\n                        typename scalar_field_type::value_type v = *rnd_iter++;\n                        typename scalar_field_type::value_type sv = s * v;\n                        t = *rnd_iter++;\n\n                        delta_s_g1.emplace_back(s * acc.gg_keypair.second.delta_g1);\n                        t_g1.emplace_back(t * acc.gg_keypair.second.gamma_ABC_g1.rest[i]);\n                        t_g2.emplace_back(t * g2_type::value_type::one());\n                        delta_sum_s_g1 = delta_sum_s_g1 + (s * t) * acc.gg_keypair.second.delta_g1;\n                        gamma_inverse_sum_s_g1 = gamma_inverse_sum_s_g1 + s * acc.gg_keypair.second.gamma_g1;\n\n                        rho_sv_g2.emplace_back(sv * g2_type::value_type::one());\n                        rho_rhov_g2.emplace_back(v * rho_g2);\n                    }\n                    gamma_inverse_sum_s_g1 = -gamma_inverse_sum_s_g1;\n\n                    public_key_type pk(acc.gg_keypair.second.delta_g1, delta_s_g1, t_g1, t_g2, delta_sum_s_g1,\n                                       gamma_inverse_sum_s_g1);\n                    private_key_type sk(rho);\n                    verification_key_type vk(rho_g2, rho_sv_g2, rho_rhov_g2);\n\n                    return {pk, sk, vk};\n                }\n            };\n\n            template<typename Curve, std::size_t BlockBits>\n            struct encrypt_op<elgamal_verifiable<Curve, BlockBits>> {\n                typedef elgamal_verifiable<Curve, BlockBits> scheme_type;\n                typedef typename scheme_type::proof_system_type proof_system_type;\n                typedef typename scheme_type::public_key_type public_key_type;\n\n                typedef typename Curve::scalar_field_type scalar_field_type;\n                typedef typename Curve::template g1_type<> g1_type;\n\n                struct init_params_type {\n                    typename scalar_field_type::value_type r;\n                    const public_key_type &pubkey;\n                    const typename proof_system_type::keypair_type &gg_keypair;\n                    // TODO: accumulate primary_input and auxiliary_input\n                    const typename proof_system_type::primary_input_type &primary_input;\n                    const typename proof_system_type::auxiliary_input_type &auxiliary_input;\n                };\n                struct internal_accumulator_type {\n                    std::vector<typename scalar_field_type::value_type> plain_text;\n                    typename scalar_field_type::value_type r;\n                    const public_key_type &pubkey;\n                    const typename proof_system_type::keypair_type &gg_keypair;\n                    const typename proof_system_type::primary_input_type &primary_input;\n                    const typename proof_system_type::auxiliary_input_type &auxiliary_input;\n                };\n                typedef typename scheme_type::cipher_type result_type;\n\n                static inline internal_accumulator_type init_accumulator(const init_params_type &init_params) {\n                    return {std::vector<typename scalar_field_type::value_type> {},\n                            std::move(init_params.r),\n                            init_params.pubkey,\n                            init_params.gg_keypair,\n                            init_params.primary_input,\n                            init_params.auxiliary_input};\n                }\n\n                // TODO: process input data in place\n                // TODO: use marshalling module instead of custom marshalling to process input data\n                template<typename InputIterator>\n                static inline void update(internal_accumulator_type &acc, InputIterator first, InputIterator last) {\n                    std::copy(first, last, std::back_inserter(acc.plain_text));\n                }\n\n                template<typename InputRange>\n                static inline void update(internal_accumulator_type &acc, InputRange range) {\n                    update(acc, std::cbegin(range), std::cend(range));\n                }\n\n                static inline result_type process(internal_accumulator_type &acc) {\n                    // TODO: check\n                    BOOST_ASSERT_MSG(acc.gg_keypair.second.gamma_ABC_g1.rest.size() > acc.plain_text.size(),\n                                     \"Array of gammas in vk should be longer than the plain text.\");\n                    BOOST_ASSERT_MSG(acc.primary_input.size() > acc.plain_text.size(),\n                                     \"Primary input should be longer than plain text.\");\n                    BOOST_ASSERT_MSG(acc.gg_keypair.second.gamma_ABC_g1.rest.size() == acc.primary_input.size(),\n                                     \"Number of gammas should be equal to the primary input size.\");\n                    BOOST_ASSERT_MSG(acc.plain_text.size() == acc.pubkey.delta_s_g1.size(),\n                                     \"Plain text size should be equal to the delta_s array size from pk.\");\n                    BOOST_ASSERT_MSG(acc.plain_text.size() == acc.pubkey.t_g1.size(),\n                                     \"Plain text size should be equal to the t_g1 array size from pk.\");\n                    BOOST_ASSERT_MSG(acc.plain_text.size() == acc.pubkey.t_g2.size() - 1,\n                                     \"Plain text size should be equal to the t_g2 array size from pk.\");\n                    for (std::size_t i = 0; i < acc.plain_text.size(); ++i) {\n                        BOOST_ASSERT_MSG(acc.primary_input[i] == acc.plain_text[i],\n                                         \"Plain text should be a prefix of primary input.\");\n                    }\n\n                    typename result_type::first_type ct_g1;\n                    ct_g1.reserve(acc.plain_text.size() + 2);\n                    ct_g1.emplace_back(acc.r * acc.pubkey.delta_g1);\n\n                    typename g1_type::value_type sum_tm_g1 = acc.r * acc.pubkey.delta_sum_s_g1;\n\n                    for (std::size_t i = 0; i < acc.plain_text.size(); ++i) {\n                        ct_g1.emplace_back(acc.r * acc.pubkey.delta_s_g1[i] +\n                                           acc.plain_text[i] * acc.gg_keypair.second.gamma_ABC_g1.rest[i]);\n                        sum_tm_g1 = sum_tm_g1 + acc.plain_text[i] * acc.pubkey.t_g1[i];\n                    }\n                    ct_g1.emplace_back(sum_tm_g1);\n                    auto proof = zk::prove<proof_system_type>(acc.gg_keypair.first, acc.pubkey, acc.primary_input,\n                                                              acc.auxiliary_input, acc.r);\n\n                    return {ct_g1, proof};\n                }\n            };\n\n            template<typename Curve, std::size_t BlockBits>\n            struct decrypt_op<elgamal_verifiable<Curve, BlockBits>> {\n                typedef elgamal_verifiable<Curve, BlockBits> scheme_type;\n                typedef typename scheme_type::proof_system_type proof_system_type;\n                typedef typename scheme_type::private_key_type private_key_type;\n                typedef typename scheme_type::verification_key_type verification_key_type;\n\n                typedef typename Curve::scalar_field_type scalar_field_type;\n                typedef typename Curve::template g1_type<> g1_type;\n                typedef typename Curve::gt_type gt_type;\n\n                struct init_params_type {\n                    const private_key_type &privkey;\n                    const verification_key_type &vk;\n                    const typename proof_system_type::keypair_type &gg_keypair;\n                };\n                struct internal_accumulator_type {\n                    std::vector<typename g1_type::value_type> cipher_text;\n                    const private_key_type &privkey;\n                    const verification_key_type &vk;\n                    const typename proof_system_type::keypair_type &gg_keypair;\n                };\n                typedef typename scheme_type::decipher_type result_type;\n\n                static inline internal_accumulator_type init_accumulator(const init_params_type &init_params) {\n                    return internal_accumulator_type {std::vector<typename g1_type::value_type> {}, init_params.privkey,\n                                                      init_params.vk, init_params.gg_keypair};\n                }\n\n                // TODO: process input data in place\n                // TODO: use marshalling module instead of custom marshalling to process input data\n                template<typename InputIterator>\n                static inline void update(internal_accumulator_type &acc, InputIterator first, InputIterator last) {\n                    std::copy(first, last, std::back_inserter(acc.cipher_text));\n                }\n\n                template<typename InputRange>\n                static inline void update(internal_accumulator_type &acc, InputRange range) {\n                    update(acc, std::cbegin(range), std::cend(range));\n                }\n\n                static inline result_type process(internal_accumulator_type &acc) {\n                    // TODO: check\n                    BOOST_ASSERT_MSG(\n                        acc.gg_keypair.second.gamma_ABC_g1.rest.size() > acc.cipher_text.size() - 2,\n                        \"Array of gammas in vk should be longer than the cipher text (exclusive of 2 element in CT).\");\n                    BOOST_ASSERT_MSG(acc.cipher_text.size() - 2 == acc.vk.rho_sv_g2.size(),\n                                     \"Cipher text size should be equal to the rho_sv_g2 array size from vk (exclusive \"\n                                     \"of 2 element in CT).\");\n                    BOOST_ASSERT_MSG(acc.cipher_text.size() - 2 == acc.vk.rho_rhov_g2.size(),\n                                     \"Cipher text size should be equal to the rho_rhov_g2 array size from vk \"\n                                     \"(exclusive of 2 element in CT).\");\n                    std::vector<typename scalar_field_type::value_type> m_new;\n                    m_new.reserve(acc.cipher_text.size() - 2);\n\n                    for (size_t j = 1; j < acc.cipher_text.size() - 1; ++j) {\n                        typename gt_type::value_type ci_sk_i =\n                            algebra::pair_reduced<Curve>(acc.cipher_text[j], acc.vk.rho_rhov_g2[j - 1]);\n                        typename gt_type::value_type c0_sk_0 =\n                            algebra::pair_reduced<Curve>(acc.cipher_text[0], acc.vk.rho_sv_g2[j - 1])\n                                .pow(acc.privkey.rho.data);\n                        typename gt_type::value_type dec_tmp = ci_sk_i * c0_sk_0.inversed();\n                        auto discrete_log = gt_type::value_type::one();\n                        typename gt_type::value_type bruteforce = algebra::pair_reduced<Curve>(\n                            acc.gg_keypair.second.gamma_ABC_g1.rest[j - 1], acc.vk.rho_rhov_g2[j - 1]);\n                        std::size_t exp = 0;\n                        bool deciphered = false;\n                        do {\n                            if (dec_tmp == discrete_log) {\n                                m_new.template emplace_back(exp);\n                                deciphered = true;\n                                break;\n                            }\n                            discrete_log = discrete_log * bruteforce;\n                        } while (exp++ < 1 << scheme_type::block_bits);\n                        BOOST_ASSERT_MSG(deciphered, \"Decryption failed.\");\n                    }\n\n                    typename g1_type::value_type verify_c0 = acc.privkey.rho * acc.cipher_text[0];\n\n                    return {m_new, verify_c0};\n                }\n            };\n\n            template<typename Curve, std::size_t BlockBits>\n            struct verify_encryption_op<elgamal_verifiable<Curve, BlockBits>> {\n                typedef elgamal_verifiable<Curve, BlockBits> scheme_type;\n                typedef typename scheme_type::proof_system_type proof_system_type;\n                typedef typename scheme_type::public_key_type public_key_type;\n\n                typedef typename Curve::scalar_field_type scalar_field_type;\n                typedef typename Curve::template g1_type<> g1_type;\n\n                struct init_params_type {\n                    const public_key_type &pubkey;\n                    const typename proof_system_type::verification_key_type &gg_vk;\n                    const typename proof_system_type::proof_type &proof;\n                    const typename proof_system_type::primary_input_type &unencrypted_primary_input;\n                };\n                struct internal_accumulator_type {\n                    const public_key_type &pubkey;\n                    const typename proof_system_type::verification_key_type &gg_vk;\n                    const typename proof_system_type::proof_type &proof;\n                    const typename proof_system_type::primary_input_type &unencrypted_primary_input;\n                    std::vector<typename g1_type::value_type> cipher_text;\n                };\n                typedef bool result_type;\n\n                static inline internal_accumulator_type init_accumulator(const init_params_type &init_params) {\n                    return internal_accumulator_type {init_params.pubkey, init_params.gg_vk, init_params.proof,\n                                                      init_params.unencrypted_primary_input,\n                                                      std::vector<typename g1_type::value_type> {}};\n                }\n\n                // TODO: process input data in place\n                // TODO: use marshalling module instead of custom marshalling to process input data\n                template<typename InputIterator>\n                static inline void update(internal_accumulator_type &acc, InputIterator first, InputIterator last) {\n                    std::copy(first, last, std::back_inserter(acc.cipher_text));\n                }\n\n                template<typename InputRange>\n                static inline void update(internal_accumulator_type &acc, InputRange range) {\n                    update(acc, std::cbegin(range), std::cend(range));\n                }\n\n                static inline result_type process(internal_accumulator_type &acc) {\n                    return zk::verify<proof_system_type>(std::cbegin(acc.cipher_text), std::cend(acc.cipher_text),\n                                                         acc.gg_vk, acc.pubkey, acc.unencrypted_primary_input,\n                                                         acc.proof);\n                }\n            };\n\n            template<typename Curve, std::size_t BlockBits>\n            struct verify_decryption_op<elgamal_verifiable<Curve, BlockBits>> {\n                typedef elgamal_verifiable<Curve, BlockBits> scheme_type;\n                typedef typename scheme_type::proof_system_type proof_system_type;\n                typedef typename scheme_type::public_key_type public_key_type;\n                typedef typename scheme_type::verification_key_type verification_key_type;\n\n                typedef typename Curve::scalar_field_type scalar_field_type;\n                typedef typename Curve::template g1_type<> g1_type;\n                typedef typename Curve::template g2_type<> g2_type;\n                typedef typename Curve::gt_type gt_type;\n\n                struct init_params_type {\n                    const verification_key_type &vk;\n                    const typename proof_system_type::keypair_type &gg_keypair;\n                    const typename g1_type::value_type &proof;\n                };\n                struct internal_accumulator_type {\n                    const verification_key_type &vk;\n                    const typename proof_system_type::keypair_type &gg_keypair;\n                    const typename g1_type::value_type &proof;\n                    std::vector<typename scalar_field_type::value_type> plain_text;\n                    std::vector<typename g1_type::value_type> cipher_text;\n                };\n                typedef bool result_type;\n\n                static inline internal_accumulator_type init_accumulator(const init_params_type &init_params) {\n                    return internal_accumulator_type {init_params.vk, init_params.gg_keypair, init_params.proof,\n                                                      std::vector<typename scalar_field_type::value_type> {},\n                                                      std::vector<typename g1_type::value_type> {}};\n                }\n\n                // TODO: process input data in place\n                // TODO: use marshalling module instead of custom marshalling to process input data\n                template<typename InputIterator>\n                static inline typename std::enable_if<\n                    std::is_same<typename scalar_field_type::value_type,\n                                 typename std::iterator_traits<InputIterator>::value_type>::value>::type\n                    update(internal_accumulator_type &acc, InputIterator first, InputIterator last) {\n                    std::copy(first, last, std::back_inserter(acc.plain_text));\n                }\n\n                template<typename InputIterator>\n                static inline typename std::enable_if<\n                    std::is_same<typename g1_type::value_type,\n                                 typename std::iterator_traits<InputIterator>::value_type>::value>::type\n                    update(internal_accumulator_type &acc, InputIterator first, InputIterator last) {\n                    std::copy(first, last, std::back_inserter(acc.cipher_text));\n                }\n\n                template<typename InputRange>\n                static inline void update(internal_accumulator_type &acc, InputRange range) {\n                    update(acc, std::cbegin(range), std::cend(range));\n                }\n\n                static inline result_type process(internal_accumulator_type &acc) {\n                    BOOST_ASSERT_MSG(\n                        acc.plain_text.size() + 2 == acc.cipher_text.size(),\n                        \"Cipher text size should be equal to the plain text size (exclusive of 2 element in CT).\");\n                    BOOST_ASSERT_MSG(acc.gg_keypair.second.gamma_ABC_g1.rest.size() > acc.plain_text.size(),\n                                     \"Array of gammas in vk should be longer than the plain text.\");\n                    typename gt_type::value_type vm_gt =\n                        algebra::pair_reduced<Curve>(acc.proof, g2_type::value_type::one());\n                    typename gt_type::value_type new_c0_v0_gt =\n                        algebra::pair_reduced<Curve>(acc.cipher_text[0], acc.vk.rho_g2);\n                    bool ans = (vm_gt == new_c0_v0_gt);\n\n                    for (size_t i = 1; i < acc.cipher_text.size() - 1; ++i) {\n                        typename gt_type::value_type ci_v_nj_gt =\n                            algebra::pair_reduced<Curve>(acc.cipher_text[i], acc.vk.rho_rhov_g2[i - 1]);\n                        typename gt_type::value_type v_vj_gt =\n                            algebra::pair_reduced<Curve>(acc.proof, acc.vk.rho_sv_g2[i - 1]);\n                        typename gt_type::value_type verify_tmp = ci_v_nj_gt * v_vj_gt.inversed();\n                        typename gt_type::value_type verify_msg =\n                            algebra::pair_reduced<Curve>(acc.gg_keypair.second.gamma_ABC_g1.rest[i - 1],\n                                                         acc.vk.rho_rhov_g2[i - 1])\n                                .pow(acc.plain_text[i - 1].data);\n                        bool ans_m = (verify_tmp == verify_msg);\n                        ans &= ans_m;\n                    }\n\n                    return ans;\n                }\n            };\n\n            template<typename Curve, std::size_t BlockBits>\n            struct rerandomize_op<elgamal_verifiable<Curve, BlockBits>> {\n                typedef elgamal_verifiable<Curve, BlockBits> scheme_type;\n                typedef typename scheme_type::proof_system_type proof_system_type;\n                typedef typename scheme_type::public_key_type public_key_type;\n\n                typedef typename Curve::scalar_field_type scalar_field_type;\n                typedef typename Curve::template g1_type<> g1_type;\n                typedef typename Curve::template g2_type<> g2_type;\n                typedef typename Curve::gt_type gt_type;\n\n                struct init_params_type {\n                    const public_key_type &pubkey;\n                    const typename proof_system_type::keypair_type &gg_keypair;\n                    const typename proof_system_type::proof_type &proof;\n                };\n                struct internal_accumulator_type {\n                    const public_key_type &pubkey;\n                    const typename proof_system_type::keypair_type &gg_keypair;\n                    const typename proof_system_type::proof_type &proof;\n                    std::vector<typename scalar_field_type::value_type> rnd;\n                    std::vector<typename g1_type::value_type> cipher_text;\n                };\n                typedef typename scheme_type::cipher_type result_type;\n\n                static inline internal_accumulator_type init_accumulator(const init_params_type &init_params) {\n                    return internal_accumulator_type {init_params.pubkey, init_params.gg_keypair, init_params.proof,\n                                                      std::vector<typename scalar_field_type::value_type> {},\n                                                      std::vector<typename g1_type::value_type> {}};\n                }\n\n                // TODO: process input data in place\n                // TODO: use marshalling module instead of custom marshalling to process input data\n                template<typename InputIterator>\n                static inline typename std::enable_if<\n                    std::is_same<typename scalar_field_type::value_type,\n                                 typename std::iterator_traits<InputIterator>::value_type>::value>::type\n                    update(internal_accumulator_type &acc, InputIterator first, InputIterator last) {\n                    std::copy(first, last, std::back_inserter(acc.rnd));\n                }\n\n                template<typename InputIterator>\n                static inline typename std::enable_if<\n                    std::is_same<typename g1_type::value_type,\n                                 typename std::iterator_traits<InputIterator>::value_type>::value>::type\n                    update(internal_accumulator_type &acc, InputIterator first, InputIterator last) {\n                    std::copy(first, last, std::back_inserter(acc.cipher_text));\n                }\n\n                template<typename InputRange>\n                static inline void update(internal_accumulator_type &acc, InputRange range) {\n                    update(acc, std::cbegin(range), std::cend(range));\n                }\n\n                static inline result_type process(internal_accumulator_type &acc) {\n                    BOOST_ASSERT_MSG(acc.rnd.size() >= 3, \"Too few numbers in the source of randomness (at least 3).\");\n                    BOOST_ASSERT_MSG(acc.pubkey.delta_s_g1.size() == acc.cipher_text.size() - 2,\n                                     \"Cipher text size should be equal to the delta_s_g1 array size from pk (exclusive \"\n                                     \"of 2 element in CT).\");\n                    BOOST_ASSERT_MSG(acc.pubkey.t_g1.size() == acc.cipher_text.size() - 2,\n                                     \"Cipher text size should be equal to the t_g1 array size from pk (exclusive of 2 \"\n                                     \"element in CT).\");\n                    BOOST_ASSERT_MSG(acc.pubkey.t_g2.size() - 1 == acc.cipher_text.size() - 2,\n                                     \"Cipher text size should be equal to the t_g2 array size from pk (exclusive of 2 \"\n                                     \"element in CT).\");\n                    std::vector<typename g1_type::value_type> ct_g1;\n                    ct_g1.reserve(acc.cipher_text.size());\n\n                    auto rnd_it = std::cbegin(acc.rnd);\n                    typename scalar_field_type::value_type r = *rnd_it++;\n                    typename scalar_field_type::value_type z1 = *rnd_it++;\n                    typename scalar_field_type::value_type z2 = *rnd_it++;\n\n                    typename scalar_field_type::value_type z1_inverse = z1.inversed();\n\n                    ct_g1.emplace_back(acc.cipher_text.front() + r * acc.pubkey.delta_g1);\n                    for (size_t i = 1; i < acc.cipher_text.size() - 1; ++i) {\n                        ct_g1.emplace_back(acc.cipher_text[i] + r * acc.pubkey.delta_s_g1[i - 1]);\n                    }\n                    ct_g1.emplace_back(acc.cipher_text.back() + r * acc.pubkey.delta_sum_s_g1);\n\n                    typename g1_type::value_type g1_A = z1 * acc.proof.g_A;\n                    typename g2_type::value_type g2_B =\n                        z1_inverse * acc.proof.g_B + z2 * acc.gg_keypair.second.delta_g2;\n                    typename g1_type::value_type g1_C =\n                        acc.proof.g_C + z2 * g1_A + r * acc.pubkey.gamma_inverse_sum_s_g1;\n\n                    return std::make_pair(ct_g1, typename proof_system_type::proof_type {\n                                                     std::move(g1_A), std::move(g2_B), std::move(g1_C)});\n                }\n            };\n        }    // namespace pubkey\n    }        // namespace crypto3\n}    // namespace nil\n\n#endif\n", "meta": {"hexsha": "8ad3d21cb6462358c259844f8ec857bf981a14af", "size": 38507, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/nil/crypto3/pubkey/elgamal_verifiable.hpp", "max_stars_repo_name": "NilFoundation/pubkey", "max_stars_repo_head_hexsha": "3b146d6ed14e127be57895a08846c9e1eea4eade", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/nil/crypto3/pubkey/elgamal_verifiable.hpp", "max_issues_repo_name": "NilFoundation/pubkey", "max_issues_repo_head_hexsha": "3b146d6ed14e127be57895a08846c9e1eea4eade", "max_issues_repo_licenses": ["MIT"], "max_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/pubkey/elgamal_verifiable.hpp", "max_forks_repo_name": "NilFoundation/pubkey", "max_forks_repo_head_hexsha": "3b146d6ed14e127be57895a08846c9e1eea4eade", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 57.1320474777, "max_line_length": 120, "alphanum_fraction": 0.5688576103, "num_tokens": 7534, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.746138993030751, "lm_q2_score": 0.44167300566462553, "lm_q1q2_score": 0.3295494516954689}}
{"text": "#include <Columns/ColumnNullable.h>\n#include <Columns/ColumnString.h>\n#include <Columns/ColumnTuple.h>\n#include <Columns/ColumnsNumber.h>\n#include <Columns/IColumn.h>\n#include <DataTypes/DataTypeTuple.h>\n#include <DataTypes/DataTypesNumber.h>\n#include <Functions/FunctionFactory.h>\n#include <Functions/FunctionHelpers.h>\n#include <Functions/IFunction.h>\n#include <Functions/castTypeToEither.h>\n#include <Interpreters/castColumn.h>\n#include <boost/math/distributions/normal.hpp>\n#include <Common/typeid_cast.h>\n\n\nnamespace DB\n{\n\nnamespace ErrorCodes\n{\n    extern const int ILLEGAL_TYPE_OF_ARGUMENT;\n    extern const int BAD_ARGUMENTS;\n}\n\n\nclass FunctionTwoSampleProportionsZTest : public IFunction\n{\npublic:\n    static constexpr auto POOLED = \"pooled\";\n    static constexpr auto UNPOOLED = \"unpooled\";\n\n    static constexpr auto name = \"proportionsZTest\";\n\n    static FunctionPtr create(ContextPtr) { return std::make_shared<FunctionTwoSampleProportionsZTest>(); }\n\n    String getName() const override { return name; }\n\n    size_t getNumberOfArguments() const override { return 6; }\n    ColumnNumbers getArgumentsThatAreAlwaysConstant() const override { return {5}; }\n\n    bool useDefaultImplementationForNulls() const override { return false; }\n    bool useDefaultImplementationForConstants() const override { return true; }\n    bool isSuitableForShortCircuitArgumentsExecution(const DataTypesWithConstInfo & /*arguments*/) const override { return false; }\n\n    static DataTypePtr getReturnType()\n    {\n        auto float_data_type = std::make_shared<DataTypeNumber<Float64>>();\n        DataTypes types(4, float_data_type);\n\n        Strings names{\"z_statistic\", \"p_value\", \"confidence_interval_low\", \"confidence_interval_high\"};\n\n        return std::make_shared<DataTypeTuple>(std::move(types), std::move(names));\n    }\n\n    DataTypePtr getReturnTypeImpl(const ColumnsWithTypeAndName & arguments) const override\n    {\n        for (size_t i = 0; i < 4; ++i)\n        {\n            if (!isUnsignedInteger(arguments[i].type))\n            {\n                throw Exception(\n                    ErrorCodes::ILLEGAL_TYPE_OF_ARGUMENT,\n                    \"The {}th Argument of function {} must be an unsigned integer.\",\n                    i + 1,\n                    getName());\n            }\n        }\n\n        if (!isFloat(arguments[4].type))\n        {\n            throw Exception{ErrorCodes::ILLEGAL_TYPE_OF_ARGUMENT,\n                \"The fifth argument {} of function {} should be a float,\",\n                arguments[4].type->getName(),\n                getName()};\n        }\n\n        /// There is an additional check for constancy in ExecuteImpl\n        if (!isString(arguments[5].type) || !arguments[5].column)\n        {\n            throw Exception{ErrorCodes::ILLEGAL_TYPE_OF_ARGUMENT,\n                \"The sixth argument {} of function {} should be a constant string\",\n                arguments[5].type->getName(),\n                getName()};\n        }\n\n        return getReturnType();\n    }\n\n\n    ColumnPtr executeImpl(const ColumnsWithTypeAndName & const_arguments, const DataTypePtr &, size_t input_rows_count) const override\n    {\n        auto arguments = const_arguments;\n        /// Only last argument have to be constant\n        for (size_t i = 0; i < 5; ++i)\n            arguments[i].column = arguments[i].column->convertToFullColumnIfConst();\n\n        static const auto uint64_data_type = std::make_shared<DataTypeNumber<UInt64>>();\n\n        auto column_successes_x = castColumnAccurate(arguments[0], uint64_data_type);\n        const auto & data_successes_x = checkAndGetColumn<ColumnVector<UInt64>>(column_successes_x.get())->getData();\n\n        auto column_successes_y = castColumnAccurate(arguments[1], uint64_data_type);\n        const auto & data_successes_y = checkAndGetColumn<ColumnVector<UInt64>>(column_successes_y.get())->getData();\n\n        auto column_trials_x = castColumnAccurate(arguments[2], uint64_data_type);\n        const auto & data_trials_x = checkAndGetColumn<ColumnVector<UInt64>>(column_trials_x.get())->getData();\n\n        auto column_trials_y = castColumnAccurate(arguments[3], uint64_data_type);\n        const auto & data_trials_y = checkAndGetColumn<ColumnVector<UInt64>>(column_trials_y.get())->getData();\n\n        static const auto float64_data_type = std::make_shared<DataTypeNumber<Float64>>();\n\n        auto column_confidence_level = castColumnAccurate(arguments[4], float64_data_type);\n        const auto & data_confidence_level = checkAndGetColumn<ColumnVector<Float64>>(column_confidence_level.get())->getData();\n\n        String usevar = checkAndGetColumnConst<ColumnString>(arguments[5].column.get())->getValue<String>();\n\n        if (usevar != UNPOOLED && usevar != POOLED)\n            throw Exception{ErrorCodes::BAD_ARGUMENTS,\n                \"The sixth argument {} of function {} must be equal to `pooled` or `unpooled`\",\n                arguments[5].type->getName(),\n                getName()};\n\n        const bool is_unpooled = (usevar == UNPOOLED);\n\n        auto res_z_statistic = ColumnFloat64::create();\n        auto & data_z_statistic = res_z_statistic->getData();\n        data_z_statistic.reserve(input_rows_count);\n\n        auto res_p_value = ColumnFloat64::create();\n        auto & data_p_value = res_p_value->getData();\n        data_p_value.reserve(input_rows_count);\n\n        auto res_ci_lower = ColumnFloat64::create();\n        auto & data_ci_lower = res_ci_lower->getData();\n        data_ci_lower.reserve(input_rows_count);\n\n        auto res_ci_upper = ColumnFloat64::create();\n        auto & data_ci_upper = res_ci_upper->getData();\n        data_ci_upper.reserve(input_rows_count);\n\n        auto insert_values_into_result = [&data_z_statistic, &data_p_value, &data_ci_lower, &data_ci_upper](\n                                             Float64 z_stat, Float64 p_value, Float64 lower, Float64 upper)\n        {\n            data_z_statistic.emplace_back(z_stat);\n            data_p_value.emplace_back(p_value);\n            data_ci_lower.emplace_back(lower);\n            data_ci_upper.emplace_back(upper);\n        };\n\n        static constexpr Float64 nan = std::numeric_limits<Float64>::quiet_NaN();\n\n        boost::math::normal_distribution<> nd(0.0, 1.0);\n\n        for (size_t row_num = 0; row_num < input_rows_count; ++row_num)\n        {\n            const UInt64 successes_x = data_successes_x[row_num];\n            const UInt64 successes_y = data_successes_y[row_num];\n            const UInt64 trials_x = data_trials_x[row_num];\n            const UInt64 trials_y = data_trials_y[row_num];\n            const Float64 confidence_level = data_confidence_level[row_num];\n\n            const Float64 props_x = static_cast<Float64>(successes_x) / trials_x;\n            const Float64 props_y = static_cast<Float64>(successes_y) / trials_y;\n            const Float64 diff = props_x - props_y;\n            const UInt64 trials_total = trials_x + trials_y;\n\n            if (successes_x == 0 || successes_y == 0 || successes_x > trials_x || successes_y > trials_y || trials_total == 0\n                || !std::isfinite(confidence_level) || confidence_level < 0.0 || confidence_level > 1.0)\n            {\n                insert_values_into_result(nan, nan, nan, nan);\n                continue;\n            }\n\n            Float64 se = std::sqrt(props_x * (1.0 - props_x) / trials_x + props_y * (1.0 - props_y) / trials_y);\n\n            /// z-statistics\n            /// z = \\frac{ \\bar{p_{1}} - \\bar{p_{2}} }{ \\sqrt{ \\frac{ \\bar{p_{1}} \\left ( 1 - \\bar{p_{1}} \\right ) }{ n_{1} } \\frac{ \\bar{p_{2}} \\left ( 1 - \\bar{p_{2}} \\right ) }{ n_{2} } } }\n            Float64 zstat;\n            if (is_unpooled)\n            {\n                zstat = (props_x - props_y) / se;\n            }\n            else\n            {\n                UInt64 successes_total = successes_x + successes_y;\n                Float64 p_pooled = static_cast<Float64>(successes_total) / trials_total;\n                Float64 trials_fact = 1.0 / trials_x + 1.0 / trials_y;\n                zstat = diff / std::sqrt(p_pooled * (1.0 - p_pooled) * trials_fact);\n            }\n\n            if (!std::isfinite(zstat))\n            {\n                insert_values_into_result(nan, nan, nan, nan);\n                continue;\n            }\n\n            // pvalue\n            Float64 pvalue = 0;\n            Float64 one_side = 1 - boost::math::cdf(nd, std::abs(zstat));\n            pvalue = one_side * 2;\n\n            // Confidence intervals\n            Float64 d = props_x - props_y;\n            Float64 z = -boost::math::quantile(nd, (1.0 - confidence_level) / 2.0);\n            Float64 dist = z * se;\n            Float64 ci_low = d - dist;\n            Float64 ci_high = d + dist;\n\n            insert_values_into_result(zstat, pvalue, ci_low, ci_high);\n        }\n\n        return ColumnTuple::create(\n            Columns{std::move(res_z_statistic), std::move(res_p_value), std::move(res_ci_lower), std::move(res_ci_upper)});\n    }\n};\n\n\nvoid registerFunctionZTest(FunctionFactory & factory)\n{\n    factory.registerFunction<FunctionTwoSampleProportionsZTest>();\n}\n\n}\n", "meta": {"hexsha": "c80b92960e9a5e9a2582551e6999525b23c99c7e", "size": 9068, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Functions/ztest.cpp", "max_stars_repo_name": "chalice19/ClickHouse", "max_stars_repo_head_hexsha": "2f38e7bc5c2113935ab86260439bb543a1737291", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 8629.0, "max_stars_repo_stars_event_min_datetime": "2016-06-14T21:03:01.000Z", "max_stars_repo_stars_event_max_datetime": "2019-09-23T07:46:38.000Z", "max_issues_repo_path": "src/Functions/ztest.cpp", "max_issues_repo_name": "chalice19/ClickHouse", "max_issues_repo_head_hexsha": "2f38e7bc5c2113935ab86260439bb543a1737291", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 4335.0, "max_issues_repo_issues_event_min_datetime": "2016-06-15T12:58:31.000Z", "max_issues_repo_issues_event_max_datetime": "2019-09-23T11:18:43.000Z", "max_forks_repo_path": "src/Functions/ztest.cpp", "max_forks_repo_name": "chalice19/ClickHouse", "max_forks_repo_head_hexsha": "2f38e7bc5c2113935ab86260439bb543a1737291", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1700.0, "max_forks_repo_forks_event_min_datetime": "2016-06-15T09:25:11.000Z", "max_forks_repo_forks_event_max_datetime": "2019-09-23T11:16:38.000Z", "avg_line_length": 40.1238938053, "max_line_length": 192, "alphanum_fraction": 0.6328848699, "num_tokens": 2099, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.752012562644147, "lm_q2_score": 0.43782349911420193, "lm_q1q2_score": 0.3292487715546984}}
{"text": "/* \n * File:   HmcSampler.cpp\n * Author: aripakman\n * \n * Created on July 4, 2012, 10:44 AM\n */\n\n#define _USE_MATH_DEFINES   // for the constant M_PI\n//#include <cstdlib>\n#include <cmath>\n#include <tr1/random>\n#include <Eigen/Dense>\n#include <magnet/math/quartic.hpp>\n\n#include \"HmcSampler.h\"\n\nusing namespace std;\nusing namespace std::tr1;\nusing namespace magnet::math;\n\n\nconst double HmcSampler::min_t = 0.00001;\n\nHmcSampler::HmcSampler(const int & d, const int & seed ) {\ndim=d;    \n//eng1.seed(static_cast<unsigned int >(time(NULL)));\neng1.seed(seed);\nud= uniform_real<>(0,M_PI);\n}   \n\n\n\nvoid HmcSampler::setInitialValue(const VectorXd & initial_value){                 \n   // double check =_verifyConstraints( initial_value );\n  /*  if (check <0) {\n        cout << \"Initial condition out of constraint!\" << endl;\n        exit(1);\n    } else */\n            lastSample = initial_value;\n    }\n\n\n\nMatrixXd HmcSampler::sampleNext(bool returnTrace ) {  \n\n    MatrixXd tracePoints = MatrixXd(dim,0);   //this matrix will only be filled if(returnTrace)\n\n    double T = ud(eng1);        // sample how much time T to move\n    VectorXd b = lastSample;\n    VectorXd a = VectorXd(dim);   // initial velocity \n\n    while(2){\n        \n        double velsign =0; \n        for (int i =0; i<dim; i++)     // Sample new initial velocity  \n        {  a(i)=  nd(eng1);            }\n\n        double tt=T;   // tt is the time left to move \n        double t1;\n        double t2;\n        int cn1,cn2; //constraint number\n\n\n        bool first_bounce = true;    // for the first move, we do not fear that a small t1 or t2 is due to being in the boundary from the previous bounce.\n        while (1){            \n            \n            t1=0; \n            if (!linearConstraints.empty())\n                    _getNextLinearHitTime(a,b,t1,cn1); \n            \n            t2=0;\n            if (!quadraticConstraints.empty() )\n                    {   _getNextQuadraticHitTime(a,b,t2,cn2, first_bounce);                        \n                        first_bounce=false;}\n\n            double t =t1;     // how much time to move. if t==0, move tt \n            bool linear_hit = true;\n            if (t2>0 && (t1==0 || t2<t1 )){\n                t=t2;\n                linear_hit = false;\n            }\n\n            if (t==0 || tt < t){                 // if no wall to be hit (t==0) or not enough time left to hit the wall (tt<t2) \n                break;\n            }\n            else{            \n                if (returnTrace){\n                    _updateTrace(a,b,t,tracePoints);\n                }\n\n                tt = tt-t;\n                VectorXd new_b   = sin(t)*a + cos(t)*b;   // hit location \n                VectorXd hit_vel = cos(t)*a - sin(t)*b;   // hit velocity\n                b = new_b;            \n           \n\n                // reflect the velocity and verify that it points in the right direction\n    \n                if (!linear_hit){\n                    QuadraticConstraint qc = quadraticConstraints[cn2];\n                    VectorXd nabla = 2* ((qc.A)*b) + qc.B;            \n                    double alpha = (nabla.dot(hit_vel))/(nabla.dot(nabla));\n                    a = hit_vel - 2*alpha*nabla;                  // reflected velocity    \n                    velsign = a.dot(nabla);\n                }\n                else {                \n                    LinearConstraint ql = linearConstraints[cn1];\n                    double f2 = ((ql.f).dot((ql.f)));\n                    double alpha = ((ql.f).dot(hit_vel))/f2;\n                    a = hit_vel - 2*alpha*(ql.f);                  // reflected velocity                                         \n                    velsign = a.dot((ql.f));\n                }\n                if (velsign <0 ) break ;    //get out of while(1). resample the velocity and start again. this occurs rarely, due to numerical instabilities\n            }\n\n        } //while(1)\n\n        if (velsign<0) {/* cout << \"wrong velocity \" << endl; */  continue;}    // go to beginning of while(2)\n        \n        VectorXd bb =  sin(tt)*a + cos(tt)*b;             //make last move of time tt without hitting walls  \n\n        double check = _verifyConstraints( bb);\n        if (check >= 0){     //verify that we don't violate the constraints due to a numerical instability\n            lastSample = bb;      \n            if (returnTrace){\n                _updateTrace(a,b,tt,tracePoints);\n                return tracePoints.transpose();          \n\n            } else return lastSample.transpose();\n        }\n       // at this point we have check<0, so we violated constraints: resample. \n\n    } // while(2)\n}\n\n\n\nvoid HmcSampler::addLinearConstraint(const VectorXd & f, const double & g){\n    LinearConstraint newConstraint;\n    newConstraint.f =f;\n    newConstraint.g =g;\n    linearConstraints.push_back(newConstraint);\n}\nvoid HmcSampler::addQuadraticConstraint(const MatrixXd & A, const VectorXd & B, const double & C){\n    QuadraticConstraint newConstraint;\n    newConstraint.A =A;\n    newConstraint.B =B;\n    newConstraint.C =C;\n    quadraticConstraints.push_back(newConstraint);\n    \n}\n\nvoid HmcSampler::_getNextLinearHitTime(const VectorXd & a, const VectorXd & b, double & hit_time, int & cn ){\n    hit_time=0;\n    \n    for (int i=0; i != linearConstraints.size(); i++ ){\n        LinearConstraint lc = linearConstraints[i];\n        double fa = (lc.f).dot(a);\n        double fb = (lc.f).dot(b);\n        double u = sqrt(fa*fa + fb*fb);\n        if (u>lc.g && u>-lc.g){\n                double phi =atan2(-fa,fb);      //     -pi < phi < pi\n                double t1 = acos(-lc.g/u)-phi;  //     -pi < t1 < 2*pi\n                \n                \n                if (t1<0) t1 += 2*M_PI;                //  0 < t1 < 2*pi                  \n                if (abs(t1) < min_t ) t1=0;    \n                else if (abs(t1-2*M_PI) < min_t ) t1=0;                                            \n                \n                \n                double t2 = -t1-2*phi;             //  -4*pi < t2 < 3*pi\n                if (t2<0) t2 += 2*M_PI;                 //-2*pi < t2 < 2*pi\n                if (t2<0) t2 += 2*M_PI;                 //0 < t2 < 2*pi\n                \n                if (abs(t2) < min_t ) t2=0;    \n                else if (abs(t2-2*M_PI) < min_t ) t2=0;                            \n                \n                \n                double t=t1;                \n                if (t1==0) t = t2;\n                else if (t2==0) t = t1;\n                else t=(t1<t2?t1:t2);\n                \n                if  (t> min_t  && (hit_time == 0 || t < hit_time)){\n                    hit_time=t;\n                    cn =i;                    \n                }            \n        }       \n    }        \n}\n\nvoid HmcSampler::_getNextQuadraticHitTime(const VectorXd & a, const VectorXd & b, double & hit_time, int & cn , const bool first_bounce ){\n        hit_time=0;\n  \n        double mint;\n        if (first_bounce) {mint=0;}\n        else {mint=min_t;}\n    \n    for (int i=0; i != quadraticConstraints.size(); i++ ){\n        \n        QuadraticConstraint qc = quadraticConstraints[i];\n        double q1= - ((a.transpose())*(qc.A))*a;\n        q1 = q1 + ((b.transpose())*(qc.A))*b;\n        double q2= (qc.B).dot(b);\n        double q3= qc.C + a.transpose()*(qc.A)*a;\n        double q4= 2*b.transpose()*(qc.A)*a;\n        double q5= (qc.B).dot(a);\n\n        double r4 = q1*q1 + q4*q4;\n        double r3 = 2*q1*q2 + 2*q4*q5;\n        double r2 = q2*q2 + 2*q1*q3 + q5*q5 -q4*q4;\n        double r1 = 2*q2*q3 - 2*q4*q5;\n        double r0=  q3*q3 - q5*q5;\n\n        double roots[]={0,0,0,0};\n        double aa = r3/r4;\n        double bb = r2/r4;\n        double cc = r1/r4;\n        double dd = r0/r4;\n\n        //Solve quartics of the form x^4 + aa x^3 + bb x^2 + cc x + dd ==0\n        int sols = quarticSolve(aa, bb, cc, dd, roots[0], roots[1],  roots[2],  roots[3]);\n        for (int j=0; j<sols; j++){\n            double r = roots[j];\n            if (abs(r) <=1 ){               \n                double l1 = q1*r*r + q2*r + q3;\n                double l2 = -sqrt(1-r*r)*(q4*r + q5); \n                if (l1/l2 > 0){\n                    double t = acos(r);\n                    if (   t> mint      && (hit_time == 0 || t < hit_time)){\n                       hit_time=t;\n                       cn=i;                                          \n                    }                    \n                }\n            }            \n        }                \n    }    \n    \n    \n}\n\n\n\n\ndouble HmcSampler::_verifyConstraints(const VectorXd & b){\n    double r =0;\n    \n    for (int i=0; i != quadraticConstraints.size(); i++ ){       \n        QuadraticConstraint qc = quadraticConstraints[i];\n        double check = ((b.transpose())*(qc.A))*b + (qc.B).dot(b) + qc.C;\n        if (i==0 || check < r) {\n            r = check;\n        }\n    }\n\n    for (int i=0; i != linearConstraints.size(); i++ ){       \n    LinearConstraint lc = linearConstraints[i];\n    double check = (lc.f).dot(b) + lc.g;\n    if (i==0 || check < r) {\n        r = check;\n    }\n    }\n    \n    \n    return r;\n}\n\nvoid HmcSampler::_updateTrace( VectorXd const & a,  VectorXd const & b, double const & t, MatrixXd & tracePoints){\n    double const stepsize = .01;\n    int steps = t/stepsize;\n    \n    int c = tracePoints.cols();\n    tracePoints.conservativeResize(NoChange, c+steps+1);\n    for (int i=0; i<steps; i++){\n        VectorXd bb= sin(i*stepsize)*a + cos(i*stepsize)*b;\n//      cout << bb.transpose() << endl;\n        tracePoints.col(c+i) = bb;                    \n    }\n        VectorXd bb= sin(t)*a + cos(t)*b;\n        tracePoints.col(c+steps) = bb;\n}\n", "meta": {"hexsha": "7af0ce032910b62980082403ad042deabdc010a8", "size": 9627, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "selectinf/src_C/HmcSampler.cpp", "max_stars_repo_name": "TianXie1999/selective-inference", "max_stars_repo_head_hexsha": "ca02bbd84af5f5597944c75bde8337db9c69066a", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 51.0, "max_stars_repo_stars_event_min_datetime": "2016-03-31T16:34:15.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-16T04:32:58.000Z", "max_issues_repo_path": "selectinf/src_C/HmcSampler.cpp", "max_issues_repo_name": "TianXie1999/selective-inference", "max_issues_repo_head_hexsha": "ca02bbd84af5f5597944c75bde8337db9c69066a", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 11.0, "max_issues_repo_issues_event_min_datetime": "2016-04-07T00:19:58.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-03T18:31:14.000Z", "max_forks_repo_path": "selectinf/src_C/HmcSampler.cpp", "max_forks_repo_name": "TianXie1999/selective-inference", "max_forks_repo_head_hexsha": "ca02bbd84af5f5597944c75bde8337db9c69066a", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 14.0, "max_forks_repo_forks_event_min_datetime": "2015-10-28T17:29:05.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-16T21:04:30.000Z", "avg_line_length": 34.1382978723, "max_line_length": 156, "alphanum_fraction": 0.4677469617, "num_tokens": 2511, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6688802735722128, "lm_q2_score": 0.49218813572079556, "lm_q1q2_score": 0.32921493486992315}}
{"text": "#ifndef KANOOTH_NUMBERS_BOOST_INTEGER_HPP\n#define KANOOTH_NUMBERS_BOOST_INTEGER_HPP\n\n#include <boost/multiprecision/number.hpp>\n#include <boost/multiprecision/detail/integer_ops.hpp>\n#include <boost/multiprecision/detail/digits.hpp>\n#include <boost/mpl/contains.hpp>\n#include <boost/cstdint.hpp>\n#include <limits>\n\n#include <kanooth/numbers/integer_base.hpp>\n#include <kanooth/numbers/natural_number.hpp>\n\nnamespace boost {\nnamespace multiprecision {\nnamespace backends {\n\ntemplate <typename N>\nstruct kanooth_integer;\n\n} // namespace backends\n\ntemplate <typename N>\nstruct number_category<backends::kanooth_integer<N> > : public mpl::int_<number_kind_integer> {};\n\nnamespace backends {\n\ntemplate <typename N>\nclass kanooth_integer : public kanooth::numbers::integer_base<N>\n{\npublic:\n    // needed by front-end\n    typedef mpl::list<long>          signed_types;\n    typedef mpl::list<unsigned long> unsigned_types;\n    typedef mpl::list<>              float_types;\n\n    template <typename T, typename R>\n    struct if_supported_int\n        : public enable_if<mpl::or_<mpl::contains<unsigned_types, T>,\n                                    mpl::contains<signed_types, T> >, R> {};\n\n    kanooth_integer() : base_type() {}\n    kanooth_integer(long v) : base_type(v) {}\n    kanooth_integer(unsigned long v) : base_type(v) {}\n    kanooth_integer(const char* s) : base_type(s) {}\nprivate:\n    typedef kanooth::numbers::integer_base<N> base_type;\n};\n\ntemplate <typename N>\ninline bool eval_is_zero(const kanooth_integer<N>& val)\n{\n    return val.is_zero();\n}\n\ntemplate <typename N>\ninline void eval_add(kanooth_integer<N>& r, const kanooth_integer<N>& a)\n{\n    r.add(r, a);\n}\n\ntemplate <typename N, typename T>\ninline typename kanooth_integer<N>::template if_supported_int<T, void>::type\neval_add(kanooth_integer<N>& r, T a)\n{\n    r.add(r, a);\n}\n\ntemplate <typename N>\ninline void eval_add(kanooth_integer<N>& r, const kanooth_integer<N>& a, const kanooth_integer<N>& b)\n{\n    r.add(a, b);\n}\n\ntemplate <typename N, typename T>\ninline typename kanooth_integer<N>::template if_supported_int<T, void>::type\neval_add(kanooth_integer<N>& r, const kanooth_integer<N>& a, T b)\n{\n    r.add(a, b);\n}\n\ntemplate <typename N>\ninline void eval_subtract(kanooth_integer<N>& r, const kanooth_integer<N>& a)\n{\n    r.subtract(r, a);\n}\n\ntemplate <typename N, typename T>\ninline typename kanooth_integer<N>::template if_supported_int<T, void>::type\neval_subtract(kanooth_integer<N>& r, T a)\n{\n    r.subtract(r, a);\n}\n\ntemplate <typename N>\ninline void eval_subtract(kanooth_integer<N>& r, const kanooth_integer<N>& a, const kanooth_integer<N>& b)\n{\n    r.subtract(a, b);\n}\n\ntemplate <typename N, typename T>\ninline typename kanooth_integer<N>::template if_supported_int<T, void>::type\neval_subtract(kanooth_integer<N>& r, const kanooth_integer<N>& a, T b)\n{\n    r.subtract(a, b);\n}\n\ntemplate <typename N>\ninline void eval_multiply(kanooth_integer<N>& r, const kanooth_integer<N>& a)\n{\n    r.multiply(r, a);\n}\n\ntemplate <typename N, typename T>\ninline typename kanooth_integer<N>::template if_supported_int<T, void>::type\neval_multiply(kanooth_integer<N>& r, T a)\n{\n    r.multiply(r, a);\n}\n\ntemplate <typename N>\ninline void eval_multiply(kanooth_integer<N>& r, const kanooth_integer<N>& a, const kanooth_integer<N>& b)\n{\n    r.multiply(a, b);\n}\n\ntemplate <typename N, typename T>\ninline typename kanooth_integer<N>::template if_supported_int<T, void>::type\neval_multiply(kanooth_integer<N>& r, const kanooth_integer<N>& a, T b)\n{\n    r.multiply(a, b);\n}\n\ntemplate <typename N>\ninline void eval_divide(kanooth_integer<N>& r, const kanooth_integer<N>& a)\n{\n    r.divide_truncate(r, a);\n}\n\ntemplate <typename N, typename T>\ninline typename kanooth_integer<N>::template if_supported_int<T, void>::type\neval_divide(kanooth_integer<N>& r, T a)\n{\n    r.divide_truncate(r, a);\n}\n\ntemplate <typename N>\ninline void eval_divide(kanooth_integer<N>& r, const kanooth_integer<N>& a, const kanooth_integer<N>& b)\n{\n    r.divide_truncate(a, b);\n}\n\ntemplate <typename N, typename T>\ninline typename kanooth_integer<N>::template if_supported_int<T, void>::type\neval_divide(kanooth_integer<N>& r, const kanooth_integer<N>& a, T b)\n{\n    r.divide_truncate(a, b);\n}\n\ntemplate <typename N>\ninline void eval_modulus(kanooth_integer<N>& r, const kanooth_integer<N>& a)\n{\n    r.modulus_truncate(r, a);\n}\n\ntemplate <typename N, typename T>\ninline typename kanooth_integer<N>::template if_supported_int<T, void>::type\neval_modulus(kanooth_integer<N>& r, T a)\n{\n    r.modulus_truncate(r, a);\n}\n\ntemplate <typename N>\ninline void eval_modulus(kanooth_integer<N>& r, const kanooth_integer<N>& a, const kanooth_integer<N>& b)\n{\n    r.modulus_truncate(a, b);\n}\n\ntemplate <typename N, typename T>\ninline typename kanooth_integer<N>::template if_supported_int<T, void>::type\neval_modulus(kanooth_integer<N>& r, const kanooth_integer<N>& a, T b)\n{\n    r.modulus_truncate(a, b);\n}\n\ntemplate <typename N>\ninline void eval_qr(const kanooth_integer<N>& x, const kanooth_integer<N>& y, kanooth_integer<N>& q, kanooth_integer<N>& r)\n{\n    kanooth_integer<N>::quotrem(q, r, x, y);\n}\n\ntemplate <typename N>\ninline void eval_gcd(kanooth_integer<N>& result, const kanooth_integer<N>& a, const kanooth_integer<N>& b)\n{\n    result.gcd(a, b);\n}\n\ntemplate <typename N, class Integer>\ninline typename enable_if<is_unsigned<Integer>, Integer>::type eval_integer_modulus(const kanooth_integer<N>& x, Integer val)\n{\n    if ((sizeof(Integer) <= sizeof(long)) || (val <= (std::numeric_limits<unsigned long>::max)())) {\n        return kanooth_integer<N>::integer_modulus(x, static_cast<unsigned long>(val));\n    } else {\n        return default_ops::eval_integer_modulus(x, val);\n    }\n}\n\ntemplate <typename N, class Integer>\ninline typename enable_if<is_signed<Integer>, Integer>::type eval_integer_modulus(const kanooth_integer<N>& x, Integer val)\n{\n   typedef typename make_unsigned<Integer>::type unsigned_type;\n   return eval_integer_modulus(x, static_cast<unsigned_type>(std::abs(val)));\n}\n\ntemplate <typename N>\ninline void eval_bitwise_and(kanooth_integer<N>& result, const kanooth_integer<N>& v)\n{\n   result.bitwise_and(result, v);\n}\n\ntemplate <typename N>\ninline void eval_bitwise_or(kanooth_integer<N>& result, const kanooth_integer<N>& v)\n{\n   result.bitwise_or(result, v);\n}\n\ntemplate <typename N>\ninline void eval_bitwise_xor(kanooth_integer<N>& result, const kanooth_integer<N>& v)\n{\n   result.bitwise_xor(result, v);\n}\n\ntemplate <typename N>\ninline void eval_bitwise_and(kanooth_integer<N>& result, const kanooth_integer<N>& u, const kanooth_integer<N>& v)\n{\n   result.bitwise_and(u, v);\n}\n\ntemplate <typename N>\ninline void eval_bitwise_or(kanooth_integer<N>& result, const kanooth_integer<N>& u, const kanooth_integer<N>& v)\n{\n   result.bitwise_or(u, v);\n}\n\ntemplate <typename N>\ninline void eval_bitwise_xor(kanooth_integer<N>& result, const kanooth_integer<N>& u, const kanooth_integer<N>& v)\n{\n   result.bitwise_xor(u, v);\n}\n\ntemplate <typename N>\ninline void eval_left_shift(kanooth_integer<N>& r, unsigned long v)\n{\n   r.left_shift(r, v);\n}\n\ntemplate <typename N>\ninline void eval_left_shift(kanooth_integer<N>& r, kanooth_integer<N>& u, unsigned long v)\n{\n   r.left_shift(u, v);\n}\n\ntemplate <typename N>\ninline void eval_right_shift(kanooth_integer<N>& r, unsigned long v)\n{\n   r.right_shift(r, v);\n}\n\ntemplate <typename N>\ninline void eval_right_shift(kanooth_integer<N>& r, kanooth_integer<N>& u, unsigned long v)\n{\n   r.right_shift(u, v);\n}\n\ntemplate <typename N>\ninline bool eval_bit_test(const kanooth_integer<N>& u, unsigned pos)\n{\n    return u.bit_test(pos);\n}\n\ntemplate <typename N>\ninline void eval_bit_set(kanooth_integer<N>& u, unsigned pos)\n{\n    u.bit_set(pos);\n}\n\ntemplate <typename N>\ninline void eval_bit_unset(kanooth_integer<N>& u, unsigned pos)\n{\n    u.bit_unset(pos);\n}\n\ntemplate <typename N>\ninline void eval_bit_flip(kanooth_integer<N>& u, unsigned pos)\n{\n    u.bit_flip(pos);\n}\n\ntemplate <typename N>\ninline bool eval_eq(const kanooth_integer<N>& a, const kanooth_integer<N>& b)\n{\n    return a.compare(b) == 0;\n}\n\ntemplate <typename N, typename T>\ninline typename kanooth_integer<N>::template if_supported_int<T, bool>::type\neval_eq(const kanooth_integer<N>& a, T b)\n{\n    return a.compare(b) == 0;\n}\n\ntemplate <typename N>\ninline bool eval_lt(const kanooth_integer<N>& a, const kanooth_integer<N>& b)\n{\n    return a.compare(b) < 0;\n}\n\ntemplate <typename N, typename T>\ninline typename kanooth_integer<N>::template if_supported_int<T, bool>::type\neval_lt(const kanooth_integer<N>& a, T b)\n{\n    return a.compare(b) < 0;\n}\n\ntemplate <typename N>\ninline bool eval_gt(const kanooth_integer<N>& a, const kanooth_integer<N>& b)\n{\n    return a.compare(b) > 0;\n}\n\ntemplate <typename N, typename T>\ninline typename kanooth_integer<N>::template if_supported_int<T, bool>::type\neval_gt(const kanooth_integer<N>& a, T b)\n{\n    return a.compare(b) > 0;\n}\n\n} // namespace backends\n} // namespace multiprecision\n} // namespace boost\n\nnamespace kanooth {\nnamespace numbers {\n\ntypedef boost::multiprecision::number<boost::multiprecision::backends::kanooth_integer<natural_number> > boost_integer;\n\n} // namespace numbers\n} // namespace kanooth\n\nnamespace std {\n\ntemplate <typename N, boost::multiprecision::expression_template_option ExpressionTemplates>\nclass numeric_limits<boost::multiprecision::number<boost::multiprecision::backends::kanooth_integer<N>, ExpressionTemplates> >\n{\n   typedef boost::multiprecision::number<boost::multiprecision::backends::kanooth_integer<N>, ExpressionTemplates> number_type;\npublic:\n   BOOST_STATIC_CONSTEXPR bool is_specialized = true;\n   //\n   // Largest and smallest numbers are bounded only by available memory, set\n   // to zero:\n   //\n   static number_type (min)() BOOST_NOEXCEPT\n   {\n      return number_type();\n   }\n   static number_type (max)() BOOST_NOEXCEPT\n   {\n      return number_type();\n   }\n   static number_type lowest() BOOST_NOEXCEPT { return (min)(); }\n   BOOST_STATIC_CONSTEXPR int digits = INT_MAX;\n   BOOST_STATIC_CONSTEXPR int digits10 = (INT_MAX / 1000) * 301L;\n   BOOST_STATIC_CONSTEXPR int max_digits10 = digits10 + 2;\n   BOOST_STATIC_CONSTEXPR bool is_signed = true;\n   BOOST_STATIC_CONSTEXPR bool is_integer = true;\n   BOOST_STATIC_CONSTEXPR bool is_exact = true;\n   BOOST_STATIC_CONSTEXPR int radix = 2;\n   static number_type epsilon() BOOST_NOEXCEPT { return number_type(); }\n   static number_type round_error() BOOST_NOEXCEPT { return number_type(); }\n   BOOST_STATIC_CONSTEXPR int min_exponent = 0;\n   BOOST_STATIC_CONSTEXPR int min_exponent10 = 0;\n   BOOST_STATIC_CONSTEXPR int max_exponent = 0;\n   BOOST_STATIC_CONSTEXPR int max_exponent10 = 0;\n   BOOST_STATIC_CONSTEXPR bool has_infinity = false;\n   BOOST_STATIC_CONSTEXPR bool has_quiet_NaN = false;\n   BOOST_STATIC_CONSTEXPR bool has_signaling_NaN = false;\n   BOOST_STATIC_CONSTEXPR float_denorm_style has_denorm = denorm_absent;\n   BOOST_STATIC_CONSTEXPR bool has_denorm_loss = false;\n   static number_type infinity() BOOST_NOEXCEPT { return number_type(); }\n   static number_type quiet_NaN() BOOST_NOEXCEPT { return number_type(); }\n   static number_type signaling_NaN() BOOST_NOEXCEPT { return number_type(); }\n   static number_type denorm_min() BOOST_NOEXCEPT { return number_type(); }\n   BOOST_STATIC_CONSTEXPR bool is_iec559 = false;\n   BOOST_STATIC_CONSTEXPR bool is_bounded = false;\n   BOOST_STATIC_CONSTEXPR bool is_modulo = false;\n   BOOST_STATIC_CONSTEXPR bool traps = false;\n   BOOST_STATIC_CONSTEXPR bool tinyness_before = false;\n   BOOST_STATIC_CONSTEXPR float_round_style round_style = round_toward_zero;\n};\n\n} // namespace std\n\n#endif // KANOOTH_NUMBERS_BOOST_INTEGER_HPP\n", "meta": {"hexsha": "06e50fab40d9724694219ecab54ff9883fa161bb", "size": 11662, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "kanooth/numbers/boost_integer.hpp", "max_stars_repo_name": "janmarthedal/kanooth-numbers", "max_stars_repo_head_hexsha": "2c6ce4f588bdd26826c20a84154881d84a70191c", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2017-10-02T13:29:54.000Z", "max_stars_repo_stars_event_max_datetime": "2018-04-24T18:17:18.000Z", "max_issues_repo_path": "kanooth/numbers/boost_integer.hpp", "max_issues_repo_name": "janmarthedal/kanooth-numbers", "max_issues_repo_head_hexsha": "2c6ce4f588bdd26826c20a84154881d84a70191c", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "kanooth/numbers/boost_integer.hpp", "max_forks_repo_name": "janmarthedal/kanooth-numbers", "max_forks_repo_head_hexsha": "2c6ce4f588bdd26826c20a84154881d84a70191c", "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.8663366337, "max_line_length": 127, "alphanum_fraction": 0.7379523238, "num_tokens": 2973, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6688802603710086, "lm_q2_score": 0.4921881357207956, "lm_q1q2_score": 0.3292149283724471}}
{"text": "#ifndef LIDAR_UNDISTORTION_HPP_\n#define LIDAR_UNDISTORTION_HPP_\n\n#include <pcl/point_types.h>\n#include <pcl/io/pcd_io.h>\n#include <pcl/common/common.h>\n#include <pcl/common/eigen.h>\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n#include <iostream>\n\nclass LidarUndistortion\n{\npublic:\n  LidarUndistortion() {}\n\n  // Ref:LeGO-LOAM(BSD-3 LICENSE)\n  // https://github.com/RobustFieldAutonomyLab/LeGO-LOAM/blob/master/LeGO-LOAM/src/featureAssociation.cpp#L431-L459\n  void getImu(\n    Eigen::Vector3f angular_velo, Eigen::Vector3f acc, const Eigen::Quaternionf quat,\n    const double imu_time /*[sec]*/)\n  {\n    float roll, pitch, yaw;\n    Eigen::Affine3f affine(quat);\n    pcl::getEulerAngles(affine, roll, pitch, yaw);\n\n    imu_ptr_last_ = (imu_ptr_last_ + 1) % imu_que_length_;\n\n    if ((imu_ptr_last_ + 1) % imu_que_length_ == imu_ptr_front_) {\n      imu_ptr_front_ = (imu_ptr_front_ + 1) % imu_que_length_;\n    }\n\n    imu_time_[imu_ptr_last_] = imu_time;\n    imu_roll_[imu_ptr_last_] = roll;\n    imu_pitch_[imu_ptr_last_] = pitch;\n    imu_yaw_[imu_ptr_last_] = yaw;\n    imu_acc_x_[imu_ptr_last_] = acc.x();\n    imu_acc_y_[imu_ptr_last_] = acc.y();\n    imu_acc_z_[imu_ptr_last_] = acc.z();\n    imu_angular_velo_x_[imu_ptr_last_] = angular_velo.x();\n    imu_angular_velo_y_[imu_ptr_last_] = angular_velo.y();\n    imu_angular_velo_z_[imu_ptr_last_] = angular_velo.z();\n\n    Eigen::Matrix3f rot = quat.toRotationMatrix();\n    acc = rot * acc;\n    // angular_velo = rot * angular_velo;\n\n    int imu_ptr_back = (imu_ptr_last_ - 1 + imu_que_length_) % imu_que_length_;\n    double time_diff = imu_time_[imu_ptr_last_] - imu_time_[imu_ptr_back];\n    if (time_diff < scan_period_) {\n      imu_shift_x_[imu_ptr_last_] =\n        imu_shift_x_[imu_ptr_back] + imu_velo_x_[imu_ptr_back] * time_diff + acc(0) * time_diff *\n        time_diff * 0.5;\n      imu_shift_y_[imu_ptr_last_] =\n        imu_shift_y_[imu_ptr_back] + imu_velo_y_[imu_ptr_back] * time_diff + acc(1) * time_diff *\n        time_diff * 0.5;\n      imu_shift_z_[imu_ptr_last_] =\n        imu_shift_z_[imu_ptr_back] + imu_velo_z_[imu_ptr_back] * time_diff + acc(2) * time_diff *\n        time_diff * 0.5;\n\n      imu_velo_x_[imu_ptr_last_] = imu_velo_x_[imu_ptr_back] + acc(0) * time_diff;\n      imu_velo_y_[imu_ptr_last_] = imu_velo_y_[imu_ptr_back] + acc(1) * time_diff;\n      imu_velo_z_[imu_ptr_last_] = imu_velo_z_[imu_ptr_back] + acc(2) * time_diff;\n\n      imu_angular_rot_x_[imu_ptr_last_] = imu_angular_rot_x_[imu_ptr_back] + angular_velo(0) *\n        time_diff;\n      imu_angular_rot_y_[imu_ptr_last_] = imu_angular_rot_y_[imu_ptr_back] + angular_velo(1) *\n        time_diff;\n      imu_angular_rot_z_[imu_ptr_last_] = imu_angular_rot_z_[imu_ptr_back] + angular_velo(2) *\n        time_diff;\n    }\n  }\n\n  // Ref:LeGO-LOAM(BSD-3 LICENSE)\n  // https://github.com/RobustFieldAutonomyLab/LeGO-LOAM/blob/master/LeGO-LOAM/src/featureAssociation.cpp#L491-L619\n  void adjustDistortion(\n    pcl::PointCloud<pcl::PointXYZI>::Ptr & cloud,\n    const double scan_time /*[sec]*/)\n  {\n    bool half_passed = false;\n    int cloud_size = cloud->points.size();\n\n    float start_ori = -std::atan2(cloud->points[0].y, cloud->points[0].x);\n    float end_ori = -std::atan2(cloud->points[cloud_size - 1].y, cloud->points[cloud_size - 1].x);\n    if (end_ori - start_ori > 3 * M_PI) {\n      end_ori -= 2 * M_PI;\n    } else if (end_ori - start_ori < M_PI) {\n      end_ori += 2 * M_PI;\n    }\n    float ori_diff = end_ori - start_ori;\n\n    Eigen::Vector3f rpy_start, shift_start, velo_start, rpy_cur, shift_cur, velo_cur;\n    Eigen::Vector3f shift_from_start;\n    Eigen::Matrix3f r_s_i, r_c;\n    Eigen::Vector3f adjusted_p;\n    float ori_h;\n    for (int i = 0; i < cloud_size; ++i) {\n      pcl::PointXYZI & p = cloud->points[i];\n      ori_h = -std::atan2(p.y, p.x);\n      if (!half_passed) {\n        if (ori_h < start_ori - M_PI * 0.5) {\n          ori_h += 2 * M_PI;\n        } else if (ori_h > start_ori + M_PI * 1.5) {\n          ori_h -= 2 * M_PI;\n        }\n\n        if (ori_h - start_ori > M_PI) {\n          half_passed = true;\n        }\n      } else {\n        ori_h += 2 * M_PI;\n        if (ori_h < end_ori - 1.5 * M_PI) {\n          ori_h += 2 * M_PI;\n        } else if (ori_h > end_ori + 0.5 * M_PI) {\n          ori_h -= 2 * M_PI;\n        }\n      }\n\n      float rel_time = (ori_h - start_ori) / ori_diff * scan_period_;\n\n      if (imu_ptr_last_ > 0) {\n        imu_ptr_front_ = imu_ptr_last_iter_;\n        while (imu_ptr_front_ != imu_ptr_last_) {\n          if (scan_time + rel_time > imu_time_[imu_ptr_front_]) {\n            break;\n          }\n          imu_ptr_front_ = (imu_ptr_front_ + 1) % imu_que_length_;\n        }\n\n        if (scan_time + rel_time > imu_time_[imu_ptr_front_]) {\n          rpy_cur(0) = imu_roll_[imu_ptr_front_];\n          rpy_cur(1) = imu_pitch_[imu_ptr_front_];\n          rpy_cur(2) = imu_yaw_[imu_ptr_front_];\n          shift_cur(0) = imu_shift_x_[imu_ptr_front_];\n          shift_cur(1) = imu_shift_y_[imu_ptr_front_];\n          shift_cur(2) = imu_shift_z_[imu_ptr_front_];\n          velo_cur(0) = imu_velo_x_[imu_ptr_front_];\n          velo_cur(1) = imu_velo_y_[imu_ptr_front_];\n          velo_cur(2) = imu_velo_z_[imu_ptr_front_];\n        } else {\n          int imu_ptr_back = (imu_ptr_front_ - 1 + imu_que_length_) % imu_que_length_;\n          float ratio_front = (scan_time + rel_time - imu_time_[imu_ptr_back]) /\n            (imu_time_[imu_ptr_front_] - imu_time_[imu_ptr_back]);\n          float ratio_back = 1.0 - ratio_front;\n          rpy_cur(0) = imu_roll_[imu_ptr_front_] * ratio_front + imu_roll_[imu_ptr_back] *\n            ratio_back;\n          rpy_cur(1) = imu_pitch_[imu_ptr_front_] * ratio_front + imu_pitch_[imu_ptr_back] *\n            ratio_back;\n          rpy_cur(2) = imu_yaw_[imu_ptr_front_] * ratio_front + imu_yaw_[imu_ptr_back] * ratio_back;\n          shift_cur(0) = imu_shift_x_[imu_ptr_front_] * ratio_front + imu_shift_x_[imu_ptr_back] *\n            ratio_back;\n          shift_cur(1) = imu_shift_y_[imu_ptr_front_] * ratio_front + imu_shift_y_[imu_ptr_back] *\n            ratio_back;\n          shift_cur(2) = imu_shift_z_[imu_ptr_front_] * ratio_front + imu_shift_z_[imu_ptr_back] *\n            ratio_back;\n          velo_cur(0) = imu_velo_x_[imu_ptr_front_] * ratio_front + imu_velo_x_[imu_ptr_back] *\n            ratio_back;\n          velo_cur(1) = imu_velo_y_[imu_ptr_front_] * ratio_front + imu_velo_y_[imu_ptr_back] *\n            ratio_back;\n          velo_cur(2) = imu_velo_z_[imu_ptr_front_] * ratio_front + imu_velo_z_[imu_ptr_back] *\n            ratio_back;\n        }\n\n        r_c = (\n          Eigen::AngleAxisf(rpy_cur(2), Eigen::Vector3f::UnitZ()) *\n          Eigen::AngleAxisf(rpy_cur(1), Eigen::Vector3f::UnitY()) *\n          Eigen::AngleAxisf(rpy_cur(0), Eigen::Vector3f::UnitX())\n          ).toRotationMatrix();\n\n        if (i == 0) {\n          rpy_start = rpy_cur;\n          shift_start = shift_cur;\n          velo_start = velo_cur;\n          r_s_i = r_c.inverse();\n        } else {\n          shift_from_start = shift_cur - shift_start - velo_start * rel_time;\n          adjusted_p = r_s_i * (r_c * Eigen::Vector3f(p.x, p.y, p.z) + shift_from_start);\n          p.x = adjusted_p.x();\n          p.y = adjusted_p.y();\n          p.z = adjusted_p.z();\n        }\n      }\n      imu_ptr_last_iter_ = imu_ptr_front_;\n    }\n  }\n\n\n  void setScanPeriod(const double scan_period /*[sec]*/)\n  {\n    scan_period_ = scan_period;\n  }\n\nprivate:\n  double scan_period_{0.1};\n  static const int imu_que_length_{200};\n  int imu_ptr_front_{0}, imu_ptr_last_{-1}, imu_ptr_last_iter_{0};\n\n  std::array<double, imu_que_length_> imu_time_;\n  std::array<float, imu_que_length_> imu_roll_;\n  std::array<float, imu_que_length_> imu_pitch_;\n  std::array<float, imu_que_length_> imu_yaw_;\n\n  std::array<float, imu_que_length_> imu_acc_x_;\n  std::array<float, imu_que_length_> imu_acc_y_;\n  std::array<float, imu_que_length_> imu_acc_z_;\n  std::array<float, imu_que_length_> imu_velo_x_;\n  std::array<float, imu_que_length_> imu_velo_y_;\n  std::array<float, imu_que_length_> imu_velo_z_;\n  std::array<float, imu_que_length_> imu_shift_x_;\n  std::array<float, imu_que_length_> imu_shift_y_;\n  std::array<float, imu_que_length_> imu_shift_z_;\n\n  std::array<float, imu_que_length_> imu_angular_velo_x_;\n  std::array<float, imu_que_length_> imu_angular_velo_y_;\n  std::array<float, imu_que_length_> imu_angular_velo_z_;\n  std::array<float, imu_que_length_> imu_angular_rot_x_;\n  std::array<float, imu_que_length_> imu_angular_rot_y_;\n  std::array<float, imu_que_length_> imu_angular_rot_z_;\n};\n\n#endif  // LIDAR_UNDISTORTION_HPP_\n", "meta": {"hexsha": "f5147c4780012550183eebbefd3182cfcda382ad", "size": 8592, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/pcl_localization/lidar_undistortion.hpp", "max_stars_repo_name": "rsasaki0109/pcl_localization_ros2", "max_stars_repo_head_hexsha": "5eed53d62d422a9dc4b6199336d96a9e9a283ce8", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 37.0, "max_stars_repo_stars_event_min_datetime": "2020-04-20T22:22:54.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-31T22:37:16.000Z", "max_issues_repo_path": "include/pcl_localization/lidar_undistortion.hpp", "max_issues_repo_name": "rsasaki0109/pcl_localization_ros2", "max_issues_repo_head_hexsha": "5eed53d62d422a9dc4b6199336d96a9e9a283ce8", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2020-10-10T07:10:40.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-23T11:24:25.000Z", "max_forks_repo_path": "include/pcl_localization/lidar_undistortion.hpp", "max_forks_repo_name": "rsasaki0109/pcl_localization_ros2", "max_forks_repo_head_hexsha": "5eed53d62d422a9dc4b6199336d96a9e9a283ce8", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2020-04-20T22:24:53.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-07T20:06:17.000Z", "avg_line_length": 38.7027027027, "max_line_length": 115, "alphanum_fraction": 0.6552607076, "num_tokens": 2567, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.668880247169804, "lm_q2_score": 0.49218813572079556, "lm_q1q2_score": 0.32921492187497076}}
{"text": "//==============================================================================\n//         Copyright 2003 - 2011 LASMEA UMR 6602 CNRS/Univ. Clermont II\n//         Copyright 2009 - 2011 LRI    UMR 8623 CNRS/Univ Paris Sud XI\n//\n//          Distributed under the Boost Software License, Version 1.0.\n//                 See accompanying file LICENSE.txt or copy at\n//                     http://www.boost.org/LICENSE_1_0.txt\n//==============================================================================\n#ifndef NT2_ELLIPTIC_FUNCTIONS_GENERIC_AM_HPP_INCLUDED\n#define NT2_ELLIPTIC_FUNCTIONS_GENERIC_AM_HPP_INCLUDED\n\n#include <nt2/elliptic/functions/am.hpp>\n#include <boost/dispatch/attributes.hpp>\n#include <nt2/include/constants/eps.hpp>\n#include <nt2/include/functions/simd/abs.hpp>\n#include <nt2/include/functions/simd/sin.hpp>\n#include <nt2/include/functions/simd/sqrt.hpp>\n#include <nt2/sdk/meta/scalar_of.hpp>\n\nnamespace nt2 { namespace ext\n{\n  BOOST_DISPATCH_IMPLEMENT  (am_, tag::cpu_,\n                             (A0)(A1)(A2)(A3),\n                             (generic_<floating_<A0> >)\n                             (generic_<floating_<A1> >)\n                             (scalar_<floating_<A2> >)\n                             (scalar_<integer_<A3> >)\n                            )\n  {\n    typedef A0 result_type;\n\n    BOOST_FORCEINLINE result_type operator()(const A0 & u, const A1 & x,\n                                             const A2 & tol, const A3 & choice) const\n    {\n      switch (choice)\n      {\n      case 'a': return am(u,nt2::sin(x), tol);\n      case 'm': return am(u,nt2::sqrt(nt2::abs(x)), tol);\n      default : return am(u,x,tol);\n      }\n    }\n  };\n\n  BOOST_DISPATCH_IMPLEMENT  (am_, tag::cpu_,\n                             (A0)(A1)(A2),\n                             (generic_<floating_<A0> >)\n                             (generic_<floating_<A1> >)\n                             (scalar_<integer_<A2> >)\n                            )\n  {\n    typedef A0 result_type;\n\n    BOOST_FORCEINLINE result_type operator()(const A0 & u, const A1 & x,\n                                             const A2 & choice) const\n    {\n      typedef typename meta::scalar_of<result_type>::type sA0;\n      return am(u,x,Eps<sA0>(),choice);\n    }\n  };\n\n  BOOST_DISPATCH_IMPLEMENT  (am_, tag::cpu_,\n                              (A0)(A1),\n                              (generic_<floating_<A0> >)\n                              (generic_<floating_<A1> >)\n                             )\n  {\n    typedef A0 result_type;\n    BOOST_FORCEINLINE result_type operator()(const A0 & u, const A1 & x) const\n    {\n      typedef typename meta::scalar_of<result_type>::type sA0;\n      return am(u,x,Eps<sA0>());\n    }\n  };\n} }\n#endif\n", "meta": {"hexsha": "d4000e372a60e028cf45e1141bdcaec91df31259", "size": 2726, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/core/elliptic/include/nt2/elliptic/functions/generic/am.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/elliptic/include/nt2/elliptic/functions/generic/am.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/elliptic/include/nt2/elliptic/functions/generic/am.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": 35.8684210526, "max_line_length": 85, "alphanum_fraction": 0.4933969186, "num_tokens": 635, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.658417500561683, "lm_q2_score": 0.5, "lm_q1q2_score": 0.3292087502808415}}
{"text": "/*\n * DistributionRightHandSide.cc\n *\n *  Created on: 30.06.2017\n *      Author: thies\n */\n\n#include <deal.II/base/exceptions.h>\n#include <deal.II/base/types.h>\n#include <deal.II/base/work_stream.h>\n#include <deal.II/fe/fe.h>\n#include <deal.II/fe/fe_update_flags.h>\n#include <deal.II/fe/fe_values.h>\n\n#include <base/DiscretizedFunction.h>\n#include <forward/DistributionRightHandSide.h>\n\n#include <vector>\n\nnamespace wavepi {\nnamespace forward {\nusing namespace dealii;\nusing namespace wavepi::base;\n\ntemplate <int dim>\nDistributionRightHandSide<dim>::AssemblyScratchData::AssemblyScratchData(const FiniteElement<dim> &fe,\n                                                                         const Quadrature<dim> &quad)\n    : fe_values(fe, quad, update_values | update_gradients | update_quadrature_points | update_JxW_values) {}\n\ntemplate <int dim>\nDistributionRightHandSide<dim>::AssemblyScratchData::AssemblyScratchData(const AssemblyScratchData &scratch_data)\n    : fe_values(scratch_data.fe_values.get_fe(), scratch_data.fe_values.get_quadrature(),\n                update_values | update_gradients | update_quadrature_points | update_JxW_values) {}\n\ntemplate <int dim>\nDistributionRightHandSide<dim>::DistributionRightHandSide(Function<dim> *f1, Function<dim> *f2) {\n  this->f1 = f1;\n  this->f2 = f2;\n}\n\ntemplate <int dim>\nvoid DistributionRightHandSide<dim>::copy_local_to_global(Vector<double> &result, const AssemblyCopyData &copy_data) {\n  for (unsigned int i = 0; i < copy_data.local_dof_indices.size(); ++i)\n    result(copy_data.local_dof_indices[i]) += copy_data.cell_rhs(i);\n}\n\ntemplate <int dim>\nvoid DistributionRightHandSide<dim>::local_assemble_cc(const Function<dim> *const f1, const Function<dim> *const f2,\n                                                       const typename DoFHandler<dim>::active_cell_iterator &cell,\n                                                       AssemblyScratchData &scratch_data, AssemblyCopyData &copy_data) {\n  const unsigned int dofs_per_cell = scratch_data.fe_values.get_fe().dofs_per_cell;\n  const unsigned int n_q_points    = scratch_data.fe_values.get_quadrature().size();\n\n  copy_data.cell_rhs.reinit(dofs_per_cell);\n  copy_data.local_dof_indices.resize(dofs_per_cell);\n  scratch_data.fe_values.reinit(cell);\n\n  for (unsigned int q_point = 0; q_point < n_q_points; ++q_point) {\n    if (f1 != nullptr) {\n      const double val1 = f1->value(scratch_data.fe_values.quadrature_point(q_point));\n\n      for (unsigned int i = 0; i < dofs_per_cell; ++i)\n        copy_data.cell_rhs(i) +=\n            val1 * scratch_data.fe_values.shape_value(i, q_point) * scratch_data.fe_values.JxW(q_point);\n    }\n\n    if (f2 != nullptr) {\n      auto val2 = f2->gradient(scratch_data.fe_values.quadrature_point(q_point));\n\n      for (unsigned int i = 0; i < dofs_per_cell; ++i)\n        copy_data.cell_rhs(i) +=\n            val2 * scratch_data.fe_values.shape_grad(i, q_point) * scratch_data.fe_values.JxW(q_point);\n    }\n  }\n\n  cell->get_dof_indices(copy_data.local_dof_indices);\n}\n\ntemplate <int dim>\nvoid DistributionRightHandSide<dim>::local_assemble_dd(const Vector<double> &f1, const Vector<double> &f2,\n                                                       const typename DoFHandler<dim>::active_cell_iterator &cell,\n                                                       AssemblyScratchData &scratch_data, AssemblyCopyData &copy_data) {\n  const unsigned int dofs_per_cell = scratch_data.fe_values.get_fe().dofs_per_cell;\n  const unsigned int n_q_points    = scratch_data.fe_values.get_quadrature().size();\n\n  copy_data.cell_rhs.reinit(dofs_per_cell);\n  copy_data.local_dof_indices.resize(dofs_per_cell);\n  scratch_data.fe_values.reinit(cell);\n\n  cell->get_dof_indices(copy_data.local_dof_indices);\n\n  for (unsigned int q_point = 0; q_point < n_q_points; ++q_point)\n    for (unsigned int i = 0; i < dofs_per_cell; ++i)\n      for (unsigned int k = 0; k < dofs_per_cell; ++k)\n        copy_data.cell_rhs(i) += (f1[copy_data.local_dof_indices[k]] * scratch_data.fe_values.shape_value(k, q_point) *\n                                      scratch_data.fe_values.shape_value(i, q_point) +\n                                  f2[copy_data.local_dof_indices[k]] * scratch_data.fe_values.shape_grad(k, q_point) *\n                                      scratch_data.fe_values.shape_grad(i, q_point)) *\n                                 scratch_data.fe_values.JxW(q_point);\n}\n\ntemplate <int dim>\nvoid DistributionRightHandSide<dim>::local_assemble_cd(const Function<dim> *const f1, const Vector<double> &f2,\n                                                       const typename DoFHandler<dim>::active_cell_iterator &cell,\n                                                       AssemblyScratchData &scratch_data, AssemblyCopyData &copy_data) {\n  const unsigned int dofs_per_cell = scratch_data.fe_values.get_fe().dofs_per_cell;\n  const unsigned int n_q_points    = scratch_data.fe_values.get_quadrature().size();\n\n  copy_data.cell_rhs.reinit(dofs_per_cell);\n  copy_data.local_dof_indices.resize(dofs_per_cell);\n  scratch_data.fe_values.reinit(cell);\n\n  cell->get_dof_indices(copy_data.local_dof_indices);\n\n  for (unsigned int q_point = 0; q_point < n_q_points; ++q_point) {\n    if (f1 != nullptr) {\n      const double val1 = f1->value(scratch_data.fe_values.quadrature_point(q_point));\n\n      for (unsigned int i = 0; i < dofs_per_cell; ++i)\n        copy_data.cell_rhs(i) +=\n            val1 * scratch_data.fe_values.shape_value(i, q_point) * scratch_data.fe_values.JxW(q_point);\n    }\n\n    for (unsigned int i = 0; i < dofs_per_cell; ++i) {\n      for (unsigned int k = 0; k < dofs_per_cell; ++k)\n        copy_data.cell_rhs(i) += f2[copy_data.local_dof_indices[k]] * scratch_data.fe_values.shape_grad(k, q_point) *\n                                 scratch_data.fe_values.shape_grad(i, q_point) * scratch_data.fe_values.JxW(q_point);\n    }\n  }\n}\n\ntemplate <int dim>\nvoid DistributionRightHandSide<dim>::local_assemble_dc(const Vector<double> &f1, const Function<dim> *const f2,\n                                                       const typename DoFHandler<dim>::active_cell_iterator &cell,\n                                                       AssemblyScratchData &scratch_data, AssemblyCopyData &copy_data) {\n  const unsigned int dofs_per_cell = scratch_data.fe_values.get_fe().dofs_per_cell;\n  const unsigned int n_q_points    = scratch_data.fe_values.get_quadrature().size();\n\n  copy_data.cell_rhs.reinit(dofs_per_cell);\n  copy_data.local_dof_indices.resize(dofs_per_cell);\n  scratch_data.fe_values.reinit(cell);\n\n  cell->get_dof_indices(copy_data.local_dof_indices);\n\n  for (unsigned int q_point = 0; q_point < n_q_points; ++q_point)\n    for (unsigned int i = 0; i < dofs_per_cell; ++i) {\n      for (unsigned int k = 0; k < dofs_per_cell; ++k)\n        copy_data.cell_rhs(i) += f1[copy_data.local_dof_indices[k]] * scratch_data.fe_values.shape_value(k, q_point) *\n                                 scratch_data.fe_values.shape_value(i, q_point) * scratch_data.fe_values.JxW(q_point);\n\n      if (f2 != nullptr) {\n        auto val2 = f2->gradient(scratch_data.fe_values.quadrature_point(q_point));\n\n        for (unsigned int i = 0; i < dofs_per_cell; ++i)\n          copy_data.cell_rhs(i) +=\n              val2 * scratch_data.fe_values.shape_grad(i, q_point) * scratch_data.fe_values.JxW(q_point);\n      }\n    }\n}\n\ntemplate <int dim>\nvoid DistributionRightHandSide<dim>::create_right_hand_side(const DoFHandler<dim> &dof, const Quadrature<dim> &quad,\n                                                            Vector<double> &rhs) const {\n  f1->set_time(this->get_time());\n  f2->set_time(this->get_time());\n\n  auto f1_d = dynamic_cast<DiscretizedFunction<dim> *>(f1);\n  auto f2_d = dynamic_cast<DiscretizedFunction<dim> *>(f2);\n\n  if (f1_d != nullptr)\n    Assert(f1_d->get_function_coefficients(f1_d->get_time_index()).size() == dof.n_dofs(),\n           ExcDimensionMismatch(f1_d->get_function_coefficients(f1_d->get_time_index()).size(), dof.n_dofs()));\n\n  if (f2_d != nullptr)\n    Assert(f2_d->get_function_coefficients(f2_d->get_time_index()).size() == dof.n_dofs(),\n           ExcDimensionMismatch(f2_d->get_function_coefficients(f2_d->get_time_index()).size(), dof.n_dofs()));\n\n  if (f1_d != nullptr && f2_d != nullptr)\n    WorkStream::run(\n        dof.begin_active(), dof.end(),\n        std::bind(&DistributionRightHandSide<dim>::local_assemble_cc, f1, f2, std::placeholders::_1,\n                  std::placeholders::_2, std::placeholders::_3),\n        std::bind(&DistributionRightHandSide<dim>::copy_local_to_global, std::ref(rhs), std::placeholders::_1),\n        AssemblyScratchData(dof.get_fe(), quad), AssemblyCopyData());\n  else if (f1_d == nullptr && f2_d != nullptr)\n    WorkStream::run(\n        dof.begin_active(), dof.end(),\n        std::bind(&DistributionRightHandSide<dim>::local_assemble_cd, f1,\n                  std::ref(f2_d->get_function_coefficients(f2_d->get_time_index())), std::placeholders::_1,\n                  std::placeholders::_2, std::placeholders::_3),\n        std::bind(&DistributionRightHandSide<dim>::copy_local_to_global, std::ref(rhs), std::placeholders::_1),\n        AssemblyScratchData(dof.get_fe(), quad), AssemblyCopyData());\n  else if (f1_d != nullptr && f2_d == nullptr)\n    WorkStream::run(\n        dof.begin_active(), dof.end(),\n        std::bind(&DistributionRightHandSide<dim>::local_assemble_dc,\n                  std::ref(f1_d->get_function_coefficients(f1_d->get_time_index())), f2, std::placeholders::_1,\n                  std::placeholders::_2, std::placeholders::_3),\n        std::bind(&DistributionRightHandSide<dim>::copy_local_to_global, std::ref(rhs), std::placeholders::_1),\n        AssemblyScratchData(dof.get_fe(), quad), AssemblyCopyData());\n  else\n    WorkStream::run(\n        dof.begin_active(), dof.end(),\n        std::bind(&DistributionRightHandSide<dim>::local_assemble_cc, f1, f2, std::placeholders::_1,\n                  std::placeholders::_2, std::placeholders::_3),\n        std::bind(&DistributionRightHandSide<dim>::copy_local_to_global, std::ref(rhs), std::placeholders::_1),\n        AssemblyScratchData(dof.get_fe(), quad), AssemblyCopyData());\n}\n\ntemplate class DistributionRightHandSide<1>;\ntemplate class DistributionRightHandSide<2>;\ntemplate class DistributionRightHandSide<3>;\n\n} /* namespace forward */\n} /* namespace wavepi */\n", "meta": {"hexsha": "a3bcc77ed44f71470bc49e2e4fe52c3684521489", "size": 10343, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lib/forward/DistributionRightHandSide.cpp", "max_stars_repo_name": "thiesgerken/wavepi", "max_stars_repo_head_hexsha": "5af37946dcc1910ad1cccdc76d2e2f546eeafec4", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "lib/forward/DistributionRightHandSide.cpp", "max_issues_repo_name": "thiesgerken/wavepi", "max_issues_repo_head_hexsha": "5af37946dcc1910ad1cccdc76d2e2f546eeafec4", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lib/forward/DistributionRightHandSide.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.8842592593, "max_line_length": 120, "alphanum_fraction": 0.6674079087, "num_tokens": 2522, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6584175005616829, "lm_q2_score": 0.5, "lm_q1q2_score": 0.32920875028084146}}
{"text": "#ifndef DDI_PROCESS_HPP\n#define DDI_PROCESS_HPP\n#define _USE_MATH_DEFINES\n#include <math.h>\n#include <boost/math/special_functions/sinc.hpp>\n#include \"basic_process.hpp\"\n#include \"basic_voxel.hpp\"\n#include \"image_model.hpp\"\n\n\ndouble base_function(double theta);\nclass QSpace2Odf  : public BaseProcess\n{\npublic:// recorded for scheme balanced\n    std::vector<image::vector<3,double> > q_vectors_time;\npublic:\n    std::vector<unsigned int> b0_images;\n    std::vector<float> sinc_ql;\n\npublic:\n    virtual void init(Voxel& voxel)\n    {\n        b0_images.clear();\n        for(unsigned int index = 0;index < voxel.bvalues.size();++index)\n            if(voxel.bvalues[index] == 0)\n                b0_images.push_back(index);\n        if(b0_images.size() > 1)\n            throw std::runtime_error(\"Correct B0 failed. Two b0 images found in src file\");\n\n\n        unsigned int odf_size = voxel.ti.half_vertices_count;\n        float sigma = voxel.param[0]; //optimal 1.24\n        if(!voxel.grad_dev.empty())\n        {\n            q_vectors_time.resize(voxel.bvalues.size());\n            for (unsigned int index = 0; index < voxel.bvalues.size(); ++index)\n            {\n                q_vectors_time[index] = voxel.bvectors[index];\n                q_vectors_time[index] *= std::sqrt(voxel.bvalues[index]*0.01506);// get q in (mm) -1\n                q_vectors_time[index] *= sigma;\n            }\n            return;\n        }\n        sinc_ql.resize(odf_size*voxel.bvalues.size());\n        // calculate reconstruction matrix\n        for (unsigned int j = 0,index = 0; j < odf_size; ++j)\n            for (unsigned int i = 0; i < voxel.bvalues.size(); ++i,++index)\n                sinc_ql[index] = voxel.bvectors[i]*\n                             image::vector<3,float>(voxel.ti.vertices[j])*\n                               std::sqrt(voxel.bvalues[i]*0.01506);\n\n        for (unsigned int index = 0; index < sinc_ql.size(); ++index)\n            sinc_ql[index] = voxel.r2_weighted ?\n                         base_function(sinc_ql[index]*sigma):\n                         boost::math::sinc_pi(sinc_ql[index]*sigma);\n\n    }\n    virtual void run(Voxel& voxel, VoxelData& data)\n    {\n        if(b0_images.size() == 1 && voxel.half_sphere)\n            data.space[b0_images.front()] *= 0.5;\n\n        if(!voxel.grad_dev.empty()) // correction for gradient nonlinearity\n        {\n            /*\n            new_bvecs = (I+grad_dev) * bvecs;\n            */\n            float grad_dev[9];\n            for(unsigned int i = 0; i < 9; ++i)\n                grad_dev[i] = voxel.grad_dev[i][data.voxel_index];\n            image::mat::transpose(grad_dev,image::dim<3,3>());\n            std::vector<float> new_sinc_ql(data.odf.size()*data.space.size());\n            for (unsigned int j = 0,index = 0; j < data.odf.size(); ++j)\n            {\n                image::vector<3,float> from(voxel.ti.vertices[j]);\n                from.rotate(grad_dev);\n                from.normalize();\n                if(voxel.r2_weighted)\n                    for (unsigned int i = 0; i < data.space.size(); ++i,++index)\n                        new_sinc_ql[index] = base_function(q_vectors_time[i]*from);\n                else\n                    for (unsigned int i = 0; i < data.space.size(); ++i,++index)\n                        new_sinc_ql[index] = boost::math::sinc_pi(q_vectors_time[i]*from);\n\n            }\n            image::mat::vector_product(&*new_sinc_ql.begin(),&*data.space.begin(),&*data.odf.begin(),\n                                    image::dyndim(data.odf.size(),data.space.size()));\n        }\n        else\n            image::mat::vector_product(&*sinc_ql.begin(),&*data.space.begin(),&*data.odf.begin(),\n                                    image::dyndim(data.odf.size(),data.space.size()));\n    }\n};\n\nclass HQSpace2Odf  : public BaseProcess\n{\npublic:// recorded for scheme balanced\n    std::vector<image::vector<3,double> > q_vectors_time;\npublic:\n    std::vector<float> sinc_ql;\npublic:\n    bool hgqi = false;\n    std::vector<float> hraw;\n    std::vector<int> offset;\n    std::vector<float> scaling;\npublic:\n    virtual void init(Voxel& voxel)\n    {\n        if(voxel.bvalues.size() != 1)\n        {\n            hgqi = false;\n            return;\n        }\n        hgqi = true;\n        hraw.resize(voxel.dim.size());\n        int range = 2;\n        for(int dz = 0;dz <= range;++dz) // half sphere\n            for(int dy = -range;dy <= range;++dy)\n                for(int dx = -range;dx <= range;++dx)\n                {\n                    int r2 = dx*dx+dy*dy+dz*dz;\n                    voxel.bvalues.push_back(r2*500);\n                    image::vector<3> dir(dx,dy,dz);\n                    dir.normalize();\n                    voxel.bvectors.push_back(dir);\n                    offset.push_back(dx + dy*voxel.dim.width() + dz*voxel.dim.plane_size());\n                    scaling.push_back(std::exp(-r2));\n                }\n\n        unsigned int odf_size = voxel.ti.half_vertices_count;\n        float sigma = voxel.param[0]; //optimal 1.24\n        sinc_ql.resize(odf_size*voxel.bvalues.size());\n        // calculate reconstruction matrix\n        for (unsigned int j = 0,index = 0; j < odf_size; ++j)\n            for (unsigned int i = 0; i < voxel.bvalues.size(); ++i,++index)\n                sinc_ql[index] = voxel.bvectors[i]*\n                             image::vector<3,float>(voxel.ti.vertices[j])*\n                               std::sqrt(voxel.bvalues[i]*0.01506);\n\n        for (unsigned int index = 0; index < sinc_ql.size(); ++index)\n            sinc_ql[index] = voxel.r2_weighted ?\n                         base_function(sinc_ql[index]*sigma):\n                         boost::math::sinc_pi(sinc_ql[index]*sigma);\n\n    }\n    virtual void run(Voxel& voxel, VoxelData& data)\n    {\n        if(!hgqi)\n            return;\n        if(data.space[0] == 0)\n        {\n            hraw[data.voxel_index] = 0;\n            std::fill(data.odf.begin(),data.odf.end(),0.0f);\n            return;\n        }\n        hraw[data.voxel_index] = data.space[0];\n        auto I = image::make_image(voxel.dwi_data[0],voxel.dim);\n        data.space.resize(voxel.bvalues.size());\n        for(int i = 1;i < voxel.bvalues.size();++i)\n        {\n            int pos1 = data.voxel_index;\n            int pos2 = data.voxel_index;\n            pos1 += offset[i-1];\n            pos2 -= offset[i-1];\n            if(pos1 < 0 || pos1 >= voxel.dim.size())\n                pos1 = pos2;\n            if(pos2 < 0 || pos2 >= voxel.dim.size())\n                pos2 = pos1;\n            data.space[i] = std::fabs(data.space[0]-(I[pos1]+I[pos2])/2.0f)*scaling[i-1];\n        }\n\n        image::mat::vector_product(&*sinc_ql.begin(),&*data.space.begin(),&*data.odf.begin(),\n                                    image::dyndim(data.odf.size(),data.space.size()));\n    }\n    virtual void end(Voxel&,gz_mat_write& mat_writer)\n    {\n        if(hgqi)\n            mat_writer.write(\"hraw\",&hraw[0],1,hraw.size());\n    }\n};\n\nclass SchemeConverter : public BaseProcess\n{\n    QSpace2Odf from,to;\n    std::vector<int> piv;\n    std::vector<image::vector<3,float> > bvectors;\n    std::vector<float> bvalues;\n    std::vector<std::vector<unsigned short> > dwi;\n    std::vector<unsigned short> b0;\n    std::vector<float> A,Rt;\n    unsigned int total_value;\n    unsigned int total_negative_value;\npublic:\n    virtual void init(Voxel& voxel)\n    {\n\n        if(!voxel.file_name.empty())\n        {\n            std::ifstream read(voxel.file_name.c_str());\n            std::vector<float> values;\n            std::copy(std::istream_iterator<float>(read),std::istream_iterator<float>(),std::back_inserter(values));\n            for(unsigned int i = 0;i < values.size()/4;++i)\n            {\n                if(values[i*4] == 0.0)\n                    continue;\n                bvalues.push_back(voxel.param[1]);\n                bvectors.push_back(image::vector<3,float>(values[i*4+1],values[i*4+2],values[i*4+3]));\n            }\n        }\n        else\n        {\n            bvalues.resize(voxel.ti.half_vertices_count);\n            bvectors.resize(voxel.ti.half_vertices_count);\n            for (unsigned int index = 0; index < bvectors.size(); ++index)\n                bvectors[index] = voxel.ti.vertices[index];\n            std::fill(bvalues.begin(),bvalues.end(),voxel.param[1]); // set the output b-value\n        }\n\n        //allocated output image space\n        dwi.resize(bvalues.size());\n        for(unsigned int index = 0;index < dwi.size();++index)\n            dwi[index].resize(voxel.dim.size());\n\n\n        from.init(voxel);\n        voxel.bvalues.swap(bvalues);\n        voxel.bvectors.swap(bvectors);\n        to.init(voxel);\n        voxel.bvalues.swap(bvalues);\n        voxel.bvectors.swap(bvectors);\n\n        if(!from.b0_images.empty())\n            b0.resize(voxel.dim.size());\n\n        Rt.resize(dwi.size()*dwi.size());\n        image::mat::transpose(&*to.sinc_ql.begin(),&*Rt.begin(),image::dyndim(dwi.size(),dwi.size()));\n        A.resize(dwi.size()*dwi.size());\n        piv.resize(dwi.size());\n        image::mat::product_transpose(&*Rt.begin(),&*Rt.begin(),&*A.begin(),\n                                       image::dyndim(dwi.size(),dwi.size()),image::dyndim(dwi.size(),dwi.size()));\n        float max_value = *std::max_element(A.begin(),A.end());\n        for (unsigned int i = 0,index = 0; i < dwi.size(); ++i,index += dwi.size() + 1)\n            A[index] += max_value*voxel.param[2];\n        image::mat::lu_decomposition(A.begin(),piv.begin(),image::dyndim(dwi.size(),dwi.size()));\n\n        total_negative_value = 0;\n        total_value = 0;\n\n        voxel.recon_report\n                << \" The converted HARDI has a total of \" << dwi.size() << \" diffusion sampling directions.\";\n    }\n\n    virtual void run(Voxel& voxel, VoxelData& data)\n    {\n        if(!from.b0_images.empty())\n        {\n            b0[data.voxel_index] = data.space[from.b0_images.front()];\n            data.space[from.b0_images.front()] = 0;\n        }\n        from.run(voxel,data);\n        std::vector<float> hardi_data(dwi.size()),tmp(dwi.size());\n        image::mat::vector_product(&*Rt.begin(),&*data.odf.begin(),&*tmp.begin(),image::dyndim(dwi.size(),dwi.size()));\n        image::mat::lu_solve(&*A.begin(),&*piv.begin(),&*tmp.begin(),&*hardi_data.begin(),image::dyndim(dwi.size(),dwi.size()));\n        for(unsigned int index = 0;index < dwi.size();++index)\n        {\n            if(hardi_data[index] < 0.0)\n                ++total_negative_value;\n            else\n                dwi[index][data.voxel_index] = hardi_data[index];\n            ++total_value;\n        }\n    }\n    virtual void end(Voxel& voxel,gz_mat_write& mat_writer)\n    {\n        voxel.recon_report\n                << \" The percentage of the negative signals was \" << (float)100.0*total_negative_value/(float)total_value << \"%.\";\n        std::vector<float> b_table(4); // space for b0\n        for (unsigned int index = 0;index < bvectors.size();++index)\n        {\n            b_table.push_back(bvalues.front());\n            std::copy(bvectors[index].begin(),bvectors[index].end(),std::back_inserter(b_table));\n        }\n        mat_writer.write(\"b_table\",&b_table[0],4,b_table.size()/4);\n        unsigned int image_num = 0;\n        if(!b0.empty())\n        {\n            mat_writer.write(\"image0\",&b0[0],1,b0.size());\n            ++image_num;\n        }\n        for (unsigned int index = 0;index < dwi.size();++index)\n        {\n            std::ostringstream out;\n            out << \"image\" << image_num;\n            mat_writer.write(out.str().c_str(),&(dwi[index][0]),1,dwi[index].size());\n            ++image_num;\n        }\n    }\n};\n\ntemplate<class value_type>\nvalue_type sinint(value_type x)\n{\n    bool sgn = x > 0;\n    x = std::fabs(x);\n    value_type eps = 1e-15f;\n    value_type x2 = x*x;\n    value_type si;\n    if(x == 0.0)\n        return 0.0;\n    if(x <= 16.0)\n    {\n        value_type xr = x;\n        si = x;\n        for(unsigned int k = 1;k <= 40;++k)\n        {\n            si += (xr *= -0.5*(value_type)(2*k-1)/(value_type)k/(value_type)(4*k*(k+1)+1)*x2);\n            if(std::fabs(xr) < std::fabs(si)*eps)\n                break;\n        }\n        return sgn ? si:-si;\n    }\n\n    if(x <= 32.0)\n    {\n        unsigned int m = std::floor(47.2+0.82*x);\n        std::vector<double> bj(m+1);\n        value_type xa1 = 0.0f;\n        value_type xa0 = 1.0e-100f;\n        for(unsigned int k=m;k>=1;--k)\n        {\n            value_type xa = 4.0*(value_type)k*xa0/x-xa1;\n            bj[k-1] = xa;\n            xa1 = xa0;\n            xa0 = xa;\n        }\n        value_type xs = bj[0];\n        for(unsigned int k=3;k <= m;k += 2)\n            xs += 2.0*bj[k-1];\n        for(unsigned int k=0;k < m;++k)\n            bj[k] /= xs;\n        value_type xr = 1.0;\n        value_type xg1 = bj[0];\n        for(int k=2;k <= m;++k)\n            xg1 += bj[k-1]*(xr *= 0.25*(2*k-3)*(2*k-3)/((k-1)*(2*k-1)*(2*k-1))*x);\n        xr = 1.0;\n        value_type xg2 = bj[0];\n        for(int k=2;k <= m;++k)\n            xg2 += bj[k-1]*(xr *= 0.25*(2*k-5)*(2*k-5)/((k-1)*(2*k-3)*(2*k-3))*x);\n        si = x*std::cos(x/2.0)*xg1+2.0*std::sin(x/2.0)*xg2-std::sin(x);\n        return sgn ? si:-si;\n    }\n\n    value_type xr = 1.0;\n    value_type xf = 1.0;\n    for(unsigned int k=1;k <= 9;++k)\n        xf += (xr *= -2.0*k*(2*k-1)/x2);\n    xr = 1.0/x;\n    value_type xg = xr;\n    for(unsigned int k=1;k <= 8;++k)\n        xg += (xr *= -2.0*(2*k+1)*k/x2);\n    si = 1.570796326794897-xf*std::cos(x)/x-xg*std::sin(x)/x;\n    return sgn ? si:-si;\n}\n\n\nclass QSpaceSpectral  : public BaseProcess\n{\npublic:\n    static const int max_length = 50; // 50 microns\n    std::vector<unsigned int> b0_images;\n    std::vector<std::vector<float> > cdf,dis,cdfw,disw;\npublic:\n    virtual void init(Voxel& voxel)\n    {\n        b0_images.clear();\n        for(unsigned int index = 0;index < voxel.bvalues.size();++index)\n            if(voxel.bvalues[index] == 0)\n                b0_images.push_back(index);\n        if(b0_images.size() > 1)\n            throw std::runtime_error(\"Correct B0 failed. Two b0 images found in src file\");\n\n        float diffusion_time = voxel.param[1];\n        float diffusion_length = std::sqrt(6.0*3.0*diffusion_time); // sqrt(6Dt)\n        dis.clear();\n        cdf.clear();\n        disw.clear();\n        cdfw.clear();\n        dis.resize(max_length);\n        cdf.resize(max_length);\n        disw.resize(max_length);\n        cdfw.resize(max_length);\n        for(unsigned int n = 0;n < max_length;++n) // from 0 micron to 49 microns\n        {\n            // calculate the diffusion length ratio\n            float sigma = ((float)n)/diffusion_length;\n\n            dis[n].resize(voxel.dim.size());\n            cdf[n].resize(voxel.dim.size());\n\n            disw[n].resize(voxel.bvalues.size());\n            cdfw[n].resize(voxel.bvalues.size());\n            for(unsigned int index = 0;index < voxel.bvalues.size();++index)\n            {\n                // 2pi*L*q = sigma*sqrt(6D*b_value)\n                double lq_2pi = sigma*std::sqrt(voxel.bvalues[index]*0.018);\n                disw[n][index] = boost::math::sinc_pi(lq_2pi);\n                cdfw[n][index] = (voxel.bvalues[index] == 0.0 ?\n                                 sigma : sinint(lq_2pi)/std::sqrt(voxel.bvalues[index]*0.018));\n            }\n        }\n    }\n    virtual void run(Voxel& voxel, VoxelData& data)\n    {\n        if(b0_images.size() == 1 && voxel.half_sphere)\n            data.space[b0_images.front()] *= 0.5;\n        for(unsigned int index = 0;index < max_length;++index)\n        {\n            dis[index][data.voxel_index] =\n                    image::vec::dot(data.space.begin(),data.space.end(),disw[index].begin());\n            cdf[index][data.voxel_index] =\n                    image::vec::dot(data.space.begin(),data.space.end(),cdfw[index].begin());\n            // make sure that cdf is increamental\n            if(index && cdf[index][data.voxel_index] < cdf[index-1][data.voxel_index])\n                cdf[index][data.voxel_index] = cdf[index-1][data.voxel_index];\n            // make sure that dis is positive\n            if(dis[index][data.voxel_index] < 0.0)\n                dis[index][data.voxel_index] = 0.0;\n        }\n    }\n    virtual void end(Voxel& voxel,gz_mat_write& mat_writer)\n    {\n        for(unsigned int index = 0;index < max_length;++index)\n        {\n            std::ostringstream out;\n            out << \"pdf_\" << index << \"um\";\n            mat_writer.write(out.str().c_str(),&*dis[index].begin(),1,dis[index].size());\n\n        }\n        for(unsigned int index = 0;index < max_length;++index)\n        {\n            std::ostringstream out;\n            out << \"cdf_\" << index << \"um\";\n            mat_writer.write(out.str().c_str(),&*cdf[index].begin(),1,cdf[index].size());\n        }\n        mat_writer.write(\"fa0\",&*dis[0].begin(),1,dis[0].size());\n        std::vector<short> index0(voxel.dim.size());\n        mat_writer.write(\"index0\",&*index0.begin(),1,index0.size());\n    }\n};\n\nclass RestrictedDiffusionImaging  : public BaseProcess\n{\nprivate:\n    std::vector<std::vector<float> > rdi;\npublic:\n    virtual void init(Voxel& voxel)\n    {\n        float sigma = voxel.param[0]; //optimal 1.24\n        if(!voxel.output_rdi)\n            return;\n        for(float L = 0.2f;L <= sigma;L+= 0.2f)\n        {\n            rdi.push_back(std::vector<float>());\n            rdi.back().resize(voxel.bvalues.size());\n            for(unsigned int index = 0;index < voxel.bvalues.size();++index)\n            {\n                float q = std::sqrt(voxel.bvalues[index]*0.018);\n                rdi.back()[index] = (q > 0)? sinint(L*q)/q: L;\n            }\n        }\n    }\n    virtual void run(Voxel& voxel, VoxelData& data)\n    {\n        if(!voxel.output_rdi)\n            return;\n        float last_value = 0;\n        std::vector<float> rdi_values(rdi.size());\n        for(unsigned int index = 0;index < rdi.size();++index)\n        {\n            // force incremental\n            rdi_values[index] = std::max<float>(last_value,image::vec::dot(rdi[index].begin(),rdi[index].end(),data.space.begin()));\n            last_value = rdi_values[index];\n        }\n        data.rdi.swap(rdi_values);\n    }\n};\n#endif//DDI_PROCESS_HPP\n", "meta": {"hexsha": "bd276450a5b09a6a18920c24b502a314ac72efc2", "size": 18104, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "libs/dsi/gqi_process.hpp", "max_stars_repo_name": "cbutakoff/DSI-Studio", "max_stars_repo_head_hexsha": "d77dffa4526d66da421fa84f7187e85bca6bce7c", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "libs/dsi/gqi_process.hpp", "max_issues_repo_name": "cbutakoff/DSI-Studio", "max_issues_repo_head_hexsha": "d77dffa4526d66da421fa84f7187e85bca6bce7c", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "libs/dsi/gqi_process.hpp", "max_forks_repo_name": "cbutakoff/DSI-Studio", "max_forks_repo_head_hexsha": "d77dffa4526d66da421fa84f7187e85bca6bce7c", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.0983606557, "max_line_length": 132, "alphanum_fraction": 0.529109589, "num_tokens": 4907, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.8311430645886583, "lm_q2_score": 0.3960681662740417, "lm_q1q2_score": 0.3291893095030173}}
{"text": "#include <cstddef>\r\n\r\n#include <gmpxx.h>\r\n#include <nfl.hpp>\r\n#include <armadillo>\r\n\r\n\r\n#include \"utils.h\"\r\n#include \"math.h\"\r\n#include <fstream>\r\n#include <time.h>\r\n\r\n#define THREADS 40    // for parallel processing. this is not important\r\n#define NUM_PRIME 6   // Numper of plaintext modulus for q=q0*q1*..*q5\r\n#define NUM_PRIME_EXT 13  // Numper of plaintext modulus for Q=q0*q1*...*q12; Q>4096*q^2\r\n#define t 33      // plaintext modulus\r\n\r\n#include \"aws/main.c\"\r\n#include \"aws/hw_interface.c\"\r\n#include \"aws/poly_functions.h\"\r\n#include \"aws/primitive_root.c\"\r\n#include \"aws/Gaussian_sampler.c\"\r\n#include \"aws/basic_ntt_large.c\"\r\n#include \"aws/homomorphic_functions.c\"\r\n\r\n\r\n\r\n/// include the FV homomorphic encryption library\r\nnamespace FV {\r\nnamespace params {\r\n//ciphertext modulus\r\nusing poly_t = nfl::poly_from_modulus<uint32_t, 1 << 12, 180>;\r\n//plaintext modulus\r\ntemplate <typename T>\r\nstruct plaintextModulus;\r\ntemplate <>\r\nstruct plaintextModulus<mpz_class> {\r\n  static mpz_class value_mpz;\r\n  static unsigned long bits_in_moduli_product;\r\n  static mpz_class product_mpz;\r\n  static mpz_class value() {return value_mpz;}\r\n  static mpz_class product() { return product_mpz;} \r\n  static void reset() {value_mpz = product();}\r\n};\r\n\r\n//noise with the standard deviation \r\nusing gauss_struct = nfl::gaussian<uint16_t, uint32_t, 2>;\r\nusing gauss_t = nfl::FastGaussianNoise<uint16_t, uint32_t, 2>;\r\ngauss_t fg_prng_sk(102.0, 80, 1 << 12);\r\ngauss_t fg_prng_evk(102.0, 80, 1 << 12);\r\ngauss_t fg_prng_pk(102.0, 80, 1 << 12);\r\ngauss_t fg_prng_enc(102.0, 80, 1 << 12);\r\n}\r\n}  // namespace FV::params\r\n#include \"FV.hpp\"\r\n\r\nusing namespace FV;\r\n\r\n//plaintext modulus initialisation\r\n//mpz_class params::plaintextModulus<mpz_class>::value_mpz = mpz_class(\"2305567963945518424753102147331756070\");\r\n//unsigned long params::plaintextModulus<mpz_class>::bits_in_moduli_product = 121;\r\n//const size_t plaintextModuli[25] = {2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97};\r\n\r\nconst size_t nPltxtModuli = 1; //13;\r\nconst char* plaintextModuli[nPltxtModuli] = {\"33\"}; //{\"269\", \"271\", \"277\", \"281\", \"283\", \"285\", \"286\", \"287\", \"289\", \"293\", \"307\", \"311\", \"313\"};\r\nmpz_class params::plaintextModulus<mpz_class>::value_mpz = mpz_class(\"33\"); //mpz_class(\"95059483533087812461171515276210\");\r\nmpz_class params::plaintextModulus<mpz_class>::product_mpz = mpz_class(\"33\"); //mpz_class(\"95059483533087812461171515276210\");\r\nunsigned long params::plaintextModulus<mpz_class>::bits_in_moduli_product = 6; //107;\r\n\r\nlong long int q_factors[6] = {1068564481, 1069219841, 1070727169, 1071513601, 1072496641, 1073479681};\r\n\r\nint nWindow = 2;\r\nsize_t cut_point = 385;\r\nsize_t cut_point_init = 2048;\r\ndouble scalar = 1.0;\r\n\r\n//new bases satisfying x^(w+1) - x^w - x - 1\r\ndouble get_base(int nWindow)\r\n  {\r\n    \r\n    if (nWindow == 1) //balanced ternary\r\n      return 3.0;\r\n\r\n    /*\r\n    if (nWindow == 2) //NAF\r\n      return 2.0;\r\n    */\r\n\r\n    //w-NIBNAF 1 to 10\r\n    {\r\n      if (nWindow == 2)\r\n        return 1.8392867552141611325518525646532866004241787460976;\r\n\r\n      if (nWindow == 3)\r\n        return 1.6180339887498948482045868343656381177203091798058;\r\n\r\n      if (nWindow == 4)\r\n        return 1.4970940487627966489512130973325937490728546766869;\r\n\r\n      if (nWindow == 5)\r\n        return 1.4196327628229445453504082292735940219073674584302;\r\n\r\n      if (nWindow == 6)\r\n        return 1.3652547066198611671464498103655204758472477135513;\r\n\r\n      if (nWindow == 7)\r\n        return 1.3247179572447460259609088544780973407344040569017;\r\n\r\n      if (nWindow == 8)\r\n        return 1.2931880356431841941707667071685055909483716918496;\r\n\r\n      if (nWindow == 9)\r\n        return 1.2678747746500370400017559167241184676895964302182;\r\n\r\n      if (nWindow == 10)\r\n        return 1.2470478623827932649094238570056113971385190030591;\r\n    }\r\n\r\n    //w-NIBNAF 11 to 100\r\n    {\r\n      if (nWindow == 11)\r\n        return 1.2295736071100086329887386204121888679687037670927;\r\n\r\n      if (nWindow == 12)\r\n        return 1.2146762120476157129198636059193192938594588768164;\r\n\r\n      if (nWindow == 13)\r\n        return 1.2018057285163738528520906252419881981195398056701;\r\n\r\n      if (nWindow == 14)\r\n        return 1.1905607496486082713018303653703967801857755824448;\r\n\r\n      if (nWindow == 15)\r\n        return 1.1806409911774026481504448588913502216577441979741;\r\n\r\n      if (nWindow == 16)\r\n        return 1.1718170471523075566771663052212383397216962084694;\r\n\r\n      if (nWindow == 17)\r\n        return 1.1639104494162406336126941752042207599347724717665;\r\n\r\n      if (nWindow == 18)\r\n        return 1.1567801397580809986131240703127383025253262481968;\r\n\r\n      if (nWindow == 19)\r\n        return 1.1503130616325995993026690082133373527130019041142;\r\n\r\n      if (nWindow == 20)\r\n        return 1.1444174725832161626875846283466857591506934154418;\r\n\r\n      if (nWindow == 21)\r\n        return 1.1390180978367039311061050513541557267654562620474;\r\n\r\n      if (nWindow == 22)\r\n        return 1.1340525571155748015425550211963430520246532358660;\r\n\r\n      if (nWindow == 23)\r\n        return 1.1294686891043132405390856649505389694782148004453;\r\n\r\n      if (nWindow == 24)\r\n        return 1.1252225198891815600034632458396451135471924297708;\r\n\r\n      if (nWindow == 25)\r\n        return 1.1212767007055639871629649459455138969099749818720;\r\n\r\n      if (nWindow == 26)\r\n        return 1.1175992926254076373185944258471520189189579833838;\r\n\r\n      if (nWindow == 27)\r\n        return 1.1141628110919165564713213821269592747564884588843;\r\n\r\n      if (nWindow == 28)\r\n        return 1.1109434674132254722845602394565531011358431290242;\r\n\r\n      if (nWindow == 29)\r\n        return 1.1079205611987054156733035059349058495250568866966;\r\n\r\n      if (nWindow == 30)\r\n        return 1.1050759896534704914828437035174681978163852172157;\r\n\r\n      if (nWindow == 31)\r\n        return 1.1023938481982226935834400582367270444653255359008;\r\n\r\n      if (nWindow == 32)\r\n        return 1.0998601030865190901488708868155197744763125360584;\r\n\r\n      if (nWindow == 33)\r\n        return 1.0974623212456344568114674971201853707406720244621;\r\n\r\n      if (nWindow == 34)\r\n        return 1.0951894459454329668968376980462752229161599569424;\r\n\r\n      if (nWindow == 35)\r\n        return 1.0930316094306794118473936206486052467737901142121;\r\n\r\n      if (nWindow == 36)\r\n        return 1.0909799755661898972865248945852075581009024451312;\r\n      \r\n      if (nWindow == 37)\r\n        return 1.0890266070042362704881318175355130756487525189390;\r\n\r\n      if (nWindow == 38)\r\n        return 1.0871643525064931522699464569032511818713235312984;\r\n\r\n      if (nWindow == 39)\r\n        return 1.0853867509230741140012743575970770458849292867892;\r\n\r\n      if (nWindow == 40)\r\n        return 1.0836879490105876789251155390977031736531038710385;\r\n\r\n      if (nWindow == 41)\r\n        return 1.0820626308051650089830897336686905975127094771450;\r\n\r\n      if (nWindow == 42)\r\n        return 1.0805059566889007177981902046073533593839033502744;\r\n\r\n      if (nWindow == 43)\r\n        return 1.0790135106244581514599317979091616322143887074312;\r\n\r\n      if (nWindow == 44)\r\n        return 1.0775812543018633508928058659218478176294808217915;\r\n\r\n      if (nWindow == 45)\r\n        return 1.0762054871583064426826478257156313731511473873510;\r\n\r\n      if (nWindow == 46)\r\n        return 1.0748828114072338403878740559132235982405408440652;\r\n\r\n      if (nWindow == 47)\r\n        return 1.0736101013557421173242037011146471806122586719155;\r\n\r\n      if (nWindow == 48)\r\n        return 1.0723844764059388089235768726602724684080573605880;\r\n\r\n      if (nWindow == 49)\r\n        return 1.0712032772317156316008578877038328699844811722388;\r\n\r\n      if (nWindow == 50)\r\n        return 1.0700640447013644706333800260072570977350330962720;\r\n\r\n      if (nWindow == 51)\r\n        return 1.0689645011818732925166981592649414599744885595665;\r\n\r\n      if (nWindow == 52)\r\n        return 1.0679025339151187378061126877148759562900707005554;\r\n\r\n      if (nWindow == 53)\r\n        return 1.0668761802015570108952286273234822652588301542193;\r\n\r\n      if (nWindow == 54)\r\n        return 1.0658836141650318865155303354023270361432918090447;\r\n\r\n      if(nWindow == 55)\r\n        return 1.0649231349042766706356389432046818667090248597406;\r\n\r\n      if(nWindow == 56)\r\n        return 1.0639931558636426215882765423529878718023906341811;\r\n      \r\n      if(nWindow == 57)\r\n        return 1.0630921952783968216570508515097669203481628264943;\r\n      \r\n      if(nWindow == 58)\r\n        return 1.0622188675692958083119878563537629378789560448259;\r\n      \r\n      if(nWindow == 59)\r\n        return 1.0613718755776280480104437706097108739635137944843;\r\n      \r\n      if(nWindow == 60)\r\n        return 1.0605500035459967772616084987669367835986122487804;\r\n      \r\n      if(nWindow == 61)\r\n        return 1.0597521107621704105673857853470305046522202507455;\r\n      \r\n      if(nWindow == 62)\r\n        return 1.0589771257936792284736230780338842254701477332678;\r\n      \r\n      if(nWindow == 63)\r\n        return 1.0582240412497485658018116853846982707904424110643;\r\n      \r\n      if(nWindow == 64)\r\n        return 1.0574919090148499361768692902607214518583741005703;\r\n      \r\n      if(nWindow == 65)\r\n        return 1.0567798359048057771819532594078426816706611594270;\r\n      \r\n      if(nWindow == 66)\r\n        return 1.0560869797021541996385404859585295082582992589701;\r\n      \r\n      if(nWindow == 67)\r\n        return 1.0554125455324960414098513039801597889592206209498;\r\n      \r\n      if(nWindow == 68)\r\n        return 1.0547557825479160414751180280552090628615859612300;\r\n      \r\n      if(nWindow == 69)\r\n        return 1.0541159808873845349967671477462470620426734057202;\r\n      \r\n      if(nWindow == 70)\r\n        return 1.0534924688873831287312278462496847139420104205103;\r\n      \r\n      if(nWindow == 71)\r\n        return 1.0528846105189230165477906339099148500819293739834;\r\n      \r\n      if(nWindow == 72)\r\n        return 1.0522918030296937871056012335913759608378266319024;\r\n      \r\n      if(nWindow == 73)\r\n        return 1.0517134747723413743707651258736424662698295590868;\r\n      \r\n      if(nWindow == 74)\r\n        return 1.0511490832018668949138902751972394286036740594394;\r\n      \r\n      if(nWindow == 75)\r\n        return 1.0505981130268983524239653297882293653946042816551;\r\n      \r\n      if(nWindow == 76)\r\n        return 1.0500600745011444825581220680601080667537795398004;\r\n      \r\n      if(nWindow == 77)\r\n        return 1.0495345018427200915381005422467905913268829810698;\r\n      \r\n      if(nWindow == 78)\r\n        return 1.0490209517702572903937384679485953360119688648475;\r\n      \r\n      if(nWindow == 79)\r\n        return 1.0485190021458062019887408790551133500863805324761;\r\n      \r\n      if(nWindow == 80)\r\n        return 1.0480282507154986008552796945121264038447575968988;\r\n      \r\n      if(nWindow == 81)\r\n        return 1.0475483139398129140559519452232999110041756012404;\r\n      \r\n      if(nWindow == 82)\r\n        return 1.0470788259060515552523553870669032437210620450187;\r\n      \r\n      if(nWindow == 83)\r\n        return 1.0466194373163325546579474481046989704095565996424;\r\n      \r\n      if(nWindow == 84)\r\n        return 1.0461698145450163624894212951029446866587237686034;\r\n      \r\n      if(nWindow == 85)\r\n        return 1.0457296387600438207045902923405073352826152053866;\r\n      \r\n      if(nWindow == 86)\r\n        return 1.0452986051031598590789909225681976644747047759591;\r\n      \r\n      if(nWindow == 87)\r\n        return 1.0448764219244458230069835603233979416898643808810;\r\n      \r\n      if(nWindow == 88)\r\n        return 1.0444628100669870516749535605290037867219037178514;\r\n      \r\n      if(nWindow == 89)\r\n        return 1.0440575021978662927629217690620088667895841956651;\r\n      \r\n      if(nWindow == 90)\r\n        return 1.0436602421820020743965976843635199297042685476647;\r\n      \r\n      if(nWindow == 91)\r\n        return 1.0432707844956480576806589181887505757910248197611;\r\n      \r\n      if(nWindow == 92)\r\n        return 1.0428888936766380201420180055786055591309635442539;\r\n      \r\n      if(nWindow == 93)\r\n        return 1.0425143438087044397437498036014050022150840948030;\r\n      \r\n      if(nWindow == 94)\r\n        return 1.0421469180374192889416741909421229772181216938142;\r\n      \r\n      if(nWindow == 95)\r\n        return 1.0417864081155059389651163040230755998480399741647;\r\n      \r\n      if(nWindow == 96)\r\n        return 1.0414326139754530852822641801944039873617921374426;\r\n      \r\n      if(nWindow == 97)\r\n        return 1.0410853433275271756615689083498186489442866497419;\r\n      \r\n      if(nWindow == 98)\r\n        return 1.0407444112814305899516580572436427374723116312638;\r\n      \r\n      if(nWindow == 99)\r\n        return 1.0404096399899902452476451942062410201587631058652;\r\n\r\n      if(nWindow == 100)\r\n        return 1.0400808583133866839905840996075171078220420079076;\r\n    }\r\n\r\n    //w-NIBNAF > 100\r\n    {\r\n      if(nWindow == 183)\r\n        return 1.0244312672844357862292237798272061378962120044720;\r\n\r\n      if(nWindow == 200)\r\n        return 1.0227024500223823696378909495239952676612396369880;\r\n\r\n      if(nWindow == 218)\r\n        return 1.0211391019952924292065439951738700325839419759453;\r\n\r\n      if(nWindow == 300)\r\n        return 1.0162081488908486099200887179950675401202202159172;\r\n\r\n      if(nWindow == 400)\r\n        return 1.0127372388036767299734723279220215835671835241309;\r\n\r\n      if(nWindow == 436)\r\n        return 1.0118466093615813680780576752210457693960703317586;\r\n\r\n      if(nWindow == 440)\r\n        return 1.0117558615275276266139666604128046148929763919207;  \r\n\r\n      if(nWindow == 450)\r\n        return 1.0115354272627753917981256263329895694631883907344;\r\n\r\n      if(nWindow == 600)\r\n        return 1.0090458503916447572704580506673508630558701015244;\r\n\r\n      if(nWindow == 900)\r\n        return 1.0064058603440620819016414846825845191663892864499;\r\n\r\n      if(nWindow == 950)\r\n        return 1.0061164903998645515559733901859907288672398849769;\r\n    }  \r\n\r\n    printf(\"No base found\\n\");\r\n    exit(1);\r\n  }\r\n\r\ndouble mse(const arma::mat& output, const arma::mat& test)\r\n  {\r\n    if(output.n_rows > test.n_rows)\r\n    {\r\n      printf(\"MSE: too many output values\\n\");\r\n      exit(1);\r\n    }\r\n\r\n    int nCoords = output.n_rows;\r\n\r\n    double res(0.0);\r\n    for(int i = 0; i < nCoords; i++)\r\n    {\r\n      res += (output(i, 0) - test(i,0)) * (output(i, 0) - test(i, 0));\r\n    }\r\n    res /= nCoords;\r\n\r\n    return res;\r\n  }\r\n\r\ndouble mape(const arma::mat& output, const arma::mat& test)\r\n  {\r\n    if(output.n_rows > test.n_rows)\r\n    {\r\n      printf(\"MSE: too many output values\\n\");\r\n      exit(1);\r\n    }\r\n\r\n    int nCoords = output.n_rows;\r\n\r\n    double res(0.0);\r\n    for(int i = 0; i < nCoords; i++)\r\n    {\r\n      res += std::abs((output(i, 0) - test(i,0)) / test(i, 0));\r\n    }\r\n    res /= nCoords;\r\n\r\n    return res;\r\n  }  \r\n\r\nvoid convert_to_balanced(std::array<mpz_t, params::poly_t::degree>& bal_repr, double fValue, size_t nIntPrec, size_t nFracPrec)\r\n  {\r\n    uint32_t d = params::poly_t::degree; //should be 4096\r\n\r\n    int tmp = int(floor(fValue * pow(3.0, nFracPrec * 1.0)+0.5));\r\n    bool sign = true; //corresponds to a positive sign, otherwise to a negative\r\n\r\n    size_t nLengthPrec = nFracPrec + nIntPrec;\r\n\r\n    if(tmp < 0)\r\n    {\r\n      sign = false;\r\n      tmp *= -1;\r\n    }\r\n    //conversion to the ternary representation\r\n    int* r = (int*)malloc(4 * nLengthPrec);\r\n    int i;\r\n    for (i = 0; i < nLengthPrec; i++) r[i] = 0;\r\n    int loc = 0;\r\n    while (tmp > 0) \r\n    {\r\n      r[loc++] = tmp % 3;\r\n      tmp = tmp/3;\r\n\r\n      if (loc == nLengthPrec and tmp != 0) \r\n      {\r\n        printf(\"Overflow in toBase, value: %f\\n\", fValue);\r\n        exit(1);\r\n      }\r\n    }\r\n\r\n    //final conversion to the balanced ternary representation\r\n    for (i = 0; i < nLengthPrec; i++) \r\n    {\r\n      if(r[i] == 2)\r\n      {\r\n        r[i] = -1;\r\n        if((i + 1) < nLengthPrec)\r\n        {\r\n          r[i + 1] += 1;\r\n          int j = i + 1;\r\n          while(r[j] == 3)\r\n          {\r\n            r[j] = 0;\r\n            j++;\r\n            if(j == nLengthPrec)\r\n            {\r\n              printf(\"Overflow in toBase, value: %f\\n\", fValue);\r\n              exit(1);            \r\n            }\r\n            r[j] += 1;\r\n          }\r\n        }\r\n        else\r\n        {\r\n          printf(\"Overflow in toBase, value: %f\\n\", fValue);\r\n          exit(1);\r\n        }\r\n      }\r\n      if(!sign) r[i] *= -1;\r\n    }\r\n\r\n    //assign coefficients to a poly\r\n    for (size_t i = nFracPrec; i < nLengthPrec; i ++)\r\n    {\r\n      mpz_set_si(bal_repr[i - nFracPrec], r[i]);\r\n      if(r[i] < 0) mpz_add(bal_repr[i - nFracPrec], bal_repr[i - nFracPrec], params::plaintextModulus<mpz_class>::value().get_mpz_t());\r\n    }\r\n    for (size_t i = 0; i < nFracPrec; i++)\r\n    {\r\n      mpz_set_si(bal_repr[d - nFracPrec + i], -r[i]);\r\n      if (-r[i] < 0) mpz_add(bal_repr[d - nFracPrec + i], bal_repr[d - nFracPrec + i], params::plaintextModulus<mpz_class>::value().get_mpz_t());\r\n    }\r\n\r\n    free(r);\r\n  }\r\n\r\nmpf_class bal_to_float(std::array<mpz_t, params::poly_t::degree>& p, mpz_t modulusForConversion = params::plaintextModulus<mpz_class>::value().get_mpz_t())\r\n  {\r\n    const size_t d = params::poly_t::degree;\r\n\r\n    mpf_t res;\r\n    mpf_init(res);\r\n    \r\n    mpf_t modulus;\r\n    mpf_init(modulus);\r\n    mpf_set_z(modulus, modulusForConversion);\r\n\r\n    mpf_t half_modulus;\r\n    mpf_init(half_modulus);\r\n    mpf_div_ui(half_modulus, modulus, 2);\r\n\r\n    mpf_t base;\r\n    mpf_init_set_d(base, 3.0);\r\n\r\n    //integer part\r\n    for (int i = 0; i < d/2; i++)\r\n    {\r\n      mpf_t coef;\r\n      mpf_init(coef);\r\n      mpf_set_z(coef,p[i]);\r\n\r\n      mpf_t power;\r\n      mpf_init_set(power, base);\r\n      mpf_pow_ui(power, power, i);\r\n\r\n      if(mpf_sgn(coef) != 0)\r\n      {\r\n        if (mpf_cmp(coef, half_modulus) > 0)\r\n        {\r\n          mpf_sub(coef, coef, modulus);\r\n        }\r\n\r\n        //std::cout << i << \" \" << coef;\r\n\r\n        mpf_mul(coef, coef, power);\r\n\r\n        //std::cout << \" \" << coef;\r\n\r\n        mpf_add(res, res, coef);\r\n\r\n        //std::cout << \" \" << res << std::endl;\r\n      }\r\n      mpf_clears(coef, power, nullptr);\r\n    }\r\n\r\n    //fractional part \r\n    for (int i = d - 1; i >= d/2; i--)\r\n    {\r\n      mpf_t coef;\r\n      mpf_init(coef);\r\n      mpf_set_z(coef,p[i]);\r\n\r\n      if(mpf_sgn(coef) != 0)\r\n      {\r\n        if (mpf_cmp(coef, half_modulus) > 0)\r\n          mpf_sub(coef, coef, modulus);\r\n\r\n        mpf_t frac_exp;\r\n        mpf_init(frac_exp);\r\n        mpf_pow_ui(frac_exp, base, d - i );\r\n        mpf_ui_div(frac_exp, 1, frac_exp);\r\n\r\n        //std::cout << i << \" \" << coef;\r\n\r\n        mpf_mul(coef, coef, frac_exp);\r\n\r\n        //std::cout << \" \" << coef;\r\n\r\n        mpf_sub(res, res, coef);\r\n\r\n        //std::cout << \" \" << res << std::endl;\r\n\r\n        mpf_clear(frac_exp);\r\n      }\r\n      mpf_clear(coef);\r\n    }\r\n\r\n    mpf_class res_f = mpf_class(res);\r\n\r\n    mpf_clear(res);\r\n    mpf_clear(modulus);\r\n    mpf_clear(half_modulus);\r\n    mpf_clear(base);\r\n\r\n    return res_f;\r\n  }\r\n\r\nmpf_class bal_to_float(params::poly_p poly, mpz_t modulusForConversion = params::plaintextModulus<mpz_class>::value().get_mpz_t())\r\n  {\r\n    const size_t d = params::poly_t::degree;\r\n\r\n    std::array<mpz_t, params::poly_t::degree> p;\r\n    for (size_t j = 0; j < d; j++)\r\n    {\r\n      mpz_inits(p[j], nullptr);\r\n    }    \r\n\r\n    poly.poly2mpz(p);\r\n\r\n    mpf_class res_f = bal_to_float(p);\r\n\r\n    for (size_t j = 0; j < d; j++)\r\n    {\r\n      mpz_clears(p[j], nullptr);\r\n    }\r\n\r\n    //return res_f;\r\n    return res_f;\r\n  }  \r\n\r\nmpf_class naf_to_float(std::array<mpz_t, params::poly_t::degree>& p, size_t cut_point, mpz_t modulusForConversion = params::plaintextModulus<mpz_class>::value().get_mpz_t())\r\n  {\r\n    if (nWindow < 1)\r\n    {\r\n      printf(\"Wrong window for conversion!\\n\");\r\n      exit(1);\r\n    }\r\n\r\n    if(nWindow == 1)\r\n    {\r\n      return bal_to_float(p, modulusForConversion);\r\n    }\r\n\r\n    const size_t d = params::poly_t::degree;\r\n\r\n    if(cut_point > d-1)\r\n    {\r\n      printf(\"Wrong cut point!\\n\");\r\n      exit(1);\r\n    }\r\n\r\n    mpf_t res;\r\n    mpf_init(res);\r\n    \r\n    mpf_t modulus;\r\n    mpf_init(modulus);\r\n    mpf_set_z(modulus, modulusForConversion);\r\n\r\n    mpf_t half_modulus;\r\n    mpf_init(half_modulus);\r\n    mpf_div_ui(half_modulus, modulus, 2);\r\n\r\n    mpf_t base;\r\n\r\n    //positive base\r\n    mpf_init_set_d(base, get_base(nWindow));\r\n    //negative base\r\n    //mpf_init_set_d(base, -get_base(nWindow));\r\n    //integer part\r\n    for (int i = 0; i < cut_point; i++)\r\n    {\r\n      mpf_t coef;\r\n      mpf_init(coef);\r\n      mpf_set_z(coef,p[i]);\r\n\r\n      mpf_t power;\r\n      mpf_init_set(power, base);\r\n      mpf_pow_ui(power, power, i);\r\n\r\n      if(mpf_sgn(coef) != 0)\r\n      {\r\n        if (mpf_cmp(coef, half_modulus) > 0)\r\n        {\r\n          mpf_sub(coef, coef, modulus);\r\n        }\r\n\r\n        //std::cout << i << \" \" << coef;\r\n\r\n        mpf_mul(coef, coef, power);\r\n\r\n        //std::cout << \" \" << coef;\r\n\r\n        mpf_add(res, res, coef);\r\n\r\n        //std::cout << \" \" << res << std::endl;\r\n      }\r\n      mpf_clears(coef, power, nullptr);\r\n    }\r\n\r\n    //fractional part \r\n    for (int i = d - 1; i >= cut_point; i--)\r\n    {\r\n      mpf_t coef;\r\n      mpf_init(coef);\r\n      mpf_set_z(coef,p[i]);\r\n\r\n      if(mpf_sgn(coef) != 0)\r\n      {\r\n        if (mpf_cmp(coef, half_modulus) > 0)\r\n          mpf_sub(coef, coef, modulus);\r\n\r\n        mpf_t frac_exp;\r\n        mpf_init(frac_exp);\r\n        mpf_pow_ui(frac_exp, base, d - i );\r\n        mpf_ui_div(frac_exp, 1, frac_exp);\r\n\r\n        //std::cout << i << \" \" << coef;\r\n\r\n        mpf_mul(coef, coef, frac_exp);\r\n\r\n        //std::cout << \" \" << coef;\r\n\r\n        mpf_sub(res, res, coef);\r\n\r\n        //std::cout << \" \" << res << std::endl;\r\n\r\n        mpf_clear(frac_exp);\r\n      }\r\n      mpf_clear(coef);\r\n    }\r\n\r\n    mpf_class res_f = mpf_class(res);\r\n\r\n    mpf_clear(res);\r\n    mpf_clear(modulus);\r\n    mpf_clear(half_modulus);\r\n    mpf_clear(base);\r\n\r\n    return res_f;\r\n  }\r\n\r\nmpf_class naf_to_float(params::poly_p poly, size_t cut_point, mpz_t modulusForConversion = params::plaintextModulus<mpz_class>::value().get_mpz_t())\r\n  {\r\n    const size_t d = params::poly_t::degree;\r\n\r\n    std::array<mpz_t, params::poly_t::degree> p;\r\n    for (size_t j = 0; j < d; j++)\r\n    {\r\n      mpz_inits(p[j], nullptr);\r\n    }    \r\n\r\n    poly.poly2mpz(p);\r\n\r\n    mpf_class res = naf_to_float(p, cut_point, modulusForConversion);\r\n\r\n    for (size_t j = 0; j < d; j++)\r\n    {\r\n      mpz_clears(p[j], nullptr);\r\n    }\r\n\r\n    return res;\r\n  }   \r\n\r\nvoid convert_to_naf_wouter(std::array<mpz_t, params::poly_t::degree>& bal_repr, double fValue, size_t nIntPrec, size_t nFracPrec)\r\n  {\r\n    if (nWindow < 1)\r\n    {\r\n      printf(\"Wrong window for conversion!\\n\");\r\n      exit(1);\r\n    }\r\n\r\n    if(nWindow == 1)\r\n    {\r\n      convert_to_balanced(bal_repr, fValue, nIntPrec, nFracPrec);\r\n      return;\r\n    }\r\n\r\n    double base = get_base(nWindow);\r\n\r\n    uint32_t d = params::poly_t::degree; //should be 4096\r\n    double tmp = fValue * pow(base, nFracPrec * 1.0);\r\n    bool sign = true; //corresponds to a positive sign, otherwise to a negative\r\n\r\n    size_t nLengthPrec = nFracPrec + nIntPrec;\r\n\r\n    if(tmp < 0)\r\n    {\r\n      sign = false;\r\n      tmp *= -1;\r\n    }\r\n\r\n    int* r = (int*)malloc(4 * nLengthPrec);\r\n    for (int i = 0; i < nLengthPrec; i++) r[i]=0;\r\n\r\n    //conversion\r\n    while(fabs(tmp) > 0.5)\r\n    {\r\n      //printf(\"tmp: %f\\n\", tmp);\r\n      int digit = 1;\r\n      if (tmp < 0)\r\n      {\r\n        tmp=fabs(tmp);\r\n        digit = -1;\r\n      }\r\n      int r1 = int(floor(fmax(log(tmp-0.5)/log(base),0)));\r\n      int r2 = int(ceil(fmax(log(tmp-0.5)/log(base),0)));\r\n\r\n      double sumr1 = 0.5;\r\n      double sumr2 = 0.5;\r\n\r\n      if(floor(r1/nWindow) > 0)\r\n      {\r\n        for(int k = 1; k <= floor(r1/nWindow); k++)\r\n          sumr1 += pow(base, (r1 - k * nWindow) * 1.0);\r\n      }\r\n      if(floor(r2/nWindow) > 0)\r\n      {\r\n        for(int k = 1; k <= floor(r2/nWindow); k++)\r\n          sumr2 += pow(base, (r2 - k * nWindow) * 1.0);\r\n      }\r\n\r\n      if(fabs(tmp - pow(base, r1 * 1.0)) <= sumr1)\r\n      {\r\n        tmp -= pow(base, r1 * 1.0);\r\n        if(r1 >= nLengthPrec)\r\n        {\r\n          printf(\"Overflow in toBase, value: %f\\n\", fValue);\r\n          exit(1); \r\n        }\r\n        r[r1] = digit;\r\n      }\r\n      else if(fabs(tmp - pow(base, r2 * 1.0)) <= sumr2)\r\n      {\r\n        tmp -= pow(base, r2 * 1.0);\r\n        if(r2 >= nLengthPrec)\r\n        {\r\n          printf(\"Overflow in toBase, value: %f\\n\", fValue);\r\n          exit(1); \r\n        }\r\n        r[r2] = digit;\r\n      }\r\n      tmp *= digit;\r\n    }\r\n\r\n\r\n    for (int i = 0; i < nLengthPrec; i++) \r\n    {\r\n      if(!sign) r[i] *= -1;\r\n    }\r\n\r\n    //assign coefficients to a poly\r\n    for (size_t i = nFracPrec; i < nLengthPrec; i ++)\r\n    {\r\n      mpz_set_si(bal_repr[i - nFracPrec], r[i]);\r\n      if(r[i] < 0) mpz_add(bal_repr[i - nFracPrec], bal_repr[i - nFracPrec], params::plaintextModulus<mpz_class>::value().get_mpz_t());\r\n    }\r\n    for (size_t i = 0; i < nFracPrec; i++)\r\n    {\r\n      mpz_set_si(bal_repr[d - nFracPrec + i], -r[i]);\r\n      if (-r[i] < 0) mpz_add(bal_repr[d - nFracPrec + i], bal_repr[d - nFracPrec + i], params::plaintextModulus<mpz_class>::value().get_mpz_t());\r\n    }\r\n\r\n    free(r);\r\n  }\r\n\r\nvoid convert_to_naf_greedy(std::array<mpz_t, params::poly_t::degree>& bal_repr, double fValue, size_t nIntPrec, size_t nFracPrec)\r\n  {\r\n    if (nWindow < 1)\r\n    {\r\n      printf(\"Wrong window for conversion!\\n\");\r\n      exit(1);\r\n    }\r\n\r\n    if(nWindow == 1)\r\n    {\r\n      convert_to_balanced(bal_repr, fValue, nIntPrec, nFracPrec);\r\n      return;\r\n    }\r\n\r\n    double base = get_base(nWindow);\r\n\r\n    uint32_t d = params::poly_t::degree; //should be 4096\r\n    double tmp = fValue * pow(base, nFracPrec * 1.0);\r\n    bool sign = true; //corresponds to a positive sign, otherwise to a negative\r\n\r\n    size_t nLengthPrec = nFracPrec + nIntPrec;\r\n\r\n    if(tmp < 0)\r\n    {\r\n      sign = false;\r\n      tmp *= -1;\r\n    }\r\n\r\n    int* r = (int*)malloc(4 * nLengthPrec);\r\n    for (int i = 0; i < nLengthPrec; i++) r[i]=0;\r\n\r\n    //conversion\r\n    while(fabs(tmp) > 1.0)\r\n    {\r\n      //printf(\"tmp: %f\\n\", tmp);\r\n      int digit = 1;\r\n      if (tmp < 0)\r\n      {\r\n        tmp=fabs(tmp);\r\n        digit = -1;\r\n      }\r\n      int r1 = int(floor(fmax(log(tmp)/log(base),0)));\r\n      int r2 = int(ceil(fmax(log(tmp)/log(base),0)));\r\n\r\n      int cl_pow;\r\n\r\n      if(fabs(tmp - pow(base, r1 * 1.0)) <= fabs(tmp - pow(base, r2 * 1.0))) \r\n        cl_pow = r1;\r\n      else\r\n        cl_pow = r2;\r\n\r\n      if(cl_pow >= nLengthPrec)\r\n        {\r\n          printf(\"Overflow in toBase, value: %f\\n\", fValue);\r\n          exit(1); \r\n        } \r\n\r\n      tmp -= pow(base, cl_pow * 1.0);\r\n\r\n      //positive base\r\n      r[cl_pow] = digit;\r\n\r\n      tmp *= digit;     \r\n    }\r\n\r\n\r\n    for (int i = 0; i < nLengthPrec; i++) \r\n    {\r\n      if(!sign) r[i] *= -1;\r\n    }\r\n\r\n    //assign coefficients to a poly\r\n    for (size_t i = nFracPrec; i < nLengthPrec; i++)\r\n    {\r\n      /*\r\n      //negative base ->\r\n      if ((i - nFracPrec) % 2 == 1)\r\n        r[i] *= -1;\r\n      //<- negative base\r\n      */\r\n\r\n      mpz_set_si(bal_repr[i - nFracPrec], r[i]);\r\n      if(r[i] < 0) mpz_add(bal_repr[i - nFracPrec], bal_repr[i - nFracPrec], params::plaintextModulus<mpz_class>::value().get_mpz_t());\r\n    }\r\n    for (size_t i = 0; i < nFracPrec; i++)\r\n    {\r\n      /*\r\n      //negative base ->\r\n      if ((i - nFracPrec) % 2 == 1)\r\n        r[i] *= -1;\r\n      //<- negative base\r\n      */\r\n\r\n      mpz_set_si(bal_repr[d - nFracPrec + i], -r[i]);\r\n      if (-r[i] < 0) mpz_add(bal_repr[d - nFracPrec + i], bal_repr[d - nFracPrec + i], params::plaintextModulus<mpz_class>::value().get_mpz_t());\r\n    }\r\n\r\n    free(r);\r\n  }\r\n\r\nsize_t int_bits(double fValue)\r\n  {\r\n    double tmp = fabs(fValue);\r\n    double base = get_base(nWindow);\r\n\r\n    int r1 = int(floor(fmax(log(tmp)/log(base),0)));\r\n    int r2 = int(ceil(fmax(log(tmp)/log(base),0)));\r\n\r\n    if(fabs(tmp - pow(base, r1 * 1.0)) <= fabs(tmp - pow(base, r2 * 1.0))) \r\n        return r1 + 1;\r\n    else\r\n        return r2 + 1;\r\n  }\r\n//generate a random balanced ternary expansion with prescribed precisions\r\nparams::poly_p random_poly(size_t nIntPrec, size_t nFracPrec)\r\n  {\r\n    params::poly_p poly;\r\n    const size_t d = params::poly_t::degree;\r\n\r\n    //initiate array\r\n    std::array<mpz_t, params::poly_t::degree> poly_mpz;\r\n    for (size_t j = 0; j < d; j++)\r\n    {\r\n      mpz_inits(poly_mpz[j], nullptr);\r\n    }\r\n\r\n    //integer part\r\n    for(size_t j = 0; j < nIntPrec; j++)\r\n    {\r\n      int tmp = rand() % 3 - 1; \r\n      mpz_set_si(poly_mpz[j], tmp);\r\n      if(tmp < 0) mpz_add(poly_mpz[j], poly_mpz[j], params::plaintextModulus<mpz_class>::value().get_mpz_t());\r\n    }\r\n    \r\n    //fractional part\r\n    for(size_t j = d - 1; j > d - 1 - nFracPrec; j--)\r\n    {\r\n      int tmp = rand() % 3 - 1; \r\n      mpz_set_si(poly_mpz[j], tmp);\r\n      if(tmp < 0) mpz_add(poly_mpz[j], poly_mpz[j], params::plaintextModulus<mpz_class>::value().get_mpz_t());\r\n    }\r\n\r\n    //convert array to poly\r\n    poly.mpz2poly(poly_mpz);\r\n\r\n    //clean array\r\n    for (size_t j = 0; j < d; j++)\r\n    {\r\n      mpz_clears(poly_mpz[j], nullptr);\r\n    }\r\n\r\n    return poly;\r\n  }\r\n\r\n//infinity norm of a polynomial\r\nmpz_class max_coef(params::poly_p p)\r\n  {\r\n    const size_t d = params::poly_t::degree;\r\n\r\n    //initiate array\r\n    std::array<mpz_t, params::poly_t::degree> poly_mpz;\r\n    for (size_t j = 0; j < d; j++)\r\n    {\r\n      mpz_inits(poly_mpz[j], nullptr);\r\n    }\r\n\r\n    p.poly2mpz(poly_mpz);\r\n\r\n    mpz_t max;\r\n    mpz_init(max);\r\n\r\n    mpz_t modulus;\r\n    mpz_init(modulus);\r\n    mpz_set(modulus, params::plaintextModulus<mpz_class>::value().get_mpz_t());\r\n\r\n    mpz_t half_modulus;\r\n    mpz_init(half_modulus);\r\n    mpz_div_ui(half_modulus, modulus, 2);\r\n\r\n    for(size_t j = 0; j < d; j++)\r\n    {\r\n      if (mpz_cmp(poly_mpz[j], half_modulus) > 0)\r\n          mpz_sub(poly_mpz[j], poly_mpz[j], modulus);\r\n      if(mpz_cmp(poly_mpz[j], max) > 0)\r\n        mpz_set(max, poly_mpz[j]);\r\n    }\r\n\r\n    //clean array\r\n    for (size_t j = 0; j < d; j++)\r\n    {\r\n      mpz_clears(poly_mpz[j], nullptr);\r\n    }\r\n\r\n    return mpz_class(max); \r\n  }\r\n\r\n//noise of a ciphertext\r\nsize_t poly_noise(sk_t const &sk, pk_t const &pk, FV::ciphertext_t const &ct) \r\n  {\r\n    using P = params::poly_p;\r\n    const size_t d = P::degree;\r\n\r\n    P poly_m;\r\n    std::array<mpz_t, d> bal_repr;\r\n    for (size_t j = 0; j < d; j++)\r\n    {\r\n      mpz_inits(bal_repr[j], nullptr);\r\n    }\r\n    FV::decrypt_poly(bal_repr, sk, pk, ct);\r\n    poly_m.mpz2poly(bal_repr);\r\n\r\n    poly_m.ntt_pow_phi();\r\n\r\n    P numerator{ct.c0 + ct.c1 * sk.value -\r\n                nfl::shoup(poly_m * pk.delta, pk.delta_shoup)};\r\n    numerator.invntt_pow_invphi();\r\n    std::array<mpz_t, P::degree> poly_mpz = numerator.poly2mpz();\r\n\r\n    size_t logMax = 0;\r\n\r\n    for (size_t i = 0; i < P::degree; i++) {\r\n      util::center(poly_mpz[i], poly_mpz[i], P::moduli_product(),\r\n                   pk.evk->qDivBy2);\r\n      logMax = std::max(logMax, mpz_sizeinbase(poly_mpz[i], 2));\r\n    }\r\n\r\n    // Clean\r\n    for (size_t i = 0; i < P::degree; i++) {\r\n      mpz_clear(poly_mpz[i]);\r\n    }\r\n\r\n    for (size_t j = 0; j < d; j++)\r\n    {\r\n      mpz_clears(bal_repr[j], nullptr);\r\n    }\r\n\r\n    return logMax;\r\n  }\r\n\r\nvoid print_poly(params::poly_p const &poly, bool bPlaintext = false)\r\n  {\r\n    params::poly_p tmp_poly = poly;\r\n    mpz_t modulus;\r\n    mpz_init(modulus);\r\n    if(bPlaintext)\r\n      mpz_set(modulus, params::plaintextModulus<mpz_class>::value().get_mpz_t());\r\n    else\r\n      mpz_set(modulus, params::poly_p::moduli_product());\r\n\r\n    mpz_t half_modulus;\r\n    mpz_init(half_modulus);\r\n    mpz_div_ui(half_modulus, modulus, 2);\r\n\r\n    const size_t d = params::poly_p::degree;\r\n    std::array<mpz_t, d> res_repr;\r\n    for (size_t k = 0; k < d; k++)\r\n    {\r\n      mpz_inits(res_repr[k], nullptr);\r\n    }\r\n\r\n    tmp_poly.poly2mpz(res_repr);\r\n\r\n    bool bFirst = true;\r\n\r\n    for(int k = 0; k < d; k++)\r\n    {\r\n      if(mpz_sgn(res_repr[k]) != 0)\r\n      {\r\n        if(!bFirst)\r\n          std::cout << \" + \";\r\n        else\r\n          bFirst = false;\r\n        mpz_t tmp;\r\n        mpz_init_set(tmp, res_repr[k]);\r\n        mpz_mod(tmp,tmp,modulus);\r\n        if(mpz_cmp(tmp, half_modulus) > 0)\r\n          mpz_sub(tmp, tmp, modulus);\r\n        std::cout << mpz_class(tmp).get_str() << \" * x^\" << k;\r\n        mpz_clear(tmp);\r\n      }\r\n    }\r\n    std::cout << std::endl;\r\n\r\n    for (size_t k = 0; k < d; k++)\r\n    {\r\n      mpz_clears(res_repr[k], nullptr);\r\n    }  \r\n  }\r\n\r\nvoid write_poly(params::poly_p &poly, std::ofstream& file)\r\n  {\r\n    const size_t d = params::poly_p::degree;\r\n    std::array<mpz_t, d> res_repr;\r\n    for (size_t k = 0; k < d; k++)\r\n    {\r\n      mpz_inits(res_repr[k], nullptr);\r\n    }\r\n\r\n    poly.poly2mpz(res_repr);\r\n\r\n    for(int k = 0; k < d; k++)\r\n    {\r\n      file << mpz_class(res_repr[k]).get_str();\r\n      file << std::endl;\r\n    }\r\n    file << std::endl;\r\n\r\n    for (size_t k = 0; k < d; k++)\r\n    {\r\n      mpz_clears(res_repr[k], nullptr);\r\n    }\r\n  }\r\n\r\nvoid print_encoding(std::array<mpz_t, params::poly_p::degree>const &poly, int nInputIntPrec, int nInputFracPrec, mpz_class curModulus)\r\n  {\r\n    const size_t d = params::poly_p::degree;\r\n    mpz_t modulus;\r\n    mpz_init(modulus);\r\n    mpz_set(modulus, curModulus.get_mpz_t());\r\n\r\n    mpz_t half_modulus;\r\n    mpz_init(half_modulus);\r\n    mpz_div_ui(half_modulus, modulus, 2); \r\n    std::cout << \"[\";\r\n    //print integral part\r\n    for(int k = nInputIntPrec - 1; k >= 0; k--)\r\n    {\r\n      mpz_t tmp;\r\n      mpz_init_set(tmp, poly[k]);\r\n      mpz_mod(tmp,tmp,modulus);\r\n      if(mpz_cmp(tmp, half_modulus) > 0)\r\n        mpz_sub(tmp, tmp, modulus);\r\n      std::cout << mpz_class(tmp).get_str() << \" \";\r\n      mpz_clear(tmp);\r\n    }\r\n    std::cout << \".\";\r\n    //print fractional part\r\n    for(int k = 1; k <= nInputFracPrec; k++)\r\n    {\r\n      mpz_t tmp;\r\n      mpz_init_set(tmp, poly[d-k]);\r\n      mpz_mod(tmp,tmp,modulus);\r\n      if(mpz_cmp(tmp, half_modulus) > 0)\r\n        mpz_sub(tmp, tmp, modulus);\r\n      mpz_neg(tmp, tmp);\r\n      std::cout << mpz_class(tmp).get_str() << \" \";\r\n      mpz_clear(tmp);\r\n    }\r\n    std::cout << \"]\";\r\n    std::cout << std::endl;\r\n    mpz_clear(modulus);\r\n    mpz_clear(half_modulus);\r\n  }\r\n\r\nvoid print_poly_array(std::array<mpz_t, params::poly_p::degree>const &poly)\r\n  {\r\n    for(int k = 0; k < params::poly_p::degree; k++)\r\n    {\r\n      if(mpz_sgn(poly[k]) != 0)\r\n        std::cout << mpz_class(poly[k]).get_str() << \" * x^\" << k << \" + \";\r\n    }\r\n    std::cout << std::endl;\r\n  }\r\n\r\nvoid print_poly_degrees(params::poly_p &poly)\r\n  {\r\n    int intDeg = cut_point;\r\n    int fracDeg = cut_point;\r\n\r\n    const size_t d = params::poly_p::degree;\r\n    std::array<mpz_t, d> res_repr;\r\n    for (size_t k = 0; k < d; k++)\r\n    {\r\n      mpz_inits(res_repr[k], nullptr);\r\n    }\r\n\r\n    poly.poly2mpz(res_repr);\r\n\r\n    while(intDeg > -1 && mpz_sgn(res_repr[intDeg]) == 0)\r\n    {\r\n      intDeg--;\r\n    }\r\n    while(fracDeg < d && mpz_sgn(res_repr[fracDeg]) == 0)\r\n    {\r\n      fracDeg++;\r\n    }\r\n    std::cout << \"Int. degree: \" << intDeg << std::endl;\r\n    std::cout << \"Frac. degree: \" << d - fracDeg << std::endl;\r\n  }\r\n\r\nvoid fit_to_modulus(std::array<mpz_t, params::poly_p::degree>& polym, mpz_t modulus)\r\n  {\r\n    for (int i = 0; i < params::poly_p::degree; i++)\r\n    {\r\n      mpz_mod(polym[i], polym[i], modulus);\r\n    }\r\n  }\r\n\r\n//the function that splits the polynomial representation of a real value according to the different moduli\r\nvoid convert_to_crt(std::array<params::poly_p, nPltxtModuli>& poly_crt, double fValue, size_t nIntPrec, size_t nFracPrec)\r\n  {\r\n    for(size_t iPltxtMod = 0; iPltxtMod < nPltxtModuli; iPltxtMod++)\r\n    {\r\n      params::plaintextModulus<mpz_class>::value_mpz = mpz_class(plaintextModuli[iPltxtMod]);\r\n      std::array<mpz_t, params::poly_p::degree> bal_repr;\r\n      for (size_t i = 0; i < params::poly_p::degree; i++)\r\n      {\r\n        mpz_inits(bal_repr[i], nullptr);\r\n      }\r\n\r\n      convert_to_naf_greedy(bal_repr, fValue, nIntPrec, nFracPrec);\r\n      poly_crt[n].mpz2poly(bal_repr);\r\n\r\n      for (size_t i = 0; i < params::poly_p::degree; i++)\r\n      {\r\n        mpz_clears(bal_repr[i], nullptr);\r\n      }\r\n      params::plaintextModulus<mpz_class>::reset();\r\n    }\r\n  }\r\n\r\nvoid convert_to_crt_one_modulus(params::poly_p& poly_crt, double fValue, size_t nIntPrec, size_t nFracPrec)\r\n  {\r\n      std::array<mpz_t, params::poly_p::degree> bal_repr;\r\n      for (size_t i = 0; i < params::poly_p::degree; i++)\r\n      {\r\n        mpz_inits(bal_repr[i], nullptr);\r\n      }\r\n\r\n      convert_to_naf_greedy(bal_repr, fValue, nIntPrec, nFracPrec);\r\n      poly_crt.mpz2poly(bal_repr);\r\n\r\n      for (size_t i = 0; i < params::poly_p::degree; i++)\r\n      {\r\n        mpz_clears(bal_repr[i], nullptr);\r\n      } \r\n  }\r\n\r\n//conversion from crt representation to float\r\nmpf_class convert_from_crt(std::array<params::poly_p, nPltxtModuli>& poly_crt, size_t cut_point)\r\n  {\r\n    std::array<mpz_t, params::poly_p::degree> res_poly;\r\n    mpf_class fRes;\r\n    \r\n    for (size_t i = 0; i < params::poly_p::degree; i++)\r\n    {\r\n      mpz_inits(res_poly[i], nullptr);\r\n    }\r\n\r\n    mpz_t quotient, current_modulus, lifting_integer;\r\n    mpz_inits(quotient, current_modulus, lifting_integer, nullptr);\r\n    \r\n    //loop over all moduli\r\n    for (size_t j = 0; j < nPltxtModuli; j++)\r\n    {\r\n      // Current modulus\r\n      mpz_set_str(current_modulus, plaintextModuli[j], 10);\r\n    \r\n      // compute the product of primes except the current one\r\n      mpz_divexact(quotient, params::plaintextModulus<mpz_class>::product().get_mpz_t(), current_modulus);\r\n\r\n      // Compute the inverse of the product\r\n      mpz_init2(lifting_integer, params::plaintextModulus<mpz_class>::bits_in_moduli_product);\r\n      mpz_invert(lifting_integer, quotient, current_modulus);\r\n\r\n      // Multiply by the quotient\r\n      mpz_mul(lifting_integer, lifting_integer, quotient);\r\n\r\n      std::array<mpz_t, params::poly_p::degree> cur_poly;\r\n      for (size_t i = 0; i < params::poly_p::degree; i++)\r\n      {\r\n        mpz_inits(cur_poly[i], nullptr);\r\n      }\r\n      poly_crt[j].poly2mpz(cur_poly);\r\n\r\n      for (size_t i = 0; i < params::poly_p::degree; i++)\r\n      {\r\n        if (mpz_sgn(cur_poly[i])!= 0)\r\n          mpz_addmul(res_poly[i], lifting_integer, cur_poly[i]);\r\n      }\r\n\r\n      for (size_t i = 0; i < params::poly_p::degree; i++)\r\n      {\r\n        mpz_clears(cur_poly[i], nullptr);\r\n      }    \r\n    }\r\n\r\n    mpz_clears(quotient, current_modulus, lifting_integer, nullptr);\r\n\r\n    params::plaintextModulus<mpz_class>::reset();\r\n\r\n    fit_to_modulus(res_poly, params::plaintextModulus<mpz_class>::value().get_mpz_t());\r\n    fRes = naf_to_float(res_poly, cut_point);\r\n\r\n    for (size_t i = 0; i < params::poly_p::degree; i++)\r\n    {\r\n      mpz_clears(res_poly[i], nullptr);\r\n    }\r\n\r\n    return fRes;  \r\n  }\r\n\r\nparams::poly_p convert_to_simd(std::array<params::poly_p, nPltxtModuli> polys)\r\n  {\r\n    std::array<mpz_t, params::poly_p::degree> res_poly;\r\n    \r\n    for (size_t i = 0; i < params::poly_p::degree; i++)\r\n    {\r\n      mpz_inits(res_poly[i], nullptr);\r\n    }\r\n\r\n    mpz_t quotient, current_modulus, lifting_integer;\r\n    mpz_inits(quotient, current_modulus, lifting_integer, nullptr);\r\n    \r\n    //loop over all moduli\r\n    for (size_t j = 0; j < nPltxtModuli; j++)\r\n    {\r\n      // Current modulus\r\n      mpz_set_str(current_modulus, plaintextModuli[j], 10);\r\n    \r\n      // compute the product of primes except the current one\r\n      mpz_divexact(quotient, params::plaintextModulus<mpz_class>::product().get_mpz_t(), current_modulus);\r\n\r\n      // Compute the inverse of the product\r\n      mpz_init2(lifting_integer, params::plaintextModulus<mpz_class>::bits_in_moduli_product);\r\n      mpz_invert(lifting_integer, quotient, current_modulus);\r\n\r\n      // Multiply by the quotient\r\n      mpz_mul(lifting_integer, lifting_integer, quotient);\r\n\r\n      std::array<mpz_t, params::poly_p::degree> cur_poly;\r\n      for (size_t i = 0; i < params::poly_p::degree; i++)\r\n      {\r\n        mpz_inits(cur_poly[i], nullptr);\r\n      }\r\n      polys[j].poly2mpz(cur_poly);\r\n\r\n      for (size_t i = 0; i < params::poly_p::degree; i++)\r\n      {\r\n        if (mpz_sgn(cur_poly[i])!= 0)\r\n          mpz_addmul(res_poly[i], lifting_integer, cur_poly[i]);\r\n      }\r\n\r\n      for (size_t i = 0; i < params::poly_p::degree; i++)\r\n      {\r\n        mpz_clears(cur_poly[i], nullptr);\r\n      }    \r\n    }\r\n\r\n    mpz_clears(quotient, current_modulus, lifting_integer, nullptr);\r\n\r\n    params::plaintextModulus<mpz_class>::reset();\r\n\r\n    fit_to_modulus(res_poly, params::plaintextModulus<mpz_class>::value().get_mpz_t());\r\n\r\n    params::poly_p res_poly_p;\r\n    res_poly_p.mpz2poly(res_poly);\r\n\r\n    return res_poly_p;\r\n  }\r\n\r\nvoid convert_from_simd(std::array<params::poly_p, nPltxtModuli>& polys, std::array<mpz_t, params::poly_p::degree> poly2conv)\r\n  {\r\n    for(size_t modInd = 0; modInd < nPltxtModuli; modInd++)\r\n    {\r\n      mpz_t curmod;\r\n      mpz_init(curmod);\r\n      mpz_set_str(curmod, plaintextModuli[modInd], 10);\r\n      \r\n      std::array<mpz_t, params::poly_p::degree> polymod;\r\n      for (size_t i = 0; i < params::poly_p::degree; i++)\r\n      {\r\n        mpz_inits(polymod[i], nullptr);\r\n        mpz_tdiv_r(polymod[i], poly2conv[i], curmod);\r\n      }\r\n\r\n      polys[modInd].mpz2poly(polymod);\r\n\r\n      for (size_t i = 0; i < params::poly_p::degree; i++)\r\n      {\r\n        mpz_clears(polymod[i], nullptr);\r\n      }\r\n      mpz_clear(curmod);\r\n    }\r\n  }\r\n\r\nFV::ciphertext_t poly_to_ciphertext(pk_t &pk, params::poly_p const &poly)\r\n  {\r\n    FV::ciphertext_t ct;\r\n    ct.pk = &pk;\r\n    ct.c0 = poly;\r\n    ct.c0.ntt_pow_phi();\r\n    ct.c0 = nfl::shoup(ct.c0 * ct.pk->delta, ct.pk->delta_shoup);\r\n    ct.isnull = false;\r\n\r\n    return ct;\r\n  }\r\n\r\nvoid convert_cphrtxt_to_c(FV::ciphertext_t const &c, long long int c0[][4096], long long int c1[][4096])\r\n  {\r\n    params::poly_p c0fv{c.c0};\r\n    params::poly_p c1fv{c.c1};\r\n\r\n    c0fv.invntt_pow_invphi();\r\n    c1fv.invntt_pow_invphi();\r\n\r\n    const size_t d = params::poly_t::degree;\r\n\r\n    //initiate array\r\n    std::array<mpz_t, params::poly_t::degree> c0fv_mpz;\r\n    std::array<mpz_t, params::poly_t::degree> c1fv_mpz;\r\n    for (size_t i = 0; i < d; i++)\r\n    {\r\n      mpz_inits(c0fv_mpz[i], nullptr);\r\n      mpz_inits(c1fv_mpz[i], nullptr);\r\n    }\r\n\r\n    c0fv.poly2mpz(c0fv_mpz);\r\n    c1fv.poly2mpz(c1fv_mpz);\r\n\r\n    for (size_t i = 0; i < (sizeof(q_factors)/sizeof(*q_factors)); i++)\r\n    {\r\n      for (size_t j = 0; j < d; j++)\r\n      {\r\n        mpz_t tmp;\r\n        mpz_init(tmp);\r\n        \r\n        mpz_set(tmp, c0fv_mpz[j]);\r\n        c0[i][j] = mpz_mod_ui(tmp, tmp, q_factors[i]);\r\n\r\n        mpz_set(tmp, c1fv_mpz[j]);\r\n        c1[i][j] = mpz_mod_ui(tmp, tmp, q_factors[i]);\r\n\r\n        mpz_clear(tmp);\r\n      }\r\n    }\r\n\r\n    for (size_t i = 0; i < d; i++)\r\n    {\r\n      mpz_clears(c0fv_mpz[i], nullptr);\r\n      mpz_clears(c1fv_mpz[i], nullptr);\r\n    }\r\n  }\r\n\r\nvoid zeroize(long long int arr[6][4096])\r\n{\r\n  for(int i = 0; i < 6; i++)\r\n  {\r\n    for(int j = 0; j < 4096; j++)\r\n    {\r\n      arr[i][j] = 0;\r\n    }\r\n  }\r\n}\r\n\r\nclass gmdh_net_layer\r\n  {\r\n    //number of nodes\r\n    size_t m_nNodes;\r\n    \r\n\r\n    std::vector<bool> m_NodeFlags; //a flag is true when a node has to be evaluated in order to compute the final output\r\n\r\n    //wiring with the previous layer\r\n    arma::mat m_aConnections;\r\n    \r\n    //balanced ternary expansion of polynomial coefficients corresponding to the current plaintext modulus\r\n    std::vector<std::vector<params::poly_p>> m_crtPolynoms;\r\n    \r\n    //polynomial coefficients as real numbers\r\n    arma::mat m_Polynoms;\r\n\r\n    //polynomial coefficients approximated by w-NIBNAF\r\n    arma::mat m_PolynomsApprox;\r\n\r\n    //current plaintext modulus\r\n    mpz_class m_mpzModulus;\r\n\r\n    //output of the layer\r\n    arma::mat m_Output;\r\n\r\n    //error (MSE) of node output values\r\n    arma::vec m_OutputError;\r\n\r\n    //index of the minimal error node\r\n    size_t m_iMinErrorNode;\r\n\r\n    //regularization parameters of nodes chosen by the algorithm after training\r\n    arma::vec m_NodeAlphas;\r\n\r\n    //precision of balanced ternary expansion\r\n    size_t m_nIntPrec;\r\n    size_t m_nFracPrec;\r\n    \r\n    //indicates whether network coefficients are encoded\r\n    bool m_bIsEncoded;\r\n\r\n    //indicates whether the network was trained and output data together with error values was saved\r\n    bool m_bHasOutput;\r\n\r\n  public:\r\n    gmdh_net_layer(): m_nNodes(0), m_OutputError(0.0), m_iMinErrorNode(0), m_bIsEncoded(false), m_bHasOutput(false) {}\r\n\r\n    gmdh_net_layer(int nNodes, arma::mat aConnections, arma::mat aPolynoms, arma::mat output, size_t iMinErrorNode, arma::vec outputError, arma::vec nodeAlphas, mpz_class mpzModulus): m_nNodes(nNodes), m_mpzModulus(mpzModulus), m_bIsEncoded(false), m_bHasOutput(true)\r\n      {\r\n        if (aConnections.n_rows != nNodes)\r\n        {\r\n          printf(\"Invalid number of connections given\\n\");\r\n          exit(1);\r\n        }\r\n        else\r\n          m_aConnections = aConnections;\r\n\r\n        if (aPolynoms.n_rows != nNodes)\r\n        {\r\n          printf(\"Invalid number of polynomials given\\n\");\r\n          exit(1);\r\n        }\r\n        else\r\n        {\r\n          m_Polynoms = aPolynoms;\r\n        }\r\n\r\n        if(output.n_cols != nNodes)\r\n        {\r\n          printf(\"Invalid number of output values\\n\");\r\n          exit(1);\r\n        }\r\n        else\r\n        {\r\n          m_Output = output;\r\n          m_OutputError = outputError;\r\n          m_iMinErrorNode = iMinErrorNode;\r\n          m_NodeAlphas = nodeAlphas;\r\n        }\r\n\r\n        for(int iNode = 0; iNode < m_nNodes; iNode++)\r\n        {\r\n          m_NodeFlags.push_back(true);\r\n        }\r\n      }\r\n\r\n    gmdh_net_layer(int nNodes, arma::mat aConnections, arma::mat aPolynoms, arma::vec nodeAlphas, mpz_class mpzModulus): m_nNodes(nNodes), m_mpzModulus(mpzModulus), m_bIsEncoded(false), m_bHasOutput(false)\r\n      {\r\n        if (aConnections.n_rows != nNodes)\r\n        {\r\n          printf(\"Invalid number of connections given\\n\");\r\n          exit(1);\r\n        }\r\n        else\r\n          m_aConnections = aConnections;\r\n\r\n        if (aPolynoms.n_rows != nNodes)\r\n        {\r\n          printf(\"Invalid number of polynomials given\\n\");\r\n          exit(1);\r\n        }\r\n        else\r\n        {\r\n          m_Polynoms = aPolynoms;\r\n        }\r\n\r\n        if(nodeAlphas.n_elem != nNodes)\r\n        {\r\n          printf(\"Invalid number of alpha values %llu\\n\", nodeAlphas.n_cols);\r\n          exit(1);\r\n        }\r\n        else\r\n        {\r\n          m_NodeAlphas = nodeAlphas;\r\n        }\r\n\r\n        for(int iNode = 0; iNode < m_nNodes; iNode++)\r\n        {\r\n          m_NodeFlags.push_back(true);\r\n        }\r\n      }\r\n\r\n    void encode_coefs(size_t nIntPrec, size_t nFracPrec)\r\n      {\r\n        m_nIntPrec = nIntPrec;\r\n        m_nFracPrec = nFracPrec;\r\n\r\n        m_PolynomsApprox = arma::mat(arma::size(m_Polynoms));\r\n\r\n        for (int iNode = 0; iNode < m_nNodes; iNode++)\r\n          {\r\n            if(m_NodeFlags[iNode])\r\n            {\r\n              std::vector<params::poly_p> tmpRowCRT;\r\n              for (int j = 0; j < m_Polynoms.n_cols; j++)\r\n              {\r\n                params::poly_p tmp;\r\n                convert_to_crt_one_modulus(tmp, m_Polynoms(iNode,j), nIntPrec, nFracPrec);\r\n                m_PolynomsApprox(iNode,j) = naf_to_float(tmp, cut_point_init, params::plaintextModulus<mpz_class>::product_mpz.get_mpz_t()).get_d();\r\n\r\n                tmpRowCRT.push_back(tmp);\r\n              }\r\n              m_crtPolynoms.push_back(tmpRowCRT);\r\n            }\r\n            else\r\n            {\r\n              m_crtPolynoms.push_back(std::vector<params::poly_p>());\r\n            }\r\n          }\r\n\r\n        m_bIsEncoded = true;\r\n      }\r\n\r\n    void get_connections(int& nInputNode1, int& nInputNode2, int nCurNode) const\r\n      {\r\n        nInputNode1 = m_aConnections(nCurNode, 0);\r\n        nInputNode2 = m_aConnections(nCurNode, 1);\r\n      }\r\n\r\n    arma::mat get_output() const\r\n      {\r\n        if(!m_bHasOutput)\r\n        {\r\n          printf(\"Layer output is not defined\\n\");\r\n          exit(1);\r\n        }\r\n        return m_Output;\r\n      }\r\n\r\n    void get_poly(std::vector<params::poly_p>& aPoly, int nCurNode) const\r\n      {\r\n        if(!m_bIsEncoded)\r\n        {\r\n          printf(\"gmdh_net_layer.get_poly: coefficients are not encoded\\n\");\r\n          exit(1); \r\n        }\r\n\r\n        aPoly.clear();\r\n        for (size_t i = 0; i < m_crtPolynoms[nCurNode].size(); i++)\r\n        {\r\n          aPoly.push_back(m_crtPolynoms[nCurNode][i]);\r\n        }\r\n      }\r\n\r\n    arma::mat get_poly_plain(int nCurNode) const\r\n      {\r\n        return m_Polynoms.row(nCurNode);\r\n      }\r\n\r\n    size_t get_num_nodes() const\r\n      {\r\n        return m_nNodes;\r\n      }\r\n\r\n    double get_min_error() const\r\n      {\r\n        if(!m_bHasOutput)\r\n        {\r\n          printf(\"Layer output is not defined\\n\");\r\n          exit(1);\r\n        }\r\n        return m_OutputError[m_iMinErrorNode];\r\n      }\r\n\r\n    size_t get_min_error_node() const\r\n      {\r\n        if(!m_bHasOutput)\r\n        {\r\n          printf(\"Layer output is not defined\\n\");\r\n          exit(1);\r\n        }\r\n        return m_iMinErrorNode;\r\n      }\r\n\r\n    void set_modulus(mpz_class mpzModulus)\r\n      {\r\n        m_mpzModulus = mpzModulus;\r\n\r\n        m_crtPolynoms.clear();\r\n        for (int iNode = 0; iNode < m_nNodes; iNode++)\r\n          {\r\n            if(m_NodeFlags[iNode])\r\n            {\r\n              std::vector<params::poly_p> tmpRowCRT;\r\n              for (int j = 0; j < m_Polynoms.n_cols; j++)\r\n              {\r\n                params::poly_p tmp;\r\n                convert_to_crt_one_modulus(tmp, m_Polynoms(iNode,j), m_nIntPrec, m_nFracPrec);\r\n\r\n                tmpRowCRT.push_back(tmp);\r\n              }\r\n              m_crtPolynoms.push_back(tmpRowCRT);\r\n            }\r\n            else\r\n            {\r\n              m_crtPolynoms.push_back(std::vector<params::poly_p>());\r\n            }\r\n          }\r\n      }\r\n\r\n    //turn off unnecessary nodes for the final output\r\n    void update_nodes(std::vector<size_t> nodesToRemain)\r\n      {\r\n        for(int iNode = 0; iNode < m_nNodes; iNode++)\r\n        {\r\n          m_NodeFlags[iNode] = false;\r\n        }\r\n\r\n\r\n        for(size_t iNode = 0; iNode < nodesToRemain.size(); iNode++)\r\n        {\r\n          m_NodeFlags[nodesToRemain[iNode]] = true;\r\n        }\r\n      }\r\n\r\n    std::vector<size_t> get_input_nodes() const\r\n      {\r\n        if(!m_bHasOutput)\r\n          printf(\"Layer input is not defined\\n\");\r\n\r\n        std::vector<size_t> resNodes;\r\n\r\n        for(int iNode = 0; iNode < m_nNodes; iNode++)\r\n          {\r\n            if(m_NodeFlags[iNode])\r\n            {\r\n              size_t inputNode0 = int(m_aConnections(iNode, 0));\r\n              size_t inputNode1 = int(m_aConnections(iNode, 1));\r\n\r\n              std::sort(resNodes.begin(), resNodes.end());\r\n\r\n              if(!std::binary_search(resNodes.begin(), resNodes.end(), inputNode0))\r\n                resNodes.push_back(inputNode0);\r\n\r\n              if(!std::binary_search(resNodes.begin(), resNodes.end(), inputNode1))\r\n                resNodes.push_back(inputNode1);\r\n            }\r\n          }\r\n        return resNodes;\r\n      }\r\n\r\n    void print() const\r\n      {\r\n        std::cout << \"Modulus: \" << m_mpzModulus << std::endl;\r\n        for (int iNode = 0; iNode < m_nNodes; iNode++)\r\n        {\r\n          if(m_NodeFlags[iNode])\r\n          {\r\n            std::cout << \"Node \" << iNode << std::endl;\r\n            std::cout << \"Input 0: \" << m_aConnections(iNode, 0) << std::endl;\r\n            std::cout << \"Input 1: \" << m_aConnections(iNode, 1) << std::endl;\r\n            std::cout << \"Polynomial coefficients: \" <<  m_Polynoms.row(iNode);\r\n            if(m_bHasOutput)\r\n              std::cout << \"Error: \" << m_OutputError(iNode) << std::endl;\r\n            std::cout << \"Alpha: \" << m_NodeAlphas(iNode) << std::endl;\r\n            std::cout << std::endl;  \r\n          }  \r\n        }\r\n        std::cout << std::endl;\r\n      }\r\n\r\n    void print_encodings() const\r\n      {\r\n        for (size_t iNode = 0; iNode < m_nNodes; iNode++)\r\n        {\r\n          if(m_NodeFlags[iNode])\r\n          {\r\n            printf(\"Node %zu\\n\", iNode);\r\n            std::cout << \"Input 0: \" << m_aConnections(iNode, 0) << std::endl;\r\n            std::cout << \"Input 1: \" << m_aConnections(iNode, 1) << std::endl;\r\n            for(size_t j = 0; j < m_Polynoms.n_cols; j++)\r\n            {\r\n              print_poly(m_crtPolynoms[iNode][j], true);\r\n            }\r\n          }\r\n        }\r\n      }\r\n\r\n    double get_max_abs_coef() const\r\n      {\r\n        double res = 0.0;\r\n\r\n        for (int iNode = 0; iNode < m_nNodes; iNode++)\r\n        {\r\n          if (m_NodeFlags[iNode])\r\n          {\r\n            for(int iCol = 0; iCol < m_Polynoms.n_cols; iCol++)\r\n            {\r\n              if (fabs(m_Polynoms(iNode, iCol)) > res)\r\n                res = fabs(m_Polynoms(iNode, iCol));  \r\n            }\r\n            \r\n          }\r\n        }\r\n        return res;\r\n      }\r\n\r\n    //evaluate nodes in the homomorphic mode\r\n    std::vector<FV::ciphertext_t> evaluate_enc(std::vector<FV::ciphertext_t>& cSample, pk_t *pk, sk_t *sk)\r\n      {\r\n        if(!m_bIsEncoded)\r\n        {\r\n          printf(\"gmdh_net_layer.evaluate_enc: coefficients are not encoded\\n\");\r\n          exit(1); \r\n        }\r\n        std::vector<FV::ciphertext_t> output;\r\n\r\n        for(int iNode = 0; iNode < m_nNodes; iNode++)\r\n        {\r\n          FV::ciphertext_t nodeOutput;\r\n          if(m_NodeFlags[iNode])\r\n          {\r\n            //printf(\"Evaluate node %d.\\n\", iNode + 1);\r\n            //std::cout << \"Polynomial coefs: \" << m_Polynoms.row(iNode);\r\n            \r\n            size_t nCoef = m_crtPolynoms[iNode].size(); \r\n            if (nCoef < m_Polynoms.n_cols)\r\n            {\r\n             printf(\"evaluate_enc: Number of coefs is less than %llu! %zu instead. \\n\", m_Polynoms.n_cols, nCoef);\r\n             exit(1);\r\n            }\r\n\r\n            std::array<FV::ciphertext_t, 6> c_aPoly;\r\n            for(size_t i = 0; i < m_Polynoms.n_cols; i++)\r\n            {\r\n              c_aPoly[i] = poly_to_ciphertext(*pk, m_crtPolynoms[iNode][i]);\r\n            }\r\n            \r\n            //std::cout << \"Current modulus: \" << params::plaintextModulus<mpz_class>::value().get_mpz_t() << std::endl;\r\n\r\n            //std::cout << \"Initial noise: \" << poly_noise(*sk, *pk, cSample[m_aConnections(iNode,0)]) << \" and \" << poly_noise(*sk, *pk, cSample[m_aConnections(iNode,1)]) << \"/\" << pk->noise_max << std::endl;\r\n\r\n            nodeOutput = cSample[m_aConnections(iNode,0)] * c_aPoly[1];            \r\n            nodeOutput += cSample[m_aConnections(iNode,1)] * c_aPoly[2];\r\n            nodeOutput += cSample[m_aConnections(iNode,0)] * cSample[m_aConnections(iNode,1)] * c_aPoly[3];\r\n            nodeOutput += cSample[m_aConnections(iNode,0)] * cSample[m_aConnections(iNode,0)] * c_aPoly[4];\r\n            nodeOutput += cSample[m_aConnections(iNode,1)] * cSample[m_aConnections(iNode,1)] * c_aPoly[5];\r\n            nodeOutput += c_aPoly[0];\r\n\r\n            /*\r\n            //if(poly_noise(*sk, *pk, nodeOutput) > pk->noise_max)\r\n            {\r\n              std::cout << \"Current modulus: \" << params::plaintextModulus<mpz_class>::value().get_mpz_t() << std::endl;\r\n              std::cout << \"Output noise: \" << poly_noise(*sk, *pk, nodeOutput) << \"/\" << pk->noise_max << std::endl;\r\n            }\r\n            */\r\n          }\r\n          output.push_back(nodeOutput);\r\n        }\r\n        return output;\r\n      }\r\n\r\n      //evaluate nodes in the homomorphic mode\r\n    std::vector<FV::ciphertext_t> evaluate_suj(std::vector<FV::ciphertext_t>& cSample, pk_t *pk, sk_t *sk)\r\n      { \r\n\r\n        \r\n        if(!m_bIsEncoded)\r\n        {\r\n          printf(\"gmdh_net_layer.evaluate_enc: coefficients are not encoded\\n\");\r\n          exit(1); \r\n        }\r\n        std::vector<FV::ciphertext_t> output;\r\n\r\n        for(int iNode = 0; iNode < m_nNodes; iNode++)\r\n        {\r\n          FV::ciphertext_t nodeOutput;\r\n          if(m_NodeFlags[iNode])\r\n          {\r\n            // printf(\"Evaluate node %d.\\n\", iNode + 1);\r\n            // std::cout << \"Polynomial coefs: \" << m_Polynoms.row(iNode);\r\n            \r\n            size_t nCoef = m_crtPolynoms[iNode].size(); \r\n            if (nCoef < m_Polynoms.n_cols)\r\n            {\r\n             printf(\"evaluate_enc: Number of coefs is less than %llu! %zu instead. \\n\", m_Polynoms.n_cols, nCoef);\r\n             exit(1);\r\n            }\r\n\r\n            std::array<FV::ciphertext_t, 6> c_aPoly;\r\n            for(size_t i = 0; i < m_Polynoms.n_cols; i++)\r\n            {\r\n              c_aPoly[i] = poly_to_ciphertext(*pk, m_crtPolynoms[iNode][i]);\r\n            }\r\n            \r\n            // std::cout << \"Current modulus: \" << params::plaintextModulus<mpz_class>::value().get_mpz_t() << std::endl;\r\n            // std::cout << \"Initial noise: \" << poly_noise(*sk, *pk, cSample[m_aConnections(iNode,0)]) << \" and \" << poly_noise(*sk, *pk, cSample[m_aConnections(iNode,1)]) << \"/\" << pk->noise_max << std::endl;\r\n\r\n            long long int tmp10[NUM_PRIME_EXT][4096];\r\n            long long int tmp11[NUM_PRIME_EXT][4096];\r\n            long long int tmp20[NUM_PRIME_EXT][4096];\r\n            long long int tmp21[NUM_PRIME_EXT][4096];\r\n            long long int tmp30[NUM_PRIME_EXT][4096];\r\n            long long int tmp31[NUM_PRIME_EXT][4096];\r\n\r\n            long long int res0[NUM_PRIME_EXT][4096];\r\n            long long int res1[NUM_PRIME_EXT][4096];\r\n\r\n            mpz_t res_mpz0[4096];\r\n            mpz_t res_mpz1[4096];\r\n\r\n            std::array<mpz_t, params::poly_p::degree> p0_array;\r\n            std::array<mpz_t, params::poly_p::degree> p1_array;\r\n\r\n            params::poly_p p0;\r\n            params::poly_p p1;\r\n\r\n            for (size_t i = 0; i < params::poly_p::degree; i++)\r\n            {\r\n              mpz_inits(p0_array[i], nullptr);\r\n              mpz_inits(p1_array[i], nullptr);\r\n            }\r\n\r\n            mpz_array_init(res_mpz0[0], 4096, 512);\r\n            mpz_array_init(res_mpz1[0], 4096, 512);\r\n\r\n\r\n\r\nstruct timespec tstart={0,0}, tend={0,0};    \r\n            \r\n            \r\n            //nodeOutput = cSample[m_aConnections(iNode,0)] * c_aPoly[1];\r\n            convert_cphrtxt_to_c(cSample[m_aConnections(iNode,0)], tmp10, tmp11);\r\n            convert_cphrtxt_to_c(c_aPoly[1], tmp20, tmp21);\r\n            \r\n          // clock_gettime(CLOCK_MONOTONIC, &tstart);\r\n          \r\n            HE_MUL_HW(tmp10, tmp11, tmp20, tmp21, res0, res1);\r\n          \r\n          // clock_gettime(CLOCK_MONOTONIC, &tend);\r\n          // printf(\"HE_MUL_HW took about %.5f seconds\\n\",\r\n          //   ((double)tend.tv_sec + 1.0e-9*tend.tv_nsec) - \r\n          //   ((double)tstart.tv_sec + 1.0e-9*tstart.tv_nsec));\r\n\r\n          // clock_gettime(CLOCK_MONOTONIC, &tstart);\r\n            // FV_mul(tmp10, tmp11, tmp20, tmp21, res0, res1);\r\n            // HE_COMPARE(res0, res1);\r\n          // clock_gettime(CLOCK_MONOTONIC, &tend);\r\n          // printf(\"FV_mul took about %.5f seconds\\n\",\r\n          //   ((double)tend.tv_sec + 1.0e-9*tend.tv_nsec) - \r\n          //   ((double)tstart.tv_sec + 1.0e-9*tstart.tv_nsec));\r\n\r\n            // getchar();\r\n                       \r\n            //nodeOutput += cSample[m_aConnections(iNode,1)] * c_aPoly[2];\r\n            convert_cphrtxt_to_c(cSample[m_aConnections(iNode,1)], tmp10, tmp11);\r\n            convert_cphrtxt_to_c(c_aPoly[2], tmp20, tmp21);\r\n            HE_MUL_HW(tmp10, tmp11, tmp20, tmp21, tmp30, tmp31);\r\n            FV_add(res0, res1, tmp30, tmp31, res0, res1);\r\n            \r\n            \r\n            //nodeOutput += cSample[m_aConnections(iNode,0)] * cSample[m_aConnections(iNode,1)] * c_aPoly[3];\r\n            convert_cphrtxt_to_c(cSample[m_aConnections(iNode,0)], tmp10, tmp11);\r\n            \r\n            convert_cphrtxt_to_c(cSample[m_aConnections(iNode,1)], tmp20, tmp21);\r\n            \r\n            HE_MUL_HW(tmp10, tmp11, tmp20, tmp21, tmp30, tmp31);\r\n            \r\n            convert_cphrtxt_to_c(c_aPoly[3], tmp20, tmp21);\r\n            \r\n            HE_MUL_HW(tmp30, tmp31, tmp20, tmp21, tmp10, tmp11);\r\n            \r\n            FV_add(res0, res1, tmp10, tmp11, res0, res1);\r\n            \r\n            \r\n            //nodeOutput += cSample[m_aConnections(iNode,0)] * cSample[m_aConnections(iNode,0)] * c_aPoly[4];\r\n            convert_cphrtxt_to_c(cSample[m_aConnections(iNode,0)], tmp10, tmp11);\r\n            convert_cphrtxt_to_c(cSample[m_aConnections(iNode,0)], tmp20, tmp21);\r\n            HE_MUL_HW(tmp10, tmp11, tmp20, tmp21, tmp30, tmp31);\r\n            convert_cphrtxt_to_c(c_aPoly[4], tmp20, tmp21);\r\n            HE_MUL_HW(tmp30, tmp31, tmp20, tmp21, tmp10, tmp11);\r\n            FV_add(res0, res1, tmp10, tmp11, res0, res1);\r\n            \r\n            \r\n            //nodeOutput += cSample[m_aConnections(iNode,1)] * cSample[m_aConnections(iNode,1)] * c_aPoly[5];\r\n            convert_cphrtxt_to_c(cSample[m_aConnections(iNode,1)], tmp10, tmp11);\r\n            convert_cphrtxt_to_c(cSample[m_aConnections(iNode,1)], tmp20, tmp21);\r\n            HE_MUL_HW(tmp10, tmp11, tmp20, tmp21, tmp30, tmp31);\r\n            convert_cphrtxt_to_c(c_aPoly[5], tmp20, tmp21);\r\n            HE_MUL_HW(tmp30, tmp31, tmp20, tmp21, tmp10, tmp11);\r\n            FV_add(res0, res1, tmp10, tmp11, res0, res1);\r\n            \r\n            \r\n            //nodeOutput += c_aPoly[0];\r\n            convert_cphrtxt_to_c(c_aPoly[0], tmp10, tmp11);\r\n            FV_add(res0, res1, tmp10, tmp11, res0, res1);\r\n\r\n            inverse_crt_length7(res0, res_mpz0);\r\n            inverse_crt_length7(res1, res_mpz1);\r\n\r\n            for (size_t i = 0; i < params::poly_p::degree; i++)\r\n            {\r\n              mpz_set(p0_array[i], res_mpz0[i]);\r\n              mpz_set(p1_array[i], res_mpz1[i]);\r\n            }\r\n\r\n            p0.mpz2poly(p0_array);\r\n            p1.mpz2poly(p1_array);\r\n\r\n            nodeOutput = FV::ciphertext_t(p0, p1, *pk);\r\n            \r\n            for (size_t i = 0; i < params::poly_p::degree; i++)\r\n            {\r\n              mpz_clears(p0_array[i], nullptr);\r\n              mpz_clears(p1_array[i], nullptr);\r\n            }\r\n\r\n            mpz_clear(res_mpz0[0]);\r\n            mpz_clear(res_mpz1[0]);\r\n\r\n            /*\r\n            //if(poly_noise(*sk, *pk, nodeOutput) > pk->noise_max)\r\n            {\r\n              std::cout << \"Current modulus: \" << params::plaintextModulus<mpz_class>::value().get_mpz_t() << std::endl;\r\n              std::cout << \"Output noise: \" << poly_noise(*sk, *pk, nodeOutput) << \"/\" << pk->noise_max << std::endl;\r\n            }\r\n            */\r\n          }\r\n          output.push_back(nodeOutput);\r\n        }\r\n        return output;\r\n      }\r\n\r\n    //evaluate nodes in the real domain\r\n    arma::rowvec evaluate_double(arma::rowvec vSample)\r\n      {\r\n        arma::rowvec output(m_nNodes);\r\n\r\n        for(int iNode = 0; iNode < m_nNodes; iNode++)\r\n        {\r\n          if(m_NodeFlags[iNode])\r\n          {\r\n            //printf(\"Evaluate node %d.\\n\", iNode + 1);\r\n            //std::cout << \"Polynomial coefs: \" << m_Polynoms.row(iNode);\r\n             \r\n            //printf(\"Input values: %f,%f\\n\", vSample(m_aConnections(iNode,0)), m_Polynoms(iNode,1));\r\n\r\n            output(iNode) = vSample[m_aConnections(iNode,0)] * m_Polynoms(iNode,1);\r\n            output(iNode) += vSample[m_aConnections(iNode,1)] * m_Polynoms(iNode,2);\r\n            output(iNode) += vSample[m_aConnections(iNode,0)] * vSample[m_aConnections(iNode,1)] * m_Polynoms(iNode,3);\r\n            output(iNode) += vSample[m_aConnections(iNode,0)] * vSample[m_aConnections(iNode,0)] * m_Polynoms(iNode,4);\r\n            output(iNode) += vSample[m_aConnections(iNode,1)] * vSample[m_aConnections(iNode,1)] * m_Polynoms(iNode,5);\r\n            output(iNode) += m_Polynoms(iNode,0);\r\n            \r\n            //printf(\"Output values: %f\\n\", output(iNode));\r\n          }\r\n        }\r\n        \r\n        return output;\r\n      }\r\n\r\n    //evaluate nodes over reals approximated by w-NIBNAF\r\n    arma::rowvec evaluate_approx(arma::rowvec vSample)\r\n      {\r\n        if(!m_bIsEncoded)\r\n        {\r\n          printf(\"gmdh_net_layer.evaluate_approx: coefficients are not encoded\\n\");\r\n          exit(1); \r\n        }\r\n\r\n        arma::rowvec output(m_nNodes);\r\n\r\n        for(int iNode = 0; iNode < m_nNodes; iNode++)\r\n        {\r\n          if(m_NodeFlags[iNode])\r\n          {\r\n            //printf(\"Evaluate node %d.\\n\", iNode);\r\n            //std::cout << \"Polynomial coefs: \" << m_PolynomsApprox.row(iNode) << std::endl;\r\n             \r\n            //printf(\"Input values: %f,%f\\n\", vSample(m_aConnections(iNode,0)), m_Polynoms(iNode,1));\r\n\r\n            output(iNode) = vSample[m_aConnections(iNode,0)] * m_PolynomsApprox(iNode,1);\r\n            output(iNode) += vSample[m_aConnections(iNode,1)] * m_PolynomsApprox(iNode,2);\r\n            output(iNode) += vSample[m_aConnections(iNode,0)] * vSample[m_aConnections(iNode,1)] * m_PolynomsApprox(iNode,3);\r\n            output(iNode) += vSample[m_aConnections(iNode,0)] * vSample[m_aConnections(iNode,0)] * m_PolynomsApprox(iNode,4);\r\n            output(iNode) += vSample[m_aConnections(iNode,1)] * vSample[m_aConnections(iNode,1)] * m_PolynomsApprox(iNode,5);\r\n            output(iNode) += m_PolynomsApprox(iNode,0);\r\n            \r\n            //printf(\"Output values: %f\\n\", output(iNode));\r\n          }\r\n        }\r\n        \r\n        return output;\r\n      }    \r\n\r\n    //evaluate node in the plaintext space\r\n    std::vector<params::poly_p> evaluate_plain(std::vector<params::poly_p> pSample, pk_t *pk)\r\n      {\r\n        if(!m_bIsEncoded)\r\n        {\r\n          printf(\"gmdh_net_layer.evaluate_plain: coefficients are not encoded\\n\");\r\n          exit(1); \r\n        }\r\n\r\n        std::vector<params::poly_p> output;\r\n\r\n        for(int iNode = 0; iNode < m_nNodes; iNode++)\r\n        {\r\n          params::poly_p nodeOutput;\r\n\r\n          if(m_NodeFlags[iNode])\r\n          {\r\n            //printf(\"Evaluate node %d\\n\", iNode);\r\n\r\n            size_t nCoef = m_crtPolynoms[iNode].size(); \r\n            if (nCoef < m_Polynoms.n_cols)\r\n            {\r\n             printf(\"Evaluate poly: Number of coefs is less than %llu! %zu instead. \\n\", m_Polynoms.n_cols, nCoef);\r\n             exit(1);\r\n            }\r\n\r\n            \r\n            //printf(\"Inputs:\\n\");\r\n            //print_poly(pSample[m_aConnections(iNode,0)]);\r\n            //print_poly(pSample[m_aConnections(iNode,1)]);\r\n            \r\n\r\n            pSample[m_aConnections(iNode,0)].ntt_pow_phi();\r\n            pSample[m_aConnections(iNode,1)].ntt_pow_phi();\r\n\r\n            //printf(\"Coefs:\\n\");\r\n            for(int iCoef = 0; iCoef < m_Polynoms.n_cols; iCoef++)\r\n            {\r\n              //print_poly(m_crtPolynoms[iNode][iCoef]);\r\n              m_crtPolynoms[iNode][iCoef].ntt_pow_phi();              \r\n            }\r\n\r\n            nodeOutput = pSample[m_aConnections(iNode,0)] * m_crtPolynoms[iNode][1];\r\n            nodeOutput = nodeOutput + pSample[m_aConnections(iNode,1)] * m_crtPolynoms[iNode][2];\r\n            nodeOutput = nodeOutput + pSample[m_aConnections(iNode,0)] * pSample[m_aConnections(iNode,1)] * m_crtPolynoms[iNode][3];\r\n            nodeOutput = nodeOutput + pSample[m_aConnections(iNode,0)] * pSample[m_aConnections(iNode,0)] * m_crtPolynoms[iNode][4];\r\n            nodeOutput = nodeOutput + pSample[m_aConnections(iNode,1)] * pSample[m_aConnections(iNode,1)] * m_crtPolynoms[iNode][5];\r\n            nodeOutput = nodeOutput + m_crtPolynoms[iNode][0]; //constant term\r\n\r\n            nodeOutput.invntt_pow_invphi();\r\n\r\n            std::array<mpz_t, params::poly_p::degree> bal_repr;\r\n            for(size_t i = 0; i < params::poly_p::degree; i++)\r\n            {\r\n              mpz_inits(bal_repr[i], nullptr);\r\n            }\r\n\r\n            nodeOutput.poly2mpz(bal_repr);\r\n            \r\n            // Reduce the coefficients\r\n            for (size_t j = 0; j < params::poly_p::degree; j++) \r\n            { \r\n              //mpz_mod(bal_repr[j], bal_repr[j], params::poly_p::moduli_product());\r\n            }\r\n            nodeOutput.mpz2poly(bal_repr);\r\n            //printf(\"Result:\\n\");\r\n            //print_poly(nodeOutput);\r\n\r\n            //print_poly_degrees(nodeOutput);\r\n            //std::cout << std::endl;\r\n\r\n            for(size_t i = 0; i < params::poly_p::degree; i++)\r\n            {\r\n              mpz_clears(bal_repr[i], nullptr);\r\n            }\r\n\r\n            for(int iCoef = 0; iCoef < m_Polynoms.n_cols; iCoef++)\r\n            {\r\n              m_crtPolynoms[iNode][iCoef].invntt_pow_invphi();              \r\n            }\r\n            pSample[m_aConnections(iNode,0)].invntt_pow_invphi();\r\n            pSample[m_aConnections(iNode,1)].invntt_pow_invphi();\r\n            \r\n          }\r\n\r\n          output.push_back(nodeOutput);\r\n\r\n        } \r\n        return output;\r\n      } \r\n\r\n    //evaluate a layer with random polynomials (random at each time)\r\n    std::vector<params::poly_p> evaluate_plain_random(std::vector<params::poly_p> pSample, pk_t *pk)\r\n      {\r\n        if(!m_bIsEncoded)\r\n        {\r\n          printf(\"gmdh_net_layer.evaluate_plain_ranodm: coefficients are not encoded\\n\");\r\n          exit(1); \r\n        } \r\n        std::vector<params::poly_p> output;\r\n\r\n        for(int iNode = 0; iNode < m_nNodes; iNode++)\r\n        {\r\n          params::poly_p nodeOutput;\r\n\r\n          if(m_NodeFlags[iNode])\r\n          {\r\n            //printf(\"Evaluate node %d.\\n\", iNode + 1);\r\n            std::vector<params::poly_p> crtPolynom;\r\n            for(size_t iCoef = 0; iCoef < 6; iCoef++)\r\n            {\r\n              crtPolynom.push_back(random_poly(m_nIntPrec, m_nFracPrec));\r\n            }\r\n\r\n            pSample[m_aConnections(iNode,0)].ntt_pow_phi();\r\n            pSample[m_aConnections(iNode,1)].ntt_pow_phi();\r\n\r\n            for(int iCoef = 0; iCoef < 6; iCoef++)\r\n            {\r\n              crtPolynom[iCoef].ntt_pow_phi();              \r\n            }\r\n\r\n            nodeOutput = pSample[m_aConnections(iNode,0)] * crtPolynom[1];\r\n            nodeOutput = nodeOutput + pSample[m_aConnections(iNode,1)] * crtPolynom[2];\r\n            nodeOutput = nodeOutput + pSample[m_aConnections(iNode,0)] * pSample[m_aConnections(iNode,1)] * crtPolynom[3];\r\n            nodeOutput = nodeOutput + pSample[m_aConnections(iNode,0)] * pSample[m_aConnections(iNode,0)] * crtPolynom[4];\r\n            nodeOutput = nodeOutput + pSample[m_aConnections(iNode,1)] * pSample[m_aConnections(iNode,1)] * crtPolynom[5];\r\n            nodeOutput = nodeOutput + crtPolynom[0];\r\n\r\n            nodeOutput.invntt_pow_invphi();\r\n\r\n            std::array<mpz_t, params::poly_p::degree> bal_repr;\r\n            for(size_t i = 0; i < params::poly_p::degree; i++)\r\n            {\r\n              mpz_inits(bal_repr[i], nullptr);\r\n            }\r\n\r\n            nodeOutput.poly2mpz(bal_repr);\r\n            \r\n            // Reduce the coefficients\r\n            for (size_t j = 0; j < params::poly_p::degree; j++) \r\n            {\r\n              mpz_mod(bal_repr[j], bal_repr[j], params::poly_p::moduli_product());\r\n            }\r\n\r\n            nodeOutput.mpz2poly(bal_repr);\r\n\r\n            for(size_t i = 0; i < params::poly_p::degree; i++)\r\n            {\r\n              mpz_clears(bal_repr[i], nullptr);\r\n            }\r\n            pSample[m_aConnections(iNode,0)].invntt_pow_invphi();\r\n            pSample[m_aConnections(iNode,1)].invntt_pow_invphi();\r\n          }\r\n\r\n          output.push_back(nodeOutput);\r\n        } \r\n        return output;\r\n      }    \r\n  \r\n    bool IsNodeUsed(int iNode)\r\n      {\r\n        if (iNode > m_nNodes || iNode < 0)\r\n        {\r\n          printf(\"Invalid node is \");\r\n        }\r\n        return m_NodeFlags[iNode];\r\n      }\r\n  };\r\n\r\nclass gmdh_net\r\n  {\r\n    //number of input nodes\r\n    size_t m_nInputs;\r\n\r\n    //number of layers where polynomials evaluated (i.e. without input layer)\r\n    size_t m_nLayers;\r\n\r\n    //number of nodes in each layer\r\n    std::vector<size_t> m_NumLayerNodes;\r\n\r\n    //layers\r\n    std::vector<gmdh_net_layer> m_aLayers;\r\n\r\n    //total number of samples\r\n    size_t m_nSamples;\r\n\r\n    //amount of train and test samples\r\n    size_t m_nTrainSamples;\r\n    size_t m_nTestSamples;\r\n\r\n    //input dataset\r\n    arma::mat m_InputData;\r\n    double m_dMaxValue;\r\n    double m_dMinValue;\r\n    \r\n    //split the real output into training and test sets\r\n    arma::mat m_RealOutputDataTrain;\r\n    arma::mat m_RealOutputDataTest;\r\n\r\n    //output of the test set\r\n    arma::mat m_OutputDataTest;    \r\n\r\n    //plaintext space modulus\r\n    mpz_class m_mpzModulus;\r\n\r\n    //secret and public keys corresponding to the plaintext modulus (other parameters are global)\r\n    sk_t *m_sk;\r\n    pk_t *m_pk;\r\n\r\n    //precision for polynomial coefficients\r\n    size_t m_nIntPrec;\r\n    size_t m_nFracPrec;\r\n\r\n    //state of the network\r\n    bool m_bIsTrained;\r\n\r\n  public:\r\n    gmdh_net(): m_nInputs(0), m_nLayers(0), m_nSamples(0), m_dMaxValue(-1.0),m_dMinValue(std::numeric_limits<double>::max()), m_sk(nullptr), m_pk(nullptr), m_bIsTrained(false){}\r\n\r\n    gmdh_net(size_t const nLayers, std::vector<gmdh_net_layer> const &aLayers, mpz_class const mpzModulus, sk_t &sk, pk_t &pk, size_t nIntPrec, size_t nFracPrec): m_nLayers(nLayers), m_mpzModulus(mpzModulus), m_sk(&sk), m_pk(&pk), m_nIntPrec(nIntPrec), m_nFracPrec(nFracPrec),m_bIsTrained(false)\r\n      {\r\n        m_aLayers.clear();\r\n        for (size_t i = 0; i < aLayers.size(); i++)\r\n        {\r\n          m_aLayers.push_back(aLayers[i]);\r\n        }\r\n      }\r\n\r\n    void read_params(char* net_filename)\r\n      {\r\n        std::ifstream net_file(net_filename);\r\n        std::string line;\r\n\r\n        if(!net_file.is_open())\r\n        {\r\n          std::cout << \"Unable to open a file.\" << std::endl;\r\n          exit(1);\r\n        }\r\n\r\n        getline(net_file, line);\r\n        std::string s(\"Inputs \");\r\n        if(line.find(s) == std::string::npos)\r\n        {\r\n          printf(\"Number of inputs is undefined\\n\");\r\n          exit(1);\r\n        }\r\n        line.erase(0, s.length());\r\n        m_nInputs = std::stoi(line);\r\n        printf(\"Number of inputs %zu\\n\", m_nInputs);\r\n\r\n        getline(net_file, line);\r\n        s = \"Layers \";\r\n        if(line.find(s) == std::string::npos)\r\n        {\r\n          printf(\"Number of layers is undefined\\n\");\r\n          exit(1);\r\n        }\r\n        line.erase(0, s.length());\r\n        m_nLayers = std::stoi(line);\r\n        printf(\"Number of layers %zu\\n\", m_nLayers);\r\n        \r\n        m_aLayers.clear();\r\n        m_NumLayerNodes.clear();\r\n\r\n        bool bSkip = false;\r\n\r\n        for(int iLayer = 0; iLayer < m_nLayers; iLayer++)\r\n        {\r\n          //number of nodes in a layer\r\n          int nNodes;\r\n          //active nodes\r\n          std::vector<size_t> nodesToRemain;\r\n\r\n          if(!bSkip)\r\n            getline(net_file, line);\r\n          std::string sLayer(\"Layer \");\r\n          sLayer += std::to_string(iLayer);\r\n          if(line.find(sLayer) == std::string::npos)\r\n          {\r\n            std::cout << sLayer << \" is not found\" << std::endl;\r\n            exit(1);\r\n          }\r\n          bSkip = false;\r\n          std::cout << sLayer << std::endl;\r\n\r\n          getline(net_file, line);\r\n          s = \"Nodes \";\r\n          if(line.find(s) == std::string::npos)\r\n          {\r\n            printf(\"Number of nodes is not found\\n\");\r\n            exit(1);\r\n          }\r\n          line.erase(0, s.length());\r\n          nNodes = std::stoi(line);\r\n          m_NumLayerNodes.push_back(nNodes);\r\n          printf(\"Number of nodes %d\\n\", nNodes);\r\n\r\n          //wiring of nodes\r\n          arma::mat incomingNodes(nNodes, 2, arma::fill::zeros);\r\n          //node polynomials\r\n          arma::mat nodePolys(nNodes, 6, arma::fill::zeros);\r\n          //node regularization parameter\r\n          arma::vec nodeAlphas(nNodes, arma::fill::zeros);\r\n          \r\n          for (int iNode = 0; iNode < nNodes; iNode++)\r\n          {\r\n            if (!bSkip)\r\n              getline(net_file, line);\r\n            std::string sNode(\"Node \");\r\n            sNode += std::to_string(iNode);\r\n            if(line.find(sNode) == std::string::npos)\r\n            {\r\n              bSkip = true;\r\n              continue;\r\n            }\r\n            else\r\n              bSkip = false;\r\n            \r\n            nodesToRemain.push_back(iNode);\r\n            std::cout << sNode << std::endl;\r\n\r\n            getline(net_file, line);\r\n            s = \"Alpha \";\r\n            if(line.find(s) == std::string::npos)\r\n            {\r\n              printf(\"Regularization parameter is not found\\n\");\r\n              exit(1);\r\n            }\r\n            line.erase(0, s.length());\r\n            nodeAlphas(iNode) = std::stod(line);\r\n            printf(\"Regularization parameter is %f\\n\", nodeAlphas(iNode));\r\n\r\n            getline(net_file, line);\r\n            s = \"Input_1 \";\r\n            if(line.find(s) == std::string::npos)\r\n            {\r\n              printf(\"Input 1 is not found\\n\");\r\n              exit(1);\r\n            }\r\n            line.erase(0, s.length());\r\n            incomingNodes(iNode, 0) = std::stoi(line);\r\n            printf(\"Input 1 is %f\\n\", incomingNodes(iNode, 0));\r\n\r\n            getline(net_file, line);\r\n            s = \"Input_2 \";\r\n            if(line.find(s) == std::string::npos)\r\n            {\r\n              printf(\"Input 2 is not found\\n\");\r\n              exit(1);\r\n            }\r\n            line.erase(0, s.length());\r\n            incomingNodes(iNode, 1) = std::stoi(line);\r\n            printf(\"Input 2 is %f\\n\", incomingNodes(iNode, 1));\r\n\r\n            getline(net_file, line);\r\n            s = \"Poly \";\r\n            if(line.find(s) == std::string::npos)\r\n            {\r\n              printf(\"Polynomial coefficients are not found\\n\");\r\n              exit(1);\r\n            }\r\n            line.erase(0, s.length());\r\n            for(int iCoef = 0; iCoef < nodePolys.n_cols; iCoef++)\r\n            {\r\n              if(line.empty())\r\n              {\r\n                printf(\"Coefficient %d is not found\\n\", iCoef);\r\n                exit(1);\r\n              }\r\n              std::string::size_type last_coef_pos;\r\n              nodePolys(iNode, iCoef) = std::stod(line, &last_coef_pos);\r\n              line.erase(0, last_coef_pos + 1);\r\n            }\r\n            std::cout << \"Polynomial: \" << nodePolys.row(iNode) << std::endl;\r\n          }\r\n\r\n          gmdh_net_layer layer(nNodes, incomingNodes, nodePolys, nodeAlphas, m_mpzModulus);\r\n          layer.update_nodes(nodesToRemain);\r\n          m_aLayers.push_back(layer);\r\n        }\r\n      }\r\n\r\n    void set_layer_nodes(std::vector<size_t> const numLayerNodes)\r\n      {\r\n        m_NumLayerNodes.clear();\r\n        for(size_t i = 0; i < numLayerNodes.size(); i++)\r\n        {\r\n          m_NumLayerNodes.push_back(numLayerNodes[i]);\r\n        }\r\n        m_nLayers = m_NumLayerNodes.size();\r\n      }\r\n\r\n    void set_input_amount(int nNodes)\r\n      {\r\n        m_nInputs = nNodes;\r\n      }\r\n\r\n    void set_modulus(mpz_class const mpzModulus)\r\n      {\r\n        m_mpzModulus = mpzModulus;\r\n\r\n        for(int iLayer = 0; iLayer < m_nLayers; iLayer++)\r\n        {\r\n          m_aLayers[iLayer].set_modulus(mpzModulus);\r\n        }\r\n      }\r\n\r\n    void set_keys(sk_t &sk, pk_t &pk)\r\n      {\r\n        m_sk = &sk;\r\n        m_pk = &pk;\r\n      }\r\n\r\n    void set_layers(std::vector<gmdh_net_layer> aLayers)\r\n      {\r\n        m_aLayers.clear();\r\n        m_nLayers = aLayers.size();\r\n        for (size_t i = 0; i < m_nLayers; i++)\r\n        {\r\n          aLayers[i].set_modulus(m_mpzModulus);\r\n          m_aLayers.push_back(aLayers[i]);\r\n        }\r\n      }\r\n\r\n    void set_precisions(double approx_error)\r\n      {\r\n        if(!m_bIsTrained)\r\n        {\r\n          printf(\"gmdh_net.set_precisions: the network is not trained\\n\");\r\n          exit(1);\r\n        }\r\n\r\n        double base = get_base(nWindow);\r\n\r\n        m_nIntPrec = int_bits(get_max_abs_coef());\r\n        m_nFracPrec = size_t(-floor(log(approx_error) / log(base)));\r\n\r\n        for(int iLayer = 0; iLayer < m_nLayers; iLayer++)\r\n        {\r\n          m_aLayers[iLayer].encode_coefs(m_nIntPrec, m_nFracPrec);\r\n        }\r\n      }\r\n\r\n    //evaluate nodes in the homomorphic mode\r\n    FV::ciphertext_t evaluate(std::vector<FV::ciphertext_t>& cSample)\r\n      {\r\n        std::vector<FV::ciphertext_t> prevLayerOutput;\r\n        std::vector<FV::ciphertext_t> curLayerOutput;\r\n\r\n        prevLayerOutput = cSample;\r\n        for (int iLayer = 0; iLayer < m_nLayers; iLayer++)\r\n        {\r\n          //printf(\"Evaluate layer %d.\\n\", iLayer + 1);\r\n          //take a matrix from a layer\r\n          curLayerOutput = m_aLayers[iLayer].evaluate_enc(prevLayerOutput, m_pk, m_sk);\r\n\r\n          prevLayerOutput.clear();\r\n          prevLayerOutput = curLayerOutput;\r\n        }\r\n        return prevLayerOutput[0];\r\n      }\r\n\r\n    //evaluate nodes in the homomorphic mode via the Sujoy's hardware unit\r\n    FV::ciphertext_t evaluate_suj(std::vector<FV::ciphertext_t>& cSample)\r\n      {\r\n        std::vector<FV::ciphertext_t> prevLayerOutput;\r\n        std::vector<FV::ciphertext_t> curLayerOutput;\r\n\r\n        prevLayerOutput = cSample;\r\n        for (int iLayer = 0; iLayer < m_nLayers; iLayer++)\r\n        {\r\n          //printf(\"Evaluate layer %d.\\n\", iLayer + 1);\r\n          //take a matrix from a layer\r\n          curLayerOutput = m_aLayers[iLayer].evaluate_suj(prevLayerOutput, m_pk, m_sk);\r\n\r\n          prevLayerOutput.clear();\r\n          prevLayerOutput = curLayerOutput;\r\n        }\r\n        return prevLayerOutput[0];\r\n      }  \r\n\r\n    //evaluate nodes in the plaintext space\r\n    params::poly_p evaluate_plain(std::vector<params::poly_p>& vSample)\r\n      {\r\n        std::vector<params::poly_p> prevLayerOutput;\r\n\r\n        for (size_t i = 0; i < vSample.size(); i++)\r\n        {\r\n          prevLayerOutput.push_back(vSample[i]);  \r\n        }\r\n        \r\n        for (int iLayer = 0; iLayer < m_nLayers; iLayer++)\r\n        {\r\n          printf(\"Evaluate layer %d.\\n\", iLayer);\r\n          //take a matrix from a layer\r\n          std::vector<params::poly_p> curLayerOutput;\r\n          curLayerOutput = m_aLayers[iLayer].evaluate_plain(prevLayerOutput, m_pk);\r\n\r\n          prevLayerOutput.clear();\r\n          for(size_t j = 0; j < curLayerOutput.size(); j++)\r\n          {\r\n            prevLayerOutput.push_back(curLayerOutput[j]);\r\n          }\r\n        }\r\n        return prevLayerOutput[0];    \r\n      }\r\n\r\n    //evaluate nodes in the plaintext space with random network coefficients\r\n    params::poly_p evaluate_plain_random(std::vector<params::poly_p>& vSample)\r\n      {\r\n        std::vector<params::poly_p> prevLayerOutput;\r\n\r\n        for (size_t i = 0; i < vSample.size(); i++)\r\n        {\r\n          prevLayerOutput.push_back(vSample[i]);  \r\n        }\r\n        \r\n        for (int iLayer = 0; iLayer < m_nLayers; iLayer++)\r\n        {\r\n          //printf(\"Evaluate layer %d.\\n\", i + 1);\r\n          //take a matrix from a layer\r\n          std::vector<params::poly_p> curLayerOutput;\r\n          curLayerOutput = m_aLayers[iLayer].evaluate_plain_random(prevLayerOutput, m_pk);\r\n\r\n          prevLayerOutput.clear();\r\n          for(size_t j = 0; j < curLayerOutput.size(); j++)\r\n          {\r\n            prevLayerOutput.push_back(curLayerOutput[j]);\r\n          }\r\n        }\r\n        return prevLayerOutput[0];    \r\n      }  \r\n\r\n    //evaluate nodes in the real domain\r\n    double evaluate_double(arma::rowvec vSample)\r\n      {\r\n        arma::rowvec prevLayerOutput;\r\n\r\n        prevLayerOutput = vSample;\r\n        for (int iLayer = 0; iLayer < m_nLayers; iLayer++)\r\n        {\r\n          //printf(\"Evaluate layer %d.\\n\", iLayer + 1);\r\n          arma::rowvec curLayerOutput(m_aLayers[iLayer].evaluate_double(prevLayerOutput));\r\n          \r\n          prevLayerOutput = curLayerOutput;\r\n        }\r\n\r\n        return prevLayerOutput(0);    \r\n      }\r\n\r\n    //evaluate a file in the real domain\r\n    void evaluate_file_double(char* data_filename, int skipLines = 0)\r\n      {\r\n        printf(\"Evaluating file %s\\n\", data_filename);\r\n        std::ifstream data_file(data_filename);\r\n        std::string line;\r\n\r\n        if(!data_file.is_open())\r\n        {\r\n          std::cout << \"Unable to open a file.\" << std::endl;\r\n          exit(1);\r\n        }\r\n\r\n        //total number of samples in a file\r\n        int nSamples = 0;\r\n        while(getline(data_file, line))\r\n        {\r\n          nSamples++;\r\n        }\r\n          \r\n        data_file.clear();\r\n        data_file.seekg(0, std::ios_base::beg);\r\n\r\n        int iSample = 0;\r\n        arma::mat inputData(nSamples - skipLines, m_nInputs);\r\n        arma::mat realOutputData(nSamples - skipLines, 1);\r\n        arma::mat outputData(nSamples - skipLines, 1);\r\n\r\n        while(getline(data_file, line))\r\n        {\r\n          if (iSample < skipLines)\r\n          {\r\n            iSample++;\r\n            continue;\r\n          }\r\n          int iCol = 0;\r\n          std::string::size_type last_pos;\r\n\r\n          while(!line.empty())\r\n          {\r\n            //srand(time(NULL));\r\n\r\n            double cur_value = std::stod(line, &last_pos) / scalar; //data scaled\r\n            double abs_cur_value = fabs(cur_value); //absolute value of a data value to find a bit range\r\n\r\n            m_dMinValue = (abs_cur_value < m_dMinValue)? abs_cur_value: m_dMinValue;\r\n            m_dMaxValue = (abs_cur_value > m_dMaxValue)? abs_cur_value: m_dMaxValue;\r\n\r\n            if(iCol < m_nInputs) \r\n            {\r\n              inputData(iSample - skipLines, iCol) = cur_value;\r\n            }\r\n            if(iCol == m_nInputs)\r\n            {\r\n              realOutputData(iSample - skipLines, 0) = cur_value;\r\n            } \r\n            line.erase(0, last_pos + 1);\r\n            iCol++; \r\n          }\r\n          outputData(iSample - skipLines, 0) = evaluate_double(inputData.row(iSample - skipLines));\r\n\r\n          iSample++;\r\n        }\r\n        data_file.close();\r\n\r\n        std::cout << \"MSE: \" << mse(outputData, realOutputData) << std::endl;\r\n        std::cout << \"MAPE: \" << mape(outputData, realOutputData) << std::endl;\r\n      }\r\n  \r\n    //evaluate nodes over reals approximated by w-NIBNAF\r\n    double evaluate_approx(arma::rowvec vSample)\r\n      {\r\n\r\n        arma::rowvec prevLayerOutput;\r\n\r\n        prevLayerOutput = vSample;\r\n        for (int iLayer = 0; iLayer < m_nLayers; iLayer++)\r\n        {\r\n          //printf(\"Evaluate layer %d.\\n\", iLayer + 1);\r\n          arma::rowvec curLayerOutput(m_aLayers[iLayer].evaluate_approx(prevLayerOutput));\r\n          \r\n          prevLayerOutput = curLayerOutput;\r\n        }\r\n\r\n        return prevLayerOutput(0);    \r\n      }\r\n\r\n    //load data file and form input and output\r\n    void get_data(char* data_filename)\r\n      {\r\n        printf(\"Get data...\\n\");\r\n        std::ifstream data_file(data_filename);\r\n        std::string line;\r\n\r\n        if(data_file.is_open())\r\n        {\r\n          int iSample = 0;\r\n          while(getline(data_file, line))\r\n          {\r\n            iSample++;\r\n          }\r\n\r\n          //set total number of samples\r\n          m_nSamples = iSample;\r\n          \r\n          data_file.clear();\r\n          data_file.seekg(0, std::ios_base::beg);\r\n        }\r\n        else\r\n        {\r\n          std::cout << \"Unable to open a file.\" << std::endl;\r\n          exit(1); \r\n        }\r\n\r\n        m_InputData = arma::mat(m_nSamples, m_nInputs);\r\n\r\n        arma::mat m_RealOutputData(m_nSamples, 1);\r\n\r\n        if(data_file.is_open())\r\n        {\r\n          int iSample = 0;\r\n          while(getline(data_file, line))\r\n          {\r\n            int iCol = 0;\r\n            std::string::size_type last_pos;\r\n\r\n            while(!line.empty())\r\n            {\r\n              //srand(time(NULL));\r\n\r\n              double cur_value = std::stod(line, &last_pos) / scalar; //data scaled\r\n              double abs_cur_value = fabs(cur_value); //absolute value of a data value to find a bit range\r\n\r\n              m_dMinValue = (abs_cur_value < m_dMinValue)? abs_cur_value: m_dMinValue;\r\n              m_dMaxValue = (abs_cur_value > m_dMaxValue)? abs_cur_value: m_dMaxValue;\r\n\r\n              if(iCol < m_nInputs) \r\n              {\r\n                m_InputData(iSample, iCol) = cur_value;\r\n              }\r\n              if(iCol == m_nInputs)\r\n              {\r\n                m_RealOutputData(iSample, 0) = cur_value;\r\n              } \r\n              line.erase(0, last_pos + 1);\r\n              iCol++; \r\n            }\r\n            iSample++; \r\n          }\r\n\r\n          //split the data into training and test set according to the ratio 2:1\r\n          m_nTrainSamples = 2 * m_nSamples / 3;\r\n          m_nTestSamples = m_nSamples / 3;           \r\n\r\n          m_RealOutputDataTrain = m_RealOutputData.submat(0, 0, m_nTrainSamples - 1, 0);\r\n          m_RealOutputDataTest = m_RealOutputData.submat(m_nTrainSamples, 0, m_nSamples - 1, 0);\r\n\r\n          printf(\"Number of training samples: %zu\\n\", m_nTrainSamples);\r\n          printf(\"Number of test samples: %zu\\n\", m_nTestSamples);\r\n\r\n          data_file.close();\r\n        }\r\n        else\r\n        {\r\n          std::cout << \"Unable to open a file.\" << std::endl;\r\n        }\r\n      }\r\n\r\n    //construct a new layer\r\n    gmdh_net_layer construct_layer(size_t const iLayer)\r\n      {\r\n        if(iLayer >= m_nLayers)\r\n        {\r\n          printf(\"The maximal number of layers is exceeded!\\n\");\r\n          exit(1);\r\n        }\r\n\r\n        arma::mat layerInput;\r\n        if(iLayer == 0)\r\n        {\r\n          layerInput = m_InputData;\r\n        }\r\n        else\r\n        {\r\n          layerInput = m_aLayers[iLayer - 1].get_output();\r\n        }\r\n\r\n        const int inputSize = layerInput.n_cols;\r\n\r\n        //input matrix of the linear regression problem        \r\n        arma::mat Xtrain(m_nTrainSamples, 6);\r\n\r\n        //test input \r\n        arma::mat Xtest(m_nTestSamples, 6);\r\n\r\n        //error matrix for node selection\r\n        arma::vec nodeErrors(m_NumLayerNodes[iLayer]);\r\n        nodeErrors.fill(100000000.0);\r\n        //index of the worst node in a layer\r\n        size_t max_error_node_ind = 0;\r\n\r\n        //wiring of nodes\r\n        arma::mat incomingNodes(m_NumLayerNodes[iLayer], 2);\r\n\r\n        //node polynomials\r\n        arma::mat nodePolys(m_NumLayerNodes[iLayer], 6);\r\n\r\n        //layer output\r\n        arma::mat layerOutput(m_nSamples, m_NumLayerNodes[iLayer]);\r\n\r\n        //node regularization parameter\r\n        arma::vec nodeAlphas(m_NumLayerNodes[iLayer]);\r\n\r\n        for(int k = 0; k < m_nTrainSamples; k++)\r\n        {\r\n          Xtrain(k, 0) = 1.0;\r\n        }\r\n        for(int k = 0; k < m_nTestSamples; k++)\r\n        {\r\n          Xtest(k, 0) = 1.0;\r\n        }\r\n\r\n        //check all pairs of input parameters\r\n        for(size_t i = 0; i < inputSize - 1; i++)\r\n        {\r\n          //form the input matrix of the linear regression problem\r\n          for(int k = 0; k < m_nTrainSamples; k++)\r\n          {\r\n            Xtrain(k, 1) = layerInput(k,i);\r\n            Xtrain(k, 4) = layerInput(k,i) * layerInput(k,i);\r\n          }\r\n          for(int k = 0; k < m_nTestSamples; k++)\r\n          {\r\n            Xtest(k, 1) = layerInput(k + m_nTrainSamples, i);\r\n            Xtest(k, 4) = layerInput(k + m_nTrainSamples, i) * layerInput(k + m_nTrainSamples, i);\r\n          }\r\n          for(size_t j = i + 1; j < inputSize; j++)\r\n          {\r\n            //printf(\"Check node %zu with node %zu\\n\", i, j);\r\n            //form the input matrix of the linear regression problem\r\n            for(int k = 0; k < m_nTrainSamples; k++)\r\n            {  \r\n              Xtrain(k, 2) = layerInput(k, j);\r\n              Xtrain(k, 3) = layerInput(k, i) * layerInput(k, j);\r\n              Xtrain(k, 5) = layerInput(k, j) * layerInput(k, j);\r\n            }\r\n            for(int k = 0; k < m_nTestSamples; k++)\r\n            {  \r\n              Xtest(k, 2) = layerInput(k + m_nTrainSamples, j);\r\n              Xtest(k, 3) = layerInput(k + m_nTrainSamples, i) * layerInput(k + m_nTrainSamples, j);\r\n              Xtest(k, 5) = layerInput(k + m_nTrainSamples, j) * layerInput(k + m_nTrainSamples, j);\r\n            }\r\n\r\n            //regularization parameters of linear regression\r\n            const int nAlphas = 11;\r\n            double alpha[nAlphas];            \r\n\r\n            //precomputed heavy matrix calculations\r\n            arma::mat Xt(arma::trans(Xtrain));\r\n            arma::mat XtX(Xt * Xtrain);\r\n            arma::mat XtY(Xt * m_RealOutputDataTrain);\r\n\r\n            double min_alpha_error = 100000000.0;\r\n            double min_alpha = 0.0;\r\n            arma::mat minAlphaPolynom;\r\n            arma::mat minAlphaNodeOutput;\r\n\r\n            for (int iAlpha = 0; iAlpha < nAlphas; iAlpha++)\r\n            {\r\n              //regularization parameters of linear regression\r\n              alpha[iAlpha] = pow(10.0, (iAlpha - 5) * 1.0 / pow(scalar, 2.0));\r\n\r\n              //perform the formula (X^t X + alpha * I)^(-1) X^t Y to get coefficients over the training set using different regularization parameters\r\n              arma::mat polynom(arma::inv(XtX + alpha[iAlpha] * arma::eye(6,6)) * XtY);\r\n\r\n              //find outcome of the node using the test set\r\n              arma::mat nodeOutput(Xtest * polynom);\r\n              \r\n              //find the MSE of the node output\r\n              double error = mse(nodeOutput, m_RealOutputDataTest);\r\n\r\n              if (error < min_alpha_error)\r\n              {\r\n                min_alpha_error = error;\r\n                min_alpha = alpha[iAlpha];\r\n                minAlphaPolynom = polynom;\r\n                minAlphaNodeOutput =  arma::join_cols(Xtrain * polynom, nodeOutput);\r\n              }\r\n            }\r\n\r\n            //compare min_alpha_error among nodes and choose best m_NumLayerNodes[iLayer] ones\r\n            if (min_alpha_error < nodeErrors[max_error_node_ind])\r\n            {\r\n              nodeErrors(max_error_node_ind) = min_alpha_error;\r\n              nodeAlphas(max_error_node_ind) = min_alpha;\r\n\r\n              incomingNodes(max_error_node_ind, 0) = i;\r\n              incomingNodes(max_error_node_ind, 1) = j;\r\n\r\n              for(int k = 0; k < 6; k++)\r\n              {\r\n                nodePolys(max_error_node_ind, k) = minAlphaPolynom(k, 0);  \r\n              }\r\n\r\n              for(int k = 0; k < m_nSamples; k++)\r\n                {\r\n                  layerOutput(k, max_error_node_ind) = minAlphaNodeOutput(k, 0);\r\n                }\r\n              \r\n\r\n              max_error_node_ind = nodeErrors.index_max();\r\n            }            \r\n          }\r\n        }\r\n        gmdh_net_layer newLayer(m_NumLayerNodes[iLayer], incomingNodes, nodePolys, layerOutput, nodeErrors.index_min(), nodeErrors, nodeAlphas, m_mpzModulus);\r\n\r\n        return newLayer;\r\n      }\r\n\r\n    //construct a neural network\r\n    void train()\r\n      {\r\n        printf(\"Train...\\n\");\r\n        m_aLayers.clear();\r\n\r\n        float min_error = 100000000.0;\r\n        size_t min_index = 0;\r\n\r\n        for(int iLayer = 0; iLayer < m_nLayers; iLayer++)\r\n        {\r\n          //construct a layer and get the minimal error among its nodes and the corresponding index of that node\r\n          gmdh_net_layer layer = construct_layer(iLayer);\r\n          \r\n          if (layer.get_min_error() < min_error)\r\n          {\r\n            min_error = layer.get_min_error();\r\n            min_index = layer.get_min_error_node();\r\n            m_aLayers.push_back(layer);\r\n\r\n            if(iLayer == (m_nLayers - 1))\r\n              {\r\n                std::vector<size_t> nodesToRemain;\r\n                for(int prevLayer = iLayer; prevLayer >= 1; prevLayer--)\r\n                  {\r\n                    nodesToRemain = m_aLayers[prevLayer].get_input_nodes();\r\n                    m_aLayers[prevLayer - 1].update_nodes(nodesToRemain);\r\n                  } \r\n              }\r\n            m_OutputDataTest = m_aLayers[iLayer].get_output().rows(m_nTrainSamples, m_nSamples - 1);\r\n            printf(\"Layer %d is created.\\n\", iLayer);\r\n          }\r\n          else\r\n          {\r\n            //output the best node from the previous layer. It will be the final output\r\n            //set the last layer as an output one with only one node\r\n            std::vector<size_t> nodesToRemain;\r\n            nodesToRemain.push_back(min_index); \r\n            m_aLayers[iLayer - 1].update_nodes(nodesToRemain);            \r\n\r\n            //update number of nodes needed for evaluation going backwards\r\n            for(int prevLayer = iLayer - 1; prevLayer > 0; prevLayer--)\r\n            {\r\n              nodesToRemain = m_aLayers[prevLayer].get_input_nodes();\r\n              m_aLayers[prevLayer - 1].update_nodes(nodesToRemain);\r\n            }\r\n            if(iLayer < m_nLayers)\r\n            {\r\n              m_nLayers = iLayer;\r\n              //exit(1);  //uncomment for any number of layers gotten after training\r\n            }\r\n\r\n            break;\r\n          }\r\n        }\r\n        m_bIsTrained = true;\r\n      }\r\n\r\n    //linear regression\r\n    void lin_regression()\r\n      {\r\n        printf(\"Linear regression...\\n\");\r\n\r\n        //input matrix of the linear regression problem        \r\n        arma::mat Xtrain(m_nTrainSamples, m_nInputs + 1);\r\n\r\n        //test input \r\n        arma::mat Xtest(m_nTestSamples, m_nInputs + 1);\r\n\r\n        for (int i = 0; i < m_nTrainSamples; i++)\r\n        {\r\n          for (int j = 0; j < m_nInputs; j++)\r\n          {\r\n            Xtrain(i,j) = m_InputData(i, j);\r\n          }\r\n          Xtrain(i, m_nInputs) = 1.0;\r\n        }\r\n\r\n        for (int i = 0; i < m_nTestSamples; i++)\r\n        {\r\n          for (int j = 0; j < m_nInputs; j++)\r\n          {\r\n            Xtest(i,j) = m_InputData(i + m_nTrainSamples, j);\r\n          }\r\n          Xtest(i, m_nInputs) = 1.0;\r\n        }\r\n\r\n        //coefficients of regression\r\n        arma::mat coefs(m_nInputs + 1, 1);           \r\n\r\n        //precomputed heavy matrix calculations\r\n        arma::mat Xt(arma::trans(Xtrain));\r\n        arma::mat XtX(Xt * Xtrain);\r\n        arma::mat XtY(Xt * m_RealOutputDataTrain);\r\n\r\n        double min_alpha_error = 100000000.0;\r\n        double min_alpha = 0.0;\r\n        double min_mape = 0.0;\r\n        arma::mat minAlphaPolynom;\r\n\r\n        //number of regularization parameters\r\n        int nAlphas = 11;\r\n        double alpha;\r\n\r\n        for (int iAlpha = 0; iAlpha < nAlphas; iAlpha++)\r\n        {\r\n          //regularization parameters of linear regression\r\n          alpha = pow(10.0, (iAlpha - 5) * 1.0 / pow(scalar, 2.0));\r\n\r\n          //perform the formula (X^t X + alpha * I)^(-1) X^t Y to get coefficients over the training set using different regularization parameters\r\n          arma::mat polynom(arma::inv(XtX + alpha * arma::eye(m_nInputs + 1, m_nInputs + 1)) * XtY);\r\n\r\n          //find outcome of the node using the test set\r\n          arma::mat output(Xtest * polynom);\r\n          \r\n          //find the MSE of the node output\r\n          double error = mse(output, m_RealOutputDataTest);\r\n\r\n          if (error < min_alpha_error)\r\n          {\r\n            min_alpha_error = error;\r\n            min_mape = mape(output, m_RealOutputDataTest);\r\n            min_alpha = alpha;\r\n            minAlphaPolynom = polynom;\r\n          }\r\n        }\r\n        std::cout << \"Coefficients:\" << std::endl << minAlphaPolynom << std::endl;\r\n\r\n        printf(\"MSE: %f\\n\", min_alpha_error);\r\n        printf(\"MAPE: %f\\n\", min_mape);\r\n\r\n      }\r\n\r\n    //naive prediction where the predictied value is equal to the last measurement done\r\n    void naive_prediction()\r\n      {\r\n        printf(\"Naive prediction: \\n\");\r\n\r\n        arma::mat output(m_nTestSamples, 1);\r\n        for (int i = 0; i < m_nTestSamples; i++)\r\n        {\r\n          output(i) = m_InputData(m_nTrainSamples + i, 47);\r\n        }\r\n\r\n        printf(\"MSE: %f\\n\", mse(output, m_RealOutputDataTest));\r\n        printf(\"MAPE: %f\\n\", mape(output, m_RealOutputDataTest));\r\n      }\r\n\r\n    //get the maximal absolute value of network coefficients\r\n    double get_max_abs_coef() const\r\n      {\r\n        if(!m_bIsTrained)\r\n        {\r\n          printf(\"get_max_abs_coef: the network is not trained\\n\");\r\n          exit(1);\r\n        }\r\n        double res;\r\n        double tmp;\r\n        for(int iLayer = 0; iLayer < m_nLayers; iLayer++)\r\n        {\r\n          tmp = m_aLayers[iLayer].get_max_abs_coef();\r\n          if  (tmp > res)\r\n          {\r\n            res = tmp;\r\n          }\r\n        }\r\n\r\n        return res;\r\n      }\r\n\r\n    //show the network structure\r\n    void print_layers() const\r\n      {\r\n        printf(\"Network structure: \\n\");\r\n        printf(\"Number of layers: %zu\\n\\n\", m_nLayers);\r\n        for(int iLayer = 0; iLayer < m_nLayers; iLayer++)\r\n        {\r\n          printf(\"Layer %d\\n\", iLayer);\r\n          m_aLayers[iLayer].print();\r\n        }\r\n      }\r\n\r\n    //print layers encoded by w-NIBNAF\r\n    void print_layers_encoded() const\r\n      {\r\n        for(size_t iLayer = 0; iLayer < m_nLayers; iLayer++)\r\n        {\r\n          printf(\"Layer %zu\\n\", iLayer);\r\n          m_aLayers[iLayer].print_encodings();\r\n        }\r\n      }\r\n\r\n    //get number of test samples\r\n    size_t get_num_test_samples() const\r\n      {\r\n        return m_nTestSamples;\r\n      }\r\n\r\n    //get a number of input nodes\r\n    size_t get_input_nodes() const\r\n      {\r\n        return m_nInputs;\r\n      }\r\n\r\n    arma::mat get_test_input() const\r\n      {\r\n        return m_InputData.rows(m_nTrainSamples, m_nSamples - 1);\r\n      }\r\n\r\n    arma::mat get_test_output() const\r\n      {\r\n        return m_RealOutputDataTest;\r\n      }\r\n\r\n    //get minimal data value\r\n    double get_min_value() const\r\n      {\r\n        return m_dMinValue;\r\n      }\r\n\r\n    //get maximal data value\r\n    double get_max_value() const\r\n      {\r\n        return m_dMaxValue;\r\n      }\r\n\r\n    arma::mat get_net_output() const\r\n      {\r\n        return m_OutputDataTest;\r\n      }\r\n  \r\n    void get_poly_bit_range(size_t& intPart, size_t& fracPart)\r\n      {\r\n        intPart = m_nIntPrec;\r\n        fracPart = m_nFracPrec;\r\n      }\r\n  };\r\n\r\n\r\nparams::poly_p read_poly_from_file(char* filename)\r\n  {\r\n      std::ifstream file(filename);\r\n      std::string line;\r\n\r\n\tprintf(\"file name %s\\n\", filename);\r\n      if(!file.is_open())\r\n      {\r\n        std::cout << \"Unable to open a file.\" << std::endl;\r\n        exit(1);\r\n      }\r\n\r\n      std::array<mpz_t, params::poly_p::degree> poly_array;\r\n      params::poly_p poly;\r\n      for (size_t i = 0; i < params::poly_p::degree; i++)\r\n      {\r\n        mpz_inits(poly_array[i], nullptr);\r\n      }\r\n      size_t index = 0;\r\n      while (getline(file,line))\r\n      {\r\n        mpz_set_str(poly_array[index], line.c_str(), 10);\r\n        //std::cout << index << \" \" << poly_array[index] << std::endl;\r\n        index++;\r\n      }\r\n      poly.mpz2poly(poly_array);\r\n      for (size_t i = 0; i < params::poly_p::degree; i++)\r\n      {\r\n        mpz_clears(poly_array[i], nullptr);\r\n      }\r\n      \r\n      return poly;\r\n  }\r\n\r\nint main() {\r\n \r\n  srand (1234);\r\n  compute_barrett_constants();\r\n  compute_crt_constants();\r\n  creat_primrt_array( );\r\n  compute_pby_t();\r\n  read_keys();\r\n  \r\n  HW_INIT_HW();\r\n\r\n  printf(\"System initialized\\n\");\r\n\r\n  //switch for different algorithm modes\r\n  bool bCipherMode = true;\r\n  bool bPlainMode = true;\r\n  bool bWriteCoefs = false;\r\n\r\n  for(int iWindow = 950; iWindow < 951; iWindow++) {\r\n    //gap of w-NIBNAF\r\n    nWindow = iWindow;\r\n    //precisions for input values and network polynomial coefficients\r\n    printf(\"w: %d\\n\", nWindow);\r\n\r\n    //w-NIBNAF base\r\n    double base = get_base(nWindow);\r\n    printf(\"base: %f\\n\", base);\r\n\r\n    //global scalar\r\n    //scalar = pow(get_base(nWindow),32.0);\r\n\r\n    //create a network\r\n    gmdh_net net;\r\n\r\n    //number of nodes in the input layer\r\n    const size_t nInputNodes = 51;\r\n\r\n    //max degree of polynomials in R_q and R_t\r\n    const size_t d = params::poly_t::degree;\r\n\r\n    //assign number of input nodes\r\n    net.set_input_amount(nInputNodes);\r\n\r\n    //assign number of nodes at each layer\r\n    std::vector<size_t> layerNodes;\r\n    layerNodes.push_back(8);\r\n    layerNodes.push_back(4);\r\n    layerNodes.push_back(2);\r\n    layerNodes.push_back(1);\r\n    net.set_layer_nodes(layerNodes);\r\n\r\n    //data filename\r\n    char data_filename[] = \"data.txt\";\r\n\r\n    //load data into the network\r\n    net.get_data(data_filename);\r\n\r\n    //approximation error\r\n    double inputApproxError = 1.0;\r\n    double polyApproxError = 0.020426459400003687;\r\n\r\n    //bit range for input data\r\n    printf(\"Max data value: %f\\n\", net.get_max_value());\r\n    size_t nInputIntPrec = int_bits(net.get_max_value());\r\n    size_t nInputFracPrec = size_t(-floor(log(inputApproxError) / log(base)));\r\n\r\n    //naive prediction\r\n    net.naive_prediction();\r\n\r\n    //linear regression\r\n    net.lin_regression();\r\n\r\n    //train the network\r\n    net.train();\r\n\r\n    //print neural network structure\r\n    net.print_layers();\r\n\r\n    //set network precisions\r\n    net.set_precisions(polyApproxError);\r\n\r\n    //bit range for network coefficients\r\n    size_t nPolyIntPrec;\r\n    size_t nPolyFracPrec;\r\n    net.get_poly_bit_range(nPolyIntPrec, nPolyFracPrec);\r\n\r\n    printf(\"Input precs: %zu, %zu\\n\", nInputIntPrec, nInputFracPrec);\r\n    printf(\"Poly precs: %zu, %zu\\n\", nPolyIntPrec, nPolyFracPrec);\r\n\r\n    printf(\"Coefs: %d\\n\", int(ceil(fmax(nInputIntPrec * 1.0 / nWindow, (nPolyIntPrec + nPolyFracPrec) * 1.0 / nWindow))));\r\n\r\n    /*\r\n    if (fmax(nInputIntPrec/iWindow, (nPolyIntPrec + nPolyFracPrec)/iWindow) < 1.0)\r\n    {\r\n      break;\r\n    }\r\n    */\r\n\r\n    //index of coefficient where to split integral and fractional part\r\n    if(nWindow >= 1)\r\n    {\r\n      cut_point = 385;\r\n    }\r\n    else\r\n    {\r\n      size_t n_int_bits = int(pow(2, layerNodes.size())) * (nInputIntPrec - 1) + (int(pow(2, layerNodes.size())) - 1) * (nPolyIntPrec - 1) + 1;\r\n      size_t n_frac_bits = int(pow(2, layerNodes.size())) * nInputFracPrec + (int(pow(2, layerNodes.size())) - 1) * nPolyFracPrec;\r\n      cut_point = (d - n_frac_bits + n_int_bits)/2;\r\n      printf(\"Sum of bits: %zu\\n\", n_int_bits + n_frac_bits);\r\n      printf(\"Cut point: %zu\\n\", cut_point);\r\n\r\n      if((cut_point > d-1) || (n_int_bits + n_frac_bits > d))\r\n      {\r\n        printf(\"Wrong cut point!\\n\");\r\n        exit(1);\r\n        //cut_point = d/2;\r\n      }\r\n    }\r\n\r\n    printf(\"Cut point: %zu\\n\", cut_point);\r\n\r\n    //cut point for initial encodings\r\n    cut_point_init = (d - std::max(nInputFracPrec, nPolyFracPrec) + std::max(nInputIntPrec, nPolyIntPrec)) / 2;\r\n\r\n    //net output of the test set\r\n    arma::mat output_net_double = net.get_net_output();\r\n\r\n    //expected output\r\n    arma::mat output_real = arma::mat(net.get_test_output());\r\n\r\n    std::cout << \"MSE: \" << mse(output_net_double, output_real) << std::endl;\r\n    std::cout << \"MAPE: \" << mape(output_net_double, output_real) << std::endl;\r\n\r\n    //print encoded polynomial coefficients\r\n    net.print_layers_encoded();\r\n\r\n    //evaluate file\r\n    //char validation_file[] = \"data/data_1000_1002_1016_1018_1023_1047_1059_1067-1068_1087.txt\";\r\n    //net.evaluate_file_double(validation_file);\r\n\r\n    //just train\r\n    //exit(0);    \r\n\r\n    if(!bCipherMode && !bPlainMode)\r\n      return 0;\r\n\r\n    //output array in the encrypted, real and plain form\r\n    arma::vec output_net_enc;\r\n    arma::vec output_net_plain;\r\n    //floating point output with approximations made while working with w-NIBNAF\r\n    arma::vec output_net_approx;\r\n    \r\n    if(bCipherMode)\r\n      output_net_enc = arma::vec(net.get_num_test_samples());\r\n    if(bPlainMode)\r\n    {\r\n      output_net_plain = arma::vec(net.get_num_test_samples());\r\n      output_net_approx = arma::vec(net.get_num_test_samples());\r\n    }\r\n\r\n    double total_time = 0.0;\r\n\r\n    //create a file to store coefficients\r\n    std::ofstream fout;\r\n    if(bWriteCoefs)\r\n    {\r\n      //define an array to contain polynomial coefficients per run\r\n      std::string s = std::to_string(nWindow);\r\n      const char* wstring = s.c_str();\r\n\r\n      char coefs_file[15];\r\n      std::strcpy(coefs_file, wstring);\r\n      std::strcat(coefs_file, \"-coefs.txt\");\r\n\r\n      fout.open(coefs_file);\r\n    }\r\n\r\n    size_t nTestSamples = net.get_num_test_samples();\r\n\r\n\r\n    //without SIMD packing\r\n    double max_error = 0.0;\r\n    double min_error = 100000.0;\r\n\r\n    size_t max_error_ind = -1;\r\n    size_t min_error_ind = -1;\r\n\r\n    int counter_eval=0;\r\n\r\n    for(size_t iSample = 0; iSample < nTestSamples; iSample++)\r\n    { \r\n      //time start for one run of the algorithm\r\n      auto start = std::chrono::system_clock::now();\r\n    \r\n      // if(counter_eval==2) break;\r\n      // counter_eval++;\r\n\r\n\r\n      mpf_class res_f;\r\n      if(bCipherMode)\r\n      {\r\n        //output in the CRT form\r\n        std::array<params::poly_p, nPltxtModuli> poly_crt_res;\r\n\r\n        //loop for every modulus\r\n        for(int i = 0; i < nPltxtModuli; i++)\r\n        {\r\n          //time start for one modulus\r\n          auto start_one_mod = std::chrono::system_clock::now();\r\n          \r\n          \r\n          //initialize a neural network\r\n          mpz_class curModulus = mpz_class(plaintextModuli[i]);\r\n          params::plaintextModulus<mpz_class>::value_mpz = curModulus;\r\n\r\n          //generate keys\r\n          params::poly_p sk_poly = read_poly_from_file(\"keys/sk\");\r\n          sk_t sk(sk_poly);\r\n          params::poly_p evk_polys[4];\r\n          evk_polys[0] = read_poly_from_file(\"keys/rlk0_0\");\r\n          evk_polys[1] = read_poly_from_file(\"keys/rlk0_1\");\r\n          evk_polys[2] = read_poly_from_file(\"keys/rlk1_0\");\r\n          evk_polys[3] = read_poly_from_file(\"keys/rlk1_1\");\r\n          evk_t evk(evk_polys, 91);\r\n          params::poly_p pk_polys[2];\r\n          pk_polys[0] = read_poly_from_file(\"keys/pk0\");\r\n          pk_polys[1] = read_poly_from_file(\"keys/pk1\");\r\n          pk_t pk(sk, evk, pk_polys);\r\n\r\n          //set the current modulus, sk, pk to the net\r\n          net.set_modulus(curModulus);\r\n          net.set_keys(sk, pk);\r\n          \r\n          //convert data to CRT\r\n          std::vector<FV::ciphertext_t> vSample;\r\n\r\n          for(int k = 0; k < nInputNodes; k++)\r\n          {\r\n            //std::cout << \"Current input node: \" << k+1 << std::endl;\r\n            params::poly_p tmpPoly;\r\n            //convert to balanced ternary expansion and then to a corresponding polynomial\r\n            convert_to_crt_one_modulus(tmpPoly, net.get_test_input()(iSample, k), nInputIntPrec, nInputFracPrec);\r\n\r\n            //encrypt data\r\n            FV::ciphertext_t c;\r\n            FV::encrypt_poly(c, pk, tmpPoly);\r\n\r\n            vSample.push_back(c);\r\n          }\r\n\r\n          //evaluate a neural network in the encrypted mode\r\n          FV::ciphertext_t c_res;\r\n          c_res = net.evaluate_suj(vSample);\r\n\r\n          //noise\r\n          int noiseBits = poly_noise(sk, pk, c_res);\r\n\r\n          if(noiseBits > pk.noise_max)\r\n          {\r\n            std::cout << \"OVERFLOW!\" << std::endl;\r\n            exit(1);\r\n          }\r\n          std::cout << std::endl;\r\n\r\n          //decryption\r\n          std::array<mpz_t, d> res_repr;\r\n          for (size_t j = 0; j < d; j++)\r\n          {\r\n            mpz_inits(res_repr[j], nullptr);\r\n          }\r\n          \r\n          //decrypt results\r\n          FV::decrypt_poly(res_repr, sk, pk, c_res);\r\n          poly_crt_res[i].mpz2poly(res_repr);\r\n\r\n          auto end_one_mod = std::chrono::system_clock::now();\r\n\r\n          std::cout << \"Time after one sample/one module (in sec): \" << get_time_us(start_one_mod, end_one_mod, 1000000) << std::endl;\r\n\r\n          for (size_t j = 0; j < d; j++)\r\n          {\r\n            mpz_clears(res_repr[j], nullptr);\r\n          }\r\n\r\n          //reset modulus\r\n          params::plaintextModulus<mpz_class>::reset();\r\n          \r\n        }\r\n        \r\n\r\n        //convert back from CRT\r\n        res_f = convert_from_crt(poly_crt_res, cut_point);\r\n        \r\n      }\r\n      \r\n      //evaluation in the plaintext space\r\n      mpf_class res_f_plain;\r\n      if(bPlainMode)\r\n      {\r\n        params::plaintextModulus<mpz_class>::value_mpz=mpz_class(params::poly_p::moduli_product());\r\n        sk_t sk;\r\n        evk_t evk(sk, 32);\r\n        pk_t pk(sk, evk);\r\n\r\n        net.set_modulus(mpz_class(params::poly_p::moduli_product()));\r\n        net.set_keys(sk, pk);\r\n\r\n        //plain input vector\r\n        std::vector<params::poly_p> poly_crt_sample;\r\n        //approximation input vector\r\n        arma::rowvec approx_sample = arma::rowvec(nInputNodes);\r\n\r\n        for(int k = 0; k < nInputNodes; k++)\r\n        {\r\n          //printf(\"Input node %d\\n\", k);\r\n          params::poly_p tmpPoly;\r\n          convert_to_crt_one_modulus(tmpPoly, net.get_test_input()(iSample, k), nInputIntPrec, nInputFracPrec);\r\n          approx_sample(k) = naf_to_float(tmpPoly, cut_point_init, params::plaintextModulus<mpz_class>::product_mpz.get_mpz_t()).get_d();\r\n          poly_crt_sample.push_back(tmpPoly);\r\n        }\r\n\r\n        //printf(\"\\n\");\r\n        params::poly_p poly_res_plain;\r\n        poly_res_plain = net.evaluate_plain(poly_crt_sample);\r\n\r\n        output_net_approx(iSample) = net.evaluate_approx(approx_sample);\r\n\r\n        std::array<mpz_t, d> res_repr;\r\n        for (size_t j = 0; j < d; j++)\r\n        {\r\n          mpz_inits(res_repr[j], nullptr);\r\n        }\r\n      \r\n        poly_res_plain.poly2mpz(res_repr);\r\n\r\n        for(size_t j= 0; j < d; j++)\r\n        {\r\n          //put coefficient in range (-q/2, q/2]\r\n          util::center(res_repr[j], res_repr[j], params::poly_p::moduli_product(), evk.qDivBy2);\r\n\r\n          /*\r\n          if(mpz_cmp_d(res_repr[j], 396) > 0 || mpz_cmp_d(res_repr[j], -396) < 0)\r\n          {\r\n            printf(\"The maximal coefficient is bigger than 396\\n\");\r\n            goto end_loop;\r\n          }\r\n          */\r\n\r\n          if(bWriteCoefs)\r\n          {\r\n            //write coefficients to the file\r\n            char tmp[] = \"\";\r\n            fout << mpz_get_str(tmp, 10, res_repr[j]) << \" \";\r\n          }\r\n        \r\n          //mod t\r\n          mpz_mod(res_repr[j], res_repr[j], params::plaintextModulus<mpz_class>::product_mpz.get_mpz_t());\r\n        }\r\n        if(bWriteCoefs)\r\n          fout << std::endl;\r\n\r\n        //print_poly_array(res_repr);\r\n\r\n        poly_res_plain.mpz2poly(res_repr);\r\n\r\n        for (size_t j = 0; j < d; j++)\r\n        {\r\n          mpz_clears(res_repr[j], nullptr);\r\n        }\r\n\r\n        //print_poly(poly_res_plain);\r\n\r\n        res_f_plain = naf_to_float(poly_res_plain, cut_point, params::plaintextModulus<mpz_class>::product_mpz.get_mpz_t());\r\n      }\r\n      \r\n      //time end for the whole algorithm\r\n      auto end = std::chrono::system_clock::now();\r\n      total_time += get_time_us(start, end, 1000000);\r\n\r\n      printf(\"w-NAF: %d\\n\", nWindow);\r\n      std::cout << \"Time after one sample (in sec): \" << get_time_us(start, end, 1000000) << \" avg.: \" << total_time/(iSample + 1) << std::endl;\r\n      std::cout << \"Remaining time (in sec): \" << total_time / (iSample + 1) * (nTestSamples - (iSample + 1)) << std::endl;\r\n      \r\n      std::cout << \"Real output: \" << output_real(iSample) << std::endl;\r\n      if(bCipherMode)\r\n        std::cout << \"Evaluation in the cipher mode: \" << res_f.get_d() << std::endl;\r\n      std::cout << \"Evaluation in the floating point mode: \" << output_net_double(iSample) << std::endl;\r\n      if(bPlainMode)\r\n      {\r\n        std::cout << \"Evaluation in the plain(poly) mode: \" << res_f_plain.get_d() << std::endl;\r\n        std::cout << \"Evaluation in the approximation mode: \" << output_net_approx(iSample) << std::endl;\r\n      }\r\n\r\n      if(bCipherMode)\r\n        output_net_enc(iSample) = res_f.get_d();\r\n      if(bPlainMode)\r\n        output_net_plain(iSample) = res_f_plain.get_d();\r\n      \r\n      std::cout << (iSample + 1) << \"/\" << nTestSamples << \" samples are done\" << std::endl;\r\n      \r\n      if(bCipherMode)\r\n      {\r\n        std::cout << \"MSE(Enc): \" << mse(output_net_enc.rows(0, iSample), output_real) << std::endl;\r\n        std::cout << \"MAPE(Enc): \" << mape(output_net_enc.rows(0, iSample), output_real) << std::endl;\r\n      }\r\n\r\n      if(bPlainMode)\r\n      {\r\n        std::cout << \"MSE(Plain): \" << mse(output_net_plain.rows(0, iSample), output_real) << std::endl;\r\n        std::cout << \"MAPE(Plain): \" << mape(output_net_plain.rows(0, iSample), output_real) << std::endl;\r\n\r\n        double cur_error;\r\n        cur_error = fabs(output_net_approx(iSample) - output_net_plain(iSample))/fabs(output_net_approx(iSample));\r\n        if (cur_error > max_error)\r\n        {\r\n          max_error = cur_error;\r\n          max_error_ind = iSample;\r\n        }\r\n        if (cur_error < min_error)\r\n        {\r\n          min_error = cur_error;\r\n          min_error_ind = iSample;\r\n        }\r\n        std::cout << \"MAPE(Plain vs approx): \" << mape(output_net_approx.rows(0, iSample), output_net_plain.rows(0, iSample)) << std::endl;\r\n        std::cout << \"Min diff: \" << min_error << \" at Sample \" << min_error_ind << std::endl;\r\n        std::cout << \"Max diff: \" << max_error << \" at Sample \" << max_error_ind << std::endl;\r\n      }\r\n      //to consider only one sample. Delete after use\r\n\r\n\r\n\r\n    }\r\n    if(bWriteCoefs)\r\n      fout.close();\r\n\r\n  }\r\n\r\n  return 0;\r\n}\r\n", "meta": {"hexsha": "e921135190fc93276f6e08e16bc003f0f9dfcb41", "size": 116832, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "AWSF1/nneval_app/actual/gmdh.cpp", "max_stars_repo_name": "KULeuven-COSIC/HEAT", "max_stars_repo_head_hexsha": "60e7a4b33d7738094a518916bcd646dd3fa05b0e", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 37.0, "max_stars_repo_stars_event_min_datetime": "2019-01-21T13:08:13.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T18:42:01.000Z", "max_issues_repo_path": "AWSF1/nneval_app/actual/gmdh.cpp", "max_issues_repo_name": "KULeuven-COSIC/HEAT", "max_issues_repo_head_hexsha": "60e7a4b33d7738094a518916bcd646dd3fa05b0e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2020-03-30T09:08:09.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-26T12:57:14.000Z", "max_forks_repo_path": "AWSF1/nneval_app/actual/gmdh.cpp", "max_forks_repo_name": "KULeuven-COSIC/HEAT", "max_forks_repo_head_hexsha": "60e7a4b33d7738094a518916bcd646dd3fa05b0e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 20.0, "max_forks_repo_forks_event_min_datetime": "2018-05-04T16:06:33.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-30T18:41:45.000Z", "avg_line_length": 31.0640787025, "max_line_length": 296, "alphanum_fraction": 0.5531018899, "num_tokens": 32296, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.8006920020959543, "lm_q2_score": 0.411110869232168, "lm_q1q2_score": 0.3291731849689126}}
{"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 WNTCELLCYCLEODESYSTEM_HPP_\n#define WNTCELLCYCLEODESYSTEM_HPP_\n\n#include \"ChasteSerialization.hpp\"\n#include <boost/serialization/base_object.hpp>\n#include <boost/serialization/shared_ptr.hpp>\n\n#include <cmath>\n#include <iostream>\n\n#include \"AbstractOdeSystem.hpp\"\n#include \"AbstractCellMutationState.hpp\"\n\n/**\n * Represents the Mirams et al. system of ODEs, based on Swat et al. (2004)\n * [doi:10.1093/bioinformatics/bth110]\n * and a simple Wnt model (unpublished)\n *\n * The variables are\n *\n * 0. r = pRb\n * 1. e = E2F1\n * 2. i = CycD (inactive)\n * 3. j = CycD (active)\n * 4. p = pRb-p\n * 5. c = destruction complex (Active)\n * 6. b1 = Beta-Catenin (from 1st allele)\n * 7. b2 = Beta-Catenin (from 1st allele)\n * 8. WntLevel\n */\nclass WntCellCycleOdeSystem : public AbstractOdeSystem\n{\nprivate:\n\n    /**\n     * Parameters for the Swat et al. (2004) model\n     */\n\n    /** Dimensional parameter k_2. */\n    double mk2d;\n    /** Dimensional parameter k_3. */\n    double mk3d;\n    /** Dimensional parameter k_34. */\n    double mk34d;\n    /** Dimensional parameter k_2. */\n    double mk43d;\n    /** Dimensional parameter k_23. */\n    double mk23d;\n    /** Dimensional parameter a. */\n    double mad;\n    /** Dimensional parameter J_11. */\n    double mJ11d;\n    /** Dimensional parameter J_12. */\n    double mJ12d;\n    /** Dimensional parameter J_13. */\n    double mJ13d;\n    /** Dimensional parameter J_13. */\n    double mJ61d;\n    /** Dimensional parameter J_62. */\n    double mJ62d;\n    /** Dimensional parameter J_63. */\n    double mJ63d;\n    /** Dimensional parameter K_m1. */\n    double mKm1d;\n    /** Dimensional parameter k_p. */\n    double mkpd;\n    /** Dimensionless parameter phi_r. */\n    double mphi_r;\n    /** Dimensionless parameter phi_i. */\n    double mphi_i;\n    /** Dimensionless parameter phi_j. */\n    double mphi_j;\n    /** Dimensionless parameter phi_p. */\n    double mphi_p;\n    /** Dimensional parameter a_2. */\n    double ma2d;\n    /** Dimensional parameter a_3. */\n    double ma3d;\n    /** Dimensional parameter a_4. */\n    double ma4d;\n    /** Dimensional parameter a_5. */\n    double ma5d;\n    /** Dimensional parameter k_16. */\n    double mk16d;\n    /** Dimensional parameter k_61. */\n    double mk61d;\n    /** Dimensionless parameter phi_E2F1. */\n    double mPhiE2F1;\n\n    /** The mutation state of the cell - Wnt pathway behaviour (and hence cell cycle time) changes depending on this */\n    boost::shared_ptr<AbstractCellMutationState> mpMutationState;\n\n    /** The Wnt level (this affects the ODE system). */\n    double mWntLevel;\n\n    friend class boost::serialization::access;\n    /**\n     * Serialize 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<AbstractOdeSystem>(*this);\n    }\n\npublic:\n\n    /**\n     * Constructor.\n     *\n     * @param wntLevel is a non-dimensional Wnt value between 0 and 1. This sets up the Wnt pathway in its steady state.\n     * @param pMutationState optional mutation state (affects the ODE system)\n     * @param stateVariables optional initial conditions for state variables (only used in archiving)\n     */\n    WntCellCycleOdeSystem(double wntLevel=0.0,\n                          boost::shared_ptr<AbstractCellMutationState> pMutationState=boost::shared_ptr<AbstractCellMutationState>(),\n                          std::vector<double> stateVariables=std::vector<double>());\n\n    /**\n     * Destructor.\n     */\n    ~WntCellCycleOdeSystem();\n\n    /**\n     * Initialise parameter values.\n     */\n    void Init();\n\n    /**\n     * Set the mutation state of the cell.\n     *\n     * This should be called by the relevant cell-cycle model before any solving\n     * of the ODE system (as it is used to evaluate the Y derivatives).\n     *\n     * @param pMutationState the mutation state.\n     */\n    void SetMutationState(boost::shared_ptr<AbstractCellMutationState> pMutationState);\n\n    /**\n     * Called by the archive function on the Wnt cell-cycle model.\n     *\n     * @return #mpMutationState the mutation state of the cell.\n     */\n    const boost::shared_ptr<AbstractCellMutationState> GetMutationState() const;\n\n    /**\n     * Compute the RHS of the WntCellCycle system of ODEs.\n     *\n     * Returns a vector representing the RHS of the ODEs at each time step, y' = [y1' ... yn'].\n     * An ODE solver will call this function repeatedly to solve for y = [y1 ... yn].\n     *\n     * @param time used to evaluate the RHS.\n     * @param rY value of the solution vector used to evaluate the RHS.\n     * @param rDY filled in with the resulting derivatives (using Alarcons et al. (2004) system of equations).\n     */\n    void EvaluateYDerivatives(double time, const std::vector<double>& rY, std::vector<double>& rDY);\n\n    /**\n     * This also contains a calculation of dY[1], copied from EvaluateYDerivatives.\n     * Ensure they do not get out of sync!\n     *\n     * @param time at which to calculate whether the stopping event has occurred\n     * @param rY value of the solution vector used to evaluate the RHS\n     *\n     * @return whether we have reached the stopping event\n     */\n    bool CalculateStoppingEvent(double time, const std::vector<double>& rY);\n\n    /**\n     * When using CVODE this function is called instead of CalculateStoppingEvent.\n     * It allows the point at which rY[1] reaches 1 to be found to greater precision.\n     *\n     * @param time at which to calculate whether the stopping event has occurred\n     * @param rY value of the solution vector used to evaluate the RHS\n     *\n     * @return function value - giving CVODE an estimate of how close we are to the root.\n     */\n    double CalculateRootFunction(double time, const std::vector<double>& rY);\n\n    /**\n     * @return #mWntLevel.\n     */\n    double GetWntLevel() const;\n};\n\n// Declare identifier for the serializer\n#include \"SerializationExportWrapper.hpp\"\nCHASTE_CLASS_EXPORT(WntCellCycleOdeSystem)\n\nnamespace boost\n{\nnamespace serialization\n{\n/**\n * Serialize information required to construct a WntCellCycleOdeSystem.\n */\ntemplate<class Archive>\ninline void save_construct_data(\n    Archive & ar, const WntCellCycleOdeSystem * t, const unsigned int file_version)\n{\n    // Save data required to construct instance\n    const double wnt_level = t->GetWntLevel();\n    ar & wnt_level;\n\n    const boost::shared_ptr<AbstractCellMutationState> p_mutation_state = t->GetMutationState();\n    ar & p_mutation_state;\n\n    const std::vector<double> state_variables = t->rGetConstStateVariables();\n    ar & state_variables;\n}\n\n/**\n * De-serialize constructor parameters and initialise a WntCellCycleOdeSystem.\n */\ntemplate<class Archive>\ninline void load_construct_data(\n    Archive & ar, WntCellCycleOdeSystem * t, const unsigned int file_version)\n{\n    // Retrieve data from archive required to construct new instance\n    double wnt_level;\n    ar & wnt_level;\n\n    boost::shared_ptr<AbstractCellMutationState> p_mutation_state;\n    ar & p_mutation_state;\n\n    std::vector<double> state_variables;\n    ar & state_variables;\n\n    // Invoke inplace constructor to initialise instance\n    ::new(t)WntCellCycleOdeSystem(wnt_level, p_mutation_state, state_variables);\n}\n}\n} // namespace ...\n\n#endif /*WNTCELLCYCLEODESYSTEM_HPP_*/\n", "meta": {"hexsha": "28db6940c6f83833e25bfa82e261335c6a03f65e", "size": 9130, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "crypt/src/odes/WntCellCycleOdeSystem.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": "crypt/src/odes/WntCellCycleOdeSystem.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": "crypt/src/odes/WntCellCycleOdeSystem.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": 33.3211678832, "max_line_length": 133, "alphanum_fraction": 0.7009857612, "num_tokens": 2209, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6150878555160665, "lm_q2_score": 0.5350984286266116, "lm_q1q2_score": 0.3291325449539595}}
{"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\n#include \"graph_filtering.hh\"\n\n#include \"graph_selectors.hh\"\n#include \"graph_properties.hh\"\n\n#include <cmath>\n\nusing namespace std;\nusing namespace boost;\nusing namespace graph_tool;\n\n\nstruct do_get_radial\n{\n    template <class Graph, class PosProp, class LevelMap, class OrderMap,\n              class WeightMap>\n    void operator()(Graph& g, PosProp tpos, LevelMap level, OrderMap order,\n                    WeightMap weight, size_t root, bool weighted, double r,\n                    bool order_propagate) const\n    {\n        typedef typename graph_traits<Graph>::vertex_descriptor vertex_t;\n        typedef typename vprop_map_t<typename property_traits<WeightMap>::value_type>::type vcount_t;\n        typename vcount_t::unchecked_t count(get(vertex_index, g), num_vertices(g));\n\n        if (!weighted)\n        {\n            for (auto v : vertices_range(g))\n                count[v] = weight[v];\n        }\n        else\n        {\n            deque<vertex_t> q;\n            for (auto v : vertices_range(g))\n            {\n                if (out_degree(v, g) == 0)\n                {\n                    q.push_back(v);\n                    count[v] = weight[v];\n                }\n            }\n\n            typedef vprop_map_t<uint8_t>::type vmark_t;\n            vmark_t::unchecked_t mark(get(vertex_index, g), num_vertices(g));\n\n            while (!q.empty())\n            {\n                vertex_t v = q.front();\n                q.pop_front();\n                for (auto e : in_edges_range(v, g))\n                {\n                    vertex_t w = source(e, g);\n                    count[w] += count[v];\n                    if (!mark[w])\n                    {\n                        q.push_back(w);\n                        mark[w] = true;\n                    }\n                }\n            }\n        }\n\n        vprop_map_t<double>::type::unchecked_t vorder(get(vertex_index, g));\n\n        if (order_propagate)\n        {\n            vorder.resize(num_vertices(g));\n            std::vector<size_t> vs(vertices(g).first, vertices(g).second);\n            std::sort(vs.begin(), vs.end(),\n                      [&] (vertex_t u, vertex_t v) { return order[u] < order[v]; });\n\n            for (size_t i = 0; i < vs.size(); ++i)\n                vorder[vs[i]] = i;\n\n            std::sort(vs.begin(), vs.end(),\n                      [&] (vertex_t u, vertex_t v) { return level[u] > level[v]; });\n\n            for (auto v : vs)\n            {\n                if (out_degree(v,g) == 0)\n                    continue;\n                vorder[v] = 0;\n                for (auto e : out_edges_range(v, g))\n                    vorder[v] += vorder[target(e,g)];\n                vorder[v] /= out_degree(v,g);\n            }\n        }\n\n        vector<vector<vertex_t>> layers(1);\n        layers[0].push_back(root);\n\n        bool last = false;\n        while (!last)\n        {\n            layers.resize(layers.size() + 1);\n            vector<vertex_t>& new_layer = layers[layers.size() - 1];\n            vector<vertex_t>& last_layer = layers[layers.size() - 2];\n\n            last = true;\n            for (size_t i = 0; i < last_layer.size(); ++i)\n            {\n                vertex_t v = last_layer[i];\n                for (auto e : out_edges_range(v, g))\n                {\n                    vertex_t w = target(e, g);\n                    new_layer.push_back(w);\n\n                    if (int(layers.size()) - 1 == int(level[w]))\n                        last = false;\n                }\n\n                if (order_propagate)\n                {\n                    std::sort(new_layer.end() - out_degree(v, g),\n                              new_layer.end(),\n                              [&] (vertex_t u, vertex_t v)\n                              { return vorder[u] < vorder[v]; });\n                }\n                else\n                {\n                    std::sort(new_layer.end() - out_degree(v, g),\n                              new_layer.end(),\n                              [&] (vertex_t u, vertex_t v)\n                              { return order[u] < order[v]; });\n                }\n\n                if (out_degree(v, g) == 0)\n                    new_layer.push_back(v);\n            }\n\n            if (last)\n                layers.pop_back();\n        }\n\n\n        typedef vprop_map_t<double>::type vangle_t;\n        vangle_t::unchecked_t angle(get(vertex_index, g), num_vertices(g));\n\n        double d_sum = 0;\n        vector<vertex_t>& outer_layer = layers.back();\n        for (size_t i = 0; i < outer_layer.size(); ++i)\n            d_sum += count[outer_layer[i]];\n        angle[outer_layer[0]] = (2 * M_PI * count[outer_layer[0]]) / d_sum;\n        for (size_t i = 1; i < outer_layer.size(); ++i)\n            angle[outer_layer[i]] = angle[outer_layer[i-1]] + (2 * M_PI * count[outer_layer[i]]) / d_sum;\n        for (size_t i = 0; i < outer_layer.size(); ++i)\n            angle[outer_layer[i]] -= (2 * M_PI * count[outer_layer[i]]) / (2 * d_sum);\n\n        for (size_t i = 0; i < layers.size(); ++i)\n        {\n            vector<vertex_t>& vs = layers[layers.size() - 1 - i];\n            for (size_t j = 0; j < vs.size(); ++j)\n            {\n                vertex_t v = vs[j];\n                d_sum = 0;\n                for (auto e : out_edges_range(v, g))\n                {\n                    vertex_t w = target(e, g);\n                    d_sum += count[w];\n                }\n                for (auto e : out_edges_range(v, g))\n                {\n                    vertex_t w = target(e, g);\n                    angle[v] += angle[w] * count[w] / d_sum;\n                }\n                double d = level[v] * r;\n                tpos[v].resize(2);\n                tpos[v][0] = d * cos(angle[v]);\n                tpos[v][1] = d * sin(angle[v]);\n            }\n        }\n    }\n};\n\nvoid get_radial(GraphInterface& gi, boost::any otpos, boost::any olevels,\n                boost::any oorder, boost::any oweight, size_t root,\n                bool weighted, double r, bool order_propagate)\n{\n    typedef vprop_map_t<int32_t>::type vmap_t;\n\n    vmap_t levels = boost::any_cast<vmap_t>(olevels);\n\n    typedef vprop_map_t<double>::type wmap_t;\n\n    wmap_t weight = boost::any_cast<wmap_t>(oweight);\n\n    run_action<graph_tool::detail::always_directed>()\n        (gi, std::bind(do_get_radial(), std::placeholders::_1, std::placeholders::_2,\n                       levels, std::placeholders::_3, weight, root, weighted, r,\n                       order_propagate),\n         vertex_scalar_vector_properties(),\n         vertex_properties())(otpos, oorder);\n}\n\n#include <boost/python.hpp>\n\nvoid export_radial()\n{\n    python::def(\"get_radial\", &get_radial);\n}\n", "meta": {"hexsha": "dc82fa40b8467b7f195ecb8212ec9114b748da9f", "size": 7440, "ext": "cc", "lang": "C++", "max_stars_repo_path": "graph-tool-2.27/src/graph/layout/graph_radial.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/layout/graph_radial.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/layout/graph_radial.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.9726027397, "max_line_length": 105, "alphanum_fraction": 0.4915322581, "num_tokens": 1708, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5774953651858118, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.32908726503052177}}
{"text": "/*\n Copyright (C) 2017 Quaternion Risk Management Ltd\n All rights reserved.\n\n This file is part of ORE, a free-software/open-source library\n for transparent pricing and risk analysis - http://opensourcerisk.org\n\n ORE is free software: you can redistribute it and/or modify it\n under the terms of the Modified BSD License.  You should have received a\n copy of the license along with this program.\n The license is also available online at <http://opensourcerisk.org>\n\n This program is distributed on the basis that it will form a useful\n contribution to risk analytics and model standardisation, but WITHOUT\n ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n FITNESS FOR A PARTICULAR PURPOSE. See the license for more details.\n*/\n#include <boost/make_shared.hpp>\n#include <ql/math/interpolations/bilinearinterpolation.hpp>\n#include <ql/math/interpolations/linearinterpolation.hpp>\n#include <ql/quotes/simplequote.hpp>\n#include <ql/termstructures/yield/forwardcurve.hpp>\n#include <ql/utilities/dataformatters.hpp>\n#include <qle/termstructures/blackvariancesurfacemoneyness.hpp>\n\nusing namespace std;\n\nnamespace QuantExt {\n\nBlackVarianceSurfaceMoneyness::BlackVarianceSurfaceMoneyness(\n    const Calendar& cal, const Handle<Quote>& spot, const std::vector<Time>& times, const std::vector<Real>& moneyness,\n    const std::vector<std::vector<Handle<Quote> > >& blackVolMatrix, const DayCounter& dayCounter, bool stickyStrike,\n    bool flatExtrapMoneyness)\n    : BlackVarianceTermStructure(0, cal, Following, dayCounter), stickyStrike_(stickyStrike), spot_(spot),\n      times_(times), moneyness_(moneyness), flatExtrapMoneyness_(flatExtrapMoneyness), quotes_(blackVolMatrix) {\n    init();\n}\n\nBlackVarianceSurfaceMoneyness::BlackVarianceSurfaceMoneyness(\n    const Date& referenceDate, const Calendar& cal, const Handle<Quote>& spot, const std::vector<Time>& times,\n    const std::vector<Real>& moneyness, const std::vector<std::vector<Handle<Quote> > >& blackVolMatrix,\n    const DayCounter& dayCounter, bool stickyStrike, bool flatExtrapMoneyness)\n    : BlackVarianceTermStructure(referenceDate, cal, Following, dayCounter), stickyStrike_(stickyStrike), spot_(spot),\n      times_(times), moneyness_(moneyness), flatExtrapMoneyness_(flatExtrapMoneyness), quotes_(blackVolMatrix) {\n    init();\n}\n\nvoid BlackVarianceSurfaceMoneyness::update() {\n    TermStructure::update();\n    LazyObject::update();\n}\n\nvoid BlackVarianceSurfaceMoneyness::performCalculations() const {\n    for (Size j = 1; j < variances_.columns(); j++) {\n        for (Size i = 0; i < variances_.rows(); i++) {\n            Real vol = quotes_[i][j - 1]->value();\n            variances_[i][j] = times_[j] * vol * vol;\n        }\n    }\n    varianceSurface_.update();\n}\n\nvoid BlackVarianceSurfaceMoneyness::init() {\n\n    QL_REQUIRE(times_.size() == quotes_.front().size(), \"mismatch between times vector and vol matrix colums\");\n    QL_REQUIRE(moneyness_.size() == quotes_.size(), \"mismatch between moneyness vector and vol matrix rows\");\n\n    QL_REQUIRE(times_[0] > 0, \"The first time must be greater than 0.0.\");\n\n    if (stickyStrike_) {\n        // we don't want to know if the spot has changed - we take a copy here\n        spot_ = Handle<Quote>(boost::make_shared<SimpleQuote>(spot_->value()));\n    } else {\n        registerWith(spot_);\n    }\n\n    // Insert time 0.0 in times_ and initialise variances_ with 0.0.\n    times_.insert(times_.begin(), 0.0);\n    variances_ = Matrix(moneyness_.size(), times_.size(), 0.0);\n\n    // Check times_ and register with quotes\n    for (Size j = 1; j < times_.size(); j++) {\n\n        QL_REQUIRE(times_[j] > times_[j - 1], \"Times must be sorted and unique but found that the \"\n                                                  << io::ordinal(j) << \" time, \" << times_[j]\n                                                  << \", is not greater than the \" << io::ordinal(j - 1) << \" time, \"\n                                                  << times_[j - 1] << \".\");\n\n        for (Size i = 0; i < moneyness_.size(); i++) {\n            registerWith(quotes_[i][j - 1]);\n        }\n    }\n\n    varianceSurface_ =\n        Bilinear().interpolate(times_.begin(), times_.end(), moneyness_.begin(), moneyness_.end(), variances_);\n\n    notifyObservers();\n}\n\nReal BlackVarianceSurfaceMoneyness::blackVarianceImpl(Time t, Real strike) const {\n\n    calculate();\n\n    if (t == 0.0)\n        return 0.0;\n\n    return blackVarianceMoneyness(t, moneyness(t, strike));\n}\n\nReal BlackVarianceSurfaceMoneyness::blackVarianceMoneyness(Time t, Real m) const {\n    if (t <= times_.back())\n        return varianceSurface_(t, m, true);\n    else\n        return varianceSurface_(times_.back(), m, true) * t / times_.back();\n}\n\nBlackVarianceSurfaceMoneynessSpot::BlackVarianceSurfaceMoneynessSpot(\n    const Calendar& cal, const Handle<Quote>& spot, const std::vector<Time>& times, const std::vector<Real>& moneyness,\n    const std::vector<std::vector<Handle<Quote> > >& blackVolMatrix, const DayCounter& dayCounter, bool stickyStrike,\n    bool flatExtrapMoneyness)\n    : BlackVarianceSurfaceMoneyness(cal, spot, times, moneyness, blackVolMatrix, dayCounter, stickyStrike,\n                                    flatExtrapMoneyness) {}\n\nBlackVarianceSurfaceMoneynessSpot::BlackVarianceSurfaceMoneynessSpot(\n    const Date& referenceDate, const Calendar& cal, const Handle<Quote>& spot, const std::vector<Time>& times,\n    const std::vector<Real>& moneyness, const std::vector<std::vector<Handle<Quote> > >& blackVolMatrix,\n    const DayCounter& dayCounter, bool stickyStrike, bool flatExtrapMoneyness)\n    : BlackVarianceSurfaceMoneyness(referenceDate, cal, spot, times, moneyness, blackVolMatrix, dayCounter,\n                                    stickyStrike, flatExtrapMoneyness) {}\n\nReal BlackVarianceSurfaceMoneynessSpot::moneyness(Time, Real strike) const {\n    if (strike == Null<Real>() || strike == 0) {\n        return 1.0;\n    } else {\n        Real moneyness = strike / spot_->value();\n        if (flatExtrapMoneyness_) {\n            if (moneyness < moneyness_.front()) {\n                moneyness = moneyness_.front();\n            } else if (moneyness > moneyness_.back()) {\n                moneyness = moneyness_.back();\n            }\n        }\n        return moneyness;\n    }\n}\n\nBlackVarianceSurfaceMoneynessForward::BlackVarianceSurfaceMoneynessForward(\n    const Calendar& cal, const Handle<Quote>& spot, const std::vector<Time>& times, const std::vector<Real>& moneyness,\n    const std::vector<std::vector<Handle<Quote> > >& blackVolMatrix, const DayCounter& dayCounter,\n    const Handle<YieldTermStructure>& forTS, const Handle<YieldTermStructure>& domTS, bool stickyStrike,\n    bool flatExtrapMoneyness)\n    : BlackVarianceSurfaceMoneyness(cal, spot, times, moneyness, blackVolMatrix, dayCounter, stickyStrike,\n                                    flatExtrapMoneyness),\n      forTS_(forTS), domTS_(domTS) {\n    init();\n}\n\nBlackVarianceSurfaceMoneynessForward::BlackVarianceSurfaceMoneynessForward(\n    const Date& referenceDate, const Calendar& cal, const Handle<Quote>& spot, const std::vector<Time>& times,\n    const std::vector<Real>& moneyness, const std::vector<std::vector<Handle<Quote> > >& blackVolMatrix,\n    const DayCounter& dayCounter, const Handle<YieldTermStructure>& forTS, const Handle<YieldTermStructure>& domTS,\n    bool stickyStrike, bool flatExtrapMoneyness)\n    : BlackVarianceSurfaceMoneyness(referenceDate, cal, spot, times, moneyness, blackVolMatrix, dayCounter,\n                                    stickyStrike, flatExtrapMoneyness),\n      forTS_(forTS), domTS_(domTS) {\n    init();\n}\n\nvoid BlackVarianceSurfaceMoneynessForward::init() {\n\n    if (!stickyStrike_) {\n        QL_REQUIRE(!forTS_.empty(), \"foreign discount curve required for atmf surface\");\n        QL_REQUIRE(!domTS_.empty(), \"domestic discount curve required for atmf surface\");\n        registerWith(forTS_);\n        registerWith(domTS_);\n    } else {\n        for (Size i = 0; i < times_.size(); i++) {\n            Time t = times_[i];\n            Real fwd = spot_->value() * forTS_->discount(t) / domTS_->discount(t);\n            forwards_.push_back(fwd);\n        }\n        forwardCurve_ = Linear().interpolate(times_.begin(), times_.end(), forwards_.begin());\n    }\n}\n\nReal BlackVarianceSurfaceMoneynessForward::moneyness(Time t, Real strike) const {\n    Real fwd;\n    Real reqMoneyness; // for flat extrapolation\n    if (strike == Null<Real>() || strike == 0)\n        return 1.0;\n    else {\n        if (stickyStrike_)\n            fwd = forwardCurve_(t, true);\n        else\n            fwd = spot_->value() * forTS_->discount(t) / domTS_->discount(t);\n        reqMoneyness = strike / fwd;\n        if (flatExtrapMoneyness_) {\n            if ((strike / fwd) < moneyness_.front()) {\n                reqMoneyness = moneyness_.front();\n            } else if ((strike / fwd) > moneyness_.back()) {\n                reqMoneyness = moneyness_.back();\n            }\n        }\n        return reqMoneyness;\n    }\n}\n\n} // namespace QuantExt\n", "meta": {"hexsha": "4254e7ae9b450b7f75c3d8d37e02237cefe19ddf", "size": 9009, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "QuantExt/qle/termstructures/blackvariancesurfacemoneyness.cpp", "max_stars_repo_name": "nvolfango/Engine", "max_stars_repo_head_hexsha": "a5ee0fc09d5a50ab36e50d55893b6e484d6e7004", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-03-30T17:24:17.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-30T17:24:17.000Z", "max_issues_repo_path": "QuantExt/qle/termstructures/blackvariancesurfacemoneyness.cpp", "max_issues_repo_name": "zhangjiayin/Engine", "max_issues_repo_head_hexsha": "a5ee0fc09d5a50ab36e50d55893b6e484d6e7004", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "QuantExt/qle/termstructures/blackvariancesurfacemoneyness.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": 43.1052631579, "max_line_length": 119, "alphanum_fraction": 0.668997669, "num_tokens": 2381, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6334102636778401, "lm_q2_score": 0.519521321952093, "lm_q1q2_score": 0.3290701375239353}}
{"text": "///////////////////////////////////////////////////////////////////////////////\n//  Copyright 2022 Matt Borland. 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_DETAIL_FUNCTIONS_TRUNC_HPP\n#define BOOST_MP_DETAIL_FUNCTIONS_TRUNC_HPP\n\n#include <cmath>\n#include <limits>\n#include <stdexcept>\n#include <boost/multiprecision/detail/standalone_config.hpp>\n#include <boost/multiprecision/detail/no_exceptions_support.hpp>\n\n#ifdef BOOST_MP_MATH_AVAILABLE\n#include <boost/math/special_functions/trunc.hpp>\n#endif\n\nnamespace boost { namespace multiprecision { namespace detail {\n\nnamespace impl {\n\ntemplate <typename T>\ninline T trunc BOOST_PREVENT_MACRO_SUBSTITUTION (const T arg)\n{\n    using std::floor;\n    using std::ceil;\n\n    return (arg > 0) ? floor(arg) : ceil(arg);\n}\n\n} // namespace impl\n\n#ifdef BOOST_MP_MATH_AVAILABLE\n\ntemplate <typename T>\ninline long long lltrunc BOOST_PREVENT_MACRO_SUBSTITUTION (const T arg)\n{\n    return boost::math::lltrunc(arg);\n}\n\ntemplate <typename T>\ninline int itrunc BOOST_PREVENT_MACRO_SUBSTITUTION (const T arg)\n{\n    return boost::math::itrunc(arg);\n}\n\n#else\n\ntemplate <typename T>\ninline long long lltrunc BOOST_PREVENT_MACRO_SUBSTITUTION (const T arg)\n{\n    if (arg > LLONG_MAX)\n    {\n        BOOST_MP_THROW_EXCEPTION(std::domain_error(\"arg cannot be converted into a long long\"));\n    }\n\n    return static_cast<long long>(boost::multiprecision::detail::impl::trunc(arg));\n}\n\ntemplate <typename T>\ninline int itrunc BOOST_PREVENT_MACRO_SUBSTITUTION (const T arg)\n{\n    if (arg > INT_MAX)\n    {\n        BOOST_MP_THROW_EXCEPTION(std::domain_error(\"arg cannot be converted into an int\"));\n    }\n\n    return static_cast<int>(boost::multiprecision::detail::impl::trunc(arg));\n}\n\n#endif\n\n}}} // Namespaces\n\n#endif // BOOST_MP_DETAIL_FUNCTIONS_TRUNC_HPP\n", "meta": {"hexsha": "3323f95456417def83dabe9e007776df6815babc", "size": 1908, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/multiprecision/detail/functions/trunc.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/detail/functions/trunc.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/detail/functions/trunc.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": 24.7792207792, "max_line_length": 96, "alphanum_fraction": 0.7180293501, "num_tokens": 437, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6334102498375401, "lm_q2_score": 0.519521321952093, "lm_q1q2_score": 0.3290701303336043}}
{"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#include <boost/python/def.hpp>\n\n#include \"pxr/pxr.h\"\n#include \"pxr/base/tf/pyUtils.h\"\n#include \"pxr/base/tf/pyContainerConversions.h\"\n\n#include \"pxr/base/gf/math.h\"\n\n#include \"pxr/base/gf/vec2i.h\"\n#include \"pxr/base/gf/vec3i.h\"\n#include \"pxr/base/gf/vec2f.h\"\n#include \"pxr/base/gf/vec3f.h\"\n#include \"pxr/base/gf/vec4f.h\"\n#include \"pxr/base/gf/vec2d.h\"\n#include \"pxr/base/gf/vec3d.h\"\n#include \"pxr/base/gf/vec4d.h\"\n\nusing namespace boost::python;\nusing std::vector;\n\nPXR_NAMESPACE_USING_DIRECTIVE\n\nvoid wrapMath()\n{    \n\n    def(\"IsClose\", (bool (*)(double, double, double))GfIsClose);\n    def(\"RadiansToDegrees\", GfRadiansToDegrees);\n    def(\"DegreesToRadians\", GfDegreesToRadians);\n\n    def(\"Sqr\", GfSqr<double>);\n    def(\"Sqr\", GfSqr<int>);\n\n    def(\"Sqr\", GfSqr<GfVec2i>);\n    def(\"Sqr\", GfSqr<GfVec3i>);\n    def(\"Sqr\", GfSqr<GfVec2f>);\n    def(\"Sqr\", GfSqr<GfVec3f>);\n    def(\"Sqr\", GfSqr<GfVec4f>);\n    def(\"Sqr\", GfSqr<GfVec2d>);\n    def(\"Sqr\", GfSqr<GfVec3d>);\n    def(\"Sqr\", GfSqr<GfVec4d>);\n\n    def(\"Sgn\", GfSgn<double>);\n    def(\"Sgn\", GfSgn<int>);\n    \n    def(\"Sqrt\", (double (*)(double))GfSqrt);\n    def(\"Sqrtf\", (float (*)(float))GfSqrt, \n        \"Sqrtf(f) -> float\\n\\n\"\n        \"f : float\\n\\n\"\n        \"Use instead of Sqrt() to return the square root of f as a float instead of a double.\");\n\n    def(\"Exp\", (double (*)(double))GfExp);\n    def(\"Expf\", (float (*)(float))GfExp, \n        \"Expf(f) -> float\\n\\n\"\n        \"f : float\\n\\n\"\n        \"Use instead of Exp() to return the exponent of f as a float instead of a double.\");\n\n    def(\"Log\", (double (*)(double))GfLog);\n    def(\"Logf\", (float (*)(float))GfLog, \n        \"Logf(f) -> float\\n\\n\"\n        \"f : float\\n\\n\"\n        \"Use instead of Log() to return the logarithm of f as a float instead of a double.\");\n\n    def(\"Floor\", (double (*)(double))GfFloor);\n    def(\"Floorf\", (float (*)(float))GfFloor, \n        \"Floorf(f) -> float\\n\\n\"\n        \"f : float\\n\\n\"\n        \"Use instead of Floor() to return the floor of f as a float instead of a double.\");\n\n    def(\"Ceil\", (double (*)(double))GfCeil);\n    def(\"Ceilf\", (float (*)(float))GfCeil, \n        \"Ceilf(f) -> float\\n\\n\"\n        \"f : float\\n\\n\"\n        \"Use instead of Ceil() to return the ceiling of f as a float instead of a double.\");\n\n    def(\"Abs\", (double (*)(double))GfAbs);\n    def(\"Absf\", (float (*)(float))GfAbs, \n        \"Absf(f) -> float\\n\\n\"\n        \"f : float\\n\\n\"\n        \"Use instead of Abs() to return the absolute value of f as a float instead of a double.\");\n\n    def(\"Round\", (double (*)(double))GfRound);\n    def(\"Roundf\", (float (*)(float))GfRound, \n        \"Roundf(f) -> float\\n\\n\"\n        \"f : float\\n\\n\"\n        \"Use instead of Round() to return the rounded value of f as a float instead of a double.\");\n\n    def(\"Pow\", (double (*)(double, double))GfPow);\n    def(\"Powf\", (float (*)(float, float))GfPow, \n        \"Powf(f) -> float\\n\\n\"\n        \"f : float\\n\\n\"\n        \"Use instead of Pow() to return the power of f as a float instead of a double.\");\n\n    def(\"Clamp\", (double (*)(double, double, double))GfClamp);\n    def(\"Clampf\", (float (*)(float, float, float))GfClamp, \n        \"Clampf(f) -> float\\n\\n\"\n        \"f : float\\n\\n\"\n        \"Use instead of Clamp() to return the clamped value of f as a float instead of a double.\");\n            \n    def(\"Mod\", (double (*)(double, double))GfMod);\n    def(\"Modf\", (float (*)(float, float))GfMod, \n        \"Modf(f) -> float\\n\\n\"\n        \"f : float\\n\\n\"\n        \"Use instead of Mod() to return the modulus of f as a float instead of a double.\");\n\n    def(\"Lerp\", GfLerp<double>);\n    def(\"Lerpf\", GfLerp<float>, \n         \"Lerpf(f) -> float\\n\\n\"\n        \"f : float\\n\\n\"\n        \"Use instead of Lerp() to return the linear interpolation of f as a float instead of a double.\");\n\n    def(\"Lerp\", GfLerp<GfVec2i>);\n    def(\"Lerp\", GfLerp<GfVec3i>);\n    def(\"Lerp\", GfLerp<GfVec2f>);\n    def(\"Lerp\", GfLerp<GfVec3f>);\n    def(\"Lerp\", GfLerp<GfVec4f>);\n    def(\"Lerp\", GfLerp<GfVec2d>);\n    def(\"Lerp\", GfLerp<GfVec3d>);\n    def(\"Lerp\", GfLerp<GfVec4d>);\n\n    def(\"Min\", (double (*)(double, double)) GfMin<double>);\n    def(\"Min\", (double (*)(double, double, double)) GfMin<double>);\n    def(\"Min\", (double (*)(double, double, double, double)) GfMin<double>);\n    def(\"Min\", (double (*)(double, double, double, double, double))\n        GfMin<double>);\n    def(\"Min\", (int (*)(int, int)) GfMin<int>);\n    def(\"Min\", (int (*)(int, int, int)) GfMin<int>);\n    def(\"Min\", (int (*)(int, int, int, int)) GfMin<int>);\n    def(\"Min\", (int (*)(int, int, int, int, int)) GfMin<int>);\n\n    def(\"Max\", (double (*)(double, double)) GfMax<double>);\n    def(\"Max\", (double (*)(double, double, double)) GfMax<double>);\n    def(\"Max\", (double (*)(double, double, double, double)) GfMax<double>);\n    def(\"Max\", (double (*)(double, double, double, double, double))\n        GfMax<double>);\n    def(\"Max\", (int (*)(int, int)) GfMax<int>);\n    def(\"Max\", (int (*)(int, int, int)) GfMax<int>);\n    def(\"Max\", (int (*)(int, int, int, int)) GfMax<int>);\n    def(\"Max\", (int (*)(int, int, int, int, int)) GfMax<int>);\n\n    def(\"Dot\", (double (*)(double, double)) GfDot);\n\n    TfPyContainerConversions::from_python_sequence< std::vector<int>, TfPyContainerConversions::variable_capacity_policy>();\n\n    TfPyContainerConversions::from_python_sequence< std::vector<unsigned int>, TfPyContainerConversions::variable_capacity_policy>();\n\n    TfPyContainerConversions::from_python_sequence< std::vector<bool>, TfPyContainerConversions::variable_capacity_policy>();\n\n    TfPyContainerConversions::from_python_sequence< std::vector<double>, TfPyContainerConversions::variable_capacity_policy>();\n\n    TfPyContainerConversions::from_python_sequence< std::vector< std::vector<int> >, TfPyContainerConversions::variable_capacity_policy>();\n\n    TfPyContainerConversions::from_python_sequence< std::vector< std::vector<double> >, TfPyContainerConversions::variable_capacity_policy>();\n \n}\n", "meta": {"hexsha": "d2a528840bcf5d49aa39c3d71a46f70ae6423f73", "size": 7019, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "pxr/base/lib/gf/wrapMath.cpp", "max_stars_repo_name": "YuqiaoZhang/USD", "max_stars_repo_head_hexsha": "bf3a21e6e049486441440ebf8c0387db2538d096", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 88.0, "max_stars_repo_stars_event_min_datetime": "2018-07-13T01:22:00.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-16T22:15:27.000Z", "max_issues_repo_path": "pxr/base/lib/gf/wrapMath.cpp", "max_issues_repo_name": "YuqiaoZhang/USD", "max_issues_repo_head_hexsha": "bf3a21e6e049486441440ebf8c0387db2538d096", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-07-07T22:39:42.000Z", "max_issues_repo_issues_event_max_datetime": "2020-07-07T22:39:42.000Z", "max_forks_repo_path": "pxr/base/lib/gf/wrapMath.cpp", "max_forks_repo_name": "YuqiaoZhang/USD", "max_forks_repo_head_hexsha": "bf3a21e6e049486441440ebf8c0387db2538d096", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 26.0, "max_forks_repo_forks_event_min_datetime": "2018-06-06T03:39:22.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-28T23:02:42.000Z", "avg_line_length": 39.4325842697, "max_line_length": 142, "alphanum_fraction": 0.6295768628, "num_tokens": 2092, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6334102498375401, "lm_q2_score": 0.5195213219520929, "lm_q1q2_score": 0.32907013033360427}}
{"text": "/***************************************************************************\n *   Copyright (C) by GFZ Potsdam                                          *\n *                                                                         *\n *   You can redistribute and/or modify this program under the             *\n *   terms of the SeisComP Public License.                                 *\n *                                                                         *\n *   This program is distributed in the hope that it will be useful,       *\n *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *\n *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *\n *   SeisComP Public License for more details.                             *\n ***************************************************************************/\n\n\n#define SEISCOMP_COMPONENT MLh\n\n#include <seiscomp3/logging/log.h>\n#include <seiscomp3/processing/amplitudes/MLh.h>\n\n#include <boost/bind.hpp>\n#include <cstdio>\n\n\nnamespace Seiscomp {\nnamespace Processing {\n\nnamespace {\n\nAmplitudeProcessor::AmplitudeValue average(\n\tconst AmplitudeProcessor::AmplitudeValue &v0,\n\tconst AmplitudeProcessor::AmplitudeValue &v1)\n{\n\tAmplitudeProcessor::AmplitudeValue v;\n\t// Average both values\n\tv.value = (v0.value + v1.value) * 0.5;\n\n\t// Compute lower and upper uncertainty\n\tdouble v0l = v0.value;\n\tdouble v0u = v0.value;\n\tdouble v1l = v1.value;\n\tdouble v1u = v1.value;\n\n\tif ( v0.lowerUncertainty ) v0l -= *v0.lowerUncertainty;\n\tif ( v0.upperUncertainty ) v0u += *v0.upperUncertainty;\n\tif ( v1.lowerUncertainty ) v1l -= *v1.lowerUncertainty;\n\tif ( v1.upperUncertainty ) v1u += *v1.upperUncertainty;\n\n\tdouble l = 0, u = 0;\n\n\tl = std::max(l, v.value - v0l);\n\tl = std::max(l, v.value - v0u);\n\tl = std::max(l, v.value - v1l);\n\tl = std::max(l, v.value - v1u);\n\n\tu = std::max(l, v0l - v.value);\n\tu = std::max(l, v0u - v.value);\n\tu = std::max(l, v1l - v.value);\n\tu = std::max(l, v1u - v.value);\n\n\tv.lowerUncertainty = l;\n\tv.upperUncertainty = u;\n\n\treturn v;\n}\n\n\nAmplitudeProcessor::AmplitudeTime average(\n\tconst AmplitudeProcessor::AmplitudeTime &t0,\n\tconst AmplitudeProcessor::AmplitudeTime &t1)\n{\n\tAmplitudeProcessor::AmplitudeTime t;\n\tt.reference = Core::Time((double(t0.reference) + double(t1.reference)) * 0.5);\n\n\t// Compute lower and upper uncertainty\n\tCore::Time t0b = t0.reference + Core::TimeSpan(t0.begin);\n\tCore::Time t0e = t0.reference + Core::TimeSpan(t0.end);\n\tCore::Time t1b = t1.reference + Core::TimeSpan(t1.begin);\n\tCore::Time t1e = t1.reference + Core::TimeSpan(t1.end);\n\n\tCore::Time minTime = t.reference;\n\tCore::Time maxTime = t.reference;\n\n\tminTime = std::min(minTime, t0b);\n\tminTime = std::min(minTime, t0e);\n\tminTime = std::min(minTime, t1b);\n\tminTime = std::min(minTime, t1e);\n\n\tmaxTime = std::max(maxTime, t0b);\n\tmaxTime = std::max(maxTime, t0e);\n\tmaxTime = std::max(maxTime, t1b);\n\tmaxTime = std::max(maxTime, t1e);\n\n\tt.begin = (double)(minTime - t.reference);\n\tt.end = (double)(maxTime - t.reference);\n\n\treturn t;\n}\n\n\nAmplitudeProcessor::AmplitudeValue gmean(\n\tconst AmplitudeProcessor::AmplitudeValue &v0,\n\tconst AmplitudeProcessor::AmplitudeValue &v1)\n{\n\tAmplitudeProcessor::AmplitudeValue v;\n\t// Average both values\n\tv.value = sqrt(v0.value * v1.value);\n\n\t// Compute lower and upper uncertainty\n\tdouble v0l = v0.value;\n\tdouble v0u = v0.value;\n\tdouble v1l = v1.value;\n\tdouble v1u = v1.value;\n\n\tif ( v0.lowerUncertainty ) v0l -= *v0.lowerUncertainty;\n\tif ( v0.upperUncertainty ) v0u += *v0.upperUncertainty;\n\tif ( v1.lowerUncertainty ) v1l -= *v1.lowerUncertainty;\n\tif ( v1.upperUncertainty ) v1u += *v1.upperUncertainty;\n\n\tdouble l = 0, u = 0;\n\n\tl = std::max(l, v.value - v0l);\n\tl = std::max(l, v.value - v0u);\n\tl = std::max(l, v.value - v1l);\n\tl = std::max(l, v.value - v1u);\n\n\tu = std::max(l, v0l - v.value);\n\tu = std::max(l, v0u - v.value);\n\tu = std::max(l, v1l - v.value);\n\tu = std::max(l, v1u - v.value);\n\n\tv.lowerUncertainty = l;\n\tv.upperUncertainty = u;\n\n\treturn v;\n}\n\n\n}\n\n\nIMPLEMENT_SC_CLASS_DERIVED(AmplitudeProcessor_ML2h, AbstractAmplitudeProcessor_ML, \"AmplitudeProcessor_ML\");\nREGISTER_AMPLITUDEPROCESSOR(AmplitudeProcessor_ML2h, \"ML\");\n\n\nAmplitudeProcessor_MLh::AmplitudeProcessor_MLh()\n: AbstractAmplitudeProcessor_ML(\"ML\") {}\n\n\nAmplitudeProcessor_ML2h::AmplitudeProcessor_ML2h()\n: Processing::AmplitudeProcessor(\"ML\") {\n\tsetSignalEnd(150.);\n\tsetMinSNR(0);\n\t// Maximum distance is 8 degrees\n\tsetMaxDist(8);\n\t// Maximum depth is 80 km\n\tsetMaxDepth(80);\n\n\tsetUsedComponent(Horizontal);\n\n\t_combiner = TakeAverage;\n\n\t_ampN.setUsedComponent(FirstHorizontal);\n\t_ampE.setUsedComponent(SecondHorizontal);\n\n\t_ampE.setPublishFunction(boost::bind(&AmplitudeProcessor_ML2h::newAmplitude, this, _1, _2));\n\t_ampN.setPublishFunction(boost::bind(&AmplitudeProcessor_ML2h::newAmplitude, this, _1, _2));\n\n\t// Propagate configuration to single processors\n\t_ampN.setConfig(config());\n\t_ampE.setConfig(config());\n}\n\n\nAmplitudeProcessor_ML2h::AmplitudeProcessor_ML2h(const Core::Time &trigger)\n: Processing::AmplitudeProcessor(trigger, \"ML\") {\n\tsetSignalEnd(150.);\n\tsetMinSNR(0);\n\t// Maximum distance is 8 degrees\n\tsetMaxDist(8);\n\t// Maximum depth is 80 km\n\tsetMaxDepth(80);\n\n\tsetUsedComponent(Horizontal);\n\n\t_combiner = TakeAverage;\n\n\t_ampN.setUsedComponent(FirstHorizontal);\n\t_ampE.setUsedComponent(SecondHorizontal);\n\n\t_ampE.setPublishFunction(boost::bind(&AmplitudeProcessor_ML2h::newAmplitude, this, _1, _2));\n\t_ampN.setPublishFunction(boost::bind(&AmplitudeProcessor_ML2h::newAmplitude, this, _1, _2));\n\n\t// Propagate configuration to single processors\n\t_ampN.setConfig(config());\n\t_ampE.setConfig(config());\n\n\t_ampN.setTrigger(trigger);\n\t_ampE.setTrigger(trigger);\n}\n\n\nconst AmplitudeProcessor *AmplitudeProcessor_ML2h::componentProcessor(Component comp) const {\n\tswitch ( comp ) {\n\t\tcase FirstHorizontalComponent:\n\t\t\treturn &_ampN;\n\t\tcase SecondHorizontalComponent:\n\t\t\treturn &_ampE;\n\t\tdefault:\n\t\t\tbreak;\n\t}\n\n\treturn NULL;\n}\n\nconst DoubleArray *AmplitudeProcessor_ML2h::processedData(Component comp) const {\n\tswitch ( comp ) {\n\t\tcase FirstHorizontalComponent:\n\t\t\treturn _ampN.processedData(comp);\n\t\tcase SecondHorizontalComponent:\n\t\t\treturn _ampE.processedData(comp);\n\t\tdefault:\n\t\t\tbreak;\n\t}\n\n\treturn NULL;\n}\n\n\nvoid AmplitudeProcessor_ML2h::reprocess(OPT(double) searchBegin, OPT(double) searchEnd) {\n\tsetStatus(WaitingForData, 0);\n\t_ampN.setConfig(config());\n\t_ampE.setConfig(config());\n\n\t_results[0] = _results[1] = Core::None;\n\n\t_ampN.reprocess(searchBegin, searchEnd);\n\t_ampE.reprocess(searchBegin, searchEnd);\n\n\tif ( !isFinished() ) {\n\t\tif ( _ampN.status() > Finished )\n\t\t\tsetStatus(_ampN.status(), _ampN.statusValue());\n\t\telse\n\t\t\tsetStatus(_ampE.status(), _ampE.statusValue());\n\t}\n}\n\n\nint AmplitudeProcessor_ML2h::capabilities() const {\n\treturn _ampN.capabilities() | Combiner;\n}\n\n\nAmplitudeProcessor::IDList\nAmplitudeProcessor_ML2h::capabilityParameters(Capability cap) const {\n\tif ( cap == Combiner ) {\n\t\tIDList params;\n\t\tparams.push_back(\"Average\");\n\t\tparams.push_back(\"Max\");\n\t\tparams.push_back(\"Min\");\n\t\tparams.push_back(\"Geometric mean\");\n\t\treturn params;\n\t}\n\n\treturn _ampN.capabilityParameters(cap);\n}\n\n\nbool AmplitudeProcessor_ML2h::setParameter(Capability cap, const std::string &value) {\n\tif ( cap == Combiner ) {\n\t\tif ( value == \"Min\" ) {\n\t\t\t_combiner = TakeMin;\n\t\t\treturn true;\n\t\t}\n\t\telse if ( value == \"Max\" ) {\n\t\t\t_combiner = TakeMax;\n\t\t\treturn true;\n\t\t}\n\t\telse if ( value == \"Average\" ) {\n\t\t\t_combiner = TakeAverage;\n\t\t\treturn true;\n\t\t}\n\t\telse if ( value == \"Geometric mean\" ) {\n\t\t\t_combiner = TakeGeometricMean;\n\t\t\treturn true;\n\t\t}\n\n\t\treturn false;\n\t}\n\n\t_ampN.setParameter(cap, value);\n\treturn _ampE.setParameter(cap, value);\n}\n\n\nbool AmplitudeProcessor_ML2h::setup(const Settings &settings) {\n\t// Copy the stream configurations (gain, orientation, responses, ...) to\n\t// the horizontal processors\n\t_ampN.streamConfig(FirstHorizontalComponent) = streamConfig(FirstHorizontalComponent);\n\t_ampE.streamConfig(SecondHorizontalComponent) = streamConfig(SecondHorizontalComponent);\n\n\t_combiner = TakeAverage;\n\n\ttry {\n\t\tstd::string s = settings.getString(\"amplitudes.\" + _type + \".combiner\");\n\t\tif ( s == \"average\" )\n\t\t\t_combiner = TakeAverage;\n\t\telse if ( s == \"max\" )\n\t\t\t_combiner = TakeMax;\n\t\telse if ( s == \"min\" )\n\t\t\t_combiner = TakeMin;\n\t\telse if ( s == \"geometric_mean\" )\n\t\t\t_combiner = TakeGeometricMean;\n\t\telse {\n\t\t\tSEISCOMP_ERROR(\"%s: invalid combiner type for station %s.%s: %s\",\n\t\t\t               _type.c_str(),\n\t\t\t               settings.networkCode.c_str(), settings.stationCode.c_str(),\n\t\t\t               s.c_str());\n\t\t\treturn false;\n\t\t}\n\t}\n\tcatch ( ... ) {}\n\n\tif ( !AmplitudeProcessor::setup(settings) ) return false;\n\n\t// Setup each component\n\tif ( !_ampN.setup(settings) || !_ampE.setup(settings) ) return false;\n\n\treturn true;\n}\n\n\nvoid AmplitudeProcessor_ML2h::setTrigger(const Core::Time& trigger) {\n\tAmplitudeProcessor::setTrigger(trigger);\n\t_ampE.setTrigger(trigger);\n\t_ampN.setTrigger(trigger);\n}\n\n\nvoid AmplitudeProcessor_ML2h::computeTimeWindow() {\n\t// Copy configuration to each component\n\t_ampN.setConfig(config());\n\t_ampE.setConfig(config());\n\n\t_ampE.computeTimeWindow();\n\t_ampN.computeTimeWindow();\n\tsetTimeWindow(_ampE.timeWindow() | _ampN.timeWindow());\n}\n\n\ndouble AmplitudeProcessor_ML2h::timeWindowLength(double distance_deg) const {\n\tdouble endN = _ampN.timeWindowLength(distance_deg);\n\tdouble endE = _ampE.timeWindowLength(distance_deg);\n\t_ampN.setSignalEnd(endN);\n\t_ampE.setSignalEnd(endE);\n\treturn std::max(endN, endE);\n}\n\n\nvoid AmplitudeProcessor_ML2h::reset() {\n\tAmplitudeProcessor::reset();\n\n\t_results[0] = _results[1] = Core::None;\n\n\t_ampE.reset();\n\t_ampN.reset();\n}\n\n\nvoid AmplitudeProcessor_ML2h::close() {\n\t// TODO: Check for best available amplitude here\n}\n\n\nbool AmplitudeProcessor_ML2h::feed(const Record *record) {\n\t// Both processors finished already?\n\tif ( _ampE.isFinished() && _ampN.isFinished() ) return false;\n\n\t// Did an error occur?\n\tif ( status() > WaveformProcessor::Finished ) return false;\n\n\tif ( record->channelCode() == _streamConfig[FirstHorizontalComponent].code() ) {\n\t\tif ( !_ampN.isFinished() ) {\n\t\t\t_ampN.feed(record);\n\t\t\tif ( _ampN.status() == InProgress )\n\t\t\t\tsetStatus(WaveformProcessor::InProgress, _ampN.statusValue());\n\t\t\telse if ( _ampN.isFinished() && _ampE.isFinished() ) {\n\t\t\t\tif ( !isFinished() ) {\n\t\t\t\t\tif ( _ampE.status() == Finished )\n\t\t\t\t\t\tsetStatus(_ampN.status(), _ampN.statusValue());\n\t\t\t\t\telse\n\t\t\t\t\t\tsetStatus(_ampE.status(), _ampE.statusValue());\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\telse if ( record->channelCode() == _streamConfig[SecondHorizontalComponent].code() ) {\n\t\tif ( !_ampE.isFinished() ) {\n\t\t\t_ampE.feed(record);\n\t\t\tif ( _ampE.status() == InProgress )\n\t\t\t\tsetStatus(WaveformProcessor::InProgress, _ampE.statusValue());\n\t\t\telse if ( _ampE.isFinished() && _ampN.isFinished() ) {\n\t\t\t\tif ( !isFinished() ) {\n\t\t\t\t\tif ( _ampN.status() == Finished )\n\t\t\t\t\t\tsetStatus(_ampE.status(), _ampE.statusValue());\n\t\t\t\t\telse\n\t\t\t\t\t\tsetStatus(_ampN.status(), _ampN.statusValue());\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn true;\n}\n\n\nbool AmplitudeProcessor_ML2h::computeAmplitude(const DoubleArray &data,\n                                               size_t i1, size_t i2,\n                                               size_t si1, size_t si2,\n                                               double offset,\n                                               AmplitudeIndex *dt,\n                                               AmplitudeValue *amplitude,\n                                               double *period, double *snr) {\n\treturn false;\n}\n\n\nvoid AmplitudeProcessor_ML2h::newAmplitude(const AmplitudeProcessor *proc,\n                                           const AmplitudeProcessor::Result &res) {\n\n\tif ( isFinished() ) return;\n\n\tint idx = 0;\n\n\tif ( proc == &_ampE ) {\n\t\tidx = 0;\n\t}\n\telse if ( proc == &_ampN ) {\n\t\tidx = 1;\n\t}\n\n\t_results[idx] = ComponentResult();\n\t_results[idx]->value = res.amplitude;\n\t_results[idx]->time = res.time;\n\t_results[idx]->snr = res.snr;\n\n\tif ( _results[0] && _results[1] ) {\n\t\tsetStatus(Finished, 100.);\n\t\tResult newRes;\n\t\tnewRes.record = res.record;\n\n\t\tswitch ( _combiner ) {\n\t\t\tcase TakeAverage:\n\t\t\t\tnewRes.amplitude = average(_results[0]->value, _results[1]->value);\n\t\t\t\tnewRes.time = average(_results[0]->time, _results[1]->time);\n\t\t\t\tnewRes.component = Horizontal;\n\t\t\t\tbreak;\n\t\t\tcase TakeGeometricMean:\n\t\t\t\tnewRes.amplitude = gmean(_results[0]->value, _results[1]->value);\n\t\t\t\tnewRes.time = average(_results[0]->time, _results[1]->time);\n\t\t\t\tnewRes.component = Horizontal;\n\t\t\t\tbreak;\n\t\t\tcase TakeMin:\n\t\t\t\tif ( _results[0]->value.value <= _results[1]->value.value ) {\n\t\t\t\t\tnewRes.amplitude = _results[0]->value;\n\t\t\t\t\tnewRes.time = _results[0]->time;\n\t\t\t\t\tnewRes.component = _ampE.usedComponent();\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tnewRes.amplitude = _results[1]->value;\n\t\t\t\t\tnewRes.time = _results[1]->time;\n\t\t\t\t\tnewRes.component = _ampN.usedComponent();\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase TakeMax:\n\t\t\t\tif ( _results[0]->value.value >= _results[1]->value.value ) {\n\t\t\t\t\tnewRes.amplitude =  _results[0]->value;\n\t\t\t\t\tnewRes.time = _results[0]->time;\n\t\t\t\t\tnewRes.component = _ampE.usedComponent();\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tnewRes.amplitude =  _results[1]->value;\n\t\t\t\t\tnewRes.time = _results[1]->time;\n\t\t\t\t\tnewRes.component = _ampN.usedComponent();\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t};\n\n\t\tnewRes.period = -1;\n\t\tnewRes.snr = std::min(_results[0]->snr, _results[1]->snr);\n\t\temitAmplitude(newRes);\n\t}\n}\n\n\n}\n}\n", "meta": {"hexsha": "84c72357917f63a5d4385082afacc0769e0ba727", "size": 13369, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/trunk/libs/seiscomp3/processing/amplitudes/MLh.cpp", "max_stars_repo_name": "kbouk/seiscomp3", "max_stars_repo_head_hexsha": "2385e4197274135c70aaef93a0b7df65ed8fa6a6", "max_stars_repo_licenses": ["Naumen", "Condor-1.1", "MS-PL"], "max_stars_count": 94.0, "max_stars_repo_stars_event_min_datetime": "2015-02-04T13:57:34.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-01T15:10:06.000Z", "max_issues_repo_path": "src/trunk/libs/seiscomp3/processing/amplitudes/MLh.cpp", "max_issues_repo_name": "kbouk/seiscomp3", "max_issues_repo_head_hexsha": "2385e4197274135c70aaef93a0b7df65ed8fa6a6", "max_issues_repo_licenses": ["Naumen", "Condor-1.1", "MS-PL"], "max_issues_count": 233.0, "max_issues_repo_issues_event_min_datetime": "2015-01-28T15:16:46.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-23T11:31:37.000Z", "max_forks_repo_path": "src/trunk/libs/seiscomp3/processing/amplitudes/MLh.cpp", "max_forks_repo_name": "kbouk/seiscomp3", "max_forks_repo_head_hexsha": "2385e4197274135c70aaef93a0b7df65ed8fa6a6", "max_forks_repo_licenses": ["Naumen", "Condor-1.1", "MS-PL"], "max_forks_count": 95.0, "max_forks_repo_forks_event_min_datetime": "2015-02-13T15:53:30.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-02T14:54:54.000Z", "avg_line_length": 26.9536290323, "max_line_length": 108, "alphanum_fraction": 0.6559204129, "num_tokens": 3661, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6791787121629466, "lm_q2_score": 0.48438008427698437, "lm_q1q2_score": 0.3289806418366218}}
{"text": "/* +------------------------------------------------------------------------+\n   |                     Mobile Robot Programming Toolkit (MRPT)            |\n   |                          https://www.mrpt.org/                         |\n   |                                                                        |\n   | Copyright (c) 2005-2021, Individual contributors, see AUTHORS file     |\n   | See: https://www.mrpt.org/Authors - All rights reserved.               |\n   | Released under BSD License. See: https://www.mrpt.org/License          |\n   +------------------------------------------------------------------------+ */\n\n#include \"poses-precomp.h\"\t// Precompiled headers\n//\n#include <mrpt/poses/CPose3DPDFGaussian.h>\n#include <mrpt/poses/CPose3DPDFParticles.h>\n#include <mrpt/poses/CPose3DPDFSOG.h>\n#include <mrpt/poses/CPosePDFGaussian.h>\n#include <mrpt/poses/CPosePDFParticles.h>\n#include <mrpt/poses/CPosePDFSOG.h>\n#include <mrpt/poses/CPoseRandomSampler.h>\n#include <mrpt/random.h>\n\n#include <Eigen/Dense>\n\nusing namespace mrpt;\nusing namespace mrpt::math;\nusing namespace mrpt::poses;\nusing namespace mrpt::random;\n\n/*---------------------------------------------------------------\n\t\tConstructor\n  ---------------------------------------------------------------*/\nCPoseRandomSampler::CPoseRandomSampler() = default;\nCPoseRandomSampler::CPoseRandomSampler(const CPoseRandomSampler& o)\n{\n\t*this = o;\n}\n\nCPoseRandomSampler& CPoseRandomSampler::operator=(const CPoseRandomSampler& o)\n{\n\tif (&o == this) return *this;\n\tm_pdf2D.reset();\n\tm_pdf3D.reset();\n\tif (o.m_pdf2D) m_pdf2D.reset(dynamic_cast<CPosePDF*>(o.m_pdf2D->clone()));\n\tif (o.m_pdf3D) m_pdf3D.reset(dynamic_cast<CPose3DPDF*>(o.m_pdf3D->clone()));\n\tm_fastdraw_gauss_Z3 = o.m_fastdraw_gauss_Z3;\n\tm_fastdraw_gauss_Z6 = o.m_fastdraw_gauss_Z6;\n\tm_fastdraw_gauss_M_2D = o.m_fastdraw_gauss_M_2D;\n\tm_fastdraw_gauss_M_3D = o.m_fastdraw_gauss_M_3D;\n\treturn *this;\n}\n\nCPoseRandomSampler::CPoseRandomSampler(CPoseRandomSampler&& o)\n\t: m_pdf2D(nullptr), m_pdf3D(nullptr)\n{\n\tif (o.m_pdf2D)\n\t{\n\t\tm_pdf2D = std::move(o.m_pdf2D);\n\t\to.m_pdf2D = nullptr;\n\t}\n\tif (o.m_pdf3D)\n\t{\n\t\tm_pdf3D = std::move(o.m_pdf3D);\n\t\to.m_pdf3D = nullptr;\n\t}\n\tm_fastdraw_gauss_Z3 = std::move(o.m_fastdraw_gauss_Z3);\n\tm_fastdraw_gauss_Z6 = std::move(o.m_fastdraw_gauss_Z6);\n\tm_fastdraw_gauss_M_2D = std::move(o.m_fastdraw_gauss_M_2D);\n\tm_fastdraw_gauss_M_3D = std::move(o.m_fastdraw_gauss_M_3D);\n}\nCPoseRandomSampler& CPoseRandomSampler::operator=(CPoseRandomSampler&& o)\n{\n\tif (this == &o) return *this;\n\tthis->clear();\n\tif (o.m_pdf2D)\n\t{\n\t\tm_pdf2D = std::move(o.m_pdf2D);\n\t\to.m_pdf2D = nullptr;\n\t}\n\tif (o.m_pdf3D)\n\t{\n\t\tm_pdf3D = std::move(o.m_pdf3D);\n\t\to.m_pdf3D = nullptr;\n\t}\n\tm_fastdraw_gauss_Z3 = std::move(o.m_fastdraw_gauss_Z3);\n\tm_fastdraw_gauss_Z6 = std::move(o.m_fastdraw_gauss_Z6);\n\tm_fastdraw_gauss_M_2D = std::move(o.m_fastdraw_gauss_M_2D);\n\tm_fastdraw_gauss_M_3D = std::move(o.m_fastdraw_gauss_M_3D);\n\treturn *this;\n}\n\n/*---------------------------------------------------------------\n\t\t\tclear\n  ---------------------------------------------------------------*/\nvoid CPoseRandomSampler::clear()\n{\n\tm_pdf2D.reset();\n\tm_pdf3D.reset();\n}\n\n/*---------------------------------------------------------------\n\t\t\t\t\t\tsetPosePDF\n  ---------------------------------------------------------------*/\nvoid CPoseRandomSampler::setPosePDF(const CPosePDF& pdf)\n{\n\tMRPT_START\n\n\tclear();\n\tm_pdf2D.reset(dynamic_cast<CPosePDF*>(pdf.clone()));\n\n\t// According to the PDF type:\n\tif (IS_CLASS(pdf, CPosePDFGaussian))\n\t{\n\t\tconst auto& gPdf = dynamic_cast<const CPosePDFGaussian&>(pdf);\n\t\tconst CMatrixDouble33& cov = gPdf.cov;\n\n\t\tm_fastdraw_gauss_M_2D = gPdf.mean;\n\n\t\tstd::vector<double> eigVals;\n\t\tcov.eig_symmetric(m_fastdraw_gauss_Z3, eigVals);\n\n\t\t// Scale eigenvectors with eigenvalues:\n\t\tmrpt::math::CMatrixDouble33 D;\n\t\tD.setDiagonal(eigVals);\n\t\tD = D.asEigen().array().sqrt().matrix();\n\t\tm_fastdraw_gauss_Z3.matProductOf_AB(m_fastdraw_gauss_Z3, D);\n\t}\n\telse if (IS_CLASS(pdf, CPosePDFParticles))\n\t{\n\t\treturn;\t // Nothing to prepare.\n\t}\n\telse\n\t{\n\t\tTHROW_EXCEPTION_FMT(\n\t\t\t\"Unsupported class: %s\", m_pdf2D->GetRuntimeClass()->className);\n\t}\n\n\tMRPT_END\n}\n\n/*---------------------------------------------------------------\n\t\t\t\t\t\tsetPosePDF\n  ---------------------------------------------------------------*/\nvoid CPoseRandomSampler::setPosePDF(const CPose3DPDF& pdf)\n{\n\tMRPT_START\n\n\tclear();\n\tm_pdf3D.reset(dynamic_cast<CPose3DPDF*>(pdf.clone()));\n\n\t// According to the PDF type:\n\tif (IS_CLASS(pdf, CPose3DPDFGaussian))\n\t{\n\t\tconst auto& gPdf = dynamic_cast<const CPose3DPDFGaussian&>(pdf);\n\t\tconst CMatrixDouble66& cov = gPdf.cov;\n\n\t\tm_fastdraw_gauss_M_3D = gPdf.mean;\n\n\t\tstd::vector<double> eigVals;\n\t\tcov.eig_symmetric(m_fastdraw_gauss_Z6, eigVals);\n\n\t\t// Scale eigenvectors with eigenvalues:\n\t\tmrpt::math::CMatrixDouble66 D;\n\t\tD.setDiagonal(eigVals);\n\n\t\t// Scale eigenvectors with eigenvalues:\n\t\tD = D.asEigen().array().sqrt().matrix();\n\t\tm_fastdraw_gauss_Z6.matProductOf_AB(m_fastdraw_gauss_Z6, D);\n\t}\n\telse if (IS_CLASS(pdf, CPose3DPDFParticles))\n\t{\n\t\treturn;\t // Nothing to prepare.\n\t}\n\telse\n\t{\n\t\tTHROW_EXCEPTION_FMT(\n\t\t\t\"Unsoported class: %s\", m_pdf3D->GetRuntimeClass()->className);\n\t}\n\n\tMRPT_END\n}\n\n/*---------------------------------------------------------------\n\t\t\t\t\tdrawSample\n  ---------------------------------------------------------------*/\nCPose2D& CPoseRandomSampler::drawSample(CPose2D& p) const\n{\n\tMRPT_START\n\n\tif (m_pdf2D) { do_sample_2D(p); }\n\telse if (m_pdf3D)\n\t{\n\t\tCPose3D q;\n\t\tdo_sample_3D(q);\n\t\tp.x(q.x());\n\t\tp.y(q.y());\n\t\tp.phi(q.yaw());\n\t}\n\telse\n\t\tTHROW_EXCEPTION(\"No associated pdf: setPosePDF must be called first.\");\n\n\treturn p;\n\tMRPT_END\n}\n\n/*---------------------------------------------------------------\n\t\t\t\t\tdrawSample\n  ---------------------------------------------------------------*/\nCPose3D& CPoseRandomSampler::drawSample(CPose3D& p) const\n{\n\tMRPT_START\n\n\tif (m_pdf2D)\n\t{\n\t\tCPose2D q;\n\t\tdo_sample_2D(q);\n\t\tp.setFromValues(q.x(), q.y(), 0, q.phi(), 0, 0);\n\t}\n\telse if (m_pdf3D)\n\t{\n\t\tdo_sample_3D(p);\n\t}\n\telse\n\t\tTHROW_EXCEPTION(\"No associated pdf: setPosePDF must be called first.\");\n\n\treturn p;\n\tMRPT_END\n}\n\n/*---------------------------------------------------------------\n\t\t\t\t  do_sample_2D: Sample from a 2D PDF\n  ---------------------------------------------------------------*/\nvoid CPoseRandomSampler::do_sample_2D(CPose2D& p) const\n{\n\tMRPT_START\n\tASSERT_(m_pdf2D);\n\n\t// According to the PDF type:\n\tif (IS_CLASS(*m_pdf2D, CPosePDFGaussian))\n\t{\n\t\t// ------------------------------\n\t\t//      A single gaussian:\n\t\t// ------------------------------\n\t\tCVectorDouble rndVector(3);\n\t\trndVector.setZero();\n\t\tfor (size_t i = 0; i < 3; i++)\n\t\t{\n\t\t\tdouble rnd = getRandomGenerator().drawGaussian1D_normalized();\n\t\t\tfor (size_t d = 0; d < 3; d++)\n\t\t\t\trndVector[d] += (m_fastdraw_gauss_Z3(d, i) * rnd);\n\t\t}\n\n\t\tp.x(m_fastdraw_gauss_M_2D.x() + rndVector[0]);\n\t\tp.y(m_fastdraw_gauss_M_2D.y() + rndVector[1]);\n\t\tp.phi(m_fastdraw_gauss_M_2D.phi() + rndVector[2]);\n\t\tp.normalizePhi();\n\t}\n\telse if (IS_CLASS(*m_pdf2D, CPosePDFSOG))\n\t{\n\t\t// -------------------------------------\n\t\t//      \t\t\tSOG\n\t\t// -------------------------------------\n\t\tTHROW_EXCEPTION(\"TODO\");\n\t}\n\telse if (IS_CLASS(*m_pdf2D, CPosePDFParticles))\n\t{\n\t\t// -------------------------------------\n\t\t//      Particles: just sample as usual\n\t\t// -------------------------------------\n\t\tconst auto& pdf = dynamic_cast<const CPosePDFParticles&>(*m_pdf2D);\n\t\tpdf.drawSingleSample(p);\n\t}\n\telse\n\t\tTHROW_EXCEPTION_FMT(\n\t\t\t\"Unsoported class: %s\", m_pdf2D->GetRuntimeClass()->className);\n\n\tMRPT_END\n}\n\n/*---------------------------------------------------------------\n\t\t\t\t  do_sample_3D: Sample from a 3D PDF\n  ---------------------------------------------------------------*/\nvoid CPoseRandomSampler::do_sample_3D(CPose3D& p) const\n{\n\tMRPT_START\n\tASSERT_(m_pdf3D);\n\n\t// According to the PDF type:\n\tif (IS_CLASS(*m_pdf3D, CPose3DPDFGaussian))\n\t{\n\t\t// ------------------------------\n\t\t//      A single gaussian:\n\t\t// ------------------------------\n\t\tCVectorDouble rndVector(6);\n\t\trndVector.setZero();\n\t\tfor (size_t i = 0; i < 6; i++)\n\t\t{\n\t\t\tdouble rnd = getRandomGenerator().drawGaussian1D_normalized();\n\t\t\tfor (size_t d = 0; d < 6; d++)\n\t\t\t\trndVector[d] += (m_fastdraw_gauss_Z6(d, i) * rnd);\n\t\t}\n\n\t\tp.setFromValues(\n\t\t\tm_fastdraw_gauss_M_3D.x() + rndVector[0],\n\t\t\tm_fastdraw_gauss_M_3D.y() + rndVector[1],\n\t\t\tm_fastdraw_gauss_M_3D.z() + rndVector[2],\n\t\t\tm_fastdraw_gauss_M_3D.yaw() + rndVector[3],\n\t\t\tm_fastdraw_gauss_M_3D.pitch() + rndVector[4],\n\t\t\tm_fastdraw_gauss_M_3D.roll() + rndVector[5]);\n\t}\n\telse if (IS_CLASS(*m_pdf3D, CPose3DPDFSOG))\n\t{\n\t\t// -------------------------------------\n\t\t//      \t\t\tSOG\n\t\t// -------------------------------------\n\t\tTHROW_EXCEPTION(\"TODO\");\n\t}\n\telse if (IS_CLASS(*m_pdf3D, CPose3DPDFParticles))\n\t{\n\t\t// -------------------------------------\n\t\t//      Particles: just sample as usual\n\t\t// -------------------------------------\n\t\tconst auto& pdf = dynamic_cast<const CPose3DPDFParticles&>(*m_pdf3D);\n\t\tpdf.drawSingleSample(p);\n\t}\n\telse\n\t\tTHROW_EXCEPTION_FMT(\n\t\t\t\"Unsoported class: %s\", m_pdf3D->GetRuntimeClass()->className);\n\n\tMRPT_END\n}\n\n/*---------------------------------------------------------------\n\t\t\t\t  isPrepared\n  ---------------------------------------------------------------*/\nbool CPoseRandomSampler::isPrepared() const { return m_pdf2D || m_pdf3D; }\n/*---------------------------------------------------------------\n\t\t\t\t  getOriginalPDFCov2D\n  ---------------------------------------------------------------*/\nvoid CPoseRandomSampler::getOriginalPDFCov2D(CMatrixDouble33& cov3x3) const\n{\n\tMRPT_START\n\tASSERT_(this->isPrepared());\n\n\tif (m_pdf2D) { m_pdf2D->getCovariance(cov3x3); }\n\telse\n\t{\n\t\tASSERT_(m_pdf3D);\n\n\t\tCPosePDFGaussian P;\n\t\tP.copyFrom(*m_pdf3D);\n\t\tcov3x3 = P.cov;\n\t}\n\n\tMRPT_END\n}\n\n/*---------------------------------------------------------------\n\t\t\t\t  getOriginalPDFCov3D\n  ---------------------------------------------------------------*/\nvoid CPoseRandomSampler::getOriginalPDFCov3D(CMatrixDouble66& cov6x6) const\n{\n\tMRPT_START\n\tASSERT_(this->isPrepared());\n\n\tif (m_pdf2D)\n\t{\n\t\tCPose3DPDFGaussian P;\n\t\tP.copyFrom(*m_pdf2D);\n\t\tcov6x6 = P.cov;\n\t}\n\telse\n\t{\n\t\tASSERT_(m_pdf3D);\n\t\tm_pdf3D->getCovariance(cov6x6);\n\t}\n\n\tMRPT_END\n}\n\n/*---------------------------------------------------------------\n\t\t\t\t  getSamplingMean2D\n  ---------------------------------------------------------------*/\nCPose2D& CPoseRandomSampler::getSamplingMean2D(CPose2D& out_mean) const\n{\n\tMRPT_START\n\tASSERT_(this->isPrepared());\n\n\tif (m_pdf2D) out_mean = m_fastdraw_gauss_M_2D;\n\telse\n\t\tout_mean = CPose2D(m_fastdraw_gauss_M_3D);\n\n\treturn out_mean;\n\tMRPT_END\n}\n\n/*---------------------------------------------------------------\n\t\t\t\t  getSamplingMean3D\n  ---------------------------------------------------------------*/\nCPose3D& CPoseRandomSampler::getSamplingMean3D(CPose3D& out_mean) const\n{\n\tMRPT_START\n\tASSERT_(this->isPrepared());\n\n\tif (m_pdf3D) out_mean = m_fastdraw_gauss_M_3D;\n\telse\n\t\tout_mean = CPose3D(m_fastdraw_gauss_M_2D);\n\n\treturn out_mean;\n\tMRPT_END\n}\n\nvoid CPoseRandomSampler::getOriginalPDFCov2D(\n\tmrpt::math::CMatrixDouble& cov3x3) const\n{\n\tmrpt::math::CMatrixDouble33 M;\n\tthis->getOriginalPDFCov2D(M);\n\tcov3x3 = mrpt::math::CMatrixDouble(M);\n}\n\nvoid CPoseRandomSampler::getOriginalPDFCov3D(\n\tmrpt::math::CMatrixDouble& cov6x6) const\n{\n\tmrpt::math::CMatrixDouble66 M;\n\tthis->getOriginalPDFCov3D(M);\n\tcov6x6 = M;\n}\n", "meta": {"hexsha": "d1fd8f8fc5ec0634316303848411bd1e3e0b19c0", "size": 11466, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/poses/src/CPoseRandomSampler.cpp", "max_stars_repo_name": "Russ76/mrpt", "max_stars_repo_head_hexsha": "4a59edd8b3250acea27fcb94bf8e29bee1ba8e1c", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1372.0, "max_stars_repo_stars_event_min_datetime": "2015-07-25T00:33:22.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T12:55:33.000Z", "max_issues_repo_path": "libs/poses/src/CPoseRandomSampler.cpp", "max_issues_repo_name": "Russ76/mrpt", "max_issues_repo_head_hexsha": "4a59edd8b3250acea27fcb94bf8e29bee1ba8e1c", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 772.0, "max_issues_repo_issues_event_min_datetime": "2015-07-18T19:18:54.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-27T02:45:51.000Z", "max_forks_repo_path": "libs/poses/src/CPoseRandomSampler.cpp", "max_forks_repo_name": "Russ76/mrpt", "max_forks_repo_head_hexsha": "4a59edd8b3250acea27fcb94bf8e29bee1ba8e1c", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 588.0, "max_forks_repo_forks_event_min_datetime": "2015-07-23T01:13:18.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T08:05:40.000Z", "avg_line_length": 26.9154929577, "max_line_length": 80, "alphanum_fraction": 0.5551194837, "num_tokens": 3264, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6477982179521103, "lm_q2_score": 0.5078118642792044, "lm_q1q2_score": 0.32895962073500756}}
{"text": "/**\n * @brief AVL木\n * @note  AVL木(AVL tree)は高さ平衡(height\n * balanced)2分探索木である.すなわち、各節点xの左右の部分木の高さは高々1しか違わない\n *        AVL木を実現するために各節点に特別な属性を管理する. x.hはxの高さである\n *        他の任意の2分探索木Tと同様、T.rootはその根を指すものと仮定する\n *\n * @note\n * Fhをh番目のフィボナッチ数とするとき、高さhのAVL木には少なくともFh個の節点があることから\n *        n個のAVL木の高さはΟ(lgn)であることがわかる\n *\n * @note  今回は属性pを省略してコードの簡略化を図ることにする\n */\n\n#ifndef AVL_TREE_HPP\n#define AVL_TREE_HPP\n\n#include \"container.hpp\"\n#include <algorithm>\n#include <boost/assert.hpp>\n#include <boost/container/pmr/polymorphic_allocator.hpp>\n#include <memory>\n#include <optional>\n#include <utility>\n\nnamespace container {\n\ntemplate <class Key, class T> struct avl_tree_node {\n  using height_t = std::int32_t;\n  union {\n    struct {\n      avl_tree_node *l; /**< 左の子    */\n      avl_tree_node *r; /**< 右の子    */\n    };\n    avl_tree_node *c[2]; /**< 左右の子(0:左, 1:右) */\n  };\n  height_t h; /**< 高さ */\n  Key key;    /**< キー    */\n  T v;        /**< 付属データ */\n\n  constexpr explicit avl_tree_node(const Key &k, const T &v) noexcept\n      : l(nullptr), r(nullptr), h(1), key(k), v(v) {}\n};\n\n/**\n * @brief  AVL木\n * @tparam Key     キーの型\n * @tparam T       付属データの型\n * @tparam Compare キーを引数にとる比較述語の型\n */\ntemplate <class Key, class T, class Compare = std::less<Key>,\n          class Allocator = boost::container::pmr::polymorphic_allocator<\n              avl_tree_node<Key, T>>>\nstruct avl_tree {\n  static_assert(std::is_nothrow_constructible_v<Key> &&\n                std::is_nothrow_constructible_v<T>);\n  using alloc = std::allocator_traits<Allocator>;\n  using sides_t = std::int32_t;\n  using pair_t = std::pair<const Key, T>;\n  using node = avl_tree_node<Key, T>;\n  using height_t = typename node::height_t;\n\n  explicit avl_tree(std::size_t n = 32) { allocate_pool(n); }\n  ~avl_tree() noexcept { free_pool(); } // 確保した記憶領域の解放\n\n  /**\n   * @brief  AVL木からキーkに対応する付属データを返す\n   * @note   実行時間はΟ(lgn)\n   * @param  const Key& k キーk\n   * @return キーkに対応する付属データ\n   */\n  std::optional<T> find(const Key &k) const {\n    const node *x = find(root_, k);\n    return x == nullptr ? std::nullopt : std::make_optional(x->v);\n  }\n\n  /**\n   * @brief AVL木Tにキーkの挿入を行う\n   * @note  実行時間はΟ(lgn)\n   * @param const Key& k キーk\n   * @param const T& v   付属データv\n   * @return キーkに対応していた付属データ\n   */\n  std::optional<T> insert(const Key &k, const T &v) {\n    std::optional<T> opt = std::nullopt;\n    root_ = insert(root_, k, v, opt);\n    return opt;\n  }\n\n  /**\n   * @brief AVL木Tからキーkを持つ節点の削除を行う\n   * @note  実行時間はΟ(lgn)\n   * @param const Key&git  k キーk\n   * @return キーkに対応していた付属データ\n   */\n  std::optional<T> erase(const Key &k) {\n    std::optional<T> opt = std::nullopt;\n    root_ = erase(root_, k, opt);\n    return opt;\n  }\n\n  /**\n   * @brief  中間順木巡回を行う\n   * @note   n個の節点を持つ2分探索木の巡回はΘ(n)かかる\n   * @tparam class F const Key&を引数に取る関数オブジェクトの型\n   * @param F fn     const T&を引数に取る関数オブジェクト\n   */\n  template <class F> void inorder(F fn) { inorder(root_, fn); }\n\nprivate:\n  /**\n   * @brief  中間順木巡回を行う\n   * @note   n個の節点を持つ2分探索木の巡回はΘ(n)かかる\n   * @tparam class F const Key&を引数に取る関数の型\n   * @param F fn     const Key&を引数に取る関数\n   * @param node*x   巡回を行う部分木の根\n   */\n  template <class F> void inorder(node *x, F fn) {\n    if (x == nullptr) {\n      return;\n    } // xがNILを指すとき、再帰は底をつく\n    inorder(x->l, fn);\n    fn(x->key, x->v);\n    inorder(x->r,\n            fn); // xの左右の子を根とする部分木に対して中間順木巡回を行う\n  }\n\n  /**\n   * @brief  AVL木からキーkに対応する付属データを返す\n   * @note   実行時間はΟ(lgn)\n   * @param  const Key& k キーk\n   * @return キーkに対応する付属データへのポインタ\n   */\n  node *find(node *x, const Key &k) const {\n    if (x == nullptr || eq(x->key, k)) {\n      return x;\n    } else {\n      return find(cmp_(k, x->key) ? x->l : x->r, k);\n    }\n  }\n\n  /**\n   * @brief 節点xを根とする部分木にキーkの挿入を行う\n   * @param node*x       節点x\n   * @param node*z       キーkを持つ節点z\n   */\n  node *insert(node *x, const Key &k, const T &v, std::optional<T> &opt) {\n    if (x == nullptr) {\n      return create_node(k, v);\n    }                      // xがNILを指すとき、再帰は底をつく\n    if (cmp_(k, x->key)) { // xの適切な子に再帰し、\n      x->l = insert(x->l, k, v, opt);\n    } else if (cmp_(x->key, k)) {\n      x->r = insert(x->r, k, v, opt);\n    } else {\n      opt = x->v;\n      x->v = v;\n      return x;\n    }\n    return balance(x); // xを根とする部分木を高さ平衡にする\n  }\n\n  /**\n   * @brief 節点xを根とする部分木からキーkを削除する\n   * @param node*x       節点x\n   * @param const Key& k キーk\n   */\n  node *erase(node *x, const Key &k, std::optional<T> &opt) {\n    if (x == nullptr) {\n      return nullptr;\n    } // キーkはAVL木Tに存在しなかった\n    if (cmp_(k, x->key)) {\n      x->l = erase(x->l, k, opt);\n      return balance(x);\n    } // xの適切な子に再帰し、\n    if (cmp_(x->key, k)) {\n      x->r = erase(x->r, k, opt);\n      return balance(x);\n    } // xを根とする部分木を高さ平衡にする\n    opt = x->v;\n    node *y = x->l,\n         *z = x->r; // x.key == kのとき、yをxの左の子、zをxの右の子とし、\n    destroy_node(x); // xを解放する\n    if (z == nullptr) {\n      return y;\n    } // zがNILを指しているならば、新たな部分木の根としてyを返す\n    node *w = leftmost(\n        z); // zがNILを指していないならば、wをzを根とする部分木の中で最も左の子とする\n    w->r = erase__(\n        z); // zに対して再帰する.そして、wの右の子に新たな部分木を受け取る\n    w->l = y;          // yをwの左の子にする\n    return balance(w); // wを根とする部分木を高さ平衡にして戻る\n  }\n\n  /**\n   * @brief\n   * 節点xの左右の部分木はそれぞれ高さ平衡しており、その左右の子の高さの差は2以下であるとする\n   *         xを入力とし、xを根とする部分木を高さ平衡になるように変換する\n   * @note   回転は高々2回であるため実行時間はΟ(1)\n   * @param  node*x 節点x\n   * @return 高さ平衡な部分木の根\n   */\n  static node *balance(node *x) {\n    x->h = reheight(x); // xの高さを更新する\n    if (bias(x) > 1) {  // 左に2つ分偏っている場合、left-l\n                        // caseおよびleft-r caseが考えられる\n      if (bias(x->l) < 0) {\n        x->l = left_rotate(x->l);\n      } // l-r caseならば、左回転を行うことで、left-l caseに帰着させる\n      return right_rotate(x); // 右回転を行うことでleft-l\n                              // caseを解消し、高さ平衡を満たす部分木の根を返す\n    }\n    if (bias(x) < -1) { // 右に2つ分偏っている場合、right-r\n                        // caseおよびright-l caseが考えられる\n      if (bias(x->r) > 0) {\n        x->r = right_rotate(x->r);\n      } // r-l caseならば、右回転を行うことで、right-r\n        // caseに帰着させる\n      return left_rotate(x); // 左回転を行うことでright-r\n                             // caseを解消し、高さ平衡を満たす部分木の根を返す\n    }\n    return x; // 高さ平衡の場合、xを返す\n  }\n  /**\n   * @brief\n   * 節点xからy(xのjの子)へのリンクを\"ピボット\"とするi回転で、回転の結果、\n   *         yが部分木の新しい根となり、xがyのiの子、yのiの子がxのjの子になる\n   * @note   x.c[j] != NILを仮定している. 実行時間はΟ(1)\n   * @param  node*   x  節点x\n   * @param  sides_t i  添字i(0のとき左、1のとき右)\n   * @param  sides_t j  添字j(0のとき左、1のとき右)\n   */\n  static node *rotate(node *x, sides_t i, sides_t j) {\n    node *y = x->c[j];  // yをxのjの子とする\n    x->c[j] = y->c[i];  // yのi部分木をxのj部分木にする\n    y->c[i] = x;        // xをyのiの子にする\n    x->h = reheight(x); // xの高さを更新する\n    y->h = reheight(y); // yの高さを更新する\n    return y;           // 部分木の新しい根yを返す\n  }\n  static node *left_rotate(node *x) { return rotate(x, 0, 1); }\n  static node *right_rotate(node *x) { return rotate(x, 1, 0); }\n\n  /**\n   * @brief 節点xを根とする部分木の中から最も左にある子を取得する\n   * @param node*x 節点x\n   */\n  static node *leftmost(node *x) { return x->l ? leftmost(x->l) : x; }\n\n  /**\n   * @brief xを根とする部分木の最も左の子を削除する補助関数\n   * @param node*x 節点x\n   */\n  static node *erase__(node *x) {\n    if (x->l == nullptr) {\n      return x->r;\n    }\n    x->l = erase__(x->l);\n    return balance(x);\n  }\n\nprivate:\n  /**< @brief 節点xの高さを取得する  */\n  static constexpr height_t height(node *x) noexcept { return x ? x->h : 0; }\n  /**< @brief 節点xの更新される高さを返す */\n  static constexpr height_t reheight(node *x) noexcept {\n    return std::max(height(x->l), height(x->r)) + 1;\n  }\n  /**< @brief 節点xの左右の子の高さの差(x.l - x.r)を返す */\n  static constexpr height_t bias(node *x) noexcept {\n    return height(x->l) - height(x->r);\n  }\n\nprivate:\n  /**< @brief 節点xの記憶領域の確保を行う */\n  node *create_node(const Key &k, const T &v) {\n    BOOST_ASSERT_MSG(size_ < cap_, \"AVL tree capacity over.\");\n    node *x = pool_ + size_;\n    alloc::construct(alloc_, x, k, v);\n    size_++;\n    return x;\n  }\n\n  /**< @brief 節点xの記憶領域の解放を行う */\n  void destroy_node(node *x) noexcept {\n    alloc::destroy(alloc_, x);\n    size_--;\n  }\n\n  /**< @brief 節点xを根とした部分木を再帰的に解放する*/\n  void postorder_destroy_nodes(node *x) noexcept {\n    if (x == nullptr) {\n      return;\n    }\n    postorder_destroy_nodes(x->l);\n    postorder_destroy_nodes(x->r);\n    destroy_node(x);\n  }\n\n  /**< @brief メモリプールの解放 */\n  void free_pool() noexcept {\n    postorder_destroy_nodes(root_);\n    alloc::deallocate(alloc_, pool_, cap_);\n    root_ = pool_ = nullptr;\n    size_ = cap_ = 0;\n  }\n\n  /**< @brief メモリプールの確保 */\n  void allocate_pool(std::size_t n) {\n    pool_ = alloc::allocate(alloc_, n);\n    cap_ = n;\n  }\n\nprivate:\n  /**< ＠brief キーlとキーrの非同値判定を行う */\n  inline bool neq(const Key &l, const Key &r) const {\n    return (cmp_(l, r) || cmp_(r, l));\n  }\n  /**< ＠brief キーlとキーrの同値判定を行う */\n  inline bool eq(const Key &l, const Key &r) const { return !neq(l, r); }\n\nprivate:\n  node *root_ = nullptr; /**< AVL木の根 */\n  std::size_t cap_ = 0;  /**< AVL木のバッファサイズ    */\n  std::size_t size_ = 0; /**< AVL木のサイズ           */\n  node *pool_ = nullptr; /**< AVL木の節点用メモリプール */\n  Compare cmp_;          /**< 比較述語  */\n  Allocator alloc_;      /**< アロケータ */\n};\n\n} // namespace container\n\n#endif // end of AVL_TREE_HPP\n", "meta": {"hexsha": "27dfb014992649b7046383112dc5f5897061f27a", "size": 9023, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/container/avl_tree.hpp", "max_stars_repo_name": "mnrn/game-memo", "max_stars_repo_head_hexsha": "8ed939b8ccc77ba9266beddd6214a5c0c5cc03c2", "max_stars_repo_licenses": ["Apache-2.0"], "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/container/avl_tree.hpp", "max_issues_repo_name": "mnrn/game-memo", "max_issues_repo_head_hexsha": "8ed939b8ccc77ba9266beddd6214a5c0c5cc03c2", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/container/avl_tree.hpp", "max_forks_repo_name": "mnrn/game-memo", "max_forks_repo_head_hexsha": "8ed939b8ccc77ba9266beddd6214a5c0c5cc03c2", "max_forks_repo_licenses": ["Apache-2.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.0149700599, "max_line_length": 77, "alphanum_fraction": 0.5791865233, "num_tokens": 4139, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5851011542032312, "lm_q2_score": 0.5621765008857981, "lm_q1q2_score": 0.32893011953421425}}
{"text": "#pragma once\n\n#include <cassert>\n#include <list>\n#include <unordered_map>\n#include <vector>\n\n#include <boost/heap/fibonacci_heap.hpp>\n\nnamespace hypergraphlib {\n\n/* A collection of distinct values, ordered by their keys. The key for every\n * value is initially zero.\n *\n * Supports incrementing the key of a value in constant time as well as removing\n * one of the values with maximum key in time linear to the number of buckets.\n *\n * Useful for computing vertex orderings for unweighted hypergraphs. See [M'05]\n * for more details.\n */\nclass BucketHeap {\npublic:\n  /* Create a bucket list with the given values and capacity (number of\n   * buckets). The values should be unique.\n   *\n   * Time complexity: O(n), where n in the number of values.\n   */\n  BucketHeap(std::vector<int> values, size_t capacity);\n\n  /* Increment the key of the value.\n   *\n   * Time complexity: O(1).\n   */\n  void increment(int value);\n\n  /* Pop an arbitrary value with a maximum key.\n   *\n   * Time complexity: Expected is O(1), worst-case is O(b), where b is the\n   * number of buckets.\n   */\n  int pop();\n\n  /* Pop a (key, value) pair with a maximum key.\n   *\n   * Time complexity: Expected is O(1), worst-case is O(b), where b is the\n   * number of buckets.\n   */\n  std::pair<size_t, int> pop_key_val();\n\nprivate:\n  const size_t capacity_;\n\n  // buckets_[i] is a collection of all values with key = i\n  std::vector<std::list<int>> buckets_;\n\n  // A mapping of values to their keys\n  std::unordered_map<int, size_t> val_to_keys_;\n\n  // A mapping of values to their iterators (for fast deletion)\n  std::unordered_map<int, std::list<int>::iterator> val_to_its_;\n\n  // The current maximum key\n  size_t max_key_;\n};\n\n/* Wrapper of boost::fibonacci_heap that conforms to the BucketHeap interface\n */\ntemplate<typename EdgeWeightType>\nclass FibonacciHeap {\npublic:\n  FibonacciHeap(const std::vector<int> &values, [[maybe_unused]] size_t capacity) {\n    for (const int v : values) {\n      auto handle = heap_.push({0, v});\n      const auto[it, inserted] = handles_.insert({v, handle});\n      assert(inserted);\n    }\n  }\n\n  /* Increment the key of the value.\n   *\n   * Time complexity: constant\n   */\n  void increment(const int value, const EdgeWeightType amount) {\n    auto handle = handles_.at(value);\n    auto[key, val] = *handle;\n    *handle = {key + amount, val};\n    heap_.increase(handle);\n  }\n\n  /* Pop an arbitrary value with a maximum key.\n   *\n   * Time complexity: constant\n   */\n  int pop() {\n    return pop_key_val().second;\n  }\n\n  std::pair<EdgeWeightType, int> pop_key_val() {\n    const auto pair = heap_.top();\n    heap_.pop();\n    return pair;\n  }\n\nprivate:\n  // Elements are ordered by their edge weight, and keep a reference to the vertex ID\n  using element_t = std::pair<EdgeWeightType, int>;\n  using handle_t = typename boost::heap::fibonacci_heap<element_t>::handle_type;\n\n  std::unordered_map<int, handle_t> handles_;\n\n  boost::heap::fibonacci_heap<element_t> heap_;\n};\n\n}\n", "meta": {"hexsha": "9d8ea3af97c78cb1a093a1f3700d199811a6e690", "size": 2971, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "lib/hypergraph/include/hypergraph/heap.hpp", "max_stars_repo_name": "vsui/hypergraph-k-cut", "max_stars_repo_head_hexsha": "1134ca254fb709bce62a4506c931362d84a06894", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-01-17T07:31:36.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-14T08:36:50.000Z", "max_issues_repo_path": "lib/hypergraph/include/hypergraph/heap.hpp", "max_issues_repo_name": "vsui/hypergraph-k-cut", "max_issues_repo_head_hexsha": "1134ca254fb709bce62a4506c931362d84a06894", "max_issues_repo_licenses": ["MIT"], "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/hypergraph/include/hypergraph/heap.hpp", "max_forks_repo_name": "vsui/hypergraph-k-cut", "max_forks_repo_head_hexsha": "1134ca254fb709bce62a4506c931362d84a06894", "max_forks_repo_licenses": ["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.8347826087, "max_line_length": 85, "alphanum_fraction": 0.6809155167, "num_tokens": 752, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5544704649604272, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.32861612524304856}}
{"text": "/*\nCopyright (c) 2015-2019, Florian Sittel (www.lettis.net) and Daniel Nagel\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n\n1. Redistributions of source code must retain the above copyright notice, this\nlist of conditions and the following disclaimer.\n\n2. Redistributions in binary form must reproduce the above copyright notice,\nthis list of conditions and the following disclaimer in the documentation\nand/or other materials provided with the distribution.\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#pragma once\n\n#include <vector>\n#include <map>\n#include <set>\n#include <stdexcept>\n#include <string>\n\n#include <boost/program_options.hpp>\n#include <boost/numeric/ublas/matrix_sparse.hpp>\n#include <boost/numeric/ublas/io.hpp>\n\n#include \"tools.hpp\"\n/*! \\file\n * \\brief Most Probable Path Clustering\n *\n * \\sa \\link Clustering::MPP\n */\n\nnamespace Clustering {\n  /*!\n   * \\brief functions related to \"Most Probable Path\"-clustering\n   *\n   * This module contains all function for dynamical clustering. In contrast to\n   * density-based clustering, can it only be applied to previously clustered\n   * trajectories. The idea is to create, based on a microstate input, a\n   * coarse-grained model (macrostates).\n   * The most probable path depends strongly on the selected timescale (mpp\n   * time). If the input was dynamically cored, the mpp time needs to be\n   * greater than the coring time.\n   */\n  namespace MPP {\n    //! BOOST implementation of a sparse matrix for floats\n    using SparseMatrixF = boost::numeric::ublas::mapped_matrix<float>;\n    //! Neighborhood per frame\n    using Neighborhood = Clustering::Tools::Neighborhood;\n    //! read (row-normalized) transition matrix from file\n    SparseMatrixF\n    read_transition_probabilities(std::string fname);\n    //! count transitions from one to the other cluster with certain lag\n    //! and return as count matrix (row/col := from/to)\n    SparseMatrixF\n    transition_counts(std::vector<std::size_t> trajectory\n                    , std::vector<std::size_t> concat_limits\n                    , std::size_t n_lag_steps\n                    , std::size_t i_max = 0);\n    //! same as 'transition_counts', but with reweighting account for\n    //! differently sized trajectory chunks (as given by concat_limits)\n    SparseMatrixF\n    weighted_transition_counts(std::vector<std::size_t> trajectory\n                             , std::vector<std::size_t> concat_limits\n                             , std::size_t n_lag_steps);\n    //! compute transition matrix from counts by normalization of rows\n    SparseMatrixF\n    row_normalized_transition_probabilities(SparseMatrixF count_matrix\n                                          , std::set<std::size_t> microstate_names);\n    //! update transition matrix after lumping states into sinks\n    SparseMatrixF\n    updated_transition_probabilities(SparseMatrixF transition_matrix\n                                   , std::map<std::size_t, std::size_t> sinks\n                                   , std::map<std::size_t, std::size_t> pops);\n    //! compute immediate future (i.e. without lag) of every state from highest probable transitions;\n    //! exclude self-transitions.\n    std::map<std::size_t, std::size_t>\n    single_step_future_state(SparseMatrixF transition_matrix,\n                             std::set<std::size_t> cluster_names,\n                             float q_min,\n                             std::map<std::size_t, float> min_free_energy);\n    //! for every state, compute most probable path by following\n    //! the 'future_state'-mapping recursively\n    std::map<std::size_t, std::vector<std::size_t>>\n    most_probable_path(std::map<std::size_t, std::size_t> future_state, std::set<std::size_t> cluster_names);\n    //! compute cluster populations\n    std::map<std::size_t, std::size_t>\n    microstate_populations(std::vector<std::size_t> clusters, std::set<std::size_t> cluster_names);\n    //! assign every state the lowest free energy value\n    //! of all of its frames.\n    std::map<std::size_t, float>\n    microstate_min_free_energy(const std::vector<std::size_t>& clustering,\n                               const std::vector<float>& free_energy);\n    //! compute path sinks, i.e. states of highest metastability,\n    //! and lowest free energy per path. these sinks will be states all other\n    //! states of the given path will be lumped into.\n    std::map<std::size_t, std::size_t>\n    path_sinks(std::vector<std::size_t> clusters,\n               std::map<std::size_t, std::vector<std::size_t>> mpp,\n               SparseMatrixF transition_matrix,\n               std::set<std::size_t> cluster_names,\n               float q_min,\n               std::vector<float> free_energy);\n    //! lump states based on path sinks and return new trajectory.\n    //! new microstates will have IDs of sinks.\n    std::vector<std::size_t>\n    lumped_trajectory(std::vector<std::size_t> trajectory,\n                      std::map<std::size_t, std::size_t> sinks);\n    //! run clustering for given Q_min value\n    std::tuple<std::vector<std::size_t>\n             , std::map<std::size_t, std::size_t>\n             , SparseMatrixF>\n    fixed_metastability_clustering(std::vector<std::size_t> initial_trajectory,\n                                   SparseMatrixF trans_prob,\n                                   float q_min,\n                                   std::vector<float> free_energy);\n    /*!\n     * \\brief MPP clustering control function and user interface\n     *\n     * \\param input input file with microstate trajectory\n     * \\param basename name format for output files\n     * \\param lagtime lag for transition estimation in units of frame numbers\n     * \\param qmin-from lower limit for metastability (Q_min)\n     * \\param qmin-to upper limit for metastability (Q_min)\n     * \\param qmin-step stepping for metastability (Q_min)\n     * \\param concat-nframes no. of frames per trajectory.\n     * \\param concat-limits length of concated trajectories.\n     * \\return void\n     * \\note Lagtime should be greater than the coring time/ smallest\n     *       timescale.\n     */\n    void\n    main(boost::program_options::variables_map args);\n  } // end namespace Clustering::MPP\n} // end namespace Clustering\n\n", "meta": {"hexsha": "10ca0719719320a885ef21ebd76e2f92979558ca", "size": 7045, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/mpp.hpp", "max_stars_repo_name": "gregorweiss/Clustering", "max_stars_repo_head_hexsha": "484eceff161adf972b068b02550d492af33535d5", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 9.0, "max_stars_repo_stars_event_min_datetime": "2019-09-30T15:52:05.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-23T07:18:49.000Z", "max_issues_repo_path": "src/mpp.hpp", "max_issues_repo_name": "gregorweiss/Clustering", "max_issues_repo_head_hexsha": "484eceff161adf972b068b02550d492af33535d5", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2019-05-16T11:13:20.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-11T17:22:23.000Z", "max_forks_repo_path": "src/mpp.hpp", "max_forks_repo_name": "gregorweiss/Clustering", "max_forks_repo_head_hexsha": "484eceff161adf972b068b02550d492af33535d5", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2019-11-21T12:15:03.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-19T10:45:20.000Z", "avg_line_length": 47.2818791946, "max_line_length": 109, "alphanum_fraction": 0.6809084457, "num_tokens": 1556, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7248702761768249, "lm_q2_score": 0.45326184801538616, "lm_q1q2_score": 0.328556040951331}}
{"text": "#include \"OT/Base/PvwBaseOT.h\"\n#include \"OT/Base/Math/DMC.h\"\n#include \"Crypto/PRNG.h\"\n#include \"Crypto/sha1.h\"\n#include \"Network/Channel.h\"\n#include \"cryptopp/osrng.h\"\n#include \"Common/Log.h\"\n\n#include <stdio.h>\n#include <iostream>\n#include <fstream>\n#include <thread>\n#include <mutex>\n\n//#include <boost/thread/tss.hpp>\n//void Cleanup_Miracl(Miracl* miracl)\n//{\n//\tif (miracl)\n//\t{\n//\t\tbOPRF::Log::out << \"deleting Miracle\" << bOPRF::Log::endl;\n//\t\tdelete miracl;\n//\t}\n//}\n\n\nusing namespace std;\nnamespace bOPRF {\n\n\tconst char* role_to_str(OTRole role)\n\t{\n\t\tif (role == Receiver)\n\t\t\treturn \"Receiver\";\n\t\tif (role == Sender)\n\t\t\treturn \"Sender\";\n\t\treturn \"Both\";\n\t}\n\n\tOTRole INV_ROLE(OTRole role)\n\t{\n\t\tif (role == Receiver)\n\t\t\treturn Sender;\n\t\tif (role == Sender)\n\t\t\treturn Receiver;\n\t\telse\n\t\t\treturn Both;\n\t}\n\n\tvoid send_if_ot_sender(Channel& channel, vector<ByteStream>& os, OTRole role)\n\t{\n\n\t\tif (role == Sender)\n\t\t{ \n\t\t\tchannel.asyncSendCopy(os[0].data(), os[0].size());\n\t\t\t//os[0].Send(channel);\n\t\t}\n\t\telse if (role == Receiver)\n\t\t{ \n\n\t\t\tchannel.recv(os[1]);\n\t\t\t//os[1].setp(0);\n\t\t\t//os[1].Receive(channel);\n\t\t}\n\t\telse\n\t\t{ \n\t\t\t// both sender + receiver\n\n\t\t\tchannel.asyncSendCopy(os[0]);\n\t\t\tchannel.recv(os[1]);\n\t\t\t//os[0].Send(channel);\n\t\t\t//os[1].setp(0);\n\t\t\t//os[1].Receive(channel);\n\t\t\t//P->send_receive_player(os);\n\t\t}\n\t}\n\n\tvoid send_if_ot_receiver(Channel& channel, vector<ByteStream>& os, OTRole role)\n\t{\n\t\tif (role == Receiver)\n\t\t{ \n\t\t\tchannel.asyncSendCopy(os[0]);\n\t\t}\n\t\telse if (role == Sender)\n\t\t{ \n\t\t\tchannel.recv(os[1]);\n\t\t\t//P->receive(os[1]);\n\t\t}\n\t\telse\n\t\t{ \n\t\t\t// both\n\t\t\tchannel.asyncSendCopy(os[0]);\n\t\t\tchannel.recv(os[1]);\n\t\t\t//P->send_receive_player(os);\n\t\t}\n\t}\n\n\n\t/*\n\t * pack/unpack routines for Miracl data types\n\t */\n\n\tvoid pack(ByteStream& s, const Big& z)\n\t{\n\t\tu8 data[50];\n\t\ti32 len = to_binary(z, 50, (char*)data, false);\n\t\ts.append((u8*)&len, sizeof(u32));\n\t\ts.append(data, len);\n\t}\n\n\n\tvoid unpack(Big& z, ByteStream& s)\n\t{\n\t\tu8 data[50];\n\t\ti32 len;\n\t\ts.consume((u8*)&len, sizeof(i32));\n\t\ts.consume(data, len);\n\t\tz = from_binary(len, (char*)data);\n\t}\n\n\n\tvoid pack(ByteStream& s, const ECn& P)\n\t{\n\t\tBig x, y;\n\t\tP.get(x, y);\n\t\tpack(s, x);\n\t\tpack(s, y);\n\t}\n\n\n\tvoid unpack(ECn& P, ByteStream& s)\n\t{\n\t\tBig x, y;\n\t\tunpack(x, s);\n\t\tunpack(y, s);\n\t\tP = ECn(x, y);\n\t}\n\n\t//#define BASEOT_DEBUG\n\n\t\t// Run the PVW OTs\n\tvoid Exec_OT(vector< vector<ECn> >& Miracl_Sender_Inputs,\n\t\tBitVector& OT_Receiver_Inputs,\n\t\tvector<ECn>& Miracl_Receiver_Outputs,\n\t\tconst CRS& crs,\n\t\tcsprng& Miracl_RNG,\n\t\tPRNG& G,\n\t\tChannel& channel,\n\t\tOTRole role)\n\t{\n\t\tu64 n = OT_Receiver_Inputs.size();\n\t\t//Log::out << Log::PvwBaseOT << \"Starting base OTs as \" << role_to_str(role) << \", n = \" << n << Log::endl;\n\t\tvector<ByteStream> strm(2);\n\n\t\tBig z;\n\t\tvector<SK> sk(n);\n\t\tPK pk;\n\t\tif (role & Receiver)\n\t\t{\n\t\t\t// Generate my receiver inputs \n\t\t\tOT_Receiver_Inputs.randomize(G);\n\t\t\tfor (u64 i = 0; i < n; i++)\n\t\t\t{\n\t\t\t\t// Generate public keys on my branch\n\t\t\t\tKeyGen(sk[i], pk, OT_Receiver_Inputs[i], crs, Miracl_RNG);\n\n\t\t\t\tpack(strm[0], pk.g);\n\t\t\t\tpack(strm[0], pk.h);\n\t\t\t}\n\t\t}\n\t\tstrm[1].setp(0);\n\n\t\t// Send receiver's public keys over\n\t\tsend_if_ot_receiver(channel, strm, role);\n\n\t\tECn c0, c1;\n\n\t\tif (role & Sender)\n\t\t{\n\t\t\tstrm[0].setp(0);\n\t\t\tfor (u64 i = 0; i < n; i++)\n\t\t\t{\n\t\t\t\t// Generate sender inputs\n\t\t\t\tz = strong_rand(&Miracl_RNG, crs.bit_size(), 2);\n\t\t\t\tMiracl_Sender_Inputs[i][0] = z*crs.get_g(0);\n\t\t\t\tz = strong_rand(&Miracl_RNG, crs.bit_size(), 2);\n\t\t\t\tMiracl_Sender_Inputs[i][1] = z*crs.get_g(0);\n\n\t\t\t\t// Unpack public keys, encrypt my two messages on the correct\n\t\t\t\t// branch and send them back\n\t\t\t\tunpack(pk.g, strm[1]);\n\t\t\t\tunpack(pk.h, strm[1]);\n\n\t\t\t\tpk.Encrypt(c0, c1, Miracl_Sender_Inputs[i][0], 0, crs, Miracl_RNG);\n\t\t\t\tpack(strm[0], c0);\n\t\t\t\tpack(strm[0], c1);\n#ifdef BASEOT_DEBUG\n\t\t\t\t//Log::out << \"m[\" << i << \", 0] = \" << Miracl_Sender_Inputs[i][0] << Log::endl;\n\t\t\t\tpack(strm[0], Miracl_Sender_Inputs[i][0]);\n#endif\n\t\t\t\tpk.Encrypt(c0, c1, Miracl_Sender_Inputs[i][1], 1, crs, Miracl_RNG);\n\t\t\t\tpack(strm[0], c0);\n\t\t\t\tpack(strm[0], c1);\n#ifdef BASEOT_DEBUG\n\t\t\t\t//Log::out << \"m[\" << i << \", 1] = \" << Miracl_Sender_Inputs[i][1] << Log::endl;\n\t\t\t\tpack(strm[0], Miracl_Sender_Inputs[i][1]);\n#endif\n\t\t\t}\n\t\t}\n\n\t\t// Sender sends ciphertexts over\n\t\tstrm[1].setp(0);\n\t\tsend_if_ot_sender(channel, strm, role); \n\n#ifdef BASEOT_DEBUG\n\t\tECn m0, m1;\n#endif\n\n\t\tif (role & Receiver)\n\t\t{\n\t\t\t// Now unpack the received ciphertexts, decrypt the one we want\n\t\t\t// and store it\n\t\t\tfor (u64 i = 0; i < n; i++)\n\t\t\t{\n\t\t\t\tunpack(c0, strm[1]);\n\t\t\t\tunpack(c1, strm[1]);\n#ifdef BASEOT_DEBUG\n\t\t\t\tunpack(m0, strm[1]);\n#endif\n\t\t\t\tif (OT_Receiver_Inputs[i] == 0)\n\t\t\t\t{\n\t\t\t\t\tsk[i].Decrypt(Miracl_Receiver_Outputs[i], c0, c1);\n#ifdef BASEOT_DEBUG\n\t\t\t\t\tif (Miracl_Receiver_Outputs[i] != m0)\n\t\t\t\t\t{\n\t\t\t\t\t\tLog::out << \"Bad PvwBaseOT message received\" << Log::endl;\n\t\t\t\t\t\tLog::out << \"Received   \" << Miracl_Receiver_Outputs[i] << Log::endl;\n\t\t\t\t\t\tLog::out << \"wanted m0  \" << m0 << Log::endl;\n\t\t\t\t\t\tthrow std::runtime_error(\"rt error at \" LOCATION);\n\t\t\t\t\t}\n#endif\n\t\t\t\t}\n\t\t\t\tunpack(c0, strm[1]);\n\t\t\t\tunpack(c1, strm[1]);\n#ifdef BASEOT_DEBUG\n\t\t\t\tunpack(m1, strm[1]);\n#endif\n\t\t\t\tif (OT_Receiver_Inputs[i] == 1)\n\t\t\t\t{\n\t\t\t\t\tsk[i].Decrypt(Miracl_Receiver_Outputs[i], c0, c1);\n#ifdef BASEOT_DEBUG\n\t\t\t\t\tif (Miracl_Receiver_Outputs[i] != m1)\n\t\t\t\t\t{\n\t\t\t\t\t\tLog::out << \"Bad PvwBaseOT message \" << i << \" received\" << Log::endl;\n\t\t\t\t\t\tLog::out << \"Received   \" << Miracl_Receiver_Outputs[i] << Log::endl;\n\t\t\t\t\t\tLog::out << \"wanted m1  \" << m1 << Log::endl;\n\t\t\t\t\t\tthrow std::runtime_error(\"rt error at \" LOCATION);\n\t\t\t\t\t}\n#endif\n\t\t\t\t}\n\n\n\n\n\t\t\t\t//Log::out << Log::PvwBaseOT << \"m\"<< OT_Receiver_Inputs.get_bit(i) <<\"[\" << i << \"] = \" << Miracl_Receiver_Outputs[i] << Log::endl;\n\n\t\t\t}\n\t\t}\n\t\t//Log::out << Log::PvwBaseOT << \"Exit base OT\" << Log::endl;\n\t}\n\n\n\tvoid PvwBaseOT::exec_base(PRNG& G)\n\t{\n\t\t// Set up crs \n\t  CRS crs(&(*GetPrecision()));\n\t\t//Log::out << \"check 0\" << Log::endl;\n\n\t\t// Initialize a secure random number generator for Miracl\n\t\tcsprng Miracl_RNG;\n\t\tu8 data[100];\n\t\t//Log::out << \"check 1\" << Log::endl;\n\t\tG.get_u8s(data, 100);\n\t\t//CryptoPP::OS_GenerateRandomBlock(false, data, sizeof(u8) * 100);\n \n\t\tstrong_init(&Miracl_RNG, 100, (char*)data, 0L);\n\t\t///Log::out << \"check 2\" << Log::endl;\n\n\t\tvector< vector<ECn> > Miracl_Sender_Inputs(nOT, vector<ECn>(2));\n\t\tvector<ECn>           Miracl_Receiver_Outputs(nOT);\n\n\t\tExec_OT(Miracl_Sender_Inputs, receiver_inputs, Miracl_Receiver_Outputs, crs, Miracl_RNG, G, mChannel, mOTRole);\n\n\t\tByteStream s;\n\t\tu8 buff[SHA1::HashSize];\n\t\t//CBC_MAC cbc;\n\t\tSHA1 sha;\n\t\t// Hash PVW output into byte strings\n\t\tfor (int i = 0; i < nOT; i++)\n\t\t{\n\t\t\tif (mOTRole & Sender)\n\t\t\t{\n\t\t\t\ts.setp(0);\n\t\t\t\tpack(s, Miracl_Sender_Inputs[i][0]);\n\n\t\t\t\tsha.Reset();\n\t\t\t\tsha.Update(s.data(), s.size());\n\t\t\t\tsha.Final(buff);\n\t\t\t\tsender_inputs[i][0] = *(block*)buff;\n\n\t\t\t\t//cbc.zero_key();\n\t\t\t\t//cbc.Update(s);\n\t\t\t\t//cbc.Finalize(sender_inputs[i][0]);\n#ifdef BASEOT_DEBUG\n\t\t\t\ts.setp(0);\n\t\t\t\tpack(s, Miracl_Sender_Inputs[i][0]);\n\t\t\t\tLog::out << Log::PvwBaseOT << \"m[\" << i << \", 0] s = \" << s << Log::endl;\n\t\t\t\tmChannel.Send(s);\n\t\t\t\ts.setp(0);\n\t\t\t\ts.append(sender_inputs[i][0]);\n\t\t\t\tmChannel.AsyncSendCopy(s);\n\t\t\t\tLog::out << Log::PvwBaseOT << \"m[\" << i << \", 0]   = \" << sender_inputs[i][0] << Log::endl;\n#endif\n\t\t\t\ts.setp(0);\n\t\t\t\tpack(s, Miracl_Sender_Inputs[i][1]);\n\t\t\t\tsha.Reset();\n\t\t\t\tsha.Update(s.data(), s.size());\n\t\t\t\tsha.Final(buff);\n\n\t\t\t\t//cbc.zero_key();\n\t\t\t\t//cbc.Update(s); \n\t\t\t\t//cbc.Finalize(sender_inputs[i][1]);\n\t\t\t\tsender_inputs[i][1] = *(block*)buff;\n#ifdef BASEOT_DEBUG\n\t\t\t\ts.setp(0);\n\t\t\t\tpack(s, Miracl_Sender_Inputs[i][1]);\n\t\t\t\tmChannel.Send(s);\n\t\t\t\tLog::out << Log::PvwBaseOT << \"m[\" << i << \", 1] s = \" << s << Log::endl;\n\n\t\t\t\ts.setp(0);\n\t\t\t\ts.append(sender_inputs[i][1]);\n\t\t\t\tmChannel.AsyncSendCopy(s);\n\t\t\t\tLog::out << Log::PvwBaseOT << \"m[\" << i << \", 1]   = \" << sender_inputs[i][1] << Log::endl;\n#endif\n\t\t\t}\n\t\t\tif (mOTRole & Receiver)\n\t\t\t{\n\t\t\t\ts.setp(0);\n\t\t\t\tpack(s, Miracl_Receiver_Outputs[i]);\n\t\t\t\tsha.Reset();\n\t\t\t\tsha.Update(s.data(), s.size());\n\t\t\t\tsha.Final(buff);\n\n\t\t\t\treceiver_outputs[i] = *(block*)buff;\n\n\t\t\t\t//cbc.zero_key();\n\t\t\t\t//cbc.Update(s);\n\t\t\t\t//cbc.Finalize(receiver_outputs[i]);\n\n#ifdef BASEOT_DEBUG\n\t\t\t\tLog::out << Log::PvwBaseOT << \"s \" << s << Log::endl;\n\t\t\t\tECn ecm0, ecm1;\n\t\t\t\tblock m0, m1;\n\n\t\t\t\ts.setp(0);\n\t\t\t\tmChannel.recv(s);\n\t\t\t\tunpack(ecm0, s);\n\t\t\t\ts.setp(0);\n\t\t\t\tmChannel.recv(s);\n\t\t\t\ts.consume(m0);\n\n\t\t\t\ts.setp(0);\n\t\t\t\tmChannel.recv(s);\n\t\t\t\tunpack(ecm1, s);\n\t\t\t\ts.setp(0);\n\t\t\t\tmChannel.recv(s);\n\t\t\t\ts.consume(m1);\n\n\t\t\t\tif (receiver_inputs[i])\n\t\t\t\t{\n\t\t\t\t\tif (Miracl_Receiver_Outputs[i] != ecm1)\n\t\t\t\t\t{\n\t\t\t\t\t\tLog::out << \"Bad PvwBaseOT Miracl message \" << i << \" received\" << Log::endl;\n\t\t\t\t\t\tLog::out << \"Received   \" << Miracl_Receiver_Outputs[i] << Log::endl;\n\t\t\t\t\t\tLog::out << \"wanted m1  \" << ecm1 << Log::endl;\n\t\t\t\t\t\tthrow std::runtime_error(\"rt error at \" LOCATION);\n\t\t\t\t\t}\n\n\t\t\t\t\tif (receiver_outputs[i] != m1)\n\t\t\t\t\t{\n\t\t\t\t\t\tLog::out << \"Bad PvwBaseOT message \" << i << \" received\" << Log::endl;\n\t\t\t\t\t\tLog::out << \"Received   \" << receiver_outputs[i] << Log::endl;\n\t\t\t\t\t\tLog::out << \"wanted m1  \" << m1 << Log::endl;\n\t\t\t\t\t\tthrow std::runtime_error(\"rt error at \" LOCATION);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\n\t\t\t\t\tif (Miracl_Receiver_Outputs[i] != ecm0)\n\t\t\t\t\t{\n\t\t\t\t\t\tLog::out << \"Bad PvwBaseOT Miracl message \" << i << \" received\" << Log::endl;\n\t\t\t\t\t\tLog::out << \"Received   \" << Miracl_Receiver_Outputs[i] << Log::endl;\n\t\t\t\t\t\tLog::out << \"wanted m0  \" << ecm0 << Log::endl;\n\t\t\t\t\t\tthrow std::runtime_error(\"rt error at \" LOCATION);\n\t\t\t\t\t}\n\n\t\t\t\t\tif (receiver_outputs[i] != m0)\n\t\t\t\t\t{\n\t\t\t\t\t\tLog::out << \"Bad PvwBaseOT message \" << i << \" received\" << Log::endl;\n\t\t\t\t\t\tLog::out << \"Received   \" << receiver_outputs[i] << Log::endl;\n\t\t\t\t\t\tLog::out << \"wanted m0  \" << m0 << Log::endl;\n\t\t\t\t\t\tthrow std::runtime_error(\"rt error at \" LOCATION);\n\t\t\t\t\t}\n\t\t\t\t}\n#endif\n\t\t\t}\n\n\t\t}\n\t\tdeletePercision();\n\t\t//delete GetPrecision();\n\t\t//Log::out << \"base ots done\" << Log::endl;\n\t}\n\n\tvoid PvwBaseOT::check()\n\t{\n\t\tByteStream os;\n\t\tblock tmp;\n\n\t\tfor (int i = 0; i < nOT; i++)\n\t\t{\n\t\t\tif (mOTRole & Sender)\n\t\t\t{\n\t\t\t\t// send both inputs over\n\t\t\t\tos.append(sender_inputs[i][0]);\n\t\t\t\tos.append(sender_inputs[i][1]);\n\n\t\t\t\tif (eq(sender_inputs[i][0], sender_inputs[i][1]))\n\t\t\t\t\tthrow std::runtime_error(\"rt error at \" LOCATION);\n\n\n\t\t\t\tmChannel.asyncSendCopy(os);\n\t\t\t}\n\n\t\t\tif (mOTRole & Receiver)\n\t\t\t{\n\t\t\t\tmChannel.recv(os);\n\n\t\t\t\tos.consume((u8*)&tmp, sizeof(block));\n\n\t\t\t\tif (receiver_inputs[i] == 1)\n\t\t\t\t{\n\t\t\t\t\tos.consume((u8*)&tmp, sizeof(block));\n\t\t\t\t}\n\n\t\t\t\tif (neq(tmp, receiver_outputs[i]))\n\t\t\t\t{\n\t\t\t\t\tLog::out << \"Base Incorrect OT\" << Log::endl;\n\t\t\t\t\tLog::out << \"I        have \" << receiver_outputs[i] << Log::endl;\n\t\t\t\t\tLog::out << \"but they have \" << tmp << Log::endl;\n\n\t\t\t\t\tthrow std::runtime_error(\"Exit\");;\n\t\t\t\t}\n\t\t\t}\n\t\t\tos.setp(0);\n\t\t}\n\t}\n\n}\n", "meta": {"hexsha": "4c7bee8736e4ad7a679bd0819d7b43b88a3d42a1", "size": 10881, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "bOPRFlib/OT/Base/PvwBaseOT.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/OT/Base/PvwBaseOT.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/OT/Base/PvwBaseOT.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.25, "max_line_length": 136, "alphanum_fraction": 0.5796342248, "num_tokens": 3796, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.72487026428967, "lm_q2_score": 0.4532618480153861, "lm_q1q2_score": 0.3285560355633372}}
{"text": "//---------------------------------------------------------------------------//\n//!\n//! \\file   MonteCarlo_WHIncoherentPhotonScatteringDistribution.cpp\n//! \\author Alex Robinson\n//! \\brief  The Waller-Hartree incoherent photon scattering distribution def.\n//!\n//---------------------------------------------------------------------------//\n\n// Boost Includes\n#include <boost/function.hpp>\n#include <boost/bind.hpp>\n\n// FRENSIE Includes\n#include \"MonteCarlo_WHIncoherentPhotonScatteringDistribution.hpp\"\n#include \"MonteCarlo_PhotonKinematicsHelpers.hpp\"\n#include \"Utility_PhysicalConstants.hpp\"\n#include \"Utility_GaussKronrodIntegrator.hpp\"\n#include \"Utility_DesignByContract.hpp\"\n\nnamespace MonteCarlo{\n\n// Constructor\nWHIncoherentPhotonScatteringDistribution::WHIncoherentPhotonScatteringDistribution(\n\t  const std::shared_ptr<const ScatteringFunction>& scattering_function,\n\t  const double kahn_sampling_cutoff_energy )\n  : IncoherentPhotonScatteringDistribution( kahn_sampling_cutoff_energy ),\n    d_scattering_function( scattering_function )\n{\n  // Make sure the scattering function is valid\n  testPrecondition( scattering_function.get() );\n}\n\n// Evaluate the distribution\ndouble WHIncoherentPhotonScatteringDistribution::evaluate(\n\t\t\t\t   const double incoming_energy,\n\t\t\t\t   const double scattering_angle_cosine ) const\n{\n  // Make sure the incoming energy is valid\n  testPrecondition( incoming_energy > 0.0 );\n  // Make sure the scattering angle cosine is valid\n  testPrecondition( scattering_angle_cosine >= -1.0 );\n  testPrecondition( scattering_angle_cosine <= 1.0 );\n\n  const double scattering_function_value =\n    this->evaluateScatteringFunction( incoming_energy,\n\t\t\t\t      scattering_angle_cosine );\n\n  const double diff_kn_cross_section =\n    this->evaluateKleinNishinaDist( incoming_energy,\n\t\t\t\t    scattering_angle_cosine );\n\n  return diff_kn_cross_section*scattering_function_value;\n}\n\n// Evaluate the integrated cross section (b)\ndouble WHIncoherentPhotonScatteringDistribution::evaluateIntegratedCrossSection(\n\t\t\t\t\t\t  const double incoming_energy,\n\t\t\t\t\t\t  const double precision) const\n{\n  // Make sure the incoming energy is valid\n  testPrecondition( incoming_energy > 0.0 );\n\n  // Evaluate the integrated cross section\n  boost::function<double (double x)> diff_cs_wrapper =\n    boost::bind<double>( &WHIncoherentPhotonScatteringDistribution::evaluate,\n\t\t\t boost::cref( *this ),\n\t\t\t incoming_energy,\n\t\t\t _1 );\n\n  double abs_error, integrated_cs;\n\n  Utility::GaussKronrodIntegrator<double> quadrature_gkq_set( precision );\n\n  quadrature_gkq_set.integrateAdaptively<15>( diff_cs_wrapper,\n\t\t\t\t\t     -1.0,\n\t\t\t\t\t     1.0,\n\t\t\t\t\t     integrated_cs,\n\t\t\t\t\t     abs_error );\n\n  // Make sure the integrated cross section is valid\n  testPostcondition( integrated_cs > 0.0 );\n\n  return integrated_cs;\n}\n\n// Sample an outgoing energy and direction from the distribution\n/*! \\details This function will only sample a Compton line energy (no\n * Doppler broadening).\n */\nvoid WHIncoherentPhotonScatteringDistribution::sample(\n\t\t\t\t     const double incoming_energy,\n\t\t\t\t     double& outgoing_energy,\n\t\t\t\t     double& scattering_angle_cosine ) const\n{\n  // Make sure the incoming energy is valid\n  testPrecondition( incoming_energy > 0.0 );\n\n  Counter trial_dummy;\n\n  return this->sampleAndRecordTrials( incoming_energy,\n\t\t\t\t      outgoing_energy,\n\t\t\t\t      scattering_angle_cosine,\n\t\t\t\t      trial_dummy );\n}\n\n// Sample an outgoing energy and direction and record the number of trials\n/*! \\details This function will only sample a Compton line energy (no\n * Doppler broadening).\n */\nvoid WHIncoherentPhotonScatteringDistribution::sampleAndRecordTrials(\n\t\t\t\t\t    const double incoming_energy,\n\t\t\t\t\t    double& outgoing_energy,\n\t\t\t\t\t    double& scattering_angle_cosine,\n\t\t\t\t\t    Counter& trials ) const\n{\n  // Make sure the incoming energy is valid\n  testPrecondition( incoming_energy > 0.0 );\n\n  // Evaluate the maximum scattering function value\n  const double max_scattering_function_value =\n    this->evaluateScatteringFunction( incoming_energy, -1.0 );\n\n  while( true )\n  {\n    this->sampleAndRecordTrialsKleinNishina( incoming_energy,\n\t\t\t\t\t     outgoing_energy,\n\t\t\t\t\t     scattering_angle_cosine,\n\t\t\t\t\t     trials );\n\n    const double scattering_function_value =\n      this->evaluateScatteringFunction( incoming_energy,\n\t\t\t\t\tscattering_angle_cosine );\n\n    const double scaled_random_number = max_scattering_function_value*\n      Utility::RandomNumberGenerator::getRandomNumber<double>();\n\n    if( scaled_random_number <= scattering_function_value )\n      break;\n  }\n\n  // Make sure the scattering angle cosine is valid\n  testPostcondition( scattering_angle_cosine >= -1.0 );\n  testPostcondition( scattering_angle_cosine <= 1.0 );\n  // Make sure the compton line energy is valid\n  testPostcondition( outgoing_energy <= incoming_energy );\n}\n\n} // end MonteCarlo namespace\n\n//---------------------------------------------------------------------------//\n// end MonteCarlo_WHIncoherentPhotonScatteringDistribution.cpp\n//---------------------------------------------------------------------------//\n", "meta": {"hexsha": "88029afcd3d9e910265e2bdcc542b71db8881f2a", "size": 5100, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "packages/monte_carlo/collision/photon/src/MonteCarlo_WHIncoherentPhotonScatteringDistribution.cpp", "max_stars_repo_name": "bam241/FRENSIE", "max_stars_repo_head_hexsha": "e1760cd792928699c84f2bdce70ff54228e88094", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2019-11-14T19:58:30.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-04T17:44:09.000Z", "max_issues_repo_path": "packages/monte_carlo/collision/photon/src/MonteCarlo_WHIncoherentPhotonScatteringDistribution.cpp", "max_issues_repo_name": "bam241/FRENSIE", "max_issues_repo_head_hexsha": "e1760cd792928699c84f2bdce70ff54228e88094", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 43.0, "max_issues_repo_issues_event_min_datetime": "2020-03-03T19:59:20.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-08T03:36:08.000Z", "max_forks_repo_path": "packages/monte_carlo/collision/photon/src/MonteCarlo_WHIncoherentPhotonScatteringDistribution.cpp", "max_forks_repo_name": "bam241/FRENSIE", "max_forks_repo_head_hexsha": "e1760cd792928699c84f2bdce70ff54228e88094", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2020-02-12T17:37:07.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-08T18:59:51.000Z", "avg_line_length": 33.3333333333, "max_line_length": 83, "alphanum_fraction": 0.7084313725, "num_tokens": 1066, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7310585786300049, "lm_q2_score": 0.44939263446475963, "lm_q1q2_score": 0.32853234059860054}}
{"text": "#ifndef STAN_MATH_PRIM_SCAL_PROB_BINOMIAL_LOGIT_LPMF_HPP\n#define STAN_MATH_PRIM_SCAL_PROB_BINOMIAL_LOGIT_LPMF_HPP\n\n#include <stan/math/prim/scal/meta/is_constant_struct.hpp>\n#include <stan/math/prim/scal/meta/partials_return_type.hpp>\n#include <stan/math/prim/scal/meta/operands_and_partials.hpp>\n#include <stan/math/prim/scal/err/check_consistent_sizes.hpp>\n#include <stan/math/prim/scal/err/check_bounded.hpp>\n#include <stan/math/prim/scal/err/check_finite.hpp>\n#include <stan/math/prim/scal/err/check_greater_or_equal.hpp>\n#include <stan/math/prim/scal/err/check_less_or_equal.hpp>\n#include <stan/math/prim/scal/err/check_nonnegative.hpp>\n#include <stan/math/prim/scal/fun/size_zero.hpp>\n#include <stan/math/prim/scal/fun/constants.hpp>\n#include <stan/math/prim/scal/fun/inv_logit.hpp>\n#include <stan/math/prim/scal/fun/log1m.hpp>\n#include <stan/math/prim/scal/fun/log_inv_logit.hpp>\n#include <stan/math/prim/scal/fun/multiply_log.hpp>\n#include <stan/math/prim/scal/fun/value_of.hpp>\n#include <stan/math/prim/scal/fun/binomial_coefficient_log.hpp>\n#include <stan/math/prim/scal/fun/lbeta.hpp>\n#include <stan/math/prim/scal/meta/VectorBuilder.hpp>\n#include <stan/math/prim/scal/meta/include_summand.hpp>\n#include <stan/math/prim/scal/meta/scalar_seq_view.hpp>\n#include <stan/math/prim/scal/fun/inc_beta.hpp>\n#include <boost/random/binomial_distribution.hpp>\n#include <boost/random/variate_generator.hpp>\n\nnamespace stan {\nnamespace math {\n\n/**\n * Binomial log PMF in logit parametrization. Binomial(n|n, inv_logit(alpha))\n *\n * If given vectors of matching lengths, returns\n * the log sum of probabilities.\n *\n * @param n successes variable\n * @param N population size parameter\n * @param alpha logit transformed probability parameter\n *\n * @return log probability or log sum of probabilities\n *\n * @throw std::domain_error if N is negative or probability parameter is invalid\n * @throw std::invalid_argument if vector sizes do not match\n */\ntemplate <bool propto, typename T_n, typename T_N, typename T_prob>\ntypename return_type<T_prob>::type binomial_logit_lpmf(const T_n& n,\n                                                       const T_N& N,\n                                                       const T_prob& alpha) {\n  typedef typename stan::partials_return_type<T_n, T_N, T_prob>::type\n      T_partials_return;\n\n  static const char* function = \"binomial_logit_lpmf\";\n\n  if (size_zero(n, N, alpha))\n    return 0.0;\n\n  T_partials_return logp = 0;\n  check_bounded(function, \"Successes variable\", n, 0, N);\n  check_nonnegative(function, \"Population size parameter\", N);\n  check_finite(function, \"Probability parameter\", alpha);\n  check_consistent_sizes(function, \"Successes variable\", n,\n                         \"Population size parameter\", N,\n                         \"Probability parameter\", alpha);\n\n  if (!include_summand<propto, T_prob>::value)\n    return 0.0;\n\n  scalar_seq_view<T_n> n_vec(n);\n  scalar_seq_view<T_N> N_vec(N);\n  scalar_seq_view<T_prob> alpha_vec(alpha);\n  size_t size = max_size(n, N, alpha);\n\n  operands_and_partials<T_prob> ops_partials(alpha);\n\n  if (include_summand<propto>::value) {\n    for (size_t i = 0; i < size; ++i)\n      logp += binomial_coefficient_log(N_vec[i], n_vec[i]);\n  }\n\n  VectorBuilder<true, T_partials_return, T_prob> log_inv_logit_alpha(\n      length(alpha));\n  for (size_t i = 0; i < length(alpha); ++i)\n    log_inv_logit_alpha[i] = log_inv_logit(value_of(alpha_vec[i]));\n\n  VectorBuilder<true, T_partials_return, T_prob> log_inv_logit_neg_alpha(\n      length(alpha));\n  for (size_t i = 0; i < length(alpha); ++i)\n    log_inv_logit_neg_alpha[i] = log_inv_logit(-value_of(alpha_vec[i]));\n\n  for (size_t i = 0; i < size; ++i)\n    logp += n_vec[i] * log_inv_logit_alpha[i]\n            + (N_vec[i] - n_vec[i]) * log_inv_logit_neg_alpha[i];\n\n  if (length(alpha) == 1) {\n    T_partials_return temp1 = 0;\n    T_partials_return temp2 = 0;\n    for (size_t i = 0; i < size; ++i) {\n      temp1 += n_vec[i];\n      temp2 += N_vec[i] - n_vec[i];\n    }\n    if (!is_constant_struct<T_prob>::value) {\n      ops_partials.edge1_.partials_[0]\n          += temp1 * inv_logit(-value_of(alpha_vec[0]))\n             - temp2 * inv_logit(value_of(alpha_vec[0]));\n    }\n  } else {\n    if (!is_constant_struct<T_prob>::value) {\n      for (size_t i = 0; i < size; ++i)\n        ops_partials.edge1_.partials_[i]\n            += n_vec[i] * inv_logit(-value_of(alpha_vec[i]))\n               - (N_vec[i] - n_vec[i]) * inv_logit(value_of(alpha_vec[i]));\n    }\n  }\n\n  return ops_partials.build(logp);\n}\n\ntemplate <typename T_n, typename T_N, typename T_prob>\ninline typename return_type<T_prob>::type binomial_logit_lpmf(\n    const T_n& n, const T_N& N, const T_prob& alpha) {\n  return binomial_logit_lpmf<false>(n, N, alpha);\n}\n\n}  // namespace math\n}  // namespace stan\n#endif\n", "meta": {"hexsha": "d4cf50ba4b8120f7c266902a6c17d02293c150ea", "size": 4798, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "stan/math/prim/scal/prob/binomial_logit_lpmf.hpp", "max_stars_repo_name": "jrmie/math", "max_stars_repo_head_hexsha": "2850ec262181075a5843968e805dc9ad1654e069", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "stan/math/prim/scal/prob/binomial_logit_lpmf.hpp", "max_issues_repo_name": "jrmie/math", "max_issues_repo_head_hexsha": "2850ec262181075a5843968e805dc9ad1654e069", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "stan/math/prim/scal/prob/binomial_logit_lpmf.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": 37.1937984496, "max_line_length": 80, "alphanum_fraction": 0.6957065444, "num_tokens": 1322, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6893056295505782, "lm_q2_score": 0.47657965106367595, "lm_q1q2_score": 0.328509036407442}}
{"text": "/******************************************************************************\n*       SOFA, Simulation Open-Framework Architecture, development version     *\n*                (c) 2006-2017 INRIA, USTL, UJF, CNRS, MGH                    *\n*                                                                             *\n* This program is free software; you can redistribute it and/or modify it     *\n* 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 (at     *\n* your option) 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 Lesser General Public License *\n* for more details.                                                           *\n*                                                                             *\n* You should have received a copy of the GNU Lesser General Public License    *\n* along with this program. If not, see <http://www.gnu.org/licenses/>.        *\n*******************************************************************************\n* Authors: The SOFA Team and external contributors (see Authors.txt)          *\n*                                                                             *\n* Contact information: contact@sofa-framework.org                             *\n******************************************************************************/\n\n#include <SofaConstraint/LMConstraintDirectSolver.h>\n#include <sofa/core/visual/VisualParams.h>\n#include <SofaConstraint/ContactDescription.h>\n#include <sofa/core/ObjectFactory.h>\n#include <Eigen/QR>\n#include <Eigen/SVD>\n\n\nnamespace sofa\n{\n\nnamespace component\n{\n\nnamespace constraintset\n{\n\nLMConstraintDirectSolver::LMConstraintDirectSolver()\n    : solverAlgorithm(initData(&solverAlgorithm, \"solverAlgorithm\", \"Algorithm used to solve the system W.Lambda=c\"))\n{\n    //Add here other algo\n    sofa::helper::OptionsGroup algo(1,\"SVD\");\n    solverAlgorithm.setValue(algo);\n}\n\n\nbool LMConstraintDirectSolver::buildSystem(const core::ConstraintParams* cParams, MultiVecId res1, MultiVecId res2)\n{\n    bool sucess = LMConstraintSolver::buildSystem(cParams, res1, res2);\n\n    return sucess;\n}\n\nbool LMConstraintDirectSolver::solveSystem(const core::ConstraintParams* cParams, MultiVecId res1, MultiVecId res2)\n{\n    //First, do n iterations of Gauss Seidel\n    bool success = LMConstraintSolver::solveSystem(cParams, res1, res2);\n\n\n    if (cParams->constOrder() != core::ConstraintParams::VEL) return success;\n\n\n    //Then process to a direct solution of the system\n\n    //We need to find all the constraint related to contact\n    // 1. extract the information about the state of the contact and build the new L, L^T matrices\n    // 2. build the full system\n    // 3. solve\n\n\n    //------------------------------------------------------------------\n    // extract the information about the state of the contact\n    //------------------------------------------------------------------\n\n    //************************************************************\n#ifdef SOFA_DUMP_VISITOR_INFO\n    sofa::simulation::Visitor::printNode(\"AnalyseConstraints\");\n#endif\n    const helper::vector< sofa::core::behavior::BaseLMConstraint* > &LMConstraints=LMConstraintVisitor.getConstraints();\n\n    JacobianRows rowsL ; rowsL.reserve(numConstraint);\n    JacobianRows rowsLT; rowsLT.reserve(numConstraint);\n    helper::vector< unsigned int > rightHandElements;\n\n    analyseConstraints(LMConstraints, cParams->constOrder(),\n            rowsL, rowsLT, rightHandElements);\n\n#ifdef SOFA_DUMP_VISITOR_INFO\n    sofa::simulation::Visitor::printCloseNode(\"AnalyseConstraints\");\n#endif\n    if (rowsL.empty() || rowsLT.empty()) return success;\n\n\n\n\n\n#ifdef SOFA_DUMP_VISITOR_INFO\n    sofa::simulation::Visitor::printNode(\"BuildFullSystem\");\n#endif\n    //------------------------------------------------------------------\n    // build c: right hand term\n    //------------------------------------------------------------------\n    VectorEigen previousC(c);\n    //TODO: change newC by c\n    c=VectorEigen::Zero(rowsL.size());\n    unsigned int idx=0;\n    for (helper::vector<unsigned int >::const_iterator it=rightHandElements.begin(); it!=rightHandElements.end(); ++it)\n        c[idx++]=previousC[*it];\n\n    //------------------------------------------------------------------\n    // build the L and LT matrices\n    //------------------------------------------------------------------\n\n\n    DofToMatrix LMatricesDirectSolver;\n    DofToMatrix LTMatricesDirectSolver;\n    for (DofToMatrix::iterator it=LMatrices.begin(); it!=LMatrices.end(); ++it)\n    {\n        //------------------------------------------------------------------\n        const SparseMatrixEigen& matrix= it->second;\n        //Init the manipulator with the full matrix\n        linearsolver::LMatrixManipulator manip;\n        manip.init(matrix);\n\n\n        //------------------------------------------------------------------\n        SparseMatrixEigen  L (rowsL.size(),  matrix.cols());\n        L.reserve(rowsL.size()*matrix.cols());\n        manip.buildLMatrix(rowsL ,L);\n        L.finalize();\n        LMatricesDirectSolver.insert (std::make_pair(it->first,L ));\n\n\n\n        //------------------------------------------------------------------\n        SparseMatrixEigen  LT(rowsLT.size(), matrix.cols());\n        LT.reserve(rowsLT.size()*matrix.cols());\n        manip.buildLMatrix(rowsLT,LT);\n        LT.finalize();\n        LTMatricesDirectSolver.insert(std::make_pair(it->first,LT));\n    }\n\n\n\n    //------------------------------------------------------------------\n    // build the full system\n    //------------------------------------------------------------------\n    const  int rows=rowsL.size();\n    const  int cols=rowsLT.size();\n    SparseColMajorMatrixEigen Wsparse(rows,cols);\n    buildLeftRectangularMatrix(invMassMatrix, LMatricesDirectSolver, LTMatricesDirectSolver, Wsparse,invMass_Ltrans);\n\n\n    //------------------------------------------------------------------\n    // conversion from sparse to dense matrix\n    //------------------------------------------------------------------\n    Lambda=VectorEigen::Zero(rows);\n\n    W=MatrixEigen::Zero(rows,cols);\n\n\n\n    SparseMatrixEigen Wresult(Wsparse);\n    for (int k=0; k<Wresult.outerSize(); ++k)\n        for (SparseMatrixEigen::InnerIterator it(Wresult,k); it; ++it) W(it.row(),it.col()) = it.value();\n\n\n\n#ifdef SOFA_DUMP_VISITOR_INFO\n    sofa::simulation::Visitor::printCloseNode(\"BuildFullSystem\");\n#endif\n\n    //------------------------------------------------------------------\n    // Solve the system\n    //------------------------------------------------------------------\n    const std::string &algo=solverAlgorithm.getValue().getSelectedItem() ;\n#ifdef SOFA_DUMP_VISITOR_INFO\n    simulation::Visitor::TRACE_ARGUMENT arg1;\n    arg1.push_back(std::make_pair(\"Algorithm\", algo));\n    arg1.push_back(std::make_pair(\"Dimension\", printDimension(W)));\n    sofa::simulation::Visitor::printNode(\"DirectSolveSystem\", \"\",arg1);\n#endif\n    if(algo == \"SVD\")\n    {\n        Eigen::JacobiSVD< MatrixEigen > solverSVD(W);\n        VectorEigen invSingularValues(solverSVD.singularValues());\n\n        for (int i=0; i<invSingularValues.size(); ++i)\n        {\n            if (invSingularValues[i] < 1e-10) invSingularValues[i]=0;\n            else invSingularValues[i]=1/invSingularValues[i];\n        }\n        Lambda.noalias() = solverSVD.matrixV()*invSingularValues.asDiagonal()*solverSVD.matrixU().transpose()*c;\n    }\n\n    if (this->f_printLog.getValue())\n    {\n        sout << \"W\" <<  printDimension(W) <<  \"  Lambda\" << printDimension(Lambda) << \"  c\" << printDimension(c) << sendl;\n        sout << \"\\nW     ===============================================\\n\" << W\n                <<  \"\\nLambda===============================================\\n\" << Lambda\n                <<  \"\\nc     ===============================================\\n\" << c << sendl;\n    }\n\n#ifdef SOFA_DUMP_VISITOR_INFO\n    sofa::simulation::Visitor::printCloseNode(\"DirectSolveSystem\");\n#endif\n    return success;\n\n}\n\n\nvoid LMConstraintDirectSolver::analyseConstraints(const helper::vector< sofa::core::behavior::BaseLMConstraint* > &LMConstraints, core::ConstraintParams::ConstOrder order,\n        JacobianRows &rowsL,JacobianRows &rowsLT, helper::vector< unsigned int > &rightHandElements) const\n{\n    //Iterate among all the Sofa LMConstraint\n    for (unsigned int componentConstraint=0; componentConstraint<LMConstraints.size(); ++componentConstraint)\n    {\n        sofa::core::behavior::BaseLMConstraint *constraint=LMConstraints[componentConstraint];\n        //Find the constraint dealing with contact\n        if (ContactDescriptionHandler* contactDescriptor=dynamic_cast<ContactDescriptionHandler*>(constraint))\n        {\n            const helper::vector< sofa::core::behavior::ConstraintGroup* > &constraintOrder=constraint->getConstraintsOrder(order);\n            //Iterate among all the contacts\n            for (helper::vector< sofa::core::behavior::ConstraintGroup* >::const_iterator itGroup=constraintOrder.begin(); itGroup!=constraintOrder.end(); ++itGroup)\n            {\n                const sofa::core::behavior::ConstraintGroup* group=*itGroup;\n                const sofa::component::constraintset::ContactDescription& contact=contactDescriptor->getContactDescription(group);\n\n                const unsigned int idxEquation=group->getConstraint(0).idx;\n\n                switch(contact.state)\n                {\n                case VANISHING:\n                {\n                    //                    serr <<\"Constraint \" << idxEquation << \" VANISHING\" << sendl;\n                    //0 equation\n                    break;\n                }\n                case STICKING:\n                {\n                    //                    serr << \"Constraint \" <<idxEquation << \" STICKING\" << sendl;\n                    const unsigned int i=rowsL.size();\n                    rowsL.push_back(linearsolver::LLineManipulator().addCombination(idxEquation  ));\n                    rowsL.push_back(linearsolver::LLineManipulator().addCombination(idxEquation+1));\n                    rowsL.push_back(linearsolver::LLineManipulator().addCombination(idxEquation+2));\n\n                    //3 equations\n                    rowsLT.push_back(rowsL[i  ]);\n                    rowsLT.push_back(rowsL[i+1]);\n                    rowsLT.push_back(rowsL[i+2]);\n\n                    rightHandElements.push_back(idxEquation  );\n                    rightHandElements.push_back(idxEquation+1);\n                    rightHandElements.push_back(idxEquation+2);\n                    break;\n                }\n                case SLIDING:\n                {\n                    //                    serr << \"Constraint \" <<idxEquation << \" SLIDING\" << sendl;\n                    rowsL.push_back(linearsolver::LLineManipulator().addCombination(idxEquation  ));\n                    rowsL.push_back(linearsolver::LLineManipulator().addCombination(idxEquation+1));\n                    rowsL.push_back(linearsolver::LLineManipulator().addCombination(idxEquation+2));\n\n\n                    //1 equation with the response force along the Coulomb friction cone\n                    rowsLT.push_back(linearsolver::LLineManipulator()\n                            .addCombination(idxEquation  ,contact.coeff[0])\n                            .addCombination(idxEquation+1,contact.coeff[1])\n                            .addCombination(idxEquation+2,contact.coeff[2]));\n\n                    rightHandElements.push_back(idxEquation  );\n                    rightHandElements.push_back(idxEquation+1);\n                    rightHandElements.push_back(idxEquation+2);\n                    break;\n                }\n                }\n            }\n        }\n        else\n        {\n            //Non contact constraints: we add all the equations\n            const helper::vector< sofa::core::behavior::ConstraintGroup* > &constraintOrder=constraint->getConstraintsOrder(order);\n            for (helper::vector< sofa::core::behavior::ConstraintGroup* >::const_iterator itGroup=constraintOrder.begin(); itGroup!=constraintOrder.end(); ++itGroup)\n            {\n                const sofa::core::behavior::ConstraintGroup* group=*itGroup;\n                std::pair< sofa::core::behavior::ConstraintGroup::EquationConstIterator,sofa::core::behavior::ConstraintGroup::EquationConstIterator> range=group->data();\n                for ( sofa::core::behavior::ConstraintGroup::EquationConstIterator it=range.first; it!=range.second; ++it)\n                {\n                    rowsL.push_back(linearsolver::LLineManipulator().addCombination(it->idx));\n                    rowsLT.push_back(rowsL.back());\n                    rightHandElements.push_back(it->idx);\n                }\n            }\n        }\n    }\n}\n\n\n\n\nvoid LMConstraintDirectSolver::buildLeftRectangularMatrix(const DofToMatrix& invMassMatrix,\n        DofToMatrix& LMatrix, DofToMatrix& LTMatrix,\n        SparseColMajorMatrixEigen &LeftMatrix, DofToMatrix &invMass_Ltrans) const\n{\n    invMass_Ltrans.clear();\n    for (SetDof::const_iterator itDofs=setDofs.begin(); itDofs!=setDofs.end(); ++itDofs)\n    {\n        const sofa::core::behavior::BaseMechanicalState* dofs=*itDofs;\n        const SparseMatrixEigen &invMass=invMassMatrix.find(dofs)->second;\n        const SparseMatrixEigen &L =LMatrix[dofs];\n        const SparseMatrixEigen &LT=LTMatrix[dofs];\n\n        SparseMatrixEigen invMass_LT=invMass*LT.transpose();\n\n        invMass_Ltrans.insert(std::make_pair(dofs, invMass_LT));\n        //SparseColMajorMatrixEigen temp=L*invMass_LT;\n        LeftMatrix += L*invMass_LT;\n    }\n}\nint LMConstraintDirectSolverClass = core::RegisterObject(\"A Direct Constraint Solver working specifically with LMConstraint based components\")\n        .add< LMConstraintDirectSolver >();\n\nSOFA_DECL_CLASS(LMConstraintDirectSolver);\n\n\n} // namespace constraintset\n\n} // namespace component\n\n} // namespace sofa\n", "meta": {"hexsha": "7bcb43dd13b979e4ba9a988931c9c0eac1c2cb4e", "size": 14230, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "modules/SofaConstraint/LMConstraintDirectSolver.cpp", "max_stars_repo_name": "sofa-framework/issofa", "max_stars_repo_head_hexsha": "94855f488465bc3ed41223cbde987581dfca5389", "max_stars_repo_licenses": ["OML"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "modules/SofaConstraint/LMConstraintDirectSolver.cpp", "max_issues_repo_name": "sofa-framework/issofa", "max_issues_repo_head_hexsha": "94855f488465bc3ed41223cbde987581dfca5389", "max_issues_repo_licenses": ["OML"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "modules/SofaConstraint/LMConstraintDirectSolver.cpp", "max_forks_repo_name": "sofa-framework/issofa", "max_forks_repo_head_hexsha": "94855f488465bc3ed41223cbde987581dfca5389", "max_forks_repo_licenses": ["OML"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 42.7327327327, "max_line_length": 171, "alphanum_fraction": 0.5593113141, "num_tokens": 2898, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.7185944046238981, "lm_q2_score": 0.4571367168274948, "lm_q1q2_score": 0.3284958868603771}}
{"text": "// Boost.Geometry\r\n\r\n// Copyright (c) 2017 Oracle and/or its affiliates.\r\n\r\n// Contributed and/or modified by Adam Wulkiewicz, on behalf of Oracle\r\n\r\n// Use, modification and distribution is subject to the Boost Software License,\r\n// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\r\n// http://www.boost.org/LICENSE_1_0.txt)\r\n\r\n#ifndef BOOST_GEOMETRY_FORMULAS_AUTHALIC_RADIUS_SQR_HPP\r\n#define BOOST_GEOMETRY_FORMULAS_AUTHALIC_RADIUS_SQR_HPP\r\n\r\n#include <boost/geometry/core/radius.hpp>\r\n#include <boost/geometry/core/tag.hpp>\r\n#include <boost/geometry/core/tags.hpp>\r\n\r\n#include <boost/geometry/formulas/eccentricity_sqr.hpp>\r\n\r\n#include <boost/geometry/util/math.hpp>\r\n\r\n#include <boost/geometry/algorithms/not_implemented.hpp>\r\n\r\n#include <boost/math/special_functions/atanh.hpp>\r\n\r\nnamespace boost { namespace geometry\r\n{\r\n\r\n#ifndef DOXYGEN_NO_DISPATCH\r\nnamespace formula_dispatch\r\n{\r\n\r\ntemplate <typename ResultType, typename Geometry, typename Tag = typename tag<Geometry>::type>\r\nstruct authalic_radius_sqr\r\n    : not_implemented<Tag>\r\n{};\r\n\r\ntemplate <typename ResultType, typename Geometry>\r\nstruct authalic_radius_sqr<ResultType, Geometry, srs_sphere_tag>\r\n{\r\n    static inline ResultType apply(Geometry const& geometry)\r\n    {\r\n        return math::sqr<ResultType>(get_radius<0>(geometry));\r\n    }\r\n};\r\n\r\ntemplate <typename ResultType, typename Geometry>\r\nstruct authalic_radius_sqr<ResultType, Geometry, srs_spheroid_tag>\r\n{\r\n    static inline ResultType apply(Geometry const& geometry)\r\n    {\r\n        ResultType const a2 = math::sqr<ResultType>(get_radius<0>(geometry));\r\n        ResultType const e2 = formula::eccentricity_sqr<ResultType>(geometry);\r\n\r\n        return apply(a2, e2);\r\n    }\r\n\r\n    static inline ResultType apply(ResultType const& a2, ResultType const& e2)\r\n    {\r\n        ResultType const c0 = 0;\r\n\r\n        if (math::equals(e2, c0))\r\n        {\r\n            return a2;\r\n        }\r\n\r\n        ResultType const e = math::sqrt(e2);\r\n        ResultType const c2 = 2;\r\n\r\n        //ResultType const b2 = math::sqr(get_radius<2>(geometry));\r\n        //return a2 / c2 + b2 * boost::math::atanh(e) / (c2 * e);\r\n\r\n        ResultType const c1 = 1;\r\n        return (a2 / c2) * ( c1 + (c1 - e2) * boost::math::atanh(e) / e );\r\n    }\r\n};\r\n\r\n} // namespace formula_dispatch\r\n#endif // DOXYGEN_NO_DISPATCH\r\n\r\n#ifndef DOXYGEN_NO_DETAIL\r\nnamespace formula\r\n{\r\n\r\ntemplate <typename ResultType, typename Geometry>\r\ninline ResultType authalic_radius_sqr(Geometry const& geometry)\r\n{\r\n    return formula_dispatch::authalic_radius_sqr<ResultType, Geometry>::apply(geometry);\r\n}\r\n\r\n} // namespace formula\r\n#endif // DOXYGEN_NO_DETAIL\r\n\r\n}} // namespace boost::geometry\r\n\r\n#endif // BOOST_GEOMETRY_FORMULAS_AUTHALIC_RADIUS_SQR_HPP\r\n", "meta": {"hexsha": "ab28941f8f63e852d32f2ccad9ad2853494cd2b8", "size": 2750, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "deps/boost/include/boost/geometry/formulas/authalic_radius_sqr.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/authalic_radius_sqr.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/authalic_radius_sqr.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.3505154639, "max_line_length": 95, "alphanum_fraction": 0.6985454545, "num_tokens": 670, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7185943925708562, "lm_q2_score": 0.4571367168274948, "lm_q1q2_score": 0.3284958813504891}}
{"text": "#pragma once\n\n#include <cstddef>\n#include <random>\n#include <boost/iterator/counting_iterator.hpp>\n#include <boost/iterator/transform_iterator.hpp>\n#include <boost/iterator/iterator_facade.hpp>\n\n#include \"nifty/graph/detail/andres/grid-graph.hxx\"\n\n#include \"nifty/tools/runtime_check.hxx\"\n#include \"nifty/tools/for_each_coordinate.hxx\"\n#include \"nifty/graph/undirected_graph_base.hxx\"\n#include \"nifty/graph/detail/adjacency.hxx\"\n#include \"nifty/graph/graph_tags.hxx\"\n#include \"nifty/parallel/threadpool.hxx\"\n#include \"nifty/array/arithmetic_array.hxx\"\n#include \"nifty/xtensor/xtensor.hxx\"\n\n\nnamespace nifty{\nnamespace graph{\n\n\nnamespace detail_graph{\n\n\n    template<std::size_t DIM, bool SIMPLE_NH>\n    class UndirectedGridGraphIter{\n    public:\n        typedef andres::graph::GridGraph<DIM> AGridGraph;\n        typedef typename AGridGraph::AdjacencyIterator AGridGraphAdjacencyIter;\n        typedef UndirectedAdjacency<int64_t,int64_t,int64_t,int64_t> NodeAdjacency;\n\n        struct UnaryFunction{\n            typedef NodeAdjacency value_type;\n            template<class ADJ>\n            NodeAdjacency operator()(const ADJ & adjacency)const{\n                return NodeAdjacency(adjacency.vertex(), adjacency.vertex());\n            }\n        };\n\n        typedef boost::transform_iterator<\n            UnaryFunction,\n            typename AGridGraph::AdjacencyIterator,\n            NodeAdjacency,\n            NodeAdjacency\n        > OldAdjacencyIter;\n\n\n\n        class AdjacencyIter\n        : public boost::iterator_facade<\n            AdjacencyIter,\n            NodeAdjacency,\n            std::random_access_iterator_tag,\n            const NodeAdjacency &\n        >\n        {\n        public:\n            AdjacencyIter(const AGridGraphAdjacencyIter & iter)\n            :   iter_(iter),\n                adjacency_(){\n            }\n            bool equal(const AdjacencyIter & other)const{\n                return iter_ == other.iter_;\n            }\n            void increment(){\n                ++iter_;\n            }\n            void dencrement(){\n                --iter_;\n            }\n            void advance(const std::size_t n){\n                iter_+=n;\n            }\n            std::ptrdiff_t distance_to(const AdjacencyIter & other)const{\n                return std::distance(iter_, other.iter_);\n            }\n            const NodeAdjacency & dereference()const{\n                adjacency_ = NodeAdjacency(iter_->vertex(), iter_->edge());\n                return adjacency_;\n            }\n        private:\n            mutable AGridGraphAdjacencyIter iter_;\n            mutable NodeAdjacency adjacency_;\n        };\n\n\n        class NodeIter : public boost::counting_iterator<int64_t>{\n            using boost::counting_iterator<int64_t>::counting_iterator;\n            using boost::counting_iterator<int64_t>::operator=;\n        };\n\n        class EdgeIter : public boost::counting_iterator<int64_t>{\n            using boost::counting_iterator<int64_t>::counting_iterator;\n            using boost::counting_iterator<int64_t>::operator=;\n        };\n    };\n\n    //\n    // distance functions along channel dimension\n    //\n\n    template<unsigned DIM, class IMAGE>\n    double l2Distance(\n        const IMAGE & image,\n        const unsigned nChannels,\n        nifty::array::StaticArray<int64_t, DIM+1> coordU,\n        nifty::array::StaticArray<int64_t, DIM+1> coordV\n    ) {\n        double val = 0;\n        for(unsigned c = 0; c < nChannels; ++c) {\n            coordU[0] = c;\n            coordV[0] = c;\n            const auto uVal = xtensor::read(image, coordU);\n            const auto vVal = xtensor::read(image, coordV);\n            val += (uVal - vVal) * (uVal - vVal);\n        }\n        return std::sqrt(val);\n    }\n\n    template<unsigned DIM, class IMAGE>\n    double l1Distance(\n        const IMAGE & image,\n        const unsigned nChannels,\n        nifty::array::StaticArray<int64_t, DIM+1> coordU,\n        nifty::array::StaticArray<int64_t, DIM+1> coordV\n    ) {\n        double val = 0;\n        for(unsigned c = 0; c < nChannels; ++c) {\n            coordU[0] = c;\n            coordV[0] = c;\n            const auto uVal = xtensor::read(image, coordU);\n            const auto vVal = xtensor::read(image, coordV);\n            val += std::abs(uVal - vVal);\n        }\n        return val;\n    }\n\n    template<unsigned DIM, class IMAGE>\n    double cosineDistance(\n        const IMAGE & image,\n        const unsigned nChannels,\n        nifty::array::StaticArray<int64_t, DIM+1> coordU,\n        nifty::array::StaticArray<int64_t, DIM+1> coordV\n    ) {\n        const double eps = 1e-7;\n\n        double val = 0;\n        double normU = 0;\n        double normV = 0;\n\n        for(unsigned c = 0; c < nChannels; ++c) {\n            coordU[0] = c;\n            coordV[0] = c;\n            const auto uVal = xtensor::read(image, coordU);\n            const auto vVal = xtensor::read(image, coordV);\n            val += uVal * vVal;\n            normU += uVal * uVal;\n            normV += vVal * vVal;\n        }\n        normU = std::sqrt(normU) + eps;\n        normV = std::sqrt(normV) + eps;\n        val = 1. - (val / normU / normV);\n        return val;\n    }\n\n\n};\n\n\ntemplate<std::size_t DIM, bool SIMPLE_NH>\nclass UndirectedGridGraph;\n\n\n\ntemplate<std::size_t DIM>\nclass UndirectedGridGraph<DIM,true> : public\n    UndirectedGraphBase<\n        UndirectedGridGraph<DIM, true>,\n        typename detail_graph::UndirectedGridGraphIter<DIM,true>::NodeIter,\n        typename detail_graph::UndirectedGridGraphIter<DIM,true>::EdgeIter,\n        typename detail_graph::UndirectedGridGraphIter<DIM,true>::AdjacencyIter\n    >\n{\nprivate:\n    typedef andres::graph::GridGraph<DIM> AndresGridGraphType;\n    typedef typename AndresGridGraphType::VertexCoordinate AndresVertexCoordinate;\npublic:\n    typedef nifty::array::StaticArray<int64_t, DIM> ShapeType;\n    typedef nifty::array::StaticArray<int64_t, DIM> CoordinateType;\n\n    typedef typename detail_graph::UndirectedGridGraphIter<DIM,true>::NodeIter      NodeIter;\n    typedef typename detail_graph::UndirectedGridGraphIter<DIM,true>::EdgeIter      EdgeIter;\n    typedef typename detail_graph::UndirectedGridGraphIter<DIM,true>::AdjacencyIter AdjacencyIter;\n\n\n    typedef ContiguousTag EdgeIdTag;\n    typedef ContiguousTag NodeIdTag;\n\n    typedef SortedTag EdgeIdOrderTag;\n    typedef SortedTag NodeIdOrderTag;\n\n\n\n    UndirectedGridGraph()\n    : gridGraph_(){\n    }\n\n    template<class T>\n    UndirectedGridGraph(const nifty::array::StaticArray<T, DIM> & shape)\n    : gridGraph_(){\n\n        AndresVertexCoordinate ashape;\n        std::copy(shape.rbegin(), shape.rend(), ashape.begin());\n        gridGraph_.assign(ashape);\n\n    }\n\n    template<class T>\n    void assign(const nifty::array::StaticArray<T, DIM> & shape){\n\n        AndresVertexCoordinate ashape;\n        std::copy(shape.rbegin(), shape.rend(), ashape.begin());\n        gridGraph_.assign(ashape);\n\n    }\n\n\n    //void assign(const uint64_t numberOfNodes = 0, const uint64_t reserveNumberOfEdges = 0);\n\n\n\n    // MUST IMPL INTERFACE\n    int64_t u(const int64_t e)const{\n        return gridGraph_.vertexOfEdge(e,0);\n    }\n    int64_t v(const int64_t e)const{\n        return gridGraph_.vertexOfEdge(e,1);\n    }\n\n    int64_t findEdge(const int64_t u, const int64_t v)const{\n        const auto r = gridGraph_.findEdge(u,v);\n        if(r.first)\n            return r.second;\n        else\n            return -1;\n    }\n    int64_t nodeIdUpperBound() const{\n         return numberOfNodes() == 0 ? 0 : numberOfNodes()-1;\n    }\n    int64_t edgeIdUpperBound() const{\n        return numberOfEdges() == 0 ? 0 : numberOfEdges()-1;\n    }\n\n    uint64_t numberOfEdges() const{\n        return gridGraph_.numberOfEdges();\n    }\n    uint64_t numberOfNodes() const{\n        return gridGraph_.numberOfVertices();\n    }\n\n    NodeIter nodesBegin()const{\n        return NodeIter(0);\n    }\n    NodeIter nodesEnd()const{\n        return NodeIter(this->numberOfNodes());\n    }\n    EdgeIter edgesBegin()const{\n        return EdgeIter(0);\n    }\n    EdgeIter edgesEnd()const{\n        return EdgeIter(this->numberOfEdges());\n    }\n\n    AdjacencyIter adjacencyBegin(const int64_t node)const{\n        return AdjacencyIter(gridGraph_.adjacenciesFromVertexBegin(node));\n    }\n    AdjacencyIter adjacencyEnd(const int64_t node)const{\n        return AdjacencyIter(gridGraph_.adjacenciesFromVertexEnd(node));\n    }\n    AdjacencyIter adjacencyOutBegin(const int64_t node)const{\n        return AdjacencyIter(gridGraph_.adjacenciesFromVertexBegin(node));\n    }\n     AdjacencyIter adjacencyOutEnd(const int64_t node)const{\n        return AdjacencyIter(gridGraph_.adjacenciesFromVertexEnd(node));\n    }\n\n\n    // optional (with default impl in base)\n    //std::pair<int64_t,int64_t> uv(const int64_t e)const;\n\n    template<class F>\n    void forEachEdge(F && f)const{\n        for(uint64_t edge=0; edge< numberOfEdges(); ++edge){\n            f(edge);\n        }\n    }\n\n    template<class F>\n    void forEachNode(F && f)const{\n        for(uint64_t node=0; node< numberOfNodes(); ++node){\n            f(node);\n        }\n    }\n\n\n    // serialization de-serialization\n\n    uint64_t serializationSize() const{\n        return DIM + 1;\n    }\n\n    template<class ITER>\n    void serialize(ITER iter) const{\n        for(auto d=0; d<DIM; ++d){\n            *iter = gridGraph_.shape(d);\n            ++iter;\n        }\n        // simple nh?\n        *iter = true;\n        ++iter;\n    }\n\n    template<class ITER>\n    void deserialize(ITER iter);\n\n\n    /**\n     * @brief convert an image with DIM dimension to an edge map\n     * @details convert an image with DIM dimension to an edge map\n     * by applying a binary functor to the values of a node map at\n     * the endpoints of an edge.\n     *\n     * @param       image the  input image\n     * @param       binaryFunctor a binary functor\n     * @param[out]  the result edge map\n     *\n     * @return [description]\n     */\n    template<class IMAGE, class BINARY_FUNCTOR, class EDGE_MAP>\n    void imageToEdgeMap(\n        const IMAGE & image,\n        BINARY_FUNCTOR binaryFunctor,\n        EDGE_MAP & edgeMap\n    )const{\n        for(const auto edge : this->edges()){\n            const auto uv = this->uv(edge);\n            CoordinateType cU, cV;\n            nodeToCoordinate(uv.first,  cU);\n            nodeToCoordinate(uv.second, cV);\n            const auto uVal = xtensor::read(image, cU.asStdArray());\n            const auto vVal = xtensor::read(image, cV.asStdArray());\n\n            edgeMap[edge] = binaryFunctor(uVal, vVal);\n        }\n    }\n\n\n    /**\n     * @brief convert an image with DIM + 1 dimension to an edge map\n     * @details convert an image with DIM + 1 dimension to an edge map\n     * by computing the distance between the values of a node map at\n     * the endpoints of an edge.\n     *\n     * @param       image the  input image\n     * @param       distance   the distance (l1, l2 or cosine)\n     * @param[out]  the result edge map\n     *\n     * @return [description]\n     */\n    template<class IMAGE, class EDGE_MAP>\n    void imageWithChannelsToEdgeMap(\n        const IMAGE & image,\n        const std::string & distance,\n        EDGE_MAP & edgeMap\n    ) const {\n        if(distance == \"l1\") {\n            imageWithChannelsToEdgeMapImpl(image, edgeMap, detail_graph::l1Distance<DIM, IMAGE>);\n        } else if(distance == \"l2\") {\n            imageWithChannelsToEdgeMapImpl(image, edgeMap, detail_graph::l2Distance<DIM, IMAGE>);\n        } else if(distance == \"cosine\") {\n            imageWithChannelsToEdgeMapImpl(image, edgeMap, detail_graph::cosineDistance<DIM, IMAGE>);\n        } else {\n            throw std::runtime_error(\"Invalid distance.\");\n        }\n    }\n\n    template<class IMAGE, class EDGES, class EDGE_MAP>\n    std::size_t imageWithChannelsToEdgeMapWithOffsets(\n        const IMAGE & image,\n        const std::string & distance,\n        const std::vector<std::vector<int>> & offsets,\n        EDGES & edges,\n        EDGE_MAP & edgeMap\n    ) const {\n\n        std::size_t edgeId = 0;\n        auto sampler = [](const nifty::array::StaticArray<int64_t, DIM+1> & coord){return true;};\n\n        if(distance == \"l1\") {\n            edgeId = imageWithChannelsToEdgeMapWithOffsetsImpl(image, offsets,\n                                                               detail_graph::l1Distance<DIM, IMAGE>,\n                                                               sampler,\n                                                               edges, edgeMap);\n        } else if(distance == \"l2\") {\n            edgeId = imageWithChannelsToEdgeMapWithOffsetsImpl(image, offsets,\n                                                               detail_graph::l2Distance<DIM, IMAGE>,\n                                                               sampler,\n                                                               edges, edgeMap);\n        } else if(distance == \"cosine\") {\n            edgeId = imageWithChannelsToEdgeMapWithOffsetsImpl(image, offsets,\n                                                               detail_graph::cosineDistance<DIM, IMAGE>,\n                                                               sampler,\n                                                               edges, edgeMap);\n        } else {\n            throw std::runtime_error(\"Invalid distance.\");\n        }\n\n        return edgeId;\n    }\n\n    template<class IMAGE, class EDGES, class EDGE_MAP>\n    std::size_t imageWithChannelsToEdgeMapWithOffsets(\n        const IMAGE & image,\n        const std::string & distance,\n        const std::vector<std::vector<int>> & offsets,\n        const std::vector<int> & strides,\n        EDGES & edges,\n        EDGE_MAP & edgeMap\n    ) const {\n\n        std::size_t edgeId = 0;\n\n        auto sampler = [&strides](const nifty::array::StaticArray<int64_t, DIM+1> & coord){\n            bool inStride = true;\n            for(unsigned d = 0; d < DIM; ++d) {\n                if(coord[d+1] % strides[d] != 0) {\n                    inStride = false;\n                    break;\n                }\n            }\n            return inStride;\n        };\n\n        if(distance == \"l1\") {\n            edgeId = imageWithChannelsToEdgeMapWithOffsetsImpl(image, offsets,\n                                                               detail_graph::l1Distance<DIM, IMAGE>,\n                                                               sampler,\n                                                               edges, edgeMap);\n        } else if(distance == \"l2\") {\n            edgeId = imageWithChannelsToEdgeMapWithOffsetsImpl(image, offsets,\n                                                               detail_graph::l2Distance<DIM, IMAGE>,\n                                                               sampler,\n                                                               edges, edgeMap);\n        } else if(distance == \"cosine\") {\n            edgeId = imageWithChannelsToEdgeMapWithOffsetsImpl(image, offsets,\n                                                               detail_graph::cosineDistance<DIM, IMAGE>,\n                                                               sampler,\n                                                               edges, edgeMap);\n        } else {\n            throw std::runtime_error(\"Invalid distance.\");\n        }\n\n        return edgeId;\n    }\n\n    template<class IMAGE, class EDGES, class EDGE_MAP>\n    std::size_t imageWithChannelsToEdgeMapWithOffsets(\n        const IMAGE & image,\n        const std::string & distance,\n        const std::vector<std::vector<int>> & offsets,\n        const double sampleProbability,\n        EDGES & edges,\n        EDGE_MAP & edgeMap\n    ) const {\n\n        std::size_t edgeId = 0;\n\n        std::default_random_engine gen;\n        std::uniform_real_distribution<double> distr;\n        auto draw = std::bind(distr, gen);\n\n        auto sampler = [&draw, sampleProbability](const nifty::array::StaticArray<int64_t, DIM+1> & coord){\n            return draw() < sampleProbability;\n        };\n\n        if(distance == \"l1\") {\n            edgeId = imageWithChannelsToEdgeMapWithOffsetsImpl(image, offsets,\n                                                               detail_graph::l1Distance<DIM, IMAGE>,\n                                                               sampler,\n                                                               edges, edgeMap);\n        } else if(distance == \"l2\") {\n            edgeId = imageWithChannelsToEdgeMapWithOffsetsImpl(image, offsets,\n                                                               detail_graph::l2Distance<DIM, IMAGE>,\n                                                               sampler,\n                                                               edges, edgeMap);\n        } else if(distance == \"cosine\") {\n            edgeId = imageWithChannelsToEdgeMapWithOffsetsImpl(image, offsets,\n                                                               detail_graph::cosineDistance<DIM, IMAGE>,\n                                                               sampler,\n                                                               edges, edgeMap);\n        } else {\n            throw std::runtime_error(\"Invalid distance.\");\n        }\n\n        return edgeId;\n    }\n\n    /**\n     * @brief convert an affinity map with DIM+1 dimension to an edge map\n     * @details convert an affinity map with DIM+1 dimension to an edge map\n     * by assigning the affinity values to corresponding affinity values\n     *\n     * @param       image the input affinities\n     * @param       whether affinities encode connectivity yo lower or upper pixel\n     * @param[out]  the result edge map\n     *\n     * @return [description]\n     */\n    template<class AFFINITIES, class EDGE_MAP>\n    void affinitiesToEdgeMap(const AFFINITIES & affinities,\n                             EDGE_MAP & edgeMap,\n                             const bool toLower=true) const {\n        NIFTY_CHECK_OP(affinities.shape()[0], ==, DIM, \"wrong number of affinity channels\")\n        for(auto d=1; d<DIM+1; ++d){\n            NIFTY_CHECK_OP(shape(d-1), ==, affinities.shape()[d], \"wrong shape\")\n        }\n\n        typedef nifty::array::StaticArray<int64_t, DIM+1> AffinityCoordType;\n\n        CoordinateType cU, cV;\n        for(const auto edge : this->edges()){\n\n            const auto uv = this->uv(edge);\n            nodeToCoordinate(uv.first,  cU);\n            nodeToCoordinate(uv.second, cV);\n\n            // find the correct affinity edge\n            AffinityCoordType affCoord;\n            for(std::size_t d = 0; d < DIM; ++d) {\n                auto diff = cU[d] - cV[d];\n                if(diff == 0) {\n                    affCoord[d + 1] = cU[d];\n                }\n                else {\n                    affCoord[d + 1] = toLower ? (cU[d] < cV[d] ? cU[d] : cV[d]) : (cU[d] < cV[d] ? cV[d] : cU[d]);\n                    affCoord[0] = d;\n                }\n            }\n\n            edgeMap(edge) = xtensor::read(affinities, affCoord.asStdArray());\n        }\n    }\n\n\n    template<class AFFINITIES, class EDGES, class EDGE_MAP>\n    std::size_t affinitiesToEdgeMapWithOffsets(const AFFINITIES & affinities,\n                                               const std::vector<std::vector<int>> & offsets,\n                                               EDGES & edges,\n                                               EDGE_MAP & edgeMap) const {\n        auto sampler = [](const nifty::array::StaticArray<int64_t, DIM+1> & coord){return true;};\n        const std::size_t edgeId = affinitiesToEdgeMapWithOffsetsImpl(\n            affinities, offsets,\n            edges, edgeMap, sampler\n        );\n        return edgeId;\n    }\n\n\n    template<class AFFINITIES, class EDGES, class EDGE_MAP>\n    std::size_t affinitiesToEdgeMapWithOffsets(const AFFINITIES & affinities,\n                                               const std::vector<std::vector<int>> & offsets,\n                                               const std::vector<int> & strides,\n                                               EDGES & edges,\n                                               EDGE_MAP & edgeMap) const {\n\n        auto sampler = [&strides](const nifty::array::StaticArray<int64_t, DIM+1> & coord){\n            bool inStride = true;\n            for(unsigned d = 0; d < DIM; ++d) {\n                if(coord[d+1] % strides[d] != 0) {\n                    inStride = false;\n                    break;\n                }\n            }\n            return inStride;\n        };\n\n        const std::size_t edgeId = affinitiesToEdgeMapWithOffsetsImpl(\n            affinities, offsets,\n            edges, edgeMap, sampler\n        );\n        return edgeId;\n    }\n\n\n    template<class AFFINITIES, class EDGES, class EDGE_MAP>\n    std::size_t affinitiesToEdgeMapWithOffsets(const AFFINITIES & affinities,\n                                               const std::vector<std::vector<int>> & offsets,\n                                               const double sampleProbability,\n                                               EDGES & edges,\n                                               EDGE_MAP & edgeMap) const {\n\n        std::default_random_engine gen;\n        std::uniform_real_distribution<double> distr(0., 1.);\n        auto draw = std::bind(distr, gen);\n\n        auto sampler = [&draw, sampleProbability](const nifty::array::StaticArray<int64_t, DIM+1> & coord){\n            return draw() < sampleProbability;\n        };\n\n        const std::size_t edgeId = affinitiesToEdgeMapWithOffsetsImpl(\n            affinities, offsets,\n            edges, edgeMap, sampler\n        );\n        return edgeId;\n    }\n\n\n    template<class AFFINITIES, class MASK, class EDGES, class EDGE_MAP>\n    std::size_t affinitiesToEdgeMapWithOffsets(const AFFINITIES & affinities,\n                                               const std::vector<std::vector<int>> & offsets,\n                                               const MASK & mask,\n                                               EDGES & edges,\n                                               EDGE_MAP & edgeMap) const {\n\n        std::default_random_engine gen;\n        std::uniform_real_distribution<double> distr(0., 1.);\n        auto draw = std::bind(distr, gen);\n\n        auto sampler = [&mask](const nifty::array::StaticArray<int64_t, DIM+1> & coord){\n            return xtensor::read(mask, coord);\n        };\n\n        const std::size_t edgeId = affinitiesToEdgeMapWithOffsetsImpl(\n            affinities, offsets,\n            edges, edgeMap, sampler\n        );\n        return edgeId;\n    }\n\n\n    /**\n     * @brief convert an image with DIM dimension to an edge map\n     * @details convert an image with DIM dimension to an edge map\n     * by taking the values of the image at the\n     * interpixel coordinates.\n     * The shape of the image must be 2*shape-1\n     *\n     *\n     * @param       image the  input image\n     * @param       binaryFunctor a binary functor\n     * @param[out]  the result edge map\n     *\n     * @return [description]\n     */\n    template<class IMAGE, class EDGE_MAP>\n    void imageToInterpixelEdgeMap(\n        const IMAGE & image,\n        EDGE_MAP & edgeMap\n    )const{\n\n        for(auto d=0; d<DIM; ++d){\n            NIFTY_CHECK_OP(shape(d)*2 - 1, ==, image.shape()[d],\n                \"wrong shape foer image to interpixel edge map\")\n        }\n\n        for(const auto edge : this->edges()){\n            const auto uv = this->uv(edge);\n            CoordinateType cU,cV;\n            nodeToCoordinate(uv.first,  cU);\n            nodeToCoordinate(uv.second, cV);\n            // FIXME I don't understand what is going on here ?!\n            // But doesn't look right\n            const auto uVal = xtensor::read(image, cU.asStdArray());\n            cU += cV;\n            edgeMap(edge) = xtensor::read(image, cU.asStdArray());\n        }\n    }\n\n\n    uint64_t shape(const std::size_t d)const{\n        return gridGraph_.shape(DIM-1-d);\n    }\n\n    // COORDINATE RELATED\n    CoordinateType nodeToCoordinate(const uint64_t node)const{\n        CoordinateType ret;\n        nodeToCoordinate(node, ret);\n        return ret;\n    }\n\n    template<class NODE_COORDINATE>\n    void nodeToCoordinate(\n        const uint64_t node,\n        NODE_COORDINATE & coordinate\n    )const{\n        AndresVertexCoordinate aCoordinate;\n        gridGraph_.vertex(node, aCoordinate);\n        for(auto d=0; d<DIM; ++d){\n            coordinate[d] = aCoordinate[DIM-1-d];\n        }\n    }\n\n    template<class NODE_COORDINATE>\n    uint64_t coordinateToNode(const NODE_COORDINATE & coordinate)const{\n        AndresVertexCoordinate aCoordinate;\n        for(auto d=0; d<DIM; ++d){\n            aCoordinate[DIM-1-d] = coordinate[d];\n        }\n        return gridGraph_.vertex(aCoordinate);\n    }\n\n\n    //\n    // edge id projection (with and w/o offsets)\n    //\n\n    template<class RET>\n    void projectEdgeIdsToPixels(\n        RET & ret\n    ) const {\n        typedef nifty::array::StaticArray<int64_t, DIM+1> EdgeCoordType;\n        CoordinateType cU, cV;\n        EdgeCoordType cEdge;\n        for(const auto edge : this->edges()){\n            const auto uv = this->uv(edge);\n            nodeToCoordinate(uv.first, cU);\n            nodeToCoordinate(uv.second, cV);\n\n            for(unsigned d = 0; d < DIM; ++d) {\n                cEdge[d+1] = cU[d];\n                if(cU[d] != cV[d]) {\n                    cEdge[0] = d;\n                }\n            }\n\n            xtensor::write(ret, cEdge, edge);\n        }\n    }\n\n    template<class RET>\n    void projectEdgeIdsToPixels(\n        const std::vector<std::vector<int>> & offsets,\n        RET & ret\n    ) const {\n        auto sampler = [](const nifty::array::StaticArray<int64_t, DIM+1> & coord){return true;};\n        projectEdgeIdsToPixelsImpl(offsets, sampler, ret);\n    }\n\n    template<class RET>\n    void projectEdgeIdsToPixels(\n        const std::vector<std::vector<int>> & offsets,\n        const std::vector<int> & strides,\n        RET & ret\n    ) const {\n        auto sampler = [&strides](const nifty::array::StaticArray<int64_t, DIM+1> & coord){\n            bool inStride = true;\n            for(unsigned d = 0; d < DIM; ++d) {\n                if(coord[d+1] % strides[d] != 0) {\n                    inStride = false;\n                    break;\n                }\n            }\n            return inStride;\n        };\n        projectEdgeIdsToPixelsImpl(offsets, sampler, ret);\n    }\n\n    template<class MASK, class RET>\n    void projectEdgeIdsToPixels(\n        const std::vector<std::vector<int>> & offsets,\n        const MASK & mask,\n        RET & ret\n    ) const {\n        auto sampler = [&mask](const nifty::array::StaticArray<int64_t, DIM+1> & coord){\n            return xtensor::read(mask, coord);\n        };\n        projectEdgeIdsToPixelsImpl(offsets, sampler, ret);\n    }\n\n    template<class RET>\n    void projectNodeIdsToPixels(RET & ret) const {\n\n        CoordinateType shape_;\n        for(unsigned d = 0; d < DIM; ++d) {\n            shape_[d] = shape(d);\n        }\n\n        nifty::tools::forEachCoordinate(shape_, [&](const auto & coordP){\n            const auto u = coordinateToNode(coordP);\n            xtensor::write(ret, coordP, u);\n        });\n    }\n\nprivate:\n\n    //\n    // implementation of imageWithChannelsToEdgeMap\n    //\n\n    template<class IMAGE, class EDGE_MAP, class F>\n    void imageWithChannelsToEdgeMapImpl(\n        const IMAGE & image,\n        EDGE_MAP & edgeMap,\n        F & dist\n    ) const {\n        const int nChannels = image.shape()[0];\n        nifty::array::StaticArray<int64_t, DIM+1> coordU;\n        nifty::array::StaticArray<int64_t, DIM+1> coordV;\n        for(const auto edge : this->edges()){\n            const auto uv = this->uv(edge);\n            CoordinateType cU, cV;\n            nodeToCoordinate(uv.first,  cU);\n            nodeToCoordinate(uv.second, cV);\n            for(unsigned d = 0; d < DIM; ++d) {\n                coordU[d + 1] = cU[d];\n                coordV[d + 1] = cV[d];\n            }\n            edgeMap(edge) = dist(image, nChannels, coordU, coordV);\n        }\n    }\n\n    //\n    // implementations of imageToEdgeMapWithChannelsWithOffsets\n    //\n\n    template<class IMAGE, class DIST, class SAMPLER,\n             class EDGES, class EDGE_MAP>\n    std::size_t imageWithChannelsToEdgeMapWithOffsetsImpl(\n        const IMAGE & image,\n        const std::vector<std::vector<int>> & offsets,\n        DIST & dist,\n        SAMPLER & sampler,\n        EDGES & edges,\n        EDGE_MAP & edgeMap\n    ) const {\n        typedef typename EDGE_MAP::value_type edgeValType;\n        typedef nifty::array::StaticArray<int64_t, DIM+1> CoordWithChannelType;\n        typedef nifty::array::StaticArray<int64_t, DIM+1> EdgeCoordType;\n\n        const unsigned nChannels = image.shape()[0];\n        const std::size_t nOffsets = offsets.size();\n\n        CoordinateType coordU;\n        CoordinateType coordV;\n        CoordWithChannelType coordUC;\n        CoordWithChannelType coordVC;\n\n        for(auto d=1; d<DIM+1; ++d){\n            NIFTY_CHECK_OP(shape(d-1), ==, image.shape()[d], \"wrong shape\")\n        }\n\n        EdgeCoordType edgeShape;\n        edgeShape[0] = offsets.size();\n        for(unsigned d = 0; d < DIM; ++d) {\n            edgeShape[d + 1] = shape(d);\n        }\n\n        std::size_t edgeId = 0;\n        tools::forEachCoordinate(edgeShape, [&](const EdgeCoordType & edgeCoord) {\n            const auto & offset = offsets[edgeCoord[0]];\n\n            // initialise the coordinates w/o and w/ channel\n            bool isValid = true;\n            for(unsigned d = 0; d < DIM; ++d) {\n                coordU[d] = edgeCoord[d+1];\n                coordV[d] = edgeCoord[d+1] + offset[d];\n                // range check\n                if(coordV[d] >= shape(d) || coordV[d] < 0) {\n                    isValid = false;\n                    break;\n                }\n                coordUC[d+1] = coordU[d];\n                coordVC[d+1] = coordV[d];\n            }\n            if(!isValid) {\n                return;\n            }\n\n            if(!sampler(edgeCoord)) {\n                return;\n            }\n\n            const std::size_t u = coordinateToNode(coordU);\n            const std::size_t v = coordinateToNode(coordV);\n\n            edgeMap(edgeId) = dist(image, nChannels, coordUC, coordVC);\n            edges(edgeId, 0) = std::min(u, v);\n            edges(edgeId, 1) = std::max(u, v);\n            ++edgeId;\n        });\n        return edgeId;\n    }\n\n    //\n    // implementation of affinitiesToEdgeMapWithOffsets\n    //\n\n    template<class AFFINITIES, class EDGES, class EDGE_MAP, class F>\n    std::size_t affinitiesToEdgeMapWithOffsetsImpl(const AFFINITIES & affinities,\n                                                   const std::vector<std::vector<int>> & offsets,\n                                                   EDGES & edges,\n                                                   EDGE_MAP & edgeMap,\n                                                   F & sampler) const {\n        NIFTY_CHECK_OP(affinities.shape()[0], ==, offsets.size(), \"wrong shape\")\n        for(auto d=1; d<DIM+1; ++d){\n            NIFTY_CHECK_OP(shape(d-1), ==, affinities.shape()[d], \"wrong shape\")\n        }\n\n        typedef nifty::array::StaticArray<int64_t, DIM+1> EdgeCoordType;\n        EdgeCoordType edgeShape;\n        edgeShape[0] = offsets.size();\n        for(unsigned d = 0; d < DIM; ++d) {\n            edgeShape[d + 1] = shape(d);\n        }\n\n        CoordinateType cU, cV;\n        std::size_t edgeId = 0;\n        tools::forEachCoordinate(edgeShape, [&](const EdgeCoordType & edgeCoord) {\n            const auto & offset = offsets[edgeCoord[0]];\n\n            for(unsigned d = 0; d < DIM; ++d) {\n                cU[d] = edgeCoord[d + 1];\n                cV[d] = edgeCoord[d + 1] + offset[d];\n                // range check\n                if(cV[d] >= shape(d) || cV[d] < 0) {\n                    return;\n                }\n            }\n\n            // check if we keep this edge\n            if(!sampler(edgeCoord)) {\n                return;\n            }\n\n            const std::size_t u = coordinateToNode(cU);\n            const std::size_t v = coordinateToNode(cV);\n\n            edgeMap(edgeId) = xtensor::read(affinities, edgeCoord.asStdArray());\n            edges(edgeId, 0) = std::min(u, v);\n            edges(edgeId, 1) = std::max(u, v);\n            ++edgeId;\n\n        });\n        return edgeId;\n    }\n\n    //\n    // implementation of projectEdgeIdsToPixels (with offsets)\n    //\n\n    template<class RET, class SAMPLER>\n    void projectEdgeIdsToPixelsImpl(\n        const std::vector<std::vector<int>> & offsets,\n        SAMPLER & sampler,\n        RET & ret\n    ) const {\n        typedef typename RET::value_type retType;\n        typedef nifty::array::StaticArray<int64_t, DIM+1> EdgeCoordType;\n\n        EdgeCoordType edgeShape;\n        edgeShape[0] = offsets.size();\n        for(unsigned d = 0; d < DIM; ++d) {\n            edgeShape[d + 1] = shape(d);\n        }\n\n        CoordinateType cV;\n        retType edgeId = 0;\n        nifty::tools::forEachCoordinate(edgeShape, [&](const auto & edgeCoord){\n            const auto & offset = offsets[edgeCoord[0]];\n            bool isValid = true;\n\n            for(unsigned d = 0; d < DIM; ++d) {\n                cV[d] = edgeCoord[d + 1] + offset[d];\n                // range check\n                if(cV[d] >= shape(d) || cV[d] < 0) {\n                    isValid = false;\n                    break;\n                }\n            }\n\n            if(!isValid) {\n                xtensor::write(ret, edgeCoord, -1);\n                return;\n            }\n\n            if(!sampler(edgeCoord)) {\n                xtensor::write(ret, edgeCoord, -1);\n                return;\n            }\n            xtensor::write(ret, edgeCoord, edgeId);\n            ++edgeId;\n        });\n    }\n\n\nprivate:\n    andres::graph::GridGraph<DIM> gridGraph_;\n};\n\n\n\n} // namespace nifty::graph\n} // namespace nifty\n", "meta": {"hexsha": "354f46b6802b11545e7b99604a6072713e16ca6b", "size": 33731, "ext": "hxx", "lang": "C++", "max_stars_repo_path": "include/nifty/graph/undirected_grid_graph.hxx", "max_stars_repo_name": "DerThorsten/n3p", "max_stars_repo_head_hexsha": "c4bd4cd90f20e68f0dbd62587aba28e4752a0ac1", "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/undirected_grid_graph.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/undirected_grid_graph.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": 33.4965243297, "max_line_length": 114, "alphanum_fraction": 0.5341080905, "num_tokens": 7708, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6370307944803832, "lm_q2_score": 0.5156199157230157, "lm_q1q2_score": 0.3284657645629409}}
{"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    HessianFactor.cpp\n * @author  Richard Roberts\n * @date    Dec 8, 2010\n */\n\n#include <sstream>\n\n#include <boost/foreach.hpp>\n#include <boost/format.hpp>\n#include <boost/make_shared.hpp>\n#include <boost/tuple/tuple.hpp>\n#include <boost/bind.hpp>\n\n#include <gtsam/base/debug.h>\n#include <gtsam/base/timing.h>\n#include <gtsam/base/Matrix.h>\n#include <gtsam/base/FastMap.h>\n#include <gtsam/base/cholesky.h>\n#include <gtsam/linear/linearExceptions.h>\n#include <gtsam/linear/GaussianConditional.h>\n#include <gtsam/linear/HessianFactor.h>\n#include <gtsam/linear/JacobianFactor.h>\n#include <gtsam/linear/GaussianFactorGraph.h>\n#include <gtsam/linear/GaussianBayesNet.h>\n\nusing namespace std;\n\nnamespace gtsam {\n\n/* ************************************************************************* */\nstring SlotEntry::toString() const {\n\tostringstream oss;\n\toss << \"SlotEntry: slot=\" << slot << \", dim=\" << dimension;\n\treturn oss.str();\n}\n\n/* ************************************************************************* */\nvoid HessianFactor::assertInvariants() const {\n\tGaussianFactor::assertInvariants(); // The base class checks for unique keys\n}\n\n/* ************************************************************************* */\nHessianFactor::HessianFactor(const HessianFactor& gf) :\n    \t\tGaussianFactor(gf), info_(matrix_) {\n\tinfo_.assignNoalias(gf.info_);\n\tassertInvariants();\n}\n\n/* ************************************************************************* */\nHessianFactor::HessianFactor() : info_(matrix_) {\n  // The empty HessianFactor has only a constant error term of zero\n  FastVector<size_t> dims;\n  dims.push_back(1);\n  info_.resize(dims.begin(), dims.end(), false);\n  info_(0,0)(0,0) = 0.0;\n\tassertInvariants();\n}\n\n/* ************************************************************************* */\nHessianFactor::HessianFactor(Index j, const Matrix& G, const Vector& g, double f) :\n      \t\tGaussianFactor(j), info_(matrix_) {\n\tif(G.rows() != G.cols() || G.rows() != g.size())\n\t\tthrow invalid_argument(\"Inconsistent matrix and/or vector dimensions in HessianFactor constructor\");\n\tsize_t dims[] = { G.rows(), 1 };\n\tInfoMatrix fullMatrix(G.rows() + 1, G.rows() + 1);\n\tBlockInfo infoMatrix(fullMatrix, dims, dims+2);\n\tinfoMatrix(0,0) = G;\n\tinfoMatrix.column(0,1,0) = g;\n\tinfoMatrix(1,1)(0,0) = f;\n\tinfoMatrix.swap(info_);\n\tassertInvariants();\n}\n\n/* ************************************************************************* */\n// error is 0.5*(x-mu)'*inv(Sigma)*(x-mu) = 0.5*(x'*G*x - 2*x'*G*mu + mu'*G*mu)\n// where G = inv(Sigma), g = G*mu, f = mu'*G*mu = mu'*g\nHessianFactor::HessianFactor(Index j, const Vector& mu, const Matrix& Sigma) :\n\t\tGaussianFactor(j), info_(matrix_) {\n\tif (Sigma.rows() != Sigma.cols() || Sigma.rows() != mu.size()) throw invalid_argument(\n\t\t\t\"Inconsistent matrix and/or vector dimensions in HessianFactor constructor\");\n\tMatrix G = inverse(Sigma);\n\tVector g = G * mu;\n\tdouble f = dot(mu, g);\n\tsize_t dims[] = { G.rows(), 1 };\n\tInfoMatrix fullMatrix(G.rows() + 1, G.rows() + 1);\n\tBlockInfo infoMatrix(fullMatrix, dims, dims + 2);\n\tinfoMatrix(0, 0) = G;\n\tinfoMatrix.column(0, 1, 0) = g;\n\tinfoMatrix(1, 1)(0, 0) = f;\n\tinfoMatrix.swap(info_);\n\tassertInvariants();\n}\n\n/* ************************************************************************* */\nHessianFactor::HessianFactor(Index j1, Index j2,\n\t\tconst Matrix& G11, const Matrix& G12, const Vector& g1,\n\t\tconst Matrix& G22, const Vector& g2, double f) :\n\t\tGaussianFactor(j1, j2), info_(matrix_) {\n\tif(G11.rows() != G11.cols() || G11.rows() != G12.rows() || G11.rows() != g1.size() ||\n\t\t\tG22.cols() != G12.cols() || G22.cols() != g2.size())\n\t\tthrow invalid_argument(\"Inconsistent matrix and/or vector dimensions in HessianFactor constructor\");\n\tsize_t dims[] = { G11.rows(), G22.rows(), 1 };\n\tInfoMatrix fullMatrix(G11.rows() + G22.rows() + 1, G11.rows() + G22.rows() + 1);\n\tBlockInfo infoMatrix(fullMatrix, dims, dims+3);\n\tinfoMatrix(0,0) = G11;\n\tinfoMatrix(0,1) = G12;\n\tinfoMatrix.column(0,2,0) = g1;\n\tinfoMatrix(1,1) = G22;\n\tinfoMatrix.column(1,2,0) = g2;\n\tinfoMatrix(2,2)(0,0) = f;\n\tinfoMatrix.swap(info_);\n\tassertInvariants();\n}\n\n/* ************************************************************************* */\nHessianFactor::HessianFactor(Index j1, Index j2, Index j3,\n    const Matrix& G11, const Matrix& G12, const Matrix& G13, const Vector& g1,\n    const Matrix& G22, const Matrix& G23, const Vector& g2,\n    const Matrix& G33, const Vector& g3, double f) :\n    GaussianFactor(j1, j2, j3), info_(matrix_) {\n\tif(G11.rows() != G11.cols() || G11.rows() != G12.rows() || G11.rows() != G13.rows()  || G11.rows() != g1.size() ||\n\t\t\tG22.cols() != G12.cols() || G33.cols() != G13.cols() ||  G22.cols() != g2.size() || G33.cols() != g3.size())\n\t\tthrow invalid_argument(\"Inconsistent matrix and/or vector dimensions in HessianFactor constructor\");\n\tsize_t dims[] = { G11.rows(), G22.rows(), G33.rows(), 1 };\n\tInfoMatrix fullMatrix(G11.rows() + G22.rows() + G33.rows() + 1, G11.rows() + G22.rows() + G33.rows() + 1);\n\tBlockInfo infoMatrix(fullMatrix, dims, dims+4);\n\tinfoMatrix(0,0) = G11;\n\tinfoMatrix(0,1) = G12;\n\tinfoMatrix(0,2) = G13;\n\tinfoMatrix.column(0,3,0) = g1;\n\tinfoMatrix(1,1) = G22;\n\tinfoMatrix(1,2) = G23;\n\tinfoMatrix.column(1,3,0) = g2;\n\tinfoMatrix(2,2) = G33;\n\tinfoMatrix.column(2,3,0) = g3;\n\tinfoMatrix(3,3)(0,0) = f;\n\tinfoMatrix.swap(info_);\n\tassertInvariants();\n}\n\n/* ************************************************************************* */\nHessianFactor::HessianFactor(const std::vector<Index>& js, const std::vector<Matrix>& Gs,\n        const std::vector<Vector>& gs, double f) : GaussianFactor(js), info_(matrix_) {\n\n  // Get the number of variables\n  size_t variable_count = js.size();\n\n  // Verify the provided number of entries in the vectors are consistent\n  if(gs.size() != variable_count || Gs.size() != (variable_count*(variable_count+1))/2)\n    throw invalid_argument(\"Inconsistent number of entries between js, Gs, and gs in HessianFactor constructor.\\nThe number of keys provided \\\n        in js must match the number of linear vector pieces in gs. The number of upper-diagonal blocks in Gs must be n*(n+1)/2\");\n\n  // Verify the dimensions of each provided matrix are consistent\n  // Note: equations for calculating the indices derived from the \"sum of an arithmetic sequence\" formula\n  for(size_t i = 0; i < variable_count; ++i){\n    int block_size = gs[i].size();\n    // Check rows\n    for(size_t j = 0; j < variable_count-i; ++j){\n      size_t index = i*(2*variable_count - i + 1)/2 + j;\n      if(Gs[index].rows() != block_size){\n        throw invalid_argument(\"Inconsistent matrix and/or vector dimensions in HessianFactor constructor\");\n      }\n    }\n    // Check cols\n    for(size_t j = 0; j <= i; ++j){\n      size_t index = j*(2*variable_count - j + 1)/2 + (i-j);\n      if(Gs[index].cols() != block_size){\n        throw invalid_argument(\"Inconsistent matrix and/or vector dimensions in HessianFactor constructor\");\n      }\n    }\n  }\n\n  // Create the dims vector\n  size_t* dims = (size_t*)alloca(sizeof(size_t)*(variable_count+1)); // FIXME: alloca is bad, just ask Google.\n  size_t total_size = 0;\n  for(unsigned int i = 0; i < variable_count; ++i){\n    dims[i] = gs[i].size();\n    total_size += gs[i].size();\n  }\n  dims[variable_count] = 1;\n  total_size += 1;\n\n  // Fill in the internal matrix with the supplied blocks\n  InfoMatrix fullMatrix(total_size, total_size);\n  BlockInfo infoMatrix(fullMatrix, dims, dims+variable_count+1);\n  size_t index = 0;\n  for(size_t i = 0; i < variable_count; ++i){\n    for(size_t j = i; j < variable_count; ++j){\n      infoMatrix(i,j) = Gs[index++];\n    }\n    infoMatrix.column(i,variable_count,0) = gs[i];\n  }\n  infoMatrix(variable_count,variable_count)(0,0) = f;\n\n  // update the BlockView variable\n  infoMatrix.swap(info_);\n\n  assertInvariants();\n}\n\n/* ************************************************************************* */\nHessianFactor::HessianFactor(const GaussianConditional& cg) : GaussianFactor(cg), info_(matrix_) {\n\tJacobianFactor jf(cg);\n\tinfo_.copyStructureFrom(jf.Ab_);\n\tmatrix_.noalias() = jf.matrix_.transpose() * jf.matrix_;\n\tassertInvariants();\n}\n\n/* ************************************************************************* */\nHessianFactor::HessianFactor(const GaussianFactor& gf) : info_(matrix_) {\n\t// Copy the variable indices\n\t(GaussianFactor&)(*this) = gf;\n\t// Copy the matrix data depending on what type of factor we're copying from\n\tif(dynamic_cast<const JacobianFactor*>(&gf)) {\n\t\tconst JacobianFactor& jf(static_cast<const JacobianFactor&>(gf));\n\t\tif(jf.model_->isConstrained())\n\t\t\tthrow invalid_argument(\"Cannot construct HessianFactor from JacobianFactor with constrained noise model\");\n\t\telse {\n\t\t\tVector invsigmas = jf.model_->invsigmas().cwiseProduct(jf.model_->invsigmas());\n\t\t\tinfo_.copyStructureFrom(jf.Ab_);\n\t\t\tBlockInfo::constBlock A = jf.Ab_.full();\n\t\t\tmatrix_.noalias() = A.transpose() * invsigmas.asDiagonal() * A;\n\t\t}\n\t} else if(dynamic_cast<const HessianFactor*>(&gf)) {\n\t\tconst HessianFactor& hf(static_cast<const HessianFactor&>(gf));\n\t\tinfo_.assignNoalias(hf.info_);\n\t} else\n\t\tthrow std::invalid_argument(\"In HessianFactor(const GaussianFactor& gf), gf is neither a JacobianFactor nor a HessianFactor\");\n\tassertInvariants();\n}\n\n/* ************************************************************************* */\nHessianFactor::HessianFactor(const FactorGraph<GaussianFactor>& factors,\n\t\tconst vector<size_t>& dimensions, const Scatter& scatter) :\n\t\tinfo_(matrix_) {\n\n\tconst bool debug = ISDEBUG(\"EliminateCholesky\");\n\t// Form Ab' * Ab\n\ttic(1, \"allocate\");\n\tinfo_.resize(dimensions.begin(), dimensions.end(), false);\n\t// Fill in keys\n\tkeys_.resize(scatter.size());\n\tstd::transform(scatter.begin(), scatter.end(), keys_.begin(), boost::bind(&Scatter::value_type::first, ::_1));\n\ttoc(1, \"allocate\");\n\ttic(2, \"zero\");\n\tmatrix_.noalias() = Matrix::Zero(matrix_.rows(),matrix_.cols());\n\ttoc(2, \"zero\");\n\ttic(3, \"update\");\n\tif (debug) cout << \"Combining \" << factors.size() << \" factors\" << endl;\n\tBOOST_FOREACH(const GaussianFactor::shared_ptr& factor, factors)\n\t{\n\t\tif(factor) {\n\t\t\tif(shared_ptr hessian = boost::dynamic_pointer_cast<HessianFactor>(factor))\n\t\t\t\tupdateATA(*hessian, scatter);\n\t\t\telse if(JacobianFactor::shared_ptr jacobianFactor = boost::dynamic_pointer_cast<JacobianFactor>(factor))\n\t\t\t\tupdateATA(*jacobianFactor, scatter);\n\t\t\telse\n\t\t\t\tthrow invalid_argument(\"GaussianFactor is neither Hessian nor Jacobian\");\n\t\t}\n\t}\n\ttoc(3, \"update\");\n\n\tif (debug) gtsam::print(matrix_, \"Ab' * Ab: \");\n\n\tassertInvariants();\n}\n\n/* ************************************************************************* */\nHessianFactor& HessianFactor::operator=(const HessianFactor& rhs) {\n  this->Base::operator=(rhs);     // Copy keys\n  info_.assignNoalias(rhs.info_); // Copy matrix and block structure\n  return *this;\n}\n\n/* ************************************************************************* */\nvoid HessianFactor::print(const std::string& s, const IndexFormatter& formatter) const {\n\tcout << s << \"\\n\";\n\tcout << \" keys: \";\n\tfor(const_iterator key=this->begin(); key!=this->end(); ++key)\n\t\tcout << formatter(*key) << \"(\" << this->getDim(key) << \") \";\n\tcout << \"\\n\";\n\tgtsam::print(Matrix(info_.range(0,info_.nBlocks(), 0,info_.nBlocks()).selfadjointView<Eigen::Upper>()), \"Ab^T * Ab: \");\n}\n\n/* ************************************************************************* */\nbool HessianFactor::equals(const GaussianFactor& lf, double tol) const {\n\tif(!dynamic_cast<const HessianFactor*>(&lf))\n\t\treturn false;\n\telse {\n\t\tMatrix thisMatrix = this->info_.full().selfadjointView<Eigen::Upper>();\n\t\tthisMatrix(thisMatrix.rows()-1, thisMatrix.cols()-1) = 0.0;\n\t\tMatrix rhsMatrix = static_cast<const HessianFactor&>(lf).info_.full().selfadjointView<Eigen::Upper>();\n\t\trhsMatrix(rhsMatrix.rows()-1, rhsMatrix.cols()-1) = 0.0;\n\t\treturn equal_with_abs_tol(thisMatrix, rhsMatrix, tol);\n\t}\n}\n\n/* ************************************************************************* */\nMatrix HessianFactor::computeInformation() const {\n  return info_.full().selfadjointView<Eigen::Upper>();\n}\n\n/* ************************************************************************* */\ndouble HessianFactor::error(const VectorValues& c) const {\n\t// error 0.5*(f - 2*x'*g + x'*G*x)\n\tconst double f = constantTerm();\n\tconst double xtg = c.vector().dot(linearTerm());\n\tconst double xGx = c.vector().transpose() * info_.range(0, this->size(), 0, this->size()).selfadjointView<Eigen::Upper>() *\tc.vector();\n\n\treturn 0.5 * (f - 2.0 * xtg +  xGx);\n}\n\n/* ************************************************************************* */\nvoid HessianFactor::updateATA(const HessianFactor& update, const Scatter& scatter) {\n\n\t// This function updates 'combined' with the information in 'update'.\n\t// 'scatter' maps variables in the update factor to slots in the combined\n\t// factor.\n\n\tconst bool debug = ISDEBUG(\"updateATA\");\n\n\t// First build an array of slots\n\ttic(1, \"slots\");\n\tsize_t* slots = (size_t*)alloca(sizeof(size_t)*update.size()); // FIXME: alloca is bad, just ask Google.\n\tsize_t slot = 0;\n\tBOOST_FOREACH(Index j, update) {\n\t\tslots[slot] = scatter.find(j)->second.slot;\n\t\t++ slot;\n\t}\n\ttoc(1, \"slots\");\n\n\tif(debug) {\n\t\tthis->print(\"Updating this: \");\n\t\tupdate.print(\"with (Hessian): \");\n\t}\n\n\t// Apply updates to the upper triangle\n\ttic(3, \"update\");\n\tfor(size_t j2=0; j2<update.info_.nBlocks(); ++j2) {\n\t\tsize_t slot2 = (j2 == update.size()) ? this->info_.nBlocks()-1 : slots[j2];\n\t\tfor(size_t j1=0; j1<=j2; ++j1) {\n\t\t\tsize_t slot1 = (j1 == update.size()) ? this->info_.nBlocks()-1 : slots[j1];\n\t\t\tif(slot2 > slot1) {\n\t\t\t\tif(debug)\n\t\t\t\t\tcout << \"Updating (\" << slot1 << \",\" << slot2 << \") from (\" << j1 << \",\" << j2 << \")\" << endl;\n\t\t\t\tmatrix_.block(info_.offset(slot1), info_.offset(slot2), info_(slot1,slot2).rows(), info_(slot1,slot2).cols()).noalias() +=\n\t\t\t\t\t\tupdate.matrix_.block(update.info_.offset(j1), update.info_.offset(j2), update.info_(j1,j2).rows(), update.info_(j1,j2).cols());\n\t\t\t} else if(slot1 > slot2) {\n\t\t\t\tif(debug)\n\t\t\t\t\tcout << \"Updating (\" << slot2 << \",\" << slot1 << \") from (\" << j1 << \",\" << j2 << \")\" << endl;\n\t\t\t\tmatrix_.block(info_.offset(slot2), info_.offset(slot1), info_(slot2,slot1).rows(), info_(slot2,slot1).cols()).noalias() +=\n\t\t\t\t\t\tupdate.matrix_.block(update.info_.offset(j1), update.info_.offset(j2), update.info_(j1,j2).rows(), update.info_(j1,j2).cols()).transpose();\n\t\t\t} else {\n\t\t\t\tif(debug)\n\t\t\t\t\tcout << \"Updating (\" << slot1 << \",\" << slot2 << \") from (\" << j1 << \",\" << j2 << \")\" << endl;\n\t\t\t\tmatrix_.block(info_.offset(slot1), info_.offset(slot2), info_(slot1,slot2).rows(), info_(slot1,slot2).cols()).triangularView<Eigen::Upper>() +=\n\t\t\t\t\t\tupdate.matrix_.block(update.info_.offset(j1), update.info_.offset(j2), update.info_(j1,j2).rows(), update.info_(j1,j2).cols());\n\t\t\t}\n\t\t\tif(debug) cout << \"Updating block \" << slot1 << \",\" << slot2 << \" from block \" << j1 << \",\" << j2 << \"\\n\";\n\t\t\tif(debug) this->print();\n\t\t}\n\t}\n\ttoc(3, \"update\");\n}\n\n/* ************************************************************************* */\nvoid HessianFactor::updateATA(const JacobianFactor& update, const Scatter& scatter) {\n\n\t// This function updates 'combined' with the information in 'update'.\n\t// 'scatter' maps variables in the update factor to slots in the combined\n\t// factor.\n\n\tconst bool debug = ISDEBUG(\"updateATA\");\n\n\t// First build an array of slots\n\ttic(1, \"slots\");\n\tsize_t* slots = (size_t*)alloca(sizeof(size_t)*update.size()); // FIXME: alloca is bad, just ask Google.\n\tsize_t slot = 0;\n\tBOOST_FOREACH(Index j, update) {\n\t\tslots[slot] = scatter.find(j)->second.slot;\n\t\t++ slot;\n\t}\n\ttoc(1, \"slots\");\n\n\ttic(2, \"form A^T*A\");\n\tif(update.model_->isConstrained())\n\t\tthrow invalid_argument(\"Cannot update HessianFactor from JacobianFactor with constrained noise model\");\n\n\tif(debug) {\n\t\tthis->print(\"Updating this: \");\n\t\tupdate.print(\"with (Jacobian): \");\n\t}\n\n\ttypedef Eigen::Block<const JacobianFactor::AbMatrix> BlockUpdateMatrix;\n\tBlockUpdateMatrix updateA(update.matrix_.block(\n\t\t\tupdate.Ab_.rowStart(),update.Ab_.offset(0), update.Ab_.full().rows(), update.Ab_.full().cols()));\n\tif (debug) cout << \"updateA: \\n\" << updateA << endl;\n\n\tMatrix updateInform;\n\tif(boost::dynamic_pointer_cast<noiseModel::Unit>(update.model_)) {\n\t\tupdateInform.noalias() = updateA.transpose() * updateA;\n\t} else {\n\t\tnoiseModel::Diagonal::shared_ptr diagonal(boost::dynamic_pointer_cast<noiseModel::Diagonal>(update.model_));\n\t\tif(diagonal) {\n\t\t\tVector invsigmas2 = update.model_->invsigmas().cwiseProduct(update.model_->invsigmas());\n\t\t\tupdateInform.noalias() = updateA.transpose() * invsigmas2.asDiagonal() * updateA;\n\t\t} else\n\t\t\tthrow invalid_argument(\"In HessianFactor::updateATA, JacobianFactor noise model is neither Unit nor Diagonal\");\n\t}\n\tif (debug) cout << \"updateInform: \\n\" << updateInform << endl;\n \ttoc(2, \"form A^T*A\");\n\n\t// Apply updates to the upper triangle\n\ttic(3, \"update\");\n\tfor(size_t j2=0; j2<update.Ab_.nBlocks(); ++j2) {\n\t\tsize_t slot2 = (j2 == update.size()) ? this->info_.nBlocks()-1 : slots[j2];\n\t\tfor(size_t j1=0; j1<=j2; ++j1) {\n\t\t\tsize_t slot1 = (j1 == update.size()) ? this->info_.nBlocks()-1 : slots[j1];\n\t\t\tsize_t off0 = update.Ab_.offset(0);\n\t\t\tif(slot2 > slot1) {\n\t\t\t\tif(debug)\n\t\t\t\t\tcout << \"Updating (\" << slot1 << \",\" << slot2 << \") from (\" << j1 << \",\" << j2 << \")\" << endl;\n\t\t\t\tmatrix_.block(info_.offset(slot1), info_.offset(slot2), info_(slot1,slot2).rows(), info_(slot1,slot2).cols()).noalias() +=\n\t\t\t\t\t\tupdateInform.block(update.Ab_.offset(j1)-off0, update.Ab_.offset(j2)-off0, update.Ab_(j1).cols(), update.Ab_(j2).cols());\n\t\t\t} else if(slot1 > slot2) {\n\t\t\t\tif(debug)\n\t\t\t\t\tcout << \"Updating (\" << slot2 << \",\" << slot1 << \") from (\" << j1 << \",\" << j2 << \")\" << endl;\n\t\t\t\tmatrix_.block(info_.offset(slot2), info_.offset(slot1), info_(slot2,slot1).rows(), info_(slot2,slot1).cols()).noalias() +=\n\t\t\t\t\t\tupdateInform.block(update.Ab_.offset(j1)-off0, update.Ab_.offset(j2)-off0, update.Ab_(j1).cols(), update.Ab_(j2).cols()).transpose();\n\t\t\t} else {\n\t\t\t\tif(debug)\n\t\t\t\t\tcout << \"Updating (\" << slot1 << \",\" << slot2 << \") from (\" << j1 << \",\" << j2 << \")\" << endl;\n\t\t\t\tmatrix_.block(info_.offset(slot1), info_.offset(slot2), info_(slot1,slot2).rows(), info_(slot1,slot2).cols()).triangularView<Eigen::Upper>() +=\n\t\t\t\t\t\tupdateInform.block(update.Ab_.offset(j1)-off0, update.Ab_.offset(j2)-off0, update.Ab_(j1).cols(), update.Ab_(j2).cols());\n\t\t\t}\n\t\t\tif(debug) cout << \"Updating block \" << slot1 << \",\" << slot2 << \" from block \" << j1 << \",\" << j2 << \"\\n\";\n\t\t\tif(debug) this->print();\n\t\t}\n\t}\n\ttoc(3, \"update\");\n}\n\n/* ************************************************************************* */\nvoid HessianFactor::partialCholesky(size_t nrFrontals) {\n\tif(!choleskyPartial(matrix_, info_.offset(nrFrontals)))\n\t\tthrow IndeterminantLinearSystemException(this->keys().front());\n}\n\n/* ************************************************************************* */\nGaussianConditional::shared_ptr HessianFactor::splitEliminatedFactor(size_t nrFrontals) {\n\n  static const bool debug = false;\n\n  // Extract conditionals\n  tic(1, \"extract conditionals\");\n  GaussianConditional::shared_ptr conditional(new GaussianConditional());\n  typedef VerticalBlockView<Matrix> BlockAb;\n  BlockAb Ab(matrix_, info_);\n\n  size_t varDim = info_.offset(nrFrontals);\n  Ab.rowEnd() = Ab.rowStart() + varDim;\n\n  // Create one big conditionals with many frontal variables.\n  tic(2, \"construct cond\");\n  Vector sigmas = Vector::Ones(varDim);\n  conditional = boost::make_shared<ConditionalType>(keys_.begin(), keys_.end(), nrFrontals, Ab, sigmas);\n  toc(2, \"construct cond\");\n  if(debug) conditional->print(\"Extracted conditional: \");\n\n  toc(1, \"extract conditionals\");\n\n  // Take lower-right block of Ab_ to get the new factor\n  tic(2, \"remaining factor\");\n  info_.blockStart() = nrFrontals;\n  // Assign the keys\n  vector<Index> remainingKeys(keys_.size() - nrFrontals);\n  remainingKeys.assign(keys_.begin() + nrFrontals, keys_.end());\n  keys_.swap(remainingKeys);\n  toc(2, \"remaining factor\");\n\n  return conditional;\n}\n\n/* ************************************************************************* */\nGaussianFactor::shared_ptr HessianFactor::negate() const {\n  // Copy Hessian Blocks from Hessian factor and invert\n  std::vector<Index> js;\n  std::vector<Matrix> Gs;\n  std::vector<Vector> gs;\n  double f;\n  js.insert(js.end(), begin(), end());\n  for(size_t i = 0; i < js.size(); ++i){\n    for(size_t j = i; j < js.size(); ++j){\n      Gs.push_back( -info(begin()+i, begin()+j) );\n    }\n    gs.push_back( -linearTerm(begin()+i) );\n  }\n  f = -constantTerm();\n\n  // Create the Anti-Hessian Factor from the negated blocks\n  return HessianFactor::shared_ptr(new HessianFactor(js, Gs, gs, f));\n}\n\n} // gtsam\n", "meta": {"hexsha": "e152738fb7a97b772e8fcc9250a281dfab870c72", "size": 21074, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "gtsam/linear/HessianFactor.cpp", "max_stars_repo_name": "sdmiller/gtsam_pcl", "max_stars_repo_head_hexsha": "1e607bd75090d35e325a8fb37a6c5afe630f1207", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 11.0, "max_stars_repo_stars_event_min_datetime": "2015-02-04T16:41:47.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-10T07:02:44.000Z", "max_issues_repo_path": "gtsam/linear/HessianFactor.cpp", "max_issues_repo_name": "sdmiller/gtsam_pcl", "max_issues_repo_head_hexsha": "1e607bd75090d35e325a8fb37a6c5afe630f1207", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "gtsam/linear/HessianFactor.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.7620889749, "max_line_length": 147, "alphanum_fraction": 0.6095188384, "num_tokens": 5699, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6370307944803831, "lm_q2_score": 0.5156199157230157, "lm_q1q2_score": 0.32846576456294085}}
{"text": "#ifndef MAPNIK_SIMPLIFY_CONVERTER_HPP\r\n#define MAPNIK_SIMPLIFY_CONVERTER_HPP\r\n\r\n// mapnik\r\n#include <mapnik/config.hpp>\r\n#include <mapnik/box2d.hpp>\r\n#include <mapnik/vertex.hpp>\r\n#include <mapnik/simplify.hpp>\r\n#include <mapnik/noncopyable.hpp>\r\n\r\n// stl\r\n#include <limits>\r\n#include <set>\r\n#include <vector>\r\n#include <deque>\r\n#include <cmath>\r\n#include <stdexcept>\r\n\r\n// boost\r\n#include <boost/optional.hpp>\r\n\r\nnamespace mapnik\r\n{\r\n\r\nstruct weighted_vertex : private mapnik::noncopyable\r\n{\r\n    vertex2d coord;\r\n    double weight;\r\n    weighted_vertex *prev;\r\n    weighted_vertex *next;\r\n\r\n    weighted_vertex(vertex2d coord_) :\r\n        coord(coord_),\r\n        weight(std::numeric_limits<double>::infinity()),\r\n        prev(NULL),\r\n        next(NULL) {}\r\n\r\n    double nominalWeight()\r\n    {\r\n        if (prev == NULL || next == NULL || coord.cmd != SEG_LINETO) {\r\n            return std::numeric_limits<double>::infinity();\r\n        }\r\n        vertex2d const& A = prev->coord;\r\n        vertex2d const& B = next->coord;\r\n        vertex2d const& C = coord;\r\n        return std::abs((double)((A.x - C.x) * (B.y - A.y) - (A.x - B.x) * (C.y - A.y))) / 2.0;\r\n    }\r\n\r\n    struct ascending_sort\r\n    {\r\n        bool operator() (const weighted_vertex *a, const weighted_vertex *b)\r\n        {\r\n            return b->weight > a->weight;\r\n        }\r\n    };\r\n};\r\n\r\nstruct sleeve\r\n{\r\n    vertex2d v[5];\r\n\r\n    sleeve(vertex2d const& v0, vertex2d const& v1, double offset)\r\n    {\r\n        double a = std::atan2((v1.y - v0.y), (v1.x - v0.x));\r\n        double dx = offset * std::cos(a);\r\n        double dy = offset * std::sin(a);\r\n        v[0].x = v0.x + dy;\r\n        v[0].y = v0.y - dx;\r\n        v[1].x = v0.x - dy;\r\n        v[1].y = v0.y + dx;\r\n        v[2].x = v1.x - dy;\r\n        v[2].y = v1.y + dx;\r\n        v[3].x = v1.x + dy;\r\n        v[3].y = v1.y - dx;\r\n        v[4].x = v0.x + dy;\r\n        v[4].y = v0.y - dx;\r\n    }\r\n\r\n    bool inside(vertex2d const& q)\r\n    {\r\n        bool inside=false;\r\n\r\n        for (unsigned i=0;i<4;++i)\r\n        {\r\n            if ((((v[i+1].y <= q.y) && (q.y < v[i].y)) ||\r\n                 ((v[i].y <= q.y) && (q.y < v[i+1].y))) &&\r\n                (q.x < (v[i].x - v[i+1].x) * (q.y - v[i+1].y)/ (v[i].y - v[i+1].y) + v[i+1].x))\r\n                inside=!inside;\r\n        }\r\n        return inside;\r\n    }\r\n    void print()\r\n    {\r\n        std::cerr << \"LINESTRING(\"\r\n                  << v[0].x << \" \" << -v[0].y << \",\"\r\n                  << v[1].x << \" \" << -v[1].y << \",\"\r\n                  << v[2].x << \" \" << -v[2].y << \",\"\r\n                  << v[3].x << \" \" << -v[3].y << \",\"\r\n                  << v[0].x << \" \" << -v[0].y << \")\" << std::endl;\r\n\r\n    }\r\n};\r\n\r\ntemplate <typename Geometry>\r\nstruct MAPNIK_DECL simplify_converter\r\n{\r\npublic:\r\n    simplify_converter(Geometry& geom)\r\n        : geom_(geom),\r\n        tolerance_(0.0),\r\n        status_(initial),\r\n        algorithm_(radial_distance),\r\n        pos_(0)\r\n    {}\r\n\r\n    enum status\r\n    {\r\n        initial,\r\n        process,\r\n        closing,\r\n        end,\r\n        cache\r\n    };\r\n\r\n    simplify_algorithm_e get_simplify_algorithm()\r\n    {\r\n        return algorithm_;\r\n    }\r\n\r\n    void set_simplify_algorithm(simplify_algorithm_e value)\r\n    {\r\n        if (algorithm_ != value)\r\n        {\r\n            algorithm_ = value;\r\n            reset();\r\n        }\r\n    }\r\n\r\n    double get_simplify_tolerance()\r\n    {\r\n        return tolerance_;\r\n    }\r\n\r\n    void set_simplify_tolerance(double value)\r\n    {\r\n        if (tolerance_ != value) {\r\n            tolerance_ = value;\r\n            reset();\r\n        }\r\n    }\r\n\r\n    void reset()\r\n    {\r\n        geom_.rewind(0);\r\n        vertices_.clear();\r\n        status_ = initial;\r\n        pos_ = 0;\r\n    }\r\n\r\n    void rewind(unsigned int) const\r\n    {\r\n        pos_ = 0;\r\n    }\r\n\r\n    unsigned vertex(double* x, double* y)\r\n    {\r\n        if (tolerance_ == 0.0)\r\n            return geom_.vertex(x, y);\r\n\r\n        if (status_ == initial)\r\n            init_vertices();\r\n\r\n        return output_vertex(x, y);\r\n    }\r\n\r\nprivate:\r\n    unsigned output_vertex(double* x, double* y)\r\n    {\r\n        switch (algorithm_)\r\n        {\r\n        case visvalingam_whyatt:\r\n            return output_vertex_cached(x, y);\r\n        case radial_distance:\r\n            return output_vertex_distance(x, y);\r\n        case zhao_saalfeld:\r\n            return output_vertex_sleeve(x, y);\r\n        default:\r\n            throw std::runtime_error(\"simplification algorithm not yet implemented\");\r\n        }\r\n\r\n        return SEG_END;\r\n    }\r\n\r\n    unsigned output_vertex_cached(double* x, double* y) {\r\n        if (pos_ >= vertices_.size())\r\n            return SEG_END;\r\n\r\n        previous_vertex_ = vertices_[pos_];\r\n        *x = previous_vertex_.x;\r\n        *y = previous_vertex_.y;\r\n        pos_++;\r\n        return previous_vertex_.cmd;\r\n    }\r\n\r\n    unsigned output_vertex_distance(double* x, double* y) {\r\n        if (status_ == closing) {\r\n            status_ = end;\r\n            return SEG_CLOSE;\r\n        }\r\n\r\n        vertex2d last(vertex2d::no_init);\r\n        vertex2d vtx(vertex2d::no_init);\r\n        while ((vtx.cmd = geom_.vertex(&vtx.x, &vtx.y)) != SEG_END)\r\n        {\r\n            if (vtx.cmd == SEG_LINETO) {\r\n                if (distance_to_previous(vtx) > tolerance_) {\r\n                    // Only output a vertex if it's far enough away from the previous\r\n                    break;\r\n                } else {\r\n                    last = vtx;\r\n                    // continue\r\n                }\r\n            } else if (vtx.cmd == SEG_CLOSE) {\r\n                if (last.cmd == vertex2d::no_init) {\r\n                    // The previous vertex was already output in the previous call.\r\n                    // We can now safely output SEG_CLOSE.\r\n                    status_ = end;\r\n                } else {\r\n                    // We eliminated the previous point because it was too close, but\r\n                    // we have to output it now anyway, since this is the end of the\r\n                    // vertex stream. Make sure that we output SEG_CLOSE in the next call.\r\n                    vtx = last;\r\n                    status_ = closing;\r\n                }\r\n                break;\r\n            } else if (vtx.cmd == SEG_MOVETO) {\r\n                break;\r\n            } else {\r\n                throw std::runtime_error(\"Unknown vertex command\");\r\n            }\r\n        }\r\n\r\n        previous_vertex_ = vtx;\r\n        *x = vtx.x;\r\n        *y = vtx.y;\r\n        return vtx.cmd;\r\n    }\r\n\r\n    template <typename Iterator>\r\n    bool fit_sleeve(Iterator itr,Iterator end, vertex2d const& v)\r\n    {\r\n        sleeve s(*itr,v,tolerance_);\r\n        ++itr; // skip first vertex\r\n        for (; itr!=end; ++itr)\r\n        {\r\n            if (!s.inside(*itr))\r\n            {\r\n                return false;\r\n            }\r\n        }\r\n        return true;\r\n    }\r\n\r\n    unsigned output_vertex_sleeve(double* x, double* y)\r\n    {\r\n        vertex2d vtx(vertex2d::no_init);\r\n        std::size_t min_size = 1;\r\n        while ((vtx.cmd = geom_.vertex(&vtx.x, &vtx.y)) != SEG_END)\r\n        {\r\n            //if ((std::fabs(vtx.x - previous_vertex_.x) < 0.5) &&\r\n            //    (std::fabs(vtx.y - previous_vertex_.y) < 0.5))\r\n            //    continue;\r\n\r\n            if (status_ == cache &&\r\n                vertices_.size() >= min_size)\r\n                status_ = process;\r\n\r\n            previous_vertex_ = vtx;\r\n\r\n            if (vtx.cmd == SEG_MOVETO)\r\n            {\r\n                if (sleeve_cont_.size() > 1)\r\n                {\r\n                    vertices_.push_back(sleeve_cont_.back());\r\n                    sleeve_cont_.clear();\r\n                }\r\n                vertices_.push_back(vtx);\r\n                sleeve_cont_.push_back(vtx);\r\n                if (status_ == process) break;\r\n            }\r\n            else if (vtx.cmd == SEG_LINETO)\r\n            {\r\n                if (sleeve_cont_.size() > 1 && !fit_sleeve(sleeve_cont_.begin(), sleeve_cont_.end(), vtx))\r\n                {\r\n                    vertex2d last = vtx;\r\n                    vtx = sleeve_cont_.back();\r\n                    sleeve_cont_.clear();\r\n                    sleeve_cont_.push_back(vtx);\r\n                    sleeve_cont_.push_back(last);\r\n                    vertices_.push_back(vtx);\r\n                    if (status_ == process) break;\r\n                }\r\n                else\r\n                {\r\n                    sleeve_cont_.push_back(vtx);\r\n                }\r\n            }\r\n            else if (vtx.cmd == SEG_CLOSE)\r\n            {\r\n                if (sleeve_cont_.size() > 1)\r\n                {\r\n                    vertices_.push_back(sleeve_cont_.back());\r\n                    sleeve_cont_.clear();\r\n                }\r\n                vertices_.push_back(vtx);\r\n                if (status_ == process) break;\r\n            }\r\n        }\r\n\r\n        if (status_ == cache)\r\n        {\r\n            if (vertices_.size() < min_size)\r\n                return SEG_END;\r\n            status_ = process;\r\n        }\r\n\r\n        if (vtx.cmd == SEG_END)\r\n        {\r\n            if (sleeve_cont_.size() > 1)\r\n            {\r\n                vertices_.push_back(sleeve_cont_.back());\r\n            }\r\n            sleeve_cont_.clear();\r\n            vertices_.push_back(vtx);\r\n        }\r\n\r\n        if (vertices_.size() > 0)\r\n        {\r\n            vertex2d v = vertices_.front();\r\n            vertices_.pop_front();\r\n            *x = v.x;\r\n            *y = v.y;\r\n            return v.cmd;\r\n        }\r\n        return SEG_END;\r\n    }\r\n\r\n    double distance_to_previous(vertex2d const& vtx) {\r\n        double dx = previous_vertex_.x - vtx.x;\r\n        double dy = previous_vertex_.y - vtx.y;\r\n        return dx * dx + dy * dy;\r\n    }\r\n\r\n    status init_vertices()\r\n    {\r\n        if (status_ != initial) // already initialized\r\n            return status_;\r\n\r\n        reset();\r\n\r\n        switch (algorithm_) {\r\n            case visvalingam_whyatt:\r\n                return init_vertices_visvalingam_whyatt();\r\n            case radial_distance:\r\n                // Use\r\n                vertices_.push_back(vertex2d(vertex2d::no_init));\r\n                return status_ = process;\r\n            case zhao_saalfeld:\r\n                return status_ = cache;\r\n            default:\r\n                throw std::runtime_error(\"simplification algorithm not yet implemented\");\r\n        }\r\n    }\r\n\r\n    status init_vertices_visvalingam_whyatt()\r\n    {\r\n        typedef std::set<weighted_vertex *, weighted_vertex::ascending_sort> VertexSet;\r\n        typedef std::vector<weighted_vertex *> VertexList;\r\n\r\n        std::vector<weighted_vertex *> v_list;\r\n        vertex2d vtx(vertex2d::no_init);\r\n        while ((vtx.cmd = geom_.vertex(&vtx.x, &vtx.y)) != SEG_END)\r\n        {\r\n            v_list.push_back(new weighted_vertex(vtx));\r\n        }\r\n\r\n        if (v_list.empty()) {\r\n            return status_ = process;\r\n        }\r\n\r\n        // Connect the vertices in a linked list and insert them into the set.\r\n        VertexSet v;\r\n        for (VertexList::iterator i = v_list.begin(); i != v_list.end(); ++i)\r\n        {\r\n            (*i)->prev = i == v_list.begin() ? NULL : *(i - 1);\r\n            (*i)->next = i + 1 == v_list.end() ? NULL : *(i + 1);\r\n            (*i)->weight = (*i)->nominalWeight();\r\n            v.insert(*i);\r\n        }\r\n\r\n        // Use Visvalingam-Whyatt algorithm to calculate each point's weight.\r\n        while (v.size() > 0)\r\n        {\r\n            VertexSet::iterator lowest = v.begin();\r\n            weighted_vertex *removed = *lowest;\r\n            if (removed->weight >= tolerance_) {\r\n                break;\r\n            }\r\n\r\n            v.erase(lowest);\r\n\r\n            // Connect adjacent vertices with each other\r\n            if (removed->prev) removed->prev->next = removed->next;\r\n            if (removed->next) removed->next->prev = removed->prev;\r\n            // Adjust weight and reinsert prev/next to move them to their correct position.\r\n            if (removed->prev) {\r\n                v.erase(removed->prev);\r\n                removed->prev->weight = std::max(removed->weight, removed->prev->nominalWeight());\r\n                v.insert(removed->prev);\r\n            }\r\n            if (removed->next) {\r\n                v.erase(removed->next);\r\n                removed->next->weight = std::max(removed->weight, removed->next->nominalWeight());\r\n                v.insert(removed->next);\r\n            }\r\n        }\r\n\r\n        v.clear();\r\n\r\n        // Traverse the remaining list and insert them into the vertex cache.\r\n        for (VertexList::iterator i = v_list.begin(); i != v_list.end(); ++i)\r\n        {\r\n            if ((*i)->weight >= tolerance_)\r\n            {\r\n                vertices_.push_back((*i)->coord);\r\n            }\r\n            delete *i;\r\n        }\r\n\r\n        // Initialization finished.\r\n        return status_ = process;\r\n    }\r\n\r\n    Geometry&                       geom_;\r\n    double                          tolerance_;\r\n    status                          status_;\r\n    simplify_algorithm_e            algorithm_;\r\n    std::deque<vertex2d>            vertices_;\r\n    std::deque<vertex2d>            sleeve_cont_;\r\n    vertex2d                        previous_vertex_;\r\n    mutable size_t                  pos_;\r\n};\r\n\r\n\r\n}\r\n\r\n#endif // MAPNIK_SIMPLIFY_CONVERTER_HPP\r\n", "meta": {"hexsha": "a320d19e7ed7c40d8687c3cdcf5d0cc06129c05d", "size": 13286, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "external/include/mapnik/simplify_converter.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/simplify_converter.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/simplify_converter.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": 29.0087336245, "max_line_length": 107, "alphanum_fraction": 0.4639470119, "num_tokens": 3077, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6370307806984444, "lm_q2_score": 0.5156199157230157, "lm_q1q2_score": 0.3284657574566988}}
{"text": "#include \"CALPHADConcSolverTernary.h\"\n#include \"CALPHADFreeEnergyFunctionsTernary.h\"\n#include \"CALPHADFunctions.h\"\n#include \"CALPHADSpeciesPhaseGibbsEnergy.h\"\n#include \"PhysicalConstants.h\"\n\n#include <chrono>\n\n#include <boost/optional/optional.hpp>\n#include <boost/property_tree/json_parser.hpp>\n#include <boost/property_tree/ptree.hpp>\n\n#include <iomanip>\n#include <iostream>\n#include <string>\n\n#include <omp.h>\n\nnamespace pt = boost::property_tree;\n\ntypedef std::chrono::high_resolution_clock Clock;\n\nint main(int argc, char* argv[])\n{\n    const int N = 10000000;\n\n#ifdef _OPENMP\n    std::cout << \"Compiled by an OpenMP-compliant implementation.\\n\";\n    std::cout << \"Run test with \" << omp_get_max_threads() << \" threads\"\n              << std::endl;\n#endif\n\n    std::cout << \" Read CALPHAD database...\" << std::endl;\n    pt::ptree calphad_db;\n    try\n    {\n        pt::read_json(\"../thermodynamic_data/calphadMoNbTa.json\", calphad_db);\n    }\n    catch (std::exception& e)\n    {\n        std::cerr << \"exception caught: \" << e.what() << std::endl;\n    }\n\n    double temperature = 2923.;\n\n    CalphadDataType LmixABPhaseL[4][2];\n    CalphadDataType LmixABPhaseA[4][2];\n\n    CalphadDataType LmixACPhaseL[4][2];\n    CalphadDataType LmixACPhaseA[4][2];\n\n    CalphadDataType LmixBCPhaseL[4][2];\n    CalphadDataType LmixBCPhaseA[4][2];\n\n    CalphadDataType LmixABCPhaseL[3][2];\n    CalphadDataType LmixABCPhaseA[3][2];\n\n    {\n        std::string dbnamemixL(\"LmixABCPhaseL\");\n        if (calphad_db.get_child_optional(dbnamemixL))\n        {\n            pt::ptree& Lmix0_db = calphad_db.get_child(dbnamemixL);\n            Thermo4PFM::readLmixTernaryParameters(Lmix0_db, LmixABCPhaseL);\n        }\n        else\n        {\n            for (int j = 0; j < 3; j++)\n                for (int i = 0; i < 2; i++)\n                {\n                    LmixABCPhaseL[j][i] = 0.;\n                }\n        }\n    }\n    {\n        std::string dbnamemixL(\"LmixABCPhaseA\");\n        if (calphad_db.get_child_optional(dbnamemixL))\n        {\n            pt::ptree& Lmix0_db = calphad_db.get_child(dbnamemixL);\n            Thermo4PFM::readLmixTernaryParameters(Lmix0_db, LmixABCPhaseA);\n        }\n        else\n        {\n            for (int j = 0; j < 3; j++)\n                for (int i = 0; i < 2; i++)\n                {\n                    LmixABCPhaseA[j][i] = 0.;\n                }\n        }\n    }\n\n    {\n        std::string dbnamemixL(\"LmixABPhaseL\");\n        pt::ptree Lmix_db = calphad_db.get_child(dbnamemixL);\n        Thermo4PFM::readLmixBinary(Lmix_db, LmixABPhaseL);\n    }\n    {\n        std::string dbnamemixA(\"LmixABPhaseA\");\n        pt::ptree Lmix_db = calphad_db.get_child(dbnamemixA);\n        Thermo4PFM::readLmixBinary(Lmix_db, LmixABPhaseA);\n    }\n    {\n        std::string dbnamemixL(\"LmixACPhaseL\");\n        pt::ptree Lmix_db = calphad_db.get_child(dbnamemixL);\n        Thermo4PFM::readLmixBinary(Lmix_db, LmixACPhaseL);\n    }\n    {\n        std::string dbnamemixA(\"LmixACPhaseA\");\n        pt::ptree Lmix_db = calphad_db.get_child(dbnamemixA);\n        Thermo4PFM::readLmixBinary(Lmix_db, LmixACPhaseA);\n    }\n    {\n        std::string dbnamemixL(\"LmixBCPhaseL\");\n        pt::ptree Lmix_db = calphad_db.get_child(dbnamemixL);\n        Thermo4PFM::readLmixBinary(Lmix_db, LmixBCPhaseL);\n    }\n    {\n        std::string dbnamemixA(\"LmixBCPhaseA\");\n        pt::ptree Lmix_db = calphad_db.get_child(dbnamemixA);\n        Thermo4PFM::readLmixBinary(Lmix_db, LmixBCPhaseA);\n    }\n\n    Thermo4PFM::CALPHADSpeciesPhaseGibbsEnergy g_species_phaseL[3];\n    Thermo4PFM::CALPHADSpeciesPhaseGibbsEnergy g_species_phaseA[3];\n\n    {\n        std::string dbnameL(\"PhaseL\");\n        std::string dbnameA(\"PhaseA\");\n\n        pt::ptree& speciesA_db = calphad_db.get_child(\"SpeciesA\");\n        g_species_phaseL[0].initialize(\"L0\", speciesA_db.get_child(dbnameL));\n        g_species_phaseA[0].initialize(\"A0\", speciesA_db.get_child(dbnameA));\n\n        pt::ptree& speciesB_db = calphad_db.get_child(\"SpeciesB\");\n        g_species_phaseL[1].initialize(\"L1\", speciesB_db.get_child(dbnameL));\n        g_species_phaseA[1].initialize(\"A1\", speciesB_db.get_child(dbnameA));\n\n        pt::ptree& speciesC_db = calphad_db.get_child(\"SpeciesC\");\n        g_species_phaseL[2].initialize(\"L2\", speciesC_db.get_child(dbnameL));\n        g_species_phaseA[2].initialize(\"A2\", speciesC_db.get_child(dbnameA));\n    }\n\n    CalphadDataType fA[2];\n    fA[0] = g_species_phaseL[0].fenergy(temperature);\n    fA[1] = g_species_phaseA[0].fenergy(temperature);\n    // std::cout<<\"fA[0]=\"<<fA[0]<<\", fA[1]=\"<<fA[1]<<std::endl;\n\n    CalphadDataType fB[2];\n    fB[0] = g_species_phaseL[1].fenergy(temperature);\n    fB[1] = g_species_phaseA[1].fenergy(temperature);\n    // std::cout<<\"fB[0]=\"<<fB[0]<<\", fB[1]=\"<<fB[1]<<std::endl;\n\n    CalphadDataType fC[2];\n    fC[0] = g_species_phaseL[2].fenergy(temperature);\n    fC[1] = g_species_phaseA[2].fenergy(temperature);\n\n    CalphadDataType L_AB_L[4];\n    for (int i = 0; i < 4; i++)\n        L_AB_L[i] = LmixABPhaseL[i][0] + temperature * LmixABPhaseL[i][1];\n\n    CalphadDataType L_AB_S[4];\n    for (int i = 0; i < 4; i++)\n        L_AB_S[i] = LmixABPhaseA[i][0] + temperature * LmixABPhaseA[i][1];\n\n    CalphadDataType L_AC_L[4];\n    for (int i = 0; i < 4; i++)\n        L_AC_L[i] = LmixACPhaseL[i][0] + temperature * LmixACPhaseL[i][1];\n\n    CalphadDataType L_AC_S[4];\n    for (int i = 0; i < 4; i++)\n        L_AC_S[i] = LmixACPhaseA[i][0] + temperature * LmixACPhaseA[i][1];\n\n    CalphadDataType L_BC_L[4];\n    for (int i = 0; i < 4; i++)\n        L_BC_L[i] = LmixBCPhaseL[i][0] + temperature * LmixBCPhaseL[i][1];\n\n    CalphadDataType L_BC_S[4];\n    for (int i = 0; i < 4; i++)\n        L_BC_S[i] = LmixBCPhaseA[i][0] + temperature * LmixBCPhaseA[i][1];\n\n    CalphadDataType L_ABC_L[3];\n    for (int i = 0; i < 3; i++)\n        L_ABC_L[i] = LmixABCPhaseL[i][0] + temperature * LmixABCPhaseL[i][1];\n\n    CalphadDataType L_ABC_S[3];\n    for (int i = 0; i < 3; i++)\n        L_ABC_S[i] = LmixABCPhaseA[i][0] + temperature * LmixABCPhaseA[i][1];\n\n    const double RTinv\n        = 1.0 / (Thermo4PFM::gas_constant_R_JpKpmol * temperature);\n\n    double sol[4] = { 0.33, 0.38, 0.32, 0.33 };\n\n    const double deviation = 1.e-4;\n\n#ifndef HAVE_OPENMP_OFFLOAD\n\n    double* xhost = new double[4 * N];\n    for (int i = 0; i < 4 * N; i++)\n    {\n        xhost[i] = -1.;\n    }\n\n    // Host solve\n    {\n        short* nits = new short[N];\n        auto t1     = Clock::now();\n\n#pragma omp parallel for\n        for (int i = 0; i < N; i++)\n        {\n#ifdef _OPENMP\n            if (!omp_is_initial_device()) abort();\n#endif\n            xhost[4 * i]     = sol[0];\n            xhost[4 * i + 1] = sol[1];\n            xhost[4 * i + 2] = sol[2];\n            xhost[4 * i + 3] = sol[3];\n            double hphi      = 0.5 + (i % 100) * deviation;\n            double c0        = 0.33;\n            double c1        = 0.33;\n            Thermo4PFM::CALPHADConcSolverTernary solver;\n            solver.setup(c0, c1, hphi, RTinv, L_AB_L, L_AC_L, L_BC_L, L_AB_S,\n                L_AC_S, L_BC_S, L_ABC_L, L_ABC_S, fA, fB, fC);\n            nits[i] = solver.ComputeConcentration(&xhost[4 * i], 1.e-8, 50);\n        }\n        auto t2 = Clock::now();\n        long int usec\n            = std::chrono::duration_cast<std::chrono::microseconds>(t2 - t1)\n                  .count();\n        std::cout << \"Host time/us/solve:   \" << (double)usec / (double)N\n                  << std::endl;\n\n        std::cout << std::setprecision(12);\n        int n = N > 20 ? 20 : N;\n        for (int i = 0; i < n; i++)\n        {\n            std::cout << \"Host: x=\" << xhost[4 * i] << \",\" << xhost[4 * i + 1]\n                      << \",\" << xhost[4 * i + 2] << \",\" << xhost[4 * i + 3]\n                      << std::endl;\n            std::cout << \"nits=\" << nits[i] << std::endl;\n        }\n        delete[] nits;\n    }\n    delete[] xhost;\n#else\n    double* xdev = new double[4 * N];\n    short* nits  = new short[N];\n\n    // Device solve\n    {\n        for (int i = 0; i < 4 * N; i++)\n        {\n            xdev[i] = -1;\n        }\n\n        // warm-up GPU with a dummy allocation\n        double dummy[N];\n#pragma omp target enter data map(alloc : dummy[:N])\n\n        auto t1 = Clock::now();\n\n// clang-format off\n#pragma omp target map(from : xdev[:4*N]) \\\n                   map(from : nits[:N])\n{\n#pragma omp teams distribute parallel for\n            // clang-format on\n            for (int i = 0; i < N; i++)\n            {\n                // if( omp_is_initial_device() ) abort();\n                xdev[4 * i]     = sol[0];\n                xdev[4 * i + 1] = sol[1];\n                xdev[4 * i + 2] = sol[2];\n                xdev[4 * i + 3] = sol[3];\n\n                double hphi = 0.5 + (i % 100) * deviation;\n                double c0   = 0.33;\n                double c1   = 0.33;\n                class Thermo4PFM::CALPHADConcSolverTernary solver;\n                solver.setup(c0, c1, hphi, RTinv, L_AB_L, L_AC_L, L_BC_L,\n                    L_AB_S, L_AC_S, L_BC_S, L_ABC_L, L_ABC_S, fA, fB, fC);\n                nits[i] = solver.ComputeConcentration(&xdev[4 * i], 1.e-8, 50);\n            }\n        }\n\n        auto t2 = Clock::now();\n\n        long int usec\n            = std::chrono::duration_cast<std::chrono::microseconds>(t2 - t1)\n                  .count();\n        std::cout << \"Device time/us/solve: \" << (double)usec / (double)N\n                  << std::endl;\n\n#pragma omp target exit data map(delete : dummy[:N])\n\n        // print out some results\n        std::cout << std::setprecision(12);\n        int n = N > 20 ? 20 : N;\n        for (int i = 0; i < n; i++)\n        {\n            std::cout << \"Dev: x=\" << xdev[4 * i] << \",\" << xdev[4 * i + 1]\n                      << \",\" << xdev[4 * i + 2] << \",\" << xdev[4 * i + 3]\n                      << std::endl;\n            std::cout << \"nits=\" << nits[i] << std::endl;\n        }\n\n        // verify results\n        double tol = 0.03;\n        int count  = 0;\n        for (int i = 0; i < N; i++)\n        {\n            if ((xdev[4 * i + 1] != xdev[4 * i + 1])\n                || std::abs(xdev[4 * i] - 0.33) > tol\n                || std::abs(xdev[4 * i + 1] - 0.33) > tol\n                || std::abs(xdev[4 * i + 2] - 0.33) > tol\n                || std::abs(xdev[4 * i + 3] - 0.33) > tol)\n            {\n                std::cout << \"Device: x=\" << xdev[4 * i] << \",\"\n                          << xdev[4 * i + 1] << \",\" << xdev[4 * i + 2] << \",\"\n                          << xdev[4 * i + 3] << std::endl;\n                std::cout << \"Difference: \" << xdev[4 * i] - 0.33 << \", \"\n                          << xdev[4 * i + 1] - 0.33 << \", \"\n                          << xdev[4 * i + 2] - 0.33 << \", \"\n                          << xdev[4 * i + 3] - 0.33 << std::endl;\n                std::cout << \"nits[\" << i << \"]=\" << nits[i] << std::endl;\n                count++;\n            }\n            if (count > 20) break;\n        }\n    }\n\n    delete[] xdev;\n    delete[] nits;\n#endif\n}\n", "meta": {"hexsha": "40c2279630f321f223f5fe14022d1873e319b91b", "size": 10939, "ext": "cc", "lang": "C++", "max_stars_repo_path": "drivers/loopCALPHADConcSolverTernary.cc", "max_stars_repo_name": "TApplencourt/Thermo4PFM", "max_stars_repo_head_hexsha": "6e98249d1b871e017c4a15052aed9d00ec2d6d96", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2022-01-21T17:39:13.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-17T21:00:24.000Z", "max_issues_repo_path": "drivers/loopCALPHADConcSolverTernary.cc", "max_issues_repo_name": "TApplencourt/Thermo4PFM", "max_issues_repo_head_hexsha": "6e98249d1b871e017c4a15052aed9d00ec2d6d96", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2022-01-21T16:51:52.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-21T16:51:52.000Z", "max_forks_repo_path": "drivers/loopCALPHADConcSolverTernary.cc", "max_forks_repo_name": "TApplencourt/Thermo4PFM", "max_forks_repo_head_hexsha": "6e98249d1b871e017c4a15052aed9d00ec2d6d96", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-12-13T14:29:16.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-01T18:12:51.000Z", "avg_line_length": 32.556547619, "max_line_length": 79, "alphanum_fraction": 0.5197915714, "num_tokens": 3559, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7371581626286833, "lm_q2_score": 0.44552953503957266, "lm_q1q2_score": 0.32842573344658293}}
{"text": "\n// Include for Visual studio, 'cos reasons.\n#define _USE_MATH_DEFINES\n#include <cmath>\n#include <numeric>\n#include <set>\n#include <omp.h>\n\n#include \"hoMatrix.h\"\n#include \"hoNDArray_elemwise.h\"\n#include \"hoNDArray_math.h\"\n#include \"hoNDFFT.h\"\n#include <boost/container/flat_set.hpp>\n\nnamespace Gadgetron {\n\n    template <typename T> hoNDFFT<T>* hoNDFFT<T>::instance() {\n        if (!instance_)\n            instance_ = new hoNDFFT<T>();\n        return instance_;\n    }\n\n    template <class T> hoNDFFT<T>* hoNDFFT<T>::instance_ = NULL;\n\n    namespace {\n\n        template <class T> struct fftw_types {};\n\n        template <> struct fftw_types<float> {\n            using complex                      = fftwf_complex;\n            using plan                         = fftwf_plan_s;\n            static constexpr auto plan_guru    = fftwf_plan_guru64_dft;\n            static constexpr auto plan_dft     = fftwf_plan_dft;\n            static constexpr auto execute_dft  = fftwf_execute_dft;\n            static constexpr auto destroy_plan = fftwf_destroy_plan;\n        };\n\n        template <> struct fftw_types<double> {\n            using complex                      = fftw_complex;\n            using plan                         = fftw_plan_s;\n            static constexpr auto plan_guru    = fftw_plan_guru64_dft;\n            static constexpr auto plan_dft     = fftw_plan_dft;\n            static constexpr auto execute_dft  = fftw_execute_dft;\n            static constexpr auto destroy_plan = fftw_destroy_plan;\n        };\n        class FFTLock {\n        protected:\n            static std::mutex lock;\n        };\n        std::mutex FFTLock::lock;\n        template <class T> class SingleFFTPlan : FFTLock {\n        public:\n            using FFTWComplex = typename fftw_types<T>::complex;\n\n            SingleFFTPlan(int dimension, const hoNDArray<std::complex<T>>& input, hoNDArray<std::complex<T>>& output,\n                bool forward) {\n                std::lock_guard<std::mutex> guard(lock);\n\n                const auto& dimensions = input.dimensions();\n                size_t stride\n                    = std::accumulate(dimensions.begin(), dimensions.begin() + dimension, 1, std::multiplies<>());\n\n                auto fftw_dimensions = fftw_iodim64{ static_cast<ptrdiff_t>(dimensions[dimension]), static_cast<ptrdiff_t>(stride), static_cast<ptrdiff_t>(stride) };\n\n                plan = fftw_types<T>::plan_guru(1, &fftw_dimensions, 0, nullptr, (FFTWComplex*)input.data(),\n                    (FFTWComplex*)output.data(), forward ? FFTW_FORWARD : FFTW_BACKWARD, FFTW_ESTIMATE);\n            }\n\n            ~SingleFFTPlan() {\n                std::lock_guard<std::mutex> guard(lock);\n                fftw_types<T>::destroy_plan(plan);\n            }\n\n            void execute(const std::complex<T>* input, std::complex<T>* output) {\n                fftw_types<T>::execute_dft(plan, (FFTWComplex*)input, (FFTWComplex*)output);\n            }\n\n        private:\n            typename fftw_types<T>::plan* plan;\n        };\n\n        template <class T> class ContigousFFTPlan : FFTLock {\n        public:\n            using FFTWComplex = typename fftw_types<T>::complex;\n            ContigousFFTPlan(\n                int rank, const hoNDArray<std::complex<T>>& input, hoNDArray<std::complex<T>>& output, bool forward) {\n                std::lock_guard<std::mutex> guard(lock);\n\n                const auto& dimensions = input.dimensions();\n\n                auto strides = std::vector<size_t>(rank + 1, 1);\n                std::partial_sum(\n                    dimensions.begin(), dimensions.begin() + rank, strides.begin() + 1, std::multiplies<>());\n\n                auto fftw_dimensions = std::vector<fftw_iodim64>(rank);\n\n                for (int i = 0; i < rank; i++) {\n                    fftw_dimensions[i] = { (int64_t)dimensions[i], (int64_t)strides[i], (int64_t)strides[i] };\n                }\n                std::reverse(fftw_dimensions.begin(),fftw_dimensions.end());\n                plan = fftw_types<T>::plan_guru(rank, fftw_dimensions.data(), 0, nullptr, (FFTWComplex*)input.data(),\n                    (FFTWComplex*)output.data(), forward ? FFTW_FORWARD : FFTW_BACKWARD, FFTW_ESTIMATE);\n\n                if (plan == nullptr) throw std::runtime_error(\"Illegal FFT plan created\");\n            }\n            ~ContigousFFTPlan() {\n                std::lock_guard<std::mutex> guard(lock);\n                fftw_types<T>::destroy_plan(plan);\n            }\n\n            void execute(const std::complex<T>* input, std::complex<T>* output) {\n                fftw_types<T>::execute_dft(plan, (FFTWComplex*)input, (FFTWComplex*)output);\n            }\n\n        private:\n            typename fftw_types<T>::plan* plan;\n        };\n\n\n        int contigous_rank(const boost::container::flat_set<int>& dimensions) {\n            if (!dimensions.count(0))\n                return 0;\n\n            int rank = std::distance(std::adjacent_find(dimensions.begin(), dimensions.end(),\n                                         [](auto val1, auto val2) { return val1 != val2 - 1; }),\n                dimensions.end());\n            return rank;\n        }\n\n        template <typename T>\n        static void contigous_fftn(const hoNDArray<std::complex<T>>& input, hoNDArray<std::complex<T>>& output, int rank,\n            bool forward, bool normalize) {\n\n            auto plan = ContigousFFTPlan<T>(rank, input, output, forward);\n            size_t batch_size\n                = std::accumulate(input.dimensions().begin(), input.dimensions().begin() + rank, 1, std::multiplies<>());\n            size_t batches = input.size() / batch_size;\n\n#pragma omp parallel for default(none) shared(plan,  input, output, batches, batch_size)\n            for (long long i = 0; i < batches; i++) {\n\n                plan.execute(input.data() + i * batch_size, output.data() + i * batch_size);\n            }\n\n            if (normalize)\n                output *= T(1) / std::sqrt<T>(batch_size);\n        }\n\n        template <typename T>\n        static void single_fft(int dimension, const hoNDArray<std::complex<T>>& a, hoNDArray<std::complex<T>>& r,\n            bool forward, bool normalize) {\n            assert(dimension >= 0);\n            auto plan              = SingleFFTPlan<T>(dimension, a, r, forward);\n            const auto& dimensions = a.dimensions();\n            size_t inner_batches\n                = std::accumulate(dimensions.begin(), dimensions.begin() + dimension, 1, std::multiplies<>());\n            size_t outer_batches\n                = std::accumulate(dimensions.begin() + dimension + 1, dimensions.end(), 1, std::multiplies<>());\n            size_t outer_batchsize = inner_batches * dimensions[dimension];\n\n#pragma omp parallel for default(none) shared(plan, a, r , outer_batches, inner_batches, outer_batchsize ) collapse(2)\n            for (long long outer = 0; outer < outer_batches; outer++) {\n                for (long long inner = 0; inner < inner_batches; inner++) {\n                    plan.execute(\n                        a.data() + inner + outer * outer_batchsize, r.data() + inner + outer * outer_batchsize);\n                }\n            }\n\n            if (normalize)\n                r *= T(1) / std::sqrt<T>(dimensions[dimension]);\n        }\n    }\n\n    static inline size_t fftshiftPivot(size_t x) {\n        return (x + 1) / 2;\n    }\n\n    static inline size_t ifftshiftPivot(size_t x) {\n        return x - (x + 1) / 2;\n    }\n\n    namespace {\n        template <typename T>\n        inline void fftshift(const std::complex<T>* a, std::complex<T>* r, size_t stride, size_t x, size_t pivot) {\n            std::rotate_copy(a, a + pivot, a + x, r);\n        }\n\n        template <typename T, typename... INDICES>\n        inline void fftshift(const std::complex<T>* a, std::complex<T>* r, size_t stride, size_t n, size_t pivot,\n            size_t n2, INDICES... indices) {\n            for (size_t i = 0; i < n; i++) {\n                auto line_begin  = a + i * stride;\n                size_t new_y     = i < pivot ? i + pivot : i - pivot;\n                auto output_line = r + new_y * stride;\n                fftshift(line_begin, output_line, stride / n2, n2, indices...);\n            }\n        }\n\n        template <typename T>\n        inline void fftshift(std::complex<T>* a, std::complex<T>* a2, std::vector<std::complex<T>>& buffer,\n            size_t stride, size_t ny, size_t pivoty, size_t nx, size_t pivotx) {\n            for (size_t iy = 0; iy < (ny + 1) / 2; iy++) {\n                auto line_begin = a + iy * stride;\n                auto line_pivot = line_begin + pivotx;\n                auto line_end   = line_begin + stride;\n\n                auto line_begin2 = a2 + ((iy + pivoty) % ny) * stride;\n                auto line_pivot2 = line_begin2 + pivotx;\n                auto line_end2   = line_begin2 + stride;\n                std::rotate_copy(line_begin2, line_pivot2, line_end2, buffer.begin());\n                std::rotate_copy(line_begin, line_pivot, line_end, line_begin2);\n                std::copy(buffer.begin(), buffer.end(), line_begin);\n            }\n        }\n\n        template <typename T, typename... INDICES>\n        inline void fftshift(std::complex<T>* a, std::complex<T>* a2, std::vector<std::complex<T>>& buffer,\n            size_t stride, size_t n, size_t pivot, size_t n2, INDICES... indices) {\n\n            for (size_t i = 0; i < n; i++) {\n                auto line_begin  = a + i * stride;\n                size_t new_y     = (i + pivot) % n;\n                auto line_begin2 = a2 + new_y * stride;\n                fftshift(line_begin, line_begin2, buffer, stride / n2, n2, indices...);\n            }\n        }\n\n    }\n\n    template <typename T> static void fftshiftPivot1D(std::complex<T>* a, size_t x, size_t n, size_t pivot) {\n\n#pragma omp parallel for shared(n, x, pivot, a) if (n > 256) default(none)\n        for (long long counter = 0; counter < (long long)n; counter++) {\n            std::rotate(a + counter * x, a + counter * x + pivot, a + x + counter * x);\n        }\n    }\n\n    template <typename T>\n    static void fftshiftPivot1D(const std::complex<T>* a, std::complex<T>* r, size_t x, size_t n, size_t pivot) {\n\n#pragma omp parallel for shared(n, x, pivot, a, r) if (n > 256) default(none)\n        for (long long counter = 0; counter < (long long)n; counter++) {\n            std::rotate_copy(a + counter * x, a + counter * x + pivot, a + x + counter * x, r + counter * x);\n        }\n    }\n\n    template <typename T> void hoNDFFT<T>::fftshift1D(hoNDArray<std::complex<T>>& a) {\n        size_t x           = a.get_size(0);\n        size_t pivot       = fftshiftPivot(x);\n        size_t numOfShifts = a.get_number_of_elements() / x;\n        fftshiftPivot1D(a.begin(), x, numOfShifts, pivot);\n    }\n\n    template <typename T>\n    void hoNDFFT<T>::fftshift1D(const hoNDArray<std::complex<T>>& a, hoNDArray<std::complex<T>>& r) {\n        if (!r.dimensions_equal(&a)) {\n            r = a;\n        }\n\n        size_t x           = a.get_size(0);\n        size_t pivot       = fftshiftPivot(x);\n        size_t numOfShifts = a.get_number_of_elements() / x;\n        fftshiftPivot1D(a.begin(), r.begin(), x, numOfShifts, pivot);\n    }\n\n    template <typename T> void hoNDFFT<T>::ifftshift1D(hoNDArray<std::complex<T>>& a) {\n        size_t x           = a.get_size(0);\n        size_t pivot       = ifftshiftPivot(x);\n        size_t numOfShifts = a.get_number_of_elements() / x;\n\n        fftshiftPivot1D(a.begin(), x, numOfShifts, pivot);\n    }\n\n    template <typename T>\n    void hoNDFFT<T>::ifftshift1D(const hoNDArray<std::complex<T>>& a, hoNDArray<std::complex<T>>& r) {\n        if (!r.dimensions_equal(&a)) {\n            r = a;\n        }\n\n        size_t x           = a.get_size(0);\n        size_t pivot       = ifftshiftPivot(x);\n        size_t numOfShifts = a.get_number_of_elements() / x;\n\n        fftshiftPivot1D(a.begin(), r.begin(), x, numOfShifts, pivot);\n    }\n\n    template <typename T>\n    static void fftshiftPivot2D(\n        const std::complex<T>* a, std::complex<T>* r, size_t x, size_t y, size_t n, size_t pivotx, size_t pivoty) {\n        if (a == NULL || r == NULL)\n            throw std::runtime_error(\"hoNDFFT::fftshiftPivot2D: void ptr provided\");\n        assert(a != r);\n\n#pragma omp parallel for shared(a, r, x, y, n, pivotx, pivoty) if (n > 16) default(none)\n        for (long long tt = 0; tt < (long long)n; tt++) {\n            const std::complex<T>* ac = a + tt * x * y;\n            std::complex<T>* rc       = r + tt * x * y;\n            fftshift(ac, rc, x, y, pivoty, x, pivotx);\n        }\n    }\n\n    template <typename T>\n    static void fftshiftPivot2D(std::complex<T>* a, size_t x, size_t y, size_t n, size_t pivotx, size_t pivoty) {\n\n        if (a == NULL)\n            throw std::runtime_error(\"hoNDFFT::fftshiftPivot2D: void ptr provided\");\n\n#pragma omp parallel if (n > 16) default(shared)\n        {\n            std::vector<std::complex<T>> buffer(x);\n\n#pragma omp for\n            for (long long tt = 0; tt < (long long)n; tt++) {\n                std::complex<T>* ac = a + tt * x * y;\n                fftshift(ac, ac, buffer, x, y, pivoty, x, pivotx);\n            }\n        }\n    }\n\n    template <typename T>\n    static inline void fftshift2D(const std::complex<T>* a, std::complex<T>* r, size_t x, size_t y, size_t n) {\n\n        if (a == NULL || r == NULL)\n            throw std::runtime_error(\"hoNDFFT::fftshift2D: void ptr provided\");\n\n        size_t pivotx = fftshiftPivot(x);\n        size_t pivoty = fftshiftPivot(y);\n\n        fftshiftPivot2D(a, r, x, y, n, pivotx, pivoty);\n    }\n\n    template <typename T> inline void hoNDFFT<T>::fftshift2D(hoNDArray<ComplexType>& a) {\n        size_t n = a.get_number_of_elements() / (a.get_size(0) * a.get_size(1));\n        fftshiftPivot2D(\n            a.data(), a.get_size(0), a.get_size(1), n, fftshiftPivot(a.get_size(0)), fftshiftPivot(a.get_size(1)));\n    }\n\n    template <typename T>\n    inline void hoNDFFT<T>::fftshift2D(const hoNDArray<ComplexType>& a, hoNDArray<ComplexType>& r) {\n        if (!r.dimensions_equal(&a)) {\n            r = a;\n        }\n\n        size_t n = a.get_number_of_elements() / (a.get_size(0) * a.get_size(1));\n        fftshiftPivot2D(a.begin(), r.begin(), a.get_size(0), a.get_size(1), n, fftshiftPivot(a.get_size(0)),\n            fftshiftPivot(a.get_size(1)));\n    }\n\n    template <typename T> inline void hoNDFFT<T>::ifftshift2D(hoNDArray<ComplexType>& a) {\n        size_t n = a.get_number_of_elements() / (a.get_size(0) * a.get_size(1));\n        fftshiftPivot2D(\n            a.begin(), a.get_size(0), a.get_size(1), n, ifftshiftPivot(a.get_size(0)), ifftshiftPivot(a.get_size(1)));\n    }\n\n    template <typename T>\n    inline void hoNDFFT<T>::ifftshift2D(const hoNDArray<ComplexType>& a, hoNDArray<ComplexType>& r) {\n        if (!r.dimensions_equal(&a)) {\n            r = a;\n        }\n        size_t n = a.get_number_of_elements() / (a.get_size(0) * a.get_size(1));\n        fftshiftPivot2D(a.begin(), r.begin(), a.get_size(0), a.get_size(1), n, ifftshiftPivot(a.get_size(0)),\n            ifftshiftPivot(a.get_size(1)));\n    }\n\n    template <typename T>\n    void fftshiftPivot3D(const std::complex<T>* a, std::complex<T>* r, size_t x, size_t y, size_t z, size_t n,\n        size_t pivotx, size_t pivoty, size_t pivotz) {\n\n        if (a == NULL || r == NULL)\n            throw std::runtime_error(\"hoNDFFT::fftshift2D: void ptr provided\");\n\n        long long tt;\n\n#pragma omp parallel for private(tt) shared(a, r, x, y, z, n, pivotx, pivoty, pivotz) if (n > 16) default(none)\n        for (tt = 0; tt < (long long)n; tt++) {\n            const std::complex<T>* ac = a + tt * x * y * z;\n            std::complex<T>* rc       = r + tt * x * y * z;\n            fftshift(ac, rc, x * y, z, pivotz, y, pivoty, x, pivotx);\n        }\n    }\n\n    template <typename T>\n    void fftshiftPivot3D(\n        std::complex<T>* a, size_t x, size_t y, size_t z, size_t n, size_t pivotx, size_t pivoty, size_t pivotz) {\n\n        if (a == NULL)\n            throw std::runtime_error(\"hoNDFFT::fftshiftPivot3D: void ptr provided\");\n\n        long long tt;\n\n#pragma omp parallel private(tt)  if (n > 16) default(shared)\n        {\n            std::vector<std::complex<T>> buffer(x);\n\n#pragma omp for\n            for (tt = 0; tt < (long long)n; tt++) {\n                std::complex<T>* ac = a + tt * x * y * z;\n                fftshift(ac, ac, buffer, x * y, z, pivotz, y, pivoty, x, pivotx);\n            }\n        }\n    }\n\n    template <typename T>\n    inline void fftshift3D(const std::complex<T>* a, std::complex<T>* r, size_t x, size_t y, size_t z, size_t n) {\n\n        if (a == NULL || r == NULL)\n            throw std::runtime_error(\"hoNDFFT::fftshift3D: void ptr provided\");\n\n        size_t pivotx = fftshiftPivot(x);\n        size_t pivoty = fftshiftPivot(y);\n        size_t pivotz = fftshiftPivot(z);\n\n        fftshiftPivot3D(a, r, x, y, z, n, pivotx, pivoty, pivotz);\n    }\n\n    template <typename T>\n    inline void ifftshift3D(const std::complex<T>* a, std::complex<T>* r, size_t x, size_t y, size_t z, size_t n) {\n\n        if (a == NULL || r == NULL)\n            throw std::runtime_error(\"hoNDFFT::ifftshift3D: void ptr provided\");\n\n        size_t pivotx = ifftshiftPivot(x);\n        size_t pivoty = ifftshiftPivot(y);\n        size_t pivotz = ifftshiftPivot(z);\n\n        fftshiftPivot3D(a, r, x, y, z, n, pivotx, pivoty, pivotz);\n    }\n\n    template <typename T> inline void fftshift3D(std::complex<T>* a, size_t x, size_t y, size_t z, size_t n) {\n        if (a == NULL)\n            throw std::runtime_error(\"hoNDFFT::fftshift3D: void ptr provided\");\n        size_t pivotx = fftshiftPivot(x);\n        size_t pivoty = fftshiftPivot(y);\n        size_t pivotz = fftshiftPivot(z);\n        fftshiftPivot3D(a, x, y, z, n, pivotx, pivoty, pivotz);\n    }\n\n    template <typename T> inline void ifftshift3D(std::complex<T>* a, size_t x, size_t y, size_t z, size_t n) {\n        if (a == NULL)\n            throw std::runtime_error(\"hoNDFFT::ifftshift3D: void ptr provided\");\n\n        size_t pivotx = ifftshiftPivot(x);\n        size_t pivoty = ifftshiftPivot(y);\n        size_t pivotz = ifftshiftPivot(z);\n\n        fftshiftPivot3D(a, x, y, z, n, pivotx, pivoty, pivotz);\n    }\n\n    template <typename T> inline void hoNDFFT<T>::fftshift3D(hoNDArray<ComplexType>& a) {\n        size_t n = a.get_number_of_elements() / (a.get_size(0) * a.get_size(1) * a.get_size(2));\n\n        fftshiftPivot3D(a.begin(), a.get_size(0), a.get_size(1), a.get_size(2), n,\n                        fftshiftPivot(a.get_size(0)),\n                        fftshiftPivot(a.get_size(1)),\n                        fftshiftPivot(a.get_size(2)));\n    }\n\n    template <typename T>\n    inline void hoNDFFT<T>::fftshift3D(const hoNDArray<ComplexType>& a, hoNDArray<ComplexType>& r) {\n        if (!r.dimensions_equal(&a)) {\n            r = a;\n        }\n\n        size_t n = a.get_number_of_elements() / (a.get_size(0) * a.get_size(1) * a.get_size(2));\n        fftshiftPivot3D(a.begin(), r.begin(), a.get_size(0), a.get_size(1), a.get_size(2), n,\n            fftshiftPivot(a.get_size(0)), fftshiftPivot(a.get_size(1)), fftshiftPivot(a.get_size(2)));\n    }\n\n    template <typename T> inline void hoNDFFT<T>::ifftshift3D(hoNDArray<ComplexType>& a) {\n        size_t n = a.get_number_of_elements() / (a.get_size(0) * a.get_size(1) * a.get_size(2));\n        fftshiftPivot3D(a.begin(), a.get_size(0), a.get_size(1), a.get_size(2), n, ifftshiftPivot(a.get_size(0)),\n            ifftshiftPivot(a.get_size(1)), ifftshiftPivot(a.get_size(2)));\n    }\n\n    template <typename T>\n    inline void hoNDFFT<T>::ifftshift3D(const hoNDArray<ComplexType>& a, hoNDArray<ComplexType>& r) {\n        if (!r.dimensions_equal(&a)) {\n            r = a;\n        }\n        size_t n = a.get_number_of_elements() / (a.get_size(0) * a.get_size(1) * a.get_size(2));\n        fftshiftPivot3D(a.begin(), r.begin(), a.get_size(0), a.get_size(1), a.get_size(2), n,\n            ifftshiftPivot(a.get_size(0)), ifftshiftPivot(a.get_size(1)), ifftshiftPivot(a.get_size(2)));\n    }\n\n    // -----------------------------------------------------------------------------------------\n\n    template <typename T> inline void hoNDFFT<T>::fft1(hoNDArray<ComplexType>& a) {\n        contigous_fftn(a, a, 1, true, true);\n    }\n\n    template <typename T> inline void hoNDFFT<T>::ifft1(hoNDArray<ComplexType>& a) {\n        contigous_fftn(a, a, 1, false, true);\n    }\n\n    template <typename T> inline void hoNDFFT<T>::fft1(const hoNDArray<ComplexType>& a, hoNDArray<ComplexType>& r) {\n        if (!r.dimensions_equal(&a)) {\n            r.create(a.dimensions());\n        }\n\n        contigous_fftn(a, r, 1, true, true);\n    }\n\n    template <typename T> inline void hoNDFFT<T>::ifft1(const hoNDArray<ComplexType>& a, hoNDArray<ComplexType>& r) {\n        if (!r.dimensions_equal(&a)) {\n            r.create(a.dimensions());\n        }\n        contigous_fftn(a, r, 1, false, true);\n    }\n\n    template <typename T> inline void hoNDFFT<T>::fft1c(hoNDArray<ComplexType>& a) {\n        ifftshift1D(a);\n        fft1(a);\n        fftshift1D(a);\n    }\n\n    template <typename T> inline void hoNDFFT<T>::ifft1c(hoNDArray<ComplexType>& a) {\n        ifftshift1D(a);\n        ifft1(a);\n        fftshift1D(a);\n    }\n\n    template <typename T> inline void hoNDFFT<T>::fft1c(const hoNDArray<ComplexType>& a, hoNDArray<ComplexType>& r) {\n        ifftshift1D(a, r);\n        fft1(r);\n        fftshift1D(r);\n    }\n\n    template <typename T> inline void hoNDFFT<T>::ifft1c(const hoNDArray<ComplexType>& a, hoNDArray<ComplexType>& r) {\n        ifftshift1D(a, r);\n        ifft1(r);\n        fftshift1D(r);\n    }\n\n    template <typename T>\n    inline void hoNDFFT<T>::fft1c(\n        const hoNDArray<ComplexType>& a, hoNDArray<ComplexType>& r, hoNDArray<ComplexType>& buf) {\n        ifftshift1D(a, r);\n        fft1(r, buf);\n        fftshift1D(buf, r);\n    }\n\n    template <typename T>\n    inline void hoNDFFT<T>::ifft1c(\n        const hoNDArray<ComplexType>& a, hoNDArray<ComplexType>& r, hoNDArray<ComplexType>& buf) {\n        ifftshift1D(a, r);\n        ifft1(r, buf);\n        fftshift1D(buf, r);\n    }\n\n    // -----------------------------------------------------------------------------------------\n\n    template <typename T> inline void hoNDFFT<T>::fft2(hoNDArray<ComplexType>& a) {\n        contigous_fftn(a, a, 2, true, true);\n    }\n\n    template <typename T> inline void hoNDFFT<T>::ifft2(hoNDArray<ComplexType>& a) {\n        contigous_fftn(a, a, 2, false, true);\n    }\n\n    template <typename T> inline void hoNDFFT<T>::fft2(const hoNDArray<ComplexType>& a, hoNDArray<ComplexType>& r) {\n        if (!r.dimensions_equal(&a)) {\n            r.create(a.dimensions());\n        }\n\n        contigous_fftn(a, r, 2, true, true);\n    }\n\n    template <typename T> inline void hoNDFFT<T>::ifft2(const hoNDArray<ComplexType>& a, hoNDArray<ComplexType>& r) {\n        if (!r.dimensions_equal(&a)) {\n            r.create(a.dimensions());\n        }\n\n        contigous_fftn(a, r, 2, false, true);\n    }\n\n    template <typename T> inline void hoNDFFT<T>::fft2c(hoNDArray<ComplexType>& a) {\n        ifftshift2D(a);\n        fft2(a);\n        fftshift2D(a);\n    }\n\n    template <typename T> inline void hoNDFFT<T>::ifft2c(hoNDArray<ComplexType>& a) {\n        ifftshift2D(a);\n        ifft2(a);\n        fftshift2D(a);\n    }\n\n    template <typename T> inline void hoNDFFT<T>::fft2c(const hoNDArray<ComplexType>& a, hoNDArray<ComplexType>& r) {\n        ifftshift2D(a, r);\n        fft2(r);\n        fftshift2D(r);\n    }\n\n    template <typename T> inline void hoNDFFT<T>::ifft2c(const hoNDArray<ComplexType>& a, hoNDArray<ComplexType>& r) {\n        ifftshift2D(a, r);\n        ifft2(r);\n        fftshift2D(r);\n    }\n\n    template <typename T>\n    inline void hoNDFFT<T>::fft2c(\n        const hoNDArray<ComplexType>& a, hoNDArray<ComplexType>& r, hoNDArray<ComplexType>& buf) {\n        ifftshift2D(a, r);\n        fft2(r, buf);\n        fftshift2D(buf, r);\n    }\n\n    template <typename T>\n    inline void hoNDFFT<T>::ifft2c(\n        const hoNDArray<ComplexType>& a, hoNDArray<ComplexType>& r, hoNDArray<ComplexType>& buf) {\n        ifftshift2D(a, r);\n        ifft2(r, buf);\n        fftshift2D(buf, r);\n    }\n\n    // -----------------------------------------------------------------------------------------\n\n    template <typename T> inline void hoNDFFT<T>::fft3(hoNDArray<ComplexType>& a) {\n        contigous_fftn(a, a, 3, true, true);\n    }\n\n    template <typename T> inline void hoNDFFT<T>::ifft3(hoNDArray<ComplexType>& a) {\n        contigous_fftn(a, a, 3, false, true);\n    }\n\n    template <typename T> inline void hoNDFFT<T>::fft3(const hoNDArray<ComplexType>& a, hoNDArray<ComplexType>& r) {\n        if (!r.dimensions_equal(&a)) {\n            r.create(a.dimensions());\n        }\n\n        contigous_fftn(a, r, 3, true, true);\n    }\n\n    template <typename T> inline void hoNDFFT<T>::ifft3(const hoNDArray<ComplexType>& a, hoNDArray<ComplexType>& r) {\n        if (!r.dimensions_equal(&a)) {\n            r.create(a.dimensions());\n        }\n\n        contigous_fftn(a, r, 3, false, true);\n    }\n\n    template <typename T> inline void hoNDFFT<T>::fft3c(hoNDArray<ComplexType>& a) {\n        ifftshift3D(a);\n        fft3(a);\n        fftshift3D(a);\n    }\n\n    template <typename T> inline void hoNDFFT<T>::ifft3c(hoNDArray<ComplexType>& a) {\n        ifftshift3D(a);\n        ifft3(a);\n        fftshift3D(a);\n    }\n\n    template <typename T> inline void hoNDFFT<T>::fft3c(const hoNDArray<ComplexType>& a, hoNDArray<ComplexType>& r) {\n        ifftshift3D(a, r);\n        fft3(r);\n        fftshift3D(r);\n    }\n\n    template <typename T> inline void hoNDFFT<T>::ifft3c(const hoNDArray<ComplexType>& a, hoNDArray<ComplexType>& r) {\n        ifftshift3D(a, r);\n        ifft3(r);\n        fftshift3D(r);\n    }\n\n    template <typename T>\n    inline void hoNDFFT<T>::fft3c(\n        const hoNDArray<ComplexType>& a, hoNDArray<ComplexType>& r, hoNDArray<ComplexType>& buf) {\n        ifftshift3D(a, r);\n        fft3(r, buf);\n        fftshift3D(buf, r);\n    }\n\n    template <typename T>\n    inline void hoNDFFT<T>::ifft3c(\n        const hoNDArray<ComplexType>& a, hoNDArray<ComplexType>& r, hoNDArray<ComplexType>& buf) {\n        ifftshift3D(a, r);\n        ifft3(r, buf);\n        fftshift3D(buf, r);\n    }\n\n    template <typename T> void fft1(hoNDArray<std::complex<T>>& a, bool forward) {\n        hoNDArray<std::complex<T>> res(a);\n        fft1(res, a, forward);\n    }\n\n    template <typename T> void fft2(hoNDArray<std::complex<T>>& a, bool forward) {\n        hoNDArray<std::complex<T>> res(a);\n        fft2(res, a, forward);\n    }\n\n    template <typename T> void fft3(hoNDArray<std::complex<T>>& a, bool forward) {\n        hoNDArray<std::complex<T>> res(a);\n        fft3(res, a, forward);\n    }\n\n    template <typename T> void fft1(hoNDArray<std::complex<T>>& a, hoNDArray<std::complex<T>>& r, bool forward) {\n        contigous_fftn(a, r, 1, forward, true);\n    }\n\n    template <typename T> void fft2(hoNDArray<std::complex<T>>& a, hoNDArray<std::complex<T>>& r, bool forward) {\n        contigous_fftn(a, r, 2, forward, true);\n    }\n\n    template <typename T> void fft3(hoNDArray<std::complex<T>>& a, hoNDArray<std::complex<T>>& r, bool forward) {\n        contigous_fftn(a, r, 3, forward, true);\n    }\n\n    template <typename T>\n    void fftn(const hoNDArray<std::complex<T>>& a, hoNDArray<std::complex<T>>& r, const std::vector<size_t>& dimensions,\n        bool forward) {\n\n        auto dimensions_set = boost::container::flat_set<int>(dimensions.begin(), dimensions.end());\n        int c_rank          = contigous_rank(dimensions_set);\n        if (c_rank)\n            contigous_fftn(a, r, c_rank, forward, false);\n\n        for (auto it = dimensions_set.lower_bound(c_rank); it != dimensions_set.end(); ++it) {\n            single_fft(*it,a, r, forward, false);\n        }\n\n        size_t batch_size = 1;\n        for (auto d : dimensions)\n            batch_size *= a.get_size(d);\n\n        T fftRatio = T(1.0 / std::sqrt(T(batch_size)));\n        r *= fftRatio;\n    }\n\n    // TODO: implement more optimized threading strategy\n    inline int get_num_threads_fft1(size_t n0, size_t num) {\n        if (omp_get_max_threads() == 1)\n            return 1;\n\n        if (n0 * num > 1024 * 128) {\n            return omp_get_max_threads();\n        } else if (n0 * num > 512 * 128) {\n            return ((omp_get_max_threads() > 8) ? 8 : omp_get_max_threads());\n        } else if (n0 * num > 256 * 128) {\n            return ((omp_get_max_threads() > 4) ? 4 : omp_get_max_threads());\n        } else if (n0 * num > 128 * 128) {\n            return 2;\n        }\n\n        return 1;\n    }\n\n    inline int get_num_threads_fft2(size_t n0, size_t n1, size_t num) {\n        if (omp_get_max_threads() == 1)\n            return 1;\n\n        if (n0 * n1 * num > 128 * 128 * 64) {\n            return omp_get_max_threads();\n        } else if (n0 * n1 * num > 128 * 128 * 32) {\n            return ((omp_get_max_threads() > 8) ? 8 : omp_get_max_threads());\n        } else if (n0 * n1 * num > 128 * 128 * 16) {\n            return ((omp_get_max_threads() > 4) ? 4 : omp_get_max_threads());\n        } else if (n0 * n1 * num > 128 * 128 * 8) {\n            return 2;\n        }\n\n        return 1;\n    }\n\n    inline int get_num_threads_fft3(size_t n0, size_t n1, size_t n2, size_t num) {\n        if (omp_get_max_threads() == 1)\n            return 1;\n\n        if (num >= omp_get_max_threads()) {\n            return omp_get_max_threads();\n        }\n\n        return 1;\n    }\n\n    int get_num_threads_fftn(const std::vector<int>& dimensions, size_t num) {\n\n        switch (dimensions.size()) {\n        case 1:\n            return get_num_threads_fft1(dimensions[0], num);\n        case 2:\n            return get_num_threads_fft2(dimensions[0], dimensions[1], num);\n        case 3:\n            return get_num_threads_fft3(dimensions[0], dimensions[1], dimensions[2], num);\n        default:\n            return std::min<long long>(omp_get_max_threads(), num);\n        }\n    }\n\n    template <typename T> void hoNDFFT<T>::fft(hoNDArray<ComplexType>* input, unsigned int dim_to_transform) {\n        single_fft(dim_to_transform, *input, *input, true, true);\n    }\n    template <typename T> void hoNDFFT<T>::ifft(hoNDArray<ComplexType>* input, unsigned int dim_to_transform) {\n        single_fft(dim_to_transform, *input, *input, false, true);\n    }\n    template <typename T> void hoNDFFT<T>::fft(hoNDArray<ComplexType>* input) {\n        contigous_fftn(*input, *input, input->get_number_of_dimensions(), true, true);\n    }\n    template <typename T> void hoNDFFT<T>::ifft(hoNDArray<ComplexType>* input) {\n        contigous_fftn(*input, *input, input->get_number_of_dimensions(), true, true);\n    }\n    template <typename T> void hoNDFFT<T>::fft(hoNDArray<complext<T>>* input, unsigned int dim_to_transform) {\n        fft(reinterpret_cast<hoNDArray<ComplexType>*>(input), dim_to_transform);\n    }\n    template <typename T> void hoNDFFT<T>::ifft(hoNDArray<complext<T>>* input, unsigned int dim_to_transform) {\n        ifft(reinterpret_cast<hoNDArray<ComplexType>*>(input), dim_to_transform);\n    }\n    template <typename T> void hoNDFFT<T>::fft(hoNDArray<complext<T>>* input) {\n        fft(reinterpret_cast<hoNDArray<ComplexType>*>(input));\n    }\n    template <typename T> void hoNDFFT<T>::ifft(hoNDArray<complext<T>>* input) {\n        ifft(reinterpret_cast<hoNDArray<ComplexType>*>(input));\n    }\n\n\n    template <class ComplexType, class ENABLER>\n    void FFT::fft(hoNDArray<ComplexType>& data, std::vector<size_t> dimensions) {\n        std::sort(dimensions.begin(), dimensions.end());\n        if (std::adjacent_find(dimensions.begin(), dimensions.end()) != dimensions.end()) {\n            throw std::runtime_error(\"Duplicate dimensions in list to be transformed\");\n        }\n        fftn(data,data,dimensions,true);\n    }\n\n    template <class ComplexType, class ENABLER> void FFT::fft(hoNDArray<ComplexType>& data, size_t dimension) {\n        single_fft(dimension,data,data,true,true);\n    }\n    template <class ComplexType, class ENABLER>\n    void FFT::ifft(hoNDArray<ComplexType>& data, std::vector<size_t> dimensions) {\n        std::sort(dimensions.begin(), dimensions.end());\n        if (std::adjacent_find(dimensions.begin(), dimensions.end()) != dimensions.end()) {\n            throw std::runtime_error(\"Duplicate dimensions in list to be transformed\");\n        }\n        fftn(data,data,dimensions,false);\n    }\n\n    template <class ComplexType, class ENABLER> void FFT::ifft(hoNDArray<ComplexType>& data, size_t dimension) {\n        single_fft(dimension,data,data,false,true);\n    }\n    template <class ComplexType, class ENABLER>\n    hoNDArray<ComplexType> FFT::fft1c(const hoNDArray<ComplexType> &data) {\n      hoNDArray<ComplexType> output(data.dimensions());\n      hoNDFFT<realType_t<ComplexType>>::instance()->fft1c(data,output);\n      return output;\n    }\n    template <class ComplexType, class ENABLER>\n    hoNDArray<ComplexType> FFT::fft2c(const hoNDArray<ComplexType> &data) {\n      hoNDArray<ComplexType> output(data.dimensions());\n      hoNDFFT<realType_t<ComplexType>>::instance()->fft2c(data,output);\n      return output;\n    }\n    template <class ComplexType, class ENABLER>\n    hoNDArray<ComplexType> FFT::fft3c(const hoNDArray<ComplexType> &data) {\n      hoNDArray<ComplexType> output(data.dimensions());\n      hoNDFFT<realType_t<ComplexType>>::instance()->fft3c(data,output);\n      return output;\n    }\n    template <class ComplexType, class ENABLER>\n    hoNDArray<ComplexType> FFT::ifft1c(const hoNDArray<ComplexType> &data) {\n      hoNDArray<ComplexType> output(data.dimensions());\n      hoNDFFT<realType_t<ComplexType>>::instance()->ifft1c(data, output);\n      return output;\n    }\n    template <class ComplexType, class ENABLER>\n    hoNDArray<ComplexType> FFT::ifft2c(const hoNDArray<ComplexType> &data) {\n      hoNDArray<ComplexType> output(data.dimensions());\n      hoNDFFT<realType_t<ComplexType>>::instance()->ifft2c(data, output);\n      return output;\n    }\n    template <class ComplexType, class ENABLER>\n    hoNDArray<ComplexType> FFT::ifft3c(const hoNDArray<ComplexType> &data) {\n      hoNDArray<ComplexType> output(data.dimensions());\n      hoNDFFT<realType_t<ComplexType>>::instance()->ifft3c(data, output);\n      return output;\n    }\n\n    // -----------------------------------------------------------------------------------------\n\n    //\n    // Instantiation\n    //\n\n    template class EXPORTCPUFFT hoNDFFT<float>;\n    template class EXPORTCPUFFT hoNDFFT<double>;\n\n\n    template void FFT::fft<std::complex<float>>(hoNDArray<std::complex<float>>& data, std::vector<size_t> dimensions);\n    template void FFT::fft<std::complex<double>>(hoNDArray<std::complex<double>>& data, std::vector<size_t> dimensions);\n    template void FFT::fft<std::complex<float>>(hoNDArray<std::complex<float>>& data, size_t dimensions);\n    template void FFT::fft<std::complex<double>>(hoNDArray<std::complex<double>>& data, size_t dimensions);\n\n    template void FFT::ifft<std::complex<float>>(hoNDArray<std::complex<float>>& data, std::vector<size_t> dimensions);\n    template void FFT::ifft<std::complex<double>>(hoNDArray<std::complex<double>>& data, std::vector<size_t> dimensions);\n    template void FFT::ifft<std::complex<float>>(hoNDArray<std::complex<float>>& data, size_t dimensions);\n    template void FFT::ifft<std::complex<double>>(hoNDArray<std::complex<double>>& data, size_t dimensions);\n\n    template hoNDArray<std::complex<float>> FFT::fft1c(const hoNDArray<std::complex<float>> &data);\n    template hoNDArray<std::complex<float>> FFT::fft2c(const hoNDArray<std::complex<float>> &data);\n    template hoNDArray<std::complex<float>> FFT::fft3c(const hoNDArray<std::complex<float>> &data);\n    template hoNDArray<std::complex<float>> FFT::ifft1c(const hoNDArray<std::complex<float>> &data);\n    template hoNDArray<std::complex<float>> FFT::ifft2c(const hoNDArray<std::complex<float>> &data);\n    template hoNDArray<std::complex<float>> FFT::ifft3c(const hoNDArray<std::complex<float>> &data);\n\n\n    template hoNDArray<std::complex<double>> FFT::fft1c(const hoNDArray<std::complex<double>> &data);\n    template hoNDArray<std::complex<double>> FFT::fft2c(const hoNDArray<std::complex<double>> &data);\n    template hoNDArray<std::complex<double>> FFT::fft3c(const hoNDArray<std::complex<double>> &data);\n    template hoNDArray<std::complex<double>> FFT::ifft1c(const hoNDArray<std::complex<double>> &data);\n    template hoNDArray<std::complex<double>> FFT::ifft2c(const hoNDArray<std::complex<double>> &data);\n    template hoNDArray<std::complex<double>> FFT::ifft3c(const hoNDArray<std::complex<double>> &data);\n\n\n}\n", "meta": {"hexsha": "e291b526544789d5b984c18055586b85d4792a2d", "size": 36603, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "toolboxes/fft/cpu/hoNDFFT.cpp", "max_stars_repo_name": "roopchansinghv/gadgetron", "max_stars_repo_head_hexsha": "fb6c56b643911152c27834a754a7b6ee2dd912da", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-02-22T21:06:36.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-22T21:06:36.000Z", "max_issues_repo_path": "toolboxes/fft/cpu/hoNDFFT.cpp", "max_issues_repo_name": "apd47/gadgetron", "max_issues_repo_head_hexsha": "073e84dabe77d2dae3b3dd9aa4bf9edbf1f890f2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "toolboxes/fft/cpu/hoNDFFT.cpp", "max_forks_repo_name": "apd47/gadgetron", "max_forks_repo_head_hexsha": "073e84dabe77d2dae3b3dd9aa4bf9edbf1f890f2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.0470459519, "max_line_length": 165, "alphanum_fraction": 0.5902794853, "num_tokens": 10020, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7634837635542924, "lm_q2_score": 0.4301473485858429, "lm_q1q2_score": 0.32841051658121945}}
{"text": "#pragma once\n\n#include <Eigen/Core>\n#include <vector>\n#include \"PointNormal.hh\"\n#include \"../adjacent_pairs.hh\"\n\nnamespace kt84 {\n\ntemplate <int N>\nstruct PolylineT {\n    typedef Eigen::Matrix<double, N, 1> Point;\n    typedef typename std::vector<Point>::iterator               iterator;\n    typedef typename std::vector<Point>::reverse_iterator       reverse_iterator;\n    typedef typename std::vector<Point>::const_iterator         const_iterator;\n    typedef typename std::vector<Point>::const_reverse_iterator const_reverse_iterator;\n    \n    std::vector<Point> points;\n    bool is_loop;\n    \n    PolylineT()\n        : is_loop()\n    {}\n    PolylineT(const std::vector<Point>& points_, bool is_loop_)\n        : points (points_ )\n        , is_loop(is_loop_)\n    {}\n    PolylineT(int size_, bool is_loop_)\n        : points (size_   )\n        , is_loop(is_loop_)\n    {}\n    \n    int size() const { return static_cast<int>(points.size()); }\n    bool empty() const { return points.empty(); }\n    void resize(int size_)                     { points.resize(size_); }\n    void resize(int size_, const Point& point) { points.resize(size_, point); }\n    void clear() { points.clear(); is_loop = false; }\n    void push_back(const Point& point) { points.push_back(point); }\n    void pop_back ()                   { points.pop_back (); }\n    iterator erase(iterator where_) { return points.erase(where_); }\n    iterator erase(iterator first, iterator last) { return points.erase(first, last); }\n    iterator insert(iterator where_, const Point& val) { return points.insert(where_, val); }\n    void     insert(iterator where_, int count, const Point& val) { points.insert(where_, count, val); }\n    template <class InputIterator>\n    void     insert(iterator where_, InputIterator first, InputIterator last) { points.insert(where_, first, last); }\n    iterator                begin()       { return points. begin(); }\n    iterator                end  ()       { return points. end  (); }\n    reverse_iterator       rbegin()       { return points.rbegin(); }\n    reverse_iterator       rend  ()       { return points.rend  (); }\n    const_iterator          begin() const { return points. begin(); }\n    const_iterator          end  () const { return points. end  (); }\n    const_reverse_iterator rbegin() const { return points.rbegin(); }\n    const_reverse_iterator rend  () const { return points.rend  (); }\n          Point& front()       { return points.front(); }\n    const Point& front() const { return points.front(); }\n          Point& back ()       { return points.back (); }\n    const Point& back () const { return points.back (); }\n          Point& operator[](int index)       { return points[index]; }\n    const Point& operator[](int index) const { return points[index]; }\n    \n    void reverse() {\n        if (is_loop) {\n            points.push_back(points.front());\n            std::reverse(points.begin(), points.end());\n            points.pop_back();\n        } else {\n            std::reverse(points.begin(), points.end());\n        }\n    }\n    \n    void offset_front(const Point& target) {\n        Point offset = target - front();\n        front() = target;\n        for (int i = 1; i < size() - 1; ++i) {\n            points[i] += offset * (size() - 1 - i) / (size() - 1.0);\n        }\n    }\n    \n    void offset_back (const Point& target) {\n        Point offset = target - back();\n        back() = target;\n        for (int i = 1; i < size() - 1; ++i) {\n            points[i] += offset * i / (size() - 1.0);\n        }\n    }\n    \n    double length() const {\n        double result = 0;\n        for (auto p : adjacent_pairs(*this, is_loop))\n            result += (p.first - p.second).norm();\n        \n        return result;\n    }\n    \n    void resample() { resample(size()); }\n    void resample_by_length(double segment_length) { resample(std::max<int>(static_cast<int>(length() / segment_length), 3)); }\n    void resample(int target_num_points) {\n        int NN = size();\n        \n        if (NN < 2 || target_num_points < 2)\n            return;\n        \n        if (target_num_points == 2) {\n            points[1] = back();\n            resize(2);\n            return;\n        }\n        \n        PolylineT result(target_num_points, is_loop);\n        \n        if (is_loop) {\n            push_back(front());\n            ++NN;\n        }\n        \n        std::vector<double> src_len_acc(NN, 0);\n        for (int i = 1; i < NN; ++i)\n            src_len_acc[i] = src_len_acc[i - 1] + (points[i] - points[i - 1]).norm();\n        \n        double tgt_len_segment = src_len_acc.back() / (target_num_points - 1.);\n        int src_i = 0;\n        double tgt_len_acc = 0;\n        int index = 0;\n        result[index++] = front();\n        while (true) {\n            while (tgt_len_acc + tgt_len_segment <= src_len_acc[src_i]) {\n                tgt_len_acc += tgt_len_segment;\n                double w1 = (tgt_len_acc - src_len_acc[src_i - 1]) / (src_len_acc[src_i] - src_len_acc[src_i - 1]);\n                double w0 = 1 - w1;\n                Point& p0 = points[src_i - 1];\n                Point& p1 = points[src_i];\n                Point p = p0 * w0 + p1 * w1;\n                result[index++] = p;\n                if (index == target_num_points - 1) break;\n            }\n            \n            if (index == target_num_points - 1) break;\n            \n            while (src_len_acc[src_i] <= tgt_len_acc + tgt_len_segment) {\n                ++src_i;\n            }\n        }\n        result[index++] = back();\n        \n        if (is_loop)\n            result.pop_back();\n        \n        *this = result;\n        return;\n    }\n    void insert_points_per_segment(int num_inserted_points_per_segment = 3) {\n        auto points_temp = points;\n        auto insert_pos = points_temp.begin();\n        for (auto i : adjacent_pairs(*this, is_loop)) {\n            auto d = (i.second - i.first) / (num_inserted_points_per_segment + 1.0);\n            Point p = i.first + d;\n            ++insert_pos;\n            for (int j = 0; j < num_inserted_points_per_segment; ++j, ++insert_pos, p += d)\n                insert_pos = points_temp.insert(insert_pos, p);\n        }\n        points = points_temp;\n    }\n    void smooth(int num_iter = 1, double weight_first_order = 1.0, double weight_second_order = 0.0, double damping = 0.5) {\n        for (int k = 0; k < num_iter; ++k) {\n            auto points_old = points;\n            for (int i = 0; i < size(); ++i) {\n                if (!is_loop && i == 0 || i == size() - 1)\n                    continue;\n                \n                int i_next  = (i + 1) % size();\n                int i_prev  = (i + size() - 1) % size();\n                int i_next2 = (i + 2) % size();\n                int i_prev2 = (i + size() - 2) % size();\n                \n                auto p_prev  = points_old[i_prev ];\n                auto p_next  = points_old[i_next ];\n                auto p_prev2 = points_old[i_prev2];\n                auto p_next2 = points_old[i_next2];\n                \n                Point p_first_order  = (p_prev + p_next) / 2.0;\n                Point p_second_order = (-p_prev2 + 4.0 * p_prev + 4.0 * p_next - p_next2) / 6.0;\n                \n                if (!is_loop && i == 1 || i == size() - 2)\n                    p_second_order = p_first_order;         // undefined\n                \n                Point p_target = (weight_first_order * p_first_order + weight_second_order * p_second_order) / (weight_first_order + weight_second_order);\n                \n                points[i] = damping * points_old[i] + (1 - damping) * p_target;\n            }\n        }\n    }\n    Point point_at(double arc_length_parameter) const {\n        if (arc_length_parameter < 0 || 1 < arc_length_parameter)\n            // arc length parameter should be between 0 and 1\n            return Point::Zero();\n        \n        if (arc_length_parameter == 0) return front();\n        if (arc_length_parameter == 1) return is_loop ? front() : back();\n        \n        const int NN = size();\n        const double target_length = length() * arc_length_parameter;\n        \n        double length_acc = 0;\n        for (int i = 0; i < NN; ++i) {\n            if (i == NN - 1 && !is_loop)\n                break;\n            \n            auto& p0 = points[i];\n            auto& p1 = points[(i + 1) % NN];\n            \n            double segment_length = (p1 - p0).norm();\n            if (length_acc <= target_length && target_length < length_acc + segment_length) {\n                double t = (target_length - length_acc) / segment_length;\n                return (1 - t) * p0 + t * p1;\n            }\n            \n            length_acc += segment_length;\n        }\n        \n        // something wrong happened\n        return Point::Zero();\n    }\n};\n\ntypedef PolylineT<2> Polyline2d;\ntypedef PolylineT<3> Polyline3d;\n\nstruct Polyline_PointNormal {\n    typedef std::vector<PointNormal>::iterator               iterator;\n    typedef std::vector<PointNormal>::reverse_iterator       reverse_iterator;\n    typedef std::vector<PointNormal>::const_iterator         const_iterator;\n    typedef std::vector<PointNormal>::const_reverse_iterator const_reverse_iterator;\n    \n    std::vector<PointNormal> points;\n    bool is_loop;\n    \n    Polyline_PointNormal()\n        : is_loop()\n    {}\n    Polyline_PointNormal(const std::vector<PointNormal>& points_, bool is_loop_)\n        : points (points_ )\n        , is_loop(is_loop_)\n    {}\n    Polyline_PointNormal(int size_, bool is_loop_)\n        : points (size_   )\n        , is_loop(is_loop_)\n    {}\n    \n    int size() const { return static_cast<int>(points.size()); }\n    bool empty() const { return points.empty(); }\n    void resize(int size_)                     { points.resize(size_); }\n    void resize(int size_, const PointNormal& point) { points.resize(size_, point); }\n    void clear() { points.clear(); }\n    void push_back(const PointNormal& point) { points.push_back(point); }\n    void pop_back ()                   { points.pop_back (); }\n    // Changed const_iterator to iterator to meet \"defect\" in standard\n    iterator  erase(iterator where_) { return points.erase(where_); }\n    iterator  erase(iterator first, iterator last) { return points.erase(first, last); }\n    iterator insert(iterator where_, const PointNormal& val) { return points.insert(where_, val); }\n    void     insert(iterator where_, int count, const PointNormal& val) { points.insert(where_, count, val); }\n    template <class InputIterator>\n    void     insert(iterator where_, InputIterator first, InputIterator last) { points.insert(where_, first, last); }\n    iterator                begin()       { return points. begin(); }\n    iterator                end  ()       { return points. end  (); }\n    reverse_iterator       rbegin()       { return points.rbegin(); }\n    reverse_iterator       rend  ()       { return points.rend  (); }\n    const_iterator          begin() const { return points. begin(); }\n    const_iterator          end  () const { return points. end  (); }\n    const_reverse_iterator rbegin() const { return points.rbegin(); }\n    const_reverse_iterator rend  () const { return points.rend  (); }\n          PointNormal& front()       { return points.front(); }\n    const PointNormal& front() const { return points.front(); }\n          PointNormal& back ()       { return points.back (); }\n    const PointNormal& back () const { return points.back (); }\n          PointNormal& operator[](int index)       { return points[index]; }\n    const PointNormal& operator[](int index) const { return points[index]; }\n    \n    void reverse() {\n        if (is_loop) {\n            std::reverse(points.begin(), points.end());\n        } else {\n            points.push_back(points.front());\n            std::reverse(points.begin(), points.end());\n            points.pop_back();\n        }\n    }\n    \n    void offset_front(const PointNormal& target) {\n        PointNormal offset = target - front();\n        front() = target;\n        for (int i = 1; i < size() - 1; ++i) {\n            points[i] += offset * (size() - 1 - i) / (size() - 1.0);\n            pn_normalize(points[i]);\n        }\n    }\n    \n    void offset_back (const PointNormal& target) {\n        PointNormal offset = target - back();\n        back() = target;\n        for (int i = 1; i < size() - 1; ++i) {\n            points[i] += offset * i / (size() - 1.0);\n            pn_normalize(points[i]);\n        }\n    }\n    \n    double length() const {\n        double result = 0;\n        \n        for (auto p : adjacent_pairs(*this, is_loop))\n            result += pn_norm(p.first - p.second);\n        \n        return result;\n    }\n    \n    void resample() { resample(size()); }\n    void resample_by_length(double segment_length) { resample(std::max<int>(static_cast<int>(length() / segment_length), 3)); }\n    void resample(int target_num_points) {\n        int N = size();\n        \n        if (N < 2 || target_num_points < 2)\n            return;\n        \n        if (target_num_points == 2) {\n            points[1] = back();\n            resize(2);\n            return;\n        }\n        \n        Polyline_PointNormal result(target_num_points, is_loop);\n        \n        if (is_loop) {\n            push_back(front());\n            ++N;\n        }\n        \n        std::vector<double> src_len_acc(N, 0);\n        for (int i = 1; i < N; ++i)\n            src_len_acc[i] = src_len_acc[i - 1] + pn_norm(points[i] - points[i - 1]);\n        \n        double tgt_len_segment = src_len_acc.back() / (target_num_points - 1.);\n        int src_i = 0;\n        double tgt_len_acc = 0;\n        int index = 0;\n        result[index++] = front();\n        while (true) {\n            while (tgt_len_acc + tgt_len_segment <= src_len_acc[src_i]) {\n                tgt_len_acc += tgt_len_segment;\n                double w1 = (tgt_len_acc - src_len_acc[src_i - 1]) / (src_len_acc[src_i] - src_len_acc[src_i - 1]);\n                double w0 = 1 - w1;\n                PointNormal& pn0 = points[src_i - 1];\n                PointNormal& pn1 = points[src_i];\n                PointNormal pn = pn0 * w0 + pn1 * w1;\n                pn_normalize(pn);\n                result[index++] = pn;\n                if (index == target_num_points - 1) break;\n            }\n            \n            if (index == target_num_points - 1) break;\n            \n            while (src_len_acc[src_i] <= tgt_len_acc + tgt_len_segment) {\n                ++src_i;\n            }\n        }\n        result[index++] = back();\n        \n        if (is_loop)\n            result.pop_back();\n        \n        *this = result;\n        return;\n    }\n    void insert_points_per_segment(int num_inserted_points_per_segment = 3) {\n        auto points_temp = points;\n        auto insert_pos = points_temp.begin();\n        for (auto i : adjacent_pairs(*this, is_loop)) {\n            auto d = (i.second - i.first) / (num_inserted_points_per_segment + 1.0);\n            PointNormal pn = i.first + d;\n            ++insert_pos;\n            for (int j = 0; j < num_inserted_points_per_segment; ++j, ++insert_pos, pn += d)\n                insert_pos = points_temp.insert(insert_pos, pn_normalized(pn));\n        }\n        points = points_temp;\n    }\n    void smooth(int num_iter = 1, double weight_first_order = 1.0, double weight_second_order = 0.0, double damping = 0.5) {\n        for (int k = 0; k < num_iter; ++k) {\n            auto points_old = points;\n            for (int i = 0; i < size(); ++i) {\n                if (!is_loop && i == 0 || i == size() - 1)\n                    continue;\n                \n                int i_next  = (i + 1) % size();\n                int i_prev  = (i + size() - 1) % size();\n                int i_next2 = (i + 2) % size();\n                int i_prev2 = (i + size() - 2) % size();\n                \n                auto p_prev  = points_old[i_prev ];\n                auto p_next  = points_old[i_next ];\n                auto p_prev2 = points_old[i_prev2];\n                auto p_next2 = points_old[i_next2];\n                \n                PointNormal p_first_order  = (p_prev + p_next) / 2.0;\n                PointNormal p_second_order = (-p_prev2 + 4.0 * p_prev + 4.0 * p_next - p_next2) / 6.0;\n                \n                if (!is_loop && i == 1 || i == size() - 2)\n                    p_second_order = p_first_order;         // undefined\n                \n                PointNormal p_target = (weight_first_order * p_first_order + weight_second_order * p_second_order) / (weight_first_order + weight_second_order);\n                \n                points[i] = damping * points_old[i] + (1 - damping) * p_target;\n                pn_normalize(points[i]);\n            }\n        }\n    }\n    PointNormal point_at(double arc_length_parameter) const {\n        if (arc_length_parameter < 0 || 1 < arc_length_parameter)\n            // arc length parameter should be between 0 and 1\n            return PointNormal::Zero();\n        \n        if (arc_length_parameter == 0) return front();\n        if (arc_length_parameter == 1) return is_loop ? front() : back();\n        \n        const int N = size();\n        const double target_length = length() * arc_length_parameter;\n        \n        double length_acc = 0;\n        for (int i = 0; i < N; ++i) {\n            if (i == N - 1 && !is_loop)\n                break;\n            \n            auto& pn0 = points[i];\n            auto& pn1 = points[(i + 1) % N];\n            \n            double segment_length = pn_norm(pn1 - pn0);\n            if (length_acc <= target_length && target_length < length_acc + segment_length) {\n                double t = (target_length - length_acc) / segment_length;\n                PointNormal pn = (1 - t) * pn0 + t * pn1;\n                pn_normalize(pn);\n                return pn;\n            }\n            \n            length_acc += segment_length;\n        }\n        \n        // something wrong happened\n        return PointNormal::Zero();\n    }\n};\n\n\n}\n\n", "meta": {"hexsha": "bad49cf54c78f184db65754145073764ecf47e0d", "size": 17861, "ext": "hh", "lang": "C++", "max_stars_repo_path": "src/kt84/geometry/PolylineT.hh", "max_stars_repo_name": "honoriocassiano/skbar", "max_stars_repo_head_hexsha": "e2a8fca752f5a2f9d9a32f19cbe1f9032a0e1ac4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/kt84/geometry/PolylineT.hh", "max_issues_repo_name": "honoriocassiano/skbar", "max_issues_repo_head_hexsha": "e2a8fca752f5a2f9d9a32f19cbe1f9032a0e1ac4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2020-09-01T12:16:28.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-01T12:21:41.000Z", "max_forks_repo_path": "src/kt84/geometry/PolylineT.hh", "max_forks_repo_name": "honoriocassiano/skbar", "max_forks_repo_head_hexsha": "e2a8fca752f5a2f9d9a32f19cbe1f9032a0e1ac4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.5154867257, "max_line_length": 160, "alphanum_fraction": 0.5260623705, "num_tokens": 4249, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5964331462646255, "lm_q2_score": 0.5506073655352404, "lm_q1q2_score": 0.32840048338266015}}
{"text": "#ifndef KINT_H_\n#define KINT_H_\n\n#include <boost/accumulators/accumulators.hpp>\n#include <boost/accumulators/statistics/stats.hpp>\n#include <boost/accumulators/statistics/sum.hpp>\n#include <boost/accumulators/framework/accumulator_base.hpp>\n#include <boost/accumulators/framework/extractor.hpp>\n#include <boost/accumulators/framework/parameters/sample.hpp>\n#include <boost/accumulators/framework/parameters/weight.hpp>\n#include <boost/accumulators/framework/accumulators/external_accumulator.hpp>\n#include <boost/accumulators/statistics/weighted_sum.hpp>\n#include <boost/accumulators/statistics/sum_kahan.hpp>\n\n#include <iostream>\n\n/*!\tThis class provides methods for integration over momenta or energies\n *\t\n *\tProblem:\n *\t\tParameters are: \n *\t\t- a: lattice spacing\n *\t\t- \\f$ D(\\eps) \\f$: density of states (DOS)\n *\t\t- Momentum, energy dependent function. In most cases this will be the impurity Green's \\f$ G(k,i\\omega_n) \\f$\n *\t\t- Some constant offset. In most cases \\f$ i \\omega_n + \\mu - \\Simga(i \\omega_n)\\f$\n *\t\t- function and limits for the integrand e.g.: \n *\t\t\\f[\n *\t\t\t\\int\\limits_{-\\frac{\\pi}{a}}^\\frac{\\pi}{a} d^D k \\frac{1}{i \\omega_n - \\epsilon_k + mu - \\Sigma (i \\omega_n)} \n *\t\t\\f]\n *\t\tor\n *\t\t\\f[\n *\t\t\t\\int\\limits_{-\\infty}^\\infty d^D \\epsilon \\frac{d(\\epsilon)}{i \\omega_n - \\epsilon_k + mu - \\Sigma (i \\omega_n)} \n *\t\t\\f]\n *\n *\tMethods:\n *\n *\t- summation (this constructs some general weighted D dimensional sum)\n *\t\t- riemann sum\n *\t\t- gaussian smearing\n *\t\t.\n *\n *\t- reformulation to ODE and solution via boost ODE int\n * \n *\t- Linear tetrahedral method for 1,2,3 D\n * \t\t- issues: can break symmetry, gamma point must be included\n *\t\t- use MFEM?\n *\t\t.\n *\n *\t- TODO: let user decide wether to use kahan summation or not\n */\t\nnamespace utility{\nusing KahanTag = boost::accumulators::tag::weighted_sum_kahan;\nusing KahanSumAccT = boost::accumulators::stats<KahanTag>;\ntemplate <typename T>\nusing AccT = boost::accumulators::accumulator_set<T, KahanSumAccT, T >;\n\n\nnamespace detail\n{\n\t/*!\tthis recursively constructs the depth of the nested for loops\n\t *\tfor the innermost loop the partially specialized struct Internal<D,0> is called\n\t */\n\ttemplate<unsigned int D, unsigned int ND, typename T, typename RetT >\n\tstruct Internal\n\t{\n\t\tstatic void sumKPoints(RetT (*integrand)(std::array<T, D> x),const std::array<T, D> &min,const std::array<T, D> &incs,\\\n\t\t\t const std::array<unsigned long, D> &N,std::array<T, D> &xVec, AccT<RetT> &acc)\n\t\t{\n\t\t\tRetT xi=min[ND];\n\t\t\tfor(unsigned int n=0; n<N[ND];n++)\n\t\t\t{\n\t\t\t\txVec[ND] = xi;\n\t\t\t\tInternal<D,ND-1, T, RetT>::sumKPoints(integrand, min, incs, N, xVec, acc);\n\t\t\t\tacc(boost::accumulators::extract_result<KahanTag>(acc), boost::accumulators::weight = incs[ND]);\n\n\t\t\t\txi+=incs[ND];\n\t\t\t}\n\t\t}\n\t};\n\n\ttemplate<unsigned int D, typename T, typename RetT>\n\tstruct Internal<D,0,T,RetT>\n\t{\n\t\tstatic void sumKPoints(RetT (*integrand)(std::array<T, D> x),const std::array<T, D> &min, \\\n\t\t\tconst std::array<T, D> &incs, const std::array<unsigned long, D> &N, std::array<T, D> &xVec, AccT<RetT> &acc)\n\t\t{\n\t\t\tRetT xi=min[0];\n\t\t\tfor(unsigned int n=0; n<N[0];n++)\n\t\t\t{\n\t\t\t\txVec[0] = xi;\n\t\t\t\tacc(integrand(xVec), boost::accumulators::weight = incs[0]);\n\t\t\t\txi+=incs[0];\n\t\t\t}\n\t\t}\n\t};\n}\n\n\n//TODO: 2 test types: 3 or 4 standard intrgrals, mean over >1000 VERY large OR mean over >MAXINT number of samples numbers (check for overflow)\n//TODO: let user specify weights, TODO: let user choose between kahan and normal sum\n\ntemplate<unsigned int D>\nclass KInt\n{\n\tpublic:\n\t\t/*!\t@brief\tinstantiates an accumulator for D nested for loops \\f$ \\sum\\limits_{min_1}^{max_1} ... \\sum\\limits_{min_D}^{max_D} f \\f$\n\t\t *\t\t\twith \\f$ f(T x_1, ... ,T x_D) -> T \\f$\n\t\t *\n\t\t *\t@param\tintegrand\tfunction pointer over which to sum\n\t\t *\t@param\tmin\t\t\tarray of start values (one element for each dimension)\n\t\t *\t@param\tmax\t\t\tarray of values for the upper limit (one element for each dimension)\n\t\t *\t@param\tN\t\t\tarray with number of steps (one element for each dimension)\n\t\t *\n\t\t *\t@return\taccumulated value\n\t\t */\n\t\ttemplate<typename T, typename RetT>\n\t\tRetT sumKPoints(RetT (*integrand)(std::array<T, D> x), std::array<T, D> &min, \\\n\t\t\tconst std::array<T, D> &max, const std::array<unsigned long, D> &N) const\n\t\t{\n\t\t\t//acc<summand type, method, weight type>\n\t\t\tAccT<RetT> acc;\n\t\t\tstd::array<T, D> incs; \t\t\t\t\t\t// increments in each dimension\n\t\t\tstd::array<T, D> xVec \t= min;\n\t\t\tfor(unsigned int d=0;d<D;d++) incs[d] = (max[d]-min[d])/N[d];\n\n\t\t\tdetail::Internal<D,D-1,T,RetT>::sumKPoints(integrand, min, incs, N, xVec, acc);\t\n\t\t\treturn boost::accumulators::extract_result<KahanTag>(acc);\n\t\t}\n\n\tprivate:\n\n};\n\n\t\t\n}\n#endif\n", "meta": {"hexsha": "268b7268bfb2e97258cb2ce3aab381a37763a99b", "size": 4627, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "AccD.hpp", "max_stars_repo_name": "Atomtomate/Memoizer", "max_stars_repo_head_hexsha": "dc3df7c139fbb5f4e6ccac5548503c909dbcd332", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "AccD.hpp", "max_issues_repo_name": "Atomtomate/Memoizer", "max_issues_repo_head_hexsha": "dc3df7c139fbb5f4e6ccac5548503c909dbcd332", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "AccD.hpp", "max_forks_repo_name": "Atomtomate/Memoizer", "max_forks_repo_head_hexsha": "dc3df7c139fbb5f4e6ccac5548503c909dbcd332", "max_forks_repo_licenses": ["BSD-3-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.0220588235, "max_line_length": 143, "alphanum_fraction": 0.6751674951, "num_tokens": 1472, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.66192288918838, "lm_q2_score": 0.4960938294709195, "lm_q1q2_score": 0.32837586091191856}}
{"text": "// Copyright (c) 2021 CNES\n//\n// All rights reserved. Use of this source code is governed by a\n// BSD-style license that can be found in the LICENSE file.\n#pragma once\n#include <pybind11/eigen.h>\n#include <pybind11/numpy.h>\n#include <pybind11/stl.h>\n\n#include <Eigen/Core>\n#include <atomic>\n#include <boost/accumulators/accumulators.hpp>\n#include <boost/accumulators/statistics/mean.hpp>\n#include <boost/accumulators/statistics/stats.hpp>\n\n#include \"pyinterp/detail/math.hpp\"\n#include \"pyinterp/detail/thread.hpp\"\n#include \"pyinterp/eigen.hpp\"\n#include \"pyinterp/grid.hpp\"\n\nnamespace pyinterp {\nnamespace detail {\n\n/// Calculate the zonal average in x direction\n///\n/// @param grid The grid to be processed.\n/// @param mask Matrix describing the undefined pixels of the grid providedNaN\n/// NumberReplaces all missing (_FillValue) values in a grid with values derived\n/// from solving Poisson's equation via relaxation. of threads used for the\n/// calculation\n///\n/// @param grid\ntemplate <typename Type>\nvoid set_zonal_average(pybind11::EigenDRef<Matrix<Type>>& grid,\n                       Matrix<bool>& mask, const size_t num_threads) {\n  // Captures the detected exceptions in the calculation function\n  // (only the last exception captured is kept)\n  auto except = std::exception_ptr(nullptr);\n\n  detail::dispatch(\n      [&](size_t y_start, size_t y_end) {\n        try {\n          // Calculation of longitude band means.\n          for (size_t iy = y_start; iy < y_end; ++iy) {\n            auto acc = boost::accumulators::accumulator_set<\n                Type,\n                boost::accumulators::stats<boost::accumulators::tag::count,\n                                           boost::accumulators::tag::mean>>();\n            for (int64_t ix = 0; ix < grid.rows(); ++ix) {\n              if (!mask(ix, iy)) {\n                acc(grid(ix, iy));\n              }\n            }\n\n            // The masked value is replaced by the average of the longitude band\n            // if it is defined; otherwise it is replaced by zero.\n            auto first_guess = boost::accumulators::count(acc)\n                                   ? boost::accumulators::mean(acc)\n                                   : Type(0);\n            for (int64_t ix = 0; ix < grid.rows(); ++ix) {\n              if (mask(ix, iy)) {\n                grid(ix, iy) = first_guess;\n              }\n            }\n          }\n        } catch (...) {\n          except = std::current_exception();\n        }\n      },\n      grid.cols(), num_threads);\n\n  if (except != nullptr) {\n    std::rethrow_exception(except);\n  }\n}\n\n///  Replaces all undefined values (NaN) in a grid using the Gauss-Seidel\n///  method by relaxation.\n///\n/// @param grid The grid to be processed\n/// @param is_circle True if the X axis of the grid defines a circle.\n/// @param relaxation Relaxation constant\n/// @return maximum residual value\ntemplate <typename Type>\nauto gauss_seidel(pybind11::EigenDRef<pyinterp::Matrix<Type>>& grid,\n                  Matrix<bool>& mask, const bool is_circle,\n                  const Type relaxation, const size_t num_threads) -> Type {\n  // Maximum residual values for each thread.\n  std::vector<Type> max_residuals(num_threads);\n\n  // Shape of the grid\n  auto x_size = grid.rows();\n  auto y_size = grid.cols();\n\n  // Captures the detected exceptions in the calculation function\n  // (only the last exception captured is kept)\n  auto except = std::exception_ptr(nullptr);\n\n  // Gets the index of the pixel (ix, iy) in the matrix.\n  auto coordinates = [](const int64_t ix, const int64_t iy,\n                        const int64_t size) -> int64_t {\n    return iy * size + ix;\n  };\n\n  // Thread worker responsible for processing several strips along the y-axis\n  // of the grid.\n  //\n  // @param y_start First index y of the band to be processed.\n  // @param y_end Last index y, excluded, of the band to be processed.\n  // @param max_residual Maximum residual of this strip.\n  // @param pipe_out Last index to be processed on in this band.\n  // @param pipe_in Last index processed in the previous band.\n  auto worker = [&](int64_t y_start, int64_t y_end, Type* max_residual,\n                    std::atomic<int64_t>* pipe_out,\n                    std::atomic<int64_t>* pipe_in) -> void {\n    // Modifies the value of a masked pixel.\n    auto cell_fill = [&grid, &relaxation, &max_residual](\n                         int64_t ix0, int64_t ix, int64_t ix1, int64_t iy0,\n                         int64_t iy, int64_t iy1) {\n      auto residual = (Type(0.25) * (grid(ix0, iy) + grid(ix1, iy) +\n                                     grid(ix, iy0) + grid(ix, iy1)) -\n                       grid(ix, iy)) *\n                      relaxation;\n      grid(ix, iy) += residual;\n      *max_residual = std::max(*max_residual, std::fabs(residual));\n    };\n\n    // Initialization of the maximum value of the residuals of the treated\n    // strips.\n    *max_residual = Type(0);\n\n    try {\n      for (auto ix = 0; ix < x_size; ++ix) {\n        //\n        auto ix0 = ix == 0 ? (is_circle ? x_size - 1 : 1) : ix - 1;\n        auto ix1 = ix == x_size - 1 ? (is_circle ? 0 : x_size - 2) : ix + 1;\n\n        // If necessary, check that the last index required for this block has\n        // been processed in the previous band.\n        if (pipe_in) {\n          auto next_coordinates = coordinates(ix, y_start, y_size);\n          while (*pipe_in < next_coordinates) {\n            std::this_thread::sleep_for(std::chrono::nanoseconds(5));\n          }\n        }\n\n        for (auto iy = y_start; iy < y_end; ++iy) {\n          auto iy0 = iy == 0 ? 1 : iy - 1;\n          auto iy1 = iy == y_size - 1 ? y_size - 2 : iy + 1;\n          if (mask(ix, iy)) {\n            cell_fill(ix0, ix, ix1, iy0, iy, iy1);\n          }\n        }\n\n        // If necessary, the other thread responsible for processing the next\n        // band is notified.\n        if (pipe_out) {\n          *pipe_out = coordinates(ix, y_end, y_size);\n        }\n      }\n    } catch (...) {\n      except = std::current_exception();\n    }\n  };\n\n  if (num_threads == 1) {\n    worker(0, y_size, &max_residuals[0], nullptr, nullptr);\n  } else {\n    assert(num_threads >= 2);\n    std::vector<std::atomic<int64_t>> pipeline(num_threads);\n    std::vector<std::thread> threads;\n\n    int64_t start = 0;\n    int64_t shift = y_size / num_threads;\n\n    for (auto& item : pipeline) {\n      item = std::numeric_limits<int>::min();\n    }\n\n    for (size_t index = 0; index < num_threads - 1; ++index) {\n      threads.emplace_back(std::thread(\n          worker, start, start + shift, &max_residuals[index], &pipeline[index],\n          index == 0 ? nullptr : &pipeline[index - 1]));\n      start += shift;\n    }\n    threads.emplace_back(std::thread(worker, start, y_size,\n                                     &max_residuals[num_threads - 1], nullptr,\n                                     &pipeline[num_threads - 2]));\n    for (auto&& item : threads) {\n      item.join();\n    }\n  }\n  if (except != nullptr) {\n    std::rethrow_exception(except);\n  }\n  return *std::max_element(max_residuals.begin(), max_residuals.end());\n}\n\n}  // namespace detail\n\nnamespace fill {\n\n/// Type of first guess grid.\nenum FirstGuess {\n  kZero,          //!< Use 0.0 as an initial guess\n  kZonalAverage,  //!< Use zonal average in x direction\n};\n\n/// Replaces all undefined values (NaN) in a grid using the Gauss-Seidel\n/// method by relaxation.\n///\n/// @param grid The grid to be processed\n/// @param is_circle True if the X axis of the grid defines a circle.\n/// @param max_iterations Maximum number of iterations to be used by relaxation.\n/// @param epsilon Tolerance for ending relaxation before the maximum number of\n/// iterations limit.\n/// @param relaxation Relaxation constant\n/// @param num_threads The number of threads to use for the computation. If 0\n/// all CPUs are used. If 1 is given, no parallel computing code is used at all,\n/// which is useful for debugging.\n/// @return A tuple containing the number of iterations performed and the\n/// maximum residual value.\ntemplate <typename Type>\nauto gauss_seidel(pybind11::EigenDRef<Matrix<Type>>& grid,\n                  const FirstGuess first_guess, const bool is_circle,\n                  const size_t max_iterations, const Type epsilon,\n                  const Type relaxation, size_t num_threads)\n    -> std::tuple<size_t, Type> {\n  /// If the grid doesn't have an undefined value, this routine has nothing more\n  /// to do.\n  if (!grid.hasNaN()) {\n    return std::make_tuple(0, Type(0));\n  }\n\n  /// Calculation of the maximum number of threads if the user chooses.\n  if (num_threads == 0) {\n    num_threads = std::thread::hardware_concurrency();\n  }\n\n  /// Calculation of the position of the undefined values on the grid.\n  auto mask = Matrix<bool>(grid.array().isNaN());\n\n  /// Calculation of the first guess with the chosen method\n  switch (first_guess) {\n    case FirstGuess::kZero:\n      grid = (mask.array()).select(0, grid);\n      break;\n    case FirstGuess::kZonalAverage:\n      detail::set_zonal_average(grid, mask, num_threads);\n      break;\n    default:\n      throw std::invalid_argument(\"Invalid guess type: \" +\n                                  std::to_string(first_guess));\n  }\n\n  // Initialization of the function results.\n  size_t iteration = 0;\n  Type max_residual = 0;\n\n  for (size_t it = 0; it < max_iterations; ++it) {\n    ++iteration;\n    max_residual = detail::gauss_seidel<Type>(grid, mask, is_circle, relaxation,\n                                              num_threads);\n    if (max_residual < epsilon) {\n      break;\n    }\n  }\n  return std::make_tuple(iteration, max_residual);\n}\n\n// Get the indexes that frame a given index.\ninline auto frame_index(const int64_t index, const int64_t size,\n                        const bool is_angle, std::vector<int64_t>& frame)\n    -> void {\n  // Index in the center of the window\n  auto center = static_cast<int64_t>(frame.size() / 2);\n\n  for (int64_t ix = 0; ix < static_cast<int64_t>(frame.size()); ++ix) {\n    auto idx = index - center + ix;\n\n    // Normalizing longitude?\n    if (is_angle) {\n      idx = detail::math::remainder(idx, size);\n    } else {\n      // Otherwise, the symmetrical indexes are used if the indexes are outside\n      // the domain definition.\n      if (idx < 0 || idx >= size) {\n        auto where = detail::math::remainder(idx, (size - 1) * 2);\n        if (where >= size) {\n          idx = size - 2 - detail::math::remainder(where, size);\n        } else {\n          idx = detail::math::remainder(where, size);\n        }\n      }\n    }\n    frame[ix] = idx;\n  }\n}\n\n/// Checking the size of the filter window.\ninline auto check_windows_size(const std::string& name1, const uint32_t size)\n    -> void {\n  if (size < 1) {\n    throw std::invalid_argument(name1 + \" must be >= 1\");\n  }\n}\n\n/// Checking the size of the filter window.\ntemplate <typename... Args>\ninline auto check_windows_size(const std::string& name1, uint32_t size,\n                               Args... args) -> void {\n  check_windows_size(name1, size);\n  check_windows_size(args...);\n}\n\n/// Type of values processed by the Loess filter.\nenum ValueType {\n  kUndefined,  //!< Undefined values (fill undefined values)\n  kDefined,    //!< Defined values (smooth values)\n  kAll         //!< Smooth and fill values\n};\n\n/// Fills undefined values using a locally weighted regression function or\n/// LOESS. The weight function used for LOESS is the tri-cube weight\n/// function, w(x)=(1-|d|^{3})^{3}\n///\n/// @param grid Grid Function on a uniform 2-dimensional grid to be filled.\n/// @param nx Number of points of the half-window to be taken into account\n/// along the longitude axis.\n/// @param nx Number of points of the half-window to be taken into account\n/// along the latitude axis.\n/// @param value_type Type of values processed by the filter\n/// @param num_threads The number of threads to use for the computation. If\n/// 0 all CPUs are used. If 1 is given, no parallel computing code is used\n/// at all, which is useful for debugging.\n/// @return The grid will have all the NaN filled with extrapolated values.\ntemplate <typename Type>\nauto loess(const Grid2D<Type>& grid, const uint32_t nx, const uint32_t ny,\n           const ValueType value_type, const size_t num_threads)\n    -> pybind11::array_t<Type> {\n  check_windows_size(\"nx\", nx, \"ny\", ny);\n  auto result = pybind11::array_t<Type>(\n      pybind11::array::ShapeContainer{grid.x()->size(), grid.y()->size()});\n  auto _result = result.template mutable_unchecked<2>();\n\n  // Captures the detected exceptions in the calculation function\n  // (only the last exception captured is kept)\n  auto except = std::exception_ptr(nullptr);\n\n  auto worker = [&](const size_t start, const size_t end) {\n    try {\n      // Access to the shared pointer outside the loop to avoid data races\n      const auto& x_axis = *grid.x();\n      const auto& y_axis = *grid.y();\n      auto x_frame = std::vector<int64_t>(nx * 2 + 1);\n      auto y_frame = std::vector<int64_t>(ny * 2 + 1);\n\n      for (size_t ix = start; ix < end; ++ix) {\n        auto x = x_axis(ix);\n\n        // We retrieve the indexes framing the current value.\n        frame_index(ix, x_axis.size(), x_axis.is_angle(), x_frame);\n\n        // Read the first value of the calculated window.\n        const auto x0 = x_axis(x_frame[0]);\n\n        // The current value is normalized to the first value in the\n        // window.\n        if (x_axis.is_angle()) {\n          x = detail::math::normalize_angle(x, x0, 360.0);\n        }\n\n        for (int64_t iy = 0; iy < y_axis.size(); ++iy) {\n          auto z = grid.value(ix, iy);\n\n          // If the current value is masked.\n          const auto undefined = std::isnan(z);\n          if (value_type == kAll || (value_type == kDefined && !undefined) ||\n              (value_type == kUndefined && undefined)) {\n            auto y = y_axis(iy);\n\n            // We retrieve the indexes framing the current value.\n            frame_index(iy, y_axis.size(), false, y_frame);\n\n            // Initialization of values to calculate the extrapolated\n            // value.\n            auto value = Type(0);\n            auto weight = Type(0);\n\n            // For all the coordinates of the frame.\n            for (auto wx : x_frame) {\n              auto xi = x_axis(wx);\n\n              // We normalize the window's coordinates to its first value.\n              if (x_axis.is_angle()) {\n                xi = detail::math::normalize_angle(xi, x0, 360.0);\n              }\n\n              for (auto wy : y_frame) {\n                auto zi = grid.value(wx, wy);\n\n                // If the value is not masked, its weight is calculated from\n                // the tri-cube weight function\n                if (!std::isnan(zi)) {\n                  const auto power = 3.0;\n                  auto d =\n                      std::sqrt(detail::math::sqr(((xi - x)) / nx) +\n                                detail::math::sqr(((y_axis(wy) - y)) / ny));\n                  auto wi = d <= 1 ? std::pow((1.0 - std::pow(d, power)), power)\n                                   : 0.0;\n                  value += static_cast<Type>(wi * zi);\n                  weight += static_cast<Type>(wi);\n                }\n              }\n            }\n\n            // Finally, we calculate the extrapolated value if possible,\n            // otherwise we will recopy the masked original value.\n            if (weight != 0) {\n              z = value / weight;\n            }\n          }\n          _result(ix, iy) = z;\n        }\n      }\n    } catch (...) {\n      except = std::current_exception();\n    }\n  };\n\n  {\n    pybind11::gil_scoped_release release;\n    detail::dispatch(worker, grid.x()->size(), num_threads);\n  }\n  return result;\n}\n\ntemplate <typename Type, typename AxisType>\nauto loess(const Grid3D<Type, AxisType>& grid, const uint32_t nx,\n           const uint32_t ny, const ValueType value_type,\n           const size_t num_threads) -> pybind11::array_t<Type> {\n  check_windows_size(\"nx\", nx, \"ny\", ny);\n  auto result = pybind11::array_t<Type>(pybind11::array::ShapeContainer{\n      grid.x()->size(), grid.y()->size(), grid.z()->size()});\n  auto _result = result.template mutable_unchecked<3>();\n\n  // Captures the detected exceptions in the calculation function\n  // (only the last exception captured is kept)\n  auto except = std::exception_ptr(nullptr);\n\n  auto worker = [&](const size_t start, const size_t end) {\n    try {\n      // Access to the shared pointer outside the loop to avoid data races\n      const auto& x_axis = *grid.x();\n      const auto& y_axis = *grid.y();\n      auto x_frame = std::vector<int64_t>(nx * 2 + 1);\n      auto y_frame = std::vector<int64_t>(ny * 2 + 1);\n\n      for (size_t iz = start; iz < end; ++iz) {\n        for (int64_t ix = 0; ix < x_axis.size(); ++ix) {\n          auto x = x_axis(ix);\n\n          // We retrieve the indexes framing the current value.\n          frame_index(ix, x_axis.size(), x_axis.is_angle(), x_frame);\n\n          // Read the first value of the calculated window.\n          const auto x0 = x_axis(x_frame[0]);\n\n          // The current value is normalized to the first value in the\n          // window.\n          if (x_axis.is_angle()) {\n            x = detail::math::normalize_angle(x, x0, 360.0);\n          }\n\n          for (int64_t iy = 0; iy < y_axis.size(); ++iy) {\n            auto z = grid.value(ix, iy, iz);\n\n            // If the current value is masked.\n            const auto undefined = std::isnan(z);\n            if (value_type == kAll || (value_type == kDefined && !undefined) ||\n                (value_type == kUndefined && undefined)) {\n              auto y = y_axis(iy);\n\n              // We retrieve the indexes framing the current value.\n              frame_index(iy, y_axis.size(), false, y_frame);\n\n              // Initialization of values to calculate the extrapolated\n              // value.\n              auto value = Type(0);\n              auto weight = Type(0);\n\n              // For all the coordinates of the frame.\n              for (auto wx : x_frame) {\n                auto xi = x_axis(wx);\n\n                // We normalize the window's coordinates to its first value.\n                if (x_axis.is_angle()) {\n                  xi = detail::math::normalize_angle(xi, x0, 360.0);\n                }\n\n                for (auto wy : y_frame) {\n                  auto zi = grid.value(wx, wy, iz);\n\n                  // If the value is not masked, its weight is calculated\n                  // from the tri-cube weight function\n                  if (!std::isnan(zi)) {\n                    const auto power = 3.0;\n                    auto d =\n                        std::sqrt(detail::math::sqr(((xi - x)) / nx) +\n                                  detail::math::sqr(((y_axis(wy) - y)) / ny));\n                    auto wi = d <= 1\n                                  ? std::pow((1.0 - std::pow(d, power)), power)\n                                  : 0.0;\n                    value += static_cast<Type>(wi * zi);\n                    weight += static_cast<Type>(wi);\n                  }\n                }\n              }\n\n              // Finally, we calculate the extrapolated value if possible,\n              // otherwise we will recopy the masked original value.\n              if (weight != 0) {\n                z = value / weight;\n              }\n            }\n            _result(ix, iy, iz) = z;\n          }\n        }\n      }\n    } catch (...) {\n      except = std::current_exception();\n    }\n  };\n\n  {\n    pybind11::gil_scoped_release release;\n    detail::dispatch(worker, grid.z()->size(), num_threads);\n  }\n  return result;\n}\n\n}  // namespace fill\n}  // namespace pyinterp\n", "meta": {"hexsha": "0614454de16d1a920099b5d8235c0a8e700a07cb", "size": 19616, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/pyinterp/core/include/pyinterp/fill.hpp", "max_stars_repo_name": "CNES/pangeo-pyinterp", "max_stars_repo_head_hexsha": "5f75f62a6c681db89c5aa8c74e43fc04a77418c3", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 67.0, "max_stars_repo_stars_event_min_datetime": "2019-07-09T09:10:22.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-01T09:46:35.000Z", "max_issues_repo_path": "src/pyinterp/core/include/pyinterp/fill.hpp", "max_issues_repo_name": "CNES/pangeo-pyinterp", "max_issues_repo_head_hexsha": "5f75f62a6c681db89c5aa8c74e43fc04a77418c3", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 8.0, "max_issues_repo_issues_event_min_datetime": "2019-07-15T13:54:31.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-28T05:06:34.000Z", "max_forks_repo_path": "src/pyinterp/core/include/pyinterp/fill.hpp", "max_forks_repo_name": "CNES/pangeo-pyinterp", "max_forks_repo_head_hexsha": "5f75f62a6c681db89c5aa8c74e43fc04a77418c3", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2019-07-15T17:28:16.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-19T19:43:47.000Z", "avg_line_length": 36.0588235294, "max_line_length": 80, "alphanum_fraction": 0.5768250408, "num_tokens": 4694, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6619228758499942, "lm_q2_score": 0.49609382947091946, "lm_q1q2_score": 0.32837585429482763}}
{"text": "//\n// Created by daeyun on 5/10/17.\n//\n\n#include \"meshdist.h\"\n\n#include <Eigen/Dense>\n#include <type_traits>\n#include <chrono>\n\n#include \"lib/common.h\"\n#include \"lib/random_utils.h\"\n#include \"lib/benchmark.h\"\n\nnamespace scene3d {\nnamespace meshdist_cgal {\n\ntypedef CGAL::Simple_cartesian<float> K;\ntypedef std::list<K::Triangle_3>::iterator Iterator;\ntypedef CGAL::AABB_triangle_primitive<K, Iterator> Primitive;\ntypedef CGAL::AABB_traits<K, Primitive> AABB_triangle_traits;\ntypedef CGAL::AABB_tree<AABB_triangle_traits> Tree;\n\nvoid Triangle::ApplyRt(const Mat34 &M) {\n  auto R = M.leftCols<3>();\n  auto t = M.col(3);\n  a = (R * a + t).eval();\n  b = (R * b + t).eval();\n  c = (R * c + t).eval();\n  OnTransformation();\n}\n\nvoid Triangle::ApplyR(const Mat33 &M) {\n  a = (M * a).eval();\n  b = (M * b).eval();\n  c = (M * c).eval();\n  OnTransformation();\n}\n\nvoid Triangle::Translate(const Vec3 &dxyz) {\n  a += dxyz;\n  b += dxyz;\n  c += dxyz;\n  OnTransformation();\n}\n\nvoid Triangle::Print() const {\n  std::cout << a.transpose() << \",      \"\n            << b.transpose() << \",      \"\n            << c.transpose() << std::endl;\n}\n\nVec3 Triangle::SamplePoint() const {\n  Vec2 v12{scene3d::Random::Rand(), scene3d::Random::Rand()};\n  if (v12.sum() > 1) {\n    v12 = 1 - v12.array();\n  }\n  return a + (v12(0) * ab_) + (v12(1) * ac_);\n}\n\ndouble Triangle::Area() const {\n  return ab_.cross(ac_).norm() * 0.5f;\n}\n\nvoid Triangle::OnTransformation() {\n  assert(a.allFinite());\n  assert(b.allFinite());\n  assert(c.allFinite());\n\n  ab_ = b - a;\n  ac_ = c - a;\n}\n\nvoid SamplePointsOnTriangles(const std::vector<Triangle> &triangles, float density, Points3d *points, std::vector<size_t> *triangle_indices) {\n  std::vector<double> areas;\n  areas.reserve(triangles.size());\n  for (auto &&triangle : triangles) {\n    areas.push_back(triangle.Area());\n  }\n\n  double surface_area = std::accumulate(areas.begin(), areas.end(), static_cast<double>(0));\n  Expects(surface_area > 0.0);\n\n  int num_samples = static_cast<int>(surface_area * density);\n  if (num_samples <= 0) {\n    // Surface area is non-zero\n    // the density parameter is not big enough. This should be a rare case. For now, print warning and just make sure to sample at least one point.\n    num_samples = 1;\n    LOGGER->warn(\"density is too small. Surface area is {}\", surface_area);\n  }\n  Expects(num_samples > 0);\n\n  std::discrete_distribution<> distribution(std::begin(areas), std::end(areas));\n\n  Eigen::Matrix<int, Dynamic, 1> counts;\n\n  Eigen::Matrix<int, Dynamic, Dynamic> local_counts;\n\n#pragma omp parallel if (USE_OMP && num_samples > 1e6)\n  {\n    const int num_threads = omp_get_num_threads();\n    const int i_thread = omp_get_thread_num();\n\n#pragma omp single\n    {\n      local_counts.resize(triangles.size(), num_threads);\n      local_counts.fill(0);\n    }\n\n#pragma omp for\n    for (int i = 0; i < num_samples; ++i) {\n      ++local_counts(distribution(scene3d::Random::Engine()), i_thread);\n    }\n  }\n\n  counts = local_counts.rowwise().sum();\n\n  points->resize(3, num_samples);\n  if (triangle_indices) {\n    triangle_indices->resize(static_cast<size_t>(num_samples));\n  }\n  int k = 0;\n  for (int i = 0; i < triangles.size(); ++i) {\n    for (int j = 0; j < counts(i); ++j) {\n      points->col(k) = triangles[i].SamplePoint();\n      if (triangle_indices) {\n        triangle_indices->push_back((size_t) i);\n      }\n      ++k;\n    }\n  }\n  Expects(k == num_samples);\n\n  Eigen::PermutationMatrix<Dynamic, Dynamic> perm(points->cols());\n  perm.setIdentity();\n  std::shuffle(perm.indices().data(), perm.indices().data() + perm.indices().size(), scene3d::Random::Engine());\n  *points *= perm; // permute columns\n}\n\n// TODO(daeyun): divide by mean distance\n\nfloat MeshToMeshDistanceOneDirection(const std::vector<Triangle> &from,\n                                     const std::vector<Triangle> &to,\n                                     float sampling_density,\n                                     std::vector<float> *distances) {\n\n  Points3d points;\n\n  SamplePointsOnTriangles(from, sampling_density, &points);\n\n  std::list<K::Triangle_3> triangle_list;\n  for (const auto &triangle : to) {\n    triangle_list.emplace_back(K::Point_3{triangle.a[0], triangle.a[1], triangle.a[2]},\n                               K::Point_3{triangle.b[0], triangle.b[1], triangle.b[2]},\n                               K::Point_3{triangle.c[0], triangle.c[1], triangle.c[2]});\n  }\n  std::vector<K::Point_3> point_list;\n  for (int i = 0; i < points.cols(); ++i) {\n    point_list.emplace_back(points(0, i), points(1, i), points(2, i));\n  }\n\n  int num_triangles = static_cast<int>(to.size());\n  int num_points = static_cast<int>(points.cols());\n\n  LOGGER->debug(\"Computing minimum distances from {} points to {} triangles.\", num_points, num_triangles);\n\n  auto start = scene3d::TimeSinceEpoch<std::milli>();\n  Tree tree(triangle_list.begin(), triangle_list.end());\n  tree.build();\n  tree.accelerate_distance_queries();\n  LOGGER->debug(\"Time elapsed for building tree (CGAL): {}\", scene3d::TimeSinceEpoch<std::milli>() - start);\n\n  float distance_sum = 0;\n\n#pragma omp parallel for if(USE_OMP) reduction(+:distance_sum) schedule(static)\n  for (int i = 0; i < point_list.size(); ++i) {\n    float dist = tree.squared_distance(point_list[i]);\n    distance_sum += dist;\n\n// TODO: needs refactoring\n    if (distances) {\n#pragma omp critical\n      distances->push_back(dist);\n    }\n  }\n\n  LOGGER->debug(\"distance: {}\", distance_sum);\n  float rms = static_cast<float>(std::sqrt(distance_sum / static_cast<double>(point_list.size())));\n  LOGGER->debug(\"RMS: {}\", rms);\n  auto elapsed = scene3d::TimeSinceEpoch<std::milli>() - start;\n  LOGGER->debug(\"Time elapsed (CGAL): {} ms\", elapsed);\n\n  return rms;\n}\n\nfloat PointsToMeshDistanceOneDirection(const std::vector<std::array<float, 3>> &from,\n                                       const std::vector<Triangle> &to) {\n  std::list<K::Triangle_3> triangle_list;\n  for (const auto &triangle : to) {\n    triangle_list.emplace_back(K::Point_3{triangle.a[0], triangle.a[1], triangle.a[2]},\n                               K::Point_3{triangle.b[0], triangle.b[1], triangle.b[2]},\n                               K::Point_3{triangle.c[0], triangle.c[1], triangle.c[2]});\n  }\n  std::vector<K::Point_3> point_list;\n  for (int i = 0; i < from.size(); ++i) {\n    point_list.emplace_back(from[i][0], from[i][1], from[i][2]);\n  }\n\n  int num_triangles = static_cast<int>(to.size());\n  int num_points = static_cast<int>(from.size());\n\n  LOGGER->debug(\"Computing minimum distances from {} points to {} triangles.\", num_points, num_triangles);\n\n  auto start = scene3d::TimeSinceEpoch<std::milli>();\n  Tree tree(triangle_list.begin(), triangle_list.end());\n  tree.build();\n  tree.accelerate_distance_queries();\n  LOGGER->debug(\"Time elapsed for building tree (CGAL): {}\", scene3d::TimeSinceEpoch<std::milli>() - start);\n\n  float distance_sum = 0;\n\n#pragma omp parallel for if(USE_OMP) reduction(+:distance_sum) schedule(static)\n  for (int i = 0; i < point_list.size(); ++i) {\n    float dist = tree.squared_distance(point_list[i]);\n    distance_sum += dist;\n  }\n\n  LOGGER->debug(\"distance: {}\", distance_sum);\n  float rms = static_cast<float>(std::sqrt(distance_sum / static_cast<double>(point_list.size())));\n\n  LOGGER->debug(\"RMS: {}\", rms);\n  auto elapsed = scene3d::TimeSinceEpoch<std::milli>() - start;\n  LOGGER->debug(\"Time elapsed (CGAL): {} ms\", elapsed);\n\n  return rms;\n}\n\nfloat MeshToPointsDistanceOneDirection(const std::vector<Triangle> &from,\n                                       const std::vector<std::array<float, 3>> &target_points,\n                                       float sampling_density) {\n  std::list<K::Triangle_3> triangle_list;\n  for (const auto &triangle : from) {\n    triangle_list.emplace_back(K::Point_3{triangle.a[0], triangle.a[1], triangle.a[2]},\n                               K::Point_3{triangle.b[0], triangle.b[1], triangle.b[2]},\n                               K::Point_3{triangle.c[0], triangle.c[1], triangle.c[2]});\n  }\n\n  Points3d points_on_mesh;\n  SamplePointsOnTriangles(from, sampling_density, &points_on_mesh);\n\n  int num_source_points = static_cast<int>(points_on_mesh.cols());\n  int num_target_points = static_cast<int>(target_points.size());\n\n  LOGGER->debug(\"Computing minimum distances from {} points on triangles to {} points.\", num_source_points, num_target_points);\n\n  auto start = scene3d::TimeSinceEpoch<std::milli>();\n\n  float distance_sum = 0;\n\n#pragma omp parallel for if(USE_OMP) reduction(+:distance_sum) schedule(static)\n  for (int i = 0; i < num_source_points; ++i) {\n    const auto source_point = points_on_mesh.col(i);\n    double min_dist = kInfinity;\n    // TODO(daeyun): this is brute force\n    for (int j = 0; j < num_target_points; ++j) {\n      double dx = (source_point(0) - target_points[j][0]);\n      double dy = (source_point(1) - target_points[j][1]);\n      double dz = (source_point(2) - target_points[j][2]);\n      double dist = std::sqrt(dx * dx + dy * dy + dz * dz);\n      if (dist < min_dist) {\n        min_dist = dist;\n      }\n    }\n    distance_sum += min_dist;\n  }\n\n  LOGGER->debug(\"distance: {}\", distance_sum);\n  float rms = static_cast<float>(std::sqrt(distance_sum / static_cast<double>(num_source_points)));\n\n  LOGGER->debug(\"RMS: {}\", rms);\n  auto elapsed = scene3d::TimeSinceEpoch<std::milli>() - start;\n  LOGGER->debug(\"Time elapsed (CGAL): {} ms\", elapsed);\n\n  return rms;\n}\n\nfloat MeshToMeshDistance(const std::vector<Triangle> &a, const std::vector<Triangle> &b) {\n  auto start = scene3d::TimeSinceEpoch<std::milli>();\n\n  constexpr int kSamplingDensity = 300;\n\n  float d1 = meshdist_cgal::MeshToMeshDistanceOneDirection(a, b, kSamplingDensity);\n  float d2 = meshdist_cgal::MeshToMeshDistanceOneDirection(b, a, kSamplingDensity);\n\n  auto elapsed = scene3d::TimeSinceEpoch<std::milli>() - start;\n  LOGGER->debug(\"Time elapsed (MeshToMeshDistance): {} ms\", elapsed);\n  LOGGER->debug(\"{}, {}\", d1, d2);\n  return static_cast<float>((d1 + d2) * 0.5);\n}\n\nvoid TrianglesFromTriMesh(const TriMesh &mesh, std::vector<Triangle> *out) {\n  for (const auto &face: mesh.faces) {\n    const auto &v1 = mesh.vertices[face[0]];\n    const auto &v2 = mesh.vertices[face[1]];\n    const auto &v3 = mesh.vertices[face[2]];\n    out->push_back(Triangle(Vec3{v1[0], v1[1], v1[2]}, Vec3{v2[0], v2[1], v2[2]}, Vec3{v3[0], v3[1], v3[2]}));\n  }\n}\n\n}\n}\n", "meta": {"hexsha": "befa316161628fe12e55e006e8d047facef34c98", "size": 10352, "ext": "cc", "lang": "C++", "max_stars_repo_path": "lib/meshdist.cc", "max_stars_repo_name": "daeyun/mesh-point-cloud", "max_stars_repo_head_hexsha": "5caf663827ad6fe10b40bdf3763a40bc013e9205", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2018-10-17T06:14:49.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-13T00:47:08.000Z", "max_issues_repo_path": "lib/meshdist.cc", "max_issues_repo_name": "daeyun/mesh-point-cloud", "max_issues_repo_head_hexsha": "5caf663827ad6fe10b40bdf3763a40bc013e9205", "max_issues_repo_licenses": ["MIT"], "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/meshdist.cc", "max_forks_repo_name": "daeyun/mesh-point-cloud", "max_forks_repo_head_hexsha": "5caf663827ad6fe10b40bdf3763a40bc013e9205", "max_forks_repo_licenses": ["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.1794871795, "max_line_length": 147, "alphanum_fraction": 0.6400695518, "num_tokens": 2826, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6619228758499942, "lm_q2_score": 0.49609382947091946, "lm_q1q2_score": 0.32837585429482763}}
{"text": "#pragma warning(disable:4996)\n#include <functional>\n#include <thread>\n#include <mutex>\n\n#include <boost/functional/hash.hpp>\n#include <boost/algorithm/string.hpp>\n\n#include <cppoptlib/meta.h>\n#include <cppoptlib/problem.h>\n#include <cppoptlib/solver/bfgssolver.h>\n\n#include <cmaes.h>\n\n#include <Unicode.hpp>\n\n//#define USE_OPTIONAL_LIB\n\n#ifdef USE_OPTIONAL_LIB\n#define USE_NLOPT\n#ifndef M_PI\n#define M_PI 3.14159265358979323846\n#endif\n\n#include <nlopt.hpp>\n\n#include <limbo/acqui.hpp>\n#include <limbo/bayes_opt/boptimizer.hpp>\n#include <limbo/kernel/matern_five_halves.hpp>\n#include <limbo/mean/data.hpp>\n#include <limbo/model/gp.hpp>\n#include <limbo/stat.hpp>\n#include <limbo/tools/macros.hpp>\n\n#ifdef _DEBUG\n#pragma comment(lib, \"Debug/nlopt_cxx.lib\")\n#else\n#pragma comment(lib, \"Release/nlopt_cxx.lib\")\n#endif\n\n//struct Params {\n//\tstruct acqui_gpucb : public limbo::defaults::acqui_gpucb {\n//\t};\n//\n//#ifdef USE_NLOPT\n//\tstruct opt_nloptnograd : public limbo::defaults::opt_nloptnograd {\n//\t};\n//#elif defined(USE_LIBCMAES)\n//\tstruct opt_cmaes : public defaults::opt_cmaes {\n//\t};\n//#else\n//\tstruct opt_gridsearch : public limbo::defaults::opt_gridsearch {\n//\t};\n//#endif\n//\tstruct acqui_ucb {\n//\t\tBO_PARAM(double, alpha, 0.1);\n//\t};\n//\n//\tstruct kernel : public limbo::defaults::kernel {\n//\t\tBO_PARAM(double, noise, 0.001);\n//\t};\n//\n//\tstruct kernel_maternfivehalves {\n//\t\tBO_PARAM(double, sigma_sq, 1);\n//\t\tBO_PARAM(double, l, 0.2);\n//\t};\n//\tstruct kernel_exp : public limbo::defaults::kernel_exp {\n//\t};\n//\tstruct bayes_opt_bobase : public limbo::defaults::bayes_opt_bobase {\n//\t\tBO_PARAM(bool, stats_enabled, true);\n//\t};\n//\n//\tstruct bayes_opt_boptimizer : public limbo::defaults::bayes_opt_boptimizer {\n//\t};\n//\n//\tstruct init_randomsampling {\n//\t\tBO_PARAM(int, samples, 5);\n//\t};\n//\n//\tstruct stop_maxiterations {\n//\t\tBO_PARAM(int, iterations, 20);\n//\t};\n//\tstruct stat_gp {\n//\t\tBO_PARAM(int, bins, 20);\n//\t};\n//\n//\tstruct kernel_squared_exp_ard : public limbo::defaults::kernel_squared_exp_ard {\n//\t};\n//\n//\tstruct opt_rprop : public limbo::defaults::opt_rprop {\n//\t};\n//};\n\nstruct Params {\n\tstruct bayes_opt_boptimizer : public limbo::defaults::bayes_opt_boptimizer {\n\t\tBO_PARAM(int, hp_period, 10);\n\t};\n\tstruct bayes_opt_bobase : public limbo::defaults::bayes_opt_bobase {\n\t\tBO_PARAM(int, stats_enabled, true);\n\t};\n\t\n\tstruct init_randomsampling {\n\t\tBO_PARAM(int, samples, 100);\n\t};\n\tstruct stop_maxiterations {\n\t\tBO_PARAM(int, iterations, 500);\n\t};\n\tstruct stop_mintolerance {\n\t\tBO_PARAM(double, tolerance, -0.1);\n\t};\n\n\tstruct acqui_ei {\n\t\tBO_PARAM(double, jitter, 0.0);\n\t};\n\n\t//struct acqui_gpucb : public limbo::defaults::acqui_gpucb {\n\t//};\n\t//struct acqui_ucb {\n\t//\t//BO_PARAM(double, alpha, 0.1);\n\t//\t//BO_PARAM(double, alpha, 0.3);\n\t//\tBO_PARAM(double, alpha, 0.5);\n\t//};\n\n\t/*struct kernel : public limbo::defaults::kernel {\n\t\tBO_PARAM(double, noise, 0.001);\n\t};*/\n\tstruct kernel : public limbo::defaults::kernel {\n\t\t//BO_PARAM(double, noise, 1.e-10);\n\t\tBO_PARAM(double, noise, 0.01);\n\t};\n\tstruct kernel_squared_exp_ard : public limbo::defaults::kernel_squared_exp_ard {\n\t};\n\tstruct kernel_maternfivehalves {\n\t\tBO_PARAM(double, sigma_sq, 1);\n\t\tBO_PARAM(double, l, 0.2);\n\t};\n\tstruct kernel_exp : public limbo::defaults::kernel_exp {\n\t};\n\n\tstruct stat_gp {\n\t\tBO_PARAM(int, bins, 3);\n\t};\n\n\tstruct opt_nloptnograd : public limbo::defaults::opt_nloptnograd {\n\t};\n\tstruct opt_rprop : public limbo::defaults::opt_rprop {\n\t};\n};\n\nstruct LimboFitFunc {\n\tstd::function<double(const Eigen::VectorXd& x)> func;\n\tsize_t numOfVars;\n\tsize_t dim_in()const { return numOfVars; }\n\tsize_t dim_out()const { return 1; }\n\n\tEigen::VectorXd operator()(const Eigen::VectorXd& x) const\n\t{\n\t\treturn limbo::tools::make_vector(func(x));\n\t}\n};\n#endif\n\n#include <Pita/Node.hpp>\n#include <Pita/Context.hpp>\n#include <Pita/OptimizationEvaluator.hpp>\n#include <Pita/Parser.hpp>\n#include <Pita/Evaluator.hpp>\n#include <Pita/Printer.hpp>\n#include <Pita/IntrinsicGeometricFunctions.hpp>\n\nextern bool printAddressInsertion;\nextern double cloneTime;\nextern unsigned cloneCount;\nextern bool isDebugMode;\n\nnamespace cgl\n{\n\tstd::string UnaryOpToStr(UnaryOp op)\n\t{\n\t\tswitch (op)\n\t\t{\n\t\tcase UnaryOp::Not:     return \"Not\";\n\t\tcase UnaryOp::Plus:    return \"Plus\";\n\t\tcase UnaryOp::Minus:   return \"Minus\";\n\t\tcase UnaryOp::Dynamic: return \"Dynamic\";\n\t\t}\n\n\t\treturn \"UnknownUnaryOp\";\n\t}\n\n\tstd::string BinaryOpToStr(BinaryOp op)\n\t{\n\t\tswitch (op)\n\t\t{\n\t\tcase BinaryOp::And: return \"And\";\n\t\tcase BinaryOp::Or:  return \"Or\";\n\n\t\tcase BinaryOp::Equal:        return \"Equal\";\n\t\tcase BinaryOp::NotEqual:     return \"NotEqual\";\n\t\tcase BinaryOp::LessThan:     return \"LessThan\";\n\t\tcase BinaryOp::LessEqual:    return \"LessEqual\";\n\t\tcase BinaryOp::GreaterThan:  return \"GreaterThan\";\n\t\tcase BinaryOp::GreaterEqual: return \"GreaterEqual\";\n\n\t\tcase BinaryOp::Add: return \"Add\";\n\t\tcase BinaryOp::Sub: return \"Sub\";\n\t\tcase BinaryOp::Mul: return \"Mul\";\n\t\tcase BinaryOp::Div: return \"Div\";\n\n\t\tcase BinaryOp::Pow:    return \"Pow\";\n\t\tcase BinaryOp::Assign: return \"Assign\";\n\n\t\tcase BinaryOp::Concat: return \"Concat\";\n\n\t\tcase BinaryOp::SetDiff: return \"SetDiff\";\n\t\t}\n\n\t\treturn \"UnknownBinaryOp\";\n\t}\n\n\tbool IsVec2(const Val& value)\n\t{\n\t\tif (!IsType<Record>(value))\n\t\t{\n\t\t\treturn false;\n\t\t}\n\n\t\tconst auto& values = As<Record>(value).values;\n\t\treturn values.find(\"x\") != values.end() && values.find(\"y\") != values.end();\n\t}\n\n\tbool IsShape(const Val& value)\n\t{\n\t\tif (!IsType<Record>(value))\n\t\t{\n\t\t\treturn false;\n\t\t}\n\n\t\tconst auto& values = As<Record>(value).values;\n\t\treturn values.find(\"x\") == values.end() || values.find(\"y\") == values.end();\n\t}\n\n\tEigen::Vector2d AsVec2(const Val& value, const Context& context)\n\t{\n\t\tconst auto& values = As<Record>(value).values;\n\n\t\tconst Val xval = context.expand(LRValue(values.find(\"x\")->second), LocationInfo());\n\t\tconst Val yval = context.expand(LRValue(values.find(\"y\")->second), LocationInfo());\n\n\t\treturn Eigen::Vector2d(AsDouble(xval), AsDouble(yval));\n\t}\n\n\t//manip::LocationInfoPrinter LocationInfo::printLoc() const { return { *this }; }\n\tstd::string LocationInfo::getInfo() const\n\t{\n\t\tstd::stringstream ss;\n\t\tss << \"[L\" << locInfo_lineBegin << \":\" << locInfo_posBegin << \"-\" << \"L\" << locInfo_lineEnd << \":\" << locInfo_posEnd << \"]\";\n\t\treturn ss.str();\n\t}\n\n\tIdentifier Identifier::MakeIdentifier(const std::u32string& name_)\n\t{\n\t\treturn Identifier(Unicode::UTF32ToUTF8(name_));\n\t}\n\n\tbool Identifier::isDeferredCall()const\n\t{\n\t\treturn boost::starts_with(name, \"#DeferredCall\");\n\t}\n\n\tIdentifier Identifier::asDeferredCall(const ScopeAddress& identifierScopeInfo)const\n\t{\n\t\tif (isDeferredCall())\n\t\t{\n\t\t\treturn *this;\n\t\t}\n\n\t\tstd::string head(\"#DeferredCall(\");\n\t\tfor (unsigned scopeIndex : identifierScopeInfo)\n\t\t{\n\t\t\thead += std::to_string(scopeIndex) + \",\";\n\t\t}\n\t\thead += \")\";\n\t\t\n\t\treturn Identifier(head + name);\n\t}\n\n\tbool Identifier::isMakeClosure()const\n\t{\n\t\treturn boost::starts_with(name, \"#MakeClosure\");\n\t}\n\n\tIdentifier Identifier::asMakeClosure(const ScopeAddress& identifierScopeInfo)const\n\t{\n\t\tif (isMakeClosure())\n\t\t{\n\t\t\treturn *this;\n\t\t}\n\n\t\tstd::string head(\"#MakeClosure(\");\n\t\tfor (unsigned scopeIndex : identifierScopeInfo)\n\t\t{\n\t\t\thead += std::to_string(scopeIndex) + \",\";\n\t\t}\n\t\thead += \")\";\n\n\t\treturn Identifier(head + name);\n\t}\n\n\tstd::pair<ScopeAddress, Identifier> Identifier::decomposed()const\n\t{\n\t\tif (!isDeferredCall() && !isMakeClosure())\n\t\t{\n\t\t\treturn { {},*this };\n\t\t}\n\n\t\tconst size_t tagEndIndex = name.find_first_of(')');\n\n\t\tScopeAddress scopeAddress;\n\t\t{\n\t\t\tconst std::string scopeIndices(name.begin() + name.find_first_of('(') + 1, name.begin() + tagEndIndex);\n\t\t\tsize_t currentPos = 0;\n\t\t\tsize_t nextPos = scopeIndices.find_first_of(',', currentPos);\n\t\t\twhile (nextPos != std::string::npos)\n\t\t\t{\n\t\t\t\tconst std::string currentStr(scopeIndices.begin() + currentPos, scopeIndices.begin() + nextPos);\n\t\t\t\tconst int scopeIndex = std::stoi(currentStr);\n\t\t\t\tscopeAddress.push_back(scopeIndex);\n\t\t\t\tcurrentPos = nextPos + 1;\n\t\t\t\tnextPos = scopeIndices.find_first_of(',', currentPos);\n\t\t\t}\n\t\t}\n\n\t\tconst Identifier rawIdentifier(std::string(name.begin() + tagEndIndex + 1, name.end()));\n\t\treturn { scopeAddress,rawIdentifier };\n\t}\n\n\tbool EitherReference::localReferenciable(const Context& context)const\n\t{\n\t\treturn local && context.existsInLocalScope(local.get());\n\t}\n\n\tstd::string EitherReference::toString()const\n\t{\n\t\tstd::stringstream ss;\n\t\tss << (local ? local.get().toString() : std::string(\"None\"));\n\t\tss << \" | \" << \"Address(\" << replaced.toString() << \")\";\n\t\treturn ss.str();\n\t}\n\n\tLRValue LRValue::Bool(bool a)\n\t{\n\t\treturn LRValue(Val(a));\n\t}\n\t\n\tLRValue LRValue::Int(int a)\n\t{\n\t\treturn LRValue(Val(a));\n\t}\n\n\tLRValue LRValue::Float(const std::u32string& str)\n\t{\n\t\treturn LRValue(std::stod(Unicode::UTF32ToUTF8(str)));\n\t}\n\n\tLRValue& LRValue::setLocation(const LocationInfo& info)\n\t{\n\t\tlocInfo_lineBegin = info.locInfo_lineBegin;\n\t\tlocInfo_lineEnd = info.locInfo_lineEnd;\n\t\tlocInfo_posBegin = info.locInfo_posBegin;\n\t\tlocInfo_posEnd = info.locInfo_posEnd;\n\t\treturn *this;\n\t}\n\n\tbool LRValue::isValid() const\n\t{\n\t\treturn IsType<Address>(value)\n\t\t\t? As<Address>(value).isValid()\n\t\t\t: true; //EitherReference/Reference/Val は常に有効であるものとする\n\t}\n\n\tboost::optional<Address> LRValue::deref(const Context& env)const\n\t{\n\t\tif (isRValue())\n\t\t{\n\t\t\treturn boost::none;\n\t\t}\n\n\t\treturn address(env);\n\t}\n\n\tstd::string LRValue::toString() const\n\t{\n\t\tif (isAddress())\n\t\t{\n\t\t\treturn std::string(\"Address(\") + As<Address>(value).toString() + std::string(\")\");\n\t\t}\n\t\telse if (isReference())\n\t\t{\n\t\t\treturn std::string(\"Reference(\") + As<Reference>(value).toString() + std::string(\")\");\n\t\t}\n\t\telse if (isEitherReference())\n\t\t{\n\t\t\treturn std::string(\"EitherReference(\") + As<EitherReference>(value).toString() + std::string(\")\");\n\t\t}\n\t\telse\n\t\t{\n\t\t\treturn std::string(\"Val(...)\");\n\t\t}\n\t}\n\n\tstd::string LRValue::toString(Context& context) const\n\t{\n\t\tif (isAddress())\n\t\t{\n\t\t\treturn std::string(\"Address(\") + As<Address>(value).toString() + std::string(\")\");\n\t\t}\n\t\telse if (isReference())\n\t\t{\n\t\t\treturn std::string(\"Reference(\") + As<Reference>(value).toString() + std::string(\")\");\n\t\t}\n\t\telse if (isEitherReference())\n\t\t{\n\t\t\treturn std::string(\"EitherReference(\") + As<EitherReference>(value).toString() + std::string(\")\");\n\t\t}\n\t\telse\n\t\t{\n\t\t\treturn std::string(\"Val(...)\");\n\t\t}\n\t}\n\n\tAddress LRValue::address(const Context & context) const\n\t{\n\t\treturn IsType<Address>(value)\n\t\t\t? As<Address>(value)\n\t\t\t: (IsType<EitherReference>(value)\n\t\t\t\t? As<EitherReference>(value).replaced\n\t\t\t\t: context.getReference(As<Reference>(value)));\n\t}\n\n\tAddress LRValue::getReference(const Context& context)const\n\t{\n\t\treturn context.getReference(As<Reference>(value));\n\t}\n\n\tAddress LRValue::makeTemporaryValue(Context& context)const\n\t{\n\t\treturn context.makeTemporaryValue(evaluated());\n\t}\n\n\tclass ExprImportForm : public boost::static_visitor<Expr>\n\t{\n\tpublic:\n\t\tExprImportForm(bool isTopLevel)\n\t\t\t:isTopLevel(isTopLevel)\n\t\t{}\n\n\t\tbool isTopLevel;\n\n\t\tExpr operator()(const Lines& node)const\n\t\t{\n\t\t\tif (!isTopLevel)\n\t\t\t{\n\t\t\t\treturn node;\n\t\t\t}\n\n\t\t\tRecordConstractor result;\n\t\t\tfor (const auto& expr : node.exprs)\n\t\t\t{\n\t\t\t\tresult.add(boost::apply_visitor(ExprImportForm(false), expr));\n\t\t\t}\n\n\t\t\treturn result;\n\t\t}\n\n\t\tExpr operator()(const BinaryExpr& node)const\n\t\t{\n\t\t\tif (node.op != BinaryOp::Assign)\n\t\t\t{\n\t\t\t\treturn node;\n\t\t\t}\n\n\t\t\tKeyExpr keyExpr(As<Identifier>(node.lhs));\n\t\t\tKeyExpr::SetExpr(keyExpr, node.rhs);\n\t\t\treturn keyExpr;\n\t\t}\n\n\t\tExpr operator()(const LRValue& node)const { return node; }\n\t\tExpr operator()(const Identifier& node)const { return node; }\n\t\tExpr operator()(const Import& node)const { return node; }\n\t\tExpr operator()(const UnaryExpr& node)const { return node; }\n\t\tExpr operator()(const Range& node)const { return node; }\n\t\tExpr operator()(const DefFunc& node)const { return node; }\n\t\tExpr operator()(const If& node)const { return node; }\n\t\tExpr operator()(const For& node)const { return node; }\n\t\tExpr operator()(const Return& node)const { return node; }\n\t\tExpr operator()(const ListConstractor& node)const { return node; }\n\t\tExpr operator()(const KeyExpr& node)const { return node; }\n\t\tExpr operator()(const RecordConstractor& node)const { return node; }\n\t\tExpr operator()(const Accessor& node)const { return node; }\n\t\tExpr operator()(const DeclSat& node)const { return node; }\n\t\tExpr operator()(const DeclFree& node)const { return node; }\n\t};\n\n\tExpr ToImportForm(const Expr& expr)\n\t{\n\t\tExprImportForm converter(true);\n\t\treturn boost::apply_visitor(converter, expr);\n\t}\n\n\tImport::Import(const std::u32string& filePath)\n\t{\n#ifdef USE_IMPORT\n\t\tconst std::string u8FilePath = Unicode::UTF32ToUTF8(filePath);\n\t\tconst auto path = cgl::filesystem::path(u8FilePath);\n\n\t\tCGL_DBG1(std::string(\"import path: \\\"\") + u8FilePath + \"\\\"\");\n\n\t\tstd::string sourceCode;\n\n\t\tif (path.is_absolute())\n\t\t{\n\t\t\tconst std::string pathStr = filesystem::canonical(path).string();\n\n\t\t\timportPath = pathStr;\n\n\t\t\t/*if (alreadyImportedFiles.find(filesystem::canonical(path)) != alreadyImportedFiles.end())\n\t\t\t{\n\t\t\t\tstd::cout << \"File \\\"\" << path.string() << \"\\\" has been already imported.\\n\";\n\t\t\t\toriginalParseTree = boost::none;\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\talreadyImportedFiles.emplace(filesystem::canonical(path));\n\n\t\t\tstd::ifstream ifs(u8FilePath);\n\t\t\tif (!ifs.is_open())\n\t\t\t{\n\t\t\t\tCGL_Error(std::string() + \"Error: import file \\\"\" + u8FilePath + \"\\\" does not exists.\");\n\t\t\t}\n\n\t\t\tsourceCode = std::string((std::istreambuf_iterator<char>(ifs)), std::istreambuf_iterator<char>());\n\t\t\tcgl::workingDirectories.emplace(path.parent_path());*/\n\t\t}\n\t\telse\n\t\t{\n\t\t\tconst auto currentDirectory = workingDirectories.top();\n\t\t\tconst auto currentFilePath = currentDirectory / path;\n\t\t\tconst std::string pathStr = filesystem::canonical(currentFilePath).string();\n\n\t\t\tCGL_DBG1(std::string(\"canonical path: \\\"\") + pathStr + \"\\\"\");\n\n\t\t\timportPath = pathStr;\n\t\t\t/*if (alreadyImportedFiles.find(filesystem::canonical(currentFilePath)) != alreadyImportedFiles.end())\n\t\t\t{\n\t\t\t\tstd::cout << \"File \\\"\" << filesystem::canonical(currentFilePath).string() << \"\\\" has been already imported.\\n\";\n\t\t\t\toriginalParseTree = boost::none;\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\talreadyImportedFiles.emplace(filesystem::canonical(currentFilePath));\n\n\t\t\tstd::ifstream ifs(currentFilePath.string());\n\t\t\tif (!ifs.is_open())\n\t\t\t{\n\t\t\t\tCGL_Error(std::string() + \"Error: import file \\\"\" + currentFilePath.string() + \"\\\" does not exists.\");\n\t\t\t}\n\n\t\t\tsourceCode = std::string((std::istreambuf_iterator<char>(ifs)), std::istreambuf_iterator<char>());\n\t\t\tcgl::workingDirectories.emplace(currentFilePath.parent_path());*/\n\t\t}\n\n\t\t/*if (auto opt = Parse(sourceCode))\n\t\t{\n\t\t\toriginalParseTree = opt;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tCGL_Error(\"Parse failed.\");\n\t\t}*/\n\t\tupdateHash();\n#else\n\t\tCGL_Error(\"Filesystem is disabled.\");\n#endif\n\t}\n\n\tImport::Import(const std::u32string& path, const Identifier& name):\n\t\tImport(path)\n\t{\n\t\timportName = name;\n\t\tupdateHash();\n\t}\n\n\tLRValue Import::eval(std::shared_ptr<Context> pContext)const\n\t{\n#ifdef USE_IMPORT\n\t\tauto it = importedParseTrees.find(seed);\n\t\tif (it == importedParseTrees.end() || !it->second)\n\t\t{\n\t\t\tCGL_Error(\"ファイルのimportに失敗\");\n\t\t}\n\n\t\tconst auto& expr = it->second.get();\n\n\t\t//通常のインポート\n\t\t//import filename\n\t\tif (importName.empty())\n\t\t{\n\t\t\treturn ExecuteProgramWithRec(expr, pContext);\n\t\t}\n\t\t//修飾付きインポート\n\t\t//import filename as name\n\t\t//トップレベルの代入式をレコードの要素に包んで評価する\n\t\telse\n\t\t{\n\t\t\tconst Expr importParseTree = BinaryExpr(Identifier(importName), ToImportForm(expr), BinaryOp::Assign);\n\t\t\t//printExpr(importParseTree, pContext, std::cout);\n\t\t\treturn ExecuteProgramWithRec(importParseTree, pContext);\n\t\t}\n#else\n\t\tCGL_Error(\"Import is disabled.\");\n#endif\n\t}\n\n\tvoid Import::SetName(Import& node, const Identifier& name)\n\t{\n\t\tnode.importName = name;\n\t\tnode.updateHash();\n\t}\n\n\tvoid Import::updateHash()\n\t{\n\t\tseed = 0;\n\t\tboost::hash_combine(seed, importPath);\n\t\tboost::hash_combine(seed, importName);\n\t}\n\n\tExpr BuildString(const std::u32string& str32)\n\t{\n\t\tExpr expr;\n\t\texpr = LRValue(CharString(str32));\n\n\t\treturn expr;\n\t}\n\n\t//Expr BuildShapeExpander(const Accessor& accessor)\n\t//{\n\t//\tExpr expr;\n\t//\t//expr = LRValue(CharString(str32));\n\t//\t//Accessor callFunction;\n\t//\t//callFunction.AppendFunction(FunctionAccess());\n\t//\t//FunctionAccess f;\n\n\t//\t/*FuncVal({},\n\t//\t\tMakeRecordConstructor(\n\t//\t\t\tIdentifier(\"line\"), MakeListConstractor(\n\t//\t\t\t\tMakeRecordConstructor(Identifier(\"x\"), Expr(LRValue(minX)), Identifier(\"y\"), Expr(LRValue(minY))),\n\t//\t\t\t\tMakeRecordConstructor(Identifier(\"x\"), Expr(LRValue(maxX)), Identifier(\"y\"), Expr(LRValue(minY)))\n\t//\t\t\t)\n\t//\t\t)*/\n\t//\treturn expr;\n\t//}\n\n#ifdef commentout\n\tclass ConstraintProblem : public cppoptlib::Problem<double>\n\t{\n\tpublic:\n\t\tusing typename cppoptlib::Problem<double>::TVector;\n\n\t\tstd::function<double(const TVector&)> evaluator;\n\t\tRecord originalRecord;\n\t\tstd::vector<Identifier> keyList;\n\t\tstd::shared_ptr<Context> pEnv;\n\n\t\tbool callback(const cppoptlib::Criteria<cppoptlib::Problem<double>::Scalar>& state, const TVector& x) override;\n\n\t\tdouble value(const TVector &x) override\n\t\t{\n\t\t\treturn evaluator(x);\n\t\t}\n\t};\n\n\tbool ConstraintProblem::callback(const cppoptlib::Criteria<cppoptlib::Problem<double>::Scalar> &state, const TVector &x)\n\t{\n\t\t/*\n\t\tRecord tempRecord = originalRecord;\n\n\t\tfor (size_t i = 0; i < x.size(); ++i)\n\t\t{\n\t\tAddress address = originalRecord.freeVariableRefs[i];\n\t\tpEnv->assignToObject(address, x[i]);\n\t\t}\n\n\t\tfor (const auto& key : keyList)\n\t\t{\n\t\tAddress address = pEnv->findAddress(key);\n\t\ttempRecord.append(key, address);\n\t\t}\n\n\t\tProgressStore::TryWrite(pEnv, tempRecord);\n\t\t*/\n\t\treturn true;\n\t}\n#endif\n\n\tclass ConstraintProblem : public cppoptlib::Problem<double>\n\t{\n\tpublic:\n\t\tusing typename cppoptlib::Problem<double>::TVector;\n\n\t\tstd::function<double(const TVector&)> evaluator;\n\t\tRecord originalRecord;\n\t\tstd::vector<Identifier> keyList;\n\t\tstd::shared_ptr<Context> pEnv;\n\n\t\tdouble beginTime;\n\n\t\tbool callback(const cppoptlib::Criteria<cppoptlib::Problem<double>::Scalar>& state, const TVector& x) override;\n\n\t\tdouble value(const TVector &x) override\n\t\t{\n\t\t\treturn evaluator(x);\n\t\t}\n\t};\n\n\tbool ConstraintProblem::callback(const cppoptlib::Criteria<cppoptlib::Problem<double>::Scalar> &state, const TVector &x)\n\t{\n\t\tif (!pEnv->hasTimeLimit())\n\t\t{\n\t\t\treturn true;\n\t\t}\n\n\t\tif (pEnv->timeLimit() < GetSec() - beginTime)\n\t\t{\n\t\t\treturn false;\n\t\t}\n\n\t\treturn true;\n\t}\n\n\tvoid OptimizationProblemSat::addUnitConstraint(const Expr& logicExpr)\n\t{\n\t\tif (expr)\n\t\t{\n\t\t\texpr = BinaryExpr(expr.get(), logicExpr, BinaryOp::And);\n\t\t}\n\t\telse\n\t\t{\n\t\t\texpr = logicExpr;\n\t\t}\n\t}\n\n\t//void OptimizationProblemSat::constructConstraint(std::shared_ptr<Context> pEnv, std::vector<std::pair<Address, VariableRange>>& freeVariables)\n\tvoid OptimizationProblemSat::constructConstraint(std::shared_ptr<Context> pEnv)\n\t{\n\t\trefs.clear();\n\t\tinvRefs.clear();\n\t\thasPlateausFunction = false;\n\n\t\t//if (!expr || freeVariableRefs.empty())\n\t\tif (!expr)\n\t\t{\n\t\t\tCGL_DBG1(\"Warning: constraint expression is empty.\");\n\t\t\treturn;\n\t\t}\n\t\t//CGL_DBG1(\"Expr: \");\n\t\t//printExpr2(expr.get(), pEnv, std::cout);\n\t\tif (freeVariableRefs.empty())\n\t\t{\n\t\t\tCGL_DBG1(\"Warning: free variable set in constraint is empty.\");\n\t\t\treturn;\n\t\t}\n\n\t\tstd::unordered_set<Address> appearingList;\n\n\t\t/*CGL_DBG1(\"freeVariables:\");\n\t\tfor (const auto& val : freeVariableRefs)\n\t\t{\n\t\t\tCGL_DBG1(std::string(\"  Address(\") + val.first.toString() + \")\");\n\t\t}*/\n\n\t\tstd::vector<char> usedInSat(freeVariableRefs.size(), 0);\n\n\t\tSatVariableBinder binder(pEnv, freeVariableRefs, usedInSat, refs, appearingList, invRefs, hasPlateausFunction);\n\n\t\t/*CGL_DBG1(\"appearingList:\");\n\t\tfor (const auto& a : appearingList)\n\t\t{\n\t\t\tCGL_DBG1(std::string(\"  Address(\") + a.toString() + \")\");\n\t\t}*/\n\n\t\tif (boost::apply_visitor(binder, expr.get()))\n\t\t{\n\t\t\t//refs = binder.refs;\n\t\t\t//invRefs = binder.invRefs;\n\t\t\t//hasPlateausFunction = binder.hasPlateausFunction;\n\n\t\t\t//satに出てこないfreeVariablesの削除\n\t\t\tfor (int i = static_cast<int>(freeVariableRefs.size()) - 1; 0 <= i; --i)\n\t\t\t{\n\t\t\t\tif (usedInSat[i] == 0)\n\t\t\t\t{\n\t\t\t\t\tfreeVariableRefs.erase(freeVariableRefs.begin() + i);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\trefs.clear();\n\t\t\tinvRefs.clear();\n\t\t\tfreeVariableRefs.clear();\n\t\t\thasPlateausFunction = false;\n\t\t}\n\t}\n\n\tbool OptimizationProblemSat::initializeData(std::shared_ptr<Context> pEnv)\n\t{\n\t\tdata.resize(refs.size());\n\n\t\tfor (size_t i = 0; i < data.size(); ++i)\n\t\t{\n\t\t\tconst auto opt = pEnv->expandOpt(LRValue(refs[i]));\n\t\t\tif (!opt)\n\t\t\t{\n\t\t\t\tCGL_Error(\"参照エラー\");\n\t\t\t}\n\t\t\tconst Val& val = opt.get();\n\t\t\tif (auto opt = AsOpt<double>(val))\n\t\t\t{\n\t\t\t\tCGL_DebugLog(ToS(i) + \" : \" + ToS(opt.get()));\n\t\t\t\tdata[i] = opt.get();\n\t\t\t}\n\t\t\telse if (auto opt = AsOpt<int>(val))\n\t\t\t{\n\t\t\t\tCGL_DebugLog(ToS(i) + \" : \" + ToS(opt.get()));\n\t\t\t\tdata[i] = opt.get();\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tCGL_Error(\"存在しない参照をsatに指定した\");\n\t\t\t}\n\t\t}\n\n\t\treturn true;\n\t}\n\n\tstd::vector<double> OptimizationProblemSat::solve(std::shared_ptr<Context> pEnv, const LocationInfo& info, const Record currentRecord, const std::vector<Identifier>& currentKeyList)\n\t{\n\t\tstd::cerr << \"OptimizationProblemSat::solve : \" << std::endl;\n\t\tprintExpr2(expr.get(), pEnv, std::cerr);\t\t\n\n\t\tconstructConstraint(pEnv);\n\t\tCGL_DBG1(std::string(\"Current constraint freeVariablesSize: \") + ToS(freeVariableRefs.size()));\n\n\t\t/*if (isDebugMode && expr)\n\t\t{\n\t\t\tstd::ofstream graphFile;\n\t\t\tgraphFile.open(\"constraint_CFG.dot\");\n\t\t\tMakeGraph(*pEnv, expr.get(), graphFile);\n\t\t}*/\n\n\t\tstd::ofstream logger;\n\t\tif (isDebugMode)\n\t\t{\n\t\t\tlogger.open(\"optimize_log.cgl\");\n\n\t\t\tfor (const auto& ref : freeVariableRefs)\n\t\t\t{\n\t\t\t\tCGL_DBG1(pEnv->makeLabel(ref.address));\n\t\t\t}\n\n\t\t\tlogger << \"{\\n\";\n\t\t\tlogger << \"\\tsize: \" << freeVariableRefs.size() << \"\\n\";\n\t\t\tlogger << \"\\tlabels: [\\n\";\n\t\t\tfor (const auto& ref : freeVariableRefs)\n\t\t\t{\n\t\t\t\tlogger << \"\\t\\t\\\"\" << pEnv->makeLabel(ref.address) << \"\\\"\\n\";\n\t\t\t}\n\t\t\tlogger << \"\\t]\\n\";\n\n\t\t\tlogger << \"\\tdata: [\\n\";\n\t\t}\n\n\t\t/*{\n\t\t\tstd::stringstream ss;\n\t\t\tfor (const auto& r : optimizeRegions)\n\t\t\t{\n\t\t\t\tss << \"index(\" << r.startIndex << \",\" << (r.startIndex + r.numOfIndices) << \"), \";\n\t\t\t}\n\t\t\tCGL_DBG1(ss.str());\n\t\t}*/\n\n\t\tstd::vector<Interval> rangeList;\n\t\t{\n\t\t\tfor (const auto& r: optimizeRegions)\n\t\t\t{\n\t\t\t\t//std::cout << \"index(\" << r.startIndex << \",\" << (r.startIndex + r.numOfIndices) << \")\\n\";\n\n\t\t\t\tif (IsType<PackedVal>(r.region))\n\t\t\t\t{\n\t\t\t\t\tconst auto& val = As<PackedVal>(r.region);\n\n\t\t\t\t\t//varに範囲指定がないときはmakePackedRangesを通るときに仮として0が設定されている。\n\t\t\t\t\tif (IsType<int>(val))\n\t\t\t\t\t{\n\t\t\t\t\t\tfor (const Address address : r.addresses)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tauto it = std::find_if(freeVariableRefs.begin(), freeVariableRefs.end(), \n\t\t\t\t\t\t\t\t[&](const RegionVariable& regionVariable) {\n\t\t\t\t\t\t\t\treturn regionVariable.address == address;\n\t\t\t\t\t\t\t});\n\n\t\t\t\t\t\t\tif (it == freeVariableRefs.end())\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tCGL_Error(\"恐らく Evaluator.cpp の maskedRegionVariables() のバグ\");\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tdouble minVal;\n\t\t\t\t\t\t\tdouble maxVal;\n\t\t\t\t\t\t\tif (it->has(RegionVariable::Position))\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tminVal = -1000;\n\t\t\t\t\t\t\t\tmaxVal = +1000;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse if (it->has(RegionVariable::Scale))\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tminVal = 1.e-3;\n\t\t\t\t\t\t\t\tmaxVal = 1.e+3;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse if (it->has(RegionVariable::Angle))\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tminVal = -180;\n\t\t\t\t\t\t\t\tmaxVal = +180;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse if (it->has(RegionVariable::Other))\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tminVal = -1.e+6;\n\t\t\t\t\t\t\t\tmaxVal = +1.e+6;\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\tCGL_Error(\"不明な属性\");\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\trangeList.push_back(Interval(minVal, maxVal));\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t/*for (int i = 0; i < r.numOfIndices; ++i)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tconst int currentIndex = r.startIndex + i;\n\n\t\t\t\t\t\t\tdouble minVal;\n\t\t\t\t\t\t\tdouble maxVal;\n\t\t\t\t\t\t\tif (freeVariableRefs[currentIndex].has(RegionVariable::Position))\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tminVal = -1000;\n\t\t\t\t\t\t\t\tmaxVal = +1000;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse if (freeVariableRefs[currentIndex].has(RegionVariable::Scale))\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tminVal = 1.e-3;\n\t\t\t\t\t\t\t\tmaxVal = 1.e+3;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse if (freeVariableRefs[currentIndex].has(RegionVariable::Angle))\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tminVal = -180;\n\t\t\t\t\t\t\t\tmaxVal = +180;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse if (freeVariableRefs[currentIndex].has(RegionVariable::Other))\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tminVal = -1.e+6;\n\t\t\t\t\t\t\t\tmaxVal = +1.e+6;\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\tCGL_Error(\"不明な属性\");\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\trangeList.push_back(Interval(minVal, maxVal));\n\t\t\t\t\t\t}*/\n\t\t\t\t\t}\n\t\t\t\t\telse if (IsType<PackedRecord>(val))\n\t\t\t\t\t{\n\t\t\t\t\t\tconst auto& shapeRegion = As<PackedRecord>(val);\n\t\t\t\t\t\tconst auto& values = shapeRegion.values;\n\t\t\t\t\t\tif (values.find(\"pos\") == values.end() ||\n\t\t\t\t\t\t\tvalues.find(\"scale\") == values.end() ||\n\t\t\t\t\t\t\tvalues.find(\"angle\") == values.end())\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tCGL_Error(\"範囲の型が不正\");\n\t\t\t\t\t\t}\n\t\t\t\t\t\tconst auto bb = GetBoundingBox(shapeRegion, pEnv);\n\t\t\t\t\t\tconst auto minRecord = As<PackedRecord>(bb.values.find(\"min\")->second.value);\n\t\t\t\t\t\tconst auto maxRecord = As<PackedRecord>(bb.values.find(\"max\")->second.value);\n\n\t\t\t\t\t\tconst double minX = AsDouble(minRecord.values.find(\"x\")->second.value);\n\t\t\t\t\t\tconst double minY = AsDouble(minRecord.values.find(\"y\")->second.value);\n\t\t\t\t\t\tconst double maxX = AsDouble(maxRecord.values.find(\"x\")->second.value);\n\t\t\t\t\t\tconst double maxY = AsDouble(maxRecord.values.find(\"y\")->second.value);\n\n\t\t\t\t\t\t//TODO: ちゃんとインデックスを見て対応付ける\n\t\t\t\t\t\t//現在はvarはVec2のみでx,yの順に並んでいると仮定している\n\t\t\t\t\t\trangeList.push_back(Interval(minX, maxX));\n\t\t\t\t\t\trangeList.push_back(Interval(minY, maxY));\n\t\t\t\t\t}\n\t\t\t\t\telse if (IsType<PackedList>(val))\n\t\t\t\t\t{\n\t\t\t\t\t\tconst auto& intervalRegion = As<PackedList>(val);\n\t\t\t\t\t\tif (intervalRegion.data.size() != 2 ||\n\t\t\t\t\t\t\t!IsNum(intervalRegion.data[0].value) ||\n\t\t\t\t\t\t\t!IsNum(intervalRegion.data[1].value))\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tCGL_Error(\"範囲の型が不正\");\n\t\t\t\t\t\t}\n\t\t\t\t\t\tconst double minV = AsDouble(intervalRegion.data[0].value);\n\t\t\t\t\t\tconst double maxV = AsDouble(intervalRegion.data[1].value);\n\n\t\t\t\t\t\t/*for (int i = 0; i < r.numOfIndices; ++i)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\trangeList.push_back(Interval(minV, maxV));\n\t\t\t\t\t\t}*/\n\n\t\t\t\t\t\tfor (const Address address : r.addresses)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\trangeList.push_back(Interval(minV, maxV));\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\tCGL_Error(\"範囲の型が不正\");\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\tCGL_Error(\"範囲の型が不正\");\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif (!initializeData(pEnv))\n\t\t{\n\t\t\tCGL_Error(\"制約の初期化に失敗\");\n\t\t}\n\n\t\tstd::vector<double> resultxs;\n\t\tif (!freeVariableRefs.empty())\n\t\t{\n\t\t\t//varのアドレス(の内実際にsatに現れるもののリスト)から、OptimizationProblemSat中の変数リストへの対応付けを行うマップを作成\n\t\t\tstd::unordered_map<int, int> variable2Data;\n\t\t\tfor (size_t freeIndex = 0; freeIndex < freeVariableRefs.size(); ++freeIndex)\n\t\t\t{\n\t\t\t\tCGL_DebugLog(ToS(freeIndex));\n\t\t\t\tCGL_DebugLog(std::string(\"Address(\") + freeVariableRefs[freeIndex].toString() + \")\");\n\t\t\t\tconst auto& ref1 = freeVariableRefs[freeIndex];\n\n\t\t\t\tbool found = false;\n\t\t\t\tfor (size_t dataIndex = 0; dataIndex < refs.size(); ++dataIndex)\n\t\t\t\t{\n\t\t\t\t\tCGL_DebugLog(ToS(dataIndex));\n\t\t\t\t\tCGL_DebugLog(std::string(\"Address(\") + refs[dataIndex].toString() + \")\");\n\n\t\t\t\t\tconst auto& ref2 = refs[dataIndex];\n\n\t\t\t\t\tif (ref1.address == ref2)\n\t\t\t\t\t{\n\t\t\t\t\t\t//std::cout << \"    \" << freeIndex << \" -> \" << dataIndex << std::endl;\n\n\t\t\t\t\t\tfound = true;\n\t\t\t\t\t\tvariable2Data[freeIndex] = dataIndex;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t//DeclFreeにあってDeclSatに無い変数は意味がない。\n\t\t\t\t//単に無視しても良いが、恐らく入力のミスと思われるので警告を出す\n\t\t\t\tif (!found)\n\t\t\t\t{\n\t\t\t\t\tCGL_WarnLog(\"freeに指定された変数が無効です\");\n\t\t\t\t}\n\t\t\t}\n\t\t\tCGL_DebugLog(\"End Record MakeMap\");\n\t\t\tif (hasPlateausFunction/*,false*/)\n\t\t\t{\n\t\t\t\tstd::cout << \"Solve constraint by CMA-ES...\\n\";\n\n\t\t\t\tlibcmaes::FitFunc func = [&](const double *x, const int N)->double\n\t\t\t\t{\n\t\t\t\t\tfor (int i = 0; i < N; ++i)\n\t\t\t\t\t{\n\t\t\t\t\t\tupdate(variable2Data[i], x[i]);\n\t\t\t\t\t}\n\n\t\t\t\t\t{\n\t\t\t\t\t\tfor (const auto& keyval : invRefs)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tpEnv->TODO_Remove__ThisFunctionIsDangerousFunction__AssignToObject(keyval.first, data[keyval.second]);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tpEnv->switchFrontScope();\n\t\t\t\t\tpEnv->enterScope();\n\t\t\t\t\tdouble result = eval(pEnv, info);\n\t\t\t\t\tpEnv->exitScope();\n\t\t\t\t\tpEnv->switchBackScope();\n\n\t\t\t\t\tCGL_DebugLog(std::string(\"cost: \") + ToS(result, 17));\n\n\t\t\t\t\treturn result;\n\t\t\t\t};\n\n\t\t\t\tstd::vector<double> x0(freeVariableRefs.size());\n\t\t\t\tfor (int i = 0; i < x0.size(); ++i)\n\t\t\t\t{\n\t\t\t\t\tx0[i] = data[variable2Data[i]];\n\t\t\t\t\tCGL_DebugLog(ToS(i) + \" : \" + ToS(x0[i]));\n\t\t\t\t}\n\n\t\t\t\tconst double sigma = 0.1;\n\n\t\t\t\tconst int lambda = 100;\n\n\t\t\t\tlibcmaes::CMAParameters<> cmaparams(x0, sigma, lambda, 1);\n\n\t\t\t\tif (pEnv->hasTimeLimit())\n\t\t\t\t{\n\t\t\t\t\tcmaparams.set_max_calc_time(pEnv->timeLimit());\n\t\t\t\t\tcmaparams.set_current_time(GetSec());\n\t\t\t\t}\n\n\t\t\t\tlibcmaes::CMASolutions cmasols = libcmaes::cmaes<>(func, cmaparams);\n\t\t\t\tresultxs = cmasols.best_candidate().get_x();\n\n\t\t\t\tstd::cout << \"solved\\n\";\n\t\t\t}\n\t\t\telse if(true)\n\t\t\t{\n\t\t\t\tstd::cout << \"Solve constraint by BFGS...\\n\";\n\n\t\t\t\tConstraintProblem constraintProblem;\n\t\t\t\tconstraintProblem.evaluator = [&](const ConstraintProblem::TVector& v)->double\n\t\t\t\t{\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\tupdate(variable2Data[i], v[i]);\n\t\t\t\t\t}\n\n\t\t\t\t\tfor (const auto& keyval : invRefs)\n\t\t\t\t\t{\n\t\t\t\t\t\tpEnv->TODO_Remove__ThisFunctionIsDangerousFunction__AssignToObject(keyval.first, data[keyval.second]);\n\t\t\t\t\t}\n\n\t\t\t\t\tpEnv->switchFrontScope();\n\t\t\t\t\tpEnv->enterScope();\n\t\t\t\t\tdouble result = eval(pEnv, info);\n\t\t\t\t\tpEnv->exitScope();\n\t\t\t\t\tpEnv->switchBackScope();\n\n\t\t\t\t\t//CGL_DebugLog(std::string(\"cost: \") + ToS(result, 17));\n\t\t\t\t\t//std::cout << std::string(\"cost: \") << ToS(result, 17) << \"\\n\";\n\t\t\t\t\treturn result*result;\n\t\t\t\t};\n\t\t\t\tconstraintProblem.originalRecord = currentRecord;\n\t\t\t\tconstraintProblem.keyList = currentKeyList;\n\t\t\t\tconstraintProblem.pEnv = pEnv;\n\n\t\t\t\tEigen::VectorXd x0s(freeVariableRefs.size());\n\t\t\t\tfor (int i = 0; i < x0s.size(); ++i)\n\t\t\t\t{\n\t\t\t\t\tx0s[i] = data[variable2Data[i]];\n\t\t\t\t\t//x0s[i] = (problem.data[variable2Data[i]] / 2000.0) + 0.5;\n\t\t\t\t\tCGL_DebugLog(ToS(i) + \" : \" + ToS(x0s[i]));\n\t\t\t\t}\n\n\t\t\t\tconstraintProblem.beginTime = GetSec();\n\n\t\t\t\tcppoptlib::BfgsSolver<ConstraintProblem> solver;\n\t\t\t\tsolver.minimize(constraintProblem, x0s);\n\n\t\t\t\tresultxs.resize(x0s.size());\n\t\t\t\tfor (int i = 0; i < x0s.size(); ++i)\n\t\t\t\t{\n\t\t\t\t\tresultxs[i] = x0s[i];\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if(true)\n\t\t\t{\n\t\t\t\tstd::cout << \"Solve constraint by Random Search...\\n\";\n\n\t\t\t\tconst auto targetFunc = [&](const std::vector<double>& v)->double\n\t\t\t\t{\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\tupdate(variable2Data[i], v[i]);\n\t\t\t\t\t}\n\n\t\t\t\t\tfor (const auto& keyval : invRefs)\n\t\t\t\t\t{\n\t\t\t\t\t\tpEnv->TODO_Remove__ThisFunctionIsDangerousFunction__AssignToObject(keyval.first, data[keyval.second]);\n\t\t\t\t\t}\n\n\t\t\t\t\tdouble result;\n\n\t\t\t\t\tpEnv->switchFrontScope();\n\t\t\t\t\tpEnv->enterScope();\n\t\t\t\t\ttry\n\t\t\t\t\t{\n\t\t\t\t\t\tresult = eval(pEnv, info);\n\t\t\t\t\t}\n\t\t\t\t\tcatch (std::exception& e)\n\t\t\t\t\t{\n\t\t\t\t\t\tstd::cout << \"Eval: \" << e.what() << std::endl;\n\t\t\t\t\t\tthrow;\n\t\t\t\t\t}\n\t\t\t\t\tpEnv->exitScope();\n\t\t\t\t\tpEnv->switchBackScope();\n\n\t\t\t\t\tif (isDebugMode)\n\t\t\t\t\t{\n\t\t\t\t\t\tlogger << \"[\";\n\t\t\t\t\t\tfor (int i = 0; i < v.size(); ++i)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tlogger << v[i] << \", \";\n\t\t\t\t\t\t}\n\t\t\t\t\t\tlogger << result << \"], \";\n\t\t\t\t\t}\n\n\t\t\t\t\t//CGL_DebugLog(std::string(\"cost: \") + ToS(result, 17));\n\t\t\t\t\treturn result;\n\t\t\t\t};\n\n\t\t\t\tstd::vector<double> answer(freeVariableRefs.size());\n\t\t\t\tfor (int i = 0; i < answer.size(); ++i)\n\t\t\t\t{\n\t\t\t\t\tanswer[i] = data[variable2Data[i]];\n\t\t\t\t}\n\n\t\t\t\tdouble beginTime = GetSec();\n\n\t\t\t\t{\n\t\t\t\t\tdouble minimumCost = targetFunc(answer);\n\t\t\t\t\tstd::vector<double> current(answer.size());\n\t\t\t\t\tif (current.size() != rangeList.size())\n\t\t\t\t\t{\n\t\t\t\t\t\tCGL_Error(\"範囲と変数の数が対応していない\");\n\t\t\t\t\t}\n\n\t\t\t\t\tstd::vector<std::uniform_real_distribution<double>> dists;\n\t\t\t\t\tfor (size_t i = 0; i < rangeList.size(); ++i)\n\t\t\t\t\t{\n\t\t\t\t\t\tstd::cout << \"Range(\" << i << \"): [\" << rangeList[i].minimum << \", \" << rangeList[i].maximum << \"]\" << std::endl;\n\t\t\t\t\t\tdists.emplace_back(rangeList[i].minimum, rangeList[i].maximum);\n\t\t\t\t\t}\n\n\t\t\t\t\tint count = 0;\n\t\t\t\t\tstd::mt19937 rng;\n\t\t\t\t\t//while (GetSec() - beginTime < 300.0)\n\t\t\t\t\t//while (count < 20000)\n\t\t\t\t\t//while (count < 6900)\n\t\t\t\t\twhile(count < 20000)\n\t\t\t\t\t{\n\t\t\t\t\t\tcloneTime = 0.0;\n\t\t\t\t\t\tcloneCount = 0;\n\t\t\t\t\t\t/*if (6660 < count)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tprintAddressInsertion = true;\n\t\t\t\t\t\t\tstd::cout << \"----------------------------------\\n\";\n\t\t\t\t\t\t\tstd::cout << count << \": \";\n\t\t\t\t\t\t}*/\n\t\t\t\t\t\tfor (size_t i = 0; i < current.size(); ++i)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tcurrent[i] = dists[i](rng);\n\t\t\t\t\t\t\tif (printAddressInsertion)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tstd::cout << current[i] << \", \";\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tif (printAddressInsertion)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tstd::cout << \"\\n\";\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tconst double currentCost = targetFunc(current);\n\t\t\t\t\t\tif (currentCost < minimumCost)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tminimumCost = currentCost;\n\t\t\t\t\t\t\tanswer = current;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (printAddressInsertion)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tstd::cout << \"cloneTime: \" << cloneTime << \" | \" << cloneCount << \"\\n\";\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t++count;\n\n\t\t\t\t\t\tif (count % 1000 == 0)\n\t\t\t\t\t\t\t//if (count % 10 == 0)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tstd::cout <<\"it(\"<< count <<\") | \"<< \"cloneTime: \" << cloneTime << \", cloneCount: \" << cloneCount << \"\\n\";\n\t\t\t\t\t\t\tpEnv->garbageCollect(true);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tif (isDebugMode)\n\t\t\t\t\t{\n\t\t\t\t\t\tlogger << \"[\";\n\t\t\t\t\t\tfor (int i = 0; i < answer.size(); ++i)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tlogger << answer[i] << \", \";\n\t\t\t\t\t\t}\n\t\t\t\t\t\tlogger << minimumCost << \"]\\n\";\n\n\t\t\t\t\t\tlogger << \"\\t]\\n\";\n\t\t\t\t\t\tlogger << \"}\\n\";\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tresultxs.resize(answer.size());\n\t\t\t\tfor (int i = 0; i < answer.size(); ++i)\n\t\t\t\t{\n\t\t\t\t\tresultxs[i] = answer[i];\n\t\t\t\t}\n\t\t\t}\n\t\t\t/*else if (true)\n\t\t\t{\n\t\t\t\tstd::cout << \"Solve constraint by nlopt...\\n\";\n\n\t\t\t\tauto targetFunc = [&](unsigned N, const double *x, double *grad, void *my_func_data)\n\t\t\t\t{\n\t\t\t\t\tfor (int i = 0; i < N; ++i)\n\t\t\t\t\t{\n\t\t\t\t\t\tupdate(variable2Data[i], x[i]);\n\t\t\t\t\t}\n\n\t\t\t\t\t{\n\t\t\t\t\t\tfor (const auto& keyval : invRefs)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tpEnv->TODO_Remove__ThisFunctionIsDangerousFunction__AssignToObject(keyval.first, data[keyval.second]);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tpEnv->switchFrontScope();\n\t\t\t\t\tpEnv->enterScope();\n\t\t\t\t\tdouble result = eval(pEnv, info);\n\t\t\t\t\tpEnv->exitScope();\n\t\t\t\t\tpEnv->switchBackScope();\n\n\t\t\t\t\tCGL_DebugLog(std::string(\"cost: \") + ToS(result, 17));\n\n\t\t\t\t\treturn result;\n\t\t\t\t};\n\n\t\t\t\tstd::vector<double> lb, ub;\n\t\t\t\tfor (size_t i = 0; i < rangeList.size(); ++i)\n\t\t\t\t{\n\t\t\t\t\tlb.push_back(rangeList[i].minimum);\n\t\t\t\t\tub.push_back(rangeList[i].maximum);\n\t\t\t\t}\n\n\t\t\t\tnlopt_opt opt;\n\t\t\t\topt = nlopt_create(NLOPT_LD_MMA, freeVariableRefs.size());\n\t\t\t\tnlopt_set_lower_bounds(opt, lb.data());\n\t\t\t\tnlopt_set_upper_bounds(opt, ub.data());\n\t\t\t\tnlopt_set_min_objective(opt, targetFunc, NULL);\n\n\t\t\t\tstd::vector<double> xs(freeVariableRefs.size());\n\t\t\t\tfor (int i = 0; i < xs.size(); ++i)\n\t\t\t\t{\n\t\t\t\t\txs[i] = data[variable2Data[i]];\n\t\t\t\t}\n\t\t\t}*/\n#ifdef USE_OPTIONAL_LIB\n\t\t\telse\n\t\t\t{\n\t\t\t\tstd::cout << \"Solve constraint by Limbo...\\n\";\n\n\t\t\t\tconst auto targetFunc = [&](const Eigen::VectorXd& x)->double\n\t\t\t\t{\n\t\t\t\t\tfor (int i = 0; i < x.size(); ++i)\n\t\t\t\t\t{\n\t\t\t\t\t\t//std::cout << (x[i] * (rangeList[i].maximum - rangeList[i].minimum) + rangeList[i].minimum) << \", \";\n\t\t\t\t\t\tupdate(variable2Data[i], x[i] * (rangeList[i].maximum - rangeList[i].minimum) + rangeList[i].minimum);\n\t\t\t\t\t}\n\t\t\t\t\t//std::cout << \"\\n\";\n\n\t\t\t\t\tfor (const auto& keyval : invRefs)\n\t\t\t\t\t{\n\t\t\t\t\t\tpEnv->TODO_Remove__ThisFunctionIsDangerousFunction__AssignToObject(keyval.first, data[keyval.second]);\n\t\t\t\t\t}\n\n\t\t\t\t\tdouble result;\n\n\t\t\t\t\tpEnv->switchFrontScope();\n\t\t\t\t\tpEnv->enterScope();\n\t\t\t\t\ttry\n\t\t\t\t\t{\n\t\t\t\t\t\tresult = eval(pEnv, info);\n\t\t\t\t\t}\n\t\t\t\t\tcatch (std::exception& e)\n\t\t\t\t\t{\n\t\t\t\t\t\tstd::cout << \"Eval: \" << e.what() << std::endl;\n\t\t\t\t\t\tthrow;\n\t\t\t\t\t}\n\t\t\t\t\tpEnv->exitScope();\n\t\t\t\t\tpEnv->switchBackScope();\n\n\t\t\t\t\t//limbo maximizes target function\n\t\t\t\t\treturn -result;\n\t\t\t\t};\n\n\t\t\t\t//*\n\t\t\t\tusing Kernel_t = limbo::kernel::MaternFiveHalves<Params>;\n\t\t\t\tusing Mean_t = limbo::mean::Data<Params>;\n\n\t\t\t\tusing gp_opt_t = limbo::model::gp::KernelLFOpt<Params>;\n\t\t\t\tusing GP_t = limbo::model::GP<Params, Kernel_t, Mean_t, gp_opt_t>;\n\t\t\t\t//using GP_t = limbo::model::GP<Params, Kernel_t, Mean_t>;\n\t\t\t\t\n\t\t\t\t//using Acqui_t = limbo::acqui::UCB<Params, GP_t>;\n\t\t\t\tusing Acqui_t = limbo::acqui::EI<Params, GP_t>;\n\t\t\t\t\n\t\t\t\tusing stat_t = boost::fusion::vector<limbo::stat::ConsoleSummary<Params>,\n\t\t\t\t\tlimbo::stat::Samples<Params>,\n\t\t\t\t\tlimbo::stat::Observations<Params>,\n\t\t\t\t\tlimbo::stat::GP<Params>>;\n\n\t\t\t\tlimbo::bayes_opt::BOptimizer<Params, limbo::modelfun<GP_t>, limbo::statsfun<stat_t>, limbo::acquifun<Acqui_t>> opt;\n\t\t\t\t//*/\n\n\t\t\t\t// example with basic HP opt\n\t\t\t\t//limbo::bayes_opt::BOptimizerHPOpt<Params> opt;\n\n\t\t\t\tLimboFitFunc target;\n\n\t\t\t\ttarget.numOfVars = freeVariableRefs.size();\n\t\t\t\ttarget.func = targetFunc;\n\n\t\t\t\topt.optimize2(target);\n\n\t\t\t\t/*std::cout << opt.best_observation() << \" res  \"\n\t\t\t\t\t<< opt.best_sample().transpose() << std::endl;*/\n\n\t\t\t\t//const auto answer = opt.best_observation();\n\t\t\t\tconst auto answer = opt.best_sample();\n\t\t\t\tresultxs.resize(answer.size());\n\t\t\t\tfor (int i = 0; i < answer.size(); ++i)\n\t\t\t\t{\n\t\t\t\t\tstd::cout << \"answer[\" << i << \"]: \" << answer[i] << \"\\n\";\n\t\t\t\t\tresultxs[i] = answer[i] * (rangeList[i].maximum - rangeList[i].minimum) + rangeList[i].minimum;\n\t\t\t\t}\n\t\t\t}\n#endif\n\t\t}\n\n\t\treturn resultxs;\n\t}\n\n\tdouble OptimizationProblemSat::eval(std::shared_ptr<Context> pEnv, const LocationInfo& info)\n\t{\n\t\tif (!expr)\n\t\t{\n\t\t\treturn 0.0;\n\t\t}\n\n\t\tif (data.empty())\n\t\t{\n\t\t\tCGL_WarnLog(\"free式に有効な変数が指定されていません。\");\n\t\t\treturn 0.0;\n\t\t}\n\n\t\t/*{\n\t\t\tCGL_DebugLog(\"data:\");\n\t\t\tfor(int i=0;i<data.size();++i)\n\t\t\t{\n\t\t\t\tCGL_DebugLog(std::string(\"  ID(\") + ToS(i) + \") -> \" + ToS(data[i]));\n\t\t\t}\n\n\t\t\tCGL_DebugLog(\"refs:\");\n\t\t\tfor (int i = 0; i<refs.size(); ++i)\n\t\t\t{\n\t\t\t\tCGL_DebugLog(std::string(\"  ID(\") + ToS(i) + \") -> Address(\" + refs[i].toString() + \")\");\n\t\t\t}\n\n\t\t\tCGL_DebugLog(\"invRefs:\");\n\t\t\tfor(const auto& keyval : invRefs)\n\t\t\t{\n\t\t\t\tCGL_DebugLog(std::string(\"  Address(\") + keyval.first.toString() + \") -> ID(\" + ToS(keyval.second) + \")\");\n\t\t\t}\n\n\t\t\tCGL_DebugLog(\"env:\");\n\t\t\tpEnv->printContext();\n\n\t\t\tCGL_DebugLog(\"expr:\");\n\t\t\tprintExpr(expr.get());\n\t\t}*/\n\t\t\n\t\tEvalSatExpr evaluator(pEnv, data, refs, invRefs);\n\t\tconst Val evaluated = pEnv->expand(boost::apply_visitor(evaluator, expr.get()), info);\n\n\t\tif (IsType<double>(evaluated))\n\t\t{\n\t\t\treturn As<double>(evaluated);\n\t\t}\n\t\telse if (IsType<int>(evaluated))\n\t\t{\n\t\t\treturn As<int>(evaluated);\n\t\t}\n\t\t\n\t\tCGL_Error(\"sat式の評価結果が不正\");\n\t}\n\n\t//値同士が等しいかを知りたいのでAddressはハッシュには含めない\n\tclass ValueHasher : public boost::static_visitor<size_t>\n\t{\n\tpublic:\n\t\tValueHasher() = default;\n\n\t\tsize_t operator()(bool node)const { return std::hash<bool>()(node); }\n\t\tsize_t operator()(int node)const { return std::hash<int>()(node); }\n\t\tsize_t operator()(double node)const { return std::hash<double>()(node); }\n\t\tsize_t operator()(const CharString& node)const { return std::hash<std::u32string>()(node.toString()); }\n\t\tsize_t operator()(const PackedList& node)const\n\t\t{\n\t\t\tsize_t result = 0;\n\t\t\tfor (const auto& val : node.data)\n\t\t\t{\n\t\t\t\tboost::hash_combine(result, boost::apply_visitor(*this, val.value));\n\t\t\t}\n\t\t\treturn result;\n\t\t}\n\t\tsize_t operator()(const KeyValue& node)const\n\t\t{\n\t\t\treturn 0;\n\t\t}\n\t\tsize_t operator()(const PackedRecord& node)const\n\t\t{\n\t\t\tsize_t result = 0;\n\t\t\tfor (const auto& keyval : node.values)\n\t\t\t{\n\t\t\t\tboost::hash_combine(result, std::hash<std::string>()(keyval.first));\n\t\t\t\tboost::hash_combine(result, boost::apply_visitor(*this, keyval.second.value));\n\t\t\t}\n\t\t\treturn result;\n\t\t}\n\t\tsize_t operator()(const FuncVal& node)const\n\t\t{\n\t\t\treturn 0;\n\t\t}\n\t\tsize_t operator()(const Jump& node)const\n\t\t{\n\t\t\treturn 0;\n\t\t}\n\t};\n\n\tsize_t GetHash(const PackedVal& val)\n\t{\n\t\tValueHasher hasher;\n\t\treturn boost::apply_visitor(hasher, val);\n\t}\n\n\tsize_t GetHash(const Val& val, const Context& context)\n\t{\n\t\tconst PackedVal& packed = Packed(val, context);\n\t\treturn GetHash(packed);\n\t}\n\n\t//中身のアドレスを全て一つの値にまとめる\n\tclass ValuePacker : public boost::static_visitor<PackedVal>\n\t{\n\tpublic:\n\t\tValuePacker(const Context& context) :\n\t\t\tcontext(context)\n\t\t{}\n\n\t\tconst Context& context;\n\n\t\tPackedVal operator()(bool node)const { return node; }\n\t\tPackedVal operator()(int node)const { return node; }\n\t\tPackedVal operator()(double node)const { return node; }\n\t\tPackedVal operator()(const CharString& node)const { return node; }\n\t\tPackedVal operator()(const List& node)const { return node.packed(context); }\n\t\tPackedVal operator()(const KeyValue& node)const { return node; }\n\t\tPackedVal operator()(const Record& node)const { return node.packed(context); }\n\t\tPackedVal operator()(const FuncVal& node)const { return node; }\n\t\tPackedVal operator()(const Jump& node)const { return node; }\n\t};\n\n\t//中身のアドレスを全て展開する\n\tclass ValueUnpacker : public boost::static_visitor<Val>\n\t{\n\tpublic:\n\t\tValueUnpacker(Context& context) :\n\t\t\tcontext(context)\n\t\t{}\n\n\t\tContext& context;\n\n\t\tVal operator()(bool node)const { return node; }\n\t\tVal operator()(int node)const { return node; }\n\t\tVal operator()(double node)const { return node; }\n\t\tVal operator()(const CharString& node)const { return node; }\n\t\tVal operator()(const PackedList& node)const { return node.unpacked(context); }\n\t\tVal operator()(const KeyValue& node)const { return node; }\n\t\tVal operator()(const PackedRecord& node)const { return node.unpacked(context); }\n\t\tVal operator()(const FuncVal& node)const { return node; }\n\t\tVal operator()(const Jump& node)const { return node; }\n\t};\n\n\tPackedVal Packed(const Val& value, const Context& context)\n\t{\n\t\tValuePacker packer(context);\n\t\treturn boost::apply_visitor(packer, value);\n\t}\n\n\tVal Unpacked(const PackedVal& packedValue, Context& context)\n\t{\n\t\tValueUnpacker unpacker(context);\n\t\treturn boost::apply_visitor(unpacker, packedValue);\n\t}\n\n\tVal PackedList::unpacked(Context& context)const\n\t{\n\t\tValueUnpacker unpacker(context);\n\n\t\tList result;\n\n\t\tfor (const auto& val : data)\n\t\t{\n\t\t\tconst Address address = val.address;\n\n\t\t\tconst PackedVal& packedValue = val.value;\n\t\t\tconst Val value = boost::apply_visitor(unpacker, packedValue);\n\n\t\t\tif (address.isValid())\n\t\t\t{\n\t\t\t\tcontext.TODO_Remove__ThisFunctionIsDangerousFunction__AssignToObject(address, value);\n\t\t\t\tresult.add(address);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tresult.add(context.makeTemporaryValue(value));\n\t\t\t}\n\t\t}\n\n\t\treturn result;\n\t}\n\n\tPackedVal List::packed(const Context& context)const\n\t{\n\t\tValuePacker packer(context);\n\n\t\tPackedList result;\n\n\t\tfor (const Address address : data)\n\t\t{\n\t\t\tconst auto& opt = context.expandOpt(LRValue(address));\n\t\t\tif (!opt)\n\t\t\t{\n\t\t\t\tstd::stringstream ss;\n\t\t\t\tss << \"リスト中の \" << LRValue(address).toString() << \" 参照に失敗しました。\";\n\t\t\t\tCGL_Error(\"参照エラー: \");\n\t\t\t}\n\t\t\tconst PackedVal packedValue = boost::apply_visitor(packer, opt.get());\n\n\t\t\tresult.add(address, packedValue);\n\t\t}\n\n\t\treturn result;\n\t}\n\n\tVal PackedRecord::unpacked(Context& context)const\n\t{\n\t\tValueUnpacker unpacker(context);\n\n\t\tRecord result;\n\n\t\tfor (const auto& keyval : values)\n\t\t{\n\t\t\tconst Address address = keyval.second.address;\n\n\t\t\tconst PackedVal& packedValue = keyval.second.value;\n\t\t\tconst Val value = boost::apply_visitor(unpacker, packedValue);\n\n\t\t\tif (address.isValid())\n\t\t\t{\n\t\t\t\tcontext.TODO_Remove__ThisFunctionIsDangerousFunction__AssignToObject(address, value);\n\t\t\t\tresult.add(keyval.first, address);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tresult.add(keyval.first, context.makeTemporaryValue(value));\n\t\t\t}\n\t\t}\n\n\t\tresult.problems = problems;\n\t\tresult.boundedFreeVariables = freeVariables;\n\t\t//result.freeVariableRefs = freeVariableRefs;\n\t\tresult.type = type;\n\t\tresult.isSatisfied = isSatisfied;\n\t\tresult.pathPoints = pathPoints;\n\t\tresult.constraint = constraint;\n\n\t\t//result.unitConstraints = unitConstraints;\n\t\t//result.variableAppearances = variableAppearances;\n\t\t////result.constraintGroups = constraintGroups;\n\t\t//result.groupConstraints = groupConstraints;\n\t\tresult.original = original;\n\n\t\treturn result;\n\t}\n\n\tPackedVal Record::packed(const Context& context)const\n\t{\n\t\tValuePacker packer(context);\n\n\t\tPackedRecord result;\n\n\t\tfor (const auto& keyval : values)\n\t\t{\n\t\t\tconst auto& opt = context.expandOpt(LRValue(keyval.second));\n\t\t\tif (!opt)\n\t\t\t{\n\t\t\t\tstd::stringstream ss;\n\t\t\t\tss << \"レコード中のキー \\\"\" << keyval.first << \"\\\": \" << LRValue(keyval.second).toString() << \" の参照に失敗しました。\";\n\t\t\t\tCGL_Error(\"参照エラー: \" + ss.str());\n\t\t\t}\n\t\t\tconst PackedVal packedValue = boost::apply_visitor(packer, opt.get());\n\n\t\t\tresult.add(keyval.first, keyval.second, packedValue);\n\t\t}\n\n\t\tresult.problems = problems;\n\t\tresult.freeVariables = boundedFreeVariables;\n\t\tresult.type = type;\n\t\tresult.isSatisfied = isSatisfied;\n\t\tresult.pathPoints = pathPoints;\n\t\tresult.constraint = constraint;\n\n\t\t//result.unitConstraints = unitConstraints;\n\t\t//result.variableAppearances = variableAppearances;\n\t\t////result.constraintGroups = constraintGroups;\n\t\t//result.groupConstraints = groupConstraints;\n\t\tresult.original = original;\n\n\t\treturn result;\n\t}\n}\n", "meta": {"hexsha": "a8163925471c4cfeaeec94a712eed2b40c2ed693", "size": 44362, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "source/Node.cpp", "max_stars_repo_name": "agehama/Pita", "max_stars_repo_head_hexsha": "26f469d5236a9babe39991bea517135d311a8ca1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 18.0, "max_stars_repo_stars_event_min_datetime": "2018-03-29T23:42:43.000Z", "max_stars_repo_stars_event_max_datetime": "2020-03-06T04:16:52.000Z", "max_issues_repo_path": "source/Node.cpp", "max_issues_repo_name": "agehama/Pita", "max_issues_repo_head_hexsha": "26f469d5236a9babe39991bea517135d311a8ca1", "max_issues_repo_licenses": ["MIT"], "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/Node.cpp", "max_forks_repo_name": "agehama/Pita", "max_forks_repo_head_hexsha": "26f469d5236a9babe39991bea517135d311a8ca1", "max_forks_repo_licenses": ["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.3787185355, "max_line_length": 182, "alphanum_fraction": 0.6376854064, "num_tokens": 13160, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6619228625116081, "lm_q2_score": 0.4960938294709195, "lm_q1q2_score": 0.32837584767773664}}
{"text": "/*\n * Copyright (c) 2015-2016, Luca Fulchir<luca@fulchir.it>, All rights reserved.\n *\n * This file is part of \"libRaptorQ\".\n *\n * libRaptorQ is free software: you can redistribute it and/or modify\n * it under the terms of the GNU Lesser General Public License as\n * published by the Free Software Foundation, either version 3\n * of the License, or (at your option) any later version.\n *\n * libRaptorQ 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 * and a copy of the GNU Lesser General Public License\n * along with libRaptorQ.  If not, see <http://www.gnu.org/licenses/>.\n */\n\n#pragma once\n\n#include \"libRaptorQ/common.hpp\"\n#include \"libRaptorQ/Parameters.hpp\"\n#include \"libRaptorQ/Octet.hpp\"\n#include <Eigen/Dense>\n\nnamespace RaptorQ__v1 {\nnamespace Impl {\n\nusing DenseMtx = Eigen::Matrix<Octet, Eigen::Dynamic, Eigen::Dynamic,\n                                                            Eigen::RowMajor>;\n\n\nclass RAPTORQ_LOCAL Operation\n{\npublic:\n    enum class _t : uint8_t {\n        NONE = 0x00,\n        SWAP = 0x01,\n        ADD_MUL = 0x02,\n        DIV = 0x03,\n        BLOCK = 0x04,\n        REORDER = 0x05\n    };\n    Operation() = delete;\n    Operation (const Operation &rhs)\n        :_type (rhs._type)\n    {\n        switch (rhs._type)\n        {\n        case _t::SWAP:\n            swap = rhs.swap;\n            break;\n        case _t::ADD_MUL:\n            add_mul = rhs.add_mul;\n            break;\n        case _t::DIV:\n            div = rhs.div;\n            break;\n        case _t::BLOCK:\n            block = rhs.block;\n            break;\n        case _t::REORDER:\n            reorder = rhs.reorder;\n            break;\n        case _t::NONE:\n            break;\n        }\n    }\n    Operation& operator= (const Operation &rhs)\n    {\n        assert (_type == rhs._type && \"Operation types do not correspond.\");\n        switch (rhs._type)\n        {\n        case _t::SWAP:\n            swap = rhs.swap;\n            break;\n        case _t::ADD_MUL:\n            add_mul = rhs.add_mul;\n            break;\n        case _t::DIV:\n            div = rhs.div;\n            break;\n        case _t::BLOCK:\n            block = rhs.block;\n            break;\n        case _t::REORDER:\n            reorder = rhs.reorder;\n            break;\n        case _t::NONE:\n            break;\n        }\n        return *this;\n    }\n\n    Operation (Operation &&rhs)\n        :_type (rhs._type)\n    {\n        switch (rhs._type)\n        {\n        case _t::SWAP:\n            swap = std::move (rhs.swap);\n            break;\n        case _t::ADD_MUL:\n            add_mul = std::move (rhs.add_mul);\n            break;\n        case _t::DIV:\n            div = std::move (rhs.div);\n            break;\n        case _t::BLOCK:\n            block = std::move (rhs.block);\n            break;\n        case _t::REORDER:\n            reorder = std::move (rhs.reorder);\n            break;\n        case _t::NONE:\n            break;\n        }\n    }\n\n    Operation& operator= (Operation &&rhs)\n    {\n        assert (_type == rhs._type && \"Operation types do not correspond.\");\n        switch (rhs._type)\n        {\n        case _t::SWAP:\n            swap = std::move (rhs.swap);\n            break;\n        case _t::ADD_MUL:\n            add_mul = std::move (rhs.add_mul);\n            break;\n        case _t::DIV:\n            div = std::move (rhs.div);\n            break;\n        case _t::BLOCK:\n            block = std::move (rhs.block);\n            break;\n        case _t::REORDER:\n            reorder = std::move (rhs.reorder);\n            break;\n        case _t::NONE:\n            break;\n        }\n        return *this;\n    }\n\n    Operation (const _t type, const uint16_t row_1, const uint16_t row_2)\n        : _type (type), swap (row_1, row_2) { assert (type == _t::SWAP); }\n    Operation (const _t type, const uint16_t row_1, const uint16_t row_2,\n                                                            const Octet scalar)\n        : _type (type), add_mul (row_1, row_2, scalar)\n                                            { assert (type == _t::ADD_MUL); }\n    Operation (const _t type, const uint16_t row, const Octet scalar)\n        : _type (type), div (row, scalar) { assert (type == _t::DIV); }\n    Operation (const _t type, const DenseMtx &mtx)\n        : _type (type), block (mtx) { assert (type == _t::BLOCK); }\n    Operation (const _t type, const std::vector<uint16_t> &order)\n        : _type (type), reorder (order) { assert (type == _t::REORDER); }\n\n    ~Operation ()\n    {\n        if (_type == _t::BLOCK)\n            block.clear();\n        if (_type == _t::REORDER)\n            reorder.clear();\n    }\n\n    void build_mtx (DenseMtx &mtx) const\n    {\n        switch (_type)\n        {\n        case _t::SWAP:\n            return swap.build_mtx (mtx);\n        case _t::ADD_MUL:\n            return add_mul.build_mtx (mtx);\n        case _t::DIV:\n            return div.build_mtx (mtx);\n        case _t::BLOCK:\n            return block.build_mtx (mtx);\n        case _t::REORDER:\n            return reorder.build_mtx (mtx);\n        case _t::NONE:\n            break;\n        }\n    }\nprivate:\n    Operation (const _t type)\n        :_type (type) {}\n    class RAPTORQ_LOCAL Swap\n    {\n    public:\n        Swap (const uint16_t row_1, const uint16_t row_2)\n            : _row_1 (row_1), _row_2 (row_2) {}\n        Swap (const Swap&) = default;\n        Swap& operator= (const Swap&) = default;\n        Swap (Swap &&) = default;\n        Swap& operator= (Swap &&) = default;\n        ~Swap() {}\n        void build_mtx (DenseMtx &mtx) const\n            { mtx.row(_row_1).swap (mtx.row(_row_2)); }\n    private:\n        uint16_t _row_1, _row_2;\n    };\n\n    class RAPTORQ_LOCAL Add_Mul\n    {\n    public:\n        Add_Mul (const uint16_t row_1, const uint16_t row_2, const Octet scalar)\n            : _row_1 (row_1), _row_2 (row_2), _scalar (scalar) {}\n        Add_Mul (const Add_Mul&) = default;\n        Add_Mul& operator= (const Add_Mul&) = default;\n        Add_Mul (Add_Mul&&) = default;\n        Add_Mul& operator= (Add_Mul&&) = default;\n        ~Add_Mul() {}\n        void build_mtx (DenseMtx &mtx) const\n        {\n            const auto row = mtx.row (_row_2) * _scalar;\n            mtx.row (_row_1) += row;\n        }\n    private:\n        uint16_t _row_1, _row_2;\n        Octet _scalar;\n    };\n\n    class RAPTORQ_LOCAL Div\n    {\n    public:\n        Div (const uint16_t row_1, const Octet scalar)\n            : _row_1 (row_1), _scalar (scalar) {}\n        Div (const Div&) = default;\n        Div& operator= (const Div&) = default;\n        Div (Div&&) = default;\n        Div& operator= (Div&&) = default;\n        ~Div() {}\n        void build_mtx (DenseMtx &mtx) const\n            { mtx.row (_row_1) /= _scalar; }\n    private:\n        uint16_t _row_1;\n        Octet _scalar;\n    };\n\n    class RAPTORQ_LOCAL Block\n    {\n    public:\n        Block (const DenseMtx &block)\n            : _block (block) {}\n        Block (const Block&) = default;\n        Block& operator= (const Block&) = default;\n        Block (Block&&) = default;\n        Block& operator= (Block&&) = default;\n        ~Block() {}\n        void build_mtx (DenseMtx &mtx) const\n        {\n            const auto orig = mtx.block (0,0, _block.cols(), mtx.cols());\n            mtx.block (0, 0, _block.cols(), mtx.cols()) = _block * orig;\n        }\n        void clear()\n            { _block = DenseMtx(); }\n    private:\n        DenseMtx _block;\n    };\n\n    class RAPTORQ_LOCAL Reorder\n    {\n    public:\n        Reorder (const std::vector<uint16_t> &order)\n            : _order (order) {}\n        Reorder (const Reorder&) = default;\n        Reorder& operator= (const Reorder&) = default;\n        Reorder (Reorder&&) = default;\n        Reorder& operator= (Reorder&&) = default;\n        ~Reorder() {}\n        void build_mtx (DenseMtx &mtx) const\n        {\n            uint16_t overhead = static_cast<uint16_t> (\n                                static_cast<uint16_t> (mtx.rows()) - _order.size());\n            DenseMtx ret = DenseMtx (mtx.rows() - overhead , mtx.cols());\n\n            // reorder some of the lines as requested by the _order vector\n            uint16_t row = 0;\n            for (const uint16_t pos : _order)\n                ret.row (pos) = mtx.row (row++);\n            mtx.swap (ret);\n            // other lines will not influence the computation, ignore them\n        }\n        void clear()\n            { _order = std::vector<uint16_t>(); }\n    private:\n        std::vector<uint16_t> _order;\n    };\n\n    const _t _type;\n    union {\n        Swap swap;\n        Add_Mul add_mul;\n        Div div;\n        Block block;\n        Reorder reorder;\n    };\n};\n\n}   // namespace Impl\n}   // namespace RaptorQ\n", "meta": {"hexsha": "470b8b734576842b1f6adb7aed92ceb895e5b501", "size": 8858, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/libRaptorQ/Operation.hpp", "max_stars_repo_name": "thenakulchawla/dash_with_erasure", "max_stars_repo_head_hexsha": "ca1f320ddf5aaea6c5c27f4655c95273b80c37b0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/libRaptorQ/Operation.hpp", "max_issues_repo_name": "thenakulchawla/dash_with_erasure", "max_issues_repo_head_hexsha": "ca1f320ddf5aaea6c5c27f4655c95273b80c37b0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/libRaptorQ/Operation.hpp", "max_forks_repo_name": "thenakulchawla/dash_with_erasure", "max_forks_repo_head_hexsha": "ca1f320ddf5aaea6c5c27f4655c95273b80c37b0", "max_forks_repo_licenses": ["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.0426229508, "max_line_length": 84, "alphanum_fraction": 0.5193045834, "num_tokens": 2323, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.743168019989179, "lm_q2_score": 0.4416730056646256, "lm_q1q2_score": 0.3282372531024492}}
{"text": "// Copyright 2018 The Simons Foundation, Inc. - All Rights Reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//    http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\n#include \"ndm_spin_phase.hpp\"\n\n#include <Eigen/Dense>\n#include <iostream>\n#include <vector>\n#include \"Machine/rbm_spin.hpp\"\n#include \"Utils/all_utils.hpp\"\n#include \"Utils/log_cosh.hpp\"\n\nnamespace netket {\n\nusing RealVectorType = NdmSpinPhase::RealVectorType;\nusing VectorType = AbstractMachine::VectorType;\n\nvoid NdmSpinPhase::Init() {\n  W1_.resize(nv_, nh_);\n  U1_.resize(nv_, na_);\n  b1_.resize(nv_);\n  h1_.resize(nh_);\n  d1_.resize(na_);\n\n  W2_.resize(nv_, nh_);\n  U2_.resize(nv_, na_);\n  b2_.resize(nv_);\n  h2_.resize(nh_);\n\n  BatchSize(1);\n\n  npar_ = 2 * nv_ * (nh_ + na_);\n\n  if (useb_) {\n    npar_ += 2 * nv_;\n  } else {\n    b1_.setZero();\n    b2_.setZero();\n  }\n\n  if (useh_) {\n    npar_ += 2 * nh_;\n  } else {\n    h1_.setZero();\n    h2_.setZero();\n  }\n\n  if (used_) {\n    npar_ += na_;\n  } else {\n    d1_.setZero();\n  }\n\n  InfoMessage() << \"Phase NDM Initizialized with nvisible = \" << nv_\n                << \" and nhidden  = \" << nh_ << \" and nancilla = \" << na_\n                << std::endl;\n  InfoMessage() << \"Using visible   bias = \" << useb_ << std::endl;\n  InfoMessage() << \"Using hidden    bias  = \" << useh_ << std::endl;\n  InfoMessage() << \"Using ancillary bias  = \" << used_ << std::endl;\n}\n\nIndex NdmSpinPhase::BatchSize() const noexcept { return thetas_r1_.rows(); }\n\nvoid NdmSpinPhase::BatchSize(Index batch_size) {\n  if (batch_size <= 0) {\n    std::ostringstream msg;\n    msg << \"invalid batch size: \" << batch_size\n        << \"; expected a positive number\";\n    throw InvalidInputError{msg.str()};\n  }\n  if (batch_size != BatchSize()) {\n    thetas_r1_.resize(batch_size, nh_);\n    thetas_r2_.resize(batch_size, nh_);\n    thetas_c1_.resize(batch_size, nh_);\n    thetas_c2_.resize(batch_size, nh_);\n\n    lnthetas_r1_.resize(batch_size, nh_);\n    lnthetas_r2_.resize(batch_size, nh_);\n    lnthetas_c1_.resize(batch_size, nh_);\n    lnthetas_c2_.resize(batch_size, nh_);\n\n    thetasnew_r1_.resize(batch_size, nh_);\n    thetasnew_r2_.resize(batch_size, nh_);\n    thetasnew_c1_.resize(batch_size, nh_);\n    thetasnew_c2_.resize(batch_size, nh_);\n\n    lnthetasnew_r1_.resize(batch_size, nh_);\n    lnthetasnew_r2_.resize(batch_size, nh_);\n    lnthetasnew_c1_.resize(batch_size, nh_);\n    lnthetasnew_c2_.resize(batch_size, nh_);\n\n    thetas_a_.resize(batch_size, na_);\n    lnthetas_a_.resize(batch_size, na_);\n    thetas_a1_.resize(batch_size, na_);\n    thetas_a2_.resize(batch_size, na_);\n    thetasnew_a1_.resize(batch_size, na_);\n    thetasnew_a2_.resize(batch_size, na_);\n    pi_.resize(batch_size, na_);\n    lnpi_.resize(batch_size, na_);\n    lnpinew_.resize(batch_size, na_);\n\n    vsum_.resize(batch_size, nv_);\n    vdelta_.resize(batch_size, nv_);\n  }\n}\n\nVectorType NdmSpinPhase::DerLogSingle(VisibleConstType vr, VisibleConstType vc,\n                                      const any & /*cache*/) {\n  VectorType der(npar_);\n\n  const int impar = (npar_ + na_ * used_) / 2;\n\n  if (useb_) {\n    der.head(nv_) = 0.5 * (vr + vc);\n    der.segment(impar, nv_) = I_ * 0.5 * (vr - vc);\n  }\n  lnthetas_r1_ = (W1_.transpose() * vr + h1_).array().tanh();\n  lnthetas_r2_ = (W2_.transpose() * vr + h2_).array().tanh();\n  lnthetas_c1_ = (W1_.transpose() * vc + h1_).array().tanh();\n  lnthetas_c2_ = (W2_.transpose() * vc + h2_).array().tanh();\n\n  if (useh_) {\n    der.segment(useb_ * nv_, nh_) = 0.5 * (lnthetas_r1_ + lnthetas_c1_);\n    der.segment(impar + useb_ * nv_, nh_) =\n        I_ * 0.5 * (lnthetas_r2_ - lnthetas_c2_);\n  }\n\n  thetas_a1_ = 0.5 * U1_.transpose() * (vr + vc) + d1_;\n  thetas_a2_ = 0.5 * U2_.transpose() * (vr - vc);\n  lnpi_ = ((0.5 * U1_.transpose() * (vr + vc) + d1_).array() +\n           I_ * (0.5 * U2_.transpose() * (vr - vc)).array())\n              .tanh();\n\n  if (used_) {\n    der.segment(useb_ * nv_ + useh_ * nh_, na_) = lnpi_;\n  }\n\n  const int initw_1 = nv_ * useb_ + nh_ * useh_ + na_ * used_;\n  const int initw_2 = nv_ * useb_ + nh_ * useh_;\n\n  MatrixType wder =\n      0.5 * (vr * lnthetas_r1_.transpose() + vc * lnthetas_c1_.transpose());\n  der.segment(initw_1, nv_ * nh_) =\n      Eigen::Map<VectorType>(wder.data(), nv_ * nh_);\n\n  wder = 0.5 * I_ *\n         (vr * lnthetas_r2_.transpose() - vc * lnthetas_c2_.transpose());\n  der.segment(impar + initw_2, nv_ * nh_) =\n      Eigen::Map<VectorType>(wder.data(), nv_ * nh_);\n\n  const int initu_1 = initw_1 + nv_ * nh_;\n  const int initu_2 = initw_2 + nv_ * nh_;\n\n  MatrixType uder = 0.5 * (vr + vc) * lnpi_.transpose();\n  der.segment(initu_1, nv_ * na_) =\n      Eigen::Map<VectorType>(uder.data(), nv_ * na_);\n\n  uder = 0.5 * I_ * (vr - vc) * lnpi_.transpose();\n  der.segment(impar + initu_2, nv_ * na_) =\n      Eigen::Map<VectorType>(uder.data(), nv_ * na_);\n\n  return der;\n}\n\nVectorType NdmSpinPhase::GetParameters() {\n  VectorType pars(npar_);\n\n  const int impar = (npar_ + na_ * used_) / 2;\n\n  if (useb_) {\n    pars.head(nv_) = b1_;\n    pars.segment(impar, nv_) = b2_;\n  }\n\n  if (useh_) {\n    pars.segment(nv_ * useb_, nh_) = h1_;\n    pars.segment(impar + nv_ * useb_, nh_) = h2_;\n  }\n\n  if (used_) {\n    pars.segment(useb_ * nv_ + useh_ * nh_, na_) = d1_;\n  }\n\n  const int initw_1 = nv_ * useb_ + nh_ * useh_ + na_ * used_;\n  const int initw_2 = nv_ * useb_ + nh_ * useh_;\n\n  pars.segment(initw_1, nv_ * nh_) =\n      Eigen::Map<RealVectorType>(W1_.data(), nv_ * nh_);\n  pars.segment(impar + initw_2, nv_ * nh_) =\n      Eigen::Map<RealVectorType>(W2_.data(), nv_ * nh_);\n\n  const int initu_1 = initw_1 + nv_ * nh_;\n  const int initu_2 = initw_2 + nv_ * nh_;\n\n  pars.segment(initu_1, nv_ * na_) =\n      Eigen::Map<RealVectorType>(U1_.data(), nv_ * na_);\n  pars.segment(impar + initu_2, nv_ * na_) =\n      Eigen::Map<RealVectorType>(U2_.data(), nv_ * na_);\n\n  return pars;\n}\n\nvoid NdmSpinPhase::SetParameters(VectorConstRefType pars) {\n  const int impar = (npar_ + na_ * used_) / 2;\n\n  if (useb_) {\n    b1_ = pars.head(nv_).real();\n    b2_ = pars.segment(impar, nv_).real();\n  }\n\n  if (useh_) {\n    h1_ = pars.segment(useb_ * nv_, nh_).real();\n    h2_ = pars.segment(impar + useb_ * nv_, nh_).real();\n  }\n\n  if (used_) {\n    d1_ = pars.segment(useb_ * nv_ + useh_ * nh_, na_).real();\n  }\n\n  const int initw_1 = nv_ * useb_ + nh_ * useh_ + na_ * used_;\n  const int initw_2 = nv_ * useb_ + nh_ * useh_;\n\n  VectorType Wpars = pars.segment(initw_1, nv_ * nh_);\n  W1_ = Eigen::Map<MatrixType>(Wpars.data(), nv_, nh_).real();\n\n  Wpars = pars.segment(impar + initw_2, nv_ * nh_);\n  W2_ = Eigen::Map<MatrixType>(Wpars.data(), nv_, nh_).real();\n\n  const int initu_1 = initw_1 + nv_ * nh_;\n  const int initu_2 = initw_2 + nv_ * nh_;\n\n  VectorType Upars = pars.segment(initu_1, nv_ * na_);\n  U1_ = Eigen::Map<MatrixType>(Upars.data(), nv_, na_).real();\n\n  Upars = pars.segment(impar + initu_2, nv_ * na_);\n  U2_ = Eigen::Map<MatrixType>(Upars.data(), nv_, na_).real();\n}\n\n// Value of the logarithm of the wave-function\n// using pre-computed look-up tables for efficiency\nComplex NdmSpinPhase::LogValSingle(VisibleConstType vr, VisibleConstType vc,\n                                   const any& /*lookup*/) {\n  auto r1s = SumLogCosh(W1_.transpose() * vr + h1_);\n  auto r2s = SumLogCosh(W2_.transpose() * vr + h2_);\n  auto c1s = SumLogCosh(W1_.transpose() * vc + h1_);\n  auto c2s = SumLogCosh(W2_.transpose() * vc + h2_);\n\n  thetas_a1_ = 0.5 * U1_.transpose() * (vr + vc) + d1_;\n  thetas_a2_ = 0.5 * U2_.transpose() * (vr - vc);\n\n  auto lnpis = SumLogCosh(thetas_a1_ + I_ * thetas_a2_);\n\n  auto gamma_1 = 0.5 * (r1s + c1s + (vr + vc).dot(b1_));\n\n  auto gamma_2 = 0.5 * (r2s - c2s + (vr - vc).dot(b2_));\n\n  return (gamma_1 + I_ * gamma_2 + lnpis);\n}\n\nvoid NdmSpinPhase::LogVal(Eigen::Ref<const RowMatrix<double>> vr,\n                          Eigen::Ref<const RowMatrix<double>> vc,\n                          Eigen::Ref<VectorType> out, const any& /*lup*/) {\n  CheckShape(__FUNCTION__, \"vr\", {vr.rows(), vr.cols()},\n             {vc.rows(), NvisiblePhysical()});\n  CheckShape(__FUNCTION__, \"vc\", {vc.rows(), vc.cols()},\n             {vr.rows(), NvisiblePhysical()});\n  CheckShape(__FUNCTION__, \"out\", out.size(), vr.rows());\n\n  BatchSize(vr.rows());\n\n  vsum_ = vr + vc;\n  vdelta_ = vr - vc;\n\n  thetas_r1_ = (vr * W1_).rowwise() + h1_.transpose();\n  thetas_r2_ = (vr * W2_).rowwise() + h2_.transpose();\n  thetas_c1_ = (vc * W1_).rowwise() + h1_.transpose();\n  thetas_c2_ = (vc * W2_).rowwise() + h2_.transpose();\n  thetas_a_ =\n      (0.5 * (vsum_ * U1_ + I_ * vdelta_ * U2_)).rowwise() + d1_.transpose();\n\n  out.noalias() = (vsum_ * b1_ + I_ * vdelta_ * b2_);\n\n#pragma omp parallel for schedule(static)\n  for (auto j = Index{0}; j < BatchSize(); ++j) {\n    out(j) += SumLogCosh(thetas_r1_.row(j));\n  }\n#pragma omp parallel for schedule(static)\n  for (auto j = Index{0}; j < BatchSize(); ++j) {\n    out(j) += I_ * SumLogCosh(thetas_r2_.row(j));\n  }\n#pragma omp parallel for schedule(static)\n  for (auto j = Index{0}; j < BatchSize(); ++j) {\n    out(j) += SumLogCosh(thetas_c1_.row(j));\n  }\n#pragma omp parallel for schedule(static)\n  for (auto j = Index{0}; j < BatchSize(); ++j) {\n    out(j) -= I_ * SumLogCosh(thetas_c2_.row(j));\n  }\n\n  // All previous term are multiplied by 0.5\n  out = out * 0.5;\n\n#pragma omp parallel for schedule(static)\n  for (auto j = Index{0}; j < BatchSize(); ++j) {\n    out(j) += SumLogCosh(thetas_a_.row(j));\n  }\n}\n\nvoid NdmSpinPhase::DerLog(Eigen::Ref<const RowMatrix<double>> vr,\n                          Eigen::Ref<const RowMatrix<double>> vc,\n                          Eigen::Ref<RowMatrix<Complex>> out,\n                          const any& /*cache*/) {\n  CheckShape(__FUNCTION__, \"vr\", {vr.rows(), vr.cols()},\n             {vc.rows(), NvisiblePhysical()});\n  CheckShape(__FUNCTION__, \"vc\", {vc.rows(), vc.cols()},\n             {vr.rows(), NvisiblePhysical()});\n  CheckShape(__FUNCTION__, \"out\", {out.rows(), out.cols()},\n             {vr.rows(), Npar()});\n  BatchSize(vr.rows());\n\n  vsum_ = vr + vc;\n  vdelta_ = vr - vc;\n\n  const int impar = (npar_ + na_ * used_) / 2;\n\n  auto i = Index{0};\n  auto i2 = Index{impar};\n  if (useb_) {\n    out.block(0, i, BatchSize(), nv_) = 0.5 * vsum_;\n    out.block(0, impar, BatchSize(), nv_) = I_ * 0.5 * vdelta_;\n    i += nv_;\n    i2 += nv_;\n  }\n\n  thetas_r1_ = ((vr * W1_).rowwise() + h1_.transpose()).array().tanh();\n  thetas_r2_ = ((vr * W2_).rowwise() + h2_.transpose()).array().tanh();\n  thetas_c1_ = ((vc * W1_).rowwise() + h1_.transpose()).array().tanh();\n  thetas_c2_ = ((vc * W2_).rowwise() + h2_.transpose()).array().tanh();\n  thetas_a_ =\n      ((0.5 * (vsum_ * U1_ + I_ * vdelta_ * U2_)).rowwise() + d1_.transpose())\n          .array()\n          .tanh();\n  if (useh_) {\n    out.block(0, i, BatchSize(), nh_) = 0.5 * (thetas_r1_ + thetas_c1_);\n    out.block(0, i2, BatchSize(), nh_) = I_ * 0.5 * (thetas_r2_ - thetas_c2_);\n    i += nh_;\n    i2 += nh_;\n  }\n\n  if (used_) {\n    out.block(0, i, BatchSize(), na_) = thetas_a_;\n    i += na_;\n  }\n\n  // TODO: Rewrite all those using tensors\n\n#pragma omp parallel for schedule(static)\n  for (auto j = Index{0}; j < BatchSize(); ++j) {\n    Eigen::Map<Eigen::MatrixXcd>{&out(j, i), W1_.rows(), W1_.cols()}.noalias() =\n        0.5 * (vr.row(j).transpose() * thetas_r1_.row(j) +\n               vc.row(j).transpose() * thetas_c1_.row(j));\n  }\n\n#pragma omp parallel for schedule(static)\n  for (auto j = Index{0}; j < BatchSize(); ++j) {\n    Eigen::Map<Eigen::MatrixXcd>{&out(j, i2), W1_.rows(), W1_.cols()}\n        .noalias() = 0.5 * I_ *\n                     (vr.row(j).transpose() * thetas_r2_.row(j) -\n                      vc.row(j).transpose() * thetas_c2_.row(j));\n  }\n\n  i += nv_ * nh_;\n  i2 += nv_ * nh_;\n\n  // TODO: Rewrite all those using tensors\n\n#pragma omp parallel for schedule(static)\n  for (auto j = Index{0}; j < BatchSize(); ++j) {\n    Eigen::Map<Eigen::MatrixXcd>{&out(j, i), U1_.rows(), U1_.cols()}.noalias() =\n        0.5 * vsum_.row(j).transpose() * thetas_a_.row(j);\n  }\n\n#pragma omp parallel for schedule(static)\n  for (auto j = Index{0}; j < BatchSize(); ++j) {\n    Eigen::Map<Eigen::MatrixXcd>{&out(j, i2), U2_.rows(), U2_.cols()}\n        .noalias() = 0.5 * I_ * vdelta_.row(j).transpose() * thetas_a_.row(j);\n  }\n}\n\nvoid NdmSpinPhase::Save(const std::string &filename) const {\n  json state;\n  state[\"Name\"] = \"NdmSpinPhase\";\n  state[\"Nvisible\"] = nv_;\n  state[\"Nhidden\"] = nh_;\n  state[\"Nancilla\"] = na_;\n  state[\"UseVisibleBias\"] = useb_;\n  state[\"UseHiddenBias\"] = useh_;\n  state[\"UseAncillaBias\"] = used_;\n  state[\"b1\"] = b1_;\n  state[\"h1\"] = h1_;\n  state[\"d1\"] = d1_;\n  state[\"W1\"] = W1_;\n  state[\"U1\"] = U1_;\n\n  state[\"b2\"] = b2_;\n  state[\"h2\"] = h2_;\n  state[\"W2\"] = W2_;\n  state[\"U2\"] = U2_;\n  WriteJsonToFile(state, filename);\n}\n\nvoid NdmSpinPhase::Load(const std::string &filename) {\n  auto pars = ReadJsonFromFile(filename);\n  std::string name = FieldVal<std::string>(pars, \"Name\");\n  if (name != \"NdmSpinPhase\") {\n    throw InvalidInputError(\n        \"Error while constructing RbmSpinPhase from input parameters\");\n  }\n\n  if (FieldExists(pars, \"Nvisible\")) {\n    nv_ = FieldVal<int>(pars, \"Nvisible\");\n  }\n  if (nv_ != GetHilbertPhysical().Size()) {\n    throw InvalidInputError(\n        \"Number of visible units is incompatible with given \"\n        \"Hilbert space\");\n  }\n\n  if (FieldExists(pars, \"Nhidden\")) {\n    nh_ = FieldVal<int>(pars, \"Nhidden\");\n  } else {\n    nh_ = nv_ * double(FieldVal<double>(pars, \"Alpha\"));\n  }\n\n  if (FieldExists(pars, \"Nancilla\")) {\n    na_ = FieldVal<int>(pars, \"Nancilla\");\n  } else {\n    na_ = nv_ * double(FieldVal<double>(pars, \"Beta\"));\n  }\n\n  useb_ = FieldOrDefaultVal(pars, \"UseVisibleBias\", true);\n  useh_ = FieldOrDefaultVal(pars, \"UseHiddenBias\", true);\n  used_ = FieldOrDefaultVal(pars, \"UseAncillaBias\", true);\n\n  Init();\n\n  // Loading parameters, if defined in the input\n  if (FieldExists(pars, \"b1\")) {\n    b1_ = FieldVal<RealVectorType>(pars, \"b1\");\n    b2_ = FieldVal<RealVectorType>(pars, \"b2\");\n  } else {\n    b1_.setZero();\n    b2_.setZero();\n  }\n\n  if (FieldExists(pars, \"h1\")) {\n    h1_ = FieldVal<RealVectorType>(pars, \"h1\");\n    h2_ = FieldVal<RealVectorType>(pars, \"h2\");\n  } else {\n    h1_.setZero();\n    h2_.setZero();\n  }\n\n  if (FieldExists(pars, \"d1\")) {\n    d1_ = FieldVal<RealVectorType>(pars, \"d1\");\n  } else {\n    d1_.setZero();\n  }\n\n  if (FieldExists(pars, \"W1\")) {\n    W1_ = FieldVal<RealMatrixType>(pars, \"W1\");\n    W2_ = FieldVal<RealMatrixType>(pars, \"W2\");\n  }\n\n  if (FieldExists(pars, \"U1\")) {\n    U1_ = FieldVal<RealMatrixType>(pars, \"U1\");\n    U2_ = FieldVal<RealMatrixType>(pars, \"U2\");\n  }\n}\n\nbool NdmSpinPhase::IsHolomorphic() const noexcept { return false; }\n};  // namespace netket\n", "meta": {"hexsha": "900596bbb4ffbd001b5817211915c375dfd24d6e", "size": 15118, "ext": "cc", "lang": "C++", "max_stars_repo_path": "Sources/Machine/DensityMatrices/ndm_spin_phase.cc", "max_stars_repo_name": "vigsterkr/netket", "max_stars_repo_head_hexsha": "1e187ae2b9d2aa3f2e53b09fe743e50763d04c9a", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Sources/Machine/DensityMatrices/ndm_spin_phase.cc", "max_issues_repo_name": "vigsterkr/netket", "max_issues_repo_head_hexsha": "1e187ae2b9d2aa3f2e53b09fe743e50763d04c9a", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Sources/Machine/DensityMatrices/ndm_spin_phase.cc", "max_forks_repo_name": "vigsterkr/netket", "max_forks_repo_head_hexsha": "1e187ae2b9d2aa3f2e53b09fe743e50763d04c9a", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.6032388664, "max_line_length": 80, "alphanum_fraction": 0.6072231777, "num_tokens": 5066, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7431680086124811, "lm_q2_score": 0.4416730056646256, "lm_q1q2_score": 0.3282372480776689}}
{"text": "/*\n * Copyright (c) 2016 Abhishek Agrawal (abhishek.agrawal@protonmail.com)\n * Distributed under the MIT License.\n * See accompanying file LICENSE.md or copy at http://opensource.org/licenses/MIT\n */\n\n#ifndef PARTICLE_AROUND_UNIFORMLY_ROTATING_ELLIPSOID\n#define PARTICLE_AROUND_UNIFORMLY_ROTATING_ELLIPSOID\n\n#include <cstdlib>\n#include <iostream>\n#include <sstream>\n#include <fstream>\n#include <string>\n#include <cmath>\n#include <limits>\n#include <vector>\n\n#include <boost/numeric/odeint.hpp>\n\n#include \"NAOS/constants.hpp\"\n#include \"NAOS/basicMath.hpp\"\n#include \"NAOS/basicAstro.hpp\"\n#include \"NAOS/misc.hpp\"\n#include \"NAOS/ellipsoidGravitationalAcceleration.hpp\"\n\nnamespace naos\n{\n\n//! particle around ellipsoid integration\n/*!\n * integrate the equations of motion for a particle around an ellipsoid. The gravitational accelerations\n * calculated using the ellipsoid gravitational potential model.\n */\nvoid executeParticleAroundEllipsoid( const double alpha,\n                                     const double beta,\n                                     const double gamma,\n                                     const double gravParameter,\n                                     std::vector< double > asteroidRotationVector,\n                                     std::vector< double > &initialOrbitalElements,\n                                     const double initialStepSize,\n                                     const double startTime,\n                                     const double endTime,\n                                     std::ostringstream &outputFilePath,\n                                     const int dataSaveIntervals );\n\n//! Trajectory calculation for regolith around an asteroid (modelled as ellipsoid here)\n/*!\n * Same as the previous function, except that the initial conditions are now given as a cartesian\n * state. The initial cartesian state should be given in body fixed frame of the asteroid.\n */\nvoid singleRegolithTrajectoryCalculator( const double alpha,\n                                         const double beta,\n                                         const double gamma,\n                                         const double gravParameter,\n                                         std::vector< double > asteroidRotationVector,\n                                         std::vector< double > &initialCartesianStateVector,\n                                         const double initialStepSize,\n                                         const double startTime,\n                                         const double endTime,\n                                         std::ostringstream &outputFilePath,\n                                         const int dataSaveIntervals );\n\n} // namespace naos\n\n#endif // PARTICLE_AROUND_UNIFORMLY_ROTATING_ELLIPSOID\n", "meta": {"hexsha": "b062ff7f90fed65cbe90c25e7846b057f23008d1", "size": 2776, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/NAOS/particleAroundUniformlyRotatingEllipsoid.hpp", "max_stars_repo_name": "agrawalabhishek/NAOS", "max_stars_repo_head_hexsha": "25ae383d2c3f9a52ecd2e06f34661e52e239478b", "max_stars_repo_licenses": ["MIT"], "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/NAOS/particleAroundUniformlyRotatingEllipsoid.hpp", "max_issues_repo_name": "agrawalabhishek/NAOS", "max_issues_repo_head_hexsha": "25ae383d2c3f9a52ecd2e06f34661e52e239478b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/NAOS/particleAroundUniformlyRotatingEllipsoid.hpp", "max_forks_repo_name": "agrawalabhishek/NAOS", "max_forks_repo_head_hexsha": "25ae383d2c3f9a52ecd2e06f34661e52e239478b", "max_forks_repo_licenses": ["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.4328358209, "max_line_length": 104, "alphanum_fraction": 0.5752881844, "num_tokens": 470, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6224593452091672, "lm_q2_score": 0.5273165233795671, "lm_q1q2_score": 0.3282330978608199}}
{"text": "#include <iostream>\n#include <fstream>\n#include <sstream>\n#include <iomanip>\n#include <string>\n#include <algorithm>\n#include <iterator>\n#include <numeric>\n#include <ext/numeric>\n#include <boost/program_options.hpp>\n#include <boost/filesystem.hpp>\n\n#include <stdlib.h>\n#include <math.h>\n#include <assert.h>\n\n#include \"mpi_kmeans.h\"\n\nnamespace po = boost::program_options;\n\nstatic unsigned int count_lines(const std::string& filename) {\n\tstd::ifstream in(filename.c_str());\n\tif (in.fail()) {\n\t\tstd::cerr << \"count_lines, failed to open \\\"\" << filename\n\t\t\t<< \"\\\".\" << std::endl;\n\t\texit(EXIT_FAILURE);\n\t}\n\tunsigned int lines = 0;\n\tstd::string line;\n\twhile (in.eof() == false) {\n\t\tstd::getline(in, line);\n\t\tif (line.size() == 0)\n\t\t\tcontinue;\n\t\tlines += 1;\n\t}\n\tin.close();\n\treturn (lines);\n}\n\n\nstatic void write_cluster_centers(const std::string& output_filename,\n\t\t\t\t\t\t\t\t  const std::vector<std::vector<double> >& data_CX) {\n\t\n\tstd::cout << \"Writing cluster centers to \\\"\"\n\t\t\t  << output_filename << \"\\\"\" << std::endl;\n\n\tstd::ofstream wout(output_filename.c_str());\n\tif (wout.fail()) {\n\t\tstd::cerr << \"Failed to open \\\"\" << output_filename\n\t\t\t\t  << \"\\\" for writing.\" << std::endl;\n\t\texit(EXIT_FAILURE);\n\t}\n\n\twout << std::setprecision(12);\n\tfor (unsigned int m=0; m < data_CX.size(); ++m) {\n\t\tfor (unsigned int n=0; n < data_CX[m].size(); ++n) {\n\t\t\twout << (n==0? \"\":\" \") << data_CX[m][n];\n\t\t}\n\t\twout << std::endl;\n\t}\n\twout.close();\n\n\treturn;\n}\n\nstatic void write_cluster_centers(const std::string& output_filename,\n\t\t\t\t\t\t\t\t  double *data_CX, \n\t\t\t\t\t\t\t\t  unsigned int nof_clusters,\n\t\t\t\t\t\t\t\t  unsigned int dims) {\n\t\n\tstd::cout << \"Writing cluster centers to \\\"\"\n\t\t\t  << output_filename << \"\\\"\" << std::endl;\n\n\tstd::ofstream wout(output_filename.c_str());\n\tif (wout.fail()) {\n\t\tstd::cerr << \"Failed to open \\\"\" << output_filename\n\t\t\t\t  << \"\\\" for writing.\" << std::endl;\n\t\texit(EXIT_FAILURE);\n\t}\n\n\twout << std::setprecision(12);\n\tunsigned int cntr = 0;\n\tfor (unsigned int m=0; m < nof_clusters; ++m) {\n\t\tfor (unsigned int n=0; n < dims; ++n) {\n\t\t\twout << (n==0? \"\":\" \") << data_CX[cntr];\n\t\t\tcntr += 1;\n\t\t}\n\t\twout << std::endl;\n\t}\n\twout.close();\n\n\treturn;\n}\n\n\nstatic int read_problem_data(const std::string& train_filename,\n\t\t\t\t\t\t\t  std::vector<std::vector<double> >& data_X) {\n\tdata_X.clear();\n\n\tstd::ifstream in(train_filename.c_str());\n\tif (in.fail()) {\n\t\tstd::cerr << \"Failed to open file \\\"\"\n\t\t\t\t  << train_filename << \"\\\" for reading.\" << std::endl;\n\t\tstd::cerr << \"Try mpi_assign --help\" << std::endl;\n\t\texit(EXIT_FAILURE);\n\t}\n\n\tstd::string line;\n\tunsigned int ndims = 0;\n\twhile (in.eof() == false) {\n\t\tstd::getline(in,line);\n\t\tif (line.size() == 0)\n\t\t\tcontinue; // skip over empty lines\n\t\n\t\t// remove trailing whitespaces \n\t\tline.erase(line.find_last_not_of(\" \")+1);\n\n\t\tstd::vector<double> current_data;\t\n\t\tstd::istringstream is(line);\n\t\twhile (is.eof() == false) {\n\t\t\tdouble value;\n\t\t\tis >> value;\n\t\t\tcurrent_data.push_back(value);\n\t\t}\n\t\t\n\t\t// Ensure the same number of dimensions for each point\n\t\tif (ndims == 0)\n\t\t\tndims = current_data.size();\t\n\t\tassert(ndims == current_data.size());\n\t\tdata_X.push_back(current_data);\n\t}\n\tin.close();\n\t\n\tif (data_X.size() == 0) {\n\t\tstd::cerr << \"No points read from file \\\"\" << train_filename\n\t\t\t\t  << \"\\\"\" << std::endl;\n\t\tstd::cerr << \"Try mpi_assign --help\" << std::endl;\n\t\texit(EXIT_FAILURE);\n\t}\n\n\treturn(data_X.size());\n\n}\n\nstatic int read_problem_data(const std::string& train_filename,\n\t\t\t\t\t\t\t  double *data_X) {\n\n\tstd::ifstream in(train_filename.c_str());\n\tif (in.fail()) {\n\t\tstd::cerr << \"Failed to open file \\\"\"\n\t\t\t\t  << train_filename << \"\\\" for reading.\" << std::endl;\n\t\tstd::cerr << \"Try mpi_assign --help\" << std::endl;\n\t\texit(EXIT_FAILURE);\n\t}\n\n\tunsigned int nof_points = count_lines(train_filename);\n\tif (nof_points == 0) {\n\t\tstd::cerr << \"No points read from file \\\"\" << train_filename\n\t\t\t\t  << \"\\\"\" << std::endl;\n\t\tstd::cerr << \"Try mpi_assign --help\" << std::endl;\n\t\texit(EXIT_FAILURE);\n\t}\n\n\tstd::string line;\n\tunsigned int ndims = 0;\n\tunsigned int cntr = 0;\n\twhile (in.eof() == false) {\n\t\tstd::getline(in,line);\n\t\tif (line.size() == 0)\n\t\t\tcontinue; // skip over empty lines\n\t\n\t\t// remove trailing whitespaces \n\t\tline.erase(line.find_last_not_of(\" \")+1);\n\n\t\tstd::vector<double> current_data;\t\n\t\tstd::istringstream is(line);\n\t\twhile (is.eof() == false) {\n\t\t\tdouble value;\n\t\t\tis >> value;\n\t\t\tcurrent_data.push_back(value);\n\t\t}\n\t\t\n\t\t// Ensure the same number of dimensions for each point\n\t\tif (ndims == 0)\n\t\t\tndims = current_data.size();\t\n\t\tassert(ndims == current_data.size());\n\t\tif (data_X==NULL)\n\t\t\tdata_X = (double *)malloc(nof_points * ndims * sizeof(double));\n\t\t\n\t\tfor (unsigned int i=0; i<ndims; ++i) {\n\t\t\tdata_X[cntr] = current_data[i];\n\t\t\tcntr += 1;\n\t\t}\n\t}\n\tin.close();\n\t\n\treturn(nof_points);\n\n}\n\n\n\nint main(int argc, char* argv[]) {\n\n\tstd::string train_filename;\n\tstd::string weight_filename;\n\tstd::string output_filename;\n\tint nof_clusters;\n\tint nof_restarts;\n\tint maxiter;\n\n\t// Set Program options\n\tpo::options_description generic(\"Generic Options\");\n\tgeneric.add_options()\n\t\t(\"help\",\"Produce help message\")\n\t\t(\"verbose\",\"Verbose output\")\n\t\t;\n\n\tpo::options_description input_options(\"Input/Output Options\");\n\tinput_options.add_options()\n\t\t(\"data\",po::value<std::string>\n\t\t (&train_filename)->default_value(\"data.txt\"),\n\t\t \"Training file, one datum per line\")\n\t\t(\"output\",po::value<std::string>\n\t\t (&output_filename)->default_value(\"output.txt\"),\n\t\t \"Output file, one cluster center per line\")\n\t\t(\"weights\",po::value<std::string>\n\t\t (&weight_filename)->default_value(\"\"),\n\t\t \"Weighting of exmaples, one number per line\")\n\t\t;\n\n\tpo::options_description kmeans_options(\"K-Means Options\");\n\tkmeans_options.add_options()\n\t\t(\"k\",po::value<int>(&nof_clusters)->default_value(100),\n\t\t \"Number of clusters to generate\")\n\t\t(\"restarts\",po::value<int>(&nof_restarts)->default_value(0),\n\t\t \"Number of K-Means restarts. (0: single run)\")\n\t\t(\"maxiter\",po::value<int>(&maxiter)->default_value(0),\n\t\t \"Maximum number of K-Means iterations. (0: infinity)\")\n\t\t;\n\n\tpo::options_description all_options;\n\tall_options.add(generic).add(input_options).add(kmeans_options);\n\tpo::variables_map vm;\n\tpo::store(po::command_line_parser(argc,argv).options(all_options).run(), vm);\n\tpo::notify(vm);\n\n\tbool verbose = vm.count(\"verbose\");\n\n\tif (vm.count(\"help\")) {\n\t\tstd::cerr << \"K-Means clustering\" << std::endl;\n\t\tstd::cerr << all_options << std::endl;\n\t\tstd::cerr << std::endl;\n\t\tstd::cerr << \"Example:\" << std::endl;\n\t\tstd::cerr << \"  mpi_kmeans --k 2 --data example.txt --output clusters.txt\" << std::endl;\n\t\texit(EXIT_SUCCESS);\n\t}\n\n\t// read in the problem\n\tstd::cout << \"Training file: \" << train_filename << std::endl;\n\tstd::vector<std::vector<double> > data_X; // so far kmeans does not support std::<vector>\n\tint nof_points = read_problem_data(train_filename,data_X);\n\tassert(nof_points>0);\n\n\tunsigned int dims = data_X[0].size();\n\tassert(dims>0);\n\n\t// convert points to double*\n\tdouble *X = (double *)malloc(nof_points * dims * sizeof(double));\n\tunsigned int cntr = 0;\n\tfor (unsigned int m=0; m < data_X.size() ; ++m) {\n\t\tfor (unsigned int n=0; n < data_X[m].size() ; ++n) {\n\t\t\tX[cntr] = data_X[m][n];\n\t\t\tcntr += 1;\n\t\t}\n\t\tdata_X[m].clear();\n\t}\n\tdata_X.clear();\n\n\n\n\t// read in weighting\n\tdouble *W = NULL;\n\tif (weight_filename != \"\") {\n\t\tstd::cout << \"Weighting file: \" << weight_filename << std::endl;\n\t\tstd::vector<std::vector<double> > data_W; // so far kmeans does not support std::<vector>\n\t\tint nof_points_wfile = read_problem_data(weight_filename,data_W);\n\t\tassert(nof_points_wfile == nof_points);\n\n\t\tunsigned int dims_wfile = data_W[0].size();\n\t\tassert(dims_wfile==1);\n\n\t\t// convert points to double*\n\t\tW = (double *)malloc(nof_points * sizeof(double));\n\t\tfor (unsigned int m=0; m < data_W.size() ; ++m)\n\t\t\tW[m] = data_W[m][0];\n\t\tdata_W.clear();\n\n\t}\n\n\t// start K-Means\n\tstd::cout << \"Starting Kmeans ...\" << std::endl;\n\tstd::cout << \" ... with \" << nof_points << \" training points \" <<std::endl;\n\tstd::cout << \" ... for \" << nof_clusters << \" clusters \" <<std::endl;\n\n\tunsigned int *assignment = (unsigned int *)malloc(nof_points * sizeof(unsigned int));\n\tdouble *CX = (double *) calloc(nof_clusters * dims, sizeof(double));\n\tdouble sse = kmeans(CX, X, W, assignment, dims, nof_points, nof_clusters, maxiter, nof_restarts);\n\tfree(X); \n\tassert(CX);\n\n\tstd::cout << \"Done!\" << std::endl;\n\tstd::cout << \"Sum of Squared Error : \" << sse << std::endl;\n\n\t// write the clusters\n\t// write_cluster_centers(output_filename,data_X);\n\twrite_cluster_centers(output_filename,CX,nof_clusters,dims);\n\n\t// done\n\texit(EXIT_SUCCESS);\n}\n", "meta": {"hexsha": "0dc9403dd18a3dc5c3d7f668f2d17347ab0cb57f", "size": 8561, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "server/intrinsic/algorithm/gehler2011/lib/mpi_kmeans-1.6/mpi_kmeans_main.cxx", "max_stars_repo_name": "paulu/opensurfaces", "max_stars_repo_head_hexsha": "7f3e987560faa62cd37f821760683ccd1e053c7c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 137.0, "max_stars_repo_stars_event_min_datetime": "2015-02-19T00:00:42.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T03:56:01.000Z", "max_issues_repo_path": "server/intrinsic/algorithm/gehler2011/lib/mpi_kmeans-1.6/mpi_kmeans_main.cxx", "max_issues_repo_name": "paulu/opensurfaces", "max_issues_repo_head_hexsha": "7f3e987560faa62cd37f821760683ccd1e053c7c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 20.0, "max_issues_repo_issues_event_min_datetime": "2015-07-28T23:39:58.000Z", "max_issues_repo_issues_event_max_datetime": "2020-05-19T11:40:55.000Z", "max_forks_repo_path": "server/intrinsic/algorithm/gehler2011/lib/mpi_kmeans-1.6/mpi_kmeans_main.cxx", "max_forks_repo_name": "paulu/opensurfaces", "max_forks_repo_head_hexsha": "7f3e987560faa62cd37f821760683ccd1e053c7c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 49.0, "max_forks_repo_forks_event_min_datetime": "2015-02-09T15:21:46.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-15T14:22:33.000Z", "avg_line_length": 26.5869565217, "max_line_length": 98, "alphanum_fraction": 0.6412802243, "num_tokens": 2398, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.3282330904745325}}
{"text": "// ---------------------------------------------------------------------\n//\n// Copyright (c) 2018 - 2019 by the IBAMR developers\n// All rights reserved.\n//\n// This file is part of IBAMR.\n//\n// IBAMR is free software and is distributed under the 3-clause BSD\n// license. The full text of the license can be found in the file\n// COPYRIGHT at the top level directory of IBAMR.\n//\n// ---------------------------------------------------------------------\n\n// Config files\n#include <SAMRAI_config.h>\n\n// Headers for basic PETSc functions\n#include <petscsys.h>\n\n// Headers for basic SAMRAI objects\n#include <BergerRigoutsos.h>\n#include <CartesianGridGeometry.h>\n#include <LoadBalancer.h>\n#include <StandardTagAndInitialize.h>\n\n// Headers for basic libMesh objects\n#include <libmesh/equation_systems.h>\n#include <libmesh/exodusII_io.h>\n#include <libmesh/mesh.h>\n#include <libmesh/mesh_generation.h>\n#include <libmesh/mesh_triangle_interface.h>\n\n// Headers for application-specific algorithm/data structure objects\n#include <ibamr/IBExplicitHierarchyIntegrator.h>\n#include <ibamr/IBFEDirectForcingKinematics.h>\n#include <ibamr/IBFEMethod.h>\n#include <ibamr/INSStaggeredHierarchyIntegrator.h>\n\n#include <ibtk/AppInitializer.h>\n#include <ibtk/IBTKInit.h>\n#include <ibtk/IBTK_MPI.h>\n#include <ibtk/LEInteractor.h>\n#include <ibtk/ibtk_utilities.h>\n#include <ibtk/libmesh_utilities.h>\n#include <ibtk/muParserCartGridFunction.h>\n#include <ibtk/muParserRobinBcCoefs.h>\n\n#include <boost/multi_array.hpp>\n\n// Set up application namespace declarations\n#include <ibamr/app_namespaces.h>\n\ninline double\nkernel(double x)\n{\n    x += 4.;\n    const double x2 = x * x;\n    const double x3 = x * x2;\n    const double x4 = x * x3;\n    const double x5 = x * x4;\n    const double x6 = x * x5;\n    const double x7 = x * x6;\n    if (x <= 0.)\n        return 0.;\n    else if (x <= 1.)\n        return .1984126984126984e-3 * x7;\n    else if (x <= 2.)\n        return .1111111111111111e-1 * x6 - .1388888888888889e-2 * x7 - .3333333333333333e-1 * x5 +\n               .5555555555555556e-1 * x4 - .5555555555555556e-1 * x3 + .3333333333333333e-1 * x2 -\n               .1111111111111111e-1 * x + .1587301587301587e-2;\n    else if (x <= 3.)\n        return .4333333333333333 * x5 - .6666666666666667e-1 * x6 + .4166666666666667e-2 * x7 - 1.500000000000000 * x4 +\n               3.055555555555556 * x3 - 3.700000000000000 * x2 + 2.477777777777778 * x - .7095238095238095;\n    else if (x <= 4.)\n        return 9. * x4 - 1.666666666666667 * x5 + .1666666666666667 * x6 - .6944444444444444e-2 * x7 -\n               28.44444444444444 * x3 + 53. * x2 - 54.22222222222222 * x + 23.59047619047619;\n    else if (x <= 5.)\n        return 96. * x3 - 22.11111111111111 * x4 + 3. * x5 - .2222222222222222 * x6 + .6944444444444444e-2 * x7 -\n               245.6666666666667 * x2 + 344. * x - 203.9650793650794;\n    else if (x <= 6.)\n        return 483.5000000000000 * x2 - 147.0555555555556 * x3 + 26.50000000000000 * x4 - 2.833333333333333 * x5 +\n               .1666666666666667 * x6 - .4166666666666667e-2 * x7 - 871.2777777777778 * x + 664.0904761904762;\n    else if (x <= 7.)\n        return 943.1222222222222 * x - 423.7000000000000 * x2 + 104.9444444444444 * x3 - 15.50000000000000 * x4 +\n               1.366666666666667 * x5 - .6666666666666667e-1 * x6 + .1388888888888889e-2 * x7 - 891.1095238095238;\n    else if (x <= 8.)\n        return 416.1015873015873 - 364.0888888888889 * x + 136.5333333333333 * x2 - 28.44444444444444 * x3 +\n               3.555555555555556 * x4 - .2666666666666667 * x5 + .1111111111111111e-1 * x6 - .1984126984126984e-3 * x7;\n    else\n        return 0.;\n} // kernel\n\nvoid\ncylinder_kinematics(double /*data_time*/, Eigen::Vector3d& U_com, Eigen::Vector3d& W_com, void* /*ctx*/)\n{\n    U_com.setZero();\n    W_com.setZero();\n\n    return;\n} // cylinder_kinematics\n\n// Function prototypes\nstatic ofstream drag_stream, lift_stream;\nstatic double R;\nvoid postprocess_data(Pointer<PatchHierarchy<NDIM> > patch_hierarchy,\n                      Pointer<INSHierarchyIntegrator> navier_stokes_integrator,\n                      Mesh& mesh,\n                      EquationSystems* equation_systems,\n                      const int iteration_num,\n                      const double loop_time,\n                      const string& data_dump_dirname);\n\n/*******************************************************************************\n * For each run, the input filename and restart information (if needed) must   *\n * be given on the command line.  For non-restarted case, command line is:     *\n *                                                                             *\n *    executable <input file name>                                             *\n *                                                                             *\n * For restarted run, command line is:                                         *\n *                                                                             *\n *    executable <input file name> <restart directory> <restart number>        *\n *                                                                             *\n *******************************************************************************/\n\nint\nmain(int argc, char* argv[])\n{\n    // Initialize IBAMR and libraries. Deinitialization is handled by this object as well.\n    IBTKInit ibtk_init(argc, argv, MPI_COMM_WORLD);\n    const LibMeshInit& init = ibtk_init.getLibMeshInit();\n\n    { // cleanup dynamically allocated objects prior to shutdown\n\n        // Parse command line options, set some standard options from the input\n        // file, initialize the restart database (if this is a restarted run),\n        // and enable file logging.\n        Pointer<AppInitializer> app_initializer = new AppInitializer(argc, argv, \"IB.log\");\n        Pointer<Database> input_db = app_initializer->getInputDatabase();\n\n        // Setup user-defined kernel function.\n        LEInteractor::s_kernel_fcn = &kernel;\n        LEInteractor::s_kernel_fcn_stencil_size = 8;\n\n        // Get various standard options set in the input file.\n        const bool dump_viz_data = app_initializer->dumpVizData();\n        const int viz_dump_interval = app_initializer->getVizDumpInterval();\n        const bool uses_visit = dump_viz_data && app_initializer->getVisItDataWriter();\n#ifdef LIBMESH_HAVE_EXODUS_API\n        const bool uses_exodus = dump_viz_data && !app_initializer->getExodusIIFilename().empty();\n#else\n        const bool uses_exodus = false;\n        if (!app_initializer->getExodusIIFilename().empty())\n        {\n            plog << \"WARNING: libMesh was compiled without Exodus support, so no \"\n                 << \"Exodus output will be written in this program.\\n\";\n        }\n#endif\n        const string exodus_filename = app_initializer->getExodusIIFilename();\n\n        const bool dump_restart_data = app_initializer->dumpRestartData();\n        const int restart_dump_interval = app_initializer->getRestartDumpInterval();\n        const string restart_dump_dirname = app_initializer->getRestartDumpDirectory();\n        const string restart_read_dirname = app_initializer->getRestartReadDirectory();\n        const int restart_restore_num = app_initializer->getRestartRestoreNumber();\n\n        const bool dump_postproc_data = app_initializer->dumpPostProcessingData();\n        const int postproc_data_dump_interval = app_initializer->getPostProcessingDataDumpInterval();\n        const string postproc_data_dump_dirname = app_initializer->getPostProcessingDataDumpDirectory();\n        if (dump_postproc_data && (postproc_data_dump_interval > 0) && !postproc_data_dump_dirname.empty())\n        {\n            Utilities::recursiveMkdir(postproc_data_dump_dirname);\n        }\n\n        const bool dump_timer_data = app_initializer->dumpTimerData();\n        const int timer_dump_interval = app_initializer->getTimerDumpInterval();\n\n        // Create a simple FE mesh.\n        Mesh solid_mesh(init.comm(), NDIM);\n        const double dx = input_db->getDouble(\"DX\");\n        const double ds = input_db->getDouble(\"MFAC\") * dx;\n        string elem_type = input_db->getString(\"ELEM_TYPE\");\n        R = input_db->getDouble(\"R\");\n        if (NDIM == 2 && (elem_type == \"TRI3\" || elem_type == \"TRI6\"))\n        {\n#ifdef LIBMESH_HAVE_TRIANGLE\n            const int num_circum_nodes = ceil(2.0 * M_PI * R / ds);\n            for (int k = 0; k < num_circum_nodes; ++k)\n            {\n                const double theta = 2.0 * M_PI * static_cast<double>(k) / static_cast<double>(num_circum_nodes);\n                solid_mesh.add_point(libMesh::Point(R * cos(theta), R * sin(theta)));\n            }\n            TriangleInterface triangle(solid_mesh);\n            triangle.triangulation_type() = TriangleInterface::GENERATE_CONVEX_HULL;\n            triangle.elem_type() = Utility::string_to_enum<ElemType>(elem_type);\n            triangle.desired_area() = 1.5 * sqrt(3.0) / 4.0 * ds * ds;\n            triangle.insert_extra_points() = true;\n            triangle.smooth_after_generating() = true;\n            triangle.triangulate();\n#else\n            TBOX_ERROR(\"ERROR: libMesh appears to have been configured without support for Triangle,\\n\"\n                       << \"       but Triangle is required for TRI3 or TRI6 elements.\\n\");\n#endif\n        }\n        else\n        {\n            // NOTE: number of segments along boundary is 4*2^r.\n            const double num_circum_segments = 2.0 * M_PI * R / ds;\n            const int r = log2(0.25 * num_circum_segments);\n            MeshTools::Generation::build_sphere(solid_mesh, R, r, Utility::string_to_enum<ElemType>(elem_type));\n        }\n\n        // Ensure nodes on the surface are on the analytic boundary.\n        MeshBase::element_iterator el_end = solid_mesh.elements_end();\n        for (MeshBase::element_iterator el = solid_mesh.elements_begin(); el != el_end; ++el)\n        {\n            Elem* const elem = *el;\n            for (unsigned int side = 0; side < elem->n_sides(); ++side)\n            {\n                const bool at_mesh_bdry = !elem->neighbor_ptr(side);\n                if (!at_mesh_bdry) continue;\n                for (unsigned int k = 0; k < elem->n_nodes(); ++k)\n                {\n                    if (!elem->is_node_on_side(k, side)) continue;\n                    Node& n = elem->node_ref(k);\n                    n = R * n.unit();\n                }\n            }\n        }\n        solid_mesh.prepare_for_use();\n        Mesh& mesh = solid_mesh;\n\n        // Create major algorithm and data objects that comprise the\n        // application.  These objects are configured from the input database\n        // and, if this is a restarted run, from the restart database.\n        Pointer<INSHierarchyIntegrator> navier_stokes_integrator = new INSStaggeredHierarchyIntegrator(\n            \"INSStaggeredHierarchyIntegrator\",\n            app_initializer->getComponentDatabase(\"INSStaggeredHierarchyIntegrator\"));\n\n        Pointer<IBFEMethod> ib_method_ops =\n            new IBFEMethod(\"IBFEMethod\",\n                           app_initializer->getComponentDatabase(\"IBFEMethod\"),\n                           &mesh,\n                           app_initializer->getComponentDatabase(\"GriddingAlgorithm\")->getInteger(\"max_levels\"),\n                           /*register_for_restart*/ true,\n                           restart_read_dirname,\n                           restart_restore_num);\n        Pointer<IBHierarchyIntegrator> time_integrator =\n            new IBExplicitHierarchyIntegrator(\"IBHierarchyIntegrator\",\n                                              app_initializer->getComponentDatabase(\"IBHierarchyIntegrator\"),\n                                              ib_method_ops,\n                                              navier_stokes_integrator);\n        Pointer<CartesianGridGeometry<NDIM> > grid_geometry = new CartesianGridGeometry<NDIM>(\n            \"CartesianGeometry\", app_initializer->getComponentDatabase(\"CartesianGeometry\"));\n        Pointer<PatchHierarchy<NDIM> > patch_hierarchy = new PatchHierarchy<NDIM>(\"PatchHierarchy\", grid_geometry);\n        Pointer<StandardTagAndInitialize<NDIM> > error_detector =\n            new StandardTagAndInitialize<NDIM>(\"StandardTagAndInitialize\",\n                                               time_integrator,\n                                               app_initializer->getComponentDatabase(\"StandardTagAndInitialize\"));\n        Pointer<BergerRigoutsos<NDIM> > box_generator = new BergerRigoutsos<NDIM>();\n        Pointer<LoadBalancer<NDIM> > load_balancer =\n            new LoadBalancer<NDIM>(\"LoadBalancer\", app_initializer->getComponentDatabase(\"LoadBalancer\"));\n        Pointer<GriddingAlgorithm<NDIM> > gridding_algorithm =\n            new GriddingAlgorithm<NDIM>(\"GriddingAlgorithm\",\n                                        app_initializer->getComponentDatabase(\"GriddingAlgorithm\"),\n                                        error_detector,\n                                        box_generator,\n                                        load_balancer);\n\n        // Create IBFE direct forcing kinematics object.\n        Pointer<IBFEDirectForcingKinematics> df_kinematics_ops = new IBFEDirectForcingKinematics(\n            \"cylinder_dfk\",\n            app_initializer->getComponentDatabase(\"CylinderIBFEDirectForcingKinematics\"),\n            ib_method_ops,\n            /*part*/ 0,\n            /*register_for_restart*/ true);\n        ib_method_ops->registerDirectForcingKinematics(df_kinematics_ops, /*part*/ 0);\n\n        // Specify structure kinematics\n        FreeRigidDOFVector solve_dofs;\n        solve_dofs.setZero();\n        df_kinematics_ops->setSolveRigidBodyVelocity(solve_dofs);\n        df_kinematics_ops->registerKinematicsFunction(&cylinder_kinematics, NULL);\n\n        // Configure the IBFE solver.\n        ib_method_ops->initializeFEEquationSystems();\n        EquationSystems* equation_systems = ib_method_ops->getFEDataManager()->getEquationSystems();\n\n        // Create Eulerian initial condition specification objects.\n        if (input_db->keyExists(\"VelocityInitialConditions\"))\n        {\n            Pointer<CartGridFunction> u_init = new muParserCartGridFunction(\n                \"u_init\", app_initializer->getComponentDatabase(\"VelocityInitialConditions\"), grid_geometry);\n            navier_stokes_integrator->registerVelocityInitialConditions(u_init);\n        }\n\n        if (input_db->keyExists(\"PressureInitialConditions\"))\n        {\n            Pointer<CartGridFunction> p_init = new muParserCartGridFunction(\n                \"p_init\", app_initializer->getComponentDatabase(\"PressureInitialConditions\"), grid_geometry);\n            navier_stokes_integrator->registerPressureInitialConditions(p_init);\n        }\n\n        // Create Eulerian boundary condition specification objects (when necessary).\n        const IntVector<NDIM>& periodic_shift = grid_geometry->getPeriodicShift();\n        vector<RobinBcCoefStrategy<NDIM>*> u_bc_coefs(NDIM);\n        if (periodic_shift.min() > 0)\n        {\n            for (unsigned int d = 0; d < NDIM; ++d)\n            {\n                u_bc_coefs[d] = NULL;\n            }\n        }\n        else\n        {\n            for (unsigned int d = 0; d < NDIM; ++d)\n            {\n                const std::string bc_coefs_name = \"u_bc_coefs_\" + std::to_string(d);\n\n                const std::string bc_coefs_db_name = \"VelocityBcCoefs_\" + std::to_string(d);\n\n                u_bc_coefs[d] = new muParserRobinBcCoefs(\n                    bc_coefs_name, app_initializer->getComponentDatabase(bc_coefs_db_name), grid_geometry);\n            }\n            navier_stokes_integrator->registerPhysicalBoundaryConditions(u_bc_coefs);\n        }\n\n        // Create Eulerian body force function specification objects.\n        if (input_db->keyExists(\"ForcingFunction\"))\n        {\n            Pointer<CartGridFunction> f_fcn = new muParserCartGridFunction(\n                \"f_fcn\", app_initializer->getComponentDatabase(\"ForcingFunction\"), grid_geometry);\n            time_integrator->registerBodyForceFunction(f_fcn);\n        }\n\n        // Set up visualization plot file writers.\n        Pointer<VisItDataWriter<NDIM> > visit_data_writer = app_initializer->getVisItDataWriter();\n        if (uses_visit)\n        {\n            time_integrator->registerVisItDataWriter(visit_data_writer);\n        }\n        std::unique_ptr<ExodusII_IO> exodus_io(uses_exodus ? new ExodusII_IO(mesh) : NULL);\n\n        // Check to see if this is a restarted run to append current exodus files\n        if (uses_exodus)\n        {\n            const bool from_restart = RestartManager::getManager()->isFromRestart();\n            exodus_io->append(from_restart);\n        }\n\n        // Initialize hierarchy configuration and data on all patches.\n        ib_method_ops->initializeFEData();\n        time_integrator->initializePatchHierarchy(patch_hierarchy, gridding_algorithm);\n\n        // Deallocate initialization objects.\n        app_initializer.setNull();\n\n        // Print the input database contents to the log file.\n        plog << \"Input database:\\n\";\n        input_db->printClassData(plog);\n\n        // Write out initial visualization data.\n        int iteration_num = time_integrator->getIntegratorStep();\n        double loop_time = time_integrator->getIntegratorTime();\n        if (dump_viz_data)\n        {\n            pout << \"\\n\\nWriting visualization files...\\n\\n\";\n            if (uses_visit)\n            {\n                time_integrator->setupPlotData();\n                visit_data_writer->writePlotData(patch_hierarchy, iteration_num, loop_time);\n            }\n            if (uses_exodus)\n            {\n                exodus_io->write_timestep(\n                    exodus_filename, *equation_systems, iteration_num / viz_dump_interval + 1, loop_time);\n            }\n        }\n\n        // Open streams to save lift and drag coefficients.\n        if (IBTK_MPI::getRank() == 0)\n        {\n            drag_stream.open(\"C_D.curve\", ios_base::out | ios_base::trunc);\n            lift_stream.open(\"C_L.curve\", ios_base::out | ios_base::trunc);\n\n            drag_stream.precision(10);\n            lift_stream.precision(10);\n        }\n\n        // Main time step loop.\n        double loop_time_end = time_integrator->getEndTime();\n        double dt = 0.0;\n        while (!MathUtilities<double>::equalEps(loop_time, loop_time_end) && time_integrator->stepsRemaining())\n        {\n            iteration_num = time_integrator->getIntegratorStep();\n            loop_time = time_integrator->getIntegratorTime();\n\n            pout << \"\\n\";\n            pout << \"+++++++++++++++++++++++++++++++++++++++++++++++++++\\n\";\n            pout << \"At beginning of timestep # \" << iteration_num << \"\\n\";\n            pout << \"Simulation time is \" << loop_time << \"\\n\";\n\n            dt = time_integrator->getMaximumTimeStepSize();\n            time_integrator->advanceHierarchy(dt);\n            loop_time += dt;\n\n            pout << \"\\n\";\n            pout << \"At end       of timestep # \" << iteration_num << \"\\n\";\n            pout << \"Simulation time is \" << loop_time << \"\\n\";\n            pout << \"+++++++++++++++++++++++++++++++++++++++++++++++++++\\n\";\n            pout << \"\\n\";\n\n            // At specified intervals, write visualization and restart files,\n            // print out timer data, and store hierarchy data for post\n            // processing.\n            iteration_num += 1;\n            const bool last_step = !time_integrator->stepsRemaining();\n            if (dump_viz_data && (iteration_num % viz_dump_interval == 0 || last_step))\n            {\n                pout << \"\\nWriting visualization files...\\n\\n\";\n                if (uses_visit)\n                {\n                    time_integrator->setupPlotData();\n                    visit_data_writer->writePlotData(patch_hierarchy, iteration_num, loop_time);\n                }\n                if (uses_exodus)\n                {\n                    exodus_io->write_timestep(\n                        exodus_filename, *equation_systems, iteration_num / viz_dump_interval + 1, loop_time);\n                }\n            }\n            if (dump_restart_data && (iteration_num % restart_dump_interval == 0 || last_step))\n            {\n                pout << \"\\nWriting restart files...\\n\\n\";\n                RestartManager::getManager()->writeRestartFile(restart_dump_dirname, iteration_num);\n                ib_method_ops->writeFEDataToRestartFile(restart_dump_dirname, iteration_num);\n            }\n            if (dump_timer_data && (iteration_num % timer_dump_interval == 0 || last_step))\n            {\n                pout << \"\\nWriting timer data...\\n\\n\";\n                TimerManager::getManager()->print(plog);\n            }\n            if (dump_postproc_data && (iteration_num % postproc_data_dump_interval == 0 || last_step))\n            {\n                postprocess_data(patch_hierarchy,\n                                 navier_stokes_integrator,\n                                 mesh,\n                                 equation_systems,\n                                 iteration_num,\n                                 loop_time,\n                                 postproc_data_dump_dirname);\n            }\n        }\n\n        // Close the logging streams.\n        if (IBTK_MPI::getRank() == 0)\n        {\n            drag_stream.close();\n            lift_stream.close();\n        }\n\n        // Cleanup Eulerian boundary condition specification objects (when\n        // necessary).\n        for (unsigned int d = 0; d < NDIM; ++d) delete u_bc_coefs[d];\n\n    } // cleanup dynamically allocated objects prior to shutdown\n} // main\n\nvoid\npostprocess_data(Pointer<PatchHierarchy<NDIM> > /*patch_hierarchy*/,\n                 Pointer<INSHierarchyIntegrator> /*navier_stokes_integrator*/,\n                 Mesh& mesh,\n                 EquationSystems* equation_systems,\n                 const int /*iteration_num*/,\n                 const double loop_time,\n                 const string& /*data_dump_dirname*/)\n{\n    const unsigned int dim = mesh.mesh_dimension();\n    double F_integral[NDIM];\n    for (unsigned int d = 0; d < NDIM; ++d) F_integral[d] = 0.0;\n\n    System& F_system = equation_systems->get_system(IBFEMethod::FORCE_SYSTEM_NAME);\n    NumericVector<double>* F_vec = F_system.solution.get();\n    NumericVector<double>* F_ghost_vec = F_system.current_local_solution.get();\n    copy_and_synch(*F_vec, *F_ghost_vec);\n    const DofMap& dof_map = F_system.get_dof_map();\n    FEType fe_type = dof_map.variable_type(0);\n    std::unique_ptr<FEBase> fe(FEBase::build(dim, fe_type));\n    std::unique_ptr<QBase> qrule = fe_type.default_quadrature_rule(dim);\n    fe->attach_quadrature_rule(qrule.get());\n    const vector<double>& JxW = fe->get_JxW();\n    const vector<vector<double> >& phi = fe->get_phi();\n\n    std::vector<std::vector<unsigned int> > dof_indices(NDIM);\n    boost::multi_array<double, 2> F_node;\n    VectorValue<double> F;\n\n    const MeshBase::const_element_iterator el_begin = mesh.active_local_elements_begin();\n    const MeshBase::const_element_iterator el_end = mesh.active_local_elements_end();\n    for (MeshBase::const_element_iterator el_it = el_begin; el_it != el_end; ++el_it)\n    {\n        Elem* const elem = *el_it;\n        fe->reinit(elem);\n        for (unsigned int d = 0; d < NDIM; ++d)\n        {\n            dof_map.dof_indices(elem, dof_indices[d], d);\n        }\n        get_values_for_interpolation(F_node, *F_ghost_vec, dof_indices);\n\n        const unsigned int n_qp = qrule->n_points();\n        for (unsigned int qp = 0; qp < n_qp; ++qp)\n        {\n            interpolate(F, qp, F_node, phi);\n            for (int d = 0; d < NDIM; ++d)\n            {\n                F_integral[d] += F(d) * JxW[qp];\n            }\n        }\n    }\n    IBTK_MPI::sumReduction(F_integral, NDIM);\n    static const double rho = 1.0;\n    static const double U_max = 1.0;\n    static const double D = 2.0 * R;\n    if (IBTK_MPI::getRank() == 0)\n    {\n        drag_stream << loop_time << \" \" << -F_integral[0] / (0.5 * rho * U_max * U_max * D) << endl;\n        lift_stream << loop_time << \" \" << -F_integral[1] / (0.5 * rho * U_max * U_max * D) << endl;\n    }\n    return;\n} // postprocess_data\n", "meta": {"hexsha": "0fb83c8ff7156621b8e452329ee38683792ef2cf", "size": 24112, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/IBFE/explicit/ex11/example.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": "examples/IBFE/explicit/ex11/example.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": "examples/IBFE/explicit/ex11/example.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": 45.4943396226, "max_line_length": 120, "alphanum_fraction": 0.5956370272, "num_tokens": 5604, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6224593312018545, "lm_q2_score": 0.5273165233795671, "lm_q1q2_score": 0.3282330904745324}}
{"text": "/*\n * Copyright 2020 Robert Bosch GmbH\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 * \\file cloe/utility/geometry.hpp\n */\n\n#pragma once\n#ifndef CLOE_UTILITY_GEOMETRY_HPP_\n#define CLOE_UTILITY_GEOMETRY_HPP_\n\n#include <Eigen/Geometry>\n\nnamespace cloe {\nnamespace utility {\n\n/**\n * QuaternionFromRPY calculates a quaternion from roll, pitch and yaw.\n */\ninline Eigen::Quaterniond quaternion_from_rpy(double roll, double pitch, double yaw) {\n  // ZYX body flxed rotations\n  Eigen::Quaterniond qt = Eigen::AngleAxisd(yaw, Eigen::Vector3d::UnitZ()) *\n                          Eigen::AngleAxisd(pitch, Eigen::Vector3d::UnitY()) *\n                          Eigen::AngleAxisd(roll, Eigen::Vector3d::UnitX());\n  return qt;\n}\n\n/**\n * PoseFromRotationTranslation calculates the pose from rotation and translation.\n */\ninline Eigen::Isometry3d pose_from_rotation_translation(const Eigen::Quaterniond& quaternion,\n                                                        const Eigen::Vector3d& trans) {\n  Eigen::Isometry3d pose;\n  pose.setIdentity();\n  pose.linear() = quaternion.matrix();\n  pose.translation() = trans;\n  return pose;\n}\n\n/**\n * Change a point's frame of reference.\n * Both the point and the child frame need to have the same parent frame.\n */\ninline void transform_to_child_frame(const Eigen::Isometry3d& child_frame, Eigen::Vector3d* point) {\n  *point = child_frame.inverse() * (*point);\n}\n\n}  // namespace utility\n}  // namespace cloe\n\n#endif  // CLOE_UTILITY_GEOMETRY_HPP_\n", "meta": {"hexsha": "99c20e7f43661e42113e83e50af899b8924c8759", "size": 2043, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "models/include/cloe/utility/geometry.hpp", "max_stars_repo_name": "Sidharth-S-S/cloe", "max_stars_repo_head_hexsha": "974ef649e7dc6ec4e6869e4cf690c5b021e5091e", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 20.0, "max_stars_repo_stars_event_min_datetime": "2020-07-07T18:28:35.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-21T04:35:28.000Z", "max_issues_repo_path": "models/include/cloe/utility/geometry.hpp", "max_issues_repo_name": "Sidharth-S-S/cloe", "max_issues_repo_head_hexsha": "974ef649e7dc6ec4e6869e4cf690c5b021e5091e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 46.0, "max_issues_repo_issues_event_min_datetime": "2021-01-20T10:13:09.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-29T12:27:19.000Z", "max_forks_repo_path": "models/include/cloe/utility/geometry.hpp", "max_forks_repo_name": "Sidharth-S-S/cloe", "max_forks_repo_head_hexsha": "974ef649e7dc6ec4e6869e4cf690c5b021e5091e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 12.0, "max_forks_repo_forks_event_min_datetime": "2021-01-25T08:01:24.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-27T10:09:53.000Z", "avg_line_length": 30.9545454545, "max_line_length": 100, "alphanum_fraction": 0.6994615761, "num_tokens": 474, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6224593171945417, "lm_q2_score": 0.5273165233795671, "lm_q1q2_score": 0.32823308308824495}}
{"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//         Torsten Sattler (sattlert@inf.ethz.ch)\n\n#include \"theia/vision/sfm/camera/camera_pose.h\"\n\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n#include <glog/logging.h>\n\n#include \"theia/alignment/alignment.h\"\n\nnamespace theia {\n\nusing Eigen::Map;\nusing Eigen::Matrix3d;\nusing Eigen::Matrix;\nusing Eigen::MatrixXd;\nusing Eigen::Vector2d;\nusing Eigen::Vector3d;\n\nCameraPose::CameraPose() : k1_(0.0), k2_(0.0), k3_(0.0), k4_(0.0) {\n  calibration_matrix_.setIdentity();\n  transformation_matrix_.setIdentity();\n  projection_matrix_.setIdentity();\n}\n\nCameraPose::~CameraPose() {}\n\nvoid CameraPose::InitializePose(const Matrix3d& rotation,\n                                const Vector3d& translation,\n                                const Matrix3d& calibration, const double k1,\n                                const double k2, const double k3,\n                                const double k4) {\n  transformation_matrix_.linear() = rotation;\n  transformation_matrix_.translation() = translation;\n  calibration_matrix_ = calibration;\n  projection_matrix_ = calibration_matrix_ * transformation_matrix_.matrix();\n  k1_ = k1;\n  k2_ = k2;\n  k3_ = k3;\n  k4_ = k4;\n}\n\n// The projection matrix is defined such that P = K * [R | t], where K = diag(f,\n// f, 1) for focal length f. The rows of the rotation matrix must have the same\n// norm, so we can recover the focal length by comparing the norms of the first\n// and third projection matrix row (since only one of them will be affected by\n// the focal length).\nvoid CameraPose::InitializePose(const Matrix<double, 3, 4>& projection_matrix,\n                                const double k1, const double k2,\n                                const double k3, const double k4) {\n  projection_matrix_ = projection_matrix;\n  k1_ = k1;\n  k2_ = k2;\n  k3_ = k3;\n  k4_ = k4;\n\n  // Recover focal length and construct the calibration matrix. NOTE: setting\n  // the calibration matrix to diag(1, 1, f) is OK since we only recover the\n  // focal length as the ratio of diagonal elements (see focal_length() method).\n  const double inv_focal_length = sqrt(projection_matrix_.block<1, 3>(\n      2, 0).squaredNorm() / projection_matrix.block<1, 3>(0, 0).squaredNorm());\n  calibration_matrix_ =\n      Eigen::DiagonalMatrix<double, 3>(1.0, 1.0, inv_focal_length);\n\n  // Since P = K * T, where T = [R | t], we can recover T with T = K^-1 * P. We\n  // must use a temp matrix so that the AffineCompact3d type of Eigen does not\n  // fix the det of the rotation. We use the det of the rotation to recover the\n  // sign of the focal length.\n  const Eigen::Matrix<double, 3, 4> temp_transformation =\n      calibration_matrix_.inverse() * projection_matrix_;\n\n  // Recover the sign of the focal length using the fact that a rotation matrix\n  // should have a determinant of 1.\n  double det = temp_transformation.block<3, 3>(0, 0).determinant();\n  if (det < 0.0) {\n    calibration_matrix_(2, 2) *= -1.0;\n  }\n  transformation_matrix_ = calibration_matrix_.inverse() * projection_matrix_;\n}\n\nvoid CameraPose::InitializePose(\n    const Matrix<double, 3, 4>& transformation_matrix,\n    const Matrix3d& calibration, const double k1, const double k2,\n    const double k3, const double k4) {\n  transformation_matrix_ = transformation_matrix;\n  calibration_matrix_ = calibration;\n  projection_matrix_ = calibration_matrix_ * transformation_matrix_.matrix();\n  k1_ = k1;\n  k2_ = k2;\n  k3_ = k3;\n  k4_ = k4;\n}\n\nvoid CameraPose::InitializePose(const CameraPose& pose) {\n  InitializePose(pose.transformation_matrix_.matrix(), pose.calibration_matrix_,\n                 pose.k1_, pose.k2_, pose.k3_, pose.k4_);\n}\n\nvoid CameraPose::WorldToCamera(const Vector3d& world_point,\n                               Vector3d* camera_point) const {\n  *camera_point = transformation_matrix_ * world_point;\n}\n\nvoid CameraPose::WorldToCamera(const std::vector<Vector3d>& world_point,\n                               std::vector<Vector3d>* camera_point) const {\n  Map<const Matrix<double, 3, Eigen::Dynamic> > world_point_matrix(\n      world_point[0].data(), 3, world_point.size());\n  camera_point->clear();\n  camera_point->resize(world_point.size());\n  Map<Matrix<double, 3, Eigen::Dynamic> > camera_point_matrix(\n      (*camera_point)[0].data(), 3, camera_point->size());\n  camera_point_matrix = transformation_matrix_ * world_point_matrix;\n}\n\nvoid CameraPose::CameraToWorld(const Vector3d& camera_point,\n                               Vector3d* world_point) const {\n  *world_point = transformation_matrix_.inverse() * camera_point;\n}\n\nvoid CameraPose::CameraToWorld(const std::vector<Vector3d>& camera_point,\n                               std::vector<Vector3d>* world_point) const {\n  Map<const Matrix<double, 3, Eigen::Dynamic> > camera_point_matrix(\n      camera_point[0].data(), 3, camera_point.size());\n  world_point->clear();\n  world_point->resize(camera_point.size());\n  Map<Matrix<double, 3, Eigen::Dynamic> > world_point_matrix(\n      (*world_point)[0].data(), 3, world_point->size());\n  world_point_matrix = transformation_matrix_.inverse() * camera_point_matrix;\n}\n\nvoid CameraPose::CameraToImage(const Vector3d& camera_point,\n                               Vector2d* image_point) const {\n  *image_point = (calibration_matrix_ * camera_point).hnormalized();\n}\n\nvoid CameraPose::CameraToImage(const std::vector<Vector3d>& camera_point,\n                               std::vector<Vector2d>* image_point) const {\n  Map<const Matrix<double, 3, Eigen::Dynamic> > camera_point_matrix(\n      camera_point[0].data(), 3, camera_point.size());\n  image_point->clear();\n  image_point->resize(camera_point.size());\n  Map<Matrix<double, 2, Eigen::Dynamic> > image_point_matrix(\n      (*image_point)[0].data(), 2, image_point->size());\n  image_point_matrix = (calibration_matrix_.inverse() * camera_point_matrix)\n      .colwise().hnormalized();\n}\n\nbool CameraPose::WorldToImage(const Vector3d& world_point,\n                              Vector2d* image_point) const {\n  const Vector3d proj_point = projection_matrix_ * world_point.homogeneous();\n  // Return false if the point is behind the camera.\n  if (calibration_matrix_(0, 0) * proj_point[2] <= 0.0) {\n    return false;\n  }\n  *image_point = proj_point.hnormalized();\n  return true;\n}\n\nvoid CameraPose::WorldToImage(const std::vector<Vector3d>& world_point,\n                              std::vector<Vector2d>* image_point) const {\n  Map<const Matrix<double, 3, Eigen::Dynamic> > world_point_matrix(\n      world_point[0].data(), 3, world_point.size());\n\n  // Create a temp 3xN matrix of the projected points... eigen tends to struggle\n  // when using colwise().homogeneous() and colwise().hnormalized() in the same\n  // expression.\n  Matrix<double, 3, Eigen::Dynamic> temp_proj_mat =\n      projection_matrix_ * (world_point_matrix.colwise().homogeneous());\n\n  image_point->clear();\n  image_point->resize(world_point.size());\n  Map<Matrix<double, 2, Eigen::Dynamic> > image_point_matrix(\n      (*image_point)[0].data(), 2, image_point->size());\n  image_point_matrix = temp_proj_mat.colwise().hnormalized();\n}\n\nvoid CameraPose::UndistortImagePoint(const Vector2d& distorted_point,\n                                     Vector2d* undistorted_point) const {\n  const double r = distorted_point.squaredNorm();\n  const double w_term =\n      1.0 + k1_ * r + k2_ * r * r + k3_ * r * r * r + k4_ * r * r * r * r;\n  *undistorted_point = distorted_point / w_term;\n}\n\nvoid CameraPose::UndistortImagePoint(\n    const std::vector<Vector2d>& distorted_point,\n    std::vector<Vector2d>* undistorted_point) const {\n  undistorted_point->clear();\n  undistorted_point->resize(distorted_point.size());\n\n  Eigen::Map<const Eigen::Matrix<double, 2, Eigen::Dynamic> > distorted_map(\n      distorted_point[0].data(), 2, distorted_point.size());\n  Eigen::ArrayXd radius = distorted_map.colwise().squaredNorm();\n  radius =\n      1.0 + radius * k1_ + radius * radius * k2_ +\n      radius * radius * radius * k3_ + radius * radius * radius * radius * k4_;\n\n  Eigen::Map<Eigen::Matrix<double, 2, Eigen::Dynamic> > undistorted_map(\n      (*undistorted_point)[0].data(), 2, undistorted_point->size());\n  undistorted_map = distorted_map;\n  undistorted_map = undistorted_map.array().rowwise() / radius.transpose();\n}\n\n}  // namespace theia\n", "meta": {"hexsha": "7bc8c58ec86a384d2e852cd14f033bf2fe115fbd", "size": 10038, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/theia/vision/sfm/camera/camera_pose.cc", "max_stars_repo_name": "nuernber/Theia", "max_stars_repo_head_hexsha": "4bac771b09458a46c44619afa89498a13cd39999", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-02-02T13:30:52.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-02T13:30:52.000Z", "max_issues_repo_path": "src/theia/vision/sfm/camera/camera_pose.cc", "max_issues_repo_name": "nuernber/Theia", "max_issues_repo_head_hexsha": "4bac771b09458a46c44619afa89498a13cd39999", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/theia/vision/sfm/camera/camera_pose.cc", "max_forks_repo_name": "nuernber/Theia", "max_forks_repo_head_hexsha": "4bac771b09458a46c44619afa89498a13cd39999", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-09-28T08:43:13.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-28T08:43:13.000Z", "avg_line_length": 42.1764705882, "max_line_length": 80, "alphanum_fraction": 0.6934648336, "num_tokens": 2471, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6513548646660542, "lm_q2_score": 0.5039061705290805, "lm_q1q2_score": 0.32822173550935885}}
{"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 \"Registration.h\"\n\n#include <cstdlib>\n#include <ctime>\n#include <iostream>\n\n#include <Eigen/Dense>\n#include <Core/Utility/Console.h>\n#include <Core/Geometry/PointCloud.h>\n#include <Core/Geometry/KDTreeFlann.h>\n#include <Core/Registration/Feature.h>\n\nnamespace open3d {\n\nnamespace {\n\ndouble compute_distance_squared(const Eigen::Vector3d p1, const Eigen::Vector3d p2){\n    Eigen::Vector3d diff = p1 - p2;\n    return diff[0]*diff[0] + diff[1]*diff[1] + diff[2]*diff[2];\n}\n\nint compute_closest_vertex(const Eigen::Vector3d best_intpoint, int f, const TriangleMesh target){\n    int vertex0 = target.triangles_[f][0];\n    int vertex1 = target.triangles_[f][1];\n    int vertex2 = target.triangles_[f][2];\n    double d0 = compute_distance_squared(best_intpoint, target.vertices_[vertex0]);\n    double d1 = compute_distance_squared(best_intpoint, target.vertices_[vertex1]); \n    double d2 = compute_distance_squared(best_intpoint, target.vertices_[vertex2]);\n    //PrintInfo(\"d0: %.2f\\n\", std::sqrt(d0));\n    //PrintInfo(\"d1: %.2f\\n\", std::sqrt(d1));\n    //PrintInfo(\"d2: %.2f\\n\", std::sqrt(d2));\n    if(d0 <= d1 && d0 <= d2){\n        //PrintInfo(\"picking d0\\n\");\n        return vertex0;\n    }\n    else{\n        if(d1 <= d0 && d1 <= d2){\n            //PrintInfo(\"picking d1\\n\");\n            return vertex1;\n        }\n        else{\n            if(d2 <= d0 && d2 <= d1){\n                //PrintInfo(\"picking d2\\n\");\n                return vertex2;\n            }\n            else{\n                //PrintInfo(\"Big mistake\\n\");\n                return -1;\n            }\n        }\n    }\n}\n\n// Returns true if a ray intersects a triangle. \nbool RayIntersectsTriangle(const Eigen::Vector3d rayOrigin, \n                        const Eigen::Vector3d rayVector, \n                        const Eigen::Vector3d vertex0, \n                        const Eigen::Vector3d vertex1, \n                        const Eigen::Vector3d vertex2,\n                        Eigen::Vector3d& outIntersectionPoint)\n{\n    const float EPSILON = 0.0000001;\n    Eigen::Vector3d edge1, edge2, h, s, q;\n    float a,f,u,v;\n    edge1 = vertex1 - vertex0;\n    edge2 = vertex2 - vertex0;\n    h = rayVector.cross(edge2);\n    a = edge1.dot(h);\n    if (a > -EPSILON && a < EPSILON)\n        return false;    // This ray is parallel to this triangle.\n    f = 1.0/a;\n    s = rayOrigin - vertex0;\n    u = f * (s.dot(h));\n    if (u < 0.0 || u > 1.0)\n        return false;\n    q = s.cross(edge1);\n    v = f * rayVector.dot(q);\n    if (v < 0.0 || u + v > 1.0)\n        return false;\n    // At this stage we can compute t to find out where the intersection point is on the line.\n    float t = f * edge2.dot(q);\n    if (t > EPSILON) // ray intersection\n    {\n        outIntersectionPoint = rayOrigin + rayVector * t;\n        return true;\n    }\n    else // This means that there is a line intersection but not a ray intersection.\n        return false;\n}\n\n// For each of the neighboring triangles to each point, find which one is intersected by the line.\nvoid find_sc_corr(const TriangleMesh &target, const std::vector<int> &neigh_triangles,\\\n        const Eigen::Vector3d &source_point, const Eigen::Vector3d &source_normal,\\\n        double max_correspondence_distance, \\\n        std::vector<int> &target_corr, std::vector<double> & sc){\n\n    // For each triangle in the set, find if it is intersecting.\n    Eigen::Vector3d best_intpoint(0.0, 0.0, 0.0); \n    double best_intpoint_dist = 100000000;\n    int intpoint_face_ix = -1;\n    for (int i = 0; i < (int) neigh_triangles.size(); i++){\n        Eigen::Vector3i f = target.triangles_[neigh_triangles[i]];\n\n        Eigen::Vector3d intPoint;\n        bool intersect = RayIntersectsTriangle(source_point, source_normal, \\\n                                                target.vertices_[f[0]], target.vertices_[f[1]],\\\n                                                target.vertices_[f[2]], intPoint);\n        if(!intersect){\n            continue;\n        }\n\n        double dist2 = compute_distance_squared(intPoint, source_point);\n        if(dist2 < best_intpoint_dist){\n            best_intpoint_dist = dist2;\n            best_intpoint = intPoint;\n            intpoint_face_ix = neigh_triangles[i];\n        }\n    }\n    if(intpoint_face_ix >= 0){\n        int f = intpoint_face_ix;\n\n        // Pick the vertex closest to the intersection point.\n        target_corr[0] = compute_closest_vertex(best_intpoint, f, target);\n        double dist2 = compute_distance_squared(target.vertices_[target_corr[0]], best_intpoint);\n        Eigen::Vector3d v = best_intpoint;\n        //PrintInfo(\"--------------\\n\");\n        //PrintInfo(\"Intpoint: %.2f %.2f %.2f\\n\", v[0], v[1], v[2]);\n        v = target.vertices_[target_corr[0]];\n        //PrintInfo(\"vrtpoint: %.2f %.2f %.2f\\n\", v[0], v[1], v[2]);\n        //PrintInfo(\"vrtpoint to intpoint: %.2f\\n\", std::sqrt(dist2));\n        v = source_point;\n        //PrintInfo(\"Srcpoint: %.2f %.2f %.2f\\n\", v[0], v[1], v[2]);\n        dist2 = compute_distance_squared(target.vertices_[target_corr[0]], source_point);\n\n        // Compute shape complementarity\n        sc[0] = target.vertex_normals_[target_corr[0]].dot(-source_normal);\n        //PrintInfo(\"normal mult: %f\\n\", sc[0]);\n        sc[0] = sc[0]*std::exp(-0.5*(dist2));\n        //PrintInfo(\"shape comp: %f \\n\", sc[0]);\n    }\n    else{\n        target_corr[0] = -1;\n        sc[0] = 0.0;\n    }\n}\n\n    //\n// PGC 2019: Get registration results based on shape complementarity\nRegistrationResult GetRegistrationResultAndCorrespondencesShapeComplementarity(\n        const PointCloud &source,\n        const TriangleMesh &target,\n        const KDTreeFlann &target_faces_kdtree,\n        double max_correspondence_distance,\n        const Eigen::Matrix4d &transformation, \n        const Feature &source_feature,\n        const Feature &target_feature,\n        const int fitness_type\n        ) {\n\n    RegistrationResult result(transformation);\n    if (max_correspondence_distance <= 0.0) {\n        return std::move(result);\n    }\n\n    double error2 = 0.0;\n\n#ifdef _OPENMP\n#pragma omp parallel\n    {\n#endif\n        double error2_private = 0.0;\n        CorrespondenceSet correspondence_set_private;\n#ifdef _OPENMP\n#pragma omp for nowait\n#endif\n        // Compute the correspondences based on shape complementarity. \n        // First find all target points within X of each source point. X=max_correspondence_distance\n        // Then get all the triangles on which each target point participates. \n        // Find the intersection of the line between source point/normal  and each of the triangles. \n        // If the intersection is less than 2, we are good.\n        // Find the nearest neighbor to the intersection point.\n        for (int i = 0; i < (int)source.points_.size(); i++) {\n            std::vector<int> indices(20);\n            std::vector<double> dists(20);\n            std::vector<int> target_corr(1);\n            std::vector<double> target_sc(1);\n            const auto &point = source.points_[i];\n            const auto &normal= source.normals_[i];\n            // Identify all faces within X of the target, up to 20\n            if (target_faces_kdtree.SearchHybrid(point, max_correspondence_distance,\n                                           20, indices, dists) > 0) {\n                // Find the intersection of the line between source point/normal \n                //      and each of the triangles.\n                find_sc_corr(target, indices, point, normal, max_correspondence_distance, \\\n                        target_corr, target_sc);\n\n                if(target_sc[0] > 0){\n                    //PrintInfo(\"Adding correspondences: %d %d\\n\", i, target_corr[0]);\n                    error2_private += target_sc[0];\n                    correspondence_set_private.push_back(\n                        Eigen::Vector2i(i, target_corr[0]));\n                }\n            }\n        }\n#ifdef _OPENMP\n#pragma omp critical\n#endif\n        {\n            for (int i = 0; i < (int)correspondence_set_private.size(); i++) {\n                result.correspondence_set_.push_back(\n                        correspondence_set_private[i]);\n            }\n            error2 += error2_private;\n        }\n#ifdef _OPENMP\n    }\n#endif\n\n    if (result.correspondence_set_.empty()) {\n        result.fitness_ = 0.0;\n        result.inlier_rmse_ = 1000.0;\n    } else {\n        size_t corres_number = result.correspondence_set_.size();\n        //result.fitness_ = (double)corres_number / (double)source.points_.size();\n        if(fitness_type == 1){\n            // PGC 2019: fitness: the number of correspondences\n            result.fitness_ = (double)corres_number; \n        }\n        else{\n            if(fitness_type == 2){\n                // Compute the descriptor distances for all pairs of correspondences.\n                double myfitness = 0;\n                for (int i = 0; i < (int)result.correspondence_set_.size(); i++) {\n                    int s_vix =  result.correspondence_set_[i][0];\n                    int t_vix = result.correspondence_set_[i][1];\n                    Eigen::VectorXd feat_s = Eigen::VectorXd(source_feature.data_.col(s_vix));\n                    Eigen::VectorXd feat_t = Eigen::VectorXd(target_feature.data_.col(t_vix));\n                    double desc_dist = 0.0;\n//                    std::cout << \"Dimension = \" << source_feature.Dimension() << std::endl;\n//                    std::cout << \"Size = \" << source_feature.Num() << std::endl;\n                    for (int j = 0; j < source_feature.Dimension(); j++){\n                        double dist = feat_t[j] - feat_s[j];\n                        dist = dist*dist; \n                        desc_dist += dist;\n                    }\n\n                    myfitness += 1.0/desc_dist;\n                }\n                 \n                result.fitness_ = myfitness;\n            \n            }\n            else{\n                if (fitness_type == 3.0){ // Use shape complementarity (which is in the error).\n                    result.fitness_ = error2 / (double)source.points_.size();\n                }\n                else{\n                    result.fitness_ = (double)corres_number / (double)source.points_.size();\n                }\n            }\n        }\n        result.inlier_rmse_ = std::sqrt(error2 / (double)corres_number);\n    }\n    return std::move(result);\n}\n\n// PGC 2019: include the fitness type and the features for a custom fitness function.\nRegistrationResult GetRegistrationResultAndCorrespondencesCustom(\n        const PointCloud &source,\n        const PointCloud &target,\n        const KDTreeFlann &target_kdtree,\n        double max_correspondence_distance,\n        const Eigen::Matrix4d &transformation, \n        const Feature &source_feature,\n        const Feature &target_feature,\n        const int fitness_type\n        ) {\n    RegistrationResult result(transformation);\n    if (max_correspondence_distance <= 0.0) {\n        return std::move(result);\n    }\n\n    double error2 = 0.0;\n\n#ifdef _OPENMP\n#pragma omp parallel\n    {\n#endif\n        double error2_private = 0.0;\n        CorrespondenceSet correspondence_set_private;\n#ifdef _OPENMP\n#pragma omp for nowait\n#endif\n        for (int i = 0; i < (int)source.points_.size(); i++) {\n            std::vector<int> indices(1);\n            std::vector<double> dists(1);\n            const auto &point = source.points_[i];\n            if (target_kdtree.SearchHybrid(point, max_correspondence_distance,\n                                           1, indices, dists) > 0) {\n                error2_private += dists[0];\n                correspondence_set_private.push_back(\n                        Eigen::Vector2i(i, indices[0]));\n            }\n        }\n#ifdef _OPENMP\n#pragma omp critical\n#endif\n        {\n            for (int i = 0; i < (int)correspondence_set_private.size(); i++) {\n                result.correspondence_set_.push_back(\n                        correspondence_set_private[i]);\n            }\n            error2 += error2_private;\n        }\n#ifdef _OPENMP\n    }\n#endif\n\n    if (result.correspondence_set_.empty()) {\n        result.fitness_ = 0.0;\n        result.inlier_rmse_ = 0.0;\n    } else {\n        size_t corres_number = result.correspondence_set_.size();\n        //result.fitness_ = (double)corres_number / (double)source.points_.size();\n        if(fitness_type == 1){\n            // PGC 2019: fitness: the number of correspondences\n            result.fitness_ = (double)corres_number; \n        }\n        else{\n            if(fitness_type == 2){\n                // Compute the descriptor distances for all pairs of correspondences.\n                double myfitness = 0;\n                for (int i = 0; i < (int)result.correspondence_set_.size(); i++) {\n                    int s_vix =  result.correspondence_set_[i][0];\n                    int t_vix = result.correspondence_set_[i][1];\n                    Eigen::VectorXd feat_s = Eigen::VectorXd(source_feature.data_.col(s_vix));\n                    Eigen::VectorXd feat_t = Eigen::VectorXd(target_feature.data_.col(t_vix));\n                    double desc_dist = 0.0;\n//                    std::cout << \"Dimension = \" << source_feature.Dimension() << std::endl;\n//                    std::cout << \"Size = \" << source_feature.Num() << std::endl;\n                    for (int j = 0; j < source_feature.Dimension(); j++){\n                        double dist = feat_t[j] - feat_s[j];\n                        dist = dist*dist; \n                        desc_dist += dist;\n                    }\n\n                    myfitness += 1.0/desc_dist;\n                }\n                 \n                result.fitness_ = myfitness;\n            \n            }\n            else{\n                result.fitness_ = (double)corres_number / (double)source.points_.size();\n            }\n        }\n        result.inlier_rmse_ = std::sqrt(error2 / (double)corres_number);\n    }\n    return std::move(result);\n}\n\nRegistrationResult GetRegistrationResultAndCorrespondences(\n        const PointCloud &source,\n        const PointCloud &target,\n        const KDTreeFlann &target_kdtree,\n        double max_correspondence_distance,\n        const Eigen::Matrix4d &transformation) {\n    RegistrationResult result(transformation);\n    if (max_correspondence_distance <= 0.0) {\n        return std::move(result);\n    }\n\n    double error2 = 0.0;\n\n#ifdef _OPENMP\n#pragma omp parallel\n    {\n#endif\n        double error2_private = 0.0;\n        CorrespondenceSet correspondence_set_private;\n#ifdef _OPENMP\n#pragma omp for nowait\n#endif\n        for (int i = 0; i < (int)source.points_.size(); i++) {\n            std::vector<int> indices(1);\n            std::vector<double> dists(1);\n            const auto &point = source.points_[i];\n            if (target_kdtree.SearchHybrid(point, max_correspondence_distance,\n                                           1, indices, dists) > 0) {\n                error2_private += dists[0];\n                correspondence_set_private.push_back(\n                        Eigen::Vector2i(i, indices[0]));\n            }\n        }\n#ifdef _OPENMP\n#pragma omp critical\n#endif\n        {\n            for (int i = 0; i < (int)correspondence_set_private.size(); i++) {\n                result.correspondence_set_.push_back(\n                        correspondence_set_private[i]);\n            }\n            error2 += error2_private;\n        }\n#ifdef _OPENMP\n    }\n#endif\n\n    if (result.correspondence_set_.empty()) {\n        result.fitness_ = 0.0;\n        result.inlier_rmse_ = 0.0;\n    } else {\n        size_t corres_number = result.correspondence_set_.size();\n        //result.fitness_ = (double)corres_number / (double)source.points_.size();\n        // PGC 2019: fitness is the number of correspondences, not the fraction.\n        result.fitness_ = (double)corres_number; \n        result.inlier_rmse_ = std::sqrt(error2 / (double)corres_number);\n    }\n    return std::move(result);\n}\n\nRegistrationResult EvaluateRANSACBasedOnCorrespondence(\n        const PointCloud &source,\n        const PointCloud &target,\n        const CorrespondenceSet &corres,\n        double max_correspondence_distance,\n        const Eigen::Matrix4d &transformation) {\n    RegistrationResult result(transformation);\n    double error2 = 0.0;\n    int good = 0;\n    double max_dis2 = max_correspondence_distance * max_correspondence_distance;\n    for (const auto &c : corres) {\n        double dis2 =\n                (source.points_[c[0]] - target.points_[c[1]]).squaredNorm();\n        if (dis2 < max_dis2) {\n            good++;\n            error2 += dis2;\n        }\n    }\n    if (good == 0) {\n        result.fitness_ = 0.0;\n        result.inlier_rmse_ = 0.0;\n    } else {\n        result.fitness_ = (double)good / (double)corres.size();\n        result.inlier_rmse_ = std::sqrt(error2 / (double)good);\n    }\n    return result;\n}\n\n}  // unnamed namespace\n\nRegistrationResult EvaluateRegistration(\n        const PointCloud &source,\n        const PointCloud &target,\n        double max_correspondence_distance,\n        const Eigen::Matrix4d\n                &transformation /* = Eigen::Matrix4d::Identity()*/) {\n    KDTreeFlann kdtree;\n    kdtree.SetGeometry(target);\n    PointCloud pcd = source;\n    if (transformation.isIdentity() == false) {\n        pcd.Transform(transformation);\n    }\n    return GetRegistrationResultAndCorrespondences(\n            pcd, target, kdtree, max_correspondence_distance, transformation);\n}\n\nRegistrationResult RegistrationICP(\n        const PointCloud &source,\n        const PointCloud &target,\n        double max_correspondence_distance,\n        const Eigen::Matrix4d &init /* = Eigen::Matrix4d::Identity()*/,\n        const TransformationEstimation &estimation\n        /* = TransformationEstimationPointToPoint(false)*/,\n        const ICPConvergenceCriteria\n                &criteria /* = ICPConvergenceCriteria()*/) {\n    if (max_correspondence_distance <= 0.0) {\n        PrintError(\"Error: Invalid max_correspondence_distance.\\n\");\n        return RegistrationResult(init);\n    }\n    if (estimation.GetTransformationEstimationType() ==\n                TransformationEstimationType::PointToPlane &&\n        (!source.HasNormals() || !target.HasNormals())) {\n        PrintError(\n                \"Error: TransformationEstimationPointToPlane requires \"\n                \"pre-computed normal vectors.\\n\");\n        return RegistrationResult(init);\n    }\n\n    Eigen::Matrix4d transformation = init;\n    KDTreeFlann kdtree;\n    kdtree.SetGeometry(target);\n    PointCloud pcd = source;\n    if (init.isIdentity() == false) {\n        pcd.Transform(init);\n    }\n    RegistrationResult result;\n    result = GetRegistrationResultAndCorrespondences(\n            pcd, target, kdtree, max_correspondence_distance, transformation);\n    for (int i = 0; i < criteria.max_iteration_; i++) {\n        PrintDebug(\"ICP Iteration #%d: Fitness %.4f, RMSE %.4f\\n\", i,\n                   result.fitness_, result.inlier_rmse_);\n        Eigen::Matrix4d update = estimation.ComputeTransformation(\n                pcd, target, result.correspondence_set_);\n        transformation = update * transformation;\n        pcd.Transform(update);\n        RegistrationResult backup = result;\n        result = GetRegistrationResultAndCorrespondences(\n                pcd, target, kdtree, max_correspondence_distance,\n                transformation);\n        if (std::abs(backup.fitness_ - result.fitness_) <\n                    criteria.relative_fitness_ &&\n            std::abs(backup.inlier_rmse_ - result.inlier_rmse_) <\n                    criteria.relative_rmse_) {\n            break;\n        }\n    }\n    return result;\n}\n\nRegistrationResult RegistrationRANSACBasedOnCorrespondence(\n        const PointCloud &source,\n        const PointCloud &target,\n        const CorrespondenceSet &corres,\n        double max_correspondence_distance,\n        const TransformationEstimation &estimation\n        /* = TransformationEstimationPointToPoint(false)*/,\n        int ransac_n /* = 6*/,\n        const RANSACConvergenceCriteria &criteria\n        /* = RANSACConvergenceCriteria()*/) {\n    if (ransac_n < 3 || (int)corres.size() < ransac_n ||\n        max_correspondence_distance <= 0.0) {\n        return RegistrationResult();\n    }\n    std::srand((unsigned int)std::time(0));\n    Eigen::Matrix4d transformation;\n    CorrespondenceSet ransac_corres(ransac_n);\n    RegistrationResult result;\n    for (int itr = 0;\n         itr < criteria.max_iteration_ && itr < criteria.max_validation_;\n         itr++) {\n        for (int j = 0; j < ransac_n; j++) {\n            ransac_corres[j] = corres[std::rand() % (int)corres.size()];\n        }\n        transformation =\n                estimation.ComputeTransformation(source, target, ransac_corres);\n        PointCloud pcd = source;\n        pcd.Transform(transformation);\n        auto this_result = EvaluateRANSACBasedOnCorrespondence(\n                pcd, target, corres, max_correspondence_distance,\n                transformation);\n        if (this_result.fitness_ > result.fitness_ ||\n            (this_result.fitness_ == result.fitness_ &&\n             this_result.inlier_rmse_ < result.inlier_rmse_)) {\n            result = this_result;\n        }\n    }\n    PrintDebug(\"RANSAC: Fitness %.4f, RMSE %.4f\\n\", result.fitness_,\n               result.inlier_rmse_);\n    return result;\n}\n\nRegistrationResult RegistrationRANSACBasedOnFeatureMatching(\n        const PointCloud &source,\n        const PointCloud &target,\n        const Feature &source_feature,\n        const Feature &target_feature,\n        double max_correspondence_distance,\n        const TransformationEstimation &estimation\n        /* = TransformationEstimationPointToPoint(false)*/,\n        int ransac_n /* = 4*/,\n        const std::vector<std::reference_wrapper<const CorrespondenceChecker>>\n                &checkers /* = {}*/,\n        const RANSACConvergenceCriteria &criteria,\n        const double ransac_random_seed, /* default: 0*/\n        const int fitness_type /* 0: standard ransac fitness function. 1: use the number of inliers (instead of the ration); 2: use 1/d^2 for inliers, where d is descriptor distance.*/\n\n        /* = RANSACConvergenceCriteria()*/) {\n    if (ransac_n < 3 || max_correspondence_distance <= 0.0) {\n        return RegistrationResult();\n    }\n\n    RegistrationResult result;\n    int total_validation = 0;\n    bool finished_validation = false;\n    int num_similar_features = 1;\n    std::vector<std::vector<int>> similar_features(source.points_.size());\n\n\n#ifdef _OPENMP\n#pragma omp parallel\n    {\n#endif\n        CorrespondenceSet ransac_corres(ransac_n);\n        KDTreeFlann kdtree(target);\n        KDTreeFlann kdtree_feature(target_feature);\n        RegistrationResult result_private;\n        unsigned int seed_number;\n#ifdef _OPENMP\n        // each thread has different seed_number\n        //seed_number = (unsigned int)std::time(0) * (omp_get_thread_num() + 1);\n        seed_number = (unsigned int)ransac_random_seed * (omp_get_thread_num() + 1);\n#else\n        //seed_number = (unsigned int)std::time(0);\n        seed_number = (unsigned int)ransac_random_seed;//std::time(0);\n#endif\n        std::srand(seed_number);\n\n#ifdef _OPENMP\n#pragma omp for nowait\n#endif\n        for (int itr = 0; itr < criteria.max_iteration_; itr++) {\n            if (!finished_validation) {\n                std::vector<double> dists(num_similar_features);\n                Eigen::Matrix4d transformation;\n                for (int j = 0; j < ransac_n; j++) {\n                    int source_sample_id =\n                            std::rand() % (int)source.points_.size();\n                    if (similar_features[source_sample_id].empty()) {\n                        std::vector<int> indices(num_similar_features);\n                        kdtree_feature.SearchKNN(\n                                Eigen::VectorXd(source_feature.data_.col(\n                                        source_sample_id)),\n                                num_similar_features, indices, dists);\n#ifdef _OPENMP\n#pragma omp critical\n#endif\n                        { similar_features[source_sample_id] = indices; }\n                    }\n                    ransac_corres[j](0) = source_sample_id;\n                    if (num_similar_features == 1)\n                        ransac_corres[j](1) =\n                                similar_features[source_sample_id][0];\n                    else\n                        ransac_corres[j](1) =\n                                similar_features[source_sample_id]\n                                                [std::rand() %\n                                                 num_similar_features];\n                }\n                bool check = true;\n                for (const auto &checker : checkers) {\n                    if (checker.get().require_pointcloud_alignment_ == false &&\n                        checker.get().Check(source, target, ransac_corres,\n                                            transformation) == false) {\n                        check = false;\n                        break;\n                    }\n                }\n                if (check == false) continue;\n                transformation = estimation.ComputeTransformation(\n                        source, target, ransac_corres);\n                check = true;\n                for (const auto &checker : checkers) {\n                    if (checker.get().require_pointcloud_alignment_ == true &&\n                        checker.get().Check(source, target, ransac_corres,\n                                            transformation) == false) {\n                        check = false;\n                        break;\n                    }\n                }\n                if (check == false) continue;\n                PointCloud pcd = source;\n                pcd.Transform(transformation);\n                auto this_result = GetRegistrationResultAndCorrespondencesCustom(\n                        pcd, target, kdtree, max_correspondence_distance,\n                        transformation, source_feature, target_feature, fitness_type);\n                if (this_result.fitness_ > result_private.fitness_ ||\n                    (this_result.fitness_ == result_private.fitness_ &&\n                     this_result.inlier_rmse_ < result_private.inlier_rmse_)) {\n                    result_private = this_result;\n                }\n#ifdef _OPENMP\n#pragma omp critical\n#endif\n                {\n                    total_validation = total_validation + 1;\n                    if (total_validation >= criteria.max_validation_)\n                        finished_validation = true;\n                }\n            }  // end of if statement\n        }      // end of for-loop\n#ifdef _OPENMP\n#pragma omp critical\n#endif\n        {\n            if (result_private.fitness_ > result.fitness_ ||\n                (result_private.fitness_ == result.fitness_ &&\n                 result_private.inlier_rmse_ < result.inlier_rmse_)) {\n                result = result_private;\n            }\n        }\n#ifdef _OPENMP\n    }\n#endif\n    PrintDebug(\"total_validation : %d\\n\", total_validation);\n    PrintDebug(\"RANSAC: Fitness %.4f, RMSE %.4f\\n\", result.fitness_,\n               result.inlier_rmse_);\n    return result;\n}\n\nRegistrationResult RegistrationRANSACBasedOnShapeComplementarity(\n        const PointCloud &source,\n        const PointCloud &target,\n        const TriangleMesh &target_mesh,\n        const PointCloud &target_face_centroids_pcd,\n        const Feature &source_feature,\n        const Feature &target_feature,\n        double max_correspondence_distance,\n        const TransformationEstimation &estimation\n        /* = TransformationEstimationPointToPoint(false)*/,\n        int ransac_n /* = 4*/,\n        const std::vector<std::reference_wrapper<const CorrespondenceChecker>>\n                &checkers /* = {}*/,\n        const RANSACConvergenceCriteria &criteria,\n        const double ransac_random_seed, /* default: 0*/\n        const int fitness_type /* 0: standard ransac fitness function. 1: use the number of inliers (instead of the ration); 2: use 1/d^2 for inliers, where d is descriptor distance.*/\n\n        /* = RANSACConvergenceCriteria()*/) {\n    if (ransac_n < 3 || max_correspondence_distance <= 0.0) {\n        return RegistrationResult();\n    }\n\n    RegistrationResult result;\n    int total_validation = 0;\n    bool finished_validation = false;\n    int num_similar_features = 1;\n    std::vector<std::vector<int>> similar_features(source.points_.size());\n\n\n#ifdef _OPENMP\n#pragma omp parallel\n    {\n#endif\n        CorrespondenceSet ransac_corres(ransac_n);\n        // Do a KDTree for the triangles.\n        PointCloud target_triangle_centroids();\n        KDTreeFlann kdtree(target_face_centroids_pcd);\n        KDTreeFlann kdtree_feature(target_feature);\n        RegistrationResult result_private;\n        unsigned int seed_number;\n#ifdef _OPENMP\n        // each thread has different seed_number\n        //seed_number = (unsigned int)std::time(0) * (omp_get_thread_num() + 1);\n        seed_number = (unsigned int)ransac_random_seed * (omp_get_thread_num() + 1);\n#else\n        //seed_number = (unsigned int)std::time(0);\n        seed_number = (unsigned int)ransac_random_seed;//std::time(0);\n#endif\n        std::srand(seed_number);\n\n#ifdef _OPENMP\n#pragma omp for nowait\n#endif\n        for (int itr = 0; itr < criteria.max_iteration_; itr++) {\n            if (!finished_validation) {\n                std::vector<double> dists(num_similar_features);\n                Eigen::Matrix4d transformation;\n                for (int j = 0; j < ransac_n; j++) {\n                    int source_sample_id =\n                            std::rand() % (int)source.points_.size();\n                    if (similar_features[source_sample_id].empty()) {\n                        std::vector<int> indices(num_similar_features);\n                        kdtree_feature.SearchKNN(\n                                Eigen::VectorXd(source_feature.data_.col(\n                                        source_sample_id)),\n                                num_similar_features, indices, dists);\n#ifdef _OPENMP\n#pragma omp critical\n#endif\n                        { similar_features[source_sample_id] = indices; }\n                    }\n                    ransac_corres[j](0) = source_sample_id;\n                    if (num_similar_features == 1)\n                        ransac_corres[j](1) =\n                                similar_features[source_sample_id][0];\n                    else\n                        ransac_corres[j](1) =\n                                similar_features[source_sample_id]\n                                                [std::rand() %\n                                                 num_similar_features];\n                }\n                bool check = true;\n                for (const auto &checker : checkers) {\n                    if (checker.get().require_pointcloud_alignment_ == false &&\n                        checker.get().Check(source, target, ransac_corres,\n                                            transformation) == false) {\n                        check = false;\n                        break;\n                    }\n                }\n                if (check == false) continue;\n                transformation = estimation.ComputeTransformation(\n                        source, target, ransac_corres);\n                check = true;\n                for (const auto &checker : checkers) {\n                    if (checker.get().require_pointcloud_alignment_ == true &&\n                        checker.get().Check(source, target, ransac_corres,\n                                            transformation) == false) {\n                        check = false;\n                        break;\n                    }\n                }\n                if (check == false) continue;\n                PointCloud pcd = source;\n                pcd.Transform(transformation);\n                //PrintInfo(\"###################\\n\"); \n                //PrintInfo(\"###################\\n\"); \n                //PrintInfo(\"Evaluating transformation\\n\"); \n                auto this_result = GetRegistrationResultAndCorrespondencesShapeComplementarity(\n                        pcd, target_mesh, kdtree, max_correspondence_distance,\n                        transformation, source_feature, target_feature, fitness_type);\n                if (this_result.fitness_ > result_private.fitness_ ||\n                    (this_result.fitness_ == result_private.fitness_ &&\n                     this_result.inlier_rmse_ < result_private.inlier_rmse_)) {\n                    result_private = this_result;\n                }\n#ifdef _OPENMP\n#pragma omp critical\n#endif\n                {\n                    total_validation = total_validation + 1;\n                    if (total_validation >= criteria.max_validation_)\n                        finished_validation = true;\n                }\n            }  // end of if statement\n        }      // end of for-loop\n#ifdef _OPENMP\n#pragma omp critical\n#endif\n        {\n            if (result_private.fitness_ > result.fitness_ ||\n                (result_private.fitness_ == result.fitness_ &&\n                 result_private.inlier_rmse_ < result.inlier_rmse_)) {\n                result = result_private;\n            }\n        }\n#ifdef _OPENMP\n    }\n#endif\n    PrintDebug(\"total_validation : %d\\n\", total_validation);\n    PrintDebug(\"RANSAC: Fitness %.4f, RMSE %.4f\\n\", result.fitness_,\n               result.inlier_rmse_);\n    return result;\n}\n\nEigen::Matrix6d GetInformationMatrixFromPointClouds(\n        const PointCloud &source,\n        const PointCloud &target,\n        double max_correspondence_distance,\n        const Eigen::Matrix4d &transformation) {\n    PointCloud pcd = source;\n    if (transformation.isIdentity() == false) {\n        pcd.Transform(transformation);\n    }\n    RegistrationResult result;\n    KDTreeFlann target_kdtree(target);\n    result = GetRegistrationResultAndCorrespondences(\n            pcd, target, target_kdtree, max_correspondence_distance,\n            transformation);\n\n    // write q^*\n    // see http://redwood-data.org/indoor/registration.html\n    // note: I comes first in this implementation\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 c = 0; c < result.correspondence_set_.size(); c++) {\n            int t = result.correspondence_set_[c](1);\n            double x = target.points_[t](0);\n            double y = target.points_[t](1);\n            double z = target.points_[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        { GTG += GTG_private; }\n#ifdef _OPENMP\n    }\n#endif\n    return std::move(GTG);\n}\n\n}  // namespace open3d\n", "meta": {"hexsha": "aaad08010f6fc289f49c880393c40e7cda9974ee", "size": 36834, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Core/Registration/Registration.cpp", "max_stars_repo_name": "pablogainza/Open3D", "max_stars_repo_head_hexsha": "b2f89b29bbfd0cfc7e1668e0edd9f17b024b521a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-05-06T22:47:22.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-06T22:47:22.000Z", "max_issues_repo_path": "src/Core/Registration/Registration.cpp", "max_issues_repo_name": "pablogainza/Open3D", "max_issues_repo_head_hexsha": "b2f89b29bbfd0cfc7e1668e0edd9f17b024b521a", "max_issues_repo_licenses": ["MIT"], "max_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/Registration/Registration.cpp", "max_forks_repo_name": "pablogainza/Open3D", "max_forks_repo_head_hexsha": "b2f89b29bbfd0cfc7e1668e0edd9f17b024b521a", "max_forks_repo_licenses": ["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.5214592275, "max_line_length": 184, "alphanum_fraction": 0.5715643156, "num_tokens": 8285, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6825737344123242, "lm_q2_score": 0.48047867804790706, "lm_q1q2_score": 0.32796212558065674}}
{"text": "\n/*\n * DynamicalSystem.hpp\n *\n *  Created on: July 7, 2019\n *      Author: Quincy Jones\n *\n * Copyright (c) <2019> <Quincy Jones - quincy@implementedrobotics.com/>\n * Permission is hereby granted, free of charge, to any person obtaining a\n * copy of this software and associated documentation files (the \"Software\"),\n * to deal in the Software without restriction, including without limitation\n * the rights to use, copy, modify, merge, publish, distribute, sublicense,\n * and/or sell copies of the Software, and to permit persons to whom the Software\n * is furnished to do so, subject to the following conditions:\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY#endif // NOMAD_CORE_NOMAD_NOMAD_H,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,\n * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n */\n\n\n#ifndef NOMAD_CORE_SYSTEMS_DYNAMICALSYSTEM_H_\n#define NOMAD_CORE_SYSTEMS_DYNAMICALSYSTEM_H_\n\n#include <Eigen/Dense>\n#include <unsupported/Eigen/MatrixFunctions>\n#include <vector>\n\n\n// TODO: Need to split all of this into Discrete Time and Continuous Time Systems\n// TODO: Also Maybe a SS Container?\nclass DynamicalSystem\n{\n\npublic:\n    DynamicalSystem(const int& num_states, const int& num_inputs, const double& Ts = 1e-1);\n\n    // Step System\n    virtual void Step(const Eigen::VectorXd& u) = 0;\n\n    // Update\n    virtual void Update() = 0;\n\n    // Get Current State\n    Eigen::VectorXd GetState() const { return x_; }\n\n    // Set Current State\n    void SetState(const Eigen::VectorXd &x) { x_ = x; }\n\n    int NumStates() const { return num_states_; }\n    int NumInputs() const { return num_inputs_; }\n\nprotected:\n\n    Eigen::VectorXd x_;  // State Vector\n\n    int num_states_; // Number of System States\n    int num_inputs_;     // Number of inputs\n\n    double T_s_; // Sample Time\n    double t_; // Current Time\n};\n\n\nclass NonLinearDynamicalSystem : public DynamicalSystem\n{\n    \nprotected:\n\n    virtual void f(const Eigen::MatrixXd& x, const Eigen::MatrixXd& u) = 0;\n\n};\n\nclass LinearDynamicalSystem : public DynamicalSystem\n{\n\npublic:\n\n    LinearDynamicalSystem(const int& num_states, const int& num_inputs, const double& T_s = 1e-1);\n\n    // Model Matrices\n    Eigen::MatrixXd A() const { return A_; };\n    Eigen::MatrixXd B() const { return B_; };\n\n    // Discrete Time Model Matrices\n    Eigen::MatrixXd A_d() const { return A_d_; };\n    Eigen::MatrixXd B_d() const { return B_d_; };\n\nprotected:\n\n    Eigen::MatrixXd A_;  // State Transition Mat rix\n    Eigen::MatrixXd B_;  // Control Input Matrix\n\n    Eigen::MatrixXd A_d_;  // Discrete Time State Transition Mat rix\n    Eigen::MatrixXd B_d_;  // Discrete Time Input Matrix\n\n};\n\nclass LinearTimeVaryingDynamicalSystem : public LinearDynamicalSystem\n{\n\npublic:\n\n    // Constructor\n    LinearTimeVaryingDynamicalSystem(const int& num_states, const int& num_inputs, const double& T_s = 1e-1);\n\n    // Get the Time-Varying Matrices from Model\n    virtual void GetModelMatrices(const int& N, Eigen::MatrixXd& A, Eigen::MatrixXd& B) = 0;\n\n    // Model Matrices (Time Varying)\n    std::vector<Eigen::MatrixXd> A_TV() const { return A_tv_; };\n    std::vector<Eigen::MatrixXd> B_TV() const { return B_tv_; };\n\n    // Discrete Time Model Matrices (Time Varying)\n    std::vector<Eigen::MatrixXd> A_d_TV() const { return A_d_tv_; };\n    std::vector<Eigen::MatrixXd> B_d_TV() const { return B_d_tv_; };\n\nprotected:\n\n    // Model Matrices (Time Varying)\n    std::vector<Eigen::MatrixXd> A_tv_;\n    std::vector<Eigen::MatrixXd> B_tv_;\n\n    // Discrete Time Model Matrices (Time Varying)\n    std::vector<Eigen::MatrixXd> A_d_tv_;\n    std::vector<Eigen::MatrixXd> B_d_tv_;\n};\n\n#endif // NOMAD_CORE_SYSTEMS_DYNAMICALSYSTEM_H_", "meta": {"hexsha": "439be5035f01ac8dcc16fd1853e641c803207632", "size": 4135, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Software/Core/Systems/include/Systems/DynamicalSystem.hpp", "max_stars_repo_name": "implementedrobotics/Nomad", "max_stars_repo_head_hexsha": "de8c27ed79cdcde59b1fd6e9a0865d29b84b7d58", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 31.0, "max_stars_repo_stars_event_min_datetime": "2019-08-11T18:24:54.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-08T01:22:55.000Z", "max_issues_repo_path": "Software/Core/Systems/include/Systems/DynamicalSystem.hpp", "max_issues_repo_name": "implementedrobotics/Nomad", "max_issues_repo_head_hexsha": "de8c27ed79cdcde59b1fd6e9a0865d29b84b7d58", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 15.0, "max_issues_repo_issues_event_min_datetime": "2019-05-29T12:57:20.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-29T02:26:06.000Z", "max_forks_repo_path": "Software/Core/Systems/include/Systems/DynamicalSystem.hpp", "max_forks_repo_name": "implementedrobotics/Nomad", "max_forks_repo_head_hexsha": "de8c27ed79cdcde59b1fd6e9a0865d29b84b7d58", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 11.0, "max_forks_repo_forks_event_min_datetime": "2019-08-12T03:05:06.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-09T05:34:16.000Z", "avg_line_length": 31.0902255639, "max_line_length": 109, "alphanum_fraction": 0.7136638452, "num_tokens": 1046, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6039318337259584, "lm_q2_score": 0.5428632831725052, "lm_q1q2_score": 0.3278524180688653}}
{"text": "/*\n boost/numeric/odeint/stepper/detail/controlled_adams_bashforth_moulton.hpp\n\n [begin_description]\n Implemetation of an controlled adams bashforth moulton stepper.\n [end_description]\n\n Copyright 2017 Valentin Noah Hartmann\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#ifndef BOOST_NUMERIC_ODEINT_STEPPER_CONTROLLED_ADAMS_BASHFORTH_MOULTON_HPP_INCLUDED\n#define BOOST_NUMERIC_ODEINT_STEPPER_CONTROLLED_ADAMS_BASHFORTH_MOULTON_HPP_INCLUDED\n\n#include <boost/numeric/odeint/stepper/stepper_categories.hpp>\n#include <boost/numeric/odeint/stepper/controlled_step_result.hpp>\n\n#include <boost/numeric/odeint/stepper/adaptive_adams_bashforth_moulton.hpp>\n#include <boost/numeric/odeint/stepper/detail/pid_step_adjuster.hpp>\n\n#include <boost/numeric/odeint/util/unwrap_reference.hpp>\n#include <boost/numeric/odeint/util/is_resizeable.hpp>\n#include <boost/numeric/odeint/util/resizer.hpp>\n\n#include <boost/numeric/odeint/util/copy.hpp>\n#include <boost/numeric/odeint/util/bind.hpp>\n\n#include <iostream>\n\nnamespace boost {\nnamespace numeric {\nnamespace odeint {\n\ntemplate<\nsize_t MaxOrder,\nclass State,\nclass Value = double,\nclass Algebra = typename algebra_dispatcher< State >::algebra_type\n>\nclass default_order_adjuster\n{\npublic:\n    typedef State state_type;\n    typedef Value value_type;\n    typedef state_wrapper< state_type > wrapped_state_type;\n\n    typedef Algebra algebra_type;\n\n    default_order_adjuster( const algebra_type &algebra = algebra_type() )\n    : m_algebra( algebra )\n    {};\n\n    size_t adjust_order(size_t order, size_t init, boost::array<wrapped_state_type, 4> &xerr)\n    {\n        using std::abs;\n\n        value_type errc = abs(m_algebra.norm_inf(xerr[2].m_v));\n\n        value_type errm1 = 3*errc;\n        value_type errm2 = 3*errc;\n\n        if(order > 2)\n        {\n            errm2 = abs(m_algebra.norm_inf(xerr[0].m_v));\n        }\n        if(order >= 2)\n        {\n            errm1 = abs(m_algebra.norm_inf(xerr[1].m_v));\n        }\n\n        size_t o_new = order;\n\n        if(order == 2 && errm1 <= 0.5*errc)\n        {\n            o_new = order - 1;\n        }\n        else if(order > 2 && errm2 < errc && errm1 < errc)\n        {\n            o_new = order - 1;\n        }\n\n        if(init < order)\n        {\n            return order+1;\n        }\n        else if(o_new == order - 1)\n        {\n            return order-1;\n        }\n        else if(order <= MaxOrder)\n        {\n            value_type errp = abs(m_algebra.norm_inf(xerr[3].m_v));\n\n            if(order > 1 && errm1 < errc && errp)\n            {\n                return order-1;\n            }\n            else if(order < MaxOrder && errp < (0.5-0.25*order/MaxOrder) * errc)\n            {\n                return order+1;\n            }\n        }\n\n        return order;\n    };\nprivate:\n    algebra_type m_algebra;\n};\n\ntemplate<\nclass ErrorStepper,\nclass StepAdjuster = detail::pid_step_adjuster< typename ErrorStepper::state_type, \n    typename ErrorStepper::value_type,\n    typename ErrorStepper::deriv_type,\n    typename ErrorStepper::time_type,\n    typename ErrorStepper::algebra_type,\n    typename ErrorStepper::operations_type,\n    detail::H211PI\n    >,\nclass OrderAdjuster = default_order_adjuster< ErrorStepper::order_value,\n    typename ErrorStepper::state_type,\n    typename ErrorStepper::value_type,\n    typename ErrorStepper::algebra_type\n    >,\nclass Resizer = initially_resizer\n>\nclass controlled_adams_bashforth_moulton\n{\npublic:\n    typedef ErrorStepper stepper_type;\n\n    static const typename stepper_type::order_type order_value = stepper_type::order_value;\n    \n    typedef typename stepper_type::state_type state_type;\n    typedef typename stepper_type::value_type value_type;\n    typedef typename stepper_type::deriv_type deriv_type;\n    typedef typename stepper_type::time_type time_type;\n\n    typedef typename stepper_type::algebra_type algebra_type;\n    typedef typename stepper_type::operations_type operations_type;\n    typedef Resizer resizer_type;\n\n    typedef StepAdjuster step_adjuster_type;\n    typedef OrderAdjuster order_adjuster_type;\n    typedef controlled_stepper_tag stepper_category;\n\n    typedef typename stepper_type::wrapped_state_type wrapped_state_type;\n    typedef typename stepper_type::wrapped_deriv_type wrapped_deriv_type;\n    typedef boost::array< wrapped_state_type , 4 > error_storage_type;\n\n    typedef typename stepper_type::coeff_type coeff_type;\n    typedef controlled_adams_bashforth_moulton< ErrorStepper , StepAdjuster , OrderAdjuster , Resizer > controlled_stepper_type;\n\n    controlled_adams_bashforth_moulton(step_adjuster_type step_adjuster = step_adjuster_type())\n    :m_stepper(),\n    m_dxdt_resizer(), m_xerr_resizer(), m_xnew_resizer(),\n    m_step_adjuster( step_adjuster ), m_order_adjuster()\n    {};\n\n    template< class ExplicitStepper, class System >\n    void initialize(ExplicitStepper stepper, System system, state_type &inOut, time_type &t, time_type dt)\n    {\n        m_stepper.initialize(stepper, system, inOut, t, dt);\n    };\n\n    template< class System >\n    void initialize(System system, state_type &inOut, time_type &t, time_type dt)\n    {\n        m_stepper.initialize(system, inOut, t, dt);\n    };\n\n    template< class ExplicitStepper, class System >\n    void initialize_controlled(ExplicitStepper stepper, System system, state_type &inOut, time_type &t, time_type &dt)\n    {\n        reset();\n        coeff_type &coeff = m_stepper.coeff();\n\n        m_dxdt_resizer.adjust_size( inOut , detail::bind( &controlled_stepper_type::template resize_dxdt_impl< state_type > , detail::ref( *this ) , detail::_1 ) );\n\n        controlled_step_result res = fail;\n\n        for( size_t i=0 ; i<order_value; ++i )\n        {\n            do\n            {\n                res = stepper.try_step( system, inOut, t, dt );\n            }\n            while(res != success);\n\n            system( inOut , m_dxdt.m_v , t );\n            \n            coeff.predict(t-dt, dt);\n            coeff.do_step(m_dxdt.m_v);\n            coeff.confirm();\n\n            if(coeff.m_eo < order_value)\n            {\n                ++coeff.m_eo;\n            }\n        }\n    }\n\n    template< class System >\n    controlled_step_result try_step(System system, state_type & inOut, time_type &t, time_type &dt)\n    {\n        m_xnew_resizer.adjust_size( inOut , detail::bind( &controlled_stepper_type::template resize_xnew_impl< state_type > , detail::ref( *this ) , detail::_1 ) );\n\n        controlled_step_result res = try_step(system, inOut, t, m_xnew.m_v, dt);\n\n        if(res == success)\n        {\n            boost::numeric::odeint::copy( m_xnew.m_v , inOut);\n        }\n\n        return res;\n    };\n\n    template< class System >\n    controlled_step_result try_step(System system, const state_type & in, time_type &t, state_type & out, time_type &dt)\n    {\n        m_xerr_resizer.adjust_size( in , detail::bind( &controlled_stepper_type::template resize_xerr_impl< state_type > , detail::ref( *this ) , detail::_1 ) );\n        m_dxdt_resizer.adjust_size( in , detail::bind( &controlled_stepper_type::template resize_dxdt_impl< state_type > , detail::ref( *this ) , detail::_1 ) );\n\n        m_stepper.do_step_impl(system, in, t, out, dt, m_xerr[2].m_v);\n\n        coeff_type &coeff = m_stepper.coeff();\n\n        time_type dtPrev = dt;\n        dt = m_step_adjuster.adjust_stepsize(coeff.m_eo, dt, m_xerr[2].m_v, out, m_stepper.dxdt() );\n\n        if(dt / dtPrev >= step_adjuster_type::threshold())\n        {\n            system(out, m_dxdt.m_v, t+dtPrev);\n\n            coeff.do_step(m_dxdt.m_v);\n            coeff.confirm();\n\n            t += dtPrev;\n\n            size_t eo = coeff.m_eo;\n\n            // estimate errors for next step\n            double factor = 1;\n            algebra_type m_algebra;\n\n            m_algebra.for_each2(m_xerr[2].m_v, coeff.phi[1][eo].m_v, \n                typename operations_type::template scale_sum1<double>(factor*dt*(coeff.gs[eo])));\n\n            if(eo > 1)\n            {\n                m_algebra.for_each2(m_xerr[1].m_v, coeff.phi[1][eo-1].m_v, \n                    typename operations_type::template scale_sum1<double>(factor*dt*(coeff.gs[eo-1])));\n            }\n            if(eo > 2)\n            {\n                m_algebra.for_each2(m_xerr[0].m_v, coeff.phi[1][eo-2].m_v, \n                    typename operations_type::template scale_sum1<double>(factor*dt*(coeff.gs[eo-2])));\n            }\n            if(eo < order_value && coeff.m_eo < coeff.m_steps_init-1)\n            {\n                m_algebra.for_each2(m_xerr[3].m_v, coeff.phi[1][eo+1].m_v, \n                    typename operations_type::template scale_sum1<double>(factor*dt*(coeff.gs[eo+1])));\n            }\n\n            // adjust order\n            coeff.m_eo = m_order_adjuster.adjust_order(coeff.m_eo, coeff.m_steps_init-1, m_xerr);\n\n            return success;\n        }\n        else\n        {\n            return fail;\n        }\n    };\n\n    void reset() { m_stepper.reset(); };\n\nprivate:\n    template< class StateType >\n    bool resize_dxdt_impl( const StateType &x )\n    {\n        return adjust_size_by_resizeability( m_dxdt, x, typename is_resizeable<deriv_type>::type() );\n    };\n    template< class StateType >\n    bool resize_xerr_impl( const StateType &x )\n    {\n        bool resized( false );\n\n        for(size_t i=0; i<m_xerr.size(); ++i)\n        {\n            resized |= adjust_size_by_resizeability( m_xerr[i], x, typename is_resizeable<state_type>::type() );\n        }\n        return resized;\n    };\n    template< class StateType >\n    bool resize_xnew_impl( const StateType &x )\n    {\n        return adjust_size_by_resizeability( m_xnew, x, typename is_resizeable<state_type>::type() );\n    };\n\n    stepper_type m_stepper;\n\n    wrapped_deriv_type m_dxdt;\n    error_storage_type m_xerr;\n    wrapped_state_type m_xnew;\n\n    resizer_type m_dxdt_resizer;\n    resizer_type m_xerr_resizer;\n    resizer_type m_xnew_resizer;\n\n    step_adjuster_type m_step_adjuster;\n    order_adjuster_type m_order_adjuster;\n};\n\n} // odeint\n} // numeric\n} // boost\n\n#endif\n", "meta": {"hexsha": "79af64ab27ffd846dbc6a3374c845bfd248627ff", "size": 10081, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "SilveR/R/library/BH/include/boost/numeric/odeint/stepper/controlled_adams_bashforth_moulton.hpp", "max_stars_repo_name": "robalexclark/SilveR-Dev", "max_stars_repo_head_hexsha": "263008fdb9dc3fdd22bfc6f71b7c092867631563", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2019-04-27T10:26:46.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-04T09:57:34.000Z", "max_issues_repo_path": "SilveR/R/library/BH/include/boost/numeric/odeint/stepper/controlled_adams_bashforth_moulton.hpp", "max_issues_repo_name": "robalexclark/SilveR-Dev", "max_issues_repo_head_hexsha": "263008fdb9dc3fdd22bfc6f71b7c092867631563", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 14.0, "max_issues_repo_issues_event_min_datetime": "2019-12-28T07:09:11.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-28T19:33:50.000Z", "max_forks_repo_path": "SilveR/R/library/BH/include/boost/numeric/odeint/stepper/controlled_adams_bashforth_moulton.hpp", "max_forks_repo_name": "robalexclark/SilveR-Dev", "max_forks_repo_head_hexsha": "263008fdb9dc3fdd22bfc6f71b7c092867631563", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-03-05T05:52:24.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-18T07:52:04.000Z", "avg_line_length": 31.2105263158, "max_line_length": 164, "alphanum_fraction": 0.6482491816, "num_tokens": 2537, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6406358685621719, "lm_q2_score": 0.5117166047041654, "lm_q1q2_score": 0.3278240115123386}}
{"text": "/*****************************************************************************\n*\n* Functions for calculating the gap\n*\n* Copyright (C) 2018 by Hidemaro Suwa\n* e-mail:suwamaro@phys.s.u-tokyo.ac.jp\n*\n*****************************************************************************/\n\n// #include <functional>\n#include <armadillo>\n#include <cuba.h>\n#include \"calc_gap.h\"\n#include \"rpa_util.h\"\n#include \"calc_intensity.h\"\n\n/* Index: NCOMP = (ope * nelem + elem) | (real=0 or imag=1) */\nstd::tuple<int, int> comp_to_ope_elem(int comp, int nelem){\n  comp >>= 1;\n  int ope = comp / nelem;\n  int elem = comp % nelem;\n  return std::make_tuple(ope, elem);\n}\n\n/* Member functions of ResponseFuncIntegrand */\nvoid ResponseFuncIntegrand::update_parameters(double _T, double _delta, double _mu, cx_double _omega, Polarization const& _Pz){\n  T_ = _T;\n  delta_ = _delta;\n  mu_ = _mu;\n  omega_ = _omega;\n  Pz_ = _Pz;  // without copying the tables\n  Pz_.is_table_set_ = false;\n};\n\n/* Member functions of ResponseFuncIntegrandBilayer */\nvoid ResponseFuncIntegrandBilayer::set_parameters(hoppings_bilayer2 const& h, double T, double delta, double mu, cx_double omega, Polarization const& Pz){\n  hb_ = h;\n  ResponseFuncIntegrand::update_parameters(T, delta, mu, omega, Pz);\n}\n\nint ResponseFuncIntegrandBilayer::calc(const int *ndim, const cubareal xx[], const int *ncomp, cubareal ff[], void *userdata) const {\n   /* Reset */\n   for(int comp=0; comp<*ncomp; comp++){ ff[comp] = 0; }\n   \t\t\t\t    \n   /* Wavenumbers */\n   double k1 = xx[0] * 2 * M_PI;\n   double k2 = xx[1] * 2 * M_PI;\n   \n   double kx = 0.5 * (k2 + k1);\n   double ky = 0.5 * (k2 - k1);\n\n   /* Polarizaiton */\n   cx_double Ppmk[NSUBL*NSUBL];\n   cx_double Pzzk[NSUBL*NSUBL];\n       \n   /* Sum over kz */\n   for(int z=0; z < 2; z++){       \n     double kz = M_PI * z;\t  \n     \n     /* Sum over bands (signs) */\n     for(int sg1=-1; sg1<=1; sg1+=2){\n       for(int sg2=-1; sg2<=1; sg2+=2){\n\t // int sg2 = - sg1; /* Opposite sign */\n\t cx_double prefactor = calc_prefactor_bare_res_func_bilayer(sg1, sg2, *ts(), T(), kx, ky, kz, Pz()->qx(), Pz()->qy(), Pz()->qz(), omega(), delta(), mu());\n    \n\t /* Getting the polarization */\n\t Pz()->calc_polarization(hb_, delta(), kx, ky, kz, sg1, sg2, Ppmk, Pzzk);\n\n\t /* Integrand */\n\t for(int comp=0; comp<*ncomp; comp+=2){\n\t   int ope, elem;\n\t   std::tie(ope, elem) = comp_to_ope_elem(comp, NSUBL*NSUBL);\n\t   if ( ope == 0 ) {  /* Ppmk */\n\t     ff[comp] += std::real(prefactor * Ppmk[elem]);\n\t     ff[comp+1] += std::imag(prefactor * Ppmk[elem]);\n\t   } else /* ope == 1 */ { /* Pzzk */\t      \n\t     ff[comp] += std::real(prefactor * Pzzk[elem]);\n\t     ff[comp+1] += std::imag(prefactor * Pzzk[elem]);\n\t   }\n\t }\n       }\n     }\n   }\n   \n   return 0;   \n}\n\n\ncx_double calc_intensity_bilayer(int L, hoppings const& ts, double mu, double U, double delta, double qx, double qy, double qz, cx_double omega, bool zz){\n  double k1 = 2. * M_PI / (double)L;\n  \n  cx_double A = 0, B = 0, C = 0, D = 0;\n  for(int z=0; z < 2; z++){    \n    double kz = M_PI * z;\n    for(int x=-L/2; x < L/2; x++){    \n      double kx = k1 * x;\n      for(int y=-L/2; y < L/2; y++){\n\tdouble ky = k1 * y;\n\tadd_to_sus_mat2( ts, mu, A, B, C, D, qx, qy, qz, kx, ky, kz, delta, omega, zz );\t\n      }\n    }\n  }\n\n  int n_sites = L * L * 2;\n  double norm = 2. / (double)n_sites;\n  A *= norm;\n  B *= norm;\n  C *= norm;\n  D *= norm;\n  \n  /* RPA */\n  arma::cx_mat chi0_mat(2,2);\n  chi0_mat(0,0) = A;   // (A, A) correlation\n  chi0_mat(0,1) = B;   // (A, B)\n  chi0_mat(1,0) = C;   // (B, A)\n  chi0_mat(1,1) = D;   // (B, B)\n\n  /* Transverse = < \\sigma^- \\sigma^+ >; Longitudinal (zz) = < \\sigma^z \\sigma^z > */\n  /* Note that 2 < \\sigma^- \\sigma^+ > = < \\sigma^z \\sigma^z > (U -> 0 for the SU(2) case) */  \n  double factor_channel = 1.0;\n  if ( zz ) { factor_channel = 0.5; }\n  \n  arma::cx_mat denom = arma::eye<arma::cx_mat>(NSUBL,NSUBL) - factor_channel * U * chi0_mat;\n  arma::cx_mat chi_mat = chi0_mat * arma::inv(denom);\n  \n  // sigma-to-spin factor\n  double factor_operator = 0.5;  \n  cx_double chi = factor_operator * factor_operator * ( chi_mat(0,0) - chi_mat(1,0) - chi_mat(0,1) + chi_mat(1,1) );  \n\n  // // for check\n  // std::cout << chi0_mat << std::endl;\n  // std::cout << chi_mat << std::endl;\n  \n  return chi;  \n}\n\n/* Instantiation */\nResponseFuncIntegrandBilayer rfib;\n\nint integrand_wrapper(const int *ndim, const cubareal xx[], const int *ncomp, cubareal ff[], void *userdata){\n  return rfib.calc(ndim, xx, ncomp, ff, userdata);\n}\n\nstd::tuple<arma::cx_mat, arma::cx_mat> calc_bare_response_bilayer(int L, hoppings_bilayer2 const& ts, double mu, double U, double T, double delta, CubaParam const& cbp, Polarization const& Pz, cx_double omega, bool continuous_k){\n  arma::cx_mat chi0_pm(NSUBL,NSUBL,arma::fill::zeros);\n  arma::cx_mat chi0_zz_u(NSUBL,NSUBL,arma::fill::zeros);\n  \n  if ( continuous_k ) {\n    /* Changing the parameters */\n    rfib.set_parameters(ts, T, delta, mu, omega, Pz);\n\n    /* For Cuba */\n    int nregions, neval, fail;\n    cubareal integral[cbp.NCOMP], error[cbp.NCOMP], prob[cbp.NCOMP];\n    \n    /* Cuhre */\n    Cuhre(cbp.NDIM, cbp.NCOMP, integrand_wrapper, cbp.userdata, cbp.nvec, cbp.epsrel, cbp.epsabs, cbp.flags, cbp.mineval, cbp.maxeval, cbp.key, cbp.statefile, cbp.spin, &nregions, &neval, &fail, integral, error, prob);\n    \n    // for check\n    printf(\"CUHRE RESULT:\\tnregions %d\\tneval %d\\tfail %d\\n\", nregions, neval, fail);\n    // for(int comp = 0; comp < cbp.NCOMP; comp++ )\n    //   printf(\"CUHRE RESULT:\\t%.8f +- %.8f\\tp = %.3f\\n\",\n    // \t     (double)integral[comp], (double)error[comp], (double)prob[comp]);      \n      \n    /* Extracting the integral results */\n    for(int comp=0; comp<cbp.NCOMP; comp+=2){\n      int ope, elem;\n      std::tie(ope, elem) = comp_to_ope_elem(comp, NSUBL*NSUBL);\n      int g1 = elem / NSUBL;\n      int g2 = elem % NSUBL;\n      cx_double int_ope_elem(integral[comp], integral[comp+1]);\n      if ( ope == 0 ) {  /* Ppmk */\n\tchi0_pm(g1,g2) = int_ope_elem;\n      } else /* ope == 1 */ { /* Pzzk */\t      \n\tchi0_zz_u(g1,g2) = int_ope_elem;\n      }\n    }\n\n    chi0_pm /= 2; /* A factor (2*M_PI) cancels because of the scale change of the integration variables. */\n    chi0_zz_u /= 2;\n  } else { /* Integral for a finite-size system */\n    double k1 = 2. * M_PI / L;\n    for(int z=0; z < 2; z++){    \n      double kz = M_PI * z;\n      for(int x=-L/2; x < L/2; x++){    \n\tdouble kx = k1 * x;\n\tfor(int y=-L/2; y < L/2; y++){\n\t  double ky = k1 * y;\n\t  add_to_sus_mat4( ts, T, mu, chi0_pm, chi0_zz_u, kx, ky, kz, Pz, delta, omega );\t  \n\t}\n      }\n    }\n    \n    int n_units = L * L;  // Number of unit cells\n    chi0_pm /= (double)(n_units);\n    chi0_zz_u /= (double)(n_units);\n  }\n\n  /* Adding the contribution from the down spin */\n  arma::cx_mat chi0_zz_d(chi0_zz_u);\n  /* Assume NSUBL == 2. */  \n  if ( NSUBL == 2 ) {\n    chi0_zz_d.swap_rows( 0, 1 );\n    chi0_zz_d.swap_cols( 0, 1 );\n  } else {\n    std::cerr << \"NSUBL is not 2.\\n\";\n    std::exit(EXIT_FAILURE);\n  }\n  arma::cx_mat chi0_zz = chi0_zz_u + chi0_zz_d;\n  return std::make_tuple(chi0_pm, chi0_zz);\n}\n\nstd::tuple<cx_double, cx_double> calc_intensity_bilayer2(int L, hoppings_bilayer2& ts, double mu, double U, double T, double delta, CubaParam const& cbp, Polarization const& Pz, cx_double omega, bool continuous_k){\n  arma::cx_mat chi0_pm(NSUBL,NSUBL,arma::fill::zeros);\n  arma::cx_mat chi0_zz(NSUBL,NSUBL,arma::fill::zeros);\n\n  /* Calculating the bare response functions */\n  std::tie(chi0_pm, chi0_zz) = calc_bare_response_bilayer(L, ts, mu, U, T, delta, cbp, Pz, omega, continuous_k);\n  \n  /* RPA */\n  /* Transverse = < \\sigma^- \\sigma^+ >; Longitudinal (zz) = < \\sigma^z \\sigma^z > */\n  /* Note that 2 < \\sigma^- \\sigma^+ > = < \\sigma^z \\sigma^z > (U -> 0 for the SU(2) case) */  \n  arma::cx_mat denom_pm = arma::eye<arma::cx_mat>(NSUBL,NSUBL) - U * chi0_pm;\n  arma::cx_mat denom_zz = arma::eye<arma::cx_mat>(NSUBL,NSUBL) - 0.5 * U * chi0_zz;  \n  arma::cx_mat chi_pm = arma::inv(denom_pm) * chi0_pm;\n  arma::cx_mat chi_zz = arma::inv(denom_zz) * chi0_zz;\n  \n  // sigma-to-spin factor\n  cx_double chi_xy = 0.5 * arma::accu(chi_pm);\n  cx_double chi_z = 0.25 * arma::accu(chi_zz);  \n\n  // // for check\n  // std::cout << chi0_pm << std::endl;\n  // std::cout << chi_pm << std::endl;  \n  // std::cout << chi0_zz << std::endl;\n  // std::cout << chi_zz << std::endl;\n  \n  return std::make_tuple(chi_xy, chi_z);\n}\n", "meta": {"hexsha": "0dbd48ba43079adff48182535eead692968c82c4", "size": 8381, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/calc_intensity_bilayer.cpp", "max_stars_repo_name": "suwamaro/rpa", "max_stars_repo_head_hexsha": "fc9d37f03705334ee17b77de6ad2b8feab3cc7b0", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/calc_intensity_bilayer.cpp", "max_issues_repo_name": "suwamaro/rpa", "max_issues_repo_head_hexsha": "fc9d37f03705334ee17b77de6ad2b8feab3cc7b0", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/calc_intensity_bilayer.cpp", "max_forks_repo_name": "suwamaro/rpa", "max_forks_repo_head_hexsha": "fc9d37f03705334ee17b77de6ad2b8feab3cc7b0", "max_forks_repo_licenses": ["Apache-2.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.9208333333, "max_line_length": 229, "alphanum_fraction": 0.5908602792, "num_tokens": 2961, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6992544210587586, "lm_q2_score": 0.46879062662624377, "lm_q1q2_score": 0.3278039182193067}}
{"text": "#ifndef HIDDEN_MARKOV_MODEL\n#define HIDDEN_MARKOV_MODEL\n\n#include \"util/integer_range.hpp\"\n\n#include <boost/assert.hpp>\n#include <boost/math/constants/constants.hpp>\n\n#include <cmath>\n\n#include <limits>\n#include <vector>\n\nnamespace osrm\n{\nnamespace engine\n{\nnamespace map_matching\n{\n\nstatic const double log_2_pi = std::log(2. * boost::math::constants::pi<double>());\nstatic const double IMPOSSIBLE_LOG_PROB = -std::numeric_limits<double>::infinity();\nstatic const double MINIMAL_LOG_PROB = std::numeric_limits<double>::lowest();\nstatic const std::size_t INVALID_STATE = std::numeric_limits<std::size_t>::max();\n\n// closures to precompute log -> only simple floating point operations\nstruct EmissionLogProbability\n{\n    double sigma_z;\n    double log_sigma_z;\n\n    EmissionLogProbability(const double sigma_z) : sigma_z(sigma_z), log_sigma_z(std::log(sigma_z))\n    {\n    }\n\n    double operator()(const double distance) const\n    {\n        return -0.5 * (log_2_pi + (distance / sigma_z) * (distance / sigma_z)) - log_sigma_z;\n    }\n};\n\nstruct TransitionLogProbability\n{\n    double beta;\n    double log_beta;\n    TransitionLogProbability(const double beta) : beta(beta), log_beta(std::log(beta)) {}\n\n    double operator()(const double d_t) const { return -log_beta - d_t / beta; }\n};\n\ntemplate <class CandidateLists> struct HiddenMarkovModel\n{\n    std::vector<std::vector<double>> viterbi;\n    std::vector<std::vector<std::pair<unsigned, unsigned>>> parents;\n    std::vector<std::vector<float>> path_distances;\n    std::vector<std::vector<bool>> pruned;\n    std::vector<bool> breakage;\n\n    const CandidateLists &candidates_list;\n    const std::vector<std::vector<double>> &emission_log_probabilities;\n\n    HiddenMarkovModel(const CandidateLists &candidates_list,\n                      const std::vector<std::vector<double>> &emission_log_probabilities)\n        : breakage(candidates_list.size()), candidates_list(candidates_list),\n          emission_log_probabilities(emission_log_probabilities)\n    {\n        viterbi.resize(candidates_list.size());\n        parents.resize(candidates_list.size());\n        path_distances.resize(candidates_list.size());\n        pruned.resize(candidates_list.size());\n        breakage.resize(candidates_list.size());\n        for (const auto i : util::irange<std::size_t>(0UL, candidates_list.size()))\n        {\n            const auto &num_candidates = candidates_list[i].size();\n            // add empty vectors\n            if (num_candidates > 0)\n            {\n                viterbi[i].resize(num_candidates);\n                parents[i].resize(num_candidates);\n                path_distances[i].resize(num_candidates);\n                pruned[i].resize(num_candidates);\n            }\n        }\n\n        Clear(0);\n    }\n\n    void Clear(std::size_t initial_timestamp)\n    {\n        BOOST_ASSERT(viterbi.size() == parents.size() && parents.size() == path_distances.size() &&\n                     path_distances.size() == pruned.size() && pruned.size() == breakage.size());\n\n        for (const auto t : util::irange(initial_timestamp, viterbi.size()))\n        {\n            std::fill(viterbi[t].begin(), viterbi[t].end(), IMPOSSIBLE_LOG_PROB);\n            std::fill(parents[t].begin(), parents[t].end(), std::make_pair(0U, 0U));\n            std::fill(path_distances[t].begin(), path_distances[t].end(), 0.0);\n            std::fill(pruned[t].begin(), pruned[t].end(), true);\n        }\n        std::fill(breakage.begin() + initial_timestamp, breakage.end(), true);\n    }\n\n    std::size_t initialize(std::size_t initial_timestamp)\n    {\n        auto num_points = candidates_list.size();\n        do\n        {\n            BOOST_ASSERT(initial_timestamp < num_points);\n\n            for (const auto s : util::irange<std::size_t>(0UL, viterbi[initial_timestamp].size()))\n            {\n                viterbi[initial_timestamp][s] = emission_log_probabilities[initial_timestamp][s];\n                parents[initial_timestamp][s] = std::make_pair(initial_timestamp, s);\n                pruned[initial_timestamp][s] = viterbi[initial_timestamp][s] < MINIMAL_LOG_PROB;\n\n                breakage[initial_timestamp] =\n                    breakage[initial_timestamp] && pruned[initial_timestamp][s];\n            }\n\n            ++initial_timestamp;\n        } while (initial_timestamp < num_points && breakage[initial_timestamp - 1]);\n\n        if (initial_timestamp >= num_points)\n        {\n            return INVALID_STATE;\n        }\n\n        BOOST_ASSERT(initial_timestamp > 0);\n        --initial_timestamp;\n\n        BOOST_ASSERT(breakage[initial_timestamp] == false);\n\n        return initial_timestamp;\n    }\n};\n} // namespace map_matching\n} // namespace engine\n} // namespace osrm\n\n#endif // HIDDEN_MARKOV_MODEL\n", "meta": {"hexsha": "dcab98d10b8e4182f1d3eac410a0cc7b3e714e62", "size": 4729, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/engine/map_matching/hidden_markov_model.hpp", "max_stars_repo_name": "motis-project/osrm-backend", "max_stars_repo_head_hexsha": "9aa492376a664304d8209513230bb43258367108", "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/engine/map_matching/hidden_markov_model.hpp", "max_issues_repo_name": "motis-project/osrm-backend", "max_issues_repo_head_hexsha": "9aa492376a664304d8209513230bb43258367108", "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/engine/map_matching/hidden_markov_model.hpp", "max_forks_repo_name": "motis-project/osrm-backend", "max_forks_repo_head_hexsha": "9aa492376a664304d8209513230bb43258367108", "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.5390070922, "max_line_length": 99, "alphanum_fraction": 0.6451681117, "num_tokens": 1062, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.754914975839675, "lm_q2_score": 0.43398146480389854, "lm_q1q2_score": 0.32761910701730185}}
{"text": "/*\nauther: wanyouwen\ndate: 2018.6.24\n\n双目示例:\n双目相机app程序框架：\n\n1. 读取相机配置文件(内参数 畸变矫正参数 双目对齐变换矩阵) =======================\n   cv::FileStorage fsSettings(setting_filename, cv::FileStorage::READ);\n   fsSettings[\"LEFT.K\"] >> K_l;//内参数\n   fsSettings[\"LEFT.D\"] >> D_l;// 畸变矫正\n   fsSettings[\"LEFT.P\"] >> P_l;// P_l,P_r --左右相机在校准后坐标系中的投影矩阵 3×4\n   fsSettings[\"LEFT.R\"] >> R_l;// R_l,R_r --左右相机校准变换（旋转）矩阵  3×3\n2. 计算双目矫正映射矩阵========================================================\n   cv::Mat M1l,M2l,M1r,M2r;\n       cv::initUndistortRectifyMap(K_l,D_l,R_l,P_l.rowRange(0,3).colRange(0,3),cv::Size(cols_l,rows_l),CV_32F,M1l,M2l);\n       cv::initUndistortRectifyMap(K_r,D_r,R_r,P_r.rowRange(0,3).colRange(0,3),cv::Size(cols_r,rows_r),CV_32F,M1r,M2r);\n3. 创建双目系统=============================================================== \n   ORB_SLAM2::System SLAM(vocabulary_filepath, setting_filename, ORB_SLAM2::System::STEREO, true);\n4. 从双目设备捕获图像,设置分辨率捕获图像========================================\n   cv::VideoCapture CapAll(deviceid); //打开相机设备 \n   //设置分辨率   1280*480  分成两张 640*480  × 2 左右相机\n       CapAll.set(CV_CAP_PROP_FRAME_WIDTH,1280);  \n       CapAll.set(CV_CAP_PROP_FRAME_HEIGHT, 480); \n    5. 获取左右相机图像===========================================================\n   CapAll.read(src_img);\n   imLeft  = src_img(cv::Range(0, 480), cv::Range(0, 640));   \n       imRight = src_img(cv::Range(0, 480), cv::Range(640, 1280));   \n6. 使用2步获取的双目矫正映射矩阵 矫正 左右相机图像==============================\n   cv::remap(imLeft,imLeftRect,M1l,M2l,cv::INTER_LINEAR);\n       cv::remap(imRight,imRightRect,M1r,M2r,cv::INTER_LINEAR);\n7. 记录时间戳 time ，并计时===================================================\n\t#ifdef COMPILEDWITHC11\n\t   std::chrono::steady_clock::time_point    t1 = std::chrono::steady_clock::now();\n\t#else\n\t   std::chrono::monotonic_clock::time_point t1 = std::chrono::monotonic_clock::now();\n\t#endif\n    8. 把左右图像和时间戳 传给 SLAM系统===========================================\n    SLAM.TrackStereo(imLeftRect, imRightRect, time);\n9. 计时结束，计算时间差，处理时间============================================= \n10.循环执行 5-9步===========================================================\n11.结束，关闭slam系统，关闭所有线程===========================================   \n12.保存相机轨迹============================================================== \n\n*/\n#include<iostream>\n#include<algorithm>\n#include<fstream>\n#include<iomanip>\n#include<chrono>//chrono是一个time library, 源于boost，现在已经是C++标准。\n\n#include<opencv2/core/core.hpp>\n#include<System.h>\n\nusing namespace std;\nusing namespace cv;\n\n#include <boost/format.hpp>  // 格式化字符串 for formating strings 处理图像文件格式\n#include <boost/thread/thread.hpp>\n\nstatic void print_help()\n{\n    printf(\"\\n orbslam2 stereo test : \\n\");//生成视差和点云图\n    printf(\"\\n Usage: my_stereo [-v=<path_to_vocabulary>] [-s=<path_to_settings>]\\n\"\n           \"\\n [--d=<camera_id>] \\n\");\n}\n\n\nint main(int argc, char **argv)\n{\n    //std::uint32_t timestamp;\n    double time=0.0, ttrack=0;\n\n    //vector<IMUData> imudatas;\n    std::string setting_filename = \"\";    //配置文件\n    std::string vocabulary_filepath = \"\"; //关键帧数据库 词典 重定位  \n    int deviceid = 1;                     //相机设备id\n    cv::CommandLineParser parser(argc, argv,\n        \"{help h||}{d|1|}{v|../../Vocabulary/ORBvoc.bin|}{s|my_stereo.yaml|}\");\n//=======打印帮助信息============\n    if(parser.has(\"help\"))\n    {\n        print_help();\n        return 0;\n    }\n    if( parser.has(\"d\") )\n        deviceid = parser.get<int>(\"d\");//相机设备id\n    if( parser.has(\"s\") )\n        setting_filename = parser.get<std::string>(\"s\");//\n    if( parser.has(\"v\") )\n        vocabulary_filepath = parser.get<std::string>(\"v\");//\n    if (!parser.check()) {\n        parser.printErrors();\n        return 1;\n    }\n//if(setting_filename.empty())//{\n\n //1.  读取相机配置文件(内参数 畸变矫正参数 双目对齐变换矩阵 ) ====================\n    cv::FileStorage fsSettings(setting_filename, cv::FileStorage::READ);\n    if(!fsSettings.isOpened())\n    {\n        cerr << \"ERROR: Wrong path to setting file : \" << setting_filename << endl;\n        return -1;\n    }\n\n    cv::Mat K_l, K_r, D_l, D_r, P_l, P_r, R_l, R_r;\n    fsSettings[\"LEFT.K\"] >> K_l;//内参数 \n    if(K_l.empty())  cout << \"K_l missing \"<<endl;\n    fsSettings[\"RIGHT.K\"] >> K_r;//\n    if(K_r.empty()) cout << \"K_r missing \"<<endl;\n    fsSettings[\"LEFT.D\"] >> D_l;// 畸变矫正\n    if(D_l.empty()) cout << \"D_l missing \"<<endl;\n    fsSettings[\"RIGHT.D\"] >> D_r;\n    if(D_r.empty()) cout << \"D_r missing \"<<endl;\n\n    fsSettings[\"LEFT.P\"] >> P_l;// P_l,P_r --左右相机在校准后坐标系中的投影矩阵 3×4\n    if(P_l.empty()) cout << \"P_l missing \"<<endl;\n    fsSettings[\"RIGHT.P\"] >> P_r;\n    if(K_r.empty()) cout << \"P_r missing \"<<endl;\n\n    fsSettings[\"LEFT.R\"] >> R_l;// R_l,R_r --左右相机校准变换（旋转）矩阵  3×3\n    if(R_l.empty()) cout << \"R_l missing \"<<endl;\n    fsSettings[\"RIGHT.R\"] >> R_r;\n    if(R_r.empty()) cout << \"R_r missing \"<<endl;\n\n    int rows_l = fsSettings[\"LEFT.height\"];\n    int cols_l = fsSettings[\"LEFT.width\"];\n    int rows_r = fsSettings[\"RIGHT.height\"];\n    int cols_r = fsSettings[\"RIGHT.width\"];\n\n    if(K_l.empty() || K_r.empty() || P_l.empty() || P_r.empty() || R_l.empty() || R_r.empty() || D_l.empty() || D_r.empty() || rows_l==0 || rows_r==0 || cols_l==0 || cols_r==0)\n    {\n        cerr << \"ERROR: Calibration parameters to rectify stereo are missing!\" << endl;\n        return -1;\n    }\n//}\n\n//外参数\n// Mat R, T, R1, P1, R2, P2;\n//fs[\"R\"] >> R;\n//fs[\"T\"] >> T;\t\n//图像矫正摆正 映射计算  \n//stereoRectify( K_l, D_l, K_r, D_r, cv::Size(cols_l,rows_l), R, T, R1, R2, P1, P2, Q, CALIB_ZERO_DISPARITY, -1, cv::Size(cols_l,rows_l), &roi1, &roi2 );\n\n// 2. 计算双目矫正映射矩阵================================================\n    cv::Mat M1l,M2l,M1r,M2r;\n    cv::initUndistortRectifyMap(K_l,D_l,R_l,P_l.rowRange(0,3).colRange(0,3),cv::Size(cols_l,rows_l),CV_32F,M1l,M2l);\n    cv::initUndistortRectifyMap(K_r,D_r,R_r,P_r.rowRange(0,3).colRange(0,3),cv::Size(cols_r,rows_r),CV_32F,M1r,M2r);\n\n// 3. 创建双目系统 ORB_SLAM2::System======================================\n    ORB_SLAM2::System SLAM(vocabulary_filepath, setting_filename, ORB_SLAM2::System::STEREO, true);\n\n\n    cout << endl << \"-------\" << endl;\n    cout << \"Start processing sequence ...\" << endl;\n// 4. 从双目设备捕获图像设置分辨率捕获图像 ===================================================\n    cv::VideoCapture CapAll(deviceid); //打开相机设备 \n    if( !CapAll.isOpened() ) \n    { \n       printf(\"打开摄像头失败\\r\\n\");\n       printf(\"再试一次\\r\\n\");\n       //sleep(1);//延时1秒 \n       cv::VideoCapture CapAll(1); //打开相机设备 \n       if( !CapAll.isOpened() ) { \n         printf(\"打开摄像头失败\\r\\n\");\n\t printf(\"再试一次..\\r\\n\");\n          //sleep(1);//延时1秒 \n          cv::VideoCapture CapAll(1); //打开相机设备 \n          if( !CapAll.isOpened() ) { \n\t  printf(\"打开摄像头失败\\r\\n\");\n\t   return -1;\n         }\n       }\n   }\n    //设置分辨率   1280*480  分成两张 640*480  × 2 左右相机\n    CapAll.set(CV_CAP_PROP_FRAME_WIDTH,1280);  \n    CapAll.set(CV_CAP_PROP_FRAME_HEIGHT, 480);  \n\n    cv::Mat src_img, imLeft, imRight, imLeftRect, imRightRect;\n\n    while(CapAll.read(src_img)) \n     {\n// 5. 获取左右相机图像====================================================\n        imLeft  = src_img(cv::Range(0, 480), cv::Range(0, 640));   \n        imRight = src_img(cv::Range(0, 480), cv::Range(640, 1280)); \n\n// 6. 矫正左右相机图像====================================================\n        cv::remap(imLeft,imLeftRect,M1l,M2l,cv::INTER_LINEAR);\n        cv::remap(imRight,imRightRect,M1r,M2r,cv::INTER_LINEAR);\n\n// 7. 记录时间戳 tframe ，并计时==========================================\n#ifdef COMPILEDWITHC11\n        std::chrono::steady_clock::time_point        t1 = std::chrono::steady_clock::now();\n#else\n        std::chrono::monotonic_clock::time_point t1 = std::chrono::monotonic_clock::now();\n#endif\t\n        time += ttrack ;\n\n// 8. 把左右图像和时间戳 传给 SLAM系统====================================\n        SLAM.TrackStereo(imLeftRect, imRightRect, time);\n\n// 9. 计时结束，计算时间差，处理时间======================================\t\n#ifdef COMPILEDWITHC11\n        std::chrono::steady_clock::time_point        t2 = std::chrono::steady_clock::now();\n#else\n        std::chrono::monotonic_clock::time_point t2 = std::chrono::monotonic_clock::now();\n#endif\n\n        ttrack= std::chrono::duration_cast<std::chrono::duration<double> >(t2 - t1).count();\n\t\n  //  if(ttrack<T)\n//   usleep((T-ttrack)*1e6); //sleep\n\t\n    }\n\n// 10. 结束，关闭slam系统，关闭所有线程===================================\n    SLAM.Shutdown();\n// 11. 保存相机轨迹======================================================\n    SLAM.SaveTrajectoryKITTI(\"myCameraTrajectory.txt\");\n\n    CapAll.release();\n    cv::destroyAllWindows();\n    return 0;\n}\n", "meta": {"hexsha": "1439c68b70e1d11dda42e8a30b10cd6e6dafe7ec", "size": 8446, "ext": "cc", "lang": "C++", "max_stars_repo_path": "Examples/my_stereo.cc", "max_stars_repo_name": "zhangxin0518/oRB-SLAM2", "max_stars_repo_head_hexsha": "b8392c1c5f415fc9953bddfb2611465ac84a54be", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-08-13T06:30:01.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-13T06:30:01.000Z", "max_issues_repo_path": "Examples/my_stereo.cc", "max_issues_repo_name": "zhangxin0518/oRB-SLAM2", "max_issues_repo_head_hexsha": "b8392c1c5f415fc9953bddfb2611465ac84a54be", "max_issues_repo_licenses": ["MIT"], "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/my_stereo.cc", "max_forks_repo_name": "zhangxin0518/oRB-SLAM2", "max_forks_repo_head_hexsha": "b8392c1c5f415fc9953bddfb2611465ac84a54be", "max_forks_repo_licenses": ["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.5377777778, "max_line_length": 176, "alphanum_fraction": 0.5448733128, "num_tokens": 2908, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6076631698328916, "lm_q2_score": 0.5389832206876841, "lm_q1q2_score": 0.3275202523698191}}
{"text": "#include <iostream>\n#include <string>\n#include <fstream>\n#include <algorithm>\n#include <vector>\n#include <iterator>\n#include <numeric>\n#include <memory>\n#include <chrono>\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 \"Solution.hpp\"\n#include \"Helper.hpp\"\n\nusing namespace std;\nnamespace ublas = boost::numeric::ublas;\n\n/*********************************************************************************/\n/*                   CONSTRUCTOR AND MEMBER FUNCTIONS OF VNS                     */\n/*********************************************************************************/\n\nVNS::VNS(const string &directory,\n\tconst unsigned int &kMin,\n\tconst unsigned int &kMax,\n\tconst unsigned int &tMax,\n\tconst unsigned int &shaking_mode,\n\tconst unsigned int &local_search_mode,\n\tconst unsigned int &update_xij_mode,\n\tconst unsigned int &initial_mode,\n\tconst unsigned int &time):\n\t// Init VNS and TestSet\n\t\tTestSet(directory), m_k(kMin - 1), m_kMax(kMax), m_kMin(kMin), m_tMax(tMax),\n\t\tm_shaking_mode(shaking_mode), m_local_search_mode(local_search_mode), m_update_xij_mode(update_xij_mode),\n\t\tm_incumbent_solution(m_locationNumber, 1), m_perturbed_solution(m_locationNumber, 1),\n\t\tm_fx(DBL_MAX), m_best_fx(DBL_MAX), m_sum_dj(accumulate(m_dj.begin(), m_dj.end(), 0.0)), \n\t\tm_initial_mode(initial_mode), m_maxNH(pow(m_kMax, 2)),m_timeMax(time), m_rMax(0), \n\t\tm_neighborhood_k(m_maxNH, vector<bool>(m_locationNumber, 1)), m_flow_tpl(0), m_initial_fx(DBL_MAX)\n{\n}\n\nvoid VNS::initialSolution(\n\tvector <bool> &incumbent_solution,\n\tconst vector<double> &bi,\n\tconst vector<double> &fi,\n\tconst vector<double> &dj,\n\tublas::matrix<double> &cij,\n\tconst double &sum_dj,\n\tconst unsigned int &init_mode)\n{\n\tif (init_mode == 0)\n\t\tinitialGreedy(incumbent_solution, bi, fi, dj, cij, sum_dj);\n\telse\n\t\tinitialRVNS(incumbent_solution, bi,  dj, cij);\n\n\tif (m_best_fx <= m_fx)\n\t\tm_initial_fx = m_best_fx;\n\telse\n\t\tm_initial_fx = m_fx;\n}\n\n// Move or not\nvoid VNS::neighborhoodChange(\n\tvector<bool> &incumbent_solution,\n\tconst vector<bool> &local_solution,\n\tunsigned int &k,\n\tconst double &fx,\n\tdouble &best_fx,\n\tconst double &kMin)\n{\n\tif (fx < best_fx)\n\t{\n\t\tincumbent_solution = local_solution;\n\t\tk = kMin - 1;\n\t\tbest_fx = fx;\n\t}\n\telse\n\t\tk++;\n}\n\n// Creates Perturbed Solution S'\nvector<bool> VNS::shaking(\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\tconst unsigned int &shaking_mode)\n{\n\tif (shaking_mode == 0)\n\t\treturn shakingKOperations(incumbent_solution, bi, m_dj, m_cij, m_k, fx);\n\telse if (shaking_mode == 1)\n\t\treturn shakingKMaxOperations(incumbent_solution, bi, m_dj, m_cij, m_k, fx);\n\telse if (shaking_mode == 2)\n\t\treturn shakingAssignments(incumbent_solution, bi, m_dj, m_cij, m_k, fx);\n\telse\n\t\treturn shakingCosts(incumbent_solution, bi, m_dj, m_cij, m_k, fx);\n}\n\n// Getter f(x)\nconst double VNS::getFx() const\n{\n\treturn m_best_fx;\n}\n\n// Getter initial f(x)\nconst double VNS::getInitialFx() const\n{\n\treturn m_initial_fx;\n}", "meta": {"hexsha": "2d82376e2cc8396ad43975b543e1bf38346cd25c", "size": 3114, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "VNS Implementierung/VNS Implementierung/VNS.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/VNS.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/VNS.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": 27.3157894737, "max_line_length": 107, "alphanum_fraction": 0.6865767502, "num_tokens": 870, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6076631698328916, "lm_q2_score": 0.5389832206876841, "lm_q1q2_score": 0.3275202523698191}}
{"text": "/* ----------------------------------------------------------------------------\r\n * Copyright 2018, Ross Hartley <m.ross.hartley@gmail.com>\r\n * All Rights Reserved\r\n * See LICENSE for the license information\r\n * -------------------------------------------------------------------------- */\r\n\r\n/**\r\n *  @file   kinematics.cpp\r\n *  @author Ross Hartley\r\n *  @brief  Example of invariant filtering for contact-aided inertial navigation\r\n *  @date   September 25, 2018\r\n **/\r\n\r\n#include <iostream>\r\n#include <fstream>\r\n#include <string>\r\n#include <cstdlib>\r\n#include <Eigen/Dense>\r\n#include <boost/algorithm/string.hpp>\r\n#include <vector>\r\n#include \"InEKF.h\"\r\n\r\n#define DT_MIN 1e-6\r\n#define DT_MAX 1\r\n\r\nusing namespace std;\r\nusing namespace inekf;\r\n\r\ndouble stod98(const std::string &s) {\r\n    return atof(s.c_str());\r\n}\r\n\r\nint stoi98(const std::string &s) {\r\n    return atoi(s.c_str());\r\n}\r\n\r\nint main() {\r\n    //  ---- Initialize invariant extended Kalman filter ----- //\r\n    RobotState initial_state; \r\n\r\n    // Initialize state mean\r\n    Eigen::Matrix3d R0;\r\n    Eigen::Vector3d v0, p0, bg0, ba0;\r\n    R0 << 1, 0, 0, // initial orientation\r\n          0, -1, 0, // IMU frame is rotated 90deg about the x-axis\r\n          0, 0, -1;\r\n    v0 << 0,0,0; // initial velocity\r\n    p0 << 0,0,0; // initial position\r\n    bg0 << 0,0,0; // initial gyroscope bias\r\n    ba0 << 0,0,0; // initial accelerometer bias\r\n    initial_state.setRotation(R0);\r\n    initial_state.setVelocity(v0);\r\n    initial_state.setPosition(p0);\r\n    initial_state.setGyroscopeBias(bg0);\r\n    initial_state.setAccelerometerBias(ba0);\r\n\r\n    // Initialize state covariance\r\n    NoiseParams noise_params;\r\n    noise_params.setGyroscopeNoise(0.01);\r\n    noise_params.setAccelerometerNoise(0.1);\r\n    noise_params.setGyroscopeBiasNoise(0.00001);\r\n    noise_params.setAccelerometerBiasNoise(0.0001);\r\n    noise_params.setContactNoise(0.01);\r\n\r\n    // Initialize filter\r\n    InEKF filter(initial_state, noise_params);\r\n    cout << \"Noise parameters are initialized to: \\n\";\r\n    cout << filter.getNoiseParams() << endl;\r\n    cout << \"Robot's state is initialized to: \\n\";\r\n    cout << filter.getState() << endl;\r\n\r\n    // Open data file\r\n    ifstream infile(\"../src/data/imu_kinematic_measurements.txt\");\r\n    string line;\r\n    Eigen::Matrix<double,6,1> imu_measurement = Eigen::Matrix<double,6,1>::Zero();\r\n    Eigen::Matrix<double,6,1> imu_measurement_prev = Eigen::Matrix<double,6,1>::Zero();\r\n    double t = 0;\r\n    double t_prev = 0;\r\n\r\n    // ---- Loop through data file and read in measurements line by line ---- //\r\n    while (getline(infile, line)){\r\n        vector<string> measurement;\r\n        boost::split(measurement,line,boost::is_any_of(\" \"));\r\n        // // Handle measurements\r\n        if (measurement[0].compare(\"IMU\")==0){\r\n            cout << \"Received IMU Data, propagating state\\n\";\r\n            assert((measurement.size()-2) == 6);\r\n            t = atof(measurement[1].c_str()); \r\n            // Read in IMU data\r\n            imu_measurement << stod98(measurement[2]), \r\n                               stod98(measurement[3]), \r\n                               stod98(measurement[4]),\r\n                               stod98(measurement[5]),\r\n                               stod98(measurement[6]),\r\n                               stod98(measurement[7]);\r\n\r\n            // Propagate using IMU data\r\n            double dt = t - t_prev;\r\n            if (dt > DT_MIN && dt < DT_MAX) {\r\n                filter.Propagate(imu_measurement_prev, dt);\r\n            }\r\n\r\n        }\r\n        else if (measurement[0].compare(\"CONTACT\")==0){\r\n            cout << \"Received CONTACT Data, setting filter's contact state\\n\";\r\n            assert((measurement.size()-2)%2 == 0);\r\n            vector<pair<int,bool> > contacts;\r\n            int id;\r\n            bool indicator;\r\n            t = stod98(measurement[1]); \r\n            // Read in contact data\r\n            for (int i=2; i<measurement.size(); i+=2) {\r\n                id = stoi98(measurement[i]);\r\n                indicator = bool(stod98(measurement[i+1]));\r\n                contacts.push_back(pair<int,bool> (id, indicator));\r\n            }       \r\n            // Set filter's contact state\r\n            filter.setContacts(contacts);\r\n        }\r\n        else if (measurement[0].compare(\"KINEMATIC\")==0){\r\n            cout << \"Received KINEMATIC observation, correcting state\\n\";  \r\n            assert((measurement.size()-2)%44 == 0);\r\n            int id;\r\n            Eigen::Quaternion<double> q;\r\n            Eigen::Vector3d p;\r\n            Eigen::Matrix4d pose = Eigen::Matrix4d::Identity();\r\n            Eigen::Matrix<double,6,6> covariance;\r\n            vectorKinematics measured_kinematics;\r\n            t = stod98(measurement[1]); \r\n            // Read in kinematic data\r\n            for (int i=2; i<measurement.size(); i+=44) {\r\n                id = stoi98(measurement[i]); \r\n                q = Eigen::Quaternion<double> (stod98(measurement[i+1]),stod98(measurement[i+2]),stod98(measurement[i+3]),stod98(measurement[i+4]));\r\n                q.normalize();\r\n                p << stod98(measurement[i+5]),stod98(measurement[i+6]),stod98(measurement[i+7]);\r\n                pose.block<3,3>(0,0) = q.toRotationMatrix();\r\n                pose.block<3,1>(0,3) = p;\r\n                for (int j=0; j<6; ++j) {\r\n                    for (int k=0; k<6; ++k) {\r\n                        covariance(j,k) = stod98(measurement[i+8 + j*6+k]);\r\n                    }\r\n                }\r\n                Kinematics frame(id, pose, covariance);\r\n                measured_kinematics.push_back(frame);\r\n            }\r\n            // Correct state using kinematic measurements\r\n            filter.CorrectKinematics(measured_kinematics);\r\n        }\r\n\r\n        // Store previous timestamp\r\n        t_prev = t;\r\n        imu_measurement_prev = imu_measurement;\r\n    }\r\n\r\n    // Print final state\r\n    cout << filter.getState() << endl;\r\n    return 0;\r\n}\r\n", "meta": {"hexsha": "c97124ff8b9548b4416d4a0dc8fa3074c1e1b848", "size": 5954, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/examples/kinematics.cpp", "max_stars_repo_name": "Woo12138/invariant-ekf", "max_stars_repo_head_hexsha": "ef16e8a1df72f9272111a488880e3fe9d161f59f", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 190.0, "max_stars_repo_stars_event_min_datetime": "2018-11-15T15:11:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T08:24:22.000Z", "max_issues_repo_path": "src/examples/kinematics.cpp", "max_issues_repo_name": "Woo12138/invariant-ekf", "max_issues_repo_head_hexsha": "ef16e8a1df72f9272111a488880e3fe9d161f59f", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2018-10-05T20:29:57.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-12T06:37:15.000Z", "max_forks_repo_path": "src/examples/kinematics.cpp", "max_forks_repo_name": "Woo12138/invariant-ekf", "max_forks_repo_head_hexsha": "ef16e8a1df72f9272111a488880e3fe9d161f59f", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 56.0, "max_forks_repo_forks_event_min_datetime": "2018-09-28T20:39:56.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-13T16:16:46.000Z", "avg_line_length": 37.4465408805, "max_line_length": 149, "alphanum_fraction": 0.5403090359, "num_tokens": 1417, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6076631698328916, "lm_q2_score": 0.5389832206876841, "lm_q1q2_score": 0.3275202523698191}}
{"text": "// This file is part of libigl, a simple c++ geometry processing library.\n//\n// Copyright (C) 2015 Alec Jacobson <alecjacobson@gmail.com>\n//\n// This Source Code Form is subject to the terms of the Mozilla Public License\n// v. 2.0. If a copy of the MPL was not distributed with this file, You can\n// obtain one at http://mozilla.org/MPL/2.0/.\n#include \"outer_hull_legacy.h\"\n#include \"extract_cells.h\"\n#include \"remesh_self_intersections.h\"\n#include \"assign.h\"\n#include \"../../remove_unreferenced.h\"\n\n#include <CGAL/AABB_tree.h>\n#include <CGAL/AABB_traits.h>\n#include <CGAL/AABB_triangle_primitive.h>\n#include <CGAL/intersections.h>\n#include <CGAL/Exact_predicates_exact_constructions_kernel.h>\n\n#include \"points_inside_component.h\"\n#include \"order_facets_around_edges.h\"\n#include \"outer_facet.h\"\n#include \"../../sortrows.h\"\n#include \"../../facet_components.h\"\n#include \"../../winding_number.h\"\n#include \"../../triangle_triangle_adjacency.h\"\n#include \"../../unique_edge_map.h\"\n#include \"../../barycenter.h\"\n#include \"../../per_face_normals.h\"\n#include \"../../sort_angles.h\"\n#include <Eigen/Geometry>\n#include <vector>\n#include <map>\n#include <queue>\n#include <iostream>\n#include <type_traits>\n#include <CGAL/number_utils.h>\n//#define IGL_OUTER_HULL_DEBUG\n\ntemplate <\n  typename DerivedV,\n  typename DerivedF,\n  typename DerivedG,\n  typename DerivedJ,\n  typename Derivedflip>\nIGL_INLINE void igl::copyleft::cgal::outer_hull_legacy(\n  const Eigen::PlainObjectBase<DerivedV> & V,\n  const Eigen::PlainObjectBase<DerivedF> & F,\n  Eigen::PlainObjectBase<DerivedG> & G,\n  Eigen::PlainObjectBase<DerivedJ> & J,\n  Eigen::PlainObjectBase<Derivedflip> & flip)\n{\n#ifdef IGL_OUTER_HULL_DEBUG\n  std::cerr << \"Extracting outer hull\" << std::endl;\n#endif\n  using namespace Eigen;\n  using namespace std;\n  typedef typename DerivedF::Index Index;\n  Matrix<Index,DerivedF::RowsAtCompileTime,1> C;\n  typedef Matrix<typename DerivedV::Scalar,Dynamic,DerivedV::ColsAtCompileTime> MatrixXV;\n  //typedef Matrix<typename DerivedF::Scalar,Dynamic,DerivedF::ColsAtCompileTime> MatrixXF;\n  typedef Matrix<typename DerivedG::Scalar,Dynamic,DerivedG::ColsAtCompileTime> MatrixXG;\n  typedef Matrix<typename DerivedJ::Scalar,Dynamic,DerivedJ::ColsAtCompileTime> MatrixXJ;\n  const Index m = F.rows();\n\n  // UNUSED:\n  //const auto & duplicate_simplex = [&F](const int f, const int g)->bool\n  //{\n  //  return\n  //    (F(f,0) == F(g,0) && F(f,1) == F(g,1) && F(f,2) == F(g,2)) ||\n  //    (F(f,1) == F(g,0) && F(f,2) == F(g,1) && F(f,0) == F(g,2)) ||\n  //    (F(f,2) == F(g,0) && F(f,0) == F(g,1) && F(f,1) == F(g,2)) ||\n  //    (F(f,0) == F(g,2) && F(f,1) == F(g,1) && F(f,2) == F(g,0)) ||\n  //    (F(f,1) == F(g,2) && F(f,2) == F(g,1) && F(f,0) == F(g,0)) ||\n  //    (F(f,2) == F(g,2) && F(f,0) == F(g,1) && F(f,1) == F(g,0));\n  //};\n\n#ifdef IGL_OUTER_HULL_DEBUG\n  cout<<\"outer hull...\"<<endl;\n#endif\n\n#ifdef IGL_OUTER_HULL_DEBUG\n  cout<<\"edge map...\"<<endl;\n#endif\n  typedef Matrix<typename DerivedF::Scalar,Dynamic,2> MatrixX2I;\n  typedef Matrix<typename DerivedF::Index,Dynamic,1> VectorXI;\n  //typedef Matrix<typename DerivedV::Scalar, 3, 1> Vector3F;\n  MatrixX2I E,uE;\n  VectorXI EMAP;\n  vector<vector<typename DerivedF::Index> > uE2E;\n  unique_edge_map(F,E,uE,EMAP,uE2E);\n#ifdef IGL_OUTER_HULL_DEBUG\n  for (size_t ui=0; ui<uE.rows(); ui++) {\n      std::cout << ui << \": \" << uE2E[ui].size() << \" -- (\";\n      for (size_t i=0; i<uE2E[ui].size(); i++) {\n          std::cout << uE2E[ui][i] << \", \";\n      }\n      std::cout << \")\" << std::endl;\n  }\n#endif\n\n  std::vector<std::vector<typename DerivedF::Index> > uE2oE;\n  std::vector<std::vector<bool> > uE2C;\n  order_facets_around_edges(V, F, uE, uE2E, uE2oE, uE2C);\n  uE2E = uE2oE;\n  VectorXI diIM(3*m);\n  for (auto ue : uE2E) {\n      for (size_t i=0; i<ue.size(); i++) {\n          auto fe = ue[i];\n          diIM[fe] = i;\n      }\n  }\n\n  vector<vector<vector<Index > > > TT,_1;\n  triangle_triangle_adjacency(E,EMAP,uE2E,false,TT,_1);\n  VectorXI counts;\n#ifdef IGL_OUTER_HULL_DEBUG\n  cout<<\"facet components...\"<<endl;\n#endif\n  facet_components(TT,C,counts);\n  assert(C.maxCoeff()+1 == counts.rows());\n  const size_t ncc = counts.rows();\n  G.resize(0,F.cols());\n  J.resize(0,1);\n  flip.setConstant(m,1,false);\n\n#ifdef IGL_OUTER_HULL_DEBUG\n  cout<<\"reindex...\"<<endl;\n#endif\n  // H contains list of faces on outer hull;\n  vector<bool> FH(m,false);\n  vector<bool> EH(3*m,false);\n  vector<MatrixXG> vG(ncc);\n  vector<MatrixXJ> vJ(ncc);\n  vector<MatrixXJ> vIM(ncc);\n  //size_t face_count = 0;\n  for(size_t id = 0;id<ncc;id++)\n  {\n    vIM[id].resize(counts[id],1);\n  }\n  // current index into each IM\n  vector<size_t> g(ncc,0);\n  // place order of each face in its respective component\n  for(Index f = 0;f<m;f++)\n  {\n    vIM[C(f)](g[C(f)]++) = f;\n  }\n\n#ifdef IGL_OUTER_HULL_DEBUG\n  cout<<\"barycenters...\"<<endl;\n#endif\n  // assumes that \"resolve\" has handled any coplanar cases correctly and nearly\n  // coplanar cases can be sorted based on barycenter.\n  MatrixXV BC;\n  barycenter(V,F,BC);\n\n#ifdef IGL_OUTER_HULL_DEBUG\n  cout<<\"loop over CCs (=\"<<ncc<<\")...\"<<endl;\n#endif\n  for(Index id = 0;id<(Index)ncc;id++)\n  {\n    auto & IM = vIM[id];\n    // starting face that's guaranteed to be on the outer hull and in this\n    // component\n    int f;\n    bool f_flip;\n#ifdef IGL_OUTER_HULL_DEBUG\n  cout<<\"outer facet...\"<<endl;\n#endif\n  igl::copyleft::cgal::outer_facet(V,F,IM,f,f_flip);\n#ifdef IGL_OUTER_HULL_DEBUG\n  cout<<\"outer facet: \"<<f<<endl;\n  //cout << V.row(F(f, 0)) << std::endl;\n  //cout << V.row(F(f, 1)) << std::endl;\n  //cout << V.row(F(f, 2)) << std::endl;\n#endif\n    int FHcount = 1;\n    FH[f] = true;\n    // Q contains list of face edges to continue traversing upong\n    queue<int> Q;\n    Q.push(f+0*m);\n    Q.push(f+1*m);\n    Q.push(f+2*m);\n    flip(f) = f_flip;\n    //std::cout << \"face \" << face_count++ << \": \" << f << std::endl;\n    //std::cout << \"f \" << F.row(f).array()+1 << std::endl;\n    //cout<<\"flip(\"<<f<<\") = \"<<(flip(f)?\"true\":\"false\")<<endl;\n#ifdef IGL_OUTER_HULL_DEBUG\n  cout<<\"BFS...\"<<endl;\n#endif\n    while(!Q.empty())\n    {\n      // face-edge\n      const int e = Q.front();\n      Q.pop();\n      // face\n      const int f = e%m;\n      // corner\n      const int c = e/m;\n#ifdef IGL_OUTER_HULL_DEBUG\n      std::cout << \"edge: \" << e << \", ue: \" << EMAP(e) << std::endl;\n      std::cout << \"face: \" << f << std::endl;\n      std::cout << \"corner: \" << c << std::endl;\n      std::cout << \"consistent: \" << uE2C[EMAP(e)][diIM[e]] << std::endl;\n#endif\n      // Should never see edge again...\n      if(EH[e] == true)\n      {\n        continue;\n      }\n      EH[e] = true;\n      // source of edge according to f\n      const int fs = flip(f)?F(f,(c+2)%3):F(f,(c+1)%3);\n      // destination of edge according to f\n      const int fd = flip(f)?F(f,(c+1)%3):F(f,(c+2)%3);\n      // edge valence\n      const size_t val = uE2E[EMAP(e)].size();\n#ifdef IGL_OUTER_HULL_DEBUG\n      //std::cout << \"vd: \" << V.row(fd) << std::endl;\n      //std::cout << \"vs: \" << V.row(fs) << std::endl;\n      //std::cout << \"edge: \" << V.row(fd) - V.row(fs) << std::endl;\n      for (size_t i=0; i<val; i++) {\n          if (i == diIM(e)) {\n              std::cout << \"* \";\n          } else {\n              std::cout << \"  \";\n          }\n          std::cout << i << \": \"\n              << \" (e: \" << uE2E[EMAP(e)][i] << \", f: \"\n              << uE2E[EMAP(e)][i] % m * (uE2C[EMAP(e)][i] ? 1:-1) << \")\" << std::endl;\n      }\n#endif\n\n      // is edge consistent with edge of face used for sorting\n      const int e_cons = (uE2C[EMAP(e)][diIM(e)] ? 1: -1);\n      int nfei = -1;\n      // Loop once around trying to find suitable next face\n      for(size_t step = 1; step<val+2;step++)\n      {\n        const int nfei_new = (diIM(e) + 2*val + e_cons*step*(flip(f)?-1:1))%val;\n        const int nf = uE2E[EMAP(e)][nfei_new] % m;\n        {\n#ifdef IGL_OUTER_HULL_DEBUG\n        //cout<<\"Next facet: \"<<(f+1)<<\" --> \"<<(nf+1)<<\", |\"<<\n        //  di[EMAP(e)][diIM(e)]<<\" - \"<<di[EMAP(e)][nfei_new]<<\"| = \"<<\n        //    abs(di[EMAP(e)][diIM(e)] - di[EMAP(e)][nfei_new])\n        //    <<endl;\n#endif\n\n\n\n          // Only use this face if not already seen\n          if(!FH[nf])\n          {\n            nfei = nfei_new;\n          //} else {\n          //    std::cout << \"skipping face \" << nfei_new << \" because it is seen before\"\n          //        << std::endl;\n          }\n          break;\n        //} else {\n        //    std::cout << di[EMAP(e)][diIM(e)].transpose() << std::endl;\n        //    std::cout << di[EMAP(e)][diIM(nfei_new)].transpose() << std::endl;\n        //    std::cout << \"skipping face \" << nfei_new << \" with identical dihedral angle\"\n        //        << std::endl;\n        }\n//#ifdef IGL_OUTER_HULL_DEBUG\n//        cout<<\"Skipping co-planar facet: \"<<(f+1)<<\" --> \"<<(nf+1)<<endl;\n//#endif\n      }\n\n      int max_ne = -1;\n      if(nfei >= 0)\n      {\n        max_ne = uE2E[EMAP(e)][nfei];\n      }\n\n      if(max_ne>=0)\n      {\n        // face of neighbor\n        const int nf = max_ne%m;\n#ifdef IGL_OUTER_HULL_DEBUG\n        if(!FH[nf])\n        {\n          // first time seeing face\n          cout<<(f+1)<<\" --> \"<<(nf+1)<<endl;\n        }\n#endif\n        FH[nf] = true;\n        //std::cout << \"face \" << face_count++ << \": \" << nf << std::endl;\n        //std::cout << \"f \" << F.row(nf).array()+1 << std::endl;\n        FHcount++;\n        // corner of neighbor\n        const int nc = max_ne/m;\n        const int nd = F(nf,(nc+2)%3);\n        const bool cons = (flip(f)?fd:fs) == nd;\n        flip(nf) = (cons ? flip(f) : !flip(f));\n        //cout<<\"flip(\"<<nf<<\") = \"<<(flip(nf)?\"true\":\"false\")<<endl;\n        const int ne1 = nf+((nc+1)%3)*m;\n        const int ne2 = nf+((nc+2)%3)*m;\n        if(!EH[ne1])\n        {\n          Q.push(ne1);\n        }\n        if(!EH[ne2])\n        {\n          Q.push(ne2);\n        }\n      }\n    }\n\n    {\n      vG[id].resize(FHcount,3);\n      vJ[id].resize(FHcount,1);\n      //nG += FHcount;\n      size_t h = 0;\n      assert(counts(id) == IM.rows());\n      for(int i = 0;i<counts(id);i++)\n      {\n        const size_t f = IM(i);\n        //if(f_flip)\n        //{\n        //  flip(f) = !flip(f);\n        //}\n        if(FH[f])\n        {\n          vG[id].row(h) = (flip(f)?F.row(f).reverse().eval():F.row(f));\n          vJ[id](h,0) = f;\n          h++;\n        }\n      }\n      assert((int)h == FHcount);\n    }\n  }\n\n  // Is A inside B? Assuming A and B are consistently oriented but closed and\n  // non-intersecting.\n  const auto & has_overlapping_bbox = [](\n    const Eigen::PlainObjectBase<DerivedV> & V,\n    const MatrixXG & A,\n    const MatrixXG & B)->bool\n  {\n    const auto & bounding_box = [](\n      const Eigen::PlainObjectBase<DerivedV> & V,\n      const MatrixXG & F)->\n        DerivedV\n    {\n      DerivedV BB(2,3);\n      BB<<\n         1e26,1e26,1e26,\n        -1e26,-1e26,-1e26;\n      const size_t m = F.rows();\n      for(size_t f = 0;f<m;f++)\n      {\n        for(size_t c = 0;c<3;c++)\n        {\n          const auto & vfc = V.row(F(f,c)).eval();\n          BB(0,0) = std::min(BB(0,0), vfc(0,0));\n          BB(0,1) = std::min(BB(0,1), vfc(0,1));\n          BB(0,2) = std::min(BB(0,2), vfc(0,2));\n          BB(1,0) = std::max(BB(1,0), vfc(0,0));\n          BB(1,1) = std::max(BB(1,1), vfc(0,1));\n          BB(1,2) = std::max(BB(1,2), vfc(0,2));\n        }\n      }\n      return BB;\n    };\n    // A lot of the time we're dealing with unrelated, distant components: cull\n    // them.\n    DerivedV ABB = bounding_box(V,A);\n    DerivedV BBB = bounding_box(V,B);\n    if( (BBB.row(0)-ABB.row(1)).maxCoeff()>0  ||\n        (ABB.row(0)-BBB.row(1)).maxCoeff()>0 )\n    {\n      // bounding boxes do not overlap\n      return false;\n    } else {\n      return true;\n    }\n  };\n\n  // Reject components which are completely inside other components\n  vector<bool> keep(ncc,true);\n  size_t nG = 0;\n  // This is O( ncc * ncc * m)\n  for(size_t id = 0;id<ncc;id++)\n  {\n    if (!keep[id]) continue;\n    std::vector<size_t> unresolved;\n    for(size_t oid = 0;oid<ncc;oid++)\n    {\n      if(id == oid || !keep[oid])\n      {\n        continue;\n      }\n      if (has_overlapping_bbox(V, vG[id], vG[oid])) {\n          unresolved.push_back(oid);\n      }\n    }\n    const size_t num_unresolved_components = unresolved.size();\n    DerivedV query_points(num_unresolved_components, 3);\n    for (size_t i=0; i<num_unresolved_components; i++) {\n        const size_t oid = unresolved[i];\n        DerivedF f = vG[oid].row(0);\n        query_points(i,0) = (V(f(0,0), 0) + V(f(0,1), 0) + V(f(0,2), 0))/3.0;\n        query_points(i,1) = (V(f(0,0), 1) + V(f(0,1), 1) + V(f(0,2), 1))/3.0;\n        query_points(i,2) = (V(f(0,0), 2) + V(f(0,1), 2) + V(f(0,2), 2))/3.0;\n    }\n    Eigen::VectorXi inside;\n    igl::copyleft::cgal::points_inside_component(V, vG[id], query_points, inside);\n    assert((size_t)inside.size() == num_unresolved_components);\n    for (size_t i=0; i<num_unresolved_components; i++) {\n        if (inside(i, 0)) {\n            const size_t oid = unresolved[i];\n            keep[oid] = false;\n        }\n    }\n  }\n  for (size_t id = 0; id<ncc; id++) {\n      if (keep[id]) {\n          nG += vJ[id].rows();\n      }\n  }\n\n  // collect G and J across components\n  G.resize(nG,3);\n  J.resize(nG,1);\n  {\n    size_t off = 0;\n    for(Index id = 0;id<(Index)ncc;id++)\n    {\n      if(keep[id])\n      {\n        assert(vG[id].rows() == vJ[id].rows());\n        G.block(off,0,vG[id].rows(),vG[id].cols()) = vG[id];\n        J.block(off,0,vJ[id].rows(),vJ[id].cols()) = vJ[id];\n        off += vG[id].rows();\n      }\n    }\n  }\n}\n\n\n#ifdef IGL_STATIC_LIBRARY\n// Explicit template instantiation\n// generated by autoexplicit.sh\ntemplate void igl::copyleft::cgal::outer_hull_legacy<Eigen::Matrix<CGAL::Epeck::FT, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, 1, 0, -1, 1>, Eigen::Matrix<int, -1, 1, 0, -1, 1> >(Eigen::PlainObjectBase<Eigen::Matrix<CGAL::Epeck::FT, -1, -1, 0, -1, -1> > const&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> > const&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> >&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, 1, 0, -1, 1> >&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, 1, 0, -1, 1> >&);\ntemplate void igl::copyleft::cgal::outer_hull_legacy< Eigen::Matrix<double, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, 1, 0, -1, 1>, Eigen::Matrix<int, -1, 1, 0, -1, 1> >(Eigen::PlainObjectBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> > const&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> > const&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> > &, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, 1, 0, -1, 1> > &, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, 1, 0, -1, 1> > &);\ntemplate void igl::copyleft::cgal::outer_hull_legacy<Eigen::Matrix<double, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, -1, 0, -1, -1> >(Eigen::PlainObjectBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> > const&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> > const&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> >&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> >&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> >&);\n#ifdef WIN32\n#endif\n#endif\n", "meta": {"hexsha": "7098c8d6a3770b3bede1f1fa8988b67adedf9952", "size": 15420, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cpp/depends/igl/headers/igl/copyleft/cgal/outer_hull_legacy.cpp", "max_stars_repo_name": "GitZHCODE/zspace_modules", "max_stars_repo_head_hexsha": "2264cb837d2f05184a51b7b453c7e24288e88ee1", "max_stars_repo_licenses": ["MIT"], "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/depends/igl/headers/igl/copyleft/cgal/outer_hull_legacy.cpp", "max_issues_repo_name": "GitZHCODE/zspace_modules", "max_issues_repo_head_hexsha": "2264cb837d2f05184a51b7b453c7e24288e88ee1", "max_issues_repo_licenses": ["MIT"], "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/depends/igl/headers/igl/copyleft/cgal/outer_hull_legacy.cpp", "max_forks_repo_name": "GitZHCODE/zspace_modules", "max_forks_repo_head_hexsha": "2264cb837d2f05184a51b7b453c7e24288e88ee1", "max_forks_repo_licenses": ["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.0397350993, "max_line_length": 602, "alphanum_fraction": 0.5507133593, "num_tokens": 5277, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6654105720171531, "lm_q2_score": 0.49218813572079556, "lm_q1q2_score": 0.3275071889300308}}
{"text": "/******************************************************************************\n\n  This source file is part of the Avogadro project.\n\n  Copyright 2010 Eric C. Brown\n\n  This source code is released under the New BSD License, (the \"License\").\n\n  Unless required by applicable law or agreed to in writing, software\n  distributed under the License is distributed on an \"AS IS\" BASIS,\n  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n  See the License for the specific language governing permissions and\n  limitations under the License.\n\n******************************************************************************/\n\n#include \"qtaimcriticalpointlocator.h\"\n#include \"qtaimwavefunction.h\"\n#include \"qtaimodeintegrator.h\"\n#include \"qtaimlsodaintegrator.h\"\n#include \"qtaimmathutilities.h\"\n\n#include <Eigen/Core>\n\n#include <QList>\n\n#include <QtConcurrentMap>\n\n#include <QTemporaryFile>\n#include <QFile>\n#include <QDataStream>\n#include <QDir>\n\n#include <QVariant>\n\n#include <QProgressDialog>\n#include <QFutureWatcher>\n#include <QFuture>\n\nusing namespace std;\nusing namespace Eigen;\n\n#define HUGE_REAL_NUMBER 1.e20\n#define SMALL_GRADIENT_NORM 1.e-4\n\nnamespace Avogadro {\nnamespace QtPlugins {\n\n  QList<QVariant> QTAIMLocateNuclearCriticalPoint( QList<QVariant> input  )\n  {\n    const QString fileName=input.at(0).toString();\n    const qint64 nucleus=input.at(1).toInt();\n    const QVector3D x0y0z0(\n        input.at(2).toReal(),\n        input.at(3).toReal(),\n        input.at(4).toReal()\n        );\n\n    QTAIMWavefunction wfn;\n    wfn.loadFromBinaryFile(fileName);\n\n    QTAIMWavefunctionEvaluator eval(wfn);\n\n    QVector3D result;\n\n    if( wfn.nuclearCharge(nucleus) < 4 )\n    {\n      //      QTAIMODEIntegrator ode(eval,QTAIMODEIntegrator::CMBPMinusThreeGradientInElectronDensity);\n      QTAIMLSODAIntegrator ode(eval,QTAIMLSODAIntegrator::CMBPMinusThreeGradientInElectronDensity);\n      result=ode.integrate(x0y0z0);\n    }\n    else\n    {\n      result=x0y0z0;\n    }\n\n    bool correctSignature;\n    Matrix<qreal,3,1> xyz; xyz << result.x(), result.y(), result.z();\n\n    if(\n        QTAIMMathUtilities::signatureOfASymmetricThreeByThreeMatrix(\n            eval.hessianOfElectronDensity(xyz)\n            ) == -3\n        )\n    {\n      correctSignature=true;\n    }\n    else\n    {\n      correctSignature=false;\n    }\n\n    QList<QVariant> value;\n\n    if( correctSignature )\n    {\n      value.append(correctSignature);\n      value.append(result.x());\n      value.append(result.y());\n      value.append(result.z());\n    }\n    else\n    {\n      value.append(false);\n    }\n\n    return value;\n\n  }\n\n  QList<QVariant> QTAIMLocateBondCriticalPoint( QList<QVariant> input  )\n  {\n\n    QList<QVariant> value;\n    value.clear();\n\n    const QString wfnFileName=input.at(0).toString();\n    const QString nuclearCriticalPointsFileName=input.at(1).toString();\n    const qint64 nucleusA=input.at(2).toInt();\n    const qint64 nucleusB=input.at(3).toInt();\n    const QVector3D x0y0z0(\n        input.at(4).toReal(),\n        input.at(5).toReal(),\n        input.at(6).toReal()\n        );\n\n    QTAIMWavefunction wfn;\n    wfn.loadFromBinaryFile(wfnFileName);\n\n    QList<QVector3D> nuclearCriticalPoints;\n    QFile nuclearCriticalPointsFile(nuclearCriticalPointsFileName);\n    nuclearCriticalPointsFile.open(QIODevice::ReadOnly);\n    QDataStream nuclearCriticalPointsFileIn(&nuclearCriticalPointsFile);\n    nuclearCriticalPointsFileIn >> nuclearCriticalPoints ;\n    nuclearCriticalPointsFile.close();\n\n    QList<QPair<QVector3D,qreal> > betaSpheres;\n    for( qint64 i=0 ; i < nuclearCriticalPoints.length() ; ++i )\n    {\n      QPair<QVector3D,qreal> thisBetaSphere;\n      thisBetaSphere.first=nuclearCriticalPoints.at(i);\n      thisBetaSphere.second=0.1;\n      betaSpheres.append(thisBetaSphere);\n    }\n\n    QTAIMWavefunctionEvaluator eval(wfn);\n\n    QList<QVector3D> ncpList;\n\n    QVector3D result;\n    //    QTAIMODEIntegrator ode(eval,QTAIMODEIntegrator::CMBPMinusOneGradientInElectronDensity);\n    QTAIMLSODAIntegrator ode(eval,QTAIMLSODAIntegrator::CMBPMinusOneGradientInElectronDensity);\n    result=ode.integrate(x0y0z0);\n    Matrix<qreal,3,1> xyz; xyz << result.x(), result.y(), result.z();\n\n    if(\n        !( QTAIMMathUtilities::signatureOfASymmetricThreeByThreeMatrix(\n            eval.hessianOfElectronDensity(xyz)\n            ) == -1 )\n        || (eval.gradientOfElectronDensity(xyz)).norm() > SMALL_GRADIENT_NORM\n        )\n    {\n      value.append(false);\n      value.append(result.x());\n      value.append(result.y());\n      value.append(result.z());\n      return value;\n    }\n\n    Matrix<qreal,3,3> eigenvectorsOfHessian;\n    eigenvectorsOfHessian=QTAIMMathUtilities::eigenvectorsOfASymmetricThreeByThreeMatrix(\n        eval.hessianOfElectronDensity(xyz)\n        );\n    Matrix<qreal,3,1> highestEigenvectorOfHessian;\n    highestEigenvectorOfHessian <<\n        eigenvectorsOfHessian(0,2),\n        eigenvectorsOfHessian(1,2),\n        eigenvectorsOfHessian(2,2);\n\n    const qreal smallStep=0.01;\n\n    QVector3D forwardStartingPoint( result.x() + smallStep*highestEigenvectorOfHessian(0),\n                                    result.y() + smallStep*highestEigenvectorOfHessian(1),\n                                    result.z() + smallStep*highestEigenvectorOfHessian(2) );\n\n    QVector3D backwardStartingPoint( result.x() - smallStep*highestEigenvectorOfHessian(0),\n                                     result.y() - smallStep*highestEigenvectorOfHessian(1),\n                                     result.z() - smallStep*highestEigenvectorOfHessian(2) );\n\n    //    QTAIMODEIntegrator forwardODE(eval,QTAIMODEIntegrator::SteepestAscentPathInElectronDensity);\n    QTAIMLSODAIntegrator forwardODE(eval,QTAIMLSODAIntegrator::SteepestAscentPathInElectronDensity);\n    forwardODE.setBetaSpheres( betaSpheres );\n    QVector3D forwardEndpoint=forwardODE.integrate(forwardStartingPoint);\n    QList<QVector3D> forwardPath=forwardODE.path();\n\n    //    QTAIMODEIntegrator backwardODE(eval,QTAIMODEIntegrator::SteepestAscentPathInElectronDensity);\n    QTAIMLSODAIntegrator backwardODE(eval,QTAIMLSODAIntegrator::SteepestAscentPathInElectronDensity);\n    backwardODE.setBetaSpheres( betaSpheres );\n    QVector3D backwardEndpoint=backwardODE.integrate(backwardStartingPoint);\n    QList<QVector3D> backwardPath=backwardODE.path();\n\n    qreal smallestDistance=HUGE_REAL_NUMBER;\n    qint64 smallestDistanceIndex=0;\n\n    for( qint64 n=0 ; n < wfn.numberOfNuclei()  ; ++n )\n    {\n      Matrix<qreal,3,1> a(forwardEndpoint.x(),forwardEndpoint.y(),forwardEndpoint.z());\n      Matrix<qreal,3,1> b(wfn.xNuclearCoordinate(n), wfn.yNuclearCoordinate(n), wfn.zNuclearCoordinate(n));\n\n      qreal distance=QTAIMMathUtilities::distance(a,b);\n\n      if( distance < smallestDistance )\n      {\n        smallestDistance = distance;\n        smallestDistanceIndex=n;\n      }\n    }\n    qint64 forwardNucleusIndex=smallestDistanceIndex;\n\n    smallestDistance=HUGE_REAL_NUMBER;\n    smallestDistanceIndex=0;\n\n    for( qint64 n=0 ; n < wfn.numberOfNuclei()  ; ++n )\n    {\n      Matrix<qreal,3,1> a(backwardEndpoint.x(),backwardEndpoint.y(),backwardEndpoint.z());\n      Matrix<qreal,3,1> b(wfn.xNuclearCoordinate(n), wfn.yNuclearCoordinate(n), wfn.zNuclearCoordinate(n));\n\n      qreal distance=QTAIMMathUtilities::distance(a,b);\n\n      if( distance < smallestDistance )\n      {\n        smallestDistance = distance;\n        smallestDistanceIndex=n;\n      }\n    }\n    qint64 backwardNucleusIndex=smallestDistanceIndex;\n\n    bool bondPathConnectsPair;\n    if( (forwardNucleusIndex == nucleusA && backwardNucleusIndex == nucleusB) ||\n        (forwardNucleusIndex == nucleusB && backwardNucleusIndex == nucleusA) )\n    {\n      bondPathConnectsPair=true;\n    }\n    else\n    {\n      bondPathConnectsPair=false;\n    }\n\n    if( bondPathConnectsPair )\n    {\n      value.append(true);\n      value.append(nucleusA);\n      value.append(nucleusB);\n      value.append(result.x());\n      value.append(result.y());\n      value.append(result.z());\n      Matrix<qreal,3,1> xyz_ ; xyz_ << result.x(),result.y(),result.z();\n      value.append( eval.laplacianOfElectronDensity(xyz_) );\n      value.append( QTAIMMathUtilities::ellipticityOfASymmetricThreeByThreeMatrix(\n          eval.hessianOfElectronDensity(xyz_)\n          )\n                    );\n      value.append( 1 + forwardPath.length() + 1 + backwardPath.length() + 1);\n      value.append( forwardEndpoint.x() );\n      for(qint64 i=forwardPath.length() - 1 ; i >= 0 ; --i)\n      {\n        value.append( forwardPath.at(i).x() );\n      }\n      value.append(result.x());\n      for(qint64 i=0; i < backwardPath.length() ; ++i)\n      {\n        value.append( backwardPath.at(i).x() );\n      }\n      value.append( backwardEndpoint.x() );\n      value.append( forwardEndpoint.y() );\n      for(qint64 i=forwardPath.length() - 1 ; i >= 0 ; --i)\n      {\n        value.append( forwardPath.at(i).y() );\n      }\n      value.append(result.y());\n      for(qint64 i=0; i < backwardPath.length() ; ++i)\n      {\n        value.append( backwardPath.at(i).y() );\n      }\n      value.append( backwardEndpoint.y() );\n      value.append( forwardEndpoint.z() );\n      for(qint64 i=forwardPath.length() - 1 ; i >= 0 ; --i)\n      {\n        value.append( forwardPath.at(i).z() );\n      }\n      value.append(result.z());\n      for(qint64 i=0; i < backwardPath.length() ; ++i)\n      {\n        value.append( backwardPath.at(i).z() );\n      }\n      value.append( backwardEndpoint.z() );\n\n    }\n    else\n    {\n      value.append(false);\n      // for debugging\n      value.append(result.x());\n      value.append(result.y());\n      value.append(result.z());\n    }\n\n    return value;\n  }\n\n\n  QList<QVariant> QTAIMLocateElectronDensitySink( QList<QVariant> input  )\n  {\n    qint64 counter=0;\n    const QString fileName=input.at(counter).toString(); counter++;\n    //    const qint64 nucleus=input.at(counter).toInt(); counter++\n    qreal x0=input.at(counter).toReal(); counter++;\n    qreal y0=input.at(counter).toReal(); counter++;\n    qreal z0=input.at(counter).toReal(); counter++;\n\n    const QVector3D x0y0z0(x0,y0,z0);\n\n    QTAIMWavefunction wfn;\n    wfn.loadFromBinaryFile(fileName);\n\n    QTAIMWavefunctionEvaluator eval(wfn);\n\n    bool correctSignature;\n    QVector3D result;\n\n    Matrix<qreal,3,1> xyz; xyz << x0, y0, z0;\n    if( eval.electronDensity( xyz ) < 1.e-1 )\n    {\n      correctSignature=false;\n    }\n    else\n    {\n      //      QTAIMODEIntegrator ode(eval,QTAIMODEIntegrator::CMBPMinusThreeGradientInElectronDensityLaplacian);\n      QTAIMLSODAIntegrator ode(eval,QTAIMLSODAIntegrator::CMBPMinusThreeGradientInElectronDensityLaplacian);\n      result=ode.integrate(x0y0z0);\n\n      Matrix<qreal,3,1> xyz_; xyz_ << result.x(), result.y(), result.z();\n\n      if( eval.electronDensity(xyz_) > 1.e-1 &&\n          eval.gradientOfElectronDensityLaplacian(xyz_).norm() < 1.e-3 )\n      {\n        if(\n            QTAIMMathUtilities::signatureOfASymmetricThreeByThreeMatrix(\n                eval.hessianOfElectronDensityLaplacian(xyz_)\n                ) == -3\n            )\n        {\n          correctSignature=true;\n        }\n        else\n        {\n          correctSignature=false;\n        }\n      }\n      else\n      {\n        correctSignature=false;\n      }\n    }\n\n    QList<QVariant> value;\n    if( correctSignature )\n    {\n      value.append(correctSignature);\n      value.append(result.x());\n      value.append(result.y());\n      value.append(result.z());\n    }\n    else\n    {\n      value.append(false);\n    }\n\n    return value;\n\n  }\n\n  QList<QVariant> QTAIMLocateElectronDensitySource( QList<QVariant> input  )\n  {\n    qint64 counter=0;\n    const QString fileName=input.at(counter).toString(); counter++;\n    //    const qint64 nucleus=input.at(counter).toInt(); counter++\n    qreal x0=input.at(counter).toReal(); counter++;\n    qreal y0=input.at(counter).toReal(); counter++;\n    qreal z0=input.at(counter).toReal(); counter++;\n\n    const QVector3D x0y0z0(x0,y0,z0);\n\n    QTAIMWavefunction wfn;\n    wfn.loadFromBinaryFile(fileName);\n\n    QTAIMWavefunctionEvaluator eval(wfn);\n\n    bool correctSignature;\n    QVector3D result;\n\n    Matrix<qreal,3,1> xyz; xyz << x0, y0, z0;\n    if( eval.electronDensity( xyz ) < 1.e-1 )\n    {\n      correctSignature=false;\n    }\n    else\n    {\n      //      QTAIMODEIntegrator ode(eval,QTAIMODEIntegrator::CMBPPlusThreeGradientInElectronDensityLaplacian);\n      QTAIMLSODAIntegrator ode(eval,QTAIMLSODAIntegrator::CMBPPlusThreeGradientInElectronDensityLaplacian);\n      result=ode.integrate(x0y0z0);\n\n      Matrix<qreal,3,1> xyz_; xyz_ << result.x(), result.y(), result.z();\n\n      if( eval.electronDensity(xyz_) > 1.e-1 &&\n          eval.gradientOfElectronDensityLaplacian(xyz_).norm() < 1.e-3 )\n      {\n        if(\n            QTAIMMathUtilities::signatureOfASymmetricThreeByThreeMatrix(\n                eval.hessianOfElectronDensityLaplacian(xyz_)\n                ) == 3\n            )\n        {\n          correctSignature=true;\n        }\n        else\n        {\n          correctSignature=false;\n        }\n      }\n      else\n      {\n        correctSignature=false;\n      }\n    }\n\n    QList<QVariant> value;\n    if( correctSignature )\n    {\n      value.append(correctSignature);\n      value.append(result.x());\n      value.append(result.y());\n      value.append(result.z());\n    }\n    else\n    {\n      value.append(false);\n    }\n\n    return value;\n\n  }\n\n  QTAIMCriticalPointLocator::QTAIMCriticalPointLocator( QTAIMWavefunction &wfn)\n  {\n    m_wfn=&wfn;\n\n    m_nuclearCriticalPoints.empty();\n    m_bondCriticalPoints.empty();\n    m_ringCriticalPoints.empty();\n    m_cageCriticalPoints.empty();\n\n    m_laplacianAtBondCriticalPoints.empty();\n    m_ellipticityAtBondCriticalPoints.empty();\n\n    m_bondPaths.empty();\n    m_bondedAtoms.empty();\n\n    m_electronDensitySources.empty();\n    m_electronDensitySinks.empty();\n\n  }\n\n  void QTAIMCriticalPointLocator::locateNuclearCriticalPoints()\n  {\n\n    QString tempFileName=QTAIMCriticalPointLocator::temporaryFileName();\n\n    QList<QList<QVariant> > inputList;\n\n    const qint64 numberOfNuclei = m_wfn->numberOfNuclei();\n\n    for( qint64 n=0 ; n < numberOfNuclei ; ++n)\n    {\n      QList<QVariant> input;\n      input.append( tempFileName );\n      input.append( n );\n      input.append( m_wfn->xNuclearCoordinate(n) );\n      input.append( m_wfn->yNuclearCoordinate(n) );\n      input.append( m_wfn->zNuclearCoordinate(n) );\n\n      inputList.append(input);\n    }\n\n    m_wfn->saveToBinaryFile(tempFileName);\n\n    QProgressDialog dialog;\n    dialog.setWindowTitle(\"QTAIM\");\n    dialog.setLabelText(QString(\"Nuclear Critical Points Search\"));\n\n    QFutureWatcher<void> futureWatcher;\n    QObject::connect(&futureWatcher, SIGNAL(finished()), &dialog, SLOT(reset()));\n    QObject::connect(&dialog, SIGNAL(canceled()), &futureWatcher, SLOT(cancel()));\n    QObject::connect(&futureWatcher, SIGNAL(progressRangeChanged(int,int)), &dialog, SLOT(setRange(int,int)));\n    QObject::connect(&futureWatcher, SIGNAL(progressValueChanged(int)), &dialog, SLOT(setValue(int)));\n\n    QFuture<QList<QVariant> > future=QtConcurrent::mapped(inputList, QTAIMLocateNuclearCriticalPoint);\n    futureWatcher.setFuture(future);\n    dialog.exec();\n    futureWatcher.waitForFinished();\n\n    QList<QList<QVariant> > results;\n    if( futureWatcher.future().isCanceled() )\n    {\n      results.clear();\n    }\n    else\n    {\n      results=future.results();\n    }\n\n    QFile file;\n    file.remove(tempFileName);\n\n    for( qint64 n=0 ; n < results.length() ; ++n )\n    {\n\n      bool correctSignature = results.at(n).at(0).toBool();\n\n      if (correctSignature)\n      {\n\n        QVector3D result(\n          results.at(n).at(1).toReal(),\n          results.at(n).at(2).toReal(),\n          results.at(n).at(3).toReal()\n        );\n\n        m_nuclearCriticalPoints.append( result );\n      }\n\n    }\n\n  }\n\n  void QTAIMCriticalPointLocator::locateBondCriticalPoints()\n  {\n\n    if( m_nuclearCriticalPoints.length() < 1 )\n    {\n      return;\n    }\n\n    const qint64 numberOfNuclei = m_wfn->numberOfNuclei();\n\n    if( numberOfNuclei < 2)\n    {\n      return;\n    }\n\n    QString tempFileName=QTAIMCriticalPointLocator::temporaryFileName();\n\n    QString nuclearCriticalPointsFileName=QTAIMCriticalPointLocator::temporaryFileName();\n    QFile nuclearCriticalPointsFile(nuclearCriticalPointsFileName);\n    nuclearCriticalPointsFile.open(QIODevice::WriteOnly);\n    QDataStream nuclearCriticalPointsOut(&nuclearCriticalPointsFile);\n    nuclearCriticalPointsOut << m_nuclearCriticalPoints;\n    nuclearCriticalPointsFile.close();\n\n    QList<QList<QVariant> > inputList;\n\n    for( qint64 M=0 ; M < numberOfNuclei - 1 ; ++M )\n    {\n      for( qint64 N=M+1 ; N < numberOfNuclei ; ++N )\n      {\n\n        const qreal distanceCutoff = 8.0 ;\n\n        Matrix<qreal,3,1> a;\n        Matrix<qreal,3,1> b;\n\n        a << m_wfn->xNuclearCoordinate(M), m_wfn->yNuclearCoordinate(M), m_wfn->zNuclearCoordinate(M) ;\n        b << m_wfn->xNuclearCoordinate(N), m_wfn->yNuclearCoordinate(N), m_wfn->zNuclearCoordinate(N) ;\n\n        if( QTAIMMathUtilities::distance(a,b) < distanceCutoff )\n        {\n          QVector3D x0y0z0( ( m_wfn->xNuclearCoordinate(M) + m_wfn->xNuclearCoordinate(N) ) / 2.0 ,\n                            ( m_wfn->yNuclearCoordinate(M) + m_wfn->yNuclearCoordinate(N) ) / 2.0,\n                            ( m_wfn->zNuclearCoordinate(M) + m_wfn->zNuclearCoordinate(N) ) / 2.0 );\n\n          QList<QVariant> input;\n          input.append( tempFileName );\n          input.append( nuclearCriticalPointsFileName );\n          input.append( M );\n          input.append( N );\n          input.append( x0y0z0.x() );\n          input.append( x0y0z0.y() );\n          input.append( x0y0z0.z() );\n\n          inputList.append(input);\n        }\n      } // end N\n    } // end M\n\n    m_wfn->saveToBinaryFile(tempFileName);\n\n    QProgressDialog dialog;\n    dialog.setWindowTitle(\"QTAIM\");\n    dialog.setLabelText(QString(\"Bond Critical Points Search\"));\n\n    QFutureWatcher<void> futureWatcher;\n    QObject::connect(&futureWatcher, SIGNAL(finished()), &dialog, SLOT(reset()));\n    QObject::connect(&dialog, SIGNAL(canceled()), &futureWatcher, SLOT(cancel()));\n    QObject::connect(&futureWatcher, SIGNAL(progressRangeChanged(int,int)), &dialog, SLOT(setRange(int,int)));\n    QObject::connect(&futureWatcher, SIGNAL(progressValueChanged(int)), &dialog, SLOT(setValue(int)));\n\n    QFuture<QList<QVariant> > future=QtConcurrent::mapped(inputList, QTAIMLocateBondCriticalPoint);;\n    futureWatcher.setFuture(future);\n    dialog.exec();\n    futureWatcher.waitForFinished();\n\n    QList<QList<QVariant> > results;\n    if( futureWatcher.future().isCanceled() )\n    {\n      results.clear();\n    }\n    else\n    {\n      results=future.results();\n    }\n\n    QFile file;\n    file.remove(tempFileName);\n    file.remove(nuclearCriticalPointsFileName);\n\n    for( qint64 i=0 ; i < results.length() ; ++i )\n    {\n      QList<QVariant> thisCriticalPoint=results.at(i);\n\n      bool success=thisCriticalPoint.at(0).toBool();\n\n      if(success)\n      {\n        QPair<qint64,qint64> bondedAtoms_;\n        bondedAtoms_.first=thisCriticalPoint.at(1).toInt();\n        bondedAtoms_.second=thisCriticalPoint.at(2).toInt();\n        m_bondedAtoms.append( bondedAtoms_ );\n\n        QVector3D coordinates(thisCriticalPoint.at(3).toReal(),\n                              thisCriticalPoint.at(4).toReal(),\n                              thisCriticalPoint.at(5).toReal());\n\n        m_bondCriticalPoints.append( coordinates );\n\n        m_laplacianAtBondCriticalPoints.append(thisCriticalPoint.at(6).toReal());\n        m_ellipticityAtBondCriticalPoints.append(thisCriticalPoint.at(7).toReal());\n        qint64 pathLength=thisCriticalPoint.at(8).toInt();\n\n        QList<QVector3D> bondPath;\n        for( qint64 j=0 ; j < pathLength ; ++j )\n        {\n          QVector3D pathPoint(thisCriticalPoint.at(9 + j                ).toReal(),\n                              thisCriticalPoint.at(9 + j +   pathLength ).toReal(),\n                              thisCriticalPoint.at(9 + j + 2*pathLength ).toReal());\n\n          bondPath.append(pathPoint);\n        }\n\n        m_bondPaths.append(bondPath);\n      }\n\n    }\n\n  }\n\n  void QTAIMCriticalPointLocator::locateElectronDensitySources()\n  {\n\n    QString tempFileName=QTAIMCriticalPointLocator::temporaryFileName();\n\n    QList<QList<QVariant> > inputList;\n\n    qreal xmin,ymin,zmin;\n    qreal xmax,ymax,zmax;\n    qreal xstep,ystep,zstep;\n\n    // TODO: if only we were using Eigen data structures...\n    QList<qreal> xNuclearCoordinates;\n    QList<qreal> yNuclearCoordinates;\n    QList<qreal> zNuclearCoordinates;\n\n    for( qint64 i=0; i < m_wfn->numberOfNuclei() ; ++i )\n    {\n      xNuclearCoordinates.append( m_wfn->xNuclearCoordinate(i) );\n      yNuclearCoordinates.append( m_wfn->yNuclearCoordinate(i) );\n      zNuclearCoordinates.append( m_wfn->zNuclearCoordinate(i) );\n    }\n\n    xmin=xNuclearCoordinates.first();\n    xmax=xNuclearCoordinates.first();\n    for( qint64 i=1 ; i < m_wfn->numberOfNuclei() ; ++i)\n    {\n      if( xNuclearCoordinates.at(i) < xmin )\n      {\n        xmin=xNuclearCoordinates.at(i);\n      }\n      if( xNuclearCoordinates.at(i) > xmax )\n      {\n        xmax=xNuclearCoordinates.at(i);\n      }\n    }\n\n    ymin=yNuclearCoordinates.first();\n    ymax=yNuclearCoordinates.first();\n    for( qint64 i=1 ; i < yNuclearCoordinates.count() ; ++i)\n    {\n      if( yNuclearCoordinates.at(i) < ymin )\n      {\n        ymin=yNuclearCoordinates.at(i);\n      }\n      if( yNuclearCoordinates.at(i) > ymax )\n      {\n        ymax=yNuclearCoordinates.at(i);\n      }\n    }\n\n    zmin=zNuclearCoordinates.first();\n    zmax=zNuclearCoordinates.first();\n    for( qint64 i=1 ; i < zNuclearCoordinates.count() ; ++i)\n    {\n      if( zNuclearCoordinates.at(i) < zmin )\n      {\n        zmin=zNuclearCoordinates.at(i);\n      }\n      if( zNuclearCoordinates.at(i) > zmax )\n      {\n        zmax=zNuclearCoordinates.at(i);\n      }\n    }\n\n    xmin= -2.0 + xmin;\n    ymin= -2.0 + ymin;\n    zmin= -2.0 + zmin;\n\n    xmax = 2.0 + xmax;\n    ymax = 2.0 + ymax;\n    zmax = 2.0 + zmax;\n\n    xstep=ystep=zstep= 0.5;\n\n    for( qreal x=xmin ; x < xmax+xstep ; x=x+xstep)\n    {\n      for( qreal y=ymin ; y < ymax+ystep ; y=y+ystep)\n      {\n        for( qreal z=zmin ; z < zmax+zstep ; z=z+zstep)\n        {\n          QList<QVariant> input;\n          input.append( tempFileName );\n//          input.append( n );\n          input.append( x );\n          input.append( y );\n          input.append( z );\n\n          inputList.append(input);\n        }\n      }\n    }\n\n    m_wfn->saveToBinaryFile(tempFileName);\n\n    QProgressDialog dialog;\n    dialog.setWindowTitle(\"QTAIM\");\n    dialog.setLabelText(QString(\"Electron Density Sources Search\"));\n\n    QFutureWatcher<void> futureWatcher;\n    QObject::connect(&futureWatcher, SIGNAL(finished()), &dialog, SLOT(reset()));\n    QObject::connect(&dialog, SIGNAL(canceled()), &futureWatcher, SLOT(cancel()));\n    QObject::connect(&futureWatcher, SIGNAL(progressRangeChanged(int,int)), &dialog, SLOT(setRange(int,int)));\n    QObject::connect(&futureWatcher, SIGNAL(progressValueChanged(int)), &dialog, SLOT(setValue(int)));\n\n    QFuture<QList<QVariant> > future=QtConcurrent::mapped(inputList, QTAIMLocateElectronDensitySource );\n    futureWatcher.setFuture(future);\n    dialog.exec();\n    futureWatcher.waitForFinished();\n\n    QList<QList<QVariant> > results;\n    if( futureWatcher.future().isCanceled() )\n    {\n      results.clear();\n    }\n    else\n    {\n      results=future.results();\n    }\n\n    QFile file;\n    file.remove(tempFileName);\n\n    for( qint64 n=0 ; n < results.length() ; ++n )\n    {\n\n      qint64 counter=0;\n      bool correctSignature = results.at(n).at(counter).toBool(); counter++;\n\n      if( correctSignature )\n      {\n        qreal x=results.at(n).at(counter).toReal(); counter++;\n        qreal y=results.at(n).at(counter).toReal(); counter++;\n        qreal z=results.at(n).at(counter).toReal(); counter++;\n\n        if( (xmin < x && x < xmax) &&\n            (ymin < y && y < ymax) &&\n            (zmin < z && z < zmax) )\n        {\n          QVector3D result(x,y,z);\n\n          qreal smallestDistance=HUGE_REAL_NUMBER;\n\n          for(qint64 i=0 ; i < m_electronDensitySources.length() ; ++i )\n          {\n\n            Matrix<qreal,3,1> a(x,y,z);\n            Matrix<qreal,3,1> b(m_electronDensitySources.at(i).x(),\n                                m_electronDensitySources.at(i).y(),\n                                m_electronDensitySources.at(i).z());\n\n            qreal distance=QTAIMMathUtilities::distance(a,b);\n\n            if( distance < smallestDistance )\n            {\n              smallestDistance=distance;\n            }\n\n          }\n\n          if( smallestDistance > 1.e-2 )\n          {\n            m_electronDensitySources.append( result );\n          }\n        }\n      }\n    }\n//    qDebug() << \"SOURCES\" << m_electronDensitySources;\n  }\n\n  void QTAIMCriticalPointLocator::locateElectronDensitySinks()\n  {\n\n    QString tempFileName=QTAIMCriticalPointLocator::temporaryFileName();\n\n    QList<QList<QVariant> > inputList;\n\n    qreal xmin,ymin,zmin;\n    qreal xmax,ymax,zmax;\n    qreal xstep,ystep,zstep;\n\n    // TODO: if only we were using Eigen data structures...\n    QList<qreal> xNuclearCoordinates;\n    QList<qreal> yNuclearCoordinates;\n    QList<qreal> zNuclearCoordinates;\n\n    for( qint64 i=0; i < m_wfn->numberOfNuclei() ; ++i )\n    {\n      xNuclearCoordinates.append( m_wfn->xNuclearCoordinate(i) );\n      yNuclearCoordinates.append( m_wfn->yNuclearCoordinate(i) );\n      zNuclearCoordinates.append( m_wfn->zNuclearCoordinate(i) );\n    }\n\n    xmin=xNuclearCoordinates.first();\n    xmax=xNuclearCoordinates.first();\n    for( qint64 i=1 ; i < m_wfn->numberOfNuclei() ; ++i)\n    {\n      if( xNuclearCoordinates.at(i) < xmin )\n      {\n        xmin=xNuclearCoordinates.at(i);\n      }\n      if( xNuclearCoordinates.at(i) > xmax )\n      {\n        xmax=xNuclearCoordinates.at(i);\n      }\n    }\n\n    ymin=yNuclearCoordinates.first();\n    ymax=yNuclearCoordinates.first();\n    for( qint64 i=1 ; i < yNuclearCoordinates.count() ; ++i)\n    {\n      if( yNuclearCoordinates.at(i) < ymin )\n      {\n        ymin=yNuclearCoordinates.at(i);\n      }\n      if( yNuclearCoordinates.at(i) > ymax )\n      {\n        ymax=yNuclearCoordinates.at(i);\n      }\n    }\n\n    zmin=zNuclearCoordinates.first();\n    zmax=zNuclearCoordinates.first();\n    for( qint64 i=1 ; i < zNuclearCoordinates.count() ; ++i)\n    {\n      if( zNuclearCoordinates.at(i) < zmin )\n      {\n        zmin=zNuclearCoordinates.at(i);\n      }\n      if( zNuclearCoordinates.at(i) > zmax )\n      {\n        zmax=zNuclearCoordinates.at(i);\n      }\n    }\n\n    xmin= -2.0 + xmin;\n    ymin= -2.0 + ymin;\n    zmin= -2.0 + zmin;\n\n    xmax = 2.0 + xmax;\n    ymax = 2.0 + ymax;\n    zmax = 2.0 + zmax;\n\n    xstep=ystep=zstep= 0.5;\n\n    for( qreal x=xmin ; x < xmax+xstep ; x=x+xstep)\n    {\n      for( qreal y=ymin ; y < ymax+ystep ; y=y+ystep)\n      {\n        for( qreal z=zmin ; z < zmax+zstep ; z=z+zstep)\n        {\n          QList<QVariant> input;\n          input.append( tempFileName );\n//          input.append( n );\n          input.append( x );\n          input.append( y );\n          input.append( z );\n\n          inputList.append(input);\n        }\n      }\n    }\n\n    m_wfn->saveToBinaryFile(tempFileName);\n\n    QProgressDialog dialog;\n    dialog.setWindowTitle(\"QTAIM\");\n    dialog.setLabelText(QString(\"Electron Density Sinks Search\"));\n\n    QFutureWatcher<void> futureWatcher;\n    QObject::connect(&futureWatcher, SIGNAL(finished()), &dialog, SLOT(reset()));\n    QObject::connect(&dialog, SIGNAL(canceled()), &futureWatcher, SLOT(cancel()));\n    QObject::connect(&futureWatcher, SIGNAL(progressRangeChanged(int,int)), &dialog, SLOT(setRange(int,int)));\n    QObject::connect(&futureWatcher, SIGNAL(progressValueChanged(int)), &dialog, SLOT(setValue(int)));\n\n    QFuture<QList<QVariant> > future=QtConcurrent::mapped(inputList, QTAIMLocateElectronDensitySink );\n    futureWatcher.setFuture(future);\n    dialog.exec();\n    futureWatcher.waitForFinished();\n\n    QList<QList<QVariant> > results;\n    if( futureWatcher.future().isCanceled() )\n    {\n      results.clear();\n    }\n    else\n    {\n      results=future.results();\n    }\n\n    QFile file;\n    file.remove(tempFileName);\n\n    for( qint64 n=0 ; n < results.length() ; ++n )\n    {\n\n      qint64 counter=0;\n      bool correctSignature = results.at(n).at(counter).toBool(); counter++;\n\n      if( correctSignature )\n      {\n        qreal x=results.at(n).at(counter).toReal(); counter++;\n        qreal y=results.at(n).at(counter).toReal(); counter++;\n        qreal z=results.at(n).at(counter).toReal(); counter++;\n\n        if( (xmin < x && x < xmax) &&\n            (ymin < y && y < ymax) &&\n            (zmin < z && z < zmax) )\n        {\n          QVector3D result(x,y,z);\n\n          qreal smallestDistance=HUGE_REAL_NUMBER;\n\n          for(qint64 i=0 ; i < m_electronDensitySinks.length() ; ++i )\n          {\n\n            Matrix<qreal,3,1> a(x,y,z);\n            Matrix<qreal,3,1> b(m_electronDensitySinks.at(i).x(),\n                                m_electronDensitySinks.at(i).y(),\n                                m_electronDensitySinks.at(i).z());\n\n            qreal distance=QTAIMMathUtilities::distance(a,b);\n\n            if( distance < smallestDistance )\n            {\n              smallestDistance=distance;\n            }\n\n          }\n\n          if( smallestDistance > 1.e-2 )\n          {\n            m_electronDensitySinks.append( result );\n          }\n        }\n      }\n    }\n//    qDebug() << \"SINKS\" << m_electronDensitySinks;\n  }\n\n  QString QTAIMCriticalPointLocator::temporaryFileName()\n  {\n    QTemporaryFile temporaryFile;\n    temporaryFile.open();\n    QString tempFileName=temporaryFile.fileName();\n    temporaryFile.close();\n    temporaryFile.remove();\n\n    // wait for temporary file to be deleted\n    QDir dir;\n    do\n    {\n      // Nothing\n    } while ( dir.exists(tempFileName) );\n\n    return tempFileName;\n  }\n\n} // namespace QtPlugins\n} // namespace Avogadro\n", "meta": {"hexsha": "6b390e0c4829e89846202c3ae966fd9e23fd8d77", "size": 29976, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "avogadro/qtplugins/qtaim/qtaimcriticalpointlocator.cpp", "max_stars_repo_name": "AlbertDeFusco/avogadrolibs", "max_stars_repo_head_hexsha": "572aad6d16295c91da684d180b6b2705070549c1", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "avogadro/qtplugins/qtaim/qtaimcriticalpointlocator.cpp", "max_issues_repo_name": "AlbertDeFusco/avogadrolibs", "max_issues_repo_head_hexsha": "572aad6d16295c91da684d180b6b2705070549c1", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "avogadro/qtplugins/qtaim/qtaimcriticalpointlocator.cpp", "max_forks_repo_name": "AlbertDeFusco/avogadrolibs", "max_forks_repo_head_hexsha": "572aad6d16295c91da684d180b6b2705070549c1", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.9343629344, "max_line_length": 112, "alphanum_fraction": 0.6244995997, "num_tokens": 7696, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6654105720171531, "lm_q2_score": 0.4921881357207955, "lm_q1q2_score": 0.3275071889300307}}
{"text": "#include <iostream>\n#include <random>\n\n#include <boost/tuple/tuple.hpp>\n\n#include \"pca.h\"\n#include \"utils.h\"\n\nstd::string word_vector_file;\nstd::vector<std::string> search_words;\n\n// main function arguments\n\nvoid printHelp() {\n  std::cout << \"c++ pca implementation \\n\\n\";\n  std::cout << \"Options:\\n\";\n  std::cout << \"Parameters for drawing:\\n\";\n  std::cout << \"\\t-word-vector <file>\\n\";\n  std::cout << \"\\t\\tUse word vector stored in <file>\\n\";\n  std::cout << \"\\t-draw-words <words>\\n\";\n  std::cout << \"\\t\\tChoose <words> to be drawed\\n\";\n  std::cout << \"\\nExamples:\\n\";\n  std::cout << \"./pca -word-vector data.txt -draw-words king queen prince princess\\n\";\n  \n}\n\nint ArgPos(char *str, int argc, char **argv) {\n  int i;\n  std::string s_str;\n  std::string s_argv[argc];\n  \n  for(i = 1; i < argc; i++) s_argv[i] = argv[i];\n  s_str = str;\n  \n  for(i = 1; i < argc; i++) if(s_str == s_argv[i]) {\n      if(i == argc - 1) {\n\tstd::cout << \"Argument missing for \" << s_str << std::endl;;\n\texit(1);\n      }\n      return i;\n  }\n  return -1;\n}\n\nvoid ArgPass(int argc, char **argv) {\n  int i;\n  if ((i = ArgPos((char *)\"-word-vector\", argc, argv)) > 0) word_vector_file = argv[i + 1];\n  if ((i = ArgPos((char *)\"-draw-words\", argc, argv)) > 0) {\n    for(int j = 0; j < argc - 4; j++)\n      {\n\tsearch_words.push_back(argv[i + 1 + j]);\n      }\n  }\n}\n\n// main function arguments\n\nint main(int argc, char **argv) {\n  std::ofstream fout;\n  \n  std::string line;\n  std::vector<std::string> word;\n\n  std::vector< std::vector<double> > data;\n  std::vector<std::string> label;\n\n  fout.open(\"temp.dat\", std::ofstream::out);\n  \n  if(argc == 1) {\n    printHelp();\n    return 0;\n  }\n\n  ArgPass(argc, argv);\n\n  std::ifstream inFile;\n  inFile.open(word_vector_file, std::ifstream::in);\n  if(inFile.fail()) {\n    std::cout << \"Word vector file not found!\\n\";\n    exit(1);\n  }\n\n  std::getline(inFile, line);\n  split(line, word);\n  int num_records = atoi(word[0].c_str());\n  int num_variables = atoi(word[1].c_str());\n  stats::pca pca(num_variables);\n  pca.set_do_bootstrap(true, 100);\n\n  for(int i = 0; i < num_records; ++i) {\n    word.clear();\n    std::getline(inFile,line);\n    split(line, word);\n    std::vector<double> record(num_variables);\n    for(int j = 0; j < num_variables; j++) record[j] = atof(word[j+1].c_str());\n    \n    pca.add_record(record);\n    label.push_back(word[0]);\n    data.push_back(record);\n  }\n\n  \n  pca.solve();\n\n  /*\n  std::cout<<\"Energy = \"<<pca.get_energy()<<\" (\"<<\n    stats::utils::get_sigma(pca.get_energy_boot())<<\")\"<<std::endl;;\n\n  const auto eigenvalues = pca.get_eigenvalues();\n  std::cout<<\"First three eigenvalues = \"<<eigenvalues[0]<<\", \"\n      <<eigenvalues[1]<<\", \"\n\t   <<eigenvalues[2]<<std::endl;;\n\n  \n  std::cout<<\"Orthogonal Check = \"<<pca.check_eigenvectors_orthogonal()<<std::endl;;\n  std::cout<<\"Projection Check = \"<<pca.check_projection_accurate()<<std::endl;;\n  */\n  \n  //pca.save(\"pca_results\");\n\n  std::vector<double> principal_1 = pca.get_principal(0);\n  std::vector<double> principal_2 = pca.get_principal(1);\n\n  // Very simple use case of gnuplot\n  \n  std::vector< boost::tuple<std::string, double, double> > xy_pts_A;\n\n  \n  double x, y;\n\n  for(int i = 0; i < num_records; i++) {\n    x = 0;\n    y = 0;\n    for(int j = 0; j < num_variables; j++) {\n      x += principal_1[j] * data[i][j];\n      y += principal_2[j] * data[i][j];\n    }\n    //xy_pts_A.push_back(boost::make_tuple(label[i],x,y));\n  }\n\n  for(int i = 0; i < num_records; i++) {\n    for(auto& k: search_words) {\n      if( label[i] == (k) ) {\n\tx = 0;\n\ty = 0;\n\tfor(int k = 0; k < num_variables; k++) {\n\t  x += principal_1[k] * data[i][k];\n\t  y += principal_2[k] * data[i][k];\n\t}\n\txy_pts_A.push_back(boost::make_tuple(label[i],x,y));\n      }\n    }\n  }\n  \n  for(const auto& i : xy_pts_A) {\n    fout << boost::get<0>(i) << \" \" << boost::get<1>(i)<< \" \" << boost::get<2>(i) << std::endl;\n  }\n\n  fout.open(\"script.gp\",std::ofstream::out);\n\n  fout << \"set term png\" << std::endl;\n  fout << \"set output \\\"sample.png\\\"\" << std::endl;\n  fout << \"plot 'temp.dat' using 2:3:1 with labels offset 1 title 'word vectors'\" << std::endl;\n\n  fout.close();\n  return 0;\n}\n", "meta": {"hexsha": "87211161f967b80ad7b50903907234af05581739", "size": 4139, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "word2vec/pca.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/pca.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/pca.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": 24.6369047619, "max_line_length": 95, "alphanum_fraction": 0.5841990819, "num_tokens": 1307, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6548947290421275, "lm_q2_score": 0.5, "lm_q1q2_score": 0.32744736452106377}}
{"text": "//#define CGAL_INTERSECTION_MAP_FOR_SUPPORTING_CIRCLES\n\n#include <CGAL/Cartesian.h>\n#include <CGAL/Handle_for.h>\n#include <CGAL/Simple_cartesian.h>\n#include <CGAL/point_generators_2.h>\n#include <CGAL/MP_Float.h>\n#include <CGAL/Gmpz.h>\n#include <CGAL/Gmpq.h>\n#include <CGAL/Algebraic_kernel_for_circles_2_2.h>\n#include <CGAL/intersections.h>\n#include <CGAL/Circular_kernel_2.h>\n#include <CGAL/Arr_circular_arc_traits_2.h>\n#include <CGAL/Lazy_circular_kernel_2.h>\n#include <CGAL/Filtered_bbox_circular_kernel_2.h>\n#include <CGAL/Arrangement_2.h>\n#include <CGAL/Arr_naive_point_location.h>\n#include <CGAL/Arr_circular_line_arc_traits_2.h>\n#include <CGAL/Timer.h>\n#include <sys/time.h>\n#include <sys/resource.h>\n#include <CGAL/IO/Dxf_variant_reader.h>\n#include <fstream>\n#include <iomanip>\n\n#include <boost/type_traits.hpp>\n\n// CIRCULAR KERNEL TYPEDEFS\n//typedef CGAL::MP_Float RT;\n//typedef CGAL::Quotient<RT> NT1;\ntypedef CGAL::Gmpz RT;\ntypedef CGAL::Gmpq NT1;\ntypedef CGAL::Cartesian<NT1> Linear_k1;\ntypedef CGAL::Algebraic_kernel_for_circles_2_2<NT1> Algebraic_k1;\ntypedef CGAL::Circular_kernel_2<Linear_k1, Algebraic_k1> CircularKernel;\ntypedef CGAL::Arr_circular_arc_traits_2<CircularKernel> CircularK_CA_Traits;\ntypedef CircularKernel::Circular_arc_2 CircularKArc;\ntypedef std::vector<CircularKArc> CircularKArcContainer;\ntypedef CircularKernel::Circular_arc_2 Circular_arc_2;\ntypedef CircularKernel::Line_arc_2 Line_arc_2;\ntypedef CGAL::Arr_circular_line_arc_traits_2<CircularKernel>   CircularK_Variant_Traits;\ntypedef boost::variant< Circular_arc_2, Line_arc_2 > CircularKVarArc;\ntypedef std::vector<CircularKVarArc> CircularKVarArcContainer;\n\n// LAZY KERNEL TYPEDEFS\ntypedef CGAL::Interval_nt_advanced NT3;\ntypedef CGAL::Cartesian<NT3> Linear_k3;\ntypedef CGAL::Algebraic_kernel_for_circles_2_2<NT3> Algebraic_k3;\ntypedef CGAL::Circular_kernel_2 <Linear_k3,Algebraic_k3> CK3_;\ntypedef CGAL::Lazy_circular_kernel_2<CircularKernel,CK3_> LazyCurvedK;\ntypedef CGAL::Arr_circular_arc_traits_2<LazyCurvedK> LazyCurvedK_CA_Traits;\ntypedef LazyCurvedK::Circular_arc_2 LazyArc;\ntypedef std::vector<LazyArc> LazyArcContainer;\ntypedef LazyCurvedK::Circular_arc_2 Circular_arc_3;\ntypedef LazyCurvedK::Line_arc_2 Line_arc_3;\ntypedef boost::variant<Circular_arc_3,Line_arc_3 > LazyVarArc;\ntypedef std::vector<LazyVarArc> LazyVarContainer;\n//~ typedef CGAL::Arr_circular_line_arc_traits_2<LazyCurvedK,Line_arc_3,Circular_arc_3> LazyCurvedK_Variant_Traits;\ntypedef CGAL::Arr_circular_line_arc_traits_2<LazyCurvedK> LazyCurvedK_Variant_Traits;\n\n// BBOX TYPEDEFS\ntypedef CGAL::Filtered_bbox_circular_kernel_2<CircularKernel>\n  BBCircularKernel ;\ntypedef CGAL::Arr_circular_arc_traits_2<BBCircularKernel>\n  BBCircularKernel_CA_Traits;\ntypedef BBCircularKernel::Circular_arc_2\n  BBCircularKernelArc;\ntypedef std::vector<BBCircularKernelArc>\n  BBCircularKernelArcContainer;\ntypedef BBCircularKernel::Circular_arc_2\n  Circular_arc_6;\ntypedef BBCircularKernel::Line_arc_2\n  Line_arc_6;\ntypedef boost::variant<Circular_arc_6,Line_arc_6 >\n  BBCircVarArc;\ntypedef std::vector<BBCircVarArc>\n  BBCircVarContainer;\ntypedef CGAL::Arr_circular_line_arc_traits_2<BBCircularKernel>  BBCircVariantTraits;\n\n// BBOX(LAZY)\ntypedef CGAL::Filtered_bbox_circular_kernel_2<LazyCurvedK>\n  BBLazyKernel ;\ntypedef CGAL::Arr_circular_arc_traits_2<BBLazyKernel>\n  BBLazyKernel_CA_Traits;\ntypedef BBLazyKernel::Circular_arc_2\n  BBLazyKernelArc;\ntypedef std::vector<BBLazyKernelArc>\n  BBLazyKernelArcContainer;\ntypedef BBLazyKernel::Circular_arc_2\n  Circular_arc_lazybb;\ntypedef BBLazyKernel::Line_arc_2\n  Line_arc_lazybb;\ntypedef boost::variant<Circular_arc_lazybb,Line_arc_lazybb >\n  BBLazyVarArc;\ntypedef std::vector<BBLazyVarArc>\n  BBLazyVarContainer;\ntypedef CGAL::Arr_circular_line_arc_traits_2<BBLazyKernel>  BBLazyVariantTraits;\n\ntemplate <class CK,class Traits,class ArcContainer>\nvoid do_main(const char *s) {\n\n  // TYPEDEFS\n  typedef typename CK::Circular_arc_2      C2;\n  typedef typename CK::Line_arc_2          L2;\n  typedef typename CGAL::Arrangement_2<Traits>          Pmwx;\n  typedef typename CGAL::Arr_naive_point_location<Pmwx> Point_location;\n\n  // LOADING CURVES\n  ArcContainer ac;\n  std::ifstream fin;\n  fin.open (s);\n  CGAL::variant_load<CK, C2, L2>(\n    fin, std::back_inserter(ac));\n  fin.close();\n\n  std::cout << \"Size:\" << ac.size() << std::endl;\n\n  // BENCHMARKING\n  Pmwx _pm;\n  Point_location _pl(_pm);\n  struct rusage before, after;\n  struct timeval utime, stime;\n  getrusage(RUSAGE_SELF,&before);\n  insert(_pm,ac.begin(),ac.end(),boost::false_type());\n  getrusage(RUSAGE_SELF,&after);\n  timersub(&(after.ru_utime),&(before.ru_utime),&utime);\n  timersub(&(after.ru_stime),&(before.ru_stime),&stime);\n  std::cout<<\"Time=\"<< utime.tv_sec<<\".\"<< std::setw(6) <<\n  std::setfill('0')<< utime.tv_usec <<std::endl;\n\n  std::cerr << utime.tv_sec << \".\" << std::setw(6) <<\n  std::setfill('0')<< utime.tv_usec << std::endl;\n\n  std::cout << \"The arrangement size:\" << std::endl\n            << \"   V = \" << _pm.number_of_vertices()\n            << \",  E = \" << _pm.number_of_edges()\n            << \",  F = \" << _pm.number_of_faces() << std::endl;\n\n}\n\ntemplate <class CK,class Traits,class ArcContainer>\nvoid do_main(int k) {\n\n  // TYPEDEFS\n  typedef typename CK::Circular_arc_2      C2;\n  typedef typename CK::Point_2 Point_2;\n  typedef typename CK::FT FT;\n  typedef typename CGAL::Arrangement_2<Traits>          Pmwx;\n  typedef typename CGAL::Arr_naive_point_location<Pmwx> Point_location;\n\n  // LOADING CURVES\n  ArcContainer ac;\n\n  double cx, cy;\n  const FT rft(1.0);\n\n  // DENSE\n  if(k == 0) {\n    for(cx = 0.0; cx <= 10.0; cx += 0.5) {\n      for(cy = 0.0; cy <= 10.0; cy += 0.5) {\n        ac.push_back(typename CK::Circular_arc_2 ( typename CK::Circle_2(Point_2(cx,cy),rft) ) );\n      }\n    }\n  }\n\n  // VERY DENSE\n  if(k == 1) {\n    for(cx = 0.0; cx <= 0.2; cx += 0.01) {\n      for(cy = 0.0; cy <= 0.2; cy += 0.01) {\n        ac.push_back(typename CK::Circular_arc_2 ( typename CK::Circle_2(Point_2(cx,cy),rft) ));\n      }\n    }\n  }\n\n  // ONE CIRCLE\n  if(k == 2) {\n    ac.push_back(typename CK::Circular_arc_2 ( typename CK::Circle_2(Point_2(0,0),5) ));\n  }\n\n  // RANDOM CASE\n  if(k == 3) {\n    CGAL::Random generatorOfgenerator;\n    int random_seed = generatorOfgenerator.get_int(0, 123456);\n    CGAL::Random theRandom(random_seed);\n    for(int i=0; i<100; i++) {\n      double x = theRandom.get_double(0.0,1.0);\n      double y = theRandom.get_double(0.0,1.0);\n      double r = theRandom.get_double(0.00001,1.0);\n      ac.push_back(typename CK::Circular_arc_2 ( typename CK::Circle_2(Point_2(x,y),FT(r)) ));\n    }\n  }\n\n  // SPARSE\n  if(k == 4) {\n    double h = (std::sqrt(3.0)+0.01);\n    for(cx = 0.0; cx <= 40.4; cx += 2.01) {\n      for(cy = h; cy <= h*20; cy += h*2) {\n        ac.push_back(typename CK::Circular_arc_2 ( typename CK::Circle_2(Point_2(cx+1.0,cy),rft) ));\n      }\n      for(cy = 0.0; cy <= h*20.0; cy += h*2) {\n        ac.push_back(typename CK::Circular_arc_2 ( typename CK::Circle_2(Point_2(cx,cy),rft)));\n      }\n    }\n  }\n\n  std::cout << \"Size:\" << ac.size() << std::endl;\n\n  // BENCHMARKING\n  Pmwx _pm;\n  Point_location _pl(_pm);\n  struct rusage before, after;\n  struct timeval utime, stime;\n  getrusage(RUSAGE_SELF,&before);\n  insert(_pm,ac.begin(),ac.end(),boost::false_type());\n  getrusage(RUSAGE_SELF,&after);\n  timersub(&(after.ru_utime),&(before.ru_utime),&utime);\n  timersub(&(after.ru_stime),&(before.ru_stime),&stime);\n  std::cout<<\"Time=\"<< utime.tv_sec<<\".\"<< std::setw(6) <<\n  std::setfill('0')<< utime.tv_usec << std::endl;\n\n  std::cerr << utime.tv_sec << \".\" << std::setw(6) <<\n  std::setfill('0')<< utime.tv_usec << std::endl;\n\n  std::cout << \"The arrangement size:\" << std::endl\n            << \"   V = \" << _pm.number_of_vertices()\n            << \",  E = \" << _pm.number_of_edges()\n            << \",  F = \" << _pm.number_of_faces() << std::endl;\n}\n\nint main(int argc, char* argv[]){\n\n  const char* dxf_filename[] = { \"DXF/51.dxf\",\n                                 \"DXF/cad_l1.dxf\",\n                                 \"DXF/cad_l2.dxf\",\n                                 \"DXF/che_mod1.dxf\",\n                                 \"DXF/CIOnZDraw.dxf\",\n                                 \"DXF/mask1.dxf\",\n                                 \"DXF/elekonta.dxf\",\n                                 \"DXF/netlist_signal_1.dxf\",\n                                 \"DXF/painttrack.dxf\" };\n  if(argc == 3) {\n    int i = argv[1][0]-'0';\n    int j = argv[2][0]-'0';\n    if((j >= 0 && j < 9)) {\n      if(i == 1) do_main<BBCircularKernel,BBCircVariantTraits, BBCircVarContainer>(dxf_filename[j]);\n      if(i == 2) do_main<LazyCurvedK,LazyCurvedK_Variant_Traits, LazyVarContainer>(dxf_filename[j]);\n      if(i == 3) do_main<CircularKernel,CircularK_Variant_Traits, CircularKVarArcContainer>(dxf_filename[j]);\n      if(i == 4) do_main<BBLazyKernel,BBLazyVariantTraits, BBLazyVarContainer>(dxf_filename[j]);\n      if((i >= 5) || (i <= 0)) std::cout << \"INVALID PARAMETERS\" << std::endl;\n    } else {\n      int k = -1;\n      if(j == 9) k = 0;\n      if(j == ('a'-'0')) k = 1;\n      if(j == ('b'-'0')) k = 2;\n      if(j == ('c'-'0')) k = 3;\n      if(j == ('d'-'0')) k = 4;\n      if(i == 1) do_main<BBCircularKernel,BBCircVariantTraits, BBCircVarContainer>(k);\n      if(i == 2) do_main<LazyCurvedK,LazyCurvedK_Variant_Traits, LazyVarContainer>(k);\n      if(i == 3) do_main<CircularKernel,CircularK_Variant_Traits, CircularKVarArcContainer>(k);\n      if(i == 4) do_main<BBLazyKernel,BBLazyVariantTraits, BBLazyVarContainer>(k);\n      if(i == 5) do_main<BBCircularKernel,BBCircularKernel_CA_Traits, BBCircularKernelArcContainer>(k);\n      if(i == 6) do_main<LazyCurvedK,LazyCurvedK_CA_Traits, LazyArcContainer>(k);\n      if(i == 7) do_main<CircularKernel,CircularK_CA_Traits, CircularKArcContainer>(k);\n      if(i == 8) do_main<BBLazyKernel,BBLazyKernel_CA_Traits, BBLazyKernelArcContainer>(k);\n    }\n  } else std::cout << \"INVALID PARAMETERS\" << std::endl;\n\n  return 0;\n}\n", "meta": {"hexsha": "cbec320b58ff9e049d7716ceefc8483bdd4c6536", "size": 9944, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Circular_kernel_2/benchmark/benchmark_CK2.cpp", "max_stars_repo_name": "antoniospg/cgal", "max_stars_repo_head_hexsha": "2891c22fc7f64f680ac7e144407afe49f6425cb9", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-12-12T09:30:07.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-04T05:00:23.000Z", "max_issues_repo_path": "Circular_kernel_2/benchmark/benchmark_CK2.cpp", "max_issues_repo_name": "antoniospg/cgal", "max_issues_repo_head_hexsha": "2891c22fc7f64f680ac7e144407afe49f6425cb9", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": 17.0, "max_issues_repo_issues_event_min_datetime": "2018-01-10T13:32:24.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-30T12:23:20.000Z", "max_forks_repo_path": "Circular_kernel_2/benchmark/benchmark_CK2.cpp", "max_forks_repo_name": "antoniospg/cgal", "max_forks_repo_head_hexsha": "2891c22fc7f64f680ac7e144407afe49f6425cb9", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-03-05T04:18:59.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-05T04:18:59.000Z", "avg_line_length": 36.8296296296, "max_line_length": 115, "alphanum_fraction": 0.6840305712, "num_tokens": 3129, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6926419831347361, "lm_q2_score": 0.47268347662043286, "lm_q1q2_score": 0.3274004206413983}}
{"text": "#include \"Heuristics.hpp\"\n#include \"DependencyHelpers.hpp\"\n#include \"TsplpExceptions.hpp\"\n\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/connected_components.hpp>\n#include <boost/graph/topological_sort.hpp>\n#include <boost/range/adaptor/reversed.hpp>\n\n#include <unordered_set>\n\n#include <xtensor/xmanipulation.hpp>\n\nstd::tuple<std::vector<std::vector<size_t>>, double> tsplp::ExploitFractionalSolution(\n    xt::xarray<double> fractionalSolution, xt::xarray<double> weights,\n    const xt::xtensor<size_t, 1>& startPositions, const xt::xtensor<size_t, 1>& endPositions,\n    const DependencyGraph& dependencies, std::chrono::milliseconds timeout)\n{\n    const auto A = startPositions.size();\n    assert(endPositions.size() == A);\n\n    if (weights.dimension() == 2)\n        weights = xt::repeat(xt::view(weights, xt::newaxis(), xt::all()), A, 0);\n\n    const auto [heuristicPaths, _] = NearestInsertion((1 - fractionalSolution) * weights, startPositions, endPositions, dependencies, timeout);\n\n    if (heuristicPaths.empty())\n        return { heuristicPaths, 0 };\n\n    double sum = 0.0;\n    for (size_t a = 0; a < A; ++a)\n        for (size_t i = 1; i < heuristicPaths[a].size(); ++i)\n            sum += weights(a, heuristicPaths[a][i - 1], heuristicPaths[a][i]);\n\n    return { heuristicPaths, sum };\n}\n\nstd::tuple<std::vector<std::vector<size_t>>, double> tsplp::NearestInsertion(\n    xt::xarray<double> weights, const xt::xtensor<size_t, 1>& startPositions, const xt::xtensor<size_t, 1>& endPositions,\n    const DependencyGraph& dependencies, std::chrono::milliseconds timeout)\n{\n    const auto startTime = std::chrono::steady_clock::now();\n\n    const auto A = startPositions.size();\n    assert(endPositions.size() == A);\n\n    if (weights.dimension() == 2)\n        weights = xt::repeat(xt::view(weights, xt::newaxis(), xt::all()), A, 0);\n\n    assert(weights.dimension() == 3);\n\n    const auto N = weights.shape(1);\n    assert(weights.shape(2) == N);\n\n    boost::adjacency_list<boost::vecS, boost::vecS, boost::directedS> dependencyGraph(N);\n    boost::adjacency_list<boost::vecS, boost::vecS, boost::undirectedS> dependencyGraphUndirected(N);\n    for (const auto& [u, v] : dependencies.GetArcs())\n    {\n        add_edge(u, v, dependencyGraph);\n        add_edge(u, v, dependencyGraphUndirected);\n    }\n\n    for (size_t a = 0; a < A; ++a)\n    {\n        add_edge(startPositions[a], endPositions[a], dependencyGraph);\n        add_edge(startPositions[a], endPositions[a], dependencyGraphUndirected);\n    }\n\n    assert(num_edges(dependencyGraph) >= size(dependencies.GetArcs()));\n\n    std::vector<size_t> componentIds(N);\n    const auto numberOfComponents = boost::connected_components(dependencyGraphUndirected, componentIds.data());\n\n    std::vector<size_t> order;\n    boost::topological_sort(dependencyGraph, std::back_inserter(order));\n\n    std::vector<size_t> component2AgentMap(numberOfComponents, A);\n\n    auto paths = std::vector<std::vector<size_t>>(A);\n    double cost = 0;\n    for (size_t a = 0; a < A; ++a)\n    {\n        assert(componentIds[startPositions[a]] == componentIds[endPositions[a]]);\n\n        paths[a].push_back(startPositions[a]);\n        paths[a].push_back(endPositions[a]);\n\n        cost += weights(a, startPositions[a], endPositions[a]);\n\n        if (component2AgentMap[componentIds[startPositions[a]]] != A)\n            throw IncompatibleDependenciesException();\n\n        component2AgentMap[componentIds[startPositions[a]]] = a;\n    }\n\n    std::vector<size_t> lastInsertPositionOfComponent(numberOfComponents, 0);\n\n    for (const auto n : boost::adaptors::reverse(order))\n    {\n        if (std::chrono::steady_clock::now() >= startTime + timeout)\n            return { std::vector<std::vector<size_t>>{}, 0 };\n\n        if (std::find(startPositions.begin(), startPositions.end(), n) != startPositions.end()\n            || std::find(endPositions.begin(), endPositions.end(), n) != endPositions.end())\n            continue;\n\n        const auto comp = componentIds[n];\n\n        auto minDeltaCost = std::numeric_limits<double>::max();\n        auto minA = std::numeric_limits<size_t>::max();\n        auto minI = std::numeric_limits<size_t>::max();\n\n        const auto [aRangeFirst, aRangeLast] = component2AgentMap[comp] == A\n            ? std::make_pair(static_cast<size_t>(0), A)\n            : std::make_pair(component2AgentMap[comp], component2AgentMap[comp] + 1);\n\n        for (size_t a = aRangeFirst; a < aRangeLast; ++a)\n        {\n            for (size_t i = 1 + lastInsertPositionOfComponent[comp]; i < paths[a].size(); ++i)\n            {\n                const auto oldCost = weights(a, paths[a][i - 1], paths[a][i]);\n                const auto newCost = weights(a, paths[a][i - 1], n) + weights(a, n, paths[a][i]);\n                const auto deltaCost = newCost - oldCost;\n                if (deltaCost < minDeltaCost)\n                {\n                    minDeltaCost = deltaCost;\n                    minA = a;\n                    minI = i;\n                }\n            }\n        }\n\n        using DiffT = decltype(paths[minA].begin())::difference_type;\n        paths[minA].insert(paths[minA].begin() + static_cast<DiffT>(minI), n);\n        cost += minDeltaCost;\n\n        component2AgentMap[comp] = minA;\n        lastInsertPositionOfComponent[comp] = minI;\n    }\n\n    return { paths, cost };\n}\n\nstd::tuple<std::vector<std::vector<size_t>>, double> tsplp::TwoOptPaths(std::vector<std::vector<size_t>> paths,\n    xt::xarray<double> weights, const DependencyGraph& dependencies)\n{\n    assert(weights.dimension() == 2);\n\n    const auto A = paths.size();\n    assert(A > 0);\n\n    bool hasImproved = true;\n    double improvementSum = 0.0;\n\n    while (hasImproved)\n    {\n        hasImproved = false;\n\n        for (size_t a1 = 0; a1 < A; ++a1)\n        {\n            for (size_t a2 = 0; a2 < A; ++a2)\n            {\n                for (size_t i = 1; i < paths[a1].size() - 1; ++i)\n                {\n                    const auto jStart = a1 == a2 ? i + 1 : size_t(1);\n                    for (size_t j = jStart; j < paths[a2].size() - 1; ++j)\n                    {\n                        const auto u = paths[a1][i];\n                        const auto v = paths[a2][j];\n                        \n                        if (a1 != a2 &&\n                            (!dependencies.GetIncomingSpan(u).empty() || !dependencies.GetIncomingSpan(v).empty() ||\n                                !dependencies.GetOutgoingSpan(u).empty() || !dependencies.GetOutgoingSpan(v).empty()))\n                            continue;\n\n                        if (a1 == a2)\n                        {\n                            bool wouldBreakDependency = false;\n                            for (auto k = i; k < j; ++k)\n                            {\n                                if (dependencies.HasArc(u, paths[a1][k + 1]) || dependencies.HasArc(paths[a1][k], v))\n                                {\n                                    wouldBreakDependency = true;\n                                    break;\n                                }\n                            }\n\n                            if (wouldBreakDependency)\n                                continue;\n                        }\n\n                        double improvement = 0.0;\n\n                        if (a1 == a2 && j == i + 1)\n                        {\n                            const auto before1 = weights(paths[a1][i - 1], paths[a1][i    ]);\n                            const auto before2 = weights(paths[a1][i    ], paths[a1][i + 1]);\n                            const auto before4 = weights(paths[a1][i + 1], paths[a1][i + 2]);\n                            const auto after1  = weights(paths[a1][i - 1], paths[a1][i + 1]);\n                            const auto after2  = weights(paths[a1][i + 1], paths[a1][i    ]);\n                            const auto after4  = weights(paths[a1][i    ], paths[a1][i + 2]);\n                            improvement = before1 + before2 + before4 - after1 - after2 - after4;\n                        }\n                        else\n                        {\n                            const auto before1 = weights(paths[a1][i - 1], paths[a1][i    ]);\n                            const auto before2 = weights(paths[a1][i    ], paths[a1][i + 1]);\n                            const auto before3 = weights(paths[a2][j - 1], paths[a2][j    ]);\n                            const auto before4 = weights(paths[a2][j    ], paths[a2][j + 1]);\n                            const auto after1  = weights(paths[a1][i - 1], paths[a2][j    ]);\n                            const auto after2  = weights(paths[a2][j    ], paths[a1][i + 1]);\n                            const auto after3  = weights(paths[a2][j - 1], paths[a1][i    ]);\n                            const auto after4  = weights(paths[a1][i    ], paths[a2][j + 1]);\n                            const auto a1Imp = before1 + before2 - after1 - after2;\n                            const auto a2Imp = before3 + before4 - after3 - after4;\n                            improvement = a1Imp + a2Imp;\n                        }\n\n                        assert(weights(paths[a1][i], paths[a1][i]) == 0);\n\n                        if (improvement > 0.0)\n                        {\n                            hasImproved = true;\n                            std::swap(paths[a1][i], paths[a2][j]);\n                            improvementSum += improvement;\n                        }\n                    }\n                }\n            }\n        }\n    }\n\n    return { paths, improvementSum };\n}\n", "meta": {"hexsha": "e89e299a97237ba52dbd0aae52001e2a68292250", "size": 9537, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tsplp/src/Heuristics.cpp", "max_stars_repo_name": "sebrockm/mtsp-vrp", "max_stars_repo_head_hexsha": "28955855d253f51fcb9397a0b22c6774f66f8d55", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tsplp/src/Heuristics.cpp", "max_issues_repo_name": "sebrockm/mtsp-vrp", "max_issues_repo_head_hexsha": "28955855d253f51fcb9397a0b22c6774f66f8d55", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tsplp/src/Heuristics.cpp", "max_forks_repo_name": "sebrockm/mtsp-vrp", "max_forks_repo_head_hexsha": "28955855d253f51fcb9397a0b22c6774f66f8d55", "max_forks_repo_licenses": ["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.5829787234, "max_line_length": 143, "alphanum_fraction": 0.5216525113, "num_tokens": 2264, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6926419704455588, "lm_q2_score": 0.47268347662043286, "lm_q1q2_score": 0.32740041464343383}}
{"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 ROOT_FINDER_H\n#define ROOT_FINDER_H\n\n#include <iostream>\n#include <cassert>\n#include <string>\n#include <utility>\n#include <Eigen/Core>\n#include <gsl/gsl_vector.h>\n#include <gsl/gsl_multiroots.h>\n\n#include \"logger.hpp\"\n#include \"error.hpp\"\n#include \"ewsb_solver.hpp\"\n#include \"gsl_utils.hpp\"\n#include \"gsl_vector.hpp\"\n#include \"wrappers.hpp\"\n\nnamespace flexiblesusy {\n\n/**\n * @class Root_finder\n * @brief Function root finder\n *\n * The user has to provide the function (of which the root should be\n * found) of the type Function_t.  This function gets as arguments an\n * Eigen vector of lenght `dimension' and returns an Eigen vector of\n * the same length.\n *\n * Example:\n * @code\n * auto parabola = [](const Eigen::Matrix<double,2,1>& x) {\n *    const double y = x(0);\n *    const double z = x(1);\n *    Eigen::Matrix<double,2,1> f;\n *    f << y*(y - 5.0), z*(z - 1.0);\n *    return f;\n * };\n *\n * Root_finder<2> root_finder(parabola, 100, 1.0e-5);\n * const double start[2] = { 10, 10 };\n * const int status = root_finder.find_root(start);\n * @endcode\n */\ntemplate <std::size_t dimension>\nclass Root_finder : public EWSB_solver {\npublic:\n   using Vector_t = Eigen::Matrix<double,dimension,1>;\n   using Function_t = std::function<Vector_t(const Vector_t&)>;\n   enum Solver_type { GSLHybrid, GSLHybridS, GSLBroyden, GSLNewton };\n\n   Root_finder() = default;\n   template <typename F>\n   Root_finder(F&&, std::size_t, double, Solver_type solver_type_ = GSLHybrid);\n   virtual ~Root_finder() = default;\n\n   template <typename F>\n   void set_function(F&& f) { function = std::forward<F>(f); }\n   void set_precision(double p) { precision = p; }\n   void set_max_iterations(std::size_t n) { max_iterations = n; }\n   void set_solver_type(Solver_type t) { solver_type = t; }\n   int find_root(const Vector_t&);\n\n   // EWSB_solver interface methods\n   virtual std::string name() const override { return \"Root_finder<\" + solver_type_name() + \">\"; }\n   virtual int solve(const Eigen::VectorXd&) override;\n   virtual Eigen::VectorXd get_solution() const override { return root; }\n\nprivate:\n   std::size_t max_iterations{100};    ///< maximum number of iterations\n   double precision{1.e-2};            ///< precision goal\n   Vector_t root{Vector_t::Zero()};    ///< the root\n   Function_t function{nullptr};       ///< function to minimize\n   Solver_type solver_type{GSLHybrid}; ///< solver type\n\n   void print_state(const gsl_multiroot_fsolver*, std::size_t) const;\n   std::string solver_type_name() const;\n   const gsl_multiroot_fsolver_type* solver_type_to_gsl_pointer() const;\n   static int gsl_function(const gsl_vector*, void*, gsl_vector*);\n};\n\n/**\n * Constructor\n *\n * @param function_ pointer to the function to minimize\n * @param max_iterations_ maximum number of iterations\n * @param precision_ precision goal\n * @param solver_type_ GSL multiroot solver type\n */\ntemplate <std::size_t dimension>\ntemplate <typename F>\nRoot_finder<dimension>::Root_finder(\n   F&& function_,\n   std::size_t max_iterations_,\n   double precision_,\n   Solver_type solver_type_\n)\n   : max_iterations(max_iterations_)\n   , precision(precision_)\n   , function(std::forward<F>(function_))\n   , solver_type(solver_type_)\n{\n}\n\n/**\n * Start the minimization\n *\n * @param start starting point\n *\n * @return GSL error code (GSL_SUCCESS if minimum found)\n */\ntemplate <std::size_t dimension>\nint Root_finder<dimension>::find_root(const Vector_t& start)\n{\n   if (!function)\n      throw SetupError(\"Root_finder: function not callable\");\n\n   int status;\n   std::size_t iter = 0;\n   void* parameters = &function;\n   gsl_multiroot_function f = {gsl_function, dimension, parameters};\n\n   gsl_multiroot_fsolver* solver\n      = gsl_multiroot_fsolver_alloc(solver_type_to_gsl_pointer(), dimension);\n\n   if (!solver) {\n      throw OutOfMemoryError(std::string(\"Cannot allocate gsl_multiroot_fsolver \") +\n                             gsl_multiroot_fsolver_name(solver));\n   }\n\n#ifndef ENABLE_DEBUG\n   gsl_set_error_handler_off();\n#endif\n\n   GSL_vector tmp_root = to_GSL_vector(start);\n\n   gsl_multiroot_fsolver_set(solver, &f, tmp_root.raw());\n\n#ifdef ENABLE_VERBOSE\n   print_state(solver, iter);\n#endif\n\n   do {\n      iter++;\n      status = gsl_multiroot_fsolver_iterate(solver);\n\n#ifdef ENABLE_VERBOSE\n      print_state(solver, iter);\n#endif\n\n      if (status)   // check if solver is stuck\n         break;\n\n      status = gsl_multiroot_test_residual(solver->f, precision);\n   } while (status == GSL_CONTINUE && iter < max_iterations);\n\n   VERBOSE_MSG(\"\\t\\t\\tRoot_finder status = \" << gsl_strerror(status));\n\n   root = to_eigen_vector_fixed<dimension>(solver->x);\n\n   gsl_multiroot_fsolver_free(solver);\n\n   return status;\n}\n\n/**\n * Print state of the root finder\n *\n * @param solver solver\n * @param iteration iteration number\n */\ntemplate <std::size_t dimension>\nvoid Root_finder<dimension>::print_state(const gsl_multiroot_fsolver* solver,\n                                         std::size_t iteration) const\n{\n   VERBOSE_MSG(\"\\t\\t\\tIteration \" << iteration\n               << \": x = \" << GSL_vector(solver->x)\n               << \", f(x) = \" << GSL_vector(solver->f));\n}\n\ntemplate <std::size_t dimension>\nint Root_finder<dimension>::gsl_function(const gsl_vector* x, void* params, gsl_vector* f)\n{\n   if (!is_finite(x)) {\n      gsl_vector_set_all(f, std::numeric_limits<double>::max());\n      return GSL_EDOM;\n   }\n\n   Function_t* fun = static_cast<Function_t*>(params);\n   int status = GSL_SUCCESS;\n   const Vector_t arg(to_eigen_vector_fixed<dimension>(x));\n   Vector_t result;\n   result.setConstant(std::numeric_limits<double>::max());\n\n   try {\n      result = (*fun)(arg);\n      // workaround for intel compiler / eigen bug that causes unexpected behavior\n      // of allFinite()\n      status = IsFinite(result) ? GSL_SUCCESS : GSL_EDOM;\n      //status = result.allFinite() ? GSL_SUCCESS : GSL_EDOM;\n   } catch (const flexiblesusy::Error&) {\n      status = GSL_EDOM;\n   }\n\n   copy(result, f);\n\n   return status;\n}\n\ntemplate <std::size_t dimension>\nstd::string Root_finder<dimension>::solver_type_name() const\n{\n   switch (solver_type) {\n   case GSLHybrid : return \"GSLHybrid\";\n   case GSLHybridS: return \"GSLHybridS\";\n   case GSLBroyden: return \"GSLBroyden\";\n   case GSLNewton : return \"GSLNewton\";\n   default:\n      throw SetupError(\"Unknown root solver type: \"\n                       + std::to_string(solver_type));\n   }\n\n   return \"unknown\";\n}\n\ntemplate <std::size_t dimension>\nconst gsl_multiroot_fsolver_type* Root_finder<dimension>::solver_type_to_gsl_pointer() const\n{\n   switch (solver_type) {\n   case GSLHybrid : return gsl_multiroot_fsolver_hybrid;\n   case GSLHybridS: return gsl_multiroot_fsolver_hybrids;\n   case GSLBroyden: return gsl_multiroot_fsolver_broyden;\n   case GSLNewton : return gsl_multiroot_fsolver_dnewton;\n   default:\n      throw SetupError(\"Unknown root solver type: \"\n                       + std::to_string(solver_type));\n   }\n\n   return nullptr;\n}\n\ntemplate <std::size_t dimension>\nint Root_finder<dimension>::solve(const Eigen::VectorXd& start)\n{\n   return (find_root(start) == GSL_SUCCESS ?\n           EWSB_solver::SUCCESS : EWSB_solver::FAIL);\n}\n\n} // namespace flexiblesusy\n\n#endif\n", "meta": {"hexsha": "679ca9db423fb5b2940db31958cd8cc032deffa9", "size": 8020, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "contrib/MassSpectra/flexiblesusy/src/root_finder.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/root_finder.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/root_finder.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.7037037037, "max_line_length": 98, "alphanum_fraction": 0.6812967581, "num_tokens": 1975, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6757646010190477, "lm_q2_score": 0.48438008427698437, "lm_q1q2_score": 0.32732691439300904}}
{"text": "#include <iostream>\n#include <fstream>\n#include <complex>\n#include <vector>\n#include <string>\n#include <armadillo>\n\nconst int _Nomega=100,_Niterations=200,_Nk=100;\n\ntypedef arma::Mat< std::complex<double> > arma_t;\n\nconst arma_t ZEROS = arma::Mat< std::complex<double> >(_Nomega,_Nk,arma::fill::zeros);\n\nclass HubbardExt{\n    public:\n        HubbardExt(double,double,double,double,int,int,int);\n        //void operator()(int,std::complex<double>);\n        void init_self();\n        void Gup_kAA(int,int,int,int);\n        void Sup_kAA(int,int);\n        void Gdo_kAA(int,int,int,int);\n        void Sdo_kAA(int,int);\n        void Gup_kBB(int,int,int,int);\n        void Sup_kBB(int,int);\n        void Gdo_kBB(int,int,int,int);\n        void Sdo_kBB(int,int);\n        std::complex<double> w(int);\n        double get_nAA();\n        double get_double_occupancy_AA();\n    private:\n        double _u,_v,_beta,_mu;\n        std::vector<double> _kArr;\n        arma_t _Gup_kAA, _Gdo_kAA, _Gup_kBB, _Gdo_kBB;\n        arma_t _Sup_kAA, _Sdo_kAA, _Sup_kBB, _Sdo_kBB;\n        std::vector< std::complex<double>* > _G_vec_ptr;\n        std::vector< std::complex<double>* > _S_vec_ptr;\n        // Static members\n        static std::complex<double> self_init;\n};\n\nint main(int argc, char ** argv){\n \n\tdouble n,d;\n    double beta_init=5.0, beta_step=5.0, beta_max=100.0;\n    double u_init=2.0, u_step=0.2, u_max=4.0;\n    double v=0.5;\n    double mu=0.0;\n  \n    std::ofstream output;\n    std::ofstream outputDO;\n    std::string strOutput(\"T_vs_U_beta_\"+std::to_string(beta_init)+\"_\"+std::to_string(beta_max)+\"_\"+std::to_string(beta_step)+\"_vs_u_\"+std::to_string(u_init)+\"_\"+std::to_string(u_max)+\"_\"+std::to_string(u_step)+\"_v_\"+std::to_string(v)+\"_Nk_\"+std::to_string(_Nk)+\"_Nomega_\"+std::to_string(_Nomega)+\"_Nit_\"+std::to_string(_Niterations)+\"_Fock.dat\");\n    std::string strOutputDO(\"DO_beta_\"+std::to_string(beta_init)+\"_\"+std::to_string(beta_max)+\"_\"+std::to_string(beta_step)+\"_vs_u_\"+std::to_string(u_init)+\"_\"+std::to_string(u_max)+\"_\"+std::to_string(u_step)+\"_v_\"+std::to_string(v)+\"_Nk_\"+std::to_string(_Nk)+\"_Nomega_\"+std::to_string(_Nomega)+\"_Nit_\"+std::to_string(_Niterations)+\"_Fock.dat\");\n    for (double beta=beta_init; beta<=beta_max; beta+=beta_step){\n        \n        for (double u=u_init; u<=u_max; u+=u_step) {\n            mu=u/2.0+2.0*v; // chemical potential in the 1D case for the extended Hubbard model.\n\n            HubbardExt hubbardExtObj(u,v,beta,mu,_Nomega,_Niterations,_Nk);\n            // Initialize the self-energies.\n            hubbardExtObj.init_self();\n    \n            for (int i=0; i<_Niterations; i++){\n                \n                for (int kn=0; kn<_Nomega; kn++){\n                    \n                    for (int k=0; k<_Nk; k++){\n                        // First updating the AA self-energies\n                        hubbardExtObj.Sup_kAA(k,kn);\n                        hubbardExtObj.Sdo_kAA(k,kn);\n                    }\n                }\n                for (int kn=0; kn<_Nomega; kn++){\n                    \n                    for (int k=0; k<_Nk; k++){\n                        // Then updating the BB self-energies\n                        hubbardExtObj.Sup_kBB(k,kn);\n                        hubbardExtObj.Sdo_kBB(k,kn);\n                    }\n                }\n                std::cout << \"it: \" << i << std::endl;\n                n = hubbardExtObj.get_nAA();\n                d = hubbardExtObj.get_double_occupancy_AA();\n                std::cout << \"d: \" << d << std::endl;\n            }\n            output.open(strOutput, std::ofstream::out | std::ofstream::app);\n            output << n << \" \";\n            output.close();\n\n            outputDO.open(strOutputDO, std::ofstream::out | std::ofstream::app);\n            outputDO << d << \" \";\n            outputDO.close();\n        }\n        std::cout << \"\\n\";\n        output.open(strOutput, std::ofstream::out | std::ofstream::app);\n        output << \"\\n\";\n        output.close();\n\n        outputDO.open(strOutputDO, std::ofstream::out | std::ofstream::app);\n        outputDO << \" \";\n        outputDO.close();\n    }\n  return 0;\n}\n\nstd::complex<double> HubbardExt::self_init = std::complex<double>(0.2,-0.1);\n\nHubbardExt::HubbardExt(double u, double v, double beta, double mu, int Nomega, int Nit, int Nk) : _u(u), _v(v), _beta(beta), _mu(mu){\n    for (int k=0; k<=_Nk; k++){\n        this->_kArr.push_back(-M_PI/2.0 + 2.0*(double)k*M_PI/(2.0*(double)Nk));\n    }\n    _Gup_kAA=ZEROS; _Gdo_kAA=ZEROS; _Gup_kBB=ZEROS; _Gdo_kBB=ZEROS;\n    _Sup_kAA=ZEROS; _Sdo_kAA=ZEROS; _Sup_kBB=ZEROS; _Sdo_kBB=ZEROS;\n    this->_G_vec_ptr = { _Gup_kAA.memptr(), _Gdo_kAA.memptr(), _Gup_kBB.memptr(), _Gdo_kBB.memptr() };\n    this->_S_vec_ptr = { _Sup_kAA.memptr(), _Sdo_kAA.memptr(), _Sup_kBB.memptr(), _Sdo_kBB.memptr() };\n}\n\nvoid HubbardExt::init_self(){\n    for (size_t it=0; it<_S_vec_ptr.size(); it++){\n        for (int j=0; j<_Nomega; j++){\n            std::complex<double> w = std::complex<double>(0.0,(2.0*(double)j+1.0)*M_PI/_beta);\n            for (int k=0; k<_kArr.size(); k++){\n                *(_S_vec_ptr[it] + j*_Nk + k) = std::complex<double>(0.4,-0.1);// /(w+_mu-self_init);\n            }\n        }\n        self_init += std::complex<double>(0.1,0.1);\n    }\n}\n\nvoid HubbardExt::Gup_kAA(int k, int kn, int q, int qn){\n    double epsk=-2.0*cos(_kArr[k]+_kArr[q]);\n    std::complex<double> wj = w(kn)+w(kn);\n    // if (Nit != 0)\n    //     Sup_kAA(k,kn,); // If Nit != \n    *(_G_vec_ptr[0] + qn*_Nk + q) = 1.0/( wj + _mu - *(_S_vec_ptr[0] + qn*_Nk + q) - epsk*epsk/( wj + _mu - *(_S_vec_ptr[2] + qn*_Nk + q) ) );\n}\n\nvoid HubbardExt::Sup_kAA(int k, int kn){\n    for (int qn=0; qn<_Nomega; qn++){\n        for (int q=0; q<_Nk; q++){\n            Gup_kAA(k,kn,q,qn);\n            *(_S_vec_ptr[0] + kn*_Nk + k) += _v*cos(_kArr[q])*( -1.0/(_Nk*_beta) )*( *(_G_vec_ptr[0] + qn*_Nk + q) );\n        }\n    }\n}\n\nvoid HubbardExt::Gdo_kAA(int k, int kn, int q, int qn){\n    double epsk=-2.0*cos(_kArr[k]+_kArr[q]);\n    std::complex<double> wj = w(kn)+w(kn);\n    *(_G_vec_ptr[1] + qn*_Nk + q) = 1.0/( wj + _mu - *(_S_vec_ptr[1] + qn*_Nk + q) - epsk*epsk/( wj + _mu - *(_S_vec_ptr[3] + qn*_Nk + q) ) );\n}\n\nvoid HubbardExt::Sdo_kAA(int k, int kn){\n    for (int qn=0; qn<_Nomega; qn++){\n        for (int q=0; q<_Nk; q++){\n            Gdo_kAA(k,kn,q,qn);\n            *(_S_vec_ptr[1] + kn*_Nk + kn) += _v*cos(_kArr[q])*( -1.0/(_Nk*_beta) )*( *(_G_vec_ptr[1] + qn*_Nk + q) );\n        }\n    }\n}\n\n// // BB quantities are computed after AA quantities have been computed.\n\nvoid HubbardExt::Gup_kBB(int k, int kn, int q, int qn){\n    double epsk=-2.0*cos(_kArr[k]+_kArr[q]);\n    std::complex<double> wj = w(kn)+w(kn);\n    *(_G_vec_ptr[2] + qn*_Nk + q) = 1.0/( wj + _mu - *(_S_vec_ptr[2] + qn*_Nk + q) - epsk*epsk/( wj + _mu - *(_S_vec_ptr[0] + qn*_Nk + q) ) );\n}\n\nvoid HubbardExt::Sup_kBB(int k, int kn){\n    for (int qn=0; qn<_Nomega; qn++){\n        for (int q=0; q<_Nk; q++){\n            Gup_kBB(k,kn,q,qn);\n            *(_S_vec_ptr[2] + kn*_Nk + k) += _v*cos(_kArr[q])*( -1.0/(_Nk*_beta) )*( *(_G_vec_ptr[2] + qn*_Nk + q) );\n        }\n    }\n}\n\nvoid HubbardExt::Gdo_kBB(int k, int kn, int q, int qn){\n    double epsk=-2.0*cos(_kArr[k]+_kArr[q]);\n    std::complex<double> wj = w(kn)+w(kn);\n    *(_G_vec_ptr[3] + qn*_Nk + q) = 1.0/( wj + _mu - *(_S_vec_ptr[3] + qn*_Nk + q) - epsk*epsk/( wj + _mu - *(_S_vec_ptr[1] + qn*_Nk + q) ) );\n}\n\nvoid HubbardExt::Sdo_kBB(int k, int kn){\n    for (int qn=0; qn<_Nomega; qn++){\n        for (int q=0; q<_Nk; q++){\n            Gup_kBB(k,kn,q,qn);\n            *(_S_vec_ptr[3] + kn*_Nk + k) += _v*cos(_kArr[q])*( -1.0/(_Nk*_beta) )*( *(_G_vec_ptr[3] + qn*_Nk + q) );\n        }\n    }\n}\n\n// Once all the self-energies of one iteration have been calculated, build the new Green's functions out of the latter.\n\ndouble HubbardExt::get_nAA(){\n    double n=0.0;\n    for (int j=0; j<_Nomega; j++){\n        std::complex<double> n_k(0.0,0.0);\n        std::complex<double> wj = w(j);\n        for (int k=0; k<_kArr.size(); k++){ // Summing over G(k)\n            double epsk = -2.0*cos(_kArr[k]);\n            if ( (k==0) || (k==_Nk) ){\n                n_k += 0.5/( wj + _mu - *(_S_vec_ptr[0] + j*_Nk + k) - epsk*epsk/( wj + _mu - *(_S_vec_ptr[2] + j*_Nk + k) ) );\n            }\n            else{\n                n_k += 1.0/( wj + _mu - *(_S_vec_ptr[0] + j*_Nk + k) - epsk*epsk/( wj + _mu - *(_S_vec_ptr[2] + j*_Nk + k) ) );\n            }\n        }\n        n_k /= (_Nk);\n        n += (2.0/_beta)*( n_k - 1.0/wj ).real();\n    }\n    n -= 0.5;\n    n *= -1.0;\n\n    std::cout << \"beta: \" << _beta << \" u: \" << _u << \" v: \" << _v << \" n: \" << n << std::endl;\n\n    return n;\n}\n\n\ndouble HubbardExt::get_double_occupancy_AA(){\n/* This function computes U<n_{up}n_{down}> = 1/(\\beta*V)*\\sum_{k,ikn} \\Sigma(k,ikn)G(k,ikn)e^{-ikn0^-} */\n    double d=0.0;\n    for (int j=0; j<_Nomega; j++){\n        std::complex<double> d_k(0.0,0.0);\n        std::complex<double> wj = w(j);\n        for (int k=0; k<_kArr.size(); k++){ // Summing over G(k)\n            double epsk = -2.0*cos(_kArr[k]);\n            if ( (k==0) || (k==_Nk) ){\n                d_k += *(_S_vec_ptr[0] + j*_Nk + k)*0.5/( wj + _mu - *(_S_vec_ptr[0] + j*_Nk + k) - epsk)//*epsk/( wj + _mu - *(_S_vec_ptr[2] + j*_Nk + k) ) );\n            }\n            else{\n                d_k += *(_S_vec_ptr[0] + j*_Nk + k)*1.0/( wj + _mu - *(_S_vec_ptr[0] + j*_Nk + k) - epsk)//*epsk/( wj + _mu - *(_S_vec_ptr[2] + j*_Nk + k) ) );\n            }\n        }\n        d_k /= (_Nk);\n        d += (2.0/_beta)*( d_k ).real();\n    }\n    d *= -1.0;\n\n    return d;\n}\n\nstd::complex<double> HubbardExt::w(int j){\n    return std::complex<double>(0.0,(2.0*(double)j+1.0)*M_PI/_beta);\n}\n", "meta": {"hexsha": "969aef0611a50bf7b2a7e3048fd4869892750cd5", "size": 9666, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "fock.cpp", "max_stars_repo_name": "oliviersimard/HF_cpp_latest", "max_stars_repo_head_hexsha": "4926d761b1880ba5a35af6edb05818445b18a4ee", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "fock.cpp", "max_issues_repo_name": "oliviersimard/HF_cpp_latest", "max_issues_repo_head_hexsha": "4926d761b1880ba5a35af6edb05818445b18a4ee", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "fock.cpp", "max_forks_repo_name": "oliviersimard/HF_cpp_latest", "max_forks_repo_head_hexsha": "4926d761b1880ba5a35af6edb05818445b18a4ee", "max_forks_repo_licenses": ["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.1336032389, "max_line_length": 347, "alphanum_fraction": 0.5317608111, "num_tokens": 3418, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7606506635289836, "lm_q2_score": 0.4301473485858429, "lm_q1q2_score": 0.3271918661170544}}
{"text": "#ifndef _RYSQ_KERNEL_ERI_BRA_HPP_\n#define _RYSQ_KERNEL_ERI_BRA_HPP_\n\n#ifdef HAVE_CONFIG_H\n#include \"config.h\"\n#endif\n\n#include <math.h>\n#include <boost/mpl/int.hpp>\n#include <rysq/core.hpp>\n#include \"vector.hpp\"\n\n#include \"kernel/eri.hpp\"\n#include \"kernel/primitives.hpp\"\n#include \"cxx/utility/permute.hpp\"\n\n#include \"kernel/transform.hpp\"\n\nBEGIN_NAMESPACE(rysq, kernel)\n\n\ntemplate<class bra_, int N>\nstruct eri<bra_, boost::mpl::int_<N> > : public Eri\n{\n    typedef bra_ bra;\n    typedef void ket;\n    typedef kernel::Transform<bra> Transform;\n    typedef typename Transform::Data Data;\n    eri(const Quartet<Shell> &quartet, Transform *transform)\n\t: quartet_(quartet),\n\t  transform_(transform),\n\t  primitives_(quartet) {}\n\n    ~eri() { delete transform_; }\n\n    void operator()(const Quartet<Center> &r,\n\t\t    Data &data,\n\t\t    const Parameters &parameters) {\n\tdouble scale = rysq::SQRT_4PI5;\n\tdouble cutoff = parameters.cutoff/(scale*quartet_.K()*10);\n\tapply(quartet_, r[0], r[1], r[2], r[3], scale, cutoff, primitives_,\n\t      (*transform_)(data));\n    }\n\nprivate:\n\n\n    const Quartet<Shell> quartet_;\n    Transform *transform_;\n    eri_::Primitives<double> primitives_;\n\n    template<typename F>\n    static void apply(const Quartet<Shell> &quartet,\n\t\t      const Vector<3> &ri, const Vector<3> &rj,\n\t\t      const Vector<3> &rk, const Vector<3> &rl,\n\t\t      double scale, double cutoff,\n\t\t      eri_::Primitives<F> &primitives,\n\t\t      Transform &transform);//  {\n\n    // \ttypedef kernel::eri_::quadrature<bra> quadrature;\n\n    // \tconst Shell &a = quartet[0];\n    // \tconst Shell &b = quartet[1];\n    // \tconst Shell &c = quartet[2];\n    // \tconst Shell &d = quartet[3];\n\n    // \tVector<3> rij = ri - rj;\n    // \tVector<3> rkl = rk - rl;\n\n    // \tdouble rkl2 = rkl.inner();\n    // \tdouble rij2 = rij.inner();\n\n    // \tdouble eij[a.K*b.K];\n    // \tfor (int Kj = 0, Kij = 0; Kj < b.K; ++Kj) {\n    // \t    for (int Ki = 0; Ki < a.K; ++Ki, ++Kij) {\n    // \t\tdouble A = a(Ki) + b(Kj);\n    // \t\tdouble A1 = 1.0/A;\n    // \t\teij[Kij] = exp(-a(Ki)*b(Kj)*A1*rij2);\n    // \t    }\n    // \t}\n\n    // \tint K = 0;\n\n    // \tfor (int Kl = 0; Kl < d.K; ++Kl) {\n    // \t    for (int Kk = 0; Kk < c.K; ++Kk) {\n    // \t\tdouble ak = c(Kk);\n    // \t\tdouble al = d(Kl);\n    // \t\tdouble B = ak + al;\n\n    // \t\tVector<3> rB = Vector<3>::center(ak, rk, al, rl);\n    // \t\tVector<3> rBk = rB - rk;\n\n    // \t\tdouble ekl = exp(-ak*al*rkl2/B);\n\n    // \t\tdouble Ckl[4] __attribute__ ((aligned(16)));\n    // \t\tdouble Ckl_max = 0.0;\n    // \t\tfor(int l = 0, kl = 0; l < d.nc; ++l) {\n    // \t\t    for(int k = 0; k < c.nc; ++k, ++kl) {\n    // \t\t\tCkl[kl] = c(Kk,k)*d(Kl,l);\n    // \t\t\tCkl_max = std::max(Ckl_max, fabs(Ckl[kl]));\n    // \t\t    }\n    // \t\t}\n\t\t    \n    // \t\tfor(int Kj = 0, Kij = 0; Kj < b.K; ++Kj) {\n    // \t\t    for(int Ki = 0; Ki < a.K; ++Ki, ++Kij) {\n    // \t\t\tdouble ai = a(Ki);\n    // \t\t\tdouble aj = b(Kj); \n    // \t\t\tdouble A = ai + aj;\n    // \t\t\tdouble e = eij[Ki+Kj*a.K]*ekl;\n    // \t\t\tdouble eAB = e/(A*B*sqrt(A+B));\n\n    // \t\t\tdouble Cij[bra::nc] __attribute__ ((aligned(16)));\n    // \t\t\tdouble Cij_max = 0.0;\n\n    // \t\t\tfor(int j = 0, ij = 0; j < bra::B::nc; ++j) {\n    // \t\t\t    for(int i = 0; i < bra::A::nc; ++i, ++ij) {\n    // \t\t\t\tCij[ij] = eAB*a(Ki,i)*b(Kj,j);\n    // \t\t\t\tCij_max = std::max(fabs(Cij[ij]), Cij_max);\n    // \t\t\t    }\n    // \t\t\t}\n    // \t\t\tif (Cij_max*Ckl_max < cutoff) continue;\n\n    // \t\t\tfor(int kl = 0; kl < (c.nc*d.nc); ++kl) {\n    // \t\t\t    for(int ij = 0; ij < bra::nc; ++ij) {\n    // \t\t\t\tprimitives.C[kl][ij + K*bra::nc] = Cij[ij]*Ckl[kl];\n    // \t\t\t    }\n    // \t\t\t}\n\n    // \t\t\tVector<3> rA = Vector<3>::center(ai, ri, aj, rj);\n    // \t\t\tVector<3> rAi = rA - ri;\n    // \t\t\tVector<3> rAB = rA - rB;\n\n    // \t\t\tdouble rho = A*B/(A + B);\n    // \t\t\tdouble X =  rho*rAB.inner();\n    // \t\t\tVector<N> W, t2;\n    // \t\t\trysq::roots<N>(X, t2, W);\n    // \t\t\tt2 /= (A + B);\n\n    // \t\t\tstatic const int LA = bra::A::L;\n    // \t\t\tstatic const int LB = bra::B::L;\n\n    // \t\t\tdouble *Ix = primitives.Ix(K);\n    // \t\t\tdouble *Iy = primitives.Iy(K);\n    // \t\t\tdouble *Iz = primitives.Iz(K); \n\n    // \t\t\tif (LB + d.L == 0) {\n    // \t\t\t    rysq::recurrence<bra::L,N>(c.L + d.L, A, B, rAB, rAi, rBk, \n    // \t\t\t\t\t\t       t2, W, Ix, Iy, Iz);\n    // \t\t\t}\n    // \t\t\telse {\n    // \t\t\t    F *Gx = primitives.template Gx<F>(K);\n    // \t\t\t    F *Gy = primitives.template Gy<F>(K);\n    // \t\t\t    F *Gz = primitives.template Gz<F>(K);\n    // \t\t\t    F *tmp = primitives.template transfer<F>();\n\n    // \t\t\t    rysq::recurrence<bra::L,N>(c.L + d.L, A, B, rAB, rAi, rBk, \n    // \t\t\t\t\t\t       t2, W, Gx, Gy, Gz);\n\n    // \t\t\t    rysq::transfer<LA,LB,N>(c.L, d.L, rij[0], rkl[0], Gx, Ix, tmp);\n    // \t\t\t    rysq::transfer<LA,LB,N>(c.L, d.L, rij[1], rkl[1], Gy, Iy, tmp);\n    // \t\t\t    rysq::transfer<LA,LB,N>(c.L, d.L, rij[2], rkl[2], Gz, Iz, tmp);\n    // \t\t\t}\n\n    // \t\t\t++K;\n\n    // \t\t\t// contract primitives\n    // \t\t\tif (K == primitives.Kmax) {\n    // \t\t\t    primitives.K = K;\n    // \t\t\t    apply(c, d, primitives, scale, transform);\n    // \t\t\t    K = 0;\n    // \t\t\t}\n\n    // \t\t    }\n    // \t\t}\n    // \t    }\n    // \t}\n\n    // \t// Final contraction\n    // \tprimitives.K = K;\n    // \tif (primitives.K) apply(c, d, primitives, scale, transform);\n\n    // }\n\nprivate:\n\n    template<typename F>\n    static void apply(rysq::type c, rysq::type d,\n\t\t      const eri_::Primitives<F> &primitives,\n\t\t      double scale, Transform &transform);//  {\n\n    // \tstatic const int ldN = (sizeof(F) > 8) ? N : N + N%2;\n    // \tstatic const int Nij = ldN*(bra::A::L+1)*(bra::B::L+1);\n\n    // \tconst int Lc = abs(c);\n    // \tconst int Ld = abs(d);\n\n    // \tconst int dim2d = Nij*(Lc+1)*(Ld+1);\n\n    // \tconst int K = primitives.K;\n    // \tconst double* const *C = primitives.C;\n    // \tconst F *Ix = primitives.Ix(0);\n    // \tconst F *Iy = primitives.Iy(0);\n    // \tconst F *Iz = primitives.Iz(0);\n\n    // \tint spk = (c < 0);\n    // \tint spl = (d < 0);\n\n    // \tconst int c_first = shell(c).begin();\n    // \tconst int d_first = shell(d).begin();\n    // \tconst int c_last = shell(c).end() - 1;\n    // \tconst int d_last = shell(d).end() - 1;\n\n    // \tfor(int l = d_first, kl = 0; l <= d_last; ++l) {\n    // \t    const int lx = (Lc+1)*LX[l];\n    // \t    const int ly = (Lc+1)*LY[l];\n    // \t    const int lz = (Lc+1)*LZ[l];\n\n    // \t    const int lsp = (spl && l) << spk;\n\n    // \t    for(int k = c_first; k <= c_last; ++k, ++kl) {\n    // \t\tconst double *Ckl = C[(spk && k) + lsp];\n\n    // \t\tconst int klx = Nij*(lx + LX[k]);\n    // \t\tconst int kly = Nij*(ly + LY[k]);\n    // \t\tconst int klz = Nij*(lz + LZ[k]);\n\n    // \t\tstatic const int ni = bra::A::size;\n    // \t\tstatic const int nj = bra::B::size;\n    // \t\tdouble I[ni*nj] __attribute__((aligned(16))) = { 0.0 };\n\t    \n    // \t\tint flags = 0;\n    // \t\tdouble screen = 0.0;\n    // \t\tquadrature::template apply<N>(flags, screen, K, Ckl, dim2d,\n    // \t\t\t\t\t      &Ix[klx], &Iy[kly], &Iz[klz], 1.0, I);\n\n    // \t\ttransform(k - c_first, l - d_first, kl, I, scale);\n    // \t    }\n    // \t}\n\n    // }\n\n};\n\n\nEND_NAMESPACE(rysq, kernel)\n\n#endif // _RYSQ_KERNEL_ERI_BRA_HPP_\n\n", "meta": {"hexsha": "e29b0681e5cadc646f2132a77a63d8ad1f47f3df", "size": 7082, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "gamess/libqc/rysq/src/kernel/eri-bra.hpp", "max_stars_repo_name": "andremirt/v_cond", "max_stars_repo_head_hexsha": "6b5c364d7cd4243686488b2bd4318be3927e07ea", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "gamess/libqc/rysq/src/kernel/eri-bra.hpp", "max_issues_repo_name": "andremirt/v_cond", "max_issues_repo_head_hexsha": "6b5c364d7cd4243686488b2bd4318be3927e07ea", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "gamess/libqc/rysq/src/kernel/eri-bra.hpp", "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": 28.4417670683, "max_line_length": 77, "alphanum_fraction": 0.4881389438, "num_tokens": 2552, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7606506526772884, "lm_q2_score": 0.43014734858584286, "lm_q1q2_score": 0.32719186144922646}}
{"text": "/**  \\file mcmc_sampler.hpp \\brief Markov Chain Monte Carlo algorithms */\n/*\n-------------------------------------------------------------------------\n   This file is part of BayesOpt, an efficient C++ library for \n   Bayesian optimization.\n\n   Copyright (C) 2011-2015 Ruben Martinez-Cantin <rmcantin@unizar.es>\n \n   BayesOpt is free software: you can redistribute it and/or modify it \n   under the terms of the GNU Affero General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   BayesOpt is distributed in the hope that it will be useful, but \n   WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU Affero General Public License for more details.\n\n   You should have received a copy of the GNU Affero General Public License\n   along with BayesOpt.  If not, see <http://www.gnu.org/licenses/>.\n------------------------------------------------------------------------\n*/\n\n\n#ifndef  _MCMC_SAMPLER_HPP_\n#define  _MCMC_SAMPLER_HPP_\n\n#include <boost/scoped_ptr.hpp>\n#include \"randgen.hpp\"\n#include \"optimizable.hpp\"\n\nnamespace bayesopt {\n\n  // We plan to add more in the future \n  typedef enum {\n    SLICE_MCMC           ///< Slice sampling\n  } McmcAlgorithms;\n\n\n  /**\n   * \\brief Markov Chain Monte Carlo sampler\n   *\n   * It generates a set of particles that are distributed according to\n   * an arbitrary pdf. IMPORTANT: As it should be a replacement for\n   * the optimization (ML or MAP) estimation, it also assumes a\n   * NEGATIVE LOG PDF.\n   *\n   * @see NLOPT_Optimization\n   */\n  class MCMCSampler\n  {\n  public:\n    /** \n     * \\brief Constructor (Note: default constructor is private)\n     * \n     * @param rbo point to RBOptimizable type of object with the PDF\n     *            to sample from. IMPORTANT: We assume that the \n     *            evaluation of rbo is the NEGATIVE LOG PDF.  \n     * @param dim number of input dimensions\n     * @param eng random number generation engine (boost)\n     */\n    MCMCSampler(RBOptimizable* rbo, size_t dim, randEngine& eng);\n    virtual ~MCMCSampler();\n\n    /** Sets the sampling algorithm (slice, MH, etc.) */\n    void setAlgorithm(McmcAlgorithms newAlg);\n\n    /** Sets the number of particles that are stored */\n    void setNParticles(size_t nParticles);\n\n    /**Usually, the initial samples of any MCMC method are biased and\n     *\tthey are discarded. This phase is called the burnout. This\n     *\tmethod sets the number of particles to be discarded \n     */\n    void setNBurnOut(size_t nParticles);\n\n    /** Compute the set of particles according to the target PDF.\n     * @param Xnext input: initial point of the Markov Chain, \n     *              output: last point of the Markov Chain\n     */\n    void run(vectord &Xnext);\n\n    vectord getParticle(size_t i);\n\n    void printParticles();\n\n  private:\n    void randomJump(vectord &x);\n    void burnOut(vectord &x);\n    void sliceSample(vectord &x);\n\n    boost::scoped_ptr<RBOptimizableWrapper> obj;\n\n    McmcAlgorithms mAlg;\n    size_t mDims;\n    size_t nBurnOut;\n    size_t nSamples;\n    bool mStepOut;\n\n    vectord mSigma;\n    vecOfvec mParticles;\n    randEngine& mtRandom;\n\n  private: //Forbidden\n    MCMCSampler();\n    MCMCSampler(MCMCSampler& copy);\n  };\n\n  inline void MCMCSampler::setAlgorithm(McmcAlgorithms newAlg)\n  { mAlg = newAlg; };\n\n  inline void MCMCSampler::setNParticles(size_t nParticles)\n  { nSamples = nParticles; };\n\n  inline void MCMCSampler::setNBurnOut(size_t nParticles)\n  { nBurnOut = nParticles; };\n\n  inline vectord MCMCSampler::getParticle(size_t i)\n  { return mParticles[i]; };\n\n  inline void MCMCSampler::printParticles()\n  {\n    for(size_t i=0; i<mParticles.size(); ++i)\n      { \n\tFILE_LOG(logDEBUG) << i << \"->\" << mParticles[i] \n\t\t\t   << \" | Log-lik \" << -obj->evaluate(mParticles[i]);\n      }\n  }\n\n} //namespace bayesopt\n\n\n#endif\n", "meta": {"hexsha": "f32ca06142ed1e92b2a755ed471ac42905523a5e", "size": 3937, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "external/bayesopt/include/mcmc_sampler.hpp", "max_stars_repo_name": "pchrapka/brain-modelling", "max_stars_repo_head_hexsha": "f232b5a858e45f10b0b0735269010454129ab017", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2017-10-13T19:37:52.000Z", "max_stars_repo_stars_event_max_datetime": "2017-10-13T19:37:52.000Z", "max_issues_repo_path": "external/bayesopt/include/mcmc_sampler.hpp", "max_issues_repo_name": "pchrapka/brain-modelling", "max_issues_repo_head_hexsha": "f232b5a858e45f10b0b0735269010454129ab017", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "external/bayesopt/include/mcmc_sampler.hpp", "max_forks_repo_name": "pchrapka/brain-modelling", "max_forks_repo_head_hexsha": "f232b5a858e45f10b0b0735269010454129ab017", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-11-25T12:22:05.000Z", "max_forks_repo_forks_event_max_datetime": "2019-11-25T12:22:05.000Z", "avg_line_length": 29.3805970149, "max_line_length": 75, "alphanum_fraction": 0.6576073152, "num_tokens": 990, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6113819732941511, "lm_q2_score": 0.5350984286266115, "lm_q1q2_score": 0.32714953320033724}}
{"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 models/crossassetmodel.hpp\n    \\brief cross asset model\n    \\ingroup crossassetmodel\n*/\n\n#ifndef quantext_crossasset_model_hpp\n#define quantext_crossasset_model_hpp\n\n#include <qle/models/cirppparametrization.hpp>\n#include <qle/models/crcirpp.hpp>\n#include <qle/models/crlgm1fparametrization.hpp>\n#include <qle/models/eqbsparametrization.hpp>\n#include <qle/models/fxbsparametrization.hpp>\n#include <qle/models/infdkparametrization.hpp>\n#include <qle/models/infjyparameterization.hpp>\n#include <qle/models/lgm.hpp>\n\n#include <qle/processes/crossassetstateprocess.hpp>\n\n#include <ql/math/distributions/normaldistribution.hpp>\n#include <ql/math/integrals/integral.hpp>\n#include <ql/math/matrix.hpp>\n#include <ql/models/model.hpp>\n\n#include <boost/bind.hpp>\n\nnamespace QuantExt {\nusing namespace QuantLib;\n\nnamespace CrossAssetModelTypes {\n//! Cross Asset Type\n//! \\ingroup crossassetmodel\nenum AssetType { IR, FX, INF, CR, EQ, AUX };\nstatic constexpr Size crossAssetModelAssetTypes = 6;\n\nstd::ostream& operator<<(std::ostream& out, const AssetType& type);\n\n/*! the model types supported by the CrossAssetModel or derived classes;\n  a model type may applicable to several asset types (like BS for FX, EQ) */\nenum ModelType { LGM1F, BS, DK, CIRPP, JY };\n\n} // namespace CrossAssetModelTypes\n\n//! Choice of measure\nstruct Measure {\n    enum Type { LGM, BA };\n};\n\nusing namespace CrossAssetModelTypes;\n\n//! Cross Asset Model\n/*! \\ingroup crossassetmodel\n */\nclass CrossAssetModel : public LinkableCalibratedModel {\npublic:\n    /*! Parametrizations must be given in the following order\n        - IR  (first parametrization defines the domestic currency)\n        - FX  (for all pairs domestic-ccy defined by the IR models)\n        - INF (optionally, ccy must be a subset of the IR ccys)\n        - CR  (optionally, ccy must be a subset of the IR ccys)\n        - EQ  (for all names equity currency defined in Parametrization)\n        If the correlation matrix is not given, it is initialized\n        as the unit matrix (and can be customized after\n        construction of the model).\n    */\n    CrossAssetModel(const std::vector<boost::shared_ptr<Parametrization>>& parametrizations,\n                    const Matrix& correlation = Matrix(), SalvagingAlgorithm::Type salvaging = SalvagingAlgorithm::None,\n                    Measure::Type measure = Measure::LGM);\n\n    /*! IR-FX model based constructor */\n    CrossAssetModel(const std::vector<boost::shared_ptr<LinearGaussMarkovModel>>& currencyModels,\n                    const std::vector<boost::shared_ptr<FxBsParametrization>>& fxParametrizations,\n                    const Matrix& correlation = Matrix(), SalvagingAlgorithm::Type salvaging = SalvagingAlgorithm::None,\n                    Measure::Type measure = Measure::LGM);\n\n    /*! returns the state process with a given discretization */\n    const boost::shared_ptr<StochasticProcess>\n    stateProcess(CrossAssetStateProcess::discretization disc = CrossAssetStateProcess::exact) const;\n\n    /*! total dimension of model (sum of number of state variables) */\n    Size dimension() const;\n\n    /*! total number of Brownian motions (this is less or equal to dimension) */\n    Size brownians() const;\n\n    /*! total number of parameters that can be calibrated */\n    Size totalNumberOfParameters() const;\n\n    /*! number of components for an asset class */\n    Size components(const AssetType t) const;\n\n    /*! number of brownian motions for a component */\n    Size brownians(const AssetType t, const Size i) const;\n\n    /*! number of state variables for a component */\n    Size stateVariables(const AssetType t, const Size i) const;\n\n    /*! model type of a component */\n    ModelType modelType(const AssetType t, const Size i) const;\n\n    /*! Choice of probability measure */\n    Measure::Type measure() const { return measure_; }\n\n    /*! return index for currency (0 = domestic, 1 = first\n      foreign currency and so on) */\n    Size ccyIndex(const Currency& ccy) const;\n\n    /*! return index for equity (0 = first equity) */\n    Size eqIndex(const std::string& eqName) const;\n\n    /*! return index for inflation (0 = first inflation index) */\n    Size infIndex(const std::string& index) const;\n\n    /*! return index for credit (0 = first credit name) */\n    Size crName(const std::string& name) const;\n\n    /*! observer and linked calibrated model interface */\n    void update();\n    void generateArguments();\n\n    /*! the vector of parametrizations */\n    const std::vector<boost::shared_ptr<Parametrization>>& parametrizations() const { return p_; }\n\n    /*! components per asset class, see below for specific model type inspectors */\n    const boost::shared_ptr<Parametrization> ir(const Size ccy) const;\n    const boost::shared_ptr<Parametrization> fx(const Size ccy) const;\n    const boost::shared_ptr<Parametrization> inf(const Size i) const;\n    const boost::shared_ptr<Parametrization> cr(const Size i) const;\n    const boost::shared_ptr<Parametrization> eq(const Size i) const;\n\n    /*! LGM1F components, ccy=0 refers to the domestic currency */\n    const boost::shared_ptr<LinearGaussMarkovModel> lgm(const Size ccy) const;\n\n    const boost::shared_ptr<IrLgm1fParametrization> irlgm1f(const Size ccy) const;\n\n    /*! LGM measure numeraire */\n    Real numeraire(const Size ccy, const Time t, const Real x,\n                   Handle<YieldTermStructure> discountCurve = Handle<YieldTermStructure>()) const;\n\n    /*! Bank account measure numeraire B(t) as a function of drifted LGM state variable x and drift-free auxiliary state\n     * variable y */\n    Real bankAccountNumeraire(const Size ccy, const Time t, const Real x, const Real y,\n                              Handle<YieldTermStructure> discountCurve = Handle<YieldTermStructure>()) const;\n\n    Real discountBond(const Size ccy, const Time t, const Time T, const Real x,\n                      Handle<YieldTermStructure> discountCurve = Handle<YieldTermStructure>()) const;\n\n    Real reducedDiscountBond(const Size ccy, const Time t, const Time T, const Real x,\n                             Handle<YieldTermStructure> discountCurve = Handle<YieldTermStructure>()) const;\n\n    Real discountBondOption(const Size ccy, Option::Type type, const Real K, const Time t, const Time S, const Time T,\n                            Handle<YieldTermStructure> discountCurve = Handle<YieldTermStructure>()) const;\n\n    /*! FXBS components, ccy=0 referes to the first foreign currency,\n        so it corresponds to ccy+1 if you want to get the corresponding\n        irmgl1f component */\n    const boost::shared_ptr<FxBsParametrization> fxbs(const Size ccy) const;\n\n    /*! INF DK components */\n    const boost::shared_ptr<InfDkParametrization> infdk(const Size i) const;\n\n    //! Inflation JY component\n    const boost::shared_ptr<InfJyParameterization> infjy(const Size i) const;\n\n    /*! CR LGM 1F components */\n    const boost::shared_ptr<CrLgm1fParametrization> crlgm1f(const Size i) const;\n\n    /*! CR CIR++ components */\n    const boost::shared_ptr<CrCirpp> crcirppModel(const Size i) const;\n    const boost::shared_ptr<CrCirppParametrization> crcirpp(const Size i) const;\n\n    /*! EQBS components */\n    const boost::shared_ptr<EqBsParametrization> eqbs(const Size ccy) const;\n\n    /* ... add more components here ...*/\n\n    /*! correlation linking the different marginal models, note that\n        the use of asset class pairs specific inspectors is\n        recommended instead of the global matrix directly */\n    const Matrix& correlation() const;\n\n    /*! check if correlation matrix is valid */\n    void checkCorrelationMatrix() const;\n\n    /*! index of component in the parametrization vector */\n    Size idx(const AssetType t, const Size i) const;\n\n    /*! index of component in the correlation matrix, by offset */\n    Size cIdx(const AssetType t, const Size i, const Size offset = 0) const;\n\n    /*! index of component in the stochastic process array, by offset */\n    Size pIdx(const AssetType t, const Size i, const Size offset = 0) const;\n\n    /*! correlation between two components */\n    const Real& correlation(const AssetType s, const Size i, const AssetType t, const Size j, const Size iOffset = 0,\n                            const Size jOffset = 0) const;\n    /*! set correlation */\n    void correlation(const AssetType s, const Size i, const AssetType t, const Size j, const Real value,\n                     const Size iOffset = 0, const Size jOffset = 0);\n\n    /*! get salvaging algorithm */\n    SalvagingAlgorithm::Type salvagingAlgorithm() const { return salvaging_; }\n\n    /*! analytical moments require numerical integration,\n      which can be customized here */\n    void setIntegrationPolicy(const boost::shared_ptr<Integrator> integrator,\n                              const bool usePiecewiseIntegration = true) const;\n    const boost::shared_ptr<Integrator> integrator() const;\n\n    /*! return (V(t), V^tilde(t,T)) in the notation of the book */\n    std::pair<Real, Real> infdkV(const Size i, const Time t, const Time T);\n\n    /*! return (I(t), I^tilde(t,T)) in the notation of the book, note that\n        I(0) is normalized to 1 here, i.e. you have to multiply the result\n        with the index value (as of the base date of the inflation ts) */\n    std::pair<Real, Real> infdkI(const Size i, const Time t, const Time T, const Real z, const Real y);\n\n    /*! return YoYIIS(t) in the notation of the book, the year on year\n        swaplet price from S to T, at time t */\n    Real infdkYY(const Size i, const Time t, const Time S, const Time T, const Real z, const Real y, const Real irz);\n\n    /*! returns (S(t), S^tilde(t,T)) in the notation of the book */\n    std::pair<Real, Real> crlgm1fS(const Size i, const Size ccy, const Time t, const Time T, const Real z,\n                                   const Real y) const;\n\n    /*! returns (S(t), S^tilde(t,T)) in the notation of the book */\n    std::pair<Real, Real> crcirppS(const Size i, const Time t, const Time T, const Real y, const Real s) const;\n\n    /*! tentative: more generic interface that is agnostic of the model type - so far only for CR */\n    virtual Handle<DefaultProbabilityTermStructure> crTs(const Size i) const;\n    virtual std::pair<Real, Real> crS(const Size i, const Size ccy, const Time t, const Time T, const Real z,\n                                      const Real y) const;\n\n    /*! calibration procedures */\n\n    /*! calibrate irlgm1f volatilities to a sequence of ir options with\n        expiry times equal to step times in the parametrization */\n    void calibrateIrLgm1fVolatilitiesIterative(const Size ccy,\n                                               const std::vector<boost::shared_ptr<BlackCalibrationHelper>>& helpers,\n                                               OptimizationMethod& method, const EndCriteria& endCriteria,\n                                               const Constraint& constraint = Constraint(),\n                                               const std::vector<Real>& weights = std::vector<Real>());\n\n    /*! calibrate irlgm1f reversion to a sequence of ir options with\n        maturities equal to step times in the parametrization */\n    void calibrateIrLgm1fReversionsIterative(const Size ccy,\n                                             const std::vector<boost::shared_ptr<BlackCalibrationHelper>>& helpers,\n                                             OptimizationMethod& method, const EndCriteria& endCriteria,\n                                             const Constraint& constraint = Constraint(),\n                                             const std::vector<Real>& weights = std::vector<Real>());\n\n    /*! calibrate irlgm1f parameters for one ccy globally to a set\n        of ir options */\n    void calibrateIrLgm1fGlobal(const Size ccy, const std::vector<boost::shared_ptr<BlackCalibrationHelper>>& helpers,\n                                OptimizationMethod& method, const EndCriteria& endCriteria,\n                                const Constraint& constraint = Constraint(),\n                                const std::vector<Real>& weights = std::vector<Real>());\n\n    /*! calibrate eq or fx volatilities to a sequence of options with\n            expiry times equal to step times in the parametrization */\n    void calibrateBsVolatilitiesIterative(const AssetType& assetType, const Size aIdx,\n                                          const std::vector<boost::shared_ptr<BlackCalibrationHelper>>& helpers,\n                                          OptimizationMethod& method, const EndCriteria& endCriteria,\n                                          const Constraint& constraint = Constraint(),\n                                          const std::vector<Real>& weights = std::vector<Real>());\n\n    /*! calibrate eq/fx volatilities globally to a set of fx options */\n    void calibrateBsVolatilitiesGlobal(const AssetType& assetType, const Size aIdx,\n                                       const std::vector<boost::shared_ptr<BlackCalibrationHelper>>& helpers,\n                                       OptimizationMethod& method, const EndCriteria& endCriteria,\n                                       const Constraint& constraint = Constraint(),\n                                       const std::vector<Real>& weights = std::vector<Real>());\n\n    /*! calibrate infdk volatilities to a sequence of cpi options with\n        expiry times equal to step times in the parametrization */\n    void calibrateInfDkVolatilitiesIterative(const Size index,\n                                             const std::vector<boost::shared_ptr<BlackCalibrationHelper>>& helpers,\n                                             OptimizationMethod& method, const EndCriteria& endCriteria,\n                                             const Constraint& constraint = Constraint(),\n                                             const std::vector<Real>& weights = std::vector<Real>());\n\n    /*! calibrate infdk reversions to a sequence of cpi options with\n        maturity times equal to step times in the parametrization */\n    void calibrateInfDkReversionsIterative(const Size index,\n                                           const std::vector<boost::shared_ptr<BlackCalibrationHelper>>& helpers,\n                                           OptimizationMethod& method, const EndCriteria& endCriteria,\n                                           const Constraint& constraint = Constraint(),\n                                           const std::vector<Real>& weights = std::vector<Real>());\n\n    /*! calibrate infdk volatilities globally to a sequence of cpi cap/floors */\n    void calibrateInfDkVolatilitiesGlobal(const Size index,\n                                          const std::vector<boost::shared_ptr<BlackCalibrationHelper>>& helpers,\n                                          OptimizationMethod& method, const EndCriteria& endCriteria,\n                                          const Constraint& constraint = Constraint(),\n                                          const std::vector<Real>& weights = std::vector<Real>());\n\n    /*! calibrate infdk reversions globally to a sequence of cpi cap/floors */\n    void calibrateInfDkReversionsGlobal(const Size index,\n                                        const std::vector<boost::shared_ptr<BlackCalibrationHelper>>& helpers,\n                                        OptimizationMethod& method, const EndCriteria& endCriteria,\n                                        const Constraint& constraint = Constraint(),\n                                        const std::vector<Real>& weights = std::vector<Real>());\n\n    /*! Calibrate JY inflation parameters globally.\n\n        The parameter \\p toCalibrate indicates which parameters of the JY inflation model that we want to calibrate.\n        The map key should be in {0, 1, 2} where 0 indicates the real rate volatility, 1 indicates the real rate\n        reversion and 2 indicates the inflation index volatility. The value is \\c true if we wish to calibrate\n        the parameter and \\p false if we do not want to calibrate it.\n    */\n    void calibrateInfJyGlobal(QuantLib::Size index,\n                              const std::vector<boost::shared_ptr<QuantLib::CalibrationHelper>>& helpers,\n                              QuantLib::OptimizationMethod& method, const QuantLib::EndCriteria& endCriteria,\n                              const std::map<QuantLib::Size, bool>& toCalibrate,\n                              const QuantLib::Constraint& constraint = QuantLib::Constraint(),\n                              const std::vector<QuantLib::Real>& weights = std::vector<QuantLib::Real>());\n\n    /*! Calibrate a single JY inflation parameter iteratively.\n\n        Calibrate one of real rate volatility, real rate reversion or inflation index volatility. The\n        \\p parameterIndex indicates the parameter that should be calibrated where 0 indicates the real rate\n        volatility, 1 indicates the real rate reversion and 2 indicates the inflation index volatility.\n    */\n    void calibrateInfJyIterative(QuantLib::Size inflationModelIndex, QuantLib::Size parameterIndex,\n                                 const std::vector<boost::shared_ptr<QuantLib::CalibrationHelper>>& helpers,\n                                 QuantLib::OptimizationMethod& method, const QuantLib::EndCriteria& endCriteria,\n                                 const QuantLib::Constraint& constraint = QuantLib::Constraint(),\n                                 const std::vector<QuantLib::Real>& weights = std::vector<QuantLib::Real>());\n\n    /*! calibrate crlgm1f volatilities to a sequence of cds options with\n        expiry times equal to step times in the parametrization */\n    void calibrateCrLgm1fVolatilitiesIterative(const Size index,\n                                               const std::vector<boost::shared_ptr<BlackCalibrationHelper>>& helpers,\n                                               OptimizationMethod& method, const EndCriteria& endCriteria,\n                                               const Constraint& constraint = Constraint(),\n                                               const std::vector<Real>& weights = std::vector<Real>());\n\n    /*! calibrate crlgm1f reversions to a sequence of cds options with\n        maturity times equal to step times in the parametrization */\n    void calibrateCrLgm1fReversionsIterative(const Size index,\n                                             const std::vector<boost::shared_ptr<BlackCalibrationHelper>>& helpers,\n                                             OptimizationMethod& method, const EndCriteria& endCriteria,\n                                             const Constraint& constraint = Constraint(),\n                                             const std::vector<Real>& weights = std::vector<Real>());\n\n    /* ... add more calibration procedures here ... */\n\nprotected:\n    /* ctor to be used in extensions, initialize is not called */\n    CrossAssetModel(const std::vector<boost::shared_ptr<Parametrization>>& parametrizations, const Matrix& correlation,\n                    SalvagingAlgorithm::Type salvaging, Measure::Type measure, const bool)\n        : LinkableCalibratedModel(), p_(parametrizations), rho_(correlation), salvaging_(salvaging), measure_(measure) {\n    }\n\n    /*! number of arguments for a component */\n    Size arguments(const AssetType t, const Size i) const;\n\n    /*! index of component in the arguments vector, by offset */\n    Size aIdx(const AssetType t, const Size i, const Size offset = 0) const;\n\n    /*! asset and model type for given parametrization */\n    virtual std::pair<AssetType, ModelType> getComponentType(const Size i) const;\n    /*! number of parameters for given parametrization */\n    virtual Size getNumberOfParameters(const Size i) const;\n    /*! number of brownians for given parametrization */\n    virtual Size getNumberOfBrownians(const Size i) const;\n    /*! number of state variables for given parametrization */\n    virtual Size getNumberOfStateVariables(const Size i) const;\n    /*! helper function to init component indices */\n    void updateIndices(const AssetType& t, const Size i, const Size cIdx, const Size pIdx, const Size aIdx);\n\n    /* init methods */\n    virtual void initialize();\n    virtual void initializeParametrizations();\n    virtual void initializeCorrelation();\n    virtual void initializeArguments();\n    virtual void finalizeArguments();\n    virtual void checkModelConsistency() const;\n    virtual void initDefaultIntegrator();\n    virtual void initStateProcess();\n\n    /* helper function for infdkI, crlgm1fS */\n    Real infV(const Size idx, const Size ccy, const Time t, const Time T) const;\n    Real crV(const Size idx, const Size ccy, const Time t, const Time T) const;\n\n    // cache for infdkI, crlgm1fS method\n    struct cache_key {\n        Size i, ccy;\n        double t, T;\n        bool operator==(const cache_key& o) const { return (i == o.i) && (ccy == o.ccy) && (t == o.t) && (T == o.T); }\n    };\n\n    struct cache_hasher : std::unary_function<cache_key, std::size_t> {\n        std::size_t operator()(cache_key const& x) const {\n            std::size_t seed = 0;\n            boost::hash_combine(seed, x.i);\n            boost::hash_combine(seed, x.ccy);\n            boost::hash_combine(seed, x.t);\n            boost::hash_combine(seed, x.T);\n            return seed;\n        }\n    };\n\n    mutable boost::unordered_map<cache_key, std::pair<Real, Real>, cache_hasher> cache_crlgm1fS_, cache_infdkI_;\n\n    /* members */\n\n    // components per asset type\n    std::vector<Size> components_;\n    // indices per asset type and component number within asset type\n    std::vector<std::vector<Size>> idx_, cIdx_, pIdx_, aIdx_, brownians_, stateVariables_, numArguments_;\n    // counter\n    Size totalDimension_, totalNumberOfBrownians_, totalNumberOfParameters_;\n    // model type per asset type and component number within asset type\n    std::vector<std::vector<ModelType>> modelType_;\n    // parametrizations, models\n    std::vector<boost::shared_ptr<Parametrization>> p_;\n    std::vector<boost::shared_ptr<LinearGaussMarkovModel>> lgm_;\n    std::vector<boost::shared_ptr<CrCirpp>> crcirppModel_;\n    Matrix rho_;\n    SalvagingAlgorithm::Type salvaging_;\n    Measure::Type measure_;\n    mutable boost::shared_ptr<Integrator> integrator_;\n    boost::shared_ptr<CrossAssetStateProcess> stateProcessExact_, stateProcessEuler_;\n\n    /* calibration constraints */\n\n    void appendToFixedParameterVector(const AssetType t, const AssetType v, const Size param, const Size index,\n                                      const Size i, std::vector<bool>& res) {\n        for (Size j = 0; j < components(t); ++j) {\n            for (Size k = 0; k < arguments(t, j); ++k) {\n                std::vector<bool> tmp1(p_[idx(t, j)]->parameter(k)->size(), true);\n                if ((param == Null<Size>() || k == param) && t == v && index == j) {\n                    for (Size ii = 0; ii < tmp1.size(); ++ii) {\n                        if (i == Null<Size>() || i == ii) {\n                            tmp1[ii] = false;\n                        }\n                    }\n                }\n                res.insert(res.end(), tmp1.begin(), tmp1.end());\n            }\n        }\n    }\n\n    // move parameter param (e.g. vol, reversion, or all if null) of asset type component t / index at step i (or at all\n    // steps if i is null)\n    Disposable<std::vector<bool>> MoveParameter(const AssetType t, const Size param, const Size index, const Size i) {\n        QL_REQUIRE(param == Null<Size>() || param < arguments(t, index),\n                   \"parameter for \" << t << \" at \" << index << \" (\" << param << \") out of bounds 0...\"\n                                    << arguments(t, index) - 1);\n        std::vector<bool> res(0);\n        appendToFixedParameterVector(IR, t, param, index, i, res);\n        appendToFixedParameterVector(FX, t, param, index, i, res);\n        appendToFixedParameterVector(INF, t, param, index, i, res);\n        appendToFixedParameterVector(CR, t, param, index, i, res);\n        appendToFixedParameterVector(EQ, t, param, index, i, res);\n        if (measure_ == Measure::BA)\n            appendToFixedParameterVector(AUX, t, param, index, i, res);\n        return res;\n    }\n};\n\n//! Utility function to return a handle to the inflation term structure given the inflation index.\nQuantLib::Handle<QuantLib::ZeroInflationTermStructure>\ninflationTermStructure(const boost::shared_ptr<CrossAssetModel>& model, QuantLib::Size index);\n\n// inline\n\ninline const boost::shared_ptr<StochasticProcess>\nCrossAssetModel::stateProcess(CrossAssetStateProcess::discretization disc) const {\n    return disc == CrossAssetStateProcess::exact ? stateProcessExact_ : stateProcessEuler_;\n}\n\ninline Size CrossAssetModel::dimension() const { return totalDimension_; }\n\ninline Size CrossAssetModel::brownians() const { return totalNumberOfBrownians_; }\n\ninline Size CrossAssetModel::totalNumberOfParameters() const { return totalNumberOfParameters_; }\n\ninline const boost::shared_ptr<Parametrization> CrossAssetModel::ir(const Size ccy) const { return p_[idx(IR, ccy)]; }\n\ninline const boost::shared_ptr<Parametrization> CrossAssetModel::fx(const Size ccy) const { return p_[idx(FX, ccy)]; }\n\ninline const boost::shared_ptr<Parametrization> CrossAssetModel::inf(const Size i) const { return p_[idx(INF, i)]; }\n\ninline const boost::shared_ptr<Parametrization> CrossAssetModel::cr(const Size i) const { return p_[idx(CR, i)]; }\n\ninline const boost::shared_ptr<Parametrization> CrossAssetModel::eq(const Size i) const {\n    return boost::static_pointer_cast<Parametrization>(p_[idx(EQ, i)]);\n}\n\ninline const boost::shared_ptr<LinearGaussMarkovModel> CrossAssetModel::lgm(const Size ccy) const {\n    boost::shared_ptr<LinearGaussMarkovModel> tmp = lgm_[idx(IR, ccy)];\n    QL_REQUIRE(tmp, \"model at \" << ccy << \" is not IR-LGM1F\");\n    return tmp;\n}\n\ninline const boost::shared_ptr<IrLgm1fParametrization> CrossAssetModel::irlgm1f(const Size ccy) const {\n    return lgm(ccy)->parametrization();\n}\n\ninline const boost::shared_ptr<InfDkParametrization> CrossAssetModel::infdk(const Size i) const {\n    boost::shared_ptr<InfDkParametrization> tmp = boost::dynamic_pointer_cast<InfDkParametrization>(p_[idx(INF, i)]);\n    QL_REQUIRE(tmp, \"model at \" << i << \" is not INF-DK\");\n    return tmp;\n}\n\ninline const boost::shared_ptr<InfJyParameterization> CrossAssetModel::infjy(const Size i) const {\n    auto tmp = boost::dynamic_pointer_cast<InfJyParameterization>(p_[idx(INF, i)]);\n    QL_REQUIRE(tmp, \"model at \" << i << \" is not INF-JY\");\n    return tmp;\n}\n\ninline const boost::shared_ptr<CrLgm1fParametrization> CrossAssetModel::crlgm1f(const Size i) const {\n    boost::shared_ptr<CrLgm1fParametrization> tmp = boost::dynamic_pointer_cast<CrLgm1fParametrization>(p_[idx(CR, i)]);\n    QL_REQUIRE(tmp, \"model at \" << i << \" is not CR-LGM\");\n    return tmp;\n}\n\ninline const boost::shared_ptr<CrCirpp> CrossAssetModel::crcirppModel(const Size i) const {\n    boost::shared_ptr<CrCirpp> tmp = crcirppModel_[i];\n    QL_REQUIRE(tmp, \"model at \" << i << \" is not CR-CIRPP\");\n    return tmp;\n}\n\ninline const boost::shared_ptr<CrCirppParametrization> CrossAssetModel::crcirpp(const Size i) const {\n    boost::shared_ptr<CrCirppParametrization> tmp = boost::dynamic_pointer_cast<CrCirppParametrization>(p_[idx(CR, i)]);\n    QL_REQUIRE(tmp, \"model at \" << i << \" is not CR-CIRPP\");\n    return tmp;\n}\n\ninline const boost::shared_ptr<EqBsParametrization> CrossAssetModel::eqbs(const Size name) const {\n    boost::shared_ptr<EqBsParametrization> tmp = boost::dynamic_pointer_cast<EqBsParametrization>(p_[idx(EQ, name)]);\n    QL_REQUIRE(tmp, \"model at \" << name << \" is not EQ-BS\");\n    return tmp;\n}\n\ninline Real CrossAssetModel::numeraire(const Size ccy, const Time t, const Real x,\n                                       Handle<YieldTermStructure> discountCurve) const {\n    return lgm(ccy)->numeraire(t, x, discountCurve);\n}\n\ninline Real CrossAssetModel::bankAccountNumeraire(const Size ccy, const Time t, const Real x, const Real y,\n                                                  Handle<YieldTermStructure> discountCurve) const {\n    return lgm(ccy)->bankAccountNumeraire(t, x, y, discountCurve);\n}\n\ninline Real CrossAssetModel::discountBond(const Size ccy, const Time t, const Time T, const Real x,\n                                          Handle<YieldTermStructure> discountCurve) const {\n    return lgm(ccy)->discountBond(t, T, x, discountCurve);\n}\n\ninline Real CrossAssetModel::reducedDiscountBond(const Size ccy, const Time t, const Time T, const Real x,\n                                                 Handle<YieldTermStructure> discountCurve) const {\n    return lgm(ccy)->reducedDiscountBond(t, T, x, discountCurve);\n}\n\ninline Real CrossAssetModel::discountBondOption(const Size ccy, Option::Type type, const Real K, const Time t,\n                                                const Time S, const Time T,\n                                                Handle<YieldTermStructure> discountCurve) const {\n    return lgm(ccy)->discountBondOption(type, K, t, S, T, discountCurve);\n}\n\ninline const boost::shared_ptr<FxBsParametrization> CrossAssetModel::fxbs(const Size ccy) const {\n    boost::shared_ptr<FxBsParametrization> tmp = boost::dynamic_pointer_cast<FxBsParametrization>(p_[idx(FX, ccy)]);\n    QL_REQUIRE(tmp, \"model at \" << ccy << \" is not FX-BS\");\n    return tmp;\n}\n\ninline const Matrix& CrossAssetModel::correlation() const { return rho_; }\n\ninline const boost::shared_ptr<Integrator> CrossAssetModel::integrator() const { return integrator_; }\n\ninline Handle<DefaultProbabilityTermStructure> CrossAssetModel::crTs(const Size i) const {\n    if (modelType(CR, i) == LGM1F)\n        return crlgm1f(i)->termStructure();\n    if (modelType(CR, i) == CIRPP)\n        return crcirpp(i)->termStructure();\n    QL_FAIL(\"model at \" << i << \" is not CR-*\");\n}\n\ninline std::pair<Real, Real> CrossAssetModel::crS(const Size i, const Size ccy, const Time t, const Time T,\n                                                  const Real z, const Real y) const {\n    if (modelType(CR, i) == LGM1F)\n        return crlgm1fS(i, ccy, t, T, z, y);\n    if (modelType(CR, i) == CIRPP) {\n        QL_REQUIRE(ccy == 0, \"CrossAssetModelPlus::crS() only implemented for ccy=0, got \" << ccy);\n        return crcirppS(i, t, T, z, y);\n    }\n    QL_FAIL(\"model at \" << i << \" is not CR-*\");\n}\n\n} // namespace QuantExt\n\n#endif\n", "meta": {"hexsha": "f0dbd2233bad81241a32b47ee6799b6197721086", "size": 31116, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "QuantExt/qle/models/crossassetmodel.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": "QuantExt/qle/models/crossassetmodel.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": "QuantExt/qle/models/crossassetmodel.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": 50.67752443, "max_line_length": 120, "alphanum_fraction": 0.6510155547, "num_tokens": 7060, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7217432182679956, "lm_q2_score": 0.45326184801538616, "lm_q1q2_score": 0.3271386649047239}}
{"text": "//State Vector- variable acceleration model\n\t// X(0) = quad_position.point.x;\n    // X(1) = quad_velocity.point.x;\n    // X(2) = quad_acc.point.x;\n    // X(3) = quad_position.point.y;\n    // X(4) = quad_velocity.point.y;\n    // X(5) = quad_acc.point.y;\n    // X(6) = quad_position.point.z;\n    // X(7) = quad_velocity.point.z;\n    // X(8) = quad_acc.point.z;\n\t// X(9)  = leader.point.x;\n    // X(10) = leader.point.y;\n    // X(11) = leader.point.z;\n\t// X(12) = neighbor.point.x;\n\t// X(13) = neighbor.point.y;\n\t// X(14) = neighbor.point.z;\n///measeurement Vector\n    //1.\n\t// Y(0) = quad.imu.acc.x\n\t// Y(1) = 0\n\t// Y(2) = 0\n\t// Y(3) = quad.imu.acc.y\n\t// Y(4) = 0\n\t// Y(5) = 0\n\t// Y(6) = quad.imu.acc.z\n\t// Y(7) = 0\n\t// Y(8) = 0\n    //2.\n    // Y(0) = quad.imu.vel.x\n    // Y(1) = 0\n    // Y(2) = 0\n    // Y(3) = quad.imu.vel.y\n    // Y(4) = 0\n    // Y(5) = 0\n    // Y(6) = quad.imu.vel.z\n    // Y(7) = 0\n    // Y(8) = 0\n    //3.\n\t// Y() = leader_quad.point.x\n\t// Y() = leader_quad.point.y\n\t// Y() = leader_quad.point.z\n    //4.\n\t// Y() = neighbor_quad.point.x\n\t// Y() = neighbor_quad.point.y\n\t// Y() = neighbor_quad.point.z\n\n#include <Eigen/Dense>\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n#include <bits/stdc++.h>\n#include <ros/ros.h>\n#include <math.h>\n#include <stdio.h>\n#include <dwm1001/anchor.h> \n#include <sensor_msgs/Imu.h>\n#include \"std_msgs/MultiArrayLayout.h\"\n#include \"std_msgs/MultiArrayDimension.h\"\n#include \"std_msgs/Float32MultiArray.h\"\n#include \"geometry_msgs/PoseStamped.h\"\n#include \"geometry_msgs/Vector3Stamped.h\"\n#include \"geometry_msgs/TwistStamped.h\"\n\n// Declarations\n\ndouble r_pred_l,r_meas_l;\ndouble R_l;\ndouble m_R_scale_l,sigma_r_l;\n//double error_l;\ndouble precisionRangeErrEst_l;\nEigen::MatrixXd H_l(1,15);\nEigen::VectorXd K_l(15);\nEigen::VectorXd Ze_r_l(15);\nEigen::MatrixXd Om_r_l(15,15);\nEigen::VectorXd X_r_l(15);\n//\ndouble r_pred_n,r_meas_n;\ndouble R_n;\ndouble m_R_scale_n,sigma_r_n;\n//double error_n;\ndouble precisionRangeErrEst_n;\nEigen::MatrixXd H_n(1,15);\nEigen::VectorXd K_n(15);\nEigen::VectorXd Ze_r_n(15);\nEigen::MatrixXd Om_r_n(15,15);\nEigen::VectorXd X_r_n(15);\n//\nEigen::Quaternionf q;\nEigen::MatrixXf R_mat(3,3);\nEigen::MatrixXf imuacc(3,1);\nEigen::MatrixXf acc(3,1);\ndouble r_acc;\nEigen::MatrixXd r_meas_acc(3,1);\nEigen::MatrixXd H_acc(3,15);\nEigen::MatrixXd R_acc(3,3);\nEigen::MatrixXd K_acc(15,3);\nEigen::MatrixXd Om_acc(15,15);\nEigen::VectorXd Ze_acc(15);\nEigen::VectorXd X_acc(15);\n//\ndouble r_vel;\nEigen::MatrixXd r_meas_vel(3,1);\nEigen::MatrixXd H_vel(3,15);\nEigen::MatrixXd R_vel(3,3);\nEigen::MatrixXd K_vel(15,3);\nEigen::MatrixXd Om_vel(15,15);\nEigen::VectorXd Ze_vel(15);\nEigen::VectorXd X_vel(15);\n//\ndouble r_pos_l;\nEigen::MatrixXd pos_meas_l(3,1);\nEigen::MatrixXd H_pos_l(3,15);\nEigen::MatrixXd R_pos_l(3,3);\nEigen::MatrixXd K_pos_l(15,3);\nEigen::MatrixXd Om_pos_l(15,15);\nEigen::VectorXd Ze_pos_l(15);\nEigen::VectorXd X_pos_l(15);\n//\ndouble r_pos_n;\nEigen::MatrixXd pos_meas_n(3,1);\nEigen::MatrixXd H_pos_n(3,15);\nEigen::MatrixXd R_pos_n(3,3);\nEigen::MatrixXd K_pos_n(15,3);\nEigen::MatrixXd Om_pos_n(15,15);\nEigen::VectorXd Ze_pos_n(15);\nEigen::VectorXd X_pos_n(15);\n//\ndouble R_h,r_h,h_meas;\nEigen::MatrixXd H_h(1,15);\nEigen::MatrixXd Om_h(15,15);\nEigen::VectorXd Ze_h(15);\nEigen::VectorXd X_h(15);\n//\nEigen::VectorXd X(15);\nEigen::VectorXd u(15);\nEigen::VectorXd X_e(15);\nEigen::MatrixXd F(15,15);\nEigen::MatrixXd block_F(3,3);\nEigen::MatrixXd B(15,15);\nEigen::MatrixXd block_B(3,3);\nEigen::MatrixXd Q(15,15);\nEigen::MatrixXd block_Q(3,3);\nEigen::MatrixXd Q_lead(3,3);\nEigen::MatrixXd Q_neigh(3,3);\nEigen::MatrixXd Om_p(15,15);\nEigen::VectorXd Ze_p(15);\nEigen::MatrixXd Om(15,15);\nEigen::VectorXd Ze(15);\ngeometry_msgs::Vector3Stamped pose;\ngeometry_msgs::Vector3Stamped vel;\ngeometry_msgs::Vector3Stamped acc_;\nstd_msgs::Float32MultiArray output;\ndouble tao_bias,m_y_damping_factor;\ndouble T,error;\ndouble m_last_range_time;\ndouble error_threshold;\ndouble T_sq,m_tao_bias_sqrt,T_cub,m_z_damping_factor,m_Q_scale;\ndouble x,y,z,x_l,y_l,z_l,x_n,y_n,z_n;\ndouble q_l,q_n;\n\n\n\nvoid setVector(Eigen::VectorXd Y)\n{\n    Ze = Y;\n    \n}\nvoid setMatrix(Eigen::MatrixXd S)\n{\n    Om = S;\n}\n\n//void prediction_step(const sensor_msgs::Imu::ConstPtr& msg)\nvoid prediction_step()\n{\n    T = ros::Time::now().toSec() - m_last_range_time;\n    int static count =0 ;\n    if(count < 5)\n       {ROS_WARN(\"prediction_step\");\n        count++;\n        T = 0.0301735 ;}\n    \n\n    T_sq = std::pow(T,2);\n    T_cub = std::pow(T,3);\n    // F is a 9x9 State Transition Matrix\n    F = Eigen::MatrixXd::Zero(15,15);\n    block_F << 1, T, -T_sq/2.0,\n               0, 1, -T,\n               0, 0, 1;\n    F.block<3,3>(0,0) = block_F;\n    F.block<3,3>(3,3) = block_F;\n    F.block<3,3>(6,6) = block_F;\n    F.block<6,6>(9,9) = Eigen::MatrixXd::Identity(6,6);\n\n\n    //std::cout << F << '\\n'<<'\\n'; \n\n    // Q is the acceleration model\n    tao_bias = m_tao_bias_sqrt * m_tao_bias_sqrt;\n    Q = Eigen::MatrixXd::Zero(15,15);\n    \n    block_Q << (T_cub*T_sq)/20.0,   (T_sq*T_sq)/8.0 ,   -T_cub/6,\n        \t   (T_sq*T_sq)/8.0 ,    (T_cub)/3,          -T_sq/2,\n         \t    T_cub/6.0,\t\t     -T_sq/2 ,               T  ;\n    block_Q *= tao_bias;\n\n\n    Q.block<3,3>(0,0) = block_Q;\n    Q.block<3,3>(3,3) = block_Q * m_y_damping_factor ;\n    Q.block<3,3>(6,6) = block_Q * m_z_damping_factor;\n    Q.block<3,3>(9,9) = Q_lead;\n    Q.block<3,3>(12,12) = Q_neigh;\n    Q *= m_Q_scale;\n    //ROS_WARN(\"covariance:## %f, ## %f, ## %f\",(T_cub*tao_acc/3.0)+(T_cub*T_sq)*tao_bias/20.0 , T*tao_acc+(T_cub*tao_bias/3), T*tao_bias);\n   \n    // if(count%50 == 1)\n    // std::cout << X << '\\n'<<'\\n';\n    // M is the predicted covariance matrix\n    // X is the predicted state vector\n    X = Om.inverse() * Ze;\n    Om_p = (F *Om.inverse() * F.transpose()) + Q ;\n    Om_p = Om_p.inverse();\n    X = F * X ;\n    Ze_p = Om_p * X;\n   //  q = Eigen::Quaternionf(msg->orientation.w, msg->orientation.x, msg->orientation.y, msg->orientation.z);\n   //  R_mat= q.toRotationMatrix();\n   //  imuacc << msg->linear_acceleration.x,msg->linear_acceleration.y,msg->linear_acceleration.z;\n   //  acc= R_mat*imuacc;\n   //  B = Eigen::MatrixXd::Zero(15,15);\n   //  block_B << T_sq/2.0,  0,  0,\n   //             T      ,  0,  0,\n   //             1      ,  0,  0;\n   //  B.block<3,3>(0,0) = block_B;\n   //  B.block<3,3>(3,3) = block_B;\n   //  B.block<3,3>(6,6) = block_B;\n   //  B.block<6,6>(9,9) = Eigen::MatrixXd::Identity(6,6);;\n   //  u<<acc(0,0),0,0,\n   //    -acc(1,0),0,0,\n   // acc(2,0)-9.8,0,0,\n   // 0,0,0,0,0,0; \n\n   //  X = F * X + B * u;\n   //  Ze_p = Om_p * X; \n    // time update\n    \n    //count++;\n    // setState(X_e);\n    // setCovariance(M);\n        \n        pose.vector.x=X(0);\n        pose.vector.y=X(3);\n        pose.vector.z=X(6);\n\n        \n        vel.vector.x=X(1);\n        vel.vector.y=X(4);\n        vel.vector.z=X(7);\n\n\n        acc_.vector.x=X(2);\n        acc_.vector.y=X(5);\n        acc_.vector.z=X(8);\n    //    fused.publish(output);\n\n\n    // if(error < error_threshold){\n    //     //ROS_WARN(\"\\n sucess too large: %f\", error);\n        setVector(Ze_p);\n        setMatrix(Om_p);\n        //std::cout << X << '\\n'<<'\\n';\n    //     return ;\n    // } else {\n\n    //     ROS_WARN(\"\\n Estimate too large: %f\", error);\n    //     return ;\n    // }\n    // count++;\n    m_last_range_time = ros::Time::now().toSec();    \n}\n\n\n\nvoid correction_step_imu(const sensor_msgs::Imu::ConstPtr& msg)\n{   \n    int static count =0 ;\n    if(count == 0)\n       {ROS_WARN(\"imu_step\");\n        count++; }\n\n    //conerts the acceleration from body frame to earth frame(NED) \n    q = Eigen::Quaternionf(msg->orientation.w, msg->orientation.x, msg->orientation.y, msg->orientation.z);\n    R_mat= q.toRotationMatrix();\n    \n    imuacc << msg->linear_acceleration.x,msg->linear_acceleration.y,msg->linear_acceleration.z;\n    acc= R_mat*imuacc;\n    acc(0,0)=acc(0,0);\n    acc(1,0)=acc(1,0);\n    acc(2,0)=(acc(2,0)-9.8);\n\n    r_meas_acc << acc(0,0),acc(1,0),acc(2,0);\n    // K is the Kalman Gain\n    R_acc = Eigen::MatrixXd::Identity(3,3) * (r_acc*r_acc);\n    R_acc(1,1) = R_acc(1,1) ;\n    R_acc(2,2) = R_acc(2,2) * m_z_damping_factor;\n    //ROS_WARN(\"R_matrix:## %f\",R);\n    // Update the state\n    R_acc = R_acc.inverse();\n    Om_acc = Om + (H_acc.transpose() * R_acc * H_acc) ; \n    Ze_acc = Ze + (H_acc.transpose() * R_acc * r_meas_acc) ;\n\n    X_acc = Om_acc.inverse() * Ze_acc;\n\nif(abs(X_acc(0)-X(0)) < error_threshold && abs(X_acc(3)-X(3)) < error_threshold && abs(X_acc(6)-X(6)) < error_threshold )\n    {   setVector(Ze_acc);\n        setMatrix(Om_acc);\n    }\n\n}\n\n\nvoid correction_step_vel(const geometry_msgs::TwistStamped::ConstPtr& msg)\n{\n    int static count =0 ;\n    if(count == 0)\n       {ROS_WARN(\"vel_step\");\n        count++; }\n\n\n    r_meas_vel << msg->twist.linear.x,msg->twist.linear.y,msg->twist.linear.z;\n    // K is the Kalman Gain\n    R_vel = Eigen::MatrixXd::Identity(3,3) * (r_vel*r_vel);\n    R_vel(1,1) = R_vel(1,1) ;\n    R_vel(2,2) = R_vel(2,2) * m_z_damping_factor;\n    //ROS_WARN(\"R_matrix:## %f\",R);\n    R_vel = R_vel.inverse();\n    Om_vel = Om + (H_vel.transpose() * R_vel * H_vel) ; \n    Ze_vel = Ze + (H_vel.transpose() * R_vel * r_meas_vel) ;\n\n        setVector(Ze_vel);\n        setMatrix(Om_vel);\n    X_vel = Om_vel.inverse() * Ze_vel;\n\nif(abs(X_vel(0)-X(0)) < error_threshold && abs(X_vel(3)-X(3)) < error_threshold && abs(X_vel(6)-X(6)) < error_threshold )\n    {   setVector(Ze_vel);\n        setMatrix(Om_vel);\n    }\n\n\n}\n\n\n\nvoid correction_step_leader(const dwm1001::anchor::ConstPtr& msg)\n{\t\n    int static count =0 ;\n    if(count == 0)\n       {ROS_WARN(\"leader_r_step\");\n        count++; }\n\n\tr_pred_l = std::sqrt( std::pow(X(0) -  X(9), 2) +\n                          std::pow(X(3) - X(10), 2) +\n                          std::pow(X(6) - X(11), 2) ) + 1e-5;\n\n\tr_meas_l = msg->range;\n    // H is the linearized measurement matrix\n    H_l << (X(0) -  X(9))/r_pred_l, 0, 0,\n           (X(3) - X(10))/r_pred_l, 0, 0,\n           (X(6) - X(11))/r_pred_l, 0, 0,\n           (X(9) - X(0))/r_pred_l, (X(10) - X(3))/r_pred_l, (X(11) - X(6))/r_pred_l,\n         \t0,\t0,\t0;\n\n    // K is the Kalman Gain\n    sigma_r_l = double(precisionRangeErrEst_l) / 1000.0;\n    R_l = std::pow(sigma_r_l,2) * m_R_scale_l;\n    //ROS_WARN(\"R_matrix:## %f\",R);\n    R_l = 1/R_l;\n    Om_r_l = Om + (H_l.transpose() * R_l * H_l) ; \n    Ze_r_l = Ze + (H_l.transpose() * R_l * (r_meas_l - r_pred_l + (H_l*X)(0,0) )) ;\n\n        \n    X_r_l = Om_r_l.inverse() * Ze_r_l;\n\nif(abs(X_r_l(0)-X(0)) < error_threshold && abs(X_r_l(3)-X(3)) < error_threshold && abs(X_r_l(6)-X(6)) < error_threshold )\n    {   setVector(Ze_r_l);\n        setMatrix(Om_r_l);\n    }\n}\n\n\n\nvoid correction_step_neigh(const dwm1001::anchor::ConstPtr& msg)\n{\t\n    int static count =0 ;\n    if(count == 0)\n       {ROS_WARN(\"neghbor_r_step\");\n        count++; }\n\n\tr_pred_n = std::sqrt( std::pow(X(0) - X(12), 2) +\n                          std::pow(X(3) - X(13), 2) +\n                          std::pow(X(6) - X(14), 2) ) + 1e-5;\n\n\tr_meas_n = msg->range;\n    // H is the linearized measurement matrix\n    H_n << (X(0) - X(12))/r_pred_n, 0, 0,\n           (X(3) - X(13))/r_pred_n, 0, 0,\n           (X(6) - X(14))/r_pred_n, 0, 0,\n         \t0,\t0,\t0,\n           (X(12) - X(0))/r_pred_n, (X(13) - X(3))/r_pred_n, (X(14) - X(6))/r_pred_n ;\n\n    // K is the Kalman Gain\n    sigma_r_n = double(precisionRangeErrEst_n) / 1000.0;\n    R_n = std::pow(sigma_r_n,2) * m_R_scale_n;\n    //ROS_WARN(\"R_matrix:## %f\",R);\n    R_n = 1/R_n;\n    Om_r_n = Om + (H_n.transpose() * R_n * H_n) ; \n    Ze_r_n = Ze + (H_n.transpose() * R_n * (r_meas_n - r_pred_n + (H_n*X)(0,0) )) ;\n\n        \n    X_r_n = Om_r_n.inverse() * Ze_r_n;\n\nif(abs(X_r_n(0)-X(0)) < error_threshold && abs(X_r_n(3)-X(3)) < error_threshold && abs(X_r_n(6)-X(6)) < error_threshold )\n    {   setVector(Ze_r_n);\n        setMatrix(Om_r_n);\n    }\n\n}\n\n\nvoid position_lead_cb(const geometry_msgs::PoseStamped::ConstPtr& msg)\n{\n    int static count =0 ;\n    if(count == 0)\n       {ROS_WARN(\"leader_pos_step\");\n        count++; }\n    pos_meas_l << msg->pose.position.x,msg->pose.position.y,msg->pose.position.z;\n    // K is the Kalman Gain\n    R_pos_l = Eigen::MatrixXd::Identity(3,3) * (r_pos_l*r_pos_l);\n    //ROS_WARN(\"R_matrix:## %f\",R);\n\n    R_pos_l = R_pos_l.inverse();\n    Om_pos_l = Om + (H_pos_l.transpose() * R_pos_l * H_pos_l) ; \n    Ze_pos_l = Ze + (H_pos_l.transpose() * R_pos_l * pos_meas_l) ;\n\n    X_pos_l = Om_pos_l.inverse() * Ze_pos_l;\n\nif(abs(X_pos_l(0)-X(0)) < error_threshold && abs(X_pos_l(3)-X(3)) < error_threshold && abs(X_pos_l(6)-X(6)) < error_threshold )\n    {   setVector(Ze_pos_l);\n        setMatrix(Om_pos_l);\n    }\n}\n\n\n\nvoid position_neigh_cb(const geometry_msgs::PoseStamped::ConstPtr& msg)\n{\n    int static count =0 ;\n    if(count == 0)\n       {ROS_WARN(\"neighbor_pos_step\");\n        count++; }\n    pos_meas_n << msg->pose.position.x,msg->pose.position.y,msg->pose.position.z;\n    // K is the Kalman Gain\n    R_pos_n = Eigen::MatrixXd::Identity(3,3) * (r_pos_n*r_pos_n);\n    //ROS_WARN(\"R_matrix:## %f\",R);\n\n    R_pos_n = R_pos_n.inverse();\n    Om_pos_n = Om + (H_pos_n.transpose() * R_pos_n * H_pos_n) ; \n    Ze_pos_n = Ze + (H_pos_n.transpose() * R_pos_n * pos_meas_n) ;\n\n    X_pos_n = Om_pos_n.inverse() * Ze_pos_n;\n\nif(abs(X_pos_n(0)-X(0)) < error_threshold && abs(X_pos_n(3)-X(3)) < error_threshold && abs(X_pos_n(6)-X(6)) < error_threshold )\n    {   setVector(Ze_pos_n);\n        setMatrix(Om_pos_n);\n    }\n\n}\n\n\nvoid height_cb(const geometry_msgs::PoseStamped::ConstPtr& msg)\n{\n    int static count =0 ;\n    if(count == 0)\n       {ROS_WARN(\"height_cb\");\n        count++; }\n    h_meas = msg->pose.position.z;\n    // K is the Kalman Gain\n    R_h = r_h*r_h;\n    //ROS_WARN(\"R_matrix:## %f\",R);\n\n    R_h = 1/R_h;\n    Om_h = Om + (H_h.transpose() * R_h * H_h) ; \n    Ze_h = Ze + (H_h.transpose() * R_h * h_meas) ;\n\n        setVector(Ze_h);\n        setMatrix(Om_h);\n    X_h = Om_h.inverse() * Ze_h;\n\nif(abs(X_h(0)-X(0)) < error_threshold && abs(X_h(3)-X(3)) < error_threshold && abs(X_h(6)-X(6)) < error_threshold )\n    {   setVector(Ze_h);\n        setMatrix(Om_h);\n    }\n\n\n}\n\n\n\nvoid param(ros::NodeHandle& nh)\n{\n    nh.getParam(\"IKalmanFilter_swarm/start_x\", x);\n    nh.getParam(\"IKalmanFilter_swarm/start_y\", y);\n    nh.getParam(\"IKalmanFilter_swarm/start_z\", z);\n    nh.getParam(\"IKalmanFilter_swarm/lead_x\", x_l);\n    nh.getParam(\"IKalmanFilter_swarm/lead_y\", y_l);\n    nh.getParam(\"IKalmanFilter_swarm/lead_z\", z_l);\n    nh.getParam(\"IKalmanFilter_swarm/neighbor_x\", x_n);\n    nh.getParam(\"IKalmanFilter_swarm/neighbor_y\", y_n);\n    nh.getParam(\"IKalmanFilter_swarm/neighbor_z\", z_n);\n    nh.getParam(\"IKalmanFilter_swarm/leader_covariance\", q_l);\n    nh.getParam(\"IKalmanFilter_swarm/neighbor_covariance\", q_n);\n    nh.getParam(\"IKalmanFilter_swarm/m_tao_bias_sqrt\", m_tao_bias_sqrt );\n    nh.getParam(\"IKalmanFilter_swarm/m_y_damping_factor\", m_y_damping_factor);\n    nh.getParam(\"IKalmanFilter_swarm/m_z_damping_factor\", m_z_damping_factor);\n    nh.getParam(\"IKalmanFilter_swarm/m_Q_scale\", m_Q_scale);\n    nh.getParam(\"IKalmanFilter_swarm/error_threshold\", error_threshold);\n    nh.getParam(\"IKalmanFilter_swarm/m_R_scale_leader\", m_R_scale_l);\n    nh.getParam(\"IKalmanFilter_swarm/precisionRangeErrEst_leader\", precisionRangeErrEst_l);\n    nh.getParam(\"IKalmanFilter_swarm/m_R_scale_neighbor\", m_R_scale_n);\n    nh.getParam(\"IKalmanFilter_swarm/precisionRangeErrEst_neighbor\", precisionRangeErrEst_n);\n    nh.getParam(\"IKalmanFilter_swarm/r_acc\", r_acc);\n    nh.getParam(\"IKalmanFilter_swarm/r_vel\", r_vel);\n    nh.getParam(\"IKalmanFilter_swarm/r_pos_l\", r_pos_l);\n    nh.getParam(\"IKalmanFilter_swarm/r_pos_n\", r_pos_n);\n    nh.getParam(\"IKalmanFilter_swarm/r_h\", r_h);\n\n    ROS_WARN(\"%f, %f, %f \",x,y,z);\n}\n\n\nvoid Initialize(ros::NodeHandle& nh)\n{\n \n    param(nh);\n\n    X<<x,0,0,y,0,0,z,0,0,x_l,y_l,z_l,x_n,y_n,z_n; \n    Eigen::MatrixXd nine_cov = Eigen::MatrixXd::Identity(15,15);\n    nine_cov(0,0) = 0.001;\n    nine_cov(3,3) = 0.001;\n    nine_cov(6,6) = 0.001;\n    // set cov of vel\n    nine_cov(1,1) = 0.01;\n    nine_cov(4,4) = 0.01;\n    nine_cov(7,7) = 0.01;\n    // set cov of acc_bias\n    nine_cov(2,2) = 0.01;\n    nine_cov(5,5) = 0.01;\n    nine_cov(8,8) = 0.01;\n\n    nine_cov(9,9)   = 0.001;\n    nine_cov(10,10) = 0.001;\n    nine_cov(11,11) = 0.001;\n\n    nine_cov(12,12) = 0.001;\n    nine_cov(13,13) = 0.001;\n    nine_cov(14,14) = 0.001;\n    nine_cov = nine_cov*100;\n    nine_cov = nine_cov.inverse();\n    setMatrix(nine_cov);\n    setVector(nine_cov*X);\n\n  \n    Q_lead <<  q_l,  0,  0,\n                0, q_l, 0,\n                0,  0,  q_l ;\n    Q_neigh << q_n,  0,  0,\n                0, q_n, 0,\n                0,  0,  q_n ;\n        // H is the linearized measurement matrix\n    H_acc << 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n             0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n             0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0;\n        // H is the linearized measurement matrix\n    H_vel << 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n             0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n             0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0;\n        // H is the linearized measurement matrix\n    H_pos_l << 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0,\n               0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0,\n               0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0;\n        // H is the linearized measurement matrix\n    H_pos_n << 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0,\n               0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0,\n               0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1;\n\n    H_h << 0,0,0,0,0,0,1,0,0,0,0,0,0,0,0;\n\n    m_last_range_time = ros::Time::now().toSec();\n\n}\n\n\nint main(int argc, char** argv){\n\n    ros::init(argc,argv,\"IKalmanFilter_swarm\");\n    ros::NodeHandle nh;     \n    //Initializinging the parameters\n    Initialize(nh);\n    //param(nh);\n    //Subscriber and Publisher for the data. remapped in the launch file to the topic required\n    ros::Subscriber quad_imu = nh.subscribe(\"imu\",20,correction_step_imu);\n    ros::Subscriber quad_vel = nh.subscribe(\"velocity\",20,correction_step_vel);\n    ros::Subscriber anchor_1 = nh.subscribe(\"anchor_lead\", 20,correction_step_leader);\n    ros::Subscriber anchor_2 = nh.subscribe(\"anchor_neigh\",20,correction_step_neigh);\n    ros::Subscriber anchor_3 = nh.subscribe(\"position_leader\",20,position_lead_cb);\n    ros::Subscriber anchor_4 = nh.subscribe(\"position_neighour\",20,position_neigh_cb);\n    ros::Subscriber height = nh.subscribe(\"height\",20,height_cb);\n\n    //ros::Publisher fused = nh.advertise<std_msgs::Float32MultiArray>(\"Filtered_data\", 100);\n    ros::Publisher fused_pose = nh.advertise<geometry_msgs::Vector3Stamped>(\"Filtered_pose\", 10);\n    ros::Publisher fused_vel = nh.advertise<geometry_msgs::Vector3Stamped>(\"Filtered_velocity\", 10);\n    ros::Publisher fused_acc = nh.advertise<geometry_msgs::Vector3Stamped>(\"Filtered_acc\", 10);\n\n    ros::Rate loop_rate(50);\n    while(ros::ok()){\n    //\toutput.data.clear();\n\t//\tfor (int i = 0; i < 15; i++)\n\t//\t\toutput.data.push_back(X(i));\n        prediction_step();\n\t\tpose.header.stamp = ros::Time::now();\n        vel.header.stamp = ros::Time::now();\n        acc_.header.stamp = ros::Time::now();\n        fused_pose.publish(pose);\n        fused_vel.publish(vel);\n        fused_acc.publish(acc_);\n\n        ros::spinOnce();\n        loop_rate.sleep();\n    }\n    return 0;\n}  ", "meta": {"hexsha": "e42b4a93197106c1ad5a4c489a8e13ec59ec43ab", "size": 19373, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "gazebo_sim/gps_denied/src/ikf_swarm.cpp", "max_stars_repo_name": "naveenbiitk/State_Estimation", "max_stars_repo_head_hexsha": "ed6f00355745ba16dcbbe5bf794fd9be56a1d999", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-05-05T06:19:20.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-05T06:19:20.000Z", "max_issues_repo_path": "gazebo_sim/gps_denied/src/ikf_swarm.cpp", "max_issues_repo_name": "naveenbiitk/State_Estimation", "max_issues_repo_head_hexsha": "ed6f00355745ba16dcbbe5bf794fd9be56a1d999", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "gazebo_sim/gps_denied/src/ikf_swarm.cpp", "max_forks_repo_name": "naveenbiitk/State_Estimation", "max_forks_repo_head_hexsha": "ed6f00355745ba16dcbbe5bf794fd9be56a1d999", "max_forks_repo_licenses": ["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.2703125, "max_line_length": 139, "alphanum_fraction": 0.5965002839, "num_tokens": 6884, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7217432062975979, "lm_q2_score": 0.45326184801538616, "lm_q1q2_score": 0.32713865947899934}}
{"text": "#ifndef BOOST_GEOMETRY_PROJECTIONS_TMERC_HPP\n#define BOOST_GEOMETRY_PROJECTIONS_TMERC_HPP\n\n// Boost.Geometry - extensions-gis-projections (based on PROJ4)\n// This file is automatically generated. DO NOT EDIT.\n\n// Copyright (c) 2008-2012 Barend Gehrels, Amsterdam, the Netherlands.\n\n// Use, modification and distribution is subject to the Boost Software License,\n// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n\n// This file is converted from PROJ4, http://trac.osgeo.org/proj\n// PROJ4 is originally written by Gerald Evenden (then of the USGS)\n// PROJ4 is maintained by Frank Warmerdam\n// PROJ4 is converted to Boost.Geometry by Barend Gehrels\n\n// Original copyright notice:\n \n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the \"Software\"),\n// to deal in the Software without restriction, including without limitation\n// the rights to use, copy, modify, merge, publish, distribute, sublicense,\n// and/or sell copies of the Software, and to permit persons to whom the\n// Software is furnished to do so, subject to the following conditions:\n\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n// DEALINGS IN THE SOFTWARE.\n\n#include <boost/concept_check.hpp>\n#include <boost/math/special_functions/hypot.hpp>\n\n#include <boost/geometry/extensions/gis/projections/impl/base_static.hpp>\n#include <boost/geometry/extensions/gis/projections/impl/base_dynamic.hpp>\n#include <boost/geometry/extensions/gis/projections/impl/projects.hpp>\n#include <boost/geometry/extensions/gis/projections/impl/factory_entry.hpp>\n#include <boost/geometry/extensions/gis/projections/impl/function_overloads.hpp>\n#include <boost/geometry/extensions/gis/projections/impl/pj_mlfn.hpp>\n\n#include <boost/geometry/extensions/gis/projections/epsg_traits.hpp>\n\nnamespace boost { namespace geometry { namespace projections\n{\n    #ifndef DOXYGEN_NO_DETAIL\n    namespace detail { namespace tmerc{ \n            static const double EPS10 = 1.e-10;\n            static const double FC1 = 1.;\n            static const double FC2 = .5;\n            static const double FC3 = .16666666666666666666;\n            static const double FC4 = .08333333333333333333;\n            static const double FC5 = .05;\n            static const double FC6 = .03333333333333333333;\n            static const double FC7 = .02380952380952380952;\n            static const double FC8 = .01785714285714285714;\n\n            struct par_tmerc\n            {\n                double    esp;\n                double    ml0;\n                double    en[EN_SIZE];\n            };\n\n            // template class, using CRTP to implement forward/inverse\n            template <typename Geographic, typename Cartesian, typename Parameters>\n            struct base_tmerc_ellipsoid : public base_t_fi<base_tmerc_ellipsoid<Geographic, Cartesian, Parameters>,\n                     Geographic, Cartesian, Parameters>\n            {\n\n                 typedef double geographic_type;\n                 typedef double cartesian_type;\n\n                par_tmerc m_proj_parm;\n\n                inline base_tmerc_ellipsoid(const Parameters& par)\n                    : base_t_fi<base_tmerc_ellipsoid<Geographic, Cartesian, Parameters>,\n                     Geographic, Cartesian, Parameters>(*this, par) {}\n\n                inline void fwd(geographic_type& lp_lon, geographic_type& lp_lat, cartesian_type& xy_x, cartesian_type& xy_y) const\n                {\n                    double al, als, n, cosphi, sinphi, t;\n                \n                        /*\n                         * Fail if our longitude is more than 90 degrees from the \n                         * central meridian since the results are essentially garbage. \n                         * Is error -20 really an appropriate return value?\n                         * \n                         *  http://trac.osgeo.org/proj/ticket/5\n                         */\n                        if( lp_lon < -HALFPI || lp_lon > HALFPI )\n                        {\n                            xy_x = HUGE_VAL;\n                            xy_y = HUGE_VAL;\n                            throw proj_exception( -14 );\n                            return;\n                        }\n                \n                    sinphi = sin(lp_lat); cosphi = cos(lp_lat);\n                    t = fabs(cosphi) > 1e-10 ? sinphi/cosphi : 0.;\n                    t *= t;\n                    al = cosphi * lp_lon;\n                    als = al * al;\n                    al /= sqrt(1. - this->m_par.es * sinphi * sinphi);\n                    n = this->m_proj_parm.esp * cosphi * cosphi;\n                    xy_x = this->m_par.k0 * al * (FC1 +\n                        FC3 * als * (1. - t + n +\n                        FC5 * als * (5. + t * (t - 18.) + n * (14. - 58. * t)\n                        + FC7 * als * (61. + t * ( t * (179. - t) - 479. ) )\n                        )));\n                    xy_y = this->m_par.k0 * (pj_mlfn(lp_lat, sinphi, cosphi, this->m_proj_parm.en) - this->m_proj_parm.ml0 +\n                        sinphi * al * lp_lon * FC2 * ( 1. +\n                        FC4 * als * (5. - t + n * (9. + 4. * n) +\n                        FC6 * als * (61. + t * (t - 58.) + n * (270. - 330 * t)\n                        + FC8 * als * (1385. + t * ( t * (543. - t) - 3111.) )\n                        ))));\n                }\n\n                inline void inv(cartesian_type& xy_x, cartesian_type& xy_y, geographic_type& lp_lon, geographic_type& lp_lat) const\n                {\n                    double n, con, cosphi, d, ds, sinphi, t;\n                \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);\n                    if (fabs(lp_lat) >= HALFPI) {\n                        lp_lat = xy_y < 0. ? -HALFPI : HALFPI;\n                        lp_lon = 0.;\n                    } else {\n                        sinphi = sin(lp_lat);\n                        cosphi = cos(lp_lat);\n                        t = fabs(cosphi) > 1e-10 ? sinphi/cosphi : 0.;\n                        n = this->m_proj_parm.esp * cosphi * cosphi;\n                        d = xy_x * sqrt(con = 1. - this->m_par.es * sinphi * sinphi) / this->m_par.k0;\n                        con *= t;\n                        t *= t;\n                        ds = d * d;\n                        lp_lat -= (con * ds / (1.-this->m_par.es)) * FC2 * (1. -\n                            ds * FC4 * (5. + t * (3. - 9. *  n) + n * (1. - 4 * n) -\n                            ds * FC6 * (61. + t * (90. - 252. * n +\n                                45. * t) + 46. * n\n                           - ds * FC8 * (1385. + t * (3633. + t * (4095. + 1574. * t)) )\n                            )));\n                        lp_lon = d*(FC1 -\n                            ds*FC3*( 1. + 2.*t + n -\n                            ds*FC5*(5. + t*(28. + 24.*t + 8.*n) + 6.*n\n                           - ds * FC7 * (61. + t * (662. + t * (1320. + 720. * t)) )\n                        ))) / cosphi;\n                    }\n                }\n            };\n\n            // template class, using CRTP to implement forward/inverse\n            template <typename Geographic, typename Cartesian, typename Parameters>\n            struct base_tmerc_spheroid : public base_t_fi<base_tmerc_spheroid<Geographic, Cartesian, Parameters>,\n                     Geographic, Cartesian, Parameters>\n            {\n\n                 typedef double geographic_type;\n                 typedef double cartesian_type;\n\n                par_tmerc m_proj_parm;\n\n                inline base_tmerc_spheroid(const Parameters& par)\n                    : base_t_fi<base_tmerc_spheroid<Geographic, Cartesian, Parameters>,\n                     Geographic, Cartesian, Parameters>(*this, par) {}\n\n                inline void fwd(geographic_type& lp_lon, geographic_type& lp_lat, cartesian_type& xy_x, cartesian_type& xy_y) const\n                {\n                    double b, cosphi;\n                \n                        /*\n                         * Fail if our longitude is more than 90 degrees from the \n                         * central meridian since the results are essentially garbage. \n                         * Is error -20 really an appropriate return value?\n                         * \n                         *  http://trac.osgeo.org/proj/ticket/5\n                         */\n                        if( lp_lon < -HALFPI || lp_lon > HALFPI )\n                        {\n                            xy_x = HUGE_VAL;\n                            xy_y = HUGE_VAL;\n                            throw proj_exception( -14 );\n                            return;\n                        }\n                \n                    b = (cosphi = cos(lp_lat)) * sin(lp_lon);\n                    if (fabs(fabs(b) - 1.) <= EPS10) throw proj_exception();;\n                    xy_x = this->m_proj_parm.ml0 * log((1. + b) / (1. - b));\n                    if ((b = fabs( xy_y = cosphi * cos(lp_lon) / sqrt(1. - b * b) )) >= 1.) {\n                        if ((b - 1.) > EPS10) throw proj_exception();\n                        else xy_y = 0.;\n                    } else\n                        xy_y = acos(xy_y);\n                    if (lp_lat < 0.) xy_y = -xy_y;\n                    xy_y = this->m_proj_parm.esp * (xy_y - this->m_par.phi0);\n                }\n\n                inline void inv(cartesian_type& xy_x, cartesian_type& xy_y, geographic_type& lp_lon, geographic_type& lp_lat) const\n                {\n                    double h, g;\n                \n                    h = exp(xy_x / this->m_proj_parm.esp);\n                    g = .5 * (h - 1. / h);\n                    h = cos(this->m_par.phi0 + xy_y / this->m_proj_parm.esp);\n                    lp_lat = asin(sqrt((1. - h * h) / (1. + g * g)));\n                    if (xy_y < 0.) lp_lat = -lp_lat;\n                    lp_lon = (g || h) ? atan2(g, h) : 0.;\n                }\n            };\n\n            template <typename Parameters>\n            void setup(Parameters& par, par_tmerc& proj_parm)  /* general initialization */\n            {\n                boost::ignore_unused_variable_warning(par);\n                boost::ignore_unused_variable_warning(proj_parm);\n                if (par.es) {\n                    pj_enfn(par.es, proj_parm.en);\n            \n                    proj_parm.ml0 = pj_mlfn(par.phi0, sin(par.phi0), cos(par.phi0), proj_parm.en);\n                    proj_parm.esp = par.es / (1. - par.es);\n                // par.inv = e_inverse;\n                // par.fwd = e_forward;\n                } else {\n                    proj_parm.esp = par.k0;\n                    proj_parm.ml0 = .5 * proj_parm.esp;\n                // par.inv = s_inverse;\n                // par.fwd = s_forward;\n                }\n            }\n\n\n            // Transverse Mercator\n            template <typename Parameters>\n            void setup_tmerc(Parameters& par, par_tmerc& proj_parm)\n            {\n                setup(par, proj_parm);\n            }\n\n            // Universal Transverse Mercator (UTM)\n            template <typename Parameters>\n            void setup_utm(Parameters& par, par_tmerc& proj_parm)\n            {\n                int zone;\n                if (!par.es) throw proj_exception(-34);\n                par.y0 = pj_param(par.params, \"bsouth\").i ? 10000000. : 0.;\n                par.x0 = 500000.;\n                if (pj_param(par.params, \"tzone\").i) /* zone input ? */\n                    if ((zone = pj_param(par.params, \"izone\").i) > 0 && zone <= 60)\n                        --zone;\n                    else\n                        throw proj_exception(-35);\n                else /* nearest central meridian input */\n                    if ((zone = int_floor((adjlon(par.lam0) + PI) * 30. / PI)) < 0)\n                        zone = 0;\n                    else if (zone >= 60)\n                        zone = 59;\n                par.lam0 = (zone + .5) * PI / 30. - PI;\n                par.k0 = 0.9996;\n                par.phi0 = 0.;\n                setup(par, proj_parm);\n            }\n\n        }} // namespace detail::tmerc\n    #endif // doxygen \n\n    /*!\n        \\brief Transverse Mercator projection\n        \\ingroup projections\n        \\tparam Geographic latlong point type\n        \\tparam Cartesian xy point type\n        \\tparam Parameters parameter type\n        \\par Projection characteristics\n         - Cylindrical\n         - Spheroid\n         - Ellipsoid\n        \\par Example\n        \\image html ex_tmerc.gif\n    */\n    template <typename Geographic, typename Cartesian, typename Parameters = parameters>\n    struct tmerc_ellipsoid : public detail::tmerc::base_tmerc_ellipsoid<Geographic, Cartesian, Parameters>\n    {\n        inline tmerc_ellipsoid(const Parameters& par) : detail::tmerc::base_tmerc_ellipsoid<Geographic, Cartesian, Parameters>(par)\n        {\n            detail::tmerc::setup_tmerc(this->m_par, this->m_proj_parm);\n        }\n    };\n\n    /*!\n        \\brief Universal Transverse Mercator (UTM) 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         - zone= south\n        \\par Example\n        \\image html ex_utm.gif\n    */\n    template <typename Geographic, typename Cartesian, typename Parameters = parameters>\n    struct utm_ellipsoid : public detail::tmerc::base_tmerc_ellipsoid<Geographic, Cartesian, Parameters>\n    {\n        inline utm_ellipsoid(const Parameters& par) : detail::tmerc::base_tmerc_ellipsoid<Geographic, Cartesian, Parameters>(par)\n        {\n            detail::tmerc::setup_utm(this->m_par, this->m_proj_parm);\n        }\n    };\n\n    /*!\n        \\brief Transverse Mercator projection\n        \\ingroup projections\n        \\tparam Geographic latlong point type\n        \\tparam Cartesian xy point type\n        \\tparam Parameters parameter type\n        \\par Projection characteristics\n         - Cylindrical\n         - Spheroid\n         - Ellipsoid\n        \\par Example\n        \\image html ex_tmerc.gif\n    */\n    template <typename Geographic, typename Cartesian, typename Parameters = parameters>\n    struct tmerc_spheroid : public detail::tmerc::base_tmerc_spheroid<Geographic, Cartesian, Parameters>\n    {\n        inline tmerc_spheroid(const Parameters& par) : detail::tmerc::base_tmerc_spheroid<Geographic, Cartesian, Parameters>(par)\n        {\n            detail::tmerc::setup_tmerc(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 tmerc_entry : public detail::factory_entry<Geographic, Cartesian, Parameters>\n        {\n            public :\n                virtual projection<Geographic, Cartesian>* create_new(const Parameters& par) const\n                {\n                    if (par.es)\n                        return new base_v_fi<tmerc_ellipsoid<Geographic, Cartesian, Parameters>, Geographic, Cartesian, Parameters>(par);\n                    else\n                        return new base_v_fi<tmerc_spheroid<Geographic, Cartesian, Parameters>, Geographic, Cartesian, Parameters>(par);\n                }\n        };\n\n        template <typename Geographic, typename Cartesian, typename Parameters>\n        class utm_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<utm_ellipsoid<Geographic, Cartesian, Parameters>, Geographic, Cartesian, Parameters>(par);\n                }\n        };\n\n        template <typename Geographic, typename Cartesian, typename Parameters>\n        inline void tmerc_init(detail::base_factory<Geographic, Cartesian, Parameters>& factory)\n        {\n            factory.add_to_factory(\"tmerc\", new tmerc_entry<Geographic, Cartesian, Parameters>);\n            factory.add_to_factory(\"utm\", new utm_entry<Geographic, Cartesian, Parameters>);\n        }\n\n    } // namespace detail \n    // Create EPSG specializations\n    // (Proof of Concept, only for some)\n\n    template<typename LatLongRadian, typename Cartesian, typename Parameters>\n    struct epsg_traits<2000, LatLongRadian, Cartesian, Parameters>\n    {\n        typedef tmerc_ellipsoid<LatLongRadian, Cartesian, Parameters> type;\n        static inline std::string par()\n        {\n            return \"+proj=tmerc +lat_0=0 +lon_0=-62 +k=0.9995000000000001 +x_0=400000 +y_0=0 +ellps=clrk80 +units=m\";\n        }\n    };\n\n\n    template<typename LatLongRadian, typename Cartesian, typename Parameters>\n    struct epsg_traits<2001, LatLongRadian, Cartesian, Parameters>\n    {\n        typedef tmerc_ellipsoid<LatLongRadian, Cartesian, Parameters> type;\n        static inline std::string par()\n        {\n            return \"+proj=tmerc +lat_0=0 +lon_0=-62 +k=0.9995000000000001 +x_0=400000 +y_0=0 +ellps=clrk80 +units=m\";\n        }\n    };\n\n\n    template<typename LatLongRadian, typename Cartesian, typename Parameters>\n    struct epsg_traits<2002, LatLongRadian, Cartesian, Parameters>\n    {\n        typedef tmerc_ellipsoid<LatLongRadian, Cartesian, Parameters> type;\n        static inline std::string par()\n        {\n            return \"+proj=tmerc +lat_0=0 +lon_0=-62 +k=0.9995000000000001 +x_0=400000 +y_0=0 +ellps=clrk80 +towgs84=725,685,536,0,0,0,0 +units=m\";\n        }\n    };\n\n\n    template<typename LatLongRadian, typename Cartesian, typename Parameters>\n    struct epsg_traits<2003, LatLongRadian, Cartesian, Parameters>\n    {\n        typedef tmerc_ellipsoid<LatLongRadian, Cartesian, Parameters> type;\n        static inline std::string par()\n        {\n            return \"+proj=tmerc +lat_0=0 +lon_0=-62 +k=0.9995000000000001 +x_0=400000 +y_0=0 +ellps=clrk80 +towgs84=72,213.7,93,0,0,0,0 +units=m\";\n        }\n    };\n\n\n    template<typename LatLongRadian, typename Cartesian, typename Parameters>\n    struct epsg_traits<2039, LatLongRadian, Cartesian, Parameters>\n    {\n        typedef tmerc_ellipsoid<LatLongRadian, Cartesian, Parameters> type;\n        static inline std::string par()\n        {\n            return \"+proj=tmerc +lat_0=31.73439361111111 +lon_0=35.20451694444445 +k=1.0000067 +x_0=219529.584 +y_0=626907.39 +ellps=GRS80 +towgs84=-48,55,52,0,0,0,0 +units=m\";\n        }\n    };\n\n\n    template<typename LatLongRadian, typename Cartesian, typename Parameters>\n    struct epsg_traits<29118, LatLongRadian, Cartesian, Parameters>\n    {\n        typedef utm_ellipsoid<LatLongRadian, Cartesian, Parameters> type;\n        static inline std::string par()\n        {\n            return \"+proj=utm +zone=18 +ellps=GRS67 +units=m\";\n        }\n    };\n\n\n    template<typename LatLongRadian, typename Cartesian, typename Parameters>\n    struct epsg_traits<29119, LatLongRadian, Cartesian, Parameters>\n    {\n        typedef utm_ellipsoid<LatLongRadian, Cartesian, Parameters> type;\n        static inline std::string par()\n        {\n            return \"+proj=utm +zone=19 +ellps=GRS67 +units=m\";\n        }\n    };\n\n\n    #endif // doxygen\n\n}}} // namespace boost::geometry::projections\n\n#endif // BOOST_GEOMETRY_PROJECTIONS_TMERC_HPP\n\n", "meta": {"hexsha": "fff3798fd29e35740727a386b3b8cdf2da3e7c99", "size": 19904, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/geometry/extensions/gis/projections/proj/tmerc.hpp", "max_stars_repo_name": "ballisticwhisper/boost", "max_stars_repo_head_hexsha": "f72119ab640b564c4b983bd457457046b52af9ee", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2015-01-02T14:24:56.000Z", "max_stars_repo_stars_event_max_datetime": "2015-01-02T14:25:17.000Z", "max_issues_repo_path": "boost/geometry/extensions/gis/projections/proj/tmerc.hpp", "max_issues_repo_name": "ballisticwhisper/boost", "max_issues_repo_head_hexsha": "f72119ab640b564c4b983bd457457046b52af9ee", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2019-01-13T23:45:51.000Z", "max_issues_repo_issues_event_max_datetime": "2019-02-03T08:13:26.000Z", "max_forks_repo_path": "boost/geometry/extensions/gis/projections/proj/tmerc.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": 43.3638344227, "max_line_length": 176, "alphanum_fraction": 0.5484324759, "num_tokens": 4676, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7217432062975978, "lm_q2_score": 0.45326184801538616, "lm_q1q2_score": 0.3271386594789993}}
{"text": "// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT license.\n\n#include \"conv.h\"\n#include \"common.h\"\n#include \"gemm.h\"\n#include <Eigen/Core>\n#include <Eigen/Dense>\n#include <vector>\n\n// Wasm interop method\nvoid conv_f32(void *data) {\n  uint32_t *dataIndex = static_cast<uint32_t *>(data);\n  uint32_t const argc = dataIndex[0];\n  // TODO: Support muti-dimensional convolution (1D and 3D atleast)\n  conv2D_f32_imp(\n      PARAM_FLOAT_PTR(data, dataIndex[1]), PARAM_INT32_PTR(data, dataIndex[2]),\n      PARAM_FLOAT_PTR(data, dataIndex[3]), PARAM_INT32_PTR(data, dataIndex[4]),\n      PARAM_FLOAT_PTR(data, dataIndex[5]), PARAM_INT32_PTR(data, dataIndex[6]),\n      PARAM_FLOAT_PTR(data, dataIndex[7]), PARAM_INT32_PTR(data, dataIndex[8]),\n      PARAM_INT32(data, dataIndex[9]), PARAM_INT32_PTR(data, dataIndex[10]),\n      PARAM_INT32_PTR(data, dataIndex[11]));\n}\n\n// Core operator implementation\nvoid conv2D_f32_imp(float *X, int *X_shape, float *W, int *W_shape, float *Y,\n                    int *Y_shape, float *bias, int *dilations, int group,\n                    int *pads, int *strides) {\n  const int input_num = X_shape[0];\n  const int input_channels = X_shape[1];\n  const int input_height = X_shape[2];\n  const int input_width = X_shape[3];\n  const int input_size =\n      input_num * input_channels * input_height * input_width;\n\n  const int filter_num = W_shape[0];\n  const int filter_channels = W_shape[1];\n  const int filter_height = W_shape[2];\n  const int filter_width = W_shape[3];\n  const int filter_size =\n      filter_num * filter_channels * filter_height * filter_width;\n  std::vector<int> kernel_shape;\n  kernel_shape.push_back(filter_height);\n  kernel_shape.push_back(filter_width);\n\n  const int output_num = Y_shape[0];\n  const int output_channels = Y_shape[1];\n  const int output_height = Y_shape[2];\n  const int output_width = Y_shape[3];\n  const int output_size =\n      output_num * output_channels * output_height * output_width;\n\n  const int input_image_size = input_height * input_width;\n  const int output_image_size = output_height * output_width;\n  const int kernel_size = kernel_shape[0] * kernel_shape[1];\n  const int X_offset = input_channels / group * input_image_size;\n  const int Y_offset = output_size / output_num / group;\n  const int W_offset = filter_size / group;\n  const int kernel_dim = input_channels / group * kernel_size;\n  const int col_buffer_size = kernel_dim * output_image_size;\n\n  float *col_buffer_data = new float[col_buffer_size]();\n\n  for (int image_id = 0; image_id < input_num; ++image_id) {\n    for (int group_id = 0; group_id < group; ++group_id) {\n      im2col_f32(X + group_id * X_offset, input_channels / group, input_height,\n                 input_width, kernel_shape[0], kernel_shape[1], dilations[0],\n                 dilations[1], pads[0], pads[1], pads[2], pads[3], strides[0],\n                 strides[1], col_buffer_data);\n\n      gemm_f32_imp(false, false, filter_num / group, output_image_size,\n                   kernel_dim, 1, W + group_id * W_offset, col_buffer_data, 0,\n                   Y + group_id * Y_offset);\n    }\n\n    if (bias != nullptr) {\n      auto Ymatrix =\n          Eigen::Map<Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic>>(\n              Y, output_image_size, filter_num);\n      auto Bvec = Eigen::Map<const Eigen::Matrix<float, Eigen::Dynamic, 1>>(\n          bias, filter_num);\n      Ymatrix.rowwise() += Bvec.transpose();\n    }\n\n    X += X_offset * group;\n    Y += Y_offset * group;\n  }\n\n  delete[] col_buffer_data;\n}\n\n// Some helpers specific to conv operator\nvoid im2col_f32(const float *data_im, const int channels, const int height,\n                const int width, const int kernel_h, const int kernel_w,\n                const int dilation_h, const int dilation_w, const int pad_t,\n                const int pad_l, const int pad_b, const int pad_r,\n                const int stride_h, const int stride_w, float *data_col) {\n  const int output_h =\n      (height + pad_b + pad_t - (dilation_h * (kernel_h - 1) + 1)) / stride_h +\n      1;\n  const int output_w =\n      (width + pad_l + pad_r - (dilation_w * (kernel_w - 1) + 1)) / stride_w +\n      1;\n\n  // Fast path for zero padding and no dilation\n  // From Torch, THNN_(unfolded_copy)\n  if (dilation_h == 1 && dilation_w == 1 && pad_l == 0 && pad_r == 0 &&\n      pad_t == 0 && pad_b == 0) {\n    for (auto k = 0; k < channels * kernel_h * kernel_w; k++) {\n      const auto nip = k / (kernel_h * kernel_w);\n      const auto rest = k % (kernel_h * kernel_w);\n      const auto kh = rest / kernel_w;\n      const auto kw = rest % kernel_w;\n      auto *dst = data_col + nip * (kernel_h * kernel_w * output_h * output_w) +\n                  kh * (kernel_w * output_h * output_w) +\n                  kw * (output_h * output_w);\n      const auto *src = data_im + nip * (height * width);\n      for (auto y = 0; y < output_h; y++) {\n        const auto iy = y * stride_h + kh;\n        const auto ix = kw;\n        if (stride_w == 1) {\n          memcpy(dst + (y * output_w), src + (iy * width + ix),\n                 sizeof(float) * output_w);\n        } else {\n          for (auto x = 0; x < output_w; x++) {\n            memcpy(dst + (y * output_w + x),\n                   src + (iy * width + ix + x * stride_w), sizeof(float));\n          }\n        }\n      }\n    }\n    return;\n  }\n\n  // Fast path for equal padding\n  if (pad_l == pad_r && pad_t == pad_b) {\n    // From Intel, https://github.com/BVLC/caffe/pull/3536\n    const int pad_h = pad_t;\n    const int pad_w = pad_l;\n    const int channel_size = height * width;\n    for (int channel = channels; channel--; data_im += channel_size) {\n      for (int kernel_row = 0; kernel_row < kernel_h; kernel_row++) {\n        for (int kernel_col = 0; kernel_col < kernel_w; kernel_col++) {\n          int input_row = -pad_h + kernel_row * dilation_h;\n          for (int output_rows = output_h; output_rows; output_rows--) {\n            if (!is_a_ge_zero_and_a_lt_b(input_row, height)) {\n              for (int output_cols = output_w; output_cols; output_cols--) {\n                *(data_col++) = 0;\n              }\n            } else {\n              int input_col = -pad_w + kernel_col * dilation_w;\n              for (int output_col = output_w; output_col; output_col--) {\n                if (is_a_ge_zero_and_a_lt_b(input_col, width)) {\n                  *(data_col++) = data_im[input_row * width + input_col];\n                } else {\n                  *(data_col++) = 0;\n                }\n                input_col += stride_w;\n              }\n            }\n            input_row += stride_h;\n          }\n        }\n      }\n    }\n    return;\n  }\n\n  // Baseline\n  const int dkernel_h = dilation_h * (kernel_h - 1) + 1;\n  const int dkernel_w = dilation_w * (kernel_w - 1) + 1;\n\n  int height_col = (height + pad_t + pad_b - dkernel_h) / stride_h + 1;\n  int width_col = (width + pad_l + pad_r - dkernel_w) / stride_w + 1;\n\n  int channels_col = channels * kernel_h * kernel_w;\n  for (int c = 0; c < channels_col; ++c) {\n    int w_offset = c % kernel_w;\n    int h_offset = (c / kernel_w) % kernel_h;\n    int c_im = c / kernel_h / kernel_w;\n    for (int h = 0; h < height_col; ++h) {\n      for (int w = 0; w < width_col; ++w) {\n        int h_pad = h * stride_h - pad_t + h_offset * dilation_h;\n        int w_pad = w * stride_w - pad_l + w_offset * dilation_w;\n        if (h_pad >= 0 && h_pad < height && w_pad >= 0 && w_pad < width)\n          data_col[(c * height_col + h) * width_col + w] =\n              data_im[(c_im * height + h_pad) * width + w_pad];\n        else\n          data_col[(c * height_col + h) * width_col + w] = 0;\n      }\n    }\n  }\n}\n", "meta": {"hexsha": "2f2c4f709b6ecc58cae2e925274a9f7b19ddca66", "size": 7654, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/wasm-ops/conv.cpp", "max_stars_repo_name": "fs-eire/onnxjs", "max_stars_repo_head_hexsha": "105e481cddb880ff54b677ca2f929706e3f31f97", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 887.0, "max_stars_repo_stars_event_min_datetime": "2019-05-07T08:58:51.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T07:41:54.000Z", "max_issues_repo_path": "src/wasm-ops/conv.cpp", "max_issues_repo_name": "fs-eire/onnxjs", "max_issues_repo_head_hexsha": "105e481cddb880ff54b677ca2f929706e3f31f97", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 113.0, "max_issues_repo_issues_event_min_datetime": "2019-05-07T13:51:52.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-12T10:11:56.000Z", "max_forks_repo_path": "src/wasm-ops/conv.cpp", "max_forks_repo_name": "fs-eire/onnxjs", "max_forks_repo_head_hexsha": "105e481cddb880ff54b677ca2f929706e3f31f97", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 106.0, "max_forks_repo_forks_event_min_datetime": "2019-05-10T05:44:58.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-09T08:17:00.000Z", "avg_line_length": 39.4536082474, "max_line_length": 80, "alphanum_fraction": 0.6039979096, "num_tokens": 2072, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7217432062975979, "lm_q2_score": 0.4532618480153861, "lm_q1q2_score": 0.3271386594789993}}
{"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 <cmath>\n\n// Third party includes\n#include <boost/math/constants/constants.hpp>\n\n// VOTCA includes\n#include <votca/tools/constants.h>\n\n// Local VOTCA includes\n#include \"votca/xtp/sigma_base.h\"\n#include \"votca/xtp/threecenter.h\"\n\nnamespace votca {\nnamespace xtp {\n\nEigen::MatrixXd Sigma_base::CalcExchangeMatrix() const {\n  Eigen::MatrixXd result = Eigen::MatrixXd::Zero(_qptotal, _qptotal);\n  Index occlevel = _opt.homo - _opt.rpamin + 1;\n  Index qpmin = _opt.qpmin - _opt.rpamin;\n#pragma omp parallel for schedule(dynamic)\n  for (Index gw_level1 = 0; gw_level1 < _qptotal; gw_level1++) {\n    const Eigen::MatrixXd& Mmn1 = _Mmn[gw_level1 + qpmin];\n    for (Index gw_level2 = gw_level1; gw_level2 < _qptotal; gw_level2++) {\n      const Eigen::MatrixXd& Mmn2 = _Mmn[gw_level2 + qpmin];\n      double sigma_x =\n          -(Mmn1.topRows(occlevel).cwiseProduct(Mmn2.topRows(occlevel))).sum();\n      result(gw_level2, gw_level1) = sigma_x;\n    }\n  }\n  result = result.selfadjointView<Eigen::Lower>();\n  return result;\n}\n\nEigen::VectorXd Sigma_base::CalcCorrelationDiag(\n    const Eigen::VectorXd& frequencies) const {\n  Eigen::VectorXd result = Eigen::VectorXd::Zero(_qptotal);\n#pragma omp parallel for schedule(dynamic)\n  for (Index gw_level = 0; gw_level < _qptotal; gw_level++) {\n    result(gw_level) =\n        CalcCorrelationDiagElement(gw_level, frequencies[gw_level]);\n  }\n  return result;\n}\n\nEigen::MatrixXd Sigma_base::CalcCorrelationOffDiag(\n    const Eigen::VectorXd& frequencies) const {\n  Eigen::MatrixXd result = Eigen::MatrixXd::Zero(_qptotal, _qptotal);\n#pragma omp parallel for schedule(dynamic)\n  for (Index gw_level1 = 0; gw_level1 < _qptotal; gw_level1++) {\n    for (Index gw_level2 = gw_level1 + 1; gw_level2 < _qptotal; gw_level2++) {\n      double sigma_c = CalcCorrelationOffDiagElement(\n          gw_level1, gw_level2, frequencies[gw_level1], frequencies[gw_level2]);\n      result(gw_level2, gw_level1) = sigma_c;\n    }\n  }\n  result = result.selfadjointView<Eigen::Lower>();\n  return result;\n}\n\n}  // namespace xtp\n}  // namespace votca\n", "meta": {"hexsha": "ea5df4807b0849dbabc185e9d2b5dc5e52863cb2", "size": 2776, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/libxtp/gwbse/sigma_base.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/sigma_base.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/sigma_base.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": 33.8536585366, "max_line_length": 80, "alphanum_fraction": 0.7028097983, "num_tokens": 751, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7217432062975979, "lm_q2_score": 0.4532618480153861, "lm_q1q2_score": 0.3271386594789993}}
{"text": "/**\n * @file\n * @copyright This code is licensed under the 3-clause BSD license.\\n\n *            Copyright ETH Zurich, Laboratory for Physical Chemistry, Reiher Group.\\n\n *            See LICENSE.txt for details.\n */\n\n#include \"Ecqpp.h\"\n#include <Eigen/QR>\n#include <algorithm>\n#include <cassert>\n#include <iostream>\n#include <limits>\n\nnamespace Scine {\nnamespace Utils {\n\nEcqpp::Ecqpp(const Eigen::MatrixXd& B, const Eigen::VectorXd& E)\n  : B_(B), E_(E), dimension_(static_cast<unsigned>(E.size())) {\n  assert(B.rows() == dimension_ && B.cols() == dimension_ && \"B matrix and E vector do not have compatible dimensions.\");\n}\n\nEigen::VectorXd Ecqpp::calculateOptimalCoefficients() {\n  solveAllConstrainedProblems();\n  return solution_;\n}\n\nvoid Ecqpp::solveAllConstrainedProblems() {\n  bestSolutionEnergy_ = std::numeric_limits<double>::max();\n  for (unsigned i = 0; i < dimension_; ++i)\n    solveAllConstrainedProblemsForNumberZeros(i);\n}\n\nvoid Ecqpp::solveAllConstrainedProblemsForNumberZeros(unsigned int numberZeros) {\n  std::vector<bool> indexConsidered(dimension_, true);\n  for (unsigned i = 0; i < numberZeros; ++i)\n    indexConsidered[i] = false;\n\n  do {\n    generatePreviousIndexesVector(indexConsidered, numberZeros);\n    generateReducedObjects();\n    solveConstrainedProblem();\n    if (solutionIsValid())\n      addSolution();\n  } while (std::next_permutation(indexConsidered.begin(), indexConsidered.end()));\n}\n\nvoid Ecqpp::generatePreviousIndexesVector(const std::vector<bool>& consideredIndexes, unsigned numberZeros) {\n  unsigned writeIndex = 0;\n  unsigned newMatrixDimension = dimension_ - numberZeros;\n  previousIndexes_.resize(newMatrixDimension);\n  for (unsigned readIndex = 0; readIndex < dimension_; ++readIndex) {\n    if (consideredIndexes[readIndex]) {\n      previousIndexes_[writeIndex] = readIndex;\n      ++writeIndex;\n    }\n  }\n}\n\nvoid Ecqpp::generateReducedObjects() {\n  auto reducedDimension = static_cast<unsigned>(previousIndexes_.size());\n\n  reducedB_.resize(reducedDimension, reducedDimension);\n  reducedE_.resize(reducedDimension);\n\n  for (unsigned i = 0; i < reducedDimension; ++i) {\n    reducedE_(i) = E_(previousIndexes_[i]);\n    for (unsigned j = 0; j < reducedDimension; ++j) {\n      reducedB_(i, j) = B_(previousIndexes_[i], previousIndexes_[j]);\n    }\n  }\n}\n\nvoid Ecqpp::solveConstrainedProblem() {\n  auto rDim = reducedB_.cols();\n\n  Eigen::MatrixXd M(rDim + 1, rDim + 1);\n  Eigen::VectorXd b(rDim + 1);\n\n  M.block(0, 0, rDim, rDim) = reducedB_;\n  M.block(rDim, 0, 1, rDim).setOnes();\n  M.block(0, rDim, rDim, 1).setOnes();\n  M(rDim, rDim) = 0;\n  b.head(rDim) = reducedE_;\n  b(rDim) = 1;\n\n  Eigen::VectorXd solution = M.colPivHouseholderQr().solve(b);\n  reducedSolution_ = solution.head(rDim);\n}\n\nbool Ecqpp::solutionIsValid() const {\n  for (unsigned i = 0; i < reducedSolution_.size(); ++i)\n    if (reducedSolution_[i] < 0)\n      return false;\n  return true;\n}\n\nvoid Ecqpp::addSolution() {\n  generateSolutionFromReducedSolution();\n  setBestSolutionIfHasLowerEnergy();\n}\n\nvoid Ecqpp::generateSolutionFromReducedSolution() {\n  fullSolution_ = Eigen::VectorXd::Zero(dimension_);\n  for (unsigned i = 0; i < previousIndexes_.size(); ++i) {\n    fullSolution_[previousIndexes_[i]] = reducedSolution_[i];\n  }\n}\n\nvoid Ecqpp::setBestSolutionIfHasLowerEnergy() {\n  double currentEnergy = E_.dot(fullSolution_) - 0.5 * fullSolution_.transpose() * B_ * fullSolution_;\n  if (currentEnergy < bestSolutionEnergy_) {\n    solution_ = fullSolution_;\n    bestSolutionEnergy_ = currentEnergy;\n  }\n}\n} // namespace Utils\n} // namespace Scine\n", "meta": {"hexsha": "f0e01d8297427767587060dcdf788f4190d212d6", "size": 3559, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Utils/Utils/Scf/ConvergenceAccelerators/Ecqpp.cpp", "max_stars_repo_name": "DockBio/utilities", "max_stars_repo_head_hexsha": "213ed5ac2a64886b16d0fee1fcecb34d36eea9e9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Utils/Utils/Scf/ConvergenceAccelerators/Ecqpp.cpp", "max_issues_repo_name": "DockBio/utilities", "max_issues_repo_head_hexsha": "213ed5ac2a64886b16d0fee1fcecb34d36eea9e9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Utils/Utils/Scf/ConvergenceAccelerators/Ecqpp.cpp", "max_forks_repo_name": "DockBio/utilities", "max_forks_repo_head_hexsha": "213ed5ac2a64886b16d0fee1fcecb34d36eea9e9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.9075630252, "max_line_length": 121, "alphanum_fraction": 0.7044113515, "num_tokens": 980, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7154239957834733, "lm_q2_score": 0.45713671682749485, "lm_q1q2_score": 0.3270465765720645}}
{"text": "/** $Id: EnergyDistribution.cxx 165001 2018-08-27 09:22:30Z jvansanten $\n * @file\n * @author Jakob van Santen <vansanten@wisc.edu>\n *\n * $Revision: 165001 $\n * $Date: 2018-08-27 03:22:30 -0600 (Mon, 27 Aug 2018) $\n */\n\n#include <MuonGun/EnergyDistribution.h>\n#include <MuonGun/RadialDistribution.h>\n#include <phys-services/I3RandomService.h>\n#include <MuonGun/EnsembleSampler.h>\n\n#include <boost/bind.hpp>\n\nnamespace I3MuonGun {\n\nEnergyDistribution::~EnergyDistribution() {};\n\ndouble\nEnergyDistribution::operator()(double d, double ct, \n    unsigned m, double r, double e) const\n{\n\treturn std::exp(GetLog(d, ct, m, r, log_value(std::log(e))));\n}\n\ndouble\nEnergyDistribution::Integrate(double d, double ct, \n    unsigned m, double r_min, double r_max, double e_min, double e_max) const\n{\n\t// restrict integration to range where density can be nonzero\n\tdouble loge_min = std::max(minLog_, std::log(e_min));\n\tdouble loge_max = std::min(maxLog_, std::log(e_max));\n\tr_min = std::max(0., r_min);\n\tr_max = std::min(GetMaxRadius(), r_max);\n\tif (m > 1) {\n\t\t// Integrate dP/(dlogE dr^2) for numerical stability\n\t\tauto integrand = [this,d,ct,m](double r2, double loge)\n\t\t{\n\t\t\tdouble r = std::sqrt(r2);\n\t\t\treturn std::exp(GetLog(d, ct, m, r, log_value(loge))\n\t\t\t    - std::log(2*r) + loge);\n\t\t};\n\t\tboost::array<double, 2> lo = {{r_min*r_min, loge_min}};\n\t\tboost::array<double, 2> hi = {{r_max*r_max, loge_max}};\n\t\treturn I3MuonGun::Integrate(boost::function<double(double,double)>(integrand),\n\t\t    lo, hi, 1e-12, 1e-6, 10000);\n\t} else {\n\t\t// For single muons, dP/dr is a delta function at 0\n\t\tauto integrand = [this,d,ct,m](double loge)\n\t\t{\n\t\t\treturn std::exp(GetLog(d, ct, m, 0, log_value(loge)) + loge);\n\t\t};\n\t\treturn I3MuonGun::Integrate(boost::function<double(double)>(integrand), loge_min, loge_max);\n\t}\n}\n\nbool\nSplineEnergyDistribution::operator==(const EnergyDistribution &o) const\n{\n\tconst SplineEnergyDistribution *other = dynamic_cast<const SplineEnergyDistribution*>(&o);\n\tif (!other)\n\t\treturn false;\n\telse\n\t\treturn (singles_ == other->singles_ && bundles_ == other->bundles_);\n}\n\nSplineEnergyDistribution::SplineEnergyDistribution(const std::string &singles, const std::string &bundles)\n    : singles_(singles), bundles_(bundles)\n{\n\tif (singles_.GetNDim() != 3u)\n\t\tlog_fatal(\"'%s' does not appear to be a single-muon energy distribution\", singles.c_str());\n\tif (bundles_.GetNDim() != 5u)\n\t\tlog_fatal(\"'%s' does not appear to be a muon bundle energy distribution\", bundles.c_str());\n\tSetMin(std::exp(std::max(singles_.GetExtents(2).first, bundles_.GetExtents(2).first)));\n\tSetMax(std::exp(std::min(singles_.GetExtents(2).second, bundles_.GetExtents(2).second)));\n}\n\ndouble\nSplineEnergyDistribution::GetMaxRadius() const\n{\n\treturn bundles_.GetExtents(3).second;\n}\n\ndouble\nSplineEnergyDistribution::GetLog(double depth, double cos_theta, \n    unsigned multiplicity, double radius, log_value log_energy) const\n{\n\tdouble coords[5] = {cos_theta, depth, static_cast<double>(multiplicity),\n\t    radius, log_energy};\n\tdouble logprob;\n\t\n\tif (radius < 0 || radius > GetMaxRadius() ||\n\t    log_energy < minLog_ || log_energy > maxLog_) {\n\t\treturn -std::numeric_limits<double>::infinity();\n\t} else if (multiplicity < 2) {\n\t\tcoords[2] = coords[4];\n\t\tif (singles_.Eval(coords, &logprob) != 0)\n\t\t\treturn -std::numeric_limits<double>::infinity();\n\t} else if (bundles_.Eval(coords, &logprob) != 0)\n\t\treturn -std::numeric_limits<double>::infinity();\n\t\n\t// Bundle spline is fit to log(dP/dr^2 dlogE)\n\tif (multiplicity > 1)\n\t\tlogprob += std::log(2*radius);\n\t\n\treturn logprob;\n}\n\nstd::vector<std::pair<double,double> >\nSplineEnergyDistribution::Generate(I3RandomService &rng, double depth,\n    double cos_theta, unsigned multiplicity, unsigned nsamples) const\n{\n\ttypedef double (Signature)(double, double);\n\ttypedef EnsembleSampler<Signature> Sampler;\n\t\n\t// the number of walkers must be even, and at least twice the\n\t// dimensionality of the space\n\tconst unsigned walkers = std::max(4u, nsamples + (nsamples % 2));\n\tstd::vector<Sampler::array_type> initial_ensemble(walkers);\n\t{\n\t\t// Draw starting positions from the MUPAGE parameterization\n\t\tBMSSEnergyDistribution proposal;\n\t\tproposal.SetMin(GetMin());\n\t\tproposal.SetMax(GetMax());\n\t\tstd::vector<std::pair<double, double> > samples =\n\t\t    proposal.Generate(rng, depth, cos_theta, multiplicity, walkers);\n\t\tfor (unsigned i=0; i < walkers; i++) {\n\t\t\tinitial_ensemble[i][0] = samples.at(i).first;\n\t\t\tinitial_ensemble[i][1] = samples.at(i).second;\n\t\t}\n\t}\n\t\n\tauto log_posterior = [this,depth,cos_theta,multiplicity](double r, double e)\n\t{\n\t\treturn this->GetLog(depth, cos_theta, multiplicity, r,\n\t\t    EnergyDistribution::log_value(std::log(e)));\n\t};\n\tSampler sampler(log_posterior, initial_ensemble);\n\t\n\t// Run the sampler for a few cycles to make it independent of the initial\n\t// ensemble. Fewer than 50 or so burn-in steps is too small to reach the\n\t// stationary distribution, while more than 100 is a waste of time, as\n\t// measured with resources/test/test_sampling.py\n\tfor (unsigned i=0; i < 64; i++)\n\t\tsampler.Sample(rng);\n\t\n\t// copy the current ensemble into the output\n\tstd::vector<std::pair<double,double> > samples;\n\tsamples.reserve(nsamples);\n\tconst std::vector<Sampler::sample> &ensemble = sampler.Sample(rng);\n\tunsigned todo = std::min(walkers, nsamples - unsigned(samples.size()));\n\tfor (unsigned j=0; j < todo; j++) {\n\t\tsamples.push_back(std::make_pair(ensemble[j].point[0], ensemble[j].point[1]));\n\t}\n\t\n\t// check the acceptance rate for sanity.\n\tdouble acceptance_rate = sampler.GetAcceptanceRate();\n\tif (acceptance_rate < 0.2) {\n\t\tlog_warn(\"Ensemble sampler accepted only %.0f%% of samples (too low). It may be stuck in a local maximum.\", 100*acceptance_rate);\n\t} else if (acceptance_rate > 0.9) {\n\t\tlog_warn(\"Ensemble sampler accepted %.0f%% of samples (too high). This is an expensive random walk.\", 100*acceptance_rate);\n\t}\n\t\n\treturn samples;\n}\n\nBMSSEnergyDistribution::BMSSEnergyDistribution() :\n    beta_(0.42), g0_(-0.232), g1_(3.961), e0a_(0.0304), e0b_(0.359), e1a_(-0.0077), e1b_(0.659),\n    a0_(0.0033), a1_(0.0079), b0a_(0.0407), b0b_(0.0283), b1a_(-0.312), b1b_(6.124),\n    q0_(0.0543), q1_(-0.365), c0a_(-0.069), c0b_(0.488), c1_(-0.117),\n    d0a_(-0.398), d0b_(3.955), d1a_(0.012), d1b_(-0.35)\n{}\n\nbool\nBMSSEnergyDistribution::operator==(const EnergyDistribution &o) const\n{\n\treturn dynamic_cast<const BMSSEnergyDistribution*>(&o);\n}\n\nOffsetPowerLaw\nBMSSEnergyDistribution::GetSpectrum(double depth, double cos_theta, unsigned m, double r) const\n{\n\t// Convert to water-equivalent depth\n\tdouble h = (200*I3Units::m/I3Units::km)*0.832 + (depth-(200*I3Units::m/I3Units::km))*0.917;\n\tdouble bX = beta_*h/cos_theta;\n\tdouble g, eps;\n\tif (m == 1) {\n\t\tg = g0_*log(h) + g1_;\n\t\teps = (e0a_*exp(e0b_*h)/cos_theta + e1a_*h + e1b_)*I3Units::TeV;\n\t} else {\n\t\tm = std::min(m, 4u);\n\t\tdouble a = a0_*h + a1_;\n\t\tdouble b = (b0a_*m + b0b_)*h + (b1a_*m + b1b_);\n\t\tdouble q = q0_*h + q1_;\n\t\tg = a*r + b*(1 - 0.5*exp(q*r));\n\t\tdouble c = (c0a_*h + c0b_)*exp(c1_*r);\n\t\tdouble d = (d0a_*h + d0b_)*pow(r, d1a_*h + d1b_);\n\t\teps = (c*acos(cos_theta) + d)*I3Units::TeV;\n\t}\n\t\n\treturn OffsetPowerLaw(g, eps*(1-exp(-bX)), GetMin(), GetMax());\n}\n\ndouble\nBMSSEnergyDistribution::GetLog(double depth, double cos_theta, \n    unsigned multiplicity, double radius, log_value log_energy) const\n{\n\t\n\treturn BMSSRadialDistribution().GetLog(depth, cos_theta, multiplicity, radius) +\n\t    GetSpectrum(depth, cos_theta, multiplicity, radius).GetLog(log_energy);\n}\n\ndouble\nBMSSEnergyDistribution::GetMaxRadius() const\n{\n\treturn 250*I3Units::m;\n}\n\nstd::vector<std::pair<double,double> >\nBMSSEnergyDistribution::Generate(I3RandomService &rng, double depth,\n    double cos_theta, unsigned multiplicity, unsigned samples) const\n{\n\tstd::vector<std::pair<double,double> > values;\n\tvalues.reserve(samples);\n\tstd::pair<double, double> val;\n\tfor (unsigned i=0; i < samples; i++) {\n\t\tval.first = BMSSRadialDistribution().Generate(rng, depth, cos_theta, multiplicity);\n\t\tval.second = GetSpectrum(depth, cos_theta, multiplicity, val.first).Generate(rng);\n\t\tvalues.push_back(val);\n\t}\n\t\n\treturn values;\n}\n\n\nOffsetPowerLaw::OffsetPowerLaw() : gamma_(NAN), offset_(NAN), emin_(NAN), emax_(NAN)\n{}\n\nOffsetPowerLaw::OffsetPowerLaw(double gamma, double offset, double emin, double emax)\n    : gamma_(gamma), offset_(offset), emin_(emin), emax_(emax)\n{\n\tif (gamma <= 0)\n\t\tlog_fatal(\"Power law index must be > 0\");\n\telse if (gamma == 1) {\n\t\tnmin_ = std::log(emin + offset);\n\t\tnmax_ = std::log(emax + offset);\n\t\tnorm_ = 1./(nmax_ - nmin_);\n\t} else {\n\t\tnmin_ = std::pow(emin + offset, 1-gamma);\n\t\tnmax_ = std::pow(emax + offset, 1-gamma);\n\t\tnorm_ = (1-gamma)/(nmax_ - nmin_);\n\t}\n\tlognorm_ = std::log(norm_);\n}\n\nbool\nOffsetPowerLaw::operator==(const OffsetPowerLaw &other) const\n{\n\treturn (gamma_ == other.gamma_ && offset_ == other.offset_\n\t    && emin_ == other.emin_ && emax_ == other.emax_ );\n}\n\ndouble\nOffsetPowerLaw::operator()(double energy) const\n{\n\tif (energy <= emax_ && energy >= emin_)\n\t\treturn norm_*std::pow(energy + offset_, -gamma_);\n\telse\n\t\treturn 0.;\n}\n\ndouble\nOffsetPowerLaw::GetLog(double energy) const\n{\n\tif (energy <= emax_ && energy >= emin_)\n\t\treturn lognorm_ - gamma_*std::log(energy + offset_);\n\telse\n\t\treturn -std::numeric_limits<double>::infinity();\n}\n\ndouble\nOffsetPowerLaw::GetLog(EnergyDistribution::log_value log_energy) const\n{\n\treturn GetLog(std::exp(log_energy));\n}\n\ndouble\nOffsetPowerLaw::Generate(I3RandomService &rng) const\n{\n\treturn InverseSurvivalFunction(rng.Uniform());\n}\n\ndouble\nOffsetPowerLaw::InverseSurvivalFunction(double p) const\n{\n\tif (gamma_ == 1)\n\t\treturn std::exp((1-p)*(nmax_ - nmin_) + nmin_) - offset_;\n\telse\n\t\treturn std::pow((1-p)*(nmax_ - nmin_) + nmin_, 1./(1.-gamma_)) - offset_;\n}\n\ntemplate <typename Archive>\nvoid\nEnergyDistribution::serialize(Archive &ar __attribute__ ((unused)), unsigned version __attribute__ ((unused)))\n{}\n\t\ntemplate <typename Archive>\nvoid\nSplineEnergyDistribution::serialize(Archive &ar, unsigned version)\n{\n\tif (version > 0)\n\t\tlog_fatal_stream(\"Version \"<<version<<\" is from the future\");\n\t\n\tar & make_nvp(\"EnergyDistribution\", base_object<EnergyDistribution>(*this));\n\tar & make_nvp(\"SingleEnergy\", singles_);\n\tar & make_nvp(\"BundleEnergy\", bundles_);\n}\n\ntemplate <typename Archive>\nvoid\nBMSSEnergyDistribution::serialize(Archive &ar, unsigned version)\n{\n\tif (version > 0)\n\t\tlog_fatal_stream(\"Version \"<<version<<\" is from the future\");\n\t\n\tar & make_nvp(\"EnergyDistribution\", base_object<EnergyDistribution>(*this));\n}\n\ntemplate <typename Archive>\nvoid\nOffsetPowerLaw::serialize(Archive &ar, unsigned version)\n{\n\tif (version > 0)\n\t\tlog_fatal_stream(\"Version \"<<version<<\" is from the future\");\n\t\n\tar & make_nvp(\"Gamma\", gamma_);\n\tar & make_nvp(\"Offset\", offset_);\n\tar & make_nvp(\"MinEnergy\", emin_);\n\tar & make_nvp(\"MaxEnergy\", emax_);\n\t\n\t*this = OffsetPowerLaw(gamma_, offset_, emin_, emax_);\n}\n\n}\n\nI3_SERIALIZABLE(I3MuonGun::EnergyDistribution);\nI3_SERIALIZABLE(I3MuonGun::SplineEnergyDistribution);\nI3_SERIALIZABLE(I3MuonGun::BMSSEnergyDistribution);\nI3_SERIALIZABLE(I3MuonGun::OffsetPowerLaw);\n", "meta": {"hexsha": "c4bec6423c2e25dfdb13bb9f1fe66cb9157f1cf9", "size": 11077, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "MuonGun/private/MuonGun/EnergyDistribution.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/EnergyDistribution.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/EnergyDistribution.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": 31.5584045584, "max_line_length": 131, "alphanum_fraction": 0.7044326081, "num_tokens": 3349, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7154239957834733, "lm_q2_score": 0.4571367168274948, "lm_q1q2_score": 0.32704657657206443}}
{"text": "#include <thread>\n#include <vector>\n#include <armadillo>\n#include \"RHF.hpp\"\n#include \"esp.hpp\"\n\n//\n// Electrostatic Potential (ESP)\n// : calculates partial atomic charges that fit\n//   the quantum mechanical electrostatic potential on the selected grid points\n//\n\nusing namespace std;\nusing namespace libint2;\n\nnamespace willow { namespace qcmol {\n\n\nstatic unsigned int num_threads;\n\nstatic void esp_esp (const int thread_id,\n\t\t     const vector<Atom>& atoms,\n\t\t     const BasisSet& bs,\n\t\t     const arma::mat& Dm,\n\t\t     const vector<arma::vec3>& grids,\n\t\t     arma::vec& results);\n\n\n\nESP::ESP (const vector<Atom>& atoms,\n\t  const BasisSet& bs,\n\t  const Integrals& ints,\n\t  const int qm_chg,\n\t  const bool l_print,\n\t  const vector<QAtom>& atoms_Q)\n  : RHF (atoms, bs, ints, qm_chg, l_print, atoms_Q)\n{\n\n  num_threads = std::thread::hardware_concurrency();\n\n  if (num_threads == 0)\n    num_threads = 1;\n\n  const arma::mat Dm = densityMatrix();\n\n  esp_grid (atoms);\n\n  // ---- Thread\n  vector<arma::vec>   grid_t(num_threads);\n  vector<std::thread> t_esp (num_threads);\n\n  for (auto id = 0; id < num_threads; ++id) {\n    t_esp[id] = std::thread (esp_esp, id,\n\t\t\t     std::cref(atoms),\n\t\t\t     std::cref(bs),\n\t\t\t     std::cref(Dm),\n\t\t\t     std::cref(m_grids),\n\t\t\t     std::ref(grid_t[id]));\n  }\n  \n  // Join\n  for (auto id = 0; id < num_threads; ++id) {\n    t_esp[id].join();\n  }\n\n  m_grids_val = grid_t[0];\n\n  for (auto id = 1; id < num_threads; ++id) {\n    m_grids_val += grid_t[id];\n  }\n  //---- (done: Thread) ---\n\n  \n  m_qf = esp_fit (atoms);\n  \n  if (l_print) {\n    for (auto i = 0; i < atoms.size(); i++)\n      cout << \"ESP \" << i+1 << \"  \" << m_qf(i) << endl;\n  }\n\n  \n}\n\n\nvoid esp_esp (const int thread_id,\n\t      const vector<Atom>& atoms,\n\t      const BasisSet& bs,\n\t      const arma::mat& Dm,\n\t      const vector<arma::vec3>& grids,\n\t      arma::vec& result)\n{\n\n  const auto nsize   = grids.size();\n\n  result = arma::vec(nsize, arma::fill::zeros);\n  \n  const auto nshells = bs.size();\n  const auto nbf     = bs.nbf();\n  \n  libint2::Engine engine (libint2::Operator::nuclear,\n\t\t\t  bs.max_nprim(),\n\t\t\t  bs.max_l(),\n\t\t\t  0);\n\n  const auto& buf = engine.results();\n  \n  const auto shell2bf = bs.shell2bf ();\n\n  arma::mat Vm(nbf,nbf);\n  \n  for (auto ig = 0; ig < grids.size(); ++ig) {\n    \n    if (ig % num_threads != thread_id) continue;\n    \n    const auto xg = grids[ig](0);\n    const auto yg = grids[ig](1);\n    const auto zg = grids[ig](2);\n\n    // Interaction with electron density\n    vector<pair<double,array<double,3>>> q;\n    q.push_back ( {1.0, {{xg, yg, zg}}} );\n\n    engine.set_params (q);\n\t\n    // calc Vm\n    Vm.zeros();\n    \n    for (auto s1 = 0; s1 != nshells; ++s1) {\n      auto bf1 = shell2bf[s1];\n      auto nbf1 = bs[s1].size();\n\n      for (auto s2 = 0; s2 != nshells; ++s2) {\n\tauto bf2 = shell2bf[s2];\n\tauto nbf2 = bs[s2].size();\n\t\n\tengine.compute (bs[s1], bs[s2]);\n\tconst auto* buf0 = buf[0];\n\t\n\tfor (auto ib = 0, ij = 0; ib < nbf1; ib++) {\n\t  for (auto jb = 0; jb < nbf2; jb++, ij++) {\n\t    const double val = buf0[ij];\n\t    Vm(bf1+ib,bf2+jb) = val;\n\t    Vm(bf2+jb,bf1+ib) = val;\n\t  }\n\t} // ib\n\t\n      } // s2\n    }  // s1\n\n    //\n    // get electrostatic potential on the grid points\n    // -- from electron density\n    double gval = 0.0;\n    \n    for (auto i = 0; i < nbf; i++)\n      for (auto j = 0; j < nbf; j++)\n\tgval += Dm(i,j)*Vm(i,j);\n    \n    // get electrostatic potential on the grid points\n    // -- from nuclei\n    auto zval = 0.0;\n    \n    for (auto ia = 0; ia < atoms.size(); ++ia) {\n      auto xij = atoms[ia].x - xg;\n      auto yij = atoms[ia].y - yg;\n      auto zij = atoms[ia].z - zg;\n      auto r2  = xij*xij + yij*yij + zij*zij;\n      auto r   = sqrt(r2);\n      zval += static_cast<double>(atoms[ia].atomic_number)/r;\n    }\n\n    result(ig) = gval + zval;\n  }\n  \n}\n\t\t     \n\narma::vec ESP::esp_fit (const vector<Atom>& atoms)\n{\n\n  // set up matrix of linear coefficients\n  auto natoms = atoms.size();\n  auto ndim   = natoms+1;\n\n  arma::mat am(ndim,ndim);\n  arma::vec bv(ndim);\n  \n  am.zeros();\n  bv.zeros();\n  \n  for (auto i = 0; i < atoms.size(); ++i) {\n    auto xi = atoms[i].x;\n    auto yi = atoms[i].y;\n    auto zi = atoms[i].z;\n    \n    for (auto j = i; j < atoms.size(); ++j) {\n      auto xj = atoms[j].x;\n      auto yj = atoms[j].y;\n      auto zj = atoms[j].z;\n      \n      auto sum = 0.0;\n\n      for (auto k = 0; k < m_grids.size(); ++k) {\n\tauto xg = m_grids[k](0);\n\tauto yg = m_grids[k](1);\n\tauto zg = m_grids[k](2);\n\n\tauto rig2 = (xi-xg)*(xi-xg) + (yi-yg)*(yi-yg) + (zi-zg)*(zi-zg);\n\tauto rjg2 = (xj-xg)*(xj-xg) + (yj-yg)*(yj-yg) + (zj-zg)*(zj-zg);\n\t  \n\tsum += 1.0/sqrt(rig2*rjg2);\n      }\n\n      am(i,j) = sum;\n      am(j,i) = sum;\n    }\n    \n    am(i,natoms) = 1.0;\n    am(natoms,i) = 1.0;\n  }\n\n  // construct column vector b\n\n  for (auto i = 0; i < atoms.size(); ++i) {\n    auto xi = atoms[i].x;\n    auto yi = atoms[i].y;\n    auto zi = atoms[i].z;\n\n    auto sum = 0.0;\n    for (auto k = 0; k < m_grids.size(); ++k) {\n      auto xg = m_grids[k](0);\n      auto yg = m_grids[k](1);\n      auto zg = m_grids[k](2);\n      auto val = m_grids_val(k);\n\n      auto rig2 = (xi-xg)*(xi-xg) + (yi-yg)*(yi-yg) + (zi-zg)*(zi-zg);\n\n      sum += val/sqrt(rig2);\n    }\n    bv(i) = sum;\n  }\n  bv(natoms) = 0.0; // b(natoms) = charge;\n\n  arma::mat am_inv = am.i();\n  \n  arma::vec qf(natoms);\n  qf.zeros();\n  \n  for (auto i = 0; i < natoms; ++i) {\n    auto sum = 0.0;\n\n    for (auto j = 0; j < ndim; ++j) {\n    //for (auto j = 0; j < atoms.size(); ++j) {\n      sum = sum + am_inv(i,j)*bv(j);\n    }\n    qf(i) = sum;\n    //cout << \" qf \" << sum << endl;\n  }\n\n  return qf;\n  \n}\n\n\n\nvoid ESP::esp_grid (const vector<Atom>& atoms)\n{\n\n  vector<double> radius(11);\n  \n  // A\n  radius[0] = 0.0; // Ghost\n  radius[1] = 0.3; // H\n  radius[2] = 1.22;// He\n  radius[3] = 1.23;// Li\n  radius[4] = 0.89; // Be\n  radius[5] = 0.88; // B\n  radius[6] = 0.77; // C\n  radius[7] = 0.70; // N\n  radius[8] = 0.66; // O\n  radius[9] = 0.58; // F\n  radius[10]= 1.60; // Ne\n\n  for (auto i = 1; i <= 10; i++) {\n    radius[i] = (radius[i] + 0.7)*ang2bohr;\n  }\n  double grd_min_x = atoms[0].x;\n  double grd_min_y = atoms[0].y;\n  double grd_min_z = atoms[0].z;\n  \n  double grd_max_x = atoms[0].x;\n  double grd_max_y = atoms[0].y;\n  double grd_max_z = atoms[0].z;\n  \n  for (auto ia = 1; ia < atoms.size(); ++ia) {\n\n    grd_min_x = min(grd_min_x, atoms[ia].x);\n    grd_min_y = min(grd_min_y, atoms[ia].y);\n    grd_min_z = min(grd_min_z, atoms[ia].z);\n\n    grd_max_x = max(grd_max_x, atoms[ia].x);\n    grd_max_y = max(grd_max_y, atoms[ia].y);\n    grd_max_z = max(grd_max_z, atoms[ia].z);\n\n  }\n  //\n  // calculate the grid size\n  //\n  // A --> au\n  const double rcut = 3.0*ang2bohr;\n  const double rcut2= rcut*rcut;\n  const double spac = 0.5*ang2bohr;\n  \n  const int ngrid_x = int ((grd_max_x - grd_min_x + 2.0*rcut)/spac) + 1;\n  const int ngrid_y = int ((grd_max_y - grd_min_y + 2.0*rcut)/spac) + 1;\n  const int ngrid_z = int ((grd_max_z - grd_min_z + 2.0*rcut)/spac) + 1;\n\n  const auto small = 1.0e-8;\n  arma::vec3 vg;\n  \n  for(auto iz = 0; iz <  ngrid_z; ++iz)\n    for(auto iy = 0; iy <  ngrid_y; ++iy)\n      for(auto ix = 0; ix <  ngrid_x; ++ix) {\n\n\tvg.zeros();\n\t\n\tvg(0) = grd_min_x - rcut + ix*spac;\n\tvg(1) = grd_min_y - rcut + iy*spac;\n\tvg(2) = grd_min_z - rcut + iz*spac;\n\n\tdouble dmin = rcut2;\n\t\n\tbool lupdate = true;\n\t\n\tfor (auto ia = 0; ia < atoms.size(); ++ia) {\n\t  int iz    = atoms[ia].atomic_number;\n\t  auto rad2 = radius[iz]*radius[iz];\n\n\t  auto dx = vg(0) - atoms[ia].x;\n\t  auto dy = vg(1) - atoms[ia].y;\n\t  auto dz = vg(2) - atoms[ia].z;\n\t  \n\t  auto d2  = dx*dx + dy*dy + dz*dz;\n\n\t  if ( (rad2 - d2) > small) {\n\t    lupdate = false;\n\t    break;\n\t  }\n\n\t  if ( (dmin-d2) > small) dmin = d2;\n\t  \n\t}\n\n\tif (lupdate) {\n\t  if ( (rcut2 - dmin) > small) {\n\t    m_grids.push_back (vg);\n\t  }\n\t}\n\t\n      }\n\n}\n\n\n} } // namespace willow::qcmol\n", "meta": {"hexsha": "52a5091f094fa72fe853be8d190640262351a337", "size": 7850, "ext": "cc", "lang": "C++", "max_stars_repo_path": "esp.cc", "max_stars_repo_name": "swillow/w-qcmol", "max_stars_repo_head_hexsha": "b278417ca8b9eaf08c4a0712e295bdf5ac18595a", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2018-02-19T22:13:38.000Z", "max_stars_repo_stars_event_max_datetime": "2018-02-19T22:13:42.000Z", "max_issues_repo_path": "esp.cc", "max_issues_repo_name": "swillow/w-qcmol", "max_issues_repo_head_hexsha": "b278417ca8b9eaf08c4a0712e295bdf5ac18595a", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "esp.cc", "max_forks_repo_name": "swillow/w-qcmol", "max_forks_repo_head_hexsha": "b278417ca8b9eaf08c4a0712e295bdf5ac18595a", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.4480874317, "max_line_length": 79, "alphanum_fraction": 0.5392356688, "num_tokens": 2859, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7154239836484143, "lm_q2_score": 0.4571367168274948, "lm_q1q2_score": 0.32704657102468343}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\n\n// Copyright (c) 2007-2015 Barend Gehrels, Amsterdam, the Netherlands.\n// Copyright (c) 2008-2015 Bruno Lalande, Paris, France.\n// Copyright (c) 2009-2015 Mateusz Loskot, London, UK.\n\n// This file was modified by Oracle on 2014, 2015.\n// Modifications copyright (c) 2014-2015, Oracle and/or its affiliates.\n\n// Contributed and/or modified by Menelaos Karavelas, on behalf of Oracle\n\n// Parts of Boost.Geometry are redesigned from Geodan's Geographic Library\n// (geolib/GGL), copyright (c) 1995-2010 Geodan, Amsterdam, the Netherlands.\n\n// Use, modification and distribution is subject to the Boost Software License,\n// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n\n#ifndef TTMATH_STUB\n#define TTMATH_STUB\n\n#include <boost/math/constants/constants.hpp>\n#include <boost/numeric/conversion/cast.hpp>\n#include <boost/geometry/util/math.hpp>\n#include <boost/geometry/util/coordinate_cast.hpp>\n\n\n#include <ttmath.h>\nnamespace ttmath\n{\n    template <uint Exponent, uint Mantissa>\n    inline Big<Exponent, Mantissa> sqrt(Big<Exponent, Mantissa> const& v)\n    {\n        return Sqrt(v);\n    }\n\n    template <uint Exponent, uint Mantissa>\n    inline Big<Exponent, Mantissa> abs(Big<Exponent, Mantissa> const& v)\n    {\n        return Abs(v);\n    }\n\n    template <uint Exponent, uint Mantissa>\n    inline Big<Exponent, Mantissa> ceil(Big<Exponent, Mantissa> const& v)\n    {\n        return Ceil(v);\n    }\n\n    template <uint Exponent, uint Mantissa>\n    inline Big<Exponent, Mantissa> floor(Big<Exponent, Mantissa> const& v)\n    {\n        return Floor(v);\n    }\n\n    template <uint Exponent, uint Mantissa>\n    inline Big<Exponent, Mantissa> asin(Big<Exponent, Mantissa> const& v)\n    {\n        return ASin(v);\n    }\n\n    template <uint Exponent, uint Mantissa>\n    inline Big<Exponent, Mantissa> sin(Big<Exponent, Mantissa> const& v)\n    {\n        return Sin(v);\n    }\n\n    template <uint Exponent, uint Mantissa>\n    inline Big<Exponent, Mantissa> cos(Big<Exponent, Mantissa> const& v)\n    {\n        return Cos(v);\n    }\n\n    template <uint Exponent, uint Mantissa>\n    inline Big<Exponent, Mantissa> tan(Big<Exponent, Mantissa> const& v)\n    {\n        return Tan(v);\n    }\n\n    template <uint Exponent, uint Mantissa>\n    inline Big<Exponent, Mantissa> atan(Big<Exponent, Mantissa> const& v)\n    {\n        return ATan(v);\n    }\n\n    template <uint Exponent, uint Mantissa>\n    inline Big<Exponent, Mantissa> acos(Big<Exponent, Mantissa> const& v)\n    {\n        return ACos(v);\n    }\n\n    template <uint Exponent, uint Mantissa>\n    inline Big<Exponent, Mantissa> atan2(Big<Exponent, Mantissa> const& y, Big<Exponent, Mantissa> const& x)\n    {\n        // return ATan2(y, 2); does not (yet) exist in ttmath...\n\n        // See http://en.wikipedia.org/wiki/Atan2\n\n        Big<Exponent, Mantissa> const zero(0);\n        Big<Exponent, Mantissa> const two(2);\n\n        if (y == zero)\n        {\n            // return x >= 0 ? 0 : pi and pi=2*arccos(0)\n            return x >= zero ? zero : two * ACos(zero);\n        }\n\n        return two * ATan((sqrt(x * x + y * y) - x) / y);\n    }\n\n    // needed in order to work with boost::geometry::math::mod\n    template <uint Exponent, uint Mantissa>\n    inline Big<Exponent, Mantissa> mod(Big<Exponent, Mantissa> const& x,\n                                       Big<Exponent, Mantissa> const& y)\n    {\n        return Mod(x, y);\n    }\n}\n\n// Specific structure implementing constructor\n// (WHICH IS NECESSARY FOR Boost.Geometry because it enables using T() !! )\nstruct ttmath_big : ttmath::Big<1,4>\n{\n    ttmath_big(double v = 0)\n        : ttmath::Big<1,4>(v)\n    {}\n    ttmath_big(ttmath::Big<1,4> const& v)\n        : ttmath::Big<1,4>(v)\n    {}\n\n    // unary operator+() is implemented for completeness\n    inline ttmath_big const& operator+() const\n    {\n        return *this;\n    }\n\n    // needed in order to work with boost::geometry::math::abs\n    inline ttmath_big operator-() const\n    {\n        return ttmath::Big<1,4>::operator-();\n    }\n\n    /*\n    inline operator double() const\n    {\n        return atof(this->ToString().c_str());\n    }\n\n    inline operator int() const\n    {\n        return atol(ttmath::Round(*this).ToString().c_str());\n    }\n    */\n};\n\n\n// arithmetic operators for ttmath_big objects, defined as free functions\ninline ttmath_big operator+(ttmath_big const& x, ttmath_big const& y)\n{\n    return static_cast<ttmath::Big<1,4> const&>(x).operator+(y);\n}\n\ninline ttmath_big operator-(ttmath_big const& x, ttmath_big const& y)\n{\n    return static_cast<ttmath::Big<1,4> const&>(x).operator-(y);\n}\n\ninline ttmath_big operator*(ttmath_big const& x, ttmath_big const& y)\n{\n    return static_cast<ttmath::Big<1,4> const&>(x).operator*(y);\n}\n\ninline ttmath_big operator/(ttmath_big const& x, ttmath_big const& y)\n{\n    return static_cast<ttmath::Big<1,4> const&>(x).operator/(y);\n}\n\n\nnamespace boost{ namespace geometry { namespace math\n{\n\nnamespace detail\n{\n    // Workaround for boost::math::constants::pi:\n    // 1) lexical cast -> stack overflow and\n    // 2) because it is implemented as a function, generic implementation not possible\n\n    // Partial specialization for ttmath\n    template <ttmath::uint Exponent, ttmath::uint Mantissa>\n    struct define_half_pi<ttmath::Big<Exponent, Mantissa> >\n    {\n        static inline ttmath::Big<Exponent, Mantissa> apply()\n        {\n            static ttmath::Big<Exponent, Mantissa> const half_pi(\n                \"1.57079632679489661923132169163975144209858469968755291048747229615390820314310449931401741267105853399107404325664115332354692230477529111586267970406424055872514205135096926055277982231147447746519098\");\n            return half_pi;\n        }\n    };\n\n    // Partial specialization for ttmath\n    template <ttmath::uint Exponent, ttmath::uint Mantissa>\n    struct define_pi<ttmath::Big<Exponent, Mantissa> >\n    {\n        static inline ttmath::Big<Exponent, Mantissa> apply()\n        {\n            static ttmath::Big<Exponent, Mantissa> const the_pi(\n                \"3.14159265358979323846264338327950288419716939937510582097494459230781640628620899862803482534211706798214808651328230664709384460955058223172535940812848111745028410270193852110555964462294895493038196\");\n            return the_pi;\n        }\n    };\n\n    // Partial specialization for ttmath\n    template <ttmath::uint Exponent, ttmath::uint Mantissa>\n    struct define_two_pi<ttmath::Big<Exponent, Mantissa> >\n    {\n        static inline ttmath::Big<Exponent, Mantissa> apply()\n        {\n            static ttmath::Big<Exponent, Mantissa> const two_pi(\n                \"6.28318530717958647692528676655900576839433879875021164194988918461563281257241799725606965068423413596429617302656461329418768921910116446345071881625696223490056820540387704221111928924589790986076392\");\n            return two_pi;\n        }\n    };\n\n    template <>\n    struct define_half_pi<ttmath_big>\n            : public define_half_pi<ttmath::Big<1,4> >\n    {};\n\n    template <>\n    struct define_pi<ttmath_big>\n            : public define_pi<ttmath::Big<1,4> >\n    {};\n\n    template <>\n    struct define_two_pi<ttmath_big>\n            : public define_two_pi<ttmath::Big<1,4> >\n    {};\n\n    template <ttmath::uint Exponent, ttmath::uint Mantissa>\n    struct equals_with_epsilon<ttmath::Big<Exponent, Mantissa>, false>\n    {\n        static inline bool apply(ttmath::Big<Exponent, Mantissa> const& a, ttmath::Big<Exponent, Mantissa> const& b)\n        {\n            // See implementation in util/math.hpp\n            // But here borrow the tolerance for double, to avoid exact comparison\n            ttmath::Big<Exponent, Mantissa> const epsilon = std::numeric_limits<double>::epsilon();\n            return ttmath::Abs(a - b) <= epsilon * ttmath::Abs(a);\n        }\n    };\n\n    template <>\n    struct equals_with_epsilon<ttmath_big, false>\n            : public equals_with_epsilon<ttmath::Big<1, 4>, false>\n    {};\n\n} // detail\n\n} // ttmath\n\n\nnamespace detail\n{\n\ntemplate <ttmath::uint Exponent, ttmath::uint Mantissa>\nstruct coordinate_cast<ttmath::Big<Exponent, Mantissa> >\n{\n    static inline ttmath::Big<Exponent, Mantissa> apply(std::string const& source)\n    {\n        return ttmath::Big<Exponent, Mantissa> (source);\n    }\n};\n\n\ntemplate <>\nstruct coordinate_cast<ttmath_big>\n{\n    static inline ttmath_big apply(std::string const& source)\n    {\n        return ttmath_big(source);\n    }\n};\n\n} // namespace detail\n\n\n}} // boost::geometry\n\n\n\n\n// Support for boost::numeric_cast to int and to double (necessary for SVG-mapper)\nnamespace boost { namespace numeric\n{\n\ntemplate\n<\n    ttmath::uint Exponent, ttmath::uint Mantissa,\n    typename Traits,\n    typename OverflowHandler,\n    typename Float2IntRounder,\n    typename RawConverter,\n    typename UserRangeChecker\n>\nstruct converter<int, ttmath::Big<Exponent, Mantissa>, Traits, OverflowHandler, Float2IntRounder, RawConverter, UserRangeChecker>\n{\n    static inline int convert(ttmath::Big<Exponent, Mantissa> arg)\n    {\n        int v;\n        arg.ToInt(v);\n        return v;\n    }\n};\n\ntemplate\n<\n    ttmath::uint Exponent, ttmath::uint Mantissa,\n    typename Traits,\n    typename OverflowHandler,\n    typename Float2IntRounder,\n    typename RawConverter,\n    typename UserRangeChecker\n>\nstruct converter<double, ttmath::Big<Exponent, Mantissa>, Traits, OverflowHandler, Float2IntRounder, RawConverter, UserRangeChecker>\n{\n    static inline double convert(ttmath::Big<Exponent, Mantissa> arg)\n    {\n        double v;\n        arg.ToDouble(v);\n        return v;\n    }\n};\n\n\ntemplate\n<\n    typename Traits,\n    typename OverflowHandler,\n    typename Float2IntRounder,\n    typename RawConverter,\n    typename UserRangeChecker\n>\nstruct converter<int, ttmath_big, Traits, OverflowHandler, Float2IntRounder, RawConverter, UserRangeChecker>\n{\n    static inline int convert(ttmath_big arg)\n    {\n        int v;\n        arg.ToInt(v);\n        return v;\n    }\n};\n\ntemplate\n<\n    typename Traits,\n    typename OverflowHandler,\n    typename Float2IntRounder,\n    typename RawConverter,\n    typename UserRangeChecker\n>\nstruct converter<double, ttmath_big, Traits, OverflowHandler, Float2IntRounder, RawConverter, UserRangeChecker>\n{\n    static inline double convert(ttmath_big arg)\n    {\n        double v;\n        arg.ToDouble(v);\n        return v;\n    }\n};\n\n\n}}\n\n\n#endif\n", "meta": {"hexsha": "cb53fc114c72da35bfbd6b0c8eff5c3a3f235dd1", "size": 10369, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "3party/boost/boost/geometry/extensions/contrib/ttmath_stub.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/contrib/ttmath_stub.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/contrib/ttmath_stub.hpp", "max_forks_repo_name": "bowlofstew/omim", "max_forks_repo_head_hexsha": "8045157c95244aa8f862d47324df42a19b87e335", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-08-09T21:21:09.000Z", "max_forks_repo_forks_event_max_datetime": "2019-08-09T21:21:09.000Z", "avg_line_length": 27.7245989305, "max_line_length": 222, "alphanum_fraction": 0.6666988138, "num_tokens": 2797, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6859494678483918, "lm_q2_score": 0.476579651063676, "lm_q1q2_score": 0.32690955803450084}}
{"text": "/*\n * img_align.cpp\n *\n *  Created on: Aug 22, 2012\n *      Author: cforster\n */\n\n#include <vector>\n#include <string>\n#include <stdint.h>\n#include <stdio.h>\n#include <iostream>\n#include <math.h>\n#include <Eigen/Core>\n#include <Eigen/StdVector>\n#include <opencv2/opencv.hpp>\n#include <vikit/math_utils.h>\n#include <vikit/vision.h>\n#include <vikit/pinhole_camera.h>\n#include <vikit/nlls_solver.h>\n#include <vikit/performance_monitor.h>\n#include <vikit/img_align.h>\n#include <sophus/se3.h>\n\nnamespace vk {\n\n/*******************************************************************************\n * Forward Compositional\n */\nForwardCompositionalSE3::\nForwardCompositionalSE3( vector<PinholeCamera>& cam_pyr,\n                         vector<cv::Mat>& depth_pyr,\n                         vector<cv::Mat>& img_pyr,\n                         vector<cv::Mat>& tpl_pyr,\n                         vector<cv::Mat>& img_pyr_dx,\n                         vector<cv::Mat>& img_pyr_dy,\n                         SE3& init_model,\n                         int n_levels,\n                         int n_iter,\n                         float res_thresh,\n                         bool display,\n                         Method method,\n                         int test_id) :\n      cam_pyr_(cam_pyr),\n      depth_pyr_(depth_pyr),\n      img_pyr_(img_pyr),\n      tpl_pyr_(tpl_pyr),\n      img_pyr_dx_(img_pyr_dx),\n      img_pyr_dy_(img_pyr_dy),\n      display_(display),\n      log_(test_id < 0),\n      res_thresh_(res_thresh)\n{\n  n_iter_ = n_iter;\n  method_ = method;\n\n  // Init Performance Monitor\n#if 0\n  if(log_)\n  {\n    permon_.init(\"forward\", ros::package::getPath(\"rpl_examples\") + \"/trace/img_align/data\",\n                 test_id, true);\n    permon_.addLog(\"iter\");\n    permon_.addLog(\"level\");\n    permon_.addLog(\"mu\");\n    permon_.addLog(\"chi2\");\n    permon_.addLog(\"trials\");\n  }\n#endif\n\n  runOptimization(init_model);\n\n}\n\nForwardCompositionalSE3::\nForwardCompositionalSE3( vector<PinholeCamera>& cam_pyr,\n                         vector<cv::Mat>& depth_pyr,\n                         vector<cv::Mat>& img_pyr,\n                         vector<cv::Mat>& tpl_pyr,\n                         vector<cv::Mat>& img_pyr_dx,\n                         vector<cv::Mat>& img_pyr_dy,\n                         int n_levels,\n                         int n_iter,\n                         float res_thresh,\n                         bool display,\n                         Method method,\n                         int test_id) :\n      cam_pyr_(cam_pyr),\n      depth_pyr_(depth_pyr),\n      img_pyr_(img_pyr),\n      tpl_pyr_(tpl_pyr),\n      img_pyr_dx_(img_pyr_dx),\n      img_pyr_dy_(img_pyr_dy),\n      display_(display),\n      log_(test_id < 0),\n      res_thresh_(res_thresh)\n{\n  n_iter_ = n_iter;\n  method_ = method;\n\n  // Init Performance Monitor\n#if 0\n  if(log_)\n  {\n    permon_.init(\"forward\", ros::package::getPath(\"rpl_examples\") + \"/trace/img_align/data\",\n                 test_id, true);\n    permon_.addLog(\"iter\");\n    permon_.addLog(\"level\");\n    permon_.addLog(\"mu\");\n    permon_.addLog(\"chi2\");\n    permon_.addLog(\"trials\");\n  }\n#endif\n\n}\n\nvoid ForwardCompositionalSE3::\nrunOptimization(SE3& model, int levelBegin, int levelEnd)\n{\n  if(levelBegin < 0 || levelBegin > n_levels_-1)\n    levelBegin = n_levels_-1;\n  if(levelEnd < 0)\n    levelEnd = 1;\n\n  // Perform Pyramidal optimization\n  for(level_=levelBegin; level_>=levelEnd; --level_)\n  {\n    mu_ = 0.1;\n    cout << endl << \"PYRAMID LEVEL \" << level_\n         << endl << \"---------------\" << endl;\n    optimize(model);\n  }\n}\n\ndouble ForwardCompositionalSE3::\ncomputeResiduals (const SE3& model, bool linearize_system, bool compute_weight_scale)\n{\n  // Warp the image such that it aligns with the template image\n  double chi2 = 0;\n  size_t n_pixels = 0;\n\n  if(linearize_system)\n    resimg_ = cv::Mat(tpl_pyr_[level_].size(), CV_32F, cv::Scalar(1));\n\n  for( int v=0; v<depth_pyr_[level_].rows; ++v )\n  {\n    for( int u=0; u<depth_pyr_[level_].cols; ++u )\n    {\n      // compute pixel location in new img\n      cv::Vec3f cv_float3 = depth_pyr_[level_].at<cv::Vec3f>(v,u);\n      Vector3d xyz_tpl(cv_float3[0], cv_float3[1], cv_float3[2]);\n      Vector3d xyz_img(model*xyz_tpl);\n      Vector2f uv_img_pyr = cam_pyr_[level_].world2cam(xyz_img).cast<float>(); // apply cam model\n      if( cam_pyr_[level_].isInFrame(uv_img_pyr.cast<int>(), 2) )\n      {\n        // compare image values\n        float intensity_tpl =\n            tpl_pyr_[level_].at<float>(v,u);\n        float intensity_img =\n            interpolateMat_32f(img_pyr_[level_], uv_img_pyr[0], uv_img_pyr[1]);\n\n        // compute residual (opposite to 2d case because of other jacobian)\n        float res = intensity_tpl-intensity_img;\n\n        // robustification\n        if(res > res_thresh_)  res = res_thresh_;\n        if(res < -res_thresh_) res = -res_thresh_;\n        chi2 += res*res;\n        n_pixels++;\n\n        if(linearize_system)\n        {\n          // get gradient of warped image (~gradient at warped position)\n          float dx = 0.5*interpolateMat_32f(img_pyr_dx_[level_], uv_img_pyr[0], uv_img_pyr[1]);\n          float dy = 0.5*interpolateMat_32f(img_pyr_dy_[level_], uv_img_pyr[0], uv_img_pyr[1]);\n\n          // evaluate jacobian\n          Matrix<double,2,6> frame_jac;\n          frameJac_xyz2uv(xyz_img, cam_pyr_[level_].fx(), frame_jac);\n\n          // compute steppest descent images\n          Vector6d J = dx*frame_jac.row(0) + dy*frame_jac.row(1);\n\n          // compute Hessian and\n          H_ += J*J.transpose();\n          Jres_ += J*res;\n\n          resimg_.at<float>(v,u) = -res;\n        }\n      }\n    }\n  }\n  chi2 /= n_pixels;\n  return chi2;\n}\n\nint ForwardCompositionalSE3::\nsolve()\n{\n  x_ = H_.ldlt().solve(-Jres_);\n  if((bool) std::isnan((double) x_[0]))\n    return 0;\n  return 1;\n}\n\nvoid ForwardCompositionalSE3::\nupdate(const ModelType& old_model,  ModelType& new_model)\n{\n  new_model = SE3::exp(x_)*(old_model);\n}\n\nvoid ForwardCompositionalSE3::\nstartIteration()\n{\n#if 0\n  if(log_)\n    permon_.newMeasurement();\n#endif\n}\n\nvoid ForwardCompositionalSE3::\nfinishIteration()\n{\n#if 0\n  if(log_)\n  {\n    permon_.log(\"iter\", iter_);\n    permon_.log(\"level\", level_);\n    permon_.log(\"mu\", mu_);\n    permon_.log(\"chi2\", chi2_);\n    permon_.log(\"trials\", n_trials_);\n  }\n#endif\n\n  if(display_)\n  {\n    cv::namedWindow(\"residuals\", CV_WINDOW_AUTOSIZE);\n    cv::imshow(\"residuals\", resimg_*3);\n    cv::waitKey(0);\n  }\n}\n\n/*******************************************************************************\n * Efficient Second Order Minimization (ESM)\n */\nSecondOrderMinimisationSE3::\nSecondOrderMinimisationSE3( vector<PinholeCamera>& cam_pyr,\n                            vector<cv::Mat>& depth_pyr,\n                            vector<cv::Mat>& img_pyr,\n                            vector<cv::Mat>& tpl_pyr,\n                            vector<cv::Mat>& img_pyr_dx,\n                            vector<cv::Mat>& img_pyr_dy,\n                            vector<cv::Mat>& tpl_pyr_dx,\n                            vector<cv::Mat>& tpl_pyr_dy,\n                            SE3& init_model,\n                            int n_levels,\n                            int n_iter,\n                            float res_thresh,\n                            bool display,\n                            Method method,\n                            int test_id) :\n      cam_pyr_(cam_pyr),\n      depth_pyr_(depth_pyr),\n      img_pyr_(img_pyr),\n      tpl_pyr_(tpl_pyr),\n      img_pyr_dx_(img_pyr_dx),\n      img_pyr_dy_(img_pyr_dy),\n      tpl_pyr_dx_(tpl_pyr_dx),\n      tpl_pyr_dy_(tpl_pyr_dy),\n      display_(display),\n      log_(test_id < 0),\n      res_thresh_(res_thresh)\n{\n  n_iter_ = n_iter;\n  method_ = method;\n  verbose_ = false;\n\n#if 0\n  if(log_)\n  {\n    // Init Performance Monitor\n    permon_.init(\"esm\", ros::package::getPath(\"rpl_examples\") + \"/trace/img_align/data\",\n                 test_id, true);\n    permon_.addLog(\"iter\");\n    permon_.addLog(\"level\");\n    permon_.addLog(\"mu\");\n    permon_.addLog(\"chi2\");\n    permon_.addLog(\"trials\");\n  }\n#endif\n\n  // perform pyramidal optimization\n  for(level_=n_levels-1; level_>2; --level_)\n  //level_ = n_levels-1;\n  {\n    // Optimize\n    mu_ = 0.01f;\n    if(display_)\n    {\n      cout << endl << \"PYRAMID LEVEL \" << level_\n           << endl << \"patch-width = \" << img_pyr_[level_].cols\n           << endl << \"---------------\" << endl;\n    }\n    optimize(init_model);\n  }\n}\n\ndouble SecondOrderMinimisationSE3::\ncomputeResiduals (const SE3& model, bool linearize_system, bool compute_weight_scale)\n{\n  // Warp the image such that it aligns with the template image\n  double chi2 = 0;\n  size_t n_pixels = 0;\n\n  // TODO: to improve access speed, use a pointer and increment every iteration\n\n  // Compute Warp\n  cv::Mat mask = cv::Mat_<bool>(tpl_pyr_[level_].rows, tpl_pyr_[level_].cols, false);\n  cv::Mat img_warped = cv::Mat_<float>(tpl_pyr_[level_].rows, tpl_pyr_[level_].cols, 1.0);\n\n  for( int v=0; v<depth_pyr_[level_].rows; ++v )\n  {\n    for( int u=0; u<depth_pyr_[level_].cols; ++u )\n    {\n      // compute pixel location in new img\n      cv::Vec3f cv_float3 = depth_pyr_[level_].at<cv::Vec3f>(v,u);\n      Vector3d xyz_tpl(cv_float3[0], cv_float3[1], cv_float3[2]);\n      Vector3d xyz_img(model*xyz_tpl);\n      Vector2f uv_img_pyr = cam_pyr_[level_].world2cam(xyz_img).cast<float>(); // apply cam model\n      if( cam_pyr_[level_].isInFrame(uv_img_pyr.cast<int>(), 1) )\n      {\n        img_warped.at<float>(v,u) = interpolateMat_32f(img_pyr_[level_], uv_img_pyr[0], uv_img_pyr[1]);\n\n        if( cam_pyr_[level_].isInFrame(uv_img_pyr.cast<int>(), 2) )\n          mask.at<bool>(v,u) = true;\n      }\n    }\n  }\n\n  // Compute Warp derivative\n  cv::Mat img_warped_dx, img_warped_dy;\n  cv::Sobel(img_warped, img_warped_dx, CV_32F, 1, 0, 1);\n  cv::Sobel(img_warped, img_warped_dy, CV_32F, 0, 1, 1);\n\n  // Compute Jacobian\n  if(linearize_system)\n    resimg_ = cv::Mat_<float>(tpl_pyr_[level_].size(), 1.0);\n\n  for( int v=0; v<depth_pyr_[level_].rows; ++v )\n  {\n    for( int u=0; u<depth_pyr_[level_].cols; ++u )\n    {\n      if (mask.at<bool>(v,u))\n      {\n        // compare image values\n        float intensity_tpl = tpl_pyr_[level_].at<float>(v,u);\n        float intensity_img = img_warped.at<float>(v,u);\n\n        // compute residual  (opposite to 2d case because of other jacobian)\n        float res = intensity_tpl-intensity_img;\n\n        // robustification\n        if(res > res_thresh_)  res = res_thresh_;\n        if(res < -res_thresh_) res = -res_thresh_;\n        chi2 += res*res;\n        n_pixels++;\n\n        if(linearize_system)\n        {\n          // 0.25 because we have two 0.5 factors. First from adding the two gradients\n          // and the second when we compute the sobel mask\n          float dx = 0.25*(tpl_pyr_dx_[level_].at<float>(v,u) + img_warped_dx.at<float>(v,u));\n          float dy = 0.25*(tpl_pyr_dy_[level_].at<float>(v,u) + img_warped_dy.at<float>(v,u));\n\n          // evaluate jacobian\n          cv::Vec3f cv_float3 = depth_pyr_[level_].at<cv::Vec3f>(v,u);\n          Vector3d xyz_tpl(cv_float3[0], cv_float3[1], cv_float3[2]);\n          Vector3d xyz_img(model*xyz_tpl);\n          Matrix<double,2,6> frame_jac;\n          frameJac_xyz2uv(xyz_tpl, cam_pyr_[level_].fx(), frame_jac);\n\n          // compute steppest descent images\n          Vector6d J = dx*frame_jac.row(0) + dy*frame_jac.row(1);\n\n          // compute Hessian\n          H_ += J*J.transpose();\n          Jres_ += J*res;\n          resimg_.at<float>(v,u) = res;\n        }\n      }\n    }\n  }\n  chi2 /= n_pixels;\n  return chi2;\n}\n\nint SecondOrderMinimisationSE3::\nsolve()\n{\n  x_ = H_.ldlt().solve(-Jres_);\n  if((bool) std::isnan((double) x_[0]))\n    return 0;\n  return 1;\n}\n\nvoid SecondOrderMinimisationSE3::\nupdate(const ModelType& old_model,  ModelType& new_model)\n{\n  new_model = SE3::exp(x_)*old_model;\n}\n\nvoid SecondOrderMinimisationSE3::\nstartIteration()\n{\n#if 0\n  if(log_)\n    permon_.newMeasurement();\n#endif\n}\n\nvoid SecondOrderMinimisationSE3::\nfinishIteration()\n{\n#if 0\n  if(log_)\n  {\n    permon_.log(\"iter\", iter_);\n    permon_.log(\"level\", level_);\n    permon_.log(\"mu\", mu_);\n    permon_.log(\"chi2\", chi2_);\n    permon_.log(\"trials\", n_trials_);\n  }\n#endif\n\n  if(display_)\n  {\n    cv::namedWindow(\"residuals\", CV_WINDOW_AUTOSIZE);\n    cv::imshow(\"residuals\", resimg_*3);\n    cv::waitKey(0);\n  }\n}\n\n} // end namespace vk\n", "meta": {"hexsha": "3fcd8b54a10c41bb9af18d34b49b3f049deac508", "size": 12320, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "rpg_vikit/vikit_common/src/img_align.cpp", "max_stars_repo_name": "vatanaksoytezer/zephyr", "max_stars_repo_head_hexsha": "3880dbdb62ec7908d4eed1bc173544979925997c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2019-03-21T15:18:17.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-28T07:52:10.000Z", "max_issues_repo_path": "rpg_vikit/vikit_common/src/img_align.cpp", "max_issues_repo_name": "VatanTezer/zephyr", "max_issues_repo_head_hexsha": "3880dbdb62ec7908d4eed1bc173544979925997c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-02-16T22:01:11.000Z", "max_issues_repo_issues_event_max_datetime": "2019-02-16T22:01:11.000Z", "max_forks_repo_path": "rpg_vikit/vikit_common/src/img_align.cpp", "max_forks_repo_name": "VatanTezer/zephyr", "max_forks_repo_head_hexsha": "3880dbdb62ec7908d4eed1bc173544979925997c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-08-10T14:09:54.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-13T13:50:24.000Z", "avg_line_length": 27.7477477477, "max_line_length": 103, "alphanum_fraction": 0.5792207792, "num_tokens": 3509, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6859494678483918, "lm_q2_score": 0.47657965106367595, "lm_q1q2_score": 0.3269095580345008}}
{"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#ifndef BOOST_GRAPH_MST_PRIM_HPP\n#define BOOST_GRAPH_MST_PRIM_HPP\n\n#include <functional>\n#include <boost/graph/graph_traits.hpp>\n#include <boost/graph/dijkstra_shortest_paths.hpp>\n\nnamespace boost {\n  \n  namespace detail {\n    // this should be somewhere else in boost...\n    template <class U, class V> struct _project2nd {\n      V operator()(U, V v) const { return v; }\n    };\n  }\n\n  namespace detail {\n\n    // This is Prim's algorithm to calculate the Minimum Spanning Tree\n    // for an undirected graph with weighted edges.\n\n    template <class Graph, class P, class T, class R, class Weight>\n    inline void\n    prim_mst_impl(const Graph& G,\n                  typename graph_traits<Graph>::vertex_descriptor s,\n                  const bgl_named_params<P,T,R>& params,\n                  Weight)\n    {\n      typedef typename property_traits<Weight>::value_type W;\n      std::less<W> compare;\n      detail::_project2nd<W,W> combine;\n      dijkstra_shortest_paths(G, s, params.distance_compare(compare).\n                              distance_combine(combine));\n    }\n  } // namespace detail\n\n  template <class VertexListGraph, class DijkstraVisitor, \n            class PredecessorMap, class DistanceMap,\n            class WeightMap, class IndexMap>\n  inline void\n  prim_minimum_spanning_tree\n    (const VertexListGraph& g,\n     typename graph_traits<VertexListGraph>::vertex_descriptor s, \n     PredecessorMap predecessor, DistanceMap distance, WeightMap weight, \n     IndexMap index_map,\n     DijkstraVisitor vis)\n  {\n    typedef typename property_traits<WeightMap>::value_type W;\n    std::less<W> compare;\n    detail::_project2nd<W,W> combine;\n    dijkstra_shortest_paths(g, s, predecessor, distance, weight, index_map,\n                            compare, combine, std::numeric_limits<W>::max(), 0,\n                            vis);\n  }\n\n  template <class VertexListGraph, class PredecessorMap,\n            class P, class T, class R>\n  inline void prim_minimum_spanning_tree\n    (const VertexListGraph& g,\n     PredecessorMap p_map,\n     const bgl_named_params<P,T,R>& params)\n  {\n    detail::prim_mst_impl\n      (g, \n       choose_param(get_param(params, root_vertex_t()), *vertices(g).first), \n       params.predecessor_map(p_map),\n       choose_const_pmap(get_param(params, edge_weight), g, edge_weight));\n  }\n\n  template <class VertexListGraph, class PredecessorMap>\n  inline void prim_minimum_spanning_tree\n    (const VertexListGraph& g, PredecessorMap p_map)\n  {\n    detail::prim_mst_impl\n      (g, *vertices(g).first, predecessor_map(p_map).\n       weight_map(get(edge_weight, g)),\n       get(edge_weight, g));\n  }\n\n} // namespace boost\n\n#endif // BOOST_GRAPH_MST_PRIM_HPP\n", "meta": {"hexsha": "b3b1facc8b21869fee4ae2575686a2f4f9282ebe", "size": 3948, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "vegastrike/boost/1_28/boost/graph/prim_minimum_spanning_tree.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": "vegastrike/boost/1_28/boost/graph/prim_minimum_spanning_tree.hpp", "max_issues_repo_name": "Ezeer/VegaStrike_win32FR", "max_issues_repo_head_hexsha": "75891b9ccbdb95e48e15d3b4a9cd977955b97d1f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "vegastrike/boost/1_28/boost/graph/prim_minimum_spanning_tree.hpp", "max_forks_repo_name": "Ezeer/VegaStrike_win32FR", "max_forks_repo_head_hexsha": "75891b9ccbdb95e48e15d3b4a9cd977955b97d1f", "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": 36.5555555556, "max_line_length": 79, "alphanum_fraction": 0.6732522796, "num_tokens": 899, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5774953651858118, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.32687308068501086}}
{"text": "//\n//=======================================================================\n// Copyright 2007 Stanford University\n// Authors: David Gleich\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_CORE_NUMBERS_HPP\n#define BOOST_GRAPH_CORE_NUMBERS_HPP\n\n#include <boost/graph/detail/d_ary_heap.hpp>\n#include <boost/graph/breadth_first_search.hpp>\n#include <boost/iterator/reverse_iterator.hpp>\n#include <boost/concept/assert.hpp>\n\n/*\n * core_numbers\n *\n * Requirement: IncidenceGraph\n */\n\n// History\n//\n// 30 July 2007\n// Added visitors to the implementation\n//\n// 8 February 2008\n// Fixed headers and missing typename\n\nnamespace boost {\n\n    // A linear time O(m) algorithm to compute the indegree core number\n    // of a graph for unweighted graphs.\n    //\n    // and a O((n+m) log n) algorithm to compute the in-edge-weight core\n    // numbers of a weighted graph.\n    //\n    // The linear algorithm comes from:\n    // Vladimir Batagelj and Matjaz Zaversnik, \"An O(m) Algorithm for Cores\n    // Decomposition of Networks.\"  Sept. 1 2002.\n\n    template <typename Visitor, typename Graph>\n    struct CoreNumbersVisitorConcept {\n        void constraints()\n        {\n            BOOST_CONCEPT_ASSERT(( CopyConstructibleConcept<Visitor> ));\n            vis.examine_vertex(u,g);\n            vis.finish_vertex(u,g);\n            vis.examine_edge(e,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 core_numbers_visitor : public bfs_visitor<Visitors> {\n        public:\n        core_numbers_visitor() {}\n        core_numbers_visitor(Visitors vis)\n            : bfs_visitor<Visitors>(vis) {}\n\n        private:\n        template <class Vertex, class Graph>\n        void initialize_vertex(Vertex, Graph&) {}\n\n        template <class Vertex, class Graph>\n        void discover_vertex(Vertex , Graph&) {}\n\n        template <class Vertex, class Graph>\n        void gray_target(Vertex, Graph&) {}\n\n        template <class Vertex, class Graph>\n        void black_target(Vertex, Graph&) {}\n\n        template <class Edge, class Graph>\n        void tree_edge(Edge, Graph&) {}\n\n        template <class Edge, class Graph>\n        void non_tree_edge(Edge, Graph&) {}\n    };\n\n    template <class Visitors>\n    core_numbers_visitor<Visitors> make_core_numbers_visitor(Visitors vis)\n    { return core_numbers_visitor<Visitors>(vis); }\n\n    typedef core_numbers_visitor<> default_core_numbers_visitor;\n\n    namespace detail {\n\n        // implement a constant_property_map to simplify compute_in_degree\n        // for the weighted and unweighted case\n        // this is based on dummy property map\n        template <typename ValueType>\n        class constant_value_property_map\n          : public boost::put_get_helper<ValueType,\n              constant_value_property_map<ValueType>  >\n        {\n        public:\n            typedef void key_type;\n            typedef ValueType value_type;\n            typedef const ValueType& reference;\n            typedef boost::readable_property_map_tag category;\n            inline constant_value_property_map(ValueType cc) : c(cc) { }\n            inline constant_value_property_map(const constant_value_property_map<ValueType>& x)\n              : c(x.c) { }\n            template <class Vertex>\n            inline reference operator[](Vertex) const { return c; }\n        protected:\n            ValueType c;\n        };\n\n\n        // the core numbers start as the indegree or inweight.  This function\n        // will initialize these values\n        template <typename Graph, typename CoreMap, typename EdgeWeightMap>\n        void compute_in_degree_map(Graph& g, CoreMap d, EdgeWeightMap wm)\n        {\n            typename graph_traits<Graph>::vertex_iterator vi,vi_end;\n            typename graph_traits<Graph>::out_edge_iterator ei,ei_end;\n            for (boost::tie(vi,vi_end) = vertices(g); vi!=vi_end; ++vi) {\n                put(d,*vi,0);\n            }\n            for (boost::tie(vi,vi_end) = vertices(g); vi!=vi_end; ++vi) {\n                for (boost::tie(ei,ei_end) = out_edges(*vi,g); ei!=ei_end; ++ei) {\n                    put(d,target(*ei,g),get(d,target(*ei,g))+get(wm,*ei));\n                }\n            }\n        }\n\n        // the version for weighted graphs is a little different\n        template <typename Graph, typename CoreMap,\n            typename EdgeWeightMap, typename MutableQueue,\n            typename Visitor>\n        typename property_traits<CoreMap>::value_type\n        core_numbers_impl(Graph& g, CoreMap c, EdgeWeightMap wm,\n            MutableQueue& Q, Visitor vis)\n        {\n            typename property_traits<CoreMap>::value_type v_cn = 0;\n            typedef typename graph_traits<Graph>::vertex_descriptor vertex;\n            while (!Q.empty())\n            {\n                // remove v from the Q, and then decrease the core numbers\n                // of its successors\n                vertex v = Q.top();\n                vis.examine_vertex(v,g);\n                Q.pop();\n                v_cn = get(c,v);\n                typename graph_traits<Graph>::out_edge_iterator oi,oi_end;\n                for (boost::tie(oi,oi_end) = out_edges(v,g); oi!=oi_end; ++oi) {\n                    vis.examine_edge(*oi,g);\n                    vertex u = target(*oi,g);\n                    // if c[u] > c[v], then u is still in the graph,\n                    if (get(c,u) > v_cn) {\n                        // remove the edge\n                        put(c,u,get(c,u)-get(wm,*oi));\n                        if (Q.contains(u))\n                          Q.update(u);\n                    }\n                }\n                vis.finish_vertex(v,g);\n            }\n            return (v_cn);\n        }\n\n        template <typename Graph, typename CoreMap, typename EdgeWeightMap,\n            typename IndexMap, typename CoreNumVisitor>\n        typename property_traits<CoreMap>::value_type\n        core_numbers_dispatch(Graph&g, CoreMap c, EdgeWeightMap wm,\n            IndexMap im, CoreNumVisitor vis)\n        {\n            typedef typename property_traits<CoreMap>::value_type D;\n            typedef std::less<D> Cmp;\n            // build the mutable queue\n            typedef typename graph_traits<Graph>::vertex_descriptor vertex;\n            std::vector<std::size_t> index_in_heap_data(num_vertices(g));\n            typedef iterator_property_map<std::vector<std::size_t>::iterator, IndexMap>\n              index_in_heap_map_type;\n            index_in_heap_map_type index_in_heap_map(index_in_heap_data.begin(), im);\n            typedef d_ary_heap_indirect<vertex, 4, index_in_heap_map_type, CoreMap, Cmp> MutableQueue;\n            MutableQueue Q(c, index_in_heap_map, Cmp());\n            typename graph_traits<Graph>::vertex_iterator vi,vi_end;\n            for (boost::tie(vi,vi_end) = vertices(g); vi!=vi_end; ++vi) {\n                Q.push(*vi);\n            }\n            return core_numbers_impl(g, c, wm, Q, vis);\n        }\n\n        // the version for the unweighted case\n        // for this functions CoreMap must be initialized\n        // with the in degree of each vertex\n        template <typename Graph, typename CoreMap, typename PositionMap,\n            typename Visitor>\n        typename property_traits<CoreMap>::value_type\n        core_numbers_impl(Graph& g, CoreMap c, PositionMap pos, Visitor vis)\n        {\n            typedef typename graph_traits<Graph>::vertices_size_type size_type;\n            typedef typename graph_traits<Graph>::degree_size_type degree_type;\n            typedef typename graph_traits<Graph>::vertex_descriptor vertex;\n            typename graph_traits<Graph>::vertex_iterator vi,vi_end;\n\n            // store the vertex core numbers\n            typename property_traits<CoreMap>::value_type v_cn = 0;\n\n            // compute the maximum degree (degrees are in the coremap)\n            typename graph_traits<Graph>::degree_size_type max_deg = 0;\n            for (boost::tie(vi,vi_end) = vertices(g); vi!=vi_end; ++vi) {\n                max_deg = (std::max<typename graph_traits<Graph>::degree_size_type>)(max_deg, get(c,*vi));\n            }\n\n            // store the vertices in bins by their degree\n            // allocate two extra locations to ease boundary cases\n            std::vector<size_type> bin(max_deg+2);\n            for (boost::tie(vi,vi_end) = vertices(g); vi!=vi_end; ++vi) {\n                ++bin[get(c,*vi)];\n            }\n\n            // this loop sets bin[d] to the starting position of vertices\n            // with degree d in the vert array for the bucket sort\n            size_type cur_pos = 0;\n            for (degree_type cur_deg = 0; cur_deg < max_deg+2; ++cur_deg) {\n                degree_type tmp = bin[cur_deg];\n                bin[cur_deg] = cur_pos;\n                cur_pos += tmp;\n            }\n\n            // perform the bucket sort with pos and vert so that\n            // pos[0] is the vertex of smallest degree\n            std::vector<vertex> vert(num_vertices(g));\n            for (boost::tie(vi,vi_end) = vertices(g); vi!=vi_end; ++vi) {\n                vertex v=*vi;\n                size_type p=bin[get(c,v)];\n                put(pos,v,p);\n                vert[p]=v;\n                ++bin[get(c,v)];\n            }\n            // we ``abused'' bin while placing the vertices, now,\n            // we need to restore it\n            std::copy(boost::make_reverse_iterator(bin.end()-2),\n                boost::make_reverse_iterator(bin.begin()),\n                boost::make_reverse_iterator(bin.end()-1));\n            // now simulate removing the vertices\n            for (size_type i=0; i < num_vertices(g); ++i) {\n                vertex v = vert[i];\n                vis.examine_vertex(v,g);\n                v_cn = get(c,v);\n                typename graph_traits<Graph>::out_edge_iterator oi,oi_end;\n                for (boost::tie(oi,oi_end) = out_edges(v,g); oi!=oi_end; ++oi) {\n                    vis.examine_edge(*oi,g);\n                    vertex u = target(*oi,g);\n                    // if c[u] > c[v], then u is still in the graph,\n                    if (get(c,u) > v_cn) {\n                        degree_type deg_u = get(c,u);\n                        degree_type pos_u = get(pos,u);\n                        // w is the first vertex with the same degree as u\n                        // (this is the resort operation!)\n                        degree_type pos_w = bin[deg_u];\n                        vertex w = vert[pos_w];\n                        if (u!=v) {\n                            // swap u and w\n                            put(pos,u,pos_w);\n                            put(pos,w,pos_u);\n                            vert[pos_w] = u;\n                            vert[pos_u] = w;\n                        }\n                        // now, the vertices array is sorted assuming\n                        // we perform the following step\n                        // start the set of vertices with degree of u\n                        // one into the future (this now points at vertex\n                        // w which we swapped with u).\n                        ++bin[deg_u];\n                        // we are removing v from the graph, so u's degree\n                        // decreases\n                        put(c,u,get(c,u)-1);\n                    }\n                }\n                vis.finish_vertex(v,g);\n            }\n            return v_cn;\n        }\n\n    } // namespace detail\n\n    // non-named parameter version for the unweighted case\n    template <typename Graph, typename CoreMap, typename CoreNumVisitor>\n    typename property_traits<CoreMap>::value_type\n    core_numbers(Graph& g, CoreMap c, CoreNumVisitor vis)\n    {\n        typedef typename graph_traits<Graph>::vertices_size_type size_type;\n        detail::compute_in_degree_map(g,c,\n            detail::constant_value_property_map<\n                typename property_traits<CoreMap>::value_type>(1) );\n        return detail::core_numbers_impl(g,c,\n            make_iterator_property_map(\n                std::vector<size_type>(num_vertices(g)).begin(),get(vertex_index, g)),\n            vis\n        );\n    }\n\n    // non-named paramter version for the unweighted case\n    template <typename Graph, typename CoreMap>\n    typename property_traits<CoreMap>::value_type\n    core_numbers(Graph& g, CoreMap c)\n    {\n        return core_numbers(g, c, make_core_numbers_visitor(null_visitor()));\n    }\n\n    // non-named parameter version for the weighted case\n    template <typename Graph, typename CoreMap, typename EdgeWeightMap,\n        typename VertexIndexMap, typename CoreNumVisitor>\n    typename property_traits<CoreMap>::value_type\n    core_numbers(Graph& g, CoreMap c, EdgeWeightMap wm, VertexIndexMap vim,\n        CoreNumVisitor vis)\n    {\n        typedef typename graph_traits<Graph>::vertices_size_type size_type;\n        detail::compute_in_degree_map(g,c,wm);\n        return detail::core_numbers_dispatch(g,c,wm,vim,vis);\n    }\n\n    // non-named parameter version for the weighted case\n//    template <typename Graph, typename CoreMap, typename EdgeWeightMap>\n//    typename property_traits<CoreMap>::value_type\n//    core_numbers(Graph& g, CoreMap c, EdgeWeightMap wm)\n//    {\n//        typedef typename graph_traits<Graph>::vertices_size_type size_type;\n//        detail::compute_in_degree_map(g,c,wm);\n//        return detail::core_numbers_dispatch(g,c,wm,get(vertex_index,g),\n//            make_core_numbers_visitor(null_visitor()));\n//    }\n\n    template <typename Graph, typename CoreMap>\n    typename property_traits<CoreMap>::value_type\n    weighted_core_numbers(Graph& g, CoreMap c)\n    {\n        return weighted_core_numbers(\n            g,c, make_core_numbers_visitor(null_visitor())\n        );\n    }\n\n    template <typename Graph, typename CoreMap, typename CoreNumVisitor>\n    typename property_traits<CoreMap>::value_type\n    weighted_core_numbers(Graph& g, CoreMap c, CoreNumVisitor vis)\n    { return core_numbers(g,c,get(edge_weight,g),get(vertex_index,g),vis); }\n\n} // namespace boost\n\n#endif // BOOST_GRAPH_CORE_NUMBERS_HPP\n\n", "meta": {"hexsha": "33764c4f40d50c528e7d3ddf7653fa08ad2a4faa", "size": 14308, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/boost/graph/core_numbers.hpp", "max_stars_repo_name": "randolphwong/mcsema", "max_stars_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_stars_repo_licenses": ["BSD-3-Clause"], "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/boost/graph/core_numbers.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/core_numbers.hpp", "max_forks_repo_name": "randolphwong/mcsema", "max_forks_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 39.0, "max_forks_repo_forks_event_min_datetime": "2015-01-07T02:03:15.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-15T00:41:50.000Z", "avg_line_length": 40.5325779037, "max_line_length": 106, "alphanum_fraction": 0.579466033, "num_tokens": 3050, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5774953651858118, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.32687308068501086}}
{"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/common/types.hpp>\n#include <crab/domains/patricia_trees.hpp>\n#include <crab/domains/separate_domains.hpp>\n\n#include <boost/range.hpp>\n\nnamespace ikos {\n\n  template< typename Element >\n  class discrete_domain: public writeable {\n    \n  private:\n    typedef patricia_tree_set< Element > ptset_t;\n\n  public:\n    typedef discrete_domain< Element > discrete_domain_t;\n    typedef typename ptset_t::iterator iterator;\n\n  private:\n    bool _is_top;\n    ptset_t _set;\n\n  private:\n    discrete_domain(bool is_top): _is_top(is_top) { }\n\n    discrete_domain(ptset_t set): _is_top(false), _set(set) { }\n\n  public:\n    static discrete_domain_t bottom() {\n      return discrete_domain_t(false);\n    }\n    \n    static discrete_domain_t top() {\n      return discrete_domain_t(true);\n    }\n\n  public:\n    discrete_domain(): _is_top(true) { }\n    \n    discrete_domain(const discrete_domain_t& other): \n        writeable(), _is_top(other._is_top), _set(other._set) { }\n\n    discrete_domain(Element s): _is_top(false), _set(s) { }\n\n    template<typename Iterator>\n    discrete_domain(Iterator eIt, Iterator eEt)\n        : _is_top(false) {\n      for (auto e: boost::make_iterator_range (eIt, eEt)) {\n        this->_set += e;\n      }\n    }\n\n    bool is_top() {\n      return this->_is_top;\n    }\n    \n    bool is_bottom() {\n      return (!this->_is_top && this->_set.empty());\n    }\n\n    bool operator<=(discrete_domain_t other) {\n      return other._is_top || (!this->_is_top && this->_set <= other._set);\n    }\n\n    bool operator==(discrete_domain_t other) {\n      return (this->_is_top && other._is_top) || (this->_set == other._set);\n    }\n\n    void operator|=(discrete_domain_t other) {\n      *this = *this | other;\n    }\n\n    discrete_domain_t operator|(discrete_domain_t other) {\n      if (this->_is_top || other._is_top) {\n        return discrete_domain_t(true);\n      } else {\n        return discrete_domain_t(this->_set | other._set);\n      }\n    }\n    \n    discrete_domain_t operator&(discrete_domain_t other) {\n      if (this->is_bottom() || other.is_bottom()) {\n        return discrete_domain_t(false);\n      } else if (this->_is_top) {\n        return other;\n      } else if (other._is_top) {\n        return *this;\n      } else {\n        return discrete_domain_t(this->_set & other._set);\n      }\n    }\n    \n    discrete_domain_t operator||(discrete_domain_t other) {\n      return this->operator|(other);\n    }\n    \n    discrete_domain_t operator&&(discrete_domain_t other) {\n      return this->operator&(other);\n    }\n    \n    discrete_domain_t& operator+=(Element s) {\n      if (!this->_is_top) {\n        this->_set += s;\n      }\n      return *this;\n    }\n    \n    template<typename Range>\n    discrete_domain_t& operator+=(Range es) {\n      if (!this->_is_top)\n        for (auto e: es)\n          this->_set += e;\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>\n    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 (!this->_is_top) {\n        this->_set -= s;\n      }\n      return *this;\n    }\n    \n    template<typename Range>\n    discrete_domain_t& operator-=(Range es) {\n      if (!this->_is_top)\n        for (auto e: es)\n          this->_set -= e;\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>\n    discrete_domain_t operator-(Range es) {\n      discrete_domain_t r(*this);\n      r.operator-=(es);\n      return r;\n    }\n    \n    std::size_t size() {\n      if (this->_is_top) {\n        CRAB_ERROR(\"Size for discrete domain TOP is undefined\");\n      } else {\n        return this->_set.size();\n      }\n    }\n    \n    iterator begin() {\n      if (this->_is_top) {\n        CRAB_ERROR(\"Iterator for discrete domain TOP is undefined\");\n      } else {\n        return this->_set.begin();\n      }\n    }\n    \n    iterator end() {\n      if (this->_is_top) {\n        CRAB_ERROR(\"Iterator for discrete domain TOP is undefined\");\n      } else {\n        return this->_set.end();\n      }\n    }\n    \n    void write(crab::crab_os& o) {\n      if (this->_is_top) {\n\to << \"{...}\";\n      } else if (this->_set.empty()) {\n\to << \"_|_\";\n      } else {\n\to << this->_set;\n      }\n    }\n    \n  }; // class discrete_domain\n\n} // namespace ikos\n\n\n", "meta": {"hexsha": "60919240d102ab63a7ab8b5b3febeb117f875c70", "size": 6699, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/crab/domains/discrete_domains.hpp", "max_stars_repo_name": "aziem/crab", "max_stars_repo_head_hexsha": "e150afd53d6fe49cefaade389542b3f3cfe9dbe5", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/crab/domains/discrete_domains.hpp", "max_issues_repo_name": "aziem/crab", "max_issues_repo_head_hexsha": "e150afd53d6fe49cefaade389542b3f3cfe9dbe5", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/crab/domains/discrete_domains.hpp", "max_forks_repo_name": "aziem/crab", "max_forks_repo_head_hexsha": "e150afd53d6fe49cefaade389542b3f3cfe9dbe5", "max_forks_repo_licenses": ["Apache-2.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.1470588235, "max_line_length": 80, "alphanum_fraction": 0.6245708315, "num_tokens": 1655, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5774953651858117, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.3268730806850108}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\n\n// Copyright (c) 2013 Barend Gehrels, Amsterdam, the Netherlands.\n// Copyright (c) 2013 Bruno Lalande, Paris, France.\n// Copyright (c) 2013 Mateusz Loskot, London, UK.\n// Copyright (c) 2013 Adam Wulkiewicz, Lodz, Poland.\n\n// Use, modification and distribution is subject to the Boost Software License,\n// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n\n#ifndef BOOST_GEOMETRY_ALGORITHMS_DETAIL_ZOOM_TO_ROBUST_HPP\n#define BOOST_GEOMETRY_ALGORITHMS_DETAIL_ZOOM_TO_ROBUST_HPP\n\n\n#include <cstddef>\n\n#include <boost/type_traits.hpp>\n\n#include <boost/geometry/algorithms/envelope.hpp>\n#include <boost/geometry/algorithms/expand.hpp>\n#include <boost/geometry/algorithms/detail/recalculate.hpp>\n\nnamespace boost { namespace geometry\n{\n\n#ifndef DOXYGEN_NO_DETAIL\nnamespace detail { namespace zoom_to_robust\n{\n\ntemplate <typename Box, std::size_t Dimension>\nstruct get_max_size\n{\n    static inline typename coordinate_type<Box>::type apply(Box const& box)\n    {\n        typename coordinate_type<Box>::type s\n            = geometry::math::abs(geometry::get<1, Dimension>(box) - geometry::get<0, Dimension>(box));\n\n        return (std::max)(s, get_max_size<Box, Dimension - 1>::apply(box));\n    }\n};\n\ntemplate <typename Box>\nstruct get_max_size<Box, 0>\n{\n    static inline typename coordinate_type<Box>::type apply(Box const& box)\n    {\n        return geometry::math::abs(geometry::get<1, 0>(box) - geometry::get<0, 0>(box));\n    }\n};\n\ntemplate <typename FpPoint, typename IntPoint, typename CalculationType>\nstruct rescale_strategy\n{\n    typedef typename geometry::coordinate_type<IntPoint>::type output_ct;\n\n    rescale_strategy(FpPoint const& fp_min, IntPoint const& int_min, CalculationType const& the_factor)\n        : m_fp_min(fp_min)\n        , m_int_min(int_min)\n        , m_multiplier(the_factor)\n    {\n    }\n\n    template <std::size_t Dimension, typename Value>\n    inline output_ct apply(Value const& value) const\n    {\n        // a + (v-b)*f\n        CalculationType const a = static_cast<CalculationType>(get<Dimension>(m_int_min));\n        CalculationType const b = static_cast<CalculationType>(get<Dimension>(m_fp_min));\n        CalculationType const result = a + (value - b) * m_multiplier;\n        return static_cast<output_ct>(result);\n    }\n\n    FpPoint const& m_fp_min;\n    IntPoint const& m_int_min;\n    CalculationType m_multiplier;\n};\n\n}} // namespace detail::zoom_to_robust\n#endif // DOXYGEN_NO_DETAIL\n\ntemplate <typename Box>\ninline typename coordinate_type<Box>::type get_max_size(Box const& box)\n{\n    return detail::zoom_to_robust::get_max_size<Box, dimension<Box>::value - 1>::apply(box);\n}\n\n#ifndef DOXYGEN_NO_DISPATCH\nnamespace dispatch\n{\n\ntemplate <typename CoordinateType, typename IsFloatingPoint>\nstruct robust_type\n{\n};\n\ntemplate <typename CoordinateType>\nstruct robust_type<CoordinateType, boost::false_type>\n{\n    typedef CoordinateType type;\n};\n\ntemplate <typename CoordinateType>\nstruct robust_type<CoordinateType, boost::true_type>\n{\n    typedef int type; // long long?\n};\n\n\ntemplate <typename IsFloatingPoint>\nstruct zoom_to_robust\n{\n    template \n    <\n        typename Geometry1, typename Geometry2, typename Geometry3, \n        typename Geometry4, typename Geometry5, typename Geometry6, \n        typename GeometryOut\n    >\n    static inline void apply(Geometry1 const& g1, Geometry2 const& g2, Geometry3 const& g3,\n          Geometry4 const& g4, Geometry5 const& g5, Geometry6 const& g6,\n          GeometryOut& og1, GeometryOut& og2, GeometryOut& og3,\n          GeometryOut& og4, GeometryOut& og5, GeometryOut& og6)\n    {\n        // By default, just convert these geometries (until now: points or maybe segments)\n        geometry::convert(g1, og1);\n        geometry::convert(g2, og2);\n        geometry::convert(g3, og3);\n        geometry::convert(g4, og4);\n        geometry::convert(g5, og5);\n        geometry::convert(g6, og6);\n    }\n};\n\ntemplate <>\nstruct zoom_to_robust<boost::true_type>\n{\n    template \n    <\n        typename Geometry1, typename Geometry2, typename Geometry3, \n        typename Geometry4, typename Geometry5, typename Geometry6, \n        typename GeometryOut\n    >\n    static inline void apply(Geometry1 const& g1, Geometry2 const& g2, Geometry3 const& g3,\n          Geometry4 const& g4, Geometry5 const& g5, Geometry6 const& g6,\n          GeometryOut& og1, GeometryOut& og2, GeometryOut& og3,\n          GeometryOut& og4, GeometryOut& og5, GeometryOut& og6)\n    {\n        typedef typename point_type<Geometry1>::type point1_type;\n\n        // Get the envelop of inputs\n        model::box<point1_type> env;\n        geometry::assign_inverse(env);\n        geometry::expand(env, g1);\n        geometry::expand(env, g2);\n        geometry::expand(env, g3);\n        geometry::expand(env, g4);\n        geometry::expand(env, g5);\n        geometry::expand(env, g6);\n\n        // Scale this to integer-range\n        typename geometry::coordinate_type<point1_type>::type diff = get_max_size(env);\n        double range = 1000000000.0; // Define a large range to get precise integer coordinates\n        double factor = double(int(range / double(diff)));\n\n        // Assign input/output minimal points\n        point1_type min_point1;\n        detail::assign_point_from_index<0>(env, min_point1);\n\n        typedef typename point_type<GeometryOut>::type point2_type;\n        point2_type min_point2;\n        assign_values(min_point2, int(-range/2.0), int(-range/2.0));\n\n        detail::zoom_to_robust::rescale_strategy<point1_type, point2_type, double> strategy(min_point1, min_point2, factor);\n\n        geometry::recalculate(og1, g1, strategy);\n        geometry::recalculate(og2, g2, strategy);\n        geometry::recalculate(og3, g3, strategy);\n        geometry::recalculate(og4, g4, strategy);\n        geometry::recalculate(og5, g5, strategy);\n        geometry::recalculate(og6, g6, strategy);\n    }\n};\n\n\n} // namespace dispatch\n#endif // DOXYGEN_NO_DISPATCH\n\ntemplate <typename CoordinateType>\nstruct robust_type\n{\n    typedef typename dispatch::robust_type\n        <\n            CoordinateType,\n            typename boost::is_floating_point<CoordinateType>::type\n        >::type type;\n};\n\n\ntemplate <typename Geometry1, typename Geometry2>\ninline void zoom_to_robust(Geometry1 const& g1a, Geometry1 const& g1b, Geometry2& g2a, Geometry2& g2b)\n{\n    typedef typename point_type<Geometry1>::type point1_type;\n    typedef typename point_type<Geometry2>::type point2_type;\n\n    point1_type min_point1;\n    point2_type min_point2;\n            \n    // Get the envelop of inputs\n    model::box<point1_type> env;\n    envelope(g1a, env);\n    expand(env, g1b);\n\n    // Scale this to integer-range\n    typename coordinate_type<point1_type>::type diff = get_max_size(env);\n    double range = 1000000000.0; // Define a large range to get precise integer coordinates\n    double factor = range / diff;\n\n    // Assign input/output minimal points\n    detail::assign_point_from_index<0>(env, min_point1);\n    assign_values(min_point2, int(-range/2.0), int(-range/2.0));\n\n    detail::zoom_to_robust::rescale_strategy<point1_type, point2_type, double> strategy(min_point1, min_point2, factor);\n    recalculate(g2a, g1a, strategy);\n    recalculate(g2b, g1b, strategy);\n}\n\ntemplate \n<\n    typename Geometry1, typename Geometry2, typename Geometry3, \n    typename Geometry4, typename Geometry5, typename Geometry6, \n    typename GeometryOut\n>\nvoid zoom_to_robust(Geometry1 const& g1, Geometry2 const& g2, Geometry3 const& g3,\n          Geometry4 const& g4, Geometry5 const& g5, Geometry6 const& g6,\n          GeometryOut& og1, GeometryOut& og2, GeometryOut& og3,\n          GeometryOut& og4, GeometryOut& og5, GeometryOut& og6)\n{\n    // Make FP robust (so dispatch to true), so float and double\n    // Other types as int, boost::rational, or ttmath are considered to be already robust \n    dispatch::zoom_to_robust\n        <\n            typename boost::is_floating_point\n                <\n                    typename geometry::coordinate_type<Geometry1>::type\n                >::type\n        >::apply(g1, g2, g3, g4, g5, g6, og1, og2, og3, og4, og5, og6);\n}\n\n}} // namespace boost::geometry\n\n\n#endif // BOOST_GEOMETRY_ALGORITHMS_DETAIL_ZOOM_TO_ROBUST_HPP\n", "meta": {"hexsha": "85a1b0105183737fc8c40a4166ef088d6f43d2d2", "size": 8279, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/geometry/algorithms/detail/zoom_to_robust.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/detail/zoom_to_robust.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/detail/zoom_to_robust.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": 32.7233201581, "max_line_length": 124, "alphanum_fraction": 0.6936828119, "num_tokens": 2111, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7090191460821871, "lm_q2_score": 0.46101677931231594, "lm_q1q2_score": 0.32686972319757834}}
{"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// Purpose:  Implementation of the nzmg (New Zealand Map Grid) projection.\n//           Very loosely based upon DMA code by Bradford W. Drew\n// Author:   Gerald Evenden\n// Copyright (c) 1995, Gerald Evenden\n\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the \"Software\"),\n// to deal in the Software without restriction, including without limitation\n// the rights to use, copy, modify, merge, publish, distribute, sublicense,\n// and/or sell copies of the Software, and to permit persons to whom the\n// Software is furnished to do so, subject to the following conditions:\n\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n// DEALINGS IN THE SOFTWARE.\n\n#ifndef BOOST_GEOMETRY_PROJECTIONS_NZMG_HPP\n#define BOOST_GEOMETRY_PROJECTIONS_NZMG_HPP\n\n#include <boost/geometry/util/math.hpp>\n\n#include <boost/geometry/srs/projections/impl/base_static.hpp>\n#include <boost/geometry/srs/projections/impl/base_dynamic.hpp>\n#include <boost/geometry/srs/projections/impl/projects.hpp>\n#include <boost/geometry/srs/projections/impl/factory_entry.hpp>\n#include <boost/geometry/srs/projections/impl/pj_zpoly1.hpp>\n\nnamespace boost { namespace geometry\n{\n\nnamespace srs { namespace par4\n{\n    struct nzmg {}; // New Zealand Map Grid\n\n}} //namespace srs::par4\n\nnamespace projections\n{\n    #ifndef DOXYGEN_NO_DETAIL\n    namespace detail { namespace nzmg\n    {\n\n            static const double epsilon = 1e-10;\n            static const int Nbf = 5;\n            static const int Ntpsi = 9;\n            static const int Ntphi = 8;\n\n            template <typename T>\n            inline T sec5_to_rad() { return 0.4848136811095359935899141023; }\n            template <typename T>\n            inline T rad_to_sec5() { return 2.062648062470963551564733573; }\n\n            template <typename T>\n            inline const pj_complex<T> * bf()\n            {\n                static const pj_complex<T> result[] = {\n                    {.7557853228,    0.0},\n                    {.249204646,    .003371507},\n                    {-.001541739,    .041058560},\n                    {-.10162907,    .01727609},\n                    {-.26623489,    -.36249218},\n                    {-.6870983,    -1.1651967}\n                };\n                return result;\n            }\n\n            template <typename T>\n            inline const T * tphi()\n            {\n                static const T result[] = { 1.5627014243, .5185406398, -.03333098,\n                                            -.1052906,   -.0368594,     .007317,\n                                             .01220,      .00394,      -.0013 };\n                return result;\n            }\n            template <typename T>\n            inline const T * tpsi()\n            {\n                static const T result[] = { .6399175073, -.1358797613, .063294409, -.02526853, .0117879,\n                                           -.0055161,     .0026906,   -.001333,     .00067,   -.00034 };\n                return result;\n            }\n\n            // template class, using CRTP to implement forward/inverse\n            template <typename T, typename Parameters>\n            struct base_nzmg_ellipsoid\n                : public base_t_fi<base_nzmg_ellipsoid<T, Parameters>, T, Parameters>\n            {\n                inline base_nzmg_ellipsoid(const Parameters& par)\n                    : base_t_fi<base_nzmg_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& lp_lon, T& lp_lat, T& xy_x, T& xy_y) const\n                {\n                    static const T rad_to_sec5 = nzmg::rad_to_sec5<T>();\n\n                    pj_complex<T> p;\n                    const T * C;\n                    int i;\n\n                    lp_lat = (lp_lat - this->m_par.phi0) * rad_to_sec5;\n                    for (p.r = *(C = tpsi<T>() + (i = Ntpsi)); i ; --i)\n                        p.r = *--C + lp_lat * p.r;\n                    p.r *= lp_lat;\n                    p.i = lp_lon;\n                    p = pj_zpoly1(p, bf<T>(), Nbf);\n                    xy_x = p.i;\n                    xy_y = p.r;\n                }\n\n                // INVERSE(e_inverse)  ellipsoid\n                // Project coordinates from cartesian (x, y) to geographic (lon, lat)\n                inline void inv(T& xy_x, T& xy_y, T& lp_lon, T& lp_lat) const\n                {\n                    static const T sec5_to_rad = nzmg::sec5_to_rad<T>();\n\n                    int nn, i;\n                    pj_complex<T> p, f, fp, dp;\n                    T den;\n                    const T* C;\n\n                    p.r = xy_y;\n                    p.i = xy_x;\n                    for (nn = 20; nn ;--nn) {\n                        f = pj_zpolyd1(p, bf<T>(), Nbf, &fp);\n                        f.r -= xy_y;\n                        f.i -= xy_x;\n                        den = fp.r * fp.r + fp.i * fp.i;\n                        p.r += dp.r = -(f.r * fp.r + f.i * fp.i) / den;\n                        p.i += dp.i = -(f.i * fp.r - f.r * fp.i) / den;\n                        if ((fabs(dp.r) + fabs(dp.i)) <= epsilon)\n                            break;\n                    }\n                    if (nn) {\n                        lp_lon = p.i;\n                        for (lp_lat = *(C = tphi<T>() + (i = Ntphi)); i ; --i)\n                            lp_lat = *--C + p.r * lp_lat;\n                        lp_lat = this->m_par.phi0 + p.r * lp_lat * sec5_to_rad;\n                    } else\n                        lp_lon = lp_lat = HUGE_VAL;\n                }\n\n                static inline std::string get_name()\n                {\n                    return \"nzmg_ellipsoid\";\n                }\n\n            };\n\n            // New Zealand Map Grid\n            template <typename Parameters>\n            inline void setup_nzmg(Parameters& par)\n            {\n                typedef typename Parameters::type calc_t;\n                static const calc_t d2r = geometry::math::d2r<calc_t>();\n\n                /* force to International major axis */\n                par.ra = 1. / (par.a = 6378388.0);\n                par.lam0 = 173. * d2r;\n                par.phi0 = -41. * d2r;\n                par.x0 = 2510000.;\n                par.y0 = 6023150.;\n            }\n\n    }} // namespace detail::nzmg\n    #endif // doxygen\n\n    /*!\n        \\brief New Zealand Map Grid 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         - Fixed Earth\n        \\par Example\n        \\image html ex_nzmg.gif\n    */\n    template <typename T, typename Parameters>\n    struct nzmg_ellipsoid : public detail::nzmg::base_nzmg_ellipsoid<T, Parameters>\n    {\n        inline nzmg_ellipsoid(const Parameters& par) : detail::nzmg::base_nzmg_ellipsoid<T, Parameters>(par)\n        {\n            detail::nzmg::setup_nzmg(this->m_par);\n        }\n    };\n\n    #ifndef DOXYGEN_NO_DETAIL\n    namespace detail\n    {\n\n        // Static projection\n        BOOST_GEOMETRY_PROJECTIONS_DETAIL_STATIC_PROJECTION(srs::par4::nzmg, nzmg_ellipsoid, nzmg_ellipsoid)\n\n        // Factory entry(s)\n        template <typename T, typename Parameters>\n        class nzmg_entry : public detail::factory_entry<T, Parameters>\n        {\n            public :\n                virtual base_v<T, Parameters>* create_new(const Parameters& par) const\n                {\n                    return new base_v_fi<nzmg_ellipsoid<T, Parameters>, T, Parameters>(par);\n                }\n        };\n\n        template <typename T, typename Parameters>\n        inline void nzmg_init(detail::base_factory<T, Parameters>& factory)\n        {\n            factory.add_to_factory(\"nzmg\", new nzmg_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_NZMG_HPP\n\n", "meta": {"hexsha": "2806e1a2d21a6c7d2ac873c2735f2938b482259c", "size": 9431, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/geometry/srs/projections/proj/nzmg.hpp", "max_stars_repo_name": "jonasdmentia/geometry", "max_stars_repo_head_hexsha": "097f6fdbe98118be82cd1917cc72c3c6a37bdf30", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2018-08-16T03:03:05.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-01T23:27:34.000Z", "max_issues_repo_path": "include/boost/geometry/srs/projections/proj/nzmg.hpp", "max_issues_repo_name": "jonasdmentia/geometry", "max_issues_repo_head_hexsha": "097f6fdbe98118be82cd1917cc72c3c6a37bdf30", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2022-02-02T11:45:07.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-09T19:19:24.000Z", "max_forks_repo_path": "include/boost/geometry/srs/projections/proj/nzmg.hpp", "max_forks_repo_name": "jonasdmentia/geometry", "max_forks_repo_head_hexsha": "097f6fdbe98118be82cd1917cc72c3c6a37bdf30", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2018-10-23T05:16:49.000Z", "max_forks_repo_forks_event_max_datetime": "2019-10-14T04:44:34.000Z", "avg_line_length": 37.724, "max_line_length": 108, "alphanum_fraction": 0.5443749337, "num_tokens": 2224, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7662936430859597, "lm_q2_score": 0.42632159254749036, "lm_q1q2_score": 0.3266875262794245}}
{"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 models/crossassetmodel.hpp\n    \\brief cross asset model\n    \\ingroup crossassetmodel\n*/\n\n#ifndef quantext_crossasset_model_hpp\n#define quantext_crossasset_model_hpp\n\n#include <qle/models/crlgm1fparametrization.hpp>\n#include <qle/models/eqbsparametrization.hpp>\n#include <qle/models/fxbsparametrization.hpp>\n#include <qle/models/infdkparametrization.hpp>\n#include <qle/models/lgm.hpp>\n\n#include <qle/processes/crossassetstateprocess.hpp>\n\n#include <ql/math/distributions/normaldistribution.hpp>\n#include <ql/math/integrals/integral.hpp>\n#include <ql/math/matrix.hpp>\n#include <ql/models/model.hpp>\n\n#include <boost/bind.hpp>\n\nnamespace QuantExt {\nusing namespace QuantLib;\n\nnamespace CrossAssetModelTypes {\n//! Cross Asset Type\n//! \\ingroup crossassetmodel\nenum AssetType { IR, FX, INF, CR, EQ };\n} // namespace CrossAssetModelTypes\n\nusing namespace CrossAssetModelTypes;\n\n//! Cross Asset Model\n/*! \\ingroup crossassetmodel\n */\nclass CrossAssetModel : public LinkableCalibratedModel {\npublic:\n    /*! Parametrizations must be given in the following order\n        - IR  (first parametrization defines the domestic currency)\n        - FX  (for all pairs domestic-ccy defined by the IR models)\n        - INF (optionally, ccy must be a subset of the IR ccys)\n        - CR  (optionally, ccy must be a subset of the IR ccys)\n        - EQ  (for all names equity currency defined in Parametrization)\n        If the correlation matrix is not given, it is initialized\n        as the unit matrix (and can be customized after\n        construction of the model).\n    */\n    CrossAssetModel(const std::vector<boost::shared_ptr<Parametrization> >& parametrizations,\n                    const Matrix& correlation = Matrix(),\n                    SalvagingAlgorithm::Type salvaging = SalvagingAlgorithm::None);\n\n    /*! IR-FX model based constructor */\n    CrossAssetModel(const std::vector<boost::shared_ptr<LinearGaussMarkovModel> >& currencyModels,\n                    const std::vector<boost::shared_ptr<FxBsParametrization> >& fxParametrizations,\n                    const Matrix& correlation = Matrix(),\n                    SalvagingAlgorithm::Type salvaging = SalvagingAlgorithm::None);\n\n    /*! returns the state process with a given discretization */\n    const boost::shared_ptr<StochasticProcess>\n    stateProcess(CrossAssetStateProcess::discretization disc = CrossAssetStateProcess::exact) const;\n\n    /*! total dimension of model (sum of number of state variables) */\n    Size dimension() const;\n\n    /*! total number of Brownian motions (this is less or equal to dimension) */\n    Size brownians() const;\n\n    /*! total number of parameters that can be calibrated */\n    Size totalNumberOfParameters() const;\n\n    /*! number of components for an asset class */\n    Size components(const AssetType t) const;\n\n    /*! number of brownian motions for a component */\n    Size brownians(const AssetType t, const Size i) const;\n\n    /*! number of state variables for a component */\n    Size stateVariables(const AssetType t, const Size i) const;\n\n    /*! return index for currency (0 = domestic, 1 = first\n      foreign currency and so on) */\n    Size ccyIndex(const Currency& ccy) const;\n\n    /*! return index for equity (0 = first equity) */\n    Size eqIndex(const std::string& eqName) const;\n\n    /*! return index for inflation (0 = first inflation index) */\n    Size infIndex(const std::string& index) const;\n\n    /*! observer and linked calibrated model interface */\n    void update();\n    void generateArguments();\n\n    /*! LGM1F components, ccy=0 refers to the domestic currency */\n    const boost::shared_ptr<LinearGaussMarkovModel> lgm(const Size ccy) const;\n\n    const boost::shared_ptr<IrLgm1fParametrization> irlgm1f(const Size ccy) const;\n\n    Real numeraire(const Size ccy, const Time t, const Real x,\n                   Handle<YieldTermStructure> discountCurve = Handle<YieldTermStructure>()) const;\n\n    Real discountBond(const Size ccy, const Time t, const Time T, const Real x,\n                      Handle<YieldTermStructure> discountCurve = Handle<YieldTermStructure>()) const;\n\n    Real reducedDiscountBond(const Size ccy, const Time t, const Time T, const Real x,\n                             Handle<YieldTermStructure> discountCurve = Handle<YieldTermStructure>()) const;\n\n    Real discountBondOption(const Size ccy, Option::Type type, const Real K, const Time t, const Time S, const Time T,\n                            Handle<YieldTermStructure> discountCurve = Handle<YieldTermStructure>()) const;\n\n    /*! FXBS components, ccy=0 referes to the first foreign currency,\n        so it corresponds to ccy+1 if you want to get the corresponding\n        irmgl1f component */\n    const boost::shared_ptr<FxBsParametrization> fxbs(const Size ccy) const;\n\n    /*! INF DK components */\n    const boost::shared_ptr<InfDkParametrization> infdk(const Size i) const;\n\n    /*! CR LGM 1F components */\n    const boost::shared_ptr<CrLgm1fParametrization> crlgm1f(const Size i) const;\n\n    /*! EQBS components */\n    const boost::shared_ptr<EqBsParametrization> eqbs(const Size ccy) const;\n\n    /* ... add more components here ...*/\n\n    /*! correlation linking the different marginal models, note that\n        the use of asset class pairs specific inspectors is\n        recommended instead of the global matrix directly */\n    const Matrix& correlation() const;\n\n    /*! check if correlation matrix is valid */\n    void checkCorrelationMatrix() const;\n\n    /*! index of component in the parametrization vector */\n    Size idx(const AssetType t, const Size i) const;\n\n    /*! index of component in the correlation matrix, by offset */\n    Size cIdx(const AssetType t, const Size i, const Size offset = 0) const;\n\n    /*! index of component in the stochastic process array, by offset */\n    Size pIdx(const AssetType t, const Size i, const Size offset = 0) const;\n\n    /*! correlation between two components */\n    const Real& correlation(const AssetType s, const Size i, const AssetType t, const Size j, const Size iOffset = 0,\n                            const Size jOffset = 0) const;\n    /*! set correlation */\n    void correlation(const AssetType s, const Size i, const AssetType t, const Size j, const Real value,\n                     const Size iOffset = 0, const Size jOffset = 0);\n\n    /*! analytical moments require numerical integration,\n      which can be customized here */\n    void setIntegrationPolicy(const boost::shared_ptr<Integrator> integrator,\n                              const bool usePiecewiseIntegration = true) const;\n    const boost::shared_ptr<Integrator> integrator() const;\n\n    /*! return (V(t), V^tilde(t,T)) in the notation of the book */\n    std::pair<Real, Real> infdkV(const Size i, const Time t, const Time T);\n\n    /*! return (I(t), I^tilde(t,T)) in the notation of the book, note that\n        I(0) is normalized to 1 here, i.e. you have to multiply the result\n        with the index value (as of the base date of the inflation ts) */\n    std::pair<Real, Real> infdkI(const Size i, const Time t, const Time T, const Real z, const Real y);\n\n    /*! return YoYIIS(t) in the notation of the book, the year on year\n        swaplet price from S to T, at time t */\n    Real infdkYY(const Size i, const Time t, const Time S, const Time T, const Real z, const Real y, const Real irz);\n\n    /*! returns (S(t), S^tilde(t,T)) in the notation of the book */\n    std::pair<Real, Real> crlgm1fS(const Size i, const Size ccy, const Time t, const Time T, const Real z,\n                                   const Real y) const;\n\n    /*! calibration procedures */\n\n    /*! calibrate irlgm1f volatilities to a sequence of ir options with\n        expiry times equal to step times in the parametrization */\n    void calibrateIrLgm1fVolatilitiesIterative(const Size ccy,\n                                               const std::vector<boost::shared_ptr<BlackCalibrationHelper> >& helpers,\n                                               OptimizationMethod& method, const EndCriteria& endCriteria,\n                                               const Constraint& constraint = Constraint(),\n                                               const std::vector<Real>& weights = std::vector<Real>());\n\n    /*! calibrate irlgm1f reversion to a sequence of ir options with\n        maturities equal to step times in the parametrization */\n    void calibrateIrLgm1fReversionsIterative(const Size ccy,\n                                             const std::vector<boost::shared_ptr<BlackCalibrationHelper> >& helpers,\n                                             OptimizationMethod& method, const EndCriteria& endCriteria,\n                                             const Constraint& constraint = Constraint(),\n                                             const std::vector<Real>& weights = std::vector<Real>());\n\n    /*! calibrate irlgm1f parameters for one ccy globally to a set\n        of ir options */\n    void calibrateIrLgm1fGlobal(const Size ccy, const std::vector<boost::shared_ptr<BlackCalibrationHelper> >& helpers,\n                                OptimizationMethod& method, const EndCriteria& endCriteria,\n                                const Constraint& constraint = Constraint(),\n                                const std::vector<Real>& weights = std::vector<Real>());\n\n    /*! calibrate eq or fx volatilities to a sequence of options with\n            expiry times equal to step times in the parametrization */\n    void calibrateBsVolatilitiesIterative(const AssetType& assetType, const Size aIdx,\n                                          const std::vector<boost::shared_ptr<BlackCalibrationHelper> >& helpers,\n                                          OptimizationMethod& method, const EndCriteria& endCriteria,\n                                          const Constraint& constraint = Constraint(),\n                                          const std::vector<Real>& weights = std::vector<Real>());\n\n    /*! calibrate eq/fx volatilities globally to a set of fx options */\n    void calibrateBsVolatilitiesGlobal(const AssetType& assetType, const Size aIdx,\n                                       const std::vector<boost::shared_ptr<BlackCalibrationHelper> >& helpers,\n                                       OptimizationMethod& method, const EndCriteria& endCriteria,\n                                       const Constraint& constraint = Constraint(),\n                                       const std::vector<Real>& weights = std::vector<Real>());\n\n    /*! calibrate infdk volatilities to a sequence of cpi options with\n        expiry times equal to step times in the parametrization */\n    void calibrateInfDkVolatilitiesIterative(const Size index,\n                                             const std::vector<boost::shared_ptr<BlackCalibrationHelper> >& helpers,\n                                             OptimizationMethod& method, const EndCriteria& endCriteria,\n                                             const Constraint& constraint = Constraint(),\n                                             const std::vector<Real>& weights = std::vector<Real>());\n\n    /*! calibrate infdk reversions to a sequence of cpi options with\n        maturity times equal to step times in the parametrization */\n    void calibrateInfDkReversionsIterative(const Size index,\n                                           const std::vector<boost::shared_ptr<BlackCalibrationHelper> >& helpers,\n                                           OptimizationMethod& method, const EndCriteria& endCriteria,\n                                           const Constraint& constraint = Constraint(),\n                                           const std::vector<Real>& weights = std::vector<Real>());\n\n    /*! calibrate infdk volatilities globally to a sequence of cpi cap/floors */\n    void calibrateInfDkVolatilitiesGlobal(const Size index,\n                                          const std::vector<boost::shared_ptr<BlackCalibrationHelper> >& helpers,\n                                          OptimizationMethod& method, const EndCriteria& endCriteria,\n                                          const Constraint& constraint = Constraint(),\n                                          const std::vector<Real>& weights = std::vector<Real>());\n\n    /*! calibrate infdk reversions globally to a sequence of cpi cap/floors */\n    void calibrateInfDkReversionsGlobal(const Size index,\n                                        const std::vector<boost::shared_ptr<BlackCalibrationHelper> >& helpers,\n                                        OptimizationMethod& method, const EndCriteria& endCriteria,\n                                        const Constraint& constraint = Constraint(),\n                                        const std::vector<Real>& weights = std::vector<Real>());\n\n    /*! calibrate crlgm1f volatilities to a sequence of cds options with\n        expiry times equal to step times in the parametrization */\n    void calibrateCrLgm1fVolatilitiesIterative(const Size index,\n                                               const std::vector<boost::shared_ptr<BlackCalibrationHelper> >& helpers,\n                                               OptimizationMethod& method, const EndCriteria& endCriteria,\n                                               const Constraint& constraint = Constraint(),\n                                               const std::vector<Real>& weights = std::vector<Real>());\n\n    /*! calibrate crlgm1f reversions to a sequence of cds options with\n        maturity times equal to step times in the parametrization */\n    void calibrateCrLgm1fReversionsIterative(const Size index,\n                                             const std::vector<boost::shared_ptr<BlackCalibrationHelper> >& helpers,\n                                             OptimizationMethod& method, const EndCriteria& endCriteria,\n                                             const Constraint& constraint = Constraint(),\n                                             const std::vector<Real>& weights = std::vector<Real>());\n\n    /* ... add more calibration procedures here ... */\n\nprotected:\n    /* ctor to be used in extensions, initialize is not called */\n    CrossAssetModel(const std::vector<boost::shared_ptr<Parametrization> >& parametrizations, const Matrix& correlation,\n                    SalvagingAlgorithm::Type salvaging, const bool)\n        : LinkableCalibratedModel(), p_(parametrizations), rho_(correlation), salvaging_(salvaging) {}\n\n    /*! number of arguments for a component */\n    Size arguments(const AssetType t, const Size i) const;\n\n    /*! index of component in the arguments vector, by offset */\n    Size aIdx(const AssetType t, const Size i, const Size offset = 0) const;\n\n    /* init methods */\n    virtual void initialize();\n    virtual void initializeParametrizations();\n    virtual void initializeCorrelation();\n    virtual void initializeArguments();\n    virtual void finalizeArguments();\n    virtual void checkModelConsistency() const;\n    virtual void initDefaultIntegrator();\n    virtual void initStateProcess();\n\n    /* helper function for infdkI, crlgm1fS */\n    Real infV(const Size idx, const Size ccy, const Time t, const Time T) const;\n    Real crV(const Size idx, const Size ccy, const Time t, const Time T) const;\n\n    // cache for infdkI, crlgm1fS method\n    struct cache_key {\n        Size i, ccy;\n        double t, T;\n        bool operator==(const cache_key& o) const { return (i == o.i) && (ccy == o.ccy) && (t == o.t) && (T == o.T); }\n    };\n\n    struct cache_hasher : std::unary_function<cache_key, std::size_t> {\n        std::size_t operator()(cache_key const& x) const {\n            std::size_t seed = 0;\n            boost::hash_combine(seed, x.i);\n            boost::hash_combine(seed, x.ccy);\n            boost::hash_combine(seed, x.t);\n            boost::hash_combine(seed, x.T);\n            return seed;\n        }\n    };\n\n    mutable boost::unordered_map<cache_key, std::pair<Real, Real>, cache_hasher> cache_crlgm1fS_, cache_infdkI_;\n\n    /* members */\n\n    Size nIrLgm1f_, nFxBs_, nInfDk_, nCrLgm1f_, nEqBs_;\n    Size totalNumberOfParameters_;\n    std::vector<boost::shared_ptr<Parametrization> > p_;\n    std::vector<boost::shared_ptr<LinearGaussMarkovModel> > lgm_;\n    Matrix rho_;\n    SalvagingAlgorithm::Type salvaging_;\n    mutable boost::shared_ptr<Integrator> integrator_;\n    boost::shared_ptr<CrossAssetStateProcess> stateProcessExact_, stateProcessEuler_;\n\n    /* calibration constraints */\n\n    // move parameter param (e.g. vol, reversion) of asset type component t / index\n    // at step i (or at all steps if i is null)\n    Disposable<std::vector<bool> > MoveParameter(const AssetType t, const Size param, const Size index, const Size i) {\n        switch (t) {\n        case IR:\n            QL_REQUIRE(param <= 1, \"irlgm1f parameter \" << param << \" out of bounds 0...1\");\n            QL_REQUIRE(i < irlgm1f(index)->parameter(param)->size(),\n                       \"irlgm1f parameter (\" << param << \") index (\" << i << \") for ccy \" << index\n                                             << \" out of bounds 0...\" << irlgm1f(index)->parameter(param)->size() - 1);\n            break;\n        case FX:\n            QL_REQUIRE(param == 0, \"fxbs parameter \" << param << \" out of bounds 0...0\");\n            QL_REQUIRE(i < fxbs(index)->parameter(param)->size(),\n                       \"fxbs volatility index (\" << i << \") for ccy \" << index << \" out of bounds 0...\"\n                                                 << fxbs(index)->parameter(param)->size() - 1);\n            break;\n        case INF:\n            QL_REQUIRE(param <= 1, \"infdk parameter \" << param << \" out of bounds 0...1\");\n            QL_REQUIRE(i < infdk(index)->parameter(param)->size(),\n                       \"infdk parameter (\" << param << \") index (\" << i << \") for inflation component \" << index\n                                           << \" out of bounds 0...\" << infdk(index)->parameter(param)->size() - 1);\n            break;\n        case CR:\n            QL_REQUIRE(param <= 1, \"crlgm1f parameter \" << param << \" out of bounds 0...1\");\n            QL_REQUIRE(i < crlgm1f(index)->parameter(param)->size(),\n                       \"crlgm1f parameter (\" << param << \") index (\" << i << \") for credit component \" << index\n                                             << \" out of bounds 0...\" << crlgm1f(index)->parameter(param)->size() - 1);\n            break;\n        case EQ:\n            QL_REQUIRE(param == 0, \"eqbs parameter \" << param << \" out of bounds 0...0\");\n            QL_REQUIRE(i < eqbs(index)->parameter(param)->size(),\n                       \"eqbs volatility index (\" << i << \") for index \" << index << \" out of bounds 0...\"\n                                                 << eqbs(index)->parameter(param)->size() - 1);\n            break;\n        default:\n            QL_FAIL(\"asset type not recognised\");\n        }\n        std::vector<bool> res(0);\n        for (Size j = 0; j < nIrLgm1f_; ++j) {\n            std::vector<bool> tmp1(p_[idx(IR, j)]->parameter(0)->size(), true);\n            std::vector<bool> tmp2(p_[idx(IR, j)]->parameter(1)->size(), true);\n            std::vector<std::vector<bool> > tmp;\n            tmp.push_back(tmp1);\n            tmp.push_back(tmp2);\n            if (t == IR && index == j) {\n                for (Size ii = 0; ii < tmp[param].size(); ++ii) {\n                    if (i == Null<Size>() || i == ii) {\n                        tmp[param][ii] = false;\n                    }\n                }\n            }\n            res.insert(res.end(), tmp[0].begin(), tmp[0].end());\n            res.insert(res.end(), tmp[1].begin(), tmp[1].end());\n        }\n        for (Size j = 0; j < nFxBs_; ++j) {\n            std::vector<bool> tmp(p_[idx(FX, j)]->parameter(0)->size(), true);\n            if (t == FX && index == j) {\n                for (Size ii = 0; ii < tmp.size(); ++ii) {\n                    if (i == Null<Size>() || i == ii) {\n                        tmp[i] = false;\n                    }\n                }\n            }\n            res.insert(res.end(), tmp.begin(), tmp.end());\n        }\n        for (Size j = 0; j < nInfDk_; ++j) {\n            std::vector<bool> tmp1(p_[idx(INF, j)]->parameter(0)->size(), true);\n            std::vector<bool> tmp2(p_[idx(INF, j)]->parameter(1)->size(), true);\n            std::vector<std::vector<bool> > tmp;\n            tmp.push_back(tmp1);\n            tmp.push_back(tmp2);\n            if (t == INF && index == j) {\n                for (Size ii = 0; ii < tmp[param].size(); ++ii) {\n                    if (i == Null<Size>() || i == ii) {\n                        tmp[param][ii] = false;\n                    }\n                }\n            }\n            res.insert(res.end(), tmp[0].begin(), tmp[0].end());\n            res.insert(res.end(), tmp[1].begin(), tmp[1].end());\n        }\n        for (Size j = 0; j < nCrLgm1f_; ++j) {\n            std::vector<bool> tmp1(p_[idx(CR, j)]->parameter(0)->size(), true);\n            std::vector<bool> tmp2(p_[idx(CR, j)]->parameter(1)->size(), true);\n            std::vector<std::vector<bool> > tmp;\n            tmp.push_back(tmp1);\n            tmp.push_back(tmp2);\n            if (t == CR && index == j) {\n                for (Size ii = 0; ii < tmp[param].size(); ++ii) {\n                    if (i == Null<Size>() || i == ii) {\n                        tmp[param][ii] = false;\n                    }\n                }\n            }\n            res.insert(res.end(), tmp[0].begin(), tmp[0].end());\n            res.insert(res.end(), tmp[1].begin(), tmp[1].end());\n        }\n        for (Size j = 0; j < nEqBs_; ++j) {\n            std::vector<bool> tmp(p_[idx(EQ, j)]->parameter(0)->size(), true);\n            if (t == EQ && index == j) {\n                for (Size ii = 0; ii < tmp.size(); ++ii) {\n                    if (i == Null<Size>() || i == ii) {\n                        tmp[i] = false;\n                    }\n                }\n            }\n            res.insert(res.end(), tmp.begin(), tmp.end());\n        }\n        return res;\n    }\n};\n\n// inline\n\ninline const boost::shared_ptr<StochasticProcess>\nCrossAssetModel::stateProcess(CrossAssetStateProcess::discretization disc) const {\n    return disc == CrossAssetStateProcess::exact ? stateProcessExact_ : stateProcessEuler_;\n}\n\ninline Size CrossAssetModel::dimension() const {\n    // this assumes specific models, as soon as other model types are added\n    // this formula has to be generalized as well\n    return nIrLgm1f_ * 1 + nFxBs_ * 1 + nInfDk_ * 2 + nCrLgm1f_ * 2 + nEqBs_ * 1;\n}\n\ninline Size CrossAssetModel::brownians() const {\n    // this assumes specific models, as soon as other model types are added\n    // this formula has to be generalized as well\n    return nIrLgm1f_ * 1 + nFxBs_ * 1 + nInfDk_ * 1 + nCrLgm1f_ * 1 + nEqBs_ * 1;\n}\n\ninline Size CrossAssetModel::totalNumberOfParameters() const { return totalNumberOfParameters_; }\n\ninline const boost::shared_ptr<LinearGaussMarkovModel> CrossAssetModel::lgm(const Size ccy) const {\n    return lgm_[idx(IR, ccy)];\n}\n\ninline const boost::shared_ptr<IrLgm1fParametrization> CrossAssetModel::irlgm1f(const Size ccy) const {\n    return lgm(ccy)->parametrization();\n}\n\ninline const boost::shared_ptr<InfDkParametrization> CrossAssetModel::infdk(const Size i) const {\n    return boost::static_pointer_cast<InfDkParametrization>(p_[idx(INF, i)]);\n}\n\ninline const boost::shared_ptr<CrLgm1fParametrization> CrossAssetModel::crlgm1f(const Size i) const {\n    return boost::static_pointer_cast<CrLgm1fParametrization>(p_[idx(CR, i)]);\n}\n\ninline const boost::shared_ptr<EqBsParametrization> CrossAssetModel::eqbs(const Size name) const {\n    return boost::dynamic_pointer_cast<EqBsParametrization>(p_[idx(EQ, name)]);\n}\n\ninline Real CrossAssetModel::numeraire(const Size ccy, const Time t, const Real x,\n                                       Handle<YieldTermStructure> discountCurve) const {\n    return lgm(ccy)->numeraire(t, x, discountCurve);\n}\n\ninline Real CrossAssetModel::discountBond(const Size ccy, const Time t, const Time T, const Real x,\n                                          Handle<YieldTermStructure> discountCurve) const {\n    return lgm(ccy)->discountBond(t, T, x, discountCurve);\n}\n\ninline Real CrossAssetModel::reducedDiscountBond(const Size ccy, const Time t, const Time T, const Real x,\n                                                 Handle<YieldTermStructure> discountCurve) const {\n    return lgm(ccy)->reducedDiscountBond(t, T, x, discountCurve);\n}\n\ninline Real CrossAssetModel::discountBondOption(const Size ccy, Option::Type type, const Real K, const Time t,\n                                                const Time S, const Time T,\n                                                Handle<YieldTermStructure> discountCurve) const {\n    return lgm(ccy)->discountBondOption(type, K, t, S, T, discountCurve);\n}\n\ninline const boost::shared_ptr<FxBsParametrization> CrossAssetModel::fxbs(const Size ccy) const {\n    return boost::dynamic_pointer_cast<FxBsParametrization>(p_[idx(FX, ccy)]);\n}\n\ninline const Matrix& CrossAssetModel::correlation() const { return rho_; }\n\ninline const boost::shared_ptr<Integrator> CrossAssetModel::integrator() const { return integrator_; }\n\n} // namespace QuantExt\n\n#endif\n", "meta": {"hexsha": "4a8d3c54bb0ec5aaa9c312c589835efb1844b459", "size": 25933, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "QuantExt/qle/models/crossassetmodel.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": "QuantExt/qle/models/crossassetmodel.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": "QuantExt/qle/models/crossassetmodel.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": 49.3961904762, "max_line_length": 120, "alphanum_fraction": 0.598850885, "num_tokens": 5855, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7025300573952052, "lm_q2_score": 0.4649015713733885, "lm_q1q2_score": 0.3266073276200677}}
{"text": "#include \"tile/math/polynomial.h\"\n\n#include <boost/format.hpp>\n\n#include \"base/util/lookup.h\"\n\nnamespace vertexai {\nnamespace tile {\nnamespace math {\n\ntemplate <typename T>\nPolynomial<T>::Polynomial() {}\n\ntemplate <typename T>\nPolynomial<T>::Polynomial(const T& c) : Polynomial<T>(\"\", c) {}\n\ntemplate <typename T>\nPolynomial<T>::Polynomial(const std::string& i, const T& c) {\n  if (c) {\n    map_[i] = c;\n  }\n}\n\ntemplate <typename T>\nT Polynomial<T>::eval(const std::map<std::string, T>& values) const {\n  T res = 0;\n  for (const auto& kvp : map_) {\n    if (kvp.first == \"\") {\n      res += kvp.second;\n    } else if (values.find(kvp.first) != values.end()) {\n      res += kvp.second * safe_at(values, kvp.first);\n    } else {\n      throw std::runtime_error(\n          str(boost::format(\"Failed to find value for %s, when evaluating %s\") % kvp.first % toString()));\n    }\n  }\n  return res;\n}\n\ntemplate <typename T>\nPolynomial<T> Polynomial<T>::partial_eval(const std::map<std::string, T>& values) const {\n  Polynomial<T> r = *this;\n  T off = 0;\n  for (const auto& kvp : values) {\n    off += get(kvp.first) * kvp.second;\n    r.map_.erase(kvp.first);\n  }\n  r += off;\n  return r;\n}\n\ntemplate <typename T>\nT Polynomial<T>::operator[](const std::string& var) const {\n  auto it = map_.find(var);\n  if (it == map_.end()) {\n    return 0;\n  }\n  return it->second;\n}\n\ntemplate <typename T>\nconst std::map<std::string, T>& Polynomial<T>::getMap() const {\n  return map_;\n}\n\ntemplate <typename T>\nstd::map<std::string, T>& Polynomial<T>::mutateMap() {\n  return map_;\n}\n\ntemplate <typename T>\nPolynomial<T>& Polynomial<T>::operator+=(const Polynomial<T>& rhs) {\n  for (const auto& kvp : rhs.map_) {\n    T new_val = (map_[kvp.first] += kvp.second);\n    if (new_val == 0) {\n      map_.erase(kvp.first);\n    }\n  }\n  return *this;\n}\n\ntemplate <typename T>\nbool Polynomial<T>::operator==(const Polynomial<T>& rhs) const {\n  return map_ == rhs.map_;\n}\n\ntemplate <typename T>\nbool Polynomial<T>::operator<(const Polynomial<T>& rhs) const {\n  return map_ < rhs.map_;\n}\n\ntemplate <typename T>\nPolynomial<T>& Polynomial<T>::operator-=(const Polynomial<T>& rhs) {\n  return *this += -1 * rhs;\n}\n\ntemplate <typename T>\nPolynomial<T> Polynomial<T>::operator-() const {\n  return -1 * (*this);\n}\n\ntemplate <typename T>\nPolynomial<T>& Polynomial<T>::operator*=(const T& rhs) {\n  if (rhs == 0) {\n    map_.clear();\n  } else {\n    for (auto& kvp : map_) {\n      kvp.second *= rhs;\n    }\n  }\n  return *this;\n}\n\ntemplate <typename T>\nPolynomial<T>& Polynomial<T>::operator/=(const T& rhs) {\n  return *this *= (1 / rhs);\n}\n\ntemplate <typename T>\nT Polynomial<T>::constant() const {\n  auto it = map_.find(\"\");\n  return (it == map_.end() ? 0 : it->second);\n}\n\ntemplate <typename T>\nvoid Polynomial<T>::setConstant(T value) {\n  if (value == T(0)) {\n    map_.erase(\"\");\n  } else {\n    map_[\"\"] = value;\n  }\n}\n\ntemplate <typename T>\nT Polynomial<T>::tryDivide(const Polynomial<T>& p, bool ignoreConst) const {\n  auto it = p.map_.begin();\n  if (ignoreConst && it != p.map_.end() && it->first == \"\") {\n    it++;\n  }\n  T val = 0;\n  for (const auto& kvp : map_) {\n    if (ignoreConst && kvp.first == \"\") {\n      continue;\n    }\n    if (it == p.map_.end() || it->first != kvp.first) {\n      return 0;  // Indexes don't exactly line up, fail\n    }\n    T div = kvp.second / it->second;\n    if (val != 0 && div != val) {\n      return 0;  // They don't all divide by the same number\n    }\n    val = div;\n    it++;\n  }\n  if (it != p.map_.end()) {\n    return 0;\n  }\n  return val;\n}\n\ntemplate <typename T>\nvoid Polynomial<T>::substitute(const std::string& var, const Polynomial<T>& replacement) {\n  if (map_.count(var) == 0) {\n    // If var isn't in this polynomial, nothing needs to be done\n    return;\n  }\n  T coeff = safe_at(map_, var);\n  map_.erase(var);\n  (*this) += coeff * replacement;\n}\n\ntemplate <typename T>\nvoid Polynomial<T>::substitute(const std::map<std::string, Polynomial<T>>& replacements) {\n  Polynomial result;\n  for (const auto& name_value : map_) {\n    auto replacement = replacements.find(name_value.first);\n    if (replacement == replacements.end()) {\n      result += Polynomial{name_value.first, name_value.second};\n      continue;\n    }\n    result += replacement->second * name_value.second;\n  }\n  map_.swap(result.map_);\n}\n\ntemplate <typename T>\nvoid Polynomial<T>::substitute(const std::string& var, const T& replacement) {\n  substitute(var, Polynomial<T>(replacement));\n}\n\ntemplate <typename T>\nPolynomial<T> Polynomial<T>::sym_eval(const std::map<std::string, Polynomial> values) const {\n  Polynomial<T> out;\n  for (const auto& kvp : map_) {\n    if (kvp.first.empty()) {\n      out += Polynomial<T>(kvp.second);\n    } else {\n      out += safe_at(values, kvp.first) * kvp.second;\n    }\n  }\n  return out;\n}\n\ntemplate <typename T>\nstd::string Polynomial<T>::GetNonzeroIndex() const {\n  // Returns a nonconstant nonzero index, if one exists; otherwise returns empty string\n  for (const auto& kvp : map_) {\n    if (!(kvp.first.empty()) && kvp.second != 0) return kvp.first;\n  }\n\n  // No nonconstant index has a nonzero coefficient\n  return std::string();\n}\n\ntemplate <typename T>\nT Polynomial<T>::get(const std::string& name) const {\n  auto it = map_.find(name);\n  if (it == map_.end()) {\n    return T();\n  }\n  return it->second;\n}\n\nint64_t abs_value(int64_t value) { return std::llabs(value); }\n\nRational abs_value(Rational value) { return abs(value); }\n\ntemplate <typename T>\nstd::string Polynomial<T>::toString() const {\n  std::stringstream ss;\n  if (map_.size() == 0) {\n    return \"0\";\n  }\n  bool first = true;\n  for (const auto& kvp : map_) {\n    if (first) {\n      if (kvp.second < 0) {\n        ss << \"-\";\n      }\n      first = false;\n    } else {\n      if (kvp.second > 0) {\n        ss << \" + \";\n      } else {\n        ss << \" - \";\n      }\n    }\n    auto value = abs_value(kvp.second);\n    if (value != 1 || kvp.first == \"\") {\n      ss << value;\n      if (kvp.first != \"\") {\n        ss << \"*\";\n      }\n    }\n    ss << kvp.first;\n  }\n  return ss.str();\n}\n\ntemplate class Polynomial<Rational>;\ntemplate class Polynomial<int64_t>;\n\nSimpleConstraint::SimpleConstraint(const Polynomial<Rational>& _poly, int64_t _rhs) : poly(_poly), rhs(_rhs) {}\n\nRangeConstraint::RangeConstraint(const Polynomial<Rational>& _poly, int64_t _range) : poly(_poly), range(_range) {}\n\nbool RangeConstraint::IsParallel(const RangeConstraint& c) {\n  if (this->poly.tryDivide(c.poly, true) != 0) return true;\n  return false;\n}\n\nSimpleConstraint RangeConstraint::lowerBound() const { return SimpleConstraint(-poly, 0); }\n\nSimpleConstraint RangeConstraint::upperBound() const { return SimpleConstraint(poly, range - 1); }\n\n}  // namespace math\n}  // namespace tile\n}  // namespace vertexai\n", "meta": {"hexsha": "54fd9d677d8ef225535dd0dc17fe1c753c69ed36", "size": 6733, "ext": "cc", "lang": "C++", "max_stars_repo_path": "tile/math/polynomial.cc", "max_stars_repo_name": "TolyaTalamanov/plaidml", "max_stars_repo_head_hexsha": "275a79cd640def34c1b7bc7053397f5989ef55c2", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-09-11T11:18:50.000Z", "max_stars_repo_stars_event_max_datetime": "2019-09-11T11:18:50.000Z", "max_issues_repo_path": "tile/math/polynomial.cc", "max_issues_repo_name": "HubBucket-Team/plaidml", "max_issues_repo_head_hexsha": "762d5fff6467b43a15623f927502892ce8df91a4", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tile/math/polynomial.cc", "max_forks_repo_name": "HubBucket-Team/plaidml", "max_forks_repo_head_hexsha": "762d5fff6467b43a15623f927502892ce8df91a4", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-09-11T11:18:52.000Z", "max_forks_repo_forks_event_max_datetime": "2019-09-11T11:18:52.000Z", "avg_line_length": 24.1326164875, "max_line_length": 115, "alphanum_fraction": 0.6197831576, "num_tokens": 1844, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6334102775181399, "lm_q2_score": 0.5156199157230157, "lm_q1q2_score": 0.3265989539119953}}
{"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 * This file contains an example of graphlab used for discrete loopy\n * belief propagation in a pairwise markov random field to denoise a\n * synthetic noisy image.\n *\n *  \\author Joseph Gonzalez\n */\n\n// INCLUDES ===================================================================>\n\n// Including Standard Libraries\n#include <cstdlib>\n#include <cassert>\n#include <cstring>\n#include <fstream>\n#include <iostream>\n#include <vector>\n#include <string>\n#include <algorithm>\n#include <limits>\n#include <cmath>\n\n#include <boost/program_options.hpp>\n\n\n#include <graphlab.hpp>\n\n#include \"image.hpp\"\n\n\n// Include the macro for the for each operation\n#include <graphlab/macros_def.hpp>\n\n\n\n// STRUCTS (Edge and Vertex data) =============================================>\n\n/**\n * The data associated with each directed edge in the pairwise markov\n * random field\n */\nstruct edge_data {\n  graphlab::unary_factor message;\n  graphlab::unary_factor old_message;\n}; // End of edge data\n\n\n/**\n * The data associated with each variable in the pairwise markov\n * random field\n */\nstruct vertex_data {\n  graphlab::unary_factor potential;\n  graphlab::unary_factor belief;\n}; // End of vertex data\n\n\n\ntypedef graphlab::graph<vertex_data, edge_data> graph_type;\ntypedef graphlab::types<graph_type> gl_types;\n\ngl_types::glshared<double> sh_bound;\ngl_types::glshared<double> sh_damping;\ngl_types::glshared<double> sh_ipfdamping;\ngl_types::glshared<graphlab::binary_factor> sh_edgepot;\ngl_types::glshared<graphlab::binary_factor> sh_truecounts;\n\n// GraphLab Update Function ===================================================>\n\n/** Construct denoising ising model based on the image */\nvoid construct_graph(image& img,\n                     size_t num_rings,\n                     double sigma,\n                     gl_types::graph& graph);\n\n/** Get the counts of the true image */\nvoid get_image_counts(image &trueimg, \n                      graphlab::binary_factor &truebinarycount, \n                      size_t arity);\n\n/** Tests if two binary factors are equal */\nbool binary_factor_equal(const graphlab::binary_factor &a, \n                         const graphlab::binary_factor &b);\n/** \n * The core belief propagation update function.  This update satisfies\n * the graphlab update_function interface.  \n */\nvoid bp_update(gl_types::iscope& scope, \n               gl_types::icallback& scheduler);\n               \n/**\n * The edge potential sync simply counts the belief across the edges\n */\nvoid edgepot_sync(gl_types::iscope &scope,  graphlab::any& acc);\n\n/**\n * Performs an IPF update using the counts and the true counts\n */\nvoid edgepot_apply(graphlab::any& result,  const graphlab::any& acc);\n\nvoid edgepot_merge(graphlab::any& result,  const graphlab::any& acc);\n\n// Command Line Parsing =======================================================>\n\nstruct options {\n  size_t ncpus;\n  double bound;\n  double damping;\n  size_t num_rings;\n  size_t rows;\n  size_t cols;\n  double sigma;\n  double lambda;\n  size_t splash_size;\n  std::string smoothing;\n  std::string engine;\n  std::string scope;\n  std::string scheduler;\n  std::string orig_fn;\n  std::string noisy_fn;\n  std::string pred_fn;\n  std::string pred_type;\n  std::string visualizer;\n  std::string partmethod;\n  size_t clustersize;\n};\n\nvoid get_image_counts(image &trueimg, \n                      graphlab::binary_factor &truebinarycount, \n                      size_t arity) {\n  truebinarycount.resize(arity,arity);\n  for (size_t i = 0; i < trueimg.rows(); ++i) {\n    for (size_t j = 0; j < trueimg.cols(); ++j) {\n      size_t color = trueimg.pixel(i,j);\n      // check neighbors\n      if (i > 1) {\n        size_t color2 = trueimg.pixel(i-1,j); \n        truebinarycount.logP(color,color2)++;\n      }\n      if (i < trueimg.rows() - 1) {\n        size_t color2 = trueimg.pixel(i+1,j); \n        truebinarycount.logP(color,color2)++;\n      }\n      if (j > 1) {\n        size_t color2 = trueimg.pixel(i,j-1); \n        truebinarycount.logP(color,color2)++;\n      }\n      if (j < trueimg.cols() - 1) {\n        size_t color2 = trueimg.pixel(i,j+1); \n        truebinarycount.logP(color,color2)++;\n      }\n    }\n  }\n}\n\nbool binary_factor_equal(const graphlab::binary_factor &a, \n                         const graphlab::binary_factor &b) {\n  ASSERT_EQ(a.arity1(), b.arity1());\n  ASSERT_EQ(a.arity2(), b.arity2());\n  for (size_t i = 0;i < a.arity1(); ++i) {\n     for (size_t j = 0;j < a.arity2(); ++j) {\n      if ((a.logP(i,j) - b.logP(i,j)) > std::numeric_limits<double>::epsilon()) {\n        return false;\n      }\n    }\n  }\n  return true;\n}\n// MAIN =======================================================================>\nint main(int argc, char** argv) {\n  std::cout << \"This program creates and denoises a synthetic \" << std::endl\n            << \"image using loopy belief propagation inside \" << std::endl\n            << \"the graphlab framework.\" << std::endl;\n\n  // set the global logger\n  global_logger().set_log_level(LOG_WARNING);\n  global_logger().set_log_to_console(true);\n\n\n  double bound = 1E-4;\n  double damping = 0.1;\n  double ipfdamping = 0.1;\n  size_t colors = 4;\n  size_t rows = 100;\n  size_t cols = 100;\n  double sigma = 2;\n  double lambda = 2;\n  std::string smoothing = \"laplace\";\n  std::string orig_fn = \"source_img.pgm\";\n  std::string noisy_fn = \"noisy_img.pgm\";\n  std::string pred_fn = \"pred_img.pgm\";\n  std::string pred_type = \"map\";\n\n\n\n\n  // Parse command line arguments --------------------------------------------->\n  graphlab::command_line_options clopts(\"Loopy BP image denoising\");\n  clopts.attach_option(\"bound\",\n                       &bound, bound,\n                       \"Residual termination bound\");\n  clopts.attach_option(\"damping\",\n                       &damping, damping,\n                       \"The amount of message damping (higher = more damping)\");\n  clopts.attach_option(\"ipfdamping\",\n                       &ipfdamping, ipfdamping,\n                       \"The amount of IPF damping. (lower == more damping)\");\n  clopts.attach_option(\"colors\",\n                       &colors, colors,\n                       \"The number of colors in the noisy image\");\n  clopts.attach_option(\"rows\",\n                       &rows, rows,\n                       \"The number of rows in the noisy image\");\n  clopts.attach_option(\"cols\",\n                       &cols, cols,\n                       \"The number of columns in the noisy image\");\n  clopts.attach_option(\"sigma\",\n                       &sigma, sigma,\n                       \"Standard deviation of noise.\");\n  clopts.attach_option(\"lambda\",\n                       &lambda, lambda,\n                       \"Smoothness parameter (larger => smoother).\");\n  clopts.attach_option(\"smoothing\",\n                       &smoothing, smoothing,\n                       \"Options are {square, laplace}\");\n  clopts.attach_option(\"orig\",\n                       &orig_fn, orig_fn,\n                       \"Original image file name.\");\n  clopts.attach_option(\"noisy\",\n                       &noisy_fn, noisy_fn,\n                       \"Noisy image file name.\");\n  clopts.attach_option(\"pred\",\n                       &pred_fn, pred_fn,\n                       \"Predicted image file name.\");\n  clopts.attach_option(\"pred_type\",\n                       &pred_type, pred_type,\n                       \"Predicted image type {map, exp}\");\n  \n  \n\n  clopts.set_scheduler_type(\"splash(splash_size=100)\");\n  clopts.set_scope_type(\"edge\");\n  \n\n  bool success = clopts.parse(argc, argv);\n  if(!success) {    \n    return EXIT_FAILURE;\n  }\n\n\n  \n  std::cout << \"ncpus:          \" << clopts.get_ncpus() << std::endl\n            << \"bound:          \" << bound << std::endl\n            << \"damping:        \" << damping << std::endl\n            << \"colors:         \" << colors << std::endl\n            << \"rows:           \" << rows << std::endl\n            << \"cols:           \" << cols << std::endl\n            << \"sigma:          \" << sigma << std::endl\n            << \"lambda:         \" << lambda << std::endl\n            << \"smoothing:      \" << smoothing << std::endl\n            << \"engine:         \" << clopts.get_engine_type() << std::endl\n            << \"scope:          \" << clopts.get_scope_type() << std::endl\n            << \"scheduler:      \" << clopts.get_scheduler_type() << std::endl\n            << \"orig_fn:        \" << orig_fn << std::endl\n            << \"noisy_fn:       \" << noisy_fn << std::endl\n            << \"pred_fn:        \" << pred_fn << std::endl\n            << \"pred_type:      \" << pred_type << std::endl;\n\n  \n  \n\n  // Create synthetic images -------------------------------------------------->\n  // Creating image for denoising\n  std::cout << \"Creating a synthetic image. \" << std::endl;\n  image img(rows, cols);\n  img.paint_sunset(colors);\n  graphlab::binary_factor truecounts;\n  get_image_counts(img, truecounts, colors);\n  std::cout << \"Saving image. \" << std::endl;\n  img.save(orig_fn.c_str());\n  std::cout << \"Corrupting Image. \" << std::endl;\n  img.corrupt(sigma);\n  std::cout << \"Saving corrupted image. \" << std::endl;\n  img.save(noisy_fn.c_str());\n\n\n  std::cout << \"True Counts: \" << std::endl;\n  std::cout << truecounts;\n \n  \n  \n  // Create the graph --------------------------------------------------------->\n  gl_types::core core;\n  // Set the engine options\n  core.set_engine_options(clopts);\n  \n  std::cout << \"Constructing pairwise Markov Random Field. \" << std::endl;\n  construct_graph(img, colors, sigma, core.graph());\n\n  \n  // Setup global shared variables -------------------------------------------->\n  // Initialize the edge agreement factor \n  std::cout << \"Initializing shared edge agreement factor. \" << std::endl;\n\n  // dummy variables 0 and 1 and num_rings by num_rings\n  graphlab::binary_factor edge_potential(0, colors, 0, colors);\n  // Set the smoothing type\n  if(smoothing == \"square\") {\n    edge_potential.set_as_agreement(lambda);\n  } else if (smoothing == \"laplace\") {\n    edge_potential.set_as_laplace(lambda);\n  } else {\n    std::cout << \"Invalid smoothing stype!\" << std::endl;\n    return EXIT_FAILURE;\n  }\n  std::cout << edge_potential << std::endl;\n  \n  \n  // fill the shared variales\n  sh_bound.set(bound);\n  sh_damping.set(damping);\n  sh_truecounts.set(truecounts);\n  sh_edgepot.set(edge_potential);\n  sh_ipfdamping.set(ipfdamping);\n  // make the true counts\n  \n\n  // Running the engine ------------------------------------------------------->\n  core.sched_options().add_option(\"update_function\",bp_update);\n  std::cout << \"Running the engine. \" << std::endl;\n\n  graphlab::binary_factor zero;\n  zero.resize(colors,colors);\n  zero.set_as_agreement(0);\n  core.set_sync(sh_edgepot,\n                edgepot_sync,\n                edgepot_apply,\n                zero,\n                rows*cols,\n                edgepot_merge);\n  graphlab::binary_factor oldedgepot = sh_edgepot.get_val();\n  graphlab::timer ti;\n  ti.start();\n  // loop it a few times\n  size_t update_count = 0;\n  for (size_t i = 0;i < 10; ++i) {\n    std::cout << \"restart \" << i << \"\\n\";\n    // Add the bp update to all vertices\n    core.add_task_to_all(bp_update, 100.0);\n    // Start the engine\n    core.start();\n    update_count += core.last_update_count();\n    graphlab::binary_factor newedgepot = sh_edgepot.get_val();\n    std::cout << newedgepot;\n    if (binary_factor_equal(oldedgepot, newedgepot)) break;\n    oldedgepot = newedgepot;\n  }\n  \n  double runtime = ti.current_time();\n  std::cout << \"Finished Running engine in \" << runtime \n            << \" seconds.\" << std::endl\n            << \"Total updates: \" << update_count << std::endl\n            << \"Efficiency: \" << (double(update_count) / runtime)\n            << \" updates per second \"\n            << std::endl;  \n\n\n  // Saving the output ----------------------------------------------------->\n  std::cout << \"Rendering the cleaned image. \" << std::endl;\n  if(pred_type == \"map\") {\n    for(size_t v = 0; v < core.graph().num_vertices(); ++v) {\n      const vertex_data& vdata = core.graph().vertex_data(v);\n      img.pixel(v) = vdata.belief.max_asg();    \n    }\n  } else if(pred_type == \"exp\") {\n    for(size_t v = 0; v < core.graph().num_vertices(); ++v) {\n      const vertex_data& vdata = core.graph().vertex_data(v);\n      img.pixel(v) = vdata.belief.expectation();\n    }\n  } else {\n    std::cout << \"Invalid prediction type! : \" << pred_type\n              << std::endl;\n    return EXIT_FAILURE;\n  }\n  std::cout << \"Saving cleaned image. \" << std::endl;\n  img.save(pred_fn.c_str());\n\n  std::cout << \"Done!\" << std::endl;\n  return EXIT_SUCCESS;\n} // End of main\n\n\n\n\n// Implementations\n// ============================================================>\nvoid bp_update(gl_types::iscope& scope, \n               gl_types::icallback& scheduler) {\n  //  std::cout << scope.vertex();;\n  //  std::getchar();\n  double bound = sh_bound.get_val();\n  double damping = sh_damping.get_val();\n\n  // Grab the state from the scope\n  // ---------------------------------------------------------------->\n  // Get the vertex data\n  vertex_data& v_data = scope.vertex_data();\n  \n  // Get the in and out edges by reference\n  gl_types::edge_list in_edges = scope.in_edge_ids();\n  gl_types::edge_list out_edges = scope.out_edge_ids();\n  assert(in_edges.size() == out_edges.size()); // Sanity check\n\n  // Flip the old and new messages to improve safety when using the\n  // unsynch scope\n  foreach(graphlab::edge_id_t ineid, in_edges) {   \n    // Get the in and out edge data\n    edge_data& in_edge = scope.edge_data(ineid);\n    // Since we are about to receive the current message make it the\n    // old message\n    in_edge.old_message = in_edge.message;\n  }\n\n  // Compute the belief\n  // ---------------------------------------------------------------->\n  // Initialize the belief as the value of the factor\n  v_data.belief = v_data.potential;\n  foreach(graphlab::edge_id_t ineid, in_edges) {\n    // Get the message\n    const edge_data& e_data = scope.edge_data(ineid);\n    // Notice we now use the old message since neighboring vertices\n    // could be changing the new messages\n    v_data.belief.times( e_data.old_message );\n  }\n  v_data.belief.normalize(); // finally normalize the belief\n  \n  // Compute outbound messages\n  // ---------------------------------------------------------------->\n  boost::shared_ptr<const graphlab::binary_factor> edge_factor_ptr = \n    sh_edgepot.get_ptr();\n  \n  \n  // Send outbound messages\n  graphlab::unary_factor cavity, tmp_msg;\n  for(size_t i = 0; i < in_edges.size(); ++i) {\n    // Get the edge ids\n    graphlab::edge_id_t outeid = out_edges[i];\n    graphlab::edge_id_t ineid = in_edges[i];\n    // CLEVER HACK: Here we are expoiting the sorting of the edge ids\n    // to do fast O(1) time edge reversal\n    assert(scope.target(outeid) == scope.source(ineid));\n    // Get the in and out edge data\n    const edge_data& in_edge = scope.edge_data(ineid);\n    edge_data& out_edge = scope.edge_data(outeid);\n    \n    // Compute cavity\n    cavity = v_data.belief;\n    cavity.divide(in_edge.old_message); // Make the cavity a cavity\n    cavity.normalize();\n\n\n    // convolve cavity with the edge factor storing the result in the\n    // temporary message\n    tmp_msg.resize(out_edge.message.arity());\n    tmp_msg.var() = out_edge.message.var();\n    tmp_msg.convolve(*edge_factor_ptr, cavity);\n    tmp_msg.normalize();\n\n    // Damp the message\n    tmp_msg.damp(out_edge.message, damping);\n    \n    // Compute message residual\n    double residual = tmp_msg.residual(out_edge.old_message);\n    \n    // Assign the out message\n    out_edge.message = tmp_msg;\n    \n    if(residual > bound) {\n      gl_types::update_task task(scope.target(outeid), bp_update);      \n      scheduler.add_task(task, residual);\n    }    \n  }\n} // end of BP_update\n\n\nvoid edgepot_sync(gl_types::iscope &scope,  graphlab::any& acc) {\n  gl_types::edge_list in_edges = scope.in_edge_ids();\n  gl_types::edge_list out_edges = scope.out_edge_ids();\n  assert(in_edges.size() == out_edges.size()); // Sanity check\n  \n  graphlab::binary_factor& counts = acc.as<graphlab::binary_factor>();\n  \n  // Get the in and out edge data\n  // the edge belief of u -- v\n  // belief of u / msg_{v->u) * belief of v / msg_{u->v} * edgepot;\n\n  const graphlab::unary_factor& blfu = scope.const_vertex_data().belief;\n  \n  foreach(graphlab::edge_id_t ineid, in_edges) {   \n    \n    graphlab::vertex_id_t srcv = scope.source(ineid);\n    // message from v->u\n    const graphlab::unary_factor &msgvu = \n      scope.const_edge_data(ineid).message;\n    // belief at v\n    const graphlab::unary_factor& blfv= \n      scope.const_neighbor_vertex_data(srcv).belief;\n    // get the message from u->v. requires the reverse edge\n    graphlab::edge_id_t outeid = scope.reverse_edge(ineid);\n    const graphlab::unary_factor &msguv = \n      scope.const_edge_data(outeid).message;\n    \n    boost::shared_ptr<const graphlab::binary_factor> edge_factor = \n      sh_edgepot.get_ptr();\n    \n    graphlab::binary_factor edge_belief;\n    edge_belief.resize(blfu.arity(), blfv.arity());\n    // loop through my assignments and my neighbor assignments\n    \n    // using logP to store actual counts\n    for (size_t i = 0;i < blfu.arity(); ++i) {\n      for (size_t j = 0;j < blfv.arity(); ++j) {\n        edge_belief.logP(i,j) = \n          blfu.logP(i) - msgvu.logP(i) + blfv.logP(j) - \n          msguv.logP(j) + edge_factor->logP(i,j);\n      }\n    }\n    edge_belief.normalize();\n    for (size_t i = 0;i < edge_belief.arity1(); ++i) {\n      for (size_t j = 0;j < edge_belief.arity2(); ++j) {\n        counts.logP(i,j) += std::exp(edge_belief.logP(i,j));\n      }\n    }\n    \n  }\n}\n\nvoid edgepot_merge(graphlab::any& result,  const graphlab::any& acc) {\n  graphlab::binary_factor& res = result.as<graphlab::binary_factor>();\n  const graphlab::binary_factor& a = acc.as<graphlab::binary_factor>();\n\n  for (size_t i = 0;i < res.arity1(); ++i) {\n    for (size_t j = 0;j < res.arity2(); ++j) {\n      res.logP(i,j) += a.logP(i,j);\n    }\n  }\n}\n\nvoid edgepot_apply(graphlab::any& result,  const graphlab::any& acc) {\n  // IPF update\n  graphlab::binary_factor& res = result.as<graphlab::binary_factor>();\n  graphlab::binary_factor truecounts = sh_truecounts.get_val();\n  const graphlab::binary_factor& curcounts = \n    acc.as<graphlab::binary_factor>();\n  double ipfdamping = sh_ipfdamping.get_val();\n  // perform the IPF update\n  // note that BP+IPF can be quite unstable.\n  // (We do recommend the gradient update in practice)\n  // so lets only update the parameter values if they change by > 1E-1\n  for (size_t i = 0;i < res.arity1(); ++i) {\n    for (size_t j = 0;j < res.arity2(); ++j) {\n      // + 100 to avoid divide by 0 problems\n      double newval = \n        ipfdamping * log((truecounts.logP(i,j)+100) / \n                         (curcounts.logP(i,j)+100)) + \n        (1 - ipfdamping) * res.logP(i,j);\n      if (std::fabs(res.logP(i,j) - newval) >= 1E-1) {\n        res.logP(i,j) = newval;\n      }\n    }\n  }\n  std::cout << \"sync of edge pot!\\n\";\n  std::cout << res << std::endl;\n}\n\n\nvoid construct_graph(image& img,\n                     size_t num_rings,\n                     double sigma,\n                     gl_types::graph& graph) {\n  // Construct a single blob for the vertex data\n  vertex_data vdata;\n  vdata.potential.resize(num_rings);\n  vdata.belief.resize(num_rings);\n  vdata.belief.uniform();\n  vdata.potential.uniform();\n  vdata.belief.normalize();\n  vdata.potential.normalize();\n  // Add all the vertices\n  double sigmaSq = sigma*sigma;\n  for(size_t i = 0; i < img.rows(); ++i) {\n    for(size_t j = 0; j < img.cols(); ++j) {\n      // initialize the potential and belief\n      uint32_t pixel_id = img.vertid(i, j);\n      vdata.potential.var() = vdata.belief.var() = pixel_id;\n      // Set the node potential\n      double obs = img.pixel(i, j);\n      for(size_t pred = 0; pred < num_rings; ++pred) {\n        vdata.potential.logP(pred) = \n          -(obs - pred)*(obs - pred) / (2.0 * sigmaSq);\n      }\n      vdata.potential.normalize();\n      // Store the actual data in the graph\n      size_t vertid = graph.add_vertex(vdata);\n      // Ensure that we are using a consistent numbering\n      assert(vertid == img.vertid(i, j));\n    } // end of for j in cols\n  } // end of for i in rows\n\n  // Add the edges\n  edge_data edata;\n  edata.message.resize(num_rings);\n  edata.message.uniform();\n  edata.message.normalize();\n  edata.old_message = edata.message;\n  \n  for(size_t i = 0; i < img.rows(); ++i) {\n    for(size_t j = 0; j < img.cols(); ++j) {\n      size_t vertid = img.vertid(i,j);\n      if(i-1 < img.rows()) {\n        edata.message.var() = img.vertid(i-1, j);\n        edata.old_message.var() = edata.message.var();\n        graph.add_edge(vertid, img.vertid(i-1, j), edata);\n      }\n      if(i+1 < img.rows()) {\n        edata.message.var() = img.vertid(i+1, j);\n        edata.old_message.var() = edata.message.var();\n        graph.add_edge(vertid, img.vertid(i+1, j), edata);\n      }\n      if(j-1 < img.cols()) {\n        edata.message.var() = img.vertid(i, j-1);\n        edata.old_message.var() = edata.message.var();\n        graph.add_edge(vertid, img.vertid(i, j-1), edata);\n      } if(j+1 < img.cols()) {\n        edata.message.var() = img.vertid(i, j+1);\n        edata.old_message.var() = edata.message.var();\n        graph.add_edge(vertid, img.vertid(i, j+1), edata);\n      }\n    } // end of for j in cols\n  } // end of for i in rows\n  graph.finalize();  \n} // End of construct graph\n\n\n", "meta": {"hexsha": "14ff277ea44dfbeb70a3d77ccb9bcc7673da315b", "size": 22120, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "demoapps/image_denoise/learning_denoise.cpp", "max_stars_repo_name": "iivek/graphlab-cmu-mirror", "max_stars_repo_head_hexsha": "028321757ea979e6a0859687e37933be375153eb", "max_stars_repo_licenses": ["ECL-2.0", "Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-08-01T06:32:58.000Z", "max_stars_repo_stars_event_max_datetime": "2018-08-01T06:32:58.000Z", "max_issues_repo_path": "demoapps/image_denoise/learning_denoise.cpp", "max_issues_repo_name": "iivek/graphlab-cmu-mirror", "max_issues_repo_head_hexsha": "028321757ea979e6a0859687e37933be375153eb", "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": "demoapps/image_denoise/learning_denoise.cpp", "max_forks_repo_name": "iivek/graphlab-cmu-mirror", "max_forks_repo_head_hexsha": "028321757ea979e6a0859687e37933be375153eb", "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": 33.1137724551, "max_line_length": 81, "alphanum_fraction": 0.5898734177, "num_tokens": 5624, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6334102636778401, "lm_q2_score": 0.5156199157230157, "lm_q1q2_score": 0.3265989467756611}}
{"text": "/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */\n\n/*\n Copyright (C) 2015 Peter Caspers\n\n This file is part of QuantLib, a free-software/open-source library\n for financial quantitative analysts and developers - http://quantlib.org/\n\n QuantLib is free software: you can redistribute it and/or modify it\n under the terms of the QuantLib license.  You should have received a\n copy of the license along with this program; if not, please email\n <quantlib-dev@lists.sf.net>. The license is also available online at\n <http://quantlib.org/license.shtml>.\n\n This program is distributed in the hope that it will be useful, but WITHOUT\n ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n FOR A PARTICULAR PURPOSE.  See the license for more details.\n*/\n\n#include <ql/experimental/math/mersennetwister_multithreaded.hpp>\n#include <boost/make_shared.hpp>\n\n#define MT_MT_DISPATCH(method)                                                 \\\n    switch (threadId) {                                                        \\\n    case 0:                                                                    \\\n        return m0_->method();                                                  \\\n    case 1:                                                                    \\\n        return m1_->method();                                                  \\\n    case 2:                                                                    \\\n        return m2_->method();                                                  \\\n    case 3:                                                                    \\\n        return m3_->method();                                                  \\\n    case 4:                                                                    \\\n        return m4_->method();                                                  \\\n    case 5:                                                                    \\\n        return m5_->method();                                                  \\\n    case 6:                                                                    \\\n        return m6_->method();                                                  \\\n    case 7:                                                                    \\\n        return m7_->method();                                                  \\\n    default:                                                                   \\\n        QL_FAIL(\"thread \" << threadId << \" out of range [0...7]\");             \\\n    }\n\nnamespace QuantLib {\n\nMersenneTwisterMultiThreaded::MersenneTwisterMultiThreaded(\n    const unsigned long seed) {\n    m0_ = boost::make_shared<MersenneTwisterCustomRng<Mtdesc19937_0> >(seed);\n    m1_ = boost::make_shared<MersenneTwisterCustomRng<Mtdesc19937_1> >(seed);\n    m2_ = boost::make_shared<MersenneTwisterCustomRng<Mtdesc19937_2> >(seed);\n    m3_ = boost::make_shared<MersenneTwisterCustomRng<Mtdesc19937_3> >(seed);\n    m4_ = boost::make_shared<MersenneTwisterCustomRng<Mtdesc19937_4> >(seed);\n    m5_ = boost::make_shared<MersenneTwisterCustomRng<Mtdesc19937_5> >(seed);\n    m6_ = boost::make_shared<MersenneTwisterCustomRng<Mtdesc19937_6> >(seed);\n    m7_ = boost::make_shared<MersenneTwisterCustomRng<Mtdesc19937_7> >(seed);\n}\n\nMersenneTwisterMultiThreaded::sample_type\nMersenneTwisterMultiThreaded::next(unsigned int threadId) const {\n    MT_MT_DISPATCH(next);\n}\n\nReal MersenneTwisterMultiThreaded::nextReal(unsigned int threadId) const {\n    MT_MT_DISPATCH(nextReal);\n}\n\nunsigned long MersenneTwisterMultiThreaded::\noperator()(unsigned int threadId) const {\n    MT_MT_DISPATCH(operator());\n}\n\ninline unsigned long\nMersenneTwisterMultiThreaded::nextInt32(unsigned int threadId) const {\n    MT_MT_DISPATCH(nextInt32);\n}\n}\n", "meta": {"hexsha": "5700550eef53d31ac6c4ffd410bf92f6b4bcd724", "size": 3762, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ql/experimental/math/mersennetwister_multithreaded.cpp", "max_stars_repo_name": "universe1987/QuantLib", "max_stars_repo_head_hexsha": "bbb0145aff285853755b9f6ed013f53a41163acb", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2016-03-28T15:05:23.000Z", "max_stars_repo_stars_event_max_datetime": "2020-02-17T23:05:57.000Z", "max_issues_repo_path": "ql/experimental/math/mersennetwister_multithreaded.cpp", "max_issues_repo_name": "universe1987/QuantLib", "max_issues_repo_head_hexsha": "bbb0145aff285853755b9f6ed013f53a41163acb", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2015-02-02T20:32:43.000Z", "max_issues_repo_issues_event_max_datetime": "2015-02-02T20:32:43.000Z", "max_forks_repo_path": "ql/experimental/math/mersennetwister_multithreaded.cpp", "max_forks_repo_name": "pcaspers/quantlib", "max_forks_repo_head_hexsha": "bbb0145aff285853755b9f6ed013f53a41163acb", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2015-01-26T14:50:24.000Z", "max_forks_repo_forks_event_max_datetime": "2015-10-23T07:41:30.000Z", "avg_line_length": 48.2307692308, "max_line_length": 80, "alphanum_fraction": 0.5034556087, "num_tokens": 759, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5888891451980403, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.326521638148106}}
{"text": "// Copyright (c) 2007  INRIA Sophia-Antipolis (France).\n// All rights reserved.\n//\n// This file is part of CGAL (www.cgal.org).\n//\n// $URL$\n// $Id$\n// SPDX-License-Identifier: GPL-3.0-or-later OR LicenseRef-Commercial\n//\n// Author(s)     : Laurent Rineau\n\n#include <iostream>\n#include <string>\n#include <vector>\n#include <map>\n#include <stack>\n#include <boost/tuple/tuple.hpp>\n#include <boost/tuple/tuple_comparison.hpp>\n#include <boost/format.hpp>\n\nusing std::cout;\nusing std::cin;\nusing std::endl;\n\nint main()\n{\n  std::string header;\n  cin >> header;\n\n  if(header != \"OFF\")\n  {\n    std::cerr << \"header is \\\"\" << header << \"\\\"\\nshould be \\\"OFF\\\".\\n\";\n    return 1;\n  }\n\n  cout << header << endl;\n  unsigned int n_vertices;\n  unsigned int n_facets;\n  std::string dummy;\n\n  cin >> n_vertices;\n  cin >> n_facets;\n  getline(cin, dummy);\n\n  // Vector that maps from old vertex index to new vertex index,\n  // as some (old) vertices may have identical point coordinates.\n  std::vector<int> new_index(n_vertices);\n\n  typedef boost::tuple<double, double, double> Point;\n  // Vector that stores the points coordinates (in a Point).\n  std::vector<Point> points(n_vertices);\n\n  // Map that retains the mapping from the point coordinates (in a Point)\n  // to the nex index.\n  typedef std::map<Point, int> Renumber;\n  Renumber renumber;\n\n  unsigned int index = 0;\n  for(unsigned int i = 0; i < n_vertices; ++i)\n  {\n    cin >> boost::get<0>(points[index])\n        >> boost::get<1>(points[index]) >> boost::get<2>(points[index]);\n    Renumber::const_iterator it = renumber.find(points[index]);\n    if( it == renumber.end() )\n    {\n      renumber[points[index]] = index;\n      new_index[i] = index;\n      ++index;\n    }\n    else\n    {\n      new_index[i] = it->second;\n    }\n  }\n\n  cout << index << \" \" << n_facets << dummy << endl;\n  for(unsigned int i = 0; i < index; ++i)\n  {\n    cout << boost::get<0>(points[i]) << \" \"\n         << boost::get<1>(points[i]) << \" \"\n         << boost::get<2>(points[i]) << \"\\n\";\n  }\n\n  // Vector that stores each facet.\n  typedef std::vector<boost::tuple<int, int, int> > Facets;\n  Facets facets;\n\n  // For each (oriented) edge, that map stores a vector of adjacent facets,\n  // with a boolean that tells if the edge is in the opposite orientation,\n  // in the facet.\n  // Edges are stores in the direction from the smallest index to the\n  // greatest.\n  typedef std::pair<int, int> Edge;\n  typedef std::map<Edge, std::vector<std::pair<int, bool> > > Edges_map;\n  Edges_map edges;\n\n  // \"nested function\" opposite, that returns the edge, in the opposite\n  // direction.\n  struct {\n    Edge operator()(Edge e) const {\n      return std::make_pair(e.second, e.first);\n    };\n  } opposite;\n\n  for(unsigned int i_facet = 0; i_facet < n_facets; ++i_facet)\n  {\n    // Read a facet, then reindex its vertices.\n    int i, j, k;\n    cin >> dummy >> i >> j >> k;\n    if( dummy != \"3\" )\n    {\n      std::cerr << \"In facet #\" << i_facet << \", expected \\\"3\\\", found \\\"\"\n                << dummy << \"\\\"!\\n\";\n      return 1;\n    }\n    i = new_index[i];\n    j = new_index[j];\n    k = new_index[k];\n    facets.push_back(boost::make_tuple(i, j, k));\n\n    // Create the three edges of the facet.\n    Edge e[3];\n    e[0] = std::make_pair(i, j);\n    e[1] = std::make_pair(j, k);\n    e[2] = std::make_pair(k, i);\n    for(int i_edge = 0; i_edge < 3; ++i_edge)\n    {\n      if( e[i_edge].first < e[i_edge].second )\n        edges[e[i_edge]].push_back(std::make_pair(i_facet, false));\n      else\n        edges[opposite(e[i_edge])].push_back(std::make_pair(i_facet, true));\n    }\n  }\n\n  // Map that stores all already passed facet, and retains the orientation\n  // of the facet. \"true\" means that the facet needs to be reoriented.\n  std::map<int, bool> oriented_set;\n\n  // Stack of facets indices to be handled.\n  std::stack<int> stack;\n  int seed_facet_candidate = 0;\n\n  while (oriented_set.size() != n_facets) {\n    // find a facet index that is not yet in 'oriented_set'.\n    while( oriented_set.find(seed_facet_candidate) != oriented_set.end() )\n      ++seed_facet_candidate;\n    std::cerr << \"Need seed facet: \" << seed_facet_candidate << \"\\n\";\n    // push it in oriented set\n    oriented_set[seed_facet_candidate] = false;\n    stack.push(seed_facet_candidate);\n\n    while(! stack.empty() ) {\n      const int f = stack.top();\n      stack.pop();\n      const int i = boost::get<0>(facets[f]);\n      const int j = boost::get<1>(facets[f]);\n      const int k = boost::get<2>(facets[f]);\n      Edge e[3];\n      e[0] = std::make_pair(i, j);\n      e[1] = std::make_pair(j, k);\n      e[2] = std::make_pair(k, i);\n      for(int ih = 0 ; ih < 3 ; ++ih)\n      {\n        bool f_orient = false;\n        if(e[ih].first > e[ih].second) {\n          f_orient = true;\n          e[ih] = opposite(e[ih]);\n        }\n\n        Edges_map::iterator edge_it = edges.find(e[ih]);\n        if(edge_it->second.size() == 2) { // regular edge\n          int fn = edge_it->second[0].first;\n          bool fn_orient = edge_it->second[0].second;\n          if(fn == f)\n          {\n            fn = edge_it->second[1].first;\n            fn_orient = edge_it->second[1].second;\n          }\n          if (oriented_set.find(fn) == oriented_set.end())\n          {\n            if(f_orient == fn_orient)\n              oriented_set[fn] = ! oriented_set[f];\n            else\n              oriented_set[fn] = oriented_set[f];\n            stack.push(fn);\n          }\n        } // end \"if the edge is regular\"\n        else {\n          std::cerr << boost::format(\"Irregular edge: (%1%,%2%)\"\n                                     \", %3% facets.\\n\")\n            % e[ih].first % e[ih].second\n            % edge_it->second.size();\n        }\n      } // end \"for each neighbor of f\"\n    } // end \"stack non empty\"\n  } // end \"oriented_set not full\"\n\n  for(unsigned int i_facet = 0; i_facet < n_facets; ++i_facet)\n  {\n    const int i = boost::get<0>(facets[i_facet]);\n    const int j = boost::get<1>(facets[i_facet]);\n    const int k = boost::get<2>(facets[i_facet]);\n    if(oriented_set[i_facet])\n      cout << \"3 \" << j << \" \" << i << \" \" << k << \"\\n\";\n    else\n      cout << \"3 \" << i << \" \" << j << \" \" << k << \"\\n\";\n  }\n}\n\n", "meta": {"hexsha": "7621daf177cc86bd608edb512ae2a03fd7b72d28", "size": 6164, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Mesh_3/archive/applications/identify_identical_points_in_OFF_files.cpp", "max_stars_repo_name": "antoniospg/cgal", "max_stars_repo_head_hexsha": "2891c22fc7f64f680ac7e144407afe49f6425cb9", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-12-12T09:30:07.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-04T05:00:23.000Z", "max_issues_repo_path": "Mesh_3/archive/applications/identify_identical_points_in_OFF_files.cpp", "max_issues_repo_name": "antoniospg/cgal", "max_issues_repo_head_hexsha": "2891c22fc7f64f680ac7e144407afe49f6425cb9", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": 17.0, "max_issues_repo_issues_event_min_datetime": "2018-01-10T13:32:24.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-30T12:23:20.000Z", "max_forks_repo_path": "Mesh_3/archive/applications/identify_identical_points_in_OFF_files.cpp", "max_forks_repo_name": "antoniospg/cgal", "max_forks_repo_head_hexsha": "2891c22fc7f64f680ac7e144407afe49f6425cb9", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-02-21T15:26:25.000Z", "max_forks_repo_forks_event_max_datetime": "2019-02-21T15:26:25.000Z", "avg_line_length": 29.3523809524, "max_line_length": 76, "alphanum_fraction": 0.5710577547, "num_tokens": 1753, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.588889130767832, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.32652163014698166}}
{"text": "/*\n * Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES)\n *\n * This file is part of Orfeo Toolbox\n *\n *     https://www.orfeo-toolbox.org/\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n\n#include \"itkNumericTraits.h\"\n\n#include \"otbProspectModel.h\"\n#include \"otb_boost_expint_header.h\"\n#include <boost/shared_ptr.hpp>\n#include \"otbMath.h\"\n\n//TODO check EPSILON matlab\n#define EPSILON 0.0000000000000000000000001\n\nnamespace otb\n{\n\n/** Constructor */\nProspectModel\n::ProspectModel()\n{\n   this->ProcessObject::SetNumberOfRequiredInputs(1);\n   this->ProcessObject::SetNumberOfRequiredOutputs(2);\n\n   SpectralResponseType::Pointer outputRefl = static_cast<SpectralResponseType *>(this->MakeOutput(0).GetPointer());\n   this->itk::ProcessObject::SetNthOutput(0, outputRefl.GetPointer());\n\n   SpectralResponseType::Pointer outputTrans = static_cast<SpectralResponseType *>(this->MakeOutput(1).GetPointer());\n   this->itk::ProcessObject::SetNthOutput(1, outputTrans.GetPointer());\n}\n\n/** Destructor */\nProspectModel\n::~ProspectModel()\n{}\n\n/** Set Input */\nvoid\nProspectModel\n::SetInput(const LeafParametersType * object)\n{\n   this->itk::ProcessObject::SetNthInput(0, const_cast<LeafParametersType *>(object));\n}\n\n/** Get Input */\nProspectModel::LeafParametersType *\nProspectModel\n::GetInput()\n{\n   if(this->GetNumberOfInputs() != 1)\n   {\n      //exit\n      return nullptr;\n   }\n   return static_cast<LeafParametersType *>(this->itk::ProcessObject::GetInput(0));\n}\n\n/** Make outputs */\nProspectModel::DataObjectPointer\nProspectModel\n::MakeOutput(DataObjectPointerArraySizeType)\n{\n   return static_cast<itk::DataObject *>(SpectralResponseType::New().GetPointer());\n}\n\n/** Get Reflectance */\nProspectModel::SpectralResponseType *\nProspectModel\n::GetReflectance()\n{\n   if(this->GetNumberOfOutputs() < 2)\n   {\n      //exit\n      return nullptr;\n   }\n   return static_cast<SpectralResponseType *>(this->itk::ProcessObject::GetOutput(0));\n}\n\n/** Get Transmittance */\nProspectModel::SpectralResponseType *\nProspectModel\n::GetTransmittance()\n{\n   if(this->GetNumberOfOutputs() < 2)\n   {\n      //exit\n      return nullptr;\n   }\n   return static_cast<SpectralResponseType *>(this->itk::ProcessObject::GetOutput(1));\n}\n\n\n/** Set Parameters */\nvoid\nProspectModel\n::SetInput(const ParametersType & params)\n{\n//    m_Parameters = params;\n   if(params.Size()!=6) itkExceptionMacro( << \"Must have 6 parameters in that order : Cab, Car, CBrown, Cw, Cm, N\" );\n   LeafParametersType::Pointer leafParams = LeafParametersType::New();\n   leafParams->SetCab(params[0]);\n   leafParams->SetCar(params[1]);\n   leafParams->SetCBrown(params[2]);\n   leafParams->SetCw(params[3]);\n   leafParams->SetCm(params[4]);\n   leafParams->SetN(params[5]);\n\n   this->itk::ProcessObject::SetNthInput(0, leafParams);\n}\n\n\n/** Plant Leaf Reflectance and Transmittance computation from 400nm to 2500 nm*/\nvoid\nProspectModel\n::GenerateData()\n{\n\n   LeafParametersType::Pointer leafParameters = this->GetInput();\n   SpectralResponseType::Pointer outRefl = this->GetReflectance();\n   SpectralResponseType::Pointer outTrans = this->GetTransmittance();\n\n   unsigned int alpha=40;\n   double lambda, n, k, trans, t12, temp, t21, r12, r21, x, y, ra, ta, r90, t90;\n   double delta, beta, va, vb, vbNN, vbNNinv, vainv, s1, s2, s3, RN, TN;\n   double N, Cab, Car, CBrown, Cw, Cm;\n\n   N = leafParameters->GetN();\n   Cab = leafParameters->GetCab();\n   Car = leafParameters->GetCar();\n   CBrown = leafParameters->GetCBrown();\n   Cw = leafParameters->GetCw();\n   Cm = leafParameters->GetCm();\n\n   int nbdata = sizeof(DataSpecP5B) / sizeof(DataSpec);\n   for (int i = 0; i < nbdata; ++i)\n   {\n      lambda = DataSpecP5B[i].lambda;\n      n = DataSpecP5B[i].refLeafMatInd;\n\n      k = Cab*DataSpecP5B[i].chlAbsCoef+Car*DataSpecP5B[i].carAbsCoef+CBrown*DataSpecP5B[i].brownAbsCoef+Cw*DataSpecP5B[i].waterAbsCoef;\n      k = k + Cm*DataSpecP5B[i].dryAbsCoef;\n      k = k / N;\n      if(k == itk::NumericTraits<double>::ZeroValue() ) k=EPSILON;\n\n      trans=(1.-k)*exp(-k)+k*k*boost::math::expint(1, k);\n\n      t12 = this->Tav(alpha, n);\n      temp = this->Tav(90, n);\n\n\n      t21 = temp/(n*n);\n      r12 = 1.-t12;\n      r21 = 1.-t21;\n      x = t12/temp;\n      y = x*(temp-1)+1-t12;\n\n      ra = r12+(t12*t21*r21*(trans*trans))/(1.-r21*r21*trans*trans);\n      ta = (t12*t21*trans)/(1.-r21*r21*trans*trans);\n      r90 = (ra-y)/x;\n      t90 = ta/x;\n\n      delta = (t90*t90-r90*r90-1.)*(t90*t90-r90*r90-1.) - 4.*r90*r90;\n      if(delta < 0) delta = EPSILON;\n      else delta=std::sqrt(delta);\n\n      beta = (1.+r90*r90-t90*t90-delta)/(2.*r90);\n      va=(1.+r90*r90-t90*t90+delta)/(2.*r90);\n      if ((beta-r90)<=0)\n         vb=std::sqrt(beta*(va-r90)/(va*EPSILON));\n      else\n         vb=std::sqrt(beta*(va-r90)/(va*(beta-r90)));\n\n      vbNN = std::pow(vb, N-1.);\n      vbNNinv = 1./vbNN;\n      vainv = 1./va;\n      s1=ta*t90*(vbNN-vbNNinv);\n      s2=ta*(va-vainv);\n      s3=va*vbNN-vainv*vbNNinv-r90*(vbNN-vbNNinv);\n\n      RN=ra+s1/s3;\n      TN=s2/s3;\n\n\n      SpectralResponseType::PairType rrefl;\n      SpectralResponseType::PairType ttrans;\n      rrefl.first=lambda/1000.0;\n      rrefl.second=RN;\n      ttrans.first=lambda/1000.0;\n      ttrans.second=TN;\n      outRefl->GetResponse().push_back(rrefl);\n      outTrans->GetResponse().push_back(ttrans);\n   }\n}\n\n\ndouble\nProspectModel\n::Tav(const int theta, double ref)\n{\n\n   double theta_rad = theta*CONST_PI/180;\n   double r2, rp, rm, a, k, ds, k2, rm2, res, b1, b2, b;\n   double ts, tp1, tp2, tp3, tp4, tp5, tp;\n\n   r2=ref*ref;\n   rp=r2+1;\n   rm=r2-1;\n   a=(ref+1)*(ref+1)/2;\n   k=-(r2-1)*(r2-1)/4;\n   ds=sin(theta_rad);\n\n   k2=k*k;\n   rm2=rm*rm;\n\n   if(theta_rad==0) res=4*ref/((ref+1)*(ref+1));\n   else\n   {\n      if(theta_rad==CONST_PI/2) b1=itk::NumericTraits<double>::ZeroValue();\n      else b1=std::sqrt((ds*ds-rp/2)*(ds*ds-rp/2)+k);\n\n      b2=ds*ds-rp/2;\n      b=b1-b2;\n      ts=(k2/(6*std::pow(b, 3))+k/b-b/2)-(k2/(6*std::pow(a, 3))+k/a-a/2);\n      tp1=-2*r2*(b-a)/(rp*rp);\n      tp2=-2*r2*rp*log(b/a)/rm2;\n      tp3=r2*(1./b-1./a)/2;\n      tp4=16*r2*r2*(r2*r2+1)*log((2*rp*b-rm2)/(2*rp*a-rm2))/(std::pow(rp, 3)*rm2);\n      tp5=16*std::pow(r2, 3)*(1./(2*rp*b-rm2)-1./(2*rp*a-rm2))/std::pow(rp, 3);\n      tp=tp1+tp2+tp3+tp4+tp5;\n      res=(ts+tp)/(2*ds*ds);\n   }\n   return res;\n\n\n}\n\nvoid\nProspectModel\n::PrintSelf(std::ostream& os, itk::Indent indent) const\n{\n   Superclass::PrintSelf(os, indent);\n\n}\n} // end namespace otb\n", "meta": {"hexsha": "f124488920ccd14fc6015ecd55adfe74060906e4", "size": 6927, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "Modules/Radiometry/Simulation/src/otbProspectModel.cxx", "max_stars_repo_name": "xcorail/OTB", "max_stars_repo_head_hexsha": "092a93654c3b5d009e420f450fe9b675f737cdca", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Modules/Radiometry/Simulation/src/otbProspectModel.cxx", "max_issues_repo_name": "xcorail/OTB", "max_issues_repo_head_hexsha": "092a93654c3b5d009e420f450fe9b675f737cdca", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Modules/Radiometry/Simulation/src/otbProspectModel.cxx", "max_forks_repo_name": "xcorail/OTB", "max_forks_repo_head_hexsha": "092a93654c3b5d009e420f450fe9b675f737cdca", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.4389312977, "max_line_length": 136, "alphanum_fraction": 0.6474664357, "num_tokens": 2261, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6477982179521103, "lm_q2_score": 0.5039061705290805, "lm_q1q2_score": 0.3264295192838106}}
{"text": "// Copyright (c) 2020 CNES\n//\n// All rights reserved. Use of this source code is governed by a\n// BSD-style license that can be found in the LICENSE file.\n#pragma once\n#include <array>\n#include <complex>\n#include <memory>\n#include <string>\n#include <vector>\n#include <Eigen/Core>\n#include \"angle.hpp\"\n#include \"astronomic_angle.hpp\"\n#include \"math.hpp\"\n\n/// @brief Wave definition\nclass Wave : public std::enable_shared_from_this<Wave> {\n public:\n  /// Typename to a function pointer for calculate the nodal factor\n  using NodalFactor = double (AstronomicAngle::*)() const;\n\n  /// @brief Possible type of tidal wave.\n  enum TidalType {\n    kLongPeriod = 0,  //!< Long period tidal waves\n    kShortPeriod      //!< Short period tidal waves\n  };\n\n  /// @brief Index to access the wave in the internal table\n  enum Ident : size_t {\n    kMm = 0,        //!< %Mm\n    kMf = 1,        //!< %Mf\n    kMtm = 2,       //!< %Mtm\n    kMsqm = 3,      //!< %Msqm\n    k2Q1 = 4,       //!< 2Q₁\n    kSigma1 = 5,    //!< σ₁\n    kQ1 = 6,        //!< Q₁\n    kRho1 = 7,      //!< ρ₁\n    kO1 = 8,        //!< O₁\n    kMP1 = 9,       //!< MP₁\n    kM11 = 10,      //!< M₁₁\n    kM12 = 11,      //!< M₁₂\n    kM13 = 12,      //!< M₁₃\n    kChi1 = 13,     //!< χ₁\n    kPi1 = 14,      //!< π₁\n    kP1 = 15,       //!< P₁\n    kS1 = 16,       //!< S₁\n    kK1 = 17,       //!< K₁\n    kPsi1 = 18,     //!< ψ₁\n    kPhi1 = 19,     //!< φ₁\n    kTheta1 = 20,   //!< θ₁\n    kJ1 = 21,       //!< J₁\n    kOO1 = 22,      //!< OO₁\n    kMNS2 = 23,     //!< MNS₂\n    kEps2 = 24,     //!< ε₂\n    k2N2 = 25,      //!< 2N₂\n    kMu2 = 26,      //!< µ₂\n    k2MS2 = 27,     //!< 2MS₂\n    kN2 = 28,       //!< N₂\n    kNu2 = 29,      //!< ν₂\n    kM2 = 30,       //!< M₂\n    kMKS2 = 31,     //!< MKS₂\n    kLambda2 = 32,  //!< λ₂\n    kL2 = 33,       //!< L₂\n    k2MN2 = 34,     //!< 2MN₂\n    kT2 = 35,       //!< T₂\n    kS2 = 36,       //!< S₂\n    kR2 = 37,       //!< R₂\n    kK2 = 38,       //!< K₂\n    kMSN2 = 39,     //!< MSN₂\n    kEta2 = 40,     //!< η₂\n    k2SM2 = 41,     //!< 2SM₂\n    kMO3 = 42,      //!< MO₃\n    k2MK3 = 43,     //!< 2MK₃\n    kM3 = 44,       //!< M₃\n    kMK3 = 45,      //!< MK₃\n    kN4 = 46,       //!< N₄\n    kMN4 = 47,      //!< MN₄\n    kM4 = 48,       //!< M₄\n    kSN4 = 49,      //!< SN₄\n    kMS4 = 50,      //!< MS₄\n    kMK4 = 51,      //!< MK₄\n    kS4 = 52,       //!< S₄\n    kSK4 = 53,      //!< SK₄\n    kR4 = 54,       //!< R₄\n    k2MN6 = 55,     //!< 2MN₆\n    kM6 = 56,       //!< M₆\n    kMSN6 = 57,     //!< MSN₆\n    k2MS6 = 58,     //!< 2MS₆\n    k2MK6 = 59,     //!< 2MK₆\n    k2SM6 = 60,     //!< 2SM₆\n    kMSK6 = 61,     //!< MSK₆\n    kS6 = 62,       //!< S₆\n    kM8 = 63,       //!< %M8\n    kMSf = 64,      //!< %MSf\n    kSsa = 65,      //!< %Ssa\n    kSa = 66,       //!< %Sa\n  };\n\n protected:\n  /// nodal correction for phase\n  double u_{std::numeric_limits<double>::quiet_NaN()};\n\n private:\n  /// Wave ident\n  Ident ident_;\n\n  /// Type of tide.\n  TidalType type_;\n\n  /// Function to call for computing the node factor\n  NodalFactor calculate_node_factor_;\n\n  /// Wave frequency.\n  double freq_;\n\n  /// greenwich argument\n  double v_{std::numeric_limits<double>::quiet_NaN()};\n\n  /// Nodal correction for amplitude.\n  double f_{std::numeric_limits<double>::quiet_NaN()};\n\n  /// Harmonic constituents (T, s, h, p, N′, p₁, shift, ξ, ν, ν′, ν″)\n  std::array<int16_t, 11> argument_;\n\n  /// Computes the wave frequency from the doodson arguments\n  ///\n  /// @param t Mean solar angle relative to Greenwich\n  /// @param s moon's mean longitude\n  /// @param h sun's mean longitude\n  /// @param p longitude of moon's perigee\n  /// @param n longitude of moon's ascending node\n  /// @param p1 longitude of sun's perigee\n  static constexpr double frequency(const int16_t t, const int16_t s,\n                                    const int16_t h, const int16_t p,\n                                    const int16_t n, const int16_t p1) {\n    return ((frequency::tau() + frequency::s() - frequency::h()) * t +\n            frequency::s() * s + frequency::h() * h + frequency::p() * p +\n            frequency::n() * n + frequency::p1() * p1) *\n           360;\n  }\n\n public:\n  /// Initializes the properties of the wave (frequency, doodson's coefficients,\n  /// etc.).\n  ///\n  /// @param ident Index of the wave in the internal table\n  /// @param t Mean solar angle relative to Greenwich\n  /// @param s moon's mean longitude\n  /// @param h sun's mean longitude\n  /// @param p longitude of moon's perigee\n  /// @param n longitude of moon's ascending node\n  /// @param p1 longitude of sun's perigee\n  /// @param shift TODO\n  /// @param eps Coefficient for the longitude in moon's orbit of lunar\n  ///   intersection\n  /// @param nu Coefficient for the right ascension of lunar intersection\n  /// @param nuprim Coefficient for the term in argument of lunisolar\n  ///   constituent K₁\n  /// @param nusec Coefficient for the term in argument of lunisolar constituent\n  ///   K₂\n  /// @param type Type of tidal wave\n  /// @param calculate_node_factor Function used to calculate the nodal factor\n  Wave(const Ident ident, const int16_t t, const int16_t s, const int16_t h,\n       const int16_t p, const int16_t n, const int16_t p1, const int16_t shift,\n       const int16_t eps, const int16_t nu, const int16_t nuprim,\n       const int16_t nusec, TidalType type, NodalFactor calculate_node_factor)\n      : ident_(ident),\n        type_(type),\n        calculate_node_factor_(calculate_node_factor),\n        freq_(radians(frequency(t, s, h, p, n, p1)) / 3600.0) {\n    argument_[0] = t;\n    argument_[1] = s;\n    argument_[2] = h;\n    argument_[3] = p;\n    argument_[4] = n;\n    argument_[5] = p1;\n    argument_[6] = shift;\n    argument_[7] = eps;\n    argument_[8] = nu;\n    argument_[9] = nuprim;\n    argument_[10] = nusec;\n  }\n\n  /// Default destructor\n  virtual ~Wave() = default;\n\n  /// Default copy constructor\n  Wave(const Wave&) = default;\n\n  /// Default copy assignment operator\n  Wave& operator=(const Wave&) = default;\n\n  /// Move constructor\n  Wave(Wave&&) noexcept = default;\n\n  /// Move assignment operator\n  Wave& operator=(Wave&&) noexcept = default;\n\n  /// Compute nodal corrections from SCHUREMAN (1958).\n  ///\n  /// @param a Astronomic angle\n  void nodal_a(const AstronomicAngle& a) { f_ = (a.*calculate_node_factor_)(); }\n\n  /// Compute nodal corrections from SCHUREMAN (1958).\n  ///\n  /// @param a Astronomic angle\n  virtual void nodal_g(const AstronomicAngle& a);\n\n  /// Gets the wave ident\n  constexpr Ident ident() const noexcept { return ident_; }\n\n  /// Gets the wave frequency (radians per seconds)\n  constexpr double freq() const noexcept { return freq_; }\n\n  /// Gets the wave type\n  constexpr TidalType type() const noexcept { return type_; }\n\n  /// Gets v (greenwich argument) + u (nodal correction for phase)\n  double vu() const noexcept { return std::fmod(v_ + u_, two_pi<double>()); }\n\n  /// Gets v0 (greenwich argument)\n  double v() const noexcept { return v_; }\n\n  /// Gets the nodal correction for amplitude\n  constexpr double f() const noexcept { return f_; }\n\n  /// Gets the nodal correction for phase\n  constexpr double u() const noexcept { return u_; }\n\n  /// Gets the wave name\n  std::string name() const;\n};\n\n/// Mm\n///\n/// V = s - p;\n/// u = 0;\n/// f = f(Mm)\nclass Mm : public Wave {\n public:\n  Mm()\n      : Wave(kMm, 0, 1, 0, -1, 0, 0, 0, 0, 0, 0, 0, kLongPeriod,\n             &AstronomicAngle::f_mm) {}\n};\n\n/// Mf\n///\n/// V = 2s\n/// u = -2ξ\n/// f = f(Mf)\nclass Mf : public Wave {\n public:\n  Mf()\n      : Wave(kMf, 0, 2, 0, 0, 0, 0, 0, -2, 0, 0, 0, kLongPeriod,\n             &AstronomicAngle::f_mf) {}\n};\n\n/// Mtm\n///\n/// V = 3s - p\n/// u = -2ξ\n/// f = f(Mf)\nclass Mtm : public Wave {\n public:\n  Mtm()\n      : Wave(kMtm, 0, 3, 0, -1, 0, 0, 0, -2, 0, 0, 0, kLongPeriod,\n             &AstronomicAngle::f_mf) {}\n};\n\n/// Msqm\n///\n/// V = 4s - 2h\n/// u = -2ξ\n/// f = f(Mf)\nclass Msqm : public Wave {\n public:\n  Msqm()\n      : Wave(kMsqm, 0, 4, -2, 0, 0, 0, 0, -2, 0, 0, 0, kLongPeriod,\n             &AstronomicAngle::f_mf) {}\n};\n\n/// Ssa\n///\n/// V = 2h\n/// u = 0\n/// f = 1\nclass Ssa : public Wave {\n public:\n  Ssa()\n      : Wave(kSsa, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, kLongPeriod,\n             &AstronomicAngle::f_1) {}\n};\n\n/// Sa\n///\n/// V = h\n/// u = 0\n/// f = 1\nclass Sa : public Wave {\n public:\n  Sa()\n      : Wave(kSa, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, kLongPeriod,\n             &AstronomicAngle::f_1) {}\n};\n\n/// 2Q₁\n///\n/// V = T - 4s + h + 2p + 90°\n/// u = +2ξ - ν\n/// f = f(O₁)\nclass _2Q1 : public Wave {\n public:\n  _2Q1()\n      : Wave(k2Q1, 1, -4, 1, 2, 0, 0, 1, 2, -1, 0, 0, kShortPeriod,\n             &AstronomicAngle::f_o1) {}\n};\n\n/// σ₁\n///\n/// V = T - 4s + 3h + 90°\n/// u = +2ξ - ν\n/// f = f(O₁)\nclass Sigma1 : public Wave {\n public:\n  Sigma1()\n      : Wave(kSigma1, 1, -4, 3, 0, 0, 0, 1, 2, -1, 0, 0, kShortPeriod,\n             &AstronomicAngle::f_o1) {}\n};\n\n/// Q₁\n///\n/// V = T - 3s + h + p + 90°\n/// u = +2ξ - ν\n/// f = f(O₁)\nclass Q1 : public Wave {\n public:\n  Q1()\n      : Wave(kQ1, 1, -3, 1, 1, 0, 0, 1, 2, -1, 0, 0, kShortPeriod,\n             &AstronomicAngle::f_o1) {}\n};\n\n/// ρ₁\n///\n/// V = T - 3s + 3h - p + 90°\n/// u = +2ξ - ν\n/// f = f(O₁)\nclass Rho1 : public Wave {\n public:\n  Rho1()\n      : Wave(kRho1, 1, -3, 3, -1, 0, 0, 1, 2, -1, 0, 0, kShortPeriod,\n             &AstronomicAngle::f_o1) {}\n};\n\n// O₁\n///\n/// V = T - 2s + h + 90°\n/// u = +2ξ - ν\n/// f = f(O₁)\n///\nclass O1 : public Wave {\n public:\n  O1()\n      : Wave(kO1, 1, -2, 1, 0, 0, 0, 1, 2, -1, 0, 0, kShortPeriod,\n             &AstronomicAngle::f_o1) {}\n};\n\n/// MP₁\n///\n/// V = T - 2s + 3h - 90°\n/// u = -ν\n/// f = f(J₁)\nclass MP1 : public Wave {\n public:\n  MP1()\n      : Wave(kMP1, 1, -2, 3, 0, 0, 0, -1, 0, -1, 0, 0, kShortPeriod,\n             &AstronomicAngle::f_j1) {}\n};\n\n/// M₁₂ (Formula A16)\n///\n/// V = T - s + h - p - 90°\n/// u = +2ξ - ν\n/// f = f(O₁)\nclass M12 : public Wave {\n public:\n  M12()\n      : Wave(kM12, 1, -1, 1, -1, 0, 0, -1, 2, -1, 0, 0, kShortPeriod,\n             &AstronomicAngle::f_o1) {}\n};\n\n/// M₁₃ (= M11 + M12)\n///\n/// V = T - s + h + p - 90\n/// u = -ν\n/// f = f(M₁₃)\nclass M13 : public Wave {\n public:\n  M13()\n      : Wave(kM13, 1, -1, 1, 1, 0, 0, -1, 0, -1, 0, 0, kShortPeriod,\n             &AstronomicAngle::f_m13) {}\n\n  /// Compute nodal corrections from SCHUREMAN (1958).\n  ///\n  /// @param a Astronomic angle\n  void nodal_g(const AstronomicAngle& a) final {\n    Wave::nodal_g(a);\n    u_ -= radians(1.0 /\n                  std::sqrt(2.310 + 1.435 * std::cos(2 * (a.p() - a.xi()))));\n  }\n};\n\n/// M₁₁ (Formula A23)\n///\n/// V = T - s + h + p - 90°\n/// u = -ν\n/// f = f(J₁)\nclass M11 : public Wave {\n public:\n  M11()\n      : Wave(kM11, 1, -1, 1, 1, 0, 0, -1, 0, -1, 0, 0, kShortPeriod,\n             &AstronomicAngle::f_j1) {}\n};\n\n/// χ₁\n///\n/// V = T - s + 3h - p - 90°\n/// u = -ν\n/// f = f(J₁)\nclass Chi1 : public Wave {\n public:\n  Chi1()\n      : Wave(kChi1, 1, -1, 3, -1, 0, 0, -1, 0, -1, 0, 0, kShortPeriod,\n             &AstronomicAngle::f_j1) {}\n};\n\n/// π₁\n///\n/// V = T - 2h + p1 + 90°\n/// u = 0\n/// f = 1\nclass Pi1 : public Wave {\n public:\n  Pi1()\n      : Wave(kPi1, 1, 0, -2, 0, 0, 1, 1, 0, 0, 0, 0, kShortPeriod,\n             &AstronomicAngle::f_1) {}\n};\n\n/// P₁\n///\n/// V = T - h + 90°\n/// u = 0\n/// f = 1\nclass P1 : public Wave {\n public:\n  P1()\n      : Wave(kP1, 1, 0, -1, 0, 0, 0, 1, 0, 0, 0, 0, kShortPeriod,\n             &AstronomicAngle::f_1) {}\n};\n\n/// S₁\n///\n/// V = T\n/// u = 0\n/// f = 1\nclass S1 : public Wave {\n public:\n  S1()\n      : Wave(kS1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, kShortPeriod,\n             &AstronomicAngle::f_1) {}\n};\n\n/// K₁\n///\n/// V = T + h - 90°\n/// u = - ν'\n/// f = f(k₁)\nclass K1 : public Wave {\n public:\n  K1()\n      : Wave(kK1, 1, 0, 1, 0, 0, 0, -1, 0, 0, -1, 0, kShortPeriod,\n             &AstronomicAngle::f_k1) {}\n};\n\n/// ψ₁\n///\n/// V = T + 2h - p1 - 90°\n/// u = 0\n/// f = 1\nclass Psi1 : public Wave {\n public:\n  Psi1()\n      : Wave(kPsi1, 1, 0, 2, 0, 0, -1, -1, 0, 0, 0, 0, kShortPeriod,\n             &AstronomicAngle::f_1) {}\n};\n\n/// φ₁\n///\n/// V = T + 3h - 90°\n/// u = 0\n/// f = 1\nclass Phi1 : public Wave {\n public:\n  Phi1()\n      : Wave(kPhi1, 1, 0, 3, 0, 0, 0, -1, 0, 0, 0, 0, kShortPeriod,\n             &AstronomicAngle::f_1) {}\n};\n\n/// θ₁\n///\n/// V = T + s - h + p - 90°\n/// u = -ν\n/// f = f(J₁)\nclass Theta1 : public Wave {\n public:\n  Theta1()\n      : Wave(kTheta1, 1, 1, -1, 1, 0, 0, -1, 0, -1, 0, 0, kShortPeriod,\n             &AstronomicAngle::f_j1) {}\n};\n\n/// J₁\n///\n/// V = T + s + h - p - 90°\n/// u = -ν\n/// f = f(J₁)\nclass J1 : public Wave {\n public:\n  J1()\n      : Wave(kJ1, 1, 1, 1, -1, 0, 0, -1, 0, -1, 0, 0, kShortPeriod,\n             &AstronomicAngle::f_j1) {}\n};\n\n/// OO₁\n///\n/// V = T + 2s + h - 90°\n/// u = -2ξ - ν\n/// f = f(OO₁)\nclass OO1 : public Wave {\n public:\n  OO1()\n      : Wave(kOO1, 1, 2, 1, 0, 0, 0, -1, -2, -1, 0, 0, kShortPeriod,\n             &AstronomicAngle::f_oo1) {}\n};\n\n/// MNS₂ = M₂ + N₂ + S₂\n///\n/// V = 2T - 5s + 4h + p\n/// u = +4ξ - 4ν\n/// f = f(M₂)²\nclass MNS2 : public Wave {\n public:\n  MNS2()\n      : Wave(kMNS2, 2, -5, 4, 1, 0, 0, 0, 4, -4, 0, 0, kShortPeriod,\n             &AstronomicAngle::f_m22) {}\n};\n\n/// ε₂\n///\n/// V = 2T - 5s + 4h + p\n/// u = +2ξ - 2ν\n/// f = f(M₂)\nclass Eps2 : public Wave {\n public:\n  Eps2()\n      : Wave(kEps2, 2, -5, 4, 1, 0, 0, 0, 2, -2, 0, 0, kShortPeriod,\n             &AstronomicAngle::f_m2) {}\n};\n\n/// 2N₂\n///\n/// V = 2T - 4s + 2h + 2p\n/// u = +2ξ - 2ν\n/// f = f(M₂)\nclass _2N2 : public Wave {\n public:\n  _2N2()\n      : Wave(k2N2, 2, -4, 2, 2, 0, 0, 0, 2, -2, 0, 0, kShortPeriod,\n             &AstronomicAngle::f_m2) {}\n};\n\n/// µ₂\n///\n/// V = 2T - 4s + 4h\n/// u = +2ξ - 2ν\n/// f = f(M₂)\nclass Mu2 : public Wave {\n public:\n  Mu2()\n      : Wave(kMu2, 2, -4, 4, 0, 0, 0, 0, 2, -2, 0, 0, kShortPeriod,\n             &AstronomicAngle::f_m2) {}\n};\n\n/// 2MS₂ = 2M₂ - S₂\n///\n/// V = 2T - 4s + 4h\n/// u = +4ξ - 4ν\n/// f = f(M₂)²\nclass _2MS2 : public Wave {\n public:\n  _2MS2()\n      : Wave(k2MS2, 2, -4, 4, 0, 0, 0, 0, 4, -4, 0, 0, kShortPeriod,\n             &AstronomicAngle::f_m22) {}\n};\n\n/// N₂\n///\n/// V = 2T - 3s + 2h + p\n/// u = +2ξ - 2ν\n/// f = f(M₂)\nclass N2 : public Wave {\n public:\n  N2()\n      : Wave(kN2, 2, -3, 2, 1, 0, 0, 0, 2, -2, 0, 0, kShortPeriod,\n             &AstronomicAngle::f_m2) {}\n};\n\n/// ν₂\n///\n/// V = 2T - 3s + 4h - p\n/// u = +2ξ - 2ν\n/// f = f(M₂)\nclass Nu2 : public Wave {\n public:\n  Nu2()\n      : Wave(kNu2, 2, -3, 4, -1, 0, 0, 0, 2, -2, 0, 0, kShortPeriod,\n             &AstronomicAngle::f_m2) {}\n};\n\n/// M₂\n///\n/// V = 2T - 2s + 2h\n/// u = +2ξ - 2ν\n/// f = f(M₂)\nclass M2 : public Wave {\n public:\n  M2()\n      : Wave(kM2, 2, -2, 2, 0, 0, 0, 0, 2, -2, 0, 0, kShortPeriod,\n             &AstronomicAngle::f_m2) {}\n};\n\n/// MKS₂ = M₂ + K₂ - S₂\n///\n/// V = 2T - 2s + 4h\n/// u = +2ξ - 2ν -2ν''\n/// f = f(M₂) × f(K₂)\nclass MKS2 : public Wave {\n public:\n  MKS2()\n      : Wave(kMKS2, 2, -2, 4, 0, 0, 0, 0, 2, -2, 0, -2, kShortPeriod,\n             &AstronomicAngle::f_m2_k2) {}\n};\n\n/// λ₂\n///\n/// V = 2T - s + p + 180°\n/// u = +2ξ - 2ν\n/// f = f(M₂)\nclass Lambda2 : public Wave {\n public:\n  Lambda2()\n      : Wave(kLambda2, 2, -1, 0, 1, 0, 0, 2, 2, -2, 0, 0, kShortPeriod,\n             &AstronomicAngle::f_m2) {}\n};\n\n/// L₂\n///\n/// V = 2T - s + 2h - p + 180°\n/// u = +2ξ - 2ν - R\n/// f = f(L₂)\nclass L2 : public Wave {\n public:\n  L2()\n      : Wave(kL2, 2, -1, 2, -1, 0, 0, 2, 2, -2, 0, 0, kShortPeriod,\n             &AstronomicAngle::f_l2) {}\n\n  /// Compute nodal corrections from SCHUREMAN (1958).\n  ///\n  /// @param a Astronomic angle\n  void nodal_g(const AstronomicAngle& a) final {\n    Wave::nodal_g(a);\n    u_ -= a.r();\n  }\n};\n\n/// 2MN₂ = 2M₂ - N₂\n///\n/// V = 2T - s + 2h - p + 180°\n/// u = +2ξ - 2ν\n/// f = f(M₂)³\nclass _2MN2 : public Wave {\n public:\n  _2MN2()\n      : Wave(k2MN2, 2, -1, 2, -1, 0, 0, 2, 2, -2, 0, 0, kShortPeriod,\n             &AstronomicAngle::f_m23) {}\n};\n\n/// T₂\n///\n/// V = 2T - h + p₁\n/// u = 0\n/// f = 1\nclass T2 : public Wave {\n public:\n  T2()\n      : Wave(kT2, 2, 0, -1, 0, 0, 1, 0, 0, 0, 0, 0, kShortPeriod,\n             &AstronomicAngle::f_1) {}\n};\n\n/// S₂\n///\n/// V = 2T\n/// u = 0\n/// f = 1\nclass S2 : public Wave {\n public:\n  S2()\n      : Wave(kS2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, kShortPeriod,\n             &AstronomicAngle::f_1) {}\n};\n\n/// R₂\n///\n/// V = 2T + h - p1 + 180°\n/// u = 0\n/// f = 1\nclass R2 : public Wave {\n public:\n  R2()\n      : Wave(kR2, 2, 0, 1, 0, 0, -1, 2, 0, 0, 0, 0, kShortPeriod,\n             &AstronomicAngle::f_1) {}\n};\n\n/// K₂\n///\n/// V = 2T + 2h\n/// u = -2ν″\n/// f = f(K₂)\nclass K2 : public Wave {\n public:\n  K2()\n      : Wave(kK2, 2, 0, 2, 0, 0, 0, 0, 0, 0, 0, -2, kShortPeriod,\n             &AstronomicAngle::f_k2) {}\n};\n\n/// MSN₂ = M2 + S2 - N2\n///\n/// V = 2T + s -p\n/// u = 0\n/// f = f(M₂)²\nclass MSN2 : public Wave {\n public:\n  MSN2()\n      : Wave(kMSN2, 2, 1, 0, -1, 0, 0, 0, 0, 0, 0, 0, kShortPeriod,\n             &AstronomicAngle::f_m22) {}\n};\n\n/// η₂ = KJ₂\n///\n/// V = 2T + s + 2h - p\n/// u = -2ν\n/// f = f(KJ₂)\nclass Eta2 : public Wave {\n public:\n  Eta2()\n      : Wave(kEta2, 2, 1, 2, -1, 0, 0, 0, 0, -2, 0, 0, kShortPeriod,\n             &AstronomicAngle::f_kj2) {}\n};\n\n/// 2SM₂ = 2S₂ - M₂\n///\n/// V = 2T + 2s - 2h\n/// u = -2ξ + 2ν\n/// f = f(M₂)\nclass _2SM2 : public Wave {\n public:\n  _2SM2()\n      : Wave(k2SM2, 2, 2, -2, 0, 0, 0, 0, 2, -2, 0, 0, kShortPeriod,\n             &AstronomicAngle::f_m2) {}\n};\n\n/// MO₃ = M₂ + O₁\n///\n/// V = 3T - 4s + 3h + 90°\n/// u = 4ξ - 3ν\n/// f = f(M₂) × f(O₁)\nclass MO3 : public Wave {\n public:\n  MO3()\n      : Wave(kMO3, 3, -4, 3, 0, 0, 0, 1, 4, -3, 0, 0, kShortPeriod,\n             &AstronomicAngle::f_m2_o1) {}\n};\n\n/// 2MK₃ = 2M₂ - K₁\n///\n/// V = 3T - 4s + 3h + 90°\n/// u = 4ξ - 4ν + ν′\n/// f = f(M₂)² × f(K₁)\nclass _2MK3 : public Wave {\n public:\n  _2MK3()\n      : Wave(k2MK3, 3, -4, 3, 0, 0, 0, 1, 4, -4, 1, 0, kShortPeriod,\n             &AstronomicAngle::f_m22_k1) {}\n};\n\n/// M₃\n///\n/// V = 3T - 3s + 3h\n/// u = +3ξ - 3ν\n/// f = f(M₃)\nclass M3 : public Wave {\n public:\n  M3()\n      : Wave(kM3, 3, -3, 3, 0, 0, 0, 0, 3, -3, 0, 0, kShortPeriod,\n             &AstronomicAngle::f_m3) {}\n};\n\n/// MK₃ = M₂ + K₁\n///\n/// V = 3T - 2s + 3h - 90°\n/// u = 2ξ - 2ν - ν′\n/// f = f(M₂) × f(K₁)\nclass MK3 : public Wave {\n public:\n  MK3()\n      : Wave(kMK3, 3, -2, 3, 0, 0, 0, -1, 2, -2, -1, 0, kShortPeriod,\n             &AstronomicAngle::f_m2_k1) {}\n};\n\n/// N4 = N₂ + N₂\n///\n/// V = 4T - 6s + 4h + 2p\n/// u = +4ξ - 4ν\n/// f = f(M₂)²\nclass N4 : public Wave {\n public:\n  N4()\n      : Wave(kN4, 4, -6, 4, 2, 0, 0, 0, 4, -4, 0, 0, kShortPeriod,\n             &AstronomicAngle::f_m22) {}\n};\n\n/// MN₄ = M₂ + N₂\n///\n/// V = 4T - 5s + 4h + p\n/// u = +4ξ - 4ν\n/// f = f(M₂)²\nclass MN4 : public Wave {\n public:\n  MN4()\n      : Wave(kMN4, 4, -5, 4, 1, 0, 0, 0, 4, -4, 0, 0, kShortPeriod,\n             &AstronomicAngle::f_m22) {}\n};\n\n/// M₄ = 2M₂\n///\n/// V = 4T - 4s + 4h\n/// u = +4ξ - 4ν\n/// f = f²(M₂)\nclass M4 : public Wave {\n public:\n  M4()\n      : Wave(kM4, 4, -4, 4, 0, 0, 0, 0, 4, -4, 0, 0, kShortPeriod,\n             &AstronomicAngle::f_m22) {}\n};\n\n/// SN₄ = S₂ + N₂\n///\n/// V = 4T - 3s + 2h + p\n/// u = 2ξ - 2ν\n/// f = f(M₂)\nclass SN4 : public Wave {\n public:\n  SN4()\n      : Wave(kSN4, 4, -3, 2, 1, 0, 0, 0, 2, -2, 0, 0, kShortPeriod,\n             &AstronomicAngle::f_m2) {}\n};\n\n/// MS₄ = M₂ + S₂\n///\n/// V = 4T - 2s + 2h\n/// u = +2ξ - 2ν\n/// f = f(M₂)\nclass MS4 : public Wave {\n public:\n  MS4()\n      : Wave(kMS4, 4, -2, 2, 0, 0, 0, 0, 2, -2, 0, 0, kShortPeriod,\n             &AstronomicAngle::f_m2) {}\n};\n\n/// MK₄ = M₂ + K₂\n///\n/// V = 4T - 2s + 4h\n/// u = 2ξ - 2ν - 2ν''\n/// f = f(MK₄)\nclass MK4 : public Wave {\n public:\n  MK4()\n      : Wave(kMK4, 4, -2, 4, 0, 0, 0, 0, 2, -2, -2, 0, kShortPeriod,\n             &AstronomicAngle::f_m2_k2) {}\n};\n\n/// S₄ = S₂ + S₂\n///\n/// V = 4T\n/// u = 0\n/// f = 1\nclass S4 : public Wave {\n public:\n  S4()\n      : Wave(kS4, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, kShortPeriod,\n             &AstronomicAngle::f_1) {}\n};\n\n/// SK₄ = S₂ + K₂\n///\n/// V = 4T + 2h\n/// u = -2ν''\n/// f = f(K₂)\nclass SK4 : public Wave {\n public:\n  SK4()\n      : Wave(kSK4, 4, 0, 2, 0, 0, 0, 0, 0, 0, 0, -2, kShortPeriod,\n             &AstronomicAngle::f_k2) {}\n};\n\n/// R₄ = R₂ + R₂\n///\n/// V = 4T + 2h - 2p1\n/// u = 0\n/// f = 1\nclass R4 : public Wave {\n public:\n  R4()\n      : Wave(kR4, 4, 0, 2, 0, 0, -2, 0, 0, 0, 0, 0, kShortPeriod,\n             &AstronomicAngle::f_1) {}\n};\n\n/// 2MN₆ = 2M₂ + N₂\n///\n/// V = 6T - 7s + 6h + p\n/// u = 6ξ - 6ν\n/// f = f(M₂)³\nclass _2MN6 : public Wave {\n public:\n  _2MN6()\n      : Wave(k2MN6, 6, -7, 6, 1, 0, 0, 0, 6, -6, 0, 0, kShortPeriod,\n             &AstronomicAngle::f_m23) {}\n};\n\n/// M₆ = 3M₂\n///\n/// V = 6T - 6s + 6h\n/// u = +6ξ - 6ν\n/// f = f(M₂)³\nclass M6 : public Wave {\n public:\n  M6()\n      : Wave(kM6, 6, -6, 6, 0, 0, 0, 0, 6, -6, 0, 0, kShortPeriod,\n             &AstronomicAngle::f_m23) {}\n};\n\n/// MSN₆ = M₂ + S₂ + N₂\n///\n/// V = 6T - 5s + 4h + p\n/// u = 4ξ - 4ν\n/// f = f(M₂)²\nclass MSN6 : public Wave {\n public:\n  MSN6()\n      : Wave(kMSN6, 6, -5, 4, 1, 0, 0, 0, 4, -4, 0, 0, kShortPeriod,\n             &AstronomicAngle::f_m22) {}\n};\n\n/// 2MS₆ = 2M₂ + S₂\n///\n/// V = 6T - 4s + 4h\n/// u = 4ξ - 4ν\n/// f = f(M₂)²\nclass _2MS6 : public Wave {\n public:\n  _2MS6()\n      : Wave(k2MS6, 6, -4, 4, 0, 0, 0, 0, 4, -4, 0, 0, kShortPeriod,\n             &AstronomicAngle::f_m22) {}\n};\n\n/// 2MK₆ = 2M₂ + K₂\n///\n/// V = 6T - 4s + 6h\n/// u = 4ξ - 4ν - 2ν''\n/// f = f(M₂)² × f(K₂)\nclass _2MK6 : public Wave {\n public:\n  _2MK6()\n      : Wave(k2MK6, 6, -4, 6, 0, 0, 0, 0, 4, -4, 0, -2, kShortPeriod,\n             &AstronomicAngle::f_m23_k2) {}\n};\n\n/// 2SM₆ = 2S₂ + M₂\n///\n/// V = 6T - 2s + 2h\n/// u = 2ξ - 2ν\n/// f = f(M₂)\nclass _2SM6 : public Wave {\n public:\n  _2SM6()\n      : Wave(k2SM6, 6, -2, 2, 0, 0, 0, 0, 2, -2, 0, 0, kShortPeriod,\n             &AstronomicAngle::f_m2) {}\n};\n\n/// MSK₆ = M₂ + K₂ + S₂\n///\n/// V = 6T - 2s + 4h\n/// u = 2ξ - 2ν - 2ν''\n/// f = f(M₂) × f(K₂)\nclass MSK6 : public Wave {\n public:\n  MSK6()\n      : Wave(kMSK6, 6, -2, 4, 0, 0, 0, 0, 2, -2, -2, 0, kShortPeriod,\n             &AstronomicAngle::f_m2_k2) {}\n};\n\n/// S₆ = 3S₂\n///\n/// V = 6T\n/// u = 0\n/// f = 1\nclass S6 : public Wave {\n public:\n  S6()\n      : Wave(kS6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, kShortPeriod,\n             &AstronomicAngle::f_1) {}\n};\n\n/// M₈ = 4M₂\n///\n/// V = 8T - 8s + 8h\n/// u = 8ξ - 8ν\n/// f = f(M₂)⁴\nclass M8 : public Wave {\n public:\n  M8()\n      : Wave(kM8, 8, -8, 8, 0, 0, 0, 0, 8, -8, 0, 0, kShortPeriod,\n             &AstronomicAngle::f_m24) {}\n};\n\n/// MSf = M₂ - S₂\n///\n/// V = 2s - 2h\n/// u = 2ξ - 2ν\n/// f = f(M₂) * f(S2) = f(M₂)\n///\n/// @warning Same frequency as MSf LP : 2s -2h\nclass MSf : public Wave {\n public:\n  MSf()\n      : Wave(kMSf, 0, 2, -2, 0, 0, 0, 0, 2, -2, 0, 0, kLongPeriod,\n             &AstronomicAngle::f_m2) {}\n};\n\n/// Properties of tide waves computed\nclass WaveTable {\n private:\n  std::vector<std::shared_ptr<Wave>> waves_{};\n\n  /// Compute nodal corrections from SCHUREMAN (1958).\n  ///\n  /// Indexes used in this routine are internal to the code\n  /// and corresponds to the \"original\" ondes.dat file.\n  ///\n  /// @param a Astronomic angle\n  void nodal_a(const AstronomicAngle& a) {\n    for (auto& item : waves_) {\n      item->nodal_a(a);\n    }\n  }\n\n  /// Compute nodal corrections from SCHUREMAN (1958).\n  ///\n  /// Indexes used in this routine are internal to the code and corresponds to\n  /// the \"original\" ondes.dat file.\n  ///\n  /// @param a Astronomic angle\n  void nodal_g(const AstronomicAngle& a) {\n    for (auto& item : waves_) {\n      item->nodal_g(a);\n    }\n  }\n\n public:\n  /// Default constructor\n  WaveTable(const std::vector<std::string>& waves = {});\n\n  /// Gets the tidal waves known\n  static std::vector<std::string> known_constituents();\n\n  /// Compute nodal corrections.\n  ///\n  /// @param epoch Desired UTC time expressed in number of seconds elapsed since\n  /// 1970-01-01T00:00:00\n  /// @return the astronomic angle, indicating the date on which the tide is to\n  /// be calculated.\n  AstronomicAngle compute_nodal_corrections(const double epoch) {\n    auto angles = AstronomicAngle(epoch);\n\n    nodal_a(angles);\n    nodal_g(angles);\n\n    return angles;\n  }\n\n  /// Gets the wave properties\n  std::shared_ptr<Wave> wave(const Wave::Ident ident) const {\n    auto it = find(ident);\n    return it != end() ? *it : nullptr;\n  }\n\n  /// Gets the wave properties\n  const std::shared_ptr<Wave>& operator[](const size_t index) const {\n    return waves_.at(index);\n  }\n\n  /// Gets the wave properties\n  std::shared_ptr<Wave> wave(const std::string& ident) const {\n    auto it = find(ident);\n    return it != end() ? *it : nullptr;\n  }\n\n  /// Gets the wave properties\n  std::shared_ptr<Wave>& wave(const Wave::Ident ident) { return waves_[ident]; }\n\n  /// Returns an iterator to the beginning of the wave table\n  std::vector<std::shared_ptr<Wave>>::const_iterator begin() const {\n    return waves_.begin();\n  }\n\n  /// Returns an iterator to the end of the wave table\n  std::vector<std::shared_ptr<Wave>>::const_iterator end() const {\n    return waves_.end();\n  }\n\n  /// Returns an iterator to the beginning of the wave table\n  std::vector<std::shared_ptr<Wave>>::iterator begin() {\n    return waves_.begin();\n  }\n\n  /// Returns an iterator to the end of the wave table\n  std::vector<std::shared_ptr<Wave>>::iterator end() { return waves_.end(); }\n\n  /// Searches the properties of a wave from its name.\n  std::vector<std::shared_ptr<Wave>>::const_iterator find(\n      const std::string& name) const {\n    for (auto it = begin(); it != end(); ++it) {\n      if (name == (*it)->name()) {\n        return it;\n      }\n    }\n    return end();\n  }\n\n  /// Searches the properties of a wave from its identifier.\n  std::vector<std::shared_ptr<Wave>>::const_iterator find(\n      const Wave::Ident& ident) const {\n    for (auto it = begin(); it != end(); ++it) {\n      if (ident == (*it)->ident()) {\n        return it;\n      }\n    }\n    return end();\n  }\n\n  /// Returns the size of the table\n  size_t size() const { return waves_.size(); }\n\n  static Eigen::VectorXcd harmonic_analysis(\n      const Eigen::Ref<const Eigen::VectorXd>& h,\n      const Eigen::Ref<const Eigen::MatrixXd>& f,\n      const Eigen::Ref<const Eigen::MatrixXd>& vu);\n};", "meta": {"hexsha": "cbcb5f3f2ebb5df30839a3eca2138b4eefccb901", "size": 26151, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/pytide/core/wave.hpp", "max_stars_repo_name": "jerabaul29/pangeo-pytide", "max_stars_repo_head_hexsha": "d07169f2aad2ba60f781f04887cdef01e0825449", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/pytide/core/wave.hpp", "max_issues_repo_name": "jerabaul29/pangeo-pytide", "max_issues_repo_head_hexsha": "d07169f2aad2ba60f781f04887cdef01e0825449", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/pytide/core/wave.hpp", "max_forks_repo_name": "jerabaul29/pangeo-pytide", "max_forks_repo_head_hexsha": "d07169f2aad2ba60f781f04887cdef01e0825449", "max_forks_repo_licenses": ["BSD-3-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.237244898, "max_line_length": 80, "alphanum_fraction": 0.5012810218, "num_tokens": 10902, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6477982043529715, "lm_q2_score": 0.5039061705290805, "lm_q1q2_score": 0.3264295124311206}}
{"text": "/*\n\tAuthor: Seyed-Vahid Sanei-Mehri\n\tContact: vahid.sanei@gmail.com or vas@iastate.edu\n\n\tHere is the source code for ** BUTTERFLY COUNTING IN BIPARTITE NETWORKS **\n\tOn Arxiv: Sanei-Mehri, Seyed-Vahid, Erdem Saryuce, and Srikanta Tirthapura. \"Butterfly Counting in Bipartite Networks.\" arXiv preprint arXiv:1801.00338 (2017).\n\n\tAbstract:\n\t\tWe consider the problem of counting motifs in bipartite affiliation networks, such as author-paper, user-product, and actor-movie relations. \n\t\tWe focus on counting the number of occurrences of a \"butterfly\", a complete 2�2 biclique, the simplest cohesive higher-order structure in a bipartite graph. \n\t\tOur main contribution is a suite of randomized algorithms that can quickly approximate the number of butterflies in a graph with a provable guarantee on accuracy. \n\t\tAn experimental evaluation on large real-world networks shows that our algorithms return accurate estimates within a few seconds, even for networks with trillions of \n\t\tbutterflies and hundreds of millions of edges.\n*/\n\n#define _CRT_SECURE_NO_WARNINGS\n\n#include <cstdlib>\n#include <cstring>\n#include <ctime>\n#include <cassert>\n\n#include <iostream>\n#include <string>\n#include <algorithm>\n#include <numeric>\n#include <set>\n#include <unordered_set>\n#include <map>\n#include <sstream>\n#include <random>\n//#include <boost/random/mersenne_twister.hpp>\n//#include <boost/random/uniform_int_distribution.hpp>\n//#include <boost/random/uniform_real_distribution.hpp>\n//#include <boost/random/random_device.hpp>\n\nusing namespace std;\n//using namespace boost::random;\n\n#define SZ(x) ((int)x.size())\n#define ll long long\n#define ull unsigned long long\n#define ld long double\n#define eps 1e-11\n#define max(x, y) ((x)>(y)?(x):(y))\n#define min(x, y) ((x)<(y)?(x):(y))\n\nconst int ITER_VER = 2200;\nconst ll shift = 1000 * 1000 * 1000LL;\nconst double TIME_LIMIT = 20;\nconst int N_WEDGE_ITERATIONS = 2 * 1000 * 1000 * 10;\nconst int ITERATIONS_SAMPLING = 5;\nconst int N_SPARSIFICATION_ITERATIONS = 5;\nconst int TIME_LIMIT_SPARSIFICATION = 10000; // !half an hour\nconst int N_FAST_EDGE_BFC_ITERATIONS = 2100; // used for fast edge sampling\nconst int N_FAST_WEDGE_ITERATIONS = 50; // used for fast wedge sampling\n\nchar input_address[2000], output_address[2000];\n\nset<pair<int, int> > edges;\nvector<pair<int, int> > list_of_edges;\nmap<int, int> vertices[2];\nvector<int> index_map;\nvector<int> vertices_in_left;\nvector<int> vertices_in_right;\nvector<vector<int> > adj;\nvector<vector<int> > sampled_adj_list;\nvector<bool> visited;\nvector<int> list_of_vertices;\nvector<int> vertex_counter;\n\nll n_vertices;\nll n_edges;\nld exact_n_bf;\nll n_wedge_in_partition[2];\nll largest_index_in_partition[2];\n\nvector<int> clr;\nvector<int> hashmap_C;\nvector<ll> sum_wedges;\nvector<ll> sum_deg_neighbors;\nvector<int> aux_array_two_neighboorhood;\n\nvoid clear_everything() {\n    largest_index_in_partition[0] = largest_index_in_partition[1] = 0;\n    n_vertices = 0;\n    n_edges = 0;\n    edges.clear();\n    vertices[0].clear();\n    vertices[1].clear();\n    index_map.clear();\n    vertices_in_left.clear();\n    vertices_in_right.clear();\n    adj.clear();\n    sampled_adj_list.clear();\n    visited.clear();\n    list_of_edges.clear();\n    vertex_counter.clear();\n    clr.clear();\n    hashmap_C.clear();\n    sum_wedges.clear();\n    sum_deg_neighbors.clear();\n    aux_array_two_neighboorhood.clear();\n}\n\nvoid resize_all() {\n    clr.resize(n_vertices);\n    hashmap_C.resize(n_vertices);\n    aux_array_two_neighboorhood.resize(n_vertices);\n    sum_wedges.resize(n_vertices);\n    visited.resize(n_vertices);\n    index_map.resize(n_vertices);\n    sum_deg_neighbors.resize(n_vertices);\n}\n\n// ------------- Read the graph ---------------------\nvoid add_vertex(int A, int side) {\n    if (vertices[side].find(A) == vertices[side].end()) {\n        if (side == 0) vertices_in_left.push_back(A);\n        else vertices_in_right.push_back(A);\n        vertices[side][A] = 1;\n    }\n}\n\nvoid get_index(int &A, int side) {\n    if (vertices[side].find(A) == vertices[side].end()) {\n        vertices[side][A] = largest_index_in_partition[side]++;\n    }\n    A = vertices[side][A];\n}\n\nvoid add_edge(int &A, int &B) {\n    add_vertex(A, 0);\n    add_vertex(B, 1);\n    if (edges.find(make_pair(A, B)) == edges.end()) {\n        edges.insert(make_pair(A, B));\n        n_edges++;\n    }\n}\n\nbool all_num(string &s) {\n    for (int i = 0; i < SZ(s); i++) if ((s[i] >= '0' && s[i] <= '9') == false) return false;\n    return true;\n}\n\nvoid get_graph() {\n    freopen(input_address, \"r\", stdin);\n    string s;\n    cin.clear();\n    while (getline(cin, s)) {\n        stringstream ss;\n        ss << s;\n        vector<string> vec_str;\n        for (string z; ss >> z; vec_str.push_back(z));\n        if (SZ(vec_str) >= 2) {\n            bool is_all_num = true;\n            for (int i = 0; i < min (2, SZ(vec_str)); i++) is_all_num &= all_num(vec_str[i]);\n            if (is_all_num) {\n                int A, B;\n                ss.clear();\n                ss << vec_str[0];\n                ss >> A;\n                ss.clear();\n                ss << vec_str[1];\n                ss >> B;\n                add_edge(A, B);\n            }\n        }\n    }\n    vertices[0].clear();\n    vertices[1].clear();\n    largest_index_in_partition[0] = 0;\n    largest_index_in_partition[1] = SZ(vertices_in_left);\n    n_vertices = SZ(vertices_in_left) + SZ(vertices_in_right);\n    adj.resize(n_vertices, vector<int>());\n    for (auto edge : edges) {\n        int A = edge.first;\n        int B = edge.second;\n        get_index(A, 0);\n        get_index(B, 1);\n        adj[A].push_back(B);\n        adj[B].push_back(A);\n        list_of_edges.push_back(make_pair(A, B));\n    }\n    resize_all();\n\n    n_wedge_in_partition[0] = 0;\n    for (int i = 0; i < largest_index_in_partition[0]; i++) {\n        n_wedge_in_partition[0] += (((ll) SZ(adj[i])) * (SZ(adj[i]) - 1)) >> 1;\n    }\n    n_wedge_in_partition[1] = 0;\n    for (int i = largest_index_in_partition[0]; i < largest_index_in_partition[1]; i++) {\n        n_wedge_in_partition[1] += ((ll) SZ(adj[i]) * (SZ(adj[i]) - 1)) >> 1;\n    }\n    for (int i = 0; i < n_vertices; i++) {\n        sort(adj[i].begin(), adj[i].end());\n        sum_deg_neighbors[i] = 0;\n        for (auto neighbor : adj[i]) {\n            sum_deg_neighbors[i] += SZ(adj[neighbor]);\n        }\n    }\n    cerr << \" for test # edges :: \" << SZ(list_of_edges) << \" left :: \" << SZ(vertices_in_left) << \" right :: \"\n         << SZ(vertices_in_right) << endl;\n    sort(list_of_edges.begin(), list_of_edges.end());\n    fclose(stdin);\n}\n// ------------- Read the graph ---------------------\n\nint exact_neighbor_intersections(int a, int b) {\n    int common = 0;\n    if (SZ(adj[a]) > SZ(adj[b])) swap(a, b);\n    unordered_set<int> set;\n    for (int i = 0; i < SZ(adj[a]); i++) set.insert(adj[a][i]);\n    for (int j = 0; j < SZ(adj[b]); j++) {\n        if (set.find(adj[b][j]) != set.end())\n            common++;\n    }\n    return common;\n}\n\ndouble fast_neighbor_intersections(int a, int b) {\n    if (SZ(adj[a]) > SZ(adj[b])) swap(a, b);\n    random_device rdw;\n    mt19937 genedg(rdw());\n    uniform_int_distribution<int> dis(0, SZ(adj[a]) - 1);\n    ld sum_wedges = 0;\n    int n_iterations = N_WEDGE_ITERATIONS;\n    for (int i = 0; i < n_iterations; i++) {\n        int c = adj[a][dis(genedg)];\n        if (binary_search(adj[b].begin(), adj[b].end(), c)) {\n            sum_wedges += SZ(adj[a]);\n        }\n    }\n    sum_wedges /= n_iterations;\n    return sum_wedges;\n}\n\nll exact_butterfly_counting(vector<vector<int> > &graph) {\n    int side = n_wedge_in_partition[0] < n_wedge_in_partition[1];\n    ld res = 0;\n    for (int vertex = side == 0 ? 0 : SZ(vertices_in_left); vertex < largest_index_in_partition[side]; vertex++) {\n        int idx = 0;\n        for (int j = 0; j < SZ(graph[vertex]); j++) {\n            int neighbor = graph[vertex][j];\n            for (int k = 0; k < SZ(graph[neighbor]); k++) {\n                int two_hop_neighborhood = graph[neighbor][k];\n                if (vertex > two_hop_neighborhood) {\n                    res += hashmap_C[two_hop_neighborhood];\n                    hashmap_C[two_hop_neighborhood]++;\n                    if (hashmap_C[two_hop_neighborhood] == 1)\n                        aux_array_two_neighboorhood[idx++] = two_hop_neighborhood;\n                } else break;\n            }\n        }\n        for (int j = 0; j < idx; j++) {\n            hashmap_C[aux_array_two_neighboorhood[j]] = 0;\n        }\n    }\n    return res;\n}\n\nll compute_n_wedges() {\n    ll wedges = 0;\n    for (int i = 0; i < n_vertices; i++) {\n        wedges += ((ll) (SZ(adj[i])) * ((ll) SZ(adj[i]) - 1)) >> 1;\n        sum_wedges[i] = wedges;\n    }\n    return wedges;\n}\n\n\nld error_percent(ld &res) {\n    if (exact_n_bf == 0) return 0;\n    ld error = (res - exact_n_bf) / exact_n_bf * 100.0;\n    if (error < 0) error *= -1.0;\n    return error;\n}\n\nld wedge_sampling(uniform_int_distribution<ll> &dis, mt19937_64 &eng, int &iter, int &alpha, ll &n_wedges) {\n    ld res_wedge_samp = 0;\n    for (; iter < alpha; iter++) {\n        int l1, l2;\n        ll ran = dis(eng);\n        int lo = 0, hi = n_vertices - 1;\n        while (lo < hi) {\n            int mid = (lo + hi) >> 1;\n            if (sum_wedges[mid] < ran) {\n                lo = mid + 1;\n            } else {\n                hi = mid;\n            }\n        }\n        random_device rdev_wedge_low;\n        mt19937 eng_wedge(rdev_wedge_low());\n        uniform_int_distribution<int> dis1(0, SZ(adj[lo]) - 1);\n        l1 = dis1(eng_wedge);\n        uniform_int_distribution<int> dis2(0, SZ(adj[lo]) - 2);\n        l2 = dis2(eng_wedge);\n        if (l2 >= l1) l2++;\n        l1 = adj[lo][l1];\n        l2 = adj[lo][l2];\n        res_wedge_samp += exact_neighbor_intersections(l1, l2) - 1;\n    }\n    return res_wedge_samp;\n}\n\nld fast_wedge_sampling(uniform_int_distribution<ll> &dis, mt19937_64 &gen, int &iter, int &alpha, ll &n_wedges) {\n    ld res_fast_wedge_samp = 0;\n    for (; iter < alpha; iter++) {\n        int l1, l2;\n        ll ran = dis(gen);\n        int lo = 0, hi = n_vertices - 1;\n        while (lo < hi) {\n            int mid = (lo + hi) >> 1;\n            if (sum_wedges[mid] < ran) {\n                lo = mid + 1;\n            } else {\n                hi = mid;\n            }\n        }\n        random_device rdev_wedge_low;\n        mt19937 eng_fast_wedge(rdev_wedge_low());\n        uniform_int_distribution<int> dis1(0, SZ(adj[lo]) - 1);\n        l1 = dis1(eng_fast_wedge);\n        uniform_int_distribution<int> dis2(0, SZ(adj[lo]) - 2);\n        l2 = dis2(eng_fast_wedge);\n        if (l2 >= l1) l2++;\n        l1 = adj[lo][l1];\n        l2 = adj[lo][l2];\n        res_fast_wedge_samp += fast_neighbor_intersections(l1, l2);\n    }\n    return res_fast_wedge_samp;\n}\n\nld colorful_sparsification(int num_clr) {\n    random_device rdev_colorful;\n    mt19937 eng_colorful(rdev_colorful());\n    uniform_int_distribution<int> dis(0, num_clr - 1);\n\n    for (int i = 0; i < n_vertices; i++) {\n        clr[i] = dis(eng_colorful);\n    }\n    sampled_adj_list.resize(n_vertices, (vector<int>()));\n\n    n_wedge_in_partition[0] = n_wedge_in_partition[1] = 0;\n    for (auto edge : edges) {\n        int A = edge.first;\n        int B = edge.second;\n        if (A > B && clr[A] == clr[B]) {\n            sampled_adj_list[A].push_back(B);\n            sampled_adj_list[B].push_back(A);\n            n_wedge_in_partition[0] += 2 * SZ(sampled_adj_list[A]) - 1;\n            n_wedge_in_partition[1] += 2 * SZ(sampled_adj_list[B]) - 1;\n        }\n    }\n    ld beta = exact_butterfly_counting(sampled_adj_list);\n    return beta * num_clr * num_clr * num_clr;\n}\n\nld edge_saprsification(double prob) {\n    prob = prob > 1.0 ? 1.0 : prob;\n    random_device rdev_edge_sprs;\n    mt19937 eng_edg_sprs(rdev_edge_sprs());\n    uniform_real_distribution<double> dis(0.0, 1.0);\n\n    sampled_adj_list.clear();\n    sampled_adj_list.resize(n_vertices, (vector<int>()));\n\n    n_wedge_in_partition[0] = n_wedge_in_partition[1] = 0;\n    for (auto edge : edges) {\n        int A = edge.first;\n        int B = edge.second;\n        double coin = dis(eng_edg_sprs);\n        if (coin <= prob || abs(coin - prob) <= eps) {\n            sampled_adj_list[A].push_back(B);\n            sampled_adj_list[B].push_back(A);\n            n_wedge_in_partition[0] += 2 * SZ(sampled_adj_list[A]) - 1;\n            n_wedge_in_partition[1] += 2 * SZ(sampled_adj_list[B]) - 1;\n        }\n    }\n    ld beta = exact_butterfly_counting(sampled_adj_list);\n    return (ld) beta / (prob * prob * prob * prob);\n}\n\nld exact_BFC_per_edge(int a, int b) {\n    ld bfc_per_edge = 0;\n    for (int k = 0; k < SZ(adj[a]); k++) {\n        int c = adj[a][k];\n        if (c != b) {\n            bfc_per_edge += exact_neighbor_intersections(c, b) - 1;\n        }\n    }\n    return bfc_per_edge;\n}\n\nld fast_exact_BFC_per_edge(int a, int b) {\n    for (int i = 0; i < SZ(adj[a]); i++) {\n        int neighbor = adj[a][i];\n        if (neighbor != b) {\n            for (int j = 0; j < SZ(adj[neighbor]); j++) {\n                int two_hop_neighborhood = adj[neighbor][j];\n                if (two_hop_neighborhood != a) {\n                    index_map[two_hop_neighborhood]++;\n                }\n            }\n        }\n    }\n    ld bfc_per_edge = 0;\n    for (int i = 0; i < SZ(adj[b]); i++) {\n        int neighbor = adj[b][i];\n        bfc_per_edge += index_map[neighbor];\n    }\n    for (int i = 0; i < SZ(adj[a]); i++) {\n        int neighbor = adj[a][i];\n        for (int j = 0; j < SZ(adj[neighbor]); j++) {\n            index_map[adj[neighbor][j]] = 0;\n        }\n    }\n    return bfc_per_edge;\n}\n\nrandom_device rd_edge;\nmt19937_64 eng_ran_bfc_per_edge(rd_edge());\n\nld randomized_BFC_per_edge(int a, int b) {\n    if (SZ(adj[a]) <= 1 || SZ(adj[b]) <= 1) {\n        return 0;\n    }\n    uniform_int_distribution<int> dis_a(0, SZ(adj[a]) - 1);\n    uniform_int_distribution<int> dis_b(0, SZ(adj[b]) - 1);\n    ld res_ran_bfc_per_edge = 0;\n    for (int i = 0; i < N_FAST_EDGE_BFC_ITERATIONS; i++) {\n        int x = adj[a][dis_a(eng_ran_bfc_per_edge)];\n        int y = adj[b][dis_b(eng_ran_bfc_per_edge)];\n        if (x != b && y != a && binary_search(adj[x].begin(), adj[x].end(), y)) {\n            res_ran_bfc_per_edge += ((ld) SZ(adj[a])) * ((ld) SZ(adj[b]));\n        }\n    }\n    res_ran_bfc_per_edge /= N_FAST_EDGE_BFC_ITERATIONS;\n    return res_ran_bfc_per_edge;\n}\n\nld exact_bfc_per_vertex(int vertex) {\n    ld res = 0;\n    for (int i = 0; i < SZ(adj[vertex]); i++) {\n        int neighbor = adj[vertex][i];\n        for (int j = 0; j < SZ(adj[neighbor]); j++) {\n            int two_hop_neighborhood = adj[neighbor][j];\n            if (two_hop_neighborhood != vertex) {\n                res += index_map[two_hop_neighborhood];\n                index_map[two_hop_neighborhood]++;\n            }\n        }\n    }\n    for (int i = 0; i < SZ(adj[vertex]); i++) {\n        int neighbor = adj[vertex][i];\n        for (int j = 0; j < SZ(adj[neighbor]); j++) {\n            index_map[adj[neighbor][j]] = 0;\n        }\n    }\n    return res;\n}\n\nld edge_sampling(mt19937 &eng, uniform_int_distribution<int> &dis, int &iter, int &alpha) {\n    ld ans = 0;\n    for (; iter < alpha; iter++) {\n        int random_edge = dis(eng);\n        int a = list_of_edges[random_edge].first;\n        int b = list_of_edges[random_edge].second;\n        ans += fast_exact_BFC_per_edge(a, b);\n    }\n    return ans;\n}\n\nld fast_edge_sampling(mt19937 &eng, uniform_int_distribution<int> &dis, int &iter, int &alpha) {\n    ld res = 0;\n    for (; iter < alpha; iter++) {\n        int random_edge = dis(eng);\n        int a = list_of_edges[random_edge].first;\n        int b = list_of_edges[random_edge].second;\n        if (sum_deg_neighbors[a] > sum_deg_neighbors[b]) {\n            swap(a, b);\n        }\n        if (SZ(adj[b]) + sum_deg_neighbors[a] * 2 > N_FAST_EDGE_BFC_ITERATIONS)\n            res += randomized_BFC_per_edge(a, b);\n        else\n            res += fast_exact_BFC_per_edge(a, b);\n    }\n    return res;\n}\n\nld vertex_sampling(uniform_int_distribution<ll> &dis, mt19937_64 &eng, int &mx, int &iter, int &alpha) {\n    ld res = 0;\n    for (; iter < alpha; iter++) {\n        int random_vertex = dis(eng);\n        res += exact_bfc_per_vertex(random_vertex);\n    }\n    return res;\n}\n\nvoid edge_sparsfication_time_tracker() {\n    for (double prob = 0.012; prob < 1.0; prob *= 2) {\n        vector<pair<ld, pair<ld, ld> > > aux_res;\n        for (int i = 0; i < N_SPARSIFICATION_ITERATIONS; i++) {\n            double beg_clock = clock();\n            ld res = edge_saprsification(prob);\n            double end_clock = clock();\n            ld error = error_percent(res);\n            double elpased_time = double(end_clock - beg_clock) / CLOCKS_PER_SEC;\n            aux_res.push_back(make_pair(error, make_pair(elpased_time, res)));\n        }\n\n        sort(aux_res.begin(), aux_res.end());\n        double elpased_time = aux_res[N_SPARSIFICATION_ITERATIONS / 2].second.first;\n        ld Er = aux_res[N_SPARSIFICATION_ITERATIONS / 2].first;\n\n        if (prob >= 1) {\n            cout << elpased_time << \" \" << 1 << \" \" << 0 << endl;\n            if (elpased_time < TIME_LIMIT_SPARSIFICATION) {\n                cout << TIME_LIMIT << \" \" << 1 << \" \" << 0 << endl;\n            } else {\n                cout << elpased_time << \" \" << 1 << \" \" << 0 << endl;\n            }\n            break;\n        } else {\n            cout << elpased_time << \" \" << prob << \" \" << Er << \" \" << endl;\n        }\n        if (elpased_time >= TIME_LIMIT_SPARSIFICATION)\n            break;\n    }\n}\n\nvoid coloful_sparsification_time_tracker() {\n    for (int num_clr = 10000;; num_clr /= 2.0) {\n        double prob = 1. / num_clr;\n        vector<pair<ld, pair<ld, ld> > > aux_ans;\n        for (int i = 0; i < N_SPARSIFICATION_ITERATIONS; i++) {\n            double beg = clock();\n            ld res = colorful_sparsification(num_clr);\n            double prob = 1. / num_clr;\n            double end = clock();\n            ld error = error_percent(res);\n            double elapsed_time = double(end - beg) / CLOCKS_PER_SEC;\n            aux_ans.push_back(make_pair(error, make_pair(elapsed_time, res)));\n        }\n        sort(aux_ans.begin(), aux_ans.end());\n        double elapsed_time = aux_ans[N_SPARSIFICATION_ITERATIONS / 2].second.first;\n        ld error = aux_ans[N_SPARSIFICATION_ITERATIONS / 2].first;\n        if (prob >= 1) {\n            cout << elapsed_time << \" \" << 1 << \" \" << 0 << endl;\n            if (elapsed_time < TIME_LIMIT_SPARSIFICATION)\n                cout << TIME_LIMIT << \" \" << 1 << \" \" << 0 << endl;\n            else\n                cout << elapsed_time << \" \" << 1 << \" \" << 0 << endl;\n\n            break;\n        } else\n            cout << elapsed_time << \" \" << prob << \" \" << error << endl;\n        if (elapsed_time >= TIME_LIMIT_SPARSIFICATION)\n            break;\n    }\n}\n\nvoid edge_sampling_time_tracker() {\n    random_device rd;\n    mt19937 eng(rd());\n    uniform_int_distribution<int> dis(0, n_edges - 1);\n    double elapsed_time = 0;\n    ld res = 0;\n    vector<ld> total_res;\n    for (int alpha = 10, iter = 0;; alpha += 10) {\n        double cur_elapsed_time = 0;\n        vector<pair<ld, pair<ld, ld> > > aux_res;\n        double res_from_previous_iterations = 0;\n        for (int i = 0; i < SZ(total_res); i++) {\n            res_from_previous_iterations += (total_res[i] / 4.0) / alpha;\n        }\n        int previous_iteration = iter;\n        for (int k = 0; k < ITERATIONS_SAMPLING; k++) { // run the algorithm ITERATION times\n            iter = previous_iteration;\n            double cur_beg_clock = clock();\n            res = edge_sampling(eng, dis, iter, alpha);\n            double cur_end_clock = clock();\n            cur_elapsed_time = double(cur_end_clock - cur_beg_clock) / CLOCKS_PER_SEC;\n            ld ans = (res / 4.0) / alpha;\n            ans += res_from_previous_iterations;\n            ans *= n_edges;\n            ld error = error_percent(ans);\n            aux_res.push_back(make_pair(error, make_pair(cur_elapsed_time, res)));\n        }\n        sort(aux_res.begin(), aux_res.end()); // take the median\n        cur_elapsed_time = aux_res[ITERATIONS_SAMPLING / 2].second.first;\n        ld error = aux_res[ITERATIONS_SAMPLING / 2].first;\n        elapsed_time += cur_elapsed_time;\n\n        total_res.push_back(aux_res[ITERATIONS_SAMPLING / 2].second.second);\n        cout << elapsed_time << \" \" << iter << \" \" << error << endl;\n        if (elapsed_time >= TIME_LIMIT) {\n            cout << alpha << endl;\n            break;\n        }\n    }\n}\n\nvoid fast_edge_sampling_time_tracker() {\n    random_device rd;\n    mt19937 genedg(rd());\n    uniform_int_distribution<int> dis(0, n_edges - 1);\n    double elapsed_time = 0;\n    ld res = 0;\n    vector<ld> total_res;\n    for (int alpha = 1000, iter = 0;; alpha += 1000) {\n        double cur_elapsed_time = 0;\n        vector<pair<ld, pair<ld, ld> > > aux_res;\n        double res_from_previous_iterations = 0;\n        for (int i = 0; i < SZ(total_res); i++) {\n            res_from_previous_iterations += (total_res[i] / 4.0) / alpha;\n        }\n        int previous_iterations = iter;\n        for (int k = 0; k < ITERATIONS_SAMPLING; k++) { // run the algorithm ITERATION times\n            iter = previous_iterations;\n            double cur_beg_clock = clock();\n            res = fast_edge_sampling(genedg, dis, iter, alpha);\n            double cur_end_clock = clock();\n            double cur_elapsed_time = double(cur_end_clock - cur_beg_clock) / CLOCKS_PER_SEC;\n            ld ans = (res / 4.0) / (alpha);\n            ans += res_from_previous_iterations;\n            ans *= n_edges;\n            ld error = error_percent(ans);\n            aux_res.push_back(make_pair(error, make_pair(cur_elapsed_time, res)));\n        }\n        sort(aux_res.begin(), aux_res.end()); // take the median\n        cur_elapsed_time = aux_res[ITERATIONS_SAMPLING / 2].second.first;\n        ld error = aux_res[ITERATIONS_SAMPLING / 2].first;\n        elapsed_time += cur_elapsed_time;\n        total_res.push_back(aux_res[ITERATIONS_SAMPLING / 2].second.second);\n\n        cout << elapsed_time << \" \" << iter << \" \" << error << endl;\n        if (elapsed_time >= TIME_LIMIT) {\n            cout << alpha << endl;\n            break;\n        }\n    }\n}\n\nvoid vertex_sampling_time_tracker() {\n    vector<int> cnt_vertex(n_vertices);\n    random_device rd;\n    mt19937_64 eng(rd());\n    uniform_int_distribution<ll> dis(0, n_vertices - 1);\n    double elapsed_time = 0;\n    ld res = 0;\n    vector<ld> total_res;\n    int mx = 0;\n    for (int alpha = 10, iter = 0;; alpha += 10) {\n        double cur_elaped_time = 0;\n        vector<pair<ld, pair<ld, ld> > > aux_res;\n        double res_from_previous_iterations = 0;\n        for (int I = 0; I < SZ(total_res); I++) {\n            res_from_previous_iterations += (total_res[I] / 4.0) / alpha;\n        }\n        int previous_iterations = iter;\n        for (int k = 0; k < ITERATIONS_SAMPLING; k++) { // run the algorithm ITERATION times\n            iter = previous_iterations;\n            double cur_beg_clock = clock();\n            res = vertex_sampling(dis, eng, mx, iter, alpha);\n            double cur_end_clock = clock();\n            double cur_elapsed_time = double(cur_end_clock - cur_beg_clock) / CLOCKS_PER_SEC;\n            ld ans = (res / 4.0) / alpha;\n            ans += res_from_previous_iterations;\n            ans *= n_vertices;\n            ld error = error_percent(ans);\n            aux_res.push_back(make_pair(error, make_pair(cur_elaped_time, res)));\n        }\n        sort(aux_res.begin(), aux_res.end()); // take the median\n        cur_elaped_time = aux_res[ITERATIONS_SAMPLING / 2].second.first;\n        ld error = aux_res[ITERATIONS_SAMPLING / 2].first;\n        elapsed_time += cur_elaped_time;\n        total_res.push_back(aux_res[ITERATIONS_SAMPLING / 2].second.second);\n\n        cout << elapsed_time << \" \" << iter << \" \" << aux_res[ITERATIONS_SAMPLING / 2].first << endl;\n        if (elapsed_time >= TIME_LIMIT) {\n            cout << alpha << endl;\n            break;\n        }\n    }\n}\n\nvoid wedge_sampling_time_tracker() {\n    clock_t beg_clock_n_wedge = clock();\n    ll n_wedges = compute_n_wedges();\n    clock_t end_clock_n_wedge = clock();\n    double time_n_wedges = double(end_clock_n_wedge - beg_clock_n_wedge) / CLOCKS_PER_SEC;\n    random_device rd;\n    mt19937_64 eng(rd());\n    uniform_int_distribution<ll> dis(1, n_wedges);\n    double total_elapsed_time = 0;\n    ld res = 0;\n    ld total = 0;\n    vector<ld> total_res;\n    for (int alpha = 1000, iter = 0;; alpha += 5000) {\n        vector<pair<ld, pair<ld, ld> > > aux_res;\n        ld res_sum_from_previous_results = 0;\n        for (int i = 0; i < SZ(total_res); i++) {\n            res_sum_from_previous_results += (total_res[i] / 4.0) / alpha;\n        }\n        ld cur_res = 0;\n        int pre_iteration = iter;\n        for (int k = 0; k < ITERATIONS_SAMPLING; k++) { // run the algorithm ITERATION times\n            iter = pre_iteration;\n            double beg = clock();\n            res = wedge_sampling(dis, eng, iter, alpha, n_wedges);\n            double end = clock();\n            double cur_elapsed_time = double(end - beg) / CLOCKS_PER_SEC;\n            cur_res = (res / 4.0) / alpha;\n            cur_res += res_sum_from_previous_results;\n            cur_res *= (ld) n_wedges;\n            ld error = error_percent(cur_res);\n            aux_res.push_back(make_pair(error, make_pair(cur_elapsed_time, res)));\n        }\n        sort(aux_res.begin(), aux_res.end()); // take the median\n        double cur_elapsed_time = aux_res[ITERATIONS_SAMPLING / 2].second.first;\n        ld error = aux_res[ITERATIONS_SAMPLING / 2].first;\n        total_elapsed_time += cur_elapsed_time;\n        total_res.push_back(aux_res[ITERATIONS_SAMPLING / 2].second.second);\n\n        cout << cur_elapsed_time + time_n_wedges << \" \" << iter << \" \" << error << endl;\n        if (total_elapsed_time + time_n_wedges >= TIME_LIMIT) {\n            cout << \"iterations: \" << alpha << endl;\n            break;\n        }\n    }\n    return;\n}\n\nvoid fast_wedge_sampling_time_tracker() {\n    clock_t beg_clock_n_wedge = clock();\n    ll n_wedges = compute_n_wedges();\n    clock_t end_clock_n_wedge = clock();\n    double time_n_wedges = double(end_clock_n_wedge - beg_clock_n_wedge) / CLOCKS_PER_SEC;\n    random_device rd;\n    mt19937_64 eng(rd());\n    uniform_int_distribution<ll> dis(1, n_wedges);\n    double total_elapsed_time = 0;\n    ld res = 0;\n    ld total = 0;\n    vector<ld> total_res;\n    for (int alpha = 1000, iter = 0;; alpha += 5000) {\n        double cur_elapsed_time = 0;\n        vector<pair<ld, pair<ld, ld> > > aux_res;\n        ld res = 0;\n        int pre_iteration = iter;\n        for (int k = 0; k < ITERATIONS_SAMPLING; k++) { // run the algorithm ITERATION times\n            iter = pre_iteration;\n            double beg = clock();\n            res = fast_wedge_sampling(dis, eng, iter, alpha, n_wedges);\n            double end = clock();\n            double aux_elapsed_time = double(end - beg) / CLOCKS_PER_SEC;\n            res += total;\n            res /= 4.0;\n            res /= alpha;\n            res *= (ld) n_wedges;\n            ld error = error_percent(res);\n            aux_res.push_back(make_pair(error, make_pair(aux_elapsed_time, res)));\n        }\n        sort(aux_res.begin(), aux_res.end()); // take the median\n        double aux_elapsed_time = aux_res[ITERATIONS_SAMPLING / 2].second.first;\n        ld error = aux_res[ITERATIONS_SAMPLING / 2].first;\n        total_elapsed_time += aux_elapsed_time;\n        total += aux_res[ITERATIONS_SAMPLING / 2].second.second;\n\n        cout << total_elapsed_time + time_n_wedges << \" \" << iter << \" \" << error << endl;\n        if (total_elapsed_time + time_n_wedges >= TIME_LIMIT) {\n            cout << \"iterations: \" << alpha << endl;\n            break;\n        }\n    }\n    return;\n}\n\nvoid exact_algorithm_time_tracker() {\n    double beg_clock = clock();\n    exact_n_bf = exact_butterfly_counting(adj);\n    double end_clock = clock();\n    double elapsed_time = (end_clock - beg_clock) / CLOCKS_PER_SEC;\n    cout << \" Exact algorithm is done in \" << elapsed_time << \" secs. There are \" << exact_n_bf << \" butterflies.\"\n         << endl;\n}\n\nstring algorithm_names[8] = {\"Exact\", \"Edge Sampling\", \"Fast Edge Sampling\", \"Vertex Sampling\", \"Wedge Sampling\",\n                             \"Edge Sparsification\", \"Colorful Sparsification\"};\n\nvoid read_the_graph() {\n    clear_everything();\n    cerr << \" Insert the input (bipartite network) file location\" << endl;\n    cerr << \" >>> \";\n    cin >> input_address;\n    cerr << \" Insert the output file\" << endl;\n    cerr << \" >>> \";\n    cin >> output_address;\n    freopen(output_address, \"w\", stdout);\n    cerr\n            << \" ---------------------------------------------------------------------------------------------------------------------- \\n\";\n    cerr << \"| * Note that edges should be separated line by line.\\n\\\n| In each line, the first integer number is considered as a vertex in the left partition of bipartite network, \\n\\\n| and the second integer number is a vertex in the right partition. \\n\\\n| In addition, multiple edges are removed from the given bipartite network.\\n\\\n| Also, note that in this version of the source code, we did NOT remove vertices with degree zero.\\n\";\n    cerr\n            << \" ---------------------------------------------------------------------------------------------------------------------- \\n\";\n\n    cerr << \" Processing the graph ... (please wait) \\n\";\n\n    get_graph();\n\n    cerr << \" -------------------------------------------------------------------------- \\n\";\n    cerr << \" The graph is processed - there are \" << n_vertices << \" vertices and \" << n_edges << \" edges  \\n\";\n    cerr << \" -------------------------------------------------------------------------- \\n\";\n}\n\nvoid choose_algorithm() {\n    string s;\n    while (true) {\n        cerr << \" Insert one of the following numbers (1-7): \\n\\\n\t [1]: Exact Algorithm \\n\\\n\t [2]: Edge Sampling Algorithm \\n\\\n\t [3]: Fast Edge Sampling Algorithm \\n\\\n\t [4]: Vertex Sampling Algorithm \\n\\\n\t [5]: Wedge Sampling Algorithm \\n\\\n\t [6]: Edge Sparsification Algorithm \\n\\\n\t [7]: Colorful Sparsification Algorithm \\n\";\n        cerr << \" >>> \";\n        cin >> s;\n        if (SZ(s) == 1 && s[0] >= '0' && s[0] <= '7') break;\n    }\n    int chosen = s[0] - '0';\n    if (chosen > 1) {\n        cerr << \" \" << algorithm_names[chosen - 1]\n             << \" Algorithm is a randomized algorithm. To report the accuracy, we need exact number of butterflies\"\n             << endl;\n        cerr\n                << \" Insert the number of butterflies. In the case, you do not know the number of butterflies, insert \\\"N\\\".\\n We will run the exact algorithm for you.\"\n                << endl;\n        string comm;\n        cerr << \" >>> \";\n        cin >> comm;\n        read_the_graph();\n        if (all_num(comm)) {\n            stringstream ss;\n            ss << comm;\n            ss >> exact_n_bf;\n        } else {\n            cerr\n                    << \" As you do not know the exact number of butterflies, we are going to run the exact algorithm ... \\n\";\n            exact_algorithm_time_tracker();\n        }\n    } else {\n        read_the_graph();\n    }\n\n    cerr << \" \" << algorithm_names[chosen - 1] << \" Algorithm is running ... (please wait) \" << endl;\n    if (chosen == 1) {\n        exact_algorithm_time_tracker();\n    } else {\n        if (chosen <= 5)\n            cout << \"Time(sec) #Iterations Error(%)\" << endl;\n        else\n            cout << \"Time(sec) Probability Error(%)\" << endl;\n        if (chosen == 2) {\n            edge_sampling_time_tracker();\n        } else if (chosen == 3) {\n            fast_edge_sampling_time_tracker();\n        } else if (chosen == 4) {\n            vertex_sampling_time_tracker();\n        } else if (chosen == 5) {\n            wedge_sampling_time_tracker();\n        } else if (chosen == 6) {\n            edge_sparsfication_time_tracker();\n        } else if (chosen == 7) {\n            coloful_sparsification_time_tracker();\n        }\n    }\n}\n\nint main() {\n    std::ios::sync_with_stdio(false);\n    choose_algorithm();\n    cerr << \" Take a look at the output file ...\" << endl;\n    return 0;\n}", "meta": {"hexsha": "4dd9674de3994d71d28ccdb974b3b9693910d911", "size": 32123, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "h-idx/tools/BFC.cpp", "max_stars_repo_name": "mexuaz/AccTrussDecomposition", "max_stars_repo_head_hexsha": "15a9e8fd2f123f5acace5f3b40b94f1a74eb17d4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9.0, "max_stars_repo_stars_event_min_datetime": "2020-03-30T13:00:15.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-17T13:40:17.000Z", "max_issues_repo_path": "h-idx/tools/BFC.cpp", "max_issues_repo_name": "mexuaz/AccTrussDecomposition", "max_issues_repo_head_hexsha": "15a9e8fd2f123f5acace5f3b40b94f1a74eb17d4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "h-idx/tools/BFC.cpp", "max_forks_repo_name": "mexuaz/AccTrussDecomposition", "max_forks_repo_head_hexsha": "15a9e8fd2f123f5acace5f3b40b94f1a74eb17d4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-08-17T10:05:51.000Z", "max_forks_repo_forks_event_max_datetime": "2020-08-30T22:57:55.000Z", "avg_line_length": 36.093258427, "max_line_length": 168, "alphanum_fraction": 0.5724870031, "num_tokens": 8580, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5926665999540697, "lm_q2_score": 0.5506073655352404, "lm_q1q2_score": 0.32632659524143853}}
{"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 \"Model.h\"\n\n#include <Eigen/Dense>\n\n#include <cassert>\n#include <cmath>\n#include <limits>\n#include <set>\n\n\ntemplate<class S, class T>\nint static findIndex(const S & v, const T & s)\n{\n  typename S::const_iterator it = std::find(v.begin(), v.end(), s);\n  if (it == v.end())\n    return -1;\n  return std::distance(v.begin(), it);\n}\n\nnamespace madai {\n\nModel\n::Model() :\n  m_LogLikelihoodObservable( -1 ),\n  m_GradientEstimateStepSize( 1.0e-4 ),\n  m_StateFlag( UNINITIALIZED ),\n  m_UseModelCovarianceToCalulateLogLikelihood( false )\n{\n}\n\n\nModel\n::~Model()\n{\n}\n\n\nbool\nModel\n::IsReady() const\n{\n  return ( m_StateFlag == READY );\n}\n\n\nunsigned int\nModel\n::GetNumberOfParameters() const\n{\n  return static_cast<unsigned int>(m_Parameters.size());\n}\n\n\nconst std::vector< Parameter > &\nModel\n::GetParameters() const\n{\n  return m_Parameters;\n}\n\n\nstd::vector< std::string >\nModel\n::GetParameterNames() const\n{\n  std::vector< std::string > parameterNames;\n  parameterNames.reserve( m_Parameters.size() );\n  for ( std::vector< Parameter >::const_iterator iter = m_Parameters.begin();\n        iter != m_Parameters.end();\n        ++iter ) {\n    parameterNames.push_back( iter->m_Name );\n  }\n  return parameterNames;\n}\n\n\nunsigned int\nModel\n::GetNumberOfScalarOutputs() const\n{\n  return static_cast<unsigned int>(m_ScalarOutputNames.size());\n}\n\n\nconst std::vector< std::string > &\nModel\n::GetScalarOutputNames() const\n{\n  return m_ScalarOutputNames;\n}\n\n\nModel::ErrorType\nModel\n::GetScalarAndGradientOutputs(\n  const std::vector< double > & parameters,\n  const std::vector< bool > & activeParameters,\n  std::vector< double > & scalars,\n  std::vector< double > & gradient) const\n{\n  if ( static_cast< unsigned int >( activeParameters.size() ) !=\n       this->GetNumberOfParameters() ) {\n    return INVALID_ACTIVE_PARAMETERS;\n  }\n\n  // Make a copy of the parameters that we can work with\n  std::vector< double > parametersCopy( parameters );\n\n  // Clear the output vectors\n  scalars.clear();\n  gradient.clear();\n\n  Model::ErrorType scalarOutputError;\n\n  double h = m_GradientEstimateStepSize;\n  for ( unsigned int i = 0; i < this->GetNumberOfParameters(); ++i ) {\n\n    if ( activeParameters[i] ) {\n      // Save the original parameter value\n      double originalParameterValue = parametersCopy[i];\n\n      // Compute the scalar outputs for a forward step\n      parametersCopy[i] = parameters[i] + h;\n      std::vector< double > forwardScalars;\n      double forwardLogLikelihood;\n      scalarOutputError = this->GetScalarOutputsAndLogLikelihood(\n        parametersCopy, forwardScalars, forwardLogLikelihood );\n      if ( scalarOutputError != NO_ERROR ) {\n        return scalarOutputError;\n      }\n\n      // Compute the scalar outputs for a backward step\n      parametersCopy[i] = parameters[i] - h;\n      std::vector< double > backwardScalars;\n      double backwardLogLikelihood;\n      scalarOutputError = this->GetScalarOutputsAndLogLikelihood(\n        parametersCopy, backwardScalars, backwardLogLikelihood );\n      if ( scalarOutputError != NO_ERROR ) {\n        return scalarOutputError;\n      }\n\n      // Compute the partial derivative with central differences\n      double partialDerivative = ( forwardLogLikelihood - backwardLogLikelihood )\n        / ( 2.0 * h );\n\n      // Store the partial derivative in the gradient output\n      gradient.push_back( partialDerivative );\n\n      // Restore the original parameter value\n      parametersCopy[i] = originalParameterValue;\n    }\n\n  }\n\n  // Now compute the scalars\n  scalarOutputError = this->GetScalarOutputs( parameters, scalars );\n  if ( scalarOutputError != NO_ERROR ) {\n    return scalarOutputError;\n  }\n\n  return NO_ERROR;\n}\n\nvoid\nModel\n::SetGradientEstimateStepSize( double stepSize )\n{\n  m_GradientEstimateStepSize = stepSize;\n}\n\n\ndouble\nModel\n::GetGradientEstimateStepSize() const\n{\n  return m_GradientEstimateStepSize;\n}\n\n\nstd::string\nModel\n::GetErrorTypeAsString( Model::ErrorType error )\n{\n  std::string outputString( \"NO_ERROR\" );\n\n  switch ( error ) {\n\n  case INVALID_PARAMETER_INDEX:\n    outputString = std::string( \"INVALID_PARAMETER_INDEX\" );\n    break;\n\n  case INVALID_ACTIVE_PARAMETERS:\n    outputString = std::string( \"INVALID_ACTIVE_PARAMETERS\" );\n    break;\n\n  case FILE_NOT_FOUND_ERROR:\n    outputString = std::string( \"FILE_NOT_FOUND_ERROR\" );\n    break;\n\n  case METHOD_NOT_IMPLEMENTED:\n    outputString = std::string( \"METHOD_NOT_IMPLEMENTED\" );\n    break;\n\n  case WRONG_VECTOR_LENGTH:\n    outputString = std::string( \"WRONG_VECTOR_LENGTH\" );\n    break;\n\n  case OTHER_ERROR:\n    outputString = std::string( \"OTHER_ERROR\" );\n    break;\n\n  default:\n    break;\n\n  }\n\n  return outputString;\n}\n\n\nbool\nModel\n::GetUseModelCovarianceToCalulateLogLikelihood()\n{\n  return m_UseModelCovarianceToCalulateLogLikelihood;\n}\n\n\nvoid\nModel\n::SetUseModelCovarianceToCalulateLogLikelihood(bool v)\n{\n  m_UseModelCovarianceToCalulateLogLikelihood = v;\n}\n\n\nvoid\nModel\n::AddParameter( const std::string & name,\n                const Distribution & priorDistribution)\n{\n  m_Parameters.push_back(\n    Parameter(name, priorDistribution) );\n}\n\n\nvoid\nModel\n::AddScalarOutputName( const std::string & name )\n{\n  //check to see if this is the log likelihood\n  std::string nameLower = name;\n  std::transform(nameLower.begin(), nameLower.end(), nameLower.begin(), ::tolower);\n  if (nameLower == \"log_likelihood\" || nameLower == \"loglikelihood\") {\n      m_LogLikelihoodObservable = m_ScalarOutputNames.size();\n  }\n\n  //actually add it to the list\n  m_ScalarOutputNames.push_back( name );\n}\n\n\nModel::ErrorType\nModel\n::SetObservedScalarValues(const std::vector< double > & observedScalarValues)\n{\n  size_t size = observedScalarValues.size();\n  if ((size != this->GetNumberOfScalarOutputs()) && (size != 0))\n    return WRONG_VECTOR_LENGTH;\n  // copy the vector\n  this->m_ObservedScalarValues = observedScalarValues;\n  return NO_ERROR;\n}\n\n\nModel::ErrorType\nModel\n::SetObservedScalarCovariance(\n    const std::vector< double > & observedScalarCovariance)\n{\n  size_t size = observedScalarCovariance.size();\n  if (size == 0) { // represents zero matrix.\n    this->m_ObservedScalarCovariance.clear();\n    return NO_ERROR;\n  }\n  size_t t = this->GetNumberOfScalarOutputs();\n  if (size != (t * t))\n    return WRONG_VECTOR_LENGTH;\n  this->m_ObservedScalarCovariance = observedScalarCovariance;\n  return NO_ERROR;\n}\n\n\nconst std::vector< double > &\nModel\n::GetObservedScalarValues() const\n{\n  return m_ObservedScalarValues; // cast to const\n}\n\nconst std::vector< double > &\nModel\n::GetObservedScalarCovariance() const\n{\n  return m_ObservedScalarCovariance; // cast to const;\n}\n\n\nModel::ErrorType\nModel\n::GetScalarOutputsAndCovariance(\n      const std::vector< double > & parameters,\n      std::vector< double > & scalars,\n      std::vector< double > & scalarCovariance) const\n{\n  scalarCovariance.clear();\n  return this->GetScalarOutputs(parameters, scalars);\n}\n\nModel::ErrorType\nModel\n::GetScalarOutputsAndLogLikelihood(\n    const std::vector< double > & parameters,\n    std::vector< double > & scalars,\n    double & logLikelihood) const\n{\n\n\n  logLikelihood = std::numeric_limits< double >::signaling_NaN();\n  double logPriorLikelihood\n    = this->GetLogPriorLikelihood(parameters);\n\n  size_t t = this->GetNumberOfScalarOutputs();\n  assert(t > 0);\n  std::vector< double > scalarCovariance;\n  // initially scalarCovariance is a empty vector\n  Model::ErrorType result;\n  if (m_UseModelCovarianceToCalulateLogLikelihood) {\n    result = this->GetScalarOutputsAndCovariance(\n        parameters, scalars, scalarCovariance);\n  } else {\n    // (! m_UseModelCovarianceToCalulateLogLikelihood)\n    result = this->GetScalarOutputs(parameters, scalars);\n  }\n  if (result != NO_ERROR)\n    return result;\n  if (scalars.size() != t)\n    return OTHER_ERROR;\n\n  // Use the model value for the log likelihood if it exists\n  if (m_LogLikelihoodObservable > -1) {\n    logLikelihood = scalars[m_LogLikelihoodObservable] + logPriorLikelihood;\n    return NO_ERROR;\n  }\n\n  std::vector< double > scalarDifferences(t);\n  std::vector<double> covariance(t * t);\n  double distSq = 0.0;\n  if (this->m_ObservedScalarValues.size() == 0) {\n    for (size_t i = 0; i < t; ++i) {\n      scalarDifferences[i] = scalars[i];\n      distSq += std::pow(scalarDifferences[i],2);\n    }\n  } else {\n    for (size_t i = 0; i < t; ++i) {\n      scalarDifferences[i] = scalars[i] - this->m_ObservedScalarValues[i];\n      distSq += std::pow(scalarDifferences[i],2);\n    }\n  }\n\n  std::vector< double > constantCovariance;\n  if ( !this->GetConstantCovariance(constantCovariance) ) {\n    std::cerr << \"Error getting the constant covariance matrix from the model\\n\";\n    return OTHER_ERROR;\n  }\n\n  if ((scalarCovariance.size() == 0) &&\n      (constantCovariance.size() == 0)) {\n    // Infinite precision makes no sense, so assume variance of 1.0\n    // for each variable.\n    logLikelihood = ((-0.5) * distSq) + logPriorLikelihood;\n    return NO_ERROR;\n  } else if (scalarCovariance.size() == 0) {\n    assert(constantCovariance.size() == (t*t));\n    covariance = constantCovariance;\n  } else if (constantCovariance.size() == 0) {\n    assert(scalarCovariance.size() == (t*t));\n    covariance = scalarCovariance;\n  } else {\n    for (size_t i = 0; i < (t*t); ++i)\n      covariance[i]\n        = scalarCovariance[i] + constantCovariance[i];\n  }\n\n  Eigen::Map< Eigen::VectorXd > diff(&(scalarDifferences[0]),t);\n  Eigen::Map< Eigen::MatrixXd > cov(&(covariance[0]),t,t);\n\n  // FIXME check for singular matrix -> return negative infinity!\n  //assert( cov.determinant() >= 0.0 ); // is there a better way?\n\n  double innerProduct = cov.colPivHouseholderQr().solve(diff).dot(diff);\n  logLikelihood = ((-0.5) * innerProduct) + logPriorLikelihood;\n  return NO_ERROR;\n}\n\n  // FIXME remove code overlap with GetScalarOutputsAndLogLikelihood\n  // some major refactoring is required to make these less cumbersome\nModel::ErrorType\nModel\n::GetScalarOutputsAndLogLikelihoodAndLikelihoodErrorGradient(\n    const std::vector< double > & parameters,\n    std::vector< double > & scalars,\n    double & logLikelihood,\n    std::vector< double > & value_gradient,\n    std::vector< double > & error_gradient) const\n{\n\n\n  logLikelihood = std::numeric_limits< double >::signaling_NaN();\n  double logPriorLikelihood\n    = this->GetLogPriorLikelihood(parameters);\n\n  size_t t = this->GetNumberOfScalarOutputs();\n  assert(t > 0);\n  std::vector< double > scalarCovariance;\n  // initially scalarCovariance is a empty vector\n  Model::ErrorType result;\n  if (m_UseModelCovarianceToCalulateLogLikelihood) {\n    result = this->GetScalarOutputsAndCovariance(\n        parameters, scalars, scalarCovariance);\n  } else {\n    // (! m_UseModelCovarianceToCalulateLogLikelihood)\n    result = this->GetScalarOutputs(parameters, scalars);\n  }\n  if (result != NO_ERROR)\n    return result;\n  if (scalars.size() != t)\n    return OTHER_ERROR;\n\n  std::vector< double > scalarDifferences(t);\n  std::vector<double> covariance(t * t);\n  double distSq = 0.0;\n  if (this->m_ObservedScalarValues.size() == 0) {\n    for (size_t i = 0; i < t; ++i) {\n      scalarDifferences[i] = scalars[i];\n      distSq += std::pow(scalarDifferences[i],2);\n    }\n  } else {\n    for (size_t i = 0; i < t; ++i) {\n      scalarDifferences[i] = scalars[i] - this->m_ObservedScalarValues[i];\n      distSq += std::pow(scalarDifferences[i],2);\n    }\n  }\n\n  std::vector< double > constantCovariance;\n  if ( !this->GetConstantCovariance(constantCovariance) ) {\n    std::cerr << \"Error getting the constant covariance matrix from the model\\n\";\n    return OTHER_ERROR;\n  }\n\n  if ((scalarCovariance.size() == 0) &&\n      (constantCovariance.size() == 0)) {\n    // Infinite precision makes no sense, so assume variance of 1.0\n    // for each variable.\n    logLikelihood = ((-0.5) * distSq) + logPriorLikelihood;\n    return NO_ERROR;\n  } else if (scalarCovariance.size() == 0) {\n    assert(constantCovariance.size() == (t*t));\n    covariance = constantCovariance;\n  } else if (constantCovariance.size() == 0) {\n    assert(scalarCovariance.size() == (t*t));\n    covariance = scalarCovariance;\n  } else {\n    for (size_t i = 0; i < (t*t); ++i)\n      covariance[i]\n        = scalarCovariance[i] + constantCovariance[i];\n  }\n\n  Eigen::Map< Eigen::VectorXd > diff(&(scalarDifferences[0]),t);\n  Eigen::Map< Eigen::MatrixXd > cov(&(covariance[0]),t,t);\n  Eigen::ColPivHouseholderQR< Eigen::MatrixXd > qrDecomposition = cov.colPivHouseholderQr();\n\n  // FIXME check for singular matrix -> return negative infinity!\n  //assert( cov.determinant() >= 0.0 ); // is there a better way?\n\n  double innerProduct = qrDecomposition.solve(diff).dot(diff);\n  logLikelihood = ((-0.5) * innerProduct) + logPriorLikelihood;\n\n  value_gradient.clear();\n  error_gradient.clear();\n  if (this->m_ObservedScalarValues.size() > 0) {\n    Eigen::MatrixXd inverse  = qrDecomposition.inverse();\n    //this is positive because diff = scalars - observedScalars\n    Eigen::VectorXd gradient = inverse*diff;\n    value_gradient.assign(gradient.data(), gradient.data()+t);\n    Eigen::MatrixXd covDelta(t,t);\n    for (size_t i = 0; i < t; ++i) {\n      covDelta.setZero();\n      for (size_t k = 0; k < t; k++) {\n        if(k == i) {\n          covDelta(i, k) = 2.0*sqrt(cov(i, k));\n        }\n        else {\n          covDelta(i, k) = cov(i, k)/sqrt(cov(i, i));\n          covDelta(k, i) = covDelta(i, k);\n        }\n      }\n      error_gradient.push_back(0.5*((inverse*covDelta*inverse)*diff).dot(diff)*sqrt(cov(i,i)));\n    }\n  }\n\n  return NO_ERROR;\n}\n\n\n/** return the sum of the LogPriorLikelihood for each x[i] */\ndouble\nModel\n::GetLogPriorLikelihood(const std::vector< double > & x) const\n{\n  const std::vector< Parameter > & params = this->GetParameters();\n  assert(x.size() == params.size());\n  double logPriorLikelihood = 0.0;\n  for ( size_t i = 0; i < params.size(); ++i ) {\n    logPriorLikelihood +=\n      params[i].GetPriorDistribution()->GetLogProbabilityDensity(x[i]);\n  }\n  return logPriorLikelihood;\n}\n\n\n/** return the gradient of the LogPriorLikelihood at x */\nstd::vector< double >\nModel\n::GetGradientOfLogPriorLikelihood(\n  const std::vector< double > & x) const\n{\n  const std::vector< Parameter > & params = this->GetParameters();\n  assert(x.size() == params.size());\n  std::vector< double > gradient;\n  for ( size_t i = 0; i < params.size(); i++ ) {\n    gradient.push_back(\n      params[i].GetPriorDistribution()->GetGradientLogProbabilityDensity( x[i]) );\n  }\n  return gradient;\n}\n\n\nbool\nModel\n::GetConstantCovariance(std::vector< double > & x) const\n{\n  x.clear();\n  unsigned int t = static_cast< unsigned int >( m_ScalarOutputNames.size() );\n  if ( m_ObservedScalarCovariance.size() != (t*t) ) {\n    std::cerr << \"Observed scalar covariance is of invalid size \"\n              << m_ObservedScalarCovariance.size() << \"\\n\";\n    return false;\n  }\n\n  x.resize(t*t);\n  x = m_ObservedScalarCovariance;\n  return true;\n}\n\n\n} // end namespace madai\n", "meta": {"hexsha": "723e2d1bfdf7bbc0e011e711c3dda23e83e90abb", "size": 15641, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "src/Model.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": "src/Model.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": "src/Model.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": 26.6911262799, "max_line_length": 95, "alphanum_fraction": 0.6766830765, "num_tokens": 4152, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5926665855647394, "lm_q2_score": 0.5506073655352404, "lm_q1q2_score": 0.3263265873185673}}
{"text": "// g2o - General Graph Optimization\r\n// Copyright (C) 2011 Kurt Konolige\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#include <random>\r\n#include <iostream>\r\n#include <stdint.h>\r\n\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/optimization_algorithm_levenberg.h\"\r\n#include \"g2o/solvers/csparse/linear_solver_csparse.h\"\r\n#include \"g2o/types/icp/types_icp.h\"\r\n\r\nusing namespace Eigen;\r\nusing namespace std;\r\nusing namespace g2o;\r\n\r\n// sampling distributions\r\n  class Sample\r\n  {\r\n\r\n    static default_random_engine gen_real;\r\n    static default_random_engine gen_int;\r\n  public:\r\n    static int uniform(int from, int to);\r\n\r\n    static double uniform();\r\n\r\n    static double gaussian(double sigma);\r\n  };\r\n\r\n\r\n  default_random_engine Sample::gen_real;\r\n  default_random_engine Sample::gen_int;\r\n\r\n  int Sample::uniform(int from, int to)\r\n  {\r\n    uniform_int_distribution<int> unif(from, to);\r\n    int sam = unif(gen_int);\r\n    return  sam;\r\n  }\r\n\r\n  double Sample::uniform()\r\n  {\r\n    std::uniform_real_distribution<double> unif(0.0, 1.0);\r\n    double sam = unif(gen_real);\r\n    return  sam;\r\n  }\r\n\r\n  double Sample::gaussian(double sigma)\r\n  {\r\n    std::normal_distribution<double> gauss(0.0, sigma);\r\n    double sam = gauss(gen_real);\r\n    return  sam;\r\n  }\r\n\r\n\r\n//\r\n// set up simulated system with noise, optimize it\r\n//\r\n\r\nint main(int argc, char **argv)\r\n{\r\n  int num_points = 0;\r\n\r\n  // check for arg, # of points to use in projection SBA\r\n  if (argc > 1)\r\n    num_points = atoi(argv[1]);\r\n\r\n  double euc_noise = 0.1;      // noise in position, m\r\n  double pix_noise = 1.0;       // pixel noise\r\n  //  double outlier_ratio = 0.1;\r\n\r\n\r\n  SparseOptimizer optimizer;\r\n  optimizer.setVerbose(false);\r\n\r\n  // variable-size block solver\r\n  g2o::OptimizationAlgorithmLevenberg* solver = new g2o::OptimizationAlgorithmLevenberg(\r\n    g2o::make_unique<BlockSolverX>(g2o::make_unique<LinearSolverCSparse<g2o::BlockSolverX::PoseMatrixType>>()));\r\n\r\n  optimizer.setAlgorithm(solver);\r\n\r\n  vector<Vector3d> true_points;\r\n  for (size_t i=0;i<1000; ++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  // set up camera params\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  // set up camera params and projection matrices on vertices\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\r\n  // set up two poses\r\n  int vertex_id = 0;\r\n  for (size_t i=0; i<2; ++i)\r\n  {\r\n    // set up rotation and translation for this node\r\n    Vector3d t(0,0,i);\r\n    Quaterniond q;\r\n    q.setIdentity();\r\n\r\n    Eigen::Isometry3d cam;           // camera pose\r\n    cam = q;\r\n    cam.translation() = t;\r\n\r\n    // set up node\r\n    VertexSCam *vc = new VertexSCam();\r\n    vc->setEstimate(cam);\r\n    vc->setId(vertex_id);      // vertex id\r\n\r\n    cerr << t.transpose() << \" | \" << q.coeffs().transpose() << endl;\r\n\r\n    // set first cam pose fixed\r\n    if (i==0)\r\n      vc->setFixed(true);\r\n\r\n    // make sure projection matrices are set\r\n    vc->setAll();\r\n\r\n    // add to optimizer\r\n    optimizer.addVertex(vc);\r\n\r\n    vertex_id++;                \r\n  }\r\n\r\n  // set up point matches for GICP\r\n  for (size_t i=0; i<true_points.size(); ++i)\r\n  {\r\n    // get two poses\r\n    VertexSE3* vp0 = \r\n      dynamic_cast<VertexSE3*>(optimizer.vertices().find(0)->second);\r\n    VertexSE3* vp1 = \r\n      dynamic_cast<VertexSE3*>(optimizer.vertices().find(1)->second);\r\n\r\n    // calculate the relative 3D position of the point\r\n    Vector3d pt0,pt1;\r\n    pt0 = vp0->estimate().inverse() * true_points[i];\r\n    pt1 = vp1->estimate().inverse() * true_points[i];\r\n\r\n    // add in noise\r\n    pt0 += Vector3d(Sample::gaussian(euc_noise ),\r\n                    Sample::gaussian(euc_noise ),\r\n                    Sample::gaussian(euc_noise ));\r\n\r\n    pt1 += Vector3d(Sample::gaussian(euc_noise ),\r\n                    Sample::gaussian(euc_noise ),\r\n                    Sample::gaussian(euc_noise ));\r\n\r\n    // form edge, with normals in varioius positions\r\n    Vector3d nm0, nm1;\r\n    nm0 << 0, i, 1;\r\n    nm1 << 0, i, 1;\r\n    nm0.normalize();\r\n    nm1.normalize();\r\n\r\n    Edge_V_V_GICP * e           // new edge with correct cohort for caching\r\n        = new Edge_V_V_GICP(); \r\n\r\n    e->vertices()[0]            // first viewpoint\r\n      = dynamic_cast<OptimizableGraph::Vertex*>(vp0);\r\n\r\n    e->vertices()[1]            // second viewpoint\r\n      = dynamic_cast<OptimizableGraph::Vertex*>(vp1);\r\n\r\n    EdgeGICP meas;\r\n\r\n    meas.pos0 = pt0;\r\n    meas.pos1 = pt1;\r\n    meas.normal0 = nm0;\r\n    meas.normal1 = nm1;\r\n    e->setMeasurement(meas);\r\n    meas = e->measurement();\r\n    //        e->inverseMeasurement().pos() = -kp;\r\n\r\n    // use this for point-plane\r\n    e->information() = meas.prec0(0.01);\r\n\r\n    // use this for point-point \r\n    //    e->information().setIdentity();\r\n\r\n    //    e->setRobustKernel(true);\r\n    //e->setHuberWidth(0.01);\r\n\r\n    optimizer.addEdge(e);\r\n  }\r\n\r\n  // set up SBA projections with some number of points\r\n\r\n  true_points.clear();\r\n  for (int i=0;i<num_points; ++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  // 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(vertex_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    optimizer.addVertex(v_p);\r\n\r\n    for (size_t j=0; j<2; ++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          z += Vector3d(Sample::gaussian(pix_noise),\r\n                        Sample::gaussian(pix_noise),\r\n                        Sample::gaussian(pix_noise/16.0));\r\n\r\n          g2o::Edge_XYZ_VSC * e\r\n              = new g2o::Edge_XYZ_VSC();\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          //e->setRobustKernel(false);\r\n          //e->setHuberWidth(1);\r\n\r\n          optimizer.addEdge(e);\r\n        }\r\n\r\n      }\r\n  } // done with adding projection points\r\n\r\n\r\n\r\n  // move second cam off of its true position\r\n  VertexSE3* vc = \r\n    dynamic_cast<VertexSE3*>(optimizer.vertices().find(1)->second);\r\n  Eigen::Isometry3d cam = vc->estimate();\r\n  cam.translation() = Vector3d(-0.1,0.1,0.2);\r\n  vc->setEstimate(cam);\r\n  optimizer.initializeOptimization();\r\n  optimizer.computeActiveErrors();\r\n  cout << \"Initial chi2 = \" << FIXED(optimizer.chi2()) << endl;\r\n\r\n  optimizer.setVerbose(true);\r\n\r\n  optimizer.optimize(20);\r\n\r\n  cout << endl << \"Second vertex should be near 0,0,1\" << endl;\r\n  cout <<  dynamic_cast<VertexSE3*>(optimizer.vertices().find(0)->second)\r\n    ->estimate().translation().transpose() << endl;\r\n  cout <<  dynamic_cast<VertexSE3*>(optimizer.vertices().find(1)->second)\r\n    ->estimate().translation().transpose() << endl;\r\n}\r\n", "meta": {"hexsha": "d543223b8c71c8df32e492f51ee4c926788fb6ce", "size": 9227, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "slambook2/3rdparty/g2o/g2o/examples/icp/gicp_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/icp/gicp_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/icp/gicp_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": 29.9577922078, "max_line_length": 113, "alphanum_fraction": 0.6070228677, "num_tokens": 2335, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5273165085228825, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.3262931378640818}}
{"text": "/*\n This program is free software; you can redistribute it and/or modify it under\n the terms of the European Union Public Licence - EUPL v.1.1 as published by\n the European Commission.\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 European Union Public Licence - EUPL v.1.1\n for more details.\n\n You should have received a copy of the European Union Public Licence - EUPL v.1.1\n along with this program.\n\n Further information about the European Union Public Licence - EUPL v.1.1 can\n also be found on the world wide web at http://ec.europa.eu/idabc/eupl\n */\n\n/*\n ------ Copyright (C) 2010 STA Steering Board (space.trajectory.analysis AT gmail.com) ----\n ------------------ Author: Ricardo Noriega  ----------------------------------------------\n ------------------ email: ricardonor@gmail.com  ------------------------------------------\nTotally changed by Guillermo in May 2011 due to the numerioud bugs in the original code that could not calculate properly and crashed STA.\nCommenting properly all methods to allow the poor new guy that will update the code\n\n */\n\n#include <QDebug>\n\n#include <math.h>\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n\n#include \"commanalysis.h\"\n#include \"Main/findDataFolder.h\"\n#include \"Locations/environmentdialog.h\"\n#include \"Payloads/receiverPayloadDialog.h\"\n#include <Astro-Core/surfaceVelocity.h>\n\n#ifdef Q_WS_MAC\n#include <CoreFoundation/CFBundle.h>\n#endif\n\n//Definition of constructors, the default one contains a warning.\n\nusing namespace Eigen;\n\n\nbool tracking=true;//This allows to set a tracking system for the calculations, so the antenna of the groundstation follows the spacecraft!\n\n\nCommAnalysis::CommAnalysis()\n{\n    qDebug()<< \"Warning: CommAnalysis object created without any participant to make the calculations\";\n}\n\nCommAnalysis::CommAnalysis(ScenarioTransmitterPayloadType *transmitter, ScenarioReceiverPayloadType *receiver, ScenarioGroundStationEnvironment* environment, PropagatedScenario* propagatedScenario, int indexSC, int indexGS, int indexMA, bool flagTX, bool flagRX):m_transmitter(transmitter), m_receiver(receiver), m_propagatedScenario(propagatedScenario), m_environment(environment), m_indexSC(indexSC), m_indexGS(indexGS), m_indexMA(indexMA), m_flagTX(flagTX), m_flagRX(flagRX)\n{\n    // Nothing to be done\n}\n\n//Default destructor\n\nCommAnalysis::~CommAnalysis()\n{\n    // Noting to be done\n}\n\ndouble lightSpeed=SPEED_OF_LIGHT;\ndouble Pi=mypi;\n\n////////////////////////////////////////////// FUNCTIONS ////////////////////////////////////////////////////////\n\n/** Calculates the Doppler shift due to motion between a receiver and a emmitter\n  * The calculation is done for a given participant a a given mission arc of this participant\n  * Accepts as parameters the lenght of the list that actually corresponds to each of the\n  *\n  * \\return a QList of double numbers containing all doppler shifts in time\n  *\n  */\nQList<double> CommAnalysis::getDopplerShiftList(int numberOfRows)\n{\n\n    QList<double> myDopplerShiftList;\n    double dopplerShift;\n\n    for(int i=0; i<numberOfRows; i++)\n    {\n        double frequency=m_transmitter->Budget()->FrequencyBand();\n        double t=m_propagatedScenario->spaceObjects().at(m_indexSC)->mission().at(m_indexMA)->trajectorySampleTime(i);\n\n        bool visibility;\n        if(m_propagatedScenario->groundObjects().at(m_indexGS)->elevationAngle(m_propagatedScenario->spaceObjects().at(m_indexSC),t)>=5.0*DEG2RAD)\n        {\n            visibility=true;\n            sta::StateVector samples;\n\n            samples=m_propagatedScenario->spaceObjects().at(m_indexSC)->mission().at(m_indexMA)->trajectorySample(i);\n\n            double latitudeGS=m_propagatedScenario->groundObjects().at(m_indexGS)->latitude;\n            double longitudeGS=m_propagatedScenario->groundObjects().at(m_indexGS)->longitude;\n            double altitudeGS=m_propagatedScenario->groundObjects().at(m_indexGS)->altitude;\n\n            latitudeGS=DEG2RAD*(latitudeGS);\n            longitudeGS=DEG2RAD*(longitudeGS);\n\n            longitudeGS=longitudeGS+getGreenwichHourAngle(m_propagatedScenario->spaceObjects().at(m_indexSC)->mission().at(m_indexMA)->trajectorySampleTime(i)+2400000.5);\n\n            Vector3d normPosition(cos(latitudeGS) * cos(longitudeGS),\n                                  cos(latitudeGS) * sin(longitudeGS),\n                                  sin(latitudeGS));\n\n            Vector3d stationPos=normPosition.cwise() * STA_SOLAR_SYSTEM->lookup(\"Earth\")->radii() + normPosition * altitudeGS;\n\n            Vector3d toSpacecraft = (samples.position - stationPos).normalized();\n\n            Vector3d velSat=samples.velocity;\n            surfaceVelocity earthVel;\n            double speedGS=earthVel.earthStationLinearVelocity(latitudeGS);\n            Vector3d velGS(speedGS*sin(longitudeGS),speedGS*cos(longitudeGS),0);\n            toSpacecraft.normalize();\n\n            double radialVelToGS = ((velGS-velSat).dot(toSpacecraft)) * 1000; //The result is in Km/sec so I convert it to m/s\n\n            dopplerShift=radialVelToGS*frequency/lightSpeed;\n\n            myDopplerShiftList.append(dopplerShift);\n\n        }\n        else\n        {\n            visibility=false;\n            myDopplerShiftList.append(0.0);\n        }\n    }\n\n    return myDopplerShiftList;\n} ///////////////////////////////////////// end of the method //////////////////////////////////////////\n\n\n\n\n/** Calculates the free space loss due to motion between a receiver and a emmitter\n  * The calculation is done for a given participant a a given mission arc of this participant\n  * Accepts as parameters the lenght of the list that actually corresponds to each of the\n  *\n  * \\return a QList of double numbers containing all free space losses in time\n  *\n  */\nQList<double> CommAnalysis::getFreeSpaceLossList(int numberOfRows)\n{\n    QList<double> myFreeSpaceLossList;\n    double eachFreeSpaceLoss, eachFreeSpaceLossIndBs;\n\n    //The inputs for this function will be the frequency and the range between both participants\n    double frequency = m_transmitter->Budget()->FrequencyBand();\n    double range, t;\n\n    for(int i=0; i<numberOfRows; i++)\n    {\n        t = m_propagatedScenario->spaceObjects().at(m_indexSC)->mission().at(m_indexMA)->trajectorySampleTime(i);\n        range = m_propagatedScenario->groundObjects().at(m_indexGS)->getRange(m_propagatedScenario->spaceObjects().at(m_indexSC), t) * 1000;  // In meters\n\n        bool visibility;\n        // The following condition shall be upgraded to make it gereric (not only 5.0*DEG2GRAD times)\n        if (m_propagatedScenario->groundObjects().at(m_indexGS)->elevationAngle(m_propagatedScenario->spaceObjects().at(m_indexSC),t) >= 5.0*DEG2RAD)\n        {\n            visibility=true;\n            //mjdList.append(t);\n            //range=range*1000;\n            //rangeList.append(range);//In metres\n            eachFreeSpaceLoss = pow((4 * Pi * range * frequency / lightSpeed), 2);  // This formula is defined to be in the denominator\n                                                                                    // of the C/No when it is expressed in natural units\n            eachFreeSpaceLossIndBs = 10*log10(eachFreeSpaceLoss); //This value shall be preceded by a minus when it is in decibels\n            myFreeSpaceLossList.append(eachFreeSpaceLossIndBs);\n        }\n        else\n        {\n            visibility=false;\n            myFreeSpaceLossList.append(0.0);\n        }\n\n    }\n\n    return myFreeSpaceLossList;\n} ///////////////////////////////////////// end of the method //////////////////////////////////////////\n\n\n\n\ndouble CommAnalysis::OxygenSpecificAttenuation(double frequency)\n{ //THE FREQUENCY HAS TO BE IN GHZ!!!!!!!\n\n    double oxSpecAtt;\n\n    oxcheck = m_environment->OxChoice();\n\n    if(oxcheck==QString(\"true\"))\n    {\n\n        oxSpecAtt=((7.1/(pow(frequency,2)+0.36))+(4.5/(pow((frequency-57),2)+0.98)))*pow(frequency,2)/1000;  //dB/Km\n        /*oxSpecAtt=(7.1/(pow(frequency,2)+0.36));\n        oxSpecAtt=oxSpecAtt+(4.5/(pow((frequency-57),2)+0.98));\n        oxSpecAtt=oxSpecAtt*pow(frequency,2)/1000;*/\n    }\n    else if(oxcheck==QString(\"false\"))\n    {\n        oxSpecAtt=0;\n    }\n\n    return oxSpecAtt;\n} ///////////////////////////////////////// end of the method //////////////////////////////////////////\n\n\n/** Calculates the ????????????\n  * For applications which require an annual mean value, the surface water vapour densities exceeded\n  *  for 50% of the year, shown for quick reference in Fig. 1, ITU-R P.836-3, should be used\n  *\n  * \\return a double\n  *\n  */\ndouble CommAnalysis::WaterVapourSpecificAttenuation(double frequency, double latitude, double longitude)\n{\n    double wpSpecAtt;\n    double waterDensity;\n\n    wvcheck=m_environment->WaterVapourChoice();\n\n    QString whereIsTheDataFolder = findDataFolder();\n\n    if(wvcheck==\"true\")\n    {\n        QString pathLat(whereIsTheDataFolder + \"/\" + \"data/maps/surfwv_lat.txt\"); QFile fileLat(pathLat);\n        QString pathLon(whereIsTheDataFolder + \"/\" + \"data/maps/surfwv_lon.txt\"); QFile fileLon(pathLon);\n        QString pathWaterVapour(whereIsTheDataFolder + \"/\" + \"data/maps/surfwv_50.txt\"); QFile fileWaterVapour(pathWaterVapour);\n\n        if((!fileLat.exists()) || (!fileLon.exists()) || (!fileWaterVapour.exists()))\n        {\n            qDebug()<<\" file error: surfwv_lat.txt does not exist\";\n        }\n        else // In this case we found the file and we can read it\n        {\n            fileLat.open(QIODevice::ReadOnly);\n            QTextStream latStream(&fileLat);\n            double latPoint;\n\n            int i=0;\n            do\n            {\n                latStream>>latPoint;\n                i++;\n            } while(latPoint>latitude);\n\n            fileLat.close();\n            if(longitude<0) longitude=longitude+360;\n\n            fileLon.open(QIODevice::ReadOnly);\n            QTextStream lonStream(&fileLon);\n            double lonPoint;\n\n            int k;\n            for(k=0; k<i; k++)\n            {\n                lonStream>>lonPoint;\n            }\n\n            int j=0;\n            do\n            {\n                lonStream>>lonPoint;\n                j++;\n            } while(lonPoint<longitude);\n\n            fileLon.close();\n\n            fileWaterVapour.open(QIODevice::ReadOnly);\n            QTextStream waterVapourStream(&fileWaterVapour);\n\n            int z=0;\n            int target=i+j;\n\n            for(z; z<target; z++)\n            {\n                waterVapourStream>>waterDensity;\n            }\n\n            wpSpecAtt=(0.067+(3/(pow(((frequency)-22.3),2)+7.3)))*waterDensity*pow((frequency),2)/10000; //This result is in dB/Km\n        }\n    }\n    else if (wvcheck==\"false\")\n    {\n        wpSpecAtt=0.0;\n    }\n\n    return wpSpecAtt;\n} ///////////////////////////////////////// end of the method //////////////////////////////////////////\n\n\n/** Calculates the atmospheric attenuation\n  * This takes the elevation angle of the participant that is on the ground station.\n  * Satellites cannot carry antennas with tracking systems since there is not attitude control in STA\n  *\n  * \\return a double\n  *\n  */\nQList<double> CommAnalysis::getAtmosphericAttenuation(double frequency, double wpSpecAtt, double oxSpecAtt, int numberOfRows)\n{\n    QList<double> myAtmosphericAttenuationList;\n    double eachAtmosphericAttenuation;\n\n    double h0 = 6;//equivalent height of a uniform medium for oxygen calculations (Km)\n    double hw; //equivalent height for water vapour calculations\n    frequency = frequency / 1000000000;\n    hw = 2.2 + (3 / (pow((frequency - 22.3),2) + 3)); // In Km\n    double elevationAngle;\n\n    for(int i=0; i<numberOfRows; i++)\n    {\n        double t=m_propagatedScenario->spaceObjects().at(m_indexSC)->mission().at(m_indexMA)->trajectorySampleTime(i);\n\n        if(tracking==true)\n        {\n            elevationAngle = m_propagatedScenario->groundObjects().at(m_indexGS)->elevationAngle(m_propagatedScenario->spaceObjects().at(m_indexSC),t);\n        }\n        else if(tracking==false)\n        {\n            if(m_flagTX==false && m_flagRX==true)\n                elevationAngle = m_transmitter->Transmitter()->PointingDirection()->elevation();\n            else if(m_flagRX==false && m_flagTX==true)\n                elevationAngle = m_receiver->Receiver()->PointingDirection()->elevation();\n        }\n\n        bool visibility;\n\n        if(m_propagatedScenario->groundObjects().at(m_indexGS)->elevationAngle(m_propagatedScenario->spaceObjects().at(m_indexSC),t)>=5.0*DEG2RAD)\n        {\n            visibility=true;\n            //elevationAngleList.append(elevationAngle);\n            //oxAttList.append(h0*oxSpecAtt*exp(-(hw/h0))/sin(elevationAngle));\n            //wvAttList.append((hw*wpSpecAtt)/sin(elevationAngle));\n            eachAtmosphericAttenuation = (((h0 * oxSpecAtt * exp(-(hw / h0))) + (hw * wpSpecAtt))) / sin(elevationAngle);\n            myAtmosphericAttenuationList.append(eachAtmosphericAttenuation);\n        }\n        else\n        {\n            visibility=false;\n            myAtmosphericAttenuationList.append(0.0);\n        }\n    }\n\n    return myAtmosphericAttenuationList;\n\n} ///////////////////////////////////////// end of the method //////////////////////////////////////////\n\n\n/** Calculates the rain attenuation\n  * This is the position of the groundstation, the parent object should be read\n  * This function is following the recommendation ITU-R P.618-10 for Rain Attenuation estimation (section 2.2)\n  *\n  * \\return a double\n  *\n  */\nQList<double>  CommAnalysis::getRainAttenuation(double latitude, double longitude, int numberOfRows)\n{\n    QList<double> myRainAttenuationList;\n    double eachRainAttenuation;\n\n    ////////////////////////////// DATA AND COEFFICIENTS FOR THIS FUNCTION ////////////////////////////////////////\n    double akh[4]={-5.3398, -0.3531, -0.23789, -0.94158};\n    double bkh[4]={-0.10008, 1.26970, 0.86036, 0.64552};\n    double ckh[4]={1.13098, 0.45400, 0.15354, 0.16817};\n\n    double akv[4]={-3.80595, -3.44965, -0.39902, 0.50167};\n    double bkv[4]={0.56934, -0.22911, 0.73042, 1.07319};\n    double ckv[4]={0.81061, 0.51059, 0.11899, 0.27195};\n\n    double aah[5]={-0.14318, 0.29591, 0.32177, -5.37610, 16.1721};\n    double bah[5]={1.82442, 0.77564, 0.63773, -0.96230, -3.29980};\n    double cah[5]={-0.55187, 0.19822, 0.13164, 1.47828, 3.43990};\n\n    double aav[5]={-0.07771, 0.56727, -0.20238, -48.2991, 48.5833};\n    double bav[5]={2.33840, 0.95545, 1.14520, 0.791669, 0.791459};\n    double cav[5]={-0.76284, 0.54039, 0.26809, 0.116226, 0.116479};\n\n    double logf;\n    double frequency;\n\n    if(m_flagTX==false && m_flagRX==true)\n    {\n        logf=log10(m_transmitter->Budget()->FrequencyBand()/1000000000);\n        frequency= m_transmitter->Budget()->FrequencyBand()/1000000000;\n    }\n    else if(m_flagRX==false && m_flagTX==true)\n    {\n        logf=log10(m_receiver->Budget()->FrequencyBand()/1000000000);\n        frequency= m_receiver->Budget()->FrequencyBand()/1000000000;\n    }\n\n    double logkh= (akh[0]*exp(-pow((logf-bkh[0])/ckh[0],2)))+(akh[1]*exp(-pow((logf-bkh[1])/ckh[1],2)))+(akh[2]*exp(-pow((logf-bkh[2])/ckh[2],2)))+(akh[3]*exp(-pow((logf-bkh[3])/ckh[3],2)))-(logf*0.18961)+0.71147;\n    double logkv= (akv[0]*exp(-pow((logf-bkv[0])/ckv[0],2)))+(akv[1]*exp(-pow((logf-bkv[1])/ckv[1],2)))+(akv[2]*exp(-pow((logf-bkv[2])/ckv[2],2)))+(akv[3]*exp(-pow((logf-bkv[3])/ckv[3],2)))-(logf*0.16398)+0.63297;\n\n    double alphah=(aah[0]*exp(-pow((logf-bah[0])/cah[0],2)))+(aah[1]*exp(-pow((logf-bah[1])/cah[1],2)))+(aah[2]*exp(-pow((logf-bah[2])/cah[2],2)))+(aah[3]*exp(-pow((logf-bah[3])/cah[3],2)))+(aah[4]*exp(-pow((logf-bah[4])/cah[4],2)))+(logf*0.67849)-1.95537;\n    double alphav=(aav[0]*exp(-pow((logf-bav[0])/cav[0],2)))+(aav[1]*exp(-pow((logf-bav[1])/cav[1],2)))+(aav[2]*exp(-pow((logf-bav[2])/cav[2],2)))+(aav[3]*exp(-pow((logf-bav[3])/cav[3],2)))+(aav[4]*exp(-pow((logf-bav[4])/cav[4],2)))-(logf*0.053739)+0.83433;\n\n    double kh=pow(10, logkh);\n\n    double kv=pow(10, logkv);\n\n    double tilt;\n\n    if(m_flagTX==false && m_flagRX==true)\n        tilt=m_transmitter->Transmitter()->EMproperties()->TiltAngle();\n    else if(m_flagRX==false && m_flagTX==true)\n        tilt=m_receiver->Receiver()->EMproperties()->TiltAngle();\n\n    //////////////////////////////////////STEP 1: Determination of rain height given in ITU-R P.839//////////////////////////////\n\n    // Find out now the correct path of the files\n    QString staResourcesPath = findDataFolder();\n\n    QString pathLat(staResourcesPath + \"/\" + \"data/maps/ESALAT.TXT\");\n    QFile fileLat(pathLat);\n\n    if(!fileLat.exists())\n        qDebug()<<\" file error\";\n    fileLat.open(QIODevice::ReadOnly);\n\n    QTextStream latStream(&fileLat);\n    double latPoint;\n\n    int i1=0;\n    do\n    {\n        latStream>>latPoint;\n        i1++;\n\n    } while(latPoint>latitude);\n\n\n    fileLat.close();\n\n    if(longitude<0)\n        longitude=longitude+360;\n\n    QString pathLon(staResourcesPath + \"/\" + \"data/maps/ESALON.TXT\");\n\n    QFile fileLon(pathLon);\n\n    if(!fileLon.exists())\n        qDebug()<<\" file error\";\n    fileLon.open(QIODevice::ReadOnly);\n\n    QTextStream lonStream(&fileLon);\n    double lonPoint;\n\n    int k1=0;\n    for(k1; k1<i1; k1++)\n        lonStream>>lonPoint;\n\n    int j1=0;\n    do\n    {\n        lonStream>>lonPoint;\n        j1++;\n    } while(lonPoint<longitude);\n\n\n    fileLon.close();\n\n    QString pathHeight(staResourcesPath + \"/\" + \"data/maps/ESA0HEIGHT.TXT\");\n\n    QFile fileHeight(pathHeight);\n\n    if(!fileHeight.exists())\n        qDebug()<<\" file error\";\n    fileHeight.open(QIODevice::ReadOnly);\n\n    QTextStream heightStream(&fileHeight);\n    double heightPoint;\n\n    int z1=0;\n    int target1=i1+j1;\n\n    for(z1; z1<target1; z1++)\n        heightStream>>heightPoint;\n\n    double hr;\n\n    hr=heightPoint+0.36; //in Km\n\n    //This step is working properly\n\n    ///////////////////////////////////////////STEP 4: Get the rainfall rate exceeded for 0.01% of an average year//////////////////////////////////////////////\n\n    QString pathLatRain(staResourcesPath + \"/\" + \"data/maps/ESARAIN_LAT_v5.TXT\");\n\n    QFile fileLatRain(pathLatRain);\n\n    if(!fileLatRain.exists())\n        qDebug()<<\" file error\";\n    fileLatRain.open(QIODevice::ReadOnly);\n\n    QTextStream latStreamRain(&fileLatRain);\n    double latPointRain;\n\n    int i2=0;\n    do\n    {\n        latStreamRain>>latPointRain;\n        i2++;\n    }while(latPointRain>latitude);\n\n    fileLatRain.close();\n\n    if(longitude<0)\n        longitude=longitude+360;\n\n    QString pathLonRain(staResourcesPath + \"/\" + \"data/maps/ESARAIN_LON_v5.TXT\");\n\n    QFile fileLonRain(pathLonRain);\n\n    if(!fileLonRain.exists())\n        qDebug()<<\" file error\";\n    fileLonRain.open(QIODevice::ReadOnly);\n\n    QTextStream lonStreamRain(&fileLonRain);\n    double lonPointRain;\n\n    int k2=0;\n    for(k2; k2<i2; k2++)\n        lonStreamRain>>lonPointRain;\n\n    int j2=0;\n    do\n    {\n        lonStreamRain>>lonPointRain;\n        j2++;\n\n    } while(lonPointRain<longitude);\n    fileLonRain.close();\n\n\n    QString pathRain001(staResourcesPath + \"/\" + \"data/maps/R0_01.TXT\");\n\n    QFile fileRain001(pathRain001);\n\n    if(!fileRain001.exists())\n        qDebug()<<\" file error\";\n    fileRain001.open(QIODevice::ReadOnly);\n\n    QTextStream rain001Stream(&fileRain001);\n    double r001;\n\n    int t=0;\n    int target2=i2+j2;\n\n    for(t; t<target2; t++)\n        rain001Stream>>r001;\n\n\n    //////////////////////////////////////////STEP 2, 3: Get the slant-path range length, below the rain height and its projection////////////////////////////////////////////\n\n    //////////////////////////////////////////STEP 5: get the Specific Attenuation in dB/Km according to ITU-R P.838-3////////////////////////////////////////////////////////\n\n    ///////////////////////////////////////// STEP 6: Calculate the horizontal reduction factor for 0.01% of the time ////////////////////////////////////////////////////////\n\n    //////////////////////////////////////////STEP 7: Calculate the vertical reduction factor for 0.01% of the time //////////////////////////////////////////////////////////\n\n    //////////////////////////////////////////STEP 8: The effective path length //////////////////////////////////////////////////////////\n\n    //////////////////////////////////////////STEP 9: The predicted attenuation exceeded for 0.01% of an average year //////////////////////////////////////////////////////////\n\n    //////////////////////////////////////////STEP 10: Other percentages //////////////////////////////////////////////////////////////////////////////////////////////////////\n\n    double elevationAngle;\n    double finalAtt;\n\n    for(int counter=0; counter<numberOfRows; counter++)\n    {\n        double t=m_propagatedScenario->spaceObjects().at(m_indexSC)->mission().at(m_indexMA)->trajectorySampleTime(counter);\n\n        if(tracking==true)\n        {\n            elevationAngle=m_propagatedScenario->groundObjects().at(m_indexGS)->elevationAngle(m_propagatedScenario->spaceObjects().at(m_indexSC),t);\n        }\n        else if(tracking==false)\n        {\n\n            if(m_flagTX==false && m_flagRX==true)\n                elevationAngle=m_transmitter->Transmitter()->PointingDirection()->elevation();\n            else if(m_flagRX==false && m_flagTX==true)\n                elevationAngle=m_receiver->Receiver()->PointingDirection()->elevation();\n\n        } //This takes the elevation angle of the participant that is on the ground station. Satellites cannot carry antennas with tracking systems since there is not attitude control in STA\n\n        bool visibility;\n        if(m_propagatedScenario->groundObjects().at(m_indexGS)->elevationAngle(m_propagatedScenario->spaceObjects().at(m_indexSC),t)>=5.0*DEG2RAD)\n        {\n            visibility=true;\n        }\n        else\n        {\n            visibility=false;\n        }\n\n        double gsAlt=m_propagatedScenario->groundObjects().at(m_indexGS)->altitude;\n        gsAlt=gsAlt/1000;//Now gsAlt is in Km\n\n        if(visibility==true )\n        {\n            raincheck=m_environment->Rain()->RainChoice();\n\n            if(raincheck==\"true\")\n            {\n                double slantPath;\n                slantPath=(hr-gsAlt)/sin(elevationAngle);\n\n                double Lg=slantPath*cos(elevationAngle); //Horizontal projection of the slant path length\n\n                //////////////////////// This belongs to step 5 //////////////////////\n                double ktot=(kh+kv+((kh-kv)*pow(cos(elevationAngle),2)*cos(2*tilt)))/2;\n                double alphatot=((kh*alphah)+(kv*alphav)+((kh*alphah-kv*alphav)*pow(cos(elevationAngle),2)*cos(2*tilt)))/(2*ktot);\n                double specAttenuation= ktot*pow(r001, alphatot); //Since it is specific attenuation, the units are dB/Km.\n\n                ////////////////////////// This belongs to step 6 /////////////////////\n                double horiz_reduc=1/(1+(0.78*sqrt(Lg*specAttenuation/frequency))-(0.38*(1-exp(-2*Lg))));\n\n                ////////////////////////// This belongs to step 7 ////////////////////////\n                double zeta=atan((hr-gsAlt)/(Lg*horiz_reduc));\n\n                double Lr;\n                double chi;\n\n                if(zeta>elevationAngle)\n                    Lr=(Lg*horiz_reduc)/cos(elevationAngle);\n                else\n                    Lr=slantPath;\n\n                if(fabs(latitude)<36)\n                    chi=36-fabs(latitude);\n                else\n                    chi=0;\n\n\n                chi=chi*DEG2RAD;\n                double ver_reduc=1/(1+(sqrt(sin(elevationAngle))*((31*(1-exp(-(elevationAngle/(1+chi))))*(sqrt((Lr*specAttenuation))/pow(frequency, 2)))-0.45)));\n\n                ////////////////////////// This belongs to step 8 /////////////////////////\n                double Le=Lr*ver_reduc;\n\n                ////////////////////////// This belongs to step 9 /////////////////////////\n                double estimatedAtt001=specAttenuation*Le;\n\n                //////////////////////// This belongs to step 10 //////////////////////////\n                double beta;\n                double percentage=m_environment->Rain()->PercentageExceededLimit();\n                if(percentage>1 || fabs(latitude)>=36)\n                    beta=0;\n                else if(percentage<1 && fabs(latitude)<36 && elevationAngle>=(25*DEG2RAD))\n                    beta=-0.005*(fabs(latitude)-36);\n                else\n                    beta=-0.005*(fabs(latitude)-36)+1.8-(4.25*sin(elevationAngle));\n\n                eachRainAttenuation = estimatedAtt001*pow((percentage/0.01),(-(0.655+(0.033*log(percentage))-(0.045*log(estimatedAtt001))-(beta*sin(elevationAngle)*(1-percentage))))); //In dB!!\n\n            }\n            else if(raincheck==\"false\")\n            {\n                eachRainAttenuation = 0;\n            }\n\n            myRainAttenuationList.append(eachRainAttenuation);\n\n        }\n        else\n        {\n            myRainAttenuationList.append(0.0);\n        }\n\n        \n    }\n\n    return myRainAttenuationList;\n} ///////////////////////////////////////// end of the method //////////////////////////////////////////\n\n\n\ndouble CommAnalysis::SystemTempCalculations()\n{\n\n    double antennaTemp, skyTemp, groundTemp, rainAttenuation, systemTemp, equivalentTemp, rxFigureNoise, rxFeederLoss, thermoTempFeeder;\n\n    rxFigureNoise=pow(10, m_receiver->Receiver()->SystemTemperature()->RxNoiseFigure()/10);//Now in natural units\n    rxFeederLoss=pow(10, m_receiver->Receiver()->FeederLossRx()/10); //Now in natural units\n    thermoTempFeeder=m_receiver->Receiver()->SystemTemperature()->ThermoFeeder();\n\n    double elevationAngle;\n    antennaTempChoice=m_receiver->Receiver()->SystemTemperature()->choiceTantenna();\n\n    for (int j=0; j<elevationAngleList.length(); j++){\n\n        elevationAngle=elevationAngleList[j];\n        if(antennaTempChoice==\"calculated\")\n        {\n               if(m_flagRX==true)\n                    antennaTemp=290;\n                else if(m_flagRX==false)\n                {\n\n                        skyTemp=4+275*(1-pow(10,(-atmosphericAttList[j]/10)));\n                        rainAttenuation=pow(10, rainAttenuationList[j]/10);\n\n                        if (elevationAngle<=-10*DEG2RAD){ groundTemp=290;}\n                        else if (elevationAngle>-10*DEG2RAD && elevationAngle<=0*DEG2RAD){ groundTemp=150;}\n                        else if (elevationAngle>0*DEG2RAD && elevationAngle<=10*DEG2RAD){ groundTemp=50;}\n                        else if (elevationAngle>10*DEG2RAD && elevationAngle<=90*DEG2RAD){ groundTemp=10;}\n\n                        antennaTemp=(skyTemp/rainAttenuation)+groundTemp+275*(1-(1/rainAttenuation));\n\n                 }\n         }else if(antennaTempChoice==\"constant\"){\n             antennaTemp=m_receiver->Receiver()->SystemTemperature()->Tantenna();\n         }\n        antennaTempList.append(antennaTemp);\n\n        equivalentTemp=290*(rxFigureNoise-1);\n\n    systemTemp=(antennaTemp/rxFeederLoss)+equivalentTemp+(thermoTempFeeder*(1-(1/rxFeederLoss))); //In Kelvin\n    systemTempList.append(systemTemp);\n\n    }\n\n  return systemTemp;\n} ///////////////////////////////////////// end of the method //////////////////////////////////////////\n\n\n\ndouble CommAnalysis::Modulations(double EbNo)\n{ //the EbNo is passed in dB\n\n    QString modType=m_transmitter->Transmitter()->Modulation()->ModulationType();\n    double ber, a, b;\n\n    if(modType==QString(\"BPSK\"))\n    {\n        a=sqrt(EbNo);\n        b=erfc(a);\n        ber=0.5*b;\n    }\n    else if (modType==\"DE-BPSK\")\n    {\n        a=sqrt(EbNo);\n        ber=erfc(a);\n    }\n    else if (modType==\"D-BPSK\")\n    {\n        a=exp((-EbNo));\n        ber=0.5*a;\n    }\n    else if (modType==\"QPSK\")\n    {\n        a=sqrt(EbNo);\n        b=erfc(a);\n        ber=0.5*b;\n    }\n    else if (modType==\"DE-QPSK\")\n    {\n        a=sqrt(EbNo);\n        ber=erfc(a);\n    }\n    else if (modType==\"D-QPSK\")\n    {\n        a=exp((-EbNo));\n        ber=0.5*a;\n    }\n    else if (modType==\"OQPSK\")\n    {\n        a=sqrt(EbNo);\n        b=erfc(a);\n        ber=0.5*b;\n    }\n\n\n    return ber;\n} ///////////////////////////////////////// end of the method //////////////////////////////////////////\n\n\n\nvoid CommAnalysis::CommReports()\n{\n    // Find out now the correct path of the files\n    QString staResourcesPath = findDataFolder();\n\n    QString firstFile = staResourcesPath + \"/\" + \"reportComm1.txt\";\n    QString secondFile = staResourcesPath + \"/\" + \"reportComm2.txt\";\n    QString thirdFile = staResourcesPath + \"/\" + \"reportComm3.txt\";\n\n    QFile reportComm1(firstFile);\n    QFile reportComm2(secondFile);\n    QFile reportComm3(thirdFile);\n\n    //qDebug() << firstFile << endl;\n    //qDebug() << secondFile << endl;\n    //qDebug() << thirdFile << endl;\n\n    reportComm1.open(QIODevice::WriteOnly|QIODevice::ReadWrite);\n    reportComm2.open(QIODevice::WriteOnly|QIODevice::ReadWrite);\n    reportComm3.open(QIODevice::WriteOnly|QIODevice::ReadWrite);\n\n    QTextStream streamReportComm1(&reportComm1);\n    QTextStream streamReportComm2(&reportComm2);\n    QTextStream streamReportComm3(&reportComm3);\n\n    streamReportComm1.setRealNumberPrecision(16);\n    streamReportComm2.setRealNumberPrecision(16);\n    streamReportComm3.setRealNumberPrecision(16);\n\n    streamReportComm1<<\"MJD\"<<\"\\t\"<<\"EIRP\"<<\"\\t\"<<\"Rcvd.Freq.\"<<\"\\t\"<<\"Doppler Shift\"<<\"\\t\"<<\"Rcvd. Power\"<<\"\\t\"<<\"Flux Density\"<<\"\\t\"<<\"OverlapBWfactor\"<<endl;\n    streamReportComm2<<\"MJD\"<<\"\\t\"<<\"FSL\"<<\"\\t\"<<\"OxLoss\"<<\"\\t\"<<\"WvLoss\"<<\"\\t\"<<\"RainLoss\"<<\"\\t\"<<\"AtmosLoss\"<<\"\\t\"<<\"PropLoss\"<<endl;\n    streamReportComm3<<\"MJD\"<<\"\\t\"<<\"G/Y\"<<\"\\t\"<<\"C/No\"<<\"\\t\"<<\"C/N\"<<\"\\t\"<<\"Eb/No\"<<\"\\t\"<<\"BER\"<<endl;\n\n    // Starting now the calculations\n    double frequency;\n\n    if(m_flagTX==false && m_flagRX==true)\n    {\n        frequency = m_transmitter->Budget()->FrequencyBand()/1000000000;\n    }\n    else if(m_flagRX==false && m_flagTX==true)\n    {\n        frequency = m_receiver->Budget()->FrequencyBand()/1000000000;\n    }\n\n    /////////////// FIXED VALUES THAT COME FROM TRANSMITTER AND RECEIVER //////////////////////\n    double potTxDb = 10*log10(m_transmitter->Transmitter()->TransmittingPower());\n    double gainTxDb = m_transmitter->Transmitter()->EMproperties()->GainMax();\n    double txFeederLossDb = m_transmitter->Transmitter()->FedderLossTx();\n    double txDepointingLossDb = m_transmitter->Transmitter()->DepointingLossTx();\n\n    double polLoss, rcvdPower, fluxDensity;\n\n    if (m_transmitter->Transmitter()->EMproperties()->Polarisation()==\"rightCircular\" && m_receiver->Receiver()->EMproperties()->Polarisation()==\"leftCircular\")\n        polLoss=20;//in dB\n    else if (m_receiver->Receiver()->EMproperties()->Polarisation()==\"rightCircular\" && m_transmitter->Transmitter()->EMproperties()->Polarisation()==\"leftCircular\")\n        polLoss=20;//in dB\n    else\n    {\n        double txAngle = m_transmitter->Transmitter()->EMproperties()->TiltAngle();\n        double rxAngle = m_receiver->Receiver()->EMproperties()->TiltAngle();\n        polLoss = -20*(log10(cos(fabs(txAngle-rxAngle))));\n    }\n\n    double gainRxDb = m_receiver->Receiver()->EMproperties()->GainMax();\n    double rxFeederLossDb = m_receiver->Receiver()->FeederLossRx();\n    double rxDepointingLossDb = m_receiver->Receiver()->DepointingLossRx();\n    double transmittedFrequency = m_transmitter->Budget()->FrequencyBand();\n\n    //Calculate some fix parameters\n    double eirp = potTxDb + gainTxDb - (txFeederLossDb + txDepointingLossDb);  //The units are in dBW\n    double txBW = m_transmitter->Transmitter()->EMproperties()->BandWidth();\n    double rxBW = m_receiver->Receiver()->EMproperties()->BandWidth();\n    double txDataRate = m_transmitter->Transmitter()->Modulation()->DataRate();\n\n    double overLapBWfactor;\n\n    if(txBW>=rxBW)\n        overLapBWfactor=rxBW/txBW;\n    else if(rxBW>txBW)\n        overLapBWfactor=txBW/rxBW;\n\n    double propLoss;\n    double carrierToNoise;\n    double EbNo, BER;\n    QList<double> rcvdFrequencyList;\n    QList<double> pathLossList;\n    QList<double> GoverTList;\n\n    double myJulianDay;\n    int myIndex;\n    int p;\n    int myNumberOfRows = m_propagatedScenario->spaceObjects().at(m_indexSC)->mission().at(m_indexMA)->trajectorySampleCount();  qDebug() << \"myNumberOfRows\" << myNumberOfRows << endl;\n\n    double receiverFrequency, receiverPower, myGoverT, pathLoss, carrierToNoiseDensity;\n    double theRange;\n\n    // Get the list of all Doppler shifts:\n    QList<double> myRealDopplerShiftList = CommAnalysis::getDopplerShiftList(myNumberOfRows);  qDebug() << \"myRealDopplerShiftListLenght\" << myRealDopplerShiftList.length() << endl;\n    // Get the list of all free space losses:\n    QList<double> myRealFreeSpaceLossList = CommAnalysis::getFreeSpaceLossList(myNumberOfRows);\n    double oxAttenuation = CommAnalysis::OxygenSpecificAttenuation(frequency);\n    double wpAttenuation = CommAnalysis::WaterVapourSpecificAttenuation(frequency, m_propagatedScenario->groundObjects().at(m_indexGS)->latitude,m_propagatedScenario->groundObjects().at(m_indexGS)->longitude);\n    QList<double> myRealAtmosphericAttenuationList = CommAnalysis::getAtmosphericAttenuation(frequency, wpAttenuation, oxAttenuation, myNumberOfRows); qDebug() << \"myRealAtmosphericAttenuationListLenght\" << myRealAtmosphericAttenuationList.length() << endl;\n    QList<double> myRealRainAttenuationList = CommAnalysis::getRainAttenuation(m_propagatedScenario->groundObjects().at(m_indexGS)->latitude,m_propagatedScenario->groundObjects().at(m_indexGS)->longitude, myNumberOfRows);  qDebug() << \"myRealRainAttenuationListLengh\" << myRealRainAttenuationList.length() << endl;\n    double SystemTempCalculations = CommAnalysis::SystemTempCalculations();\n\n    for(myIndex=0; myIndex<myNumberOfRows; myIndex++)\n    {\n        myJulianDay = m_propagatedScenario->spaceObjects().at(m_indexSC)->mission().at(m_indexMA)->trajectorySampleTime(myIndex);\n        receiverFrequency = transmittedFrequency + myRealDopplerShiftList[myIndex];  //qDebug() << receiverFrequency << endl;\n        theRange = m_propagatedScenario->groundObjects().at(m_indexGS)->getRange(m_propagatedScenario->spaceObjects().at(m_indexSC), myIndex) * 1000;\n        fluxDensity = eirp - (10 * log10(4 * theRange * theRange * Pi)); //qDebug() << fluxDensity << endl;\n        pathLoss = myRealRainAttenuationList[myIndex] + myRealAtmosphericAttenuationList[myIndex] + myRealFreeSpaceLossList[myIndex];\n        //myGoverT = gainRxDb - (rxFeederLossDb + rxDepointingLossDb + pathLoss) - (10*log10(systemTempList[myIndex]));  //The units are dBHz\n        myGoverT = gainRxDb - (rxFeederLossDb + rxDepointingLossDb + pathLoss) - (10*log10(1.0));\n        carrierToNoiseDensity = eirp - pathLoss + myGoverT + 228.6 + (10*log10(overLapBWfactor));  //The units are dBHz, the 228.6 factor is in dBW/HzK and it is the Bolztman constant in decibels\n        receiverPower = eirp - propLoss;\n        carrierToNoise = carrierToNoiseDensity - (10*log10(txBW));\n        BER = CommAnalysis::Modulations(EbNo);\n\n        streamReportComm1 << myJulianDay << \"\\t\" << eirp << \"\\t\" << receiverFrequency << \"\\t\" << myRealDopplerShiftList[myIndex] << \"\\t\" << receiverPower << \"\\t\" << fluxDensity << \"\\t\" << overLapBWfactor << endl;\n        //streamReportComm2 << myJulianDay << \"\\t\" << myRealFreeSpaceLossList[myIndex] << \"\\t\" << oxAttList[p] << \"\\t\" << wvAttList[myIndex] << \"\\t\" << myRealRainAttenuationList[myIndex] << \"\\t\" << myRealAtmosphericAttenuationList[myIndex] << \"\\t\" << pathLoss << endl;\n        streamReportComm2 << myJulianDay << \"\\t\" << myRealFreeSpaceLossList[myIndex] << \"\\t\" << 0.0 << \"\\t\" << 0.0 << \"\\t\" << myRealRainAttenuationList[myIndex] << \"\\t\" << myRealAtmosphericAttenuationList[myIndex] << \"\\t\" << pathLoss << endl;\n        streamReportComm3 << myJulianDay << \"\\t\" << myGoverT << \"\\t\" << carrierToNoiseDensity << \"\\t\" << carrierToNoise << \"\\t\" << EbNo << \"\\t\" << BER <<endl;\n    }\n\n    reportComm1.close();\n    reportComm2.close();\n    reportComm3.close();\n}\n", "meta": {"hexsha": "62001f8f78742811f994c9235b6b5e9f3755de54", "size": 35927, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "sta-src/Coverage/commanalysis.cpp", "max_stars_repo_name": "hoehnp/SpaceDesignTool", "max_stars_repo_head_hexsha": "9abd34048274b2ce9dbbb685124177b02d6a34ca", "max_stars_repo_licenses": ["IJG"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2018-09-05T12:41:59.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-01T05:34:23.000Z", "max_issues_repo_path": "sta-src/Coverage/commanalysis.cpp", "max_issues_repo_name": "hoehnp/SpaceDesignTool", "max_issues_repo_head_hexsha": "9abd34048274b2ce9dbbb685124177b02d6a34ca", "max_issues_repo_licenses": ["IJG"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2015-02-07T19:09:21.000Z", "max_issues_repo_issues_event_max_datetime": "2015-08-14T03:15:42.000Z", "max_forks_repo_path": "sta-src/Coverage/commanalysis.cpp", "max_forks_repo_name": "hoehnp/SpaceDesignTool", "max_forks_repo_head_hexsha": "9abd34048274b2ce9dbbb685124177b02d6a34ca", "max_forks_repo_licenses": ["IJG"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2015-03-25T15:50:31.000Z", "max_forks_repo_forks_event_max_datetime": "2017-12-06T12:16:47.000Z", "avg_line_length": 39.0935799782, "max_line_length": 477, "alphanum_fraction": 0.6058396192, "num_tokens": 9283, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7931059511841119, "lm_q2_score": 0.411110869232168, "lm_q1q2_score": 0.3260544769845056}}
{"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\n#include <boost/python.hpp>\n#include <boost/graph/betweenness_centrality.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\ntemplate <class Graph, class EdgeBetweenness, class VertexBetweenness>\nvoid normalize_betweenness(const Graph& g,\n                           EdgeBetweenness edge_betweenness,\n                           VertexBetweenness vertex_betweenness,\n                           size_t n)\n{\n    double vfactor = (n > 2) ? 1.0/((n-1)*(n-2)) : 1.0;\n    double efactor = (n > 1) ? 1.0/(n*(n-1)) : 1.0;\n    if (std::is_convertible<typename graph_traits<Graph>::directed_category,\n                            undirected_tag>::value)\n    {\n        vfactor *= 2;\n        efactor *= 2;\n    }\n\n    int i, N = num_vertices(g);\n    #pragma omp parallel for default(shared) private(i)   \\\n        schedule(runtime) if (N > 100)\n    for (i = 0; i < N; ++i)\n    {\n        typename graph_traits<Graph>::vertex_descriptor v = vertex(i, g);\n        if (v == graph_traits<Graph>::null_vertex())\n            continue;\n        put(vertex_betweenness, v, vfactor * get(vertex_betweenness, v));\n    }\n\n    typename graph_traits<Graph>::edge_iterator e, e_end;\n    for (tie(e, e_end) = edges(g); e != e_end; ++e)\n    {\n        put(edge_betweenness, *e, efactor * get(edge_betweenness, *e));\n    }\n}\n\nstruct get_betweenness\n{\n    typedef void result_type;\n    template <class Graph, class EdgeBetweenness, class VertexBetweenness>\n    void operator()(Graph& g,\n                    GraphInterface::vertex_index_map_t index_map,\n                    EdgeBetweenness edge_betweenness,\n                    VertexBetweenness vertex_betweenness,\n                    bool normalize, size_t n) const\n    {\n        vector<vector<typename graph_traits<Graph>::edge_descriptor> >\n            incoming_map(num_vertices(g));\n        vector<size_t> distance_map(num_vertices(g));\n        vector<typename property_traits<VertexBetweenness>::value_type>\n            dependency_map(num_vertices(g));\n        vector<size_t> path_count_map(num_vertices(g));\n        brandes_betweenness_centrality\n            (g, vertex_betweenness, edge_betweenness,\n             make_iterator_property_map(incoming_map.begin(), index_map),\n             make_iterator_property_map(distance_map.begin(), index_map),\n             make_iterator_property_map(dependency_map.begin(), index_map),\n             make_iterator_property_map(path_count_map.begin(), index_map),\n             index_map);\n        if (normalize)\n            normalize_betweenness(g, edge_betweenness, vertex_betweenness, n);\n    }\n};\n\nstruct get_weighted_betweenness\n{\n    typedef void result_type;\n    template <class Graph, class EdgeBetweenness, class VertexBetweenness,\n              class VertexIndexMap>\n        void operator()(Graph& g, VertexIndexMap vertex_index,\n                        EdgeBetweenness edge_betweenness,\n                        VertexBetweenness vertex_betweenness,\n                        boost::any weight_map, bool normalize,\n                        size_t n, size_t max_eindex) const\n    {\n        vector<vector<typename graph_traits<Graph>::edge_descriptor> >\n            incoming_map(num_vertices(g));\n        vector<typename property_traits<EdgeBetweenness>::value_type>\n            distance_map(num_vertices(g));\n        vector<typename property_traits<VertexBetweenness>::value_type>\n            dependency_map(num_vertices(g));\n        vector<size_t> path_count_map(num_vertices(g));\n\n        typename EdgeBetweenness::checked_t weight =\n            any_cast<typename EdgeBetweenness::checked_t>(weight_map);\n\n        brandes_betweenness_centrality\n            (g, vertex_betweenness, edge_betweenness,\n             make_iterator_property_map(incoming_map.begin(), vertex_index),\n             make_iterator_property_map(distance_map.begin(), vertex_index),\n             make_iterator_property_map(dependency_map.begin(), vertex_index),\n             make_iterator_property_map(path_count_map.begin(), vertex_index),\n             vertex_index, weight.get_unchecked(max_eindex+1));\n        if (normalize)\n            normalize_betweenness(g, edge_betweenness, vertex_betweenness, n);\n    }\n};\n\nvoid betweenness(GraphInterface& g, boost::any weight,\n                 boost::any edge_betweenness,\n                 boost::any vertex_betweenness,\n                 bool normalize)\n{\n    if (!belongs<edge_floating_properties>()(edge_betweenness))\n        throw ValueException(\"edge property must be of floating point value\"\n                             \" type\");\n\n    if (!belongs<vertex_floating_properties>()(vertex_betweenness))\n        throw ValueException(\"vertex property must be of floating point value\"\n                             \" type\");\n\n    if (!weight.empty())\n    {\n        run_action<>()\n            (g, std::bind<>(get_weighted_betweenness(),\n                            std::placeholders::_1, g.GetVertexIndex(),\n                            std::placeholders::_2,\n                            std::placeholders::_3, weight, normalize,\n                            g.GetNumberOfVertices(), g.GetMaxEdgeIndex()),\n             edge_floating_properties(),\n             vertex_floating_properties())\n            (edge_betweenness, vertex_betweenness);\n    }\n    else\n    {\n        run_action<>()\n            (g, std::bind<void>(get_betweenness(), std::placeholders::_1,\n                                g.GetVertexIndex(), std::placeholders::_2,\n                                std::placeholders::_3, normalize,\n                                g.GetNumberOfVertices()),\n             edge_floating_properties(),\n             vertex_floating_properties())\n            (edge_betweenness, vertex_betweenness);\n    }\n}\n\nstruct get_central_point_dominance\n{\n    template <class Graph, class VertexBetweenness>\n    void operator()(Graph& g, VertexBetweenness vertex_betweenness, double& c)\n        const\n    {\n        c = double(central_point_dominance(g, vertex_betweenness));\n    }\n};\n\ndouble central_point(GraphInterface& g,\n                     boost::any vertex_betweenness)\n{\n    double c = 0.0;\n    run_action<graph_tool::detail::never_reversed>()\n        (g, std::bind<>(get_central_point_dominance(), std::placeholders::_1,\n                        std::placeholders::_2, std::ref(c)),\n         vertex_scalar_properties()) (vertex_betweenness);\n    return c;\n}\n\nvoid export_betweenness()\n{\n    using namespace boost::python;\n    def(\"get_betweenness\", &betweenness);\n    def(\"get_central_point_dominance\", &central_point);\n}\n", "meta": {"hexsha": "d46b0bcbb4f4d848be699640ebd7161877fe21b8", "size": 7412, "ext": "cc", "lang": "C++", "max_stars_repo_path": "graph-tool/src/graph/centrality/graph_betweenness.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/centrality/graph_betweenness.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/centrality/graph_betweenness.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.8062827225, "max_line_length": 78, "alphanum_fraction": 0.6350512682, "num_tokens": 1548, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6370307944803831, "lm_q2_score": 0.5117166047041654, "lm_q1q2_score": 0.32597923524349864}}
{"text": "// Copyright 2021 University of Adelaide\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//    http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n#include \"ChisquareTest.h\"\n#include \"Analysis.h\"\n#include \"Trace.h\"\n#include \"Variant.h\"\n#include \"WorkContext.h\"\n#include \"TraceUtils.h\"\n#include \"AnalysisOuput.h\"\n#include <vector>\n#include <string>\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n#include <boost/math/distributions/chi_squared.hpp>\n\ntypedef double real_t;\n\nstruct lv_chisquare_hist_t\n{\n    std::vector<int> bins;\n};\n\nstruct chisquare_test_priv_t\n{\n    std::vector<lv_chisquare_hist_t> hists[2];\n    std::vector<lv_chisquare_hist_t> copyhists[2];\n    int copydone[2];\n    int traces[2];\n    double min;\n    double normdiv;\n    int nbins;\n    traceinfo_t ti;\n    traceinfo_t tout;\n    int m;\n    analysis_output_t *ao;\n};\nchisquare_test_t::chisquare_test_t(const chisquare_test_t&) = default;\nchisquare_test_t::chisquare_test_t(chisquare_test_t&&) = default;\nchisquare_test_t::chisquare_test_t()\n{\n    _pimpl.init();\n}\n\nvoid chisquare_test_t::init(const traceinfo_t *traceinfo, \n        analysis_output_t* output, const analysis_opts_t& opts)\n{\n    _pimpl.init();\n    // make init size non zero\n    int ns = (int) traceinfo->nsamples;\n    _pimpl.get()->hists[0].resize(ns);\n    _pimpl.get()->hists[1].resize(ns);\n    _pimpl.get()->nbins = wc_gopts_get(\"chisq_bin_count\", variant_t(256)).get_int();\n    _pimpl.get()->min = wc_gopts_get(\"chisq_trace_min\").get_double();\n    _pimpl.get()->normdiv = wc_gopts_get(\"chisq_trace_div\").get_double();\n    _pimpl.get()->ti = *traceinfo;\n    _pimpl.get()->traces[0] = 0;\n    _pimpl.get()->traces[1] = 0;\n    _pimpl.get()->copydone[0] = 0;\n    _pimpl.get()->copydone[1] = 0;\n    _pimpl.get()->m = wc_gopts_get(\"at_each_ntraces\").get_int();\n    _pimpl.get()->ao = output;\n\n    traceinfo_t tout = *traceinfo;\n    tout.ntraces = tout.ntraces/_pimpl.get()->m;\n    tout.ndata = 0;\n    tout.nterms = 1;\n    output->init(&tout);\n\n    _pimpl.get()->tout = tout;\n    // init bins with 0\n    for(int i=0;i<2;i++)\n    {\n        for(int j=0;j<ns;j++)\n        {\n            _pimpl.get()->hists[i][j].bins.resize(_pimpl.get()->nbins);\n            for(int k=0;k<_pimpl.get()->nbins;k++) \n            {\n                _pimpl.get()->hists[i][j].bins[k] = 0;\n            }\n        }\n    }\n}\nvoid chisquare_test_t::trace_submit(const trace_t* trace)\n{\n    uint32_t g = traceutils_group(trace);\n    std::vector<lv_chisquare_hist_t>& hists = _pimpl.get()->hists[g];\n    auto ns = (int) trace->_traceinfo.nsamples;\n    auto nbins = _pimpl.get()->nbins;\n    _pimpl.get()->traces[g]++;\n    // Add values to bins\n    for(int i=0;i<ns;i++) \n    {\n        int bin = (int)round((trace->_samples[i] - _pimpl.get()->min)* nbins / _pimpl.get()->normdiv);\n        //int bin = round(trace->_samples[i] * nbins);\n        //LogInfo(\"xx%d\\n\", bin);\n        if(bin < 0)\n            bin = 0;\n        if(bin >= nbins)\n            bin = nbins-1;\n        hists[i].bins[bin]++;\n    }\n    auto m = _pimpl.get()->m;\n    if ((_pimpl.get()->traces[g] % m) == 0)\n    {\n        _pimpl.get()->copyhists[g] = hists;\n        _pimpl.get()->copydone[g] = _pimpl.get()->traces[g];\n        LogInfo(\"ff %d %d\\n\", g,_pimpl.get()->traces[g]);\n    }\n\n    if ((_pimpl.get()->copydone[0] == _pimpl.get()->copydone[1]) && \n            (_pimpl.get()->copydone[0] > 0))\n    {\n        trace_t restrace;\n        restrace.init(&_pimpl.get()->tout);\n\n        for (int i=0;i<ns;i++)\n        {\n            restrace._samples[i] = calc_chisq_at(i);\n        }\n        _pimpl.get()->ao->on_result_trace(&restrace);\n\n        _pimpl.get()->copydone[0] = 0;\n        _pimpl.get()->copydone[1] = 0;\n    }\n\n}\ndouble chisquare_test_t::calc_chisq_at(int index)\n{\n    auto nbins = _pimpl.get()->nbins;\n  real_t F[2][nbins];\n  real_t E[2][nbins];\n\n  for(int i=0;i<nbins;i++) \n  {\n      F[0][i] = _pimpl.get()->copyhists[0][index].bins[i];\n      F[1][i] = _pimpl.get()->copyhists[1][index].bins[i];\n  }\n\n  //Calculate expected frequency\n  for(int i=0;i<2;i++)\n  {\n    for(int j=0;j<nbins;j++) \n    {\n      real_t val = 0;\n      for(int k=0;k<nbins;k++)\n      {\n        val += F[i][k];\n      }\n      val *= F[0][j] + F[1][j];\n      E[i][j] = val / (2 *_pimpl.get()->copydone[i]);\n    }\n  }\n  // Calculate x and v\n  real_t x = 0;\n  for(int i=0;i<2;i++)\n  {\n    for(int j=0;j<nbins;j++)\n    {\n      real_t temp;\n      temp = F[i][j] - E[i][j];\n      if (E[i][j] != 0.0)\n          x += (temp*temp) / E[i][j];\n    }\n  }\n  int v = 1 * (nbins-1);\n  boost::math::chi_squared chi_dist(v);\n  return -1 * log10( 1 - boost::math::cdf(chi_dist, x));\n}\nvoid chisquare_test_t::finit()\n{\n    _pimpl.get()->ao->finit();\n}\n\nchisquare_test_t::~chisquare_test_t()\n{\n}\n", "meta": {"hexsha": "b2174570a4b7b8eff5dffb7813239dbf2278fcc0", "size": 5177, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/ChisquareTest.cpp", "max_stars_repo_name": "0xADE1A1DE/tracetools", "max_stars_repo_head_hexsha": "5eaa3aa84a5781bf7997e0539da1b1f1b3666821", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2021-12-16T11:12:27.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-30T04:16:39.000Z", "max_issues_repo_path": "src/ChisquareTest.cpp", "max_issues_repo_name": "0xADE1A1DE/tracetools", "max_issues_repo_head_hexsha": "5eaa3aa84a5781bf7997e0539da1b1f1b3666821", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/ChisquareTest.cpp", "max_forks_repo_name": "0xADE1A1DE/tracetools", "max_forks_repo_head_hexsha": "5eaa3aa84a5781bf7997e0539da1b1f1b3666821", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-12-16T11:38:42.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-17T14:02:41.000Z", "avg_line_length": 27.2473684211, "max_line_length": 102, "alphanum_fraction": 0.5926212092, "num_tokens": 1640, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6893056295505783, "lm_q2_score": 0.47268347662043286, "lm_q1q2_score": 0.3258233814300035}}
{"text": "#include <algorithm>\n#include <cstring>\n#include <limits>\n#include <memory>\n#include <queue>\n\n#include <android/log.h>\n\n#include <boost/foreach.hpp>\n#include <boost/integer_traits.hpp>\n\n#include <tbb/blocked_range2d.h>\n#include <tbb/parallel_for.h>\n#include <tbb/task_scheduler_init.h>\n\n#include \"body_parts_recognizer.h\"\n#include \"cloud.h\"\n#include \"stopwatch.h\"\n\nconst Depth BACKGROUND_DEPTH = std::numeric_limits<Depth>::max();\n\ntemplate <typename Format> void\napplyThreshold(ChannelRef<Format> & channel, Format threshold, Format bgValue)\n{\n  for (int i = 0; i < channel.size; ++i)\n    if (channel.data[i] > threshold)\n      channel.data[i] = bgValue;\n}\n\ntemplate <typename Format> Format\nselectThreshold(const ChannelRef<Format> & channel)\n{\n  // We use Otsu's method here.\n  const int num_bins = boost::integer_traits<Format>::const_max + 1;\n  int bins[num_bins] = { 0 };\n  int count = 0;\n\n  for (int i = 0; i < channel.size; ++i)\n    if (channel.data[i] != BACKGROUND_DEPTH)\n    {\n      ++bins[channel.data[i]];\n      ++count;\n    }\n\n  double scale = 1. / count;\n  double mu = 0;\n\n  for (int i = 0; i < num_bins; ++i) mu += i * bins[i] * scale;\n\n  double mu1 = 0, mu2, p1 = 0, p2;\n  double max_var = 0;\n  Format thresh = 0;\n\n  for (int i = 0; i < num_bins; ++i)\n  {\n    p1 += bins[i] * scale;\n    p2 = 1 - p1;\n\n    mu1 += i * bins[i] * scale;\n    mu2 = mu - mu1;\n\n    double var = p1 * p2 * (mu1 - mu2) * (mu1 - mu2);\n    if (var > max_var)\n    {\n      max_var = var;\n      thresh = i;\n    }\n  }\n\n  return thresh;\n}\n\ntemplate <typename Format> Format\nreplaceZeroes(ChannelRef<Format> & channel, Format replacement)\n{\n  std::replace(channel.data, channel.data + channel.size, Format(), replacement);\n}\n\nDECLARE_CLOUD_TAG(TagVisited, bool)\n\nstruct Component\n{\n  int y, x, surface;\n};\n\nstruct ComponentSurfaceCompare\n{\n  bool operator() (const Component & c1, const Component & c2)\n  { return c1.surface < c2.surface; }\n};\n\ntemplate <typename Format> int\ncalcComponentSurface(const ChannelRef<Format> channel, ChannelRef<bool> visited, Format empty, int startY, int startX)\n{\n  std::queue<std::pair<int, int> > to_visit;\n  to_visit.push(std::make_pair(startY, startX));\n  int surface = 0;\n\n  while (!to_visit.empty())\n  {\n    const std::pair<int, int> yx = to_visit.front();\n    to_visit.pop();\n\n    int y = yx.first, x = yx.second;\n\n    if (x < 0 || x >= channel.width || y < 0 || y >= channel.height || visited.at(y, x) || channel.at(y, x) == empty) continue;\n\n    visited.at(y, x) = true;\n    ++surface;\n\n    to_visit.push(std::make_pair(y, x + 1));\n    to_visit.push(std::make_pair(y, x - 1));\n    to_visit.push(std::make_pair(y + 1, x));\n    to_visit.push(std::make_pair(y - 1, x));\n  }\n\n  return surface;\n}\n\ntemplate <typename Format> void\neraseComponent(ChannelRef<Format> channel, Format empty, int y, int x)\n{\n  std::queue<std::pair<int, int> > to_visit;\n  to_visit.push(std::make_pair(y, x));\n\n  while (!to_visit.empty())\n  {\n    const std::pair<int, int> yx = to_visit.front();\n    to_visit.pop();\n\n    int y = yx.first, x = yx.second;\n\n    if (x < 0 || x >= channel.width || y < 0 || y >= channel.height || channel.at(y, x) == empty) continue;\n\n    channel.at(y, x) = empty;\n\n    to_visit.push(std::make_pair(y, x + 1));\n    to_visit.push(std::make_pair(y, x - 1));\n    to_visit.push(std::make_pair(y + 1, x));\n    to_visit.push(std::make_pair(y - 1, x));\n  }\n}\n\ntemplate <typename Format> Format\nkeepBiggestComponent(const ChannelRef<Format> channel, Format empty)\n{\n  Cloud temp;\n  temp.resize(channel.width, channel.height);\n\n  ChannelRef<bool> visited = temp.get<TagVisited>();\n  std::fill_n(visited.data, visited.size, false);\n\n  std::vector<Component> components;\n\n  for (int i = 0; i < channel.height; ++i)\n    for (int j = 0; j < channel.width; ++j)\n      if (channel.at(i, j) != empty && !visited.at(i, j))\n      {\n        Component component = { i, j, calcComponentSurface(channel, visited, empty, i, j) };\n        components.push_back(component);\n      }\n\n  const Component & biggest = *std::max_element(components.begin(), components.end(), ComponentSurfaceCompare());\n\n  int with = 0;\n\n  BOOST_FOREACH(const Component & c, components)\n    if (c.surface < biggest.surface)\n      eraseComponent(channel, empty, c.y, c.x);\n}\n\nstruct DecisionTreeCPU\n{\n  tbb::task_scheduler_init tbb_init;\n\n  struct Offsets\n  {\n    boost::int16_t du1, dv1, du2, dv2;\n  };\n\n  struct Node\n  {\n    Offsets offsets;\n    boost::int16_t threshold;\n  };\n\n  boost::uint16_t depth;\n  std::vector<Node> nodes;\n  std::vector<Label> leaves;\n\n  explicit DecisionTreeCPU(const char * data)\n  {\n    std::memcpy (&depth, data, sizeof depth);\n    data += sizeof depth;\n\n    nodes.resize ((1 << depth) - 1);\n    std::memcpy (&nodes.front (), data, nodes.size () * sizeof (Node));\n    data += nodes.size () * sizeof (Node);\n\n    leaves.resize (1 << depth);\n    std::memcpy (&leaves.front (), data, leaves.size () * sizeof (Label));\n    data += leaves.size () * sizeof (Label);\n  }\n\n  Label\n  walk(const ChannelRef<Depth> & depthChannel, int x, int y) const\n  {\n    unsigned nid = 0;\n    Depth d0 = depthChannel.at(y, x);\n    float scale = 1000.0f / d0;\n\n    for(int node_depth = 0; node_depth < depth; ++node_depth)\n    {\n      const Node & node = nodes[nid];\n\n      Depth d1 = depthChannel.atDef(y + node.offsets.dv1 * scale, x + node.offsets.du1 * scale, BACKGROUND_DEPTH);\n      Depth d2 = depthChannel.atDef(y + node.offsets.dv2 * scale, x + node.offsets.du2 * scale, BACKGROUND_DEPTH);\n\n      int feature = int (d1) - int (d2);\n\n      if (feature > node.threshold)\n        nid = nid * 2 + 2;\n      else\n        nid = nid * 2 + 1;\n    }\n\n    return leaves[nid - nodes.size()];\n  }\n\n  struct WalkHelper\n  {\n  private:\n    const DecisionTreeCPU & tree;\n    const ChannelRef<Depth> depth;\n    std::vector<Label> & labels;\n\n  public:\n    WalkHelper(const DecisionTreeCPU & tree, Cloud & cloud, std::vector<Label> & labels)\n      : tree(tree), depth(cloud.get<TagDepth>()), labels(labels)\n    {\n    }\n\n    void\n    operator () (const tbb::blocked_range2d<unsigned> & range) const\n    {\n      for (unsigned y = range.rows().begin(); y < range.rows().end(); ++y)\n        for (unsigned x = range.cols().begin(); x < range.cols().end(); ++x)\n          labels[x + y * depth.width] = depth.at(y, x) == BACKGROUND_DEPTH ?\n                Labels::Background : tree.walk(depth, x, y);\n    }\n  };\n\n  void\n  eval(Cloud & cloud, std::vector<Label> & labels) const\n  {\n    tbb::parallel_for(\n          tbb::blocked_range2d<unsigned>(0, cloud.getHeight(), 0, cloud.getWidth()),\n          WalkHelper(*this, cloud, labels)\n    );\n  }\n};\n\nint maxElementNoTie(int num, unsigned * elements)\n{\n  int max_element = 0;\n  unsigned max = elements[max_element];\n\n  for (int i = 1; i < num; ++i)\n  {\n    unsigned val = elements[i];\n    if (max < val) { max_element = i; max = val; }\n    else if (max == val) { max_element = -1; }\n  }\n\n  return max_element;\n}\n\nstruct FilterHelper\n{\nprivate:\n  ChannelRef<Label> noisy, good;\n  int radius;\n\npublic:\n  FilterHelper(ChannelRef<Label> noisy, ChannelRef<Label> good, int radius)\n    : noisy(noisy), good(good), radius(radius)\n  { }\n\n  void\n  operator ()(const tbb::blocked_range2d<int> & range) const\n  {\n    int width = noisy.width, height = noisy.height;\n\n    for (int i = range.rows().begin(); i < range.rows().end(); ++i)\n      for (int j = range.cols().begin(); j < range.cols().end(); ++j)\n      {\n        int idx = i * width + j;\n\n        if (i < radius || i >= height - radius || j < radius || j >= width - radius || noisy.data[idx] == Labels::Background)\n        {\n          good.data[idx] = Labels::Background;\n          continue;\n        }\n\n        int bins[Labels::NUM_LABELS] = { 0 };\n        Label mode = -1;\n        Label mode_count = 0;\n\n        for (int dy = -radius; dy <= radius; ++dy)\n          for (int dx = -radius; dx <= radius; ++dx)\n          {\n            Label current = noisy.data[idx + dx + dy * width];\n            ++bins[current];\n            if (bins[current] > mode_count) {\n              mode_count = bins[current];\n              mode = current;\n            }\n          }\n\n        good.data[idx] = mode;\n      }\n  }\n};\n\nvoid filterLabels(Cloud & noisy, Cloud & output, int radius)\n{\n  int width = noisy.getWidth(), height = noisy.getHeight();\n  ChannelRef<Label> noisy_labels = noisy.get<TagBPLabel>();\n  ChannelRef<Label> good_labels = output.get<TagBPLabel>();\n\n  tbb::parallel_for(\n        tbb::blocked_range2d<int>(0, noisy.getHeight(), 0, noisy.getWidth()),\n        FilterHelper(noisy_labels, good_labels, radius)\n  );\n}\n\nstruct ConsensusHelper\n{\nprivate:\n  const std::vector<std::vector<Label> > & multi_labels;\n  ChannelRef<Label> labels;\n  const ChannelRef<Depth> depths;\n\npublic:\n  ConsensusHelper(\n      const std::vector<std::vector<Label> > & multi_labels,\n      Cloud & cloud\n  )\n    : multi_labels(multi_labels), labels(cloud.get<TagBPLabel>()), depths(cloud.get<TagDepth>())\n  { }\n\n  void\n  operator ()(const tbb::blocked_range2d<unsigned> & range) const\n  {\n    for (unsigned y = range.rows().begin(); y < range.rows().end(); ++y)\n      for (unsigned x = range.cols().begin(); x < range.cols().end(); ++x)\n      {\n        std::size_t i = &depths.at(y, x) - depths.data;\n\n        bool background = true;\n        for (std::size_t ti = 0; ti < multi_labels.size (); ++ti)\n          if (multi_labels[ti][i] != Labels::Background) background = false;\n\n        if (background)\n        {\n          labels.data[i] = Labels::Background;\n          continue;\n        }\n\n        unsigned bins[Labels::NUM_LABELS] = { 0 };\n\n        for (std::size_t ti = 0; ti < multi_labels.size (); ++ti)\n          ++bins[multi_labels[ti][i]];\n\n        int consensus = maxElementNoTie(Labels::NUM_LABELS, bins);\n\n        if (consensus == -1)\n        {\n          std::fill (bins, bins + Labels::NUM_LABELS, 0);\n          Depth d = depths.at(y, x);\n\n          for (int off_x = -1; off_x <= 1; ++off_x)\n            for (int off_y = -1; off_y <= 1; ++off_y)\n            {\n              Depth off_d = depths.atDef(y + off_y, x + off_x, BACKGROUND_DEPTH);\n\n              if (std::abs (d - off_d) < 50)\n                for (std::size_t ti = 0; ti < multi_labels.size (); ++ti)\n                  ++bins[multi_labels[ti][i]];\n            }\n\n          labels.data[i] = std::max_element (bins, bins + Labels::NUM_LABELS) - bins;\n        }\n        else\n        {\n          labels.data[i] = consensus;\n        }\n      }\n  }\n};\n\nvoid\nfindConsensus(const std::vector<std::vector<Label> > & multi_labels, Cloud & cloud)\n{\n  tbb::parallel_for(\n        tbb::blocked_range2d<unsigned>(0, cloud.getHeight(), 0, cloud.getWidth()),\n        ConsensusHelper(multi_labels, cloud)\n  );\n}\n\nBodyPartsRecognizer::BodyPartsRecognizer(std::size_t num_trees, const char * trees[])\n{\n  this->trees.resize(num_trees);\n\n  for (std::size_t i = 0; i < num_trees; ++i)\n    this->trees[i].reset(new Tree(trees[i]));\n}\n\nvoid\nBodyPartsRecognizer::recognize(Cloud & cloud) const\n{\n  ChannelRef<Depth> depth = cloud.get<TagDepth>();\n\n  Stopwatch watch_threshold;\n\n  replaceZeroes(depth, BACKGROUND_DEPTH);\n  applyThreshold(depth, selectThreshold(depth), BACKGROUND_DEPTH);\n  keepBiggestComponent(depth, BACKGROUND_DEPTH);\n\n  __android_log_print(ANDROID_LOG_INFO, \"BPR\", \"Thresholding: %d ms\", watch_threshold.elapsedMs());\n\n  std::vector<std::vector<Label> > multi_labels (trees.size ());\n\n  for (std::size_t ti = 0; ti < trees.size (); ++ti)\n  {\n    Stopwatch watch_evaluation;\n\n    multi_labels[ti].resize (cloud.getHeight() * cloud.getWidth());\n    trees[ti]->eval (cloud, multi_labels[ti]);\n\n    __android_log_print(ANDROID_LOG_INFO, \"BPR\", \"Evaluating tree %d: %d ms\", ti, watch_evaluation.elapsedMs());\n  }\n\n  Stopwatch watch_consensus;\n\n  Cloud noisy;\n  noisy.resize(cloud.getWidth(), cloud.getHeight());\n\n  findConsensus(multi_labels, noisy);\n\n  __android_log_print(ANDROID_LOG_INFO, \"BPR\", \"Finding consensus: %d ms\", watch_consensus.elapsedMs());\n\n  Stopwatch watch_filtering;\n\n  filterLabels(noisy, cloud, 2);\n\n  __android_log_print(ANDROID_LOG_INFO, \"BPR\", \"Filtering labels: %d ms\", watch_consensus.elapsedMs());\n\n}\n", "meta": {"hexsha": "a09327df80bbdf9b6aed98ffa2d124563d76998f", "size": 12114, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "apps/android/BodyParts/jni/bodyparts/body_parts_recognizer.cpp", "max_stars_repo_name": "PointCloudLibrary/mobile", "max_stars_repo_head_hexsha": "ce2f5c48907e019961eda43db480f6295e421315", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 26.0, "max_stars_repo_stars_event_min_datetime": "2015-01-20T01:35:48.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-17T06:16:26.000Z", "max_issues_repo_path": "apps/android/BodyParts/jni/bodyparts/body_parts_recognizer.cpp", "max_issues_repo_name": "Web5design/mobile", "max_issues_repo_head_hexsha": "68a5edce04966494cf5e0d2449881809086b1af3", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-02-25T13:00:32.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-13T11:00:33.000Z", "max_forks_repo_path": "apps/android/BodyParts/jni/bodyparts/body_parts_recognizer.cpp", "max_forks_repo_name": "Web5design/mobile", "max_forks_repo_head_hexsha": "68a5edce04966494cf5e0d2449881809086b1af3", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 17.0, "max_forks_repo_forks_event_min_datetime": "2015-03-11T03:10:24.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-30T11:37:32.000Z", "avg_line_length": 26.3347826087, "max_line_length": 127, "alphanum_fraction": 0.6123493479, "num_tokens": 3362, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6224593452091673, "lm_q2_score": 0.523420348936324, "lm_q1q2_score": 0.3258078876680582}}
{"text": "#include <Eigen/Dense>\n#include <doubleCCD/double_subfunctions.h>\n#include <doubleCCD/doubleccd.hpp>\n#include <doubleCCD/exact_subtraction.hpp>\n#include <fstream>\n#include <iomanip>\n\nnamespace doubleccd {\n\n// cube\ncube::cube(double eps)\n{\n    vr[0] = Vector3d(-eps, -eps, eps), vr[1] = Vector3d(eps, -eps, eps),\n    vr[2] = Vector3d(eps, eps, eps), vr[3] = Vector3d(-eps, eps, eps),\n    vr[4] = Vector3d(-eps, -eps, -eps), vr[5] = Vector3d(eps, -eps, -eps),\n    vr[6] = Vector3d(eps, eps, -eps), vr[7] = Vector3d(-eps, eps, -eps);\n    edgeid[0] = { { 0, 1 } };\n    edgeid[1] = { { 1, 2 } };\n    edgeid[2] = { { 2, 3 } };\n    edgeid[3] = { { 3, 0 } };\n    edgeid[4] = { { 4, 5 } };\n    edgeid[5] = { { 5, 6 } };\n    edgeid[6] = { { 6, 7 } };\n    edgeid[7] = { { 7, 4 } };\n    edgeid[8] = { { 0, 4 } };\n    edgeid[9] = { { 1, 5 } };\n    edgeid[10] = { { 2, 6 } };\n    edgeid[11] = { { 3, 7 } };\n    faceid[0] = { { 0, 1, 2, 3 } };\n    faceid[1] = { { 4, 7, 6, 5 } };\n    faceid[2] = { { 0, 4, 5, 1 } };\n    faceid[3] = { { 1, 5, 6, 2 } };\n    faceid[4] = { { 3, 2, 6, 7 } };\n    faceid[5] = { { 0, 3, 7, 4 } }; // orientation out\n    bmax = vr[2];\n    bmin = vr[4];\n    epsilon = eps;\n}\n\n// get aabb corners\nvoid get_corners(const Eigen::MatrixX3d& p, Vector3d& min, Vector3d& max)\n{\n    min = p.colwise().minCoeff();\n    max = p.colwise().maxCoeff();\n}\nvoid get_tet_corners(\n    const std::array<Vector3d, 4>& p, Vector3d& min, Vector3d& max)\n{\n\n    min = p[0];\n    max = p[0];\n    for (int i = 0; i < 4; i++) {\n        if (min[0] > p[i][0])\n            min[0] = p[i][0];\n        if (min[1] > p[i][1])\n            min[1] = p[i][1];\n        if (min[2] > p[i][2])\n            min[2] = p[i][2];\n\n        if (max[0] < p[i][0])\n            max[0] = p[i][0];\n        if (max[1] < p[i][1])\n            max[1] = p[i][1];\n        if (max[2] < p[i][2])\n            max[2] = p[i][2];\n    }\n}\nvoid get_edge_coners(\n    const Vector3d& e0, const Vector3d& e1, Vector3d& emin, Vector3d& emax)\n{\n    for (int i = 0; i < 3; i++) {\n        if (e0[i] > e1[i]) {\n            emin[i] = e1[i];\n            emax[i] = e0[i];\n        } else {\n            emin[i] = e0[i];\n            emax[i] = e1[i];\n        }\n    }\n}\n\nVector3d get_prism_corner_double(\n    const Vector3d& vertex_start,       // x0\n    const Vector3d& face_vertex0_start, // x1\n    const Vector3d& face_vertex1_start, // x2\n    const Vector3d& face_vertex2_start, // x3\n    const Vector3d& vertex_end,\n    const Vector3d& face_vertex0_end,\n    const Vector3d& face_vertex1_end,\n    const Vector3d& face_vertex2_end,\n    int i)\n{\n    Vector3d x0 = vertex_start, x1 = face_vertex0_start,\n             x2 = face_vertex1_start, x3 = face_vertex2_start, x0b = vertex_end,\n             x1b = face_vertex0_end, x2b = face_vertex1_end,\n             x3b = face_vertex2_end;\n    if (i == 0)\n        return x0 - x1;\n    if (i == 1)\n        return x0 - x3;\n    if (i == 2)\n        return x0 - x2;\n    if (i == 3)\n        return x0b - x1b;\n    if (i == 4)\n        return x0b - x3b;\n    if (i == 5)\n        return x0b - x2b;\n\n    else\n        return Vector3d();\n}\n\nbool is_seg_intersect_cube(\n    const double& eps, const Vector3d& e0, const Vector3d& e1)\n{\n    if (is_point_intersect_cube(eps, e0))\n        return true;\n    if (is_point_intersect_cube(eps, e1))\n        return true;\n    if (same_point(e0, e1))\n        return false; // degenerate case: the segment is degenerated as a point\n    // if intersected, must be coplanar with the edge, or intersect edge or face\n    if (is_seg_intersect_cube_2d(eps, e0, e1, 0)\n        && is_seg_intersect_cube_2d(eps, e0, e1, 1)\n        && is_seg_intersect_cube_2d(eps, e0, e1, 2)) {\n\n        return true;\n    }\n\n    return false;\n}\n// check if a 2d segment intersects 2d cube\nbool is_seg_intersect_cube_2d(\n    const double eps, const Vector3d& e0, const Vector3d& e1, int axis)\n{\n    Vector2d p0, p1, p2, p3, e0p, e1p;         // e0 and e1 projected to 2d\n    projected_cube_edges(eps, p0, p1, p2, p3); // TODO move this out\n\n    const int i1 = (axis + 1) % 3;\n    const int i2 = (axis + 2) % 3;\n\n    if (e0[i1] <= eps && e0[i1] >= -eps && e0[i2] <= eps && e0[i2] >= -eps)\n        return true;\n    if (e1[i1] <= eps && e1[i1] >= -eps && e1[i2] <= eps && e1[i2] >= -eps)\n        return true;\n    e0p = Vector2d(e0[i1], e0[i2]);\n    e1p = Vector2d(e1[i1], e1[i2]);\n    if (segment_segment_intersection_2d(e0p, e1p, p0, p1))\n        return true; // check if segments has intersection, or if cube points\n                     // p0, p1 on e0-e1\n    if (segment_segment_intersection_2d(e0p, e1p, p1, p2))\n        return true;\n    if (segment_segment_intersection_2d(e0p, e1p, p2, p3))\n        return true;\n    if (segment_segment_intersection_2d(e0p, e1p, p3, p0))\n        return true;\n\n    return false;\n}\nvoid projected_cube_edges(\n    const double eps, Vector2d& e0, Vector2d& e1, Vector2d& e2, Vector2d& e3)\n{\n    const int i1 = 0;\n    const int i2 = 1;\n\n    e0[i1] = -eps;\n    e0[i2] = eps;\n\n    e1[i1] = eps;\n    e1[i2] = eps;\n\n    e2[i1] = eps;\n    e2[i2] = -eps;\n\n    e3[i1] = -eps;\n    e3[i2] = -eps;\n}\nbool is_point_intersect_cube(const double eps, const Vector3d& p)\n{\n    if (p[0] <= eps && p[0] >= -eps) {\n        if (p[1] <= eps && p[1] >= -eps) {\n            if (p[2] <= eps && p[2] >= -eps) {\n                return true;\n            }\n        }\n    }\n    return false;\n}\n\nbool is_cube_edges_intersect_triangle(\n    const cube& cb, const Vector3d& t0, const Vector3d& t1, const Vector3d& t2)\n{\n    // the vertices of triangle are checked before going here, the edges are\n    // also checked. so, only need to check if cube edge has intersection with\n    // the open triangle.\n\n    /// if triangle degenerated as a segment or point, then\n    //    no\n    //                  // intersection, because before here we already check\n    //                  that\n    Vector3d s0, s1;\n    for (int i = 0; i < 12; i++) {\n        s0 = cb.vr[cb.edgeid[i][0]];\n        s1 = cb.vr[cb.edgeid[i][1]];\n        if (segment_triangle_intersection(s0, s1, t0, t1, t2, false)\n            > 0) // return 0,1,2\n\n            return true;\n    }\n    return false;\n}\n\n////////////\n////////////\n////////////\n////////////\n//////////// the following codes are for shifting vf_pairs or ee_pairs to have\n/// no truncation error\n\n// convert a array of subtraction pair to vertices\nvoid convert_to_shifted_v(\n    const std::array<std::pair<double, double>, 18>& dt, vf_pair& vs)\n{\n    vs.x0[0] = dt[0].first;\n    vs.x0[1] = dt[1].first;\n    vs.x0[2] = dt[2].first;\n\n    vs.x0b[0] = dt[15].first;\n    vs.x0b[1] = dt[16].first;\n    vs.x0b[2] = dt[17].first;\n\n    vs.x1[0] = dt[0].second;\n    vs.x1[1] = dt[1].second;\n    vs.x1[2] = dt[2].second;\n\n    vs.x3[0] = dt[3].second;\n    vs.x3[1] = dt[4].second;\n    vs.x3[2] = dt[5].second;\n\n    vs.x2[0] = dt[6].second;\n    vs.x2[1] = dt[7].second;\n    vs.x2[2] = dt[8].second;\n\n    vs.x1b[0] = dt[9].second;\n    vs.x1b[1] = dt[10].second;\n    vs.x1b[2] = dt[11].second;\n\n    vs.x3b[0] = dt[12].second;\n    vs.x3b[1] = dt[13].second;\n    vs.x3b[2] = dt[14].second;\n\n    vs.x2b[0] = dt[15].second;\n    vs.x2b[1] = dt[16].second;\n    vs.x2b[2] = dt[17].second;\n}\nvoid convert_to_shifted_v(\n    const std::array<std::pair<double, double>, 24>& dt, ee_pair& vs)\n{\n    vs.a0[0] = dt[0].first;\n    vs.a0[1] = dt[1].first;\n    vs.a0[2] = dt[2].first;\n\n    vs.a1[0] = dt[3].first;\n    vs.a1[1] = dt[4].first;\n    vs.a1[2] = dt[5].first;\n\n    vs.b0[0] = dt[0].second;\n    vs.b0[1] = dt[1].second;\n    vs.b0[2] = dt[2].second;\n\n    vs.b1[0] = dt[6].second;\n    vs.b1[1] = dt[7].second;\n    vs.b1[2] = dt[8].second;\n    //////\n    vs.a0b[0] = dt[12].first;\n    vs.a0b[1] = dt[13].first;\n    vs.a0b[2] = dt[14].first;\n\n    vs.a1b[0] = dt[15].first;\n    vs.a1b[1] = dt[16].first;\n    vs.a1b[2] = dt[17].first;\n\n    vs.b0b[0] = dt[12].second;\n    vs.b0b[1] = dt[13].second;\n    vs.b0b[2] = dt[14].second;\n\n    vs.b1b[0] = dt[18].second;\n    vs.b1b[1] = dt[19].second;\n    vs.b1b[2] = dt[20].second;\n}\n\n// convert vf_pairs and ee_pairs into subtraction list\nvoid push_vers_into_subtract_pair(\n    const std::vector<vf_pair>& data1,\n    const std::vector<ee_pair>& data2,\n    std::vector<std::pair<double, double>>& sub)\n{\n    sub.clear();\n    sub.reserve(\n        18 * data1.size() + 24 * data2.size()); // each vf_pair has 6*3, ee_pair\n                                                // has 8*3 subtractions\n    std::pair<double, double> temp;\n\n    for (int j = 0; j < data1.size(); j++) {\n        for (int i = 0; i < 3; i++) {\n            temp.first = data1[j].x0[i];\n            temp.second = data1[j].x1[i];\n            sub.push_back(temp);\n        }\n        for (int i = 0; i < 3; i++) {\n            temp.first = data1[j].x0[i];\n            temp.second = data1[j].x3[i];\n            sub.push_back(temp);\n        }\n        for (int i = 0; i < 3; i++) {\n            temp.first = data1[j].x0[i];\n            temp.second = data1[j].x2[i];\n            sub.push_back(temp);\n        }\n        //\n        for (int i = 0; i < 3; i++) {\n            temp.first = data1[j].x0b[i];\n            temp.second = data1[j].x1b[i];\n            sub.push_back(temp);\n        }\n        for (int i = 0; i < 3; i++) {\n            temp.first = data1[j].x0b[i];\n            temp.second = data1[j].x3b[i];\n            sub.push_back(temp);\n        }\n        for (int i = 0; i < 3; i++) {\n            temp.first = data1[j].x0b[i];\n            temp.second = data1[j].x2b[i];\n            sub.push_back(temp);\n        }\n    }\n    // ee\n    for (int j = 0; j < data2.size(); j++) {\n        for (int i = 0; i < 3; i++) {\n            temp.first = data2[j].a0[i];\n            temp.second = data2[j].b0[i];\n            sub.push_back(temp);\n        }\n        for (int i = 0; i < 3; i++) {\n            temp.first = data2[j].a1[i];\n            temp.second = data2[j].b0[i];\n            sub.push_back(temp);\n        }\n        for (int i = 0; i < 3; i++) {\n            temp.first = data2[j].a1[i];\n            temp.second = data2[j].b1[i];\n            sub.push_back(temp);\n        }\n        for (int i = 0; i < 3; i++) {\n            temp.first = data2[j].a0[i];\n            temp.second = data2[j].b1[i];\n            sub.push_back(temp);\n        }\n        //\n        for (int i = 0; i < 3; i++) {\n            temp.first = data2[j].a0b[i];\n            temp.second = data2[j].b0b[i];\n            sub.push_back(temp);\n        }\n        for (int i = 0; i < 3; i++) {\n            temp.first = data2[j].a1b[i];\n            temp.second = data2[j].b0b[i];\n            sub.push_back(temp);\n        }\n        for (int i = 0; i < 3; i++) {\n            temp.first = data2[j].a1b[i];\n            temp.second = data2[j].b1b[i];\n            sub.push_back(temp);\n        }\n        for (int i = 0; i < 3; i++) {\n            temp.first = data2[j].a0b[i];\n            temp.second = data2[j].b1b[i];\n            sub.push_back(temp);\n        }\n    }\n}\n\n// convert vf_pair into matrix\nEigen::Matrix<double, 8, 3> convert_vf_to_matrix(const vf_pair& data)\n{\n    Eigen::Matrix<double, 8, 3> V;\n    V.row(0) = data.x0;\n    V.row(1) = data.x1;\n    V.row(2) = data.x2;\n    V.row(3) = data.x3;\n    V.row(4) = data.x0b;\n    V.row(5) = data.x1b;\n    V.row(6) = data.x2b;\n    V.row(7) = data.x3b;\n    return V;\n}\n// convert ee_pair into matrix\nEigen::Matrix<double, 8, 3> convert_ee_to_matrix(const ee_pair& data)\n{\n    Eigen::Matrix<double, 8, 3> V;\n    V.row(0) = data.a0;\n    V.row(1) = data.a1;\n    V.row(2) = data.b0;\n    V.row(3) = data.b1;\n    V.row(4) = data.a0b;\n    V.row(5) = data.a1b;\n    V.row(6) = data.b0b;\n    V.row(7) = data.b1b;\n    return V;\n}\n\n// return the difference between two input pairs\n// TODO this is wrong because we are not shifting back\ndouble vf_shift_error(const vf_pair& d1, const vf_pair& d2)\n{\n    double err = 0;\n    for (int i = 0; i < 3; i++) {\n        if (fabs(d1.x0[i] - d2.x0[i]) > err)\n            err = fabs(d1.x0[i] - d2.x0[i]);\n        if (fabs(d1.x1[i] - d2.x1[i]) > err)\n            err = fabs(d1.x1[i] - d2.x1[i]);\n        if (fabs(d1.x2[i] - d2.x2[i]) > err)\n            err = fabs(d1.x2[i] - d2.x2[i]);\n        if (fabs(d1.x3[i] - d2.x3[i]) > err)\n            err = fabs(d1.x3[i] - d2.x3[i]);\n\n        if (fabs(d1.x0b[i] - d2.x0b[i]) > err)\n            err = fabs(d1.x0b[i] - d2.x0b[i]);\n        if (fabs(d1.x1b[i] - d2.x1b[i]) > err)\n            err = fabs(d1.x1b[i] - d2.x1b[i]);\n        if (fabs(d1.x2b[i] - d2.x2b[i]) > err)\n            err = fabs(d1.x2b[i] - d2.x2b[i]);\n        if (fabs(d1.x3b[i] - d2.x3b[i]) > err)\n            err = fabs(d1.x3b[i] - d2.x3b[i]);\n    }\n    return err;\n}\n// return the difference between two input pairs\n// TODO this is wrong because we are not shifting back\ndouble ee_shift_error(const ee_pair& d1, const ee_pair& d2)\n{\n    double err = 0;\n    for (int i = 0; i < 3; i++) {\n        if (fabs(d1.a0[i] - d2.a0[i]) > err)\n            err = fabs(d1.a0[i] - d2.a0[i]);\n        if (fabs(d1.a1[i] - d2.a1[i]) > err)\n            err = fabs(d1.a1[i] - d2.a1[i]);\n        if (fabs(d1.b0[i] - d2.b0[i]) > err)\n            err = fabs(d1.b0[i] - d2.b0[i]);\n        if (fabs(d1.b1[i] - d2.b1[i]) > err)\n            err = fabs(d1.b1[i] - d2.b1[i]);\n\n        if (fabs(d1.a0b[i] - d2.a0b[i]) > err)\n            err = fabs(d1.a0b[i] - d2.a0b[i]);\n        if (fabs(d1.a1b[i] - d2.a1b[i]) > err)\n            err = fabs(d1.a1b[i] - d2.a1b[i]);\n        if (fabs(d1.b0b[i] - d2.b0b[i]) > err)\n            err = fabs(d1.b0b[i] - d2.b0b[i]);\n        if (fabs(d1.b1b[i] - d2.b1b[i]) > err)\n            err = fabs(d1.b1b[i] - d2.b1b[i]);\n    }\n    return err;\n}\n\n// push the whole mesh into subtraction-pair format\nvoid push_mesh_vers_into_sub_pair(\n    const Eigen::MatrixX3d& V, std::vector<std::pair<double, double>>& sub)\n{\n    sub.resize(V.size());\n    for (int i = 0; i < V.rows(); i++) {\n        for (int j = 0; j < V.cols(); j++) {\n            sub[i * 3 + j].first = V(i, j);\n            sub[i * 3 + j].second = 0;\n        }\n    }\n}\n// push the whole mesh into subtraction-pair format\nvoid push_mesh_vers_into_sub_pair(\n    const Eigen::MatrixX3d& V,\n    std::vector<std::pair<double, double>>& sub_x,\n    std::vector<std::pair<double, double>>& sub_y,\n    std::vector<std::pair<double, double>>& sub_z)\n{\n    sub_x.clear();\n    sub_y.clear();\n    sub_z.clear();\n    sub_x.resize(V.rows());\n    sub_y.resize(V.rows());\n    sub_z.resize(V.rows());\n    for (int i = 0; i < V.rows(); i++) {\n        sub_x[i].first = V(i, 0);\n        sub_x[i].second = 0;\n        sub_y[i].first = V(i, 1);\n        sub_y[i].second = 0;\n        sub_z[i].first = V(i, 2);\n        sub_z[i].second = 0;\n    }\n}\n\n// convert the subtraction pairs into vertices\nvoid convert_sub_pairs_to_mesh_vers(\n    const std::vector<std::pair<double, double>>& sub, Eigen::MatrixX3d& V)\n{\n    // assert(sub.size() % 3 == 0 && V.size() == sub.size());\n    V.resize(sub.size() / 3, 3);\n    for (int i = 0; i < V.rows(); i++) {\n        for (int j = 0; j < 3; j++) {\n            V(i, j) = sub[i * 3 + j].first;\n        }\n    }\n}\n\n// convert the subtraction pairs into vertices\nvoid convert_sub_pairs_to_mesh_vers(\n    const std::vector<std::pair<double, double>>& sub_x,\n    const std::vector<std::pair<double, double>>& sub_y,\n    const std::vector<std::pair<double, double>>& sub_z,\n    Eigen::MatrixX3d& V)\n{\n    V.resize(sub_x.size(), 3);\n    for (int i = 0; i < sub_x.size(); i++) {\n        V(i, 0) = sub_x[i].first;\n        V(i, 1) = sub_y[i].first;\n        V(i, 2) = sub_z[i].first;\n    }\n}\n\ndouble shifted_error(\n    const std::vector<std::pair<double, double>>& before,\n    const std::vector<std::pair<double, double>>& after,\n    const double shift)\n{\n    double err = 0;\n    Rational s = shift;\n    assert(before.size() == after.size());\n    for (int i = 0; i < before.size(); i++) {\n        Rational real = Rational(before[i].first) + s;\n        double terr = fabs((real - Rational(after[i].first)).to_double());\n        if (terr > err) {\n            err = terr;\n        }\n        real = Rational(before[i].second) + s;\n        terr = fabs((real - Rational(after[i].second)).to_double());\n        if (terr > err) {\n            err = terr;\n        }\n    }\n    return err;\n}\n\n// shift whole mesh based on the bounding-box of the scene\ndouble get_whole_mesh_shifted(\n    Eigen::MatrixX3d& vertices, const Vector3d& pmin, const Vector3d& pmax)\n{\n    Vector3d invShift;\n    return get_whole_mesh_shifted(vertices, pmin, pmax, invShift);\n}\n\n// shift whole mesh based on the bounding-box of the scene\ndouble get_whole_mesh_shifted(\n    Eigen::MatrixX3d& vertices,\n    const Vector3d& pmin,\n    const Vector3d& pmax,\n    Vector3d& invShift)\n{\n    std::vector<std::pair<double, double>> box_x(1), box_y(1), box_z(1),\n        whole_x, whole_y, whole_z;\n    box_x[0].first = pmax[0];\n    box_x[0].second = pmin[0];\n    box_y[0].first = pmax[1];\n    box_y[0].second = pmin[1];\n    box_z[0].first = pmax[2];\n    box_z[0].second = pmin[2];\n    std::vector<std::pair<double, double>> bo0 = box_x, bo1 = box_y,\n                                           bo2 = box_z;\n    push_mesh_vers_into_sub_pair(vertices, whole_x, whole_y, whole_z);\n    double k1 = perturbSubtractions(whole_x, box_x);\n    double k2 = perturbSubtractions(whole_y, box_y);\n    double k3 = perturbSubtractions(whole_z, box_z);\n    convert_sub_pairs_to_mesh_vers(whole_x, whole_y, whole_z, vertices);\n    invShift = Vector3d(-k1, -k2, -k3);\n    double error = 0;\n    error = std::max(error, shifted_error(bo0, box_x, k1));\n    error = std::max(error, shifted_error(bo1, box_y, k2));\n    error = std::max(error, shifted_error(bo2, box_z, k3));\n    return error;\n}\n\n// compare the error of the whole mesh\n// void compare_whole_mesh_err(const Eigen::MatrixX3d& vertices,const\n// Eigen::MatrixX3d& vertices1){\n//     double ex=0,ey=0,ez=0;\n//     for(int i=0;i<vertices.rows();i++){\n//         if(fabs(vertices(i,0)-vertices1(i,0))>ex)\n//             ex=fabs(vertices(i,0)-vertices1(i,0));\n\n//         if(fabs(vertices(i,1)-vertices1(i,1))>ey)\n//             ey=fabs(vertices(i,1)-vertices1(i,1));\n\n//         if(fabs(vertices(i,2)-vertices1(i,2))>ez)\n//             ez=fabs(vertices(i,2)-vertices1(i,2));\n//     }\n//     std::cout<<\"vertices diff x, \"<<ex<<\" y, \"<<ey<<\" z, \"<<ez<<std::endl;\n// }\n\n/*x0 is the point, x1, x2, x3 is the triangle\nshift the whole mesh and get the shift - back vertices*/\n// double get_whole_mesh_shifted(\n//     const std::vector<vf_pair>& data1,\n//     const std::vector<ee_pair>& data2,\n//     std::vector<vf_pair>& shift_back1,\n//     std::vector<ee_pair>& shift_back2,\n//     Eigen::MatrixX3d& vertices)\n// {\n//     std::vector<std::pair<double, double>> whole, suback;\n//\n//     push_vers_into_subtract_pair(data1, data2, suback);\n//     int subsize = suback.size();\n//     push_mesh_vers_into_sub_pair(vertices, whole);\n//     // suback = sub;// this is for shift back\n//     // k = displaceSubtractions_double(sub);\n//     suback.insert(suback.end(), whole.begin(), whole.end());\n//     perturbSubtractions(suback); // get shifted back data\n//\n//     shift_back1.resize(data1.size());\n//\n//     shift_back2.resize(data2.size());\n//     int c = 0;\n//     // Vector3d kvec(k, k, k);\n//     int d1size = data1.size();\n//     int d2size = data2.size();\n//     int datasize = d1size + d2size;\n//     std::array<std::pair<double, double>, 18> dtback1;\n//     std::array<std::pair<double, double>, 24> dtback2;\n//     for (int r = 0; r < datasize; r++) {\n//         if (r < d1size) {\n//             for (int i = 0; i < 18; i++) {\n//                 // dt1[i] = sub[r * 18 + i];\n//                 dtback1[i] = suback[r * 18 + i];\n//             }\n//\n//             convert_to_shifted_v(dtback1, shift_back1[r]);\n//         }      // r is d1size-1, sub has been read to d1size*18-1\n//         else { // r is from d1size to datasize-1, sub is from d1*18\n//             for (int i = 0; i < 24; i++) {\n//                 // dt2[i] = sub[d1size * 18 + (r - d1size) * 24 + i];\n//                 dtback2[i] = suback[d1size * 18 + (r - d1size) * 24 + i];\n//             }\n//\n//             convert_to_shifted_v(dtback2, shift_back2[r - d1size]);\n//         }\n//     }\n//     std::vector<std::pair<double, double>> vernew;\n//     vernew.resize(vertices.size());\n//     int c1 = 0;\n//     for (int i = subsize; i < suback.size(); i++) {\n//         vernew[c1] = suback[i];\n//         c1++;\n//     }\n//     convert_sub_pairs_to_mesh_vers(vernew, vertices);\n//     double err = 0, temerr;\n//     for (int i = 0; i < d1size; i++) {\n//         temerr = vf_shift_error(data1[i], shift_back1[i]);\n//         if (temerr > err)\n//             err = temerr;\n//     }\n//     for (int i = 0; i < d2size; i++) {\n//         temerr = ee_shift_error(data2[i], shift_back2[i]);\n//         if (temerr > err)\n//             err = temerr;\n//     }\n//     return err;\n// }\n//\n//// x0 is the point, x1, x2, x3 is the triangle\n// double get_whole_mesh_shifted(\n//     const std::vector<vf_pair>& data1,\n//     const std::vector<ee_pair>& data2,\n//     Eigen::MatrixX3d& vertices)\n// {\n//     // std::vector<std::pair<double, double>> whole, suback;\n//\n//     // push_vers_into_subtract_pair(data1, data2, suback);\n//     // int subsize = suback.size();\n//     // push_mesh_vers_into_sub_pair(vertices, whole);\n//     // // suback = sub;// this is for shift back\n//     // // k = displaceSubtractions_double(sub);\n//     // suback.insert(suback.end(), whole.begin(), whole.end());\n//     // perturbSubtractions(suback); // get shifted back data\n//\n//     // std::vector<std::pair<double, double>> vernew;\n//     // vernew.resize(vertices.size());\n//     // int c = 0;\n//     // for (int i = subsize; i < suback.size(); i++) {\n//     //     vernew[c] = suback[i];\n//     //     c++;\n//     // }\n//     // assert(whole.size() == vernew.size());\n//     double err = 0;\n//     // for (int i = 0; i < whole.size(); i++) {\n//     //     if (fabs(whole[i].first - vernew[i].first) > err) {\n//     //         err = fabs(whole[i].first - vernew[i].first);\n//     //     }\n//     // }\n//\n//     // convert_sub_pairs_to_mesh_vers(vernew, vertices);\n//\n//     return err;\n// }\n\n// shift vertex-face pair to a far away place\ndouble shift_vertex_face(\n    const vf_pair& input_vf_pair, vf_pair& shifted_vf_pair, double& time)\n{\n    igl::Timer timer;\n    timer.start();\n    Vector3d x0 = input_vf_pair.x0, x1 = input_vf_pair.x1,\n             x2 = input_vf_pair.x2, x3 = input_vf_pair.x3,\n             x0b = input_vf_pair.x0b, x1b = input_vf_pair.x1b,\n             x2b = input_vf_pair.x2b, x3b = input_vf_pair.x3b;\n\n    std::vector<std::pair<double, double>> subs, subs_ori;\n    subs.resize(6 * 3);\n    for (int i = 0; i < 3; i++) {\n        subs[3 * 0 + i].first = x0[i];\n        subs[3 * 0 + i].second = x1[i];\n        subs[3 * 1 + i].first = x0[i];\n        subs[3 * 1 + i].second = x3[i];\n        subs[3 * 2 + i].first = x0[i];\n        subs[3 * 2 + i].second = x2[i];\n\n        subs[3 * 3 + i].first = x0b[i];\n        subs[3 * 3 + i].second = x1b[i];\n        subs[3 * 4 + i].first = x0b[i];\n        subs[3 * 4 + i].second = x3b[i];\n        subs[3 * 5 + i].first = x0b[i];\n        subs[3 * 5 + i].second = x2b[i];\n    }\n    subs_ori = subs;\n    // this perturbSubtractions shift and shift - back is wrong\n    // perturbSubtractions(subs);\n    double k = displaceSubtractions_double(subs);\n    for (int i = 0; i < 3; i++) {\n        x0[i] = subs[3 * 0 + i].first;\n        x1[i] = subs[3 * 0 + i].second;\n        x3[i] = subs[3 * 1 + i].second;\n        x2[i] = subs[3 * 2 + i].second;\n\n        x0b[i] = subs[3 * 3 + i].first;\n        x1b[i] = subs[3 * 3 + i].second;\n        x3b[i] = subs[3 * 4 + i].second;\n        x2b[i] = subs[3 * 5 + i].second;\n    }\n    shifted_vf_pair.x0 = x0;\n    shifted_vf_pair.x1 = x1;\n    shifted_vf_pair.x2 = x2;\n    shifted_vf_pair.x3 = x3;\n\n    shifted_vf_pair.x0b = x0b;\n    shifted_vf_pair.x1b = x1b;\n    shifted_vf_pair.x2b = x2b;\n    shifted_vf_pair.x3b = x3b;\n    timer.stop();\n    time = timer.getElapsedTimeInMicroSec();\n    double err = 0;\n    for (int i = 0; i < subs.size(); i++) {\n        double value = subs[i].first;\n        double value_ori = subs_ori[i].first;\n        Rational rvalue = Rational(value_ori) + Rational(k);\n        double diff = (rvalue - Rational(value)).to_double();\n        diff = fabs(diff);\n        if (diff > err) {\n            err = diff;\n        }\n    }\n    for (int i = 0; i < subs.size(); i++) {\n        double value = subs[i].second;\n        double value_ori = subs_ori[i].second;\n        Rational rvalue = Rational(value_ori) + Rational(k);\n        double diff = (rvalue - Rational(value)).to_double();\n        diff = fabs(diff);\n        if (diff > err) {\n            err = diff;\n        }\n    }\n\n    return err;\n}\n\n// check if there are error in the subtraction, comparing with rational results\nbool check_subs_err(\n    std::vector<std::pair<double, double>> subs, std::string discribe)\n{\n    bool have_err = false;\n    for (int i = 0; i < subs.size(); i++) {\n        Rational a = subs[i].first;\n        Rational b = subs[i].second;\n        Rational rst = a - b;\n        double rd = subs[i].first - subs[i].second;\n        if (rst == rd) {\n\n        } else {\n            std::cout << discribe << \" diff, \" << std::setprecision(17) << i\n                      << \", \" << (rst - rd) << \", \" << rst << \", \" << rd\n                      << std::endl;\n            have_err = true;\n        }\n    }\n    return have_err;\n}\n\nstd::vector<std::pair<double, double>>\nread_rational_CSV(const std::string inputFileName)\n{\n\n    std::vector<std::pair<double, double>> vs;\n\n    vs.clear();\n\n    std::ifstream infile;\n\n    infile.open(inputFileName);\n\n    // std::array<double,3> v;\n\n    if (!infile.is_open())\n\n    {\n\n        std::cout << \"Path Wrong!!!!\" << std::endl;\n\n        return vs;\n    }\n    int l = 0;\n\n    while (infile) // there is input overload classfile\n\n    {\n        l++;\n        std::string s;\n        if (!getline(infile, s))\n            break;\n        if (s[0] != '#') {\n            std::istringstream ss(s);\n            std::array<std::string, 4> record;\n            int c = 0;\n            while (ss) {\n                std::string line;\n                if (!getline(ss, line, ','))\n                    break;\n                try {\n                    record[c] = line;\n                    c++;\n                } catch (const std::invalid_argument e) {\n                    std::cout << \"NaN found in file \" << inputFileName\n                              << \" line \" << l << std::endl;\n                    e.what();\n                }\n            }\n            Rational rt;\n            double x = rt.get_double(record[0], record[1]),\n                   y = rt.get_double(record[2], record[3]);\n            std::pair<double, double> pr;\n            pr.first = x;\n            pr.second = y;\n            vs.push_back(pr);\n        }\n    }\n    return vs;\n    // Eigen::MatrixXd all_v(vs.size(),3);\n    // for(int i=0;i<vs.size();i++){\n    //     all_v(i,0)=vs[i][0];\n    //   all_v(i,1)=vs[i][1];\n    //     all_v(i,2)=vs[i][2];\n    // }\n    // if (!infile.eof()) {\n    // \tstd::cerr << \"Could not read file \" << inputFileName << \"\\n\";\n    // }\n    // return all_v;\n}\n\nvoid print_exact_ee_pair_file(\n    const ee_pair& input_ee_pair, const std::string filename)\n{\n    Vector3d a0 = input_ee_pair.a0, a1 = input_ee_pair.a1,\n             b0 = input_ee_pair.b0, b1 = input_ee_pair.b1,\n             a0b = input_ee_pair.a0b, a1b = input_ee_pair.a1b,\n             b0b = input_ee_pair.b0b, b1b = input_ee_pair.b1b;\n\n    std::vector<std::pair<double, double>> subs;\n    subs.resize(8 * 3);\n    for (int i = 0; i < 3; i++) {\n        subs[3 * 0 + i].first = a0[i];\n        subs[3 * 0 + i].second = b0[i];\n        subs[3 * 1 + i].first = a1[i];\n        subs[3 * 1 + i].second = b0[i];\n        subs[3 * 2 + i].first = a1[i];\n        subs[3 * 2 + i].second = b1[i];\n        subs[3 * 3 + i].first = a0[i];\n        subs[3 * 3 + i].second = b1[i];\n\n        subs[3 * 4 + i].first = a0b[i];\n        subs[3 * 4 + i].second = b0b[i];\n        subs[3 * 5 + i].first = a1b[i];\n        subs[3 * 5 + i].second = b0b[i];\n        subs[3 * 6 + i].first = a1b[i];\n        subs[3 * 6 + i].second = b1b[i];\n        subs[3 * 7 + i].first = a0b[i];\n        subs[3 * 7 + i].second = b1b[i];\n    }\n    std::ofstream fout;\n    fout.open(filename);\n    for (int i = 0; i < subs.size(); i++) {\n        Rational n1(subs[i].first), n2(subs[i].second);\n        fout << n1.get_numerator_str() << \",\" << n1.get_denominator_str() << \",\"\n             << n2.get_numerator_str() << \",\" << n2.get_denominator_str()\n             << std::endl;\n    }\n    fout.close();\n\n    // read the same file and compare\n    std::vector<std::pair<double, double>> readed = read_rational_CSV(filename);\n    assert(readed.size() == subs.size());\n    for (int i = 0; i < subs.size(); i++) {\n        assert(\n            readed[i].first == subs[i].first\n            && readed[i].second == subs[i].second);\n    }\n    displaceSubtractions_double(readed);\n    check_subs_err(readed, std::string(\"readed number\"));\n}\n\ndouble shift_edge_edge(\n    const ee_pair& input_ee_pair, ee_pair& shifted_ee_pair, double& time)\n{\n    igl::Timer timer;\n    timer.start();\n    Vector3d a0 = input_ee_pair.a0, a1 = input_ee_pair.a1,\n             b0 = input_ee_pair.b0, b1 = input_ee_pair.b1,\n             a0b = input_ee_pair.a0b, a1b = input_ee_pair.a1b,\n             b0b = input_ee_pair.b0b, b1b = input_ee_pair.b1b;\n\n    std::vector<std::pair<double, double>> subs, save_subs;\n    subs.resize(8 * 3);\n    for (int i = 0; i < 3; i++) {\n        subs[3 * 0 + i].first = a0[i];\n        subs[3 * 0 + i].second = b0[i];\n        subs[3 * 1 + i].first = a1[i];\n        subs[3 * 1 + i].second = b0[i];\n        subs[3 * 2 + i].first = a1[i];\n        subs[3 * 2 + i].second = b1[i];\n        subs[3 * 3 + i].first = a0[i];\n        subs[3 * 3 + i].second = b1[i];\n\n        subs[3 * 4 + i].first = a0b[i];\n        subs[3 * 4 + i].second = b0b[i];\n        subs[3 * 5 + i].first = a1b[i];\n        subs[3 * 5 + i].second = b0b[i];\n        subs[3 * 6 + i].first = a1b[i];\n        subs[3 * 6 + i].second = b1b[i];\n        subs[3 * 7 + i].first = a0b[i];\n        subs[3 * 7 + i].second = b1b[i];\n    }\n\n    save_subs = subs; // this is the value before rounding\n\n    double k = displaceSubtractions_double(subs);\n    for (int i = 0; i < 3; i++) {\n        a0[i] = subs[3 * 0 + i].first;\n        b0[i] = subs[3 * 0 + i].second;\n        a1[i] = subs[3 * 1 + i].first;\n        b1[i] = subs[3 * 2 + i].second;\n\n        a0b[i] = subs[3 * 4 + i].first;\n        b0b[i] = subs[3 * 4 + i].second;\n        a1b[i] = subs[3 * 5 + i].first;\n        b1b[i] = subs[3 * 6 + i].second;\n    }\n    shifted_ee_pair.a0 = a0;\n    shifted_ee_pair.a1 = a1;\n    shifted_ee_pair.b0 = b0;\n    shifted_ee_pair.b1 = b1;\n\n    shifted_ee_pair.a0b = a0b;\n    shifted_ee_pair.a1b = a1b;\n    shifted_ee_pair.b0b = b0b;\n    shifted_ee_pair.b1b = b1b;\n    timer.stop();\n    time = timer.getElapsedTimeInMicroSec();\n    double err = 0;\n    for (int i = 0; i < subs.size(); i++) {\n        double value = subs[i].first;\n        double value_ori = save_subs[i].first;\n        Rational rvalue = Rational(value_ori) + Rational(k);\n        double diff = (rvalue - Rational(value)).to_double();\n        diff = fabs(diff);\n        if (diff > err) {\n            err = diff;\n        }\n    }\n    for (int i = 0; i < subs.size(); i++) {\n        double value = subs[i].second;\n        double value_ori = save_subs[i].second;\n        Rational rvalue = Rational(value_ori) + Rational(k);\n        double diff = (rvalue - Rational(value)).to_double();\n        diff = fabs(diff);\n        if (diff > err) {\n            err = diff;\n        }\n    }\n\n    return err;\n}\nbool have_no_truncation(const double a, const double b)\n{\n    Rational sub = Rational(a) - Rational(b);\n    double sub_d = a - b;\n    if (sub != sub_d) {\n        return false;\n    }\n    return true;\n}\n// x0 is the point, x1, x2, x3 is the triangle\nvoid get_prism_shifted_vertices_double(\n    const Vector3d& x0,\n    const Vector3d& x1,\n    const Vector3d& x2,\n    const Vector3d& x3,\n    const Vector3d& x0b,\n    const Vector3d& x1b,\n    const Vector3d& x2b,\n    const Vector3d& x3b,\n    double& k,\n    std::array<Vector3d, 6>& p_vertices)\n{\n    std::vector<std::pair<double, double>> sub;\n\n    sub.clear();\n    sub.reserve(18);\n    std::pair<double, double> temp;\n    for (int i = 0; i < 3; i++) {\n        temp.first = x0[i];\n        temp.second = x1[i];\n        sub.push_back(temp);\n    }\n    for (int i = 0; i < 3; i++) {\n        temp.first = x0[i];\n        temp.second = x3[i];\n        sub.push_back(temp);\n    }\n    for (int i = 0; i < 3; i++) {\n        temp.first = x0[i];\n        temp.second = x2[i];\n        sub.push_back(temp);\n    }\n    //\n    for (int i = 0; i < 3; i++) {\n        temp.first = x0b[i];\n        temp.second = x1b[i];\n        sub.push_back(temp);\n    }\n    for (int i = 0; i < 3; i++) {\n        temp.first = x0b[i];\n        temp.second = x3b[i];\n        sub.push_back(temp);\n    }\n    for (int i = 0; i < 3; i++) {\n        temp.first = x0b[i];\n        temp.second = x2b[i];\n        sub.push_back(temp);\n    }\n\n    k = displaceSubtractions_double(sub);\n    int c = 0;\n    for (int i = 0; i < 6; i++) {\n        for (int j = 0; j < 3; j++) {\n            p_vertices[i][j] = sub[c].first - sub[c].second;\n            assert(have_no_truncation(sub[c].first, sub[c].second));\n            c++;\n        }\n    }\n}\n// check if p1-p2 has truncation\nbool have_no_truncation(const Vector3d& p1, const Vector3d& p2)\n{\n    for (int i = 0; i < 3; i++) {\n        double x = p1[i] - p2[i];\n        Rational xr = Rational(p1[i]) - Rational(p2[i]);\n        if (xr > x || xr < x) {\n            std::cout << \"double, \" << x << std::endl;\n            std::cout << \"rational, \" << xr << std::endl;\n            if (xr > x) {\n                std::cout << \"larger\" << std::endl;\n            }\n            if (xr < x) {\n                std::cout << \"smaller\" << std::endl;\n            }\n            std::cout << \"diff,\" << xr - x << std::endl;\n            std::cout << std::setprecision(17) << \"pair is, \" << p1[i] << \",\"\n                      << p2[i] << std::endl;\n            return false;\n        }\n    }\n    return true;\n}\n\n// x0 is the point, x1, x2, x3 is the triangle\nvoid prism::get_prism_vertices(\n    const Vector3d& x0,\n    const Vector3d& x1,\n    const Vector3d& x2,\n    const Vector3d& x3,\n    const Vector3d& x0b,\n    const Vector3d& x1b,\n    const Vector3d& x2b,\n    const Vector3d& x3b,\n    std::array<Vector3d, 6>& p_vertices)\n{\n    p_vertices[0] = x0 - x1;\n    p_vertices[1] = x0 - x3;\n    p_vertices[2] = x0 - x2;\n    p_vertices[3] = x0b - x1b;\n    p_vertices[4] = x0b - x3b;\n    p_vertices[5] = x0b - x2b;\n    assert(have_no_truncation(x0, x1));\n    assert(have_no_truncation(x0, x3));\n    assert(have_no_truncation(x0, x2));\n    assert(have_no_truncation(x0b, x1b));\n    assert(have_no_truncation(x0b, x3b));\n    assert(have_no_truncation(x0b, x2b));\n}\nprism::prism(\n    const Vector3d& vs,\n    const Vector3d& fs0,\n    const Vector3d& fs1,\n    const Vector3d& fs2,\n    const Vector3d& ve,\n    const Vector3d& fe0,\n    const Vector3d& fe1,\n    const Vector3d& fe2)\n{\n\n    //\n    // these are the 6 vertices of the prism,right hand law\n    double k = 0;\n#ifdef CCD_ROUND_INPUTS\n    get_prism_shifted_vertices_double(\n        vs, fs0, fs1, fs2, ve, fe0, fe1, fe2, k, p_vertices);\n#else\n    get_prism_vertices(\n        vs, fs0, fs1, fs2, ve, fe0, fe1, fe2,\n        p_vertices); //  before use this we need to shift all the vertices\n#endif\n\n    std::array<int, 2> eid;\n\n    eid[0] = 0;\n    eid[1] = 1;\n    prism_edge_id[0] = eid;\n    eid[0] = 1;\n    eid[1] = 2;\n    prism_edge_id[1] = eid;\n    eid[0] = 2;\n    eid[1] = 0;\n    prism_edge_id[2] = eid;\n\n    eid[0] = 3;\n    eid[1] = 4;\n    prism_edge_id[3] = eid;\n    eid[0] = 4;\n    eid[1] = 5;\n    prism_edge_id[4] = eid;\n    eid[0] = 5;\n    eid[1] = 3;\n    prism_edge_id[5] = eid;\n\n    eid[0] = 0;\n    eid[1] = 3;\n    prism_edge_id[6] = eid;\n    eid[0] = 1;\n    eid[1] = 4;\n    prism_edge_id[7] = eid;\n    eid[0] = 2;\n    eid[1] = 5;\n    prism_edge_id[8] = eid;\n}\nbool prism::is_triangle_degenerated(const int up_or_bottom)\n{\n    int pid = up_or_bottom == 0 ? 0 : 3;\n    const auto to_2d = [](const Vector3d& p, int t) {\n        return Vector2d(p[(t + 1) % 3], p[(t + 2) % 3]);\n    };\n    double r = ((p_vertices[pid] - p_vertices[pid + 1])\n                    .cross(p_vertices[pid] - p_vertices[pid + 2]))\n                   .norm();\n    if (fabs(r) > 1e-8)\n        return false;\n    int ori;\n    std::array<Vector2d, 3> p;\n    for (int j = 0; j < 3; j++) {\n\n        p[0] = to_2d(p_vertices[pid], j);\n        p[1] = to_2d(p_vertices[pid + 1], j);\n        p[2] = to_2d(p_vertices[pid + 2], j);\n\n        ori = orient_2d(p[0], p[1], p[2]);\n        if (ori != 0) {\n            return false;\n        }\n    }\n    return true;\n}\n\nvoid hex::get_hex_vertices(\n    const Vector3d& a0,\n    const Vector3d& a1,\n    const Vector3d& b0,\n    const Vector3d& b1,\n    const Vector3d& a0b,\n    const Vector3d& a1b,\n    const Vector3d& b0b,\n    const Vector3d& b1b,\n    std::array<Vector3d, 8>& h_vertices)\n{\n    h_vertices[0] = a0 - b0;\n    h_vertices[1] = a1 - b0;\n    h_vertices[2] = a1 - b1;\n    h_vertices[3] = a0 - b1;\n    h_vertices[4] = a0b - b0b;\n    h_vertices[5] = a1b - b0b;\n    h_vertices[6] = a1b - b1b;\n    h_vertices[7] = a0b - b1b;\n    assert(have_no_truncation(a0, b0));\n    assert(have_no_truncation(a1, b0));\n    assert(have_no_truncation(a1, b1));\n    assert(have_no_truncation(a0, b1));\n\n    assert(have_no_truncation(a0b, b0b));\n    assert(have_no_truncation(a1b, b0b));\n    assert(have_no_truncation(a1b, b1b));\n    assert(have_no_truncation(a0b, b1b));\n}\n\nvoid hex::get_hex_shifted_vertices_double(\n    const Vector3d& a0,\n    const Vector3d& a1,\n    const Vector3d& b0,\n    const Vector3d& b1,\n    const Vector3d& a0b,\n    const Vector3d& a1b,\n    const Vector3d& b0b,\n    const Vector3d& b1b,\n    std::array<Vector3d, 8>& h_vertices)\n{\n\n    std::vector<std::pair<double, double>> subs, save_subs;\n    subs.resize(8 * 3);\n    for (int i = 0; i < 3; i++) {\n        subs[3 * 0 + i].first = a0[i];\n        subs[3 * 0 + i].second = b0[i];\n        subs[3 * 1 + i].first = a1[i];\n        subs[3 * 1 + i].second = b0[i];\n        subs[3 * 2 + i].first = a1[i];\n        subs[3 * 2 + i].second = b1[i];\n        subs[3 * 3 + i].first = a0[i];\n        subs[3 * 3 + i].second = b1[i];\n\n        subs[3 * 4 + i].first = a0b[i];\n        subs[3 * 4 + i].second = b0b[i];\n        subs[3 * 5 + i].first = a1b[i];\n        subs[3 * 5 + i].second = b0b[i];\n        subs[3 * 6 + i].first = a1b[i];\n        subs[3 * 6 + i].second = b1b[i];\n        subs[3 * 7 + i].first = a0b[i];\n        subs[3 * 7 + i].second = b1b[i];\n    }\n\n    double k = displaceSubtractions_double(subs);\n    Vector3d a0_p;\n    Vector3d a1_p;\n    Vector3d b0_p;\n    Vector3d b1_p;\n    Vector3d a0b_p;\n    Vector3d a1b_p;\n    Vector3d b0b_p;\n    Vector3d b1b_p;\n    for (int i = 0; i < 3; i++) {\n        a0_p[i] = subs[3 * 0 + i].first;\n        b0_p[i] = subs[3 * 0 + i].second;\n        a1_p[i] = subs[3 * 1 + i].first;\n        b1_p[i] = subs[3 * 2 + i].second;\n\n        a0b_p[i] = subs[3 * 4 + i].first;\n        b0b_p[i] = subs[3 * 4 + i].second;\n        a1b_p[i] = subs[3 * 5 + i].first;\n        b1b_p[i] = subs[3 * 6 + i].second;\n    }\n    get_hex_vertices(\n        a0_p, a1_p, b0_p, b1_p, a0b_p, a1b_p, b0b_p, b1b_p, h_vertices);\n}\n\n// a0, a1 is one edge, b0, b1 is another  edge\nhex::hex(\n    const Vector3d& a0,\n    const Vector3d& a1,\n    const Vector3d& b0,\n    const Vector3d& b1,\n    const Vector3d& a0b,\n    const Vector3d& a1b,\n    const Vector3d& b0b,\n    const Vector3d& b1b)\n{\n\n#ifdef CCD_ROUND_INPUTS\n    get_hex_shifted_vertices_double(\n        a0, a1, b0, b1, a0b, a1b, b0b, b1b, h_vertices);\n#else\n    get_hex_vertices(\n        a0, a1, b0, b1, a0b, a1b, b0b, b1b,\n        h_vertices); // before use this we need to shift all the vertices\n#endif\n\n    std::array<int, 2> eid;\n\n    eid[0] = 0;\n    eid[1] = 1;\n    hex_edge_id[0] = eid;\n    eid[0] = 1;\n    eid[1] = 2;\n    hex_edge_id[1] = eid;\n    eid[0] = 2;\n    eid[1] = 3;\n    hex_edge_id[2] = eid;\n    eid[0] = 3;\n    eid[1] = 0;\n    hex_edge_id[3] = eid;\n\n    eid[0] = 4;\n    eid[1] = 5;\n    hex_edge_id[4] = eid;\n    eid[0] = 5;\n    eid[1] = 6;\n    hex_edge_id[5] = eid;\n    eid[0] = 6;\n    eid[1] = 7;\n    hex_edge_id[6] = eid;\n    eid[0] = 7;\n    eid[1] = 4;\n    hex_edge_id[7] = eid;\n\n    eid[0] = 0;\n    eid[1] = 4;\n    hex_edge_id[8] = eid;\n    eid[0] = 1;\n    eid[1] = 5;\n    hex_edge_id[9] = eid;\n    eid[0] = 2;\n    eid[1] = 6;\n    hex_edge_id[10] = eid;\n    eid[0] = 3;\n    eid[1] = 7;\n    hex_edge_id[11] = eid;\n}\n\n// the facets of the tet are all oriented to outside. check if p is inside of\n// OPEN tet\nbool is_point_inside_tet(const bilinear& bl, const Vector3d& p)\n{\n\n    for (int i = 0; i < 4; i++) { // facets.size()==4\n        Vector3d pt1 = bl.v[bl.facets[i][0]], pt2 = bl.v[bl.facets[i][1]],\n                 pt3 = bl.v[bl.facets[i][2]];\n        if (orient_3d(p, pt1, pt2, pt3) >= 0) {\n            return false;\n        }\n    }\n    return true; // all the orientations are -1, then point inside\n}\n\n// we already know the bilinear is degenerated, next check which kind\nint bilinear_degeneration(const bilinear& bl)\n{\n    bool dege1 = is_triangle_degenerated(bl.v[0], bl.v[1], bl.v[2]);\n    bool dege2 = is_triangle_degenerated(bl.v[0], bl.v[2], bl.v[3]);\n\n    if (dege1 && dege2) {\n        return BI_DEGE_PLANE;\n    }\n    Vector3d p0, p1, p2;\n\n    if (dege1) {\n        p0 = bl.v[0];\n        p1 = bl.v[2];\n        p2 = bl.v[3];\n    } else {\n        p0 = bl.v[0];\n        p1 = bl.v[1];\n        p2 = bl.v[2];\n    }\n\n    Vector3d np = Vector3d::Random();\n    int ori = orient_3d(np, p0, p1, p2);\n    while (ori == 0) { // if coplanar, random\n        np = Vector3d::Random();\n        ori = orient_3d(np, p0, p1, p2);\n    }\n    int ori0 = orient_3d(np, bl.v[0], bl.v[1], bl.v[2]);\n    int ori1 = orient_3d(np, bl.v[0], bl.v[2], bl.v[3]);\n    if (ori0 * ori1 <= 0) {\n        return BI_DEGE_XOR_02;\n    }\n    ori0 = orient_3d(np, bl.v[0], bl.v[1], bl.v[3]);\n    ori1 = orient_3d(np, bl.v[3], bl.v[1], bl.v[2]);\n    if (ori0 * ori1 <= 0) {\n        return BI_DEGE_XOR_13;\n    }\n    return BI_DEGE_PLANE;\n}\n\nbool is_cube_intersect_degenerated_bilinear(\n    const bilinear& bl, const cube& cube)\n{\n    int dege = bilinear_degeneration(bl);\n    // int axis;\n    bool res;\n    if (dege == BI_DEGE_PLANE) {\n\n        if (is_cube_edges_intersect_triangle(cube, bl.v[0], bl.v[1], bl.v[3]))\n            return true;\n        if (is_cube_edges_intersect_triangle(cube, bl.v[3], bl.v[1], bl.v[2]))\n            return true;\n        return false;\n    } else {\n\n        if (dege == BI_DEGE_XOR_02) { // triangle 0-1-2 and 0-2-3\n            for (int i = 0; i < 12; i++) {\n                res = int_seg_XOR(\n                    segment_triangle_intersection(\n                        cube.vr[cube.edgeid[i][0]], cube.vr[cube.edgeid[i][1]],\n                        bl.v[1], bl.v[2], bl.v[0],\n                        true), // CAUTION: need to be careful for the order here\n                    segment_triangle_intersection(\n                        cube.vr[cube.edgeid[i][0]], cube.vr[cube.edgeid[i][1]],\n                        bl.v[3], bl.v[2], bl.v[0], true));\n                if (res == true)\n                    return true;\n            }\n            return false;\n        }\n        if (dege == BI_DEGE_XOR_13) { // triangle 0-1-2 and 0-2-3\n            for (int i = 0; i < 12; i++) {\n                res = int_seg_XOR(\n                    segment_triangle_intersection(\n                        cube.vr[cube.edgeid[i][0]], cube.vr[cube.edgeid[i][1]],\n                        bl.v[0], bl.v[1], bl.v[3],\n                        true), // CAUTION: need to be careful for the order here\n                    segment_triangle_intersection(\n                        cube.vr[cube.edgeid[i][0]], cube.vr[cube.edgeid[i][1]],\n                        bl.v[2], bl.v[1], bl.v[3], true));\n                if (res == true)\n                    return true;\n            }\n            return false;\n        }\n    }\n    std::cout << \"!! THIS CANNOT HAPPEN\" << std::endl;\n    return false;\n}\n// phisign gives the pair we want to check\nbool line_shoot_same_pair_tet(\n    const Vector3d& p0, const Vector3d& p1, const int phisign, bilinear& bl)\n{\n    int fid;\n    if (bl.phi_f[0] == 2)\n        get_tet_phi(bl);\n\n    if (phisign > 0) {\n        if (bl.phi_f[0] > 0)\n            fid = 0;\n        else\n            fid = 2;\n    } else {\n        if (bl.phi_f[1] > 0)\n            fid = 0;\n        else\n            fid = 2;\n    } // get which pair of facets to check\n    // if line is parallel to the triangle, return false\n    int inter0 = is_line_cut_triangle(\n        p0, p1, bl.v[bl.facets[fid][0]], bl.v[bl.facets[fid][1]],\n        bl.v[bl.facets[fid][2]], false);\n\n    int inter1 = is_line_cut_triangle(\n        p0, p1, bl.v[bl.facets[fid + 1][0]], bl.v[bl.facets[fid + 1][1]],\n        bl.v[bl.facets[fid + 1][2]], false);\n\n    if (inter0 == 1 && inter1 == 1)\n        return true;\n    return false;\n}\n\nRational quadratic_function_value(\n    const Rational& a, const Rational& b, const Rational& c, const Rational& t)\n{\n\n    if (t.get_sign() == 0) {\n        return c;\n    } else {\n        return a * t * t + b * t + c;\n    }\n}\n// f(t)=at^2+bt+c, when t is [t0, t1]\nbool quadratic_function_rootfinder(\n    const Rational& a,\n    const Rational& b,\n    const Rational& c,\n    const Rational t0,\n    const Rational t1) // t0 t1 no matter which is bigger\n{\n    Rational ft0, ft1;\n    ft0 = quadratic_function_value(a, b, c, t0);\n    ft1 = quadratic_function_value(a, b, c, t1);\n    if (ft0.get_sign() == 0 || ft1.get_sign() == 0)\n        return true;\n    if (ft0.get_sign() != ft1.get_sign())\n        return true;\n    // the following are cases which signs of endpoints are same\n    if (a.get_sign() == 0)\n        return false;\n    Rational t = -b / (2 * a);\n    if (t < t1 && t > t0) {\n        Rational ft\n            = (4 * a * c - b * b); // actually it should be /4a. we only\n                                   // care about the signs so doesnt matter\n        int ftsign = a.get_sign() > 0 ? ft.get_sign() : (-1) * ft.get_sign();\n        if (ft0.get_sign() != ftsign)\n            return true;\n    }\n    return false;\n}\n// v0 is one point, dir is the direction,\n// x0 - x3 are four points defined the shape\nvoid get_quadratic_function(\n    const Rational& v00,\n    const Rational& v01,\n    const Rational& v02,\n    const Rational& dir0,\n    const Rational& dir1,\n    const Rational& dir2,\n    const Vector3d x0d,\n    const Vector3d x1d,\n    const Vector3d x2d,\n    const Vector3d x3d,\n    Rational& a,\n    Rational& b,\n    Rational& c)\n{\n    Vector3r x0(x0d[0], x0d[1], x0d[2]), x1(x1d[0], x1d[1], x1d[2]),\n        x2(x2d[0], x2d[1], x2d[2]), x3(x3d[0], x3d[1], x3d[2]);\n    Rational x00 = x0[0], x01 = x0[1], x02 = x0[2];\n    Rational x10 = x1[0], x11 = x1[1], x12 = x1[2];\n    Rational x20 = x2[0], x21 = x2[1], x22 = x2[2];\n    Rational x30 = x3[0], x31 = x3[1], x32 = x3[2];\n\n    Rational x101 = x11 - x01, x100 = x10 - x00, x102 = x12 - x02,\n             x201 = x21 - x01, x200 = x20 - x00, x300 = x30 - x00,\n             x301 = x31 - x01, x310 = x30 - x10, x211 = x21 - x11,\n             x311 = x31 - x11, x210 = x20 - x10, x202 = x22 - x02,\n             x302 = x32 - x02, x212 = x22 - x12, x312 = x32 - x12;\n    a = (dir0 * (x101 * x202 - x102 * x201)\n         + dir1 * (-x100 * x202 + x102 * x200)\n         + dir2 * (x100 * x201 - x101 * x200))\n            * (dir0 * (-x201 * x302 + x202 * x301)\n               + dir1 * (x200 * x302 - x202 * x300)\n               + dir2 * (-x200 * x301 + x201 * x300))\n        - (dir0 * (-x211 * x312 + x212 * x311)\n           + dir1 * (x210 * x312 - x212 * x310)\n           + dir2 * (-x210 * x311 + x211 * x310))\n            * (dir0 * (x101 * x302 - x102 * x301)\n               + dir1 * (-x100 * x302 + x102 * x300)\n               + dir2 * (x100 * x301 - x101 * x300));\n    b = ((v00 - x00) * (x101 * x202 - x102 * x201)\n         + (v01 - x01) * (-x100 * x202 + x102 * x200)\n         + (v02 - x02) * (x100 * x201 - x101 * x200))\n            * (dir0 * (-x201 * x302 + x202 * x301)\n               + dir1 * (x200 * x302 - x202 * x300)\n               + dir2 * (-x200 * x301 + x201 * x300))\n        + (dir0 * (x101 * x202 - x102 * x201)\n           + dir1 * (-x100 * x202 + x102 * x200)\n           + dir2 * (x100 * x201 - x101 * x200))\n            * ((v00 - x00) * (-x201 * x302 + x202 * x301)\n               + (v01 - x01) * (x200 * x302 - x202 * x300)\n               + (v02 - x02) * (-x200 * x301 + x201 * x300))\n        - ((v00 - x10) * (-x211 * x312 + x212 * x311)\n           + (v01 - x11) * (x210 * x312 - x212 * x310)\n           + (v02 - x12) * (-x210 * x311 + x211 * x310))\n            * (dir0 * (x101 * x302 - x102 * x301)\n               + dir1 * (-x100 * x302 + x102 * x300)\n               + dir2 * (x100 * x301 - x101 * x300))\n        - (dir0 * (-x211 * x312 + x212 * x311)\n           + dir1 * (x210 * x312 - x212 * x310)\n           + dir2 * (-x210 * x311 + x211 * x310))\n            * ((v00 - x00) * (x101 * x302 - x102 * x301)\n               + (v01 - x01) * (-x100 * x302 + x102 * x300)\n               + (v02 - x02) * (x100 * x301 - x101 * x300));\n    c = ((v00 - x00) * (x101 * x202 - x102 * x201)\n         + (v01 - x01) * (-x100 * x202 + x102 * x200)\n         + (v02 - x02) * (x100 * x201 - x101 * x200))\n            * ((v00 - x00) * (-x201 * x302 + x202 * x301)\n               + (v01 - x01) * (x200 * x302 - x202 * x300)\n               + (v02 - x02) * (-x200 * x301 + x201 * x300))\n        - ((v00 - x10) * (-x211 * x312 + x212 * x311)\n           + (v01 - x11) * (x210 * x312 - x212 * x310)\n           + (v02 - x12) * (-x210 * x311 + x211 * x310))\n            * ((v00 - x00) * (x101 * x302 - x102 * x301)\n               + (v01 - x01) * (-x100 * x302 + x102 * x300)\n               + (v02 - x02) * (x100 * x301 - x101 * x300));\n}\nbool get_function_find_root(\n    const bilinear& bl,\n    const Vector3r& p0,\n    const Vector3r& p1,\n    const Rational& t0,\n    const Rational& t1)\n{\n    if (t0 > 1 || t0 < 0)\n        std::cout << \"t is not right: exceed the limit\" << std::endl;\n    if (t1 > 1 || t1 < 0)\n        std::cout << \"t is not right: exceed the limit\" << std::endl;\n    Rational a, b, c;\n\n    Vector3r dir = p1 - p0;\n    get_quadratic_function(\n        Rational(p0[0]), Rational(p0[1]), Rational(p0[2]), Rational(dir[0]),\n        Rational(dir[1]), Rational(dir[2]), bl.v[0], bl.v[1], bl.v[2], bl.v[3],\n        a, b, c);\n    bool res = quadratic_function_rootfinder(a, b, c, t0, t1);\n\n    return res;\n}\nvoid print_sub()\n{\n    // std::cout<<\"time of rootfinder \"<<rftime<<std::endl;\n}\ndouble root_finder_time() { return 0; }\nbool rootfinder(\n    const bilinear& bl,\n    const Vector3d& p0d,\n    const Vector3d& p1d,\n    const bool p0in,\n    const bool p1in,\n    const int pairid)\n{\n\n    Vector3r p0(p0d[0], p0d[1], p0d[2]), p1(p1d[0], p1d[1], p1d[2]);\n\n    if (p0in && p1in) {\n        // t0=0, t1=1\n        return get_function_find_root(bl, p0, p1, Rational(0), Rational(1));\n    }\n    int fid = 2 * pairid; // it should be 0 or 2\n    Rational t;\n    if (p0in) {\n        bool res1 = seg_triangle_inter_return_t(\n            p0d, p1d, bl.v[bl.facets[fid][0]], bl.v[bl.facets[fid][1]],\n            bl.v[bl.facets[fid][2]], t);\n        if (!res1) {\n            res1 = seg_triangle_inter_return_t(\n                p0d, p1d, bl.v[bl.facets[fid + 1][0]],\n                bl.v[bl.facets[fid + 1][1]], bl.v[bl.facets[fid + 1][2]], t);\n        }\n        if (!res1)\n            return false; // means not really intersected\n        // we got t\n        return get_function_find_root(bl, p0, p1, 0, t);\n    }\n    if (p1in) { // change the order of input to get t just because we want\n                // domain to be [0, t]\n        bool res1 = seg_triangle_inter_return_t( // here get n1, d1, n2, d2\n            p1d, p0d, bl.v[bl.facets[fid][0]], bl.v[bl.facets[fid][1]],\n            bl.v[bl.facets[fid][2]], t);\n        if (!res1) {\n            res1 = seg_triangle_inter_return_t(\n                p1d, p0d, bl.v[bl.facets[fid + 1][0]],\n                bl.v[bl.facets[fid + 1][1]], bl.v[bl.facets[fid + 1][2]], t);\n        }\n        if (!res1)\n            return false; // means not really intersected\n        // we got t\n        return get_function_find_root(bl, p1, p0, 0, t);\n    }\n\n    Rational t1;\n    bool res1 = seg_triangle_inter_return_t(\n        p0d, p1d, bl.v[bl.facets[fid][0]], bl.v[bl.facets[fid][1]],\n        bl.v[bl.facets[fid][2]], t);\n    if (!res1)\n        return false; // means not really intersected\n    bool res2 = seg_triangle_inter_return_t(\n        p0d, p1d, bl.v[bl.facets[fid + 1][0]], bl.v[bl.facets[fid + 1][1]],\n        bl.v[bl.facets[fid + 1][2]], t1);\n    if (!res2)\n        return false; // means not really intersected\n    // we got t, t1\n    return get_function_find_root(bl, p0, p1, t, t1);\n}\n// segment intersect two opposite faces not included. compare phi, then use root\n// finder\nbool is_seg_intersect_not_degenerated_bilinear(\n    bilinear& bl,\n    const Vector3d& p0,\n    const Vector3d& p1,\n    const bool pin0,\n    const bool pin1)\n{\n    // first compare phi, if phis are different, intersected;\n    // then check if the line intersect two opposite facets of bilinear, if so,\n    // use rootfinder, else, not intersected\n\n    if (pin0 && pin1) { // two points are all inside\n\n        Rational phi0 = phi(p0, bl.v);\n        Rational phi1 = phi(p1, bl.v);\n        if (phi0 == 0 || phi1 == 0 || phi0.get_sign() != phi1.get_sign())\n            return true;\n        if (line_shoot_same_pair_tet(p0, p1, phi1.get_sign(), bl)) {\n            if (phi1.get_sign() == bl.phi_f[0]) {\n\n                bool rf = rootfinder(bl, p0, p1, pin0, pin1, 0);\n\n                return rf;\n            }\n\n            else {\n\n                bool rf = rootfinder(bl, p0, p1, pin0, pin1, 1);\n\n                return rf;\n            }\n\n        }\n\n        else\n            return false; // if the phis are the same, and shoot same pair, need\n                          // to use rootfinder\n    }\n    if (pin0) {\n        Rational phi0 = phi(p0, bl.v);\n        if (phi0 == 0)\n            return true;\n        int hitpair = -1;\n\n        for (int i = 0; i < 4; i++) {\n            if (segment_triangle_intersection( // 0,1,2,3. 1,2,3 are all\n                                               // intersected\n                    p0, p1, bl.v[bl.facets[i][0]], bl.v[bl.facets[i][1]],\n                    bl.v[bl.facets[i][2]], false)\n                > 0) {\n                if (i < 2)\n                    hitpair = 0;\n                else\n                    hitpair = 1;\n                break;\n            }\n        }\n        if (bl.phi_f[0] == 2)\n            get_tet_phi(bl);\n        if (hitpair == -1)\n            return false;\n        if (phi0.get_sign()\n            != bl.phi_f[hitpair]) { // if different, intersected, if same,\n                                    // extend; if shoot same, rootfinder, if\n                                    // shoot diff, false\n            return true;\n        }\n\n        else {\n            if (line_shoot_same_pair_tet(p0, p1, phi0.get_sign(), bl)) {\n                if (phi0.get_sign() == bl.phi_f[0]) {\n\n                    bool rf = rootfinder(bl, p0, p1, pin0, pin1, 0);\n\n                    return rf;\n                }\n\n                else {\n\n                    bool rf = rootfinder(bl, p0, p1, pin0, pin1, 1);\n\n                    return rf;\n                }\n\n            }\n\n            else\n                return false; // if the phis are the same, and shoot same pair,\n                              // need to use rootfinder\n        }\n    }\n    if (pin1) {\n        Rational phi1 = phi(p1, bl.v);\n        if (phi1 == 0)\n            return true;\n        int hitpair = -1;\n        for (int i = 0; i < 4; i++) {\n            if (segment_triangle_intersection( // 0,1,2,3. 1,2,3 are all\n                                               // intersected\n                    p0, p1, bl.v[bl.facets[i][0]], bl.v[bl.facets[i][1]],\n                    bl.v[bl.facets[i][2]], false)\n                > 0) {\n                if (i < 2)\n                    hitpair = 0;\n                else\n                    hitpair = 1;\n                break;\n            }\n        }\n        if (bl.phi_f[0] == 2)\n            get_tet_phi(bl);\n        if (hitpair == -1)\n            return false; // parallel , should be impossible\n        if (phi1.get_sign() != bl.phi_f[hitpair]) {\n            return true;\n        }\n\n        else {\n            if (line_shoot_same_pair_tet(p0, p1, phi1.get_sign(), bl)) {\n                if (phi1.get_sign() == bl.phi_f[0]) {\n\n                    bool rf = rootfinder(bl, p0, p1, pin0, pin1, 0);\n\n                    return rf;\n                }\n\n                else {\n\n                    bool rf = rootfinder(bl, p0, p1, pin0, pin1, 1);\n\n                    return rf;\n                }\n\n            } else\n                return false; // if the phis are the same, and shoot same pair,\n                              // need to use rootfinder\n        }\n    }\n    if (!pin0\n        && !pin1) { // not intersect tet (false), or intersect same side(root\n                    // finder) or intersect diff side(checked before)\n\n        if (line_shoot_same_pair_tet(p0, p1, 1, bl)) {\n            if (1 == bl.phi_f[0]) {\n\n                bool rf = rootfinder(bl, p0, p1, pin0, pin1, 0);\n\n                return rf;\n            }\n\n            else {\n\n                bool rf = rootfinder(bl, p0, p1, pin0, pin1, 1);\n\n                return rf;\n            }\n\n        }\n\n        else if (line_shoot_same_pair_tet(p0, p1, -1, bl)) {\n            if (-1 == bl.phi_f[0]) {\n\n                bool rf = rootfinder(bl, p0, p1, pin0, pin1, 0);\n\n                return rf;\n            }\n\n            else {\n\n                bool rf = rootfinder(bl, p0, p1, pin0, pin1, 1);\n\n                return rf;\n            }\n        }\n        return false; // if the phis are the same, and shoot same pair,\n                      // need to use rootfinder\n    }\n    std::cout\n        << \" it cannot happen here in is_seg_intersect_not_degenerated_bilinear\"\n        << std::endl;\n    return false;\n}\n\nbool is_cube_edge_intersect_bilinear(\n    bilinear& bl, const cube& cb, const std::array<bool, 8>& pin)\n{\n    if (bl.is_degenerated)\n        return false; // we already checked degenerated cases\n    for (int i = 0; i < 12; i++) {\n        if (is_seg_intersect_not_degenerated_bilinear(\n                bl, cb.vr[cb.edgeid[i][0]], cb.vr[cb.edgeid[i][1]],\n                pin[cb.edgeid[i][0]], pin[cb.edgeid[i][1]]))\n            return true;\n    }\n    return false;\n}\n// vin is true, this vertex has intersection with open tet\n// if tet is degenerated, just tell us if cube is intersected with the shape\nbool is_cube_intersect_tet_opposite_faces(\n    const bilinear& bl,\n    const Vector3d& pmin,\n    const Vector3d& pmax,\n    const cube& cube,\n    std::array<bool, 8>& vin,\n    bool& cube_inter_tet)\n{\n\n    cube_inter_tet = false;\n    if (!bl.is_degenerated) {\n        for (int i = 0; i < 8; i++) {\n            vin[i] = false;\n\n            if (is_point_inside_tet(bl, cube.vr[i])) {\n                cube_inter_tet = true;\n                vin[i] = true;\n            }\n        }\n    } else {\n\n        bool rst = is_cube_intersect_degenerated_bilinear(bl, cube);\n\n        return rst;\n    }\n\n    bool side1 = false;\n    bool side2 = false;\n    Vector3d vmin, vmax;\n    for (int i = 0; i < 12; i++) {\n\n        if (vin[cube.edgeid[i][0]]\n            && vin[cube.edgeid[i][1]]) { // if two vertices are all inside, it\n                                         // can not cut any edge\n            cube_inter_tet = true;\n            continue;\n        }\n        get_edge_coners(\n            cube.vr[cube.edgeid[i][0]], cube.vr[cube.edgeid[i][1]], vmin, vmax);\n        if (!box_box_intersection(pmin, pmax, vmin, vmax)) {\n            continue;\n        }\n        for (int j = 0; j < 4; j++) {\n\n            int inter = segment_triangle_intersection(\n                cube.vr[cube.edgeid[i][0]], cube.vr[cube.edgeid[i][1]],\n                bl.v[bl.facets[j][0]], bl.v[bl.facets[j][1]],\n                bl.v[bl.facets[j][2]], false);\n\n            if (inter > 0) {\n                cube_inter_tet = true;\n                if (j == 0 || j == 1)\n                    side1 = true;\n                if (j == 2 || j == 3)\n                    side2 = true;\n                if (side1 && side2)\n                    return true;\n            }\n        }\n    }\n    if (side1 && side2)\n        return true;\n    return false;\n}\nbool cube_discrete_bilinear_intersection(\n    const cube& cb, const bilinear& bl, int n)\n{\n    Vector3d s0, s1;\n    for (int i = 0; i < 12; i++) {\n        s0 = cb.vr[cb.edgeid[i][0]];\n        s1 = cb.vr[cb.edgeid[i][1]];\n        if (seg_discrete_bilinear_intersection(bl, n, s0, s1)) // return 0,1,2\n\n            return true;\n    }\n    return false;\n}\n\n} // namespace doubleccd\n", "meta": {"hexsha": "008956424716512b2ae2ade7cd874afe0e40ad44", "size": 61045, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "doubleccd/double_subfunctions.cpp", "max_stars_repo_name": "geometryprocessing/ExactRootParityCCD", "max_stars_repo_head_hexsha": "bf4847bc5ccf1b822610b561ae2e6939c0742da1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9.0, "max_stars_repo_stars_event_min_datetime": "2022-02-21T19:40:00.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T01:18:31.000Z", "max_issues_repo_path": "doubleccd/double_subfunctions.cpp", "max_issues_repo_name": "geometryprocessing/ExactRootParityCCD", "max_issues_repo_head_hexsha": "bf4847bc5ccf1b822610b561ae2e6939c0742da1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "doubleccd/double_subfunctions.cpp", "max_forks_repo_name": "geometryprocessing/ExactRootParityCCD", "max_forks_repo_head_hexsha": "bf4847bc5ccf1b822610b561ae2e6939c0742da1", "max_forks_repo_licenses": ["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.7221942627, "max_line_length": 80, "alphanum_fraction": 0.5039069539, "num_tokens": 20429, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6224593312018546, "lm_q2_score": 0.523420348936324, "lm_q1q2_score": 0.3258078803363456}}
{"text": "#pragma once\n\n#if defined(_OPENMP)\n#include <omp.h>\n#endif\n\n#include <chrono>\n#include <cmath>\n#include <cstdint>\n#include <functional>\n#include <fstream>\n#include <iostream>\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/openmp_helpers.hpp>\n#include <common_robotics_utilities/voxel_grid.hpp>\n#include <voxelized_geometry_tools/signed_distance_field.hpp>\n\nnamespace voxelized_geometry_tools\n{\nnamespace signed_distance_field_generation\n{\nusing common_robotics_utilities::voxel_grid::GridIndex;\nusing common_robotics_utilities::voxel_grid::GridSizes;\n\nstruct BucketCell\n{\n  double distance_square = 0.0;\n  int32_t update_direction = 0;\n  uint32_t location[3] = {0u, 0u, 0u};\n  uint32_t closest_point[3] = {0u, 0u, 0u};\n};\n\ntypedef common_robotics_utilities::voxel_grid\n    ::VoxelGrid<BucketCell, std::vector<BucketCell>> DistanceField;\n\ninline int32_t GetDirectionNumber(\n    const int32_t dx, const int32_t dy, const int32_t dz)\n{\n  return ((dx + 1) * 9) + ((dy + 1) * 3) + (dz + 1);\n}\n\ninline std::vector<std::vector<std::vector<std::vector<int32_t>>>>\nMakeNeighborhoods()\n{\n  // First vector<>: 2 - the first bucket queue, the points we know are zero\n  // distance, start with a complete set of neighbors to check. Every other\n  // bucket queue checks fewer neighbors.\n  // Second vector<>: 27 (# of source directions in fully-connected 3d grid).\n  // Third vector<>:\n  std::vector<std::vector<std::vector<std::vector<int32_t>>>> neighborhoods;\n  // I don't know why there are 2 initial neighborhoods.\n  neighborhoods.resize(2);\n  for (size_t n = 0; n < neighborhoods.size(); n++)\n  {\n    neighborhoods[n].resize(27);\n    // Loop through the source directions.\n    for (int32_t dx = -1; dx <= 1; dx++)\n    {\n      for (int32_t dy = -1; dy <= 1; dy++)\n      {\n        for (int32_t dz = -1; dz <= 1; dz++)\n        {\n          const int32_t direction_number = GetDirectionNumber(dx, dy, dz);\n          // Loop through the target directions.\n          for (int32_t tdx = -1; tdx <= 1; tdx++)\n          {\n            for (int32_t tdy = -1; tdy <= 1; tdy++)\n            {\n              for (int32_t tdz = -1; tdz <= 1; tdz++)\n              {\n                // Ignore the case of ourself.\n                if (tdx == 0 && tdy == 0 && tdz == 0)\n                {\n                  continue;\n                }\n                // Why is one set of neighborhoods larger than the other?\n                if (n >= 1)\n                {\n                  if ((abs(tdx) + abs(tdy) + abs(tdz)) != 1)\n                  {\n                    continue;\n                  }\n                  if ((dx * tdx) < 0 || (dy * tdy) < 0 || (dz * tdz) < 0)\n                  {\n                    continue;\n                  }\n                }\n                std::vector<int32_t> new_point;\n                new_point.resize(3);\n                new_point[0] = tdx;\n                new_point[1] = tdy;\n                new_point[2] = tdz;\n                neighborhoods[n][direction_number].push_back(new_point);\n              }\n            }\n          }\n        }\n      }\n    }\n  }\n  return neighborhoods;\n}\n\ninline double ComputeDistanceSquared(\n    const int32_t x1, const int32_t y1, const int32_t z1,\n    const int32_t x2, const int32_t y2, const int32_t z2)\n{\n  const int32_t dx = x1 - x2;\n  const int32_t dy = y1 - y2;\n  const int32_t dz = z1 - z2;\n  return double((dx * dx) + (dy * dy) + (dz * dz));\n}\n\nclass MultipleThreadIndexQueueWrapper\n{\npublic:\n\n  explicit MultipleThreadIndexQueueWrapper(const size_t max_queues)\n  {\n    per_thread_queues_.resize(\n        common_robotics_utilities::openmp_helpers::GetNumOmpThreads(),\n        ThreadIndexQueues(max_queues));\n  }\n\n  const GridIndex& Query(const int32_t distance_squared, const size_t idx) const\n  {\n    size_t working_index = idx;\n    for (size_t thread = 0; thread < per_thread_queues_.size(); thread++)\n    {\n      const auto& current_thread_queue =\n          per_thread_queues_.at(thread).at(distance_squared);\n      const size_t current_thread_queue_size = current_thread_queue.size();\n      if (working_index < current_thread_queue_size)\n      {\n        return current_thread_queue.at(working_index);\n      }\n      else\n      {\n        working_index -= current_thread_queue_size;\n      }\n    }\n    throw std::runtime_error(\"Failed to find item\");\n  }\n\n  size_t NumQueues() const\n  {\n    return per_thread_queues_.at(0).size();\n  }\n\n  size_t Size(const int32_t distance_squared) const\n  {\n    size_t total_size = 0;\n    for (size_t thread = 0; thread < per_thread_queues_.size(); thread++)\n    {\n      total_size += per_thread_queues_.at(thread).at(distance_squared).size();\n    }\n    return total_size;\n  }\n\n  void Enqueue(const int32_t distance_squared, const GridIndex& index)\n  {\n    const int32_t thread_num\n        = common_robotics_utilities::openmp_helpers::GetContextOmpThreadNum();\n    per_thread_queues_.at(thread_num).at(distance_squared).push_back(index);\n  }\n\n  void ClearCompletedQueues(const int32_t distance_squared)\n  {\n    for (size_t thread = 0; thread < per_thread_queues_.size(); thread++)\n    {\n      per_thread_queues_.at(thread).at(distance_squared).clear();\n    }\n  }\n\nprivate:\n  typedef std::vector<std::vector<GridIndex>> ThreadIndexQueues;\n  std::vector<ThreadIndexQueues> per_thread_queues_;\n\n};\n\ninline DistanceField BuildDistanceFieldSerial(\n    const Eigen::Isometry3d& grid_origin_transform,\n    const GridSizes& grid_sizes, const std::vector<GridIndex>& points)\n{\n  if (!grid_sizes.UniformCellSize())\n  {\n    throw std::invalid_argument(\n        \"Cannot build distance field from grid with non-uniform cells\");\n  }\n  const std::chrono::time_point<std::chrono::steady_clock> start_time\n      = std::chrono::steady_clock::now();\n  // Make the DistanceField container\n  BucketCell default_cell;\n  default_cell.distance_square = std::numeric_limits<double>::infinity();\n  DistanceField distance_field(grid_origin_transform, grid_sizes, default_cell);\n  // Compute maximum distance square\n  const int64_t max_distance_square =\n      (distance_field.GetNumXCells() * distance_field.GetNumXCells())\n      + (distance_field.GetNumYCells() * distance_field.GetNumYCells())\n      + (distance_field.GetNumZCells() * distance_field.GetNumZCells());\n  // Make bucket queue\n  std::vector<std::vector<BucketCell>> bucket_queue(max_distance_square + 1);\n  bucket_queue[0].reserve(points.size());\n  // Set initial update direction\n  int32_t initial_update_direction = GetDirectionNumber(0, 0, 0);\n  // Mark all provided points with distance zero and add to the bucket queue\n  for (size_t index = 0; index < points.size(); index++)\n  {\n    const GridIndex& current_index = points[index];\n    auto query = distance_field.GetMutable(current_index);\n    if (query)\n    {\n      query.Value().location[0] = static_cast<uint32_t>(current_index.X());\n      query.Value().location[1] = static_cast<uint32_t>(current_index.Y());\n      query.Value().location[2] = static_cast<uint32_t>(current_index.Z());\n      query.Value().closest_point[0] = static_cast<uint32_t>(current_index.X());\n      query.Value().closest_point[1] = static_cast<uint32_t>(current_index.Y());\n      query.Value().closest_point[2] = static_cast<uint32_t>(current_index.Z());\n      query.Value().distance_square = 0.0;\n      query.Value().update_direction = initial_update_direction;\n      bucket_queue[0].push_back(query.Value());\n    }\n    // If the point is outside the bounds of the SDF, skip\n    else\n    {\n      throw std::runtime_error(\"Point for BuildDistanceField out of bounds\");\n    }\n  }\n  // HERE BE DRAGONS\n  // Process the bucket queue\n  const std::vector<std::vector<std::vector<std::vector<int>>>> neighborhoods =\n      MakeNeighborhoods();\n  for (size_t bq_idx = 0; bq_idx < bucket_queue.size(); bq_idx++)\n  {\n    for (const auto& cur_cell : bucket_queue[bq_idx])\n    {\n      // Get the current location\n      const double x = cur_cell.location[0];\n      const double y = cur_cell.location[1];\n      const double z = cur_cell.location[2];\n      // Pick the update direction\n      // Only the first bucket queue gets the larger set of neighborhoods?\n      // Don't really userstand why.\n      const size_t direction_switch = (bq_idx > 0) ? 1 : 0;\n      // Make sure the update direction is valid\n      if (cur_cell.update_direction < 0 || cur_cell.update_direction > 26)\n      {\n        continue;\n      }\n      // Get the current neighborhood list\n      const std::vector<std::vector<int>>& neighborhood =\n          neighborhoods[direction_switch][cur_cell.update_direction];\n      // Update the distance from the neighboring cells\n      for (size_t nh_idx = 0; nh_idx < neighborhood.size(); nh_idx++)\n      {\n        // Get the direction to check\n        const int32_t dx = neighborhood[nh_idx][0];\n        const int32_t dy = neighborhood[nh_idx][1];\n        const int32_t dz = neighborhood[nh_idx][2];\n        const int32_t nx = static_cast<int32_t>(x + dx);\n        const int32_t ny = static_cast<int32_t>(y + dy);\n        const int32_t nz = static_cast<int32_t>(z + dz);\n        auto neighbor_query =\n            distance_field.GetMutable(static_cast<int64_t>(nx),\n                                      static_cast<int64_t>(ny),\n                                      static_cast<int64_t>(nz));\n        if (!neighbor_query)\n        {\n          // \"Neighbor\" is outside the bounds of the SDF\n          continue;\n        }\n        // Update the neighbor's distance based on the current\n        const int32_t new_distance_square =\n            static_cast<int32_t>(ComputeDistanceSquared(\n                                   nx, ny, nz,\n                                   cur_cell.closest_point[0],\n                                   cur_cell.closest_point[1],\n                                   cur_cell.closest_point[2]));\n        if (new_distance_square > max_distance_square)\n        {\n          // Skip these cases\n          continue;\n        }\n        if (new_distance_square < neighbor_query.Value().distance_square)\n        {\n          // If the distance is better, time to update the neighbor\n          neighbor_query.Value().distance_square = new_distance_square;\n          neighbor_query.Value().closest_point[0] = cur_cell.closest_point[0];\n          neighbor_query.Value().closest_point[1] = cur_cell.closest_point[1];\n          neighbor_query.Value().closest_point[2] = cur_cell.closest_point[2];\n          neighbor_query.Value().location[0] = nx;\n          neighbor_query.Value().location[1] = ny;\n          neighbor_query.Value().location[2] = nz;\n          neighbor_query.Value().update_direction =\n              GetDirectionNumber(dx, dy, dz);\n          // Add the neighbor into the bucket queue\n          bucket_queue[new_distance_square].push_back(neighbor_query.Value());\n        }\n      }\n    }\n    // Clear the current queue now that we're done with it\n    bucket_queue[bq_idx].clear();\n  }\n  const std::chrono::time_point<std::chrono::steady_clock> end_time\n      = std::chrono::steady_clock::now();\n  const std::chrono::duration<double> elapsed = end_time - start_time;\n  std::cout << \"Computed DistanceField in \" << elapsed.count() << \" seconds\"\n            << std::endl;\n  return distance_field;\n}\n\ninline DistanceField BuildDistanceFieldParallel(\n    const Eigen::Isometry3d& grid_origin_transform,\n    const GridSizes& grid_sizes,\n    const std::vector<GridIndex>& points)\n{\n  if (!grid_sizes.UniformCellSize())\n  {\n    throw std::invalid_argument(\n        \"Cannot build distance field from grid with non-uniform cells\");\n  }\n  const std::chrono::time_point<std::chrono::steady_clock> start_time\n      = std::chrono::steady_clock::now();\n  // Make the DistanceField container\n  BucketCell default_cell;\n  default_cell.distance_square = std::numeric_limits<double>::infinity();\n  DistanceField distance_field(grid_origin_transform, grid_sizes, default_cell);\n  // Compute maximum distance square\n  const int64_t max_distance_square =\n      (distance_field.GetNumXCells() * distance_field.GetNumXCells())\n      + (distance_field.GetNumYCells() * distance_field.GetNumYCells())\n      + (distance_field.GetNumZCells() * distance_field.GetNumZCells());\n  // Make bucket queue\n  std::vector<std::vector<BucketCell>> bucket_queue(max_distance_square + 1);\n  bucket_queue[0].reserve(points.size());\n  MultipleThreadIndexQueueWrapper bucket_queues(max_distance_square + 1);\n  // Set initial update direction\n  int32_t initial_update_direction = GetDirectionNumber(0, 0, 0);\n  // Mark all provided points with distance zero and add to the bucket queues\n  // points MUST NOT CONTAIN DUPLICATE ENTRIES!\n#if defined(_OPENMP)\n#pragma omp parallel for\n#endif\n  for (size_t index = 0; index < points.size(); index++)\n  {\n    const GridIndex& current_index = points[index];\n    auto query = distance_field.GetMutable(current_index);\n    if (query)\n    {\n      query.Value().location[0] = static_cast<uint32_t>(current_index.X());\n      query.Value().location[1] = static_cast<uint32_t>(current_index.Y());\n      query.Value().location[2] = static_cast<uint32_t>(current_index.Z());\n      query.Value().closest_point[0] = static_cast<uint32_t>(current_index.X());\n      query.Value().closest_point[1] = static_cast<uint32_t>(current_index.Y());\n      query.Value().closest_point[2] = static_cast<uint32_t>(current_index.Z());\n      query.Value().distance_square = 0.0;\n      query.Value().update_direction = initial_update_direction;\n      bucket_queues.Enqueue(0, current_index);\n    }\n    // If the point is outside the bounds of the SDF, skip\n    else\n    {\n      throw std::runtime_error(\"Point for BuildDistanceField out of bounds\");\n    }\n  }\n  // HERE BE DRAGONS\n  // Process the bucket queue\n  const std::vector<std::vector<std::vector<std::vector<int>>>> neighborhoods =\n      MakeNeighborhoods();\n  for (int32_t current_distance_square = 0;\n       current_distance_square\n           < static_cast<int32_t>(bucket_queues.NumQueues());\n       current_distance_square++)\n  {\n#if defined(_OPENMP)\n#pragma omp parallel for\n#endif\n    for (size_t idx = 0; idx < bucket_queues.Size(current_distance_square);\n         idx++)\n    {\n      const GridIndex& current_index =\n          bucket_queues.Query(current_distance_square, idx);\n      // Get the current location\n      const BucketCell& cur_cell =\n          distance_field.GetImmutable(current_index).Value();\n      const double x = cur_cell.location[0];\n      const double y = cur_cell.location[1];\n      const double z = cur_cell.location[2];\n      // Pick the update direction\n      // Only the first bucket queue gets the larger set of neighborhoods?\n      // Don't really userstand why.\n      const size_t direction_switch = (current_distance_square > 0) ? 1 : 0;\n      // Make sure the update direction is valid\n      if (cur_cell.update_direction < 0 || cur_cell.update_direction > 26)\n      {\n        continue;\n      }\n      // Get the current neighborhood list\n      const std::vector<std::vector<int32_t>>& neighborhood =\n          neighborhoods[direction_switch][cur_cell.update_direction];\n      // Update the distance from the neighboring cells\n      for (size_t nh_idx = 0; nh_idx < neighborhood.size(); nh_idx++)\n      {\n        // Get the direction to check\n        const int32_t dx = neighborhood[nh_idx][0];\n        const int32_t dy = neighborhood[nh_idx][1];\n        const int32_t dz = neighborhood[nh_idx][2];\n        const int32_t nx = static_cast<int32_t>(x + dx);\n        const int32_t ny = static_cast<int32_t>(y + dy);\n        const int32_t nz = static_cast<int32_t>(z + dz);\n        const GridIndex neighbor_index(static_cast<int64_t>(nx),\n                                       static_cast<int64_t>(ny),\n                                       static_cast<int64_t>(nz));\n        auto neighbor_query = distance_field.GetMutable(neighbor_index);\n        if (!neighbor_query)\n        {\n          // \"Neighbor\" is outside the bounds of the SDF\n          continue;\n        }\n        // Update the neighbor's distance based on the current\n        const int32_t new_distance_square =\n            static_cast<int32_t>(ComputeDistanceSquared(\n                                   nx, ny, nz,\n                                   cur_cell.closest_point[0],\n                                   cur_cell.closest_point[1],\n                                   cur_cell.closest_point[2]));\n        if (new_distance_square > max_distance_square)\n        {\n          // Skip these cases\n          continue;\n        }\n        if (new_distance_square < neighbor_query.Value().distance_square)\n        {\n          // If the distance is better, time to update the neighbor\n          neighbor_query.Value().distance_square = new_distance_square;\n          neighbor_query.Value().closest_point[0] = cur_cell.closest_point[0];\n          neighbor_query.Value().closest_point[1] = cur_cell.closest_point[1];\n          neighbor_query.Value().closest_point[2] = cur_cell.closest_point[2];\n          neighbor_query.Value().location[0] = nx;\n          neighbor_query.Value().location[1] = ny;\n          neighbor_query.Value().location[2] = nz;\n          neighbor_query.Value().update_direction =\n              GetDirectionNumber(dx, dy, dz);\n          // Add the neighbor into the bucket queue\n          bucket_queues.Enqueue(new_distance_square, neighbor_index);\n        }\n      }\n    }\n    // Clear the current queues now that we're done with it\n    bucket_queues.ClearCompletedQueues(current_distance_square);\n  }\n  const std::chrono::time_point<std::chrono::steady_clock> end_time\n      = std::chrono::steady_clock::now();\n  const std::chrono::duration<double> elapsed = end_time - start_time;\n  std::cout << \"Computed DistanceField in \" << elapsed.count() << \" seconds\"\n            << std::endl;\n  return distance_field;\n}\n\ninline DistanceField BuildDistanceField(\n    const Eigen::Isometry3d& grid_origin_transform,\n    const GridSizes& grid_sizes,\n    const std::vector<GridIndex>& points,\n    const bool use_parallel)\n{\n  if (use_parallel)\n  {\n    return BuildDistanceFieldParallel(\n        grid_origin_transform, grid_sizes, points);\n  }\n  else\n  {\n    return BuildDistanceFieldSerial(grid_origin_transform, grid_sizes, points);\n  }\n}\n\ntemplate<typename SDFBackingStore>\nclass SignedDistanceFieldResult\n{\nprivate:\n  SignedDistanceField<SDFBackingStore> distance_field_;\n  double maximum_ = 0.0;\n  double minimum_ = 0.0;\n\npublic:\n  SignedDistanceFieldResult(\n      const SignedDistanceField<SDFBackingStore>& distance_field,\n      const double maximum, const double minimum)\n      : distance_field_(distance_field),\n        maximum_(maximum), minimum_(minimum)\n  {\n    if (minimum_ > maximum_)\n    {\n      throw std::invalid_argument(\"minimum_ > maximum_\");\n    }\n  }\n\n  const SignedDistanceField<SDFBackingStore>& DistanceField() const\n  {\n    return distance_field_;\n  }\n\n  const SignedDistanceField<SDFBackingStore>& MutableDistanceField()\n  {\n    return distance_field_;\n  }\n\n  double Maximum() const { return maximum_; }\n\n  double Minimum() const { return minimum_; }\n};\n\ntemplate<typename SDFBackingStore>\nSignedDistanceFieldResult<SDFBackingStore> MakeSignedDistanceFieldResult(\n    const SignedDistanceField<SDFBackingStore>& signed_distance_field,\n    const double maximum, const double minimum)\n{\n  return SignedDistanceFieldResult<SDFBackingStore>(\n      signed_distance_field, maximum, minimum);\n}\n\n\ntemplate<typename T, typename SDFBackingStore=std::vector<float>>\ninline SignedDistanceFieldResult<SDFBackingStore> ExtractSignedDistanceField(\n    const Eigen::Isometry3d& grid_origin_tranform, const GridSizes& grid_sizes,\n    const std::function<bool(const GridIndex&)>& is_filled_fn,\n    const float oob_value, const std::string& frame, const bool use_parallel)\n{\n  const std::chrono::time_point<std::chrono::steady_clock> start_time\n      = std::chrono::steady_clock::now();\n  std::vector<GridIndex> filled;\n  std::vector<GridIndex> free;\n  for (int64_t x_index = 0; x_index < grid_sizes.NumXCells(); x_index++)\n  {\n    for (int64_t y_index = 0; y_index < grid_sizes.NumYCells(); y_index++)\n    {\n      for (int64_t z_index = 0; z_index < grid_sizes.NumZCells(); z_index++)\n      {\n        const GridIndex current_index(x_index, y_index, z_index);\n        if (is_filled_fn(current_index))\n        {\n          // Mark as filled\n          filled.push_back(current_index);\n        }\n        else\n        {\n          // Mark as free space\n          free.push_back(current_index);\n        }\n      }\n    }\n  }\n  // Make two distance fields, one for distance to filled voxels, one for\n  // distance to free voxels.\n  const DistanceField filled_distance_field =\n      BuildDistanceField(\n        grid_origin_tranform, grid_sizes, filled, use_parallel);\n  const DistanceField free_distance_field =\n      BuildDistanceField(grid_origin_tranform, grid_sizes, free, use_parallel);\n  // Generate the SDF\n  SignedDistanceField<SDFBackingStore> new_sdf(\n      grid_origin_tranform, frame, grid_sizes, oob_value);\n  double max_distance = -std::numeric_limits<double>::infinity();\n  double min_distance = std::numeric_limits<double>::infinity();\n  for (int64_t x_index = 0; x_index < new_sdf.GetNumXCells(); x_index++)\n  {\n    for (int64_t y_index = 0; y_index < new_sdf.GetNumYCells(); y_index++)\n    {\n      for (int64_t z_index = 0; z_index < new_sdf.GetNumZCells(); z_index++)\n      {\n        const double distance1 =\n            std::sqrt(\n                filled_distance_field.GetImmutable(x_index, y_index, z_index)\n                    .Value().distance_square)\n            * new_sdf.GetResolution();\n        const double distance2 =\n            std::sqrt(\n                free_distance_field.GetImmutable(x_index, y_index, z_index)\n                    .Value().distance_square)\n            * new_sdf.GetResolution();\n        const double distance = distance1 - distance2;\n        if (distance > max_distance)\n        {\n          max_distance = distance;\n        }\n        if (distance < min_distance)\n        {\n          min_distance = distance;\n        }\n        new_sdf.SetValue(\n            x_index, y_index, z_index, static_cast<float>(distance));\n      }\n    }\n  }\n  const std::chrono::time_point<std::chrono::steady_clock> end_time\n      = std::chrono::steady_clock::now();\n  const std::chrono::duration<double> elapsed = end_time - start_time;\n  std::cout << \"Computed SDF for grid size in \" << elapsed.count() << \" seconds\"\n            << std::endl;\n  return MakeSignedDistanceFieldResult<SDFBackingStore>(\n      new_sdf, max_distance, min_distance);\n}\n\ntemplate<typename T, typename BackingStore=std::vector<T>,\n         typename SDFBackingStore=std::vector<float>>\ninline SignedDistanceFieldResult<SDFBackingStore> ExtractSignedDistanceField(\n    const common_robotics_utilities::voxel_grid\n        ::VoxelGridBase<T, BackingStore>& grid,\n    const std::function<bool(const GridIndex&)>& is_filled_fn,\n    const float oob_value, const std::string& frame,\n    const bool use_parallel, const bool add_virtual_border)\n{\n  if (!grid.HasUniformCellSize())\n  {\n    throw std::invalid_argument(\"Grid must have uniform resolution\");\n  }\n  if (add_virtual_border == false)\n  {\n    // This is the conventional single-pass result\n    return ExtractSignedDistanceField<T, SDFBackingStore>(\n        grid.GetOriginTransform(), grid.GetGridSizes(), is_filled_fn, oob_value,\n        frame, use_parallel);\n  }\n  else\n  {\n    const int64_t x_axis_size_offset =\n        (grid.GetNumXCells() > 1) ? INT64_C(2) : INT64_C(0);\n    const int64_t x_axis_query_offset =\n        (grid.GetNumXCells() > 1) ? INT64_C(1) : INT64_C(0);\n    const int64_t y_axis_size_offset =\n        (grid.GetNumYCells() > 1) ? INT64_C(2) : INT64_C(0);\n    const int64_t y_axis_query_offset =\n        (grid.GetNumYCells() > 1) ? INT64_C(1) : INT64_C(0);\n    const int64_t z_axis_size_offset =\n        (grid.GetNumZCells() > 1) ? INT64_C(2) : INT64_C(0);\n    const int64_t z_axis_query_offset =\n        (grid.GetNumZCells() > 1) ? INT64_C(1) : INT64_C(0);\n    // We need to lie about the size of the grid to add a virtual border\n    const int64_t num_x_cells = grid.GetNumXCells() + x_axis_size_offset;\n    const int64_t num_y_cells = grid.GetNumYCells() + y_axis_size_offset;\n    const int64_t num_z_cells = grid.GetNumZCells() + z_axis_size_offset;\n    // Make some deceitful helper functions that hide our lies about size\n    // For the free space SDF, we lie and say the virtual border is filled\n    const std::function<bool(const GridIndex&)> free_is_filled_fn\n        = [&] (const GridIndex& virtual_border_grid_index)\n    {\n      // Is there a virtual border on our axis?\n      if (x_axis_size_offset > 0)\n      {\n        // Are we a virtual border cell?\n        if ((virtual_border_grid_index.X() == 0)\n            || (virtual_border_grid_index.X() == (num_x_cells - 1)))\n        {\n          return true;\n        }\n      }\n      // Is there a virtual border on our axis?\n      if (y_axis_size_offset > 0)\n      {\n        // Are we a virtual border cell?\n        if ((virtual_border_grid_index.Y() == 0)\n            || (virtual_border_grid_index.Y() == (num_y_cells - 1)))\n        {\n          return true;\n        }\n      }\n      // Is there a virtual border on our axis?\n      if (z_axis_size_offset > 0)\n      {\n        // Are we a virtual border cell?\n        if ((virtual_border_grid_index.Z() == 0)\n            || (virtual_border_grid_index.Z() == (num_z_cells - 1)))\n        {\n          return true;\n        }\n      }\n      const GridIndex real_grid_index(\n            virtual_border_grid_index.X() - x_axis_query_offset,\n            virtual_border_grid_index.Y() - y_axis_query_offset,\n            virtual_border_grid_index.Z() - z_axis_query_offset);\n      return is_filled_fn(real_grid_index);\n    };\n    // For the filled space SDF, we lie and say the virtual border is empty\n    const std::function<bool(const GridIndex&)> filled_is_filled_fn\n        = [&] (const GridIndex& virtual_border_grid_index)\n    {\n      // Is there a virtual border on our axis?\n      if (x_axis_size_offset > 0)\n      {\n        // Are we a virtual border cell?\n        if ((virtual_border_grid_index.X() == 0)\n            || (virtual_border_grid_index.X() == (num_x_cells - 1)))\n        {\n          return false;\n        }\n      }\n      // Is there a virtual border on our axis?\n      if (y_axis_size_offset > 0)\n      {\n        // Are we a virtual border cell?\n        if ((virtual_border_grid_index.Y() == 0)\n            || (virtual_border_grid_index.Y() == (num_y_cells - 1)))\n        {\n          return false;\n        }\n      }\n      // Is there a virtual border on our axis?\n      if (z_axis_size_offset > 0)\n      {\n        // Are we a virtual border cell?\n        if ((virtual_border_grid_index.Z() == 0)\n            || (virtual_border_grid_index.Z() == (num_z_cells - 1)))\n        {\n          return false;\n        }\n      }\n      const GridIndex real_grid_index(\n            virtual_border_grid_index.X() - x_axis_query_offset,\n            virtual_border_grid_index.Y() - y_axis_query_offset,\n            virtual_border_grid_index.Z() - z_axis_query_offset);\n      return is_filled_fn(real_grid_index);\n    };\n    // Make both SDFs\n    const common_robotics_utilities::voxel_grid::GridSizes enlarged_sizes(\n        grid.GetCellSizes().x(), num_x_cells, num_y_cells, num_z_cells);\n    auto free_sdf_result\n        = ExtractSignedDistanceField<T>(\n            grid.GetOriginTransform(), enlarged_sizes, free_is_filled_fn,\n            oob_value, frame, use_parallel);\n    auto filled_sdf_result\n        = ExtractSignedDistanceField<T>(\n            grid.GetOriginTransform(), enlarged_sizes, filled_is_filled_fn,\n            oob_value, frame, use_parallel);\n    // Combine to make a single SDF\n    SignedDistanceField<SDFBackingStore> combined_sdf(\n          grid.GetOriginTransform(), frame, grid.GetGridSizes(), oob_value);\n    for (int64_t x_idx = 0; x_idx < combined_sdf.GetNumXCells(); x_idx++)\n    {\n      for (int64_t y_idx = 0; y_idx < combined_sdf.GetNumYCells(); y_idx++)\n      {\n        for (int64_t z_idx = 0; z_idx < combined_sdf.GetNumZCells(); z_idx++)\n        {\n          const int64_t query_x_idx = x_idx + x_axis_query_offset;\n          const int64_t query_y_idx = y_idx + y_axis_query_offset;\n          const int64_t query_z_idx = z_idx + z_axis_query_offset;\n          const float free_sdf_value\n              = free_sdf_result.DistanceField().GetImmutable(\n                  query_x_idx, query_y_idx, query_z_idx).Value();\n          const float filled_sdf_value\n              = filled_sdf_result.DistanceField().GetImmutable(\n                  query_x_idx, query_y_idx, query_z_idx).Value();\n          if (free_sdf_value >= 0.0)\n          {\n            combined_sdf.SetValue(x_idx, y_idx, z_idx, free_sdf_value);\n          }\n          else if (filled_sdf_value <= -0.0)\n          {\n            combined_sdf.SetValue(x_idx, y_idx, z_idx, filled_sdf_value);\n          }\n          else\n          {\n            combined_sdf.SetValue(x_idx, y_idx, z_idx, 0.0f);\n          }\n        }\n      }\n    }\n    // Get the combined max/min values\n    return MakeSignedDistanceFieldResult<SDFBackingStore>(\n        combined_sdf, free_sdf_result.Maximum(), filled_sdf_result.Minimum());\n  }\n}\n\ntemplate<typename T, typename BackingStore=std::vector<T>,\n         typename SDFBackingStore=std::vector<float>>\ninline SignedDistanceFieldResult<SDFBackingStore> ExtractSignedDistanceField(\n    const common_robotics_utilities::voxel_grid\n        ::VoxelGridBase<T, BackingStore>& grid,\n    const std::function<bool(const T&)>& is_filled_fn,\n    const float oob_value, const std::string& frame,\n    const bool use_parallel)\n{\n  if (!grid.HasUniformCellSize())\n  {\n    throw std::invalid_argument(\"Grid must have uniform resolution\");\n  }\n  const std::function<bool(const GridIndex&)> real_is_filled_fn =\n      [&] (const GridIndex& index)\n  {\n    const T& stored = grid.GetImmutable(index).Value();\n    // If it matches an object to use OR there are no objects supplied\n    if (is_filled_fn(stored))\n    {\n      // Mark as filled\n      return true;\n    }\n    else\n    {\n      // Mark as free space\n      return false;\n    }\n  };\n  return ExtractSignedDistanceField<T, BackingStore, SDFBackingStore>(\n        grid, real_is_filled_fn, oob_value, frame, use_parallel, false);\n}\n}  // namespace signed_distance_field_generation\n}  // namespace voxelized_geometry_tools\n", "meta": {"hexsha": "2be63fa79f24416babfa21cc9cfb33f60959d235", "size": 30494, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/voxelized_geometry_tools/signed_distance_field_generation.hpp", "max_stars_repo_name": "calderpg/voxelized_geometry_tools", "max_stars_repo_head_hexsha": "cc36bfd426e984e451e5b844f89be8596b905774", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 29.0, "max_stars_repo_stars_event_min_datetime": "2018-10-15T19:05:07.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T05:29:13.000Z", "max_issues_repo_path": "include/voxelized_geometry_tools/signed_distance_field_generation.hpp", "max_issues_repo_name": "calderpg/voxelized_geometry_tools", "max_issues_repo_head_hexsha": "cc36bfd426e984e451e5b844f89be8596b905774", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2018-11-29T23:49:57.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-20T13:16:19.000Z", "max_forks_repo_path": "include/voxelized_geometry_tools/signed_distance_field_generation.hpp", "max_forks_repo_name": "calderpg/voxelized_geometry_tools", "max_forks_repo_head_hexsha": "cc36bfd426e984e451e5b844f89be8596b905774", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 13.0, "max_forks_repo_forks_event_min_datetime": "2018-10-17T23:58:35.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-30T06:26:46.000Z", "avg_line_length": 37.4619164619, "max_line_length": 80, "alphanum_fraction": 0.6478651538, "num_tokens": 7291, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6619228758499942, "lm_q2_score": 0.49218813572079556, "lm_q1q2_score": 0.32579058625555624}}
{"text": "//=======================================================================\n// Copyright (c) 2013 Piotr Wygocki\n//               2014 Piotr Godlewski\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_network_oracle.hpp\n * @brief\n * @author Piotr Wygocki, Piotr Godlewski\n * @version 1.0\n * @date 2013-06-24\n */\n#ifndef PAAL_STEINER_NETWORK_ORACLE_HPP\n#define PAAL_STEINER_NETWORK_ORACLE_HPP\n\n#include \"paal/iterative_rounding/min_cut.hpp\"\n\n#include <boost/range/as_array.hpp>\n\nnamespace paal {\nnamespace ir {\n\n/**\n * @class steiner_network_violation_checker\n * @brief Violations checker for the separation oracle\n *      in the steiner network problem.\n */\nclass steiner_network_violation_checker {\n    using AuxVertex = min_cut_finder::Vertex;\n    using Violation = double;\n\n  public:\n    using Candidate = std::pair<AuxVertex, AuxVertex>;\n\n    /**\n     * Checks if any solution to the problem exists.\n     */\n    template <typename Problem>\n    bool check_if_solution_exists(Problem &problem) {\n        auto const &g = problem.get_graph();\n        auto const &index = problem.get_index();\n        m_min_cut.init(num_vertices(g));\n\n        for (auto e : boost::as_array(edges(g))) {\n            auto u = get(index, source(e, g));\n            auto v = get(index, target(e, g));\n            m_min_cut.add_edge_to_graph(u, v, 1, 1);\n        }\n\n        for (auto res : problem.get_restrictions_vec()) {\n            if (check_violation(res, problem)) {\n                return false;\n            }\n        }\n\n        return true;\n    }\n\n    /**\n     * Returns an iterator range of violated constraint candidates.\n     */\n    template <typename Problem, typename LP>\n    auto get_violation_candidates(const Problem &problem, const LP &lp)\n        ->decltype(problem.get_restrictions_vec()) {\n\n        fill_auxiliary_digraph(problem, lp);\n        return problem.get_restrictions_vec();\n    }\n\n    /**\n     * Checks if the given constraint candidate is violated an if it is,\n     * returns the violation value and violated constraint ID.\n     */\n    template <typename Problem>\n    Violation check_violation(Candidate candidate, const Problem &problem) {\n        double violation =\n            find_violation(candidate.first, candidate.second, problem);\n        if (problem.get_compare().g(violation, 0)) {\n            return violation;\n        } else {\n            return Violation{};\n        }\n    }\n\n    /**\n     * Adds a violated constraint to the LP.\n     */\n    template <typename Problem, typename LP>\n    void add_violated_constraint(Candidate violation, const Problem &problem,\n                                 LP &lp) {\n        if (violation != m_min_cut.get_last_cut()) {\n            find_violation(violation.first, violation.second, problem);\n        }\n\n        auto const &g = problem.get_graph();\n        auto const &index = problem.get_index();\n        auto restriction =\n            problem.get_max_restriction(violation.first, violation.second);\n\n        for (auto const &e : problem.get_edges_in_solution()) {\n            if (is_edge_in_violating_cut(e, g, index)) {\n                --restriction;\n            }\n        }\n\n        lp::linear_expression expr;\n        for (auto const &e : problem.get_edge_map()) {\n            if (is_edge_in_violating_cut(e.second, g, index)) {\n                expr += e.first;\n            }\n        }\n\n        lp.add_row(std::move(expr) >= restriction);\n    }\n\n  private:\n\n    /**\n     * Checks if a given edge belongs to the cut given by the current violating\n     * set.\n     */\n    template <typename Edge, typename Graph, typename Index>\n    bool is_edge_in_violating_cut(Edge edge, const Graph &g,\n                                  const Index &index) {\n        auto u = get(index, source(edge, g));\n        auto v = get(index, target(edge, g));\n        return m_min_cut.is_in_source_set(u) != m_min_cut.is_in_source_set(v);\n    }\n\n    /**\n     * Creates the auxiliary directed graph used for feasibility testing.\n     */\n    template <typename Problem, typename LP>\n    void fill_auxiliary_digraph(Problem &problem, const LP &lp) {\n        auto const &g = problem.get_graph();\n        auto const &index = problem.get_index();\n        m_min_cut.init(num_vertices(g));\n\n        for (auto const &e : problem.get_edge_map()) {\n            lp::col_id col_idx = e.first;\n            double col_val = lp.get_col_value(col_idx);\n\n            if (problem.get_compare().g(col_val, 0)) {\n                auto u = get(index, source(e.second, g));\n                auto v = get(index, target(e.second, g));\n                m_min_cut.add_edge_to_graph(u, v, col_val, col_val);\n            }\n        }\n\n        for (auto const &e : problem.get_edges_in_solution()) {\n            auto u = get(index, source(e, g));\n            auto v = get(index, target(e, g));\n            m_min_cut.add_edge_to_graph(u, v, 1, 1);\n        }\n    }\n\n    /**\n     * Finds the most violated set of vertices containing \\c src and not\n     * containing \\c trg and returns its violation value.\n     * @param src vertex to be contained in the violating set\n     * @param trg vertex not to be contained in the violating set\n     * @param problem problem object\n     * @return violation of the found set\n     */\n    template <typename Problem>\n    double find_violation(AuxVertex src, AuxVertex trg,\n                          const Problem &problem) {\n        double min_cut_weight = m_min_cut.find_min_cut(src, trg);\n        double restriction = problem.get_max_restriction(src, trg);\n        return restriction - min_cut_weight;\n    }\n\n    min_cut_finder m_min_cut;\n};\n\n} //! ir\n} //! paal\n#endif // PAAL_STEINER_NETWORK_ORACLE_HPP\n", "meta": {"hexsha": "d096bf79581eda8ccbd861756f1a18428bfe2c56", "size": 5843, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/paal/iterative_rounding/steiner_network/steiner_network_oracle.hpp", "max_stars_repo_name": "Kommeren/AA", "max_stars_repo_head_hexsha": "e537b58d50e93d4a72709821b9ea413008970c6b", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/paal/iterative_rounding/steiner_network/steiner_network_oracle.hpp", "max_issues_repo_name": "Kommeren/AA", "max_issues_repo_head_hexsha": "e537b58d50e93d4a72709821b9ea413008970c6b", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/paal/iterative_rounding/steiner_network/steiner_network_oracle.hpp", "max_forks_repo_name": "Kommeren/AA", "max_forks_repo_head_hexsha": "e537b58d50e93d4a72709821b9ea413008970c6b", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-02-24T06:23:56.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-24T06:23:56.000Z", "avg_line_length": 32.1043956044, "max_line_length": 79, "alphanum_fraction": 0.5966113298, "num_tokens": 1331, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6619228758499942, "lm_q2_score": 0.49218813572079556, "lm_q1q2_score": 0.32579058625555624}}
{"text": "/* ============================================================================\n * Copyright (c) 2009-2019 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 Air Force Prime Contract FA8650-15-D-5231\n *    United States Prime Contract Navy N00173-07-C-2068\n *\n * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */\n\n#include \"RotateSampleRefFrame.h\"\n\n#include <cmath>\n\n#ifdef SIMPL_USE_PARALLEL_ALGORITHMS\n#include <tbb/blocked_range3d.h>\n#include <tbb/parallel_for.h>\n#include <tbb/partitioner.h>\n#endif\n\n#include <QtCore/QTextStream>\n\n#include <Eigen/Dense>\n\n#include \"SIMPLib/SIMPLibVersion.h\"\n#include \"SIMPLib/Common/Constants.h\"\n#include \"SIMPLib/DataContainers/DataContainer.h\"\n#include \"SIMPLib/DataContainers/DataContainerArray.h\"\n#include \"SIMPLib/FilterParameters/AbstractFilterParametersReader.h\"\n#include \"SIMPLib/FilterParameters/AttributeMatrixSelectionFilterParameter.h\"\n#include \"SIMPLib/FilterParameters/DynamicTableFilterParameter.h\"\n#include \"SIMPLib/FilterParameters/FloatFilterParameter.h\"\n#include \"SIMPLib/FilterParameters/FloatVec3FilterParameter.h\"\n#include \"SIMPLib/FilterParameters/LinkedChoicesFilterParameter.h\"\n#include \"SIMPLib/FilterParameters/SeparatorFilterParameter.h\"\n#include \"SIMPLib/Geometry/ImageGeom.h\"\n#include \"SIMPLib/Math/MatrixMath.h\"\n\nnamespace\n{\nstruct RotateArgs\n{\n  int64_t xp = 0;\n  int64_t yp = 0;\n  int64_t zp = 0;\n  float xRes = 0.0f;\n  float yRes = 0.0f;\n  float zRes = 0.0f;\n  int64_t xpNew = 0;\n  int64_t ypNew = 0;\n  int64_t zpNew = 0;\n  float xResNew = 0.0f;\n  float yResNew = 0.0f;\n  float zResNew = 0.0f;\n  float xMinNew = 0.0f;\n  float yMinNew = 0.0f;\n  float zMinNew = 0.0f;\n};\n\nusing Matrix3fR = Eigen::Matrix<float, 3, 3, Eigen::RowMajor>;\n\nconstexpr float k_Threshold = 0.0001f;\n\nconst Eigen::Vector3f k_XAxis = Eigen::Vector3f::UnitX();\nconst Eigen::Vector3f k_YAxis = Eigen::Vector3f::UnitY();\nconst Eigen::Vector3f k_ZAxis = Eigen::Vector3f::UnitZ();\n\n// Requires table to be 3 x 3\nMatrix3fR tableToMatrix(const std::vector<std::vector<double>>& table)\n{\n  Matrix3fR matrix;\n\n  for(size_t i = 0; i < table.size(); i++)\n  {\n    const auto& row = table[i];\n    for(size_t j = 0; j < row.size(); j++)\n    {\n      matrix(i, j) = row[j];\n    }\n  }\n\n  return matrix;\n}\n\nvoid determineMinMax(const Matrix3fR& rotationMatrix, const FloatVec3Type& spacing, size_t col, size_t row, size_t plane, float& xMin, float& xMax, float& yMin, float& yMax, float& zMin, float& zMax)\n{\n  Eigen::Vector3f coords(static_cast<float>(col) * spacing[0], static_cast<float>(row) * spacing[1], static_cast<float>(plane) * spacing[2]);\n\n  Eigen::Vector3f newCoords = rotationMatrix * coords;\n\n  xMin = std::min(newCoords[0], xMin);\n  xMax = std::max(newCoords[0], xMax);\n\n  yMin = std::min(newCoords[1], yMin);\n  yMax = std::max(newCoords[1], yMax);\n\n  zMin = std::min(newCoords[2], zMin);\n  zMax = std::max(newCoords[2], zMax);\n}\n\nfloat cosBetweenVectors(const Eigen::Vector3f& a, const Eigen::Vector3f& b)\n{\n  float normA = a.norm();\n  float normB = b.norm();\n\n  if(normA == 0.0f || normB == 0.0f)\n  {\n    return 1.0f;\n  }\n\n  return a.dot(b) / (normA * normB);\n}\n\nfloat determineSpacing(const FloatVec3Type& spacing, const Eigen::Vector3f& axisNew)\n{\n  float xAngle = std::abs(cosBetweenVectors(k_XAxis, axisNew));\n  float yAngle = std::abs(cosBetweenVectors(k_YAxis, axisNew));\n  float zAngle = std::abs(cosBetweenVectors(k_ZAxis, axisNew));\n\n  std::array<float, 3> axes = {xAngle, yAngle, zAngle};\n\n  auto iter = std::max_element(axes.cbegin(), axes.cend());\n\n  size_t index = std::distance(axes.cbegin(), iter);\n\n  return spacing[index];\n}\n\nRotateArgs createRotateParams(const ImageGeom& imageGeom, const Matrix3fR& rotationMatrix)\n{\n  const SizeVec3Type origDims = imageGeom.getDimensions();\n  const FloatVec3Type spacing = imageGeom.getSpacing();\n  // const FloatVec3Type origin = imageGeom.getOrigin();\n\n  float xMin = std::numeric_limits<float>::max();\n  float xMax = std::numeric_limits<float>::min();\n  float yMin = std::numeric_limits<float>::max();\n  float yMax = std::numeric_limits<float>::min();\n  float zMin = std::numeric_limits<float>::max();\n  float zMax = std::numeric_limits<float>::min();\n\n  const std::vector<std::vector<size_t>> coords{{0, 0, 0},\n                                                {origDims[0] - 1, 0, 0},\n                                                {0, origDims[1] - 1, 0},\n                                                {origDims[0] - 1, origDims[1] - 1, 0},\n                                                {0, 0, origDims[2] - 1},\n                                                {origDims[0] - 1, 0, origDims[2] - 1},\n                                                {0, origDims[1] - 1, origDims[2] - 1},\n                                                {origDims[0] - 1, origDims[1] - 1, origDims[2] - 1}};\n\n  for(const auto& item : coords)\n  {\n    determineMinMax(rotationMatrix, spacing, item[0], item[1], item[2], xMin, xMax, yMin, yMax, zMin, zMax);\n  }\n\n  Eigen::Vector3f xAxisNew = rotationMatrix * k_XAxis;\n  Eigen::Vector3f yAxisNew = rotationMatrix * k_YAxis;\n  Eigen::Vector3f zAxisNew = rotationMatrix * k_ZAxis;\n\n  float xResNew = determineSpacing(spacing, xAxisNew);\n  float yResNew = determineSpacing(spacing, yAxisNew);\n  float zResNew = determineSpacing(spacing, zAxisNew);\n\n  MeshIndexType xpNew = static_cast<int64_t>(std::nearbyint((xMax - xMin) / xResNew) + 1);\n  MeshIndexType ypNew = static_cast<int64_t>(std::nearbyint((yMax - yMin) / yResNew) + 1);\n  MeshIndexType zpNew = static_cast<int64_t>(std::nearbyint((zMax - zMin) / zResNew) + 1);\n\n  RotateArgs params;\n\n  params.xp = origDims[0];\n  params.xRes = spacing[0];\n  params.yp = origDims[1];\n  params.yRes = spacing[1];\n  params.zp = origDims[2];\n  params.zRes = spacing[2];\n\n  params.xpNew = xpNew;\n  params.xResNew = xResNew;\n  params.xMinNew = xMin;\n  params.ypNew = ypNew;\n  params.yResNew = yResNew;\n  params.yMinNew = yMin;\n  params.zpNew = zpNew;\n  params.zResNew = zResNew;\n  params.zMinNew = zMin;\n\n  return params;\n}\n\nvoid updateGeometry(ImageGeom& imageGeom, const RotateArgs& params)\n{\n  FloatVec3Type origin = imageGeom.getOrigin();\n\n  imageGeom.setSpacing(params.xResNew, params.yResNew, params.zResNew);\n  imageGeom.setDimensions(params.xpNew, params.ypNew, params.zpNew);\n  origin[0] += params.xMinNew;\n  origin[1] += params.yMinNew;\n  origin[2] += params.zMinNew;\n  imageGeom.setOrigin(origin);\n}\n\n/**\n * @brief The RotateSampleRefFrameImpl class implements a threaded algorithm to do the\n * actual computation of the rotation by applying the rotation to each Euler angle\n */\nclass SampleRefFrameRotator\n{\n  DataArray<int64_t>::Pointer m_NewIndicesPtr;\n  float m_RotMatrixInv[3][3] = {{0.0f, 0.0f, 0.0f}, {0.0f, 0.0f, 0.0f}, {0.0f, 0.0f, 0.0f}};\n  bool m_SliceBySlice = false;\n  RotateArgs m_Params;\n\npublic:\n  SampleRefFrameRotator(DataArray<int64_t>::Pointer newindices, const RotateArgs& args, const Matrix3fR& rotationMatrix, bool sliceBySlice)\n  : m_NewIndicesPtr(newindices)\n  , m_SliceBySlice(sliceBySlice)\n  , m_Params(args)\n  {\n    // We have to inline the 3x3 Maxtrix transpose here because of the \"const\" nature of the 'convert' function\n    Matrix3fR transpose = rotationMatrix.transpose();\n    // Need to use row based Eigen matrix so that the values get mapped to the right place in the raw array\n    // Raw array is faster than Eigen\n    Eigen::Map<Matrix3fR>(&m_RotMatrixInv[0][0], transpose.rows(), transpose.cols()) = transpose;\n  }\n\n  ~SampleRefFrameRotator() = default;\n\n  void convert(int64_t zStart, int64_t zEnd, int64_t yStart, int64_t yEnd, int64_t xStart, int64_t xEnd) const\n  {\n    int64_t* newindicies = m_NewIndicesPtr->getPointer(0);\n\n    for(int64_t k = zStart; k < zEnd; k++)\n    {\n      int64_t ktot = (m_Params.xpNew * m_Params.ypNew) * k;\n      for(int64_t j = yStart; j < yEnd; j++)\n      {\n        int64_t jtot = (m_Params.xpNew) * j;\n        for(int64_t i = xStart; i < xEnd; i++)\n        {\n          int64_t index = ktot + jtot + i;\n          newindicies[index] = -1;\n\n          float coords[3] = {0.0f, 0.0f, 0.0f};\n          float coordsNew[3] = {0.0f, 0.0f, 0.0f};\n\n          coords[0] = (static_cast<float>(i) * m_Params.xResNew) + m_Params.xMinNew;\n          coords[1] = (static_cast<float>(j) * m_Params.yResNew) + m_Params.yMinNew;\n          coords[2] = (static_cast<float>(k) * m_Params.zResNew) + m_Params.zMinNew;\n\n          MatrixMath::Multiply3x3with3x1(m_RotMatrixInv, coords, coordsNew);\n\n          int64_t colOld = static_cast<int64_t>(std::nearbyint(coordsNew[0] / m_Params.xRes));\n          int64_t rowOld = static_cast<int64_t>(std::nearbyint(coordsNew[1] / m_Params.yRes));\n          int64_t planeOld = static_cast<int64_t>(std::nearbyint(coordsNew[2] / m_Params.zRes));\n\n          if(m_SliceBySlice)\n          {\n            planeOld = k;\n          }\n\n          if(colOld >= 0 && colOld < m_Params.xp && rowOld >= 0 && rowOld < m_Params.yp && planeOld >= 0 && planeOld < m_Params.zp)\n          {\n            newindicies[index] = (m_Params.xp * m_Params.yp * planeOld) + (m_Params.xp * rowOld) + colOld;\n          }\n        }\n      }\n    }\n  }\n\n#ifdef SIMPL_USE_PARALLEL_ALGORITHMS\n  void operator()(const tbb::blocked_range3d<int64_t, int64_t, int64_t>& r) const\n  {\n    convert(r.pages().begin(), r.pages().end(), r.rows().begin(), r.rows().end(), r.cols().begin(), r.cols().end());\n  }\n#endif\n};\n\n} // namespace\n\nstruct RotateSampleRefFrame::Impl\n{\n  Matrix3fR m_RotationMatrix = Matrix3fR::Zero();\n  RotateArgs m_Params;\n\n  void reset()\n  {\n    m_RotationMatrix.setZero();\n\n    m_Params = RotateArgs();\n  }\n};\n\n// -----------------------------------------------------------------------------\n//\n// -----------------------------------------------------------------------------\nRotateSampleRefFrame::RotateSampleRefFrame()\n: p_Impl(std::make_unique<Impl>())\n{\n  std::vector<std::vector<double>> defaultTable{{1.0, 0.0, 0.0}, {0.0, 1.0, 0.0}, {0.0, 0.0, 1.0}};\n\n  m_RotationTable.setTableData(defaultTable);\n  m_RotationTable.setDynamicRows(false);\n  m_RotationTable.setDynamicCols(false);\n  m_RotationTable.setDefaultColCount(3);\n  m_RotationTable.setDefaultRowCount(3);\n  m_RotationTable.setMinCols(3);\n  m_RotationTable.setMinRows(3);\n}\n\n// -----------------------------------------------------------------------------\n//\n// -----------------------------------------------------------------------------\nRotateSampleRefFrame::~RotateSampleRefFrame() = default;\n\n// -----------------------------------------------------------------------------\n//\n// -----------------------------------------------------------------------------\nvoid RotateSampleRefFrame::setupFilterParameters()\n{\n  FilterParameterVectorType parameters;\n\n  {\n    LinkedChoicesFilterParameter::Pointer parameter = LinkedChoicesFilterParameter::New();\n    parameter->setHumanLabel(\"Rotation Representation\");\n    parameter->setPropertyName(\"RotationRepresentationChoice\");\n    parameter->setSetterCallback(SIMPL_BIND_SETTER(RotateSampleRefFrame, this, RotationRepresentationChoice));\n    parameter->setGetterCallback(SIMPL_BIND_GETTER(RotateSampleRefFrame, this, RotationRepresentationChoice));\n    std::vector<QString> choices{\"Axis Angle\", \"Rotation Matrix\"};\n    parameter->setChoices(choices);\n    std::vector<QString> linkedProps{\"RotationAngle\", \"RotationAxis\", \"RotationTable\"};\n    parameter->setLinkedProperties(linkedProps);\n    parameter->setEditable(false);\n    parameter->setCategory(FilterParameter::Category::Parameter);\n    parameters.push_back(parameter);\n  }\n\n  // Axis Angle Parameters\n\n  parameters.push_back(SIMPL_NEW_FLOAT_FP(\"Rotation Angle (Degrees)\", RotationAngle, FilterParameter::Category::Parameter, RotateSampleRefFrame, 0));\n  parameters.push_back(SIMPL_NEW_FLOAT_VEC3_FP(\"Rotation Axis (ijk)\", RotationAxis, FilterParameter::Category::Parameter, RotateSampleRefFrame, 0));\n\n  // Rotation Matrix Parameters\n\n  parameters.push_back(SIMPL_NEW_DYN_TABLE_FP(\"Rotation Matrix\", RotationTable, FilterParameter::Category::Parameter, RotateSampleRefFrame, 1));\n\n  // Required Arrays\n\n  parameters.push_back(SeparatorFilterParameter::Create(\"Cell Data\", FilterParameter::Category::RequiredArray));\n  {\n    AttributeMatrixSelectionFilterParameter::RequirementType req = AttributeMatrixSelectionFilterParameter::CreateRequirement(AttributeMatrix::Type::Cell, IGeometry::Type::Image);\n    parameters.push_back(SIMPL_NEW_AM_SELECTION_FP(\"Cell Attribute Matrix\", CellAttributeMatrixPath, FilterParameter::Category::RequiredArray, RotateSampleRefFrame, req));\n  }\n\n  setFilterParameters(parameters);\n}\n\n// -----------------------------------------------------------------------------\n//\n// -----------------------------------------------------------------------------\nvoid RotateSampleRefFrame::readFilterParameters(AbstractFilterParametersReader* reader, int index)\n{\n  reader->openFilterGroup(this, index);\n  setCellAttributeMatrixPath(reader->readDataArrayPath(\"CellAttributeMatrixPath\", getCellAttributeMatrixPath()));\n  setRotationAxis(reader->readFloatVec3(\"RotationAxis\", getRotationAxis()));\n  setRotationAngle(reader->readValue(\"RotationAngle\", getRotationAngle()));\n  reader->closeFilterGroup();\n}\n\n// -----------------------------------------------------------------------------\n//\n// -----------------------------------------------------------------------------\nvoid RotateSampleRefFrame::initialize()\n{\n}\n\n// -----------------------------------------------------------------------------\n//\n// -----------------------------------------------------------------------------\nvoid RotateSampleRefFrame::dataCheck()\n{\n  clearErrorCode();\n  clearWarningCode();\n\n  p_Impl->reset();\n\n  if(getErrorCode() < 0)\n  {\n    return;\n  }\n\n  if(!isRotationRepresentationValid(m_RotationRepresentationChoice))\n  {\n    QString ss = QObject::tr(\"Invalid rotation representation\");\n    setErrorCondition(-45001, ss);\n    return;\n  }\n\n  getDataContainerArray()->getPrereqGeometryFromDataContainer<ImageGeom>(this, getCellAttributeMatrixPath().getDataContainerName());\n  getDataContainerArray()->getPrereqAttributeMatrixFromPath(this, getCellAttributeMatrixPath(), -301);\n  if(getErrorCode() < 0)\n  {\n    return;\n  }\n\n  DataContainer::Pointer m = getDataContainerArray()->getDataContainer(getCellAttributeMatrixPath().getDataContainerName());\n\n  if(m == nullptr)\n  {\n    QString ss = QObject::tr(\"Failed to get DataContainer '%1'\").arg(getCellAttributeMatrixPath().getDataContainerName());\n    setErrorCondition(-45002, ss);\n    return;\n  }\n\n  ImageGeom::Pointer imageGeom = m->getGeometryAs<ImageGeom>();\n\n  if(imageGeom == nullptr)\n  {\n    QString ss = QObject::tr(\"Failed to get Image Geometry from '%1'\").arg(getCellAttributeMatrixPath().getDataContainerName());\n    setErrorCondition(-45002, ss);\n    return;\n  }\n\n  const RotationRepresentation representation = getRotationRepresentation();\n\n  switch(representation)\n  {\n  case RotationRepresentation::AxisAngle: {\n    const Eigen::Vector3f rotationAxis(m_RotationAxis.data());\n    float norm = rotationAxis.norm();\n    if(!SIMPLibMath::closeEnough(rotationAxis.norm(), 1.0f, k_Threshold))\n    {\n      QString ss = QObject::tr(\"Axis angle is not normalized (norm is %1). Filter will automatically normalize the value.\").arg(norm);\n      setWarningCondition(-45003, ss);\n    }\n\n    float rotationAngleRadians = m_RotationAngle * SIMPLib::Constants::k_DegToRadD;\n\n    Eigen::AngleAxisf axisAngle(rotationAngleRadians, rotationAxis.normalized());\n\n    p_Impl->m_RotationMatrix = axisAngle.toRotationMatrix();\n  }\n  break;\n  case RotationRepresentation::RotationMatrix: {\n    auto rotationMatrixTable = m_RotationTable.getTableData();\n\n    if(rotationMatrixTable.size() != 3)\n    {\n      QString ss = QObject::tr(\"Rotation Matrix must be 3 x 3\");\n      setErrorCondition(-45004, ss);\n      return;\n    }\n\n    for(const auto& row : rotationMatrixTable)\n    {\n      if(row.size() != 3)\n      {\n        QString ss = QObject::tr(\"Rotation Matrix must be 3 x 3\");\n        setErrorCondition(-45005, ss);\n        return;\n      }\n    }\n\n    Matrix3fR rotationMatrix = tableToMatrix(rotationMatrixTable);\n\n    float determinant = rotationMatrix.determinant();\n\n    if(!SIMPLibMath::closeEnough(determinant, 1.0f, k_Threshold))\n    {\n      QString ss = QObject::tr(\"Rotation Matrix must have a determinant of 1 (is %1)\").arg(determinant);\n      setErrorCondition(-45006, ss);\n      return;\n    }\n\n    Matrix3fR transpose = rotationMatrix.transpose();\n    Matrix3fR inverse = rotationMatrix.inverse();\n\n    if(!transpose.isApprox(inverse, k_Threshold))\n    {\n      QString ss = QObject::tr(\"Rotation Matrix's inverse and transpose must be equal\");\n      setErrorCondition(-45007, ss);\n      return;\n    }\n\n    p_Impl->m_RotationMatrix = rotationMatrix;\n  }\n  break;\n  default: {\n    QString ss = QObject::tr(\"Invalid rotation representation\");\n    setErrorCondition(-45008, ss);\n    return;\n  }\n  }\n\n  p_Impl->m_Params = createRotateParams(*imageGeom, p_Impl->m_RotationMatrix);\n\n  updateGeometry(*imageGeom, p_Impl->m_Params);\n\n  // Resize attribute matrix\n\n  std::vector<size_t> tDims(3);\n  tDims[0] = p_Impl->m_Params.xpNew;\n  tDims[1] = p_Impl->m_Params.ypNew;\n  tDims[2] = p_Impl->m_Params.zpNew;\n  QString attrMatName = getCellAttributeMatrixPath().getAttributeMatrixName();\n  m->getAttributeMatrix(attrMatName)->resizeAttributeArrays(tDims);\n}\n\n// -----------------------------------------------------------------------------\n//\n// -----------------------------------------------------------------------------\nvoid RotateSampleRefFrame::execute()\n{\n  dataCheck();\n  if(getErrorCode() < 0)\n  {\n    return;\n  }\n\n  DataContainer::Pointer m = getDataContainerArray()->getDataContainer(getCellAttributeMatrixPath().getDataContainerName());\n\n  if(m == nullptr)\n  {\n    QString ss = QObject::tr(\"Failed to get DataContainer '%1'\").arg(getCellAttributeMatrixPath().getDataContainerName());\n    setErrorCondition(-45101, ss);\n    return;\n  }\n\n  int64_t newNumCellTuples = p_Impl->m_Params.xpNew * p_Impl->m_Params.ypNew * p_Impl->m_Params.zpNew;\n\n  DataArray<int64_t>::Pointer newIndiciesPtr = DataArray<int64_t>::CreateArray(newNumCellTuples, std::string(\"_INTERNAL_USE_ONLY_RotateSampleRef_NewIndicies\"), true);\n  newIndiciesPtr->initializeWithValue(-1);\n  int64_t* newindicies = newIndiciesPtr->getPointer(0);\n\n#ifdef SIMPL_USE_PARALLEL_ALGORITHMS\n  tbb::parallel_for(tbb::blocked_range3d<int64_t, int64_t, int64_t>(0, p_Impl->m_Params.zpNew, 0, p_Impl->m_Params.ypNew, 0, p_Impl->m_Params.xpNew),\n                    SampleRefFrameRotator(newIndiciesPtr, p_Impl->m_Params, p_Impl->m_RotationMatrix, m_SliceBySlice), tbb::auto_partitioner());\n#else\n  {\n    SampleRefFrameRotator serial(newIndiciesPtr, p_Impl->m_Params, p_Impl->m_RotationMatrix, m_SliceBySlice);\n    serial.convert(0, p_Impl->m_Params.zpNew, 0, p_Impl->m_Params.ypNew, 0, p_Impl->m_Params.xpNew);\n  }\n#endif\n\n  // This could technically be parallelized also where each thread takes an array to adjust. Except\n  // that the DataContainer is NOT thread safe or re-entrant so that would actually be a BAD idea.\n\n  QString attrMatName = getCellAttributeMatrixPath().getAttributeMatrixName();\n  QList<QString> voxelArrayNames = m->getAttributeMatrix(attrMatName)->getAttributeArrayNames();\n\n  for(const auto& attrArrayName : voxelArrayNames)\n  {\n    IDataArray::Pointer p = m->getAttributeMatrix(attrMatName)->getAttributeArray(attrArrayName);\n\n    // Make a copy of the 'p' array that has the same name. When placed into\n    // the data container this will over write the current array with\n    // the same name.\n\n    IDataArray::Pointer data = p->createNewArray(newNumCellTuples, p->getComponentDimensions(), p->getName());\n    int64_t newIndicies_I = 0;\n    for(size_t i = 0; i < static_cast<size_t>(newNumCellTuples); i++)\n    {\n      newIndicies_I = newindicies[i];\n      if(newIndicies_I >= 0)\n      {\n        if(!data->copyFromArray(i, p, newIndicies_I, 1))\n        {\n          QString ss = QObject::tr(\"copyFromArray Failed: \");\n          QTextStream out(&ss);\n          out << \"Source Array Name: \" << p->getName() << \" Source Tuple Index: \" << newIndicies_I << \"\\n\";\n          out << \"Dest Array Name: \" << data->getName() << \"  Dest. Tuple Index: \" << i << \"\\n\";\n          setErrorCondition(-45102, ss);\n          return;\n        }\n      }\n      else\n      {\n        int var = 0;\n        data->initializeTuple(i, &var);\n      }\n    }\n    m->getAttributeMatrix(attrMatName)->insertOrAssign(data);\n  }\n}\n\n// -----------------------------------------------------------------------------\n//\n// -----------------------------------------------------------------------------\nAbstractFilter::Pointer RotateSampleRefFrame::newFilterInstance(bool copyFilterParameters) const\n{\n  RotateSampleRefFrame::Pointer filter = RotateSampleRefFrame::New();\n  if(copyFilterParameters)\n  {\n    copyFilterParameterInstanceVariables(filter.get());\n  }\n  return filter;\n}\n\n// -----------------------------------------------------------------------------\n//\n// -----------------------------------------------------------------------------\nQString RotateSampleRefFrame::getCompiledLibraryName() const\n{\n  return Core::CoreBaseName;\n}\n\n// -----------------------------------------------------------------------------\n//\n// -----------------------------------------------------------------------------\nQString RotateSampleRefFrame::getBrandingString() const\n{\n  return \"SIMPLib Core Filter\";\n}\n\n// -----------------------------------------------------------------------------\n//\n// -----------------------------------------------------------------------------\nQString RotateSampleRefFrame::getFilterVersion() const\n{\n  QString version;\n  QTextStream vStream(&version);\n  vStream << SIMPLib::Version::Major() << \".\" << SIMPLib::Version::Minor() << \".\" << SIMPLib::Version::Patch();\n  return version;\n}\n// -----------------------------------------------------------------------------\n//\n// -----------------------------------------------------------------------------\nQString RotateSampleRefFrame::getGroupName() const\n{\n  return SIMPL::FilterGroups::SamplingFilters;\n}\n\n// -----------------------------------------------------------------------------\n//\n// -----------------------------------------------------------------------------\nQUuid RotateSampleRefFrame::getUuid() const\n{\n  return QUuid(\"{e25d9b4c-2b37-578c-b1de-cf7032b5ef19}\");\n}\n\n// -----------------------------------------------------------------------------\n//\n// -----------------------------------------------------------------------------\nQString RotateSampleRefFrame::getSubGroupName() const\n{\n  return SIMPL::FilterSubGroups::RotationTransformationFilters;\n}\n\n// -----------------------------------------------------------------------------\n//\n// -----------------------------------------------------------------------------\nQString RotateSampleRefFrame::getHumanLabel() const\n{\n  return \"Rotate Sample Reference Frame\";\n}\n\n// -----------------------------------------------------------------------------\nRotateSampleRefFrame::Pointer RotateSampleRefFrame::NullPointer()\n{\n  return Pointer(static_cast<Self*>(nullptr));\n}\n\n// -----------------------------------------------------------------------------\nstd::shared_ptr<RotateSampleRefFrame> RotateSampleRefFrame::New()\n{\n  struct make_shared_enabler : public RotateSampleRefFrame\n  {\n  };\n  std::shared_ptr<make_shared_enabler> val = std::make_shared<make_shared_enabler>();\n  val->setupFilterParameters();\n  return val;\n}\n\n// -----------------------------------------------------------------------------\nQString RotateSampleRefFrame::getNameOfClass() const\n{\n  return QString(\"RotateSampleRefFrame\");\n}\n\n// -----------------------------------------------------------------------------\nQString RotateSampleRefFrame::ClassName()\n{\n  return QString(\"RotateSampleRefFrame\");\n}\n\n// -----------------------------------------------------------------------------\nvoid RotateSampleRefFrame::setCellAttributeMatrixPath(const DataArrayPath& value)\n{\n  m_CellAttributeMatrixPath = value;\n}\n\n// -----------------------------------------------------------------------------\nDataArrayPath RotateSampleRefFrame::getCellAttributeMatrixPath() const\n{\n  return m_CellAttributeMatrixPath;\n}\n\n// -----------------------------------------------------------------------------\nvoid RotateSampleRefFrame::setRotationAxis(const FloatVec3Type& value)\n{\n  m_RotationAxis = value;\n}\n\n// -----------------------------------------------------------------------------\nFloatVec3Type RotateSampleRefFrame::getRotationAxis() const\n{\n  return m_RotationAxis;\n}\n\n// -----------------------------------------------------------------------------\nvoid RotateSampleRefFrame::setRotationAngle(float value)\n{\n  m_RotationAngle = value;\n}\n\n// -----------------------------------------------------------------------------\nfloat RotateSampleRefFrame::getRotationAngle() const\n{\n  return m_RotationAngle;\n}\n\n// -----------------------------------------------------------------------------\nvoid RotateSampleRefFrame::setSliceBySlice(bool value)\n{\n  m_SliceBySlice = value;\n}\n\n// -----------------------------------------------------------------------------\nbool RotateSampleRefFrame::getSliceBySlice() const\n{\n  return m_SliceBySlice;\n}\n\n// -----------------------------------------------------------------------------\nvoid RotateSampleRefFrame::setRotationTable(const DynamicTableData& value)\n{\n  m_RotationTable = value;\n}\n\n// -----------------------------------------------------------------------------\nDynamicTableData RotateSampleRefFrame::getRotationTable() const\n{\n  return m_RotationTable;\n}\n\n// -----------------------------------------------------------------------------\nvoid RotateSampleRefFrame::setRotationRepresentationChoice(int value)\n{\n  m_RotationRepresentationChoice = value;\n}\n\n// -----------------------------------------------------------------------------\nint RotateSampleRefFrame::getRotationRepresentationChoice() const\n{\n  return m_RotationRepresentationChoice;\n}\n\n// -----------------------------------------------------------------------------\nRotateSampleRefFrame::RotationRepresentation RotateSampleRefFrame::getRotationRepresentation() const\n{\n  return static_cast<RotationRepresentation>(m_RotationRepresentationChoice);\n}\n\n// -----------------------------------------------------------------------------\nvoid RotateSampleRefFrame::setRotationRepresentation(RotationRepresentation value)\n{\n  m_RotationRepresentationChoice = static_cast<int>(value);\n}\n\n// -----------------------------------------------------------------------------\nbool RotateSampleRefFrame::isRotationRepresentationValid(int value) const\n{\n  return (value >= 0) && (value <= 1);\n}\n", "meta": {"hexsha": "3cbe47c0c5f7c25ba739fd42eefd0c6c3a2faf7f", "size": 28387, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Source/SIMPLib/CoreFilters/RotateSampleRefFrame.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/CoreFilters/RotateSampleRefFrame.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/CoreFilters/RotateSampleRefFrame.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.48375, "max_line_length": 199, "alphanum_fraction": 0.6082713918, "num_tokens": 6587, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7248702642896702, "lm_q2_score": 0.4493926344647596, "lm_q1q2_score": 0.3257513577143014}}
{"text": "#ifndef DFG_PHYSICS_DIDNITUL\r\n#define DFG_PHYSICS_DIDNITUL\r\n\r\n#include \"dfgDefs.hpp\"\r\n#include \"physics/constants.hpp\"\r\n#include \"math/constants.hpp\"\r\n#include \"math/pow.hpp\"\r\n#include \"build/utils.hpp\"\r\n#include <boost/units/quantity.hpp>\r\n#include <boost/units/systems/si/temperature.hpp>\r\n#include <boost/units/systems/si/frequency.hpp>\r\n#include <boost/units/systems/si/energy.hpp>\r\n#include <boost/units/systems/si/temperature.hpp>\r\n#include <boost/units/systems/temperature/celsius.hpp>\r\n#include <boost/units/systems/temperature/fahrenheit.hpp>\r\n\r\nDFG_ROOT_NS_BEGIN { DFG_SUB_NS(physics) {\r\n\r\nclass CelsiusType\r\n{\r\npublic:\r\n\texplicit CelsiusType(double val) :\r\n\t  m_val(val)\r\n\t{}\r\n\r\n\tdouble value() const {return m_val;}\r\n\r\n\tdouble m_val;\r\n};\r\n\r\nconst auto kelvin\t\t= boost::units::si::kelvin;\r\nconst auto celsius\t\t= boost::units::celsius::degrees;\r\nconst auto fahrenheit\t= boost::units::fahrenheit::degrees;\r\n\r\nclass InvalidType {};\r\n\r\ninline double photonEnergy_RawSi(const double& fInHz)\r\n{\r\n\treturn const_hPlanck_rawSiValue * fInHz;\r\n}\r\n\r\ninline double photonEnergyVacuumWavelength_RawSi(const double& waveLengthInM)\r\n{\r\n\treturn photonEnergy_RawSi(const_speedOfLight_rawSiValue / waveLengthInM);\r\n}\r\n\r\ntemplate <class FromQuantity_T, class ToUnit_T> inline InvalidType convertTo(const FromQuantity_T&, const ToUnit_T&)\r\n{\r\n\tDFG_BUILD_GENERATE_FAILURE_IF_INSTANTIATED(FromQuantity_T,\r\n\t\t\t\t\t\t\t\t\t\t\t\tDFG_CURRENT_FUNCTION_NAME \": not implemented. Note that e.g. for temperatures \"\r\n\t\t\t\t\t\t\t\t\t\t\t\t\"either convertToAbsolute or convertToDifference should be used.\");\r\n\treturn InvalidType();\r\n}\r\n\r\ntemplate <class FromQuantity_T, class ToUnit_T> inline InvalidType convertToAbsolute(const FromQuantity_T&, const ToUnit_T&)\r\n{\r\n\tDFG_BUILD_GENERATE_FAILURE_IF_INSTANTIATED(FromQuantity_T, DFG_CURRENT_FUNCTION_NAME \": not implemented.\");\r\n\treturn InvalidType();\r\n}\r\n\r\ntemplate <class FromQuantity_T, class ToUnit_T> inline InvalidType convertToDifference(const FromQuantity_T&, const ToUnit_T&)\r\n{\r\n\tDFG_BUILD_GENERATE_FAILURE_IF_INSTANTIATED(FromQuantity_T, DFG_CURRENT_FUNCTION_NAME \": not implemented.\");\r\n\treturn InvalidType();\r\n}\r\n\r\n// Celsius -> Kelvin\r\nauto inline convertToAbsolute(const decltype(1.0 * celsius)& from, const decltype(kelvin)&) -> decltype(from.value() * kelvin)\r\n{\r\n\treturn (from.value() + 273.15) * kelvin;\r\n}\r\n\r\n// Kelvin -> Celsius\r\nauto inline convertToAbsolute(const decltype(1.0 * kelvin)& from, const decltype(celsius)&) -> decltype(from.value() * celsius)\r\n{\r\n\treturn (from.value() - 273.15) * celsius;\r\n}\r\n\r\nauto inline convertToDifference(const decltype(1.0 * celsius)& from, const decltype(kelvin)&) -> decltype(from.value() * kelvin)\r\n{\r\n\treturn from.value() * kelvin;\r\n}\r\n\r\nauto inline convertToDifference(const decltype(1.0 * kelvin)& from, const decltype(celsius)&) -> decltype(from.value() * celsius)\r\n{\r\n\treturn from.value() * celsius;\r\n}\r\n\r\n// Wikipedia http://en.wikipedia.org/wiki/Planck%27s_law\r\n// TODO: test\r\ninline double planckBlackBodySpectralEnergyDensityByFrequency_RawSi(const double TinK, const double fInHz)\r\n{\r\n\tconst double factor = 8.0 * DFG_SUB_NS_NAME(math)::const_pi * const_hPlanck_rawSiValue / DFG_SUB_NS_NAME(math)::pow3(const_speedOfLight_rawSiValue);\r\n\tconst double beta = 1.0 / (const_k_B_rawSiValue * TinK);\r\n\treturn factor * DFG_SUB_NS_NAME(math)::pow3(fInHz) / (exp(photonEnergy_RawSi(fInHz) * beta) - 1);\r\n}\r\n\r\n// Wikipedia http://en.wikipedia.org/wiki/Planck%27s_law\r\n// TODO: test\r\ninline double planckBlackBodySpectralEnergyDensityByWaveLength_RawSi(const double TinK, const double wavelengthInM)\r\n{\r\n\tconst double factor = 8.0 * DFG_SUB_NS_NAME(math)::const_pi * const_hPlanck_rawSiValue * const_speedOfLight_rawSiValue;\r\n\tconst double beta = 1.0 / (const_k_B_rawSiValue * TinK);\r\n\treturn factor * (1.0 / DFG_SUB_NS_NAME(math)::pow5(wavelengthInM)) * (1.0 / (exp(photonEnergyVacuumWavelength_RawSi(wavelengthInM) * beta) - 1));\r\n}\r\n\r\n}} // module physics\r\n\r\n#endif // include guard\r\n", "meta": {"hexsha": "a4db1908f6dcc065507547a940cfd1ab6348eecb", "size": 3956, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "dfg/physics.hpp", "max_stars_repo_name": "tc3t/dfglib", "max_stars_repo_head_hexsha": "7157973e952234a010da8e9fbd551a912c146368", "max_stars_repo_licenses": ["MIT", "BSL-1.0", "BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2017-08-01T04:42:29.000Z", "max_stars_repo_stars_event_max_datetime": "2017-08-01T04:42:29.000Z", "max_issues_repo_path": "dfg/physics.hpp", "max_issues_repo_name": "tc3t/dfglib", "max_issues_repo_head_hexsha": "7157973e952234a010da8e9fbd551a912c146368", "max_issues_repo_licenses": ["MIT", "BSL-1.0", "BSD-3-Clause"], "max_issues_count": 128.0, "max_issues_repo_issues_event_min_datetime": "2018-04-06T23:01:51.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T20:19:38.000Z", "max_forks_repo_path": "dfg/physics.hpp", "max_forks_repo_name": "tc3t/dfglib", "max_forks_repo_head_hexsha": "7157973e952234a010da8e9fbd551a912c146368", "max_forks_repo_licenses": ["MIT", "BSL-1.0", "BSD-3-Clause"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2018-03-21T01:11:05.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-05T19:20:31.000Z", "avg_line_length": 35.9636363636, "max_line_length": 150, "alphanum_fraction": 0.7492416582, "num_tokens": 1029, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7310585786300049, "lm_q2_score": 0.4455295350395727, "lm_q1q2_score": 0.325708188623717}}
{"text": "/*\n * func_ver.cpp\n *\n *  Created on: 04.07.2012\n *      Author: stephaniebayer\n */\n\n#include \"func_ver.h\"\n#include<vector>\n#include \"Cipher_elg.h\"\n#include \"G_q.h\"\n#include \"Mod_p.h\"\n#include \"Functions.h\"\n#include \"ElGammal.h\"\n#include \"multi_expo.h\"\n#include <fstream>\n\n#include <time.h>\n#include <NTL/ZZ.h>\nNTL_CLIENT\n\n\nextern G_q G;\nextern G_q H;\nextern Pedersen Ped;\nextern ElGammal El;\n\nfunc_ver::func_ver() {\n\t// TODO Auto-generated constructor stub\n\n}\n\nfunc_ver::~func_ver() {\n\t// TODO Auto-generated destructor stub\n}\n\n\nint func_ver::check_Dh(vector<Mod_p>* c_Dh, vector<ZZ>* chal, vector<ZZ>* D_h_bar, ZZ r_Dh_bar){\n\tlong i;\n\tMod_p t_Dh, co_Dh, temp;\n\tlong m = c_Dh->size();\n\n\tt_Dh =c_Dh->at(0);\n\tfor (i=1; i<m;i++){\n\t\tMod_p::expo(temp,c_Dh->at(i),chal->at(i-1));\n\t\tMod_p::mult(t_Dh,t_Dh,temp);\n\t}\n\tco_Dh = Ped.commit(D_h_bar,r_Dh_bar);\n/*\tstring name = \"example.txt\";\n\tofstream ost;\n\tost.open(name.c_str(),ios::app);\n\tost<<\"D_h \"<<t_Dh<<\" \"<<co_Dh<<endl;*/\n\tif (t_Dh == co_Dh){\n\t\treturn 1;\n\t}\n\treturn 0;\n}\n\nint func_ver::check_D(Mod_p c_D0, Mod_p c_z, vector<Mod_p>* c_A, vector<Mod_p>* c_B, vector<ZZ>* chal_1, ZZ chal_2, vector<ZZ>* A_bar, ZZ r_A_bar, long n){\n\tint i;\n\tMod_p t_D, co_D, temp, inv;\n\tlong m = c_A->size()-1;\n\tZZ ord = H.get_ord();\n\tvector<ZZ>* v_1 = new vector<ZZ>(n);\n\n\tt_D = c_D0;\n\tMod_p::inv(inv, c_z);\n\tfor (i=1; i<m;i++){\n\t\tMod_p::expo(temp,c_A->at(i),chal_2);\n\t\tMod_p::mult(temp, temp,c_B->at(i));\n\t\tMod_p::mult(temp,temp,inv);\n\t\tMod_p::expo(temp, temp, chal_1->at(i-1));\n\t\tMod_p::mult(t_D,t_D,temp);\n\t}\n\tfor(i=0; i<n;i++){\n\t\tNegateMod(v_1->at(i),to_ZZ(1),ord);\n\t}\n\ttemp=Ped.commit(v_1,to_ZZ(0));\n\tMod_p::expo(temp, temp, chal_1->at(m-1));\n\tMod_p::mult(t_D,t_D,temp);\n\tco_D = Ped.commit(A_bar, r_A_bar);\n\n\t/*string name = \"example.txt\";\n\tofstream s;\n\tost.open(name.c_str(),ios::app);\n\tost<<\"D \"<<t_D<<\" \"<<co_D<<endl;*/\n\tdelete v_1;\n\tif(t_D == co_D){\n\t\treturn 1;\n\t}\n\treturn 0;\n}\n\n\nint func_ver::check_Ds(vector<Mod_p>* c_Ds, vector<Mod_p>* c_Dh, Mod_p c_Dm, vector<ZZ>* chal_1, vector<ZZ>* chal_2, vector<ZZ>* Ds_bar, ZZ r_Ds_bar){\n\tlong i,l;\n\tlong m= c_Ds->size()-1;\n\tMod_p t_Ds, co_Ds, temp, temp_1;\n\n\tl=m-1;\n\tfor(i=0; i<l; i++){\n\t\tMod_p::expo(c_Ds->at(i),c_Dh->at(i), chal_1->at(i));\n\t}\n\tif(m>1){\n\t\tMod_p::expo(temp, c_Dh->at(1), chal_1->at(0));\n\t\tfor(i=1;i<l; i++){\n\t\t\tMod_p::expo(temp_1,c_Dh->at(i+1), chal_1->at(i));\n\t\t\tMod_p::mult(temp,temp,temp_1);\n\t\t}\n\t\tc_Ds->at(l)=temp;\n\t}\n\telse{\n\t\tc_Ds->at(l)=Mod_p(1,G.get_mod());\n\t}\n\n\tc_Ds->at(m)=c_Dm;\n\tMod_p::expo(t_Ds, c_Ds->at(0),chal_2->at(m-1));\n\tfor(i=1; i<m; i++){\n\t\tMod_p::expo(temp, c_Ds->at(i), chal_2->at(m-1-i));\n\t\tMod_p::mult(t_Ds, t_Ds,temp);\n\t}\n\tMod_p::mult(t_Ds,t_Ds,c_Ds->at(m));\n\tco_Ds = Ped.commit(Ds_bar, r_Ds_bar);\n\n/*\tstring name = \"example.txt\";\n\tofstream ost;\n\tost.open(name.c_str(),ios::app);\n\tost<<\"Ds \"<<t_Ds<<\" \"<<co_Ds<<endl;*/\n\tif(t_Ds == co_Ds){\n\t\treturn 1;\n\t}\n\treturn 0;\n}\n\nint func_ver::check_Dl(vector<Mod_p>* c_Dl, vector<ZZ>* chal_1, vector<ZZ>* A, vector<ZZ>* B, vector<ZZ>*  chal_2, ZZ r_Dl_bar){\n\tlong i;\n\tMod_p t_Dl, co_Dl, temp;\n\tZZ temp_1;\n\tlong l = c_Dl->size();\n\tlong pos = (l-1)/2+1;\n\tZZ mod = G.get_mod();\n\tt_Dl = c_Dl->at(0);\n\tfor(i=1; i<l; i++){\n\t\tMod_p::expo(temp, c_Dl->at(i),chal_1->at(i-1));\n\t\tMod_p::mult(t_Dl, t_Dl, temp);\n\t}\n\ttemp_1=Functions::bilinearMap(A,B,chal_2);\n\tco_Dl =Ped.commit(temp_1,r_Dl_bar);\n\n/*\tstring name = \"example.txt\";\n\tofstream ost;\n\tost.open(name.c_str(),ios::app);\n\tost<<\"Dl \"<<t_Dl<<\" \"<<co_Dl<<endl;*/\n\n\ttemp = Mod_p(1,mod);\n\tif(t_Dl==co_Dl & c_Dl->at(pos) ==temp){\n\t\treturn 1;\n\t}\n\treturn 0;\n}\n\n\nint func_ver::check_d(vector<Mod_p>* c_Dh, Mod_p c_d, vector<ZZ>* chal, vector<ZZ>* d_bar, ZZ r_d_bar){\n\tMod_p t_d, co_d, temp;\n\tlong m = c_Dh->size();\n\n\tMod_p::expo(temp, c_Dh->at(m-1), chal->at(0));\n\tMod_p::mult(t_d, temp, c_d);\n\t\tco_d = Ped.commit(d_bar, r_d_bar);\n\n\t/*\tstring name = \"example.txt\";\n\t\tofstream ost;\n\t\tost.open(name.c_str(),ios::app);\n\t\tost<<\"d \"<<t_d<<\" \"<<co_d<<endl;*/\n\tif(t_d==co_d){\n\t\treturn 1;\n\t}\n\treturn 0;\n}\n\n\nint func_ver::check_Delta(Mod_p c_dh, Mod_p c_Delta, vector<ZZ>* chal, vector<ZZ>* Delta_bar, vector<ZZ>* d_bar, ZZ r_Delta_bar, ZZ chal_1, ZZ chal_2, ZZ chal_3){\n\tlong i,j;\n\tMod_p t_Delta, co_Delta, temp;\n\tZZ t_1, t_2, t_3, prod, chal_temp;\n\tZZ ord = H.get_ord();\n\tlong m = (chal->size()-1)/2;\n\tlong n = Delta_bar->size();\n\tvector<ZZ>* Delta_temp=0;\n\n\tMod_p::expo(temp, c_dh, chal->at(0));\n\tMod_p::mult(t_Delta, temp, c_Delta);\n\n\tDelta_temp = new vector<ZZ>(n-1);\n\tt_3= chal->at(0);\n\tfor(i=0; i<n-1; i++){\n\t\tMulMod(t_1, Delta_bar->at(i), d_bar->at(i+1), ord);\n\t\tMulMod(t_2, t_3, Delta_bar->at(i+1),ord);\n\t\tSubMod(Delta_temp->at(i), t_2, t_1, ord);\n\t}\n\n\tco_Delta = Ped.commit(Delta_temp, r_Delta_bar);\n\n\tdelete Delta_temp;\n/*\tstring name = \"example.txt\";\n\tofstream ost;\n\tost.open(name.c_str(),ios::app);\n\tost<<\"Delta \"<<t_Delta<<\" \"<<c_Delta<<endl;*/\n\n\tprod = to_ZZ(1);\n\tchal_temp =to_ZZ(1);\n\tfor(i=1; i<=m; i++){\n\t\tfor(j=1; j<=n; j++){\n\t\t\tMulMod(chal_temp, chal_temp, chal_1,ord);\n\t\t\tSubMod(t_1, chal_temp, chal_2,ord);\n\t\t\tt_3 = n*(i-1)+j;\n\t\t\tMulMod(t_3,t_3, chal_3, ord);\n\t\t\tAddMod(t_1,t_1, t_3, ord);\n\t\t\tMulMod(prod,prod, t_1, ord);\n\t\t}\n\t}\n\tMulMod(prod, prod, chal->at(0), ord);\n\n\t//\tost<<\"prod \"<<prod<<\" \"<<Delta_bar->at(n-1)<<endl;\n\t//ost<<d_bar->at(0)<<\" \"<<Delta_bar->at(0)<<endl;\n\tif(t_Delta ==co_Delta)\n\t\tif(prod ==Delta_bar->at(n-1) & d_bar->at(0)==Delta_bar->at(0)){\n\t\treturn 1;\n\t}\n\treturn 0;\n}\n\nint func_ver::check_B(vector<Mod_p>* c_B, Mod_p c_B0, vector<ZZ>* chal, vector<ZZ>* B_bar, ZZ r_B_bar){\n\tlong i;\n\tMod_p t_B, co_B, temp, temp_1;\n\tlong m = c_B->size();\n\t//check for correctness of the committed B\n\ttemp = c_B0;\n\tfor(i = 0; i<m; i++){\n\t\tMod_p::expo(temp_1,c_B->at(i), chal->at(i));\n\t\tMod_p::mult(temp,temp,temp_1);\n\t}\n\tt_B = temp;\n\tco_B = Ped.commit(B_bar, r_B_bar);\n/*\tstring name = \"example.txt\";\n\tofstream ost;\n\tost.open(name.c_str(),ios::app);\n\tost<<\"B \"<<t_B<<\" \"<<co_B<<endl;*/\n\tif(t_B==co_B){\n\t\treturn 1;\n\t}\n\treturn 0;\n}\n\nint func_ver::check_a(vector<Mod_p>* c_a, vector<Mod_p>* c_Dl, vector<ZZ>* chal, ZZ a_bar, ZZ r_a_bar){\n\tlong i,l;\n\tMod_p t_a, co_a, temp, temp_1;\n\tlong m = c_a->size()/2;\n\n\t//Check that the random values are used right\n\ttemp = c_a->at(0);\n\tl=2*m-1;\n\tfor(i = 1; i<=l; i++){\n\t\tMod_p::expo(temp_1,c_a->at(i), chal->at(i-1));\n\t\tMod_p::mult(temp,temp,temp_1);\n\t}\n\tt_a = temp;\n\tco_a = Ped.commit(a_bar, r_a_bar);\n/*\tstring name = \"example.txt\";\n\tofstream ost;\n\tost.open(name.c_str(),ios::app);\n\tost<<\"a \"<<t_a<<\" \"<<co_a<<endl;\n*/\n\tif(t_a==co_a & c_a->at(m)==c_Dl->at(m+1)){//both commitments should be com(0,0), so equal\n\t\treturn 1;\n\t}\n\treturn 0;\n}\n\nint func_ver::check_c(vector<vector<Cipher_elg>* >* enc, vector<Cipher_elg>* E, ZZ chal){\n\tlong i,j;\n\tZZ chal_temp;\n\tZZ ord = H.get_ord();\n\tCipher_elg c, temp;\n\tlong m = enc->size();\n\tlong n = enc->at(0)->size();\n\n\tchal_temp = to_ZZ(1);\n\tc = Cipher_elg(1,1,H.get_mod());\n \tfor(i = 0; i<m;i++){\n\t\tfor(j = 0; j<n;j++){\n\t\t\tMulMod(chal_temp, chal_temp, chal, ord);\n\t\t\tCipher_elg::expo(temp,enc->at(i)->at(j),chal_temp);\n\t\t\tCipher_elg::mult(c,c,temp);\n\t\t}\n\t}\n \tif(E->at(m)==c){\n \t\treturn 1;\n \t}\n \treturn 0;\n}\n\nint func_ver::check_E(vector<vector<Cipher_elg>* >* C, vector<Cipher_elg>* E, vector<ZZ>* chal, vector<ZZ>* B_bar, ZZ a_bar, ZZ rho_bar ){\n\tlong i,j,l;\n\tCipher_elg t_E, co_E, temp, temp_1, temp_2;\n\tMod_p gen,t;\n\tlong m = C->size();\n\tlong n = C->at(0)->size();\n\tZZ te;\n\tZZ ord = H.get_ord();\n\tZZ mod = H.get_mod();\n\n \ttemp = E->at(0);\n \tl=2*m;\n\tfor(i = 1; i<l; i++){\n\t\tCipher_elg::expo(temp_1,E->at(i), chal->at(i-1));\n\t\tCipher_elg::mult(temp,temp,temp_1);\n\t}\n\tt_E = temp;\n\n\tgen = H.get_gen();\n\tt = Mod_p::expo(gen,a_bar);\n\ttemp = El.encrypt(t, rho_bar);\n\ttemp_1=Cipher_elg(1,1,mod);\n\tl=m-1;\n\tfor(i = 0; i<l;i++){\n\t\tfor(j = 0; j<n;j++){\n\t\t\tMulMod(te , B_bar->at(j),chal->at(m-i-2),ord);\n\t\t\tCipher_elg::expo(temp_2,C->at(i)->at(j),te);\n\t\t\tCipher_elg::mult(temp_1,temp_1,temp_2);\n\t\t}\n\t}\n\tfor(j = 0; j<n;j++){\n\t\tte =B_bar->at(j);\n\t\tCipher_elg::expo(temp_2,C->at(m-1)->at(j),te);\n\t\tCipher_elg::mult(temp_1,temp_1,temp_2);\n\t}\n\tCipher_elg::mult(co_E ,temp_1, temp);\n\n/*\tstring name = \"example.txt\";\n\tofstream ost;\n\tost.open(name.c_str(),ios::app);\n\tost<<\"E\"<<t_E<<\" \"<<co_E<<endl;*/\n\tif(t_E==co_E){\n\t\treturn 1;\n\t}\n\treturn 0;\n}\n\n\nint func_ver::check_Dh_op(vector<Mod_p>* c_Dh, vector<ZZ>* chal, vector<ZZ>* D_h_bar, ZZ r_Dh_bar, long win_LL){\n\tMod_p t_Dh, co_Dh;\n\n\tmulti_expo::multi_expo_LL(t_Dh,c_Dh, chal, win_LL);\n\tco_Dh = Ped.commit_opt(D_h_bar,r_Dh_bar);\n\n\t//cout<<\"D_h \"<<t_Dh<<\" \"<<co_Dh<<endl;\n\tif (t_Dh == co_Dh){\n\t\treturn 1;\n\t}\n\treturn 0;\n}\n\n\nint func_ver::check_D_op(Mod_p c_D0, Mod_p c_z, vector<Mod_p>* c_A, vector<Mod_p>* c_B, vector<ZZ>* chal_1, ZZ chal_2, vector<ZZ>* A_bar, ZZ r_A_bar, long n){\n\tint i;\n\tMod_p t_D, co_D, temp, inv;\n\tlong m = c_A->size()-1;\n\tZZ ord = H.get_ord();\n\tvector<ZZ>* v_1 = new vector<ZZ>(n);\n\n\tt_D = c_D0;\n\tMod_p::inv(inv, c_z);\n\tfor (i=1; i<m;i++){\n\t\tMod_p::expo(temp,c_A->at(i),chal_2);\n\t\tMod_p::mult(temp, temp,c_B->at(i));\n\t\tMod_p::mult(temp,temp,inv);\n\t\tMod_p::expo(temp, temp, chal_1->at(i-1));\n\t\tMod_p::mult(t_D,t_D,temp);\n\t}\n\tfor(i=0; i<n;i++){\n\t\tNegateMod(v_1->at(i),to_ZZ(1),ord);\n\t}\n\ttemp=Ped.commit_opt(v_1,to_ZZ(0));\n\tMod_p::expo(temp, temp, chal_1->at(m-1));\n\tMod_p::mult(t_D,t_D,temp);\n\tco_D = Ped.commit_opt(A_bar, r_A_bar);\n\t//cout<<\"D \"<<t_D<<\" \"<<co_D<<endl;\n\tdelete v_1;\n\tif(t_D == co_D){\n\t\treturn 1;\n\t}\n\treturn 0;\n}\n\n\nint func_ver::check_Ds_op(vector<Mod_p>* c_Ds, vector<Mod_p>* c_Dh, Mod_p c_Dm, vector<ZZ>* chal_1, vector<ZZ>* chal_2, vector<ZZ>* Ds_bar, ZZ r_Ds_bar){\n\tlong i,l;\n\tlong m= c_Ds->size()-1;\n\tMod_p t_Ds, co_Ds, temp, temp_1;\n\n\tl=m-1;\n\tfor(i=0; i<l; i++){\n\t\tMod_p::expo(c_Ds->at(i),c_Dh->at(i), chal_1->at(i));\n\t}\n\tif(m>1){\n\t\tMod_p::expo(temp, c_Dh->at(1), chal_1->at(0));\n\t\tfor(i=1;i<l; i++){\n\t\t\tMod_p::expo(temp_1,c_Dh->at(i+1), chal_1->at(i));\n\t\t\tMod_p::mult(temp,temp,temp_1);\n\t\t}\n\t\tc_Ds->at(l)=temp;\n\t}\n\telse{\n\t\tc_Ds->at(l)=Mod_p(1,G.get_mod());\n\t}\n\n\tc_Ds->at(m)=c_Dm;\n\tMod_p::expo(t_Ds, c_Ds->at(0),chal_2->at(m-1));\n\tfor(i=1; i<m; i++){\n\t\tMod_p::expo(temp, c_Ds->at(i), chal_2->at(m-1-i));\n\t\tMod_p::mult(t_Ds, t_Ds,temp);\n\t}\n\tMod_p::mult(t_Ds,t_Ds,c_Ds->at(m));\n\tco_Ds = Ped.commit_opt(Ds_bar, r_Ds_bar);\n\t//cout<<\"Ds \"<<t_Ds<<\" \"<<co_Ds<<endl;\n\tif(t_Ds == co_Ds){\n\t\treturn 1;\n\t}\n\treturn 0;\n}\n\nint func_ver::check_Dl_op(vector<Mod_p>* c_Dl, vector<ZZ>* chal, vector<ZZ>* A_bar, vector<ZZ>* Ds_bar, vector<ZZ>*  chal_1, ZZ r_Dl_bar){\n\tlong i;\n\tMod_p t_Dl, co_Dl, temp;\n\tZZ temp_1;\n\tlong l = c_Dl->size();\n\tlong pos = (l-1)/2+1;\n\tZZ mod = G.get_mod();\n\n\tt_Dl = c_Dl->at(0);\n\tfor(i=1; i<l; i++){\n\t\tMod_p::expo(temp, c_Dl->at(i),chal->at(i-1));\n\t\t//Mod_p::mult(t_Dl,t_Dl, temp);\n\t\tt_Dl = t_Dl*temp;\n\t}\n\ttemp_1=Functions::bilinearMap(A_bar,Ds_bar,chal_1);\n\tco_Dl =Ped.commit_sw(temp_1,r_Dl_bar);\n\t//cout<<\"Dl \"<<t_Dl<<\" \"<<co_Dl<<endl;\n\n\ttemp= Mod_p(1, mod);\n\tif(t_Dl==co_Dl & c_Dl->at(pos)==temp){\n\t\treturn 1;\n\t}\n\treturn 0;\n}\n\n\nint func_ver::check_d_op(vector<Mod_p>* c_Dh, Mod_p c_d, vector<ZZ>* chal, vector<ZZ>* d_bar, ZZ r_d_bar){\n\tMod_p t_d, co_d, temp;\n\tlong m = c_Dh->size();\n\tMod_p::expo(temp, c_Dh->at(m-1), chal->at(0));\n\tMod_p::mult(t_d, temp, c_d);\n\tco_d = Ped.commit_opt(d_bar, r_d_bar);\n\t//cout<<\"d \"<<t_d<<\" \"<<co_d<<endl;\n\tif(t_d==co_d){\n\t\treturn 1;\n\t}\n\treturn 0;\n}\n\n\nint func_ver::check_Delta_op(Mod_p c_dh, Mod_p c_Delta, vector<ZZ>* chal, vector<ZZ>* Delta_bar, vector<ZZ>* d_bar, ZZ r_Delta_bar, ZZ chal_1, ZZ chal_2, ZZ chal_3){\n\tlong i,j;\n\tMod_p t_Delta, co_Delta, temp;\n\tZZ t_1, t_2, t_3, prod, chal_temp;\n\tZZ ord = H.get_ord();\n\tlong m = (chal->size()-1)/2;\n\tlong n = Delta_bar->size();\n\tvector<ZZ>* Delta_temp=0;\n\n\tMod_p::expo(temp, c_dh, chal->at(0));\n\tMod_p::mult(t_Delta, temp, c_Delta);\n\n\tDelta_temp = new vector<ZZ>(n-1);\n\tt_3= chal->at(0);\n\tfor(i=0; i<n-1; i++){\n\t\tMulMod(t_1, Delta_bar->at(i), d_bar->at(i+1), ord);\n\t\tMulMod(t_2, t_3, Delta_bar->at(i+1),ord);\n\t\tSubMod(Delta_temp->at(i), t_2, t_1, ord);\n\t}\n\n\tco_Delta = Ped.commit_opt(Delta_temp, r_Delta_bar);\n\n\tdelete Delta_temp;\n\t//cout<<\"Delta \"<<t_Delta<<\" \"<<co_Delta<<endl;\n\n\tprod = to_ZZ(1);\n\tchal_temp =to_ZZ(1);\n\tfor(i=1; i<=m; i++){\n\t\tfor(j=1; j<=n; j++){\n\t\t\tMulMod(chal_temp, chal_temp, chal_1,ord);\n\t\t\tSubMod(t_1, chal_temp, chal_2,ord);\n\t\t\tt_3 = n*(i-1)+j;\n\t\t\tMulMod(t_3,t_3, chal_3, ord);\n\t\t\tAddMod(t_1,t_1, t_3, ord);\n\t\t\tMulMod(prod,prod, t_1, ord);\n\t\t}\n\t}\n\tMulMod(prod, prod, chal->at(0), ord);\n\n\t//cout<<\"prod \"<<prod<<\" \"<<Delta_bar->at(n-1)<<endl;\n\t//cout<<d_bar->at(0)<<\" \"<<Delta_bar->at(0)<<endl;\n\tif(t_Delta ==co_Delta)\n\t\tif(prod ==Delta_bar->at(n-1) & d_bar->at(0)==Delta_bar->at(0)){\n\t\treturn 1;\n\t}\n\treturn 0;\n}\n\nint func_ver::check_B_op(vector<Mod_p>* c_B, Mod_p c_B0, vector<ZZ>* chal, vector<ZZ>* B_bar, ZZ r_B_bar, long win_LL){\n\tlong i;\n\tMod_p t_B, co_B, temp, temp_1;\n\tlong m = c_B->size();\n\tvector<Mod_p>* B_temp = new vector<Mod_p>(m+1);\n\tvector<ZZ>* chal_mult = new vector<ZZ>(m+1);\n\n\t//check for correctness of the committed B\n\tB_temp ->at(0)= c_B0;\n\tchal_mult->at(0)=1;\n\tfor(i = 0; i<m; i++){\n\t\tB_temp->at(i+1)=c_B->at(i);\n\t\tchal_mult->at(i+1)=chal->at(i);\n\t}\n\tmulti_expo::multi_expo_LL(t_B, B_temp, chal_mult, win_LL);\n\n\tco_B = Ped.commit_opt(B_bar, r_B_bar);\n\t//cout<<\"B \"<<t_B<<\" \"<<co_B<<endl;\n\tdelete B_temp;\n\tdelete chal_mult;\n\tif(t_B==co_B){\n\t\treturn 1;\n\t}\n\treturn 0;\n}\n\nint func_ver::check_a_op(vector<Mod_p>* c_a, vector<Mod_p>* c_Dl, vector<ZZ>* chal, ZZ a_bar, ZZ r_a_bar){\n\tlong i,l;\n\tMod_p t_a, co_a, temp, temp_1;\n\tlong m = c_a->size()/2;\n\n\t//Check that the random values are used right\n\ttemp = c_a->at(0);\n\tl=2*m-1;\n\tfor(i = 1; i<=l; i++){\n\t\tMod_p::expo(temp_1,c_a->at(i), chal->at(i-1));\n\t\tMod_p::mult(temp,temp,temp_1);\n\t}\n\tt_a = temp;\n\tco_a = Ped.commit_sw(a_bar, r_a_bar);\n\t//cout<<\"a \"<<t_a<<\" \"<<co_a<<endl;\n\n\tif(t_a==co_a & c_a->at(m)==c_Dl->at(m+1)){//both commitments should be com(0,0), so equal\n\t\treturn 1;\n\t}\n\treturn 0;\n}\n\n\nint func_ver::check_c_op(vector<vector<Cipher_elg>* >* enc, vector<Cipher_elg>* E, ZZ chal, long omega){\n\tlong i,j;\n\tZZ chal_temp;\n\tZZ ord = H.get_ord();\n\tCipher_elg c, temp;\n\tvector<ZZ>* v_chal = 0;\n\tlong m = enc->size();\n\tlong n = enc->at(0)->size();\n\n\tchal_temp = to_ZZ(1);\n\tc = Cipher_elg(1,1,H.get_mod());\n\tv_chal = new vector<ZZ>(n);\n \tfor(i = 0; i<m;i++){\n\t\tfor(j = 0; j<n;j++){\n\t\t\tMulMod(chal_temp, chal_temp, chal, ord);\n\t\t\tv_chal->at(j)=chal_temp;\n\t\t}\n\t\tmulti_expo::expo_mult(temp, enc->at(i), v_chal, omega);\n\t\tCipher_elg::mult(c,c,temp);\n\t}\n \tdelete v_chal;\n \t//cout<<\"c \"<<E->at(m)<<\" \"<<c<<endl;\n \tif(E->at(m)==c){\n \t\treturn 1;\n \t}\n \treturn 0;\n}\n\nint func_ver::check_E_op(vector<vector<Cipher_elg>* >* C, vector<Cipher_elg>* E, vector<ZZ>* chal, vector<ZZ>* B_bar, ZZ a_bar, ZZ rho_bar , long omega){\n\tlong i,l;\n\tCipher_elg t_E, co_E, temp, temp_1;\n\tMod_p gen,t;\n\tlong m = C->size();\n\tZZ ord = H.get_ord();\n\tZZ mod = H.get_mod();\n\tlong num_b = NumBits(ord);\n\tl=2*m;\n\tvector<vector<long>* >* basis_chal = new vector<vector<long>* >(l);\n\n\tbasis_chal ->at(0)= multi_expo::to_basis(to_ZZ(1), num_b, omega);\n\tbasis_chal->at(1) = multi_expo::to_basis(chal->at(0), num_b, omega);\n\tfor(i=2; i<l; i++){\n\t\tbasis_chal->at(i) = multi_expo::to_basis(chal->at(i-1), num_b, omega);\n\t}\n\n\tmulti_expo::expo_mult(t_E, E, basis_chal, omega);\n\n\tvector<ZZ>* chal_temp = new vector<ZZ>(m);\n\tl=m-1;\n\tfor(i=0; i<l; i++){\n\t\tchal_temp->at(i)= chal->at(m-i-2);\n\t}\n\tchal_temp->at(l)=1;\n\n\tgen = H.get_gen();\n\tt = Mod_p::expo(gen,a_bar);\n\ttemp = El.encrypt(t, rho_bar);\n\tmulti_expo::expo_mult(temp_1, C, chal_temp, B_bar, omega);\n\n\tCipher_elg::mult(co_E ,temp_1, temp);\n\n\tFunctions::delete_vector(basis_chal);\n\tdelete(chal_temp);\n\t//cout<<\"E\"<<t_E<<\" \"<<co_E<<endl;\n\tif(t_E==co_E){\n\t\treturn 1;\n\t}\n\n\treturn 0;\n\n}\n\n\nvoid func_ver::fill_vector(vector<ZZ>* t){\n\tlong i,l;\n\tZZ temp;\n\tZZ ord = H.get_ord();\n\n\tl= t->size();\n\ttemp = RandomBnd(ord);\n\tt->at(0)=temp;\n\tfor(i=1; i<l; i++){\n\t\tMulMod(t->at(i),t->at(i-1),temp, ord);\n\t}\n}\n\n\nvoid func_ver::fill_x8(vector<ZZ>* chal_x8, vector<vector<long>* >* basis_chal_x8, vector<ZZ>* mul_chal_x8, long omega){\n\tlong i, l;\n\tZZ chal;\n\tZZ ord = H.get_ord();\n\tlong num_b= NumBits(ord);\n\n\tl= chal_x8->size();\n\tchal = RandomBnd(ord);\n\n\tchal_x8->at(0)= chal;\n\tbasis_chal_x8->at(0) = multi_expo::to_basis(to_ZZ(1),num_b, omega);\n\tbasis_chal_x8->at(1) = multi_expo::to_basis(chal_x8->at(0),num_b, omega);\n\n\tmul_chal_x8->at(0) =1;\n\tmul_chal_x8->at(1) =chal_x8->at(0);\n\n\tfor (i = 1; i<l; i++){\n\t\t MulMod(chal_x8->at(i),chal, chal_x8->at(i-1), ord);\n\t\t basis_chal_x8->at(i+1) = multi_expo::to_basis(chal_x8->at(i),num_b, omega);\n\t\t mul_chal_x8->at(i+1) = chal_x8->at(i);\n\t}\n}\n\n", "meta": {"hexsha": "e8e54112c1500ac577e942f9b409dc0fe46c366b", "size": 16527, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/func_ver.cpp", "max_stars_repo_name": "3for/verifiable-shuffle", "max_stars_repo_head_hexsha": "73f92b41bbe76eee4ef8ad35e6ccf7e83acef28b", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2018-01-11T14:06:41.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-27T08:28:26.000Z", "max_issues_repo_path": "src/func_ver.cpp", "max_issues_repo_name": "3for/verifiable-shuffle", "max_issues_repo_head_hexsha": "73f92b41bbe76eee4ef8ad35e6ccf7e83acef28b", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/func_ver.cpp", "max_forks_repo_name": "3for/verifiable-shuffle", "max_forks_repo_head_hexsha": "73f92b41bbe76eee4ef8ad35e6ccf7e83acef28b", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-04-13T06:11:06.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-03T15:21:49.000Z", "avg_line_length": 24.3044117647, "max_line_length": 165, "alphanum_fraction": 0.6183215345, "num_tokens": 6674, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7310585786300049, "lm_q2_score": 0.4455295350395727, "lm_q1q2_score": 0.325708188623717}}
{"text": "#include <pcl/point_cloud.h>\n#include <pcl/point_types.h>\n#include <pcl/common/transforms.h>\n#include <string>\n#include <pcl/io/boost.h>\n#include <pcl/io/pcd_io.h>\n#include <pcl/filters/extract_indices.h>\n#include <Eigen/Dense>\n#include <stdio.h>\n#include <stdlib.h>\n#include <time.h>\n\n#ifndef CUBE_ALIGNER_H\n#define CUBE_ALIGNER_H\n\n#define RAND_SCALE 100000\n#define V_CT 7\n\n#ifdef ADAPT_SIMPLEX\n  #define ALPHA 1.0\n  #define BETA (4.0/3.0)\n  #define GAMMA (2.0/3.0)\n  #define DELTA (5.0/6.0)\n#else\n  #define ALPHA 1.0\n  #define BETA 2.0\n  #define GAMMA 0.5\n  #define DELTA 0.5\n#endif\n\n#define CUBE_MAX_ITER 500\n//#define E_VAL 0.1\n#define EPS_VAL 1200\n#define MIN_CLUSTER_DENS 0.66\n\n#ifndef MY_PI\n#define MY_PI 3.141592\n#endif\n\nusing namespace std;\nusing namespace pcl;\n\nstatic bool isRandSeeded = false;\n\nstatic double E_VAL = 0.2;\n  \nclass CVertex\n{\npublic:\n  CVertex(){\n    _alpha = 0;\n    _beta = 0;\n    _gamma = 0;\n    _x = 0;\n    _y = 0;\n    _z = 0;\n  }\n  \n  CVertex(double a, double b, double g, double x, double y, double z)\n  {\n    _alpha = a;\n    _beta = b;\n    _gamma = g;\n    _x = x;\n    _y = y;\n    _z = z;\n    _score = 0;\n  }\n  \n  CVertex(Eigen::Matrix4f input)\n  {\n    double cb;\n    _x = input(0,3);\n    _y = input(1,3);\n    _z = input(2,3);\n    _beta = asin(-input(2,0));\n    cb = cos(_beta);\n    _alpha = asin(input(1,0)/cb);\n    _gamma = asin(input(2,1)/cb);\n    \n    _score = 0;\n  }\n  \n  /*CVertex(Eigen::Matrix4d input)\n  {\n    double cb;\n    _x = input(0,3);\n    _y = input(1,3);\n    _z = input(2,3);\n    _beta = asin(-input(2,0));\n    cb = cos(_beta);\n    _alpha = asin(input(1,0)/cb);\n    _gamma = asin(input(2,1)/cb);\n    \n    _score = 0;\n  }*/\n  \n#define RAD_SCALE 1.0\n  \n  CVertex(int i, double d, const CVertex& vert)\n  {\n    if (!isRandSeeded)\n    {\n      srand(time(NULL));\n      isRandSeeded = true;\n    }\n    int m = i/7;\n    _alpha = vert._alpha;\n    _beta = vert._beta;\n    _gamma = vert._gamma;\n    _x = vert._x;\n    _y = vert._y;\n    _z = vert._z;\n    \n    switch(i%7)\n    {\n      case 0:\n\t_alpha += (1-2*m)*d/RAD_SCALE;\n\tbreak;\n      case 1:\n\t_beta += (1-2*m)*d/RAD_SCALE;\n\tbreak;\n      case 2:\n\t_gamma += (1-2*m)*d/RAD_SCALE;\n\tbreak;\n      case 3:\n\t_x += (1-2*m)*d;\n\tbreak;\n      case 4:\n\t_y += (1-2*m)*d;\n\tbreak;\n      case 5:\n\t_z += (1-2*m)*d;\n\tbreak;\n      default:\n\tbreak;\n    }\n    /*switch(j)\n    {\n      case 1:\n\t_alpha += d/10.0;\n\tbreak;\n      case 2:\n\t_beta += d/10.0;\n\tbreak;\n      case 3:\n\t_gamma += d/10.0;\n\tbreak;\n      case 4:\n\t_x += d/10.0;\n\tbreak;\n      case 5:\n\t_y += d/10.0;\n\tbreak;\n      case 6:\n\t_z += d/10.0;\n\tbreak;\n      default:\n\tbreak;\n    }*/\n    _score = 0;\n  }\n  \n  CVertex(const CVertex& cg)\n  {\n    _alpha = cg._alpha;\n    _beta = cg._beta;\n    _gamma = cg._gamma;\n    _x = cg._x;\n    _y = cg._y;\n    _z = cg._z;\n    _score = 0;\n  }\n  \n  CVertex(CVertex *cgArr, int count)\n  {\n    int i;\n    for (i=0;i<count;i++)\n    {\n      _alpha = cgArr[i]._alpha/count;\n      _beta = cgArr[i]._beta/count;\n      _gamma = cgArr[i]._gamma/count;\n      _x = cgArr[i]._x/count;\n      _y = cgArr[i]._y/count;\n      _z = cgArr[i]._z/count;\n    }\n    _score = 0;\n  }\n  \n  CVertex(double maxRot, double maxTran)\n  {\n    if (!isRandSeeded)\n    {\n      srand(time(NULL));\n      isRandSeeded = true;\n    }\n    _alpha = (((rand()% (RAND_SCALE*2))-RAND_SCALE)*maxRot)/(double)RAND_SCALE;\n    _beta = (((rand()% (RAND_SCALE*2))-RAND_SCALE)*maxRot)/(double)RAND_SCALE;\n    _gamma = (((rand()% (RAND_SCALE*2))-RAND_SCALE)*maxRot)/(double)RAND_SCALE;\n    _x = (((rand()% (RAND_SCALE*2))-RAND_SCALE)*maxTran)/(double)RAND_SCALE;\n    _y = (((rand()% (RAND_SCALE*2))-RAND_SCALE)*maxTran)/(double)RAND_SCALE;\n    _z = (((rand()% (RAND_SCALE*2))-RAND_SCALE)*maxTran)/(double)RAND_SCALE;\n    _score = 0;\n  }\n  \n  inline double getDist()\n  {\n    return sqrt(_x*_x + _y*_y + _z*_z);\n  }\n  \n  inline double getMaxDiff(CVertex comp)\n  {\n    double diff = 0;\n    \n    if (fabs(_x-comp._x) > diff)\n    {\n      diff = fabs(_x-comp._x);\n    }\n    if (fabs(_y-comp._y) > diff)\n    {\n      diff = fabs(_y-comp._y);\n    }\n    if (fabs(_z-comp._z) > diff)\n    {\n      diff = fabs(_z-comp._z);\n    }\n    if (fabs(_alpha-comp._alpha) > diff)\n    {\n      diff = fabs(_alpha-comp._alpha);\n    }\n    if (fabs(_beta-comp._beta) > diff)\n    {\n      diff = fabs(_beta-comp._beta);\n    }\n    if (fabs(_gamma-comp._gamma) > diff)\n    {\n      diff = fabs(_gamma-comp._gamma);\n    }\n    \n    return diff;\n  }\n  \n  inline Eigen::Matrix4f toTranslation()\n  {\n    Eigen::Matrix4f outMat;\n    double ca = cos(_alpha);\n    double cb = cos(_beta);\n    double cg = cos(_gamma);\n    double sa = sin(_alpha);\n    double sb = sin(_beta);\n    double sg = sin(_gamma);\n    \n    //build the trans-rot matrix\n    outMat(0,0) = ca*cb;\n    outMat(0,1) = ca*sb*sg - sa*cg;\n    outMat(0,2) = sa*sg - ca*sb*cg;\n    outMat(1,0) = sa*cb;\n    outMat(1,1) = ca*cg - sa*sb*sg;\n    outMat(1,2) = sa*sb*cg - ca*sg;\n    outMat(2,0) = -sb;\n    outMat(2,1) = cb*sg;\n    outMat(2,2) = cb*cg;\n    outMat(3,0) = 0;outMat(3,1)=0;outMat(3,2)=0;\n    outMat(0,3) = _x;\n    outMat(1,3) = _y;\n    outMat(2,3) = _z;\n    outMat(3,3) = 1;\n    \n    return outMat;\n  }\n  \n  inline void setScore(int score)\n  {\n    _score = score;\n  }\n  \n  inline int getScore()\n  {\n    return _score;\n  }\n  \n  inline static int sorter(const void *v1, const void *v2)\n  {\n    CVertex *cv1,*cv2;\n    if (!v1 || !v2)\n    {\n      return 0;\n    }\n    cv1 = (CVertex*)v1;\n    cv2 = (CVertex*)v2;\n    \n    return (cv1->_score < cv2->_score) - \n      2*(cv1->_score > cv2->_score);\n  }\n  \n  inline CVertex operator+(const CVertex& vIn)\n  {\n    CVertex outVert(this,1);\n    outVert += vIn;\n    \n    return outVert;\n  }\n  \n  inline CVertex operator+=(const CVertex& vIn)\n  {\n    _alpha += vIn._alpha;\n    _beta += vIn._beta;\n    _gamma += vIn._gamma;\n    _x += vIn._x;\n    _y += vIn._y;\n    _z += vIn._z;\n    \n    return *this;\n  }\n  \n  inline CVertex operator-(const CVertex& vIn)\n  {\n    CVertex outVert(this,1);\n    outVert -= vIn;\n    \n    return outVert;\n  }\n  \n  inline CVertex operator-=(const CVertex& vIn)\n  {\n    _alpha -= vIn._alpha;\n    _beta -= vIn._beta;\n    _gamma -= vIn._gamma;\n    _x -= vIn._x;\n    _y -= vIn._y;\n    _z -= vIn._z;\n    \n    return *this;\n  }\n  \n  inline CVertex operator*(float alpha)\n  {\n    CVertex outVert(this,1);\n    outVert *= alpha;\n    \n    return outVert;\n  }\n  \n  inline CVertex operator*=(float alpha)\n  {\n    _alpha *= alpha;\n    _beta *= alpha;\n    _gamma *= alpha;\n    _x *= alpha;\n    _y *= alpha;\n    _z *= alpha;\n    \n    return *this;\n  }\n  \n  inline double getX(){return _x;}\n  inline double getY(){return _y;}\n  inline double getZ(){return _z;}\n  \nprivate:\n  friend std::ostream& operator<<(std::ostream &strm, const CVertex& vert);\n  double _alpha;\n  double _beta;\n  double _gamma;\n  double _x;\n  double _y;\n  double _z;\n  int _score;\n};\n\n//add the scalar*matrix operator outside the class\ninline CVertex operator*(float alpha, const CVertex& vert)\n{\n  CVertex outMat(vert);\n  outMat *= alpha;\n  return outMat;\n}\n\n//String writer\nstd::ostream& operator<<(std::ostream &strm, const CVertex& vert)\n{\n  return strm << \"(\" << vert._x << \",\" << vert._y << \",\" << vert._z << \",\" << vert._alpha << \",\" << vert._beta << \",\" << vert._gamma <<\")\";\n}\n\n\nclass CubeAligner\n{\npublic:\n  typedef PointCloud<PointXYZI> Cloud;\n  typedef PointCloud<PointXYZI>::Ptr CloudPtr;\n  typedef PointCloud<PointXYZI>::iterator CloudItr;\n  \n  CubeAligner(CloudPtr cloudBase, double e)\n  {\n    CloudItr npIt = cloudBase->begin();\n    _min_x=0;\n    _max_x=0;\n    _min_y=0;\n    _max_y=0;\n    _min_z=0;\n    _max_z=0;\n    _arrSz = 0;\n    \n    while (npIt<cloudBase->end())\n    {\n      if (_min_x==0)\n      {\n\t_min_x = (*npIt).x;\n\t_max_x = (*npIt).x;\n\t_min_y = (*npIt).y;\n\t_max_y = (*npIt).y;\n\t_min_z = (*npIt).z;\n\t_max_z = (*npIt).z;\n      }\n      else\n      {\n\tif ((*npIt).x < _min_x)\n\t{\n\t  _min_x = (*npIt).x;\n\t}\n\tif ((*npIt).x > _max_x)\n\t{\n\t  _max_x = (*npIt).x;\n\t}\n\tif ((*npIt).y < _min_y)\n\t{\n\t  _min_y = (*npIt).y;\n\t}\n\tif ((*npIt).y > _max_y)\n\t{\n\t  _max_y = (*npIt).y;\n\t}\n\tif ((*npIt).z < _min_z)\n\t{\n\t  _min_z = (*npIt).z;\n\t}\n\tif ((*npIt).z > _max_z)\n\t{\n\t  _max_z = (*npIt).z;\n\t}\n      }\n      npIt++;\n    }\n    int gf=0;\n    \n    do\n    {\n      _e = e + ((gf++) * 0.01);\n      _xCount = (_max_x - _min_x)/_e;\n      _yCount = (_max_y - _min_y)/_e;\n      _zCount = (_max_z - _min_z)/_e;\n    }\n    while (_xCount*_yCount*_zCount <= 0);\n    \n    //printf(\"Setup cube grid for (%.2f,%.2f,%.2f)->(%.2f,%.2f,%.2f)\\n\"\n    //\"%ld grid points\\n\",\n\t   //_min_x,_min_y,_min_z,_max_x,_max_y,_max_z,arraySizeNeeded());\n    _vBase = (unsigned char *)malloc(arraySizeNeeded());\n    memset(_vBase,0,arraySizeNeeded());\n    \n    \n    //printf(\"%d/%ld filled grid points\\n\",cloudToArray(cloudBase,_vBase),_xCount*_yCount*_zCount);\n    cloudToArray(cloudBase,_vBase);\n  }\n  \n  ~CubeAligner()\n  {\n    if (_vBase)\n    {\n      free(_vBase);\n    }\n  }\n  \n  inline void idxToXYZ(long idx, double *x, double *y, double *z)\n  {\n    int ix,iy,iz;\n    ix = idx%_xCount;\n    iy = (idx/_xCount)%_yCount;\n    iz = idx/_xCount/_yCount;\n    \n    *x = _min_x + ix*_e;\n    *y = _min_y + iy*_e;\n    *z = _min_z + iz*_e;\n    \n    return;\n  }\n    \n  inline long toIdx(long ix, long iy, long iz)\n  {\n    if (ix < 0 || ix >= _xCount || \n      iy < 0 || iy >= _yCount || \n      iz < 0 || iz >= _zCount)\n      return -1;\n    \n    return ix+iy*_xCount+iz*_xCount*_yCount;\n  }\n  \n  inline size_t arraySizeNeeded()\n  {\n    size_t totalCount;\n    \n    if (!_arrSz)\n    {\n      totalCount = _xCount*_yCount*_zCount;\n      \n      totalCount += (totalCount%8)?8:0;\n      \n      _arrSz = totalCount/8;\n    }\n    \n    return _arrSz;\n  }\n  \n  inline int cloudToArray(CloudPtr cloud, unsigned char *v)\n  {\n    CloudItr npIt = cloud->begin();\n    long ix,iy,iz;\n    int bitIdx;\n    long long idx;\n    size_t arrIdx;\n    int ptCount = 0;\n    int matchCount = 0;\n    \n    while (npIt<cloud->end())\n    {\n      ptCount++;\n      ix = ((*npIt).x-_min_x)/_e;\n      iy = ((*npIt).y-_min_y)/_e;\n      iz = ((*npIt).z-_min_z)/_e;\n      //ignore points outsize range\n      if (ix < 0 || iy < 0 || iz < 0\n\t|| ix >= _xCount || iy >= _yCount || iz >= _zCount)\n      {npIt++;continue;}\n      \n      matchCount++;\n      \n      idx = ix+iy*_xCount+iz*_xCount*_yCount;\n      arrIdx = idx/8;\n      bitIdx = idx%8;\n      v[arrIdx] |= (0x80 >> bitIdx);\n      \n      npIt++;\n    }\n    \n    return matchCount;\n  }\n  \n  class CCluster\n  {\n  public:\n    CCluster(CubeAligner *cube){_my_cube = cube;}\n    \n    inline void addIdx(long idx)\n    {\n      _my_pts.push_back(idx);\n    }\n    \n    inline void addIdx(long ix, long iy, long iz)\n    {\n      _my_pts.push_back(_my_cube->toIdx(ix,iy,iz));\n    }\n    \n    inline void calcDimensions()\n    {\n      std::vector<long>::iterator it;\n      double x,y,z;\n      double mX=0,mY=0,mZ=0; // max values\n      //set origin to obsurdly large value to fin min value\n      _x_orig = 1e9;\n      _y_orig = 1e9;\n      _z_orig = 1e9;\n      \n      for (it = _my_pts.begin();it < _my_pts.end(); it++)\n      {\n\t_my_cube->idxToXYZ(*it,&x,&y,&z);\n\t\n\tif (x < _x_orig){_x_orig = x;}\n\tif (y < _y_orig){_y_orig = y;}\n\tif (z < _z_orig){_z_orig = z;}\n\tif (x > mX){mX = x;}\n\tif (y > mY){mY = y;}\n\tif (z > mZ){mZ = z;}\n      }\n      _dx = mX - _x_orig;\n      _dy = mY - _y_orig;\n      _dz = mZ - _z_orig;\n      \n      return;\n    }\n    \n    inline bool isInside(long idx)\n    {\n      double x,y,z;\n      _my_cube->idxToXYZ(idx,&x,&y,&z);\n      \n      if (x >= _x_orig && x <= (_x_orig+_dx) &&\n\ty >= _y_orig && y <= (_y_orig+_dy) &&\n\tz >= _z_orig && z <= (_z_orig+_dz))\n      {\n\treturn true;\n      }\n      else\n      {\n\treturn false;\n      }\n    }\n    \n    inline bool includes(long idx)\n    {\n      std::vector<long>::iterator it;\n      \n      for (it = _my_pts.begin(); it < _my_pts.end(); it++)\n      {\n\tif (*it == idx)\n\t{\n\t  return true;\n\t}\n      }\n      \n      return false;\n    }\n    \n    inline PointXYZI getCOG()\n    {\n      std::vector<long>::iterator lIt;\n      PointXYZI p1;\n      double x,y,z;\n      p1.x = 0;\n      p1.y = 0;\n      p1.z = 0;\n      \n      for (lIt = _my_pts.begin(); lIt < _my_pts.end() ; lIt++)\n      {\n\t_my_cube->idxToXYZ(*lIt,&x,&y,&z);\n\tp1.x += x/_my_pts.size();\n\tp1.y += y/_my_pts.size();\n\tp1.z += z/_my_pts.size();\n      }\n      \n      return p1;\n    }\n    \n    inline CloudPtr toPolygon(int i)\n    {\n      CloudPtr cloudOut(new Cloud);\n      std::vector<long>::iterator lIt;\n      \n      PointXYZI p1;\n      double x,y,z;\n      \n      for (lIt = _my_pts.begin(); lIt < _my_pts.end() ; lIt++)\n      {\n\t_my_cube->idxToXYZ(*lIt,&x,&y,&z);\n\tp1.x = x;\n\tp1.y = y;\n\tp1.z = z;\n  p1.intensity = i;\n\tcloudOut->push_back(p1);\n      }\n      \n//       PointXYZI p1,p2,p3,p4,p5,p6,p7,p8;\n//       p1.x = _x_orig;\n//       p1.y = _y_orig;\n//       p1.z = _z_orig;\n//       p2.x = _x_orig+_dx;\n//       p2.y = _y_orig;\n//       p2.z = _z_orig;\n//       p3.x = _x_orig+_dx;\n//       p3.y = _y_orig+_dy;\n//       p3.z = _z_orig;\n//       p4.x = _x_orig;\n//       p4.y = _y_orig+_dy;\n//       p4.z = _z_orig;\n//       p5.x = _x_orig;\n//       p5.y = _y_orig;\n//       p5.z = _z_orig + _dz;\n//       p6.x = _x_orig+_dx;\n//       p6.y = _y_orig;\n//       p6.z = _z_orig + _dz;\n//       p7.x = _x_orig+_dx;\n//       p7.y = _y_orig+_dy;\n//       p7.z = _z_orig + _dz;\n//       p8.x = _x_orig;\n//       p8.y = _y_orig+_dy;\n//       p8.z = _z_orig + _dz;\n//       cloudOut->push_back(p1);\n//       cloudOut->push_back(p2);\n//       cloudOut->push_back(p3);\n//       cloudOut->push_back(p4);\n//       cloudOut->push_back(p5);\n//       cloudOut->push_back(p6);\n//       cloudOut->push_back(p7);\n//       cloudOut->push_back(p8);\n      \n      return cloudOut;\n    }\n    \n    inline int getSize(){return _my_pts.size();}\n    \n    inline double getDensity()\n    {\n      return ((double)_my_pts.size())/((_dx*_dy*_dz)/(_my_cube->getE3()));\n    }\n    \n    inline CCluster splitMe()\n    {\n      CCluster newClust(_my_cube);\n      CCluster backFillClust(_my_cube);\n      \n      std::vector<long>::iterator cIt;\n      long ix,iy,iz;\n      long z;\n      long hitCount,lastHitCount = -1;\n      double lastDens = 0;\n      \n      cout << \"Trying to split\" << endl;\n      \n      for (iz=0;iz<_my_cube->getZCount();iz++)\n      {\n\t/*hitCount = 0;\n\tfor (ix=0;ix<_my_cube->getXCount();ix++)\n\t{\n\t  for (iy=0;iy<_my_cube->getYCount();iy++)\n\t  {\n\t    if (_my_cube->isFilledIdx(_my_cube->toIdx(ix,iy,iz)))\n\t    {\n\t      hitCount++;\n\t    }\n\t  }\n\t}*/\n\t\n\tfor (cIt = _my_pts.begin();cIt < _my_pts.end();\n\t      cIt++)\n\t{\n\t  z = (*cIt)/_my_cube->getXCount()/_my_cube->getYCount();\n\t  if (z == iz)\n\t  {\n\t    newClust.addIdx(*cIt);\n\t  }\n\t}\n\tif (iz > 1)\n\t{\n\t  newClust.calcDimensions();\n\t  if (lastDens > 0 && newClust.getDensity() < lastDens)\n\t  {\n\t    break;\n\t  }\n\t  lastDens = newClust.getDensity();\n\t}\n      }\n      \n      newClust._my_pts.clear();\n      if (iz < _my_cube->getZCount())\n      {\n\tfor (cIt = _my_pts.begin();cIt < _my_pts.end();\n\t      cIt++)\n\t{\n\t  z = (*cIt)/_my_cube->getXCount()/_my_cube->getYCount();\n\t  if (z < iz)\n\t  {\n\t    newClust.addIdx(*cIt);\n\t  }\n\t  else\n\t  {\n\t    backFillClust.addIdx(*cIt);\n\t  }\n\t}\n\t_my_pts.clear();\n\tfor (cIt = backFillClust._my_pts.begin();cIt < backFillClust._my_pts.end();\n\t      cIt++)\n\t{\n\t  addIdx(*cIt);\n\t}\n\tbackFillClust._my_pts.clear();\n      }\n      \n      return newClust;\n    }\n    \n    inline double getXMin(){return _x_orig;}\n    inline double getYMin(){return _y_orig;}\n    inline double getZMin(){return _z_orig;}\n    inline double getXMax(){return _x_orig+_dx;}\n    inline double getYMax(){return _y_orig+_dy;}\n    inline double getZMax(){return _z_orig+_dz;}\n    inline double getDX(){return _dx;}\n    inline double getDY(){return _dy;}\n    inline double getDZ(){return _dz;}\n    \n    inline std::vector<long> *getIdxs(){return &_my_pts;}\n    \n  private:\n    std::vector<long> _my_pts;\n    CubeAligner *_my_cube;\n    double _x_orig;\n    double _y_orig;\n    double _z_orig;\n    double _dx;\n    double _dy;\n    double _dz;\n  };\n  \n  inline double getE3(){return _e*_e*_e;}\n  \n  inline void removeCluster(CCluster *cluster)\n  {\n    std::vector<long>::iterator clustIter;\n    long idx,arrIdx;\n    int bitIdx;\n    \n    for (clustIter = cluster->getIdxs()->begin();\n\t clustIter < cluster->getIdxs()->end();\n\t clustIter++)\n    {\n      idx = *clustIter;\n    \n      arrIdx = idx/8;\n      bitIdx = idx%8;\n      _vBase[arrIdx] ^= (0x80 >> bitIdx);\n    }\n    \n    return;\n  }\n  \n  inline void identifyClusters()\n  {\n    long ix,iy,iz,idx;\n    std::vector<CCluster>::iterator clustIter;\n    \n    _clusters.clear();\n    \n    for (iz=0;iz<(-_min_z)/_e;iz++)\n    {\n      for (ix=0;ix<_xCount;ix++)\n      {\n\tfor (iy=0;iy<_yCount;iy++)\n\t{\n\t  idx = toIdx(ix,iy,iz);\n\t  if ( isFilledIdx(idx) )\n\t  {\n\t    bool found = false;\n\t    for (clustIter = _clusters.begin(); clustIter < _clusters.end();\n\t\t clustIter++)\n\t    {\n\t      if ((*clustIter).includes(idx))\n\t      {\n\t\tfound = true;\n\t\tbreak;\n\t      }\n\t    }\n\t    if (found)\n\t    {\n\t      continue;\n\t    }\n\t    CCluster newClust((CubeAligner*)this);\n\t    //growClusterRadial(idx,idx,&newClust);\n\t    growCluster(idx,&newClust);\n\t    if (newClust.getSize() > 25)\n\t    {\n\t      newClust.calcDimensions();\n\t      _clusters.push_back(newClust);\n\t    }\n\t  }\n\t}\n      }\n    }\n    \n    splitClusters();\n    \n    return;\n    \n    for (clustIter = _clusters.begin(); clustIter < _clusters.end();\n\t  clustIter++)\n    {\n      //if ((*clustIter).getZMin() < 0)\n      //{\n\tremoveCluster(&(*clustIter));\n      //}\n    }\n    \n    _clusters.clear();\n    \n    for (ix=0;ix<_xCount;ix++)\n    {\n      for (iy=0;iy<_yCount;iy++)\n      {\n\tfor (iz=0;iz<_zCount;iz++)\n\t{\n\t  idx = toIdx(ix,iy,iz);\n\t  if ( isFilledIdx(idx) )\n\t  {\n\t    bool found = false;\n\t    for (clustIter = _clusters.begin(); clustIter < _clusters.end();\n\t\t clustIter++)\n\t    {\n\t      if ((*clustIter).includes(idx))\n\t      {\n\t\tfound = true;\n\t\tbreak;\n\t      }\n\t    }\n\t    if (found)\n\t    {\n\t      continue;\n\t    }\n\t    CCluster newClust((CubeAligner*)this);\n\t    growCluster(idx,&newClust);\n\t    if (newClust.getSize() > 20)\n\t    {\n\t      newClust.calcDimensions();\n\t      //cout << \"Added Cluster -> size = \" << newClust.getSize() << endl;\n\t      found = false;\n\t      for (clustIter = _clusters.begin(); clustIter < _clusters.end();\n\t\t  clustIter++)\n\t      {\n\t\tif (\n\t\t  (*clustIter).getDensity() < newClust.getDensity() )\n\t\t{\n\t\t  _clusters.insert(clustIter,newClust);\n\t\t  found = true;\n\t\t  break;\n\t\t}\n\t      }\n\t      if (!found)\n\t      {\n\t\t_clusters.push_back(newClust);\n\t      }\n\t    }\n\t  }\n\t}\n      }\n    }\n    \n    cout << \"Found \" << _clusters.size() << \" Clusters\" << endl;\n    \n    return;\n  }\n  \n  inline std::vector<CCluster> *getClusters()\n  {\n    return &_clusters;\n  }\n  \n  inline void splitClusters()\n  {\n    std::vector<CCluster>::iterator clustIter;\n    for (clustIter = _clusters.begin(); clustIter < _clusters.end();\n\tclustIter++)\n    {\n      if ((*clustIter).getDensity() < MIN_CLUSTER_DENS )\n      {\n\t_clusters.push_back((*clustIter).splitMe());\n      }\n    }\n    \n    return;\n  }\n  \n  inline void growClusterRadial(long startIdx, long thisIdx, CCluster *clust)\n  {\n    long ix,iy,iz,ix2,iy2,iz2;\n    int dx,dy,dz;\n    long newIdx;\n    bool isThisFilled;\n    \n    ix = startIdx%_xCount;\n    iy = (startIdx/_xCount)%_yCount;\n    iz = startIdx/_xCount/_yCount;\n    \n    isThisFilled = isFilledIdx(thisIdx);\n    if (isThisFilled)\n    {\n      if (!clust->includes(thisIdx))\n      {\n\tclust->addIdx(thisIdx);\n      }\n      else\n      {\n\treturn;\n      }\n    }\n    \n    if (startIdx==thisIdx)\n    {\n      for (dx=-1;dx<=1;dx++)\n      {\n\tfor (dy=-1;dy<=1;dy++)\n\t{\n\t  if (!dx && !dy){continue;}\n\t  newIdx = toIdx(ix+dx,iy+dy,iz);\n\t  if (newIdx >=  0)\n\t    growClusterRadial(startIdx,newIdx,clust);\n\t}\n      }\n    }\n    else\n    {\n      ix2 = thisIdx%_xCount;\n      iy2 = (thisIdx/_xCount)%_yCount;\n      iz2 = thisIdx/_xCount/_yCount;\n      dx = ix2-ix;\n      dy = iy2-iy;\n      \n      //cout << \"checking \" << ix2<<\",\"<<iy2<<\",\"<<iz2<<endl;\n      //cout << \"ctr = \" << ix<<\",\"<<iy<<\",\"<<iz<<endl;\n      \n      if (dx)\n      {\n\tnewIdx = toIdx(ix2+(dx<0?-1:1),iy2,iz2);\n\tif ( newIdx >= 0 && (isFilledIdx(newIdx) || isThisFilled))\n\t  growClusterRadial(startIdx,newIdx,clust);\n\t/*if (!isFilledIdx(newIdx) && isThisFilled)\n\t{\n\t  newIdx = toIdx(ix2+(dx<0?-1:1),iy2,iz2+1);\n\t  if (isFilledIdx(newIdx) && !clust->includes(newIdx))\n\t    growClusterRadial(startIdx,newIdx,clust);\n\t  newIdx = toIdx(ix2+(dx<0?-1:1),iy2,iz2-1);\n\t  if (isFilledIdx(newIdx) && !clust->includes(newIdx))\n\t    growClusterRadial(startIdx,newIdx,clust);\n\t}*/\n      }\n      if (dy)\n      {\n\tnewIdx = toIdx(ix2,iy2+(dy<0?-1:1),iz2);\n\tif ( newIdx >= 0 && (isFilledIdx(newIdx) || isThisFilled))\n\t  growClusterRadial(startIdx,newIdx,clust);\n\t/*if (!isFilledIdx(newIdx) & isThisFilled)\n\t{\n\t  newIdx = toIdx(ix2,iy2+(dy<0?-1:1),iz2+1);\n\t  if (isFilledIdx(newIdx) && !clust->includes(newIdx))\n\t    growClusterRadial(startIdx,newIdx,clust);\n\t  newIdx = toIdx(ix2,iy2+(dy<0?-1:1),iz2-1);\n\t  if (isFilledIdx(newIdx) && !clust->includes(newIdx))\n\t    growClusterRadial(startIdx,newIdx,clust);\n\t}*/\n      }\n      if (dx && dy)\n      {\n\tnewIdx = toIdx(ix2+(dx<0?-1:1),iy2+(dy<0?-1:1),iz2);\n\tif ( newIdx >= 0 && (isFilledIdx(newIdx) || isThisFilled))\n\t  growClusterRadial(startIdx,newIdx,clust);\n      }\n    }\n    \n    return;\n  }\n  \n  inline void growCluster(long startIdx, CCluster *clust)\n  {\n    long ix,iy,iz,idx;\n    ix = startIdx%_xCount;\n    iy = (startIdx/_xCount)%_yCount;\n    iz = startIdx/_xCount/_yCount;\n    int offset;\n    \n    clust->addIdx(startIdx);\n    \n    for (offset = -1; offset <= 1; offset += 2)\n    {\n      idx = toIdx(ix,iy+offset,iz);\n      if (idx >= 0 && isFilledIdx(idx) && !clust->includes(idx))\n      {\n\tgrowCluster(idx,clust);\n      }\n      else if ((idx = toIdx(ix,iy+offset*2,iz)) >= 0 && isFilledIdx(idx) &&\n\t!clust->includes(idx))\n      {\n\tgrowCluster(idx,clust);\n      }\n      \n      idx = toIdx(ix,iy,iz+offset);\n      if (idx >= 0 && isFilledIdx(idx) && !clust->includes(idx))\n      {\n\tgrowCluster(idx,clust);\n      }\n      else if ( (idx = toIdx(ix,iy,iz+offset*2)) >= 0 && isFilledIdx(idx) &&\n      !clust->includes(idx))\n      {\n      growCluster(idx,clust);\n      }\n      \n      //if (abs(ixStart - (ix+offset)) <= 3)\n      //{\n      idx = toIdx(ix+offset,iy,iz);\n      if (idx >= 0 && isFilledIdx(idx) && !clust->includes(idx))\n      {\n\tgrowCluster(idx,clust);\n      }\n      else if ((idx = toIdx(ix+offset*2,iy,iz)) >= 0 && isFilledIdx(idx) &&\n\t!clust->includes(idx))\n      {\n\tgrowCluster(idx,clust);\n      }\n      //}\n    }\n    \n    return;\n  }\n  \n  inline void filterCloudCubic(CloudPtr cloud)\n  {\n    CloudItr npIt = cloud->begin();\n    CloudPtr cloud2(new Cloud);\n    ExtractIndices<PointXYZI> iextract(false);\n    boost::shared_ptr<vector<int> > removeIndices(new vector<int>);\n    long ix,iy,iz;\n    int bitIdx;\n    long long idx;\n    size_t arrIdx;\n    int i=0;\n    int dropCount=0;\n    \n    removeIndices->reserve(cloud->size());\n    \n    while (npIt<cloud->end())\n    {\n      ix = ((*npIt).x-_min_x)/_e;\n      iy = ((*npIt).y-_min_y)/_e;\n      iz = ((*npIt).z-_min_z)/_e;\n      \n      if (isFilledIdx(toIdx(ix,iy,iz)))\n      {\n\tremoveIndices->push_back(i);\n\tdropCount++;\n      }\n      \n      npIt++;\n      i++;\n    }\n    //cout << \"before \" << cloud->size();\n    iextract.setInputCloud(cloud);\n    iextract.setNegative(true);\n    iextract.setIndices(removeIndices);\n    iextract.filter(*cloud2);\n    cloud->swap(*cloud2);\n    //cout << \"after \" << cloud->size() << endl;\n\n    //cout << \"Dropped \" << dropCount << \" non cubic points\" << endl;\n    return;\n  }\n  \n  inline Eigen::Matrix4f alignToMatrix(Eigen::Matrix4f mat, CloudPtr cloud,\n    double *eVal)\n  {\n    CloudPtr transCloud;\n    CVertex x0;\n    CVertex xr;\n    CVertex xe;\n    CVertex vertArr[V_CT];\n    int i,j;\n    int lCount=0;\n    int cubeCount;\n    int loopCount = 0;\n    unsigned char *vArr;\n    vArr = (unsigned char *)malloc(arraySizeNeeded());\n    //try an initial offset in the direction of carts motion...\n    CVertex v0(mat);\n    double newScore;\n    int didReduct;\n    \n    \n    while(1)\n    {\n      loopCount++;\n      for (i=0;i<V_CT;i++)\n      {\n\tvertArr[i] = CVertex(i,*eVal,v0);\n\ttransCloud = CloudPtr(new Cloud);\n\ttransformPointCloud(*cloud,*transCloud,vertArr[i].toTranslation());\n\tmemset(vArr,0,arraySizeNeeded());\n\tif (i==0){\n\t  cubeCount = cloudToArray(transCloud,vArr);\n\t}\n\telse\n\t{\n\t  cloudToArray(transCloud,vArr);\n\t}\n  \n\tvertArr[i].setScore(getHitCount(vArr));\n      }\n      qsort(vertArr,V_CT,sizeof(CVertex),CVertex::sorter);\n      didReduct = 0;\n      \n      while (1)\n      {\n  \n\t/*for (i=0;i<V_CT;i++)\n\t{\n\t  printf(\"%d,\",vertArr[i].getScore());\n\t}\n\tprintf(\"\\n\");*/\n\tfor (i=0;i<V_CT;i++)\n\t{\n\t  //printf(\"%d,\",vertArr[i].getScore());\n\t}\n\t//printf(\"\\n\");\n\t\n\t//calculate center of mass and reflection point\n\tx0 = CVertex(vertArr,V_CT-1);\n\txr = x0 + ALPHA*(x0-vertArr[V_CT-1]);\n\t\n\t//calculate reflection points score\n\ttransCloud = CloudPtr(new Cloud);\n\ttransformPointCloud(*cloud,*transCloud,xr.toTranslation());\n\tmemset(vArr,0,arraySizeNeeded());\n\tcloudToArray(transCloud,vArr);\n\txr.setScore(getHitCount(vArr));\n\t\n\tfor (i=0;i<V_CT;i++)\n\t{\n\t  if (xr.getScore() > vertArr[i].getScore())\n\t  {\n\t    break;\n\t  }\n\t}\n\t\n\t//replace the worst point with reflected and continue\n\tif ((i > 0 && i < V_CT-1) || xr.getScore() == vertArr[0].getScore())\n\t{\n\t  vertArr[V_CT-1] = xr;\n\t}\n\telse if (i==0)\n\t{\n\t  xe = x0 + BETA*(xr-x0);\n\t  //calculate expansion points score\n\t  transCloud = CloudPtr(new Cloud);\n\t  transformPointCloud(*cloud,*transCloud,xe.toTranslation());\n\t  memset(vArr,0,arraySizeNeeded());\n\t  cloudToArray(transCloud,vArr);\n\t  xe.setScore(getHitCount(vArr));\n\t  if (xe.getScore() > xr.getScore())\n\t  {\n\t    vertArr[V_CT-1] = xe;\n\t  }\n\t  else\n\t  {\n\t    vertArr[V_CT-1] = xr;\n\t  }\n\t}\n\telse if (i == (V_CT - 1))\n\t{\n\t  //outside contraction\n\t  xe = x0 + GAMMA*(vertArr[V_CT-1]-x0);\n\t  transCloud = CloudPtr(new Cloud);\n\t  transformPointCloud(*cloud,*transCloud,xe.toTranslation());\n\t  memset(vArr,0,arraySizeNeeded());\n\t  cloudToArray(transCloud,vArr);\n\t  xe.setScore(getHitCount(vArr));\n\t  if (xe.getScore()  > xr.getScore())\n\t  {\n\t    vertArr[V_CT-1] = xe;\n\t  }\n\t  else\n\t  {\n\t    i=-1;\n\t  }\n\t}\n\telse\n\t{\n\t  //inside contraction\n\t  xe = x0 - GAMMA*(vertArr[V_CT-1]-x0);\n\t  transCloud = CloudPtr(new Cloud);\n\t  transformPointCloud(*cloud,*transCloud,xe.toTranslation());\n\t  memset(vArr,0,arraySizeNeeded());\n\t  cloudToArray(transCloud,vArr);\n\t  xe.setScore(getHitCount(vArr));\n\t  if (xe.getScore()  > xr.getScore())\n\t  {\n\t    vertArr[V_CT-1] = xe;\n\t  }\n\t  else\n\t  {\n\t    i=-1;\n\t  }\n\t}\n\t\n\tif (i == -1)\n\t{\n\t  //reduction\n\t  if (didReduct == 5)\n\t  {\n\t    lCount = CUBE_MAX_ITER;\n\t  }\n\t  else\n\t  {\n\t    //reduce\n\t    for (i=1;i<V_CT;i++)\n\t    {\n\t      vertArr[i] = vertArr[0] + DELTA*(vertArr[i]-vertArr[0]);\n\t      transCloud = CloudPtr(new Cloud);\n\t      transformPointCloud(*cloud,*transCloud,vertArr[i].toTranslation());\n\t      memset(vArr,0,arraySizeNeeded());\n\t      cloudToArray(transCloud,vArr);\n\t      vertArr[i].setScore(getHitCount(vArr));\n\t    }\n\n\t    //cout << \"REDUCED...\";\n\t    didReduct++;\n\t  }\n\t}\n\t\n\tnewScore = vertArr[V_CT-1].getScore();\n\t//printf(\"Next score = %d\\n\",vertArr[V_CT-1].getScore());\n\t\n\tqsort(vertArr,V_CT,sizeof(CVertex),CVertex::sorter);\n\tif (didReduct && i == V_CT)\n\t{\n\t  //dont quit early from std dev right after a reduction\n\t  newScore = vertArr[0].getScore();\n\t}\n\t\n\t//terminate the loop\n\tif (++lCount > CUBE_MAX_ITER)\n\t{\n\t  break;\n\t}\n\tif (newScore != vertArr[0].getScore() && \n\t  getStdDev(vertArr,V_CT) < (vertArr[0].getScore()*.01))\n\t{\n\t  break;\n\t}\n      }\n      \n      /*cout << \"TESTING 123 \" << loopCount << endl << endl << endl;\n      \n      //check the distance to the new and restart maybe??\n      if (loopCount <= 3 && vertArr[0].getScore() < cubeCount*0.2)\n      {\n\tlCount = 0;\n\tv0 = vertArr[0];\n      }\n      else\n      {*/\n\tbreak;\n      //}\n    }\n    \n    x0 = vertArr[0];\n    \n    /*newScore = x0.getScore();\n    for (j=0;j<10;j++)\n    {\n      lCount = 0;\n      for (i=0;i<V_CT;i++)\n      {\n\txe = CVertex(i,E_VAL/100.0,x0);\n\ttransCloud = CloudPtr(new Cloud);\n\ttransformPointCloud(*cloud,*transCloud,xe.toTranslation());\n\tmemset(vArr,0,arraySizeNeeded());\n\tcloudToArray(transCloud,vArr);\n\txe.setScore(getHitCount(vArr));\n\tif (xe.getScore() > newScore)\n\t{\n\t  lCount = i;\n\t  newScore = xe.getScore();\n\t  xr = xe;\n\t}\n\tcout << \"Offset \" << i << \" = \" << xe.getScore() << endl;\n      }\n      if (lCount == 0)\n      {\n\tbreak;\n      }\n      else\n      {\n\tx0=xr;\n      }\n    }*/\n    \n    //E_VAL = ( E_VAL + x0.getMaxDiff(v0)*2 )/2.0;\n    //if (E_VAL<0.05)E_VAL = 0.05;\n    \n    //*eVal = (*eVal + v0.getMaxDiff(x0))*0.5;\n    //if (*eVal<0.01) *eVal = 0.01;\n   \n    //cout << \"New E_VAL = \" << *eVal << endl;\n    //cout << \"Starting point found:\" << endl << v0 << endl;\n    //cout << \"Best trans = \" << x0 << endl;\n    \n#ifdef ADAPT_SIMPLEX\n    //cout << \"ADAPTING!!>>!!!!!\" << endl;\n#endif\n    \n    free(vArr);\n    \n    return x0.toTranslation();\n  }\n  \n  inline double getNextEval(Eigen::Matrix4f *guess, Eigen::Matrix4f *align)\n  {\n    CVertex c1(*guess);\n    CVertex c2(*align);\n    \n    return c1.getMaxDiff(c2);\n  }\n  \n  inline int getXCount(){return _xCount;}\n  inline int getYCount(){return _yCount;}\n  inline int getZCount(){return _zCount;}\n  \nprivate:\n  \n  inline CVertex findStartingPoint(CloudPtr cloud, double minX,\n    double maxX, double minY, double maxY, double minZ, double maxZ,\n    double stepSize)\n  {\n    CVertex best;\n    CVertex test;\n    CloudPtr transCloud;\n    double x,y,z;\n    unsigned char *vArr;\n    vArr = (unsigned char *)malloc(arraySizeNeeded());\n    \n    best.setScore(0);\n    \n    for (x = minX;x<=maxX;x+=stepSize)\n    {\n      for (y = minY;y<=maxY;y+=stepSize)\n      {\n\tfor (z = minZ; z <= maxZ; z+=stepSize)\n\t{\n\t  test = CVertex(0,0,0,x,y,z);\n\t  cout << \"testing \" << test <<\"...\" << endl;\n\t  transCloud = CloudPtr(new Cloud);\n\t  transformPointCloud(*cloud,*transCloud,test.toTranslation());\n\t  memset(vArr,0,arraySizeNeeded());\n\t  cloudToArray(transCloud,vArr);\n\t  test.setScore(getHitCount(vArr));\n\t  if (test.getScore() > best.getScore())\n\t  {\n\t    best = test;\n\t  }\n\t}\n      }\n    }\n    \n    free(vArr);\n    return best;\n  }\n  \n  inline int getHitCount(unsigned char *v2)\n  {\n    int count = 0;\n    int i,j;\n    int byteCount = arraySizeNeeded();\n    unsigned char cpByte;\n    \n    for (i=0;i<byteCount;i++)\n    {\n      cpByte = _vBase[i]&v2[i];\n      for (j=0;j<8;j++)\n      {\n\tcount += ((cpByte >> j) & 0x01);\n      }\n    }\n    \n    return count;\n  }\n  \n  inline bool isFilledIdx(long idx)\n  {\n    long arrIdx;\n    int bitIdx;\n    \n    //catch out of range from toIdx()\n    if (idx==-1)\n    {\n      return false;\n    }\n    \n    arrIdx = idx/8;\n    bitIdx = idx%8;\n    return (_vBase[arrIdx] & (0x80 >> bitIdx) );\n  }\n    \n  \n  inline double getStdDev(CVertex *vertArr, int count)\n  {\n    double mean=0;\n    double stdDev=0;\n    int i;\n    for (i=0;i<count;i++)\n    {\n      mean += vertArr[i].getScore();\n    }\n    mean /= count;\n    \n    for (i=0;i<count;i++)\n    {\n      stdDev += pow(vertArr[i].getScore()-mean,2.0)/(count-1);\n    }\n    \n    stdDev = sqrt(stdDev);\n    //printf(\"Std dev = %.2f\\n\",stdDev);\n    return stdDev;\n  }\n  \n  std::vector<CCluster> _clusters;\n  double _min_x;\n  double _max_x;\n  double _min_y;\n  double _max_y;\n  double _min_z;\n  double _max_z;\n  double _e;\n  long _xCount;\n  long _yCount;\n  long _zCount;\n  size_t _arrSz;\n  unsigned char* _vBase;\n};\n\n\n\n\n#endif\n", "meta": {"hexsha": "0e2cc8f0966a478083bcb926fa973b9b43627bd9", "size": 31494, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "CubeAligner.hpp", "max_stars_repo_name": "jmlien/mapgmu", "max_stars_repo_head_hexsha": "b4b5eb42e876530e52217191d7980720302522d0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "CubeAligner.hpp", "max_issues_repo_name": "jmlien/mapgmu", "max_issues_repo_head_hexsha": "b4b5eb42e876530e52217191d7980720302522d0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "CubeAligner.hpp", "max_forks_repo_name": "jmlien/mapgmu", "max_forks_repo_head_hexsha": "b4b5eb42e876530e52217191d7980720302522d0", "max_forks_repo_licenses": ["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.7607119314, "max_line_length": 139, "alphanum_fraction": 0.5487394424, "num_tokens": 10463, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6513548646660542, "lm_q2_score": 0.5, "lm_q1q2_score": 0.3256774323330271}}
{"text": "#pragma once\n\n#include \"conditionals.hpp\"\n\n#include <vector>\n#include <boost/math/distributions/gamma.hpp>\n\nnamespace lorad {\n\n    class ASRV {\n\n        public:\n#if defined(POLGSS)\n#if defined(HOLDER_ETAL_PRIOR)\n            typedef std::vector<double>                 shape_refdist_t;\n            typedef std::shared_ptr<shape_refdist_t>    shape_refdist_ptr_t;\n#else\n            typedef std::vector<double>                 ratevar_refdist_t;\n            typedef std::shared_ptr<ratevar_refdist_t>  ratevar_refdist_ptr_t;\n#endif\n            typedef std::vector<double>                 pinvar_refdist_t;\n            typedef std::shared_ptr<pinvar_refdist_t>   pinvar_refdist_ptr_t;\n#endif\n\n            typedef std::vector<double>                 rate_prob_t;\n            typedef std::shared_ptr<double>             relrate_ptr_t;\n#if defined(HOLDER_ETAL_PRIOR)\n            typedef std::shared_ptr<double>             shape_ptr_t;\n#else\n            typedef std::shared_ptr<double>             ratevar_ptr_t;\n#endif\n            typedef std::shared_ptr<double>             pinvar_ptr_t;\n            typedef std::shared_ptr<ASRV>               SharedPtr;\n        \n                                                ASRV();\n            virtual                             ~ASRV();\n        \n            void                                clear();\n        \n            void                                setNumCateg(unsigned ncateg);\n            unsigned                            getNumCateg() const;\n\n#if defined(HOLDER_ETAL_PRIOR)\n            void                                setShapeSharedPtr(shape_ptr_t shape);\n            void                                setShape(double v);\n            const shape_ptr_t                   getShapeSharedPtr() const;\n            double                              getShape() const;\n            void                                fixShape(bool is_fixed);\n            bool                                isFixedShape() const;\n#else\n            void                                setRateVarSharedPtr(ratevar_ptr_t ratevar);\n            void                                setRateVar(double v);\n            const ratevar_ptr_t                 getRateVarSharedPtr() const;\n            double                              getRateVar() const;\n            void                                fixRateVar(bool is_fixed);\n            bool                                isFixedRateVar() const;\n#endif\n\n            void                                setPinvarSharedPtr(pinvar_ptr_t pinvar);\n            void                                setPinvar(double p);\n            const pinvar_ptr_t                  getPinvarSharedPtr() const;\n            double                              getPinvar() const;\n            void                                fixPinvar(bool is_fixed);\n            bool                                isFixedPinvar() const;\n\n#if defined(POLGSS)\n#if defined(HOLDER_ETAL_PRIOR)\n            void                                setShapeRefDistParamsSharedPtr(shape_refdist_ptr_t shape_refdist_ptr);\n            std::vector<double>                 getShapeRefDistParamsVect() const;\n#else\n            void                                setRateVarRefDistParamsSharedPtr(ratevar_refdist_ptr_t ratevar_refdist_ptr);\n            std::vector<double>                 getRateVarRefDistParamsVect() const;\n#endif\n            void                                setPinvarRefDistParamsSharedPtr(pinvar_refdist_ptr_t pinvar_refdist_ptr);\n            std::vector<double>                 getPinvarRefDistParamsVect() const;\n#endif\n\n            void                                setIsInvarModel(bool is_invar_model);\n            bool                                getIsInvarModel() const;\n\n            const double *                      getRates() const;\n            const double *                      getProbs() const;\n\n        private:\n        \n            virtual void                        recalcASRV();\n\n            unsigned                            _num_categ;\n            bool                                _invar_model;\n        \n#if defined(HOLDER_ETAL_PRIOR)\n            bool                                _shape_fixed;\n            shape_ptr_t                         _shape;\n#else\n            bool                                _ratevar_fixed;\n            ratevar_ptr_t                       _ratevar;\n#endif\n            pinvar_ptr_t                        _pinvar;\n        \n            bool                                _pinvar_fixed;\n        \n            rate_prob_t                         _rates;\n            rate_prob_t                         _probs;\n#if defined(POLGSS)\n#if defined(HOLDER_ETAL_PRIOR)\n            shape_refdist_ptr_t                 _shape_refdist;\n#else\n            ratevar_refdist_ptr_t               _ratevar_refdist;\n#endif\n            pinvar_refdist_ptr_t                _pinvar_refdist;\n#endif\n    };\n    \n    inline ASRV::ASRV() {\n        clear();\n    }\n\n    inline ASRV::~ASRV() {\n    }\n\n    inline void ASRV::clear() {\n        // Rate homogeneity is the default\n        _invar_model = false;\n#if defined(HOLDER_ETAL_PRIOR)\n        _shape_fixed = false;\n        _shape = std::make_shared<double>(1.0);\n#else\n        _ratevar_fixed = false;\n        _ratevar = std::make_shared<double>(1.0);\n#endif\n        _pinvar_fixed = false;\n        _pinvar = std::make_shared<double>(0.0);\n        _num_categ = 1;\n#if defined(POLGSS)\n#if defined(HOLDER_ETAL_PRIOR)\n        ASRV::shape_refdist_t tmp = {1.0, 1.0};\n        _shape_refdist = std::make_shared<ASRV::shape_refdist_t>(tmp);\n#else\n        ASRV::ratevar_refdist_t tmp = {1.0, 1.0};\n        _ratevar_refdist = std::make_shared<ASRV::ratevar_refdist_t>(tmp);\n#endif\n        ASRV::pinvar_refdist_t tmp2 = {1.0, 1.0};\n        _pinvar_refdist = std::make_shared<ASRV::pinvar_refdist_t>(tmp2);\n#endif\n        recalcASRV();\n    }\n\n#if defined(HOLDER_ETAL_PRIOR)\n    inline const ASRV::shape_ptr_t ASRV::getShapeSharedPtr() const {\n        return _shape;\n    }\n\n    inline double ASRV::getShape() const {\n        assert(_shape);\n        return *_shape;\n    }\n    \n    inline void ASRV::setShapeSharedPtr(shape_ptr_t shape) {\n        _shape = shape;\n        recalcASRV();\n    }\n    \n    inline void ASRV::setShape(double v) {\n        *_shape = v;\n        recalcASRV();\n    }\n    \n    inline void ASRV::fixShape(bool is_fixed) {\n        _shape_fixed = is_fixed;\n    }\n\n    inline bool ASRV::isFixedShape() const {\n        return _shape_fixed;\n    }\n#else\n    inline const ASRV::ratevar_ptr_t ASRV::getRateVarSharedPtr() const {\n        return _ratevar;\n    }\n\n    inline double ASRV::getRateVar() const {\n        assert(_ratevar);\n        return *_ratevar;\n    }\n    \n    inline void ASRV::setRateVarSharedPtr(ratevar_ptr_t ratevar) {\n        _ratevar = ratevar;\n        recalcASRV();\n    }\n    \n    inline void ASRV::setRateVar(double v) {\n        *_ratevar = v;\n        recalcASRV();\n    }\n    \n    inline void ASRV::fixRateVar(bool is_fixed) {\n        _ratevar_fixed = is_fixed;\n    }\n\n    inline bool ASRV::isFixedRateVar() const {\n        return _ratevar_fixed;\n    }\n#endif\n\n    inline const ASRV::pinvar_ptr_t ASRV::getPinvarSharedPtr() const {\n        return _pinvar;\n    }\n\n    inline double ASRV::getPinvar() const {\n        assert(_pinvar);\n        return *_pinvar;\n    }\n\n    inline const double * ASRV::getRates() const {\n        return &_rates[0];\n    }\n\n    inline const double * ASRV::getProbs() const {\n        return &_probs[0];\n    }\n\n    inline bool ASRV::getIsInvarModel() const {\n        return _invar_model;\n    }\n\n    inline unsigned ASRV::getNumCateg() const {\n        return _num_categ;\n    }\n    \n    inline void ASRV::setNumCateg(unsigned ncateg) {\n        _num_categ = ncateg;\n        recalcASRV();\n    }\n    \n    inline void ASRV::setPinvarSharedPtr(pinvar_ptr_t pinvar) {\n        _pinvar = pinvar;\n        recalcASRV();\n    }\n    \n    inline void ASRV::setPinvar(double p) {\n        *_pinvar = p;\n        recalcASRV();\n    }\n    \n    inline void ASRV::setIsInvarModel(bool is_invar_model) {\n        _invar_model = is_invar_model;\n        recalcASRV();\n    }\n\n    inline void ASRV::fixPinvar(bool is_fixed) {\n        _pinvar_fixed = is_fixed;\n    }\n\n    inline bool ASRV::isFixedPinvar() const {\n        return _pinvar_fixed;\n    }\n    \n    inline void ASRV::recalcASRV() {\n        // This implementation assumes discrete gamma among-site rate heterogeneity\n        // using a _num_categ category discrete gamma distribution with equal category\n        // probabilities and Gamma density with mean 1.0 and variance _rate_var.\n        // If _invar_model is true, then rate probs will sum to 1 - _pinvar rather than 1\n        // and the mean rate will be 1/(1 - _pinvar) rather than 1; the rest of the invariable\n        // sites component of the model is handled outside the ASRV class.\n        \n        // _num_categ, _rate_var, and _pinvar must all have been assigned in order to compute rates and probs\n#if defined(HOLDER_ETAL_PRIOR)\n        if ( (!_shape) || (!_num_categ) || (!_pinvar) )\n            return;\n#else\n        if ( (!_ratevar) || (!_num_categ) || (!_pinvar) )\n            return;\n#endif\n        \n        double pinvar = *_pinvar;\n        assert(pinvar >= 0.0);\n        assert(pinvar <  1.0);\n\n        assert(_num_categ > 0);\n\n        double equal_prob = 1.0/_num_categ;\n        double mean_rate_variable_sites = 1.0;\n        if (_invar_model)\n            mean_rate_variable_sites /= (1.0 - pinvar);\n        \n        _rates.assign(_num_categ, mean_rate_variable_sites);\n        _probs.assign(_num_categ, equal_prob);\n\n#if defined(HOLDER_ETAL_PRIOR)\n        double gamma_shape = *_shape;\n        assert(gamma_shape >= 0.0);\n        \n        if (_num_categ == 1 || gamma_shape > 1000.0)\n            return;\n\n        double alpha = gamma_shape;\n        double beta = 1.0/gamma_shape;\n#else\n        double rate_variance = *_ratevar;\n        assert(rate_variance >= 0.0);\n        \n        if (_num_categ == 1 || rate_variance == 0.0)\n            return;\n\n        double alpha = 1.0/rate_variance;\n        double beta = rate_variance;\n#endif\n    \n        boost::math::gamma_distribution<> my_gamma(alpha, beta);\n        boost::math::gamma_distribution<> my_gamma_plus(alpha + 1.0, beta);\n\n        double cum_upper        = 0.0;\n        double cum_upper_plus   = 0.0;\n        double upper            = 0.0;\n        double cum_prob         = 0.0;\n        for (unsigned i = 1; i <= _num_categ; ++i) {\n            double cum_lower_plus       = cum_upper_plus;\n            double cum_lower            = cum_upper;\n            cum_prob                    += equal_prob;\n\n            if (i < _num_categ) {\n                upper                   = boost::math::quantile(my_gamma, cum_prob);\n                cum_upper_plus          = boost::math::cdf(my_gamma_plus, upper);\n                cum_upper               = boost::math::cdf(my_gamma, upper);\n            }\n            else {\n                cum_upper_plus          = 1.0;\n                cum_upper               = 1.0;\n            }\n\n            double numer                = cum_upper_plus - cum_lower_plus;\n            double denom                = cum_upper - cum_lower;\n            double r_mean               = (denom > 0.0 ? (alpha*beta*numer/denom) : 0.0);\n            _rates[i-1]        = r_mean*mean_rate_variable_sites;\n        }\n    }\n\n#if defined(POLGSS)\n#if defined(HOLDER_ETAL_PRIOR)\n    inline void ASRV::setShapeRefDistParamsSharedPtr(ASRV::shape_refdist_ptr_t shape_refdist_params_ptr) {\n        if (shape_refdist_params_ptr->size() != 2)\n            throw XLorad(boost::format(\"Expecting 2 shape reference distribution parameters and got %d\") % shape_refdist_params_ptr->size());\n        _shape_refdist = shape_refdist_params_ptr;\n    }\n    \n    inline std::vector<double> ASRV::getShapeRefDistParamsVect() const {\n        return std::vector<double>(_shape_refdist->begin(), _shape_refdist->end());\n    }\n#else\n    inline void ASRV::setRateVarRefDistParamsSharedPtr(ASRV::ratevar_refdist_ptr_t ratevar_refdist_params_ptr) {\n        if (ratevar_refdist_params_ptr->size() != 2)\n            throw XLorad(boost::format(\"Expecting 2 rate variance reference distribution parameters and got %d\") % ratevar_refdist_params_ptr->size());\n        _ratevar_refdist = ratevar_refdist_params_ptr;\n    }\n    \n    inline std::vector<double> ASRV::getRateVarRefDistParamsVect() const {\n        return std::vector<double>(_ratevar_refdist->begin(), _ratevar_refdist->end());\n    }\n#endif\n\n    inline void ASRV::setPinvarRefDistParamsSharedPtr(ASRV::pinvar_refdist_ptr_t pinvar_refdist_params_ptr) {\n        if (pinvar_refdist_params_ptr->size() != 2)\n            throw XLorad(boost::format(\"Expecting 2 pinvar reference distribution parameters and got %d\") % pinvar_refdist_params_ptr->size());\n        _pinvar_refdist = pinvar_refdist_params_ptr;\n    }\n    \n    inline std::vector<double> ASRV::getPinvarRefDistParamsVect() const {\n        return std::vector<double>(_pinvar_refdist->begin(), _pinvar_refdist->end());\n    }\n#endif\n}\n", "meta": {"hexsha": "c50edb6288ce45938cc29f298cd7113259e7d75a", "size": 13050, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/asrv.hpp", "max_stars_repo_name": "plewis/lorad", "max_stars_repo_head_hexsha": "bdc70e966e423e92aef66ef9d52220a5c241e6f3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-06-17T17:07:24.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-17T17:07:24.000Z", "max_issues_repo_path": "src/asrv.hpp", "max_issues_repo_name": "plewis/hpd-histogram", "max_issues_repo_head_hexsha": "4cc35206e0505127bffe9db6f650852f07bb7f63", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/asrv.hpp", "max_forks_repo_name": "plewis/hpd-histogram", "max_forks_repo_head_hexsha": "4cc35206e0505127bffe9db6f650852f07bb7f63", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.1752021563, "max_line_length": 151, "alphanum_fraction": 0.5475095785, "num_tokens": 2997, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6513548511303336, "lm_q2_score": 0.5, "lm_q1q2_score": 0.3256774255651668}}
{"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\n/**\n *  키를 생성하여 파일로 내보내는 모듈.\n *\n *  원래 RSA 방식과는 다르게 비밀키에서 공개키를 생성하는 구조임.\n *  공개키로 암호화를 하고, 비밀키로 복호화를 함.\n *\n *  키마다 txt파일(ascii)과 bin파일의 두 파일로 내보내짐\n *  공개키 : FHEcontext와 FHEPubKey 두 객체를 내보냄\n *  비밀키 : FHEcontext, FHESecKey, FHEPubKey 세 객체를 내보냄\n *\n */\nint main(int argc, char *argv[]) {\n\n    ArgMapping amap;\n\n    long r = 1;\n    long c = 2;\n    long w = 64;\n    long k = 80;\n    long d = 1;\n\n    long p = 257;\n    long L = 8;\n    string owner = \"owner\";\n    string dir = \"data\";\n\n    amap.arg(\"p\", p, \"plaintext base\");\n    amap.arg(\"L\", L, \"number of levels wanted\");\n    amap.arg(\"o\", owner, \"owner's address\");\n    amap.arg(\"dir\", dir, \"save directory\");\n    amap.parse(argc, argv);\n\n    // file names\n    const string secretKeyBinaryFile = dir + \"/secretKey/\" + owner + \".bin\";\n    const string publicKeyBinaryFile = dir + \"/publicKey/\" + owner + \".bin\";\n\n    ofstream secretBinFile(secretKeyBinaryFile.c_str(), ios::binary);\n    assert(secretBinFile.is_open());\n\n    ofstream publicBinFile(publicKeyBinaryFile.c_str(), ios::binary);\n    assert(publicBinFile.is_open());\n\n    // create context\n    long m = FindM(k, L, c, p, d, 0, 0);\n    std::unique_ptr<FHEcontext> context(new FHEcontext(m, p, r));\n    buildModChain(*context, L, c);  // Set the modulus chain\n\n    // create key\n    std::unique_ptr<FHESecKey> secKey(new FHESecKey(*context));\n    FHEPubKey *pubKey = (FHEPubKey *) secKey.get();\n    secKey->GenSecKey(w);\n    addSome1DMatrices(*secKey);\n    addFrbMatrices(*secKey);\n\n    // Secret Bin\n    cout << \"\\tWriting Secret Binary file \" << secretKeyBinaryFile << endl;\n    writeContextBaseBinary(secretBinFile, *context);\n    writeContextBinary(secretBinFile, *context);\n    writePubKeyBinary(secretBinFile, *pubKey);\n    writeSecKeyBinary(secretBinFile, *secKey);\n\n    // Public Bin\n    cout << \"\\tWriting Public Binary file \" << publicKeyBinaryFile << endl;\n    writeContextBaseBinary(publicBinFile, *context);\n    writeContextBinary(publicBinFile, *context);\n    writePubKeyBinary(publicBinFile, *pubKey);\n\n    secretBinFile.close();\n    publicBinFile.close();\n\n    cout << \"createKey successful.\\n\\n\";\n}", "meta": {"hexsha": "d7c21ef766af22006c1251cbe9d3fc34a110f5a5", "size": 2290, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/createKey.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": "src/createKey.cpp", "max_issues_repo_name": "HanBae/voting-HElib-script", "max_issues_repo_head_hexsha": "bfd88ef6fc42d3a1b8f5383d0db4f36ca24a515a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2019-02-20T15:25:41.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-19T15:29:31.000Z", "max_forks_repo_path": "src/createKey.cpp", "max_forks_repo_name": "HanBae/voting-HElib-script", "max_forks_repo_head_hexsha": "bfd88ef6fc42d3a1b8f5383d0db4f36ca24a515a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2018-11-11T23:39:17.000Z", "max_forks_repo_forks_event_max_datetime": "2019-10-06T05:12:37.000Z", "avg_line_length": 27.5903614458, "max_line_length": 76, "alphanum_fraction": 0.6510917031, "num_tokens": 744, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6723316991792861, "lm_q2_score": 0.48438008427698437, "lm_q1q2_score": 0.3256640851105507}}
{"text": "// __BEGIN_LICENSE__\n//  Copyright (c) 2006-2013, United States Government as represented by the\n//  Administrator of the National Aeronautics and Space Administration. All\n//  rights reserved.\n//\n//  The NASA Vision Workbench is licensed under the Apache License,\n//  Version 2.0 (the \"License\"); you may not use this file except in\n//  compliance with the License. You may obtain a copy of the License at\n//  http://www.apache.org/licenses/LICENSE-2.0\n//\n//  Unless required by applicable law or agreed to in writing, software\n//  distributed under the License is distributed on an \"AS IS\" BASIS,\n//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n//  See the License for the specific language governing permissions and\n//  limitations under the License.\n// __END_LICENSE__\n\n#include <vw/Core/Log.h>\n#include <vw/config.h>\n#include <vw/Math/Matrix.h>\n#include <vw/Math/Vector.h>\n#include <vw/Math/Quaternion.h>\n#include <vw/Camera/PinholeModel.h>\n#include <vw/Camera/LensDistortion.h>\n\n#if defined(VW_HAVE_PKG_LAPACK) && VW_HAVE_PKG_LAPACK==1\n#include <vw/Math/LinearAlgebra.h>\n#endif\n\n#include <algorithm>\n#include <sstream>\n#include <iomanip>\n#include <string>\n\n// TODO: One day remove this protobuf dependency.\n#if defined(VW_HAVE_PKG_PROTOBUF) && VW_HAVE_PKG_PROTOBUF==1\n#include <vw/Camera/TsaiFile.pb.h>\nusing google::protobuf::RepeatedFieldBackInserter;\n#endif\n\n#include <boost/filesystem/convenience.hpp>\nnamespace fs = boost::filesystem;\n\nusing namespace vw;\nusing namespace camera;\n\nPinholeModel::PinholeModel() : m_distortion(DistortPtr(new NullLensDistortion)),\n                               m_camera_center(Vector3(0,0,0)),\n                               m_fu(1), m_fv(1), m_cu(0), m_cv(0),\n                               m_u_direction(Vector3(1,0,0)),\n                               m_v_direction(Vector3(0,1,0)),\n                               m_w_direction(Vector3(0,0,1)), m_pixel_pitch(1) {\n\n  m_rotation.set_identity();\n  this->rebuild_camera_matrix();\n}\n\n/// Initialize from a file on disk.\nPinholeModel::PinholeModel(std::string const& filename) : m_distortion(DistortPtr(new NullLensDistortion)) {\n  read(filename);\n}\n\nPinholeModel::PinholeModel(Vector3 camera_center, Matrix<double,3,3> rotation,\n                           double f_u, double f_v, double c_u, double c_v,\n                           Vector3 u_direction, Vector3 v_direction,\n                           Vector3 w_direction,\n                           LensDistortion const& distortion_model,\n                           double pixel_pitch) : m_distortion(DistortPtr(distortion_model.copy())),\n                                                 m_camera_center(camera_center),  \n                                                 m_rotation(rotation),\n                                                 m_fu(f_u), m_fv(f_v), m_cu(c_u), m_cv(c_v),\n                                                 m_u_direction(u_direction),\n                                                 m_v_direction(v_direction),\n                                                 m_w_direction(w_direction),\n                                                 m_pixel_pitch(pixel_pitch) {\n  this->rebuild_camera_matrix();\n}\n\nPinholeModel::PinholeModel(Vector3 camera_center, Matrix<double,3,3> rotation,\n                           double f_u, double f_v, double c_u, double c_v,\n                           LensDistortion const& distortion_model,\n                           double pixel_pitch) : m_distortion(DistortPtr(distortion_model.copy())),\n                                                 m_camera_center(camera_center),\n                                                 m_rotation(rotation),\n                                                 m_fu(f_u), m_fv(f_v), m_cu(c_u), m_cv(c_v),\n                                                 m_u_direction(Vector3(1,0,0)),\n                                                 m_v_direction(Vector3(0,1,0)),\n                                                 m_w_direction(Vector3(0,0,1)),\n                                                 m_pixel_pitch(pixel_pitch) {\n  rebuild_camera_matrix();\n}\n\n\n/// Construct a basic pinhole model with no lens distortion\nPinholeModel::PinholeModel(Vector3 camera_center, Matrix<double,3,3> rotation,\n                           double f_u, double f_v,\n                           double c_u, double c_v,\n                           double pixel_pitch) : m_distortion(DistortPtr(new NullLensDistortion)),\n                                                 m_camera_center(camera_center),\n                                                 m_rotation(rotation),\n                                                 m_fu(f_u), m_fv(f_v), m_cu(c_u), m_cv(c_v),\n                                                 m_u_direction(Vector3(1,0,0)),\n                                                 m_v_direction(Vector3(0,1,0)),\n                                                 m_w_direction(Vector3(0,0,1)),\n                                                 m_pixel_pitch(pixel_pitch) {\n  rebuild_camera_matrix();\n}\n\n\n\nvoid PinholeModel::read(std::string const& filename) {\n\n  // Handle deprecated .pinhole protobuf files\n  fs::path filename_path( filename );\n  if ( filename_path.extension() == \".pinhole\" )\n    return read_protobuf_file(filename);\n\n  // Open the input file\n  std::ifstream cam_file;\n  cam_file.open(filename.c_str());\n  if (cam_file.fail())\n    vw_throw( IOErr() << \"PinholeModel::read_file: Could not open file: \" << filename );\n\n  // Check for version number on the first line\n  int file_version = 1; // The default version written before the 2016 changes\n  std::string line;\n  std::getline(cam_file, line);\n  if (line.find(\"VERSION\") != std::string::npos) {\n    sscanf(line.c_str(),\"VERSION_%d\", &file_version); // Parse the version of the input file\n    \n    // Right now there is only one version (VERSION_3) so if we find the version\n    //  we just skip it and move on to the next line.  If the version is changed,\n    //  handler logic needs to be implemented here.\n    std::getline(cam_file, line);\n  }\n  \n  // Start parsing all the parameters from the lines.\n  if (!cam_file.good() || sscanf(line.c_str(),\"fu = %lf\", &m_fu) != 1) {\n    cam_file.close();\n    vw_throw( IOErr() << \"PinholeModel::read_file(): Could not read x focal length\\n\" );\n  }\n\n  std::getline(cam_file, line);\n  if (!cam_file.good() || sscanf(line.c_str(),\"fv = %lf\", &m_fv) != 1) {\n    cam_file.close();\n    vw_throw( IOErr() << \"PinholeModel::read_file(): Could not read y focal length\\n\" );\n  }\n\n  std::getline(cam_file, line);\n  if (!cam_file.good() || sscanf(line.c_str(),\"cu = %lf\", &m_cu) != 1) {\n    cam_file.close();\n    vw_throw( IOErr() << \"PinholeModel::read_file(): Could not read x principal point\\n\" );\n  }\n\n  std::getline(cam_file, line);\n  if (!cam_file.good() || sscanf(line.c_str(),\"cv = %lf\", &m_cv) != 1) {\n    cam_file.close();\n    vw_throw( IOErr() << \"PinholeModel::read_file(): Could not read y principal point\\n\" );\n  }\n\n  std::getline(cam_file, line);\n  if (!cam_file.good() || sscanf(line.c_str(),\"u_direction = %lf %lf %lf\", \n        &m_u_direction(0), &m_u_direction(1), &m_u_direction(2)) != 3) {\n    cam_file.close();\n    vw_throw( IOErr() << \"PinholeModel::read_file(): Could not read u direction vector\\n\" );\n  }\n\n  std::getline(cam_file, line);\n  if (!cam_file.good() || sscanf(line.c_str(),\"v_direction = %lf %lf %lf\", \n        &m_v_direction(0), &m_v_direction(1), &m_v_direction(2)) != 3) {\n    cam_file.close();\n    vw_throw( IOErr() << \"PinholeModel::read_file(): Could not read v direction vector\\n\" );\n  }\n\n  std::getline(cam_file, line);\n  if (!cam_file.good() || sscanf(line.c_str(),\"w_direction = %lf %lf %lf\", \n        &m_w_direction(0), &m_w_direction(1), &m_w_direction(2)) != 3) {\n    cam_file.close();\n    vw_throw( IOErr() << \"PinholeModel::read_file(): Could not read w direction vector\\n\" );\n  }\n\n  // Read extrinsic parameters\n  std::getline(cam_file, line);\n  if (!cam_file.good() || sscanf(line.c_str(),\"C = %lf %lf %lf\", \n        &m_camera_center(0), &m_camera_center(1), &m_camera_center(2)) != 3) {\n    cam_file.close();\n    vw_throw( IOErr() << \"PinholeModel::read_file: Could not read C (camera center) vector\\n\" );\n  }\n\n  std::getline(cam_file, line);\n  if ( !cam_file.good() ||\n       sscanf(line.c_str(), \"R = %lf %lf %lf %lf %lf %lf %lf %lf %lf\",\n              &m_rotation(0,0), &m_rotation(0,1), &m_rotation(0,2),\n              &m_rotation(1,0), &m_rotation(1,1), &m_rotation(1,2),\n              &m_rotation(2,0), &m_rotation(2,1), &m_rotation(2,2)) != 9 ) {\n    cam_file.close();\n    vw_throw( IOErr() << \"PinholeModel::read_file(): Could not read rotation matrix\\n\" );\n  }\n\n  // The pitch line does not exist in older files, so don't fail if it is missing.\n  // - At this point we need to hang on to the position immediately before the \n  int lens_start = cam_file.tellg();\n  std::getline(cam_file, line);\n  if (line.find(\"pitch\") != std::string::npos) {\n    if (!cam_file.good() || sscanf(line.c_str(),\"pitch = %lf\", &m_pixel_pitch) != 1) {\n      cam_file.close();\n      vw_throw( IOErr() << \"PinholeModel::read_file(): Could not read pixel pitch\\n\" );\n    }\n    lens_start = cam_file.tellg();\n    std::getline(cam_file, line); // After reading the pitch, read the next line.\n  }\n  else // Pixel pitch not specified, use 1.0 as the default.\n  {\n    if (file_version > 2){\n      cam_file.close();\n      vw_throw( IOErr() << \"PinholeModel::read_file(): Pitch value required in this file version!\\n\" );\n    }\n    m_pixel_pitch = 1.0;\n  }\n\n  // Now that we have loaded all the parameters, update the dependend class members.\n  this->rebuild_camera_matrix();\n\n  // This creates m_distortion but we still need to read the parameters.\n  bool found_name = construct_lens_distortion(line);\n\n  if (!found_name && (file_version > 2)){\n    cam_file.close();\n    vw_throw( IOErr() << \"PinholeModel::read_file(): Distortion name required in this file version!\\n\" );\n  }\n  \n  // If there was no line containing the distortion model name (true for old files)\n  //  then we need to back up to before the distortion parameters begin in the file.\n  if (!found_name)\n    cam_file.seekg(lens_start ,std::ios_base::beg);    \n\n  // The lens distortion class knows how to parse the rest of the input stream.\n  m_distortion->read(cam_file);\n\n  cam_file.close();    \n}\n\nbool PinholeModel::construct_lens_distortion(std::string const& config_line) {\n\n  // Check if the passed in string contains the string for any of the\n  //  recognized lens distortion models.\n  if (config_line.find(NullLensDistortion::class_name()) != std::string::npos) {\n    m_distortion.reset(new NullLensDistortion());\n    return true;\n  }\n  if (config_line.find(BrownConradyDistortion::class_name()) != std::string::npos) {\n    m_distortion.reset(new BrownConradyDistortion());\n    return true;\n  }\n  if (config_line.find(AdjustableTsaiLensDistortion::class_name()) != std::string::npos) {\n    m_distortion.reset(new AdjustableTsaiLensDistortion());\n    return true;\n  }\n  if (config_line.find(PhotometrixLensDistortion::class_name()) != std::string::npos) {\n    m_distortion.reset(new PhotometrixLensDistortion());\n    return true;\n  }\n\n  // TSAI is the default model.  Older files which do not have a specifier string\n  //  contain TSAI parameters.\n  m_distortion.reset(new TsaiLensDistortion());\n  \n  if (config_line.find(TsaiLensDistortion::class_name()) != std::string::npos)\n    return true;\n  else\n    return false;\n}\n\n\n// This file type is DEPRECATED!\nvoid PinholeModel::read_protobuf_file(std::string const& filename) {\n\n  fs::path filename_path( filename );\n  if ( filename_path.extension() != \".pinhole\" )\n    vw_throw( IOErr() << \"Not a protobuf file extension: \" << filename_path.extension() );\n  \n#if defined(VW_HAVE_PKG_PROTOBUF) && VW_HAVE_PKG_PROTOBUF==1\n  std::fstream input( filename.c_str(), std::ios::in | std::ios::binary );\n  if ( !input )\n    vw_throw( IOErr() << \"Pinhole::read_file: Could not open \" << filename << \"\\n\" );\n  TsaiFile file;\n  if ( !file.ParseFromIstream( &input ) )\n    vw_throw( IOErr() << \"Pinhole::read_file: Protocol buffer failed to parse \\\"\" << filename << \"\\\"\\n\" );\n  input.close();\n\n  // Making sure protobuf seems correct\n  VW_ASSERT( file.focal_length_size() == 2,\n             IOErr() << \"Pinhole::read_file: Unexpected amount of focal lengths.\" );\n  VW_ASSERT( file.center_point_size() == 2,\n             IOErr() << \"Pinhole::read_file: Unexpected amount of center points.\" );\n  VW_ASSERT( file.u_direction_size() == 3,\n             IOErr() << \"Pinhole::read_file: Unexpected size of u vector.\" );\n  VW_ASSERT( file.v_direction_size() == 3,\n             IOErr() << \"Pinhole::read_file: Unexpected size of v vector.\" );\n  VW_ASSERT( file.w_direction_size() == 3,\n             IOErr() << \"Pinhole::read_file: Unexpected size of w vector.\" );\n  VW_ASSERT( file.camera_center_size() == 3,\n             IOErr() << \"Pinhole::read_file: Unexpected size of camera vector.\" );\n  VW_ASSERT( file.camera_rotation_size() == 9,\n             IOErr() << \"Pinhole::read_file: Unexpected size of rotation matrix.\" );\n\n  typedef VectorProxy<double,3> Vector3P;\n  m_u_direction = Vector3P(file.mutable_u_direction()->mutable_data());\n  m_v_direction = Vector3P(file.mutable_v_direction()->mutable_data());\n  m_w_direction = Vector3P(file.mutable_w_direction()->mutable_data());\n  m_camera_center = Vector3P(file.mutable_camera_center()->mutable_data());\n  m_fu = file.focal_length(0);\n  m_fv = file.focal_length(1);\n  m_cu = file.center_point(0);\n  m_cv = file.center_point(1);\n  m_rotation = MatrixProxy<double,3,3>(file.mutable_camera_rotation()->mutable_data());\n  m_pixel_pitch = file.pixel_pitch();\n\n  this->rebuild_camera_matrix();\n\n  if ( file.distortion_name() == \"NULL\" ) {\n    VW_ASSERT( file.distortion_vector_size() == 0,\n               IOErr() << \"Pinhole::read_file: Unexpected distortion vector.\" );\n    m_distortion.reset( new NullLensDistortion());\n  } else if ( file.distortion_name() == \"TSAI\" ) {\n    VW_ASSERT( file.distortion_vector_size() == 4,\n               IOErr() << \"Pinhole::read_file: Unexpected distortion vector.\" );\n    m_distortion.reset( new TsaiLensDistortion(VectorProxy<double,4>(file.mutable_distortion_vector()->mutable_data())));\n  } else if ( file.distortion_name() == \"BROWNCONRADY\" ) {\n    VW_ASSERT( file.distortion_vector_size() == 8,\n               IOErr() << \"Pinhole::read_file: Unexpected distortion vector.\" );\n    m_distortion.reset( new BrownConradyDistortion(VectorProxy<double,8>(file.mutable_distortion_vector()->mutable_data())));\n  } else if ( file.distortion_name() == \"AdjustableTSAI\" ) {\n    VW_ASSERT( file.distortion_vector_size() > 3,\n               IOErr() << \"Pinhole::read_file: Unexpected distortion vector.\" );\n    m_distortion.reset( new AdjustableTsaiLensDistortion(VectorProxy<double>(file.distortion_vector_size(),file.mutable_distortion_vector()->mutable_data())));\n  }\n#else\n  // If you hit this point, you need to install Google Protobuffers to to read this file type.\n  vw_throw( IOErr() << \"Pinhole::write_file: Camera IO not supported without Google Protobuffers\" );\n#endif\n\n}\n\nvoid PinholeModel::write(std::string const& filename) const {\n\n  // Update this field whenever there is a significant change to the file.\n  // - It can be used to keep backwards compatibility with future plain text changes.\n  const std::string PINHOLE_VERSION = \"VERSION_3\";\n\n  // Set the path an open the output file for writing\n  std::string file_path = fs::path(filename).replace_extension(\".tsai\").string();\n  std::ofstream cam_file(file_path.c_str());\n  if( !cam_file.is_open() ) \n    vw_throw( IOErr() << \"PinholeModel::write: Could not open file: \" << file_path );\n\n  // Write the pinhole camera model parts\n  //   # digits to survive double->text->double conversion\n  const size_t ACCURATE_DIGITS = 17; // = std::numeric_limits<double>::max_digits10\n  cam_file << std::setprecision(ACCURATE_DIGITS); \n  cam_file << PINHOLE_VERSION << \"\\n\";\n  cam_file << \"fu = \" << m_fu << \"\\n\";\n  cam_file << \"fv = \" << m_fv << \"\\n\";\n  cam_file << \"cu = \" << m_cu << \"\\n\";\n  cam_file << \"cv = \" << m_cv << \"\\n\";\n  cam_file << \"u_direction = \" << m_u_direction[0] << \" \" << m_u_direction[1] << \" \" << m_u_direction[2] << \"\\n\";\n  cam_file << \"v_direction = \" << m_v_direction[0] << \" \" << m_v_direction[1] << \" \" << m_v_direction[2] << \"\\n\";\n  cam_file << \"w_direction = \" << m_w_direction[0] << \" \" << m_w_direction[1] << \" \" << m_w_direction[2] << \"\\n\";\n  cam_file << \"C = \" << m_camera_center[0] << \" \" << m_camera_center[1] << \" \" << m_camera_center[2] << \"\\n\";\n  cam_file << \"R = \" << m_rotation(0,0) << \" \" << m_rotation(0,1) << \" \" << m_rotation(0,2) << \" \" << m_rotation(1,0) << \" \" << m_rotation(1,1) << \" \" << m_rotation(1,2) << \" \" << m_rotation(2,0) << \" \" << m_rotation(2,1) << \" \" << m_rotation(2,2) << \"\\n\";\n  cam_file << \"pitch = \" << m_pixel_pitch << \"\\n\";\n\n  // Write the name of the distortion model, then use the distortion model\n  //  << overload to write it to the file. \n  cam_file << m_distortion->name() << std::endl;\n  cam_file << *m_distortion;\n  cam_file.close();\n}\n\n\nVector2 PinholeModel::point_to_pixel(Vector3 const& point) const {\n\n  // Multiply the pixel location by the 3x4 camera matrix.\n  // - The pixel coordinate is de-homogenized by dividing by the denominator.\n  double denominator = m_camera_matrix(2,0)*point(0) + m_camera_matrix(2,1)*point(1) +\n                       m_camera_matrix(2,2)*point(2) + m_camera_matrix(2,3);\n  Vector2 pixel = Vector2( (m_camera_matrix(0,0)*point(0) + m_camera_matrix(0,1)*point(1) +\n                            m_camera_matrix(0,2)*point(2) + m_camera_matrix(0,3)           ) / denominator,\n                           (m_camera_matrix(1,0)*point(0) + m_camera_matrix(1,1)*point(1) +\n                            m_camera_matrix(1,2)*point(2) + m_camera_matrix(1,3)           ) / denominator);\n\n  // Apply the lens distortion model\n  // - Divide by pixel pitch to convert from metric units to pixels if the intrinsic\n  //   values were not specified in pixel units (in that case m_pixel_pitch == 1.0)\n  return m_distortion->distorted_coordinates(*this, pixel)/m_pixel_pitch;\n}\n\nVector2 PinholeModel::point_to_pixel_no_distortion(Vector3 const& point) const {\n\n  // Multiply the pixel location by the 3x4 camera matrix.\n  // - The pixel coordinate is de-homogenized by dividing by the denominator.\n  double denominator = m_camera_matrix(2,0)*point(0) + m_camera_matrix(2,1)*point(1) +\n                       m_camera_matrix(2,2)*point(2) + m_camera_matrix(2,3);\n  Vector2 pixel = Vector2( (m_camera_matrix(0,0)*point(0) + m_camera_matrix(0,1)*point(1) +\n                            m_camera_matrix(0,2)*point(2) + m_camera_matrix(0,3)           ) / denominator,\n                           (m_camera_matrix(1,0)*point(0) + m_camera_matrix(1,1)*point(1) +\n                            m_camera_matrix(1,2)*point(2) + m_camera_matrix(1,3)           ) / denominator);\n\n  // Divide by pixel pitch to convert from metric units to pixels if the intrinsic\n  //   values were not specified in pixel units (in that case m_pixel_pitch == 1.0)\n  return pixel/m_pixel_pitch;\n}\n\nbool PinholeModel::projection_valid(Vector3 const& point) const {\n  // z coordinate after extrinsic transformation\n  double z = m_extrinsics(2, 0)*point(0) + m_extrinsics(2, 1)*point(1) +\n    m_extrinsics(2, 2)*point(2) + m_extrinsics(2,3);\n  return z > 0;\n}\n\nVector3 PinholeModel::pixel_to_vector (Vector2 const& pix) const {\n  // Apply the inverse lens distortion model\n  Vector2 undistorted_pix = m_distortion->undistorted_coordinates(*this, pix*m_pixel_pitch);\n\n  // Compute the direction of the ray emanating from the camera center.\n  Vector3 p(0,0,1);\n  subvector(p,0,2) = undistorted_pix;\n  return normalize( m_inv_camera_transform * p);\n}\n\nVector3 PinholeModel::camera_center(Vector2 const& /*pix*/ ) const {\n  return m_camera_center;\n};\n\nvoid PinholeModel::set_camera_center(Vector3 const& position) {\n  m_camera_center = position; \n  rebuild_camera_matrix();\n}\n\nQuaternion<double> PinholeModel::camera_pose(Vector2 const& /*pix*/ ) const {\n  return Quaternion<double>(m_rotation);\n}\n\nvoid PinholeModel::set_camera_pose(Quaternion<double> const& pose) {\n  m_rotation = pose.rotation_matrix(); \n  rebuild_camera_matrix();\n}\n\nvoid PinholeModel::set_camera_pose(Matrix<double,3,3> const& pose) {\n  m_rotation = pose; \n  rebuild_camera_matrix();\n}\n\nvoid PinholeModel::coordinate_frame(Vector3 &u_vec, Vector3 &v_vec, Vector3 &w_vec) const {\n  u_vec = m_u_direction;\n  v_vec = m_v_direction;\n  w_vec = m_w_direction;\n}\n\nvoid PinholeModel::set_coordinate_frame(Vector3 u_vec, Vector3 v_vec, Vector3 w_vec) {\n  m_u_direction = u_vec;\n  m_v_direction = v_vec;\n  m_w_direction = w_vec;\n\n  rebuild_camera_matrix();\n}\n\nVector3 PinholeModel::coordinate_frame_u_direction() const { return m_u_direction; }\nVector3 PinholeModel::coordinate_frame_v_direction() const { return m_v_direction; }\nVector3 PinholeModel::coordinate_frame_w_direction() const { return m_w_direction; }\n\nconst LensDistortion* PinholeModel::lens_distortion() const { return m_distortion.get(); };\nvoid PinholeModel::set_lens_distortion(LensDistortion const& distortion) {\n  m_distortion = distortion.copy();\n}\n\nvoid PinholeModel::intrinsic_parameters(double& f_u, double& f_v,\n                                        double& c_u, double& c_v) const {\n  f_u = m_fu;  f_v = m_fv;  c_u = m_cu;  c_v = m_cv;\n}\n\nvoid PinholeModel::set_intrinsic_parameters(double f_u, double f_v,\n                                            double c_u, double c_v) {\n  m_fu = f_u;  m_fv = f_v;  m_cu = c_u;  m_cv = c_v;\n  rebuild_camera_matrix();\n}\n\nVector2 PinholeModel::focal_length() const { return Vector2(m_fu,m_fv); }\nvoid PinholeModel::set_focal_length(Vector2 const& f, bool rebuild ) {\n  m_fu = f[0]; m_fv = f[1];\n  if (rebuild) rebuild_camera_matrix();\n}\nVector2 PinholeModel::point_offset() const { return Vector2(m_cu,m_cv); }\nvoid PinholeModel::set_point_offset(Vector2 const& c, bool rebuild ) {\n  m_cu = c[0]; m_cv = c[1];\n  if (rebuild) rebuild_camera_matrix();\n}\ndouble PinholeModel::pixel_pitch() const { return m_pixel_pitch; }\nvoid PinholeModel::set_pixel_pitch( double pitch ) { m_pixel_pitch = pitch; }\n\n\nvoid PinholeModel::set_camera_matrix( Matrix<double,3,4> const& p ) {\n#if defined(VW_HAVE_PKG_LAPACK) && VW_HAVE_PKG_LAPACK==1\n  // Solving for camera center\n  Matrix<double> cam_nullsp = nullspace(p);\n  Vector<double> cam_center = select_col(cam_nullsp,0);\n  cam_center /= cam_center[3];\n  m_camera_center = subvector(cam_center,0,3);\n\n  // Solving for intrinsics with RQ decomposition\n  Matrix<double> M = submatrix(p,0,0,3,3);\n  Matrix<double> R,Q;\n  rqd( M, R, Q );\n  Matrix<double> sign_fix(3,3);\n  sign_fix.set_identity();\n  if ( R(0,0) < 0 )\n    sign_fix(0,0) = -1;\n  if ( R(1,1) < 0 )\n    sign_fix(1,1) = -1;\n  if ( R(2,2) < 0 )\n    sign_fix(2,2) = -1;\n  R = R*sign_fix;\n  Q = sign_fix*Q;\n  R /= R(2,2);\n\n  // Pulling out intrinsic and last extrinsic\n  Matrix<double,3,3> uvwRotation;\n  select_row(uvwRotation,0) = m_u_direction;\n  select_row(uvwRotation,1) = m_v_direction;\n  select_row(uvwRotation,2) = m_w_direction;\n  m_rotation = inverse(uvwRotation*Q);\n  m_fu = R(0,0);\n  m_fv = R(1,1);\n  m_cu = R(0,2);\n  m_cv = R(1,2);\n\n  if ( fabs(R(0,1)) >= 1.2 )\n    vw_out(WarningMessage,\"camera\") << \"Significant skew not modelled by pinhole camera\\n\";\n\n  // Rebuild\n  rebuild_camera_matrix();\n#else\n  vw_throw( NoImplErr() << \"PinholeModel::set_Camera_Matrix is unavailable without LAPACK\" );\n#endif\n}\n\nMatrix<double,3,4> PinholeModel::camera_matrix() const {\n  return m_camera_matrix;\n}\n\nvoid PinholeModel::rebuild_camera_matrix() {\n\n  /// The intrinsic portion of the camera matrix is stored as\n  ///\n  ///    [  fx   0   cx  ]\n  /// K= [  0    fy  cy  ]\n  ///    [  0    0   1   ]\n  ///\n  /// with fx, fy the focal length of the system (in horizontal and\n  /// vertical pixels), and (cx, cy) the pixel coordinates of the\n  /// central pixel (the principal point on the image plane).\n\n  m_intrinsics(0,0) = m_fu;\n  m_intrinsics(0,1) = 0;\n  m_intrinsics(0,2) = m_cu;\n  m_intrinsics(1,0) = 0;\n  m_intrinsics(1,1) = m_fv;\n  m_intrinsics(1,2) = m_cv;\n  m_intrinsics(2,0) = 0;\n  m_intrinsics(2,1) = 0;\n  m_intrinsics(2,2) = 1;\n\n  // The extrinsics are normally built as the matrix:  [ R | -R*C ].\n  // To allow for user-specified coordinate frames, the\n  // extrinsics are now build to include the u,v,w rotation\n  //\n  //               | u_0  u_1  u_2  |\n  //     Extr. =   | v_0  v_1  v_2  | * [ R | -R*C]\n  //               | w_0  w_1  w_2  |\n  //\n  // The vectors u,v, and w must be orthonormal.\n\n  /*   check for orthonormality of u,v,w              */\n  VW_LINE_ASSERT( dot_prod(m_u_direction, m_v_direction) == 0 );\n  VW_LINE_ASSERT( dot_prod(m_u_direction, m_w_direction) == 0 );\n  VW_LINE_ASSERT( dot_prod(m_v_direction, m_w_direction) == 0 );\n  VW_LINE_ASSERT( fabs( norm_2(m_u_direction) - 1 ) < 0.001 );\n  VW_LINE_ASSERT( fabs( norm_2(m_v_direction) - 1 ) < 0.001 );\n  VW_LINE_ASSERT( fabs( norm_2(m_w_direction) - 1 ) < 0.001 );\n\n  Matrix<double,3,3> uvwRotation;\n\n  select_row(uvwRotation,0) = m_u_direction;\n  select_row(uvwRotation,1) = m_v_direction;\n  select_row(uvwRotation,2) = m_w_direction;\n\n  Matrix<double,3,3> rotation_inverse = transpose(m_rotation);\n  submatrix(m_extrinsics,0,0,3,3) = uvwRotation * rotation_inverse;\n  select_col(m_extrinsics,3) = uvwRotation * -rotation_inverse * m_camera_center;\n\n  m_camera_matrix = m_intrinsics * m_extrinsics;\n  m_inv_camera_transform = inverse(uvwRotation*rotation_inverse) * inverse(m_intrinsics);\n}\n\n// Apply a given rotation + translation + scale transform to a pinhole camera\nvoid PinholeModel::apply_transform(vw::Matrix3x3 const & rotation,\n                                   vw::Vector3   const & translation,\n                                   double                scale) {\n\n  // Extract current parameters\n  vw::Vector3 position = this->camera_center();\n  vw::Quat    pose     = this->camera_pose();\n  \n  vw::Quat rotation_quaternion(rotation);\n  \n  // New position and rotation\n  position = scale*rotation*position + translation;\n  pose     = rotation_quaternion*pose;\n  this->set_camera_center(position);\n  this->set_camera_pose  (pose);\n}\n\nPinholeModel\ncamera::scale_camera(PinholeModel const& camera_model, float scale) {\n  if (scale == 0)\n    vw_throw( ArgumentErr() << \"PinholeModel::scale_camera cannot have zero scale value!\" );\n  // Scaling the camera is easy, just update the pixel pitch to account for the new image size.\n  Vector2 focal  = camera_model.focal_length();\n  Vector2 offset = camera_model.point_offset();\n  boost::shared_ptr<LensDistortion> lens = camera_model.lens_distortion()->copy();\n  return PinholeModel( camera_model.camera_center(),\n                       camera_model.camera_pose().rotation_matrix(),\n                       focal[0], focal[1], offset[0], offset[1],\n                       camera_model.coordinate_frame_u_direction(),\n                       camera_model.coordinate_frame_v_direction(),\n                       camera_model.coordinate_frame_w_direction(),\n                       *lens,\n                       camera_model.pixel_pitch()/scale);\n}\n\n\nPinholeModel\ncamera::strip_lens_distortion(PinholeModel const& camera_model) {\n  Vector2 focal  = camera_model.focal_length();\n  Vector2 offset = camera_model.point_offset();\n  NullLensDistortion distortion;\n  return PinholeModel(camera_model.camera_center(),\n                      camera_model.camera_pose().rotation_matrix(),\n                      focal[0], focal[1], offset[0], offset[1],\n                      camera_model.coordinate_frame_u_direction(),\n                      camera_model.coordinate_frame_v_direction(),\n                      camera_model.coordinate_frame_w_direction(),\n                      distortion, camera_model.pixel_pitch());\n}\n\nstd::ostream& camera::operator<<(std::ostream& str,\n                                 PinholeModel const& model) {\n  str << \"Pinhole camera: \\n\";\n  str << \"\\tCamera Center: \" << model.camera_center() << \"\\n\";\n  str << \"\\tRotation Matrix: \" << model.camera_pose() << \"\\n\";\n  str << \"\\tIntrinsics:\\n\";\n  str << \"\\t  focal: \"       << model.focal_length() << \"\\n\";\n  str << \"\\t  offset: \"      << model.point_offset() << \"\\n\";\n  str << \"\\t  pixel pitch: \" << model.pixel_pitch()  << \"\\n\";\n  str << \"\\tu direction: \" << model.coordinate_frame_u_direction() << \"\\n\";\n  str << \"\\tv direction: \" << model.coordinate_frame_v_direction() << \"\\n\";\n  str << \"\\tw direction: \" << model.coordinate_frame_w_direction() << \"\\n\";\n  str << \"\\tDistortion Model: \" << model.lens_distortion()->name() << \"\\n\";\n  str << *(model.lens_distortion()); // this will be multiple lines\n\n  return str;\n}\n", "meta": {"hexsha": "d72c4f475fc05b38bf143dd8ed0e97a4be88a6b3", "size": 28745, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/vw/Camera/PinholeModel.cc", "max_stars_repo_name": "CVandML/visionworkbench", "max_stars_repo_head_hexsha": "c432442b1e806961b4b7eb15d73051ebb08f1d6b", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2017-02-04T20:08:18.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-07T05:07:13.000Z", "max_issues_repo_path": "src/vw/Camera/PinholeModel.cc", "max_issues_repo_name": "CVandML/visionworkbench", "max_issues_repo_head_hexsha": "c432442b1e806961b4b7eb15d73051ebb08f1d6b", "max_issues_repo_licenses": ["Apache-2.0"], "max_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/PinholeModel.cc", "max_forks_repo_name": "CVandML/visionworkbench", "max_forks_repo_head_hexsha": "c432442b1e806961b4b7eb15d73051ebb08f1d6b", "max_forks_repo_licenses": ["Apache-2.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.7117384844, "max_line_length": 256, "alphanum_fraction": 0.6393459732, "num_tokens": 7580, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7122321842389469, "lm_q2_score": 0.4571367168274948, "lm_q1q2_score": 0.32558748232186757}}
{"text": "﻿//***********************************************************\r\n// 07/03/2019\t1.0.0\tRémi Saint-Amant   Creation\r\n//***********************************************************\r\n#include \"LaricobiusNigrinusModel.h\"\r\n#include \"ModelBase/EntryPoint.h\"\r\n#include \"Basic\\DegreeDays.h\"\r\n#include <boost/math/distributions/weibull.hpp>\r\n#include <boost/math/distributions/beta.hpp>\r\n#include <boost/math/distributions/Rayleigh.hpp>\r\n#include <boost/math/distributions/logistic.hpp>\r\n#include <boost/math/distributions/exponential.hpp>\r\n\r\n\r\nusing namespace WBSF::HOURLY_DATA;\r\nusing namespace WBSF::LNF;\r\nusing namespace std;\r\n\r\n//static const bool BEGIN_NOVEMBER = false;\r\n//static const size_t FIRST_Y = BEGIN_NOVEMBER ? 1 : 0;\r\n\r\nnamespace WBSF\r\n{\r\n\tstatic const CDegreeDays::TDailyMethod DD_METHOD = CDegreeDays::MODIFIED_ALLEN_WAVE;\r\n\tenum { ACTUAL_CDD, DATE_DD717, DIFF_DAY, NB_OUTPUTS };\r\n\r\n\t//this line link this model with the EntryPoint of the DLL\r\n\tstatic const bool bRegistred =\r\n\t\tCModelFactory::RegisterModel(CLaricobiusNigrinusModel::CreateObject);\r\n\r\n\tCLaricobiusNigrinusModel::CLaricobiusNigrinusModel()\r\n\t{\r\n\t\t//NB_INPUT_PARAMETER is used to determine if the dll\r\n\t\t//uses the same number of parameters than the model interface\r\n\t\tNB_INPUT_PARAMETER = -1;\r\n\t\tVERSION = \"1.0.2 (2020)\";\r\n\r\n\t\t//\t\tm_start = CTRef(YEAR_NOT_INIT, JANUARY, DAY_01);\r\n\t\t\t//\tm_threshold = 5.6;\r\n\t\t\t\t//m_sumDD = 540;\r\n\r\n\t\tm_bCumul = false;\r\n\t\tfor (size_t s = 0; s < NB_STAGES; s++)\r\n\t\t{\r\n\t\t\tfor (size_t p = 0; p < NB_RDR_PARAMS; p++)\r\n\t\t\t{\r\n\t\t\t\tm_RDR[s][p] = CLaricobiusNigrinusEquations::RDR[s][p];\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tfor (size_t p = 0; p < NB_OVP_PARAMS; p++)\r\n\t\t\tm_OVP[p] = CLaricobiusNigrinusEquations::OVP[p];\r\n\r\n\t\tfor (size_t p = 0; p < NB_ADE_PARAMS; p++)\r\n\t\t\tm_ADE[p] = CLaricobiusNigrinusEquations::ADE[p];\r\n\r\n\t\tfor (size_t p = 0; p < NB_EAS_PARAMS; p++)\r\n\t\t\tm_EAS[p] = CLaricobiusNigrinusEquations::EAS[p];\r\n\t}\r\n\r\n\tCLaricobiusNigrinusModel::~CLaricobiusNigrinusModel()\r\n\t{\r\n\t}\r\n\r\n\r\n\t//this method is call to load your parameter in your variable\r\n\tERMsg CLaricobiusNigrinusModel::ProcessParameters(const CParameterVector& parameters)\r\n\t{\r\n\t\tERMsg msg;\r\n\r\n\t\tsize_t c = 0;\r\n\r\n\t\tm_bCumul = parameters[c++].GetBool();\r\n\r\n\t\tif (parameters.size() == 1 + NB_STAGES * NB_RDR_PARAMS + NB_OVP_PARAMS + NB_ADE_PARAMS + NB_EAS_PARAMS)\r\n\t\t{\r\n\t\t\tfor (size_t s = 0; s < NB_STAGES; s++)\r\n\t\t\t{\r\n\t\t\t\tfor (size_t p = 0; p < NB_RDR_PARAMS; p++)\r\n\t\t\t\t{\r\n\t\t\t\t\tm_RDR[s][p] = parameters[c++].GetFloat();\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\tfor (size_t p = 0; p < NB_OVP_PARAMS; p++)\r\n\t\t\t\tm_OVP[p] = parameters[c++].GetFloat();\r\n\r\n\t\t\tfor (size_t p = 0; p < NB_ADE_PARAMS; p++)\r\n\t\t\t\tm_ADE[p] = parameters[c++].GetFloat();\r\n\r\n\t\t\tfor (size_t p = 0; p < NB_EAS_PARAMS; p++)\r\n\t\t\t\tm_EAS[p] = parameters[c++].GetFloat();\r\n\r\n\t\t}\r\n\r\n\t\treturn msg;\r\n\t}\r\n\r\n\r\n\r\n\r\n\r\n\t/*ERMsg CLaricobiusNigrinusModel::OnExecuteAnnual()\r\n\t{\r\n\t\t_ASSERTE(m_weather.size() > 1);\r\n\r\n\t\tERMsg msg;\r\n\t\tCTRef today = CTRef::GetCurrentTRef();\r\n\r\n\t\tCTPeriod outputPeriod = m_weather.GetEntireTPeriod(CTM::ANNUAL);\r\n\t\tm_output.Init(outputPeriod, NB_OUTPUTS);\r\n\r\n\r\n\t\tfor (size_t y = 0; y < m_weather.GetNbYears(); y++)\r\n\t\t{\r\n\t\t\tint year = m_weather[y].GetTRef().GetYear();\r\n\t\t\tCTRef begin = CTRef(year, m_start.GetMonth(), m_start.GetDay());\r\n\t\t\tCTRef end = CTRef(year, DECEMBER, DAY_31);\r\n\r\n\t\t\tdouble CDD = 0;\r\n\r\n\t\t\tCTRef day717;\r\n\t\t\tdouble actualCDD = -999;\r\n\t\t\tCDegreeDays DD(DD_METHOD, m_threshold);\r\n\r\n\t\t\tfor (CTRef d = begin; d < end; d++)\r\n\t\t\t{\r\n\t\t\t\tCDD += DD.GetDD(m_weather.GetDay(d));\r\n\t\t\t\tif (CDD >= m_sumDD && !day717.IsInit())\r\n\t\t\t\t\tday717 = d;\r\n\r\n\t\t\t\tif (d.as(CTM(CTM::DAILY, CTM::OVERALL_YEARS)) == today.as(CTM(CTM::DAILY, CTM::OVERALL_YEARS)))\r\n\t\t\t\t\tactualCDD = CDD;\r\n\t\t\t}\r\n\r\n\t\t\tm_output[y][ACTUAL_CDD] = actualCDD;\r\n\t\t\tif (day717.IsInit())\r\n\t\t\t{\r\n\t\t\t\tm_output[y][DATE_DD717] = day717.GetRef();\r\n\t\t\t\tm_output[y][DIFF_DAY] = (int)day717.GetJDay() - (int)today.GetJDay();\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\treturn msg;\r\n\t}*/\r\n\r\n\t//This method is called to compute the solution\r\n\tERMsg CLaricobiusNigrinusModel::OnExecuteDaily()\r\n\t{\r\n\t\tERMsg msg;\r\n\r\n\t\t/*\tif (m_weather.GetNbYears() < 2)\r\n\t\t\t{\r\n\t\t\t\tmsg.ajoute(\"Laricobius nigrinus model need at least 2 years of data\");\r\n\t\t\t\treturn msg;\r\n\t\t\t}*/\r\n\r\n\t\tif (!m_weather.IsHourly())\r\n\t\t\tm_weather.ComputeHourlyVariables();\r\n\r\n\t\t//This is where the model is actually executed\r\n\t\tCTPeriod p = m_weather.GetEntireTPeriod(CTM(CTM::DAILY));\r\n\t\tm_output.Init(p, NB_STATS, 0);\r\n\r\n\t\t//we simulate 2 years at a time. \r\n\t\t//we also manager the possibility to have only one year\r\n\t\tfor (size_t y = 0; y < m_weather.size(); y++)\r\n\t\t{\r\n\t\t\tExecuteDaily(m_weather[y].GetTRef().GetYear(), m_weather, m_output);\r\n\t\t}\r\n\r\n\t\treturn msg;\r\n\t}\r\n\r\n\tvoid CLaricobiusNigrinusModel::ExecuteDaily(int year, const CWeatherYears& weather, CModelStatVector& output)\r\n\t{\r\n\t\t//Create stand\r\n\t\tCLNFStand stand(this, m_OVP[Τᴴ¹], m_OVP[Τᴴ²]);\r\n\r\n\t\t//Set parameters to equation\r\n\t\tfor (size_t s = 0; s < NB_STAGES; s++)\r\n\t\t{\r\n\t\t\tfor (size_t p = 0; p < NB_RDR_PARAMS; p++)\r\n\t\t\t{\r\n\t\t\t\tstand.m_equations.m_RDR[s][p] = m_RDR[s][p];\r\n\t\t\t}\r\n\t\t}\r\n\r\n\r\n\t\tfor (size_t p = 0; p < NB_OVP_PARAMS; p++)\r\n\t\t\tstand.m_equations.m_OVP[p] = m_OVP[p];\r\n\r\n\t\tfor (size_t p = 0; p < NB_ADE_PARAMS; p++)\r\n\t\t\tstand.m_equations.m_ADE[p] = m_ADE[p];\r\n\r\n\t\tfor (size_t p = 0; p < NB_EAS_PARAMS; p++)\r\n\t\t\tstand.m_equations.m_EAS[p] = m_EAS[p];\r\n\r\n\r\n\t\tstand.init(year, weather);\r\n\r\n\t\t//compute 30 days avg\r\n\t\t//stand.ComputeTavg30(year, weather);\r\n\r\n\r\n\t\t//Create host\r\n\t\tCLNFHostPtr pHost(new CLNFHost(&stand));\r\n\r\n\t\tpHost->m_nbMinObjects = 10;\r\n\t\tpHost->m_nbMaxObjects = 1000;\r\n\r\n\r\n\t\tpHost->Initialize<CLaricobiusNigrinus>(CInitialPopulation(CTRef(year, JANUARY, DAY_01), 0, 400, 100, -1));\r\n\r\n\t\t//add host to stand\t\t\t\r\n\t\tstand.m_host.push_front(pHost);\r\n\r\n\t\tCTPeriod p = weather[year].GetEntireTPeriod(CTM(CTM::DAILY));\r\n\r\n\t\t//if have other year extend period to February\r\n\t\t//ASSERT(weather[year].HavePrevious());\r\n\t\t//if (BEGIN_NOVEMBER)\r\n\t\t//{\r\n\t\t//\tp.Begin() = CTRef(year - 1, NOVEMBER, DAY_01);\r\n\t\t//}\r\n\r\n\t\t//if have other year extend period to February\r\n\t\t//if (weather[year].HavePrevious())\r\n\t\t\t//p.Begin() = CTRef(year - 1, JULY, DAY_01);\r\n\r\n\r\n\t\t//if have other year extend period to February\r\n\t\tif (weather[year].HaveNext())\r\n\t\t\tp.End() = CTRef(year + 1, JUNE, DAY_30);\r\n\r\n\r\n\t\tfor (CTRef d = p.Begin(); d <= p.End(); d++)\r\n\t\t{\r\n\t\t\t/*if (d == CTRef(year + 1, JANUARY, DAY_01))\r\n\t\t\t{\r\n\t\t\t\tint gg;\r\n\t\t\t\t\tgg=0;\r\n\t\t\t}*/\r\n\r\n\t\t\tstand.Live(weather.GetDay(d));\r\n\t\t\tif (output.IsInside(d))\r\n\t\t\t\tstand.GetStat(d, output[d]);\r\n\r\n\t\t\tstand.AdjustPopulation();\r\n\t\t\tHxGridTestConnection();\r\n\t\t}\r\n\r\n\r\n\r\n\r\n\t\tif (m_bCumul)\r\n\t\t{\r\n\t\t\t//cumulative result\r\n\t\t\tfor (size_t s = S_EGG; s < S_ACTIVE_ADULT; s++)\r\n\t\t\t{\r\n\t\t\t\tCTPeriod p = weather[year].GetEntireTPeriod(CTM(CTM::DAILY));\r\n\r\n\t\t\t\tCStatistic stat = output.GetStat(s, p);\r\n\t\t\t\tif (stat.IsInit() && stat[SUM] > 0)\r\n\t\t\t\t{\r\n\t\t\t\t\toutput[0][s] = output[0][s] * 100 / stat[SUM];//when first day is not 0\r\n\t\t\t\t\tfor (CTRef d = p.Begin() + 1; d <= p.End(); d++)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\toutput[d][s] = output[d - 1][s] + output[d][s] * 100 / stat[SUM];\r\n\t\t\t\t\t\t_ASSERTE(!_isnan(output[d][s]));\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/*for (size_t s = S_M_EGG; s <= S_M_DEAD_ADULT; s++)\r\n\t\t\t{\r\n\t\t\t\tCTPeriod p = weather[year].GetEntireTPeriod(CTM(CTM::DAILY));\r\n\t\t\t\tif (s >= S_M_ACTIVE_ADULT)\r\n\t\t\t\t{\r\n\t\t\t\t\tp.Begin() = CTRef(year, JULY, DAY_01);\r\n\t\t\t\t\tif (weather[year].HaveNext())\r\n\t\t\t\t\t\tp.End() = CTRef(year + 1, JUNE, DAY_30);\r\n\t\t\t\t}\r\n\r\n\t\t\t\tCStatistic stat = output.GetStat(s, p);\r\n\t\t\t\tif (stat.IsInit() && stat[SUM] > 0)\r\n\t\t\t\t{\r\n\t\t\t\t\tfor (CTRef d = p.Begin() + 1; d <= p.End(); d++)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tif(output.IsInside(d))\r\n\t\t\t\t\t\t\toutput[d][s] = output[d - 1][s] + output[d][s] * 100 / stat[SUM];\r\n\t\t\t\t\t\t_ASSERTE(!_isnan(output[d][s]));\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\r\n\t\t\t}*/\r\n\r\n\t\t}\r\n\t}\r\n\r\n\r\n\tvoid CLaricobiusNigrinusModel::AddDailyResult(const StringVector& header, const StringVector& data)\r\n\t{\r\n\t\tASSERT(data.size() == 5);\r\n\r\n\t\tCSAResult obs;\r\n\t\t//if (data[0] != \"BlacksburgLab\" && data[0] != \"VictoriaLab\")\r\n\t\t//if (data[0] != \"VictoriaLab\")\r\n\t\t//{\r\n\t\tCStatistic egg_creation_date;\r\n\r\n\r\n\t\tobs.m_ref.FromFormatedString(data[1]);\r\n\t\tobs.m_obs.resize(NB_INPUTS);\r\n\t\tfor (size_t i = 0; i < NB_INPUTS; i++)\r\n\t\t{\r\n\t\t\tobs.m_obs[i] = stod(data[i + 2]);\r\n\r\n\t\t\tif (i == 0 && obs.m_obs[i] > -999)\r\n\t\t\t\tm_egg_creation_date[data[0] + \"_\" + to_string(obs.m_ref.GetYear())] += obs.m_ref.GetJDay();\r\n\r\n\t\t\t//if (i == 1 && obs.m_obs[i] <= -999 && stod(data[i + 5]) > -999)\r\n\t\t\t\t//obs.m_obs[i] = stod(data[i + 5]);//second method\r\n\r\n\t\t\tif (obs.m_obs[i] > -999)\r\n\t\t\t{\r\n\t\t\t\tm_nb_days[i] += obs.m_ref.GetJDay();\r\n\t\t\t\tm_years[i].insert(obs.m_ref.GetYear());\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tm_SAResult.push_back(obs);\r\n\r\n\r\n\t\t//}\r\n\r\n\r\n\t}\r\n\r\n\tdouble GetSimX(size_t s, CTRef TRefO, double obs, const CModelStatVector& output)\r\n\t{\r\n\t\tdouble x = -999;\r\n\r\n\t\tif (obs > -999)\r\n\t\t{\r\n\t\t\t//if (obs > 0.01 && obs < 99.99)\r\n\t\t\tif (obs >= 100)\r\n\t\t\t\tobs = 99.99;//to avoid some problem of truncation\r\n\r\n\t\t\tlong index = output.GetFirstIndex(s, \">=\", obs, 1, CTPeriod(TRefO.GetYear(), FIRST_MONTH, FIRST_DAY, TRefO.GetYear(), LAST_MONTH, LAST_DAY));\r\n\t\t\tif (index >= 1)\r\n\t\t\t{\r\n\t\t\t\tdouble obsX1 = output.GetFirstTRef().GetJDay() + index;\r\n\t\t\t\tdouble obsX2 = output.GetFirstTRef().GetJDay() + index + 1;\r\n\r\n\t\t\t\tdouble obsY1 = output[index][s];\r\n\t\t\t\tdouble obsY2 = output[index + 1][s];\r\n\t\t\t\tif (obsY2 != obsY1)\r\n\t\t\t\t{\r\n\t\t\t\t\tdouble slope = (obsX2 - obsX1) / (obsY2 - obsY1);\r\n\t\t\t\t\tdouble obsX = obsX1 + (obs - obsY1)*slope;\r\n\t\t\t\t\tASSERT(!_isnan(obsX) && _finite(obsX));\r\n\r\n\t\t\t\t\tx = obsX;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\treturn x;\r\n\t}\r\n\r\n\tbool CLaricobiusNigrinusModel::IsParamValid()const\r\n\t{\r\n\t\tif (m_OVP[Τᴴ¹] >= m_OVP[Τᴴ²])\r\n\t\t\treturn false;\r\n\r\n\r\n\t\tbool bValid = true;\r\n\t\tfor (size_t s = 0; s <= NB_STAGES && bValid; s++)\r\n\t\t{\r\n\t\t\tif (s == EGG || s == LARVAE /*|| s == AESTIVAL_DIAPAUSE_ADULT*/)\r\n\t\t\t{\r\n\t\t\t\tCStatistic rL;\r\n\t\t\t\tfor (double Э = 0.01; Э < 0.5; Э += 0.01)\r\n\t\t\t\t{\r\n\t\t\t\t\tdouble r = 1.0 - log((pow(Э, m_RDR[s][Ϙ]) - 1.0) / (pow(0.5, m_RDR[s][Ϙ]) - 1.0)) / m_RDR[s][к];\r\n\t\t\t\t\tif (r >= 0.4 && r <= 2.5)\r\n\t\t\t\t\t\trL += 1.0 / r;//reverse for comparison\r\n\t\t\t\t}\r\n\r\n\t\t\t\tCStatistic rH;\r\n\t\t\t\tfor (double Э = 0.51; Э < 1.0; Э += 0.01)\r\n\t\t\t\t{\r\n\t\t\t\t\tdouble r = 1.0 - log((pow(Э, m_RDR[s][Ϙ]) - 1.0) / (pow(0.5, m_RDR[s][Ϙ]) - 1.0)) / m_RDR[s][к];\r\n\t\t\t\t\tif (r >= 0.4 && r <= 2.5)\r\n\t\t\t\t\t\trH += r;\r\n\t\t\t\t}\r\n\r\n\t\t\t\tif (rL.IsInit() && rH.IsInit())\r\n\t\t\t\t\tbValid = fabs(rL[SUM] - rH[SUM]) < 5.3; //in Régnière (2012) obtain a max of 5.3\r\n\t\t\t\telse\r\n\t\t\t\t\tbValid = false;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\treturn bValid;\r\n\t}\r\n\r\n\r\n\r\n\tvoid CLaricobiusNigrinusModel::CalibrateDiapauseEndTh(CStatisticXY& stat)\r\n\t{\r\n\t\tstatic const double DiapauseDuration[3][3] =\r\n\t\t{\r\n\t\t\t{128.1,127.9,134.0},\r\n\t\t\t{156.7,162.2,166.2},\r\n\t\t\t{194.8,203.7,-999}\r\n\t\t};\r\n\r\n\t\tstatic const double DiapauseDurationSD[3][3] =\r\n\t\t{\r\n\t\t\t{2.2,3,\t3.8},\r\n\t\t\t{4.1,4.4,5.4},\r\n\t\t\t{4.2,3.4,10.8}\r\n\t\t};\r\n\r\n\t\tif (m_SAResult.size() != 8)\r\n\t\t\treturn;\r\n\r\n\r\n\t\tfor (size_t t = 0; t < 3; t++)\r\n\t\t{\r\n\t\t\tfor (size_t dl = 0; dl < 3; dl++)\r\n\t\t\t{\r\n\t\t\t\tif (DiapauseDuration[t][dl] > -999)\r\n\t\t\t\t{\r\n\t\t\t\t\t//NbVal = 8\tBias = 0.00263\tMAE = 0.95222\tRMSE = 1.25691\tCD = 0.99785\tR² = 0.99786\r\n\t\t\t\t\t//lam0 = 15.81011 {  15.80907, 15.81142}\tVM = { 0.00021,   0.00060 }\r\n\t\t\t\t\t//lam1 = 2.50857 {   2.50779, 2.50943}\tVM = { 0.00021,   0.00073 }\r\n\t\t\t\t\t//lam2 = 6.64395 {   6.63745, 6.64922}\tVM = { 0.00113,   0.00379 }\r\n\t\t\t\t\t//lam3 = 7.81911 {   7.80857, 7.82666}\tVM = { 0.00183,   0.00492 }\r\n\t\t\t\t\t//lam_a = 0.16346 {   0.16328, 0.16369}\tVM = { 0.00006,   0.00019 }\r\n\t\t\t\t\t//lam_b = 0.26484 {   0.26458, 0.26499}\tVM = { 0.00007,   0.00020 }\r\n\r\n\t\t\t\t\tdouble T = 10 + 5 * t;\r\n\t\t\t\t\tdouble DL = 8 + dl * 4;\r\n\t\t\t\t\tdouble DD = 120.0 + (215.0 - 120.0) * 1 / (1 + exp(-(T - m_ADE[ʎ0]) / m_ADE[ʎ1]));\r\n\t\t\t\t\tdouble f = exp(-m_ADE[ʎa] + m_ADE[ʎb] * 1 / (1 + exp(-(DL - m_ADE[ʎ2]) / m_ADE[ʎ3])));\r\n\r\n\t\t\t\t\tstat.Add(DiapauseDuration[t][dl], DD * f);\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\n\tstatic const int ROUND_VAL = 4;\r\n\tCTRef CLaricobiusNigrinusModel::GetDiapauseEnd(const CWeatherYear& weather)\r\n\t{\r\n\t\tCTPeriod p = weather.GetEntireTPeriod(CTM(CTM::DAILY));\r\n\t\t//return  p.Begin() + 253;\r\n\r\n\r\n\r\n\r\n\t\tdouble sumDD = 0;\r\n\t\t//for (CTRef TRef = p.Begin()+172; TRef <= p.End()&& TRef<= p.Begin() + int(m_ADE[ʎ0]); TRef++)\r\n\t\tfor (CTRef TRef = p.Begin() + int(m_ADE[ʎ0]-1); TRef <= p.End() && TRef <= p.Begin() + int(m_ADE[ʎ1]-1); TRef++)\r\n\t\t{\r\n\t\t\t//size_t ii = TRef - p.Begin();\r\n\t\t\tconst CWeatherDay& wday = m_weather.GetDay(TRef);\r\n\t\t\tdouble T = wday[H_TNTX][MEAN];\r\n\r\n\t\t\tT = CLaricobiusNigrinus::AdjustTLab(wday.GetWeatherStation()->m_name, NOT_INIT, wday.GetTRef(), T);\r\n\t\t\t//T = Round(max(m_ADE[ʎa], T), ROUND_VAL);\r\n\r\n\t\t\tdouble DD = min(0.0, T - m_ADE[ʎb]);//DD is negative\r\n\r\n\t\t\tsumDD += DD;\r\n\t\t}\r\n\r\n\r\n\t\t\r\n\t\t//boost::math::weibull_distribution<double> begin_dist(-m_ADE[ʎ2], m_ADE[ʎ3]);\r\n//\t\tint begin = (int)Round(m_ADE[ʎ0] + m_ADE[ʎa] * cdf(begin_dist, -sumDD), 0);\r\n\r\n\t\tboost::math::logistic_distribution<double> begin_dist(m_ADE[ʎ2], m_ADE[ʎ3]);\r\n\t\tint begin = (int)Round(m_ADE[ʎ1] + m_ADE[ʎa] * cdf(begin_dist, sumDD), 0);\r\n\t\treturn  p.Begin() + begin;\r\n\r\n\r\n\r\n\t}\r\n\r\n\r\n\tvoid CLaricobiusNigrinusModel::CalibrateDiapauseEnd(const bitset<3>& test, CStatisticXY& stat)\r\n\t{\r\n\t\tfor (size_t EVALUATE_STAGE = 0; EVALUATE_STAGE < NB_INPUTS; EVALUATE_STAGE++)\r\n\t\t\t//for (size_t j = 0; j < NB_INPUTS; j++)\r\n\t\t{\r\n\t\t\tif (test[EVALUATE_STAGE])\r\n\t\t\t{\r\n\r\n\t\t\t\tif (m_OVP[Τᴴ¹] >= m_OVP[Τᴴ²])\r\n\t\t\t\t\treturn;\r\n\r\n\r\n\t\t\t\tif (m_SAResult.empty())\r\n\t\t\t\t\treturn;\r\n\r\n\t\t\t\tif (!m_weather.IsHourly())\r\n\t\t\t\t\tm_weather.ComputeHourlyVariables();\r\n\r\n\r\n\r\n\t\t\t\tfor (size_t y = 0; y < m_weather.GetNbYears(); y++)\r\n\t\t\t\t{\r\n\t\t\t\t\tint year = m_weather[y].GetTRef().GetYear();\r\n\t\t\t\t\tif (m_years[EVALUATE_STAGE].find(year) == m_years[EVALUATE_STAGE].end())\r\n\t\t\t\t\t\tcontinue;\r\n\r\n\r\n\r\n\t\t\t\t\tdouble sumDD = 0;\r\n\t\t\t\t\tvector<double> CDD;\r\n\t\t\t\t\tCTPeriod p;\r\n\r\n\t\t\t\t\tif (EVALUATE_STAGE == I_EMERGED_ADULT)\r\n\t\t\t\t\t{\r\n\r\n\t\t\t\t\t\tp = m_weather[year].GetEntireTPeriod(CTM(CTM::DAILY));\r\n\t\t\t\t\t\tCDD.resize(p.size(), 0);\r\n\r\n\t\t\t\t\t\tCTRef diapauseEnd = GetDiapauseEnd(m_weather[year]);\r\n\t\t\t\t\t\tfor (CTRef TRef = diapauseEnd; TRef <= p.End(); TRef++)\r\n\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\tconst CWeatherDay& wday = m_weather.GetDay(TRef);\r\n\t\t\t\t\t\t\tdouble T = wday[H_TNTX][MEAN];\r\n\t\t\t\t\t\t\tT = CLaricobiusNigrinus::AdjustTLab(wday.GetWeatherStation()->m_name, NOT_INIT, wday.GetTRef(), T);\r\n\r\n\t\t\t\t\t\t\t//double DD = max(0.0, T - 4.0);//DD is negative\r\n\t\t\t\t\t\t\t//T = min(T, m_OVP[Τᴴ²]);\r\n\t\t\t\t\t\t\tdouble DD = max(0.0, T - m_EAS[Τᴴ]);//DD is positive\r\n\r\n\t\t\t\t\t\t\tsumDD += DD;\r\n\r\n\t\t\t\t\t\t\tsize_t ii = TRef - p.Begin();\r\n\t\t\t\t\t\t\tCDD[ii] = sumDD;\r\n\t\t\t\t\t\t}\r\n\r\n\r\n\r\n\t\t\t\t\t}\r\n\t\t\t\t\telse\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tp = m_weather[year].GetEntireTPeriod(CTM(CTM::DAILY));\r\n\t\t\t\t\t\t//p.Begin() = GetDiapauseEnd(m_weather[year - 1]);\r\n\r\n\t\t\t\t\t\tCDD.resize(p.size(), 0);\r\n\r\n\t\t\t\t\t\tCDegreeDays DDModel(CDegreeDays::MODIFIED_ALLEN_WAVE, m_OVP[Τᴴ¹], m_OVP[Τᴴ²]);\r\n\r\n\t\t\t\t\t\tfor (CTRef TRef = p.Begin(); TRef <= p.End(); TRef++)\r\n\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\tconst CWeatherDay& wday = m_weather.GetDay(TRef);\r\n\t\t\t\t\t\t\tsize_t ii = TRef - p.Begin();\r\n\t\t\t\t\t\t\tsumDD += DDModel.GetDD(wday);\r\n\t\t\t\t\t\t\tCDD[ii] = sumDD;\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\r\n\r\n\r\n\t\t\t\t\tfor (size_t i = 0; i < m_SAResult.size(); i++)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tsize_t ii = m_SAResult[i].m_ref - p.Begin();\r\n\t\t\t\t\t\tif (m_SAResult[i].m_ref.GetYear() == year && ii < CDD.size())\r\n\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\tdouble obs_y = m_SAResult[i].m_obs[EVALUATE_STAGE];\r\n\r\n\t\t\t\t\t\t\tif (obs_y > -999)\r\n\t\t\t\t\t\t\t{\r\n\r\n\t\t\t\t\t\t\t\tdouble sim_y = 0;\r\n\r\n\t\t\t\t\t\t\t\tif (EVALUATE_STAGE == I_EMERGED_ADULT)\r\n\t\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\t\tboost::math::logistic_distribution<double> emerged_dist(m_EAS[μ], m_EAS[ѕ]);\r\n\t\t\t\t\t\t\t\t\t//boost::math::weibull_distribution<double> emerged_dist(m_EAS[μ], m_EAS[ѕ]);\r\n\t\t\t\t\t\t\t\t\tsim_y = Round(cdf(emerged_dist, CDD[ii]) * 100, ROUND_VAL);\r\n\r\n\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\telse\r\n\t\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\t\tboost::math::logistic_distribution<double> create_dist(m_OVP[μ], m_OVP[ѕ]);\r\n\t\t\t\t\t\t\t\t\t//boost::math::weibull_distribution<double> create_dist(m_OVP[μ], m_OVP[ѕ]);\r\n\t\t\t\t\t\t\t\t\tsim_y = Round(cdf(create_dist, CDD[ii]) * 100, ROUND_VAL);\r\n\r\n\t\t\t\t\t\t\t\t}\r\n\r\n\r\n\t\t\t\t\t\t\t\tif (sim_y < 0.1)\r\n\t\t\t\t\t\t\t\t\tsim_y = 0;\r\n\t\t\t\t\t\t\t\tif (sim_y > 99.9)\r\n\t\t\t\t\t\t\t\t\tsim_y = 100;\r\n\r\n\t\t\t\t\t\t\t\tstat.Add(obs_y, sim_y);\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}//for all years\r\n\t\t\t}//if\r\n\t\t}//for\r\n\t\treturn;\r\n\r\n\t}\r\n\r\n\r\n\tvoid CLaricobiusNigrinusModel::CalibrateOviposition(CStatisticXY& stat)\r\n\t{\r\n\t\tif (m_SAResult.empty())\r\n\t\t\treturn;\r\n\r\n\t\tfor (size_t y = 0; y < m_weather.GetNbYears(); y++)\r\n\t\t{\r\n\t\t\tint year = m_weather[y].GetTRef().GetYear();\r\n\t\t\tstring key = m_info.m_loc.m_ID + \"_\" + to_string(year);\r\n\r\n\t\t\tif (m_egg_creation_date.find(key) == m_egg_creation_date.end())\r\n\t\t\t\tcontinue;\r\n\r\n\t\t\t//CTRef emergingBegin = GetDiapauseEnd(m_weather[year-1]);\r\n\r\n\r\n\t\t\tASSERT(m_weather[year].HavePrevious());\r\n\r\n\t\t\tif (m_weather[year].HavePrevious())\r\n\t\t\t{\r\n\t\t\t\tCStatistic Tmin;\r\n\t\t\t\tTmin += m_weather[year - 1][NOVEMBER][H_TMIN];\r\n\t\t\t\tTmin += m_weather[year - 1][DECEMBER][H_TMIN];\r\n\t\t\t\tTmin += m_weather[year][JANUARY][H_TMIN];\r\n\t\t\t\tTmin += m_weather[year][FEBRUARY][H_TMIN];\r\n\r\n\t\t\t\tCStatistic Tmean;\r\n\t\t\t\tTmean += m_weather[year - 1][NOVEMBER][H_TNTX];\r\n\t\t\t\tTmean += m_weather[year - 1][DECEMBER][H_TNTX];\r\n\t\t\t\tTmean += m_weather[year][JANUARY][H_TNTX];\r\n\t\t\t\tTmean += m_weather[year][FEBRUARY][H_TNTX];\r\n\r\n\r\n\t\t\t\tdouble obs = m_egg_creation_date.at(key);\r\n\t\t\t\tdouble sim = m_ADE[ʎa] - m_ADE[ʎb] * 1 / (1 + exp(-(Tmean[MEAN] - m_ADE[ʎ2]) / m_ADE[ʎ3]));\r\n\r\n\t\t\t\tif (sim < 0.1)\r\n\t\t\t\t\tsim = 0;\r\n\t\t\t\tif (sim > 99.9)\r\n\t\t\t\t\tsim = 100;\r\n\r\n\t\t\t\tstat.Add(obs, sim);\r\n\t\t\t}\r\n\r\n\r\n\t\t}\r\n\t\treturn;\r\n\r\n\t}\r\n\r\n\tvoid CLaricobiusNigrinusModel::GetFValueDaily(CStatisticXY& stat)\r\n\t{\r\n\t\tbitset<3> test;\r\n\t\ttest.reset();\r\n\r\n\t\t//test.set(I_EGGS);\r\n\t\t//test.set(I_LARVAE);\r\n\t\ttest.set(I_EMERGED_ADULT);\r\n\r\n\t\t//return CalibrateDiapauseEndTh(stat);\r\n\t\treturn CalibrateDiapauseEnd(test, stat);\r\n\t\t//return CalibrateOviposition(stat);\r\n\r\n\t\tif (!m_SAResult.empty())\r\n\t\t{\r\n\t\t\tif (!m_bCumul)\r\n\t\t\t\tm_bCumul = true;//SA always cumulative\r\n\r\n\t\t\tif (!m_weather.IsHourly())\r\n\t\t\t\tm_weather.ComputeHourlyVariables();\r\n\r\n\t\t\t//low and hi relative development rate must be approximatively the same\r\n\t\t\t//if (!IsParamValid())\r\n\t\t\t\t//return;\r\n\r\n\r\n\r\n\t\t\tfor (size_t y = 0; y < m_weather.GetNbYears(); y++)\r\n\t\t\t{\r\n\t\t\t\tint year = m_weather[y].GetTRef().GetYear();\r\n\t\t\t\tif ((test[0] && m_years[I_EGGS].find(year) != m_years[I_EGGS].end()) ||\r\n\t\t\t\t\t(test[1] && m_years[I_LARVAE].find(year) != m_years[I_LARVAE].end()) ||\r\n\t\t\t\t\t(test[2] && m_years[I_EMERGED_ADULT].find(year) != m_years[I_EMERGED_ADULT].end()))\r\n\t\t\t\t{\r\n\r\n\t\t\t\t\tCModelStatVector output;\r\n\t\t\t\t\tCTPeriod p = m_weather[y].GetEntireTPeriod(CTM(CTM::DAILY));\r\n\t\t\t\t\t//not possible to add a second year without having problem in evaluation....\r\n\t\t\t\t\t//if (m_weather[y].HaveNext())\r\n\t\t\t\t\t\t//p.End() = m_weather[y + 1].GetEntireTPeriod(CTM(CTM::DAILY)).End();\r\n\r\n\t\t\t\t\toutput.Init(p, NB_STATS, 0);\r\n\t\t\t\t\tExecuteDaily(m_weather[y].GetTRef().GetYear(), m_weather, output);\r\n\r\n\t\t\t\t\tstatic const size_t STAT_STAGE[3] = { S_EGG, S_LARVAE, S_ACTIVE_ADULT };\r\n\r\n\t\t\t\t\tfor (size_t i = 0; i < m_SAResult.size(); i++)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tif (output.IsInside(m_SAResult[i].m_ref))\r\n\t\t\t\t\t\t{\r\n\r\n\t\t\t\t\t\t\tfor (size_t j = 0; j < NB_INPUTS; j++)\r\n\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\tif (test[j])\r\n\t\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\t\tdouble obs_y = Round(m_SAResult[i].m_obs[j], ROUND_VAL);\r\n\t\t\t\t\t\t\t\t\tdouble sim_y = Round(output[m_SAResult[i].m_ref][STAT_STAGE[j]], ROUND_VAL);\r\n\r\n\t\t\t\t\t\t\t\t\tif (obs_y > -999)\r\n\t\t\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\t\t\tstat.Add(obs_y, sim_y);\r\n\r\n\t\t\t\t\t\t\t\t\t\tdouble obs_x = m_SAResult[i].m_ref.GetJDay();\r\n\t\t\t\t\t\t\t\t\t\tdouble sim_x = GetSimX(STAT_STAGE[j], m_SAResult[i].m_ref, obs_y, output);\r\n\r\n\t\t\t\t\t\t\t\t\t\t/*if (sim_x > -999)\r\n\t\t\t\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\t\t\t\tobs_x = Round(100 * (obs_x - m_nb_days[j][LOWEST]) / m_nb_days[j][RANGE],ROUND_VAL);\r\n\t\t\t\t\t\t\t\t\t\t\tsim_x = Round(100 * (sim_x - m_nb_days[j][LOWEST]) / m_nb_days[j][RANGE],ROUND_VAL);\r\n\t\t\t\t\t\t\t\t\t\t\tstat.Add(obs_x, sim_x);\r\n\t\t\t\t\t\t\t\t\t\t}*/\r\n\t\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}\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}//for all results\r\n\t\t\t\t}//have data\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n}\r\n", "meta": {"hexsha": "da8feca8fbce7724e1fcd8314d05b800f7562425", "size": 19921, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "wbsModels/LaricobiusNigrinus/LaricobiusNigrinusModel.cpp", "max_stars_repo_name": "RNCan/WeatherBasedSimulationFramework", "max_stars_repo_head_hexsha": "19df207d11b1dddf414d78e52bece77f31d45df8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2017-05-26T21:19:41.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-03T14:17:29.000Z", "max_issues_repo_path": "wbsModels/LaricobiusNigrinus/LaricobiusNigrinusModel.cpp", "max_issues_repo_name": "RNCan/WeatherBasedSimulationFramework", "max_issues_repo_head_hexsha": "19df207d11b1dddf414d78e52bece77f31d45df8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2016-02-18T12:39:58.000Z", "max_issues_repo_issues_event_max_datetime": "2016-03-13T12:57:45.000Z", "max_forks_repo_path": "wbsModels/LaricobiusNigrinus/LaricobiusNigrinusModel.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": 26.5613333333, "max_line_length": 145, "alphanum_fraction": 0.5747201446, "num_tokens": 7054, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7371581741774411, "lm_q2_score": 0.44167300566462553, "lm_q1q2_score": 0.325582866439198}}
{"text": "\n\n/* --------------------------------------------------------------------- \n * \n * Copyright (C) 2014 - 2020 by the deal.II authors \n * \n * This file is part of the deal.II library. \n * \n * The deal.II library is free software; you can use it, redistribute \n * it, and/or modify it under the terms of the GNU Lesser General \n * Public License as published by the Free Software Foundation; either \n * version 2.1 of the License, or (at your option) any later version. \n * The full text of the license can be found in the file LICENSE.md at \n * the top level directory of deal.II. \n * \n * --------------------------------------------------------------------- \n * \n * Authors: Wolfgang Bangerth, Texas A&M University, 2014 \n *          Luca Heltai, SISSA, 2014 \n *          D. Sarah Stamps, MIT, 2014 \n */ \n\n\n\n// 让我们从这里需要的包含文件开始。显然，我们需要描述三角形的文件（  <code>tria.h</code>  ），以及允许我们创建和输出三角形的文件（  <code>grid_generator.h</code>  和  <code>grid_out.h</code>  ）。此外，我们需要声明Manifold和ChartManifold类的头文件，我们将需要这些类来描述几何体（ <code>manifold.h</code> ）。然后我们还需要以下头文件中的 GridTools::transform() 函数；这个函数的用途将在我们使用它时讨论。\n\n#include <deal.II/grid/tria.h> \n#include <deal.II/grid/grid_generator.h> \n#include <deal.II/grid/grid_out.h> \n#include <deal.II/grid/manifold.h> \n#include <deal.II/grid/grid_tools.h> \n\n// 其余的包含文件与读取地形数据有关。正如介绍中所解释的，我们将从一个文件中读取它，然后使用下面头文件中第一个声明的 Functions::InterpolatedUniformGridData  类。因为数据很大，所以我们读取的文件是以gzip压缩数据的形式存储的，我们利用BOOST提供的一些功能来直接读取gzipped数据。\n\n#include <deal.II/base/function_lib.h> \n\n#include <boost/iostreams/filtering_stream.hpp> \n#include <boost/iostreams/filter/gzip.hpp> \n#include <boost/iostreams/device/file.hpp> \n\n#include <fstream> \n#include <iostream> \n#include <memory> \n\n// 上事的最后部分是打开一个命名空间，把所有东西都放进去，然后把dealii命名空间导入其中。\n\nnamespace Step53 \n{ \n  using namespace dealii; \n// @sect3{Describing topography: AfricaTopography}  \n\n// 这个程序的第一个重要部分是描述地形 $h(\\hat phi,\\hat \\theta)$ 作为经度和纬度的函数的类。正如在介绍中所讨论的那样，我们在这里将使我们的生活更容易一些，不以最普遍的方式来写这个类，而是只为我们在这里感兴趣的特定目的来写：插值从一个非常具体的数据文件中获得的数据，该文件包含了关于世界上一个特定地区的信息，我们知道该地区的范围。\n\n// 该类的总体布局已经在上面讨论过了。下面是它的声明，包括我们在初始化 <code>topography_data</code> 成员变量时需要的三个静态成员函数。\n\n  class AfricaTopography \n  { \n  public: \n    AfricaTopography(); \n\n    double value(const double lon, const double lat) const; \n\n  private: \n    const Functions::InterpolatedUniformGridData<2> topography_data; \n\n    static std::vector<double> get_data(); \n  }; \n\n// 让我们来看看这个类的实现。该类的有趣部分是构造函数和 <code>value()</code> 函数。前者初始化了 Functions::InterpolatedUniformGridData 成员变量，我们将使用这个构造函数，它要求我们传入我们要插值的二维数据集的端点（这里由区间 $[-6.983333, 11.98333]$ 给出）。 ]，使用介绍中讨论的切换端点的技巧，和 $[25, 35.983333]$ ，都是以度数给出的），数据被分割成的区间数（纬度方向379，经度方向219，总共 $380\\times 220$ 个数据点），和一个包含数据的表对象。然后，数据的大小当然是 $380\\times 220$ ，我们通过提供一个迭代器给下面 std::vector 函数返回的 <code>get_data()</code> 对象的83,600个元素中的第一个来初始化它。注意，我们在这里调用的所有成员函数都是静态的，因为(i)它们不访问类的任何成员变量，(ii)因为它们是在对象没有完全初始化的时候调用的。\n\n  AfricaTopography::AfricaTopography() \n    : topography_data({{std::make_pair(-6.983333, 11.966667), \n                        std::make_pair(25, 35.95)}}, \n                      {{379, 219}}, \n                      Table<2, double>(380, 220, get_data().begin())) \n  {} \n\n  double AfricaTopography::value(const double lon, const double lat) const \n  { \n    return topography_data.value( \n      Point<2>(-lat * 180 / numbers::PI, lon * 180 / numbers::PI)); \n  } \n\n// 唯一一个更有意义的函数是 <code>get_data()</code> 函数。它返回一个临时向量，其中包含描述高度的所有83600个数据点，并从文件 <code>topography.txt.gz</code> 中读取。因为文件被gzip压缩了，所以我们不能直接通过类型为 std::ifstream, 的对象来读取它，但在BOOST库中有一些方便的方法（见http:www.boost.org），允许我们从压缩的文件中读取，而不用先在磁盘上解压缩。其结果是，基本上，只是另一个输入流，就所有的实际目的而言，看起来就像我们一直使用的那些输入流。\n\n// 当读取数据时，我们读取三列数据，但忽略了前两列。最后一列的数据被附加到一个数组中，我们返回的数组将被复制到 <code>topography_data</code> 的表中，并被初始化。由于BOOST.iostreams库在输入文件不存在、不可读或不包含正确的数据行数时没有提供非常有用的异常，我们捕捉它可能产生的所有异常并创建我们自己的异常。为此，在 <code>catch</code> 子句中，我们让程序运行到一个 <code>AssertThrow(false, ...)</code> 语句中。由于条件总是假的，这总是会触发一个异常。换句话说，这相当于写了 <code>throw ExcMessage(\"...\")</code> ，但它也填补了异常对象中的某些字段，这些字段以后会被打印在屏幕上，识别出发生异常的函数、文件和行。\n\n  std::vector<double> AfricaTopography::get_data() \n  { \n    std::vector<double> data; \n\n// 创建一个流，我们从gzipped数据中读取\n\n    boost::iostreams::filtering_istream in; \n    in.push(boost::iostreams::basic_gzip_decompressor<>()); \n    in.push(boost::iostreams::file_source(\"topography.txt.gz\")); \n\n    for (unsigned int line = 0; line < 83600; ++line) \n      { \n        try \n          { \n            double lat, lon, elevation; \n            in >> lat >> lon >> elevation; \n\n            data.push_back(elevation); \n          } \n        catch (...) \n          { \n            AssertThrow(false, \n                        ExcMessage(\"Could not read all 83,600 data points \" \n                                   \"from the file <topography.txt.gz>!\")); \n          } \n      } \n\n    return data; \n  } \n// @sect3{Describing the geometry: AfricaGeometry}  \n\n// 下面的类是本程序的主类。它的结构已经在介绍中详细描述过了，不需要再多做介绍。\n\n  class AfricaGeometry : public ChartManifold<3, 3> \n  { \n  public: \n    virtual Point<3> pull_back(const Point<3> &space_point) const override; \n\n    virtual Point<3> push_forward(const Point<3> &chart_point) const override; \n\n    virtual std::unique_ptr<Manifold<3, 3>> clone() const override; \n\n  private: \n    static const double R; \n    static const double ellipticity; \n\n    const AfricaTopography topography; \n\n    Point<3> push_forward_wgs84(const Point<3> &phi_theta_d) const; \n    Point<3> pull_back_wgs84(const Point<3> &x) const; \n\n    Point<3> push_forward_topo(const Point<3> &phi_theta_d_hat) const; \n    Point<3> pull_back_topo(const Point<3> &phi_theta_d) const; \n  }; \n\n  const double AfricaGeometry::R           = 6378137; \n  const double AfricaGeometry::ellipticity = 8.1819190842622e-2; \n\n// 如果你读过介绍，实现起来也是非常简单的。特别是，回拉和前推函数都只是WGS 84和地形图映射各自函数的串联。\n\n  Point<3> AfricaGeometry::pull_back(const Point<3> &space_point) const \n  { \n    return pull_back_topo(pull_back_wgs84(space_point)); \n  } \n\n  Point<3> AfricaGeometry::push_forward(const Point<3> &chart_point) const \n  { \n    return push_forward_wgs84(push_forward_topo(chart_point)); \n  } \n\n// 下一个函数是Manifold基类的接口所要求的，它允许克隆AfricaGeometry类。注意，虽然该函数返回一个  `std::unique_ptr<Manifold<3,3>>`,  我们在内部创建了一个 `unique_ptr<AfricaGeometry>`。换句话说，这个库需要一个指向基类的指针，我们通过创建一个指向派生类的指针来提供这个指针。\n\n  std::unique_ptr<Manifold<3, 3>> AfricaGeometry::clone() const \n  { \n    return std::make_unique<AfricaGeometry>(); \n  } \n\n// 下面的两个函数就定义了对应于地球WGS84参考形状的正向和反向变换。正向变换遵循介绍中所示的公式。反变换要复杂得多，至少不是直观的。它还存在一个问题，即它返回一个角度，在函数结束时，如果它应该从那里逃出来，我们需要将其夹回区间 $[0,2\\pi]$ 。\n\n  Point<3> AfricaGeometry::push_forward_wgs84(const Point<3> &phi_theta_d) const \n  { \n    const double phi   = phi_theta_d[0]; \n    const double theta = phi_theta_d[1]; \n    const double d     = phi_theta_d[2]; \n\n    const double R_bar = R / std::sqrt(1 - (ellipticity * ellipticity * \n                                            std::sin(theta) * std::sin(theta))); \n\n    return {(R_bar + d) * std::cos(phi) * std::cos(theta), \n            (R_bar + d) * std::sin(phi) * std::cos(theta), \n            ((1 - ellipticity * ellipticity) * R_bar + d) * std::sin(theta)}; \n  } \n\n  Point<3> AfricaGeometry::pull_back_wgs84(const Point<3> &x) const \n  { \n    const double b   = std::sqrt(R * R * (1 - ellipticity * ellipticity)); \n    const double ep  = std::sqrt((R * R - b * b) / (b * b)); \n    const double p   = std::sqrt(x(0) * x(0) + x(1) * x(1)); \n    const double th  = std::atan2(R * x(2), b * p); \n    const double phi = std::atan2(x(1), x(0)); \n    const double theta = \n      std::atan2(x(2) + ep * ep * b * std::pow(std::sin(th), 3), \n                 (p - \n                  (ellipticity * ellipticity * R * std::pow(std::cos(th), 3)))); \n    const double R_bar = \n      R / (std::sqrt(1 - ellipticity * ellipticity * std::sin(theta) * \n                           std::sin(theta))); \n    const double R_plus_d = p / std::cos(theta); \n\n    Point<3> phi_theta_d; \n    if (phi < 0) \n      phi_theta_d[0] = phi + 2 * numbers::PI; \n    else if (phi > 2 * numbers::PI) \n      phi_theta_d[0] = phi - 2 * numbers::PI; \n    else \n      phi_theta_d[0] = phi; \n    phi_theta_d[1] = theta; \n    phi_theta_d[2] = R_plus_d - R_bar; \n    return phi_theta_d; \n  } \n\n// 与此相反，地形变换完全按照介绍中的描述进行。因此，没有什么可以补充的。\n\n  Point<3> \n  AfricaGeometry::push_forward_topo(const Point<3> &phi_theta_d_hat) const \n  { \n    const double d_hat = phi_theta_d_hat[2]; \n    const double h = topography.value(phi_theta_d_hat[0], phi_theta_d_hat[1]); \n    const double d = d_hat + (d_hat + 500000) / 500000 * h; \n    return {phi_theta_d_hat[0], phi_theta_d_hat[1], d}; \n  } \n\n  Point<3> AfricaGeometry::pull_back_topo(const Point<3> &phi_theta_d) const \n  { \n    const double d     = phi_theta_d[2]; \n    const double h     = topography.value(phi_theta_d[0], phi_theta_d[1]); \n    const double d_hat = 500000 * (d - h) / (500000 + h); \n    return {phi_theta_d[0], phi_theta_d[1], d_hat}; \n  } \n// @sect3{Creating the mesh}  \n\n// 在描述了几何体的属性之后，现在是处理用于离散它的网格的时候了。为此，我们为几何体和三角形创建对象，然后继续创建一个与参考域 $1\\times 2\\times 1$ 相对应的 $\\hat U=[26,35]\\times[-10,5]\\times[-500000,0]$ 矩形网格。我们选择这个数目的细分，因为它导致了单元格大致上像立方体，而不是在某个方向上被拉伸。\n\n// 当然，我们实际上对参考域的网格划分不感兴趣。我们感兴趣的是对真实域的网格划分。因此，我们将使用 GridTools::transform() 函数，它只是根据一个给定的变换来移动三角形的每个点。它想要的变换函数是一个将参考域中的一个点作为其单一参数的函数，并返回我们想要映射到的域中的相应位置。当然，这正是我们使用的几何学的前推函数。我们用一个lambda函数来包装它，以获得转换所需的那种函数对象。\n\n  void run() \n  { \n    AfricaGeometry   geometry; \n    Triangulation<3> triangulation; \n\n    { \n      const Point<3> corner_points[2] = { \n        Point<3>(26 * numbers::PI / 180, -10 * numbers::PI / 180, -500000), \n        Point<3>(35 * numbers::PI / 180, 5 * numbers::PI / 180, 0)}; \n      std::vector<unsigned int> subdivisions(3); \n      subdivisions[0] = 1; \n      subdivisions[1] = 2; \n      subdivisions[2] = 1; \n      GridGenerator::subdivided_hyper_rectangle( \n        triangulation, subdivisions, corner_points[0], corner_points[1], true); \n\n      GridTools::transform( \n        [&geometry](const Point<3> &chart_point) { \n          return geometry.push_forward(chart_point); \n        }, \n        triangulation); \n    } \n\n// 下一步是向三角计算说明，在细化网格时，每当需要一个新的点时，都要使用我们的几何对象。我们通过告诉三角计算对所有流形指示器为零的物体使用我们的几何体，然后继续用流形指示器为零标记所有单元及其边界面和边。这确保了三角计算在每次需要新的顶点时都会参考我们的几何对象。由于流形指标是由母体继承给子体的，这也会在几个递归细化步骤之后发生。\n\n    triangulation.set_manifold(0, geometry); \n    for (const auto &cell : triangulation.active_cell_iterators()) \n      cell->set_all_manifold_ids(0); \n\n// 最后一步是在最初的 $1\\times 2\\times 1$ 粗略网格之外细化该网格。我们可以在全局范围内细化若干次，但由于本教程程序的目的，我们实际上只对靠近表面的情况感兴趣，所以我们只是对所有在边界上有一个指标为5的面的单元进行6次细化。在我们上面使用的 GridGenerator::subdivided_hyper_rectangle() 函数的文档中查找，发现边界指标5对应于域的顶面（这就是上面调用 GridGenerator::subdivided_hyper_rectangle() 的最后一个 <code>true</code> 参数的含义：通过给每个边界分配一个独特的边界指标来给边界 \"着色\"）。\n\n    for (unsigned int i = 0; i < 6; ++i) \n      { \n        for (const auto &cell : triangulation.active_cell_iterators()) \n          for (const auto &face : cell->face_iterators()) \n            if (face->boundary_id() == 5) \n              { \n                cell->set_refine_flag(); \n                break; \n              } \n        triangulation.execute_coarsening_and_refinement(); \n\n        std::cout << \"Refinement step \" << i + 1 << \": \" \n                  << triangulation.n_active_cells() << \" cells, \" \n                  << GridTools::minimal_cell_diameter(triangulation) / 1000 \n                  << \"km minimal cell diameter\" << std::endl; \n      } \n\n// 做完这一切，我们现在可以将网格输出到一个自己的文件中。\n\n    const std::string filename = \"mesh.vtu\"; \n    std::ofstream     out(filename); \n    GridOut           grid_out; \n    grid_out.write_vtu(triangulation, out); \n  } \n} // namespace Step53 \n\n//  @sect3{The main function}  \n\n// 最后是主函数，它采用了从  step-6  开始的所有教程程序中使用的相同方案。这里没有什么可做的，只需要调用单一的  <code>run()</code>  函数。\n\nint main() \n{ \n  try \n    { \n      Step53::run(); \n    } \n  catch (std::exception &exc) \n    { \n      std::cerr << std::endl \n                << std::endl \n                << \"----------------------------------------------------\" \n                << std::endl; \n      std::cerr << \"Exception on processing: \" << std::endl \n                << exc.what() << std::endl \n                << \"Aborting!\" << std::endl \n                << \"----------------------------------------------------\" \n                << std::endl; \n\n      return 1; \n    } \n  catch (...) \n    { \n      std::cerr << std::endl \n                << std::endl \n                << \"----------------------------------------------------\" \n                << std::endl; \n      std::cerr << \"Unknown exception!\" << std::endl \n                << \"Aborting!\" << std::endl \n                << \"----------------------------------------------------\" \n                << std::endl; \n      return 1; \n    } \n} \n\n\n", "meta": {"hexsha": "428f1a71ccb19aed856254a660ce32758562aef9", "size": 12542, "ext": "cc", "lang": "C++", "max_stars_repo_path": "Translator_file/examples/step-53/step-53.cc", "max_stars_repo_name": "jiaqiwang969/deal.ii-course-practice", "max_stars_repo_head_hexsha": "0da5ad1537d8152549d8a0e4de5872efe7619c8a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Translator_file/examples/step-53/step-53.cc", "max_issues_repo_name": "jiaqiwang969/deal.ii-course-practice", "max_issues_repo_head_hexsha": "0da5ad1537d8152549d8a0e4de5872efe7619c8a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Translator_file/examples/step-53/step-53.cc", "max_forks_repo_name": "jiaqiwang969/deal.ii-course-practice", "max_forks_repo_head_hexsha": "0da5ad1537d8152549d8a0e4de5872efe7619c8a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.1215805471, "max_line_length": 464, "alphanum_fraction": 0.6266943071, "num_tokens": 5086, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6039318337259584, "lm_q2_score": 0.538983220687684, "lm_q1q2_score": 0.3255091248174359}}
{"text": "// This file is part of KWIVER, and is distributed under the\n// OSI-approved BSD 3-Clause License. See top-level LICENSE file or\n// https://github.com/Kitware/kwiver/blob/master/LICENSE for details.\n\n/// \\file\n/// Operations to calculate closest points and ray intersections\n/// to triangles and meshes.\n\n#include \"mesh_intersect.h\"\n\n#include <limits>\n\n#include <vital/logger/logger.h>\n\n#include <Eigen/Geometry>\n\nnamespace kwiver {\n\nnamespace arrows {\n\nnamespace core {\n\nusing namespace kwiver::vital;\n\n// ----------------------------------------------------------------------------\nbool\nmesh_intersect_triangle(\n  const point_3d& p, const vector_3d& d, const point_3d& a, const point_3d& b,\n  const point_3d& c, double& dist, double& u, double& v )\n{\n  vector_3d n( ( b.value() - a.value() ).cross( c.value() - a.value() ) );\n  return mesh_intersect_triangle( p, d, a, b, c, n, dist, u, v );\n}\n\n// ----------------------------------------------------------------------------\nbool\nmesh_intersect_triangle(\n  const point_3d& p, const vector_3d& d, const point_3d& a, const point_3d& b,\n  const point_3d& c, const vector_3d& n, double& dist, double& u, double& v )\n{\n  double denom = -d.dot( n );\n\n  if( denom <= 0 ) // back facing triangles\n  {\n    return false;\n  }\n\n  vector_3d ap( p.value() - a.value() );\n  vector_3d t( d.cross( ap ) );\n  v = ( b.value() - p.value() ).dot( t );\n  if( v < 0.0 || v > denom )\n  {\n    return false;\n  }\n\n  u = -( c.value() - p.value() ).dot( t );\n  if( u < 0.0 || u + v > denom )\n  {\n    return false;\n  }\n\n  dist = ap.dot( n );\n  if( dist < 0.0 )\n  {\n    return false;\n  }\n\n  u /= denom;\n  v /= denom;\n  dist /= denom;\n\n  return true;\n}\n\n// ----------------------------------------------------------------------------\nbool\nmesh_intersect_triangle_min_dist(\n  const point_3d& p, const vector_3d& d, const point_3d& a, const point_3d& b,\n  const point_3d& c, const vector_3d& n, double& dist, double& u, double& v )\n{\n  double denom = -d.dot( n );\n\n  if( denom <= 0 ) // back facing triangles\n  {\n    return false;\n  }\n\n  vector_3d ap( p.value() - a.value() );\n  double new_dist = ap.dot( n ) / denom;\n\n  if( new_dist < 0.0 || new_dist > dist )\n  {\n    return false;\n  }\n\n  vector_3d t( d.cross( ap ) );\n  v = ( b.value() - p.value() ).dot( t );\n  if( v < 0.0 || v > denom )\n  {\n    return false;\n  }\n\n  u = -( c.value() - p.value() ).dot( t );\n  if( u < 0.0 || u + v > denom )\n  {\n    return false;\n  }\n\n  dist = new_dist;\n  u /= denom;\n  v /= denom;\n\n  return true;\n}\n\n// ----------------------------------------------------------------------------\nunsigned char\nmesh_triangle_closest_point(\n  const point_3d& p, const point_3d& a, const point_3d& b, const point_3d& c,\n  const vector_3d& n, double& dist, double& u, double& v )\n{\n  double denom = 1.0 / n.squaredNorm();\n\n  vector_3d ap( p.value() - a.value() );\n  vector_3d bp( p.value() - b.value() );\n  vector_3d cp( p.value() - c.value() );\n\n  vector_3d t( n.cross( ap ) );\n  v = bp.dot( t ) * denom;\n  u = -cp.dot( t ) * denom;\n\n  vector_3d ab( b.value() - a.value() );\n  vector_3d bc( c.value() - b.value() );\n  vector_3d ca( a.value() - c.value() );\n\n  double eps = std::numeric_limits< double >::epsilon();\n\n  unsigned char state = 0;\n  double uv;\n  if( u <= eps )\n  {\n    double p_v = v - u * ab.dot( ca ) / ca.squaredNorm();\n\n    if( p_v <= eps )\n    {\n      state = 1;\n    }\n    else if( p_v >= 1.0 )\n    {\n      state = 4;\n    }\n    else\n    {\n      u = 0.0;\n      v = p_v;\n      dist = ( ( 1 - v ) * ap + v * cp ).norm();\n      return 5;\n    }\n  }\n  if( v <= eps )\n  {\n    double p_u = u - v * ca.dot( ab ) / ab.squaredNorm();\n\n    if( p_u <= eps )\n    {\n      state = 1;\n    }\n    else if( p_u >= 1.0 )\n    {\n      state = 2;\n    }\n    else\n    {\n      u = p_u;\n      v = 0.0;\n      dist = ( ( 1 - u ) * ap + u * bp ).norm();\n      return 3;\n    }\n  }\n  if( ( uv = 1.0 - u - v ) <= eps )\n  {\n    double s = -ca.dot( bc ) / bc.squaredNorm();\n    double p_u = u + uv * s;\n    double p_v = v + uv * ( 1.0 - s );\n    if( p_v <= eps )\n    {\n      state = 2;\n    }\n    else if( p_u <= eps )\n    {\n      state = 4;\n    }\n    else\n    {\n      u = p_u;\n      v = p_v;\n      dist = ( u * bp + v * cp ).norm();\n      return 6;\n    }\n  }\n\n  switch( state )\n  {\n    case 1:\n      u = 0.0;\n      v = 0.0;\n      dist = ap.norm();\n      return 1;\n    case 2:\n      u = 1.0;\n      v = 0.0;\n      dist = bp.norm();\n      return 2;\n    case 4:\n      u = 0.0;\n      v = 1.0;\n      dist = cp.norm();\n      return 4;\n    default:\n      dist = std::abs( ap.dot( n ) * std::sqrt( denom ) );\n      return 7;\n  }\n\n  return 0;\n}\n\n// ----------------------------------------------------------------------------\nunsigned char\nmesh_triangle_closest_point(\n  const point_3d& p, const point_3d& a, const point_3d& b, const point_3d& c,\n  double& dist, double& u, double& v )\n{\n  vector_3d n( ( b.value() - a.value() ).cross( c.value() - a.value() ) );\n  return mesh_triangle_closest_point( p, a, b, c, n, dist, u, v );\n}\n\n// ----------------------------------------------------------------------------\nvital::point_3d\nmesh_triangle_closest_point(\n  const point_3d& p, const point_3d& a, const point_3d& b, const point_3d& c,\n  double& dist )\n{\n  double u, v;\n  mesh_triangle_closest_point( p, a, b, c, dist, u, v );\n\n  double t = 1 - u - v;\n  return point_3d( t * a[ 0 ] + u * b[ 0 ] + v * c[ 0 ],\n                   t * a[ 1 ] + u * b[ 1 ] + v * c[ 1 ],\n                   t * a[ 2 ] + u * b[ 2 ] + v * c[ 2 ] );\n}\n\n// ----------------------------------------------------------------------------\nint\nmesh_closest_point(\n  const point_3d& p, const mesh& mesh, point_3d& cp, double& u, double& v )\n{\n  // check for a triangular mesh\n  if( mesh.faces().regularity() != 3 )\n  {\n    LOG_ERROR( vital::get_logger( \"arrows.core.mesh_closest_point\" ),\n               \"Closest point calculation requires triangular mesh.\" );\n    return -1;\n  }\n\n  const mesh_vertex_array< 3 >& verts = mesh.vertices< 3 >();\n  const mesh_regular_face_array< 3 >& faces =\n    static_cast< const mesh_regular_face_array< 3 >& >( mesh.faces() );\n\n  int isect = -1;\n  double u1, v1;\n  double shortest_dist = std::numeric_limits< double >::infinity();\n\n  for( unsigned int i = 0; i < faces.size(); ++i )\n  {\n    const mesh_regular_face< 3 >& f = faces[ i ];\n    vital::point_3d a( verts[ f[ 0 ] ] );\n    vital::point_3d b( verts[ f[ 1 ] ] );\n    vital::point_3d c( verts[ f[ 2 ] ] );\n    double dist = shortest_dist;\n    if( mesh_triangle_closest_point( p, a, b, c, dist, u1, v1 ) &&\n        dist < shortest_dist )\n    {\n      u = u1;\n      v = v1;\n      isect = i;\n      shortest_dist = dist;\n    }\n  }\n\n  // Get the closest point in physical space from barycentric coordinates\n  double t = 1 - u - v;\n  const mesh_regular_face< 3 >& f = faces[ isect ];\n  vital::point_3d a( verts[ f[ 0 ] ] );\n  vital::point_3d b( verts[ f[ 1 ] ] );\n  vital::point_3d c( verts[ f[ 2 ] ] );\n  cp.set_value( vector_3d( t * a[ 0 ] + u * b[ 0 ] + v * c[ 0 ],\n                           t * a[ 1 ] + u * b[ 1 ] + v * c[ 1 ],\n                           t * a[ 2 ] + u * b[ 2 ] + v * c[ 2 ] ) );\n  return isect;\n}\n\n// ----------------------------------------------------------------------------\nint\nmesh_intersect(\n  const point_3d& p, const vector_3d& d, const mesh& mesh, double& dist,\n  double& u, double& v )\n{\n  // check for a triangular mesh\n  if( mesh.faces().regularity() != 3 )\n  {\n    LOG_ERROR( vital::get_logger( \"arrows.core.mesh_closest_point\" ),\n               \"Closest point calculation requires triangular mesh.\" );\n    return -1;\n  }\n\n  // Calculate normals if needed\n  if( !mesh.faces().has_normals() )\n  {\n    LOG_ERROR( vital::get_logger( \"arrows.core.mesh_closest_point\" ),\n               \"Closest point calculation requires faces normals.\" );\n    return -1;\n  }\n\n  const mesh_vertex_array< 3 >& verts = mesh.vertices< 3 >();\n  const mesh_regular_face_array< 3 >& faces =\n    static_cast< const mesh_regular_face_array< 3 >& >( mesh.faces() );\n\n  // Check that normal magnitude corresponds to face area\n  if( ( ( verts[ faces[ 0 ][ 1 ] ] - verts[ faces[ 0 ][ 0 ] ] )\n        .cross( verts[ faces[ 0 ][ 2 ] ] - verts[ faces[ 0 ][ 0 ] ] ) -\n        0.5 * faces.normal( 0 ) ).norm() < 1e-14 )\n  {\n    LOG_ERROR( vital::get_logger(\n                 \"arrows.core.mesh_closest_point\" ),\n               \"Closest point calculation requires faces normal lengths be set to face area.\" );\n    return -1;\n  }\n\n  int isect = -1;\n  dist = std::numeric_limits< double >::infinity();\n  for( unsigned int i = 0; i < faces.size(); ++i )\n  {\n    const mesh_regular_face< 3 >& f = faces[ i ];\n    vital::point_3d a( verts[ f[ 0 ] ] );\n    vital::point_3d b( verts[ f[ 1 ] ] );\n    vital::point_3d c( verts[ f[ 2 ] ] );\n    if( mesh_intersect_triangle_min_dist( p, d, a, b, c, faces.normal( i ),\n                                          dist, u, v ) )\n    {\n      isect = i;\n    }\n  }\n  return isect;\n}\n\n} // namespace core\n\n} // namespace arrows\n\n} // namespace kwiver\n", "meta": {"hexsha": "8c00940d995a1815b1077aecba35278725ed5b84", "size": 8987, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "arrows/core/mesh_intersect.cxx", "max_stars_repo_name": "johnwparent/kwiver", "max_stars_repo_head_hexsha": "ef12afb416653d7f268e5b38f0a5768a486f7e44", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 176.0, "max_stars_repo_stars_event_min_datetime": "2015-07-31T23:33:37.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-21T23:42:44.000Z", "max_issues_repo_path": "arrows/core/mesh_intersect.cxx", "max_issues_repo_name": "johnwparent/kwiver", "max_issues_repo_head_hexsha": "ef12afb416653d7f268e5b38f0a5768a486f7e44", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1276.0, "max_issues_repo_issues_event_min_datetime": "2015-05-03T01:21:27.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T15:32:20.000Z", "max_forks_repo_path": "arrows/core/mesh_intersect.cxx", "max_forks_repo_name": "johnwparent/kwiver", "max_forks_repo_head_hexsha": "ef12afb416653d7f268e5b38f0a5768a486f7e44", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 85.0, "max_forks_repo_forks_event_min_datetime": "2015-01-25T05:13:38.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-14T14:59:37.000Z", "avg_line_length": 24.8947368421, "max_line_length": 96, "alphanum_fraction": 0.5059530433, "num_tokens": 2814, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7431680086124811, "lm_q2_score": 0.43782349911420193, "lm_q1q2_score": 0.32537641796044986}}
{"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#include \"utility/openmp.hpp\"\n\n#include \"geometry/meshop.hpp\"\n#include \"geometry/mesh-voxelizer.hpp\"\n#include \"math/geometry_core.hpp\"\n#include \"imgproc/scanconversion.hpp\"\n\n//#include <opencv2/opencv.hpp>\n\n#include <boost/lexical_cast.hpp>\n#include <boost/numeric/ublas/vector.hpp>\n\n#include <algorithm>\n//#define RASTERIZE_MESH_DEBUG\n\n\n\nnamespace geometry{\n\nMeshVoxelizer::MeshVoxelizer(const Parameters &params){\n    params_ = params;\n}\n\nvoid MeshVoxelizer::add( geometry::Mesh & mesh ){\n    meshes.push_back(&mesh);\n}\n\nvoid MeshVoxelizer::voxelize(){\n    if(meshes.size()<=0){\n        LOG( warn2 )<<\"Zero meshes to voxelize. Skipping voxelization.\";\n        return;\n    }\n\n    //add floor to mimic closed mesh\n    std::vector<geometry::Mesh> seals;\n    if(params_.addSeal){\n        for(auto & mesh: meshes){\n            seals.push_back(sealOfMesh(*mesh));\n        }\n    }\n\n    //compute united extents\n    math::Extents3 extents(math::InvalidExtents{});\n    for(auto & mesh: meshes){\n        math::Extents3 meshExtents = math::computeExtents(mesh->vertices);\n        extents = math::unite(extents, meshExtents);\n    }\n    for(auto & mesh: seals){\n        math::Extents3 meshExtents = math::computeExtents(mesh.vertices);\n        extents = math::unite(extents, meshExtents);\n    }\n\n    LOG( info2 )<<\"Meshes extents: \"<<extents;\n\n    // volume size\n\n    {\n        math::Point3 extentsSize = extents.ur-extents.ll;\n        math::Point3i volumeGridRes(\n                    std::ceil(extentsSize(0)/params_.voxelSize)\n                    ,std::ceil(extentsSize(1)/params_.voxelSize)\n                    ,std::ceil(extentsSize(2)/params_.voxelSize));\n        math::Point3 newExtentsSize = volumeGridRes*params_.voxelSize;\n        math::Point3 extentsCenter = math::center(extents);\n\n        extents = math::Extents3( extentsCenter-newExtentsSize/2\n                                 , extentsCenter+newExtentsSize/2);\n\n        if ( valid(params_.overrideExtents) ) {\n            LOG(info2) << \"Using supplied extents for voxelization.\";\n\n            extents = params_.overrideExtents;\n\n            for (uint i(0); i < 3; ++i) {\n                volumeGridRes(i)\n                    = std::ceil(size(extents)(i)/params_.voxelSize);\n            }\n        }\n\n        LOG(info2) << \"Volumetric grid resolution: \" << volumeGridRes;\n        LOG(info2) << \"Volume extents: \" << extents;\n    }\n\n\n    //generate directions for 3 main axes + axes of icosahedron faces\n    std::vector<math::Point3> directions;\n    directions.push_back(-math::Point3(1,0,0));\n    directions.push_back(-math::Point3(0,1,0));\n    directions.push_back(-math::Point3(0,0,1));\n\n    directions.push_back(-math::Point3(1,1,1));\n    directions.push_back(-math::Point3(1,-1, 1));\n    directions.push_back(-math::Point3(-1,1,1));\n    directions.push_back(-math::Point3(-1,-1,1));\n    directions.push_back(-math::Point3(1,0,1));\n    directions.push_back(-math::Point3(-1,0,1));\n    directions.push_back(-math::Point3(0,1,1));\n    directions.push_back(-math::Point3(0,-1,1));\n    directions.push_back(-math::Point3(1,1,0));\n    directions.push_back(-math::Point3(1,-1,0));\n\n    //generate projection matrices and layered zbuffers\n\n    Projections projections;\n    ProjectionResults results;\n    for(const auto & dir: directions){\n        Projection projection = orthoProj( dir, extents, params_.voxelSize);\n        projections.push_back(projection);\n    }\n\n    LOG( info2 )<<\"Rasterizing meshes\";\n    //rasterize mesh using generated projection matrices\n    for(uint p=0; p<projections.size(); ++p){\n        LayeredZBuffer buffer(projections[p].viewportSize);\n        for(auto & mesh: meshes){\n            rasterizeMesh(*mesh, projections[p].transformation, buffer);\n        }\n        for(auto & mesh: seals){\n            rasterizeMesh(mesh, projections[p].transformation, buffer);\n        }\n        buffer.sortCells();\n        results.push_back(ProjectionResult( projections[p].transformation\n                                      , CompressedLayeredZBuffer(buffer)));\n    }\n\n#ifdef RASTERIZE_MESH_DEBUG\n    uint i=0;\n    for( auto &proj : results){\n        fs::path path = fs::path(std::string(\"depth\")\n                                 +boost::lexical_cast<std::string>(i++)\n                                 +std::string(\".png\"));\n        visualizeDepthMap(proj, extents ,path);\n    }\n#endif\n\n\n\n    //create new volume\n    /**************\n     * Ugly hack (shaveVolume)\n     *\n     * Voxelization has problems with edges - create volume 2*cells\n     * smaller from both x and y directions\n     *\n     * Voxelization itself should be fixed instead\n     **************************/\n    {\n        math::Size3i volSize( std::ceil( size(extents)(0)/params_.voxelSize )\n                            , std::ceil( size(extents)(1)/params_.voxelSize )\n                            , std::ceil( size(extents)(2)/params_.voxelSize ));\n\n        math::Point3 ll( extents.ll(0)\n                       , extents.ll(1)\n                       , extents.ll(2));\n\n        if (params_.shaveVolume) {\n            for (uint i(0); i < 2; ++i) {\n                // strip 2 from each side\n                volSize(i) -= 4;\n                // shift extents's ll by 2 voxel size because that is what we stripped\n                ll(i) += 2*params_.voxelSize;\n            }\n        }\n\n        // prepare volume for filtering and downsampling: reserve space so all\n        // dimensions can be inflated to closest larger odd value\n        // add few layers of cells on the ceiling of the volume as a margin\n        // for subsampling.\n        math::Size3i capacity( volSize(0) + !(volSize(0) % 2)\n                             , volSize(1) + !(volSize(1) % 2)\n                             , volSize(2) + !(volSize(2) % 2) + 4);\n\n        LOG(info2) << \"Creating volume of size \" << volSize\n                   << \" and capacity \" << capacity;\n\n\n        volume_ = std::unique_ptr<Volume>( new Volume( ll\n                                                     , params_.voxelSize\n                                                     , volSize\n                                                     , VoxelizerUnit::empty()\n                                                     , capacity));\n    }\n\n    math::Size3i vSize = volume_->cSize();\n    long long volMem = (long long)vSize.width * vSize.height\n                    * vSize.depth * sizeof(unsigned short);\n    LOG( info2 )<<\"Memory consumption of volume: \"\n        << volMem/1024.0/1024.0/1024.0 << \" GB.\";\n\n    long long mem = 0;\n    for(auto res : results){\n        mem += res.buffer.mem();\n    }\n\n    LOG( info2 )<<\"Memory consumption of zbuffers: \"\n        << mem/1024.0/1024.0/1024.0 << \" GB.\";\n\n\n    uint progress = 0;\n    LOG( info2 )<<\"Voxelization progress: \"<<progress;\n#ifdef _OPENMP\n    #pragma omp parallel for schedule( dynamic, 10 )\n#endif\n    for(int x=0; x< vSize.width; ++x){\n        for(int y=0; y< vSize.height; ++y){\n            for(int z=0; z< vSize.depth; ++z){\n                //voxel center position\n                auto voxCenter\n                        = volume_->grid2geo(math::Point3(x,y,z));\n                if(isInside({voxCenter.x, voxCenter.y, voxCenter.z}, results)){\n                        volume_->set( x, y, z,VoxelizerUnit::full());\n                }\n\n            }\n        }\n        //voxelization progress\n        uint newProgress = std::ceil((float)x/vSize.width * 100);\n        if(newProgress>progress){\n            progress=newProgress;\n            LOG( info2 )<<\"Voxelization progress: \"<<progress;\n        }\n    }\n\n    if(params_.addSeal){\n        LOG( info2 )<<\"Filling volume from seal\";\n        fillVolumeFromSeal();\n    }\n}\n\nstd::shared_ptr<MeshVoxelizer::Volume> MeshVoxelizer::volume(){\n    return volume_;\n}\n\nvoid MeshVoxelizer::reset(){\n    std::vector<geometry::Mesh*>().swap(meshes);\n}\n\n\nMeshVoxelizer::Projection MeshVoxelizer::orthoProj(const math::Point3 &direction\n                            , const math::Extents3 &extents\n                            , const float &voxelSize\n                            ){\n    LOG( debug )<<\"Projection direction: \"<<direction;\n    LOG( debug )<<\"Mesh extents: \"<<extents;\n\n    math::Point3 normalizedDir = math::normalize(direction);\n\n    math::Matrix4 projMat = ublas::identity_matrix<double>(4);\n    //translate so the center of the extents is in the middle\n    math::Point3 extentsCenter = math::center(extents);\n    projMat(0,3) = -extentsCenter[0];\n    projMat(1,3) = -extentsCenter[1];\n    projMat(2,3) = -extentsCenter[2];\n\n    //LOG( debug )<<\"Projection matrix - after centering: \"<<projMat;\n\n    //rotate scene in specified direction\n    math::Matrix4 rotation = ublas::identity_matrix<double>(4);\n\n    math::Point3 up(0,0,-1);\n    if(std::abs(ublas::inner_prod(normalizedDir,math::Point3(0,0,1)))==1){\n        up = math::Point3(0,1,0);\n    }\n    math::Point3 right = math::normalize(math::crossProduct(up,direction));\n    up = math::normalize(math::crossProduct(normalizedDir,right));\n\n    auto c1 = ublas::row(rotation,0);\n    auto c2 = ublas::row(rotation,1);\n    auto c3 = ublas::row(rotation,2);\n\n    ublas::subrange(c1,0,3) = right;\n    ublas::subrange(c2,0,3) = up;\n    ublas::subrange(c3,0,3) = normalizedDir;\n\n    projMat = prod(rotation,projMat);\n\n    //find out extents images\n    math::Extents2 viewExtents(math::InvalidExtents{});\n    math::Points3 extPoints;\n    extPoints.push_back(math::Point3(extents.ll[0],extents.ll[1],extents.ll[2]));\n    extPoints.push_back(math::Point3(extents.ll[0],extents.ll[1],extents.ur[2]));\n    extPoints.push_back(math::Point3(extents.ll[0],extents.ur[1],extents.ll[2]));\n    extPoints.push_back(math::Point3(extents.ll[0],extents.ur[1],extents.ur[2]));\n    extPoints.push_back(math::Point3(extents.ur[0],extents.ll[1],extents.ll[2]));\n    extPoints.push_back(math::Point3(extents.ur[0],extents.ll[1],extents.ur[2]));\n    extPoints.push_back(math::Point3(extents.ur[0],extents.ur[1],extents.ll[2]));\n    extPoints.push_back(math::Point3(extents.ur[0],extents.ur[1],extents.ur[2]));\n\n    for(const auto &point : extPoints){\n        math::Point3 pointImg = transform(projMat,point);\n        viewExtents.ll[0] = std::min(pointImg[0],viewExtents.ll[0]);\n        viewExtents.ll[1] = std::min(pointImg[1],viewExtents.ll[1]);\n        viewExtents.ur[0] = std::max(pointImg[0],viewExtents.ur[0]);\n        viewExtents.ur[1] = std::max(pointImg[1],viewExtents.ur[1]);\n    }\n\n    //scale scene so the extents fit to space < -1,1 > CC/NDC\n    math::Matrix4 scaleMat = ublas::identity_matrix<double>(4);\n    scaleMat(0,0) = 2./size(viewExtents).width;\n    scaleMat(1,1) = 2./size(viewExtents).height;\n\n    projMat = prod(scaleMat, projMat);\n\n    //scale and transform scene to VC\n    math::Matrix4 transformMat = ublas::identity_matrix<double>(4);\n    transformMat(0,3)=1;\n    transformMat(1,3)=1;\n\n    //calculate viewport size\n    LOG( debug ) << \"View extents: \"<< viewExtents;\n\n    math::Size2 viewport( std::ceil(size(viewExtents).width/voxelSize)\n                        , std::ceil(size(viewExtents).height/voxelSize));\n\n    LOG( debug ) << \"Viewport:\" << viewport;\n\n    scaleMat = ublas::identity_matrix<double>(4);\n    scaleMat(0,0) = viewport.width/2;\n    scaleMat(1,1) = viewport.height/2;\n\n    projMat = prod(transformMat, projMat);\n    projMat = prod(scaleMat, projMat);\n\n    LOG( debug )<<\"Projection matrix - final from WC to CC: \"<<projMat;\n\n    for(const auto &point : extPoints){\n        math::Point3 pointImg = transform(projMat,point);\n        LOG( debug ) << point <<\" - \"<< pointImg;\n    }\n\n    return Projection(projMat, viewport);\n}\n\ngeometry::Mesh MeshVoxelizer::sealOfMesh(geometry::Mesh & mesh){\n\n    math::Extents3 extents = math::computeExtents(mesh.vertices);\n\n    float offset = params_.voxelSize * params_.sealFactor;\n\n    geometry::Mesh seal;\n    math::Point3 extSize = extents.ur-extents.ll;\n\n    double cellWidth = offset;\n\n    int cols=std::ceil(extSize(0)/cellWidth);\n    int rows=std::ceil(extSize(1)/cellWidth);\n\n    std::vector<std::vector<double>> minMap\n        = std::vector<std::vector<double>>(cols);\n    for(int x=0; x<cols; ++x){\n        minMap[x] = std::vector<double>(rows,INFINITY);\n    }\n\n    for(const auto& vertex: mesh.vertices){\n        int x = std::min((int)std::floor((vertex(0)-extents.ll(0))/cellWidth),cols-1);\n        int y = std::min((int)std::floor((vertex(1)-extents.ll(1))/cellWidth),rows-1);\n        minMap[x][y]=std::min(minMap[x][y],vertex(2));\n    }\n\n    for(int x=0; x< cols; ++x){\n        for(int y=0; y< rows; ++y){\n            if(x==0 || y==0 || x==cols-1 || y==rows-1){\n                //fill unsetted values\n                int searchOffset=1;\n                while(!std::isfinite(minMap[x][y])){\n                    for(int xoff=-searchOffset; xoff<searchOffset; ++xoff ){\n                        for(int yoff=-searchOffset; yoff<searchOffset; ++yoff ){\n                            if( x+xoff>0 && x+xoff<(int)cols\n                               && y+yoff>0 && y+yoff<(int)rows){\n                                minMap[x][y]=std::min( minMap[x][y]\n                                                     , minMap[x+xoff][y+yoff]);\n                            }\n                        }\n                    }\n                    searchOffset++;\n                    if(searchOffset>params_.sealFactor*2){\n                        minMap[x][y] = extents.ll(2);\n                    }\n                }\n            }\n        }\n    }\n\n    for(int x=1; x< cols-1; ++x){\n        for(int y=1; y< rows-1; ++y){\n            minMap[x][y] = extents.ll(2);\n        }\n    }\n\n    for(int y=0; y< rows; ++y){\n        for(int x=0; x< cols; ++x){\n            seal.vertices.push_back(\n                math::Point3( x*cellWidth+extents.ll(0)\n                            , y*cellWidth+extents.ll(1)\n                            , minMap[x][y]-offset ));\n        }\n    }\n\n    for(int x=0; x< cols-1; ++x){\n        for(int y=0; y< rows-1; ++y){\n            seal.addFace(x+(y*cols), x+1+((y+1)*cols), x+1+(y*cols));\n            seal.addFace(x+(y*cols), x+((y+1)*cols), x+1+((y+1)*cols));\n        }\n    }\n\n    return seal;\n}\n\nvoid MeshVoxelizer::fillVolumeFromSeal(){\n    math::Size3i vSize = volume_->cSize();\n    for(int x = 0;x<vSize.width; ++x){\n        for(int y = 0;y<vSize.height; ++y){\n            //find first full voxel from the direction of seal\n            int full = -1;\n            for(int z = 0;z<vSize.depth; ++z){\n                if(volume_->get(x,y,z)!=VoxelizerUnit::empty()){\n                        full = z;\n                        break;\n                }\n            }\n            //fill from bottom up\n            for(int z = 0;z<full; ++z){\n                volume_->set(x,y,z,VoxelizerUnit::full());\n            }\n        }\n    }\n}\n\nvoid MeshVoxelizer::rasterizeMesh( const Mesh &mesh\n                                 , const math::Matrix4 &projMat\n                                 , LayeredZBuffer & lZBuffer){\n    std::vector<imgproc::Scanline> scanlines;\n\n    LOG(info2) << \"rasterizing \" << mesh.faces.size() << \" triangles\";\n\n    // draw all faces into the zBuffer\n    for (const auto &face : mesh.faces)\n    {\n        cv::Point3f tri[3];\n\n        int i(0);\n        for (auto it(mesh.begin(face)); it != mesh.end(face); ++it, ++i) {\n            math::Point3d pt(transform(projMat, *it));\n            tri[i] = {float(pt(0)), float(pt(1)), float(pt(2))};\n        }\n\n        scanlines.clear();\n        imgproc::scanConvertTriangle(tri, 0, lZBuffer.size.height, scanlines);\n\n        for (const auto& sl : scanlines)\n        {\n            imgproc::processScanline(sl, 0, lZBuffer.size.width,\n                [&](int x, int y, float z) {\n                    lZBuffer.data[x][y].push_back(z);\n                } );\n        }\n    }\n\n\n}\n\nbool MeshVoxelizer::isInside( const math::Point3 & position\n                      ,  ProjectionResults & projectionResults){\n    uint inside=0;\n    uint outside=0;\n\n    uint projId = 0;\n    for(auto & proj : projectionResults){\n        math::Point3 projPos = math::transform(proj.transformation, position);\n        projId++;\n        if(params_.method==Method::PARITY_COUNT){\n            uint parity=0;\n            if(projPos[0]<proj.buffer.size.width\n                    && projPos[1]<proj.buffer.size.height\n                    && projPos[0]>0 && projPos[1]>0){\n                //std::cout<<proj.buffer.data[projPos[0]][projPos[1]].size()<<std::endl;\n                for(auto dit = proj.buffer.begin(projPos[0],projPos[1]);\n                        dit != proj.buffer.end(projPos[0],projPos[1]); ++dit){\n\n                    if(*dit<projPos[2]){\n                        parity++;\n                    }\n                    else{\n                        break;\n                    }\n                }\n                if(parity%2==1){\n                    inside++;\n                    continue;\n                }\n                outside++;\n            }\n        }\n\n        if(params_.method==Method::RAY_STABING){\n            if( projPos[2]<*proj.buffer.begin(projPos[0],projPos[1])\n               && projPos[2]>*proj.buffer.end(projPos[0],projPos[1])){\n                inside++;\n                continue;\n            }\n            outside++;\n        }\n    }\n\n    if(params_.method==Method::PARITY_COUNT){\n        if(inside>outside)\n            return true;\n    }\n    if(params_.method==Method::RAY_STABING){\n        if(outside==0)\n            return true;\n    }\n    return false;\n}\n\nvoid MeshVoxelizer::visualizeDepthMap( const ProjectionResult &proj\n                                      , const math::Extents3 & extents\n                                      , const fs::path & path){\n    cv::Mat depthMapImg( proj.buffer.size.height, proj.buffer.size.width\n                     , CV_8UC3, cv::Scalar(0,0,0));\n\n    float min = FLT_MAX;\n    float max = -FLT_MAX;\n\n    for(int x = 0; x < proj.buffer.size.width; ++x){\n        for(int y = 0; y < proj.buffer.size.height; ++y){\n            if(proj.buffer.begin(x,y) == proj.buffer.end(x,y)){\n                continue;\n            }\n            min = std::min(*proj.buffer.begin(x,y),min);\n            max = std::max(*std::prev(proj.buffer.end(x,y)),max);\n        }\n    }\n\n    float range = max-min;\n\n    LOG( debug )<<\"Minimal/maximal depth: \"<< min <<\" / \"<< max\n                << \" Range: \"<<range;\n\n    for(int x = 0; x < proj.buffer.size.width; ++x){\n        for(int y = 0; y < proj.buffer.size.height; ++y){\n            if(proj.buffer.begin(x,y) == proj.buffer.end(x,y)){\n                depthMapImg.at<cv::Vec3b>(y,x)=\n                        cv::Vec3b(0,0,255);\n                continue;\n            }\n            float val  = (*proj.buffer.begin(x,y) - min) / range;\n            depthMapImg.at<cv::Vec3b>(y,x)=\n                    cv::Vec3b(255-val*255,255-val*255,255-val*255);\n        }\n    }\n\n    math::Points3 extPoints;\n    extPoints.push_back(math::Point3(extents.ll[0],extents.ll[1],extents.ll[2]));\n    extPoints.push_back(math::Point3(extents.ll[0],extents.ll[1],extents.ur[2]));\n    extPoints.push_back(math::Point3(extents.ll[0],extents.ur[1],extents.ll[2]));\n    extPoints.push_back(math::Point3(extents.ll[0],extents.ur[1],extents.ur[2]));\n    extPoints.push_back(math::Point3(extents.ur[0],extents.ll[1],extents.ll[2]));\n    extPoints.push_back(math::Point3(extents.ur[0],extents.ll[1],extents.ur[2]));\n    extPoints.push_back(math::Point3(extents.ur[0],extents.ur[1],extents.ll[2]));\n    extPoints.push_back(math::Point3(extents.ur[0],extents.ur[1],extents.ur[2]));\n\n    for(auto &point : extPoints){\n        point = transform(proj.transformation,point);\n    }\n\n    cv::line(depthMapImg, cv::Point2f(extPoints[0][0],extPoints[0][1])\n            , cv::Point2f(extPoints[1][0],extPoints[1][1]),cv::Scalar(255,0,0),2);\n    cv::line(depthMapImg, cv::Point2f(extPoints[2][0],extPoints[2][1])\n            , cv::Point2f(extPoints[3][0],extPoints[3][1]),cv::Scalar(255,0,0),2);\n\n    cv::line(depthMapImg, cv::Point2f(extPoints[0][0],extPoints[0][1])\n            , cv::Point2f(extPoints[2][0],extPoints[2][1]),cv::Scalar(255,0,0),2);\n    cv::line(depthMapImg, cv::Point2f(extPoints[1][0],extPoints[1][1])\n            , cv::Point2f(extPoints[3][0],extPoints[3][1]),cv::Scalar(255,0,0),2);\n\n    cv::line(depthMapImg, cv::Point2f(extPoints[4][0],extPoints[4][1])\n            , cv::Point2f(extPoints[5][0],extPoints[5][1]),cv::Scalar(255,0,0),2);\n    cv::line(depthMapImg, cv::Point2f(extPoints[6][0],extPoints[6][1])\n            , cv::Point2f(extPoints[7][0],extPoints[7][1]),cv::Scalar(255,0,0),2);\n\n    cv::line(depthMapImg, cv::Point2f(extPoints[4][0],extPoints[4][1])\n            , cv::Point2f(extPoints[6][0],extPoints[6][1]),cv::Scalar(255,0,0),2);\n    cv::line(depthMapImg, cv::Point2f(extPoints[5][0],extPoints[5][1])\n            , cv::Point2f(extPoints[7][0],extPoints[7][1]),cv::Scalar(255,0,0),2);\n\n    cv::line(depthMapImg, cv::Point2f(extPoints[1][0],extPoints[1][1])\n            , cv::Point2f(extPoints[5][0],extPoints[5][1]),cv::Scalar(255,0,0),2);\n    cv::line(depthMapImg, cv::Point2f(extPoints[0][0],extPoints[0][1])\n            , cv::Point2f(extPoints[4][0],extPoints[4][1]),cv::Scalar(255,0,0),2);\n\n    cv::line(depthMapImg, cv::Point2f(extPoints[3][0],extPoints[3][1])\n            , cv::Point2f(extPoints[7][0],extPoints[7][1]),cv::Scalar(255,0,0),2);\n    cv::line(depthMapImg, cv::Point2f(extPoints[2][0],extPoints[2][1])\n            , cv::Point2f(extPoints[6][0],extPoints[6][1]),cv::Scalar(255,0,0),2);\n\n    cv::imwrite( path.string().c_str(), depthMapImg );\n}\n\n} //namespace geometry\n", "meta": {"hexsha": "493eee26a9c6ee3cc58497904a47d4a28e8bc47f", "size": 22845, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "geometry/mesh-voxelizer.cpp", "max_stars_repo_name": "tomas2211/libgeometry", "max_stars_repo_head_hexsha": "003c58cf92e46ac01d506987f47b770929cc799b", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2017-06-23T19:09:29.000Z", "max_stars_repo_stars_event_max_datetime": "2019-02-26T06:52:15.000Z", "max_issues_repo_path": "externals/browser/externals/browser/externals/libgeometry/geometry/mesh-voxelizer.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": 3.0, "max_issues_repo_issues_event_min_datetime": "2021-02-23T02:20:26.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-04T10:25:19.000Z", "max_forks_repo_path": "externals/browser/externals/browser/externals/libgeometry/geometry/mesh-voxelizer.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": 3.0, "max_forks_repo_forks_event_min_datetime": "2019-09-25T05:22:12.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-17T16:43:00.000Z", "avg_line_length": 36.4354066986, "max_line_length": 88, "alphanum_fraction": 0.5642810243, "num_tokens": 6170, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6406358548398982, "lm_q2_score": 0.5078118642792044, "lm_q1q2_score": 0.3253224877703505}}
{"text": "#include <stdlib.h> /* srand, rand */\n#include <iostream>\n#include <fstream> // creating (.csv) files\n#include <vector>\n#include <cstring>\n#include <string>\n#include <functional>\n#include <armadillo> // http://arma.sourceforge.net/docs.html\n#include <thread>    /* std::this_thread::sleep_for */\n\n\n#include \"EvolutionaryAlgorithm.hpp\"\n\n#include \"mypch.hpp\"\n\n#include \"EAController.hpp\"\n\n// NOT USED??\n// enum events{\n//     BASE_RATE = 0,\n//     MUTA_RATE,\n//     PRED_RATE,\n//     PART_RATE,\n//     GENO_RATE,\n//     EV_A_RATE,\n// };\n\nnamespace EvoAlg\n{\n    //arma::rowvec semiFinalsAndFinals[SEMI_FINALS][TOURNMENT_RATE];\n    //arma::rowvec indvFinals[TOURNMENT_RATE];\n    void EvolutionaryAlgorithm::saveBestIndvParamsCSV()\n    {\n        std::fstream myFile;\n        myFile.open(\"constValues.cfg\", std::ios_base::app);\n\n        myFile << attributesValues[0].name << \" = \" << population(bestFitIndex, 0);\n        for (size_t i = 1; i < NB_PARAMETERS; i++)\n            myFile << std::endl\n                   << attributesValues[i].name << \" = \" << population(bestFitIndex, i);\n        //printf(\"k%sk\\n\", parametersList[i]);\n        myFile.close();\n    }\n\n    // 1st step: initialize population\n    void EvolutionaryAlgorithm::initializePop(int tournmentType)\n    {\n        double minVal, maxVal;\n        std::cout << \"INITIALIZING POPULATION\\n\";\n        // for (int i = 0; i < POPULATION_SIZE; i++) {\n        //     for (int j = 0; j < NB_PARAMETERS; j++) {\n        //         population[i][j] = (double) (rand() % MAX_PARAM_VALUE); // number range = [0, MAX_PARAM_VALUE[\n        //     }\n        // }\n        population.randu(); // initialize with values between 0 and 1\n\n        //TODO: find a better way to pass a non-variable to lambda\n        // auto &_attributesValues = attributesValues;\n        if (tournmentType == INITIALS) {\n            int index = 0;\n            population.each_col([=, &index](arma::vec& popCol) { popCol = attributesValues[index].min + popCol * (attributesValues[index].max - attributesValues[index].min); index++; } );\n            // for(int j = 0; j < NB_PARAMETERS; j++)\n            //     population.col(j) = attributesValues[j].min + population.col(j)*(attributesValues[j].max - attributesValues[j].min); // if a normal EA is taking place, just multiply the population by a givern value\n        }\n        else\n        {\n            int middle = TOURNMENT_RATE + (POPULATION_SIZE - TOURNMENT_RATE) / 2;\n            fillInitialsWithBests(tournmentType);\n            for (int j = 0; j < NB_PARAMETERS; j++)\n            { // Min and max values are defined for each col, and converting the current col values to a number between this constraints.\n                // this starts after the first TOURNMENT_RATE individuls, and the remaining is divided into two pars, one with biased rand values, and other without\n                minVal = MIN_MULT * bestTournmentIndv[tournmentType].col(j).min();\n                maxVal = MAX_MULT * bestTournmentIndv[tournmentType].col(j).max();\n\n                for (int i = TOURNMENT_RATE; i < middle; i++)\n                {\n                    population(i, j) = minVal + (maxVal - minVal) * (population(i, j));\n                }\n            }\n            for (int i = middle; i < POPULATION_SIZE; i++)\n                for (int j = 0; j< NB_PARAMETERS; i++)\n                    population(i,j) = attributesValues[j].min + population(i,j)*(attributesValues[j].max - attributesValues[j].min);\n        }\n\n        population.print(\"Population matrix initialized:\");\n\n        \n\n        return;\n    }\n\n    // Function to normalize fitness (values between 0 and 1)\n    void EvolutionaryAlgorithm::normalizeFitness(double *normalizedFitness)\n    {\n        if (normalizedFitness == NULL)\n            return;\n\n        for (int i = 0; i < POPULATION_SIZE; i++)\n            normalizedFitness[i] = (fitness[i] - bestFitness) / (worstFitness - bestFitness);\n\n        return;\n    }\n\n    // 2nd step: evaluate population (calculate fitness)\n    void EvolutionaryAlgorithm::evaluatePop()\n    {\n        //Limit the values in each col\n        // for(int j = 0; j < NB_PARAMETERS; j++){\n        //     population.col(j) = arma::clamp(population.col(j),attributesValues[j].min,attributesValues[j].max);\n        // }\n        int index = 0;\n\n        //TODO: find a better way to pass a non-variable to lambda\n        auto &_attributesValues = attributesValues;\n        population.each_col([&_attributesValues, &index](arma::vec& popCol) { popCol = arma::clamp(popCol, _attributesValues[index].min, _attributesValues[index].max); index++; } );\n\n        std::cout << \"EVALUATING POPULATION\\n\";\n\n        nbNoImprovementGens++; // we begin considering there was no improvement in the generation\n\n\n        std::vector<std::vector<double>> populationVec2(population.n_rows);\n        for (size_t i = 0; i < population.n_rows; ++i)\n            populationVec2[i] = (arma::conv_to<std::vector<double>>::from(population.row(i)));\n\n        DE_TRACE(\"(EvolutionaryAlgorithm) Sending population to EAController to execute it\");\n        auto gameplayResults = m_EAController.RunPopulationInGame(populationVec2);\n        DE_TRACE(\"(EvolutionaryAlgorithm) Population received from EAController\");\n\n        DE_TRACE(\"Calculating fitness of population after gameplay results received\");\n        calcFitness(gameplayResults);\n\n        \n\n        for (int i = 0; i < POPULATION_SIZE; i++)\n        {\n            DE_ASSERT(fitness[i] >= 0);\n            if (fitness[i] < bestFitness)\n            { // searching for the  max fitness from new generation\n                bestFitness = fitness[i];\n                bestFitIndex = i;\n                nbNoImprovementGens = 0; // this generation shows improvement -> reset counter\n            }\n            else if (fitness[i] > worstFitness)\n            {\n                worstFitness = fitness[i];\n                worstFitIndex = i;\n            }\n\n            // printf(\"fitness[%d] %lf\\n\", i, fitness[i]);\n        }\n\n        printf(\"BEST FITNESS: %lf - INDEX: %d\\n\", bestFitness, bestFitIndex);\n        printf(\"WORST FITNESS: %lf - INDEX: %d\\n\", worstFitness, worstFitIndex);\n\n        return;\n    }\n\n    void EvolutionaryAlgorithm::crossover(int indv, arma::rowvec parent1, arma::rowvec parent2)\n    {\n        // for(int j = 0; j < NB_PARAMETERS; j++){\n        //     population[i][j] = (parent1[j] + parent2[j])/2.0;\n        // }\n        population.row(indv) = (parent1 + parent2) / 2.0;\n\n        return;\n    }\n\n    void EvolutionaryAlgorithm::elitism()\n    {\n        std::cout << \"ELITISM\\n\";\n        arma::rowvec bestIndv = population.row(bestFitIndex);\n\n        for (int i = 0; i < POPULATION_SIZE; i++)\n        {\n            // crossover\n            crossover(i, population.row(i), bestIndv);\n        }\n\n        return;\n    }\n\n    void EvolutionaryAlgorithm::tournament()\n    {\n        std::cout << \"TOURNAMENT\\n\";\n        arma::mat::fixed<POPULATION_SIZE, NB_PARAMETERS> oldPopulation;\n        int parentIndex[2];\n\n        // copying last population (new one will be different)\n        // for (int i = 0; i < POPULATION_SIZE; i++) {\n        //     for (int j = 0; j < NB_PARAMETERS; j++) {\n        //         oldPopulation[i][j] = population[i][j];\n        //     }\n        // }\n        oldPopulation = population;\n\n        for (int i = 0; i < POPULATION_SIZE; i++)\n        {\n            if (i == bestFitIndex)\n                continue;\n\n            // chossing parents for new individual\n            for (int j = 0; j < 2; j++)\n            {\n                int indexIndA = rand() % POPULATION_SIZE; // indv 1 that will \"fight\" to be parent\n                int indexIndB = rand() % POPULATION_SIZE; // indv 2 that will \"fight\" to be parent\n\n                parentIndex[j] = (fitness[indexIndA] < fitness[indexIndB] ? indexIndA : indexIndB);\n            }\n\n            // crossover\n            crossover(i, oldPopulation.row(parentIndex[0]), oldPopulation.row(parentIndex[1]));\n        }\n\n        return;\n    }\n\n    //TODO: swap priorities. Smaller fitness must be morre relevant\n    void EvolutionaryAlgorithm::roulette()\n    {\n        std::cout << \"ROULETTE\\n\";\n        arma::mat::fixed<POPULATION_SIZE, NB_PARAMETERS> oldPopulation;\n        double standardizedFitness[POPULATION_SIZE];\n        int parentIndex[2], rNb;\n        double probSum = 0.0, partialSum = 0.0;\n\n        (void) standardizedFitness[0];\n\n\n        // copying last population (new one will be different)\n        // for (int i = 0; i < POPULATION_SIZE; i++) {\n        //     for (int j = 0; j < NB_PARAMETERS; j++) {\n        //         oldPopulation[i][j] = population[i][j];\n        //     }\n        // }\n        oldPopulation = population;\n\n        // Standardize fitness (set probabilites that add up to 100%)\n        for (int i = 0; i < POPULATION_SIZE; i++)\n            probSum += fitness[i];\n        for (int i = 0; i < POPULATION_SIZE; i++)\n            standardizedFitness[i] = fitness[i] / probSum;\n\n        // Chosing new parents for each individual\n        for (int i = 0; i < POPULATION_SIZE; i++)\n        {\n            if (i == bestFitIndex) // preserves best individual\n                continue;\n\n            for (int k = 0; k < 2; k++)\n            {                                      // chosing 2 parents\n                rNb = ((double)rand() / RAND_MAX); // rand between 0 and 1\n                partialSum = 0.0;\n\n                for (int j = 0; j < POPULATION_SIZE; j++)\n                { // randomly chosing and individual according to its fitness (+fitness = +probabity)\n                    partialSum += fitness[j];\n                    if (partialSum >= rNb)\n                    {\n                        parentIndex[k] = j; // new parent at index j\n                        break;\n                    }\n                }\n            }\n\n            // crossover\n            crossover(i, oldPopulation.row(parentIndex[0]), oldPopulation.row(parentIndex[1]));\n        }\n    }\n\n    void EvolutionaryAlgorithm::mutate(int indIndex)\n    {\n        int plusMinusSign = (rand() % 2 ? MUTATE_POSITIVE_MULT : MUTATE_NEGATIVE_MULT); // mutation will increase the param value or decrease it\n        int mutateParamIndex = rand() % NB_PARAMETERS;                                  // index of parameter that will be mutated\n\n        population(indIndex, mutateParamIndex) += population(indIndex, mutateParamIndex) * mutationRate * plusMinusSign;\n\n        return;\n    }\n\n    // 3rd step: selection + mutation and crossover\n    void EvolutionaryAlgorithm::selectionAndMutation()\n    { // tournament, elitism, roulette...\n        std::cout << \"SELECTION\\n\";\n\n        // Selection method (+ crossover)\n        (this->*(selectionType[selectionMethod]))(); // void (*selectionType[])() => tournament(), elitism() or roulette()\n\n        // Mutation\n\n        // Mutating all params from individuals\n        // arma::rowvec bestIndv = population.row(maxFitIndex);\n\n        // arma::mat mutateMatrix(POPULATION_SIZE, NB_PARAMETERS, arma::fill::randu);\n        // mutateMatrix = ((mutateMatrix * MAX_PARAM_VALUE) - MAX_PARAM_VALUE/2.0) * mutationRate;\n\n        // population = population + mutateMatrix;\n\n        // population.row(maxFitIndex) = bestIndv;\n        // population.transform( [](double x) { return ((x < 0 || x > MAX_PARAM_VALUE) ? abs(MAX_PARAM_VALUE-abs(x)) : x); } );\n\n        // Mutating only one parameter from each individual\n        for (int i = 0; i < bestFitIndex; i++)\n            mutate(i);\n        // (don't mutate best one)\n        for (int i = bestFitIndex + 1; i < POPULATION_SIZE; i++)\n            mutate(i);\n\n        return;\n    }\n\n    // Initialize .csv file to sabe data from the EA\n    // Creates the column's headers\n    // generation, paramsIndv1, fitnessIndv1 ..., paramsIndvN, fitnessIndvN, bestParams, bestFitness\n    void EvolutionaryAlgorithm::createCSV(std::string pathPos)\n    {\n        std::ofstream csvFileWriter;\n\n        csvFileWriter.open(\"historyEA-\" + pathPos + \".csv\");\n        if (!csvFileWriter.good())\n        {\n            std::cout << \"[!] Error occurred while trying to create historyEA\" << pathPos << \".csv!\\n\";\n            return;\n        }\n\n        csvFileWriter << \"generation,\";\n        for (int i = 0; i < POPULATION_SIZE; i++)\n            csvFileWriter << \"paramsIndv\" << i << \",fitnessIndv\" << i << \",\";\n        csvFileWriter << \"paramsBestIndv,fitnessBestIndv\\n\";\n\n        return;\n    }\n\n    std::string EvolutionaryAlgorithm::formatParamsString(int indvIndex)\n    {\n        std::string paramsFormated = \"[ \";\n        for (int i = 0; i < NB_PARAMETERS; i++)\n        {\n            paramsFormated += std::to_string(population(indvIndex, i));\n            paramsFormated += \" \";\n        }\n        paramsFormated += \"]\";\n\n        return paramsFormated;\n    }\n\n    // Saves information about a generation in a .csv file\n    // Information: generation, paramsIndv1, fitnessIndv1 ..., paramsIndvN, fitnessIndvN, bestParams, bestFitness\n    void EvolutionaryAlgorithm::saveGenerationData(int generation, const std::string& pathPos)\n    {\n        std::ofstream csvFileWriter;\n\n        csvFileWriter.open(\"historyEA-\" + pathPos + \".csv\", std::ios_base::app); // append instead of overwrite\n        if (!csvFileWriter.good())\n        {\n            std::cout << \"[!] Error occurred while trying to open historyEA.csv!\\n\";\n            return;\n        }\n\n        csvFileWriter << generation << \",\";\n        for (int i = 0; i < POPULATION_SIZE; i++)\n        {\n            csvFileWriter << formatParamsString(i) << \",\" << fitness[i] << \",\";\n        }\n        csvFileWriter << formatParamsString(bestFitIndex) << \",\" << bestFitness << \"\\n\";\n        csvFileWriter.close();\n    }\n\n    void EvolutionaryAlgorithm::increaseMutation()\n    {\n        if (mutationRate < 1e-3 && mutationRate > -1e-3)\n        {\n            mutationRate = INITIAL_MUTATION;\n        }\n        else\n        {\n            mutationRate *= MUTATION_INCREASE_RATIO;\n\n            if (mutationRate > MAX_MUTATION_RATE) // mutation reached its max value\n                mutationRate = MAX_MUTATION_RATE;\n        }\n\n        return;\n    }\n\n    // Function that will kill the worst individual every \"APPLY_PREDATION_INTERVAL\" number of generations\n    void EvolutionaryAlgorithm::predationOfOne()\n    {\n        arma::rowvec newInd(NB_PARAMETERS, arma::fill::randu); // creating totally new individual\n        // for(int j = 0; j < NB_PARAMETERS; j++){\n        //     newInd(j) = attributesValues[j].min + newInd(j)*(attributesValues[j].max - attributesValues[j].min);\n        // }\n        int index = 0;\n        //TODO: find a better way to pass a non-variable to lambda\n        auto &_attributesValues = attributesValues;\n        newInd.for_each([&_attributesValues, &index](double &paramNewInd) { paramNewInd = _attributesValues[index].min + paramNewInd * (_attributesValues[index].max - _attributesValues[index].min); index++; } );\n\n        population.row(worstFitIndex) = newInd;\n\n        return;\n    }\n\n    // A sequence of selections will run, this method will indicate the selection method that will be used by the next batch of generations\n    void EvolutionaryAlgorithm::partIncrease()\n    {\n        const static int selectionMethodCount = sizeof(partsSelectionMethods)/sizeof(selectionMethods);\n        partPos++;\n        if (partPos > selectionMethodCount)\n            partPos = selectionMethodCount;\n        selectionMethod = partsSelectionMethods[partPos];\n\n        return;\n    }\n\n    // Function that will kill all individuals but the best to reset the population and generate new individuals (without biases)\n    void EvolutionaryAlgorithm::oneRemainingPopReset()\n    {\n        std::cout << \"APPLYING POPULATION RESET\\n\";\n\n        arma::rowvec best = population.row(bestFitIndex);\n\n        initializePop(INITIALS);\n        population.row(0) = best;\n        partIncrease();\n\n        return;\n    }\n\n    // Ends the batch of generations from current EA\n    void EvolutionaryAlgorithm::endEABatch()\n    {\n        std::cout << \"END EA BATCH\";\n\n        continueBatch = false;\n\n        return;\n    }\n\n    // Generic function that checks if certain event should happen (predation, population reset, mutation increase...)\n    bool EvolutionaryAlgorithm::eventHappens(int eventType)\n    {\n        if (nbNoImprovementGens % eventTriggerModule[eventType] == 0)\n            return true; // the event being verified should happen!\n        return false;\n    }\n\n    void EvolutionaryAlgorithm::checkEvents()\n    {\n        if (nbNoImprovementGens == 0)\n            return;\n\n        for (int i = 4; i >= 0; i--)\n        {\n            if (eventHappens(i + 1))\n            {\n                (this->*(eventTypes[i]))(); // calls one of these functions: increaseMutation, predationOfOne, partIncrease, oneRemainingPopReset, fullPopReset\n                return;\n            }\n        }\n    }\n\n    void EvolutionaryAlgorithm::startEventTriggerList()\n    {\n        for (int i = 1; i < 6; i++)\n            eventTriggerModule[i] *= eventTriggerModule[i - 1];\n    }\n\n    void EvolutionaryAlgorithm::evoAlg(int createPopType, const std::string& csvStr)\n    {\n        initializePop(createPopType);\n        nbNoImprovementGens = 0;\n        createCSV(csvStr);\n        continueBatch = true;\n        partPos = 0; // defines selection method of current batch of generations\n\n        generationIndex = 0;\n        while (continueBatch)\n        {\n            std::cout << \"\\n==== Generation \" << generationIndex << \" ====\\n\";\n            // population.print(\"Current population:\");\n            evaluatePop();\n            selectionAndMutation();\n\n            saveGenerationData(generationIndex, csvStr);\n\n            checkEvents(); // checks if mutation should increase, predation or population reset should occur etc.\n            // if fullPopReset() is called, continueEA = false\n\n            generationIndex++;\n        }\n\n        return;\n    }\n\n    void EvolutionaryAlgorithm::fillInitialsWithBests(int tournmentType)\n    {\n        for (int i = 0; i < TOURNMENT_RATE; i++)\n            population.row(i) = bestTournmentIndv[tournmentType].row(i);\n    }\n\n    void EvolutionaryAlgorithm::semiFinalsTournment(int semiFinalPos)\n    {\n        for (int i = 0; i < TOURNMENT_RATE; i++)\n        {\n            evoAlg(INITIALS,\"SF-\" + std::to_string(semiFinalPos) + \"_EA-\" + std::to_string(i));\n            bestTournmentIndv[SEMI_FINALS].row(i) = population.row(bestFitIndex); // saves the best individual from current EA\n        }\n        evoAlg(SEMI_FINALS,\"SF-\" + std::to_string(semiFinalPos));                               // this EA will use the best individuals from each previous EA\n        bestTournmentIndv[FINALS].row(semiFinalPos) = population.row(bestFitIndex); // saves the best individual from current EA\n        return;\n    }\n\n    void EvolutionaryAlgorithm::finalTournment()\n    {\n        for (int i = 0; i < TOURNMENT_RATE; i++)\n            semiFinalsTournment(i);\n\n        evoAlg(FINALS,\"FINAL\"); // this EA will use the best individuals from each semifinal\n\n        // bestIndividual = population.row(bestFitIndex); not used, but I'm too afraid to delete\n        std::cout << \"EVOLUTIONARY ALGORITHM FINISHED!\" << std::endl;\n        //eaFinished = true;\n        return;\n    }\n\n    EvolutionaryAlgorithm::EvolutionaryAlgorithm(EAController &eaController) : m_EAController(eaController), eaFinished(false)\n    {\n        srand(time(NULL));\n        startEventTriggerList();\n    }\n\n    static void *runScript(void *scriptFuncObject)\n    {\n        EvolutionaryAlgorithm *script = (EvolutionaryAlgorithm *)scriptFuncObject;\n        script->finalTournment();\n        return NULL;\n    }\n\n    void EvolutionaryAlgorithm::startAlgorithm()\n    {\n        DE_ASSERT(scriptThread == nullptr);\n        scriptThread = new std::thread(runScript, this);\n    }\n\n    EvolutionaryAlgorithm::~EvolutionaryAlgorithm()\n    {\n        if (scriptThread != nullptr && scriptThread->joinable())\n            scriptThread->join();\n        delete scriptThread;\n    }\n\n    \n\n    void EvolutionaryAlgorithm::calcFitness(const std::vector<IndividualRunResult> &gameplayResultsPop)\n    {\n        int pos = 0;\n        for (auto &indivResults : gameplayResultsPop)\n        {\n            fitness[pos] = 0;\n            for (auto &timeResult : indivResults)\n            {\n                fitness[pos] += std::abs(timeResult.TargetTime - timeResult.MeasuredTime) / timeResult.TargetTime;\n            }\n            pos++;\n        }\n        return;\n    }\n\n} // namespace EvoAlg\n", "meta": {"hexsha": "7812c8635cb5ba08072200a02331c0015dda7bf0", "size": 20466, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Application/src/EvoAlg/EvolutionaryAlgorithm.cpp", "max_stars_repo_name": "Haltz01/OSRobotsGame", "max_stars_repo_head_hexsha": "f54b100b4e44dfe274e0881175ef42903bd09719", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-12-09T18:26:40.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-06T04:41:41.000Z", "max_issues_repo_path": "Application/src/EvoAlg/EvolutionaryAlgorithm.cpp", "max_issues_repo_name": "Haltz01/OSRobotsGame", "max_issues_repo_head_hexsha": "f54b100b4e44dfe274e0881175ef42903bd09719", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Application/src/EvoAlg/EvolutionaryAlgorithm.cpp", "max_forks_repo_name": "Haltz01/OSRobotsGame", "max_forks_repo_head_hexsha": "f54b100b4e44dfe274e0881175ef42903bd09719", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2020-12-12T14:15:17.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-07T11:32:58.000Z", "avg_line_length": 35.9052631579, "max_line_length": 217, "alphanum_fraction": 0.5873155477, "num_tokens": 4869, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.640635854839898, "lm_q2_score": 0.5078118642792044, "lm_q1q2_score": 0.32532248777035044}}
{"text": "///////////////////////////////////////////////////////////////////////////////\n// lost_df.hpp                                                               //\n//                                                                           //\n//  Copyright 2010 Erwann Rogard. Distributed under the Boost                //\n//  Software License, Version 1.0. (See accompanying file                    //\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)         //\n///////////////////////////////////////////////////////////////////////////////\n#ifndef BOOST_STATISTICS_DETAIL_NON_PARAMETRIC_CONTINGENCY_TABLE_PEARSON_CHISQ_INDEPENDENCE_LOST_DF_HPP_ER_2010\n#define BOOST_STATISTICS_DETAIL_NON_PARAMETRIC_CONTINGENCY_TABLE_PEARSON_CHISQ_INDEPENDENCE_LOST_DF_HPP_ER_2010\n#include <boost/mpl/for_each.hpp>\n#include <boost/mpl/detail/wrapper.hpp>\n#include <boost/range.hpp>\n#include <boost/accumulators/framework/depends_on.hpp> //contains_feature_of\n#include <boost/accumulators/framework/accumulator_set.hpp> //visit_if\n#include <boost/statistics/detail/non_parametric/contingency_table/factor/vec_levels.hpp>\n#include <boost/statistics/detail/non_parametric/contingency_table/pearson_chisq/independence/tag.hpp>\n\nnamespace boost { \nnamespace statistics{\nnamespace detail{\nnamespace contingency_table{\nnamespace pearson_chisq_statistic{\nnamespace independence_between_aux{\n\n    template<typename A>\n    struct lost_df_accumulator{\n    \n        lost_df_accumulator(const A& acc,std::size_t& df)\n            :acc_(acc),df_(df){}\n\n        template<typename Key>\n        void operator()(const boost::mpl::detail::wrapper<Key>& wrapper)const{\n            namespace ns = contingency_table::extract;\n            this->df_ += (ns::levels<Key>( this->acc_ ).size() - 1);\n        }\n\n        private:\n        const A& acc_;\n        mutable std::size_t& df_;\n    };\n\n\n    template<typename A>\n    independence_between_aux::lost_df_accumulator<A> \n    make_lost_df_accumulator(const A& acc,std::size_t& df){\n        return independence_between_aux::lost_df_accumulator<A>(acc,df);\n    }\n\n}// independence_between_aux\n\n  \ttemplate<typename Keys,typename AccSet>\n    std::size_t lost_degrees_of_freedom(\n        const boost::mpl::detail::wrapper<\n            pearson_chisq_statistic::tag::independence_between<Keys>\n        >& statistic,    \n        const AccSet& acc\n    )\n    {\n        typedef boost::mpl::detail::wrapper<boost::mpl::_> op_;\n        std::size_t result = 0;\n        boost::mpl::for_each<Keys,op_>(\n            independence_between_aux::make_lost_df_accumulator(acc, result)\n        );\n        return result;   \n  \t}\n\n}// pearson_chisq_statistic\n}// contingency_table\n}// detail\n}// statistics\n}// boost\n\n#endif\n", "meta": {"hexsha": "7408023af18277b533fad460a065d5ddc580ac13", "size": 2727, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "non_parametric/boost/statistics/detail/non_parametric/backup_once_in_trunk/non_parametric/contingency_table/pearson_chisq/independence/lost_df.hpp", "max_stars_repo_name": "rogard/boost_sandbox_statistics", "max_stars_repo_head_hexsha": "16aacbc716a31a9f7bb6c535b1c90dc343282a23", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "non_parametric/boost/statistics/detail/non_parametric/backup_once_in_trunk/non_parametric/contingency_table/pearson_chisq/independence/lost_df.hpp", "max_issues_repo_name": "rogard/boost_sandbox_statistics", "max_issues_repo_head_hexsha": "16aacbc716a31a9f7bb6c535b1c90dc343282a23", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "non_parametric/boost/statistics/detail/non_parametric/backup_once_in_trunk/non_parametric/contingency_table/pearson_chisq/independence/lost_df.hpp", "max_forks_repo_name": "rogard/boost_sandbox_statistics", "max_forks_repo_head_hexsha": "16aacbc716a31a9f7bb6c535b1c90dc343282a23", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.8513513514, "max_line_length": 111, "alphanum_fraction": 0.6266960029, "num_tokens": 591, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.640635854839898, "lm_q2_score": 0.5078118642792044, "lm_q1q2_score": 0.32532248777035044}}
{"text": "#pragma once\n#include \"branch_tree_node.hpp\"\n#include <Eigen/Core>\n#include <Eigen/Dense>\n#include \"leaf_tree_node.hpp\"\n#include \"marching_cubes.hpp\"\n#include \"object.hpp\"\n#include \"tree_config.hpp\"\n#include \"tree_node.hpp\"\n#include \"vector.hpp\"\n#include <algorithm>\n#include <array>\n#include <memory>\n#include <vector>\n\nnamespace dmc\n{\ntemplate <class Scalar>\nclass tree\n{\npublic:\n\ttypedef Scalar scalar_type;\n\ttypedef vector<scalar_type, 3> vector_type;\n\ttypedef object<scalar_type> object_type;\n\ttypedef tree_config<scalar_type> config_type;\n\ttypedef tree_node<scalar_type> node_type;\n\ttypedef branch_tree_node<scalar_type> branch_node_type;\n\ttypedef leaf_tree_node<scalar_type> leaf_node_type;\n\ttypedef vertex<scalar_type> vertex_type;\n\n\texplicit tree(const vector_type &minimum, const vector_type &maximum, const config_type &config = config_type())\n\t\t\t: minimum_(minimum), config_(config)\n\t{\n\t\tauto v = maximum - minimum;\n\n\t\tsize_ = v.map([&](auto x) {\n\t\t\t\t\t\t\t return std::max(static_cast<scalar_type>(1.0), std::ceil(x / config_.grid_width));\n\t\t\t\t\t\t })\n\t\t\t\t\t\t\t\t.template cast<std::size_t>();\n\n\t\tchildren_.resize(size_.product());\n\t}\n\n\tvoid generate(const object_type &obj)\n\t{\n\t\tfor (std::size_t iz = 0; iz < size_.z(); ++iz)\n\t\t{\n\t\t\tfor (std::size_t iy = 0; iy < size_.y(); ++iy)\n\t\t\t{\n\t\t\t\tfor (std::size_t ix = 0; ix < size_.x(); ++ix)\n\t\t\t\t{\n\t\t\t\t\tauto minimum = minimum_ + vector<std::size_t, 3>(ix, iy, iz).cast<scalar_type>() * config_.grid_width;\n\t\t\t\t\tauto maximum = minimum_ + vector<std::size_t, 3>(ix + 1, iy + 1, iz + 1).cast<scalar_type>() * config_.grid_width;\n\t\t\t\t\tchildren_[index(ix, iy, iz)] = generate_impl(obj, minimum, maximum, 0);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\ttemplate <class Receiver>\n\tvoid enumerate(Receiver receiver)\n\t{\n\t\tfor (std::size_t iz = 0; iz < size_.z(); ++iz)\n\t\t{\n\t\t\tfor (std::size_t iy = 0; iy < size_.y(); ++iy)\n\t\t\t{\n\t\t\t\tfor (std::size_t ix = 0; ix < size_.x(); ++ix)\n\t\t\t\t{\n\t\t\t\t\tenumerate_impl_c(*children_[index(ix, iy, iz)], receiver);\n\n\t\t\t\t\tif (ix != size_.x() - 1)\n\t\t\t\t\t\tenumerate_impl_f_x(*children_[index(ix, iy, iz)], *children_[index(ix + 1, iy, iz)], receiver);\n\n\t\t\t\t\tif (iy != size_.y() - 1)\n\t\t\t\t\t\tenumerate_impl_f_y(*children_[index(ix, iy, iz)], *children_[index(ix, iy + 1, iz)], receiver);\n\n\t\t\t\t\tif (iz != size_.z() - 1)\n\t\t\t\t\t\tenumerate_impl_f_z(*children_[index(ix, iy, iz)], *children_[index(ix, iy, iz + 1)], receiver);\n\n\t\t\t\t\tif (ix != size_.x() - 1 && iy != size_.y() - 1)\n\t\t\t\t\t{\n\t\t\t\t\t\tenumerate_impl_e_xy(\n\t\t\t\t\t\t\t\t*children_[index(ix, iy, iz)],\n\t\t\t\t\t\t\t\t*children_[index(ix + 1, iy, iz)],\n\t\t\t\t\t\t\t\t*children_[index(ix, iy + 1, iz)],\n\t\t\t\t\t\t\t\t*children_[index(ix + 1, iy + 1, iz)],\n\t\t\t\t\t\t\t\treceiver);\n\t\t\t\t\t}\n\n\t\t\t\t\tif (iy != size_.y() - 1 && iz != size_.z() - 1)\n\t\t\t\t\t{\n\t\t\t\t\t\tenumerate_impl_e_yz(\n\t\t\t\t\t\t\t\t*children_[index(ix, iy, iz)],\n\t\t\t\t\t\t\t\t*children_[index(ix, iy + 1, iz)],\n\t\t\t\t\t\t\t\t*children_[index(ix, iy, iz + 1)],\n\t\t\t\t\t\t\t\t*children_[index(ix, iy + 1, iz + 1)],\n\t\t\t\t\t\t\t\treceiver);\n\t\t\t\t\t}\n\n\t\t\t\t\tif (ix != size_.x() - 1 && iz != size_.z() - 1)\n\t\t\t\t\t{\n\t\t\t\t\t\tenumerate_impl_e_xz(\n\t\t\t\t\t\t\t\t*children_[index(ix, iy, iz)],\n\t\t\t\t\t\t\t\t*children_[index(ix + 1, iy, iz)],\n\t\t\t\t\t\t\t\t*children_[index(ix, iy, iz + 1)],\n\t\t\t\t\t\t\t\t*children_[index(ix + 1, iy, iz + 1)],\n\t\t\t\t\t\t\t\treceiver);\n\t\t\t\t\t}\n\n\t\t\t\t\tif (ix != size_.x() - 1 && iy != size_.y() - 1 && iz != size_.z() - 1)\n\t\t\t\t\t{\n\t\t\t\t\t\tenumerate_impl_v(\n\t\t\t\t\t\t\t\t*children_[index(ix, iy, iz)],\n\t\t\t\t\t\t\t\t*children_[index(ix + 1, iy, iz)],\n\t\t\t\t\t\t\t\t*children_[index(ix, iy + 1, iz)],\n\t\t\t\t\t\t\t\t*children_[index(ix + 1, iy + 1, iz)],\n\t\t\t\t\t\t\t\t*children_[index(ix, iy, iz + 1)],\n\t\t\t\t\t\t\t\t*children_[index(ix + 1, iy, iz + 1)],\n\t\t\t\t\t\t\t\t*children_[index(ix, iy + 1, iz + 1)],\n\t\t\t\t\t\t\t\t*children_[index(ix + 1, iy + 1, iz + 1)],\n\t\t\t\t\t\t\t\treceiver);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\nprivate:\n\tstd::size_t index(std::size_t ix, std::size_t iy, std::size_t iz) const\n\t{\n\t\treturn iz * size_.y() * size_.x() + iy * size_.x() + ix;\n\t}\n\n\tstd::unique_ptr<node_type> generate_impl(const object_type &obj, const vector_type &minimum, const vector_type &maximum, std::size_t depth) const\n\t{\n\t\tstd::array<vector_type, 8> points =\n\t\t\t\t{{\n\t\t\t\t\t\t{minimum.x(), minimum.y(), minimum.z()},\n\t\t\t\t\t\t{maximum.x(), minimum.y(), minimum.z()},\n\t\t\t\t\t\t{minimum.x(), maximum.y(), minimum.z()},\n\t\t\t\t\t\t{maximum.x(), maximum.y(), minimum.z()},\n\t\t\t\t\t\t{minimum.x(), minimum.y(), maximum.z()},\n\t\t\t\t\t\t{maximum.x(), minimum.y(), maximum.z()},\n\t\t\t\t\t\t{minimum.x(), maximum.y(), maximum.z()},\n\t\t\t\t\t\t{maximum.x(), maximum.y(), maximum.z()},\n\t\t\t\t}};\n\n\t\tstd::array<scalar_type, 8> values;\n\n\t\tstd::transform(points.begin(), points.end(), values.begin(),\n\t\t\t\t\t\t\t\t\t [&](const auto &p) {\n\t\t\t\t\t\t\t\t\t\t return obj.value(p);\n\t\t\t\t\t\t\t\t\t });\n\n\t\tstd::array<vector_type, 8> grads;\n\n\t\tstd::transform(points.begin(), points.end(), grads.begin(),\n\t\t\t\t\t\t\t\t\t [&](const auto &p) {\n\t\t\t\t\t\t\t\t\t\t return obj.grad(p);\n\t\t\t\t\t\t\t\t\t });\n\n\t\tEigen::Matrix<scalar_type, 11, 4> a;\n\n\t\tfor (int i = 0; i < 8; ++i)\n\t\t{\n\t\t\ta(i, 0) = grads[i].x();\n\t\t\ta(i, 1) = grads[i].y();\n\t\t\ta(i, 2) = grads[i].z();\n\t\t\ta(i, 3) = static_cast<scalar_type>(-1.0);\n\t\t}\n\n\t\ta(8, 0) = config_.nominal_weight;\n\t\ta(8, 1) = 0.0;\n\t\ta(8, 2) = 0.0;\n\t\ta(8, 3) = 0.0;\n\t\ta(9, 0) = 0.0;\n\t\ta(9, 1) = config_.nominal_weight;\n\t\ta(9, 2) = 0.0;\n\t\ta(9, 3) = 0.0;\n\t\ta(10, 0) = 0.0;\n\t\ta(10, 1) = 0.0;\n\t\ta(10, 2) = config_.nominal_weight;\n\t\ta(10, 3) = 0.0;\n\n\t\tEigen::Matrix<scalar_type, 11, 1> b;\n\n\t\tauto medium = (minimum + maximum) * static_cast<scalar_type>(0.5);\n\n\t\tfor (int i = 0; i < 8; ++i)\n\t\t\tb(i) = dot_product(grads[i], points[i] - medium) - values[i];\n\n\t\tb(8) = 0.0;\n\t\tb(9) = 0.0;\n\t\tb(10) = 0.0;\n\n\t\tEigen::Matrix<scalar_type, 4, 1> x = a.jacobiSvd(Eigen::ComputeFullU | Eigen::ComputeFullV).solve(b);\n\n\t\tauto center = vector_type(x(0), x(1), x(2)) + medium;\n\t\tauto offset = obj.value(center);\n\n\t\tauto error = scalar_type();\n\n\t\tfor (int i = 0; i < 8; ++i)\n\t\t\terror += squared(offset - values[i] - dot_product(grads[i], center - points[i]));\n\n\t\tif (depth >= config_.maximum_depth || error < squared(config_.tolerance))\n\t\t{\n\t\t\treturn std::make_unique<leaf_node_type>(vertex_type(center, offset));\n\t\t}\n\t\telse\n\t\t{\n\t\t\tstd::array<std::unique_ptr<node_type>, 8> nodes =\n\t\t\t\t\t{{\n\t\t\t\t\t\t\tgenerate_impl(obj, {minimum.x(), minimum.y(), minimum.z()}, {medium.x(), medium.y(), medium.z()}, depth + 1),\n\t\t\t\t\t\t\tgenerate_impl(obj, {medium.x(), minimum.y(), minimum.z()}, {maximum.x(), medium.y(), medium.z()}, depth + 1),\n\t\t\t\t\t\t\tgenerate_impl(obj, {minimum.x(), medium.y(), minimum.z()}, {medium.x(), maximum.y(), medium.z()}, depth + 1),\n\t\t\t\t\t\t\tgenerate_impl(obj, {medium.x(), medium.y(), minimum.z()}, {maximum.x(), maximum.y(), medium.z()}, depth + 1),\n\t\t\t\t\t\t\tgenerate_impl(obj, {minimum.x(), minimum.y(), medium.z()}, {medium.x(), medium.y(), maximum.z()}, depth + 1),\n\t\t\t\t\t\t\tgenerate_impl(obj, {medium.x(), minimum.y(), medium.z()}, {maximum.x(), medium.y(), maximum.z()}, depth + 1),\n\t\t\t\t\t\t\tgenerate_impl(obj, {minimum.x(), medium.y(), medium.z()}, {medium.x(), maximum.y(), maximum.z()}, depth + 1),\n\t\t\t\t\t\t\tgenerate_impl(obj, {medium.x(), medium.y(), medium.z()}, {maximum.x(), maximum.y(), maximum.z()}, depth + 1),\n\t\t\t\t\t}};\n\n\t\t\treturn std::make_unique<branch_node_type>(std::move(nodes));\n\t\t}\n\t}\n\n\ttemplate <class Receiver>\n\tvoid enumerate_impl_c(const node_type &n, Receiver receiver)\n\t{\n\t\tif (auto b = dynamic_cast<const branch_node_type *>(&n))\n\t\t{\n\t\t\tenumerate_impl_c(*b->children()[0], receiver);\n\t\t\tenumerate_impl_c(*b->children()[1], receiver);\n\t\t\tenumerate_impl_c(*b->children()[2], receiver);\n\t\t\tenumerate_impl_c(*b->children()[3], receiver);\n\t\t\tenumerate_impl_c(*b->children()[4], receiver);\n\t\t\tenumerate_impl_c(*b->children()[5], receiver);\n\t\t\tenumerate_impl_c(*b->children()[6], receiver);\n\t\t\tenumerate_impl_c(*b->children()[7], receiver);\n\n\t\t\tenumerate_impl_f_x(*b->children()[0], *b->children()[1], receiver);\n\t\t\tenumerate_impl_f_x(*b->children()[2], *b->children()[3], receiver);\n\t\t\tenumerate_impl_f_x(*b->children()[4], *b->children()[5], receiver);\n\t\t\tenumerate_impl_f_x(*b->children()[6], *b->children()[7], receiver);\n\n\t\t\tenumerate_impl_f_y(*b->children()[0], *b->children()[2], receiver);\n\t\t\tenumerate_impl_f_y(*b->children()[1], *b->children()[3], receiver);\n\t\t\tenumerate_impl_f_y(*b->children()[4], *b->children()[6], receiver);\n\t\t\tenumerate_impl_f_y(*b->children()[5], *b->children()[7], receiver);\n\n\t\t\tenumerate_impl_f_z(*b->children()[0], *b->children()[4], receiver);\n\t\t\tenumerate_impl_f_z(*b->children()[1], *b->children()[5], receiver);\n\t\t\tenumerate_impl_f_z(*b->children()[2], *b->children()[6], receiver);\n\t\t\tenumerate_impl_f_z(*b->children()[3], *b->children()[7], receiver);\n\n\t\t\tenumerate_impl_e_xy(*b->children()[0], *b->children()[1], *b->children()[2], *b->children()[3], receiver);\n\t\t\tenumerate_impl_e_xy(*b->children()[4], *b->children()[5], *b->children()[6], *b->children()[7], receiver);\n\n\t\t\tenumerate_impl_e_yz(*b->children()[0], *b->children()[2], *b->children()[4], *b->children()[6], receiver);\n\t\t\tenumerate_impl_e_yz(*b->children()[1], *b->children()[3], *b->children()[5], *b->children()[7], receiver);\n\n\t\t\tenumerate_impl_e_xz(*b->children()[0], *b->children()[1], *b->children()[4], *b->children()[5], receiver);\n\t\t\tenumerate_impl_e_xz(*b->children()[2], *b->children()[3], *b->children()[6], *b->children()[7], receiver);\n\n\t\t\tenumerate_impl_v(\n\t\t\t\t\t*b->children()[0],\n\t\t\t\t\t*b->children()[1],\n\t\t\t\t\t*b->children()[2],\n\t\t\t\t\t*b->children()[3],\n\t\t\t\t\t*b->children()[4],\n\t\t\t\t\t*b->children()[5],\n\t\t\t\t\t*b->children()[6],\n\t\t\t\t\t*b->children()[7],\n\t\t\t\t\treceiver);\n\t\t}\n\t}\n\n\ttemplate <class Receiver>\n\tvoid enumerate_impl_f_x(const node_type &n1, const node_type &n2, Receiver receiver)\n\t{\n\t\tauto b1 = dynamic_cast<const branch_node_type *>(&n1);\n\t\tauto b2 = dynamic_cast<const branch_node_type *>(&n2);\n\n\t\tif (b1 || b2)\n\t\t{\n\t\t\tenumerate_impl_f_x(b1 ? *b1->children()[1] : n1, b2 ? *b2->children()[0] : n2, receiver);\n\t\t\tenumerate_impl_f_x(b1 ? *b1->children()[3] : n1, b2 ? *b2->children()[2] : n2, receiver);\n\t\t\tenumerate_impl_f_x(b1 ? *b1->children()[5] : n1, b2 ? *b2->children()[4] : n2, receiver);\n\t\t\tenumerate_impl_f_x(b1 ? *b1->children()[7] : n1, b2 ? *b2->children()[6] : n2, receiver);\n\n\t\t\tenumerate_impl_e_xy(\n\t\t\t\t\tb1 ? *b1->children()[1] : n1,\n\t\t\t\t\tb2 ? *b2->children()[0] : n2,\n\t\t\t\t\tb1 ? *b1->children()[3] : n1,\n\t\t\t\t\tb2 ? *b2->children()[2] : n2,\n\t\t\t\t\treceiver);\n\n\t\t\tenumerate_impl_e_xy(\n\t\t\t\t\tb1 ? *b1->children()[5] : n1,\n\t\t\t\t\tb2 ? *b2->children()[4] : n2,\n\t\t\t\t\tb1 ? *b1->children()[7] : n1,\n\t\t\t\t\tb2 ? *b2->children()[6] : n2,\n\t\t\t\t\treceiver);\n\n\t\t\tenumerate_impl_e_xz(\n\t\t\t\t\tb1 ? *b1->children()[1] : n1,\n\t\t\t\t\tb2 ? *b2->children()[0] : n2,\n\t\t\t\t\tb1 ? *b1->children()[5] : n1,\n\t\t\t\t\tb2 ? *b2->children()[4] : n2,\n\t\t\t\t\treceiver);\n\n\t\t\tenumerate_impl_e_xz(\n\t\t\t\t\tb1 ? *b1->children()[3] : n1,\n\t\t\t\t\tb2 ? *b2->children()[2] : n2,\n\t\t\t\t\tb1 ? *b1->children()[7] : n1,\n\t\t\t\t\tb2 ? *b2->children()[6] : n2,\n\t\t\t\t\treceiver);\n\n\t\t\tenumerate_impl_v(\n\t\t\t\t\tb1 ? *b1->children()[1] : n1,\n\t\t\t\t\tb2 ? *b2->children()[0] : n2,\n\t\t\t\t\tb1 ? *b1->children()[3] : n1,\n\t\t\t\t\tb2 ? *b2->children()[2] : n2,\n\t\t\t\t\tb1 ? *b1->children()[5] : n1,\n\t\t\t\t\tb2 ? *b2->children()[4] : n2,\n\t\t\t\t\tb1 ? *b1->children()[7] : n1,\n\t\t\t\t\tb2 ? *b2->children()[6] : n2,\n\t\t\t\t\treceiver);\n\t\t}\n\t}\n\n\ttemplate <class Receiver>\n\tvoid enumerate_impl_f_y(const node_type &n1, const node_type &n2, Receiver receiver)\n\t{\n\t\tauto b1 = dynamic_cast<const branch_node_type *>(&n1);\n\t\tauto b2 = dynamic_cast<const branch_node_type *>(&n2);\n\n\t\tif (b1 || b2)\n\t\t{\n\t\t\tenumerate_impl_f_y(b1 ? *b1->children()[2] : n1, b2 ? *b2->children()[0] : n2, receiver);\n\t\t\tenumerate_impl_f_y(b1 ? *b1->children()[3] : n1, b2 ? *b2->children()[1] : n2, receiver);\n\t\t\tenumerate_impl_f_y(b1 ? *b1->children()[6] : n1, b2 ? *b2->children()[4] : n2, receiver);\n\t\t\tenumerate_impl_f_y(b1 ? *b1->children()[7] : n1, b2 ? *b2->children()[5] : n2, receiver);\n\n\t\t\tenumerate_impl_e_xy(\n\t\t\t\t\tb1 ? *b1->children()[2] : n1,\n\t\t\t\t\tb1 ? *b1->children()[3] : n1,\n\t\t\t\t\tb2 ? *b2->children()[0] : n2,\n\t\t\t\t\tb2 ? *b2->children()[1] : n2,\n\t\t\t\t\treceiver);\n\n\t\t\tenumerate_impl_e_xy(\n\t\t\t\t\tb1 ? *b1->children()[6] : n1,\n\t\t\t\t\tb1 ? *b1->children()[7] : n1,\n\t\t\t\t\tb2 ? *b2->children()[4] : n2,\n\t\t\t\t\tb2 ? *b2->children()[5] : n2,\n\t\t\t\t\treceiver);\n\n\t\t\tenumerate_impl_e_yz(\n\t\t\t\t\tb1 ? *b1->children()[3] : n1,\n\t\t\t\t\tb2 ? *b2->children()[1] : n2,\n\t\t\t\t\tb1 ? *b1->children()[7] : n1,\n\t\t\t\t\tb2 ? *b2->children()[5] : n2,\n\t\t\t\t\treceiver);\n\n\t\t\tenumerate_impl_e_yz(\n\t\t\t\t\tb1 ? *b1->children()[2] : n1,\n\t\t\t\t\tb2 ? *b2->children()[0] : n2,\n\t\t\t\t\tb1 ? *b1->children()[6] : n1,\n\t\t\t\t\tb2 ? *b2->children()[4] : n2,\n\t\t\t\t\treceiver);\n\n\t\t\tenumerate_impl_v(\n\t\t\t\t\tb1 ? *b1->children()[2] : n1,\n\t\t\t\t\tb1 ? *b1->children()[3] : n1,\n\t\t\t\t\tb2 ? *b2->children()[0] : n2,\n\t\t\t\t\tb2 ? *b2->children()[1] : n2,\n\t\t\t\t\tb1 ? *b1->children()[6] : n1,\n\t\t\t\t\tb1 ? *b1->children()[7] : n1,\n\t\t\t\t\tb2 ? *b2->children()[4] : n2,\n\t\t\t\t\tb2 ? *b2->children()[5] : n2,\n\t\t\t\t\treceiver);\n\t\t}\n\t}\n\n\ttemplate <class Receiver>\n\tvoid enumerate_impl_f_z(const node_type &n1, const node_type &n2, Receiver receiver)\n\t{\n\t\tauto b1 = dynamic_cast<const branch_node_type *>(&n1);\n\t\tauto b2 = dynamic_cast<const branch_node_type *>(&n2);\n\n\t\tif (b1 || b2)\n\t\t{\n\t\t\tenumerate_impl_f_z(b1 ? *b1->children()[4] : n1, b2 ? *b2->children()[0] : n2, receiver);\n\t\t\tenumerate_impl_f_z(b1 ? *b1->children()[5] : n1, b2 ? *b2->children()[1] : n2, receiver);\n\t\t\tenumerate_impl_f_z(b1 ? *b1->children()[6] : n1, b2 ? *b2->children()[2] : n2, receiver);\n\t\t\tenumerate_impl_f_z(b1 ? *b1->children()[7] : n1, b2 ? *b2->children()[3] : n2, receiver);\n\n\t\t\tenumerate_impl_e_xz(\n\t\t\t\t\tb1 ? *b1->children()[4] : n1,\n\t\t\t\t\tb1 ? *b1->children()[5] : n1,\n\t\t\t\t\tb2 ? *b2->children()[0] : n2,\n\t\t\t\t\tb2 ? *b2->children()[1] : n2,\n\t\t\t\t\treceiver);\n\n\t\t\tenumerate_impl_e_xz(\n\t\t\t\t\tb1 ? *b1->children()[6] : n1,\n\t\t\t\t\tb1 ? *b1->children()[7] : n1,\n\t\t\t\t\tb2 ? *b2->children()[2] : n2,\n\t\t\t\t\tb2 ? *b2->children()[3] : n2,\n\t\t\t\t\treceiver);\n\n\t\t\tenumerate_impl_e_yz(\n\t\t\t\t\tb1 ? *b1->children()[4] : n1,\n\t\t\t\t\tb1 ? *b1->children()[6] : n1,\n\t\t\t\t\tb2 ? *b2->children()[0] : n2,\n\t\t\t\t\tb2 ? *b2->children()[2] : n2,\n\t\t\t\t\treceiver);\n\n\t\t\tenumerate_impl_e_yz(\n\t\t\t\t\tb1 ? *b1->children()[5] : n1,\n\t\t\t\t\tb1 ? *b1->children()[7] : n1,\n\t\t\t\t\tb2 ? *b2->children()[1] : n2,\n\t\t\t\t\tb2 ? *b2->children()[3] : n2,\n\t\t\t\t\treceiver);\n\n\t\t\tenumerate_impl_v(\n\t\t\t\t\tb1 ? *b1->children()[4] : n1,\n\t\t\t\t\tb1 ? *b1->children()[5] : n1,\n\t\t\t\t\tb1 ? *b1->children()[6] : n1,\n\t\t\t\t\tb1 ? *b1->children()[7] : n1,\n\t\t\t\t\tb2 ? *b2->children()[0] : n2,\n\t\t\t\t\tb2 ? *b2->children()[1] : n2,\n\t\t\t\t\tb2 ? *b2->children()[2] : n2,\n\t\t\t\t\tb2 ? *b2->children()[3] : n2,\n\t\t\t\t\treceiver);\n\t\t}\n\t}\n\n\ttemplate <class Receiver>\n\tvoid enumerate_impl_e_xy(\n\t\t\tconst node_type &n1,\n\t\t\tconst node_type &n2,\n\t\t\tconst node_type &n3,\n\t\t\tconst node_type &n4,\n\t\t\tReceiver receiver)\n\t{\n\t\tauto b1 = dynamic_cast<const branch_node_type *>(&n1);\n\t\tauto b2 = dynamic_cast<const branch_node_type *>(&n2);\n\t\tauto b3 = dynamic_cast<const branch_node_type *>(&n3);\n\t\tauto b4 = dynamic_cast<const branch_node_type *>(&n4);\n\n\t\tif (b1 || b2 || b3 || b4)\n\t\t{\n\t\t\tenumerate_impl_e_xy(\n\t\t\t\t\tb1 ? *b1->children()[3] : n1,\n\t\t\t\t\tb2 ? *b2->children()[2] : n2,\n\t\t\t\t\tb3 ? *b3->children()[1] : n3,\n\t\t\t\t\tb4 ? *b4->children()[0] : n4,\n\t\t\t\t\treceiver);\n\n\t\t\tenumerate_impl_e_xy(\n\t\t\t\t\tb1 ? *b1->children()[7] : n1,\n\t\t\t\t\tb2 ? *b2->children()[6] : n2,\n\t\t\t\t\tb3 ? *b3->children()[5] : n3,\n\t\t\t\t\tb4 ? *b4->children()[4] : n4,\n\t\t\t\t\treceiver);\n\n\t\t\tenumerate_impl_v(\n\t\t\t\t\tb1 ? *b1->children()[3] : n1,\n\t\t\t\t\tb2 ? *b2->children()[2] : n2,\n\t\t\t\t\tb3 ? *b3->children()[1] : n3,\n\t\t\t\t\tb4 ? *b4->children()[0] : n4,\n\t\t\t\t\tb1 ? *b1->children()[7] : n1,\n\t\t\t\t\tb2 ? *b2->children()[6] : n2,\n\t\t\t\t\tb3 ? *b3->children()[5] : n3,\n\t\t\t\t\tb4 ? *b4->children()[4] : n4,\n\t\t\t\t\treceiver);\n\t\t}\n\t}\n\n\ttemplate <class Receiver>\n\tvoid enumerate_impl_e_yz(\n\t\t\tconst node_type &n1,\n\t\t\tconst node_type &n2,\n\t\t\tconst node_type &n3,\n\t\t\tconst node_type &n4,\n\t\t\tReceiver receiver)\n\t{\n\t\tauto b1 = dynamic_cast<const branch_node_type *>(&n1);\n\t\tauto b2 = dynamic_cast<const branch_node_type *>(&n2);\n\t\tauto b3 = dynamic_cast<const branch_node_type *>(&n3);\n\t\tauto b4 = dynamic_cast<const branch_node_type *>(&n4);\n\n\t\tif (b1 || b2 || b3 || b4)\n\t\t{\n\t\t\tenumerate_impl_e_yz(\n\t\t\t\t\tb1 ? *b1->children()[6] : n1,\n\t\t\t\t\tb2 ? *b2->children()[4] : n2,\n\t\t\t\t\tb3 ? *b3->children()[2] : n3,\n\t\t\t\t\tb4 ? *b4->children()[0] : n4,\n\t\t\t\t\treceiver);\n\n\t\t\tenumerate_impl_e_yz(\n\t\t\t\t\tb1 ? *b1->children()[7] : n1,\n\t\t\t\t\tb2 ? *b2->children()[5] : n2,\n\t\t\t\t\tb3 ? *b3->children()[3] : n3,\n\t\t\t\t\tb4 ? *b4->children()[1] : n4,\n\t\t\t\t\treceiver);\n\n\t\t\tenumerate_impl_v(\n\t\t\t\t\tb1 ? *b1->children()[6] : n1,\n\t\t\t\t\tb1 ? *b1->children()[7] : n1,\n\t\t\t\t\tb2 ? *b2->children()[4] : n2,\n\t\t\t\t\tb2 ? *b2->children()[5] : n2,\n\t\t\t\t\tb3 ? *b3->children()[2] : n3,\n\t\t\t\t\tb3 ? *b3->children()[3] : n3,\n\t\t\t\t\tb4 ? *b4->children()[0] : n4,\n\t\t\t\t\tb4 ? *b4->children()[1] : n4,\n\t\t\t\t\treceiver);\n\t\t}\n\t}\n\n\ttemplate <class Receiver>\n\tvoid enumerate_impl_e_xz(\n\t\t\tconst node_type &n1,\n\t\t\tconst node_type &n2,\n\t\t\tconst node_type &n3,\n\t\t\tconst node_type &n4,\n\t\t\tReceiver receiver)\n\t{\n\t\tauto b1 = dynamic_cast<const branch_node_type *>(&n1);\n\t\tauto b2 = dynamic_cast<const branch_node_type *>(&n2);\n\t\tauto b3 = dynamic_cast<const branch_node_type *>(&n3);\n\t\tauto b4 = dynamic_cast<const branch_node_type *>(&n4);\n\n\t\tif (b1 || b2 || b3 || b4)\n\t\t{\n\t\t\tenumerate_impl_e_xz(\n\t\t\t\t\tb1 ? *b1->children()[5] : n1,\n\t\t\t\t\tb2 ? *b2->children()[4] : n2,\n\t\t\t\t\tb3 ? *b3->children()[1] : n3,\n\t\t\t\t\tb4 ? *b4->children()[0] : n4,\n\t\t\t\t\treceiver);\n\n\t\t\tenumerate_impl_e_xz(\n\t\t\t\t\tb1 ? *b1->children()[7] : n1,\n\t\t\t\t\tb2 ? *b2->children()[6] : n2,\n\t\t\t\t\tb3 ? *b3->children()[3] : n3,\n\t\t\t\t\tb4 ? *b4->children()[2] : n4,\n\t\t\t\t\treceiver);\n\n\t\t\tenumerate_impl_v(\n\t\t\t\t\tb1 ? *b1->children()[5] : n1,\n\t\t\t\t\tb2 ? *b2->children()[4] : n2,\n\t\t\t\t\tb1 ? *b1->children()[7] : n1,\n\t\t\t\t\tb2 ? *b2->children()[6] : n2,\n\t\t\t\t\tb3 ? *b3->children()[1] : n3,\n\t\t\t\t\tb4 ? *b4->children()[0] : n4,\n\t\t\t\t\tb3 ? *b3->children()[3] : n3,\n\t\t\t\t\tb4 ? *b4->children()[2] : n4,\n\t\t\t\t\treceiver);\n\t\t}\n\t}\n\n\ttemplate <class Receiver>\n\tvoid enumerate_impl_v(\n\t\t\tconst node_type &n1,\n\t\t\tconst node_type &n2,\n\t\t\tconst node_type &n3,\n\t\t\tconst node_type &n4,\n\t\t\tconst node_type &n5,\n\t\t\tconst node_type &n6,\n\t\t\tconst node_type &n7,\n\t\t\tconst node_type &n8,\n\t\t\tReceiver receiver)\n\t{\n\t\tauto b1 = dynamic_cast<const branch_node_type *>(&n1);\n\t\tauto b2 = dynamic_cast<const branch_node_type *>(&n2);\n\t\tauto b3 = dynamic_cast<const branch_node_type *>(&n3);\n\t\tauto b4 = dynamic_cast<const branch_node_type *>(&n4);\n\t\tauto b5 = dynamic_cast<const branch_node_type *>(&n5);\n\t\tauto b6 = dynamic_cast<const branch_node_type *>(&n6);\n\t\tauto b7 = dynamic_cast<const branch_node_type *>(&n7);\n\t\tauto b8 = dynamic_cast<const branch_node_type *>(&n8);\n\n\t\tif (b1 || b2 || b3 || b4 || b5 || b6 || b7 || b8)\n\t\t{\n\t\t\tenumerate_impl_v(\n\t\t\t\t\tb1 ? *b1->children()[7] : n1,\n\t\t\t\t\tb2 ? *b2->children()[6] : n2,\n\t\t\t\t\tb3 ? *b3->children()[5] : n3,\n\t\t\t\t\tb4 ? *b4->children()[4] : n4,\n\t\t\t\t\tb5 ? *b5->children()[3] : n5,\n\t\t\t\t\tb6 ? *b6->children()[2] : n6,\n\t\t\t\t\tb7 ? *b7->children()[1] : n7,\n\t\t\t\t\tb8 ? *b8->children()[0] : n8,\n\t\t\t\t\treceiver);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tauto l1 = static_cast<const leaf_node_type *>(&n1);\n\t\t\tauto l2 = static_cast<const leaf_node_type *>(&n2);\n\t\t\tauto l3 = static_cast<const leaf_node_type *>(&n3);\n\t\t\tauto l4 = static_cast<const leaf_node_type *>(&n4);\n\t\t\tauto l5 = static_cast<const leaf_node_type *>(&n5);\n\t\t\tauto l6 = static_cast<const leaf_node_type *>(&n6);\n\t\t\tauto l7 = static_cast<const leaf_node_type *>(&n7);\n\t\t\tauto l8 = static_cast<const leaf_node_type *>(&n8);\n\n\t\t\tstd::array<const vertex_type *, 8> vertices =\n\t\t\t\t\t{{\n\t\t\t\t\t\t\t&l1->vertex(),\n\t\t\t\t\t\t\t&l2->vertex(),\n\t\t\t\t\t\t\t&l3->vertex(),\n\t\t\t\t\t\t\t&l4->vertex(),\n\t\t\t\t\t\t\t&l5->vertex(),\n\t\t\t\t\t\t\t&l6->vertex(),\n\t\t\t\t\t\t\t&l7->vertex(),\n\t\t\t\t\t\t\t&l8->vertex(),\n\t\t\t\t\t}};\n\n\t\t\tmarching_cubes<scalar_type>(vertices, receiver);\n\t\t}\n\t}\n\n\tvector_type minimum_;\n\tconfig_type config_;\n\n\tstd::size_t grid_size_;\n\tscalar_type grid_width_;\n\n\tvector<std::size_t, 3> size_;\n\tstd::vector<std::unique_ptr<node_type>> children_;\n};\n} // namespace dmc\n", "meta": {"hexsha": "8846f6a9866395cf1886963994b6de4100224524", "size": 19890, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/dmc/tree.hpp", "max_stars_repo_name": "Calebsem/node-dmc", "max_stars_repo_head_hexsha": "1991e9b09fae79678f2e63112d67fbf08dfa70ff", "max_stars_repo_licenses": ["BSD-3-Clause"], "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/dmc/tree.hpp", "max_issues_repo_name": "Calebsem/node-dmc", "max_issues_repo_head_hexsha": "1991e9b09fae79678f2e63112d67fbf08dfa70ff", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/dmc/tree.hpp", "max_forks_repo_name": "Calebsem/node-dmc", "max_forks_repo_head_hexsha": "1991e9b09fae79678f2e63112d67fbf08dfa70ff", "max_forks_repo_licenses": ["BSD-3-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.1755485893, "max_line_length": 146, "alphanum_fraction": 0.5703368527, "num_tokens": 6988, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6825737344123242, "lm_q2_score": 0.476579651063676, "lm_q1q2_score": 0.3253007521714557}}
{"text": "/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n/* ------------------------------------------------------\n *\n * @file logistic.cpp\n *\n * @brief Logistic-Regression functions\n *\n * We implement the conjugate-gradient method and the iteratively-reweighted-\n * least-squares method.\n *\n *//* ----------------------------------------------------------------------- */\n#include <limits>\n#include <dbconnector/dbconnector.hpp>\n#include <modules/shared/HandleTraits.hpp>\n#include <modules/prob/boost.hpp>\n#include <boost/math/distributions.hpp>\n#include <modules/prob/student.hpp>\n#include \"simple_logistic.hpp\"\n\nnamespace madlib {\n\n// Use Eigen\nusing namespace dbal::eigen_integration;\n\nnamespace modules {\n\n// Import names from other MADlib modules\nusing dbal::NoSolutionFoundException;\n\nnamespace hello_world {\n\n// FIXME this enum should be accessed by all modules that may need grouping\n// valid status values\nenum { IN_PROCESS, COMPLETED, TERMINATED, NULL_EMPTY };\n\n// Internal functions\nAnyType stateToResult(const Allocator &inAllocator,\n                      const HandleMap<const ColumnVector, TransparentHandle<double> >& inCoef,\n                      const Matrix & hessian,\n                      const double &logLikelihood,\n                      int status,\n                      const uint64_t &numRows);\n\n\n// ---------------------------------------------------------------------------\n//              Logistic Regression States\n// ---------------------------------------------------------------------------\n\n/**\n * @brief Inter- and intra-iteration state for conjugate-gradient method for\n *        logistic regression\n *\n * TransitionState encapsualtes the transition state during the\n * logistic-regression aggregate function. To the database, the state is\n * exposed as a single DOUBLE PRECISION array, to the C++ code it is a proper\n * object containing scalars and vectors.\n *\n * Note: We assume that the DOUBLE PRECISION array is initialized by the\n * database with length at least 5, and all elemenets are 0.\n *\n */\ntemplate <class Handle>\nclass LogRegrSPTransitionState {\n    template <class OtherHandle>\n    friend class LogRegrSPTransitionState;\n\n  public:\n    LogRegrSPTransitionState(const AnyType &inArray)\n        : mStorage(inArray.getAs<Handle>()) {\n\n        rebind(static_cast<uint16_t>(mStorage[1]));\n    }\n\n    /**\n     * @brief Convert to backend representation\n     *\n     * We define this function so that we can use State in the\n     * argument list and as a return type.\n     */\n    inline operator AnyType() const {\n        return mStorage;\n    }\n\n    /**\n     * @brief Initialize the conjugate-gradient state.\n     *\n     * This function is only called for the first iteration, for the first row.\n     */\n    inline void initialize(const Allocator &inAllocator, uint16_t inWidthOfX) {\n        mStorage = inAllocator.allocateArray<double, dbal::AggregateContext,\n                                             dbal::DoZero, dbal::ThrowBadAlloc>(arraySize(inWidthOfX));\n        rebind(inWidthOfX);\n        widthOfX = inWidthOfX;\n    }\n\n    /**\n     * @brief We need to support assigning the previous state\n     */\n    template <class OtherHandle>\n    LogRegrSPTransitionState &operator=(\n        const LogRegrSPTransitionState<OtherHandle> &inOtherState) {\n\n        for (size_t i = 0; i < mStorage.size(); i++)\n            mStorage[i] = inOtherState.mStorage[i];\n        return *this;\n    }\n\n    /**\n     * @brief Merge with another State object by copying the intra-iteration\n     *     fields\n     */\n    template <class OtherHandle>\n    LogRegrSPTransitionState &operator+=(\n        const LogRegrSPTransitionState<OtherHandle> &inOtherState) {\n\n        if (mStorage.size() != inOtherState.mStorage.size() ||\n            widthOfX != inOtherState.widthOfX)\n            throw std::logic_error(\"Internal error: Incompatible transition \"\n                                   \"states\");\n\n        numRows += inOtherState.numRows;\n        gradNew += inOtherState.gradNew;\n        X_transp_AX += inOtherState.X_transp_AX;\n        logLikelihood += inOtherState.logLikelihood;\n        // merged state should have the higher status\n        // (see top of file for more on 'status' )\n        status = (inOtherState.status > status) ? inOtherState.status : status;\n        return *this;\n    }\n\n    /**\n     * @brief Reset the inter-iteration fields.\n     */\n    inline void reset() {\n        numRows = 0;\n        X_transp_AX.fill(0);\n        gradNew.fill(0);\n        logLikelihood = 0;\n        status = IN_PROCESS;\n    }\n\n  private:\n    static inline size_t arraySize(const uint16_t inWidthOfX) {\n        return 6 + inWidthOfX * inWidthOfX + 4 * inWidthOfX;\n    }\n\n    /**\n     * @brief Rebind to a new storage array\n     *\n     * @param inWidthOfX The number of independent variables.\n     *\n     * Array layout (iteration refers to one aggregate-function call):\n     * Inter-iteration components (updated in final function):\n     * - 0: iteration (current iteration)\n     * - 1: widthOfX (number of coefficients)\n     * - 2: coef (vector of coefficients)\n     * - 2 + widthOfX: dir (direction)\n     * - 2 + 2 * widthOfX: grad (gradient)\n     * - 2 + 3 * widthOfX: beta (scale factor)\n     *\n     * Intra-iteration components (updated in transition step):\n     * - 3 + 3 * widthOfX: numRows (number of rows already processed in this iteration)\n     * - 4 + 3 * widthOfX: gradNew (intermediate value for gradient)\n     * - 4 + 4 * widthOfX: X_transp_AX (X^T A X)\n     * - 4 + widthOfX * widthOfX + 4 * widthOfX: logLikelihood ( ln(l(c)) )\n     */\n    void rebind(uint16_t inWidthOfX) {\n        iteration.rebind(&mStorage[0]);\n        widthOfX.rebind(&mStorage[1]);\n        coef.rebind(&mStorage[2], inWidthOfX);\n        dir.rebind(&mStorage[2 + inWidthOfX], inWidthOfX);\n        grad.rebind(&mStorage[2 + 2 * inWidthOfX], inWidthOfX);\n        beta.rebind(&mStorage[2 + 3 * inWidthOfX]);\n        numRows.rebind(&mStorage[3 + 3 * inWidthOfX]);\n        gradNew.rebind(&mStorage[4 + 3 * inWidthOfX], inWidthOfX);\n        X_transp_AX.rebind(&mStorage[4 + 4 * inWidthOfX], inWidthOfX, inWidthOfX);\n        logLikelihood.rebind(&mStorage[4 + inWidthOfX * inWidthOfX + 4 * inWidthOfX]);\n        status.rebind(&mStorage[5 + inWidthOfX * inWidthOfX + 4 * inWidthOfX]);\n    }\n\n    Handle mStorage;\n\n  public:\n    typename HandleTraits<Handle>::ReferenceToUInt32 iteration;\n    typename HandleTraits<Handle>::ReferenceToUInt16 widthOfX;\n    typename HandleTraits<Handle>::ColumnVectorTransparentHandleMap coef;\n    typename HandleTraits<Handle>::ColumnVectorTransparentHandleMap dir;\n    typename HandleTraits<Handle>::ColumnVectorTransparentHandleMap grad;\n    typename HandleTraits<Handle>::ReferenceToDouble beta;\n\n    typename HandleTraits<Handle>::ReferenceToUInt64 numRows;\n    typename HandleTraits<Handle>::ColumnVectorTransparentHandleMap gradNew;\n    typename HandleTraits<Handle>::MatrixTransparentHandleMap X_transp_AX;\n    typename HandleTraits<Handle>::ReferenceToDouble logLikelihood;\n    typename HandleTraits<Handle>::ReferenceToUInt16 status;\n};\n\n\n\n\n/**\n * @brief Logistic function\n */\ninline double sigma(double x) {\n    return 1. / (1. + std::exp(-x));\n}\n\n/**\n * @brief Perform the logistic-regression transition step\n */\nAnyType\nlogregr_simple_step_transition::run(AnyType &args) {\n    LogRegrSPTransitionState<MutableArrayHandle<double> > state = args[0];\n    if (args[1].isNull() || args[2].isNull()) { return args[0]; }\n    double y = args[1].getAs<bool>() ? 1. : -1.;\n    MappedColumnVector x;\n    try {\n        // an exception is raised in the backend if args[2] contains nulls\n        MappedColumnVector xx = args[2].getAs<MappedColumnVector>();\n        // x is a const reference, we can only rebind to change its pointer\n        x.rebind(xx.memoryHandle(), xx.size());\n    } catch (const ArrayWithNullException &e) {\n        return args[0];\n    }\n\n    // The following check was added with MADLIB-138.\n    if (!dbal::eigen_integration::isfinite(x)) {\n        warning(\"Design matrix is not finite.\");\n        state.status = TERMINATED;\n        return state;\n    }\n\n    if (state.numRows == 0) {\n        if (x.size() > std::numeric_limits<uint16_t>::max()){\n            warning(\"Number of independent variables cannot be larger than 65535.\");\n            state.status = TERMINATED;\n            return state;\n        }\n\n\n        state.initialize(*this, static_cast<uint16_t>(x.size()));\n        if (!args[3].isNull()) {\n            LogRegrSPTransitionState<ArrayHandle<double> > previousState = args[3];\n\n            state = previousState;\n            state.reset();\n        }\n    }\n    // Now do the transition step\n    state.numRows++;\n    double xc = dot(x, state.coef);\n    state.gradNew.noalias() += sigma(-y * xc) * y * trans(x);\n\n    // Note: sigma(-x) = 1 - sigma(x).\n    double a = sigma(xc) * sigma(-xc);\n    state.X_transp_AX += x * trans(x) * a;\n\n    state.logLikelihood -= std::log( 1. + std::exp(-y * xc) );\n\n    return state;\n}\n\n\n/**\n * @brief Perform the perliminary aggregation function: Merge transition states\n */\nAnyType\nlogregr_simple_step_merge_states::run(AnyType &args) {\n    LogRegrSPTransitionState<MutableArrayHandle<double> > stateLeft = args[0];\n    LogRegrSPTransitionState<ArrayHandle<double> > stateRight = args[1];\n\n    // We first handle the trivial case where this function is called with one\n    // of the states being the initial state\n    if (stateLeft.numRows == 0)\n        return stateRight;\n    else if (stateRight.numRows == 0)\n        return stateLeft;\n\n    // Merge states together and return\n    stateLeft += stateRight;\n    return stateLeft;\n}\n\n\n\n/**\n * @brief Perform the logistic-regression final step\n */\nAnyType\nlogregr_simple_step_final::run(AnyType &args) {\n    // We request a mutable object. Depending on the backend, this might perform\n    // a deep copy.\n    LogRegrSPTransitionState<MutableArrayHandle<double> > state = args[0];\n\n    // Aggregates that haven't seen any data just return Null.\n    if (state.numRows == 0){\n        state.status = NULL_EMPTY;\n        return state;\n    }\n\n    // Note: k = state.iteration\n    if (state.iteration == 0) {\n        // Iteration computes the gradient\n\n        state.dir = state.gradNew;\n        state.grad = state.gradNew;\n    } else {\n        // We use the Hestenes-Stiefel update formula:\n        //\n        //            g_k^T (g_k - g_{k-1})\n        // beta_k = -------------------------\n        //          d_{k-1}^T (g_k - g_{k-1})\n        ColumnVector gradNewMinusGrad = state.gradNew - state.grad;\n        state.beta\n            = dot(state.gradNew, gradNewMinusGrad)\n            / dot(state.dir, gradNewMinusGrad);\n\n        // Do a direction restart (Powell restart)\n        // Note: This is testing whether state.beta < 0 if state.beta were\n        // assigned according to Polak-Ribière\n        if (dot(state.gradNew, gradNewMinusGrad)\n            / dot(state.grad, state.grad) <= std::numeric_limits<double>::denorm_min()) state.beta = 0;\n\n        // d_k = g_k - beta_k * d_{k-1}\n        state.dir = state.gradNew - state.beta * state.dir;\n        state.grad = state.gradNew;\n    }\n\n    // H_k = - X^T A_k X\n    // where A_k = diag(a_1, ..., a_n) and a_i = sigma(x_i c_{k-1}) sigma(-x_i c_{k-1})\n    //\n    //             g_k^T d_k\n    // alpha_k = -------------\n    //           d_k^T H_k d_k\n    //\n    // c_k = c_{k-1} - alpha_k * d_k\n    state.coef += dot(state.grad, state.dir) /\n        as_scalar(trans(state.dir) * state.X_transp_AX * state.dir)\n        * state.dir;\n\n    if(!state.coef.is_finite()){\n        // we don't throw an error - instead set the state status to allow\n        // other states (possibly trained as part of group by) to continue\n        // training\n        warning(\"Over- or underflow in conjugate-gradient step, while updating \"\n              \"coefficients. Input data is likely of poor numerical condition.\");\n        state.status = TERMINATED;\n        return state;\n    }\n\n    state.iteration++;\n    return state;\n}\n\n/**\n * @brief Return the difference in log-likelihood between two states\n */\nAnyType\ninternal_logregr_simple_step_distance::run(AnyType &args) {\n    LogRegrSPTransitionState<ArrayHandle<double> > stateLeft = args[0];\n    LogRegrSPTransitionState<ArrayHandle<double> > stateRight = args[1];\n\n    if(stateLeft.status == NULL_EMPTY || stateRight.status == NULL_EMPTY){\n        return 0.0;\n    }\n    return std::abs(stateLeft.logLikelihood - stateRight.logLikelihood);\n}\n\n/**\n * @brief Return the coefficients and diagnostic statistics of the state\n */\nAnyType\ninternal_logregr_simple_result::run(AnyType &args) {\n    LogRegrSPTransitionState<ArrayHandle<double> > state = args[0];\n    if (state.status == NULL_EMPTY)\n        return Null();\n\n    SymmetricPositiveDefiniteEigenDecomposition<Matrix> decomposition(\n        state.X_transp_AX, EigenvaluesOnly, ComputePseudoInverse);\n\n    return stateToResult(*this, state.coef,\n                         state.X_transp_AX, state.logLikelihood,\n                         state.status, state.numRows);\n}\n\n\n/**\n * @brief Compute the diagnostic statistics\n *\n * This function wraps the common parts of computing the results for both the\n * CG and the IRLS method.\n */\nAnyType stateToResult(\n    const Allocator &inAllocator,\n    const HandleMap<const ColumnVector, TransparentHandle<double> > &inCoef,\n    const Matrix & hessian,\n    const double &logLikelihood,\n    int status,\n    const uint64_t &numRows) {\n\n    SymmetricPositiveDefiniteEigenDecomposition<Matrix> decomposition(\n        hessian, EigenvaluesOnly, ComputePseudoInverse);\n\n    const Matrix &inverse_of_X_transp_AX = decomposition.pseudoInverse();\n    const ColumnVector &diagonal_of_X_transp_AX = inverse_of_X_transp_AX.diagonal();\n\n    MutableNativeColumnVector stdErr(\n        inAllocator.allocateArray<double>(inCoef.size()));\n    MutableNativeColumnVector waldZStats(\n        inAllocator.allocateArray<double>(inCoef.size()));\n    MutableNativeColumnVector waldPValues(\n        inAllocator.allocateArray<double>(inCoef.size()));\n    MutableNativeColumnVector oddsRatios(\n        inAllocator.allocateArray<double>(inCoef.size()));\n\n    for (Index i = 0; i < inCoef.size(); ++i) {\n        stdErr(i) = std::sqrt(diagonal_of_X_transp_AX(i));\n        waldZStats(i) = inCoef(i) / stdErr(i);\n        waldPValues(i) = 2. * prob::cdf( prob::normal(),\n                                         -std::abs(waldZStats(i)));\n        oddsRatios(i) = std::exp( inCoef(i) );\n    }\n\n    // Return all coefficients, standard errors, etc. in a tuple\n    AnyType tuple;\n    tuple << inCoef << logLikelihood << stdErr << waldZStats << waldPValues\n          << oddsRatios << inverse_of_X_transp_AX\n          << sqrt(decomposition.conditionNo()) << status << numRows;\n    return tuple;\n}\n\n} // namespace hello_world\n} // namespace modules\n} // namespace madlib\n", "meta": {"hexsha": "6c5f41fa0677f21159c33a672c0523a4b68de6b9", "size": 15595, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/hello_world/iterative/simple_logistic.cpp", "max_stars_repo_name": "fmcquillan99/apache-madlib", "max_stars_repo_head_hexsha": "e2dea62d1eadc7f662f2d926c71f42332f414ca0", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2018-09-18T07:44:22.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-14T19:45:18.000Z", "max_issues_repo_path": "examples/hello_world/iterative/simple_logistic.cpp", "max_issues_repo_name": "fmcquillan99/apache-madlib", "max_issues_repo_head_hexsha": "e2dea62d1eadc7f662f2d926c71f42332f414ca0", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-09-06T05:50:17.000Z", "max_issues_repo_issues_event_max_datetime": "2018-09-06T05:50:17.000Z", "max_forks_repo_path": "examples/hello_world/iterative/simple_logistic.cpp", "max_forks_repo_name": "fmcquillan99/apache-madlib", "max_forks_repo_head_hexsha": "e2dea62d1eadc7f662f2d926c71f42332f414ca0", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-09-03T20:50:13.000Z", "max_forks_repo_forks_event_max_datetime": "2019-09-03T20:50:13.000Z", "avg_line_length": 34.5022123894, "max_line_length": 103, "alphanum_fraction": 0.6403975633, "num_tokens": 3808, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6261241772283034, "lm_q2_score": 0.519521321952093, "lm_q1q2_score": 0.32528486025981473}}
{"text": "//==================================================================================================\n/*!\n  @file\n\n  @copyright 2016 NumScale SAS\n\n  Distributed under the Boost Software License, Version 1.0.\n  (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\n*/\n//==================================================================================================\n#ifndef BOOST_SIMD_ARCH_COMMON_SCALAR_FUNCTION_LOG2_HPP_INCLUDED\n#define BOOST_SIMD_ARCH_COMMON_SCALAR_FUNCTION_LOG2_HPP_INCLUDED\n#include <boost/simd/function/std.hpp>\n\n#include <boost/simd/detail/dispatch/function/overload.hpp>\n#include <boost/simd/function/musl.hpp>\n#include <boost/simd/function/std.hpp>\n#include <boost/assert.hpp>\n#include <boost/config.hpp>\n#include <cmath>\n#include <boost/simd/function/bitwise_and.hpp>\n#include <boost/simd/function/dec.hpp>\n#include <boost/simd/function/fma.hpp>\n#include <boost/simd/function/frexp.hpp>\n#include <boost/simd/function/horn.hpp>\n#include <boost/simd/function/ilog2.hpp>\n#include <boost/simd/function/musl.hpp>\n#include <boost/simd/function/plain.hpp>\n#include <boost/simd/function/sqr.hpp>\n#include <boost/simd/function/std.hpp>\n\n#include <boost/simd/constant/inf.hpp>\n#include <boost/simd/constant/invlog_2.hpp>\n#include <boost/simd/constant/nan.hpp>\n#include <boost/simd/constant/minf.hpp>\n#include <boost/simd/constant/smallestposval.hpp>\n#include <boost/simd/constant/sqrt_2o_2.hpp>\n\n#include <boost/simd/detail/constant/invlog_2hi.hpp>\n#include <boost/simd/detail/constant/invlog_2lo.hpp>\n\n#include <boost/simd/detail/dispatch/meta/as_integer.hpp>\n\n#include <cmath>\nnamespace boost { namespace simd { namespace ext\n{\n  namespace bd = boost::dispatch;\n  namespace bs = boost::simd;\n\n  BOOST_DISPATCH_OVERLOAD ( log2_\n                          , (typename A0)\n                          , bd::cpu_\n                          , bd::scalar_< bd::floating_<A0> >\n                          )\n  {\n    BOOST_FORCEINLINE A0 operator() (A0 const& a0) const BOOST_NOEXCEPT\n    {\n      return musl_(log2)(a0);\n    }\n  };\n\n  BOOST_DISPATCH_OVERLOAD ( log2_\n                          , (typename A0)\n                          , bd::cpu_\n                          , bd::scalar_< bd::arithmetic_<A0> >\n                          )\n  {\n    BOOST_FORCEINLINE A0 operator() (A0 const& a0) const BOOST_NOEXCEPT\n    {\n      return bs::ilog2(a0);\n    }\n  };\n\n  BOOST_DISPATCH_OVERLOAD ( log2_\n                          , (typename A0)\n                          , bd::cpu_\n                          , bs::std_tag\n                          , bd::scalar_< bd::arithmetic_<A0> >\n                          )\n  {\n    BOOST_FORCEINLINE A0 operator() (const std_tag &, A0 a0\n                                    ) const BOOST_NOEXCEPT\n    {\n      return std::log2(a0);\n    }\n  };\n\n  BOOST_DISPATCH_OVERLOAD ( log2_\n                          , (typename A0)\n                          , bd::cpu_\n                          , bs::plain_tag\n                          , bd::scalar_< bd::arithmetic_<A0> >\n                          )\n  {\n    BOOST_FORCEINLINE A0 operator() (const std_tag &, A0 a0\n                                    ) const BOOST_NOEXCEPT\n    {\n      return musl_(log2(a0));\n    }\n  };\n\n  BOOST_DISPATCH_OVERLOAD ( log2_\n                          , (typename A0)\n                          , bd::cpu_\n                          , bs::musl_tag\n                          , bd::scalar_< bd::single_<A0> >\n                          )\n  {\n    /* origin: FreeBSD /usr/src/lib/msun/src/e_log2f.c */\n    /*\n     * ====================================================\n     * Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved.\n     *\n     * Developed at SunPro, a Sun Microsystems, Inc. business.\n     * Permission to use, copy, modify, and distribute this\n     * software is freely granted, provided that this notice\n     * is preserved.\n     * ====================================================\n     */\n     BOOST_FORCEINLINE A0 operator() (const musl_tag &, A0 x) const BOOST_NOEXCEPT\n    {\n      using uiA0 = bd::as_integer_t<A0, unsigned>;\n      using iA0 = bd::as_integer_t<A0,   signed>;\n      uiA0 ix = bitwise_cast<uiA0>(x);\n      iA0 k = 0;\n      if (ix < 0x00800000 || ix>>31)         /* x < 2**-126  */\n      {\n        if (ix<<1 == 0) return Minf<A0>();  /* log(+-0)=-inf */\n        if (ix>>31) return Nan<A0>();       /* log(-#) = NaN */\n#ifndef BOOST_SIMD_NO_DENORMALS\n        /* subnormal number, scale up x */\n        k -= 25;\n        x *= 33554432.0f;\n         ix = bitwise_cast<iA0>(x);\n#endif\n      }\n      else if (ix >= 0x7f800000)\n      {\n        return x;\n      }\n      else if (ix == 0x3f800000)\n        return 0;\n\n      /* reduce x into [sqrt(2)/2, sqrt(2)] */\n      ix += 0x3f800000 - 0x3f3504f3;\n      k += bitwise_cast<iA0>(ix>>23) - 0x7f;\n      ix = (ix&0x007fffff) + 0x3f3504f3;\n      x =  bitwise_cast<A0>(ix);\n      A0 f = dec(x);\n      A0 s = f/(2.0f + f);\n      A0 z = sqr(s);\n      A0 w = sqr(z);\n      A0 t1= w*horn<A0, 0x3eccce13, 0x3e789e26>(w);\n      A0 t2= z*horn<A0, 0x3f2aaaaa, 0x3e91e9ee>(w);\n      A0 R = t2 + t1;\n      A0 hfsq = 0.5f*sqr(f);\n      return -(hfsq-(s*(hfsq+R))-f)*Invlog_2<A0>()+k;\n      // The original algorithm does some extra calculation in place of the return line\n      // to get extra precision but this is uneeded for float as the exhaustive test shows\n      // a 0.5 ulp maximal error on the full range.\n      // Moreover all log2(exp2(i)) i =  1..31 are flint\n      // I leave the code here in case an exotic proc will not play the game.\n      //       A0  hi = f - hfsq;\n      //       hi =  bitwise_and(hi, uiA0(0xfffff000ul));\n      //       A0  lo = fma(s, hfsq+R, f - hi - hfsq);\n      //       return fma((lo+hi), Invlog_2lo<A0>(), lo*Invlog_2hi<A0>() + hi*Invlog_2hi<A0>() + k);\n    }\n  };\n\n  BOOST_DISPATCH_OVERLOAD ( log2_\n                          , (typename A0)\n                          , bd::cpu_\n                          , bs::musl_tag\n                          , bd::scalar_< bd::double_<A0> >\n                          )\n  {\n    /* origin: FreeBSD /usr/src/lib/msun/src/e_log2.c */\n    /*\n     * ====================================================\n     * Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved.\n     *\n     * Developed at SunSoft, a Sun Microsystems, Inc. business.\n     * Permission to use, copy, modify, and distribute this\n     * software is freely granted, provided that this notice\n     * is preserved.\n     * ====================================================\n     */\n    BOOST_FORCEINLINE A0 operator() (const musl_tag &, A0 x) const BOOST_NOEXCEPT\n    {\n      using uiA0 = bd::as_integer_t<A0, unsigned>;\n      using iA0 = bd::as_integer_t<A0,   signed>;\n      uiA0 hx = bitwise_cast<uiA0>(x) >> 32;\n      iA0 k = 0;\n      if (hx < 0x00100000 || hx>>31)\n      {\n        if(is_eqz(x))\n          return Minf<A0>();  /* log(+-0)=-inf */\n        if (hx>>31)\n          return Nan<A0>(); /* log(-#) = NaN */\n        /* subnormal number, scale x up */\n#ifndef BOOST_SIMD_NO_DENORMALS\n        k -= 54;\n        x *=  18014398509481984.0;\n        hx = bitwise_cast<uiA0>(x) >> 32;\n#endif\n      }\n      else if (hx >= 0x7ff00000)\n      {\n        return x;\n      }\n      else if (x == One<A0>())\n        return Zero<A0>();\n      /* reduce x into [sqrt(2)/2, sqrt(2)] */\n      hx += 0x3ff00000 - 0x3fe6a09e;\n      k += bitwise_cast<iA0>(hx>>20) - 0x3ff;\n      hx = (hx&0x000fffff) + 0x3fe6a09e;\n      x = bitwise_cast<A0>( (uint64_t)hx<<32 | (bitwise_and(0xffffffffull, bitwise_cast<uiA0>(x))));\n      A0 f = dec(x);\n      A0 hfsq = 0.5*sqr(f);\n      A0 s = f/(2.0f + f);\n      A0 z = sqr(s);\n      A0 w = sqr(z);\n      A0 t1= w*horn<A0, 0x3fd999999997fa04ll, 0x3fcc71c51d8e78afll, 0x3fc39a09d078c69fll > (w);\n      A0 t2= z*horn<A0, 0x3fe5555555555593ll, 0x3fd2492494229359ll\n                      , 0x3fc7466496cb03dell, 0x3fc2f112df3e5244ll> (w);\n      A0 R = t2 + t1;\n//        return -(hfsq-(s*(hfsq+R))-f)*Invlog_2<A0>()+dk;  // fast ?\n\n\n      /*\n       * f-hfsq must (for args near 1) be evaluated in extra precision\n       * to avoid a large cancellation when x is near sqrt(2) or 1/sqrt(2).\n       * This is fairly efficient since f-hfsq only depends on f, so can\n       * be evaluated in parallel with R.  Not combining hfsq with R also\n       * keeps R small (though not as small as a true `lo' term would be),\n       * so that extra precision is not needed for terms involving R.\n       *\n       * Compiler bugs involving extra precision used to break Dekker's\n       * theorem for spitting f-hfsq as hi+lo, unless double_t was used\n       * or the multi-precision calculations were avoided when double_t\n       * has extra precision.  These problems are now automatically\n       * avoided as a side effect of the optimization of combining the\n       * Dekker splitting step with the clear-low-bits step.\n       *\n       * y must (for args near sqrt(2) and 1/sqrt(2)) be added in extra\n       * precision to avoid a very large cancellation when x is very near\n       * these values.  Unlike the above cancellations, this problem is\n       * specific to base 2.  It is strange that adding +-1 is so much\n       * harder than adding +-ln2 or +-log10_2.\n       *\n       * This uses Dekker's theorem to normalize y+val_hi, so the\n       * compiler bugs are back in some configurations, sigh.  And I\n       * don't want to used double_t to avoid them, since that gives a\n       * pessimization and the support for avoiding the pessimization\n       * is not yet available.\n       *\n       * The multi-precision calculations for the multiplications are\n       * routine.\n       */\n\n      /* hi+lo = f - hfsq + s*(hfsq+R) ~ log(1+f) */\n      A0  hi = f - hfsq;\n      hi =  bitwise_and(hi, (Allbits<uiA0>() << 32));\n      A0 lo = f - hi - hfsq + s*(hfsq+R);\n\n      A0 val_hi = hi*Invlog_2hi<A0>();\n      A0 val_lo = fma(lo+hi, Invlog_2lo<A0>(), lo*Invlog_2hi<A0>());\n\n      A0 dk = k;\n      A0 w1 = dk + val_hi;\n      val_lo += (dk - w1) + val_hi;\n      val_hi = w1;\n      return val_lo + val_hi;\n    }\n  };\n\n  BOOST_DISPATCH_OVERLOAD ( log2_\n                          , (typename A0)\n                          , bd::cpu_\n                          , bs::plain_tag\n                          , bd::scalar_< bd::floating_<A0> >\n                          )\n  {\n    BOOST_FORCEINLINE A0 operator() (const plain_tag &, A0 x) const BOOST_NOEXCEPT\n    {\n      return musl_(log2)(x); //the \"plain\" version of the algorithm is never speedier than the \"musl\" version.\n      // the call is here to allow a scalar fallback to simd calls\n    }\n  };\n\n} } }\n\n\n#endif\n", "meta": {"hexsha": "4fbfd53fb9584ee929882eac28bb2441ca5b0355", "size": 10603, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/arch/common/scalar/function/log2.hpp", "max_stars_repo_name": "SylvainCorlay/pythran", "max_stars_repo_head_hexsha": "908ec070d837baf77d828d01c3e35e2f4bfa2bfa", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2018-02-25T22:23:33.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-15T15:13:12.000Z", "max_issues_repo_path": "third_party/boost/simd/arch/common/scalar/function/log2.hpp", "max_issues_repo_name": "SylvainCorlay/pythran", "max_issues_repo_head_hexsha": "908ec070d837baf77d828d01c3e35e2f4bfa2bfa", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "third_party/boost/simd/arch/common/scalar/function/log2.hpp", "max_forks_repo_name": "SylvainCorlay/pythran", "max_forks_repo_head_hexsha": "908ec070d837baf77d828d01c3e35e2f4bfa2bfa", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2017-12-12T12:36:31.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-10T14:27:07.000Z", "avg_line_length": 35.9423728814, "max_line_length": 110, "alphanum_fraction": 0.5379609544, "num_tokens": 3009, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6654105454764747, "lm_q2_score": 0.48828339529583464, "lm_q1q2_score": 0.32490892041090647}}
{"text": "/*  Copyright (C) 2017 NEC Laboratories America, Inc. (\"NECLA\"). All rights reserved.\n *\n * This source code is licensed under the license found in the LICENSE file in\n * the root directory of this source tree. An additional grant of patent rights\n * can be found in the PATENTS file in the same directory.\n */\n\n#include \"optimizelu.hh\"\n#include \"utils.h\"\n#include \"boost/iterator/counting_iterator.hpp\"\n#include <boost/numeric/conversion/bounds.hpp>  // boost::numeric::bounds<T>\n#include <cmath>\n#include <iostream>\n\n#include \"constants.h\"\n\n#define __restricted /* __restricted seems to be an error */\n\n\nnamespace mcsolver_detail{\n\n  using namespace std;  \n  /** get optimal {l,u} bounds given projection and class order.\n   * Computationally expensive, so it should be done sparingly.\n   */\n  void optimizeLU(VectorXd& l, VectorXd& u,\n\t\t  const VectorXd& projection, const SparseMb& y,\n\t\t  const vector<int>& class_order, const vector<int>& sorted_class,\n\t\t  const VectorXd& wc, const VectorXi& nclasses, \n\t\t  const VectorXd& inside_weight, const VectorXd& outside_weight,\n\t\t  const boolmatrix& filtered,\n\t\t  const double C1, const double C2,\n\t\t  const param_struct& params)\n  {\n#define BOUNDGRAD_THREAD 1 // 1=good\n    \n    // -------------- and sanity checks\n#if MCTHREADS && defined(_OPENMP)\n    if( omp_in_parallel() )\n      throw runtime_error(\" ERROR: please don't call optimizeLU from and omp parallel section\");\n#endif\n    static bool check_once=false;\n    if( !check_once ){\n      size_t nErase=0U;\n#if MCTHREADS && defined(_OPENMP)\n#pragma omp parallel for schedule(static)\n#endif\n      for(size_t o=0U; o<y.outerSize(); ++o){\n\tfor(SparseMb::InnerIterator it(y,o); it; ++it) {\n\t  if( it.value()==false ){\n\t    ++nErase;\n\t  }\n\t}\n      }\n      if( nErase )\n\tthrow runtime_error(\" ERROR: SparseMb 'y' should have only 'true' entries\");\n      if( ! y.isCompressed() )\n\tthrow runtime_error(\" ERROR: expect SparseMb 'y' to be compressed sparse\");\n      check_once=true;\n    }\n    // ------------------------------------------------------\n    size_t const n = projection.size();\n    size_t const noClasses = y.cols();\n    bool const none_filtered = filtered.count()==0;\n    VectorXd allproj(2*n);\n    allproj << (projection.array() - 1), (projection.array() + 1);\n    std::vector<size_t> indices(allproj.size());\n    sort_index(allproj, indices);\n    \n    // yes, co[sc[c]] == c\n    // initialize the gradients for u and l \n    VectorXd gradu(noClasses); // by ranked classes, to minimize cache misses/false sharing\n    VectorXd gradl(noClasses); // by ranked classes, to minimize cache misses/false sharing\n#if MCTHREADS && defined(_OPENMP)\n    size_t const ck = std::max(size_t{256U},size_t{noClasses/omp_get_max_threads()});\n#pragma omp parallel for schedule(static,ck)\n#endif\n    for (size_t sc = 0; sc <noClasses; ++sc) {\n      int const c = sorted_class[sc];\n      double const classweight = wc.coeff(c); \n      if (classweight <= 0.0) { // no examples of this class\n\t// classes with no weight (wc[]) get {l,u} bounds set to high/low values.\n\tu.coeffRef(c) = boost::numeric::bounds<double>::lowest()/10; // the /10 is needed because octave has trouble reading back ascii files that are written with the highest/lowest limits\n\tl.coeffRef(c) = boost::numeric::bounds<double>::highest()/10; // the /10 is needed because octave has trouble reading back ascii files that are written with the highest/lowest limits;\n\tgradu.coeffRef(sc) = -1.0;\n\tgradl.coeffRef(sc) = -1.0;\n      } else {\n\tgradu.coeffRef(sc) = C1*classweight;\n\tgradl.coeffRef(sc) = C1*classweight;\n      }\n    }\n    \n    \n    \n#if BOUNDGRAD_THREAD && MCTHREADS && defined(_OPENMP)\n    int const max_n_chunks = omp_get_max_threads();\n    \n    int const min_chunk_size = 10000;     // need a test case to set this value XXX\n#endif\n    \n#if MCTHREADS\n#pragma omp parallel default(none) shared(l, u, allproj, indices, filtered, y, class_order, sorted_class, wc, nclasses, inside_weight, outside_weight, params, gradu, gradl)\n#endif\n    {\n#if MCTHREADS\n#pragma omp single nowait\n#endif\n      { // calculate the optimal value for upper bounds -- iterate from beginning\n        std::vector<int> classes;\n        classes.reserve(nclasses.maxCoeff());\n        for (std::vector<size_t>::const_iterator i = indices.begin(); i != indices.end(); ++i) {\n\t  bool plus = false;\n\t  size_t idx = *i;\n\t  if (idx >= n) { plus = true; idx -= n; }\n\t  \n\t  if (plus) { // only the upper bounds of the classes of this example are affected\n\t    double const class_weight = C1*inside_weight.coeff(idx);\n\t    for (SparseMb::InnerIterator it(y,idx); it; ++it) {\n\t      int const cs = it.col();                // raw [unsorted] class\n\t      int const sc = class_order[cs];         // sorted class number\n\t      if( gradu.coeff(sc) >= 0 && (gradu.coeffRef(sc) -= class_weight) <  std::numeric_limits<double>::epsilon()*class_weight*10){\n\t\tu.coeffRef(cs) = allproj.coeff(*i);\n\t      }\n\t    }\n\t  }else{\n\t    // only the classes ranked lower than the classes of this example are affected\n\t    sortedClasses( /*OUT*/ classes, /*IN*/ class_order, y, idx );\n\t    if (classes.size() == 0) continue;\n\t    if (classes.back() == 0) continue;\n\t    \n\t    double const other_weight = C2*outside_weight.coeff(idx);\n\t    // how many classes of the curent instance should be ranked higher \n\t    //  times the weight of each\n\t    //  if each class has its own weight will need to\n\t    //  be calculated below (or have it precomputed for each example \n\t    //  as a corresponding wclasses to nclasses to be wclasses the same as wc \n\t    //  corresponds to nc\n\t    double const right_update = other_weight * nclasses.coeff(idx);\n#if BOUNDGRAD_THREAD && MCTHREADS && defined(_OPENMP)\n\t    // make sure there is enough work to do to paralelize this\n\t    int n_chunks = classes.back()/min_chunk_size + 1;\n\t    n_chunks = n_chunks < max_n_chunks?n_chunks:max_n_chunks;\n\t    if( n_chunks > 1 ){\n\t      int chunk_size = classes.back()/n_chunks;\n\t      int remaining = classes.back()%n_chunks;\n\t      for (int chunk=0; chunk < n_chunks; ++chunk)\n\t\t{\n#pragma omp task default(shared) firstprivate(chunk) shared(gradu, u, idx, i, sorted_class, classes, allproj, filtered, chunk_size, remaining)\n\t\t  {\n\t\t    int sc_start = chunk*chunk_size + (chunk<remaining?chunk:remaining);\n\t\t    int sc_incr = chunk_size + (chunk<remaining);\n\t\t    getBoundGrad(gradu, u, idx, *i, sorted_class, sc_start, sc_start + sc_incr, classes, right_update, -other_weight, allproj, none_filtered, filtered);\n\t\t  }\n#pragma omp taskwait // need to wait for all tasks to finish before moving to the next example\n\t\t}\n\t    }else{\n\t      getBoundGrad(gradu, u, idx, *i, sorted_class, 0,classes.back(),classes,right_update,-other_weight,allproj,none_filtered,filtered);\n\t    }\n#else // not _OPENMP\n\t    getBoundGrad(gradu, u, idx, *i, sorted_class, 0,classes.back(),classes,right_update,-other_weight,allproj,none_filtered,filtered);\n#endif // _OPENMP\t   \n\t  }\n        }\n      }\n      \n#if MCTHREADS\n#pragma omp single nowait\n#endif\n      { // calculate the optimal value for lower bounds -- iterate from end\n        std::vector<int> classes;\n        classes.reserve(nclasses.maxCoeff());\n        for (std::vector<size_t>::const_reverse_iterator i = indices.rbegin(); i != indices.rend(); i++) {\n\t  bool plus = false;\n\t  size_t idx = *i;\n\t  if (idx >= n) { plus = true; idx -= n; }\n\t  \n\t  if (!plus){ // only the lower bounds of the classes of this example are affected\n\t    double const class_weight = inside_weight.coeff(idx)*C1;\n\t    for (SparseMb::InnerIterator it(y,idx); it; ++it) {\n\t      //assert( it.value() ); //if (it.value())\n\t      int cs = it.col();\n\t      int sc = class_order[cs];\n\t      if (gradl.coeff(sc) >= 0 && (gradl.coeffRef(sc) -= class_weight) < std::numeric_limits<double>::epsilon()*class_weight*10){\n\t\tl.coeffRef(cs) = allproj.coeff(*i);\n\t      }\n\t    }\n\t  }else{\n\t    // only the classes ranked higher than the classes of this example are affected\n\t    // calling y.coeff is expensive so get the classes in the ranked order here\n\t    sortedClasses( /*OUT*/ classes, /*IN*/ class_order, y, idx );\n\t    if(classes.size() == 0U) continue;\n\t    // if a class has lower rank than the lowest rank class of this example\n\t    // it's lower bound will not be influenced by this example\n\t    int n_active = noClasses - classes.front() - 1;\n\t    if (n_active <= 0)\n\t      continue;\n\t    \n\t    double const other_weight = outside_weight.coeff(idx)*C2;\n#if BOUNDGRAD_THREAD && MCTHREADS && defined(_OPENMP)\n\t    // make sure there is enough work to do to paralelize this\n\t    int n_chunks = n_active/min_chunk_size + 1;\n\t    n_chunks = n_chunks < max_n_chunks?n_chunks:max_n_chunks;\n\t    if( n_chunks > 1 ){\n\t      int chunk_size = n_active/n_chunks;\n\t      int remaining = n_active%n_chunks;\n\t      for (int chunk=0; chunk < n_chunks; ++chunk)\n\t\t{\n#pragma omp task default(shared) firstprivate(chunk) shared(gradl, l, idx, i, sorted_class, classes, allproj, filtered, chunk_size, remaining)\n\t\t  {\n\t\t    int sc_start = classes.front() + 1 + chunk*chunk_size + (chunk<remaining?chunk:remaining);\n\t\t    int sc_incr = chunk_size + (chunk<remaining);\n\t\t    getBoundGrad(gradl, l, idx, *i, sorted_class, sc_start, sc_start + sc_incr, classes, 0.0, other_weight, allproj, none_filtered, filtered);\n\t\t  }\n#pragma omp taskwait  // need to wait for all tasks to finish before moving to the next example\n\t\t}\n\t    }else{\n\t      getBoundGrad(gradl, l, idx, *i, sorted_class, classes.front() + 1,noClasses,classes, 0.0, other_weight, allproj, none_filtered, filtered);\n\t    }\n#else // not _OPENMP\n\t    getBoundGrad(gradl, l, idx, *i, sorted_class, classes.front() + 1,noClasses,classes, 0.0, other_weight, allproj, none_filtered, filtered);\n#endif // _OPENMP\n\t  }\n        }\n      } // omp single\n    } // omp parallel   \n  }\n}\n", "meta": {"hexsha": "bcb829098a371e99d6da6dc3f44976edc639a0e5", "size": 9810, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/c/optimizelu.cpp", "max_stars_repo_name": "rupea/LabelFilters", "max_stars_repo_head_hexsha": "a70b1f90427fe44bd43fee842aad34704d51854c", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2019-04-23T01:32:47.000Z", "max_stars_repo_stars_event_max_datetime": "2019-12-12T07:02:52.000Z", "max_issues_repo_path": "src/c/optimizelu.cpp", "max_issues_repo_name": "rupea/LabelFilters", "max_issues_repo_head_hexsha": "a70b1f90427fe44bd43fee842aad34704d51854c", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-01-21T22:05:09.000Z", "max_issues_repo_issues_event_max_datetime": "2019-03-06T15:37:35.000Z", "max_forks_repo_path": "src/c/optimizelu.cpp", "max_forks_repo_name": "rupea/LabelFilters", "max_forks_repo_head_hexsha": "a70b1f90427fe44bd43fee842aad34704d51854c", "max_forks_repo_licenses": ["BSD-3-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.0263157895, "max_line_length": 184, "alphanum_fraction": 0.6637104995, "num_tokens": 2575, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6548947155710234, "lm_q2_score": 0.4960938294709195, "lm_q1q2_score": 0.3248892273478976}}
{"text": "/* =========================================================================\n   Copyright (c) 2010-2014, Institute for Microelectronics,\n                            Institute for Analysis and Scientific Computing,\n                            TU Wien.\n   Portions of this software are copyright by UChicago Argonne, LLC.\n\n                            -----------------\n                  ViennaCL - The Vienna Computing Library\n                            -----------------\n\n   Project Head:    Karl Rupp                   rupp@iue.tuwien.ac.at\n\n   (A list of authors and contributors can be found in the PDF manual)\n\n   License:         MIT (X11), see file LICENSE in the base directory\n============================================================================= */\n\n/** \\example multithreaded.cpp\n*\n*   This tutorial shows how to use ViennaCL with multiple threads, one thread per GPU.\n*   The use of one thread per context (host, CUDA, OpenCL) is supported.\n*   However, using more than one thread per context is not fully covered by the OpenCL standard.\n*   It is, however, perfectly fine to use multiple OpenCL contexts simultaneously, each using one thread.\n*\n*   We start with including the necessary headers:\n**/\n\n#ifndef VIENNACL_WITH_OPENCL\n  #define VIENNACL_WITH_OPENCL\n#endif\n\n// include necessary system headers\n#include <iostream>\n\n//include basic scalar and vector types of ViennaCL\n#include \"viennacl/scalar.hpp\"\n#include \"viennacl/vector.hpp\"\n#include \"viennacl/matrix.hpp\"\n\n#include \"viennacl/ocl/device.hpp\"\n#include \"viennacl/ocl/platform.hpp\"\n#include \"viennacl/ocl/backend.hpp\"\n\n//include the generic inner product functions of ViennaCL\n#include \"viennacl/linalg/norm_2.hpp\"\n\n// Some helper functions for this tutorial:\n#include \"Random.hpp\"\n\n#include <boost/thread.hpp>\n\n\n/**\n*  Each thread runs a separate task, for which we provide the following functor.\n*  For each thread, vector operations and a vector norm gets computed.\n**/\ntemplate<typename NumericT>\nclass worker\n{\npublic:\n  worker(std::size_t tid) : thread_id_(tid) {}\n\n  void operator()()\n  {\n    std::size_t N = 6;\n\n    viennacl::context ctx(viennacl::ocl::get_context(static_cast<long>(thread_id_)));\n    viennacl::vector<NumericT> u = viennacl::scalar_vector<NumericT>(N, NumericT(1) * NumericT(thread_id_ + 1), ctx);\n    viennacl::vector<NumericT> v = viennacl::scalar_vector<NumericT>(N, NumericT(2) * NumericT(thread_id_ + 1), ctx);\n    viennacl::matrix<NumericT> A = viennacl::linalg::outer_prod(u, v);\n    viennacl::vector<NumericT> x(u);\n\n    u += v;\n    NumericT result = viennacl::linalg::norm_2(u);\n\n    std::stringstream ss;\n    ss << \"Result of thread \" << thread_id_ << \" on device \" << viennacl::ocl::get_context(static_cast<long>(thread_id_)).devices()[0].name() << \": \" << result << std::endl;\n    ss << \"  A: \" << A << std::endl;\n    ss << \"  x: \" << x << std::endl;\n    message_ = ss.str();\n  }\n\n  std::string message() const { return message_; }\n\nprivate:\n  std::string message_;\n  std::size_t thread_id_;\n};\n\n/**\n*   In the main routine we create two OpenCL contexts and then use one thread per context to run the operations in the functor defined above.\n**/\nint main()\n{\n  // Change this type definition to double if your gpu supports that\n  typedef float       ScalarType;\n\n  if (viennacl::ocl::get_platforms().size() == 0)\n  {\n    std::cerr << \"Error: No platform found!\" << std::endl;\n    return EXIT_FAILURE;\n  }\n\n  /**\n  *   Part 1: Setup first device for first context, second device for second context:\n  **/\n  viennacl::ocl::platform pf = viennacl::ocl::get_platforms()[0];\n  std::vector<viennacl::ocl::device> const & devices = pf.devices();\n\n  // Set first device to first context:\n  viennacl::ocl::setup_context(0, devices[0]);\n\n  // Set second device for second context (use the same device for the second context if only one device available):\n  if (devices.size() > 1)\n    viennacl::ocl::setup_context(1, devices[1]);\n  else\n    viennacl::ocl::setup_context(1, devices[0]);\n\n  /**\n  *   Part 2: Now let two threads operate on two GPUs in parallel.\n  **/\n\n  worker<ScalarType> work_functor0(0);\n  worker<ScalarType> work_functor1(1);\n  boost::thread worker_thread_0(boost::ref(work_functor0));\n  boost::thread worker_thread_1(boost::ref(work_functor1));\n\n  worker_thread_0.join();\n  worker_thread_1.join();\n\n  std::cout << work_functor0.message() << std::endl;\n  std::cout << work_functor1.message() << std::endl;\n\n  /**\n  *  We're done - print a success message.\n  **/\n  std::cout << \"!!!! TUTORIAL COMPLETED SUCCESSFULLY !!!!\" << std::endl;\n\n  return EXIT_SUCCESS;\n}\n\n", "meta": {"hexsha": "13a3d9f05331f9d55c6e42d555f307000d93fa6f", "size": 4591, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/tutorial/multithreaded.cpp", "max_stars_repo_name": "ddemidov/viennacl-dev", "max_stars_repo_head_hexsha": "0f7de9cd28e54a5ca8f7c2ab03263bc56bf004ef", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2016-08-23T17:05:21.000Z", "max_stars_repo_stars_event_max_datetime": "2016-08-23T17:06:24.000Z", "max_issues_repo_path": "examples/tutorial/multithreaded.cpp", "max_issues_repo_name": "ddemidov/viennacl-dev", "max_issues_repo_head_hexsha": "0f7de9cd28e54a5ca8f7c2ab03263bc56bf004ef", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/tutorial/multithreaded.cpp", "max_forks_repo_name": "ddemidov/viennacl-dev", "max_forks_repo_head_hexsha": "0f7de9cd28e54a5ca8f7c2ab03263bc56bf004ef", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.3309859155, "max_line_length": 173, "alphanum_fraction": 0.6445218907, "num_tokens": 1157, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.32477183492559664}}
{"text": "/* \n  uniform_smooth_noise64.hh\n  \n  Copyright (c) 2018 Ryan P. Nicholl, \"Exaeta\", <exaeta@protonmail.com>\n  \n    https://github.com/Exaeta/det_noise64\n    \n    uniform_smooth_noise64 is a N-dimensional uniform smooth noise \n    function, but I'm going to change the hash function into something \n    faster/more well known in a later version (and/or allow templating \n    the hash used). The next version or version with templated hash will\n    be cross platform deterministic.\n    \n    It doesn't rely on any third party libraries except boost::multiprecision,\n    which can be substituited for any library that provides a 128-bit \n    unsigned integer.\n    \n    Any donations would be appreciated. :)\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#ifndef RPNX_G_NOISE_HH\n#define RPNX_G_NOISE_HH\n\n\n\n#include <array>\n#include <cinttypes>\n#include <random>\n#include <boost/multiprecision/cpp_int.hpp> \n\nnamespace rpnx\n{\n  \n  using uint64_t = std::uint64_t;\n  using uint128_t = boost::multiprecision::uint128_t;\n  \n  /*\n    This function is probably not cryptographically secure.\n    For insecure functions only.\n  */\n  template <std::size_t N>\n  std::uint64_t det_point_noise64(std::array<std::uint64_t, N> inputs, std::size_t c = 5, std::uint64_t seed = 0)\n  {\n    std::uint64_t output = seed + 0xFAFAFAFAFAFAFAFAull;\n    for (std::size_t k = 0; k < c; k++)\n    {\n      for (std::size_t i = 0; i < N; i++)\n      {\n        output = (output >> 17) | (output  << (64 - 17));\n        output += inputs[i];\n        output = (output >> ((k+inputs[i]) &0x0F)) | (output  << (64 - ((k+inputs[i]) &0x0F)));\n        output ^= 7;\n        output ^= ((output & (0xbeull << 31)) >> 21);\n        output += 1;\n        \n      }\n    }\n    output = (output >> 17) | (output  << (64 - 17));\n    \n    return output;\n  }\n  \n  \n  \n  template <std::size_t N>\n  bool det_point_noise1(std::array<std::uint64_t, N> inputs)\n  {\n    \n    std::uint64_t output = 0xFAFAFAFAFAFAFAFAull;\n    for (std::size_t k = 0; k < 4; k++)\n    {\n      for (std::size_t i = 0; i < N; i++)\n      {\n        output = (output >> 17) | (output  << (64 - 17));\n        output += inputs[i];      \n        output ^= 7;\n        output ^= ((output & (0xbeull << 31)) >> 21);\n        output += k;\n      }\n    }\n    output = (output >> 19) | (output  << (64 - 19));\n    \n    return 1 & ( (output >> 7) ^ (output >> 3) ^ (output >> 5) ^ \n    (output >> 2) ^ (output >> 11) ^ (output >> 17) ^ (output >> 13) );\n  }\n\n  \n  /** A deterministic pseudo-random N-dimensional smooth noise function, \n      which, assuming the values of the input and hash function are \n      uniformly distributed, provides uniformly distributed output.\n      \n      The algorithm used by this function might be changed in a future\n      version of this library.      \n      \n      @param C C is the template parameter that represents the number of\n      bits used to interpolate between coordinates. A higher value of C\n      will make the noise smooth over a larger range.\n      \n      @param N N is the number of elements in the array. Generally leave\n      this to automatic deduction.\n      \n      @param inputs A std::array of N 64-bit integers\n      \n      @time O(N 2^N), O(1) as compiled\n      \n      @space O(2^N),  O(1) as compiled\n  */\n  template <std::size_t C = 32, std::size_t N = 1>\n  std::uint64_t wave_noise64(std::array<std::uint64_t, N> inputs, std::uint64_t seed = 0)\n  {\n    using u64 = std::uint64_t;\n    using u128 = uint128_t;\n    using std::uint8_t;\n    \n    u64 out=0;\n    \n    std::array<uint64_t, (1 << N)> field_corners;\n    // 2 ^ N dimensions\n    // gathers the values in each corner.\n    \n    std::mt19937 rg;\n    \n    std::uint8_t r = 0; // used later;\n    \n    std::array<std::uint64_t, N> field_inputs = inputs;\n    // Each dimension has a set of inputs\n      \n    for (std::size_t k = 0; k < field_inputs.size(); k++)\n    {\n      field_inputs[k] >>= C;\n    \n      // only the first N-C bits are significant to the field\n       \n     \n    }\n      \n    \n    for (std::size_t i = 0; i < field_corners.size(); i++)\n    {\n   \n      std::array<std::uint64_t, N> field_inputs2 = field_inputs;\n      \n      \n      for (std::size_t k = 0; k < N; k++)\n      {\n        if (i & (1 << k)) field_inputs2[k]++;\n        // We must adjust the field inputs depending on which \"corners\"\n        // we are in.\n      }\n      \n      field_corners[i] = det_point_noise64(field_inputs2, 8, seed);\n      // calculate the corner values\n      \n      r += field_corners[i] & 0xFF;\n      // replace lost randomness with this value;\n      \n      \n    }   \n    \n   // std::cout << \"intial corner[0]=\" << field_corners[0] << std::endl;\n    \n    std::array<std::uint64_t, N> sigvals;\n    std::array<bool, N> bvals;\n    for (std::size_t i = 0; i < N; i++)\n    {\n      sigvals[i] = inputs[i] & ((std::uint64_t(1) << C) - 1);\n      bvals[i] = 1 & inputs[i] >> C;\n    }\n    // We need to know the dimensional significance of dimension in\n    // order to interpolate the values correctly.\n    \n    \n    // The following code interpolates the N-dimensional structure\n    // in N log N time by collapsing each dimension one at a time\n    // until the structure is 0-dimensional and has only 1 value\n    \n    std::size_t q = N;\n    // q here is to avoid taking logs later\n    \n    \n    out = 0;\n    \n    for (size_t z = 0; z < N; z++)\n    {\n      u64 a = det_point_noise64(std::array<u64, 1>{field_inputs[z]}, 5, z+seed);\n      u64 b = det_point_noise64(std::array<u64, 1>{field_inputs[z]+1}, 5, z+seed);\n      \n      u64 v1 = sigvals[z];\n      u64 v2 = (u64(1) << C) - v1;\n      \n      //std::swap(a, b);\n      if (bvals[z]) \n      {\n        std::swap(a, b);\n        std::swap(v1, v2);\n      }\n      \n      u64 m1 = static_cast<u64>( ((u128(b) * v1) + (u128(a) * v2)) >> C );\n      \n      out += 0;\n      out += m1;\n      \n      \n      \n      \n    }\n    \n     if (out & (std::uint64_t(1) << 63))\n    {\n      out = ((~out ^ 1) << 1) | 1;\n    }\n    else out = out << 1;\n    \n    /* The transformation above is supposed to redistribute the \"out\" \n    value such that values near 0 are \"similar\" so there aren't abrupt \n    transitions due to modular arithmetic wrapping from 1 to 0.\n    */\n    \n    out ^= 1 & (r ^ (r >> 3) ^ (r >> 5));\n    /*\n      An unfortunate result of the above transformation is that although \n      it's uniform over the 64-bit space, the last bit only changes when\n      the sign flips and thus effectively only 63 bits are adequately \n      random. To fix that some \"random\" bits are used.\n    */\n    \n    return out;\n    \n  }\n  \n    template <typename R>\n  void wrap_correction(R & r, uint64_t & val)\n  {\n    if (val & (std::uint64_t(1) << 63))\n    {\n      val = ((~val ^ 1) << 1) | 1;\n    }\n    else val = val << 1;\n    \n    val ^= 1 & r();\n  }\n  \n  template <std::size_t C = 32, std::size_t D = 2, std::size_t N = 1>\n  std::uint64_t crystal_noise64(std::array<std::uint64_t, N> inputs)\n  {\n    using u64 = std::uint64_t;\n    \n    static_assert(64 - C - D >= 0 && 64 - C - D <= 63, \"Invalid parameters\");\n    \n    u64 out = 0;\n    std::array<u64, N+1> a;\n    \n    for (int i = 0; i < N; i++) \n    { \n      a[i] = inputs[i];\n    }\n    a[N] = 0;\n    \n    std::array<u64, N> field_input = inputs;\n    for (int i = 0; i < N; i++)\n    {\n      field_input[i] = inputs[i];\n    }\n    \n    if (true) for (u64 i = 0; i < N; i++)\n    {\n      std::array<u64, N> b = inputs;\n      \n      u64 k = det_point_noise64(std::array<u64, N>{i}, 5, i);\n      for (size_t i2 = 0; i2 < N; i2++)\n      {\n        b[i2] += k;\n      }\n      \n      field_input[i] += (wave_noise64<C>(b)) >> (64 - C - D) ;\n      \n    }\n    \n    out = wave_noise64<C>(field_input);\n    \n    return out;\n  }\n \n  \n  \n  template <std::size_t C = 32, std::size_t D = 2, std::size_t N = 1>\n  std::uint64_t bicrystal_noise64(std::array<std::uint64_t, N> inputs)\n  {\n    using u64 = std::uint64_t;\n    \n    static_assert(64 - C - D >= 0 && 64 - C - D <= 63, \"Invalid parameters\");\n    \n    \n    std::array<u64, N+1> a;\n    for (int i = 0; i < N; i++) \n    { \n      a[i] = inputs[i];\n    }\n    a[N] = 0;\n    \n    std::array<u64, N> field_input = inputs;\n    for (int i = 0; i < N; i++)\n    {\n      field_input[i] = inputs[i];\n    }\n    \n    if (true) for (u64 i = 0; i < N; i++)\n    {\n      std::array<u64, N> b = inputs;\n      \n      u64 k = det_point_noise64(std::array<u64, N>{i});\n      for (size_t i2 = 0; i2 < N; i2++)\n      {\n        b[i2] += k;\n      }\n      \n      field_input[i] += (crystal_noise64<C>(b)) >> (64 - C - D) ;\n      \n    }\n    \n    return wave_noise64<C>(field_input);\n  }\n  \n  \n  \n  \n  \n  template <std::size_t C = 12, size_t N = 1>\n  uint64_t weave_noise2d_64(std::array<uint64_t, N> inputs, bool correct = true, size_t d = 1)\n  {\n    std::mt19937_64 r{0};\n    std::uint64_t output = 0;\n    \n    const constexpr std::size_t K = 3;\n    const constexpr std::size_t k = (1 << K);\n    \n    std::array<uint64_t, N + 2> k_inputs;\n    \n    for (size_t i = 0; i < N; i++)\n    {\n      k_inputs[i] = inputs[i];\n    }\n    \n    k_inputs[N] = r();\n     k_inputs[N+1] = r();\n    \n    std::uint64_t q = (1 << (C));\n        \n    for (std::size_t i = 0; i < k; i++) for (std::size_t j = 0; j < k; j++)\n    {\n      \n      std::array<std::uint64_t, N+2> y_inputs = k_inputs;\n      y_inputs[N] = r();\n      y_inputs[N+1] = r();\n      y_inputs[0] += q*i;\n      y_inputs[1] += q*j;\n      \n      uint64_t km = crystal_noise64<C+K, 1>(y_inputs);\n      km = km/d;\n      output += km;\n    }\n    \n    if (correct) wrap_correction(r, output);\n    \n    return output;\n    \n    \n  }\n  \n}\n\n#endif\n", "meta": {"hexsha": "40caf1b15e9d93eab325eaeeca25bda3933f1f99", "size": 10591, "ext": "hh", "lang": "C++", "max_stars_repo_path": "uniform_smooth_noise64.hh", "max_stars_repo_name": "Exaeta/det_noise64", "max_stars_repo_head_hexsha": "6d9595988a2442cd6d59265bfce320c60b848513", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2018-06-14T17:06:07.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-27T03:15:38.000Z", "max_issues_repo_path": "uniform_smooth_noise64.hh", "max_issues_repo_name": "Exaeta/det_noise64", "max_issues_repo_head_hexsha": "6d9595988a2442cd6d59265bfce320c60b848513", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "uniform_smooth_noise64.hh", "max_forks_repo_name": "Exaeta/det_noise64", "max_forks_repo_head_hexsha": "6d9595988a2442cd6d59265bfce320c60b848513", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-12-21T08:10:16.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-21T08:10:16.000Z", "avg_line_length": 27.0178571429, "max_line_length": 113, "alphanum_fraction": 0.559437258, "num_tokens": 3196, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5698526514141571, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.3247320443237448}}
{"text": "/*\n Copyright (C) 2020 Quaternion Risk Management Ltd\n All rights reserved.\n\n This file is part of ORE, a free-software/open-source library\n for transparent pricing and risk analysis - http://opensourcerisk.org\n\n ORE is free software: you can redistribute it and/or modify it\n under the terms of the Modified BSD License.  You should have received a\n copy of the license along with this program.\n The license is also available online at <http://opensourcerisk.org>\n\n This program is distributed on the basis that it will form a useful\n contribution to risk analytics and model standardisation, but WITHOUT\n ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n FITNESS FOR A PARTICULAR PURPOSE. See the license for more details.\n*/\n\n/*! \\file qle/termstructures/blackvolsurfacewithatm.hpp\n    \\brief Wrapper class for a BlackVolTermStructure that easily exposes ATM vols.\n    \\ingroup termstructures\n*/\n\n#ifndef quantext_blackvolsurfacewithatm_hpp\n#define quantext_blackvolsurfacewithatm_hpp\n\n#include <boost/shared_ptr.hpp>\n#include <ql/termstructures/volatility/equityfx/blackvoltermstructure.hpp>\n#include <ql/termstructures/yieldtermstructure.hpp>\n#include <qle/indexes/equityindex.hpp>\n\nnamespace QuantExt {\nusing namespace QuantLib;\n\n//! Wrapper class for a BlackVolTermStructure that allows us to proxy one equity vol surface off another.\n/*! This class implements BlackVolatilityTermStructure and takes a surface (well, any BlackVolTermStructure) as an\n    input. It also takes Handles to two EquityIndices (index and proxyIndex), where index is the 'EquityIndex' of the\n   underlying for the surface being constructed and proxyIndex is the 'EquityIndex' for the surface being proxied off.\n\n    The vol returned from the new surface is proxied from the base, adjusting by the forward prices to match ATM:\n\n    \\f{eqnarray}{\n    \\sigma_2(K,T) = \\sigma_1(\\frac{K}{F_2}*F_1,T)\n    \\f}\n\n    Where \\n\\n\n    \\f$ \\sigma_1 = \\text{Volatility of underlying being proxied against}\\f$ \\n\n    \\f$ \\sigma_2 = \\text{Volatility of underlying being proxied}\\f$ \\n\n    \\f$ F_1 = \\text{Forward at time T of the underlying being proxied against}\\f$ \\n\n    \\f$ F_2 = \\text{Forward at time T of the underlying being proxied}\\f$ \\n\n    \\f$ T = \\text{Time}\\f$\n    \\n\n\n    Note: This surface only proxies equity volatilities, this is because we are forced to look up the equity fixings\n    using time instead of date and use the forecastFixing method in an EquityIndex. A more general class could be\n   developed if need, using Index instead of EquityIndex, if the time lookup could be overcome.\n\n    */\n//!\\ingroup termstructures\n\nclass EquityBlackVolatilitySurfaceProxy : public BlackVolatilityTermStructure {\npublic:\n    //! Constructor. This is a floating term structure (settlement days is zero)\n    EquityBlackVolatilitySurfaceProxy(const boost::shared_ptr<BlackVolTermStructure>& proxySurface,\n                                      const boost::shared_ptr<EquityIndex>& index,\n                                      const boost::shared_ptr<EquityIndex>& proxyIndex);\n\n    //! \\name TermStructure interface\n    //@{\n    DayCounter dayCounter() const { return proxySurface_->dayCounter(); }\n    Date maxDate() const { return proxySurface_->maxDate(); }\n    Time maxTime() const { return proxySurface_->maxTime(); }\n    const Date& referenceDate() const { return proxySurface_->referenceDate(); }\n    Calendar calendar() const { return proxySurface_->calendar(); }\n    Natural settlementDays() const { return proxySurface_->settlementDays(); }\n    //@}\n\n    //! \\name VolatilityTermStructure interface\n    //@{\n    Rate minStrike() const;\n    Rate maxStrike() const;\n    //@}\n\n    //! \\name Inspectors\n    //@{\n    boost::shared_ptr<BlackVolTermStructure> proxySurface() const { return proxySurface_; }\n    boost::shared_ptr<EquityIndex> index() const { return index_; }\n    boost::shared_ptr<EquityIndex> proxyIndex() const { return proxyIndex_; }\n    //@}\n\nprotected:\n    // Here we adjust the returned vol.\n    Volatility blackVolImpl(Time t, Real strike) const;\n\nprivate:\n    boost::shared_ptr<BlackVolTermStructure> proxySurface_;\n    boost::shared_ptr<EquityIndex> index_, proxyIndex_;\n};\n\n} // namespace QuantExt\n\n#endif\n", "meta": {"hexsha": "eb4307038958f5a55e8c8b868d395b87fa9baa28", "size": 4232, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "QuantExt/qle/termstructures/equityblackvolsurfaceproxy.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": "QuantExt/qle/termstructures/equityblackvolsurfaceproxy.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": "QuantExt/qle/termstructures/equityblackvolsurfaceproxy.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": 41.0873786408, "max_line_length": 118, "alphanum_fraction": 0.7332230624, "num_tokens": 1008, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6297746213017459, "lm_q2_score": 0.5156199157230157, "lm_q1q2_score": 0.32472433716010035}}
{"text": "//=======================================================================\n// Copyright 1997, 1998, 1999, 2000 University of Notre Dame.\n// Copyright 2004, 2005 Trustees of Indiana University\n// Authors: Andrew Lumsdaine, Lie-Quan Lee, Jeremy G. Siek,\n//          Doug Gregor, D. Kevin McGrath\n//\n// Distributed under the Boost Software License, Version 1.0. (See\n// accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n//=======================================================================\n#ifndef BOOST_GRAPH_CUTHILL_MCKEE_HPP\n#define BOOST_GRAPH_CUTHILL_MCKEE_HPP\n\n#include <boost/config.hpp>\n#include <boost/graph/detail/sparse_ordering.hpp>\n#include <boost/graph/graph_utility.hpp>\n#include <algorithm>\n\n\n/*\n  (Reverse) Cuthill-McKee Algorithm for matrix reordering\n*/\n\nnamespace boost {\n\n  namespace detail {\n\n\n\n    template < typename OutputIterator, typename Buffer, typename DegreeMap > \n    class bfs_rcm_visitor:public default_bfs_visitor\n    {\n    public:\n      bfs_rcm_visitor(OutputIterator *iter, Buffer *b, DegreeMap deg): \n        permutation(iter), Qptr(b), degree(deg) { }\n      template <class Vertex, class Graph>\n      void examine_vertex(Vertex u, Graph&) {\n        *(*permutation)++ = u;\n        index_begin = (int)Qptr->size();\n      }\n      template <class Vertex, class Graph>\n      void finish_vertex(Vertex, Graph&) {\n        using std::sort;\n\n        typedef typename property_traits<DegreeMap>::value_type ds_type;\n\n        typedef indirect_cmp<DegreeMap, std::less<ds_type> > Compare;\n        Compare comp(degree);\n                \n        sort(Qptr->begin()+index_begin, Qptr->end(), comp);\n      }\n    protected:\n      OutputIterator *permutation;\n      int index_begin;\n      Buffer *Qptr;\n      DegreeMap degree;\n    };\n\n  } // namespace detail  \n\n\n  // Reverse Cuthill-McKee algorithm with a given starting Vertex.\n  //\n  // If user provides a reverse iterator, this will be a reverse-cuthill-mckee\n  // algorithm, otherwise it will be a standard CM algorithm\n\n  template <class Graph, class OutputIterator,\n            class ColorMap, class DegreeMap>\n  OutputIterator\n  cuthill_mckee_ordering(const Graph& g,\n                         std::deque< typename\n                         graph_traits<Graph>::vertex_descriptor > vertex_queue,\n                         OutputIterator permutation, \n                         ColorMap color, DegreeMap degree)\n  {\n\n    //create queue, visitor...don't forget namespaces!\n#ifdef __GNUC__\n    typedef typename property_traits<DegreeMap>::value_type ds_type __attribute__((unused));\n#else\n    typedef typename property_traits<DegreeMap>::value_type ds_type;\n#endif\n    typedef typename graph_traits<Graph>::vertex_descriptor Vertex;\n    typedef typename boost::sparse::sparse_ordering_queue<Vertex> queue;\n    typedef typename detail::bfs_rcm_visitor<OutputIterator, queue, DegreeMap> Visitor;\n    typedef typename property_traits<ColorMap>::value_type ColorValue;\n    typedef color_traits<ColorValue> Color;\n\n\n    queue Q;\n\n    //create a bfs_rcm_visitor as defined above\n    Visitor     vis(&permutation, &Q, degree);\n\n    typename graph_traits<Graph>::vertex_iterator ui, ui_end;    \n\n    // Copy degree to pseudo_degree\n    // initialize the color map\n    for (boost::tie(ui, ui_end) = vertices(g); ui != ui_end; ++ui){\n      put(color, *ui, Color::white());\n    }\n\n\n    while( !vertex_queue.empty() ) {\n      Vertex s = vertex_queue.front();\n      vertex_queue.pop_front();\n      \n      //call BFS with visitor\n      breadth_first_visit(g, s, Q, vis, color);\n    }\n    return permutation;\n  }\n    \n\n  // This is the case where only a single starting vertex is supplied.\n  template <class Graph, class OutputIterator,\n            class ColorMap, class DegreeMap>\n  OutputIterator\n  cuthill_mckee_ordering(const Graph& g,\n                         typename graph_traits<Graph>::vertex_descriptor s,\n                         OutputIterator permutation, \n                         ColorMap color, DegreeMap degree)\n  {\n\n    std::deque< typename graph_traits<Graph>::vertex_descriptor > vertex_queue;\n    vertex_queue.push_front( s );\n\n    return cuthill_mckee_ordering(g, vertex_queue, permutation, color, degree);\n  \n  }\n  \n\n  // This is the version of CM which selects its own starting vertex\n  template < class Graph, class OutputIterator, \n             class ColorMap, class DegreeMap>\n  OutputIterator \n  cuthill_mckee_ordering(const Graph& G, OutputIterator permutation, \n                         ColorMap color, DegreeMap degree)\n  {\n    if (boost::graph::has_no_vertices(G))\n      return permutation;\n\n    typedef typename boost::graph_traits<Graph>::vertex_descriptor Vertex;\n#ifdef __GNUC__\n    typedef typename boost::graph_traits<Graph>::vertex_iterator   VerIter __attribute__((unused));\n#else\n    typedef typename boost::graph_traits<Graph>::vertex_iterator   VerIter;\n#endif\n    typedef typename property_traits<ColorMap>::value_type ColorValue;\n    typedef color_traits<ColorValue> Color;\n\n    std::deque<Vertex>      vertex_queue;\n\n    // Mark everything white\n    BGL_FORALL_VERTICES_T(v, G, Graph) put(color, v, Color::white());\n\n    // Find one vertex from each connected component \n    BGL_FORALL_VERTICES_T(v, G, Graph) {\n      if (get(color, v) == Color::white()) {\n        depth_first_visit(G, v, dfs_visitor<>(), color);\n        vertex_queue.push_back(v);\n      }\n    }\n\n    // Find starting nodes for all vertices\n    // TBD: How to do this with a directed graph?\n    for (typename std::deque<Vertex>::iterator i = vertex_queue.begin();\n         i != vertex_queue.end(); ++i)\n      *i = find_starting_node(G, *i, color, degree);\n    \n    return cuthill_mckee_ordering(G, vertex_queue, permutation,\n                                  color, degree);\n  }\n\n  template<typename Graph, typename OutputIterator, typename VertexIndexMap>\n  OutputIterator \n  cuthill_mckee_ordering(const Graph& G, OutputIterator permutation, \n                         VertexIndexMap index_map)\n  {\n    if (boost::graph::has_no_vertices(G))\n      return permutation;\n    \n#ifdef __GNUC__\n    typedef out_degree_property_map<Graph> DegreeMap __attribute__((unused));\n#else\n    typedef out_degree_property_map<Graph> DegreeMap;\n#endif\n    std::vector<default_color_type> colors(num_vertices(G));\n    return cuthill_mckee_ordering(G, permutation, \n                                  make_iterator_property_map(&colors[0], \n                                                             index_map,\n                                                             colors[0]),\n                                  make_out_degree_map(G));\n  }\n\n  template<typename Graph, typename OutputIterator>\n  inline OutputIterator \n  cuthill_mckee_ordering(const Graph& G, OutputIterator permutation)\n  { return cuthill_mckee_ordering(G, permutation, get(vertex_index, G)); }\n} // namespace boost\n\n\n#endif // BOOST_GRAPH_CUTHILL_MCKEE_HPP\n", "meta": {"hexsha": "4476cbe4eaee6a3412eae102accfdb112ca592f2", "size": 6919, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "extlibs/miniBoost/boost/graph/cuthill_mckee_ordering.hpp", "max_stars_repo_name": "sofa-framework/issofa", "max_stars_repo_head_hexsha": "94855f488465bc3ed41223cbde987581dfca5389", "max_stars_repo_licenses": ["OML"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "extlibs/miniBoost/boost/graph/cuthill_mckee_ordering.hpp", "max_issues_repo_name": "sofa-framework/issofa", "max_issues_repo_head_hexsha": "94855f488465bc3ed41223cbde987581dfca5389", "max_issues_repo_licenses": ["OML"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "extlibs/miniBoost/boost/graph/cuthill_mckee_ordering.hpp", "max_forks_repo_name": "sofa-framework/issofa", "max_forks_repo_head_hexsha": "94855f488465bc3ed41223cbde987581dfca5389", "max_forks_repo_licenses": ["OML"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.9166666667, "max_line_length": 99, "alphanum_fraction": 0.6493712964, "num_tokens": 1534, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.6297746074044135, "lm_q1q2_score": 0.3247243299943589}}
{"text": "/*\n//@HEADER\n// ************************************************************************\n//\n// qr_tpetra_mv_householder_using_eigen_impl.hpp\n//                     \t\t  Pressio\n//                             Copyright 2019\n//    National Technology & Engineering Solutions of Sandia, LLC (NTESS)\n//\n// Under the terms of Contract DE-NA0003525 with NTESS, the\n// U.S. Government retains certain rights in this software.\n//\n// Pressio is licensed under BSD-3-Clause terms of use:\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\n// from this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n// \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n// COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\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) ARISING\n// IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n// POSSIBILITY OF SUCH DAMAGE.\n//\n// Questions? Contact Francesco Rizzi (fnrizzi@sandia.gov)\n//\n// ************************************************************************\n//@HEADER\n*/\n\n#ifndef QR_IMPL_TPETRA_QR_TPETRA_MV_HOUSEHOLDER_USING_EIGEN_IMPL_HPP_\n#define QR_IMPL_TPETRA_QR_TPETRA_MV_HOUSEHOLDER_USING_EIGEN_IMPL_HPP_\n\n#include <Eigen/OrderingMethods>\n#include <Eigen/SparseQR>\n#include <Tpetra_Map.hpp>\n#include <Tpetra_Vector.hpp>\n\nnamespace pressio{ namespace qr{ namespace impl{\n\ntemplate<typename MatrixType, typename R_t>\nclass TpetraMVHouseholderUsingEigen\n{\n\npublic:\n  using sc_t = typename ::pressio::Traits<MatrixType>::scalar_type;\n  using lo_t         = typename ::pressio::Traits<MatrixType>::local_ordinal_type;\n  using go_t         = typename ::pressio::Traits<MatrixType>::global_ordinal_type;\n  using node_t       = typename ::pressio::Traits<MatrixType>::node_type;\n  using Q_type       = Tpetra::MultiVector<sc_t, lo_t, go_t, node_t>;\n\n  using eig_dyn_mat\t= Eigen::Matrix<sc_t, -1, -1>;\n  using help_impl_t\t= QRHouseholderDenseEigenMatrix<eig_dyn_mat, R_t>;\n  help_impl_t myImpl_\t= {};\n\npublic:\n  TpetraMVHouseholderUsingEigen() = default;\n  ~TpetraMVHouseholderUsingEigen() = default;\n\n  template < typename vector_in_t, typename vector_out_t>\n  void applyQTranspose(const vector_in_t & vecIn, vector_out_t & vecOut) const\n  {\n    constexpr auto beta  = ::pressio::utils::Constants<sc_t>::zero();\n    constexpr auto alpha = ::pressio::utils::Constants<sc_t>::one();\n    ::pressio::ops::product(::pressio::transpose(), alpha, *this->Qmat_, vecIn, beta, vecOut);\n  }\n\n  template <typename VectorType>\n  void doLinSolve(const VectorType & rhs, VectorType & y)const{\n    myImpl_.template doLinSolve<VectorType>(rhs, y);\n  }\n\n  const Q_type & QFactor() const {\n    return *this->Qmat_;\n  }\n\n  void computeThinOutOfPlace(const MatrixType & Ain)\n  {\n    auto & A = const_cast<MatrixType &>(Ain);\n\n    auto rows = ::pressio::ops::extent(A,0);\n    auto cols = ::pressio::ops::extent(A,1);\n    auto ArowMap = A.getMap();\n    Teuchos::RCP<const Teuchos::Comm<int> > comm =\n      Teuchos::rcp (new Teuchos::MpiComm<int> (MPI_COMM_SELF));\n\n    // convert it to replicated eptra matrix\n    using local_map_t = Tpetra::Map<lo_t, go_t, node_t>;\n    using rcp_local_map_t = Teuchos::RCP<const local_map_t>;\n    rcp_local_map_t rcp_local_map = Teuchos::rcp( new local_map_t(rows, 0, comm) );\n\n    using import_t = Tpetra::Import<lo_t, go_t, node_t>;\n    import_t importer(ArowMap, rcp_local_map);\n    MatrixType A2(rcp_local_map, cols);\n    A2.doImport(A, importer, Tpetra::INSERT);\n\n    // store it into an Eigen matrix\n    Eigen::Matrix<sc_t, -1, -1> eA2W(rows,cols);\n    for (int j=0;j<cols;j++)\n    {\n      auto colData = A2.getData(j);\n      for (int i=0;i<rows;i++){\n    \t eA2W(i,j) = colData[i];\n      }\n    }\n\n    myImpl_.computeThinOutOfPlace(eA2W);\n\n    // store Q into replicated Tpetra::Multivector\n    const auto & Q2 = myImpl_.QFactor();\n    Q_type locQ( rcp_local_map, Q2.cols() );\n    // auto trilD = locQ.data();\n    locQ.template sync<Kokkos::HostSpace>();\n\n    auto v2d = locQ.template getLocalView<Kokkos::HostSpace>();\n    auto c0 = Kokkos::subview(v2d, Kokkos::ALL(), 0);\n    // //we are going to change the host view\n    locQ.template modify<Kokkos::HostSpace>();\n    for (int i=0;i<Q2.rows();i++)\n      for (int j=0;j<Q2.cols();j++)\n    \tv2d(i,j) = Q2(i,j);\n\n    // import from local to distributed\n    Qmat_ = std::make_shared<Q_type>(ArowMap, Q2.cols());\n    import_t importer2(rcp_local_map, ArowMap);\n    Qmat_->doImport(locQ, importer2, Tpetra::INSERT);\n  }\n\nprivate:\n  // todo: these must be moved somewhere else\n  mutable std::shared_ptr<Q_type> Qmat_\t= nullptr;\n  mutable std::shared_ptr<R_t> Rmat_\t= nullptr;\n\n};//end class\n\n}}} // end namespace pressio::qr::impl\n#endif  // QR_IMPL_TPETRA_QR_TPETRA_MV_HOUSEHOLDER_USING_EIGEN_IMPL_HPP_\n", "meta": {"hexsha": "a1dff6fa1b6dad0abefe862413f4f1c31674ccbb", "size": 5834, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "tpls/pressio/include/pressio/qr/impl/tpetra/qr_tpetra_mv_householder_using_eigen_impl.hpp", "max_stars_repo_name": "fnrizzi/pressio-demoapps", "max_stars_repo_head_hexsha": "6ff10bbcf4d526610580940753c9620725bff1ba", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 29.0, "max_stars_repo_stars_event_min_datetime": "2019-11-11T13:17:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-16T01:31:31.000Z", "max_issues_repo_path": "tpls/pressio/include/pressio/qr/impl/tpetra/qr_tpetra_mv_householder_using_eigen_impl.hpp", "max_issues_repo_name": "fnrizzi/pressio-demoapps", "max_issues_repo_head_hexsha": "6ff10bbcf4d526610580940753c9620725bff1ba", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 303.0, "max_issues_repo_issues_event_min_datetime": "2019-09-30T10:15:41.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T08:24:04.000Z", "max_forks_repo_path": "tpls/pressio/include/pressio/qr/impl/tpetra/qr_tpetra_mv_householder_using_eigen_impl.hpp", "max_forks_repo_name": "fnrizzi/pressio-demoapps", "max_forks_repo_head_hexsha": "6ff10bbcf4d526610580940753c9620725bff1ba", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2020-07-07T03:32:36.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-10T05:21:42.000Z", "avg_line_length": 37.3974358974, "max_line_length": 94, "alphanum_fraction": 0.6924922866, "num_tokens": 1546, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6297745935070806, "lm_q2_score": 0.5156199157230156, "lm_q1q2_score": 0.3247243228286173}}
{"text": "//============================================================================\n// Name        : IntervalAnalyzer.cpp\n// Author      : Tomasz Hoffmann\n// Version     :\n// Copyright   : TH\n// Description : Analyzer for interval results\n//============================================================================\n\n#include <iostream>\n#include <iomanip>\n#include <fstream>\n#include <time.h>\n#include <string>\n#include <vector>\n#include <limits.h>\n#include <boost/lexical_cast.hpp>\n#include <boost/filesystem.hpp>\n#include <boost/algorithm/string.hpp>\n#include <boost/exception/diagnostic_information.hpp>\n\nusing namespace std;\n\nnamespace alg = boost::algorithm;\nnamespace fs = boost::filesystem;\n\nint main(int ac, char *av[])\n{\n\tlong double eps = std::numeric_limits<long double>::epsilon();\n\ttry\n\t{\n\n\t\tif (ac != 7)\n\t\t{\n\t\t\tcout << \"Interval Analyzer\" << endl;\n\t\t\tcout << \"Usage: \\n\" << fs::basename(av[0]) << \" <l_filename>\"\n\t\t\t\t\t<< \" <r_filename>\" << \" <e_filename>\" << \" <f_filename>\"\n\t\t\t\t\t<< \" <oe_filename\" << \" <of_filename>\" << endl << endl;\n\t\t\tcout << \"where: \\n\" << \"l_ - left ends of interval solution \\n\"\n\t\t\t\t\t<< \"r_ - right ends of interval solution \\n\"\n\t\t\t\t\t<< \"e_ - exact solution (if known) \\n\"\n\t\t\t\t\t<< \"f_ - fp arithmetic solutions \\n\"\n\t\t\t\t\t<< \"oe_ - exact distribution output file name \\n\"\n\t\t\t\t\t<< \"of_ - fp distribution output file name \\n\" << endl;\n\t\t\treturn 0;\n\t\t}\n\t\tifstream l_file(av[1]);\n\t\tifstream r_file(av[2]);\n\t\tifstream e_file(av[3]);\n\t\tifstream f_file(av[4]);\n\t\tfstream oe_file(av[5], fstream::out);\n\t\tfstream of_file(av[6], fstream::out);\n\n\t\t//string fname = av[4];\n\t\t//\t\to_file.open(fname.c_str(), fstream::out);\n\n\t\tint dprec = std::numeric_limits<long double>::digits10;\n\n\t\tbool allopen = true;\n\t\tallopen &= l_file.is_open();\n\t\tallopen &= r_file.is_open();\n\t\tallopen &= e_file.is_open();\n\t\tallopen &= f_file.is_open();\n\n\t\tif (!allopen)\n\t\t{\n\t\t\tcout << \"One or more files cannot be open! \\n\";\n\t\t\treturn 0;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tstring line;\n\t\t\tvector<string> v;\n\t\t\tvector<long double> lv;\n\t\t\tvector<long double> rv;\n\t\t\tvector<long double> ev;\n\t\t\tvector<long double> fv;\n\n\t\t\twhile ((!l_file.eof()) && (!r_file.eof()) && (!e_file.eof())\n\t\t\t\t\t&& (!f_file.eof()))\n\t\t\t{\n\t\t\t\tgetline(l_file, line);\n\t\t\t\talg::split(v, line, alg::is_any_of(\";\"));\n\t\t\t\tvector<string>::iterator it;\n\t\t\t\tif (v.size() < 2)\n\t\t\t\t\tbreak;\n//\t\t\t\tcout << \"Start left...\" << endl;\n\t\t\t\tfor (it = v.begin(); it != v.end(); ++it)\n\t\t\t\t{\n\t\t\t\t\tlv.push_back(boost::lexical_cast<long double>(*it));\n\t\t\t\t}\n//\t\t\t\tcout << \"Read left done.\" << endl;\n\n\t\t\t\tgetline(r_file, line);\n//\t\t\t\tcout << \"Start right...\" << endl;\n\t\t\t\talg::split(v, line, alg::is_any_of(\";\"));\n\t\t\t\tif (v.size() < 2)\n\t\t\t\t\tbreak;\n\t\t\t\tfor (it = v.begin(); it != v.end(); ++it)\n\t\t\t\t{\n\t\t\t\t\trv.push_back(boost::lexical_cast<long double>(*it));\n\t\t\t\t}\n//\t\t\t\tcout << \"Read right done.\" << endl;\n\n\t\t\t\tgetline(e_file, line);\n//\t\t\t\tcout << \"Start exact...\" << endl;\n\t\t\t\tif (v.size() < 2)\n\t\t\t\t\tbreak;\n\t\t\t\talg::split(v, line, alg::is_any_of(\";\"));\n\t\t\t\tfor (it = v.begin(); it != v.end(); ++it)\n\t\t\t\t{\n//\t\t\t\t\tcout << (*it);\n\t\t\t\t\tev.push_back(boost::lexical_cast<long double>(*it));\n\t\t\t\t}\n//\t\t\t\tcout << \"Read exact done.\" << endl;\n\n\t\t\t\tgetline(f_file, line);\n\t\t\t\talg::split(v, line, alg::is_any_of(\";\"));\n\t\t\t\tfor (it = v.begin(); it != v.end(); ++it)\n\t\t\t\t{\n\t\t\t\t\tfv.push_back(boost::lexical_cast<long double>(*it));\n\t\t\t\t}\n//\t\t\t\tcout << \"Read floating-point done.\" << endl;\n\n\t\t\t\tif ((lv.size() == rv.size()) && (rv.size() == ev.size())\n\t\t\t\t\t\t&& (ev.size() == fv.size()))\n\t\t\t\t{\n\t\t\t\t\tlong double l, r, e, f, w1, w, m;\n\n\t\t\t\t\tvector<long double> res;\n\t\t\t\t\t//caluclate exact solutions distribution\n\t\t\t\t\tfor (size_t i = 0; i < lv.size(); ++i)\n\t\t\t\t\t{\n\t\t\t\t\t\tl = lv.at(i);\n\t\t\t\t\t\tr = rv.at(i);\n\t\t\t\t\t\te = ev.at(i);\n\t\t\t\t\t\tw = r - l;\n\t\t\t\t\t\tm = (r + l) / 2;\n\t\t\t\t\t\tif ((w < eps) || (e == r) || (e == l))\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tres.push_back(0.5);\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tw1 = abs(e - m);\n\t\t\t\t\t\tif ((w1 / w) > 0.5)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tcout << \" \\n Wrong element: \"\n\t\t\t\t\t\t\t\t\t<< std::setprecision(dprec) << e;\n\t\t\t\t\t\t\tcout << std::setprecision(dprec) << \"\\n [ \" << l\n\t\t\t\t\t\t\t\t\t<< \" ; \" << r << \" ] \\n\";\n\t\t\t\t\t\t\tcout << std::setprecision(dprec) << \"m = \" << m\n\t\t\t\t\t\t\t\t\t<< \" \\n\";\n\t\t\t\t\t\t}\n\t\t\t\t\t\tres.push_back(w1 / w);\n\t\t\t\t\t}\n\n\t\t\t\t\tstringstream ss;\n\t\t\t\t\tvector<long double>::iterator it;\n\t\t\t\t\tfor (it = res.begin(); it != res.end(); ++it)\n\t\t\t\t\t{\n\t\t\t\t\t\tss << std::setprecision(dprec) << (*it) << \";\";\n\t\t\t\t\t}\n\t\t\t\t\tss << endl;\n\t\t\t\t\toe_file << ss.str();\n\n\t\t\t\t\t//caluclate floating-pint solutions distribution\n\t\t\t\t\tres.clear();\n\t\t\t\t\tfor (size_t i = 0; i < lv.size(); ++i)\n\t\t\t\t\t{\n\t\t\t\t\t\tl = lv.at(i);\n\t\t\t\t\t\tr = rv.at(i);\n\t\t\t\t\t\tf = fv.at(i);\n\t\t\t\t\t\tw = r - l;\n\t\t\t\t\t\tm = (r + l) / 2;\n\t\t\t\t\t\tif ((w < eps) || (f == r) || (f == l))\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tres.push_back(0.5);\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tw1 = abs(f - m);\n\t\t\t\t\t\tif ((w1 / w) > 0.5)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tcout << \" \\n Wrong element: \"\n\t\t\t\t\t\t\t\t\t<< std::setprecision(dprec) << e;\n\t\t\t\t\t\t\tcout << std::setprecision(dprec) << \"\\n [ \" << l\n\t\t\t\t\t\t\t\t\t<< \" ; \" << r << \" ] \\n\";\n\t\t\t\t\t\t\tcout << std::setprecision(dprec) << \"m = \" << m\n\t\t\t\t\t\t\t\t\t<< \" \\n\";\n\t\t\t\t\t\t}\n\t\t\t\t\t\tres.push_back(w1 / w);\n\t\t\t\t\t}\n\n\t\t\t\t\tss.str(string());\n\t\t\t\t\tfor (it = res.begin(); it != res.end(); ++it)\n\t\t\t\t\t{\n\t\t\t\t\t\tss << std::setprecision(dprec) << (*it) << \";\";\n\t\t\t\t\t}\n\t\t\t\t\tss << endl;\n\t\t\t\t\tof_file << ss.str();\n\n\t\t\t\t\t//clear input vectors for current row\n\t\t\t\t\tlv.clear();\n\t\t\t\t\trv.clear();\n\t\t\t\t\tev.clear();\n\t\t\t\t\tfv.clear();\n\t\t\t\t}\n\t\t\t}\n\n\t\t}\n\t\tl_file.close();\n\t\tr_file.close();\n\t\te_file.close();\n\t\toe_file.close();\n\t} catch (boost::exception const& ex)\n\t{\n\t\tcout\n\t\t\t\t<< \"Execution problem \"\n\t\t\t\t\t\t+ boost::current_exception_diagnostic_information();\n\t}\n\treturn 0;\n}\n", "meta": {"hexsha": "89fa3a07369b3cf29f7ea5d9a7ff8562204708e4", "size": 5658, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "IntervalAnalyzer/src/IntervalAnalyzer.cpp", "max_stars_repo_name": "tomaszhof/interval_arithmetic", "max_stars_repo_head_hexsha": "0d1e7c842803f8ca211bf2a9d7239f7541452492", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "IntervalAnalyzer/src/IntervalAnalyzer.cpp", "max_issues_repo_name": "tomaszhof/interval_arithmetic", "max_issues_repo_head_hexsha": "0d1e7c842803f8ca211bf2a9d7239f7541452492", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "IntervalAnalyzer/src/IntervalAnalyzer.cpp", "max_forks_repo_name": "tomaszhof/interval_arithmetic", "max_forks_repo_head_hexsha": "0d1e7c842803f8ca211bf2a9d7239f7541452492", "max_forks_repo_licenses": ["Apache-2.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.6018099548, "max_line_length": 78, "alphanum_fraction": 0.4980558501, "num_tokens": 1710, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5660185498374789, "lm_q2_score": 0.5736784074525098, "lm_q1q2_score": 0.32471262025934394}}
{"text": "/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */\n\n/*\n Copyright (C) 2013 Peter Caspers\n\n This file is part of QuantLib, a free-software/open-source library\n for financial quantitative analysts and developers - http://quantlib.org/\n\n QuantLib is free software: you can redistribute it and/or modify it\n under the terms of the QuantLib license.  You should have received a\n copy of the license along with this program; if not, please email\n <quantlib-dev@lists.sf.net>. The license is also available online at\n <http://quantlib.org/license.shtml>.\n\n This program is distributed in the hope that it will be useful, but WITHOUT\n ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n FOR A PARTICULAR PURPOSE.  See the license for more details.\n*/\n\n/*! \\file gaussian1dmodel.hpp\n    \\brief basic interface for one factor interest rate models\n*/\n\n// uncomment to enable NTL support (see below for more details and references)\n// #define GAUSS1D_ENABLE_NTL \n\n#ifndef quantlib_gaussian1dmodel_hpp\n#define quantlib_gaussian1dmodel_hpp\n\n#include <ql/models/model.hpp>\n#include <ql/models/parameter.hpp>\n#include <ql/math/interpolation.hpp>\n#include <ql/math/interpolations/cubicinterpolation.hpp>\n#include <ql/indexes/iborindex.hpp>\n#include <ql/indexes/swapindex.hpp>\n#include <ql/instruments/vanillaswap.hpp>\n#include <ql/time/date.hpp>\n#include <ql/time/period.hpp>\n#include <ql/termstructures/yieldtermstructure.hpp>\n#include <ql/stochasticprocess.hpp>\n#include <ql/utilities/null.hpp>\n#include <ql/patterns/lazyobject.hpp>\n\n#ifdef GAUSS1D_ENABLE_NTL\n    #include <boost/math/bindings/rr.hpp>\n#endif\n\n#include <boost/math/special_functions/erf.hpp>\n\nnamespace QuantLib {\n\n    /*! One factor interest rate model interface class\n        The only methods that must be implemented by subclasses\n        are the numeraire and zerobond methods for an input array\n        of state variable values. The variable $y$ is understood\n        to be the standardized (zero mean, unit variance) version\n        of the model's original state variable $x$.\n\n        NTL support may be enabled by defining GAUSS1D_ENABLE_NTL in this\n        file. For details on NTL see\n                 http://www.shoup.net/ntl/\n\n        \\warning the variance of the state process conditional on\n        $x(t)=x$ must be independent of the value of $x$\n\n    */\n\n    class Gaussian1dModel : public TermStructureConsistentModel,\n                            public LazyObject {\n\n      public:\n\n        const boost::shared_ptr<StochasticProcess1D> stateProcess() const;\n\n        const Real numeraire(const Time t, const Real y = 0.0,\n                             const Handle<YieldTermStructure> &yts =\n                                 Handle<YieldTermStructure>()) const;\n\n        const Real zerobond(const Time T, const Time t = 0.0,\n                            const Real y = 0.0,\n                            const Handle<YieldTermStructure> &yts =\n                                Handle<YieldTermStructure>()) const;\n\n        const Real numeraire(const Date &referenceDate, const Real y = 0.0,\n                             const Handle<YieldTermStructure> &yts =\n                                 Handle<YieldTermStructure>()) const;\n\n        const Real zerobond(const Date &maturity,\n                            const Date &referenceDate = Null<Date>(),\n                            const Real y = 0.0,\n                            const Handle<YieldTermStructure> &yts =\n                                Handle<YieldTermStructure>()) const;\n\n        const Real zerobondOption(\n            const Option::Type &type, const Date &expiry, const Date &valueDate,\n            const Date &maturity, const Rate strike,\n            const Date &referenceDate = Null<Date>(), const Real y = 0.0,\n            const Handle<YieldTermStructure> &yts =\n                Handle<YieldTermStructure>(),\n            const Real yStdDevs = 7.0, const Size yGridPoints = 64,\n            const bool extrapolatePayoff = true,\n            const bool flatPayoffExtrapolation = false) const;\n\n        const Real forwardRate(const Date &fixing,\n                               const Date &referenceDate = Null<Date>(),\n                               const Real y = 0.0,\n                               boost::shared_ptr<IborIndex> iborIdx =\n                                   boost::shared_ptr<IborIndex>()) const;\n\n        const Real swapRate(const Date &fixing, const Period &tenor,\n                            const Date &referenceDate = Null<Date>(),\n                            const Real y = 0.0,\n                            boost::shared_ptr<SwapIndex> swapIdx =\n                                boost::shared_ptr<SwapIndex>()) const;\n\n        const Real swapAnnuity(const Date &fixing, const Period &tenor,\n                               const Date &referenceDate = Null<Date>(),\n                               const Real y = 0.0,\n                               boost::shared_ptr<SwapIndex> swapIdx =\n                                   boost::shared_ptr<SwapIndex>()) const;\n\n        /*! Computes the integral\n        \\f[ {2\\pi}^{-0.5} \\int_{a}^{b} p(x) \\exp{-0.5*x*x} \\mathrm{d}x \\f]\n        with\n        \\f[ p(x) = ax^4+bx^3+cx^2+dx+e \\f].\n        */\n        const static Real gaussianPolynomialIntegral(const Real a, const Real b,\n                                                     const Real c, const Real d,\n                                                     const Real e,\n                                                     const Real x0,\n                                                     const Real x1);\n\n        /*! Computes the integral\n        \\f[ {2\\pi}^{-0.5} \\int_{a}^{b} p(x) \\exp{-0.5*x*x} \\mathrm{d}x \\f]\n        with\n        \\f[ p(x) = a(x-h)^4+b(x-h)^3+c(x-h)^2+d(x-h)+e \\f].\n        */\n        const static Real gaussianShiftedPolynomialIntegral(\n            const Real a, const Real b, const Real c, const Real d,\n            const Real e, const Real h, const Real x0, const Real x1);\n\n        /*! Generates a grid of values for the standardized state variable $y$\n           at time $T$\n            conditional on $y(t)=y$, covering yStdDevs standard deviations\n           consisting of\n            2*gridPoints+1 points */\n\n        const Disposable<Array> yGrid(const Real yStdDevs, const int gridPoints,\n                                      const Real T = 1.0, const Real t = 0,\n                                      const Real y = 0) const;\n\n      protected:\n\n        // we let derived classes register with the termstructure\n        Gaussian1dModel(const Handle<YieldTermStructure> &yieldTermStructure)\n            : TermStructureConsistentModel(yieldTermStructure) {}\n\n        virtual ~Gaussian1dModel() {}\n\n        virtual const Real\n        numeraireImpl(const Time t, const Real y,\n                      const Handle<YieldTermStructure> &yts) const = 0;\n\n        virtual const Real\n        zerobondImpl(const Time T, const Time t, const Real y,\n                     const Handle<YieldTermStructure> &yts) const = 0;\n\n        void performCalculations() const {}\n\n        void generateArguments() {\n            calculate();\n            notifyObservers();\n        }\n\n        boost::shared_ptr<StochasticProcess1D> stateProcess_;\n    };\n\n    inline const boost::shared_ptr<StochasticProcess1D>\n    Gaussian1dModel::stateProcess() const {\n\n        QL_REQUIRE(stateProcess_ != NULL, \"state process not set\");\n        return stateProcess_;\n\n    }\n\n    inline const Real\n    Gaussian1dModel::numeraire(const Time t, const Real y,\n                               const Handle<YieldTermStructure> &yts) const {\n\n        return numeraireImpl(t, y, yts);\n    }\n\n    inline const Real\n    Gaussian1dModel::zerobond(const Time T, const Time t, const Real y,\n                              const Handle<YieldTermStructure> &yts) const {\n\n        return zerobondImpl(T, t, y, yts);\n    }\n\n    inline const Real\n    Gaussian1dModel::numeraire(const Date &referenceDate, const Real y,\n                               const Handle<YieldTermStructure> &yts) const {\n\n        return numeraire(termStructure()->timeFromReference(referenceDate), y,\n                         yts);\n    }\n\n    inline const Real\n    Gaussian1dModel::zerobond(const Date &maturity, const Date &referenceDate,\n                              const Real y,\n                              const Handle<YieldTermStructure> &yts) const {\n\n        return zerobond(termStructure()->timeFromReference(maturity),\n                        referenceDate != Null<Date>()\n                            ? termStructure()->timeFromReference(referenceDate)\n                            : 0.0,\n                        y, yts);\n    }\n\n}\n\n#endif\n", "meta": {"hexsha": "4fc4fdbaa68487aa831259476c3860a7d4a1c9e8", "size": 8700, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ql/experimental/models/gaussian1dmodel.hpp", "max_stars_repo_name": "quantosaurosProject/quantLib", "max_stars_repo_head_hexsha": "84b49913d3940cf80d6de8f70185867373f45e8d", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ql/experimental/models/gaussian1dmodel.hpp", "max_issues_repo_name": "quantosaurosProject/quantLib", "max_issues_repo_head_hexsha": "84b49913d3940cf80d6de8f70185867373f45e8d", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ql/experimental/models/gaussian1dmodel.hpp", "max_forks_repo_name": "quantosaurosProject/quantLib", "max_forks_repo_head_hexsha": "84b49913d3940cf80d6de8f70185867373f45e8d", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-03-29T05:44:27.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-29T05:44:27.000Z", "avg_line_length": 39.0134529148, "max_line_length": 80, "alphanum_fraction": 0.5794252874, "num_tokens": 1938, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6926419831347361, "lm_q2_score": 0.46879062662624377, "lm_q1q2_score": 0.32470406930137713}}
{"text": "//==============================================================================\n//         Copyright 2003 - 2011 LASMEA UMR 6602 CNRS/Univ. Clermont II\n//         Copyright 2009 - 2011 LRI    UMR 8623 CNRS/Univ Paris Sud XI\n//\n//          Distributed under the Boost Software License, Version 1.0.\n//                 See accompanying file LICENSE.txt or copy at\n//                     http://www.boost.org/LICENSE_1_0.txt\n//==============================================================================\n#ifndef BOOST_SIMD_TOOLBOX_ARITHMETIC_FUNCTIONS_SIMD_COMMON_ADDS_HPP_INCLUDED\n#define BOOST_SIMD_TOOLBOX_ARITHMETIC_FUNCTIONS_SIMD_COMMON_ADDS_HPP_INCLUDED\n#include <boost/simd/toolbox/arithmetic/functions/adds.hpp>\n#include <boost/mpl/logical.hpp>\n#include <boost/simd/toolbox/arithmetic/functions/adds.hpp>\n#include <boost/simd/include/functions/simd/plus.hpp>\n#include <boost/simd/include/functions/simd/bitwise_or.hpp>\n#include <boost/simd/include/functions/simd/is_less.hpp>\n#include <boost/simd/include/functions/simd/is_greater.hpp>\n#include <boost/simd/include/functions/simd/is_gtz.hpp>\n#include <boost/simd/include/functions/simd/logical_and.hpp>\n#include <boost/simd/include/functions/simd/logical_or.hpp>\n#include <boost/simd/include/functions/simd/logical_not.hpp>\n//#include <boost/simd/include/functions/simd/logical_notand.hpp>\n#include <boost/simd/include/functions/simd/if_else.hpp>\n#include <boost/simd/include/functions/simd/min.hpp>\n#include <boost/simd/include/functions/simd/max.hpp>\n#include <boost/simd/include/constants/valmin.hpp>\n#include <boost/simd/include/constants/valmax.hpp>\n\nnamespace boost { namespace simd { namespace ext\n{\n  BOOST_SIMD_FUNCTOR_IMPLEMENTATION(boost::simd::tag::adds_, tag::cpu_,\n                          (A0)(X),\n                          ((simd_<floating_<A0>,X>))\n                          ((simd_<floating_<A0>,X>))\n                         )\n  {\n    typedef A0 result_type;\n    BOOST_SIMD_FUNCTOR_CALL_REPEAT(2) { return a0+a1; }\n  };\n\n  BOOST_SIMD_FUNCTOR_IMPLEMENTATION(boost::simd::tag::adds_, tag::cpu_,\n                          (A0)(X),\n                          ((simd_<uint_<A0>,X>))\n                          ((simd_<uint_<A0>,X>))\n                         )\n  {\n    typedef A0 result_type;\n    BOOST_SIMD_FUNCTOR_CALL_REPEAT(2)\n    {\n      A0 a0pa1 = a0+a1;\n      return if_else(lt(a0pa1, a0), Valmax<A0>(), a0pa1);\n    }\n  };\n\n  BOOST_SIMD_FUNCTOR_IMPLEMENTATION(boost::simd::tag::adds_, tag::cpu_,\n                          (A0)(X),\n                          ((simd_<int_<A0>,X>))\n                          ((simd_<int_<A0>,X>))\n                         )\n  {\n    typedef A0 result_type;\n    BOOST_SIMD_FUNCTOR_CALL_REPEAT(2)\n    {\n      typedef typename meta::as_logical<A0>::type bA0;\n      bA0 gtza0 = is_gtz(a0);\n      bA0 gtza1 = is_gtz(a1);\n      A0 a0pa1 = a0+a1;\n      bA0 test1 = logical_and(logical_and(gtza0, gtza1), lt(a0pa1, a0));\n      bA0 test2 = logical_and(logical_not(logical_or(gtza0, gtza1)), gt(a0pa1,a0)); //logical_notand\n      return if_else(test1,Valmax<A0>(),if_else(test2,Valmin<A0>(),a0pa1));\n    }\n  };\n} } }\n#endif\n", "meta": {"hexsha": "98a578a6f98e0c3aede5a794a376e2cfe0b3a337", "size": 3120, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/boost/simd/arithmetic/include/boost/simd/toolbox/arithmetic/functions/simd/common/adds.hpp", "max_stars_repo_name": "timblechmann/nt2", "max_stars_repo_head_hexsha": "6c71f7063ca4e5975c9c019877e6b2fe07c9e4ce", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2016-09-14T00:23:53.000Z", "max_stars_repo_stars_event_max_datetime": "2018-01-14T12:51:18.000Z", "max_issues_repo_path": "modules/boost/simd/arithmetic/include/boost/simd/toolbox/arithmetic/functions/simd/common/adds.hpp", "max_issues_repo_name": "timblechmann/nt2", "max_issues_repo_head_hexsha": "6c71f7063ca4e5975c9c019877e6b2fe07c9e4ce", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "modules/boost/simd/arithmetic/include/boost/simd/toolbox/arithmetic/functions/simd/common/adds.hpp", "max_forks_repo_name": "timblechmann/nt2", "max_forks_repo_head_hexsha": "6c71f7063ca4e5975c9c019877e6b2fe07c9e4ce", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.6, "max_line_length": 100, "alphanum_fraction": 0.6080128205, "num_tokens": 801, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6926419831347361, "lm_q2_score": 0.46879062662624377, "lm_q1q2_score": 0.32470406930137713}}
{"text": "/******************************************************************************\n\n  This source file is part of the OpenQube project.\n\n  Copyright 2008-2010 Marcus D. Hanwell\n\n  This source code is released under the New BSD License, (the \"License\").\n\n  Unless required by applicable law or agreed to in writing, software\n  distributed under the License is distributed on an \"AS IS\" BASIS,\n  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n  See the License for the specific language governing permissions and\n  limitations under the License.\n\n******************************************************************************/\n\n#include \"slaterset.h\"\n\n#ifdef WIN32\n#define _USE_MATH_DEFINES\n#include <math.h> // needed for M_PI\n#endif\n\n#include \"cube.h\"\n\n//#include <Eigen/Array>\n#include <Eigen/Eigenvalues>\n#include <Eigen/LU>\n#include <Eigen/QR>\n\n#include <cmath>\n\n#include <QtCore/QtConcurrentMap>\n#include <QtCore/QFuture>\n#include <QtCore/QFutureWatcher>\n#include <QtCore/QReadWriteLock>\n#include <QtCore/QDebug>\n\nusing std::vector;\nusing Eigen::Vector3d;\nusing Eigen::Vector3i;\nusing Eigen::MatrixXd;\nusing Eigen::SelfAdjointEigenSolver;\n\nnamespace OpenQube\n{\nstruct SlaterShell\n{\n  SlaterSet *set;    // A pointer to the SlaterSet, cannot write to member vars\n  Cube *cube;        // The target cube, used to initialise temp cubes too\n  unsigned int pos;  // The index of position of the point to calculate the MO for\n  unsigned int state;// The MO number to calculate\n};\n\nusing std::vector;\n\nstatic const double BOHR_TO_ANGSTROM = 0.529177249;\nstatic const double ANGSTROM_TO_BOHR = 1.0 / 0.529177249;\n\nSlaterSet::SlaterSet() : m_initialized(false)\n{\n}\n\nSlaterSet::~SlaterSet()\n{\n\n}\n\nbool SlaterSet::addAtoms(const std::vector<Eigen::Vector3d> &pos)\n{\n  m_atomPos = pos;\n  return true;\n}\n\nbool SlaterSet::addSlaterIndices(const std::vector<int> &i)\n{\n  m_slaterIndices = i;\n  return true;\n}\n\nbool SlaterSet::addSlaterTypes(const std::vector<int> &t)\n{\n  m_slaterTypes = t;\n  return true;\n}\n\nbool SlaterSet::addZetas(const std::vector<double> &zetas)\n{\n  m_zetas = zetas;\n  return true;\n}\n\nbool SlaterSet::addPQNs(const std::vector<int> &pqns)\n{\n  m_pqns = pqns;\n  return true;\n}\n\nbool SlaterSet::addOverlapMatrix(const Eigen::MatrixXd &m)\n{\n  m_overlap.resize(m.rows(), m.cols());\n  m_overlap = m;\n  return true;\n}\n\nbool SlaterSet::addEigenVectors(const Eigen::MatrixXd &e)\n{\n  m_eigenVectors.resize(e.rows(), e.cols());\n  m_eigenVectors = e;\n  return true;\n}\n\nbool SlaterSet::addDensityMatrix(const Eigen::MatrixXd &d)\n{\n  m_density.resize(d.rows(), d.cols());\n  m_density = d;\n  return true;\n}\n\nunsigned int SlaterSet::numMOs()\n{\n  return static_cast<unsigned int>(m_overlap.cols());\n}\n\ninline bool SlaterSet::isSmall(double val)\n{\n  if (val > -1e-15 && val < 1e-15)\n    return true;\n  else\n    return false;\n}\n\nunsigned int SlaterSet::factorial(unsigned int n)\n{\n  if (n <= 1)\n    return n;\n  return (n * factorial(n-1));\n}\n\nvoid SlaterSet::outputAll()\n{\n\n}\n\nbool SlaterSet::calculateCubeMO(Cube *cube, unsigned int state)\n{\n  // Set up the calculation and ideally use the new QtConcurrent code to\n  // multithread the calculation...\n  if (state < 1 || static_cast<int>(state) > m_overlap.rows())\n    return false;\n\n  if (!m_initialized)\n    initialize();\n\n  // It is more efficient to process each shell over the entire cube than it\n  // is to process each MO at each point in the cube. This is probably the best\n  // point at which to multithread too - QtConcurrent!\n  m_slaterShells.resize(static_cast<int>(cube->data()->size()));\n\n  qDebug() << \"Number of points:\" << m_slaterShells.size();\n\n  for (int i = 0; i < m_slaterShells.size(); ++i) {\n    m_slaterShells[i].set = this;\n    m_slaterShells[i].cube = cube;\n    m_slaterShells[i].pos = i;\n    m_slaterShells[i].state = state;\n  }\n\n  // Lock the cube until we are done.\n  cube->lock()->lockForWrite();\n\n  // Set the cube type\n  cube->setCubeType(Cube::MO);\n\n  // Watch for the future\n  connect(&m_watcher, SIGNAL(finished()), this, SLOT(calculationComplete()));\n\n  // The main part of the mapped reduced function...\n  m_future = QtConcurrent::map(m_slaterShells, SlaterSet::processPoint);\n  // Connect our watcher to our future\n  m_watcher.setFuture(m_future);\n\n  return true;\n}\n\nbool SlaterSet::calculateCubeDensity(Cube *cube)\n{\n  // Set up the calculation and ideally use the new QtConcurrent code to\n  // multithread the calculation...\n  if (!m_initialized)\n    initialize();\n\n  // It is more efficient to process each shell over the entire cube than it\n  // is to process each MO at each point in the cube. This is probably the best\n  // point at which to multithread too - QtConcurrent!\n  m_slaterShells.resize(static_cast<int>(cube->data()->size()));\n\n  qDebug() << \"Number of points for density:\" << m_slaterShells.size();\n\n  for (int i = 0; i < m_slaterShells.size(); ++i) {\n    m_slaterShells[i].set = this;\n    m_slaterShells[i].cube = cube;\n    m_slaterShells[i].pos = i;\n    m_slaterShells[i].state = 0;\n  }\n\n  // Lock the cube until we are done.\n  cube->lock()->lockForWrite();\n\n  // Set the cube type\n  cube->setCubeType(Cube::ElectronDensity);\n\n  // Watch for the future\n  connect(&m_watcher, SIGNAL(finished()), this, SLOT(calculationComplete()));\n\n  // The main part of the mapped reduced function...\n  m_future = QtConcurrent::map(m_slaterShells, SlaterSet::processDensity);\n  // Connect our watcher to our future\n  m_watcher.setFuture(m_future);\n\n  return true;\n}\n\nBasisSet * SlaterSet::clone()\n{\n  SlaterSet *result = new SlaterSet();\n  result->m_atomPos = this->m_atomPos;\n  result->m_slaterIndices = this->m_slaterIndices;\n  result->m_zetas = this->m_zetas;\n  result->m_pqns = this->m_pqns;\n  result->m_PQNs = this->m_PQNs;\n\n  result->m_factors = this->m_factors;\n  result->m_overlap = this->m_overlap;\n  result->m_eigenVectors = this->m_eigenVectors;\n  result->m_density = this->m_density;\n  result->m_normalized = this->m_normalized;\n  result->m_initialized = this->m_initialized;\n\n  // Skip tmp variables\n  return result;\n}\n\nvoid SlaterSet::calculationComplete()\n{\n  disconnect(&m_watcher, SIGNAL(finished()), this, SLOT(calculationComplete()));\n  qDebug() << m_slaterShells[0].cube->data()->at(0) << m_slaterShells[0].cube->data()->at(1);\n  qDebug() << \"Calculation complete - cube map...\";\n  m_slaterShells[0].cube->lock()->unlock();\n}\n\nbool SlaterSet::initialize()\n{\n  m_normalized.resize(m_overlap.cols(), m_overlap.rows());\n\n  SelfAdjointEigenSolver<MatrixXd> s(m_overlap);\n  MatrixXd p = s.eigenvectors();\n  MatrixXd m = p * s.eigenvalues().array().inverse().array().sqrt()\n                    .matrix().asDiagonal() * p.inverse();\n  m_normalized = m * m_eigenVectors;\n\n  if (!(m_overlap*m*m).eval().isIdentity())\n    qDebug() << \"Identity test FAILED - do you need a newer version of Eigen?\";\n  //    std::cout << m_normalized << std::endl << std::endl;\n  //    std::cout << s.eigenvalues() << std::endl << std::endl;\n  //    std::cout << m_overlap << std::endl << std::endl;\n  //    std::cout << s.eigenvalues().minCoeff() << ' ' << s.eigenvalues().maxCoeff() << std::endl << std::endl;\n\n  m_factors.resize(m_zetas.size());\n  m_PQNs = m_pqns;\n  // Calculate the normalizations of the orbitals\n  for (unsigned int i = 0; i < m_zetas.size(); ++i) {\n    switch (m_slaterTypes[i]) {\n    case S:\n      m_factors[i] = pow(2.0 * m_zetas[i], m_pqns[i] + 0.5) *\n          sqrt(1.0 / (4.0*M_PI) / factorial(2*m_pqns[i]));\n      m_PQNs[i] -= 1;\n      break;\n    case PX:\n    case PY:\n    case PZ:\n      m_factors[i] = pow(2.0 * m_zetas[i], m_pqns[i] + 0.5) *\n          sqrt(3.0 / (4.0*M_PI) / factorial(2*m_pqns[i]));\n      m_PQNs[i] -= 2;\n      break;\n    case X2:\n      m_factors[i] = 0.5 * pow(2.0 * m_zetas[i], m_pqns[i] + 0.5) *\n          sqrt(15.0 / (4.0*M_PI) / factorial(2*m_pqns[i]));\n      m_PQNs[i] -= 3;\n      break;\n    case XZ:\n      m_factors[i] = pow(2.0 * m_zetas[i], m_pqns[i] + 0.5) *\n          sqrt(15.0 / (4.0*M_PI) / factorial(2*m_pqns[i]));\n      m_PQNs[i] -= 3;\n      break;\n    case Z2:\n      m_factors[i] = (0.5/sqrt(3.0)) * pow(2.0 * m_zetas[i], m_pqns[i] + 0.5) *\n          sqrt(15.0 / (4.0*M_PI) / factorial(2*m_pqns[i]));\n      m_PQNs[i] -= 3;\n      break;\n    case YZ:\n    case XY:\n      m_factors[i] = pow(2.0 * m_zetas[i], m_pqns[i] + 0.5) *\n          sqrt(15.0 / (4.0*M_PI) / factorial(2*m_pqns[i]));\n      m_PQNs[i] -= 3;\n      break;\n    default:\n      qDebug() << \"Orbital\" << i << \"not handled, type\" << m_slaterTypes[i];\n    }\n  }\n  // Convert the exponents into Angstroms\n  for (unsigned int i = 0; i < m_zetas.size(); ++i)\n    m_zetas[i] = m_zetas[i] / BOHR_TO_ANGSTROM;\n\n  m_initialized = true;\n\n  return true;\n}\n\nvoid SlaterSet::processPoint(SlaterShell &shell)\n{\n  SlaterSet *set = shell.set;\n  unsigned int atomsSize = static_cast<unsigned int>(set->m_atomPos.size());\n  unsigned int basisSize = static_cast<unsigned int>(set->m_zetas.size());\n\n  vector<Vector3d> deltas;\n  vector<double> dr;\n  deltas.reserve(atomsSize);\n  dr.reserve(atomsSize);\n\n  // Simply the row of the matrix to operate on\n  unsigned int indexMO = shell.state - 1;\n\n  // Calculate our position\n  Vector3d pos = shell.cube->position(shell.pos);// * ANGSTROM_TO_BOHR;\n\n  // Calculate the deltas for the position\n  for (unsigned int i = 0; i < atomsSize; ++i) {\n    deltas.push_back(pos - set->m_atomPos[i]);\n    dr.push_back(deltas[i].norm());\n  }\n\n  // Now calculate the value at this point in space\n  double tmp = 0.0;\n  for (unsigned int i = 0; i < basisSize; ++i) {\n    tmp += pointSlater(shell.set, deltas[set->m_slaterIndices[i]],\n                       dr[set->m_slaterIndices[i]], i, indexMO);\n  }\n  // Set the value\n  shell.cube->setValue(shell.pos, tmp);\n}\n\nvoid SlaterSet::processDensity(SlaterShell &shell)\n{\n  // Calculate the electron density\n  SlaterSet *set = shell.set;\n  unsigned int atomsSize = static_cast<unsigned int>(set->m_atomPos.size());\n  unsigned int basisSize = static_cast<unsigned int>(set->m_zetas.size());\n  unsigned int matrixSize = static_cast<unsigned int>(set->m_density.rows());\n\n  vector<Vector3d> deltas;\n  vector<double> dr;\n  deltas.reserve(atomsSize);\n  dr.reserve(atomsSize);\n\n  // Calculate our position\n  Vector3d pos = shell.cube->position(shell.pos);// * ANGSTROM_TO_BOHR;\n\n  // Calculate the deltas for the position\n  for (unsigned int i = 0; i < atomsSize; ++i) {\n    deltas.push_back(pos - set->m_atomPos[i]);\n    dr.push_back(deltas[i].norm());\n  }\n\n  // Precompute the factor * exp (-zeta * drs)\n  vector<double> expZetas(basisSize);\n  for (unsigned int i = 0; i < basisSize; ++i) {\n    expZetas[i] = exp(- set->m_zetas[i] * dr[set->m_slaterIndices[i]]);\n  }\n\n  // Now calculate the value of the density at this point in space\n  double rho = 0.0;\n  for (unsigned int i = 0; i < matrixSize; ++i) {\n    // Calculate the off-diagonal parts of the matrix\n    for (unsigned int j = 0; j < i; ++j) {\n      if (isSmall(set->m_density.coeffRef(i, j))) continue;\n      double a = 0.0, b = 0.0;\n      // Do the first basis\n      a = calcSlater(shell.set, deltas[set->m_slaterIndices[i]],\n                     dr[set->m_slaterIndices[i]], i);\n      b = calcSlater(shell.set, deltas[set->m_slaterIndices[j]],\n                     dr[set->m_slaterIndices[j]], j);\n      rho += 2.0 * set->m_density.coeffRef(i, j) * (a*b);\n    }\n    // Now calculate the matrix diagonal\n    double tmp = 0.0;\n    tmp = calcSlater(shell.set, deltas[set->m_slaterIndices[i]],\n                     dr[set->m_slaterIndices[i]], i);\n    rho += set->m_density.coeffRef(i, i) * (tmp*tmp);\n  }\n  // Set the value\n  shell.cube->setValue(shell.pos, rho);\n}\n\ninline double SlaterSet::pointSlater(SlaterSet *set, const Eigen::Vector3d &delta,\n                                     double dr, unsigned int slater,\n                                     unsigned int indexMO)\n{\n  if (isSmall(set->m_normalized.coeffRef(slater, indexMO)))\n    return 0.0;\n  double tmp = set->m_normalized.coeffRef(slater, indexMO) *\n      set->m_factors[slater] * exp(- set->m_zetas[slater] * dr);\n  // Radial part with effective PQNs\n  for (int i = 0; i < set->m_PQNs[slater]; ++i)\n    tmp *= dr;\n  switch (set->m_slaterTypes[slater]) {\n  case S:\n    break;\n  case PX:\n    tmp *= delta.x();\n    break;\n  case PY:\n    tmp *= delta.y();\n    break;\n  case PZ:\n    tmp *= delta.z();\n    break;\n  case X2: // (x^2 - y^2)r^n\n    tmp *= delta.x() * delta.x() - delta.y() * delta.y();\n    break;\n  case XZ: // xzr^n\n    tmp *= delta.x() * delta.z();\n    break;\n  case Z2: // (2z^2 - x^2 - y^2)r^n\n    tmp *= 2.0 * delta.z() * delta.z() - delta.x() * delta.x()\n        - delta.y() * delta.y();\n    break;\n  case YZ: // yzr^n\n    tmp *= delta.y() * delta.z();\n    break;\n  case XY: // xyr^n\n    tmp *= delta.x() * delta.y();\n    break;\n  default:\n    return 0.0;\n  }\n  return tmp;\n}\n\ninline double SlaterSet::pointSlater(SlaterSet *set, const Eigen::Vector3d &delta,\n                                     double dr, unsigned int slater,\n                                     unsigned int indexMO, double expZeta)\n{\n  if (isSmall(set->m_normalized.coeffRef(slater, indexMO)))\n    return 0.0;\n  double tmp = set->m_normalized.coeffRef(slater, indexMO) * expZeta;\n  // Radial part with effective PQNs\n  for (int i = 0; i < set->m_PQNs[slater]; ++i)\n    tmp *= dr;\n  switch (set->m_slaterTypes[slater]) {\n  case S:\n    break;\n  case PX:\n    tmp *= delta.x();\n    break;\n  case PY:\n    tmp *= delta.y();\n    break;\n  case PZ:\n    tmp *= delta.z();\n    break;\n  case X2: // (x^2 - y^2)r^n\n    tmp *= delta.x() * delta.x() - delta.y() * delta.y();\n    break;\n  case XZ: // xzr^n\n    tmp *= delta.x() * delta.z();\n    break;\n  case Z2: // (2z^2 - x^2 - y^2)r^n\n    tmp *= 2.0 * delta.z() * delta.z() - delta.x() * delta.x()\n        - delta.y() * delta.y();\n    break;\n  case YZ: // yzr^n\n    tmp *= delta.y() * delta.z();\n    break;\n  case XY: // xyr^n\n    tmp *= delta.x() * delta.y();\n    break;\n  default:\n    return 0.0;\n  }\n  return tmp;\n}\n\ninline double SlaterSet::calcSlater(SlaterSet *set, const Eigen::Vector3d &delta,\n                                    double dr, unsigned int slater)\n{\n  double tmp = set->m_factors[slater] * exp(- set->m_zetas[slater] * dr);\n  // Radial part with effective PQNs\n  for (int i = 0; i < set->m_PQNs[slater]; ++i)\n    tmp *= dr;\n  switch (set->m_slaterTypes[slater]) {\n  case S:\n    break;\n  case PX:\n    tmp *= delta.x();\n    break;\n  case PY:\n    tmp *= delta.y();\n    break;\n  case PZ:\n    tmp *= delta.z();\n    break;\n  case X2: // (x^2 - y^2)r^n\n    tmp *= delta.x() * delta.x() - delta.y() * delta.y();\n    break;\n  case XZ: // xzr^n\n    tmp *= delta.x() * delta.z();\n    break;\n  case Z2: // (2z^2 - x^2 - y^2)r^n\n    tmp *= 2.0 * delta.z() * delta.z() - delta.x() * delta.x()\n        - delta.y() * delta.y();\n    break;\n  case YZ: // yzr^n\n    tmp *= delta.y() * delta.z();\n    break;\n  case XY: // xyr^n\n    tmp *= delta.x() * delta.y();\n    break;\n  default:\n    return 0.0;\n  }\n  return tmp;\n}\n\n}\n", "meta": {"hexsha": "bfc0d6841b0cbe3040533ebd666ef60eb2c56d25", "size": 14949, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "openqube/slaterset.cpp", "max_stars_repo_name": "OpenChemistry/openqube", "max_stars_repo_head_hexsha": "dc396bcf6c74cbfd9fb94201312e70bb377b0805", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2015-05-05T19:49:55.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-30T12:27:40.000Z", "max_issues_repo_path": "openqube/slaterset.cpp", "max_issues_repo_name": "OpenChemistry/openqube", "max_issues_repo_head_hexsha": "dc396bcf6c74cbfd9fb94201312e70bb377b0805", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "openqube/slaterset.cpp", "max_forks_repo_name": "OpenChemistry/openqube", "max_forks_repo_head_hexsha": "dc396bcf6c74cbfd9fb94201312e70bb377b0805", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2015-01-29T16:25:12.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-06T17:47:47.000Z", "avg_line_length": 27.8899253731, "max_line_length": 111, "alphanum_fraction": 0.6192387451, "num_tokens": 4488, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6757645879592642, "lm_q2_score": 0.48047867804790706, "lm_q1q2_score": 0.32469047589425587}}
{"text": "// This file is part of MLDB. Copyright 2015 mldb.ai inc. All rights reserved.\n\n/* perceptron_generator.cc\n   Jeremy Barnes, 15 March 2006\n   Copyright (c) 2006 Jeremy Barnes  All rights reserved.\n\n   Generator for perceptrons.\n*/\n\n#include \"perceptron_generator.h\"\n#include \"mldb/plugins/jml/jml/registry.h\"\n#include <boost/timer.hpp>\n#include <boost/progress.hpp>\n#include \"mldb/plugins/jml/jml/training_index.h\"\n#include \"mldb/utils/distribution_simd.h\"\n#include \"mldb/arch/simd_vector.h\"\n#include \"mldb/plugins/jml/algebra/lapack.h\"\n#include \"mldb/plugins/jml/algebra/matrix_ops.h\"\n#include \"mldb/plugins/jml/algebra/irls.h\"\n#include <iomanip>\n#include \"mldb/utils/environment.h\"\n#include \"mldb/utils/profile.h\"\n#include \"mldb/base/parallel.h\"\n#include \"mldb/base/scope.h\"\n#include \"mldb/plugins/jml/jml/evaluation.h\"\n#include <boost/scoped_ptr.hpp>\n#include \"mldb/utils/smart_ptr_utils.h\"\n#include \"mldb/utils/vector_utils.h\"\n#include \"mldb/utils/pair_utils.h\"\n#include \"mldb/plugins/jml/neural/dense_layer.h\"\n#include \"discriminative_trainer.h\"\n\nusing namespace std;\n\n\nnamespace ML {\n\n\nnamespace {\n\nEnvOption<bool> profile(\"PROFILE_PERCEPTRON\", false);\n\ndouble t_train = 0.0, t_decorrelate = 0.0;\ndouble t_cholesky = 0.0, t_qr = 0.0, t_gs = 0.0, t_mean = 0.0, t_covar = 0.0;\ndouble t_update = 0.0, t_fprop = 0.0, t_bprop = 0.0, t_zero = 0.0;\ndouble t_setup = 0.0;\n\nstruct Stats {\n    ~Stats()\n    {\n        if (profile) {\n            cerr << \"perceptron training profile: \" << endl;\n            cerr << \"  decorrelate:    \" << t_decorrelate << \"s\" << endl;\n            cerr << \"    qr:           \" << t_qr          << \"s\" << endl;\n            cerr << \"    gram schmidt: \" << t_gs          << \"s\" << endl;\n            cerr << \"    mean:         \" << t_mean        << \"s\" << endl;\n            cerr << \"    covar         \" << t_covar       << \"s\" << endl;\n            cerr << \"    cholesky:     \" << t_cholesky    << \"s\" << endl;\n            cerr << \"  train:          \" << t_train       << \"s\" << endl;\n            cerr << \"    setup:        \" << t_setup       << \"s\" << endl;\n            cerr << \"    update:       \" << t_update      << \"s\" << endl;\n            cerr << \"    fprop:        \" << t_fprop       << \"s\" << endl;\n            cerr << \"    bprop:        \" << t_bprop       << \"s\" << endl;\n            cerr << \"    zero:         \" << t_zero        << \"s\" << endl;\n        }\n    }\n} stats;\n\n} // file scope\n\n\n/*****************************************************************************/\n/* PERCEPTRON_GENERATOR                                                      */\n/*****************************************************************************/\n\nPerceptron_Generator::\nPerceptron_Generator()\n{\n    defaults();\n}\n\nPerceptron_Generator::~Perceptron_Generator()\n{\n}\n\nvoid\nPerceptron_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(learning_rate, \"learning_rate\", unparsedKeys);\n    config.findAndRemove(arch_str, \"arch\", unparsedKeys);\n    config.findAndRemove(batch_size, \"batch_size\", unparsedKeys);\n    config.findAndRemove(activation, \"activation\", unparsedKeys);\n    config.findAndRemove(output_activation, \"output_activation\", unparsedKeys);\n    config.findAndRemove(do_decorrelate, \"decorrelate\", unparsedKeys);\n    config.findAndRemove(do_normalize, \"normalize\", unparsedKeys);\n    config.findAndRemove(target_value, \"target_value\", unparsedKeys);\n}\n\nvoid\nPerceptron_Generator::\ndefaults()\n{\n    Early_Stopping_Generator::defaults();\n    max_iter = 100;\n    min_iter = 10;\n    learning_rate = 0.01;\n    arch_str = \"%i\";\n    activation = output_activation = TF_TANH;\n    do_decorrelate = true;\n    do_normalize = true;\n    batch_size = 1024;\n    target_value = 0.8;\n}\n\nConfig_Options\nPerceptron_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(\"learning_rate\", learning_rate, \"real\",\n             \"positive: rate of learning relative to dataset size: negative for absolute\")\n        .add(\"arch\", arch_str, \"(see doc)\",\n             \"hidden unit specification; %i=in vars, %o=out vars; eg 5_10\")\n        .add(\"activation\", activation,\n             \"activation function for neurons\")\n        .add(\"output_activation\", output_activation,\n             \"activation function for output layer of neurons\")\n        .add(\"decorrelate\", do_decorrelate,\n             \"decorrelate the features before training\")\n        .add(\"normalize\", do_normalize,\n             \"normalize to zero mean and unit std before training\")\n        .add(\"batch_size\", batch_size, \"0.0-1.0 or 1 - nvectors\",\n             \"number of samples in each \\\"mini batch\\\" for stochastic\")\n        .add(\"target_value\", target_value, \"0.0-1.0\", \"the output for a 1 that we ask the network to provide\");\n    \n    return result;\n}\n\nvoid\nPerceptron_Generator::\ninit(std::shared_ptr<const Feature_Space> fs, Feature predicted)\n{\n    Early_Stopping_Generator::init(fs, predicted);\n    model = Perceptron(fs, predicted);\n}\n\nstd::shared_ptr<Classifier_Impl>\nPerceptron_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    bool regression = feature_space->info(predicted).type() == REAL;\n\n    Perceptron current(model);\n    Perceptron best(model);\n    \n    float best_acc = 0.0;\n    float best_rmse = 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    //    validate_is_train = true;\n\n    if (validate_ex_weights.total() == 0.0)\n        throw Exception(\"no validate ex weights\");\n\n    std::unique_ptr<boost::progress_display> progress;\n\n    //cerr << \"training_ex_weights = \" << training_ex_weights << endl;\n    //cerr << \"validate_ex_weights = \" << validate_ex_weights << endl;\n\n    log(\"perceptron_generator\", 1)\n        << \"training \" << max_iter << \" iterations...\" << endl;\n\n    if (verbosity < 3)\n        progress.reset(new boost::progress_display\n                       (max_iter, log(\"perceptron_generator\", 1)));\n    \n    vector<int> arch = Perceptron::parse_architecture(arch_str);\n    \n    boost::multi_array<float, 2> decorrelated\n        = init(training_set, features, arch, current, context);\n\n    size_t nx_validate\n        = (validate_is_train ? training_set : validation_set)\n        .example_count();\n\n    boost::multi_array<float, 2> val_decorrelated\n        (boost::extents[nx_validate][decorrelated.shape()[1]]);\n\n    if (validate_is_train) val_decorrelated = decorrelated;\n    else val_decorrelated = current.decorrelate(validation_set);\n\n    size_t nx = decorrelated.shape()[0];\n    size_t nxv = val_decorrelated.shape()[0];\n    size_t nf = decorrelated.shape()[1];\n\n    log(\"perceptron_generator\", 1)\n        << current.parameters() << \" parameters, \"\n        << nx << \" examples, \" << nx * nf << \" training values\" << endl;\n    \n    if (min_iter > max_iter)\n        throw Exception(\"min_iter is greater than max_iter\");\n\n    log(\"perceptron_generator\", 3)\n        << \"  it   train     rmse     val     rmse    best     diff\" << endl;\n    \n    float validate_acc = 0.0, validate_rmse = 0.0;\n    float train_acc = 0.0, train_rmse = 0.0;\n\n    const std::vector<Label> & labels\n        = training_set.index().labels(predicted);\n    const std::vector<Label> & val_labels MLDB_UNUSED\n        = validation_set.index().labels(predicted);\n\n    double last_best_acc = 0.0;\n    double last_best_rmse MLDB_UNUSED = 0.0;\n\n    int our_batch_size = batch_size;\n    if (batch_size == 0.0) our_batch_size = nx;\n    else if (batch_size < 1.0) our_batch_size = nx * batch_size;\n\n    /* If we specified a negative learning rate, that means that we wanted it\n       to be absolute (and so not depend upon the size of the dataset).  In\n       order to get this behaviour, we need to multipy by the number of\n       examples in the dataset, since it is implicitly multiplied by the\n       example weight (on average 1/num examples in training set) as part of\n       the training, and we want to counteract this effect).\n    */\n    float learning_rate = this->learning_rate;\n    if (learning_rate < 0.0) {\n        learning_rate\n            *= -1.0 * training_ex_weights.size() / training_ex_weights.total();\n    }\n\n    // Create a layer stack without the decorrelation layer to be trained\n    Layer_Stack<Layer> train_stack;\n    for (unsigned i = 1;  i < current.layers.size();  ++i)\n        train_stack.add(current.layers.share(i));\n    \n    Discriminative_Trainer trainer;\n    trainer.layer = &train_stack;\n\n    bool randomize = false;\n    float sample_proportion = 1.0;\n\n    vector<const float *> examples(nx);\n    for (unsigned i = 0;  i < nx;  ++i)\n        examples[i] = &decorrelated[i][0];\n\n    vector<const float *> val_examples(nxv);\n    for (unsigned i = 0;  i < nxv;  ++i)\n        val_examples[i] = &val_decorrelated[i][0];\n    \n    Output_Encoder & output_encoder = current.output;\n    output_encoder.configure(model.feature_space()->info(model.predicted()),\n                             train_stack, target_value);\n\n\n    for (unsigned i = 0;  i < max_iter;  ++i) {\n\n        //cerr << \"params = \" << Parameters_Copy<float>(train_stack.parameters()).values << endl;\n\n        //cerr << \"mode = \" << output_encoder.mode << \" value_true = \" << output_encoder.value_true\n        //     << \" value_false = \" << output_encoder.value_false << \" num_inputs = \"\n        //     << output_encoder.num_inputs << \" num_outputs = \" << output_encoder.num_outputs\n        //     << endl;\n\n        {\n            PROFILE_FUNCTION(t_train);\n            \n            std::tie(train_acc, train_rmse)\n                = trainer.train_iter(examples, labels, training_ex_weights,\n                                     output_encoder,\n                                     context, our_batch_size, learning_rate,\n                                     verbosity, sample_proportion, randomize);\n        }\n\n        if (validate_is_train) {\n            validate_acc = train_acc;\n            validate_rmse = train_rmse;\n        }\n        else {\n            std::tie(validate_acc, validate_rmse)\n                = trainer.test(val_examples, val_labels, validate_ex_weights,\n                               output_encoder, context, verbosity);\n        }\n\n        last_best_acc = best_acc;\n        last_best_rmse = best_rmse;\n\n        if (i == min_iter\n            || (validate_acc > best_acc && !regression)\n            || (validate_acc < best_acc && regression)) {\n            best = current;\n            best_acc = validate_acc;\n            best_rmse = validate_rmse;\n            best_iter = i;\n        }\n\n        log(\"perceptron_generator\", 3)\n            << format(\"%4d %6.2f%% %8.6f %6.2f%% %8.6f %6.2f%% %+7.3f%%\",\n                      i, train_acc * 100.0, train_rmse, validate_acc * 100.0,\n                      validate_rmse,\n                      best_acc * 100.0, (validate_acc - last_best_acc) * 100.0)\n            << endl;\n\n        if (progress) ++(*progress);\n\n                \n        log(\"perceptron_generator\", 5) << current.print() << endl;\n    }\n    \n    if (profile)\n        log(\"perceptron_generator\", 1)\n            << \"training time: \" << timer.elapsed().wall << \"s\" << endl;\n    \n    log(\"perceptron_generator\", 1)\n        << format(\"best was %6.2f%% on iteration %d\", best_acc * 100.0,\n                  best_iter)\n        << endl;\n\n    float trn_acc, trn_rmse, val_acc, val_rmse;\n    std::tie(trn_acc, trn_rmse)\n        = best.accuracy(training_set);\n    std::tie(val_acc, val_rmse)\n        = best.accuracy(validation_set);\n\n    log(\"perceptron_generator\", 1)\n        << \"best accuracy: \" << trn_acc << \"/\"\n        << trn_rmse << \" train, \"\n        << val_acc << \"/\" << val_rmse\n        << \" validation\" << endl;\n    \n    log(\"perceptron_generator\", 4) << best.print() << endl;\n    \n    return make_sp(best.make_copy());\n}\n\nnamespace {\n\nboost::multi_array<double, 2>\ncholesky(const boost::multi_array<double, 2> & A_)\n{\n    PROFILE_FUNCTION(t_cholesky);\n\n    if (A_.shape()[0] != A_.shape()[1])\n        throw Exception(\"cholesky: matrix isn't square\");\n    \n    int n = A_.shape()[0];\n\n    boost::multi_array<double, 2> A(boost::extents[n][n]);\n    std::copy(A_.begin(), A_.end(), A.begin());\n    \n    int res = LAPack::potrf('U', n, A.data(), n);\n    \n    if (res < 0)\n        throw Exception(format(\"cholesky: potrf: argument %d was illegal\", -res));\n    else if (res > 0)\n        throw Exception(format(\"cholesky: potrf: leading minor %d of %d \"\n                               \"not positive definite\", res, n));\n    \n    for (unsigned i = 0;  i < n;  ++i)\n        std::fill(&A[i][0] + i + 1, &A[i][0] + n, 0.0);\n\n    return A;\n\n#if 0\n    //cerr << \"residuals = \" << endl << (A * transpose(A)) - A_ << endl;\n\n    boost::multi_array<float, 2> result(boost::extents[n][n]);\n    std::copy(A.begin(), A.end(), result.begin());\n\n    return result;\n#endif\n}\n\ntemplate<typename Float>\nboost::multi_array<Float, 2>\nlower_inverse(const boost::multi_array<Float, 2> & A)\n{\n    if (A.shape()[0] != A.shape()[1])\n        throw Exception(\"lower_inverse: matrix isn't square\");\n    \n    int n = A.shape()[0];\n\n    boost::multi_array<Float, 2> L = A;\n    \n    for (int j = 0;  j < n;  ++j) {\n        L[j][j] = 1.0 / L[j][j];\n\n        for (int i = j + 1;  i < n;  ++i) {\n            double sum = 0.0;\n            for (unsigned k = j;  k < i;  ++k)\n                sum -= L[i][k] * L[k][j];\n            L[i][j] = sum / L[i][i];\n        }\n    }\n    \n    //cerr << \"L * A = \" << endl << L * A << endl;\n\n    return L;\n}\n\n} // file scope\n\n/** Decorrelates the training data, returning a dense decorrelated dataset. */\nboost::multi_array<float, 2>\nPerceptron_Generator::\ndecorrelate(const Training_Data & data,\n            const std::vector<Feature> & possible_features,\n            Perceptron & result) const\n{\n    PROFILE_FUNCTION(t_decorrelate);\n\n    const Dataset_Index & index = data.index();\n\n    vector<Feature> & features = result.features;\n    features.clear();\n\n    cerr << \"decorrelate: \" << possible_features.size() << \" features at input\"\n         << endl;\n    \n    /* Figure out if we can keep each feature or not. */\n    \n    for (unsigned i = 0;  i < possible_features.size();  ++i) {\n        const Feature & feature = possible_features[i];\n\n        if (feature == result.predicted()) continue;  // don't use label as a feature!\n\n        /* Find out information about the feature from the training data. */\n        if (!index.dense(feature)) {\n            cerr << \"feature \" << result.feature_space()->print(feature)\n                 << \" skipped due to missing values\" << endl;\n            continue;\n        }\n        else if (!index.exactly_one(feature)) {\n            cerr << \"feature \" << i << \" (\"\n                 << result.feature_space()->print(feature)\n                 << \") skipped due to more than one value\" << endl;\n            continue;\n        }\n        else if (index.constant(feature)) {\n            cerr << \"feature \" << i << \" (\"\n                 << result.feature_space()->print(feature)\n                 << \") skipped as it is constant over the dataset\" << endl;\n            continue;\n        }\n        else {\n            float min, max;\n            std::tie(min, max) = index.range(feature);\n            if (abs(min) > 1e10 || abs(max) > 1e10) {\n                cerr << \"feature \" << i << \" (\"\n                     << result.feature_space()->print(feature)\n                     << \") skipped as its range is too large: \"\n                     << min << \" to \" << max << endl;\n                continue;\n            }\n        }\n        features.push_back(feature);\n    }\n\n    cerr << \"decorrelate: \" << features.size()\n         << \" features after trivial elimination\" << endl;\n    \n    std::sort(features.begin(), features.end());\n\n    size_t nx = data.example_count();\n    size_t nf = features.size();\n\n    /* Get a dense matrix of the features. */\n    boost::multi_array<double, 2> input(boost::extents[nx][nf + 1]);\n    \n    for (unsigned x = 0;  x < nx;  ++x) {\n        result.extract_features(data[x], &input[x][0]);\n        input[x][nf] = 1.0;  // bias term\n    }\n\n    //cerr << \"input.shape()[0] = \" << input.shape()[0] << endl;\n    //cerr << \"input.shape()[1] = \" << input.shape()[1] << endl;\n    boost::multi_array<double, 2> inputt = transpose(input);\n\n    //cerr << \"inputt.shape()[0] = \" << inputt.shape()[0] << endl;\n    //cerr << \"inputt.shape()[1] = \" << inputt.shape()[1] << endl;\n    vector<distribution<double> > dependent;\n    vector<int> permutations(nf + 1, 0);\n    \n#if 0\n    boost::multi_array<float, 2> input2 = inputt;\n\n    /* Factorize the matrix with partial pivoting.  This allows us to find the\n       largest number of linearly independent columns possible. */\n\n    float tau[nf];\n    vector<int> permutations(nf + 1, 0);\n    permutations[nf] = 1;  // make bias be a leading column\n\n    {\n        PROFILE_FUNCTION(t_qr);\n        int res = LAPack::geqp3(nx, nf + 1, inputt.data_begin(), inputt.shape()[1],\n                                &permutations[0],\n                                tau);\n        \n        if (res != 0)\n            throw Exception(format(\"geqp3: error in parameter %d\", -res));\n    }\n    \n    cerr << \"permutations = \" << permutations << endl;\n    for (unsigned i = 0;  i <= nf;  ++i)\n        cerr << \"r[\" << i << \"][\" << i << \"] = \" << inputt[i][i] << endl;\n\n    /* Check for linearly dependent columns. */\n    inputt = input2;\n#endif\n    \n    {\n        PROFILE_FUNCTION(t_gs);\n        permutations = remove_dependent_impl(inputt, dependent, 1e-4);\n    }\n\n    //cerr << \"permutations = \" << permutations << endl;\n    \n    /* Find which features are left */\n    vector<Feature> new_features;\n    for (unsigned i = 0;  i < features.size();  ++i) {\n        if (permutations[i] != -1) {\n            //cerr << \"feature \" << new_features.size() << \" is old feature \"\n            //     << i << \" (\" << feature_space->print(features[i]) << \")\"\n            //     << endl;\n            new_features.push_back(features[i]);\n        }\n    }\n    \n    for (unsigned i = 0;  i < features.size();  ++i) {\n        if (permutations[i] == -1) {\n            cerr << \"feature \"\n                 << result.feature_space()->print(features[i])\n                 << \" removed as it can be calculated as \";\n            cerr << result.feature_space()->print(features[i])\n                 << \" = \";\n            bool first = true;\n            for (unsigned j = 0;  j < dependent[i].size();  ++j) {\n                double v = dependent[i][j];\n                if (abs(v) < 0.0001) continue;\n\n                if (v < 0.0) {\n                    cerr << \" - \";\n                }\n                else {\n                    if (first) ;\n                    else cerr << \" + \";\n                }\n                \n                v = abs(v);\n                if (abs(v - 1.0) < 0.0001) ;\n                else cerr << setprecision(4) << v << \" \";\n                \n                if (j == new_features.size()) ;\n                else cerr << result.feature_space()->print(new_features[j]);\n                \n                first = false;\n            }\n            cerr << endl;\n        }\n    }\n\n    /* Calculate the covariance matrix over those that are left.  Note that\n       we could decorrelate them with the orthogonalization that we did above,\n       but then we wouldn't be able to save it as a covariance matrix.\n    */\n    features.swap(new_features);\n    nf = features.size();\n\n    distribution<double> mean(nf, 0.0);\n    distribution<double> stdev(nf, 0.0);\n    boost::multi_array<double, 2> covar(boost::extents[nf][nf]);\n\n    if (do_decorrelate && !do_normalize)\n        throw Exception(\"normalization required if decorrelation is done\");\n\n    if (do_normalize || do_decorrelate) {\n        {\n            PROFILE_FUNCTION(t_mean);\n            for (unsigned f = 0;  f < nf;  ++f) {\n                mean[f] = SIMD::vec_sum_dp(&inputt[f][0], nx) / nx;\n                for (unsigned x = 0;  x < nx;  ++x)\n                    inputt[f][x] -= mean[f];\n            }\n        }\n\n        cerr << \"mean = \" << mean << endl;\n\n        {\n            PROFILE_FUNCTION(t_covar);\n            for (unsigned f = 0;  f < nf;  ++f) {\n                for (unsigned f2 = 0;  f2 <= f;  ++f2)\n                    covar[f][f2] = covar[f2][f]\n                        = SIMD::vec_dotprod_dp(&inputt[f][0], &inputt[f2][0], nx) / nx;\n            }\n        \n            for (unsigned f = 0;  f < nf;  ++f)\n                stdev[f] = sqrt(covar[f][f]);\n            \n            cerr << \"stdev = \" << stdev << endl;\n        }\n    }\n    \n    boost::multi_array<double, 2> transform(boost::extents[nf][nf]);\n\n    if (do_decorrelate) {\n        /* Do the cholevsky stuff */\n        PROFILE_FUNCTION(t_cholesky);\n        transform = transpose(lower_inverse(cholesky(covar)));\n    }\n    else if (do_normalize) {\n        /* Use a unit diagonal of 1/stdev for the transform; no\n           decorrelation */\n        std::fill(transform.origin(),\n                  transform.origin() + transform.num_elements(),\n                  0.0f);\n        for (unsigned f = 0;  f < nf;  ++f)\n            transform[f][f] = 1.0 / stdev[f];\n    }\n    else {\n        /* Use the identity function */\n        std::fill(transform.origin(),\n                  transform.origin() + transform.num_elements(),\n                  0.0f);\n        for (unsigned f = 0;  f < nf;  ++f)\n            transform[f][f] = 1.0;\n    }\n    \n    /* Finally, we add a layer.  This will perform both the removal of the\n       mean (via the biasing) and the decorrelation (via the application\n       of the matrix).\n    */\n    \n    /* y = (x - mean) * A;\n         = (x * A) - (mean * A);\n    */\n\n    std::shared_ptr<Dense_Layer<float> > layer\n        (new Dense_Layer<float>(\"decorrelation\", nf, nf, TF_IDENTITY,\n                                MV_NONE));\n    layer->weights.resize(boost::extents[transform.shape()[0]][transform.shape()[1]]);\n    layer->weights = transform;\n    layer->bias = distribution<float>(nf, 0.0);  // already have mean removed\n    \n    //cerr << \"transform = \" << transform << endl;\n\n    boost::multi_array<float, 2> decorrelated(boost::extents[nx][nf]);\n    float fv_in[nf];\n\n    for (unsigned x = 0;  x < nx;  ++x) {\n        for (unsigned f = 0;  f < nf;  ++f)\n            fv_in[f] = inputt[f][x];\n\n        //cerr << \"fv_in = \" << distribution<float>(fv_in, fv_in + nf) << endl;\n\n        layer->apply(&fv_in[0], &decorrelated[x][0]);\n\n        //cerr << \"fv_out = \"\n        //     << distribution<float>(&decorrelated[x][0],\n        //                            &decorrelated[x][0] + nf)\n        //     << endl;\n        \n    }\n\n    layer->bias = (transform * mean) * -1.0;  // now add the bias\n    result.layers.clear();\n    result.add_layer(layer);\n    \n    layer->validate();\n\n    return decorrelated;\n}\n\nboost::multi_array<float, 2>\nPerceptron_Generator::\ninit(const Training_Data & data,\n     const std::vector<Feature> & possible_features,\n     const std::vector<int> & architecture,\n     Perceptron & result,\n     Thread_Context & context) const\n{\n    result = model;\n\n    /* Find out about the output that we need (in particular, how many\n       values it can have). */\n    boost::multi_array<float, 2> decorrelated\n        = decorrelate(data, possible_features, result);\n\n    Feature_Info pred_info = model.feature_space()->info(model.predicted());\n    int nout = pred_info.value_count();\n    if (nout == 0) nout = 1;  // regression problem; one output\n\n    int nunits = result.features.size();\n\n    cerr << \"adding decorrelating input layer with \" << nunits\n         << \" linear units\" << endl;\n\n    /* Add hidden layers with the specified sizes */\n    for (unsigned i = 0;  i < architecture.size();  ++i) {\n        int units = architecture[i];\n        if (units == -1) units = result.features.size();\n\n        cerr << \"adding hidden layer \" << i + 1 << \" with \"\n             << units << \" units and activation function \"\n             << activation << endl;\n\n        std::shared_ptr<Layer>\n            layer(new Dense_Layer<float>(format(\"hidden%d\", i),\n                                         nunits, units, activation,\n                                         MV_NONE, context));\n        result.add_layer(layer);\n        nunits = units;\n    }\n    \n    /* Add the output units. */\n    std::shared_ptr<Layer> layer\n        (new Dense_Layer<float>(\"output\", nunits, nout, output_activation,\n                                MV_NONE, context));\n    result.add_layer(layer);\n\n    cerr << \"adding output layer with \" << nout << \" units and activation \"\n         << output_activation << endl;\n    \n    return decorrelated;\n}\n\n\n\n/*****************************************************************************/\n/* REGISTRATION                                                              */\n/*****************************************************************************/\n\nnamespace {\n\nRegister_Factory<Classifier_Generator, Perceptron_Generator>\n    PERCEPTRON_REGISTER(\"perceptron\");\n\n} // file scope\n\n} // namespace ML\n", "meta": {"hexsha": "9cc1e9b358b86d2f8b70af1a34d9bee5e0e05d61", "size": 25776, "ext": "cc", "lang": "C++", "max_stars_repo_path": "plugins/jml/neural/perceptron_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/neural/perceptron_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/neural/perceptron_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.6941176471, "max_line_length": 111, "alphanum_fraction": 0.5488826816, "num_tokens": 6493, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6442251064863697, "lm_q2_score": 0.5039061705290805, "lm_q1q2_score": 0.3246290063682356}}
{"text": "/*\r\n * Copyright (c) 2013, Christian Gehring, Hannes Sommer, Paul Furgale, Remo Diethelm\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 *     * Redistributions of source code must retain the above copyright\r\n *       notice, this list of conditions and the following disclaimer.\r\n *     * Redistributions in binary form must reproduce the above copyright\r\n *       notice, this list of conditions and the following disclaimer in the\r\n *       documentation and/or other materials provided with the distribution.\r\n *     * Neither the name of the Autonomous Systems Lab, ETH Zurich 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\" AND\r\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\r\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\r\n * DISCLAIMED. IN NO EVENT SHALL Christian Gehring, Hannes Sommer, Paul Furgale,\r\n * Remo Diethelm BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,\r\n * 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)\r\n * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\r\n * OR TORT (INCLUDING 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*/\r\n#ifndef KINDR_ROTATIONS_ROTATION_EIGEN_FUNCTIONS_HPP_\r\n#define KINDR_ROTATIONS_ROTATION_EIGEN_FUNCTIONS_HPP_\r\n\r\n\r\n#include <cmath>\r\n\r\n#include <Eigen/Core>\r\n#include <Eigen/Geometry>\r\n\r\n#include \"kindr/common/common.hpp\"\r\n\r\nnamespace kindr {\r\nnamespace rotations {\r\nnamespace eigen_impl {\r\nnamespace eigen_internal {\r\n\r\n\r\n// 1) Output: AngleAxis\r\n\r\ntemplate<typename T, typename TReturn = T>\r\nstatic Eigen::AngleAxis<TReturn> getAngleAxisFromQuaternion(const Eigen::Quaternion<T>& p_BI)\r\n{\r\n  // Bad precision!\r\n  return Eigen::AngleAxis<TReturn>(p_BI.template cast<TReturn>());\r\n}\r\n\r\ntemplate<typename T, typename TReturn = T>\r\nstatic Eigen::AngleAxis<TReturn> getAngleAxisFromTransformationMatrix(const Eigen::Matrix<T,3,3>& A_IB)\r\n{\r\n  // Bad precision!\r\n  return Eigen::AngleAxis<TReturn>(A_IB.template cast<TReturn>());\r\n}\r\n\r\ntemplate<typename T, typename TReturn = T>\r\nstatic Eigen::AngleAxis<TReturn> getAngleAxisFromRotationMatrix(const Eigen::Matrix<T,3,3>& R_BI)\r\n{\r\n  // Bad precision!\r\n  return Eigen::AngleAxis<TReturn>(R_BI.template cast<TReturn>());\r\n}\r\n\r\n//template<typename T, typename TReturn = T>\r\n//static Eigen::Matrix<TReturn,3,1> getRotationVectorFromRotationMatrix(const Eigen::Matrix<T,3,3>& R_BI)\r\n//{\r\n//  const Eigen::Matrix<TReturn,3,3> rotationMatrix = R_BI.template cast<TReturn>();\r\n//\r\n//  // Bad precision!\r\n//  return Eigen::Matrix<TReturn, 3, 1>();\r\n//}\r\n\r\ntemplate<typename T, typename TReturn = T>\r\nstatic Eigen::AngleAxis<TReturn> getAngleAxisFromRpy(const Eigen::Matrix<T,3,1>& rpy_BI)\r\n{\r\n  // Bad precision!\r\n  return Eigen::AngleAxis<TReturn>(\r\n    Eigen::AngleAxis<TReturn>((TReturn)rpy_BI(0), Eigen::Matrix<TReturn, 3, 1>::UnitX()) *\r\n    Eigen::AngleAxis<TReturn>((TReturn)rpy_BI(1), Eigen::Matrix<TReturn, 3, 1>::UnitY()) *\r\n    Eigen::AngleAxis<TReturn>((TReturn)rpy_BI(2), Eigen::Matrix<TReturn, 3, 1>::UnitZ()));\r\n}\r\n\r\ntemplate<typename T, typename TReturn = T>\r\nstatic Eigen::AngleAxis<TReturn> getAngleAxisFromYpr(const Eigen::Matrix<T,3,1>& ypr_BI)\r\n{\r\n  // Bad precision!\r\n  return Eigen::AngleAxis<TReturn>(\r\n    Eigen::AngleAxis<TReturn>((TReturn)ypr_BI(0), Eigen::Matrix<TReturn, 3, 1>::UnitZ()) *\r\n    Eigen::AngleAxis<TReturn>((TReturn)ypr_BI(1), Eigen::Matrix<TReturn, 3, 1>::UnitY()) *\r\n    Eigen::AngleAxis<TReturn>((TReturn)ypr_BI(2), Eigen::Matrix<TReturn, 3, 1>::UnitX()));\r\n}\r\n\r\n\r\n// 2) Output: Quaternion\r\n\r\ntemplate<typename T, typename TReturn = T>\r\nstatic Eigen::Quaternion<TReturn> getQuaternionFromAngleAxis(const Eigen::AngleAxis<T>& aa_BI)\r\n{\r\n  return Eigen::Quaternion<TReturn>(aa_BI.template cast<TReturn>());\r\n}\r\n\r\ntemplate<typename T, typename TReturn = T>\r\nstatic Eigen::Quaternion<TReturn> getQuaternionFromTransformationMatrix(const Eigen::Matrix<T,3,3>& A_IB)\r\n{\r\n//  // Untested\r\n//  // Bad precision!\r\n//  double w;\r\n//  double x;\r\n//  double y;\r\n//  double z;\r\n//  w = sqrt(1+mat(0,0)+mat(1,1)+mat(2,2))/2;\r\n//  if(w>0.02){\r\n//    x = 1/4/w*(mat(2,1)-mat(1,2));\r\n//    y = 1/4/w*(mat(0,2)-mat(2,0));\r\n//    z = 1/4/w*(mat(1,0)-mat(0,1));\r\n//  } else {\r\n//    x = sqrt(1+mat(0,0)-mat(1,1)-mat(2,2))/2;\r\n//    y = 1/4/x*(mat(0,1)+mat(1,0));\r\n//    z = 1/4/x*(mat(0,2)+mat(2,0));\r\n//    w = 1/4/x*(mat(2,1)-mat(1,2));\r\n//  }\r\n//  q.w() = w;\r\n//  q.x() = x;\r\n//  q.y() = y;\r\n//  q.z() = z;\r\n//  q.normalize();\r\n\r\n  return Eigen::Quaternion<TReturn>(A_IB.template cast<TReturn>());\r\n}\r\n\r\ntemplate<typename T, typename TReturn = T>\r\nstatic Eigen::Quaternion<TReturn> getQuaternionFromRotationMatrix(const Eigen::Matrix<T,3,3>& R_BI)\r\n{\r\n//  // Untested\r\n//  // Bad precision!\r\n//  double w;\r\n//  double x;\r\n//  double y;\r\n//  double z;\r\n//  w = sqrt(1+mat(0,0)+mat(1,1)+mat(2,2))/2;\r\n//  if(w>0.02){\r\n//    x = 1/4/w*(mat(2,1)-mat(1,2));\r\n//    y = 1/4/w*(mat(0,2)-mat(2,0));\r\n//    z = 1/4/w*(mat(1,0)-mat(0,1));\r\n//  } else {\r\n//    x = sqrt(1+mat(0,0)-mat(1,1)-mat(2,2))/2;\r\n//    y = 1/4/x*(mat(0,1)+mat(1,0));\r\n//    z = 1/4/x*(mat(0,2)+mat(2,0));\r\n//    w = 1/4/x*(mat(2,1)-mat(1,2));\r\n//  }\r\n//  q.w() = w;\r\n//  q.x() = x;\r\n//  q.y() = y;\r\n//  q.z() = z;\r\n//  q.normalize();\r\n\r\n  return Eigen::Quaternion<TReturn>(R_BI.template cast<TReturn>());\r\n}\r\n\r\ntemplate<typename T, typename TReturn = T>\r\nstatic Eigen::Quaternion<TReturn> getQuaternionFromRpy(const Eigen::Matrix<T,3,1>& rpy_BI)\r\n{\r\n//  // Tested and Working\r\n//  Eigen::Quaternion<T> p_BI;\r\n//\r\n//  const T sr = sin(rpy_BI(0)/2);\r\n//  const T cr = cos(rpy_BI(0)/2);\r\n//  const T sp = sin(rpy_BI(1)/2);\r\n//  const T cp = cos(rpy_BI(1)/2);\r\n//  const T sy = sin(rpy_BI(2)/2);\r\n//  const T cy = cos(rpy_BI(2)/2);\r\n//\r\n//  const T srsp = sr*sp;\r\n//  const T srcp = sr*cp;\r\n//  const T crsp = cr*sp;\r\n//  const T crcp = cr*cp;\r\n//\r\n//  p_BI.w() = -srsp*sy+crcp*cy;\r\n//  p_BI.x() = crsp*sy+srcp*cy;\r\n//  p_BI.y() = crsp*cy-srcp*sy;\r\n//  p_BI.z() = srsp*cy+crcp*sy;\r\n////  p_BI.normalize();\r\n//\r\n//  return p_BI;\r\n\r\n  return Eigen::Quaternion<TReturn>(\r\n    Eigen::AngleAxis<TReturn>((TReturn)rpy_BI(0), Eigen::Matrix<TReturn, 3, 1>::UnitX()) *\r\n    Eigen::AngleAxis<TReturn>((TReturn)rpy_BI(1), Eigen::Matrix<TReturn, 3, 1>::UnitY()) *\r\n    Eigen::AngleAxis<TReturn>((TReturn)rpy_BI(2), Eigen::Matrix<TReturn, 3, 1>::UnitZ()));\r\n}\r\n\r\ntemplate<typename T, typename TReturn = T>\r\nstatic Eigen::Quaternion<TReturn> getQuaternionFromYpr(const Eigen::Matrix<T,3,1>& ypr_BI)\r\n{\r\n//  // Tested and Working\r\n//  Eigen::Quaternion<T> p_BI;\r\n//\r\n//  const T sy = sin(ypr_BI(0)/2);\r\n//  const T cy = cos(ypr_BI(0)/2);\r\n//  const T sp = sin(ypr_BI(1)/2);\r\n//  const T cp = cos(ypr_BI(1)/2);\r\n//  const T sr = sin(ypr_BI(2)/2);\r\n//  const T cr = cos(ypr_BI(2)/2);\r\n//\r\n//  const T sysp = sy*sp;\r\n//  const T sycp = sy*cp;\r\n//  const T cysp = cy*sp;\r\n//  const T cycp = cy*cp;\r\n//\r\n//  p_BI.w() = sysp*sr+cycp*cr;\r\n//  p_BI.x() = -sysp*cr+cycp*sr;\r\n//  p_BI.y() = sycp*sr+cysp*cr;\r\n//  p_BI.z() = sycp*cr-cysp*sr;\r\n////  p_BI.normalize();\r\n//\r\n//  return p_BI;\r\n\r\n  return Eigen::Quaternion<TReturn>(\r\n    Eigen::AngleAxis<TReturn>((TReturn)ypr_BI(0), Eigen::Matrix<TReturn, 3, 1>::UnitZ()) *\r\n    Eigen::AngleAxis<TReturn>((TReturn)ypr_BI(1), Eigen::Matrix<TReturn, 3, 1>::UnitY()) *\r\n    Eigen::AngleAxis<TReturn>((TReturn)ypr_BI(2), Eigen::Matrix<TReturn, 3, 1>::UnitX()));\r\n}\r\n\r\n\r\n// 3) Output: Transformation Matrix\r\n\r\ntemplate<typename T, typename TReturn = T>\r\nstatic Eigen::Matrix<TReturn,3,3> getTransformationMatrixFromAngleAxis(const Eigen::AngleAxis<T>& aa_BI)\r\n{\r\n  return (aa_BI.template cast<TReturn>()).toRotationMatrix(); // A_IB\r\n}\r\n\r\ntemplate<typename T, typename TReturn = T>\r\nstatic Eigen::Matrix<TReturn,3,3> getTransformationMatrixFromQuaternion(const Eigen::Quaternion<T>& p_BI)\r\n{\r\n  return (p_BI.template cast<TReturn>()).toRotationMatrix(); // A_IB\r\n}\r\n\r\ntemplate<typename T, typename TReturn = T>\r\nstatic Eigen::Matrix<TReturn,3,3> getTransformationMatrixFromRotationMatrix(const Eigen::Matrix<T,3,3>& R_BI)\r\n{\r\n  return R_BI.template cast<TReturn>(); // A_IB\r\n}\r\n\r\ntemplate<typename T, typename TReturn = T>\r\nstatic Eigen::Matrix<TReturn,3,3> getTransformationMatrixFromRpy(const Eigen::Matrix<T,3,1>& rpy_BI)\r\n{\r\n  Eigen::Matrix<TReturn,3,3> A_IB;\r\n\r\n  const TReturn sr = sin(rpy_BI(0));\r\n  const TReturn cr = cos(rpy_BI(0));\r\n  const TReturn sp = sin(rpy_BI(1));\r\n  const TReturn cp = cos(rpy_BI(1));\r\n  const TReturn sy = sin(rpy_BI(2));\r\n  const TReturn cy = cos(rpy_BI(2));\r\n\r\n  const TReturn srsy = sr*sy;\r\n  const TReturn srcy = sr*cy;\r\n  const TReturn crsy = cr*sy;\r\n  const TReturn crcy = cr*cy;\r\n\r\n  A_IB(0,0) = cp*cy;\r\n  A_IB(0,1) = -cp*sy;\r\n  A_IB(0,2) = sp;\r\n  A_IB(1,0) = crsy+srcy*sp;\r\n  A_IB(1,1) = crcy-srsy*sp;\r\n  A_IB(1,2) = -sr*cp;\r\n  A_IB(2,0) = srsy-crcy*sp;\r\n  A_IB(2,1) = srcy+crsy*sp;\r\n  A_IB(2,2) = cr*cp;\r\n\r\n  return A_IB;\r\n}\r\n\r\ntemplate<typename T, typename TReturn = T>\r\nstatic Eigen::Matrix<TReturn,3,3> getTransformationMatrixFromYpr(const Eigen::Matrix<T,3,1>& ypr_BI)\r\n{\r\n  Eigen::Matrix<TReturn,3,3> A_IB;\r\n\r\n  const TReturn sy = sin(ypr_BI(0));\r\n  const TReturn cy = cos(ypr_BI(0));\r\n  const TReturn sp = sin(ypr_BI(1));\r\n  const TReturn cp = cos(ypr_BI(1));\r\n  const TReturn sr = sin(ypr_BI(2));\r\n  const TReturn cr = cos(ypr_BI(2));\r\n\r\n  const TReturn sysr = sy*sr;\r\n  const TReturn sycr = sy*cr;\r\n  const TReturn cysr = cy*sr;\r\n  const TReturn cycr = cy*cr;\r\n\r\n  A_IB(0,0) = cy*cp;\r\n  A_IB(0,1) = cysr*sp-sycr;\r\n  A_IB(0,2) = sysr+cycr*sp;\r\n  A_IB(1,0) = cp*sy;\r\n  A_IB(1,1) = sysr*sp+cycr;\r\n  A_IB(1,2) = sycr*sp-cysr;\r\n  A_IB(2,0) = -sp;\r\n  A_IB(2,1) = cp*sr;\r\n  A_IB(2,2) = cp*cr;\r\n\r\n  return A_IB;\r\n}\r\n\r\n\r\n// 4) Output: Rotation Matrix\r\n\r\ntemplate<typename T, typename TReturn = T>\r\nstatic Eigen::Matrix<TReturn,3,3> getRotationMatrixFromAngleAxis(const Eigen::AngleAxis<T>& aa_BI)\r\n{\r\n  return (aa_BI.template cast<TReturn>()).toRotationMatrix();\r\n}\r\n\r\ntemplate<typename T, typename TReturn = T>\r\nstatic Eigen::Matrix<TReturn,3,3> getRotationMatrixFromQuaternion(const Eigen::Quaternion<T>& p_BI)\r\n{\r\n  return (p_BI.template cast<TReturn>()).toRotationMatrix();\r\n}\r\n\r\ntemplate<typename T, typename TReturn = T>\r\nstatic Eigen::Matrix<TReturn,3,3> getRotationMatrixFromTransformationMatrix(const Eigen::Matrix<T,3,3>& A_IB)\r\n{\r\n  return A_IB.template cast<TReturn>(); // R_BI\r\n}\r\n\r\ntemplate<typename T, typename TReturn = T>\r\nstatic Eigen::Matrix<TReturn,3,3> getRotationMatrixFromRpy(const Eigen::Matrix<T,3,1>& rpy_BI)\r\n{\r\n  Eigen::Matrix<TReturn,3,3> R_BI;\r\n\r\n  const TReturn sr = sin(rpy_BI(0));\r\n  const TReturn cr = cos(rpy_BI(0));\r\n  const TReturn sp = sin(rpy_BI(1));\r\n  const TReturn cp = cos(rpy_BI(1));\r\n  const TReturn sy = sin(rpy_BI(2));\r\n  const TReturn cy = cos(rpy_BI(2));\r\n\r\n  const TReturn srsy = sr*sy;\r\n  const TReturn srcy = sr*cy;\r\n  const TReturn crsy = cr*sy;\r\n  const TReturn crcy = cr*cy;\r\n\r\n  R_BI(0,0) = cp*cy;\r\n  R_BI(0,1) = -cp*sy;\r\n  R_BI(0,2) = sp;\r\n  R_BI(1,0) = crsy+srcy*sp;\r\n  R_BI(1,1) = crcy-srsy*sp;\r\n  R_BI(1,2) = -sr*cp;\r\n  R_BI(2,0) = srsy-crcy*sp;\r\n  R_BI(2,1) = srcy+crsy*sp;\r\n  R_BI(2,2) = cr*cp;\r\n\r\n  return R_BI;\r\n}\r\n\r\ntemplate<typename T, typename TReturn = T>\r\nstatic Eigen::Matrix<TReturn,3,3> getRotationMatrixFromYpr(const Eigen::Matrix<T,3,1>& ypr_BI)\r\n{\r\n  Eigen::Matrix<TReturn,3,3> R_BI;\r\n\r\n  const TReturn sy = sin(ypr_BI(0));\r\n  const TReturn cy = cos(ypr_BI(0));\r\n  const TReturn sp = sin(ypr_BI(1));\r\n  const TReturn cp = cos(ypr_BI(1));\r\n  const TReturn sr = sin(ypr_BI(2));\r\n  const TReturn cr = cos(ypr_BI(2));\r\n\r\n  const TReturn sysr = sy*sr;\r\n  const TReturn sycr = sy*cr;\r\n  const TReturn cysr = cy*sr;\r\n  const TReturn cycr = cy*cr;\r\n\r\n  R_BI(0,0) = cy*cp;\r\n  R_BI(0,1) = cysr*sp-sycr;\r\n  R_BI(0,2) = sysr+cycr*sp;\r\n  R_BI(1,0) = cp*sy;\r\n  R_BI(1,1) = sysr*sp+cycr;\r\n  R_BI(1,2) = sycr*sp-cysr;\r\n  R_BI(2,0) = -sp;\r\n  R_BI(2,1) = cp*sr;\r\n  R_BI(2,2) = cp*cr;\r\n\r\n  return R_BI;\r\n}\r\n\r\n\r\n// 5) Output: Roll-Pitch-Yaw\r\n\r\ntemplate<typename T, typename TReturn = T>\r\nstatic Eigen::Matrix<TReturn,3,1> getRpyFromAngleAxis(const Eigen::AngleAxis<T>& aa_BI)\r\n{\r\n  return (aa_BI.toRotationMatrix().eulerAngles(0, 1, 2)).template cast<TReturn>();\r\n}\r\n\r\ntemplate<typename T, typename TReturn = T>\r\nstatic Eigen::Matrix<TReturn,3,1> getRpyFromQuaternion(const Eigen::Quaternion<T>& p_BI)\r\n{\r\n//  Eigen::Matrix<T,3,1> rpy_BI;\r\n//\r\n//  const T w = p_BI.w();\r\n//  const T x = p_BI.x();\r\n//  const T y = p_BI.y();\r\n//  const T z = p_BI.z();\r\n//\r\n////  rpy_BI(1) = -asin(2*(x*z-w*y));\r\n////\r\n//////  std::cout << 2*(x*z-w*y)+1 << std::endl;\r\n////\r\n////  if(cos(rpy_BI(1)) == 0) // roll and yaw axis are the same -> yaw angle can be set to zero, roll does the whole rotation\r\n////  {\r\n////    rpy_BI(0) = -asin(2*(y*z-w*x));\r\n////    rpy_BI(2) = 0;\r\n////  }\r\n////  else\r\n////  {\r\n////    rpy_BI(0) = atan2(2*(y*z+w*x),1-2*(x*x+y*y));\r\n////    rpy_BI(2) = atan2(2*(x*y+w*z),1-2*(y*y+z*z));\r\n////  }\r\n//\r\n//\r\n//  // NEW\r\n//\r\n////  const T rpy_BI(1) = atan2(-2*(x*z-w*y),sqrt((1-2*(y*y+z*z))*(1-2*(y*y+z*z))+4*(x*y+w*z)*(x*y+w*z)));\r\n//  const T test = 2*(x*z-w*y);\r\n//\r\n//  if(test > 0.999999999) // roll and yaw axis are the same -> yaw angle can be set to zero, roll does the whole rotation\r\n//  {\r\n////    rpy_BI(0) = -asin(2*(y*z-w*x));\r\n////    rpy_BI(0) = acos(1-2*(x*x+z*z));\r\n////    rpy_BI(0) = atan2(2*(y*z-w*x),1-2*(x*x+z*z));\r\n//    rpy_BI(0) = 2*atan2(x,w);\r\n//    rpy_BI(1) = -M_PI/2; // if test is a slight bit larger than 1, asin(test) does not work anymore\r\n//    rpy_BI(2) = 0;\r\n//  }\r\n//  else if(test < -0.999999999)\r\n//  {\r\n////    rpy_BI(0) = -asin(2*(y*z-w*x));\r\n////    rpy_BI(0) = acos(1-2*(x*x+z*z));\r\n////    rpy_BI(0) = atan2(2*(y*z-w*x),1-2*(x*x+z*z));\r\n//    rpy_BI(0) = -2*atan2(x,w);\r\n//    rpy_BI(1) = M_PI/2;\r\n//    rpy_BI(2) = 0;\r\n//  }\r\n//  else\r\n//  {\r\n//    rpy_BI(0) = atan2(2*(y*z+w*x),1-2*(x*x+y*y));\r\n//    rpy_BI(1) = -asin(test);\r\n//    rpy_BI(2) = atan2(2*(x*y+w*z),1-2*(y*y+z*z));\r\n//  }\r\n//\r\n//  return rpy_BI;\r\n\r\n  return (p_BI.toRotationMatrix().eulerAngles(0, 1, 2)).template cast<TReturn>();\r\n}\r\n\r\ntemplate<typename T, typename TReturn = T>\r\nstatic Eigen::Matrix<TReturn,3,1> getRpyFromTransformationMatrix(const Eigen::Matrix<T,3,3>& A_IB)\r\n{\r\n  return (A_IB.eulerAngles(0, 1, 2)).template cast<TReturn>(); // rpy_BI\r\n}\r\n\r\ntemplate<typename T, typename TReturn = T>\r\nstatic Eigen::Matrix<TReturn,3,1> getRpyFromRotationMatrix(const Eigen::Matrix<T,3,3>& R_BI)\r\n{\r\n  return (R_BI.eulerAngles(0, 1, 2)).template cast<TReturn>(); // rpy_BI\r\n}\r\n\r\ntemplate<typename T, typename TReturn = T>\r\nstatic Eigen::Matrix<TReturn,3,1> getRpyFromYpr(const Eigen::Matrix<T,3,1>& ypr_BI)\r\n{\r\n  return getRpyFromQuaternion(getQuaternionFromYpr(ypr_BI)).template cast<TReturn>();\r\n//  return getRpyFromQuaternion(getQuaternionFromYpr(ypr_BI.template cast<TReturn>()));\r\n}\r\n\r\n\r\n// 6) Output: Yaw-Pitch-Roll\r\n\r\ntemplate<typename T, typename TReturn = T>\r\nstatic Eigen::Matrix<TReturn,3,1> getYprFromAngleAxis(const Eigen::AngleAxis<T>& aa_BI)\r\n{\r\n  return (aa_BI.toRotationMatrix().eulerAngles(2, 1, 0)).template cast<TReturn>();\r\n}\r\n\r\ntemplate<typename T, typename TReturn = T>\r\nstatic Eigen::Matrix<TReturn,3,1> getYprFromQuaternion(const Eigen::Quaternion<T>& p_BI)\r\n{\r\n//  Eigen::Matrix<T,3,1> ypr_BI;\r\n//\r\n//  const T w = p_BI.w();\r\n//  const T x = p_BI.x();\r\n//  const T y = p_BI.y();\r\n//  const T z = p_BI.z();\r\n//\r\n////  ypr_BI(1) = asin(2*(x*z+w*y));\r\n////\r\n////  if(cos(ypr_BI(1)) == 0) // yaw and roll axis are the same -> roll angle can be set to zero, yaw does the whole rotation\r\n////  {\r\n////    ypr_BI(0) = asin(2*(y*z+w*x));\r\n////    ypr_BI(2) = 0;\r\n////  }\r\n////  else\r\n////  {\r\n////    ypr_BI(0) = -atan2(2*(x*y-w*z),1-2*(y*y+z*z));\r\n////    ypr_BI(2) = -atan2(2*(y*z-w*x),1-2*(x*x+y*y));\r\n////  }\r\n//\r\n//\r\n//  // NEW\r\n//\r\n////  const T rpy_BI(1) = atan2(-2*(x*z-w*y),sqrt((1-2*(y*y+z*z))*(1-2*(y*y+z*z))+4*(x*y+w*z)*(x*y+w*z)));\r\n//  const T test = 2*(x*z+w*y);\r\n//\r\n//  if(test > 0.999999999) // roll and yaw axis are the same -> yaw angle can be set to zero, roll does the whole rotation\r\n//  {\r\n////    ypr_BI(0) = asin(2*(y*z+w*x));\r\n//    ypr_BI(0) = 2*atan2(x,w);\r\n//    ypr_BI(1) = M_PI/2; // if test is a slight bit larger than 1, asin(test) does not work anymore\r\n//    ypr_BI(2) = 0;\r\n//  }\r\n//  else if(test < -0.999999999)\r\n//  {\r\n////    ypr_BI(0) = -asin(2*(y*z+w*x));\r\n//    ypr_BI(0) = -2*atan2(x,w);\r\n//    ypr_BI(1) = -M_PI/2;\r\n//    ypr_BI(2) = 0;\r\n//  }\r\n//  else\r\n//  {\r\n//    ypr_BI(0) = -atan2(2*(x*y-w*z),1-2*(y*y+z*z));\r\n//    ypr_BI(1) = asin(test);\r\n//    ypr_BI(2) = -atan2(2*(y*z-w*x),1-2*(x*x+y*y));\r\n//  }\r\n//\r\n//  return ypr_BI;\r\n\r\n//  const TReturn q0 = p_BI.w();\r\n//  const TReturn q1 = p_BI.x();\r\n//  const TReturn q2 = p_BI.y();\r\n//  const TReturn q3 = p_BI.z();\r\n//  return Eigen::Matrix<TReturn,3,1>(atan2(2.0*q1*q2 + 2.0*q0*q3, q1*q1 + q0*q0 - q3*q3 - q2*q2),\r\n//                                    -asin(2.0*q1*q3 - 2.0*q0*q2),\r\n//                                    atan2(2.0*q2*q3 + 2.0*q0*q1, q3*q3 - q2*q2 - q1*q1 + q0*q0));\r\n\r\n  return (p_BI.toRotationMatrix().eulerAngles(2, 1, 0)).template cast<TReturn>();\r\n}\r\n\r\ntemplate<typename T, typename TReturn = T>\r\nstatic Eigen::Matrix<TReturn,3,1> getYprFromTransformationMatrix(const Eigen::Matrix<T,3,3>& A_IB)\r\n{\r\n  return (A_IB.eulerAngles(2, 1, 0)).template cast<TReturn>(); // ypr_BI\r\n}\r\n\r\ntemplate<typename T, typename TReturn = T>\r\nstatic Eigen::Matrix<TReturn,3,1> getYprFromRotationMatrix(const Eigen::Matrix<T,3,3>& R_BI)\r\n{\r\n  const TReturn r23 = R_BI(1,2);\r\n  const TReturn r33 = R_BI(2,2);\r\n  const TReturn r13 = R_BI(0,2);\r\n  const TReturn r12 = R_BI(0,1);\r\n  const TReturn r11 = R_BI(0,0);\r\n\r\n  return Eigen::Matrix<TReturn,3,1>(atan2(r12,r11), -asin(r13), atan2(r23,r33));\r\n//  return (R_BI.eulerAngles(2, 1, 0)).template cast<TReturn>(); // original\r\n}\r\n\r\ntemplate<typename T, typename TReturn = T>\r\nstatic Eigen::Matrix<TReturn,3,1> getYprFromRpy(const Eigen::Matrix<T,3,1>& rpy_BI)\r\n{\r\n  return getYprFromQuaternion(getQuaternionFromRpy(rpy_BI)).template cast<TReturn>();\r\n//  return getYprFromQuaternion(getQuaternionFromRpy(rpy_BI.template cast<TReturn>()));\r\n}\r\n\r\n\r\n// TODO inverse will be deleted in future\r\n\r\n// 7) Output: Inverses\r\n\r\n//template<typename T, typename TReturn = T>\r\n//static Eigen::AngleAxis<TReturn> getInverseAngleAxis(const Eigen::AngleAxis<T>& aa_BI)\r\n//{\r\n//  return (aa_BI.template cast<TReturn>()).inverse();\r\n//}\r\n//\r\ntemplate<typename T, typename TReturn = T>\r\nstatic Eigen::Quaternion<TReturn> getInverseQuaternion(const Eigen::Quaternion<T>& p_BI)\r\n{\r\n  return (p_BI.conjugate()).template cast<TReturn>();\r\n}\r\n//\r\n//template<typename T, typename TReturn = T>\r\n//static Eigen::Matrix<TReturn,3,3> getInverseTransformationMatrix(const Eigen::Matrix<T,3,3>& A_IB)\r\n//{\r\n//  return (A_IB.template cast<TReturn>()).transpose();\r\n//}\r\n//\r\n//template<typename T, typename TReturn = T>\r\n//static Eigen::Matrix<TReturn,3,3> getInverseRotationMatrix(const Eigen::Matrix<T,3,3>& R_BI)\r\n//{\r\n//  return (R_BI.template cast<TReturn>()).transpose();\r\n//}\r\n\r\ntemplate<typename T, typename TReturn = T>\r\nstatic Eigen::Matrix<TReturn,3,1> getInverseRpy(const Eigen::Matrix<T,3,1>& rpy_BI)\r\n{\r\n  return getRpyFromQuaternion(getInverseQuaternion(getQuaternionFromRpy(rpy_BI.template cast<TReturn>())));\r\n}\r\n\r\ntemplate<typename T, typename TReturn = T>\r\nstatic Eigen::Matrix<TReturn,3,1> getInverseYpr(const Eigen::Matrix<T,3,1>& ypr_BI)\r\n{\r\n  return getYprFromQuaternion(getInverseQuaternion(getQuaternionFromYpr(ypr_BI.template cast<TReturn>())));\r\n}\r\n\r\n\r\n\r\n\r\n/*\r\n\r\n\r\n\r\nMatrix3x4d get_H_bar(const Vector4d &p)\r\n{\r\n  Matrix3x4d H_bar = Matrix3x4d::Zero();\r\n  const double w = p(0);\r\n  const Vector3d e = p.tail(3);\r\n  const Matrix3x3d eye3 = Matrix3x3d::Identity();\r\n\r\n  H_bar.col(0) = -e;\r\n  H_bar.block<3,3>(0,1) = -skewsymm(e)+w*eye3;\r\n\r\n  return H_bar;\r\n}\r\n\r\n\r\nMatrixDyn get_F(const VectorDyn &q)\r\n{\r\n  const double dim_q = q.rows();\r\n  const double dim_u = dim_q - 1;\r\n\r\n  MatrixDyn F = MatrixDyn::Zero(dim_q,dim_u);\r\n  const Vector4d p = q.block<4,1>(3,0);\r\n\r\n  F.block<3,3>(0,0) = Matrix3x3d::Identity();\r\n  F.block<4,3>(3,3) = 0.5*get_H_bar(p).transpose();\r\n  if(dim_u > 6)\r\n  {\r\n    F.block(7,6,dim_u-6,dim_u-6) = MatrixDyn::Identity(dim_u-6,dim_u-6);\r\n  }\r\n\r\n  return F;\r\n}\r\n\r\nVectorDyn get_dqdt(const VectorDyn &q, const VectorDyn &u)\r\n{\r\n  const double dim_q = q.rows();\r\n  const double dim_u = dim_q - 1;\r\n\r\n  VectorDyn dqdt = VectorDyn::Zero(dim_q);\r\n  const Vector4d p = q.block<4,1>(3,0);\r\n\r\n  dqdt.head(3) = u.head(3);\r\n  dqdt.block<4,1>(3,0) = 0.5*get_H_bar(p).transpose()*u.block<3,1>(3,0);\r\n  if(dim_u > 6)\r\n  {\r\n    dqdt.tail(dim_u-6) = u.tail(dim_u-6);\r\n  }\r\n\r\n  return dqdt;\r\n}\r\n\r\nVectorDyn get_dqdt_2(const VectorDyn &q, const VectorDyn &u) // older version, slower\r\n{\r\n  return get_F(q)*u;\r\n}\r\n\r\nvoid prox1D(double &y, const double &x, const double &min, const double &max)\r\n{\r\n  if     (x < min) {y = min;}\r\n  else if(x > max) {y = max;}\r\n  else             {y = x;  }\r\n}\r\n\r\nvoid prox2D(double &y1, double &y2, const double &x1, const double &x2, const double &max)\r\n{\r\n  const double r = sqrt(x1*x1 + x2*x2);\r\n  if(r > max)\r\n  {\r\n    y1 = max*x1/r;\r\n    y2 = max*x2/r;\r\n  }\r\n  else\r\n  {\r\n    y1 = x1;\r\n    y2 = x2;\r\n  }\r\n}\r\n\r\n*/\r\n\r\n/*\r\n\r\n\r\nVector4d multiplyQuaternion(const Vector4d &p_CB, const Vector4d &p_BA) // same in eigen\r\n{\r\n  // p_CA = p_CB*p_BA\r\n  Vector4d p_CA = Vector4d::Zero();\r\n\r\n  p_CA(0) = p_CB(0)*p_BA(0) - p_CB.tail(3).transpose()*p_BA.tail(3);\r\n  p_CA.tail(3) = p_CB(0)*p_BA.tail(3) + p_BA(0)*p_CB.tail(3) + skewsymm(p_BA.tail(3))*p_CB.tail(3);\r\n\r\n  p_CA.normalize();\r\n\r\n  return p_CA;\r\n}\r\n\r\n\r\n\r\n\r\ndouble w_to_angleVel(const Vector3d &K_w_JK, const Vector3d &n)\r\n{\r\n//  if(n(0) == 1) // around x\r\n//  {\r\n//    return K_w_JK(0);\r\n//  }\r\n//  else\r\n//  if(n(1) == 1) // around y\r\n//  {\r\n//    return K_w_JK(1);\r\n//  }\r\n//  else\r\n//  if(n(2) == 1) // around z\r\n//  {\r\n//    return K_w_JK(2);\r\n//  }\r\n\r\n  const Vector3d n_norm = n.normalized();\r\n\r\n  return n_norm.dot(K_w_JK); // attention: dot product doesn't eliminate small errors\r\n}\r\n\r\n\r\n\r\n\r\nVector3d omega2kardan(const Vector3d &K_w_IK, const Vector3d &abc) // quaternion: rotation from I to K, kardan: x-y-z with alpha-beta-gamma\r\n{\r\n  double alpha = abc(0);\r\n  double beta = abc(1);\r\n  double gamma = abc(2);\r\n\r\n  Vector3d dadbdc = Vector3d::Zero();\r\n  Matrix3x3d H = Matrix3x3d::Zero();\r\n\r\n  if(cos(beta) == 0)\r\n  {\r\n    H << std::numeric_limits<double>::max(), std::numeric_limits<double>::max(), 0, sin(gamma), cos(gamma), 0, -cos(gamma)*tan(beta), sin(gamma)*tan(beta), 1;\r\n  }\r\n  else\r\n  {\r\n    H << cos(gamma)/cos(beta), -sin(gamma)/cos(beta), 0, sin(gamma), cos(gamma), 0, -cos(gamma)*tan(beta), sin(gamma)*tan(beta), 1;\r\n  }\r\n\r\n  dadbdc = H*K_w_IK;\r\n\r\n  return dadbdc;\r\n\r\n  */\r\n\r\n\r\n\r\n\r\n} // namespace eigen_internal\r\n} // namespace eigen_impl\r\n} // namespace rotations\r\n} // namespace rm\r\n\r\n#endif /* KINDR_ROTATIONS_ROTATION_EIGEN_FUNCTIONS_HPP_ */\r\n", "meta": {"hexsha": "2634730c52b7c55bd183c704e0f02512c6924131", "size": 23491, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "IHMCPerception/third-party/kindr/include/kindr/rotations/eigen/RotationEigenFunctions.hpp", "max_stars_repo_name": "wxmerkt/ihmc-open-robotics-software", "max_stars_repo_head_hexsha": "2c47c9a9bd999e7811038e99c3888683f9973a2a", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 170.0, "max_stars_repo_stars_event_min_datetime": "2016-02-01T18:58:50.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-17T05:28:01.000Z", "max_issues_repo_path": "IHMCPerception/third-party/kindr/include/kindr/rotations/eigen/RotationEigenFunctions.hpp", "max_issues_repo_name": "wxmerkt/ihmc-open-robotics-software", "max_issues_repo_head_hexsha": "2c47c9a9bd999e7811038e99c3888683f9973a2a", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 162.0, "max_issues_repo_issues_event_min_datetime": "2016-01-29T17:04:29.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-10T16:25:37.000Z", "max_forks_repo_path": "IHMCPerception/third-party/kindr/include/kindr/rotations/eigen/RotationEigenFunctions.hpp", "max_forks_repo_name": "wxmerkt/ihmc-open-robotics-software", "max_forks_repo_head_hexsha": "2c47c9a9bd999e7811038e99c3888683f9973a2a", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 83.0, "max_forks_repo_forks_event_min_datetime": "2016-01-28T22:49:01.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T03:11:24.000Z", "avg_line_length": 30.0781049936, "max_line_length": 159, "alphanum_fraction": 0.6201098293, "num_tokens": 8232, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5583269943353745, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.3245572073973032}}
{"text": "// Copyright Yamaha 2021\n// MIT License\n// https://github.com/yamaha-bps/cbr_control/blob/master/LICENSE\n\n#ifndef CBR_CONTROL__FIRST_ORDER_FILTER_HPP_\n#define CBR_CONTROL__FIRST_ORDER_FILTER_HPP_\n\n#include <Eigen/Core>\n\n#include <cbr_utils/cyber_timer.hpp>\n\n#include <cmath>\n#include <memory>\n#include <type_traits>\n#include <utility>\n\n\nnamespace cbr\n{\n\nnamespace fof_details\n{\n\ntemplate<typename T>\nstruct zero_value\n{\n  static T value()\n  {\n    if constexpr (std::is_base_of_v<Eigen::MatrixBase<T>, T>) {\n      return T::Zero();\n    } else {\n      return T{0};\n    }\n  }\n};\n\n}  // namespace fof_details\n\ntemplate<typename T, typename _clock_t = std::chrono::high_resolution_clock>\nclass FirstOrderFilter\n{\npublic:\n  using clock_t = _clock_t;\n  using timer_t = CyberTimerNoAvg<std::ratio<1>, double, clock_t>;\n\n  FirstOrderFilter() = default;\n  FirstOrderFilter(const FirstOrderFilter &) = default;\n  FirstOrderFilter(FirstOrderFilter &) = default;\n  FirstOrderFilter(FirstOrderFilter &&) = default;\n  FirstOrderFilter & operator=(const FirstOrderFilter &) = default;\n  FirstOrderFilter & operator=(FirstOrderFilter &) = default;\n  FirstOrderFilter & operator=(FirstOrderFilter &&) = default;\n  ~FirstOrderFilter() = default;\n\n  template<typename T1>\n  explicit FirstOrderFilter(T1 && clock, const double tau = 1.)\n  : timer_(std::forward<T1>(clock)),\n    tau_(tau)\n  {}\n\n  explicit FirstOrderFilter(const double tau)\n  : tau_(tau)\n  {}\n\n\n  template<typename T1>\n  void set_clock(T1 && clock)\n  {\n    timer_.set_clock(std::forward<T1>(clock));\n  }\n\n  void set_params(const double tau)\n  {\n    tau_ = tau;\n  }\n\n  double get_params() const\n  {\n    return tau_;\n  }\n\n  const T & update(const T & val, const typename timer_t::time_point tNow)\n  {\n    if (tau_ <= 0.0) {\n      return valNm1_ = val;\n    }\n\n    if (init_) {\n      const double dt = timer_.toctic(tNow);\n      const double e = std::exp(-dt / tau_);\n      return valNm1_ = valNm1_ * e + (1 - e) * val;\n    }\n\n    init_ = true;\n    timer_.tic(tNow);\n    return valNm1_ = val;\n  }\n\n  const T & update(const T & val)\n  {\n    return update(val, timer_.now());\n  }\n  const T & operator()(const T & val)\n  {\n    return update(val);\n  }\n\n  const T & getValue() const\n  {\n    return valNm1_;\n  }\n\n  void reset()\n  {\n    init_ = false;\n  }\n\n  const T & reset(const T & val, const typename timer_t::time_point tNow)\n  {\n    timer_.tic(tNow);\n    init_ = true;\n    return valNm1_ = val;\n  }\n\n  const T & reset(const T & val)\n  {\n    return reset(val, timer_.now());\n  }\n\nprotected:\n  timer_t timer_ = timer_t(clock_t{});\n  double tau_{1.0};\n  T valNm1_{fof_details::zero_value<T>::value()};\n  bool init_{false};\n};\n\n}  // namespace cbr\n\n#endif  // CBR_CONTROL__FIRST_ORDER_FILTER_HPP_\n", "meta": {"hexsha": "c8c9f6bdb7d6c2eb131ad5e8ce29ddfe0674f504", "size": 2733, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/cbr_control/first_order_filter.hpp", "max_stars_repo_name": "yamaha-bps/cbr_control", "max_stars_repo_head_hexsha": "c2faf79673d46c950dd7590f1072fc7decafad06", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/cbr_control/first_order_filter.hpp", "max_issues_repo_name": "yamaha-bps/cbr_control", "max_issues_repo_head_hexsha": "c2faf79673d46c950dd7590f1072fc7decafad06", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/cbr_control/first_order_filter.hpp", "max_forks_repo_name": "yamaha-bps/cbr_control", "max_forks_repo_head_hexsha": "c2faf79673d46c950dd7590f1072fc7decafad06", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.5214285714, "max_line_length": 76, "alphanum_fraction": 0.6586169045, "num_tokens": 764, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5583269943353744, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.3245572073973031}}
{"text": "#pragma once\n\n#if defined(_OPENMP)\n#include <omp.h>\n#endif\n\n#include <cmath>\n#include <functional>\n#include <map>\n#include <vector>\n\n#include <Eigen/Geometry>\n\nnamespace common_robotics_utilities\n{\nnamespace math\n{\n///////////////////////////////////////////////////////////////\n//// Typedefs for aligned STL containers using Eigen types ////\n///////////////////////////////////////////////////////////////\n\nusing VectorVector2f\n  = std::vector<Eigen::Vector2f, Eigen::aligned_allocator<Eigen::Vector2f>>;\nusing VectorVector2d\n  = std::vector<Eigen::Vector2d, Eigen::aligned_allocator<Eigen::Vector2d>>;\nusing VectorVector3f\n  = std::vector<Eigen::Vector3f, Eigen::aligned_allocator<Eigen::Vector3f>>;\nusing VectorVector3d\n  = std::vector<Eigen::Vector3d, Eigen::aligned_allocator<Eigen::Vector3d>>;\nusing VectorVector4f\n  = std::vector<Eigen::Vector4f, Eigen::aligned_allocator<Eigen::Vector4f>>;\nusing VectorVector4d\n  = std::vector<Eigen::Vector4d, Eigen::aligned_allocator<Eigen::Vector4d>>;\nusing VectorQuaternionf\n  = std::vector<Eigen::Quaternionf,\n                Eigen::aligned_allocator<Eigen::Quaternionf>>;\nusing VectorQuaterniond\n  = std::vector<Eigen::Quaterniond,\n                Eigen::aligned_allocator<Eigen::Quaterniond>>;\nusing VectorIsometry3f\n  = std::vector<Eigen::Isometry3f,\n                Eigen::aligned_allocator<Eigen::Isometry3f>>;\nusing VectorIsometry3d\n  = std::vector<Eigen::Isometry3d,\n                Eigen::aligned_allocator<Eigen::Isometry3d>>;\nusing MapStringVector2f\n  = std::map<std::string, Eigen::Vector2f, std::less<std::string>,\n  Eigen::aligned_allocator<std::pair<const std::string, Eigen::Vector2f>>>;\nusing MapStringVector2d\n  = std::map<std::string, Eigen::Vector2d, std::less<std::string>,\n  Eigen::aligned_allocator<std::pair<const std::string, Eigen::Vector2d>>>;\nusing MapStringVector3f\n  = std::map<std::string, Eigen::Vector3f, std::less<std::string>,\n  Eigen::aligned_allocator<std::pair<const std::string, Eigen::Vector3f>>>;\nusing MapStringVector3d\n  = std::map<std::string, Eigen::Vector3d, std::less<std::string>,\n  Eigen::aligned_allocator<std::pair<const std::string, Eigen::Vector3d>>>;\nusing MapStringVector4f\n  = std::map<std::string, Eigen::Vector4f, std::less<std::string>,\n  Eigen::aligned_allocator<std::pair<const std::string, Eigen::Vector4f>>>;\nusing MapStringVector4d\n  = std::map<std::string, Eigen::Vector4d, std::less<std::string>,\n  Eigen::aligned_allocator<std::pair<const std::string, Eigen::Vector4d>>>;\nusing MapStringQuaternionf\n  = std::map<std::string, Eigen::Quaternionf, std::less<std::string>,\n  Eigen::aligned_allocator<std::pair<const std::string, Eigen::Quaternionf>>>;\nusing MapStringQuaterniond\n  = std::map<std::string, Eigen::Quaterniond, std::less<std::string>,\n  Eigen::aligned_allocator<std::pair<const std::string, Eigen::Quaterniond>>>;\nusing MapStringIsometry3f\n  = std::map<std::string, Eigen::Isometry3f, std::less<std::string>,\n  Eigen::aligned_allocator<std::pair<const std::string, Eigen::Isometry3f>>>;\nusing MapStringIsometry3d\n  = std::map<std::string, Eigen::Isometry3d, std::less<std::string>,\n  Eigen::aligned_allocator<std::pair<const std::string, Eigen::Isometry3d>>>;\n\nbool Equal3d(const Eigen::Vector3d& v1, const Eigen::Vector3d& v2);\n\nbool Equal4d(const Eigen::Vector4d& v1, const Eigen::Vector4d& v2);\n\nbool CloseEnough(const double p1, const double p2, const double threshold);\n\nbool CloseEnough(const Eigen::Vector3d& v1,\n                 const Eigen::Vector3d& v2,\n                 const double threshold);\n\nEigen::Vector3d RotateVector(const Eigen::Quaterniond& quat,\n                             const Eigen::Vector3d& vec);\n\nEigen::Vector3d RotateVectorReverse(const Eigen::Quaterniond& quat,\n                                    const Eigen::Vector3d& vec);\n\ndouble EnforceContinuousRevoluteBounds(const double value);\n\nEigen::VectorXd SafeNormal(const Eigen::VectorXd& vec);\n\ndouble SquaredNorm(const std::vector<double>& vec);\n\ndouble Norm(const std::vector<double>& vec);\n\nstd::vector<double> Abs(const std::vector<double>& vec);\n\nstd::vector<double> Multiply(const std::vector<double>& vec,\n                             const double scalar);\n\nstd::vector<double> Multiply(const std::vector<double>& vec1,\n                             const std::vector<double>& vec2);\n\nstd::vector<double> Divide(const std::vector<double>& vec,\n                           const double scalar);\n\nstd::vector<double> Divide(const std::vector<double>& vec1,\n                           const std::vector<double>& vec2);\n\nstd::vector<double> Add(const std::vector<double>& vec,\n                        const double scalar);\n\nstd::vector<double> Add(const std::vector<double>& vec1,\n                        const std::vector<double>& vec2);\n\nstd::vector<double> Sub(const std::vector<double>& vec,\n                        const double scalar);\n\nstd::vector<double> Sub(const std::vector<double>& vec1,\n                        const std::vector<double>& vec2);\n\ndouble Sum(const std::vector<double>& vec);\n\nEigen::Matrix3d Skew(const Eigen::Vector3d& vector);\n\nEigen::Vector3d Unskew(const Eigen::Matrix3d& matrix);\n\nEigen::Matrix4d TwistHat(const Eigen::Matrix<double, 6, 1>& twist);\n\nEigen::Matrix<double, 6, 1> TwistUnhat(const Eigen::Matrix4d& hatted_twist);\n\nEigen::Matrix<double, 6, 6> AdjointFromTransform(\n    const Eigen::Isometry3d& transform);\n\nEigen::Matrix<double, 6, 1> TransformTwist(\n    const Eigen::Isometry3d& transform,\n    const Eigen::Matrix<double, 6, 1>& initial_twist);\n\nEigen::Matrix<double, 6, 1> TwistBetweenTransforms(\n    const Eigen::Isometry3d& start,\n    const Eigen::Isometry3d& end);\n\nEigen::Matrix3d ExpMatrixExact(const Eigen::Matrix3d& hatted_rot_velocity,\n                               const double delta_t);\n\nEigen::Isometry3d ExpTwist(const Eigen::Matrix<double, 6, 1>& twist,\n                           const double delta_t);\n\ndouble Interpolate(const double p1, const double p2, const double ratio);\n\ndouble InterpolateContinuousRevolute(const double p1,\n                                     const double p2,\n                                     const double ratio);\n\nstd::vector<double> Interpolate(const std::vector<double>& v1,\n                                const std::vector<double>& v2,\n                                const double ratio);\n\nEigen::Quaterniond Interpolate(const Eigen::Quaterniond& q1,\n                               const Eigen::Quaterniond& q2,\n                               const double ratio);\n\nEigen::VectorXd InterpolateXd(const Eigen::VectorXd& v1,\n                              const Eigen::VectorXd& v2,\n                              const double ratio);\n\nEigen::Vector3d Interpolate3d(const Eigen::Vector3d& v1,\n                              const Eigen::Vector3d& v2,\n                              const double ratio);\n\nEigen::Vector4d Interpolate4d(const Eigen::Vector4d& v1,\n                              const Eigen::Vector4d& v2,\n                              const double ratio);\n\nEigen::Isometry3d Interpolate(const Eigen::Isometry3d& t1,\n                              const Eigen::Isometry3d& t2,\n                              const double ratio);\n\ndouble SquaredDistance(const Eigen::Vector2d& v1,\n                       const Eigen::Vector2d& v2);\n\ndouble Distance(const Eigen::Vector2d& v1,\n                const Eigen::Vector2d& v2);\n\ndouble SquaredDistance(const Eigen::Vector3d& v1,\n                       const Eigen::Vector3d& v2);\n\ndouble Distance(const Eigen::Vector3d& v1,\n                const Eigen::Vector3d& v2);\n\ndouble SquaredDistance(const Eigen::VectorXd& v1,\n                       const Eigen::VectorXd& v2);\n\ndouble Distance(const Eigen::VectorXd& v1,\n                const Eigen::VectorXd& v2);\n\ndouble Distance(const Eigen::Quaterniond& q1,\n                const Eigen::Quaterniond& q2);\n\ndouble Distance(const Eigen::Isometry3d& t1,\n                const Eigen::Isometry3d& t2,\n                const double alpha=0.5);\n\ndouble SquaredDistance(const std::vector<double>& p1,\n                       const std::vector<double>& p2);\n\ndouble Distance(const std::vector<double>& p1, const std::vector<double>& p2);\n\ndouble ContinuousRevoluteSignedDistance(const double p1, const double p2);\n\ndouble ContinuousRevoluteDistance(const double p1, const double p2);\n\ndouble AddContinuousRevoluteValues(const double start, const double change);\n\ndouble GetContinuousRevoluteRange(const double start, const double end);\n\nbool CheckInContinuousRevoluteRange(const double start,\n                                    const double range,\n                                    const double val);\n\nbool CheckInContinuousRevoluteBounds(const double start,\n                                     const double end,\n                                     const double val);\n\ndouble AverageStdVectorDouble(\n    const std::vector<double>& values,\n    const std::vector<double>& weights=std::vector<double>());\n\ndouble ComputeStdDevStdVectorDouble(const std::vector<double>& values,\n                                    const double mean);\n\ndouble ComputeStdDevStdVectorDouble(const std::vector<double>& values);\n\ndouble WeightedDotProduct(const Eigen::VectorXd& vec1,\n                          const Eigen::VectorXd& vec2,\n                          const Eigen::VectorXd& weights);\n\ndouble WeightedSquaredNorm(const Eigen::VectorXd& vec,\n                           const Eigen::VectorXd weights);\n\ndouble WeightedNorm(const Eigen::VectorXd& vec,\n                    const Eigen::VectorXd& weights);\n\ndouble WeightedCosineAngleBetweenVectors(const Eigen::VectorXd& vec1,\n                                         const Eigen::VectorXd& vec2,\n                                         const Eigen::VectorXd& weights);\n\ndouble WeightedAngleBetweenVectors(const Eigen::VectorXd& vec1,\n                                   const Eigen::VectorXd& vec2,\n                                   const Eigen::VectorXd& weights);\n\nEigen::Vector3d AverageEigenVector3d(\n    const VectorVector3d& vectors,\n    const std::vector<double>& weights=std::vector<double>());\n\nEigen::Vector4d AverageEigenVector4d(\n    const VectorVector4d& vectors,\n    const std::vector<double>& weights=std::vector<double>());\n\nEigen::VectorXd AverageEigenVectorXd(\n    const std::vector<Eigen::VectorXd>& vectors,\n    const std::vector<double>& weights=std::vector<double>());\n\nEigen::Quaterniond AverageEigenQuaterniond(\n    const VectorQuaterniond& quaternions,\n    const std::vector<double>& weights=std::vector<double>());\n\nEigen::Isometry3d AverageEigenIsometry3d(\n    const VectorIsometry3d& transforms,\n    const std::vector<double>& weights=std::vector<double>());\n\n// This function does not actually deal with the continuous revolute\n// space correctly, it just assumes a normal real Euclidean space\ndouble AverageContinuousRevolute(\n    const std::vector<double>& angles,\n    const std::vector<double>& weights=std::vector<double>());\n\ntemplate <typename Derived>\ninline Eigen::MatrixXd ClampNorm(\n    const Eigen::MatrixBase<Derived>& item_to_clamp, const double max_norm)\n{\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// This function is really only going to work well for \"almost continuous\"\n// types, i.e. floats and doubles, due to the implementation\ntemplate<typename ScalarType, int Rows,\n         typename Allocator=std::allocator<Eigen::Matrix<ScalarType, Rows, 1>>>\ninline 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  if (vectors.empty())\n  {\n    throw std::invalid_argument(\"vectors is empty\");\n  }\n  if ((weights.size() > 0) && (vectors.size() != weights.size()))\n  {\n    throw std::invalid_argument(\"weights.size() > 0 != vectors.size()\");\n  }\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  if (starting_idx >= vectors.size())\n  {\n    throw std::invalid_argument(\"All provided weights are zero\");\n  }\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])\n                                             : 1.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\n                 + (effective_weight * (current - prev_avg_vector));\n  }\n  return avg_vector;\n}\n\n// Projects vector_to_project onto base_vector and\n// returns the portion that is parallel to base_vector\ntemplate <typename DerivedB, typename DerivedV>\ninline Eigen::Matrix<typename DerivedB::Scalar, Eigen::Dynamic, 1>\nVectorProjection(\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,\n                typename DerivedV::Scalar>::value,\n                \"vectors 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>\n        ::Zero(base_vector.rows());\n  }\n}\n\n// Projects vector_to_project onto base_vector and\n// returns the portion that is perpendicular to base_vector\ntemplate <typename DerivedB, typename DerivedV>\ninline Eigen::Matrix<typename DerivedB::Scalar, Eigen::Dynamic, 1>\nVectorRejection(\n    const Eigen::MatrixBase<DerivedB>& base_vector,\n    const Eigen::MatrixBase<DerivedV>& vector_to_reject)\n{\n  // Rejection is defined in relation to projection\n  return vector_to_reject - VectorProjection(base_vector, vector_to_reject);\n}\n\ntemplate <typename DerivedV>\ninline Eigen::Matrix<typename DerivedV::Scalar, Eigen::Dynamic, 1>\nGetArbitraryOrthogonalVector(const Eigen::MatrixBase<DerivedV>& vector)\n{\n  // We're going to try arbitrary possibilities until one of them works\n  const ssize_t vector_size = vector.size();\n  if (vector_size > 0)\n  {\n    for (ssize_t idx = 0; idx < vector_size; idx++)\n    {\n      Eigen::Matrix<typename DerivedV::Scalar, Eigen::Dynamic, 1> test_vector\n          = Eigen::Matrix<typename DerivedV::Scalar, Eigen::Dynamic, 1>\n          ::Zero(vector_size);\n      test_vector(idx) = static_cast<typename DerivedV::Scalar>(1.0);\n      const auto rejected_vector = VectorRejection(vector, test_vector);\n      const typename DerivedV::Scalar rejected_vector_squared_norm\n          = rejected_vector.squaredNorm();\n      if (rejected_vector_squared_norm > 0)\n      {\n        return rejected_vector;\n      }\n    }\n    throw std::runtime_error(\"Vector rejection failed to find orthogonal\"\n                             \" vector, probably numerical error\");\n  }\n  else\n  {\n    throw std::invalid_argument(\"Vector size is zero\");\n  }\n}\n\ntemplate <typename DerivedV>\ninline Eigen::Matrix<typename DerivedV::Scalar, Eigen::Dynamic, 1>\nGetArbitraryOrthogonalVectorToPlane(\n    const Eigen::MatrixBase<DerivedV>& plane_vector1,\n    const Eigen::MatrixBase<DerivedV>& plane_vector2,\n    const Eigen::MatrixBase<DerivedV>& vector)\n{\n  const ssize_t vector_size = vector.size();\n  if ((vector_size > 0)\n      && (vector_size == plane_vector1.size())\n      && (vector_size == plane_vector2.size()))\n  {\n    const Eigen::MatrixBase<DerivedV> unit_plane_vector1\n        = plane_vector1 / plane_vector1.norm();\n    const Eigen::MatrixBase<DerivedV> unit_plane_vector2\n        = plane_vector2 / plane_vector2.norm();\n    const typename DerivedV::Scalar plane_vector_dot_product_mag\n        = std::abs(unit_plane_vector1.dot(unit_plane_vector2));\n    if (plane_vector_dot_product_mag == 1.0)\n    {\n      throw std::invalid_argument(\"Plane vectors do not define a valid plane\");\n    }\n    else\n    {\n      // Try both plane vectors\n      // (by definition, one of the two MUST have an orthogonal component!)\n      const auto rejected_vector1 = VectorRejection(vector, plane_vector1);\n      const typename DerivedV::Scalar rejected_vector1_squared_norm\n          = rejected_vector1.squaredNorm();\n      if (rejected_vector1_squared_norm > 0)\n      {\n        return rejected_vector1;\n      }\n      else\n      {\n        const auto rejected_vector2 = VectorRejection(vector, plane_vector2);\n        const typename DerivedV::Scalar rejected_vector2_squared_norm\n            = rejected_vector2.squaredNorm();\n        if (rejected_vector2_squared_norm > 0)\n        {\n          return rejected_vector2;\n        }\n        else\n        {\n          throw std::runtime_error(\"Vector rejection failed to find orthogonal\"\n                                   \" vector, probably numerical error\");\n        }\n      }\n    }\n  }\n  else\n  {\n    throw std::invalid_argument(\"Vector size is zero\");\n  }\n}\n\ntemplate<typename DataType, typename Container=std::vector<DataType>>\nEigen::MatrixXd BuildPairwiseDistanceMatrixParallel(\n    const Container& data,\n    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(static_cast<ssize_t>(idx), static_cast<ssize_t>(jdx))\n            = distance;\n        distance_matrix(static_cast<ssize_t>(jdx), static_cast<ssize_t>(idx))\n            = distance;\n      }\n      else\n      {\n        distance_matrix(static_cast<ssize_t>(idx), static_cast<ssize_t>(jdx))\n            = 0.0;\n        distance_matrix(static_cast<ssize_t>(jdx), static_cast<ssize_t>(idx))\n            = 0.0;\n      }\n    }\n  }\n  return distance_matrix;\n}\n\ntemplate<typename DataType, typename Container=std::vector<DataType>>\nEigen::MatrixXd BuildPairwiseDistanceMatrixSerial(\n    const Container& data,\n    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(static_cast<ssize_t>(idx), static_cast<ssize_t>(jdx))\n            = distance;\n        distance_matrix(static_cast<ssize_t>(jdx), static_cast<ssize_t>(idx))\n            = distance;\n      }\n      else\n      {\n        distance_matrix(static_cast<ssize_t>(idx), static_cast<ssize_t>(jdx))\n            = 0.0;\n        distance_matrix(static_cast<ssize_t>(jdx), static_cast<ssize_t>(idx))\n            = 0.0;\n      }\n    }\n  }\n  return distance_matrix;\n}\n\ntemplate<typename DataType, typename Container=std::vector<DataType>>\nEigen::MatrixXd BuildPairwiseDistanceMatrix(\n    const Container& data,\n    const std::function<double(const DataType&, const DataType&)>& distance_fn,\n    const bool use_parallel = false)\n{\n  if (use_parallel)\n  {\n    return BuildPairwiseDistanceMatrixParallel(data, distance_fn);\n  }\n  else\n  {\n    return BuildPairwiseDistanceMatrixSerial(data, distance_fn);\n  }\n}\n\ntemplate<typename FirstDataType, typename SecondDataType,\n         typename FirstContainer=std::vector<FirstDataType>,\n         typename SecondContainer=std::vector<SecondDataType>>\nEigen::MatrixXd BuildPairwiseDistanceMatrixParallel(\n    const FirstContainer& data1, const SecondContainer& data2,\n    const std::function<double(const FirstDataType&,\n                               const SecondDataType&)>& distance_fn)\n{\n  Eigen::MatrixXd distance_matrix(data1.size(), data2.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(static_cast<ssize_t>(idx), static_cast<ssize_t>(jdx))\n          = distance;\n    }\n  }\n  return distance_matrix;\n}\n\ntemplate<typename FirstDataType, typename SecondDataType,\n         typename FirstContainer=std::vector<FirstDataType>,\n         typename SecondContainer=std::vector<SecondDataType>>\nEigen::MatrixXd BuildPairwiseDistanceMatrixSerial(\n    const FirstContainer& data1, const SecondContainer& data2,\n    const std::function<double(const FirstDataType&,\n                               const SecondDataType&)>& distance_fn)\n{\n  Eigen::MatrixXd distance_matrix(data1.size(), data2.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(static_cast<ssize_t>(idx), static_cast<ssize_t>(jdx))\n          = distance;\n    }\n  }\n  return distance_matrix;\n}\n\ntemplate<typename FirstDataType, typename SecondDataType,\n         typename FirstContainer=std::vector<FirstDataType>,\n         typename SecondContainer=std::vector<SecondDataType>>\nEigen::MatrixXd BuildPairwiseDistanceMatrix(\n    const FirstContainer& data1, const SecondContainer& data2,\n    const std::function<double(const FirstDataType&,\n                               const SecondDataType&)>& distance_fn,\n    const bool use_parallel = false)\n{\n  if (use_parallel)\n  {\n    return BuildPairwiseDistanceMatrixParallel(data1, data2, distance_fn);\n  }\n  else\n  {\n    return BuildPairwiseDistanceMatrixSerial(data1, data2, distance_fn);\n  }\n}\n\nclass Hyperplane\n{\nprivate:\n  Eigen::VectorXd plane_origin_;\n  Eigen::VectorXd plane_normal_;\n\npublic:\n\n  Hyperplane(const Eigen::VectorXd& origin, const Eigen::VectorXd& normal)\n      : plane_origin_(origin), plane_normal_(normal)\n  {\n    if (plane_origin_.size() != plane_normal_.size())\n    {\n      throw std::invalid_argument(\"origin.size() != normal.size()\");\n    }\n  }\n\n  Hyperplane() {}\n\n  size_t GetDimensionality() const\n  {\n    return static_cast<size_t>(plane_origin_.size());\n  }\n\n  const Eigen::VectorXd& GetOrigin() const { return plane_origin_; }\n\n  const Eigen::VectorXd& GetNormal() const { return plane_normal_; }\n\n  double GetNormedDotProduct(const Eigen::VectorXd& point) const\n  {\n    const Eigen::VectorXd check_vector = point - GetOrigin();\n    const Eigen::VectorXd check_vector_normed = SafeNormal(check_vector);\n    const double dot_product = check_vector_normed.dot(GetNormal());\n    return dot_product;\n  }\n\n  double GetRawDotProduct(const Eigen::VectorXd& point) const\n  {\n    const Eigen::VectorXd check_vector = point - GetOrigin();\n    const double dot_product = check_vector.dot(GetNormal());\n    return dot_product;\n  }\n\n  Eigen::VectorXd RejectVectorOntoPlane(const Eigen::VectorXd& vector) const\n  {\n    return VectorProjection(GetNormal(), vector);\n  }\n\n  double GetSquaredDistanceToPlane(const Eigen::VectorXd& point) const\n  {\n    const Eigen::VectorXd origin_to_point_vector = point - GetOrigin();\n    return VectorProjection(GetNormal(), 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 - GetOrigin();\n    return VectorProjection(GetNormal(), origin_to_point_vector).norm();\n  }\n\n  Eigen::VectorXd ProjectVectorOntoPlane(const Eigen::VectorXd& vector) const\n  {\n    return VectorRejection(GetNormal(), vector);\n  }\n\n  Eigen::VectorXd ProjectPointOntoPlane(const Eigen::VectorXd& point) const\n  {\n    const Eigen::VectorXd origin_to_point_vector = point - GetOrigin();\n    const Eigen::VectorXd projected_to_point_vector =\n        VectorRejection(GetNormal(), origin_to_point_vector);\n    const Eigen::VectorXd projected_point =\n        GetOrigin() + projected_to_point_vector;\n    return projected_point;\n  }\n};\n\nHyperplane FitPlaneToPoints(const std::vector<Eigen::VectorXd>& points);\n}  // namespace math\n}  // namespace common_robotics_utilities\n", "meta": {"hexsha": "60111dffb31946baf0565b00478b7b1c376740a7", "size": 24876, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/common_robotics_utilities/math.hpp", "max_stars_repo_name": "calderpg/common_robotics_utilities", "max_stars_repo_head_hexsha": "8b1c06dd45b283f8234c6a4d565bcb7078d1a851", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2018-10-15T19:04:55.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-23T01:35:16.000Z", "max_issues_repo_path": "include/common_robotics_utilities/math.hpp", "max_issues_repo_name": "calderpg/common_robotics_utilities", "max_issues_repo_head_hexsha": "8b1c06dd45b283f8234c6a4d565bcb7078d1a851", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 13.0, "max_issues_repo_issues_event_min_datetime": "2018-10-18T19:14:40.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-21T15:08:21.000Z", "max_forks_repo_path": "include/common_robotics_utilities/math.hpp", "max_forks_repo_name": "calderpg/common_robotics_utilities", "max_forks_repo_head_hexsha": "8b1c06dd45b283f8234c6a4d565bcb7078d1a851", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2018-10-17T21:12:01.000Z", "max_forks_repo_forks_event_max_datetime": "2019-11-18T03:53:47.000Z", "avg_line_length": 36.0, "max_line_length": 79, "alphanum_fraction": 0.672173983, "num_tokens": 5753, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5583269943353744, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.3245572073973031}}
{"text": "//============================================================================\n// Name        : LBFGSSolver.cpp\n// Author      : Yaser\n// Version     :\n// Copyright   :\n// Description : LBFGS MPI implementation\n//============================================================================\n\n#include \"LBFGSSolver.h\"\n#include <boost/mpi.hpp>\n#include <iomanip>\n\n\nnamespace mpi = boost::mpi;\n\n//virtual void computeAndTakeStep();\n//virtual double ();\n\nLBFGSSolver::LBFGSSolver(ProblemData problemData, OptimizationParameters _optParams) :\n\t\t\t\t\t\tQuasiNewtonSolver(problemData, _optParams) {\n\tmpi::communicator world;\n\tstepSize = optParams.stepsize;\n\tlbfgsHistorySize = optParams.lbfgs_memory;\n\tm = optParams.m;\n\tglobalN = optParams.n;\n\tlocalN = optParams.n / world.size();\n\tint localNTmp = localN;\n\t// We are going to split data by columns. Local N tells how many columns\n\t//\tare stored locally.\n\tif (world.rank() == world.size() - 1) { // If optParam.n is not divisible by world.size we need to have few extra points on last node\n\t\tlocalN = optParams.n - (localN * (world.size() - 1));\n\t}\n\tAlocal.resize(localN * m);\n\txLocalEven.resize(localN);\n\txLocalOdd.resize(localN);\n\tcLocal.resize(localN * lbfgsHistorySize*2);\n\tpreMatrixGlobal.resize((2*lbfgsHistorySize+1) * (2*lbfgsHistorySize+1));\n\tgradientLocalEven.resize(localN);\n\tgradientLocalOdd.resize(localN);\n\txGlobalEven.resize(globalN);\n\txGlobalOdd.resize(globalN);\n\tpK.resize(globalN);\n\tbLocal.resize(m);\n\t// Send data to other nodes\n\tif (world.rank() == 0) { // Sends data to others\n/*\n\t\tfor (int r = 0; r < m; r++) {\n\t\t\tfor (int c = 0; c < globalN; c++) {\n\t\t\t\tcout << problemData.A[r + c * m] << \" \";\n\t\t\t}\n\t\t\tcout << endl;\n\t\t}\n*/\n\t\tfor (int i = 1; i < world.size(); i++) {\n\t\t\tint nnz = localNTmp;\n\t\t\tif (i == world.size() - 1) {\n\t\t\t\tnnz = optParams.n - (localNTmp * (world.size() - 1));\n\t\t\t}\n\t\t\tworld.send(i, 0, &problemData.A[(i) * localNTmp * m], nnz * m);\n\n\t\t}\n\t\t// Also copy local data\n\t\tfor (int i = 0; i < localN * optParams.m; i++) {\n\t\t\tAlocal[i] = problemData.A[i];\n\t\t}\n\t\tfor (int i = 0; i < m; i++) {\n\t\t\tbLocal[i] = problemData.b[i];\n\t\t\tcout << bLocal[i] << \" \";\n\t\t}\n\t\tcout << endl;\n\t\tif (iter%2==0){\n\t\t\tfor (int i = 0; i < globalN; i++) {\n\t\t\t\txGlobalEven[i] = problemData.x[i];\n\t\t\t}\n\t\t} else {\n\t\t\tfor (int i = 0; i < globalN; i++) {\n\t\t\t\txGlobalOdd[i] = problemData.x[i];\n\t\t\t}\n\t\t}\n\n\t} else {\n\t\t// Receive data from root\n\t\tworld.recv(0, 0, &Alocal[0], localN * m);\n\n\t}\n\tif (iter%2==0){\n\t\tthis->sendXFromRootToNodes(xGlobalEven);\n\t} else {\n\t\tthis->sendXFromRootToNodes(xGlobalOdd);\n\t}\n\n}\n\nvoid LBFGSSolver::sendXFromRootToNodes(std::vector<double> xIn) {\n\n\tmpi::communicator world;\n\tif (world.rank() == 0) { // Sends data to others\n\t\tfor (int i = 1; i < world.size(); i++) {\n\t\t\tint nnz = localN;\n\t\t\tif (i == world.size() - 1) {\n\t\t\t\tnnz = globalN - (localN * (world.size() - 1));\n\t\t\t}\n\t\t\tworld.send(i, 1, &xIn[(i) * localN], nnz);\n\n\t\t}\n\t\t// Also copy local data\n\t\tif (iter%2==0){\n\n\t\t\tfor (int i = 0; i < localN; i++) {\n\t\t\t\txLocalEven[i] = xIn[i];\n\t\t\t}\n\t\t} else {\n\t\t\tfor (int i = 0; i < localN; i++) {\n\t\t\t\txLocalOdd[i] = xIn[i];\n\t\t\t}\n\t\t}\n\n\t} else {\n\t\t// Receive data from root\n\t\tif (iter%2==0){\n\t\t\tworld.recv(0, 1, &xLocalEven[0], localN);\n\t\t} else {\n\t\t\tworld.recv(0, 1, &xLocalOdd[0], localN);\n\n\t\t}\n\t}\n\n}\n\n\nstd::vector<double> LBFGSSolver::computeResidualForCurrentX() { // computes Ax-b\n\tmpi::communicator world;\n\tstd::vector<double> g(m, 0);\n\n\tif (iter%2==0){\n\n\t\tfor (int i = 0; i < localN; i++) {\n\t\t\tfor (int j = 0; j < m; j++) {\n\t\t\t\tg[j] += xLocalEven[i] * Alocal[i * m + j];\n\t\t\t}\n\t\t}\n\t} else {\n\n\t\tfor (int i = 0; i < localN; i++) {\n\t\t\tfor (int j = 0; j < m; j++) {\n\t\t\t\tg[j] += xLocalOdd[i] * Alocal[i * m + j];\n\t\t\t}\n\t\t}\n\t}\n\n\tstd::vector<double> gTmp(m, 0);\n\tmpi::reduce(world, &g[0], m, &gTmp[0], std::plus<double>(), 0);\n\n\tif (world.rank() == 0) {\n\t\tfor (int i = 0; i < m; i++) {\n\t\t\tgTmp[i] -= bLocal[i];\n\t\t}\n\t}\n\treturn gTmp;\n}\n\ndouble LBFGSSolver::computeCurrentObjectiveValue() {\n\tdouble objVal = 0;\n\t// objVal = 1/2 * \\|Ax - b\\|^2\n\t// first I multiply  g = ALocal*xLocal\n\tstd::vector<double> residual = this->computeResidualForCurrentX();\n\tmpi::communicator world;\n\n\tif (world.rank() == 0) {\n\n\t\tfor (unsigned int i = 0; i < residual.size(); i++) {\n\t\t\tobjVal += residual[i] * residual[i];\n\t\t}\n\t}\n\treturn objVal / 2;\n}\nstd::vector<double> LBFGSSolver::computeGradientForCurrentX() { // computes A'*(Ax-b)\n\n\tstd::vector<double> residual = this->computeResidualForCurrentX();\n\tmpi::communicator world;\n\tif (world.rank() == 0) {\n\t\t//cout<<\"residual: \"<< residual[0]<< \"  iter: \"<<iter<<\" xLocalEven: \"<<xLocalEven[0]<<\" xLocalOdd: \"<<xLocalOdd[0]<<endl;\n\t}\n\n\n\n\tbroadcast(world, &residual[0], residual.size(), 0);  // now residuals is the same on each node.\n\n\t// gradient = A'*residual\n\tif(iter%2 == 0){\n\t\tfor (int r = 0; r < m; r++) {\n\t\t\tfor (int col = 0; col < localN; col++) {\n\t\t\t\tgradientLocalEven[col] = 0;\n\t\t\t}\n\t\t}\n\n\t\tfor (int r = 0; r < m; r++) {\n\t\t\tfor (int col = 0; col < localN; col++) {\n\t\t\t\tgradientLocalEven[col] += residual[r] * Alocal[r + col * m];\n\t\t\t}\n\t\t}\n\t} else {\n\t\tfor (int r = 0; r < m; r++) {\n\t\t\tfor (int col = 0; col < localN; col++) {\n\t\t\t\tgradientLocalOdd[col] = 0;\n\t\t\t}\n\t\t}\n\t\tfor (int r = 0; r < m; r++) {\n\t\t\tfor (int col = 0; col < localN; col++) {\n\t\t\t\tgradientLocalOdd[col] += residual[r] * Alocal[r + col * m];\n\t\t\t}\n\t\t}\n\t}\n\n\t// gather to a root note to store full gradient\n\tstd::vector<double> gradient;\n\tif (world.rank() == 0) {\n\t\tgradient.resize(globalN);\n\t\tfor (int from = 1; from < world.size(); from++) {\n\t\t\tint nnz = localN;\n\t\t\tif (from == world.size() - 1) {\n\t\t\t\tnnz = globalN - (localN * (world.size() - 1));\n\t\t\t}\n\t\t\tworld.recv(from, 0, &gradient[localN * from], nnz);\n\n\t\t}\n\t\tif(iter%2 == 0){\n\n\t\t\tfor (int i = 0; i < localN; i++) {\n\t\t\t\tgradient[i] = gradientLocalEven[i];\n\t\t\t}\n\t\t} else {\n\t\t\tfor (int i = 0; i < localN; i++) {\n\t\t\t\tgradient[i] = gradientLocalOdd[i];\n\t\t\t}\n\t\t}\n\n\t} else {\n\t\t// send data to ROOT\n\t\tif(iter%2 == 0){\n\t\t\tworld.send(0, 0, &gradientLocalEven[0], gradientLocalEven.size());\n\t\t} else {\n\t\t\tworld.send(0, 0, &gradientLocalOdd[0], gradientLocalOdd.size());\n\t\t}\n\t}\n\n\treturn gradient;\n\n}\n\n\nstd::vector<double> LBFGSSolver::computeMatrixPre() { // calculates the b.b' (here c.c') and returns precondition matrix of alg. 3\n\tmpi::communicator world;\n\t// First time to enter this function, iter=0\n\tif (iter>0){\n\t\tint mod1 = (iter-1) % lbfgsHistorySize;\n\n\t\tint mod2 = (iter-1) % lbfgsHistorySize + lbfgsHistorySize;\n\n\t\tstd::vector<double> preMatUpdateLocal(2*lbfgsHistorySize+1, 0);\n\n\n\n\t\tfor (int i = 0; i < localN; i++) {\n\t\t\tfor (int j = 0; j < 2*lbfgsHistorySize; j++) {\n\t\t\t\tpreMatUpdateLocal[j] += cLocal[localN*mod1+ i] * cLocal[j * localN + i];\n\t\t\t}\n\t\t}\n\n\n\t\t//std::vector<double> gTmp(2*lbfgsHistorySize, 0); ////// why?\n\t\tmpi::reduce(world, &preMatUpdateLocal[0], 2*lbfgsHistorySize,\n\t\t\t\t&preMatrixGlobal[mod1*(2*lbfgsHistorySize+1)], std::plus<double>(), 0);\n\n\t\t// mod1*(2*lbfgsHistorySize) is the first element in the column 3\n\t\tstd::fill(preMatUpdateLocal.begin(), preMatUpdateLocal.end(), 0);     //\n\t\tif (world.rank() == 0) {    //\n\t\t\tfor (int i = 0; i < 2*lbfgsHistorySize; i++) {\n\t\t\t\tpreMatrixGlobal[mod1 + i * (2*lbfgsHistorySize+1) ]\t=\n\t\t\t\t\t\tpreMatrixGlobal[mod1*(2*lbfgsHistorySize+1)+i];\n\t\t\t}\n\t\t}\n\n\n\t\tfor (int i = 0; i < localN; i++) {\n\t\t\tfor (int j = 0; j < 2*lbfgsHistorySize; j++) {\n\t\t\t\tpreMatUpdateLocal[j] += cLocal[localN*mod2+ i] * cLocal[j * localN + i];\n\t\t\t}\n\t\t}\n\n\n\t\tmpi::reduce(world, &preMatUpdateLocal[0], 2*lbfgsHistorySize, &preMatrixGlobal[mod2*(2*lbfgsHistorySize+1)], std::plus<double>(), 0);\n\t\tstd::fill(preMatUpdateLocal.begin(), preMatUpdateLocal.end(), 0);     //\n\t\t// mod2(?)*(2*lbfgsHistorySize) is the first element in the column 3\n\n\t\tif (world.rank() == 0) {    ////////////////////////////////\n\t\t\tfor (int i = 0; i < 2*lbfgsHistorySize; i++) {\n\t\t\t\tpreMatrixGlobal[mod2 + i * (2*lbfgsHistorySize +1)]\t= \tpreMatrixGlobal[mod2*(2*lbfgsHistorySize+1)+i];\n\t\t\t}\n\t\t}\n\n\n\n\t\tif (iter%2 == 0){\n//\t\t\tcout<<\"grad @ even= [\";\n\t\t\tfor (int i = 0; i < localN; i++) {\n\t\t\t\tfor (int j = 0; j < 2*lbfgsHistorySize; j++) {\n\t\t\t\t\tpreMatUpdateLocal[j] += gradientLocalEven[i] * cLocal[j * localN + i];\n\t\t\t\t}\n\t\t\t\tpreMatUpdateLocal[2*lbfgsHistorySize] += gradientLocalEven[i]*gradientLocalEven[i];\n//\t\t\t\tcout<<gradientLocalOdd[i]<<\"   \"<<gradientLocalEven[i];\n\n\t\t\t}\n//\t\t\tcout<<endl;\n//\t\t\tcout<<\"gradNorm @ even= \"<<preMatUpdateLocal[2*lbfgsHistorySize]<<endl;\n\n\t\t}\n\t\telse {\n//\t\t\tcout<<\"grad @ odd= [\";\n\t\t\tfor (int i = 0; i < localN; i++) {\n\t\t\t\tfor (int j = 0; j < 2*lbfgsHistorySize; j++) {\n\t\t\t\t\tpreMatUpdateLocal[j] += gradientLocalOdd[i] * cLocal[j * localN + i];\n\t\t\t\t}\n\t\t\t\tpreMatUpdateLocal[2*lbfgsHistorySize] += gradientLocalOdd[i]*gradientLocalOdd[i];\n\n\t\t\t}\n\t\t}\n\n\t\t//std::vector<double> gTmp(2*lbfgsHistorySize, 0);  ////// why?\n\t\tmpi::reduce(world, &preMatUpdateLocal[0], 2*lbfgsHistorySize+1,\n\t\t\t\t&preMatrixGlobal[(2*lbfgsHistorySize+1)*(2*lbfgsHistorySize)], std::plus<double>(), 0);\n\t\t// mod1*(2*lbfgsHistorySize) is the first element in the column 3\n\n\t\tif (world.rank() == 0) {    ////////////////////////////////\n\t\t\tfor (int i = 0; i < 2*lbfgsHistorySize; i++) {\n\t\t\t\tpreMatrixGlobal[2*lbfgsHistorySize + i * (2*lbfgsHistorySize+1) ]\t=\n\t\t\t\t\t\tpreMatrixGlobal[(2*lbfgsHistorySize+1)*(2*lbfgsHistorySize)+i];\n\t\t\t}\n\t\t}\n\t}\n\treturn preMatrixGlobal;\n\n}\n\n\nvoid LBFGSSolver::findPk() { // finds p_k\n\tstd::vector<double> preMatrix = this->computeMatrixPre();\n\tmpi::communicator world;\n\n\tstd::vector<double> delta(2*lbfgsHistorySize+1, 0);\n\n\tif (world.rank() == 0) {\n\n\n\t\tstd::vector<double> alpha(lbfgsHistorySize, 0);\n\t\tdelta[2*lbfgsHistorySize] = -1;\n\t\tint last_i = max(iter - lbfgsHistorySize, 0);\n\t\t// first loop\n\n//\t\tcout<<\"first loop: prematrix access\"<<endl;\n\t\tfor (int i = iter - 1; i >= last_i; i--) {\n//\t\t\tint j = i - (iter-lbfgsHistorySize) + 1;\n\t\t\tint j = i%lbfgsHistorySize;\n\n\t\t\tfor (int l = 0; l<2*lbfgsHistorySize+1;l++){\n\t\t\t\talpha[j] += preMatrix[(2*lbfgsHistorySize+1)*j+l]*delta[l];\n//\t\t\t\tcout<<\"[j,l] = [\"<<j<<\",\"<<l<<\"]   \";\n\n\t\t\t}\n\t\t\talpha[j] = alpha[j]/preMatrix[j*(2*lbfgsHistorySize+1)+(lbfgsHistorySize+j)];\n//\t\t\tcout<<\"\\ns[j,m+j] = [\"<<j<<\",\"<<lbfgsHistorySize+j<<\"]   \";\n\t\t\tdelta[lbfgsHistorySize+j] -=  alpha[j];\n\n//\t\t\tcout<<endl<<\"next mem\";\n\n\t\t}\n\n\n\t\tdouble scalarMultiplier = preMatrix[((iter - 1)%lbfgsHistorySize)*(2*lbfgsHistorySize+1)+\n\t\t                                    (iter - 1)%lbfgsHistorySize+lbfgsHistorySize]/preMatrix[((iter - 1)%lbfgsHistorySize+lbfgsHistorySize)*(2*lbfgsHistorySize+1)+((iter - 1)%lbfgsHistorySize+lbfgsHistorySize)];\n\n\t\tfor (int i = 0; i<2*lbfgsHistorySize+1; i++) {\n\t\t\tdelta[i] *= scalarMultiplier;\n\t\t}\n\n\t\t// second loop\n\t\tdouble bbeta = 0;\n//\t\tcout<<\"second loop: prematrix access\"<<endl;\n\t\tint first_i = max(0, iter - lbfgsHistorySize);\n\t\tfor (int i = first_i; i < iter; i++) {\n\t\t\tbbeta = 0;\n//\t\t\tint j = i - (iter-lbfgsHistorySize) + 1;\n\t\t\tint j = i%lbfgsHistorySize;\n\n\t\t\tfor (int l = 0; l<2*lbfgsHistorySize+1;l++){\n\t\t\t\tbbeta += preMatrix[(2*lbfgsHistorySize+1)*(lbfgsHistorySize+j)+l]*delta[l];\n\t\t\t}\n\t\t\tbbeta =  bbeta /preMatrix[j*(2*lbfgsHistorySize+1)+(lbfgsHistorySize+j)];\n\t\t\tdelta[j] +=  alpha[j]-bbeta;\n\n\t\t}\n\n\n\t}\n\tbroadcast(world, &delta[0], delta.size(), 0);  // now delta is the same on all nodes.\n\tstd::vector<double> pLocal (localN);\n\tfor (int i = 0; i < localN ; i++){\n\t\tfor (int j = 0; j< 2*lbfgsHistorySize ; j++){\n\t\t\tpLocal[i] += delta[j] * cLocal[j*localN+i];\n\t\t}\n\t}\n\n\n\n\n\n\n\tif (iter%2 == 0){\n\t\tfor (int i = 0; i < localN ; i++){\n\t\t\tpLocal[i] += delta[2*lbfgsHistorySize] * gradientLocalEven[i];\n\t\t}\n\t} else {\n\t\tfor (int i = 0; i < localN ; i++){\n\t\t\tpLocal[i] += delta[2*lbfgsHistorySize] * gradientLocalOdd[i];\n\t\t}\n\t}\n\n//\tstd::vector<double> pK ;\n\n\tif (world.rank() == 0) {\n//\t\tpK.resize(globalN);\n\t\tfor (int from = 1; from < world.size(); from++) {\n\t\t\tint nnz = localN;\n\t\t\tif (from == world.size() - 1) {\n\t\t\t\tnnz = globalN - (localN * (world.size() - 1));\n\t\t\t}\n\t\t\tworld.recv(from, 0, &pK[localN * from], nnz);\n\n\t\t}\n\n\t\tfor (int i = 0; i < localN; i++) {\n\t\t\tpK[i] = pLocal[i];\n\t\t}\n\n\n\t} else {\n\t\t// send data to ROOT\n\t\tworld.send(0, 0, &pLocal[0], localN);\n\t\tif (world.rank()==1){\n//\t\t\tcout<<endl<<endl<<endl<<\"pLocal on node \"<<world.rank()<<\" is:   \"<<pLocal[0]<<endl;\n\t\t}\n\n\n\t}\n\n\n}\n\n\nvoid LBFGSSolver::updateYk() { // finds y_k after each iteration\n\tmpi::communicator world;\n\tint modd = iter % lbfgsHistorySize;\n\tif (iter%2 == 0){\n\t\tfor(int i =0 ; i< localN; i++){\n\t\t\tcLocal[(lbfgsHistorySize+modd)*localN + i] = gradientLocalOdd[i] - gradientLocalEven[i];\n\t\t}\n\t} else {\n\t\tfor(int i =0 ; i< localN; i++){\n\t\t\tcLocal[(lbfgsHistorySize+modd)*localN + i] = gradientLocalEven[i] - gradientLocalOdd[i];\n\t\t}\n\t}\n}\n\nvoid LBFGSSolver::updateSk() { // finds s_k after each iteration\n\tmpi::communicator world;\n\t// First time to enter this function, iter=0\n\tint modd = iter % lbfgsHistorySize;\n\tif (iter%2 == 0){\n\t\tfor(int i =0 ; i< localN; i++){\n\t\t\tcLocal[modd*localN + i] = xLocalOdd[i] - xLocalEven[i];\t// bb local is stack of y_k, s_k and grad_k\n\t\t}\n\t} else {\n\t\tfor(int i =0 ; i< localN; i++){\n\t\t\tcLocal[modd*localN + i] = xLocalEven[i] - xLocalOdd[i];\n\t\t}\n\t}\n}\n\n\nvoid LBFGSSolver::computeAndTakeStep() {\n\tmpi::communicator world;\n\n\tif(iter == 0){\n\t\tgradientEven = this->computeGradientForCurrentX();\n\t}\n\t/*        two loop recursion\t */\n\tif (iter>=0){\n\t\tthis->findPk();\n\t}\n\n\t/*      Take the step and update s_k and y_k   */\n\n\n\tif(iter%2 == 0){\n\n\t\tif (world.rank() == 0) {\n\t\t\tfor (int i = 0; i < globalN; i++) {\n\t\t\t\tif (iter==0){\n\t\t\t\t\txGlobalOdd[i] = xGlobalEven[i] - stepSize * gradientEven[i];\n\t\t\t\t}else{\n\t\t\t\t\txGlobalOdd[i] = xGlobalEven[i] + stepSize * pK[i];\n\t\t\t\t}\n\t\t\t}\n\t\t\t//cout<<endl<<\"gradientEven: \"<< gradientEven[0]<< \"  iter: \"<<iter<<\" xGlobal even cur: \"<<xGlobalEven[0]<<\" xGlobal odd next: \"<<xGlobalOdd[0]<<endl;\n\t\t}\n\n\t\titer +=1;\n\t\tthis->sendXFromRootToNodes(xGlobalOdd);\n\n\n\n\t\titer -=1;\n\t\tthis->updateSk();\n\t\titer +=1;\n\n\t\tgradientOdd = this->computeGradientForCurrentX();\n\n\t\titer -=1;\n\t\tthis->updateYk();\n\t\titer +=1;\n\n\n\t} else {\n\t\tif (world.rank() == 0) {\n\n\t\t\tfor (int i = 0; i < globalN; i++) {\n\t\t\t\tif (iter==0){\n\t\t\t\t\txGlobalEven[i] = xGlobalOdd[i]- stepSize * gradientOdd[i];\n\t\t\t\t}else{\n\t\t\t\t\txGlobalEven[i] = xGlobalOdd[i]+ stepSize * pK[i];\n\t\t\t\t}\n\t\t\t}\n\n\t\t}\n\n\t\titer +=1;\n\t\tthis->sendXFromRootToNodes(xGlobalEven);\n\n\t\titer -=1;\n\t\tthis->updateSk();\n\t\titer +=1;\n\t\tgradientEven = this->computeGradientForCurrentX();\n\t\titer -=1;\n\t\tthis->updateYk();\n\t\titer +=1;\n\n\t}\n\n\n}\n", "meta": {"hexsha": "852d0e6c6bbba7ffe7e3448d1ae9690eb6f2722c", "size": 14386, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/solvers/LBFGSSolver.cpp", "max_stars_repo_name": "yasersharaf/LBFGS_MPI", "max_stars_repo_head_hexsha": "5c0e0b2383a1bfa74c852a2962a7d0380b03136c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/solvers/LBFGSSolver.cpp", "max_issues_repo_name": "yasersharaf/LBFGS_MPI", "max_issues_repo_head_hexsha": "5c0e0b2383a1bfa74c852a2962a7d0380b03136c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/solvers/LBFGSSolver.cpp", "max_forks_repo_name": "yasersharaf/LBFGS_MPI", "max_forks_repo_head_hexsha": "5c0e0b2383a1bfa74c852a2962a7d0380b03136c", "max_forks_repo_licenses": ["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.6434937611, "max_line_length": 212, "alphanum_fraction": 0.5857083275, "num_tokens": 5084, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.585101139733739, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.3244213009970422}}
{"text": "// The MIT License (MIT)\n//\n// Copyright (c) 2015 Markus Herb\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#ifndef KALMAN_MATRIX_HPP_\n#define KALMAN_MATRIX_HPP_\n\n#include <cmath>\n\n#include <Eigen/Dense>\n\n#define KALMAN_VECTOR(NAME, T, N)                                                       \\\n    typedef Kalman::Vector<T, N> Base;                                                  \\\n    using typename Base::Scalar;                                                        \\\n    using Base::RowsAtCompileTime;                                                      \\\n    using Base::ColsAtCompileTime;                                                      \\\n    using Base::SizeAtCompileTime;                                                      \\\n                                                                                        \\\n    NAME(void) : Kalman::Vector<T, N>() {}                                              \\\n                                                                                        \\\n    template<typename OtherDerived>                                                     \\\n    NAME(const Eigen::MatrixBase<OtherDerived>& other) : Kalman::Vector<T, N>(other) {} \\\n                                                                                        \\\n    template<typename OtherDerived>                                                     \\\n    NAME& operator= (const Eigen::MatrixBase <OtherDerived>& other)                     \\\n    {                                                                                   \\\n        this->Base::operator=(other);                                                   \\\n        return *this;                                                                   \\\n    }\n\nnamespace Kalman {\n    const int Dynamic = Eigen::Dynamic;\n\n    /**\n     * @class Kalman::Matrix\n     * @brief Template type for matrices\n     * @param T The numeric scalar type\n     * @param rows The number of rows\n     * @param cols The number of columns\n     */\n    template<typename T, int rows, int cols>\n    using Matrix = Eigen::Matrix<T, rows, cols>;\n    \n    /**\n     * @brief Template type for vectors\n     * @param T The numeric scalar type\n     * @param N The vector dimension\n     */\n    template<typename T, int N>\n    class Vector : public Matrix<T, N, 1>\n    {\n    public:\n        //! Matrix base type\n        typedef Matrix<T, N, 1> Base;\n\n        using typename Base::Scalar;\n        using Base::RowsAtCompileTime;\n        using Base::ColsAtCompileTime;\n        using Base::SizeAtCompileTime;\n\n        Vector(void) : Matrix<T, N, 1>() {}\n        \n        /**\n         * @brief Copy constructor\n         */\n        template<typename OtherDerived>\n        Vector(const Eigen::MatrixBase<OtherDerived>& other)\n            : Matrix<T, N, 1>(other)\n        { }\n        /**\n         * @brief Copy assignment constructor\n         */\n        template<typename OtherDerived>\n        Vector& operator= (const Eigen::MatrixBase <OtherDerived>& other)\n        {\n            this->Base::operator=(other);\n            return *this;\n        }\n    };\n    \n    /**\n     * @brief Cholesky square root decomposition of a symmetric positive-definite matrix\n     * @param _MatrixType The matrix type\n     * @param _UpLo Square root form (Eigen::Lower or Eigen::Upper)\n     */\n    template<typename _MatrixType, int _UpLo = Eigen::Lower>\n    class Cholesky : public Eigen::LLT< _MatrixType, _UpLo >\n    {\n    public:\n        Cholesky() : Eigen::LLT< _MatrixType, _UpLo >() {}\n        \n        /**\n         * @brief Construct cholesky square root decomposition from matrix\n         * @param m The matrix to be decomposed\n         */\n        Cholesky(const _MatrixType& m ) : Eigen::LLT< _MatrixType, _UpLo >(m) {}\n        \n        /**\n         * @brief Set decomposition to identity\n         */\n        Cholesky& setIdentity()\n        {\n            this->m_matrix.setIdentity();\n            this->m_isInitialized = true;\n            return *this;\n        }\n        \n        /**\n         * @brief Check whether the decomposed matrix is the identity matrix\n         */\n        bool isIdentity() const\n        {\n            eigen_assert(this->m_isInitialized && \"LLT is not initialized.\");\n            return this->m_matrix.isIdentity();\n        }\n        \n        /**\n         * @brief Set lower triangular part of the decomposition\n         * @param matrix The lower part stored in a full matrix\n         */\n        template<typename Derived>\n        Cholesky& setL(const Eigen::MatrixBase <Derived>& matrix)\n        {\n            this->m_matrix = matrix.template triangularView<Eigen::Lower>();\n            this->m_isInitialized = true;\n            return *this;\n        }\n        \n        /**\n         * @brief Set upper triangular part of the decomposition\n         * @param matrix The upper part stored in a full matrix\n         */\n        template<typename Derived>\n        Cholesky& setU(const Eigen::MatrixBase <Derived>& matrix)\n        {\n            this->m_matrix = matrix.template triangularView<Eigen::Upper>().adjoint();\n            this->m_isInitialized = true;\n            return *this;\n        }\n    };\n}\n\n#endif\n", "meta": {"hexsha": "574ebdf58e44dd61564060a945be522f54eb9b7e", "size": 6194, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/kalman/Matrix.hpp", "max_stars_repo_name": "Zengqt-e/kalman", "max_stars_repo_head_hexsha": "57d21784389b240d46f5ca179c012983d51d4ecb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 875.0, "max_stars_repo_stars_event_min_datetime": "2015-09-07T14:12:53.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T09:57:08.000Z", "max_issues_repo_path": "include/kalman/Matrix.hpp", "max_issues_repo_name": "Zengqt-e/kalman", "max_issues_repo_head_hexsha": "57d21784389b240d46f5ca179c012983d51d4ecb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 31.0, "max_issues_repo_issues_event_min_datetime": "2015-10-01T18:06:53.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-15T03:42:15.000Z", "max_forks_repo_path": "include/kalman/Matrix.hpp", "max_forks_repo_name": "Zengqt-e/kalman", "max_forks_repo_head_hexsha": "57d21784389b240d46f5ca179c012983d51d4ecb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 316.0, "max_forks_repo_forks_event_min_datetime": "2015-09-27T13:18:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-30T05:21:58.000Z", "avg_line_length": 38.4720496894, "max_line_length": 89, "alphanum_fraction": 0.5195350339, "num_tokens": 1213, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5544704502361149, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.32442130040473605}}
{"text": "// boost\\math\\distributions\\non_central_t.hpp\n\n// Copyright John Maddock 2008.\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_SPECIAL_NON_CENTRAL_T_HPP\n#define BOOST_MATH_SPECIAL_NON_CENTRAL_T_HPP\n\n#include <boost/math/distributions/fwd.hpp>\n#include <boost/math/distributions/non_central_beta.hpp> // for nc beta\n#include <boost/math/distributions/normal.hpp> // for normal CDF and quantile\n#include <boost/math/distributions/students_t.hpp>\n#include <boost/math/distributions/detail/generic_quantile.hpp> // quantile\n\nnamespace boost\n{\n   namespace math\n   {\n\n      template <class RealType, class Policy>\n      class non_central_t_distribution;\n\n      namespace detail{\n\n         template <class T, class Policy>\n         T non_central_t2_p(T n, T delta, T x, T y, const Policy& pol, T init_val)\n         {\n            BOOST_MATH_STD_USING\n            //\n            // Variables come first:\n            //\n            boost::uintmax_t max_iter = policies::get_max_series_iterations<Policy>();\n            T errtol = ldexp(1.0f, -boost::math::policies::digits<T, Policy>());\n            T d2 = delta * delta / 2;\n            //\n            // k is the starting point for iteration, and is the\n            // maximum of the poisson weighting term:\n            //\n            int k = boost::math::itrunc(d2);\n            // Starting Poisson weight:\n            T pois = gamma_p_derivative(T(k+1), d2, pol) \n               * tgamma_delta_ratio(T(k + 1), T(0.5f))\n               * delta / constants::root_two<T>();\n            if(pois == 0)\n               return init_val;\n            // Starting beta term:\n            T beta = x < y\n               ? ibeta(T(k + 1), n / 2, x, pol)\n               : ibetac(n / 2, T(k + 1), y, pol);\n            // Recurance term:\n            T xterm = x < y\n               ? ibeta_derivative(T(k + 1), n / 2, x, pol)\n               : ibeta_derivative(n / 2, T(k + 1), y, pol);\n            xterm *= y / (n / 2 + k);\n            T poisf(pois), betaf(beta), xtermf(xterm);\n            T sum = init_val;\n            if((xterm == 0) && (beta == 0))\n               return init_val;\n\n            //\n            // Backwards recursion first, this is the stable\n            // direction for recursion:\n            //\n            boost::uintmax_t count = 0;\n            for(int i = k; i >= 0; --i)\n            {\n               T term = beta * pois;\n               sum += term;\n               if(fabs(term/sum) < errtol)\n                  break;\n               pois *= (i + 0.5f) / d2;\n               beta += xterm;\n               xterm *= (i) / (x * (n / 2 + i - 1));\n               ++count;\n            }\n            for(int i = k + 1; ; ++i)\n            {\n               poisf *= d2 / (i + 0.5f);\n               xtermf *= (x * (n / 2 + i - 1)) / (i);\n               betaf -= xtermf;\n               T term = poisf * betaf;\n               sum += term;\n               if(fabs(term/sum) < errtol)\n                  break;\n               ++count;\n               if(count > max_iter)\n               {\n                  return policies::raise_evaluation_error(\n                     \"cdf(non_central_t_distribution<%1%>, %1%)\", \n                     \"Series did not converge, closest value was %1%\", sum, pol);\n               }\n            }\n            return sum;\n         }\n\n         template <class T, class Policy>\n         T non_central_t2_q(T n, T delta, T x, T y, const Policy& pol, T init_val)\n         {\n            BOOST_MATH_STD_USING\n            //\n            // Variables come first:\n            //\n            boost::uintmax_t max_iter = policies::get_max_series_iterations<Policy>();\n            T errtol = ldexp(1.0f, -boost::math::policies::digits<T, Policy>());\n            T d2 = delta * delta / 2;\n            //\n            // k is the starting point for iteration, and is the\n            // maximum of the poisson weighting term:\n            //\n            int k = boost::math::itrunc(d2);\n            // Starting Poisson weight:\n            T pois = gamma_p_derivative(T(k+1), d2, pol) \n               * tgamma_delta_ratio(T(k + 1), T(0.5f))\n               * delta / constants::root_two<T>();\n            if(pois == 0)\n               return init_val;\n            // Starting beta term:\n            T beta = x < y \n               ? ibetac(T(k + 1), n / 2, x, pol)\n               : ibeta(n / 2, T(k + 1), y, pol);\n            // Recurance term:\n            T xterm = x < y\n               ? ibeta_derivative(T(k + 1), n / 2, x, pol)\n               : ibeta_derivative(n / 2, T(k + 1), y, pol);\n            xterm *= y / (n / 2 + k);\n            T poisf(pois), betaf(beta), xtermf(xterm);\n            T sum = init_val;\n            if((xterm == 0) && (beta == 0))\n               return init_val;\n\n            //\n            // Forward recursion first, this is the stable direction:\n            //\n            boost::uintmax_t count = 0;\n            for(int i = k + 1; ; ++i)\n            {\n               poisf *= d2 / (i + 0.5f);\n               xtermf *= (x * (n / 2 + i - 1)) / (i);\n               betaf += xtermf;\n\n               T term = poisf * betaf;\n               sum += term;\n               if(fabs(term/sum) < errtol)\n                  break;\n               if(count > max_iter)\n               {\n                  return policies::raise_evaluation_error(\n                     \"cdf(non_central_t_distribution<%1%>, %1%)\", \n                     \"Series did not converge, closest value was %1%\", sum, pol);\n               }\n               ++count;\n            }\n            //\n            // Backwards recursion:\n            //\n            for(int i = k; i >= 0; --i)\n            {\n               T term = beta * pois;\n               sum += term;\n               if(fabs(term/sum) < errtol)\n                  break;\n               pois *= (i + 0.5f) / d2;\n               beta -= xterm;\n               xterm *= (i) / (x * (n / 2 + i - 1));\n               ++count;\n               if(count > max_iter)\n               {\n                  return policies::raise_evaluation_error(\n                     \"cdf(non_central_t_distribution<%1%>, %1%)\", \n                     \"Series did not converge, closest value was %1%\", sum, pol);\n               }\n            }\n            return sum;\n         }\n\n         template <class T, class Policy>\n         T non_central_t_cdf(T n, T delta, T t, bool invert, const Policy& pol)\n         {\n            //\n            // For t < 0 we have to use reflect:\n            //\n            if(t < 0)\n            {\n               t = -t;\n               delta = -delta;\n               invert = !invert;\n            }\n            //\n            // x and y are the corresponding random\n            // variables for the noncentral beta distribution,\n            // with y = 1 - x:\n            //\n            T x = t * t / (n + t * t);\n            T y = n / (n + t * t);\n            T d2 = delta * delta;\n            T a = 0.5f;\n            T b = n / 2;\n            T c = a + b + d2 / 2;\n            //\n            // Crossover point for calculating p or q is the same\n            // as for the noncentral beta:\n            //\n            T cross = 1 - (b / c) * (1 + d2 / (2 * c * c));\n            T result;\n            if(x < cross)\n            {\n               //\n               // Calculate p:\n               //\n               if(x != 0)\n               {\n                  result = non_central_beta_p(a, b, d2, x, y, pol);\n                  result = non_central_t2_p(n, delta, x, y, pol, result);\n                  result /= 2;\n               }\n               else\n                  result = 0;\n               result += cdf(boost::math::normal_distribution<T, Policy>(), -delta);\n            }\n            else\n            {\n               //\n               // Calculate q:\n               //\n               invert = !invert;\n               if(x != 0)\n               {\n                  result = non_central_beta_q(a, b, d2, x, y, pol);\n                  result = non_central_t2_q(n, delta, x, y, pol, result);\n                  result /= 2;\n               }\n               else\n                  result = cdf(complement(boost::math::normal_distribution<T, Policy>(), -delta));\n            }\n            if(invert)\n               result = 1 - result;\n            return result;\n         }\n\n         template <class T, class Policy>\n         T non_central_t_quantile(T v, T delta, T p, T q, const Policy&)\n         {\n            BOOST_MATH_STD_USING\n            static const char* function = \"quantile(non_central_t_distribution<%1%>, %1%)\";\n            typedef typename policies::evaluation<T, Policy>::type value_type;\n            typedef typename policies::normalise<\n               Policy, \n               policies::promote_float<false>, \n               policies::promote_double<false>, \n               policies::discrete_quantile<>,\n               policies::assert_undefined<> >::type forwarding_policy;\n\n               T r;\n               if(!detail::check_df(\n                  function,\n                  v, &r, Policy())\n                  ||\n               !detail::check_finite(\n                  function,\n                  delta,\n                  &r,\n                  Policy())\n                  ||\n               !detail::check_probability(\n                  function,\n                  p,\n                  &r,\n                  Policy()))\n                     return r;\n\n            value_type guess = 0;\n            if(v > 3)\n            {\n               value_type mean = delta * sqrt(v / 2) * tgamma_delta_ratio((v - 1) * 0.5f, T(0.5f));\n               value_type var = ((delta * delta + 1) * v) / (v - 2) - mean * mean;\n               if(p < q)\n                  guess = quantile(normal_distribution<value_type, forwarding_policy>(mean, var), p);\n               else\n                  guess = quantile(complement(normal_distribution<value_type, forwarding_policy>(mean, var), q));\n            }\n            //\n            // We *must* get the sign of the initial guess correct, \n            // or our root-finder will fail, so double check it now:\n            //\n            value_type pzero = non_central_t_cdf(\n               static_cast<value_type>(v), \n               static_cast<value_type>(delta), \n               static_cast<value_type>(0), \n               !(p < q), \n               forwarding_policy());\n            int s;\n            if(p < q)\n               s = boost::math::sign(p - pzero);\n            else\n               s = boost::math::sign(pzero - q);\n            if(s != boost::math::sign(guess))\n            {\n               guess = s;\n            }\n\n            value_type result = detail::generic_quantile(\n               non_central_t_distribution<value_type, forwarding_policy>(v, delta), \n               (p < q ? p : q), \n               guess, \n               (p >= q), \n               function);\n            return policies::checked_narrowing_cast<T, forwarding_policy>(\n               result, \n               function);\n         }\n\n         template <class T, class Policy>\n         T non_central_t2_pdf(T n, T delta, T x, T y, const Policy& pol, T init_val)\n         {\n            BOOST_MATH_STD_USING\n            //\n            // Variables come first:\n            //\n            boost::uintmax_t max_iter = policies::get_max_series_iterations<Policy>();\n            T errtol = ldexp(1.0f, -boost::math::policies::digits<T, Policy>());\n            T d2 = delta * delta / 2;\n            //\n            // k is the starting point for iteration, and is the\n            // maximum of the poisson weighting term:\n            //\n            int k = boost::math::itrunc(d2);\n            // Starting Poisson weight:\n            T pois = gamma_p_derivative(T(k+1), d2, pol) \n               * tgamma_delta_ratio(T(k + 1), T(0.5f))\n               * delta / constants::root_two<T>();\n            // Starting beta term:\n            T xterm = x < y\n               ? ibeta_derivative(T(k + 1), n / 2, x, pol)\n               : ibeta_derivative(n / 2, T(k + 1), y, pol);\n            T poisf(pois), xtermf(xterm);\n            T sum = init_val;\n            if((pois == 0) || (xterm == 0))\n               return init_val;\n\n            //\n            // Backwards recursion first, this is the stable\n            // direction for recursion:\n            //\n            boost::uintmax_t count = 0;\n            for(int i = k; i >= 0; --i)\n            {\n               T term = xterm * pois;\n               sum += term;\n               if((fabs(term/sum) < errtol) || (term == 0))\n                  break;\n               pois *= (i + 0.5f) / d2;\n               xterm *= (i) / (x * (n / 2 + i));\n               ++count;\n               if(count > max_iter)\n               {\n                  return policies::raise_evaluation_error(\n                     \"pdf(non_central_t_distribution<%1%>, %1%)\", \n                     \"Series did not converge, closest value was %1%\", sum, pol);\n               }\n            }\n            for(int i = k + 1; ; ++i)\n            {\n               poisf *= d2 / (i + 0.5f);\n               xtermf *= (x * (n / 2 + i)) / (i);\n               T term = poisf * xtermf;\n               sum += term;\n               if((fabs(term/sum) < errtol) || (term == 0))\n                  break;\n               ++count;\n               if(count > max_iter)\n               {\n                  return policies::raise_evaluation_error(\n                     \"pdf(non_central_t_distribution<%1%>, %1%)\", \n                     \"Series did not converge, closest value was %1%\", sum, pol);\n               }\n            }\n            return sum;\n         }\n\n         template <class T, class Policy>\n         T non_central_t_pdf(T n, T delta, T t, const Policy& pol)\n         {\n            BOOST_MATH_STD_USING\n            //\n            // For t < 0 we have to use the reflection formula:\n            //\n            if(t < 0)\n            {\n               t = -t;\n               delta = -delta;\n            }\n            if(t == 0)\n            {\n               //\n               // Handle this as a special case, using the formula\n               // from Weisstein, Eric W. \n               // \"Noncentral Student's t-Distribution.\" \n               // From MathWorld--A Wolfram Web Resource. \n               // http://mathworld.wolfram.com/NoncentralStudentst-Distribution.html \n               // \n               // The formula is simplified thanks to the relation\n               // 1F1(a,b,0) = 1.\n               //\n               return tgamma_delta_ratio(n / 2 + 0.5f, T(0.5f))\n                  * sqrt(n / constants::pi<T>()) \n                  * exp(-delta * delta / 2) / 2;\n            }\n            //\n            // x and y are the corresponding random\n            // variables for the noncentral beta distribution,\n            // with y = 1 - x:\n            //\n            T x = t * t / (n + t * t);\n            T y = n / (n + t * t);\n            T a = 0.5f;\n            T b = n / 2;\n            T d2 = delta * delta;\n            //\n            // Calculate pdf:\n            //\n            T dt = n * t / (n * n + 2 * n * t * t + t * t * t * t);\n            T result = non_central_beta_pdf(a, b, d2, x, y, pol);\n            T tol = tools::epsilon<T>() * result * 500;\n            result = non_central_t2_pdf(n, delta, x, y, pol, result);\n            if(result <= tol)\n               result = 0;\n            result *= dt;\n            return result;\n         }\n\n         template <class T, class Policy>\n         T mean(T v, T delta, const Policy& pol)\n         {\n            BOOST_MATH_STD_USING\n            return delta * sqrt(v / 2) * tgamma_delta_ratio((v - 1) * 0.5f, T(0.5f), pol);\n         }\n\n         template <class T, class Policy>\n         T variance(T v, T delta, const Policy& pol)\n         {\n            T result = ((delta * delta + 1) * v) / (v - 2);\n            T m = mean(v, delta, pol);\n            result -= m * m;\n            return result;\n         }\n\n         template <class T, class Policy>\n         T skewness(T v, T delta, const Policy& pol)\n         {\n            BOOST_MATH_STD_USING\n            T mean = boost::math::detail::mean(v, delta, pol);\n            T l2 = delta * delta;\n            T var = ((l2 + 1) * v) / (v - 2) - mean * mean;\n            T result = -2 * var;\n            result += v * (l2 + 2 * v - 3) / ((v - 3) * (v - 2));\n            result *= mean;\n            result /= pow(var, T(1.5f));\n            return result;\n         }\n\n         template <class T, class Policy>\n         T kurtosis_excess(T v, T delta, const Policy& pol)\n         {\n            BOOST_MATH_STD_USING\n            T mean = boost::math::detail::mean(v, delta, pol);\n            T l2 = delta * delta;\n            T var = ((l2 + 1) * v) / (v - 2) - mean * mean;\n            T result = -3 * var;\n            result += v * (l2 * (v + 1) + 3 * (3 * v - 5)) / ((v - 3) * (v - 2));\n            result *= -mean * mean;\n            result += v * v * (l2 * l2 + 6 * l2 + 3) / ((v - 4) * (v - 2));\n            result /= var * var;\n            return result;\n         }\n\n#if 0\n         // \n         // This code is disabled, since there can be multiple answers to the\n         // question, and it's not clear how to find the \"right\" one.\n         //\n         template <class RealType, class Policy>\n         struct t_degrees_of_freedom_finder\n         {\n            t_degrees_of_freedom_finder(\n               RealType delta_, RealType x_, RealType p_, bool c)\n               : delta(delta_), x(x_), p(p_), comp(c) {}\n\n            RealType operator()(const RealType& v)\n            {\n               non_central_t_distribution<RealType, Policy> d(v, delta);\n               return comp ?\n                  p - cdf(complement(d, x))\n                  : cdf(d, x) - p;\n            }\n         private:\n            RealType delta;\n            RealType x;\n            RealType p;\n            bool comp;\n         };\n\n         template <class RealType, class Policy>\n         inline RealType find_t_degrees_of_freedom(\n            RealType delta, RealType x, RealType p, RealType q, const Policy& pol)\n         {\n            const char* function = \"non_central_t<%1%>::find_degrees_of_freedom\";\n            if((p == 0) || (q == 0))\n            {\n               //\n               // Can't a thing if one of p and q is zero:\n               //\n               return policies::raise_evaluation_error<RealType>(function, \n                  \"Can't find degrees of freedom when the probability is 0 or 1, only possible answer is %1%\", \n                  RealType(std::numeric_limits<RealType>::quiet_NaN()), Policy());\n            }\n            t_degrees_of_freedom_finder<RealType, Policy> f(delta, x, p < q ? p : q, p < q ? false : true);\n            tools::eps_tolerance<RealType> tol(policies::digits<RealType, Policy>());\n            boost::uintmax_t max_iter = policies::get_max_root_iterations<Policy>();\n            //\n            // Pick an initial guess:\n            //\n            RealType guess = 200;\n            std::pair<RealType, RealType> ir = tools::bracket_and_solve_root(\n               f, guess, RealType(2), false, tol, max_iter, pol);\n            RealType result = ir.first + (ir.second - ir.first) / 2;\n            if(max_iter >= policies::get_max_root_iterations<Policy>())\n            {\n               policies::raise_evaluation_error<RealType>(function, \"Unable to locate solution in a reasonable time:\"\n                  \" or there is no answer to problem.  Current best guess is %1%\", result, Policy());\n            }\n            return result;\n         }\n\n         template <class RealType, class Policy>\n         struct t_non_centrality_finder\n         {\n            t_non_centrality_finder(\n               RealType v_, RealType x_, RealType p_, bool c)\n               : v(v_), x(x_), p(p_), comp(c) {}\n\n            RealType operator()(const RealType& delta)\n            {\n               non_central_t_distribution<RealType, Policy> d(v, delta);\n               return comp ?\n                  p - cdf(complement(d, x))\n                  : cdf(d, x) - p;\n            }\n         private:\n            RealType v;\n            RealType x;\n            RealType p;\n            bool comp;\n         };\n\n         template <class RealType, class Policy>\n         inline RealType find_t_non_centrality(\n            RealType v, RealType x, RealType p, RealType q, const Policy& pol)\n         {\n            const char* function = \"non_central_t<%1%>::find_t_non_centrality\";\n            if((p == 0) || (q == 0))\n            {\n               //\n               // Can't do a thing if one of p and q is zero:\n               //\n               return policies::raise_evaluation_error<RealType>(function, \n                  \"Can't find non centrality parameter when the probability is 0 or 1, only possible answer is %1%\", \n                  RealType(std::numeric_limits<RealType>::quiet_NaN()), Policy());\n            }\n            t_non_centrality_finder<RealType, Policy> f(v, x, p < q ? p : q, p < q ? false : true);\n            tools::eps_tolerance<RealType> tol(policies::digits<RealType, Policy>());\n            boost::uintmax_t max_iter = policies::get_max_root_iterations<Policy>();\n            //\n            // Pick an initial guess that we know is the right side of\n            // zero:\n            //\n            RealType guess;\n            if(f(0) < 0)\n               guess = 1;\n            else\n               guess = -1;\n            std::pair<RealType, RealType> ir = tools::bracket_and_solve_root(\n               f, guess, RealType(2), false, tol, max_iter, pol);\n            RealType result = ir.first + (ir.second - ir.first) / 2;\n            if(max_iter >= policies::get_max_root_iterations<Policy>())\n            {\n               policies::raise_evaluation_error<RealType>(function, \"Unable to locate solution in a reasonable time:\"\n                  \" or there is no answer to problem.  Current best guess is %1%\", result, Policy());\n            }\n            return result;\n         }\n#endif\n      } // namespace detail\n\n      template <class RealType = double, class Policy = policies::policy<> >\n      class non_central_t_distribution\n      {\n      public:\n         typedef RealType value_type;\n         typedef Policy policy_type;\n\n         non_central_t_distribution(RealType v_, RealType lambda) : v(v_), ncp(lambda)\n         { \n            const char* function = \"boost::math::non_central_t_distribution<%1%>::non_central_t_distribution(%1%,%1%)\";\n            RealType r;\n            detail::check_df(\n               function,\n               v, &r, Policy());\n            detail::check_finite(\n               function,\n               lambda,\n               &r,\n               Policy());\n         } // non_central_t_distribution constructor.\n\n         RealType degrees_of_freedom() const\n         { // Private data getter function.\n            return v;\n         }\n         RealType non_centrality() const\n         { // Private data getter function.\n            return ncp;\n         }\n#if 0\n         // \n         // This code is disabled, since there can be multiple answers to the\n         // question, and it's not clear how to find the \"right\" one.\n         //\n         static RealType find_degrees_of_freedom(RealType delta, RealType x, RealType p)\n         {\n            const char* function = \"non_central_t<%1%>::find_degrees_of_freedom\";\n            typedef typename policies::evaluation<RealType, Policy>::type value_type;\n            typedef typename policies::normalise<\n               Policy, \n               policies::promote_float<false>, \n               policies::promote_double<false>, \n               policies::discrete_quantile<>,\n               policies::assert_undefined<> >::type forwarding_policy;\n            value_type result = detail::find_t_degrees_of_freedom(\n               static_cast<value_type>(delta), \n               static_cast<value_type>(x), \n               static_cast<value_type>(p), \n               static_cast<value_type>(1-p), \n               forwarding_policy());\n            return policies::checked_narrowing_cast<RealType, forwarding_policy>(\n               result, \n               function);\n         }\n         template <class A, class B, class C>\n         static RealType find_degrees_of_freedom(const complemented3_type<A,B,C>& c)\n         {\n            const char* function = \"non_central_t<%1%>::find_degrees_of_freedom\";\n            typedef typename policies::evaluation<RealType, Policy>::type value_type;\n            typedef typename policies::normalise<\n               Policy, \n               policies::promote_float<false>, \n               policies::promote_double<false>, \n               policies::discrete_quantile<>,\n               policies::assert_undefined<> >::type forwarding_policy;\n            value_type result = detail::find_t_degrees_of_freedom(\n               static_cast<value_type>(c.dist), \n               static_cast<value_type>(c.param1), \n               static_cast<value_type>(1-c.param2), \n               static_cast<value_type>(c.param2), \n               forwarding_policy());\n            return policies::checked_narrowing_cast<RealType, forwarding_policy>(\n               result, \n               function);\n         }\n         static RealType find_non_centrality(RealType v, RealType x, RealType p)\n         {\n            const char* function = \"non_central_t<%1%>::find_t_non_centrality\";\n            typedef typename policies::evaluation<RealType, Policy>::type value_type;\n            typedef typename policies::normalise<\n               Policy, \n               policies::promote_float<false>, \n               policies::promote_double<false>, \n               policies::discrete_quantile<>,\n               policies::assert_undefined<> >::type forwarding_policy;\n            value_type result = detail::find_t_non_centrality(\n               static_cast<value_type>(v), \n               static_cast<value_type>(x), \n               static_cast<value_type>(p), \n               static_cast<value_type>(1-p), \n               forwarding_policy());\n            return policies::checked_narrowing_cast<RealType, forwarding_policy>(\n               result, \n               function);\n         }\n         template <class A, class B, class C>\n         static RealType find_non_centrality(const complemented3_type<A,B,C>& c)\n         {\n            const char* function = \"non_central_t<%1%>::find_t_non_centrality\";\n            typedef typename policies::evaluation<RealType, Policy>::type value_type;\n            typedef typename policies::normalise<\n               Policy, \n               policies::promote_float<false>, \n               policies::promote_double<false>, \n               policies::discrete_quantile<>,\n               policies::assert_undefined<> >::type forwarding_policy;\n            value_type result = detail::find_t_non_centrality(\n               static_cast<value_type>(c.dist), \n               static_cast<value_type>(c.param1), \n               static_cast<value_type>(1-c.param2), \n               static_cast<value_type>(c.param2), \n               forwarding_policy());\n            return policies::checked_narrowing_cast<RealType, forwarding_policy>(\n               result, \n               function);\n         }\n#endif\n      private:\n         // Data member, initialized by constructor.\n         RealType v;   // degrees of freedom\n         RealType ncp; // non-centrality parameter\n      }; // template <class RealType, class Policy> class non_central_t_distribution\n\n      typedef non_central_t_distribution<double> non_central_t; // Reserved name of type double.\n\n      // Non-member functions to give properties of the distribution.\n\n      template <class RealType, class Policy>\n      inline const std::pair<RealType, RealType> range(const non_central_t_distribution<RealType, Policy>& /* dist */)\n      { // Range of permissible values for random variable k.\n         using boost::math::tools::max_value;\n         return std::pair<RealType, RealType>(-max_value<RealType>(), max_value<RealType>());\n      }\n\n      template <class RealType, class Policy>\n      inline const std::pair<RealType, RealType> support(const non_central_t_distribution<RealType, Policy>& /* dist */)\n      { // Range of supported values for random variable k.\n         // This is range where cdf rises from 0 to 1, and outside it, the pdf is zero.\n         using boost::math::tools::max_value;\n         return std::pair<RealType, RealType>(-max_value<RealType>(), max_value<RealType>());\n      }\n\n      template <class RealType, class Policy>\n      inline RealType mode(const non_central_t_distribution<RealType, Policy>& dist)\n      { // mode.\n         static const char* function = \"mode(non_central_t_distribution<%1%> const&)\";\n         RealType v = dist.degrees_of_freedom();\n         RealType l = dist.non_centrality();\n         RealType r;\n         if(!detail::check_df(\n            function,\n            v, &r, Policy())\n            ||\n         !detail::check_finite(\n            function,\n            l,\n            &r,\n            Policy()))\n               return (RealType)r;\n\n         BOOST_MATH_STD_USING\n\n         RealType m = v < 3 ? 0 : detail::mean(v, l, Policy());\n         RealType var = v < 4 ? 1 : detail::variance(v, l, Policy());\n\n         return detail::generic_find_mode(\n            dist, \n            m,\n            function,\n            sqrt(var));\n      }\n\n      template <class RealType, class Policy>\n      inline RealType mean(const non_central_t_distribution<RealType, Policy>& dist)\n      { \n         BOOST_MATH_STD_USING\n         const char* function = \"mean(const non_central_t_distribution<%1%>&)\";\n         typedef typename policies::evaluation<RealType, Policy>::type value_type;\n         typedef typename policies::normalise<\n            Policy, \n            policies::promote_float<false>, \n            policies::promote_double<false>, \n            policies::discrete_quantile<>,\n            policies::assert_undefined<> >::type forwarding_policy;\n         RealType v = dist.degrees_of_freedom();\n         RealType l = dist.non_centrality();\n         RealType r;\n         if(!detail::check_df(\n            function,\n            v, &r, Policy())\n            ||\n         !detail::check_finite(\n            function,\n            l,\n            &r,\n            Policy()))\n               return (RealType)r;\n         if(v <= 1)\n            return policies::raise_domain_error<RealType>(\n               function, \n               \"The non central t distribution has no defined mean for degrees of freedom <= 1: got v=%1%.\", v, Policy());\n         // return l * sqrt(v / 2) * tgamma_delta_ratio((v - 1) * 0.5f, RealType(0.5f));\n         return policies::checked_narrowing_cast<RealType, forwarding_policy>(\n            detail::mean(static_cast<value_type>(v), static_cast<value_type>(l), forwarding_policy()), function);\n\n      } // mean\n\n      template <class RealType, class Policy>\n      inline RealType variance(const non_central_t_distribution<RealType, Policy>& dist)\n      { // variance.\n         const char* function = \"variance(const non_central_t_distribution<%1%>&)\";\n         typedef typename policies::evaluation<RealType, Policy>::type value_type;\n         typedef typename policies::normalise<\n            Policy, \n            policies::promote_float<false>, \n            policies::promote_double<false>, \n            policies::discrete_quantile<>,\n            policies::assert_undefined<> >::type forwarding_policy;\n         BOOST_MATH_STD_USING\n         RealType v = dist.degrees_of_freedom();\n         RealType l = dist.non_centrality();\n         RealType r;\n         if(!detail::check_df(\n            function,\n            v, &r, Policy())\n            ||\n         !detail::check_finite(\n            function,\n            l,\n            &r,\n            Policy()))\n               return (RealType)r;\n         if(v <= 2)\n            return policies::raise_domain_error<RealType>(\n               function, \n               \"The non central t distribution has no defined variance for degrees of freedom <= 2: got v=%1%.\", v, Policy());\n         return policies::checked_narrowing_cast<RealType, forwarding_policy>(\n            detail::variance(static_cast<value_type>(v), static_cast<value_type>(l), forwarding_policy()), function);\n      }\n\n      // RealType standard_deviation(const non_central_t_distribution<RealType, Policy>& dist)\n      // standard_deviation provided by derived accessors.\n\n      template <class RealType, class Policy>\n      inline RealType skewness(const non_central_t_distribution<RealType, Policy>& dist)\n      { // skewness = sqrt(l).\n         const char* function = \"skewness(const non_central_t_distribution<%1%>&)\";\n         typedef typename policies::evaluation<RealType, Policy>::type value_type;\n         typedef typename policies::normalise<\n            Policy, \n            policies::promote_float<false>, \n            policies::promote_double<false>, \n            policies::discrete_quantile<>,\n            policies::assert_undefined<> >::type forwarding_policy;\n         RealType v = dist.degrees_of_freedom();\n         RealType l = dist.non_centrality();\n         RealType r;\n         if(!detail::check_df(\n            function,\n            v, &r, Policy())\n            ||\n         !detail::check_finite(\n            function,\n            l,\n            &r,\n            Policy()))\n               return (RealType)r;\n         if(v <= 3)\n            return policies::raise_domain_error<RealType>(\n               function, \n               \"The non central t distribution has no defined skewness for degrees of freedom <= 3: got v=%1%.\", v, Policy());;\n         return policies::checked_narrowing_cast<RealType, forwarding_policy>(\n            detail::skewness(static_cast<value_type>(v), static_cast<value_type>(l), forwarding_policy()), function);\n      }\n\n      template <class RealType, class Policy>\n      inline RealType kurtosis_excess(const non_central_t_distribution<RealType, Policy>& dist)\n      { \n         const char* function = \"kurtosis_excess(const non_central_t_distribution<%1%>&)\";\n         typedef typename policies::evaluation<RealType, Policy>::type value_type;\n         typedef typename policies::normalise<\n            Policy, \n            policies::promote_float<false>, \n            policies::promote_double<false>, \n            policies::discrete_quantile<>,\n            policies::assert_undefined<> >::type forwarding_policy;\n         RealType v = dist.degrees_of_freedom();\n         RealType l = dist.non_centrality();\n         RealType r;\n         if(!detail::check_df(\n            function,\n            v, &r, Policy())\n            ||\n         !detail::check_finite(\n            function,\n            l,\n            &r,\n            Policy()))\n               return (RealType)r;\n         if(v <= 4)\n            return policies::raise_domain_error<RealType>(\n               function, \n               \"The non central t distribution has no defined kurtosis for degrees of freedom <= 4: got v=%1%.\", v, Policy());;\n         return policies::checked_narrowing_cast<RealType, forwarding_policy>(\n            detail::kurtosis_excess(static_cast<value_type>(v), static_cast<value_type>(l), forwarding_policy()), function);\n      } // kurtosis_excess\n\n      template <class RealType, class Policy>\n      inline RealType kurtosis(const non_central_t_distribution<RealType, Policy>& dist)\n      {\n         return kurtosis_excess(dist) + 3;\n      }\n\n      template <class RealType, class Policy>\n      inline RealType pdf(const non_central_t_distribution<RealType, Policy>& dist, const RealType& t)\n      { // Probability Density/Mass Function.\n         const char* function = \"cdf(non_central_t_distribution<%1%>, %1%)\";\n         typedef typename policies::evaluation<RealType, Policy>::type value_type;\n         typedef typename policies::normalise<\n            Policy, \n            policies::promote_float<false>, \n            policies::promote_double<false>, \n            policies::discrete_quantile<>,\n            policies::assert_undefined<> >::type forwarding_policy;\n\n         RealType v = dist.degrees_of_freedom();\n         RealType l = dist.non_centrality();\n         RealType r;\n         if(!detail::check_df(\n            function,\n            v, &r, Policy())\n            ||\n         !detail::check_finite(\n            function,\n            l,\n            &r,\n            Policy())\n            ||\n         !detail::check_x(\n            function,\n            t,\n            &r,\n            Policy()))\n               return (RealType)r;\n         return policies::checked_narrowing_cast<RealType, forwarding_policy>(\n            detail::non_central_t_pdf(static_cast<value_type>(v), \n               static_cast<value_type>(l), \n               static_cast<value_type>(t), \n               Policy()),\n            function);\n      } // pdf\n\n      template <class RealType, class Policy>\n      RealType cdf(const non_central_t_distribution<RealType, Policy>& dist, const RealType& x)\n      { \n         const char* function = \"boost::math::non_central_t_distribution<%1%>::cdf(%1%)\";\n         typedef typename policies::evaluation<RealType, Policy>::type value_type;\n         typedef typename policies::normalise<\n            Policy, \n            policies::promote_float<false>, \n            policies::promote_double<false>, \n            policies::discrete_quantile<>,\n            policies::assert_undefined<> >::type forwarding_policy;\n\n         RealType v = dist.degrees_of_freedom();\n         RealType l = dist.non_centrality();\n         RealType r;\n         if(!detail::check_df(\n            function,\n            v, &r, Policy())\n            ||\n         !detail::check_finite(\n            function,\n            l,\n            &r,\n            Policy())\n            ||\n         !detail::check_x(\n            function,\n            x,\n            &r,\n            Policy()))\n               return (RealType)r;\n\n         if(l == 0)\n            return cdf(students_t_distribution<RealType, Policy>(v), x);\n\n         return policies::checked_narrowing_cast<RealType, forwarding_policy>(\n            detail::non_central_t_cdf(\n               static_cast<value_type>(v), \n               static_cast<value_type>(l), \n               static_cast<value_type>(x), \n               false, Policy()),\n            function);\n      } // cdf\n\n      template <class RealType, class Policy>\n      RealType cdf(const complemented2_type<non_central_t_distribution<RealType, Policy>, RealType>& c)\n      { // Complemented Cumulative Distribution Function\n         const char* function = \"boost::math::non_central_t_distribution<%1%>::cdf(%1%)\";\n         typedef typename policies::evaluation<RealType, Policy>::type value_type;\n         typedef typename policies::normalise<\n            Policy, \n            policies::promote_float<false>, \n            policies::promote_double<false>, \n            policies::discrete_quantile<>,\n            policies::assert_undefined<> >::type forwarding_policy;\n\n         non_central_t_distribution<RealType, Policy> const& dist = c.dist;\n         RealType x = c.param;\n         RealType v = dist.degrees_of_freedom();\n         RealType l = dist.non_centrality();\n         RealType r;\n         if(!detail::check_df(\n            function,\n            v, &r, Policy())\n            ||\n         !detail::check_finite(\n            function,\n            l,\n            &r,\n            Policy())\n            ||\n         !detail::check_x(\n            function,\n            x,\n            &r,\n            Policy()))\n               return (RealType)r;\n\n         if(l == 0)\n            return cdf(complement(students_t_distribution<RealType, Policy>(v), x));\n\n         return policies::checked_narrowing_cast<RealType, forwarding_policy>(\n            detail::non_central_t_cdf(\n               static_cast<value_type>(v), \n               static_cast<value_type>(l), \n               static_cast<value_type>(x), \n               true, Policy()),\n            function);\n      } // ccdf\n\n      template <class RealType, class Policy>\n      inline RealType quantile(const non_central_t_distribution<RealType, Policy>& dist, const RealType& p)\n      { // Quantile (or Percent Point) function.\n         RealType v = dist.degrees_of_freedom();\n         RealType l = dist.non_centrality();\n         return detail::non_central_t_quantile(v, l, p, 1-p, Policy());\n      } // quantile\n\n      template <class RealType, class Policy>\n      inline RealType quantile(const complemented2_type<non_central_t_distribution<RealType, Policy>, RealType>& c)\n      { // Quantile (or Percent Point) function.\n         non_central_t_distribution<RealType, Policy> const& dist = c.dist;\n         RealType q = c.param;\n         RealType v = dist.degrees_of_freedom();\n         RealType l = dist.non_centrality();\n         return detail::non_central_t_quantile(v, l, 1-q, q, Policy());\n      } // quantile complement.\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_MATH_SPECIAL_NON_CENTRAL_T_HPP\n\n", "meta": {"hexsha": "f68efe6ce76142b35503e90f10d58bdf42227231", "size": 41281, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/math/distributions/non_central_t.hpp", "max_stars_repo_name": "mike-code/boost_1_38_0", "max_stars_repo_head_hexsha": "7ff8b2069344ea6b0b757aa1f0778dfb8526df3c", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 30.0, "max_stars_repo_stars_event_min_datetime": "2016-04-23T04:55:52.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-19T10:26:27.000Z", "max_issues_repo_path": "boost/math/distributions/non_central_t.hpp", "max_issues_repo_name": "mike-code/boost_1_38_0", "max_issues_repo_head_hexsha": "7ff8b2069344ea6b0b757aa1f0778dfb8526df3c", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2016-03-31T20:56:08.000Z", "max_issues_repo_issues_event_max_datetime": "2016-04-18T08:56:40.000Z", "max_forks_repo_path": "boost/math/distributions/non_central_t.hpp", "max_forks_repo_name": "mike-code/boost_1_38_0", "max_forks_repo_head_hexsha": "7ff8b2069344ea6b0b757aa1f0778dfb8526df3c", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 15.0, "max_forks_repo_forks_event_min_datetime": "2016-04-26T13:16:38.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-08T06:13:14.000Z", "avg_line_length": 38.6526217228, "max_line_length": 127, "alphanum_fraction": 0.5089992975, "num_tokens": 9513, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6150878555160665, "lm_q2_score": 0.5273165233795671, "lm_q1q2_score": 0.3243459895437257}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\n\n// Copyright (c) 2007-2014 Barend Gehrels, Amsterdam, the Netherlands.\n// Copyright (c) 2013-2017 Adam Wulkiewicz, Lodz, Poland.\n\n// This file was modified by Oracle on 2014-2020.\n// Modifications copyright (c) 2014-2020, Oracle and/or its affiliates.\n\n// Contributed and/or modified by Menelaos Karavelas, on behalf of Oracle\n// Contributed and/or modified by Adam Wulkiewicz, on behalf of Oracle\n\n// Use, modification and distribution is subject to the Boost Software License,\n// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n\n#ifndef BOOST_GEOMETRY_STRATEGIES_CARTESIAN_INTERSECTION_HPP\n#define BOOST_GEOMETRY_STRATEGIES_CARTESIAN_INTERSECTION_HPP\n\n#include <algorithm>\n\n#include <boost/geometry/core/exception.hpp>\n\n#include <boost/geometry/geometries/concepts/point_concept.hpp>\n#include <boost/geometry/geometries/concepts/segment_concept.hpp>\n#include <boost/geometry/geometries/segment.hpp>\n\n#include <boost/geometry/arithmetic/determinant.hpp>\n#include <boost/geometry/algorithms/detail/assign_values.hpp>\n#include <boost/geometry/algorithms/detail/assign_indexed_point.hpp>\n#include <boost/geometry/algorithms/detail/equals/point_point.hpp>\n#include <boost/geometry/algorithms/detail/recalculate.hpp>\n\n#include <boost/geometry/util/math.hpp>\n#include <boost/geometry/util/promote_integral.hpp>\n#include <boost/geometry/util/select_calculation_type.hpp>\n\n#include <boost/geometry/strategy/cartesian/area.hpp>\n#include <boost/geometry/strategy/cartesian/envelope.hpp>\n#include <boost/geometry/strategy/cartesian/expand_box.hpp>\n#include <boost/geometry/strategy/cartesian/expand_segment.hpp>\n\n#include <boost/geometry/strategies/cartesian/disjoint_box_box.hpp>\n#include <boost/geometry/strategies/cartesian/disjoint_segment_box.hpp>\n#include <boost/geometry/strategies/cartesian/distance_pythagoras.hpp>\n#include <boost/geometry/strategies/cartesian/point_in_point.hpp>\n#include <boost/geometry/strategies/cartesian/point_in_poly_winding.hpp>\n#include <boost/geometry/strategies/cartesian/side_by_triangle.hpp>\n#include <boost/geometry/strategies/covered_by.hpp>\n#include <boost/geometry/strategies/intersection.hpp>\n#include <boost/geometry/strategies/intersection_result.hpp>\n#include <boost/geometry/strategies/side.hpp>\n#include <boost/geometry/strategies/side_info.hpp>\n#include <boost/geometry/strategies/within.hpp>\n\n#include <boost/geometry/policies/robustness/rescale_policy_tags.hpp>\n#include <boost/geometry/policies/robustness/robust_point_type.hpp>\n\n\n#if defined(BOOST_GEOMETRY_DEBUG_ROBUSTNESS)\n#  include <boost/geometry/io/wkt/write.hpp>\n#endif\n\n\nnamespace boost { namespace geometry\n{\n\n\nnamespace strategy { namespace intersection\n{\n\n\n/*!\n    \\see http://mathworld.wolfram.com/Line-LineIntersection.html\n */\ntemplate\n<\n    typename CalculationType = void\n>\nstruct cartesian_segments\n{\n    typedef cartesian_tag cs_tag;\n\n    typedef side::side_by_triangle<CalculationType> side_strategy_type;\n\n    static inline side_strategy_type get_side_strategy()\n    {\n        return side_strategy_type();\n    }\n\n    template <typename Geometry1, typename Geometry2>\n    struct point_in_geometry_strategy\n    {\n        typedef strategy::within::cartesian_winding\n            <\n                typename point_type<Geometry1>::type,\n                typename point_type<Geometry2>::type,\n                CalculationType\n            > type;\n    };\n\n    template <typename Geometry1, typename Geometry2>\n    static inline typename point_in_geometry_strategy<Geometry1, Geometry2>::type\n        get_point_in_geometry_strategy()\n    {\n        typedef typename point_in_geometry_strategy\n            <\n                Geometry1, Geometry2\n            >::type strategy_type;\n        return strategy_type();\n    }\n\n    template <typename Geometry>\n    struct area_strategy\n    {\n        typedef area::cartesian\n            <\n                CalculationType\n            > type;\n    };\n\n    template <typename Geometry>\n    static inline typename area_strategy<Geometry>::type get_area_strategy()\n    {\n        typedef typename area_strategy<Geometry>::type strategy_type;\n        return strategy_type();\n    }\n\n    template <typename Geometry>\n    struct distance_strategy\n    {\n        typedef distance::pythagoras\n            <\n                CalculationType\n            > type;\n    };\n\n    template <typename Geometry>\n    static inline typename distance_strategy<Geometry>::type get_distance_strategy()\n    {\n        typedef typename distance_strategy<Geometry>::type strategy_type;\n        return strategy_type();\n    }\n\n    typedef envelope::cartesian<CalculationType> envelope_strategy_type;\n\n    static inline envelope_strategy_type get_envelope_strategy()\n    {\n        return envelope_strategy_type();\n    }\n\n    typedef expand::cartesian_segment expand_strategy_type;\n\n    static inline expand_strategy_type get_expand_strategy()\n    {\n        return expand_strategy_type();\n    }\n\n    typedef within::cartesian_point_point point_in_point_strategy_type;\n\n    static inline point_in_point_strategy_type get_point_in_point_strategy()\n    {\n        return point_in_point_strategy_type();\n    }\n\n    typedef within::cartesian_point_point equals_point_point_strategy_type;\n\n    static inline equals_point_point_strategy_type get_equals_point_point_strategy()\n    {\n        return equals_point_point_strategy_type();\n    }\n\n    typedef disjoint::cartesian_box_box disjoint_box_box_strategy_type;\n\n    static inline disjoint_box_box_strategy_type get_disjoint_box_box_strategy()\n    {\n        return disjoint_box_box_strategy_type();\n    }\n\n    typedef disjoint::segment_box disjoint_segment_box_strategy_type;\n\n    static inline disjoint_segment_box_strategy_type get_disjoint_segment_box_strategy()\n    {\n        return disjoint_segment_box_strategy_type();\n    }\n\n    typedef covered_by::cartesian_point_box disjoint_point_box_strategy_type;\n    typedef covered_by::cartesian_point_box covered_by_point_box_strategy_type;\n    typedef within::cartesian_point_box within_point_box_strategy_type;\n    typedef envelope::cartesian_box envelope_box_strategy_type;\n    typedef expand::cartesian_box expand_box_strategy_type;\n\n    template <typename CoordinateType, typename SegmentRatio>\n    struct segment_intersection_info\n    {\n    private :\n        typedef typename select_most_precise\n            <\n                CoordinateType, double\n            >::type promoted_type;\n\n        promoted_type comparable_length_a() const\n        {\n            return dx_a * dx_a + dy_a * dy_a;\n        }\n\n        promoted_type comparable_length_b() const\n        {\n            return dx_b * dx_b + dy_b * dy_b;\n        }\n\n        template <typename Point, typename Segment1, typename Segment2>\n        void assign_a(Point& point, Segment1 const& a, Segment2 const& ) const\n        {\n            assign(point, a, dx_a, dy_a, robust_ra);\n        }\n        template <typename Point, typename Segment1, typename Segment2>\n        void assign_b(Point& point, Segment1 const& , Segment2 const& b) const\n        {\n            assign(point, b, dx_b, dy_b, robust_rb);\n        }\n\n        template <typename Point, typename Segment>\n        void assign(Point& point, Segment const& segment,\n                    CoordinateType const& dx, CoordinateType const& dy,\n                    SegmentRatio const& ratio) const\n        {\n            // Calculate the intersection point based on segment_ratio\n            // Up to now, division was postponed. Here we divide using numerator/\n            // denominator. In case of integer this results in an integer\n            // division.\n            BOOST_GEOMETRY_ASSERT(ratio.denominator() != 0);\n\n            typedef typename promote_integral<CoordinateType>::type calc_type;\n\n            calc_type const numerator\n                = boost::numeric_cast<calc_type>(ratio.numerator());\n            calc_type const denominator\n                = boost::numeric_cast<calc_type>(ratio.denominator());\n            calc_type const dx_calc = boost::numeric_cast<calc_type>(dx);\n            calc_type const dy_calc = boost::numeric_cast<calc_type>(dy);\n\n            set<0>(point, get<0, 0>(segment)\n                   + boost::numeric_cast<CoordinateType>(numerator * dx_calc\n                                                         / denominator));\n            set<1>(point, get<0, 1>(segment)\n                   + boost::numeric_cast<CoordinateType>(numerator * dy_calc\n                                                         / denominator));\n        }\n\n        template <int Index, int Dim, typename Point, typename Segment>\n        static bool exceeds_side_in_dimension(Point& p, Segment const& s)\n        {\n            // Situation a (positive)\n            //     0>-------------->1     segment\n            // *                          point left of segment<I> in D x or y\n            // Situation b (negative)\n            //     1<--------------<0     segment\n            // *                          point right of segment<I>\n            // Situation c (degenerate), return false (check other dimension)\n            auto const& c = get<Dim>(p);\n            auto const& c0 = get<Index, Dim>(s);\n            auto const& c1 = get<1 - Index, Dim>(s);\n            return c0 < c1 ? math::smaller(c, c0)\n                 : c0 > c1 ? math::larger(c, c0)\n                 : false;\n        }\n\n        template <int Index, typename Point, typename Segment>\n        static bool exceeds_side_of_segment(Point& p, Segment const& s)\n        {\n            return exceeds_side_in_dimension<Index, 0>(p, s)\n                || exceeds_side_in_dimension<Index, 1>(p, s);\n        }\n\n        template <typename Point, typename Segment>\n        static void assign_if_exceeds(Point& point, Segment const& s)\n        {\n            if (exceeds_side_of_segment<0>(point, s))\n            {\n                detail::assign_point_from_index<0>(s, point);\n            }\n            else if (exceeds_side_of_segment<1>(point, s))\n            {\n                detail::assign_point_from_index<1>(s, point);\n            }\n        }\n\n    public :\n        template <typename Point, typename Segment1, typename Segment2>\n        void calculate(Point& point, Segment1 const& a, Segment2 const& b) const\n        {\n            bool use_a = true;\n\n            // Prefer one segment if one is on or near an endpoint\n            bool const a_near_end = robust_ra.near_end();\n            bool const b_near_end = robust_rb.near_end();\n            if (a_near_end && ! b_near_end)\n            {\n                use_a = true;\n            }\n            else if (b_near_end && ! a_near_end)\n            {\n                use_a = false;\n            }\n            else\n            {\n                // Prefer shorter segment\n                promoted_type const len_a = comparable_length_a();\n                promoted_type const len_b = comparable_length_b();\n                if (len_b < len_a)\n                {\n                    use_a = false;\n                }\n                // else use_a is true but was already assigned like that\n            }\n\n            if (use_a)\n            {\n                assign_a(point, a, b);\n            }\n            else\n            {\n                assign_b(point, a, b);\n            }\n\n#if defined(BOOST_GEOMETRY_USE_RESCALING)\n            return;\n#endif\n\n            // Verify nearly collinear cases (the threshold is arbitrary\n            // but influences performance). If the intersection is located\n            // outside the segments, then it should be moved.\n            if (robust_ra.possibly_collinear(1.0e-3)\n                && robust_rb.possibly_collinear(1.0e-3))\n            {\n                // The segments are nearly collinear and because of the calculation\n                // method with very small denominator, the IP appears outside the\n                // segment(s). Correct it to the end point.\n                // Because they are nearly collinear, it doesn't really matter to\n                // to which endpoint (or it is corrected twice).\n                assign_if_exceeds(point, a);\n                assign_if_exceeds(point, b);\n            }\n        }\n\n        CoordinateType dx_a, dy_a;\n        CoordinateType dx_b, dy_b;\n        SegmentRatio robust_ra;\n        SegmentRatio robust_rb;\n    };\n\n    template <typename D, typename W, typename ResultType>\n    static inline void cramers_rule(D const& dx_a, D const& dy_a,\n        D const& dx_b, D const& dy_b, W const& wx, W const& wy,\n        // out:\n        ResultType& nominator, ResultType& denominator)\n    {\n        // Cramers rule\n        nominator = geometry::detail::determinant<ResultType>(dx_b, dy_b, wx, wy);\n        denominator = geometry::detail::determinant<ResultType>(dx_a, dy_a, dx_b, dy_b);\n        // Ratio r = nominator/denominator\n        // Collinear if denominator == 0, intersecting if 0 <= r <= 1\n        // IntersectionPoint = (x1 + r * dx_a, y1 + r * dy_a)\n    }\n\n    // Version for non-rescaled policies\n    template\n    <\n        typename UniqueSubRange1,\n        typename UniqueSubRange2,\n        typename Policy\n    >\n    static inline typename Policy::return_type\n        apply(UniqueSubRange1 const& range_p,\n              UniqueSubRange2 const& range_q,\n              Policy const& policy)\n    {\n        // Pass the same ranges both as normal ranges and as modelled ranges\n        return apply(range_p, range_q, policy, range_p, range_q);\n    }\n\n    // Version for non rescaled versions.\n    // The \"modelled\" parameter might be rescaled (will be removed later)\n    template\n    <\n        typename UniqueSubRange1,\n        typename UniqueSubRange2,\n        typename Policy,\n        typename ModelledUniqueSubRange1,\n        typename ModelledUniqueSubRange2\n    >\n    static inline typename Policy::return_type\n        apply(UniqueSubRange1 const& range_p,\n              UniqueSubRange2 const& range_q,\n              Policy const& policy,\n              ModelledUniqueSubRange1 const& modelled_range_p,\n              ModelledUniqueSubRange2 const& modelled_range_q)\n    {\n        typedef typename UniqueSubRange1::point_type point1_type;\n        typedef typename UniqueSubRange2::point_type point2_type;\n\n        BOOST_CONCEPT_ASSERT( (concepts::ConstPoint<point1_type>) );\n        BOOST_CONCEPT_ASSERT( (concepts::ConstPoint<point2_type>) );\n\n        point1_type const& p1 = range_p.at(0);\n        point1_type const& p2 = range_p.at(1);\n        point2_type const& q1 = range_q.at(0);\n        point2_type const& q2 = range_q.at(1);\n\n        // Declare segments, currently necessary for the policies\n        // (segment_crosses, segment_colinear, degenerate, one_degenerate, etc)\n        model::referring_segment<point1_type const> const p(p1, p2);\n        model::referring_segment<point2_type const> const q(q1, q2);\n\n        typedef typename select_most_precise\n            <\n                typename geometry::coordinate_type<typename ModelledUniqueSubRange1::point_type>::type,\n                typename geometry::coordinate_type<typename ModelledUniqueSubRange1::point_type>::type\n            >::type modelled_coordinate_type;\n\n        typedef segment_ratio<modelled_coordinate_type> ratio_type;\n        segment_intersection_info\n            <\n                typename select_calculation_type<point1_type, point2_type, CalculationType>::type,\n                ratio_type\n            > sinfo;\n\n        sinfo.dx_a = get<0>(p2) - get<0>(p1); // distance in x-dir\n        sinfo.dx_b = get<0>(q2) - get<0>(q1);\n        sinfo.dy_a = get<1>(p2) - get<1>(p1); // distance in y-dir\n        sinfo.dy_b = get<1>(q2) - get<1>(q1);\n\n        return unified<ratio_type>(sinfo, p, q, policy, modelled_range_p, modelled_range_q);\n    }\n\n    //! Returns true if two segments do not overlap.\n    //! If not, then no further calculations need to be done.\n    template\n    <\n        std::size_t Dimension,\n        typename PointP,\n        typename PointQ\n    >\n    static inline bool disjoint_by_range(PointP const& p1, PointP const& p2,\n                                         PointQ const& q1, PointQ const& q2)\n    {\n        auto minp = get<Dimension>(p1);\n        auto maxp = get<Dimension>(p2);\n        auto minq = get<Dimension>(q1);\n        auto maxq = get<Dimension>(q2);\n        if (minp > maxp)\n        {\n            std::swap(minp, maxp);\n        }\n        if (minq > maxq)\n        {\n            std::swap(minq, maxq);\n        }\n\n        // In this case, max(p) < min(q)\n        //     P         Q\n        // <-------> <------->\n        // (and the space in between is not extremely small)\n        return math::smaller(maxp, minq) || math::smaller(maxq, minp);\n    }\n\n    // Implementation for either rescaled or non rescaled versions.\n    template\n    <\n        typename RatioType,\n        typename SegmentInfo,\n        typename Segment1,\n        typename Segment2,\n        typename Policy,\n        typename UniqueSubRange1,\n        typename UniqueSubRange2\n    >\n    static inline typename Policy::return_type\n        unified(SegmentInfo& sinfo,\n                Segment1 const& p, Segment2 const& q, Policy const&,\n                UniqueSubRange1 const& range_p,\n                UniqueSubRange2 const& range_q)\n    {\n        typedef typename UniqueSubRange1::point_type point1_type;\n        typedef typename UniqueSubRange2::point_type point2_type;\n        typedef typename select_most_precise\n            <\n                typename geometry::coordinate_type<point1_type>::type,\n                typename geometry::coordinate_type<point2_type>::type\n            >::type coordinate_type;\n\n        point1_type const& p1 = range_p.at(0);\n        point1_type const& p2 = range_p.at(1);\n        point2_type const& q1 = range_q.at(0);\n        point2_type const& q2 = range_q.at(1);\n\n        bool const p_is_point = equals_point_point(p1, p2);\n        bool const q_is_point = equals_point_point(q1, q2);\n\n        if (p_is_point && q_is_point)\n        {\n            return equals_point_point(p1, q2)\n                ? Policy::degenerate(p, true)\n                : Policy::disjoint()\n                ;\n        }\n\n        if (disjoint_by_range<0>(p1, p2, q1, q2)\n         || disjoint_by_range<1>(p1, p2, q1, q2))\n        {\n            return Policy::disjoint();\n        }\n\n        side_info sides;\n        sides.set<0>(side_strategy_type::apply(q1, q2, p1),\n                     side_strategy_type::apply(q1, q2, p2));\n\n        if (sides.same<0>())\n        {\n            // Both points are at same side of other segment, we can leave\n            return Policy::disjoint();\n        }\n\n        sides.set<1>(side_strategy_type::apply(p1, p2, q1),\n                     side_strategy_type::apply(p1, p2, q2));\n        \n        if (sides.same<1>())\n        {\n            // Both points are at same side of other segment, we can leave\n            return Policy::disjoint();\n        }\n\n        bool collinear = sides.collinear();\n\n        // Calculate the differences again\n        // (for rescaled version, this is different from dx_p etc)\n        coordinate_type const dx_p = get<0>(p2) - get<0>(p1);\n        coordinate_type const dx_q = get<0>(q2) - get<0>(q1);\n        coordinate_type const dy_p = get<1>(p2) - get<1>(p1);\n        coordinate_type const dy_q = get<1>(q2) - get<1>(q1);\n\n        // r: ratio 0-1 where intersection divides A/B\n        // (only calculated for non-collinear segments)\n        if (! collinear)\n        {\n            coordinate_type denominator_a, nominator_a;\n            coordinate_type denominator_b, nominator_b;\n\n            cramers_rule(dx_p, dy_p, dx_q, dy_q,\n                get<0>(p1) - get<0>(q1),\n                get<1>(p1) - get<1>(q1),\n                nominator_a, denominator_a);\n\n            cramers_rule(dx_q, dy_q, dx_p, dy_p,\n                get<0>(q1) - get<0>(p1),\n                get<1>(q1) - get<1>(p1),\n                nominator_b, denominator_b);\n\n            math::detail::equals_factor_policy<coordinate_type>\n                policy(dx_p, dy_p, dx_q, dy_q);\n\n            coordinate_type const zero = 0;\n            if (math::detail::equals_by_policy(denominator_a, zero, policy)\n             || math::detail::equals_by_policy(denominator_b, zero, policy))\n            {\n                // If this is the case, no rescaling is done for FP precision.\n                // We set it to collinear, but it indicates a robustness issue.\n                sides.set<0>(0, 0);\n                sides.set<1>(0, 0);\n                collinear = true;\n            }\n            else\n            {\n                sinfo.robust_ra.assign(nominator_a, denominator_a);\n                sinfo.robust_rb.assign(nominator_b, denominator_b);\n            }\n        }\n\n        if (collinear)\n        {\n            std::pair<bool, bool> const collinear_use_first\n                    = is_x_more_significant(geometry::math::abs(dx_p),\n                                            geometry::math::abs(dy_p),\n                                            geometry::math::abs(dx_q),\n                                            geometry::math::abs(dy_q),\n                                            p_is_point, q_is_point);\n\n            if (collinear_use_first.second)\n            {\n                // Degenerate cases: segments of single point, lying on other segment, are not disjoint\n                // This situation is collinear too\n\n                if (collinear_use_first.first)\n                {\n                    return relate_collinear<0, Policy, RatioType>(p, q,\n                            p1, p2, q1, q2,\n                            p_is_point, q_is_point);\n                }\n                else\n                {\n                    // Y direction contains larger segments (maybe dx is zero)\n                    return relate_collinear<1, Policy, RatioType>(p, q,\n                            p1, p2, q1, q2,\n                            p_is_point, q_is_point);\n                }\n            }\n        }\n\n        return Policy::segments_crosses(sides, sinfo, p, q);\n    }\n\nprivate:\n    // first is true if x is more significant\n    // second is true if the more significant difference is not 0\n    template <typename CoordinateType>\n    static inline std::pair<bool, bool>\n        is_x_more_significant(CoordinateType const& abs_dx_a,\n                              CoordinateType const& abs_dy_a,\n                              CoordinateType const& abs_dx_b,\n                              CoordinateType const& abs_dy_b,\n                              bool const a_is_point,\n                              bool const b_is_point)\n    {\n        //BOOST_GEOMETRY_ASSERT_MSG(!(a_is_point && b_is_point), \"both segments shouldn't be degenerated\");\n\n        // for degenerated segments the second is always true because this function\n        // shouldn't be called if both segments were degenerated\n\n        if (a_is_point)\n        {\n            return std::make_pair(abs_dx_b >= abs_dy_b, true);\n        }\n        else if (b_is_point)\n        {\n            return std::make_pair(abs_dx_a >= abs_dy_a, true);\n        }\n        else\n        {\n            CoordinateType const min_dx = (std::min)(abs_dx_a, abs_dx_b);\n            CoordinateType const min_dy = (std::min)(abs_dy_a, abs_dy_b);\n            return min_dx == min_dy ?\n                    std::make_pair(true, min_dx > CoordinateType(0)) :\n                    std::make_pair(min_dx > min_dy, true);\n        }\n    }\n\n    template\n    <\n        std::size_t Dimension,\n        typename Policy,\n        typename RatioType,\n        typename Segment1,\n        typename Segment2,\n        typename RobustPoint1,\n        typename RobustPoint2\n    >\n    static inline typename Policy::return_type\n        relate_collinear(Segment1 const& a,\n                         Segment2 const& b,\n                         RobustPoint1 const& robust_a1, RobustPoint1 const& robust_a2,\n                         RobustPoint2 const& robust_b1, RobustPoint2 const& robust_b2,\n                         bool a_is_point, bool b_is_point)\n    {\n        if (a_is_point)\n        {\n            return relate_one_degenerate<Policy, RatioType>(a,\n                get<Dimension>(robust_a1),\n                get<Dimension>(robust_b1), get<Dimension>(robust_b2),\n                true);\n        }\n        if (b_is_point)\n        {\n            return relate_one_degenerate<Policy, RatioType>(b,\n                get<Dimension>(robust_b1),\n                get<Dimension>(robust_a1), get<Dimension>(robust_a2),\n                false);\n        }\n        return relate_collinear<Policy, RatioType>(a, b,\n                                get<Dimension>(robust_a1),\n                                get<Dimension>(robust_a2),\n                                get<Dimension>(robust_b1),\n                                get<Dimension>(robust_b2));\n    }\n\n    /// Relate segments known collinear\n    template\n    <\n        typename Policy,\n        typename RatioType,\n        typename Segment1,\n        typename Segment2,\n        typename Type1,\n        typename Type2\n    >\n    static inline typename Policy::return_type\n        relate_collinear(Segment1 const& a, Segment2 const& b,\n                         Type1 oa_1, Type1 oa_2,\n                         Type2 ob_1, Type2 ob_2)\n    {\n        // Calculate the ratios where a starts in b, b starts in a\n        //         a1--------->a2         (2..7)\n        //                b1----->b2      (5..8)\n        // length_a: 7-2=5\n        // length_b: 8-5=3\n        // b1 is located w.r.t. a at ratio: (5-2)/5=3/5 (on a)\n        // b2 is located w.r.t. a at ratio: (8-2)/5=6/5 (right of a)\n        // a1 is located w.r.t. b at ratio: (2-5)/3=-3/3 (left of b)\n        // a2 is located w.r.t. b at ratio: (7-5)/3=2/3 (on b)\n        // A arrives (a2 on b), B departs (b1 on a)\n\n        // If both are reversed:\n        //         a2<---------a1         (7..2)\n        //                b2<-----b1      (8..5)\n        // length_a: 2-7=-5\n        // length_b: 5-8=-3\n        // b1 is located w.r.t. a at ratio: (8-7)/-5=-1/5 (before a starts)\n        // b2 is located w.r.t. a at ratio: (5-7)/-5=2/5 (on a)\n        // a1 is located w.r.t. b at ratio: (7-8)/-3=1/3 (on b)\n        // a2 is located w.r.t. b at ratio: (2-8)/-3=6/3 (after b ends)\n\n        // If both one is reversed:\n        //         a1--------->a2         (2..7)\n        //                b2<-----b1      (8..5)\n        // length_a: 7-2=+5\n        // length_b: 5-8=-3\n        // b1 is located w.r.t. a at ratio: (8-2)/5=6/5 (after a ends)\n        // b2 is located w.r.t. a at ratio: (5-2)/5=3/5 (on a)\n        // a1 is located w.r.t. b at ratio: (2-8)/-3=6/3 (after b ends)\n        // a2 is located w.r.t. b at ratio: (7-8)/-3=1/3 (on b)\n        Type1 const length_a = oa_2 - oa_1; // no abs, see above\n        Type2 const length_b = ob_2 - ob_1;\n\n        RatioType ra_from(oa_1 - ob_1, length_b);\n        RatioType ra_to(oa_2 - ob_1, length_b);\n        RatioType rb_from(ob_1 - oa_1, length_a);\n        RatioType rb_to(ob_2 - oa_1, length_a);\n\n        // use absolute measure to detect endpoints intersection\n        // NOTE: it'd be possible to calculate bx_wrt_a using ax_wrt_b values\n        int const a1_wrt_b = position_value(oa_1, ob_1, ob_2);\n        int const a2_wrt_b = position_value(oa_2, ob_1, ob_2);\n        int const b1_wrt_a = position_value(ob_1, oa_1, oa_2);\n        int const b2_wrt_a = position_value(ob_2, oa_1, oa_2);\n        \n        // fix the ratios if necessary\n        // CONSIDER: fixing ratios also in other cases, if they're inconsistent\n        // e.g. if ratio == 1 or 0 (so IP at the endpoint)\n        // but position value indicates that the IP is in the middle of the segment\n        // because one of the segments is very long\n        // In such case the ratios could be moved into the middle direction\n        // by some small value (e.g. EPS+1ULP)\n        if (a1_wrt_b == 1)\n        {\n            ra_from.assign(0, 1);\n            rb_from.assign(0, 1);\n        }\n        else if (a1_wrt_b == 3)\n        {\n            ra_from.assign(1, 1);\n            rb_to.assign(0, 1);\n        } \n\n        if (a2_wrt_b == 1)\n        {\n            ra_to.assign(0, 1);\n            rb_from.assign(1, 1);\n        }\n        else if (a2_wrt_b == 3)\n        {\n            ra_to.assign(1, 1);\n            rb_to.assign(1, 1);\n        }\n\n        if ((a1_wrt_b < 1 && a2_wrt_b < 1) || (a1_wrt_b > 3 && a2_wrt_b > 3))\n        //if ((ra_from.left() && ra_to.left()) || (ra_from.right() && ra_to.right()))\n        {\n            return Policy::disjoint();\n        }\n\n        bool const opposite = math::sign(length_a) != math::sign(length_b);\n\n        return Policy::segments_collinear(a, b, opposite,\n                                          a1_wrt_b, a2_wrt_b, b1_wrt_a, b2_wrt_a,\n                                          ra_from, ra_to, rb_from, rb_to);\n    }\n\n    /// Relate segments where one is degenerate\n    template\n    <\n        typename Policy,\n        typename RatioType,\n        typename DegenerateSegment,\n        typename Type1,\n        typename Type2\n    >\n    static inline typename Policy::return_type\n        relate_one_degenerate(DegenerateSegment const& degenerate_segment,\n                              Type1 d, Type2 s1, Type2 s2,\n                              bool a_degenerate)\n    {\n        // Calculate the ratios where ds starts in s\n        //         a1--------->a2         (2..6)\n        //              b1/b2      (4..4)\n        // Ratio: (4-2)/(6-2)\n        RatioType const ratio(d - s1, s2 - s1);\n\n        if (!ratio.on_segment())\n        {\n            return Policy::disjoint();\n        }\n\n        return Policy::one_degenerate(degenerate_segment, ratio, a_degenerate);\n    }\n\n    template <typename ProjCoord1, typename ProjCoord2>\n    static inline int position_value(ProjCoord1 const& ca1,\n                                     ProjCoord2 const& cb1,\n                                     ProjCoord2 const& cb2)\n    {\n        // S1x  0   1    2     3   4\n        // S2       |---------->\n        return math::equals(ca1, cb1) ? 1\n             : math::equals(ca1, cb2) ? 3\n             : cb1 < cb2 ?\n                ( ca1 < cb1 ? 0\n                : ca1 > cb2 ? 4\n                : 2 )\n              : ( ca1 > cb1 ? 0\n                : ca1 < cb2 ? 4\n                : 2 );\n    }\n\n    template <typename Point1, typename Point2>\n    static inline bool equals_point_point(Point1 const& point1, Point2 const& point2)\n    {\n        return strategy::within::cartesian_point_point::apply(point1, point2);\n    }\n};\n\n\n#ifndef DOXYGEN_NO_STRATEGY_SPECIALIZATIONS\nnamespace services\n{\n\ntemplate <typename CalculationType>\nstruct default_strategy<cartesian_tag, CalculationType>\n{\n    typedef cartesian_segments<CalculationType> type;\n};\n\n} // namespace services\n#endif // DOXYGEN_NO_STRATEGY_SPECIALIZATIONS\n\n\n}} // namespace strategy::intersection\n\nnamespace strategy\n{\n\nnamespace within { namespace services\n{\n\ntemplate <typename Geometry1, typename Geometry2, typename AnyTag1, typename AnyTag2>\nstruct default_strategy<Geometry1, Geometry2, AnyTag1, AnyTag2, linear_tag, linear_tag, cartesian_tag, cartesian_tag>\n{\n    typedef strategy::intersection::cartesian_segments<> type;\n};\n\ntemplate <typename Geometry1, typename Geometry2, typename AnyTag1, typename AnyTag2>\nstruct default_strategy<Geometry1, Geometry2, AnyTag1, AnyTag2, linear_tag, polygonal_tag, cartesian_tag, cartesian_tag>\n{\n    typedef strategy::intersection::cartesian_segments<> type;\n};\n\ntemplate <typename Geometry1, typename Geometry2, typename AnyTag1, typename AnyTag2>\nstruct default_strategy<Geometry1, Geometry2, AnyTag1, AnyTag2, polygonal_tag, linear_tag, cartesian_tag, cartesian_tag>\n{\n    typedef strategy::intersection::cartesian_segments<> type;\n};\n\ntemplate <typename Geometry1, typename Geometry2, typename AnyTag1, typename AnyTag2>\nstruct default_strategy<Geometry1, Geometry2, AnyTag1, AnyTag2, polygonal_tag, polygonal_tag, cartesian_tag, cartesian_tag>\n{\n    typedef strategy::intersection::cartesian_segments<> type;\n};\n\n}} // within::services\n\nnamespace covered_by { namespace services\n{\n\ntemplate <typename Geometry1, typename Geometry2, typename AnyTag1, typename AnyTag2>\nstruct default_strategy<Geometry1, Geometry2, AnyTag1, AnyTag2, linear_tag, linear_tag, cartesian_tag, cartesian_tag>\n{\n    typedef strategy::intersection::cartesian_segments<> type;\n};\n\ntemplate <typename Geometry1, typename Geometry2, typename AnyTag1, typename AnyTag2>\nstruct default_strategy<Geometry1, Geometry2, AnyTag1, AnyTag2, linear_tag, polygonal_tag, cartesian_tag, cartesian_tag>\n{\n    typedef strategy::intersection::cartesian_segments<> type;\n};\n\ntemplate <typename Geometry1, typename Geometry2, typename AnyTag1, typename AnyTag2>\nstruct default_strategy<Geometry1, Geometry2, AnyTag1, AnyTag2, polygonal_tag, linear_tag, cartesian_tag, cartesian_tag>\n{\n    typedef strategy::intersection::cartesian_segments<> type;\n};\n\ntemplate <typename Geometry1, typename Geometry2, typename AnyTag1, typename AnyTag2>\nstruct default_strategy<Geometry1, Geometry2, AnyTag1, AnyTag2, polygonal_tag, polygonal_tag, cartesian_tag, cartesian_tag>\n{\n    typedef strategy::intersection::cartesian_segments<> type;\n};\n\n}} // within::services\n\n} // strategy\n\n}} // namespace boost::geometry\n\n\n#endif // BOOST_GEOMETRY_STRATEGIES_CARTESIAN_INTERSECTION_HPP\n", "meta": {"hexsha": "a3ac28f95159cd697a2044df26228963d4401bc3", "size": 33315, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/geometry/strategies/cartesian/intersection.hpp", "max_stars_repo_name": "pranavgo/RRT", "max_stars_repo_head_hexsha": "87148c3ddb91600f4e74f00ffa8af14b54689aa4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "boost/geometry/strategies/cartesian/intersection.hpp", "max_issues_repo_name": "pranavgo/RRT", "max_issues_repo_head_hexsha": "87148c3ddb91600f4e74f00ffa8af14b54689aa4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "boost/geometry/strategies/cartesian/intersection.hpp", "max_forks_repo_name": "pranavgo/RRT", "max_forks_repo_head_hexsha": "87148c3ddb91600f4e74f00ffa8af14b54689aa4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.0551948052, "max_line_length": 123, "alphanum_fraction": 0.5976587123, "num_tokens": 7884, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7279754489059774, "lm_q2_score": 0.4455295350395727, "lm_q1q2_score": 0.32433456327130433}}
{"text": "/* Author: Wolfgang Bangerth, Texas A&M University, 2006, 2007 */\n\n/*    $Id: step-27.cc 27657 2012-11-21 13:19:08Z bangerth $       */\n/*                                                                */\n/*    Copyright (C) 2006-2012 by the deal.II authors */\n/*                                                                */\n/*    This file is subject to QPL and may not be  distributed     */\n/*    without copyright and license information. Please refer     */\n/*    to the file deal.II/doc/license.html for the  text  and     */\n/*    further information on this license.                        */\n\n// @sect3{Include files}\n\n// The first few files have already been covered in previous examples and will\n// thus not be further commented on.\n#include <deal.II/base/quadrature_lib.h>\n#include <deal.II/base/function.h>\n#include <deal.II/base/logstream.h>\n#include <deal.II/base/utilities.h>\n#include <deal.II/lac/vector.h>\n#include <deal.II/lac/full_matrix.h>\n#include <deal.II/lac/sparse_matrix.h>\n#include <deal.II/lac/solver_cg.h>\n#include <deal.II/lac/precondition.h>\n#include <deal.II/lac/constraint_matrix.h>\n#include <deal.II/grid/tria.h>\n#include <deal.II/grid/grid_generator.h>\n#include <deal.II/grid/tria_accessor.h>\n#include <deal.II/grid/tria_iterator.h>\n#include <deal.II/grid/grid_refinement.h>\n#include <deal.II/dofs/dof_accessor.h>\n#include <deal.II/dofs/dof_tools.h>\n#include <deal.II/fe/fe_q.h>\n#include <deal.II/numerics/vector_tools.h>\n#include <deal.II/numerics/matrix_tools.h>\n#include <deal.II/numerics/data_out.h>\n#include <deal.II/numerics/error_estimator.h>\n\n// These are the new files we need. The first one provides an alternative to\n// the usual SparsityPattern class and the CompressedSparsityPattern class\n// already discussed in step-11 and step-18. The last two provide <i>hp</i>\n// versions of the DoFHandler and FEValues classes as described in the\n// introduction of this program.\n#include <deal.II/lac/compressed_set_sparsity_pattern.h>\n#include <deal.II/hp/dof_handler.h>\n#include <deal.II/hp/fe_values.h>\n\n// The last set of include files are standard C++ headers. We need support for\n// complex numbers when we compute the Fourier transform.\n#include <fstream>\n#include <iostream>\n#include <complex>\n\n\n// Finally, this is as in previous programs:\nnamespace Step27\n{\n  using namespace dealii;\n\n\n  // @sect3{The main class}\n\n  // The main class of this program looks very much like the one already used\n  // in the first few tutorial programs, for example the one in step-6. The\n  // main difference is that we have merged the refine_grid and output_results\n  // functions into one since we will also want to output some of the\n  // quantities used in deciding how to refine the mesh (in particular the\n  // estimated smoothness of the solution). There is also a function that\n  // computes this estimated smoothness, as discussed in the introduction.\n  //\n  // As far as member variables are concerned, we use the same structure as\n  // already used in step-6, but instead of a regular DoFHandler we use an\n  // object of type hp::DoFHandler, and we need collections instead of\n  // individual finite element, quadrature, and face quadrature objects. We\n  // will fill these collections in the constructor of the class. The last\n  // variable, <code>max_degree</code>, indicates the maximal polynomial\n  // degree of shape functions used.\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 create_coarse_grid ();\n    void estimate_smoothness (Vector<float> &smoothness_indicators) const;\n    void postprocess (const unsigned int cycle);\n\n    Triangulation<dim>   triangulation;\n\n    hp::DoFHandler<dim>      dof_handler;\n    hp::FECollection<dim>    fe_collection;\n    hp::QCollection<dim>     quadrature_collection;\n    hp::QCollection<dim-1>   face_quadrature_collection;\n\n    ConstraintMatrix     constraints;\n\n    SparsityPattern      sparsity_pattern;\n    SparseMatrix<double> system_matrix;\n\n    Vector<double>       solution;\n    Vector<double>       system_rhs;\n\n    const unsigned int max_degree;\n  };\n\n\n\n  // @sect3{Equation data}\n  //\n  // Next, let us define the right hand side function for this problem. It is\n  // $x+1$ in 1d, $(x+1)(y+1)$ in 2d, and so on.\n  template <int dim>\n  class RightHandSide : public Function<dim>\n  {\n  public:\n    RightHandSide () : Function<dim> () {}\n\n    virtual double value (const Point<dim>   &p,\n                          const unsigned int  component) const;\n  };\n\n\n  template <int dim>\n  double\n  RightHandSide<dim>::value (const Point<dim>   &p,\n                             const unsigned int  /*component*/) const\n  {\n    double product = 1;\n    for (unsigned int d=0; d<dim; ++d)\n      product *= (p[d]+1);\n    return product;\n  }\n\n\n\n\n  // @sect3{Implementation of the main class}\n\n  // @sect4{LaplaceProblem::LaplaceProblem}\n\n  // The constructor of this class is fairly straightforward. It associates\n  // the hp::DoFHandler object with the triangulation, and then sets the\n  // maximal polynomial degree to 7 (in 1d and 2d) or 5 (in 3d and higher). We\n  // do so because using higher order polynomial degrees becomes prohibitively\n  // expensive, especially in higher space dimensions.\n  //\n  // Following this, we fill the collections of finite element, and cell and\n  // face quadrature objects. We start with quadratic elements, and each\n  // quadrature formula is chosen so that it is appropriate for the matching\n  // finite element in the hp::FECollection object.\n  template <int dim>\n  LaplaceProblem<dim>::LaplaceProblem ()\n    :\n    dof_handler (triangulation),\n    max_degree (dim <= 2 ? 7 : 5)\n  {\n    for (unsigned int degree=2; degree<=max_degree; ++degree)\n      {\n        fe_collection.push_back (FE_Q<dim>(degree));\n        quadrature_collection.push_back (QGauss<dim>(degree+1));\n        face_quadrature_collection.push_back (QGauss<dim-1>(degree+1));\n      }\n  }\n\n\n  // @sect4{LaplaceProblem::~LaplaceProblem}\n\n  // The destructor is unchanged from what we already did in step-6:\n  template <int dim>\n  LaplaceProblem<dim>::~LaplaceProblem ()\n  {\n    dof_handler.clear ();\n  }\n\n\n  // @sect4{LaplaceProblem::setup_system}\n  //\n  // This function is again an almost verbatim copy of what we already did in\n  // step-6. The first change is that we append the Dirichlet boundary\n  // conditions to the ConstraintMatrix object, which we consequently call\n  // just <code>constraints</code> instead of\n  // <code>hanging_node_constraints</code>. The second difference is that we\n  // don't directly build the sparsity pattern, but first create an\n  // intermediate object that we later copy into the usual SparsityPattern\n  // data structure, since this is more efficient for the problem with many\n  // entries per row (and different number of entries in different rows). In\n  // another slight deviation, we do not first build the sparsity pattern and\n  // then condense away constrained degrees of freedom, but pass the\n  // constraint matrix object directly to the function that builds the\n  // sparsity pattern. We disable the insertion of constrained entries with\n  // <tt>false</tt> as fourth argument in the DoFTools::make_sparsity_pattern\n  // function. All of these changes are explained in the introduction of this\n  // program.\n  //\n  // The last change, maybe hidden in plain sight, is that the dof_handler\n  // variable here is an hp object -- nevertheless all the function calls we\n  // had before still work in exactly the same way as they always did.\n  template <int dim>\n  void LaplaceProblem<dim>::setup_system ()\n  {\n    dof_handler.distribute_dofs (fe_collection);\n\n    solution.reinit (dof_handler.n_dofs());\n    system_rhs.reinit (dof_handler.n_dofs());\n\n    constraints.clear ();\n    DoFTools::make_hanging_node_constraints (dof_handler,\n                                             constraints);\n    VectorTools::interpolate_boundary_values (dof_handler,\n                                              0,\n                                              ZeroFunction<dim>(),\n                                              constraints);\n    constraints.close ();\n\n    CompressedSetSparsityPattern csp (dof_handler.n_dofs(),\n                                      dof_handler.n_dofs());\n    DoFTools::make_sparsity_pattern (dof_handler, csp, constraints, false);\n    sparsity_pattern.copy_from (csp);\n\n    system_matrix.reinit (sparsity_pattern);\n  }\n\n\n\n  // @sect4{LaplaceProblem::assemble_system}\n\n  // This is the function that assembles the global matrix and right hand side\n  // vector from the local contributions of each cell. Its main working is as\n  // has been described in many of the tutorial programs before. The\n  // significant deviations are the ones necessary for <i>hp</i> finite\n  // element methods. In particular, that we need to use a collection of\n  // FEValues object (implemented through the hp::FEValues class), and that we\n  // have to eliminate constrained degrees of freedom already when copying\n  // local contributions into global objects. Both of these are explained in\n  // detail in the introduction of this program.\n  //\n  // One other slight complication is the fact that because we use different\n  // polynomial degrees on different cells, the matrices and vectors holding\n  // local contributions do not have the same size on all cells. At the\n  // beginning of the loop over all cells, we therefore each time have to\n  // resize them to the correct size (given by\n  // <code>dofs_per_cell</code>). Because these classes are implement in such\n  // a way that reducing the size of a matrix or vector does not release the\n  // currently allocated memory (unless the new size is zero), the process of\n  // resizing at the beginning of the loop will only require re-allocation of\n  // memory during the first few iterations. Once we have found in a cell with\n  // the maximal finite element degree, no more re-allocations will happen\n  // because all subsequent <code>reinit</code> calls will only set the size\n  // to something that fits the currently allocated memory. This is important\n  // since allocating memory is expensive, and doing so every time we visit a\n  // new cell would take significant compute time.\n  template <int dim>\n  void LaplaceProblem<dim>::assemble_system ()\n  {\n    hp::FEValues<dim> hp_fe_values (fe_collection,\n                                    quadrature_collection,\n                                    update_values    |  update_gradients |\n                                    update_quadrature_points  |  update_JxW_values);\n\n    const RightHandSide<dim> rhs_function;\n\n    FullMatrix<double>   cell_matrix;\n    Vector<double>       cell_rhs;\n\n    std::vector<unsigned int> local_dof_indices;\n\n    typename hp::DoFHandler<dim>::active_cell_iterator\n    cell = dof_handler.begin_active(),\n    endc = dof_handler.end();\n    for (; cell!=endc; ++cell)\n      {\n        const unsigned int   dofs_per_cell = cell->get_fe().dofs_per_cell;\n\n        cell_matrix.reinit (dofs_per_cell, dofs_per_cell);\n        cell_matrix = 0;\n\n        cell_rhs.reinit (dofs_per_cell);\n        cell_rhs = 0;\n\n        hp_fe_values.reinit (cell);\n\n        const FEValues<dim> &fe_values = hp_fe_values.get_present_fe_values ();\n\n        std::vector<double>  rhs_values (fe_values.n_quadrature_points);\n        rhs_function.value_list (fe_values.get_quadrature_points(),\n                                 rhs_values);\n\n        for (unsigned int q_point=0;\n             q_point<fe_values.n_quadrature_points;\n             ++q_point)\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) += (fe_values.shape_value(i,q_point) *\n                              rhs_values[q_point] *\n                              fe_values.JxW(q_point));\n            }\n\n        local_dof_indices.resize (dofs_per_cell);\n        cell->get_dof_indices (local_dof_indices);\n\n        constraints.distribute_local_to_global (cell_matrix, cell_rhs,\n                                                local_dof_indices,\n                                                system_matrix, system_rhs);\n      }\n\n    // Now with the loop over all cells finished, we are done for this\n    // function. The steps we still had to do at this point in earlier\n    // tutorial programs, namely condensing hanging node constraints and\n    // applying Dirichlet boundary conditions, have been taken care of by the\n    // ConstraintMatrix object <code>constraints</code> on the fly.\n  }\n\n\n\n  // @sect4{LaplaceProblem::solve}\n\n  // The function solving the linear system is entirely unchanged from\n  // previous examples. We simply try to reduce the initial residual (which\n  // equals the $l_2$ norm of the right hand side) by a certain factor:\n  template <int dim>\n  void LaplaceProblem<dim>::solve ()\n  {\n    SolverControl           solver_control (system_rhs.size(),\n                                            1e-8*system_rhs.l2_norm());\n    SolverCG<>              cg (solver_control);\n\n    PreconditionSSOR<> preconditioner;\n    preconditioner.initialize(system_matrix, 1.2);\n\n    cg.solve (system_matrix, solution, system_rhs,\n              preconditioner);\n\n    constraints.distribute (solution);\n  }\n\n\n\n  // @sect4{LaplaceProblem::postprocess}\n\n  // After solving the linear system, we will want to postprocess the\n  // solution. Here, all we do is to estimate the error, estimate the local\n  // smoothness of the solution as described in the introduction, then write\n  // graphical output, and finally refine the mesh in both $h$ and $p$\n  // according to the indicators computed before. We do all this in the same\n  // function because we want the estimated error and smoothness indicators\n  // not only for refinement, but also include them in the graphical output.\n  template <int dim>\n  void LaplaceProblem<dim>::postprocess (const unsigned int cycle)\n  {\n    // Let us start with computing estimated error and smoothness indicators,\n    // which each are one number for each active cell of our\n    // triangulation. For the error indicator, we use the KellyErrorEstimator\n    // class as always. Estimating the smoothness is done in the respective\n    // function of this class; that function is discussed further down below:\n    Vector<float> estimated_error_per_cell (triangulation.n_active_cells());\n    KellyErrorEstimator<dim>::estimate (dof_handler,\n                                        face_quadrature_collection,\n                                        typename FunctionMap<dim>::type(),\n                                        solution,\n                                        estimated_error_per_cell);\n\n\n    Vector<float> smoothness_indicators (triangulation.n_active_cells());\n    estimate_smoothness (smoothness_indicators);\n\n    // Next we want to generate graphical output. In addition to the two\n    // estimated quantities derived above, we would also like to output the\n    // polynomial degree of the finite elements used on each of the elements\n    // on the mesh.\n    //\n    // The way to do that requires that we loop over all cells and poll the\n    // active finite element index of them using\n    // <code>cell-@>active_fe_index()</code>. We then use the result of this\n    // operation and query the finite element collection for the finite\n    // element with that index, and finally determine the polynomial degree of\n    // that element. The result we put into a vector with one element per\n    // cell. The DataOut class requires this to be a vector of\n    // <code>float</code> or <code>double</code>, even though our values are\n    // all integers, so that it what we use:\n    {\n      Vector<float> fe_degrees (triangulation.n_active_cells());\n      {\n        typename hp::DoFHandler<dim>::active_cell_iterator\n        cell = dof_handler.begin_active(),\n        endc = dof_handler.end();\n        for (unsigned int index=0; cell!=endc; ++cell, ++index)\n          fe_degrees(index)\n            = fe_collection[cell->active_fe_index()].degree;\n      }\n\n      // With now all data vectors available -- solution, estimated errors and\n      // smoothness indicators, and finite element degrees --, we create a\n      // DataOut object for graphical output and attach all data. Note that\n      // the DataOut class has a second template argument (which defaults to\n      // DoFHandler@<dim@>, which is why we have never seen it in previous\n      // tutorial programs) that indicates the type of DoF handler to be\n      // used. Here, we have to use the hp::DoFHandler class:\n      DataOut<dim,hp::DoFHandler<dim> > data_out;\n\n      data_out.attach_dof_handler (dof_handler);\n      data_out.add_data_vector (solution, \"solution\");\n      data_out.add_data_vector (estimated_error_per_cell, \"error\");\n      data_out.add_data_vector (smoothness_indicators, \"smoothness\");\n      data_out.add_data_vector (fe_degrees, \"fe_degree\");\n      data_out.build_patches ();\n\n      // The final step in generating output is to determine a file name, open\n      // the file, and write the data into it (here, we use VTK format):\n      const std::string filename = \"solution-\" +\n                                   Utilities::int_to_string (cycle, 2) +\n                                   \".vtk\";\n      std::ofstream output (filename.c_str());\n      data_out.write_vtk (output);\n    }\n\n    // After this, we would like to actually refine the mesh, in both $h$ and\n    // $p$. The way we are going to do this is as follows: first, we use the\n    // estimated error to flag those cells for refinement that have the\n    // largest error. This is what we have always done:\n    {\n      GridRefinement::refine_and_coarsen_fixed_number (triangulation,\n                                                       estimated_error_per_cell,\n                                                       0.3, 0.03);\n\n      // Next we would like to figure out which of the cells that have been\n      // flagged for refinement should actually have $p$ increased instead of\n      // $h$ decreased. The strategy we choose here is that we look at the\n      // smoothness indicators of those cells that are flagged for refinement,\n      // and increase $p$ for those with a smoothness larger than a certain\n      // threshold. For this, we first have to determine the maximal and\n      // minimal values of the smoothness indicators of all flagged cells,\n      // which we do using a loop over all cells and comparing current minimal\n      // and maximal values. (We start with the minimal and maximal values of\n      // <i>all</i> cells, a range within which the minimal and maximal values\n      // on cells flagged for refinement must surely lie.) Absent any better\n      // strategies, we will then set the threshold above which will increase\n      // $p$ instead of reducing $h$ as the mean value between minimal and\n      // maximal smoothness indicators on cells flagged for refinement:\n      float max_smoothness = *std::min_element (smoothness_indicators.begin(),\n                                                smoothness_indicators.end()),\n                             min_smoothness = *std::max_element (smoothness_indicators.begin(),\n                                                                 smoothness_indicators.end());\n      {\n        typename hp::DoFHandler<dim>::active_cell_iterator\n        cell = dof_handler.begin_active(),\n        endc = dof_handler.end();\n        for (unsigned int index=0; cell!=endc; ++cell, ++index)\n          if (cell->refine_flag_set())\n            {\n              max_smoothness = std::max (max_smoothness,\n                                         smoothness_indicators(index));\n              min_smoothness = std::min (min_smoothness,\n                                         smoothness_indicators(index));\n            }\n      }\n      const float threshold_smoothness = (max_smoothness + min_smoothness) / 2;\n\n      // With this, we can go back, loop over all cells again, and for those\n      // cells for which (i) the refinement flag is set, (ii) the smoothness\n      // indicator is larger than the threshold, and (iii) we still have a\n      // finite element with a polynomial degree higher than the current one\n      // in the finite element collection, we then increase the polynomial\n      // degree and in return remove the flag indicating that the cell should\n      // undergo bisection. For all other cells, the refinement flags remain\n      // untouched:\n      {\n        typename hp::DoFHandler<dim>::active_cell_iterator\n        cell = dof_handler.begin_active(),\n        endc = dof_handler.end();\n        for (unsigned int index=0; cell!=endc; ++cell, ++index)\n          if (cell->refine_flag_set()\n              &&\n              (smoothness_indicators(index) > threshold_smoothness)\n              &&\n              (cell->active_fe_index()+1 < fe_collection.size()))\n            {\n              cell->clear_refine_flag();\n              cell->set_active_fe_index (cell->active_fe_index() + 1);\n            }\n      }\n\n      // At the end of this procedure, we then refine the mesh. During this\n      // process, children of cells undergoing bisection inherit their mother\n      // cell's finite element index:\n      triangulation.execute_coarsening_and_refinement ();\n    }\n  }\n\n\n  // @sect4{LaplaceProblem::create_coarse_grid}\n\n  // The following function is used when creating the initial grid. It is a\n  // specialization for the 2d case, i.e. a corresponding function needs to be\n  // implemented if the program is run in anything other then 2d. The function\n  // is actually stolen from step-14 and generates the same mesh used already\n  // there, i.e. the square domain with the square hole in the middle. The\n  // meaning of the different parts of this function are explained in the\n  // documentation of step-14:\n  template <>\n  void LaplaceProblem<2>::create_coarse_grid ()\n  {\n    const unsigned int dim = 2;\n\n    static const Point<2> vertices_1[]\n      = {  Point<2> (-1.,   -1.),\n           Point<2> (-1./2, -1.),\n           Point<2> (0.,    -1.),\n           Point<2> (+1./2, -1.),\n           Point<2> (+1,    -1.),\n\n           Point<2> (-1.,   -1./2.),\n           Point<2> (-1./2, -1./2.),\n           Point<2> (0.,    -1./2.),\n           Point<2> (+1./2, -1./2.),\n           Point<2> (+1,    -1./2.),\n\n           Point<2> (-1.,   0.),\n           Point<2> (-1./2, 0.),\n           Point<2> (+1./2, 0.),\n           Point<2> (+1,    0.),\n\n           Point<2> (-1.,   1./2.),\n           Point<2> (-1./2, 1./2.),\n           Point<2> (0.,    1./2.),\n           Point<2> (+1./2, 1./2.),\n           Point<2> (+1,    1./2.),\n\n           Point<2> (-1.,   1.),\n           Point<2> (-1./2, 1.),\n           Point<2> (0.,    1.),\n           Point<2> (+1./2, 1.),\n           Point<2> (+1,    1.)\n        };\n    const unsigned int\n    n_vertices = sizeof(vertices_1) / sizeof(vertices_1[0]);\n    const std::vector<Point<dim> > vertices (&vertices_1[0],\n                                             &vertices_1[n_vertices]);\n    static const int cell_vertices[][GeometryInfo<dim>::vertices_per_cell]\n    = {{0, 1, 5, 6},\n      {1, 2, 6, 7},\n      {2, 3, 7, 8},\n      {3, 4, 8, 9},\n      {5, 6, 10, 11},\n      {8, 9, 12, 13},\n      {10, 11, 14, 15},\n      {12, 13, 17, 18},\n      {14, 15, 19, 20},\n      {15, 16, 20, 21},\n      {16, 17, 21, 22},\n      {17, 18, 22, 23}\n    };\n    const unsigned int\n    n_cells = sizeof(cell_vertices) / sizeof(cell_vertices[0]);\n\n    std::vector<CellData<dim> > cells (n_cells, CellData<dim>());\n    for (unsigned int i=0; i<n_cells; ++i)\n      {\n        for (unsigned int j=0;\n             j<GeometryInfo<dim>::vertices_per_cell;\n             ++j)\n          cells[i].vertices[j] = cell_vertices[i][j];\n        cells[i].material_id = 0;\n      }\n\n    triangulation.create_triangulation (vertices,\n                                        cells,\n                                        SubCellData());\n    triangulation.refine_global (3);\n  }\n\n\n\n\n  // @sect4{LaplaceProblem::run}\n\n  // This function implements the logic of the program, as did the respective\n  // function in most of the previous programs already, see for example\n  // step-6.\n  //\n  // Basically, it contains the adaptive loop: in the first iteration create a\n  // coarse grid, and then set up the linear system, assemble it, solve, and\n  // postprocess the solution including mesh refinement. Then start over\n  // again. In the meantime, also output some information for those staring at\n  // the screen trying to figure out what the program does:\n  template <int dim>\n  void LaplaceProblem<dim>::run ()\n  {\n    for (unsigned int cycle=0; cycle<6; ++cycle)\n      {\n        std::cout << \"Cycle \" << cycle << ':' << std::endl;\n\n        if (cycle == 0)\n          create_coarse_grid ();\n\n        setup_system ();\n\n        std::cout << \"   Number of active cells:       \"\n                  << triangulation.n_active_cells()\n                  << std::endl\n                  << \"   Number of degrees of freedom: \"\n                  << dof_handler.n_dofs()\n                  << std::endl\n                  << \"   Number of constraints       : \"\n                  << constraints.n_constraints()\n                  << std::endl;\n\n        assemble_system ();\n        solve ();\n        postprocess (cycle);\n      }\n  }\n\n\n  // @sect4{LaplaceProblem::estimate_smoothness}\n\n  // This last function of significance implements the algorithm to estimate\n  // the smoothness exponent using the algorithms explained in detail in the\n  // introduction. We will therefore only comment on those points that are of\n  // implementational importance.\n  template <int dim>\n  void\n  LaplaceProblem<dim>::\n  estimate_smoothness (Vector<float> &smoothness_indicators) const\n  {\n    // The first thing we need to do is to define the Fourier vectors ${\\bf\n    // k}$ for which we want to compute Fourier coefficients of the solution\n    // on each cell. In 2d, we pick those vectors ${\\bf k}=(\\pi i, \\pi j)^T$\n    // for which $\\sqrt{i^2+j^2}\\le N$, with $i,j$ integers and $N$ being the\n    // maximal polynomial degree we use for the finite elements in this\n    // program. The 3d case is handled analogously. 1d and dimensions higher\n    // than 3 are not implemented, and we guard our implementation by making\n    // sure that we receive an exception in case someone tries to compile the\n    // program for any of these dimensions.\n    //\n    // We exclude ${\\bf k}=0$ to avoid problems computing $|{\\bf k}|^{-mu}$\n    // and $\\ln |{\\bf k}|$. The other vectors are stored in the field\n    // <code>k_vectors</code>. In addition, we store the square of the\n    // magnitude of each of these vectors (up to a factor $\\pi^2$) in the\n    // <code>k_vectors_magnitude</code> array -- we will need that when we\n    // attempt to find out which of those Fourier coefficients corresponding\n    // to Fourier vectors of the same magnitude is the largest:\n    const unsigned int N = max_degree;\n\n    std::vector<Tensor<1,dim> > k_vectors;\n    std::vector<unsigned int>   k_vectors_magnitude;\n    switch (dim)\n      {\n      case 2:\n      {\n        for (unsigned int i=0; i<N; ++i)\n          for (unsigned int j=0; j<N; ++j)\n            if (!((i==0) && (j==0))\n                &&\n                (i*i + j*j < N*N))\n              {\n                k_vectors.push_back (Point<dim>(numbers::PI * i,\n                                                numbers::PI * j));\n                k_vectors_magnitude.push_back (i*i+j*j);\n              }\n\n        break;\n      }\n\n      case 3:\n      {\n        for (unsigned int i=0; i<N; ++i)\n          for (unsigned int j=0; j<N; ++j)\n            for (unsigned int k=0; k<N; ++k)\n              if (!((i==0) && (j==0) && (k==0))\n                  &&\n                  (i*i + j*j + k*k < N*N))\n                {\n                  k_vectors.push_back (Point<dim>(numbers::PI * i,\n                                                  numbers::PI * j,\n                                                  numbers::PI * k));\n                  k_vectors_magnitude.push_back (i*i+j*j+k*k);\n                }\n\n        break;\n      }\n\n      default:\n        Assert (false, ExcNotImplemented());\n      }\n\n    // After we have set up the Fourier vectors, we also store their total\n    // number for simplicity, and compute the logarithm of the magnitude of\n    // each of these vectors since we will need it many times over further\n    // down below:\n    const unsigned n_fourier_modes = k_vectors.size();\n    std::vector<double> ln_k (n_fourier_modes);\n    for (unsigned int i=0; i<n_fourier_modes; ++i)\n      ln_k[i] = std::log (k_vectors[i].norm());\n\n\n    // Next, we need to assemble the matrices that do the Fourier transforms\n    // for each of the finite elements we deal with, i.e. the matrices ${\\cal\n    // F}_{{\\bf k},j}$ defined in the introduction. We have to do that for\n    // each of the finite elements in use. Note that these matrices are\n    // complex-valued, so we can't use the FullMatrix class. Instead, we use\n    // the Table class template.\n    std::vector<Table<2,std::complex<double> > >\n    fourier_transform_matrices (fe_collection.size());\n\n    // In order to compute them, we of course can't perform the Fourier\n    // transform analytically, but have to approximate it using quadrature. To\n    // this end, we use a quadrature formula that is obtained by iterating a\n    // 2-point Gauss formula as many times as the maximal exponent we use for\n    // the term $e^{i{\\bf k}\\cdot{\\bf x}}$:\n    QGauss<1>      base_quadrature (2);\n    QIterated<dim> quadrature (base_quadrature, N);\n\n    // With this, we then loop over all finite elements in use, reinitialize\n    // the respective matrix ${\\cal F}$ to the right size, and integrate each\n    // entry of the matrix numerically as ${\\cal F}_{{\\bf k},j}=\\sum_q\n    // e^{i{\\bf k}\\cdot {\\bf x}}\\varphi_j({\\bf x}_q) w_q$, where $x_q$ are the\n    // quadrature points and $w_q$ are the quadrature weights. Note that the\n    // imaginary unit $i=\\sqrt{-1}$ is obtained from the standard C++ classes\n    // using <code>std::complex@<double@>(0,1)</code>.\n\n    // Because we work on the unit cell, we can do all this work without a\n    // mapping from reference to real cell and consequently do not need the\n    // FEValues class.\n    for (unsigned int fe=0; fe<fe_collection.size(); ++fe)\n      {\n        fourier_transform_matrices[fe].reinit (n_fourier_modes,\n                                               fe_collection[fe].dofs_per_cell);\n\n        for (unsigned int k=0; k<n_fourier_modes; ++k)\n          for (unsigned int j=0; j<fe_collection[fe].dofs_per_cell; ++j)\n            {\n              std::complex<double> sum = 0;\n              for (unsigned int q=0; q<quadrature.size(); ++q)\n                {\n                  const Point<dim> x_q = quadrature.point(q);\n                  sum += std::exp(std::complex<double>(0,1) *\n                                  (k_vectors[k] * x_q)) *\n                         fe_collection[fe].shape_value(j,x_q) *\n                         quadrature.weight(q);\n                }\n              fourier_transform_matrices[fe](k,j)\n                = sum / std::pow(2*numbers::PI, 1.*dim/2);\n            }\n      }\n\n    // The next thing is to loop over all cells and do our work there, i.e. to\n    // locally do the Fourier transform and estimate the decay coefficient. We\n    // will use the following two arrays as scratch arrays in the loop and\n    // allocate them here to avoid repeated memory allocations:\n    std::vector<std::complex<double> > fourier_coefficients (n_fourier_modes);\n    Vector<double>                     local_dof_values;\n\n    // Then here is the loop:\n    typename hp::DoFHandler<dim>::active_cell_iterator\n    cell = dof_handler.begin_active(),\n    endc = dof_handler.end();\n    for (unsigned int index=0; cell!=endc; ++cell, ++index)\n      {\n        // Inside the loop, we first need to get the values of the local\n        // degrees of freedom (which we put into the\n        // <code>local_dof_values</code> array after setting it to the right\n        // size) and then need to compute the Fourier transform by multiplying\n        // this vector with the matrix ${\\cal F}$ corresponding to this finite\n        // element. We need to write out the multiplication by hand because\n        // the objects holding the data do not have <code>vmult</code>-like\n        // functions declared:\n        local_dof_values.reinit (cell->get_fe().dofs_per_cell);\n        cell->get_dof_values (solution, local_dof_values);\n\n        for (unsigned int f=0; f<n_fourier_modes; ++f)\n          {\n            fourier_coefficients[f] = 0;\n\n            for (unsigned int i=0; i<cell->get_fe().dofs_per_cell; ++i)\n              fourier_coefficients[f] +=\n                fourier_transform_matrices[cell->active_fe_index()](f,i)\n                *\n                local_dof_values(i);\n          }\n\n        // The next thing, as explained in the introduction, is that we wanted\n        // to only fit our exponential decay of Fourier coefficients to the\n        // largest coefficients for each possible value of $|{\\bf k}|$. To\n        // this end, we create a map that for each magnitude $|{\\bf k}|$\n        // stores the largest $|\\hat U_{{\\bf k}}|$ found so far, i.e. we\n        // overwrite the existing value (or add it to the map) if no value for\n        // the current $|{\\bf k}|$ exists yet, or if the current value is\n        // larger than the previously stored one:\n        std::map<unsigned int, double> k_to_max_U_map;\n        for (unsigned int f=0; f<n_fourier_modes; ++f)\n          if ((k_to_max_U_map.find (k_vectors_magnitude[f]) ==\n               k_to_max_U_map.end())\n              ||\n              (k_to_max_U_map[k_vectors_magnitude[f]] <\n               std::abs (fourier_coefficients[f])))\n            k_to_max_U_map[k_vectors_magnitude[f]]\n              = std::abs (fourier_coefficients[f]);\n        // Note that it comes in handy here that we have stored the magnitudes\n        // of vectors as integers, since this way we do not have to deal with\n        // round-off-sized differences between different values of $|{\\bf\n        // k}|$.\n\n        // As the final task, we have to calculate the various contributions\n        // to the formula for $\\mu$. We'll only take those Fourier\n        // coefficients with the largest magnitude for a given value of $|{\\bf\n        // k}|$ as explained above:\n        double  sum_1           = 0,\n                sum_ln_k        = 0,\n                sum_ln_k_square = 0,\n                sum_ln_U        = 0,\n                sum_ln_U_ln_k   = 0;\n        for (unsigned int f=0; f<n_fourier_modes; ++f)\n          if (k_to_max_U_map[k_vectors_magnitude[f]] ==\n              std::abs (fourier_coefficients[f]))\n            {\n              sum_1 += 1;\n              sum_ln_k += ln_k[f];\n              sum_ln_k_square += ln_k[f]*ln_k[f];\n              sum_ln_U += std::log (std::abs (fourier_coefficients[f]));\n              sum_ln_U_ln_k += std::log (std::abs (fourier_coefficients[f])) *\n                               ln_k[f];\n            }\n\n        // With these so-computed sums, we can now evaluate the formula for\n        // $\\mu$ derived in the introduction:\n        const double mu\n          = (1./(sum_1*sum_ln_k_square - sum_ln_k*sum_ln_k)\n             *\n             (sum_ln_k*sum_ln_U - sum_1*sum_ln_U_ln_k));\n\n        // The final step is to compute the Sobolev index $s=\\mu-\\frac d2$ and\n        // store it in the vector of estimated values for each cell:\n        smoothness_indicators(index) = mu - 1.*dim/2;\n      }\n  }\n}\n\n\n// @sect3{The main function}\n\n// The main function is again verbatim what we had before: wrap creating and\n// running an object of the main class into a <code>try</code> block and catch\n// whatever exceptions are thrown, thereby producing meaningful output if\n// anything should go wrong:\nint main ()\n{\n  try\n    {\n      using namespace dealii;\n      using namespace Step27;\n\n      deallog.depth_console (0);\n\n      LaplaceProblem<2> laplace_problem;\n      laplace_problem.run ();\n    }\n  catch (std::exception &exc)\n    {\n      std::cerr << std::endl << std::endl\n                << \"----------------------------------------------------\"\n                << std::endl;\n      std::cerr << \"Exception on processing: \" << std::endl\n                << exc.what() << std::endl\n                << \"Aborting!\" << std::endl\n                << \"----------------------------------------------------\"\n                << std::endl;\n\n      return 1;\n    }\n  catch (...)\n    {\n      std::cerr << std::endl << std::endl\n                << \"----------------------------------------------------\"\n                << std::endl;\n      std::cerr << \"Unknown exception!\" << std::endl\n                << \"Aborting!\" << std::endl\n                << \"----------------------------------------------------\"\n                << std::endl;\n      return 1;\n    }\n\n  return 0;\n}\n", "meta": {"hexsha": "d1ced6a5798a3a855c10544db2ce4b86d4157d64", "size": 37278, "ext": "cc", "lang": "C++", "max_stars_repo_path": "MHD/examples/step-27/step-27.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-27/step-27.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-27/step-27.cc", "max_forks_repo_name": "wathen/PhD", "max_forks_repo_head_hexsha": "35524f40028541a4d611d8c78574e4cf9ddc3278", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2019-10-28T16:12:13.000Z", "max_forks_repo_forks_event_max_datetime": "2020-01-13T13:59:44.000Z", "avg_line_length": 41.6049107143, "max_line_length": 95, "alphanum_fraction": 0.6125060357, "num_tokens": 8883, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.32424669288441366}}
{"text": "#include <Rcpp.h>\n\n//[[Rcpp::depends(RcppEigen)]]\n#include <RcppEigen.h>\n\n//[[Rcpp::depends(BH)]]\n#include <boost/math/special_functions/digamma.hpp>\n\n#include \"experimentalSetup.hpp\"\n#include \"logLikelihoods.hpp\"\n#include \"individual.hpp\"\n#include \"estimatePoissonGammaParameters.hpp\"\n#include \"AuxiliaryFunctions.hpp\"\n\n#include \"nlopt.hpp\"\n\n// Allele coverage\nEstimatePoissonGammaAlleleParameters::EstimatePoissonGammaAlleleParameters(const Eigen::VectorXd & coverage, const std::vector<Eigen::MatrixXd> & expectedContributionMatrix,\n                                                                           const std::vector<Eigen::VectorXd> & alleleIndex, const Eigen::VectorXd & markerImbalances,\n                                                                           const Eigen::VectorXd & partialSumAlleles, const double & convexMarkerImbalanceInterpolation,\n                                                                           const Eigen::VectorXd & tolerance)\n{\n    Coverage = coverage;\n    ExpectedContributionMatrix = expectedContributionMatrix;\n    AlleleIndex = alleleIndex;\n\n    PartialSumAlleles = partialSumAlleles;\n    MarkerImbalances = markerImbalances;\n\n    ConvexMarkerImbalanceInterpolation = convexMarkerImbalanceInterpolation;\n    Tolerance = tolerance;\n    MaximumNumberOfIterations = 2000;\n\n    Counter = 0;\n\n    NumberOfContributors = expectedContributionMatrix[0].cols();\n    NumberOfMarkers = MarkerImbalances.size();\n\n    initialiseParameters();\n}\n\n\nvoid EstimatePoissonGammaAlleleParameters::initialiseParameters()\n{\n    // Initialising mixture parameters\n    Eigen::VectorXd phiCurrent = Eigen::VectorXd::Ones(NumberOfContributors) / NumberOfContributors;\n    double sumCoverage = 0.0;\n    double sumCount = 0.0;\n    Eigen::VectorXd sumCoverageMarker = Eigen::VectorXd::Zero(NumberOfMarkers);\n    for (std::size_t m = 0; m < NumberOfMarkers; m++)\n    {\n        const Eigen::VectorXd & AlleleIndex_m = AlleleIndex[m];\n        const Eigen::MatrixXd & ExpectedContributionMatrix_m = ExpectedContributionMatrix[m];\n        for (std::size_t a = 0; a < AlleleIndex_m.size(); a++)\n        {\n            std::size_t n = PartialSumAlleles[m] + AlleleIndex_m[a];\n            sumCoverageMarker[m] += Coverage[n];\n            sumCount++;\n\n            for (std::size_t c = 0; c < NumberOfContributors; c++)\n            {\n                Eigen::VectorXd contributor_c = ExpectedContributionMatrix_m.col(c);\n                if (contributor_c[a] >= 1)\n                {\n                    phiCurrent[c] += Coverage[n] / contributor_c[a];\n                }\n            }\n        }\n\n        sumCoverage += sumCoverageMarker[m];\n    }\n\n    MixtureParameters = phiCurrent / phiCurrent.sum();\n\n    // Initialising sample and marker parameters\n    double averageCoverageDenominator = 0.0;\n    Eigen::VectorXd markerImbalancesMoM = sumCoverageMarker;\n    for (std::size_t m = 0; m < NumberOfMarkers; m++)\n    {\n        const Eigen::MatrixXd & ExpectedContributionMatrix_m = ExpectedContributionMatrix[m];\n        Eigen::VectorXd EC = ExpectedContributionMatrix_m * MixtureParameters;\n        const double & ECSum = EC.sum();\n        double markerImbalancesMoM_m = markerImbalancesMoM[m];\n        if (!(markerImbalancesMoM_m > 0))\n        {\n            markerImbalancesMoM_m = 1e-6;\n        }\n\n        averageCoverageDenominator += ECSum;\n        markerImbalancesMoM[m] = markerImbalancesMoM_m / ECSum;\n    }\n\n    SampleParameters = 2.0 * Eigen::VectorXd::Ones(2);\n    SampleParameters[0] = sumCoverage / averageCoverageDenominator;\n\n    markerImbalancesMoM = markerImbalancesMoM / SampleParameters[0];\n    markerImbalancesMoM = markerImbalancesMoM / markerImbalancesMoM.mean();\n\n    MarkerImbalancesParameters = ConvexMarkerImbalanceInterpolation * markerImbalancesMoM + (1 - ConvexMarkerImbalanceInterpolation) * MarkerImbalances;\n}\n\ndouble logLikelihoodAlleleCoverageNLopt(const std::vector<double> & x, std::vector<double> & grad, void *data)\n{\n    // Unpacking data\n    EstimatePoissonGammaAlleleParameters *EPGA = reinterpret_cast<EstimatePoissonGammaAlleleParameters*>(data);\n    const std::vector<Eigen::MatrixXd> & ExpectedContributionMatrix = EPGA->ExpectedContributionMatrix;\n    const std::vector<Eigen::VectorXd> & AlleleIndex = EPGA->AlleleIndex;\n\n    const Eigen::VectorXd & MarkerImbalances = EPGA->MarkerImbalancesParameters;\n    const Eigen::VectorXd & PartialSumAlleles = EPGA->PartialSumAlleles;\n    const Eigen::VectorXd & Coverage = EPGA->Coverage;\n\n    const std::size_t NumberOfMarkers = EPGA->NumberOfMarkers;\n\n    std::size_t & Counter = EPGA->Counter;\n\n    const std::size_t & C = EPGA->NumberOfContributors;\n    const std::size_t S = 2;\n\n    const double & referenceMarkerAverage = x[0];\n    const double & dispersion = x[1];\n\n    double logLikelihood = 0.0;\n    std::vector<double> gradient(C + S - 1, 0.0);\n    for (std::size_t m = 0; m < NumberOfMarkers; m++)\n    {\n        const Eigen::VectorXd & AlleleIndex_m = AlleleIndex[m];\n        const Eigen::MatrixXd & ExpectedContributionMatrix_m = ExpectedContributionMatrix[m];\n        for (std::size_t a = 0; a < AlleleIndex_m.size(); a++)\n        {\n            std::size_t n = PartialSumAlleles[m] + AlleleIndex_m[a];\n            const Eigen::VectorXd ExpectedContributionMatrix_ma = ExpectedContributionMatrix_m.row(a);\n\n            double EC_n = ExpectedContributionMatrix_ma[C - 1];\n            for (std::size_t c = 0; c < C - 1; c++)\n            {\n                EC_n += (ExpectedContributionMatrix_ma[c] - ExpectedContributionMatrix_ma[C - 1]) * x[S + c];\n            }\n\n            double mu_ma = referenceMarkerAverage * MarkerImbalances[m] * EC_n;\n            if (!(mu_ma > 0.0))\n            {\n                mu_ma += 2e-16;\n            }\n\n            logLikelihood += logPoissonGammaDistribution(Coverage[n], mu_ma, mu_ma / dispersion);\n\n            if (!grad.empty())\n            {\n                const double & gradient_common_term = boost::math::digamma(Coverage[n] + mu_ma / dispersion) - boost::math::digamma(mu_ma / dispersion) - std::log(dispersion + 1.0);\n\n                gradient[0] += gradient_common_term * (MarkerImbalances[m] * EC_n) / (dispersion);\n                gradient[1] += (Coverage[n] - mu_ma) / (dispersion * (dispersion + 1.0)) - gradient_common_term * (mu_ma / (std::pow(dispersion, 2.0)));\n\n                for (std::size_t c = 0; c < C - 1; c++)\n                {\n                    const double & EC_nm = ExpectedContributionMatrix_ma[c] - ExpectedContributionMatrix_ma[C - 1];\n                    gradient[S + c] +=  gradient_common_term * ((referenceMarkerAverage * MarkerImbalances[m] * EC_nm) / dispersion);\n                }\n\n            }\n        }\n    }\n\n    if (!grad.empty())\n    {\n        grad = gradient;\n    }\n\n    Counter++;\n    return logLikelihood;\n}\n\nvoid estimateParametersAlleleCoverage(EstimatePoissonGammaAlleleParameters &EPGA)\n{\n    std::size_t S = EPGA.SampleParameters.size();\n    std::size_t C = EPGA.MixtureParameters.size();\n\n    std::vector<double> parameters(S + C - 1, 0.0);\n    for (std::size_t s = 0; s < S; s++)\n    {\n        parameters[s] = EPGA.SampleParameters[s];\n    }\n\n    for (std::size_t c = 0; c < C - 1; c++)\n    {\n        parameters[S + c] = EPGA.MixtureParameters[c];\n    }\n\n    // Optimiser\n    // nlopt::opt individualOptimisation(nlopt::LN_BOBYQA, S + C - 1);\n    // nlopt::opt individualOptimisation(nlopt::LD_LBFGS, S + C - 1);\n    nlopt::opt individualOptimisation(nlopt::LD_SLSQP, S + C - 1);\n\n    // Box-constraints\n    std::size_t N = EPGA.Coverage.size();\n    std::vector<double> lowerBound(S + C - 1), upperBound(S + C - 1);\n    lowerBound[0] = 1;\n    lowerBound[1] = 2e-8;\n    upperBound[0] = EPGA.Coverage.maxCoeff() + 1;\n    upperBound[1] = std::exp(std::log(2.0) + std::log(N) - std::log(2.0 * N - 2.0))  * (std::pow(EPGA.Coverage.maxCoeff(), 2.0) + 1);\n\n    if (C == 1)\n    {\n        lowerBound[S] = 1 - 2e-16;\n        upperBound[S] = 1;\n    }\n    else\n    {\n        for (std::size_t j = 0; j < C - 1; j++)\n        {\n            lowerBound[S + j] = 2e-16;\n            upperBound[S + j] = 1.0 - 2e-16;\n        }\n    }\n\n    individualOptimisation.set_lower_bounds(lowerBound);\n    individualOptimisation.set_upper_bounds(upperBound);\n\n    // Objective function\n    individualOptimisation.set_max_objective(logLikelihoodAlleleCoverageNLopt, &EPGA);\n\n    individualOptimisation.set_ftol_rel(EPGA.Tolerance[0]);\n    individualOptimisation.set_ftol_abs(EPGA.Tolerance[1]);\n    individualOptimisation.set_xtol_rel(EPGA.Tolerance[2]);\n    individualOptimisation.set_xtol_abs(EPGA.Tolerance[3]);\n\n    individualOptimisation.set_maxeval(EPGA.MaximumNumberOfIterations);\n\n    double logLikelihood;\n    try\n    {\n        nlopt::result result = individualOptimisation.optimize(parameters, logLikelihood);\n    }\n    catch (...)\n    {\n        try\n        {\n            if (EPGA.Tolerance[0] > 0)\n                individualOptimisation.set_ftol_rel(std::pow(10, (-2 + std::log10(EPGA.Tolerance[0])) / 2));\n\n            if (EPGA.Tolerance[1] > 0)\n                individualOptimisation.set_ftol_abs(std::pow(10, (-2 + std::log10(EPGA.Tolerance[1])) / 2));\n\n            if (EPGA.Tolerance[2] > 0)\n                individualOptimisation.set_xtol_rel(std::pow(10, (-2 + std::log10(EPGA.Tolerance[2])) / 2));\n\n            if (EPGA.Tolerance[3] > 0)\n                individualOptimisation.set_xtol_abs(std::pow(10, (-2 + std::log10(EPGA.Tolerance[3])) / 2));\n\n            nlopt::result result = individualOptimisation.optimize(parameters, logLikelihood);\n        }\n        catch (...)\n        {\n            //\n        }\n    }\n\n    EPGA.LogLikelihood = logLikelihood;\n    Eigen::VectorXd Parameters = STDEigen(parameters);\n\n    EPGA.SampleParameters = Parameters.segment(0, S);\n\n    EPGA.MixtureParameters.segment(0, C - 1) = Parameters.segment(S, C - 1);\n    EPGA.MixtureParameters[C - 1] =  1.0 - Parameters.segment(S, C - 1).sum();\n}\n\n\n// Noise coverage\nEstimatePoissonGammaNoiseParameters::EstimatePoissonGammaNoiseParameters(const Eigen::VectorXd & coverage,\n                                                                         const std::vector<Eigen::VectorXd> & noiseIndex,\n                                                                         const Eigen::VectorXd & partialSumAlleles,\n                                                                         const Eigen::VectorXd & tolerance,\n                                                                         const double & varianceUpperLimit)\n{\n    Coverage = coverage;\n    NoiseIndex = noiseIndex;\n\n    PartialSumAlleles = partialSumAlleles;\n\n    NumberOfMarkers = NoiseIndex.size();\n    Tolerance = tolerance;\n    MaximumNumberOfIterations = 2000;\n    VarianceUpperLimit = varianceUpperLimit;\n\n    Counter = 0;\n\n    initialiseParameters();\n}\n\nvoid EstimatePoissonGammaNoiseParameters::initialiseParameters()\n{\n    Eigen::VectorXd parameters = Eigen::VectorXd::Ones(3);\n\n    double noiseCoverageSum = 0.0;\n    double noiseCoverageSquaredSum = 0.0;\n    double noiseCoverageSize = 0.0;\n    double noiseCoverageInflation = 0.0;\n    for (std::size_t m = 0; m < NumberOfMarkers; m++)\n    {\n        const Eigen::VectorXd & NoiseIndex_m = NoiseIndex[m];\n        for (std::size_t a = 0; a < NoiseIndex_m.size(); a++)\n        {\n            std::size_t n = PartialSumAlleles[m] + NoiseIndex_m[a];\n            noiseCoverageSum += Coverage[n];\n            noiseCoverageSquaredSum += std::pow(Coverage[n], 2.0);\n            noiseCoverageSize++;\n\n            if (Coverage[n] == 1.0)\n                noiseCoverageInflation++;\n        }\n    }\n\n    double averageNoiseCoverage = std::ceil(0.5 * noiseCoverageSum) / noiseCoverageSize;\n\n    parameters[0] = averageNoiseCoverage * (1 - std::exp(logPoissonGammaDistribution(0, averageNoiseCoverage, averageNoiseCoverage)));\n    parameters[1] = 1.0; // std::abs((noiseCoverageSquaredSum / noiseCoverageSize - std::pow(parameters[0], 2.0)) / parameters[0] - 1.0);\n    parameters[2] = noiseCoverageInflation / (2.0 * noiseCoverageSize);\n\n    if (parameters[0] < 1.0) {\n        parameters[0] = 1.0;\n    }\n\n    if (parameters[1] < 1.0) {\n        parameters[1] = 1.0;\n    }\n\n    if (parameters[1] > VarianceUpperLimit) {\n        parameters[1] = VarianceUpperLimit;\n    }\n\n    NoiseParameters = parameters;\n}\n\ndouble logLikelihoodNoiseCoverageNLopt(const std::vector<double> &x, std::vector<double> &grad, void *data)\n{\n    EstimatePoissonGammaNoiseParameters *EPGN = reinterpret_cast<EstimatePoissonGammaNoiseParameters*>(data);\n    const Eigen::VectorXd & Coverage = EPGN->Coverage;\n    const std::vector<Eigen::VectorXd> & NoiseIndex = EPGN->NoiseIndex;\n    const Eigen::VectorXd & PartialSumAlleles = EPGN->PartialSumAlleles;\n    const std::size_t & NumberOfMarkers = EPGN->NumberOfMarkers;\n    std::size_t & Counter = EPGN->Counter;\n\n    const double & mu_ma = x[0];\n    const double & dispersion = x[1];\n    const double & p = x[2];\n\n    double logLikelihood = 0.0;\n    for (std::size_t m = 0; m < NumberOfMarkers; m++)\n    {\n        const Eigen::VectorXd & NoiseIndex_m = NoiseIndex[m];\n        for (std::size_t a = 0; a < NoiseIndex_m.size(); a++)\n        {\n            std::size_t n = PartialSumAlleles[m] + NoiseIndex_m[a];\n            logLikelihood += logInflatedTruncatedPoissonGammaDistribution(Coverage[n], mu_ma, dispersion, p, 1.0, 0.0);\n                //- std::log(1 - std::exp(dispersion * logeta)); // std::log(1.0 - std::exp(gamma * zero_truncation)); //\n        }\n    }\n\n    Counter++;\n    return logLikelihood;\n}\n\nvoid estimateParametersNoiseCoverage(EstimatePoissonGammaNoiseParameters &EPGN)\n{\n    const std::size_t & N = EPGN.NoiseParameters.size();\n    std::vector<double> parameters = EigenSTD(EPGN.NoiseParameters);\n\n    // Optimiser\n    // nlopt::opt individualOptimisation(nlopt::LN_BOBYQA, N);\n    nlopt::opt individualOptimisation(nlopt::LN_SBPLX, N);\n\n    // Box-constraints\n    std::vector<double> lowerBound(N), upperBound(N);\n    lowerBound[0] = 1.0;\n    lowerBound[1] = 1.0;\n    lowerBound[2] = 2e-16;\n\n    upperBound[0] = EPGN.Coverage.maxCoeff();\n    upperBound[1] = EPGN.VarianceUpperLimit; // (EPGN.Coverage.size() / (EPGN.Coverage.size() - 1.0)) * std::pow(EPGN.Coverage.maxCoeff(), 2.0);\n    upperBound[2] = 1.0 - 2e-16;\n\n    individualOptimisation.set_lower_bounds(lowerBound);\n    individualOptimisation.set_upper_bounds(upperBound);\n\n    // Objective function\n    individualOptimisation.set_max_objective(logLikelihoodNoiseCoverageNLopt, &EPGN);\n\n    individualOptimisation.set_ftol_rel(EPGN.Tolerance[0]);\n    individualOptimisation.set_ftol_abs(EPGN.Tolerance[1]);\n    individualOptimisation.set_xtol_rel(EPGN.Tolerance[2]);\n    individualOptimisation.set_xtol_abs(EPGN.Tolerance[3]);\n\n    individualOptimisation.set_maxeval(EPGN.MaximumNumberOfIterations);\n\n    double logLikelihood;\n    try\n    {\n        nlopt::result result = individualOptimisation.optimize(parameters, logLikelihood);\n    }\n    catch (...)\n    {\n        try\n        {\n            if (EPGN.Tolerance[0] > 0)\n                individualOptimisation.set_ftol_rel(std::pow(10, (-2 + std::log10(EPGN.Tolerance[0])) / 2));\n\n            if (EPGN.Tolerance[1] > 0)\n                individualOptimisation.set_ftol_abs(std::pow(10, (-2 + std::log10(EPGN.Tolerance[1])) / 2));\n\n            if (EPGN.Tolerance[2] > 0)\n                individualOptimisation.set_xtol_rel(std::pow(10, (-2 + std::log10(EPGN.Tolerance[2])) / 2));\n\n            if (EPGN.Tolerance[3] > 0)\n                individualOptimisation.set_xtol_abs(std::pow(10, (-2 + std::log10(EPGN.Tolerance[3])) / 2));\n\n            nlopt::result result = individualOptimisation.optimize(parameters, logLikelihood);\n        }\n        catch (...)\n        {\n            //\n        }\n    }\n\n    EPGN.LogLikelihood = logLikelihood;\n    Eigen::VectorXd Parameters = STDEigen(parameters);\n    EPGN.NoiseParameters = Parameters;\n}\n", "meta": {"hexsha": "b2941a288611760773c7f0eb35b15c1ae40df0f7", "size": 15867, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/estimatePoissonGammaParameters.cpp", "max_stars_repo_name": "svilsen/MPSMixtures", "max_stars_repo_head_hexsha": "07b21c593bee795162f6282446ff370985ceec38", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/estimatePoissonGammaParameters.cpp", "max_issues_repo_name": "svilsen/MPSMixtures", "max_issues_repo_head_hexsha": "07b21c593bee795162f6282446ff370985ceec38", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/estimatePoissonGammaParameters.cpp", "max_forks_repo_name": "svilsen/MPSMixtures", "max_forks_repo_head_hexsha": "07b21c593bee795162f6282446ff370985ceec38", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.986013986, "max_line_length": 181, "alphanum_fraction": 0.6263313796, "num_tokens": 4194, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7341195269001831, "lm_q2_score": 0.4416730056646256, "lm_q1q2_score": 0.3242407779630968}}
{"text": "/* This module defines overall interface to the generalized Ising solver.\n * See the README for the meaning of input flags, input files, and installation\n *\n * Author: Wenxuan Huang\n * Maintainer: Wenxuan Huang, Daniil Kitchaev\n * Date: 15 March, 2015\n *\n */\n\n#include <iostream>\n#include <fstream>\n#include <sstream>\n#include <streambuf>\n#include <string>\n#include <stdio.h>\n#include <vector>\n#include <set>\n#include <map>\n#include \"gurobi_c++.h\"\n#include \"boost/tuple/tuple.hpp\"\n#include \"boost/tuple/tuple_comparison.hpp\"\n#include \"boost/tuple/tuple_io.hpp\"\n#include <boost/lexical_cast.hpp>\n#include \"solver.h\"\n\nusing namespace std;\nusing namespace ::boost::tuples;\nusing namespace ::boost;\n\nvoid read_from_file(std::string &id,\n                     int &max_sites,\n                     map< set<tuple<int,int,int,int,int> >, double> &J,\n                     double &prec,\n                     int &num_loops,\n                     bool &translation_algorithm,\n                     bool &basic_exact_mode,\n                     bool &pseudo_mode,\n                     bool &pseudo_mode_with_proof,\n                     bool &verbose,\n                     bool &very_verbose,\n                     bool &obscenely_verbose);\n\nint main (void) {\n    std::string id=\"IS0\";\n    int max_sites = 50;\n    int num_loops = 4;\n    double prec = 0.00001;\n    bool translation_algorithm = false;\n    bool basic_exact_mode = false;\n    bool pseudo_mode = true;\n    bool pseudo_mode_with_proof = false;\n    bool verbose = true;\n    bool very_verbose = false;\n    bool obscenely_verbose = false;\n\n    double lower_bound, upper_bound, exact_lowerbound;\n\n    map< set<tuple<int,int,int,int,int> >, double> J, lowerboundclustertype, upperboundclustertype, J_for_proof;\n    map< tuple<int,int,int,int>,int> unitcell;\n    tuple<int,int,int,int,int,int> periodicity;\n    map< tuple<int,int,int,int>, int> cellrepresentation;\n\n    read_from_file(id, max_sites, J, prec, num_loops, translation_algorithm,\n                   basic_exact_mode, pseudo_mode, pseudo_mode_with_proof,\n                   verbose, very_verbose, obscenely_verbose);\n\n    run_solver(max_sites, J,\n               lowerboundclustertype, upperboundclustertype, cellrepresentation,\n               lower_bound, upper_bound, exact_lowerbound, unitcell, periodicity,\n               J_for_proof,\n               id,\n               prec, num_loops,\n               basic_exact_mode, pseudo_mode, pseudo_mode_with_proof,\n               verbose, very_verbose, obscenely_verbose);\n\n    return 0;\n}\n\nvoid read_from_file(std::string &id,\n                     int &max_sites,\n                     map< set<tuple<int,int,int,int,int> >, double> &J,\n                     double &prec,\n                     int &num_loops,\n                     bool &translation_algorithm,\n                     bool &basic_exact_mode,\n                     bool &pseudo_mode,\n                     bool &pseudo_mode_with_proof,\n                     bool &verbose,\n                     bool &very_verbose,\n                     bool &obscenely_verbose) {\n\tmap< set<tuple<int,int,int,int,int> >, double> J_negative1_positive1;\n\tset< tuple<int,int,int,int,int> >setoftupletemp;\n\tdouble constant_term = 0;\n\tint solver_mode = 1;\n\tint verbosity = 1;\n\n\tstd::ifstream t2(\"J_config.in\");\n\tstd::stringstream buffer2;\n\tbuffer2 << t2.rdbuf();\n\tstring J_config_file=buffer2.str();\n\n\tvector<string> J_config_line;\n\tsplit_is(J_config_file, '\\n', J_config_line);\n\tfor (vector<string>::iterator it=J_config_line.begin(); it!=J_config_line.end(); it++) {\n\t\tvector<string> J_config_line_segment;\n\t\tstring temp=*it;\n\t\tsplit_is(temp, ' ', J_config_line_segment);\n\t\tvector<string>::iterator segment_iterator=J_config_line_segment.begin();\n\t\tstring first_segment=*segment_iterator;\n\t\tvector<string> equal_left_right;\n\t\tsplit_is(first_segment, '=', equal_left_right);\n\t\tvector<string>::iterator equal_iterator=equal_left_right.begin();\n\t\tstring equal_left=*equal_iterator;\n\t\tequal_iterator++;\n\t\tstring equal_right=*equal_iterator;\n\n\t\tif (equal_left==\"NSITES\") {\n\t\t\tmax_sites=lexical_cast<int>(equal_right) ;\n\t\t}else if (equal_left==\"NLOOPS\") {\n\t\t\tnum_loops=lexical_cast<int>(equal_right) ;\n\t\t}else if (equal_left==\"LABEL\") {\n\t\t\tid=equal_right;\n\t\t}else if (equal_left==\"PREC\") {\n\t\t\tprec=lexical_cast<double>(equal_right) ;\n\t\t}else if (equal_left==\"MODE_JPLUSMINUS\") {\n\t\t\ttranslation_algorithm=lexical_cast<bool>(equal_right) ;\n\t\t}else if (equal_left==\"MODE_SOLVER\") {\n\t\t\tsolver_mode=lexical_cast<int>(equal_right) ;\n\t\t}else if (equal_left==\"MODE_VERBOSITY\") {\n\t\t\tverbosity = lexical_cast<int>(equal_right) ;\n\t\t}\n\t}\n\n\tif (solver_mode == 0) {\n\t\tbasic_exact_mode = true;\n\t\tpseudo_mode = false;\n\t\tpseudo_mode = false;\n\t}else if (solver_mode == 1) {\n\t\tbasic_exact_mode = false;\n\t\tpseudo_mode = true;\n\t\tpseudo_mode_with_proof = false;\n\t}else if (solver_mode == 2) {\n\t\tbasic_exact_mode = false;\n\t\tpseudo_mode = true;\n\t\tpseudo_mode_with_proof = true;\n\t}else{\n\t\tcout << \"Invalid solver mode given. Exiting.\" << endl;\n\t\texit(1);\n\t}\n\n\tif (verbosity == 0) {\n\t\tverbose = false;\n\t\tvery_verbose = false;\n\t\tobscenely_verbose = false;\n\t}else if (verbosity == 1) {\n\t\tverbose = true;\n\t\tvery_verbose = false;\n\t\tobscenely_verbose = false;\n\t}else if (verbosity == 2) {\n\t\tverbose = true;\n\t\tvery_verbose = true;\n\t\tobscenely_verbose = false;\n\t}else if (verbosity == 3) {\n\t\tverbose = true;\n\t\tvery_verbose = true;\n\t\tobscenely_verbose = true;\n\t}else {\n\t\tcout << \"Invalid verbosity mode given. Exiting.\" << endl;\n\t\texit(1);\n\t}\n\n\tstd::ifstream t1(\"J_in.in\");\n\tstd::stringstream buffer1;\n\tbuffer1 << t1.rdbuf();\n\tstring J_in_file=buffer1.str();\n\n\tvector<string> J_in_line;\n\tsplit_is(J_in_file, '\\n', J_in_line);\n\tint line_format_indicator=0;\n\tfor (vector<string>::iterator it=J_in_line.begin(); it!=J_in_line.end(); it++){\n\t\tstring this_line=*it;\n\t\tif (it==J_in_line.begin()){\n\t\t\tvector<string> segment;\n\t\t\tsplit_is(this_line, ' ', segment);\n\t\t\tvector<string>::iterator segment_iterator=segment.begin();\n\t\t\tstring temp_segment=*segment_iterator;\n\t\t\tif (temp_segment==\"Constant\"){\n\t\t\t\tsegment_iterator++;\n\t\t\t\tconstant_term=lexical_cast<double>(*segment_iterator);\n\t\t\t}\n\t\t}else{\n\t\t\tif (line_format_indicator==0) {\n\t\t\t\tvector<string> segment;\n\t\t\t\tsplit_is(this_line, ' ', segment);\n\t\t\t\tvector<string>::iterator segment_iterator=segment.begin();\n\t\t\t\tstring temp_segment=*segment_iterator;\n\t\t\t\tif (temp_segment==\"Cluster\") {\n\t\t\t\t\tline_format_indicator=1;\n\t\t\t\t}\n\t\t\t}else if (line_format_indicator==1){\n\t\t\t\tsetoftupletemp.clear();\n\t\t\t\tvector<string> segment;\n\t\t\t\tsplit_is(this_line, ' ', segment);\n\n\t\t\t\tfor (vector<string>::iterator it2=segment.begin(); it2!=segment.end(); it2++) {\n\t\t\t\t\tstring this_segment=*it2;\n\t\t\t\t\tvector<string> number_vector;\n\t\t\t\t\tsplit_is(this_segment, ',', number_vector);\n\t\t\t\t\tint l1,l2,l3,l4,l5;\n\t\t\t\t\tl1=lexical_cast<int>(number_vector[0]);\n\t\t\t\t\tl2=lexical_cast<int>(number_vector[1]);\n\t\t\t\t\tl3=lexical_cast<int>(number_vector[2]);\n\t\t\t\t\tl4=lexical_cast<int>(number_vector[3]);\n\t\t\t\t\tl5=lexical_cast<int>(number_vector[4]);\n\t\t\t\t\tsetoftupletemp.insert(make_tuple(l1,l2,l3,l4,l5));\n\t\t\t\t}\n\n\t\t\t\tline_format_indicator=2;\n\t\t\t}else if (line_format_indicator==2) {\n\t\t\t\tvector<string> segment;\n\t\t\t\tsplit_is(this_line, '=', segment);\n\n\t\t\t\tif (translation_algorithm){\n\t\t\t\t\tJ_negative1_positive1[setoftupletemp]=lexical_cast<double>(segment[1]);\n\t\t\t\t}else{\n\t\t\t\t\tJ[setoftupletemp]=lexical_cast<double>(segment[1]);\n\t\t\t\t}\n\n\t\t\t\tline_format_indicator=0;\n\t\t\t}\n\t\t}\n\t}\n\n\tif(translation_algorithm){\n\t\tconvertJ_neg1_pos1toJ(J_negative1_positive1, J, constant_term);\n\t}\n}\n", "meta": {"hexsha": "35037bd3290fb53eaa3548ca2eb2216afa727db7", "size": 7521, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/ising/main.cpp", "max_stars_repo_name": "dkitch/maxsat-ising", "max_stars_repo_head_hexsha": "ef6fe68f73e23b6d5729786a77aa468c4250f9b8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 13.0, "max_stars_repo_stars_event_min_datetime": "2016-10-27T22:56:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-06T12:48:02.000Z", "max_issues_repo_path": "src/ising/main.cpp", "max_issues_repo_name": "dkitch/maxsat-ising", "max_issues_repo_head_hexsha": "ef6fe68f73e23b6d5729786a77aa468c4250f9b8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/ising/main.cpp", "max_forks_repo_name": "dkitch/maxsat-ising", "max_forks_repo_head_hexsha": "ef6fe68f73e23b6d5729786a77aa468c4250f9b8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2016-10-23T15:13:44.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-30T11:51:33.000Z", "avg_line_length": 31.6008403361, "max_line_length": 112, "alphanum_fraction": 0.6586890041, "num_tokens": 1905, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.685949467848392, "lm_q2_score": 0.47268347662043286, "lm_q1q2_score": 0.32423697924851375}}
{"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#include <cmath>\n#include <iostream>\n#include <boost/math/tools/roots.hpp>\n#include <boost/bind.hpp>\n\n#include \"BoostTolerance.hpp\"\n#include \"HiornsAirwayWall.hpp\"\n#include \"MathsCustomFunctions.hpp\"\n#include \"Exception.hpp\"\n\n\nHiornsAirwayWall::HiornsAirwayWall() : mTargetPressure(0),\n                                       mRIn(0),\n                                       mROut(0),\n                                       mmu(0),\n                                       mphi1(0),\n                                       mphi2(0),\n                                       mC1(0),\n                                       mC2(0),\n                                       mA(0)\n{\n}\n\nHiornsAirwayWall::~HiornsAirwayWall() {}\n\nvoid HiornsAirwayWall::SetTimestep(double dt) {}\n\ndouble HiornsAirwayWall::CalculatePressureRadiusResidual(double radius)\n{\n\n    mTargetPressure = mAirwayPressure - mPleuralPressure;\n\n    double rin = radius;\n\n    double areaOfAirwayWall = M_PI*(mROut*mROut - mRIn*mRIn);\n    double rout = sqrt(rin*rin + areaOfAirwayWall/M_PI);\n    double pressure;\n\n    pressure = mmu*log((rin*mROut)/(rout*mRIn)) + mmu*((rin*rin - mRIn*mRIn)/2.)*((1./rin*rin) - (1./rout*rout)) + 2*cos(mphi2)*cos(mphi2)*mA*log(mROut/mRIn);\n\n    if (rin - mRIn > 0.)\n        {\n\n        //  THE COMMENTED OUT CODE CORRESPONDS TO THE PRELIMINARY VERSION OF THE HIORNS QUASI-STATIC\n        //  AIRWAY WALL MODEL (I.E. EQUATION 1.1 IN THE HIORNS LOOKUP TABLES NOTES). THE VERSION THAT\n        //  WE USE (FOLLOWING THE COMMENTED SECTION) INSTEAD IS MODIFIED SO THAT THE CONTRIBUTION OF\n        //  THE COLLAGEN TO THE STRAIN-ENERGY LAW SATISFIES THE MODEL OF HOLZAPFEL ET AL.\n\n        //  const int numberTrap = 10000;\n        //  double integrandVals[numberTrap];\n        //  double tVals[numberTrap];\n        //  double integralStuff = 0.;\n\n        //  double upperlimit = -1.;\n        //  double lowerlimit = -1.;\n\n        //  lowerlimit = ((sqrt(mC2)*(rout*rout - mROut*mROut)*cos(mphi1)*cos(mphi1))/((mROut)*(mROut)));\n        //  upperlimit = ((sqrt(mC2)*(rin*rin - mRIn*mRIn)*cos(mphi1)*cos(mphi1))/((mRIn)*(mRIn)));\n\n        //  for (int it = 0; it < numberTrap; it++)\n        //  {\n\n            //  double tVal = lowerlimit + ((double)it/((double)numberTrap - 1.))*(upperlimit - lowerlimit);\n            //  tVals[it] = tVal;\n            //  integrandVals[it] = (2.*exp(tVal*tVal)/sqrt(M_PI));\n\n        //  }\n\n        //  integralStuff = (0.5*(integrandVals[0] + integrandVals[numberTrap - 1]));\n        //  integralStuff = integralStuff*(tVals[1] - tVals[0]);\n        //  for (int i = 1; i < (numberTrap - 1); i++)\n        //  {\n            //  integralStuff = integralStuff + integrandVals[i]*(tVals[1] - tVals[0]);\n        //  }\n\n        //  pressure = pressure + mC1*sqrt(M_PI/mC2)*cos(mphi1)*cos(mphi1)*integralStuff;\n\n            double integralStuff = exp(mC2*((rin*rin - mRIn*mRIn)/(mRIn*mRIn))*((rin*rin - mRIn*mRIn)/(mRIn*mRIn))*cos(mphi1)*cos(mphi1)*cos(mphi1)*cos(mphi1)) - exp(mC2*((rout*rout - mROut*mROut)/(mROut*mROut))*((rout*rout - mROut*mROut)/(mROut*mROut))*cos(mphi1)*cos(mphi1)*cos(mphi1)*cos(mphi1));\n            pressure = pressure + (mC1/mC2)*cos(mphi1)*cos(mphi1)*integralStuff;\n\n        }\n\n    double residual = mTargetPressure - pressure;\n\n    return residual;\n\n}\n\nvoid HiornsAirwayWall::SolveAndUpdateState(double tStart, double tEnd)\n{\n\n    double guess = (mRIn + mROut)/2.;\n    double factor = 2.;\n\n    Tolerance tol = 0.000001;\n    boost::uintmax_t maxIterations = 500u;\n\n    std::pair<double, double> found = boost::math::tools::bracket_and_solve_root(boost::bind(&HiornsAirwayWall::CalculatePressureRadiusResidual, this, _1), guess, factor, false, tol, maxIterations);\n    mDeformedAirwayRadius = found.first;\n}\n\nvoid HiornsAirwayWall::SetRIn(double RIn)\n{\n    assert (RIn >= 0.0);\n    mRIn = RIn;\n}\n\nvoid HiornsAirwayWall::SetROut(double ROut)\n{\n    assert (ROut >= 0.0);\n    mROut = ROut;\n}\n\nvoid HiornsAirwayWall::Setmu(double mu)\n{\n    assert (mu >= 0.0);\n    mmu = mu;\n}\n\nvoid HiornsAirwayWall::Setphi1(double phi1)\n{\n    mphi1 = phi1;\n}\n\nvoid HiornsAirwayWall::Setphi2(double phi2)\n{\n    mphi2 = phi2;\n}\n\nvoid HiornsAirwayWall::SetC1(double C1)\n{\n    mC1 = C1;\n}\n\nvoid HiornsAirwayWall::SetC2(double C2)\n{\n    mC2 = C2;\n}\n\nvoid HiornsAirwayWall::SetA(double A)\n{\n    mA = A;\n}\n\ndouble HiornsAirwayWall::GetLumenRadius()\n{\n    return mDeformedAirwayRadius;\n}\n\nvoid HiornsAirwayWall::SetAirwayPressure(double pressure)\n{\n    mAirwayPressure = pressure;\n}\n\nvoid HiornsAirwayWall::SetPleuralPressure(double pressure)\n{\n    mPleuralPressure = pressure;\n}\n", "meta": {"hexsha": "60812dfaa5222a0095a6415b25b7e7949c105e41", "size": 6298, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lung/src/ventilation/odes/HiornsAirwayWall.cpp", "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": "lung/src/ventilation/odes/HiornsAirwayWall.cpp", "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": "lung/src/ventilation/odes/HiornsAirwayWall.cpp", "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": 32.4639175258, "max_line_length": 299, "alphanum_fraction": 0.6546522706, "num_tokens": 1751, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6334102498375401, "lm_q2_score": 0.5117166047041654, "lm_q1q2_score": 0.32412654243168315}}
{"text": "/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */\n\n/*!\nCalibration of Heston model on SPX vol surface\n*/\n\n#include <ql/quantlib.hpp>\n#include \"CsvHelper.hpp\"\n#include \"HestonTools.hpp\"\n\n#ifdef BOOST_MSVC\n/* Uncomment the following lines to unmask floating-point\n   exceptions. Warning: unpredictable results can arise...\n\n   See http://www.wilmott.com/messageview.cfm?catid=10&threadid=9481\n   Is there anyone with a definitive word about this?\n*/\n// #include <float.h>\n// namespace { unsigned int u = _controlfp(_EM_INEXACT, _MCW_EM); }\n#endif\n\n#include <boost/timer.hpp>\n#include <iostream>\n#include <iomanip>\n#include <string>\n#include <fstream>\n\n#define DEBUG_OUT true\n\nusing namespace QuantLib;\n\n#if defined(QL_ENABLE_SESSIONS)\nnamespace QuantLib\n{\n\nInteger sessionId()\n{\n    return 0;\n}\n\n}\n#endif\n\n\nint main(int, char* [])\n{\n\n    Handle<Quote> s0(boost::shared_ptr<Quote>(new SimpleQuote(1290.59)));\n\n    try\n    {\n\n// calibration data\n\n        std::fstream file1(\"/home/phn/dev/R/ValidationModeles/calibration.csv\", ios::in);\n        if (!file1.is_open())\n        {\n            std::cout << \"Calibration File not found!\\n\";\n            return 1;\n        }\n\n        std::vector<CALIB> calibData;\n        readCSV_Calib(file1, calibData);\n        file1.close();\n\n// interest rates and dividend yield\n\n        std::fstream file2(\"/home/phn/dev/R/ValidationModeles/rate_div.csv\", ios::in);\n        if (!file2.is_open())\n        {\n            std::cout << \"Rate/Yield File not found!\\n\";\n            return 1;\n        }\n\n        std::vector<RD> RDData;\n        readCSV_RD(file2, RDData);\n        file2.close();\n\n        std::vector<double> res;\n\n        res = HestonCalibration(s0, calibData, RDData);\n\n        if (DEBUG_OUT)\n            std::cout << \"Theta: \" << res[0] <<\n                      \"\\nKappa: \" << res[1] <<\n                      \"\\nsigma: \" << res[2] <<\n                      \"\\nrho: \" << res[3] <<\n                      \"\\nv0: \" << res[4] <<\n                      \"\\nsse: \" << res[5] << std::endl;\n\n    }\n    catch (std::exception& e)\n    {\n        std::cerr << e.what() << std::endl;\n        return 1;\n    }\n    catch (...)\n    {\n        std::cerr << \"unknown error\" << std::endl;\n        return 1;\n    }\n}\n", "meta": {"hexsha": "bc1cbe03766ebd5fab1bb7182c67c1a1aaa981fc", "size": 2254, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/c++/HestonCalibrationDriver.cpp", "max_stars_repo_name": "bpmbank/pyql", "max_stars_repo_head_hexsha": "db1fc886a61ab3e234cebf54723abaa4258138b3", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 488.0, "max_stars_repo_stars_event_min_datetime": "2015-01-13T11:03:27.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T07:19:44.000Z", "max_issues_repo_path": "examples/c++/HestonCalibrationDriver.cpp", "max_issues_repo_name": "bpmbank/pyql", "max_issues_repo_head_hexsha": "db1fc886a61ab3e234cebf54723abaa4258138b3", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 139.0, "max_issues_repo_issues_event_min_datetime": "2015-01-05T18:56:55.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-26T18:33:37.000Z", "max_forks_repo_path": "examples/c++/HestonCalibrationDriver.cpp", "max_forks_repo_name": "bpmbank/pyql", "max_forks_repo_head_hexsha": "db1fc886a61ab3e234cebf54723abaa4258138b3", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 142.0, "max_forks_repo_forks_event_min_datetime": "2015-01-07T14:26:46.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-23T14:08:47.000Z", "avg_line_length": 21.8834951456, "max_line_length": 89, "alphanum_fraction": 0.5585625555, "num_tokens": 601, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6334102498375401, "lm_q2_score": 0.5117166047041654, "lm_q1q2_score": 0.32412654243168315}}
{"text": "#include \"RooRealVar.h\"\n#include \"RooRealConstant.h\"\n#include \"RooGaussian.h\"\n#include \"RooExponential.h\"\n#include \"RooAddPdf.h\"\n#include \"RooAddition.h\"\n#include \"RooDataSet.h\"\n#include \"RooDataHist.h\"\n#include \"RooHistPdf.h\"\n#include \"RooChebychev.h\"\n#include \"RooExponential.h\"\n#include \"RooProdPdf.h\"\n#include \"RooChi2Var.h\"\n#include \"RooGlobalFunc.h\"\n#include \"RooPlot.h\"\n#include \"RooMinuit.h\"\n#include \"RooFitResult.h\"\n#include \"RooFormulaVar.h\"\n#include \"RooGenericPdf.h\"\n#include \"RooExtendPdf.h\"\n#include \"TCanvas.h\"\n#include \"TROOT.h\"\n#include \"TFile.h\"\n#include \"TH1.h\"\n#include \"RooNLLVar.h\"\n#include \"RooRandom.h\"\n#include \"TRandom3.h\"\n#include <iostream>\n#include <fstream>\n#include <boost/program_options.hpp>\nusing namespace boost;\nnamespace po = boost::program_options;\n#include <vector>\n\nusing namespace std;\nusing namespace RooFit;\n\n// A function that get histogram, restricting it on fit range  and sets contents to 0.0 if entries are too small\n\nTH1F *getHisto(TFile *file, const char *name, double fMin, double fMax, unsigned int rebin) {\n  TObject *h = file->Get(name);\n  if (h == nullptr)\n    cout << \"Can't find object \" << name << \"\\n\";\n  TH1F *histo = dynamic_cast<TH1F *>(h);\n  if (histo == nullptr)\n    cout << \"Object \" << name << \" is of type \" << h->ClassName() << \", not TH1\\n\";\n  TH1F *new_histo = new TH1F(name, name, (int)(fMax - fMin), fMin, fMax);\n  int bin_num = 0;\n  for (int i = (int)fMin; i <= (int)fMax; ++i) {\n    bin_num = (i - (int)fMin + 1);\n    new_histo->SetBinContent(bin_num, histo->GetBinContent(i));\n  }\n  delete histo;\n  new_histo->Sumw2();\n  new_histo->Rebin(rebin);\n  for (int i = 1; i <= new_histo->GetNbinsX(); ++i) {\n    if (new_histo->GetBinContent(i) == 0.00) {\n      cout << \" WARNING: histo \" << name << \" has 0 enter in bin number \" << i << endl;\n    }\n    if (new_histo->GetBinContent(i) < 0.1) {\n      new_histo->SetBinContent(i, 0.0);\n      new_histo->SetBinError(i, 0.0);\n      cout << \" WARNING: setting value 0.0 to histo \" << name << \" for bin number \" << i << endl;\n    }\n  }\n\n  return new_histo;\n}\n\n// a function that create fromm a model pdf a toy RooDataHist\n\nRooDataHist *genHistFromModelPdf(\n    const char *name, RooAbsPdf *model, RooRealVar *var, double ScaleLumi, int range, int rebin, int seed) {\n  double genEvents = model->expectedEvents(*var);\n  TRandom3 *rndm = new TRandom3();\n  rndm->SetSeed(seed);\n  double nEvt = rndm->PoissonD(genEvents);\n  int intEvt = ((nEvt - (int)nEvt) >= 0.5) ? (int)nEvt + 1 : int(nEvt);\n  RooDataSet *data = model->generate(*var, intEvt);\n  cout << \" expected events for \" << name << \" = \" << genEvents << endl;\n  cout << \" data->numEntries() for name \" << name << \" == \" << data->numEntries() << endl;\n  // cout<< \" nEvt from PoissonD for\" << name << \" == \" << nEvt<< endl;\n  //cout<< \" cast of nEvt  for\" << name << \" == \" << intEvt<< endl;\n  RooAbsData *binned_data = data->binnedClone();\n  TH1 *toy_hist = binned_data->createHistogram(name, *var, Binning(range / rebin));\n  for (int i = 1; i <= toy_hist->GetNbinsX(); ++i) {\n    toy_hist->SetBinError(i, sqrt(toy_hist->GetBinContent(i)));\n    if (toy_hist->GetBinContent(i) == 0.00) {\n      cout << \" WARNING: histo \" << name << \" has 0 enter in bin number \" << i << endl;\n    }\n    if (toy_hist->GetBinContent(i) < 0.1) {\n      toy_hist->SetBinContent(i, 0.0);\n      toy_hist->SetBinError(i, 0.0);\n      cout << \" WARNING: setting value 0.0 to histo \" << name << \" for bin number \" << i << endl;\n    }\n  }\n  RooDataHist *toy_rooHist = new RooDataHist(name, name, RooArgList(*var), toy_hist);\n  return toy_rooHist;\n}\n\n// a function to create the pdf used for the fit, need the histo model, should be zmm except for zmusta case.....\n\nRooHistPdf *createHistPdf(const char *name, TH1F *model, RooRealVar *var, int rebin) {\n  TH1F *model_clone = new TH1F(*model);\n  model_clone->Sumw2();\n  model_clone->Rebin(rebin);\n  RooDataHist *model_dataHist = new RooDataHist(name, name, RooArgList(*var), model_clone);\n  RooHistPdf *HistPdf = new RooHistPdf(name, name, *var, *model_dataHist, 0);\n  delete model_clone;\n  return HistPdf;\n}\n\nvoid fit(RooAbsReal &chi2, int numberOfBins, const char *outFileNameWithFitResult) {\n  TFile *out_root_file = new TFile(outFileNameWithFitResult, \"recreate\");\n  RooMinuit m_tot(chi2);\n  m_tot.migrad();\n  // m_tot.hesse();\n  RooFitResult *r_chi2 = m_tot.save();\n  cout << \"==> Chi2 Fit results \" << endl;\n  r_chi2->Print(\"v\");\n  //  r_chi2->floatParsFinal().Print(\"v\") ;\n  int NumberOfFreeParameters = r_chi2->floatParsFinal().getSize();\n  for (int i = 0; i < NumberOfFreeParameters; ++i) {\n    r_chi2->floatParsFinal()[i].Print();\n  }\n  cout << \"chi2:\" << chi2.getVal() << \", numberOfBins: \" << numberOfBins\n       << \", NumberOfFreeParameters: \" << NumberOfFreeParameters << endl;\n  cout << \"Normalized Chi2   = \" << chi2.getVal() / (numberOfBins - NumberOfFreeParameters) << endl;\n  r_chi2->Write();\n  delete out_root_file;\n}\n\nint main(int argc, char **argv) {\n  gROOT->SetStyle(\"Plain\");\n  double fMin, fMax, lumi, scaleLumi = 1;\n  int seed;\n  Bool_t toy = kFALSE;\n  Bool_t fitFromData = kFALSE;\n  string infile, outfile;\n  int rebinZMuMu = 1, rebinZMuSa = 1, rebinZMuTk = 1, rebinZMuMuNoIso = 1, rebinZMuMuHlt = 1;\n  po::options_description desc(\"Allowed options\");\n  desc.add_options()(\"help,h\", \"produce help message\")(\"toy,t\", \"toy enabled\")(\n      \"seed,s\", po::value<int>(&seed)->default_value(34567), \"seed value for toy\")(\n      \"luminosity,l\", po::value<double>(&lumi)->default_value(45.), \"luminosity value for toy \")(\n      \"fit,f\", \"fit from data enabled\")(\n      \"rebin,r\", po::value<vector<int> >(), \"rebin value: r_mutrk r mumuNotIso r_musa r _muhlt\")(\n      \"input-file,i\", po::value<string>(&infile), \"input file\")(\n      \"output-file,o\", po::value<string>(&outfile), \"output file with fit results\")(\n      \"min,m\", po::value<double>(&fMin)->default_value(60), \"minimum value for fit range\")(\n      \"max,M\", po::value<double>(&fMax)->default_value(120), \"maximum value for fit range\");\n  po::positional_options_description p;\n  p.add(\"rebin\", -1);\n  po::variables_map vm;\n  po::store(po::command_line_parser(argc, argv).options(desc).positional(p).run(), vm);\n  po::notify(vm);\n  if (vm.count(\"help\")) {\n    cout << \"Usage: options_description [options]\\n\";\n    cout << desc;\n    return 0;\n  }\n\n  if (vm.count(\"toy\")) {\n    cout << \"toy enabled with seed \" << seed << \"\\n\";\n    toy = kTRUE;\n    //RooRandom::randomGenerator()->SetSeed(seed) ;\n    // lumi should be intented as pb-1 and passed from outside\n    scaleLumi = lumi / 45.0;  // 45 is the current lumi correspondent to the histogram.....\n  }\n  if (vm.count(\"fit\")) {\n    cout << \"fit from data enabled \\n\";\n    fitFromData = kTRUE;\n  }\n\n  if (!vm.count(\"toy\") && !vm.count(\"fit\")) {\n    cerr << \"Choose one beetween  fitting form data or with a toy MC \\n\";\n    return 1;\n  }\n\n  if (toy == fitFromData) {\n    cerr << \"Choose if fit from data or with a toy MC \\n\";\n    return 1;\n  }\n\n  if (vm.count(\"rebin\")) {\n    vector<int> v_rebin = vm[\"rebin\"].as<vector<int> >();\n    if (v_rebin.size() != 4) {\n      cerr << \" please provide 4 numbers in the given order:r_mutrk r mumuNotIso r_musa r _muhlt \\n\";\n      return 1;\n    }\n    rebinZMuTk = v_rebin[0];\n    rebinZMuMuNoIso = v_rebin[1];\n    rebinZMuSa = v_rebin[2];\n    rebinZMuMuHlt = v_rebin[3];\n  }\n\n  RooRealVar *mass = new RooRealVar(\"mass\", \"mass (GeV/c^{2})\", fMin, fMax);\n  TFile *root_file = new TFile(infile.c_str(), \"read\");\n  int range = (int)(fMax - fMin);\n  int numberOfBins = range / rebinZMuSa + range / rebinZMuTk + range / rebinZMuMuNoIso + 2 * range / rebinZMuMuHlt;\n  // zmm histograms used for pdf\n  TH1F *zmm = getHisto(root_file, \"goodZToMuMuPlots/zMass\", fMin, fMax, rebinZMuMu);\n  // zmsta used for pdf\n  TH1F *zmsta = getHisto(root_file, \"zmumuSaMassHistogram/zMass\", fMin, fMax, 1);  // histogramms to fit.....\n  TH1F *zmmsta = getHisto(root_file, \"goodZToMuMuOneStandAloneMuonPlots/zMass\", fMin, fMax, rebinZMuSa / rebinZMuMu);\n  TH1F *zmt = getHisto(root_file, \"goodZToMuMuOneTrackPlots/zMass\", fMin, fMax, rebinZMuTk / rebinZMuMu);\n  TH1F *zmmNotIso = getHisto(root_file, \"nonIsolatedZToMuMuPlots/zMass\", fMin, fMax, rebinZMuMuNoIso / rebinZMuMu);\n  TH1F *zmm1hlt = getHisto(root_file, \"goodZToMuMu1HLTPlots/zMass\", fMin, fMax, rebinZMuMuHlt / rebinZMuMu);\n  TH1F *zmm2hlt = getHisto(root_file, \"goodZToMuMu2HLTPlots/zMass\", fMin, fMax, rebinZMuMuHlt / rebinZMuMu);\n\n  // creating a pdf for Zmt\n\n  RooHistPdf *ZmtPdf = createHistPdf(\"ZmtPdf\", zmm, mass, rebinZMuTk / rebinZMuMu);\n  // creating a pdf for Zmm not iso\n  RooHistPdf *ZmmNoIsoPdf = createHistPdf(\"ZmmNoIsoPdf\", zmm, mass, rebinZMuMuNoIso / rebinZMuMu);\n  // creating a pdf for Zms from zmsta!!!\n  RooHistPdf *ZmsPdf = createHistPdf(\"ZmsPdf\", zmsta, mass, rebinZMuSa / rebinZMuMu);\n  // creating a pdf for Zmmhlt\n  RooHistPdf *ZmmHltPdf = createHistPdf(\"ZmmHltPdf\", zmm, mass, rebinZMuMuHlt / rebinZMuMu);\n\n  // creating the variable with random init values\n\n  RooRealVar Yield(\"Yield\", \"Yield\", 15000., 345., 3567890.);\n  RooRealVar nbkg_mutrk(\"nbkg_mutrk\", \"background _mutrk fraction\", 500, 0., 100000.);\n  RooRealVar nbkg_mumuNotIso(\"nbkg_mumuNotIso\", \"background fraction\", 500, 0., 100000.);\n  RooRealVar nbkg_musa(\"nbkg_musa\", \"background fraction\", 50, 0., 100000.);\n  RooRealVar eff_tk(\"eff_tk\", \"signal _mutrk fraction\", .99, 0.8, 1.0);\n  RooRealVar eff_sa(\"eff_sa\", \"eff musta\", 0.99, 0.8, 1.0);\n  RooRealVar eff_iso(\"eff_iso\", \"eff mumuNotIso\", .99, 0.8, 1.0);\n  RooRealVar eff_hlt(\"eff_hlt\", \"eff 1hlt\", 0.99, 0.8, 1.0);\n  RooRealVar alpha(\"alpha\", \"coefficient alpha\", -0.01, -1000, 1000.);\n  RooRealVar a0(\"a0\", \"coefficient 0\", 1, -1000., 1000.);\n  RooRealVar a1(\"a1\", \"coefficient 1\", -0.001, -1000, 1000.);\n  RooRealVar a2(\"a2\", \"coefficient 2\", 0.0, -1000., 1000.);\n  RooRealVar beta(\"beta\", \"coefficient beta\", -0.01, -1000, 1000.);\n  RooRealVar b0(\"b0\", \"coefficient 0\", 1, -1000., 1000.);\n  RooRealVar b1(\"b1\", \"coefficient 1\", -0.001, -1000, 1000.);\n  RooRealVar b2(\"b2\", \"coefficient 2\", 0.0, -1000., 1000.);\n  RooRealVar gamma(\"gamma\", \"coefficient gamma\", -0.01, -1000, 1000.);\n  RooRealVar c0(\"c0\", \"coefficient 0\", 1, -1000., 1000.);\n  RooRealVar c1(\"c1\", \"coefficient 1\", -0.001, -1000, 1000.);\n  // fit parameters setted from datacard\n  filebuf fb;\n  fb.open(\"zMuMuRooFit.txt\", ios::in);\n  istream is(&fb);\n  char line[1000];\n\n  Yield.readFromStream(is.getline(line, 1000), kFALSE);\n  nbkg_mutrk.readFromStream(is.getline(line, 1000), kFALSE);\n  nbkg_mumuNotIso.readFromStream(is.getline(line, 1000), kFALSE);\n  nbkg_musa.readFromStream(is.getline(line, 1000), kFALSE);\n  eff_tk.readFromStream(is.getline(line, 1000), kFALSE);\n  eff_sa.readFromStream(is.getline(line, 1000), kFALSE);\n  eff_iso.readFromStream(is.getline(line, 1000), kFALSE);\n  eff_hlt.readFromStream(is.getline(line, 1000), kFALSE);\n  alpha.readFromStream(is.getline(line, 1000), kFALSE);\n  a0.readFromStream(is.getline(line, 1000), kFALSE);\n  a1.readFromStream(is.getline(line, 1000), kFALSE);\n  a2.readFromStream(is.getline(line, 1000), kFALSE);\n  beta.readFromStream(is.getline(line, 1000), kFALSE);\n  b0.readFromStream(is.getline(line, 1000), kFALSE);\n  b1.readFromStream(is.getline(line, 1000), kFALSE);\n  b2.readFromStream(is.getline(line, 1000), kFALSE);\n  gamma.readFromStream(is.getline(line, 1000), kFALSE);\n  c0.readFromStream(is.getline(line, 1000), kFALSE);\n  c1.readFromStream(is.getline(line, 1000), kFALSE);\n  fb.close();\n\n  // scaling to lumi if toy is enabled...\n  if (vm.count(\"toy\")) {\n    Yield.setVal(scaleLumi * (Yield.getVal()));\n    nbkg_mutrk.setVal(scaleLumi * (nbkg_mutrk.getVal()));\n    nbkg_mumuNotIso.setVal(scaleLumi * (nbkg_mumuNotIso.getVal()));\n  }\n\n  //efficiency term\n\n  //zMuMuEff1HLTTerm = _2 * (effTk ^ _2) *  (effSa ^ _2) * (effIso ^ _2) * effHLT * (_1 - effHLT);\n  RooFormulaVar zMuMu1HLTEffTerm(\n      \"zMuMu1HLTEffTerm\",\n      \"Yield * (2.* (eff_tk)^2 * (eff_sa)^2 * (eff_iso)^2 * eff_hlt *(1.- eff_hlt))\",\n      RooArgList(eff_tk,\n                 eff_sa,\n                 eff_iso,\n                 eff_hlt,\n                 Yield));  //zMuMuEff2HLTTerm = (effTk ^ _2) *  (effSa ^ _2) * (effIso ^ _2) * (effHLT ^ _2) ;\n  RooFormulaVar zMuMu2HLTEffTerm(\"zMuMu2HLTEffTerm\",\n                                 \"Yield * ((eff_tk)^2 * (eff_sa)^2 * (eff_iso)^2 * (eff_hlt)^2)\",\n                                 RooArgList(eff_tk, eff_sa, eff_iso, eff_hlt, Yield));\n  //zMuMuNoIsoEffTerm = (effTk ^ _2) * (effSa ^ _2) * (_1 - (effIso ^ _2)) * (_1 - ((_1 - effHLT)^_2));\n  RooFormulaVar zMuMuNoIsoEffTerm(\"zMuMuNoIsoEffTerm\",\n                                  \"Yield * ((eff_tk)^2 * (eff_sa)^2 * (1.- (eff_iso)^2) * (1.- ((1.-eff_hlt)^2)))\",\n                                  RooArgList(eff_tk, eff_sa, eff_iso, eff_hlt, Yield));\n  //zMuTkEffTerm = _2 * (effTk ^ _2) * effSa * (_1 - effSa) * (effIso ^ _2) * effHLT;\n  RooFormulaVar zMuTkEffTerm(\"zMuTkEffTerm\",\n                             \"Yield * (2. *(eff_tk)^2 * eff_sa * (1.-eff_sa)* (eff_iso)^2 * eff_hlt)\",\n                             RooArgList(eff_tk, eff_sa, eff_iso, eff_hlt, Yield));\n  //zMuSaEffTerm = _2 * (effSa ^ _2) * effTk * (_1 - effTk) * (effIso ^ _2) * effHLT;\n  RooFormulaVar zMuSaEffTerm(\"zMuSaEffTerm\",\n                             \"Yield * (2. *(eff_sa)^2 * eff_tk * (1.-eff_tk)* (eff_iso)^2 * eff_hlt)\",\n                             RooArgList(eff_tk, eff_sa, eff_iso, eff_hlt, Yield));\n\n  // creating model for the  fit\n  // z mu track\n\n  RooGenericPdf *bkg_mutrk = new RooGenericPdf(\"bkg_mutrk\",\n                                               \"zmt bkg_model\",\n                                               \"exp(alpha*mass) * ( a0 + a1 * mass + a2 * mass^2 )\",\n                                               RooArgSet(*mass, alpha, a0, a1, a2));\n  // RooFormulaVar fracSigMutrk(\"fracSigMutrk\", \"@0 / (@0 + @1)\", RooArgList(zMuTkEffTerm, nbkg_mutrk ));\n  RooAddPdf *model_mutrk = new RooAddPdf(\n      \"model_mutrk\", \"model_mutrk\", RooArgList(*ZmtPdf, *bkg_mutrk), RooArgList(zMuTkEffTerm, nbkg_mutrk));\n  // z mu mu not Iso\n\n  // creating background pdf for zmu mu not Iso\n  RooGenericPdf *bkg_mumuNotIso = new RooGenericPdf(\"bkg_mumuNotIso\",\n                                                    \"zmumuNotIso bkg_model\",\n                                                    \"exp(beta * mass) * (b0 + b1 * mass + b2 * mass^2)\",\n                                                    RooArgSet(*mass, beta, b0, b1, b2));\n  // RooFormulaVar fracSigMuMuNoIso(\"fracSigMuMuNoIso\", \"@0 / (@0 + @1)\", RooArgList(zMuMuNoIsoEffTerm, nbkg_mumuNotIso ));\n  RooAddPdf *model_mumuNotIso = new RooAddPdf(\"model_mumuNotIso\",\n                                              \"model_mumuNotIso\",\n                                              RooArgList(*ZmmNoIsoPdf, *bkg_mumuNotIso),\n                                              RooArgList(zMuMuNoIsoEffTerm, nbkg_mumuNotIso));\n  // z mu sta\n\n  // RooGenericPdf model_musta(\"model_musta\",  \" ZmsPdf * zMuSaEffTerm \", RooArgSet( *ZmsPdf, zMuSaEffTerm)) ;\n  RooGenericPdf *bkg_musa = new RooGenericPdf(\n      \"bkg_musa\", \"zmusa bkg_model\", \"exp(gamma * mass) * (c0 + c1 * mass )\", RooArgSet(*mass, gamma, c0, c1));\n  // RooAddPdf * eZmsSig= new RooAddPdf(\"eZmsSig\",\"eZmsSig\",RooArgList(*,*bkg_mumuNotIso), RooArgList(zMuMuNoIsoEffTerm, nbkg_mumuNotIso));\n  RooAddPdf *eZmsSig =\n      new RooAddPdf(\"eZmsSig\", \"eZmsSig\", RooArgList(*ZmsPdf, *bkg_musa), RooArgList(zMuSaEffTerm, nbkg_musa));\n\n  //RooExtendPdf * eZmsSig= new RooExtendPdf(\"eZmsSig\",\"extended signal p.d.f for zms \",*ZmsPdf,  zMuSaEffTerm ) ;\n\n  // z mu mu HLT\n\n  // count ZMuMu Yield\n  double nZMuMu = 0.;\n  double nZMuMu1HLT = 0.;\n  double nZMuMu2HLT = 0.;\n  unsigned int nBins = zmm->GetNbinsX();\n  double xMin = zmm->GetXaxis()->GetXmin();\n  double xMax = zmm->GetXaxis()->GetXmax();\n  double deltaX = (xMax - xMin) / nBins;\n  for (unsigned int i = 0; i < nBins; ++i) {\n    double x = xMin + (i + .5) * deltaX;\n    if (x > fMin && x < fMax) {\n      nZMuMu += zmm->GetBinContent(i + 1);\n      nZMuMu1HLT += zmm1hlt->GetBinContent(i + 1);\n      nZMuMu2HLT += zmm2hlt->GetBinContent(i + 1);\n    }\n  }\n\n  cout << \">>> count of ZMuMu yield in the range [\" << fMin << \", \" << fMax << \"]: \" << nZMuMu << endl;\n  cout << \">>> count of ZMuMu (1HLT) yield in the range [\" << fMin << \", \" << fMax << \"]: \" << nZMuMu1HLT << endl;\n  cout << \">>> count of ZMuMu (2HLT) yield in the range [\" << fMin << \", \" << fMax << \"]: \" << nZMuMu2HLT << endl;\n  // we set eff_hlt\n  //eff_hlt.setVal( 1. / (1. + (nZMuMu1HLT/ (2 * nZMuMu2HLT))) ) ;\n  // creating the pdf for z mu mu 1hlt\n\n  RooExtendPdf *eZmm1hltSig =\n      new RooExtendPdf(\"eZmm1hltSig\", \"extended signal p.d.f for zmm 1hlt\", *ZmmHltPdf, zMuMu1HLTEffTerm);\n  // creating the pdf for z mu mu 2hlt\n  RooExtendPdf *eZmm2hltSig =\n      new RooExtendPdf(\"eZmm2hltSig\", \"extended signal p.d.f for zmm 2hlt\", *ZmmHltPdf, zMuMu2HLTEffTerm);\n\n  // getting the data if fit otherwise constructed the data for model if toy....\n\n  RooDataHist *zmtMass, *zmmNotIsoMass, *zmsMass, *zmm1hltMass, *zmm2hltMass;\n\n  if (toy) {\n    zmtMass = genHistFromModelPdf(\"zmtMass\", model_mutrk, mass, scaleLumi, range, rebinZMuTk, seed);\n    zmmNotIsoMass =\n        genHistFromModelPdf(\"zmmNotIsoMass\", model_mumuNotIso, mass, scaleLumi, range, rebinZMuMuNoIso, seed);\n    zmsMass = genHistFromModelPdf(\"zmsMass\", eZmsSig, mass, scaleLumi, range, rebinZMuSa, seed);\n    zmm1hltMass = genHistFromModelPdf(\"zmm1hltMass\", eZmm1hltSig, mass, scaleLumi, range, rebinZMuMuHlt, seed);\n    zmm2hltMass = genHistFromModelPdf(\"zmm2hltMass\", eZmm2hltSig, mass, scaleLumi, range, rebinZMuMuHlt, seed);\n  } else {  // if  fit from data....\n    zmtMass = new RooDataHist(\"zmtMass\", \"good z mu track\", RooArgList(*mass), zmt);\n    zmmNotIsoMass = new RooDataHist(\"ZmmNotIso\", \"good z mu mu not isolated\", RooArgList(*mass), zmmNotIso);\n    zmsMass = new RooDataHist(\"zmsMass\", \"good z mu sta mass\", RooArgList(*mass), zmmsta);\n    zmm1hltMass = new RooDataHist(\"zmm1hltMass\", \"good Z mu mu 1hlt\", RooArgList(*mass), zmm1hlt);\n    zmm2hltMass = new RooDataHist(\"zmm2hltMass\", \"good Z mu mu 2hlt\", RooArgList(*mass), zmm2hlt);\n  }\n\n  // creting the chi2s\n  RooChi2Var *chi2_mutrk =\n      new RooChi2Var(\"chi2_mutrk\", \"chi2_mutrk\", *model_mutrk, *zmtMass, Extended(kTRUE), DataError(RooAbsData::SumW2));\n  RooChi2Var *chi2_mumuNotIso = new RooChi2Var(\"chi2_mumuNotIso\",\n                                               \"chi2_mumuNotIso\",\n                                               *model_mumuNotIso,\n                                               *zmmNotIsoMass,\n                                               Extended(kTRUE),\n                                               DataError(RooAbsData::SumW2));\n\n  RooChi2Var *chi2_musta =\n      new RooChi2Var(\"chi2_musta\", \"chi2_musta\", *eZmsSig, *zmsMass, Extended(kTRUE), DataError(RooAbsData::SumW2));\n  // uncomment this line if you want to use logLik for mu sta\n  // RooNLLVar *chi2_musta = new RooNLLVar(\"chi2_musta\",\"chi2_musta\",*eZmsSig, *zmsMass,  Extended(kTRUE), DataError(RooAbsData::SumW2) ) ;\n  RooChi2Var *chi2_mu1hlt = new RooChi2Var(\n      \"chi2_mu1hlt\", \"chi2_mu1hlt\", *eZmm1hltSig, *zmm1hltMass, Extended(kTRUE), DataError(RooAbsData::SumW2));\n  RooChi2Var *chi2_mu2hlt = new RooChi2Var(\n      \"chi2_mu2hlt\", \"chi2_mu2hlt\", *eZmm2hltSig, *zmm2hltMass, Extended(kTRUE), DataError(RooAbsData::SumW2));\n\n  // adding the chi2\n  RooAddition totChi2(\"totChi2\",\n                      \"chi2_mutrk + chi2_mumuNotIso  + chi2_musta   + chi2_mu1hlt  +  chi2_mu2hlt \",\n                      RooArgSet(*chi2_mutrk, *chi2_mumuNotIso, *chi2_musta, *chi2_mu1hlt, *chi2_mu2hlt));\n\n  // printing out the model integral befor fitting\n  double N_zMuMu1hlt = eZmm1hltSig->expectedEvents(*mass);\n  double N_bkgTk = bkg_mutrk->expectedEvents(*mass);\n  double N_bkgIso = bkg_mumuNotIso->expectedEvents(*mass);\n\n  double N_zMuTk = zMuTkEffTerm.getVal();\n\n  double e_hlt = eff_hlt.getVal();\n  double e_tk = eff_tk.getVal();\n  double e_sa = eff_sa.getVal();\n  double e_iso = eff_iso.getVal();\n  double Y_hlt = N_zMuMu1hlt / ((2. * (e_tk * e_tk) * (e_sa * e_sa) * (e_iso * e_iso) * e_hlt * (1. - e_hlt)));\n  double Y_mutk = N_zMuTk / ((2. * (e_tk * e_tk) * e_sa * (1. - e_sa) * (e_iso * e_iso) * e_hlt));\n\n  cout << \"Yield prediction from mumu1hlt integral befor fitting: \" << Y_hlt << endl;\n  cout << \"Yield prediction from mutk integral befor fitting: \" << Y_mutk << endl;\n  cout << \"Bkg for mutk prediction from mutk integral after fitting: \" << N_bkgTk << endl;\n  cout << \"Bkg for mumuNotIso prediction from mumuNotIso integral after fitting: \" << N_bkgIso << endl;\n\n  fit(totChi2, numberOfBins, outfile.c_str());\n  N_zMuMu1hlt = eZmm1hltSig->expectedEvents(*mass);\n  N_zMuTk = zMuTkEffTerm.getVal();\n  double N_zMuMuNoIso = zMuMuNoIsoEffTerm.getVal();\n  double N_Tk = model_mutrk->expectedEvents(*mass);\n  double N_Iso = model_mumuNotIso->expectedEvents(*mass);\n  e_hlt = eff_hlt.getVal();\n  e_tk = eff_tk.getVal();\n  e_sa = eff_sa.getVal();\n  e_iso = eff_iso.getVal();\n  Y_hlt = N_zMuMu1hlt / ((2. * (e_tk * e_tk) * (e_sa * e_sa) * (e_iso * e_iso) * e_hlt * (1. - e_hlt)));\n  Y_mutk = N_zMuTk / ((2. * (e_tk * e_tk) * e_sa * (1. - e_sa) * (e_iso * e_iso) * e_hlt));\n\n  cout << \"Yield prediction from mumu1hlt integral after fitting: \" << Y_hlt << endl;\n  //cout << \"Yield prediction from mutk integral after fitting: \" <<  Y_mutk << endl;\n  cout << \"N + B  prediction from mutk integral after fitting: \" << N_Tk << endl;\n  cout << \"zMuTkEffTerm \" << N_zMuTk << endl;\n  cout << \"N + B  prediction from mumuNotIso integral after fitting: \" << N_Iso << endl;\n  cout << \"zMuMuNoIsoEffTerm \" << N_zMuMuNoIso << endl;\n\n  cout << \"chi2_mutrk:\" << chi2_mutrk->getVal() << endl;\n  cout << \"chi2_mumuNotIso:\" << chi2_mumuNotIso->getVal() << endl;\n  cout << \"chi2_musta:\" << chi2_musta->getVal() << endl;\n  cout << \"chi2_mumu1hlt:\" << chi2_mu1hlt->getVal() << endl;\n  cout << \"chi2_mumu2hlt:\" << chi2_mu2hlt->getVal() << endl;\n\n  //plotting\n  RooPlot *massFrame_mutrk = mass->frame();\n  RooPlot *massFrame_mumuNotIso = mass->frame();\n  RooPlot *massFrame_musta = mass->frame();\n  RooPlot *massFrame_mumu1hlt = mass->frame();\n  RooPlot *massFrame_mumu2hlt = mass->frame();\n\n  TCanvas *canv1 = new TCanvas(\"canvas\");\n  TCanvas *canv2 = new TCanvas(\"new_canvas\");\n  canv1->Divide(2, 3);\n  canv1->cd(1);\n  canv1->SetLogy(kTRUE);\n  zmtMass->plotOn(massFrame_mutrk, LineColor(kBlue));\n  model_mutrk->plotOn(massFrame_mutrk, LineColor(kRed));\n  model_mutrk->plotOn(massFrame_mutrk, Components(*bkg_mutrk), LineColor(kGreen));\n  massFrame_mutrk->SetTitle(\"Z -> #mu track\");\n  // massFrame_mutrk->GetYaxis()->SetLogScale();\n  massFrame_mutrk->Draw();\n  gPad->SetLogy(1);\n\n  canv2->cd();\n  canv2->SetLogy(kTRUE);\n  massFrame_mutrk->Draw();\n  canv2->SaveAs(\"LogZMuTk.eps\");\n  canv2->SetLogy(kFALSE);\n  canv2->SaveAs(\"LinZMuTk.eps\");\n\n  canv1->cd(2);\n  zmmNotIsoMass->plotOn(massFrame_mumuNotIso, LineColor(kBlue));\n  model_mumuNotIso->plotOn(massFrame_mumuNotIso, LineColor(kRed));\n  model_mumuNotIso->plotOn(massFrame_mumuNotIso, Components(*bkg_mumuNotIso), LineColor(kGreen));\n  massFrame_mumuNotIso->SetTitle(\"Z -> #mu #mu not isolated\");\n  massFrame_mumuNotIso->Draw();\n  gPad->SetLogy(1);\n\n  canv2->cd();\n  canv2->Clear();\n  canv2->SetLogy(kTRUE);\n  massFrame_mumuNotIso->Draw();\n  canv2->SaveAs(\"LogZMuMuNotIso.eps\");\n  canv2->SetLogy(kFALSE);\n  canv2->SaveAs(\"LinZMuMuNotIso.eps\");\n\n  canv1->cd(3);\n  zmsMass->plotOn(massFrame_musta, LineColor(kBlue));\n  eZmsSig->plotOn(massFrame_musta, Components(*bkg_musa), LineColor(kGreen));\n  eZmsSig->plotOn(massFrame_musta, LineColor(kRed));\n  massFrame_musta->SetTitle(\"Z -> #mu sta\");\n  massFrame_musta->Draw();\n\n  canv2->cd();\n  canv2->Clear();\n  canv2->SetLogy(kTRUE);\n  massFrame_musta->Draw();\n  canv2->SaveAs(\"LogZMuSa.eps\");\n  canv2->SetLogy(kFALSE);\n  canv2->SaveAs(\"LinZMuSa.eps\");\n\n  canv1->cd(4);\n  zmm1hltMass->plotOn(massFrame_mumu1hlt, LineColor(kBlue));\n  eZmm1hltSig->plotOn(massFrame_mumu1hlt, LineColor(kRed));\n  massFrame_mumu1hlt->SetTitle(\"Z -> #mu #mu 1hlt\");\n  massFrame_mumu1hlt->Draw();\n  canv2->cd();\n  canv2->Clear();\n  canv2->SetLogy(kTRUE);\n  massFrame_mumu1hlt->Draw();\n  canv2->SaveAs(\"LogZMuMu1Hlt.eps\");\n  canv2->SetLogy(kFALSE);\n  canv2->SaveAs(\"LinZMuMu1Hlt.eps\");\n\n  canv1->cd(5);\n  zmm2hltMass->plotOn(massFrame_mumu2hlt, LineColor(kBlue));\n  eZmm2hltSig->plotOn(massFrame_mumu2hlt, LineColor(kRed));\n  massFrame_mumu2hlt->SetTitle(\"Z -> #mu #mu 2hlt\");\n  massFrame_mumu2hlt->Draw();\n\n  canv1->SaveAs(\"mass.eps\");\n\n  canv2->cd();\n  canv2->Clear();\n  canv2->SetLogy(kTRUE);\n  massFrame_mumu2hlt->Draw();\n  canv2->SaveAs(\"LogZMuMu2Hlt.eps\");\n  canv2->SetLogy(kFALSE);\n  canv2->SaveAs(\"LinZMuMu2Hlt.eps\");\n\n  /* how to read the fit result in root \n     TH1D h_Yield(\"h_Yield\", \"h_Yield\", 100, 10000, 30000)\n     for (int i =0: i < 100; i++){ \n     RooFitResult* r = gDirectory->Get(Form(\"toy_totChi2;%d)\",i)\n     //r->floatParsFinal().Print(\"s\");\n     // without s return a list,  can we get the number?\n     RooFitResult* r = gDirectory->Get(\"toy_totChi2;1\")\n     // chi2\n     r->minNll();\n     //distamce form chi2.....\n     //r->edm();\n     // yield\n     r->floatParsFinal()[0]->Print();\n     //RooAbsReal * l = r->floatParsFinal()->first()\n     RooAbsReal * y = r->floatParsFinal()->find(\"Yield\");\n     h_Yield->Fill(y->getVal());\n     }\n     \n  */\n\n  delete root_file;\n  //delete out_root_file;\n  return 0;\n}\n", "meta": {"hexsha": "0a454044a0692296ad5aa5dec04f8abf9151aa66", "size": 25427, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ElectroWeakAnalysis/ZMuMu/bin/zMuMuRooFit.cpp", "max_stars_repo_name": "SWuchterl/cmssw", "max_stars_repo_head_hexsha": "769b4a7ef81796579af7d626da6039dfa0347b8e", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2017-09-08T14:12:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-09T23:57:01.000Z", "max_issues_repo_path": "ElectroWeakAnalysis/ZMuMu/bin/zMuMuRooFit.cpp", "max_issues_repo_name": "SWuchterl/cmssw", "max_issues_repo_head_hexsha": "769b4a7ef81796579af7d626da6039dfa0347b8e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 545.0, "max_issues_repo_issues_event_min_datetime": "2017-09-19T17:10:19.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-07T16:55:27.000Z", "max_forks_repo_path": "ElectroWeakAnalysis/ZMuMu/bin/zMuMuRooFit.cpp", "max_forks_repo_name": "SWuchterl/cmssw", "max_forks_repo_head_hexsha": "769b4a7ef81796579af7d626da6039dfa0347b8e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 14.0, "max_forks_repo_forks_event_min_datetime": "2017-10-04T09:47:21.000Z", "max_forks_repo_forks_event_max_datetime": "2019-10-23T18:04:45.000Z", "avg_line_length": 44.9240282686, "max_line_length": 139, "alphanum_fraction": 0.6424666693, "num_tokens": 8805, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7090191337850932, "lm_q2_score": 0.4571367168274948, "lm_q1q2_score": 0.3241186789863918}}
{"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/FundamentalTypes.h>\n#include <vw/Math/Vector.h>\n#include <asp/IsisIO/PolyEquation.h>\n\n#include <iomanip>\n#include <vector>\n#include <string>\n#include <algorithm>\n\n#include <boost/algorithm/string/split.hpp>\n#include <boost/algorithm/string/classification.hpp>\n\nusing namespace vw;\nusing namespace asp;\n\n// Constructors\n//---------------------------------------------\nPolyEquation::PolyEquation ( int order ) {\n  if ( order < 0 )\n    vw_throw( ArgumentErr() << \"PolyEquation: Polynomial order must be greater than zero.\" );\n  if ( order > 254 )\n    vw_throw( ArgumentErr() << \"PolyEquation: Polynomial order must be less than 255\" );\n  m_x_coeff.set_size( order + 1 );\n  m_y_coeff.set_size( order + 1 );\n  m_z_coeff.set_size( order + 1 );\n  for ( int i = 0; i < order+1; i++ )\n    m_x_coeff[i] = m_y_coeff[i] = m_z_coeff[i] = 0;\n  m_cached_time = -1;\n  m_time_offset = 0;\n  m_max_length = uint8(order)+1;\n}\nPolyEquation::PolyEquation( int order_x,\n                            int order_y,\n                            int order_z ) {\n  if ( order_x < 0 || order_y < 0 || order_z < 0 )\n    vw_throw( ArgumentErr() << \"PolyEquation: Polynomial order must be greater than zero.\" );\n  if ( order_x > 254 || order_y > 254 || order_z > 254 )\n    vw_throw( ArgumentErr() << \"PolyEquation: Polynomial order must be less than 255\" );\n  m_x_coeff.set_size(order_x+1);\n  m_y_coeff.set_size(order_y+1);\n  m_z_coeff.set_size(order_z+1);\n  for ( unsigned i = 0; i < m_x_coeff.size(); i++ )\n    m_x_coeff[i] = 0;\n  for ( unsigned i = 0; i < m_y_coeff.size(); i++ )\n    m_y_coeff[i] = 0;\n  for ( unsigned i = 0; i < m_z_coeff.size(); i++ )\n    m_z_coeff[i] = 0;\n  m_cached_time = -1;\n  m_time_offset = 0;\n  m_max_length = uint8( std::max( order_x, std::max( order_y, order_z ) ) ) + 1;\n}\n\n// Update\n//-----------------------------------------------\nvoid PolyEquation::update( double t ) {\n  m_cached_time = t;\n  double delta_t = t-m_time_offset;\n  Vector<double> powers( m_max_length );\n  powers[0] = 1;\n  for ( uint8 i = 1; i < m_max_length; i++ )\n    powers[i] = powers[i-1]*delta_t;\n  m_cached_output[0] = sum( elem_prod(m_x_coeff,\n                                      subvector(powers,0,m_x_coeff.size())) );\n  m_cached_output[1] = sum( elem_prod(m_y_coeff,\n                                      subvector(powers,0,m_y_coeff.size())) );\n  m_cached_output[2] = sum( elem_prod(m_z_coeff,\n                                      subvector(powers,0,m_z_coeff.size())) );\n}\n\n// FileIO\n//-----------------------------------------------\nvoid PolyEquation::write( std::ofstream& f ) {\n  for ( int i = 0; i < 3; i++ ) {\n    Vector<double>* pointer;\n    switch(i) {\n    case 0:\n      pointer = &m_x_coeff;\n      break;\n    case 1:\n      pointer = &m_y_coeff;\n      break;\n    default:\n    case 2:\n      pointer = &m_z_coeff;\n      break;\n    }\n\n    f << std::setprecision( 15 );\n    for ( unsigned j = 0; j < (*pointer).size(); j++ )\n      f << (*pointer)[j] << \" \";\n    f << \"\\n\";\n  }\n}\n\nvoid PolyEquation::read( std::ifstream& f ) {\n  std::string buffer;\n  std::vector<std::string> tokens;\n  m_cached_time = -1;\n  for ( int i = 0; i < 3; i++ ) {\n    buffer = \"\";\n    std::getline( f, buffer );\n    boost::split( tokens, buffer, boost::is_any_of(\" =\\n\") );\n\n    // Cleaning out any tokens that are just \"\"\n    for(std::vector<std::string>::iterator iter = tokens.begin();\n        iter != tokens.end(); ++iter )\n      if ( (*iter) == \"\" ) {\n        iter = tokens.erase(iter);\n        iter--;\n      }\n\n    Vector<double>* pointer;\n    switch(i) {\n    case 0:\n      pointer = &m_x_coeff;\n      break;\n    case 1:\n      pointer = &m_y_coeff;\n      break;\n    default:\n    case 2:\n      pointer = &m_z_coeff;\n      break;\n    }\n\n    pointer->set_size( tokens.size() );\n    for ( unsigned j = 0; j < tokens.size(); j++ )\n      (*pointer)[j] = atof( tokens[j].c_str() );\n\n  }\n}\n\n// Constant Access\n//-----------------------------------------------\ndouble& PolyEquation::operator[]( size_t n ) {\n  m_cached_time = -1;\n  if (n >= m_x_coeff.size() + m_y_coeff.size() + m_z_coeff.size())\n    vw_throw(ArgumentErr() << \"PolyEquation: invalid index.\");\n  if (n < m_x_coeff.size()) {\n    return m_x_coeff[n];\n  } else if (n < m_x_coeff.size() + m_y_coeff.size()) {\n    return m_y_coeff[n - m_x_coeff.size()];\n  } else {\n    return m_z_coeff[n - m_x_coeff.size() - m_y_coeff.size()];\n  }\n}\n", "meta": {"hexsha": "b4cc4447fc1a8ef83877646ccbc9f459e22ef599", "size": 5163, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/asp/IsisIO/PolyEquation.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/IsisIO/PolyEquation.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/IsisIO/PolyEquation.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": 31.4817073171, "max_line_length": 93, "alphanum_fraction": 0.5886112725, "num_tokens": 1440, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.658417500561683, "lm_q2_score": 0.49218813572079556, "lm_q1q2_score": 0.32406528212740066}}
{"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#include <ndt/ndt_voxel.hpp>\n#include <ndt/utils.hpp>\n#include <Eigen/LU>\n#include <limits>\n#include \"common/types.hpp\"\n\nusing autoware::common::types::bool8_t;\n\nnamespace autoware\n{\nnamespace localization\n{\nnamespace ndt\n{\nconstexpr uint32_t DynamicNDTVoxel::NUM_POINT_THRESHOLD;\n\nDynamicNDTVoxel::DynamicNDTVoxel()\n{\n  // default constructors use uninitialized values.\n  m_centroid.setZero();\n  m_M2.setZero();\n  m_covariance.setZero();\n}\n\nvoid DynamicNDTVoxel::add_observation(const Point & pt)\n{\n  const auto last_count = m_num_points++;\n\n  const auto last_centroid = m_centroid;\n  const auto last_delta = pt - last_centroid;\n  m_centroid = last_centroid + (last_delta / m_num_points);\n\n  const auto current_delta = pt - m_centroid;\n  m_M2 += last_delta * current_delta.transpose();\n\n  if (usable()) {\n    // TODO(yunus.caliskan): Apply numerical stability enhancing steps described in:\n    // http://www.diva-portal.org/smash/get/diva2:276162/FULLTEXT02.pdf, pg 60\n    m_covariance = m_M2 / last_count;\n  }\n\n  // set invertibility to unknown since the covariance has changed\n  m_invertible = Invertibility::UNKNOWN;\n}\n\n\nbool8_t DynamicNDTVoxel::try_stabilize()\n{\n  bool8_t invertible = try_stabilize_covariance(m_covariance);\n  if (invertible) {\n    m_invertible = Invertibility::INVERTIBLE;\n  } else {\n    m_invertible = Invertibility::NOT_INVERTIBLE;\n  }\n\n  return invertible;\n}\n\nbool8_t DynamicNDTVoxel::usable() const noexcept\n{\n  return m_num_points >= NUM_POINT_THRESHOLD;\n}\n\nconst Eigen::Matrix3d & DynamicNDTVoxel::covariance() const\n{\n  if (!usable()) {\n    throw std::out_of_range(\n            \"DynamicNDTVoxel: Cannot get covariance from a \"\n            \"voxel without sufficient number of points\");\n  }\n  return m_covariance;\n}\n\nstd::experimental::optional<Eigen::Matrix3d> DynamicNDTVoxel::inverse_covariance() const\n{\n  if (!usable()) {\n    throw std::out_of_range(\n            \"DynamicNDTVoxel: Cannot get covariance from a \"\n            \"voxel without sufficient number of points\");\n  }\n\n  if (m_invertible == Invertibility::NOT_INVERTIBLE) {\n    // if stabilization has been performed and covariance is not invertible\n    return {};\n  }\n\n  Eigen::Matrix3d inv_covariance;\n  bool8_t invertible;\n  m_covariance.computeInverseWithCheck(inv_covariance, invertible);\n  if (invertible) {\n    return inv_covariance;\n  } else {\n    return {};\n  }\n}\n\nconst Eigen::Vector3d & DynamicNDTVoxel::centroid() const\n{\n  // Using the overloaded function as the parent function will use the hidden occupancy check\n  if (!usable()) {\n    throw std::out_of_range(\"DynamicNDTVoxel: Cannot get centroid from an unoccupied voxel\");\n  }\n  return m_centroid;\n}\n\nuint64_t DynamicNDTVoxel::count() const noexcept\n{\n  return m_num_points;\n}\n\n/////////////////////////////////////////////////\n\nStaticNDTVoxel::StaticNDTVoxel()\n{\n  m_centroid.setZero();\n  m_inv_covariance.setZero();\n}\n\nStaticNDTVoxel::StaticNDTVoxel(const Point & centroid, const Cov & inv_covariance)\n: m_centroid{centroid}, m_inv_covariance{inv_covariance}, m_occupied{true}\n{}\n\nEigen::Matrix3d StaticNDTVoxel::covariance() const\n{\n  Eigen::Matrix3d covariance;\n  if (m_occupied) {\n    bool8_t invertible{false};\n    m_inv_covariance.computeInverseWithCheck(covariance, invertible);\n    if (!invertible) {\n      throw std::out_of_range(\"StaticNDTVoxel: Inverse covariance is not invertible\");\n    }\n  } else {\n    throw std::out_of_range(\"StaticNDTVoxel: Cannot get covariance from an unoccupied voxel\");\n  }\n  return covariance;\n}\n\nconst Eigen::Vector3d & StaticNDTVoxel::centroid() const\n{\n  if (!m_occupied) {\n    throw std::out_of_range(\"StaticNDTVoxel: Cannot get centroid from an unoccupied voxel\");\n  }\n  return m_centroid;\n}\n\nconst Eigen::Matrix3d & StaticNDTVoxel::inverse_covariance() const\n{\n  if (!m_occupied) {\n    throw std::out_of_range(\n            \"StaticNDTVoxel: Cannot get inverse covariance \"\n            \"from an unoccupied voxel\");\n  }\n  return m_inv_covariance;\n}\n\nbool8_t StaticNDTVoxel::usable() const noexcept\n{\n  return m_occupied;\n}\n}  // namespace ndt\n}  // namespace localization\n}  // namespace autoware\n", "meta": {"hexsha": "a5109a976732f7c0dd85b615a7b9e955f31ad76d", "size": 4753, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/localization/ndt/src/ndt_voxel.cpp", "max_stars_repo_name": "ruvus/auto", "max_stars_repo_head_hexsha": "25ae62d6e575cae40212356eed43ec3e76e9a13e", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 19.0, "max_stars_repo_stars_event_min_datetime": "2021-05-28T06:14:21.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-10T10:03:08.000Z", "max_issues_repo_path": "src/localization/ndt/src/ndt_voxel.cpp", "max_issues_repo_name": "ruvus/auto", "max_issues_repo_head_hexsha": "25ae62d6e575cae40212356eed43ec3e76e9a13e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-05-23T16:45:11.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-03T16:59:40.000Z", "max_forks_repo_path": "src/localization/ndt/src/ndt_voxel.cpp", "max_forks_repo_name": "ruvus/auto", "max_forks_repo_head_hexsha": "25ae62d6e575cae40212356eed43ec3e76e9a13e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 14.0, "max_forks_repo_forks_event_min_datetime": "2021-05-29T14:59:17.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-10T10:03:09.000Z", "avg_line_length": 26.5530726257, "max_line_length": 94, "alphanum_fraction": 0.718493583, "num_tokens": 1220, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.658417500561683, "lm_q2_score": 0.49218813572079556, "lm_q1q2_score": 0.32406528212740066}}
{"text": "/*\n* Software License Agreement (BSD License)\n*\n*  Copyright (c) 2014-2015, Timm Linder, Social Robotics Lab, University of Freiburg\n*  Copyright (c) 2006-2012, Matthias Luber, Luciano Spinello and Kai O. Arras, Social Robotics Laboratory and\n*    Oscar Martinez, Autonomous Intelligent Systems, University of Freiburg\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*  * 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 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 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 <srl_laser_features/features/feature10.h>\n#include <Eigen/QR>\n#include <float.h>\n\n\nnamespace srl_laser_features\n{\n\nFeature10::Feature10(bool extended) : Feature(), m_extended(extended)\n{\n}\n\nvoid Feature10::evaluate(const Segment& segment, Eigen::VectorXd& result) const\n{\n    result = Eigen::VectorXd::Zero(getNDimensions());\n\n    const size_t numPoints = segment.points.size();\n    if (numPoints >= 2) {\n        double px[numPoints];\n        double py[numPoints];\n\n        // copy\n        for (size_t pIndex = 0; pIndex < numPoints; ++pIndex) {\n            px[pIndex] = segment.points[pIndex](0);\n            py[pIndex] = segment.points[pIndex](1);\n        }\n\n        double m, q, diff;\n        result(0) = 0.0;\n        if (m_extended) {\n            result(1) = 0.0;\n            result(2) = DBL_MAX;\n            result(3) = 0.0;\n        }\n        fitLine(numPoints, px, py, m, q);\n\n        // check for vertical line\n        if (fabs(m) > 10e+10) {\n            // residual sum\n            double diff;\n            for (size_t i = 0; i < numPoints; ++i) {\n                diff = segment.points[i](0) - segment.mean(0);\n                result(0) += diff * diff;\n                if (m_extended) {\n                    if (diff < result(2)) {\n                        result(2) = diff;\n                    }\n                    if (diff > result(3)) {\n                        result(3) = diff;\n                    }\n                }\n            }\n        }\n        else {\n            // residual sum\n            for (size_t i = 0; i < numPoints; ++i) {\n                diff = m * segment.points[i](0) + q - segment.points[i](1);\n                result(0) += diff * diff;\n                if (m_extended) {\n                    if (diff < result(2)) {\n                        result(2) = diff;\n                    }\n                    if (diff > result(3)) {\n                        result(3) = diff;\n                    }\n                }\n            }\n        }\n\n        if (m_extended) {\n            result(1) = result(0) / numPoints;\n            if (result(3) != 0.0) {\n                result(4) = result(2) / result(3);\n            }\n        }\n    }\n    else {\n        result.setConstant(getNDimensions(), -1.0);\n    }\n}\n\nvoid Feature10::fitLine(int n, double* xData, double* yData, double& m, double& q)\n{\n    Eigen::MatrixXd A(n, 2);\n    Eigen::VectorXd B(n);\n    Eigen::VectorXd C(2);\n\n    // fill A and B\n    for (int i = 0; i < n; i++) {\n        A(i, 0) = xData[i];\n        A(i, 1) = 1.0;\n        B(i) = yData[i];\n    }\n\n    // solve\n    Eigen::FullPivHouseholderQR<Eigen::MatrixXd> QR(A);\n    C = QR.solve(B);\n    m = C(0);\n    q = C(1);\n}\n\n} // end of namespace srl_laser_features\n", "meta": {"hexsha": "9fa4f88888bd857abfdea231b7e6cbc8740dec21", "size": 4541, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/spencer_people_tracking/detection/laser_detectors/srl_laser_features/src/srl_laser_features/features/feature10.cpp", "max_stars_repo_name": "CodeToPoem/HumanAwareRobotNavigation", "max_stars_repo_head_hexsha": "d44eb7e5acd73a5a7bf8bf1cd88c23d6a4a3c330", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 20.0, "max_stars_repo_stars_event_min_datetime": "2017-10-26T05:58:24.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-13T11:18:54.000Z", "max_issues_repo_path": "src/spencer_people_tracking/detection/laser_detectors/srl_laser_features/src/srl_laser_features/features/feature10.cpp", "max_issues_repo_name": "dmr-goncalves/HumanAwareRobotNavigation", "max_issues_repo_head_hexsha": "d44eb7e5acd73a5a7bf8bf1cd88c23d6a4a3c330", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/spencer_people_tracking/detection/laser_detectors/srl_laser_features/src/srl_laser_features/features/feature10.cpp", "max_forks_repo_name": "dmr-goncalves/HumanAwareRobotNavigation", "max_forks_repo_head_hexsha": "d44eb7e5acd73a5a7bf8bf1cd88c23d6a4a3c330", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2018-02-05T09:31:42.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-07T22:05:57.000Z", "avg_line_length": 33.637037037, "max_line_length": 109, "alphanum_fraction": 0.5776260736, "num_tokens": 1121, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6688802603710086, "lm_q2_score": 0.48438008427698437, "lm_q1q2_score": 0.3239922768897204}}
{"text": "// Petter Strandmark 2012.\n\n#include <cstring>\n#include <iostream>\n#include <limits>\n#include <memory>\n#include <random>\n#include <stdexcept>\n\n// GNU 4.8.1 define _X on Cygwin.\n// This breaks Eigen.\n// http://eigen.tuxfamily.org/bz/show_bug.cgi?id=658\n#ifdef _X\n#undef _X\n#endif\n#include <Eigen/Dense>\n#include <Eigen/Eigenvalues>\n#include <Eigen/Sparse>\n\nextern \"C\" {\n\t#include \"matrix.h\"\n\t#include \"matrix2.h\"\n\t#undef min\n\t#undef max\n\t#undef catch\n\t#undef SPARSE\n}\n\n#include <spii/spii.h>\n#include <spii/solver.h>\n\nnamespace spii {\n\ntemplate<typename EigenMat>\nvoid Eigen_to_Meschach(const EigenMat& eigen_matrix, MAT* A)\n{\n\tauto m = eigen_matrix.rows();\n\tauto n = eigen_matrix.cols();\n\n\tfor (int i = 0; i < m; ++i) {\n\t\tfor (int j = 0; j < n; ++j) {\n\t\t\tA->me[i][j] = eigen_matrix(i, j);\n\t\t}\n\t}\n}\n\nstruct FactorizationCacheInternal\n{\n\tPERM* pivot;\n\tPERM* block;\n\tMAT* Hmat;\n\tVEC* x;\n\tVEC* b;\n};\n\nFactorizationCache::FactorizationCache(int n)\n{\n\tauto cache = new FactorizationCacheInternal;\n\tcache->pivot = px_get(n);\n\tcache->block = px_get(n);\n\tcache->Hmat  = m_get(n, n);\n\tcache->x     = v_get(n);\n\tcache->b     = v_get(n);\n\tthis->data = cache;\n}\n\nFactorizationCache::~FactorizationCache()\n{\n\tv_free(this->data->b);\n\tv_free(this->data->x);\n\tm_free(this->data->Hmat);\n\tpx_free(this->data->pivot);\n\tpx_free(this->data->block);\n\tdelete this->data;\n}\n\nvoid Solver::BKP_dense(const Eigen::MatrixXd& H,\n                       const Eigen::VectorXd& g,\n                       const FactorizationCache& cache_input,\n                       Eigen::VectorXd* p,\n                       SolverResults* results) const\n{\n\tusing namespace Eigen;\n\tdouble start_time = wall_time();\n\n\tauto cache = cache_input.data;\n\tauto n = H.rows();\n\n\tEigen_to_Meschach(H, cache->Hmat);\n\n\t//m_foutput(stderr, cache->Hmat);\n\n\tBKPfactor(cache->Hmat, cache->pivot, cache->block);\n\n\t//m_foutput(stderr, cache->Hmat);\n\n\tMatrixXd B(n, n);\n\tMatrixXd Q(n, n);\n\tVectorXd tau(n);\n\tVectorXd lambda(n);\n\tB.setZero();\n\tQ.setZero();\n\n\tSelfAdjointEigenSolver<MatrixXd> eigensolver;\n\n\tdouble delta = 1e-12;\n\n\tint onebyone;\n\tfor (int i = 0; i < n; i = onebyone ? i+1 : i+2 ) {\n\t\tonebyone = ( cache->block->pe[i] == i );\n\t\tif ( onebyone ) {\n\t\t    B(i, i) = m_entry(cache->Hmat, i, i);\n\t\t\tlambda(i) = B(i, i);\n\t\t\tif (lambda(i) >= delta) {\n\t\t\t\ttau(i) = 0;\n\t\t\t}\n\t\t\telse {\n\t\t\t\ttau(i) = delta - (1.0 + delta) * lambda(i);\n\t\t\t}\n\t\t\tQ(i, i) = 1;\n\t\t}\n\t\telse {\n\t\t    auto a11 = m_entry(cache->Hmat, i, i);\n\t\t    auto a22 = m_entry(cache->Hmat, i+1, i+1);\n\t\t    auto a12 = m_entry(cache->Hmat, i+1, i);\n\t\t\tB(i,   i)   = a11;\n\t\t\tB(i+1, i)   = a12;\n\t\t\tB(i,   i+1) = a12;\n\t\t\tB(i+1, i+1) = a22;\n\t\t\teigensolver.compute(B.block(i, i, 2, 2));\n\n\t\t\tlambda(i)   = eigensolver.eigenvalues()(0);\n\t\t\tlambda(i+1) = eigensolver.eigenvalues()(1);\n\t\t\tfor (int k = i; k <= i + 1; ++k) {\n\t\t\t\tif (lambda(k) >= delta) {\n\t\t\t\t\ttau(k) = 0;\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\ttau(k) = delta - (1.0 + delta) * lambda(k);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tQ.block(i, i, 2, 2) = eigensolver.eigenvectors();\n\t\t}\n\t}\n\n\t//std::cerr << \"B = \\n\" << B << \"\\n\\n\";\n\t//std::cerr << \"F = \\n\" <<  Q * tau.asDiagonal() * Q.transpose() << \"\\n\\n\";\n\n\tB = B + Q * tau.asDiagonal() * Q.transpose();\n\n\t//std::cerr << \"B = \\n\" << B << \"\\n\\n\";\n\n\tfor (int i = 0; i < n; i = onebyone ? i+1 : i+2 ) {\n\t\tonebyone = ( cache->block->pe[i] == i );\n\t\tif ( onebyone ) {\n\t\t   m_entry(cache->Hmat, i, i) = B(i, i);\n\t\t}\n\t\telse {\n\t\t    m_entry(cache->Hmat, i,   i)   = B(i,   i);\n\t\t    m_entry(cache->Hmat, i+1, i+1) = B(i+1, i+1);\n\t\t    m_entry(cache->Hmat, i+1, i)   = B(i+1, i);\n\t\t\tm_entry(cache->Hmat, i,   i+1) = B(i,   i+1);\n\t\t}\n\t}\n\n\tresults->matrix_factorization_time += wall_time() - start_time;\n\tstart_time = wall_time();\n\n\t//m_foutput(stderr, cache->Hmat);\n\n\tfor (int i = 0; i < n; ++i) {\n\t\tcache->b->ve[i] = -g(i);\n\t}\n\tBKPsolve(cache->Hmat, cache->pivot, cache->block, cache->b, cache->x);\n\tfor (int i = 0; i < n; ++i) {\n\t\t(*p)(i) = cache->x->ve[i];\n\t}\n\n\tresults->linear_solver_time += wall_time() - start_time;\n\tstart_time = wall_time();\n\n\tresults->matrix_factorization_time += wall_time() - start_time;\n}\n\n}  // namespace spii\n", "meta": {"hexsha": "eccf3fd877bb625378052bc778887447e09470d9", "size": 4086, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "source/solver_newton_factorization.cpp", "max_stars_repo_name": "PetterS/spii", "max_stars_repo_head_hexsha": "98c5847223d7c3febea5a1aac6f4978dfef207ec", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 35.0, "max_stars_repo_stars_event_min_datetime": "2015-03-03T16:21:40.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-16T08:02:12.000Z", "max_issues_repo_path": "source/solver_newton_factorization.cpp", "max_issues_repo_name": "nashdingsheng/spii", "max_issues_repo_head_hexsha": "3130d0dc43af8ae79d1fdf315a8b5fc05fe00321", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2015-07-16T14:41:55.000Z", "max_issues_repo_issues_event_max_datetime": "2018-04-09T19:27:22.000Z", "max_forks_repo_path": "source/solver_newton_factorization.cpp", "max_forks_repo_name": "nashdingsheng/spii", "max_forks_repo_head_hexsha": "3130d0dc43af8ae79d1fdf315a8b5fc05fe00321", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 11.0, "max_forks_repo_forks_event_min_datetime": "2015-09-21T23:09:37.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-24T20:20:30.000Z", "avg_line_length": 21.8502673797, "max_line_length": 76, "alphanum_fraction": 0.5756240822, "num_tokens": 1414, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6688802471698041, "lm_q2_score": 0.4843800842769844, "lm_q1q2_score": 0.32399227049531987}}
{"text": "\n#include <algorithm>\n#include <numeric>\n#include <limits>\n#include <iostream>\n#include <cmath>\n#include <cassert>\n\n#include <boost/lambda/lambda.hpp>\n\n#include \"TreeCoverDecomposition.h\"\n#include \"LinearProgrammingMAPInference.h\"\n\nusing namespace boost::lambda;\n\nnamespace Grante {\n\nLinearProgrammingMAPInference::LinearProgrammingMAPInference(\n\tconst FactorGraph* fg, bool verbose)\n\t: InferenceMethod(fg), verbose(verbose), max_iter(100), conv_tol(1.0e-6),\n\t\tprimal_best_energy(0.0), T(0) {\n\t// Check each variable has at least one unary factors attached\n\tsize_t var_count = fg->Cardinalities().size();\n\tstd::vector<int> has_unary(var_count, -1);\n\thas_unary.resize(var_count, -1);\n\tconst std::vector<Factor*>& factors = fg->Factors();\n\tfor (size_t fi = 0; fi < factors.size(); ++fi) {\n\t\tconst Factor* fac = factors[fi];\n\t\tif (fac->Variables().size() > 1)\n\t\t\tcontinue;\n\n\t\tassert(fac->Variables().size() == 1);\n\t\tunsigned int var_index = fac->Variables()[0];\n\t\tif (has_unary[var_index] >= 0)\n\t\t\tcontinue;\n\t\thas_unary[var_index] = static_cast<int>(fi);\n\t}\n\tif (std::find(has_unary.begin(), has_unary.end(), -1) !=\n\t\thas_unary.end()) {\n\t\tstd::cout << \"Factor graph has variables without unary factors.  \"\n\t\t\t<< \"This is required for MAP-MRF LP inference.\" << std::endl;\n\t\tassert(false);\n\t}\n\n\t// Build a fast factor-to-variable lookup map for the unary factors\n\tstd::unordered_map<unsigned int, unsigned int> unary_fi_to_var;\n\tfor (unsigned int ui = 0; ui < has_unary.size(); ++ui)\n\t\tunary_fi_to_var[static_cast<unsigned int>(has_unary[ui])] = ui;\n\n\tprimal_best.resize(var_count, 0);\n\n\t// Perform tree decomposition\n\tTreeCoverDecomposition tcov_decomp(fg);\n\ttcov_decomp.ComputeDecompositionGreedy(tree_factor_indices,\n\t\tfactor_cover_count);\n\tT = tree_factor_indices.size();\n\n\t// Instantiate spanning trees\n\ttrees.resize(T, 0);\n\ttree_var_to_factor_map.resize(T);\n\ttree_inf.resize(T, 0);\n\tfor (size_t t = 0; t < T; ++t) {\n\t\t// Scale all factors by the inverse number of times they are covered\n\t\tstd::vector<double> f_scale(tree_factor_indices[t].size());\n\t\tfor (size_t tfi = 0; tfi < f_scale.size(); ++tfi) {\n\t\t\t// Factor tfi in tree t\n\t\t\tf_scale[tfi] = 1.0 /static_cast<double>(\n\t\t\t\tfactor_cover_count[tree_factor_indices[t][tfi]]);\n\t\t}\n\n\t\t// Create a subgraph with the given set of factors\n\t\ttrees[t] = new SubFactorGraph(fg, tree_factor_indices[t], f_scale);\n\t\tassert(trees[t]->FG()->Cardinalities().size() == var_count);\n\n\t\t// Build a map for \"global variable index -> per-tree factor index\"\n\t\t// lookups\n\t\tfor (size_t tfi = 0; tfi < tree_factor_indices[t].size(); ++tfi) {\n\t\t\t// Is it a unary factor?\n\t\t\tunsigned int fi = tree_factor_indices[t][tfi];\n\t\t\tif (unary_fi_to_var.count(fi) == 0)\n\t\t\t\tcontinue;\n\n\t\t\t// It is, find the variable index\n\t\t\tunsigned int var_index = unary_fi_to_var[fi];\n\t\t\ttree_var_to_factor_map[t][var_index] =\n\t\t\t\tstatic_cast<unsigned int>(tfi);\n\t\t}\n\n\t\t// Tree inference object for this subgraph\n\t\ttree_inf[t] = new TreeInference(trees[t]->FG());\n\t}\n}\n\nLinearProgrammingMAPInference::~LinearProgrammingMAPInference() {\n\tfor (size_t t = 0; t < T; ++t) {\n\t\tdelete (tree_inf[t]);\n\t\tdelete (trees[t]);\n\t}\n}\n\nInferenceMethod* LinearProgrammingMAPInference::Produce(\n\tconst FactorGraph* new_fg) const {\n\treturn (new LinearProgrammingMAPInference(new_fg));\n}\n\nvoid LinearProgrammingMAPInference::SetParameters(\n\tunsigned int max_iter, double conv_tol) {\n\tassert(conv_tol >= 0.0);\n\tthis->max_iter = max_iter;\n\tthis->conv_tol = conv_tol;\n}\n\nvoid LinearProgrammingMAPInference::PerformInference() {\n\t// Distribute energies uniformly over decomposed trees\n\tfor (size_t t = 0; t < T; ++t)\n\t\ttrees[t]->ForwardMap();\n\n\t// Initialize primal labeling\n\tconst std::vector<unsigned int>& var_card = fg->Cardinalities();\n\tsize_t var_count = fg->Cardinalities().size();\n\tprimal_best.resize(var_count);\n\tstd::fill(primal_best.begin(), primal_best.end(), 0);\n\tprimal_best_energy = std::numeric_limits<double>::infinity();\n\n\t// Initialize relaxed solution\n#if 0\n\tconst std::vector<Factor*>& factors = fg->Factors();\n\trelaxed_sol.resize(factors.size());\n\tfor (unsigned int fi = 0; fi < factors.size(); ++fi) {\n\t\trelaxed_sol[fi].resize(factors[fi]->Type()->ProdCardinalities());\n\t\tstd::fill(relaxed_sol[fi].begin(), relaxed_sol[fi].end(), 0.0);\n\t}\n\trelaxed_sol_energy = -std::numeric_limits<double>::infinity();\n#endif\n\n\t// \\lambda_{t,vi,state} = 0\n\tstd::vector<std::vector<double> > sol_avg(var_count);\n\tfor (size_t vi = 0; vi < var_count; ++vi) {\n\t\tunsigned int vi_card = var_card[vi];\n\t\tsol_avg[vi].resize(vi_card, 0.0);\n\t}\n\t// Individual tree solutions\n\tstd::vector<std::vector<unsigned int> > cur_sol_t(T);\n\tfor (size_t t = 0; t < T; ++t)\n\t\tcur_sol_t[t].resize(var_count);\n\n\t// Stepsize control\n\t// The control mechanism is from Section 8.2, \"Path-Based Incremental\n\t// Target Level Algorithm\" in Bertsekas, Nedic, Ozdaglar, \"Convex Analysis\n\t// and Optimization\".\n\tdouble delta = -1.0;\n\tdouble B = 2.0;\t// Travel-length bound\n\tdouble sigma = 0.0;\t// Actual travel-length since last control\n\tdouble dual_obj_target = -std::numeric_limits<double>::infinity();\n\tdouble dual_obj_best = -std::numeric_limits<double>::infinity();\n\n\t// Iterate\n\tdouble sol_step = 1.0 / static_cast<double>(T);\n\tfor (int iter = 1; max_iter == 0 || iter <= static_cast<int>(max_iter);\n\t\t++iter) {\n\t\t// Clear averaged solution\n\t\tfor (unsigned int vi = 0; vi < var_count; ++vi)\n\t\t\tstd::fill(sol_avg[vi].begin(), sol_avg[vi].end(), 0.0);\n\n\t\t// Perform inference for all submodels\n\t\tdouble dual_obj = 0.0;\n\t\tbool new_primal_best = false;\n\t\tfor (unsigned int t = 0; t < T; ++t) {\n\t\t\tdouble t_obj = tree_inf[t]->MinimizeEnergy(cur_sol_t[t]);\n\n\t\t\t// Dual objective is simply the sum of all tree objectives\n\t\t\tdual_obj += t_obj;\n\n\t\t\t// Produce averaged solution (primal infeasible)\n\t\t\tfor (unsigned int vi = 0; vi < var_count; ++vi)\n\t\t\t\tsol_avg[vi][cur_sol_t[t][vi]] += sol_step;\n\n\t\t\t// Identify best feasible integral labeling\n\t\t\tdouble t_primal_energy = fg->EvaluateEnergy(cur_sol_t[t]);\n\t\t\tif (t_primal_energy < primal_best_energy) {\n\t\t\t\tstd::copy(cur_sol_t[t].begin(), cur_sol_t[t].end(),\n\t\t\t\t\tprimal_best.begin());\n\t\t\t\tprimal_best_energy = t_primal_energy;\n\t\t\t\tnew_primal_best = true;\n\t\t\t}\n\t\t}\n\n\t\tif (dual_obj > dual_obj_best)\n\t\t\tdual_obj_best = dual_obj;\n\n\t\t// Initial delta: half the primal-dual gap\n\t\tif (delta < 0.0)\n\t\t\tdelta = 0.5 * (primal_best_energy - dual_obj);\n\n\t\tbool sufficient_descent = false;\n\t\tbool oscillation = false;\n\t\tif (dual_obj >= (dual_obj_target + 0.5 * delta)) {\n\t\t\t// Sufficient descent because target level is reached\n\t\t\tsufficient_descent = true;\n\t\t\tsigma = 0.0;\n\t\t\tdual_obj_target = dual_obj_best;\n\t\t} else if (sigma > B) {\n\t\t\t// Oscillation detected\n\t\t\toscillation = true;\n\t\t\tsigma = 0.0;\n\t\t\tdelta *= 0.5;\n\t\t\tdual_obj_target = dual_obj_best;\n\t\t}\n\n#if 0\n\t\t// Linear program primal solution recovery by subgradient averaged\n\t\t// solution (Anstreicher and Wolsey, MathProg 2009)\n#if 1\n\t\t// Uniform average\n\t\tdouble new_sol_scale = 1.0 / static_cast<double>(T * iter);\n\t\tdouble old_sol_scale = static_cast<double>(iter - 1) /\n\t\t\tstatic_cast<double>(iter);\n#endif\n#if 0\n\t\t// Geometric average\n\t\tdouble vol_alpha = 0.005;\n\t\tdouble new_sol_scale = vol_alpha / static_cast<double>(T);\n\t\tdouble old_sol_scale = (1.0 - vol_alpha);\n\t\tif (iter == 1) {\n\t\t\told_sol_scale = 0.0;\n\t\t\tnew_sol_scale = 1.0;\n\t\t}\n#endif\n\t\trelaxed_sol_energy = 0.0;\n\t\tfor (unsigned int fi = 0; fi < factors.size(); ++fi) {\n\t\t\tstd::transform(relaxed_sol[fi].begin(), relaxed_sol[fi].end(),\n\t\t\t\trelaxed_sol[fi].begin(), _1 * old_sol_scale);\n\n\t\t\tfor (unsigned int t = 0; t < T; ++t) {\n\t\t\t\tunsigned int ei =\n\t\t\t\t\tfactors[fi]->ComputeAbsoluteIndex(cur_sol_t[t]);\n\t\t\t\tassert(ei < relaxed_sol[fi].size());\n\t\t\t\trelaxed_sol[fi][ei] += new_sol_scale * 1.0;\n\t\t\t}\n\t\t\trelaxed_sol_energy += std::inner_product(\n\t\t\t\trelaxed_sol[fi].begin(), relaxed_sol[fi].end(),\n\t\t\t\tfactors[fi]->Energies().begin(), 0.0);\n\t\t}\n#endif\n\n\t\t// Output statistics\n\t\tif (verbose) {\n\t\t\tstd::cout << \"iter \" << iter << \", primal \" << primal_best_energy\n\t\t\t\t<< \", dual \" << dual_obj << \", best dual \" << dual_obj_best\n\t\t\t\t<< \", gap \" << (primal_best_energy - dual_obj) << std::endl;\n\t\t}\n\n\t\t// Compute step size\n\t\tdouble subgradient_norm = 0.0;\n\t\tfor (size_t t = 0; t < T; ++t) {\n\t\t\tfor (unsigned int vi = 0; vi < var_count; ++vi) {\n\t\t\t\t// Obtain a unary factor of the variable\n\t\t\t\tunsigned int vi_card = var_card[vi];\n\t\t\t\tfor (unsigned int vs = 0; vs < vi_card; ++vs) {\n\t\t\t\t\tsubgradient_norm += std::pow(\n\t\t\t\t\t\t(cur_sol_t[t][vi] == vs ? 1.0 : 0.0)\n\t\t\t\t\t\t- sol_avg[vi][vs], 2.0);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t//subgradient_norm = std::sqrt(subgradient_norm);\n\t\tdouble gamma = 1.95;\n\t\tdouble alpha = gamma * ((dual_obj_target + delta) - dual_obj) /\n\t\t\tsubgradient_norm;\n\t\tdouble dgap = primal_best_energy - dual_obj;\n\t\tdouble convergence_measure = dgap / (fabs(dual_obj) + 1.0e-5);\n\t\tsigma += std::min(1.0, alpha * subgradient_norm);\n\t\tif (subgradient_norm <= 1.0e-5 || convergence_measure <= conv_tol) {\n\t\t\tif (verbose) {\n\t\t\t\tstd::cout << \"Converged, subg norm \" << subgradient_norm\n\t\t\t\t\t<< \", conv \" << convergence_measure << std::endl;\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\n\t\t// 4. Compute step size\n#if 0\n\t\talpha = 1.0 / (10.0 + static_cast<double>(iter));\n#endif\n\n\t\t// Update Lagrange multipliers implicitly by directly updating the\n\t\t// energies of the trees in the decomposition\n\t\tfor (unsigned int t = 0; t < T; ++t) {\n\t\t\tconst std::vector<Factor*>& factors = trees[t]->FG()->Factors();\n\t\t\tfor (unsigned int vi = 0; vi < var_count; ++vi) {\n\t\t\t\t// Obtain a unary factor of the variable\n\t\t\t\tunsigned int t_fi = tree_var_to_factor_map[t][vi];\n\t\t\t\tstd::vector<double>& t_fi_energies = factors[t_fi]->Energies();\n\n\t\t\t\t// Modify the energies\n\t\t\t\tunsigned int vi_card = var_card[vi];\n\t\t\t\tfor (unsigned int vs = 0; vs < vi_card; ++vs) {\n\t\t\t\t\t// Subgradient update\n\t\t\t\t\tt_fi_energies[vs] += alpha * (\n\t\t\t\t\t\t(cur_sol_t[t][vi] == vs ? 1.0 : 0.0) -\n\t\t\t\t\t\tsol_avg[vi][vs]);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\nvoid LinearProgrammingMAPInference::ClearInferenceResult() {\n#if 0\n\trelaxed_sol.clear();\n#endif\n}\n\n// Returns one part of the (approximate) relaxed solution\nconst std::vector<double>& LinearProgrammingMAPInference::Marginal(\n\tunsigned int factor_id) const {\n\tassert(factor_id < relaxed_sol.size());\n\treturn (relaxed_sol[factor_id]);\n}\n\n// Returns the relaxed solution\nconst std::vector<std::vector<double> >&\nLinearProgrammingMAPInference::Marginals() const {\n\tassert(0);\n\treturn (relaxed_sol);\n}\n\n// XXX: not implemented\ndouble LinearProgrammingMAPInference::LogPartitionFunction() const {\n\tassert(false);\n\treturn (std::numeric_limits<double>::signaling_NaN());\n}\n\n// XXX: not implemented\nvoid LinearProgrammingMAPInference::Sample(\n\tstd::vector<std::vector<unsigned int> >& states,\n\tunsigned int sample_count) {\n\tassert(false);\n}\n\n// Obtain an approximate minimum energy state for the current factor graph\n// energies.\ndouble LinearProgrammingMAPInference::MinimizeEnergy(\n\tstd::vector<unsigned int>& state) {\n\tPerformInference();\n\tstate = primal_best;\n\n\treturn (primal_best_energy);\n}\n\n}\n\n", "meta": {"hexsha": "2bedbeaba68c8ae956a61d4c9d61846d04b06f0b", "size": 10974, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "grante/LinearProgrammingMAPInference.cpp", "max_stars_repo_name": "pantonante/grante-bazel", "max_stars_repo_head_hexsha": "e3f22ec111463a7ae0686494422ab09f86b4d39a", "max_stars_repo_licenses": ["DOC"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "grante/LinearProgrammingMAPInference.cpp", "max_issues_repo_name": "pantonante/grante-bazel", "max_issues_repo_head_hexsha": "e3f22ec111463a7ae0686494422ab09f86b4d39a", "max_issues_repo_licenses": ["DOC"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "grante/LinearProgrammingMAPInference.cpp", "max_forks_repo_name": "pantonante/grante-bazel", "max_forks_repo_head_hexsha": "e3f22ec111463a7ae0686494422ab09f86b4d39a", "max_forks_repo_licenses": ["DOC"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.0878186969, "max_line_length": 75, "alphanum_fraction": 0.6816110807, "num_tokens": 3218, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6477982315512488, "lm_q2_score": 0.5, "lm_q1q2_score": 0.3238991157756244}}
{"text": "#include <Eigen/Core>\n#include <cstdint>\n#include <string>\n\n#include \"pyinterp/axis.hpp\"\n#include \"pyinterp/detail/math/frame.hpp\"\n#include \"pyinterp/grid.hpp\"\n\nnamespace pyinterp {\n\n// Error thrown if it' s not possible to frame the value on the specified axis.\ntemplate <typename T>\nauto index_error(const std::string& axis, T value, size_t n) -> void {\n  throw std::invalid_argument(\n      \"Unable to frame the value \" + std::to_string(value) + \" with \" +\n      std::to_string(n) + \" items of the \" + axis + \" axis\");\n}\n\n/// Loads the interpolation frame into memory\ntemplate <typename DataType>\nauto load_frame(const Grid2D<DataType>& grid, const double x, const double y,\n                const axis::Boundary boundary, const bool bounds_error,\n                detail::math::Frame2D& frame) -> bool {\n  const auto& x_axis = *grid.x();\n  const auto& y_axis = *grid.y();\n  const auto y_indexes =\n      y_axis.find_indexes(y, static_cast<uint32_t>(frame.ny()), boundary);\n  const auto x_indexes =\n      x_axis.find_indexes(x, static_cast<uint32_t>(frame.nx()), boundary);\n\n  if (x_indexes.empty() || y_indexes.empty()) {\n    if (bounds_error) {\n      if (x_indexes.empty()) {\n        index_error(\"x\", x, frame.nx());\n      }\n      index_error(\"y\", y, frame.ny());\n    }\n    return false;\n  }\n\n  auto x0 = x_axis(x_indexes[0]);\n\n  for (Eigen::Index jx = 0; jx < frame.y()->size(); ++jx) {\n    frame.y(jx) = y_axis(y_indexes[jx]);\n  }\n\n  for (Eigen::Index ix = 0; ix < frame.x()->size(); ++ix) {\n    const auto index = x_indexes[ix];\n\n    frame.x(ix) = x_axis.is_angle()\n                      ? detail::math::normalize_angle(x_axis(index), x0, 360.0)\n                      : x_axis(index);\n\n    for (Eigen::Index jx = 0; jx < frame.y()->size(); ++jx) {\n      frame.q(ix, jx) = static_cast<double>(grid.value(index, y_indexes[jx]));\n    }\n  }\n  return frame.is_valid();\n}\n\n/// Loads the interpolation frame into memory\ntemplate <typename DataType, typename AxisType>\nauto load_frame(const Grid3D<DataType, AxisType>& grid, const double x,\n                const double y, const AxisType z, const axis::Boundary boundary,\n                const bool bounds_error, detail::math::Frame3D<AxisType>& frame)\n    -> bool {\n  const auto& x_axis = *grid.x();\n  const auto& y_axis = *grid.y();\n  const auto& z_axis = *grid.z();\n  const auto z_indexes =\n      z_axis.find_indexes(z, static_cast<uint32_t>(frame.nz()), boundary);\n  const auto y_indexes =\n      y_axis.find_indexes(y, static_cast<uint32_t>(frame.ny()), boundary);\n  const auto x_indexes =\n      x_axis.find_indexes(x, static_cast<uint32_t>(frame.nx()), boundary);\n\n  if (x_indexes.empty() || y_indexes.empty() || z_indexes.empty()) {\n    if (bounds_error) {\n      if (x_indexes.empty()) {\n        index_error(\"x\", x, frame.nx());\n      } else if (y_indexes.empty()) {\n        index_error(\"y\", y, frame.ny());\n      }\n      index_error(\"z\", z, frame.nz());\n    }\n    return false;\n  }\n\n  auto x0 = x_axis(x_indexes[0]);\n\n  for (Eigen::Index jx = 0; jx < frame.y()->size(); ++jx) {\n    frame.y(jx) = y_axis(y_indexes[jx]);\n  }\n\n  for (Eigen::Index kx = 0; kx < frame.z().size(); ++kx) {\n    frame.z(kx) = z_axis(z_indexes[kx]);\n  }\n\n  for (Eigen::Index ix = 0; ix < frame.x()->size(); ++ix) {\n    const auto x_index = x_indexes[ix];\n\n    frame.x(ix) = x_axis.is_angle() ? detail::math::normalize_angle(\n                                          x_axis(x_index), x0, 360.0)\n                                    : x_axis(x_index);\n\n    for (Eigen::Index jx = 0; jx < frame.y()->size(); ++jx) {\n      const auto y_index = y_indexes[jx];\n\n      for (Eigen::Index kx = 0; kx < frame.z().size(); ++kx) {\n        frame.q(ix, jx, kx) =\n            static_cast<double>(grid.value(x_index, y_index, z_indexes[kx]));\n      }\n    }\n  }\n  return frame.is_valid();\n}\n\n/// Loads the interpolation frame into memory\ntemplate <typename DataType, typename AxisType>\nauto load_frame(const Grid4D<DataType, AxisType>& grid, const double x,\n                const double y, const AxisType z, const double u,\n                const axis::Boundary boundary, const bool bounds_error,\n                detail::math::Frame4D<AxisType>& frame) -> bool {\n  const auto& x_axis = *grid.x();\n  const auto& y_axis = *grid.y();\n  const auto& z_axis = *grid.z();\n  const auto& u_axis = *grid.u();\n  const auto u_indexes =\n      u_axis.find_indexes(u, static_cast<uint32_t>(frame.nu()), boundary);\n  const auto z_indexes =\n      z_axis.find_indexes(z, static_cast<uint32_t>(frame.nz()), boundary);\n  const auto y_indexes =\n      y_axis.find_indexes(y, static_cast<uint32_t>(frame.ny()), boundary);\n  const auto x_indexes =\n      x_axis.find_indexes(x, static_cast<uint32_t>(frame.nx()), boundary);\n\n  if (x_indexes.empty() || y_indexes.empty() || z_indexes.empty() ||\n      u_indexes.empty()) {\n    if (bounds_error) {\n      if (x_indexes.empty()) {\n        index_error(\"x\", x, frame.nx());\n      } else if (y_indexes.empty()) {\n        index_error(\"y\", y, frame.ny());\n      } else if (z_indexes.empty()) {\n        index_error(\"z\", z, frame.nz());\n      }\n      index_error(\"u\", u, frame.nu());\n    }\n    return false;\n  }\n\n  auto x0 = x_axis(x_indexes[0]);\n\n  for (Eigen::Index jx = 0; jx < frame.y()->size(); ++jx) {\n    frame.y(jx) = y_axis(y_indexes[jx]);\n  }\n\n  for (Eigen::Index kx = 0; kx < frame.z().size(); ++kx) {\n    frame.z(kx) = z_axis(z_indexes[kx]);\n  }\n\n  for (Eigen::Index lx = 0; lx < frame.u().size(); ++lx) {\n    frame.u(lx) = u_axis(u_indexes[lx]);\n  }\n\n  for (Eigen::Index ix = 0; ix < frame.x()->size(); ++ix) {\n    const auto x_index = x_indexes[ix];\n\n    frame.x(ix) = x_axis.is_angle() ? detail::math::normalize_angle(\n                                          x_axis(x_index), x0, 360.0)\n                                    : x_axis(x_index);\n\n    for (Eigen::Index jx = 0; jx < frame.y()->size(); ++jx) {\n      const auto y_index = y_indexes[jx];\n\n      for (Eigen::Index kx = 0; kx < frame.z().size(); ++kx) {\n        const auto z_index = z_indexes[kx];\n\n        for (Eigen::Index lx = 0; lx < frame.u().size(); ++lx) {\n          frame.q(ix, jx, kx, lx) = static_cast<double>(\n              grid.value(x_index, y_index, z_index, u_indexes[lx]));\n        }\n      }\n    }\n  }\n  return frame.is_valid();\n}\n\n}  // namespace pyinterp", "meta": {"hexsha": "6468a5ff83d2096c45153a46a0ab5b80cc84a8b5", "size": 6268, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/pyinterp/core/include/pyinterp/frame.hpp", "max_stars_repo_name": "CNES/pangeo-pyinterp", "max_stars_repo_head_hexsha": "5f75f62a6c681db89c5aa8c74e43fc04a77418c3", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 67.0, "max_stars_repo_stars_event_min_datetime": "2019-07-09T09:10:22.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-01T09:46:35.000Z", "max_issues_repo_path": "src/pyinterp/core/include/pyinterp/frame.hpp", "max_issues_repo_name": "CNES/pangeo-pyinterp", "max_issues_repo_head_hexsha": "5f75f62a6c681db89c5aa8c74e43fc04a77418c3", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 8.0, "max_issues_repo_issues_event_min_datetime": "2019-07-15T13:54:31.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-28T05:06:34.000Z", "max_forks_repo_path": "src/pyinterp/core/include/pyinterp/frame.hpp", "max_forks_repo_name": "CNES/pangeo-pyinterp", "max_forks_repo_head_hexsha": "5f75f62a6c681db89c5aa8c74e43fc04a77418c3", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2019-07-15T17:28:16.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-19T19:43:47.000Z", "avg_line_length": 33.164021164, "max_line_length": 80, "alphanum_fraction": 0.5867900447, "num_tokens": 1729, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6477982179521103, "lm_q2_score": 0.5, "lm_q1q2_score": 0.3238991089760552}}
{"text": "/*\n * @Description: Kalman Filter interface.\n * @Author: Ge Yao\n * @Date: 2020-11-12 15:14:07\n */\n\n#ifndef LIDAR_LOCALIZATION_MODELS_KALMAN_FILTER_KALMAN_FILTER_HPP_\n#define LIDAR_LOCALIZATION_MODELS_KALMAN_FILTER_KALMAN_FILTER_HPP_\n\n#include <yaml-cpp/yaml.h>\n\n#include <deque>\n\n#include <Eigen/Core>\n#include <Eigen/Dense>\n\n#include \"lidar_localization/sensor_data/imu_data.hpp\"\n\nnamespace lidar_localization {\n\nclass KalmanFilter {\npublic:\n  /**\n   * @class MeasurementType\n   * @brief enum for observation type\n   */\n  enum MeasurementType {\n    POSE = 0,\n    POSE_VEL,\n    POSI,\n    POSI_VEL,\n    POSI_MAG,\n    POSI_VEL_MAG,\n    NUM_TYPES\n  };\n\n  /**\n   * @class Measurement\n   * @brief Kalman filter measurement data\n   */\n  struct Measurement {\n    // timestamp:\n    double time;\n    // a. pose observation, lidar/visual frontend:\n    Eigen::Matrix4d T_nb;\n    // b. body frame velocity observation, odometer:\n    Eigen::Vector3d v_b;\n    // c. body frame angular velocity, needed by motion constraint:\n    Eigen::Vector3d w_b;\n    // d. magnetometer:\n    Eigen::Vector3d B_b;\n  };\n\n  /**\n   * @class Cov\n   * @brief Kalman filter process covariance data\n   */\n  struct Cov {\n    struct {\n      double x;\n      double y;\n      double z;\n    } pos;\n    struct {\n      double x;\n      double y;\n      double z;\n    } vel;\n    // here quaternion is used for orientation representation:\n    struct {\n      double w;\n      double x;\n      double y;\n      double z;\n    } ori;\n    struct {\n      double x;\n      double y;\n      double z;\n    } gyro_bias;\n    struct {\n      double x;\n      double y;\n      double z;\n    } accel_bias;\n  };\n\n  /**\n   * @brief  init filter\n   * @param  imu_data, input IMU measurements\n   * @return true if success false otherwise\n   */\n  virtual void Init(const Eigen::Vector3d &vel, const IMUData &imu_data) = 0;\n\n  /**\n   * @brief  update state & covariance estimation, Kalman prediction\n   * @param  imu_data, input IMU measurements\n   * @return true if success false otherwise\n   */\n  virtual bool Update(const IMUData &imu_data) = 0;\n\n  /**\n   * @brief  correct state & covariance estimation, Kalman correction\n   * @param  measurement_type, input measurement type\n   * @param  measurement, input measurement\n   * @return void\n   */\n  virtual bool Correct(const IMUData &imu_data,\n                       const MeasurementType &measurement_type,\n                       const Measurement &measurement) = 0;\n\n  /**\n   * @brief  get filter time\n   * @return filter time as double\n   */\n  double GetTime(void) const { return time_; }\n\n  /**\n   * @brief  get odometry estimation\n   * @param  pose, output pose\n   * @param  vel, output vel\n   * @return void\n   */\n  virtual void GetOdometry(Eigen::Matrix4f &pose, Eigen::Vector3f &vel) = 0;\n\n  /**\n   * @brief  get covariance estimation\n   * @param  cov, output covariance\n   * @return void\n   */\n  virtual void GetCovariance(Cov &cov) = 0;\n\n  /**\n   * @brief  update observability analysis\n   * @param  time, measurement time\n   * @param  measurement_type, measurement type\n   * @return void\n   */\n  virtual void\n  UpdateObservabilityAnalysis(const double &time,\n                              const MeasurementType &measurement_type) = 0;\n\n  /**\n   * @brief  save observability analysis to persistent storage\n   * @param  measurement_type, measurement type\n   * @return void\n   */\n  virtual bool\n  SaveObservabilityAnalysis(const MeasurementType &measurement_type) = 0;\n\nprotected:\n  KalmanFilter() {}\n\n  static void AnalyzeQ(const int DIM_STATE, const double &time,\n                       const Eigen::MatrixXd &Q, const Eigen::VectorXd &Y,\n                       std::vector<std::vector<double>> &data);\n\n  static void WriteAsCSV(const int DIM_STATE,\n                         const std::vector<std::vector<double>> &data,\n                         const std::string filename);\n\n  // time:\n  double time_;\n\n  // data buff:\n  std::deque<IMUData> imu_data_buff_;\n\n  // earth constants:\n  Eigen::Vector3d g_;\n  Eigen::Vector3d w_;\n  Eigen::Vector3d b_;\n\n  // observability analysis:\n  struct {\n    std::vector<double> time_;\n    std::vector<Eigen::MatrixXd> Q_;\n    std::vector<Eigen::VectorXd> Y_;\n  } observability;\n\n  // hyper-params:\n  // a. earth constants:\n  struct {\n    double GRAVITY_MAGNITUDE;\n    double ROTATION_SPEED;\n    double LATITUDE;\n    double LONGITUDE;\n    struct {\n      double B_E;\n      double B_N;\n      double B_U;\n    } MAG;\n  } EARTH;\n  // b. prior state covariance, process & measurement noise:\n  struct {\n    struct {\n      double POSI;\n      double VEL;\n      double ORI;\n      double EPSILON;\n      double DELTA;\n    } PRIOR;\n    struct {\n      double GYRO;\n      double ACCEL;\n      double BIAS_ACCEL;\n      double BIAS_GYRO;\n      bool BIAS_FLAG;\n    } PROCESS;\n    struct {\n      struct {\n        double POSI;\n        double ORI;\n      } POSE;\n      double POSI;\n      double VEL;\n      double ORI;\n      double MAG;\n    } MEASUREMENT;\n  } COV;\n  // c. motion constraint:\n  struct {\n    bool ACTIVATED;\n    double W_B_THRESH;\n  } MOTION_CONSTRAINT;\n};\n\n} // namespace lidar_localization\n\n#endif // LIDAR_LOCALIZATION_MODELS_KALMAN_FILTER_KALMAN_FILTER_HPP_", "meta": {"hexsha": "401e599974f1f944cff697d5a25509531d959f05", "size": 5170, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "06-filtering-basic/src/lidar_localization/include/lidar_localization/models/kalman_filter/kalman_filter.hpp", "max_stars_repo_name": "WeihengXia0123/LiDar-SLAM", "max_stars_repo_head_hexsha": "834060da7ee0125cefd310d6215821551bac16c3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2021-03-19T05:51:44.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-16T06:10:16.000Z", "max_issues_repo_path": "06-filtering-basic/src/lidar_localization/include/lidar_localization/models/kalman_filter/kalman_filter.hpp", "max_issues_repo_name": "WeihengXia0123/LiDar-SLAM", "max_issues_repo_head_hexsha": "834060da7ee0125cefd310d6215821551bac16c3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "06-filtering-basic/src/lidar_localization/include/lidar_localization/models/kalman_filter/kalman_filter.hpp", "max_forks_repo_name": "WeihengXia0123/LiDar-SLAM", "max_forks_repo_head_hexsha": "834060da7ee0125cefd310d6215821551bac16c3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2021-02-17T12:31:08.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-22T17:12:44.000Z", "avg_line_length": 22.576419214, "max_line_length": 77, "alphanum_fraction": 0.6272727273, "num_tokens": 1347, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6477982179521103, "lm_q2_score": 0.5, "lm_q1q2_score": 0.3238991089760552}}
{"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 UZAWA_H\n#define UZAWA_H\n\n#include <boost/fusion/sequence.hpp>\n\n#include \"dune/common/static_assert.hh\"\n#include \"dune/istl/preconditioners.hh\"\n#include \"dune/istl/solvers.hh\"\n\n#include \"fem/linearspace.hh\"\n\nnamespace Kaskade\n{\n  /**\n   * Convenience function for simple application of\n   * preconditioners. Calls pre(), apply(), and post() sequentially.\n   */\n  template <class X, class Y>\n  void applyPreconditioner(Dune::Preconditioner<X,Y>& p, X& x, Y& y) {\n    p.pre(x,y);\n    p.apply(x,y);\n    p.post(x);\n  }\n\n  /**\n   * An inexact Uzawa solver for solving symmetric saddle point systems\n   *\n   * \\f[ \\begin{array}{cc} A & B^T \\\\ B & \\end{array}\\begin{matrix}{c} u \\\\ \\lambda \\end{matrix} =\n   * \\begin{matrix}{c} f \\\\ g \\end{matrix} \\f]\n   *\n   * It implements an inexact preconditioned conjugate gradient method for the\n   * Schur complement \\f$ BA^{-1}B^T\\f$.\n   *\n   * Template parameters:\n   * - X: the linear space of the primal variable \\f$ u \\f$\n   * - Y: the linear space of the dual variable \\f$ \\lambda \\f$\n   */\n  template<class X, class Y>\n  class UzawaSolver : public Dune::InverseOperator<LinearProductSpace<typename X::field_type,boost::fusion::vector<X,Y> >,\n  LinearProductSpace<typename X::field_type,boost::fusion::vector<X,Y> > > {\n  public:\n    typedef LinearProductSpace<typename X::field_type,boost::fusion::vector<X,Y> > domain_type;\n    typedef domain_type                                                            range_type;\n    typedef typename X::field_type                                                 field_type;\n    typedef field_type Scalar;\n    typedef domain_type Domain;\n    typedef range_type Range;\n\n    /**\n     * Constructor.\n     * \\param opA_ the linear operator \\f$ A \\f$\n     * \\param solA_ the approximate inverse operator \\f$ A^{-1} \\f$, needs to be a subclass of Dune::InverseOperator<X,X>\n     * \\param opB_ the linear operaotr \\f$ B \\f$\n     * \\param opBt_ the linear operator \\f$ B^T \\f$\n     * \\param pb_ the Schur complement preconditioner\n     * \\param reduction_ the default required reduction in preconditioned Schur complement's residual\n     * \\param maxit_ the maximum number of iterations\n     * \\param verbose_ printing level to stdout (0=silent, 1=result, 2=every iteration)\n     */\n    template<class A, class SolA, class B, class Bt, class PB>\n    UzawaSolver (A& opA_, SolA& solA_, B& opB_, Bt& opBt_, PB& pb_, double reduction_, int maxit_, int verbose_) :\n    opA(opA_), solA(solA_), opB(opB_), opBt(opBt_), precB(pb_), reduction(reduction_), maxit(maxit_), verbose(verbose_) {\n      using namespace Dune;\n      dune_static_assert( static_cast<int>(PB::category) == static_cast<int>(SolverCategory::sequential) , \"Preconditioner PB should be sequential.\");\n      dune_static_assert( static_cast<int>(A::category) == static_cast<int>(SolverCategory::sequential)  , \"Operator A should be sequential\");\n      dune_static_assert( static_cast<int>(B::category) == static_cast<int>(SolverCategory::sequential)  , \"Operator B should be sequential\");\n      dune_static_assert( static_cast<int>(Bt::category) == static_cast<int>(SolverCategory::sequential) , \"Operator Bt should be sequential\");\n    }\n\n\n    virtual void apply (Domain& x, Range& b, Dune::InverseOperatorResult& res) {\n      using namespace boost::fusion;\n      using namespace Dune;\n\n\n      Timer watch;                // start a timer\n\n      InverseOperatorResult resA;\n      if (verbose>0) printf(\"=== UzawaSolver\\n\");\n\n      // Declare variables\n      X& u(at_c<0>(x.data));\n      X& f(at_c<0>(b.data));\n      X r(u), h(u), rSave(u);\n      Y& lambda(at_c<1>(x.data));\n      Y g(at_c<1>(b.data)), d(g), p(g);\n      Y tmp(g); // WARNING: needed only for applying P twice!\n\n      // initialize\n      r = f;\n        opBt.applyscaleadd(-1,lambda,r);  // r = f-B'*u\n      solA.apply(u,r,resA);                    // Au = r\n      opB.applyscaleadd(-1,u,g);               // g = g-Bu\n      applyPreconditioner(precB,tmp,g);\n      applyPreconditioner(precB,d,tmp); // d = Pg // WARNING: assumes precB^2 is preco\n      double sigma = spY.dot(g,d);            // sigma = g'd\n      double sigma0 = sigma;\n\n      //std::cout << \"sigma = \" << sigma << \"\\n g=\" << at_c<0>(g.data) << \"d=\" << at_c<0>(d.data);\n\n      // Perform stationary iteration.\n      int i=0;\n      for ( ; i<maxit && sigma>reduction*reduction*sigma0; i++) {\n\n        // std::cout << \"d=P(g-Bu)=\" << at_c<0>(d.data);\n\n        opBt.apply(d,r);                       // r = B'd\n        rSave = r;\n        solA.apply(h,r,resA);                  // Ah = r\n        r = rSave;\n\n        double alpha = sigma / spX.dot(h,r);   // alpha = sigma / h'r\n        lambda.axpy(-alpha,d);                  // lambda = lambda-alpha d\n        u.axpy(alpha,h);                      // u = u+alpha h\n        opB.applyscaleadd(-alpha,h,g);          // g = g-alpha Bh\n\n        applyPreconditioner(precB,tmp,g);        // p = Pg\n        applyPreconditioner(precB,p,tmp); // WARNING\n\n        double sigmaOld = sigma;\n        sigma = spY.dot(g,p);\n        double beta = sigma / sigmaOld;\n\n\n        d *= beta; d.axpy(1,p);               // d = beta d + p\n\n\n        if (verbose>1) {\n          if (i%30==0)\n            std::printf(\"%5s %14s %14s\\n\",\"Iter\",\"Preco. Res.\",\"Rate\");\n          std::printf(\"%5d %14.4e %14.4e\\n\",i,std::sqrt(sigma),std::sqrt(beta));\n        }\n      }\n\n      // Fill statistics\n      res.clear();\n      res.iterations = i;\n      res.reduction = std::sqrt(sigma/sigma0);\n      res.converged = res.reduction<=reduction;\n      res.conv_rate = std::pow(res.reduction,1.0/i);\n      res.elapsed = watch.elapsed();\n\n\n      if (verbose>0)                 // final print\n        printf(\"=== rate=%g, time=%g, time/it=%g, iter=%d\\n\",res.conv_rate,res.elapsed,res.elapsed/i,i);\n    }\n\n    virtual void apply (Domain& x, Range& b, double reduction_, Dune::InverseOperatorResult& res)\n    {\n      reduction = reduction_;\n      this->apply(x,b,res);\n    }\n\n    void apply(Domain& x, Range& b)\n    {\n      Dune::InverseOperatorResult tmpResult;\n      apply(x,b,tmpResult);\n    }\n\n  private:\n    Dune::SeqScalarProduct<X> spX;\n    Dune::SeqScalarProduct<Y> spY;\n\n    Dune::LinearOperator<X,X>& opA;\n    Dune::InverseOperator<X,X>& solA;\n\n    Dune::LinearOperator<X,Y>& opB;\n    Dune::LinearOperator<Y,X>& opBt;\n    Dune::Preconditioner<Y,Y>& precB;\n\n    double reduction;\n    int    maxit;\n    int    verbose;\n  };\n}\n\n#endif\n", "meta": {"hexsha": "45f32aaceac93789f84f7ec5ce18ab915babe853", "size": 7289, "ext": "hh", "lang": "C++", "max_stars_repo_path": "Kaskade/linalg/uzawa.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/uzawa.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/uzawa.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.3631578947, "max_line_length": 150, "alphanum_fraction": 0.5476745781, "num_tokens": 1977, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6477982043529716, "lm_q2_score": 0.5, "lm_q1q2_score": 0.3238991021764858}}
{"text": "#include \"languageModels.h\"\n#include <boost/range/adaptor/map.hpp>\n#include <vector>\n#include <regex>\n#include <map>\n#include <tuple>\n#include \"platformTools.h\"\n#include <boost/filesystem/fstream.hpp>\n#include \"appInfo.h\"\n#include <cmath>\n#include <gsl_util.h>\n\nusing std::string;\nusing std::u32string;\nusing std::vector;\nusing std::regex;\nusing std::map;\nusing std::tuple;\nusing std::make_tuple;\nusing std::get;\nusing std::endl;\nusing boost::filesystem::path;\n\nusing unigram_t = string;\nusing bigram_t = tuple<string, string>;\nusing trigram_t = tuple<string, string, string>;\n\nmap<unigram_t, int> getUnigramCounts(const vector<string>& words) {\n\tmap<unigram_t, int> unigramCounts;\n\tfor (const unigram_t& unigram : words) {\n\t\t++unigramCounts[unigram];\n\t}\n\treturn unigramCounts;\n}\n\nmap<bigram_t, int> getBigramCounts(const vector<string>& words) {\n\tmap<bigram_t, int> bigramCounts;\n\tfor (auto it = words.begin(); it < words.end() - 1; ++it) {\n\t\t++bigramCounts[bigram_t(*it, *(it + 1))];\n\t}\n\treturn bigramCounts;\n}\n\nmap<trigram_t, int> getTrigramCounts(const vector<string>& words) {\n\tmap<trigram_t, int> trigramCounts;\n\tif (words.size() >= 3) {\n\t\tfor (auto it = words.begin(); it < words.end() - 2; ++it) {\n\t\t\t++trigramCounts[trigram_t(*it, *(it + 1), *(it + 2))];\n\t\t}\n\t}\n\treturn trigramCounts;\n}\n\nmap<unigram_t, double> getUnigramProbabilities(const vector<string>& words, const map<unigram_t, int>& unigramCounts, const double deflator) {\n\tmap<unigram_t, double> unigramProbabilities;\n\tfor (const auto& pair : unigramCounts) {\n\t\tunigram_t unigram = get<0>(pair);\n\t\tint unigramCount = get<1>(pair);\n\t\tunigramProbabilities[unigram] = double(unigramCount) / words.size() * deflator;\n\t}\n\treturn unigramProbabilities;\n}\n\nmap<bigram_t, double> getBigramProbabilities(const map<unigram_t, int>& unigramCounts, const map<bigram_t, int>& bigramCounts, const double deflator) {\n\tmap<bigram_t, double> bigramProbabilities;\n\tfor (const auto& pair : bigramCounts) {\n\t\tbigram_t bigram = get<0>(pair);\n\t\tint bigramCount = get<1>(pair);\n\t\tint unigramPrefixCount = unigramCounts.at(get<0>(bigram));\n\t\tbigramProbabilities[bigram] = double(bigramCount) / unigramPrefixCount * deflator;\n\t}\n\treturn bigramProbabilities;\n}\n\nmap<trigram_t, double> getTrigramProbabilities(const map<bigram_t, int>& bigramCounts, const map<trigram_t, int>& trigramCounts, const double deflator) {\n\tmap<trigram_t, double> trigramProbabilities;\n\tfor (const auto& pair : trigramCounts) {\n\t\ttrigram_t trigram = get<0>(pair);\n\t\tint trigramCount = get<1>(pair);\n\t\tint bigramPrefixCount = bigramCounts.at(bigram_t(get<0>(trigram), get<1>(trigram)));\n\t\ttrigramProbabilities[trigram] = double(trigramCount) / bigramPrefixCount * deflator;\n\t}\n\treturn trigramProbabilities;\n}\n\nmap<unigram_t, double> getUnigramBackoffWeights(\n\tconst map<unigram_t, int>& unigramCounts,\n\tconst map<unigram_t, double>& unigramProbabilities,\n\tconst map<bigram_t, int>& bigramCounts,\n\tconst double discountMass)\n{\n\tmap<unigram_t, double> unigramBackoffWeights;\n\tfor (const unigram_t& unigram : unigramCounts | boost::adaptors::map_keys) {\n\t\tdouble denominator = 1;\n\t\tfor (const bigram_t& bigram : bigramCounts | boost::adaptors::map_keys) {\n\t\t\tif (get<0>(bigram) == unigram) {\n\t\t\t\tdenominator -= unigramProbabilities.at(get<1>(bigram));\n\t\t\t}\n\t\t}\n\t\tunigramBackoffWeights[unigram] = discountMass / denominator;\n\t}\n\treturn unigramBackoffWeights;\n}\n\nmap<bigram_t, double> getBigramBackoffWeights(\n\tconst map<bigram_t, int>& bigramCounts,\n\tconst map<bigram_t, double>& bigramProbabilities,\n\tconst map<trigram_t, int>& trigramCounts,\n\tconst double discountMass)\n{\n\tmap<bigram_t, double> bigramBackoffWeights;\n\tfor (const bigram_t& bigram : bigramCounts | boost::adaptors::map_keys) {\n\t\tdouble denominator = 1;\n\t\tfor (const trigram_t& trigram : trigramCounts | boost::adaptors::map_keys) {\n\t\t\tif (bigram_t(get<0>(trigram), get<1>(trigram)) == bigram) {\n\t\t\t\tdenominator -= bigramProbabilities.at(bigram_t(get<1>(trigram), get<2>(trigram)));\n\t\t\t}\n\t\t}\n\t\tbigramBackoffWeights[bigram] = discountMass / denominator;\n\t}\n\treturn bigramBackoffWeights;\n}\n\nvoid createLanguageModelFile(const vector<string>& words, path filePath) {\n\tconst double discountMass = 0.5;\n\tconst double deflator = 1.0 - discountMass;\n\n\tmap<unigram_t, int> unigramCounts = getUnigramCounts(words);\n\tmap<bigram_t, int> bigramCounts = getBigramCounts(words);\n\tmap<trigram_t, int> trigramCounts = getTrigramCounts(words);\n\n\tmap<unigram_t, double> unigramProbabilities = getUnigramProbabilities(words, unigramCounts, deflator);\n\tmap<bigram_t, double> bigramProbabilities = getBigramProbabilities(unigramCounts, bigramCounts, deflator);\n\tmap<trigram_t, double> trigramProbabilities = getTrigramProbabilities(bigramCounts, trigramCounts, deflator);\n\n\tmap<unigram_t, double> unigramBackoffWeights = getUnigramBackoffWeights(unigramCounts, unigramProbabilities, bigramCounts, discountMass);\n\tmap<bigram_t, double> bigramBackoffWeights = getBigramBackoffWeights(bigramCounts, bigramProbabilities, trigramCounts, discountMass);\n\n\tboost::filesystem::ofstream file(filePath);\n\tfile << \"Generated by \" << appName << \" \" << appVersion << endl << endl;\n\n\tfile << \"\\\\data\\\\\" << endl;\n\tfile << \"ngram 1=\" << unigramCounts.size() << endl;\n\tfile << \"ngram 2=\" << bigramCounts.size() << endl;\n\tfile << \"ngram 3=\" << trigramCounts.size() << endl << endl;\n\n\tfile.setf(std::ios::fixed, std::ios::floatfield);\n\tfile.precision(4);\n\tfile << \"\\\\1-grams:\" << endl;\n\tfor (const unigram_t& unigram : unigramCounts | boost::adaptors::map_keys) {\n\t\tfile << log10(unigramProbabilities.at(unigram))\n\t\t\t<< \" \" << unigram\n\t\t\t<< \" \" << log10(unigramBackoffWeights.at(unigram)) << endl;\n\t}\n\tfile << endl;\n\n\tfile << \"\\\\2-grams:\" << endl;\n\tfor (const bigram_t& bigram : bigramCounts | boost::adaptors::map_keys) {\n\t\tfile << log10(bigramProbabilities.at(bigram))\n\t\t\t<< \" \" << get<0>(bigram) << \" \" << get<1>(bigram)\n\t\t\t<< \" \" << log10(bigramBackoffWeights.at(bigram)) << endl;\n\t}\n\tfile << endl;\n\n\tfile << \"\\\\3-grams:\" << endl;\n\tfor (const trigram_t& trigram : trigramCounts | boost::adaptors::map_keys) {\n\t\tfile << log10(trigramProbabilities.at(trigram))\n\t\t\t<< \" \" << get<0>(trigram) << \" \" << get<1>(trigram) << \" \" << get<2>(trigram) << endl;\n\t}\n\tfile << endl;\n\n\tfile << \"\\\\end\\\\\" << endl;\n}\n\nlambda_unique_ptr<ngram_model_t> createLanguageModel(const vector<string>& words, logmath_t& logMath) {\n\tpath tempFilePath = getTempFilePath();\n\tcreateLanguageModelFile(words, tempFilePath);\n\tauto deleteTempFile = gsl::finally([&]() { boost::filesystem::remove(tempFilePath); });\n\n\treturn lambda_unique_ptr<ngram_model_t>(\n\t\tngram_model_read(nullptr, tempFilePath.string().c_str(), NGRAM_ARPA, &logMath),\n\t\t[](ngram_model_t* lm) { ngram_model_free(lm); });\n}\n", "meta": {"hexsha": "1574a64f1baeccdbe453822f3127c341d6efa2ec", "size": 6699, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/languageModels.cpp", "max_stars_repo_name": "meshonline/rhubarb-lip-sync", "max_stars_repo_head_hexsha": "75e73300455192144cd31634cfc5c5b653cc55a9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2016-12-28T22:14:50.000Z", "max_stars_repo_stars_event_max_datetime": "2018-05-05T21:31:37.000Z", "max_issues_repo_path": "src/languageModels.cpp", "max_issues_repo_name": "meshonline/rhubarb-lip-sync", "max_issues_repo_head_hexsha": "75e73300455192144cd31634cfc5c5b653cc55a9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/languageModels.cpp", "max_forks_repo_name": "meshonline/rhubarb-lip-sync", "max_forks_repo_head_hexsha": "75e73300455192144cd31634cfc5c5b653cc55a9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-11-17T18:59:57.000Z", "max_forks_repo_forks_event_max_datetime": "2018-11-17T18:59:57.000Z", "avg_line_length": 36.4076086957, "max_line_length": 153, "alphanum_fraction": 0.7217495149, "num_tokens": 1956, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6477982043529715, "lm_q2_score": 0.5, "lm_q1q2_score": 0.32389910217648576}}
{"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/Util.h\"\n#include \"netbuilder/Helpers/Path.h\"\n#include <cmath>\n#include <cstdlib>\n#include <fstream>\n#include <boost/filesystem.hpp>\n\n#include <NTL/ZZ.h>\n\nnamespace LatBuilder\n{\n\n//===============================================================================\nPolynomial PolynomialFromInt(uInteger x)\n{\n   Polynomial P;\n   P.SetLength(LENGTH_UINTEGER); \n   uInteger y=x;\n   long i=0;\n    do{\n       P[i++] = y%2;\n   } while(y >>= 1);\n    \n    P.normalize();\n    return P;\n}\n\n//================================================================================\n\nuInteger IndexOfPolynomial(Polynomial P)\n{\n   uInteger x=0;\n   uInteger q=1;\n   \n   for (int i = 0; i <= deg(P); i++)\n    { \n        if(IsOne(coeff(P,i))){\n            x+= q;\n       }\n       q <<= 1;\n    }\n    return x;\n}\n\n\n\n//================================================================================\n\nstd::vector<uInteger> primeFactors(uInteger n, bool raise)\n{\n  NTL::PrimeSeq s;\n   unsigned long p;\n   p = s.next();\n   std::vector<uInteger> factors;\n   while (p <= n) {\n      ldiv_t qr = std::ldiv(n, p);\n      uInteger factor = 1;\n      while (qr.rem == 0) {\n         n = qr.quot;\n         factor *= p;\n         if (!raise)\n            break;\n         qr = std::ldiv(n, p);\n      }\n      if (factor > 1)\n         factors.push_back(factor);\n      p = s.next();\n   }\n   return factors;\n}\n\n//================================================================================\n\nstd::map<uInteger, uInteger> primeFactorsMap(uInteger n)\n{\n  NTL::PrimeSeq s;\n   unsigned long factor;\n   factor = s.next();\n   std::map<uInteger, uInteger> factors;\n   while (factor <= n) {\n      ldiv_t qr = std::ldiv(n, factor);\n      while (qr.rem == 0) {\n         n = qr.quot;\n         factors[factor]++;\n         qr = std::ldiv(n, factor);\n      }\n      factor = s.next();\n   }\n   return factors;\n}\n\n//================================================================================\n\nstd::pair<long long, long long> egcd(uInteger a, uInteger b)\n{\n   typedef std::pair<long long, long long> result_type;\n   result_type cur{0, 1};\n   result_type last{1, 0};\n   while (b != 0) {\n      ldiv_t qr = std::ldiv(a, b);\n      a = b;\n      b = qr.rem;\n      std::swap(cur, last);\n      cur.first = cur.first - qr.quot * last.first;\n      cur.second = cur.second - qr.quot * last.second;\n   }\n   return last;\n}\n\n//================================================================================\n\n\nuInteger Vm(const Polynomial& h, const Polynomial& P)\n{\n   \n   long m = deg(P);\n   NTL::vector<NTL::GF2> w;\n   w.resize(m);\n   uInteger res = 0;\n   for(long i=0; i<m; i++){\n      w[i] = (m-i-1>deg(h)) ? NTL::GF2(0) : coeff(h,m-i-1);\n      for(long j=0; j<i; j++){\n         w[i] += w[j]* coeff(P,m-(i-j));\n      }  \n   }\n   uInteger q = 1;\n   for(long i=m-1; i>=0; i--){\n      res += IsOne(w[i])*q;\n      q *= 2;\n   }\n\n   return res;\n\n}\n\nuInteger log2Int(unsigned int n){\n    unsigned int res=0;\n    while (n>1){\n    n = n >> 1;\n    res ++;\n    }\n    return res;\n}\n\n//================================================================================\n\nconst char* ws = \" \\t\\n\\r\\f\\v\";\n\n// trim from end (right)\ninline std::string& rtrim(std::string& s, const char* t = ws)\n{\n      s.erase(s.find_last_not_of(t) + 1);\n      return s;\n}\n\n// trim from beginning (left)\ninline std::string& ltrim(std::string& s, const char* t = ws)\n{\n      s.erase(0, s.find_first_not_of(t));\n      return s;\n}\n\n// trim from both ends (left & right)\ninline std::string& trim(std::string& s, const char* t = ws)\n{\n      return ltrim(rtrim(s, t), t);\n}    \n\nstd::string getDefaultPolynomial(unsigned int degree)\n{\n    if (degree <= 32)\n    {\n        std::string path = NetBuilder::PATH_TO_LATNETBUILDER_DIR + \"/../share/latnetbuilder/data/default_polys.csv\";\n        if (boost::filesystem::exists(path)){\n            std::ifstream file(path);\n            std::string sent;\n            do\n            {\n            getline(file,sent);\n            trim(sent);\n            }\n            while (sent != \"###\");\n        \n            getline(file,sent);\n\n            for(unsigned int d = 0; d <= degree; ++d)\n            {\n                getline(file,sent);\n            }\n            return sent;\n        }\n        else{\n            throw std::runtime_error(\"Unable to locate data folder. The value of PATH_TO_LATNETBUILDER_DIR is probably incorrect. See netbuilder/Path.h.\");\n        }\n    }\n    return \"\";\n}\n\nstd::string to_string(LatticeType LT){\n    \n    static const char * LatticeTypeStrings[] = { \"Ordinary\", \"Polynomial\", \"Digital\" };\n\n    return LatticeTypeStrings[(int) LT];\n}\n\n} // namespace LatBuilder\n", "meta": {"hexsha": "55af6a6c89632fdc4d13067f8d0ca160b1c8be84", "size": 5349, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/LatBuilder/Util.cc", "max_stars_repo_name": "YochevedDarmon/latnetbuilder", "max_stars_repo_head_hexsha": "7df3a7ba89e10ca51d4af347b75cdb0987e5151c", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2020-01-21T06:08:51.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-24T16:11:31.000Z", "max_issues_repo_path": "src/LatBuilder/Util.cc", "max_issues_repo_name": "YochevedDarmon/latnetbuilder", "max_issues_repo_head_hexsha": "7df3a7ba89e10ca51d4af347b75cdb0987e5151c", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2019-10-31T07:49:28.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-03T12:07:49.000Z", "max_forks_repo_path": "src/LatBuilder/Util.cc", "max_forks_repo_name": "YochevedDarmon/latnetbuilder", "max_forks_repo_head_hexsha": "7df3a7ba89e10ca51d4af347b75cdb0987e5151c", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2016-07-27T19:25:26.000Z", "max_forks_repo_forks_event_max_datetime": "2018-05-22T20:00:47.000Z", "avg_line_length": 23.9865470852, "max_line_length": 155, "alphanum_fraction": 0.5047672462, "num_tokens": 1356, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6187804337438501, "lm_q2_score": 0.523420348936324, "lm_q1q2_score": 0.32388227054517593}}
{"text": "/***********************************************************************************************************************\n*  OpenStudio(R), Copyright (c) 2008-2021, 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_MATRIX_HPP\n#define UTILITIES_DATA_MATRIX_HPP\n\n#include \"Vector.hpp\"\n#include \"../UtilitiesAPI.hpp\"\n#include \"../core/Logger.hpp\"\n\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/io.hpp>\n#include <boost/numeric/ublas/lu.hpp>\n\nnamespace openstudio {\n\n/// Matrix\ntypedef boost::numeric::ublas::matrix<double> Matrix;\n\n//////////////////////////////////////////////////////////////////////////\n// Begin SWIG'able, copy and paste into Matrix.i\n//////////////////////////////////////////////////////////////////////////\n\n/// new operators\n\nUTILITIES_API bool operator==(const Matrix& lhs, const Matrix& rhs);\nUTILITIES_API bool operator!=(const Matrix& lhs, const Matrix& rhs);\n\n/// common methods\n\n/// linear interpolation of the function v = f(x, y) at point xi, yi\n/// assumes that x and y are strictly increasing\nUTILITIES_API double interp(const Vector& x, const Vector& y, const Matrix& v, double xi, double yi, InterpMethod interpMethod = LinearInterp,\n                            ExtrapMethod extrapMethod = NoneExtrap);\n\n/// linear interpolation of the function v = f(x, y) at points xi, yi\n/// assumes that x and y are strictly increasing\nUTILITIES_API Vector interp(const Vector& x, const Vector& y, const Matrix& v, const Vector& xi, double yi, InterpMethod interpMethod = LinearInterp,\n                            ExtrapMethod extrapMethod = NoneExtrap);\n\n/// linear interpolation of the function v = f(x, y) at points xi, yi\n/// assumes that x and y are strictly increasing\nUTILITIES_API Vector interp(const Vector& x, const Vector& y, const Matrix& v, double xi, const Vector& yi, InterpMethod interpMethod = LinearInterp,\n                            ExtrapMethod extrapMethod = NoneExtrap);\n\n/// linear interpolation of the function v = f(x, y) at points xi, yi\n/// assumes that x and y are strictly increasing\nUTILITIES_API Matrix interp(const Vector& x, const Vector& y, const Matrix& v, const Vector& xi, const Vector& yi,\n                            InterpMethod interpMethod = LinearInterp, ExtrapMethod extrapMethod = NoneExtrap);\n\n/// matrix product\nUTILITIES_API Matrix prod(const Matrix& lop, const Matrix& rop);\n\n/// vector product\nUTILITIES_API Vector prod(const Matrix& m, const Vector& v);\n\n/// outer product\nUTILITIES_API Matrix outerProd(const Vector& lhs, const Vector& rhs);\n\n/// take the natural logarithm of Matrix elements, componentwise\nUTILITIES_API Matrix log(const Matrix& v);\n\n/// take the logarithm of Matrix elements with respect to base, componentwise\nUTILITIES_API Matrix log(const Matrix& v, double base);\n\n/// generates a M x N Matrix whose elements come from the uniform distribution on [a,b].\nUTILITIES_API Matrix randMatrix(double a, double b, unsigned M, unsigned N);\n\n/// sum of all elements\nUTILITIES_API double sum(const Matrix& matrix);\n\n/// maximum of all elements\nUTILITIES_API double maximum(const Matrix& matrix);\n\n/// minimum of all elements\nUTILITIES_API double minimum(const Matrix& matrix);\n\n/// mean of all elements\nUTILITIES_API double mean(const Matrix& matrix);\n\n/// get the connected components from an NxN adjacency matrix (1.0 for i-j connected, 0.0 for i-j not connected)\nUTILITIES_API std::vector<std::vector<unsigned>> findConnectedComponents(const Matrix& matrix);\n\n// from the boost vault:\n// The following code inverts the matrix input using LU-decomposition with backsubstitution of unit vectors. Reference: Numerical Recipes in C, 2nd ed., by Press, Teukolsky, Vetterling & Flannery.\n/// Matrix inversion routine, using lu_factorize and lu_substitute in uBLAS to invert a matrix */\ntemplate <class T>\nbool invert(const boost::numeric::ublas::matrix<T>& input, boost::numeric::ublas::matrix<T>& inverse) {\n\n  // create a working copy of the input\n  boost::numeric::ublas::matrix<T> A(input);\n\n  // create a permutation matrix for the LU-factorization\n  boost::numeric::ublas::permutation_matrix<std::size_t> pm(A.size1());\n\n  // perform LU-factorization\n  typename boost::numeric::ublas::matrix<T>::size_type res = boost::numeric::ublas::lu_factorize(A, pm);\n  if (res != 0) {\n    LOG_FREE(Info, \"boost.ublas\",\n             \"boost::numeric::ublas::lu_factorize returned res = \" << res << \", A = \" << A << \", pm = \" << pm << \" for input = \" << input);\n    return false;\n  }\n\n  // create identity matrix of \"inverse\"\n  inverse.assign(boost::numeric::ublas::identity_matrix<T>(A.size1()));\n\n  // backsubstitute to get the inverse\n  try {\n    boost::numeric::ublas::lu_substitute(A, pm, inverse);\n  } catch (std::exception& e) {\n    LOG_FREE(Info, \"boost.ublas\", \"boost::numeric::ublas::lu_substitute threw exception '\" << e.what() << \"' for A = \" << A << \", pm = \" << pm);\n    return false;\n  }\n\n  return true;\n}\n\n}  // namespace openstudio\n\n#endif  //UTILITIES_DATA_MATRIX_HPP\n", "meta": {"hexsha": "161d84e73e7722cac013450f4934e453a0a8230f", "size": 7099, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/utilities/data/Matrix.hpp", "max_stars_repo_name": "muehleisen/OpenStudio", "max_stars_repo_head_hexsha": "3bfe89f6c441d1e61e50b8e94e92e7218b4555a0", "max_stars_repo_licenses": ["blessing"], "max_stars_count": 354.0, "max_stars_repo_stars_event_min_datetime": "2015-01-10T17:46:11.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T10:00:00.000Z", "max_issues_repo_path": "src/utilities/data/Matrix.hpp", "max_issues_repo_name": "muehleisen/OpenStudio", "max_issues_repo_head_hexsha": "3bfe89f6c441d1e61e50b8e94e92e7218b4555a0", "max_issues_repo_licenses": ["blessing"], "max_issues_count": 3243.0, "max_issues_repo_issues_event_min_datetime": "2015-01-02T04:54:45.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T17:22:22.000Z", "max_forks_repo_path": "src/utilities/data/Matrix.hpp", "max_forks_repo_name": "jmarrec/OpenStudio", "max_forks_repo_head_hexsha": "5276feff0d8dbd6c8ef4e87eed626bc270a19b14", "max_forks_repo_licenses": ["blessing"], "max_forks_count": 157.0, "max_forks_repo_forks_event_min_datetime": "2015-01-07T15:59:55.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-30T07:46:09.000Z", "avg_line_length": 48.2925170068, "max_line_length": 196, "alphanum_fraction": 0.6950274687, "num_tokens": 1582, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6187804196836382, "lm_q2_score": 0.523420348936324, "lm_q1q2_score": 0.32388226318577495}}
{"text": "/*\n * DivRightHandSide.cc\n *\n *  Created on: 29.06.2017\n *      Author: thies\n */\n\n#include <deal.II/base/exceptions.h>\n#include <deal.II/base/types.h>\n#include <deal.II/base/work_stream.h>\n#include <deal.II/fe/fe.h>\n#include <deal.II/fe/fe_update_flags.h>\n#include <deal.II/fe/fe_values.h>\n\n#include <base/DiscretizedFunction.h>\n#include <forward/DivRightHandSide.h>\n\n#include <functional>\n#include <vector>\n\nnamespace wavepi {\nnamespace forward {\nusing namespace dealii;\nusing namespace wavepi::base;\n\ntemplate<int dim>\nDivRightHandSide<dim>::DivRightHandSide(std::shared_ptr<DiscretizedFunction<dim>> a,\n      std::shared_ptr<DiscretizedFunction<dim>> b, std::shared_ptr<DiscretizedFunction<dim>> u)\n      : a(a), b(b), u(u) {\n}\n\ntemplate<int dim>\nDivRightHandSide<dim>::AssemblyScratchData::AssemblyScratchData(const FiniteElement<dim> &fe,\n      const Quadrature<dim> &quad)\n      : fe_values(fe, quad, update_values | update_gradients | update_quadrature_points | update_JxW_values) {\n}\n\ntemplate<int dim>\nDivRightHandSide<dim>::AssemblyScratchData::AssemblyScratchData(const AssemblyScratchData &scratch_data)\n      :\n            fe_values(scratch_data.fe_values.get_fe(), scratch_data.fe_values.get_quadrature(),\n                  update_values | update_gradients | update_quadrature_points | update_JxW_values) {\n}\n\ntemplate<int dim>\nvoid DivRightHandSide<dim>::copy_local_to_global(Vector<double> &result, const AssemblyCopyData &copy_data) {\n   for (unsigned int i = 0; i < copy_data.local_dof_indices.size(); ++i)\n      result(copy_data.local_dof_indices[i]) += copy_data.cell_rhs(i);\n}\n\ntemplate<int dim>\nvoid DivRightHandSide<dim>::local_assemble(const Vector<double> &a, const Vector<double> &b, const Vector<double> &u,\n      const typename DoFHandler<dim>::active_cell_iterator &cell, AssemblyScratchData &scratch_data,\n      AssemblyCopyData &copy_data) {\n   const unsigned int dofs_per_cell = scratch_data.fe_values.get_fe().dofs_per_cell;\n   const unsigned int n_q_points = scratch_data.fe_values.get_quadrature().size();\n\n   copy_data.cell_rhs.reinit(dofs_per_cell);\n   copy_data.local_dof_indices.resize(dofs_per_cell);\n   scratch_data.fe_values.reinit(cell);\n\n   cell->get_dof_indices(copy_data.local_dof_indices);\n\n   for (unsigned int q_point = 0; q_point < n_q_points; ++q_point)\n      for (unsigned int i = 0; i < dofs_per_cell; ++i)\n         for (unsigned int ka = 0; ka < dofs_per_cell; ++ka) {\n            for (unsigned int ku = 0; ku < dofs_per_cell; ++ku)\n               copy_data.cell_rhs(i) -= a[copy_data.local_dof_indices[ka]]\n                     * scratch_data.fe_values.shape_value(ka, q_point) * u[copy_data.local_dof_indices[ku]]\n                     * scratch_data.fe_values.shape_grad(ku, q_point) * scratch_data.fe_values.shape_grad(i, q_point)\n                     * scratch_data.fe_values.JxW(q_point);\n\n            copy_data.cell_rhs(i) += b[copy_data.local_dof_indices[ka]]\n                  * scratch_data.fe_values.shape_value(ka, q_point) * scratch_data.fe_values.shape_value(i, q_point)\n                  * scratch_data.fe_values.JxW(q_point);\n         }\n}\n\ntemplate<int dim>\nvoid DivRightHandSide<dim>::create_right_hand_side(const DoFHandler<dim> &dof, const Quadrature<dim> &quad,\n      Vector<double> &rhs) const {\n   AssertThrow(a != nullptr, ExcZero());\n   AssertThrow(b != nullptr, ExcZero());\n   AssertThrow(u != nullptr, ExcZero());\n\n   const Vector<double> &ca = a->get_function_coefficients_by_time(this->get_time());\n   const Vector<double> &cb = b->get_function_coefficients_by_time(this->get_time());\n   const Vector<double> &cu = u->get_function_coefficients_by_time(this->get_time());\n\n   Assert(ca.size() == dof.n_dofs(), ExcDimensionMismatch(ca.size(), dof.n_dofs()));\n   Assert(cb.size() == dof.n_dofs(), ExcDimensionMismatch(cb.size(), dof.n_dofs()));\n   Assert(cu.size() == dof.n_dofs(), ExcDimensionMismatch(cu.size(), dof.n_dofs()));\n\n   WorkStream::run(dof.begin_active(), dof.end(),\n         std::bind(&DivRightHandSide<dim>::local_assemble, *this, ca, cb, cu, std::placeholders::_1,\n               std::placeholders::_2, std::placeholders::_3),\n         std::bind(&DivRightHandSide<dim>::copy_local_to_global, *this, std::ref(rhs), std::placeholders::_1),\n         AssemblyScratchData(dof.get_fe(), quad), AssemblyCopyData());\n}\n\ntemplate class DivRightHandSide<1> ;\ntemplate class DivRightHandSide<2> ;\ntemplate class DivRightHandSide<3> ;\n\n} /* namespace forward */\n} /* namespace wavepi */\n", "meta": {"hexsha": "da87301e06940308eba69b6d775ef1587357a76d", "size": 4471, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lib/forward/DivRightHandSide.cpp", "max_stars_repo_name": "thiesgerken/wavepi", "max_stars_repo_head_hexsha": "5af37946dcc1910ad1cccdc76d2e2f546eeafec4", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "lib/forward/DivRightHandSide.cpp", "max_issues_repo_name": "thiesgerken/wavepi", "max_issues_repo_head_hexsha": "5af37946dcc1910ad1cccdc76d2e2f546eeafec4", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lib/forward/DivRightHandSide.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": 41.785046729, "max_line_length": 117, "alphanum_fraction": 0.7065533438, "num_tokens": 1142, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7025300573952054, "lm_q2_score": 0.4610167793123159, "lm_q1q2_score": 0.323878144430434}}
{"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 cardinality.hpp\n *\n * @brief SAT cardinality constraints\n *\n * @author Mathias Soeken\n * @author Heinz Riener\n *\n * @since  2.2\n */\n\n#ifndef CARDINALITY_HPP\n#define CARDINALITY_HPP\n\n#include <numeric>\n\n#include <boost/assign/std/vector.hpp>\n#include <boost/range.hpp>\n#include <boost/range/adaptors.hpp>\n#include <boost/range/algorithm_ext/iota.hpp>\n#include <boost/range/algorithm_ext/push_back.hpp>\n\n#include <core/utils/range_utils.hpp>\n#include <classical/sat/sat_solver.hpp>\n#include <classical/sat/operations/logic.hpp>\n\nusing namespace boost::assign;\n\n/**\n * Carsten Sinz's CNF encoding of Boolean cardinality constraints [1].\n * The implementation is mainly based on the Knuth's descriptions [2].\n *\n * [1] Carsten Sinz. Towards an optimal CNF encoding of boolean\n * cardinality constraints, CP, pages 827-831, 2005.\n *\n * [2] Donald E. Knuth, The Art of Computer Programming, Volume 4,\n * Pre-Fascicle 6A, page 8ff.\n */\n\nnamespace cirkit\n{\n\ntemplate<class S, class C>\nvoid atmost_one( S& solver, const C& x )\n{\n  for ( auto i = boost::begin( x ); i != boost::end( x ); ++i )\n  {\n    if ( i + 1 == boost::end( x ) ) continue;\n    for ( auto j = i + 1; j != boost::end( x ); ++j )\n    {\n      add_clause( solver )( {-*i, -*j} );\n    }\n  }\n}\n\ntemplate<class S, class C>\ninline void one_hot( S& solver, const C& x )\n{\n  add_clause( solver )( x );\n  atmost_one( solver, x );\n}\n\ntemplate < class S >\nint less_or_equal_sinz( S& solver, const clause_t& x, unsigned r, int sid, int spol = 1 )\n{\n  const unsigned n = x.size();\n\n  //std::cerr << \"n = \" << n << \" r = \" << r << \" sid = \" << sid << '\\n';\n  assert( n > r );\n  for ( auto j = 0u; j < n - r - 1; ++j )\n  {\n    for ( auto k = 0u; k < r; ++k )\n    {\n      // std::cerr << \"(\" << j << \",\" << k << \")\" << '\\n';\n      //const int l1 = spol * -(sid + j * (n - r) + k);\n      //const int l2 = spol * (sid + (j + 1u) * (n - r) + k);\n      const int l1 = spol * -( sid + j * r + k );\n      const int l2 = spol * (sid + ( j + 1u ) * r + k );\n      add_clause( solver )( {l1, l2} );\n    }\n  }\n\n  for ( auto j = 0u; j < (n - r); ++j )\n  {\n    for ( auto k = 0u; k <= r; ++k )\n    {\n      // std::cerr << \"(\" << j << \",\" << k << \")\" << '\\n';\n      clause_t clause;\n      clause += -x[ j + k ];\n      //if ( k > 0u ) clause += spol * -(sid + j * ( n - r ) + k - 1u );\n      //if ( k < r ) clause += spol * (sid + j * ( n - r ) + k );\n      if ( k > 0u ) clause += spol * -(sid + j * r + k - 1u );\n      if ( k < r ) clause += spol * (sid + j * r + k );\n      add_clause( solver )( clause );\n    }\n  }\n\n  sid += (n - r)*r/* + 1u*/;\n  //std::cerr << \"next sid: \" << sid << '\\n';\n  return sid;\n}\n\ntemplate < class S >\nint greater_or_equal_sinz( S& solver, const clause_t& x, unsigned r, int sid, int spol = 1 )\n{\n  using boost::adaptors::transformed;\n\n  clause_t xn;\n  boost::push_back( xn, x | transformed( []( int v ) { return -v; } ) );\n  return less_or_equal_sinz( solver, xn, x.size() - r, sid, spol );\n}\n\ntemplate < class S >\nint equals_sinz( S& solver, const clause_t& x, unsigned r, int sid )\n{\n  //std::cout << \"call equals_size with x.size = \" << x.size() << \", r = \" << r << \", and sid = \" << sid << std::endl;\n\n  if ( r == 0u )\n  {\n    for ( const auto& l : x )\n    {\n      add_clause( solver )( {-l} );\n    }\n    return sid;\n  }\n\n  if ( r == x.size() )\n  {\n    for ( const auto& l : x )\n    {\n      add_clause( solver )( {l} );\n    }\n    return sid;\n  }\n\n  sid = less_or_equal_sinz( solver, x, r, sid, 1 );\n  return greater_or_equal_sinz( solver, x, r, sid, -1 );\n}\n\n/******************************************************************************\n * Binary tree encoding from Bailleux and Boufkhad                            *\n ******************************************************************************/\ntemplate<class S>\nint less_or_equal_bailleux_boufkhad_assume( S& solver, int assume, const clause_t& x, unsigned r, int sid )\n{\n  const auto n = x.size();                    /* number of variables */\n  std::vector<unsigned> ts_count( 2 * n, 1 ); /* pre-assign t's with 1 (for the leaves), we don't use index 0 */\n  std::vector<int> ts( 2 * n, 0 );\n  std::vector<int> pol( 2 * n, 1 );\n\n  auto offset = sid;\n  for ( auto k = n - 1; k > 1; --k )\n  {\n    ts_count[k] = std::min( ts_count[k << 1] + ts_count[( k << 1 ) + 1], r );\n    ts[k] = offset;\n    offset += ts_count[k];\n  }\n  for ( auto k = n; k < 2 * n; ++k )\n  {\n    ts[k] = abs( x[k - n] );\n    pol[k] = x[k - n] > 0 ? 1 : -1;\n  }\n\n  for ( auto k = 2u; k < n; ++k )\n  {\n    for ( auto i = 0u; i <= ts_count[k << 1]; ++i )\n    {\n      for ( auto j = 0u; j <= ts_count[( k << 1 ) + 1]; ++j )\n      {\n        if ( ( i + j < 1 ) || ( i + j > ts_count[k] + 1 ) ) { continue; }\n\n        std::vector<int> clause = { -assume };\n        if ( i > 0 ) { clause.push_back( -pol[k << 1] * ( ts[k << 1] + i - 1 ) ); }\n        if ( j > 0 ) { clause.push_back( -pol[( k << 1 ) + 1] * ( ts[( k << 1 ) + 1] + j - 1 ) ); }\n        if ( i + j <= r ) { clause.push_back( pol[k] * ( ts[k] + i + j - 1 ) ); }\n\n        if ( !clause.empty() )\n        {\n          add_clause( solver )( clause );\n        }\n      }\n    }\n  }\n\n  for ( auto i = 0; i <= static_cast<int>( ts_count[2] ); ++i )\n  {\n    for ( auto j = 0; j <= static_cast<int>( ts_count[3] ); ++j )\n    {\n      if ( i + j == static_cast<int>( r ) + 1 )\n      {\n        assert( i && j );\n        add_clause( solver )( { -assume, -pol[2] * ( ts[2] + i - 1 ), -pol[3] * ( ts[3] + j - 1 )} );\n      }\n    }\n  }\n\n  return offset;\n}\n\ntemplate<class S>\nint less_or_equal_bailleux_boufkhad( S& solver, const clause_t& x, unsigned r, int sid )\n{\n  const auto n = x.size();                    /* number of variables */\n  std::vector<unsigned> ts_count( 2 * n, 1 ); /* pre-assign t's with 1 (for the leaves), we don't use index 0 */\n  std::vector<int> ts( 2 * n, 0 );\n  std::vector<int> pol( 2 * n, 1 );\n\n  auto offset = sid;\n  for ( int k = n - 1; k > 1; --k )\n  {\n    ts_count[k] = std::min( ts_count[k << 1] + ts_count[( k << 1 ) + 1], r );\n    ts[k] = offset;\n    offset += ts_count[k];\n  }\n  for ( auto k = n; k < 2 * n; ++k )\n  {\n    ts[k] = abs( x[k - n] );\n    pol[k] = x[k - n] > 0 ? 1 : -1;\n  }\n\n  for ( auto k = 2u; k < n; ++k )\n  {\n    for ( auto i = 0u; i <= ts_count[k << 1]; ++i )\n    {\n      for ( auto j = 0u; j <= ts_count[( k << 1 ) + 1]; ++j )\n      {\n        if ( ( i + j < 1 ) || ( i + j > ts_count[k] + 1 ) ) { continue; }\n\n        std::vector<int> clause;\n        if ( i > 0 ) { clause.push_back( -pol[k << 1] * ( ts[k << 1] + i - 1 ) ); }\n        if ( j > 0 ) { clause.push_back( -pol[( k << 1 ) + 1] * ( ts[( k << 1 ) + 1] + j - 1 ) ); }\n        if ( i + j <= r ) { clause.push_back( pol[k] * ( ts[k] + i + j - 1 ) ); }\n\n        if ( !clause.empty() )\n        {\n          add_clause( solver )( clause );\n        }\n      }\n    }\n  }\n\n  for ( auto i = 0; i <= static_cast<int>( ts_count[2] ); ++i )\n  {\n    for ( auto j = 0; j <= static_cast<int>( ts_count[3] ); ++j )\n    {\n      if ( i + j == static_cast<int>( r ) + 1 )\n      {\n        assert( i && j );\n        add_clause( solver )( {-pol[2] * ( ts[2] + i - 1 ), -pol[3] * ( ts[3] + j - 1 )} );\n      }\n    }\n  }\n\n  return offset;\n}\n\ntemplate<class S>\nint greater_or_equal_bailleux_boufkhad( S& solver, const clause_t& x, unsigned r, int sid )\n{\n  using boost::adaptors::transformed;\n\n  clause_t xn;\n  boost::push_back( xn, x | transformed( []( int v ) { return -v; } ) );\n  return less_or_equal_bailleux_boufkhad( solver, xn, x.size() - r, sid );\n}\n\ntemplate < class S >\nint equals_bailleux_boufkhad( S& solver, const clause_t& x, unsigned r, int sid )\n{\n  if ( r == 0u )\n  {\n    for ( const auto& l : x )\n    {\n      add_clause( solver )( {-l} );\n    }\n    return sid;\n  }\n\n  if ( r == x.size() )\n  {\n    for ( const auto& l : x )\n    {\n      add_clause( solver )( {l} );\n    }\n    return sid;\n  }\n\n  sid = less_or_equal_bailleux_boufkhad( solver, x, r, sid );\n  return greater_or_equal_bailleux_boufkhad( solver, x, r, sid );\n}\n\n/******************************************************************************\n * Pairwise cardinality networks                                              *\n ******************************************************************************/\n\n// Based on [M. Codish and M. Zazon-Ivry, LPAR, 2016, 154-172] and https://bitbucket.org/alanmi/abc/src/f78c2854aa5948fea93533c3934fb0f6a2c3c785/src/aig/gia/giaSatMap.c?at=default&fileviewer=file-view-default\n\n// namespace detail\n// {\n\n// template<class S>\n// void sat_add_half_sorter( S& solver, int a, int b, int y, int z )\n// {\n//   add_clause( solver )( {a, -y} );\n//   add_clause( solver )( {a, -z} );\n//   add_clause( solver )( {b, -y, -z} );\n//   // add_clause( solver )( {-a, y} );\n//   // add_clause( solver )( {-a, z} );\n//   // add_clause( solver )( {-b, y, z} );\n// }\n\n// template<class S>\n// void sat_pairwise_cardinality_network_add_sorter( S& solver, std::vector<int>& vvars, int i, int k, int *pnvars )\n// {\n//   const auto ivar1 = (*pnvars)++;\n//   const auto ivar2 = (*pnvars)++;\n\n//   sat_add_half_sorter( solver, ivar1, ivar2, vvars[i], vvars[k] );\n//   vvars[i] = ivar1;\n//   vvars[k] = ivar2;\n// }\n\n// template<class S>\n// void sat_pairwise_cardinality_network_add_constraint_merge( S& solver, std::vector<int>& vvars, int lo, int hi, int r, int *pnvars )\n// {\n//   const auto step = r * 2;\n//   if ( step >= hi - lo ) return;\n\n//   sat_pairwise_cardinality_network_add_constraint_merge( solver, vvars, lo, hi - r, step, pnvars );\n//   sat_pairwise_cardinality_network_add_constraint_merge( solver, vvars, lo + r, hi, step, pnvars );\n//   for ( auto i = lo + r; i < hi - r; i += step )\n//   {\n//     sat_pairwise_cardinality_network_add_sorter( solver, vvars, i, i + r, pnvars );\n//   }\n// }\n\n// template<class S>\n// void sat_pairwise_cardinality_network_add_constraint_range( S& solver, std::vector<int>& vvars, int lo, int hi, int *pnvars )\n// {\n//   if ( hi - lo < 1 ) return;\n\n//   const auto mid = lo + ( hi - lo ) / 2;\n//   for ( auto i = lo; i <= mid; ++i )\n//   {\n//     sat_pairwise_cardinality_network_add_sorter( solver, vvars, i, i + ( hi - lo + 1 ) / 2, pnvars );\n//   }\n//   sat_pairwise_cardinality_network_add_constraint_range( solver, vvars, lo, mid, pnvars );\n//   sat_pairwise_cardinality_network_add_constraint_range( solver, vvars, mid + 1, hi, pnvars );\n//   sat_pairwise_cardinality_network_add_constraint_merge( solver, vvars, lo, hi, 1, pnvars );\n// }\n\n// template<class S>\n// int sat_pairwise_cardinality_network_add_constraint_pairwise( S& solver, std::vector<int>& vvars )\n// {\n//   int nvars = vvars.size();\n//   sat_pairwise_cardinality_network_add_constraint_range( solver, vvars, 0, nvars - 1, &nvars );\n//   return nvars;\n// }\n\n// }\n\n// template<class S>\n// int sat_pairwise_cardinality_network2( S& solver, unsigned log_n, int sid, std::vector<int>* ovars = nullptr )\n// {\n//   auto nvars = 1u << log_n;\n//   const auto nvars_alloc = nvars + 2u * (nvars * log_n * ( log_n - 1 ) / 4 + nvars - 1);\n\n//   std::vector<int> vvars( nvars );\n//   boost::iota( vvars, sid );\n\n//   std::cout << \"[i] original vvars: \" << any_join( vvars, \" \" ) << std::endl;\n\n//   const auto nvars_real = detail::sat_pairwise_cardinality_network_add_constraint_pairwise( solver, vvars );\n//   assert( nvars_real == nvars_alloc );\n\n//   if ( ovars )\n//   {\n//     *ovars = vvars;\n//   }\n\n//   return sid + nvars_alloc;\n// }\n\n/******************************************************************************\n * PW implementation based on paper                                           *\n ******************************************************************************/\n\nnamespace detail\n{\n\ntemplate<class S>\nvoid sat_pairwise_comparator( S& solver, int a, int b, int c, int d)\n{\n  //logic_or( solver, a, b, c );\n  //logic_and( solver, a, b, d );\n\n  add_clause( solver )( {c, -a} );\n  add_clause( solver )( {c, -b} );\n  add_clause( solver )( {d, -a, -b} );\n}\n\ntemplate<class S>\nvoid sat_pairwise_split( S& solver, const std::vector<int>& as, const std::vector<int>& bs, const std::vector<int>& cs )\n{\n  assert( bs.size() == cs.size() );\n  assert( bs.size() << 1u == as.size() );\n\n  for ( auto i = 0u; i < bs.size(); ++i )\n  {\n    sat_pairwise_comparator( solver, as[2 * i], as[2 * i + 1], bs[i], cs[i] );\n  }\n}\n\ntemplate<class S>\nint sat_pairwise_merge( S& solver, const std::vector<int>& as, const std::vector<int>& bs, const std::vector<int>& cs, int sid )\n{\n  const auto n = as.size();\n\n  if ( n == 1u )\n  {\n    equals( solver, as[0], cs[0] );\n    equals( solver, bs[0], cs[1] );\n    return sid;\n  }\n\n  /* fill ds and es */\n  std::vector<int> ds( n ), es( n );\n\n  ds[0u] = cs[0];\n  for ( auto i = 1u; i < n; ++i ) { ds[i] = sid++; }\n\n  for ( auto i = 0u; i < n - 1; ++i ) { es[i] = sid++; }\n  es[n - 1] = cs[2 * n - 1];\n\n  /* fill a0, b0, a1, b1 */\n  std::vector<int> a0( n / 2 ), b0( n / 2 ), a1( n / 2 ), b1( n / 2 );\n  for ( auto i = 0u; i < n / 2; ++i )\n  {\n    a0[i] = as[2 * i];\n    a1[i] = as[2 * i + 1];\n    b0[i] = bs[2 * i];\n    b1[i] = bs[2 * i + 1];\n  }\n\n  sid = sat_pairwise_merge( solver, a0, b0, ds, sid );\n  sid = sat_pairwise_merge( solver, a1, b1, es, sid );\n\n  for ( auto i = 0u; i < n - 1; ++i )\n  {\n    sat_pairwise_comparator( solver, es[i], ds[i + 1], cs[2 * i + 1], cs[2 * i + 2] );\n  }\n\n  /* sort outputs */\n  for ( auto i = 0u; i < cs.size() - 1; ++i )\n  {\n    add_clause( solver )( {cs[i], -cs[i + 1]} );\n  }\n\n  return sid;\n}\n\ntemplate<class S>\nint sat_pairwise_sort( S& solver, const std::vector<int>& as, const std::vector<int>& ds, int sid )\n{\n  const auto n = as.size();\n\n  if ( n == 1u )\n  {\n    equals( solver, as[0], ds[0] );\n    return sid;\n  }\n\n  std::vector<int> bs( n / 2 ), cs( n / 2 ), bbs( n / 2), ccs( n / 2 );\n\n  boost::iota( bs, sid ); sid += n / 2;\n  boost::iota( cs, sid ); sid += n / 2;\n  boost::iota( bbs, sid ); sid += n / 2;\n  boost::iota( ccs, sid ); sid += n / 2;\n\n  sat_pairwise_split( solver, as, bs, cs );\n  sid = sat_pairwise_sort( solver, bs, bbs, sid );\n  sid = sat_pairwise_sort( solver, cs, ccs, sid );\n  return sat_pairwise_merge( solver, bbs, ccs, ds, sid );\n}\n\n}\n\ntemplate<class S>\nint sat_pairwise_cardinality_network( S& solver, const std::vector<int>& ivars, int sid, std::vector<int>* ovars = nullptr )\n{\n  std::vector<int> ds( ivars.size() );\n  boost::iota( ds, sid );\n  sid += ivars.size();\n\n  if ( ovars )\n  {\n    *ovars = ds;\n  }\n\n  return detail::sat_pairwise_sort( solver, ivars, ds, sid );\n}\n\ntemplate<class S>\nint sat_pairwise_cardinality_network( S& solver, unsigned log_n, int sid, std::vector<int>* ovars = nullptr )\n{\n  const auto n = 1 << log_n;\n  std::vector<int> as( n );\n\n  boost::iota( as, sid ); sid += n;\n\n  return sat_pairwise_cardinality_network( solver, as, sid, ovars );\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": "55211a107c30ac34154026dbd892a454e23a130a", "size": 16043, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/classical/sat/operations/cardinality.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/sat/operations/cardinality.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/sat/operations/cardinality.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": 29.2222222222, "max_line_length": 208, "alphanum_fraction": 0.5377423175, "num_tokens": 5222, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5428632831725051, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.3237816559741215}}
{"text": "/*  \n * Copyright (c) 2009 Carnegie Mellon University. \n *     All rights reserved.\n *\n *  Licensed under the Apache License, Version 2.0 (the \"License\");\n *  you may not use this file except in compliance with the License.\n *  You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n *  Unless required by applicable law or agreed to in writing,\n *  software distributed under the License is distributed on an \"AS\n *  IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either\n *  express or implied.  See the License for the specific language\n *  governing permissions and limitations under the License.\n *\n * For more about this software visit:\n *\n *      http://www.graphlab.ml.cmu.edu\n *\n */\n\n\n/**\n *\n * \\brief This application performs MAP inference on Markov Nets \n * provided in standard UAI file format via Dual-Decomposition. \n *\n *\n *  \\author Dhruv Batra\n */\n\n\n#ifndef __DD_GRLAB_HPP__\n#define __DD_GRLAB_HPP__\n\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\n\n#include <Eigen/Dense>\n#include \"eigen_serialization.hpp\"\n\n\n\n#include <graphlab.hpp>\n#include <graphlab/macros_def.hpp>\n\n\nusing namespace std;\n\n\n/**\n * \\brief Eigen library vectors are used to store the potentials (log-space)\n */\ntypedef Eigen::VectorXd factor_type;\ntypedef Eigen::VectorXd vec;\ntypedef Eigen::MatrixXd mat;\n\n\n/**\n * \\brief The convergence threshold for each message.  Smaller values\n * imply tighter convergence but slower execution.\n *\n */\ndouble TOLERANCE = 0.01;\n\n\n/////////////////////////////////////////////////////////////////////////\n// Edge and Vertex data and Graph Type\n/**\n * \\brief There is a vertex for each factor in the graph AND each singleton\n */\nstruct vertex_data \n{\n    int nvars;              // Number of variables in this factor.\n    int degree;             // Degree of this factor (same as nvars for higher-order factors).\n    vector<int> cards;      // Cardinality of each variable.\n    vector<int> neighbors;  // Vertex ids of the neighbors.    \n    vec potentials;         // Potentials for each configuration of the factor.\n    \n    int best_configuration; // Index of the best configuration at a subgradient step.\n                            // TODO: Maybe replace best_configuration by beliefs for the high order variables?\n                            // In which case, beliefs would be vector<vec> beliefs.\n    vec beliefs;            // Posterior values for the configurations after averaging (projected DD, unary variables only).\n    \n    vertex_data(): nvars(0) {}\n    \n    void load(graphlab::iarchive& arc) \n    {\n      arc >> nvars >> degree >> cards >> neighbors >> potentials >> best_configuration >> beliefs;\n    }\n    void save(graphlab::oarchive& arc) const \n    {\n      arc << nvars << degree << cards << neighbors << potentials << best_configuration << beliefs;\n    }\n}; // end of vertex_data\n\n\n/**\n * \\brief There is an edge connecting each factor to each singleton\n * in its scope.\n */\nstruct edge_data \n{\n    int varid; // Do we need this? (afm)\n    int card; // Do we need this? (afm)\n    vec potentials; // TODO: Unary potentials distributed evenly through the edges (i.e. unary potentials divided by degree).\n    \n    vec multiplier_messages; // Dual variables, i.e. Lagrangian multipliers.\n    vec local_messages;      // Local MAP variables (for projected DD).\n    \n    edge_data(): varid(0), card(0) {}\n    \n    void load(graphlab::iarchive& arc) {\n      arc >> varid >> card >> potentials >> multiplier_messages >> local_messages;\n    }\n    void save(graphlab::oarchive& arc) const {\n      arc << varid << card << potentials << multiplier_messages << local_messages;\n    }\n};\n\n\n/**\n * The graph type\n */\ntypedef graphlab::distributed_graph<vertex_data, edge_data> graph_type;\n\n\n/** \n * \\brief The Dual Decomposition Vertex Program.\n */\nstruct dd_vertex_program : \n  public graphlab::ivertex_program< graph_type, factor_type,\n                                    graphlab::messages::sum_priority >,\n  public graphlab::IS_POD_TYPE {\n  \n  /////////////////////////////////////////////////////////////////////////\n  // Find the configuration index of a factor given the array of states.\n  /////////////////////////////////////////////////////////////////////////\n  int get_configuration_index(const graph_type::vertex_type& vertex,\n                              const std::vector<int>& states) const {\n    const vertex_data& vdata = vertex.data();\n    int index = states[0];\n    for (size_t i = 1; i < states.size(); ++i) {\n      index *= vdata.cards[i];\n      index += states[i];\n    }\n    return index;\n  }\n\n  /////////////////////////////////////////////////////////////////////////\n  // Find the array of states corresponding to a factor configuration index.\n  /////////////////////////////////////////////////////////////////////////\n  void get_configuration_states(const graph_type::vertex_type& vertex,\n                                int index, std::vector<int>* states) const {\n    const vertex_data& vdata = vertex.data();\n    int tmp = 1;\n    for (size_t i = 1; i < states->size(); ++i) {\n      tmp *= vdata.cards[i];\n    }\n    (*states)[0] = index / tmp;\n    for (size_t i = 1; i < states->size(); ++i) {\n      index = index % tmp;\n      tmp /= vdata.cards[i];\n      (*states)[i] = index / tmp;\n    }\n  }\n  \n  /**\n   * \\brief Given an edge and a vertex return the other vertex along\n   * that edge. \n   */\n  inline vertex_type get_other_vertex(edge_type& edge, \n                                      const vertex_type& vertex) const {\n    return vertex.id() == edge.source().id()? edge.target() : edge.source();\n  }; // end of other_vertex\n  \n  \n  virtual edge_dir_type gather_edges(icontext_type& context,\n                                     const vertex_type& vertex) const = 0;\n  virtual factor_type gather(icontext_type& context, const vertex_type& vertex, \n                             edge_type& edge) const = 0;\n  virtual void apply(icontext_type& context, vertex_type& vertex, \n                     const factor_type& total) = 0;\n  virtual edge_dir_type scatter_edges(icontext_type& context,\n                                      const vertex_type& vertex) const = 0; \n  virtual void scatter(icontext_type& context, const vertex_type& vertex, \n                       edge_type& edge) const = 0;\n}; // end of class bp_vertex_program\n\n\n\n////////////////////////////////////////////////////////////////////////////////\n// This class implements the \"symmetric\" version of dual decomposition described\n// in:\n// D. Sontag, A. Globerson, T. Jaakkola.\n// Introduction to Dual Decomposition for Inference.\n// Optimization for Machine Learning, editors S. Sra, S. Nowozin, and S. J.\n// Wright: MIT Press, 2011\n////////////////////////////////////////////////////////////////////////////////\n\nstruct dd_vertex_program_symmetric : public dd_vertex_program {\n  /**\n   * \\brief Since the MRF is undirected we will use all edges for gather and\n   * scatter\n   */\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 The gather function takes a vertex and an edge as inputs and outputs \n   a vector of numeric values. Vectors of numeric values will later be summed \n   over all edges incident in this vertex. So, if the vertex is a unary factor, \n   we can just return the vector of Lagrange multipliers stored in \"edge.messages\". \n   Otherwise (if vertex is a general factor), things are a little more tricky. \n   Suppose the factor is linked to K variables, with cardinalities C_1, ..., C_K. \n   Suppose this edge is with respect to the k-th variable. Then, we return a \n   vector of size C_1 + ... + C_K which is zero everywhere except in the \n   k-th slot, where the Lagrange multipliers in \"edge.messages\" will be copied \n   to. This way, when the \"gather sum\" takes place, and since all these slots \n   are disjoint, we will just get the Lagrange multipliers of all the variables.    \n   */\n  factor_type gather(icontext_type& context, const vertex_type& vertex, \n                     edge_type& edge) const {\n    cout << \"gather begin\" << endl;\n    const vertex_type other_vertex = get_other_vertex(edge, vertex);\n    const vertex_data& vdata = vertex.data();\n    edge_data& edata = edge.data();\n\n    if (vdata.nvars == 1) {\n      // Unary factor.\n      cout << \"This unary factor has \" << vertex.num_in_edges() << \n        \" in edges and \" << vertex.num_out_edges() << \" out edges\" << endl;\n      return edata.multiplier_messages;\n    } else {\n      // General factor.\n      factor_type messages;\n      messages.resize(vdata.potentials.size());\n      int offset = 0;\n      int index_neighbor = -1;\n      for (int k = 0; k < vdata.nvars; ++k) {\n        int vertex_id = vdata.neighbors[k];\n        if (vertex_id == other_vertex.id()) {\n          index_neighbor = k;\n          break;\n        }\n        offset += vdata.cards[k];\n      }\n      CHECK_GE(index_neighbor, 0);\n      for (int state = 0; state < vdata.cards[index_neighbor]; ++state) {\n        messages[offset + state] = -edata.multiplier_messages[state];\n      }\n      return messages;\n    }\n    cout << \"gather end\" << endl;\n  }; // end of gather function\n\n  /**\n   * \\brief The apply function takes a vertex and a vector of numeric values \n   (a total) as input. For unary vertices, this will be the sum of Lagrange \n   multipliers, and we just need to sum that to the vertex potential and compute \n   the argmax. For general factors, the vector of numeric values, as stated above, \n   will contain all the Lagrange multipliers of the neighboring variables. \n   So we need to loop through all possible factor configurations, get the \n   sequence of states of each configuration, fetch the Lagrange multipliers for \n   those states, and add them to the factor potential. Then we compute the argmax. \n   */\n  void apply(icontext_type& context, vertex_type& vertex, \n             const factor_type& total) {\n    vertex_data& vdata = vertex.data();\n    cout << \"begin apply\" << endl;\n    if (vdata.nvars == 1) {\n      // Unary factor.\n      ASSERT_EQ(vdata.potentials.size(), total.size());\n      vec belief = vdata.potentials + total;\n      // Save the best configuration for this vertex.\n      belief.maxCoeff(&vdata.best_configuration);\n      cout << \"vdata.best_configuration = \" << vdata.best_configuration << endl;\n    } else {\n      // General factor.\n      vec belief = vdata.potentials;\n      int num_configurations = vdata.potentials.size();\n      for (int index_configuration = 0;\n           index_configuration < num_configurations;\n           ++index_configuration) {\n        vector<int> states(vdata.nvars, -1);\n        // This could be made more efficient by defining an iterator over factor\n        // configurations.\n        get_configuration_states(vertex, index_configuration, &states);\n        int offset = 0;\n        for (int k = 0; k < vdata.nvars; ++k) {\n          belief[index_configuration] += total[offset + states[k]];\n          offset += vdata.cards[k];\n        }\n      }\n      // Save the best configuration for this factor.\n      belief.maxCoeff(&vdata.best_configuration);\n    }\n    cout << \"end apply\" << endl;\n  }; // end of apply\n\n  /**\n   * \\brief Since the MRF is undirected we will use all edges for gather and\n   * scatter\n   */\n  edge_dir_type scatter_edges(icontext_type& context,\n                              const vertex_type& vertex) const { \n    return graphlab::ALL_EDGES; \n  }; // end of scatter edges\n\n  /**\n   * \\brief The scatter function takes a vertex and an edge as input. \n   We just need to update the messages (Lagrange multipliers) by looking at the \n   saved argmaxes.\n   */\n  void scatter(icontext_type& context, const vertex_type& vertex, \n               edge_type& edge) const {  \n    const vertex_type other_vertex = get_other_vertex(edge, vertex);\n    const vertex_type *unary_vertex;\n    const vertex_type *factor_vertex;\n    cout << \"begin scatter\" << endl;\n    if (vertex.data().nvars == 1) {\n      // Unary factor.\n      unary_vertex = &vertex;\n      factor_vertex = &other_vertex;\n    } else {\n      // General factor.\n      unary_vertex = &other_vertex;\n      factor_vertex = &vertex;\n    }\n    const vertex_data& vdata = unary_vertex->data();\n    const vertex_data& other_vdata = factor_vertex->data();\n    edge_data& edata = edge.data();\n    double stepsize = 1.0; // TODO: Make this decay over iteration number.\n\n    CHECK_GE(vdata.best_configuration, 0);\n    CHECK_LT(vdata.best_configuration, vdata.cards[0]);    \n    edata.multiplier_messages[vdata.best_configuration] += stepsize;\n    vector<int> states(other_vdata.nvars, -1);\n    get_configuration_states(*factor_vertex, other_vdata.best_configuration, &states);\n    int offset = 0;\n    int index_neighbor = -1;\n    for (int k = 0; k < other_vdata.nvars; ++k) {\n      int vertex_id = other_vdata.neighbors[k];\n      if (vertex_id == unary_vertex->id()) {\n        index_neighbor = k;\n        break;\n      }\n      offset += other_vdata.cards[k];\n    }\n    CHECK_GE(index_neighbor, 0);\n    CHECK_GE(states[index_neighbor], 0);\n    CHECK_LT(states[index_neighbor], other_vdata.cards[index_neighbor]);\n    CHECK_EQ(other_vdata.cards[index_neighbor], vdata.cards[0]);\n    edata.multiplier_messages[states[index_neighbor]] -= stepsize;\n    cout << \"end scatter\" << endl;\n  }; // end of scatter\n}; // end of class bp_vertex_program_symmetric\n\n\n\n////////////////////////////////////////////////////////////////////////////////\n// This class implements the \"projected\" version of dual decomposition described\n// in:\n// Komodakis, N., Paragios, N., and Tziritas, G. (2007).\n// MRF optimization via dual decomposition: Message-passing revisited.\n// In Proc. of International Conference on Computer Vision.\n// \n// The formulation used is the one in Algorithm 1 of:\n//\n// André F. T. Martins, Mário A. T. Figueiredo, Pedro M. Q. Aguiar,\n// Noah A. Smith, and Eric P. Xing.\n// \"An Augmented Lagrangian Approach to Constrained MAP Inference.\"\n// International Conference on Machine Learning (ICML), 2011.\n////////////////////////////////////////////////////////////////////////////////\n\nstruct dd_vertex_program_projected : public dd_vertex_program {\n  /**\n   * \\brief Since the MRF is undirected we will use all edges for gather and\n   * scatter\n   */\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 The gather function takes a vertex and an edge as inputs and outputs \n   a vector of numeric values. Vectors of numeric values will later be summed \n   over all edges incident in this vertex. \n   If the vertex is a unary factor, compute the sum of all the local MAP variables,\n   which in the \"apply\" function will serve to compute the global MAP. \n   Otherwise (if vertex is a general factor), things are a little more tricky. \n   Suppose the factor is linked to K variables, with cardinalities C_1, ..., C_K. \n   Suppose this edge is with respect to the k-th variable. Then, we return a \n   vector of size C_1 + ... + C_K which is zero everywhere except in the \n   k-th slot, where the Lagrange multipliers in \"edge.messages\" will be copied \n   to. This way, when the \"gather sum\" takes place, and since all these slots \n   are disjoint, we will just get the Lagrange multipliers of all the variables.    \n   */\n  factor_type gather(icontext_type& context, const vertex_type& vertex, \n                     edge_type& edge) const {\n    cout << \"gather begin\" << endl;\n    const vertex_type other_vertex = get_other_vertex(edge, vertex);\n    const vertex_data& vdata = vertex.data();\n    edge_data& edata = edge.data();\n\n    if (vdata.nvars == 1) {\n      // Unary factor.\n      cout << \"This unary factor has \" << vertex.num_in_edges() << \n        \" in edges and \" << vertex.num_out_edges() << \" out edges\" << endl;\n      factor_type messages = edata.local_messages;\n      return messages; \n    } else {\n      // General factor.\n      factor_type messages;\n      messages.resize(vdata.potentials.size());\n      int offset = 0;\n      int index_neighbor = -1;\n      for (int k = 0; k < vdata.nvars; ++k) {\n        int vertex_id = vdata.neighbors[k];\n        if (vertex_id == other_vertex.id()) {\n          index_neighbor = k;\n          break;\n        }\n        offset += vdata.cards[k];\n      }\n      CHECK_GE(index_neighbor, 0);\n      //const vec &unary_potential = other_vertex.data().potential;\n      //int degree = other_vertex.data().degree;\n\n      for (int state = 0; state < vdata.cards[index_neighbor]; ++state) {\n        messages[offset + state] = edata.multiplier_messages[state];\n        // TODO: somehow set the \"edge potential\" to be the potential of the\n        // unary variable divided by the number of factors in which that \n        // variable appears.\n        messages[offset + state] += edata.potentials[state]; \n        //message[offset + state] += unary_potential[state] / static_cast<double>(degree);\n      }\n      return messages;\n    }\n    cout << \"gather end\" << endl;\n  }; // end of gather function\n\n  /**\n   * \\brief The apply function takes a vertex and a vector of numeric values \n   (a total) as input. \n   For a unary vertex, \"total\" will be the sum of local MAP vectors, and we \n   just need to divide by the vertex degree and save the result as global MAP.\n   For higher-order factors, \"total\" will contain all the Lagrange multipliers \n   of the neighboring variables. So we need to loop through all possible factor \n   configurations, get the sequence of states of each configuration, fetch the \n   Lagrange multipliers for those states, and add them to the factor potential. \n   Then we compute the argmax and save result to local MAP for each variable \n   connected to the factor. \n   */\n  void apply(icontext_type& context, vertex_type& vertex, \n             const factor_type& total) {\n    vertex_data& vdata = vertex.data();\n    cout << \"begin apply\" << endl;\n    if (vdata.nvars == 1) {\n      // Unary factor. Divide by vertex degree.\n      vdata.beliefs = total / static_cast<double>(vdata.degree);\n      return;\n    } else {\n      // General factor.\n      vec beliefs = vdata.potentials;\n      int num_configurations = vdata.potentials.size();\n      for (int index_configuration = 0;\n           index_configuration < num_configurations;\n           ++index_configuration) {\n        vector<int> states(vdata.nvars, -1);\n        // This could be made more efficient by defining an iterator over factor\n        // configurations.\n        get_configuration_states(vertex, index_configuration, &states);\n        int offset = 0;\n        for (int k = 0; k < vdata.nvars; ++k) {\n          beliefs[index_configuration] += total[offset + states[k]];\n          offset += vdata.cards[k];\n        }\n      }\n      // Save the best configuration for this factor.\n      beliefs.maxCoeff(&vdata.best_configuration);\n    }\n    cout << \"end apply\" << endl;\n  }; // end of apply\n\n  /**\n   * \\brief Since the MRF is undirected we will use all edges for gather and\n   * scatter\n   */\n  edge_dir_type scatter_edges(icontext_type& context,\n                              const vertex_type& vertex) const { \n    return graphlab::ALL_EDGES; \n  }; // end of scatter edges\n\n  /**\n   * \\brief The scatter function takes a vertex and an edge as input. \n   (1) If the vertex is a unary factor, we update the messages (Lagrange multipliers)\n   by subtracting the global MAP by the local MAP.\n   (2) If the vertex is a higher order factor, this function will take the best\n   configuration (obtained at the apply function) and save the local MAP \n   at the corresponding edge.\n   */\n  void scatter(icontext_type& context, const vertex_type& vertex, \n               edge_type& edge) const {  \n    const vertex_data& vdata = vertex.data();\n    edge_data& edata = edge.data();\n    cout << \"begin scatter\" << endl;\n    if (vdata.nvars == 1) {\n      // Unary factor. Update the messages (Lagrange multipliers).      \n      double stepsize = 1.0; // TODO: Make this decay over iteration number.\n      edata.multiplier_messages += (vdata.beliefs - edata.local_messages) * stepsize;\n    } else {\n      // General factor. Update the local MAPs.\n      const vertex_type &unary_vertex = get_other_vertex(edge, vertex);\n      vector<int> states(vdata.nvars, -1);\n      get_configuration_states(vertex, vdata.best_configuration, &states);\n      int offset = 0;\n      int index_neighbor = -1;\n      for (int k = 0; k < vdata.nvars; ++k) {\n        int vertex_id = vdata.neighbors[k];\n        if (vertex_id == unary_vertex.id()) {\n          index_neighbor = k;\n          break;\n        }\n        offset += vdata.cards[k];\n      }\n      CHECK_GE(index_neighbor, 0);\n      CHECK_GE(states[index_neighbor], 0);\n      CHECK_LT(states[index_neighbor], vdata.cards[index_neighbor]);\n      CHECK_EQ(vdata.cards[index_neighbor], unary_vertex.data().cards[0]);\n      edata.local_messages.setZero();\n      edata.local_messages[states[index_neighbor]] += 1.0;\n    }\n    cout << \"end scatter\" << endl;\n  }; // end of scatter\n}; // end of class dd_vertex_program_projected\n\n\n#endif\n", "meta": {"hexsha": "228cd57e235018e3baa028e2336e230f3ef19e64", "size": 21413, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "toolkits/graphical_models/dd_grlab.hpp", "max_stars_repo_name": "madi171/madi171-graphlab", "max_stars_repo_head_hexsha": "806dde3ac848adcebb442bbb156b5ba50f962ddd", "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": "toolkits/graphical_models/dd_grlab.hpp", "max_issues_repo_name": "madi171/madi171-graphlab", "max_issues_repo_head_hexsha": "806dde3ac848adcebb442bbb156b5ba50f962ddd", "max_issues_repo_licenses": ["ECL-2.0", "Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "toolkits/graphical_models/dd_grlab.hpp", "max_forks_repo_name": "madi171/madi171-graphlab", "max_forks_repo_head_hexsha": "806dde3ac848adcebb442bbb156b5ba50f962ddd", "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": 39.0748175182, "max_line_length": 125, "alphanum_fraction": 0.632092654, "num_tokens": 4953, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.679178699175393, "lm_q2_score": 0.476579651063676, "lm_q1q2_score": 0.32368274746289016}}
{"text": "/*\n * Copyright 2020 Ria Sonecha, Massachusetts Institute of Technology in Cambridge, MA, USA\n * Copyright 2020 Giuseppe Silano, University of Sannio in Benevento, Italy\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n#include <thread>\n#include <chrono>\n\n#include \"rotors_gazebo/Quaternion.h\"\n#include \"rotors_gazebo/transform_datatypes.h\"\n#include \"rotors_gazebo/parameters_ros.h\"\n#include <nav_msgs/Odometry.h>\n#include \"rotors_gazebo/Matrix3x3.h\"\n#include <ros/console.h>\n#include <time.h>\n\n#include <Eigen/Core>\n#include <mav_msgs/conversions.h>\n#include <mav_msgs/default_topics.h>\n#include <ros/ros.h>\n#include <std_srvs/Empty.h>\n#include <trajectory_msgs/MultiDOFJointTrajectory.h>\n#include <math.h>\n#include \"rotors_gazebo/spline_trajectory_generator.h\"\n\n#define DELTA_1   0.5\n#define ALPHA_1   2\n#define ALPHA_2   20\n#define ALPHA_3   8\n#define ALPHA_4   12\n#define ALPHA_5   3\n#define BETA_1    30\n#define BETA_2    14\n#define BETA_3    16\n#define BETA_4    2\n#define GAMMA_1   12\n#define GAMMA_2   6\n#define SAMPLING_TIME  10e-3       /* SAMPLING CONTROLLER TIME [s] - 100Hz */\n#define START_SIMULATION_TIME 3   /* TIME GAZEBO NEEDS TO INITIALIZE THE ENVIRONMENT */\n\nnamespace rotors_gazebo {\n\n  SplineTrajectoryGenerator::SplineTrajectoryGenerator(){\n\n    // Parameters initializion\n    a0_.setZero(); a1_.setZero(); a2_.setZero(); a3_.setZero(); a4_.setZero(); a5_.setZero();\n    b0_.setZero(); b1_.setZero(); b2_.setZero(); b3_.setZero(); b4_.setZero();\n    c0_.setZero(); c1_.setZero(); c2_.setZero(); c3_.setZero();\n\n    g0_.setZero(); g1_.setZero(); g2_.setZero(); g3_.setZero(); g4_.setZero(); g5_.setZero();\n    h0_.setZero(); h1_.setZero(); h2_.setZero(); h3_.setZero(); h4_.setZero();\n    i0_.setZero(); i1_.setZero(); i2_.setZero(); i3_.setZero();\n\n  }\n\n  SplineTrajectoryGenerator::~SplineTrajectoryGenerator(){}\n\n  void SplineTrajectoryGenerator::TrajectoryCallback(mav_msgs::EigenDroneState* odometry, double* time_final, double* time_init) {\n    assert(odometry);\n    assert(time_final);\n    assert(time_init);\n\n    double time_spline;\n    time_spline = *time_final - *time_init;\n\n    if (enable_parameter_computation_){\n      ComputeSplineParameters(&time_final_);\n      enable_parameter_computation_ = false;\n\n      ROS_DEBUG(\"Publishing time_final_: %f\", time_final_);\n    }\n\n    ROS_DEBUG(\"Publishing time_spline: %f\", time_spline);\n\n    // Desired Position\n    double x_component, y_component, z_component;\n    x_component = a5_.x() * pow(time_spline, 5) + a4_.x() * pow(time_spline, 4) + a3_.x() * pow(time_spline, 3) + a2_.x() * pow(time_spline, 2)\n                  + a1_.x() * time_spline + a0_.x();\n    y_component = a5_.y() * pow(time_spline, 5) + a4_.y() * pow(time_spline, 4) + a3_.y() * pow(time_spline, 3) + a2_.y() * pow(time_spline, 2)\n                  + a1_.y() * time_spline + a0_.y();\n    z_component = a5_.z() * pow(time_spline, 5) + a4_.z() * pow(time_spline, 4) + a3_.z() * pow(time_spline, 3) + a2_.z() * pow(time_spline, 2)\n                  + a1_.z() * time_spline + a0_.z();\n\n    ROS_DEBUG(\"Publishing position spline parameters along x-axis: [%f, %f, %f, %f, %f, %f].\", a0_.x(), a1_.x(), a2_.x(), a3_.x(), a4_.x(), a5_.x());\n    ROS_DEBUG(\"Publishing position spline parameters along y-axis: [%f, %f, %f, %f, %f, %f].\", a0_.y(), a1_.y(), a2_.y(), a3_.y(), a4_.y(), a5_.y());\n    ROS_DEBUG(\"Publishing position spline parameters along z-axis: [%f, %f, %f, %f, %f, %f].\", a0_.z(), a1_.z(), a2_.z(), a3_.z(), a4_.z(), a5_.z());\n\n    odometry->position_W = Eigen::Vector3f(x_component, y_component, z_component);\n\n    ROS_DEBUG(\"Publishing position waypoint: [%f, %f, %f].\", x_component, y_component, z_component);\n\n    // Desired Linear Velocity\n    x_component = b4_.x() * pow(time_spline, 4) + b3_.x() * pow(time_spline, 3) + b2_.x() * pow(time_spline, 2) + b1_.x() * time_spline\n                  + b0_.x();\n    y_component = b4_.y() * pow(time_spline, 4) + b3_.y() * pow(time_spline, 3) + b2_.y() * pow(time_spline, 2) + b1_.y() * time_spline\n                  + b0_.y();\n    z_component = b4_.z() * pow(time_spline, 4) + b3_.z() * pow(time_spline, 3) + b2_.z() * pow(time_spline, 2) + b1_.z() * time_spline\n                  + b0_.z();\n\n    ROS_DEBUG(\"Publishing velocity spline parameters along x-axis: [%f, %f, %f, %f, %f].\", b0_.x(), b1_.x(), b2_.x(), b3_.x(), b4_.x());\n    ROS_DEBUG(\"Publishing velocity spline parameters along y-axis: [%f, %f, %f, %f, %f].\", b0_.y(), b1_.y(), b2_.y(), b3_.y(), b4_.y());\n    ROS_DEBUG(\"Publishing velocity spline parameters along z-axis: [%f, %f, %f, %f, %f].\", b0_.z(), b1_.z(), b2_.z(), b3_.z(), b4_.z());\n\n    odometry->velocity = Eigen::Vector3f(x_component, y_component, z_component);\n\n    ROS_DEBUG(\"Publishing velocity waypoint: [%f, %f, %f].\", x_component, y_component, z_component);\n\n    // Desired Acceleration\n    x_component = c3_.x() * pow(time_spline, 3) + c2_.x() * pow(time_spline, 2) + c1_.x() * time_spline + c0_.x();\n    y_component = c3_.y() * pow(time_spline, 3) + c2_.y() * pow(time_spline, 2) + c1_.y() * time_spline + c0_.y();\n    z_component = c3_.z() * pow(time_spline, 3) + c2_.z() * pow(time_spline, 2) + c1_.z() * time_spline + c0_.z();\n\n    ROS_DEBUG(\"Publishing acceleration spline parameters along y-axis: [%f, %f, %f, %f].\", c0_.y(), c1_.y(), c2_.y(), c3_.y());\n    ROS_DEBUG(\"Publishing acceleration spline parameters along x-axis: [%f, %f, %f, %f].\", c0_.x(), c1_.x(), c2_.x(), c3_.x());\n    ROS_DEBUG(\"Publishing acceleration spline parameters along z-axis: [%f, %f, %f, %f].\", c0_.z(), c1_.z(), c2_.z(), c3_.z());\n\n    odometry->acceleration = Eigen::Vector3f(x_component, y_component, z_component);\n\n    ROS_DEBUG(\"Publishing acceleration waypoint: [%f, %f, %f].\", x_component, y_component, z_component);\n\n    // Desired Attitute\n    rollDesRad_ = g5_.x() * pow(time_spline, 5) + g4_.x() * pow(time_spline, 4) + g3_.x() * pow(time_spline, 3) + g2_.x() * pow(time_spline, 2)\n                + g1_.x() * time_spline + g0_.x();\n    pitchDesRad_ = g5_.y() * pow(time_spline, 5) + g4_.y() * pow(time_spline, 4) + g3_.y() * pow(time_spline, 3) + g2_.y() * pow(time_spline, 2)\n                + g1_.y() * time_spline + g0_.y();\n    yawDesRad_ = g5_.z() * pow(time_spline, 5) + g4_.z() * pow(time_spline, 4) + g3_.z() * pow(time_spline, 3) + g2_.z() * pow(time_spline, 2)\n                + g1_.z() * time_spline + g0_.z();\n\n    ROS_DEBUG(\"Publishing orientation spline parameters along x-axis: [%f, %f, %f, %f, %f, %f].\", g0_.x(), g1_.x(), g2_.x(), g3_.x(), g4_.x(), g5_.x());\n    ROS_DEBUG(\"Publishing orientation spline parameters along y-axis: [%f, %f, %f, %f, %f, %f].\", g0_.y(), g1_.y(), g2_.y(), g3_.y(), g4_.y(), g5_.y());\n    ROS_DEBUG(\"Publishing orientation spline parameters along z-axis: [%f, %f, %f, %f, %f, %f].\", g0_.z(), g1_.z(), g2_.z(), g3_.z(), g4_.z(), g5_.z());\n\n    // Converts radians in quaternions\n    double x, y, z, w;\n    Euler2QuaternionCommandTrajectory(&x, &y, &z, &w);\n    odometry->orientation_W_B = Eigen::Quaterniond(w, x, y, z);\n\n    ROS_DEBUG(\"Publishing attitude waypoint: [%f, %f, %f].\", rollDesRad_, pitchDesRad_, yawDesRad_);\n\n    // Desired Angular Velocity\n    double roll_component, pitch_component, yaw_component;\n    roll_component = h4_.x() * pow(time_spline, 4) + h3_.x() * pow(time_spline, 3) + h2_.x() * pow(time_spline, 2) + h1_.x() * time_spline + h0_.x();\n    pitch_component = h4_.y() * pow(time_spline, 4) + h3_.y() * pow(time_spline, 3) + h2_.y() * pow(time_spline, 2) + h1_.y() * time_spline + h0_.y();\n    yaw_component = h4_.z() * pow(time_spline, 4) + h3_.z() * pow(time_spline, 3) + h2_.z() * pow(time_spline, 2) + h1_.z() * time_spline + h0_.z();\n\n    ROS_DEBUG(\"Publishing angular velocity waypoint: [%f, %f, %f].\", roll_component, pitch_component, yaw_component);\n\n    // The angular rates are rotated from the inertial to the body frame\n    // https://home.aero.polimi.it/trainelli/downloads/Bottasso_ThreeDimensionalRotations.pdf, eqs. 1.206 and 1.208\n    double roll_component_B, pitch_component_B, yaw_component_B;\n    roll_component_B = roll_component - sin(pitchDesRad_) * yaw_component;\n    pitch_component_B = cos(rollDesRad_) * pitch_component + sin(rollDesRad_) * cos(pitchDesRad_) * yaw_component;\n    yaw_component_B = -sin(rollDesRad_) * pitch_component + cos(rollDesRad_) * cos(pitchDesRad_) * yaw_component;\n\n    odometry->angular_velocity_B = Eigen::Vector3f(roll_component_B, pitch_component_B, yaw_component_B);\n\n    ROS_DEBUG(\"Publishing angular velocity waypoint in the body frame: [%f, %f, %f].\", roll_component_B, pitch_component_B, yaw_component_B);\n\n  }\n\n  void SplineTrajectoryGenerator::ComputeSplineParameters(double* time_spline){\n      assert(time_spline);\n\n      /*        POSITION       */\n      // Parameters used for the position and its derivatives. The coefficient\n      // refers to the x, y and z-avis\n      a0_ = position_initial_;\n\n      ROS_DEBUG(\"Publishing position initial: [%f, %f, %f].\", position_initial_[0], position_initial_[1], position_initial_[2]);\n      ROS_DEBUG(\"Content of the a0 coefficient: [%f, %f, %f].\", a0_[0], a0_[1], a0_[2]);\n\n      a1_ = velocity_initial_;\n\n      ROS_DEBUG(\"Publishing velocity initial: [%f, %f, %f].\", velocity_initial_[0], velocity_initial_[1], velocity_initial_[2]);\n      ROS_DEBUG(\"Content of the a1 coefficient: [%f, %f, %f].\", a1_[0], a1_[1], a1_[2]);\n\n      a2_.x() = acceleration_initial_.x() * DELTA_1;\n      a2_.y() = acceleration_initial_.y() * DELTA_1;\n      a2_.z() = acceleration_initial_.z() * DELTA_1;\n\n      ROS_DEBUG(\"Publishing acceleration initial: [%f, %f, %f].\", acceleration_initial_[0], acceleration_initial_[1], acceleration_initial_[2]);\n      ROS_DEBUG(\"Content of the a2 coefficient: [%f, %f, %f].\", a2_[0], a2_[1], a2_[2]);\n\n      a3_.x() = (1/(ALPHA_1*pow(*time_spline,3))) * (ALPHA_2 * (position_final_.x() - position_initial_.x()) -\n                (ALPHA_3 * velocity_final_.x() + ALPHA_4 * velocity_initial_.x()) * *time_spline -\n                (ALPHA_5 * acceleration_final_.x() - acceleration_initial_.x()) * pow(*time_spline, 2));\n\n      a3_.y() = (1/(ALPHA_1*pow(*time_spline,3))) * (ALPHA_2 * (position_final_.y() - position_initial_.y()) -\n                (ALPHA_3 * velocity_final_.y() + ALPHA_4 * velocity_initial_.y()) * *time_spline -\n                (ALPHA_5 * acceleration_final_.y() - acceleration_initial_.y()) * pow(*time_spline, 2));\n\n      a3_.z() = (1/(ALPHA_1*pow(*time_spline,3))) * (ALPHA_2 * (position_final_.z() - position_initial_.z()) -\n                (ALPHA_3 * velocity_final_.z() + ALPHA_4 * velocity_initial_.z()) * *time_spline -\n                (ALPHA_5 * acceleration_final_.z() - acceleration_initial_.z()) * pow(*time_spline, 2));\n\n      ROS_DEBUG(\"Content of the a3 coefficient: [%f, %f, %f].\", a3_[0], a3_[1], a3_[2]);\n\n      a4_.x() = (1/(ALPHA_1*pow(*time_spline,4))) * (BETA_1 * (position_initial_.x() - position_final_.x()) +\n                (BETA_2 * velocity_final_.x() + BETA_3 * velocity_initial_.x()) * *time_spline +\n                (BETA_3 * acceleration_final_.x() - BETA_4 * acceleration_initial_.x()) * pow(*time_spline, 2));\n\n      a4_.y() = (1/(ALPHA_1*pow(*time_spline,4))) * (BETA_1 * (position_initial_.y() - position_final_.y()) +\n                (BETA_2 * velocity_final_.y() + BETA_3 * velocity_initial_.y()) * *time_spline +\n                (BETA_3 * acceleration_final_.y() - BETA_4 * acceleration_initial_.y()) * pow(*time_spline, 2));\n\n      a4_.z() = (1/(ALPHA_1*pow(*time_spline,4))) * (BETA_1 * (position_initial_.z() - position_final_.z()) +\n                (BETA_2 * velocity_final_.z() + BETA_3 * velocity_initial_.z()) * *time_spline +\n                (BETA_3 * acceleration_final_.z() - BETA_4 * acceleration_initial_.z()) * pow(*time_spline, 2));\n\n      ROS_DEBUG(\"Content of the a4 coefficient: [%f, %f, %f].\", a4_[0], a4_[1], a4_[2]);\n\n      a5_.x() = (1/(ALPHA_1*pow(*time_spline,5))) * (GAMMA_1 * (position_final_.x() - position_initial_.x()) -\n                GAMMA_2 * (velocity_final_.x() + velocity_initial_.x()) * *time_spline -\n                (acceleration_final_.x() - acceleration_initial_.x()) * pow(*time_spline, 2));\n\n      a5_.y() = (1/(ALPHA_1*pow(*time_spline,5))) * (GAMMA_1 * (position_final_.y() - position_initial_.y()) -\n                GAMMA_2 * (velocity_final_.y() + velocity_initial_.y()) * *time_spline -\n                (acceleration_final_.y() - acceleration_initial_.y()) * pow(*time_spline, 2));\n\n      a5_.z() = (1/(ALPHA_1*pow(*time_spline,5))) * (GAMMA_1 * (position_final_.z() - position_initial_.z()) -\n                GAMMA_2 * (velocity_final_.z() + velocity_initial_.z()) * *time_spline -\n                (acceleration_final_.z() - acceleration_initial_.z()) * pow(*time_spline, 2));\n\n      ROS_DEBUG(\"Content of the a5 coefficient: [%f, %f, %f].\", a5_[0], a5_[1], a5_[2]);\n\n      // The coefficients are used for having the velocity reference trajectory. The polynomial is computed\n      // derivating the a one. In other words,\n      // a5 * x^5 + a4 * x^4 + a3 * x^3 + a2 * x^2 + a1 * x + a0\n      // 5 * a5 * x^4 + 4 * a4 * x^3 + 3 * a3 * x^2 + 2 * a2 * x + a1\n      // b4 = 5 * a5 -- b3 = 4 * a4 -- b2 = 3 * a3 - b1 = 2 * a2 - b0 = a1\n      // and so on\n      b4_ = 5 * a5_;\n      b3_ = 4 * a4_;\n      b2_ = 3 * a3_;\n      b1_ = 2 * a2_;\n      b0_ = a1_;\n\n      ROS_DEBUG(\"Content of the b0 coefficient: [%f, %f, %f].\", b0_[0], b0_[1], b0_[2]);\n      ROS_DEBUG(\"Content of the b1 coefficient: [%f, %f, %f].\", b1_[0], b1_[1], b1_[2]);\n      ROS_DEBUG(\"Content of the b2 coefficient: [%f, %f, %f].\", b2_[0], b2_[1], b2_[2]);\n      ROS_DEBUG(\"Content of the b3 coefficient: [%f, %f, %f].\", b3_[0], b3_[1], b3_[2]);\n      ROS_DEBUG(\"Content of the b4 coefficient: [%f, %f, %f].\", b4_[0], b4_[1], b4_[2]);\n\n      // The coefficients are used for having the acceleration reference trajectory. The polynomial is computed\n      // derivating the b one. In other words,\n      // 4 * b4 * x^4 + 3 * b3 * x^3 + 2 * b2 * x^2 + b1 * x\n      // c3 = 4 * b4 -- c2 = 3 * b3 -- c1 = 2 * b2 - c0 = b1\n      c3_ = 4 * b4_;\n      c2_ = 3 * b3_;\n      c1_ = 2 * b2_;\n      c0_ = b1_;\n\n      ROS_DEBUG(\"Content of the c0 coefficient: [%f, %f, %f].\", c0_[0], c0_[1], c0_[2]);\n      ROS_DEBUG(\"Content of the c1 coefficient: [%f, %f, %f].\", c1_[0], c1_[1], c1_[2]);\n      ROS_DEBUG(\"Content of the c2 coefficient: [%f, %f, %f].\", c2_[0], c2_[1], c2_[2]);\n      ROS_DEBUG(\"Content of the c3 coefficient: [%f, %f, %f].\", c3_[0], c3_[1], c3_[2]);\n\n      /*        ORIENTATION      */\n      // Parameters used for the orientation and its derivatives. The coefficient\n      // refers to the ROLL (X), PITCH (Y) and YAW (Z)\n      g0_ = orientation_initial_;\n\n      ROS_DEBUG(\"Publishing orientation initial: [%f, %f, %f].\", orientation_initial_[0], orientation_initial_[1], orientation_initial_[2]);\n      ROS_DEBUG(\"Content of the g0 coefficient: [%f, %f, %f].\", g0_[0], g0_[1], g0_[2]);\n\n      g1_ = angular_velocity_initial_;\n\n      ROS_DEBUG(\"Publishing angular rate initial: [%f, %f, %f].\", angular_velocity_initial_[0], angular_velocity_initial_[1], angular_velocity_initial_[2]);\n      ROS_DEBUG(\"Content of the g1 coefficient: [%f, %f, %f].\", g1_[0], g1_[1], g1_[2]);\n\n      g2_.x() = angular_acceleration_initial_.x() * DELTA_1;\n      g2_.y() = angular_acceleration_initial_.y() * DELTA_1;\n      g2_.z() = angular_acceleration_initial_.z() * DELTA_1;\n\n      ROS_DEBUG(\"Publishing angular acceleration initial: [%f, %f, %f].\", angular_acceleration_initial_[0], angular_acceleration_initial_[1],\n                angular_acceleration_initial_[2]);\n      ROS_DEBUG(\"Content of the g2 coefficient: [%f, %f, %f].\", g2_[0], g2_[1], g2_[2]);\n\n      g3_.x() = (1/(ALPHA_1*pow(*time_spline,3))) * (ALPHA_2 * (orientation_final_.x() - orientation_initial_.x()) -\n                (ALPHA_3 * angular_velocity_final_.x() + ALPHA_4 * angular_velocity_initial_.x()) * *time_spline -\n                (ALPHA_5 * angular_acceleration_final_.x() - angular_acceleration_initial_.x()) * pow(*time_spline, 2));\n\n      g3_.y() = (1/(ALPHA_1*pow(*time_spline,3))) * (ALPHA_2 * (orientation_final_.y() - orientation_initial_.y()) -\n                (ALPHA_3 * angular_velocity_final_.y() + ALPHA_4 * angular_velocity_initial_.y()) * *time_spline -\n                (ALPHA_5 * angular_acceleration_final_.y() - angular_acceleration_initial_.y()) * pow(*time_spline, 2));\n\n      g3_.z() = (1/(ALPHA_1*pow(*time_spline,3))) * (ALPHA_2 * (orientation_final_.z() - orientation_initial_.z()) -\n                (ALPHA_3 * angular_velocity_final_.z() + ALPHA_4 * angular_velocity_initial_.z()) * *time_spline -\n                (ALPHA_5 * angular_acceleration_final_.z() - angular_acceleration_initial_.z()) * pow(*time_spline, 2));\n\n      ROS_DEBUG(\"Content of the g3 coefficient: [%f, %f, %f].\", g3_[0], g3_[1], g3_[2]);\n\n      g4_.x() = (1/(ALPHA_1*pow(*time_spline,4))) * (BETA_1 * (orientation_initial_.x() - orientation_final_.x()) +\n                (BETA_2 * angular_velocity_final_.x() + BETA_3 * angular_velocity_initial_.x()) * *time_spline +\n                (BETA_3 * angular_acceleration_final_.x() - BETA_4 * angular_acceleration_initial_.x()) * pow(*time_spline, 2));\n\n      g4_.y() = (1/(ALPHA_1*pow(*time_spline,4))) * (BETA_1 * (orientation_initial_.y() - orientation_final_.y()) +\n                (BETA_2 * angular_velocity_final_.y() + BETA_3 * angular_velocity_initial_.y()) * *time_spline +\n                (BETA_3 * angular_acceleration_final_.y() - BETA_4 * angular_acceleration_initial_.y()) * pow(*time_spline, 2));\n\n      g4_.z() = (1/(ALPHA_1*pow(*time_spline,4))) * (BETA_1 * (orientation_initial_.z() - orientation_final_.z()) +\n                (BETA_2 * angular_velocity_final_.z() + BETA_3 * angular_velocity_initial_.z()) * *time_spline +\n                (BETA_3 * angular_acceleration_final_.z() - BETA_4 * angular_acceleration_initial_.z()) * pow(*time_spline, 2));\n\n      ROS_DEBUG(\"Content of the g4 coefficient: [%f, %f, %f].\", g4_[0], g4_[1], g4_[2]);\n\n      g5_.x() = (1/(ALPHA_1*pow(*time_spline,5))) * (GAMMA_1 * (orientation_final_.x() - orientation_initial_.x()) -\n                GAMMA_2 * (angular_velocity_final_.x() + angular_velocity_initial_.x()) * *time_spline -\n                (angular_acceleration_final_.x() - angular_acceleration_initial_.x()) * pow(*time_spline, 2));\n\n      g5_.y() = (1/(ALPHA_1*pow(*time_spline,5))) * (GAMMA_1 * (orientation_final_.y() - orientation_initial_.y()) -\n                GAMMA_2 * (angular_velocity_final_.y() + angular_velocity_initial_.y()) * *time_spline -\n                (angular_acceleration_final_.y() - angular_acceleration_initial_.y()) * pow(*time_spline, 2));\n\n      g5_.z() = (1/(ALPHA_1*pow(*time_spline,5))) * (GAMMA_1 * (orientation_final_.z() - orientation_initial_.z()) -\n                GAMMA_2 * (angular_velocity_final_.z() + angular_velocity_initial_.z()) * *time_spline -\n                (angular_acceleration_final_.z() - angular_acceleration_initial_.z()) * pow(*time_spline, 2));\n\n      ROS_DEBUG(\"Content of the g5 coefficient: [%f, %f, %f].\", g5_[0], g5_[1], g5_[2]);\n\n      // The coefficients are used for having the angular velocity reference trajectory. The polynomial is computed\n      // derivating the g one. In other words,\n      // g5 * x^5 + g4 * x^4 + g3 * x^3 + g2 * x^2 + g1 * x + g0\n      // 5 * g5 * x^4 + 4 * g4 * x^3 + 3 * g3 * x^2 + 2 * g2 * x + g1\n      // h4 = 5 * g5 -- h3 = 4 * g4 -- h2 = 3 * g3 - h1 = 2 * g2 - h0 = g1\n      // and so on\n      h4_ = 5 * g5_;\n      h3_ = 4 * g4_;\n      h2_ = 3 * g3_;\n      h1_ = 2 * g2_;\n      h0_ = g1_;\n\n      ROS_DEBUG(\"Content of the h0 coefficient: [%f, %f, %f].\", h0_[0], h0_[1], h0_[2]);\n      ROS_DEBUG(\"Content of the h1 coefficient: [%f, %f, %f].\", h1_[0], h1_[1], h1_[2]);\n      ROS_DEBUG(\"Content of the h2 coefficient: [%f, %f, %f].\", h2_[0], h2_[1], h2_[2]);\n      ROS_DEBUG(\"Content of the h3 coefficient: [%f, %f, %f].\", h3_[0], h3_[1], h3_[2]);\n      ROS_DEBUG(\"Content of the h4 coefficient: [%f, %f, %f].\", h4_[0], h4_[1], h4_[2]);\n\n      // The coefficients are used for having the angular acceleration reference trajectory. The polynomial is computed\n      // derivating the b one. In other words,\n      // 4 * h4 * x^4 + 3 * h3 * x^3 + 2 * h2 * x^2 + h1 * x\n      // i3 = 4 * h4 -- i2 = 3 * h3 -- i1 = 2 * h2 - i0 = h1\n      i3_ = 4 * h4_;\n      i2_ = 3 * h3_;\n      i1_ = 2 * h2_;\n      i0_ = h1_;\n\n      ROS_DEBUG(\"Content of the i0 coefficient: [%f, %f, %f].\", i0_[0], i0_[1], i0_[2]);\n      ROS_DEBUG(\"Content of the i1 coefficient: [%f, %f, %f].\", i1_[0], i1_[1], i1_[2]);\n      ROS_DEBUG(\"Content of the i2 coefficient: [%f, %f, %f].\", i2_[0], i2_[1], i2_[2]);\n      ROS_DEBUG(\"Content of the i3 coefficient: [%f, %f, %f].\", i3_[0], i3_[1], i3_[2]);\n\n  }\n\n  void SplineTrajectoryGenerator::Euler2QuaternionCommandTrajectory(double* x, double* y, double* z, double* w) const {\n      assert(x);\n      assert(y);\n      assert(z);\n      assert(w);\n\n      // Abbreviations for the various angular functions\n      double cy = cos(yawDesRad_ * 0.5);\n      double sy = sin(yawDesRad_ * 0.5);\n      double cp = cos(pitchDesRad_ * 0.5);\n      double sp = sin(pitchDesRad_ * 0.5);\n      double cr = cos(rollDesRad_ * 0.5);\n      double sr = sin(rollDesRad_ * 0.5);\n\n      *w = cy * cp * cr + sy * sp * sr;\n      *x = cy * cp * sr - sy * sp * cr;\n      *y = sy * cp * sr + cy * sp * cr;\n      *z = sy * cp * cr - cy * sp * sr;\n\n      ROS_DEBUG(\"x Trajectory: %f, y Trajectory: %f, z Trajectory: %f, w Trajectory: %f\", *x, *y, *z, *w);\n    }\n\n   void SplineTrajectoryGenerator::InitializeParams(){\n\n     ros::NodeHandle pnh(\"~\");\n\n     // Parameters reading from rosparam.\n     GetRosParameter(pnh, \"time_final/time\", time_final_, &time_final_);\n     GetRosParameter(pnh, \"position_initial/x\", position_initial_.x(), &position_initial_.x());\n     GetRosParameter(pnh, \"position_initial/y\", position_initial_.y(), &position_initial_.y());\n     GetRosParameter(pnh, \"position_initial/z\", position_initial_.z(), &position_initial_.z());\n\n     GetRosParameter(pnh, \"position_final/x\", position_final_.x(), &position_final_.x());\n     GetRosParameter(pnh, \"position_final/y\", position_final_.y(), &position_final_.y());\n     GetRosParameter(pnh, \"position_final/z\", position_final_.z(), &position_final_.z());\n\n     GetRosParameter(pnh, \"velocity_initial/x\", velocity_initial_.x(), &velocity_initial_.x());\n     GetRosParameter(pnh, \"velocity_initial/y\", velocity_initial_.y(), &velocity_initial_.y());\n     GetRosParameter(pnh, \"velocity_initial/z\", velocity_initial_.z(), &velocity_initial_.z());\n\n     GetRosParameter(pnh, \"velocity_final/x\", velocity_final_.x(), &velocity_final_.x());\n     GetRosParameter(pnh, \"velocity_final/y\", velocity_final_.y(), &velocity_final_.y());\n     GetRosParameter(pnh, \"velocity_final/z\", velocity_final_.z(), &velocity_final_.z());\n\n     GetRosParameter(pnh, \"acceleration_initial/x\", acceleration_initial_.x(), &acceleration_initial_.x());\n     GetRosParameter(pnh, \"acceleration_initial/y\", acceleration_initial_.y(), &acceleration_initial_.y());\n     GetRosParameter(pnh, \"acceleration_initial/z\", acceleration_initial_.z(), &acceleration_initial_.z());\n\n     GetRosParameter(pnh, \"acceleration_final/x\", acceleration_final_.x(), &acceleration_final_.x());\n     GetRosParameter(pnh, \"acceleration_final/y\", acceleration_final_.y(), &acceleration_final_.y());\n     GetRosParameter(pnh, \"acceleration_final/z\", acceleration_final_.z(), &acceleration_final_.z());\n\n     GetRosParameter(pnh, \"orientation_initial/roll\", orientation_initial_.x(), &orientation_initial_.x());\n     GetRosParameter(pnh, \"orientation_initial/pitch\", orientation_initial_.y(), &orientation_initial_.y());\n     GetRosParameter(pnh, \"orientation_initial/yaw\", orientation_initial_.z(), &orientation_initial_.z());\n\n     GetRosParameter(pnh, \"orientation_final/roll\", orientation_final_.x(), &orientation_final_.x());\n     GetRosParameter(pnh, \"orientation_final/pitch\", orientation_final_.y(), &orientation_final_.y());\n     GetRosParameter(pnh, \"orientation_final/yaw\", orientation_final_.z(), &orientation_final_.z());\n\n     GetRosParameter(pnh, \"angularRate_initial/roll\", angular_velocity_initial_.x(), &angular_velocity_initial_.x());\n     GetRosParameter(pnh, \"angularRate_initial/pitch\", angular_velocity_initial_.y(), &angular_velocity_initial_.y());\n     GetRosParameter(pnh, \"angularRate_initial/yaw\", angular_velocity_initial_.z(), &angular_velocity_initial_.z());\n\n     GetRosParameter(pnh, \"angularRate_final/roll\", angular_velocity_final_.x(), &angular_velocity_final_.x());\n     GetRosParameter(pnh, \"angularRate_final/pitch\", angular_velocity_final_.y(), &angular_velocity_final_.y());\n     GetRosParameter(pnh, \"angularRate_final/yaw\", angular_velocity_final_.z(), &angular_velocity_final_.z());\n\n     GetRosParameter(pnh, \"angularDoubleRate_initial/roll\", angular_acceleration_initial_.x(), &angular_acceleration_initial_.x());\n     GetRosParameter(pnh, \"angularDoubleRate_initial/pitch\", angular_acceleration_initial_.y(), &angular_acceleration_initial_.y());\n     GetRosParameter(pnh, \"angularDoubleRate_initial/yaw\", angular_acceleration_initial_.z(), &angular_acceleration_initial_.z());\n\n     GetRosParameter(pnh, \"angularDoubleRate_final/roll\", angular_acceleration_final_.x(), &angular_acceleration_final_.x());\n     GetRosParameter(pnh, \"angularDoubleRate_final/pitch\", angular_acceleration_final_.y(), &angular_acceleration_final_.y());\n     GetRosParameter(pnh, \"angularDoubleRate_final/yaw\", angular_acceleration_final_.z(), &angular_acceleration_final_.z());\n\n   }\n\n   template<typename T> inline void SplineTrajectoryGenerator::GetRosParameterHovering(const ros::NodeHandle& nh,\n                                                            const std::string& key,\n                                                            const T& default_value,\n                                                            T* value) {\n\n     ROS_ASSERT(value != nullptr);\n     bool have_parameter = nh.getParam(key, *value);\n     if (!have_parameter) {\n       ROS_WARN_STREAM(\"[rosparam]: could not find parameter \" << nh.getNamespace()\n                       << \"/\" << key << \", setting to default: \" << default_value);\n       *value = default_value;\n     }\n   }\n\n}\n", "meta": {"hexsha": "ffcd5a6386562a1c9cf12c3dba2e7064aff36af3", "size": 26758, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "rotors_gazebo/src/library/spline_trajectory_generator.cpp", "max_stars_repo_name": "dfl-rlab/CrazyS", "max_stars_repo_head_hexsha": "00eac2eef0302ac14f07bc326fa4c57171470234", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 124.0, "max_stars_repo_stars_event_min_datetime": "2018-03-03T07:28:08.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T12:59:12.000Z", "max_issues_repo_path": "rotors_gazebo/src/library/spline_trajectory_generator.cpp", "max_issues_repo_name": "dfl-rlab/CrazyS", "max_issues_repo_head_hexsha": "00eac2eef0302ac14f07bc326fa4c57171470234", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 87.0, "max_issues_repo_issues_event_min_datetime": "2018-05-28T15:18:24.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-27T13:44:20.000Z", "max_forks_repo_path": "rotors_gazebo/src/library/spline_trajectory_generator.cpp", "max_forks_repo_name": "dfl-rlab/CrazyS", "max_forks_repo_head_hexsha": "00eac2eef0302ac14f07bc326fa4c57171470234", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 76.0, "max_forks_repo_forks_event_min_datetime": "2018-06-05T09:31:37.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-12T20:33:44.000Z", "avg_line_length": 58.1695652174, "max_line_length": 156, "alphanum_fraction": 0.6348008072, "num_tokens": 8462, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6959583124210896, "lm_q2_score": 0.46490157137338844, "lm_q1q2_score": 0.3235521130549362}}
{"text": "/**************************************************************************\\\n|\n|    Copyright (C) 2009 Marc Stevens\n|\n|    This program is free software: you can redistribute it and/or modify\n|    it under the terms of the GNU General Public License as published by\n|    the Free Software Foundation, either version 3 of the License, or\n|    (at your option) any later version.\n|\n|    This program is distributed in the hope that it will be useful,\n|    but WITHOUT ANY WARRANTY; without even the implied warranty of\n|    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n|    GNU General Public License for more details.\n|\n|    You should have received a copy of the GNU General Public License\n|    along with this program.  If not, see <http://www.gnu.org/licenses/>.\n|\n\\**************************************************************************/\n\n#include <vector>\n#include <string>\n#include <map>\n#include <cmath>\n#include <algorithm>\n\n#include <hashclash/saveload_bz2.hpp>\n\n#include \"main.hpp\"\n\n#include <boost/lexical_cast.hpp>\n#include <boost/filesystem/operations.hpp>\n#include <boost/filesystem/convenience.hpp>\n#include <boost/thread/thread.hpp>\n#include <boost/thread/mutex.hpp>\n\n#include <hashclash/sdr.hpp>\n#include <hashclash/rng.hpp>\n#include <hashclash/timer.hpp>\n#include <hashclash/md5detail.hpp>\n\n#include \"distribution.hpp\" // distribution tables\n#include \"storage.hpp\"\n\nvoid determine_nrblocks_distribution(birthday_parameters& parameters);\n\nboost::mutex global_mutex;\n#define LOCK_GLOBAL_MUTEX\tboost::mutex::scoped_lock lock(global_mutex);\n\nusing namespace hashclash;\nusing namespace std;\n\n/* LOCK_GLOBAL_MUTEX not needed */\nuint32 ihv1[4], ihv2[4], ihv2mod[4], msg1[16], msg2[16], precomp1[4], precomp2[4];\nuint32 hybridmask = 0, distinguishedpointmask = 0, maximumpathlength = 1;\nunsigned maxblocks = 64;\nbool memhardlimit = false;\nunsigned parameterspathtyperange = 0;\nunsigned procmodn = 0, procmodi = 0;\nvector< pair<uint32,uint32> > singleblockdata;\n/**/\n\n/* LOCK_GLOBAL_MUTEX required */\nuint32 colla1, collb1, collc1, colla2, collb2, collc2;\nuint64 totwork = 0, totworkallproc = 0;\nunsigned bestnrblocks = 64;\nbool quit = false;\nunsigned collrobinhoods = 0, collequalihvs = 0, collusefull = 0;\nvector< vector<trail_type> > trail_distribution(0);\n//vector< pair<trail_type, trail_type> > collisions_queue(0);\n/**/\n\n\n// LOCK_GLOBAL_MUTEX required\nvoid status_line()\n{\n\tunsigned totcoll = main_storage.get_totcoll();\n\tunsigned collqueue = main_storage.get_collqueuesize();\n\tif (procmodn > 1) \n\t\tcout << \"Work: mine=2^(\" << log(double(totwork))/log(double(2)) << \") all=2^(\" << log(double(totworkallproc))/log(double(2)) << \")\";\n\telse\n\t\tcout << \"Work: 2^(\" << log(double(totwork))/log(double(2)) << \")\";\n\tcout << \", Coll.: \" << main_storage.get_totcoll() \n\t\t << \"(uf=\" << collusefull << \",nuf=\" << collequalihvs \n\t\t << \",?=\" << (totcoll-collusefull-collequalihvs-collrobinhoods-collqueue) \n\t\t << \",q=\" << collqueue << \",rh=\" << collrobinhoods \n\t\t << \"), Blocks: \" << bestnrblocks << endl; //\"     \\r\" << flush;\n}\n\n// LOCK_GLOBAL_MUTEX not needed\nunsigned nrblocks(uint32 dihv[4])\n{\n\tuint32 ptrmaskt2 = 0;\n\tfor (unsigned j = 0; j < parameterspathtyperange; ++j)\n\t\tptrmaskt2 |= 2<<j;\n\tsdr p1naf = naf(dihv[3]);\n\tuint32 p1nafmask = p1naf.mask;\n\tuint32 p2nafmask = naf(dihv[1]-dihv[3]).mask;\n\tp2nafmask = rotate_right(p2nafmask, 21);\n\tuint32 p1mask = p1nafmask;\n\tfor (unsigned j = 0; j < parameterspathtyperange; ++j)\n\t\tp1mask |= p1nafmask << (j+1);\n\tp2nafmask &= ~p1mask;\n\tfor (unsigned b = 0; b < 32; ++b)\n\t\tif (p2nafmask & (1<<b))\n\t\t\tp2nafmask &= ~(ptrmaskt2<<b);\n\tp1nafmask &= ~(p2nafmask<<1);\n\tp1nafmask &= ~(p1nafmask>>31);\n\treturn hw(p1nafmask) + 2*hw(p2nafmask);\n}\n\n\n// LOCK_GLOBAL_MUTEX not needed\nvoid precomputestate(uint32 ihv[4], uint32 block[16])\n{\n        #define HASHCLASH_MD5COMPRESS_STEP(f, a, b, c, d, m, ac, rc) \\\n                a += f(b, c, d) + m + ac; a = rotate_left(a,rc); a += b;\n        \n\tuint32 a = ihv[0]; uint32 b = ihv[1]; uint32 c = ihv[2]; uint32 d = ihv[3];\n\n\tHASHCLASH_MD5COMPRESS_STEP(md5_ff, a, b, c, d, block[ 0], 0xd76aa478,  7);  \n\tHASHCLASH_MD5COMPRESS_STEP(md5_ff, d, a, b, c, block[ 1], 0xe8c7b756, 12); \n\tHASHCLASH_MD5COMPRESS_STEP(md5_ff, c, d, a, b, block[ 2], 0x242070db, 17); \n\tHASHCLASH_MD5COMPRESS_STEP(md5_ff, b, c, d, a, block[ 3], 0xc1bdceee, 22); \n\tHASHCLASH_MD5COMPRESS_STEP(md5_ff, a, b, c, d, block[ 4], 0xf57c0faf,  7);  \n\tHASHCLASH_MD5COMPRESS_STEP(md5_ff, d, a, b, c, block[ 5], 0x4787c62a, 12); \n\tHASHCLASH_MD5COMPRESS_STEP(md5_ff, c, d, a, b, block[ 6], 0xa8304613, 17); \n\tHASHCLASH_MD5COMPRESS_STEP(md5_ff, b, c, d, a, block[ 7], 0xfd469501, 22); \n\tHASHCLASH_MD5COMPRESS_STEP(md5_ff, a, b, c, d, block[ 8], 0x698098d8,  7);  \n\tHASHCLASH_MD5COMPRESS_STEP(md5_ff, d, a, b, c, block[ 9], 0x8b44f7af, 12); \n\tHASHCLASH_MD5COMPRESS_STEP(md5_ff, c, d, a, b, block[10], 0xffff5bb1, 17);\n\tHASHCLASH_MD5COMPRESS_STEP(md5_ff, b, c, d, a, block[11], 0x895cd7be, 22);\n\tHASHCLASH_MD5COMPRESS_STEP(md5_ff, a, b, c, d, block[12], 0x6b901122,  7); \n\n\tihv[0] = a; ihv[1] = b; ihv[2] = c; ihv[3] = d;\n}\n\n// LOCK_GLOBAL_MUTEX not needed\ninline void birthday_step(uint32& x, uint32& y, uint32& z)\n{\n\tuint32* block;\n\tuint32* precomp;\n\tuint32* ihv;\n\tif (x <= y) {\n\t\tprecomp = precomp1;\n\t\tblock = msg1;\n\t\tihv = ihv1;\n\t} else {\n\t\tprecomp = precomp2;\n\t\tblock = msg2;\n\t\tihv = ihv2mod;\n\t}\n\t{\n\t\tuint32 a = precomp[0], b = precomp[1], c = precomp[2], d = precomp[3];\n\t\tHASHCLASH_MD5COMPRESS_STEP(md5_ff, d, a, b, c, z, 0xfd987193, 12);\n\t\tHASHCLASH_MD5COMPRESS_STEP(md5_ff, c, d, a, b, x, 0xa679438e, 17);\n\t\tHASHCLASH_MD5COMPRESS_STEP(md5_ff, b, c, d, a, y, 0x49b40821, 22);\n\t\tHASHCLASH_MD5COMPRESS_STEP(md5_gg, a, b, c, d, block[ 1], 0xf61e2562,  5);  \n\t\tHASHCLASH_MD5COMPRESS_STEP(md5_gg, d, a, b, c, block[ 6], 0xc040b340,  9);  \n\t\tHASHCLASH_MD5COMPRESS_STEP(md5_gg, c, d, a, b, block[11], 0x265e5a51, 14);\n\t\tHASHCLASH_MD5COMPRESS_STEP(md5_gg, b, c, d, a, block[ 0], 0xe9b6c7aa, 20); \n\t\tHASHCLASH_MD5COMPRESS_STEP(md5_gg, a, b, c, d, block[ 5], 0xd62f105d,  5);  \n\t\tHASHCLASH_MD5COMPRESS_STEP(md5_gg, d, a, b, c, block[10], 0x02441453,  9); \n\t\tHASHCLASH_MD5COMPRESS_STEP(md5_gg, c, d, a, b, y, 0xd8a1e681, 14);\n\t\tHASHCLASH_MD5COMPRESS_STEP(md5_gg, b, c, d, a, block[ 4], 0xe7d3fbc8, 20); \n\t\tHASHCLASH_MD5COMPRESS_STEP(md5_gg, a, b, c, d, block[ 9], 0x21e1cde6,  5);  \n\t\tHASHCLASH_MD5COMPRESS_STEP(md5_gg, d, a, b, c, x, 0xc33707d6,  9); \n\t\tHASHCLASH_MD5COMPRESS_STEP(md5_gg, c, d, a, b, block[ 3], 0xf4d50d87, 14); \n\t\tHASHCLASH_MD5COMPRESS_STEP(md5_gg, b, c, d, a, block[ 8], 0x455a14ed, 20); \n\t\tHASHCLASH_MD5COMPRESS_STEP(md5_gg, a, b, c, d, z, 0xa9e3e905,  5); \n\t\tHASHCLASH_MD5COMPRESS_STEP(md5_gg, d, a, b, c, block[ 2], 0xfcefa3f8,  9);  \n\t\tHASHCLASH_MD5COMPRESS_STEP(md5_gg, c, d, a, b, block[ 7], 0x676f02d9, 14); \n\t\tHASHCLASH_MD5COMPRESS_STEP(md5_gg, b, c, d, a, block[12], 0x8d2a4c8a, 20);\n\t\tHASHCLASH_MD5COMPRESS_STEP(md5_hh, a, b, c, d, block[ 5], 0xfffa3942,  4); \n\t\tHASHCLASH_MD5COMPRESS_STEP(md5_hh, d, a, b, c, block[ 8], 0x8771f681, 11); \n\t\tHASHCLASH_MD5COMPRESS_STEP(md5_hh, c, d, a, b, block[11], 0x6d9d6122, 16);\n\t\tHASHCLASH_MD5COMPRESS_STEP(md5_hh, b, c, d, a, x, 0xfde5380c, 23);\n\t\tHASHCLASH_MD5COMPRESS_STEP(md5_hh, a, b, c, d, block[ 1], 0xa4beea44,  4);  \n\t\tHASHCLASH_MD5COMPRESS_STEP(md5_hh, d, a, b, c, block[ 4], 0x4bdecfa9, 11); \n\t\tHASHCLASH_MD5COMPRESS_STEP(md5_hh, c, d, a, b, block[ 7], 0xf6bb4b60, 16); \n\t\tHASHCLASH_MD5COMPRESS_STEP(md5_hh, b, c, d, a, block[10], 0xbebfbc70, 23);\n\t\tHASHCLASH_MD5COMPRESS_STEP(md5_hh, a, b, c, d, z, 0x289b7ec6,  4); \n\t\tHASHCLASH_MD5COMPRESS_STEP(md5_hh, d, a, b, c, block[ 0], 0xeaa127fa, 11); \n\t\tHASHCLASH_MD5COMPRESS_STEP(md5_hh, c, d, a, b, block[ 3], 0xd4ef3085, 16); \n\t\tHASHCLASH_MD5COMPRESS_STEP(md5_hh, b, c, d, a, block[ 6], 0x04881d05, 23); \n\t\tHASHCLASH_MD5COMPRESS_STEP(md5_hh, a, b, c, d, block[ 9], 0xd9d4d039,  4);  \n\t\tHASHCLASH_MD5COMPRESS_STEP(md5_hh, d, a, b, c, block[12], 0xe6db99e5, 11);\n\t\tHASHCLASH_MD5COMPRESS_STEP(md5_hh, c, d, a, b, y, 0x1fa27cf8, 16);\n\t\tHASHCLASH_MD5COMPRESS_STEP(md5_hh, b, c, d, a, block[ 2], 0xc4ac5665, 23); \n\t\tHASHCLASH_MD5COMPRESS_STEP(md5_ii, a, b, c, d, block[ 0], 0xf4292244,  6);  \n\t\tHASHCLASH_MD5COMPRESS_STEP(md5_ii, d, a, b, c, block[ 7], 0x432aff97, 10); \n\t\tHASHCLASH_MD5COMPRESS_STEP(md5_ii, c, d, a, b, x, 0xab9423a7, 15);\n\t\tHASHCLASH_MD5COMPRESS_STEP(md5_ii, b, c, d, a, block[ 5], 0xfc93a039, 21); \n\t\tHASHCLASH_MD5COMPRESS_STEP(md5_ii, a, b, c, d, block[12], 0x655b59c3,  6); \n\t\tHASHCLASH_MD5COMPRESS_STEP(md5_ii, d, a, b, c, block[ 3], 0x8f0ccc92, 10); \n\t\tHASHCLASH_MD5COMPRESS_STEP(md5_ii, c, d, a, b, block[10], 0xffeff47d, 15);\n\t\tHASHCLASH_MD5COMPRESS_STEP(md5_ii, b, c, d, a, block[ 1], 0x85845dd1, 21); \n\t\tHASHCLASH_MD5COMPRESS_STEP(md5_ii, a, b, c, d, block[ 8], 0x6fa87e4f,  6);  \n\t\tHASHCLASH_MD5COMPRESS_STEP(md5_ii, d, a, b, c, y, 0xfe2ce6e0, 10);\n\t\tHASHCLASH_MD5COMPRESS_STEP(md5_ii, c, d, a, b, block[ 6], 0xa3014314, 15); \n\t\tHASHCLASH_MD5COMPRESS_STEP(md5_ii, b, c, d, a, z, 0x4e0811a1, 21);\n\t\tHASHCLASH_MD5COMPRESS_STEP(md5_ii, a, b, c, d, block[ 4], 0xf7537e82,  6);  \n\t\tHASHCLASH_MD5COMPRESS_STEP(md5_ii, d, a, b, c, block[11], 0xbd3af235, 10);\n\t\tHASHCLASH_MD5COMPRESS_STEP(md5_ii, c, d, a, b, block[ 2], 0x2ad7d2bb, 15); \n\t\tHASHCLASH_MD5COMPRESS_STEP(md5_ii, b, c, d, a, block[ 9], 0xeb86d391, 21); \n\t\ta += ihv[0];\n\t\tb += ihv[1];\n\t\tc += ihv[2];\n\t\td += ihv[3];\n\t\tif (maxblocks != 1) {\n\t\t\tx = a;\n\t\t\ty = d - c;\n\t\t\tz = (d - b) & hybridmask;\n\t\t} else {\n\t\t\tx = a;\n\t\t\ty = d;\n\t\t\tz = c & hybridmask;\n\t\t}\n\t}\n}\n\n// LOCK_GLOBAL_MUTEX not needed\nvoid generate_trail(trail_type& trail)\n{\n\tuint32 x = trail.start[0], y = trail.start[1], z = trail.start[2];\n\ttrail.len = 1;\n\tbirthday_step(x,y,z);\n\twhile (trail.len <= maximumpathlength && 0!=(x & distinguishedpointmask)) {\n\t\tbirthday_step(x,y,z);\n\t\t++trail.len;\n\t}\n\ttrail.end[0] = x;\n\ttrail.end[1] = y;\n\ttrail.end[2] = z;\n}\n\n// do not use LOCK_GLOBAL_MUTEX \n// function possibly calls LOCK_GLOBAL_MUTEX\nvoid find_collision(const trail_type& trail1, const trail_type& trail2)\n{\n\tuint32 a1 = trail1.start[0];\n\tuint32 b1 = trail1.start[1];\n\tuint32 c1 = trail1.start[2];\n\tuint32 a2 = trail2.start[0];\n\tuint32 b2 = trail2.start[1];\n\tuint32 c2 = trail2.start[2];\n\tuint32 len1 = trail1.len;\n\tuint32 len2 = trail2.len;\n\t// sanity check\n\tif (trail1.len > maximumpathlength || 0!=(trail1.end[0]&distinguishedpointmask)\n\t    || trail2.len > maximumpathlength || 0!=(trail2.end[0]&distinguishedpointmask))\n\t{\n\t\tLOCK_GLOBAL_MUTEX;\n\t\tcout << \"X\" << flush;\n\t\t++collrobinhoods; // have to categorize this collision\n\t\treturn;\n\t}\n\n\twhile (len1 > len2)\n\t{\n\t\tbirthday_step(a1, b1, c1);\n\t\t--len1;\n\t}\n\twhile (len2 > len1)\n\t{\n\t\tbirthday_step(a2, b2, c2);\n\t\t--len2;\n\t}\n\n\t// check for robin hood\n\tif (a1 == a2 && b1 == b2 && c1 == c2)\n\t{\n\t\tLOCK_GLOBAL_MUTEX;\n\t\t++collrobinhoods;\n\t\treturn;\n\t}\n\n\tuint32 oa1 = a1, oa2 = a2, ob1 = b1, ob2 = b2, oc1 = c1, oc2 = c2;\n\twhile ((a1 != a2 || b1 != b2 || c1 != c2) && len1 > 0)\n\t{\n\t\toa1 = a1; oa2 = a2; ob1 = b1; ob2 = b2; oc1 = c1; oc2 = c2;\n\t\tbirthday_step(a1, b1, c1);\n\t\tbirthday_step(a2, b2, c2);\n\t\t--len1;\n\t}\n\tif (len1 == 0 && (a1 != a2 || b1 != b2 || c1 != c2)) \n\t{\n\t\tLOCK_GLOBAL_MUTEX;\n\t\tcerr << \"find_collision(): len=0 (len1=\" << trail1.len << \",len2=\" << trail2.len << \")           \" << endl;\n\t\t++collrobinhoods;\n\t\treturn;\n\t}\n\n\t// check for same ihv birthday collision\n\tif ((oa1 <= ob1) == (oa2 <= ob2))\n\t{\n\t\tLOCK_GLOBAL_MUTEX;\n\t\t++collequalihvs;\n\t\treturn;\n\t}\n\n\tuint32 ihvmsg1[4];\n\tuint32 ihvmsg2[4];\n\tif (oa2 <= ob2) {\n\t\tswap(oa2, oa1);\n\t\tswap(ob2, ob1);\n\t\tswap(oc2, oc1);\n\t}\n\tuint32 lmsg1[16];\n\tuint32 lmsg2[16];\n\tfor (unsigned i = 0; i < 13; ++i)\n\t{\n\t\tlmsg1[i] = msg1[i];\n\t\tlmsg2[i] = msg2[i];\n\t}\n\tlmsg1[13] = oc1; lmsg1[14] = oa1; lmsg1[15] = ob1;\n\tihvmsg1[0] = ihv1[0]; ihvmsg1[1] = ihv1[1]; \n\tihvmsg1[2] = ihv1[2]; ihvmsg1[3] = ihv1[3];\n\tmd5compress(ihvmsg1, lmsg1);\n\tlmsg2[13] = oc2; lmsg2[14] = oa2; lmsg2[15] = ob2;\n\tihvmsg2[0] = ihv2[0]; ihvmsg2[1] = ihv2[1]; \n\tihvmsg2[2] = ihv2[2]; ihvmsg2[3] = ihv2[3];\n\tmd5compress(ihvmsg2, lmsg2);\n\tuint32 dihv[4] = { ihvmsg2[0]-ihvmsg1[0], ihvmsg2[1]-ihvmsg1[1],\n\t\t\t\t\t   ihvmsg2[2]-ihvmsg1[2], ihvmsg2[3]-ihvmsg1[3] };\n\n\tunsigned n = 64;\n\tif (maxblocks == 1) {\n\t\tif (dihv[0] == -(1<<5) \n\t\t\t&& dihv[3] == -(1<<5)+(1<<25) \n\t\t\t&& (dihv[2]&hybridmask) == (uint32(-(1<<5)+(1<<25)+(1<<23))&hybridmask)\n\t\t\t) \n\t\t{\n\t\t\tpair<uint32,uint32> bc(dihv[1],dihv[2]);\n\t\t\tif (binary_search(singleblockdata.begin(), singleblockdata.end(), bc))\n\t\t\t\tn = 1;\n\t\t} else if (dihv[0] == (1<<5) \n\t\t\t&& dihv[3] == (1<<5)-(1<<25) \n\t\t\t&& (dihv[2]&hybridmask) == (uint32((1<<5)-(1<<25)-(1<<23))&hybridmask)\n\t\t\t) \n\t\t{\n\t\t\tpair<uint32,uint32> bc(-dihv[1],-dihv[2]);\n\t\t\tif (binary_search(singleblockdata.begin(), singleblockdata.end(), bc))\n\t\t\t\tn = 1;\n\t\t} else\n\t\t\tcout << \"bad!!\" << endl;\n\t} else {\n\t\tif (dihv[0] != 0 && dihv[2] != dihv[3])\n\t\t{\n\t\t\tcerr << \"dihv fails assumptions\" << endl;\n\t\t\treturn;\n//\t\t\tthrow;\n\t\t}\n\t\tn = nrblocks(dihv);\n\t}\n\tLOCK_GLOBAL_MUTEX;\n\t++collusefull;\n\tif (quit == true)\n\t\treturn;\n\n\tif (n < bestnrblocks) {\n\t\tbestnrblocks = n;\n\t\tcout << endl;\n\t\tstatus_line();\n\t}\n\n\tif (n <= maxblocks)\n\t{\n\t\tif (n >= bestnrblocks) {\n\t\t\tcout << endl;\n\t\t\tstatus_line();\n\t\t}\n\t\tcolla1 = oa1;\n\t\tcollb1 = ob1;\n\t\tcollc1 = oc1;\n\t\tcolla2 = oa2;\n\t\tcollb2 = ob2;\n\t\tcollc2 = oc2;\n\t\tcout << endl;\n\n\t\tcout << \"IHV1   = {\" << ihvmsg1[0] << \",\" << ihvmsg1[1] << \",\" << ihvmsg1[2] << \",\" << ihvmsg1[3] << \"}\" << endl;\n\t\tcout << \"IHV2   = {\" << ihvmsg2[0] << \",\" << ihvmsg2[1] << \",\" << ihvmsg2[2] << \",\" << ihvmsg2[3] << \"}\" << endl;\n\t\tcout << \"dIHV   = {\" << dihv[0] << \",\" << dihv[1] << \",\" << dihv[2] << \",\" << dihv[3] << \"}\" << endl;\n\t\tsdr v = naf(dihv[3]);\n\t\tsdr w = naf(dihv[1] - dihv[3]);\n\t\tcout << \"Dv     = \" << v << endl;\n\t\tcout << \"Dw     = \" << w << endl;\n\t\tcout << \"Blocks = \" << n << endl << endl;\n\t\tcout << \"Msg1   = \";\n\t\tfor (unsigned i = 0; i < 13; ++i)\n\t\t\tcout << msg1[i] << \" \";\n\t\tcout << oc1 << \" \" << oa1 << \" \" << ob1 << endl;\n\t\tcout << \"Msg2   = \";\n\t\tfor (unsigned i = 0; i < 13; ++i)\n\t\t\tcout << msg2[i] << \" \";\n\t\tcout << oc2 << \" \" << oa2 << \" \" << ob2 << endl;\n#if 1\n\t\tquit = true;\n#else\n\t\tstring filename1 = workdir + \"/birthdayblock1_\" + boost::lexical_cast<string>(v)+\"_\" + boost::lexical_cast<string>(w)+\".bin\";\n\t\tstring filename2 = workdir + \"/birthdayblock2_\" + boost::lexical_cast<string>(v)+\"_\" + boost::lexical_cast<string>(w)+\".bin\";\n\t\tofstream of1(filename1.c_str(), ios::binary | ios::app);\n\t\tofstream of2(filename2.c_str(), ios::binary | ios::app);\n\t\tsave_block(of1,msg1);\n\t\tsave_block(of2,msg2);\n\t\tcout << \"Wrote birthdaycollision block to: \" << endl;\n\t\tcout << \"\\t\" << filename1 << endl << \"\\t\" << filename2 << endl;\n#endif\n\t}\n}\n\n\n\n\n// LOCK_GLOBAL_MUTEX required\nvoid distribute_trail(const trail_type& newtrail) \n{\n\ttotwork += newtrail.len;\n\ttotworkallproc += newtrail.len;\n\tuint32 procindex = newtrail.end[1] % procmodn;\n\tif (procindex == procmodi) {\n\t\tmain_storage.insert_trail(newtrail);\n\t} else\n\t\ttrail_distribution[procindex].push_back(newtrail);\n}\n\n// LOCK_GLOBAL_MUTEX required\nstruct trail_distribute_type {\n\tuint32 proci;\n\tuint64 totwork;\n\tvector< trail_type > trails;\n\tuint32 check;\n\n\ttemplate<class Archive>\n\tvoid serialize(Archive& ar, const unsigned int file_version) {\n\t\tar & boost::serialization::make_nvp(\"proci\", proci);\n\t\tar & boost::serialization::make_nvp(\"totwork\", totwork);\n\t\tar & boost::serialization::make_nvp(\"trails\", trails);\n\t\tar & boost::serialization::make_nvp(\"check\", check);\n\t}\n};\n\n// do not use LOCK_GLOBAL_MUTEX \n// function possibly calls LOCK_GLOBAL_MUTEX\nvoid load_save_trails(bool dosave = true)\n{\n\tstatic vector<uint64> workothers(procmodn, 0);\n\tstatic vector<unsigned> fileserialothers(procmodn, 0);\n\tstatic unsigned savepart = 0;\n\ttry {\n\t\tboost::filesystem::directory_iterator dit(workdir + \"/\" + boost::lexical_cast<string>(procmodi)), ditend;\n\t\tfor (; dit != ditend; ++dit)\n\t\t{\n\t\t\tboost::filesystem::path filepath = *dit;\n\t\t\tif (!exists(*dit) \n\t\t\t\t|| symbolic_link_exists(*dit)\n\t\t\t\t|| is_directory(*dit))\n\t\t\t\tcontinue;\n#if BOOST_VERSION == 104300\n\t\t\tstring filename = dit->leaf();\n#else\n\t\t\tstring filename = dit->path().filename().string();\n#endif\n\t\t\tif (filename.size() < 16)\n\t\t\t\tcontinue;\n\t\t\tif (filename.substr(0, 12) != \"birthdaydata\")\n\t\t\t\tcontinue;\n\t\t\tif (filename.substr(filename.size()-4) != \".bin\")\n\t\t\t\tcontinue;\n\t\n\t\t\ttrail_distribute_type traildata;\n\t\t\ttraildata.check = 0;\n\t\t\ttry {\n\t\t\t\tload(traildata, binary_archive, *dit);\n\t\t\t} catch (exception& ) {} catch (...) {}\n\t\t\tif (traildata.check != 0x56139078) continue; // incomplete file\n\t\t\ttry { \n\t\t\t\tboost::filesystem::remove(*dit);\n\t\t\t} catch (exception& ) {} catch (...) {}\n\t\t\tif (traildata.proci >= procmodn) continue;\n\t\t\tif (workothers[traildata.proci] < traildata.totwork)\n\t\t\t\tworkothers[traildata.proci] = traildata.totwork;\n\t\t\tLOCK_GLOBAL_MUTEX;\n\t\t\tfor (unsigned i = 0; i < traildata.trails.size(); ++i)\n\t\t\t\tif (traildata.trails[i].end[1] % procmodn != procmodi) \n\t\t\t\t\tcerr << \"False trail loaded!!\" << endl;\n\t\t\tmain_storage.insert_trails(traildata.trails);\n\t\t}\n\t} \n\tcatch (exception& ) {}\n\tcatch (...) {}\n\tif (dosave) {\n\t\ttry {\n\t\t\ttrail_distribute_type traildata;\n\t\t\ttraildata.proci = procmodi;\n\t\t\ttraildata.totwork = totwork;\n\t\t\ttraildata.check = 0x56139078;\n\t\t\tsavepart = (savepart+1) % 64;\n\t\t\tfor (unsigned i = 0; i < procmodn; ++i) {\n\t\t\t\tif ( (i%64) != savepart) continue;\n\t\t\t\ttraildata.trails.clear();\n\t\t\t\t{\n\t\t\t\t\tLOCK_GLOBAL_MUTEX;\n\t\t\t\t\tswap(traildata.trails, trail_distribution[i]);\n\t\t\t\t}\n\t\t\t\tif (traildata.trails.size()) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\t++fileserialothers[i];\n\t\t\t\t\t\tstring basefilename = workdir + \"/\" + boost::lexical_cast<string>(i) \n\t\t\t\t\t\t\t+ \"/birthdaydata_\" + boost::lexical_cast<string>(procmodi) + \"_\";\n\t\t\t\t\t\tstring tmpfilename = \"/tmp/birthdaydata_\" + boost::lexical_cast<string>(i) \n\t\t\t\t\t\t\t+ \"_\" + boost::lexical_cast<string>(procmodi) + \"_\";\n\t\t\t\t\t\tsave(traildata, binary_archive, tmpfilename + boost::lexical_cast<string>(fileserialothers[i]) + \".tmp\");\n\t\t\t\t\t\tboost::filesystem::copy_file( tmpfilename + boost::lexical_cast<string>(fileserialothers[i]) + \".tmp\",\n\t\t\t\t\t\t\tbasefilename + boost::lexical_cast<string>(fileserialothers[i]) + \".bin\");\n\t\t\t\t\t\tboost::filesystem::remove( tmpfilename + boost::lexical_cast<string>(fileserialothers[i]) + \".tmp\" );\n\t\t\t\t\t}\n\t\t\t\t\tcatch (exception& e) { cerr << e.what() << endl; }\n\t\t\t\t\tcatch (...) {}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tcatch (exception& ) {}\n\t\tcatch (...) {}\n\t}\n\tLOCK_GLOBAL_MUTEX;\n\tworkothers[procmodi] = totwork;\n\ttotworkallproc = 0;\n\tfor (unsigned i = 0; i < workothers.size(); ++i)\n\t\ttotworkallproc += workothers[i];\n}\n\n\nstruct coll_less : public std::binary_function<pair<trail_type,trail_type>, pair<trail_type,trail_type>, bool>\n{\n\tbool operator()(const pair<trail_type,trail_type>& _Left, const pair<trail_type,trail_type>& _Right) const {\n\t\treturn _Left.first.len < _Right.first.len;\n\t}\n};\n\nstruct birthday_thread {\n\tstatic uint32 id_counter; // = 1 (below class definition)\n\tuint32 id;\n\tint _cuda_device_nr;\n\tcuda_device _cuda_device;\n\t\n\tbirthday_thread(int cuda_device_nr = -1)\n\t\t: _cuda_device_nr(cuda_device_nr), id(id_counter++)\n\t{}\n\n\tvoid loop_cuda(bool single = false)\n\t{\n\t\tvector<trail_type> work;\n\t\tvector< pair<trail_type, trail_type> > collisions;\n\t\twhile (true)\n\t\t{\n\t\t\tuint64 seed;\n\t\t\t{\n\t\t\t\tLOCK_GLOBAL_MUTEX;\n\t\t\t\tseed = uint64(xrng128()) + (uint64(xrng128())<<32)+1111*procmodi;\n\t\t\t\txrng128();\n\t\t\t\txrng128();\n\n\t\t\t\tif (quit) return;\n\t\t\t}\n#ifdef HAVE_CUDA\n\t\t\tif (_cuda_device_nr >= 0)\n\t\t\t\t_cuda_device.cuda_fill_trail_buffer(id, seed, work, collisions, bool(maxblocks == 1));\n\t\t\telse\n\t\t\t\treturn;\n#endif\n\n\t\t\t// insert the trails into the trail hash\n\t\t\tif (collisions.size() > 0)\n\t\t\t\tcollisions.clear();\n\t\t\telse {\n\t\t\t\tLOCK_GLOBAL_MUTEX;\n\t\t\t\tfor (unsigned i = 0; i < work.size(); ++i) \n\t\t\t\t\tdistribute_trail(work[i]); \n\t\t\t}\n\t\t\tif (single)\n\t\t\t\tbreak;\n\t\t}\n\t}\n\n\tvoid loop(bool single = false)\n\t{\n#ifdef HAVE_CUDA\n\t\tif (_cuda_device_nr >= 0) {\n\t\t\tloop_cuda(single);\n\t\t\treturn;\n\t\t}\n#endif // CUDA\n\t\tvector<trail_type> work(256);\n\t\tvector< pair<trail_type,trail_type> > collisions;\n\t\twhile (true)\n\t\t{\n\t\t\t// generate a batch of new trail starting points\n\t\t\t{\n\t\t\t\tLOCK_GLOBAL_MUTEX;\t\t\t\t\n\t\t\t\tif (quit) return;\n\t\t\t\tmain_storage.get_birthdaycollisions(collisions);\n\t\t\t\twork.resize(256);\n\t\t\t\tfor (unsigned i = 0; i < work.size(); ++i)\n\t\t\t\t{\n\t\t\t\t\twork[i].start[0] = xrng128();\n\t\t\t\t\twork[i].start[1] = xrng128();\n\t\t\t\t\twork[i].start[2] = xrng128() & hybridmask;\n\t\t\t\t\twork[i].len = 0;\n\t\t\t\t\txrng128();\n\t\t\t\t\txrng128();\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (collisions.size() > 0)\n\t\t\t{\n\t\t\t\tfor (unsigned i = 0; i < collisions.size(); ++i)\n\t\t\t\t\tfind_collision(collisions[i].first, collisions[i].second);\n\t\t\t\tcollisions.clear();\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\t\n\t\t\t// generate the trails\n\t\t\tfor (unsigned i = 0; i < work.size(); ++i)\n\t\t\t\tgenerate_trail(work[i]);\n\n\t\t\t// insert the trails into the trail hash\n\t\t\t{\n\t\t\t\tLOCK_GLOBAL_MUTEX;\n\t\t\t\tfor (unsigned i = 0; i < work.size(); ++i)\n\t\t\t\t\tdistribute_trail(work[i]); \n\t\t\t}\n\n\t\t\tif (single)\n\t\t\t\tbreak;\n\t\t}\n\t}\n\n\tvoid thread_run()\n\t{\n\t\ttry \n\t\t{\n\t\t\t{\t\n\t\t\t\tLOCK_GLOBAL_MUTEX;\n#ifdef HAVE_CUDA\n\t\t\t\tif (_cuda_device_nr >= 0) {\n\t\t\t\t\tcout << \"Thread \" << id << \" created (CUDA).\" << endl;\n\t\t\t\t\tif (!_cuda_device.init(_cuda_device_nr, ihv1, ihv2, ihv2mod, msg1, msg2, hybridmask, distinguishedpointmask, maximumpathlength))\n\t\t\t\t\t\treturn;\n//\t\t\t\t\t_cuda_device.benchmark();\n\t\t\t\t} else \n#endif // CUDA\n\t\t\t\tcout << \"Thread \" << id << \" created.\" << endl;\n\t\t\t}\n\t\t\tloop();\n\t\t\tcout << \"Thread \" << id << \" exited.          \" << endl;\n\t\t} \n\t\tcatch (...) \n\t\t{\n\t\t\tcerr << \"Exception in thread \" << id << \"!         \" << endl;\n\t\t}\n\t\tLOCK_GLOBAL_MUTEX;\n\t}\n\t\n\tvoid single_run()\n\t{\n\t\tloop(true);\n\t}\n\n\tvoid operator()()\n\t{\n\t\tthread_run();\n\t}\n};\nuint32 birthday_thread::id_counter = 1;\nstruct birthday_thread_shell {\n\tbirthday_thread* bt;\n\tbirthday_thread_shell(birthday_thread* _bt): bt(_bt) {}\n\tvoid operator()() { bt->operator()(); }\n};\n\nvoid birthday(birthday_parameters& parameters)\n{\n\tprocmodn = parameters.modn;\n\tprocmodi = parameters.modi;\n\ttrail_distribution.resize(procmodn);\n\n\t// add the modi parameter to the seed\n\taddseed(parameters.modi);\n\n\thybridmask = (parameters.hybridbits==0) ? uint32(0) : (uint32(~0)>>(32-parameters.hybridbits));\n\tparameterspathtyperange = parameters.pathtyperange;\n\tmemhardlimit = parameters.memhardlimit;\n\tuint64 maxtrails = 0;\n\tif (parameters.maxblocks > 16)\n\t\tparameters.maxblocks = 16;\n\tdouble logprob = log(dist[parameters.hybridbits][parameters.pathtyperange][parameters.maxblocks])/log(double(2));\n\tif (parameters.maxblocks == 1) {\n\t\tbool loaded = false;\n\t\ttry {\n\t\t\tcout << \"Loading 'singleblockdata.bin'...\" << flush;\n\t\t\tload_bz2(singleblockdata, \"singleblockdata\", binary_archive);\n\t\t\tloaded = true;\n\t\t} catch (exception& e ) {} catch (...) {}\n\t\tif (!loaded) {\n\t\t\tcout << \"failed!\" << endl;\n\t\t\tcout << \"Loading 'singleblockdata.txt.bz2'...\" << flush;\n\t\t\ttry {\n\t\t\t\tload_bz2(singleblockdata, \"singleblockdata\", text_archive);\n\t\t\t\tloaded = true;\n\t\t\t\tsave_bz2(singleblockdata, \"singleblockdata\", binary_archive);\n\t\t\t} catch (exception& e) {} catch (...) {}\n\t\t\tif (!loaded) {\n\t\t\t\tcout << \"failed!\" << endl;\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t\tcout << \"done: \" << singleblockdata.size() << \" dIHVs loaded.\" << endl;\n\t\tlogprob = (log(double(singleblockdata.size()))/log(2.0)) - (64 - parameters.hybridbits);\n\t}\n\tdouble estcomplexity = 32.825748 - 0.5*logprob + 0.5*double(parameters.hybridbits);\n\tdouble estcollisions = 1-logprob;\n\n\tif (parameters.maxmemory != 0)\n\t{\n\t\tmaxtrails = uint64(parameters.maxmemory) << 19;\n\t\tmaxtrails /= sizeof(trail_type);\n\t}\n\tif (parameters.logpathlength < 0)\n\t{\n\t\tdouble comppertrail = pow(double(2),estcomplexity)/double(maxtrails);\n\t\tdouble logcpt = log(comppertrail)/log(double(2));\n\t\tparameters.logpathlength = unsigned(logcpt+0.9);\n\t}\n\tif (parameters.maxmemory == 0)\n\t{\n\t\tmaxtrails = pow(double(2),estcomplexity-double(parameters.logpathlength));\n\t\tuint64 tmp = (maxtrails*sizeof(trail_type))>>19;\n\t\tparameters.maxmemory = unsigned(tmp);\n\t}\n\tcout << \"Maximum amount of memory in MB for trails: \" << parameters.maxmemory << \" (local: \" << parameters.maxmemory/parameters.modn << \")\" << endl;\n\tcout << \"Estimated number of trails that will be stored:    \" << maxtrails << \" (local: \" << maxtrails/parameters.modn << \")\" << endl;\n\tcout << \"Estimated number of trails that will be generated: \" << uint64(pow(double(2),estcomplexity-parameters.logpathlength)) << endl;\n\tcout << \"Estimated complexity per trail: 2^(\" << parameters.logpathlength << \")\" << endl;\n\tcout << \"Estimated complexity on trails: 2^(\" << estcomplexity << \")\" << endl;\n\tcout << \"Estimated complexity on collisions: 2^(\" << parameters.logpathlength + estcollisions + 1.321928 << \")\" << endl;\n\tcout << endl;\n\n\tdistinguishedpointmask = 0;\n\tunsigned pathlen = parameters.logpathlength;\n\tfor (unsigned k = 0; k < unsigned(parameters.logpathlength) && k < 32; ++k)\n\t\tdistinguishedpointmask |= 1<<k;\n\n\tuint64 mpl = (uint64(1) << parameters.logpathlength)*20;\n\tmaximumpathlength = (mpl>>31) ? 0x7FFFFFFF : mpl;\n\n\tmaxblocks = parameters.maxblocks;\n\n\tfor (unsigned k = 0; k < 4; ++k)\n\t{\n\t\tprecomp1[k] = ihv1[k] = parameters.ihv1[k];\n\t\tprecomp2[k] = ihv2[k] = parameters.ihv2[k];\n\t\tihv2mod[k] = ihv2[k];\n\t}\n\tif (maxblocks == 1) {\n\t\tihv2mod[0] -= -(1<<5);\n\t\tihv2mod[3] -= -(1<<5) + (1<<25);\n\t\tihv2mod[2] -= -(1<<5) + (1<<25) + (1<<23);\n\t}\n\tfor (unsigned k = 0; k < 16; ++k)\n\t{\n\t\tmsg1[k] = parameters.msg1[k];\n\t\tmsg2[k] = parameters.msg2[k];\n\t}\n\tprecomputestate(precomp1, msg1);\n\tprecomputestate(precomp2, msg2);\n\t\n\tmain_storage.set_parameters(parameters);\n\tmain_storage.reserve_memory(maxtrails/parameters.modn);\n\n\tif (parameters.threads == 0 || parameters.threads > boost::thread::hardware_concurrency())\n\t\tparameters.threads = boost::thread::hardware_concurrency();\n\n\tint cuda_dev_cnt = 0;\n#ifdef HAVE_CUDA\n\tif (parameters.cuda_enabled)\n\t{\n\t\ttry\n\t\t{\n\t\t\tcuda_dev_cnt = get_num_cuda_devices();\n\t\t}\n\t\tcatch (std::exception& e)\n\t\t{\n\t\t\tstd::cerr << \"CUDA ERROR: \" << e.what() << std::endl; \n\t\t\tcuda_dev_cnt = 0; \n\t\t}\n\t\tstd::cout << \"Found \" << cuda_dev_cnt << \" CUDA devices.\" << std::endl;\n\t}\n\t// if possible save 1 cpucore for better cuda latency\n\tif (parameters.threads > 1 && cuda_dev_cnt > 0 && parameters.threads == boost::thread::hardware_concurrency())\n\t\t--parameters.threads;\n#endif\n\n\tboost::thread_group threads;\n\tvector<birthday_thread*> threads_data(parameters.threads, 0);\n\tfor (unsigned i = 0; i < threads_data.size(); ++i)\n\t{\n\t\tthreads_data[i] = new birthday_thread();\n\t\tthreads.create_thread( birthday_thread_shell(threads_data[i]) );\n\t}\n#ifdef HAVE_CUDA\n\tif (parameters.cuda_enabled) {\n\t\tfor (int i = 0; i < cuda_dev_cnt; ++i) {\n\t\t\tthreads_data.push_back(new birthday_thread(i));\n\t\t\tthreads.create_thread( birthday_thread_shell(threads_data[threads_data.size()-1]) );\n\t\t}\n\t}\n#endif\n\tif (threads_data.size() == 0)\n\t\tquit = true;\n\n\ttimer save_timer(true);\n\twhile (!quit)\n\t{\n\t\tboost::this_thread::sleep(boost::posix_time::seconds(10));\n\t\tif (procmodn > 1) {\n\t\t\tif (save_timer.time() > 60) {\n\t\t\t\tload_save_trails();\n\t\t\t\tsave_timer.start();\n\t\t\t} //else load_save_trails(false);\n\t\t}\n\t\tLOCK_GLOBAL_MUTEX;\n\t\tstatus_line();\n\t}\n\tcout << endl << \"Waiting for threads to finish...\" << flush;\n\tthreads.join_all();\n\tcout << \"done.\" << endl;\n\n\tfor (unsigned i = 0; i < threads_data.size(); ++i)\n\t\tdelete threads_data[i];\n\n}\n", "meta": {"hexsha": "a1edf9a9554a16c1ebb87da8be95f97a70f89a7e", "size": 27206, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/md5birthdaysearch/birthday.cpp", "max_stars_repo_name": "enricobacis/hashclash", "max_stars_repo_head_hexsha": "0df53bb6e3d79410e8501502c365d8200153477e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/md5birthdaysearch/birthday.cpp", "max_issues_repo_name": "enricobacis/hashclash", "max_issues_repo_head_hexsha": "0df53bb6e3d79410e8501502c365d8200153477e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/md5birthdaysearch/birthday.cpp", "max_forks_repo_name": "enricobacis/hashclash", "max_forks_repo_head_hexsha": "0df53bb6e3d79410e8501502c365d8200153477e", "max_forks_repo_licenses": ["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.3495838288, "max_line_length": 149, "alphanum_fraction": 0.6423215467, "num_tokens": 9728, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6370307944803832, "lm_q2_score": 0.5078118642792044, "lm_q1q2_score": 0.32349179534834616}}
{"text": "/***************************************************************************\n *   Copyright (C) 2006 by Nicola Bellotto                                 *\n *   nbellotto@lincoln.ac.uk                                                    *\n *                                                                         *\n *   This program is free software; you can redistribute it and/or modify  *\n *   it under the terms of the GNU General Public License as published by  *\n *   the Free Software Foundation; either version 2 of the License, or     *\n *   (at your option) any later version.                                   *\n *                                                                         *\n *   This program is distributed in the hope that it will be useful,       *\n *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *\n *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *\n *   GNU General Public License for more details.                          *\n *                                                                         *\n *   You should have received a copy of the GNU General Public License     *\n *   along with this program; if not, write to the                         *\n *   Free Software Foundation, Inc.,                                       *\n *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *\n ***************************************************************************/\n#include \"ukf.h\"\n#include <float.h>\n#include <boost/numeric/ublas/io.hpp>\n#include \"bayes_tracking/BayesFilter/matSup.hpp\"\n#include \"bayes_tracking/BayesFilter/bayesFlt.hpp\"\n\nusing namespace Bayesian_filter;\nusing namespace Bayesian_filter_matrix;\n\n\nUKFilter::UKFilter(std::size_t x_size) :\n        Kalman_state_filter(x_size),\n        Unscented_scheme(x_size),\n        z_p(Empty)\n{\n    UKFilter::x_size = x_size;\n    UKFilter::XX_size = 2*x_size+1;\n    FM::Vec x0(x_size);\n    x0.clear();\n    FM::SymMatrix P0(x_size, x_size);\n    P0.clear();\n    init(x0, P0);\n}\n\n\nUKFilter::UKFilter(const FM::Vec& x0, const FM::SymMatrix& P0) :\n        Kalman_state_filter(x0.size()),\n        Unscented_scheme(x0.size()),\n        z_p(Empty)\n{\n    UKFilter::x_size = x0.size();\n    UKFilter::XX_size = 2*x0.size()+1;\n    init(x0, P0);\n}\n\n\nUKFilter::~UKFilter()\n{\n}\n\n\nvoid UKFilter::init(const FM::Vec& x0, const FM::SymMatrix& P0)\n{\n    init_kalman(x0, P0);\n}\n\n\nvoid UKFilter::update(Additive_predict_model& predict_model,\n                      Correlated_additive_observe_model& observe_model,\n                      const FM::Vec& z)\n{\n    predict(predict_model);\n    observe(observe_model, z);\n}\n\n\nvoid UKFilter::predict_observation(Correlated_additive_observe_model& observe_model, FM::Vec& z_pred, FM::SymMatrix& R_pred)\n{\n    std::size_t z_size = z_pred.size();\n    ColMatrix zXX(z_size, 2*x_size+1);\n    SymMatrix Xzz(z_size,z_size);\n    Matrix Xxz(x_size,z_size);\n\n    z_p.resize(z_size);\n    observe_size (z_size);  // Dynamic sizing\n\n    // Create unscented distribution\n    kappa = observe_Kappa(x_size);\n    Float x_kappa = Float(x_size) + kappa;\n    unscented (XX, x, X, x_kappa);\n\n    // Predict points of XX using supplied observation model\n    {\n        Vec zXXi(z_size), zXX0(z_size);\n        zXX0 = static_cast<Correlated_additive_observe_model&>(observe_model).h( column(XX,0) );\n        column(zXX,0) = zXX0;\n        for (std::size_t i = 1; i < XX.size2(); ++i) {\n            zXXi = static_cast<Correlated_additive_observe_model&>(observe_model).h( column(XX,i) );\n            // Normalise relative to zXX0\n            observe_model.normalise (zXXi, zXX0);\n            column(zXX,i) = zXXi;\n        }\n    }\n\n    // Mean of predicted distribution: z_p\n    noalias(z_p) = column(zXX,0) * kappa;\n    for (std::size_t i = 1; i < zXX.size2(); ++i) {\n        noalias(z_p) += column(zXX,i) / Float(2); // ISSUE uBlas may not be able to promote integer 2\n    }\n    z_pred = z_p /= x_kappa;\n\n    // Covariance of observation predict: Xzz\n    // Subtract mean from each point in zXX\n    for (std::size_t i = 0; i < XX_size; ++i) {\n        column(zXX,i).minus_assign (z_p);\n    }\n    // Center point, premult here by 2 for efficency\n    {\n        ColMatrix::Column zXX0 = column(zXX,0);\n        noalias(Xzz) = FM::outer_prod(zXX0, zXX0);\n        Xzz *= 2*kappa;\n    }\n    // Remaining unscented points\n    for (std::size_t i = 1; i < zXX.size2(); ++i) {\n        ColMatrix::Column zXXi = column(zXX,i);\n        noalias(Xzz) += FM::outer_prod(zXXi, zXXi);\n    }\n    Xzz /= 2*x_kappa;\n\n\n    /** Fix for non-positive semidefinite covariance **/\n    {\n        ColMatrix::Column zXX0 = column(zXX,0);      // mean zp already subtracted above\n        noalias(Xzz) += FM::outer_prod(zXX0, zXX0);  // modified covariance about mean\n    }\n\n\n    R_pred = Xzz;\n\n//    // Correlation of state with observation: Xxz\n//    // Center point, premult here by 2 for efficency\n//    {\n//       noalias(Xxz) = FM::outer_prod(column(XX,0) - x, column(zXX,0));\n//       Xxz *= 2*kappa;\n//    }\n//    // Remaining unscented points\n//    for (std::size_t i = 1; i < zXX.size2(); ++i) {\n//       noalias(Xxz) += FM::outer_prod(column(XX,i) - x, column(zXX,i));\n//    }\n//    Xxz /= 2* (Float(x_size) + kappa);\n}\n\n\nBayes_base::Float UKFilter::observeInnovation(Correlated_additive_observe_model& h, const Vec& si, const SymMatrix& Si)\n/*\n * Observation fusion\n *  Pre : x,X\n *  Post: x,X is PSD\n */\n{\n    std::size_t z_size = si.size();\n    ColMatrix zXX (z_size, 2*x_size+1);\n    Vec zp(z_size);\n    SymMatrix Xzz(z_size,z_size);\n    Matrix Xxz(x_size,z_size);\n    Matrix W(x_size,z_size);\n\n    observe_size (si.size());   // Dynamic sizing\n\n    // Create unscented distribution\n    kappa = observe_Kappa(x_size);\n    Float x_kappa = Float(x_size) + kappa;\n    unscented (XX, x, X, x_kappa);\n\n    // Predict points of XX using supplied observation model\n    {\n        Vec zXXi(z_size), zXX0(z_size);\n        zXX0 = h.h( column(XX,0) );\n        column(zXX,0) = zXX0;\n        for (std::size_t i = 1; i < XX.size2(); ++i) {\n            zXXi = h.h( column(XX,i) );\n            // Normalise relative to zXX0\n            h.normalise (zXXi, zXX0);\n            column(zXX,i) = zXXi;\n        }\n    }\n\n    // Mean of predicted distribution: zp\n    noalias(zp) = column(zXX,0) * kappa;\n    for (std::size_t i = 1; i < zXX.size2(); ++i) {\n        noalias(zp) += column(zXX,i) / Float(2); // ISSUE uBlas may not be able to promote integer 2\n    }\n    zp /= x_kappa;\n\n    // Covariance of observation predict: Xzz\n    // Subtract mean from each point in zXX\n    for (std::size_t i = 0; i < XX_size; ++i) {\n        column(zXX,i).minus_assign (zp);\n    }\n    // Center point, premult here by 2 for efficency\n    {\n        ColMatrix::Column zXX0 = column(zXX,0);\n        noalias(Xzz) = FM::outer_prod(zXX0, zXX0);\n        Xzz *= 2*kappa;\n    }\n    // Remaining unscented points\n    for (std::size_t i = 1; i < zXX.size2(); ++i) {\n        ColMatrix::Column zXXi = column(zXX,i);\n        noalias(Xzz) += FM::outer_prod(zXXi, zXXi);\n    }\n    Xzz /= 2*x_kappa;\n\n\n    /** Fix for non-positive semidefinite covariance **/\n    {\n        ColMatrix::Column zXX0 = column(zXX,0);      // mean zp already subtracted above\n        noalias(Xzz) += FM::outer_prod(zXX0, zXX0);  // modified covariance about mean\n    }\n\n\n    // Correlation of state with observation: Xxz\n    // Center point, premult here by 2 for efficency\n    {\n        noalias(Xxz) = FM::outer_prod(column(XX,0) - x, column(zXX,0));\n        Xxz *= 2*kappa;\n    }\n    // Remaining unscented points\n    for (std::size_t i = 1; i < zXX.size2(); ++i) {\n        noalias(Xxz) += FM::outer_prod(column(XX,i) - x, column(zXX,i));\n    }\n    Xxz /= 2* (Float(x_size) + kappa);\n\n    // Innovation covariance\n    S = Xzz;\n    noalias(S) += h.Z;\n    // Inverse innovation covariance\n    Float rcond = UdUinversePD (SI, S);\n    rclimit.check_PD(rcond, \"S not PD in observeInnovation\");\n    // Kalman gain\n    noalias(W) = prod(Xxz,SI);\n\n    // Store innovation\n    noalias(s) = si;\n\n    // Filter update\n    noalias(x) += prod(W,s);\n    RowMatrix WStemp(W.size1(), S.size2());\n    // update state cov with modified innovation cov\n    noalias(X) -= prod_SPD(W, Si, WStemp);\n\n    return rcond;\n}\n\n\n\ndouble UKFilter::logLikelihood() {\n    SymMatrix Si(S.size1(), S.size2());\n    Float detS;\n    Float rcond = UdUinversePD(Si, detS, S);  // Si = inv(S)\n    Numerical_rcond rclimit;\n    rclimit.check_PD(rcond, \"S not PD in UKFilter::logLikelihood\");\n    // exp(-0.5 * (s' * Si * s)) / sqrt(2pi^ns * |S|)\n    return -0.5*(inner_prod(trans(s),prod(Si, s))) - 0.5*((double)s.size()*log(2*M_PI)+log(detS));\n}\n\n\nvoid UKFilter::unscented(FM::ColMatrix& XX, const FM::Vec& x, const FM::SymMatrix& X, Float scale) {\n    UTriMatrix Sigma(x_size, x_size);\n\n    // Get a upper Cholesky factoriation\n    Float rcond = UCfactor(Sigma, X);\n    rclimit.check_PSD(rcond, \"X not PSD in UKFilter::unscented(...)\");\n    Sigma *= std::sqrt(scale);\n\n    // Generate XX with the same sample Mean and Covar as before\n    column(XX,0) = x;\n\n    for (std::size_t c = 0; c < x_size; ++c) {\n        UTriMatrix::Column SigmaCol = column(Sigma,c);\n        noalias(column(XX,c+1)) = x  + SigmaCol;\n        noalias(column(XX,x_size+c+1)) = x - SigmaCol;\n    }\n}\n", "meta": {"hexsha": "f35dff4864ac75c22a328b4f1542725af5689d31", "size": 9287, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/ukf.cpp", "max_stars_repo_name": "socrob/bayes_objects_tracker", "max_stars_repo_head_hexsha": "1373ac19ae5a19d0f077e703ef7a1340a82b7225", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/ukf.cpp", "max_issues_repo_name": "socrob/bayes_objects_tracker", "max_issues_repo_head_hexsha": "1373ac19ae5a19d0f077e703ef7a1340a82b7225", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/ukf.cpp", "max_forks_repo_name": "socrob/bayes_objects_tracker", "max_forks_repo_head_hexsha": "1373ac19ae5a19d0f077e703ef7a1340a82b7225", "max_forks_repo_licenses": ["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.816254417, "max_line_length": 124, "alphanum_fraction": 0.5705825347, "num_tokens": 2668, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7520125848754472, "lm_q2_score": 0.4301473485858429, "lm_q1q2_score": 0.3234762194873598}}
{"text": "/*===================================================================\n\nThe Medical Imaging Interaction Toolkit (MITK)\n\nCopyright (c) German Cancer Research Center,\nDivision of Medical and Biological Informatics.\nAll rights reserved.\n\nThis software is distributed WITHOUT ANY WARRANTY; without\neven the implied warranty of MERCHANTABILITY or FITNESS FOR\nA PARTICULAR PURPOSE.\n\nSee LICENSE.txt or http://www.mitk.org for details.\n\n===================================================================*/\n\n#include \"mitkDiffusionFunctionCollection.h\"\n#include \"mitkNumericTypes.h\"\n\n#include <boost/math/special_functions/legendre.hpp>\n#include <boost/math/special_functions/spherical_harmonic.hpp>\n#include <boost/version.hpp>\n#include <itkPointShell.h>\n#include \"itkVectorContainer.h\"\n#include \"vnl/vnl_vector.h\"\n#include <vtkBox.h>\n#include <vtkMath.h>\n#include <itksys/SystemTools.hxx>\n#include <boost/algorithm/string.hpp>\n\n// Intersect a finite line (with end points p0 and p1) with all of the\n// cells of a vtkImageData\nstd::vector< std::pair< itk::Index<3>, double > > mitk::imv::IntersectImage(const itk::Vector<double,3>& spacing, itk::Index<3>& si, itk::Index<3>& ei, itk::ContinuousIndex<float, 3>& sf, itk::ContinuousIndex<float, 3>& ef)\n{\n  std::vector< std::pair< itk::Index<3>, double > > out;\n  if (si == ei)\n  {\n    double d[3];\n    for (int i=0; i<3; ++i)\n      d[i] = (sf[i]-ef[i])*spacing[i];\n    double len = std::sqrt( d[0]*d[0] + d[1]*d[1] + d[2]*d[2] );\n    out.push_back(  std::pair< itk::Index<3>, double >(si, len) );\n    return out;\n  }\n\n  double bounds[6];\n\n  double entrancePoint[3];\n  double exitPoint[3];\n\n  double startPoint[3];\n  double endPoint[3];\n\n  double t0, t1;\n  for (int i=0; i<3; ++i)\n  {\n    startPoint[i] = sf[i];\n    endPoint[i] = ef[i];\n\n    if (si[i]>ei[i])\n    {\n      int t = si[i];\n      si[i] = ei[i];\n      ei[i] = t;\n    }\n  }\n\n  for (int x = si[0]; x<=ei[0]; ++x)\n    for (int y = si[1]; y<=ei[1]; ++y)\n      for (int z = si[2]; z<=ei[2]; ++z)\n      {\n        bounds[0] = (double)x - 0.5;\n        bounds[1] = (double)x + 0.5;\n        bounds[2] = (double)y - 0.5;\n        bounds[3] = (double)y + 0.5;\n        bounds[4] = (double)z - 0.5;\n        bounds[5] = (double)z + 0.5;\n\n        int entryPlane;\n        int exitPlane;\n        int hit = vtkBox::IntersectWithLine(bounds,\n                                            startPoint,\n                                            endPoint,\n                                            t0,\n                                            t1,\n                                            entrancePoint,\n                                            exitPoint,\n                                            entryPlane,\n                                            exitPlane);\n        if (hit)\n        {\n          if (entryPlane>=0 && exitPlane>=0)\n          {\n            double d[3];\n            for (int i=0; i<3; ++i)\n              d[i] = (exitPoint[i] - entrancePoint[i])*spacing[i];\n            double len = std::sqrt( d[0]*d[0] + d[1]*d[1] + d[2]*d[2] );\n\n            itk::Index<3> idx; idx[0] = x; idx[1] = y; idx[2] = z;\n            out.push_back(  std::pair< itk::Index<3>, double >(idx, len) );\n          }\n          else if (entryPlane>=0)\n          {\n            double d[3];\n            for (int i=0; i<3; ++i)\n              d[i] = (ef[i] - entrancePoint[i])*spacing[i];\n            double len = std::sqrt( d[0]*d[0] + d[1]*d[1] + d[2]*d[2] );\n\n            itk::Index<3> idx; idx[0] = x; idx[1] = y; idx[2] = z;\n            out.push_back(  std::pair< itk::Index<3>, double >(idx, len) );\n          }\n          else if (exitPlane>=0)\n          {\n            double d[3];\n            for (int i=0; i<3; ++i)\n              d[i] = (exitPoint[i]-sf[i])*spacing[i];\n            double len = std::sqrt( d[0]*d[0] + d[1]*d[1] + d[2]*d[2] );\n\n            itk::Index<3> idx; idx[0] = x; idx[1] = y; idx[2] = z;\n            out.push_back(  std::pair< itk::Index<3>, double >(idx, len) );\n          }\n        }\n      }\n  return out;\n}\n\n//------------------------- SH-function ------------------------------------\n\ndouble mitk::sh::factorial(int number) {\n  if(number <= 1) return 1;\n  double result = 1.0;\n  for(int i=1; i<=number; i++)\n    result *= i;\n  return result;\n}\n\nvoid mitk::sh::Cart2Sph(double x, double y, double z, double *spherical)\n{\n  double phi, th, rad;\n  rad = sqrt(x*x+y*y+z*z);\n  if( rad < mitk::eps )\n  {\n    th = itk::Math::pi/2;\n    phi = itk::Math::pi/2;\n  }\n  else\n  {\n    th = acos(z/rad);\n    phi = atan2(y, x);\n  }\n  spherical[0] = phi;\n  spherical[1] = th;\n  spherical[2] = rad;\n}\n\nvnl_vector_fixed<double, 3> mitk::sh::Sph2Cart(const double& theta, const double& phi, const double& rad)\n{\n  vnl_vector_fixed<double, 3> dir;\n  dir[0] = rad * sin(theta) * cos(phi);\n  dir[1] = rad * sin(theta) * sin(phi);\n  dir[2] = rad * cos(theta);\n  return dir;\n}\n\ndouble mitk::sh::legendre0(int l)\n{\n  if( l%2 != 0 )\n  {\n    return 0;\n  }\n  else\n  {\n    double prod1 = 1.0;\n    for(int i=1;i<l;i+=2) prod1 *= i;\n    double prod2 = 1.0;\n    for(int i=2;i<=l;i+=2) prod2 *= i;\n    return pow(-1.0,l/2.0)*(prod1/prod2);\n  }\n}\n\ndouble mitk::sh::Yj(int m, int l, float theta, float phi, bool mrtrix)\n{\n  if (!mrtrix)\n  {\n    if (m<0)\n      return sqrt(2.0)*::boost::math::spherical_harmonic_r(l, -m, theta, phi);\n    else if (m==0)\n      return ::boost::math::spherical_harmonic_r(l, m, theta, phi);\n    else\n      return pow(-1.0,m)*sqrt(2.0)*::boost::math::spherical_harmonic_i(l, m, theta, phi);\n  }\n  else\n  {\n    double plm = ::boost::math::legendre_p<float>(l,abs(m),-cos(theta));\n    double mag = sqrt((double)(2*l+1)/(4.0*itk::Math::pi)*::boost::math::factorial<float>(l-abs(m))/::boost::math::factorial<float>(l+abs(m)))*plm;\n    if (m>0)\n      return mag*cos(m*phi);\n    else if (m==0)\n      return mag;\n    else\n      return mag*sin(-m*phi);\n  }\n\n  return 0;\n}\n\nvnl_matrix<float> mitk::sh::CalcShBasisForDirections(int sh_order, vnl_matrix<double> U, bool mrtrix)\n{\n  vnl_matrix<float> sh_basis  = vnl_matrix<float>(U.cols(), (sh_order*sh_order + sh_order + 2)/2 + sh_order );\n  for(unsigned int i=0; i<U.cols(); i++)\n  {\n    double x = U(0,i);\n    double y = U(1,i);\n    double z = U(2,i);\n    double spherical[3];\n    mitk::sh::Cart2Sph(x,y,z,spherical);\n    U(0,i) = spherical[0];\n    U(1,i) = spherical[1];\n    U(2,i) = spherical[2];\n  }\n\n  for(unsigned int i=0; i<U.cols(); i++)\n  {\n    for(int k=0; k<=sh_order; k+=2)\n    {\n      for(int m=-k; m<=k; m++)\n      {\n        int j = (k*k + k + 2)/2 + m - 1;\n        double phi = U(0,i);\n        double th = U(1,i);\n        sh_basis(i,j) = mitk::sh::Yj(m,k,th,phi, mrtrix);\n      }\n    }\n  }\n\n  return sh_basis;\n}\n\nfloat mitk::sh::GetValue(const vnl_vector<float> &coefficients, const int &sh_order, const double theta, const double phi, const bool mrtrix)\n{\n  float val = 0;\n  for(int k=0; k<=sh_order; k+=2)\n  {\n    for(int m=-k; m<=k; m++)\n    {\n      int j = (k*k + k + 2)/2 + m - 1;\n      val += coefficients[j] * mitk::sh::Yj(m, k, theta, phi, mrtrix);\n    }\n  }\n\n  return val;\n}\n\nfloat mitk::sh::GetValue(const vnl_vector<float> &coefficients, const int &sh_order, const vnl_vector_fixed<double, 3> &dir, const bool mrtrix)\n{\n  double spherical[3];\n  mitk::sh::Cart2Sph(dir[0], dir[1], dir[2], spherical);\n\n  float val = 0;\n  for(int k=0; k<=sh_order; k+=2)\n  {\n    for(int m=-k; m<=k; m++)\n    {\n      int j = (k*k + k + 2)/2 + m - 1;\n      val += coefficients[j] * mitk::sh::Yj(m, k, spherical[1], spherical[0], mrtrix);\n    }\n  }\n\n  return val;\n}\n\n//------------------------- gradients-function ------------------------------------\n\n\nmitk::gradients::GradientDirectionContainerType::Pointer mitk::gradients::ReadBvalsBvecs(std::string bvals_file, std::string bvecs_file, double& reference_bval)\n{\n  mitk::gradients::GradientDirectionContainerType::Pointer directioncontainer = mitk::gradients::GradientDirectionContainerType::New();\n\n  std::vector<float> bvec_entries;\n  if (!itksys::SystemTools::FileExists(bvecs_file))\n    mitkThrow() << \"bvecs file not existing: \" << bvecs_file;\n  else\n  {\n    std::string line;\n    std::ifstream myfile (bvecs_file.c_str());\n    if (myfile.is_open())\n    {\n      while (std::getline(myfile, line))\n      {\n        std::vector<std::string> strs;\n        boost::split(strs,line,boost::is_any_of(\"\\t \\n\"));\n        for (auto token : strs)\n        {\n          if (!token.empty())\n          {\n            try\n            {\n              bvec_entries.push_back(boost::lexical_cast<float>(token));\n            }\n            catch(...)\n            {\n              mitkThrow() << \"Encountered invalid bvecs file entry >\" << token << \"<\";\n            }\n          }\n        }\n      }\n      myfile.close();\n    }\n    else\n    {\n      mitkThrow() << \"bvecs file could not be opened: \" << bvals_file;\n    }\n  }\n\n  reference_bval = -1;\n  std::vector<float> bval_entries;\n  if (!itksys::SystemTools::FileExists(bvals_file))\n    mitkThrow() << \"bvals file not existing: \" << bvals_file;\n  else\n  {\n    std::string line;\n    std::ifstream myfile (bvals_file.c_str());\n    if (myfile.is_open())\n    {\n      while (std::getline(myfile, line))\n      {\n        std::vector<std::string> strs;\n        boost::split(strs,line,boost::is_any_of(\"\\t \\n\"));\n        for (auto token : strs)\n        {\n          if (!token.empty())\n          {\n            try {\n              bval_entries.push_back(boost::lexical_cast<float>(token));\n              if (bval_entries.back()>reference_bval)\n                reference_bval = bval_entries.back();\n            }\n            catch(...)\n            {\n              mitkThrow() << \"Encountered invalid bvals file entry >\" << token << \"<\";\n            }\n          }\n        }\n      }\n      myfile.close();\n    }\n    else\n    {\n      mitkThrow() << \"bvals file could not be opened: \" << bvals_file;\n    }\n  }\n\n  for(unsigned int i=0; i<bval_entries.size(); i++)\n  {\n    double b_val = bval_entries.at(i);\n\n    mitk::gradients::GradientDirectionType vec;\n    vec[0] = bvec_entries.at(i);\n    vec[1] = bvec_entries.at(i+bval_entries.size());\n    vec[2] = bvec_entries.at(i+2*bval_entries.size());\n\n    // Adjust the vector length to encode gradient strength\n    double factor = b_val/reference_bval;\n    if(vec.magnitude() > 0)\n    {\n      vec.normalize();\n      vec[0] = sqrt(factor)*vec[0];\n      vec[1] = sqrt(factor)*vec[1];\n      vec[2] = sqrt(factor)*vec[2];\n    }\n\n    directioncontainer->InsertElement(i,vec);\n  }\n\n  return directioncontainer;\n}\n\nvoid mitk::gradients::WriteBvalsBvecs(std::string bvals_file, std::string bvecs_file, GradientDirectionContainerType::Pointer gradients, double reference_bval)\n{\n  std::ofstream myfile;\n  myfile.open (bvals_file.c_str());\n  for(unsigned int i=0; i<gradients->Size(); i++)\n  {\n    double twonorm = gradients->ElementAt(i).two_norm();\n    myfile << std::round(reference_bval*twonorm*twonorm) << \" \";\n  }\n  myfile.close();\n\n  std::ofstream myfile2;\n  myfile2.open (bvecs_file.c_str());\n  for(int j=0; j<3; j++)\n  {\n    for(unsigned int i=0; i<gradients->Size(); i++)\n    {\n      GradientDirectionType direction = gradients->ElementAt(i);\n      direction.normalize();\n      myfile2 << direction.get(j) << \" \";\n    }\n    myfile2 << std::endl;\n  }\n}\n\nstd::vector<unsigned int> mitk::gradients::GetAllUniqueDirections(const BValueMap & refBValueMap, GradientDirectionContainerType *refGradientsContainer )\n{\n\n  IndiciesVector directioncontainer;\n  auto mapIterator = refBValueMap.begin();\n\n  if(refBValueMap.find(0) != refBValueMap.end() && refBValueMap.size() > 1)\n    mapIterator++; //skip bzero Values\n\n  for( ; mapIterator != refBValueMap.end(); mapIterator++){\n\n    IndiciesVector currentShell = mapIterator->second;\n\n    while(currentShell.size()>0)\n    {\n      unsigned int wntIndex = currentShell.back();\n      currentShell.pop_back();\n\n      auto containerIt = directioncontainer.begin();\n      bool directionExist = false;\n      while(containerIt != directioncontainer.end())\n      {\n        if (fabs(dot_product(refGradientsContainer->ElementAt(*containerIt), refGradientsContainer->ElementAt(wntIndex)))  > 0.9998)\n        {\n          directionExist = true;\n          break;\n        }\n        containerIt++;\n      }\n      if(!directionExist)\n      {\n        directioncontainer.push_back(wntIndex);\n      }\n    }\n  }\n\n  return directioncontainer;\n}\n\n\nbool mitk::gradients::CheckForDifferingShellDirections(const BValueMap & refBValueMap, GradientDirectionContainerType::ConstPointer refGradientsContainer)\n{\n  auto mapIterator = refBValueMap.begin();\n\n  if(refBValueMap.find(0) != refBValueMap.end() && refBValueMap.size() > 1)\n    mapIterator++; //skip bzero Values\n\n  for( ; mapIterator != refBValueMap.end(); mapIterator++){\n\n    auto mapIterator_2 = refBValueMap.begin();\n    if(refBValueMap.find(0) != refBValueMap.end() && refBValueMap.size() > 1)\n      mapIterator_2++; //skip bzero Values\n\n    for( ; mapIterator_2 != refBValueMap.end(); mapIterator_2++){\n\n      if(mapIterator_2 == mapIterator) continue;\n\n      IndiciesVector currentShell = mapIterator->second;\n      IndiciesVector testShell = mapIterator_2->second;\n      for (unsigned int i = 0; i< currentShell.size(); i++)\n        if (fabs(dot_product(refGradientsContainer->ElementAt(currentShell[i]), refGradientsContainer->ElementAt(testShell[i])))  <= 0.9998) { return true; }\n\n    }\n  }\n  return false;\n}\n\nvnl_matrix<double> mitk::gradients::ComputeSphericalFromCartesian(const IndiciesVector & refShell, const GradientDirectionContainerType * refGradientsContainer)\n{\n\n  vnl_matrix<double> Q(3, refShell.size());\n  Q.fill(0.0);\n\n  for(unsigned int i = 0; i < refShell.size(); i++)\n  {\n    GradientDirectionType dir = refGradientsContainer->ElementAt(refShell[i]);\n    double x = dir.normalize().get(0);\n    double y = dir.normalize().get(1);\n    double z = dir.normalize().get(2);\n    double cart[3];\n    mitk::sh::Cart2Sph(x,y,z,cart);\n    Q(0,i) = cart[0];\n    Q(1,i) = cart[1];\n    Q(2,i) = cart[2];\n  }\n  return Q;\n}\n\nvnl_matrix<double> mitk::gradients::ComputeSphericalHarmonicsBasis(const vnl_matrix<double> & QBallReference, const unsigned int & LOrder)\n{\n  vnl_matrix<double> SHBasisOutput(QBallReference.cols(), (LOrder+1)*(LOrder+2)*0.5);\n  SHBasisOutput.fill(0.0);\n  for(int i=0; i< (int)SHBasisOutput.rows(); i++)\n    for(int k = 0; k <= (int)LOrder; k += 2)\n      for(int m =- k; m <= k; m++)\n      {\n        int j = ( k * k + k + 2 ) / 2.0 + m - 1;\n        double phi = QBallReference(0,i);\n        double th = QBallReference(1,i);\n        double val = mitk::sh::Yj(m,k,th,phi);\n        SHBasisOutput(i,j) = val;\n      }\n  return SHBasisOutput;\n}\n\nmitk::gradients::GradientDirectionContainerType::Pointer mitk::gradients::CreateNormalizedUniqueGradientDirectionContainer(const mitk::gradients::BValueMap & bValueMap,\n                                                                                                                           const GradientDirectionContainerType *origninalGradentcontainer)\n{\n  mitk::gradients::GradientDirectionContainerType::Pointer directioncontainer = mitk::gradients::GradientDirectionContainerType::New();\n  auto mapIterator = bValueMap.begin();\n\n  if(bValueMap.find(0) != bValueMap.end() && bValueMap.size() > 1){\n    mapIterator++; //skip bzero Values\n    vnl_vector_fixed<double, 3> vec;\n    vec.fill(0.0);\n    directioncontainer->push_back(vec);\n  }\n\n  for( ; mapIterator != bValueMap.end(); mapIterator++){\n\n    IndiciesVector currentShell = mapIterator->second;\n\n    while(currentShell.size()>0)\n    {\n      unsigned int wntIndex = currentShell.back();\n      currentShell.pop_back();\n\n      mitk::gradients::GradientDirectionContainerType::Iterator containerIt = directioncontainer->Begin();\n      bool directionExist = false;\n      while(containerIt != directioncontainer->End())\n      {\n        if (fabs(dot_product(containerIt.Value(), origninalGradentcontainer->ElementAt(wntIndex)))  > 0.9998)\n        {\n          directionExist = true;\n          break;\n        }\n        containerIt++;\n      }\n      if(!directionExist)\n      {\n        GradientDirectionType dir(origninalGradentcontainer->ElementAt(wntIndex));\n        directioncontainer->push_back(dir.normalize());\n      }\n    }\n  }\n\n  return directioncontainer;\n}\n", "meta": {"hexsha": "2279e3df084bfbb452dab29e79a77fb27a790587", "size": 16219, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Modules/DiffusionImaging/DiffusionCore/src/mitkDiffusionFunctionCollection.cpp", "max_stars_repo_name": "wyyrepo/MITK", "max_stars_repo_head_hexsha": "d0837f3d0d44f477b888ec498e9a2ed407e79f20", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-11-20T08:19:27.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-20T08:19:27.000Z", "max_issues_repo_path": "Modules/DiffusionImaging/DiffusionCore/src/mitkDiffusionFunctionCollection.cpp", "max_issues_repo_name": "wyyrepo/MITK", "max_issues_repo_head_hexsha": "d0837f3d0d44f477b888ec498e9a2ed407e79f20", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Modules/DiffusionImaging/DiffusionCore/src/mitkDiffusionFunctionCollection.cpp", "max_forks_repo_name": "wyyrepo/MITK", "max_forks_repo_head_hexsha": "d0837f3d0d44f477b888ec498e9a2ed407e79f20", "max_forks_repo_licenses": ["BSD-3-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.4355716878, "max_line_length": 223, "alphanum_fraction": 0.570380418, "num_tokens": 4681, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6224593312018545, "lm_q2_score": 0.519521321952093, "lm_q1q2_score": 0.3233808946074031}}
{"text": "/* Copyright (c) 2021 Grumpy Cat Software S.L.\n *\n * This Source Code is licensed under the MIT 2.0 license.\n * the terms can be found in  LICENSE.md at the root of\n * this project, or at http://mozilla.org/MPL/2.0/.\n */\n\n#include <arrayfire.h>\n#include <gauss/clustering.h>\n#include <gauss/internal/scopedHostPtr.h>\n#include <gauss/normalization.h>\n#include <gauss/linalg.h>\n#include <gauss/random.h>\n\n#include <Eigen/Eigenvalues>\n#include <limits>\n#include <random>\n#include <tuple>\n#include <iostream>\n#include <chrono>\n\nnamespace gauss::clustering\n{\n    /**\n     * Computes initial k means or centroids.\n     *\n     * @param tts       The time series.\n     * @param k         The number of centroids.\n     * @return          The new centroids.\n     */\n    af::array calculateInitialMeans(const af::array &tss, int k)\n    {\n        return af::constant(0, tss.dims(0), k, tss.type());\n    }\n\n    /**\n     * Computes The euclidean distance for a tiled time series agains k-means.\n     *\n     * @param tts       The tiled time series.\n     * @param means     The centroids.\n     * @return          The distance from a time series to all k-means.\n     */\n    af::array kEuclideanDistance(const af::array &tts, const af::array &means)\n    {\n        return af::reorder(af::sqrt(af::sum(af::pow((tts - means), 2), 0)), 1, 0);\n    }\n\n    /**\n     * Computes the euclidean distance of each time series w.r.t. all k-means.\n     *\n     * @param tss           The time series.\n     * @param means         The k-means.\n     * @param minDistance   The resulting distance for each time series to all k-means.\n     * @param labels        The ids of the closes mean for all time series.\n     */\n    void euclideanDistance(const af::array &tss, const af::array &means, af::array &minDistance, af::array &idxs)\n    {\n        auto nSeries = tss.dims(1);\n        af::array kDistances = af::constant(0.0, means.dims(1), nSeries, tss.type());\n\n        // This for loop could be parallel, not parallelized to keep memory footprint low\n        for (int i = 0; i < nSeries; i++)\n        {\n            af::array tiledSeries = af::tile(tss.col(i), 1, means.dims(1));\n            kDistances(af::span, i) = kEuclideanDistance(tiledSeries, means);\n        }\n        af::min(minDistance, idxs, kDistances, 0);\n    }\n\n    /**\n     * Compute the new means for the i-th iteration.\n     *\n     * @param tss       The time series.\n     * @param labels    The ids for each time series which indicates the closest mean.\n     * @param k         Number of means.\n     * @return          The new means.\n     */\n    af::array computeNewMeans(const af::array &tss, const af::array &labels, int k)\n    {\n        af::array labelsTiled = af::tile(labels, tss.dims(0));\n        af::array newMeans = af::constant(0.0, tss.dims(0), k, tss.type());\n\n        gfor(af::seq ii, k)\n        {\n            newMeans(af::span, ii) = af::sum(tss * (labelsTiled == ii), 1) / (af::sum(af::sum((labels == ii), 3), 1));\n        }\n        return newMeans;\n    }\n\n    /**\n     *  This function generates random labels for n time series.\n     *\n     * @param nTimeSeries   Number of time series to be labeled.\n     * @param k             The number of groups.\n     * @return              The random labels.\n     */\n    af::array generateRandomLabels(int nTimeSeries, int k)\n    {\n        std::vector<int> idx(nTimeSeries, 0);\n\n        // Fill with sequential data\n        for (int i = 0; i < nTimeSeries; i++)\n        {\n            idx[i] = i % k;\n        }\n\n        // Randomize\n        std::shuffle(idx.begin(), idx.end(), std::mt19937(std::random_device()()));\n        return af::array(nTimeSeries, 1, idx.data());\n    }\n\n    /**\n     * Computes the means' difference between two iterations.\n     *\n     * @param means     The last iteration means\n     * @param newMeans  The newMeans\n     * @return          The accumulated change ratio between iterations.\n     */\n    float computeError(const af::array &means, const af::array &newMeans)\n    {\n        auto err = af::sum(af::sqrt(af::sum(af::pow(means - newMeans, 2), 0)));\n        if (err.type() != af::dtype::f32)\n            err = err.as(af::dtype::f32);\n        return err.scalar<float>();\n    }\n\n\n    void kMeans(const af::array &tss, int k, af::array &centroids, af::array &labels, float tolerance, int maxIterations)\n    {\n        float error = std::numeric_limits<float>::max();\n\n        if (centroids.isempty())\n        {\n            // initial guess of means, select k random time series\n            centroids = calculateInitialMeans(tss, k);\n        }\n\n        if (labels.isempty())\n        {\n            // assigns a random centroid to every time series\n            labels = generateRandomLabels(tss.dims(1), k);\n        }\n\n        af::array distances = af::constant(0, tss.dims(1), tss.type());\n        af::array newMeans;\n        int iter = 0;\n\n        // Stop updating after convergence is reached.\n        while ((error > tolerance) && (iter < maxIterations))\n        {\n            // 1. Compute distances to current means\n            euclideanDistance(tss, centroids, distances, labels);\n\n            // 2. Compute new means\n            newMeans = computeNewMeans(tss, labels, k);\n\n            // 3. Compute convergence\n            error = computeError(centroids, newMeans);\n\n            // 4. Update Means\n            centroids = newMeans;\n            iter++;\n        }\n    }\n\n\n    //////////////////\n    // K-Shape\n    //////////////////\n\n    /**\n     * Computes the normalized crosscorrelation for all time series and all centroids.\n     *\n     * @param tss       The set of time series.\n     * @param centroids The set of centroids.\n     * @return          The computed normalized CrossCorrelation.\n     */\n    af::array ncc3Dim(const af::array &tss, const af::array &centroids) {\n        auto normtss = af::sqrt(af::sum(af::pow(tss, 2.0), 0));\n        auto normcen = af::sqrt(af::sum(af::pow(centroids, 2.0), 0));\n        auto den = af::matmulTN(normcen, normtss);\n        auto den_tiled = af::tile(den, 1, 1, (centroids.dims(0)*2)-1);\n\n        auto inv_centroids = af::flip(centroids, 0);\n        auto batched = af::reorder(inv_centroids, 0, 2, 1, 3);\n        auto convolution = af::convolve1(tss, batched, AF_CONV_EXPAND);\n        auto shaped = af::reorder(convolution, 2, 1, 0);\n        return shaped / den_tiled;\n    }\n\n    /**\n     * This function computes the assignment step. It is the update of time series labels w.r.t. the dinamics of the\n     * centroids.\n     *\n     * @param tss       The set of time series in columnar manner.\n     * @param centroids The set of centroids in columnar mode.\n     * @return          The new set of labels.\n     */\n    af::array assignmentStep(const af::array &tss, const af::array &centroids)\n    {\n        auto distances = 1.0 - af::max(ncc3Dim(tss, centroids), 2);\n        af::array min;\n        af::array labels;\n        af::min(min, labels, distances, 0);\n        return labels.T();\n    }\n\n    /**\n     * This function returns an updated shape of the centroid passed as argument w.r.t. the tss.\n     *\n     * @param tss       The subset of time series acting on the centroid.  These are znorm.\n     * @param centroid  The given centroid (which could be all zeros in the first iteration or \n     *                  znorm centroid in further iterations).\n     * @return          The updated shape of the centroid znorm.\n     */\n    af::array shapeExtraction(const af::array &tss, const af::array &centroid, const af::array &p)\n    {\n        // since data is always znorm and so are the centroids,\n        // it is not necessary to invoke sbd, ever!\n        auto s = af::matmulNT(tss, tss);\n        auto m = af::matmul(p, s, p);\n        af::array eigvec;\n        std::tie (std::ignore, eigvec) = gauss::linalg::eigh(m);\n        // last column, per eigh, is the eigenvector whose \n        // eigenval is max.\n        auto c = eigvec.col(af::end);\n        auto z_c = gauss::normalization::znorm(c, 0, 1);\n\n        auto findDistance1 = af::sqrt(af::sum(af::pow((tss.col(0) - c), 2.0)));\n        auto findDistance2 = af::sqrt(af::sum(af::pow((tss.col(0) + c), 2.0)));\n        auto condition = findDistance1 >= findDistance2;\n\n        // use select instead of 'if' \n        auto condition_tied = af::tile(condition, tss.dims(0), 1);\n        return af::select(condition_tied, -1.0 * z_c, z_c);\n    }\n\n    /**\n     * This function performs the refinement step.\n     *\n     * @param tss       The set of time series in columnar manner.\n     * @param centroids The set of centroids in columnar mode.\n     * @param labels    The set of labels.\n     * @return          The new centroids.\n     */\n    af::array refinementStep(const af::array &tss, const af::array &centroids, const af::array &labels)\n    {\n        auto ncentroids = centroids.dims(1);\n        af::array result = centroids;\n\n        // prepare p array\n        // this used to be @ shapeExtraction method but it is a constant throughout \n        // the entire process...\n        auto nelements = tss.dims(0);\n        auto scale = 1.0 / static_cast<double>(nelements);\n        auto scale_tiled = af::constant(scale, nelements, nelements, tss.type());\n        auto p = af::identity(nelements, nelements, tss.type()) - scale_tiled;\n\n        for (dim_t j = 0; j < ncentroids; j++) {\n            // current centroid\n            auto centroid = centroids.col(j);\n            // select those tss assigned to the centroid j\n            auto subset = af::lookup(tss, af::where((labels == j)), 1);\n            // if centroid j has at least one labeled time series.\n            if (!subset.isempty()) {\n                result(af::span, j) = shapeExtraction(subset, centroid, p);\n            }\n        }\n\n        return result;\n    }\n\n    void kshape_calibrate(const af::array &tss, int k, af::array &centroids, af::array &labels, const int maxIterations, const bool rnd_labels)\n    {\n        auto nTimeseries = static_cast<unsigned int>(tss.dims(1));\n        auto nElements = static_cast<unsigned int>(tss.dims(0));\n\n        if (centroids.isempty()) {\n            centroids = af::constant(0, nElements, k, tss.type());\n        }\n\n        if (labels.isempty()) {\n            labels = rnd_labels \n                ? gauss::random::randint(0, k, af::dim4(nTimeseries), af::dtype::u32)\n                : af::iota(af::dim4(nTimeseries), af::dim4(1), af::dtype::u32) % k;\n        } \n        else {\n            if (labels.dims(0) != nTimeseries) \n                throw std::invalid_argument(\"The number of labels must be equal to the number of time series\");\n            \n            if (labels.type() != af::dtype::u32) \n                labels = labels.as(af::dtype::u32);\n            \n            auto unique_labels = af::setUnique(labels, false);\n            if (unique_labels.dims(0) != k) \n                throw std::invalid_argument(\"The number of unique labels do not correspond to the number of clusters\");\n\n            if (!af::allTrue<bool>(unique_labels >= 0 && unique_labels < k))\n                throw std::invalid_argument(\"The labels should be identified with values ranging from 0 up to the number of clusters\");\n        }\n\n        auto terminate = false;\n        int iter = 0;\n\n        // 0. Ensure tss is normalized\n        auto normTSS = gauss::normalization::znorm(tss, 0, 1);\n\n        while (!terminate)\n        {\n            // 1. Refinement step. New centroids computation.\n            auto newCentroids = refinementStep(normTSS, centroids, labels);\n\n            // 2. Assignment step. New labels computation.\n            auto new_labels = assignmentStep(normTSS, newCentroids);\n\n            // 3. Update centroids\n            centroids = newCentroids;\n\n            // 4. Check if no movement in labels or max iterations reached            \n            terminate = iter++ == maxIterations || af::allTrue<bool>(new_labels == labels);\n\n            // 5. Update labels.\n            labels = new_labels;\n        }\n    }\n\n    af::array kshape_classify(const af::array &tss, const af::array &centroids) {\n        auto normTSS = gauss::normalization::znorm(tss, 0, 1);\n        return assignmentStep(normTSS, centroids);\n    }\n}", "meta": {"hexsha": "682a91ea4295e345c0b3e28d71f2e9450beeb6a5", "size": 12136, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "modules/gauss/src/clustering.cpp", "max_stars_repo_name": "shapelets/shapelets-compute", "max_stars_repo_head_hexsha": "1dffe62d4eab9b1115b95bda5aaa7a3392024d72", "max_stars_repo_licenses": ["MIT", "BSD-3-Clause"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2021-05-28T09:43:28.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T01:44:55.000Z", "max_issues_repo_path": "modules/gauss/src/clustering.cpp", "max_issues_repo_name": "shapelets/shapelets-compute", "max_issues_repo_head_hexsha": "1dffe62d4eab9b1115b95bda5aaa7a3392024d72", "max_issues_repo_licenses": ["MIT", "BSD-3-Clause"], "max_issues_count": 14.0, "max_issues_repo_issues_event_min_datetime": "2021-05-31T11:48:12.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-06T20:30:34.000Z", "max_forks_repo_path": "modules/gauss/src/clustering.cpp", "max_forks_repo_name": "shapelets/shapelets-compute", "max_forks_repo_head_hexsha": "1dffe62d4eab9b1115b95bda5aaa7a3392024d72", "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.664652568, "max_line_length": 143, "alphanum_fraction": 0.5755603164, "num_tokens": 3170, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.66192288918838, "lm_q2_score": 0.48828339529583464, "lm_q1q2_score": 0.32320595575693073}}
{"text": "/*\n * (C) Copyright 1996- ECMWF.\n *\n * This software is licensed under the terms of the Apache Licence Version 2.0\n * which can be obtained at http://www.apache.org/licenses/LICENSE-2.0.\n * In applying this licence, ECMWF does not waive the privileges and immunities\n * granted to it by virtue of its status as an intergovernmental organisation\n * nor does it submit to any jurisdiction.\n */\n\n\n#include \"eckit/linalg/dense/LinearAlgebraArmadillo.h\"\n\n#include <armadillo>\n\n#include <ostream>\n\n#include \"eckit/exception/Exceptions.h\"\n#include \"eckit/linalg/Matrix.h\"\n#include \"eckit/linalg/SparseMatrix.h\"\n#include \"eckit/linalg/Vector.h\"\n\n\nnamespace eckit {\nnamespace linalg {\nnamespace dense {\n\n\nstatic const LinearAlgebraArmadillo __la(\"armadillo\");\n\n\nusing vec_t = arma::vec;\nusing mat_t = arma::mat;\n\n\nvoid LinearAlgebraArmadillo::print(std::ostream& out) const {\n    out << \"LinearAlgebraArmadillo[]\";\n}\n\n\nScalar LinearAlgebraArmadillo::dot(const Vector& x, const Vector& y) const {\n    ASSERT(x.size() == y.size());\n\n    // Armadillo requires non-const pointers to the data for views without copy\n    vec_t xi(const_cast<Scalar*>(x.data()), x.size(), /* copy_aux_mem= */ false);\n    vec_t yi(const_cast<Scalar*>(y.data()), y.size(), /* copy_aux_mem= */ false);\n\n    return arma::dot(xi, yi);\n}\n\n\nvoid LinearAlgebraArmadillo::gemv(const Matrix& A, const Vector& x, Vector& y) const {\n    ASSERT(x.size() == A.cols());\n    ASSERT(y.size() == A.rows());\n\n    // Armadillo requires non-const pointers to the data for views without copy\n    mat_t Ai(const_cast<Scalar*>(A.data()), A.rows(), A.cols(), /* copy_aux_mem= */ false);\n    vec_t xi(const_cast<Scalar*>(x.data()), x.size(), /* copy_aux_mem= */ false);\n    vec_t yi(y.data(), y.size(), /* copy_aux_mem= */ false);\n\n    yi = Ai * xi;\n}\n\n\nvoid LinearAlgebraArmadillo::gemm(const Matrix& A, const Matrix& B, Matrix& C) const {\n    ASSERT(A.cols() == B.rows());\n    ASSERT(A.rows() == C.rows());\n    ASSERT(B.cols() == C.cols());\n\n    // Armadillo requires non-const pointers to the data for views without copy\n    mat_t Ai(const_cast<Scalar*>(A.data()), A.rows(), A.cols(), /* copy_aux_mem= */ false);\n    mat_t Bi(const_cast<Scalar*>(B.data()), B.rows(), B.cols(), /* copy_aux_mem= */ false);\n    mat_t Ci(C.data(), C.rows(), C.cols(), /* copy_aux_mem= */ false);\n\n    Ci = Ai * Bi;\n}\n\n\n}  // namespace dense\n}  // namespace linalg\n}  // namespace eckit\n", "meta": {"hexsha": "4229745dc72dc043baa4210af34ba63020c7bb6f", "size": 2410, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/eckit/linalg/dense/LinearAlgebraArmadillo.cc", "max_stars_repo_name": "matthewrmshin/eckit", "max_stars_repo_head_hexsha": "ea30183f8d7a65ed89abf97f86d97e02ec366144", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/eckit/linalg/dense/LinearAlgebraArmadillo.cc", "max_issues_repo_name": "matthewrmshin/eckit", "max_issues_repo_head_hexsha": "ea30183f8d7a65ed89abf97f86d97e02ec366144", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/eckit/linalg/dense/LinearAlgebraArmadillo.cc", "max_forks_repo_name": "matthewrmshin/eckit", "max_forks_repo_head_hexsha": "ea30183f8d7a65ed89abf97f86d97e02ec366144", "max_forks_repo_licenses": ["Apache-2.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.3902439024, "max_line_length": 91, "alphanum_fraction": 0.6680497925, "num_tokens": 647, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6619228758499942, "lm_q2_score": 0.4882833952958347, "lm_q1q2_score": 0.32320594924401846}}
{"text": "//---------------------------------------------------------------------------//\n// Copyright (c) 2021 Mikhail Komarov <nemo@nil.foundation>\n// Copyright (c) 2021 Ilias Khairullin <ilias@nil.foundation>\n//\n// MIT License\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in all\n// copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n// SOFTWARE.\n//---------------------------------------------------------------------------//\n\n#ifndef CRYPTO3_ACCUMULATORS_PUBKEY_SSS_DEAL_SHARES_HPP\n#define CRYPTO3_ACCUMULATORS_PUBKEY_SSS_DEAL_SHARES_HPP\n\n#include <cstddef>\n#include <set>\n#include <utility>\n#include <algorithm>\n#include <iterator>\n\n#include <boost/concept_check.hpp>\n\n#include <boost/accumulators/framework/accumulator_base.hpp>\n#include <boost/accumulators/framework/parameters/sample.hpp>\n\n#include <nil/crypto3/pubkey/accumulators/parameters/threshold_value.hpp>\n#include <nil/crypto3/pubkey/accumulators/parameters/iterator_last.hpp>\n#include <nil/crypto3/pubkey/accumulators/parameters/weights.hpp>\n\n#include <nil/crypto3/pubkey/secret_sharing/shamir.hpp>\n#include <nil/crypto3/pubkey/secret_sharing/feldman.hpp>\n#include <nil/crypto3/pubkey/secret_sharing/pedersen.hpp>\n#include <nil/crypto3/pubkey/secret_sharing/weighted_shamir.hpp>\n\n#include <nil/crypto3/pubkey/modes/isomorphic.hpp>\n\nnamespace nil {\n    namespace crypto3 {\n        namespace pubkey {\n            namespace accumulators {\n                namespace impl {\n                    template<typename ProcessingMode, typename = void>\n                    struct deal_shares_impl;\n\n                    template<typename ProcessingMode>\n                    struct deal_shares_impl<ProcessingMode> : boost::accumulators::accumulator_base {\n                    protected:\n                        typedef ProcessingMode processing_mode_type;\n                        typedef typename processing_mode_type::scheme_type scheme_type;\n                        typedef typename processing_mode_type::op_type op_type;\n                        typedef typename processing_mode_type::internal_accumulator_type internal_accumulator_type;\n\n                    public:\n                        typedef typename processing_mode_type::result_type result_type;\n\n                        //\n                        // boost::accumulators::sample -- participants number\n                        //\n                        // nil::crypto3::accumulators::threshold_value -- threshold number of participants\n                        //\n                        template<typename Args>\n                        deal_shares_impl(const Args &args) :\n                            seen_coeffs(0), n(args[boost::accumulators::sample]),\n                            t(args[nil::crypto3::accumulators::threshold_value]) {\n                            if constexpr (std::is_same<weighted_shamir_sss<typename scheme_type::group_type>,\n                                                       scheme_type>::value) {\n                                processing_mode_type::init_accumulator(\n                                    acc, n, t, args[nil::crypto3::accumulators::weights]);\n                            } else {\n                                processing_mode_type::init_accumulator(acc, n, t);\n                            }\n                        }\n\n                        inline result_type result(boost::accumulators::dont_care) const {\n                            assert(t == seen_coeffs);\n\n                            return processing_mode_type::process(acc);\n                        }\n\n                        //\n                        // boost::accumulators::sample -- polynomial coefficients\n                        // input coefficients should be supplied in increasing term degrees order\n                        //\n                        template<typename Args>\n                        inline void operator()(const Args &args) {\n                            resolve_type(args[boost::accumulators::sample],\n                                         args[::nil::crypto3::accumulators::iterator_last | nullptr]);\n                        }\n\n                    protected:\n                        inline void resolve_type(const typename scheme_type::coeff_type &coeff,\n                                                 std::nullptr_t = nullptr) {\n                            if (t == seen_coeffs) {\n                                return;\n                            }\n\n                            processing_mode_type::update(acc, seen_coeffs, coeff);\n                            seen_coeffs++;\n                        }\n\n                        template<typename InputRange>\n                        inline void resolve_type(const InputRange &range, std::nullptr_t) {\n                            for (const auto &c : range) {\n                                resolve_type(c);\n                            }\n                        }\n\n                        template<typename InputIterator>\n                        inline void resolve_type(InputIterator first, InputIterator last) {\n                            for (auto it = first; it != last; it++) {\n                                resolve_type(*it);\n                            }\n                        }\n\n                        std::size_t n;\n                        std::size_t t;\n                        std::size_t seen_coeffs;\n                        mutable internal_accumulator_type acc;\n                    };\n\n                    // template<typename ProcessingMode>\n                    // struct deal_shares_impl<\n                    //     ProcessingMode,\n                    //     typename std::enable_if<std::is_same<\n                    //         typename ProcessingMode::scheme_type,\n                    //         pubkey::weighted_shamir_sss<typename\n                    //         ProcessingMode::scheme_type::group_type>>::value>::type>\n                    //     : boost::accumulators::accumulator_base {\n                    // protected:\n                    //     typedef typename ProcessingMode::scheme_type scheme_type;\n                    //     typedef typename ProcessingMode::op_type op_type;\n                    //\n                    //     typedef typename op_type::coeffs_type coeffs_type;\n                    //     typedef typename op_type::weight_type weight_type;\n                    //     typedef typename op_type::weights_type weights_type;\n                    //     typedef typename op_type::shares_type shares_type;\n                    //\n                    // public:\n                    //     typedef shares_type result_type;\n                    //\n                    //     //\n                    //     // boost::accumulators::sample -- participants number\n                    //     //\n                    //     // nil::crypto3::accumulators::threshold_value -- threshold number of participants\n                    //     //\n                    //     template<typename Args>\n                    //     deal_shares_impl(const Args &args) : seen_coeffs(0) {\n                    //         assert(op_type::check_t(args[nil::crypto3::accumulators::threshold_value],\n                    //                                  args[boost::accumulators::sample]));\n                    //         t = args[nil::crypto3::accumulators::threshold_value];\n                    //         n = args[boost::accumulators::sample];\n                    //         std::size_t i = 1;\n                    //         std::generate_n(std::inserter(shares_weights, shares_weights.end()), n, [&i]() {\n                    //             return weight_type(i++, 1);\n                    //         });\n                    //     }\n                    //\n                    //     inline result_type result(boost::accumulators::dont_care) const {\n                    //         assert(t == seen_coeffs);\n                    //         return op_type::deal_shares(coeffs, shares_weights);\n                    //     }\n                    //\n                    //     //\n                    //     // boost::accumulators::sample -- participant weight\n                    //     // or\n                    //     // boost::accumulators::sample -- polynomial coefficients\n                    //     // input coefficients should be supplied in increasing term degrees order\n                    //     //\n                    //     template<typename Args>\n                    //     inline void operator()(const Args &args) {\n                    //         resolve_type(\n                    //             args[boost::accumulators::sample],\n                    //             args[::nil::crypto3::accumulators::iterator_last | typename\n                    //             coeffs_type::iterator()]);\n                    //     }\n                    //\n                    // protected:\n                    //     template<typename Coeff,\n                    //              typename InputIterator,\n                    //              typename op_type::template check_coeff_type<Coeff> = true>\n                    //     inline void resolve_type(const Coeff &coeff, InputIterator) {\n                    //         assert(t > seen_coeffs);\n                    //         coeffs.emplace_back(coeff);\n                    //         seen_coeffs++;\n                    //     }\n                    //\n                    //     template<typename Coeffs,\n                    //              typename InputIterator,\n                    //              typename op_type::template check_coeff_type<typename Coeffs::value_type> = true>\n                    //     inline void resolve_type(const Coeffs &coeffs, InputIterator dont_care) {\n                    //         for (const auto &c : coeffs) {\n                    //             resolve_type(c, dont_care);\n                    //         }\n                    //     }\n                    //\n                    //     template<typename InputIterator,\n                    //              typename op_type::template check_coeff_type<\n                    //                  typename std::iterator_traits<InputIterator>::value_type> = true>\n                    //     inline void resolve_type(InputIterator first, InputIterator last) {\n                    //         for (auto it = first; it != last; it++) {\n                    //             resolve_type(*it, last);\n                    //         }\n                    //     }\n                    //\n                    //     template<typename Weight,\n                    //              typename InputIterator,\n                    //              typename op_type::template check_weight_type<Weight> = true>\n                    //     inline void resolve_type(const Weight &w, InputIterator) {\n                    //         assert(op_type::check_weight(w, n));\n                    //         shares_weights.insert_or_assign(w.first, w.second);\n                    //     }\n                    //\n                    //     template<typename InputIterator,\n                    //              typename op_type::template check_weight_type<\n                    //                  typename std::iterator_traits<InputIterator>::value_type> = true>\n                    //     inline void resolve_type(InputIterator first, InputIterator last) {\n                    //         for (auto it = first; it != last; it++) {\n                    //             resolve_type(*it, last);\n                    //         }\n                    //     }\n                    //\n                    //     std::size_t t;\n                    //     std::size_t n;\n                    //     std::size_t seen_coeffs;\n                    //     coeffs_type coeffs;\n                    //     weights_type shares_weights;\n                    // };\n                }    // namespace impl\n\n                namespace tag {\n                    template<typename ProcessingMode>\n                    struct deal_shares : boost::accumulators::depends_on<> {\n                        typedef ProcessingMode mode_type;\n\n                        /// INTERNAL ONLY\n                        ///\n\n                        typedef boost::mpl::always<accumulators::impl::deal_shares_impl<mode_type>> impl;\n                    };\n                }    // namespace tag\n\n                namespace extract {\n                    template<typename ProcessingMode, typename AccumulatorSet>\n                    typename boost::mpl::apply<AccumulatorSet, tag::deal_shares<ProcessingMode>>::type::result_type\n                        deal_shares(const AccumulatorSet &acc) {\n                        return boost::accumulators::extract_result<tag::deal_shares<ProcessingMode>>(acc);\n                    }\n                }    // namespace extract\n            }        // namespace accumulators\n        }            // namespace pubkey\n    }                // namespace crypto3\n}    // namespace nil\n\n#endif    // CRYPTO3_ACCUMULATORS_PUBKEY_SSS_DEAL_SHARES_HPP\n", "meta": {"hexsha": "0b89720ba121bcdefdc2602b7dd9df4e909e7f30", "size": 13853, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/nil/crypto3/pubkey/accumulators/deal_shares.hpp", "max_stars_repo_name": "NilFoundation/pubkey", "max_stars_repo_head_hexsha": "3b146d6ed14e127be57895a08846c9e1eea4eade", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-09-23T02:25:55.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-23T02:25:55.000Z", "max_issues_repo_path": "include/nil/crypto3/pubkey/accumulators/deal_shares.hpp", "max_issues_repo_name": "NilFoundation/pubkey", "max_issues_repo_head_hexsha": "3b146d6ed14e127be57895a08846c9e1eea4eade", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 19.0, "max_issues_repo_issues_event_min_datetime": "2020-10-10T00:23:29.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-20T21:03:41.000Z", "max_forks_repo_path": "include/nil/crypto3/pubkey/accumulators/deal_shares.hpp", "max_forks_repo_name": "NilFoundation/pubkey", "max_forks_repo_head_hexsha": "3b146d6ed14e127be57895a08846c9e1eea4eade", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2022-02-13T21:40:05.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-16T21:39:35.000Z", "avg_line_length": 51.4981412639, "max_line_length": 116, "alphanum_fraction": 0.4756370461, "num_tokens": 2325, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6619228758499941, "lm_q2_score": 0.4882833952958347, "lm_q1q2_score": 0.3232059492440184}}
{"text": "//  Copyright John Maddock 2006.\n//  Use, modification and distribution are subject to the\n//  Boost Software License, Version 1.0. (See accompanying file\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n#ifndef BOOST_STATS_EXPONENTIAL_HPP\n#define BOOST_STATS_EXPONENTIAL_HPP\n\n#include <boost/math/distributions/fwd.hpp>\n#include <boost/math/constants/constants.hpp>\n#include <boost/math/special_functions/log1p.hpp>\n#include <boost/math/special_functions/expm1.hpp>\n#include <boost/math/distributions/complement.hpp>\n#include <boost/math/distributions/detail/common_error_handling.hpp>\n#include <boost/config/no_tr1/cmath.hpp>\n\n#ifdef BOOST_MSVC\n# pragma warning(push)\n# pragma warning(disable: 4702) // unreachable code (return after domain_error throw).\n#endif\n\n#include <utility>\n\nnamespace boost{ namespace math{\n\nnamespace detail{\n//\n// Error check:\n//\ntemplate <class RealType, class Policy>\ninline bool verify_lambda(const char* function, RealType l, RealType* presult, const Policy& pol)\n{\n   if(l <= 0)\n   {\n      *presult = policies::raise_domain_error<RealType>(\n         function,\n         \"The scale parameter \\\"lambda\\\" must be > 0, but was: %1%.\", l, pol);\n      return false;\n   }\n   return true;\n}\n\ntemplate <class RealType, class Policy>\ninline bool verify_exp_x(const char* function, RealType x, RealType* presult, const Policy& pol)\n{\n   if(x < 0)\n   {\n      *presult = policies::raise_domain_error<RealType>(\n         function,\n         \"The random variable must be >= 0, but was: %1%.\", x, pol);\n      return false;\n   }\n   return true;\n}\n\n} // namespace detail\n\ntemplate <class RealType = double, class Policy = policies::policy<> >\nclass exponential_distribution\n{\npublic:\n   typedef RealType value_type;\n   typedef Policy policy_type;\n\n   exponential_distribution(RealType lambda = 1)\n      : m_lambda(lambda)\n   {\n      RealType err;\n      detail::verify_lambda(\"boost::math::exponential_distribution<%1%>::exponential_distribution\", lambda, &err, Policy());\n   } // exponential_distribution\n\n   RealType lambda()const { return m_lambda; }\n\nprivate:\n   RealType m_lambda;\n};\n\ntypedef exponential_distribution<double> exponential;\n\ntemplate <class RealType, class Policy>\ninline const std::pair<RealType, RealType> range(const exponential_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>());\n}\n\ntemplate <class RealType, class Policy>\ninline const std::pair<RealType, RealType> support(const exponential_distribution<RealType, Policy>& /*dist*/)\n{ // Range of supported values for random variable x.\n   // This is range where cdf rises from 0 to 1, and outside it, the pdf is zero.\n   using boost::math::tools::max_value;\n   using boost::math::tools::min_value;\n   return std::pair<RealType, RealType>(min_value<RealType>(),  max_value<RealType>());\n   // min_value<RealType>() to avoid a discontinuity at x = 0.\n}\n\ntemplate <class RealType, class Policy>\ninline RealType pdf(const exponential_distribution<RealType, Policy>& dist, const RealType& x)\n{\n   BOOST_MATH_STD_USING // for ADL of std functions\n\n   static const char* function = \"boost::math::pdf(const exponential_distribution<%1%>&, %1%)\";\n\n   RealType lambda = dist.lambda();\n   RealType result;\n   if(0 == detail::verify_lambda(function, lambda, &result, Policy()))\n      return result;\n   if(0 == detail::verify_exp_x(function, x, &result, Policy()))\n      return result;\n   result = lambda * exp(-lambda * x);\n   return result;\n} // pdf\n\ntemplate <class RealType, class Policy>\ninline RealType cdf(const exponential_distribution<RealType, Policy>& dist, const RealType& x)\n{\n   BOOST_MATH_STD_USING // for ADL of std functions\n\n   static const char* function = \"boost::math::cdf(const exponential_distribution<%1%>&, %1%)\";\n\n   RealType result;\n   RealType lambda = dist.lambda();\n   if(0 == detail::verify_lambda(function, lambda, &result, Policy()))\n      return result;\n   if(0 == detail::verify_exp_x(function, x, &result, Policy()))\n      return result;\n   result = -boost::math::expm1(-x * lambda, Policy());\n\n   return result;\n} // cdf\n\ntemplate <class RealType, class Policy>\ninline RealType quantile(const exponential_distribution<RealType, Policy>& dist, const RealType& p)\n{\n   BOOST_MATH_STD_USING // for ADL of std functions\n\n   static const char* function = \"boost::math::quantile(const exponential_distribution<%1%>&, %1%)\";\n\n   RealType result;\n   RealType lambda = dist.lambda();\n   if(0 == detail::verify_lambda(function, lambda, &result, Policy()))\n      return result;\n   if(0 == detail::check_probability(function, p, &result, Policy()))\n      return result;\n\n   if(p == 0)\n      return 0;\n   if(p == 1)\n      return policies::raise_overflow_error<RealType>(function, 0, Policy());\n\n   result = -boost::math::log1p(-p, Policy()) / lambda;\n   return result;\n} // quantile\n\ntemplate <class RealType, class Policy>\ninline RealType cdf(const complemented2_type<exponential_distribution<RealType, Policy>, RealType>& c)\n{\n   BOOST_MATH_STD_USING // for ADL of std functions\n\n   static const char* function = \"boost::math::cdf(const exponential_distribution<%1%>&, %1%)\";\n\n   RealType result;\n   RealType lambda = c.dist.lambda();\n   if(0 == detail::verify_lambda(function, lambda, &result, Policy()))\n      return result;\n   if(0 == detail::verify_exp_x(function, c.param, &result, Policy()))\n      return result;\n   result = exp(-c.param * lambda);\n\n   return result;\n}\n\ntemplate <class RealType, class Policy>\ninline RealType quantile(const complemented2_type<exponential_distribution<RealType, Policy>, RealType>& c)\n{\n   BOOST_MATH_STD_USING // for ADL of std functions\n\n   static const char* function = \"boost::math::quantile(const exponential_distribution<%1%>&, %1%)\";\n\n   RealType result;\n   RealType lambda = c.dist.lambda();\n   if(0 == detail::verify_lambda(function, lambda, &result, Policy()))\n      return result;\n\n   RealType q = c.param;\n   if(0 == detail::check_probability(function, q, &result, Policy()))\n      return result;\n\n   if(q == 1)\n      return 0;\n   if(q == 0)\n      return policies::raise_overflow_error<RealType>(function, 0, Policy());\n\n   result = -log(q) / lambda;\n   return result;\n}\n\ntemplate <class RealType, class Policy>\ninline RealType mean(const exponential_distribution<RealType, Policy>& dist)\n{\n   RealType result;\n   RealType lambda = dist.lambda();\n   if(0 == detail::verify_lambda(\"boost::math::mean(const exponential_distribution<%1%>&)\", lambda, &result, Policy()))\n      return result;\n   return 1 / lambda;\n}\n\ntemplate <class RealType, class Policy>\ninline RealType standard_deviation(const exponential_distribution<RealType, Policy>& dist)\n{\n   RealType result;\n   RealType lambda = dist.lambda();\n   if(0 == detail::verify_lambda(\"boost::math::standard_deviation(const exponential_distribution<%1%>&)\", lambda, &result, Policy()))\n      return result;\n   return 1 / lambda;\n}\n\ntemplate <class RealType, class Policy>\ninline RealType mode(const exponential_distribution<RealType, Policy>& /*dist*/)\n{\n   return 0;\n}\n\ntemplate <class RealType, class Policy>\ninline RealType median(const exponential_distribution<RealType, Policy>& dist)\n{\n   using boost::math::constants::ln_two;\n   return ln_two<RealType>() / dist.lambda(); // ln(2) / lambda\n}\n\ntemplate <class RealType, class Policy>\ninline RealType skewness(const exponential_distribution<RealType, Policy>& /*dist*/)\n{\n   return 2;\n}\n\ntemplate <class RealType, class Policy>\ninline RealType kurtosis(const exponential_distribution<RealType, Policy>& /*dist*/)\n{\n   return 9;\n}\n\ntemplate <class RealType, class Policy>\ninline RealType kurtosis_excess(const exponential_distribution<RealType, Policy>& /*dist*/)\n{\n   return 6;\n}\n\n} // namespace math\n} // namespace boost\n\n#ifdef BOOST_MSVC\n# pragma warning(pop)\n#endif\n\n// This include must be at the end, *after* the accessors\n// for this distribution have been defined, in order to\n// keep compilers that support two-phase lookup happy.\n#include <boost/math/distributions/detail/derived_accessors.hpp>\n\n#endif // BOOST_STATS_EXPONENTIAL_HPP\n", "meta": {"hexsha": "44bf04240cf1907fa6457e4ad5f9dd93e642b13f", "size": 8200, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/lib/boost/math/distributions/exponential.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": 27.0, "max_stars_repo_stars_event_min_datetime": "2020-11-12T19:24:54.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-27T23:10:45.000Z", "max_issues_repo_path": "src/lib/boost/math/distributions/exponential.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/math/distributions/exponential.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": 7.0, "max_forks_repo_forks_event_min_datetime": "2018-02-05T19:34:34.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-01T08:46:34.000Z", "avg_line_length": 31.2977099237, "max_line_length": 133, "alphanum_fraction": 0.7130487805, "num_tokens": 1998, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6039318337259583, "lm_q2_score": 0.5350984286266116, "lm_q1q2_score": 0.32316297522434834}}
{"text": "#include \"stdafx.h\"\n\n#ifdef USE_EIGEN\n//#define EIGEN_DONT_VECTORIZE\n//#define EIGEN_DONT_PARALLELIZE\n#include <Eigen/Eigen>\n#include <Eigen/SVD>\n#include <opencv2/core/eigen.hpp>\n#endif\n\nusing namespace std;\nusing namespace cv;\n\nnamespace cp\n{\n\tvoid plotDCTKernel(string wname, bool isWait, const double* GCn, const int radius, const int order, const double G0, const double sigma)\n\t{\n\t\tconst int size = (order) * (radius + 1);\n\t\tAutoBuffer<float> G(size);\n\t\tfor (int i = 0; i < size; i++)G[i] = (float)GCn[i];\n\t\tplotDCTKernel(wname, isWait, G, radius, order, (float)G0, sigma);\n\t}\n\n\tvoid plotDCTKernel(string wname, bool isWait, const float* GCn, const int radius, const int order, const float G0, const double sigma)\n\t{\n\t\tMat gauss(radius + 1, 1, CV_64F);\n\t\tcp::setGaussKernelHalf(gauss, radius, sigma, true);\n\n\t\tstatic int pre_order = 0;\n\t\tcp::Plot p;\n\t\tcv::namedWindow(wname);\n\t\tconst int allIndex = order + 2;\n\t\tconst int totalIndex = allIndex - 1;\n\t\tstatic int fk = allIndex; createTrackbar(\"k\", wname, &fk, allIndex);\n\t\tif (pre_order != order)\n\t\t{\n\t\t\tpre_order = order;\n\t\t\tfk = allIndex;\n\t\t\tsetTrackbarMax(\"k\", wname, allIndex);\n\t\t\tsetTrackbarPos(\"k\", wname, fk);\n\t\t}\n\n\t\tint key = 0;\n\t\tfor (int k = 0; k <= order; k++)\n\t\t{\n\t\t\tp.setPlotTitle(k, format(\"order %d\", k));\n\t\t}\n\t\tp.setPlotTitle(order + 1, \"total\");\n\n\t\tif (G0 == 0.f)\n\t\t{\n\t\t\twhile (key != 'q')\n\t\t\t{\n\t\t\t\tdouble error = 0.0;\n\t\t\t\tif (fk == allIndex)\n\t\t\t\t{\n\t\t\t\t\tfor (int k = 0; k <= order; k++)\n\t\t\t\t\t{\n\t\t\t\t\t\tfor (int n = -radius; n <= radius; n++)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t//p.push_back(n, GCn[(order + 1) * abs(n) + order - k], k);\n\t\t\t\t\t\t\tp.push_back(n, GCn[(order + 1) * abs(n) + k], k);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\t//total\n\t\t\t\t\tfor (int n = -radius; n <= radius; n++)\n\t\t\t\t\t{\n\t\t\t\t\t\tfloat sum = 0.f;\n\t\t\t\t\t\tfor (int k = 0; k <= order; k++)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tsum += GCn[(order + 1) * abs(n) + k];\n\t\t\t\t\t\t}\n\t\t\t\t\t\tp.push_back(n, sum, totalIndex);\n\t\t\t\t\t\tdouble v = gauss.at<double>(abs(n)) - sum;\n\t\t\t\t\t\terror += v * v;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tif (fk == totalIndex)\n\t\t\t\t\t{\n\t\t\t\t\t\tfor (int n = -radius; n <= radius; n++)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tfloat sum = 0.f;\n\t\t\t\t\t\t\tfor (int k = 0; k <= order; k++)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tsum += GCn[(order + 1) * abs(n) + k];\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tp.push_back(n, sum, totalIndex);\n\t\t\t\t\t\t\tdouble v = gauss.at<double>(abs(n)) - sum;\n\t\t\t\t\t\t\terror += v * v;\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\tfor (int n = -radius; n <= radius; n++)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tp.push_back(n, GCn[(order + 1) * abs(n) + order - fk], fk);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tp.plot(wname, false, \"\", format(\"10log10(1/mse) %f\", 10 * log10(1 / error)));\n\t\t\t\tp.clear();\n\t\t\t\tkey = waitKey(1);\n\t\t\t\tif (!isWait)break;\n\t\t\t}\n\t\t}\n\t\telse //DCT1,5\n\t\t{\n\t\t\twhile (key != 'q')\n\t\t\t{\n\t\t\t\tdouble error = 0.0;\n\t\t\t\tif (fk == allIndex)\n\t\t\t\t{\n\t\t\t\t\tfor (int n = -radius; n <= radius; n++)\n\t\t\t\t\t{\n\t\t\t\t\t\tp.push_back(n, G0, 0);\n\t\t\t\t\t}\n\t\t\t\t\tfor (int k = 0; k < order; k++)\n\t\t\t\t\t{\n\t\t\t\t\t\tfor (int n = -radius; n <= radius; n++)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tp.push_back(n, GCn[order * abs(n) + k], k + 1);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\t//total\n\t\t\t\t\tfor (int n = -radius; n <= radius; n++)\n\t\t\t\t\t{\n\t\t\t\t\t\tfloat sum = G0;\n\t\t\t\t\t\tfor (int k = 0; k < order; k++)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tsum += GCn[order * abs(n) + k];\n\t\t\t\t\t\t}\n\t\t\t\t\t\tp.push_back(n, sum, totalIndex);\n\t\t\t\t\t\tdouble v = gauss.at<double>(abs(n)) - sum;\n\t\t\t\t\t\terror += v * v;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tif (fk == totalIndex)\n\t\t\t\t\t{\n\t\t\t\t\t\tfor (int n = -radius; n <= radius; n++)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tfloat sum = G0;\n\t\t\t\t\t\t\tfor (int k = 0; k < order; k++)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tsum += GCn[(order)*abs(n) + k];\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tp.push_back(n, sum, totalIndex);\n\t\t\t\t\t\t\tdouble v = gauss.at<double>(abs(n)) - sum;\n\t\t\t\t\t\t\terror += v * v;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\telse if (fk == 0)\n\t\t\t\t\t{\n\t\t\t\t\t\tfor (int n = -radius; n <= radius; n++)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tp.push_back(n, G0, 0);\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\tfor (int n = -radius; n <= radius; n++)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tp.push_back(n, GCn[(order)*abs(n) + fk - 1], fk);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tp.plot(wname, false, \"\", format(\"10log10(1/mse) %f\", 10 * log10(1 / error)));\n\n\t\t\t\tp.clear();\n\t\t\t\tkey = waitKey(1);\n\t\t\t\tif (!isWait)break;\n\t\t\t}\n\t\t}\n\t}\n\n\tvoid computeSpectrumGaussianClosedForm(const double sigma, const int K, const int R, const int dcttype, double* destSpect)\n\t{\n\t\tdouble omega = 0.0;\n\t\tdouble k0 = 0.0;\n\t\tswitch (dcttype)\n\t\t{\n\t\tcase 1:\tomega = CV_2PI / (2.0 * R + 0.0); k0 = 0.0; break;\n\t\tcase 3:\tomega = CV_2PI / (2.0 * R + 2.0); k0 = 0.5; break;\n\t\tcase 5:\tomega = CV_2PI / (2.0 * R + 1.0); k0 = 0.0; break;\n\t\tcase 7:\tomega = CV_2PI / (2.0 * R + 1.0); k0 = 0.5; break;\n\t\t\t//default: throw \"Unsupported DCT type\"; break;\n\t\t}\n\n\t\tfor (int k = 0; k <= K; k++)\n\t\t{\n\t\t\tdouble coeff = sigma * omega * (k + k0);\n\t\t\tdestSpect[k] = 2.0 * exp(-0.5 * coeff * coeff);\n\t\t}\n\n\t\tif (dcttype == 1 || dcttype == 5)\n\t\t\tdestSpect[0] = 1.0;\n\t}\n\n\tvoid computeCtWCinv(Mat& dest, const int K, const int R, const int dctType)\n\t{\n\t\tMat Minv = Mat::eye(K, K, CV_64F);\n\n\t\tdouble T = 0.0;\n\t\tswitch (dctType)\n\t\t{\n\t\tcase 1:\n\t\t{\n\t\t\tMinv.at<double>(0, 0) = 0.5;\n\t\t\t//Minv.at<double>(K - 1, K - 1) = 0.5;\n\t\t\tT = (2.0 * R + 0.0); break;\n\t\t}\n\t\tcase 3:\n\t\t{\n\t\t\t//Minv.at<double>(0, 0) = 0.5;\n\t\t\tT = (2.0 * R + 2.0); break;\n\t\t}\n\t\tcase 5:\n\t\t{\n\t\t\tMinv.at<double>(0, 0) = 0.5;\n\t\t\tT = (2.0 * R + 1.0); break;\n\t\t}\n\t\tcase 7:\n\t\t{\n\t\t\t//Minv.at<double>(0, 0) = 0.5;\n\t\t\t//Minv.at<double>(K - 1, K - 1) = 0.5;\n\t\t\tT = (2.0 * R + 1.0); break;\n\t\t}\n\t\tdefault: throw \"Unsupported DCT type\"; break;\n\t\t}\n\n\t\tif (dctType == 1)\n\t\t{\n\t\t\tMat s = Mat::ones(K, 1, CV_64F);\n\t\t\tfor (int i = 1; i < K; i += 2)s.at<double>(i) = -1.0;\n\n\t\t\tMat Minvs = Minv * s;\n\t\t\t//cv::trace(Minv).val[0]=K-2+0.5+0.5\n\t\t\tMat((Minv - (Minvs * Minvs.t()) / (T + (double)K - 1.0))).copyTo(dest);\n\t\t}\n\t\telse\n\t\t{\n\t\t\t//Mat(4/T * Minv).copyTo(dest);\n\t\t\tMinv.copyTo(dest);//scaling (4/T) is not required due to other rescaling.\n\t\t}\n\t}\n\n\tvoid setGaussKernelHalf(Mat& dest, const int R, const double sigma, bool isNormalize)\n\t{\n\t\tCV_Assert(dest.depth() == CV_64F);\n\t\tdouble sum = 0.0;\n\t\tconst double coeff = 1.0 / (-2.0 * sigma * sigma);\n\t\tfor (int n = 1; n <= R; ++n)\n\t\t{\n\t\t\tconst double v = exp((double)(n * n) * coeff);\n\t\t\t//const double v = exp(-(double)(abs(u)) / (sigma));\n\t\t\t//int n = 1;\n\t\t\t//const double v = exp(-(double)pow(abs(u),(double)n) / (n*pow(sigma,double(n))));\n\t\t\tdest.at<double>(n, 0) = v;\n\t\t\tsum += v;\n\t\t}\n\t\tsum *= 2.0;\n\t\tdest.at<double>(0, 0) = 1.0;//u=0\n\t\tsum += 1.0;//u=0\n\n\t\tconst int rend = int(10.0 * sigma);\n\t\tdouble eout = 0.0;\n\t\tfor (int i = R + 1; i <= rend; i++)\n\t\t{\n\t\t\tconst double v = exp(i * i * coeff);\n\t\t\teout += v;\n\t\t}\n\t\tdest.at<double>(R, 0) += eout;\n\n\t\tif (isNormalize)\n\t\t{\n\t\t\tfor (int n = 0; n <= R; ++n)\n\t\t\t{\n\t\t\t\tdest.at<double>(n, 0) /= sum;\n\t\t\t}\n\t\t}\n\t}\n\n\t//without normalize\n\tvoid generateCosKernel(double* dest, double& totalInv, const int dctType, const double* Gk, const int radius, const int order)\n\t{\n\t\tdouble k0;\n\t\tdouble omega;\n\t\tswitch (dctType)\n\t\t{\n\t\tcase 1:\tomega = CV_2PI / (2.0 * radius + 0.0); k0 = 0.0; break;\n\t\tcase 3:\tomega = CV_2PI / (2.0 * radius + 2.0); k0 = 0.5; break;\n\t\tcase 5:\tomega = CV_2PI / (2.0 * radius + 1.0); k0 = 0.0; break;\n\t\tcase 7:\tomega = CV_2PI / (2.0 * radius + 1.0); k0 = 0.5; break;\n\t\tdefault: throw \"Unsupported DCT type\"; break;\n\t\t}\n\n\t\tdouble sum = 0.0;\n\t\tif (dctType == 1 || dctType == 5)\n\t\t{\n\t\t\tsum = Gk[0] * double(2 * radius + 1);//k=0\n\t\t\tfor (int r = 0; r <= radius; ++r)\n\t\t\t{\n\t\t\t\tfor (int k = 1; k <= order; ++k)\n\t\t\t\t{\n\t\t\t\t\tconst double coeff = cos((k + k0) * omega * r) * Gk[k];\n\t\t\t\t\tdest[order * r + k - 1] = coeff;\n\n\t\t\t\t\tif (r == 0) sum += coeff;\n\t\t\t\t\telse sum += 2.0 * coeff;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\tfor (int r = 0; r <= radius; ++r)\n\t\t\t{\n\t\t\t\tfor (int k = 0; k <= order; ++k)\n\t\t\t\t{\n\t\t\t\t\tconst double coeff = cos((k + k0) * omega * r) * Gk[k];\n\n#ifdef COEFFICIENTS_SMALLEST_FIRST\n\t\t\t\t\tdest[(order + 1) * r + (order)-k] = coeff;\n#else\n\t\t\t\t\tdest[(order + 1) * r + k] = coeff;\n#endif\n\n\t\t\t\t\tif (r == 0) sum += coeff;\n\t\t\t\t\telse sum += 2.0 * coeff;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\ttotalInv = (1.0 / sum);\n\t}\n\n\tbool optimizeSpectrum(const double sigma, const int K, const int R, const int dcttype, double* destSpect, const int M)\n\t{\n\t\t/*if (K > R)\n\t\t{\n\t\t\tcomputeSpectrumGaussianClosedForm(sigma, K, R, dcttype, destSpect);\n\t\t\treturn false;\n\t\t}*/\n\n\t\tdouble omega, ratio, k0, n0 = 0.0;\n\t\tswitch (dcttype)\n\t\t{\n\t\tcase 1:\tomega = CV_2PI / (2.0 * R + 0.0); ratio = 2.0 / sqrt(2.0 * R + 0.0); k0 = 0.0; break;\n\t\tcase 3:\tomega = CV_2PI / (2.0 * R + 2.0); ratio = 2.0 / sqrt(2.0 * R + 2.0); k0 = 0.5; break;\n\t\tcase 5:\tomega = CV_2PI / (2.0 * R + 1.0); ratio = 2.0 / sqrt(2.0 * R + 1.0); k0 = 0.0; break;\n\t\tcase 7:\tomega = CV_2PI / (2.0 * R + 1.0); ratio = 2.0 / sqrt(2.0 * R + 1.0); k0 = 0.5; break;\n\t\tdefault: throw \"Unsupported DCT type\"; break;\n\t\t}\n\n\t\t//kernel\n\t\tcv::Mat1d h0(R + 1, 1);//R+1\n\t\tsetGaussKernelHalf(h0, R, sigma, false);\n\n\t\t//weight matrix\n\t\tcv::Mat1d W = cv::Mat1d::eye(R + 1, R + 1);\n\t\tW(0, 0) = 0.5;\n\n\t\t// DCT matrix\n\t\tcv::Mat1d C(R + 1, K + 1);\n\t\tfor (int n = 0; n <= R; ++n)\n\t\t{\n\t\t\tfor (int k = 0; k <= K; ++k)\n\t\t\t{\n\t\t\t\tC(n, k) = cos(omega * (k + k0) * (n + n0));\n\t\t\t}\n\t\t}\n\t\tC *= ratio;\n\n\t\tcv::Mat1d CWCinv;//K+1 x K+1\n\t\tcv::Mat1d a_ls;\n\n#ifdef USE_OPTIMIZE_DCT_SWICH\n\t\tstatic int method = 1;\n#ifdef USE_EIGEN\n\t\tcreateTrackbar(\"opt method\", \"\", &method, 4);\n#else\n\t\tcreateTrackbar(\"opt method\", \"\", &method, 2);\n#endif\n#else \n\t\tint method = 0;//OpenCV direct\n\t\t//int method = 1;//fast method ICASSP2018 universal(but DCT1 and 7 has some bugs?)\n\t\t//int method = 2;//OpenCV SVD\n\t\t//int method = 3;//Eigen direct\n\t\t//int method = 4;//Eigen SVD\n#endif\n\t\t//print_debug3(K, R, dcttype);\n\t\tswitch (method)\n\t\t{\n\t\tdefault:\n\t\tcase 0:\n\t\t{\n\t\t\t// (CWC)^-1\n\t\t\tCWCinv = (C.t() * W * C).inv(DECOMP_CHOLESKY);\n\t\t\t//cv::Mat1d CWCinv = (C.t() * W * C).inv(DECOMP_LU);\n\t\t\t// L2 minimization with moment preservation\n\t\t\ta_ls = CWCinv * C.t() * W * h0;\n\t\t\t//showMat64F(CWCinv, true);\n\n\t\t\tbreak;\n\t\t}\n\t\tcase 1:\n\t\t{\n\t\t\tcomputeCtWCinv(CWCinv, K + 1, R + 1, dcttype);\n\t\t\t//showMat64F(CWCinv, true);\n\t\t\ta_ls = CWCinv * C.t() * W * h0;\n\n\t\t\tbreak;\n\t\t}\n\t\tcase 2:\n\t\t{\n\t\t\tMat w, u, vt;\n\t\t\tW(0, 0) = sqrt(0.5);\n\t\t\t//with weight W\n\t\t\tcv::SVDecomp(W * C, w, u, vt, SVD::FULL_UV);\n\t\t\tSVD::backSubst(w, u, vt, W * h0, a_ls);\n\n\t\t\t//without weight W\n\t\t\t//cv::SVDecomp(C, w, u, vt, SVD::FULL_UV);\n\t\t\t//SVD::backSubst(w, u, vt, h0, a_ls);\n\t\t\tbreak;\n\t\t}\n\t\tcase 3:\n\t\t{\n#ifdef USE_EIGEN\n\t\t\tEigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> CE;\n\t\t\tcv::cv2eigen(C, CE);\n\t\t\tEigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> WE;\n\t\t\tcv::cv2eigen(W, WE);\n\t\t\tEigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> h0E;\n\t\t\tcv::cv2eigen(h0, h0E);\n\n\t\t\tEigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> CtE;\n\t\t\tcv::cv2eigen(C.t(), CtE);\n\n\t\t\tEigen::MatrixXd temp = CtE * WE * CE;\n\t\t\tEigen::MatrixXd temp2 = temp.inverse() * CtE * WE * h0E;\n\t\t\tcv::eigen2cv(temp2, a_ls);\n#endif\n\t\t\tbreak;\n\t\t}\n\t\tcase 4:\n\t\t{\n\n#ifdef USE_EIGEN\n\t\t\tW(0, 0) = sqrt(0.5);\n\t\t\tEigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> CE;\n\t\t\tcv::cv2eigen(C, CE);\n\t\t\tEigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> WE;\n\t\t\tcv::cv2eigen(W, WE);\n\t\t\tEigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> h0E;\n\t\t\tcv::cv2eigen(h0, h0E);\n\n\t\t\tEigen::BDCSVD<Eigen::MatrixXd> svd(WE * CE, Eigen::ComputeThinU | Eigen::ComputeThinV);\n\t\t\tEigen::MatrixXd a = svd.solve(WE * h0E);\n\t\t\tcv::eigen2cv(a, a_ls);\n#endif\n\t\t\tbreak;\n\t\t}\n\t\t}\n\n\t\tconst double sp0 = (dcttype == 1 || dcttype == 5) ? 1.0 : 2.0;\n\t\t//const double v = sp0 / a_ls(0, 0);\n\n#ifdef PRINT_RANK_DEFICIENT\n\t\tif (a_ls(0, 0) == 0)\n\t\t{\n\t\t\tcout << \"PRINT_RANK_DEFICIENT\" << endl;\n\t\t\tprint_debug4(sigma, K, R, dcttype);\n\t\t}\n#endif\n\t\tif (a_ls(0, 0) == 0)\n\t\t{\n\t\t\tcomputeSpectrumGaussianClosedForm(sigma, K, R, dcttype, destSpect);\n\t\t\treturn false;\n\t\t}\n\n\t\tconst double v = sp0 / a_ls(0, 0);\n\n\t\tfor (int k = 0; k <= K; ++k)\n\t\t{\n\t\t\t//cout << k << \": \" << spect[k] << \": \";\n\t\t\tdestSpect[k] = a_ls(k, 0) * v;\n\t\t\t//destSpect[k] = a_ls(k, 0)*ratio;\n\t\t\t//cout << spect[k] << endl;\t\t\n\t\t}\n\n\t\tif (1 <= M)\n\t\t{\n\t\t\tcv::Mat1d a = a_ls.clone();\n\n\t\t\t//ideal gaussian moment vector\n\t\t\tcv::Mat1d mu(M, 1, 1.0);\n\t\t\tfor (auto m = 1; m < M; ++m)\n\t\t\t\tmu(m, 0) = mu(m - 1, 0) * (2 * m - 1) * sigma * sigma;\n\n\t\t\t// Vandermonde\n\t\t\tcv::Mat1d V(R + 1, M);\n\t\t\tfor (auto m = 0; m < M; ++m)\n\t\t\t{\n\t\t\t\tfor (auto u = 0; u <= R; ++u)\n\t\t\t\t\tV(u, m) = pow(u, 2 * m);\n\t\t\t\t//V(0, m) /= 2.0; // moved from W\n\t\t\t}\n\n\t\t\t// Moment constraint\n\t\t\tcv::Mat1d U = V.t() * W * C;\n\t\t\tcv::Mat1d S = U * CWCinv * U.t();\n\t\t\tcv::Mat1d Sinv = S.inv();\n\t\t\ta -= CWCinv * U.t() * Sinv * (U * a - 0.5 * mu);\n\n\t\t\t//print_matrix(U, \"[U]\");\n\t\t\t//print_matrix(S, \"[S]\");\n\t\t\t//print_matrix(Sinv, \"[S^-1]\");\n\t\t\t//print_matrix(U*a - 0.5*mu, \"[U*a - 0.5*mu]\");\n\n\t\t\tfor (auto k = 0; k <= K; ++k)\n\t\t\t{\n\t\t\t\t//cout <<k<<\": \"<< spect[k] << \": \";\n\t\t\t\tdestSpect[k] = a(k, 0);\n\t\t\t\t//cout << spect[k] << endl;\n\t\t\t}\n\n\t\t\tif (dcttype == 1 || dcttype == 5)\n\t\t\t\tdestSpect[0] = 1.0;\n\t\t}\n\n\t\t//std::cerr << \"[Spectra]\" << std::endl;\n\t\t//for (auto k = 0; k < K; ++k)\n\t\t//\tstd::cerr << cv::format(\"k=%d:  %10.8f  %10.8f\", k, a_ls(k, 0), a(k, 0)) << std::endl;\n\t\treturn true;\n\t}\n\n\tclass SearchFullDCTRadius :public cp::Search1DInt\n\t{\n\t\tdouble sigma;\n\t\tint K;\n\t\tint dcttype;\n\t\tdouble* spect;\n\n\t\tbool isOptimize;\n\n\t\tdouble getErrorDCT(const double sigma, const int K, const int R, const int dcttype, const double* spect)\n\t\t{\n\t\t\tconst int ROut = (int)ceil(9.0 * sigma);\n\t\t\t//const int ROut = (int)ceil(7.5 * sigma);\n\t\t\t//const int ROut = (int)ceil(6.0 * sigma);\n\t\t\tAutoBuffer<double> ans(ROut + 1);\n\t\t\tAutoBuffer<double> approx(ROut + 1);\n\t\t\tAutoBuffer<double> e2(ROut + 1);\n\n\t\t\tdouble sum = 1.0;\n\t\t\tans[0] = 1.0;\n\t\t\tfor (int i = ROut; i >= 1; --i)\n\t\t\t{\n\t\t\t\tdouble v = exp(i * i / (-2.0 * sigma * sigma));\n\t\t\t\tans[i] = v;\n\t\t\t\tsum += 2.0 * v;\n\t\t\t}\n\t\t\tfor (int i = 0; i <= ROut; i++)\n\t\t\t{\n\t\t\t\tans[i] /= sum;\n\t\t\t}\n\n\t\t\tdouble errorTruncation = 0.0;\n\t\t\tfor (int i = ROut; i >= R + 1; --i)\n\t\t\t{\n\t\t\t\tdouble e = ans[i];\n\t\t\t\terrorTruncation = fma(e, e, errorTruncation);\n\t\t\t}\n\n\t\t\tdouble phi, k0;//n0=0\n\t\t\tswitch (dcttype)\n\t\t\t{\n\t\t\tcase 1:\tphi = CV_2PI / (2.0 * R + 0.0); k0 = 0.0; break;\n\t\t\tcase 3:\tphi = CV_2PI / (2.0 * R + 2.0); k0 = 0.5; break;\n\t\t\tcase 5:\tphi = CV_2PI / (2.0 * R + 1.0); k0 = 0.0; break;\n\t\t\tcase 7:\tphi = CV_2PI / (2.0 * R + 1.0); k0 = 0.5; break;\n\n\t\t\tdefault: throw \"Unsupported DCT type\"; break;\n\t\t\t}\n\n\t\t\tsum = 0.0;\n\t\t\tfor (int i = R; i >= 1; --i)\n\t\t\t{\n\t\t\t\tdouble s = 0.0;\n\t\t\t\tfor (int k = K; k >= 0; --k)\n\t\t\t\t{\n\t\t\t\t\ts = fma(cos(phi * (k + k0) * (i)), spect[k], s);//DCT1,3,5,7: n0 = 0.\n\t\t\t\t}\n\t\t\t\tsum += 2.0 * s;\n\t\t\t\tapprox[i] = s;\n\t\t\t}\n\t\t\t{\n\t\t\t\tdouble s = 0.0;\n\t\t\t\tfor (int k = K; k >= 0; --k)\n\t\t\t\t{\n\t\t\t\t\ts += spect[k];\n\t\t\t\t}\n\t\t\t\tsum += s;\n\t\t\t\tapprox[0] = s;\n\t\t\t}\n\t\t\tfor (int i = 0; i <= R; i++)\n\t\t\t{\n\t\t\t\tapprox[i] /= sum;\n\t\t\t}\n\n\t\t\tdouble errorFrec = 0.0;\n\t\t\tfor (int i = R; i >= 1; --i)\n\t\t\t{\n\t\t\t\terrorFrec = fma((ans[i] - approx[i]), (ans[i] - approx[i]), errorFrec);\n\t\t\t}\n\t\t\terrorFrec *= 2.0;\n\t\t\terrorFrec += (ans[0] - approx[0]) * (ans[0] - approx[0]);\n\n\t\t\treturn errorFrec + errorTruncation;\n\t\t}\n\n\t\tdouble getError(int x)\n\t\t{\n\t\t\tif (isOptimize)optimizeSpectrum(sigma, K, x, dcttype, spect);\n\t\t\telse computeSpectrumGaussianClosedForm(sigma, K, x, dcttype, spect);\n\n\t\t\treturn getErrorDCT(sigma, K, x, dcttype, spect);\n\t\t}\n\n\tpublic:\n\t\tSearchFullDCTRadius(const double sigma, const int K, const int dcttype, const double* spect, bool isOptimize)\n\t\t{\n\t\t\tthis->sigma = sigma;\n\t\t\tthis->K = K;\n\t\t\tthis->dcttype = dcttype;\n\t\t\tthis->spect = (double*)spect;\n\t\t\tthis->isOptimize = isOptimize;\n\t\t}\n\t};\n\n\tint test_ratio(const double sigma, const int K, const int dcttype)\n\t{\n\t\tdouble a, b, c_1, c_2, c_3, c_4;\n\t\tint dest;\n\t\tif (dcttype == 1)\n\t\t\tb = 0.467347, c_1 = 0.0007, c_2 = -0.0277, c_3 = 0.6053, c_4 = 1.8088;\n\t\telse if (dcttype == 3)\n\t\t\tb = -0.16509, c_1 = 0.0005, c_2 = -0.0221, c_3 = 0.5458, c_4 = 2.1403;\n\t\telse if (dcttype == 5)\n\t\t\tb = 0.00696, c_1 = 0.0008, c_2 = -0.0289, c_3 = 0.6159, c_4 = 1.7929;\n\t\telse if (dcttype == 7)\n\t\t\tb = -0.029, c_1 = 0.0005, c_2 = -0.0217, c_3 = 0.5412, c_4 = 2.1912;\n\t\telse\n\t\t{\n\t\t\tcout << \"This is not Sliding DCT\" << endl;\n\t\t\treturn 0;\n\t\t}\n\t\ta = c_1 * K * K * K + c_2 * K * K + c_3 * K + c_4;\n\t\treturn dest = int(a * sigma + b);\n\t}\n\n\tint argminR_BruteForce_DCT(const double sigma, const int K, const int dcttype, const double* spect, const bool isOptimize, const bool isGoldenSelectionSearch)\n\t{\n\t\t//case K<=R:OK\n\t\t//case K>R:NG\n\t\tint r = argminR_ContinuousForm_DCT(sigma, K, dcttype, isGoldenSelectionSearch);\n\t\t\n\t\tconst int rmin = max(1, (int)floor(0.6 * r));\n\t\tconst int rmax = (int)ceil(1.4 * r);\n\t\tint argmin_r = 0;\n\n\t\tSearchFullDCTRadius s(sigma, K, dcttype, spect, isOptimize);\n\n\t\t//\t\ts.plotError(\"test\", rmin, rmax);\n\t\t\t\t//debug\n\t\t\t\t/*{\n\t\t\t\t\tint r_gs = s.goldenSearch(rmin, rmax);\n\t\t\t\t\tint r_li = s.linearSearch(rmin, rmax);\n\t\t\t\t\tif (r_li != r_gs)\n\t\t\t\t\t{\n\t\t\t\t\t\tcout << \"NG: (sigma, k) = \" << sigma << \",\" << K << endl;\n\t\t\t\t\t\tprint_debug2(r_li, r_gs);\n\t\t\t\t\t\tprint_debug2(rmin, rmax);\n\t\t\t\t\t\ts.plotError(\"error\", rmin, rmax);\n\t\t\t\t\t}\n\t\t\t\t\t//cout << \"dct\" << dcttype << \": K=\" << K << \", r=\" << argmin_r << \", sigma=\" << argmin_r / sigma << endl;\n\t\t\t\t}*/\n\n\n\t\tif (isGoldenSelectionSearch)\n\t\t{\n\t\t\targmin_r = s.goldenSearch(rmin, rmax);\n\t\t\t//cout << \"dct\" << dcttype << \": K=\" << K << \", r=\" << argmin_r << \", sigma=\" << argmin_r / sigma << endl;\n\t\t}\n\t\telse\n\t\t{\n\t\t\targmin_r = s.linearSearch(rmin, rmax);\n\t\t\t//cout << \"dct\" << dcttype << \": K=\" << K << \", r=\" << argmin_r << \", sigma=\" << argmin_r / sigma << endl;\n\t\t}\n\n\t\t//cout << \"Linear search radius is\" << test_ratio(sigma, K, dcttype) << endl;\n\t\t//cout << \"True number radius is\" << argmin_r << endl;\n\t\treturn argmin_r;\n\t}\n\n#pragma region ContinuousForm\n\tclass SearchDCTRadiusContinuousForm :public cp::Search1DInt\n\t{\n\t\tdouble sigma;\n\t\tint K;\n\t\tdouble* spect = nullptr;\n\n\t\tdouble getError(int x)\n\t\t{\n\t\t\tdouble T = 2.0 * x + 1.0;\n\t\t\tdouble Es = erfc(T / (2.0 * sigma));\n\t\t\tdouble Ef = erfc(sigma * CV_PI * (2.0 * K + 1.0) / T);\n\t\t\treturn Es + Ef;\n\t\t}\n\n\tpublic:\n\t\tSearchDCTRadiusContinuousForm(const double sigma, const int K)\n\t\t{\n\t\t\tthis->sigma = sigma;\n\t\t\tthis->K = K;\n\t\t}\n\t};\n\n\tint argminR_ContinuousForm_DCT(const double sigma, const int K, const int dcttype, const bool isGoldenSelectionSearch)\n\t{\n\t\tint argmin_r = 0;\n\n\t\tint rmin = max(K, (int)floor(1.0 * sigma));\n\t\tint rmax = (int)ceil(10.0 * sigma);\n\t\tif (rmin > rmax)return rmin;\n\t\tSearchDCTRadiusContinuousForm s(sigma, K);\n\n\t\tif (isGoldenSelectionSearch)\n\t\t{\n\t\t\targmin_r = s.goldenSearch(rmin, rmax);\n\t\t\t//cout << \"dct\" << dcttype << \": K=\" << K << \", r=\" << argmin_r << \", sigma=\" << argmin_r / sigma << endl;\n\t\t}\n\t\telse\n\t\t{\n\t\t\targmin_r = s.linearSearch(rmin, rmax);\n\t\t\t//cout << \"dct\" << dcttype << \": K=\" << K << \", r=\" << argmin_r << \", sigma=\" << argmin_r / sigma << endl;\n\t\t}\n\t\treturn argmin_r;\n\t}\n#pragma endregion\n}", "meta": {"hexsha": "6a30e4b6e3251ed893995675e9bcfbc366fc26c9", "size": 18702, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "SpatialFilter/SpatialFilterSlidingDCT.cpp", "max_stars_repo_name": "norishigefukushima/OpenCP", "max_stars_repo_head_hexsha": "63090131ec975e834f85b04e84ec29b2893845b2", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 137.0, "max_stars_repo_stars_event_min_datetime": "2015-03-27T07:11:19.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T05:58:22.000Z", "max_issues_repo_path": "SpatialFilter/SpatialFilterSlidingDCT.cpp", "max_issues_repo_name": "Pandinosaurus/OpenCP", "max_issues_repo_head_hexsha": "a5234ed531c610d7944fa14d42f7320442ea34a1", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2016-05-18T06:33:16.000Z", "max_issues_repo_issues_event_max_datetime": "2016-07-11T17:39:17.000Z", "max_forks_repo_path": "SpatialFilter/SpatialFilterSlidingDCT.cpp", "max_forks_repo_name": "Pandinosaurus/OpenCP", "max_forks_repo_head_hexsha": "a5234ed531c610d7944fa14d42f7320442ea34a1", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 43.0, "max_forks_repo_forks_event_min_datetime": "2015-02-20T15:34:25.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-27T14:59:37.000Z", "avg_line_length": 24.8037135279, "max_line_length": 159, "alphanum_fraction": 0.5301037322, "num_tokens": 7506, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5350984286266116, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.32316297522434834}}
{"text": "/*\n * PCGSolver.cpp\n *\n *  Created on: Feb 14, 2012\n *      Author: ydjian\n */\n\n#include <gtsam/linear/GaussianFactorGraph.h>\n//#include <gtsam/inference/FactorGraph-inst.h>\n//#include <gtsam/linear/FactorGraphUtil-inl.h>\n//#include <gtsam/linear/JacobianFactorGraph.h>\n//#include <gtsam/linear/LSPCGSolver.h>\n#include <gtsam/linear/PCGSolver.h>\n#include <gtsam/linear/Preconditioner.h>\n//#include <gtsam/linear/SuiteSparseUtil.h>\n//#include <gtsam/linear/ConjugateGradientMethod-inl.h>\n//#include <gsp2/gtsam-interface-sbm.h>\n//#include <ydjian/tool/ThreadSafeTimer.h>\n#include <boost/algorithm/string.hpp>\n#include <iostream>\n#include <stdexcept>\n\nusing namespace std;\n\nnamespace gtsam {\n\n/*****************************************************************************/\nvoid PCGSolverParameters::print(ostream &os) const {\n  Base::print(os);\n  os << \"PCGSolverParameters:\" <<  endl;\n  preconditioner_->print(os);\n}\n\n/*****************************************************************************/\nPCGSolver::PCGSolver(const PCGSolverParameters &p) {\n  preconditioner_ = createPreconditioner(p.preconditioner_);\n}\n\n/*****************************************************************************/\nVectorValues PCGSolver::optimize (\n  const GaussianFactorGraph &gfg,\n  const KeyInfo &keyInfo,\n  const std::map<Key, Vector> &lambda,\n  const VectorValues &initial)\n{\n  /* build preconditioner */\n  preconditioner_->build(gfg, keyInfo, lambda);\n\n  /* apply pcg */\n  const Vector sol = preconditionedConjugateGradient<GaussianFactorGraphSystem, Vector>(\n        GaussianFactorGraphSystem(gfg, *preconditioner_, keyInfo, lambda),\n        initial.vector(keyInfo.ordering()), parameters_);\n\n  return buildVectorValues(sol, keyInfo);\n}\n\n/*****************************************************************************/\nGaussianFactorGraphSystem::GaussianFactorGraphSystem(\n    const GaussianFactorGraph &gfg,\n    const Preconditioner &preconditioner,\n    const KeyInfo &keyInfo,\n    const std::map<Key, Vector> &lambda)\n  : gfg_(gfg), preconditioner_(preconditioner), keyInfo_(keyInfo), lambda_(lambda) {}\n\n/*****************************************************************************/\nvoid GaussianFactorGraphSystem::residual(const Vector &x, Vector &r) const {\n  /* implement b-Ax, assume x and r are pre-allocated */\n\n  /* reset r to b */\n  getb(r);\n\n  /* substract A*x */\n  Vector Ax = Vector::Zero(r.rows(), 1);\n  multiply(x, Ax);\n  r -= Ax ;\n}\n\n/*****************************************************************************/\nvoid GaussianFactorGraphSystem::multiply(const Vector &x, Vector& Ax) const {\n  /* implement Ax, assume x and Ax are pre-allocated */\n\n  /* reset y */\n  Ax.setZero();\n\n  BOOST_FOREACH ( const GaussianFactor::shared_ptr &gf, gfg_ ) {\n    if ( JacobianFactor::shared_ptr jf = boost::dynamic_pointer_cast<JacobianFactor>(gf) ) {\n      /* accumulate At A x*/\n      for ( JacobianFactor::const_iterator it = jf->begin() ; it != jf->end() ; ++it ) {\n        const Matrix Ai = jf->getA(it);\n        /* this map lookup should be replaced */\n        const KeyInfoEntry &entry = keyInfo_.find(*it)->second;\n        Ax.segment(entry.colstart(), entry.dim())\n            += Ai.transpose() * (Ai * x.segment(entry.colstart(), entry.dim()));\n      }\n    }\n    else if ( HessianFactor::shared_ptr hf = boost::dynamic_pointer_cast<HessianFactor>(gf) ) {\n      /* accumulate H x */\n\n      /* use buffer to avoid excessive table lookups */\n      const size_t sz = hf->size();\n      vector<Vector> y;\n      y.reserve(sz);\n      for (HessianFactor::const_iterator it = hf->begin(); it != hf->end(); it++) {\n        /* initialize y to zeros */\n        y.push_back(zero(hf->getDim(it)));\n      }\n\n      for (HessianFactor::const_iterator j = hf->begin(); j != hf->end(); j++ ) {\n        /* retrieve the key mapping */\n        const KeyInfoEntry &entry = keyInfo_.find(*j)->second;\n        // xj is the input vector\n        const Vector xj = x.segment(entry.colstart(), entry.dim());\n        size_t idx = 0;\n        for (HessianFactor::const_iterator i = hf->begin(); i != hf->end(); i++, idx++ ) {\n          if ( i == j ) y[idx] += hf->info(j, j).selfadjointView() * xj;\n          else y[idx] += hf->info(i, j).knownOffDiagonal() * xj;\n        }\n      }\n\n      /* accumulate to r */\n      for(DenseIndex i = 0; i < (DenseIndex) sz; ++i) {\n        /* retrieve the key mapping */\n        const KeyInfoEntry &entry = keyInfo_.find(hf->keys()[i])->second;\n        Ax.segment(entry.colstart(), entry.dim()) += y[i];\n      }\n    }\n    else {\n      throw invalid_argument(\"GaussianFactorGraphSystem::multiply gfg contains a factor that is neither a JacobianFactor nor a HessianFactor.\");\n    }\n  }\n}\n\n/*****************************************************************************/\nvoid GaussianFactorGraphSystem::getb(Vector &b) const {\n  /* compute rhs, assume b pre-allocated */\n\n  /* reset */\n  b.setZero();\n\n  BOOST_FOREACH ( const GaussianFactor::shared_ptr &gf, gfg_ ) {\n    if ( JacobianFactor::shared_ptr jf = boost::dynamic_pointer_cast<JacobianFactor>(gf) ) {\n      const Vector rhs = jf->getb();\n      /* accumulate At rhs */\n      for ( JacobianFactor::const_iterator it = jf->begin() ; it != jf->end() ; ++it ) {\n        /* this map lookup should be replaced */\n        const KeyInfoEntry &entry = keyInfo_.find(*it)->second;\n        b.segment(entry.colstart(), entry.dim()) += jf->getA(it).transpose() * rhs ;\n      }\n    }\n    else if ( HessianFactor::shared_ptr hf = boost::dynamic_pointer_cast<HessianFactor>(gf) ) {\n      /* accumulate g */\n      for (HessianFactor::const_iterator it = hf->begin(); it != hf->end(); it++) {\n        const KeyInfoEntry &entry = keyInfo_.find(*it)->second;\n        b.segment(entry.colstart(), entry.dim()) += hf->linearTerm(it);\n      }\n    }\n    else {\n      throw invalid_argument(\"GaussianFactorGraphSystem::getb gfg contains a factor that is neither a JacobianFactor nor a HessianFactor.\");\n    }\n  }\n}\n\n/**********************************************************************************/\nvoid GaussianFactorGraphSystem::leftPrecondition(const Vector &x, Vector &y) const\n{ preconditioner_.transposeSolve(x, y); }\n\n/**********************************************************************************/\nvoid GaussianFactorGraphSystem::rightPrecondition(const Vector &x, Vector &y) const\n{ preconditioner_.solve(x, y); }\n\n/**********************************************************************************/\nVectorValues buildVectorValues(const Vector &v,\n                               const Ordering &ordering,\n                               const map<Key, size_t>  & dimensions) {\n  VectorValues result;\n\n  DenseIndex offset = 0;\n  for ( size_t i = 0 ; i < ordering.size() ; ++i ) {\n    const Key &key = ordering[i];\n    map<Key, size_t>::const_iterator it = dimensions.find(key);\n    if ( it == dimensions.end() ) {\n      throw invalid_argument(\"buildVectorValues: inconsistent ordering and dimensions\");\n    }\n    const size_t dim = it->second;\n    result.insert(key, v.segment(offset, dim));\n    offset += dim;\n  }\n\n  return result;\n}\n\n/**********************************************************************************/\nVectorValues buildVectorValues(const Vector &v, const KeyInfo &keyInfo) {\n  VectorValues result;\n  BOOST_FOREACH ( const KeyInfo::value_type &item, keyInfo ) {\n    result.insert(item.first, v.segment(item.second.colstart(), item.second.dim()));\n  }\n  return result;\n}\n\n}\n", "meta": {"hexsha": "27eb57b44a01effcf5b65651175252cfe3170865", "size": 7436, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "gtsam/linear/PCGSolver.cpp", "max_stars_repo_name": "ashariati/gtsam-3.2.1", "max_stars_repo_head_hexsha": "f880365c259eb7532b9c1d20979ecad2eb04779c", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 75.0, "max_stars_repo_stars_event_min_datetime": "2015-04-02T08:58:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-18T08:01:42.000Z", "max_issues_repo_path": "gtsam/linear/PCGSolver.cpp", "max_issues_repo_name": "ashariati/gtsam-3.2.1", "max_issues_repo_head_hexsha": "f880365c259eb7532b9c1d20979ecad2eb04779c", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2016-07-05T16:21:08.000Z", "max_issues_repo_issues_event_max_datetime": "2020-05-13T16:50:42.000Z", "max_forks_repo_path": "gtsam/linear/PCGSolver.cpp", "max_forks_repo_name": "ashariati/gtsam-3.2.1", "max_forks_repo_head_hexsha": "f880365c259eb7532b9c1d20979ecad2eb04779c", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 66.0, "max_forks_repo_forks_event_min_datetime": "2015-06-01T11:22:38.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-18T11:03:57.000Z", "avg_line_length": 36.8118811881, "max_line_length": 144, "alphanum_fraction": 0.5720817644, "num_tokens": 1740, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6893056295505784, "lm_q2_score": 0.4687906266262437, "lm_q1q2_score": 0.32314001801401304}}
{"text": "#include <Eigen/Dense>\n#include <vector>\n#include <fstream>\n#include <iostream>\n#include <cmath>\n\n#include \"../include/KF.h\"\n#include \"../include/dsho.h\"\n#include \"../include/matern32.h\"\n#include \"../include/ndsho.h\"\n\n\nusing namespace Eigen;\nusing namespace std;\n\n// function to read a space separated file\n\nstd::vector<double> load_csv (const std::string & path) {\n    std::ifstream indata;\n    indata.open(path);\n    std::string line;\n    std::vector<double> values;\n    uint rows = 0;\n    while (std::getline(indata, line)) {\n        std::stringstream lineStream(line);\n        std::string cell;\n        while (std::getline(lineStream, cell, ' ')) {\n            //cout << std::stod(cell) << endl;\n            values.push_back(std::stod(cell));\n        }\n        ++rows;\n    }\n    return values;\n}\n\nint main() {\n\n\t// read file with two component damped simple harmonic oscillator simulated data\n\t//std::vector<double> values = load_csv(\"two_comp_dsho.txt\");\n\t//cout << values.size() << endl;\n\n\t// map data to VectorXds\n\t//VectorXd times = Map<VectorXd, 0, InnerStride<2> > (values.data(), 10000);\n\t//VectorXd yi = Map<VectorXd, 0, InnerStride<2> > (values.data()+1, 10000);\n\n  int vecsize = 10000;\n\t// map data to VectorXds\n\tVectorXd yi(vecsize);\n  VectorXd times = Eigen::VectorXd::Random(vecsize);\n  times.array() += 1.0;\n  times.array() *= (100*0.5);\n  std::sort(times.data(), times.data() + times.size());\n\n\n\t// this is the observational error vector\n\tVectorXd yerr = VectorXd::Ones(yi.size());\n\tyerr.array() *= 0.05;\n\n\tVectorXd y_sim;\n\n\tdouble varf_list[2] = {1.0, 0.1*0.1};\n\tfor (int k=0; k<2; k++){\n\t\tfor(int j=0; j < 6; j++) {\n\t\t\tdouble varf = varf_list[k];\n\t\t\t//auto const seed = std::random_device()();\n\t\t\tint seed = 123;\n\t\t\tstd::mt19937 rng(seed);\n\t\t\tcout << seed << endl;\n\t\t\tdouble lambda = std::pow(2,j);\n\n\t\t\t// Simulate a Matern 3/2 model\n\t\t\tgpstate::matern32::Matern32Solver m32(times,yi,yerr, lambda, varf);\n\t\t\tm32.simulate_Matern32(y_sim, rng);\n\n\t\t\tdouble mean = y_sim.mean();\n\t\t\tEigen::VectorXd tmp = y_sim.array()-mean;\n\t\t\tdouble variance  = tmp.dot(tmp) / y_sim.rows();\n\t\t\tstd::cout << \"var:\" << variance << \" \" << std::to_string(k*6 + j+1) << std::endl;\n\n\t\t\t// write simulated vector to file GPtest.txt\n\t\t\tstd::ofstream file(\"GPtest\" + std::to_string(k*6 + j+1) + \"_m32.txt\");\n\t\t\tassert(file.is_open());\n\t\t\tfile << \"# Matern 3/2 simulated light curve\" << endl;\n\t\t\tfile << \"# input parameters: \" << endl;\n\t\t\tfile << \"# omega: \" << lambda << endl;\n\t\t\tfile << \"# varf: \" << varf  << endl;\n\t\t\tfile << \"#time y_sim\" << endl;\n\t\t\tfor(int i=0; i<times.rows(); i++)\n\t\t\t\tfile <<  times(i) <<\" \"<< y_sim(i) << endl;\n\n\t\t}\n\t}\n\n}\n", "meta": {"hexsha": "a3c7127e5f379400ac4b63ff4ddd72e8954d8cbd", "size": 2639, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/simulate_matern32.cpp", "max_stars_repo_name": "andres-jordan/gpstate", "max_stars_repo_head_hexsha": "4daabcd0b851318c581995836ebd81e6ecde6f54", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-11-13T23:27:32.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-13T23:27:32.000Z", "max_issues_repo_path": "src/simulate_matern32.cpp", "max_issues_repo_name": "andres-jordan/gpstate", "max_issues_repo_head_hexsha": "4daabcd0b851318c581995836ebd81e6ecde6f54", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/simulate_matern32.cpp", "max_forks_repo_name": "andres-jordan/gpstate", "max_forks_repo_head_hexsha": "4daabcd0b851318c581995836ebd81e6ecde6f54", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.7789473684, "max_line_length": 84, "alphanum_fraction": 0.6093217128, "num_tokens": 794, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6893056167854461, "lm_q2_score": 0.46879062662624377, "lm_q1q2_score": 0.3231400120298387}}
{"text": "/**\n * @file envelope_model.cc\n * Reverberation envelope time series for a single combination of\n * receiver azimuth, source beam number, receiver beam number.\n */\n#include <boost/foreach.hpp>\n#include <boost/numeric/ublas/vector_proxy.hpp>\n#include <boost/numeric/ublas/matrix_proxy.hpp>\n#include <usml/eigenverb/envelope_model.h>\n\nusing namespace usml::eigenverb;\n\n//#define DEBUG_ENVELOPE\n\n/**\n * Reserve the memory used to store the results of this calculation.\n */\nenvelope_model::envelope_model(\n\tconst seq_vector* envelope_freq,\n\tsize_t src_freq_first,\n\tconst seq_vector* travel_time,\n\tdouble initial_time,\n\tdouble pulse_length,\n\tdouble threshold\n) :\n\t_envelope_freq(envelope_freq),\n\t_src_freq_first(src_freq_first),\n\t_travel_time( travel_time->clone() ),\n\t_initial_time(initial_time),\n\t_pulse_length(pulse_length),\n\t_threshold(threshold),\n\t_level(travel_time->size()),\n\t_power(envelope_freq->size()),\n\t_duration(envelope_freq->size()),\n\t_intensity(envelope_freq->size(), travel_time->size())\n{\n}\n\n/**\n * Reserve the memory used to store the results of this calculation.\n */\nenvelope_model::~envelope_model() {\n\tdelete _travel_time ;\n}\n\n/**\n * Adds a single combination of source and receiver eigenverbs\n * to this time series.\n */\nbool envelope_model::compute_intensity(\n\t\tconst eigenverb& src_verb, const eigenverb& rcv_verb,\n\t\tconst vector<double>& scatter, double xs2, double ys2 )\n{\n\tbool ok = compute_overlap( src_verb, rcv_verb, scatter, xs2, ys2 );\n\tif ( !ok ) return false ;\n\n\tcompute_time_series( src_verb.time, rcv_verb.time ) ;\n\treturn true ;\n}\n\n/**\n * Compute the total power of the overlap between two eigenverbs.\n */\nbool envelope_model::compute_overlap(\n\tconst eigenverb& src_verb, const eigenverb& rcv_verb,\n\tconst vector<double>& scatter, double xs2, double ys2 )\n{\n\t#ifdef DEBUG_ENVELOPE\n\t\tcout << \"wave_queue::compute_overlap() \" << endl\n\t\t\t<< \"\\txs2=\" << xs2\n\t\t\t<< \" ys2=\" << ys2\n\t\t\t<< \" scatter=\" << scatter << endl\n\t\t\t<< \"\\tsrc_verb\"\n\t\t\t<< \" t=\" << src_verb.time\n\t\t\t<< \" de=\" << to_degrees(src_verb.source_de)\n\t\t\t<< \" az=\" << to_degrees(src_verb.source_az)\n\t\t\t<< \" direction=\" << to_degrees(src_verb.direction)\n\t\t\t<< \" grazing=\" << to_degrees(src_verb.grazing) << endl\n\t\t\t<< \"\\tpower=\" << 10.0 * log10(src_verb.power)\n\t\t\t<< \" length=\" << sqrt(src_verb.length2)\n\t\t\t<< \" width=\" << sqrt(src_verb.width2) << endl\n\t\t\t<< \"\\tsurface=\" << src_verb.surface << \" bottom=\" << src_verb.bottom\n\t\t\t<< \" caustic=\" << src_verb.caustic << endl\n\t\t\t<< \"\\trcv_verb\"\n\t\t\t<< \" t=\" << rcv_verb.time\n\t\t\t<< \" de=\" << to_degrees(rcv_verb.source_de)\n\t\t\t<< \" az=\" << to_degrees(rcv_verb.source_az)\n\t\t\t<< \" direction=\" << to_degrees(rcv_verb.direction)\n\t\t\t<< \" grazing=\" << to_degrees(rcv_verb.grazing) << endl\n\t\t\t<< \"\\tpower=\" << 10.0 * log10(rcv_verb.power)\n\t\t\t<< \" length=\" << sqrt(rcv_verb.length2)\n\t\t\t<< \" width=\" << sqrt(rcv_verb.width2) << endl\n\t\t\t<< \"\\tsurface=\" << rcv_verb.surface << \" bottom=\" << rcv_verb.bottom\n\t\t\t<< \" caustic=\" << rcv_verb.caustic << endl;\n\t#endif\n\n\t// determine the relative tilt between the projected Gaussians\n\n\tconst double alpha = src_verb.direction - rcv_verb.direction;\n\tconst double cos2alpha = cos(2.0 * alpha);\n\tconst double sin2alpha = sin(2.0 * alpha);\n\n\t// define subset of frequency dependent terms in source\n    // Although the use of const_cast<> allows us to ignore the read-only\n    // nature of src_verb, we are *very careful* to not write anything to it.\n\n\trange window( _src_freq_first, _src_freq_first + _envelope_freq->size() ) ;\n\teigenverb& verb = const_cast<eigenverb&>( src_verb ) ;\n\tconst vector_range< vector<double> > src_verb_power( verb.power, window ) ;\n\n    // compute commonly used terms in the intersection of the Gaussian profiles\n\n\tconst double src_sum = src_verb.length2 + src_verb.width2 ;\n\tconst double src_diff = src_verb.length2 - src_verb.width2 ;\n\tconst double src_prod = src_verb.length2 * src_verb.width2 ;\n\n\tconst double rcv_sum = rcv_verb.length2 + rcv_verb.width2 ;\n\tconst double rcv_diff = rcv_verb.length2 - rcv_verb.width2 ;\n\tconst double rcv_prod = rcv_verb.length2 * rcv_verb.width2 ;\n\n    // compute the scaling of the exponential\n    // equations (26) and (28) from the paper\n\n    double det_sr = 0.5 * ( 2.0 * ( src_prod + rcv_prod )\n    \t\t+ ( src_sum * rcv_sum ) - ( src_diff * rcv_diff ) * cos2alpha ) ;\n    noalias(_power) = 0.25 * 0.5 * _pulse_length\n    \t\t* src_verb_power * rcv_verb.power * scatter ;\n\n    // compute the power of the exponential\n    // equation (28) from the paper\n\n    const double new_prod = src_diff * cos2alpha ;\n    const double kappa = -0.25 * (\n  \t\t  xs2 * ( src_sum + new_prod + 2.0 * rcv_verb.length2 )\n\t\t+ ys2 * ( src_sum - new_prod + 2.0 * rcv_verb.width2 )\n\t\t- 2.0 * sqrt( xs2 * ys2 ) * src_diff * sin2alpha )\n\t\t/ det_sr ;\n\t#ifdef DEBUG_ENVELOPE\n\t\tcout << \"\\tsrc_verb_power=\" << src_verb_power\n\t\t\t << \" rcv_verb.power=\" << rcv_verb.power << endl\n\t\t\t << \"\\tdet_sr=\" << det_sr\n\t\t\t << \" kappa=\" << kappa\n\t\t\t << \" power=\" << (10.0*log10(_power)) << endl ;\n\t#endif\n\t_power *= exp( kappa ) / sqrt( det_sr ) ;\n\n    // compute the square of the duration of the overlap\n    // equation (41) from the paper\n\n    det_sr = det_sr / ( src_prod * rcv_prod ) ;\n\t_duration = 0.5 * (\n\t\t\t( 1.0 / src_verb.width2 + 1.0 / src_verb.length2 )\n\t\t\t+ ( 1.0 / src_verb.width2 - 1.0 / src_verb.length2 ) * cos2alpha\n\t\t\t+ 2.0 / rcv_verb.width2\n\t\t\t) / det_sr ;\n\n\t// combine duration of the overlap with pulse length\n\t// equation (33) from the paper\n\n\tconst double factor = cos( rcv_verb.grazing ) / rcv_verb.sound_speed ;\n\t_duration = 0.5 * sqrt( _pulse_length * _pulse_length\n\t\t\t+ factor * factor * _duration ) ;\n\t#ifdef DEBUG_ENVELOPE\n\t\tcout << \"\\tcontribution\"\n\t\t\t<< \" duration=\" << _duration\n\t\t\t<< \" power=\" << (10.0*log10(_power)) << endl ;\n\t#endif\n\n\t// check threshold to avoid calculations for weak signals\n\n\tBOOST_FOREACH( double level, _power ) {\n\t\tif ( level / _duration > _threshold ) return true ;\n\t}\n\treturn false ;\n}\n\n/**\n * Computes Gaussian time series contribution given delay, duration, and\n * total power.\n */\nvoid envelope_model::compute_time_series(\n\t\tdouble src_verb_time, double rcv_verb_time )\n{\n\t_intensity.clear() ;\n\n\tfor ( size_t f = 0 ;f < _envelope_freq->size(); ++f ) {\n\n\t\t// compute the peak time and intensity\n\n\t\tconst double delay = src_verb_time + rcv_verb_time + _duration - _initial_time;\n\t\tconst double scale = _power[f] / _duration;\n\n\t\t// compute Gaussian intensity as a function of time\n\n\t\tmatrix_row< matrix<double> > intensity( _intensity, f ) ;\n\n\t\t// use uBLAS vector proxies to only compute the portion of the\n\t\t// time series within +/- five (5) times the duration\n\t\t// speeds up the computation by over a factor of 3\n\n\t\t_level.clear() ;\n\t\tsize_t first = _travel_time->find_index(delay - 5.0 * _duration);\n\t\tsize_t last = _travel_time->find_index(delay + 5.0 * _duration) + 1;\n\t\trange window(first, last);\n\t\tvector_range< seq_vector > time(*_travel_time, window);\n\t\tvector_range< vector<double> > level(_level, window);\n\t\tlevel = scale * exp(-0.5 * abs2((time - delay) / _duration)) ;\n\t\tintensity = _level ;\n\t}\n}\n", "meta": {"hexsha": "dfca8abe4f6eb6b74b2a62fb6a56900935c98302", "size": 7052, "ext": "cc", "lang": "C++", "max_stars_repo_path": "eigenverb/envelope_model.cc", "max_stars_repo_name": "fraclipe/UnderSeaModelingLibrary", "max_stars_repo_head_hexsha": "52ef9dd03c7cbe548749e4527190afe7668ff4e7", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-02-07T14:48:22.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-07T14:48:22.000Z", "max_issues_repo_path": "eigenverb/envelope_model.cc", "max_issues_repo_name": "Wolframy-NUDT/UnderSeaModelingLibrary", "max_issues_repo_head_hexsha": "43365639b435841e1bf2297cf1ac575b8cf91932", "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": "eigenverb/envelope_model.cc", "max_forks_repo_name": "Wolframy-NUDT/UnderSeaModelingLibrary", "max_forks_repo_head_hexsha": "43365639b435841e1bf2297cf1ac575b8cf91932", "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.4218009479, "max_line_length": 81, "alphanum_fraction": 0.6806579694, "num_tokens": 2067, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6893056167854461, "lm_q2_score": 0.46879062662624377, "lm_q1q2_score": 0.3231400120298387}}
{"text": "//Released under the MIT License - https://opensource.org/licenses/MIT\r\n//\r\n//Copyright (c) 2019 AIT Austrian Institute of Technology GmbH\r\n//\r\n//Permission is hereby granted, free of charge, to any person obtaining\r\n//a 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,\r\n//EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\r\n//MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\r\n//IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\r\n//DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\r\n//OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\r\n//USE OR OTHER DEALINGS IN THE SOFTWARE.\r\n//\r\n//Author: Josef Maier (josefjohann-dot-maier-at-gmail-dot-at)\r\n/**********************************************************************************************************\r\n FILE: RectStructMot.cpp\r\n\r\n PLATFORM: Windows 7, MS Visual Studio 2010, OpenCV 2.4.2\r\n\r\n CODE: C++\r\n\r\n AUTOR: Josef Maier, AIT Austrian Institute of Technology\r\n\r\n DATE: July 2015\r\n\r\n LOCATION: TechGate Vienna, Donau-City-Strasse 1, 1220 Vienna\r\n\r\n VERSION: 1.0\r\n\r\n DISCRIPTION: This file provides functions for calculating the extrinsic camera parameters R & t based\r\n\t\t\t  on multiple homography alignment.\r\n**********************************************************************************************************/\r\n\r\n#include \"HomographyAlignment.h\"\r\n#include <Eigen/Core>\r\n#include <opencv2/core/eigen.hpp>\r\n#include \"poselib/pose_helper.h\"\r\n\r\nusing namespace std;\r\nusing namespace cv;\r\n\r\n/* --------------------- Functions --------------------- */\r\n\r\n/* Estimation of R & t based on multi homography alignment.\r\n *\r\n * vector<pair<Mat,Mat>> inl_points\t\tInput  -> Vector containing the correspondences of the different planes in the camera\r\n *\t\t\t\t\t\t\t\t\t\t\t\t  coordinate system. Each vector element contains the correspondeces of one\r\n *\t\t\t\t\t\t\t\t\t\t\t\t  plane where the first points are coordinates of the left camera and the second\r\n *\t\t\t\t\t\t\t\t\t\t\t\t  points are coordinates of the right camera. The first vector element must contain\r\n *\t\t\t\t\t\t\t\t\t\t\t\t  the largest correspondence set for the dominatest plane in the images.\r\n * vector<Mat> Hs\t\t\t\t\t\tInput  -> Homographies of the planes in the camera coordinate system. The vector-ordering\r\n *\t\t\t\t\t\t\t\t\t\t\t\t  of the homographys must be in the same order than their correspondences in\r\n *\t\t\t\t\t\t\t\t\t\t\t\t  inl_points.\r\n * vector<unsigned int> num_inl\t\t\tInput  -> Number of inliers (correspondences) for each plane. The vector-ordering\r\n *\t\t\t\t\t\t\t\t\t\t\t\t  must be in the same order than Hs.\r\n * Mat R1_2\t\t\t\t\t\t\t\tInput & Output -> If a rotation matrix is provided, the homography alignment is initialized\r\n *\t\t\t\t\t\t\t\t\t\t\t\t\t\t  with this rotation and with t1_2 (in this case both, R1_2 & t1_2 have to\r\n *\t\t\t\t\t\t\t\t\t\t\t\t\t\t  be provided. Be careful to use the right rotation matrix and not its\r\n *\t\t\t\t\t\t\t\t\t\t\t\t\t\t  inverse R1_2.t(). If no initialization should be performed R1_2 must be empty.\r\n *\t\t\t\t\t\t\t\t\t\t\t\t\t\t  The resulting rotation matrix after homography alignment is stored in R1_2.\r\n * Mat t1_2\t\t\t\t\t\t\t\tInput & Output -> If a translation vector is provided, the homography alignment is initialized\r\n *\t\t\t\t\t\t\t\t\t\t\t\t\t\t  with this translation and with R1_2 (in this case both, R1_2 & t1_2 have to\r\n *\t\t\t\t\t\t\t\t\t\t\t\t\t\t  be provided. Be careful to use the right rotation matrix and not its\r\n *\t\t\t\t\t\t\t\t\t\t\t\t\t\t  inverse -t1_2. If no initialization should be performed t1_2 must be empty.\r\n *\t\t\t\t\t\t\t\t\t\t\t\t\t\t  The resulting translation vector after homography alignment is stored in t1_2.\r\n * double tol\t\t\t\t\t\t\tInput  -> Inlier threshold in the camera coordinate system.\r\n * Mat N\t\t\t\t\t\t\t\tOutput -> The resulting plane normal vectors after refinement in the same order than Hs.\r\n * vector<Mat> Hs_out\t\t\t\t\tOutput -> The refined homography matrices in the same order than Hs.\r\n *\r\n * Return value:\t\t\t\t\t\t1 :\t\tEverything ok\r\n *\t\t\t\t\t\t\t\t\t\t0 :\t\tHomography alignment not possible/failed\r\n */\r\nint ComputeHomographyMotion(const std::vector<std::pair<cv::Mat,cv::Mat>>& inl_points,\r\n\t\t\t\t\t\t\tstd::vector<cv::Mat> Hs,\r\n\t\t\t\t\t\t\tconst std::vector<unsigned int>& num_inl,\r\n\t\t\t\t\t\t\tcv::Mat & R1_2,\r\n\t\t\t\t\t\t\tcv::Mat & t1_2,\r\n\t\t\t\t\t\t\tdouble tol,\r\n\t\t\t\t\t\t\tcv::Mat & N,\r\n\t\t\t\t\t\t\tstd::vector<cv::Mat> Hs_out)\r\n{\r\n\tMat norms, homo, rot2_1;\r\n\tvector<Mat> rot_b2, dt_b2, norm2, inv_rot_b2;\r\n\tint num_planes;\r\n\r\n\tint i;\r\n\tdouble error[2];\r\n\r\n\tnum_planes = (int)num_inl.size();\r\n\r\n\tnorms = Mat(3,num_planes,CV_64F);\r\n\r\n\tif(num_planes > 1)\r\n\t{\r\n\t\t//rot is rotation from frame 1 to frame 2\r\n\t\tif(!t1_2.empty() && cv::norm(t1_2) > 0.0)\r\n\t\t{\r\n\t\t\tif(!R1_2.empty())\r\n\t\t\t\trot2_1 = R1_2.t();\r\n            Homographys_Alignment_initial_rotation(inl_points, num_inl, Hs[0], homo, rot2_1, t1_2, norms, tol);\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n            Homographys_Alignment(inl_points, num_inl, Hs[0], homo, rot2_1, t1_2, norms, tol);\r\n\t\t}\r\n\t\tR1_2 = rot2_1.t();\r\n\t\tnorms.col(0).copyTo(N);\r\n\t\tfor(i = 0; i < num_planes; ++i)\r\n\t\t{\r\n            construct_analytic_homography(rot2_1, t1_2, norms.col(i), homo);\r\n\t\t\tHs_out.push_back(homo.clone());\r\n\t\t}\r\n\t}\r\n\telse if(num_planes == 1)\r\n\t{\r\n\t\tif(t1_2.empty() || cv::norm(t1_2) < 1e-6)\r\n\t\t\treturn 0;\r\n\r\n        Longuet_Higgins_Solution(Hs[0], rot_b2, dt_b2, norm2);\r\n\t\tinv_rot_b2.push_back(rot_b2[0].t());\r\n\t\tinv_rot_b2.push_back(rot_b2[1].t());\r\n\t\terror[0] = 0.0;\r\n\t\terror[1] = 0.0;\r\n\r\n\t\terror[0] = t1_2.dot(dt_b2[0]);\r\n\t\terror[1] = t1_2.dot(dt_b2[1]);\r\n\t\tif(error[0] > error[1])\r\n\t\t{\r\n\t\t\tR1_2 = rot_b2[0].t();\r\n\t\t\tdt_b2[0].copyTo(t1_2);\r\n\t\t\tnorm2[0].copyTo(N);\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\tR1_2 = rot_b2[1].t();\r\n\t\t\tdt_b2[1].copyTo(t1_2);\r\n\t\t\tnorm2[1].copyTo(N);\r\n\t\t}\r\n\t}\r\n\telse\r\n\t{\r\n\t\t//PRT_MSG(\"there is no plane in this data set\")\r\n\t\treturn 0;\r\n\t}\r\n\r\n//#define  CHECK_REPROJECTION_ERROR\r\n#ifdef CHECK_REPROJECTION_ERROR\r\n  double *h_a = (double*)Hs_out[0].data;\r\n  Mat test_pts2, p_diff;\r\n  for(j = 0; j < (int)num_inl[0]; ++j)\r\n  {\r\n    double op[2];\r\n\ttest_pts2 = Mat(2,1,CV_64F,op);\r\n\tdouble *test_pts = (double*)inl_points[0].first.row(j).data;\r\n\thomography_transfer_33D(h_a, test_pts, op);\r\n\tp_diff = test_pts2 - inl_points[0].first.row(j).t();\r\n\tcout << \"reprojection error \" << p_diff.at<double>(0) << \", \" << p_diff.at<double>(1) << endl;\r\n  }\r\n#endif\r\n\r\n  return 1;//*numm;\r\n}\r\n\r\n/* Estimation of R & t based on multi homography alignment without initialization.\r\n *\r\n * vector<pair<Mat,Mat>> inl_points\t\tInput  -> Vector containing the correspondences of the different planes in the camera\r\n *\t\t\t\t\t\t\t\t\t\t\t\t  coordinate system. Each vector element contains the correspondeces of one\r\n *\t\t\t\t\t\t\t\t\t\t\t\t  plane where the first points are coordinates of the left camera and the second\r\n *\t\t\t\t\t\t\t\t\t\t\t\t  points are coordinates of the right camera. The first vector element must contain\r\n *\t\t\t\t\t\t\t\t\t\t\t\t  the largest correspondence set for the dominatest plane in the images.\r\n * vector<unsigned int> num_inl\t\t\tInput  -> Number of inliers (correspondences) for each plane. The vector-ordering\r\n *\t\t\t\t\t\t\t\t\t\t\t\t  must be in the same order than inl_points.\r\n * InputArray H\t\t\t\t\t\t\tInput  -> Homography corresponding to the first entry (correspondences) of inl_points. This\r\n *\t\t\t\t\t\t\t\t\t\t\t\t  homography should have the largest support set of correspondences.\r\n * Mat homo\t\t\t\t\t\t\t\tOutput -> The refined input homography H after homography alignment.\r\n * Mat R2_1\t\t\t\t\t\t\t\tOutput -> The resulting rotation matrix from camera 1 to camera 2.\r\n * Mat t1_2\t\t\t\t\t\t\t\tOutput -> The resulting translation vector from camera 2 to camera 1.\r\n * Mat & norms\t\t\t\t\t\t\tOutput -> The resulting plane normal vectors after refinement for all planes.\r\n * double tol\t\t\t\t\t\t\tInput  -> Inlier threshold in the camera coordinate system.\r\n *\r\n * Return value:\t\t\t\t\t\t1 :\t\tEverything ok\r\n *\t\t\t\t\t\t\t\t\t\t0 :\t\tHomography alignment not possible/failed\r\n */\r\n#ifndef MAX_ITERATION\r\n#define MAX_ITERATION 40\r\n//estimated rotation is from camera 1 to camera 2\r\n//estimate translation if the camera 2 in camera 1 frame\r\nint  Homographys_Alignment(std::vector<std::pair<cv::Mat,cv::Mat>> inl_points,\r\n                           std::vector<unsigned int> num_inl,\r\n                           cv::InputArray H,\r\n                           cv::Mat & homo,\r\n                           cv::Mat & R2_1,\r\n                           cv::Mat & t1_2,\r\n                           cv::Mat & norms,\r\n                           double tol)\r\n{\r\n\r\n\tMat Hm = H.getMat();\r\n\tstd::vector<Mat> rot_b2, dt_b2, norm2, base_rt2, rot2, homo2, t2/*, rt2*/;\r\n\tMat dn, dn2, h0, rt0, rot_b, dt_b, norm_b, _hh;\r\n\trot2.emplace_back(3,3,CV_64F);\r\n\trot2.emplace_back(Mat(3,3,CV_64F));\r\n\thomo2.emplace_back(Mat(3,3,CV_64F));\r\n\thomo2.emplace_back(Mat(3,3,CV_64F));\r\n\tt2.emplace_back(Mat(3,1,CV_64F));\r\n\tt2.emplace_back(Mat(3,1,CV_64F));\r\n\tbase_rt2.emplace_back(Mat(3,1,CV_64F));\r\n\tbase_rt2.emplace_back(Mat(3,1,CV_64F));\r\n\tint i ;\r\n\tint iter;\r\n\tdouble hh[3][3];\r\n\tdouble e1, e2;\r\n\tint nump;\r\n\tint q;\r\n\tint iter1;\r\n\r\n\tdouble errors[2];\r\n\tdouble s1;\r\n\r\n\tint num_patches;\r\n\tnum_patches = (int)num_inl.size();\r\n\t_hh = Mat(3,3,CV_64F,hh);\r\n\r\n\tnump = 0;\r\n\tfor(i = 0; i < num_patches; ++i)\r\n\t{\r\n\t\tnump += (int)num_inl[i];\r\n\t}\r\n\r\n\tdn = Mat(num_patches,3,CV_64F);\r\n\tdn2 = Mat(2*num_patches,3,CV_64F);\r\n\r\n\tHm.copyTo(h0);\r\n\r\n    Longuet_Higgins_Solution(Hm, rot_b2, dt_b2, norm2);\r\n\terrors[0] = Check_motion_error(inl_points, num_inl, rot_b2[0], dt_b2[0]);\r\n\terrors[1] = Check_motion_error(inl_points, num_inl, rot_b2[1], dt_b2[1]);\r\n\r\n\tdn.row(0) = Mat::zeros(1,3,CV_64F);\r\n\r\n\tbase_rt2[0] = rot_b2[0] * dt_b2[0];\r\n\tbase_rt2[1] = rot_b2[1] * dt_b2[1];\r\n\r\n\t//q is the index of which solution is used for HA\r\n\tfor(q = 0; q < 2; ++q)\r\n\t{\r\n\t\tHm.copyTo(h0);\r\n\t\tbase_rt2[q].copyTo(rt0);\r\n\t\trot_b2[q].copyTo(rot_b);\r\n\t\tdt_b2[q].copyTo(dt_b);\r\n\t\te2 = 100000.0;\r\n\t\tfor(iter1 = 0; iter1 < 4; ++iter1)\r\n\t\t{\r\n\t\t\t//this is to update the h0 and dn\r\n\t\t\tfor(iter = 0 ; iter < MAX_ITERATION; ++iter)\r\n\t\t\t{\r\n\t\t\t\tdn.row(0) = Mat::zeros(1,3,CV_64F);\r\n\r\n\t\t\t\tfor(i = 1; i < num_patches; ++i)\r\n\t\t\t\t{\r\n\t\t\t\t\tcv::Mat tmp = dn.row(i);\r\n\t\t\t\t\tupdate_dn(inl_points[i].first, inl_points[i].second, (int)num_inl[i], h0, rt0, tmp);\r\n\t\t\t\t}\r\n\r\n\t\t\t\tupdate_h0_rt(inl_points,num_inl,h0,dn,rt0);\r\n\t\t\t\te1 = check_error(inl_points, num_inl, h0, dn, rt0);\r\n\r\n\t\t\t\tif((fabs(e1-e2) < 0.00001 || e1 < tol)&& iter > 2)\r\n\t\t\t\t{\r\n\t\t\t\t\tbreak;\r\n\t\t\t\t}\r\n\t\t\t\telse\r\n\t\t\t\t{\r\n\t\t\t\t\te2 = e1;\r\n\t\t\t\t}\r\n\t\t\t\t//update k\r\n\t\t\t\t//compute the total error\r\n\t\t\t}\r\n\r\n            Longuet_Higgins_Solution_with_initial(h0, rot_b, dt_b, norm_b);\r\n\t\t\trt0 = rot_b * dt_b;\r\n\r\n\t\t\te1 = check_error(inl_points, num_inl, h0, dn, rt0);\r\n\r\n\t\t\tif((fabs(e1-e2) < 0.000001 || e1 < tol)&& iter > 2)\r\n\t\t\t{\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t\telse\r\n\t\t\t{\r\n\t\t\t\te2 = e1;\r\n\t\t\t}\r\n\t\t\t//update k\r\n\t\t\t//compute the total error\r\n\t\t}\r\n\r\n\t\trot_b.copyTo(rot2[q]);\r\n\t\tnorm_b.copyTo(norm2[q]);\r\n\t\th0.copyTo(homo2[q]);\r\n\t\tdt_b.copyTo(t2[q]);\r\n\r\n\t\terrors[q] = e1;\r\n\t\tfor(i = 0; i < num_patches; ++i)\r\n\t\t{\r\n\t\t\tdn.row(i).copyTo(dn2.row(q*num_patches + i));//keep the old dn for the future uses\r\n\t\t}\r\n\t}\r\n\r\n\t//Longuet_Higgins_Solution(h0, rot_b2, dt_b2, norm2);\r\n\terrors[0] = Check_motion_error(inl_points, num_inl, rot2[0], t2[0]);\r\n\terrors[1] = Check_motion_error(inl_points, num_inl, rot2[1], t2[1]);\r\n\r\n\tif(errors[0] < errors[1])\r\n\t{\r\n\t\tnorm2[0].copyTo(norms.col(0));\r\n\t\trot2[0].copyTo(R2_1);\r\n\t\thomo2[0].copyTo(homo);\r\n\t\tt2[0].copyTo(t1_2);\r\n\t}\r\n\telse\r\n\t{\r\n\t\tnorm2[1].copyTo(norms.col(0));\r\n\t\trot2[1].copyTo(R2_1);\r\n\t\thomo2[1].copyTo(homo);\r\n\t\tt2[1].copyTo(t1_2);\r\n\t}\r\n\tdn2.rowRange(0, num_patches).copyTo(dn);\r\n\r\n\t//compute the scale factor of the first homography and mulple it to rest dns\r\n\tfor(int j = 0; j < 3; j++)\r\n\t{\r\n\t\tfor(int j1 = 0; j1 < 3; j1++)\r\n\t\t{\r\n\t\t\thh[j][j1] = t1_2.at<double>(j) * norms.at<double>(j1,0);\r\n\t\t}\r\n\t}\r\n\th0 = Mat::eye(3,3,CV_64F);\r\n\t_hh = h0 - _hh;\r\n\th0 = R2_1 * _hh;\r\n\ts1 = h0.at<double>(2,2);\r\n\r\n\t// update the dn and surface normal vectors\r\n\r\n\tfor(i = 1; i < num_patches; ++i)\r\n\t{\r\n\t\tdn.row(i) = s1 * dn.row(i);\r\n\t\tnorms.col(i) = norms.col(0) - dn.row(i).t();\r\n\t}\r\n\r\n\treturn 1;\r\n}\r\n#undef MAX_ITERATION\r\n#endif\r\n\r\n\r\n/* Estimation of R & t based on multi homography alignment with initialization.\r\n *\r\n * vector<pair<Mat,Mat>> inl_points\t\tInput  -> Vector containing the correspondences of the different planes in the camera\r\n *\t\t\t\t\t\t\t\t\t\t\t\t  coordinate system. Each vector element contains the correspondeces of one\r\n *\t\t\t\t\t\t\t\t\t\t\t\t  plane where the first points are coordinates of the left camera and the second\r\n *\t\t\t\t\t\t\t\t\t\t\t\t  points are coordinates of the right camera. The first vector element must contain\r\n *\t\t\t\t\t\t\t\t\t\t\t\t  the largest correspondence set for the dominatest plane in the images.\r\n * vector<unsigned int> num_inl\t\t\tInput  -> Number of inliers (correspondences) for each plane. The vector-ordering\r\n *\t\t\t\t\t\t\t\t\t\t\t\t  must be in the same order than inl_points.\r\n * InputArray H\t\t\t\t\t\t\tInput  -> Homography corresponding to the first entry (correspondences) of inl_points. This\r\n *\t\t\t\t\t\t\t\t\t\t\t\t  homography should have the largest support set of correspondences.\r\n * Mat homo\t\t\t\t\t\t\t\tOutput -> The refined input homography H after homography alignment.\r\n * Mat R2_1\t\t\t\t\t\t\t\tInput & Output -> The homography alignment is initialized with this rotation. The resulting\r\n *\t\t\t\t\t\t\t\t\t\t\t\t\t\t  rotation matrix from camera 1 to camera 2 after homography alignment is\r\n *\t\t\t\t\t\t\t\t\t\t\t\t\t\t  copied back to R2_1.\r\n * Mat t1_2\t\t\t\t\t\t\t\tOutput -> The resulting translation vector from camera 2 to camera 1.\r\n * Mat & norms\t\t\t\t\t\t\tOutput -> The resulting plane normal vectors after refinement for all planes.\r\n * double tol\t\t\t\t\t\t\tInput  -> Inlier threshold in the camera coordinate system.\r\n *\r\n * Return value:\t\t\t\t\t\t1 :\t\tEverything ok\r\n *\t\t\t\t\t\t\t\t\t\t0 :\t\tHomography alignment not possible/failed\r\n */\r\n#ifndef MAX_ITERATION\r\n#define MAX_ITERATION 30\r\n\r\nint Homographys_Alignment_initial_rotation(std::vector<std::pair<cv::Mat,cv::Mat>> inl_points,\r\n                                           std::vector<unsigned int> num_inl,\r\n                                           cv::InputArray H,\r\n                                           cv::Mat & homo,\r\n                                           cv::Mat & R2_1,\r\n                                           cv::Mat & t1_2,\r\n                                           cv::Mat & norms,\r\n                                           double tol)\r\n{\r\n\tMat h0, Hm, R, dR, rot_b, dn, dn2, rt0, rt00, dt_b, norm_b, _hh;\r\n\tstd::vector<Mat> rot_b2, dt_b2, norm2, base_rt2, rot2, homo2, t2;\r\n    Hm = H.getMat();\r\n\tbase_rt2.emplace_back(3,1,CV_64F);\r\n\tbase_rt2.emplace_back(Mat(3,1,CV_64F));\r\n\trot2.emplace_back(Mat(3,3,CV_64F));\r\n\trot2.emplace_back(Mat(3,3,CV_64F));\r\n\thomo2.emplace_back(Mat(3,3,CV_64F));\r\n\thomo2.emplace_back(Mat(3,3,CV_64F));\r\n\tt2.emplace_back(Mat(3,1,CV_64F));\r\n\tt2.emplace_back(Mat(3,1,CV_64F));\r\n\tint i ;\r\n\tint iter;\r\n\tdouble hh[3][3];\r\n\tdouble e1, e2;\r\n\r\n\tint nump;\r\n\tint q;\r\n\tint iter1;\r\n\tdouble errors[2];\r\n\tdouble s1;\r\n\tint num_patches;\r\n\tnum_patches = (int)num_inl.size();\r\n\t_hh = Mat(3,3,CV_64F,hh);\r\n\tnump = 0;\r\n\tfor(i = 0; i < num_patches; ++i)\r\n\t{\r\n\t\tnump += (int)num_inl[i];\r\n\t}\r\n\r\n\tdn = Mat(num_patches,3,CV_64F);\r\n\tdn2 = Mat(2*num_patches,3,CV_64F);\r\n\r\n\tHm.copyTo(h0);\r\n\r\n    Longuet_Higgins_Solution(h0, rot_b2, dt_b2, norm2);\r\n\tR = R2_1.t();\r\n\tdR = R * rot_b2[0];\r\n\tEigen::Matrix3d rot_e;\r\n\tEigen::Vector4d quat_e;\r\n\tEigen::Vector3d axis_e;\r\n\tcv2eigen(dR, rot_e);\r\n\tposelib::MatToQuat(rot_e, quat_e);\r\n\tposelib::QuatToAxisAngle(quat_e, axis_e, errors[0]);\r\n\tdR = R * rot_b2[1];\r\n\tcv2eigen(dR, rot_e);\r\n\tposelib::MatToQuat(rot_e, quat_e);\r\n\tposelib::QuatToAxisAngle(quat_e, axis_e, errors[1]);\r\n\r\n\t//\tthere are two solutions here\r\n\t//  pick up this solution, in which, the estimated surface faces more or less to the first camera\r\n\t//  because the camera 1 optical point is 0 0 1, therefore the larger abs(n[2]) one is the real solution\r\n\r\n\tif(errors[0] < errors[1])\r\n\t{\r\n\t\tbase_rt2[0] = rot_b2[0] * dt_b2[0];\r\n\t\tbase_rt2[1] = rot_b2[1] * dt_b2[1];\r\n\t\trot_b2[0].copyTo(rot_b);\r\n\t\tdt_b2[0].copyTo(dt_b);\r\n\t\tnorm2[0].copyTo(norm_b);\r\n\t}\r\n\telse\r\n\t{\r\n\t\tbase_rt2[0] = rot_b2[1] * dt_b2[1];\r\n\t\tbase_rt2[1] = rot_b2[0] * dt_b2[0];\r\n\t\trot_b2[1].copyTo(rot_b);\r\n\t\tdt_b2[1].copyTo(dt_b);\r\n\t\tnorm2[1].copyTo(norm_b);\r\n\t}\r\n\tdn.row(0) = Mat::zeros(1,3,CV_64F);\r\n\r\n\t//q is the index of which solution is used for HA\r\n\tfor(q = 0; q < 1; ++q)\r\n\t{\r\n\t\tHm.copyTo(h0);\r\n\t\tbase_rt2[q].copyTo(rt0);\r\n\t\trt0.copyTo(rt00);\r\n\t\te2 = 100000.0;\r\n\t\tfor(iter1 = 0; iter1 < 4; ++iter1)\r\n\t\t{\r\n\t\t\tfor(iter = 0 ; iter < MAX_ITERATION; ++iter)\r\n\t\t\t{\r\n\t\t\t\tdn.row(0) = Mat::zeros(1,3,CV_64F);\r\n\r\n\t\t\t\tfor(i = 1; i < num_patches; ++i)\r\n\t\t\t\t{\r\n\t\t\t\t\tcv::Mat tmp = dn.row(i);\r\n\t\t\t\t\tupdate_dn(inl_points[i].first, inl_points[i].second, (int)num_inl[i], h0, rt0, tmp);\r\n\t\t\t\t}\r\n\r\n\t\t\t\tupdate_h0_rt(inl_points,num_inl,h0,dn,rt0);\r\n\t\t\t\te1 = check_error(inl_points, num_inl, h0, dn, rt0);\r\n\r\n\t\t\t\tif((fabs(e1-e2) < 0.00001 || e1 < tol)&& iter > 2)\r\n\t\t\t\t{\r\n\t\t\t\t\tbreak;\r\n\t\t\t\t}\r\n\t\t\t\telse\r\n\t\t\t\t{\r\n\t\t\t\t\te2 = e1;\r\n\t\t\t\t}\r\n\t\t\t\t//update k\r\n\t\t\t\t//compute the total error\r\n\t\t\t}\r\n\t\t\t//update rt0\r\n            Longuet_Higgins_Solution_with_initial(h0, rot_b, dt_b, norm_b);\r\n\r\n\t\t\t//this may no tbe the right solution\r\n\t\t\trt0 = rot_b * dt_b;\r\n\t\t\trot_b.copyTo(rot2[q]);\r\n\t\t\tnorm_b.copyTo(norm2[q]);\r\n\t\t\th0.copyTo(homo2[q]);\r\n\t\t\tdt_b.copyTo(t2[q]);\r\n\r\n\t\t\te1 = check_error(inl_points, num_inl, h0, dn, rt0);\r\n\t\t\tif((fabs(e1-e2) < 0.000001 || e1 < tol)&& iter > 2)\r\n\t\t\t{\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t\telse\r\n\t\t\t{\r\n\t\t\t\te2 = e1;\r\n\t\t\t}\r\n\t\t\t//update k\r\n\t\t\t//compute the total error\r\n\t\t}\r\n\t\terrors[q] = e1;\r\n\t\tfor(i = 0; i < num_patches; ++i)\r\n\t\t{\r\n\t\t\tdn.row(i).copyTo(dn2.row(q*num_patches + i));//keep the old dn for the future uses\r\n\t\t}\r\n\t}\r\n\r\n\tnorm2[0].copyTo(norms.col(0));\r\n\trot2[0].copyTo(R2_1);\r\n\thomo2[0].copyTo(homo);\r\n\tt2[0].copyTo(t1_2);\r\n\r\n\tdn2.rowRange(0, num_patches).copyTo(dn);\r\n\r\n\t//compute the scale factor of the first homography and mulple it to rest dns\r\n\tfor(size_t j = 0; j < 3; j++)\r\n\t{\r\n\t\tfor(size_t j1 = 0; j1 < 3; j1++)\r\n\t\t{\r\n\t\t\thh[j][j1] = t1_2.at<double>(j) * norms.at<double>(j1,0);\r\n\t\t}\r\n\t}\r\n\th0 = Mat::eye(3,3,CV_64F);\r\n\t_hh = h0 - _hh;\r\n\th0 = R2_1 * _hh;\r\n\ts1 = h0.at<double>(2,2);\r\n\r\n\t// update the dn and surface normal vectors\r\n\r\n\tfor(i = 1; i < num_patches; ++i)\r\n\t{\r\n\t\tdn.row(i) = s1 * dn.row(i);\r\n\t\tnorms.col(i) = norms.col(0) - dn.row(i).t();\r\n\t}\r\n\r\n\treturn 1;\r\n}\r\n#undef MAX_ITERATION\r\n#endif\r\n\r\n/* Estimation of R, t & the plane normal vector (two possible solutions) based on the algorithm from Longuet-Higgine \"A computer\r\n * algorithm for reconstructing a scene from two projections\", 1981. These parameters are estimted from a homography H and its\r\n * inliers (in the camera coordinate system).\r\n *\r\n * InputArray H\t\t\t\t\t\t\tInput  -> Homography between images and a world plane in the camera coordinate system.\r\n * vector<Mat> R1_2\t\t\t\t\t\tOutput -> Two possible solutions for the rotation matrix.\r\n * vector<Mat> dt2in1\t\t\t\t\tOutput -> Two possible solutions for the translation vector.\r\n * vector<Mat> norm\t\t\t\t\t\tOutput -> Two possible solutions for the plane normal vector.\r\n *\r\n * Return value:\t\t\t\t\t\t1 :\t\tEverything ok\r\n *\t\t\t\t\t\t\t\t\t\t0 :\t\tEstimation not possible/failed\r\n */\r\nint Longuet_Higgins_Solution(cv::InputArray H, std::vector<cv::Mat> & R1_2, std::vector<cv::Mat> & dt2in1, std::vector<cv::Mat> & norm)\r\n{\r\n    Mat Hm = H.getMat();\r\n\tif(!R1_2.empty())\r\n\t\tR1_2.clear();\r\n\r\n\t{\r\n\t\tMat tmp = Mat(3,3,CV_64F);\r\n\t\tR1_2.push_back(tmp.clone());\r\n\t\tR1_2.push_back(tmp.clone());\r\n\t}\r\n\tif(!dt2in1.empty())\r\n\t\tdt2in1.clear();\r\n\r\n\t{\r\n\t\tMat tmp = Mat(3,1,CV_64F);\r\n\t\tdt2in1.push_back(tmp.clone());\r\n\t\tdt2in1.push_back(tmp.clone());\r\n\t}\r\n\tif(!norm.empty())\r\n\t\tnorm.clear();\r\n\r\n\t{\r\n\t\tMat tmp = Mat(3,1,CV_64F);\r\n\t\tnorm.push_back(tmp.clone());\r\n\t\tnorm.push_back(tmp.clone());\r\n\t}\r\n\r\n\tdouble hh[3][3], d[3], u[3][3], n[3], check, d2;\r\n    double p[3], t[3], tn[3][3];\r\n    double ts[3];\r\n    double ps[3] ;\r\n    double check1;\r\n    int s1, s2, iter, k, i;\r\n\r\n\tMat ht, ut, h_norm, x, r, _ts, _n, trans, plane, invtn, rot;\r\n\tMat _tn = Mat(3,3,CV_64F,tn);\r\n\tMat _hh = Mat(3,3,CV_64F,hh);\r\n\tMat _u = Mat(3,3,CV_64F,u);\r\n\tht = Hm.t();\r\n\t_hh = ht * Hm;\r\n    //u here is the Ut on the right side\r\n    jacobi_mat_33(hh, d, u, &iter);\r\n\tut = _u.t();\r\n\r\n\t_hh = d[1] * _hh;\r\n    d2 = 1.0/sqrt(d[1]);\r\n\th_norm = d2 * Hm;//the homo_norm is the homo transform with\r\n    d[0] = d[0]/d[1];\r\n    d[2] = d[2]/d[1];\r\n    d[1] = 1.0;\r\n\r\n    if(d[0] - d[1] < 0.000001 && d[1]- d[2] < 0.000001)\r\n    {\r\n        // the two images are too close each other\r\n\t\tdt2in1[0] = Mat::zeros(3,1,CV_64F);\r\n\t\tdt2in1[1] = Mat::zeros(3,1,CV_64F);\r\n        //the homography degerate to a rotation\r\n\t\th_norm.copyTo(R1_2[0]);\r\n\t\th_norm.copyTo(R1_2[1]);\r\n\r\n        //the surface normal cannot be estimated here\r\n\t\tnorm[0] = Mat::zeros(3,1,CV_64F);\r\n\t\tnorm[1] = Mat::zeros(3,1,CV_64F);\r\n        return 1;\r\n    }\r\n\r\n    if(d[0] > 1.0 && d[2] <= 1.0)\r\n    {\r\n        t[0] = sqrt((d[0] - 1.0)*d[2]/(d[0] - d[2]));\r\n        t[1] = 0.0;\r\n        t[2] = sqrt((1.0 - d[2])*d[0]/(d[0] - d[2]));\r\n        p[0] = sqrt((d[0] - 1.0)*d[0]/(d[0] - d[2]));\r\n        p[1] = 0.0;\r\n        p[2] = sqrt((1.0 - d[2])*d[2]/(d[0] - d[2]));\r\n    }\r\n    else\r\n    {\r\n        return 0;\r\n    }\r\n\tx = Mat::zeros(3,1,CV_64F);\r\n\tx.at<double>(2) = 1.0;\r\n    k = 0;\r\n\tr = _u * x;\r\n\t_ts = Mat(3,1,CV_64F,ts);\r\n\t_ts = Mat::zeros(3,1,CV_64F);\r\n\t_n = Mat(3,1,CV_64F,n);\r\n\r\n    for(s1 =-1; s1 <=1; s1 +=2)\r\n    {\r\n        for(s2 =-1; s2 <=1; s2 +=2)\r\n        {\r\n\t\t    ps[0] = -s1*p[0];\r\n\t\t\tps[1] = 0.0;\r\n\t\t\tps[2] = -s2*p[2];\r\n\t\t    n[0] = s1*t[0] + ps[0];\r\n\t\t    n[1] = 0.0;\r\n\t\t    n[2] = s2*t[2] + ps[2];\r\n\t\t\tts[0] = s1*t[0];\r\n\t\t\tts[1] = 0.0;\r\n\t\t\tts[2] = s2*t[2];\r\n\r\n\t\t\ttrans = _u * _ts;\r\n\t\t\tplane = _u * _n;\r\n\t\t\tcheck1 = _n.dot(r);\r\n\t\t\tcheck = trans.dot(plane) - 1.0;\r\n\r\n\t\t\tif(plane.at<double>(2) > 0.0 )\r\n\t\t\t{\r\n\t\t\t\ttrans.copyTo(dt2in1[k]);\r\n\t\t\t\tplane.copyTo(norm[k]);\r\n\t\t\t\tk++;\r\n\t\t\t}\r\n         }\r\n    }\r\n\r\n\r\n    for(i = 0; i < k; ++i)\r\n    {\r\n\t\tfor(size_t j = 0; j < 3; j++)\r\n\t\t{\r\n\t\t\tfor(size_t j1 = 0; j1 < 3; j1++)\r\n\t\t\t{\r\n\t\t\t\ttn[j][j1] = dt2in1[i].at<double>(j) * norm[i].at<double>(j1);\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\ttn[0][0] -=1.0;\r\n\t\ttn[1][1] -=1.0;\r\n\t\ttn[2][2] -=1.0;\r\n\t\t_tn = -1.0 * _tn;\r\n\t\tinvtn = _tn.inv();\r\n        rot = h_norm * invtn;\r\n\t\tif(determinant(rot) < 0.0)\r\n\t\t{\r\n\t\t\trot = -1.0 * rot;\r\n\t\t}\r\n\t\trot.copyTo(R1_2[i]);\r\n    }\r\n\r\n    return 1;\r\n}\r\n\r\n/* Estimation of R, t & the plane normal vector (two possible solutions) based on the algorithm from Longuet-Higgine \"A computer\r\n * algorithm for reconstructing a scene from two projections\", 1981. These parameters are estimted from a homography H and its\r\n * inliers (in the camera coordinate system).\r\n *\r\n * InputArray H\t\t\t\t\t\t\tInput  -> Homography between images and a world plane in the camera coordinate system.\r\n * vector<Mat> R1_2\t\t\t\t\t\tOutput -> The resulting rotation matrix.\r\n * vector<Mat> dt1\t\t\t\t\t\tInput & Output -> As input an initial translation vector has to be specified. The resulting\r\n *\t\t\t\t\t\t\t\t\t\t\t\t\t\t  translation vector is copied back to dt1.\r\n * vector<Mat> norm\t\t\t\t\t\tOutput -> The resulting plane normal vector.\r\n *\r\n * Return value:\t\t\t\t\t\t1 :\t\tEverything ok\r\n *\t\t\t\t\t\t\t\t\t\t0 :\t\tEstimation not possible/failed\r\n */\r\nint Longuet_Higgins_Solution_with_initial(cv::InputArray H, cv::Mat & R2_1, cv::Mat & dt1, cv::Mat & norm1)\r\n{\r\n    Mat Hm = H.getMat();\r\n\tdouble hh[3][3], d[3], u[3][3], n[3], check, d2;\r\n    double p[3], t[3], tn[3][3];\r\n\r\n    double ts[3];\r\n    double ps[3] ;\r\n\r\n    double check1;\r\n\r\n    int s1, s2, iter, i;\r\n\r\n\tMat ht, h_norm, rot, x, r, _ts, trans, plane, _ps, _n, invtn;\r\n\tvector<Mat> dt, norm;\r\n\tMat _tn = Mat(3,3,CV_64F,tn);\r\n\tMat _hh = Mat(3,3,CV_64F,hh);\r\n\tMat _u = Mat(3,3,CV_64F,u);\r\n\r\n\tht = Hm.t();\r\n\t_hh = ht * Hm;\r\n    //u here is the Ut on the right side\r\n    jacobi_mat_33(hh, d, u, &iter);\r\n\r\n\r\n    //if d[1] != 1.0 make a correction\r\n\t_hh = -1.0 * _hh;\r\n    d2 = 1.0/sqrt(d[1]);\r\n\th_norm = d2 * Hm;//the homo_norm is the homo transform with\r\n    d[0] = d[0]/d[1];\r\n    d[2] = d[2]/d[1];\r\n    d[1] = 1.0;\r\n    if(d[0] - d[1] < 0.000001 && d[1]- d[2] < 0.000001)\r\n    {\r\n        // the two images are too close each other\r\n\t\tdt1 = Mat::zeros(3,1,CV_64F);\r\n        //the homography degerate to a rotation\r\n\t\th_norm.copyTo(rot);\r\n\t\th_norm.copyTo(R2_1);\r\n\r\n        //the surface normal cannot be estimated here\r\n\t\tnorm1 = Mat::zeros(3,1,CV_64F);\r\n        return 1;\r\n    }\r\n\r\n    if(d[0] > 1.0 && d[2] <= 1.0)\r\n    {\r\n        t[0] = sqrt((d[0] - 1.0)*d[2]/(d[0] - d[2]));\r\n        t[1] = 0.0;\r\n        t[2] = sqrt((1.0 - d[2])*d[0]/(d[0] - d[2]));\r\n        p[0] = sqrt((d[0] - 1.0)*d[0]/(d[0] - d[2]));\r\n        p[1] = 0.0;\r\n        p[2] = sqrt((1.0 - d[2])*d[2]/(d[0] - d[2]));\r\n    }\r\n    else\r\n    {\r\n        return 0;\r\n    }\r\n\r\n\tx = Mat::zeros(3,1,CV_64F);\r\n\tx.at<double>(2) = 1.0;\r\n\tr = _u * x;\r\n\t_ts = Mat(3,1,CV_64F,ts);\r\n\t_ts = Mat::zeros(3,1,CV_64F);\r\n\t_n = Mat(3,1,CV_64F,n);\r\n\r\n    for(s1 =-1; s1 <=1; s1 +=2)\r\n    {\r\n        for(s2 =-1; s2 <=1; s2 +=2)\r\n        {\r\n\t\t    ps[0] = -s1*p[0];\r\n\t\t\tps[1] = 0.0;\r\n\t\t\tps[2] = -s2*p[2];\r\n\t\t    n[0] = s1*t[0] + ps[0];\r\n\t\t    n[1] = 0.0;\r\n\t\t    n[2] = s2*t[2] + ps[2];\r\n\t\t\tts[0] = s1*t[0];\r\n\t\t\tts[1] = 0.0;\r\n\t\t\tts[2] = s2*t[2];\r\n\r\n\t\t\ttrans = _u * _ts;\r\n\t\t\tplane = _u * _n;\r\n\t\t\tcheck1 = _n.dot(r);\r\n\t\t\tcheck = trans.dot(plane) - 1.0;\r\n\r\n\t\t\tif(plane.at<double>(2) > 0.0 )\r\n\t\t\t{\r\n\t\t\t\tdt.push_back(trans.clone());\r\n\t\t\t\tnorm.push_back(plane.clone());\r\n\t\t\t}\r\n        }\r\n    }\r\n\tif(dt[0].dot(dt1) > dt[1].dot(dt1)){\r\n\t\ti = 0;\r\n\t\tdt[0].copyTo(dt1);\r\n\t\tnorm[0].copyTo(norm1);\r\n    }else{\r\n\t    i = 1;\r\n\t\tdt[1].copyTo(dt1);\r\n\t\tnorm[1].copyTo(norm1);\r\n    }\r\n\r\n\tfor(size_t j = 0; j < 3; j++)\r\n\t{\r\n\t\tfor(size_t j1 = 0; j1 < 3; j1++)\r\n\t\t{\r\n\t\t\ttn[j][j1] = dt[i].at<double>(j) * norm[i].at<double>(j1);\r\n\t\t}\r\n\t}\r\n    tn[0][0] -=1.0;\r\n    tn[1][1] -=1.0;\r\n    tn[2][2] -=1.0;\r\n\t_tn = -1.0 * _tn;\r\n\tinvtn = _tn.inv();\r\n\trot = h_norm * invtn;\r\n\r\n    if(determinant(rot) < 0.0)\r\n    {\r\n\t\trot = -1.0 * rot;\r\n    }\r\n    rot.copyTo(R2_1);\r\n\r\n    return 1;\r\n}\r\n\r\n/* Diagonalization of the matrix W=(H^T)H with the unknown orthogonal matrix U (where H is a homography) to solve UWU^T=Diag(d1, d2, d3)\r\n * as described in the paper \"Real-time Surface Estimation by Homography Alignment for Spacecraft Safe Landing\" from Yang Cheng\r\n * in 2010. The input to this function is a=W=(H^T)H. The output are the 3 diagonal elemnts d and the matrix v=U^T.\r\n *\r\n * double a[3][3]\t\t\t\t\t\tInput  -> Matrix W=(H^T)H, where H is a homography matrix\r\n * double d[3]\t\t\t\t\t\t\tOutput -> The resulting diagonal entries of the diagonal matrix Diag(d1, d2, d3)\r\n * double v[3][3]\t\t\t\t\t\tOutput -> The resulting orthogonal matrix U^T\r\n * int *nrot\t\t\t\t\t\t\tOutput -> Number of iterations needed for estimating d and v\r\n *\r\n * Return value:\t\t\t\t\t\t1 :\t\tEverything ok\r\n *\t\t\t\t\t\t\t\t\t\t0 :\t\tEstimation failed (max. number of iterations exceeded)\r\n */\r\n#define ROTATE(a,i,j,k,l) g=a[i][j];h=a[k][l];a[i][j]=g-s*(h+g*tau);\\\r\n\ta[k][l]=h+s*(g-h*tau);\r\n\r\nint jacobi_mat_33(double a[3][3], double *d, double v[3][3], int *nrot)\r\n{\r\n\tint j,iq,ip,i;\r\n\tdouble tresh,theta,tau,t,sm,s,h,g,c, b[3],z[3];\r\n    double dt[3][3], abc[3][3], tmp[3][3], tmp1[3][3];\r\n\tmemcpy(abc,a,9*sizeof(double));\r\n\r\n\tfor (ip=0;ip<3;ip++) {\r\n\t\tfor (iq=0;iq<3;iq++) v[ip][iq]=0.0;\r\n\t\tv[ip][ip]=1.0;\r\n\t}\r\n\tfor (ip=0;ip< 3;ip++) {\r\n\t\tb[ip]=d[ip]=a[ip][ip];\r\n\t\tz[ip]=0.0;\r\n\t}\r\n\t*nrot=0;\r\n\tfor (i=1;i<=50;i++) {\r\n\t\tsm=0.0;\r\n\t\tfor (ip=0;ip<2;ip++) {\r\n\t\t\tfor (iq=ip+1;iq< 3;iq++)\r\n\t\t\t\tsm += fabs(a[ip][iq]);\r\n\t\t}\r\n\t\tif (sm < 0.000001) {\r\n\t\t\tif(d[1] > d[0])\r\n\t\t\t{\r\n\t\t\t\tc = d[0];\r\n\t\t\t\td[0] = d[1];\r\n\t\t\t\td[1] = c;\r\n\t\t\t\tmemset(dt,0,9*sizeof(double));\r\n\t\t\t\tdt[0][1] = 1.0;\r\n\t\t\t\tdt[1][0] = 1.0;\r\n\t\t\t\tdt[2][2] = 1.0;\r\n\r\n\t\t\t\tMat _v = Mat(3,3,CV_64F,v);\r\n\t\t\t\tMat _dt = Mat(3,3,CV_64F,dt);\r\n\t\t\t\tMat _tmp = Mat(3,3,CV_64F,tmp);\r\n\t\t\t\t_tmp = _v * _dt;\r\n\r\n\t\t\t\tmemcpy(v,tmp,9*sizeof(double));\r\n\t\t\t}\r\n\t\t\tif(d[2] > d[1])\r\n\t\t\t{\r\n\t\t\t\tc = d[1];\r\n\t\t\t\td[1] = d[2];\r\n\t\t\t\td[2] = c;\r\n\t\t\t\tmemset(dt,0,9*sizeof(double));\r\n\t\t\t\tdt[0][0] = 1.0;\r\n\t\t\t\tdt[1][2] = 1.0;\r\n\t\t\t\tdt[2][1] = 1.0;\r\n\r\n\t\t\t\tMat _v = Mat(3,3,CV_64F,v);\r\n\t\t\t\tMat _dt = Mat(3,3,CV_64F,dt);\r\n\t\t\t\tMat _tmp = Mat(3,3,CV_64F,tmp);\r\n\t\t\t\t_tmp = _v * _dt;\r\n\r\n\t\t\t\tmemcpy(v,tmp,9*sizeof(double));\r\n\t\t\t}\r\n\t\t\tif(d[1] > d[0])\r\n\t\t\t{\r\n\t\t\t\tc = d[0];\r\n\t\t\t\td[0] = d[1];\r\n\t\t\t\td[1] = c;\r\n\t\t\t\tmemset(dt,0,9*sizeof(double));\r\n\t\t\t\tdt[0][1] = 1.0;\r\n\t\t\t\tdt[1][0] = 1.0;\r\n\t\t\t\tdt[2][2] = 1.0;\r\n\r\n\t\t\t\tMat _v = Mat(3,3,CV_64F,v);\r\n\t\t\t\tMat _dt = Mat(3,3,CV_64F,dt);\r\n\t\t\t\tMat _tmp = Mat(3,3,CV_64F,tmp);\r\n\t\t\t\t_tmp = _v * _dt;\r\n\r\n\t\t\t\tmemcpy(v,tmp,9*sizeof(double));\r\n\t\t\t}\r\n\t\t\tMat _v = Mat(3,3,CV_64F,v);\r\n\t\t\tMat _dt = Mat(3,3,CV_64F,dt);\r\n\t\t\t_dt = _v.t();\r\n\t\t\tMat _abc = Mat(3,3,CV_64F,abc);\r\n\t\t\tMat _tmp = Mat(3,3,CV_64F,tmp);\r\n\t\t\t_tmp = _dt * _abc;\r\n\t\t\tMat _tmp1 = Mat(3,3,CV_64F,tmp1);\r\n\t\t\t_tmp1 = _tmp * _v;\r\n\t\t\tmemcpy(a,abc,9*sizeof(double));//copy back the a\r\n\t\t\treturn 1;\r\n\t\t}\r\n\t\tif (i < 4)\r\n\t\t\ttresh=0.2*sm/9;\r\n\t\telse\r\n\t\t\ttresh=0.0;\r\n\t\tfor (ip=0;ip<3-1;ip++) {\r\n\t\t\tfor (iq=ip+1;iq<3;iq++) {\r\n\t\t\t\tg=100.0*fabs(a[ip][iq]);\r\n\t\t\t\tif (i > 4 && (fabs(d[ip])+g) == fabs(d[ip])\r\n\t\t\t\t\t&& (fabs(d[iq])+g) == fabs(d[iq]))\r\n\t\t\t\t\ta[ip][iq]=0.0;\r\n\t\t\t\telse if (fabs(a[ip][iq]) > tresh) {\r\n\t\t\t\t\th=d[iq]-d[ip];\r\n\t\t\t\t\tif ((fabs(h)+g) == fabs(h))\r\n\t\t\t\t\t\tt=(a[ip][iq])/h;\r\n\t\t\t\t\telse {\r\n\t\t\t\t\t\ttheta=0.5*h/(a[ip][iq]);\r\n\t\t\t\t\t\tt=1.0/(fabs(theta)+sqrt(1.0+theta*theta));\r\n\t\t\t\t\t\tif (theta < 0.0) t = -t;\r\n\t\t\t\t\t}\r\n\t\t\t\t\tc=1.0/sqrt(1+t*t);\r\n\t\t\t\t\ts=t*c;\r\n\t\t\t\t\ttau=s/(1.0+c);\r\n\t\t\t\t\th=t*a[ip][iq];\r\n\t\t\t\t\tz[ip] -= h;\r\n\t\t\t\t\tz[iq] += h;\r\n\t\t\t\t\td[ip] -= h;\r\n\t\t\t\t\td[iq] += h;\r\n\t\t\t\t\ta[ip][iq]=0.0;\r\n\t\t\t\t\tfor (j=0;j<=ip-1;j++) {\r\n\t\t\t\t\t\tROTATE(a,j,ip,j,iq)\r\n\t\t\t\t\t}\r\n\t\t\t\t\tfor (j=ip+1;j<=iq-1;j++) {\r\n\t\t\t\t\t\tROTATE(a,ip,j,j,iq)\r\n\t\t\t\t\t}\r\n\t\t\t\t\tfor (j=iq+1;j<3;j++) {\r\n\t\t\t\t\t\tROTATE(a,ip,j,iq,j)\r\n\t\t\t\t\t}\r\n\t\t\t\t\tfor (j=0;j<3;j++) {\r\n\t\t\t\t\t\tROTATE(v,j,ip,j,iq)\r\n\t\t\t\t\t}\r\n\t\t\t\t\t++(*nrot);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\tfor (ip=0;ip<3;ip++) {\r\n\t\t\tb[ip] += z[ip];\r\n\t\t\td[ip]=b[ip];\r\n\t\t\tz[ip]=0.0;\r\n\t\t}\r\n\t}\r\n\treturn 0;\r\n}\r\n#undef ROTATE\r\n\r\ndouble Check_motion_error(std::vector<std::pair<cv::Mat,cv::Mat>> inl_points,\r\n\t\t\t\t\t\t  std::vector<unsigned int> num_inl,\r\n\t\t\t\t\t\t  const cv::Mat& R1_2,\r\n\t\t\t\t\t\t  const cv::Mat& t)\r\n{\r\n\tMat c0, R2_1, p, r1, r2, p1, p2, dp;\r\n\tsize_t num_homo = num_inl.size();\r\n    size_t i, j;\r\n\tdouble error, error1;\r\n\tint total_pts;\r\n\r\n\tc0 = Mat::zeros(3,1,CV_64F);\r\n\tR2_1 = R1_2.t();\r\n\ttotal_pts = 0;\r\n\terror = 0.0;\r\n\tfor(i = 0; i < num_homo; ++i)\r\n\t{\r\n\t\terror1 = 0;\r\n\t\tfor(j = 0; j < num_inl[i]; ++j)\r\n\t\t{\r\n\t\t\tp = (Mat_<double>(3, 1) << inl_points[i].first.at<double>(j,0), inl_points[i].first.at<double>(j,1), 1.0);\r\n\r\n\t\t\tr1 = p / cv::norm(p);\r\n\r\n\t\t\tp = (Mat_<double>(3, 1) << inl_points[i].second.at<double>(j,0), inl_points[i].second.at<double>(j,1), 1.0);\r\n\r\n\t\t\tp1 = R2_1 * p;\r\n\t\t\tr2 = p1 / cv::norm(p1);\r\n\r\n\t\t\tif(Rays_Closest_Points(c0, r1, t, r2, p1, p2) != 0)\r\n\t\t\t{\r\n\t\t\t\tdp = p1 - p2;\r\n\t\t\t\terror1 += cv::norm(dp);\r\n\r\n\t\t\t\ttotal_pts++;\r\n\t\t\t}\r\n\t\t}\r\n\t\terror +=error1;\r\n\t}\r\n\treturn error/(double)total_pts;\r\n}\r\n\r\nint Rays_Closest_Points(const cv::Mat& pt1, const cv::Mat& ray1, const cv::Mat& pt2, const cv::Mat& ray2, cv::Mat & p1, cv::Mat & p2)\r\n{\r\n    double m1, m2, dotp, dotbv1, dotbv2;\r\n\tMat b;\r\n\r\n\tif(fabs(ray1.dot(ray2)) >0.9999999)\r\n\t{\r\n\t\t//two rays are close to parallel\r\n\t\treturn 0;\r\n\t}\r\n\tb = pt2 - pt1;\r\n\tdotp = ray1.dot(ray2);\r\n\tdotbv1 = b.dot(ray1);\r\n\tdotbv2 = b.dot(ray2);\r\n\r\n\tif(dotp == 0.0)\r\n\t{\r\n\t\tm1 = dotbv1;\r\n\t\tm2 = dotbv2;\r\n\t}\r\n\telse\r\n\t{\r\n\t\tm1 = (dotbv1 - dotbv2*dotp)/(1.0-dotp*dotp);\r\n\t\tm2 = dotp*m1 - dotbv2;\r\n\t}\r\n\tp1 = m1 * ray1;\r\n\tp2 = m2 * ray2;\r\n\tp1 = pt1 + p1;\r\n\tp2 = pt2 + p2;\r\n\treturn 1;\r\n}\r\n\r\nint update_dn(cv::Mat points1, cv::Mat points2, int num_pts, const cv::Mat& h0, const cv::Mat& k0, cv::Mat & dn)\r\n{\r\n\tMat A, B, invA, p, p1, t, t1, _hp, _tt, ty;\r\n\tint i;\r\n\r\n\tdouble hp[3];\r\n\tdouble tt[3][3];\r\n\tdouble y;\r\n\tdouble d;\r\n\tdouble *_k0;\r\n\t_k0 = (double*)k0.data;\r\n\t_tt = Mat(3,3,CV_64F,tt);\r\n\t_hp = Mat(3,1,CV_64F,hp);\r\n\tB = Mat::zeros(3,1,CV_64F);\r\n\tA = Mat::zeros(3,3,CV_64F);\r\n\tfor(i = 0; i < num_pts; ++i)\r\n\t{\r\n\t\tp = (Mat_<double>(3, 1) << points1.at<double>(i,0), points1.at<double>(i,1), 1.0);\r\n\t\tp1 = (Mat_<double>(3, 1) << points2.at<double>(i,0), points2.at<double>(i,1), 1.0);\r\n\t\tt = _k0[0] * p;\r\n\t\td = _k0[2] * points2.at<double>(i,0);\r\n\t\tt1 = d * p;\r\n\t\tt = t - t1;\r\n\t\t_hp = h0 * p;\r\n\t\ty = points2.at<double>(i,0) * hp[2] - hp[0];\r\n\t\tfor(int j = 0; j < 3; j++)\r\n\t\t{\r\n\t\t\tfor(int j1 = 0; j1 < 3; j1++)\r\n\t\t\t{\r\n\t\t\t\ttt[j][j1] = t.at<double>(j) * t.at<double>(j1);\r\n\t\t\t}\r\n\t\t}\r\n\t\tty = y * t;\r\n\t\tA = _tt + A;\r\n\t\tB = ty + B;\r\n\r\n\t\tt = _k0[1] * p;\r\n\t\td = _k0[2] * points2.at<double>(i,1);\r\n\t\tt1 = d * p;\r\n\t\tt = t - t1;\r\n\t\t_hp = h0 * p;\r\n\t\ty = points2.at<double>(i,1) * hp[2] - hp[1];\r\n\t\tfor(int j = 0; j < 3; j++)\r\n\t\t{\r\n\t\t\tfor(int j1 = 0; j1 < 3; j1++)\r\n\t\t\t{\r\n\t\t\t\ttt[j][j1] = t.at<double>(j) * t.at<double>(j1);\r\n\t\t\t}\r\n\t\t}\r\n\t\tty = y * t;\r\n\t\tA = _tt + A;\r\n\t\tB = ty + B;\r\n\t}\r\n\tinvA = A.inv();\r\n\tdn = (invA * B).t();\r\n\r\n\treturn 1;\r\n}\r\n\r\n int update_h0_rt(std::vector<std::pair<cv::Mat,cv::Mat>> inl_points,\r\n\t\t\t\t  std::vector<unsigned int> num_inl,\r\n\t\t\t\t  cv::Mat & homo,\r\n\t\t\t\t  const cv::Mat& dn,\r\n\t\t\t\t  cv::Mat & rt)\r\n{\r\n\tMat rt_back, _p1;\r\n\tsize_t num_homo = num_inl.size();\r\n\tdouble *_homo;\r\n\tdouble *_rt;\r\n\t_homo = (double*)homo.data;\r\n\t_rt = (double*)rt.data;\r\n    size_t i, j;\r\n\tdouble r[11];\r\n\tdouble a[121], inva[121], b[11], m[11];\r\n\tdouble c[121];\r\n\tdouble p1[3];\r\n\tdouble p2[3];\r\n\tdouble d;\r\n\tdouble dnp;\r\n\t_p1 = Mat(3,1,CV_64F,p1);\r\n\r\n\trt.copyTo(rt_back);\r\n\tfor(i = 0; i<11; ++i)\r\n\t{\r\n\t\tb[i] = 0.0;\r\n\t\tm[i] = 0.0;\r\n\t}\r\n\tfor(i = 0; i < 121; ++i)\r\n\t{\r\n\t\ta[i] = 0.0;\r\n\t}\r\n\tfor(i = 0; i < num_homo; ++i)\r\n\t{\r\n\t\tfor(j = 0; j < num_inl[i]; ++j)\r\n\t\t{\r\n\t\t\tp1[0] = inl_points[i].first.at<double>(j,0);\r\n\t\t\tp1[1] = inl_points[i].first.at<double>(j,1);\r\n\t\t\tp1[2] = 1.0;\r\n\r\n\t\t\tdnp = _p1.dot(dn.row(i).t());\r\n\t\t\tp2[0] = inl_points[i].second.at<double>(j,0);\r\n\t\t\tp2[1] = inl_points[i].second.at<double>(j,1);\r\n\t\t\tr[0] = p1[0];\r\n\t\t\tr[1] = p1[1];\r\n\t\t\tr[2] = 1.0;\r\n\t\t\tr[3] = 0.0;\r\n\t\t\tr[4] = 0.0;\r\n\t\t\tr[5] = 0.0;\r\n\r\n\t\t\tr[6] = (double)(-p1[0]*p2[0]);\r\n\t\t\tr[7] = (double)(-p1[1]*p2[0]);\r\n\r\n\t\t\tr[8] = dnp;\r\n\t\t\tr[9] = 0.0;\r\n\t\t\tr[10] = -p2[0]*dnp;\r\n            Linear_Transform_D(r, r, c, 11, 1, 11);\r\n            add_matrix_D(c, a, a, 11, 11);\r\n\t\t\td = (double)p2[0];\r\n            scale_matrix_D(d, r, r, 11, 1);\r\n            add_matrix_D(r, b, b, 11, 1);\r\n\r\n\t\t\tr[0] = 0.0;\r\n\t\t\tr[1] = 0.0;\r\n\t\t\tr[2] = 0.0;\r\n\t\t\tr[3] = p1[0];\r\n\t\t\tr[4] = p1[1];\r\n\t\t\tr[5] = 1.0;\r\n\r\n\t\t\tr[6] = (double)(-p1[0]*p2[1]);\r\n\t\t\tr[7] = (double)(-p1[1]*p2[1]);\r\n\r\n\t\t\tr[8] = 0.0;\r\n\t\t\tr[9] = dnp;\r\n\t\t\tr[10] = -p2[1]*dnp;\r\n            Linear_Transform_D(r, r, c, 11, 1, 11);\r\n            add_matrix_D(c, a, a, 11, 11);\r\n\t\t\td = (double)p2[1];\r\n            scale_matrix_D(d, r, r, 11, 1);\r\n            add_matrix_D(r, b, b, 11, 1);\r\n\t\t}\r\n\t}\r\n\tif(invert_matrix_D(a, inva, 11, 11) == 0)\r\n\t{\r\n\t\treturn (0);\r\n\t}\r\n\r\n    Linear_Transform_D(inva, b, m, 11, 11, 1);\r\n\t_homo[0] = m[0];\r\n\t_homo[1] = m[1];\r\n\t_homo[2] = m[2];\r\n\r\n\t_homo[3] = m[3];\r\n\t_homo[4] = m[4];\r\n\t_homo[5] = m[5];\r\n\r\n\t_homo[6] = m[6];\r\n\t_homo[7] = m[7];\r\n\t_homo[8] = 1.0;\r\n\t_rt[0] = m[8];\r\n\t_rt[1] = m[9];\r\n\t_rt[2] = m[10];\r\n\treturn 1;\r\n}\r\n\r\n/* Linear transformations, for transforming vectors and matrices.\r\n * This works for row vectors and column vectors alike.\r\n *\tL[nRows][lCol]\t- input (left) matrix\r\n *\trg[lCol][rCol]\t- transformation (right) matrix\r\n *\tP[nRows][rCol]\t- output (product) matrix\r\n *\r\n * Examples:\r\n * v[3] * M[3][3] -> w[3] :\t\t\tMLLinearTransform(&v[0], &M[0][0], &w[0], 1, 3, 3);\r\n * M[3][3] * v[3] -> w[3] :\t\t\tMLLinearTransform(&M[0][0], &v[0], &w[0], 3, 3, 1);\r\n * M[4][4] * N[4][4] -> P[4][4]:\tMLLinearTransform(&M[0][0], &N[0][0], &P[0][0], 4, 4, 4);\r\n * v[4] * M[4][3] -> w[3]:\t\t\tMLLinearTransform(&v[0], &M[0][0], &w[0], 1, 4, 3);\r\n * v[3] tensor w[3] -> T[3][3]:\t\tMLLinearTransform(&v[0], &w[0], T[3][3], 3, 1, 3);\r\n * This can be used In Place, i.e.,\r\n * to transform the left matrix\r\n * by the right matrix, placing the result back in the left.  By its nature,\r\n * then, this can only be used for transforming row vectors or concatenating\r\n * matrices from the right.\r\n */\r\n#define MAXDIM\t32\t\t\t/* The maximum dimension of a matrix */\r\n\r\nvoid Linear_Transform_D(\r\n        const double *L, //The left mat\r\n        const double *R, //The right mat\r\n        double\t*P,\t//The result mat\r\n        int nRows, //Number of rows of the left and result matrices\r\n        int lCol, //Number of columns in the left matrix\r\n        int rCol) //The number of columns in the result matrix\r\n{\r\n\tconst double *lp;\t\t/* Left matrix pointer for dot product */\r\n\tconst char *rp;\t\t/* Right matrix pointer for dot product */\r\n\tint k;\t\t\t\t/* Loop counter */\r\n\tdouble sum;\t\t\t/* Extended precision for intermediate results */\r\n    size_t rowBytes = lCol * sizeof(double);\r\n    size_t rRowBytes = rCol * sizeof(double);\r\n\tint j, i;\t\t\t\t/* Loop counters */\r\n\tsize_t lRowBytes = lCol * sizeof(double);\r\n\tconst char *lb = (const char*)L;\r\n\tdouble temp[MAXDIM*MAXDIM]; // Temporary storage for in-place transformations\r\n\tdouble *tp;\r\n\r\n\tif (P == L) {  // IN PLACE\r\n\t\tdouble *op = P;\t\t\t\t/* Output geometry */\r\n\t\tfor (i = nRows; i--; lb += rowBytes) {\t/* Each row in L */\r\n\t\t\t{\r\n\t\t\t\tfor (k = lCol, lp = (double*)lb, tp = &temp[0]; k--; )\r\n\t\t\t\t\t*tp++ = *lp++;\t\t\t/* Copy one input vector to temp storage */\r\n\t\t\t}\r\n\t\t\tfor (j = 0; j < lCol; j++) {\t\t/* Each column in R */\r\n\t\t\t\tlp = &temp[0];\t\t\t\t/* Left of ith row of L */\r\n\t\t\t\trp = (const char *)(R + j);\t/* Top of jth column of R */\r\n\t\t\t\tsum = 0;\r\n\t\t\t\tfor (k = lCol; k--; rp += rowBytes)\r\n\t\t\t\t\tsum += *lp++ * (*((const double*)rp));\t/* *P += L[i'][k'] * R[k'][j] */\r\n\t\t\t\t*op++ = sum;\r\n\t\t\t}\r\n\t\t}\r\n\t} else if (P != R) {\r\n\t\tfor (i = nRows; i--; lb += lRowBytes) {\t/* Each row in L */\r\n\t\t\tfor (j = 0; j < rCol; j++) {\t/* Each column in R */\r\n\t\t\t\tlp = (const double *)lb;\t\t/* Left of ith row of L */\r\n\t\t\t\trp = (const char *)(R + j);\t/* Top of jth column of R */\r\n\t\t\t\tsum = 0;\r\n\t\t\t\tfor (k = lCol; k--; rp += rRowBytes)\r\n\t\t\t\t\tsum += *lp++ * (*((const double*)rp));\t/* *P += L[i'][k'] * R[k'][j] */\r\n\t\t\t\t*P++ = sum;\r\n\t\t\t}\r\n\t\t}\r\n\t} else { // P == R\r\n\t\tfor (tp = temp, i = lCol * rCol; i--; ) *tp++ = *R++;  // copy R\r\n\t\tfor (i = nRows; i--; lb += lRowBytes) {\t/* Each row in L */\r\n\t\t\tfor (j = 0; j < rCol; j++) {\t/* Each column in R */\r\n\t\t\t\tlp = (const double *)lb;\t\t/* Left of ith row of L */\r\n\t\t\t\trp = (const char *)(temp + j);\t/* Top of jth column of R (now in temp) */\r\n\t\t\t\tsum = 0;\r\n\t\t\t\tfor (k = lCol; k--; rp += rRowBytes)\r\n\t\t\t\t\tsum += *lp++ * (*((const double*)rp));\t/* *P += L[i'][k'] * R[k'][j] */\r\n\t\t\t\t*P++ = sum;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n}\r\n\r\nvoid add_matrix_D(double *A, double *B, double *result, int m, int n)\r\n{\r\n\tfor (int i = m * n; i --; A++, B++, result ++)\r\n\t\t*result = (*A) + (*B);\r\n}\r\n\r\nvoid scale_matrix_D (double scale, double *from, double *to, int m, int n)\r\n{\r\n\tfor (int i = m * n; i--; from ++, to++)\r\n\t\t*to = scale * (*from);\r\n}\r\n\r\n/*  Inverts square matrices\r\n *\tWith tall matrices, invert upper part and transform the bottom\r\n *\trows as would be expected if embedded into a larger matrix.\r\n *\tUndefined for wide matrices.\r\n * M^(-1) --> Minv\r\n *\r\n * 1 is returned if the matrix was non-singular and the inversion was successful\r\n * 0 is returned if the matrix was singular and the inversion failed\r\n */\r\n\r\nsize_t invert_matrix_D (const double *M, double *Minv, int nRows, int n)\r\n{\r\n\tdouble *m;\r\n\tint tallerBy = nRows - n;\t\t/* Excess of rows over columns */\r\n\tint j, i;\r\n\tdouble b[MAXDIM];\r\n\tdouble lu[MAXDIM*MAXDIM+MAXDIM];\r\n\r\n\t/* Decompose matrix into L and U triangular matrices */\r\n\tif ((tallerBy < 0) || (LU_decompose_D(M, lu, n) == 0)) {\r\n\t\treturn(0);\t\t/* Singular */\r\n\t}\r\n\r\n\t/* Invert matrix by solving n simultaneous equations n times */\r\n\tfor (i = 0, m = Minv; i < n; i++, m += n) {\r\n\t\tfor(j = 0; j < n; j++)\r\n\t\t\tb[j] = 0;\r\n\t\tb[i] = 1;\r\n\r\n        LU_solve_D(lu, b, m, n);\t/* Into a row of m */\r\n\t}\r\n\r\n\t/* Special post-processing for affine transformations (e.g. 4x3) */\r\n\tif (tallerBy) {\t/* Affine transformation */\r\n\t\tdouble *t = Minv+n*n;/* Translation vector */\r\n\t\tm = Minv;/* Reset m */\r\n        Linear_Transform_D(t, m, t, tallerBy, n, n);/* Invert translation */\r\n\t\tfor (j = tallerBy * n; n--; t++)\r\n\t\t\t*t = -*t;/* Negate translation vector */\r\n\t}\r\n\r\n\treturn(1);\r\n}\r\n\r\n/* Decomposes the coefficient matrix A into upper and lower\r\n * triangular matrices, the composite being the LU matrix.\r\n * This is then followed by multiple applications of FELUSolve(),\r\n * to solve several problems with the same system matrix.\r\n *\r\n * 1 is returned if the matrix is non-singular and the decomposition was successful;\r\n * 0 is returned if the matrix is singular and the decomposition failed.\r\n */\r\n#define luel(i, j)  lu[(i)*n+(j)]\r\n#define ael(i, j)\ta[(i)*n+(j)]\r\n\r\nsize_t LU_decompose_D(\r\n        const double *a, //n x n coefficient matrix\r\n        double *lu, //n x n LU matrix augmented by an n x 1 pivot sequence\r\n        int n) //Order of the matrix\r\n{\r\n\tint i, j, k;\r\n    int pivotindex;\r\n\tdouble pivot, biggest, mult, tempf;\r\n\tint *ps;\r\n\tdouble scales[MAXDIM];\r\n\r\n\tps = (int *)(&lu[n*n]); /* Memory for ps[] comes after LU[][] */\r\n\r\n\tfor (i = 0; i < n; i++) {\t/* For each row */\r\n\t\t/* Find the largest element in each row for row equilibration */\r\n\t\tbiggest = 0.0;\r\n\t\tfor (j = 0; j < n; j++)\r\n\t\t\tif (biggest < (tempf = fabs(luel(i,j) = ael(j,i)))) /* A transposed for row vectors */\r\n\t\t\t\tbiggest = tempf;\r\n\t\tif (biggest != 0.0)\r\n\t\t\tscales[i] = 1.0 / biggest;\r\n\t\telse {\r\n\t\t\tscales[i] = 0.0;\r\n\t\t\treturn(0);\t/* Zero row: singular matrix */\r\n\t\t}\r\n\r\n\t\tps[i] = i;\t\t/* Initialize pivot sequence */\r\n\t}\r\n\r\n\tfor (k = 0; k < n-1; k++) { /* For each column */\r\n\t\t/* Find the largest element in each column to pivot around */\r\n\t\tbiggest = 0.0;\r\n\t\tfor (i = k; i < n; i++) {\r\n\t\t\tif (biggest < (tempf = fabs(luel(ps[i],k)) * scales[ps[i]])) {\r\n\t\t\t\tbiggest = tempf;\r\n\t\t\t\tpivotindex = i;\r\n\t\t\t}\r\n\t\t}\r\n\t\tif (biggest == 0.0)\r\n\t\t\treturn(0);\t/* Zero column: singular matrix */\r\n\t\tif (pivotindex != k) {\t/* Update pivot sequence */\r\n\t\t\tj = ps[k];\r\n\t\t\tps[k] = ps[pivotindex];\r\n\t\t\tps[pivotindex] = j;\r\n\t\t}\r\n\r\n\t\t/* Pivot, eliminating an extra variable each time */\r\n\t\tpivot = luel(ps[k],k);\r\n\t\tfor (i = k+1; i < n; i++) {\r\n\t\t\tluel(ps[i],k) = mult = luel(ps[i],k) / pivot;\r\n\t\t\tif (mult != 0.0) {\r\n\t\t\t\tfor (j = k+1; j < n; j++)\r\n\t\t\t\t\tluel(ps[i],j) -= mult * luel(ps[k],j);\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\treturn(luel(ps[n-1],n-1) != 0.0);\t/* 0 if singular, 1 if not */\r\n}\r\n\r\n/*\r\n * Solves the linear equation xA = b after the matrix A has\r\n * been decomposed with LUDecompose into the lower and upper triangular\r\n * matrices L and U, giving the equivalent equation xUL = b.\r\n */\r\nvoid LU_solve_D(\r\n        const double *lu, //decomposed LU matrix\r\n        const double *b, //constant vector\r\n        double *x, //solution vector\r\n        int n) //order of the equation\r\n{\r\n\tint i, j;\r\n\tdouble dot;\r\n\tconst int *ps;\r\n\r\n\tps = (const int *)(&lu[n*n]); /* Memory for ps[] comes after LU[][] */\r\n\r\n\t/* Vector reduction using U triangular matrix */\r\n\tfor (i = 0; i < n; i++) {\r\n\t\tdot = 0.0;\r\n\t\tfor (j = 0; j < i; j++)\r\n\t\t\tdot += luel(ps[i],j) * x[j];\r\n\t\tx[i] = b[ps[i]] - dot;\r\n\t}\r\n\r\n\t/* Back substitution, in L triangular matrix */\r\n\tfor (i = n-1; i >= 0; i--) {\r\n\t\tdot = 0.0;\r\n\t\tfor (j = i+1; j < n; j++)\r\n\t\t\tdot += luel(ps[i],j) * x[j];\r\n\t\tx[i] = (x[i] - dot) / luel(ps[i],i);\r\n\t}\r\n}\r\n\r\n//compute mean of reprojection error\r\ndouble check_error(std::vector<std::pair<cv::Mat,cv::Mat>> inl_points,\r\n                   std::vector<unsigned int> num_inl,\r\n                   const cv::Mat& base_homo,\r\n                   cv::Mat dn,\r\n                   cv::Mat rt)\r\n{\r\n\tsize_t num_homo = num_inl.size();\r\n\tdouble *points1, *points2;\r\n\tMat _h;\r\n    size_t i, j;\r\n\tdouble error, error1;\r\n\tdouble dx, dy;\r\n\tdouble op[2];\r\n\tdouble h[3][3];\r\n\tdouble s;\r\n\tint total_pts;\r\n\t_h = Mat(3,3,CV_64F,h);\r\n\r\n\ttotal_pts = 0;\r\n\terror = 0.0;\r\n\tfor(i = 0; i < num_homo; ++i)\r\n\t{\r\n\t\tfor(size_t j1 = 0; j1 < 3; j1++)\r\n\t\t{\r\n\t\t\tfor(size_t j2 = 0; j2 < 3; j2++)\r\n\t\t\t{\r\n\t\t\t\th[j1][j2] = rt.at<double>(j1) * dn.at<double>(i,j2);\r\n\t\t\t}\r\n\t\t}\r\n\t\t_h = base_homo + _h;\r\n\t\ts = 1.0/h[2][2];\r\n\t\t_h = s * _h;\r\n\t\terror1 = 0;\r\n\t\tfor(j = 0; j < num_inl[i]; ++j)\r\n\t\t{\r\n\t\t\tpoints1 = (double*)inl_points[i].first.row(j).data;\r\n\t\t\tpoints2 = (double*)inl_points[i].second.row(j).data;\r\n            homography_transfer_33D(h, points1, op);\r\n\t\t\tdx = op[0] - points2[0];\r\n\t\t\tdy = op[1] - points2[1];\r\n\t\t\terror1 +=sqrt(dx*dx + dy*dy);\r\n\t\t\ttotal_pts++;\r\n\t\t}\r\n\t\terror +=error1;\r\n\t}\r\n\treturn error/(float)total_pts;\r\n}\r\n\r\nint homography_transfer_33D(double h[3][3], double *ip, double *op)\r\n{\r\n\tdouble  p[3];\r\n\tdouble hp[3];\r\n\tMat _h, _p, _hp;\r\n\t_h = Mat(3,3,CV_64F,h);\r\n\t_hp = Mat(3,1,CV_64F,hp);\r\n\t_p = Mat(3,1,CV_64F,p);\r\n    convertToHomography(ip, p);\r\n\t_hp = _h * _p;\r\n\tconvertToImage(hp, op);\r\n\treturn 1;\r\n}\r\n\r\nint convertToHomography(const double *ip, double *op)\r\n{\r\n\top[0] = ip[0];\r\n\top[1] = ip[1];\r\n\top[2] = 1.0;\r\n\treturn 1;\r\n}\r\n\r\nint convertToImage(const double ip[3], double op[2])\r\n{\r\n\top[0] = ip[0]/ip[2];\r\n\top[1] = ip[1]/ip[2];\r\n\treturn 1;\r\n}\r\n\r\n//rot is from camera1 to camera 2\r\n//t is the translation in camera 1 frame, plane is in the camera 1 frame\r\n//in this formula, the 3d point translation is\r\n//P2 = RP1 + dt\r\n//the argument input is\r\n//P2 = R(P1-t)\r\n\r\nint construct_analytic_homography(const cv::Mat& rot, cv::Mat t, cv::Mat plane, cv::Mat & h)\r\n{\r\n\tMat _tp, im;\r\n\tdouble tp[3][3], s;\r\n\t_tp = Mat(3,3,CV_64F,tp);\r\n\r\n\tfor(size_t j1 = 0; j1 < 3; j1++)\r\n\t{\r\n\t\tfor(size_t j2 = 0; j2 < 3; j2++)\r\n\t\t{\r\n\t\t\ttp[j1][j2] = t.at<double>(j1) * plane.at<double>(j2);\r\n\t\t}\r\n\t}\r\n\tim = Mat::eye(3,3,CV_64F);\r\n\t_tp = im - _tp;\r\n\th = rot * _tp;\r\n\tif(fabs(h.at<double>(2,2)) > 0.0)\r\n\t{\r\n\t\ts = 1.0/h.at<double>(2,2);\r\n\t\th = s * h;\r\n\t\treturn 1;\r\n\t}\r\n\telse\r\n\t{\r\n\t\treturn 0;\r\n\t}\r\n}\r\n", "meta": {"hexsha": "2cf8052e02a583e9660c04b4bf528df34d20dbe6", "size": 46148, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "matchinglib_poselib/source/poselib/source/HomographyAlignment.cpp", "max_stars_repo_name": "josefmaierfl/matchinglib_poselib", "max_stars_repo_head_hexsha": "3bd7125a1ddfea68dfa95c8b3f978cba4a678348", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-12-30T14:58:18.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-30T14:58:18.000Z", "max_issues_repo_path": "matchinglib_poselib/source/poselib/source/HomographyAlignment.cpp", "max_issues_repo_name": "josefmaierfl/matchinglib_poselib", "max_issues_repo_head_hexsha": "3bd7125a1ddfea68dfa95c8b3f978cba4a678348", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-08-19T16:11:15.000Z", "max_issues_repo_issues_event_max_datetime": "2020-08-19T16:11:15.000Z", "max_forks_repo_path": "matchinglib_poselib/source/poselib/source/HomographyAlignment.cpp", "max_forks_repo_name": "josefmaierfl/matchinglib_poselib", "max_forks_repo_head_hexsha": "3bd7125a1ddfea68dfa95c8b3f978cba4a678348", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-09-28T13:20:59.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-04T10:56:02.000Z", "avg_line_length": 28.7705735661, "max_line_length": 137, "alphanum_fraction": 0.5536317934, "num_tokens": 16357, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6513548782017745, "lm_q2_score": 0.49609382947091946, "lm_q1q2_score": 0.32313313587168263}}
{"text": "// This file is part of Eigen, a lightweight C++ template library\n// for linear algebra.\n//\n// Copyright (C) 2011 Gael Guennebaud <gael.guennebaud@inria.fr>\n//\n// This Source Code Form is subject to the terms of the Mozilla\n// Public License v. 2.0. If a copy of the MPL was not distributed\n// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.\n\n#include \"lapack_common.h\"\n#include <Eigen/Eigenvalues>\n\n// computes eigen values and vectors of a general N-by-N matrix A\nEIGEN_LAPACK_FUNC(syev,(char *jobz, char *uplo, int* n, Scalar* a, int *lda, Scalar* w, Scalar* /*work*/, int* lwork, int *info))\n{\n  // TODO exploit the work buffer\n  bool query_size = *lwork==-1;\n  \n  *info = 0;\n        if(*jobz!='N' && *jobz!='V')                    *info = -1;\n  else  if(UPLO(*uplo)==INVALID)                        *info = -2;\n  else  if(*n<0)                                        *info = -3;\n  else  if(*lda<std::max(1,*n))                         *info = -5;\n  else  if((!query_size) && *lwork<std::max(1,3**n-1))  *info = -8;\n    \n  if(*info!=0)\n  {\n    int e = -*info;\n    return xerbla_(SCALAR_SUFFIX_UP\"SYEV \", &e, 6);\n  }\n  \n  if(query_size)\n  {\n    *lwork = 0;\n    return 0;\n  }\n  \n  if(*n==0)\n    return 0;\n  \n  PlainMatrixType mat(*n,*n);\n  if(UPLO(*uplo)==UP) mat = matrix(a,*n,*n,*lda).adjoint();\n  else                mat = matrix(a,*n,*n,*lda);\n  \n  bool computeVectors = *jobz=='V' || *jobz=='v';\n  SelfAdjointEigenSolver<PlainMatrixType> eig(mat,computeVectors?ComputeEigenvectors:EigenvaluesOnly);\n  \n  if(eig.info()==NoConvergence)\n  {\n    make_vector(w,*n).setZero();\n    if(computeVectors)\n      matrix(a,*n,*n,*lda).setIdentity();\n    //*info = 1;\n    return 0;\n  }\n  \n  make_vector(w,*n) = eig.eigenvalues();\n  if(computeVectors)\n    matrix(a,*n,*n,*lda) = eig.eigenvectors();\n  \n  return 0;\n}\n", "meta": {"hexsha": "921c51569708f5a2ca5dede14162c14ce3caf2fd", "size": 1826, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Eigen-3.3/lapack/eigenvalues.cpp", "max_stars_repo_name": "shareq2005/CarND-MPC-Project", "max_stars_repo_head_hexsha": "f4094e8b446d2fac2ca0a4c5054d5058621595b0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3457.0, "max_stars_repo_stars_event_min_datetime": "2018-06-09T15:36:42.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-01T22:09:25.000Z", "max_issues_repo_path": "src/Eigen-3.3/lapack/eigenvalues.cpp", "max_issues_repo_name": "shareq2005/CarND-MPC-Project", "max_issues_repo_head_hexsha": "f4094e8b446d2fac2ca0a4c5054d5058621595b0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 851.0, "max_issues_repo_issues_event_min_datetime": "2017-11-27T15:09:56.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T22:26:38.000Z", "max_forks_repo_path": "src/Eigen-3.3/lapack/eigenvalues.cpp", "max_forks_repo_name": "shareq2005/CarND-MPC-Project", "max_forks_repo_head_hexsha": "f4094e8b446d2fac2ca0a4c5054d5058621595b0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1380.0, "max_forks_repo_forks_event_min_datetime": "2017-06-12T23:58:23.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T14:52:48.000Z", "avg_line_length": 28.9841269841, "max_line_length": 129, "alphanum_fraction": 0.5750273823, "num_tokens": 592, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6723317123102955, "lm_q2_score": 0.48047867804790706, "lm_q1q2_score": 0.32304105234053654}}
{"text": "#ifndef VIENNACL_LINALG_AMG_HPP_\n#define VIENNACL_LINALG_AMG_HPP_\n\n/* =========================================================================\n   Copyright (c) 2010-2014, Institute for Microelectronics,\n                            Institute for Analysis and Scientific Computing,\n                            TU Wien.\n   Portions of this software are copyright by UChicago Argonne, LLC.\n\n                            -----------------\n                  ViennaCL - The Vienna Computing Library\n                            -----------------\n\n   Project Head:    Karl Rupp                   rupp@iue.tuwien.ac.at\n\n   (A list of authors and contributors can be found in the PDF manual)\n\n   License:         MIT (X11), see file LICENSE in the base directory\n============================================================================= */\n\n/** @file viennacl/linalg/amg.hpp\n    @brief Main include file for algebraic multigrid (AMG) preconditioners.  Experimental.\n\n    Implementation contributed by Markus Wagner\n*/\n\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/lu.hpp>\n#include <boost/numeric/ublas/operation.hpp>\n#include <boost/numeric/ublas/vector_proxy.hpp>\n#include <boost/numeric/ublas/matrix_proxy.hpp>\n#include <boost/numeric/ublas/vector.hpp>\n#include <boost/numeric/ublas/triangular.hpp>\n#include <vector>\n#include <cmath>\n#include \"viennacl/forwards.h\"\n#include \"viennacl/tools/tools.hpp\"\n#include \"viennacl/linalg/prod.hpp\"\n#include \"viennacl/linalg/direct_solve.hpp\"\n\n#include \"viennacl/linalg/detail/amg/amg_base.hpp\"\n#include \"viennacl/linalg/detail/amg/amg_coarse.hpp\"\n#include \"viennacl/linalg/detail/amg/amg_interpol.hpp\"\n\n#include <map>\n\n#ifdef VIENNACL_WITH_OPENMP\n #include <omp.h>\n#endif\n\n#include \"viennacl/linalg/detail/amg/amg_debug.hpp\"\n\n#define VIENNACL_AMG_COARSE_LIMIT 50\n#define VIENNACL_AMG_MAX_LEVELS 100\n\nnamespace viennacl\n{\nnamespace linalg\n{\n\ntypedef detail::amg::amg_tag          amg_tag;\n\n\n/** @brief Setup AMG preconditioner\n*\n* @param A            Operator matrices on all levels\n* @param P            Prolongation/Interpolation operators on all levels\n* @param pointvector  Vector of points on all levels\n* @param tag          AMG preconditioner tag\n*/\ntemplate<typename InternalT1, typename InternalT2>\nvoid amg_setup(InternalT1 & A, InternalT1 & P, InternalT2 & pointvector, amg_tag & tag)\n{\n  typedef typename InternalT2::value_type      PointVectorType;\n\n  unsigned int i, iterations, c_points, f_points;\n  detail::amg::amg_slicing<InternalT1,InternalT2> slicing;\n\n  // Set number of iterations. If automatic coarse grid construction is chosen (0), then set a maximum size and stop during the process.\n  iterations = tag.get_coarselevels();\n  if (iterations == 0)\n    iterations = VIENNACL_AMG_MAX_LEVELS;\n\n  // For parallel coarsenings build data structures (number of threads set automatically).\n  if (tag.get_coarse() == VIENNACL_AMG_COARSE_RS0 || tag.get_coarse() == VIENNACL_AMG_COARSE_RS3)\n    slicing.init(iterations);\n\n  for (i=0; i<iterations; ++i)\n  {\n    // Initialize Pointvector on level i and construct points.\n    pointvector[i] = PointVectorType(static_cast<unsigned int>(A[i].size1()));\n    pointvector[i].init_points();\n\n    // Construct C and F points on coarse level (i is fine level, i+1 coarse level).\n    detail::amg::amg_coarse (i, A, pointvector, slicing, tag);\n\n    // Calculate number of C and F points on level i.\n    c_points = pointvector[i].get_cpoints();\n    f_points = pointvector[i].get_fpoints();\n\n    #if defined (VIENNACL_AMG_DEBUG) //or defined(VIENNACL_AMG_DEBUGBENCH)\n    std::cout << \"Level \" << i << \": \";\n    std::cout << \"No of C points = \" << c_points << \", \";\n    std::cout << \"No of F points = \" << f_points << std::endl;\n    #endif\n\n    // Stop routine when the maximal coarse level is found (no C or F point). Coarsest level is level i.\n    if (c_points == 0 || f_points == 0)\n      break;\n\n    // Construct interpolation matrix for level i.\n    detail::amg::amg_interpol (i, A, P, pointvector, tag);\n\n    // Compute coarse grid operator (A[i+1] = R * A[i] * P) with R = trans(P).\n    detail::amg::amg_galerkin_prod(A[i], P[i], A[i+1]);\n\n    // Test triple matrix product. Very slow for large matrix sizes (ublas).\n    // test_triplematprod(A[i],P[i],A[i+1]);\n\n    pointvector[i].delete_points();\n\n    #ifdef VIENNACL_AMG_DEBUG\n    std::cout << \"Coarse Grid Operator Matrix:\" << std::endl;\n    printmatrix (A[i+1]);\n    #endif\n\n    // If Limit of coarse points is reached then stop. Coarsest level is level i+1.\n    if (tag.get_coarselevels() == 0 && c_points <= VIENNACL_AMG_COARSE_LIMIT)\n    {\n      tag.set_coarselevels(i+1);\n      return;\n    }\n  }\n  tag.set_coarselevels(i);\n}\n\n/** @brief Initialize AMG preconditioner\n*\n* @param mat          System matrix\n* @param A            Operator matrices on all levels\n* @param P            Prolongation/Interpolation operators on all levels\n* @param pointvector  Vector of points on all levels\n* @param tag          AMG preconditioner tag\n*/\ntemplate<typename MatrixT, typename InternalT1, typename InternalT2>\nvoid amg_init(MatrixT const & mat, InternalT1 & A, InternalT1 & P, InternalT2 & pointvector, amg_tag & tag)\n{\n  //typedef typename MatrixType::value_type ScalarType;\n  typedef typename InternalT1::value_type SparseMatrixType;\n\n  if (tag.get_coarselevels() > 0)\n  {\n    A.resize(tag.get_coarselevels()+1);\n    P.resize(tag.get_coarselevels());\n    pointvector.resize(tag.get_coarselevels());\n  }\n  else\n  {\n    A.resize(VIENNACL_AMG_MAX_LEVELS+1);\n    P.resize(VIENNACL_AMG_MAX_LEVELS);\n    pointvector.resize(VIENNACL_AMG_MAX_LEVELS);\n  }\n\n  // Insert operator matrix as operator for finest level.\n  SparseMatrixType A0(mat);\n  A.insert_element(0, A0);\n}\n\n/** @brief Save operators after setup phase for CPU computation.\n*\n* @param A      Operator matrices on all levels on the CPU\n* @param P      Prolongation/Interpolation operators on all levels on the CPU\n* @param R      Restriction operators on all levels on the CPU\n* @param A_setup    Operators matrices on all levels from setup phase\n* @param P_setup    Prolongation/Interpolation operators on all levels from setup phase\n* @param tag    AMG preconditioner tag\n*/\ntemplate<typename InternalT1, typename InternalT2>\nvoid amg_transform_cpu(InternalT1 & A, InternalT1 & P, InternalT1 & R, InternalT2 & A_setup, InternalT2 & P_setup, amg_tag & tag)\n{\n  //typedef typename InternalType1::value_type MatrixType;\n\n  // Resize internal data structures to actual size.\n  A.resize(tag.get_coarselevels()+1);\n  P.resize(tag.get_coarselevels());\n  R.resize(tag.get_coarselevels());\n\n  // Transform into matrix type.\n  for (unsigned int i=0; i<tag.get_coarselevels()+1; ++i)\n  {\n    A[i].resize(A_setup[i].size1(),A_setup[i].size2(),false);\n    A[i] = A_setup[i];\n  }\n  for (unsigned int i=0; i<tag.get_coarselevels(); ++i)\n  {\n    P[i].resize(P_setup[i].size1(),P_setup[i].size2(),false);\n    P[i] = P_setup[i];\n  }\n  for (unsigned int i=0; i<tag.get_coarselevels(); ++i)\n  {\n    R[i].resize(P_setup[i].size2(),P_setup[i].size1(),false);\n    P_setup[i].set_trans(true);\n    R[i] = P_setup[i];\n    P_setup[i].set_trans(false);\n  }\n}\n\n/** @brief Save operators after setup phase for GPU computation.\n*\n* @param A          Operator matrices on all levels on the GPU\n* @param P          Prolongation/Interpolation operators on all levels on the GPU\n* @param R          Restriction operators on all levels on the GPU\n* @param A_setup    Operators matrices on all levels from setup phase\n* @param P_setup    Prolongation/Interpolation operators on all levels from setup phase\n* @param tag        AMG preconditioner tag\n* @param ctx        Optional context in which the auxiliary objects are created (one out of multiple OpenCL contexts, CUDA, host)\n*/\ntemplate<typename InternalT1, typename InternalT2>\nvoid amg_transform_gpu(InternalT1 & A, InternalT1 & P, InternalT1 & R, InternalT2 & A_setup, InternalT2 & P_setup, amg_tag & tag, viennacl::context ctx)\n{\n  typedef typename InternalT2::value_type::value_type    NumericType;\n\n  // Resize internal data structures to actual size.\n  A.resize(tag.get_coarselevels()+1);\n  P.resize(tag.get_coarselevels());\n  R.resize(tag.get_coarselevels());\n\n  // Copy to GPU using the internal sparse matrix structure: std::vector<std::map>.\n  for (unsigned int i=0; i<tag.get_coarselevels()+1; ++i)\n  {\n    viennacl::switch_memory_context(A[i], ctx);\n    //A[i].resize(A_setup[i].size1(),A_setup[i].size2(),false);\n    viennacl::copy(*(A_setup[i].get_internal_pointer()),A[i]);\n  }\n  for (unsigned int i=0; i<tag.get_coarselevels(); ++i)\n  {\n    // find number of nonzeros in P:\n    vcl_size_t nonzeros = 0;\n    for (vcl_size_t j=0; j<P_setup[i].get_internal_pointer()->size(); ++j)\n      nonzeros += (*P_setup[i].get_internal_pointer())[j].size();\n\n    viennacl::switch_memory_context(P[i], ctx);\n    //P[i].resize(P_setup[i].size1(),P_setup[i].size2(),false);\n    viennacl::detail::copy_impl(tools::const_sparse_matrix_adapter<NumericType>(*(P_setup[i].get_internal_pointer()), P_setup[i].size1(), P_setup[i].size2()), P[i], nonzeros);\n    //viennacl::copy((boost::numeric::ublas::compressed_matrix<ScalarType>)P_setup[i],P[i]);\n\n    viennacl::switch_memory_context(R[i], ctx);\n    //R[i].resize(P_setup[i].size2(),P_setup[i].size1(),false);\n    P_setup[i].set_trans(true);\n    viennacl::detail::copy_impl(tools::const_sparse_matrix_adapter<NumericType>(*(P_setup[i].get_internal_pointer()), P_setup[i].size1(), P_setup[i].size2()), R[i], nonzeros);\n    P_setup[i].set_trans(false);\n  }\n}\n\n/** @brief Setup data structures for precondition phase.\n*\n* @param result      Result vector on all levels\n* @param rhs         RHS vector on all levels\n* @param residual    Residual vector on all levels\n* @param A           Operators matrices on all levels from setup phase\n* @param tag         AMG preconditioner tag\n*/\ntemplate<typename InternalVectorT, typename SparseMatrixT>\nvoid amg_setup_apply(InternalVectorT & result, InternalVectorT & rhs, InternalVectorT & residual, SparseMatrixT const & A, amg_tag const & tag)\n{\n  typedef typename InternalVectorT::value_type VectorType;\n\n  result.resize(tag.get_coarselevels()+1);\n  rhs.resize(tag.get_coarselevels()+1);\n  residual.resize(tag.get_coarselevels());\n\n  for (unsigned int level=0; level < tag.get_coarselevels()+1; ++level)\n  {\n    result[level] = VectorType(A[level].size1());\n    result[level].clear();\n    rhs[level] = VectorType(A[level].size1());\n    rhs[level].clear();\n  }\n  for (unsigned int level=0; level < tag.get_coarselevels(); ++level)\n  {\n    residual[level] = VectorType(A[level].size1());\n    residual[level].clear();\n  }\n}\n\n\n/** @brief Setup data structures for precondition phase for later use on the GPU\n*\n* @param result      Result vector on all levels\n* @param rhs         RHS vector on all levels\n* @param residual    Residual vector on all levels\n* @param A           Operators matrices on all levels from setup phase\n* @param tag         AMG preconditioner tag\n* @param ctx         Optional context in which the auxiliary objects are created (one out of multiple OpenCL contexts, CUDA, host)\n*/\ntemplate<typename InternalVectorT, typename SparseMatrixT>\nvoid amg_setup_apply(InternalVectorT & result, InternalVectorT & rhs, InternalVectorT & residual, SparseMatrixT const & A, amg_tag const & tag, viennacl::context ctx)\n{\n  typedef typename InternalVectorT::value_type VectorType;\n\n  result.resize(tag.get_coarselevels()+1);\n  rhs.resize(tag.get_coarselevels()+1);\n  residual.resize(tag.get_coarselevels());\n\n  for (unsigned int level=0; level < tag.get_coarselevels()+1; ++level)\n  {\n    result[level] = VectorType(A[level].size1(), ctx);\n      rhs[level] = VectorType(A[level].size1(), ctx);\n  }\n  for (unsigned int level=0; level < tag.get_coarselevels(); ++level)\n  {\n    residual[level] = VectorType(A[level].size1(), ctx);\n  }\n}\n\n\n/** @brief Pre-compute LU factorization for direct solve (ublas library).\n *  @brief Speeds up precondition phase as this is computed only once overall instead of once per iteration.\n*\n* @param op           Operator matrix for direct solve\n* @param permutation  Permutation matrix which saves the factorization result\n* @param A            Operator matrix on coarsest level\n*/\ntemplate<typename NumericT, typename SparseMatrixT>\nvoid amg_lu(boost::numeric::ublas::compressed_matrix<NumericT> & op, boost::numeric::ublas::permutation_matrix<> & permutation, SparseMatrixT const & A)\n{\n  typedef typename SparseMatrixT::const_iterator1 ConstRowIterator;\n  typedef typename SparseMatrixT::const_iterator2 ConstColIterator;\n\n  // Copy to operator matrix. Needed\n  op.resize(A.size1(),A.size2(),false);\n  for (ConstRowIterator row_iter = A.begin1(); row_iter != A.end1(); ++row_iter)\n    for (ConstColIterator col_iter = row_iter.begin(); col_iter != row_iter.end(); ++col_iter)\n      op (col_iter.index1(), col_iter.index2()) = *col_iter;\n\n  // Permutation matrix has to be reinitialized with actual size. Do not clear() or resize()!\n  permutation = boost::numeric::ublas::permutation_matrix<> (op.size1());\n  boost::numeric::ublas::lu_factorize(op, permutation);\n}\n\n/** @brief AMG preconditioner class, can be supplied to solve()-routines\n*/\ntemplate<typename MatrixT>\nclass amg_precond\n{\n  typedef typename MatrixT::value_type                NumericType;\n  typedef boost::numeric::ublas::vector<NumericType>  VectorType;\n  typedef detail::amg::amg_sparsematrix<NumericType>  SparseMatrixType;\n  typedef detail::amg::amg_pointvector                PointVectorType;\n\n  typedef typename SparseMatrixType::const_iterator1  InternalConstRowIterator;\n  typedef typename SparseMatrixType::const_iterator2  InternalConstColIterator;\n  typedef typename SparseMatrixType::iterator1        InternalRowIterator;\n  typedef typename SparseMatrixType::iterator2        InternalColIterator;\n\n  boost::numeric::ublas::vector<SparseMatrixType> A_setup_;\n  boost::numeric::ublas::vector<SparseMatrixType> P_setup_;\n  boost::numeric::ublas::vector<MatrixT>          A_;\n  boost::numeric::ublas::vector<MatrixT>          P_;\n  boost::numeric::ublas::vector<MatrixT>          R_;\n  boost::numeric::ublas::vector<PointVectorType>  pointvector_;\n\n  mutable boost::numeric::ublas::compressed_matrix<NumericType> op_;\n  mutable boost::numeric::ublas::permutation_matrix<>           permutation_;\n\n  mutable boost::numeric::ublas::vector<VectorType> result_;\n  mutable boost::numeric::ublas::vector<VectorType> rhs_;\n  mutable boost::numeric::ublas::vector<VectorType> residual_;\n\n  mutable bool done_init_apply_;\n\n  amg_tag tag_;\npublic:\n\n  amg_precond(): permutation_(0) {}\n  /** @brief The constructor. Saves system matrix, tag and builds data structures for setup.\n  *\n  * @param mat  System matrix\n  * @param tag  The AMG tag\n  */\n  amg_precond(MatrixT const & mat, amg_tag const & tag): permutation_(0)\n  {\n    tag_ = tag;\n    // Initialize data structures.\n    amg_init (mat, A_setup_, P_setup_, pointvector_, tag_);\n\n    done_init_apply_ = false;\n  }\n\n  /** @brief Start setup phase for this class and copy data structures.\n  */\n  void setup()\n  {\n    // Start setup phase.\n    amg_setup(A_setup_, P_setup_, pointvector_, tag_);\n    // Transform to CPU-Matrixtype for precondition phase.\n    amg_transform_cpu(A_, P_, R_, A_setup_, P_setup_, tag_);\n\n    done_init_apply_ = false;\n  }\n\n  /** @brief Prepare data structures for preconditioning:\n   *  Build data structures for precondition phase.\n   *  Do LU factorization on coarsest level.\n  */\n  void init_apply() const\n  {\n    // Setup precondition phase (Data structures).\n    amg_setup_apply(result_, rhs_, residual_, A_setup_, tag_);\n    // Do LU factorization for direct solve.\n    amg_lu(op_, permutation_, A_setup_[tag_.get_coarselevels()]);\n\n    done_init_apply_ = true;\n  }\n\n  /** @brief Returns complexity measures.\n  *\n  * @param avgstencil  Average stencil sizes on all levels\n  * @return            Operator complexity of AMG method\n  */\n  template<typename VectorT>\n  NumericType calc_complexity(VectorT & avgstencil)\n  {\n    avgstencil = VectorT(tag_.get_coarselevels()+1);\n    unsigned int nonzero=0, systemmat_nonzero=0, level_coefficients=0;\n\n    for (unsigned int level=0; level < tag_.get_coarselevels()+1; ++level)\n    {\n      level_coefficients = 0;\n      for (InternalRowIterator row_iter = A_setup_[level].begin1(); row_iter != A_setup_[level].end1(); ++row_iter)\n      {\n        for (InternalColIterator col_iter = row_iter.begin(); col_iter != row_iter.end(); ++col_iter)\n        {\n          if (level == 0)\n            systemmat_nonzero++;\n          nonzero++;\n          level_coefficients++;\n        }\n      }\n      avgstencil[level] = static_cast<NumericType>(level_coefficients)/static_cast<NumericType>(A_setup_[level].size1());\n    }\n    return static_cast<NumericType>(nonzero) / static_cast<NumericType>(systemmat_nonzero);\n  }\n\n  /** @brief Precondition Operation\n  *\n  * @param vec The vector to which preconditioning is applied to (ublas version)\n  */\n  template<typename VectorT>\n  void apply(VectorT & vec) const\n  {\n    // Build data structures and do lu factorization before first iteration step.\n    if (!done_init_apply_)\n      init_apply();\n\n    int level;\n\n    // Precondition operation (Yang, p.3)\n    rhs_[0] = vec;\n    for (level=0; level<static_cast<int>(tag_.get_coarselevels()); level++)\n    {\n      result_[level].clear();\n\n      // Apply Smoother presmooth_ times.\n      smooth_jacobi (level, tag_.get_presmooth(), result_[level], rhs_[level]);\n\n      #ifdef VIENNACL_AMG_DEBUG\n      std::cout << \"After presmooth:\" << std::endl;\n      printvector(result_[level]);\n      #endif\n\n      // Compute residual.\n      residual_[level] = rhs_[level] - boost::numeric::ublas::prod(A_[level], result_[level]);\n\n      #ifdef VIENNACL_AMG_DEBUG\n      std::cout << \"Residual:\" << std::endl;\n      printvector(residual_[level]);\n      #endif\n\n      // Restrict to coarse level. Restricted residual is RHS of coarse level.\n      rhs_[level+1] = boost::numeric::ublas::prod(R_[level], residual_[level]);\n\n      #ifdef VIENNACL_AMG_DEBUG\n      std::cout << \"Restricted Residual: \" << std::endl;\n      printvector(rhs_[level+1]);\n      #endif\n    }\n\n    // On highest level use direct solve to solve equation.\n    result_[level] = rhs_[level];\n    boost::numeric::ublas::lu_substitute(op_, permutation_, result_[level]);\n\n    #ifdef VIENNACL_AMG_DEBUG\n    std::cout << \"After direct solve: \" << std::endl;\n    printvector(result_[level]);\n    #endif\n\n    for (level=tag_.get_coarselevels()-1; level >= 0; level--)\n    {\n      #ifdef VIENNACL_AMG_DEBUG\n      std::cout << \"Coarse Error: \" << std::endl;\n      printvector(result_[level+1]);\n      #endif\n\n      // Interpolate error to fine level. Correct solution by adding error.\n      result_[level] += boost::numeric::ublas::prod(P_[level], result_[level+1]);\n\n      #ifdef VIENNACL_AMG_DEBUG\n      std::cout << \"Corrected Result: \" << std::endl;\n      printvector(result_[level]);\n      #endif\n\n      // Apply Smoother postsmooth_ times.\n      smooth_jacobi(level, tag_.get_postsmooth(), result_[level], rhs_[level]);\n\n      #ifdef VIENNACL_AMG_DEBUG\n      std::cout << \"After postsmooth: \" << std::endl;\n      printvector(result_[level]);\n      #endif\n    }\n    vec = result_[0];\n  }\n\n  /** @brief (Weighted) Jacobi Smoother (CPU version)\n  * @param level       Coarse level to which smoother is applied to\n  * @param iterations  Number of smoother iterations\n  * @param x           The vector smoothing is applied to\n  * @param rhs_smooth  The right hand side of the equation for the smoother\n  */\n  template<typename VectorT>\n  void smooth_jacobi(int level, int const iterations, VectorT & x, VectorT const & rhs_smooth) const\n  {\n    VectorT old_result(x.size());\n    long index;\n\n    for (int i=0; i<iterations; ++i)\n    {\n      old_result = x;\n      x.clear();\n#ifdef VIENNACL_WITH_OPENMP\n      #pragma omp parallel for\n#endif\n      for (index=0; index < static_cast<long>(A_setup_[level].size1()); ++index)\n      {\n        InternalConstRowIterator row_iter = A_setup_[level].begin1();\n        row_iter += index;\n        NumericType sum  = 0;\n        NumericType diag = 1;\n        for (InternalConstColIterator col_iter = row_iter.begin(); col_iter != row_iter.end(); ++col_iter)\n        {\n          if (col_iter.index1() == col_iter.index2())\n            diag = *col_iter;\n          else\n            sum += *col_iter * old_result[col_iter.index2()];\n        }\n        x[index]= static_cast<NumericType>(tag_.get_jacobiweight()) * (rhs_smooth[index] - sum) / diag + (1-static_cast<NumericType>(tag_.get_jacobiweight())) * old_result[index];\n      }\n    }\n  }\n\n  amg_tag & tag() { return tag_; }\n};\n\n/** @brief AMG preconditioner class, can be supplied to solve()-routines.\n*\n*  Specialization for compressed_matrix\n*/\ntemplate<typename NumericT, unsigned int AlignmentV>\nclass amg_precond< compressed_matrix<NumericT, AlignmentV> >\n{\n  typedef viennacl::compressed_matrix<NumericT, AlignmentV> MatrixType;\n  typedef viennacl::vector<NumericT>                        VectorType;\n  typedef detail::amg::amg_sparsematrix<NumericT>           SparseMatrixType;\n  typedef detail::amg::amg_pointvector                      PointVectorType;\n\n  typedef typename SparseMatrixType::const_iterator1   InternalConstRowIterator;\n  typedef typename SparseMatrixType::const_iterator2   InternalConstColIterator;\n  typedef typename SparseMatrixType::iterator1         InternalRowIterator;\n  typedef typename SparseMatrixType::iterator2         InternalColIterator;\n\n  boost::numeric::ublas::vector<SparseMatrixType> A_setup_;\n  boost::numeric::ublas::vector<SparseMatrixType> P_setup_;\n  boost::numeric::ublas::vector<MatrixType>       A_;\n  boost::numeric::ublas::vector<MatrixType>       P_;\n  boost::numeric::ublas::vector<MatrixType>       R_;\n  boost::numeric::ublas::vector<PointVectorType>  pointvector_;\n\n  mutable boost::numeric::ublas::compressed_matrix<NumericT>  op_;\n  mutable boost::numeric::ublas::permutation_matrix<>         permutation_;\n\n  mutable boost::numeric::ublas::vector<VectorType> result_;\n  mutable boost::numeric::ublas::vector<VectorType> rhs_;\n  mutable boost::numeric::ublas::vector<VectorType> residual_;\n\n  viennacl::context ctx_;\n\n  mutable bool done_init_apply_;\n\n  amg_tag tag_;\n\npublic:\n\n  amg_precond(): permutation_(0) {}\n\n  /** @brief The constructor. Builds data structures.\n  *\n  * @param mat  System matrix\n  * @param tag  The AMG tag\n  */\n  amg_precond(compressed_matrix<NumericT, AlignmentV> const & mat, amg_tag const & tag): permutation_(0), ctx_(viennacl::traits::context(mat))\n  {\n    tag_ = tag;\n\n    // Copy to CPU. Internal structure of sparse matrix is used for copy operation.\n    std::vector<std::map<unsigned int, NumericT> > mat2 = std::vector<std::map<unsigned int, NumericT> >(mat.size1());\n    viennacl::copy(mat, mat2);\n\n    // Initialize data structures.\n    amg_init (mat2, A_setup_, P_setup_, pointvector_, tag_);\n\n    done_init_apply_ = false;\n  }\n\n  /** @brief Start setup phase for this class and copy data structures.\n  */\n  void setup()\n  {\n    // Start setup phase.\n    amg_setup(A_setup_, P_setup_, pointvector_, tag_);\n    // Transform to GPU-Matrixtype for precondition phase.\n    amg_transform_gpu(A_, P_, R_, A_setup_, P_setup_, tag_, ctx_);\n\n    done_init_apply_ = false;\n  }\n\n  /** @brief Prepare data structures for preconditioning:\n   *  Build data structures for precondition phase.\n   *  Do LU factorization on coarsest level.\n  */\n  void init_apply() const\n  {\n    // Setup precondition phase (Data structures).\n    amg_setup_apply(result_, rhs_, residual_, A_setup_, tag_, ctx_);\n    // Do LU factorization for direct solve.\n    amg_lu(op_, permutation_, A_setup_[tag_.get_coarselevels()]);\n\n    done_init_apply_ = true;\n  }\n\n  /** @brief Returns complexity measures\n  *\n  * @param avgstencil  Average stencil sizes on all levels\n  * @return     Operator complexity of AMG method\n  */\n  template<typename VectorT>\n  NumericT calc_complexity(VectorT & avgstencil)\n  {\n    avgstencil = VectorT(tag_.get_coarselevels()+1);\n    unsigned int nonzero=0, systemmat_nonzero=0, level_coefficients=0;\n\n    for (unsigned int level=0; level < tag_.get_coarselevels()+1; ++level)\n    {\n      level_coefficients = 0;\n      for (InternalRowIterator row_iter = A_setup_[level].begin1(); row_iter != A_setup_[level].end1(); ++row_iter)\n      {\n        for (InternalColIterator col_iter = row_iter.begin(); col_iter != row_iter.end(); ++col_iter)\n        {\n          if (level == 0)\n            systemmat_nonzero++;\n          nonzero++;\n          level_coefficients++;\n        }\n      }\n      avgstencil[level] = level_coefficients/static_cast<double>(A_[level].size1());\n    }\n    return nonzero/static_cast<double>(systemmat_nonzero);\n  }\n\n  /** @brief Precondition Operation\n  *\n  * @param vec The vector to which preconditioning is applied to\n  */\n  template<typename VectorT>\n  void apply(VectorT & vec) const\n  {\n    if (!done_init_apply_)\n      init_apply();\n\n    vcl_size_t level;\n\n    // Precondition operation (Yang, p.3).\n    rhs_[0] = vec;\n    for (level=0; level < tag_.get_coarselevels(); level++)\n    {\n      result_[level].clear();\n\n      // Apply Smoother presmooth_ times.\n      smooth_jacobi(level, tag_.get_presmooth(), result_[level], rhs_[level]);\n\n      #ifdef VIENNACL_AMG_DEBUG\n      std::cout << \"After presmooth: \" << std::endl;\n      printvector(result_[level]);\n      #endif\n\n      // Compute residual.\n      //residual[level] = rhs_[level] - viennacl::linalg::prod(A_[level], result_[level]);\n      residual_[level] = viennacl::linalg::prod(A_[level], result_[level]);\n      residual_[level] = rhs_[level] - residual_[level];\n\n      #ifdef VIENNACL_AMG_DEBUG\n      std::cout << \"Residual: \" << std::endl;\n      printvector(residual_[level]);\n      #endif\n\n      // Restrict to coarse level. Result is RHS of coarse level equation.\n      //residual_coarse[level] = viennacl::linalg::prod(R[level],residual[level]);\n      rhs_[level+1] = viennacl::linalg::prod(R_[level], residual_[level]);\n\n      #ifdef VIENNACL_AMG_DEBUG\n      std::cout << \"Restricted Residual: \" << std::endl;\n      printvector(rhs_[level+1]);\n      #endif\n    }\n\n    // On highest level use direct solve to solve equation (on the CPU)\n    //TODO: Use GPU direct solve!\n    result_[level] = rhs_[level];\n    boost::numeric::ublas::vector<NumericT> result_cpu(result_[level].size());\n\n    viennacl::copy(result_[level], result_cpu);\n    boost::numeric::ublas::lu_substitute(op_, permutation_, result_cpu);\n    viennacl::copy(result_cpu, result_[level]);\n\n    #ifdef VIENNACL_AMG_DEBUG\n    std::cout << \"After direct solve: \" << std::endl;\n    printvector (result[level]);\n    #endif\n\n    for (int level2 = static_cast<int>(tag_.get_coarselevels()-1); level2 >= 0; level2--)\n    {\n      level = static_cast<vcl_size_t>(level2);\n\n      #ifdef VIENNACL_AMG_DEBUG\n      std::cout << \"Coarse Error: \" << std::endl;\n      printvector(result[level+1]);\n      #endif\n\n      // Interpolate error to fine level and correct solution.\n      result_[level] += viennacl::linalg::prod(P_[level], result_[level+1]);\n\n      #ifdef VIENNACL_AMG_DEBUG\n      std::cout << \"Corrected Result: \" << std::endl;\n      printvector(result_[level]);\n      #endif\n\n      // Apply Smoother postsmooth_ times.\n      smooth_jacobi(level, tag_.get_postsmooth(), result_[level], rhs_[level]);\n\n      #ifdef VIENNACL_AMG_DEBUG\n      std::cout << \"After postsmooth: \" << std::endl;\n      printvector(result_[level]);\n      #endif\n    }\n    vec = result_[0];\n  }\n\n  /** @brief Jacobi Smoother (GPU version)\n  * @param level       Coarse level to which smoother is applied to\n  * @param iterations  Number of smoother iterations\n  * @param x           The vector smoothing is applied to\n  * @param rhs_smooth  The right hand side of the equation for the smoother\n  */\n  template<typename VectorT>\n  void smooth_jacobi(vcl_size_t level, unsigned int iterations, VectorT & x, VectorT const & rhs_smooth) const\n  {\n    VectorType old_result = x;\n\n    viennacl::ocl::context & ctx = const_cast<viennacl::ocl::context &>(viennacl::traits::opencl_handle(x).context());\n    viennacl::linalg::opencl::kernels::compressed_matrix<NumericT>::init(ctx);\n    viennacl::ocl::kernel & k = ctx.get_kernel(viennacl::linalg::opencl::kernels::compressed_matrix<NumericT>::program_name(), \"jacobi\");\n\n    for (unsigned int i=0; i<iterations; ++i)\n    {\n      if (i > 0)\n        old_result = x;\n      x.clear();\n      viennacl::ocl::enqueue(k(A_[level].handle1().opencl_handle(), A_[level].handle2().opencl_handle(), A_[level].handle().opencl_handle(),\n                              static_cast<NumericT>(tag_.get_jacobiweight()),\n                              viennacl::traits::opencl_handle(old_result),\n                              viennacl::traits::opencl_handle(x),\n                              viennacl::traits::opencl_handle(rhs_smooth),\n                              static_cast<cl_uint>(rhs_smooth.size())));\n\n    }\n  }\n\n  amg_tag & tag() { return tag_; }\n};\n\n}\n}\n\n\n\n#endif\n\n", "meta": {"hexsha": "40d73ec5562ac1aa9bd59afa4808a79b76deec03", "size": 29071, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "viennacl/linalg/amg.hpp", "max_stars_repo_name": "ddemidov/viennacl-dev", "max_stars_repo_head_hexsha": "0f7de9cd28e54a5ca8f7c2ab03263bc56bf004ef", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2016-08-23T17:05:21.000Z", "max_stars_repo_stars_event_max_datetime": "2016-08-23T17:06:24.000Z", "max_issues_repo_path": "viennacl/linalg/amg.hpp", "max_issues_repo_name": "ddemidov/viennacl-dev", "max_issues_repo_head_hexsha": "0f7de9cd28e54a5ca8f7c2ab03263bc56bf004ef", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "viennacl/linalg/amg.hpp", "max_forks_repo_name": "ddemidov/viennacl-dev", "max_forks_repo_head_hexsha": "0f7de9cd28e54a5ca8f7c2ab03263bc56bf004ef", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.0235439901, "max_line_length": 179, "alphanum_fraction": 0.6766193113, "num_tokens": 7550, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7248702761768248, "lm_q2_score": 0.4455295350395727, "lm_q1q2_score": 0.3229511171090674}}
{"text": "#include <cmath>\n#include <fstream>\n#include <iostream>\n#include <iomanip>\n#include <random>\n#include <sstream>\n#include <fftw3.h>\n#include \"parameter.hpp\"\n#include \"utilities.hpp\"\n#include <boost/filesystem.hpp>\n\nnamespace fs = boost::filesystem;\n\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\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    double phase,phase2, 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 = m*pow(L/(dx*dx),.5)/sqrt(4*M_PI);\n#elif  dim==2\n    static double norm =  m*pow(L/(dx*dx),1)/(sqrt(2*M_PI));\n#elif  dim==3\n    static double norm =  m*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    phase2 = 2*M_PI*rand_uniform();\n  //  std::cout << \"phase2 \" << phase/(2*M_PI) << std::endl;\n        re_f_right = amplitude * cos( phase2 );\n        im_f_right = amplitude * sin( phase2 );\n    \n    field[0] = re_f_left + re_f_right;\n    field[1] = im_f_left + im_f_right;\n    deriv[0] = omega*(im_f_left - im_f_right);\n    deriv[1] = -omega*(re_f_left - re_f_right);\n    if(real==1)\n    {\n        field[1]=0;\n        deriv[1]=0;\n    }\n    return;\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", "meta": {"hexsha": "819f3fc0bdffa8f0eb7333ff490e6355272b83e3", "size": 21062, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lib/utilities.cpp", "max_stars_repo_name": "embreakin/FLattice_KKLT", "max_stars_repo_head_hexsha": "5f9f0b8f13129d5b68db0cb1196fe3bbeb783adf", "max_stars_repo_licenses": ["MIT"], "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/utilities.cpp", "max_issues_repo_name": "embreakin/FLattice_KKLT", "max_issues_repo_head_hexsha": "5f9f0b8f13129d5b68db0cb1196fe3bbeb783adf", "max_issues_repo_licenses": ["MIT"], "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/utilities.cpp", "max_forks_repo_name": "embreakin/FLattice_KKLT", "max_forks_repo_head_hexsha": "5f9f0b8f13129d5b68db0cb1196fe3bbeb783adf", "max_forks_repo_licenses": ["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.5845648604, "max_line_length": 185, "alphanum_fraction": 0.4547051562, "num_tokens": 6417, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.640635854839898, "lm_q2_score": 0.5039061705290805, "lm_q1q2_score": 0.3228203603159969}}
{"text": "/*\nCopyright 2020 Dennis Rohde\n\nPermission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n*/\n\n#pragma once\n\n#include <unordered_map>\n\n#include <boost/chrono/include.hpp>\n\n#include \"random.hpp\"\n#include \"curve.hpp\"\n#include \"frechet.hpp\"\n#include \"dynamic_time_warping.hpp\"\n#include \"simplification.hpp\"\n\nnamespace Clustering {\n    \n    \nstruct Distance_Matrix : public std::vector<std::vector<distance_t>> {\n    Distance_Matrix() {}\n    Distance_Matrix(const curve_number_t n, const curve_number_t m) : std::vector<std::vector<distance_t>>(n, std::vector<distance_t>(m, -1.0)) {}\n    \n    void print() const {\n        for (const auto &row : *this) {\n            for (const auto elem : row) {\n                std::cout << elem << \" \";\n            }\n            std::cout << std::endl;\n        }\n    }\n};\n\nclass Cluster_Assignment : public std::vector<std::vector<curve_number_t>> {\npublic:\n    inline Cluster_Assignment(const curve_number_t k = 0) : std::vector<std::vector<curve_number_t>>(k, std::vector<curve_number_t>()) {}\n    \n    inline curve_number_t count(const curve_number_t i) const {\n        return operator[](i).size();\n    }\n    \n    inline curve_number_t get(const curve_number_t i, const curve_number_t j) const {\n        return operator[](i)[j];\n    }\n    \n};\n\ninline distance_t _cheap_dist(const curve_number_t i, const curve_number_t j, const Curves &in, const Curves &simplified_in, Distance_Matrix &distances) {\n    if (distances[i][j] < 0) {\n        const auto dist = Frechet::Continuous::distance(in[i], simplified_in[j]);\n        distances[i][j] = dist.value;\n    }\n    return distances[i][j];\n}\n\ninline curve_number_t _nearest_center(const curve_number_t i, const Curves &in, const Curves &simplified_in, const std::vector<curve_number_t> &centers, Distance_Matrix &distances) {\n    const auto infty = std::numeric_limits<distance_t>::infinity();\n    // cost for curve is infinity\n    auto min_cost = infty;\n    curve_number_t nearest = 0;\n    \n    // except there is a center with smaller cost, then choose the one with smallest cost\n    for (curve_number_t j = 0; j < centers.size(); ++j) {\n        if (_cheap_dist(i, centers[j], in, simplified_in, distances) < min_cost) {\n            min_cost = _cheap_dist(i, centers[j], in, simplified_in, distances);\n            nearest = j;\n        }\n    }\n    return nearest;\n}\n\ninline distance_t _curve_cost(const curve_number_t i, const Curves &in, const Curves &simplified_in, const std::vector<curve_number_t> &centers, Distance_Matrix &distances) {\n    return _cheap_dist(i, centers[_nearest_center(i, in, simplified_in, centers, distances)], in, simplified_in, distances);\n}\n\ninline distance_t _center_cost_sum(const Curves &in, const Curves &simplified_in, const std::vector<curve_number_t> &centers, Distance_Matrix &distances) {\n    distance_t cost = 0;\n    \n    // for all curves\n    for (curve_number_t i = 0; i < in.size(); ++i) {\n        const auto min_cost_elem = _curve_cost(i, in, simplified_in, centers, distances);\n        cost += min_cost_elem;\n    }\n    return cost;\n}\n\ninline Cluster_Assignment _cluster_assignment(const Curves &in, const Curves &simplified_in, const std::vector<curve_number_t> &centers, Distance_Matrix &distances) {\n    const auto k = centers.size();\n    Cluster_Assignment result(centers.size());\n    \n    if (k == 0) return result;\n        \n    for (curve_number_t i = 0; i < in.size(); ++i) result[_nearest_center(i, in, simplified_in, centers, distances)].push_back(i);\n    \n    return result;  \n}\n\nstruct Clustering_Result {\n    Curves centers;\n    distance_t value;\n    double running_time;\n    Cluster_Assignment assignment;\n    \n    inline Curve& get(const curve_number_t i) {\n        return centers[i];\n    }\n    inline curve_number_t size() const {\n        return centers.size();\n    }\n    \n    inline Curves::const_iterator cbegin() const {\n        return centers.cbegin();\n    }\n    \n    inline Curves::const_iterator cend() const {\n        return centers.cend();\n    }\n    \n    inline void compute_assignment(const Curves &in) {\n        Distance_Matrix distances(in.size(), centers.size());\n        std::vector<curve_number_t> center_indices = std::vector<curve_number_t>(centers.size(), 0);\n        for (curve_size_t i = 1; i < centers.size(); ++i) center_indices[i] = i;\n        assignment = _cluster_assignment(in, centers, center_indices, distances);\n    }\n};\n\n\nClustering_Result gonzalez(const curve_number_t num_centers, const curve_size_t ell, const Curves &in, Distance_Matrix &distances, const bool arya = false, const Curves &center_domain = Curves(), const bool random_start_center = true) {\n    \n    const auto start = boost::chrono::process_real_cpu_clock::now();\n    Clustering_Result result;\n    \n    if (in.empty()) return result;\n        \n    std::vector<curve_number_t> centers;\n    const Curves &simplified_in = center_domain;\n    \n    if (center_domain.empty()) {\n        Curves simplified_in_self(in.number(), ell, in.dimensions());\n        \n        for (curve_number_t i = 0; i < in.size(); ++i) {\n            Simplification::Subcurve_Shortcut_Graph graph(const_cast<Curve&>(in[i]));\n            auto simplified_curve = graph.weak_minimum_error_simplification(ell);\n            simplified_curve.set_name(\"Simplification of \" + in[i].get_name());\n            simplified_in_self[i] = simplified_curve;\n        }\n        const_cast<Curves&>(simplified_in) = simplified_in_self;\n    }\n        \n    if (random_start_center) {\n        \n        Random::Uniform_Random_Generator<double> ugen;\n        const curve_number_t r =  std::floor(simplified_in.size() * ugen.get());\n        centers.push_back(r);\n        \n    } else centers.push_back(0);\n    \n    distance_t curr_maxdist = 0;\n    curve_number_t curr_maxcurve = 0;\n    distance_t curr_curve_cost;\n    \n    if (distances.empty()) distances = Distance_Matrix(in.size(), simplified_in.size());\n    \n    {\n        // remaining centers\n        for (curve_number_t i = 1; i < num_centers; ++i) {\n            \n            curr_maxdist = 0;\n            curr_maxcurve = 0;\n            {\n            \n                // all curves\n                for (curve_number_t j = 0; j < in.size(); ++j) {\n                    \n                    curr_curve_cost = _curve_cost(j, in, simplified_in, centers, distances);\n                    \n                    if (curr_curve_cost > curr_maxdist) {\n                        curr_maxdist = curr_curve_cost;\n                        curr_maxcurve = j;\n                    }\n                    \n                }\n                #if DEBUG\n                std::cout << \"found center no. \" << i+1 << std::endl;\n                #endif\n                \n                centers.push_back(curr_maxcurve);\n            }   \n        }\n    }\n    \n    if (arya) {\n        \n        auto cost = _center_cost_sum(in, simplified_in, centers, distances);\n        auto approxcost = cost;\n        auto gamma = 1/(3 * num_centers * in.size());\n        auto found = true;\n        \n        // try to improve current solution\n        while (found) {\n            found = false;\n            \n            // go through all centers\n            for (curve_number_t i = 0; i < num_centers; ++i) {\n                auto curr_centers = centers;\n                \n                // check if there is a better center among all other curves\n                for (curve_number_t j = 0; j < simplified_in.size(); ++j) {\n                    // continue if curve is already part of center set\n                    if (std::find(curr_centers.begin(), curr_centers.end(), j) != curr_centers.end()) continue;\n                    \n                    // swap\n                    curr_centers[i] = j;\n                    // new cost\n                    const auto curr_cost = _center_cost_sum(in, simplified_in, curr_centers, distances);\n                    // check if improvement is done\n                    if (curr_cost < cost - gamma * approxcost) {\n                        cost = curr_cost;\n                        centers = curr_centers;\n                        found = true;\n                    }\n                }\n            }\n        }\n        curr_maxdist = cost;\n    }\n\n    Curves simpl_centers;\n    for (const auto center: centers) simpl_centers.push_back(simplified_in[center]);\n    \n    auto end = boost::chrono::process_real_cpu_clock::now();\n    result.centers = simpl_centers;\n    result.value = curr_maxdist;\n    result.running_time = (end-start).count() / 1000000000.0;\n    return result;\n}\n\nClustering_Result arya(const curve_number_t num_centers, const curve_size_t ell, const Curves &in, Distance_Matrix &distances, const Curves &center_domain = Curves()) {\n    return gonzalez(num_centers, ell, in, distances, true, center_domain, false);\n}\n\nClustering_Result one_median_sampling(const curve_size_t ell, const Curves &in, const double epsilon, const Curves &center_domain = Curves()) {\n    const auto start = boost::chrono::process_real_cpu_clock::now();\n    Clustering_Result result;\n    std::vector<curve_number_t> centers;\n    const Curves &simplified_in = center_domain;\n    \n    if (center_domain.empty()) {\n        Curves simplified_in_self(in.number(), ell, in.dimensions());\n        \n        for (curve_number_t i = 0; i < in.size(); ++i) {\n            Simplification::Subcurve_Shortcut_Graph graph(const_cast<Curve&>(in[i]));\n            auto simplified_curve = graph.weak_minimum_error_simplification(ell);\n            simplified_curve.set_name(\"Simplification of \" + in[i].get_name());\n            simplified_in_self[i] = simplified_curve;\n        }\n        const_cast<Curves&>(simplified_in) = simplified_in_self;\n    }\n    \n    const auto n = in.size();\n    \n    const auto s = std::ceil(60);\n    const auto t = std::ceil(std::log(60)/(epsilon*epsilon));\n    \n    Random::Uniform_Random_Generator<double> ugen;\n    \n    const auto candidates = ugen.get(s);\n    const auto witnesses = ugen.get(t);\n    \n    Distance_Matrix distances = Distance_Matrix(in.size(), in.size());\n    \n    curve_number_t best_candidate = 0;\n    distance_t best_objective_value = std::numeric_limits<distance_t>::infinity();\n    \n    for (curve_number_t i = 0; i < candidates.size(); ++i) {\n        \n        const curve_number_t candidate = std::floor(candidates[i] * n);\n        distance_t objective = 0;\n        \n        for (curve_number_t j = 0; j < witnesses.size(); ++j) {\n            const curve_number_t witness = std::floor(witnesses[j] * n);\n            \n            _cheap_dist(witness, candidate, in, simplified_in, distances);\n            objective += distances[witness][candidate];\n        }\n        \n        if (objective < best_objective_value) {\n            best_candidate = candidate;\n            best_objective_value = objective;\n        }\n    }\n    centers.push_back(best_candidate);\n    \n    auto end = boost::chrono::process_real_cpu_clock::now();\n    result.centers.push_back(simplified_in[centers[0]]);\n    result.value = _center_cost_sum(in, simplified_in, centers, distances);\n    result.running_time = (end-start).count() / 1000000000.0;\n    return result;\n}\n\nClustering_Result one_median_exhaustive(const curve_size_t ell, const Curves &in, const Curves &center_domain = Curves()) {\n    const auto start = boost::chrono::process_real_cpu_clock::now();\n    Clustering_Result result;\n    std::vector<curve_number_t> centers;\n    const Curves &simplified_in = center_domain;\n    \n    if (center_domain.empty()) {\n        Curves simplified_in_self(in.number(), ell, in.dimensions());\n        \n        for (curve_number_t i = 0; i < in.size(); ++i) {\n            Simplification::Subcurve_Shortcut_Graph graph(const_cast<Curve&>(in[i]));\n            auto simplified_curve = graph.weak_minimum_error_simplification(ell);\n            simplified_curve.set_name(\"Simplification of \" + in[i].get_name());\n            simplified_in_self[i] = simplified_curve;\n        }\n        const_cast<Curves&>(simplified_in) = simplified_in_self;\n    }\n    \n    const auto n = in.size();\n        \n    Distance_Matrix distances = Distance_Matrix(in.size(), in.size());\n    \n    curve_number_t best_candidate = 0;\n    distance_t best_objective_value = std::numeric_limits<distance_t>::infinity();\n    \n    for (curve_number_t j = 0; j < in.size(); ++j) {\n        \n        distance_t objective = 0;\n        \n        for (curve_number_t i = 0; i < in.size(); ++i) {\n            _cheap_dist(i, j, in, simplified_in, distances);\n            objective += distances[i][j];\n        }\n        \n        if (objective < best_objective_value) {\n            best_candidate = j;\n            best_objective_value = objective;\n        }\n    }\n    centers.push_back(best_candidate);\n    \n    auto end = boost::chrono::process_real_cpu_clock::now();\n    result.centers.push_back(simplified_in[centers[0]]);\n    result.value = best_objective_value;\n    result.running_time = (end-start).count() / 1000000000.0;\n    return result;\n}\n\nClustering_Result two_two_dtw_one_two_median(const Curves &in, const bool with_assignment = false) {\n    const auto start = boost::chrono::process_real_cpu_clock::now();\n    Clustering_Result result;\n    \n    const auto n = in.size();\n    \n    std::vector<std::vector<bool>> markings = std::vector<std::vector<bool>>(n, std::vector<bool>(in.get_m(), false));\n    std::vector<curve_size_t> svert = std::vector<curve_size_t>(n, 0), evert = std::vector<curve_size_t>(n, 0);\n    \n    Points S1(in.dimensions()), S2(in.dimensions());\n    Point mu1(in.dimensions()), mu2(in.dimensions());\n    \n    for (curve_number_t i = 0; i < n; ++i) {\n        S1.push_back(in[i][svert[i]]);\n        markings[i][svert[i]] = true;\n        ++svert[i];\n        evert[i] = in[i].size() - 1;\n        S2.push_back(in[i][evert[i]]);\n        markings[i][evert[i]] = true;\n        --evert[i];\n    }\n    \n    mu1 = S1.centroid();\n    mu2 = S2.centroid();\n        \n    const auto infty = std::numeric_limits<distance_t>::infinity();\n    \n    bool done = false;\n    distance_t d1 = infty, d2 = infty, dist = infty;\n    curve_number_t c1 = 0, c2 = 0;\n    \n    while (not done) {\n        d1 = infty;\n        d2 = infty;\n        \n        for (curve_size_t i = 0; i < in.size(); ++i) {\n            if (not markings[i][svert[i]]) {\n                dist = in[i][svert[i]].dist_sqr(mu1);\n                if (dist < d1) {\n                    d1 = dist;\n                    c1 = i;\n                }\n            }\n            if (not markings[i][evert[i]]) {\n                dist = in[i][evert[i]].dist_sqr(mu2);\n                if (dist < d2) {\n                    d2 = dist;\n                    c2 = i;\n                }\n            }\n        }\n        \n        if (d1 < d2) {\n            //std::cout << \"S1 add \" << c1 << \".\" << svert[c1] << std::endl;\n            S1.push_back(in[c1][svert[c1]]);\n            markings[c1][svert[c1]] = true;\n            ++svert[c1];\n            mu1 = S1.centroid();\n            done = false;\n        }\n        else if (d2 < infty) {\n            //std::cout << \"S2 add \" << c2 << \".\" << evert[c2] << std::endl;\n            S2.push_back(in[c2][evert[c2]]);\n            markings[c2][evert[c2]] = true;\n            --evert[c2];\n            mu2 = S2.centroid();\n            done = false;\n        } else done = true;\n        \n    }\n    \n    Curve center_curve(mu1.dimensions(), \"center curve\");\n    center_curve.push_back(mu1);\n    center_curve.push_back(mu2);\n    \n    distance_t cost = 0;\n    \n    for (const auto &p : S1) cost += p.dist(mu1);\n    for (const auto &p : S2) cost += p.dist(mu2);\n    \n    auto end = boost::chrono::process_real_cpu_clock::now();\n    result.centers.push_back(center_curve);\n    result.value = cost;\n    result.running_time = (end-start).count() / 1000000000.0;\n    return result;\n}\n\nClustering_Result two_two_dtw_one_two_median_exact(const Curves &in, const bool with_assignment = false) {\n    const auto start = boost::chrono::process_real_cpu_clock::now();\n    Clustering_Result result;\n    Curve best_center(in.dimensions());\n    const auto infty = std::numeric_limits<distance_t>::infinity();\n    \n    curve_size_t n = 1;\n    std::vector<curve_size_t> pointers = std::vector<curve_size_t>(in.size(), 0), \n                                divisors = std::vector<curve_size_t>(in.size(), 0);\n    distance_t best = infty, cost = 0;\n    Points S1(in.dimensions()), S2(in.dimensions());\n    \n    for (curve_number_t i = 0; i < in.size(); ++i) {\n        n *= in[i].complexity() - 1;\n        if (i == 0) divisors[i] = in[0].complexity() - 1;\n        else if (i == 1) divisors[i] = in[0].complexity() - 1;\n        else divisors[i] = divisors[i-1] * (in[i].complexity() - 1);\n    }\n    \n    const auto onepercent = n / 100;\n    \n    int currperc = 0;\n    \n    for (curve_size_t i = 0; i < n; ++i) {\n        \n        if (onepercent > 0) {\n            if (i / onepercent > currperc) {\n                currperc = i / onepercent;\n                std::cout << currperc << \"% done\" << std::endl;\n            }\n        }\n        \n        pointers[0] = i % divisors[0];\n        for (curve_number_t j = 1; j < in.size(); ++j) {\n            pointers[j] = (i / divisors[j]) % (in[j].complexity() - 1);\n        }\n        \n        S1.clear();\n        S2.clear();\n        \n        for (curve_number_t j = 0; j < in.size(); ++j) {\n            for (curve_size_t k = 0; k < in[j].complexity(); ++ k) {\n                if (k <= pointers[j]) {\n                    S1.push_back(in[j][k]);\n                    if (k == in[j].complexity() - 1) std::cerr << \"error!!\" << std::endl;\n                }\n                else S2.push_back(in[j][k]);\n            }\n        }\n        \n        auto mu1 = S1.centroid();\n        auto mu2 = S2.centroid();\n        \n        Curve center_curve(mu1.dimensions(), \"optimal center curve\");\n        center_curve.push_back(mu1);\n        center_curve.push_back(mu2);\n        \n        cost = 0;\n        \n        for (curve_number_t j = 0; j < in.size(); ++j) {\n            const auto dist = Dynamic_Time_Warping::Discrete::distance(center_curve, in[j]);\n            cost += dist.value;\n        }\n        \n        if (cost < best) {\n            best = cost;\n            best_center = center_curve;\n        }\n    }\n    \n    auto end = boost::chrono::process_real_cpu_clock::now();\n    result.centers.push_back(best_center);\n    result.value = best;\n    result.running_time = (end-start).count() / 1000000000.0;\n    return result;\n}\n\n\n}\n", "meta": {"hexsha": "81690ee5ed25a84a4d059a884489cdcd23d905fe", "size": 19326, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/clustering.hpp", "max_stars_repo_name": "hairbeRt/Fred", "max_stars_repo_head_hexsha": "ae3770e2ad62f83a7d2070e8e48087d89aa09bfc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/clustering.hpp", "max_issues_repo_name": "hairbeRt/Fred", "max_issues_repo_head_hexsha": "ae3770e2ad62f83a7d2070e8e48087d89aa09bfc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/clustering.hpp", "max_forks_repo_name": "hairbeRt/Fred", "max_forks_repo_head_hexsha": "ae3770e2ad62f83a7d2070e8e48087d89aa09bfc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.094049904, "max_line_length": 460, "alphanum_fraction": 0.5917416951, "num_tokens": 4700, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6076631698328917, "lm_q2_score": 0.5312093733737562, "lm_q1q2_score": 0.3227963716692408}}
{"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 <climits>\n//#include <iostream>\n\n#include <boost/numeric/conversion/converter.hpp>\n#include \"BConverter.hh\"\n\n\ntemplate<typename T, typename S> T BConverter::round_to_even(const S& x) \n{\n    typedef boost::numeric::conversion_traits<T, S> Traits;\n    typedef boost::numeric::def_overflow_handler OverflowHandler;\n    typedef boost::numeric::RoundEven<typename Traits::source_type> Rounder;\n    typedef boost::numeric::converter<T, S, Traits, OverflowHandler, Rounder> Converter;\n    return Converter::convert(x);\n}\n\nshort BConverter::shortnorm( float v, float center, float extent ) // static\n{\n    float f = (v - center)/extent ;\n    return std::abs(f) > 1 ? SHRT_MIN : round_to_even<short, float>( 32767.0f * f ) ; \n}\n\n\n#define fitsInShort(x) !(((((x) & 0xffff8000) >> 15) + 1) & 0x1fffe)\n#define iround(x) ((x)>=0?(int)((x)+0.5):(int)((x)-0.5))\n\nshort BConverter::shortnorm_old( float v, float center, float extent )  // static \n{\n    // range of short is -32768 to 32767\n    // Expect no positions out of range, as constrained by the geometry are bouncing on,\n    // but getting times beyond the range eg 0.:100 ns is expected\n    //  \n    int inorm = iround(32767.0f * (v - center)/extent ) ;    // linear scaling into -1.f:1.f * float(SHRT_MAX)\n    return fitsInShort(inorm) ? short(inorm) : SHRT_MIN  ;\n} \n\n\nunsigned char BConverter::my__float2uint_rn_old( float f ) // static\n{\n    return iround(f);\n}\n\nunsigned char BConverter::my__float2uint_rn( float fv ) // static\n{\n    return BConverter::round_to_even<unsigned char, float>( fv ) ; \n}\n\n\nunsigned char BConverter::my__float2uint_rn_kludge( float fv ) // static\n{\n    unsigned char uc(0);  \n    try \n    {\n        uc = BConverter::my__float2uint_rn(fv ) ;\n    }     \n    catch( boost::numeric::positive_overflow& e  )\n    {\n        //std::cout << e.what() << std::endl ;  \n    }\n    catch( boost::numeric::negative_overflow& e  )\n    {\n        //std::cout << e.what() << std::endl ;  \n    }\n    return uc ; \n}\n\n\n\n\n\ntemplate BRAP_API int   BConverter::round_to_even(const float& x);\ntemplate BRAP_API short BConverter::round_to_even(const float& x);\ntemplate BRAP_API unsigned char BConverter::round_to_even(const float& x);\n\n", "meta": {"hexsha": "f5b4330981d373ecd874b17b28450d5e8dd6abf7", "size": 2912, "ext": "cc", "lang": "C++", "max_stars_repo_path": "boostrap/BConverter.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": "boostrap/BConverter.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": "boostrap/BConverter.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": 30.6526315789, "max_line_length": 110, "alphanum_fraction": 0.6799450549, "num_tokens": 791, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6076631698328916, "lm_q2_score": 0.5312093733737562, "lm_q1q2_score": 0.32279637166924074}}
{"text": "// ----------------------------------------------------------------------------\n// -                        Open3D: www.open3d.org                            -\n// ----------------------------------------------------------------------------\n// The MIT License (MIT)\n//\n// Copyright (c) 2019 www.open3d.org\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n// IN THE SOFTWARE.\n// ----------------------------------------------------------------------------\n\n#include \"Open3D/Geometry/Geometry3D.h\"\n\n#include <Eigen/Dense>\n#include <numeric>\n\n#include \"Open3D/Utility/Console.h\"\n\nnamespace open3d {\nnamespace geometry {\n\nEigen::Vector3d Geometry3D::ComputeMinBound(\n        const std::vector<Eigen::Vector3d>& points) const {\n    if (points.empty()) {\n        return Eigen::Vector3d(0.0, 0.0, 0.0);\n    }\n    return 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}\n\nEigen::Vector3d Geometry3D::ComputeMaxBound(\n        const std::vector<Eigen::Vector3d>& points) const {\n    if (points.empty()) {\n        return Eigen::Vector3d(0.0, 0.0, 0.0);\n    }\n    return 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}\nEigen::Vector3d Geometry3D::ComputeCenter(\n        const std::vector<Eigen::Vector3d>& points) const {\n    Eigen::Vector3d center(0, 0, 0);\n    if (points.empty()) {\n        return center;\n    }\n    center = std::accumulate(points.begin(), points.end(), center);\n    center /= double(points.size());\n    return center;\n}\n\nvoid Geometry3D::ResizeAndPaintUniformColor(\n        std::vector<Eigen::Vector3d>& colors,\n        const size_t size,\n        const Eigen::Vector3d& color) const {\n    colors.resize(size);\n    Eigen::Vector3d clipped_color = color;\n    if (color.minCoeff() < 0 || color.maxCoeff() > 1) {\n        utility::LogWarning(\n                \"invalid color in PaintUniformColor, clipping to [0, 1]\");\n        clipped_color = clipped_color.array()\n                                .max(Eigen::Vector3d(0, 0, 0).array())\n                                .matrix();\n        clipped_color = clipped_color.array()\n                                .min(Eigen::Vector3d(1, 1, 1).array())\n                                .matrix();\n    }\n    for (size_t i = 0; i < size; i++) {\n        colors[i] = clipped_color;\n    }\n}\n\nvoid Geometry3D::TransformPoints(const Eigen::Matrix4d& transformation,\n                                 std::vector<Eigen::Vector3d>& points) const {\n    for (auto& point : points) {\n        Eigen::Vector4d new_point =\n                transformation *\n                Eigen::Vector4d(point(0), point(1), point(2), 1.0);\n        point = new_point.head<3>() / new_point(3);\n    }\n}\n\nvoid Geometry3D::TransformNormals(const Eigen::Matrix4d& transformation,\n                                  std::vector<Eigen::Vector3d>& normals) const {\n    for (auto& normal : normals) {\n        Eigen::Vector4d new_normal =\n                transformation *\n                Eigen::Vector4d(normal(0), normal(1), normal(2), 0.0);\n        normal = new_normal.head<3>();\n    }\n}\n\nvoid Geometry3D::TranslatePoints(const Eigen::Vector3d& translation,\n                                 std::vector<Eigen::Vector3d>& points,\n                                 bool relative) const {\n    Eigen::Vector3d transform = translation;\n    if (!relative) {\n        transform -= ComputeCenter(points);\n    }\n    for (auto& point : points) {\n        point += transform;\n    }\n}\n\nvoid Geometry3D::ScalePoints(const double scale,\n                             std::vector<Eigen::Vector3d>& points,\n                             const Eigen::Vector3d& center) const {\n    for (auto& point : points) {\n        point = (point - center) * scale + center;\n    }\n}\n\nvoid Geometry3D::RotatePoints(const Eigen::Matrix3d& R,\n                              std::vector<Eigen::Vector3d>& points,\n                              const Eigen::Vector3d& center) const {\n    for (auto& point : points) {\n        point = R * (point - center) + center;\n    }\n}\n\nvoid Geometry3D::RotateNormals(const Eigen::Matrix3d& R,\n                               std::vector<Eigen::Vector3d>& normals) const {\n    for (auto& normal : normals) {\n        normal = R * normal;\n    }\n}\n\nEigen::Matrix3d Geometry3D::GetRotationMatrixFromXYZ(\n        const Eigen::Vector3d& rotation) {\n    return open3d::utility::RotationMatrixX(rotation(0)) *\n           open3d::utility::RotationMatrixY(rotation(1)) *\n           open3d::utility::RotationMatrixZ(rotation(2));\n}\n\nEigen::Matrix3d Geometry3D::GetRotationMatrixFromYZX(\n        const Eigen::Vector3d& rotation) {\n    return open3d::utility::RotationMatrixY(rotation(0)) *\n           open3d::utility::RotationMatrixZ(rotation(1)) *\n           open3d::utility::RotationMatrixX(rotation(2));\n}\n\nEigen::Matrix3d Geometry3D::GetRotationMatrixFromZXY(\n        const Eigen::Vector3d& rotation) {\n    return open3d::utility::RotationMatrixZ(rotation(0)) *\n           open3d::utility::RotationMatrixX(rotation(1)) *\n           open3d::utility::RotationMatrixY(rotation(2));\n}\n\nEigen::Matrix3d Geometry3D::GetRotationMatrixFromXZY(\n        const Eigen::Vector3d& rotation) {\n    return open3d::utility::RotationMatrixX(rotation(0)) *\n           open3d::utility::RotationMatrixZ(rotation(1)) *\n           open3d::utility::RotationMatrixY(rotation(2));\n}\n\nEigen::Matrix3d Geometry3D::GetRotationMatrixFromZYX(\n        const Eigen::Vector3d& rotation) {\n    return open3d::utility::RotationMatrixZ(rotation(0)) *\n           open3d::utility::RotationMatrixY(rotation(1)) *\n           open3d::utility::RotationMatrixX(rotation(2));\n}\n\nEigen::Matrix3d Geometry3D::GetRotationMatrixFromYXZ(\n        const Eigen::Vector3d& rotation) {\n    return open3d::utility::RotationMatrixY(rotation(0)) *\n           open3d::utility::RotationMatrixX(rotation(1)) *\n           open3d::utility::RotationMatrixZ(rotation(2));\n}\n\nEigen::Matrix3d Geometry3D::GetRotationMatrixFromAxisAngle(\n        const Eigen::Vector3d& rotation) {\n    const double phi = rotation.norm();\n    return Eigen::AngleAxisd(phi, rotation / phi).toRotationMatrix();\n}\n\nEigen::Matrix3d Geometry3D::GetRotationMatrixFromQuaternion(\n        const Eigen::Vector4d& rotation) {\n    return Eigen::Quaterniond(rotation(0), rotation(1), rotation(2),\n                              rotation(3))\n            .normalized()\n            .toRotationMatrix();\n}\n\n}  // namespace geometry\n}  // namespace open3d\n", "meta": {"hexsha": "8482eae386976abe2e0fb46ec8dc7a0d9db479a9", "size": 7675, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Open3D/Geometry/Geometry3D.cpp", "max_stars_repo_name": "arunabhcode/Open3D", "max_stars_repo_head_hexsha": "40902ae67947fa27abeb748673bcc78b002180f6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2021-01-23T13:03:03.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T12:55:59.000Z", "max_issues_repo_path": "src/Open3D/Geometry/Geometry3D.cpp", "max_issues_repo_name": "arunabhcode/Open3D", "max_issues_repo_head_hexsha": "40902ae67947fa27abeb748673bcc78b002180f6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-01-24T00:33:28.000Z", "max_issues_repo_issues_event_max_datetime": "2019-06-11T00:44:32.000Z", "max_forks_repo_path": "src/Open3D/Geometry/Geometry3D.cpp", "max_forks_repo_name": "arunabhcode/Open3D", "max_forks_repo_head_hexsha": "40902ae67947fa27abeb748673bcc78b002180f6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 14.0, "max_forks_repo_forks_event_min_datetime": "2020-12-30T12:19:45.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-24T01:28:45.000Z", "avg_line_length": 37.4390243902, "max_line_length": 80, "alphanum_fraction": 0.5971335505, "num_tokens": 1813, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6076631698328916, "lm_q2_score": 0.5312093733737562, "lm_q1q2_score": 0.32279637166924074}}
{"text": "/**\n\nCopyright (c) 2016, Aumann Florian, Borella Jocelyn, Heller Florian, Meißner Pascal, Schleicher Ralf, Stöckle Patrick, Stroh Daniel, Trautmann Jeremias, Walter Milena, Wittenbeck Valerij\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\n4. The use is explicitly not permitted to any application which deliberately try to kill or do harm to any living creature.\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#ifndef MYMATHHELPER_HPP_\n#define MYMATHHELPER_HPP_\n\n#include \"robot_model_services/typedef.hpp\"\n#include <boost/math/special_functions/binomial.hpp>\n#include <boost/random/mersenne_twister.hpp>\n#include <boost/random/uniform_int.hpp>\n#include <boost/random/uniform_real.hpp>\n#include <boost/random/normal_distribution.hpp>\n#include <boost/random/variate_generator.hpp>\n#include <boost/foreach.hpp>\n#include <ros/ros.h>\n#include <set>\n#include <vector>\n#include <geometry_msgs/Quaternion.h>\n\nnamespace robot_model_services {\n\t/*!\n\t * \\brief MathHelper unites the generally needed math operations.\n\t * \\author Ralf Schleicher\n\t * \\date 2014\n\t * \\version 1.0\n\t * \\copyright GNU Public License\n\t */\n\tclass MathHelper {\n\tprivate:\n\t\t/*!\n\t\t * \\return the randomness generator.\n\t\t */\n\t\tstatic boost::mt19937& getRandomnessGenerator();\n\tpublic:\n\t\t/*!\n\t\t * \\brief converts cartesian coordinates to sphere coordinates\n\t\t * \\param cartestian any cartesian coordinates\n\t\t * \\return sphere coordinates (radius,inclinate,azimuth)\n\t\t */\n\t\tstatic SimpleSphereCoordinates convertC2S(const SimpleVector3 &cartesian);\n\n\t\t/*!\n\t\t * \\brief converts cartesian coordinates to sphere coordinates (lightweight)\n\t\t * \\param cartestian any cartesian coordinates\n\t\t * \\param sphere (out) sphere coordinates (radius,inclinate,azimuth)\n\t\t */\n\t\tstatic void convertC2S(const SimpleVector3 &cartesian, SimpleSphereCoordinates &sphere);\n\n\t\t/*!\n\t\t * \\brief converts sphere coordinates to cartesian coordinates (lightweight)\n\t\t * \\param sphere any sphere coordinates (radius,inclinate,azimuth)\n\t\t * \\return cartesian coordinates\n\t\t */\n\t\tstatic SimpleVector3 convertS2C(const SimpleSphereCoordinates &sphere);\n\n\t\t/*!\n\t\t * \\brief converts sphere coordinates to cartesian coordinates (lightweight)\n\t\t * \\param sphere any sphere coordinates (radius,inclinate,azimuth)\n\t\t * \\param cartesian (out) cartesian coordinates\n\t\t */\n\t\tstatic void convertS2C(const SimpleSphereCoordinates &sphere, SimpleVector3 &cartesian);\n\n\t\tstatic SimpleVector3 getVisualAxis(const SimpleQuaternion &orientation);\n\n\t\tstatic void getVisualAxis(const SimpleQuaternion &orientation, SimpleVector3 &resultAxis);\n\n\t\t/*!\n\t\t * \\param value [in]\n\t\t * \\return the signum of value\n\t\t */\n\t\tstatic double getSignum(const double &value);\n\n\t\t/*!\n\t\t * \\param idx [in] the index to project to 0\n\t\t * \\param X [in] the 3d vector used for this action.\n\t\t * \\return the 3d vector after projection\n\t\t */\n\t\tstatic SimpleVector3 getProjection(const std::size_t &idx, const SimpleVector3 &X);\n\n\t\t/*!\n\t\t * \\param X [in] the first 3d vector\n\t\t * \\param Y [in] the second 3d vector\n         * \\return the cosinus between the two vectors.\n\t\t */\n\t\tstatic Precision getCosinus(const SimpleVector3 &X, const SimpleVector3 &Y);\n\n        /*!\n         * \\param X [in] the first 3d vector\n         * \\param Y [in] the second 3d vector\n         * \\return the angle between the two vectors\n         */\n        static Precision getAngle(const SimpleVector3 &X, const SimpleVector3 &Y);\n\n        /*!\n\t\t * \\param firstAngle [in] the first angle\n\t\t * \\param secondAngle [in] the second angle\n\t\t * \\return the minimum angle difference.\n\t\t */\n\t\tstatic Precision getMinimumAngleDifference(const Precision &firstAngle, const Precision &secondAngle);\n\n\t\t/*!\n\t\t * \\param min [in] the minumum integer\n\t\t * \\param max [in] the maximum integer\n\t\t * \\return a random integer in the range [min, max]\n\t\t */\n\t\tstatic int getRandomInteger(const int &min, const int &max);\n\n\t\t/*!\n\t\t * \\param mean [in] the mean value\n\t\t * \\param standardDeviation [in] the standard deviation to use.\n\t\t * \\return a normal distributed random number.\n\t\t */\n\t\tstatic Precision getRandomNumber(const Precision &mean, const Precision &standardDeviation);\n\n\t\t/*!\n\t\t * \\param mean [in] the mean value in X dimensions\n\t\t * \\param standardDeviation [in] the standard deviation to use in X dimensions.\n\t\t * \\return a normal distributed random vector.\n\t\t */\n\t\tstatic SimpleVectorX getRandomVector(const SimpleVectorX &mean, const SimpleVectorX &standardDeviation);\n\n\t\t/*!\n\t\t * \\return a random rotation quaternion\n\t\t */\n\t\tstatic SimpleQuaternion getRandomQuaternion();\n\n\t\t/*!\n\t\t * \\param heading [in] the heading angle\n\t\t * \\param attitude [in] the attitude angle\n\t\t * \\param bank [in] the bank angle\n\t\t * \\return the corresponding quaternion\n\t\t */\n\t\tstatic SimpleQuaternion getQuaternionByAngles(const Precision &heading, const Precision &attitude, const Precision &bank);\n\n\t\t/*!\n\t\t * \\param numberOfPoints [in] the number of points to use.\n\t\t * \\return an array of orientations.\n\t\t */\n\t\tstatic SimpleQuaternionCollectionPtr getOrientationsOnUnitSphere(const int &numberOfPoints);\n\n\t\t/*!\n\t\t * \\param input in radians\n\t\t * \\return input in degrees\n\t\t */\n\t\tstatic double radToDeg(double input);\n\n\t\t/*!\n\t\t * \\param input in degrees\n\t\t * \\return input in radians\n\t\t */\n\t\tstatic double degToRad(double input);\n\n\t\tstatic double getDotProduct(SimpleVector3 v1, SimpleVector3 v2);\n\n\t\ttemplate<typename Set> static void printSet(boost::shared_ptr<Set> &setPtr) {\n\t\t\tstd::cout << \"\\t{ \";\n\t\t\tBOOST_FOREACH(typename Set::value_type value, *setPtr) {\n\t\t\t\tstd::cout << value << \", \";\n\t\t\t}\n\t\t\tstd::cout << \"}\" << std::endl;\n\t\t}\n\n\t\ttemplate<typename Set> static void printPowerSet(boost::shared_ptr<std::set<boost::shared_ptr<Set> > > &powerSetPtr) {\n\t\t\tstd::cout << \"{ \" << std::endl;\n\t\t\tBOOST_FOREACH(boost::shared_ptr<Set> subSetPtr, *powerSetPtr) {\n\t\t\t\tprintSet(subSetPtr);\n\t\t\t}\n\t\t\tstd::cout << \"} \" << std::endl;\n\t\t\tstd::cout << powerSetPtr->size() << \" Items\" << std::endl;\n\t\t}\n\n\t\ttemplate<typename Set> static boost::shared_ptr<std::set<boost::shared_ptr<Set> > > powerSet(const boost::shared_ptr<Set> &setPtr) {\n\t\t\tboost::shared_ptr<std::set<boost::shared_ptr<Set> > > powerSetPtr(new std::set<boost::shared_ptr<Set> >);\n\n\t\t\tstd::size_t value = 0;\n\t\t\tassert(setPtr->size() <= 31);\n\n\n\t\t\tstd::size_t limit = (1 << setPtr->size());\n\t\t\tfor (std::size_t counter = 0; counter < limit; ++counter) {\n\t\t\t\tboost::shared_ptr<Set> subSetPtr(new Set);\n\t\t\t\tstd::size_t idx = 0;\n\t\t\t\tfor (typename Set::iterator setIter = setPtr->begin(); setIter != setPtr->end();  ++setIter, ++idx) {\n\t\t\t\t\tif ( (value & (1 << idx)) != 0 ) {\n\t\t\t\t\t\tsubSetPtr->insert(*setIter);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tpowerSetPtr->insert(subSetPtr);\n\n\t\t\t\t// the value\n\t\t\t\t++value;\n\t\t\t}\n\n\t\t\treturn powerSetPtr;\n\t\t}\n\n\n\t\ttemplate<typename PowerSet> static boost::shared_ptr<PowerSet> filterCardinalityPowerSet(const boost::shared_ptr<PowerSet> &powerSetPtr, const std::size_t min, const std::size_t max) {\n\t\t\tboost::shared_ptr<PowerSet> resultPowerSetPtr(new PowerSet);\n\n\t\t\tfor (typename PowerSet::iterator powerSetIter = powerSetPtr->begin(); powerSetIter != powerSetPtr->end(); ++powerSetIter) {\n\t\t\t\tif ((*powerSetIter)->size() < min || (*powerSetIter)->size() > max) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tresultPowerSetPtr->insert(*powerSetIter);\n\t\t\t}\n\n\t\t\treturn resultPowerSetPtr;\n\t\t}\n\n\t\ttemplate<typename PowerSet> static boost::shared_ptr<PowerSet> filterCardinalityPowerSet(const boost::shared_ptr<PowerSet> &setPtr, const std::size_t min) {\n\t\t\treturn filterCardinalityPowerSet<PowerSet>(setPtr, min, setPtr->size());\n\t\t}\n\t};\n}\n\n\n\n#endif /* MYMATHHELPER_HPP_ */\n", "meta": {"hexsha": "71f790e9fa4b4de5a6223966462fcefb8faa4766", "size": 8918, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/robot_model_services/helper/MathHelper.hpp", "max_stars_repo_name": "asr-ros/asr_robot_model_services", "max_stars_repo_head_hexsha": "93fe96abd31bbf3fe2bd0533ac35267cd6613f2f", "max_stars_repo_licenses": ["BSD-3-Clause"], "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/robot_model_services/helper/MathHelper.hpp", "max_issues_repo_name": "asr-ros/asr_robot_model_services", "max_issues_repo_head_hexsha": "93fe96abd31bbf3fe2bd0533ac35267cd6613f2f", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/robot_model_services/helper/MathHelper.hpp", "max_forks_repo_name": "asr-ros/asr_robot_model_services", "max_forks_repo_head_hexsha": "93fe96abd31bbf3fe2bd0533ac35267cd6613f2f", "max_forks_repo_licenses": ["BSD-3-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.6286919831, "max_line_length": 755, "alphanum_fraction": 0.7212379457, "num_tokens": 2212, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6076631556226291, "lm_q2_score": 0.5312093733737562, "lm_q1q2_score": 0.3227963641206161}}
{"text": "///////////////////////////////////////////////////////////////////////////////\n// BSD 3-Clause License\n//\n// Copyright (C) 2021, University of Edinburgh\n// Copyright note valid unless otherwise stated in individual files.\n// All rights reserved.\n///////////////////////////////////////////////////////////////////////////////\n\n#ifndef CROCODDYL_CORE_RESIDUAL_BASE_HPP_\n#define CROCODDYL_CORE_RESIDUAL_BASE_HPP_\n\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/data-collector-base.hpp\"\n\nnamespace crocoddyl {\n\n/**\n * @brief Abstract class for residual models\n *\n * In Crocoddyl, a residual model defines a vector function \\f$\\mathbf{r}(\\mathbf{x}, \\mathbf{u})\\mathbb{R}^{nr}\\f$\n * where `nr` describes its dimension in the Euclidean space. This function depends on the state point\n * \\f$\\mathbf{x}\\in\\mathcal{X}\\f$, which lies in the state manifold described with a `nq`-tuple, its velocity\n * \\f$\\dot{\\mathbf{x}}\\in T_{\\mathbf{x}}\\mathcal{X}\\f$ that belongs to the tangent space with `nv` dimension, and the\n * control input \\f$\\mathbf{u}\\in\\mathbb{R}^{nu}\\f$. The residual function can used across cost and constraint models.\n *\n * The main computations are carring out in `calc` and `calcDiff` routines. `calc` computes the residual vector\n * and `calcDiff` computes the Jacobians of the residual function.\n * Additionally, it is important remark that `calcDiff()` computes the Jacobians using the latest stored values by\n * `calc()`. Thus, we need to run first `calc()`.\n *\n * \\sa `StateAbstractTpl`, `calc()`, `calcDiff()`, `createData()`\n */\ntemplate <typename _Scalar>\nclass ResidualModelAbstractTpl {\n public:\n  EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n\n  typedef _Scalar Scalar;\n  typedef MathBaseTpl<Scalar> MathBase;\n  typedef ResidualDataAbstractTpl<Scalar> ResidualDataAbstract;\n  typedef StateAbstractTpl<Scalar> StateAbstract;\n  typedef DataCollectorAbstractTpl<Scalar> DataCollectorAbstract;\n  typedef typename MathBase::VectorXs VectorXs;\n  typedef typename MathBase::MatrixXs MatrixXs;\n\n  /**\n   * @brief Initialize the residual model\n   *\n   * @param[in] state        State of the system\n   * @param[in] nr           Dimension of residual vector\n   * @param[in] nu           Dimension of control vector\n   * @param[in] q_dependent  Define if the residual function depends on q (default true)\n   * @param[in] v_dependent  Define if the residual function depends on v (default true)\n   * @param[in] u_dependent  Define if the residual function depends on u (default true)\n   */\n  ResidualModelAbstractTpl(boost::shared_ptr<StateAbstract> state, const std::size_t nr, const std::size_t nu,\n                           const bool q_dependent = true, const bool v_dependent = true,\n                           const bool u_dependent = true);\n\n  /**\n   * @copybrief ResidualModelAbstractTpl()\n   *\n   * The default `nu` value is obtained from `StateAbstractTpl::get_nv()`.\n   *\n   * @param[in] state        State of the system\n   * @param[in] nr           Dimension of residual vector\n   * @param[in] q_dependent  Define if the residual function depends on q (default true)\n   * @param[in] v_dependent  Define if the residual function depends on v (default true)\n   * @param[in] u_dependent  Define if the residual function depends on u (default true)\n   */\n  ResidualModelAbstractTpl(boost::shared_ptr<StateAbstract> state, const std::size_t nr, const bool q_dependent = true,\n                           const bool v_dependent = true, const bool u_dependent = true);\n  virtual ~ResidualModelAbstractTpl();\n\n  /**\n   * @brief Compute the residual vector\n   *\n   * @param[in] data  Residual data\n   * @param[in] x     State point \\f$\\mathbf{x}\\in\\mathbb{R}^{ndx}\\f$\n   * @param[in] u     Control input \\f$\\mathbf{u}\\in\\mathbb{R}^{nu}\\f$\n   */\n  virtual void calc(const boost::shared_ptr<ResidualDataAbstract>& data, const Eigen::Ref<const VectorXs>& x,\n                    const Eigen::Ref<const VectorXs>& u);\n\n  /**\n   * @brief Compute the Jacobian of the residual vector\n   *\n   * It computes the Jacobian the residual function. It assumes that `calc()` has been run first.\n   *\n   * @param[in] data  Residual data\n   * @param[in] x     State point \\f$\\mathbf{x}\\in\\mathbb{R}^{ndx}\\f$\n   * @param[in] u     Control input \\f$\\mathbf{u}\\in\\mathbb{R}^{nu}\\f$\n   */\n  virtual void calcDiff(const boost::shared_ptr<ResidualDataAbstract>& data, const Eigen::Ref<const VectorXs>& x,\n                        const Eigen::Ref<const VectorXs>& u);\n\n  /**\n   * @brief Create the residual data\n   *\n   * The default data contains objects to store the values of the residual vector and their Jacobians.\n   * However, it is possible to specialized this function if we need to create additional data, for instance, to avoid\n   * dynamic memory allocation.\n   *\n   * @param data  Data collector\n   * @return the residual data\n   */\n  virtual boost::shared_ptr<ResidualDataAbstract> createData(DataCollectorAbstract* const data);\n\n  /**\n   * @copybrief calc()\n   *\n   * @param[in] data  Residual data\n   * @param[in] x     State point\n   */\n  void calc(const boost::shared_ptr<ResidualDataAbstract>& data, const Eigen::Ref<const VectorXs>& x);\n\n  /**\n   * @copybrief calcDiff()\n   *\n   * @param[in] data  Residual data\n   * @param[in] x     State point\n   */\n  void calcDiff(const boost::shared_ptr<ResidualDataAbstract>& data, const Eigen::Ref<const VectorXs>& x);\n\n  /**\n   * @brief Return the state\n   */\n  const boost::shared_ptr<StateAbstract>& get_state() const;\n\n  /**\n   * @brief Return the dimension of the residual vector\n   */\n  std::size_t get_nr() const;\n\n  /**\n   * @brief Return the dimension of the control input\n   */\n  std::size_t get_nu() const;\n\n  /**\n   * @brief Return true if the residual function depends on q\n   */\n  bool get_q_dependent() const;\n\n  /**\n   * @brief Return true if the residual function depends on v\n   */\n  bool get_v_dependent() const;\n\n  /**\n   * @brief Return true if the residual function depends on u\n   */\n  bool get_u_dependent() const;\n\n  /**\n   * @brief Print information on the residual model\n   */\n  template <class Scalar>\n  friend std::ostream& operator<<(std::ostream& os, const ResidualModelAbstractTpl<Scalar>& model);\n\n  /**\n   * @brief Print relevant information of the residual model\n   *\n   * @param[out] os  Output stream object\n   */\n  virtual void print(std::ostream& os) const;\n\n protected:\n  boost::shared_ptr<StateAbstract> state_;  //!< State description\n  std::size_t nr_;                          //!< Residual vector dimension\n  std::size_t nu_;                          //!< Control dimension\n  VectorXs unone_;                          //!< No control vector\n  bool q_dependent_;                        //!< Label that indicates if the residual function depends on q\n  bool v_dependent_;                        //!< Label that indicates if the residual function depends on v\n  bool u_dependent_;                        //!< Label that indicates if the residual function depends on u\n};\n\ntemplate <typename _Scalar>\nstruct ResidualDataAbstractTpl {\n  EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n\n  typedef _Scalar Scalar;\n  typedef MathBaseTpl<Scalar> MathBase;\n  typedef DataCollectorAbstractTpl<Scalar> DataCollectorAbstract;\n  typedef typename MathBase::VectorXs VectorXs;\n  typedef typename MathBase::MatrixXs MatrixXs;\n\n  template <template <typename Scalar> class Model>\n  ResidualDataAbstractTpl(Model<Scalar>* const model, DataCollectorAbstract* const data)\n      : shared(data),\n        r(model->get_nr()),\n        Rx(model->get_nr(), model->get_state()->get_ndx()),\n        Ru(model->get_nr(), model->get_nu()) {\n    r.setZero();\n    Rx.setZero();\n    Ru.setZero();\n  }\n  virtual ~ResidualDataAbstractTpl() {}\n\n  DataCollectorAbstract* shared;  //!< Shared data allocated by the action model\n  VectorXs r;                     //!< Residual vector\n  MatrixXs Rx;                    //!< Jacobian of the residual vector with respect the state\n  MatrixXs Ru;                    //!< Jacobian of the residual vector with respect the control\n};\n\n}  // namespace crocoddyl\n\n/* --- Details -------------------------------------------------------------- */\n/* --- Details -------------------------------------------------------------- */\n/* --- Details -------------------------------------------------------------- */\n#include \"crocoddyl/core/residual-base.hxx\"\n\n#endif  // CROCODDYL_CORE_RESIDUAL_BASE_HPP_\n", "meta": {"hexsha": "d17b1bf45365da4dc708406c97182b4c58ff8f12", "size": 8477, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/crocoddyl/core/residual-base.hpp", "max_stars_repo_name": "longhathuc/crocoddyl", "max_stars_repo_head_hexsha": "07a35d9c2d97f443c3e3665d33e80dae0720af9b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 322.0, "max_stars_repo_stars_event_min_datetime": "2019-06-04T12:04:00.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T14:37:44.000Z", "max_issues_repo_path": "include/crocoddyl/core/residual-base.hpp", "max_issues_repo_name": "longhathuc/crocoddyl", "max_issues_repo_head_hexsha": "07a35d9c2d97f443c3e3665d33e80dae0720af9b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 954.0, "max_issues_repo_issues_event_min_datetime": "2019-09-02T10:07:27.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T16:14:25.000Z", "max_forks_repo_path": "include/crocoddyl/core/residual-base.hpp", "max_forks_repo_name": "longhathuc/crocoddyl", "max_forks_repo_head_hexsha": "07a35d9c2d97f443c3e3665d33e80dae0720af9b", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 89.0, "max_forks_repo_forks_event_min_datetime": "2019-08-13T13:37:52.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T15:55:07.000Z", "avg_line_length": 38.8853211009, "max_line_length": 119, "alphanum_fraction": 0.6494042704, "num_tokens": 2056, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5660185498374789, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.3225471713744836}}
{"text": "/**\n *  Project: The Stock Libraries\n *\n *  File: globals.hpp\n *  Created: Jun 05, 2012\n *\n *  Author: Abhinav Sarje <abhinav.sarje@gmail.com>\n *\n *  Copyright (c) 2012-2017 Abhinav Sarje\n *  Distributed under the Boost Software License.\n *  See accompanying LICENSE file.\n */\n\n#ifndef __GLOBALS_HPP__\n#define __GLOBALS_HPP__\n\n#include <boost/array.hpp>\n#include <vector>\n#include <cmath>\n\n#include \"typedefs.hpp\"\n\n\nnamespace stock {\n\n\ttypedef struct vector2_t {\n\t\tboost::array <real_t, 2> vec_;\n\n\t\t/* constructors */\n\n\t\tvector2_t() {\n\t\t\tvec_[0] = 0; vec_[1] = 0;\n\t\t} // vector2_t()\n\n\t\tvector2_t(real_t a, real_t b) {\n\t\t\tvec_[0] = a; vec_[1] = b;\n\t\t} // vector2_t()\n\n\t\tvector2_t(vector2_t& a) {\n\t\t\tvec_[0] = a[0]; vec_[1] = a[1];\n\t\t} // vector2_t()\n\n\t\tvector2_t(const vector2_t& a) {\n\t\t\tvec_ = a.vec_;\n\t\t} // vector2_t()\n\n\t\t/* operators */\n\n\t\tvector2_t& operator=(const vector2_t& a) {\n\t\t\tvec_ = a.vec_;\n\t\t\treturn *this;\n\t\t} // operator=\n\n\t\tvector2_t& operator=(vector2_t& a) {\n\t\t\tvec_ = a.vec_;\n\t\t\treturn *this;\n\t\t} // operator=\n\n\t\treal_t& operator[](int i) {\n\t\t\treturn vec_[i];\n\t\t} // operator[]\n\t} vector2_t;\n\n\n\ttypedef struct vector3_t {\n\t\tboost::array <real_t, 3> vec_;\n\n\t\t/* constructors */\n\n\t\tvector3_t() {\n\t\t\tvec_[0] = 0; vec_[1] = 0; vec_[2] = 0;\n\t\t} // vector3_t()\n\n\t\tvector3_t(real_t a, real_t b, real_t c) {\n\t\t\tvec_[0] = a; vec_[1] = b; vec_[2] = c;\n\t\t} // vector3_t()\n\n\t\tvector3_t(vector3_t& a) {\n\t\t\tvec_[0] = a[0]; vec_[1] = a[1]; vec_[2] = a[2];\n\t\t} // vector3_t()\n\n\t\tvector3_t(const vector3_t& a) {\n\t\t\tvec_ = a.vec_;\n\t\t} // vector3_t()\n\n\t\t/* operators */\n\n\t\tvector3_t& operator=(const vector3_t& a) {\n\t\t\tvec_ = a.vec_;\n\t\t\treturn *this;\n\t\t} // operator=\n\n\t\tvector3_t& operator=(vector3_t& a) {\n\t\t\tvec_ = a.vec_;\n\t\t\treturn *this;\n\t\t} // operator=\n\n\t\treal_t& operator[](int i) {\n\t\t\treturn vec_[i];\n\t\t} // operator[]\n\n\t\tvector3_t operator+(int toadd) {\n\t\t\treturn vector3_t(vec_[0] + toadd, vec_[1] + toadd, vec_[2] + toadd);\n\t\t} // operator+()\n\n\t\tvector3_t operator+(vector3_t toadd) {\n\t\t\treturn vector3_t(vec_[0] + toadd[0], vec_[1] + toadd[1], vec_[2] + toadd[2]);\n\t\t} // operator+()\n\n\t\tvector3_t operator-(int tosub) {\n\t\t\treturn vector3_t(vec_[0] - tosub, vec_[1] - tosub, vec_[2] - tosub);\n\t\t} // operator-()\n\n\t\tvector3_t operator-(vector3_t tosub) {\n\t\t\treturn vector3_t(vec_[0] - tosub[0], vec_[1] - tosub[1], vec_[2] - tosub[2]);\n\t\t} // operator-()\n\n\t\tvector3_t operator/(vector3_t todiv) {\n\t\t\treturn vector3_t(vec_[0] / todiv[0], vec_[1] / todiv[1], vec_[2] / todiv[2]);\n\t\t} // operator/()\n\t} vector3_t;\n\n\n\ttypedef struct matrix3x3_t {\n\t\ttypedef boost::array<real_t, 3> mat3_t;\n\t\tmat3_t mat_[3];\n\n\t\t/* constructors */\n\n\t\tmatrix3x3_t() {\n\t\t\tfor(int i = 0; i < 3; ++ i)\n\t\t\t\tfor(int j = 0; j < 3; ++ j)\n\t\t\t\t\tmat_[i][j] = 0.0;\n\t\t} // matrix3x3_t()\n\n\t\tmatrix3x3_t(const matrix3x3_t& a) {\n\t\t\tmat_[0] = a.mat_[0];\n\t\t\tmat_[1] = a.mat_[1];\n\t\t\tmat_[2] = a.mat_[2];\n\t\t} // matrix3x3_t\n\n\t\t/* operators */\n\n\t\tmat3_t& operator[](unsigned int index) {\n\t\t\treturn mat_[index];\n\t\t} // operator[]()\n\n\t\tmat3_t& operator[](int index) {\n\t\t\treturn mat_[index];\n\t\t} // operator[]()\n\n\t\tmatrix3x3_t& operator=(matrix3x3_t& a) {\n\t\t\tfor(int i = 0; i < 3; ++ i)\n\t\t\t\tfor(int j = 0; j < 3; ++ j)\n\t\t\t\t\tmat_[i][j] = a[i][j];\n\t\t\treturn *this;\n\t\t} // operstor=()\n\n\t\tmatrix3x3_t operator+(int toadd) {\n\t\t\tmatrix3x3_t sum;\n\t\t\tfor(int i = 0; i < 3; ++ i)\n\t\t\t\tfor(int j = 0; j < 3; ++ j)\n\t\t\t\t\tsum.mat_[i][j] = mat_[i][j] + toadd;\n\t\t\treturn sum;\n\t\t} // operator+()\n\n\t\tmatrix3x3_t operator+(matrix3x3_t& toadd) {\n\t\t\tmatrix3x3_t sum;\n\t\t\tfor(int i = 0; i < 3; ++ i)\n\t\t\t\tfor(int j = 0; j < 3; ++ j)\n\t\t\t\t\tsum.mat_[i][j] = mat_[i][j] + toadd[i][j];\n\t\t\treturn sum;\n\t\t} // operator+()\n\n\t\tmatrix3x3_t operator*(int tomul) {\n\t\t\tmatrix3x3_t prod;\n\t\t\tfor(int i = 0; i < 3; ++ i)\n\t\t\t\tfor(int j = 0; j < 3; ++ j)\n\t\t\t\t\tprod.mat_[i][j] = mat_[i][j] * tomul;\n\t\t\treturn prod;\n\t\t} // operator*()\n\n\t\tmatrix3x3_t operator*(matrix3x3_t& tomul) {\n\t\t\tmatrix3x3_t prod;\n\t\t\tfor(int i = 0; i < 3; ++ i)\n\t\t\t\tfor(int j = 0; j < 3; ++ j)\n\t\t\t\t\tprod.mat_[i][j] = mat_[i][j] * tomul[i][j];\n\t\t\treturn prod;\n\t\t} // operator*()\n\n\t} matrix3x3_t;\n\n} // namespace stock\n\n#endif /* __GLOBALS_HPP__ */\n", "meta": {"hexsha": "26adb3d9943b8ee8a33b935fe87e6ad5d0233046", "size": 4140, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "image/globals.hpp", "max_stars_repo_name": "mywoodstock/woo", "max_stars_repo_head_hexsha": "7a6e39b2914ec8ff5bf52c3aa5217214532390e4", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2017-05-09T14:25:18.000Z", "max_stars_repo_stars_event_max_datetime": "2017-05-09T14:25:18.000Z", "max_issues_repo_path": "image/globals.hpp", "max_issues_repo_name": "mywoodstock/woo", "max_issues_repo_head_hexsha": "7a6e39b2914ec8ff5bf52c3aa5217214532390e4", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "image/globals.hpp", "max_forks_repo_name": "mywoodstock/woo", "max_forks_repo_head_hexsha": "7a6e39b2914ec8ff5bf52c3aa5217214532390e4", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.1224489796, "max_line_length": 80, "alphanum_fraction": 0.5724637681, "num_tokens": 1573, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5698526514141571, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.3225471630310558}}
{"text": "#include <algorithm>\n#include <fstream>\n#include <sstream>\n\n#include <boost/archive/text_iarchive.hpp>\n#include <boost/archive/text_oarchive.hpp>\n\n#include <iostream>\n\n#include \"Indices.hxx\"\n#include \"Tensor.hxx\"\n#include \"Epsilon.hxx\"\n#include \"Eta.hxx\"\n#include \"Scalar.hxx\"\n#include \"LinearAlgebra.hxx\"\n#include \"Algorithms.hxx\"\n\nstd::string printTree (std::unique_ptr<Tree<Node>> const & tree) {\n  if (tree->isEmpty()) {\n    return printForest (tree->forest, 0);\n  } else {\n    std::stringstream ss;\n    ss << tree->node->print();\n    ss << \"\\n\";\n    ss << printForest (tree->forest, 1);\n    return ss.str();\n  }\n}\n\nstd::string printTreeMaple (std::unique_ptr<Tree<Node>> const & tree) {\n  std::stringstream ss;\n  auto it = tree->firstLeaf();\n\n  bool first = true;\n  while (it != nullptr) {\n    if (first) {\n      first = false;\n    } else {\n      ss << \"+ \";\n    }\n    ss << printBranchMaple (it->getBranch());\n    ss << std::endl;\n    \n    it = it->nextLeaf();\n  }\n\n  return ss.str();\n}\n\nstd::string printBranchMaple (std::vector <Node *> const & branch) {\n  assert (branch.size() > 1);\n  std::stringstream ss;\n  \n  ss << branch.back()->printMaple();\n\n  for (size_t counter = 0; counter < branch.size() - 1; ++counter) {\n    ss << \" * \";\n    ss << branch[counter]->printMaple();\n  }\n\n  return ss.str();\n}\n\nstd::string printForest (Forest<Node> const & f, size_t depth) {\n  std::stringstream ss;\n  std::for_each (f.cbegin(), f.cend(),\n    [depth, &ss] (auto const & t) {\n      for (size_t counter = 0; counter < depth; ++counter) {\n        ss << \"\\t\";\n      }\n      ss << t->node->print();\n      ss << \"\\n\";\n      ss << printForest (t->forest, depth + 1);\n    });\n  return ss.str();\n}\n\nstd::unique_ptr<Tree<Node>> copyTree (std::unique_ptr<Tree<Node>> const & tree) {\n  auto new_tree = std::make_unique<Tree<Node>>();\n  if (!tree->isEmpty()) {\n    new_tree->node = tree->node->clone();\n  }\n  new_tree->forest = Forest<Node>();\n  new_tree->forest.reserve(tree->forest.size());\n\n  std::for_each(tree->forest.cbegin(), tree->forest.cend(),\n    [&new_tree,&tree] (auto const & t) {\n      new_tree->forest.emplace_back(std::move(copyTree(t)));\n      new_tree->forest.back()->parent = new_tree.get();\n    });\n\n  return new_tree;\n}\n\nvoid multiplyTree (std::unique_ptr<Tree<Node>> & tree, mpq_class const & factor) {\n  auto it = tree->firstLeaf();\n\n  while (it != nullptr) {\n    it->node->multiply(factor);\n    it = it->nextLeaf();\n  }\n}\n\nvoid exchangeTensorIndices (std::unique_ptr<Tree<Node>> & tree, std::map<char, char> const & exchange_map) {\n  if (!tree->isEmpty()) {\n    tree->node->exchangeTensorIndices(exchange_map);\n  }\n\n  std::for_each(tree->forest.begin(), tree->forest.end(),\n    [&exchange_map] (auto & t) {\n      exchangeTensorIndices (t, exchange_map);\n    });\n}\n\nvoid exchangeSymmetrizeTree (std::unique_ptr<Tree<Node>> & tree, std::map<char, char> const & exchange_map, int parity) {\n  multiplyTree(tree, mpq_class(1, 2));\n\n  auto new_tree = copyTree(tree);\n\n  mpq_class factor = (parity < 0 ? -1 : 1);\n  multiplyTree (new_tree, factor);\n\n  exchangeTensorIndices (new_tree, exchange_map);\n\n  applyTensorSymmetries (new_tree);\n  removeEmptyBranches(new_tree);\n\n  sortTreeAndMerge (tree, new_tree);\n  removeEmptyBranches(tree);\n}\n\nvoid multiExchangeSymmetrizeTree (std::unique_ptr<Tree<Node>> & tree, std::vector<std::pair<std::map<char, char>, int>> const & exchange_map_set) {\n  multiplyTree (tree, mpq_class(1, exchange_map_set.size() + 1));\n\n  auto tree_copy = copyTree (tree);\n\n  std::for_each (exchange_map_set.cbegin(), exchange_map_set.cend(),\n    [&tree_copy,&tree] (auto const & p) {\n      auto new_tree = copyTree (tree_copy);\n      auto exchange_map = p.first;\n      int parity = p.second;\n      mpq_class factor = (parity < 0 ? -1 : 1);\n      multiplyTree (new_tree, factor);\n      exchangeTensorIndices (new_tree, exchange_map);\n      applyTensorSymmetries (new_tree);\n      removeEmptyBranches (new_tree);\n      sortTreeAndMerge (tree, new_tree);\n      removeEmptyBranches (tree);\n    });\n}\n\nvoid redefineScalarsSym (std::unique_ptr<Tree<Node>> & tree) {\n  auto leaf_it = tree->firstLeaf();\n  std::map<size_t, std::pair<size_t, mpq_class>> substitution_map;\n  size_t var_counter = 0;\n  \n  while (leaf_it != nullptr) {\n    Scalar * scalar = static_cast<Scalar *>(leaf_it->node.get());\n    auto first = scalar->getCoefficientMap()->begin();\n    auto it = substitution_map.find(first->first);\n    if (it == substitution_map.end()) {\n      std::unique_ptr<Node> new_scalar = std::make_unique<Scalar>(++var_counter, first->second);\n      std::swap(new_scalar, leaf_it->node);\n      substitution_map[first->first] = std::make_pair(var_counter, first->second);\n    } else {\n      std::unique_ptr<Node> new_scalar = std::make_unique<Scalar>(it->second.first, first->second);\n      std::swap(new_scalar, leaf_it->node);\n    }\n\n    leaf_it = leaf_it->nextLeaf();\n  }\n}\n\nvoid sortBranch (std::vector<Node *> & branch) {\n  std::sort (branch.begin(), branch.end(),\n    [] (auto & n, auto & m) {\n      return (*n) < m;\n    });\n}\n\nvoid sortForest (Forest<Node> & forest) {\n  std::sort (forest.begin(), forest.end(),\n    [] (auto const & n, auto const & m) {\n      return *(n->node) < m->node.get();\n    });\n}\n\nvoid sortTree (std::unique_ptr<Tree<Node>> & tree) {\n  sortForest (tree->forest);\n\n  std::for_each(tree->forest.begin(), tree->forest.end(),\n    [] (auto & t) {\n      sortTree (t);\n    });\n}\n\nvoid sortTreeAndMerge (std::unique_ptr<Tree<Node>> & dst, std::unique_ptr<Tree<Node>> const & src) {\n  auto src_it = src->firstLeaf();\n\n  while (src_it != nullptr) {\n    auto branch = src_it->getBranch();\n    sortBranch (branch);\n\n    insertBranch (dst, branch);\n\n    src_it = src_it->nextLeaf();\n  }\n}\n\nvoid mergeTrees (std::unique_ptr<Tree<Node>> & dst, std::unique_ptr<Tree<Node>> const & src) {\n  auto src_it = src->firstLeaf();\n\n  while (src_it != nullptr) {\n    auto branch = src_it->getBranch();\n\n    insertBranch (dst, branch);\n\n    src_it = src_it->nextLeaf();\n  }\n}\n\nvoid canonicalizeTree (std::unique_ptr<Tree<Node>> & tree) {\n  applyTensorSymmetries (tree);\n\n  auto ret = std::make_unique<Tree<Node>>();\n  \n  sortTreeAndMerge (ret, tree);\n  removeZeroScalars (ret);\n  removeEmptyBranches (ret);\n  sortTree (ret);\n\n  std::swap (ret, tree);\n}\n\nvoid insertBranch (std::unique_ptr<Tree<Node>> & dst, std::vector<Node *> & branch, size_t const node_number) {\n  if (branch.size() == node_number) {\n    return;\n  }\n\n  bool const branch_node_is_scalar = (typeid(*(branch[node_number])) == typeid(Scalar));\n\n  auto node_it = std::find_if (dst->forest.begin(), dst->forest.end(),\n    [&branch,branch_node_is_scalar,node_number] (auto & t) {\n      if (t->node == nullptr) {\n        return false;\n      } else if (branch_node_is_scalar && (typeid(*(t->node)) == typeid(Scalar))) {\n        return true;\n      } else if (t->node->equals(branch[node_number])){\n        return true;\n      } else {\n        return false;\n      }\n    });\n\n  if (node_it == dst->forest.end()) {\n    dst->forest.push_back (std::make_unique<Tree<Node>>());\n    dst->forest.back()->node = branch[node_number]->clone();\n    dst->forest.back()->parent = dst.get();\n    insertBranch(dst->forest.back(), branch, node_number + 1);\n  } else if (branch_node_is_scalar && (typeid(*((*node_it)->node)) == typeid(Scalar))) {\n    static_cast<Scalar *>((*node_it)->node.get())->addOther(static_cast<Scalar *>(branch[node_number]));\n    insertBranch (*node_it, branch, node_number + 1);\n  } else {\n    insertBranch (*node_it, branch, node_number + 1);\n  }\n}\n\nvoid removeEmptyBranches (std::unique_ptr<Tree<Node>> & tree) {\n  std::for_each(tree->forest.begin(), tree->forest.end(),\n    [] (auto & t) {\n      removeEmptyBranches (t);\n    });\n\n  tree->forest.erase(std::remove_if(tree->forest.begin(), tree->forest.end(),\n    [] (auto & t) {\n\n      if (!t->isEmpty()) {\n        auto is_node_scalar = (typeid(*(t->node)) == typeid(Scalar));\n        if (is_node_scalar && static_cast<Scalar *>(t->node.get())->isZero()) {\n          return true;\n        } else if (!is_node_scalar && t->isLeaf()) {\n          return true;\n        }\n      } else {\n        if (t->isLeaf()) {\n          return true;\n        }\n      }\n\n  return false;\n\n  }), tree->forest.end());\n}\n\nvoid removeZeroScalars (std::unique_ptr<Tree<Node>> & tree) {\n  auto it = tree->firstLeaf();\n\n  while (it != nullptr) {\n    static_cast<Scalar *>(it->node.get())->removeZeros();\n    it = it->nextLeaf();\n  }\n}\n\nbool isTreeSorted (std::unique_ptr<Tree<Node>> const & tree) {\n  return (std::is_sorted(tree->forest.cbegin(), tree->forest.cend(),\n    [] (auto const & a, auto const & b) {\n      return *(a->node) < b->node.get();\n    }) && std::all_of(tree->forest.cbegin(), tree->forest.cend(),\n      [] (auto const & t) {\n        return isTreeSorted (t);\n      }));\n}\n\nstd::map<size_t, mpq_class> evaluateTree (std::unique_ptr<Tree<Node>> const & tree, std::map<char, char> const & eval_map, mpq_class prefactor) {\n  std::map<size_t, mpq_class> ret;\n\n  if (tree->isLeaf()) {\n    std::map<size_t, mpq_class> const * leaf_map = tree->node->getCoefficientMap();\n    std::for_each(leaf_map->cbegin(), leaf_map->cend(),\n      [&ret,&prefactor] (auto const & p) {\n        ret.insert(std::make_pair(p.first, prefactor * p.second));\n      });\n  } else {\n    if (!tree->isRoot()) {\n      prefactor *= static_cast<Tensor const *>(tree->node.get())->evaluate(eval_map);\n      if (prefactor == 0) {\n        return ret;\n      }\n    } \n\n    std::for_each(tree->forest.cbegin(), tree->forest.cend(),\n      [&ret, &eval_map, &prefactor] (auto const & t) {\n        auto _map = evaluateTree (t, eval_map, prefactor);\n        std::for_each(_map.cbegin(), _map.cend(),\n          [&ret] (auto const & a) {\n            auto it = ret.find(a.first);\n            if (it == ret.end()) {\n              ret.insert(std::make_pair(a.first, a.second));\n            } else {\n              it->second += a.second;\n              if (it->second == 0) {\n                ret.erase(it);\n              }\n            }\n          });\n      });\n  }\n\n  return ret;\n}\n\nvoid applyTensorSymmetries(std::unique_ptr<Tree<Node>> & tree, int parity) {\n  std::vector<Tree<Node>*> erase_vec;\n  std::for_each(tree->forest.begin(), tree->forest.end(),\n    [parity,&erase_vec] (auto & t) {\n      int new_parity = t->node->applyTensorSymmetries(parity);\n      if (new_parity == 0) {\n        erase_vec.push_back(t.get());\n      } else {\n        applyTensorSymmetries (t, new_parity);\n      }\n    });\n\n  tree->forest.erase(std::remove_if(tree->forest.begin(), tree->forest.end(),\n    [&erase_vec] (auto & t) {\n      return (std::find(erase_vec.begin(), erase_vec.end(), t.get()) != erase_vec.end());\n    }), tree->forest.end());\n}\n\nstd::map<size_t, size_t> getVariableMap (std::unique_ptr<Tree<Node>> const & tree) {\n  auto variables = getVariableSet(tree);\n  std::map<size_t, size_t> ret;\n  std::for_each(variables.cbegin(), variables.cend(),\n    [&ret,n=0] (auto const & v) mutable {\n      ret[v] = n++;\n    });\n  return ret;\n}\n\nstd::set<size_t> getVariableSet (std::unique_ptr<Tree<Node>> const & tree) {\n  std::set<size_t> ret;\n\n  auto leaf_it = tree->firstLeaf();\n\n  while (leaf_it != nullptr) {\n    ret.merge (leaf_it->node->getVariableSet());\n    leaf_it = leaf_it->nextLeaf();\n  }\n\n  return ret;\n}\n\nvoid shrinkForest (Forest<Node> & forest) {\n  forest.shrink_to_fit();\n  std::for_each(forest.begin(), forest.end(),\n    [] (auto & t) {\n      t->forest.shrink_to_fit();\n    });\n}\n\nvoid substituteVariables (std::unique_ptr<Tree<Node>> & tree, std::map<size_t, size_t> const & subs_map) {\n  auto leaf_it = tree->firstLeaf();\n\n  while (leaf_it != nullptr) {\n    leaf_it->node->substituteVariables (subs_map);\n    leaf_it = leaf_it->nextLeaf();\n  }\n}\n\nvoid setVariablesToZero (std::unique_ptr<Tree<Node>> & tree, std::set<size_t> const & variables) {\n  auto leaf_it = tree->firstLeaf();\n\n  while (leaf_it != nullptr) {\n    leaf_it->node->removeVariables(variables);\n    leaf_it = leaf_it->nextLeaf();\n  }\n}\n\nvoid solveNumerical (std::vector<std::pair<std::unique_ptr<Tree<Node>> &, std::function< void (std::unique_ptr<Tree<Node>> const &, std::set<std::map<size_t, mpq_class>> &)>>> const & equations) {\n  std::set<std::map<size_t, mpq_class>> eval_res_set;\n  std::set<size_t> var_set;\n\n  std::for_each (equations.cbegin(), equations.cend(),\n      [&eval_res_set,&var_set] (auto const & eq) {\n        auto & fun = eq.second;\n        auto & tree = eq.first;\n\n        var_set.merge (getVariableSet (tree));\n        fun (tree, eval_res_set);\n      });\n\n    std::cout << \"number of equations : \" << eval_res_set.size() << std::endl;\n    \n    std::cout << \"number of coefficients : \" << var_set.size() << std::endl;\n  \n    std::map<size_t, size_t> var_map;\n    std::set<std::pair<std::pair<size_t, size_t>, mpq_class>> eval_res_mat;\n    std::set<std::pair<std::pair<size_t, size_t>, mpq_class>> eval_res_mat_mapped;\n  \n    std::for_each(eval_res_set.cbegin(), eval_res_set.cend(),\n      [row_counter=0,&eval_res_mat] (auto const & m) mutable {\n        std::for_each(m.cbegin(), m.cend(),\n          [&row_counter,&eval_res_mat] (auto const & p) {\n            eval_res_mat.insert(std::make_pair(std::make_pair(row_counter, p.first), p.second));\n          }); \n        ++row_counter; \n      }); \n  \n    eval_res_set.clear();\n  \n    std::for_each(eval_res_mat.cbegin(), eval_res_mat.cend(),\n      [&eval_res_mat_mapped,&var_map,var=0] (auto const & v) mutable {\n        auto it = var_map.find(v.first.second);\n        if (it == var_map.end()) {\n          var_map.insert(std::make_pair(v.first.second, var));\n          ++var;\n        }\n        eval_res_mat_mapped.insert(std::make_pair(std::make_pair(v.first.first, var_map.at(v.first.second)), v.second));\n      });\n  \n    eval_res_mat.clear();\n\n  solveLinearSystem (eval_res_mat_mapped, eval_res_mat_mapped.rbegin()->first.first + 1, var_map.size());\n}\n\nvoid reduceNumerical (std::unique_ptr<Tree<Node>> & tree, std::function< void (std::unique_ptr<Tree<Node>> const &, std::set<std::map<size_t, mpq_class>> &)> fun) {\n  std::set<std::map<size_t, mpq_class>> eval_res_set;\n  \n  fun (tree, eval_res_set);\n\n  std::set<size_t> var_set = getVariableSet (tree);\n  std::map<size_t, size_t> var_map;\n  std::set<size_t> erase_set = var_set;\n  std::set<std::pair<std::pair<size_t, size_t>, mpq_class>> eval_res_mat;\n  std::set<std::pair<std::pair<size_t, size_t>, mpq_class>> eval_res_mat_mapped;\n\n  std::for_each(eval_res_set.cbegin(), eval_res_set.cend(),\n    [row_counter=0,&eval_res_mat] (auto const & m) mutable {\n      std::for_each(m.cbegin(), m.cend(),\n        [&row_counter,&eval_res_mat] (auto const & p) {\n          eval_res_mat.insert(std::make_pair(std::make_pair(row_counter, p.first), p.second));\n        }); \n      ++row_counter; \n    }); \n\n  eval_res_set.clear();\n\n  std::for_each(eval_res_mat.cbegin(), eval_res_mat.cend(),\n    [&eval_res_mat_mapped,&var_map,&erase_set,var=0] (auto const & v) mutable {\n      erase_set.erase(v.first.second);\n      auto it = var_map.find(v.first.second);\n      if (it == var_map.end()) {\n        var_map.insert(std::make_pair(v.first.second, var));\n        ++var;\n      }\n      eval_res_mat_mapped.insert(std::make_pair(std::make_pair(v.first.first, var_map.at(v.first.second)), v.second));\n    });\n\n  eval_res_mat.clear();\n\n  std::cout << \"These equations contain \" << var_map.size() << \" variables.\" << std::endl;\n  std::cout << \"That is, \" << erase_set.size() << \" variables do not contribute at all.\" << std::endl;\n  std::cout << std::endl;\n  std::cout << \"Computing LU decomposition of the linear system using Eigen subroutines ...\" << std::endl;\n\n  auto erase_set_2_mapped = findDependentVariables (eval_res_mat_mapped, eval_res_mat_mapped.rbegin()->first.first + 1, var_map.size());\n  std::cout << \"... done! \" << erase_set_2_mapped.size() << \" variables are dependent.\" << std::endl;\n\n  eval_res_mat_mapped.clear();\n\n  std::map<size_t, size_t> var_rmap;\n  std::transform (var_map.cbegin(), var_map.cend(), std::inserter(var_rmap, var_rmap.begin()),\n    [] (auto const & p) {\n      return std::make_pair(p.second, p.first);\n    });\n\n  std::set<size_t> erase_set_2;\n  std::transform(erase_set_2_mapped.cbegin(), erase_set_2_mapped.cend(), std::inserter(erase_set_2, erase_set_2.begin()),\n    [&var_rmap] (auto const & v) {\n      return var_rmap.at(v);\n    });\n\n  erase_set_2_mapped.clear();\n\n  erase_set.merge(erase_set_2);\n  erase_set_2.clear();\n\n  std::cout << \"Removing all \" << erase_set.size() << \" variables from the ansatz.\" << std::endl;\n\n  setVariablesToZero (tree, erase_set);\n  removeEmptyBranches (tree);\n\n  var_set = getVariableSet (tree);\n\n  var_map.clear();\n\n  std::transform (var_set.cbegin(), var_set.cend(), std::inserter (var_map, var_map.begin()),\n    [counter=0] (auto const & v) mutable {\n      return std::make_pair (v, ++counter);\n    });\n\n  substituteVariables (tree, var_map);\n}\n\nbool compareTrees (std::unique_ptr<Tree<Node>> const & tree1, std::unique_ptr<Tree<Node>> const & tree2) {\n  bool nodes_equal = false;\n  if (tree1->isEmpty() != tree2->isEmpty()) {\n    nodes_equal = false;\n  } else if (tree1->isEmpty() && tree2->isEmpty()) {\n    nodes_equal = true;\n  } else {\n    nodes_equal = tree1->node->equals(tree2->node.get());\n  }\n\n  return (nodes_equal && std::equal(tree1->forest.cbegin(), tree1->forest.cend(),\n                                    tree2->forest.cbegin(), tree2->forest.cend(),\n                                    [] (auto const & t1, auto const & t2) {\n                                      return compareTrees (t1, t2);\n                                    }));\n}\n\nvoid contractTreeWithEta (std::unique_ptr<Tree<Node>> & tree, char i1, char i2) {\n  std::vector<std::unique_ptr<Tree<Node>>> new_forest;\n  std::for_each (tree->forest.begin(), tree->forest.end(),\n    [i1, i2, &new_forest] (auto & t) {\n      auto parent = t->parent;\n      auto forest = contractTreeWithEtaInner (t, i1, i2);\n      std::for_each (forest.begin(), forest.end(),\n        [&t,parent] (auto & t2) {\n          t2->parent = parent;\n        });\n      new_forest.insert (new_forest.end(), std::make_move_iterator (forest.begin()), std::make_move_iterator (forest.end()));\n    });\n  std::swap (tree->forest, new_forest);\n}\n\nForest<Node> contractTreeWithEtaInner (std::unique_ptr<Tree<Node>> & tree, char i1, char i2) {\n  tree->parent = nullptr;\n  Forest<Node> ret;\n  auto & node_type = typeid (*(tree->node));\n  if (node_type == typeid (Epsilon)) {\n    bool const contains_i1 = static_cast<Epsilon *>(tree->node.get())->containsIndex (i1);\n    bool const contains_i2 = static_cast<Epsilon *>(tree->node.get())->containsIndex (i2);\n    if (contains_i1) {\n      if (contains_i2) {\n        return ret;\n      } else {\n        auto _tree = std::make_unique<Tree<Node>>();\n        _tree->forest.emplace_back (std::move(tree));\n        return std::move(eliminateSecondEta(_tree, i1, i2)->forest);\n      }\n    } else {\n      if (contains_i2) {\n        auto _tree = std::make_unique<Tree<Node>>();\n        _tree->forest.emplace_back (std::move(tree));\n        return std::move(eliminateSecondEta(_tree, i2, i1)->forest);\n      } else {\n        contractTreeWithEta (tree, i1, i2);\n        ret.emplace_back (std::move(tree));\n        return ret;\n      }\n    }\n  } else if (node_type == typeid (Eta)) {\n    bool const contains_i1 = static_cast<Eta *>(tree->node.get())->containsIndex (i1);\n    bool const contains_i2 = static_cast<Eta *>(tree->node.get())->containsIndex (i2);\n    if (contains_i1) {\n      if (contains_i2) {\n        multiplyTree (tree, mpq_class (4, 1));\n        std::for_each (tree->forest.begin(), tree->forest.end(),\n          [&ret] (auto & t) {\n            ret.emplace_back(std::move(t));\n          });\n        return ret;\n      } else {\n        auto _tree = std::make_unique<Tree<Node>>();\n        _tree->forest.emplace_back (std::move(tree));\n        return std::move(eliminateSecondEta(_tree, i1, i2)->forest);\n      }\n    } else {\n      if (contains_i2) {\n        auto _tree = std::make_unique<Tree<Node>>();\n        _tree->forest.emplace_back (std::move(tree));\n        return std::move(eliminateSecondEta(_tree, i2, i1)->forest);\n      } else {\n        contractTreeWithEta (tree, i1, i2);\n        ret.emplace_back (std::move(tree));\n        return ret;\n      }\n    }\n  } else {\n    contractTreeWithEta (tree, i1, i2);\n    ret.emplace_back (std::move(tree));\n    return ret;\n  }\n}\n\nstd::unique_ptr<Tree<Node>> eliminateSecondEta (std::unique_ptr<Tree<Node>> & tree, char i1, char i2) {\n  auto ret = std::make_unique<Tree<Node>>();\n  auto it = tree->firstLeaf ();\n\n  while (it != nullptr) {\n    auto branch = it->getBranch();\n    assert (branch[0] != nullptr);\n\n    auto eta_it = std::find_if (branch.cbegin(), branch.cend(),\n      [i2] (auto const & n) {\n        return (n != nullptr &&\n                typeid (*n) == typeid (Eta) &&\n                static_cast<Eta *>(n)->containsIndex (i2));\n      });\n    char i_new = static_cast<Eta *>(*eta_it)->getOther(i2);\n\n    branch.erase (eta_it);\n    auto node_cpy = branch[0]->clone();\n    branch[0] = node_cpy.get();\n    static_cast<Tensor *>(branch[0])->exchangeTensorIndices({{i1, i_new}});\n\n    sortBranch (branch);\n    insertBranch (ret, branch);\n\n    it = it->nextLeaf();\n  }\n\n  return ret;\n}\n\nvoid contractTreeWithEpsilon3 (std::unique_ptr<Tree<Node>> & tree, char m, char i1, char i2, char i3) {\n  auto new_tree = std::make_unique<Tree<Node>> ();\n  auto it = tree->firstLeaf ();\n\n  while (it != nullptr) {\n    auto branch = it->getBranch ();\n    auto & type = typeid(*(branch[0]));\n    if (type == typeid(Eta)) {\n      if (std::any_of (branch.cbegin(), branch.cend(),\n           [i1, i2, i3] (auto const & n) {\n             if (typeid (*n) == typeid (Eta)) {\n               auto eta = static_cast<Eta *>(n);\n               int count = 0;\n               if (eta->containsIndex(i1)) { ++count; }\n               if (eta->containsIndex(i2)) { ++count; }\n               if (eta->containsIndex(i3)) { ++count; }\n               if (count == 2) {\n                 return true;\n               } else {\n                 assert (count < 2);\n                 return false;\n               }\n             } else {\n               return false;\n             }\n           })) {\n        // do nothing\n      } else {\n        std::vector<Node *> new_branch;\n        char j1 = 0;\n        char j2 = 0;\n        char j3 = 0;\n        new_branch.push_back (nullptr);\n        std::for_each (branch.begin(), branch.end(),\n            [&j1,&j2,&j3,i1,i2,i3,&new_branch] (auto n) {\n              if (typeid (*n) == typeid (Eta)) {\n                auto eta = static_cast<Eta *>(n);\n                if (eta->containsIndex(i1)) {\n                  assert (j1 == 0);\n                  j1 = eta->getOther (i1);\n                }\n                else if (eta->containsIndex(i2)) {\n                  assert (j2 == 0);\n                  j2 = eta->getOther (i2);\n                }\n                else if (eta->containsIndex(i3)) {\n                  assert (j3 == 0);\n                  j3 = eta->getOther(i3);\n                } else {\n                  new_branch.push_back (n);\n                }\n              } else {\n                new_branch.push_back (n);\n              }\n            });\n        assert (j1 != 0 && j2 != 0 && j3 != 0);\n        assert (branch.size() == new_branch.size() + 2);\n        std::unique_ptr<Node> epsilon = std::make_unique<Epsilon> (m, j1, j2, j3);\n        new_branch[0] = epsilon.get();\n        insertBranch (new_tree, new_branch);\n      }\n    } else if (type == typeid(Epsilon)) {\n      auto epsilon = static_cast<Epsilon *> (branch[0]);\n      auto mult_res = epsilon->multiplyWithOther3 (i1, i2, i3);\n      auto new_tree_2 = std::make_unique<Tree<Node>>();\n      new_tree_2->forest.emplace_back (std::make_unique<Tree<Node>>());\n      new_tree_2->forest[0]->node = std::make_unique<Eta>(m, std::get<1>(mult_res));\n      new_tree_2->forest[0]->parent = new_tree_2.get();\n      std::for_each (branch.cbegin() + 1, branch.cend(),\n          [&mult_res,&new_tree_2] (auto const & n) {\n            auto leaf = new_tree_2->firstLeaf();\n            if (typeid(*n) == typeid(Scalar)) {\n              auto scalar_clone = n->clone();\n              scalar_clone->multiply (std::get<0>(mult_res));\n              leaf->forest.emplace_back (std::make_unique<Tree<Node>>());\n              std::swap (leaf->forest[0]->node, scalar_clone);\n              leaf->forest[0]->parent = leaf;\n            } else if (typeid(*n) == typeid(Eta)) {\n              auto eta_clone = n->clone();\n              eta_clone->exchangeTensorIndices (std::get<2>(mult_res));\n              leaf->forest.emplace_back (std::make_unique<Tree<Node>>());\n              std::swap (leaf->forest[0]->node, eta_clone);\n              leaf->forest[0]->parent = leaf;\n            } else {\n              assert (false);\n            }\n          });\n      std::vector<char> indices_to_symmetrize;\n      indices_to_symmetrize.push_back (std::get<1>(mult_res));\n      std::transform (std::get<2>(mult_res).cbegin(), std::get<2>(mult_res).cend(),\n          std::back_inserter (indices_to_symmetrize), [] (auto const & p) { return p.second; });\n      auto to_sym_size = indices_to_symmetrize.size();\n      assert (to_sym_size > 0);\n      assert (to_sym_size < 5);\n      if (to_sym_size == 2) {\n        exchangeSymmetrizeTree (new_tree_2, {{indices_to_symmetrize[0], indices_to_symmetrize[1]},\n                                          {indices_to_symmetrize[1], indices_to_symmetrize[0]}}, -1);\n      } else if (to_sym_size == 3) {\n        auto & iv = indices_to_symmetrize;\n        multiExchangeSymmetrizeTree (new_tree_2, \n            {{{{iv[1], iv[2]}, {iv[2], iv[1]}}, -1},\n             {{{iv[0], iv[1]}, {iv[1], iv[0]}}, -1},\n             {{{iv[0], iv[1]}, {iv[1], iv[2]}, {iv[2], iv[0]}}, 1},\n             {{{iv[0], iv[2]}, {iv[1], iv[0]}, {iv[2], iv[1]}}, 1},\n             {{{iv[0], iv[2]}, {iv[2], iv[0]}}, -1}});\n      } else if (to_sym_size == 4) {\n        auto & iv = indices_to_symmetrize;\n        multiExchangeSymmetrizeTree (new_tree_2, \n            {{{{iv[2], iv[3]}, {iv[3], iv[2]}}, -1},                                  // 0 1 3 2\n             {{{iv[1], iv[2]}, {iv[2], iv[1]}}, -1},                                  // 0 2 1 3\n             {{{iv[1], iv[2]}, {iv[2], iv[3]}, {iv[3], iv[1]}}, 1},                   // 0 2 3 1\n             {{{iv[1], iv[3]}, {iv[2], iv[1]}, {iv[3], iv[2]}}, 1},                   // 0 3 1 2\n             {{{iv[1], iv[3]}, {iv[3], iv[1]}}, -1},                                  // 0 3 2 1\n             {{{iv[0], iv[1]}, {iv[1], iv[0]}}, -1},                                  // 1 0 2 3 \n             {{{iv[0], iv[1]}, {iv[1], iv[0]}, {iv[2], iv[3]}, {iv[3], iv[2]}}, 1},   // 1 0 3 2\n             {{{iv[0], iv[1]}, {iv[1], iv[2]}, {iv[2], iv[0]}}, 1},                   // 1 2 0 3\n             {{{iv[0], iv[1]}, {iv[1], iv[2]}, {iv[2], iv[3]}, {iv[3], iv[0]}}, -1},  // 1 2 3 0\n             {{{iv[0], iv[1]}, {iv[1], iv[3]}, {iv[2], iv[0]}, {iv[3], iv[2]}}, -1},  // 1 3 0 2\n             {{{iv[0], iv[1]}, {iv[1], iv[3]}, {iv[3], iv[0]}}, 1},                   // 1 3 2 0\n             {{{iv[0], iv[2]}, {iv[1], iv[0]}, {iv[2], iv[1]}}, 1},                   // 2 0 1 3\n             {{{iv[0], iv[2]}, {iv[1], iv[0]}, {iv[2], iv[3]}, {iv[3], iv[1]}}, -1},  // 2 0 3 1\n             {{{iv[0], iv[2]}, {iv[2], iv[0]}}, -1},                                  // 2 1 0 3\n             {{{iv[0], iv[2]}, {iv[2], iv[3]}, {iv[3], iv[0]}}, 1},                   // 2 1 3 0\n             {{{iv[0], iv[2]}, {iv[1], iv[3]}, {iv[2], iv[0]}, {iv[3], iv[1]}}, 1},   // 2 3 0 1\n             {{{iv[0], iv[2]}, {iv[1], iv[3]}, {iv[2], iv[1]}, {iv[3], iv[0]}}, -1},  // 2 3 1 0\n             {{{iv[0], iv[3]}, {iv[1], iv[0]}, {iv[2], iv[1]}, {iv[3], iv[2]}}, -1},  // 3 0 1 2\n             {{{iv[0], iv[3]}, {iv[1], iv[0]}, {iv[3], iv[1]}}, 1},                   // 3 0 2 1\n             {{{iv[0], iv[3]}, {iv[2], iv[0]}, {iv[3], iv[2]}}, 1},                   // 3 1 0 2\n             {{{iv[0], iv[3]}, {iv[3], iv[0]}}, -1},                                  // 3 1 2 0\n             {{{iv[0], iv[3]}, {iv[1], iv[2]}, {iv[2], iv[0]}, {iv[3], iv[1]}}, -1},  // 3 2 0 1\n             {{{iv[0], iv[3]}, {iv[1], iv[2]}, {iv[2], iv[1]}, {iv[3], iv[0]}}, 1}}); // 3 2 1 0\n      }\n      mergeTrees (new_tree, new_tree_2);\n    } else {\n      assert(false);\n    }\n    it = it->nextLeaf();\n  }\n\n  std::swap (tree, new_tree);\n}\n\nvoid saveTree (std::unique_ptr<Tree<Node>> const & tree, std::string const & filename) {\n  std::ofstream file {filename};\n  boost::archive::text_oarchive oa {file};\n  oa << tree;\n}\n\nstd::unique_ptr<Tree<Node>> loadTree (std::string const & filename) {\n  std::ifstream file {filename};\n  boost::archive::text_iarchive ia {file};\n  std::unique_ptr<Tree<Node>> tree;\n  ia >> tree;\n  return tree;\n}\n\nbool checkSaveAndLoad (std::unique_ptr<Tree<Node>> const & tree) {\n  saveTree (tree, \"check.prs\");\n  auto tree2 = loadTree (\"check.prs\");\n  return (compareTrees (tree, tree2));\n}\n\nvoid shiftVariables (std::unique_ptr<Tree<Node>> & tree, int i) {\n  auto it = tree->firstLeaf();\n\n  while (it != nullptr) {\n    assert (typeid(*(it->node.get())) == typeid(Scalar));\n    static_cast<Scalar *>(it->node.get())->shiftVariables (i);\n\n    it = it->nextLeaf();\n  }\n}\n\nvoid multiplyTreeWithEta (std::unique_ptr<Tree<Node>> & tree, char i1, char i2) {\n  auto new_tree = std::make_unique<Tree<Node>>();\n\n  new_tree->forest.emplace_back (std::make_unique<Tree<Node>>());\n  new_tree->forest.back()->parent = new_tree.get();\n  new_tree->forest.back()->node = std::make_unique<Eta> (i1, i2);\n\n  std::transform (tree->forest.begin(), tree->forest.end(), std::back_inserter (new_tree->forest.back()->forest),\n      [&new_tree] (auto & t) {\n        auto new_subtree = std::make_unique<Tree<Node>>();\n        std::swap (t, new_subtree);\n        new_subtree->parent = new_tree->forest.back().get();\n        return std::move (new_subtree);\n      });\n\n  std::swap (tree, new_tree);\n}\n", "meta": {"hexsha": "cbd1f1a9f5202b98305c1f6f35c70d8f4d4ef5ce", "size": 29985, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "src/Algorithms.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/Algorithms.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/Algorithms.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.9883313886, "max_line_length": 196, "alphanum_fraction": 0.5664832416, "num_tokens": 8678, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5774953797290153, "lm_q2_score": 0.5583269943353744, "lm_q1q2_score": 0.3224312596066668}}
{"text": "// json parser\n#include <boost/property_tree/json_parser.hpp>\n#include <boost/property_tree/ptree.hpp>\n#include <utility>\nnamespace pt = boost::property_tree;\n\n#include \"../MemoryKernel/MemoryKernelFactory.h\"\n#include \"PermittivityLorentz.h\"\n\nPermittivityLorentz::PermittivityLorentz(\n    double eps_inf, double omega_p, double omega_0,\n    std::shared_ptr<MemoryKernel> memory_kernel)\n    : eps_inf(eps_inf), omega_p(omega_p), omega_0(omega_0),\n      memory_kernel(std::move(memory_kernel)) {}\n\n// constructor for drude model from .json file\nPermittivityLorentz::PermittivityLorentz(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 == \"lorentz\");\n\n  // read parameters\n  this->eps_inf = root.get<double>(\"Permittivity.eps_inf\");\n  this->omega_p = root.get<double>(\"Permittivity.omega_p\");\n  this->omega_0 = root.get<double>(\"Permittivity.omega_0\");\n\n  this->memory_kernel =\n      MemoryKernelFactory::create(input_file, \"Permittivity.MemoryKernel\");\n}\n\n// calculate the permittivity\nstd::complex<double> PermittivityLorentz::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 = eps_inf - omega_p * omega_p /\n                         (omega_0 * omega_0 - omega * omega -\n                          I * omega * memory_kernel->calculate(omega));\n\n  return result;\n}\n\n// calculate the permittivity scaled by omega\nstd::complex<double>\nPermittivityLorentz::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 = eps_inf * omega - omega_p * omega_p * omega /\n                                 (omega_0 * omega_0 - omega * omega -\n                                  I * omega * memory_kernel->calculate(omega));\n\n  return result;\n}\n\nvoid PermittivityLorentz::print_info(std::ostream &stream) const {\n  stream << \"# PermittivityLorentz\\n#\\n\"\n         << \"# eps_inf = \" << eps_inf << \"\\n\"\n         << \"# omega_p = \" << omega_p << \"\\n\"\n         << \"# omega_0 = \" << omega_0 << \"\\n\";\n  memory_kernel->print_info(stream);\n}\n", "meta": {"hexsha": "f0ff40b23da2059c1b87f313cb69faa1049f7fe6", "size": 2374, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Permittivity/PermittivityLorentz.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/PermittivityLorentz.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/PermittivityLorentz.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": 32.0810810811, "max_line_length": 79, "alphanum_fraction": 0.6668070767, "num_tokens": 623, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5583269943353745, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.32243125148680374}}
{"text": "/*\nCopyright (c) 2016 Bastien Durix\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n*/\n\n\n/**\n *  \\brief 2D skeletonization\n *  \\author Bastien Durix\n */\n\n#include <boost/program_options.hpp>\n#include <time.h>\n#include <iostream>\n#include <iomanip>\n#include <chrono>\n\n#include <opencv2/core/core.hpp>\n#include <opencv2/highgui/highgui.hpp>\n#include <opencv2/imgproc/imgproc.hpp>\n#include <opencv2/imgcodecs/imgcodecs.hpp>\n\n#include <shape/DiscreteShape.h>\n#include <boundary/DiscreteBoundary.h>\n#include <skeleton/Skeletons.h>\n\n#include <algorithm/extractboundary/NaiveBoundary.h>\n#include <algorithm/skeletonization/propagation/SpherePropagation2D.h>\n#include <algorithm/skeletonization/voronoi/VoronoiSkeleton2D.h>\n#include <algorithm/skinning/Filling.h>\n#include <algorithm/evaluation/ReprojError.h>\n#include <algorithm/pruning/ScaleAxisTransform.h>\n#include <algorithm/pruning/LambdaMedialAxis.h>\n#include <algorithm/pruning/ThetaMedialAxis.h>\n\n#include <displayopencv/DisplayShapeOCV.h>\n#include <displayopencv/DisplayBoundaryOCV.h>\n#include <displayopencv/DisplaySkeletonOCV.h>\n\nstd::tuple<double,double,int,int> EvalSkel(const shape::DiscreteShape<2>::Ptr dissh,\n\t\t\t\t\t\t\t\t\t   const boundary::DiscreteBoundary<2>::Ptr disbnd,\n\t\t\t\t\t\t\t\t\t   const skeleton::GraphSkel2d::Ptr skel)\n{\n\tshape::DiscreteShape<2>::Ptr shp(new shape::DiscreteShape<2>(dissh->getWidth(),dissh->getHeight()));\n\talgorithm::skinning::Filling(shp,skel);\n\t\n\tdouble res = algorithm::evaluation::SymDiffArea(dissh,shp);\n\tdouble res2 = algorithm::evaluation::HausDist(skel,disbnd,dissh->getFrame());\n\t\n\tstd::list<unsigned int> lnod;\n\tskel->getAllNodes(lnod);\n\tunsigned int nbbr = 0;\n\tfor(std::list<unsigned int>::iterator it = lnod.begin(); it != lnod.end(); it++)\n\t{\n\t\tunsigned int deg = skel->getNodeDegree(*it);\n\t\tif(deg != 2)\n\t\t\tnbbr += deg;\n\t}\n\tnbbr /= 2;\n\tstd::tuple<double,double,int,int> result = std::make_tuple(res*100.0,res2,skel->getNbNodes(),nbbr);\n\t\n\treturn result;\n}\n\nint main(int argc, char** argv)\n{\n\tstd::string imgfile, fileskl, fileimg, filebnd;\n\tbool output = false;\n\tbool compare = false;\n\tbool eval = false;\n\tdouble alpha, noise;\n\n\tboost::program_options::options_description desc(\"OPTIONS\");\n\t\n\tdesc.add_options()\n\t\t(\"help\", \"Help message\")\n\t\t(\"imgfile\", boost::program_options::value<std::string>(&imgfile)->default_value(\"mask\"), \"Binary image file (*.png)\")\n\t\t(\"output\", boost::program_options::value<bool>(&output)->implicit_value(true), \"Returns output images\")\n\t\t(\"sigma\", boost::program_options::value<double>(&noise)->default_value(1.0), \"Shape noise (sigma parameter)\")\n\t\t(\"alpha\", boost::program_options::value<double>(&alpha)->default_value(2.1), \"Skeleton precision (alpha parameter)\")\n\t\t(\"fileimg\", boost::program_options::value<std::string>(&fileimg)->default_value(\"skelpropagortho\"), \"Skeleton img file\")\n\t\t(\"compare\", boost::program_options::value<bool>(&compare)->implicit_value(true), \"Compare result with pruning methods\")\n\t\t;\n\t\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\t\n\tif (vm.count(\"help\")) {\n\t\tstd::cout << desc << std::endl;\n\t\treturn 0;\n\t}\n\n\ttime_t start,end;\n\tdouble diff;\n\n\tcv::Mat shpimggray = cv::imread(imgfile,cv::ImreadModes::IMREAD_GRAYSCALE);\n\tcv::Mat shpimg;\n\tcv::threshold(shpimggray,shpimg,125,255,cv::THRESH_BINARY);\n\t\n\t// topological closure\n\tcv::Mat shpdil;\n\tcv::Mat element = cv::getStructuringElement(cv::MORPH_RECT,cv::Size(3,3),cv::Point(1,1));\n\tcv::dilate(shpimg,shpdil,element);\n\tcv::erode(shpdil,shpimg,element);\n\tshape::DiscreteShape<2>::Ptr dissh = shape::DiscreteShape<2>::Ptr(new shape::DiscreteShape<2>(shpimg.cols,shpimg.rows));\n\tcv::Mat cpymat(shpimg.rows,shpimg.cols,CV_8U,&dissh->getContainer()[0]);\n\tshpimg.copyTo(cpymat);\n\tcv::Mat image(shpimg.rows,shpimg.cols,CV_8UC3,cv::Scalar(255,255,255));\n\t\n\tdisplayopencv::DisplayDiscreteShape(dissh,image,dissh->getFrame(),cv::Scalar(0,0,255));\n\t\n\tboundary::DiscreteBoundary<2>::Ptr disbnd = algorithm::extractboundary::NaiveBoundary(dissh);\n\t\n\tauto start0 = std::chrono::steady_clock::now();\n\talgorithm::skeletonization::OptionsSphProp options(noise,alpha);\n\tskeleton::GraphSkel2d::Ptr grskelpropag = algorithm::skeletonization::SpherePropagation2D(disbnd,dissh,options);\n\tauto duration0 = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::steady_clock::now() - start0);\n\tstd::tuple<double,double,int,int> respropag = EvalSkel(dissh,disbnd,grskelpropag);\n\tint t0 = duration0.count();\n\tdouble A0 = std::get<0>(respropag); // sym area diff\n\tdouble H0 = std::get<1>(respropag); // Hausdorff dist\n\tint N0 = std::get<2>(respropag); // nb nodes\n\tint B0 = std::get<3>(respropag); // nb branches\n\n\tif(H0 > alpha)\n\t\tstd::cerr << \"Problem while computing propagation\" << std::endl;\n\t\n\tstd::cout << \"Propagation skeleton computation: \" << duration0.count() << \"ms.\" << std::endl;\n\n\tshape::DiscreteShape<2>::Ptr shppropag(new shape::DiscreteShape<2>(dissh->getWidth(),dissh->getHeight()));\n\talgorithm::skinning::Filling(shppropag,grskelpropag);\n\n\tcv::Mat imagepropag;\n\timage.copyTo(imagepropag);\n\tdisplayopencv::DisplayDiscreteShape(shppropag,imagepropag,shppropag->getFrame(),cv::Scalar(0,255,0));\n\tdisplayopencv::DisplayDiscreteBoundary(disbnd,imagepropag,dissh->getFrame(),cv::Scalar(0,0,0));\n\tdisplayopencv::DisplayGraphSkeleton(grskelpropag,imagepropag,dissh->getFrame(),cv::Scalar(255,0,0));\n\t\n\tif(output)\n\t{\n\t\tstd::ostringstream oss;\n\t\toss.setf( std::ios::fixed, std:: ios::floatfield );\n\t\toss.precision(1);\n\t\toss << fileimg << \".png\";\n\t\tcv::imwrite(oss.str(), imagepropag);\n\t}\n\n\tif(compare)\n\t{\n\t\tstd::cout.setf(std::ios_base::fixed, std::ios_base::floatfield);\n\t\tstd::cout.precision(2);\n\n\t\tauto startv = std::chrono::steady_clock::now();\n\t\tskeleton::GraphSkel2d::Ptr grskelvoro = algorithm::skeletonization::VoronoiSkeleton2d(disbnd);\n\t\tauto durationv = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::steady_clock::now() - startv);\n\t\tstd::tuple<double,double,int,int> resv = EvalSkel(dissh,disbnd,grskelvoro);\n\t\tint tv = durationv.count();\n\t\tdouble Av = std::get<0>(resv); // sym area diff\n\t\tdouble Hv = std::get<1>(resv); // Hausdorff dist\n\t\tint Nv = std::get<2>(resv); // nb nodes\n\t\tint Bv = std::get<3>(resv); // nb branches\n\t\n\t\tint t1;\n\t\tdouble A1;\n\t\tdouble H1;\n\t\tint N1;\n\t\tint B1;\n\t\tdouble sat = 1.2;\n\t\tauto start1 = std::chrono::steady_clock::now();\n\t\tskeleton::GraphSkel2d::Ptr grskelsat = algorithm::pruning::ScaleAxisTransform(grskelvoro,sat);\n\t\tauto duration1 = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::steady_clock::now() - start1);\n\t\tstd::tuple<double,double,int,int> res1 = EvalSkel(dissh,disbnd,grskelsat);\n\t\tt1 = tv + duration1.count();\n\t\tA1 = std::get<0>(res1); // sym area diff\n\t\tH1 = std::get<1>(res1); // Hausdorff dist\n\t\tN1 = std::get<2>(res1); // nb nodes\n\t\tB1 = std::get<3>(res1); // nb branches\n\n\t\tif(output)\n\t\t{\n\t\t\tshape::DiscreteShape<2>::Ptr shpskel(new shape::DiscreteShape<2>(dissh->getWidth(),dissh->getHeight()));\n\t\t\talgorithm::skinning::Filling(shpskel,grskelsat);\n\n\t\t\tcv::Mat imagerec;\n\t\t\timage.copyTo(imagerec);\n\t\t\tdisplayopencv::DisplayDiscreteShape(shpskel,imagerec,shpskel->getFrame(),cv::Scalar(0,255,0));\n\t\t\tdisplayopencv::DisplayDiscreteBoundary(disbnd,imagerec,dissh->getFrame(),cv::Scalar(0,0,0));\n\t\t\tdisplayopencv::DisplayGraphSkeleton(grskelsat,imagerec,dissh->getFrame(),cv::Scalar(255,0,0));\n\n\t\t\tstd::ostringstream oss;\n\t\t\toss.setf( std::ios::fixed, std:: ios::floatfield );\n\t\t\toss.precision(1);\n\t\t\toss << \"sat.png\";\n\t\t\tcv::imwrite(oss.str(), imagerec);\n\t\t}\n\n\t\tint t2;\n\t\tdouble A2;\n\t\tdouble H2;\n\t\tint N2;\n\t\tint B2;\n\t\tdouble lambda = 2.0;\n\t\tauto start2 = std::chrono::steady_clock::now();\n\t\tskeleton::GraphSkel2d::Ptr grskellambda = algorithm::pruning::LambdaMedialAxis(grskelvoro,disbnd,lambda);\n\t\tauto duration2 = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::steady_clock::now() - start2);\n\t\tstd::tuple<double,double,int,int> res2 = EvalSkel(dissh,disbnd,grskellambda);\n\t\tt2 = tv + duration2.count();\n\t\tA2 = std::get<0>(res2); // sym area diff\n\t\tH2 = std::get<1>(res2); // Hausdorff dist\n\t\tN2 = std::get<2>(res2); // nb nodes\n\t\tB2 = std::get<3>(res2); // nb branches\n\n\t\tif(output)\n\t\t{\n\t\t\tshape::DiscreteShape<2>::Ptr shpskel(new shape::DiscreteShape<2>(dissh->getWidth(),dissh->getHeight()));\n\t\t\talgorithm::skinning::Filling(shpskel,grskellambda);\n\n\t\t\tcv::Mat imagerec;\n\t\t\timage.copyTo(imagerec);\n\t\t\tdisplayopencv::DisplayDiscreteShape(shpskel,imagerec,shpskel->getFrame(),cv::Scalar(0,255,0));\n\t\t\tdisplayopencv::DisplayDiscreteBoundary(disbnd,imagerec,dissh->getFrame(),cv::Scalar(0,0,0));\n\t\t\tdisplayopencv::DisplayGraphSkeleton(grskellambda,imagerec,dissh->getFrame(),cv::Scalar(255,0,0));\n\n\t\t\tstd::ostringstream oss;\n\t\t\toss.setf( std::ios::fixed, std:: ios::floatfield );\n\t\t\toss.precision(0);\n\t\t\toss << \"lambda.png\";\n\t\t\tcv::imwrite(oss.str(), imagerec);\n\t\t}\n\n\t\tint t3;\n\t\tdouble A3;\n\t\tdouble H3;\n\t\tint N3;\n\t\tint B3;\n\t\tdouble theta = 100*M_PI/180.0;\n\t\tauto start3 = std::chrono::steady_clock::now();\n\t\tskeleton::GraphSkel2d::Ptr grskeltheta = algorithm::pruning::ThetaMedialAxis(grskelvoro,theta);\n\t\tauto duration3 = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::steady_clock::now() - start3);\n\t\tstd::tuple<double,double,int,int> res3 = EvalSkel(dissh,disbnd,grskeltheta);\n\t\tt3 = tv + duration3.count();\n\t\tA3 = std::get<0>(res3); // sym area diff\n\t\tH3 = std::get<1>(res3); // Hausdorff dist\n\t\tN3 = std::get<2>(res3); // nb nodes\n\t\tB3 = std::get<3>(res3); // nb branches\n\n\t\tif(output)\n\t\t{\n\t\t\tshape::DiscreteShape<2>::Ptr shpskel(new shape::DiscreteShape<2>(dissh->getWidth(),dissh->getHeight()));\n\t\t\talgorithm::skinning::Filling(shpskel,grskeltheta);\n\n\t\t\tcv::Mat imagerec;\n\t\t\timage.copyTo(imagerec);\n\t\t\tdisplayopencv::DisplayDiscreteShape(shpskel,imagerec,shpskel->getFrame(),cv::Scalar(0,255,0));\n\t\t\tdisplayopencv::DisplayDiscreteBoundary(disbnd,imagerec,dissh->getFrame(),cv::Scalar(0,0,0));\n\t\t\tdisplayopencv::DisplayGraphSkeleton(grskeltheta,imagerec,dissh->getFrame(),cv::Scalar(255,0,0));\n\n\t\t\tstd::ostringstream oss;\n\t\t\toss.setf( std::ios::fixed, std:: ios::floatfield );\n\t\t\toss.precision(2);\n\t\t\toss << \"theta.png\";\n\t\t\tcv::imwrite(oss.str(), imagerec);\n\t\t}\n\t\t\n\t\tstd::cout << \"\\t Time \\t SymArea  Hausdorff  Branches \\t Nodes\" << std::endl;\n\t\tstd::cout << \"Propag : \" << t0 << \" \\t \" << A0 << \" \\t  \" << H0 << \" \\t     \" << B0 << \" \\t \" << N0 << std::endl;\n\t\tstd::cout << \"Voro   : \" << tv << \" \\t \" << Av << \" \\t  \" << Hv << \" \\t     \" << Bv << \" \\t \" << Nv << std::endl;\n\t\tstd::cout << \"SAT    : \" << t1 << \" \\t \" << A1 << \" \\t  \" << H1 << \" \\t     \" << B1 << \" \\t \" << N1 << std::endl;\n\t\tstd::cout << \"Lambda : \" << t2 << \" \\t \" << A2 << \" \\t  \" << H2 << \" \\t     \" << B2 << \" \\t \" << N2 << std::endl;\n\t\tstd::cout << \"Theta  : \" << t3 << \" \\t \" << A3 << \" \\t  \" << H3 << \" \\t     \" << B3 << \" \\t \" << N3 << std::endl;\n\t}\n\n\treturn 0;\n}\n", "meta": {"hexsha": "9f45d52717625ed6a37d52d004ca3dd6007105e5", "size": 11896, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/soft/soft_2dskeletonization/main.cpp", "max_stars_repo_name": "Ibujah/propagatedskeleton", "max_stars_repo_head_hexsha": "56a583e6f9907e68a388eec6ad179ad671ca156e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-03-29T08:40:16.000Z", "max_stars_repo_stars_event_max_datetime": "2019-03-30T11:06:46.000Z", "max_issues_repo_path": "src/soft/soft_2dskeletonization/main.cpp", "max_issues_repo_name": "Ibujah/propagatedskeleton", "max_issues_repo_head_hexsha": "56a583e6f9907e68a388eec6ad179ad671ca156e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/soft/soft_2dskeletonization/main.cpp", "max_forks_repo_name": "Ibujah/propagatedskeleton", "max_forks_repo_head_hexsha": "56a583e6f9907e68a388eec6ad179ad671ca156e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.6006825939, "max_line_length": 122, "alphanum_fraction": 0.6977135171, "num_tokens": 3680, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5583269943353745, "lm_q2_score": 0.5774953651858117, "lm_q1q2_score": 0.3224312514868037}}
{"text": "//==============================================================================\n//         Copyright 2003 - 2011   LASMEA UMR 6602 CNRS/Univ. Clermont II\n//         Copyright 2009 - 2013   LRI    UMR 8623 CNRS/Univ Paris Sud XI\n//         Copyright 2012 - 2013   MetaScale 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_CORE_FUNCTIONS_LOGEPS_HPP_INCLUDED\n#define NT2_CORE_FUNCTIONS_LOGEPS_HPP_INCLUDED\n\n#include <nt2/include/functor.hpp>\n#include <nt2/include/constants/logeps.hpp>\n#include <nt2/sdk/meta/generative_hierarchy.hpp>\n#include <nt2/core/container/dsl/generative.hpp>\n#include <nt2/core/functions/common/generative.hpp>\n\n#include <nt2/sdk/parameters.hpp>\n#include <boost/preprocessor/arithmetic/inc.hpp>\n#include <boost/preprocessor/repetition/repeat_from_to.hpp>\n\nnamespace nt2\n{\n  #if defined(DOXYGEN_ONLY)\n  /*!\n    @brief Logeps generator\n\n    Create an array full of log(eps).\n\n    @par Semantic:\n\n    logeps() semantic depends of its parameters type and quantity:\n\n    - The following code:\n      @code\n      double x = logeps();\n      @endcode\n      is equivalent to\n      @code\n      double x = log(eps);\n      @endcode\n\n    - For any Integer @c n, the following code:\n      @code\n      auto x = logeps(n);\n      @endcode\n      generates an expression that evaluates as a @size2d{n,n} table filled with\n      @c double log(eps)\n\n    - For any Integer @c sz1,...,szn , the following code:\n      @code\n      auto x = logeps(sz1,...,szn);\n      @endcode\n      generates an expression that evaluates as a @sizes{sz1,szn} table filled\n      @c double log(eps)\n\n    - For any Expression @c dims evaluating as a row vector of @c N elements,\n      the following code:\n      @code\n      auto x = logeps(dims);\n      @endcode\n      generates an expression that evaluates as a @sizes{dims(1),dims(N)}\n      table filled with @c double log(eps)\n\n    - For any Fusion Sequence @c dims of @c N elements, the following code:\n      @code\n      auto x = logeps(dims);\n      @endcode\n      generates an expression that evaluates as a @sizes{at_c<0>(dims),at_c<N-1>(dims)}\n      table filled with @c double log(eps)\n\n    - For any type @c T, the following code:\n      @code\n      T x = logeps( as_<T>() );\n      @endcode\n      is equivalent to\n      @code\n      T x = T(2);\n      @endcode\n\n    - For any Integer @c n and any type @c T, the following code:\n      @code\n      auto x = logeps(n, as_<T>());\n      @endcode\n      generates an expression that evaluates as a @size2d{n,n} table filled with\n      type @c T logepss.\n\n    - For any Integer @c sz1,...,szN and any type @c T, the following code:\n      @code\n      auto x = logeps(sz1,...,szn, as_<T>());\n      @endcode\n      generates an expression that evaluates as a @sizes{sz1,szn} table filled\n      with type @c T logepss.\n\n    - For any Expression @c dims evaluating as a row vector of @c N elements\n      and any type @c T, the following code:\n      @code\n      auto x = logeps(dims, as_<T>());\n      @endcode\n      generates an expression that evaluates as a @sizes{dims(1),dims(N)}\n      table filled with type @c T logepss.\n\n    - For any Fusion Sequence @c dims of @c N elements and any type @c T, the\n      following code:\n      @code\n      auto x = logeps(dims, as_<T>());\n      @endcode\n      generates an expression that evaluates as a @sizes{at_c<0>(dims),at_c<N-1>(dims)}\n      table filled with type @c T logepss.\n\n    @param dims Size of each dimension, specified as one or more integer values\n                or as a row vector of integer values. If any @c dims is lesser\n                or equal to 0, then the resulting expression is empty.\n\n    @param classname  Type specifier of the output. If left unspecified, the\n                      resulting expression behaves as an array of double.\n\n    @return An Expression evaluating as an array of a given type and dimensions\n            filled with the @c Logeps constant.\n\n    @sa Logeps\n  **/\n  template<typename... Args, typename ClassName>\n  details::unspecified logeps(Args const&... dims, ClassName const& classname);\n\n  /// @overload\n  template<typename... Args> details::unspecified logeps(Args const&... dims);\n\n  /// @overload\n  template<typename ClassName> ClassName::type logeps(ClassName const& classname);\n\n  /// @overload\n  double logeps();\n\n  #else\n\n  #define M0(z,n,t)                                                            \\\n  NT2_FUNCTION_IMPLEMENTATION(nt2::tag::Logeps,logeps, n)                            \\\n  /**/\n\n  BOOST_PP_REPEAT_FROM_TO(1,BOOST_PP_INC(BOOST_PP_INC(NT2_MAX_DIMENSIONS)),M0,~)\n\n  #undef M0\n\n  #endif\n}\n\nnamespace nt2 { namespace ext\n{\n  /// INTERNAL ONLY\n  template<typename Domain, typename Expr, int N>\n  struct  value_type<tag::Logeps,Domain,N,Expr>\n        : meta::generative_value<Expr>\n  {};\n\n  /// INTERNAL ONLY\n  template<typename Domain, typename Expr, int N>\n  struct  size_of<tag::Logeps,Domain,N,Expr>\n        : meta::generative_size<Expr>\n  {};\n} }\n#endif\n\n", "meta": {"hexsha": "b49415676251232f9629df1d7400678298a12fef", "size": 5193, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/core/generative/include/nt2/core/functions/logeps.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/generative/include/nt2/core/functions/logeps.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/generative/include/nt2/core/functions/logeps.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": 31.4727272727, "max_line_length": 87, "alphanum_fraction": 0.6160215675, "num_tokens": 1323, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5774953651858117, "lm_q2_score": 0.5583269943353745, "lm_q1q2_score": 0.3224312514868037}}
{"text": "\n#include <iostream>\n//#include <iomanip>\n//#include <fstream>\n\n//#include <boost/numeric/ublas/matrix.hpp>\n//#include <boost/numeric/ublas/vector.hpp>\n//#include <boost/numeric/ublas/io.hpp>\n\n#include <vector>\n#include <cmath>\n#include <cstring>\n\n//#include <unistd.h>\n\n#include \"NRGclasses.hpp\"\n#include \"NRGfunctions.hpp\"\n#include \"DM_NRG.hpp\"\n#include \"NRGOpMatRules.hpp\"\n\n\n#ifndef pi\n#define pi 3.141592653589793238462643383279502884197169\n#endif\n\n\nint main (int argc, char* argv[]){\n\n\n  CNRGCodeHandler ThisCode;\n\n  //CNRGbasisarray AcutN;\n  CNRGbasisarray* AcutN;\n  CNRGbasisarray AbasisN;\n\n  //CNRGbasisarray AcutNp1;\n  CNRGbasisarray AbasisNp1;\n\n  CNRGmatrix** OpArrayN;\n\n  CNRGmatrix* RhoN;\n  vector<double> ParamsTemp;\n  double betabar, DM,TM;\n  // 0 - betabar; 1 - TM; 2 - DM ?\n\n  char CNsites[8];\n  char CNmat[8];\n  char arqname[32];\n  char ext[32];\n\n  int NshellMax=3;\n  int NFermiOps=2;\n\n  ThisCode.NumNRGmats=0;\n  ThisCode.pAcut=&AcutN[NshellMax];\n  ThisCode.pAbasis=&AbasisN;\n  //ThisCode.MatArray=MatArray;\n\n  // Set betabar\n  betabar=0.727;\n  ParamsTemp.push_back(betabar);\n\n  // Tricky\n\n  OpArrayN=new CNRGmatrix* [NFermiOps];\n  for (int iop=0;iop<NFermiOps;iop++){\n    OpArrayN[iop]=new CNRGmatrix [NshellMax+1];\n  }\n\n  AcutN = new CNRGbasisarray [NshellMax+1];\n  RhoN = new CNRGmatrix [NshellMax+1];\n\n  ThisCode.ReadGenPars(\"\");\n\n  // This for now\n  ThisCode.Nsitesmax=NshellMax;\n\n  cout << \"Lambda = \" << ThisCode.Lambda << endl;\n  cout << \"Nsitesmax = \" << ThisCode.Nsitesmax << endl;\n\n  // Read last Nshell\n\n  AcutN[NshellMax].Nshell=NshellMax;\n  AbasisNp1.Nshell=NshellMax;\n  //ThisCode.ReadArrays(\"test\"); // ReadsInto pAcutN\n  // Not too handy...\n\n  sprintf(CNsites,\"%d\",NshellMax);\n  strcpy(ext,\"test_N\");\n  strcat(ext,CNsites);\n  strcat(ext,\".bin\");\n\n  // Read Abasis\n  strcpy(arqname,\"Abasis_\");\n  strcat(arqname,ext);\n  AbasisNp1.ReadBin(arqname);\n\n  // Read Acut\n  strcpy(arqname,\"Acut_\");\n  strcat(arqname,ext);\n  AcutN[NshellMax].ReadBin(arqname);\n\n  // Read Operators \n  for (int iop=0;iop<NFermiOps;iop++){\n    sprintf(CNmat,\"%d\",iop);\n    strcpy(arqname,\"Mat\");\n    strcat(arqname,CNmat);\n    strcat(arqname,\"_\");\n    strcat(arqname,ext);\n    OpArrayN[iop][NshellMax].ReadBin(arqname);\n    // Need a better way to do this but for now it will do:\n    // Actually, from Mat block it works!\n    //OpArrayN[iop][NshellMax].CheckForMatEl=OneChQSz_cd_check;\n\n  }\n  // end read operators\n\n  //AcutN[NshellMax].PrintAll();\n\n  // Set density matrix at the LAST NRG iteration\n\n  DM_NRG_SetRhoNmax(ParamsTemp,&AcutN[NshellMax],&RhoN[NshellMax]);\n\n  //RhoN[NshellMax].PrintAllBlocks();\n\n  // Calculate reduced density matrices\n\n  for (int Nshell=NshellMax-1;Nshell>=0;Nshell--){\n\n    AcutN[Nshell].ClearAll();\n    AbasisN.ClearAll();\n    AcutN[Nshell].Nshell=Nshell;\n    AbasisN.Nshell=Nshell;\n    //ThisCode.ReadArrays(\"test\"); // ReadsInto pAcutN\n    // Not too handy...\n\n    sprintf(CNsites,\"%d\",Nshell);\n    strcpy(ext,\"test_N\");\n    strcat(ext,CNsites);\n    strcat(ext,\".bin\");\n\n    // Read Abasis\n    strcpy(arqname,\"Abasis_\");\n    strcat(arqname,ext);\n    AbasisN.ReadBin(arqname);\n\n    // Read Acut\n    strcpy(arqname,\"Acut_\");\n    strcat(arqname,ext);\n    AcutN[Nshell].ReadBin(arqname);\n\n\n    // Set ChildStates in AcutN\n    DM_NRG_SetChildSt(&AcutN[Nshell],&AbasisNp1);\n\n    // Set RhoN from RhoNp1\n\n    DM_NRG_CalcRhoN(ParamsTemp,\n\t\t    &AcutN[Nshell],&AcutN[Nshell+1],&AbasisNp1,\n\t\t    &RhoN[Nshell],\n\t\t    &RhoN[Nshell+1]);\n\n    //RhoN[Nshell].PrintAllBlocks();\n\n    // Update AbasisNp1\n    AbasisNp1.ClearAll();\n    AbasisNp1=AbasisN;\n\n    // Read Operators \n    for (int iop=0;iop<NFermiOps;iop++){\n      sprintf(CNmat,\"%d\",iop); // Get all SavedMatrices\n      strcpy(arqname,\"Mat\");\n      strcat(arqname,CNmat);\n      strcat(arqname,\"_\");\n      strcat(arqname,ext);\n      OpArrayN[iop][Nshell].ReadBin(arqname);\n      // Need a better way to do this but for now it will do:\n      // Not needed!\n      //OpArrayN[iop][Nshell].CheckForMatEl=OneChQSz_cd_check;\n\n    }\n    // end read operators\n\n\n\n  }\n  // end loop in Nshell\n\n\n\n  // Given AcutN, rhoN and the Operators, calculate the spectral density\n\n\n  DM_NRG_CalcSpecFuncs(&ThisCode,AcutN,RhoN,OpArrayN);\n\n\n\n  delete[] RhoN;\n  delete[] AcutN;\n  for (int iop=NFermiOps-1;iop>=0;iop--){\n    delete[] OpArrayN[iop];\n  }\n  delete[] OpArrayN;\n\n}\n// end MAIN\n", "meta": {"hexsha": "b80be010276d3d9f8170e775f546db72cd60dd40", "size": 4346, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/DM_NRG/DM_NRG_SpecDens.cpp", "max_stars_repo_name": "lgds/NRG_USP", "max_stars_repo_head_hexsha": "ff66846e92498aa429cce6fc5793bec23ad03eb4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2015-09-21T20:58:45.000Z", "max_stars_repo_stars_event_max_datetime": "2019-03-20T01:21:41.000Z", "max_issues_repo_path": "src/DM_NRG/DM_NRG_SpecDens.cpp", "max_issues_repo_name": "lgds/NRG_USP", "max_issues_repo_head_hexsha": "ff66846e92498aa429cce6fc5793bec23ad03eb4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/DM_NRG/DM_NRG_SpecDens.cpp", "max_forks_repo_name": "lgds/NRG_USP", "max_forks_repo_head_hexsha": "ff66846e92498aa429cce6fc5793bec23ad03eb4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.9951690821, "max_line_length": 72, "alphanum_fraction": 0.6642890014, "num_tokens": 1462, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6992544085240401, "lm_q2_score": 0.4610167793123159, "lm_q1q2_score": 0.3223680153376914}}
{"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// Created by Roman Weissflog & Philipp Schulz\n\n\n\n/** \\file Bubble.h */\n\n#ifndef AMDIS_BUBBLE_H\n#define AMDIS_BUBBLE_H\n\n#include <list>\n#include <boost/numeric/mtl/mtl.hpp>\n#include \"AbstractFunction.h\"\n#include \"BasisFunction.h\"\n#include \"FixVec.h\"\n\nnamespace AMDiS\n{\n\n  /** \\ingroup FEMSpace\n  * \\brief\n  * Lagrange basis functions plus Bubble function. Sub class of BasisFunction\n  */\n\n  class Bubble : public BasisFunction\n  {\n  public:\n    /// Creator class used in the BasisFunctionCreatorMap.\n    class Creator : public BasisFunctionCreator\n    {\n    public:\n      virtual ~Creator() {}\n\n      /// Returns a new Lagrange object.\n      BasisFunction* create()\n      {\n        return getBubble(this->dim, this->dim + 1); // has to be generalized in later versions of bubble functions\n      }\n    };\n\n  protected:\n    /// Constructs lagrange/bubble basis functions with the given dim and degree.\n    /// Constructor is protected to avoid multiple instantiation of identical\n    /// basis functions. Use \\ref getBubble instead.\n    Bubble(int dim_, int degree_);\n\n    /** \\brief\n    * destructor\n    */\n    virtual ~Bubble();\n\n  public:\n    /// Returns a pointer to lagrange and bubble basis functions with the given dim and\n    /// degree. Multiple instantiation of identical basis functions is avoided\n    /// by rembering once created basis functions in \\ref allBasFcts.\n    static Bubble* getBubble(int dim, int degree);\n\n    /// Implements BasisFunction::interpol\n    void interpol(const ElInfo*, int, const int*,\n                  AbstractFunction<double, WorldVector<double>>*,\n                  mtl::dense_vector<double>&) const override;\n\n    /// Implements BasisFunction::interpol\n    void interpol(const ElInfo*, int,\n                  const int* b_no,\n                  AbstractFunction<WorldVector<double>, WorldVector<double>>*,\n                  mtl::dense_vector<WorldVector<double>>&) const override;\n\n    /// Returns the barycentric coordinates of the i-th basis function.\n    DimVec<double>* getCoords(int i) const override;\n\n\n    /// Implements BasisFunction::getBound\n    void getBound(const ElInfo*, BoundaryType*) const override;\n\n\n    /** \\brief\n    * Calculates the local vertex indices which are involved in evaluating\n    * the nodeIndex-th DOF at the positionIndex-th part of type position\n    * (VERTEX/EDGE/FACE/CENTER). nodeIndex determines the permutation\n    * of the involved vertices. So in 1d for lagrange4 there are two DOFs at\n    * the CENTER (which is an edge in this case). Then vertices[0] = {0, 1} and\n    * vertices[1] = {1, 0}. This allows to use the same local basis function\n    * for all DOFs at the same position.\n    */\n    static void setVertices(int dim, int degree,\n                            GeoIndex position, int positionIndex, int nodeIndex,\n                            int** vertices);\n\n\n    /// Implements BasisFunction::refineInter\n    inline void refineInter(DOFIndexed<double>* drv, RCNeighbourList* list, int n) override\n    {\n      if (refineInter_fct)\n        (*refineInter_fct)(drv, list, n, this);\n    }\n\n    /// Implements BasisFunction::coarseRestrict\n    inline void coarseRestr(DOFIndexed<double>* drv, RCNeighbourList* list, int n) override\n    {\n      if (coarseRestr_fct)\n        (*coarseRestr_fct)(drv, list, n, this);\n    }\n\n    /// Implements BasisFunction::coarseInter\n    inline void coarseInter(DOFIndexed<double>* drv, RCNeighbourList* list, int n) override\n    {\n      if (coarseInter_fct)\n        (*coarseInter_fct)(drv, list, n, this);\n    }\n\n    /// Implements BasisFunction::getLocalIndices().\n    void getLocalIndices(const Element* el,\n                         const DOFAdmin* admin,\n                         std::vector<DegreeOfFreedom>& dofs) const override;\n\n    /// Implements BasisFunction::getLocalDofPtrVec()\n    /// Returns an vector filled with all DOFs per position\n    void getLocalDofPtrVec(const Element* el,\n                           const DOFAdmin* admin,\n                           std::vector<const DegreeOfFreedom*>& vec) const override;\n\n    /// Implements BasisFunction::l2ScpFctBas\n    void l2ScpFctBas(Quadrature* q,\n                     AbstractFunction<double, WorldVector<double>>* f,\n                     DOFVector<double>* fh) override;\n\n    /// Implements BasisFunction::l2ScpFctBas\n    void l2ScpFctBas(Quadrature* q,\n                     AbstractFunction<WorldVector<double>, WorldVector<double>>* f,\n                     DOFVector<WorldVector<double>>* fh) override;\n\n    static void clear();\n\n    /// Implements BasisFunction::isnodal\n    bool isNodal() const override\n    {\n      return false;\n    }\n\n\n\n  protected:\n    /// sets the barycentric coordinates (stored in \\ref bary) of the local\n    /// basis functions.\n    void setBary();\n\n    /// Implements BasisFunction::setNDOF\n    void setNDOF() override;\n\n    /// Sets used function pointers\n    void setFunctionPointer();\n\n    /// Used by \\ref getVec\n    int* orderOfPositionIndices(const Element* el,\n                                GeoIndex position,\n                                int positionIndex) const override;\n\n  private:\n    /// barycentric coordinates of the locations of all basis functions\n    std::vector<DimVec<double>*>* bary;\n\n    /** \\name static dim-degree-arrays\n    * \\{\n    */\n    static std::vector<DimVec<double>*> baryDimDegree;\n    static DimVec<int>* ndofDimDegree;\n    static int nBasFctsDimDegree;\n    static std::vector<BasFctType*> phifunc;\n    static std::vector<GrdBasFctType*> grdPhifunc;\n    static std::vector<D2BasFctType*> D2Phifunc;\n    /** \\} */\n\n    /// List of all used BasisFunctions in the whole program. Avoids duplicate\n    /// instantiation of identical BasisFunctions.\n    static Bubble* Singleton;\n\n\n  protected:\n    /// Pointer to the used refineInter function\n    void (*refineInter_fct)(DOFIndexed<double>*, RCNeighbourList*, int, BasisFunction*);\n\n    static void  refineInter2_1d(DOFIndexed<double>*, RCNeighbourList*, int,\n                                 BasisFunction*);\n    static void  refineInter3_2d(DOFIndexed<double>*, RCNeighbourList*, int,\n                                 BasisFunction*);\n    static void  refineInter4_3d(DOFIndexed<double>*, RCNeighbourList*, int,\n                                 BasisFunction*);\n\n    /// Pointer to the used coarseRestr function\n    void (*coarseRestr_fct)(DOFIndexed<double>*, RCNeighbourList*, int, BasisFunction*);\n\n    static void  coarseRestr2_1d(DOFIndexed<double>*, RCNeighbourList*, int,\n                                 BasisFunction*);\n    static void  coarseRestr3_2d(DOFIndexed<double>*, RCNeighbourList*, int,\n                                 BasisFunction*);\n    static void  coarseRestr4_3d(DOFIndexed<double>*, RCNeighbourList*, int,\n                                 BasisFunction*);\n\n    /// Pointer to the used coarseInter function\n    void (*coarseInter_fct)(DOFIndexed<double>*, RCNeighbourList*, int, BasisFunction*);\n\n    static void  coarseInter2_1d(DOFIndexed<double>*, RCNeighbourList*, int,\n                                 BasisFunction*);\n    static void  coarseInter3_2d(DOFIndexed<double>*, RCNeighbourList*, int,\n                                 BasisFunction*);\n    static void  coarseInter4_3d(DOFIndexed<double>*, RCNeighbourList*, int,\n                                 BasisFunction*);\n\n\n    /// AbstractFunction which implements lagrange/bubble basis functions\n    class Phi : public BasFctType\n    {\n    public:\n      /// Constructs the local lagrange/bubble basis function for the given position,\n      /// positionIndex and nodeIndex. owner_ is a pointer to the Bubble\n      /// object this basis function belongs to.\n      Phi(Bubble* owner, GeoIndex position, int positionIndex, int nodeIndex);\n\n      /// Destructor\n      virtual ~Phi();\n\n    private:\n      /// vertices needed for evaluation of this function\n      int* vertices;\n\n      /// Pointer to the evaluating function\n      double (*func)(const DimVec<double>& lambda, int* vert);\n\n      /// Returns \\ref func(lambda, vertices)\n      inline double operator()(const DimVec<double>& lambda) const override\n      {\n        return func(lambda, vertices);\n      }\n\n      // ====== Lagrange, degree = 1 =====================================\n      // vertex\n      inline static double phi1v(const DimVec<double>& lambda, int* vertices)\n      {\n        return lambda[vertices[0]];\n      }\n\n      // ====== Bubble ===================================================\n      // 1d\n      inline static double phi2c(const DimVec<double>& lambda, int* vertices)\n      {\n        return (4.0 * lambda[vertices[0]] * lambda[vertices[1]]);\n      }\n\n      // 2d\n      inline static double phi3c(const DimVec<double>& lambda, int* vertices)\n      {\n        return 27.0 * lambda[vertices[0]] * lambda[vertices[1]] * lambda[vertices[2]];\n      }\n\n      // 3d\n      inline static double phi4c(const DimVec<double>& lambda, int* vertices)\n      {\n        return 256.0 * lambda[vertices[0]] * lambda[vertices[1]] *\n               lambda[vertices[2]] * lambda[vertices[3]];\n      }\n    };\n\n\n    /// AbstractFunction which implements gradients of Lagrange/Bubble basis functions.\n    /// See \\ref Phi\n    class GrdPhi : public GrdBasFctType\n    {\n    public:\n      GrdPhi(Bubble* owner, GeoIndex position, int positionIndex, int nodeIndex);\n\n      virtual ~GrdPhi();\n    private:\n      int* vertices;\n\n      void (*func)(const DimVec<double>& lambda,\n                   int* vertices_,\n                   mtl::dense_vector<double>& result);\n\n      inline void operator()(const DimVec<double>& lambda,\n                             mtl::dense_vector<double>& result) const override\n      {\n        func(lambda, vertices, result);\n      }\n\n      // ====== Lagrange1 ================================================\n      // vertex\n      inline static void grdPhi1v(const DimVec<double>&,\n                                  int* vertices,\n                                  mtl::dense_vector<double>& result)\n      {\n        result = 0.0;\n        result[vertices[0]] = 1.0;\n      }\n\n      // ======= Bubble ==================================================\n      inline static void grdPhi2c(const DimVec<double>& lambda,\n                                  int* vertices,\n                                  mtl::dense_vector<double>& result)\n      {\n        result = 0.0;\n        result[vertices[0]] = 4.0 * lambda[vertices[1]];\n        result[vertices[1]] = 4.0 * lambda[vertices[0]];\n      }\n\n\n      inline static void grdPhi3c(const DimVec<double>& lambda,\n                                  int* vertices,\n                                  mtl::dense_vector<double>& result)\n      {\n        result = 0.0;\n        result[vertices[0]] = 27.0 * lambda[vertices[1]] * lambda[vertices[2]];\n        result[vertices[1]] = 27.0 * lambda[vertices[0]] * lambda[vertices[2]];\n        result[vertices[2]] = 27.0 * lambda[vertices[0]] * lambda[vertices[1]];\n      }\n\n      inline static void grdPhi4c(const DimVec<double>& lambda,\n                                  int* vertices,\n                                  mtl::dense_vector<double>& result)\n      {\n        result = 0.0;\n        result[0] =\n          256.0 * lambda[vertices[1]] * lambda[vertices[2]] * lambda[vertices[3]];\n        result[1] =\n          256.0 * lambda[vertices[0]] * lambda[vertices[2]] * lambda[vertices[3]];\n        result[2] =\n          256.0 * lambda[vertices[0]] * lambda[vertices[1]] * lambda[vertices[3]];\n        result[3] =\n          256.0 * lambda[vertices[0]] * lambda[vertices[1]] * lambda[vertices[2]];\n      }\n    };\n\n\n    /// AbstractFunction which implements second derivatives of Lagrange/Bubble basis\n    /// functions. See \\ref Phi\n    class D2Phi : public D2BasFctType\n    {\n    public:\n      D2Phi(Bubble* owner, GeoIndex position, int positionIndex, int nodeIndex);\n\n      virtual ~D2Phi();\n\n    private:\n      int* vertices;\n\n      void (*func)(const DimVec<double>& lambda, int* vertices_, DimMat<double>& result);\n\n      inline void operator()(const DimVec<double>& lambda, DimMat<double>& result) const override\n      {\n        return func(lambda, vertices, result);\n      }\n\n      // ===== Lagrange1 ================================================\n      // vertex\n      inline static void D2Phi1v(const DimVec<double>&, int*, DimMat<double>& result)\n      {\n        result.set(0.0);\n      }\n\n\n      // ===== Bubble ===================================================\n      inline static void D2Phi2c(const DimVec<double>&, int* vertices,\n                                 DimMat<double>& result)\n      {\n        result.set(0.0);\n        result[vertices[0]][vertices[1]] = 4.0;\n        result[vertices[1]][vertices[0]] = 4.0;\n      }\n\n      inline static void D2Phi3c(const DimVec<double>& lambda, int* vertices,\n                                 DimMat<double>& result)\n      {\n        result.set(0.0);\n        result[vertices[0]][vertices[1]] =\n          result[vertices[1]][vertices[0]] = 27.0 * lambda[vertices[2]];\n        result[vertices[0]][vertices[2]] =\n          result[vertices[2]][vertices[0]] = 27.0 * lambda[vertices[1]];\n        result[vertices[1]][vertices[2]] =\n          result[vertices[2]][vertices[1]] = 27.0 * lambda[vertices[0]];\n      }\n\n      inline static void D2Phi4c(const DimVec<double>& lambda, int* vertices,\n                                 DimMat<double>& result)\n      {\n        result.set(0.0);\n        result[vertices[0]][vertices[1]] =\n          result[vertices[1]][vertices[0]] =\n            256.0 * lambda[vertices[2]] * lambda[vertices[3]];\n        result[vertices[0]][vertices[2]] =\n          result[vertices[2]][vertices[0]] =\n            256.0 * lambda[vertices[1]] * lambda[vertices[3]];\n        result[vertices[0]][vertices[3]] =\n          result[vertices[3]][vertices[0]] =\n            256.0 * lambda[vertices[1]] * lambda[vertices[2]];\n        result[vertices[1]][vertices[2]] =\n          result[vertices[2]][vertices[1]] =\n            256.0 * lambda[vertices[0]] * lambda[vertices[3]];\n        result[vertices[1]][vertices[3]] =\n          result[vertices[3]][vertices[1]] =\n            256.0 * lambda[vertices[0]] * lambda[vertices[2]];\n        result[vertices[2]][vertices[3]] =\n          result[vertices[3]][vertices[2]] =\n            256.0 * lambda[vertices[0]] * lambda[vertices[1]];\n      }\n    };\n  };\n}\n\n#endif // AMDIS_Bubble_H\n", "meta": {"hexsha": "ae662b267324965855c11ceeb0c149cbc68980a8", "size": 15020, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/experimental/Bubble.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/experimental/Bubble.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/experimental/Bubble.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.0116550117, "max_line_length": 114, "alphanum_fraction": 0.5841544607, "num_tokens": 3540, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6548947425132315, "lm_q2_score": 0.49218813572079556, "lm_q1q2_score": 0.3223314224109379}}
{"text": "/*\n \n Copyright (c) 2005-2015, University of Oxford.\n All rights reserved.\n \n University of Oxford means the Chancellor, Masters and Scholars of the\n University of Oxford, having an administrative office at Wellington\n Square, Oxford OX1 2JD, UK.\n \n This file is part of Chaste.\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 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 \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 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\n OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n \n */\n\n/*\n Jessica Cervi and Raymond J. Spiteri\n Numerical Simulation Laboratory\n University of Saskatchewan\n August 2016\n */\n\n#ifndef THIRDORDERRDIRKOPERATORSPLITTINGBIDOMAINSOLVER_HPP_\n#define THIRDORDERRDIRKOPERATORSPLITTINGBIDOMAINSOLVER_HPP_\n\n\n#include \"UblasIncludes.hpp\"\n\n//#include <iostream>\n#include <vector>\n#include <petscvec.h>\n\n#include \"AbstractBidomainSolver.hpp\"\n#include \"HeartConfig.hpp\"\n#include \"BidomainAssembler.hpp\"\n#include \"BidomainMassMatrixAssembler.hpp\"\n#include \"BidomainStiffnessMatrixAssembler.hpp\"\n#include \"BidomainCorrectionTermAssembler.hpp\"\n#include \"BidomainNeumannSurfaceTermAssembler.hpp\"\n#include \"TimeStepper.hpp\"\n\n#include <boost/numeric/ublas/vector_proxy.hpp>\n\n//EDIT COMMENTS HERE!!!\n/**\n *  A bidomain solver that uses Strang operator splitting of the diffusion (conductivity) term and the reaction\n *  (ionic current) term, instead of solving the full reaction-diffusion PDE. This does NOT refer to operator splitting\n *  of the two PDEs in the bidomain equations. For details see for example Sundnes et al \"Computing the Electrical\n *  Activity of the Heart\". This solves the PDEs using the SDIRK2O2 method (second order).\n *\n *  The algorithm is, for solving from t=T to T+dt.\n *\n *  (i)   Solve ODEs   dV/dt = Iionic, du/dt = f(u,V)  for t=T to T+dt/2\n *        [giving updated V (internally, and in solution vector) and updated state variables]\n *  (ii)  Solve PDE    dV/dt = div (sigma_i grad V) + div (sigma_i grad phi_e), div (sigma_i grad V) + div ((sigma_i+sigma_e) grad phi_e) = 0\n *        for t=T to dt         [using V from step i, --> updated V]\n *  (iii) Solve ODEs   dV/dt = Iionic, du/dt = f(u,V)  for t=T+dt/2 to T+dt  [using V from step ii, --> final V]\n *\n *  Notes\n *   (a)  Stages (iii) and (i) can normally be solved together in one go, except just before/after printing the voltage to file.\n *        However for simplicity of code this has not been implemented\n *   (b)  Therefore, the effective ODE timestep will be:  min(ode_dt, pde_dt/2), where ode_dt and pde_dt are those\n *        given via HeartConfig.\n *   (c)  This solver is FOR COMPARING ACCURACY, NOT PERFORMANCE. It has not been optimised and may or may not\n *        perform well in parallel.\n *   (d)  Usage: add the follwoing lines to your original code:\n *        HeartConfig::Instance()->SetUseReactionDiffusionOperatorSplittingBidomainSolver();\n * \t  HeartConfig::Instance()->SetUseReactionDiffusionThirdOrderOperatorSplittingBidomainSolver();\n */\ntemplate<unsigned ELEMENT_DIM, unsigned SPACE_DIM>\nclass ThirdOrderRDIRKOperatorSplittingBidomainSolver : public AbstractBidomainSolver<ELEMENT_DIM, SPACE_DIM>\n{\nprivate:\n    \n    /** Coefficient for SDIRK2O3 method */\n    double mGamma;\n    \n    /** Mass matrix, used to computing the RHS vector (actually: mass-matrix in\n     *  voltage-voltage block, zero elsewhere\n     */\n    Mat mMassMatrix;\n    \n    /** Ai matrix, used to computing the RHS vector (actually: Ai-matrix in\n     *  voltage-voltage block, zero elsewhere\n     */\n\n    Mat mAiMatrix;\n    \n    \n    /**\n     *  The vector multiplied by the mass matrix. Ie, if the linear system to\n     *  be solved is Ax=b, this vector is z1 where b = M z1 + Ai z2.\n     */\n    Vec mVecForConstructingRhs1;\n    \n    /**\n     *  The vector multiplied by the Ai matrix. Ie, if the linear system to\n     *  be solved is Ax=b, this vector is z2 where b = M z1 + Ai z2.\n     */\n    Vec mVecForConstructingRhs2;\n    /**\n     *  The vector multiplied by the mass matrix. Ie, if the linear system to\n     *  be solved is Ax=b, this vector is z1 where b = M z1 + Ai z2., Third stage\n     */\n    Vec mVecForConstructingRhs1_2;\n    \n    /**\n     *  The vector multiplied by the Ai matrix. Ie, if the linear system to\n     *  be solved is Ax=b, this vector is z2 where b = M z1 + Ai z2. Third Stage\n     */\n    Vec mVecForConstructingRhs2_2;\n    \n    /** The bidomain assembler, used to set up the LHS matrix */\n    BidomainAssembler<ELEMENT_DIM, SPACE_DIM>* mpBidomainAssembler;\n    \n    /** Assembler for surface integrals coming from any non-zero Neumann boundary conditions */\n    BidomainNeumannSurfaceTermAssembler<ELEMENT_DIM, SPACE_DIM>* mpBidomainNeumannSurfaceTermAssembler;\n    \n    /**\n     * If using state variable interpolation, points to an assembler to use in\n     * computing the correction term to apply to the RHS.\n     */\n    BidomainCorrectionTermAssembler<ELEMENT_DIM, SPACE_DIM>* mpBidomainCorrectionTermAssembler;\n    \n    /**\n     *  The linear system that will be set up and solved first as part of the\n     *  PDE solve\n     */\n    //LinearSystem* mpLinearSystem_first_solve;\n    \n    /**\n     * If using state variable interpolation, points to an assembler to use in\n     * computing the correction term to apply to the RHS.\n     */\n    //BidomainCorrectionTermAssembler<ELEMENT_DIM,SPACE_DIM>* mpBidomainCorrectionTermAssembler;\n    \n    \n    /** Overloaded InitialiseForSolve() which calls base version but also\n     *  initialises mMassMatrix and mVecForConstructingRhs\n     *\n     *  @param initialSolution initial solution\n     */\n    void InitialiseForSolve(Vec initialSolution);\n    \n    /**\n     *  Implementation of SetupLinearSystem() which uses the assembler to compute the\n     *  LHS matrix, but sets up the RHS vector using the mass-matrix (constructed\n     *  using a separate assembler) multiplied by a vector\n     *\n     *  @param currentSolution Solution at current time\n     *  @param computeMatrix Whether to compute the matrix of the linear system\n     */\n    void SetupLinearSystem(Vec currentSolution, bool computeMatrix);\n    \n    /**\n     *  Called before setting up the linear system, used to solve the cell models for first half timestep (step (i) above)\n     *  @param currentSolution the latest solution vector\n     */\n    void PrepareForSetupLinearSystem(Vec currentSolution);\n    \n    \n    /**\n     *  Called after solving the linear system, used to solve the cell models for second half timestep (step (iii) above)\n     *  @param currentSolution the latest solution vector (ie the solution of the linear system).\n     */\n    void FollowingSolveLinearSystem(Vec currentSolution);\n    \n    /**\n     * Called when we are ready to solve the splitted system\n     */\n    Vec SolveOS(Vec currentSolution);\n    \n    \n    \n    \n    /**\n     * Whether we are solving the cell system or not\n     */\n    bool SolvingCellSystem;\n    \n    /**\n     * When using third-order OS, the substeps for the ODE and PDE system have to be the following\n     */\n    double ThirdOrderTimeSteps;\n    \n    /**\n     * Index for the time-step array\n     */\n    int TimeSubStepIndex;\n    \n    /**\n     * Index for the whether solving the cell system of not\n     */\n    int BackwardTimeIntegrationIndex;\n\n    /**\n     * Index for DIRK stage\n     */\n    int DIRKStage;\n    \n    /*\n     *Stepper\n     */\n    TimeStepper stepper();\n    \n    /*\n     *Stage counter for DIRK method\n     */\n    int currentStage;\n    \n    \npublic:\n    /**\n     * Constructor\n     *\n     * @param bathSimulation Whether the simulation involves a perfusing bath\n     * @param pMesh pointer to the mesh\n     * @param pTissue pointer to the tissue\n     * @param pBoundaryConditions pointer to the boundary conditions\n     */\n    ThirdOrderRDIRKOperatorSplittingBidomainSolver(bool bathSimulation,\n                                              AbstractTetrahedralMesh<ELEMENT_DIM, SPACE_DIM>* pMesh,\n                                              BidomainTissue<SPACE_DIM>* pTissue,\n                                              BoundaryConditionsContainer<ELEMENT_DIM, SPACE_DIM,2>* pBoundaryConditions);\n    \n    ~ThirdOrderRDIRKOperatorSplittingBidomainSolver();\n    \n    //  void FinaliseLinearSystem_first_solve(Vec existingSolution);\n    \n};\n\n\n#endif /*THIRDORDERRDIRKOPERATORSPLITTINGBIDOMAINSOLVER_HPP_*/\n", "meta": {"hexsha": "294dec1a32b6bd1c08d4cae42c2cc1e8cf062cf6", "size": 9569, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "heart/src/solver/electrics/bidomain/ThirdOrderRDIRKOperatorSplittingBidomainSolver.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": "heart/src/solver/electrics/bidomain/ThirdOrderRDIRKOperatorSplittingBidomainSolver.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": "heart/src/solver/electrics/bidomain/ThirdOrderRDIRKOperatorSplittingBidomainSolver.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": 37.6732283465, "max_line_length": 141, "alphanum_fraction": 0.7016407148, "num_tokens": 2269, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6548947155710233, "lm_q2_score": 0.49218813572079556, "lm_q1q2_score": 0.3223314091503026}}
{"text": "/* Copyright (c) 2015, Julian Straub <jstraub@csail.mit.edu>                    \n * Licensed under the MIT license. See the license file LICENSE.                \n */\n\n#include <iostream>\n#include <fstream>\n#include <string>\n#include <boost/program_options.hpp>\n\n#include <dpMM/dpSubclusterMM.hpp>\n#include <dpMM/dirBaseMeasure.hpp>\n\nusing namespace Eigen;\nusing std::string; \nnamespace po = boost::program_options;\n\ntypedef double flt;\n\nint main(int argc, char **argv)\n{\n\n  // Declare the supported options.\n  po::options_description desc(\"Allowed options\");\n  desc.add_options()\n    (\"help,h\", \"produce help message\")\n    (\"seed\", po::value<int>(), \"seed for random number generator\")\n    (\"N,N\", po::value<int>(), \"number of input datapoints\")\n    (\"D,D\", po::value<int>(), \"number of dimensions of the data\")\n    (\"T,T\", po::value<int>(), \"iterations\")\n    (\"alpha,a\", po::value< vector<double> >()->multitoken(), \n      \"alpha parameter of the DP (if single value assumes all alpha_i are the \"\n      \"same\")\n    (\"K,K\", po::value<int>(), \"number of initial clusters \")\n    (\"base\", po::value<string>(), \n      \"which base measure to use (only DpDir, \")\n    (\"params,p\", po::value< vector<double> >()->multitoken(), \n      \"parameters of the base measure\")\n    (\"brief\", po::value< vector<double> >()->multitoken(), \n      \"brief parameters of the base measure (ie Delta = delta*I; \"\n      \"theta=t*ones(D)\")\n    (\"input,i\", po::value<string>(), \n      \"path to input dataset .csv file (rows: dimensions; cols: different \"\n      \"datapoints)\")\n    (\"output,o\", po::value<string>(), \n      \"path to output labels .csv file (rows: time; cols: different \"\n      \"datapoints)\")\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    cout << desc << \"\\n\";\n    return 1;\n  }\n\n  uint64_t seed = time(0);\n  if(vm.count(\"seed\"))\n    seed = static_cast<uint64_t>(vm[\"seed\"].as<int>());\n  boost::mt19937 rndGen(seed);\n  uint32_t K=5;\n  if (vm.count(\"K\")) K = vm[\"K\"].as<int>();\n  // number of iterations\n  uint32_t T=100;\n  if (vm.count(\"T\")) T = vm[\"T\"].as<int>();\n  uint32_t N=100;\n  if (vm.count(\"N\")) N = vm[\"N\"].as<int>();\n  uint32_t D=2;\n  if (vm.count(\"D\")) D = vm[\"D\"].as<int>();\n  cout << \"T=\"<<T<<endl;\n  // DP alpha parameter\n  VectorXd alpha(K);\n  alpha.setOnes(K);\n  if (vm.count(\"alpha\"))\n  {\n    vector<double> params = vm[\"alpha\"].as< vector<double> >();\n    if(params.size()==1)\n      alpha *= params[0];\n    else\n      for (uint32_t k=0; k<K; ++k)\n        alpha(k) = params[k];\n  }\n  cout << \"alpha=\"<<alpha.transpose()<<endl;\n\n  shared_ptr<MatrixXd> spx(new MatrixXd(D,N));\n  MatrixXd& x(*spx);\n  string pathIn =\"\";\n  if(vm.count(\"input\")) pathIn = vm[\"input\"].as<string>();\n  if (!pathIn.compare(\"\"))\n  {\n    for(uint32_t i=0; i<N; ++i)\n    {\n      if(i<N/3)\n      {\n        x.col(i) << VectorXd::Zero(D/3), VectorXd::Zero(D/3), VectorXd::Ones(D/3)*100;\n      }else if(N/3 <= i && i < 2*N/3){\n        x.col(i) << VectorXd::Zero(D/3), VectorXd::Ones(D/3)*100, VectorXd::Zero(D/3);\n      }else{\n        x.col(i) << VectorXd::Ones(D/3)*100, VectorXd::Zero(D/3), VectorXd::Zero(D/3);\n      }\n//      x.col(i) /= x.col(i).sum();\n    }\n    cout<<x<<endl;\n  }else{\n    cout<<\"loading data from \"<<pathIn<<endl;\n    std::ifstream fin(pathIn.data(),std::ifstream::in);\n    for (uint32_t j=0; j<D; ++j)\n      for (uint32_t i=0; i<N; ++i)\n        fin>>x(j,i);\n  }\n\n  // which base distribution\n  string base = \"DpDir\";\n  if(vm.count(\"base\")) base = vm[\"base\"].as<string>();\n\n//  if(base.compare(\"DpDir\")){\n//    // normalize to unit sum\n//    int err = 0;\n//#pragma omp parallel for\n//    for (uint32_t i=0; i<N; ++i)\n//      if(fabs(x.col(i).sum() - 1.0) > 1e-1)\n//      {\n//        err++;\n//        cout<<x.col(i).sum() <<endl;\n//      }else\n//        x.col(i) /= x.col(i).sum();\n//    if(err>0) return 0;\n//  }\n\n  \n  DpMM<double> *dpmm=NULL;\n  if(!base.compare(\"DpDir\"))\n  {\n  // Dir alpha parameter\n    VectorXd gamma(D);\n    gamma.setOnes(D);\n    if(vm.count(\"params\"))\n    {\n      vector<double> params = vm[\"params\"].as< vector<double> >();\n      cout<<\"params length=\"<<params.size()<<\" D=\"<<D<<endl;\n      if(params.size() == 1)\n        gamma *= params[0];\n      else\n        for(uint32_t i=0; i<D; ++i)\n          gamma(i) = params[i];\n      cout <<\"gamma=\"<<gamma<<endl;\n    }\n    DirMultd dir(gamma, &rndGen);\n    shared_ptr<DirMultSampledd> dirSampl(new DirMultSampledd(dir));\n    shared_ptr<LrCluster<DirMultSampledd,double> > lrTheta(new \n        LrCluster<DirMultSampledd,double>(dirSampl,1.0,&rndGen));\n    dpmm = new DpSubclusterMM<DirMultSampledd,double>(alpha(0), \n        lrTheta, K, &rndGen);\n  }  \n  \n  \n  string pathOut =\"./labels.csv\";\n  if(vm.count(\"output\")) \n    pathOut = vm[\"output\"].as<string>();\n  cout<<\"output to \"<<pathOut<<endl;\n\n  assert(dpmm!=NULL);\n  dpmm->initialize(x);\n\n  std::ofstream fout(pathOut.data(),std::ofstream::out);\n  std::ofstream foutJointLike((pathOut+\"_jointLikelihood.csv\").data(),std::ofstream::out);\n  std::ofstream foutMeans((pathOut+\"_means.csv\").data(),std::ofstream::out);\n  std::ofstream foutCovs((pathOut+\"_covs.csv\").data(),std::ofstream::out);\n\n  const VectorXu& z = dpmm->getLabels().transpose();\n  for (uint32_t i=0; i<z.size()-1; ++i) \n    fout<<z(i)<<\" \";\n  fout<<z(z.size()-1)<<endl;\n  foutJointLike<<dpmm->logJoint()<<endl;\n  dpmm->dump(foutMeans,foutCovs);\n\n  for (uint32_t t=0; t<T; ++t)\n  {\n    cout<<\"------------ t=\"<<t<<\" -------------\"<<endl;\n    //      VectorXd Ns = counts(dpmm->getLabels(),dpmm->getK()*2).transpose();\n    //      cout<<\"-- counts= \"<<Ns.transpose()<<\" sum=\"<<Ns.sum()<<endl;\n    dpmm->sampleParameters();\n\n\n    const VectorXu& z = dpmm->getLabels().transpose();\n    for (uint32_t i=0; i<z.size()-1; ++i) \n      fout<<z(i)<<\" \";\n    fout<<z(z.size()-1)<<endl;\n    foutJointLike<<dpmm->logJoint()<<endl;\n    dpmm->dump(foutMeans,foutCovs);\n\n    dpmm->sampleLabels();\n\n    VectorXd Ns = dpmm->getCounts();\n    cout<<\"--  counts= \"<<Ns.transpose()<<\" sum=\"<<Ns.sum()<<endl;\n    cout<<\"    K=\"<<dpmm->getK();\n    cout<<\"    logJoint= \"<<dpmm->logJoint()<<endl;\n\n    dpmm->proposeMerges();\n    //      Ns = counts(dpmm->getLabels(),dpmm->getK()*2).transpose();\n    //      cout<<\"-- counts= \"<<Ns.transpose()<<\" sum=\"<<Ns.sum()<<endl;\n\n    dpmm->proposeSplits();\n    //      Ns = counts(dpmm->getLabels(),dpmm->getK()*2).transpose();\n    //      cout<<\"-- counts= \"<<Ns.transpose()<<\" sum=\"<<Ns.sum()<<endl;\n\n  }\n  fout.close();\n  foutJointLike.close();\n\n  MatrixXd logLikes;\n  MatrixXu inds = dpmm->mostLikelyInds(10,logLikes);\n  cout<<\"most likely indices\"<<endl;\n  cout<<inds<<endl;\n  cout<<\"----------------------------------------\"<<endl;\n\n  fout.open((pathOut+\"mlInds.csv\").data(),std::ofstream::out);\n  fout<<inds<<endl;\n  fout.close();\n  fout.open((pathOut+\"mlLogLikes.csv\").data(),std::ofstream::out);\n  fout<<logLikes<<endl;\n  fout.close();\n};\n\n", "meta": {"hexsha": "4c605375bc8ec0cc7b87349017de0353cd359b85", "size": 6940, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/dpDirMM.cpp", "max_stars_repo_name": "jstraub/dpMM", "max_stars_repo_head_hexsha": "538c432d5f98c040d5c1adb072e545e38f97fc69", "max_stars_repo_licenses": ["MIT-feh"], "max_stars_count": 11.0, "max_stars_repo_stars_event_min_datetime": "2015-04-27T15:14:01.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-18T00:19:18.000Z", "max_issues_repo_path": "src/dpDirMM.cpp", "max_issues_repo_name": "jstraub/dpMM", "max_issues_repo_head_hexsha": "538c432d5f98c040d5c1adb072e545e38f97fc69", "max_issues_repo_licenses": ["MIT-feh"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/dpDirMM.cpp", "max_forks_repo_name": "jstraub/dpMM", "max_forks_repo_head_hexsha": "538c432d5f98c040d5c1adb072e545e38f97fc69", "max_forks_repo_licenses": ["MIT-feh"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2015-07-02T12:46:20.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-30T04:39:30.000Z", "avg_line_length": 30.7079646018, "max_line_length": 90, "alphanum_fraction": 0.5690201729, "num_tokens": 2111, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5813030906443133, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.3223153949524858}}
{"text": "// Filename: mixed_complex.cpp (part of MTL4)\n\n#include <complex>\n#include <iostream>\n#include <boost/numeric/mtl/operation/extended_complex.hpp>\n\nint main()\n{\n    std::complex<double>  z(2.0, 3.0);\n    std::cout << \"2 * z = \" << 2 * z << '\\n';\n    std::cout << \"2 + z = \" << 2 + z << '\\n';\n    std::cout << \"z / 2 = \" << z / 2 << '\\n';\n    std::cout << \"2 / z = \" << 2 / z << '\\n';\n    std::cout << \"2 - z = \" << 2 - z << '\\n';\n\n    return 0;\n}\n", "meta": {"hexsha": "2643e737d63aa5b061aab3f868c5100f2745c353", "size": 446, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/mtl/examples/mixed_complex.cpp", "max_stars_repo_name": "lit-uriy/mtl4-mirror", "max_stars_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_stars_repo_licenses": ["MTLL"], "max_stars_count": 24.0, "max_stars_repo_stars_event_min_datetime": "2019-03-26T15:25:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T10:00:45.000Z", "max_issues_repo_path": "libs/numeric/mtl/examples/mixed_complex.cpp", "max_issues_repo_name": "lit-uriy/mtl4-mirror", "max_issues_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_issues_repo_licenses": ["MTLL"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-04-17T12:35:32.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-03T15:46:25.000Z", "max_forks_repo_path": "libs/numeric/mtl/examples/mixed_complex.cpp", "max_forks_repo_name": "lit-uriy/mtl4-mirror", "max_forks_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_forks_repo_licenses": ["MTLL"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2019-12-01T13:40:30.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-14T08:39:54.000Z", "avg_line_length": 24.7777777778, "max_line_length": 59, "alphanum_fraction": 0.466367713, "num_tokens": 165, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.665410572017153, "lm_q2_score": 0.48438008427698437, "lm_q1q2_score": 0.32231162895246496}}
{"text": "/*Copyright (c) 2021 James Gayvert\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n*/\n\n/*\n * AOCAP.cpp\n */\n\n#include \"AOCAP.h\"\n#include \"grid_radial.h\"\n#include \"bragg.h\"\n#include <numgrid.h>\n#include <omp.h>\n#include <chrono>\n#include <ctime>\n#include <Eigen/Dense>\n#include <iomanip>\n#include <iostream>\n#include <thread>\n#include <vector>\n#include <cmath>\n#include <limits>\n#include \"BasisSet.h\"\n#include \"gto_ordering.h\"\n#include \"opencap_exception.h\"\n#include \"utils.h\"\n#include <typeinfo>\n#include \"boxcap.h\"\n#include \"cap_types.h\"\n\nAOCAP::AOCAP(std::vector<Atom> geometry,std::map<std::string, std::string> params)\n{\n\tverify_cap_parameters(params);\n\tdouble capx,capy,capz,rcut,radial,angpts;\n\tstd::stringstream capxss(params[\"cap_x\"]);\n\tstd::stringstream capyss(params[\"cap_y\"]);\n\tstd::stringstream capzss(params[\"cap_z\"]);\n\tstd::stringstream rcutss(params[\"r_cut\"]);\n\tstd::stringstream radialss(params[\"radial_precision\"]);\n\tstd::stringstream angularss(params[\"angular_points\"]);\n\tcapxss >> capx;\n\tcapyss >> capy;\n\tcapzss >> capz;\n\trcutss >> rcut;\n\tradialss >> radial;\n\tangularss >> angpts;\n\t//now fill class members\n\tcap_type = params[\"cap_type\"];\n\tcap_x = capx;\n\tcap_y= capy;\n\tcap_z = capz;\n\tr_cut = rcut;\n\tradial_precision = pow(10,-1.0*radial);\n\tangular_points = angpts;\n\tatoms = geometry;\n    num_atoms = atoms.size();\n\tif(compare_strings(cap_type,\"box\"))\n\t\tcap_func = box_cap(cap_x,cap_y,cap_z);\n\telse if(compare_strings(cap_type,\"voronoi\"))\n\t\tcap_func = voronoi_cap(r_cut,atoms);\n\telse\n\t\topencap_throw(\"Error: Only box and voronoi caps are implemented natively.\");\n\tif(params.find(\"do_numerical\")!=params.end())\n\t{\n\t\tstd::string num_int = params[\"do_numerical\"];\n\t\tif(compare_strings(num_int,\"true\"))\n\t\t\tdo_numerical = true;\n\t\telse if(compare_strings(num_int,\"false\") && compare_strings(cap_type,\"box\"))\n\t\t\tdo_numerical = false;\n\t\telse\n\t\t\tdo_numerical = true; \n\t}\n\telse if(compare_strings(cap_type,\"box\"))\n\t\tdo_numerical = false;\n\telse\n\t\tdo_numerical = true;\n}\n\nAOCAP::AOCAP(std::vector<Atom> geometry,std::map<std::string, std::string> params,const std::function<std::vector<double>(std::vector<double> &, std::vector<double> &, \nstd::vector<double> &, std::vector<double> &)> &custom_cap_func)\n{\n\tverify_cap_parameters(params);\n\tdouble radial,angpts;\n\tstd::stringstream radialss(params[\"radial_precision\"]);\n\tstd::stringstream angularss(params[\"angular_points\"]);\n\tradialss >> radial;\n\tangularss >> angpts;\n\t//now fill class members\n\tcap_type = \"custom\";\n\tcap_x = 0.0;\n\tcap_y= 0.0;\n\tcap_z = 0.0;\n\tr_cut = 0.0;\n\tradial_precision = pow(10,-1.0*radial);\n\tangular_points = angpts;\n\tatoms = geometry;\n    num_atoms = atoms.size();\n\tdo_numerical = true;\n\tcap_func = custom_cap_func;\n}\n\n\nvoid AOCAP::integrate_cap_numerical(Eigen::MatrixXd &cap_mat, BasisSet bs)\n{\n\t// funny business happens with GIL if we try to parallelize over atoms when custom python function is used\n\tif(cap_type==\"custom\")\n\t\tomp_set_num_threads(1);\n    std::cout << \"Calculating CAP matrix in AO basis using \" << std::to_string(omp_get_max_threads()) << \" threads.\" << std::endl;\n    std::cout << std::setprecision(2) << std::scientific  << \"Radial precision: \" << radial_precision\n              << \" Angular points: \" << angular_points << std::endl;\n\tsize_t num_atoms = atoms.size();\n    double x_coords_bohr[num_atoms];\n\tdouble y_coords_bohr[num_atoms];\n\tdouble z_coords_bohr[num_atoms];\n\tint nuc_charges[num_atoms];\n\tfor(size_t i=0;i<num_atoms;i++)\n\t{\n\t\tx_coords_bohr[i]=atoms[i].coords[0];\n\t\ty_coords_bohr[i]=atoms[i].coords[1];\n\t\tz_coords_bohr[i]=atoms[i].coords[2];\n\t\tnuc_charges[i]=atoms[i].Z;\n\t\tif (atoms[i].Z==0)\n\t\t\tnuc_charges[i]=1; //choose bragg radius for H for ghost atoms\n\t}\n    int min_num_angular_points = angular_points;\n    int max_num_angular_points = angular_points;\n\t#pragma omp parallel for \n\tfor(size_t i=0;i<num_atoms;i++)\n\t{\n        // check parameters\n        double alpha_max = bs.alpha_max(atoms[i]);\n        std::vector<double> alpha_min = bs.alpha_min(atoms[i]);\n        double r_inner = get_r_inner(radial_precision,\n                                     alpha_max * 2.0); // factor 2.0 to match DIRAC\n        double h = std::numeric_limits<float>::max();\n        double r_outer = 0.0;\n        for (int l = 0; l <= bs.max_L(); l++)\n        {\n            if (alpha_min[l] > 0.0)\n            {\n                r_outer =\n                std::max(r_outer,\n                         get_r_outer(radial_precision,\n                                     alpha_min[l],\n                                     l,\n                                     4.0 * get_bragg_angstrom(nuc_charges[i])));\n                if(r_outer < r_inner)\n                {\n                    opencap_throw(\"Error: r_outer < r_inner, grid cannot be allocated for this basis.\");\n                    //std::cout << \"Setting alpha min[l] to 0.01\" << std::endl; \n                    //alpha_min[l]=0.01;\n                }\n                else\n                {\n                    h = std::min(h,\n                                 get_h(radial_precision, l, 0.1 * (r_outer - r_inner)));\n                    if(r_outer < h)\n                    {\n                        opencap_throw(\"Error: r_outer < h, grid cannot be allocated for this basis.\");\n                    }\n                }\n            }\n        }\n        context_t *context = numgrid_new_atom_grid(radial_precision,\n\t\t                                 min_num_angular_points,\n\t\t                                 max_num_angular_points,\n\t\t                                 nuc_charges[i],\n\t\t                                 bs.alpha_max(atoms[i]),\n\t\t                                 bs.max_L(),\n\t\t                                 alpha_min.data());\n\t\tint num_points = numgrid_get_num_grid_points(context);\n        double *grid_x_bohr = new double[num_points];\n        double *grid_y_bohr = new double[num_points];\n        double *grid_z_bohr = new double[num_points];\n        double *grid_w = new double[num_points];\n\t\tdouble *cap_values = new double[num_points];\n        numgrid_get_grid(  context,\n                           num_atoms,\n                           i,\n                           x_coords_bohr,\n                           y_coords_bohr,\n                           z_coords_bohr,\n                           nuc_charges,\n                           grid_x_bohr,\n                           grid_y_bohr,\n                           grid_z_bohr,\n                           grid_w);\n        int num_radial_points = numgrid_get_num_radial_grid_points(context);\n\t\tcompute_cap_on_grid(cap_mat,bs,grid_x_bohr,grid_y_bohr,grid_z_bohr,grid_w,num_points);\n\t}\n}\n\nvoid AOCAP::compute_cap_on_grid(Eigen::MatrixXd &cap_mat,BasisSet bs,double* x, double* y, double* z, \ndouble *grid_w, int num_points)\n{\n\tEigen::VectorXd cap_vals; Eigen::MatrixXd bf_values;\n\tbf_values = Eigen::MatrixXd::Zero(num_points,bs.num_carts());\n    std::vector<double> x_vec(x,x+num_points);\n    std::vector<double> y_vec(y,y+num_points);\n    std::vector<double> z_vec(z,z+num_points);\n    std::vector<double> w_vec(grid_w,grid_w+num_points);\n    std::vector<double> cap_vec = cap_func(x_vec,y_vec,z_vec,w_vec);\n\tsize_t bf_idx = 0;\n\tfor(size_t i=0;i<bs.basis.size();i++)\n\t{\n\t\tShell my_shell = bs.basis[i];\n\t\tstd::vector<std::array<size_t,3>> order = opencap_carts_ordering(my_shell.l);\n\t\tfor(size_t j=0;j<my_shell.num_carts();j++)\n\t\t{\n\t\t\tstd::array<size_t,3> cart = order[j];\n\t\t\tmy_shell.evaluate_on_grid(x,y,z,num_points,cart[0],cart[1],cart[2],bf_values.col(bf_idx));\n\t\t\tbf_idx++;\n\t\t}\n\t}\n    cap_vals = Eigen::Map<Eigen::VectorXd>(cap_vec.data(),cap_vec.size());\n\tEigen::MatrixXd bf_prime;\n\tbf_prime =  Eigen::MatrixXd::Zero(num_points,bs.num_carts());\n\tfor(size_t i=0;i<bf_prime.cols();i++)\n\t\tbf_prime.col(i) = bf_values.col(i).array()*cap_vals.array();\n\tcap_mat+=bf_prime.transpose()*bf_values;\n}\n\n\nvoid AOCAP::compute_ao_cap_mat(Eigen::MatrixXd &cap_mat, BasisSet &bs)\n{\n\tif(!do_numerical)\n\t{\n\t\tstd::cout << \"CAP integrals will be computed analytically.\" << std::endl;\n\t\teval_box_cap_analytical(cap_mat,bs);\n\t\treturn;\n\t}\n\telse\n\t\tintegrate_cap_numerical(cap_mat,bs);\n}\n\nvoid AOCAP::eval_box_cap_analytical(Eigen::MatrixXd &cap_mat, BasisSet &bs)\n{\n\tdouble boxlength[3] = {cap_x,cap_y,cap_z};\n\tsize_t bf1_idx = 0;\n\tfor(size_t i=0;i<bs.basis.size();i++)\n\t{\n\t\tShell shell1 = bs.basis[i];\n\t\tstd::vector<std::array<size_t,3>> order1 = opencap_carts_ordering(shell1.l);\n\t\tfor(size_t j=0;j<shell1.num_carts();j++)\n\t\t{\n\t\t\tstd::array<size_t,3> l1 = order1[j];\n\t\t\tsize_t bf2_idx = 0;\n\t\t\tfor (size_t q=0;q<bs.basis.size();q++)\n\t\t\t{\n\t\t\t\tShell shell2 = bs.basis[q];\n\t\t\t\tstd::vector<std::array<size_t,3>> order2 = opencap_carts_ordering(shell2.l);\n\t\t\t\tfor(size_t k=0;k<shell2.num_carts();k++)\n\t\t\t\t{\n\t\t\t\t\tstd::array<size_t,3> l2 = order2[k];\n\t\t\t\t\tcap_mat(bf1_idx+j,bf2_idx+k) = integrate_box_cap(shell1,shell2,l1,l2,boxlength);\n\t\t\t\t}\n\t\t\t\tbf2_idx += shell2.num_carts();\n\t\t\t}\n\t\t}\n\t\tbf1_idx += shell1.num_carts();\n\t}\n}\n\n\nvoid AOCAP::verify_cap_parameters(std::map<std::string,std::string> &parameters)\n{\n\tstd::vector<std::string> missing_keys;\n\tif(parameters.find(\"cap_type\")==parameters.end())\n\t\topencap_throw(\"Error: Missing cap_type keyword.\");\n\tif(compare_strings(parameters[\"cap_type\"],\"box\"))\n\t{\n\t\tif(parameters.find(\"cap_x\")==parameters.end())\n\t\t\tmissing_keys.push_back(\"cap_x\");\n\t\tif(parameters.find(\"cap_y\")==parameters.end())\n\t\t\tmissing_keys.push_back(\"cap_y\");\n\t\tif (parameters.find(\"cap_z\")==parameters.end())\n\t\t\tmissing_keys.push_back(\"cap_z\");\n\t}\n\telse if (compare_strings(parameters[\"cap_type\"],\"voronoi\"))\n\t{\n\t\tif(parameters.find(\"r_cut\")==parameters.end())\n\t\t\tmissing_keys.push_back(\"r_cut\");\n\t}\n\telse if(compare_strings(parameters[\"cap_type\"],\"custom\"))\n\t\t;\n\telse\n\t\topencap_throw(\"Error: only box and voronoi CAPs supported.\");\n\tif(missing_keys.size()!=0)\n\t{\n\t\tstd::string error_str = \"Missing CAP keywords: \";\n\t\tfor (auto key: missing_keys)\n\t\t\terror_str+=key+\" \";\n\t\topencap_throw(error_str);\n\t}\n\tstd::map<std::string, std::string> defaults = {{\"radial_precision\", \"14\"}, {\"angular_points\", \"590\"}};\n\tfor (const auto &pair:defaults)\n\t{\n\t\tif(parameters.find(pair.first)==parameters.end())\n\t\t\tparameters[pair.first]=pair.second;\n\t}\n}\n\n", "meta": {"hexsha": "e5d5bd1be9589b456742b75bb0a05255402d97ae", "size": 11117, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "opencap/src/AOCAP.cpp", "max_stars_repo_name": "SoubhikM/opencap", "max_stars_repo_head_hexsha": "08706ea07e576c96eed32dc224070201781981b2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "opencap/src/AOCAP.cpp", "max_issues_repo_name": "SoubhikM/opencap", "max_issues_repo_head_hexsha": "08706ea07e576c96eed32dc224070201781981b2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "opencap/src/AOCAP.cpp", "max_forks_repo_name": "SoubhikM/opencap", "max_forks_repo_head_hexsha": "08706ea07e576c96eed32dc224070201781981b2", "max_forks_repo_licenses": ["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.740625, "max_line_length": 168, "alphanum_fraction": 0.6441486012, "num_tokens": 2933, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.665410558746814, "lm_q2_score": 0.4843800842769844, "lm_q1q2_score": 0.32231162252457707}}
{"text": "//\n// Copyright (c) 2009, Markus Rickert\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are met:\n//\n// * Redistributions of source code must retain the above copyright notice,\n//   this list of conditions and the following disclaimer.\n// * Redistributions in binary form must reproduce the above copyright notice,\n//   this list of conditions and the following disclaimer in the documentation\n//   and/or other materials provided with the distribution.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n// POSSIBILITY OF SUCH DAMAGE.\n//\n\n#include <iostream>\n#include <memory>\n#include <stdexcept>\n#include <boost/lexical_cast.hpp>\n#include <rl/math/Unit.h>\n#include <rl/mdl/Dynamic.h>\n#include <rl/mdl/XmlFactory.h>\n\nint\nmain(int argc, char** argv)\n{\n\tif (argc < 2)\n\t{\n\t\tstd::cout << \"Usage: rlDynamics2Demo MODELFILE Q1 ... Qn QD1 ... QDn QDD1 ... QDDn\" << std::endl;\n\t\treturn EXIT_FAILURE;\n\t}\n\t\n\ttry\n\t{\n\t\trl::mdl::XmlFactory factory;\n\t\tstd::shared_ptr<rl::mdl::Dynamic> dynamic = std::dynamic_pointer_cast<rl::mdl::Dynamic>(factory.create(argv[1]));\n\t\t\n\t\trl::math::Vector q(dynamic->getDofPosition());\n\t\trl::math::Vector qd(dynamic->getDof());\n\t\trl::math::Vector qdd(dynamic->getDof());\n\t\t\n\t\tfor (std::size_t i = 0; i < dynamic->getDofPosition(); ++i)\n\t\t{\n\t\t\tq(i) = boost::lexical_cast<rl::math::Real>(argv[i + 2]);\n\t\t}\n\t\t\n\t\tfor (std::size_t i = 0; i < dynamic->getDof(); ++i)\n\t\t{\n\t\t\tqd(i) = boost::lexical_cast<rl::math::Real>(argv[i + 2 + dynamic->getDofPosition()]);\n\t\t\tqdd(i) = boost::lexical_cast<rl::math::Real>(argv[i + 2 + dynamic->getDofPosition() + dynamic->getDof()]);\n\t\t}\n\t\t\n\t\tstd::cout << \"===============================================================================\" << std::endl;\n\t\t\n\t\t// forward position\n\t\t\n\t\tdynamic->setPosition(q);\n\t\tdynamic->forwardPosition();\n\t\tconst rl::math::Transform::ConstTranslationPart& position = dynamic->getOperationalPosition(0).translation();\n\t\trl::math::Vector3 orientation = dynamic->getOperationalPosition(0).rotation().eulerAngles(2, 1, 0).reverse();\n\t\tstd::cout << \"x = \" << position.x() << \" m, y = \" << position.y() << \" m, z = \" << position.z() << \" m, a = \" << orientation.x() * rl::math::RAD2DEG << \" deg, b = \" << orientation.y() * rl::math::RAD2DEG << \" deg, c = \" << orientation.z() * rl::math::RAD2DEG << \" deg\" << std::endl;\n\t\t\n\t\tstd::cout << \"===============================================================================\" << std::endl;\n\t\t\n\t\t// forward velocity\n\t\t\n\t\tdynamic->setPosition(q);\n\t\tdynamic->setVelocity(qd);\n\t\tdynamic->forwardVelocity();\n\t\tstd::cout << \"xd = \" << dynamic->getOperationalVelocity(0).linear().transpose() << \" \" << dynamic->getOperationalVelocity(0).angular().transpose() << std::endl;\n\t\t\n\t\tstd::cout << \"-------------------------------------------------------------------------------\" << std::endl;\n\t\t\n\t\t// J\n\t\t\n\t\trl::math::Matrix J(6 * dynamic->getOperationalDof(), dynamic->getDof());\n\t\tdynamic->calculateJacobian(J, false);\n\t\tstd::cout << \"J = \" << std::endl << J << std::endl;\n\t\t\n\t\t// J * qd\n\t\t\n\t\trl::math::Vector Jqd = J * qd;\n\t\tstd::cout << \"xd = J * qd = \" << Jqd.transpose() << std::endl;\n\t\t\n\t\t// J^{-1}\n\t\t\n\t\trl::math::Matrix invJ(dynamic->getDof(), 6 * dynamic->getOperationalDof());\n\t\tdynamic->calculateJacobianInverse(J, invJ);\n\t\tstd::cout << \"J^{-1} = \" << std::endl << invJ << std::endl;\n\t\t\n\t\t// J^{-1} * xd\n\t\t\n\t\trl::math::Vector invJxd = invJ * Jqd;\n\t\tstd::cout << \"qd = J^{-1} * xd = \" << invJxd.transpose() << std::endl;\n\t\t\n\t\tstd::cout << \"===============================================================================\" << std::endl;\n\t\t\n\t\t// forward acceleration\n\t\t\n\t\tdynamic->setPosition(q);\n\t\tdynamic->setVelocity(qd);\n\t\tdynamic->setAcceleration(qdd);\n\t\tdynamic->forwardVelocity();\n\t\tdynamic->forwardAcceleration();\n\t\tstd::cout << \"xdd = \" << dynamic->getOperationalAcceleration(0).linear().transpose() << \" \" << dynamic->getOperationalAcceleration(0).angular().transpose() << std::endl;\n\t\t\n\t\tstd::cout << \"-------------------------------------------------------------------------------\" << std::endl;\n\t\t\n\t\t// Jd * qd\n\t\t\n\t\trl::math::Vector Jdqd(6 * dynamic->getOperationalDof());\n\t\tdynamic->calculateJacobianDerivative(Jdqd, false);\n\t\tstd::cout << \"Jd * qd = \" << Jdqd.transpose() << std::endl;\n\t\t\n\t\t// J * qdd + Jd * qd\n\t\t\n\t\trl::math::Vector JqddJdqd = J * qdd + Jdqd;\n\t\tstd::cout << \"xdd = J * qdd + Jd * qd = \" << JqddJdqd.transpose() << std::endl;\n\t\t\n\t\t// J^{-1} * (xdd - Jd * qd)\n\t\t\n\t\trl::math::Vector invJxddJdqd = invJ * (JqddJdqd - Jdqd);\n\t\tstd::cout << \"qdd = J^{-1} * (xdd - Jd * qd) = \" << invJxddJdqd.transpose() << std::endl;\n\t\t\n\t\tstd::cout << \"===============================================================================\" << std::endl;\n\t\t\n\t\t// inverse dynamics\n\t\t\n\t\tdynamic->setPosition(q);\n\t\tdynamic->setVelocity(qd);\n\t\tdynamic->setAcceleration(qdd);\n\t\tdynamic->inverseDynamics();\n\t\tstd::cout << \"tau = \" << dynamic->getTorque().transpose() << std::endl;\n\t\t\n\t\trl::math::Vector tau = dynamic->getTorque();\n\t\t\n\t\tstd::cout << \"-------------------------------------------------------------------------------\" << std::endl;\n\t\t\n\t\t// M\n\t\t\n\t\trl::math::Matrix M(dynamic->getDof(), dynamic->getDof());\n\t\tdynamic->setPosition(q);\n\t\tdynamic->calculateMassMatrix(M);\n\t\tstd::cout << \"M = \" << std::endl << M << std::endl;\n\t\t\n\t\t// V\n\t\t\n\t\trl::math::Vector V(dynamic->getDof());\n\t\tdynamic->setPosition(q);\n\t\tdynamic->setVelocity(qd);\n\t\tdynamic->calculateCentrifugalCoriolis(V);\n\t\tstd::cout << \"V = \" << V.transpose() << std::endl;\n\t\t\n\t\t// G\n\t\t\n\t\trl::math::Vector G(dynamic->getDof());\n\t\tdynamic->setPosition(q);\n\t\tdynamic->calculateGravity(G);\n\t\tstd::cout << \"G = \" << G.transpose() << std::endl;\n\t\t\n\t\t// M * qdd + V + G\n\t\t\n\t\trl::math::Vector MqddVG = M * qdd + V + G;\n\t\tstd::cout << \"tau = M * qdd + V + G = \" << MqddVG.transpose() << std::endl;\n\t\t\n\t\tstd::cout << \"===============================================================================\" << std::endl;\n\t\t\n\t\t// forward dynamics\n\t\t\n\t\tdynamic->setPosition(q);\n\t\tdynamic->setVelocity(qd);\n\t\tdynamic->setTorque(tau);\n\t\tdynamic->forwardDynamics();\n\t\tstd::cout << \"qdd = \" << dynamic->getAcceleration().transpose() << std::endl;\n\t\t\n\t\tstd::cout << \"-------------------------------------------------------------------------------\" << std::endl;\n\t\t\n\t\t// M^{-1}\n\t\t\n\t\trl::math::Matrix invM(dynamic->getDof(), dynamic->getDof());\n\t\tdynamic->setPosition(q);\n\t\tdynamic->calculateMassMatrixInverse(invM);\n\t\tstd::cout << \"M^{-1} = \" << std::endl << invM << std::endl;\n\t\t\n\t\t// V\n\t\t\n\t\tstd::cout << \"V = \" << V.transpose() << std::endl;\n\t\t\n\t\t// G\n\t\t\n\t\tstd::cout << \"G = \" << G.transpose() << std::endl;\n\t\t\n\t\t// M^{-1} * (tau - V - G)\n\t\t\n\t\trl::math::Vector invMtauVG = invM * (tau - V - G);\n\t\tstd::cout << \"qdd = M^{-1} * (tau - V - G) = \" << invMtauVG.transpose() << std::endl;\n\t\t\n\t\tstd::cout << \"===============================================================================\" << std::endl;\n\t}\n\tcatch (const std::exception& e)\n\t{\n\t\tstd::cout << e.what() << std::endl;\n\t\treturn EXIT_FAILURE;\n\t}\n\t\n\treturn EXIT_SUCCESS;\n}\n", "meta": {"hexsha": "447a6412a52e32137a6b3c781b1b2ab7d7688146", "size": 7810, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "demos/rlDynamics2Demo/rlDynamics2Demo.cpp", "max_stars_repo_name": "jencureboy/rl", "max_stars_repo_head_hexsha": "658cdd8387397261ebf0f52d3bde74aae0379e24", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-11-29T04:44:15.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-29T04:44:15.000Z", "max_issues_repo_path": "demos/rlDynamics2Demo/rlDynamics2Demo.cpp", "max_issues_repo_name": "jencureboy/rl", "max_issues_repo_head_hexsha": "658cdd8387397261ebf0f52d3bde74aae0379e24", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "demos/rlDynamics2Demo/rlDynamics2Demo.cpp", "max_forks_repo_name": "jencureboy/rl", "max_forks_repo_head_hexsha": "658cdd8387397261ebf0f52d3bde74aae0379e24", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.6621004566, "max_line_length": 284, "alphanum_fraction": 0.5553137004, "num_tokens": 2218, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.665410558746814, "lm_q2_score": 0.4843800842769843, "lm_q1q2_score": 0.32231162252457696}}
{"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/JaccardMatch.h\"\n#include \"mps_voxels/AABB.h\"\n#include \"mps_voxels/util/hungarian.hpp\"\n#include <boost/bimap.hpp>\n#include <utility>\n\nnamespace mps\n{\n\nJaccardMatch::JaccardMatch(const cv::Mat& labels1, const cv::Mat& labels2)\n{\n\n\tif (labels1.channels() > 1 || labels1.type() != CV_16U || labels2.channels() > 1 || labels2.type() != CV_16U)\n\t{\n\t\tthrow std::logic_error(\"jaccard() !!! Only works with CV_16U 1-channel Mats\");\n\t}\n\n\tboxes1 = getBBoxes(labels1);\n\tboxes2 = getBBoxes(labels2);\n\n\tint count = 0;\n\tfor (const auto& i : boxes1) { lblIndex1.insert({i.first, count++}); }\n\tcount = 0;\n\tfor (const auto& j : boxes2) { lblIndex2.insert({j.first, count++}); }\n\n\tintersection = Eigen::MatrixXi::Zero(boxes1.size(), boxes2.size());\n\tsize_t dSize = std::max(boxes1.size(), boxes2.size());\n\tIOU = Eigen::MatrixXd::Zero(dSize, dSize);\n\n\tfor (const auto& i : boxes1)\n\t{\n\t\tcv::Mat mask1 = (labels1 == i.first);\n\t\tint count1 = cv::countNonZero(mask1);\n\t\tiSizes.insert({i.first, count1});\n\t\tfor (const auto& j : boxes2)\n\t\t{\n\t\t\tint intersectionCount = 0;\n\t\t\tdouble iou = 0;\n\t\t\t// Prune actual comparisons by starting with bounding boxes\n\t\t\tif (intersect(i.second, j.second))\n\t\t\t{\n\t\t\t\tcv::Mat mask2 = (labels2 == j.first);\n\n\t\t\t\tint count2;\n\t\t\t\tconst auto iter = jSizes.find(j.first);\n\t\t\t\tif (iter == jSizes.end())\n\t\t\t\t{\n\t\t\t\t\tcount2 = cv::countNonZero(mask2);\n\t\t\t\t\tjSizes.insert({j.first, count2});\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tcount2 = iter->second;\n\t\t\t\t}\n\n\t\t\t\tcv::Mat intersectionMask = (mask1 & mask2);\n\n\t\t\t\tintersectionCount = cv::countNonZero(intersectionMask);\n\t\t\t\tint unionCount = count1 + count2 - intersectionCount;\n//\t\t\t    cv::Mat unionMask = (mask1 | mask2); // Optimized to be (|A|+|B|-|AB|)\n\t\t\t\tiou = (intersectionCount) / static_cast<double>(unionCount);\n\t\t\t}\n\t\t\tIOU(lblIndex1.left.at(i.first), lblIndex2.left.at(j.first)) = iou;\n\t\t\tintersection(lblIndex1.left.at(i.first), lblIndex2.left.at(j.first)) = intersectionCount;\n\t\t}\n\t}\n\n\t// If an element in J doesn't intersect anything, it won't have a size computed and cached\n\tfor (const auto& j : boxes2)\n\t{\n\t\tconst auto iter = jSizes.find(j.first);\n\t\tif (iter == jSizes.end())\n\t\t{\n\t\t\tcv::Mat mask2 = (labels2 == j.first);\n\t\t\tint count2 = cv::countNonZero(mask2);\n\t\t\tjSizes.insert({j.first, count2});\n\t\t}\n\t}\n\n\t// Compute the optimal assignment of patches\n\tHungarian H(-IOU);\n\tconst auto& A = H.getAssignment();\n\tboost::bimap<LabelT, LabelT> matches;\n\tfor (size_t i = 0; i < A.size(); ++i)\n\t{\n\t\tif (i >= boxes1.size()) { continue; }\n\t\tif (A[i] >= (int)boxes2.size()) { continue; }\n\t\tmatches.insert({lblIndex1.right.at(i), lblIndex2.right.at(A[i])});\n\t}\n\n\tmatch = {-H.getSolutionCost(), matches};\n}\n\ndouble JaccardMatch::symmetricCover() const\n{\n\tdouble score = 0.0;\n\tEigen::VectorXd iMax = IOU.rowwise().maxCoeff();\n\tfor (const auto& pair : lblIndex1.left)\n\t{\n\t\t// pair is (label, index)\n\t\tscore += iSizes.at(pair.first) * iMax[pair.second];\n\t}\n\tEigen::RowVectorXd jMax = IOU.colwise().maxCoeff();\n\tfor (const auto& pair : lblIndex2.left)\n\t{\n\t\t// pair is (label, index)\n\t\tscore += jSizes.at(pair.first) * jMax[pair.second];\n\t}\n\n\tdouble fullSize = 0;\n\tfor (const auto& i : iSizes) { fullSize += i.second; }\n\treturn score / (2.0 * fullSize);\n}\n\ndouble JaccardMatch::cover() const\n{\n\tdouble score = 0.0;\n\tEigen::VectorXd iMax = IOU.rowwise().maxCoeff();\n\tfor (const auto& pair : lblIndex1.left)\n\t{\n\t\t// pair is (label, index)\n\t\tscore += iSizes.at(pair.first) * iMax[pair.second];\n\t}\n\n\tdouble fullSize = 0;\n\tfor (const auto& i : iSizes) { fullSize += i.second; }\n\treturn score / fullSize;\n}\n\nJaccardMatch3D::LabelBounds\ngetBBoxes(const OccupancyData& labels)\n{\n\tJaccardMatch3D::LabelBounds boxes;\n\tif (!labels.objects.empty())\n\t{\n\t\tfor (const auto& kv : labels.objects)\n\t\t{\n\t\t\tboxes.emplace(kv.first.id, JaccardMatch3D::AABB(kv.second->minExtent, kv.second->maxExtent));\n\t\t}\n\t}\n\telse\n\t{\n\t\tfor (size_t i = 0; i < labels.voxelRegion->num_vertices(); ++i)\n\t\t{\n\t\t\tconst auto val = labels.vertexState[i];\n\t\t\tif (val != mps::VoxelRegion::FREE_SPACE)\n\t\t\t{\n\t\t\t\tconst auto coord = labels.voxelRegion->coordinate_of(labels.voxelRegion->vertex_at(i));\n\t\t\t\tboxes[val].extend(coord);\n\t\t\t}\n\t\t}\n\t}\n\treturn boxes;\n}\n\nstd::set<size_t>\nsparse_matches(const VoxelRegion::VertexLabels& labels,\n               const VoxelRegion::VertexLabels::value_type & id)\n{\n\tstd::set<size_t> res;\n\tfor (size_t i = 0; i < labels.size(); ++i)\n\t{\n\t\tif (labels[i] == id) { res.insert(i); }\n\t}\n\treturn res;\n}\n\nJaccardMatch3D::JaccardMatch3D(const OccupancyData& labels1, const OccupancyData& labels2)\n{\n//\tif (labels1.channels() > 1 || labels1.type() != CV_16U || labels2.channels() > 1 || labels2.type() != CV_16U)\n//\t{\n//\t\tthrow std::logic_error(\"jaccard() !!! Only works with CV_16U 1-channel Mats\");\n//\t}\n\tassert(labels1.voxelRegion->num_vertices() == labels1.vertexState.size());\n\tassert(labels2.voxelRegion->num_vertices() == labels2.vertexState.size());\n\tassert(labels1.voxelRegion->num_vertices() == labels2.voxelRegion->num_vertices());\n\n\tboxes1 = getBBoxes(labels1);\n\tboxes2 = getBBoxes(labels2);\n\n\tint count = 0;\n\tfor (const auto& i : boxes1) { lblIndex1.insert({i.first, count++}); }\n\tcount = 0;\n\tfor (const auto& j : boxes2) { lblIndex2.insert({j.first, count++}); }\n\n\tintersection = Eigen::MatrixXi::Zero(boxes1.size(), boxes2.size());\n\tsize_t dSize = std::max(boxes1.size(), boxes2.size());\n\tIOU = Eigen::MatrixXd::Zero(dSize, dSize);\n\n\tfor (const auto& i : boxes1)\n\t{\n\t\tconst auto mask1 = sparse_matches(labels1.vertexState, i.first);\n\t\tint count1 = mask1.size();\n\t\tiSizes.insert({i.first, count1});\n\t\tfor (const auto& j : boxes2)\n\t\t{\n\t\t\tint intersectionCount = 0;\n\t\t\tdouble iou = 0;\n\t\t\t// Prune actual comparisons by starting with bounding boxes\n\t\t\tif (i.second.intersects(j.second))\n\t\t\t{\n\t\t\t\tconst auto mask2 = sparse_matches(labels2.vertexState, j.first);\n\n\t\t\t\tint count2;\n\t\t\t\tconst auto iter = jSizes.find(j.first);\n\t\t\t\tif (iter == jSizes.end())\n\t\t\t\t{\n\t\t\t\t\tcount2 = mask2.size();\n\t\t\t\t\tjSizes.insert({j.first, count2});\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tcount2 = iter->second;\n\t\t\t\t}\n\n\t\t\t\tstd::vector<size_t> intersectionMask;\n\t\t\t\tstd::vector<int> crossover;\n\t\t\t\tstd::set_intersection(mask1.begin(), mask1.end(), mask2.begin(), mask2.end(), std::back_inserter(intersectionMask));\n\n\t\t\t\tintersectionCount = intersectionMask.size();\n\t\t\t\tint unionCount = count1 + count2 - intersectionCount;\n//\t\t\t    cv::Mat unionMask = (mask1 | mask2); // Optimized to be (|A|+|B|-|AB|)\n\t\t\t\tiou = (intersectionCount) / static_cast<double>(unionCount);\n\t\t\t}\n\t\t\tIOU(lblIndex1.left.at(i.first), lblIndex2.left.at(j.first)) = iou;\n\t\t\tintersection(lblIndex1.left.at(i.first), lblIndex2.left.at(j.first)) = intersectionCount;\n\t\t}\n\t}\n\n\t// If an element in J doesn't intersect anything, it won't have a size computed and cached\n\tfor (const auto& j : boxes2)\n\t{\n\t\tconst auto iter = jSizes.find(j.first);\n\t\tif (iter == jSizes.end())\n\t\t{\n\t\t\tconst auto mask2 = sparse_matches(labels2.vertexState, j.first);\n\t\t\tint count2 = mask2.size();\n\t\t\tjSizes.insert({j.first, count2});\n\t\t}\n\t}\n\n\t// Compute the optimal assignment of patches\n\tHungarian H(-IOU);\n\tconst auto& A = H.getAssignment();\n\tboost::bimap<LabelT, LabelT> matches;\n\tfor (size_t i = 0; i < A.size(); ++i)\n\t{\n\t\tif (i >= boxes1.size()) { continue; }\n\t\tif (A[i] >= (int)boxes2.size()) { continue; }\n\t\tmatches.insert({lblIndex1.right.at(i), lblIndex2.right.at(A[i])});\n\t}\n\n\tmatch = {-H.getSolutionCost(), matches};\n}\n\ndouble JaccardMatch3D::symmetricCover() const\n{\n\tdouble score = 0.0;\n\tEigen::VectorXd iMax = IOU.rowwise().maxCoeff();\n\tfor (const auto& pair : lblIndex1.left)\n\t{\n\t\t// pair is (label, index)\n\t\tscore += iSizes.at(pair.first) * iMax[pair.second];\n\t}\n\tEigen::RowVectorXd jMax = IOU.colwise().maxCoeff();\n\tfor (const auto& pair : lblIndex2.left)\n\t{\n\t\t// pair is (label, index)\n\t\tscore += jSizes.at(pair.first) * jMax[pair.second];\n\t}\n\n\tdouble fullSize = 0;\n\tfor (const auto& i : iSizes) { fullSize += i.second; }\n\treturn score / (2.0 * fullSize);\n}\n\n}\n", "meta": {"hexsha": "c6d4b6595c64b8f2c95589aaf28e34e573667371", "size": 9501, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "mps_voxels/src/mps_voxels/JaccardMatch.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/JaccardMatch.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/JaccardMatch.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": 30.9478827362, "max_line_length": 120, "alphanum_fraction": 0.6728765393, "num_tokens": 2731, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6297746074044134, "lm_q2_score": 0.5117166047041654, "lm_q1q2_score": 0.3222661238298851}}
{"text": "// Copyright 2015-2022 The ALMA Project Developers\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//   http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n// implied. See the License for the specific language governing\n// permissions and limitations under the License.\n\n/// @file\n/// Implements full BTE calculations defined in nanos.hpp.\n\n#include <iostream>\n#include <map>\n#include <Eigen/Dense>\n#include <Eigen/Sparse>\n#include <unordered_map>\n#include <Eigen/IterativeLinearSolvers>\n#include <unsupported/Eigen/src/IterativeSolvers/Scaling.h>\n#include <unsupported/Eigen/src/IterativeSolvers/GMRES.h>\n\n#include <utilities.hpp>\n#include <nanos.hpp>\n#include <vasp_io.hpp>\n\n/// TBB stuff\n#include <mutex>\n#include <tbb/parallel_for.h>\n#include <tbb/concurrent_vector.h>\n#include <tbb/concurrent_unordered_map.h>\n\n\nnamespace alma {\nnamespace nanos {\n\n\ndouble scale_tau_nanowire(double tau0,\n                          const Eigen::Ref<const Eigen::Vector3d>& uaxis,\n                          const Eigen::Ref<const Eigen::Vector3d>& vel,\n                          double R) {\n    /// Calculate the velocity vector projected onto a\n    /// plane with normal vector equal to uaxis\n    Eigen::Vector3d vrho_xyz = vel - vel.dot(uaxis) * uaxis;\n\n    double vrho = vrho_xyz.norm();\n    double mfp = vrho * tau0;\n\n    if (alma::almost_equal(mfp, 0.)) {\n        return tau0;\n    }\n\n\n    return tau0 *\n           (1 - 2 / (R * R) * mfp * (mfp * (std::exp(-R / mfp) - 1) + R));\n}\n\ndouble scale_tau_nanoribbon(double tau0,\n                            const Eigen::Ref<const Eigen::Vector3d>& uaxis,\n                            const Eigen::Ref<const Eigen::Vector3d>& vel,\n                            double L) {\n    /// It is supposed that the z axis is the one discarded\n\n\n    /// Change-of-base matrices to xy coordinates with\n    /// y-axis equal to uaxis\n    static Eigen::Matrix2d B = Eigen::Matrix2d::Zero();\n    static Eigen::Matrix2d Binv;\n\n    /// If not inited fill B and its inverse\n    if (alma::almost_equal(B.sum(), 0.)) {\n        if (!alma::almost_equal(uaxis(2), 0.)) {\n            std::cout << \"ERROR: Nanoribbons are defined in xy plane\"\n                      << std::endl;\n            exit(1);\n        }\n\n        B << uaxis(1), uaxis(0), -uaxis(0), uaxis(1);\n        Binv = B.inverse();\n    }\n\n    /// Calculate velocity in new coordinates\n    Eigen::Vector2d v_cart, v_newcord;\n    v_cart << vel(0), vel(1);\n    v_newcord = Binv * v_cart;\n\n    double mfp = std::abs(tau0 * v_newcord(0));\n\n    if (alma::almost_equal(mfp, 0.)) {\n        return tau0;\n    }\n\n    return tau0 * (mfp / L * (std::exp(-L / mfp) - 1.0) + 1.0);\n}\n\n\ndouble calc_kappa_RTA(const alma::Crystal_structure& poscar,\n                      const alma::Gamma_grid& grid,\n                      const Eigen::Ref<const Eigen::ArrayXXd>& w,\n                      const Eigen::Ref<const Eigen::Vector3d>& uaxis,\n                      const std::string& system_name,\n                      const double limiting_length,\n                      double T) {\n    auto Nbranches =\n        static_cast<std::size_t>(grid.get_spectrum_at_q(0).omega.size());\n\n    if ((static_cast<std::size_t>(w.rows()) != Nbranches) ||\n        (static_cast<std::size_t>(w.cols()) != grid.nqpoints))\n        throw alma::value_error(\"inconsistent dimensions\");\n\n    double kappa = 0.;\n\n    // The Gamma point is ignored.\n    for (decltype(Nbranches) iq = 1; iq < grid.nqpoints; iq++) {\n        auto sp = grid.get_spectrum_at_q(iq);\n\n        for (decltype(Nbranches) im = 0; im < Nbranches; im++) {\n            double tau = (w(im, iq) == 0.) ? 0. : (1. / w(im, iq));\n\n            Eigen::Vector3d vg = sp.vg.col(im);\n            double vgproj = vg.dot(uaxis);\n\n\n            /// Scale the lifetimes\n            if (system_name == \"nanowire\") {\n                tau = scale_tau_nanowire(tau, uaxis, vg, limiting_length);\n            }\n            else if (system_name == \"nanoribbon\") {\n                tau = scale_tau_nanoribbon(tau, uaxis, vg, limiting_length);\n            }\n            else {\n                std::cout << \"ERROR: calc_k not recognized system_name\"\n                          << std::endl;\n                exit(1);\n            }\n\n\n            kappa += alma::bose_einstein_kernel(sp.omega[im], T) * tau *\n                     vgproj * vgproj;\n        }\n    }\n    return (1e21 * alma::constants::kB / poscar.V / grid.nqpoints) * kappa;\n}\n\nvoid get_fullBZ_processes(\n    const alma::Gamma_grid& grid,\n    const alma::Crystal_structure& cell,\n    std::string& anhIFCfile,\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    boost::mpi::communicator& world,\n    double scalebroad_three) {\n    /// Get anharmonic IFC\n    auto anhIFC = alma::load_FORCE_CONSTANTS_3RD(anhIFCfile.c_str(), cell);\n\n    /// First we are getting sizes\n    std::size_t nbands = grid.get_spectrum_at_q(0).omega.size();\n\n    std::size_t my_id = world.rank();\n    std::size_t nprocs = world.size();\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    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                        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                                                scalebroad_three *\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                                            //                                                 0.1 * grid.base_sigma(v2 - 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                                                //                                         Gamma_of_triplet1.compute_vp2(cell,grid,anhIFC);\n                                                vpsXdelta.push_back(\n                                                    Gamma_of_triplet1\n                                                        .compute_gaussian());\n                                            }\n                                            //                                             sigma =\n                                            //                                                 0.1 * grid.base_sigma(v1 - v3);\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                                                //                                         Gamma_of_triplet2.compute_vp2(cell,grid,anhIFC);\n                                                vpsXdelta.push_back(\n                                                    Gamma_of_triplet2\n                                                        .compute_gaussian());\n                                            }\n                                            //                                             sigma =\n                                            //                                                 0.1 * grid.base_sigma(v1 - v2);\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                                                //                                         Gamma_of_triplet3.compute_vp2(cell,grid,anhIFC);\n                                                vpsXdelta.push_back(\n                                                    Gamma_of_triplet3\n                                                        .compute_gaussian());\n                                            }\n                                            /*                                            sigma\n                                               = 0.1 * grid.base_sigma(v2 -\n                                               v1)*/\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                                                //                                         Gamma_of_triplet4.compute_vp2(cell,grid,anhIFC);\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                                            //                                                 0.1 * grid.base_sigma(v2 - 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                                                //                                         Gamma_of_triplet1.compute_vp2(cell,grid,anhIFC);\n                                                vpsXdelta.push_back(\n                                                    Gamma_of_triplet1\n                                                        .compute_gaussian());\n                                            }\n                                            //                                             sigma =\n                                            //                                                 0.1 * grid.base_sigma(v3 - v2);\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                                                //                                         Gamma_of_triplet2.compute_vp2(cell,grid,anhIFC);\n                                                vpsXdelta.push_back(\n                                                    Gamma_of_triplet2\n                                                        .compute_gaussian());\n                                            }\n                                            //                                             sigma =\n                                            //                                                 0.1 * grid.base_sigma(v2 - v1);\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                                                //                                         Gamma_of_triplet3.compute_vp2(cell,grid,anhIFC);\n                                                vpsXdelta.push_back(\n                                                    Gamma_of_triplet3\n                                                        .compute_gaussian());\n                                            }\n                                            //                                             sigma =\n                                            //                                                 0.1 * grid.base_sigma(v3 - v1);\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                                                // Gamma_of_triplet4.compute_vp2(cell,grid,anhIFC);\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(\n                                            SymGamma, 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 (triplet_indexes[0] ==\n                                                    triplet_indexes[1]) {\n                                                    double effective_vp2 =\n                                                        2 * peq.get_vp2();\n                                                    peq.set_vp2(effective_vp2);\n                                                }\n\n                                                if (absorption_processes_tbb\n                                                        .count(\n                                                            triplet_indexes) ==\n                                                    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\n                                                        .count(\n                                                            triplet_indexes) ==\n                                                    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\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\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    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\ndouble calc_kappa_nanos(\n    const alma::Crystal_structure& poscar,\n    const alma::Gamma_grid& grid,\n    const alma::Symmetry_operations& syms,\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    const Eigen::Ref<const Eigen::ArrayXXd>& w0,\n    const Eigen::Ref<const Eigen::Vector3d>& uaxis,\n    const std::string& system_name,\n    const double limiting_length,\n    double T,\n    bool iterative,\n    boost::mpi::communicator& world) {\n    // GATHER INFORMATION FOR FULL BTE SYSTEM AND DECLARE SOME VARIABLES\n\n    int Ngridpoints = grid.nqpoints;\n\n    int Nbranches = grid.get_spectrum_at_q(0).omega.size();\n    int Ntot = Ngridpoints * Nbranches - 3;\n\n    // Unknowns in the linear system\n    Eigen::VectorXd H(Ntot);\n\n    // stores heat capacities of the irreducible points\n    Eigen::VectorXd C(Ntot);\n    C.setConstant(0.0);\n\n    // stores relaxation times of the irreducible points\n    Eigen::VectorXd tau(Ntot);\n    tau.setConstant(0.0);\n\n    // stores phonon frequencies of the irreducible points\n    Eigen::VectorXd omega(Ntot);\n    omega.setConstant(0.0);\n\n    // stores group velocity vectors of the irreducible points\n    Eigen::MatrixXd vg(Ntot, 3);\n    Eigen::VectorXd vgproj(Ntot);\n    vg.fill(0.0);\n\n    // GATHER PHONON PROPERTIES FOR IRREDUCIBLE Q-POINTS\n\n    double C_factor = 1e27 * alma::constants::kB / Ngridpoints / poscar.V;\n\n    // scan over all points in the grid\n\n    for (int nq = 0; nq < Ngridpoints; nq++) {\n        // spectrum at point\n\n        auto spectrum = grid.get_spectrum_at_q(nq);\n\n\n        for (int nbranch = 0; nbranch < Nbranches; nbranch++) {\n            int imode = nq * Nbranches + nbranch - 3;\n\n            if (imode < 0)\n                continue;\n\n            // store heat capacity\n            C(imode) = C_factor *\n                       alma::bose_einstein_kernel(spectrum.omega[nbranch], T);\n\n\n            // store group velocity vector and projected one\n            Eigen::Vector3d myvg = spectrum.vg.col(nbranch);\n            vg(imode, 0) = myvg(0);\n            vg(imode, 1) = myvg(1);\n            vg(imode, 2) = myvg(2);\n\n            vgproj(imode) = myvg.dot(uaxis);\n\n            // store relaxation time\n            double mytau =\n                (w0(nbranch, nq) == 0.) ? 0. : (1. / w0(nbranch, nq));\n\n            if (system_name == \"nanowire\") {\n                mytau = scale_tau_nanowire(mytau, uaxis, myvg, limiting_length);\n            }\n            else if (system_name == \"nanoribbon\") {\n                mytau =\n                    scale_tau_nanoribbon(mytau, uaxis, myvg, limiting_length);\n            }\n            else {\n                std::cout\n                    << \"ERROR: calc_kappa_nanos not recognized system_name\"\n                    << std::endl;\n                exit(1);\n            }\n\n            tau(imode) = mytau;\n\n            // store phonon frequency\n            omega(imode) = spectrum.omega(nbranch);\n        }\n    }\n\n    typedef std::array<int, 2> idx_pair;\n\n    std::unordered_map<idx_pair, double> A_elements;\n    A_elements.reserve(std::ceil(0.15 * Ntot * Ntot));\n\n    // CALCULATE NON-RTA CONDUCTIVITY BY SOLVING LINEAR SYSTEM\n\n    // build the list of Gamma values for 2-phonon processes\n    for (auto& process_block : isotopic_processes) {\n        auto I = process_block.first.first;\n        auto J = process_block.first.second;\n        A_elements[{static_cast<int>(I - 3), static_cast<int>(J - 3)}] -=\n            process_block.second * tau(I - 3);\n    } // done scanning over all 2-phonon processes\n\n    for (auto& process_block : absorption_processes) {\n        auto process(process_block.second);\n        auto I = process.q[0] * Nbranches + process.alpha[0];\n        auto J = process.q[1] * Nbranches + process.alpha[1];\n        auto K = process.q[2] * Nbranches + process.alpha[2];\n\n        double Gamma = process.compute_gamma(grid, T, true);\n\n        A_elements[{static_cast<int>(I - 3), static_cast<int>(J - 3)}] +=\n            Gamma * tau(I - 3);\n        A_elements[{static_cast<int>(I - 3), static_cast<int>(K - 3)}] -=\n            Gamma * tau(I - 3);\n    }\n\n\n    for (auto& process_block : emission_processes) {\n        auto process(process_block.second);\n        auto I = process.q[0] * Nbranches + process.alpha[0];\n        auto J = process.q[1] * Nbranches + process.alpha[1];\n        auto K = process.q[2] * Nbranches + process.alpha[2];\n\n        double Gamma = process.compute_gamma(grid, T, true);\n\n        A_elements[{static_cast<int>(I - 3), static_cast<int>(J - 3)}] -=\n            0.5 * Gamma * tau(I - 3);\n        A_elements[{static_cast<int>(I - 3), static_cast<int>(K - 3)}] -=\n            0.5 * Gamma * tau(I - 3);\n    }\n\n\n    // diagonal elements in the system\n    for (int diag_idx = 0; diag_idx < Ntot; diag_idx++) {\n        A_elements[{diag_idx, diag_idx}] += 1.0;\n    }\n\n\n    /// Get tripletList\n    std::vector<Eigen::Triplet<double>> tripletList;\n    for (auto& [key, val] : A_elements) {\n        auto idx1 = key[0];\n        auto idx2 = key[1];\n        tripletList.push_back(Eigen::Triplet<double>(idx1, idx2, val));\n    }\n\n    // build system of equations \"A*H = B\"\n\n    Eigen::SparseMatrix<double> A(Ntot, Ntot);\n\n    // Fill sparse matrix\n    A.setFromTriplets(tripletList.begin(), tripletList.end());\n\n    Eigen::VectorXd B(Ntot);\n\n    // projected-components of omega*MFP_RTA over transport axis\n    B = omega.array() * tau.array() * vgproj.array();\n\n    // Transform to compressed format\n\n    A.makeCompressed();\n\n    std::cout << \"#Linear system information\\n\";\n    std::cout << \"**A sparsity \"\n              << static_cast<double>(A.nonZeros()) / (Ntot * Ntot) << std::endl;\n    std::cout.flush();\n\n    // Scale system\n    Eigen::IterScaling<Eigen::SparseMatrix<double>> scal;\n    scal.computeRef(A);\n    B = scal.LeftScaling().cwiseProduct(B);\n\n    // SOLVE SYSTEM\n\n    if (iterative) {\n        Eigen::BiCGSTAB<Eigen::SparseMatrix<double>> solver;\n        // Eigen::GMRES<Eigen::SparseMatrix<double>> solver;\n        solver.compute(A);\n\n        // RTA solution to be used as initial guess\n        Eigen::VectorXd H_guess(Ntot);\n\n        H_guess = omega.array() * tau.array() * vgproj.array();\n\n        H_guess = scal.RightScaling().cwiseInverse().cwiseProduct(H_guess);\n\n        H = solver.solveWithGuess(B, H_guess);\n\n        std::cout << \"# Iterative solver information:\\n\" << std::endl;\n        std::cout << \"# -iterations:     \" << solver.iterations() << std::endl;\n        std::cout << \"# -estimated error: \" << solver.error() << std::endl;\n    }\n\n    else {\n        H = omega.array() * tau.array() * vgproj.array();\n    }\n\n    double rel_err = (A * H - B).norm() / B.norm();\n\n    if (rel_err > 1e-3) {\n        std::cout << \"alma::beyondRTA::calc_kappa_nanos > WARNING:\"\n                  << std::endl;\n        std::cout << \"solution of linear system might be unstable.\"\n                  << std::endl;\n        std::cout << \"Relative error metric = \" << rel_err << std::endl;\n    }\n\n    // Scale back the solution\n    H = scal.RightScaling().cwiseProduct(H);\n\n    // PROCESS THE LINEAR SYSTEM SOLUTION\n\n    // construct \"generalised MFPs\"\n    Eigen::VectorXd MFP_nonRTA(Ntot);\n    MFP_nonRTA = H.array() / omega.array();\n\n    // fix potential NaN/Inf problems\n    for (int n = 0; n < Ntot; n++) {\n        if (omega(n) <= 0.0) {\n            MFP_nonRTA(n) = 0.0;\n        }\n    }\n\n    // CALCULATE NON-RTA CONDUCTIVITY\n\n    double kappa_nano = 0.0;\n    for (int nq = 0; nq < Ngridpoints; nq++) {\n        for (int nbranch = 0; nbranch < Nbranches; nbranch++) {\n            int imode = nq * Nbranches + nbranch - 3;\n\n            if (imode < 0)\n                continue;\n\n            kappa_nano += 1e-6 * C(imode) * MFP_nonRTA(imode) * vgproj(imode);\n        }\n    }\n\n    // RETURN RESULT\n    return kappa_nano;\n\n} // end of calc_kappa_nanos\n} // namespace nanos\n} // end of namespace alma\n", "meta": {"hexsha": "30e44a9edcc9fedfda6d06a18dc6fc03b6a39874", "size": 42231, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/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/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/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": 46.6125827815, "max_line_length": 139, "alphanum_fraction": 0.3660344297, "num_tokens": 7634, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6442251064863697, "lm_q2_score": 0.5, "lm_q1q2_score": 0.32211255324318483}}
{"text": "/*\n * ****** Graph Algorithms using Boost Graph Library ********\n *\n * Variable elimination ordering heuristics developed by Cyril Terrioux <cyril.terrioux@lsis.org>\n */\n\n#include \"core/tb2wcsp.hpp\"\n#include \"core/tb2binconstr.hpp\"\n#include \"core/tb2knapsack.hpp\"\n#include \"core/tb2naryconstr.hpp\"\n\n#ifdef BOOST\n#include <boost/config.hpp>\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/graph_utility.hpp>\n#include <boost/graph/graphviz.hpp>\n#include <boost/graph/connected_components.hpp>\n#include <boost/graph/biconnected_components.hpp>\n#include <boost/graph/johnson_all_pairs_shortest.hpp>\n#include <boost/graph/minimum_degree_ordering.hpp>\n#include <boost/graph/prim_minimum_spanning_tree.hpp>\n#include <boost/graph/cuthill_mckee_ordering.hpp>\n\nusing namespace boost;\n\nnamespace boost {\nstruct edge_component_t {\n    enum { num = 555 };\n    typedef edge_property_tag kind;\n} edge_component;\n}\n\ntypedef adjacency_list<setS, vecS, undirectedS> Graph;\ntypedef adjacency_list<setS, vecS, directedS> DirectedGraph;\ntypedef adjacency_list<setS, vecS, undirectedS, no_property,\n    property<edge_weight_t, int, property<edge_component_t, std::size_t>>>\n    IntWeightedGraph;\ntypedef adjacency_list<setS, vecS, undirectedS, no_property,\n    property<edge_weight_t, double, property<edge_component_t, std::size_t>>>\n    DoubleWeightedGraph;\ntypedef adjacency_list<setS, vecS, undirectedS, property<vertex_color_t, default_color_type, property<vertex_degree_t, int>>> ColoredGraph;\n\ntemplate <typename T>\nstatic void addConstraint(Constraint* c, T& g)\n{\n    int a = c->arity();\n    for (int i = 0; i < a; i++) {\n        for (int j = i + 1; j < a; j++) {\n            Variable* vari = c->getVar(i);\n            Variable* varj = c->getVar(j);\n            add_edge(vari->wcspIndex, varj->wcspIndex, g);\n        }\n    }\n}\n\nstatic void addConstraint(Constraint* c, DirectedGraph& g)\n{\n    int a = c->arity();\n    for (int i = 0; i < a; i++) {\n        for (int j = i + 1; j < a; j++) {\n            Variable* vari = c->getVar(i);\n            Variable* varj = c->getVar(j);\n            add_edge(vari->wcspIndex, varj->wcspIndex, g);\n            add_edge(varj->wcspIndex, vari->wcspIndex, g);\n        }\n    }\n}\n\nstatic void addConstraint(Constraint* c, IntWeightedGraph& g, int weight = 1)\n{\n    property_map<IntWeightedGraph, edge_weight_t>::type weights = get(edge_weight, g);\n    int a = c->arity();\n    for (int i = 0; i < a; i++) {\n        for (int j = i + 1; j < a; j++) {\n            Variable* vari = c->getVar(i);\n            Variable* varj = c->getVar(j);\n            weights[add_edge(vari->wcspIndex, varj->wcspIndex, g).first] = weight;\n        }\n    }\n}\n\nstatic void addConstraint(Constraint* c, DoubleWeightedGraph& g, double maxweight = 1000000)\n{\n    property_map<DoubleWeightedGraph, edge_weight_t>::type weights = get(edge_weight, g);\n    int a = c->arity();\n    for (int i = 0; i < a; i++) {\n        for (int j = i + 1; j < a; j++) {\n            Variable* vari = c->getVar(i);\n            Variable* varj = c->getVar(j);\n            weights[add_edge(vari->wcspIndex, varj->wcspIndex, g).first] = maxweight - c->getTightness();\n        }\n    }\n}\n\nint WCSP::connectedComponents()\n{\n    Graph G;\n    for (unsigned int i = 0; i < vars.size(); i++)\n        add_vertex(G);\n    for (unsigned int i = 0; i < constrs.size(); i++)\n        if (constrs[i]->connected() && !constrs[i]->universal())\n            addConstraint(constrs[i], G);\n    for (int i = 0; i < elimBinOrder; i++)\n        if (elimBinConstrs[i]->connected())\n            addConstraint(elimBinConstrs[i], G);\n    for (int i = 0; i < elimTernOrder; i++)\n        if (elimTernConstrs[i]->connected())\n            addConstraint(elimTernConstrs[i], G);\n    vector<int> component(num_vertices(G));\n    int num = connected_components(G, &component[0]);\n    vector<int> cctruesize(num, 0);\n    for (size_t i = 0; i < num_vertices(G); ++i) {\n        assert(component[i] >= 0 && component[i] < num);\n        if (unassigned(i))\n            cctruesize[component[i]]++;\n    }\n    int res = 0;\n    char c = '(';\n    for (int i = 0; i < num; ++i) {\n        if (cctruesize[i] >= 1) {\n            res++;\n            cout << c << cctruesize[i];\n            c = ' ';\n        }\n    }\n    cout << \")\";\n\n    return res;\n}\n\nint WCSP::biConnectedComponents()\n{\n    IntWeightedGraph G;\n    for (unsigned int i = 0; i < vars.size(); i++)\n        add_vertex(G);\n    for (unsigned int i = 0; i < constrs.size(); i++)\n        if (constrs[i]->connected())\n            addConstraint(constrs[i], G);\n    for (int i = 0; i < elimBinOrder; i++)\n        if (elimBinConstrs[i]->connected())\n            addConstraint(elimBinConstrs[i], G);\n    for (int i = 0; i < elimTernOrder; i++)\n        if (elimTernConstrs[i]->connected())\n            addConstraint(elimTernConstrs[i], G);\n    property_map<IntWeightedGraph, edge_component_t>::type component = get(edge_component, G);\n\n    int num = biconnected_components(G, component);\n\n    vector<int> art_points;\n    articulation_points(G, back_inserter(art_points));\n    cout << \"Articulation points: \" << art_points.size() << endl;\n    if (art_points.size() > 0) {\n        for (unsigned int i = 0; i < art_points.size(); i++)\n            cout << \" \" << art_points[i];\n        cout << endl;\n    }\n    return num;\n}\n\nint WCSP::diameter()\n{\n    if (vars.size() >= LARGE_NB_VARS)\n        return -1;\n\n    IntWeightedGraph G;\n    for (unsigned int i = 0; i < vars.size(); i++)\n        add_vertex(G);\n    for (unsigned int i = 0; i < constrs.size(); i++)\n        if (constrs[i]->connected())\n            addConstraint(constrs[i], G);\n    for (int i = 0; i < elimBinOrder; i++)\n        if (elimBinConstrs[i]->connected())\n            addConstraint(elimBinConstrs[i], G);\n    for (int i = 0; i < elimTernOrder; i++)\n        if (elimTernConstrs[i]->connected())\n            addConstraint(elimTernConstrs[i], G);\n\n    typedef int* int_ptr;\n    int** D;\n    D = new int_ptr[num_vertices(G)];\n    for (unsigned int i = 0; i < num_vertices(G); ++i)\n        D[i] = new int[num_vertices(G)];\n    johnson_all_pairs_shortest_paths(G, D);\n\n    if (ToulBar2::verbose >= 2) {\n        cout << \"     \";\n        for (unsigned int i = 0; i < num_vertices(G); ++i) {\n            cout << i << \" -> \";\n            for (unsigned int j = 0; j < num_vertices(G); ++j) {\n                cout << \" \" << D[i][j];\n            }\n            cout << endl;\n        }\n    }\n\n    int maxd = 0;\n    double meand = 0;\n    for (unsigned int i = 0; i < num_vertices(G); ++i) {\n        for (unsigned int j = 0; j < num_vertices(G); ++j) {\n            if (D[i][j] > maxd)\n                maxd = D[i][j];\n            meand += D[i][j];\n        }\n    }\n    meand /= num_vertices(G) * num_vertices(G);\n    if (ToulBar2::verbose >= 1) {\n        cout << \"Mean diameter: \" << meand << endl;\n    }\n\n    for (unsigned int i = 0; i < num_vertices(G); ++i)\n        delete[] D[i];\n    delete[] D;\n\n    return maxd;\n}\n\ninline bool cmp_vars(Variable* v1, Variable* v2) { return (v1->wcspIndex < v2->wcspIndex); }\n\n/// \\brief Minimum Degree Ordering algorithm\n/// \\warning Output order usually worse than WCSP::minimumDegreeOrdering ???\nvoid WCSP::minimumDegreeOrderingBGL(vector<int>& order_inv)\n{\n    DirectedGraph G;\n    for (unsigned int i = 0; i < vars.size(); i++)\n        add_vertex(G);\n    for (unsigned int i = 0; i < constrs.size(); i++)\n        if (constrs[i]->connected())\n            addConstraint(constrs[i], G);\n    for (int i = 0; i < elimBinOrder; i++)\n        if (elimBinConstrs[i]->connected())\n            addConstraint(elimBinConstrs[i], G);\n    for (int i = 0; i < elimTernOrder; i++)\n        if (elimTernConstrs[i]->connected())\n            addConstraint(elimTernConstrs[i], G);\n\n    int n = num_vertices(G);\n    int delta = 0;\n    typedef vector<int> Vector;\n    Vector inverse_perm(n, 0);\n    Vector perm(n, 0);\n\n    Vector supernode_sizes(n, 1); // init has to be 1\n\n    property_map<DirectedGraph, vertex_index_t>::type id = get(vertex_index, G);\n\n    Vector degree(n, 0);\n\n    minimum_degree_ordering(G,\n        make_iterator_property_map(&degree[0], id, degree[0]),\n        &inverse_perm[0],\n        &perm[0],\n        make_iterator_property_map(&supernode_sizes[0], id, supernode_sizes[0]),\n        delta,\n        id);\n\n    order_inv = inverse_perm;\n    if (ToulBar2::verbose >= 1) {\n        cout << \"Minimum degree ordering:\";\n        for (size_t i = 0; i < num_vertices(G); ++i) {\n            cout << \" \" << order_inv[i];\n        }\n        cout << endl;\n    }\n\n    // // \\bug reordering of vars array is dubious!!! (invalidates further use of variable indexes)\n    // for (size_t i=0; i < num_vertices(G); ++i) {\n    //    vars[i]->wcspIndex = num_vertices(G) - perm[i] - 1;\n    //  }\n    //  stable_sort(vars.begin(), vars.end(), cmp_vars);\n    //  for (size_t i=0; i < num_vertices(G); ++i) {\n    //    assert(vars[i]->wcspIndex == (int) i);\n    //  }\n\n    assert(order_inv.size() == numberOfVariables());\n}\n\nvoid WCSP::spanningTreeOrderingBGL(vector<int>& order_inv)\n{\n    double alltight = 0;\n    double maxt = 0;\n    for (unsigned int i = 0; i < constrs.size(); i++)\n        if (constrs[i]->connected()) {\n            double t = constrs[i]->getTightness();\n            alltight += t;\n            if (t > maxt)\n                maxt = t;\n        }\n    for (int i = 0; i < elimBinOrder; i++)\n        if (elimBinConstrs[i]->connected()) {\n            double t = elimBinConstrs[i]->getTightness();\n            alltight += t;\n            if (t > maxt)\n                maxt = t;\n        }\n    for (int i = 0; i < elimTernOrder; i++)\n        if (elimTernConstrs[i]->connected()) {\n            double t = elimTernConstrs[i]->getTightness();\n            alltight += t;\n            if (t > maxt)\n                maxt = t;\n        }\n\n    DoubleWeightedGraph G;\n    for (unsigned int i = 0; i < vars.size(); i++)\n        add_vertex(G);\n    for (unsigned int i = 0; i < constrs.size(); i++)\n        if (constrs[i]->connected())\n            addConstraint(constrs[i], G, maxt);\n    for (int i = 0; i < elimBinOrder; i++)\n        if (elimBinConstrs[i]->connected())\n            addConstraint(elimBinConstrs[i], G, maxt);\n    for (int i = 0; i < elimTernOrder; i++)\n        if (elimTernConstrs[i]->connected())\n            addConstraint(elimTernConstrs[i], G, maxt);\n\n    int n = num_vertices(G);\n\n    vector<graph_traits<DoubleWeightedGraph>::vertex_descriptor> p(n);\n    prim_minimum_spanning_tree(G, &p[0]);\n\n    double tight = 0;\n    bool tightok = true;\n    vector<int> roots;\n    vector<vector<int>> listofsuccessors(n, vector<int>());\n    if (ToulBar2::verbose >= 0)\n        cout << \"Maximum spanning tree ordering\"; // << endl;\n    for (size_t i = 0; i != p.size(); ++i) {\n        if (p[i] != i) {\n            BinaryConstraint* bctr = getVar(i)->getConstr(getVar(p[i]));\n            if (bctr) {\n                //      cout << \"parent[\" << i << \"] = \" << p[i] << \" (\" << bctr->getTightness() << \")\" << endl;\n                tight += bctr->getTightness();\n            } else {\n                tightok = false;\n            }\n            listofsuccessors[p[i]].push_back(i);\n        } else {\n            roots.push_back(i);\n            //      cout << \"parent[\" << i << \"] = no parent\" << endl;\n        }\n    }\n    if (ToulBar2::verbose >= 0) {\n        if (tightok)\n            cout << \" (\" << 100.0 * tight / alltight << \"%)\";\n        cout << endl;\n    }\n\n    vector<bool> marked(n, false);\n    for (int i = roots.size() - 1; i >= 0; i--) {\n        visit(roots[i], order_inv, marked, listofsuccessors);\n    }\n    for (int i = n - 1; i >= 0; i--) {\n        if (!marked[i]) {\n            visit(i, order_inv, marked, listofsuccessors);\n        }\n    }\n\n    if (ToulBar2::verbose >= 1) {\n        cout << \"Maximum spanning tree ordering:\";\n        for (int i = 0; i < n; i++) {\n            cout << \" \" << order_inv[i];\n        }\n        cout << endl;\n    }\n\n    assert(order_inv.size() == numberOfVariables());\n}\n\nvoid WCSP::reverseCuthillMcKeeOrderingBGL(vector<int>& order_inv)\n{\n    ColoredGraph G;\n    for (unsigned int i = 0; i < vars.size(); i++)\n        add_vertex(G);\n    for (unsigned int i = 0; i < constrs.size(); i++)\n        if (constrs[i]->connected())\n            addConstraint(constrs[i], G);\n    for (int i = 0; i < elimBinOrder; i++)\n        if (elimBinConstrs[i]->connected())\n            addConstraint(elimBinConstrs[i], G);\n    for (int i = 0; i < elimTernOrder; i++)\n        if (elimTernConstrs[i]->connected())\n            addConstraint(elimTernConstrs[i], G);\n\n    int n = num_vertices(G);\n    vector<int> inverse_perm(n, 0);\n\n    cuthill_mckee_ordering(G, inverse_perm.rbegin(), get(vertex_color, G), make_degree_map(G));\n    order_inv = inverse_perm;\n    if (ToulBar2::verbose >= 1) {\n        cout << \"Reverse Cuthill-McKee ordering:\";\n        for (size_t i = 0; i < num_vertices(G); ++i) {\n            cout << \" \" << order_inv[i];\n        }\n        cout << endl;\n    }\n\n    assert(order_inv.size() == numberOfVariables());\n}\n\n/// \\brief Maximum Cardinality Search algorithm (Tarjan & Yannakakis)\n/// \\note code from Cyril Terrioux\nvoid WCSP::maximumCardinalitySearch(vector<int>& order_inv)\n{\n    Graph G;\n    for (unsigned int i = 0; i < vars.size(); i++)\n        add_vertex(G);\n    for (unsigned int i = 0; i < constrs.size(); i++)\n        if (constrs[i]->connected())\n            addConstraint(constrs[i], G);\n    for (int i = 0; i < elimBinOrder; i++)\n        if (elimBinConstrs[i]->connected())\n            addConstraint(elimBinConstrs[i], G);\n    for (int i = 0; i < elimTernOrder; i++)\n        if (elimTernConstrs[i]->connected())\n            addConstraint(elimTernConstrs[i], G);\n\n    int n = num_vertices(G);\n    vector<int> inverse_perm(n, 0);\n\n    vector<vector<int>> sets(n, vector<int>(n));\n    vector<int> size(n);\n    vector<int> card(n);\n    vector<int> degree(n);\n\n    Graph::adjacency_iterator neighbourIt, neighbourEnd;\n\n    /* initialize sets, card and size */\n    for (int v = 0; v < n; v++) {\n        size[v] = 0;\n\n        for (int i = 0; i < n; i++)\n            sets[v][i] = 0;\n\n        sets[0][v] = 1;\n        card[v] = 0;\n        degree[v] = boost::degree(v, G);\n    }\n\n    card[0] = n;\n    int i = n - 1;\n    int j = 0;\n    int v = 0;\n\n    while (i >= 0) {\n        /* choose a vertex */\n        int deg = -1;\n        for (int x = 0; x < n; x++)\n            if ((sets[j][x] == 1) && (degree[x] > deg)) {\n                v = x;\n                deg = degree[x];\n            }\n        sets[j][v] = 0;\n        card[j]--;\n\n        /* build the order */\n        inverse_perm[i] = v;\n        size[v] = -1;\n\n        /* update sets and size */\n        boost::tie(neighbourIt, neighbourEnd) = adjacent_vertices(v, G);\n        for (; neighbourIt != neighbourEnd; ++neighbourIt) {\n            if (size[*neighbourIt] >= 0) {\n                sets[size[*neighbourIt]][*neighbourIt] = 0;\n                card[size[*neighbourIt]]--;\n\n                size[*neighbourIt]++;\n\n                sets[size[*neighbourIt]][*neighbourIt] = 1;\n                card[size[*neighbourIt]]++;\n            }\n        }\n\n        i--;\n        j++;\n        while ((j >= 0) && (card[j] == 0))\n            j--;\n    }\n\n    order_inv = inverse_perm;\n    if (ToulBar2::verbose >= 1) {\n        cout << \"MCS ordering:\";\n        for (size_t i = 0; i < num_vertices(G); ++i) {\n            cout << \" \" << order_inv[i];\n        }\n        cout << endl;\n    }\n    assert(order_inv.size() == numberOfVariables());\n}\n\n/// \\brief Minimum Fill-In Ordering algorithm\n/// \\note code from Cyril Terrioux\nvoid WCSP::minimumFillInOrdering(vector<int>& order_inv)\n{\n    Graph G;\n    for (unsigned int i = 0; i < vars.size(); i++)\n        add_vertex(G);\n    for (unsigned int i = 0; i < constrs.size(); i++)\n        if (constrs[i]->connected())\n            addConstraint(constrs[i], G);\n    for (int i = 0; i < elimBinOrder; i++)\n        if (elimBinConstrs[i]->connected())\n            addConstraint(elimBinConstrs[i], G);\n    for (int i = 0; i < elimTernOrder; i++)\n        if (elimTernConstrs[i]->connected())\n            addConstraint(elimTernConstrs[i], G);\n\n    int n = num_vertices(G);\n    vector<int> order(n, -1);\n    order_inv = order;\n\n    vector<int> nb_fillin(n, 0);\n    vector<int> degree(n, 0);\n\n    Graph::adjacency_iterator neighbourIt, neighbourEnd;\n\n    for (int v = 0; v < n; v++) {\n        degree[v] = boost::degree(v, G);\n        /* compute initial number of edges to add for each vertex */\n        boost::tie(neighbourIt, neighbourEnd) = adjacent_vertices(v, G);\n        for (; neighbourIt != neighbourEnd; ++neighbourIt) {\n            Graph::adjacency_iterator neighbourIt2 = neighbourIt;\n            for (++neighbourIt2; neighbourIt2 != neighbourEnd; ++neighbourIt2) {\n                if (!edge(*neighbourIt, *neighbourIt2, G).second)\n                    nb_fillin[v]++;\n            }\n        }\n    }\n    for (int i = 0; i < n - 1; i++) {\n        /* compute number of fill-in edges to add for each unprocessed vertex */\n        /* choose vertex with minimum fill-in */\n        int v = 0;\n        Long minfill = (Long)n * n;\n        int deg = -1;\n        for (int x = 0; x < n; x++) {\n            if ((order[x] == -1) && ((nb_fillin[x] < minfill) || ((nb_fillin[x] == minfill) && (degree[x] > deg)))) {\n                v = x;\n                minfill = nb_fillin[x];\n                deg = degree[x];\n            }\n        }\n        order[v] = i;\n        order_inv[i] = v;\n\n        /* remove vertex v from nb_fillin */\n        boost::tie(neighbourIt, neighbourEnd) = adjacent_vertices(v, G);\n        for (; neighbourIt != neighbourEnd; ++neighbourIt) {\n            if (order[*neighbourIt] == -1) {\n                Graph::adjacency_iterator neighbourIt2, neighbourEnd2;\n                boost::tie(neighbourIt2, neighbourEnd2) = adjacent_vertices(*neighbourIt, G);\n                for (; neighbourIt2 != neighbourEnd2; ++neighbourIt2) {\n                    if (order[*neighbourIt2] == -1 && !edge(v, *neighbourIt2, G).second)\n                        nb_fillin[*neighbourIt]--;\n                }\n            }\n        }\n        /* add fill-in edges to G */\n        boost::tie(neighbourIt, neighbourEnd) = adjacent_vertices(v, G);\n        for (; neighbourIt != neighbourEnd; ++neighbourIt) {\n            if (order[*neighbourIt] == -1) {\n                Graph::adjacency_iterator neighbourIt2 = neighbourIt;\n                for (++neighbourIt2; neighbourIt2 != neighbourEnd; ++neighbourIt2) {\n                    if ((order[*neighbourIt2] == -1) && !edge(*neighbourIt, *neighbourIt2, G).second) {\n                        add_edge(*neighbourIt, *neighbourIt2, G);\n                        degree[*neighbourIt]++;\n                        degree[*neighbourIt2]++;\n\n                        unsigned int x = *neighbourIt;\n                        unsigned int y = *neighbourIt2;\n                        /* update nb_fillin with missing edges between x and neighbors of y */\n                        Graph::adjacency_iterator neighbourItX, neighbourEndX;\n                        boost::tie(neighbourItX, neighbourEndX) = adjacent_vertices(x, G);\n                        for (; neighbourItX != neighbourEndX; ++neighbourItX) {\n                            if ((order[*neighbourItX] == -1) && (*neighbourItX != y)) {\n                                if (!edge(y, *neighbourItX, G).second)\n                                    nb_fillin[x]++;\n                                else\n                                    nb_fillin[*neighbourItX]--; /* new added edge between x and y has to be removed from nb_fillin  */\n                            }\n                        }\n                        /* update nb_fillin with missing edges between y and neighbors of x */\n                        Graph::adjacency_iterator neighbourItY, neighbourEndY;\n                        boost::tie(neighbourItY, neighbourEndY) = adjacent_vertices(y, G);\n                        for (; neighbourItY != neighbourEndY; ++neighbourItY) {\n                            if ((order[*neighbourItY] == -1) && (*neighbourItY != x) && !edge(x, *neighbourItY, G).second)\n                                nb_fillin[y]++;\n                        }\n                    }\n                }\n            }\n        }\n    }\n\n    int v = 0;\n    while (order[v] != -1)\n        v++;\n    order[v] = n - 1;\n    order_inv[n - 1] = v;\n    if (ToulBar2::verbose >= 1) {\n        cout << \"Min-fill ordering:\";\n        for (int j = 0; j < n; ++j) {\n            cout << \" \" << getName(order_inv[j]);\n        }\n        cout << endl;\n    }\n    assert(order_inv.size() == numberOfVariables());\n}\n\n/// \\brief Minimum Degree Ordering algorithm\n/// \\note code from Cyril Terrioux\nvoid WCSP::minimumDegreeOrdering(vector<int>& order_inv)\n{\n    Graph G;\n    for (unsigned int i = 0; i < vars.size(); i++)\n        add_vertex(G);\n    for (unsigned int i = 0; i < constrs.size(); i++)\n        if (constrs[i]->connected())\n            addConstraint(constrs[i], G);\n    for (int i = 0; i < elimBinOrder; i++)\n        if (elimBinConstrs[i]->connected())\n            addConstraint(elimBinConstrs[i], G);\n    for (int i = 0; i < elimTernOrder; i++)\n        if (elimTernConstrs[i]->connected())\n            addConstraint(elimTernConstrs[i], G);\n    int n = num_vertices(G);\n    vector<int> order(n, -1);\n    order_inv = order;\n    vector<int> degree(n, 0);\n\n    //    vector<int> preorder;\n    //    reverseCuthillMcKeeOrderingBGL(preorder);\n\n    Graph::adjacency_iterator neighbourIt, neighbourEnd;\n\n    for (int v = 0; v < n; v++) {\n        degree[v] = boost::degree(v, G);\n    }\n    for (int i = 0; i < n - 1; i++) {\n        /* find vertex with minimum degree */\n        int v = 0;\n        int deg_min = n + 1;\n        for (int x = 0; x < n; x++) {\n            //           int x = preorder[xx];\n            if ((order[x] == -1) && (degree[x] < deg_min)) {\n                v = x;\n                deg_min = degree[x];\n            }\n        }\n        order[v] = i;\n        order_inv[i] = v;\n\n        boost::tie(neighbourIt, neighbourEnd) = adjacent_vertices(v, G);\n        for (; neighbourIt != neighbourEnd; ++neighbourIt) {\n            if (order[*neighbourIt] == -1) {\n                degree[*neighbourIt]--;\n                Graph::adjacency_iterator neighbourIt2 = neighbourIt;\n                for (++neighbourIt2; neighbourIt2 != neighbourEnd; ++neighbourIt2) {\n                    if ((order[*neighbourIt2] == -1) && !edge(*neighbourIt, *neighbourIt2, G).second) {\n                        add_edge(*neighbourIt, *neighbourIt2, G);\n                        degree[*neighbourIt]++;\n                        degree[*neighbourIt2]++;\n                    }\n                }\n            }\n        }\n    }\n    int v = 0;\n    while (order[v] != -1)\n        v++;\n    order[v] = n - 1;\n    order_inv[n - 1] = v;\n    if (ToulBar2::verbose >= 1) {\n        cout << \"Minimum degree ordering:\";\n        for (int j = 0; j < n; ++j) {\n            cout << \" \" << order_inv[j];\n        }\n        cout << endl;\n    }\n    assert(order_inv.size() == numberOfVariables());\n}\n\nint cmpValueCost3(const void* p1, const void* p2)\n{\n    Cost c1 = ((ValueCost*)p1)->cost;\n    Cost c2 = ((ValueCost*)p2)->cost;\n    Value v1 = ((ValueCost*)p1)->value;\n    Value v2 = ((ValueCost*)p2)->value;\n    if (c1 < c2)\n        return -1;\n    else if (c1 > c2)\n        return 1;\n    else if (v1 < v2)\n        return -1;\n    else if (v1 > v2)\n        return 1;\n    else\n        return 0;\n}\ntemplate <typename T>\nstatic vector<vector<pair<int, int>>> FindClique(vector<int> scope, T& g)\n{\n    Graph G;\n    for (unsigned int i = 0; i < scope.size(); ++i) {\n        add_vertex(G);\n        add_vertex(G);\n    }\n    for (unsigned int i = 0; i < scope.size(); i++) {\n        for (unsigned int j = i + 1; j < scope.size(); j++) {\n            if (edge(2 * scope[i], 2 * scope[j], g).second)\n                add_edge(2 * i, 2 * j, G);\n            if (edge(2 * scope[i] + 1, 2 * scope[j], g).second)\n                add_edge(2 * i + 1, 2 * j, G);\n            if (edge(2 * scope[i], 2 * scope[j] + 1, g).second)\n                add_edge(2 * i, 2 * j + 1, G);\n            if (edge(2 * scope[i] + 1, 2 * scope[j] + 1, g).second)\n                add_edge(2 * i + 1, 2 * j + 1, G);\n        }\n    }\n    vector<int> Temp;\n    vector<vector<int>> Tempclq;\n    vector<int> order;\n    for (unsigned int i = 0; i < scope.size(); ++i) {\n        order.push_back(i);\n    }\n    if (G.m_vertices[2 * order[0]].m_out_edges.size() > G.m_vertices[2 * order[0] + 1].m_out_edges.size())\n        Temp.push_back(0);\n    else\n        Temp.push_back(1);\n    Tempclq.push_back(Temp);\n    bool ok;\n    unsigned j, k, curr;\n    for (int i = 1; i < (int)order.size(); i++) {\n        ok = false;\n        j = 0;\n        curr = 2 * order[i] + 1;\n        if (G.m_vertices[2 * order[i]].m_out_edges.size() > G.m_vertices[2 * order[i] + 1].m_out_edges.size())\n            curr = 2 * order[order[i]];\n        while (!ok && j < Tempclq.size()) {\n            k = 0;\n            ok = true;\n            while (ok && k < Tempclq[j].size()) {\n                if (!edge(curr, Tempclq[j][k], G).second && !edge(Tempclq[j][k], curr, G).second)\n                    ok = false;\n                k++;\n            }\n            j++;\n        }\n        if (ok) {\n            Tempclq[j - 1].push_back(curr);\n        } else {\n            Temp.clear();\n            Temp.push_back(curr);\n            Tempclq.push_back(Temp);\n        }\n    }\n    vector<vector<pair<int, int>>> clq;\n    vector<pair<int, int>> clq2;\n    for (unsigned int i = 0; i < Tempclq.size(); ++i) {\n        clq2.clear();\n        for (unsigned int l = 0; l < Tempclq[i].size(); ++l) {\n            clq2.push_back(pair(scope[(int)floor(Tempclq[i][l] / 2.0 + 0.1)], Tempclq[i][l] % 2));\n        }\n        if (clq2.size() > 1)\n            clq.push_back(clq2);\n    }\n    return clq;\n}\n\nvoid WCSP::addAMOConstraints()\n{\n    if (ToulBar2::verbose >= 1)\n        cout << \"Add AMO constraints to knapsack contraints.\" << endl;\n    double startCpuTime = cpuTime();\n    double startRealTime = realTime();\n\n    vector<int> Var;\n    Graph G;\n    int count = 0;\n    if (ToulBar2::verbose >= 1)\n        cout << \"Construct Graph of size \" << vars.size() << endl;\n    for (int i = 0; i < (int)vars.size(); ++i) {\n        if (vars[i]->unassigned()) {\n            Var.push_back(i);\n            assert(i == vars[i]->wcspIndex);\n        }\n        add_vertex(G);\n        add_vertex(G);\n    }\n    for (unsigned int varIndex = 0; varIndex < Var.size(); varIndex++) {\n        int size = getDomainSize(Var[varIndex]);\n        ValueCost sorted[size];\n        getEnumDomainAndCost(Var[varIndex], sorted);\n        qsort(sorted, size, sizeof(ValueCost), cmpValueCost3);\n        for (int a = 0; a < size; a++) {\n            int storedepth = Store::getDepth();\n            try {\n                Store::store();\n                assign(Var[varIndex], sorted[a].value);\n            } catch (const Contradiction&) {\n            }\n            for (unsigned int i = 0; i < Var.size(); ++i) {\n                if (vars[Var[i]]->assigned() && i != varIndex) {\n                    add_edge(2 * Var[varIndex] + sorted[a].value, 2 * Var[i] + 1 - vars[Var[i]]->getValue(), G);\n                }\n            }\n            Store::restore(storedepth);\n        }\n    }\n    if (ToulBar2::verbose >= 1)\n        cout << \"Graph done.\" << endl;\n    count = 0;\n    vector<int> scope;\n    vector<int> scope2;\n    vector<vector<pair<int, int>>> clq;\n    int MaxAMO = 0;\n    int total = 0;\n    unsigned int nbconstrs = constrs.size();\n    for (unsigned int i = 0; i < nbconstrs; ++i) {\n        auto* k = dynamic_cast<KnapsackConstraint*>(constrs[i]);\n        if (!k)\n            continue;\n        else {\n            if (constrs[i]->arity() > 3 && constrs[i]->connected()) {\n                scope.clear();\n                scope2.clear();\n                clq.clear();\n                //scope=k->GetOrder();\n                for (int j = 0; j < constrs[i]->arity(); j++) {\n                    if (constrs[i]->getVar(j)->unassigned()) {\n                        scope2.push_back(constrs[i]->getVar(j)->wcspIndex);\n                    }\n                }\n                if (scope2.size() > 3) {\n                    clq = FindClique(scope2, G);\n                    if (clq.size() > 0) {\n                        for (unsigned int j = 0; j < clq.size(); ++j) {\n                            if ((int)clq[j].size() > MaxAMO)\n                                MaxAMO = clq[j].size();\n                            total += clq[j].size();\n                        }\n                        count++;\n                        k->addAMOConstraints(clq, vars, this);\n                    }\n                }\n            }\n        }\n    }\n    if (ToulBar2::verbose >= 0) {\n        if (count>0) cout << count << \" AMO constraint\" << ((count>1)?\"s\":\"\") << \" added with max size \" << MaxAMO;\n        else cout << \"No AMO constraint added\";\n        cout << \" in \" << ((ToulBar2::parallel) ? (realTime() - startRealTime) : (cpuTime() - startCpuTime)) << \" seconds.\" << endl;\n    }\n}\n\n#endif\n\n/* Local Variables: */\n/* c-basic-offset: 4 */\n/* tab-width: 4 */\n/* indent-tabs-mode: nil */\n/* c-default-style: \"k&r\" */\n/* End: */\n", "meta": {"hexsha": "361a4908309fa236900337fac944113089359e82", "size": 29164, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/utils/tb2boostgraph.cpp", "max_stars_repo_name": "Pierre-Mont/toulbar2", "max_stars_repo_head_hexsha": "623b92d593eab2dc1e21df9f853c28cc84626ed6", "max_stars_repo_licenses": ["MIT"], "max_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/tb2boostgraph.cpp", "max_issues_repo_name": "Pierre-Mont/toulbar2", "max_issues_repo_head_hexsha": "623b92d593eab2dc1e21df9f853c28cc84626ed6", "max_issues_repo_licenses": ["MIT"], "max_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/tb2boostgraph.cpp", "max_forks_repo_name": "Pierre-Mont/toulbar2", "max_forks_repo_head_hexsha": "623b92d593eab2dc1e21df9f853c28cc84626ed6", "max_forks_repo_licenses": ["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.8329466357, "max_line_length": 139, "alphanum_fraction": 0.5144356055, "num_tokens": 8203, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6757646010190476, "lm_q2_score": 0.47657965106367595, "lm_q1q2_score": 0.3220556577548419}}
{"text": "/* Copyright (C) 2011 Ion Torrent Systems, Inc. All Rights Reserved */\n#include <cassert>\n#include <cmath>\n#include <algorithm>\n#include <deque>\n#include <functional>\n#include <iostream>\n#include <iomanip>\n#include <numeric>\n#include <set>\n#include <string>\n#include <vector>\n#include <fenv.h>\n#include <armadillo>\n#include \"Mask.h\"\n#include \"RawWells.h\"\n#include \"mixed.h\"\n#include \"bivariate_gaussian.h\"\n#include \"armadillo_utils.h\"\n#include \"MaskSample.h\"\n#include \"BeadTracker.h\"\n\nusing namespace std;\nusing namespace arma;\n\ntypedef pair<int,int>   well_coord;\ntypedef set<well_coord> well_set;\n\nstatic void count_sample(filter_counts& counts, deque<float>& ppf, deque<float>& ssq, Mask& mask, RawWells& wells, const vector<int>& key_ionogram, const PolyclonalFilterOpts & opts);\nwell_set sample_lib(Mask& mask, int nsamp);\nvoid calcMeanCovariance(mat new_sgma[2], vec new_mean[2], vec &new_alpha, const vec mean[2], const mat sgma[2], const vec& alpha, const deque<float>& ppf, const deque<float>& ssq, int option);\n\n\nvoid make_filter(clonal_filter& filter, filter_counts& counts, Mask& mask, RawWells& wells, const vector<int>& key_ionogram, const PolyclonalFilterOpts & opts)\n{\n    // Make a clonality filter from a sample of reads from a RawWells file.\n    // Record number of reads in sample that are caught by each filter.\n    deque<float>  ppf;\n    deque<float>  ssq;\n    count_sample(counts, ppf, ssq, mask, wells, key_ionogram, opts);\n    make_filter(filter, counts, ppf, ssq, opts);\n}\n\nvoid make_filter(clonal_filter& filter, filter_counts& counts, const deque<float>& ppf, const deque<float>& ssq, const PolyclonalFilterOpts & opts)\n{\n    // Make a clonality filter from ppf and ssq for a sample of reads.\n    // Record number of putative clonal and mixed reads in the sample.\n    vec  mean[2];\n    mat  sigma[2];\n    vec  alpha;\n    bool converged = fit_normals(mean, sigma, alpha, ppf, ssq, opts);\n\n    if(converged){\n        bivariate_gaussian clonal(mean[0], sigma[0]);\n        bivariate_gaussian mixed( mean[1], sigma[1]);\n        filter = clonal_filter(clonal, mixed, mixed_ppf_cutoff(), converged);\n    }\n\n    if(converged){\n        deque<float>::const_iterator p = ppf.begin();\n        for(deque<float>::const_iterator s=ssq.begin(); s!=ssq.end(); ++p, ++s){\n            if(filter.is_clonal(*p,*s, opts.mixed_stringency))\n                ++counts._nclonal;\n        }\n        counts._nmixed = ppf.size() - counts._nclonal;\n    }\n}\n\nstatic void count_sample(filter_counts& counts, deque<float>& ppf, deque<float>& ssq, Mask& mask, RawWells& wells, const vector<int>& key_ionogram, const PolyclonalFilterOpts & opts)\n{\n    // Take sample of reads from a RawWells file, and apply some simple\n    // filters to identify problem reads.\n    // Record number of reads in sample, and number of reads caught by\n    // each filter.\n    well_set sample = sample_lib(mask, counts._nsamp);\n    WellData data;\n    unsigned int nflows = wells.NumFlows();\n    vector<float> nrm(nflows);\n    int flow0 = opts.mixed_first_flow;\n    int flow1 = opts.mixed_last_flow;\n    wells.ResetCurrentRegionWell();\n    \n    // Some temporary code for comparing clonal filter in background model:\n    ofstream out(\"basecaller_ppf_ssq.txt\");\n    assert(out);\n\n    while(!wells.ReadNextRegionData(&data)){\n        // Skip if this is not in the sample:\n        well_coord wc(data.y, data.x);\n        if(sample.find(wc) == sample.end())\n            continue;\n\n        // Skip wells with infinite signal:\n        bool finite = all_finite(data.flowValues, data.flowValues+nflows);\n        if(not finite){\n            ++counts._ninf;\n            continue;\n        }\n\n        // Key-normalize:\n        float normalizer = ComputeNormalizerKeyFlows(data.flowValues, &key_ionogram[0], key_ionogram.size());\n        transform(data.flowValues, data.flowValues+nflows, nrm.begin(), bind2nd(divides<float>(),normalizer));\n\n        // Skip wells with bad key:\n        bool good_key = key_is_good(nrm.begin(), key_ionogram.begin(), key_ionogram.end());\n        if(not good_key){\n            ++counts._nbad_key;\n            continue;\n        }\n\n        // Skip possible super-mixed beads:\n        float perc_pos = percent_positive(nrm.begin()+flow0, nrm.begin()+flow1);;\n        if(perc_pos > mixed_ppf_cutoff()){\n            ++counts._nsuper;\n            continue;\n        }\n\n        // Record ppf and ssq:\n        float sum_frac = sum_fractional_part(nrm.begin()+flow0, nrm.begin()+flow1);\n        ppf.push_back(perc_pos);\n        ssq.push_back(sum_frac);\n\n        // Some temporary code for comparing clonal filter in background model:\n        out << setw(6) << data.y\n            << setw(6) << data.x\n            << setw(8) << setprecision(2) << fixed << perc_pos\n            << setw(8) << setprecision(2) << fixed << sum_frac\n            << setw(8) << setprecision(2) << fixed << normalizer\n            << endl;\n    }\n    assert(ppf.size() == ssq.size());\n}\n\nwell_set sample_lib(Mask& mask, int nsamp)\n{\n    // Return a random sample of wells with library beads.\n    MaskSample<uint32_t> lib_sample(mask, MaskLib, nsamp);\n\n    well_set sample;\n    int chip_width = mask.W();\n    for(vector<uint32_t>::iterator i=lib_sample.Sample().begin(); i!=lib_sample.Sample().end(); ++i){\n        int row = *i / chip_width;\n        int col = *i % chip_width;\n        sample.insert(make_pair(row,col));\n    }\n\n    return sample;\n}\n\n\ninline double square(double x)\n{\n    return x * x;\n}\n\nstatic bool test_convergence(const vec mean[2], const mat sgma[2], const vec& alpha, const vec new_mean[2], const mat new_sgma[2], const vec& new_alpha)\n{\n    double eps        = 1e-4;\n    double mean_diff0  = max(max(new_mean[0] - mean[0]));\n    double mean_diff1  = max(max(new_mean[1] - mean[1]));\n    double sgma_diff0  = max(max(new_sgma[0]    - sgma[0]));\n    double sgma_diff1  = max(max(new_sgma[1]    - sgma[1]));\n    double sgma_diff   = max(sgma_diff0, sgma_diff1);\n    double alpha_diff  = max(max(new_alpha   - alpha));\n    double max_diff    = max(max(mean_diff0, mean_diff1), max(sgma_diff, alpha_diff));\n\n    return max_diff < eps;\n}\n\nstatic void print_dist(vec mean[2], mat sgma[2], vec& alpha, bool converged, int iter, int option)\n{\n    cout << \"Clonal Filter: fit_normals with option \" << option << \" at iteration\" << setw(4) << iter << endl;\n    cout << \"convergence status: \" << boolalpha << converged << endl;\n    cout << \"Mean of first cluster:\" << endl;\n    cout << mean[0] << endl;\n    cout << \"Mean of mixed cluster:\"<< endl;\n    cout << mean[1] << endl;\n    cout << \"Covariance of clonal cluster:\" <<endl;\n    cout << sgma[0] << endl;\n    cout << \"Covariance of mixed cluster:\" <<endl;\n    cout << sgma[1] << endl;\n    cout << \"fraction clonal vs mixed: \" << alpha[0] << \" & \" << alpha[1] << endl;\n    cout << endl;\n}\n\nstatic void init(vec mean[2], mat sgma[2], vec& alpha)\n{\n    for (int i = 0; i < 2; i++) {\n        mean[i].set_size(2);\n        sgma[i].set_size(2,2);\n    }\n\n    alpha.set_size(2);\n    // Following intializations are based on average over largne number of runs.\n    // Average parameters for clonal population:\n    mean[0] << 0.48811  << 1.61692;\n    sgma[0] << 0.004836 << 0.032828 << endr\n            << 0.032828 << 0.548305 << endr;\n\n    // Average parameters for mixed population:\n    mean[1] << 0.693371 << 4.397405;\n    sgma[1] = sgma[0];\n\n    // Start by assuming that clonal and mixed populations are equinumerous:\n    alpha.fill(0.5);\n}\n\nbool fit_normals(vec mean[2], mat sgma[2], vec& alpha, const deque<float>& ppf, const deque<float>& ssq, const PolyclonalFilterOpts & opts)\n{\n    bool converged = false;\n    \n    try {\n        // Initial guesses for two normal distributions:\n        init(mean, sgma, alpha);\n        if (opts.verbose)\n          print_dist(mean, sgma, alpha, converged, 0, opts.mixed_model_option);  // XXX\n\n        // increased stablity of iterative method:\n        // Add two points to the ppf, ssp deqeue corresponding to the a-priori cluster centers\n        std::deque<float> my_ppf(ppf);\n        my_ppf.push_front(mean[0][0]);\n        my_ppf.push_front(mean[1][0]);\n        std::deque<float> my_ssq(ssq);\n        my_ssq.push_front(mean[0][1]);\n        my_ssq.push_front(mean[1][1]);\n\n        int  max_iters = opts.max_iterations;\n        int iteration = 1;\n        cout << \"max_iters: \" << max_iters << endl;\n        bool not_pos_def = false;\n        bool not_finite_params = false;\n        for(; iteration<=max_iters and not converged; ++iteration){\n\n            vec  new_mean[2];\n            mat  new_sgma[2];\n            vec  new_alpha;\n\n            calcMeanCovariance(new_sgma, new_mean, new_alpha, mean, sgma, alpha, my_ppf, my_ssq, opts.mixed_model_option);\n\n            if(not is_pos_def(sgma[0]) or not is_pos_def(sgma[1])) {\n                not_pos_def = true;\n                break;\n            }\n\n            // Test for convergence:\n            if(not new_mean[0].is_finite() or not new_mean[1].is_finite() or not new_sgma[0].is_finite() or not new_sgma[1].is_finite() or not new_alpha.is_finite()) {\n                not_finite_params = true;\n                break;\n            }\n\n            converged = test_convergence(mean, sgma, alpha, new_mean, new_sgma, new_alpha);//ignore new_sigma2 comparison\n\n            // Update parameters, forcing covariances to be the same for both distributions:\n            alpha   = new_alpha;\n            mean[0] = new_mean[0];\n            mean[1] = new_mean[1];\n            sgma[0] = new_sgma[0];\n            sgma[1] = new_sgma[1];\n\n            if (opts.verbose)\n              print_dist(mean, sgma, alpha, converged, iteration, opts.mixed_model_option);\n        }\n\n        // Fallback position if failed to converge:\n        if(not converged){\n            // in case of singular covariance matrices on infinite means, don't use the mean and covariances at the last iteration\n            if (not_pos_def || not_finite_params) {\n              cout << \"failed to converge to an acceptable filter with improper covariance and mean parameters for the clusters: default filtering used\" << endl;\n              init(mean, sgma, alpha);\n            }\n            else {\n              cout << \"failed to converge to an acceptable filter in \" << max_iters << \" iterations\";\n              if (opts.use_last_iter_params) {\n                cout << \": using last iteration params for filtering\" << endl;\n              }\n              else {\n                cout << \": default filtering used\" << endl;\n                init(mean, sgma, alpha);\n              }\n            }\n            converged = true;\n        } else {\n          cout << \"converged to acceptable filter: using adapted filter at iteration \" << (iteration-1) << endl;\n        }\n    }catch(const exception& ex){\n        converged = false;\n        cerr << \"exception thrown during fit_normals()\" << endl;\n        cerr << ex.what() << endl;\n    }catch(...){\n        converged = false;\n        cerr << \"unknown exception thrown during fit_normals()\" << endl;\n    }\n\n    return converged;\n}\n\nvoid calcMeanCovariance(mat new_sgma[2], vec new_mean[2], vec &new_alpha, const vec mean[2], const mat sgma[2], const vec& alpha, const deque<float>& ppf, const deque<float>& ssq, int option)\n{\n  switch(option){\n    case 0:{//common covariance\n        bivariate_gaussian clone_dist(mean[0], sgma[0]);\n        bivariate_gaussian mixed_dist(mean[1], sgma[1]);\n\n        // Re-estimate parameters for each distribution:\n        int nsamp = ppf.size();\n        vec sumw(2);\n        sumw.fill(0.5);\n\n        mat sum2(2,2);\n        sum2.fill(0.0);\n\n        vec   sum1[2];\n        sum1[0].set_size(2);\n        sum1[1].set_size(2);\n        sum1[0].fill(0.0);\n        sum1[1].fill(0.0);\n\n        // Accumulate weighted sums for re-estimating moments:\n        int savedExceptionFlags = fegetexcept();\n        fedisableexcept(FE_DIVBYZERO | FE_INVALID | FE_OVERFLOW | FE_INEXACT | FE_UNDERFLOW); //possible division by zero in probability normalization for outliers\n        for(int j=0; j<nsamp; ++j){\n            // Skip reads outside the poisson range for ppf:\n            if(mixed_ppf_cutoff() < ppf[j])\n                continue;\n\n            // Each read gets two weights, reflecting the likelyhoods of that\n            // read being clonal or mixed.\n            vec x(2);\n            x << ppf[j] << ssq[j];\n            vec q(2);\n            q[0] = alpha[0] * clone_dist.pdf(x);\n            q[1] = alpha[1] * mixed_dist.pdf(x);\n\n            vec w = q / sum(q);\n\n            // Skip outliers:\n            if( not w.is_finite() )\n              continue;\n\n            // Running sums for moments are weighted:\n            sumw         += w;\n            sum1[0]      += w[0] * x;\n            sum1[1]      += w[1] * x;\n            sum2.at(0,0) += w[0] * square(ppf[j] - mean[0][0]);\n            sum2.at(0,1) += w[0] * (ppf[j] - mean[0][0]) * (ssq[j] - mean[0][1]);\n            sum2.at(1,1) += w[0] * square(ssq[j] - mean[0][1]);\n        }\n        feenableexcept(savedExceptionFlags);\n\n        // New means:\n        for(int j=0; j<2; ++j) {\n            new_mean[j].set_size(2);\n            new_mean[j] = sum1[j] / sumw[j];\n        }\n\n        // New covariance:\n        mat new_sgma1(2,2);\n        new_sgma1.at(0,0) = sum2.at(0,0) / sumw[0];\n        new_sgma1.at(0,1) = sum2.at(0,1) / sumw[0];\n        new_sgma1.at(1,0) = new_sgma1.at(0,1);\n        new_sgma1.at(1,1) = sum2.at(1,1) / sumw[0];\n\n        new_sgma[0] = new_sgma1;\n        new_sgma[1] = new_sgma1;\n\n        // New prior:\n        new_alpha = sumw / nsamp;\n    }\n        break;\n    case 7: {\n        //same volume and shape, different orientation: lambda*D_k*A*(D_k)'\n      bivariate_gaussian clone_dist(mean[0], sgma[0]);\n      bivariate_gaussian mixed_dist(mean[1], sgma[1]);\n      // Re-estimate parameters for each distribution:\n      int nsamp = ppf.size();\n      vec sumw(2);\n      sumw.fill(0.0);\n\n      mat sum2(2,2);\n      sum2.fill(0.0);\n\n      mat sum3(2,2);\n      sum3.fill(0.0);\n\n      vec   sum1[2];\n      sum1[0].set_size(2);\n      sum1[1].set_size(2);\n      sum1[0].fill(0.0);\n      sum1[1].fill(0.0);\n\n      // Accumulate weighted sums for re-estimating moments:\n      for(int j=0; j<nsamp; ++j){\n          // Skip reads outside the poisson range for ppf:\n          if(mixed_ppf_cutoff() < ppf[j])\n              continue;\n\n          // Each read gets two weights, reflecting the likelyhoods of that\n          // read being clonal or mixed.\n          vec x(2);\n          x << ppf[j] << ssq[j];\n          vec q(2);\n          q[0] = alpha[0] * clone_dist.pdf(x);\n          q[1] = alpha[1] * mixed_dist.pdf(x);\n          vec w = q / sum(q);\n\n          // Skip outliers:\n          if(not w.is_finite())\n              continue;\n\n          // Running sums for moments are weighted:\n          sumw         += w;\n          sum1[0]      += w[0] * x;\n          sum1[1]      += w[1] * x;\n          sum2.at(0,0) += w[0] * square(ppf[j] - mean[0][0]);\n          sum2.at(0,1) += w[0] * (ppf[j] - mean[0][0]) * (ssq[j] - mean[0][1]);\n\n          sum2.at(1,1) += w[0] * square(ssq[j] - mean[0][1]);\n          sum3.at(0,0) += w[1] * square(ppf[j] - mean[1][0]);\n          sum3.at(0,1) += w[1] * (ppf[j] - mean[1][0]) * (ssq[j] - mean[1][1]);\n\n          sum3.at(1,1) += w[1] * square(ssq[j] - mean[1][1]);\n      }\n      sum2.at(1,0) =  sum2.at(0,1);\n      sum3.at(1,0) =  sum3.at(0,1);\n\n      // New means:\n      for(int j=0; j<2; ++j) {\n          new_mean[j].set_size(2);\n          new_mean[j] = sum1[j] / sumw[j];\n      }\n\n      //calculate eigen values and vectors for sum2 and sum3\n      vec eigval_clonal;\n      mat eigvec_clonal;\n      eig_sym(eigval_clonal, eigvec_clonal, sum2);\n\n      vec eigval_mixed;\n      mat eigvec_mixed;\n      eig_sym(eigval_mixed, eigvec_mixed, sum3);\n\n      //maintain same ascending order between clonal and mixed: ascending order by default and should be no op\n      //should we bail out if eigenvalue is complex\n      if(eigval_clonal.at(0) > eigval_clonal.at(1)){\n        double temp = eigval_clonal.at(0);\n        eigval_clonal.at(0) = eigval_clonal.at(1);\n        eigval_clonal.at(1) = temp;\n        temp = eigvec_clonal.at(0, 0);\n        eigvec_clonal.at(0, 0) = eigvec_clonal.at(0, 1);\n        eigvec_clonal.at(0, 1) = temp;\n        temp = eigvec_clonal.at(1, 0);\n        eigvec_clonal.at(1, 0) = eigvec_clonal.at(1, 1);\n        eigvec_clonal.at(1, 1) = temp;\n      }\n      if(eigval_mixed.at(0) > eigval_mixed.at(1)){\n        double temp = eigval_mixed.at(0);\n        eigval_mixed.at(0) = eigval_mixed.at(1);\n        eigval_mixed.at(1) = temp;\n        temp = eigvec_mixed.at(0, 0);\n        eigvec_mixed.at(0, 0) = eigvec_mixed.at(0, 1);\n        eigvec_mixed.at(0, 1) = temp;\n        temp = eigvec_mixed.at(1, 0);\n        eigvec_mixed.at(1, 0) = eigvec_mixed.at(1, 1);\n        eigvec_mixed.at(1, 1) = temp;\n      }\n      //average out the eigenvalues\n      vec eigval_sum = eigval_clonal + eigval_mixed;\n      //calculate the new covariance\n      new_sgma[0] = eigvec_clonal * diagmat(eigval_sum) * trans(eigvec_clonal) / (sumw[0] + sumw[1]);\n      new_sgma[1] = eigvec_mixed * diagmat(eigval_sum) * trans(eigvec_mixed) / (sumw[0] + sumw[1]);\n\n      // New prior:\n      new_alpha = sumw / nsamp;\n\n    }\n        break;\n\n    case 8:{//common volume\n        bivariate_gaussian clone_dist(mean[0], sgma[0]);\n        bivariate_gaussian mixed_dist(mean[1], sgma[1]);\n        // Re-estimate parameters for each distribution:\n        int nsamp = ppf.size();\n        vec sumw(2);\n        sumw.fill(0.0);\n\n        mat sum2(2,2);\n        sum2.fill(0.0);\n\n        mat sum3(2,2);\n        sum3.fill(0.0);\n\n        vec   sum1[2];\n        sum1[0].set_size(2);\n        sum1[1].set_size(2);\n        sum1[0].fill(0.0);\n        sum1[1].fill(0.0);\n\n        // Accumulate weighted sums for re-estimating moments:\n        for(int j=0; j<nsamp; ++j){\n            // Skip reads outside the poisson range for ppf:\n            if(mixed_ppf_cutoff() < ppf[j])\n                continue;\n\n            // Each read gets two weights, reflecting the likelyhoods of that\n            // read being clonal or mixed.\n            vec x(2);\n            x << ppf[j] << ssq[j];\n            vec q(2);\n            q[0] = alpha[0] * clone_dist.pdf(x);\n            q[1] = alpha[1] * mixed_dist.pdf(x);\n            vec w = q / sum(q);\n\n            // Skip outliers:\n            if(not w.is_finite())\n                continue;\n\n            // Running sums for moments are weighted:\n            sumw         += w;\n            sum1[0]      += w[0] * x;\n            sum1[1]      += w[1] * x;\n            sum2.at(0,0) += w[0] * square(ppf[j] - mean[0][0]);\n            sum2.at(0,1) += w[0] * (ppf[j] - mean[0][0]) * (ssq[j] - mean[0][1]);\n\n            sum2.at(1,1) += w[0] * square(ssq[j] - mean[0][1]);\n            sum3.at(0,0) += w[1] * square(ppf[j] - mean[1][0]);\n            sum3.at(0,1) += w[1] * (ppf[j] - mean[1][0]) * (ssq[j] - mean[1][1]);\n            sum3.at(1,1) += w[1] * square(ssq[j] - mean[1][1]);\n        }\n        sum2.at(1,0) =  sum2.at(0,1);\n        sum3.at(1,0) =  sum3.at(0,1);\n\n        // New means:\n        for(int j=0; j<2; ++j) {\n            new_mean[j].set_size(2);\n            new_mean[j] = sum1[j] / sumw[j];\n        }\n\n        vec det(2);\n        det[0] = sqrt(sum2.at(0, 0)*sum2.at(1,1) - sum2.at(0, 1)*sum2.at(1,0));\n        det[1] = sqrt(sum3.at(0, 0)*sum3.at(1,1) - sum3.at(0, 1)*sum3.at(1,0));\n        double det_factor = (det[0] + det[1])/(sumw[0] + sumw[1]);\n\n        // New covariance:\n        mat new_sgma1(2,2);\n        new_sgma1.at(0,0) = sum2.at(0,0) * det_factor / det[0];\n        new_sgma1.at(0,1) = sum2.at(0,1) * det_factor / det[0];\n        new_sgma1.at(1,0) = new_sgma1.at(0,1);\n        new_sgma1.at(1,1) = sum2.at(1,1) * det_factor / det[0];\n\n        mat new_sgma2(2,2);\n        new_sgma2.at(0,0) = sum3.at(0,0) * det_factor / det[1];\n        new_sgma2.at(0,1) = sum3.at(0,1) * det_factor / det[1];\n        new_sgma2.at(1,0) = new_sgma2.at(0,1);\n        new_sgma2.at(1,1) = sum3.at(1,1) * det_factor / det[1];\n\n\n        new_sgma[0] = new_sgma1;\n        new_sgma[1] = new_sgma2;\n\n        // New prior:\n        new_alpha = sumw / nsamp;\n    }\n        break;\n\n    case 9:{//independent covariance\n        bivariate_gaussian clone_dist(mean[0], sgma[0]);\n        bivariate_gaussian mixed_dist(mean[1], sgma[1]);\n        // Re-estimate parameters for each distribution:\n        int nsamp = ppf.size();\n        vec sumw(2);\n        sumw.fill(0.0);\n\n        mat sum2(2,2);\n        sum2.fill(0.0);\n\n        mat sum3(2,2);\n        sum3.fill(0.0);\n\n        vec   sum1[2];\n        sum1[0].set_size(2);\n        sum1[1].set_size(2);\n        sum1[0].fill(0.0);\n        sum1[1].fill(0.0);\n\n        // Accumulate weighted sums for re-estimating moments:\n        for(int j=0; j<nsamp; ++j){\n            // Skip reads outside the poisson range for ppf:\n            if(mixed_ppf_cutoff() < ppf[j])\n                continue;\n\n            // Each read gets two weights, reflecting the likelyhoods of that\n            // read being clonal or mixed.\n            vec x(2);\n            x << ppf[j] << ssq[j];\n            vec q(2);\n            q[0] = alpha[0] * clone_dist.pdf(x);\n            q[1] = alpha[1] * mixed_dist.pdf(x);\n            vec w = q / sum(q);\n\n            // Skip outliers:\n            if(not w.is_finite())\n                continue;\n\n            // Running sums for moments are weighted:\n            sumw         += w;\n            sum1[0]      += w[0] * x;\n            sum1[1]      += w[1] * x;\n            sum2.at(0,0) += w[0] * square(ppf[j] - mean[0][0]);\n            sum2.at(0,1) += w[0] * (ppf[j] - mean[0][0]) * (ssq[j] - mean[0][1]);\n            sum2.at(1,1) += w[0] * square(ssq[j] - mean[0][1]);\n            sum3.at(0,0) += w[1] * square(ppf[j] - mean[1][0]);\n            sum3.at(0,1) += w[1] * (ppf[j] - mean[1][0]) * (ssq[j] - mean[1][1]);\n            sum3.at(1,1) += w[1] * square(ssq[j] - mean[1][1]);\n        }\n\n        // New means:\n        for(int j=0; j<2; ++j) {\n            new_mean[j].set_size(2);\n            new_mean[j] = sum1[j] / sumw[j];\n        }\n\n        // New covariance:\n        mat new_sgma1(2,2);\n        new_sgma1.at(0,0) = sum2.at(0,0) / sumw[0];\n        new_sgma1.at(0,1) = sum2.at(0,1) / sumw[0];\n        new_sgma1.at(1,0) = new_sgma1.at(0,1);\n        new_sgma1.at(1,1) = sum2.at(1,1) / sumw[0];\n\n        mat new_sgma2(2,2);\n        new_sgma2.at(0,0) = sum3.at(0,0) / sumw[1];\n        new_sgma2.at(0,1) = sum3.at(0,1) / sumw[1];\n        new_sgma2.at(1,0) = new_sgma2.at(0,1);\n        new_sgma2.at(1,1) = sum3.at(1,1) / sumw[1];\n        new_sgma[0] = new_sgma1;\n        new_sgma[1] = new_sgma2;\n\n        // New prior:\n        new_alpha = sumw / nsamp;\n    }\n        break;\n  }\n\n\n\n}\n\nostream& operator<<(ostream& out, const filter_counts& c)\n{\n    out << setw(8) << \"infinite\" << setw(12) << c. _ninf    << endl\n        << setw(8) << \"bad-key\"  << setw(12) << c._nbad_key << endl\n        << setw(8) << \"high-ppf\" << setw(12) << c._nsuper   << endl\n        << setw(8) << \"mixed\"    << setw(12) << c._nmixed   << endl\n        << setw(8) << \"clonal\"   << setw(12) << c._nclonal  << endl\n        << setw(8) << \"samples\"  << setw(12) << c._nsamp    << endl;\n\n    return out;\n}\n\n//lamda * D_k * A_k * (D_k)'\n\n//alternative: using lamda from clonal\n\n//Is it possible to try different models and find the one fitting the data best?\n\n\n", "meta": {"hexsha": "4309f52c8fd7572eac3c0dd94f02ba312a135696", "size": 23355, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Analysis/ClonalFilter/mixed.cpp", "max_stars_repo_name": "sequencer2014/TS", "max_stars_repo_head_hexsha": "465804570349d46b47c1bdf131bdafea5c582dee", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Analysis/ClonalFilter/mixed.cpp", "max_issues_repo_name": "sequencer2014/TS", "max_issues_repo_head_hexsha": "465804570349d46b47c1bdf131bdafea5c582dee", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Analysis/ClonalFilter/mixed.cpp", "max_forks_repo_name": "sequencer2014/TS", "max_forks_repo_head_hexsha": "465804570349d46b47c1bdf131bdafea5c582dee", "max_forks_repo_licenses": ["Apache-2.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.1203007519, "max_line_length": 192, "alphanum_fraction": 0.5545707557, "num_tokens": 7055, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7690802264851919, "lm_q2_score": 0.4186969093556867, "lm_q1q2_score": 0.3220115138759214}}
{"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 \"five_point_relative_pose.h\"\n\n#include <Eigen/Dense>\n\n#include <cmath>\n#include <ctime>\n#include <vector>\n\n\nusing Eigen::Map;\nusing Eigen::Matrix3d;\nusing Eigen::Matrix4d;\nusing Eigen::Matrix;\nusing Eigen::MatrixXd;\nusing Eigen::RowVector3d;\nusing Eigen::RowVector4d;\nusing Eigen::Vector2d;\nusing Eigen::Vector3d;\nusing Eigen::Vector4d;\nusing Eigen::VectorXd;\n\ntypedef Matrix<double, 10, 10> Matrix10d;\n\n\n// Multiply two degree one polynomials of variables x, y, z.\n// E.g. p1 = a[0]x + a[1]y + a[2]z + a[3]\n// Output order: x^2 xy y^2 xz yz z^2 x y z 1 (GrevLex)\nMatrix<double, 1, 10> MultiplyDegOnePoly(const RowVector4d& a,\n                                         const RowVector4d& b) {\n  Matrix<double, 1, 10> output;\n  // x^2\n  output(0) = a(0) * b(0);\n  // xy\n  output(1) = a(0) * b(1) + a(1) * b(0);\n  // y^2\n  output(2) = a(1) * b(1);\n  // xz\n  output(3) = a(0) * b(2) + a(2) * b(0);\n  // yz\n  output(4) = a(1) * b(2) + a(2) * b(1);\n  // z^2\n  output(5) = a(2) * b(2);\n  // x\n  output(6) = a(0) * b(3) + a(3) * b(0);\n  // y\n  output(7) = a(1) * b(3) + a(3) * b(1);\n  // z\n  output(8) = a(2) * b(3) + a(3) * b(2);\n  // 1\n  output(9) = a(3) * b(3);\n  return output;\n}\n\n// Multiply a 2 deg poly (in x, y, z) and a one deg poly in GrevLex order.\n// x^3 x^2y xy^2 y^3 x^2z xyz y^2z xz^2 yz^2 z^3 x^2 xy y^2 xz yz z^2 x y z 1\nMatrix<double, 1, 20> MultiplyDegTwoDegOnePoly(const Matrix<double, 1, 10>& a,\n                                               const RowVector4d& b) {\n  Matrix<double, 1, 20> output;\n  // x^3\n  output(0) = a(0) * b(0);\n  // x^2y\n  output(1) = a(0) * b(1) + a(1) * b(0);\n  // xy^2\n  output(2) = a(1) * b(1) + a(2) * b(0);\n  // y^3\n  output(3) = a(2) * b(1);\n  // x^2z\n  output(4) = a(0) * b(2) + a(3) * b(0);\n  // xyz\n  output(5) = a(1) * b(2) + a(3) * b(1) + a(4) * b(0);\n  // y^2z\n  output(6) = a(2) * b(2) + a(4) * b(1);\n  // xz^2\n  output(7) = a(3) * b(2) + a(5) * b(0);\n  // yz^2\n  output(8) = a(4) * b(2) + a(5) * b(1);\n  // z^3\n  output(9) = a(5) * b(2);\n  // x^2\n  output(10) = a(0) * b(3) + a(6) * b(0);\n  // xy\n  output(11) = a(1) * b(3) + a(6) * b(1) + a(7) * b(0);\n  // y^2\n  output(12) = a(2) * b(3) + a(7) * b(1);\n  // xz\n  output(13) = a(3) * b(3) + a(6) * b(2) + a(8) * b(0);\n  // yz\n  output(14) = a(4) * b(3) + a(7) * b(2) + a(8) * b(1);\n  // z^2\n  output(15) = a(5) * b(3) + a(8) * b(2);\n  // x\n  output(16) = a(6) * b(3) + a(9) * b(0);\n  // y\n  output(17) = a(7) * b(3) + a(9) * b(1);\n  // z\n  output(18) = a(8) * b(3) + a(9) * b(2);\n  // 1\n  output(19) = a(9) * b(3);\n  return output;\n}\n\nMatrix<double, 1, 20> GetDeterminantConstraint(\n    const Matrix<double, 1, 4> null_space[3][3]) {\n  // Singularity constraint.\n  const Matrix<double, 1, 20> determinant =\n      MultiplyDegTwoDegOnePoly(\n          MultiplyDegOnePoly(null_space[0][1], null_space[1][2]) -\n          MultiplyDegOnePoly(null_space[0][2], null_space[1][1]),\n          null_space[2][0]) +\n      MultiplyDegTwoDegOnePoly(\n          MultiplyDegOnePoly(null_space[0][2], null_space[1][0]) -\n          MultiplyDegOnePoly(null_space[0][0], null_space[1][2]),\n          null_space[2][1]) +\n      MultiplyDegTwoDegOnePoly(\n          MultiplyDegOnePoly(null_space[0][0], null_space[1][1]) -\n          MultiplyDegOnePoly(null_space[0][1], null_space[1][0]),\n          null_space[2][2]);\n  return determinant;\n}\n\n// Shorthand for multiplying the Essential matrix with its transpose.\nMatrix<double, 1, 10> EETranspose(\n    const Matrix<double, 1, 4> null_space[3][3], int i, int j) {\n  return MultiplyDegOnePoly(null_space[i][0], null_space[j][0]) +\n      MultiplyDegOnePoly(null_space[i][1], null_space[j][1]) +\n      MultiplyDegOnePoly(null_space[i][2], null_space[j][2]);\n}\n\n\n// Builds the trace constraint: EEtE - 1/2 trace(EEt)E = 0\nMatrix<double, 9, 20> GetTraceConstraint(\n    const Matrix<double, 1, 4> null_space[3][3]) {\n  Matrix<double, 9, 20> trace_constraint;\n\n  // Comput EEt.\n  Matrix<double, 1, 10> eet[3][3];\n  for (int i = 0; i < 3; i++) {\n    for (int j = 0; j < 3; j++) {\n      eet[i][j] = 2 * EETranspose(null_space, i, j);\n    }\n  }\n\n  // Compute the trace.\n  const Matrix<double, 1, 10> trace = eet[0][0] + eet[1][1] + eet[2][2];\n\n  // Multiply EEt with E.\n  for (int i = 0; i < 3; i++) {\n    for (int j = 0; j < 3; j++) {\n      trace_constraint.row(3 * i + j) =\n          MultiplyDegTwoDegOnePoly(eet[i][0], null_space[0][j]) +\n          MultiplyDegTwoDegOnePoly(eet[i][1], null_space[1][j]) +\n          MultiplyDegTwoDegOnePoly(eet[i][2], null_space[2][j]) -\n          0.5 * MultiplyDegTwoDegOnePoly(trace, null_space[i][j]);\n    }\n  }\n\n  return trace_constraint;\n}\n\nMatrix<double, 10, 20> BuildConstraintMatrix(\n    const Matrix<double, 1, 4> null_space[3][3]) {\n  Matrix<double, 10, 20> constraint_matrix;\n  constraint_matrix.block<9, 20>(0, 0) = GetTraceConstraint(null_space);\n  constraint_matrix.row(9) = GetDeterminantConstraint(null_space);\n  return constraint_matrix;\n}\n\n// Implementation of Nister from \"An Efficient Solution to the Five-Point\n// Relative Pose Problem\"\nbool FivePointRelativePose(const std::vector<Vector2d>& image1_points,\n                           const std::vector<Vector2d>& image2_points,\n                           std::vector<Matrix3d>* essential_matrices) {\n\n  // Step 1. Create the nx9 matrix containing epipolar constraints.\n  //   Essential matrix is a linear combination of the 4 vectors spanning the\n  //   null space of this matrix.\n  MatrixXd epipolar_constraint(image1_points.size(), 9);\n  for (int i = 0; i < image1_points.size(); i++) {\n    // Fill matrix with the epipolar constraint from q'_t*E*q = 0. Where q is\n    // from the first image, and q' is from the second.\n    epipolar_constraint.row(i) <<\n        image2_points[i].x() * image1_points[i].x(),\n        image2_points[i].y() * image1_points[i].x(),\n        image1_points[i].x(),\n        image2_points[i].x() * image1_points[i].y(),\n        image2_points[i].y() * image1_points[i].y(),\n        image1_points[i].y(),\n        image2_points[i].x(),\n        image2_points[i].y(),\n        1.0;\n  }\n\n  Matrix<double, 9, 4> null_space;\n\n  // Extract the null space from a minimal sampling (using LU) or non-minimal\n  // sampling (using SVD).\n  if (image1_points.size() == 5) {\n    const Eigen::FullPivLU<MatrixXd> lu(epipolar_constraint);\n    if (lu.dimensionOfKernel() != 4) {\n      return false;\n    }\n    null_space = lu.kernel();\n  } else {\n    const Eigen::JacobiSVD<MatrixXd> svd(\n        epipolar_constraint.transpose() * epipolar_constraint,\n        Eigen::ComputeFullV);\n    null_space = svd.matrixV().rightCols<4>();\n  }\n\n  const Matrix<double, 1, 4> null_space_matrix[3][3] = {\n    { null_space.row(0), null_space.row(3), null_space.row(6) },\n    { null_space.row(1), null_space.row(4), null_space.row(7) },\n    { null_space.row(2), null_space.row(5), null_space.row(8) }\n  };\n\n  // Step 2. Expansion of the epipolar constraints on the determinant and trace.\n  const Matrix<double, 10, 20> constraint_matrix =\n      BuildConstraintMatrix(null_space_matrix);\n\n  // Step 3. Eliminate part of the matrix to isolate polynomials in z.\n  Eigen::FullPivLU<Matrix10d> c_lu(constraint_matrix.block<10, 10>(0, 0));\n  Matrix10d eliminated_matrix =\n      c_lu.solve(constraint_matrix.block<10, 10>(0, 10));\n\n  Matrix10d action_matrix = Matrix10d::Zero();\n  action_matrix.block<3, 10>(0, 0) = eliminated_matrix.block<3, 10>(0, 0);\n  action_matrix.row(3) = eliminated_matrix.row(4);\n  action_matrix.row(4) = eliminated_matrix.row(5);\n  action_matrix.row(5) = eliminated_matrix.row(7);\n  action_matrix(6, 0) = -1.0;\n  action_matrix(7, 1) = -1.0;\n  action_matrix(8, 3) = -1.0;\n  action_matrix(9, 6) = -1.0;\n\n  Eigen::EigenSolver<Matrix10d> eigensolver(action_matrix);\n  const auto& eigenvectors = eigensolver.eigenvectors();\n  const auto& eigenvalues = eigensolver.eigenvalues();\n\n  // Now that we have x, y, and z we need to substitute them back into the null\n  // space to get a valid essential matrix solution.\n  for (int i = 0; i < 10; i++) {\n    // Only consider real solutions.\n    if (eigenvalues(i).imag() != 0) {\n      continue;\n    }\n    Matrix3d ematrix;\n    Map<Matrix<double, 9, 1> >(ematrix.data()) =\n        null_space * eigenvectors.col(i).tail<4>().real();\n    essential_matrices->emplace_back(ematrix);\n  }\n\n  return essential_matrices->size() > 0;\n}", "meta": {"hexsha": "43cbf5abbc27dea762050db15afb5d2a6f1f08d6", "size": 10099, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/pose/five_point_relative_pose.cc", "max_stars_repo_name": "donaldmunro/PlanarTrainer", "max_stars_repo_head_hexsha": "c990ad78226d260730f0af2d9d1e65d6aa5fd444", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-04-12T06:34:11.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-12T06:34:11.000Z", "max_issues_repo_path": "src/pose/five_point_relative_pose.cc", "max_issues_repo_name": "donaldmunro/PlanarTrainer", "max_issues_repo_head_hexsha": "c990ad78226d260730f0af2d9d1e65d6aa5fd444", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/pose/five_point_relative_pose.cc", "max_forks_repo_name": "donaldmunro/PlanarTrainer", "max_forks_repo_head_hexsha": "c990ad78226d260730f0af2d9d1e65d6aa5fd444", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.1881533101, "max_line_length": 80, "alphanum_fraction": 0.623824141, "num_tokens": 3331, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6926419831347361, "lm_q2_score": 0.46490157137338844, "lm_q1q2_score": 0.32201034635851883}}
{"text": "/* Copyright (c) 2015, Julian Straub <jstraub@csail.mit.edu>\n * Licensed under the MIT license. See the license file LICENSE.\n */\n \n\n#pragma once\n\n#include <vector>\n#include <Eigen/Dense>\n\n#include <dpMM/gpuMatrix.hpp>\n#include <dpMM/sphere.hpp>\n#include <dpMM/clGMMDataGpu.hpp>\n#include <dpMM/timer.hpp>\n\nusing namespace Eigen;\nusing std::vector;\n\nextern  void Log_p_gpu(double *p, double *q, double *Rs, uint32_t *z, \n  uint32_t K, uint32_t N, double *x);\nextern void meanInTpS2_gpu(double *d_p, double *d_mu_karch, double *d_q, \n    uint32_t *d_z , uint32_t N, uint32_t K);\nextern void sufficientStatisticsOnTpS2_gpu(double *d_p, double *d_Rnorths,\n    double *d_q, uint32_t *d_z , uint32_t N, uint32_t k0, uint32_t K, \n    double *d_SSs);\nextern void sphereGMMPdf(double *d_p, double *d_Rnorths, double * d_q,\n    double *d_invSigmas, double *d_logNormalizer, double *d_logPi, \n    double* d_logPdf, uint32_t N, uint32_t K);\n\nextern  void Log_p_gpu(float *p, float *q, float *Rs, uint32_t *z, \n  uint32_t K, uint32_t N, float *x);\nextern void meanInTpS2_gpu(float *d_p, float *d_mu_karch, float *d_q, \n    uint32_t *d_z , uint32_t N, uint32_t K);\nextern void sufficientStatisticsOnTpS2_gpu(float *d_p, float *d_Rnorths,\n    float *d_q, uint32_t *d_z , uint32_t N, uint32_t k0, uint32_t K, \n    float *d_SSs);\nextern void sphereGMMPdf(float *d_p, float *d_Rnorths, float * d_q,\n    float *d_invSigmas, float *d_logNormalizer, float *d_logPi, \n    float* d_logPdf, uint32_t N, uint32_t K);\n\ntemplate<typename T>\nclass ClTGMMDataGpu : public ClGMMDataGpu<T>\n{\nprotected:\n  GpuMatrix<T> d_q_; // normals on GPU\n//  GpuMatrix<uint32_t> d_z_; // indicators on GPU\n//  GpuMatrix<T> d_x_; // points in tangent plane (dim. is 1 less than q)\n  \n  //uint32_t K_; // number of different tangent planes \n  GpuMatrix<T> d_ps_; // points around which we have tangent spaces\n  GpuMatrix<T> d_muKarch_; // karcher means\n//  GpuMatrix<T> d_Ss_; // sufficient statistics in tangent spaces\n  GpuMatrix<T> d_northRps_; // rotations from tangent spaces to north\n\n//  GpuMatrix<T> d_pdfs_; //\n//  GpuMatrix<T> d_logPi_; //\n//  GpuMatrix<T> d_logNormalizers_; //\n//  GpuMatrix<T> d_invSigmas_; //\n \n  Matrix<T,Dynamic,Dynamic> ps_;\n  \n  Sphere<T> sphere_;\n\npublic: \n  ClTGMMDataGpu(const boost::shared_ptr<Matrix<T,Dynamic,Dynamic> >& q, \n      const spVectorXu& z, uint32_t K);\n  ~ClTGMMDataGpu(){;};\n  virtual void init(const Matrix<T,Dynamic,Dynamic>& ps);\n  \n  /* normal in tangent space around p rotate to the north pole\n   * -> the last dimension will always be 0\n   * -> return only first 2 dims\n   */\n  void Log_p_north(const Matrix<T,Dynamic,Dynamic>& ps, \n      const VectorXu& z, Matrix<T,Dynamic,Dynamic>& x, int32_t K=-1);\n  void Log_p_north(const Matrix<T,Dynamic,Dynamic>& ps, \n      const VectorXu& z, int32_t K=-1);\n\n  Matrix<T,Dynamic,Dynamic> Log_p_north(const Matrix<T,Dynamic,Dynamic>& ps, \n      int32_t K=-1)\n  {\n    Matrix<T,Dynamic,Dynamic> x(this->d_x_.rows(),this->d_x_.cols());\n    Log_p_north(ps, *this->z_, x, K);\n    return x;\n  };\n\n  virtual void update(uint32_t K);\n\n  void relinearize(const Matrix<T,Dynamic,Dynamic>& ps);\n\n  Matrix<T,Dynamic,Dynamic> karcherMeans(const Matrix<T,Dynamic,Dynamic>& p0,\n      uint32_t maxIter = 50);\n\n  virtual void computeLogLikelihoods(const Matrix<T,Dynamic,1>& pi, \n    const vector<Matrix<T,Dynamic,Dynamic> >& Sigmas, \n    const Matrix<T,Dynamic,1>& logNormalizers);\n  virtual void sampleGMMpdf(const Matrix<T,Dynamic,1>& pi, \n      const vector<Matrix<T,Dynamic,Dynamic> >& Sigmas, \n      const Matrix<T,Dynamic,1>& logNormalizers, Sampler<T> *sampler);\n\n  const Matrix<T,Dynamic,Dynamic>& ps() const {return ps_;};\n  const Matrix<T,Dynamic,1>& p(uint32_t k) const {return ps_.col(k);};\n  // TODO: broke compatibility! this used to be ps\n//  Matrix<T,Dynamic,1> mean(uint32_t k) const {return ps_.col(k);};\n//  const Matrix<T,Dynamic,Dynamic>& means() const {return ps_;};\n\n\n  virtual const boost::shared_ptr<Matrix<T,Dynamic,Dynamic> >& q() const \n  {return this->x_;};\n  virtual const Matrix<T,Dynamic,Dynamic>& qMat() const \n  {return (*this->x_);};\n\n  GpuMatrix<T>& d_q(){ return d_q_;};\n\nprotected:\n  Matrix<T,Dynamic,Dynamic> meanInTpS2(const Matrix<T,Dynamic,Dynamic>& ps);\n  Matrix<T,Dynamic,Dynamic> karcherMeans__(const Matrix<T,Dynamic,Dynamic>& p0,\n      uint32_t maxIter = 50);\n};\n\ntypedef ClTGMMDataGpu<double> ClTGMMDataGpud;\ntypedef ClTGMMDataGpu<float> ClTGMMDataGpuf;\n\n// ------------------------------------ impl --------------------------------\ntemplate<typename T>\nClTGMMDataGpu<T>::ClTGMMDataGpu(const boost::shared_ptr<Matrix<T,Dynamic,Dynamic> >& q, \n    const spVectorXu& z, uint32_t K)\n  : ClGMMDataGpu<T>(q,z,K), d_q_(this->D_,this->N_), \n    d_ps_(this->D_,this->K_), d_muKarch_(this->D_+1,this->K_), \n    d_northRps_(this->D_-1,this->K_*this->D_),\n    ps_(Matrix<T,Dynamic,Dynamic>::Zero(this->D_,this->K_)), \n    sphere_(this->D_)\n{};\n\ntemplate<typename T>\nvoid ClTGMMDataGpu<T>::init(const Matrix<T,Dynamic,Dynamic>& ps)\n{\n  for(uint32_t i=0; i<this->N_; ++i)\n    if(fabs(this->x_->col(i).norm()-1.0) > 1e-5 )\n    {\n        cout<<\"ClTGMMDataGpu<T>::ClTGMMDataGpu: warning: renormalizing normal \"\n          <<this->x_->col(i).norm()<<endl;\n      this->x_->col(i) /= this->x_->col(i).norm();\n    }\n  d_q_.set(*this->x_);\n  this->d_x_.setZero();\n\n  // resize the statistyics to be one less dim, since we are in \n  // the tangent planes\n  this->Ns_.setZero(this->K_);\n  this->means_.setZero(this->D_-1,this->K_);\n  for(uint32_t k=0; k<this->K_; ++k)\n    this->Ss_[k].setZero(this->D_-1,this->D_-1);\n  \n  ps_ = ps;\n//  for(uint32_t k=0; k<this->K_; ++k)\n//    ps_.col(k) = sphere_.sampleUnif(this->pRndGen_);\n};\n\n\ntemplate<typename T>\nvoid ClTGMMDataGpu<T>::update(uint32_t K)\n{\n  this->K_ = K>0?K:this->z_->maxCoeff()+1;\n  assert(this->z_->maxCoeff() < this->K_); // no indicators \\geq K\n  assert(this->z_->minCoeff() >= 0); // no indicators \\le 0\n  assert((this->z_->array() < this->K_).all());\n  // update the labels on the GPU\n  this->d_z_.set(this->z_);\n  //TODO shouldnt need to do this everytime?\n  //d_q_.set(*this->x_);\n  // run karcher means to obtain ps\n//  Matrix<T,Dynamic,Dynamic> q = d_q_.get();\n//  cout<<q<<endl;\n  Timer t;\n  ps_ = karcherMeans__(ps_);\n  t.toctic(\"karcherMeansFull\");\n  cout<<\"linearize around: \\n\"<<ps_<<endl;\n  // relinearize around the new centers\n  t.tic();\n  relinearize(ps_);\n  t.toctic(\"relinearize\");\n\n//  // put points into tangent spaces - relinearize\n//  Log_p_gpu(d_ps_.data(), d_q_.data(), d_northRps_.data(), this->d_z_.data(), this->K_, \n//      d_q_.cols(),d_this->x_.data());\n  // compute moments\n  this->computeSufficientStatistics();\n  t.toctic(\"computeSufficientStatistics\");\n}\n\ntemplate<typename T>\nvoid ClTGMMDataGpu<T>::relinearize(const Matrix<T,Dynamic,Dynamic>& ps)\n{\n  // TODO: need to call udapte Labels before this function\n  \n  // compute rotations to north and push them to GPU\n  Matrix<T,Dynamic,Dynamic> Rs(ps.rows()-1, this->K_*3);\n  for(uint32_t k=0; k<this->K_; ++k)\n    Rs.middleCols(k*3,3) = sphere_.north_R_TpS2(ps.col(k)).topRows(2);\n \n  d_ps_.set(ps);\n  d_northRps_.set(Rs);\n\n  // q is already in GPU since construction\n//  d_ps_.print(); d_q_.print(); d_northRps_.print(); this->d_z_.print(); d_q_.print();\n//  this->d_x_.print();\n  \n  Log_p_gpu(d_ps_.data(), d_q_.data(), d_northRps_.data(), this->d_z_.data(), \n      this->K_, d_q_.cols(), this->d_x_.data());\n  \n//  d_northRps_.get(Rs);\n//  cout<<Rs<<endl;\n//  Matrix<T,Dynamic,Dynamic> pps(ps.rows(),ps.cols());\n//  d_ps_.get(pps);\n//  cout<<pps<<endl;\n};\n\ntemplate<typename T>\nMatrix<T,Dynamic,Dynamic> ClTGMMDataGpu<T>::meanInTpS2(\n    const Matrix<T,Dynamic,Dynamic>& ps)\n{\n  assert(ps.cols() == this->K_);\n  assert(ps.rows() == this->D_);\n\n  // one more dimension to hold the counts\n  Matrix<T,Dynamic,Dynamic> muKarch = \n    Matrix<T,Dynamic,Dynamic>::Zero(this->D_+1,this->K_);\n  d_muKarch_.set(muKarch);\n  d_ps_.set(ps);\n\n//  cout<<\"ClTGMMDataGpu<T>::meanInTpS2: mean starting from \"<<endl<<ps<<endl;\n//  cout<<d_ps_.rows()<<\" \"<<d_ps_.cols()<<endl;\n//  cout<<d_muKarch_.rows()<<\" \"<<d_muKarch_.cols()<<endl;\n//  cout<<d_q_.rows()<<\" \"<<d_q_.cols()<<endl;\n//  cout<<this->d_z_.rows()<<\" \"<<this->d_z_.cols()<<endl;\n\n//  cout<<d_ps_.get()<<endl;\n//  cout<<d_muKarch_.get()<<endl;\n//  cout<<d_q_.get()<<endl;\n//  cout<<this->d_z_.get()<<endl;\n\n  meanInTpS2_gpu(d_ps_.data(), d_muKarch_.data(), d_q_.data(), this->d_z_.data(),\n      this->N_,this->K_);\n  //meanInTpS2GPU(h_p, d_p_, h_mu_karch, d_mu_karch_, d_q_, d_z, w_, h_);\n  d_muKarch_.get(muKarch);\n\n  Matrix<T,Dynamic,Dynamic> mu = muKarch.topRows(this->D_);\n  for(uint32_t k=0; k<this->K_; ++k)\n    if(muKarch(this->D_,k) > 0)\n    {\n      mu.col(k) /= muKarch(this->D_,k);\n    }\n\n//  cout<<muKarch<<endl<<endl;\n//  cout<<mu<<endl;\n  return mu;\n}\n\ntemplate<typename T>\nMatrix<T,Dynamic,Dynamic> ClTGMMDataGpu<T>::karcherMeans(const Matrix<T,Dynamic,Dynamic>& p0, uint32_t maxIter)\n{\n  // stand alone karcher means\n  assert(this->z_->maxCoeff() < this->K_); // no indicators \\geq K\n  assert(this->z_->minCoeff() >= 0); // no indicators \\le 0\n  assert((this->z_->array() < this->K_).all());\n  // update the labels on the GPU\n  this->d_z_.set(this->z_);\n\n  Matrix<T,Dynamic,Dynamic> p(p0.rows(),p0.cols());\n  Timer t;\n  p = karcherMeans__(p0);\n  t.toctic(\"karcherMeansFull\");\n  return p;\n};\n\ntemplate<typename T>\nMatrix<T,Dynamic,Dynamic> ClTGMMDataGpu<T>::karcherMeans__(const Matrix<T,Dynamic,Dynamic>& p0, uint32_t maxIter)\n{\n\n  assert(p0.rows() == d_ps_.rows()); // we dont want dimension change\n  Matrix<T,Dynamic,Dynamic> p = p0;\n//  cout<<\"p0\"<<endl<<p<<endl;\n\n  Matrix<T,Dynamic,1> residual(this->K_);\n  residual.setOnes(this->K_);\n//  cout<<(this->z_->transpose())<<endl;\n  for(uint32_t i=0; i< maxIter; ++i)\n  {\n//    Timer t0;\n    Matrix<T,Dynamic,Dynamic> mu_karch = meanInTpS2(p);\n//    t0.toctic(\"meanInTpS2_GPU\");\n//    cout<<\"mu_karch\"<<endl<<mu_karch<<endl;\n//    cout<<\"p\"<<endl<<p<<endl;\n    for (uint32_t k=0; k<this->K_; ++k)\n    {\n      p.col(k) = sphere_.Exp_p(p.col(k),mu_karch.col(k));\n//      cout<<p.col(k).norm()<<endl;\n      residual(k) = mu_karch.col(k).norm();\n    }\n//    cout<<\"p\"<<endl<<p<<endl;\n    //cout<<\"karcherMeans \"<<i<<\" residual=\"<<residual<<endl;\n//    cout<<\"@\"<<i<<\" residual = \"<<residual.transpose()<<endl;\n    if((residual.array() < 1e-5).all())\n    {\n      cout<<\"ClTGMMDataGpu<T>::karcherMeans__: converged after \"<<i\n        <<\" residual = \"<<residual.transpose()<<endl;\n      assert((residual.array() != 0.0).any());\n//      assert(i>0); // first itaration convergence is rare\n      break;\n    }\n  }\n//  cout<<\"p\"<<endl<<p<<endl;\n  return p;\n}\n\n\ntemplate<typename T>\nvoid ClTGMMDataGpu<T>::Log_p_north(const Matrix<T,Dynamic,Dynamic>& ps, \n    const VectorXu& z, Matrix<T,Dynamic,Dynamic>& x, int32_t K)\n{\n  Log_p_north(ps,z,K);\n  this->d_x_.get(x);\n};\n\n\ntemplate<typename T>\nvoid ClTGMMDataGpu<T>::Log_p_north(const Matrix<T,Dynamic,Dynamic>& ps, \n    const VectorXu& z,  int32_t K)\n{\n  if(K > 0){\n    this->K_ = K>0?K:this->z_->maxCoeff()+1;\n//    cout<<this->K_<<\" \"<< uint32_t(this->z_->maxCoeff()) <<endl;\n    assert(this->z_->maxCoeff() < this->K_); // no indicators \\geq K\n    assert(this->z_->minCoeff() >= 0); // no indicators \\le 0\n    assert((this->z_->array() < this->K_).all());\n  }\n  // updates d_ps_, d_northRps_, this->d_z_, this->K_\n  relinearize(ps);\n  this->d_z_.set(z);\n  //TODO shouldnt need to do this everytime?\n  d_q_.set(*this->x_);\n  // q is already in GPU since construction\n//  d_ps_.print();\n//  d_q_.print();\n//  d_northRps_.print();\n//  this->d_z_.print();\n//  d_q_.print();\n//  this->d_x_.print();\n  \n  Log_p_gpu(d_ps_.data(), d_q_.data(), d_northRps_.data(), this->d_z_.data(), \n      this->K_, d_q_.cols(),this->d_x_.data());\n};\n\ntemplate<typename T>\nvoid ClTGMMDataGpu<T>::computeLogLikelihoods(const Matrix<T,Dynamic,1>& pi, \n    const vector<Matrix<T,Dynamic,Dynamic> >& Sigmas, \n    const Matrix<T,Dynamic,1>& logNormalizers)\n{\n//  cout<<\"ClGMMDataGpu<T>::sampleGMMpdf\"<<endl;\n  assert(pi.size() == this->K_);\n  assert(logNormalizers.size() == this->K_);\n\n  Matrix<T,Dynamic,Dynamic> invSigmas((this->D_-1)*(this->D_-1),this->K_);\n//  Matrix<T,Dynamic,1> logNormalizer(this->K_);\n  for(uint32_t k=0; k<this->K_; ++k)\n  {\n    Matrix<T,Dynamic,Dynamic> invS =Sigmas[k].inverse();\n    for(uint32_t i=0; i<invS.cols(); ++i)\n      for(uint32_t j=0; j<invS.rows(); ++j)\n        invSigmas(i*invS.rows()+j,k) = invS(j,i);\n//    logNormalizer(k) = -0.5*Sigmas[k]\n  }\n//  assert(fabs(pi.sum()-1.0) <1e-6);\n  Matrix<T,Dynamic,1> logPi = pi.array().log().matrix();\n  //copy parameters into memory\n  this->d_logPi_.set(logPi);  \n  this->d_invSigmas_.set(invSigmas);\n  this->d_logNormalizers_.set(logNormalizers);\n\n//  cout<<\"sphereGMMPdf\"<<endl;\n//  cout<<\"logNormaloizers\"<<endl<<logNormalizers.transpose()<<endl;\n//  cout<<\"logPi\"<<endl<<logPi.transpose()<<endl;\n//  cout<<invSigmas<<endl;\n//  \n//  d_ps_.data();\n//  d_northRps_.data();\n//  d_q_.data();\n//  d_invSigmas_.data();\n//  d_logNormalizers_.data();\n//  d_logPi_.data();\n\n  Matrix<T,Dynamic,Dynamic> pdfs(this->N_,this->K_); \n  if(!this->d_pdfs_->isInit())\n  { \n    this->d_pdfs_->setZero();\n//    pdfs = Matrix<T,Dynamic,Dynamic>::Zero(this->N_,this->K_);\n//    d_pdfs_->set(pdfs);\n  }\n\n  sphereGMMPdf(d_ps_.data(), d_northRps_.data(), d_q_.data(), \n    this->d_invSigmas_.data(), this->d_logNormalizers_.data(), \n    this->d_logPi_.data(), this->d_pdfs_->data(), this->N_, this->K_);\n};\n\ntemplate<typename T>\nvoid ClTGMMDataGpu<T>::sampleGMMpdf(const Matrix<T,Dynamic,1>& pi, \n    const vector<Matrix<T,Dynamic,Dynamic> >& Sigmas, \n    const Matrix<T,Dynamic,1>& logNormalizers, Sampler<T> *sampler)\n{\n  computeLogLikelihoods(pi,Sigmas,logNormalizers);\n\n  sampler->sampleDiscPdf(this->d_pdfs_->data(),this->z_);\n\n//  cout<< this->z_->transpose()<<endl;\n//  d_pdfs_->get(pdfs);\n//  cout<<pdfs<<endl;\n  \n};\n", "meta": {"hexsha": "40b0596781e7cc544534ce0396c07200b8c25ffe", "size": 13913, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/dpMM/clTGMMDataGpu.hpp", "max_stars_repo_name": "jstraub/dpMM", "max_stars_repo_head_hexsha": "538c432d5f98c040d5c1adb072e545e38f97fc69", "max_stars_repo_licenses": ["MIT-feh"], "max_stars_count": 11.0, "max_stars_repo_stars_event_min_datetime": "2015-04-27T15:14:01.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-18T00:19:18.000Z", "max_issues_repo_path": "include/dpMM/clTGMMDataGpu.hpp", "max_issues_repo_name": "jstraub/dpMM", "max_issues_repo_head_hexsha": "538c432d5f98c040d5c1adb072e545e38f97fc69", "max_issues_repo_licenses": ["MIT-feh"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/dpMM/clTGMMDataGpu.hpp", "max_forks_repo_name": "jstraub/dpMM", "max_forks_repo_head_hexsha": "538c432d5f98c040d5c1adb072e545e38f97fc69", "max_forks_repo_licenses": ["MIT-feh"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2015-07-02T12:46:20.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-30T04:39:30.000Z", "avg_line_length": 33.1261904762, "max_line_length": 113, "alphanum_fraction": 0.6519801624, "num_tokens": 4641, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6926419831347361, "lm_q2_score": 0.46490157137338844, "lm_q1q2_score": 0.32201034635851883}}
{"text": "#include <Eigen/Core>\n#include <Eigen/Sparse>\n#include <iostream>\n#include <igl/readDMAT.h>\n#include <igl/writeDMAT.h>\n#include <unordered_map>\n#include <array>\n#include <vector>\n#include <queue>\n\nvoid sparse_continuation(const Eigen::RowVector3d p0, const std::vector<Eigen::RowVector3i> init_voxels, const std::vector<double> t0, const std::function<double(const Eigen::RowVector3d &, double &, std::vector<std::vector<double>> &, std::vector<std::vector<double>> &, std::vector<std::vector<double>> &)> scalarFunc, const double eps, const int expected_number_of_cubes, Eigen::VectorXd & CS, Eigen::MatrixXd & CV, Eigen::MatrixXi & CI, Eigen::VectorXd & CV_argmins_vector){\n    \n    struct IndexRowVectorHash  {\n        std::size_t operator()(const Eigen::RowVector3i& key) const {\n            std::size_t seed = 0;\n            std::hash<int> hasher;\n            for (int i = 0; i < 3; i++) {\n                seed ^= hasher(key[i]) + 0x9e3779b9 + (seed<<6) + (seed>>2); // Copied from boost::hash_combine\n            }\n            return seed;\n        }\n    };\n    \n    auto sgn = [](double val) -> int {\n        return (double(0) < val) - (val < double(0));\n    };\n    \n    double half_eps = 0.5 * eps;\n    \n    std::vector<Eigen::Matrix<int,1,8>> CI_vector;\n    std::vector<Eigen::RowVector3d> CV_vector;\n    std::vector<std::vector<std::vector<double>>> CV_intervals;\n    std::vector<std::vector<std::vector<double>>> CV_values;\n    std::vector<std::vector<std::vector<double>>> CV_minima;\n    std::vector<double> CS_vector;\n    CI_vector.reserve(expected_number_of_cubes);\n    CV_vector.reserve(8 * expected_number_of_cubes);\n    CS_vector.reserve(8 * expected_number_of_cubes);\n    std::vector<std::vector<double>> argmins;\n    std::vector<double> CV_argmins;\n    \n    argmins.reserve(32 * expected_number_of_cubes);\n    int counter = 0;\n    \n    // Track visisted neighbors\n    std::unordered_map<Eigen::RowVector3i, int, IndexRowVectorHash> visited;\n    visited.reserve(6 * expected_number_of_cubes);\n    visited.max_load_factor(0.5);\n    \n    // BFS Queue\n    auto cmp = [](std::tuple<Eigen::RowVector3i, double, int, double> left, std::tuple<Eigen::RowVector3i, double, int, double> right) {\n        double pleft, pright;\n        pleft = std::get<3>(left);\n        pright = std::get<3>(right);\n        return pleft > pright;\n    };\n    \n    std::priority_queue<std::tuple<Eigen::RowVector3i, double, int, double>, std::vector<std::tuple<Eigen::RowVector3i, double, int, double>>, decltype(cmp)> p_queue(cmp);\n    \n    std::vector<Eigen::RowVector3i> queue;\n    queue.reserve(expected_number_of_cubes * 8);\n    std::vector<double> time_queue;\n    time_queue.reserve(expected_number_of_cubes * 8);\n    std::vector<int> correspondence_queue;\n    correspondence_queue.reserve(expected_number_of_cubes * 8);\n    std::vector<double> intervals_turn, values_turn, minima_turn;\n    \n    for (int seed_ind = 0; seed_ind < init_voxels.size(); seed_ind++) {\n        \n        double min_turn = 1000.0;\n        double final_seed = t0[seed_ind];\n//        for (double tt = 0; tt <=1.0; tt = tt + 0.1) {\n//            intervals_turn.resize(0);\n//            values_turn.resize(0);\n//            minima_turn.resize(0);\n//            double seed_turn = tt;\n//            Eigen::RowVector3i pi_turn = init_voxels[seed_ind];\n//            Eigen::RowVector3d ctr_turn = p0 + eps*pi_turn.cast<double>();\n//            double val_turn = scalarFunc(ctr_turn,seed_turn,intervals_turn,values_turn,minima_turn);\n//            if (val_turn < min_turn) {\n//                final_seed = seed_turn;\n//                min_turn = val_turn;\n//            }\n//        }\n        queue.push_back(init_voxels[seed_ind]);\n        time_queue.push_back(final_seed);\n        correspondence_queue.push_back(-1);\n        auto bar = std::make_tuple(init_voxels[seed_ind], final_seed, -1, 0.0);\n        p_queue.push(bar);\n    }\n    //queue.push_back(Eigen::RowVector3i(0, 0, 0));\n    //time_queue.push_back(t0);\n    //std::cout << \"test\" << std::endl;\n    \n    int additions_normal, additions_corrections, additions_self;\n    additions_normal = 0;\n    additions_corrections = 0;\n    additions_self = 0;\n    while (queue.size() > 0)\n    {\n        Eigen::RowVector3i pi = queue.back();\n        queue.pop_back();\n        double time_seed = time_queue.back();\n        time_queue.pop_back();\n        int correspondence = correspondence_queue.back();\n        correspondence_queue.pop_back();\n        \n        \n//        std::tuple<Eigen::RowVector3i, double, int, double> val;\n//        val = p_queue.top();\n//        p_queue.pop();\n//        pi = std::get<0>(val);\n//        time_seed = std::get<1>(val);\n//        correspondence = std::get<2>(val);\n        \n        \n        Eigen::RowVector3d ctr = p0 + eps*pi.cast<double>(); // R^3 center of this cube\n        \n        // X, Y, Z basis vectors, and array of neighbor offsets used to construct cubes\n        const Eigen::RowVector3i bx(1, 0, 0), by(0, 1, 0), bz(0, 0, -1);\n        const std::array<Eigen::RowVector3i, 30> neighbors = {\n            bx, -bx, by, -by, bz, -bz,\n            by-bz, -by+bz, // 1-2 4-7\n            bx+by, -bx-by, // 0-1 7-6\n            by+bz, -by-bz,  // 0-3 6-5\n            by-bx, -by+bx,  // 2-3 5-4\n            bx-bz, -bx+bz, // 1-5 3-7\n            bx+bz, -bx-bz, // 0-4 2-6\n            -bx+by+bz, bx-by-bz, // 3 5\n            bx+by+bz, -bx-by-bz, // 0 6\n            bx+by-bz, -bx-by+bz, //1 7\n            -bx+by-bz, bx-by+bz, // 2 4,\n            bx-bx, bx-bx,\n            bx-bx, bx-bx\n        };\n        \n        // Compute the position of the cube corners and the scalar values at those corners\n        std::array<Eigen::RowVector3d, 8> cubeCorners = {\n            ctr+half_eps*(bx+by+bz).cast<double>(), ctr+half_eps*(bx+by-bz).cast<double>(), ctr+half_eps*(-bx+by-bz).cast<double>(), ctr+half_eps*(-bx+by+bz).cast<double>(),\n            ctr+half_eps*(bx-by+bz).cast<double>(), ctr+half_eps*(bx-by-bz).cast<double>(), ctr+half_eps*(-bx-by-bz).cast<double>(), ctr+half_eps*(-bx-by+bz).cast<double>()\n        };\n        std::array<double, 8> cubeScalars;\n        //double time_seed = 0.0;\n        //std::cout << time_seed << std::endl;\n        double time_test;\n        argmins[CI_vector.size()].resize(8);\n        std::vector<double> argmins_cube;\n        \n        \n        \n        // Add the cube vertices and indices to the output arrays if they are not there already\n        \n        uint8_t vertexAlreadyAdded = 0; // This is a bimask. If a bit is 1, it has been visited already by the BFS\n        constexpr std::array<uint8_t, 30> zv = {\n            (1 << 0) | (1 << 1) | (1 << 4) | (1 << 5),\n            (1 << 2) | (1 << 3) | (1 << 6) | (1 << 7),\n            (1 << 0) | (1 << 1) | (1 << 2) | (1 << 3),\n            (1 << 4) | (1 << 5) | (1 << 6) | (1 << 7),\n            (1 << 0) | (1 << 3) | (1 << 4) | (1 << 7),\n            (1 << 1) | (1 << 2) | (1 << 5) | (1 << 6),\n            (1 << 1) | (1 << 2),\n            (1 << 4) | (1 << 7),\n            (1 << 0) | (1 << 1),\n            (1 << 6) | (1 << 7),\n            (1 << 0) | (1 << 3),\n            (1 << 5) | (1 << 6),\n            (1 << 2) | (1 << 3),\n            (1 << 4) | (1 << 5),\n            (1 << 1) | (1 << 5),\n            (1 << 3) | (1 << 7),\n            (1 << 0) | (1 << 4),\n            (1 << 2) | (1 << 6),\n            (1 << 3), (1 << 5), // diagonals\n            (1 << 0), (1 << 6),\n            (1 << 1), (1 << 7),\n            (1 << 2), (1 << 4),\n            (1 << 0) | (1 << 1) | (1 << 2) | (1 << 3),\n            (1 << 0) | (1 << 1) | (1 << 2) | (1 << 3),\n            (1 << 4) | (1 << 5) | (1 << 6) | (1 << 7),\n            (1 << 4) | (1 << 5) | (1 << 6) | (1 << 7),\n        };\n        constexpr std::array<std::array<int, 4>, 30> zvv {{\n            {{0, 1, 4, 5}}, {{3, 2, 7, 6}}, {{0, 1, 2, 3}},\n            {{4, 5, 6, 7}}, {{0, 3, 4, 7}}, {{1, 2, 5, 6}},\n            {{-1,-1,1,2}}, {{-1,-1,4,7}}, {{-1,-1,0,1}},{{-1,-1,7,6}},\n            {{-1,-1,0,3}}, {{-1,-1,5,6}}, {{-1,-1,2,3}}, {{-1,-1,5,4}},\n            {{-1,-1,1,5}}, {{-1,-1,3,7}}, {{-1,-1,0,4}}, {{-1,-1,2,6}},\n            {{-1,-1,-1,3}}, {{-1,-1,-1,5}}, {{-1,-1,-1,0}}, {{-1,-1,-1,6}},\n            {{-1,-1,-1,1}}, {{-1,-1,-1,7}}, {{-1,-1,-1,2}}, {{-1,-1,-1,4}},\n            {{0,1,2,3}}, {{0,1,2,3}}, {{4,5,6,7}}, {{4,5,6,7}}\n        }};\n        bool flag = false;\n        \n        \n        Eigen::Matrix<int,1,8> cube;\n        cube << -1, -1, -1, -1, -1, -1, -1, -1;\n        for (int n = 0; n < 30; n++) { // For each neighbor, check the hash table to see if its been added before\n            Eigen::RowVector3i nkey = pi + neighbors[n];\n            auto nbr = visited.find(nkey);\n            if (nbr != visited.end()) {\n                for (int i = 0; i < 4; i++) {\n                    if (zvv[n][i]!=-1) {\n                        cube[zvv[n][i]] = CI_vector[nbr->second][zvv[n % 2 == 0 ? n + 1 : n - 1][i]];\n                    }\n                }\n            }\n        }\n        \n        \n        // do we already know we're inside?\n        bool we_in = true;\n        for (int i = 0; i<8; i++) {\n            if(cube[i]==-1){\n                we_in = false;\n                break;\n            }\n            if (CS_vector[cube[i]] > 0.0) {\n                we_in = false;\n                break;\n            }\n        }\n        \n        if (we_in) {\n            continue;\n        }\n        \n        \n        \n        std::vector<std::vector<std::vector<double>>> intervals;\n        intervals.resize(8);\n        std::vector<std::vector<std::vector<double>>> values;\n        values.resize(8);\n        std::vector<std::vector<std::vector<double>>> minima;\n        minima.resize(8);\n        \n        bool debug_flag = false;\n        bool in_existing_interval = false;\n        bool intersecting_interval = false;\n        time_test = time_seed;\n        double running_argmin = 0.0;\n        for (int i = 0; i < 8; i++){\n            time_test = time_seed;\n            //            cubeScalars[i] = scalarFunc(cubeCorners[i],time_test);\n            //            argmins[CI_vector.size()][i] = time_test;\n            //   running_argmin = running_argmin + (time_test/8.0);\n            \n            if (cube[i] >= 0) {\n                cubeScalars[i] = scalarFunc(cubeCorners[i],time_test,CV_intervals[cube[i]], CV_values[cube[i]], CV_minima[cube[i]]);\n                argmins[CI_vector.size()][i] = time_test;\n                \n                if (correspondence==-1) {\n                double temp = cubeScalars[i];\n                    //std::cout << \"We got \" << temp << \" at \" << time_seed << \"...\";\n                int temp_i = -1;\n                    int temp_s = -1;\n                    for (int s = 0; s < CV_intervals[cube[i]].size(); s++) {\n                for (int mm = 0; mm < (CV_intervals[cube[i]][s].size()/2); mm++){\n                    if ( (CV_values[cube[i]][s][mm]+1e-3) < temp) {\n                        temp = CV_values[cube[i]][s][mm];\n                        temp_i = mm;\n                        temp_s = s;\n                    }\n                }}\n                if (temp_i > -1) {\n                     //JAN 24 change this\n                    queue.push_back(pi);\n                    //std::cout << \" but we found \" << temp << \" at \" << CV_minima[cube[i]][temp_s][temp_i] << \" (correspondence \" << correspondence << std::endl;\n                    // Otherwise, we have not visited the neighbor, put it in the BFS queue\n                    // time_queue.push_back(time_test);\n                    time_queue.push_back(CV_minima[cube[i]][temp_s][temp_i]);\n                    correspondence_queue.push_back(1);\n                    auto bar = std::make_tuple(pi, CV_minima[cube[i]][temp_s][temp_i], 1, temp);\n                    p_queue.push(bar);\n                    additions_self++;\n                    \n                    //time_seed = CV_minima[cube[i]][temp_s][temp_i];\n//                    cubeScalars[i] = temp;\n//                    argmins[CI_vector.size()][i] = CV_minima[cube[i]][temp_s][temp_i];\n                }else{\n                    //std::cout << std::endl;\n                }\n                }\n                // DEBUGGING\n                //                if (cube[i]==10) {\n//                std::cout << \"______________\";\n//                std::cout << \"Time seed: \" << time_seed << std::endl;\n//                for (int mm = 0; mm < (CV_intervals[cube[i]].size()/2); mm++){\n//                    std::cout << \"Existing interval: \" << CV_intervals[cube[i]][2*mm] << \" \" <<  CV_intervals[cube[i]][2*mm + 1] << \" value: \" << CV_values[cube[i]][mm] << std::endl;\n//                }\n                //                }\n                //                            in_existing_interval = false;\n                //                            for (int mm = 0; mm < (CV_intervals[cube[i]].size()/2); mm++) {\n                //                                if ((time_test >= CV_intervals[cube[i]][2*mm]) && (time_test <= CV_intervals[cube[i]][2*mm+1]) ){\n                //                                    cubeScalars[i] = CV_values[cube[i]][mm];\n                //                                    argmins[CI_vector.size()][i] = CV_minima[cube[i]][mm];\n                //                                    in_existing_interval = true;\n                //                                }\n                //                            }\n                //                            if (!in_existing_interval) {\n                //                                intersecting_interval = false;\n                //                                time_test = time_seed;\n                //                                cubeScalars[i] = scalarFunc(cubeCorners[i],time_test,CV_intervals[cube[i]], CV_values[cube[i]], CV_minima[cube[i]]);\n                //                                argmins[CI_vector.size()][i] = time_test;\n                //                                for (int mm = 0; mm < (CV_intervals[cube[i]].size()/2); mm++) {\n                //                                    if ((time_test >= CV_intervals[cube[i]][2*mm]) && (time_test <= CV_intervals[cube[i]][2*mm+1]) ){\n                //                                        intersecting_interval = true;\n                //                                        CV_intervals[cube[i]][2*mm] = std::min(CV_intervals[cube[i]][2*mm],time_seed);\n                //                                        CV_intervals[cube[i]][2*mm+1] = std::max(CV_intervals[cube[i]][2*mm+1],time_seed);\n                //                                        CV_values[cube[i]][mm] = std::min(CV_values[cube[i]][mm],cubeScalars[i]); //  ??\n                //                                    }\n                //                                }\n                //                            }\n                //                            if (!in_existing_interval && !intersecting_interval) {\n                //                                std::vector<double> interval_i;\n                //                                interval_i.push_back(time_test);\n                //                                interval_i.push_back(time_seed);\n                //                                std::sort(interval_i.begin(), interval_i.end());\n                //                                CV_intervals[cube[i]].push_back(interval_i[0]);\n                //                                CV_intervals[cube[i]].push_back(interval_i[1]);\n                //                                CV_values[cube[i]].push_back(cubeScalars[i]);\n                //                                CV_minima[cube[i]].push_back(time_test);\n                //                            }\n                //                time_test = time_seed;\n                //                double debug = scalarFunc(cubeCorners[i],time_test);\n                //                if (fabs(debug - cubeScalars[i])>1e-3 ) {\n                //                                std::cout << \"______________\";\n                ////                                std::cout << \"Seed: \" << time_seed << \" value \" << debug << \" at time \" << time_test << std::endl;\n                //                                for (int mm = 0; mm < (CV_intervals[cube[i]].size()/2); mm++){\n                //                                    std::cout << \"Existing interval :\" << CV_intervals[cube[i]][2*mm] << \" \" <<  CV_intervals[cube[i]][2*mm + 1] << \" value: \" << CV_values[cube[i]][mm] << std::endl;\n                //                                }\n                //                                std::cout << \"Point: \" << CV_vector[cube[i]] << std::endl;\n                //                }\n                \n            }else{\n                time_test = time_seed;\n                intervals[i].resize(0);\n                values[i].resize(0);\n                minima[i].resize(0);\n                cubeScalars[i] = scalarFunc(cubeCorners[i],time_test,intervals[i],values[i],minima[i]);\n                argmins[CI_vector.size()][i] = time_test;\n            }\n            \n            running_argmin = running_argmin + (argmins[CI_vector.size()][i]/8.0);\n            //            if (cubeScalars[i]>0.3) {\n            //                debug_flag = true;\n            //            }\n            \n        }\n        //std::cout << time_test << std::endl;\n        // If this cube doesn't intersect the surface, disregard it\n        bool validCube = false;\n        int sign = sgn(cubeScalars[0]);\n        for (int i = 1; i < 8; i++) {\n            if (sign != sgn(cubeScalars[i])) {\n                validCube = true;\n                break;\n            }\n        }\n        \n        \n        \n        \n        //    if (!validCube) {\n        //continue;\n        //  }\n        \n        // Debugging\n        //        if (debug_flag) {\n        //            std::cout << \"voxel\" << std::endl;\n        //            for (int i = 0; i<8; i++) {\n        //                std::cout << \"value: \" << cubeScalars[i] << \" at time\" << argmins[CI_vector.size()][i] << \" with seed\" << time_seed << std::endl;\n        //\n        //            }\n        //        }\n        \n        \n        \n        \n        \n        \n        for (int n = 0; n < 30; n++) { // For each neighbor, check the hash table to see if its been added before\n            Eigen::RowVector3i nkey = pi + neighbors[n];\n            auto nbr = visited.find(nkey);\n            flag = false;\n            if (nbr != visited.end()) { // We've already visited this neighbor, use references to its vertices instead of duplicating them\n                vertexAlreadyAdded |= zv[n];\n                for (int i = 0; i < 4; i++) {\n                    if (zvv[n][i]!=-1) {\n                        cube[zvv[n][i]] = CI_vector[nbr->second][zvv[n % 2 == 0 ? n + 1 : n - 1][i]];\n                        //              if( CS_vector[cube[zvv[n][i]]] < cubeScalars[zvv[n][i]] ){\n                        //                  // It was better before\n                        //                  cubeScalars[zvv[n][i]] = CS_vector[cube[zvv[n][i]]];\n                        //              }else\n                        if((CS_vector[cube[zvv[n][i]]]>cubeScalars[zvv[n][i]] && (CS_vector[cube[zvv[n][i]]]*cubeScalars[zvv[n][i]])<0) || CS_vector[cube[zvv[n][i]]]>(cubeScalars[zvv[n][i]] + 1e-3)){\n                            if (!flag) {\n                                queue.push_back(nkey);\n                                //time_queue.push_back(time_test);\n                                // JAN 24 CHANGE THIS\n                                time_queue.push_back(running_argmin);\n                                correspondence_queue.push_back(nbr->second);\n                                additions_corrections++;\n                                flag = true;\n                                auto bar = std::make_tuple(nkey, running_argmin, nbr->second, cubeScalars[zvv[n][i]]);\n                                p_queue.push(bar);\n                            }\n                        }\n                        \n                        \n                        // WARNING: THIS BELOW IS WRONG, HAVE TO CHANGE\n                        //cubeScalars[zvv[n][i]] = std::min(CS_vector[cube[zvv[n][i]]],cubeScalars[zvv[n][i]]);\n                        //CS_vector[cube[zvv[n][i]]] = cubeScalars[zvv[n][i]];\n                    }\n                }\n                //} else if(correspondence==-1) {\n            }\n        }\n        \n        validCube = false;\n        sign = sgn(cubeScalars[0]);\n        for (int i = 1; i < 8; i++) {\n            if (sign != sgn(cubeScalars[i])) {\n                validCube = true;\n            }\n        }\n        bool validCube_before = validCube;\n        \n        for (int n = 0; n < 30; n++) { // For each neighbor, check the hash table to see if its been added before\n            Eigen::RowVector3i nkey = pi + neighbors[n];\n            auto nbr = visited.find(nkey);\n            flag = false;\n            if (nbr != visited.end()) { // We've already visited this neighbor, use references to its vertices instead of duplicating them\n                for (int i = 0; i < 4; i++) {\n                    if (zvv[n][i]!=-1) {\n                        cube[zvv[n][i]] = CI_vector[nbr->second][zvv[n % 2 == 0 ? n + 1 : n - 1][i]];\n                        // WARNING: THIS BELOW IS WRONG, HAVE TO CHANGE\n                        cubeScalars[zvv[n][i]] = std::min(CS_vector[cube[zvv[n][i]]],cubeScalars[zvv[n][i]]);\n                        CS_vector[cube[zvv[n][i]]] = cubeScalars[zvv[n][i]];\n                    }\n                }\n                //} else if(correspondence==-1) {\n            }else{\n                //                validCube = false;\n                //                sign = sgn(cubeScalars[0]);\n                //                for (int i = 1; i < 8; i++) {\n                //                    if (sign != sgn(cubeScalars[i])) {\n                //                        validCube = true;\n                //                    }\n                //                }\n                if (validCube) {\n                    //                    if (debug_flag) {\n                    //                        std::cout << \"BAD THING HAPPENED\" << std::endl;\n                    //                    }\n                    //                    queue.push_back(nkey);\n                    //                    // Otherwise, we have not visited the neighbor, put it in the BFS queue\n                    //                   // time_queue.push_back(time_test);\n                    //                    time_queue.push_back(running_argmin);\n                    //                    correspondence_queue.push_back(-1);\n                }\n                \n            }\n        }\n  // WARNING THIS SHOULDNT BE COMMENTED!!\n        validCube = false;\n        sign = sgn(cubeScalars[0]);\n        for (int i = 1; i < 8; i++) {\n            if (sign != sgn(cubeScalars[i])) {\n                validCube = true;\n            }\n        }\n        \n        \n        for (int n = 0; n < 6; n++) { // For each neighbor, check the hash table to see if its been added before\n            Eigen::RowVector3i nkey = pi + neighbors[n];\n            auto nbr = visited.find(nkey);\n            flag = false;\n            if (nbr == visited.end()) {\n                if(validCube && validCube_before){\n                    queue.push_back(nkey);\n                    // Otherwise, we have not visited the neighbor, put it in the BFS queue\n                    // time_queue.push_back(time_test);\n                    \n                    time_queue.push_back(running_argmin);\n                    correspondence_queue.push_back(-1);\n                    auto bar = std::make_tuple(nkey, running_argmin, -1, 0.0);\n                    p_queue.push(bar);\n                    additions_normal++;\n                }\n            }\n        }\n        \n        \n        \n        \n        \n        auto did_we_visit_this_one = visited.find(pi);\n        if (correspondence==-1 && did_we_visit_this_one==visited.end()) {\n            for (int i = 0; i < 8; i++) { // Add new, non-visited,2 vertices to the arrays\n                //if (0 == ((1 << i) & vertexAlreadyAdded)) {\n                if (0 == ((1 << i) & vertexAlreadyAdded)) {\n//                    std::vector<double> interval;\n//                    std::vector<double> interval_values;\n//                    std::vector<double> interval_minima;\n//                    std::vector<double> interval_big;\n//                    std::vector<double> interval_values_big;\n//                    std::vector<double> interval_minima_big;\n//                    interval_minima.push_back(argmins[CI_vector.size()][i]);\n//                    interval.push_back(argmins[CI_vector.size()][i]);\n//                    interval.push_back(time_seed);\n//                    std::sort(interval.begin(), interval.end());\n//                    interval_values.push_back(cubeScalars[i]);\n                    \n                    \n                    CV_intervals.push_back(intervals[i]);\n                    CV_values.push_back(values[i]);\n                    CV_minima.push_back(minima[i]);\n                    cube[i] = CS_vector.size();\n                    CV_vector.push_back(cubeCorners[i]);\n                    CS_vector.push_back(cubeScalars[i]);\n                    CV_argmins.push_back(argmins[CI_vector.size()][i]);\n                }\n            }\n            \n            visited[pi] = CI_vector.size();\n            CI_vector.push_back(cube);\n        }\n        \n        //std::cout << queue.size() << std::endl;\n        \n        \n        bool debug = false;\n        if (debug) {\n            CV.resize(CV_vector.size(), 3);\n            CV_argmins_vector.resize(CV_vector.size(), 1);\n            CS.resize(CS_vector.size(), 1);\n            CI.resize(CI_vector.size(), 8);\n            Eigen::MatrixXi Q;\n            Q.resize(queue.size(),3);\n            for (int i = 0; i < queue.size(); i++) {\n                Q.row(i) = queue[i];\n            }\n            // If you pass in column-major matrices, this is going to be slooooowwwww\n            for (int i = 0; i < CV_vector.size(); i++) {\n                CV.row(i) = CV_vector[i];\n            }\n            for (int i = 0; i < CS_vector.size(); i++) {\n                CS(i) = CS_vector[i];\n            }\n            for (int i = 0; i < CI_vector.size(); i++) {\n                CI.row(i) = CI_vector[i];\n            }\n            igl::writeDMAT(\"/Volumes/Seagate Hard Drive/debug/CS\" + std::to_string(counter) + \".dmat\",CS);\n            igl::writeDMAT(\"/Volumes/Seagate Hard Drive/debug/CV\" + std::to_string(counter) + \".dmat\",CV);\n            igl::writeDMAT(\"/Volumes/Seagate Hard Drive/debug/CI\" + std::to_string(counter) + \".dmat\",CI);\n            igl::writeDMAT(\"/Volumes/Seagate Hard Drive/debug/Q\" + std::to_string(counter) + \".dmat\",Q);\n            counter = counter + 1;\n        }\n        \n        \n        \n        \n        \n    }\n    //std::cout << \"test\" << std::endl;\n//    std::cout << \" Normal: \" << additions_normal << std::endl;\n//    std::cout << \" Corrections: \" << additions_corrections << std::endl;\n//    std::cout << \" Self: \" << additions_self << std::endl;\n    \n    \n    \n    CV.conservativeResize(CV_vector.size(), 3);\n    CV_argmins_vector.conservativeResize(CV_vector.size(), 1);\n    CS.conservativeResize(CS_vector.size(), 1);\n    CI.conservativeResize(CI_vector.size(), 8);\n//    // If you pass in column-major matrices, this is going to be slooooowwwww\n//    for (int j = 0; j < CV_vector.size(); j++) {\n//        std::cout << \"______________\" << std::endl;\n//        for (int mm = 0; mm < (CV_intervals[j].size()/2); mm++){\n//            std::cout << \"Existing interval: \" << CV_intervals[j][2*mm] << \" \" <<  CV_intervals[j][2*mm + 1] << \" value: \" << CV_values[j][mm] << std::endl;\n//        }\n//    }\n                    \n    for (int i = 0; i < CV_vector.size(); i++) {\n        CV.row(i) = CV_vector[i];\n    }\n    for (int i = 0; i < CS_vector.size(); i++) {\n        CS(i) = CS_vector[i];\n        //CS(i) = std::min_element(CV_values[i].begin(), CV_values[i].end());\n    }\n    for (int i = 0; i < CI_vector.size(); i++) {\n        CI.row(i) = CI_vector[i];\n    }\n    for (int i = 0; i < CV_argmins.size(); i++) {\n        double val = 100.0;\n        double argmin = 0.0;\n        for(int s = 0; s<CV_values[i].size(); s++){\n        for (int mm = 0; mm<CV_values[i][s].size(); mm++) {\n            if (CV_values[i][s][mm]<val) {\n                val = CV_values[i][s][mm];\n                argmin = CV_minima[i][s][mm];\n            }\n        }\n        }\n        CV_argmins_vector(i) = argmin;\n    }\n}\n\n\n\n\n\nvoid sparse_continuation(const Eigen::RowVector3d p0, const std::vector<Eigen::RowVector3i> init_voxels, const std::vector<Eigen::RowVectorXd> t0, const  std::function<double(const Eigen::RowVector3d &, Eigen::RowVectorXd &, std::vector<std::vector<Eigen::RowVectorXd>> &, std::vector<std::vector<double>> &, std::vector<std::vector<Eigen::RowVectorXd>> &)> scalarFunc, const double eps, const int expected_number_of_cubes, Eigen::VectorXd & CS, Eigen::MatrixXd & CV, Eigen::MatrixXi & CI, Eigen::MatrixXd & CV_argmins_vector){\n    \n    struct IndexRowVectorHash  {\n        std::size_t operator()(const Eigen::RowVector3i& key) const {\n            std::size_t seed = 0;\n            std::hash<int> hasher;\n            for (int i = 0; i < 3; i++) {\n            seed ^= hasher(key[i]) + 0x9e3779b9 + (seed<<6) + (seed>>2); // Copied from boost::hash_combine\n            }\n            return seed;\n        }\n    };\n    \n    auto sgn = [](double val) -> int {\n        return (double(0) < val) - (val < double(0));\n    };\n    \n    double half_eps = 0.5 * eps;\n    \n    std::vector<Eigen::Matrix<int,1,8>> CI_vector;\n    std::vector<Eigen::RowVector3d> CV_vector;\n    std::vector<std::vector<std::vector<Eigen::RowVectorXd>>> CV_intervals;\n    std::vector<std::vector<std::vector<double>>> CV_values;\n    std::vector<std::vector<std::vector<Eigen::RowVectorXd>>> CV_minima;\n    std::vector<double> CS_vector;\n    CI_vector.reserve(expected_number_of_cubes);\n    CV_vector.reserve(8 * expected_number_of_cubes);\n    CS_vector.reserve(8 * expected_number_of_cubes);\n    std::vector<std::vector<Eigen::RowVectorXd>> argmins;\n    std::vector<Eigen::RowVectorXd> CV_argmins;\n    \n    argmins.reserve(32 * expected_number_of_cubes);\n    int counter = 0;\n    \n    // Track visisted neighbors\n    std::unordered_map<Eigen::RowVector3i, int, IndexRowVectorHash> visited;\n    visited.reserve(6 * expected_number_of_cubes);\n    visited.max_load_factor(0.5);\n    \n    // BFS Queue\n    std::vector<Eigen::RowVector3i> queue;\n    queue.reserve(expected_number_of_cubes * 8);\n    std::vector<Eigen::RowVectorXd> time_queue;\n    time_queue.reserve(expected_number_of_cubes * 8);\n    std::vector<int> correspondence_queue;\n    correspondence_queue.reserve(expected_number_of_cubes * 8);\n    std::vector<double> intervals_turn, values_turn, minima_turn;\n    \n    for (int seed_ind = 0; seed_ind < init_voxels.size(); seed_ind++) {\n        \n        double min_turn = 1000.0;\n        Eigen::VectorXd final_seed = t0[seed_ind];\n\n        queue.push_back(init_voxels[seed_ind]);\n        time_queue.push_back(final_seed);\n        correspondence_queue.push_back(-1);\n    }\n\n    while (queue.size() > 0)\n    {\n        Eigen::RowVector3i pi = queue.back();\n        queue.pop_back();\n        Eigen::VectorXd time_seed = time_queue.back();\n        time_queue.pop_back();\n        int correspondence = correspondence_queue.back();\n        correspondence_queue.pop_back();\n        \n        Eigen::RowVector3d ctr = p0 + eps*pi.cast<double>(); // R^3 center of this cube\n        \n        // X, Y, Z basis vectors, and array of neighbor offsets used to construct cubes\n        const Eigen::RowVector3i bx(1, 0, 0), by(0, 1, 0), bz(0, 0, -1);\n        const std::array<Eigen::RowVector3i, 30> neighbors = {\n            bx, -bx, by, -by, bz, -bz,\n            by-bz, -by+bz, // 1-2 4-7\n            bx+by, -bx-by, // 0-1 7-6\n            by+bz, -by-bz,  // 0-3 6-5\n            by-bx, -by+bx,  // 2-3 5-4\n            bx-bz, -bx+bz, // 1-5 3-7\n            bx+bz, -bx-bz, // 0-4 2-6\n            -bx+by+bz, bx-by-bz, // 3 5\n            bx+by+bz, -bx-by-bz, // 0 6\n            bx+by-bz, -bx-by+bz, //1 7\n            -bx+by-bz, bx-by+bz, // 2 4,\n            bx-bx, bx-bx,\n            bx-bx, bx-bx\n        };\n        \n        // Compute the position of the cube corners and the scalar values at those corners\n        std::array<Eigen::RowVector3d, 8> cubeCorners = {\n            ctr+half_eps*(bx+by+bz).cast<double>(), ctr+half_eps*(bx+by-bz).cast<double>(), ctr+half_eps*(-bx+by-bz).cast<double>(), ctr+half_eps*(-bx+by+bz).cast<double>(),\n            ctr+half_eps*(bx-by+bz).cast<double>(), ctr+half_eps*(bx-by-bz).cast<double>(), ctr+half_eps*(-bx-by-bz).cast<double>(), ctr+half_eps*(-bx-by+bz).cast<double>()\n        };\n        std::array<double, 8> cubeScalars;\n        //double time_seed = 0.0;\n        //std::cout << time_seed << std::endl;\n        Eigen::RowVectorXd time_test;\n        argmins[CI_vector.size()].resize(8);\n        std::vector<Eigen::RowVectorXd> argmins_cube;\n        \n        \n        \n        // Add the cube vertices and indices to the output arrays if they are not there already\n        \n        uint8_t vertexAlreadyAdded = 0; // This is a bimask. If a bit is 1, it has been visited already by the BFS\n        constexpr std::array<uint8_t, 30> zv = {\n            (1 << 0) | (1 << 1) | (1 << 4) | (1 << 5),\n            (1 << 2) | (1 << 3) | (1 << 6) | (1 << 7),\n            (1 << 0) | (1 << 1) | (1 << 2) | (1 << 3),\n            (1 << 4) | (1 << 5) | (1 << 6) | (1 << 7),\n            (1 << 0) | (1 << 3) | (1 << 4) | (1 << 7),\n            (1 << 1) | (1 << 2) | (1 << 5) | (1 << 6),\n            (1 << 1) | (1 << 2),\n            (1 << 4) | (1 << 7),\n            (1 << 0) | (1 << 1),\n            (1 << 6) | (1 << 7),\n            (1 << 0) | (1 << 3),\n            (1 << 5) | (1 << 6),\n            (1 << 2) | (1 << 3),\n            (1 << 4) | (1 << 5),\n            (1 << 1) | (1 << 5),\n            (1 << 3) | (1 << 7),\n            (1 << 0) | (1 << 4),\n            (1 << 2) | (1 << 6),\n            (1 << 3), (1 << 5), // diagonals\n            (1 << 0), (1 << 6),\n            (1 << 1), (1 << 7),\n            (1 << 2), (1 << 4),\n            (1 << 0) | (1 << 1) | (1 << 2) | (1 << 3),\n            (1 << 0) | (1 << 1) | (1 << 2) | (1 << 3),\n            (1 << 4) | (1 << 5) | (1 << 6) | (1 << 7),\n            (1 << 4) | (1 << 5) | (1 << 6) | (1 << 7),\n        };\n        constexpr std::array<std::array<int, 4>, 30> zvv {{\n            {{0, 1, 4, 5}}, {{3, 2, 7, 6}}, {{0, 1, 2, 3}},\n            {{4, 5, 6, 7}}, {{0, 3, 4, 7}}, {{1, 2, 5, 6}},\n            {{-1,-1,1,2}}, {{-1,-1,4,7}}, {{-1,-1,0,1}},{{-1,-1,7,6}},\n            {{-1,-1,0,3}}, {{-1,-1,5,6}}, {{-1,-1,2,3}}, {{-1,-1,5,4}},\n            {{-1,-1,1,5}}, {{-1,-1,3,7}}, {{-1,-1,0,4}}, {{-1,-1,2,6}},\n            {{-1,-1,-1,3}}, {{-1,-1,-1,5}}, {{-1,-1,-1,0}}, {{-1,-1,-1,6}},\n            {{-1,-1,-1,1}}, {{-1,-1,-1,7}}, {{-1,-1,-1,2}}, {{-1,-1,-1,4}},\n            {{0,1,2,3}}, {{0,1,2,3}}, {{4,5,6,7}}, {{4,5,6,7}}\n        }};\n        bool flag = false;\n        \n        \n        Eigen::Matrix<int,1,8> cube;\n        cube << -1, -1, -1, -1, -1, -1, -1, -1;\n        for (int n = 0; n < 30; n++) { // For each neighbor, check the hash table to see if its been added before\n            Eigen::RowVector3i nkey = pi + neighbors[n];\n            auto nbr = visited.find(nkey);\n            if (nbr != visited.end()) {\n                for (int i = 0; i < 4; i++) {\n                    if (zvv[n][i]!=-1) {\n                        cube[zvv[n][i]] = CI_vector[nbr->second][zvv[n % 2 == 0 ? n + 1 : n - 1][i]];\n                    }\n                }\n            }\n        }\n        \n        std::vector<std::vector<std::vector<Eigen::RowVectorXd>>> intervals;\n        intervals.resize(8);\n        std::vector<std::vector<std::vector<double>>> values;\n        values.resize(8);\n        std::vector<std::vector<std::vector<Eigen::RowVectorXd>>> minima;\n        minima.resize(8);\n        \n        bool debug_flag = false;\n        bool in_existing_interval = false;\n        bool intersecting_interval = false;\n        time_test = time_seed;\n        Eigen::RowVectorXd running_argmin;\n        running_argmin.resize(time_seed.size());\n        running_argmin.setZero();\n        for (int i = 0; i < 8; i++){\n            time_test = time_seed;\n            //            cubeScalars[i] = scalarFunc(cubeCorners[i],time_test);\n            //            argmins[CI_vector.size()][i] = time_test;\n            //   running_argmin = running_argmin + (time_test/8.0);\n            \n            if (cube[i] >= 0) {\n               // std::cout << \" CALL FUNC \" << std::endl;\n                cubeScalars[i] = scalarFunc(cubeCorners[i],time_test,CV_intervals[cube[i]], CV_values[cube[i]], CV_minima[cube[i]]);\n               // std::cout << \" end CALL FUNC \" << std::endl;\n                argmins[CI_vector.size()][i] = time_test;\n                minima[i] = CV_minima[cube[i]];\n                values[i] = CV_values[cube[i]];\n                intervals[i] = CV_intervals[cube[i]];\n                \n                if (correspondence==-1) {\n                double temp = cubeScalars[i];\n                int temp_i = -1;\n                    int temp_s = -1;\n                    for (int s = 0; s < CV_intervals[cube[i]].size(); s++) {\n                for (int mm = 0; mm < (CV_intervals[cube[i]][s].size()/2); mm++){\n                    if (CV_values[cube[i]][s][mm]+1e-3 < temp) {\n                        temp = CV_values[cube[i]][s][mm];\n                        temp_i = mm;\n                        temp_s = s;\n                    }\n                }}\n                if (temp_i > -1) {\n                    queue.push_back(pi);\n                    // Otherwise, we have not visited the neighbor, put it in the BFS queue\n                    // time_queue.push_back(time_test);\n                    time_queue.push_back(CV_minima[cube[i]][temp_s][temp_i]);\n                    correspondence_queue.push_back(1);\n                }\n                }\n                // DEBUGGING\n                //                if (cube[i]==10) {\n//                std::cout << \"______________\";\n//                std::cout << \"Time seed: \" << time_seed << std::endl;\n//                for (int mm = 0; mm < (CV_intervals[cube[i]].size()/2); mm++){\n//                    std::cout << \"Existing interval: \" << CV_intervals[cube[i]][2*mm] << \" \" <<  CV_intervals[cube[i]][2*mm + 1] << \" value: \" << CV_values[cube[i]][mm] << std::endl;\n//                }\n                //                }\n                //                            in_existing_interval = false;\n                //                            for (int mm = 0; mm < (CV_intervals[cube[i]].size()/2); mm++) {\n                //                                if ((time_test >= CV_intervals[cube[i]][2*mm]) && (time_test <= CV_intervals[cube[i]][2*mm+1]) ){\n                //                                    cubeScalars[i] = CV_values[cube[i]][mm];\n                //                                    argmins[CI_vector.size()][i] = CV_minima[cube[i]][mm];\n                //                                    in_existing_interval = true;\n                //                                }\n                //                            }\n                //                            if (!in_existing_interval) {\n                //                                intersecting_interval = false;\n                //                                time_test = time_seed;\n                //                                cubeScalars[i] = scalarFunc(cubeCorners[i],time_test,CV_intervals[cube[i]], CV_values[cube[i]], CV_minima[cube[i]]);\n                //                                argmins[CI_vector.size()][i] = time_test;\n                //                                for (int mm = 0; mm < (CV_intervals[cube[i]].size()/2); mm++) {\n                //                                    if ((time_test >= CV_intervals[cube[i]][2*mm]) && (time_test <= CV_intervals[cube[i]][2*mm+1]) ){\n                //                                        intersecting_interval = true;\n                //                                        CV_intervals[cube[i]][2*mm] = std::min(CV_intervals[cube[i]][2*mm],time_seed);\n                //                                        CV_intervals[cube[i]][2*mm+1] = std::max(CV_intervals[cube[i]][2*mm+1],time_seed);\n                //                                        CV_values[cube[i]][mm] = std::min(CV_values[cube[i]][mm],cubeScalars[i]); //  ??\n                //                                    }\n                //                                }\n                //                            }\n                //                            if (!in_existing_interval && !intersecting_interval) {\n                //                                std::vector<double> interval_i;\n                //                                interval_i.push_back(time_test);\n                //                                interval_i.push_back(time_seed);\n                //                                std::sort(interval_i.begin(), interval_i.end());\n                //                                CV_intervals[cube[i]].push_back(interval_i[0]);\n                //                                CV_intervals[cube[i]].push_back(interval_i[1]);\n                //                                CV_values[cube[i]].push_back(cubeScalars[i]);\n                //                                CV_minima[cube[i]].push_back(time_test);\n                //                            }\n                //                time_test = time_seed;\n                //                double debug = scalarFunc(cubeCorners[i],time_test);\n                //                if (fabs(debug - cubeScalars[i])>1e-3 ) {\n                //                                std::cout << \"______________\";\n                ////                                std::cout << \"Seed: \" << time_seed << \" value \" << debug << \" at time \" << time_test << std::endl;\n                //                                for (int mm = 0; mm < (CV_intervals[cube[i]].size()/2); mm++){\n                //                                    std::cout << \"Existing interval :\" << CV_intervals[cube[i]][2*mm] << \" \" <<  CV_intervals[cube[i]][2*mm + 1] << \" value: \" << CV_values[cube[i]][mm] << std::endl;\n                //                                }\n                //                                std::cout << \"Point: \" << CV_vector[cube[i]] << std::endl;\n                //                }\n                \n            }else{\n                time_test = time_seed;\n                intervals[i].resize(0);\n                values[i].resize(0);\n                minima[i].resize(0);\n          //      std::cout << \" CALL FUNC \" << std::endl;\n                cubeScalars[i] = scalarFunc(cubeCorners[i],time_test,intervals[i],values[i],minima[i]);\n          //      std::cout << \" end CALL FUNC \" << std::endl;\n                argmins[CI_vector.size()][i] = time_test;\n            }\n            \n            running_argmin = running_argmin + (argmins[CI_vector.size()][i]/8.0);\n            //            if (cubeScalars[i]>0.3) {\n            //                debug_flag = true;\n            //            }\n            \n        }\n        //std::cout << time_test << std::endl;\n        // If this cube doesn't intersect the surface, disregard it\n        bool validCube = false;\n        int sign = sgn(cubeScalars[0]);\n        for (int i = 1; i < 8; i++) {\n            if (sign != sgn(cubeScalars[i])) {\n                validCube = true;\n                break;\n            }\n        }\n        \n        \n        \n        \n        //    if (!validCube) {\n        //continue;\n        //  }\n        \n        // Debugging\n        //        if (debug_flag) {\n        //            std::cout << \"voxel\" << std::endl;\n        //            for (int i = 0; i<8; i++) {\n        //                std::cout << \"value: \" << cubeScalars[i] << \" at time\" << argmins[CI_vector.size()][i] << \" with seed\" << time_seed << std::endl;\n        //\n        //            }\n        //        }\n        \n        \n        \n        \n        \n        \n        for (int n = 0; n < 6; n++) { // For each neighbor, check the hash table to see if its been added before\n            Eigen::RowVector3i nkey = pi + neighbors[n];\n            auto nbr = visited.find(nkey);\n            flag = false;\n            if (nbr != visited.end()) { // We've already visited this neighbor, use references to its vertices instead of duplicating them\n                vertexAlreadyAdded |= zv[n];\n                for (int i = 0; i < 4; i++) {\n                    if (zvv[n][i]!=-1) {\n                        cube[zvv[n][i]] = CI_vector[nbr->second][zvv[n % 2 == 0 ? n + 1 : n - 1][i]];\n                        //              if( CS_vector[cube[zvv[n][i]]] < cubeScalars[zvv[n][i]] ){\n                        //                  // It was better before\n                        //                  cubeScalars[zvv[n][i]] = CS_vector[cube[zvv[n][i]]];\n                        //              }else\n                        if((CS_vector[cube[zvv[n][i]]]>cubeScalars[zvv[n][i]] && (CS_vector[cube[zvv[n][i]]]*cubeScalars[zvv[n][i]])<0) || CS_vector[cube[zvv[n][i]]]>(cubeScalars[zvv[n][i]] + 1e-3)){\n                            if (!flag) {\n                                queue.push_back(nkey);\n                                //time_queue.push_back(time_test);\n                                time_queue.push_back(running_argmin);\n                                correspondence_queue.push_back(nbr->second);\n                                flag = true;\n                            }\n                        }\n                        \n                        \n                        // WARNING: THIS BELOW IS WRONG, HAVE TO CHANGE\n                        //cubeScalars[zvv[n][i]] = std::min(CS_vector[cube[zvv[n][i]]],cubeScalars[zvv[n][i]]);\n                        //CS_vector[cube[zvv[n][i]]] = cubeScalars[zvv[n][i]];\n                    }\n                }\n                //} else if(correspondence==-1) {\n            }\n        }\n        \n        validCube = false;\n        sign = sgn(cubeScalars[0]);\n        for (int i = 1; i < 8; i++) {\n            if (sign != sgn(cubeScalars[i])) {\n                validCube = true;\n            }\n        }\n        \n        \n        for (int n = 0; n < 30; n++) { // For each neighbor, check the hash table to see if its been added before\n            Eigen::RowVector3i nkey = pi + neighbors[n];\n            auto nbr = visited.find(nkey);\n            flag = false;\n            if (nbr != visited.end()) { // We've already visited this neighbor, use references to its vertices instead of duplicating them\n                for (int i = 0; i < 4; i++) {\n                    if (zvv[n][i]!=-1) {\n                        cube[zvv[n][i]] = CI_vector[nbr->second][zvv[n % 2 == 0 ? n + 1 : n - 1][i]];\n                        // WARNING: THIS BELOW IS WRONG, HAVE TO CHANGE\n                        cubeScalars[zvv[n][i]] = std::min(CS_vector[cube[zvv[n][i]]],cubeScalars[zvv[n][i]]);\n                        CS_vector[cube[zvv[n][i]]] = cubeScalars[zvv[n][i]];\n                    }\n                }\n                //} else if(correspondence==-1) {\n            }else{\n                //                validCube = false;\n                //                sign = sgn(cubeScalars[0]);\n                //                for (int i = 1; i < 8; i++) {\n                //                    if (sign != sgn(cubeScalars[i])) {\n                //                        validCube = true;\n                //                    }\n                //                }\n                if (validCube) {\n                    //                    if (debug_flag) {\n                    //                        std::cout << \"BAD THING HAPPENED\" << std::endl;\n                    //                    }\n                    //                    queue.push_back(nkey);\n                    //                    // Otherwise, we have not visited the neighbor, put it in the BFS queue\n                    //                   // time_queue.push_back(time_test);\n                    //                    time_queue.push_back(running_argmin);\n                    //                    correspondence_queue.push_back(-1);\n                }\n                \n            }\n        }\n  // WARNING THIS SHOULDNT BE COMMENTED!!\n//        validCube = false;\n//        sign = sgn(cubeScalars[0]);\n//        for (int i = 1; i < 8; i++) {\n//            if (sign != sgn(cubeScalars[i])) {\n//                validCube = true;\n//            }\n//        }\n        for (int n = 0; n < 6; n++) { // For each neighbor, check the hash table to see if its been added before\n            Eigen::RowVector3i nkey = pi + neighbors[n];\n            auto nbr = visited.find(nkey);\n            flag = false;\n            if (nbr == visited.end()) {\n                if(validCube){\n                    queue.push_back(nkey);\n                    // Otherwise, we have not visited the neighbor, put it in the BFS queue\n                    // time_queue.push_back(time_test);\n                    time_queue.push_back(running_argmin);\n                    correspondence_queue.push_back(-1);\n                }\n            }\n        }\n        \n        \n        \n        \n        \n        auto did_we_visit_this_one = visited.find(pi);\n        if (correspondence==-1 && did_we_visit_this_one==visited.end()) {\n            for (int i = 0; i < 8; i++) { // Add new, non-visited,2 vertices to the arrays\n                //if (0 == ((1 << i) & vertexAlreadyAdded)) {\n                if (0 == ((1 << i) & vertexAlreadyAdded)) {\n//                    std::vector<double> interval;\n//                    std::vector<double> interval_values;\n//                    std::vector<double> interval_minima;\n//                    std::vector<double> interval_big;\n//                    std::vector<double> interval_values_big;\n//                    std::vector<double> interval_minima_big;\n//                    interval_minima.push_back(argmins[CI_vector.size()][i]);\n//                    interval.push_back(argmins[CI_vector.size()][i]);\n//                    interval.push_back(time_seed);\n//                    std::sort(interval.begin(), interval.end());\n//                    interval_values.push_back(cubeScalars[i]);\n                    \n                    \n                    CV_intervals.push_back(intervals[i]);\n                    CV_values.push_back(values[i]);\n                    CV_minima.push_back(minima[i]);\n                    cube[i] = CS_vector.size();\n                    CV_vector.push_back(cubeCorners[i]);\n                    CS_vector.push_back(cubeScalars[i]);\n                    CV_argmins.push_back(argmins[CI_vector.size()][i]);\n                }\n            }\n            \n            visited[pi] = CI_vector.size();\n            CI_vector.push_back(cube);\n        }\n        \n        //std::cout << queue.size() << std::endl;\n        \n        \n        bool debug = false;\n        if (debug) {\n            CV.resize(CV_vector.size(), 3);\n            CV_argmins_vector.resize(CV_vector.size(), 1);\n            CS.resize(CS_vector.size(), 1);\n            CI.resize(CI_vector.size(), 8);\n            Eigen::MatrixXi Q;\n            Q.resize(queue.size(),3);\n            for (int i = 0; i < queue.size(); i++) {\n                Q.row(i) = queue[i];\n            }\n            // If you pass in column-major matrices, this is going to be slooooowwwww\n            for (int i = 0; i < CV_vector.size(); i++) {\n                CV.row(i) = CV_vector[i];\n            }\n            for (int i = 0; i < CS_vector.size(); i++) {\n                CS(i) = CS_vector[i];\n            }\n            for (int i = 0; i < CI_vector.size(); i++) {\n                CI.row(i) = CI_vector[i];\n            }\n            igl::writeDMAT(\"/Volumes/Seagate Hard Drive/debug/CS\" + std::to_string(counter) + \".dmat\",CS);\n            igl::writeDMAT(\"/Volumes/Seagate Hard Drive/debug/CV\" + std::to_string(counter) + \".dmat\",CV);\n            igl::writeDMAT(\"/Volumes/Seagate Hard Drive/debug/CI\" + std::to_string(counter) + \".dmat\",CI);\n            igl::writeDMAT(\"/Volumes/Seagate Hard Drive/debug/Q\" + std::to_string(counter) + \".dmat\",Q);\n            counter = counter + 1;\n        }\n        \n        \n        \n        \n        \n    }\n    //std::cout << \"test\" << std::endl;\n    \n    CV.conservativeResize(CV_vector.size(), 3);\n    CV_argmins_vector.conservativeResize(CV_vector.size(), 2);\n    CS.conservativeResize(CS_vector.size(), 1);\n    CI.conservativeResize(CI_vector.size(), 8);\n//    // If you pass in column-major matrices, this is going to be slooooowwwww\n//    for (int j = 0; j < CV_vector.size(); j++) {\n//        std::cout << \"______________\" << std::endl;\n//        for (int mm = 0; mm < (CV_intervals[j].size()/2); mm++){\n//            std::cout << \"Existing interval: \" << CV_intervals[j][2*mm] << \" \" <<  CV_intervals[j][2*mm + 1] << \" value: \" << CV_values[j][mm] << std::endl;\n//        }\n//    }\n                    \n    for (int i = 0; i < CV_vector.size(); i++) {\n        CV.row(i) = CV_vector[i];\n    }\n    for (int i = 0; i < CS_vector.size(); i++) {\n        CS(i) = CS_vector[i];\n        //CS(i) = std::min_element(CV_values[i].begin(), CV_values[i].end());\n    }\n    for (int i = 0; i < CI_vector.size(); i++) {\n        CI.row(i) = CI_vector[i];\n    }\n    for (int i = 0; i < CV_vector.size(); i++) {\n        std::cout << \"1\" << std::endl;\n        double val = CV_values[i][0][0];\n        Eigen::RowVectorXd argmin;\n        argmin = CV_minima[i][0][0];\n        std::cout << \"2\" << std::endl;\n        for(int s = 0; s<CV_values[i].size(); s++){\n        for (int mm = 0; mm<CV_values[i][s].size(); mm++) {\n            if (CV_values[i][s][mm]<val) {\n                std::cout << \"3\" << std::endl;\n                val = CV_values[i][s][mm];\n                std::cout << \"4\" << std::endl;\n                argmin = CV_minima[i][s][mm];\n            }\n        }\n        }\n        std::cout << \"5\" << std::endl;\n        std::cout << argmin << std::endl;\n        CV_argmins_vector.row(i) = argmin;\n        std::cout << \"5b\" << std::endl;\n    }\n    std::cout << \"6\" << std::endl;\n}\n\n\n\n\n\n", "meta": {"hexsha": "92007876de0da6da3f7fce4d498f25a2790df350", "size": 54331, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "include/sparse_continuation.cpp", "max_stars_repo_name": "sgsellan/swept-volumes", "max_stars_repo_head_hexsha": "12d1ec636e1f64dfd9cd0c13639e15ab9de67284", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 17.0, "max_stars_repo_stars_event_min_datetime": "2021-06-19T16:37:30.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-08T23:56:15.000Z", "max_issues_repo_path": "include/sparse_continuation.cpp", "max_issues_repo_name": "sgsellan/swept-volumes", "max_issues_repo_head_hexsha": "12d1ec636e1f64dfd9cd0c13639e15ab9de67284", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/sparse_continuation.cpp", "max_forks_repo_name": "sgsellan/swept-volumes", "max_forks_repo_head_hexsha": "12d1ec636e1f64dfd9cd0c13639e15ab9de67284", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-06-19T15:27:10.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-30T13:01:28.000Z", "avg_line_length": 47.5336832896, "max_line_length": 527, "alphanum_fraction": 0.430914211, "num_tokens": 13851, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6926419704455589, "lm_q2_score": 0.4649015713733885, "lm_q1q2_score": 0.32201034045930044}}
{"text": "// Copyright 2010-2013 The Trustees of Indiana University.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are met: \n\n// 1. Redistributions of source code must retain the above copyright notice, this\n//    list of conditions and the following disclaimer. \n// 2. Redistributions in binary form must reproduce the above copyright notice,\n//    this list of conditions and the following disclaimer in the documentation\n//    and/or other materials provided with the distribution. \n\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR\n// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n//\n//  Authors: Jeremiah Willcock\n//           Andrew Lumsdaine\n\n#ifndef BOOST_SPLITTABLE_ECUYER1988_HPP\n#define BOOST_SPLITTABLE_ECUYER1988_HPP\n\n#include <boost/cstdint.hpp>\n#include <boost/iterator.hpp>\n#include <boost/random/uniform_01.hpp>\n#include <boost/iterator/iterator_facade.hpp>\n#include <utility>\n\nnamespace boost {\n  namespace random {\n\n    template <typename Base> // To get around incomplete class issues\n    class generic_split_iterator: public boost::iterator_facade<generic_split_iterator<Base>, Base, std::input_iterator_tag, Base> {\n      public:\n      Base base;\n      uint32_t new_multiplier1, new_multiplier2;\n\n      generic_split_iterator(Base base, uint32_t new_multiplier1, uint32_t new_multiplier2)\n\t: base(base), new_multiplier1(new_multiplier1), new_multiplier2(new_multiplier2) {}\n\n      generic_split_iterator(): base(), new_multiplier1(0), new_multiplier2(0) {}\n\n      Base dereference() const {\n\tBase result = base;\n\tresult.multiplier1 = new_multiplier1;\n\tresult.multiplier2 = new_multiplier2;\n\treturn result;\n      }\n\n      bool equal(const generic_split_iterator& it) const {\n\treturn base.state1 == it.base.state1 && base.state2 == it.base.state2;\n      }\n\n      void increment() {\n\tbase(); // Advance seeds\n      }\n    };\n\n    class splittable_ecuyer1988 {\n      uint32_t state1, state2, multiplier1, multiplier2;\n\n      static const uint64_t modulus1 = 2147483563;\n      static const uint64_t modulus2 = 2147483399;\n\n      template <uint64_t Modulus>\n      static uint32_t mul_mod(uint32_t a, uint32_t b) {\n\treturn uint32_t((uint64_t(a) * b) % Modulus);\n      }\n\n      template <uint64_t Modulus>\n      static uint32_t exp_mod(uint32_t a, uint32_t b) {\n\tif (b == 0) {\n\t  return 1;\n\t} else if (b == 1) {\n\t  return a;\n\t} else {\n\t  uint32_t temp = exp_mod<Modulus>(a, b>>1);\n\t  temp = mul_mod<Modulus>(temp, temp);\n\t  if (b % 2) temp = mul_mod<Modulus>(a, temp);\n\t  return temp;\n\t}\n      }\n\n      public:\n      splittable_ecuyer1988(): state1(1), state2(1), multiplier1(40014), multiplier2(40692) {}\n      splittable_ecuyer1988(uint32_t seed1, uint32_t seed2): state1(seed1), state2(seed2), multiplier1(40014), multiplier2(40692) {}\n\n      void seed(uint32_t seed1, uint32_t seed2) {\n\tstate1 = seed1;\n\tstate2 = seed2;\n      }\n\n      void split(splittable_ecuyer1988& a, splittable_ecuyer1988& b) const {\n\ta = *this;\n\ta.multiplier1 = mul_mod<modulus1>(a.multiplier1, a.multiplier1);\n\ta.multiplier2 = mul_mod<modulus2>(a.multiplier2, a.multiplier2);\n\tb = *this;\n\tb();\n\tb.multiplier1 = a.multiplier1;\n\tb.multiplier2 = a.multiplier2;\n      }\n\n      typedef generic_split_iterator<splittable_ecuyer1988> split_iterator;\n      typedef std::pair<split_iterator, split_iterator> split_iterator_pair;\n      friend class generic_split_iterator<splittable_ecuyer1988>;\n\n      split_iterator_pair split_n(uint32_t n) const { // This RNG is not usable after the split\n\tsplit_iterator begin(*this, exp_mod<modulus1>(multiplier1, n), exp_mod<modulus2>(multiplier2, n));\n\tsplit_iterator end(*this, begin.new_multiplier1, begin.new_multiplier2);\n\tend.base.state1 = mul_mod<modulus1>(end.base.state1, end.new_multiplier1);\n\tend.base.state2 = mul_mod<modulus2>(end.base.state2, end.new_multiplier2);\n\treturn std::make_pair(begin, end);\n      }\n\n      split_iterator_pair split_off_n(uint32_t n) { // Allows this RNG to keep being used\n\tsplit_iterator_pair p = split_n(n + 1);\n\t*this = *p.first;\n\t++p.first;\n\treturn p;\n      }\n\n      typedef uint32_t result_type;\n\n      uint32_t operator()() {\n\tstate1 = mul_mod<modulus1>(state1, multiplier1);\n\tstate2 = mul_mod<modulus2>(state2, multiplier2);\n\treturn (state1 + modulus1 - 1 - state2) % (modulus1 - 1);\n      }\n\n      BOOST_STATIC_CONSTANT(bool, has_fixed_range = true);\n      BOOST_STATIC_CONSTANT(uint32_t, min_value = 0);\n      BOOST_STATIC_CONSTANT(uint32_t, max_value = modulus1 - 1);\n      uint32_t min BOOST_PREVENT_MACRO_SUBSTITUTION () const {return min_value;}\n      uint32_t max BOOST_PREVENT_MACRO_SUBSTITUTION () const {return max_value;}\n\n      static bool validation(uint32_t x) {\n\treturn x == 831582319;\n      }\n    };\n\n    template <typename Gen>\n    class uniform_01_wrapper {\n      Gen& gen;\n\n      public:\n      uniform_01_wrapper(Gen& gen): gen(gen) {}\n\n      double operator()() const {return boost::uniform_01<double>()(gen);}\n\n      typedef double result_type;\n      BOOST_STATIC_CONSTANT(bool, has_fixed_range = true);\n      static const double min_value, max_value;\n      double min BOOST_PREVENT_MACRO_SUBSTITUTION () const {return min_value;}\n      double max BOOST_PREVENT_MACRO_SUBSTITUTION () const {return max_value;}\n    };\n\n    template <typename Gen>\n    const double uniform_01_wrapper<Gen>::min_value = 0.;\n    template <typename Gen>\n    const double uniform_01_wrapper<Gen>::max_value = 1.;\n  }\n}\n\n#endif // BOOST_SPLITTABLE_ECUYER1988_HPP\n", "meta": {"hexsha": "e301467b875e680ca113831fb3599b1db027107f", "size": 6203, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "runtime/tests/splittable_ecuyer1988.hpp", "max_stars_repo_name": "thejkane/AGM", "max_stars_repo_head_hexsha": "4d5cfe9522461d207ceaef7d90c1cd10ce9b469c", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-09-03T10:22:04.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-03T10:22:04.000Z", "max_issues_repo_path": "runtime/tests/splittable_ecuyer1988.hpp", "max_issues_repo_name": "thejkane/AGM", "max_issues_repo_head_hexsha": "4d5cfe9522461d207ceaef7d90c1cd10ce9b469c", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "runtime/tests/splittable_ecuyer1988.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": 36.2748538012, "max_line_length": 132, "alphanum_fraction": 0.7194905691, "num_tokens": 1585, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5888891451980404, "lm_q2_score": 0.5467381519846138, "lm_q1q2_score": 0.3219681629693755}}
{"text": "/**\n * particle_filter.cpp\n *\n * Created on: Dec 12, 2016\n * Author: Tiffany Huang\n */\n\n#include \"particle_filter.h\"\n\n#include <algorithm>\n#include <chrono>\n#include <array>\n#include <boost/format.hpp>\n#include <boost/log/trivial.hpp>\n#include <cmath>\n#include <ctime>\n#include <eigen3/Eigen/Geometry>\n#include <iostream>\n#include <iterator>\n#include <numeric>\n#include <random>\n#include <string>\n#include <vector>\n#ifdef _OPENMP\n#include <omp.h>\n#endif\n\n#include \"helper_functions.h\"\n\nusing Eigen::Isometry2d;\nusing Eigen::Matrix2Xd;\nusing Eigen::Vector2d;\nusing Eigen::VectorXd;\nusing std::cout;\nusing std::endl;\nusing std::string;\nusing std::vector;\n\nnamespace {\n\n/**\n * @brief      Trivial implementation of nearest neighborhood using euclidean\n * distances\n *\n * @param[in]  obs        The obs\n * @param      landmarks  The landmarks\n *\n * @return     the min distance indices in landmark set\n */\nint findNN(const Vector2d &obs, Matrix2Xd &predicted) {\n  int minIndex = -1;\n\n  if (predicted.cols() < 1) {\n    return minIndex;\n  }\n\n  VectorXd distances = (predicted.colwise() - obs).colwise().norm();\n  double minDist = distances.minCoeff(&minIndex);\n  if (not std::isinf(minDist)) {\n    predicted.col(minIndex) = Vector2d(std::numeric_limits<double>::infinity(),\n                                       std::numeric_limits<double>::infinity());\n    return minIndex;\n  } else {\n    return -1;\n  }\n}\n\ndouble Gaussian(const Vector2d &obs, const Vector2d &landmark,\n                const Vector2d &std) {\n  using std::exp;\n  double dx = obs[0] - landmark[0];\n  double dy = obs[1] - landmark[1];\n  double gaussianNormalizer = 1.0 / (2 * M_PI * std[0] * std[1]);\n  return gaussianNormalizer *\n         exp(-(dx * dx / (2 * std[0] * std[0]) + (dy * dy)) /\n             (2 * std[1] * std[1]));\n}\n\n}  // end of namespace\n\nstd::pair<Eigen::Matrix2Xd, std::vector<int>>\nParticle::computePredictedObservations(const Map &map, double sensorRange,\n                                       const Eigen::Vector2d &sensorStd) {\n  std::default_random_engine gen;\n  gen.seed(std::time(0));\n  std::normal_distribution<double> x_d{0.0, sensorStd[0]};\n  std::normal_distribution<double> y_d{0.0, sensorStd[1]};\n\n  vector<int> indices;\n  const Vector2d pos = {x, y};\n\n  std::vector<Vector2d, Eigen::aligned_allocator<Vector2d>> landmarks;\n  for (size_t i = 0; i < map.landmark_list.size(); ++i) {\n    Vector2d landmark = {map.landmark_list[i].x_f + x_d(gen),\n                         map.landmark_list[i].y_f + y_d(gen)};\n    if ((pos - landmark).norm() < sensorRange) {\n      indices.push_back(i);\n      landmarks.push_back(landmark);\n    }\n  }\n  return std::make_pair(Eigen::Map<const Matrix2Xd>(\n                            reinterpret_cast<const double *>(landmarks.data()),\n                            2, landmarks.size()),\n                        indices);\n}\n\nstd::vector<int> Particle::observationAssociation(\n    const Matrix2Xd &observationsInWorld,\n    const Matrix2Xd &predictedObservationsInWorld) {\n  associations.clear();\n\n  // Make a local copy\n  vector<int> matches;\n  Matrix2Xd predictedObservationsInWorld2 = predictedObservationsInWorld;\n  for (int i = 0; i < observationsInWorld.cols(); ++i) {\n    int nearestPredicted =\n        findNN(observationsInWorld.col(i), predictedObservationsInWorld2);\n    if (nearestPredicted != -1) {\n      matches.push_back(nearestPredicted);\n    }\n  }\n  return matches;\n}\n\nvoid Particle::updateWeight(const Eigen::Matrix2Xd &observationsInWorld,\n                            const Eigen::Matrix2Xd &predictedLandmarks,\n                            const std::vector<int> &matchedIndices,\n                            const Eigen::Vector2d &sensorStd) {\n  // BOOST_LOG_TRIVIAL(debug)\n  //     << (boost::format(\" --- Updating weight of particle %d --- \") % id).str();\n\n  // Reset weight\n  weight = 1.0;\n\n  for (size_t i = 0; i < matchedIndices.size(); ++i) {\n    Vector2d observation = observationsInWorld.col(i);\n    Vector2d predicted = predictedLandmarks.col(matchedIndices[i]);\n\n    const double likelihood = Gaussian(observation, predicted, sensorStd);\n\n    // BOOST_LOG_TRIVIAL(debug)\n    //     << (boost::format(\"observation=%s, landmark=%s, likelihood=%.3e\") %\n    //         observation.transpose() % predicted.transpose() % likelihood)\n    //            .str();\n    weight *= likelihood;\n  }\n\n  // BOOST_LOG_TRIVIAL(debug)\n  //     << (boost::format(\"Updating weight to %.3e\") % weight).str();\n}\n\nvoid ParticleFilter::init(double x, double y, double theta,\n                          const Eigen::Vector3d &std) {\n  /**\n   * TODO: Set the number of particles. Initialize all particles to\n   *   first position (based on estimates of x, y, theta and their uncertainties\n   *   from GPS) and all weights to 1.\n   * TODO: Add random Gaussian noise to each particle.\n   * NOTE: Consult particle_filter.h for more information about this method\n   *   (and others in this file).\n   */\n  BOOST_LOG_TRIVIAL(info) << \"Initializing particle filters.\";\n  std::default_random_engine gen;\n  gen.seed(std::time(0));\n\n  std::normal_distribution<double> x_d{x, std[0]};\n  std::normal_distribution<double> y_d{y, std[1]};\n  std::normal_distribution<double> s_d{theta, std[2]};\n\n  particles = vector<Particle>(num_particles);\n  weights = vector<double>(num_particles);\n  for (int i = 0; i < num_particles; ++i) {\n    Particle &p = particles[i];\n\n    p.id = i;\n    p.x = x_d(gen);\n    p.y = y_d(gen);\n    p.theta = s_d(gen);\n    p.weight = 1.0;\n\n    weights[i] = 1.0;\n  }\n\n  // Set to true after initialization\n  is_initialized = true;\n}\n\nvoid ParticleFilter::prediction(double delta_t, const Eigen::Vector3d &std_pose,\n                                double velocity, double yaw_rate) {\n  /**\n   * TODO: Add measurements to each particle and add random Gaussian noise.\n   * NOTE: When adding noise you may find std::normal_distribution\n   *   and std::default_random_engine useful.\n   *  http://en.cppreference.com/w/cpp/numeric/random/normal_distribution\n   *  http://www.cplusplus.com/reference/random/default_random_engine/\n   */\n  using std::abs;\n  using std::cos;\n  using std::sin;\n\n  // BOOST_LOG_TRIVIAL(info) << \"Run prediction.\";\n  std::default_random_engine gen;\n  gen.seed(std::time(0));\n\n  std::normal_distribution<double> x_d{0.0, std_pose[0]};\n  std::normal_distribution<double> y_d{0.0, std_pose[1]};\n  std::normal_distribution<double> s_d{0.0, std_pose[2]};\n\n  for (size_t i = 0; i < particles.size(); ++i) {\n    Particle &p = particles[i];\n    double delta_yaw = 0.0;\n    double delta_x = 0.0;\n    double delta_y = 0.0;\n    if (abs(yaw_rate) < 1e-10) {\n      delta_x = velocity * delta_t * cos(p.theta);\n      delta_y = velocity * delta_t * sin(p.theta);\n    } else {\n      delta_yaw = yaw_rate * delta_t;\n      delta_x = velocity / yaw_rate * (sin(p.theta + delta_yaw) - sin(p.theta));\n      delta_y = velocity / yaw_rate * (cos(p.theta) - cos(p.theta + delta_yaw));\n    }\n    p.x += delta_x + x_d(gen);\n    p.y += delta_y + y_d(gen);\n    p.theta += delta_yaw + s_d(gen);\n  }\n}\n\nEigen::Matrix2Xd Particle::computeObsvervationsInWorld(\n    const std::vector<LandmarkObs> &observations) {\n  // Construct eigen matrices for convenient computation\n  vector<double> obsBuffer(observations.size() * 2);\n  for (size_t i = 0, j = 0; i < observations.size(); ++i, j += 2) {\n    obsBuffer[j] = observations[i].x;\n    obsBuffer[j + 1] = observations[i].y;\n  }\n\n  Matrix2Xd obs =\n      Eigen::Map<Matrix2Xd>(obsBuffer.data(), 2, observations.size());\n  Isometry2d Tparticle = getIsometry2d(x, y, theta);\n  return (Tparticle * obs.colwise().homogeneous()).topRows<2>();\n}\n\nvoid ParticleFilter::updateWeights(double sensor_range,\n                                   const Eigen::Vector2d &std_landmark,\n                                   const vector<LandmarkObs> &observations,\n                                   const Map &map_landmarks) {\n  /**\n   * NOTE: The observations are given in the VEHICLE'S coordinate system.\n   *   Your particles are located according to the MAP'S coordinate system.\n   *   You will need to transform between the two systems. Keep in mind that\n   *   this transformation requires both rotation AND translation (but no\n   * scaling). The following is a good resource for the theory:\n   *   https://www.willamette.edu/~gorr/classes/GeneralGraphics/Transforms/transforms2d.htm\n   *   and the following is a good resource for the actual equation to implement\n   *   (look at equation 3.33) http://planning.cs.uiuc.edu/node99.html\n   */\n  // BOOST_LOG_TRIVIAL(debug) << \"Updating particle weights.\";\n  using Eigen::Isometry2d;\n  using Eigen::Vector2f;\n  using namespace std::chrono;\n\n  // Update sense_x, sense_y and associations.\n  auto start = high_resolution_clock::now();\n\n#ifdef _OPENMP\n  #pragma omp parallel for\n#endif\n  for (size_t i = 0; i < particles.size(); ++i) {\n    Particle &p = particles[i];\n\n    const Eigen::Matrix2Xd observationsInWorld =\n        p.computeObsvervationsInWorld(observations);\n\n    Matrix2Xd predictedObservations;\n    vector<int> predictedLandmarkIndices;\n    std::tie(predictedObservations, predictedLandmarkIndices) =\n        p.computePredictedObservations(map_landmarks, sensor_range,\n                                       std_landmark);\n\n    std::vector<int> matchedIndices =\n        p.observationAssociation(observationsInWorld, predictedObservations);\n\n    // Update associations\n    p.associations.clear();\n    p.sense_x.clear();\n    p.sense_y.clear();\n    for (int matchedIndex : matchedIndices) {\n      // +1 to output the landmark id\n      p.associations.push_back(predictedLandmarkIndices[matchedIndex] + 1);\n      p.sense_x.push_back(predictedObservations.col(matchedIndex).x());\n      p.sense_y.push_back(predictedObservations.col(matchedIndex).y());\n    }\n\n    p.updateWeight(observationsInWorld, predictedObservations, matchedIndices,\n                   std_landmark);\n\n    weights[i] = p.weight;\n  }\n\n  auto elapsedTime = duration_cast<milliseconds>(high_resolution_clock::now() - start).count();\n  BOOST_LOG_TRIVIAL(debug) << \"updateWeights took \" << elapsedTime << \" ms\";\n}\n\nvoid ParticleFilter::resample() {\n  using namespace std;\n  if (weights.empty()) {\n    return;\n  }\n\n  VectorXd weights_ =\n      Eigen::Map<VectorXd>(weights.data(), weights.size(), 1);\n  weights_ /= weights_.sum();\n\n  // BOOST_LOG_TRIVIAL(info) << \"Weights: \" << weights_.transpose();\n\n  // First index initialization\n  std::default_random_engine gen;\n  gen.seed(std::time(0));\n  std::uniform_real_distribution<> urd(0, 2.0 * weights_.maxCoeff());\n  std::uniform_int_distribution<> rid(0, num_particles - 1);\n\n  int sampledIndex = rid(gen);\n\n  // Resampling the particles\n  vector<Particle> newParticles(num_particles);\n  // Eigen::VectorXi samples(num_particles);\n  // samples[0] = sampledIndex;\n  newParticles[0] = particles[sampledIndex];\n\n  double beta = 0.0;\n\n  for (int i = 1; i < num_particles; ++i) {\n    beta += urd(gen);\n    while (weights_[sampledIndex] < beta) {\n      beta -= weights_[sampledIndex];\n      sampledIndex = (sampledIndex + 1) % num_particles;\n    }\n    // samples[i] = sampledIndex; // DEBUG\n    newParticles[i] = particles[sampledIndex];\n    newParticles[i].weight = weights_[sampledIndex];\n    newParticles[i].id = i;\n  }\n\n  particles = newParticles;\n  // BOOST_LOG_TRIVIAL(info) << \"samples: \" << samples.transpose();\n}\n\nvoid ParticleFilter::setAssociations(Particle &particle,\n                                     const vector<int> &associations,\n                                     const vector<double> &sense_x,\n                                     const vector<double> &sense_y) {\n  // particle: the particle to which assign each listed association,\n  //   and association's (x,y) world coordinates mapping\n  // associations: The landmark id that goes along with each listed association\n  // sense_x: the associations x mapping already converted to world coordinates\n  // sense_y: the associations y mapping already converted to world coordinates\n  particle.associations = associations;\n  particle.sense_x = sense_x;\n  particle.sense_y = sense_y;\n}\n\nstring ParticleFilter::getAssociations(Particle best) {\n  vector<int> v = best.associations;\n  std::stringstream ss;\n  copy(v.begin(), v.end(), std::ostream_iterator<int>(ss, \" \"));\n  string s = ss.str();\n  s = s.substr(0, s.length() - 1);  // get rid of the trailing space\n  return s;\n}\n\nstring ParticleFilter::getSenseCoord(Particle best, string coord) {\n  vector<double> v;\n\n  if (coord == \"X\") {\n    v = best.sense_x;\n  } else {\n    v = best.sense_y;\n  }\n\n  std::stringstream ss;\n  copy(v.begin(), v.end(), std::ostream_iterator<float>(ss, \" \"));\n  string s = ss.str();\n  s = s.substr(0, s.length() - 1);  // get rid of the trailing space\n  return s;\n}", "meta": {"hexsha": "ac85aaaa519c44dd6b029a3041ff364479a156fe", "size": 12716, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/particle_filter.cpp", "max_stars_repo_name": "kunlin596/CarND-Kidnapped-Vehicle-Project", "max_stars_repo_head_hexsha": "8eadfbe63b6d177d4b651520855023b754261278", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/particle_filter.cpp", "max_issues_repo_name": "kunlin596/CarND-Kidnapped-Vehicle-Project", "max_issues_repo_head_hexsha": "8eadfbe63b6d177d4b651520855023b754261278", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/particle_filter.cpp", "max_forks_repo_name": "kunlin596/CarND-Kidnapped-Vehicle-Project", "max_forks_repo_head_hexsha": "8eadfbe63b6d177d4b651520855023b754261278", "max_forks_repo_licenses": ["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.0285714286, "max_line_length": 95, "alphanum_fraction": 0.6505976722, "num_tokens": 3251, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5888891163376235, "lm_q2_score": 0.5467381519846138, "lm_q1q2_score": 0.32196814719028455}}
{"text": "//---------------------------------Spheral++----------------------------------//\n// VoronoiRedistributeNodes\n//\n// This algorithm uses the Voronoi tessellation to decide how to domain \n// decompose our points.  The idea is to relax a set of generator points into\n// the SPH node distribution -- the generators are attracted to the SPH points\n// repelled by one and other.  These generator points then become the seeds to\n// draw the Voronoi tessellation about, each cell of which then represents a \n// computational domain.\n//\n// Created by JMO, Fri Jan 15 09:56:56 PST 2010\n//----------------------------------------------------------------------------//\n#include \"VoronoiRedistributeNodes.hh\"\n#include \"Utilities/DomainNode.hh\"\n#include \"Boundary/Boundary.hh\"\n#include \"DataBase/DataBase.hh\"\n#include \"Field/FieldList.hh\"\n#include \"Field/Field.hh\"\n#include \"FieldOperations/binFieldList2Lattice.hh\"\n#include \"NodeList/NodeList.hh\"\n#include \"Kernel/TableKernel.hh\"\n#include \"Kernel/BSplineKernel.hh\"\n#include \"Utilities/globalNodeIDs.hh\"\n#include \"Utilities/RedistributionRegistrar.hh\"\n#include \"Utilities/safeInv.hh\"\n#include \"Utilities/boundPointWithinBox.hh\"\n#include \"Utilities/testBoxIntersection.hh\"\n#include \"Utilities/PairComparisons.hh\"\n#include \"Utilities/allReduce.hh\"\n#include \"Communicator.hh\"\n\n#include \"Utilities/DBC.hh\"\n\n#include <algorithm>\n#include <sstream>\n#include <fstream>\n#include <cstdlib>\n#include <bitset>\nusing std::vector;\nusing std::string;\nusing std::pair;\nusing std::make_pair;\nusing std::cout;\nusing std::cerr;\nusing std::endl;\nusing std::min;\nusing std::max;\nusing std::abs;\n\n#include <boost/assign.hpp>\n\nnamespace Spheral {\n\n\n//------------------------------------------------------------------------------\n// Helper method to find the nearest position in a vector of positions to the \n// given one.\n//------------------------------------------------------------------------------\ntemplate<typename Dimension>\nsize_t\nfindNearestGenerator(const typename Dimension::Vector& xi,\n                     const vector<typename Dimension::Vector>& generators,\n                     const vector<int>& generatorFlags) {\n\n  // This N^2 thing shouldn't be too bad until we get to lots of processors.\n  // Then we'll have to do something smarter.\n  size_t result = 0;\n  double minR2 = DBL_MAX;\n  for (size_t igen = 0; igen != generators.size(); ++igen) {\n    if (generatorFlags[igen] == 1) {\n      const double dr2 = (xi - generators[igen]).magnitude2();\n      // integrateThroughMeshAlongSegment<Dimension, double>(workBins, xmin, xmax, ncells, generators[igen], xi);\n      if (dr2 < minR2) {\n        minR2 = dr2;\n        result = igen;\n      }\n    }\n  }\n  ENSURE(result < generators.size() or (generators.size() == 0 and result == 0));\n  return result;\n}\n\n//------------------------------------------------------------------------------\n// Compute the center cell position.\n//------------------------------------------------------------------------------\ntemplate<typename Dimension>\ninline\ntypename Dimension::Vector\ncomputeCellPosition(const typename Dimension::Vector& xmin,\n\t\t    const typename Dimension::Vector& xmax,\n\t\t    const unsigned nxCells,\n\t\t    const unsigned index);\n\ntemplate<>\ninline\nDim<1>::Vector\ncomputeCellPosition<Dim<1> >(const Dim<1>::Vector& xmin,\n\t\t\t     const Dim<1>::Vector& xmax,\n\t\t\t     const unsigned nxCells,\n\t\t\t     const unsigned index) {\n  REQUIRE(index < nxCells);\n  return Dim<1>::Vector(xmin.x() + (xmax.x() - xmin.x())/nxCells * (index + 0.5));\n}\n\ntemplate<>\ninline\nDim<2>::Vector\ncomputeCellPosition<Dim<2> >(const Dim<2>::Vector& xmin,\n\t\t\t     const Dim<2>::Vector& xmax,\n\t\t\t     const unsigned nxCells,\n\t\t\t     const unsigned index) {\n  REQUIRE(index < nxCells*nxCells);\n  const unsigned ix = index % nxCells;\n  const unsigned iy = index / nxCells;\n  const Dim<2>::Vector xstep = (xmax - xmin)/nxCells;\n  return xmin + Dim<2>::Vector(xstep.x() * (ix + 0.5),\n                               xstep.y() * (iy + 0.5));\n}\n\ntemplate<>\ninline\nDim<3>::Vector\ncomputeCellPosition<Dim<3> >(const Dim<3>::Vector& xmin,\n\t\t\t     const Dim<3>::Vector& xmax,\n\t\t\t     const unsigned nxCells,\n\t\t\t     const unsigned index) {\n  REQUIRE(index < nxCells*nxCells*nxCells);\n  const unsigned iz = index / (nxCells*nxCells);\n  const unsigned iy = (index - iz*nxCells*nxCells) / nxCells;\n  const unsigned ix = index % nxCells;\n  const Dim<3>::Vector xstep = (xmax - xmin)/nxCells;\n  return xmin + Dim<3>::Vector(xstep.x() * (ix + 0.5),\n                               xstep.y() * (iy + 0.5),\n                               xstep.z() * (iz + 0.5));\n}\n\n//------------------------------------------------------------------------------\n// Compute the cell boundaries.\n//------------------------------------------------------------------------------\ntemplate<typename Dimension>\ninline\nvoid\ncomputeCellBoundaries(const typename Dimension::Vector& xmin,\n\t\t      const typename Dimension::Vector& xmax,\n\t\t      const size_t nxCells,\n\t\t      const size_t index,\n\t\t      typename Dimension::Vector& xcellMin,\n\t\t      typename Dimension::Vector& xcellMax);\n\ntemplate<>\ninline\nvoid\ncomputeCellBoundaries<Dim<1> >(const Dim<1>::Vector& xmin,\n\t\t\t       const Dim<1>::Vector& xmax,\n\t\t\t       const size_t nxCells,\n\t\t\t       const size_t index,\n\t\t\t       Dim<1>::Vector& xcellMin,\n\t\t\t       Dim<1>::Vector& xcellMax) {\n  REQUIRE(index < nxCells);\n  typedef Dim<1>::Vector Vector;\n  const Vector xstep = (xmax - xmin)/nxCells;\n  xcellMin = Vector(xstep.x()*index);\n  xcellMax = Vector(xstep.x()*(index + 1));\n}\n\ntemplate<>\ninline\nvoid\ncomputeCellBoundaries<Dim<2> >(const Dim<2>::Vector& xmin,\n\t\t\t       const Dim<2>::Vector& xmax,\n\t\t\t       const size_t nxCells,\n\t\t\t       const size_t index,\n\t\t\t       Dim<2>::Vector& xcellMin,\n\t\t\t       Dim<2>::Vector& xcellMax) {\n  REQUIRE(index < nxCells*nxCells);\n  typedef Dim<2>::Vector Vector;\n  const size_t ix = index % nxCells;\n  const size_t iy = index / nxCells;\n  const Vector xstep = (xmax - xmin)/nxCells;\n  xcellMin = Vector(xstep.x()*ix,\n\t\t    xstep.y()*iy);\n  xcellMin = Vector(xstep.x()*(ix + 1),\n\t\t    xstep.y()*(iy + 1));\n}\n\ntemplate<>\ninline\nvoid\ncomputeCellBoundaries<Dim<3> >(const Dim<3>::Vector& xmin,\n\t\t\t       const Dim<3>::Vector& xmax,\n\t\t\t       const size_t nxCells,\n\t\t\t       const size_t index,\n\t\t\t       Dim<3>::Vector& xcellMin,\n\t\t\t       Dim<3>::Vector& xcellMax) {\n  REQUIRE(index < nxCells*nxCells*nxCells);\n  typedef Dim<3>::Vector Vector;\n  const size_t iz = 2*(index / (nxCells*nxCells));\n  const size_t iy = 2*((index - iz/2) / nxCells);\n  const size_t ix = 2*(index % nxCells);\n  const Vector xstep = (xmax - xmin)/nxCells;\n  xcellMin = Vector(xstep.x() * ix,\n\t\t    xstep.y() * iy,\n\t\t    xstep.z() * iz);\n  xcellMax = Vector(xstep.x() * (ix + 1),\n\t\t    xstep.y() * (iy + 1),\n\t\t    xstep.z() * (iz + 1));\n}\n\n//------------------------------------------------------------------------------\n// Compute the subcell positions.\n//------------------------------------------------------------------------------\n// 1-D\ninline\nvector<Dim<1>::Vector>\ncomputeDaughterPositions(const Dim<1>::Vector& xmin,\n                         const Dim<1>::Vector& xmax) {\n  typedef Dim<1>::Vector Vector;\n  vector<Vector> result;\n  const Vector delta = xmax - xmin;\n  result.push_back(xmin + 0.25*delta);\n  result.push_back(xmin + 0.75*delta);\n  ENSURE(result.size() == 2);\n  return result;\n}\n\n// 2-D\ninline\nvector<Dim<2>::Vector>\ncomputeDaughterPositions(const Dim<2>::Vector& xmin,\n                         const Dim<2>::Vector& xmax) {\n  typedef Dim<2>::Vector Vector;\n  vector<Vector> result;\n  const Vector delta = xmax - xmin;\n  result.push_back(Vector(xmin.x() + 0.25*delta.x(), xmin.y() + 0.25*delta.y()));\n  result.push_back(Vector(xmin.x() + 0.75*delta.x(), xmin.y() + 0.25*delta.y()));\n  result.push_back(Vector(xmin.x() + 0.25*delta.x(), xmin.y() + 0.75*delta.y()));\n  result.push_back(Vector(xmin.x() + 0.75*delta.x(), xmin.y() + 0.75*delta.y()));\n  ENSURE(result.size() == 4);\n  return result;\n}\n\n// 3-D\ninline\nvector<Dim<3>::Vector>\ncomputeDaughterPositions(const Dim<3>::Vector& xmin,\n                         const Dim<3>::Vector& xmax) {\n  typedef Dim<3>::Vector Vector;\n  vector<Vector> result;\n  const Vector delta = xmax - xmin;\n  result.push_back(Vector(xmin.x() + 0.25*delta.x(), xmin.y() + 0.25*delta.y(), xmin.z() + 0.25*delta.z()));\n  result.push_back(Vector(xmin.x() + 0.75*delta.x(), xmin.y() + 0.25*delta.y(), xmin.z() + 0.25*delta.z()));\n  result.push_back(Vector(xmin.x() + 0.25*delta.x(), xmin.y() + 0.75*delta.y(), xmin.z() + 0.25*delta.z()));\n  result.push_back(Vector(xmin.x() + 0.75*delta.x(), xmin.y() + 0.75*delta.y(), xmin.z() + 0.25*delta.z()));\n  result.push_back(Vector(xmin.x() + 0.25*delta.x(), xmin.y() + 0.25*delta.y(), xmin.z() + 0.75*delta.z()));\n  result.push_back(Vector(xmin.x() + 0.75*delta.x(), xmin.y() + 0.25*delta.y(), xmin.z() + 0.75*delta.z()));\n  result.push_back(Vector(xmin.x() + 0.25*delta.x(), xmin.y() + 0.75*delta.y(), xmin.z() + 0.75*delta.z()));\n  result.push_back(Vector(xmin.x() + 0.75*delta.x(), xmin.y() + 0.75*delta.y(), xmin.z() + 0.75*delta.z()));\n  ENSURE(result.size() == 8);\n  return result;\n}\n\n//------------------------------------------------------------------------------\n// Compute the node position closest to the cell center.\n//------------------------------------------------------------------------------\ntemplate<typename Dimension>\ninline\ntypename Dimension::Vector\ncomputeClosestNodePosition(const typename Dimension::Vector& targetPosition,\n                           const vector<DomainNode<Dimension> >& nodes,\n                           const int numProcs, \n                           MPI_Comm communicator) {\n  typedef typename Dimension::Vector Vector;\n\n  // First find the local node closest to the center.\n  Vector localResult;\n  double minr2 = DBL_MAX;\n  const size_t n = nodes.size();\n  for (typename vector<DomainNode<Dimension> >::const_iterator itr = nodes.begin();\n       itr != nodes.end();\n       ++itr) {\n    const double r2 = (itr->position - targetPosition).magnitude2();\n    if (r2 < minr2) {\n      localResult = itr->position;\n      minr2 = r2;\n    }\n  }\n  CHECK(minr2 < DBL_MAX);\n\n  // Find the global minimum.\n  Vector result;\n  minr2 = DBL_MAX;\n  for (int sendProc = 0; sendProc != numProcs; ++sendProc) {\n    vector<char> buffer;\n    packElement(localResult, buffer);\n    MPI_Bcast(&buffer.front(), buffer.size(), MPI_CHAR, sendProc, communicator);\n    vector<char>::const_iterator itr = buffer.begin();\n    Vector xi;\n    unpackElement(xi, itr, buffer.end());\n    CHECK(itr == buffer.end());\n    const double r2 = (xi - targetPosition).magnitude2();\n    if (r2 < minr2) {\n      result = xi;\n      minr2 = r2;\n    }\n  }\n  CHECK(minr2 < DBL_MAX);\n\n  // That's it.\n  return result;\n}\n\n//------------------------------------------------------------------------------\n// Constructor.\n//------------------------------------------------------------------------------\ntemplate<typename Dimension>\nVoronoiRedistributeNodes<Dimension>::\nVoronoiRedistributeNodes(double dummy,\n                         const bool workBalance,\n                         const bool balanceGenerators,\n                         const double tolerance,\n                         const unsigned maxIterations):\n  RedistributeNodes<Dimension>(),\n  mWorkBalance(workBalance),\n  mBalanceGenerators(balanceGenerators),\n  mTolerance(tolerance),\n  mMaxIterations(maxIterations) {\n}\n\n//------------------------------------------------------------------------------\n// Destructor\n//------------------------------------------------------------------------------\ntemplate<typename Dimension>\nVoronoiRedistributeNodes<Dimension>::\n~VoronoiRedistributeNodes() {\n}\n\n//------------------------------------------------------------------------------\n// The main method of this class.  Call on the Voronoi library to describe an\n// optimal partioning of the nodes, and then apply that partitioning.\n//------------------------------------------------------------------------------\ntemplate<typename Dimension>\nvoid\nVoronoiRedistributeNodes<Dimension>::\nredistributeNodes(DataBase<Dimension>& dataBase,\n                  vector<Boundary<Dimension>*> boundaries) {\n\n  // The usual parallel info.\n  const int numProcs = this->numDomains();\n  const int procID = this->domainID();\n\n  // Get the global IDs.\n  const FieldList<Dimension, int> globalIDs = globalNodeIDs(dataBase);\n  const size_t numNodeLists = dataBase.numNodeLists();\n\n  // Compute the work and number density per node.\n  const TableKernel<Dimension> W(BSplineKernel<Dimension>(), 100);\n  FieldList<Dimension, Scalar> workField = dataBase.newGlobalFieldList(1.0, \"work\");\n  if (this->workBalance()) { // or mBalanceGenerators) {\n\n    // Enforce boundary conditions for the work computation.\n    for (typename DataBase<Dimension>::NodeListIterator nodeListItr = dataBase.nodeListBegin();\n         nodeListItr != dataBase.nodeListEnd();\n         ++nodeListItr) {\n      (*nodeListItr)->numGhostNodes(0);\n      (*nodeListItr)->neighbor().updateNodes();\n    }\n    for (typename vector<Boundary<Dimension>*>::iterator boundaryItr = boundaries.begin(); \n         boundaryItr != boundaries.end();\n         ++boundaryItr) {\n      (*boundaryItr)->setAllGhostNodes(dataBase);\n      (*boundaryItr)->finalizeGhostBoundary();\n      for (typename DataBase<Dimension>::FluidNodeListIterator nodeListItr = dataBase.fluidNodeListBegin();\n           nodeListItr != dataBase.fluidNodeListEnd(); \n           ++nodeListItr) (*nodeListItr)->neighbor().updateNodes();\n    }\n\n    // Update the connectivity.\n    dataBase.updateConnectivityMap(false, false);\n\n    // Get the local description of the domain distribution, with the work per node filled in.\n    if (this->workBalance()) workField = this->workPerNode(dataBase, 1.0);\n  }\n\n  // Print the beginning statistics.\n  std::string stats0 = this->gatherDomainDistributionStatistics(workField);\n  if (procID == 0) cout << \"VoronoiRedistributeNodes: INITIAL node distribution statistics:\" << endl\n                        << stats0 << endl;\n\n  // Now we can get the node distribution description.\n  vector<DomainNode<Dimension> > nodeDistribution = this->currentDomainDecomposition(dataBase, globalIDs, workField);\n  const size_t numNodes = nodeDistribution.size();\n  const size_t numNodesGlobal = allReduce((uint64_t) numNodes, MPI_SUM, Communicator::communicator());\n  const size_t avgNumNodes = numNodesGlobal/numProcs;\n  CHECK(numNodes > 0);\n\n  // Clear out any ghost nodes.\n  // We won't bother to update the neighbor info at this point -- we don't need \n  // it for this algorithm, so we just update it when we're done.\n  for (typename DataBase<Dimension>::NodeListIterator nodeListItr = dataBase.nodeListBegin();\n       nodeListItr != dataBase.nodeListEnd();\n       ++nodeListItr) (*nodeListItr)->numGhostNodes(0);\n\n  // Get the bounding boxes for the node set.\n  Vector xmin, xmax;\n  dataBase.boundingBox(xmin, xmax);\n\n  // Define the the length scale we use to determine when the generator positions have converged.\n  const double tol = (xmax - xmin).minElement() * mTolerance;\n  if (procID == 0) cerr << \"VoronoiRedistributeNodes: Found bounding box of \" << xmin << \" \" << xmax << endl\n                        << \"                          yielding generator convergence tolerance of \" << tol << endl;\n\n  // Determine the average work per generator.\n  const Scalar totWork = workField.sumElements();\n  const Scalar avgWork = totWork/numProcs;\n  \n  // Try and distribute the seeds according to where the work is by an AMR like zooming\n  // in of the work distribution in bins.\n  vector<Vector> generators(numProcs, 0.5*(xmin + xmax));\n  vector<pair<Vector, Vector> > generatorBounds(numProcs, make_pair(xmin, xmax));\n  const size_t numDaughters = (1U << Dimension::nDim);\n  vector<unsigned> ncells(Dimension::nDim, 2U);\n  {\n    // Everyone starts out in the same bin.\n    vector<vector<size_t> > generatorsInParents(1);\n    vector<pair<Vector, Vector> > parentCells;\n    for (size_t igen = 0; igen != numProcs; ++igen) generatorsInParents[0].push_back(igen);\n    parentCells.push_back(make_pair(xmin, xmax));\n\n    // Descend until we either get each generator in an individual cell or hit the maximum number\n    // of allowed levels\n    size_t level = 0;\n    size_t numRemainingGenerators = numProcs;\n    while (generatorsInParents.size() > 0 and level < mMaxIterations) {\n      CHECK(generatorsInParents.size() == parentCells.size());\n      ++level;\n      numRemainingGenerators = 0;\n      vector<vector<size_t> > newGeneratorsInParents;\n      vector<pair<Vector, Vector> > newParentCells;\n\n      // Walk each parent cell.\n      for (size_t k = 0; k != generatorsInParents.size(); ++k) {\n        const vector<size_t>& gens = generatorsInParents[k];\n        const size_t numParentGenerators = gens.size();\n        const Vector& xminParent = parentCells[k].first;\n        const Vector& xmaxParent = parentCells[k].second;\n\n        // Break up the work in this parent cell into 2^ndim subcells.\n        const vector<double> workBins = binFieldList2Lattice(workField, xminParent, xmaxParent, ncells);\n        const double workParent = accumulate(workBins.begin(), workBins.end(), 0.0);\n        CHECK(workBins.size() == numDaughters);\n        CHECK(workParent > 0.0);\n        \n        // Sort the daughters by work.\n        vector<pair<double, size_t> > sortedDaughters;\n        for (size_t k = 0; k != numDaughters; ++k) sortedDaughters.push_back(make_pair(workBins[k], k));\n        sort(sortedDaughters.begin(), sortedDaughters.end(), ComparePairsByFirstElementInDecreasingOrder<pair<double, size_t> >());\n\n        // Figure out how many generators we're assigning to each daughter.\n        vector<size_t> numGensForDaughter(numDaughters, 0);\n        {\n          size_t numAssigned = 0;\n          size_t k = 0;\n          while (numAssigned < numParentGenerators and k < numDaughters and sortedDaughters[k].first > 0.0) {\n            const double work = sortedDaughters[k].first;\n            const size_t kdaughter = sortedDaughters[k].second;\n            numGensForDaughter[kdaughter] = min(numParentGenerators - numAssigned, size_t(work*safeInv(workParent, 1.0e-30)*numParentGenerators + 1));\n            numAssigned += numGensForDaughter[kdaughter];\n            ++k;\n          }\n\n          // Pick up any stragglers.\n          VERIFY(numAssigned == numParentGenerators);\n          if (numAssigned < numParentGenerators) {\n            k = 0;\n            while (numAssigned < numParentGenerators and k < numDaughters and sortedDaughters[k].first > 0.0) {\n              const size_t kdaughter = sortedDaughters[k].second;\n              ++numGensForDaughter[kdaughter];\n              ++numAssigned;\n              ++k;\n            }\n          }\n          VERIFY(numAssigned == numParentGenerators);\n        }\n\n//         // Iterate until we have assigned each of the parent generators to a daughter.\n//         vector<size_t> numGensForDaughter(numDaughters, 0);\n//         int numRemaining = numParentGenerators;\n//         int iteration = 0;\n//         while (iteration < mMaxIterations and numRemaining > 0) {\n//           ++iteration;\n//           int numStillRemaining = numRemaining;\n//           for (size_t kdaughter = 0; kdaughter != workBins.size(); ++kdaughter) {\n//             const size_t delta = min(size_t(numStillRemaining), size_t(workBins[kdaughter]*numRemaining*safeInv(workParent, 1.0e-30) + 0.5 + 0.5*double(iteration)/double(max(1U, mMaxIterations - 1))));\n//             numGensForDaughter[kdaughter] += delta;\n//             numStillRemaining -= delta;\n//             CHECK(numStillRemaining >= 0);\n//           }\n//           numRemaining = numStillRemaining;\n//         }\n//         VERIFY(numRemaining == 0);\n\n        // Find the positions of the daughter cells.\n        const vector<Vector> daughterPositions = computeDaughterPositions(xminParent, xmaxParent);\n        CHECK(daughterPositions.size() == numDaughters);\n\n        // Now assign the generator positions and the next generation of parents.\n        vector<size_t>::const_iterator genItr = gens.begin();\n        for (size_t kdaughter = 0; kdaughter != numDaughters; ++kdaughter) {\n          CHECK(genItr + numGensForDaughter[kdaughter] <= gens.end());\n          const Vector dcell = 0.25*(xmaxParent - xminParent);\n          const Vector xminDaughter = daughterPositions[kdaughter] - dcell;\n          const Vector xmaxDaughter = daughterPositions[kdaughter] + dcell;\n          if (numGensForDaughter[kdaughter] == 1) {\n            generators[*genItr] = computeClosestNodePosition<Dimension>(0.5*(xminDaughter + xmaxDaughter),\n                                                                        nodeDistribution, numProcs, Communicator::communicator());\n            generatorBounds[*genItr] = make_pair(xminDaughter, xmaxDaughter);\n            CHECK(testPointInBox(generators[*genItr], xminDaughter, xmaxDaughter));\n          } else if (numGensForDaughter[kdaughter] > 1) {\n            for (vector<size_t>::const_iterator itr = genItr; itr != genItr + numGensForDaughter[kdaughter]; ++itr) {\n              generators[*itr] = daughterPositions[kdaughter];\n              generatorBounds[*itr] = make_pair(xminDaughter, xmaxDaughter);\n            }\n            newGeneratorsInParents.push_back(vector<size_t>(genItr, genItr + numGensForDaughter[kdaughter]));\n            newParentCells.push_back(make_pair(xminDaughter, xmaxDaughter));\n            numRemainingGenerators += numGensForDaughter[kdaughter];\n          }\n          genItr += numGensForDaughter[kdaughter];\n        }\n        CHECK(genItr == gens.end());\n      }\n\n      // Assign the next generation.\n      CHECK(newGeneratorsInParents.size() == newParentCells.size());\n      generatorsInParents = newGeneratorsInParents;\n      parentCells = newParentCells;\n      if (procID == 0) cerr << \"   Generation \" << level << \" : \"\n                            << numRemainingGenerators << \" generators remaining in \" \n                            << generatorsInParents.size() << \" cells.\"\n                            << endl;\n    }\n    VERIFY(numRemainingGenerators == 0);\n\n//     // Are there still remaining degeneracies in the generator positions?\n//     if (numRemainingGenerators > 0) {\n//       if (procID == 0) cerr << \"  --> Breaking up \" << numRemainingGenerators \n//                             << \" degeneracies in intial generator positions.\"\n//                             << endl;\n//       for (vector<vector<size_t> >::const_iterator cellItr = generatorsInParents.begin();\n//            cellItr != generatorsInParents.end();\n//            ++cellItr) {\n//         for (vector<size_t>::const_iterator genItr = cellItr->begin();\n//              genItr != cellItr->end();\n//              ++genItr) {\n//           const size_t igen = *genItr;\n//           if (procID == igen) generators[igen] = nodeDistribution[numNodes/2].position;\n//           vector<char> buffer;\n//           packElement(generators[igen], buffer);\n//           MPI_Bcast(&buffer.front(), buffer.size(), MPI_CHAR, igen, Communicator::communicator());\n//           vector<char>::const_iterator itr = buffer.begin();\n//           unpackElement(generators[igen], itr, buffer.end());\n//           CHECK(itr == buffer.end());\n//         }\n//       }\n//     }\n\n  }\n\n  // Copy the initial generator distribution.\n  const vector<Vector> startingGenerators(generators);\n\n//   // Stage 1:  Lloyds algorithm iteration of the generator positions.\n//   // Choose the initial positions of the generators randomly, one per domain.\n//   vector<Vector> generators(numProcs);\n//   for (size_t igen = 0; igen != numProcs; ++igen) {\n//     if (procID == igen) generators[igen] = nodeDistribution[numNodes/2].position;\n//     vector<char> buffer;\n//     packElement(generators[igen], buffer);\n//     MPI_Bcast(&buffer.front(), buffer.size(), MPI_CHAR, igen, Communicator::communicator());\n//     Vector xgen;\n//     vector<char>::const_iterator itr = buffer.begin();\n//     unpackElement(xgen, itr, buffer.end());\n//     CHECK(itr == buffer.end());\n//     generators[igen] = xgen;\n//   }\n\n  // Set all nodes as unassigned.\n  for (size_t i = 0; i != nodeDistribution.size(); ++i) nodeDistribution[i].domainID = -1;\n\n  // Assign the Voronoi distribution based on the initial seeds.\n  vector<double> generatorWork(generators.size(), 0.0);\n  vector<int> generatorFlags(generators.size(), 1);\n  double minWork, maxWork;\n  unsigned minNodes, maxNodes;\n  assignNodesToGenerators(generators,\n                          generatorFlags,\n                          generatorWork,\n                          nodeDistribution,\n                          minWork,\n                          maxWork,\n                          minNodes,\n                          maxNodes);\n                          \n\n  // Now iterate the generators until we either converge or hit the max iterations.\n  size_t iteration = 0;\n  double maxDeltaGenerator = 10.0*tol;\n  double oldWorkRatio = maxWork*safeInv(minWork);\n  double workRatio = 10.0*oldWorkRatio;\n  while (iteration < mMaxIterations and\n         maxDeltaGenerator > tol and\n         abs(workRatio*safeInv(oldWorkRatio) - 1.0) > 0.001) {\n\n    // Remember the starting generators.\n    const vector<Vector> generators0(generators);\n\n    // Iterate until we either have the desired work distribution for this pass or\n    // all generators have been flagged.\n    generatorFlags = vector<int>(generators.size(), 1);\n    while (minWork/maxWork < 1.1 and accumulate(generatorFlags.begin(), generatorFlags.end(), 0) > 1) {\n\n      // Cull out nodes from generators that have too much work.\n      cullGeneratorNodesByWork(generators, generatorWork, avgWork, generatorFlags, nodeDistribution);\n\n      // Reassign the loose nodes.\n      assignNodesToGenerators(generators, generatorFlags, generatorWork, nodeDistribution,\n                              minWork, maxWork, minNodes, maxNodes);\n\n    }\n\n    // Determine the new generators.\n    computeCentroids(nodeDistribution, generators);\n\n    // Reestablish the proper Voronoi distribution based on this iterations\n    // generators.\n    generatorWork = vector<double>(generators.size(), 0.0);\n    generatorFlags = vector<int>(generators.size(), 1);\n    for (size_t i = 0; i != nodeDistribution.size(); ++i) nodeDistribution[i].domainID = -1;\n    assignNodesToGenerators(generators, generatorFlags, generatorWork, nodeDistribution, \n                            minWork, maxWork, minNodes, maxNodes);\n\n    // How much did the generators shift?\n    maxDeltaGenerator = 0.0;\n    for (size_t igen = 0; igen != generators.size(); ++igen) {\n      maxDeltaGenerator = max(maxDeltaGenerator, (generators[igen] - generators0[igen]).magnitude2());\n    }\n    maxDeltaGenerator = sqrt(maxDeltaGenerator);\n\n    // How much did the work distribution change?\n    oldWorkRatio = workRatio;\n    workRatio = maxWork*safeInv(minWork);\n\n    // Report this iterations statistics.\n    if (procID == 0) cerr << \"VoronoiRedistributeNodes: Lloyds iteration \" << iteration << endl\n                          << \"                          max change:  \" << maxDeltaGenerator << endl\n                          << \"                          work ratio change:  \" << workRatio << \" \" << oldWorkRatio << \" \" << abs(workRatio*safeInv(oldWorkRatio) - 1.0) << endl\n                          << \"                          [min, max, avg] work      [\" << minWork << \", \" << maxWork << \", \" << avgWork << \"]\" << endl\n                          << \"                          [min, max, avg] num nodes [\" << minNodes << \", \" << maxNodes << \", \" << avgNumNodes << \"]\" << endl;\n    if (minWork == 0.0) {\n      if (procID == 0) {\n        cerr << \"ERROR:  zero work associated with the following generators:\" << endl;\n        for (size_t k = 0; k != numProcs; ++k) {\n          if (generatorWork[k] == 0.0) {\n            cerr << \"    ----->  \" << generators[k] << endl;\n            generators[k] = startingGenerators[k];\n          }\n        }\n      }\n    }\n    //VERIFY(minWork > 0);\n    ++iteration;\n  }\n\n  // Redistribute nodes between domains.\n  CHECK(this->validDomainDecomposition(nodeDistribution, dataBase));\n  this->enforceDomainDecomposition(nodeDistribution, dataBase);\n\n  // Reinitialize neighbor info.\n  for (typename DataBase<Dimension>::NodeListIterator nodeListItr = dataBase.nodeListBegin();\n       nodeListItr != dataBase.nodeListEnd();\n       ++nodeListItr) {\n    (*nodeListItr)->neighbor().updateNodes();\n  }\n\n  // Notify everyone that the nodes have just been shuffled around.\n  RedistributionRegistrar::instance().broadcastRedistributionNotifications();\n\n  // Print the final statistics.\n  std::string stats1 = this->gatherDomainDistributionStatistics(workField);\n  if (Process::getRank() == 0) cout << \"VoronoiRedistributeNodes: FINAL node distribution statistics:\" << endl\n                                    << stats1 << endl;\n}\n\n//------------------------------------------------------------------------------\n// Split the given node distribution into ncells sets using a Voronoi Lloyds type\n// algorithm.  The result is returned by setting the domainID attribute of each\n// DomainNode to a value in the range [0, ncells[.\n//------------------------------------------------------------------------------\ntemplate<typename Dimension>\nvoid\nVoronoiRedistributeNodes<Dimension>::\ncomputeCentroids(const vector<DomainNode<Dimension> >& nodes,\n                 vector<typename Dimension::Vector>& generators) const {\n\n  const int numProcs = this->numDomains();\n  const int procID = this->domainID();\n  const size_t numGenerators = generators.size();\n  REQUIRE(numGenerators == numProcs);\n\n  // Initializations.\n  const vector<Vector> generators0(generators);\n  generators = vector<Vector>(numGenerators, Vector::zero);\n\n  // Iterate over the nodes, assigning each to it's nearest generator.\n  vector<double> normalization(numGenerators, 0.0);\n  for (typename vector<DomainNode<Dimension> >::const_iterator itr = nodes.begin();\n       itr != nodes.end();\n       ++itr) {\n    const DomainNode<Dimension>& node = *itr;\n    const size_t igen = node.domainID;\n    CHECK(igen < numGenerators);\n    const double thpt = node.work;\n    generators[igen] += thpt*node.position;\n    normalization[igen] += thpt;\n  }\n\n  // Reduce the generator info across processors.\n  vector<char> localBuffer;\n  for (size_t igen = 0; igen != numGenerators; ++igen) {\n    packElement(generators[igen], localBuffer);\n    packElement(normalization[igen], localBuffer);\n    generators[igen] = Vector::zero;\n    normalization[igen] = 0.0;\n  }\n  for (size_t sendProc = 0; sendProc != numProcs; ++sendProc) {\n    vector<char> buffer = localBuffer;\n    MPI_Bcast(&buffer.front(), buffer.size(), MPI_CHAR, sendProc, Communicator::communicator());\n    vector<char>::const_iterator itr = buffer.begin();\n    for (size_t igen = 0; igen != numGenerators; ++igen) {\n      Vector ri;\n      double normi;\n      unpackElement(ri, itr, buffer.end());\n      unpackElement(normi, itr, buffer.end());\n      generators[igen] += ri;\n      normalization[igen] += normi;\n    }\n    CHECK(itr == buffer.end());\n  }\n\n  // Normalize the new generator positions and compute our final statistics.\n  // We also force the generator to the position of the nearest node, ensuring\n  // that all generators are actually in the the node distribution and have \n  // at least some work.\n  for (size_t igen = 0; igen != numGenerators; ++igen) {\n    generators[igen] = 0.25*generators[igen]*safeInv(normalization[igen]) + 0.75*generators0[igen];\n    generators[igen] = computeClosestNodePosition<Dimension>(generators[igen], nodes, numProcs, Communicator::communicator());\n  }\n}\n\n//------------------------------------------------------------------------------\n// Split the given node distribution into ncells sets using a Voronoi algorithm.\n// The result is returned by setting the domainID attribute of each\n// DomainNode to a value in the range [0, ncells).\n//------------------------------------------------------------------------------\ntemplate<typename Dimension>\nvoid\nVoronoiRedistributeNodes<Dimension>::\nassignNodesToGenerators(const vector<typename Dimension::Vector>& generators,\n                        const vector<int>& generatorFlags,\n                        vector<double>& generatorWork,\n                        vector<DomainNode<Dimension> >& nodes,\n                        double& minWork,\n                        double& maxWork,\n                        unsigned& minNodes,\n                        unsigned& maxNodes) const {\n\n  const int numProcs = this->numDomains();\n  const int procID = this->domainID();\n\n  // Initializations.\n  minWork = DBL_MAX;\n  maxWork = -DBL_MAX;\n  minNodes = INT_MAX;\n  maxNodes = 0;\n  const size_t numGenerators = generators.size();\n  generatorWork = vector<double>(numGenerators, 0.0);\n  vector<unsigned> numNodesPerGenerator(numGenerators, 0);\n\n  // Iterate over the nodes, assigning unassigned nodes to the nearest available generator.\n  for (typename vector<DomainNode<Dimension> >::iterator itr = nodes.begin();\n       itr != nodes.end();\n       ++itr) {\n    DomainNode<Dimension>& node = *itr;\n    if (node.domainID == -1) {\n      const size_t igen = findNearestGenerator<Dimension>(node.position, generators, generatorFlags);\n      node.domainID = igen;\n    }\n    const size_t igen = node.domainID;\n    CHECK(igen < numGenerators);\n    generatorWork[igen] += node.work;\n    ++numNodesPerGenerator[igen];\n  }\n\n  // Reduce the generator info across processors.\n  vector<char> localBuffer;\n  for (size_t igen = 0; igen != numGenerators; ++igen) {\n    packElement(generatorWork[igen], localBuffer);\n    packElement(numNodesPerGenerator[igen], localBuffer);\n    generatorWork[igen] = 0.0;\n    numNodesPerGenerator[igen] = 0;\n  }\n  for (size_t sendProc = 0; sendProc != numProcs; ++sendProc) {\n    vector<char> buffer = localBuffer;\n    MPI_Bcast(&buffer.front(), buffer.size(), MPI_CHAR, sendProc, Communicator::communicator());\n    vector<char>::const_iterator itr = buffer.begin();\n    for (size_t igen = 0; igen != numGenerators; ++igen) {\n      double worki;\n      unsigned ni;\n      unpackElement(worki, itr, buffer.end());\n      unpackElement(ni, itr, buffer.end());\n      generatorWork[igen] += worki;\n      numNodesPerGenerator[igen] += ni;\n    }\n    CHECK(itr == buffer.end());\n  }\n\n  // Compute our final statistics.\n  for (size_t igen = 0; igen != numGenerators; ++igen) {\n    minWork = min(minWork, generatorWork[igen]);\n    maxWork = max(maxWork, generatorWork[igen]);\n    minNodes = min(minNodes, numNodesPerGenerator[igen]);\n    maxNodes = max(maxNodes, numNodesPerGenerator[igen]);\n  }\n}\n\n//------------------------------------------------------------------------------\n// Cull or unassign nodes from generators with too much work.\n//------------------------------------------------------------------------------\ntemplate<typename Dimension>\nvoid\nVoronoiRedistributeNodes<Dimension>::\ncullGeneratorNodesByWork(const vector<typename Dimension::Vector>& generators,\n                         const vector<double>& generatorWork,\n                         const double targetWork,\n                         vector<int>& generatorFlags,\n                         vector<DomainNode<Dimension> >& nodes) const {\n\n  const int numProcs = this->numDomains();\n  const int procID = this->domainID();\n\n  // Pre-conditions.\n  const size_t numGenerators = generators.size();\n  REQUIRE(targetWork > 0.0);\n  REQUIRE(generatorWork.size() == numGenerators);\n\n  // How many generators are we starting with?\n  const int numOpenGenerators = accumulate(generatorFlags.begin(), generatorFlags.end(), 0);\n\n  // Walk the generators.\n  for (size_t igen = 0; igen != numGenerators; ++igen) {\n\n    // Do we need to examine this generator?\n    if (generatorFlags[igen] == 1 and \n        generatorWork[igen] >= targetWork) {\n      generatorFlags[igen] = 0;\n\n      // Try to cull out nodes from this generator so we don't overshoot the target work.\n      // Find the nodes associated with this generator on this processor.\n      // Sort them in increasing distance from the generator.\n      typedef pair<size_t, double> PairType;\n      vector<PairType> distances;\n      for (size_t i = 0; i != nodes.size(); ++i) {\n        if (nodes[i].domainID == igen) distances.push_back(make_pair(i, (nodes[i].position - generators[igen]).magnitude2()));\n      }\n      sort(distances.begin(), distances.end(), ComparePairsBySecondElement<PairType>());\n\n      // Find the global range of distances from the generator.\n      double rmin = allReduce((distances.size() > 0 ? distances.front().second : DBL_MAX), MPI_MIN, Communicator::communicator());\n      double rmax = allReduce((distances.size() > 0 ? distances.back().second  : 0.0),     MPI_MAX, Communicator::communicator());\n\n      // Bisect for the appropriate radius to reject nodes.\n      const double worktol = max(1.0e-10, 0.01*targetWork);\n      const double rtol = 1.0e-10*max(1.0, rmax - rmin);\n      double rreject = rmax;\n      double currentWork = generatorWork[igen];\n      while ((abs(currentWork - targetWork) >  worktol) and ((rmax - rmin) > rtol)) {\n        rreject = 0.5*(rmin + rmax);\n        double localWork = 0.0;\n        vector<PairType>::const_iterator itr = distances.begin();\n        while (itr != distances.end() and itr->second < rreject) {\n          localWork += nodes[itr->first].work;\n          ++itr;\n        }\n        currentWork = allReduce(localWork, MPI_SUM, Communicator::communicator());\n        if (currentWork < targetWork) {\n          rmin = rreject;\n        } else {\n          rmax = rreject;\n        }\n      }\n\n      // Now go through and unassign any nodes from this generator that are outside the\n      // rejection threshold.\n      typename vector<PairType>::iterator lowerItr = lower_bound(distances.begin(), \n                                                                 distances.end(),\n                                                                 rreject,\n                                                                 ComparePairsBySecondElement<PairType>());\n      for (typename vector<PairType>::iterator itr = lowerItr;\n           itr != distances.end();\n           ++itr) nodes[itr->first].domainID = -1;\n    }\n  }\n\n  // Did we actually assign any generators this pass?  If not, we're stuck!\n  // Flag all generators as done.\n  if (accumulate(generatorFlags.begin(), generatorFlags.end(), 0) == numOpenGenerators) {\n    generatorFlags = vector<int>(numGenerators, 0);\n  }\n}\n\n//------------------------------------------------------------------------------\n// Find the Voronoi cells adjacent to the specified one.\n// If the given cell is one of the vertices, reject it.\n//------------------------------------------------------------------------------\ntemplate<typename Dimension>\nvector<size_t>\nVoronoiRedistributeNodes<Dimension>::\nfindNeighborGenerators(const size_t igen,\n                       const vector<Vector>& generators) const {\n\n  // Are there enough generators to construct a meaningful volume?\n  vector<size_t> result;\n  if (generators.size() < (Dimension::nDim + 1)) {\n    for (size_t i = 0; i != generators.size(); ++i) {\n      if (i != igen) result.push_back(i);\n    }\n    return result;\n  }\n\n  // Construct the convex hull of the inverse distance to the other generators.\n  vector<Vector> inverseDistance;\n  for (size_t jgen = 0; jgen != generators.size(); ++jgen) {\n    if (jgen != igen) {\n      const Vector delta = generators[jgen] - generators[igen];\n      const Scalar rmag2 = delta.magnitude2();\n      CHECK(rmag2 > 0.0);\n      inverseDistance.push_back(delta * safeInv(rmag2, 1.0e-4));\n    } else {\n      inverseDistance.push_back(Vector::zero);\n    }\n  }\n  typedef typename Dimension::ConvexHull ConvexHull;\n  ConvexHull invHull(inverseDistance);\n  const vector<Vector> hullVertices = invHull.vertices();\n\n  // Select the generators that correspond to the vertices of the inverse hull.\n  for (size_t jgen = 0; jgen != generators.size(); ++jgen) {\n    if (jgen != igen) {\n      for (typename vector<Vector>::const_iterator itr = hullVertices.begin();\n           itr != hullVertices.end();\n           ++itr) {\n        if (fuzzyEqual((inverseDistance[jgen] - *itr).magnitude2(), 0.0, 1.0e-10)) result.push_back(jgen);\n      }\n    }\n  }\n\n  return result;\n}\n\n//------------------------------------------------------------------------------\n// Flag for whether we should compute the work per node or strictly balance by\n// node count.\n//------------------------------------------------------------------------------\ntemplate<typename Dimension>\nbool\nVoronoiRedistributeNodes<Dimension>::\nworkBalance() const {\n  return mWorkBalance;\n}\n\ntemplate<typename Dimension>\nvoid\nVoronoiRedistributeNodes<Dimension>::\nworkBalance(bool val) {\n  mWorkBalance = val;\n}\n\n//------------------------------------------------------------------------------\n// Flag to determine if we try to work balance the generators as part of the \n// iteration.\n//------------------------------------------------------------------------------\ntemplate<typename Dimension>\nbool\nVoronoiRedistributeNodes<Dimension>::\nbalanceGenerators() const {\n  return mBalanceGenerators;\n}\n\ntemplate<typename Dimension>\nvoid\nVoronoiRedistributeNodes<Dimension>::\nbalanceGenerators(bool val) {\n  mBalanceGenerators = val;\n}\n\n//------------------------------------------------------------------------------\n// Tolerance used to determine convergence of the generators.\n//------------------------------------------------------------------------------\ntemplate<typename Dimension>\ndouble\nVoronoiRedistributeNodes<Dimension>::\ntolerance() const {\n  return mTolerance;\n}\n\ntemplate<typename Dimension>\nvoid\nVoronoiRedistributeNodes<Dimension>::\ntolerance(double val) {\n  mTolerance = val;\n}\n\n//------------------------------------------------------------------------------\n// Maximum allowed iterations to try and converge the generator positions.\n//------------------------------------------------------------------------------\ntemplate<typename Dimension>\nunsigned\nVoronoiRedistributeNodes<Dimension>::\nmaxIterations() const {\n  return mMaxIterations;\n}\n\ntemplate<typename Dimension>\nvoid\nVoronoiRedistributeNodes<Dimension>::\nmaxIterations(unsigned val) {\n  mMaxIterations = val;\n}\n\n}\n\n", "meta": {"hexsha": "cabea4b3e4600510ee872f7d3798487175cbf070", "size": 42283, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/Distributed/VoronoiRedistributeNodes.cc", "max_stars_repo_name": "markguozhiming/spheral", "max_stars_repo_head_hexsha": "bbb982102e61edb8a1d00cf780bfa571835e1b61", "max_stars_repo_licenses": ["BSD-Source-Code", "BSD-3-Clause-LBNL", "FSFAP"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-10-21T01:56:55.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-21T01:56:55.000Z", "max_issues_repo_path": "src/Distributed/VoronoiRedistributeNodes.cc", "max_issues_repo_name": "markguozhiming/spheral", "max_issues_repo_head_hexsha": "bbb982102e61edb8a1d00cf780bfa571835e1b61", "max_issues_repo_licenses": ["BSD-Source-Code", "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/Distributed/VoronoiRedistributeNodes.cc", "max_forks_repo_name": "markguozhiming/spheral", "max_forks_repo_head_hexsha": "bbb982102e61edb8a1d00cf780bfa571835e1b61", "max_forks_repo_licenses": ["BSD-Source-Code", "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": 40.6176753122, "max_line_length": 204, "alphanum_fraction": 0.6047347634, "num_tokens": 9891, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6150878696277512, "lm_q2_score": 0.523420348936324, "lm_q1q2_score": 0.32194950734705774}}
{"text": "//=======================================================================\n// Copyright 2002 Indiana University.\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//\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_DAG_SHORTEST_PATHS_HPP\n#define BOOST_GRAPH_DAG_SHORTEST_PATHS_HPP\n\n#include <boost/graph/topological_sort.hpp>\n#include <boost/graph/dijkstra_shortest_paths.hpp>\n\n// single-source shortest paths for a Directed Acyclic Graph (DAG)\n\nnamespace boost {\n\n  // Initalize distances and call depth first search\n  template <class VertexListGraph, class DijkstraVisitor, \n            class DistanceMap, class WeightMap, class ColorMap, \n            class PredecessorMap,\n            class Compare, class Combine, \n            class DistInf, class DistZero>\n  inline void\n  dag_shortest_paths\n    (const VertexListGraph& g,\n     typename graph_traits<VertexListGraph>::vertex_descriptor s, \n     DistanceMap distance, WeightMap weight, ColorMap color,\n     PredecessorMap pred,\n     DijkstraVisitor vis, Compare compare, Combine combine, \n     DistInf inf, DistZero zero)\n  {\n    typedef typename graph_traits<VertexListGraph>::vertex_descriptor Vertex;\n    std::vector<Vertex> rev_topo_order;\n    rev_topo_order.reserve(num_vertices(g));\n    topological_sort(g, std::back_inserter(rev_topo_order));\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(distance, *ui, inf);\n      put(pred, *ui, *ui);\n    }\n\n    put(distance, s, zero);\n    vis.discover_vertex(s, g);\n    typename std::vector<Vertex>::reverse_iterator i;\n    for (i = rev_topo_order.rbegin(); i != rev_topo_order.rend(); ++i) {\n      Vertex u = *i;\n      vis.examine_vertex(u, g);\n      typename graph_traits<VertexListGraph>::out_edge_iterator e, e_end;\n      for (tie(e, e_end) = out_edges(u, g); e != e_end; ++e) {\n        vis.discover_vertex(target(*e, g), g);\n        bool decreased = relax(*e, g, weight, pred, distance, \n                               combine, compare);\n        if (decreased)\n          vis.edge_relaxed(*e, g);\n        else\n          vis.edge_not_relaxed(*e, g);\n      }\n      vis.finish_vertex(u, g);      \n    }\n  }\n\n  namespace detail {\n\n    // Defaults are the same as Dijkstra's algorithm\n\n    // Handle Distance Compare, Combine, Inf and Zero defaults\n    template <class VertexListGraph, class DijkstraVisitor, \n      class DistanceMap, class WeightMap, class ColorMap, \n      class IndexMap, class Params>\n    inline void\n    dag_sp_dispatch2\n      (const VertexListGraph& g,\n       typename graph_traits<VertexListGraph>::vertex_descriptor s, \n       DistanceMap distance, WeightMap weight, ColorMap color, IndexMap id,\n       DijkstraVisitor vis, const Params& params)\n    {\n      typedef typename property_traits<DistanceMap>::value_type D;\n      dummy_property_map p_map;\n      dag_shortest_paths\n        (g, s, distance, weight, color, \n         choose_param(get_param(params, vertex_predecessor), p_map),\n         vis, \n         choose_param(get_param(params, distance_compare_t()), std::less<D>()),\n         choose_param(get_param(params, distance_combine_t()), closed_plus<D>()),\n         choose_param(get_param(params, distance_inf_t()), \n                      (std::numeric_limits<D>::max)()),\n         choose_param(get_param(params, distance_zero_t()), \n                      D()));\n    }\n\n    // Handle DistanceMap and ColorMap defaults\n    template <class VertexListGraph, class DijkstraVisitor, \n              class DistanceMap, class WeightMap, class ColorMap,\n              class IndexMap, class Params>\n    inline void\n    dag_sp_dispatch1\n      (const VertexListGraph& g,\n       typename graph_traits<VertexListGraph>::vertex_descriptor s, \n       DistanceMap distance, WeightMap weight, ColorMap color, IndexMap id,\n       DijkstraVisitor vis, const Params& params)\n    {\n      typedef typename property_traits<WeightMap>::value_type T;\n      typename std::vector<T>::size_type n;\n      n = is_default_param(distance) ? num_vertices(g) : 1;\n      std::vector<T> distance_map(n);\n      n = is_default_param(color) ? num_vertices(g) : 1;\n      std::vector<default_color_type> color_map(n);\n\n      dag_sp_dispatch2\n        (g, s, \n         choose_param(distance, \n                      make_iterator_property_map(distance_map.begin(), id,\n                                                 distance_map[0])),\n         weight, \n         choose_param(color,\n                      make_iterator_property_map(color_map.begin(), id, \n                                                 color_map[0])),\n         id, vis, params);\n    }\n    \n  } // namespace detail \n  \n  template <class VertexListGraph, class Param, class Tag, class Rest>\n  inline void\n  dag_shortest_paths\n    (const VertexListGraph& g,\n     typename graph_traits<VertexListGraph>::vertex_descriptor s,\n     const bgl_named_params<Param,Tag,Rest>& params)\n  {\n    // assert that the graph is directed...\n    null_visitor null_vis;\n    detail::dag_sp_dispatch1\n      (g, s, \n       get_param(params, vertex_distance),\n       choose_const_pmap(get_param(params, edge_weight), g, edge_weight),\n       get_param(params, vertex_color),\n       choose_const_pmap(get_param(params, vertex_index), g, vertex_index),\n       choose_param(get_param(params, graph_visitor),\n                    make_dijkstra_visitor(null_vis)),\n       params);\n  }\n  \n} // namespace boost\n\n#endif // BOOST_GRAPH_DAG_SHORTEST_PATHS_HPP\n", "meta": {"hexsha": "3e79fbf5b34ff5951a09548f1eb28bb3d1960b04", "size": 6425, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "CvGameCoreDLL/Boost-1.32.0/include/boost/graph/dag_shortest_paths.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/dag_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/dag_shortest_paths.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": 39.1768292683, "max_line_length": 81, "alphanum_fraction": 0.6557198444, "num_tokens": 1440, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.3219494999607148}}
{"text": "/*\r\n This program is free software; you can redistribute it and/or modify it under\r\n the terms of the European Union Public Licence - EUPL v.1.1 as published by\r\n the European Commission.\r\n\r\n This program is distributed in the hope that it will be useful, but WITHOUT\r\n ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\r\n FOR A PARTICULAR PURPOSE. See the European Union Public Licence - EUPL v.1.1\r\n for more details.\r\n\r\n You should have received a copy of the European Union Public Licence - EUPL v.1.1\r\n along with this program.\r\n\r\n Further information about the European Union Public Licence - EUPL v.1.1 can\r\n also be found on the world wide web at http://ec.europa.eu/idabc/eupl\r\n\r\n*/\r\n\r\n/*\r\n ------ Copyright (C) 2010 STA Steering Board (space.trajectory.analysis AT gmail.com) ----\r\n*/\r\n\r\n/*\r\n------------------ Author: Valentino Zuccarelli  -------------------------------------------------\r\n ------------------ E-mail: (Valentino.Zuccarelli@gmail.com) ----------------------------\r\n */\r\n\r\n#include <Eigen/Core>\r\n#include \"Optimization/GlobalOptimizers.h\"\r\n#include <QDebug>\r\nusing namespace Eigen;\r\n\r\nextern int numObj, numIterations, initMODE;\r\nvoid GlobalOptimizers::InitializeOptimizer()\r\n{\r\n        int i;\r\n\r\n        //Random numbers generator initialization:\r\n        // Next line patched by Guillermo to avoid complaints of MingW 4.4\r\n        //int seed=time(0);\t\t\t\t\t\t//set initial seed for random number generator based on current clock\r\n        int seed=0;\r\n        srand(seed);\t\t\t\t\t\t\t//initialize random numbers generator\r\n        //NOTE: seed can be ANY integer number\r\n\r\n\r\n        //Problem parameters definition:\r\n        NVAR=4;\t\t\t\t\t\t\t\t//define number of optimization variables\r\n        NOBJ=numObj;\t\t\t\t\t\t\t\t\t//define number of optimization objectives\r\n        qDebug()<<\"numObj\"<<NOBJ;\r\n        NCONS=1;\t\t\t\t\t\t\t\t//define number of optimization constraints\r\n        NsolPareto=150;\t\t\t\t\t\t\t//define number of archive solutions\r\n        //NOTE: the parameter NsolPareto is NOT used within PSO-1D (only one solution is found for mono-objective optimization),\r\n        //for NSGA-II it defines the population size (and the archive coincides with the population) and for DG-MOPSO it defines\r\n        //the archive size, while the swarm size is fixed to 100 (it can be changed within the code in file dgmopso.cpp).\r\n        MAXITER=numIterations;\t\t\t\t\t\t\t//define number of iterations to be performed by the algorithm\r\n        InitMode=initMODE;\t\t\t\t\t\t\t\t//define initial set of solutions initialization mode\r\n        // InitMode=0: standard random initialization, to use the first time an optimization is run;\r\n        // InitMode=1: initialize from previous iteration results: optimization variables for N ARCHIVE solutions must have previously\r\n        //\t\t\t\tbeen saved in gsl_matrix *OptimalSolutions (of dimensions NxNVAR: 1 solution for each of the N rows,\r\n        //\t\t\t\t1 variable for each of the NVAR variables) and optimization objectives and constraints must have\r\n        //\t\t\t\tpreviously been saved in gsl_matrix *ParetoFront (of dimensions Nx(NOBJ+NCONS): 1 solution for each of\r\n        //\t\t\t\tthe N rows, with the objectives and then the constraints on the columns).\r\n        //\t\tIn case of NSGA-II archive and population coincide, while for PSO-1D and DG-MOPSO it is also necessary to provide\r\n        //\t\tthe results in terms of previous swarm positions, velocities and personal bests --> also the matrixes *OldSwarm,\r\n        //\t\t*OldPbest,*OldVel (which have 100 rows for the 100 particles of the swarm and NVAR columns for each variable\r\n        //\t\tvalue) must be initialized by the user.\r\n        // InitMode=2: initialize from previous run results: only optimization variables of a the optimal solutions found in\r\n        //\t\t\t\ta previous run must have been saved in *OptimalSolutions (same structure as above).\r\n\r\n\r\n        //GSL vectors and matrixes memory allocation\r\n        LOWERBOUND=VectorXd(NVAR); //=gsl_vector_alloc(NVAR);\r\n        UPPERBOUND=VectorXd(NVAR); //=gsl_vector_alloc(NVAR);\r\n        OptimalSolutions=MatrixXd(NsolPareto,NVAR); //=gsl_matrix_alloc(NsolPareto,NVAR);\r\n        ParetoFront=MatrixXd(NsolPareto,NOBJ+NCONS); //=gsl_matrix_alloc(NsolPareto,NOBJ+NCONS);\r\n\r\n        //the 1st number in brackets should be the same of swarmsize in pso1D or DG-MOPSO\r\n        OldSwarm=MatrixXd(500,NVAR); //=gsl_matrix_alloc(100,NVAR);\t\t//This matrix must be allocated only if PSO-1D or DG-MOPSO are selected\r\n        OldPbest=MatrixXd(500,NVAR); //=gsl_matrix_alloc(100,NVAR);\t\t//This matrix must be allocated only if PSO-1D or DG-MOPSO are selected\r\n        OldVel=MatrixXd(500,NVAR); //=gsl_matrix_alloc(100,NVAR);\t\t\t//This matrix must be allocated only if PSO-1D or DG-MOPSO are selected\r\n        OldJpbest=MatrixXd(500,NVAR); //=gsl_matrix_alloc(100,NVAR);\t\t//This matrix must be allocated only if DG-MOPSO is selected\r\n        OldJswarm=MatrixXd(500,NVAR); //=gsl_matrix_alloc(100,NVAR);\t\t//This matrix must be allocated only if DG-MOPSO is selected\r\n\r\n        //Variables optimization boundaries definition:\r\n        for(i=0;i<NVAR;i++)\r\n                {\r\n                    LOWERBOUND(i)=0;\r\n                    UPPERBOUND(i)=1;\r\n                }\r\n        LOWERBOUND(0)=-0.001; UPPERBOUND(0)=0.001;//for deviation of Halo orbit\r\n\r\n        char *file1=\"OutputPareto.stam\";\t\t//File name for Pareto front objectives and constraints history writing\r\n        char *file2=\"OutputSolutions.stam\";\t\t//File name for Pareto front variables writing at the end of run\r\n        if ((fpParetoFront=fopen(file1,\"w\"))==NULL) { printf(\"\\nError: could not open file %s for writing.\\n\",file1); exit(1); }\r\n        if ((fpSolutions=fopen(file2,\"w\"))==NULL) { printf(\"\\nError: could not open file %s for writing.\\n\",file2); exit(1); }\r\n}\r\n\r\n\r\n\r\n\r\n", "meta": {"hexsha": "54f7cc41cf0934d514a9d1ba955e3e3972d5f4c6", "size": 5809, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "sta-src/Lagrangian/InizializeOptimizer.cpp", "max_stars_repo_name": "hoehnp/SpaceDesignTool", "max_stars_repo_head_hexsha": "9abd34048274b2ce9dbbb685124177b02d6a34ca", "max_stars_repo_licenses": ["IJG"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2018-09-05T12:41:59.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-01T05:34:23.000Z", "max_issues_repo_path": "sta-src/Lagrangian/InizializeOptimizer.cpp", "max_issues_repo_name": "hoehnp/SpaceDesignTool", "max_issues_repo_head_hexsha": "9abd34048274b2ce9dbbb685124177b02d6a34ca", "max_issues_repo_licenses": ["IJG"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2015-02-07T19:09:21.000Z", "max_issues_repo_issues_event_max_datetime": "2015-08-14T03:15:42.000Z", "max_forks_repo_path": "sta-src/Lagrangian/InizializeOptimizer.cpp", "max_forks_repo_name": "hoehnp/SpaceDesignTool", "max_forks_repo_head_hexsha": "9abd34048274b2ce9dbbb685124177b02d6a34ca", "max_forks_repo_licenses": ["IJG"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2015-03-25T15:50:31.000Z", "max_forks_repo_forks_event_max_datetime": "2017-12-06T12:16:47.000Z", "avg_line_length": 57.5148514851, "max_line_length": 141, "alphanum_fraction": 0.671372009, "num_tokens": 1396, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5926665999540698, "lm_q2_score": 0.5428632831725052, "lm_q1q2_score": 0.3217369362777521}}
{"text": "/*=============================================================================\nCopyright 2018 Pranam Lashkari <plashkari628@gmail.com>\n\nDistributed under the Boost Software License, Version 1.0. (See accompanying\nfile License.txt or copy at https://www.boost.org/LICENSE_1_0.txt)\n=============================================================================*/\n\n#ifndef BOOST_ASTRONOMY_IO_IMAGE_HPP\n#define BOOST_ASTRONOMY_IO_IMAGE_HPP\n\n\n#include <cstddef>\n#include <algorithm>\n#include <iterator>\n#include <cstdint>\n#include <string>\n#include <cmath>\n#include <numeric>\n#include <valarray>\n\n#include <boost/endian/conversion.hpp>\n#include <boost/cstdfloat.hpp>\n#include <boost/variant.hpp>\n\n#include <boost/astronomy/io/bitpix.hpp>\n\n\nnamespace boost { namespace astronomy { namespace io {\n\ntemplate <typename PixelType>\nstruct image_buffer\n{\nprotected:\n    std::valarray<PixelType> data_; //! stores the image\n    std::size_t width_; //! width of image\n    std::size_t height_; //! height of image\n    //std::fstream image_file; //! image file\n\n    /**\n     * @brief Only used for Type Punning ( Accessing bytes individually )\n    */\n    union pixel_data\n    {\n        PixelType pixel;\n        std::uint8_t byte[sizeof(PixelType)];\n        //char byte[sizeof(PixelType)];\n    };\n\npublic:\n    /**\n     * @brief       Constructs an standalone object of image_buffer\n    */\n    image_buffer() {}\n\n    /**\n     * @brief       Constructs an image_buffer object by allocating width*height space for buffer\n     * @param[in]   width Width of Image\n     * @param[in]   height  Height of Image\n    */\n    image_buffer(std::size_t width, std::size_t height) : width_(width), height_(height)\n    {\n        this->data_.resize(width*height);\n    }\n\n    /**\n     * @brief       virtual destructor allowing image_buffer to be a polymorphic base for derived classes\n    */\n    virtual ~image_buffer() {}\n\n    /**\n     * @brief   Gets the maximum value of all the pixels in the image\n     * @return  PixelType containing the maximum pixel value\n    */\n    PixelType max() const\n    {\n        return this->data_.max();\n    }\n\n    /**\n     * @brief   Gets the minimum value of all the pixels in the image\n     * @return  PixelType containing the minimum pixel value\n    */\n    PixelType min() const\n    {\n        return this->data_.min();\n    }\n\n\n    /**\n     * @brief   Gets the mean value of all the pixels in the image\n     * @return  mean value of pixels in the image\n    */\n    double mean() const\n    {\n        if (this->data_.size() == 0)\n        {\n            return 0;\n        }\n\n        return (std::accumulate(std::begin(this->data_),\n            std::end(this->data_), 0.0) / this->data_.size());\n    }\n\n    /**\n     * @brief   Gets the median of all the pixel values in the image\n     * @note    This method uses additional space of order O(n) where n is the number of total pixels\n     * @return  median of all the pixel values in the image\n    */\n    PixelType median() const\n    {\n        std::valarray<PixelType> sorted_array = this->data_;\n        std::nth_element(std::begin(sorted_array),\n            std::begin(sorted_array) + sorted_array.size() / 2, std::end(sorted_array));\n\n        return sorted_array[sorted_array.size() / 2];\n    }\n\n   /**\n     * @brief   Gets the standard deviation of all the pixel values in the image\n     * @note    This method uses additional space of order O(n) where n is the number of total pixels\n     * @return  standard deviation of all the pixel values in the image\n    */\n    double std_dev() const\n    {\n        if (this->data_.size() == 0)\n        {\n            return 0;\n        }\n\n        double avg = this->mean();\n\n        std::valarray<double> diff(this->data_.size());\n        for (size_t i = 0; i < diff.size(); i++)\n        {\n            diff[i] = this->data_[i] - avg;\n        }\n\n        diff *= diff;\n        return std::sqrt(diff.sum() / (diff.size() - 1));\n    }\n\n    /**\n     * @brief       Gets the pixel value at specified position\n     * @param[in]   x x position of pixel\n     * @param[in]   y y position of pixel\n    */\n    PixelType operator() (std::size_t x, std::size_t y)\n    {\n        return this->data_[(x*this->width_) + y];\n    }\n\n    /**\n     * @brief       Returns the size of image\n    */\n    std::size_t size() { return data_.size(); }\n};\n\n\n\n/**\n * @brief Visitor used for reading image from data buffer for image variants\n*/\nstruct read_image_visitor :public boost::static_visitor<> {\n\n    const std::string& data_buffer;\n\n    read_image_visitor(const std::string& data_buf) :data_buffer(data_buf) {}\n\n    template<typename Image_Type>\n    void operator()(Image_Type& type) { type.read_image(data_buffer); }\n};\n\n/**\n * @brief Visitor used for writing image data from the image variants onto a buffer\n*/\n\nstruct write_image_visitor : public boost::static_visitor<std::string> {\n\n    template<typename Image_Type>\n    std::string operator()(Image_Type& type) { return type.write_image(); }\n\n};\n\n/**\n * @brief   Stores image data associated with the perticular HDU\n * @tparam  args Specifies the number of bits that represents a data value in image.\n * @author  Pranam Lashkari, Gopi Krishna Menon\n * @see     image_buffer\n*/\ntemplate<bitpix bitpix_val,typename Converter>\nstruct image:public image_buffer<typename bitpix_type<bitpix_val>::underlying_type> {\n\npublic:\n    /**\n     * @brief Reads an image from the data buffer\n     * @param[in] data_buffer Data associated with image HDU or primary HDU\n    */\n    void read_image(const std::string& data_buffer) {\n\n        if (data_buffer.empty()) { return; }\n\n        auto element_size = get_element_size_from_bitpix(bitpix_val);\n        std::string::const_iterator raw_data_iter=data_buffer.begin();\n\n        this->data_.resize(data_buffer.size() / element_size);\n\n\n        for (auto& element : this->data_) {\n            std::string data(raw_data_iter, raw_data_iter + element_size);\n            element = Converter::template deserialize_to<typename std::remove_reference<decltype(element)>::type>(data,0);\n            raw_data_iter += element_size;\n        }\n    }\n\n    /**\n     * @brief Creates a temporary buffer and writes all image data to it\n    */\n    std::string write_image() {\n\n\n        if (this->data_.size() != 0) {\n\n            std::string temp_buffer;\n\n            for (auto& element : this->data_) {\n                temp_buffer += Converter::template serialize(element);\n            }\n            return temp_buffer;\n        }\n\n        return \"\";\n    }\n\n};\n}}} //namespace boost::astronomy::io\n\n#endif // !BOOST_ASTRONOMY_IO_IMAGE_HPP\n", "meta": {"hexsha": "02ee8d33ac36783b476c56fdd91e27e18d022de1", "size": 6571, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/astronomy/io/image.hpp", "max_stars_repo_name": "nitink25/astronomy", "max_stars_repo_head_hexsha": "0a1d137171b08d1014d4ff138b2a40a146f4f39b", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 75.0, "max_stars_repo_stars_event_min_datetime": "2019-05-14T13:53:02.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-03T20:37:18.000Z", "max_issues_repo_path": "include/boost/astronomy/io/image.hpp", "max_issues_repo_name": "Zyro9922/astronomy", "max_issues_repo_head_hexsha": "56be0f8dfb103520ffbec0b793a92a531cd4b714", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 96.0, "max_issues_repo_issues_event_min_datetime": "2019-05-28T17:46:00.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-09T07:59:17.000Z", "max_forks_repo_path": "include/boost/astronomy/io/image.hpp", "max_forks_repo_name": "Zyro9922/astronomy", "max_forks_repo_head_hexsha": "56be0f8dfb103520ffbec0b793a92a531cd4b714", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 29.0, "max_forks_repo_forks_event_min_datetime": "2019-05-13T21:09:50.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-04T06:24:39.000Z", "avg_line_length": 27.6092436975, "max_line_length": 122, "alphanum_fraction": 0.6128443159, "num_tokens": 1551, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.3217369362777521}}
{"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_LOCALEVALUATION_SIPDG_HH\n#define DUNE_GDT_LOCALEVALUATION_SIPDG_HH\n\n#include <tuple>\n\n#include <boost/numeric/conversion/cast.hpp>\n\n#include <dune/common/dynmatrix.hh>\n\n#include <dune/stuff/common/color.hh>\n#ifndef NDEBUG\n# ifndef DUNE_GDT_LOCALEVALUATION_SIPDG_DISABLE_WARNINGS\n#   include <dune/stuff/common/timedlogging.hh>\n# endif\n#endif\n#include <dune/stuff/common/type_utils.hh>\n#include <dune/stuff/functions/interfaces.hh>\n\n#include \"interface.hh\"\n\nnamespace Dune {\nnamespace GDT {\nnamespace LocalEvaluation {\n\n/**\n *  \\brief      Contains local evaluations for the symmetric interior penalty discontinuous Galerkin (SIPDG)\n *              discretization.\n *\n *              For the choice of penalization and the role of the user input see Epshteyn, Riviere (2007):\n *              \"Estimation of penalty parameters for symmetric interior penalty Galerkin methods\"\n */\nnamespace SIPDG {\n\n\n// forwards\ntemplate< class LocalizableFunctionImp >\nclass Inner;\n\ntemplate< class LocalizableFunctionImp >\nclass BoundaryLHS;\n\ntemplate< class LocalizableDiffusionFunctionImp, class LocalizableDirichletFunctionImp >\nclass BoundaryRHS;\n\n\nnamespace internal {\n\n\ntemplate< class LocalizableFunctionImp >\nclass InnerTraits\n{\n  static_assert(Stuff::is_localizable_function< LocalizableFunctionImp >::value,\n                \"LocalizableFunctionImp has to be a localizable function!\");\npublic:\n  typedef Inner< LocalizableFunctionImp >                     derived_type;\n  typedef LocalizableFunctionImp                              LocalizableFunctionType;\n  typedef typename LocalizableFunctionType::EntityType        EntityType;\n  typedef typename LocalizableFunctionType::DomainFieldType   DomainFieldType;\n  typedef typename LocalizableFunctionType::LocalfunctionType LocalfunctionType;\n  typedef std::tuple< std::shared_ptr< LocalfunctionType > >  LocalfunctionTupleType;\n  static const size_t                                         dimDomain = LocalizableFunctionType::dimDomain;\n}; // class InnerTraits\n\n\ntemplate< class LocalizableFunctionImp >\nclass BoundaryLHSTraits\n{\n  static_assert(Stuff::is_localizable_function< LocalizableFunctionImp >::value,\n                \"LocalizableFunctionImp has to be a localizable function!\");\npublic:\n  typedef LocalizableFunctionImp                              LocalizableFunctionType;\n  typedef BoundaryLHS< LocalizableFunctionImp >               derived_type;\n  typedef typename LocalizableFunctionType::EntityType        EntityType;\n  typedef typename LocalizableFunctionType::DomainFieldType   DomainFieldType;\n  typedef typename LocalizableFunctionType::LocalfunctionType LocalfunctionType;\n  typedef std::tuple< std::shared_ptr< LocalfunctionType > >  LocalfunctionTupleType;\n  static const size_t                                         dimDomain = LocalizableFunctionType::dimDomain;\n}; // class BoundaryLHSTraits\n\n\ntemplate< class LocalizableDiffusionFunctionImp, class LocalizableDirichletFunctionImp >\nclass BoundaryRHSTraits\n{\n  static_assert(Stuff::is_localizable_function< LocalizableDiffusionFunctionImp >::value,\n                \"LocalizableDiffusionFunctionImp has to be a localizable function!\");\n  static_assert(Stuff::is_localizable_function< LocalizableDirichletFunctionImp >::value,\n                \"LocalizableDirichletFunctionImp has to be a localizable function!\");\n  static_assert(std::is_same< typename LocalizableDiffusionFunctionImp::EntityType,\n                              typename LocalizableDirichletFunctionImp::EntityType >::value,\n                \"EntityTypes have to agree!\");\n  static_assert(std::is_same< typename LocalizableDiffusionFunctionImp::DomainFieldType,\n                              typename LocalizableDirichletFunctionImp::DomainFieldType >::value,\n                \"DomainFieldTypes have to agree!\");\n  static_assert(LocalizableDiffusionFunctionImp::dimDomain == LocalizableDirichletFunctionImp::dimDomain,\n                \"Dimensions have to agree\");\npublic:\n  typedef BoundaryRHS< LocalizableDiffusionFunctionImp, LocalizableDirichletFunctionImp >   derived_type;\n  typedef LocalizableDiffusionFunctionImp                              LocalizableDiffusionFunctionType;\n  typedef LocalizableDirichletFunctionImp                              LocalizableDirichletFunctionType;\n  typedef typename LocalizableDiffusionFunctionType::LocalfunctionType LocalDiffusionFunctionType;\n  typedef typename LocalizableDirichletFunctionType::LocalfunctionType LocalDirichletFunctionType;\n  typedef std::tuple< std::shared_ptr< LocalDiffusionFunctionType >,\n                      std::shared_ptr< LocalDirichletFunctionType > >  LocalfunctionTupleType;\n  typedef typename LocalizableDiffusionFunctionType::EntityType        EntityType;\n  typedef typename LocalizableDiffusionFunctionType::DomainFieldType   DomainFieldType;\n  static const size_t dimDomain = LocalizableDiffusionFunctionType::dimDomain;\n}; // class BoundaryRHSTraits\n\n\n/**\n * \\note see Epshteyn, Riviere, 2007\n */\nstatic inline double default_beta(const size_t dimDomain)\n{\n  return 1.0/(dimDomain - 1.0);\n}\n\n\n/**\n * \\note see Epshteyn, Riviere, 2007\n */\nstatic inline double inner_sigma(const size_t pol_order)\n{\n  double sigma = 1.0;\n  if (pol_order <= 1)\n    sigma *= 8.0;\n  else if (pol_order <= 2)\n    sigma *= 20.0;\n  else if (pol_order <= 3)\n    sigma *= 38.0;\n  else {\n#ifndef NDEBUG\n# ifndef DUNE_GDT_LOCALEVALUATION_SIPDG_DISABLE_WARNINGS\n    DSC::TimedLogger().get(\"gdt.localevaluation.sipdg.inner\").warn()\n        << \"a polynomial order of \" << pol_order << \" is untested!\\n\"\n        << \"  #define DUNE_GDT_LOCALEVALUATION_SIPDG_DISABLE_WARNINGS to statically disable this warning\\n\"\n        << \"  or dynamically disable warnings of the TimedLogger() instance!\" << std::endl;\n# endif\n#endif\n    sigma *= 50.0;\n  }\n  return sigma;\n} // ... inner_sigma(...)\n\n\n/**\n * \\note see Epshteyn, Riviere, 2007\n */\nstatic inline double boundary_sigma(const size_t pol_order)\n{\n  double sigma = 1.0;\n  if (pol_order <= 1)\n    sigma *= 14.0;\n  else if (pol_order <= 2)\n    sigma *= 38.0;\n  else if (pol_order <= 3)\n    sigma *= 74.0;\n  else {\n#ifndef NDEBUG\n# ifndef DUNE_GDT_LOCALEVALUATION_SIPDG_DISABLE_WARNINGS\n    DSC::TimedLogger().get(\"gdt.localevaluation.sipdg.inner\").warn()\n        << \"a polynomial order of \" << pol_order << \" is untested!\\n\"\n        << \"  #define DUNE_GDT_LOCALEVALUATION_SIPDG_DISABLE_WARNINGS to statically disable this warning\\n\"\n        << \"  or dynamically disable warnings of the TimedLogger() instance!\" << std::endl;\n# endif\n#endif\n    sigma *= 100.0;\n  }\n  return sigma;\n} // ... boundary_sigma(...)\n\n} // namespace internal\n\n\n/**\n * see Epshteyn, Riviere, 2007 for the meaning of beta\n */\ntemplate< class LocalizableFunctionImp >\nclass Inner\n  : public LocalEvaluation::Codim1Interface< internal::InnerTraits< LocalizableFunctionImp >, 4 >\n{\npublic:\n  typedef internal::InnerTraits< LocalizableFunctionImp > Traits;\n  typedef typename Traits::LocalizableFunctionType        LocalizableFunctionType;\n  typedef typename Traits::LocalfunctionTupleType         LocalfunctionTupleType;\n  typedef typename Traits::EntityType                     EntityType;\n  typedef typename Traits::DomainFieldType                DomainFieldType;\n  static const size_t                                     dimDomain = Traits::dimDomain;\n\n  Inner(const LocalizableFunctionType& inducingFunction, const double beta = internal::default_beta(dimDomain))\n    : inducingFunction_(inducingFunction)\n    , beta_(beta)\n  {}\n\n  /// \\name Required by LocalEvaluation::Codim1Interface< ..., 4 >\n  /// \\{\n\n  LocalfunctionTupleType localFunctions(const EntityType& entity) const\n  {\n    return std::make_tuple(inducingFunction_.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& localFunctionsEntity,\n               const LocalfunctionTupleType& localFunctionsNeighbor,\n               const Stuff::LocalfunctionSetInterface\n                   < EntityType, DomainFieldType, dimDomain, R, rT, rCT >& testBaseEntity,\n               const Stuff::LocalfunctionSetInterface\n                   < EntityType, DomainFieldType, dimDomain, R, rA, rCA >& ansatzBaseEntity,\n               const Stuff::LocalfunctionSetInterface\n                   < EntityType, DomainFieldType, dimDomain, R, rT, rCT >& testBaseNeighbor,\n               const Stuff::LocalfunctionSetInterface\n                   < EntityType, DomainFieldType, dimDomain, R, rA, rCA >& ansatzBaseNeighbor) const\n  {\n    const auto localFunctionEntity = std::get< 0 >(localFunctionsEntity);\n    const auto localFunctionNeighbor = std::get< 0 >(localFunctionsNeighbor);\n    return order(*localFunctionEntity, *localFunctionNeighbor,\n                 testBaseEntity, ansatzBaseEntity,\n                 testBaseNeighbor, ansatzBaseNeighbor);\n  }\n\n  /**\n   * \\brief extracts the local functions and calls the correct evaluate() method\n   */\n  template< class IntersectionType, class R, size_t rT, size_t rCT, size_t rA, size_t rCA >\n  void evaluate(const LocalfunctionTupleType& localFunctionsEntity,\n                const LocalfunctionTupleType& localFunctionsNeighbor,\n                const Stuff::LocalfunctionSetInterface\n                    < EntityType, DomainFieldType, dimDomain, R, rT, rCT >& testBaseEntity,\n                const Stuff::LocalfunctionSetInterface\n                    < EntityType, DomainFieldType, dimDomain, R, rA, rCA >& ansatzBaseEntity,\n                const Stuff::LocalfunctionSetInterface\n                    < EntityType, DomainFieldType, dimDomain, R, rT, rCT >& testBaseNeighbor,\n                const Stuff::LocalfunctionSetInterface\n                    < EntityType, DomainFieldType, dimDomain, R, rA, rCA >& ansatzBaseNeighbor,\n                const IntersectionType& intersection,\n                const Dune::FieldVector< DomainFieldType, dimDomain - 1 >& localPoint,\n                Dune::DynamicMatrix< R >& entityEntityRet,\n                Dune::DynamicMatrix< R >& neighborNeighborRet,\n                Dune::DynamicMatrix< R >& entityNeighborRet,\n                Dune::DynamicMatrix< R >& neighborEntityRet) const\n  {\n    const auto localFunctionEntity = std::get< 0 >(localFunctionsEntity);\n    const auto localFunctionNeighbor = std::get< 0 >(localFunctionsNeighbor);\n    evaluate(*localFunctionEntity, *localFunctionNeighbor,\n             testBaseEntity, ansatzBaseEntity,\n             testBaseNeighbor, ansatzBaseNeighbor,\n             intersection, localPoint,\n             entityEntityRet,\n             neighborNeighborRet,\n             entityNeighborRet,\n             neighborEntityRet);\n  }\n\n  /// \\}\n  /// \\name Actual implementation of order\n  /// \\{\n\n  template< class R, size_t rL, size_t rCL, size_t rT, size_t rCT, size_t rA, size_t rCA >\n  size_t order(const Stuff::LocalfunctionInterface\n                   < EntityType, DomainFieldType, dimDomain, R, rL, rCL >& localFunctionEntity,\n               const Stuff::LocalfunctionInterface\n                   < EntityType, DomainFieldType, dimDomain, R, rL, rCL >& localFunctionNeighbor,\n               const Stuff::LocalfunctionSetInterface\n                   < EntityType, DomainFieldType, dimDomain, R, rT, rCT >& testBaseEntity,\n               const Stuff::LocalfunctionSetInterface\n                   < EntityType, DomainFieldType, dimDomain, R, rA, rCA >& ansatzBaseEntity,\n               const Stuff::LocalfunctionSetInterface\n                   < EntityType, DomainFieldType, dimDomain, R, rT, rCT >& testBaseNeighbor,\n               const Stuff::LocalfunctionSetInterface\n                   < EntityType, DomainFieldType, dimDomain, R, rA, rCA >& ansatzBaseNeighbor) const\n  {\n    return std::max(localFunctionEntity.order(), localFunctionNeighbor.order())\n         + std::max(testBaseEntity.order(), testBaseNeighbor.order())\n         + std::max(ansatzBaseEntity.order(), ansatzBaseNeighbor.order());\n  }\n\n  /// \\}\n  /// \\name Actual implementation of evaluate\n  /// \\{\n\n  /**\n   *  \\brief  Computes the ipdg fluxes in a primal setting.\n   *  \\tparam IntersectionType Type of the codim 1 Intersection\n   *  \\tparam R         RangeFieldType\n   */\n  template< class IntersectionType, class R >\n  void evaluate(const Stuff::LocalfunctionInterface< EntityType, DomainFieldType, 2, R, 1, 1 >& localFunctionEntity,\n                const Stuff::LocalfunctionInterface< EntityType, DomainFieldType, 2, R, 1, 1 >& localFunctionNeighbor,\n                const Stuff::LocalfunctionSetInterface< EntityType, DomainFieldType, 2, R, 1, 1 >& testBaseEntity,\n                const Stuff::LocalfunctionSetInterface< EntityType, DomainFieldType, 2, R, 1, 1 >& ansatzBaseEntity,\n                const Stuff::LocalfunctionSetInterface< EntityType, DomainFieldType, 2, R, 1, 1 >& testBaseNeighbor,\n                const Stuff::LocalfunctionSetInterface< EntityType, DomainFieldType, 2, R, 1, 1 >& ansatzBaseNeighbor,\n                const IntersectionType& intersection,\n                const Dune::FieldVector< DomainFieldType, 1 >& localPoint,\n                Dune::DynamicMatrix< R >& entityEntityRet,\n                Dune::DynamicMatrix< R >& neighborNeighborRet,\n                Dune::DynamicMatrix< R >& entityNeighborRet,\n                Dune::DynamicMatrix< R >& neighborEntityRet) const\n  {\n    // clear ret\n    entityEntityRet *= 0.0;\n    neighborNeighborRet *= 0.0;\n    entityNeighborRet *= 0.0;\n    neighborEntityRet *= 0.0;\n    // convert local point (which is in intersection coordinates) to entity/neighbor coordinates\n    const auto localPointEn = intersection.geometryInInside().global(localPoint);\n    const auto localPointNe = intersection.geometryInOutside().global(localPoint);\n    const auto unitOuterNormal = intersection.unitOuterNormal(localPoint);\n    // evaluate local function\n    const auto functionValueEn = localFunctionEntity.evaluate(localPointEn);\n    const auto functionValueNe = localFunctionNeighbor.evaluate(localPointNe);\n    // compute penalty (see Epshteyn, Riviere, 2007)\n    const auto max_polorder = std::max(testBaseEntity.order(),\n                                       std::max(ansatzBaseEntity.order(),\n                                                std::max(testBaseNeighbor.order(),\n                                                         ansatzBaseNeighbor.order())));\n    const R sigma = internal::inner_sigma(max_polorder);\n    const R penalty = sigma / std::pow(intersection.geometry().volume(), beta_);\n    // evaluate bases\n    // * entity\n    //   * test\n    const auto rowsEn = testBaseEntity.size();\n    const auto testValuesEn = testBaseEntity.evaluate(localPointEn);\n    const auto testGradientsEn = testBaseEntity.jacobian(localPointEn);\n    //   * ansatz\n    const auto colsEn = ansatzBaseEntity.size();\n    const auto ansatzValuesEn = ansatzBaseEntity.evaluate(localPointEn);\n    const auto ansatzGradientsEn = ansatzBaseEntity.jacobian(localPointEn);\n    // * neighbor\n    //   * test\n    const auto rowsNe = testBaseNeighbor.size();\n    const auto testValuesNe = testBaseNeighbor.evaluate(localPointNe);\n    const auto testGradientsNe = testBaseNeighbor.jacobian(localPointNe);\n    //   * ansatz\n    const auto colsNe = ansatzBaseNeighbor.size();\n    const auto ansatzValuesNe = ansatzBaseNeighbor.evaluate(localPointNe);\n    const auto ansatzGradientsNe = ansatzBaseNeighbor.jacobian(localPointNe);\n    // compute the evaluations\n    assert(entityEntityRet.rows() >= rowsEn);\n    assert(entityEntityRet.cols() >= colsEn);\n    assert(entityNeighborRet.rows() >= rowsEn);\n    assert(entityNeighborRet.cols() >= colsNe);\n    assert(neighborEntityRet.rows() >= rowsNe);\n    assert(neighborEntityRet.cols() >= colsEn);\n    assert(neighborNeighborRet.rows() >= rowsNe);\n    assert(neighborNeighborRet.cols() >= colsNe);\n    // loop over all entity test basis functions\n    for (size_t ii = 0; ii < rowsEn; ++ii) {\n      auto& entityEntityRetRow = entityEntityRet[ii];\n      auto& entityNeighborRetRow = entityNeighborRet[ii];\n      // loop over all entity ansatz basis functions\n      for (size_t jj = 0; jj < colsEn; ++jj) {\n        // consistency term\n        entityEntityRetRow[jj]\n            += -0.5 * functionValueEn * (ansatzGradientsEn[jj][0] * unitOuterNormal) * testValuesEn[ii];\n        // symmetry term\n        entityEntityRetRow[jj]\n            += -0.5 * ansatzValuesEn[jj] * functionValueEn * (testGradientsEn[ii][0] * unitOuterNormal);\n        // penalty term\n        entityEntityRetRow[jj] += penalty * ansatzValuesEn[jj] * testValuesEn[ii];\n      } // loop over all entity ansatz basis functions\n      // loop over all neighbor ansatz basis functions\n      for (size_t jj = 0; jj < colsNe; ++jj) {\n        // consistency term\n        entityNeighborRetRow[jj]\n            += -0.5 * functionValueNe * (ansatzGradientsNe[jj][0] * unitOuterNormal) * testValuesEn[ii];\n        // symmetry term\n        entityNeighborRetRow[jj]\n            += 0.5 * ansatzValuesNe[jj] * functionValueEn * (testGradientsEn[ii][0] * unitOuterNormal);\n        // penalty term\n        entityNeighborRetRow[jj] += -1.0 * penalty * ansatzValuesNe[jj] * testValuesEn[ii];\n      } // loop over all neighbor ansatz basis functions\n    } // loop over all entity test basis functions\n    // loop over all neighbor test basis functions\n    for (size_t ii = 0; ii < rowsNe; ++ii) {\n      auto& neighborEntityRetRow = neighborEntityRet[ii];\n      auto& neighborNeighborRetRow = neighborNeighborRet[ii];\n      // loop over all entity ansatz basis functions\n      for (size_t jj = 0; jj < colsEn; ++jj) {\n        // consistency term\n        neighborEntityRetRow[jj]\n            += 0.5 * functionValueEn * (ansatzGradientsEn[jj][0] * unitOuterNormal) * testValuesNe[ii];\n        // symmetry term\n        neighborEntityRetRow[jj]\n            += -0.5 * ansatzValuesEn[jj] * functionValueNe * (testGradientsNe[ii][0] * unitOuterNormal);\n        // penalty term\n        neighborEntityRetRow[jj] += -1.0 * penalty * ansatzValuesEn[jj] * testValuesNe[ii];\n      } // loop over all entity ansatz basis functions\n      // loop over all neighbor ansatz basis functions\n      for (size_t jj = 0; jj < colsNe; ++jj) {\n        // consistency term\n        neighborNeighborRetRow[jj]\n            += 0.5 * functionValueNe * (ansatzGradientsNe[jj][0] * unitOuterNormal) * testValuesNe[ii];\n        // symmetry term\n        neighborNeighborRetRow[jj]\n            += 0.5 * ansatzValuesNe[jj] * functionValueNe * (testGradientsNe[ii][0] * unitOuterNormal);\n        // penalty term\n        neighborNeighborRetRow[jj] += penalty * ansatzValuesNe[jj] * testValuesNe[ii];\n      } // loop over all neighbor ansatz basis functions\n    } // loop over all neighbor test basis functions\n  } // ... evaluate(...)\n\n  /// \\}\n\nprivate:\n  const LocalizableFunctionType& inducingFunction_;\n  const double beta_;\n}; // class Inner\n\n\n/**\n * see Epshteyn, Riviere, 2007 for the meaning of beta\n */\ntemplate< class LocalizableFunctionImp >\nclass BoundaryLHS\n    : public LocalEvaluation::Codim1Interface< internal::BoundaryLHSTraits< LocalizableFunctionImp >, 2 >\n{\npublic:\n  typedef internal::BoundaryLHSTraits< LocalizableFunctionImp > Traits;\n  typedef typename Traits::LocalizableFunctionType              LocalizableFunctionType;\n  typedef typename Traits::LocalfunctionTupleType               LocalfunctionTupleType;\n  typedef typename Traits::EntityType                           EntityType;\n  typedef typename Traits::DomainFieldType                      DomainFieldType;\n  static const size_t                                           dimDomain = Traits::dimDomain;\n\n  BoundaryLHS(const LocalizableFunctionType& inducingFunction, const double beta = internal::default_beta(dimDomain))\n    : inducingFunction_(inducingFunction)\n    , beta_(beta)\n  {}\n\n  /// \\name Required by LocalEvaluation::Codim1Interface< ..., 2>\n  /// \\{\n\n  LocalfunctionTupleType localFunctions(const EntityType& entity) const\n  {\n    return std::make_tuple(inducingFunction_.local_function(entity));\n  }\n\n  /**\n   * \\brief extracts the local functions and calls the correct order() method\n   */\n  template< class R, size_t rT, size_t rCT, size_t rA, size_t rCA >\n  size_t order(const LocalfunctionTupleType localFuncs,\n               const Stuff::LocalfunctionSetInterface< EntityType, DomainFieldType, dimDomain, R, rT, rCT >& testBase,\n               const Stuff::LocalfunctionSetInterface< EntityType, DomainFieldType, dimDomain, R, rA, rCA >& ansatzBase)\n  const\n  {\n    return order(*std::get< 0 >(localFuncs), testBase, ansatzBase);\n  }\n\n  /**\n   * \\brief extracts the local functions and calls the correct evaluate() method\n   */\n  template< class IntersectionType, class R, size_t rT, size_t rCT, size_t rA, size_t rCA >\n  void evaluate(const LocalfunctionTupleType localFuncs,\n                const Stuff::LocalfunctionSetInterface\n                    < EntityType, DomainFieldType, dimDomain, R, rT, rCT >& testBase,\n                const Stuff::LocalfunctionSetInterface\n                    < EntityType, DomainFieldType, dimDomain, R, rA, rCA >& ansatzBase,\n                const IntersectionType& intersection,\n                const Dune::FieldVector< DomainFieldType, dimDomain - 1 >& localPoint,\n                Dune::DynamicMatrix< R >& ret) const\n  {\n    evaluate(*std::get< 0 >(localFuncs), testBase, ansatzBase, intersection, localPoint, ret);\n  }\n\n  /// \\}\n  /// \\name Actual implementation of order\n  /// \\{\n\n  /**\n   * \\return localFunction.order() + testBase.order() + ansatzBase.order();\n   */\n  template< class R, size_t rL, size_t rCL, size_t rT, size_t rCT, size_t rA, size_t rCA >\n  size_t order(const Stuff::LocalfunctionInterface< EntityType, DomainFieldType, dimDomain, R, rL, rCL >& localFunction,\n               const Stuff::LocalfunctionSetInterface< EntityType, DomainFieldType, dimDomain, R, rT, rCT >& testBase,\n               const Stuff::LocalfunctionSetInterface< EntityType, DomainFieldType, dimDomain, R, rA, rCA >& ansatzBase)\n  const\n  {\n    return localFunction.order() + testBase.order() + ansatzBase.order();\n  }\n\n  /// \\}\n  /// \\name Actual implementation of evaluate\n  /// \\{\n\n  template< class IntersectionType, class R >\n  void evaluate(const Stuff::LocalfunctionInterface< EntityType, DomainFieldType, 2, R, 1, 1 >& localFunction,\n                const Stuff::LocalfunctionSetInterface< EntityType, DomainFieldType, 2, R, 1, 1 >& testBase,\n                const Stuff::LocalfunctionSetInterface< EntityType, DomainFieldType, 2, R, 1, 1 >& ansatzBase,\n                const IntersectionType& intersection,\n                const Dune::FieldVector< DomainFieldType, 1 >& localPoint,\n                Dune::DynamicMatrix< R >& ret) const\n  {\n    // clear ret\n    ret *= 0.0;\n    // get local point (which is in intersection coordinates) in entity coordinates\n    const auto localPointEntity = intersection.geometryInInside().global(localPoint);\n    const auto unitOuterNormal = intersection.unitOuterNormal(localPoint);\n    // evaluate local function\n    const auto functionValue = localFunction.evaluate(localPointEntity);\n    // compute penalty (see Epshteyn, Riviere, 2007)\n    const auto max_polorder = std::max(testBase.order(), ansatzBase.order());\n    const R sigma = internal::boundary_sigma(max_polorder);\n    const R penalty = sigma / std::pow(intersection.geometry().volume(), beta_);\n    // evaluate bases\n    // * test\n    const auto rows = testBase.size();\n    const auto testValues = testBase.evaluate(localPointEntity);\n    const auto testGradients = testBase.jacobian(localPointEntity);\n    // * ansatz\n    const auto cols = ansatzBase.size();\n    const auto ansatzValues = ansatzBase.evaluate(localPointEntity);\n    const auto ansatzGradients = ansatzBase.jacobian(localPointEntity);\n    // compute products\n    assert(ret.rows() >= rows);\n    assert(ret.cols() >= cols);\n    // loop over all test basis functions\n    for (size_t ii = 0; ii < rows; ++ii) {\n      auto& retRow = ret[ii];\n      // loop over all ansatz basis functions\n      for (size_t jj = 0; jj < cols; ++jj) {\n        // consistency term\n        retRow[jj] += -1.0 * functionValue * (ansatzGradients[jj][0] * unitOuterNormal) * testValues[ii];\n        // symmetry term\n        retRow[jj] += -1.0 * ansatzValues[jj] * functionValue * (testGradients[ii][0] * unitOuterNormal);\n        // penalty term\n        retRow[jj] += penalty * ansatzValues[jj] * testValues[ii];\n      } // loop over all ansatz basis functions\n    } // loop over all test basis functions\n  } // ... evaluate(...)\n\n  /// \\}\nprivate:\n  const LocalizableFunctionType& inducingFunction_;\n  const double beta_;\n}; // class BoundaryLHS\n\n\n/**\n * see Epshteyn, Riviere, 2007 for the meaning of beta\n */\ntemplate< class LocalizableDiffusionFunctionImp, class LocalizableDirichletFunctionImp >\nclass BoundaryRHS\n  : public LocalEvaluation::Codim1Interface< internal::BoundaryRHSTraits< LocalizableDiffusionFunctionImp,\n                                                                LocalizableDirichletFunctionImp >, 1 >\n{\npublic:\n  typedef internal::BoundaryRHSTraits< LocalizableDiffusionFunctionImp, LocalizableDirichletFunctionImp > Traits;\n  typedef typename Traits::LocalizableDiffusionFunctionType LocalizableDiffusionFunctionType;\n  typedef typename Traits::LocalizableDirichletFunctionType LocalizableDirichletFunctionType;\n  typedef typename Traits::LocalfunctionTupleType           LocalfunctionTupleType;\n  typedef typename Traits::EntityType                       EntityType;\n  typedef typename Traits::DomainFieldType                  DomainFieldType;\n  static const size_t                                       dimDomain = Traits::dimDomain;\n\n  BoundaryRHS(const LocalizableDiffusionFunctionType& diffusion,\n              const LocalizableDirichletFunctionType& dirichlet,\n              const double beta = internal::default_beta(dimDomain))\n    : diffusion_(diffusion)\n    , dirichlet_(dirichlet)\n    , beta_(beta)\n  {}\n\n  /// \\name Required by LocalEvaluation::Codim1Interface< ...., 1 >\n  /// \\{\n\n  LocalfunctionTupleType localFunctions(const EntityType& entity) const\n  {\n    return std::make_tuple(diffusion_.local_function(entity), dirichlet_.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 r, size_t rC >\n  size_t order(const LocalfunctionTupleType localFuncs,\n               const Stuff::LocalfunctionSetInterface< EntityType, DomainFieldType, dimDomain, R, r, rC >& testBase)\n  const\n  {\n    const auto localDiffusion = std::get< 0 >(localFuncs);\n    const auto localDirichlet = std::get< 1 >(localFuncs);\n    return order(*localDiffusion, *localDirichlet, testBase);\n  }\n\n  /**\n   * \\brief extracts the local functions and calls the correct evaluate() method\n   */\n  template< class IntersectionType, class R, size_t r, size_t rC >\n  void evaluate(const LocalfunctionTupleType localFuncs,\n                const Stuff::LocalfunctionSetInterface< EntityType, DomainFieldType, dimDomain, R, r, rC >& testBase,\n                const IntersectionType& intersection,\n                const Dune::FieldVector< DomainFieldType, dimDomain - 1 >& localPoint,\n                Dune::DynamicVector< R >& ret) const\n  {\n    const auto localDiffusion = std::get< 0 >(localFuncs);\n    const auto localDirichlet = std::get< 1 >(localFuncs);\n    evaluate(*localDiffusion, *localDirichlet, testBase, intersection, localPoint, ret);\n  }\n\n  /// \\}\n  /// \\name Actual implementation of order\n  /// \\{\n\n  /**\n   *  \\return std::max(testOrder + dirichletOrder, diffusionOrder + testGradientOrder + dirichletOrder);\n   */\n  template< class R, size_t rLF, size_t rCLF, size_t rLR, size_t rCLR, size_t rT, size_t rCT >\n  size_t order(const Stuff::LocalfunctionInterface\n                            < EntityType, DomainFieldType, dimDomain, R, rLF, rCLF >& localDiffusion,\n                        const Stuff::LocalfunctionInterface\n                            < EntityType, DomainFieldType, dimDomain, R, rLR, rCLR >& localDirichlet,\n                        const Stuff::LocalfunctionSetInterface\n                            < EntityType, DomainFieldType, dimDomain, R, rT, rCT >& testBase) const\n  {\n    const size_t testOrder = testBase.order();\n    const size_t testGradientOrder = boost::numeric_cast< size_t >(std::max(ssize_t(testOrder) - 1, ssize_t(0)));\n    const size_t diffusionOrder = localDiffusion.order();\n    const size_t dirichletOrder = localDirichlet.order();\n    return std::max(testOrder + dirichletOrder, diffusionOrder + testGradientOrder + dirichletOrder);\n  } // ... order(...)\n\n  /// \\}\n  /// \\name Actual implementation of evaluate\n  /// \\{\n\n  template< class IntersectionType, class R >\n  void evaluate(const Stuff::LocalfunctionInterface< EntityType, DomainFieldType, dimDomain, R, 1, 1 >& localDiffusion,\n                const Stuff::LocalfunctionInterface< EntityType, DomainFieldType, dimDomain, R, 1, 1 >& localDirichlet,\n                const Stuff::LocalfunctionSetInterface< EntityType, DomainFieldType, dimDomain, R, 1, 1 >& testBase,\n                const IntersectionType& intersection,\n                const Dune::FieldVector< DomainFieldType, dimDomain - 1 >& localPoint,\n                Dune::DynamicVector< R >& ret) const\n  {\n    // clear ret\n    ret *= 0.0;\n    // get local point (which is in intersection coordinates) in entity coordinates\n    const auto localPointEntity = intersection.geometryInInside().global(localPoint);\n    const auto unitOuterNormal = intersection.unitOuterNormal(localPoint);\n    // evaluate local functions\n    const auto diffusionValue = localDiffusion.evaluate(localPointEntity);\n    const auto dirichletValue = localDirichlet.evaluate(localPointEntity);\n    // compute penalty (see Epshteyn, Riviere, 2007)\n    const auto polorder = testBase.order();\n    const R sigma = internal::boundary_sigma(polorder);\n    const R penalty = sigma / std::pow(intersection.geometry().volume(), beta_);\n    // evaluate basis\n    const auto size = testBase.size();\n    const auto testValues = testBase.evaluate(localPointEntity);\n    const auto testGradients = testBase.jacobian(localPointEntity);\n    // compute\n    assert(ret.size() >= size);\n    // loop over all test basis functions\n    for (size_t ii = 0; ii < size; ++ii) {\n      // symmetry term\n      ret[ii] += -1.0 * dirichletValue * diffusionValue * (testGradients[ii][0] * unitOuterNormal);\n      // penalty term\n      ret[ii] += penalty * dirichletValue * testValues[ii];\n    } // loop over all test basis functions\n  } // ... evaluate(...)\n\n  /// \\{\n\nprivate:\n  const LocalizableDiffusionFunctionType& diffusion_;\n  const LocalizableDirichletFunctionType& dirichlet_;\n  const double beta_;\n}; // class BoundaryRHS\n\n\n} // namespace SIPDG\n} // namespace LocalEvaluation\n} // namespace GDT\n} // namespace Dune\n\n#endif // DUNE_GDT_LOCALEVALUATION_SIPDG_HH\n", "meta": {"hexsha": "29034a684dc0e0d68d203f0517a09636d6014578", "size": 31151, "ext": "hh", "lang": "C++", "max_stars_repo_path": "dune/gdt/localevaluation/sipdg.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/localevaluation/sipdg.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/localevaluation/sipdg.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.4096209913, "max_line_length": 120, "alphanum_fraction": 0.6823215948, "num_tokens": 7335, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6334102498375401, "lm_q2_score": 0.5078118642792044, "lm_q1q2_score": 0.3216532398235579}}
{"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// The Natural Earth projection was designed by Tom Patterson, US National Park\r\n// Service, in 2007, using Flex Projector. The shape of the original projection\r\n// was defined at every 5 degrees and piece-wise cubic spline interpolation was\r\n// used to compute the complete graticule.\r\n// The code here uses polynomial functions instead of cubic splines and\r\n// is therefore much simpler to program. The polynomial approximation was\r\n// developed by Bojan Savric, in collaboration with Tom Patterson and Bernhard\r\n// Jenny, Institute of Cartography, ETH Zurich. It slightly deviates from\r\n// Patterson's original projection by adding additional curvature to meridians\r\n// where they meet the horizontal pole line. This improvement is by intention\r\n// and designed in collaboration with Tom Patterson.\r\n// Port to PROJ.4 by Bernhard Jenny, 6 June 2011\r\n\r\n#ifndef BOOST_GEOMETRY_PROJECTIONS_NATEARTH_HPP\r\n#define BOOST_GEOMETRY_PROJECTIONS_NATEARTH_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 natearth {}; // Natural Earth\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 natearth\r\n    {\r\n\r\n            static const double A0 = 0.8707;\r\n            static const double A1 = -0.131979;\r\n            static const double A2 = -0.013791;\r\n            static const double A3 = 0.003971;\r\n            static const double A4 = -0.001529;\r\n            static const double B0 = 1.007226;\r\n            static const double B1 = 0.015085;\r\n            static const double B2 = -0.044475;\r\n            static const double B3 = 0.028874;\r\n            static const double B4 = -0.005916;\r\n            static const double C0 = B0;\r\n            static const double C1 = (3 * B1);\r\n            static const double C2 = (7 * B2);\r\n            static const double C3 = (9 * B3);\r\n            static const double C4 = (11 * B4);\r\n            static const double epsilon = 1e-11;\r\n\r\n            template <typename T>\r\n            inline T max_y() { return (0.8707 * 0.52 * detail::pi<T>()); }\r\n\r\n            /* Not sure at all of the appropriate number for max_iter... */\r\n            static const int max_iter = 100;\r\n\r\n            // template class, using CRTP to implement forward/inverse\r\n            template <typename T, typename Parameters>\r\n            struct base_natearth_spheroid\r\n                : public base_t_fi<base_natearth_spheroid<T, Parameters>, T, Parameters>\r\n            {\r\n                inline base_natearth_spheroid(const Parameters& par)\r\n                    : base_t_fi<base_natearth_spheroid<T, Parameters>, T, Parameters>(*this, par)\r\n                {}\r\n\r\n                // FORWARD(s_forward)  spheroid\r\n                // Project coordinates from geographic (lon, lat) to cartesian (x, y)\r\n                inline void fwd(T& lp_lon, T& lp_lat, T& xy_x, T& xy_y) const\r\n                {\r\n                    T phi2, phi4;\r\n\r\n                    phi2 = lp_lat * lp_lat;\r\n                    phi4 = phi2 * phi2;\r\n                    xy_x = lp_lon * (A0 + phi2 * (A1 + phi2 * (A2 + phi4 * phi2 * (A3 + phi2 * A4))));\r\n                    xy_y = lp_lat * (B0 + phi2 * (B1 + phi4 * (B2 + B3 * phi2 + B4 * phi4)));\r\n                }\r\n\r\n                // INVERSE(s_inverse)  spheroid\r\n                // Project coordinates from cartesian (x, y) to geographic (lon, lat)\r\n                inline void inv(T& xy_x, T& xy_y, T& lp_lon, T& lp_lat) const\r\n                {\r\n                    static const T max_y = natearth::max_y<T>();\r\n\r\n                    T yc, tol, y2, y4, f, fder;\r\n                    int i;\r\n\r\n                    /* make sure y is inside valid range */\r\n                    if (xy_y > max_y) {\r\n                        xy_y = max_y;\r\n                    } else if (xy_y < -max_y) {\r\n                        xy_y = -max_y;\r\n                    }\r\n\r\n                    /* latitude */\r\n                    yc = xy_y;\r\n                    for (i = max_iter; i ; --i) { /* Newton-Raphson */\r\n                        y2 = yc * yc;\r\n                        y4 = y2 * y2;\r\n                        f = (yc * (B0 + y2 * (B1 + y4 * (B2 + B3 * y2 + B4 * y4)))) - xy_y;\r\n                        fder = C0 + y2 * (C1 + y4 * (C2 + C3 * y2 + C4 * y4));\r\n                        yc -= tol = f / fder;\r\n                        if (fabs(tol) < epsilon) {\r\n                            break;\r\n                        }\r\n                    }\r\n                    if( i == 0 )\r\n                        BOOST_THROW_EXCEPTION( projection_exception(error_non_convergent) );\r\n                    lp_lat = yc;\r\n\r\n                    /* longitude */\r\n                    y2 = yc * yc;\r\n                    lp_lon = xy_x / (A0 + y2 * (A1 + y2 * (A2 + y2 * y2 * y2 * (A3 + y2 * A4))));\r\n                }\r\n\r\n                static inline std::string get_name()\r\n                {\r\n                    return \"natearth_spheroid\";\r\n                }\r\n\r\n            };\r\n\r\n            // Natural Earth\r\n            template <typename Parameters>\r\n            inline void setup_natearth(Parameters& par)\r\n            {\r\n                par.es = 0;\r\n            }\r\n\r\n    }} // namespace detail::natearth\r\n    #endif // doxygen\r\n\r\n    /*!\r\n        \\brief Natural Earth 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         - Spheroid\r\n        \\par Example\r\n        \\image html ex_natearth.gif\r\n    */\r\n    template <typename T, typename Parameters>\r\n    struct natearth_spheroid : public detail::natearth::base_natearth_spheroid<T, Parameters>\r\n    {\r\n        inline natearth_spheroid(const Parameters& par) : detail::natearth::base_natearth_spheroid<T, Parameters>(par)\r\n        {\r\n            detail::natearth::setup_natearth(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::natearth, natearth_spheroid, natearth_spheroid)\r\n\r\n        // Factory entry(s)\r\n        template <typename T, typename Parameters>\r\n        class natearth_entry : public detail::factory_entry<T, Parameters>\r\n        {\r\n            public :\r\n                virtual base_v<T, Parameters>* create_new(const Parameters& par) const\r\n                {\r\n                    return new base_v_fi<natearth_spheroid<T, Parameters>, T, Parameters>(par);\r\n                }\r\n        };\r\n\r\n        template <typename T, typename Parameters>\r\n        inline void natearth_init(detail::base_factory<T, Parameters>& factory)\r\n        {\r\n            factory.add_to_factory(\"natearth\", new natearth_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_NATEARTH_HPP\r\n\r\n", "meta": {"hexsha": "816244ea062cfa7802b4c9aa77d68e79ff18c10c", "size": 9215, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/geometry/srs/projections/proj/natearth.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/natearth.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/natearth.hpp", "max_forks_repo_name": "jeffphi/advent-of-code-2018", "max_forks_repo_head_hexsha": "8e54bd23ebfe42fcbede315f0ab85db903551532", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.4166666667, "max_line_length": 119, "alphanum_fraction": 0.5815518177, "num_tokens": 2135, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6859494550081925, "lm_q2_score": 0.4687906266262437, "lm_q1q2_score": 0.3215666748472209}}
{"text": "#include <stdio.h>\n#include <cfloat>\n#include <list>\n#include <vector>\n#include <math.h>\n#include <iostream>\n#include <algorithm>\n#include <numeric>\n#include <random>\n#include <boost/algorithm/clamp.hpp>\n#include <boost/geometry.hpp>\n#include <boost/geometry/geometries/geometries.hpp>\n#include <boost/geometry/geometries/point_xy.hpp>\n#include <boost/graph/adjacency_matrix.hpp>\n#include <boost/graph/kruskal_min_spanning_tree.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#include <boost/geometry/io/wkt/write.hpp>\n#include \"bboxes.h\"\n\nusing namespace boost;\nusing namespace tensorflow;\nusing namespace std;\n\ntypedef Eigen::ThreadPoolDevice CPUDevice;\ntypedef adjacency_matrix<undirectedS, no_property, property <edge_weight_t, float>> Graph;\ntypedef graph_traits <Graph>::edge_descriptor Edge;\ntypedef std::pair<int, int> E;\n/*\n * 根据输入的boxes生成一个邻接矩阵\n * boxes: [N,4], ymin,xmin,ymax,xmax相对坐标\n * output:\n * matrix[N,N] 第i行,j列表示第i个点与第j个点之间的连接\n */\nREGISTER_OP(\"AdjacentMatrixGeneratorByIou\")\n    .Attr(\"T: {float, double,int32}\")\n\t.Attr(\"threshold:float\")\n    .Attr(\"keep_connect: bool\")\n    .Input(\"bboxes: T\")\n\t.Output(\"matrix:int32\")\n\t.SetShapeFn([](shape_inference::InferenceContext* c) {\n\t\t    auto box_nr = c->Dim(c->input(0),0);\n\t\t\tc->set_output(0, c->Matrix(box_nr,box_nr));\n\t\t\treturn Status::OK();\n\t\t\t});\n\ntemplate <typename Device, typename T>\nclass AdjacentMatrixGeneratorByIouOp: public OpKernel {\n    public:\n        explicit AdjacentMatrixGeneratorByIouOp(OpKernelConstruction* context) : OpKernel(context) {\n            OP_REQUIRES_OK(context, context->GetAttr(\"threshold\", &threshold_));\n            OP_REQUIRES_OK(context, context->GetAttr(\"keep_connect\", &keep_connect_));\n        }\n\n        void Compute(OpKernelContext* context) override\n        {\n            const Tensor &_bboxes  = context->input(0);\n            auto          bboxes   = _bboxes.template tensor<T,2>();\n\n            OP_REQUIRES(context, _bboxes.dims() == 2, errors::InvalidArgument(\"bboxes data must be 2-dimensional\"));\n            const auto bboxes_nr    = _bboxes.dim_size(0);\n            Eigen::Tensor<float,2,Eigen::RowMajor> dis_matrix(bboxes_nr,bboxes_nr);\n\n            dis_matrix.setZero();\n\n            if(keep_connect_) {\n                for(auto i=0; i<bboxes_nr-1; ++i) {\n                    const Eigen::Tensor<T,1,Eigen::RowMajor> box_data0 = bboxes.chip(i,0);\n\n                    dis_matrix(i,i) = 0.;\n                    for(auto j=i+1; j<bboxes_nr; ++j) {\n                        const Eigen::Tensor<T,1,Eigen::RowMajor> box_data1 = bboxes.chip(j,0);\n                        const auto dis = distance(box_data0,box_data1);\n                        dis_matrix(i,j) = dis;\n                        dis_matrix(j,i) = dis;\n                    }\n                }\n            }\n\n            auto res = make_graph(bboxes,dis_matrix);\n\n            Tensor      *output_matrix = NULL;\n            TensorShape  output_shape;\n            const int    dims_2d[]     = {int(bboxes_nr),int(bboxes_nr)};\n\n            TensorShapeUtils::MakeShape(dims_2d, 2, &output_shape);\n            OP_REQUIRES_OK(context, context->allocate_output(0, output_shape, &output_matrix));\n\n            auto output           = output_matrix->template tensor<int,2>();\n            for(auto i=0; i<bboxes_nr; ++i) {\n                output(i,i) = 0;\n                for(auto j=i+1; j<bboxes_nr; ++j) {\n                    output(i,j) = res(i,j);\n                    output(j,i) = res(i,j);\n                }\n            }\n        }\n        template<typename _T,typename M>\n            Eigen::Tensor<int,2,Eigen::RowMajor> make_graph(const _T& bboxes,const M& dis_m) {\n                const auto data_nr = bboxes.dimension(0);\n                Graph g(data_nr);\n                Eigen::Tensor<int,2,Eigen::RowMajor> res(data_nr,data_nr);\n                res.setZero();\n\n                if(keep_connect_) {\n                    auto weightmap = get(edge_weight,g);\n                    for(auto i=0; i<data_nr; ++i) {\n                        for(auto j=i+1; j<data_nr; ++j) {\n                            Edge e;\n                            bool inserted;\n                            boost::tie(e,inserted) = add_edge(i,j,g);\n                            weightmap[e] = dis_m(i,j);\n                        }\n                    }\n                    std::vector < Edge > spanning_tree;\n                    kruskal_minimum_spanning_tree(g, std::back_inserter(spanning_tree));\n                    for(auto e:spanning_tree) {\n                        auto si = source(e,g);\n                        auto ti = target(e,g);\n                        res(si,ti) = 1;\n                        res(ti,si) = 1;\n                    }\n                }\n                for(auto i=0; i<data_nr; ++i) {\n                    const Eigen::Tensor<T,1,Eigen::RowMajor> box_data0 = bboxes.chip(i,0);\n                    for(auto j=i+1; j<data_nr; ++j) {\n                        const Eigen::Tensor<T,1,Eigen::RowMajor> box_data1 = bboxes.chip(j,0);\n                        //if(bboxes_jaccardv1(box_data0,box_data1)>threshold_) {\n                        if((bboxes_jaccard_of_box0v1(box_data0,box_data1)>threshold_) ||\n                                (bboxes_jaccard_of_box0v1(box_data1,box_data0)>threshold_)) {\n                            res(i,j) = 1;\n                            res(j,i) = 1;\n                        }\n                    }\n                }\n                return res;\n            }\n        template<typename _T>\n            inline float distance(const _T& box0, const _T& box1) {\n                float cx0,cy0,cx1,cy1;\n                tie(cx0,cy0) = get_cxy(box0);\n                tie(cx1,cy1) = get_cxy(box1);\n                const auto dx = (cx0-cx1);\n                const auto dy = (cy0-cy1);\n                return sqrt(dx*dx+dy*dy);\n            }\n        template<typename _T>\n        static inline std::pair<float,float> get_cxy(const _T& box) {\n            return make_pair((box(1)+box(3))/2.0f,(box(0)+box(2))/2.0f);\n        }\n    private:\n        float threshold_ = 0.3f;\n        bool keep_connect_ = false;\n};\nREGISTER_KERNEL_BUILDER(Name(\"AdjacentMatrixGeneratorByIou\").Device(DEVICE_CPU).TypeConstraint<float>(\"T\"), AdjacentMatrixGeneratorByIouOp<CPUDevice, float>);\nREGISTER_KERNEL_BUILDER(Name(\"AdjacentMatrixGeneratorByIou\").Device(DEVICE_CPU).TypeConstraint<double>(\"T\"), AdjacentMatrixGeneratorByIouOp<CPUDevice, double>);\n\n/*\n * 根据输入的boxes生成一个邻接矩阵\n * boxes: [N,4], ymin,xmin,ymax,xmax相对坐标\n * output:\n * matrix[N,N] 第i行,j列表示第i个点与第j个点之间的连接\n */\nREGISTER_OP(\"AdjacentMatrixGeneratorByIouV2\")\n    .Attr(\"T: {float, double,int32}\")\n\t.Attr(\"threshold:list(float)=[0.3,0.12]\")\n    .Attr(\"keep_connect: bool\")\n    .Input(\"bboxes: T\")\n    .Input(\"labels: int32\")\n    .Input(\"probs: T\")\n\t.Output(\"matrix:int32\")\n\t.SetShapeFn([](shape_inference::InferenceContext* c) {\n\t\t    auto box_nr = c->Dim(c->input(0),0);\n\t\t\tc->set_output(0, c->Matrix(box_nr,box_nr));\n\t\t\treturn Status::OK();\n\t\t\t});\n\ntemplate <typename Device, typename T>\nclass AdjacentMatrixGeneratorByIouV2Op: public OpKernel {\n    public:\n        explicit AdjacentMatrixGeneratorByIouV2Op(OpKernelConstruction* context) : OpKernel(context) {\n            OP_REQUIRES_OK(context, context->GetAttr(\"threshold\", &threshold_));\n            OP_REQUIRES_OK(context, context->GetAttr(\"keep_connect\", &keep_connect_));\n        }\n\n        void Compute(OpKernelContext* context) override\n        {\n            const Tensor &_bboxes  = context->input(0);\n            const Tensor &_labels = context->input(1);\n            const Tensor &_probs = context->input(2);\n            auto          bboxes   = _bboxes.template tensor<T,2>();\n            auto          labels = _labels.template tensor<int,1>();\n            auto          probs = _probs.template tensor<T,2>();\n\n            OP_REQUIRES(context, _bboxes.dims() == 2, errors::InvalidArgument(\"bboxes data must be 2-dimensional\"));\n            const auto bboxes_nr    = _bboxes.dim_size(0);\n            Eigen::Tensor<float,2,Eigen::RowMajor> dis_matrix(bboxes_nr,bboxes_nr);\n\n            dis_matrix.setZero();\n\n            if(keep_connect_) {\n                for(auto i=0; i<bboxes_nr-1; ++i) {\n                    const Eigen::Tensor<T,1,Eigen::RowMajor> box_data0 = bboxes.chip(i,0);\n\n                    dis_matrix(i,i) = 0.;\n                    for(auto j=i+1; j<bboxes_nr; ++j) {\n                        const Eigen::Tensor<T,1,Eigen::RowMajor> box_data1 = bboxes.chip(j,0);\n                        const auto dis = distance(box_data0,box_data1);\n                        dis_matrix(i,j) = dis;\n                        dis_matrix(j,i) = dis;\n                    }\n                }\n            }\n\n            auto res = make_graph(bboxes,labels,probs,dis_matrix);\n\n            Tensor      *output_matrix = NULL;\n            TensorShape  output_shape;\n            const int    dims_2d[]     = {int(bboxes_nr),int(bboxes_nr)};\n\n            TensorShapeUtils::MakeShape(dims_2d, 2, &output_shape);\n            OP_REQUIRES_OK(context, context->allocate_output(0, output_shape, &output_matrix));\n\n            auto output           = output_matrix->template tensor<int,2>();\n            for(auto i=0; i<bboxes_nr; ++i) {\n                output(i,i) = 0;\n                for(auto j=i+1; j<bboxes_nr; ++j) {\n                    output(i,j) = res(i,j);\n                    output(j,i) = res(i,j);\n                }\n            }\n        }\n        template<typename _T,typename _TL,typename _TP,typename M>\n            Eigen::Tensor<int,2,Eigen::RowMajor> make_graph(const _T& bboxes,const _TL& labels,const _TP& probs,const M& dis_m) {\n                const auto data_nr = bboxes.dimension(0);\n                Graph g(data_nr);\n                Eigen::Tensor<int,2,Eigen::RowMajor> res(data_nr,data_nr);\n                res.setZero();\n\n                if(keep_connect_) {\n                    auto weightmap = get(edge_weight,g);\n                    for(auto i=0; i<data_nr; ++i) {\n                        for(auto j=i+1; j<data_nr; ++j) {\n                            Edge e;\n                            bool inserted;\n                            boost::tie(e,inserted) = add_edge(i,j,g);\n                            weightmap[e] = dis_m(i,j);\n                        }\n                    }\n                    std::vector < Edge > spanning_tree;\n                    kruskal_minimum_spanning_tree(g, std::back_inserter(spanning_tree));\n                    for(auto e:spanning_tree) {\n                        auto si = source(e,g);\n                        auto ti = target(e,g);\n                        res(si,ti) = 1;\n                        res(ti,si) = 1;\n                    }\n                }\n                for(auto i=0; i<data_nr; ++i) {\n                    const Eigen::Tensor<T,1,Eigen::RowMajor> box_data0 = bboxes.chip(i,0);\n                    for(auto j=i+1; j<data_nr; ++j) {\n                        const Eigen::Tensor<T,1,Eigen::RowMajor> box_data1 = bboxes.chip(j,0);\n                        const auto probs_corr = prob_correlation(probs,i,j);\n                        if((labels(i) != labels(j)) &&\n                            (probs_corr<threshold_[1]))\n                            continue;\n                        if((bboxes_jaccardv1(box_data0,box_data1)>threshold_[0])) {\n                            res(i,j) = 1;\n                            res(j,i) = 1;\n                        }\n                    }\n                }\n                return res;\n            }\n        template<typename _T>\n            float prob_correlation(const _T& p0, int i,int j) {\n                const auto nr = p0.dimension(1);\n                float dis = 0.0f;\n                for(auto k=0; k<nr; ++k) {\n                    dis += (p0(i,k)*p0(j,k));\n                }\n                return dis;\n            }\n        template<typename _T>\n            inline float distance(const _T& box0, const _T& box1) {\n                float cx0,cy0,cx1,cy1;\n                tie(cx0,cy0) = get_cxy(box0);\n                tie(cx1,cy1) = get_cxy(box1);\n                const auto dx = (cx0-cx1);\n                const auto dy = (cy0-cy1);\n                return sqrt(dx*dx+dy*dy);\n            }\n        template<typename _T>\n        static inline std::pair<float,float> get_cxy(const _T& box) {\n            return make_pair((box(1)+box(3))/2.0f,(box(0)+box(2))/2.0f);\n        }\n    private:\n        vector<float> threshold_;\n        bool keep_connect_ = false;\n};\nREGISTER_KERNEL_BUILDER(Name(\"AdjacentMatrixGeneratorByIouV2\").Device(DEVICE_CPU).TypeConstraint<float>(\"T\"), AdjacentMatrixGeneratorByIouV2Op<CPUDevice, float>);\nREGISTER_KERNEL_BUILDER(Name(\"AdjacentMatrixGeneratorByIouV2\").Device(DEVICE_CPU).TypeConstraint<double>(\"T\"), AdjacentMatrixGeneratorByIouV2Op<CPUDevice, double>);\n\n/*\n * 根据输入的boxes生成一个邻接矩阵\n * boxes: [N,4], ymin,xmin,ymax,xmax相对坐标\n * output:\n * matrix[N,N] 第i行,j列表示第i个点与第j个点之间的连接\n */\nREGISTER_OP(\"AdjacentMatrixGeneratorByIouV3\")\n    .Attr(\"T: {float, double,int32}\")\n\t.Attr(\"threshold:float\")\n    .Attr(\"keep_connect: bool=False\")\n    .Input(\"bboxes: T\")\n\t.Output(\"matrix:int32\")\n\t.SetShapeFn([](shape_inference::InferenceContext* c) {\n\t\t    auto box_nr = c->Dim(c->input(0),0);\n\t\t\tc->set_output(0, c->Matrix(box_nr,box_nr));\n\t\t\treturn Status::OK();\n\t\t\t});\n\ntemplate <typename Device, typename T>\nclass AdjacentMatrixGeneratorByIouV3Op: public OpKernel {\n    public:\n        explicit AdjacentMatrixGeneratorByIouV3Op(OpKernelConstruction* context) : OpKernel(context) {\n            OP_REQUIRES_OK(context, context->GetAttr(\"threshold\", &threshold_));\n            OP_REQUIRES_OK(context, context->GetAttr(\"keep_connect\", &keep_connect_));\n        }\n\n        void Compute(OpKernelContext* context) override\n        {\n            const Tensor &_bboxes  = context->input(0);\n            auto          bboxes   = _bboxes.template tensor<T,2>();\n\n            OP_REQUIRES(context, _bboxes.dims() == 2, errors::InvalidArgument(\"bboxes data must be 2-dimensional\"));\n            const auto bboxes_nr    = _bboxes.dim_size(0);\n            Eigen::Tensor<float,2,Eigen::RowMajor> dis_matrix(bboxes_nr,bboxes_nr);\n\n            dis_matrix.setZero();\n\n            if(keep_connect_) {\n                for(auto i=0; i<bboxes_nr-1; ++i) {\n                    const Eigen::Tensor<T,1,Eigen::RowMajor> box_data0 = bboxes.chip(i,0);\n\n                    dis_matrix(i,i) = 0.;\n                    for(auto j=i+1; j<bboxes_nr; ++j) {\n                        const Eigen::Tensor<T,1,Eigen::RowMajor> box_data1 = bboxes.chip(j,0);\n                        const auto dis = distance(box_data0,box_data1);\n                        dis_matrix(i,j) = dis;\n                        dis_matrix(j,i) = dis;\n                    }\n                }\n            }\n\n            auto res = make_graph(bboxes,dis_matrix);\n\n            Tensor      *output_matrix = NULL;\n            TensorShape  output_shape;\n            const int    dims_2d[]     = {int(bboxes_nr),int(bboxes_nr)};\n\n            TensorShapeUtils::MakeShape(dims_2d, 2, &output_shape);\n            OP_REQUIRES_OK(context, context->allocate_output(0, output_shape, &output_matrix));\n\n            auto output           = output_matrix->template tensor<int,2>();\n            for(auto i=0; i<bboxes_nr; ++i) {\n                output(i,i) = 0;\n                for(auto j=i+1; j<bboxes_nr; ++j) {\n                    output(i,j) = res(i,j);\n                    output(j,i) = res(j,i);\n                }\n            }\n        }\n        template<typename _T,typename M>\n            Eigen::Tensor<int,2,Eigen::RowMajor> make_graph(const _T& bboxes,const M& dis_m) {\n                const auto data_nr = bboxes.dimension(0);\n                Graph g(data_nr);\n                Eigen::Tensor<int,2,Eigen::RowMajor> res(data_nr,data_nr);\n                res.setZero();\n\n                if(keep_connect_) {\n                    auto weightmap = get(edge_weight,g);\n                    for(auto i=0; i<data_nr; ++i) {\n                        for(auto j=i+1; j<data_nr; ++j) {\n                            Edge e;\n                            bool inserted;\n                            boost::tie(e,inserted) = add_edge(i,j,g);\n                            weightmap[e] = dis_m(i,j);\n                        }\n                    }\n                    std::vector < Edge > spanning_tree;\n                    kruskal_minimum_spanning_tree(g, std::back_inserter(spanning_tree));\n                    for(auto e:spanning_tree) {\n                        auto si = source(e,g);\n                        auto ti = target(e,g);\n                        res(si,ti) = 1;\n                        res(ti,si) = 1;\n                    }\n                }\n                for(auto i=0; i<data_nr; ++i) {\n                    const Eigen::Tensor<T,1,Eigen::RowMajor> box_data0 = bboxes.chip(i,0);\n                    for(auto j=i+1; j<data_nr; ++j) {\n                        const Eigen::Tensor<T,1,Eigen::RowMajor> box_data1 = bboxes.chip(j,0);\n                        if((bboxes_jaccardv1(box_data0,box_data1)>threshold_)) {\n                            res(i,j) = 1;\n                            res(j,i) = 1;\n                        }\n                    }\n                }\n                return res;\n            }\n        template<typename _T>\n            inline float distance(const _T& box0, const _T& box1) {\n                float cx0,cy0,cx1,cy1;\n                tie(cx0,cy0) = get_cxy(box0);\n                tie(cx1,cy1) = get_cxy(box1);\n                const auto dx = (cx0-cx1);\n                const auto dy = (cy0-cy1);\n                return sqrt(dx*dx+dy*dy);\n            }\n        template<typename _T>\n        static inline std::pair<float,float> get_cxy(const _T& box) {\n            return make_pair((box(1)+box(3))/2.0f,(box(0)+box(2))/2.0f);\n        }\n    private:\n        float threshold_ = 0.3f;\n        bool keep_connect_ = false;\n};\nREGISTER_KERNEL_BUILDER(Name(\"AdjacentMatrixGeneratorByIouV3\").Device(DEVICE_CPU).TypeConstraint<float>(\"T\"), AdjacentMatrixGeneratorByIouV3Op<CPUDevice, float>);\nREGISTER_KERNEL_BUILDER(Name(\"AdjacentMatrixGeneratorByIouV3\").Device(DEVICE_CPU).TypeConstraint<double>(\"T\"), AdjacentMatrixGeneratorByIouV3Op<CPUDevice, double>);\n\n/*\n * 根据输入的boxes生成一个邻接矩阵\n * boxes: [N,4], ymin,xmin,ymax,xmax相对坐标\n * output:\n * matrix[N,N] 第i行,j列表示第i个点与第j个点之间的连接\n */\nREGISTER_OP(\"AdjacentMatrixGeneratorByIouV4\")\n    .Attr(\"T: {float, double,int32}\")\n\t.Attr(\"threshold:float=0.3\")\n    .Attr(\"keep_connect: bool\")\n    .Input(\"bboxes: T\")\n    .Input(\"labels: int32\")\n\t.Output(\"matrix:int32\")\n\t.SetShapeFn([](shape_inference::InferenceContext* c) {\n\t\t    auto box_nr = c->Dim(c->input(0),0);\n\t\t\tc->set_output(0, c->Matrix(box_nr,box_nr));\n\t\t\treturn Status::OK();\n\t\t\t});\n\ntemplate <typename Device, typename T>\nclass AdjacentMatrixGeneratorByIouV4Op: public OpKernel {\n    public:\n        explicit AdjacentMatrixGeneratorByIouV4Op(OpKernelConstruction* context) : OpKernel(context) {\n            OP_REQUIRES_OK(context, context->GetAttr(\"threshold\", &threshold_));\n            OP_REQUIRES_OK(context, context->GetAttr(\"keep_connect\", &keep_connect_));\n        }\n\n        void Compute(OpKernelContext* context) override\n        {\n            const Tensor &_bboxes  = context->input(0);\n            const Tensor &_labels = context->input(1);\n            auto          bboxes   = _bboxes.template tensor<T,2>();\n            auto          labels = _labels.template tensor<int,1>();\n\n            OP_REQUIRES(context, _bboxes.dims() == 2, errors::InvalidArgument(\"bboxes data must be 2-dimensional\"));\n            const auto bboxes_nr    = _bboxes.dim_size(0);\n            Eigen::Tensor<float,2,Eigen::RowMajor> dis_matrix(bboxes_nr,bboxes_nr);\n\n            dis_matrix.setZero();\n\n            if(keep_connect_) {\n                for(auto i=0; i<bboxes_nr-1; ++i) {\n                    const Eigen::Tensor<T,1,Eigen::RowMajor> box_data0 = bboxes.chip(i,0);\n\n                    dis_matrix(i,i) = 0.;\n                    for(auto j=i+1; j<bboxes_nr; ++j) {\n                        const Eigen::Tensor<T,1,Eigen::RowMajor> box_data1 = bboxes.chip(j,0);\n                        const auto dis = distance(box_data0,box_data1);\n                        dis_matrix(i,j) = dis;\n                        dis_matrix(j,i) = dis;\n                    }\n                }\n            }\n\n            auto res = make_graph(bboxes,labels,dis_matrix);\n\n            Tensor      *output_matrix = NULL;\n            TensorShape  output_shape;\n            const int    dims_2d[]     = {int(bboxes_nr),int(bboxes_nr)};\n\n            TensorShapeUtils::MakeShape(dims_2d, 2, &output_shape);\n            OP_REQUIRES_OK(context, context->allocate_output(0, output_shape, &output_matrix));\n\n            auto output           = output_matrix->template tensor<int,2>();\n            for(auto i=0; i<bboxes_nr; ++i) {\n                output(i,i) = 0;\n                for(auto j=i+1; j<bboxes_nr; ++j) {\n                    output(i,j) = res(i,j);\n                    output(j,i) = res(i,j);\n                }\n            }\n        }\n        template<typename _T,typename _TL,typename M>\n            Eigen::Tensor<int,2,Eigen::RowMajor> make_graph(const _T& bboxes,const _TL& labels,const M& dis_m) {\n                const auto data_nr = bboxes.dimension(0);\n                Graph g(data_nr);\n                Eigen::Tensor<int,2,Eigen::RowMajor> res(data_nr,data_nr);\n                res.setZero();\n\n                if(keep_connect_) {\n                    auto weightmap = get(edge_weight,g);\n                    for(auto i=0; i<data_nr; ++i) {\n                        for(auto j=i+1; j<data_nr; ++j) {\n                            Edge e;\n                            bool inserted;\n                            boost::tie(e,inserted) = add_edge(i,j,g);\n                            weightmap[e] = dis_m(i,j);\n                        }\n                    }\n                    std::vector < Edge > spanning_tree;\n                    kruskal_minimum_spanning_tree(g, std::back_inserter(spanning_tree));\n                    for(auto e:spanning_tree) {\n                        auto si = source(e,g);\n                        auto ti = target(e,g);\n                        res(si,ti) = 1;\n                        res(ti,si) = 1;\n                    }\n                }\n                for(auto i=0; i<data_nr; ++i) {\n                    const Eigen::Tensor<T,1,Eigen::RowMajor> box_data0 = bboxes.chip(i,0);\n                    for(auto j=i+1; j<data_nr; ++j) {\n                        const Eigen::Tensor<T,1,Eigen::RowMajor> box_data1 = bboxes.chip(j,0);\n                        if((labels(i) != labels(j)))\n                            continue;\n                        if((bboxes_jaccardv1(box_data0,box_data1)>threshold_)) {\n                            res(i,j) = 1;\n                            res(j,i) = 1;\n                        }\n                    }\n                }\n                return res;\n            }\n        template<typename _T>\n            inline float distance(const _T& box0, const _T& box1) {\n                float cx0,cy0,cx1,cy1;\n                tie(cx0,cy0) = get_cxy(box0);\n                tie(cx1,cy1) = get_cxy(box1);\n                const auto dx = (cx0-cx1);\n                const auto dy = (cy0-cy1);\n                return sqrt(dx*dx+dy*dy);\n            }\n        template<typename _T>\n        static inline std::pair<float,float> get_cxy(const _T& box) {\n            return make_pair((box(1)+box(3))/2.0f,(box(0)+box(2))/2.0f);\n        }\n    private:\n        float threshold_=0.3f;\n        bool keep_connect_ = false;\n};\nREGISTER_KERNEL_BUILDER(Name(\"AdjacentMatrixGeneratorByIouV4\").Device(DEVICE_CPU).TypeConstraint<float>(\"T\"), AdjacentMatrixGeneratorByIouV4Op<CPUDevice, float>);\nREGISTER_KERNEL_BUILDER(Name(\"AdjacentMatrixGeneratorByIouV4\").Device(DEVICE_CPU).TypeConstraint<double>(\"T\"), AdjacentMatrixGeneratorByIouV4Op<CPUDevice, double>);\n", "meta": {"hexsha": "8186d8bd9e4bf93cd828fee39234a7bf0aebd730", "size": 24100, "ext": "cc", "lang": "C++", "max_stars_repo_path": "tfop/gn.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/gn.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/gn.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": 42.5795053004, "max_line_length": 164, "alphanum_fraction": 0.52406639, "num_tokens": 5996, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.727975460709318, "lm_q2_score": 0.44167300566462564, "lm_q1q2_score": 0.32152710978157506}}
{"text": "#ifndef INCLUDED_search_HackPack_hh\n#define INCLUDED_search_HackPack_hh\n\n#include \"scheme/objective/storage/TwoBodyTable.hh\"\n\n\t#include <random>\n\t#include <boost/foreach.hpp>\n\n\nnamespace scheme { namespace search {\n\ntemplate< typename Float >\ninline\nbool\npass_metropolis(\n\tFloat const & temperature,\n\tFloat const & deltaE,\n\tFloat const & random_uniform\n)\n{\n\tif ( deltaE < 0 ) {\n\t\treturn true;\n\t} else { //evaluate prob of substitution\n\t\tFloat lnprob = deltaE / temperature;\n\t\tif ( lnprob < 10.0 ) {\n\t\t\tFloat probability = std::exp(-lnprob);\n\t\t\tif ( probability > random_uniform ) return true;\n\t\t}\n\t}\n\treturn false;\n }\n\n\n\n\nstruct HackPackOpts\n{\n\tint   pack_n_iters = 1;\n\tfloat pack_iter_mult = 2.0;\n\tfloat hbond_weight = 2.0;\n\tfloat upweight_iface = 1.0;\n\tfloat upweight_multi_hbond = 0.0;\n\tfloat min_hb_quality_for_satisfaction = -0.6;\n\tbool  use_extra_rotamers = true;\n\tint   always_available_rotamers_level = 0;\n\tbool  packing_use_rif_rotamers = true;\n\tbool  add_native_scaffold_rots_when_packing = false;\n\tfloat rotamer_inclusion_threshold = -0.5;\n\tfloat rotamer_onebody_inclusion_threshold = 30.0;//5\n\tbool  init_with_best_1be_rots = true;\n\tfloat user_rotamer_bonus_constant = -2; //-2\n\tfloat user_rotamer_bonus_per_chi = -2; // 2\n\tbool  rescore_rots_before_insertion = true;\t\t// this isn't a real flag, gets used in MyScoreBBActorVsRif\n};\ninline\nstd::ostream & operator<<( std::ostream & out, HackPackOpts const & hpo ){\n\tout << \"HackPackOpts:\"\n\t\t<< \"\\n  pack_iter_mult \" << hpo.pack_iter_mult\n\t\t<< \"\\n  hbond_weight \" << hpo.hbond_weight\n\t\t<< \"\\n  upweight_iface \" << hpo.upweight_iface\n\t\t<< \"\\n  upweight_multi_hbond \" << hpo.upweight_multi_hbond\n\t\t<< \"\\n  use_extra_rotamers \" << hpo.use_extra_rotamers\n\t\t<< \"\\n  always_available_rotamers_level \" << hpo.always_available_rotamers_level\n\t\t<< \"\\n  packing_use_rif_rotamers \" << hpo.packing_use_rif_rotamers\n\t\t<< \"\\n  add_native_scaffold_rots_when_packing \" << hpo.add_native_scaffold_rots_when_packing\n\t\t<< \"\\n  rotamer_inclusion_threshold \" << hpo.rotamer_inclusion_threshold\n\t\t<< \"\\n  rotamer_onebody_inclusion_threshold \" << hpo.rotamer_onebody_inclusion_threshold\n\t\t<< \"\\n  init_with_best_1be_rots \" << hpo.init_with_best_1be_rots\n\t\t<< \"\\n  user_rotamer_bonus_constant \" << hpo.user_rotamer_bonus_constant \n\t\t<< \"\\n  user_rotamer_bonus_per_chi\" << hpo.user_rotamer_bonus_per_chi\n\t\t<< \"\\n  rescore_rots_before_insertion \" << hpo.rescore_rots_before_insertion\n\n\n\t    << std::endl;\n\treturn out;\n}\n\nstruct HackPack\n{\n\ttypedef std::pair<int32_t,float> RotInfo;\n\ttypedef std::pair< int32_t, std::vector< RotInfo > > RotInfos;\n\tint nres_; // total res currently stored\n\tstd::vector< RotInfos > res_rots_; // iresapp + list of irottwob/onebody pairs\n\tstd::vector< std::pair<int32_t,int32_t> > rot_list_; // list of ireslocal / irotlocal pairs\n\tstd::vector< int32_t > current_rots_, trial_best_rots_, global_best_rots_; // current rotamer in local numbering\n\tstd::mt19937 rng;\n\tshared_ptr<::scheme::objective::storage::TwoBodyTable<float>> twob_; \n\tfloat score_, trial_best_score_, global_best_score_;\n\tHackPackOpts opts_;\n\tint32_t default_rot_num_;\n\tHackPack(\n\t\t// ::scheme::objective::storage::TwoBodyTable<float> const & twob,\n\t\tHackPackOpts const & opts,\n\t\tint32_t default_rot_num,\n\t\tint seed_offset = 0 // mainly for threads\n\t)\n\t\t: nres_(0)\n\t\t, rng( time(0)+seed_offset )\n\t\t// , twob_( twob )\n\t\t, opts_(opts)\n\t\t, default_rot_num_( default_rot_num )\n\t{}\n\n\tvoid reinitialize(\n\t\tshared_ptr<::scheme::objective::storage::TwoBodyTable<float> > twob ){\n\n\t\t// Brian\n\n\t\ttwob_ = twob;\n\t\tALWAYS_ASSERT( twob_->nrot_ > 0 );\n\t\tALWAYS_ASSERT( twob_->nres_ > 0 );\n\t\tALWAYS_ASSERT( twob_->nrot_ < 99999 );\n\t\tALWAYS_ASSERT( twob_->nres_ < 99999 );\n\n\t\t////////////////////\n\n\n\t\t// todo: always add native rotamer and ALA/GLY as appropriate\n\t\t// should hopefully not deallocate memory\n\t\trot_list_.clear();\n\t\tBOOST_FOREACH( RotInfos & rotinfos, res_rots_ ){\n\t\t\trotinfos.first = -1;\n\t\t\trotinfos.second.clear();\n\t\t}\n\t\tnres_ = 0;\n\t}\n\ttemplate< class Int >\n\tbool using_rotamer( Int const & ires, Int const & irotglobal )\n\t{\n\t\tALWAYS_ASSERT( 0 <= ires && ires < twob_->all2sel_.shape()[0] );\n\t\tALWAYS_ASSERT( 0 <= irotglobal && irotglobal < twob_->all2sel_.shape()[1] );\n\t\treturn twob_->all2sel_[ires][irotglobal] >= 0;\n\t}\n\ttemplate< class Int >\n\tvoid add_tmp_rot( int const & ires, Int const & irotglobal, float const & onebody_e, bool allow_high_energy=false )\n\t{\n\t\t// #pragma omp critical\n\t\t// {\n\t\t// \tstd::cout << \"================= add_tmp_rot \" << ires << \" \" << irotglobal << \" \" << onebody_e << std::endl;\n\t\t// \tprint_rot_info();\n\t\t// }\n\t\tif( onebody_e > 10.0 && ! allow_high_energy ){\n\t\t\treturn;\n\t\t}\n\t\tALWAYS_ASSERT( 0 <= ires && ires < twob_->all2sel_.shape()[0] );\n\t\tALWAYS_ASSERT( 0 <= irotglobal && irotglobal < twob_->all2sel_.shape()[1] );\n\t\tint32_t irotlocal = twob_->all2sel_[ires][irotglobal];\n\t\t// std::cout << \"irotlocal\" << irotlocal << std::endl;\n\t\tif( irotlocal >= 0 ){\n\t\t\tif( nres_==0 || res_rots_.at(nres_-1).first != ires ){\n\t\t\t\t++nres_;\n\t\t\t\tif( res_rots_.size() < nres_ ) res_rots_.resize( nres_ );\n\t\t\t\tres_rots_.at(nres_-1).first = ires;\n\t\t\t\t// always allow ALA as an option:\n\t\t\t\tint alarot = twob_->all2sel_[ires][ default_rot_num_ ];\n\t\t\t\tif( alarot >= 0 ) {\n\t\t\t\t\trot_list_.push_back( std::make_pair( nres_-1, res_rots_.at(nres_-1).second.size() ) );\n\t\t\t\t\tres_rots_.at(nres_-1).second.push_back( RotInfo( alarot, 0.0 ) );\n\t\t\t\t}\n\t\t\t}\n\t\t\trot_list_.push_back( std::make_pair( nres_-1, res_rots_.at(nres_-1).second.size() ) );\n\t\t\tres_rots_.at(nres_-1).second.push_back( RotInfo( irotlocal, onebody_e ) );\n\t\t} else {\n\t\t\t// std::cout << \"Error!!!: Rotamer not in twobody energies \" << irotglobal << \" \" << ires << std::endl;\n\t\t\t// static bool missingrotwarn = true;\n\t\t\t// if( missingrotwarn ){\n\t\t\t// \t#ifdef USE_OPENMP\n\t\t\t// \t#pragma omp critical\n\t\t\t// \t#endif\n\t\t\t// \t{\n\t\t\t// \t\tstd::cout << \"WARNING: requested rotamer not in TwoBodyTable, probably has bad 1BE, subsequent warnings will be skipped: \"\n\t\t\t// \t\t          << \" irotglobal: \" << irotglobal << std::endl;\n\t\t\t// \t\tmissingrotwarn = false;\n\t\t\t// \t\t// std::exit(-1);\n\t\t\t// \t}\n\t\t\t// }\n\t\t}\n\t}\n\n\n\tfloat\n\tcompute_energy_full(\n\t\tstd::vector< int32_t > const & rots\n\t) const {\n\t\t\t// using namespace ObjexxFCL::format;\n\t\t// for( int i = 1; i < nres_; ++i ){\n\t\t// \t\tint   const iresglobal = res_rots_[i].first;\n\t\t// \t\tint   const irottwob   = res_rots_[i].second[ rots[i] ].first;\n\t\t// \t\tfloat const ionebody   = res_rots_[i].second[ rots[i] ].second;\n\t\t// \t\tint irotglobal = twob_->sel2all_[ iresglobal ][ irottwob ];\n\t\t// \t\tstd::cout << \"ONEBODY \" << iresglobal << \" \" << rot_index_.resname(irotglobal) << irotglobal << \" \" << ionebody << std::endl;\n\t\t// \t}\n\t\tfloat score = 0.0;\n\t\tfor( int ires = 0; ires < nres_; ++ires ){\n\t\t\t\tassert( 0 <= ires && ires < rots.size() );\n\t\t\tint32_t const irotlocal = rots.at(ires);\n\t\t\t\tassert( 0 <= ires && ires < res_rots_.size() );\n\t\t\t\t// std::cout << ires << \" \" << irotlocal << \" \" << res_rots_[ires].second.size() << std::endl;\n\t\t\t\tassert( 0 <= irotlocal && irotlocal < res_rots_.at(ires).second.size() );\n\t\t\tint32_t const iresglobal = res_rots_.at(ires).first;\n\t\t\tint32_t const irottwob   = res_rots_.at(ires).second.at( irotlocal ).first;\n\t\t\tfloat const ionebody     = res_rots_.at(ires).second.at( irotlocal ).second;\n\t\t\tscore += ionebody;\n\t\t\tfor( int jres = 0; jres < ires; ++jres ){\n\t\t\t\t\tassert( 0 <= jres && jres < rots.size() );\n\t\t\t\tint32_t const jrotlocal = rots.at(jres);\n\t\t\t\t\tassert( 0 <= jres && jres < res_rots_.size() );\n\t\t\t\t\tassert( 0 <= jrotlocal && jrotlocal < res_rots_.at(jres).second.size() );\n\t\t\t\tint32_t const jresglobal = res_rots_.at(jres).first;\n\t\t\t\tint32_t const jrottwob   = res_rots_.at(jres).second.at( jrotlocal ).first;\n\t\t\t\tfloat const jonebody     = res_rots_.at(jres).second.at( jrotlocal ).second;\n\t\t\t\tfloat const twobodye     = twob_->twobody_rotlocalnumbering( iresglobal, jresglobal, irottwob, jrottwob );\n\t\t\t\tscore += twobodye;\n\t\t\t\t\t// int irotglobal = twob_->sel2all_[ iresglobal ][ irottwob ];\n\t\t\t\t\t// int jrotglobal = twob_->sel2all_[ jresglobal ][ jrottwob ];\n\t\t\t\t\t// std::cout << \"TWOBODY \"\n\t\t\t\t\t//           << I(2,ires) << \"/\" << I(2,jres) << \" \"\n\t\t\t\t\t//           << I(3,iresglobal) << \"/\" << I(3,jresglobal) << \" \"\n\t\t\t\t\t//           << rot_index_.resname(irotglobal) << I(3,irottwob) << \"/\"\n\t\t\t\t\t//           << rot_index_.resname(jrotglobal) << I(3,jrottwob) << \" \"\n\t\t\t\t\t//           << F(7,3,twobodye) << std::endl;\n\t\t\t}\n\t\t}\n\t\treturn score;\n\t}\n\tfloat\n\tcompute_energy_delta(\n\t\tstd::vector< int32_t > const & rots,\n\t\tint32_t const & ilres,\n\t\tint32_t const & ilrotnew\n\t) const {\n\t\t// using namespace ObjexxFCL::format;\n\t\tfloat delta = 0;\n\t\tint32_t const ilrotold = rots.at(ilres);\n\t\tint32_t const iresglobal  = res_rots_.at(ilres).first;\n\t\tint32_t const irottwobold = res_rots_.at(ilres).second.at( rots.at(ilres) ).first;\n\t\tfloat   const ionebodyold = res_rots_.at(ilres).second.at( rots.at(ilres) ).second;\n\t\tint32_t const irottwobnew = res_rots_.at(ilres).second.at(  ilrotnew   ).first;\n\t\tfloat   const ionebodynew = res_rots_.at(ilres).second.at(  ilrotnew   ).second;\n\t\tdelta -= ionebodyold;\n\t\tdelta += ionebodynew;\n\t\tfor( int j = 0; j < nres_; ++j ){\n\t\t\tif( j == ilres ) continue;\n\t\t\tint32_t const jresglobal = res_rots_.at(j).first;\n\t\t\tint32_t const jrottwob   = res_rots_.at(j).second.at( rots.at(j) ).first;\n\t\t\tfloat   const jonebody   = res_rots_.at(j).second.at( rots.at(j) ).second;\n\t\t\tfloat   const twobodyeold = twob_->twobody_rotlocalnumbering( iresglobal, jresglobal, irottwobold, jrottwob );\n\t\t\tfloat   const twobodyenew = twob_->twobody_rotlocalnumbering( iresglobal, jresglobal, irottwobnew, jrottwob );\n\t\t\tdelta -= twobodyeold;\n\t\t\tdelta += twobodyenew;\n\t\t\t// std::cout << \"DELTA TWOB\"\n\t\t\t//           << \" ires \"    << I(2,ilres   ) << \"/\" << I(3,iresglobal )\n\t\t\t//           << \" jres \"    << I(2,j       ) << \"/\" << I(3,jresglobal)\n\t\t\t//           << \" irotold \" << I(2,ilrotold) << \"/\" << I(3,irottwobold)\n\t\t\t//           << \" irotnew \" << I(2,ilrotnew) << \"/\" << I(3,irottwobnew)\n\t\t\t//           << \" jrot \"    << I(2,rots[j] ) << \"/\" << I(3,jrottwob)\n\t\t\t//           << \" e \" << F(7,3,twobodyeold)  << \" \" << F(7,3,twobodyenew)\n\t\t\t//           << std::endl;\n\t\t}\n\t\tif( -123460.0 > delta || delta > 123460.0 ){ // 10x energy cap per-rottable entry\n\t\t\tbool throwerr = false;\n\t\t\t#ifdef USE_OPENMP\n\t\t\t#pragma omp critical\n\t\t\t#endif\n\t\t\t{\n\t\t\t\tstd::cout << \"crazy energy delta, indicates a problem.... res (scene numbering) = \" << res_rots_.at(ilres).first << \" \" << delta \n\t\t\t\t\t<< \" 1body-old: \" << ionebodyold << \" 1body-new: \" << ionebodynew << std::endl;\n\t\t\t\tstatic int errcount = 0;\n\t\t\t\tif( ++errcount > 10 ) throwerr = true;\n\t\t\t}\n\t\t\tif( throwerr ) throw std::logic_error(\"too many crazy energy deltas\");\n\t\t\treturn 9e9;\n\t\t}\n\t\treturn delta;\n\t}\n\tint32_t randres()\n\t{\n\t\tstd::uniform_int_distribution<> rand_idx(0,nres_-1);\n\t\treturn rand_idx( rng );\n\t}\n\tint32_t randrot( int32_t const & ires )\n\t{\n\t\tassert( res_rots_.at(ires).second.size() > 0 );\n\t\t// if( res_rots_[ires].second.size() == 1 ) return 0;\n\t\tstd::uniform_int_distribution<> rand_idx(0,res_rots_.at(ires).second.size()-1);\n\t\treturn rand_idx( rng );\n\t}\n\tvoid randrot_not_current_uniform_res( int32_t & ires, int32_t & irot )\n\t{\n\t\tfor( int k = 0; k < 1000; ++k ){\n\t\t\tires = randres();\n\t\t\tif( res_rots_.at(ires).second.size() > 1 ) break;\n\t\t}\n\t\tALWAYS_ASSERT( 0 <= ires && ires < nres_ );\n\t\tALWAYS_ASSERT( res_rots_.at(ires).second.size() > 1 );\n\n\t\tfor( int k = 0; k < 1000; ++k ){\n\t\t\tirot = randrot( ires );\n\t\t\tif( irot != current_rots_.at(ires) ) return;\n\t\t}\n\t\tALWAYS_ASSERT( 0 <= irot && irot < res_rots_.at(ires).second.size() );\n\t}\n\tvoid randrot_not_current_uniform_rot( int32_t & ires, int32_t & irot )\n\t{\n\t\tstd::uniform_int_distribution<> rand_idx(0,rot_list_.size()-1);\n\t\tfor( int i = 0; i < 1000; ++i ){\n\t\t\tint const irand = rand_idx(rng);\n\t\t\tires = rot_list_.at(irand).first;\n\t\t\tirot = rot_list_.at(irand).second;\n\t\t\tif( res_rots_.at(ires).second.size() > 1 && irot != current_rots_.at(ires) ) return;\n\t\t}\n\t\tstd::cerr << \"randrot_not_current_uniform_rot FAIL\" << std::endl;\n\t\tstd::exit(-1);\n\t}\n\tvoid random_substitution_test( float temperature ){\n\t\tstd::uniform_real_distribution<float> runif(0,1);\n\n\t\tint32_t ires, irot;\n\t\trandrot_not_current_uniform_rot( ires, irot );\n\n\t\tfloat delta = compute_energy_delta( current_rots_, ires, irot );\n\t\t// {\n\t\t// \t// std::cout << \"SUB: \" << ires << \" \" << irot << \" \" << res_rots_[ires].first << std::endl;\n\t\t// \t// std::cout << \"==================================== old ==========================================\" << std::endl;\n\t\t// \t// for( int k = 0; k < current_rots_.size(); ++k ) std::cout << \"currot \" << k << \" \" << current_rots_[k] << std::endl;\n\t\t// \tfloat curfull = compute_energy_full( current_rots_ );\n\t\t// \tint32_t tmp = current_rots_[ires];\n\t\t// \tcurrent_rots_[ires] = irot;\n\t\t// \t// std::cout << \"==================================== new ==========================================\" << std::endl;\n\t\t// \t// for( int k = 0; k < current_rots_.size(); ++k ) std::cout << \"currot \" << k << \" \" << current_rots_[k] << std::endl;\n\t\t// \tfloat newfull = compute_energy_full( current_rots_ );\n\t\t// \tcurrent_rots_[ires] = tmp;\n\t\t// \tfloat test_delta = newfull-curfull;\n\t\t// \t// std::cout << delta << \" \" << test_delta << \" \" << curfull << \" \" << newfull << std::endl;\n\t\t// \tif( fabs(delta-test_delta) > 0.01 ){\n\t\t// \t\t#pragma omp critical\n\t\t// \t\tstd::cout << \"fabs(delta-test_delta) \" << fabs(delta-test_delta) << \" \" << delta << \" \" << test_delta << std::endl;\n\t\t// \t}\n\t\t// }\n\n\t\tif( pass_metropolis( temperature, delta, runif(rng) ) ){\n\t\t\tcurrent_rots_.at(ires) = irot;\n\t\t\tscore_ += delta;\n\t\t\tif( score_ < trial_best_score_ ){\n\t\t\t\ttrial_best_score_ = score_;\n\t\t\t\ttrial_best_rots_ = current_rots_;\n\t\t\t}\n\t\t}\n\t}\n\tvoid recover_trial_best(){\n\t\tscore_ = trial_best_score_;\n\t\tcurrent_rots_ = trial_best_rots_;\n\t}\n\tvoid assign_random_rots(){\n\t\tcurrent_rots_.resize( nres_ );\n\t\tfor( int ires = 0; ires < nres_; ++ires ){\n\t\t\tcurrent_rots_.at(ires) = randrot(ires);\n\t\t\t// std::cout << \"starting rot \" << ires << \" \" << current_rots_[ires] << std::endl;\n\t\t\tassert( 0 <= current_rots_.at(ires) && current_rots_.at(ires) < res_rots_.at(ires).second.size() );\n\t\t}\n\t}\n\tvoid assign_best_obe_rots(){\n\t\tcurrent_rots_.resize( nres_ );\n\t\tfor( int ilres = 0; ilres < nres_; ++ilres ){\n\t\t\tfloat best = 9e9;\n\t\t\tfor( int ilrot = 0; ilrot < res_rots_.at(ilres).second.size(); ++ilrot ){\n\t\t\t\tfloat obe = res_rots_.at(ilres).second.at(ilrot).second;\n\t\t\t\tif( obe < best ){\n\t\t\t\t\tbest = obe;\n\t\t\t\t\tcurrent_rots_.at(ilres) = ilrot;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tvoid assign_initial_rots(){\n\t\tif( opts_.init_with_best_1be_rots ){\n\t\t\tassign_best_obe_rots();\n\t\t} else {\n\t\t\tassign_random_rots();\n\t\t}\n\t}\n\tvoid fill_result_rots( std::vector<std::pair<int32_t,int32_t> > & result_rots ){\n\t\tresult_rots.clear();\n\t\tfor( int i = 0; i < nres_; ++i ){\n\t\t\tint32_t iresglobal = res_rots_.at(i).first;\n\t\t\tint32_t irottwob   = res_rots_.at(i).second.at( global_best_rots_.at(i) ).first;\n\t\t\tALWAYS_ASSERT( 0 <= iresglobal && iresglobal < twob_->sel2all_.shape()[0] );\n\t\t\tif( irottwob < 0 ){\n\t\t\t\t#ifdef USE_OPENMP\n\t\t\t\t#pragma omp critical\n\t\t\t\t#endif\n\t\t\t\t{\n\t\t\t\t\tstd::cout << \"local rot num: \" << i << \" iresglobal: \" << iresglobal << \" irottwob: \" << irottwob << std::endl;\n\t\t\t\t\tprint_rot_info();\n\t\t\t\t\tstd::cerr << \"debug....\" << std::endl;\n\t\t\t\t\tstd::exit(-1);\n\t\t\t\t}\n\t\t\t}\n\t\t\tALWAYS_ASSERT( 0 <= irottwob   && irottwob   < twob_->sel2all_.shape()[1] );\n\t\t\tint32_t irotglobal = twob_->sel2all_[ iresglobal ][ irottwob ];\n\t\t\tresult_rots.push_back( std::make_pair( iresglobal, irotglobal ) );\n\t\t}\n\t}\n\tfloat pack( std::vector<std::pair<int32_t,int32_t> > & result_rots )\n\t{\n\t\tassert( res_rots_.size() >= nres_ );\n\t\tfor( int i = 0; i < nres_; ++i ){\n\t\t\t//std::cout << i << \" \" << res_rots_[i].second.size() << std::endl;\n\t\t\tassert( res_rots_.at(i).second.size() > 0 );\n\t\t}\n\n\t\tassign_initial_rots();\n\n\t\tuint64_t nchoices = 1;\n\t\tfor( int ires = 0; ires < nres_; ++ires ){\n\t\t\tALWAYS_ASSERT_MSG( res_rots_.at(ires).second.size() > 0, \"no rotamers at designable position!\" );\n\t\t\tnchoices *= res_rots_.at(ires).second.size();\n\t\t\tif( nchoices > 1000000000000000ull ) break;\n\t\t}\n\t\tif( nchoices == 1 ){\n            global_best_rots_ = current_rots_;\n\t\t\tfill_result_rots( result_rots );\n\t\t\tscore_ = compute_energy_full( current_rots_ );\n\t\t\treturn score_;\n\t\t}\n\n\t\tint const ntrials = opts_.pack_n_iters;\n\t\tint const pack_iters = opts_.pack_iter_mult * rot_list_.size()+10;\n\t\tglobal_best_score_ = 9e9;\n\t\tfor( int k = 0; k < ntrials; ++k ){\n\t\t\tif( k > 0 ) assign_initial_rots();\n\t\t\tscore_ = compute_energy_full( current_rots_ );\n\t\t\ttrial_best_score_ = score_;\n\t\t\ttrial_best_rots_ = current_rots_;\n\t\t\tfor( int i = 0; i < pack_iters; ++i ) random_substitution_test( 100.0  ); recover_trial_best();\n\t\t\tfor( int i = 0; i < pack_iters; ++i ) random_substitution_test(  33.0  ); recover_trial_best();\n\t\t\tfor( int i = 0; i < pack_iters; ++i ) random_substitution_test(  10.0  ); recover_trial_best();\n\t\t\tfor( int i = 0; i < pack_iters; ++i ) random_substitution_test(   3.3  ); recover_trial_best();\n\t\t\tfor( int i = 0; i < pack_iters; ++i ) random_substitution_test(   1.0  ); recover_trial_best();\n\t\t\tfor( int i = 0; i < pack_iters; ++i ) random_substitution_test(   0.33 ); recover_trial_best();\n\t\t\tfor( int i = 0; i < pack_iters; ++i ) random_substitution_test(   0.1  ); recover_trial_best();\n\t\t\tfor( int i = 0; i < pack_iters; ++i ) random_substitution_test(   0.0  ); recover_trial_best();\n\t\t\tif( score_ < global_best_score_ ){\n\t\t\t\tglobal_best_score_ = score_;\n\t\t\t\tglobal_best_rots_ = current_rots_;\n\t\t\t}\n\t\t}\n\n\t\tfill_result_rots( result_rots );\n\n\t\treturn score_;\n\t}\n\n\tvoid print_rot_info() const {\n\t\t// using namespace ObjexxFCL::format;\n\n\t\tstd::cout << \"====== res_rots_ =======\" << std::endl;\n\t\tfor( int ilres = 0; ilres < this->nres_; ++ilres ){\n\t\t\tint ires = this->res_rots_[ilres].first;\n\t\t\t// std::cout << I(3,ilres) << \" res \" << I(3,ires);\n\t\t\tstd::cout << ilres << \" res \" << ires;\n\t\t\tBOOST_FOREACH( typename HackPack::RotInfo const & rinfo, this->res_rots_[ilres].second ){\n\t\t\t\tstd::cout << \" \" << rinfo.first << \"/\" << rinfo.second;\n\t\t\t}\n\t\t\tstd::cout << std::endl;\n\t\t}\n\t\tstd::cout << \"====== rot_list_ =======\" << std::endl;\n\t\tfor( int k = 0; k < this->rot_list_.size(); ++k ){\n\t\t\tint32_t ilres = this->rot_list_[k].first;\n\t\t\tint32_t ilrot = this->rot_list_[k].second;\n\t\t\t// std::cout << I(3,k) << \" res: \" << I(2,ilres) << \"/\" << I(3,this->res_rots_[ilres].first)\n\t\t\t//           << \" rot: \" << I(2,ilrot) << \"/\" << I(3,this->res_rots_[ilres].second[ilrot].first)\n\t\t\t//           << \" score: \" << this->res_rots_[ilres].second[ilrot].second << std::endl;\n\t\t\tstd::cout << k << \" res: \" << ilres << \"/\" << this->res_rots_[ilres].first\n\t\t\t          << \" rot: \" << ilrot << \"/\" << this->res_rots_[ilres].second[ilrot].first\n\t\t\t          << \" score: \" << this->res_rots_[ilres].second[ilrot].second << std::endl;\n\t\t}\n\t}\n};\n\n\n\n} // namespace search\n} // namespace scheme\n\n\n#endif\n", "meta": {"hexsha": "881dd29c20ebd75dc67788d3012a6eeb0ff13e46", "size": 18920, "ext": "hh", "lang": "C++", "max_stars_repo_path": "schemelib/scheme/search/HackPack.hh", "max_stars_repo_name": "YaoYinYing/rifdock", "max_stars_repo_head_hexsha": "cbde6bbeefd29a066273bdf2937cf36b0d2e6335", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 25.0, "max_stars_repo_stars_event_min_datetime": "2019-07-23T01:03:48.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T04:16:08.000Z", "max_issues_repo_path": "schemelib/scheme/search/HackPack.hh", "max_issues_repo_name": "YaoYinYing/rifdock", "max_issues_repo_head_hexsha": "cbde6bbeefd29a066273bdf2937cf36b0d2e6335", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 13.0, "max_issues_repo_issues_event_min_datetime": "2018-01-30T17:45:57.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-28T11:02:44.000Z", "max_forks_repo_path": "schemelib/scheme/search/HackPack.hh", "max_forks_repo_name": "YaoYinYing/rifdock", "max_forks_repo_head_hexsha": "cbde6bbeefd29a066273bdf2937cf36b0d2e6335", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 14.0, "max_forks_repo_forks_event_min_datetime": "2018-02-08T01:42:28.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T12:56:17.000Z", "avg_line_length": 38.7704918033, "max_line_length": 133, "alphanum_fraction": 0.6265856237, "num_tokens": 6374, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7154240079185319, "lm_q2_score": 0.44939263446475963, "lm_q1q2_score": 0.3215062796778461}}
{"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) 2017 Adam Wulkiewicz, Lodz, Poland.\n\n// This file was modified by Oracle on 2017-2021.\n// Modifications copyright (c) 2017-2021 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_AREA_HPP\n#define BOOST_GEOMETRY_ALGORITHMS_AREA_HPP\n\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/core/closure.hpp>\n#include <boost/geometry/core/exterior_ring.hpp>\n#include <boost/geometry/core/interior_rings.hpp>\n#include <boost/geometry/core/point_order.hpp>\n#include <boost/geometry/core/point_type.hpp>\n#include <boost/geometry/core/ring_type.hpp>\n#include <boost/geometry/core/tags.hpp>\n#include <boost/geometry/core/visit.hpp>\n\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/algorithms/detail/multi_sum.hpp>\n#include <boost/geometry/algorithms/detail/visit.hpp>\n\n#include <boost/geometry/algorithms/area_result.hpp>\n#include <boost/geometry/algorithms/default_area_result.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/area/services.hpp>\n#include <boost/geometry/strategies/area/cartesian.hpp>\n#include <boost/geometry/strategies/area/geographic.hpp>\n#include <boost/geometry/strategies/area/spherical.hpp>\n#include <boost/geometry/strategies/concepts/area_concept.hpp>\n#include <boost/geometry/strategies/default_strategy.hpp>\n\n#include <boost/geometry/util/math.hpp>\n\n#include <boost/geometry/views/detail/closed_clockwise_view.hpp>\n\n\nnamespace boost { namespace geometry\n{\n\n\n#ifndef DOXYGEN_NO_DETAIL\nnamespace detail { namespace area\n{\n\nstruct box_area\n{\n    template <typename Box, typename Strategies>\n    static inline typename coordinate_type<Box>::type\n    apply(Box const& box, Strategies const& strategies)\n    {\n        // Currently only works for 2D Cartesian boxes\n        assert_dimension<Box, 2>();\n\n        return strategies.area(box).apply(box);\n    }\n};\n\n\nstruct ring_area\n{\n    template <typename Ring, typename Strategies>\n    static inline typename area_result<Ring, Strategies>::type\n    apply(Ring const& ring, Strategies const& strategies)\n    {\n        using strategy_type = decltype(strategies.area(ring));\n\n        BOOST_CONCEPT_ASSERT( (geometry::concepts::AreaStrategy<Ring, strategy_type>) );\n        assert_dimension<Ring, 2>();\n\n        // Ignore warning (because using static method sometimes) on strategy\n        boost::ignore_unused(strategies);\n\n        // An open ring has at least three points,\n        // A closed ring has at least four points,\n        // if not, there is no (zero) area\n        if (boost::size(ring) < detail::minimum_ring_size<Ring>::value)\n        {\n            return typename area_result<Ring, Strategies>::type();\n        }\n\n        detail::closed_clockwise_view<Ring const> const view(ring);\n        auto it = boost::begin(view);\n        auto const end = boost::end(view);\n\n        strategy_type const strategy = strategies.area(ring);\n        typename strategy_type::template state<Ring> state;        \n\n        for (auto previous = it++; it != end; ++previous, ++it)\n        {\n            strategy.apply(*previous, *it, state);\n        }\n\n        return strategy.result(state);\n    }\n};\n\n\n}} // namespace detail::area\n\n\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 area : detail::calculate_null\n{\n    template <typename Strategy>\n    static inline typename area_result<Geometry, Strategy>::type\n        apply(Geometry const& geometry, Strategy const& strategy)\n    {\n        return calculate_null::apply\n            <\n                typename area_result<Geometry, Strategy>::type\n            >(geometry, strategy);\n    }\n};\n\n\ntemplate <typename Geometry>\nstruct area<Geometry, box_tag> : detail::area::box_area\n{};\n\n\ntemplate <typename Ring>\nstruct area<Ring, ring_tag>\n    : detail::area::ring_area\n{};\n\n\ntemplate <typename Polygon>\nstruct area<Polygon, polygon_tag> : detail::calculate_polygon_sum\n{\n    template <typename Strategy>\n    static inline typename area_result<Polygon, Strategy>::type\n        apply(Polygon const& polygon, Strategy const& strategy)\n    {\n        return calculate_polygon_sum::apply\n            <\n                typename area_result<Polygon, Strategy>::type,\n                detail::area::ring_area\n            >(polygon, strategy);\n    }\n};\n\n\ntemplate <typename MultiGeometry>\nstruct area<MultiGeometry, multi_polygon_tag> : detail::multi_sum\n{\n    template <typename Strategy>\n    static inline typename area_result<MultiGeometry, Strategy>::type\n    apply(MultiGeometry const& multi, Strategy const& strategy)\n    {\n        return multi_sum::apply\n               <\n                   typename area_result<MultiGeometry, Strategy>::type,\n                   area<typename boost::range_value<MultiGeometry>::type>\n               >(multi, strategy);\n    }\n};\n\n\n} // namespace dispatch\n#endif // DOXYGEN_NO_DISPATCH\n\n\nnamespace resolve_strategy\n{\n\ntemplate\n<\n    typename Strategy,\n    bool IsUmbrella = strategies::detail::is_umbrella_strategy<Strategy>::value\n>\nstruct area\n{\n    template <typename Geometry>\n    static inline typename area_result<Geometry, Strategy>::type\n    apply(Geometry const& geometry, Strategy const& strategy)\n    {\n        return dispatch::area<Geometry>::apply(geometry, strategy);\n    }\n};\n\ntemplate <typename Strategy>\nstruct area<Strategy, false>\n{\n    template <typename Geometry>\n    static auto apply(Geometry const& geometry, Strategy const& strategy)\n    {\n        using strategies::area::services::strategy_converter;\n        return dispatch::area\n            <\n                Geometry\n            >::apply(geometry, strategy_converter<Strategy>::get(strategy));\n    }\n};\n\ntemplate <>\nstruct area<default_strategy, false>\n{\n    template <typename Geometry>\n    static inline typename area_result<Geometry>::type\n    apply(Geometry const& geometry, default_strategy)\n    {\n        typedef typename strategies::area::services::default_strategy\n            <\n                Geometry\n            >::type strategy_type;\n\n        return dispatch::area<Geometry>::apply(geometry, strategy_type());\n    }\n};\n\n\n} // namespace resolve_strategy\n\n\nnamespace resolve_dynamic\n{\n\ntemplate <typename Geometry, typename Tag = typename geometry::tag<Geometry>::type>\nstruct area\n{\n    template <typename Strategy>\n    static inline typename area_result<Geometry, Strategy>::type\n        apply(Geometry const& geometry, Strategy const& strategy)\n    {\n        return resolve_strategy::area<Strategy>::apply(geometry, strategy);\n    }\n};\n\ntemplate <typename Geometry>\nstruct area<Geometry, dynamic_geometry_tag>\n{\n    template <typename Strategy>\n    static inline typename area_result<Geometry, Strategy>::type\n        apply(Geometry const& geometry, Strategy const& strategy)\n    {\n        typename area_result<Geometry, Strategy>::type result = 0;\n        traits::visit<Geometry>::apply([&](auto const& g)\n        {\n            result = area<util::remove_cref_t<decltype(g)>>::apply(g, strategy);\n        }, geometry);\n        return result;\n    }\n};\n\ntemplate <typename Geometry>\nstruct area<Geometry, geometry_collection_tag>\n{\n    template <typename Strategy>\n    static inline typename area_result<Geometry, Strategy>::type\n        apply(Geometry const& geometry, Strategy const& strategy)\n    {\n        typename area_result<Geometry, Strategy>::type result = 0;\n        detail::visit_breadth_first([&](auto const& g)\n        {\n            result += area<util::remove_cref_t<decltype(g)>>::apply(g, strategy);\n            return true;\n        }, geometry);\n        return result;\n    }\n};\n\n} // namespace resolve_dynamic\n\n\n/*!\n\\brief \\brief_calc{area}\n\\ingroup area\n\\details \\details_calc{area}. \\details_default_strategy\n\nThe area algorithm calculates the surface area of all geometries having a surface, namely\nbox, polygon, ring, multipolygon. The units are the square of the units used for the points\ndefining the surface. If subject geometry is defined in meters, then area is calculated\nin square meters.\n\nThe area calculation can be done in all three common coordinate systems, Cartesian, Spherical\nand Geographic as well.\n\n\\tparam Geometry \\tparam_geometry\n\\param geometry \\param_geometry\n\\return \\return_calc{area}\n\n\\qbk{[include reference/algorithms/area.qbk]}\n\\qbk{[heading Examples]}\n\\qbk{[area] [area_output]}\n*/\ntemplate <typename Geometry>\ninline typename area_result<Geometry>::type\narea(Geometry const& geometry)\n{\n    concepts::check<Geometry const>();\n\n    // detail::throw_on_empty_input(geometry);\n\n    return resolve_dynamic::area<Geometry>::apply(geometry, default_strategy());\n}\n\n/*!\n\\brief \\brief_calc{area} \\brief_strategy\n\\ingroup area\n\\details \\details_calc{area} \\brief_strategy. \\details_strategy_reasons\n\\tparam Geometry \\tparam_geometry\n\\tparam Strategy \\tparam_strategy{Area}\n\\param geometry \\param_geometry\n\\param strategy \\param_strategy{area}\n\\return \\return_calc{area}\n\n\\qbk{distinguish,with strategy}\n\n\\qbk{\n[include reference/algorithms/area.qbk]\n\n[heading Available Strategies]\n\\* [link geometry.reference.strategies.strategy_area_cartesian Cartesian]\n\\* [link geometry.reference.strategies.strategy_area_spherical Spherical]\n\\* [link geometry.reference.strategies.strategy_area_geographic Geographic]\n\n[heading Example]\n[area_with_strategy]\n[area_with_strategy_output]\n}\n */\ntemplate <typename Geometry, typename Strategy>\ninline typename area_result<Geometry, Strategy>::type\narea(Geometry const& geometry, Strategy const& strategy)\n{\n    concepts::check<Geometry const>();\n\n    // detail::throw_on_empty_input(geometry);\n\n    return resolve_dynamic::area<Geometry>::apply(geometry, strategy);\n}\n\n\n}} // namespace boost::geometry\n\n\n#endif // BOOST_GEOMETRY_ALGORITHMS_AREA_HPP\n", "meta": {"hexsha": "4b4a0bb9c339026955546e29c4ff52494f2b0935", "size": 10811, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "lib/boost_1.78.0/boost/geometry/algorithms/area.hpp", "max_stars_repo_name": "LaudateCorpus1/math", "max_stars_repo_head_hexsha": "990a66b3cccd27a5fd48626360bb91093a48278b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 326.0, "max_stars_repo_stars_event_min_datetime": "2015-02-08T13:47:49.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-16T02:13:59.000Z", "max_issues_repo_path": "lib/boost_1.78.0/boost/geometry/algorithms/area.hpp", "max_issues_repo_name": "LaudateCorpus1/math", "max_issues_repo_head_hexsha": "990a66b3cccd27a5fd48626360bb91093a48278b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 623.0, "max_issues_repo_issues_event_min_datetime": "2015-01-02T23:45:23.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-09T11:15:23.000Z", "max_forks_repo_path": "lib/boost_1.78.0/boost/geometry/algorithms/area.hpp", "max_forks_repo_name": "LaudateCorpus1/math", "max_forks_repo_head_hexsha": "990a66b3cccd27a5fd48626360bb91093a48278b", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 215.0, "max_forks_repo_forks_event_min_datetime": "2015-01-14T15:50:38.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-23T03:58:36.000Z", "avg_line_length": 28.9839142091, "max_line_length": 93, "alphanum_fraction": 0.7149199889, "num_tokens": 2389, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7154239957834733, "lm_q2_score": 0.44939263446475963, "lm_q1q2_score": 0.3215062742244401}}
{"text": "#include \"mesh_generator.h\"\n\n#include <fstream>\n#include <climits>\n\n#include <deal.II/grid/tria.h>\n#include <deal.II/grid/manifold_lib.h>\n#include <deal.II/grid/grid_generator.h>\n#include <deal.II/grid/grid_tools.h>\n#include <deal.II/grid/tria_accessor.h>\n#include <deal.II/grid/tria_iterator.h>\n#include <deal.II/grid/grid_in.h>\n\n// note that prm here cannot be const because InitializeRelativePositionToIDMap\n// invokes dealii::ParameterHandler::enter_subsection not marked const\ntemplate <int dim>\nMeshGenerator<dim>::MeshGenerator (dealii::ParameterHandler &prm)\n    : is_mesh_generated_(prm.get_bool(\"is mesh generated by deal.II\")),\n      have_reflective_bc_(prm.get_bool(\"have reflective boundary\")),\n      global_refinements_(prm.get_integer(\"uniform refinements\")) {\n  if (!is_mesh_generated_) {\n    mesh_filename_ = prm.get (\"mesh file name\");\n  } else {\n    is_mesh_pin_resolved_ = prm.get_bool (\"is mesh pin-resolved\");\n    if (is_mesh_pin_resolved_) {\n      rod_radius_ = prm.get_double (\"fuel rod radius\");\n      rod_type_ = prm.get (\"fuel rod triangulation type\");\n    }\n    ProcessCoordinateInformation (prm);\n    InitializeRelativePositionToIDMap (prm);\n    PreprocessReflectiveBC (prm);\n  }\n}\n\ntemplate <int dim>\nMeshGenerator<dim>::~MeshGenerator () {}\n\ntemplate <int dim>\nvoid MeshGenerator<dim>::MakeGrid (dealii::Triangulation<dim> &tria) {\n  if (is_mesh_generated_) {\n    GenerateInitialGrid (tria);\n    InitializeMaterialID (tria);\n    SetupBoundaryIDs (tria);\n    if (global_refinements_>0)\n      GlobalRefine (tria);\n  } else {\n    dealii::GridIn<dim> gi;\n    gi.attach_triangulation (tria);\n    std::ifstream f(mesh_filename_);\n    gi.read_msh (f);\n  }\n}\n\ntemplate <int dim>\nvoid MeshGenerator<dim>::FuelRod2D (dealii::Triangulation<2> &tria,\n    const dealii::Point<2> &p) {\n  double r = (rod_type_==\"simple\") ? rod_radius_ : (0.6*rod_radius_);\n  const double a=1. / (std::sqrt(2.0)) * r;\n  std::vector<dealii::Point<2>> v={\n      p + dealii::Point<2>(0, 0)*r,\n      p + dealii::Point<2>(0, 1)*r,\n      p + dealii::Point<2>(1, 1)*a,\n      p + dealii::Point<2>(1, 0)*r,\n      p + dealii::Point<2>(1, -1)*a,\n      p + dealii::Point<2>(0, -1)*r,\n      p + dealii::Point<2>(-1, -1)*a,\n      p + dealii::Point<2>(-1, 0)*r,\n      p + dealii::Point<2>(-1, 1)*a\n  };\n  // vertices per cell for the circle\n  std::vector<std::vector<dealii::Point<2>>> ps={\n      {v[8], v[0], v[1], v[2]},\n      {v[0], v[4], v[2], v[3]},\n      {v[6], v[5], v[0], v[4]},\n      {v[7], v[6], v[8], v[0]}\n  };\n  // generate a quater of the circle\n  dealii::GridGenerator::general_cell(tria, ps[0]);\n  // generate the rest of the circle\n  for (int i=1; i<4; ++i) {\n    dealii::Triangulation<2> t;\n    dealii::GridGenerator::general_cell (t, ps[i]);\n    dealii::GridGenerator::merge_triangulations (tria, t, tria);\n  }\n\n  // for composite type rod, a ring should be generated outside the inner circle\n  if (rod_type_==\"composite\") {\n    dealii::Triangulation<2> t;\n    dealii::GridGenerator::hyper_shell (t, p, r, rod_radius_, 8);\n    dealii::GridGenerator::merge_triangulations (tria, t, tria);\n  }\n}\n\ntemplate <int dim>\nvoid MeshGenerator<dim>::FuelPin2DGrid (dealii::Triangulation<2> &tria,\n    const dealii::Point<2> &center_xy) {\n  // generate a fuel rod at origin\n  FuelRod2D (tria, dealii::Point<2>());\n\n  // generate the rest part of a 2D pin\n  dealii::Triangulation<2> tria_moderator;\n  dealii::GridGenerator::hyper_cube_with_cylindrical_hole (tria_moderator,\n      rod_radius_, 0.5*cell_size_all_dir_[0]);\n\n\n  // merge these two parts to get a pin\n  dealii::GridGenerator::merge_triangulations (tria, tria_moderator, tria);\n\n  // shift the triangulation to the desired center\n  dealii::GridTools::shift (dealii::Tensor<1,2>(center_xy), tria);\n}\n\ntemplate <int dim>\nvoid MeshGenerator<dim>::NonFuelPin2DGrid (dealii::Triangulation<2> &tria,\n    const dealii::Point<2> &center_xy) {\n  // generate 4 squares around origin with same side length of rod_radius_\n  // diags are the lower_left-upper_right diagonal points of squares\n  double r = 0.5 * cell_size_all_dir_[0];\n  std::vector<std::pair<dealii::Point<2>, dealii::Point<2>>> diags = {\n      {dealii::Point<2>(-r, 0), dealii::Point<2>(0, r)},\n      {dealii::Point<2>(0,0), dealii::Point<2>(r,r)},\n      {dealii::Point<2>(-r, -r), dealii::Point<2>(0, 0)},\n      {dealii::Point<2>(0,-r), dealii::Point<2>(r,0)}\n  };\n  // generate the first subcell\n  dealii::GridGenerator::hyper_rectangle (tria,\n      diags[0].first, diags[0].second);\n  // generate the rest and merge together\n  for (int i=1; i<4; ++i) {\n    dealii::Triangulation<2> t;\n    dealii::GridGenerator::hyper_rectangle (t, diags[i].first, diags[i].second);\n    dealii::GridGenerator::merge_triangulations (tria, t, tria);\n  }\n\n  // shift the triangulation to the destination\n  dealii::GridTools::shift (center_xy, tria);\n}\n\ntemplate <>\nvoid MeshGenerator<1>::GenerateInitialUnstructGrid (\n    dealii::Triangulation<1> &) {}\n\ntemplate <>\nvoid MeshGenerator<2>::GenerateInitialUnstructGrid (\n    dealii::Triangulation<2> &tria) {\n  // generate two basic pin models at lower left corner of the x-y plane\n  dealii::Triangulation<2> t_fuel, t_moderator;\n  double length = cell_size_all_dir_[0];\n  FuelPin2DGrid (t_fuel, dealii::Point<2>(0.5*length, 0.5*length));\n  NonFuelPin2DGrid (t_moderator, dealii::Point<2>(0.5*length, 0.5*length));\n\n  // create a local triangulation and modify it for the first time\n  dealii::Triangulation<2> t_loc;\n\n  // modify the rest of the domain\n  for (int ix=0; ix<ncell_per_dir_[0]; ++ix)\n    for (int iy=0; iy<ncell_per_dir_[1]; ++iy) {\n      std::vector<int> rel_pos = {ix, iy};\n      auto fuel_id = relative_position_to_fuel_id_[rel_pos];\n      // the first cell\n      if (ix==0 && iy==0) {\n        if (fuel_id<0)\n          t_loc.copy_triangulation (t_moderator);\n        else\n          t_loc.copy_triangulation (t_fuel);\n      } else {\n        dealii::Triangulation<2> t_tmp;\n        if (fuel_id<0)\n          t_tmp.copy_triangulation (t_moderator);\n        else\n          t_tmp.copy_triangulation (t_fuel);\n\n        dealii::GridTools::shift (\n            dealii::Tensor<1, 2>(dealii::Point<2>(ix*length, iy*length)), t_tmp);\n        dealii::GridGenerator::merge_triangulations (t_loc, t_tmp, t_loc);\n      }\n    }\n  tria.copy_triangulation (t_loc);\n}\n\ntemplate <>\nvoid MeshGenerator<3>::GenerateInitialUnstructGrid (\n    dealii::Triangulation<3> &tria) {\n  // generate two basic pin models at lower left corner of the x-y plane\n  dealii::Triangulation<2> t_fuel, t_moderator;\n  double length = cell_size_all_dir_[0];\n  FuelPin2DGrid (t_fuel, dealii::Point<2>(0.5*length, 0.5*length));\n  NonFuelPin2DGrid (t_moderator, dealii::Point<2>(0.5*length, 0.5*length));\n\n  // create a local triangulation and modify it for the first time\n  dealii::Triangulation<2> t_loc;\n  // modify the rest of the domain\n  for (int ix=0; ix<ncell_per_dir_[0]; ++ix) {\n    for (int iy=0; iy<ncell_per_dir_[1]; ++iy) {\n      int fuel_id = -1;\n      for (int iz=0; iz<ncell_per_dir_[2]; ++iz) {\n        std::vector<int> rel_pos = {ix, iy, iz};\n        if (relative_position_to_fuel_id_[rel_pos]>=0) {\n          fuel_id = 1;\n          curved_blocks.insert(std::vector<int>{ix, iy});\n          break;\n        }\n      }\n      // the first cell\n      if (ix==0 && iy==0) {\n        if (fuel_id<0)\n          t_loc.copy_triangulation (t_moderator);\n        else\n          t_loc.copy_triangulation (t_fuel);\n      } else {\n        dealii::Triangulation<2> t_tmp;\n        if (fuel_id<0)\n          t_tmp.copy_triangulation (t_moderator);\n        else\n          t_tmp.copy_triangulation (t_fuel);\n\n        dealii::GridTools::shift (\n            dealii::Tensor<1, 2>(dealii::Point<2>(ix*length, iy*length)), t_tmp);\n        dealii::GridGenerator::merge_triangulations (t_loc, t_tmp, t_loc);\n      }\n    }\n  }\n  // extrude 2d to 3d\n  dealii::Triangulation<3> t_3d;\n  dealii::GridGenerator::extrude_triangulation (\n      t_loc, ncell_per_dir_[2]+1, axis_max_values_[2], t_3d);\n  tria.copy_triangulation (t_3d);\n}\n\ntemplate <int dim>\nvoid MeshGenerator<dim>::GenerateInitialGrid (dealii::Triangulation<dim> &tria) {\n  if (is_mesh_pin_resolved_) {\n    AssertThrow(dim>1,\n        dealii::ExcMessage(\"unstructured mesh is only valid for multi-D\"))\n    GenerateInitialUnstructGrid (tria);\n  } else {\n  // Note that this function is only suitable to\n  // generate a hyper rectangle, which is a line\n  // in 1D, a rectangle in 2D and a rectangular\n  // cuboid in 3D\n\n  // Construction of such a rectangle requires\n  dealii::Point<dim> origin;\n  dealii::Point<dim> diagonal;\n  switch (dim) {\n    case 1: {\n      diagonal[0] = axis_max_values_[0];\n      break;\n    }\n\n    case 2: {\n      diagonal[0] = axis_max_values_[0];\n      diagonal[1] = axis_max_values_[1];\n      break;\n    }\n\n    case 3: {\n      diagonal[0] = axis_max_values_[0];\n      diagonal[1] = axis_max_values_[1];\n      diagonal[2] = axis_max_values_[2];\n      break;\n    }\n\n    default:\n      break;\n  }\n  std::vector<unsigned int> tmp(ncell_per_dir_.begin(), ncell_per_dir_.end());\n  dealii::GridGenerator::subdivided_hyper_rectangle (tria, tmp,\n      origin, diagonal);\n  }\n}\n\ntemplate <int dim>\nvoid MeshGenerator<dim>::InitializeMaterialID (\n    dealii::Triangulation<dim> &tria) {\n  AssertThrow (is_mesh_generated_==true,\n      dealii::ExcMessage(\"mesh read in have to have boundary ids associated\"));\n  for (typename dealii::Triangulation<dim>::active_cell_iterator\n       cell=tria.begin_active(); cell!=tria.end(); ++cell)\n    if (cell->is_locally_owned()) {\n      dealii::Point<dim> center(cell->center());\n      std::vector<int> relative_position;\n      GetCellRelativePosition(center, relative_position);\n      int material_id = relative_position_to_id_[relative_position];\n\n      if (is_mesh_pin_resolved_) {\n        AssertThrow(dim>1,\n            dealii::ExcMessage(\"unstructured mesh is not supported in 1D\"));\n        int fuel_id = relative_position_to_fuel_id_[relative_position];\n        if (fuel_id<0) {\n          // if it's not fuel pin, set material id\n          cell->set_material_id(material_id);\n        } else {\n          AssertThrow (material_id!=fuel_id,\n              dealii::ExcMessage(\"fuel rod must have different id than moderator\"));\n          // get pin center on xy plane\n          double ctr_x, ctr_y;\n          ctr_x = (0.5+relative_position[0])*cell_size_all_dir_[0];\n          ctr_y = (0.5+relative_position[1])*cell_size_all_dir_[1];\n          dealii::Point<dim> pin_center;\n          pin_center[0]=ctr_x, pin_center[1]=ctr_y;\n          if (dim==3) pin_center[2] = center[2];\n\n          if (center.distance(pin_center)<rod_radius_) {\n            // within pin, set id to fuel id\n            cell->set_material_id(fuel_id);\n          } else {\n            // outside pin, set id to material id\n            cell->set_material_id(material_id);\n          }\n        }\n      } else {\n        // structured mesh, directly set id\n        cell->set_material_id (material_id);\n      }\n    }\n}\n\ntemplate <int dim>\nvoid MeshGenerator<dim>::GetCellRelativePosition (\n    const dealii::Point<dim> &center,\n    std::vector<int> &relative_position) {\n  if (dim>=1) {\n    relative_position.push_back(\n        static_cast<int> (center[0] / cell_size_all_dir_[0]));\n    if (dim>=2) {\n      relative_position.push_back(\n          static_cast<int> (center[1] / cell_size_all_dir_[1]));\n      if (dim==3)\n        relative_position.push_back(\n            static_cast<int> (center[2] / cell_size_all_dir_[2]));\n    }\n  }\n}\n\ntemplate <int dim>\nvoid MeshGenerator<dim>::SetupBoundaryIDs\n(dealii::Triangulation<dim> &tria)\n{\n  AssertThrow (is_mesh_generated_==true,\n      dealii::ExcMessage(\"mesh read in have to have boundary ids associated\"));\n  AssertThrow (axis_max_values_.size()==dim,\n      dealii::ExcMessage(\"number of entries axis max values should be dimension\"));\n\n  for (typename dealii::Triangulation<dim>::active_cell_iterator\n       cell=tria.begin_active(); cell!=tria.end(); ++cell)\n    if (cell->is_locally_owned())\n      for (unsigned int fn=0;\n           fn<dealii::GeometryInfo<dim>::faces_per_cell; ++fn)\n        if (cell->at_boundary(fn)) {\n          dealii::Point<dim> ct = cell->face(fn)->center();\n          // x-axis boundaries\n          if (std::fabs(ct[0])<1.0e-14)\n            cell->face(fn)->set_boundary_id (0);\n          else if (std::fabs(ct[0]-axis_max_values_[0])<1.0e-14)\n            cell->face(fn)->set_boundary_id (1);\n\n          // 2D and 3D boundaries\n          if (dim>1) {\n            // y-axis boundaries\n            if (std::fabs(ct[1])<1.0e-14)\n              cell->face(fn)->set_boundary_id (2);\n            else if (std::fabs(ct[1]-axis_max_values_[1])<1.0e-14)\n              cell->face(fn)->set_boundary_id (3);\n\n            // z-axis boundaries for 3D only\n            if (dim==3) {\n              if (std::fabs(ct[2])<1.0e-14)\n                cell->face(fn)->set_boundary_id (4);\n              else if (std::fabs(ct[2]-axis_max_values_[2])<1.0e-14)\n                cell->face(fn)->set_boundary_id (5);\n            }\n          }\n        }\n}\n\ntemplate <int dim>\nvoid MeshGenerator<dim>::ProcessCoordinateInformation (\n    const dealii::ParameterHandler &prm) {\n  // max values for all axis\n  std::vector<std::string> strings = dealii::Utilities::split_string_list (\n      prm.get (\"x, y, z max values of boundary locations\"));\n  AssertThrow (strings.size()>=dim,\n      dealii::ExcMessage(\"Number of axis max values must be no less than dimension\"));\n  for (int i=0; i<dim; ++i)\n    axis_max_values_.push_back (std::atof (strings[i].c_str()));\n\n  // read in number of cells and get cell sizes along axes\n  strings = dealii::Utilities::split_string_list (\n      prm.get (\"number of cells for x, y, z directions\"));\n  AssertThrow (strings.size()>=dim,\n               dealii::ExcMessage (\"Entries for numbers of cells must be no less than dimension\"));\n  std::vector<int> cells_per_dir;\n  std::vector<std::vector<double> > spacings;\n  for (int d=0; d<dim; ++d)\n  {\n    ncell_per_dir_.push_back (std::atoi (strings[d].c_str ()));\n    cell_size_all_dir_.push_back (axis_max_values_[d]/ncell_per_dir_[d]);\n  }\n}\n\ntemplate <int dim>\nvoid MeshGenerator<dim>::PreprocessReflectiveBC (\n    const dealii::ParameterHandler &prm) {\n  if (have_reflective_bc_) {\n    std::map<std::string, int> bd_names_to_id {{\"xmin\",0}, {\"xmax\",1},\n        {\"ymin\",2}, {\"ymax\",3}, {\"zmin\",4}, {\"zmax\",5}};\n    std::vector<std::string> strings = dealii::Utilities::split_string_list (\n        prm.get (\"reflective boundary names\"));\n    AssertThrow (strings.size()>0,\n        dealii::ExcMessage(\"reflective boundary names have to be entered\"));\n    std::set<int> tmp;\n    for (unsigned int i=0; i<strings.size (); ++i) {\n      AssertThrow(bd_names_to_id.find(strings[i])!=bd_names_to_id.end(),\n          dealii::ExcMessage(\"Invalid reflective boundary name: use xmin, xmax, etc.\"));\n      tmp.insert (bd_names_to_id[strings[i]]);\n    }\n    auto it = tmp.begin ();\n    std::ostringstream os;\n    os << \"No valid reflective boundary name for \" << dim << \"D\";\n    AssertThrow(*it<2*dim,\n                dealii::ExcMessage(os.str()));\n    for (int i=0; i<2*dim; ++i) {\n      if (tmp.count (i))\n        is_reflective_bc_[i] = true;\n      else\n        is_reflective_bc_[i] = false;\n    }\n  }\n}\n\ntemplate <int dim>\nvoid MeshGenerator<dim>::InitializeRelativePositionToIDMap (\n    dealii::ParameterHandler &prm) {\n  prm.enter_subsection (\"material ID map\");\n  {\n    int ncell_z = dim==3?ncell_per_dir_[2]:1;\n    int ncell_y = dim>=2?ncell_per_dir_[1]:1;\n    int ncell_x = ncell_per_dir_[0];\n    std::string id_fname = prm.get (\"material id file name\");\n    std::ifstream in (id_fname);\n    std::string line;\n    int ct = 0;\n    if (in.is_open ()) {\n      while (std::getline (in, line)) {\n        int y = ct % ncell_y;\n        int z = ct / ncell_y;\n        std::vector<std::string> strings =\n            dealii::Utilities::split_string_list (line, ' ');\n        AssertThrow (static_cast<int>(strings.size()) == ncell_x,\n            dealii::ExcMessage(\"Entries of material ID per row must be ncell_x\"));\n        for (int x=0; x<ncell_x; ++x) {\n          std::vector<int> tmp = {x};\n          if (dim>1) tmp.push_back (y);\n          if (dim>2) tmp.push_back (z);\n          relative_position_to_id_[tmp] = std::atoi (strings[x].c_str());\n        }\n        ct += 1;\n      }\n      AssertThrow (ct==ncell_y*ncell_z,\n          dealii::ExcMessage(\"Number of y, z ID entries are not correct\"));\n      in.close ();\n    }\n    if (is_mesh_pin_resolved_) {\n      std::string fuel_id_name = prm.get (\"fuel pin material id file name\");\n      std::ifstream in_fuel (fuel_id_name);\n      ct = 0;\n      if (in_fuel.is_open ()) {\n        while (std::getline (in_fuel, line)) {\n          int y = ct % ncell_y;\n          int z = ct / ncell_y;\n          std::vector<std::string> strings =\n              dealii::Utilities::split_string_list (line, ' ');\n          AssertThrow (static_cast<int>(strings.size())==ncell_x,\n              dealii::ExcMessage(\"Entries of material ID per row must be ncell_x\"));\n          for (int x=0; x<ncell_x; ++x) {\n            std::vector<int> tmp = {x};\n            if (dim>1) tmp.push_back (y);\n            if (dim>2) tmp.push_back (z);\n            // Note: material has to be stored using Hash table to BST\n            relative_position_to_fuel_id_[tmp] = std::atoi (strings[x].c_str());\n          }\n          ct += 1;\n        }\n        AssertThrow (ct==ncell_y*ncell_z,\n            dealii::ExcMessage(\"Number of y, z fuel ID entries are not correct\"));\n        in_fuel.close ();\n      }\n    }\n  }\n  prm.leave_subsection ();\n}\n\ntemplate <>\nvoid MeshGenerator<2>::SetManifoldsAndRefine (dealii::Triangulation<2> &tria) {\n  // declare manifold as cylinder surfaces around axis parallel to z-axis\n  std::map<std::vector<int>, dealii::SphericalManifold<2>*> rod_surfaces;\n  //std::vector<dealii::SphericalManifold<2>*> rod_surfaces;\n  for (int x=0; x<ncell_per_dir_[0]; ++x)\n    for (int y=0; y<ncell_per_dir_[1]; ++y) {\n      std::vector<int> t = {x, y};\n      auto fuel_id = relative_position_to_fuel_id_[t];\n      if (fuel_id>=0) {\n\n        dealii::Point<2> ctr((0.5+x)*cell_size_all_dir_[0],\n                             (0.5+y)*cell_size_all_dir_[1]);\n        rod_surfaces[t] = new dealii::SphericalManifold<2> (ctr);\n        tria.set_manifold (10+x+y*ncell_per_dir_[0], *rod_surfaces[t]);\n      }\n    }\n\n  for (typename dealii::Triangulation<2>::active_cell_iterator\n       cell=tria.begin_active(); cell!=tria.end(); ++cell)\n    if (cell->is_locally_owned()) {\n      std::vector<int> relative_position;\n      GetCellRelativePosition (cell->center(), relative_position);\n      auto fuel_id = relative_position_to_fuel_id_[relative_position];\n\n      // only set manifolds for rod cells having cladding surface\n      if (fuel_id>=0) {\n        // fuel pin center on x-y plane\n        dealii::Point<2> pin_ctr_xy (\n            (0.5+relative_position[0])*cell_size_all_dir_[0],\n            (0.5+relative_position[1])*cell_size_all_dir_[1]);\n        dealii::Point<2> cell_ctr_xy (cell->center()[0], cell->center()[1]);\n        if (cell_ctr_xy.distance(pin_ctr_xy)<rod_radius_) {\n          int x=relative_position[0], y=relative_position[1];\n          for (unsigned  vn=0;\n               vn<dealii::GeometryInfo<2>::vertices_per_cell; ++vn) {\n            dealii::Point<2> vertex_xy(cell->vertex(vn)[0], cell->vertex(vn)[1]);\n            double dist = vertex_xy.distance(pin_ctr_xy);\n            if (std::fabs(dist-rod_radius_)<1.0e-14) {\n              cell->set_all_manifold_ids (10+x+y*ncell_per_dir_[0]);\n              break;\n            }\n          }\n        }\n\n      }\n    }\n  // perform the refinement\n  tria.refine_global (global_refinements_);\n\n  // reset the manifolds to avoid error from deal.II design defect of manifold\n  tria.reset_manifold (INT_MAX);\n}\n\ntemplate <>\nvoid MeshGenerator<3>::SetManifoldsAndRefine (dealii::Triangulation<3> &tria) {\n  // declare manifold as cylinder surfaces around axis parallel to z-axis\n  std::map<std::vector<int>, dealii::CylindricalManifold<3>*> curved_surfaces;\n  for (int ix=0; ix<ncell_per_dir_[0]; ++ix)\n    for (int iy=0; iy<ncell_per_dir_[1]; ++iy) {\n      std::vector<int> rel_pos = {ix, iy};\n      if (curved_blocks.find(rel_pos)!=curved_blocks.end()) {\n        dealii::Point<3> pt_on_axis ((0.5+ix)*cell_size_all_dir_[0],\n            (0.5+iy)*cell_size_all_dir_[1] ,0);\n        curved_surfaces[rel_pos] =\n            new dealii::CylindricalManifold<3> (dealii::Point<3>(0,0,1.),\n                pt_on_axis);\n        tria.set_manifold (10+ix+iy*ncell_per_dir_[0],\n            *curved_surfaces[rel_pos]);\n      }\n    }\n\n  for (typename dealii::Triangulation<3>::active_cell_iterator\n       cell=tria.begin_active(); cell!=tria.end(); ++cell)\n    if (cell->is_locally_owned()) {\n      //bool dist = cell->center().distance(cell->barycenter())>1.0e-15\n      if (cell->center().distance(cell->barycenter())>1.0e-15) {\n        std::vector<int> rel_pos;\n        GetCellRelativePosition (cell->center(), rel_pos);\n        dealii::Point<3> pin_ctr((0.5+rel_pos[0])*cell_size_all_dir_[0],\n            (0.5+rel_pos[1])*cell_size_all_dir_[1],\n            cell->center()[2]);\n        if (pin_ctr.distance(cell->center())<rod_radius_)\n          cell->set_all_manifold_ids(10+rel_pos[0]+rel_pos[1]*ncell_per_dir_[0]);\n      }\n    }\n\n  // perform the refinement\n  tria.refine_global (global_refinements_);\n  // reset the manifolds to avoid error from deal.II design defect of manifold\n  tria.reset_manifold (INT_MAX);\n}\n\ntemplate <>\nvoid MeshGenerator<1>::GlobalRefine (dealii::Triangulation<1>& tria) {\n  tria.refine_global (global_refinements_);\n}\n\ntemplate <>\nvoid MeshGenerator<2>::GlobalRefine (dealii::Triangulation<2>& tria) {\n  if (is_mesh_pin_resolved_)\n    // set manifolds for fuel rod surfaces and refine\n    SetManifoldsAndRefine (tria);\n  else\n    tria.refine_global (global_refinements_);\n}\n\ntemplate <>\nvoid MeshGenerator<3>::GlobalRefine (dealii::Triangulation<3>& tria) {\n  if (is_mesh_pin_resolved_)\n    // set manifolds for fuel rod surfaces and refine\n    SetManifoldsAndRefine (tria);\n  else\n    tria.refine_global (global_refinements_);\n}\n\ntemplate <int dim>\nstd::unordered_map<int, bool>\nMeshGenerator<dim>::GetReflectiveBCMap () {\n  return is_reflective_bc_;\n}\n\ntemplate <int dim>\nint MeshGenerator<dim>::GetUniformRefinement () {\n  return global_refinements_;\n}\n\ntemplate class MeshGenerator<1>;\ntemplate class MeshGenerator<2>;\ntemplate class MeshGenerator<3>;\n", "meta": {"hexsha": "6cf3aa6f9a23b213769fb97ef674f7070107f28d", "size": 22522, "ext": "cc", "lang": "C++", "max_stars_repo_path": "legacy_code/mesh/mesh_generator.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/mesh/mesh_generator.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/mesh/mesh_generator.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": 36.0929487179, "max_line_length": 99, "alphanum_fraction": 0.635645147, "num_tokens": 6572, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.658417487156366, "lm_q2_score": 0.48828339529583464, "lm_q1q2_score": 0.32149432615086204}}
{"text": "// MIT License\n//\n// Copyright (c) 2019 Jelle Spijker\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 \"../include/fluids/Liquid.h\"\n\n#include <boost/units/cmath.hpp>\n#include <fluids/Liquid.h>\n\nnamespace Fluids {\n\nLiquid::Liquid() :\n    m_static_pressure(new quantity<si::pressure>(1.e5 * si::pascals)),\n    m_speed(new quantity<si::velocity>(0. * si::meters_per_second)),\n    m_height(new quantity<si::length>(0. * si::meter)),\n    m_density(new quantity<si::mass_density>(1000. * si::kilogram_per_cubic_meter)),\n    m_dynamic_viscosity(new quantity<si::dynamic_viscosity>(1.15e-3 * si::pascals * si::seconds)),\n    m_dynamic_pressure(new quantity<si::pressure>(0. * si::pascal)),\n    m_potential_pressure(new quantity<si::pressure>(0. * si::pascal)),\n    m_bernoulli(new quantity<si::pressure>(0. * si::pascal)) {\n\n}\n\nLiquid::Liquid(const Liquid &other) :\n    m_static_pressure(new quantity<si::pressure>(*other.m_static_pressure)),\n    m_speed(new quantity<si::velocity>(*other.m_speed)),\n    m_height(new quantity<si::length>(*other.m_height)),\n    m_density(new quantity<si::mass_density>(*other.m_density)),\n    m_dynamic_viscosity(new quantity<si::dynamic_viscosity>(*other.m_dynamic_viscosity)),\n    m_dynamic_pressure(new quantity<si::pressure>(*other.m_dynamic_pressure)),\n    m_potential_pressure(new quantity<si::pressure>(*other.m_potential_pressure)),\n    m_bernoulli(new quantity<si::pressure>(*other.m_bernoulli)) {\n\n}\n\nLiquid &Liquid::operator=(const Liquid &other) {\n  if (this == &other)\n    return *this;\n  m_static_pressure = std::make_shared<quantity<si::pressure>>(*other.m_static_pressure);\n  m_speed = std::make_shared<quantity<si::velocity>>(*other.m_speed);\n  m_height = std::make_shared<quantity<si::length>>(*other.m_height);\n  m_density = std::make_shared<quantity<si::mass_density>>(*other.m_density);\n  m_dynamic_viscosity = std::make_shared<quantity<si::dynamic_viscosity>>(*other.m_dynamic_viscosity);\n  m_dynamic_pressure = std::make_shared<quantity<si::pressure>>(*other.m_dynamic_pressure);\n  m_potential_pressure = std::make_shared<quantity<si::pressure>>(*other.m_potential_pressure);\n  m_bernoulli = std::make_shared<quantity<si::pressure>>(*other.m_bernoulli);\n  return *this;\n}\n\nconst std::shared_ptr<quantity<si::mass_density>> &Liquid::Get_Density() const {\n  return m_density;\n}\n\nvoid Liquid::Set_Density(const std::shared_ptr<quantity<si::mass_density>> &density) {\n  Liquid::m_density = density;\n}\n\nconst std::shared_ptr<quantity<si::length>> &Liquid::Get_Height() const {\n  return m_height;\n}\n\nvoid Liquid::Set_Height(const std::shared_ptr<quantity<si::length>> &height) {\n  Liquid::m_height = height;\n}\n\nconst std::shared_ptr<quantity<si::pressure>> &Liquid::Get_Dynamic_pressure() const {\n  *m_dynamic_pressure = 0.5 * *this->Get_Density() * abs(*this->Get_Speed()) * *this->Get_Speed();\n  return m_dynamic_pressure;\n}\n\nconst std::shared_ptr<quantity<si::pressure>> &Liquid::Get_Potential_pressure() const {\n  *m_potential_pressure = si::constants::g * *this->Get_Height() * *this->Get_Density();\n  return m_potential_pressure;\n}\n\nconst std::shared_ptr<quantity<si::pressure>> &Liquid::Get_Bernoulli() const {\n  *m_bernoulli = *this->Get_Static_pressure() + *this->Get_Dynamic_pressure() + *this->Get_Potential_pressure();\n  return m_bernoulli;\n}\n\nconst std::shared_ptr<quantity<si::dynamic_viscosity>> &Liquid::Get_Dynamic_viscosity() const {\n  return m_dynamic_viscosity;\n}\n\nvoid Liquid::Set_Dynamic_viscosity(const std::shared_ptr<quantity<si::dynamic_viscosity>> &dynamic_viscosity) {\n  Liquid::m_dynamic_viscosity = dynamic_viscosity;\n}\n\nconst std::shared_ptr<quantity<si::velocity>> &Liquid::Get_Speed() const {\n  return m_speed;\n}\n\nvoid Liquid::Set_Speed(const std::shared_ptr<quantity<si::velocity>> &speed) {\n  Liquid::m_speed = speed;\n}\n\nconst std::shared_ptr<quantity<si::pressure>> &Liquid::Get_Static_pressure() const {\n  return m_static_pressure;\n}\n\nvoid Liquid::Set_Static_pressure(const std::shared_ptr<quantity<si::pressure>> &static_pressure) {\n  Liquid::m_static_pressure = static_pressure;\n}\n}\n", "meta": {"hexsha": "d2d456ac2ad57ae41fbd47c0d979c5bd787c13cc", "size": 5103, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Liquid.cpp", "max_stars_repo_name": "peer23peer/fluids", "max_stars_repo_head_hexsha": "f45de7b951733cec3520371ffeb99304aa6a4659", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Liquid.cpp", "max_issues_repo_name": "peer23peer/fluids", "max_issues_repo_head_hexsha": "f45de7b951733cec3520371ffeb99304aa6a4659", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Liquid.cpp", "max_forks_repo_name": "peer23peer/fluids", "max_forks_repo_head_hexsha": "f45de7b951733cec3520371ffeb99304aa6a4659", "max_forks_repo_licenses": ["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.1532258065, "max_line_length": 112, "alphanum_fraction": 0.7456398197, "num_tokens": 1317, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6187804337438502, "lm_q2_score": 0.5195213219520929, "lm_q1q2_score": 0.32146962893669445}}
{"text": "/*\n * MIT License\n *\n * Copyright (c) 2020 Robert Grupp\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\n#include \"xregLineSearchOpt.h\"\n\n#include <boost/variant.hpp>\n\n#include <fmt/printf.h>\n\n#include \"xregAssert.h\"\n\nnamespace\n{\n\nusing namespace xreg;\n\nusing Pt  = LineSearchOptimization::Pt;\nusing Mat = LineSearchOptimization::Mat;\n\nusing SearchDirFnFirstOrder = LineSearchOptimization::SearchDirFnFirstOrder;\nusing SearchDirFnSecOrder   = LineSearchOptimization::SearchDirFnSecOrder;\n\nstruct SearchDirNeedsHessian : public boost::static_visitor<bool>\n{\n  bool operator()(const SearchDirFnFirstOrder& search_fn) const\n  {\n    xregASSERT(bool(search_fn));\n    return false;\n  }\n\n  bool operator()(const SearchDirFnSecOrder& search_fn) const\n  {\n    xregASSERT(bool(search_fn));\n    return true;\n  }\n};\n\nstruct ComputeSearchDir : public boost::static_visitor<Pt>\n{\n  const Pt*  g;\n  const Mat* H;\n\n  Pt operator()(const SearchDirFnFirstOrder& search_fn) const\n  {\n    return search_fn(*g);\n  }\n  \n  Pt operator()(const SearchDirFnSecOrder& search_fn) const\n  {\n    return search_fn(*g, *H);\n  }\n};\n\n}  // un-named\n\nstd::tuple<xreg::LineSearchOptimization::TermStatus,\n           xreg::LineSearchOptimization::Pt,\n           xreg::LineSearchOptimization::Scalar,\n           xreg::size_type>\nxreg::LineSearchOptimization::solve(const Pt& init_x) const\n{\n  xregASSERT(bool(obj_fn));\n  xregASSERT(bool(backtrack_fn));\n\n  TermStatus status = kOTHER;\n\n  Scalar cur_F;\n  Pt cur_x = init_x;\n  Pt cur_grad;\n  Mat cur_H;\n\n  // search direction\n  Pt p;\n\n  Pt prev_x;\n\n  const bool requires_hessian = boost::apply_visitor(SearchDirNeedsHessian(), search_dir_fn);\n  \n  std::tie(cur_F,cur_grad,cur_H) = obj_fn(cur_x, true, requires_hessian);\n\n  Scalar cur_grad_norm = cur_grad.norm();\n\n  const Scalar grad_term_tol = std::max(Scalar(1), cur_grad_norm) * grad_tol;\n\n  bool should_stop = false;\n\n  size_type cur_it = 0;\n\n  dout() << \" Iter.      F       ||grad F||\" << std::endl;\n\n  while (!should_stop)\n  {\n    dout() << fmt::sprintf(\"%04lu   %+10.4f  %+10.4f\", cur_it, cur_F, cur_grad_norm) << std::endl;\n\n    if (cur_grad_norm <= grad_term_tol)\n    {\n      status = kGRAD_CONVERGED;\n      should_stop = true;\n    }\n    else if ((cur_it > 0) && ((prev_x - cur_x).norm() < param_tol))\n    {\n      status = kNO_POS_CHANGE;\n      should_stop = true;\n    }\n    else if (max_its && (cur_it >= max_its))\n    {\n      status = kMAX_ITS_PERFORMED;\n      should_stop = true;\n    }\n    else\n    {\n      {\n        ComputeSearchDir compute_search_dir_visitor;\n        compute_search_dir_visitor.g = &cur_grad;\n        compute_search_dir_visitor.H = &cur_H;\n\n        p = boost::apply_visitor(compute_search_dir_visitor, search_dir_fn);\n      }\n\n      prev_x = cur_x;\n\n      std::tie(cur_x,cur_F,cur_grad,cur_H) = backtrack_fn(obj_fn, p, prev_x, cur_F, cur_grad, requires_hessian);\n\n      cur_grad_norm = cur_grad.norm();\n\n      ++cur_it;\n    }\n  }\n\n  dout() << \"Termination Status: \" << TermStatusString(status) << std::endl;\n\n  return std::make_tuple(status, cur_x, cur_F, cur_it);\n}\n\nstd::string xreg::LineSearchOptimization::TermStatusString(const TermStatus status)\n{\n  std::string s;\n\n  switch (status)\n  {\n  case kGRAD_CONVERGED:\n    s = \"Gradient Converged\";\n    break;\n  case kMAX_ITS_PERFORMED:\n    s = \"Maximum Iterations Performed\";\n    break;\n  case kNO_POS_CHANGE:\n    s = \"Insufficient Parameter Change\";\n    break;\n  case kOTHER:\n  default:\n    s = \"Other/Unknown\";\n    break;\n  }\n\n  return s;\n}\n\nxreg::LineSearchOptimization::Pt\nxreg::NegativeGradSearchDir(const LineSearchOptimization::Pt& grad,\n                            const LineSearchOptimization::Mat& /*hessian*/)\n{\n  return -1 * grad;\n}\n\nxreg::LineSearchOptimization::Pt\nxreg::NewtonSearchDir(const LineSearchOptimization::Pt& grad,\n                      const LineSearchOptimization::Mat& hessian)\n{\n  using Mat = LineSearchOptimization::Mat;\n\n  // solves hessian \\ -grad\n  return Eigen::JacobiSVD<Mat>(hessian, Eigen::ComputeThinU | Eigen::ComputeThinV).solve(-1 * grad);\n}\n\nxreg::ModNewtonSearchDir::Pt xreg::ModNewtonSearchDir::operator()(const Pt& grad, const Mat& hessian)\n{\n  spectral_dcomp.compute(hessian, Eigen::ComputeEigenvectors);\n\n  const SpectralDecomp::RealVectorType& eig_vals = spectral_dcomp.eigenvalues();\n\n  const Scalar H_L2_norm = eig_vals.array().abs().maxCoeff();\n\n  const Scalar eps = (H_L2_norm > 1.0e-6) ? (H_L2_norm / beta) : Scalar(1);\n\n  bool use_hessian = true;\n\n  const unsigned long d = static_cast<unsigned long>(grad.size());\n\n  mod_eigen_vals.resize(d);\n\n  for (unsigned long i = 0; i < d; ++i)\n  {\n    if (eig_vals(i) >= eps)\n    {\n      mod_eigen_vals(i) = eig_vals(i);\n    }\n    else if (eig_vals(i) <= -eps)\n    {\n      mod_eigen_vals(i) = -eig_vals(i);\n      use_hessian = false;\n    }\n    else\n    {\n      mod_eigen_vals(i) = eps;\n      use_hessian = false;\n    }\n  }\n\n  if (!use_hessian)\n  {\n    const Mat& eigen_vecs = spectral_dcomp.eigenvectors();\n\n    B = eigen_vecs * mod_eigen_vals.asDiagonal() * eigen_vecs.transpose();\n  }\n\n  // solve B \\ -grad\n  return NewtonSearchDir(grad, use_hessian ? hessian : B);\n}\n  \nxreg::LineSearchOptimization::SearchDirFn xreg::ModNewtonSearchDir::callback_fn()\n{\n  return [this] (const Pt& grad, const Mat& hessian) { return this->operator()(grad, hessian); };\n}\n\nstd::tuple<xreg::LineSearchOptimization::Pt,\n           xreg::LineSearchOptimization::Scalar,\n           xreg::LineSearchOptimization::Pt,\n           xreg::LineSearchOptimization::Mat>\nxreg::FixedStepNoBacktracking(const LineSearchOptimization::ObjFn& obj_fn,\n                              const LineSearchOptimization::Pt& p,\n                              const LineSearchOptimization::Pt& x,\n                              const bool compute_hessian,\n                              const LineSearchOptimization::Scalar alpha)\n{\n  using Pt     = LineSearchOptimization::Pt;\n  using Mat    = LineSearchOptimization::Mat;\n  using Scalar = LineSearchOptimization::Scalar;\n  \n  Pt next_x = x + (alpha * p);\n  \n  Scalar next_F;\n  Pt next_g;\n  Mat next_H;\n\n  std::tie(next_F, next_g, next_H) = obj_fn(next_x, true, compute_hessian);\n\n  return std::make_tuple(next_x, next_F, next_g, next_H);\n}\n\nxreg::LineSearchOptimization::BacktrackFn\nxreg::MakeFixedStepNoBacktrackingCallback(const LineSearchOptimization::Scalar alpha)\n{\n  return [alpha] (const LineSearchOptimization::ObjFn& obj_fn,\n                  const LineSearchOptimization::Pt& p,\n                  const LineSearchOptimization::Pt& x,\n                  const LineSearchOptimization::Scalar /*F*/,\n                  const LineSearchOptimization::Pt& /*g*/,\n                  const bool compute_hessian)\n  {\n    return FixedStepNoBacktracking(obj_fn, p, x, compute_hessian, alpha);\n  };\n}\n\nstd::tuple<xreg::LineSearchOptimization::Pt,\n           xreg::LineSearchOptimization::Scalar,\n           xreg::LineSearchOptimization::Pt,\n           xreg::LineSearchOptimization::Mat>\nxreg::BacktrackingArmijo(const LineSearchOptimization::ObjFn& obj_fn,\n                         const LineSearchOptimization::Pt& p,\n                         const LineSearchOptimization::Pt& x,\n                         const LineSearchOptimization::Scalar F,\n                         const LineSearchOptimization::Pt& g,\n                         const bool compute_hessian,\n                         const LineSearchOptimization::Scalar init_alpha,\n                         const LineSearchOptimization::Scalar eta,\n                         const LineSearchOptimization::Scalar tau)\n{\n  using Pt     = LineSearchOptimization::Pt;\n  using Mat    = LineSearchOptimization::Mat;\n  using Scalar = LineSearchOptimization::Scalar;\n\n  const Scalar eta_grad_dot_p = eta * g.dot(p);\n  \n  Scalar alpha = init_alpha;\n  \n  Pt next_x = x + (alpha * p);\n  \n  Scalar next_F;\n\n  // passing false for gradient and hessian defers their computation until\n  // after we stop backtracking - this really helps for expensive computations\n\n  std::tie(next_F,std::ignore,std::ignore) = obj_fn(next_x, false, false);\n\n  while (next_F > (F + (alpha * eta_grad_dot_p)))\n  {\n    alpha *= tau;\n    next_x = x + (alpha * p);\n    std::tie(next_F,std::ignore,std::ignore) = obj_fn(next_x, false, false);\n  }\n  \n  Pt next_g;\n\n  Mat next_H;\n\n  std::tie(next_F,next_g,next_H) = obj_fn(next_x, true, compute_hessian);\n  \n  return std::make_tuple(next_x, next_F, next_g, next_H);\n}\n\nxreg::LineSearchOptimization::BacktrackFn\nxreg::MakeBacktrackingArmijoCallback(const LineSearchOptimization::Scalar alpha,\n                                     const LineSearchOptimization::Scalar eta,\n                                     const LineSearchOptimization::Scalar tau)\n{\n  return [alpha,eta,tau] (const LineSearchOptimization::ObjFn& obj_fn,\n                          const LineSearchOptimization::Pt& p,\n                          const LineSearchOptimization::Pt& x,\n                          const LineSearchOptimization::Scalar F,\n                          const LineSearchOptimization::Pt& g,\n                          const bool compute_hessian)\n  {\n    return BacktrackingArmijo(obj_fn, p, x, F, g, compute_hessian, alpha, eta, tau);\n  };\n}\n\n", "meta": {"hexsha": "2b4f5ed610f53ca0e335696a592759ef9a68e546", "size": 10158, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lib/optim/xregLineSearchOpt.cpp", "max_stars_repo_name": "rg2/xreg", "max_stars_repo_head_hexsha": "c06440d7995f8a441420e311bb7b6524452843d3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 30.0, "max_stars_repo_stars_event_min_datetime": "2020-09-29T18:36:13.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T09:25:13.000Z", "max_issues_repo_path": "lib/optim/xregLineSearchOpt.cpp", "max_issues_repo_name": "gaocong13/Orthopedic-Robot-Navigation", "max_issues_repo_head_hexsha": "bf36f7de116c1c99b86c9ba50f111c3796336af0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2020-10-09T01:21:27.000Z", "max_issues_repo_issues_event_max_datetime": "2020-12-10T15:39:44.000Z", "max_forks_repo_path": "lib/optim/xregLineSearchOpt.cpp", "max_forks_repo_name": "rg2/xreg", "max_forks_repo_head_hexsha": "c06440d7995f8a441420e311bb7b6524452843d3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2021-05-25T05:14:48.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-26T12:29:50.000Z", "avg_line_length": 29.106017192, "max_line_length": 112, "alphanum_fraction": 0.6617444379, "num_tokens": 2595, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.3214674580985964}}
{"text": "/**\n * \\file gtpack/cooperative.hpp\n *\n * \\brief Cooperative games.\n *\n * \\author Marco Guazzone (marco.guazzone@gmail.com)\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#ifndef GTPACK_COOPERATIVE_HPP\n#define GTPACK_COOPERATIVE_HPP\n\n\n#include <boost/dynamic_bitset.hpp>\n#include <boost/math/special_functions/factorials.hpp>\n#include <boost/smart_ptr.hpp>\n#include <cstddef>\n#include <dcs/algorithm/combinatorics.hpp>\n#include <dcs/assert.hpp>\n#include <dcs/debug.hpp>\n#include <dcs/exception.hpp>\n#include <dcs/logging.hpp>\n#include <dcs/math/traits/float.hpp>\n#include <iostream>\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#include <limits>\n#include <map>\n#include <set>\n#include <sstream>\n#include <stdexcept>\n\n\nnamespace gtpack {\n\ntypedef unsigned int pid_type;\ntypedef pid_type player_type; //XXX: DEPRECATED\ntypedef unsigned long cid_type;\n\nstatic const cid_type empty_cid = 0;\nstatic const cid_type empty_coalition_id = empty_cid; //XXX: DEPRECATED\n\n/// Returns the identifier of the singleton coalition for the given player\ninline\ncid_type make_coalition_id(pid_type pid)\n{\n\tconst cid_type one = 1;\n\n\treturn one << pid;\n}\n\n/// Returns the identifier of the coalition for the given players\ntemplate <typename IterT>\ncid_type make_coalition_id(IterT first_player, IterT last_player)\n{\n\t// Each coalition $S\\subseteq\\{1,2,...,N\\}$ can be characterized\n\t// uniquely by the $\\sum_{i \\in S}{2^{i-1}}$, which is the sum of\n\t// integers associated to players belonging to a particular coalition.\n\n\tconst cid_type one = 1;\n\n\tcid_type cid = 0;\n\n\twhile (first_player != last_player)\n\t{\n\t\tconst pid_type pid = *first_player;\n\n\t\t// Update only if the player in not already member of this coalition\n\t\tif (!(cid & (one << pid)))\n\t\t{\n\t\t\tcid += one << pid;\n\t\t}\n\n\t\t++first_player;\n\t}\n\n\treturn cid;\n}\n\n/// Returns the identifier of the grand coalition for \\a n players\ninline\ncid_type make_grand_coalition_id(std::size_t n)\n{\n\tif (n == 0)\n\t{\n\t\treturn empty_cid;\n\t}\n\n\tconst std::size_t nb = sizeof(cid_type)*8; // # bits in cid_type\n\treturn ~static_cast<cid_type>(0) >> (nb-n);\n}\n\n/// Returns the identifier of the complement of a given coalition\ninline\ncid_type make_complement_coalition_id(std::size_t n, cid_type cid)\n{\n    return make_grand_coalition_id(n) - cid;\n}\n\n/// Returns the identifier of the complement of a coalition for the given players\ntemplate <typename IterT>\ncid_type make_complement_coalition_id(std::size_t n, IterT first_player, IterT last_player)\n{\n\treturn make_complement_coalition_id(n, make_coalition_id(first_player, last_player));\n}\n\ntemplate <typename RealT>\nstruct characteristic_function\n{\n\ttypedef RealT real_type;\n\n\tpublic: real_type operator()(cid_type cid) const\n\t{\n\t\tif (cid == empty_coalition_id)\n\t\t{\n\t\t\treturn 0;\n\t\t}\n\n\t\treturn this->do_get(cid);\n\t}\n\n\tpublic: void operator()(cid_type cid, real_type v)\n\t{\n\t\tDCS_ASSERT(cid != empty_coalition_id,\n\t\t\t\t   DCS_EXCEPTION_THROW(::std::invalid_argument,\n\t\t\t\t\t\t\t\t\t   \"Cannot change the value of the empty coalition\"));\n\n\t\tthis->do_set(cid, v);\n\t}\n\n//\tpublic: real_type& operator()(cid_type cid)\n//\t{\n//\t\treturn this->do_get(cid);\n//\t}\n\n\tprivate: virtual real_type do_get(cid_type cid) const = 0;\n\n\tprivate: virtual void do_set(cid_type cid, real_type v) = 0;\n\n//\tprivate: virtual real_type& do_get(cid_type cid) = 0;\n}; // characteristic_function\n\ntemplate <typename RealT>\nclass enumerated_characteristic_function: public characteristic_function<RealT>\n{\n\tpublic: typedef RealT real_type;\n\n\n\tpublic: enumerated_characteristic_function()\n\t{\n\t}\n\n\tpublic: template <typename CidValIterT>\n\t\t\tenumerated_characteristic_function(CidValIterT first, CidValIterT last)\n\t: map_(first, last)\n\t{\n\t}\n\n\tprivate: real_type do_get(cid_type cid) const\n\t{\n\t\treturn map_.count(cid) > 0 ? map_.at(cid) : ::std::numeric_limits<real_type>::quiet_NaN();\n\t}\n\n\tprivate: void do_set(cid_type cid, real_type v)\n\t{\n\t\tmap_[cid] = v;\n\t}\n\n//\tprivate: real_type& do_get(cid_type cid)\n//\t{\n//\t\treturn map_[cid];\n//\t}\n\n\n\tprivate: ::std::map<cid_type,real_type> map_;\n}; // enumerated_characteristic_function\n\n\ntemplate <typename RealT>\nclass explicit_characteristic_function: public enumerated_characteristic_function<RealT> { };\n/*\n{\n\tpublic: typedef RealT real_type;\n\n\n\tpublic: explicit_characteristic_function()\n\t{\n\t}\n\n\tpublic: template <typename CidValIterT>\n\t\t\texplicit_characteristic_function(CidValIterT first, CidValIterT last)\n\t: map_(first, last)\n\t{\n\t}\n\n\tprivate: real_type do_get(cid_type cid) const\n\t{\n\t\treturn map_.count(cid) > 0 ? map_.at(cid) : ::std::numeric_limits<real_type>::quiet_NaN();\n\t}\n\n\tprivate: void do_set(cid_type cid, real_type v)\n\t{\n\t\tmap_[cid] = v;\n\t}\n\n//\tprivate: real_type& do_get(cid_type cid)\n//\t{\n//\t\treturn map_[cid];\n//\t}\n\n\n\tprivate: ::std::map<cid_type,real_type> map_;\n}; // explicit_characteristic_function\n*/\n\n\ntemplate <typename RealT>\nclass players_coalition\n{\n\tpublic: typedef unsigned long cid_type;\n\tpublic: typedef RealT real_type;\n\tprivate: typedef ::boost::dynamic_bitset<> bitset_container;\n\tprivate: typedef typename bitset_container::size_type size_type;\n\n\n//\ttemplate <typename C, typename CT, typename R>\n//\tfriend\n//\t::std::basic_ostream<C,CT>& operator<<(::std::basic_ostream<C,CT>&, players_coalition<R> const&);\n\n\n\tpublic: template <typename IterT>\n\t\t\tstatic cid_type make_id(IterT first_player, IterT last_player)\n\t{\n\t\t// Each coalition $S\\subseteq\\{1,2,...,N\\}$ can be characterized\n\t\t// uniquely by the $\\sum_{i \\in S}{2^{i-1}}$, which is the sum of\n\t\t// integers associated to players belonging to a particular coalition.\n\n\t\tconst cid_type one(1);\n\n\t\tcid_type cid(0);\n\n\t\twhile (first_player != last_player)\n\t\t{\n\t\t\tcid += one << *first_player;\n\n\t\t\t++first_player;\n\t\t}\n\n\t\treturn cid;\n\t}\n\n\n\tpublic: players_coalition(::std::size_t n, cid_type cid)\n\t: id_(cid),\n\t  players_(),\n\t  //players_bs_(n, id_),\n\t  players_bs_(::std::max(num_bits(id_), n), id_),\n\t  n_(players_bs_.count()),\n\t  v_(0)\n\t{\n\t\tfor (size_type player = players_bs_.find_first();\n\t\t\t player != bitset_container::npos;\n\t\t\t player = players_bs_.find_next(player))\n\t\t{\n\t\t\tplayers_.push_back(player);\n\t\t}\n\t}\n\n//\tpublic: template <typename IterT>\n//\t\t\tplayers_coalition(::std::size_t n, IterT first_player, IterT last_player)\n//\t: id_(make_id(first_player, last_player)),\n//\t  players_(n, id_),\n//\t  n_(players_.count()),\n//\t  v_(0)\n//\t{\n//\t}\n\n\tpublic: template <typename IterT>\n\t\t\tplayers_coalition(IterT first_player, IterT last_player)\n\t: id_(make_id(first_player, last_player)),\n\t  players_(first_player, last_player),\n\t  players_bs_(players_.size(), id_),\n\t  n_(players_.size()),\n\t  v_(0)\n\t{\n\t}\n\n\tpublic: cid_type id() const\n\t{\n\t\treturn id_;\n\t}\n\n\tpublic: ::std::size_t size() const\n\t{\n\t\treturn n_;\n\t}\n\n\tpublic: bool has_player(pid_type player) const\n\t{\n\t\treturn players_bs_.test(player);\n\t}\n\n\tpublic: ::std::vector<pid_type> players() const\n\t{\n\t\treturn players_;\n\t}\n\n\tpublic: ::std::size_t num_players() const\n\t{\n\t\treturn players_.size();\n\t}\n\n\tpublic: void value(real_type v)\n\t{\n\t\tv_ = v;\n\t}\n\n\tpublic: real_type value() const\n\t{\n\t\treturn v_;\n\t}\n\n\n//\tprivate: static unsigned int count_bit_set(unsigned long v)\n//\t{\n//\t\tunsigned int c(0); // c accumulates the total bits set in v\n//\t\twhile (v)\n//\t\t{\n//\t\t\tv &= v-1; // Clear the least significant bit set\n//\t\t\t++c;\n//\t\t}\n//\n//\t\treturn c;\n//\t}\n\n\tprivate: static ::std::size_t num_bits(unsigned long v)\n\t{\n\t\treturn ::std::floor(::std::log(v)/::std::log(2)+1);\n\t}\n\n\t//private: ::std::bitset<8*sizeof(cid_type)> players_;\n\tprivate: cid_type id_;\n\tprivate: ::std::vector<pid_type> players_;\n\tprivate: bitset_container players_bs_;\n\tprivate: ::std::size_t n_;\n\tprivate: RealT v_;\n}; // players_coalition\n\n\ntemplate <typename CharT,\n\t\t  typename CharTraitsT,\n\t\t  typename RealT>\n::std::basic_ostream<CharT,CharTraitsT>& operator<<(::std::basic_ostream<CharT,CharTraitsT>& os, players_coalition<RealT> const& coalition)\n{\n\ttypedef ::std::vector<pid_type> player_container;\n\ttypedef typename player_container::const_iterator player_iterator;\n\n\tbool first(true);\n\n\tos << \"{\";\n\tplayer_container players(coalition.players());\n\tplayer_iterator end_it(players.end());\n\tfor (player_iterator it = players.begin(); it != end_it; ++it)\n\t{\n\t\tif (!first)\n\t\t{\n\t\t\tos << \",\";\n\t\t}\n\t\telse\n\t\t{\n\t\t\tfirst = false;\n\t\t}\n\t\tos << *it;\n\t}\n\tos << \"}\";\n\n\treturn os;\n}\n\n\ntemplate <typename RealT>\nclass cooperative_game\n{\n\tpublic: typedef RealT real_type;\n\n\n\tpublic: cooperative_game()\n\t{\n\t}\n\n\tpublic: cooperative_game(::std::size_t n,\n\t\t\t\t\t\t\t ::boost::shared_ptr< characteristic_function<RealT> > const& p_v)\n\t: n_(n),\n\t  p_v_(p_v)\n\t{\n\t\tfor (pid_type i = 0; i < n_; ++i)\n\t\t{\n\t\t\tplayers_.insert(i);\n\t\t}\n\n\t\tcoal_struc_.insert(this->coalition(players_.begin(), players_.end()).id());\n\t}\n\n\tpublic: template <typename IterT>\n\t\t\tcooperative_game(IterT first_player,\n\t\t\t\t\t\t\t IterT last_player,\n\t\t\t\t\t\t\t ::boost::shared_ptr< characteristic_function<RealT> > const& p_v)\n\t: n_(0),\n\t  p_v_(p_v),\n\t  players_(first_player,last_player)\n\t{\n\t\tn_ = players_.size();\n\n\t\tcoal_struc_.insert(this->coalition(players_.begin(), players_.end()).id());\n\t}\n\n\tpublic: ::std::size_t num_players() const\n\t{\n\t\treturn n_;\n\t}\n\n\tpublic: ::std::vector<pid_type> players() const\n\t{\n\t\treturn ::std::vector<pid_type>(players_.begin(), players_.end());\n\t}\n\n\tpublic: real_type value(cid_type cid) const\n\t{\n\t\treturn (*p_v_)(cid);\n\t}\n\n\tpublic: void value(cid_type cid, real_type value)\n\t{\n\t\t(*p_v_)(cid, value);\n\t}\n\n\tpublic: players_coalition<real_type> coalition(cid_type cid) const\n\t{\n\t\tplayers_coalition<real_type> c(n_, cid);\n\n\t\tc.value(this->value(cid));\n\n\t\treturn c;\n\t}\n\n\tpublic: template <typename PlayerIterT>\n\t\t\tplayers_coalition<real_type> coalition(PlayerIterT first, PlayerIterT last) const\n\t{\n\t\tplayers_coalition<real_type> c(first, last);\n\n\t\tc.value(this->value(c.id()));\n\n\t\treturn c;\n\t}\n\n\tpublic: template <typename CidIterT>\n\t\t\tvoid coalition_structure(CidIterT first, CidIterT last)\n\t{\n\t\tcoal_struc_.clear();\n\t\twhile (first != last)\n\t\t{\n\t\t\tconst cid_type cid(*first);\n\n\t\t\tcoal_struc_.insert(cid);\n\n\t\t\t++first;\n\t\t}\n\t}\n\n//\tpublic: ::std::vector<cid_type> coalition_structure() const\n//\t{\n//\t\treturn ::std::vector<cid_type>(coal_struc_.begin(), coal_struc_.end());\n//\t}\n\tpublic: ::std::set<cid_type> coalition_structure() const\n\t{\n\t\treturn coal_struc_;\n\t}\n\n\tpublic: template <typename PlayerIterT>\n\t\t\tcooperative_game<real_type> subgame(PlayerIterT first, PlayerIterT last) const\n\t{\n\t\treturn cooperative_game<real_type>(first, last, p_v_);\n\t}\n\n\tpublic: cooperative_game<real_type> subgame(cid_type cid) const\n\t{\n\t\tconst ::std::vector<pid_type> players = this->coalition(n_, cid).players();\n\n\t\treturn this->subgame(players.begin(), players.end());\n\t}\n\n\n\tprivate: ::std::size_t n_; ///< Number of players\n\t//private: ::boost::function<real_type (cid_type)> p_v_; ///< Pointer to the characteristic function\n\tprivate: ::boost::shared_ptr< characteristic_function<real_type> > p_v_; ///< Pointer to the characteristic function\n\tprivate: ::std::set<pid_type> players_; ///< The set of players\n\tprivate: ::std::set<cid_type> coal_struc_; ///< The set of coalition ID making the coalition structure for this game\n}; // cooperative_game\n\n\ntemplate <typename RealT>\nclass core\n{\n\tpublic: typedef RealT real_type;\n\n\n\tpublic: core(/*::boost::shared_ptr< cooperative_game<real_type> > const& p_game*/)\n\t: empty_(true)\n\t{\n\t}\n\n\tpublic: template <typename IterT>\n\t\t\tcore(IterT first_payoff, IterT last_payoff)\n\t: empty_(false),\n\t  x_(first_payoff, last_payoff)\n\t{\n\t}\n\n\tpublic: ::std::vector<real_type> imputation() const\n\t{\n\t\treturn x_;\n\t}\n\n\tpublic: bool empty() const\n\t{\n\t\treturn empty_;\n\t}\n\n\n\tprivate: bool empty_;\n\tprivate: ::std::vector<real_type> x_;\n};\n\n\n/**\n * \\brief Compute the Shapley value for a given player.\n *\n * Given a game \\f$(N,v)\\f$, the Shapley value \\f$\\phi_i\\f$ for player \\f$i\\f$\n * is computed as:\n * \\f[\n *  \\phi_i(v)=\\sum_{S \\subseteq N \\setminus \\{i\\}} \\frac{|S|!\\; (|N|-|S|-1)!}{|N|!}(v(S\\cup\\{i\\})-v(S)) \n * \\f]\n */\ntemplate <typename RealT>\nRealT shapley_value(cooperative_game<RealT> const& game, pid_type player)\n{\n\tconst ::std::size_t n(game.num_players());\n\tconst RealT n_fact(::boost::math::factorial<RealT>(n));\n\n\t::std::vector<pid_type> players(game.players());\n\t::std::set<pid_type> other_players(players.begin(), players.end());\n\tplayers.clear();\n\tother_players.erase(player);\n\n\tRealT sv(0);\n\n\tif (other_players.size() > 0)\n\t{\n\t\t::dcs::algorithm::lexicographic_subset subset(other_players.size(), true);\n\t\twhile (subset.has_next())\n\t\t{\n\t\t\t::std::size_t s(subset.size());\n\t\t\tRealT s_fact(::boost::math::factorial<RealT>(s));\n\t\t\tRealT nmsm1_fact(::boost::math::factorial<RealT>(n-s-1));\n\n\t\t\t::std::vector<pid_type> tmp_players(subset(other_players.begin(), other_players.end()));\n\t\t\tcid_type s_cid = players_coalition<RealT>::make_id(tmp_players.begin(), tmp_players.end());\n\t\t\ttmp_players.push_back(player);\n\t\t\tcid_type sui_cid = players_coalition<RealT>::make_id(tmp_players.begin(), tmp_players.end());\n\n\t\t\tsv += s_fact*nmsm1_fact*(game.value(sui_cid)-game.value(s_cid));\n\n\t\t\t++subset;\n\t\t}\n\t}\n\telse\n\t{\n\t\tcid_type cid = players_coalition<RealT>::make_id(&player, &player+1);\n\t\tsv += game.value(cid);\n\t}\n\n\treturn sv/n_fact;\n}\n\n/**\n * \\brief Compute the Shapley value for all the players of a given game.\n *\n * Given a game \\f$(N,v)\\f$, the Shapley value \\f$\\phi_i\\f$ for player \\f$i\\f$\n * is computed as:\n * \\f[\n *  \\phi_i(v)=\\sum_{S \\subseteq N \\setminus \\{i\\}} \\frac{|S|!\\; (|N|-|S|-1)!}{|N|!}(v(S\\cup\\{i\\})-v(S)) \n * \\f]\n */\ntemplate <typename RealT>\n::std::map<pid_type,RealT> shapley_value(cooperative_game<RealT> const& game)\n{\n\tconst ::std::size_t n(game.num_players());\n\tconst RealT n_fact(::boost::math::factorial<RealT>(n));\n\n\t::std::vector<pid_type> players(game.players());\n\n\t::std::map<pid_type,RealT> sv_map;\n\n\t::std::vector<pid_type>::const_iterator players_end_it(players.end());\n\tfor (::std::vector<pid_type>::const_iterator players_it = players.begin();\n\t\t players_it != players_end_it;\n\t\t ++players_it)\n\t{\n\t\tpid_type pid(*players_it);\n\n\t\tRealT sv(0);\n\n\t\t::std::set<pid_type> other_players(players.begin(), players.end());\n\t\tother_players.erase(pid);\n\n\t\tif (other_players.size() > 0)\n\t\t{\n\t\t\t::dcs::algorithm::lexicographic_subset subset(other_players.size(), true);\n\t\t\twhile (subset.has_next())\n\t\t\t{\n\t\t\t\tconst ::std::size_t s(subset.size());\n\t\t\t\tconst RealT s_fact(::boost::math::factorial<RealT>(s));\n\t\t\t\tconst RealT nmsm1_fact(::boost::math::factorial<RealT>(n-s-1));\n\n\t\t\t\t::std::vector<pid_type> tmp_players(subset(other_players.begin(), other_players.end()));\n\t\t\t\tcid_type s_cid = players_coalition<RealT>::make_id(tmp_players.begin(), tmp_players.end());\n\t\t\t\ttmp_players.push_back(pid);\n\t\t\t\tconst cid_type sui_cid = players_coalition<RealT>::make_id(tmp_players.begin(), tmp_players.end());\n\n\t\t\t\tsv += s_fact*nmsm1_fact*(game.value(sui_cid)-game.value(s_cid));\n\n\t\t\t\t++subset;\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\tcid_type cid = players_coalition<RealT>::make_id(&pid, &pid+1);\n\t\t\tsv += game.value(cid);\n\t\t}\n\n\t\tsv_map[pid] = sv/n_fact;\n\t}\n\n\treturn sv_map;\n}\n\n/**\n * \\brief Compute the Banzhaf value for all the players of a given game.\n *\n * Given a game \\f$(N,v)\\f$, the Banzhaf value \\f$\\beta_i\\f$ for player \\f$i\\f$\n * is computed as:\n * \\f[\n *  \\beta_i(v)=\\frac{1}{2^{|N|-1}}\\sum_{S \\subseteq N \\setminus \\{i\\}} (v(S\\cup\\{i\\})-v(S)) \n * \\f]\n */\ntemplate <typename RealT>\n::std::map<pid_type,RealT> banzhaf_value(cooperative_game<RealT> const& game)\n{\n\tconst ::std::size_t n(game.num_players());\n\tconst RealT prod(1.0/::std::pow(2, n-1));\n\t//const RealT prod(1.0/(1 << (n-1)));\n\n\t::std::vector<pid_type> players(game.players());\n\n\t::std::map<pid_type,RealT> bv_map;\n\n\t::std::vector<pid_type>::const_iterator players_end_it(players.end());\n\tfor (::std::vector<pid_type>::const_iterator players_it = players.begin();\n\t\t players_it != players_end_it;\n\t\t ++players_it)\n\t{\n\t\tpid_type player(*players_it);\n\n\t\tRealT bv(0);\n\n\t\t::std::set<pid_type> other_players(players.begin(), players.end());\n\t\tother_players.erase(player);\n\n\t\tif (other_players.size() > 0)\n\t\t{\n\t\t\t::dcs::algorithm::lexicographic_subset subset(other_players.size(), true);\n\t\t\twhile (subset.has_next())\n\t\t\t{\n\t\t\t\t::std::vector<pid_type> tmp_players(subset(other_players.begin(), other_players.end()));\n\t\t\t\tcid_type s_cid = players_coalition<RealT>::make_id(tmp_players.begin(), tmp_players.end());\n\t\t\t\ttmp_players.push_back(player);\n\t\t\t\tcid_type sui_cid = players_coalition<RealT>::make_id(tmp_players.begin(), tmp_players.end());\n\n\t\t\t\tbv += (game.value(sui_cid)-game.value(s_cid));\n\n\t\t\t\t++subset;\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\tcid_type cid = players_coalition<RealT>::make_id(&player, &player+1);\n\t\t\tbv += game.value(cid);\n\t\t}\n\n\t\tbv_map[player] = bv*prod;\n\t}\n\n\treturn bv_map;\n}\n\n/**\n * \\brief Compute the normalized Banzhaf value for all the players of a given\n *  game.\n *\n * Given a game \\f$(N,v)\\f$, the normalized Banzhaf value \\f$\\bar{\\beta}_i\\f$\n * for player \\f$i\\f$ is computed as:\n * \\f[\n *  \\bar{\\beta}_i=\\frac{\\beta_i}{\\sum_{j \\in N}\\beta_j}\n * \\f]\n * where\n * \\f[\n *  \\beta_i(v)=\\frac{1}{2^{|N|-1}}\\sum_{S \\subseteq N \\setminus \\{i\\}} (v(S\\cup\\{i\\})-v(S)) \n * \\f]\n * is the non-normalized Banzhaf value.\n */\ntemplate <typename RealT>\n::std::map<pid_type,RealT> norm_banzhaf_value(cooperative_game<RealT> const& game)\n{\n\t::std::map<pid_type,RealT> bv_map = banzhaf_value(game);\n\n\tRealT den(0);\n\t// Compute the sum of all non-normalized Banzhaf values\n\t{\n\t\ttypename ::std::map<pid_type,RealT>::const_iterator end_it(bv_map.end());\n\t\tfor (typename ::std::map<pid_type,RealT>::const_iterator it = bv_map.begin();\n\t\t\t it != end_it;\n\t\t\t ++it)\n\t\t{\n\t\t\tden += it->second;\n\t\t}\n\t}\n\t// Normalize each Banzhaf value\n\t{\n\t\t::std::vector<pid_type> players(game.players());\n\t\tcid_type gc_cid = players_coalition<RealT>::make_id(players.begin(), players.end());\n\t\tRealT v_gc = game.value(gc_cid);\n\t\ttypename ::std::map<pid_type,RealT>::iterator end_it(bv_map.end());\n\t\tfor (typename ::std::map<pid_type,RealT>::iterator it = bv_map.begin();\n\t\t\t it != end_it;\n\t\t\t ++it)\n\t\t{\n\t\t\tit->second *= v_gc/den;\n\t\t}\n//\t\ttypename ::std::map<pid_type,RealT>::iterator end_it(bv_map.end());\n//\t\tfor (typename ::std::map<pid_type,RealT>::iterator it = bv_map.begin();\n//\t\t\t it != end_it;\n//\t\t\t ++it)\n//\t\t{\n//\t\t\tit->second /= den;\n//\t\t}\n\t}\n\n\treturn bv_map;\n}\n\n/**\n * \\brief Compute the Aumann-Dreze value for all the players of a given game.\n *\n * Given a game \\f$(N,v)\\f$ with coalition structure \\f$\\mathcal{P}\\f$, the\n * Aumann-Dreze value \\f$\\text{AD}_i\\f$ for player \\f$i\\f$ is computed as:\n * \\f[\n *  \\text{AD}_i(v)=\\sum_{S \\subseteq \\mathcal{P}(i) \\setminus \\{i\\}} \\frac{|S|!\\; (|\\mathcal{P}(i)|-|S|-1)!}{|\\mathcal{P}(i)|!}(v(S\\cup\\{i\\})-v(S)) \n * \\f]\n * where \\f$\\mathcal{P}(i)\\in\\mathcal{P}\\f$ is the coalition containing the\n * player $i$.\n *\n * References:\n * -# R.J. Aumann and J.H. Dr{\\`e}ze,\n *    Cooperative games with coalition structures,\n *    International Journal of Game Theory 3:217-237, 1974\n * .\n */\ntemplate <typename RealT>\n::std::map<pid_type,RealT> aumann_dreze_value(cooperative_game<RealT> const& game)\n{\n\tconst ::std::vector<cid_type> structure(game.coalition_structure());\n\tconst ::std::size_t nc(structure.size());\n\n\t::std::map<pid_type,RealT> ad_map;\n\n\tfor (::std::size_t i = 0; i < nc; ++i)\n\t{\n\t\tconst cid_type cid(structure[i]);\n\n\t\tconst ::std::vector<pid_type> players = game.coalition(cid).players();\n\n\t\t::std::map<pid_type,RealT> sh_map = shapley_value(game.subgame(cid));\n\t\tad_map.insert(sh_map.begin(), sh_map.end());\n\t}\n\n\treturn ad_map;\n}\n\n/**\n * \\brief Compute the Chi-value for all the players of a given\n *  game.\n *\n * Given a game \\f$(N,v)\\f$ with coalition structure \\f$\\mathcal{P}\\f$, the\n * Chi-value \\f$\\Chi_i\\f$ for player \\f$i\\f$ is computed as:\n * \\f[\n *  Chi_i=\\phi_i(N,v)+\\frac{v(\\mathcal{P}(i)-\\sum_{j\\in\\mathcal{P}(i)}\\phi_j(N,v)}{|\\mathcal{P}(i)|}\n * \\f]\n * where\\f$\\mathcal{P}(i)\\f$ is the coalition in \\f$\\mathcal{P}\\f$ that contains\n * the player \\f$i\\f$.\n *\n * References:\n * -# Andre` Casajus. \"Outside options, component efficiency, and stability\", Games and Economic Behavior 65:49-61, 2009.\n * .\n */\ntemplate <typename RealT>\n::std::map<pid_type,RealT> chi_value(cooperative_game<RealT> const& game)\n{\n\tconst ::std::vector<cid_type> structure(game.coalition_structure());\n\tconst ::std::size_t nc(structure.size());\n\tconst ::std::map<pid_type,RealT> shapley_map(shapley_value(game));\n\n\t::std::map< ::std::size_t,RealT> coal_shapley_map;\n\n\tfor (::std::size_t i = 0; i < nc; ++i)\n\t{\n\t\tconst cid_type cid = structure[i];\n\t\tconst ::std::vector<pid_type> players = game.coalition(cid).players();\n\t\tconst ::std::size_t np = players.size();\n\n\t\tRealT sh(0);\n\t\tfor (::std::size_t j = 0; j < np; ++j)\n\t\t{\n\t\t\tconst pid_type pid(players[j]);\n\n\t\t\tsh += shapley_map.at(pid);\n\t\t}\n\t\tcoal_shapley_map[cid] = sh;\n\t}\n\n\t::std::map<pid_type,RealT> chi_map;\n\n\tfor (::std::size_t i = 0; i < nc; ++i)\n\t{\n\t\tconst cid_type cid = structure[i];\n\t\tconst players_coalition<RealT> coalition = game.coalition(cid);\n\t\tconst ::std::vector<pid_type> players = coalition.players();\n\t\tconst ::std::size_t np = players.size();\n\t\tconst RealT add = (coalition.value()-coal_shapley_map.at(cid))/np;\n\n\t\tfor (::std::size_t j = 0; j < np; ++j)\n\t\t{\n\t\t\tconst pid_type pid(players[j]);\n\n\t\t\tchi_map[pid] = shapley_map.at(pid)+add;\n\t\t}\n\t}\n\n\treturn chi_map;\n}\n\n\n/**\n * \\brief Compute the core of the given cooperative game.\n *\n * Given a cooperative game G=(N,v), the core C(v) is the set\n * \\f[\n *  \\biggl\\bigl{x | \\sum_{i \\in N} x_i=v(N), \\text{ and } x_i \\ge v(i) \\forall i \\in N, \\text{ and } \\sum_{i\\in S} x_i \\ge v(S) \\forall S \\subset N\\setminus \\{\\emptyset\\bigr\\}\\biggr\\}\n * \\f]\n *\n * TODO: manage the case of games with a coalition structure CS. For such games, the core is defined as the set of payoff vectors x = (x1 , ..., xn ) and a coalition Structure CS = (C1 , ...,Ck ) such that:\n * - \\forall C \\subseteq N, x(C) \\ge v(C) and\n * - x(C_j) = v(C_j) for any C_j \\in CS\n * .\n */\ntemplate <typename RealT>\n//core<RealT> find_core(typename coalition<RealT>::cid_type const& cid, ::std::vector<pid_type> const& players, ::std::map<cid_type,RealT> const& coalitions)\ncore<RealT> find_core(cooperative_game<RealT> const& game)\n//typename coalition<RealT>::cid_type const& cid, ::std::vector<pid_type> const& players, ::std::map<cid_type,RealT> const& coalitions)\n{\n\ttypedef RealT real_type;\n\ttypedef players_coalition<real_type> coalition_type;\n\t//typedef typename coalition_type::cid_type cid_type;\n\ttypedef IloNumVarArray var_vector_type;\n//\ttypedef IloArray<IloNumVarArray> var_matrix_type;\n\ttypedef typename ::dcs::algorithm::lexicographic_subset subset_type;\n\ttypedef typename subset_type::const_iterator subset_iterator;\n\ttypedef typename ::dcs::algorithm::subset_traits<pid_type>::subset_container subset_container;\n//\ttypedef typename ::dcs::algorithm::subset_traits<pid_type>::subset_container_const_iterator subset_container_iterator;\n\n\tcore<real_type> kore;\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\tmodel.setName(\"Core\");\n\n\t\t::std::size_t n(game.num_players());\n\t\t::std::vector<pid_type> players(game.players());\n\n\t\t// Decision Variable\n\n\t\t// Variables x_{i} >= 0: the payoff for player i\n\t\tvar_vector_type x(env, n);\n\t\tfor (std::size_t i = 0; i < n; ++i)\n\t\t{\n\t\t\tstd::ostringstream oss;\n\t\t\toss << \"x[\" << i << \"]\";\n\t\t\tx[i] = IloNumVar(env, -IloInfinity, IloInfinity, ILOFLOAT, oss.str().c_str());\n\t\t\tmodel.add(x[i]);\n\t\t}\n\n\t\t// Constraints\n\n\t\tstd::size_t cc(0); // Constraint counter\n\t\tstd::size_t csc(0); // Constraint subcounter\n\n\t\tsubset_type lex_subset(n, false);\n\n\t\t// C1: \\forall S \\subset N, \\sum_{i \\in S} x[i] >= v(S), and \\sum_{i \\in N} x[i] = v(N)\n\t\t++cc;\n\t\twhile (lex_subset.has_next())\n\t\t{\n\t\t\t++csc;\n\n\t\t\tsubset_container players_subset;\n\n\t\t\t//players_subset = ::dcs::algorithm::next_subset(players.begin(), players.end(), lex_subset);\n\t\t\tplayers_subset = lex_subset(players.begin(), players.end());\n\n\t\t\tcid_type cid = coalition_type::make_id(players_subset.begin(), players_subset.end());\n\n\t\t\treal_type v_cid = game.value(cid);\n\n\t\t\tstd::ostringstream oss;\n\t\t\toss << \"C\" << cc << \"_{\" << csc << \"}\";\n\t\t\tIloExpr lhs(env);\n\t\t\tsubset_iterator sub_end_it(lex_subset.end());\n\t\t\tfor (subset_iterator sub_it = lex_subset.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\ttypename subset_iterator::value_type player_num(*sub_it);\n\n\t\t\t\t// check: player_num is a valid player number\n\t\t\t\tDCS_ASSERT(player_num < n,\n\t\t\t\t\t\t   DCS_EXCEPTION_THROW(::std::runtime_error, \"Invalid player number\"));\n\n\t\t\t\tlhs += x[player_num];\n\t\t\t}\n\t\t\tIloConstraint cons;\n\t\t\tif (players_subset.size() == n)\n\t\t\t{\n\t\t\t\tcons = IloConstraint(lhs == IloNum(v_cid));\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tcons = IloConstraint(lhs >= IloNum(v_cid));\n\t\t\t}\n\t\t\tcons.setName(oss.str().c_str());\n\t\t\tmodel.add(cons);\n\n\t\t\t++lex_subset;\n\t\t}\n\n\n\t\t// Set objective\n\t\t//   max z = \\sum_{i=1}^N x_i\n\t\tIloObjective z;\n\t\tz = IloMaximize(env, IloSum(x));\n\t\tmodel.add(z);\n\n\t\tIloCplex solver(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-core_model.lp\");\n#endif // DCS_DEBUG\n\n\t\t// Set Relative Gap to 1%: CPLEX will stop as soon as it has found a feasible integer solution proved to be within 1% of optimal.\n\t\t//if (relative_gap > 0)\n\t\t//{\n\t\t//\tsolver.setParam(IloCplex::EpGap, relative_gap);\n\t\t//}\n\n\t\tbool solved = solver.solve();\n\n\t\tIloAlgorithm::Status status = solver.getStatus();\n\t\tswitch (status)\n\t\t{\n\t\t\tcase IloAlgorithm::Optimal: // The algorithm found an optimal solution.\n\t\t\tcase IloAlgorithm::Feasible: // The algorithm found a feasible solution, though it may not necessarily be optimal.\n//\n//\t\t\t\tv = static_cast<RealT>(solver.getObjValue());\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\toss << \"Optimization was stopped with status = \" << status << \" (CPLEX status = \" << solver.getCplexStatus() << \", sub-status = \" << solver.getCplexSubStatus() << \")\";\n\t\t\t\tdcs::log_warn(DCS_LOGGING_AT, oss.str());\n\t\t\t}\n\t\t}\n\n\t\tif (solved)\n\t\t{\n#ifdef DCS_DEBUG\n\t\t\tDCS_DEBUG_TRACE( \"-------------------------------------------------------------------------------[\" );\n\t\t\tDCS_DEBUG_TRACE( \"- Objective value: \" << static_cast<real_type>(solver.getObjValue()) );\n\n\t\t\tDCS_DEBUG_TRACE( \"- Decision variables: \" );\n\n\t\t\t// Output x_{i}\n\t\t\tfor (std::size_t i = 0; i < n; ++i)\n\t\t\t{\n\t\t\t\tDCS_DEBUG_STREAM << x[i].getName() << \" = \" << solver.getValue(x[i]) << ::std::endl;\n\t\t\t}\n\n\t\t\tDCS_DEBUG_TRACE( \"]-------------------------------------------------------------------------------\" );\n#endif // DCS_DEBUG\n\n\t\t\t::std::vector<real_type> payoff(n);\n\t\t\tfor (std::size_t i = 0; i < n; ++i)\n\t\t\t{\n\t\t\t\t//payoff[players[i]] = solver.getValue(x[i]);\n\t\t\t\tpayoff[i] = solver.getValue(x[i]);\n\t\t\t}\n\t\t\tkore = core<real_type>(payoff.begin(), payoff.end());\n\t\t}\n\n\t\tz.end();\n\t\tx.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,\n\t\t\t\t\t\t\toss.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\n\treturn kore;\n}\n\n\n/**\n * \\brief Compute the core of the given cooperative game.\n *\n * Given a cooperative game G=(N,v), the core C(v) is the set\n * \\f[\n *  \\biggl\\bigl{x | \\sum_{i \\in N} x_i=v(N), \\text{ and } x_i \\ge v(i) \\forall i \\in N, \\text{ and } \\sum_{i\\in S} x_i \\ge v(S) \\forall S \\subset N\\setminus \\{\\emptyset\\bigr\\}\\biggr\\}\n * \\f]\n */\ntemplate <typename RealT, typename IterT>\nbool belongs_to_core(cooperative_game<RealT> const& game, IterT first_payoff, IterT last_payoff)\n{\n\ttypedef RealT real_type;\n\ttypedef players_coalition<real_type> coalition_type;\n\t//typedef typename coalition_type::cid_type cid_type;\n\ttypedef typename ::dcs::algorithm::lexicographic_subset subset_type;\n\t//typedef typename subset_type::const_iterator subset_iterator;\n\ttypedef typename ::dcs::algorithm::subset_traits<pid_type>::subset_container subset_container;\n\ttypedef typename ::dcs::algorithm::subset_traits<pid_type>::subset_container_const_iterator subset_container_iterator;\n\n\t::std::map<pid_type,real_type> x(first_payoff, last_payoff);\n\t::std::size_t n(game.num_players());\n\t::std::vector<pid_type> players(game.players());\n\n\tsubset_type lex_subset(n, false);\n\n\t// \\forall S \\subset N, \\sum_{i \\in S} x[i] >= v(S), and \\sum_{i \\in N} x[i] = v(N)\n\twhile (lex_subset.has_next())\n\t{\n\t\tsubset_container players_subset;\n\n\t\tplayers_subset = lex_subset(players.begin(), players.end());\n\n\t\tcid_type cid = coalition_type::make_id(players_subset.begin(), players_subset.end());\n\n\t\treal_type v_cid = game.value(cid);\n\t\treal_type xs(0);\n\n\t\tsubset_container_iterator sub_end_it(players_subset.end());\n\t\tfor (subset_container_iterator sub_it = players_subset.begin();\n\t\t\t sub_it != sub_end_it;\n\t\t\t ++sub_it)\n\t\t{\n\t\t\tpid_type player_num(*sub_it);\n\n\t\t\txs += x[player_num];\n\t\t}\n\t\tbool ok;\n\t\tif (lex_subset.size() == n)\n\t\t{\n\t\t\t//ok = xs == v_cid;\n\t\t\tok = ::dcs::math::float_traits<real_type>::essentially_equal(xs, v_cid);\n\t\t}\n\t\telse\n\t\t{\n\t\t\t//ok = xs >= v_cid;\n\t\t\tok = ::dcs::math::float_traits<real_type>::essentially_greater_equal(xs, v_cid);\n\t\t}\n\t\tif (!ok)\n\t\t{\n\t\t\treturn false;\n\t\t}\n\n\t\t++lex_subset;\n\t}\n\n\treturn true;\n}\n\n} // Namespace gtpack\n\n\n#endif // GTPACK_COOPERATIVE_HPP\n", "meta": {"hexsha": "0e3a22a57b95b6fb9589180d1d07f3ddd288ee07", "size": 30543, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/gtpack/cooperative.hpp", "max_stars_repo_name": "sguazt/fog-gt", "max_stars_repo_head_hexsha": "92a01de4f3d71bf89741c7e4af1bebb965c64d28", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-03-26T19:03:40.000Z", "max_stars_repo_stars_event_max_datetime": "2019-03-26T19:03:40.000Z", "max_issues_repo_path": "include/gtpack/cooperative.hpp", "max_issues_repo_name": "sguazt/fog-gt", "max_issues_repo_head_hexsha": "92a01de4f3d71bf89741c7e4af1bebb965c64d28", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/gtpack/cooperative.hpp", "max_forks_repo_name": "sguazt/fog-gt", "max_forks_repo_head_hexsha": "92a01de4f3d71bf89741c7e4af1bebb965c64d28", "max_forks_repo_licenses": ["Apache-2.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.5130208333, "max_line_length": 206, "alphanum_fraction": 0.6761287365, "num_tokens": 8988, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5389832058771035, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.32146744926507514}}
{"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 related to for simple nanostructures:\n/// nanowires and nanoribbons.\n/// This is done using approach developed by Li et. al.\n/// see 10.1103/PhysRevB.85.195436 for theoretical\n/// expressions. Scaling integrals are solved in\n/// non-cartesian coordinates to make them easier\n/// to work with\n\n#include <unordered_map>\n#include <constants.hpp>\n#include <structures.hpp>\n#include <qpoint_grid.hpp>\n#include <processes.hpp>\n#include <isotopic_scattering.hpp>\n#include <boost/mpi.hpp>\n#if BOOST_VERSION >= 106700\n#include <boost/container_hash/hash.hpp>\n#else\n#include <boost/functional/hash.hpp>\n#endif\n#include <Eigen/Dense>\n\n/// Hash for pairs and arrays\nnamespace std {\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};\ntemplate <typename T, std::size_t S> struct hash<std::array<T, S>> {\n    std::size_t operator()(const array<T, S>& key) const {\n        hash<T> backend;\n        std::size_t nruter = 0;\n\n        for (auto& e : key)\n            boost::hash_combine(nruter, backend(e));\n        return nruter;\n    }\n};\n} // namespace std\n\nnamespace alma {\nnamespace nanos {\n\n\n/// Obtain the scaled lifetime for nanowires (see Eq. 8 of\n/// 10.1103/PhysRevB.85.195436) the integral is\n/// analitically solved in cilidrical coordinates\n/// with z-axis being the transport axis\n/// @param[in] tau0 - bulk lifetime\n/// @param[in] uaxis - transport axis ( unitary vector )\n/// @param[in] vel - phonon velocity\n/// @param[in] R - nanowire radii\n/// @return scaled tau\ndouble scale_tau_nanowire(double tau0,\n                          const Eigen::Ref<const Eigen::Vector3d>& uaxis,\n                          const Eigen::Ref<const Eigen::Vector3d>& vel,\n                          double R);\n\n/// Obtain the scaled lifetime for nanoribbons(see Eq. 8 of\n/// 10.1103/PhysRevB.85.195436) the integral is\n/// analitically solved in xy-rotated cartesian\n/// coordinates with new y-axis (y') aligned with\n/// transport axis. The nanoribbon is then centered\n/// and defined from x' = [-L/2,L/2]\n/// NOTE: the nanoribbon is contained in xy plane\n///       otherwise it will fail.\n/// @param[in] tau0 - bulk lifetime\n/// @param[in] uaxis - transport axis (unitary vector)\n/// @param[in] vel - phonon velocity\n/// @param[in] L - nanoribbon width\n/// @return scaled tau\n\ndouble scale_tau_nanoribbon(double tau0,\n                            const Eigen::Ref<const Eigen::Vector3d>& uaxis,\n                            const Eigen::Ref<const Eigen::Vector3d>& vel,\n                            double L);\n\n/// Obtain the thermal conductivity of a nanosystem\n/// under RTA\n///\n/// @param[in] poscar - description of the unit cell\n/// @param[in] grid - phonon spectrum on a regular q-point grid\n/// @param[in] w - RTA scattering rates\n/// @param[in] uaxis - transport axis ( unitary vector )\n/// @param[in] system_name - kind of nanosystem\n/// @param[in] limiting_length - the limiting length of the nanostructure [nm]\n/// @param[in] T - temperature in K\n/// @return the RTA thermal conductivity over transpot axis\ndouble calc_kappa_RTA(const alma::Crystal_structure& poscar,\n                      const alma::Gamma_grid& grid,\n                      const Eigen::Ref<const Eigen::ArrayXXd>& w,\n                      const Eigen::Ref<const Eigen::Vector3d>& uaxis,\n                      const std::string& system_name,\n                      const double limiting_length,\n                      double T);\n\n\n/// Obtain the thermal conductivity of a nanowires system\n/// under the full BTE (beyond Relaxation Time Approximation).\n/// This is achieved by deterministic solution a linear system\n/// over full BZ due to symmetry breaking caused by boundaries\n/// (i.e.: scaling of tau can be different for bulk equivalent\n///    qpoints. Consequently we cannot use some symmetry operations)\n/// @param[in] poscar - description of the unit cell\n/// @param[in] grid - phonon spectrum on a regular q-point grid\n/// @param[in] syms - symmetry operations object\n/// @param[in] emission_processes   - list of 3-phonon emission processes\n/// @param[in] absorption_processes - list of 3-phonon  processes\n/// @param[in] isotopic_processes   - list of 2-phonon processes\n/// @param[in] w0 - RTA scattering rates\n/// @param[in] uaxis - transport axis ( unitary vector )\n/// @param[in] system_name - kind of nanosystem\n/// @param[in] limiting_length - the limiting length of the nanostructure [nm]\n/// @param[in] T - temperature in K\n/// @param[in] iterative - use iterative Eigen solver for faster computation\n/// @param[in] world - mpi communicator\n/// @return the thermal conductivity over transpot axis\ndouble calc_kappa_nanos(\n    const alma::Crystal_structure& poscar,\n    const alma::Gamma_grid& grid,\n    const alma::Symmetry_operations& syms,\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    const Eigen::Ref<const Eigen::ArrayXXd>& w0,\n    const Eigen::Ref<const Eigen::Vector3d>& uaxis,\n    const std::string& system_name,\n    const double limiting_length,\n    double T,\n    bool iterative,\n    boost::mpi::communicator& world);\n\n/// Get processes in full BZ\n/// @param[in] grid - phonon spectrum on a regular q-point grid\n/// @param[in] cell - description of the unit cell\n/// @param[in] syms - symmetry operations object\n/// @param[in,out] emission_processes   - list of 3-phonon emission processes\n/// @param[in,out] absorption_processes - list of 3-phonon  processes\n/// @param[in,out] isotopic_processes   - list of 2-phonon processes\n/// @param[in] world - mpi communicator\n/// @param[in] scalebroad_three - scale parameter for broadening in 3-ph\n/// processes\nvoid get_fullBZ_processes(\n    const alma::Gamma_grid& grid,\n    const alma::Crystal_structure& cell,\n    std::string& anhIFCfile,\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    boost::mpi::communicator& world,\n    double scalebroad_three = 0.1);\n\n} // namespace nanos\n} // namespace alma\n", "meta": {"hexsha": "7a20f188c165359cff87d59ccfd33cfbe2525067", "size": 7260, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/nanos.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/nanos.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/nanos.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": 39.4565217391, "max_line_length": 78, "alphanum_fraction": 0.6807162534, "num_tokens": 1811, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6688802603710086, "lm_q2_score": 0.48047867804790706, "lm_q1q2_score": 0.3213827032754021}}
{"text": "//---------------------------------------------------------------------------//\n// Copyright (c) 2018-2020 Mikhail Komarov <nemo@nil.foundation>\n// Copyright (c) 2020-2021 Ilias Khairullin <ilias@nil.foundation>\n//\n// MIT License\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in all\n// copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n// SOFTWARE.\n//---------------------------------------------------------------------------//\n\n#ifndef CRYPTO3_PUBKEY_BLS_CORE_FUNCTIONS_HPP\n#define CRYPTO3_PUBKEY_BLS_CORE_FUNCTIONS_HPP\n\n#include <utility>\n#include <vector>\n#include <array>\n#include <type_traits>\n#include <iterator>\n#include <algorithm>\n\n#include <boost/assert.hpp>\n#include <boost/concept_check.hpp>\n\n#include <boost/range/concepts.hpp>\n\n#include <nil/crypto3/hash/algorithm/to_curve.hpp>\n\n#include <nil/crypto3/algebra/curves/bls12.hpp>\n\n#include <nil/crypto3/detail/type_traits.hpp>\n\nnamespace nil {\n    namespace crypto3 {\n        namespace pubkey {\n            namespace detail {\n                template<typename policy_type>\n                struct bls_basic_functions {\n                    typedef typename policy_type::curve_type curve_type;\n                    typedef typename policy_type::gt_value_type gt_value_type;\n                    typedef typename policy_type::private_key_type private_key_type;\n                    typedef typename policy_type::public_key_type public_key_type;\n                    typedef typename policy_type::signature_type signature_type;\n                    typedef typename policy_type::h2c_policy h2c_policy;\n\n                    typedef typename policy_type::bls_serializer bls_serializer;\n                    typedef typename policy_type::public_key_serialized_type public_key_serialized_type;\n                    typedef typename policy_type::signature_serialized_type signature_serialized_type;\n\n                    typedef typename policy_type::internal_accumulator_type internal_accumulator_type;\n                    typedef std::pair<std::vector<public_key_type>, std::vector<internal_accumulator_type>>\n                        internal_aggregation_accumulator_type;\n                    typedef std::pair<std::vector<public_key_type>, internal_accumulator_type>\n                        internal_fast_aggregation_accumulator_type;\n\n                    constexpr static const std::size_t private_key_bits = policy_type::private_key_bits;\n                    constexpr static const std::size_t L = static_cast<std::size_t>((3 * private_key_bits) / 16) +\n                                                           static_cast<std::size_t>((3 * private_key_bits) % 16 != 0);\n                    static_assert(L < 0x10000, \"L is required to fit in 2 octets\");\n                    constexpr static const std::array<std::uint8_t, 2> L_os = {static_cast<std::uint8_t>(L >> 8u),\n                                                                               static_cast<std::uint8_t>(L % 0x100)};\n\n                    // TODO: implement key_gen\n                    // template<typename IkmType, typename KeyInfoType>\n                    // static inline private_key_type key_gen(const IkmType &ikm, const KeyInfoType &key_info) {}\n\n                    static inline bool validate_private_key(const private_key_type &sk) {\n                        return !sk.is_zero();\n                    }\n\n                    static inline public_key_type privkey_to_pubkey(const private_key_type &sk) {\n                        BOOST_ASSERT(validate_private_key(sk));\n\n                        return sk * public_key_type::one();\n                    }\n\n                    static inline bool validate_public_key(const public_key_type &pk) {\n                        return !(pk.is_zero() || !pk.is_well_formed());\n                    }\n\n                    template<typename InputRange>\n                    static inline void update(internal_accumulator_type &acc, const InputRange &range) {\n                        BOOST_CONCEPT_ASSERT((boost::SinglePassRangeConcept<InputRange>));\n\n                        to_curve<h2c_policy>(range, acc);\n                    }\n\n                    template<typename InputIterator>\n                    static inline void update(internal_accumulator_type &acc, InputIterator first, InputIterator last) {\n                        BOOST_CONCEPT_ASSERT((boost::InputIteratorConcept<InputIterator>));\n\n                        to_curve<h2c_policy>(first, last, acc);\n                    }\n\n                    static inline signature_type sign(const internal_accumulator_type &acc,\n                                                      const private_key_type &sk) {\n                        BOOST_ASSERT(validate_private_key(sk));\n\n                        signature_type Q = hashes::accumulators::extract::to_curve<h2c_policy>(acc);\n                        return sk * Q;\n                    }\n\n                    static inline bool verify(const internal_accumulator_type &acc, const public_key_type &pk,\n                                              const signature_type &sig) {\n                        /// check if signature point is on the curve\n                        if (!sig.is_well_formed()) {\n                            return false;\n                        }\n                        if (!validate_public_key(pk)) {\n                            return false;\n                        }\n                        signature_type Q = hashes::accumulators::extract::to_curve<h2c_policy>(acc);\n                        auto C1 = policy_type::pairing(Q, pk);\n                        auto C2 = policy_type::pairing(sig, public_key_type::one());\n                        return C1 == C2;\n                    }\n\n                    template<\n                        typename SignatureIterator,\n                        typename = typename std::enable_if<std::is_same<\n                            signature_type, typename std::iterator_traits<SignatureIterator>::value_type>::value>::type>\n                    static inline void aggregate(signature_type &acc, SignatureIterator sig_first,\n                                                 SignatureIterator sig_last) {\n                        BOOST_CONCEPT_ASSERT((boost::InputIteratorConcept<SignatureIterator>));\n                        assert(std::distance(sig_first, sig_last) > 0);\n\n                        while (sig_first != sig_last) {\n                            signature_type next_p = *sig_first++;\n                            acc = acc + next_p;\n                        }\n                    }\n\n                    template<typename SignatureRange,\n                             typename = typename std::enable_if<std::is_same<\n                                 signature_type, typename std::iterator_traits<\n                                                     typename SignatureRange::iterator>::value_type>::value>::type>\n                    static inline void aggregate(signature_type &acc, const SignatureRange &sig_n) {\n                        BOOST_CONCEPT_ASSERT((boost::SinglePassRangeConcept<SignatureRange>));\n\n                        aggregate(acc, std::cbegin(sig_n), std::cend(sig_n));\n                    }\n\n                    static inline bool aggregate_verify(const internal_aggregation_accumulator_type &acc,\n                                                        const signature_type &sig) {\n                        const typename internal_aggregation_accumulator_type::first_type &pk_n = acc.first;\n                        const typename internal_aggregation_accumulator_type::second_type &acc_n = acc.second;\n                        assert(std::distance(pk_n.begin(), pk_n.end()) > 0 &&\n                               std::distance(pk_n.begin(), pk_n.end()) == std::distance(acc_n.begin(), acc_n.end()));\n\n                        if (!sig.is_well_formed()) {\n                            return false;\n                        }\n                        auto pk_n_iter = std::cbegin(pk_n);\n                        auto acc_n_iter = std::cbegin(acc_n);\n                        gt_value_type C1 = gt_value_type::one();\n                        while (pk_n_iter != std::cend(pk_n) && acc_n_iter != std::cend(acc_n)) {\n                            if (!validate_public_key(*pk_n_iter)) {\n                                return false;\n                            }\n                            signature_type Q = hashes::accumulators::extract::to_curve<h2c_policy>(*acc_n_iter++);\n                            C1 = C1 * policy_type::pairing(Q, *pk_n_iter++);\n                        }\n                        return C1 == policy_type::pairing(sig, public_key_type::one());\n                    }\n\n                    static inline bool aggregate_verify(const internal_fast_aggregation_accumulator_type &acc,\n                                                        const signature_type &sig) {\n                        const typename internal_fast_aggregation_accumulator_type::first_type &pk_n = acc.first;\n                        const typename internal_fast_aggregation_accumulator_type::second_type &msg_acc = acc.second;\n                        assert(std::distance(pk_n.begin(), pk_n.end()) > 0);\n\n                        auto pk_n_iter = pk_n.begin();\n                        public_key_type aggregate_p = *pk_n_iter++;\n                        while (pk_n_iter != pk_n.end()) {\n                            public_key_type next_p = *pk_n_iter++;\n                            aggregate_p = aggregate_p + next_p;\n                        }\n                        return verify(msg_acc, aggregate_p, sig);\n                    }\n\n                    static inline signature_type pop_prove(const private_key_type &sk) {\n                        assert(validate_private_key(sk));\n\n                        public_key_type pk = privkey_to_pubkey(sk);\n                        signature_type Q = to_curve<h2c_policy>(point_to_pubkey(pk));\n                        return sk * Q;\n                    }\n\n                    static inline bool pop_verify(const public_key_type &pk, const signature_type &pop) {\n                        if (!pop.is_well_formed()) {\n                            return false;\n                        }\n                        if (!validate_public_key(pk)) {\n                            return false;\n                        }\n                        signature_type Q = to_curve<h2c_policy>(point_to_pubkey(pk));\n                        auto C1 = policy_type::pairing(Q, pk);\n                        auto C2 = policy_type::pairing(pop, public_key_type::one());\n                        return C1 == C2;\n                    }\n\n                    static inline public_key_serialized_type point_to_pubkey(const public_key_type &pk) {\n                        return bls_serializer::point_to_octets_compress(pk);\n                    }\n\n                    static inline signature_serialized_type point_to_signature(const signature_type &sig) {\n                        return bls_serializer::point_to_octets_compress(sig);\n                    }\n                };\n            }    // namespace detail\n        }        // namespace pubkey\n    }            // namespace crypto3\n}    // namespace nil\n\n#endif    // CRYPTO3_PUBKEY_BLS_CORE_FUNCTIONS_HPP\n", "meta": {"hexsha": "0badc42d0383b3117d038af9079f5e11ffcc771a", "size": 12135, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/nil/crypto3/pubkey/detail/bls/bls_basic_functions.hpp", "max_stars_repo_name": "NilFoundation/pubkey", "max_stars_repo_head_hexsha": "3b146d6ed14e127be57895a08846c9e1eea4eade", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/nil/crypto3/pubkey/detail/bls/bls_basic_functions.hpp", "max_issues_repo_name": "NilFoundation/pubkey", "max_issues_repo_head_hexsha": "3b146d6ed14e127be57895a08846c9e1eea4eade", "max_issues_repo_licenses": ["MIT"], "max_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/pubkey/detail/bls/bls_basic_functions.hpp", "max_forks_repo_name": "NilFoundation/pubkey", "max_forks_repo_head_hexsha": "3b146d6ed14e127be57895a08846c9e1eea4eade", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 52.7608695652, "max_line_length": 120, "alphanum_fraction": 0.5393489905, "num_tokens": 2132, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6688802603710086, "lm_q2_score": 0.480478678047907, "lm_q1q2_score": 0.321382703275402}}
{"text": "#include <rovi_pose_estimator/rovi_pose_estimator.h>\n\n#include <iostream>\n#include <vector>\n#include <tuple>\n\n#include <ros/ros.h>\n#include <ros/package.h>\n\n#include <sensor_msgs/PointCloud2.h>\n#include <sensor_msgs/Image.h>\n#include <std_msgs/Int32.h>\n\n#include <Eigen/Eigen>\n#include <eigen_conversions/eigen_msg.h>\n\n#include <opencv4/opencv2/imgproc.hpp>\n#include <opencv4/opencv2/core.hpp>\n#include <opencv4/opencv2/imgcodecs.hpp>\n#include <opencv4/opencv2/highgui.hpp>\n#include <opencv4/opencv2/flann.hpp>\n#include <opencv4/opencv2/calib3d.hpp>\n#include <opencv4/opencv2/stereo.hpp>\n#include <opencv4/opencv2/ximgproc/disparity_filter.hpp>\n#include <opencv4/opencv2/core/eigen.hpp>\n#include <cv_bridge/cv_bridge.h>\n\n#include <pcl/features/normal_3d.h>\n#include <pcl/features/spin_image.h>\n\n#include <pcl/filters/statistical_outlier_removal.h>\n#include <pcl/filters/voxel_grid.h>\n#include <pcl/filters/crop_box.h>\n#include <pcl/filters/passthrough.h>\n\n#include <pcl/kdtree/kdtree_flann.h>\n#include <pcl/visualization/pcl_visualizer.h>\n\n#include <pcl/segmentation/extract_clusters.h>\n#include <pcl/segmentation/sac_segmentation.h>\n\n#include <pcl/sample_consensus/method_types.h>\n#include <pcl/sample_consensus/model_types.h>\n\n#include <pcl/registration/correspondence_rejection_sample_consensus.h>\n#include <pcl/registration/transformation_estimation_svd.h>\n#include <pcl/registration/icp.h>\n\n// #include <pcl/surface/mls.h>\n// #include <pcl/surface/impl/mls.hpp>\n// #include <pcl/surface/bilateral_upsampling.h>\n\n#include <pcl/io/pcd_io.h>\n#include <pcl/io/ply_io.h>\n\n#include <pcl/common/random.h>\n#include <pcl/common/time.h>\n#include <pcl/common/transforms.h>\n\n#include <rovi_gazebo/rovi_gazebo.h>\n#include <rovi_utils/rovi_utils.h>\n\nnamespace rovi_pose_estimator\n{\n\n// Scene\nstatic pcl::PointCloud<pcl::PointXYZRGBNormal>::Ptr cloud_scene_ptr(new pcl::PointCloud<pcl::PointXYZRGBNormal>());\nstatic pcl::PointCloud<pcl::PointXYZRGBNormal>::Ptr cloud_orig_ptr(new pcl::PointCloud<pcl::PointXYZRGBNormal>());\nstatic pcl::PointCloud<pcl::PointXYZRGBNormal>::Ptr filtered_scene_ptr(new pcl::PointCloud<pcl::PointXYZRGBNormal>());\nstatic pcl::PointCloud<pcl::Histogram<153>>::Ptr features_scene_ptr(new pcl::PointCloud<pcl::Histogram<153>>());\n\n// Object\nstatic pcl::PointCloud<pcl::PointXYZRGBNormal>::Ptr cloud_object_ptr(new pcl::PointCloud<pcl::PointXYZRGBNormal>());\nstatic pcl::PointCloud<pcl::PointXYZRGBNormal>::Ptr filtered_object_ptr(new pcl::PointCloud<pcl::PointXYZRGBNormal>());\nstatic pcl::PointCloud<pcl::Histogram<153>>::Ptr features_object_ptr(new pcl::PointCloud<pcl::Histogram<153>>());\n\n// Correspondences\nstatic pcl::Correspondences corr;\n\nstd::array<cv::Mat, 2> \nM1::get_image_data(const std::string & ns_ros)\n{\n    static std::mutex mutex_image_l;\n    static sensor_msgs::Image image_l;\n    static auto thread_left = rovi_utils::create_async_listener(ns_ros + \"/left/image_raw\", image_l, mutex_image_l);\n\n    static std::mutex mutex_image_r;\n    static sensor_msgs::Image image_r;\n    static auto thread_right = rovi_utils::create_async_listener(ns_ros + \"/right/image_raw\", image_r, mutex_image_r);\n\n    static bool first = true;\n\n    std::array<cv::Mat, 2> arr;\n    cv::Mat temp_l, temp_r;\n\n    std::lock_guard<std::mutex> lock_l(mutex_image_l);\n    std::lock_guard<std::mutex> lock_r(mutex_image_r);\n\n    auto ptr_image_l = boost::make_shared<const sensor_msgs::Image>(image_l);\n    auto ptr_image_r = boost::make_shared<const sensor_msgs::Image>(image_r);\n\n    cv_bridge::toCvShare(ptr_image_l, \"bgr8\")->image.copyTo(temp_l);\n    arr[0] = temp_l;\n    cv_bridge::toCvShare(ptr_image_r, \"bgr8\")->image.copyTo(temp_r);\n    arr[1] = temp_r;\n\n    return arr;\n}\n\nvoid\nM1::set_structed_light(ros::NodeHandle & nh, const bool & state)\n{\n    static auto handler = nh.advertise<std_msgs::Int32>(\"/projector_controller/projector\", 1);\n    \n    // spam the buffer\n    ros::Rate lp(200);\n    auto tic = ros::Time::now();\n    while (1.0 > (ros::Time::now() - tic).toSec())\n    {\n        // ROS_INFO_STREAM((ros::Time::now() - tic).toSec());\n        std_msgs::Int32 msg;\n        msg.data = ( state == 1 ) ? 1 : 0;\n        handler.publish(msg);\n        lp.sleep();\n    }\n}\n\nstd::array<sensor_msgs::CameraInfo, 2>\nM1::get_image_info(const std::string & ns_ros)\n{\n    std::array<sensor_msgs::CameraInfo, 2> arr;\n\n    for (const auto & [idx, cam] : std::array{std::tuple(0, std::string(\"/left/camera_info\")), std::tuple(1, std::string(\"/right/camera_info\"))})\n    {\n        // get the message\n        auto msg = ros::topic::waitForMessage<sensor_msgs::CameraInfo>(ns_ros + cam);\n        arr[idx] = *msg;\n    }\n    return arr;\n}\n\ncv::Mat\nM1::compute_disparitymap(const cv::Mat & img_left, const cv::Mat & img_right)\n{   \n    // FileStorage\n    cv::FileStorage fs(\"stereosgbm_config.yaml\", cv::FileStorage::READ);\n\n    static auto min_disp          = 0;\n    static auto num_disp          = 16*8;\n    static auto block_size        = 5; // has to be odd\n    static auto cn                = 3;\n    static auto p1_smoothness     = 100;\n    static auto p2_smoothness     = 400; // he larger the values are, the smoother the disparity is\n    static auto disp_12_max       = 1;\n    static auto unique_ratio      = 5;\n    static auto speckle_win_size  = 0;\n    static auto specke_range      = 1;\n    static auto filter_gap        = 2;\n    static auto written           = 0;\n    static auto lambda            = 2;\n    static auto sigma             = 5;\n\n    // // Check if the file exists\n    fs[\"written\"] >> written;\n    // ROS_INFO_STREAM_ONCE(\"Checking if the file exists stereosgbm_config.yaml exists, the state is: \" << written);\n    // ROS_INFO_STREAM_ONCE(\"If not, write to the file\");\n\n    if (fs.isOpened() && written == 1)\n    {   \n        //read from file\n        fs[\"min_disp\"]         >> min_disp;\n        fs[\"num_disp\"]         >> num_disp;\n        fs[\"block_size\"]       >> block_size;\n        fs[\"cn\"]               >> cn;\n        fs[\"p1_smoothness\"]    >> p1_smoothness;\n        fs[\"p2_smoothness\"]    >> p2_smoothness;\n        fs[\"disp_12_max\"]      >> disp_12_max;\n        fs[\"unique_ratio\"]     >> unique_ratio;\n        fs[\"speckle_win_size\"] >> speckle_win_size;\n        fs[\"specke_range\"]     >> specke_range;\n        fs[\"filter_gap\"]       >> filter_gap;\n        fs[\"lambda\"]           >> lambda;\n        fs[\"sigma\"]            >> sigma;\n    }\n    else\n    {\n        // write to file\n        cv::FileStorage fs1(\"stereosgbm_config.yaml\", cv::FileStorage::WRITE);\n        fs1 << \"written\"          << 1;\n        fs1 << \"min_disp\"         << min_disp;\n        fs1 << \"num_disp\"         << num_disp;\n        fs1 << \"block_size\"       << block_size;\n        fs1 << \"cn\"               << cn;\n        fs1 << \"p1_smoothness\"    << p1_smoothness;\n        fs1 << \"p2_smoothness\"    << p2_smoothness;\n        fs1 << \"disp_12_max\"      << disp_12_max;\n        fs1 << \"unique_ratio\"     << unique_ratio;\n        fs1 << \"speckle_win_size\" << speckle_win_size;\n        fs1 << \"specke_range\"     << specke_range;\n        fs1 << \"filter_gap\"       << filter_gap;\n        fs1 << \"sigma\"            << sigma;\n        fs1 << \"lambda\"           << lambda;\n    }  \n\n    // Write the configurations\n    ROS_INFO_STREAM( min_disp           << \", \" << \n                     num_disp           << \", \" <<  \n                     block_size         << \", \" <<\n                     cn                 << \", \" << \n                     p1_smoothness      << \", \" <<\n                     p2_smoothness      << \", \" <<\n                     disp_12_max        << \", \" <<\n                     unique_ratio       << \", \" <<\n                     speckle_win_size   << \", \" <<\n                     specke_range       << \", \" <<\n                     filter_gap\n                    );\n    \n    // Setup the matchers\n    cv::Ptr<cv::StereoSGBM> left_matcher = cv::StereoSGBM::create(\n                                                                min_disp, \n                                                                num_disp, \n                                                                block_size, \n                                                                p1_smoothness, \n                                                                p2_smoothness, \n                                                                disp_12_max, \n                                                                filter_gap, \n                                                                unique_ratio, \n                                                                speckle_win_size, \n                                                                specke_range, \n                                                                cv::StereoSGBM::MODE_SGBM_3WAY\n                                                              );\n\n    // Use the recomended solvers from OpenCV\n    cv::Ptr<cv::ximgproc::DisparityWLSFilter> wls = cv::ximgproc::createDisparityWLSFilter(left_matcher);\n    cv::Ptr<cv::StereoMatcher> right_matcher = cv::ximgproc::createRightMatcher(left_matcher);\n\n    // For plotting the sets, define 5 cv::Mat\n    cv::Mat disp_left, disp_right, disp_filtered, img_left_temp, img_right_temp, point_cloud;\n\n    // Color convert\n    cv::cvtColor(img_left,  img_left_temp, cv::COLOR_BGR2GRAY);\n    cv::cvtColor(img_right, img_right_temp, cv::COLOR_BGR2GRAY);\n\n    // Remove noise before canny, always.\n    cv::GaussianBlur(img_left_temp, img_left_temp, GAUSS_BLUR_KERNEL, GAUSS_BLUR_STD);\n    cv::GaussianBlur(img_right_temp, img_right_temp, GAUSS_BLUR_KERNEL, GAUSS_BLUR_STD);\n\n    // Compute left and right disparity\n    left_matcher->compute(img_left_temp, img_right_temp, disp_left);\n    right_matcher->compute(img_right_temp, img_left_temp, disp_right);\n\n    // Computed weighted least squares optimization\n    wls->setLambda(lambda);\n    wls->setSigmaColor(sigma);\n    wls->filter(disp_left, img_left, disp_filtered, disp_right);\n\n    // Compute Disparity Map\n    cv::ximgproc::getDisparityVis(disp_filtered, disp_filtered, 1.0);\n    // cv::imwrite(\"disparity_map.jpg\", disp_filtered);\n\n    // Define the Camera matrix\n    static auto cam_info_arr = M1::get_image_info();\n    static Eigen::Matrix<double, 3, 3, Eigen::RowMajor> K_left(cam_info_arr[LEFT].K.data());\n\n    // Compute the Q-matrix\n    static cv::Mat Q = (cv::Mat_<double>(4, 4)<< 1.f, 0.f,  0.f, -K_left(0,2),\n                                                 0.f, 1.f,  0.f, -K_left(1,2),\n                                                 0.f, 0.f,  0.f,  K_left(1,1),\n                                                 0.f, 0.f, -1.f/BASELINE, 0.f );\n\n    // Reproject the image to 3D\n    cv::reprojectImageTo3D(disp_filtered, point_cloud, Q, false);\n\n    return point_cloud;\n};\n\nvoid\nM1::compute_pointcloud_scene(const cv::Mat & point_cloud, const cv::Mat & left_img)\n{\n\n    // cloud_ptr set width etc\n    cloud_scene_ptr->width = point_cloud.cols;\n    cloud_scene_ptr->height = point_cloud.rows;\n    cloud_scene_ptr->is_dense = false;\n    cloud_scene_ptr->resize(cloud_scene_ptr->width * cloud_scene_ptr->height);\n\n    // these are reuqired for the for loop\n    for (int i = 0, m = 0, k = 0; i < point_cloud.rows; ++i)\n    {\n        const float* point_cloud_ele = point_cloud.ptr<float>(i);\n        const uchar* rbg_left = left_img.ptr<uchar>(i);\n        m = 0;\n\n        for(int j = 0; j < point_cloud.cols * 3; )\n        {\n            \n\n            std::uint8_t b = (std::uint8_t) rbg_left[m++];\n            std::uint8_t g = (std::uint8_t) rbg_left[m++];\n            std::uint8_t r = (std::uint8_t) rbg_left[m++];\n\n            cloud_scene_ptr -> points[k].x = point_cloud_ele[j++];\n            cloud_scene_ptr -> points[k].y = point_cloud_ele[j++];\n            cloud_scene_ptr -> points[k].z = point_cloud_ele[j++];\n\n            std::uint32_t rgb = ( (uint32_t) r << 24 | (uint32_t) g << 16 | (uint32_t) b << 8);\n                \n            cloud_scene_ptr -> points[k++].rgb = *reinterpret_cast<float*>(&rgb);\n        }\n    }\n\n    // Compute the transformation matrix from world to gazebo camera\n    static Eigen::Affine3d w_T_gaze;    \n    tf::poseMsgToEigen(rovi_gazebo::get_model_pose(\"camera_stereo\"), w_T_gaze);\n\n    // Get constant OPENGL transformation\n    static Eigen::Matrix4f gaze_T_c  = ( Eigen::Matrix4f() << 0.f, 0.f, 1.f, 0.f, \n                                                             -1.f, 0.f, 0.f, 0.f, \n                                                              0.f,-1.f, 0.f, 0.f, \n                                                              0.f, 0.f, 0.f, 1.f ).finished();\n\n    // Define the overall transformation\n    static Eigen::Matrix4f trans = (w_T_gaze.cast<float>()).matrix() * gaze_T_c;\n\n    // Transform the point cloud \n    pcl::transformPointCloud(*cloud_scene_ptr, *cloud_scene_ptr, trans);\n\n    // Cropbox\n    static pcl::CropBox<pcl::PointXYZRGBNormal> box_filter;\n    {\n        box_filter.setMin(Eigen::Vector4f(0.0, 0.85, 0.70, 1.0f));\n        box_filter.setMax(Eigen::Vector4f(0.8, 1.25, 1.25, 1.0f));\n        box_filter.setInputCloud(cloud_scene_ptr);\n        box_filter.filter(*filtered_scene_ptr);\n        *cloud_scene_ptr = *filtered_scene_ptr;\n        //*cloud_orig_ptr = *cloud_scene_ptr;\n    }\n\n    // Plane fitting\n    constexpr auto dist_tsh = 0.01f;\n    static pcl::ModelCoefficients::Ptr coeff(new pcl::ModelCoefficients);    \n    static pcl::PointIndices::Ptr inliers (new pcl::PointIndices);\n    static pcl::SACSegmentation<pcl::PointXYZRGBNormal> segm;\n    {\n        segm.setOptimizeCoefficients(true);\n        segm.setModelType(pcl::SACMODEL_PLANE);\n        segm.setMethodType(pcl::SAC_RANSAC);\n        segm.setDistanceThreshold(dist_tsh);\n        segm.setInputCloud(cloud_scene_ptr);\n        segm.segment(*inliers, *coeff);\n\n        ROS_INFO_STREAM(\"Number of inliers for plane_segmentation: \" << inliers->indices.size());\n\n        if (inliers->indices.size() != 0 )\n        {\n            double zmin = 0;\n            for (const auto &idx : inliers->indices)\n                zmin += cloud_scene_ptr->points[idx].z;\n            zmin /= inliers->indices.size();\n\n            // Create filtering object  \n            pcl::PassThrough<pcl::PointXYZRGBNormal> pass;\n            pass.setInputCloud(cloud_scene_ptr);\n            pass.setFilterFieldName(\"z\");\n            pass.setFilterLimits(zmin + 0.025, zmin + 1);\n            pass.setFilterLimitsNegative(false);\n            pass.filter(*filtered_scene_ptr);\n            *cloud_scene_ptr = *filtered_scene_ptr;\n        }\n    }\n\n    // Voxel Filter\n    static pcl::VoxelGrid<pcl::PointXYZRGBNormal> voxel_filter;\n    {\n        voxel_filter.setInputCloud(cloud_scene_ptr);\n        voxel_filter.setLeafSize(leaf_size, leaf_size, leaf_size);\n        voxel_filter.filter(*filtered_scene_ptr);\n        *cloud_scene_ptr = *filtered_scene_ptr;\n    }\n\n    // Statistical outlier removal\n    static pcl::StatisticalOutlierRemoval<pcl::PointXYZRGBNormal> sor;\n    {\n        sor.setInputCloud(cloud_scene_ptr);\n        sor.setMeanK(10);\n        sor.setStddevMulThresh(1);\n        sor.filter(*filtered_scene_ptr);\n        *cloud_scene_ptr = *filtered_scene_ptr;\n    }\n\n    // Estimate normals from PoV\n    static pcl::NormalEstimation<pcl::PointXYZRGBNormal, pcl::PointXYZRGBNormal> normal_est;\n    {\n        pcl::search::KdTree<pcl::PointXYZRGBNormal>::Ptr tree(new pcl::search::KdTree<pcl::PointXYZRGBNormal>());\n        normal_est.setInputCloud(cloud_scene_ptr);\n        normal_est.setViewPoint(trans(0,3), trans(1,3), trans(2,3));\n        normal_est.setSearchMethod(tree);\n        normal_est.setKSearch(25);\n        normal_est.compute(*cloud_scene_ptr);\n    }\n\n    static pcl::SpinImageEstimation<pcl::PointXYZRGBNormal, pcl::PointXYZRGBNormal, pcl::Histogram<153>> spin;\n    {\n        spin.setInputCloud(cloud_scene_ptr);\n        spin.setInputNormals(cloud_scene_ptr);\n        spin.setRadiusSearch(0.15);\n        spin.compute(*features_scene_ptr);\n    }\n\n    // Save the pointcloud \n    // pcl::io::savePCDFileASCII(\"scene_voxel.pcd\", *cloud_scene_ptr);\n}\n\nbool\nM1::read_compute_features_object(const std::string & obj)\n{\n\n    int error = pcl::io::loadPCDFile<pcl::PointXYZRGBNormal>(obj, *cloud_object_ptr);\n\n    if(error != 0)\n    {\n        return false;\n    }\n\n    // Compute the transformation matrix from world to gazebo camera\n    static Eigen::Affine3d w_T_gaze;    \n    tf::poseMsgToEigen(rovi_gazebo::get_model_pose(\"camera_stereo\"), w_T_gaze);\n\n    // Get constant OPENGL transformation\n    static Eigen::Matrix4f gaze_T_c  = ( Eigen::Matrix4f() << 0.f, 0.f, 1.f, 0.f, \n                                                             -1.f, 0.f, 0.f, 0.f, \n                                                              0.f,-1.f, 0.f, 0.f, \n                                                              0.f, 0.f, 0.f, 1.f ).finished();\n    // Define the overall transformation\n    static Eigen::Matrix4f trans = (w_T_gaze.cast<float>()).matrix() * gaze_T_c;\n\n    // Give some arbitrary colours to the object\n    for (size_t i = 0; i < cloud_object_ptr->size(); i++)\n    {\n        std::uint8_t b = (std::uint8_t) 200;\n        std::uint8_t g = (std::uint8_t) 150;\n        std::uint8_t r = (std::uint8_t) 128;\n        std::uint32_t rgb = ( (uint32_t) r << 24 | (uint32_t) g << 16 | (uint32_t) b << 8);\n        cloud_object_ptr -> points[i].rgb = *reinterpret_cast<float*>(&rgb);\n    }\n\n    // Voxel Filter\n    static pcl::VoxelGrid<pcl::PointXYZRGBNormal> voxel_filter;\n    {\n        voxel_filter.setInputCloud(cloud_object_ptr);\n        voxel_filter.setLeafSize(leaf_size, leaf_size, leaf_size);\n        voxel_filter.filter(*filtered_object_ptr);\n        *cloud_object_ptr = *filtered_object_ptr;\n    }\n\n    // Estimate normals from PoV\n    static pcl::NormalEstimation<pcl::PointXYZRGBNormal, pcl::PointXYZRGBNormal> normal_est;\n    {\n        pcl::search::KdTree<pcl::PointXYZRGBNormal>::Ptr tree(new pcl::search::KdTree<pcl::PointXYZRGBNormal>());\n        normal_est.setInputCloud(cloud_object_ptr);\n        normal_est.setViewPoint(trans(0,3), trans(1,3), trans(2,3));\n        normal_est.setSearchMethod(tree);\n        normal_est.setKSearch(25);\n        normal_est.compute(*cloud_object_ptr);\n    }\n\n    static pcl::SpinImageEstimation<pcl::PointXYZRGBNormal, pcl::PointXYZRGBNormal, pcl::Histogram<153>> spin;\n    {\n        spin.setInputCloud(cloud_object_ptr);\n        spin.setInputNormals(cloud_object_ptr);\n        spin.setRadiusSearch(0.15);\n        spin.compute(*features_object_ptr);\n    }\n\n    // Save the pointcloud \n    //pcl::io::savePCDFileASCII(\"voxel_object.pcd\", *cloud_object_ptr);\n\n    return true;\n}\n\nvoid \nM1::match_features()\n{\n\n    // Define the L2_norm operator\n    static auto L2_norm = [](const pcl::Histogram<153> & f1, const pcl::Histogram<153> & f2)\n    {\n        float sum = 0.f;\n        for(auto i = 0; i < f1.descriptorSize(); i++)\n            sum += std::pow((f1.histogram[i]-f2.histogram[i]), 2);\n        return sum;\n    };\n\n    // Define nearest neightbour\n    static auto nearest_neighbour = [](const pcl::PointCloud<pcl::Histogram<153>>::Ptr & query, const int idx_query, const pcl::PointCloud<pcl::Histogram<153>>::Ptr & scene, int & idx_scene)\n    {\n        float min_dist = std::numeric_limits<float>::max();\n\n        for(auto i = 0; i < scene->size(); i++)\n        {\n            float dist = L2_norm(query->points[idx_query], scene->points[i]);\n            if (min_dist > dist)\n            {\n                min_dist = dist;\n                idx_scene = i;\n            }\n        }\n\n        return min_dist;\n    };\n\n    // Correspondences are reset.\n    corr.clear();\n    corr.resize(features_object_ptr->size());\n\n    // Start matching\n    int idx_scene = 0;\n    for(auto idx_query = 0; idx_query < features_object_ptr->size(); idx_query++)\n    {\n        corr[idx_query].index_query    = idx_query;\n        corr[idx_query].distance       = nearest_neighbour(features_object_ptr, idx_query, features_scene_ptr, idx_scene);\n        corr[idx_query].index_match    = idx_scene;\n    }\n}\n\nEigen::Matrix4f \nM1::ransac_features(const int & max_it)\n{\n    // Note\n    ROS_INFO_STREAM(\"Amount of iterations: \" << max_it);\n\n    // Metrics\n    int max_inliers = 0;\n    Eigen::Matrix4f best_T, T;\n\n    // Variables\n    std::vector<int> query(3), scene(3);\n    pcl::PointCloud<pcl::PointXYZRGBNormal>::Ptr aligned_object_ptr(new pcl::PointCloud<pcl::PointXYZRGBNormal>());\n\n    // Random generator\n    pcl::common::UniformGenerator<int> rnd_gen(0, corr.size() - 1);\n    rnd_gen.setSeed(time(0));\n\n    // Define search tree\n    pcl::KdTreeFLANN<pcl::PointXYZRGBNormal> kd_tree_scene;\n    kd_tree_scene.setInputCloud(cloud_scene_ptr);\n\n    for(auto i = 0; i < max_it; i++)\n    {   \n        // How far are we?\n        if(i % 500 == 0)\n        {\n            ROS_INFO_STREAM(\"Iteration: \" << i);\n        }\n\n        // Pick 3 points\n        for (auto j = 0; j < 3; j++)\n        {\n            int random = rnd_gen.run();\n            query[j] = corr[random].index_query;\n            scene[j] = corr[random].index_match;\n        }\n        // Determine the transformation between cloud and cloud_object, we use the object and the scene\n        pcl::registration::TransformationEstimationSVD<pcl::PointXYZRGBNormal, pcl::PointXYZRGBNormal> svd;\n        svd.estimateRigidTransformation(*cloud_object_ptr, query, *cloud_scene_ptr, scene, T);\n\n        // Perform the transformation on the two clouds, here we usedaligned\n        pcl::transformPointCloud(*cloud_object_ptr, *aligned_object_ptr, T);\n\n        // Perform NN\n        int K = 1;\n        std::vector<int> point_idx_nn_search(K);\n        std::vector<float> point_nn_L2(K);\n        \n        // Inlier\n        int inliers = 0;\n\n        for (auto j = 0; j < aligned_object_ptr->size(); j++)\n        {\n            if ( kd_tree_scene.nearestKSearch(aligned_object_ptr->points[j], K, point_idx_nn_search, point_nn_L2) > 0 )\n            {   \n                if (point_nn_L2[0] < 0.00001f)\n                {\n                    inliers++;\n                }\n            }\n        }\n\n        if (inliers > max_inliers)\n        {\n            ROS_INFO_STREAM(\"Inliers: \" << inliers);\n            max_inliers = inliers;\n            best_T = T;\n        }\n    }\n\n    pcl::transformPointCloud(*cloud_object_ptr, *cloud_object_ptr, best_T);\n\n    // pcl::visualization::PCLVisualizer viewer(\"vis\");\n    // viewer.addPointCloud<pcl::PointXYZRGBNormal>(cloud_orig_ptr, \"scene\");\n    // viewer.addPointCloud<pcl::PointXYZRGBNormal>(cloud_object_ptr, \"obj\");\n    // viewer.spin();\n\n    pcl::IterativeClosestPoint<pcl::PointXYZRGBNormal, pcl::PointXYZRGBNormal > icp;\n    icp.setInputSource(cloud_object_ptr);\n    icp.setInputTarget(cloud_scene_ptr);\n    icp.setRANSACOutlierRejectionThreshold(leaf_size*1.2);\n    icp.setMaxCorrespondenceDistance(0.005);\n    icp.setEuclideanFitnessEpsilon(1e-9);\n    icp.setTransformationEpsilon(1e-9);\n    icp.setMaximumIterations(20);\n    icp.align(*cloud_object_ptr);\n\n    // viewer.addPointCloud<pcl::PointXYZRGBNormal>(cloud_orig_ptr, \"scene\");\n    // viewer.addPointCloud<pcl::PointXYZRGBNormal>(cloud_object_ptr, \"obj1\");\n    // viewer.spin();\n\n    return icp.getFinalTransformation() * best_T; //;\n\n}\n\ngeometry_msgs::Pose\nM1::estimate_pose(const int & it, const bool & draw, const double & noise)\n{\n    static auto file_bottle_pcd = ros::package::getPath(\"rovi_gazebo\") + std::string(\"/models/bottle/bottle.pcd\");\n\n    // Get stereo images\n    auto cam_images = M1::get_image_data();\n\n    cv::Mat gaussian_noise_left = cv::Mat::zeros(cam_images[0].size(), cam_images[0].type());\n    cv::Mat gaussian_noise_right = gaussian_noise_left;\n    \n    std::vector<double> mean = { 0, 0, 0 };\n    std::vector<double> std = { noise, noise, noise };\n\n    cv::randn(gaussian_noise_left, mean, std);\n    cv::randn(gaussian_noise_right, mean, std);\n\n    if(draw)\n    {\n        cv::imwrite(\"left.jpg\", gaussian_noise_left);\n    }\n\n    cam_images[0] += gaussian_noise_left;\n    cam_images[1] += gaussian_noise_right;\n\n    // Compute the disparity map\n    cv::Mat point_cloud = M1::compute_disparitymap(cam_images[LEFT], cam_images[RIGHT]);\n    \n    if(draw)\n    {\n        cv::imwrite(\"bottle_left.jpg\",  cam_images[0]);\n        cv::imwrite(\"bottle_right.jpg\", cam_images[1]);\n        std::ofstream write_cloud(\"write_mat.mat\", std::ios_base::out);\n        write_cloud << cv::format(point_cloud, cv::Formatter::FMT_CSV) << std::endl;\n        write_cloud.close();\n    }\n    \n    M1::compute_pointcloud_scene(point_cloud, cam_images[0]);\n    M1::read_compute_features_object(file_bottle_pcd);\n    M1::match_features();\n\n    auto T = Eigen::Affine3d(M1::ransac_features(it).cast<double>());\n    geometry_msgs::Pose pose;\n    tf::poseEigenToMsg(T, pose);\n\n    return pose;\n}\n\n\n}", "meta": {"hexsha": "b3c13ffe821497e556faf48fee8a5de2a454fe6c", "size": 24716, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ws/src/rovi_pose_estimator/src/lib_rovi_pose_est_M1.cpp", "max_stars_repo_name": "martinandrovich/rb-rovi", "max_stars_repo_head_hexsha": "223497438923e592b7a0ace3c9a251146fff84ce", "max_stars_repo_licenses": ["OLDAP-2.3", "OLDAP-2.8"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2021-03-15T12:23:16.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-17T23:42:03.000Z", "max_issues_repo_path": "ws/src/rovi_pose_estimator/src/lib_rovi_pose_est_M1.cpp", "max_issues_repo_name": "martinandrovich/rb-rovi", "max_issues_repo_head_hexsha": "223497438923e592b7a0ace3c9a251146fff84ce", "max_issues_repo_licenses": ["OLDAP-2.3", "OLDAP-2.8"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ws/src/rovi_pose_estimator/src/lib_rovi_pose_est_M1.cpp", "max_forks_repo_name": "martinandrovich/rb-rovi", "max_forks_repo_head_hexsha": "223497438923e592b7a0ace3c9a251146fff84ce", "max_forks_repo_licenses": ["OLDAP-2.3", "OLDAP-2.8"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-03-15T12:23:34.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-20T11:53:58.000Z", "avg_line_length": 36.7797619048, "max_line_length": 190, "alphanum_fraction": 0.6030506554, "num_tokens": 6336, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.668880247169804, "lm_q2_score": 0.48047867804790706, "lm_q1q2_score": 0.32138269693250476}}
{"text": "// Copyright 2017 Reinaldo Astudillo and Martin van Gijzen\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 \n// OR 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 \n// DEALINGS IN THE SOFTWARE.\n// \n// IDR(s) for solving systems of linear equations, biorthogonal version.\n//\n// Reference: \n// Martin B. van Gijzen and Peter Sonneveld, Algorithm 913: An Elegant IDR(s) \n// Variant that Efficiently Exploits Bi-orthogonality Properties.\n// ACM Transactions on Mathematical Software, Vol. 38, No. 1, pp. 5:1-5:19, 2011\n\n#ifndef ITL_BIDR_S_INCLUDE\n#define ITL_BIDR_S_INCLUDE\n\n#include <boost/numeric/mtl/concept/collection.hpp>\n#include <boost/numeric/mtl/vector/dense_vector.hpp>\n#include <boost/numeric/mtl/operation/random.hpp>\n#include <boost/numeric/mtl/operation/orth.hpp>\n#include <boost/numeric/mtl/operation/resource.hpp>\n#include <boost/numeric/mtl/matrix/strict_upper.hpp>\n#include <boost/numeric/mtl/utility/exception.hpp>\n#include <boost/numeric/mtl/utility/irange.hpp>\n#include <boost/numeric/linear_algebra/identity.hpp>\n#include <boost/numeric/mtl/interface/vpt.hpp>\n\nnamespace itl {\nusing namespace mtl;\n\n/// Induced Dimension Reduction (IDR(s)) \ntemplate < class LinearOperator, class HilbertSpaceX, class HilbertSpaceB, \n\t   class Preconditioner, class Iteration >\nint idr_s(const LinearOperator& A, HilbertSpaceX& x, const HilbertSpaceB& b, \n\t     const Preconditioner& M, Iteration& iter, size_t s)\n{\n    typedef typename mtl::Collection<HilbertSpaceX>::value_type Scalar;\n    typedef HilbertSpaceX                                       Vector;\n    mtl::vampir_trace<7010> tracer;\n\n    if (size(b) == 0) throw mtl::logic_error(\"empty rhs vector\");\n    if (s < 1) s= 1;\n\n    const Scalar                zero= math::zero(Scalar());\n    const Scalar                one= math::one(Scalar());\n    const double angle = 0.7; \n    Vector                      v(resource(x)), t(resource(x)), r(b - A * x);\n    mat::multi_vector<Vector>   G(Vector(resource(x), zero), s), U(Vector(resource(x), zero), s), P(Vector(resource(x), zero), s);\n    dense_vector<Scalar>   f(s), c(s);\n    mat::dense2D<Scalar>        Ms(s, s); Ms = one;\n    double om = 1.0;\n    random(P);\n    orth(P);\n    // Main iteration loop, build G-spaces:\n    while (! iter.finished(r)) {\n         // New righ-hand size for small system:\n         f = trans(P) * r;\n         for (size_t k= 0; k < s; k++) {\n            // Solve small system and make v orthogonal to P\n            irange range(k, s);\n            c[range] = lower_trisolve(Ms[range][range], f[range]);\n            // Preconditioning\n            v = solve(M, r - G.vector(range)*c[range]);\n            // Compute new U(:,k) and G(:,k), G(:,k) is in space G_j\n            U.vector(k) = U.vector(range)*c[range] + om*v;\n            // Matvec\n            G.vector(k) = A*U.vector(k);\n            // Bi-Orthogonalise the new basis vectors\n            for (size_t i= 0; i < k; i++) {\n                Scalar alpha = dot(P.vector(i), G.vector(k))/Ms[i][i];\n                G.vector(k) = G.vector(k) - alpha*G.vector(i);\n                U.vector(k) = U.vector(k) - alpha*U.vector(i);\n            }\n            // New column of M = P'*G  (first k-1 entries are zero)\n            for (size_t i= k; i < s; i++) {\n                Ms[i][k] = dot(P.vector(i), G.vector(k));\n            }\n            // Make r orthogonal to g_i, i = 1..k \n            Scalar beta = f[k] / Ms[k][k];\n            r = r - beta*G.vector(k);\n            x = x + beta*U.vector(k);\n            if ((++iter).finished(r))\n                return iter;\n            if (k < s-1) {\n               for (size_t i= k+1; i < s; i++) {\n                   f[i] = f[i] - beta*Ms[i][k];\n               }\n            }\n         }\n         // Now we have sufficient vectors in G_j to compute residual in G_j+1\n         // Note: r is already perpendicular to P so v = r\n         // Preconditioning\n         v = solve(M, r);\n         // Matvec\n         t = A*v;\n         // Computation of a new omega\n         double ns = two_norm(r);\n         double nt = two_norm(t);\n         double ts = dot(t, r);\n         double rho = fabs(ts/(nt*ns));\n         om=ts/(nt*nt);\n         if (rho < angle)\n             om = om*angle/rho;\n         r = r - om*t;\n         x = x + om*v;\n         ++iter;\n    }\n    return iter;\n}\n\n\n} // namespace itl\n\n#endif // ITL_BIDR_S_INCLUDE\n", "meta": {"hexsha": "fb43b20d68a74d4670028bf81e3513ac6e3b5e0d", "size": 5293, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/idr_s.hpp", "max_stars_repo_name": "astudillor/idrs_mtl", "max_stars_repo_head_hexsha": "c9600401fe65ecffe813740c440797c4272cccad", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/idr_s.hpp", "max_issues_repo_name": "astudillor/idrs_mtl", "max_issues_repo_head_hexsha": "c9600401fe65ecffe813740c440797c4272cccad", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/idr_s.hpp", "max_forks_repo_name": "astudillor/idrs_mtl", "max_forks_repo_head_hexsha": "c9600401fe65ecffe813740c440797c4272cccad", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.0310077519, "max_line_length": 130, "alphanum_fraction": 0.5996599282, "num_tokens": 1391, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.668880247169804, "lm_q2_score": 0.48047867804790706, "lm_q1q2_score": 0.32138269693250476}}
{"text": "//==============================================================================\n//         Copyright 2003 - 2011 LASMEA UMR 6602 CNRS/Univ. Clermont II\n//         Copyright 2009 - 2011 LRI    UMR 8623 CNRS/Univ Paris Sud XI\n//\n//          Distributed under the Boost Software License, Version 1.0.\n//                 See accompanying file LICENSE.txt or copy at\n//                     http://www.boost.org/LICENSE_1_0.txt\n//==============================================================================\n#ifndef BOOST_SIMD_TOOLBOX_ARITHMETIC_FUNCTIONS_SIMD_COMMON_TWO_PROD_HPP_INCLUDED\n#define BOOST_SIMD_TOOLBOX_ARITHMETIC_FUNCTIONS_SIMD_COMMON_TWO_PROD_HPP_INCLUDED\n#include <boost/simd/toolbox/arithmetic/functions/two_prod.hpp>\n#include <boost/simd/sdk/simd/logical.hpp>\n#include <boost/simd/include/constants/zero.hpp>\n#include <boost/simd/include/functions/simd/minus.hpp>\n#include <boost/simd/include/functions/simd/is_inf.hpp>\n#include <boost/simd/include/functions/simd/if_else.hpp>\n#include <boost/simd/include/functions/simd/two_split.hpp>\n#include <boost/simd/include/functions/simd/multiplies.hpp>\n#include <boost/simd/include/functions/simd/logical_or.hpp>\n#include <boost/simd/include/functions/simd/if_zero_else.hpp>\n#include <boost/simd/include/functions/simd/logical_and.hpp>\n#include <boost/simd/toolbox/arithmetic/functions/two_prod.hpp>\n#include <boost/fusion/tuple.hpp>\n\nnamespace boost { namespace simd { namespace ext\n{\n  BOOST_SIMD_FUNCTOR_IMPLEMENTATION(boost::simd::tag::two_prod_, tag::cpu_,\n                          (A0)(X),\n                          ((simd_<floating_<A0>,X>))\n                          ((simd_<floating_<A0>,X>))\n                          ((simd_<floating_<A0>,X>))\n                          ((simd_<floating_<A0>,X>))\n                         )\n  {\n    typedef int result_type;\n    inline result_type operator()(A0 const& a,A0 const& b,\n                                  A0 & r0,A0 & r1) const\n    {\n      typedef typename meta::as_logical<A0>::type bA0;\n      r0 = a*b;\n      A0 a1, a2, b1, b2;\n      bA0 isinf = logical_and(logical_or(is_inf(b), is_inf(a)), is_inf(r0));\n      two_split(a, a1, a2);\n      two_split(b, b1, b2);\n      r1 = if_zero_else(isinf, a2*b2 -(((r0-a1*b1)-a2*b1)-a1*b2));\n      return 0;\n    }\n  };\n\n  BOOST_SIMD_FUNCTOR_IMPLEMENTATION(boost::simd::tag::two_prod_, tag::cpu_,\n                          (A0)(X),\n                          ((simd_<floating_<A0>,X>))\n                          ((simd_<floating_<A0>,X>))\n                          ((simd_<floating_<A0>,X>))\n                         )\n  {\n    typedef A0 result_type;\n    inline result_type operator()(A0 const& a0,A0 const& a1,A0 & a3) const\n    {\n      A0 a2;\n      two_prod(a0, a1, a2, a3);\n      return a2;\n    }\n  };\n\n  BOOST_SIMD_FUNCTOR_IMPLEMENTATION(boost::simd::tag::two_prod_, tag::cpu_,\n                           (A0)(X),\n                           ((simd_<floating_<A0>,X>))\n                           ((simd_<floating_<A0>,X>))\n                          )\n  {\n    typedef typename boost::fusion::tuple<A0,A0> result_type;\n\n    BOOST_SIMD_FUNCTOR_CALL_REPEAT(2)\n    {\n      result_type res;\n      two_prod(a0,a1, boost::fusion::at_c<0>(res),boost::fusion::at_c<1>(res));\n      return res;\n    }\n  };\n} } }\n#endif\n", "meta": {"hexsha": "6ed2c0b561a0202671d16e53b2acc167e75f674a", "size": 3261, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/boost/simd/arithmetic/include/boost/simd/toolbox/arithmetic/functions/simd/common/two_prod.hpp", "max_stars_repo_name": "timblechmann/nt2", "max_stars_repo_head_hexsha": "6c71f7063ca4e5975c9c019877e6b2fe07c9e4ce", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2016-09-14T00:23:53.000Z", "max_stars_repo_stars_event_max_datetime": "2018-01-14T12:51:18.000Z", "max_issues_repo_path": "modules/boost/simd/arithmetic/include/boost/simd/toolbox/arithmetic/functions/simd/common/two_prod.hpp", "max_issues_repo_name": "timblechmann/nt2", "max_issues_repo_head_hexsha": "6c71f7063ca4e5975c9c019877e6b2fe07c9e4ce", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "modules/boost/simd/arithmetic/include/boost/simd/toolbox/arithmetic/functions/simd/common/two_prod.hpp", "max_forks_repo_name": "timblechmann/nt2", "max_forks_repo_head_hexsha": "6c71f7063ca4e5975c9c019877e6b2fe07c9e4ce", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.2891566265, "max_line_length": 81, "alphanum_fraction": 0.5642440969, "num_tokens": 829, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7606506635289836, "lm_q2_score": 0.42250463481418826, "lm_q1q2_score": 0.3213784308154832}}
{"text": "/*\n * AbstractEquationAdjoint.cpp\n *\n *  Created on: 16.11.2018\n *      Author: thies\n */\n\n#include <deal.II/base/exceptions.h>\n#include <deal.II/base/logstream.h>\n#include <deal.II/base/patterns.h>\n#include <deal.II/base/thread_management.h>\n#include <deal.II/base/timer.h>\n#include <deal.II/base/types.h>\n#include <deal.II/base/utilities.h>\n#include <deal.II/lac/precondition.h>\n#include <deal.II/lac/solver_cg.h>\n#include <deal.II/lac/solver_control.h>\n#include <deal.II/numerics/matrix_tools.h>\n#include <deal.II/numerics/vector_tools.h>\n\n#include <iostream>\n#include <map>\n#include <string>\n\n#include <base/Norm.h>\n#include <forward/AbstractEquationAdjoint.h>\n\nnamespace wavepi {\nnamespace forward {\n\ntemplate <int dim>\nvoid AbstractEquationAdjoint<dim>::next_mesh(size_t source_idx, size_t target_idx) {\n  if (source_idx == mesh->length()) {\n    dof_handler = mesh->get_dof_handler(target_idx);\n\n    system_rhs_u.reinit(dof_handler->n_dofs());\n    system_rhs_v.reinit(dof_handler->n_dofs());\n\n    tmp_u.reinit(dof_handler->n_dofs());\n    tmp_v.reinit(dof_handler->n_dofs());\n  } else\n    dof_handler =\n        mesh->transfer(source_idx, target_idx, {&system_rhs_u, &system_rhs_v, &tmp_u, &tmp_v, &tmp_R_adjoint});\n\n  sparsity_pattern = mesh->get_sparsity_pattern(target_idx);\n  constraints      = mesh->get_constraint_matrix(target_idx);\n\n  matrix_A.reinit(*sparsity_pattern);\n  matrix_B.reinit(*sparsity_pattern);\n  matrix_C.reinit(*sparsity_pattern);\n\n  system_matrix.reinit(*sparsity_pattern);\n\n  rhs.reinit(dof_handler->n_dofs());\n\n  solution_u.reinit(dof_handler->n_dofs());\n  solution_v.reinit(dof_handler->n_dofs());\n}\n\ntemplate <int dim>\nvoid AbstractEquationAdjoint<dim>::cleanup() {\n  matrix_A.clear();\n  matrix_B.clear();\n  matrix_C.clear();\n\n  solution_u.reinit(0);\n  solution_v.reinit(0);\n\n  system_rhs_u.reinit(0);\n  system_rhs_v.reinit(0);\n\n  tmp_u.reinit(0);\n  tmp_v.reinit(0);\n\n  rhs.reinit(0);\n}\n\ntemplate <int dim>\nvoid AbstractEquationAdjoint<dim>::next_step(size_t time_idx) {\n  LogStream::Prefix p(\"next_step\");\n\n  double time = mesh->get_time(time_idx);\n  right_hand_side->set_time(time);\n}\n\ntemplate <int dim>\nvoid AbstractEquationAdjoint<dim>::assemble(size_t i) {\n  double time = mesh->get_time(i);\n  right_hand_side->set_time(time);\n\n  // this helps only a bit because each of the operations is already parallelized\n  Threads::TaskGroup<void> task_group;\n  task_group += Threads::new_task(&AbstractEquationAdjoint<dim>::assemble_matrices, *this, i);\n  task_group += Threads::new_task(&RightHandSide<dim>::create_right_hand_side, *right_hand_side, *dof_handler,\n                                  mesh->get_quadrature(), rhs);\n  task_group.join_all();\n}\n\ntemplate <int dim>\nvoid AbstractEquationAdjoint<dim>::assemble_u_pre(size_t i) {\n  // grid has not been changed yet,\n  // matrix_* contain the matrices of the *last* time step.\n\n  if (i == mesh->length() - 1) {\n    /* i == N\n     *\n     * (M_N^2)^t (u_N, v_N)^t = (g_N, 0)^t\n     *\n     * g_N = ((M_N^2)^t)_11 u_N + ((M_N^2)^t)_12 v_N\n     *     = [k_N^2 C^N + θ k_N B^N + θ^2 A^N] u_N + (1-θ) A^N v_N\n     *     = [k_N^2 C^N + θ k_N B^N + θ^2 A^N] u_N\n     */\n  } else if (i == 0) {\n    /*\n     * (u_0, v_0)^t = (g_0, 0)^t - (M_{i+1}^1)^t (u_1, v_1)^t\n     *\n     * u_0 = g_0 + [-θ(1-θ) A^i + k_{i+1}(k_{i+1} C^{i+1} + θ B^{i+1})] u_1\n     *              - (1-θ) A^i v_1\n     */\n\n    double time_step_last = mesh->get_time(i + 1) - mesh->get_time(i);\n\n    Vector<double> tmp = solution_u;\n    tmp *= 1 / (time_step_last * time_step_last);\n    matrix_C.vmult(system_rhs_u, tmp);\n\n    tmp *= time_step_last * theta;\n    matrix_B.vmult_add(system_rhs_u, tmp);\n\n    tmp_u.equ(-1.0 * theta * (1 - theta), solution_u);\n    tmp_u.add(-1.0 * (1 - theta), solution_v);\n  } else {\n    /*\n     * (M_i^2)^t (u_i, v_i)^t = (g_i, 0)^t - (M_{i+1}^1)^t (u_{i+1}, v_{i+1})^t\n     *\n     * ((M_i^2)^t)_11 u_i = g_i - (M_{i+1}^1)^t_11 u_{i+1} - (M_{i+1}^1)^t_12 v_{i+1} - ((M_i^2)^t)_12 v_i\n     * ╰──────┬─────╯     = g_i + [-θ(1-θ) A^i + k_{i+1}(k_{i+1} C^{i+1} + θ B^{i+1})] u_{i+1}\n     *        │             - (1-θ) A^i v_{i+1} - θ A^i v_i\n     *        │\n     *        ╰‒‒‒  =  [k_i^2 C^i + θ k_i B^i + θ^2 A^i]\n     */\n\n    double time_step_last = mesh->get_time(i + 1) - mesh->get_time(i);\n\n    Vector<double> tmp = solution_u;\n    tmp *= 1 / (time_step_last * time_step_last);\n    matrix_C.vmult(system_rhs_u, tmp);\n\n    tmp *= time_step_last * theta;\n    matrix_B.vmult_add(system_rhs_u, tmp);\n\n    tmp_u.equ(-1.0 * theta * (1 - theta), solution_u);\n    tmp_u.add(-1.0 * (1 - theta), solution_v);\n  }\n}\n\ntemplate <int dim>\nvoid AbstractEquationAdjoint<dim>::assemble_u(size_t i) {\n  if (i == mesh->length() - 1) {\n    /* i == N\n     *\n     * (M_N^2)^t (u_N, v_N)^t = (g_N, 0)^t\n     *\n     * g_N = ((M_N^2)^t)_11 u_N + ((M_N^2)^t)_12 v_N\n     *     = [k_N^2 C^N + θ k_N B^N + θ^2 A^N] u_N + (1-θ) A^N v_N\n     *     = [k_N^2 C^N + θ k_N B^N + θ^2 A^N] u_N\n     */\n\n    double time_step = mesh->get_time(i) - mesh->get_time(i - 1);\n\n    system_rhs_u = rhs;\n\n    system_matrix = 0.0;  // important because it still holds the matrix for v !!\n    system_matrix.add(1.0 / (time_step * time_step), matrix_C);\n    system_matrix.add(theta / time_step, matrix_B);\n    system_matrix.add(theta * theta, matrix_A);\n  } else if (i == 0) {\n    /*\n     * (u₀, v₀)^t = (g₀, 0)^t - (M_{i+1}¹)^t (u₁, v₁)^t\n     *\n     * u₀ = g₀ + [-θ(1-θ) D^{0,1}M⁻¹A⁰ + k₁(k₁ C¹ + θ B¹)] u₁\n     *              - (1-θ) D^{0,1}M⁻¹A⁰ v₁\n     * tmp_u = -θ(1-θ) u₁ - (1-θ) v₁\n     *\n     *        + some D intermediate transposes, but not applied to v_i !\n     */\n\n    Vector<double> tmp1(tmp_u.size());\n    Vector<double> tmp2(tmp_u.size());\n\n    // M⁻¹D^{i,i+1} before multiplying with A^i, then add to system_rhs_u\n    vmult_D_intermediate_transpose(*mesh->get_mass_matrix(i), tmp1, tmp_u, this->solver_tolerance);\n\n    tmp1.add(-theta, solution_v);\n    matrix_A.vmult(tmp2, tmp1);\n    system_rhs_u.add(1.0, tmp2);\n\n    system_rhs_u += rhs;\n\n    system_matrix = IdentityMatrix(solution_u.size());\n  } else {\n    /*\n     * (M_i^2)^t (u_i, v_i)^t = (g_i, 0)^t - (M_{i+1}^1)^t (u_{i+1}, v_{i+1})^t\n     *\n     * ((M_i^2)^t)_11 u_i = g_i - (M_{i+1}^1)^t_11 u_{i+1} - (M_{i+1}^1)^t_12 v_{i+1} - ((M_i^2)^t)_12 v_i\n     * ╰──────┬─────╯     = g_i + [-θ(1-θ) A^i + k_{i+1}(k_{i+1} C^{i+1} + θ B^{i+1})] u_{i+1}\n     *        │             - (1-θ) A^i v_{i+1} - θ A^i v_i\n     *        │\n     *        ╰‒‒‒  =  [k_i^2 C^i + θ k_i B^i + θ^2 A^i]\n     *\n     *        + some D intermediate transposes, but not applied to v_i !\n     */\n\n    Vector<double> tmp1(tmp_v.size());\n    Vector<double> tmp2(tmp_v.size());\n\n    // M⁻¹D^{i,i+1} before multiplying with A^i, then add to system_rhs_u\n    vmult_D_intermediate_transpose(*mesh->get_mass_matrix(i), tmp1, tmp_u, this->solver_tolerance);\n\n    tmp1.add(-theta, solution_v);\n    matrix_A.vmult(tmp2, tmp1);\n    system_rhs_u.add(1.0, tmp2);\n\n    system_rhs_u += rhs;\n\n    double time_step = mesh->get_time(i) - mesh->get_time(i - 1);\n    system_matrix    = 0.0;  // important because it still holds the matrix for v !!\n    system_matrix.add(1.0 / (time_step * time_step), matrix_C);\n    system_matrix.add(theta / time_step, matrix_B);\n    system_matrix.add(theta * theta, matrix_A);\n  }\n\n  // needed, because hanging node constraints are not already built into the sparsity pattern\n  constraints->condense(system_matrix, system_rhs_u);\n\n  apply_boundary_conditions_u(mesh->get_time(i));\n}\n\ntemplate <int dim>\nvoid AbstractEquationAdjoint<dim>::assemble_v_pre(size_t i) {\n  // grid has not been changed yet,\n  // matrix_* contain the matrices of the *last* time step.\n\n  if (i == mesh->length() - 1) {\n    /*\n     * (M_N^2)^t (u_N, v_N)^t = (g_N, 0)^t\n     *\n     * 0 = ((M_N^2)^t)_21 u_N + ((M_N^2)^t)_22 v_N\n     *     \\------------/       \\------------/\n     *           = 0                 /= 0\n     *\n     *     => v_N = 0\n     */\n  } else if (i == 0) {\n    /*\n     * (u_0, v_0)^t = (g_0, 0)^t - (M_{i+1}^1)^t (u_1, v_1)^t\n     *\n     * v_0 = - ((M_{i+1}^1)^t)_21 u_1 - ((M_{i+1}^1)^t)_22 v_1\n     *     = [θ(k_{i+1} C^i - (1-θ) B^i) + (1-θ) (k_{i+1} C^{i+1} + θ B^{i+1})] u_1\n     *       + [k_{i+1} C^i - (1-θ) B^i)] v_1\n     */\n\n    double time_step_last = mesh->get_time(1) - mesh->get_time(0);\n\n    Vector<double> tmp = solution_u;\n    tmp *= (1 - theta) / time_step_last;\n    matrix_C.vmult(system_rhs_v, tmp);\n\n    tmp *= time_step_last * theta;\n    matrix_B.vmult_add(system_rhs_v, tmp);\n\n    tmp_v.equ(theta, solution_u);\n    tmp_v += solution_v;\n  } else {\n    /*\n     * (M_i^2)^t (u_i, v_i)^t = (g_i, 0)^t - (M_{i+1}^1)^t (u_{i+1}, v_{i+1})^t\n     *\n     * ((M_i^2)^t)_22 v_i = - (M_{i+1}^1)^t_21 u_{i+1} - (M_{i+1}^1)^t_22 v_{i+1} - ((M_i^2)^t)_21 u_i\n     * ╰──────┬─────╯     = [θ(k_{i+1} C^i - (1-θ) B^i) + (1-θ) (k_{i+1} C^{i+1} + θ B^{i+1})] u_{i+1}\n     *        │             + [k_{i+1} C^i - (1-θ) B^i)] v_{i+1}\n     *        │\n     *        ╰‒‒‒  =  [k_i C^i + θ B^i]\n     */\n\n    double time_step_last = mesh->get_time(i + 1) - mesh->get_time(i);\n\n    Vector<double> tmp = solution_u;\n    tmp *= (1 - theta) / time_step_last;\n    matrix_C.vmult(system_rhs_v, tmp);\n\n    tmp *= time_step_last * theta;\n    matrix_B.vmult_add(system_rhs_v, tmp);\n\n    tmp_v.equ(theta, solution_u);\n    tmp_v += solution_v;\n  }\n}\n\ntemplate <int dim>\nvoid AbstractEquationAdjoint<dim>::assemble_v(size_t i) {\n  if (i == mesh->length() - 1) {\n    /*\n     * (M_N^2)^t (u_N, v_N)^t = (g_N, 0)^t\n     *\n     * 0 = ((M_N^2)^t)_21 u_N + ((M_N^2)^t)_22 v_N\n     *     \\------------/       \\------------/\n     *           = 0                 /= 0\n     *\n     *     => v_N = 0\n     */\n\n    system_rhs_v  = 0.0;\n    system_matrix = IdentityMatrix(solution_v.size());\n  } else if (i == 0) {\n    /*\n     * (u_0, v_0)^t = (g_0, 0)^t - (M_{i+1}^1)^t (u_1, v_1)^t\n     *\n     * v_0 = - ((M_{i+1}^1)^t)_21 u_1 - ((M_{i+1}^1)^t)_22 v_1\n     *     = [θ(k_{i+1} C^i - (1-θ) B^i) + (1-θ) (k_{i+1} C^{i+1} + θ B^{i+1})] u_1\n     *       + [k_{i+1} C^i - (1-θ) B^i)] v_1\n     *\n     *        + some D intermediate transposes\n     */\n\n    double time_step_last = mesh->get_time(1) - mesh->get_time(0);\n\n    Vector<double> tmp1(tmp_v.size());\n    Vector<double> tmp2(tmp_v.size());\n\n    // C^{0,1} instead of C^0\n    vmult_C_intermediate(tmp1, tmp_v);\n    system_rhs_v.add(1.0 / time_step_last, tmp1);\n\n    // M⁻¹D^{0,1} before multiplying with B^0, then add to system_rhs_v\n    vmult_D_intermediate_transpose(*mesh->get_mass_matrix(i), tmp1, tmp_v, this->solver_tolerance);\n    matrix_B.vmult(tmp2, tmp1);\n    system_rhs_v.add(-1 * (1 - theta), tmp2);\n\n    system_matrix = IdentityMatrix(solution_u.size());\n  } else {\n    /*\n     * (M_i^2)^t (u_i, v_i)^t = (g_i, 0)^t - (M_{i+1}^1)^t (u_{i+1}, v_{i+1})^t\n     *\n     * ((M_i^2)^t)_22 v_i = - (M_{i+1}^1)^t_21 u_{i+1} - (M_{i+1}^1)^t_22 v_{i+1} - ((M_i^2)^t)_21 u_i\n     * ╰──────┬─────╯     = [θ(k_{i+1} C^i - (1-θ) B^i) + (1-θ) (k_{i+1} C^{i+1} + θ B^{i+1})] u_{i+1}\n     *        │             + [k_{i+1} C^i - (1-θ) B^i)] v_{i+1}\n     *        │\n     *        ╰‒‒‒  =  [k_i C^i + θ B^i]\n     *\n     *        + some D intermediate transposes\n     */\n\n    double time_step_last = mesh->get_time(i + 1) - mesh->get_time(i);\n\n    Vector<double> tmp1(tmp_v.size());\n    Vector<double> tmp2(tmp_v.size());\n\n    // C^{i,i+1} instead of C^i\n    vmult_C_intermediate(tmp1, tmp_v);\n    system_rhs_v.add(1.0 / time_step_last, tmp1);\n\n    // M⁻¹D^{i,i+1} before multiplying with B^i, then add to system_rhs_v\n    vmult_D_intermediate_transpose(*mesh->get_mass_matrix(i), tmp1, tmp_v, this->solver_tolerance);\n    matrix_B.vmult(tmp2, tmp1);\n    system_rhs_v.add(-1 * (1 - theta), tmp2);\n\n    // system_matrix <- 0 not needed because matrix was reinited due to possible mesh change\n    double time_step = mesh->get_time(i) - mesh->get_time(i - 1);\n    system_matrix.add(1.0 / time_step, matrix_C);\n    system_matrix.add(theta, matrix_B);\n  }\n\n  // needed, because hanging node constraints are not already built into the sparsity pattern\n  constraints->condense(system_matrix, system_rhs_v);\n\n  apply_boundary_conditions_v(mesh->get_time(i));\n}\n\ntemplate <int dim>\nvoid AbstractEquationAdjoint<dim>::solve_u() {\n  LogStream::Prefix p(\"solve_u\");\n\n  double norm_rhs = system_rhs_u.l2_norm();\n\n  SolverControl solver_control(this->solver_max_iter, this->solver_tolerance * norm_rhs);\n  SolverCG<> cg(solver_control);\n\n  // Fewer (~half) iterations using preconditioner, but at least in 2D this is still not worth the effort\n  // PreconditionSSOR<SparseMatrix<double> > precondition;\n  // precondition.initialize (system_matrix, PreconditionSSOR<SparseMatrix<double> >::AdditionalData(.6));\n  PreconditionIdentity precondition = PreconditionIdentity();\n\n  cg.solve(system_matrix, solution_u, system_rhs_u, precondition);\n  constraints->distribute(solution_u);\n\n  std::ios::fmtflags f(deallog.flags(std::ios_base::scientific));\n  deallog << \"Steps: \" << solver_control.last_step();\n  deallog << \", ‖res‖ = \" << solver_control.last_value();\n  deallog << \", ‖rhs‖ = \" << norm_rhs << std::endl;\n\n  deallog.flags(f);\n}\n\ntemplate <int dim>\nvoid AbstractEquationAdjoint<dim>::solve_v() {\n  LogStream::Prefix p(\"solve_v\");\n\n  double norm_rhs = system_rhs_v.l2_norm();\n\n  SolverControl solver_control(this->solver_max_iter, this->solver_tolerance * norm_rhs);\n  SolverCG<> cg(solver_control);\n\n  // See the comment in solve_u about preconditioning\n  PreconditionIdentity precondition = PreconditionIdentity();\n\n  cg.solve(system_matrix, solution_v, system_rhs_v, precondition);\n  constraints->distribute(solution_v);\n\n  std::ios::fmtflags f(deallog.flags(std::ios_base::scientific));\n\n  deallog << \"Steps: \" << solver_control.last_step();\n  deallog << \", ‖res‖ = \" << solver_control.last_value();\n  deallog << \", ‖rhs‖ = \" << norm_rhs << std::endl;\n\n  deallog.flags(f);\n}\n\ntemplate <int dim>\nDiscretizedFunction<dim> AbstractEquationAdjoint<dim>::run(std::shared_ptr<RightHandSide<dim>> right_hand_side) {\n  LogStream::Prefix p(\"AbstractEqAdj\");\n  Assert(mesh->length() >= 2, ExcInternalError());\n\n  Timer timer, assembly_timer;\n  timer.start();\n\n  // this is going to be the result\n  DiscretizedFunction<dim> res(mesh);\n\n  // save handle to rhs function so that `assemble` and `next_step` can use it\n  this->right_hand_side = right_hand_side;\n\n  for (size_t j = 0; j < mesh->length(); j++) {\n    size_t i = mesh->length() - 1 - j;\n\n    LogStream::Prefix pp(\"step-\" + Utilities::int_to_string(j, 4));\n    double time = mesh->get_time(i);\n\n    // u -> u_old, same for v and matrices\n    next_step(i);\n\n    // assembling that needs to take place on the old grid\n    assemble_v_pre(i);\n    assemble_u_pre(i);\n\n    // set dof_handler to mesh for this time step,\n    // interpolate to new mesh (if j != 0)\n    next_mesh(i + 1, i);\n\n    // assemble new matrices\n    assembly_timer.start();\n    assemble(i);\n    assembly_timer.stop();\n\n    // finish assembling of rhs_v\n    // and solve for $v^i$\n    assemble_v(i);\n    solve_v();\n\n    // finish assembling of rhs_u\n    // and solve for $u^i$\n    assemble_u(i);\n    solve_u();\n\n    /* apply R^t */\n\n    if (i < mesh->length() - 1) {\n      Vector<double> tmp(solution_u.size());\n      vmult_D_intermediate_transpose(*mesh->get_mass_matrix(i), tmp, tmp_R_adjoint, this->solver_tolerance);\n\n      res[i].add(1.0, tmp);\n    }\n\n    if (i > 0) {\n      tmp_R_adjoint.reinit(solution_u.size());\n      tmp_R_adjoint.equ(theta * (1 - theta), solution_u);\n      tmp_R_adjoint.add(1 - theta, solution_v);\n\n      // tmp_R_adjoint has to be transferred to grid i-1 first!\n      // res[i - 1] += \" vmult_D_intermediate_transpose(tmp_R_adjoint) \";\n\n      res[i].add(theta * theta, solution_u);\n      res[i].add(theta, solution_v);\n    }\n\n    std::ios::fmtflags f(deallog.flags(std::ios_base::fixed));\n    deallog << \"t=\" << time << std::scientific << \", \";\n    deallog << \"‖u‖=\" << solution_u.l2_norm() << \", ‖v‖=\" << solution_v.l2_norm() << std::endl;\n    deallog.flags(f);\n  }\n\n  timer.stop();\n  std::ios::fmtflags f(deallog.flags(std::ios_base::fixed));\n  deallog << \"solved adjoint PDE in \" << timer.wall_time() << \"s (setup \" << assembly_timer.wall_time() << \"s)\"\n          << std::endl;\n  deallog.flags(f);\n\n  cleanup();\n\n  return res;\n}\n\ntemplate class AbstractEquationAdjoint<1>;\ntemplate class AbstractEquationAdjoint<2>;\ntemplate class AbstractEquationAdjoint<3>;\n\n} /* namespace forward */\n} /* namespace wavepi */\n", "meta": {"hexsha": "18173e95934cee0b0090c5499cc9920ce6e99809", "size": 16446, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lib/forward/AbstractEquationAdjoint.cpp", "max_stars_repo_name": "thiesgerken/wavepi", "max_stars_repo_head_hexsha": "5af37946dcc1910ad1cccdc76d2e2f546eeafec4", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "lib/forward/AbstractEquationAdjoint.cpp", "max_issues_repo_name": "thiesgerken/wavepi", "max_issues_repo_head_hexsha": "5af37946dcc1910ad1cccdc76d2e2f546eeafec4", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lib/forward/AbstractEquationAdjoint.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": 31.749034749, "max_line_length": 113, "alphanum_fraction": 0.5954639426, "num_tokens": 5678, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7606506526772884, "lm_q2_score": 0.4225046348141882, "lm_q1q2_score": 0.32137842623059165}}
{"text": "// Copyright 2018 Martin Krasser. All Rights Reserved.\n// Modifications copyright (C) 2018 Uber Technologies, Inc.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//     http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n// =============================================================================\n\n#include \"bayesian_optimization.h\"\n\n#include <cmath>\n#include <iostream>\n#include <numeric>\n\n#include <Eigen/LU>\n#include \"LBFGS.h\"\n\nusing Eigen::VectorXd;\nusing Eigen::MatrixXd;\n\nnamespace horovod {\nnamespace common {\n\nconst double NORM_PDF_C = std::sqrt(2 * M_PI);\n\nvoid GetSufficientStats(std::vector<double>& v, double* mu, double* sigma) {\n  double sum = std::accumulate(v.begin(), v.end(), 0.0);\n  *mu = sum / v.size();\n\n  std::vector<double> diff(v.size());\n  std::transform(v.begin(), v.end(), diff.begin(), [mu](double& x) { return x - *mu; });\n  double sq_sum = std::inner_product(diff.begin(), diff.end(), diff.begin(), 0.0);\n  *sigma = std::sqrt(sq_sum / v.size());\n}\n\n// Returns a list of distributions that generate real values uniformly and random between the bounds.\nstd::vector<std::uniform_real_distribution<>> GetDistributions(std::vector<std::pair<double, double>> bounds) {\n  std::vector<std::uniform_real_distribution<>> dists;\n  for (const std::pair<double, double>& bound : bounds) {\n    dists.push_back(std::uniform_real_distribution<>(bound.first, bound.second));\n  }\n  return dists;\n}\n\n\nBayesianOptimization::BayesianOptimization(std::vector<std::pair<double, double>> bounds, double alpha, double xi)\n    : d_(bounds.size()),\n      bounds_(bounds),\n      xi_(xi),\n      dists_(GetDistributions(bounds)),\n      gpr_(GaussianProcessRegressor(alpha)) {}\n\nvoid BayesianOptimization::AddSample(const Eigen::VectorXd& x, double y) {\n  x_samples_.push_back(x);\n  y_samples_.push_back(y);\n}\n\nVectorXd BayesianOptimization::NextSample(bool normalize) {\n  double mu = 0.0;\n  double sigma = 1.0;\n  if (normalize && y_samples_.size() >= 3) {\n    GetSufficientStats(y_samples_, &mu, &sigma);\n  }\n\n  // Matrices are immutable and must be regenerated each time a new sample is added.\n  MatrixXd x_sample(x_samples_.size(), d_);\n  for (unsigned int i = 0; i < x_samples_.size(); ++i) {\n    x_sample.row(i) = x_samples_[i];\n  }\n\n  MatrixXd y_sample(y_samples_.size(), 1);\n  for (unsigned int i = 0; i < y_samples_.size(); ++i) {\n    double norm_score = (y_samples_[i] - mu) / sigma;\n\n    VectorXd y_i(1);\n    y_i(0) = norm_score;\n    y_sample.row(i) = y_i;\n  }\n\n  // Generate the posterior distribution for the GP given the observed data.\n  gpr_.Fit(&x_sample, &y_sample);\n\n  // Return the next proposed location that maximizes the expected improvement.\n  return ProposeLocation(x_sample, y_sample);\n}\n\nvoid BayesianOptimization::Clear() {\n  x_samples_.clear();\n  y_samples_.clear();\n}\n\nVectorXd BayesianOptimization::ProposeLocation(const MatrixXd& x_sample, const MatrixXd& y_sample, int n_restarts) {\n  // Objective function we wish to minimize, the negative acquisition function.\n  auto f = [&](const VectorXd& x) {\n    return -ExpectedImprovement(x.transpose(), x_sample)[0];\n  };\n\n  // Minimization routine. To approximate bounded LBFGS, we set to infinity the value of any input outside of bound.\n  auto min_obj = [&](const VectorXd& x, VectorXd& grad) {\n    double fx = CheckBounds(x) ? f(x) : std::numeric_limits<double>::max();\n    GaussianProcessRegressor::ApproxFPrime(x, f, fx, grad);\n    return fx;\n  };\n\n  // Use the L-BFGS method for minimizing the objective, limit our search to a set number of iterations\n  // if convergence has not be reached within the threshold (epsilon).\n  LBFGSpp::LBFGSParam<double> param;\n  param.epsilon = 1e-5;\n  param.max_iterations = 100;\n  LBFGSpp::LBFGSSolver<double> solver(param);\n\n  // Optimize with random restarts to avoid getting stuck in local minimum.\n  VectorXd x_next = VectorXd::Zero(d_);\n  double fx_min = std::numeric_limits<double>::max();\n  for (int i = 0; i < n_restarts; ++i) {\n    // Generate a random starting point by drawing from our bounded distributions.\n    VectorXd x = VectorXd::Zero(d_);\n    for (unsigned int j = 0; j < d_; ++j) {\n      x[j] = dists_[j](gen_);\n    }\n\n    // Minimize the objective function.\n    double fx;\n    solver.minimize(min_obj, x, fx);\n\n    // Update the new minimum among all attempts.\n    if (fx < fx_min) {\n      fx_min = fx;\n      x_next = x;\n    }\n  }\n\n  // Return the input point that minimized the negative expected improvement.\n  return x_next;\n}\n\nVectorXd BayesianOptimization::ExpectedImprovement(const MatrixXd& x, const MatrixXd& x_sample) {\n  // Compute sufficient statistics for the proposed locations.\n  Eigen::VectorXd mu;\n  Eigen::VectorXd sigma;\n  gpr_.Predict(x, mu, &sigma);\n\n  // Compute sufficient statistics for the observed locations.\n  Eigen::VectorXd mu_sample;\n  gpr_.Predict(x_sample, mu_sample);\n\n  // Needed for noise-based model, otherwise use y_sample.maxCoeff().\n  // See also section 2.4 in https://arxiv.org/pdf/1012.2599.pdf:\n  // Eric Brochu, Vlad M. Cora, Nando de Freitas,\n  // A Tutorial on Bayesian Optimization of Expensive Cost Functions\n  double mu_sample_opt = mu_sample.maxCoeff();\n\n  // Probability density function of the standard normal distribution.\n  auto pdf = [](double x) {\n    return std::exp(-(x * x) / 2.0) / NORM_PDF_C;\n  };\n\n  // Cumulative distribution function of the standard normal distribution.\n  auto cdf = [](double x) {\n    return 0.5 * std::erfc(-x * M_SQRT1_2);\n  };\n\n  // Parameter xi_ determines the amount of exploration during optimization. Higher values of xi_ results\n  // in more exploration. With higher values of xi_, the importance of improvements predicted by the\n  // underlying GP posterior mean mu_sample_opt decreases relative to the importance of improvements\n  // in regions of high prediction uncertainty, as indicated by large values of variable sigma.\n  Eigen::VectorXd imp = mu.array() - mu_sample_opt - xi_;\n  VectorXd z = imp.array() / sigma.array();\n\n  // The first term of the summation is the exploitation term, the second the exploration term.\n  VectorXd ei = imp.cwiseProduct(z.unaryExpr(cdf)) + sigma.cwiseProduct(z.unaryExpr(pdf));\n  ei = (sigma.array() != 0).select(ei, 0.0);\n  return ei;\n}\n\nbool BayesianOptimization::CheckBounds(const Eigen::VectorXd& x) {\n  for (int i = 0; i < x.size(); ++i) {\n    if (x[i] < bounds_[i].first || x[i] > bounds_[i].second) {\n      return false;\n    }\n  }\n  return true;\n}\n\n} // namespace common\n} // namespace horovod\n", "meta": {"hexsha": "c1d8654961f6e70a6bdb847613eec3952c766945", "size": 6920, "ext": "cc", "lang": "C++", "max_stars_repo_path": "horovod/common/optim/bayesian_optimization.cc", "max_stars_repo_name": "Infi-zc/horovod", "max_stars_repo_head_hexsha": "94cd8561a21d449fc8c80c8fef422025b84dfc22", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 7676.0, "max_stars_repo_stars_event_min_datetime": "2019-02-12T02:57:22.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T21:05:40.000Z", "max_issues_repo_path": "horovod/common/optim/bayesian_optimization.cc", "max_issues_repo_name": "Infi-zc/horovod", "max_issues_repo_head_hexsha": "94cd8561a21d449fc8c80c8fef422025b84dfc22", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 2431.0, "max_issues_repo_issues_event_min_datetime": "2019-02-12T01:34:21.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T21:43:38.000Z", "max_forks_repo_path": "horovod/common/optim/bayesian_optimization.cc", "max_forks_repo_name": "Infi-zc/horovod", "max_forks_repo_head_hexsha": "94cd8561a21d449fc8c80c8fef422025b84dfc22", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1557.0, "max_forks_repo_forks_event_min_datetime": "2019-02-12T07:52:15.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T21:05:43.000Z", "avg_line_length": 35.4871794872, "max_line_length": 116, "alphanum_fraction": 0.6924855491, "num_tokens": 1768, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6477982315512488, "lm_q2_score": 0.49609382947091946, "lm_q1q2_score": 0.32136870541474843}}
{"text": "#include <math.h>\n#include <stdio.h>\n#include <stdlib.h>\n\n#include <Eigen/Geometry>\n#include <arc_utilities/arc_helpers.hpp>\n#include <arc_utilities/eigen_typedefs.hpp>\n#include <map>\n#include <vector>\n\n#ifndef ABB_IRB1600_145_FK_FAST_HPP\n#define ABB_IRB1600_145_FK_FAST_HPP\n\nnamespace ABB_IRB1600_145_FK_FAST {\nconst size_t ABB_IRB1600_145_NUM_ACTIVE_JOINTS = 6;\nconst size_t ABB_IRB1600_145_NUM_LINKS = 8;\n\nconst std::string ABB_IRB1600_145_ACTIVE_JOINT_1_NAME = \"joint_1\";\nconst std::string ABB_IRB1600_145_ACTIVE_JOINT_2_NAME = \"joint_2\";\nconst std::string ABB_IRB1600_145_ACTIVE_JOINT_3_NAME = \"joint_3\";\nconst std::string ABB_IRB1600_145_ACTIVE_JOINT_4_NAME = \"joint_4\";\nconst std::string ABB_IRB1600_145_ACTIVE_JOINT_5_NAME = \"joint_5\";\nconst std::string ABB_IRB1600_145_ACTIVE_JOINT_6_NAME = \"joint_6\";\n\nconst std::string ABB_IRB1600_145_LINK_1_NAME = \"link_0\";\nconst std::string ABB_IRB1600_145_LINK_2_NAME = \"link_1\";\nconst std::string ABB_IRB1600_145_LINK_3_NAME = \"link_2\";\nconst std::string ABB_IRB1600_145_LINK_4_NAME = \"link_3\";\nconst std::string ABB_IRB1600_145_LINK_5_NAME = \"link_4\";\nconst std::string ABB_IRB1600_145_LINK_6_NAME = \"link_5\";\nconst std::string ABB_IRB1600_145_LINK_7_NAME = \"link_6\";\nconst std::string ABB_IRB1600_145_LINK_8_NAME = \"link_7\";\n\ninline Eigen::Isometry3d Get_base_joint1_LinkJointTransform(const double joint_val) {\n  Eigen::Translation3d pre_joint_translation(0.0, 0.0, 0.1245);\n  Eigen::Quaterniond pre_joint_rotation(1.0, 0.0, 0.0, 0.0);\n  Eigen::Isometry3d pre_joint_transform = pre_joint_translation * pre_joint_rotation;\n  Eigen::Translation3d joint_translation(0.0, 0.0, 0.0);\n  Eigen::Quaterniond joint_rotation(Eigen::AngleAxisd(joint_val, Eigen::Vector3d::UnitZ()));\n  Eigen::Isometry3d joint_transform = joint_translation * joint_rotation;\n  return (pre_joint_transform * joint_transform);\n}\n\ninline Eigen::Isometry3d Get_link_1_joint_2_LinkJointTransform(const double joint_val) {\n  Eigen::Translation3d pre_joint_translation(0.15, -0.1395, 0.362);\n  Eigen::Quaterniond pre_joint_rotation(1.0, 0.0, 0.0, 0.0);\n  Eigen::Isometry3d pre_joint_transform = pre_joint_translation * pre_joint_rotation;\n  Eigen::Translation3d joint_translation(0.0, 0.0, 0.0);\n  Eigen::Quaterniond joint_rotation(Eigen::AngleAxisd(joint_val, Eigen::Vector3d::UnitY()));\n  Eigen::Isometry3d joint_transform = joint_translation * joint_rotation;\n  return (pre_joint_transform * joint_transform);\n}\n\ninline Eigen::Isometry3d Get_link_2_joint_3_LinkJointTransform(const double joint_val) {\n  Eigen::Translation3d pre_joint_translation(0.0, 0.028, 0.7);\n  Eigen::Quaterniond pre_joint_rotation(1.0, 0.0, 0.0, 0.0);\n  Eigen::Isometry3d pre_joint_transform = pre_joint_translation * pre_joint_rotation;\n  Eigen::Translation3d joint_translation(0.0, 0.0, 0.0);\n  Eigen::Quaterniond joint_rotation(Eigen::AngleAxisd(joint_val, Eigen::Vector3d::UnitY()));\n  Eigen::Isometry3d joint_transform = joint_translation * joint_rotation;\n  return (pre_joint_transform * joint_transform);\n}\n\ninline Eigen::Isometry3d Get_link_3_joint_4_LinkJointTransform(const double joint_val) {\n  Eigen::Translation3d pre_joint_translation(0.314, 0.107, 0.0);\n  Eigen::Quaterniond pre_joint_rotation(1.0, 0.0, 0.0, 0.0);\n  Eigen::Isometry3d pre_joint_transform = pre_joint_translation * pre_joint_rotation;\n  Eigen::Translation3d joint_translation(0.0, 0.0, 0.0);\n  Eigen::Quaterniond joint_rotation(Eigen::AngleAxisd(joint_val, Eigen::Vector3d::UnitX()));\n  Eigen::Isometry3d joint_transform = joint_translation * joint_rotation;\n  return (pre_joint_transform * joint_transform);\n}\n\ninline Eigen::Isometry3d Get_link_4_joint_5_LinkJointTransform(const double joint_val) {\n  Eigen::Translation3d pre_joint_translation(0.286, 0.0, 0.0);\n  Eigen::Quaterniond pre_joint_rotation(1.0, 0.0, 0.0, 0.0);\n  Eigen::Isometry3d pre_joint_transform = pre_joint_translation * pre_joint_rotation;\n  Eigen::Translation3d joint_translation(0.0, 0.0, 0.0);\n  Eigen::Quaterniond joint_rotation(Eigen::AngleAxisd(joint_val, Eigen::Vector3d::UnitY()));\n  Eigen::Isometry3d joint_transform = joint_translation * joint_rotation;\n  return (pre_joint_transform * joint_transform);\n}\n\ninline Eigen::Isometry3d Get_link_5_joint_6_LinkJointTransform(const double joint_val) {\n  Eigen::Translation3d pre_joint_translation(0.0, 0.0, 0.0);\n  Eigen::Quaterniond pre_joint_rotation(1.0, 0.0, 0.0, 0.0);\n  Eigen::Isometry3d pre_joint_transform = pre_joint_translation * pre_joint_rotation;\n  Eigen::Translation3d joint_translation(0.0, 0.0, 0.0);\n  Eigen::Quaterniond joint_rotation(Eigen::AngleAxisd(joint_val, Eigen::Vector3d::UnitX()));\n  Eigen::Isometry3d joint_transform = joint_translation * joint_rotation;\n  return (pre_joint_transform * joint_transform);\n}\n\ninline Eigen::Isometry3d Get_Fixed_link_6_joint_tool_LinkJointTransform(void) {\n  Eigen::Translation3d pre_joint_translation(0.065, 0.0, 0.0);\n  Eigen::Quaterniond pre_joint_rotation(0.7071067811865476, 0.0, 0.7071067811865476, 0.0);\n  Eigen::Isometry3d pre_joint_transform = pre_joint_translation * pre_joint_rotation;\n  return pre_joint_transform;\n}\n\ninline EigenHelpers::VectorIsometry3d GetLinkTransforms(\n    const std::vector<double>& configuration, const Eigen::Isometry3d& base_transform = Eigen::Isometry3d::Identity()) {\n  assert(configuration.size() == ABB_IRB1600_145_NUM_ACTIVE_JOINTS);\n  EigenHelpers::VectorIsometry3d link_transforms(ABB_IRB1600_145_NUM_LINKS);\n  link_transforms[0] = base_transform;\n  link_transforms[1] = link_transforms[0] * Get_base_joint1_LinkJointTransform(configuration[0]);\n  link_transforms[2] = link_transforms[1] * Get_link_1_joint_2_LinkJointTransform(configuration[1]);\n  link_transforms[3] = link_transforms[2] * Get_link_2_joint_3_LinkJointTransform(configuration[2]);\n  link_transforms[4] = link_transforms[3] * Get_link_3_joint_4_LinkJointTransform(configuration[3]);\n  link_transforms[5] = link_transforms[4] * Get_link_4_joint_5_LinkJointTransform(configuration[4]);\n  link_transforms[6] = link_transforms[5] * Get_link_5_joint_6_LinkJointTransform(configuration[5]);\n  link_transforms[7] = link_transforms[6] * Get_Fixed_link_6_joint_tool_LinkJointTransform();\n  return link_transforms;\n}\n\ninline EigenHelpers::VectorIsometry3d GetLinkTransforms(\n    std::map<std::string, double> configuration,\n    const Eigen::Isometry3d& base_transform = Eigen::Isometry3d::Identity()) {\n  std::vector<double> configuration_vector(ABB_IRB1600_145_NUM_ACTIVE_JOINTS);\n  configuration_vector[0] = configuration[ABB_IRB1600_145_ACTIVE_JOINT_1_NAME];\n  configuration_vector[1] = configuration[ABB_IRB1600_145_ACTIVE_JOINT_2_NAME];\n  configuration_vector[2] = configuration[ABB_IRB1600_145_ACTIVE_JOINT_3_NAME];\n  configuration_vector[3] = configuration[ABB_IRB1600_145_ACTIVE_JOINT_4_NAME];\n  configuration_vector[4] = configuration[ABB_IRB1600_145_ACTIVE_JOINT_5_NAME];\n  configuration_vector[5] = configuration[ABB_IRB1600_145_ACTIVE_JOINT_6_NAME];\n  return GetLinkTransforms(configuration_vector, base_transform);\n}\n\ninline EigenHelpers::MapStringIsometry3d GetLinkTransformsMap(\n    const std::vector<double>& configuration, const Eigen::Isometry3d& base_transform = Eigen::Isometry3d::Identity()) {\n  const EigenHelpers::VectorIsometry3d link_transforms = GetLinkTransforms(configuration, base_transform);\n  EigenHelpers::MapStringIsometry3d link_transforms_map;\n  link_transforms_map[ABB_IRB1600_145_LINK_1_NAME] = link_transforms[0];\n  link_transforms_map[ABB_IRB1600_145_LINK_2_NAME] = link_transforms[1];\n  link_transforms_map[ABB_IRB1600_145_LINK_3_NAME] = link_transforms[2];\n  link_transforms_map[ABB_IRB1600_145_LINK_4_NAME] = link_transforms[3];\n  link_transforms_map[ABB_IRB1600_145_LINK_5_NAME] = link_transforms[4];\n  link_transforms_map[ABB_IRB1600_145_LINK_6_NAME] = link_transforms[5];\n  link_transforms_map[ABB_IRB1600_145_LINK_7_NAME] = link_transforms[6];\n  link_transforms_map[ABB_IRB1600_145_LINK_8_NAME] = link_transforms[7];\n  return link_transforms_map;\n}\n\ninline EigenHelpers::MapStringIsometry3d GetLinkTransformsMap(\n    const std::map<std::string, double>& configuration,\n    const Eigen::Isometry3d& base_transform = Eigen::Isometry3d::Identity()) {\n  const EigenHelpers::VectorIsometry3d link_transforms = GetLinkTransforms(configuration, base_transform);\n  EigenHelpers::MapStringIsometry3d link_transforms_map;\n  link_transforms_map[ABB_IRB1600_145_LINK_1_NAME] = link_transforms[0];\n  link_transforms_map[ABB_IRB1600_145_LINK_2_NAME] = link_transforms[1];\n  link_transforms_map[ABB_IRB1600_145_LINK_3_NAME] = link_transforms[2];\n  link_transforms_map[ABB_IRB1600_145_LINK_4_NAME] = link_transforms[3];\n  link_transforms_map[ABB_IRB1600_145_LINK_5_NAME] = link_transforms[4];\n  link_transforms_map[ABB_IRB1600_145_LINK_6_NAME] = link_transforms[5];\n  link_transforms_map[ABB_IRB1600_145_LINK_7_NAME] = link_transforms[6];\n  link_transforms_map[ABB_IRB1600_145_LINK_8_NAME] = link_transforms[7];\n  return link_transforms_map;\n}\n}  // namespace ABB_IRB1600_145_FK_FAST\n\n#endif  // ABB_IRB1600_145_FK_FAST_HPP\n", "meta": {"hexsha": "09cfa14666294fd51a64fcb6d5265e7e5f2cef7f", "size": 9014, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/arc_utilities/abb_irb1600_145_fk_fast.hpp", "max_stars_repo_name": "UM-ARM-Lab/arc_utilities", "max_stars_repo_head_hexsha": "e21bd5062983b25e61e33f832ec66b937540ba10", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2017-01-09T14:37:14.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-16T08:02:08.000Z", "max_issues_repo_path": "include/arc_utilities/abb_irb1600_145_fk_fast.hpp", "max_issues_repo_name": "UM-ARM-Lab/arc_utilities", "max_issues_repo_head_hexsha": "e21bd5062983b25e61e33f832ec66b937540ba10", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 62.0, "max_issues_repo_issues_event_min_datetime": "2017-05-25T16:52:38.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-08T20:05:09.000Z", "max_forks_repo_path": "include/arc_utilities/abb_irb1600_145_fk_fast.hpp", "max_forks_repo_name": "UM-ARM-Lab/arc_utilities", "max_forks_repo_head_hexsha": "e21bd5062983b25e61e33f832ec66b937540ba10", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2017-08-04T13:06:17.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-16T08:02:11.000Z", "avg_line_length": 55.6419753086, "max_line_length": 120, "alphanum_fraction": 0.8119591746, "num_tokens": 2722, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7401743735019594, "lm_q2_score": 0.4339814648038985, "lm_q1q2_score": 0.32122195882268817}}
{"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// Written by Jiahu Deng and Peter Gottschling\n\n#ifndef MTL_DILATED_INT_INCLUDE\n#define MTL_DILATED_INT_INCLUDE\n\n#include <boost/numeric/mtl/detail/masked_dilation_tables.hpp>\n#include <iostream>\n\nnamespace mtl { namespace dilated {\n\ntemplate <typename T>\nstruct even_bits\n{\n    static T const value = T(-1) / T(3);\n};\n    \ntemplate <typename T>\nstruct odd_bits\n{\n    static T const value = ~even_bits<T>::value;\n};\n\n// And is mostly used with original mask\ntemplate <typename T, T BitMask, bool Normalized>\nstruct masking\n{\n    inline void operator() (T& x) const\n    {\n\tx &= BitMask;\n    }\n};\n\n// Or is mostly used with complementary mask\ntemplate <typename T, T BitMask>\nstruct masking<T, BitMask, false>\n{\n    inline void operator() (T& x) const\n    {\n\tstatic T const anti_mask = ~BitMask;\n\tx |= anti_mask;\n    }    \n};\n\ntemplate <typename T, T BitMask>\nstruct last_bit;\n\ntemplate <typename T, T BitMask, bool IsZero>\nstruct last_bit_helper {\n    static T const tmp = BitMask >> 1;\n    static T const value = BitMask & 1 ? 1 : last_bit_helper<T, tmp, tmp == 0>::value << 1;\n};\n\ntemplate <typename T, T BitMask>\nstruct last_bit_helper<T, BitMask, true> {\n    static T const value = 0;\n};\n\ntemplate <typename T, T BitMask>\nstruct last_bit\n{\n    static T const value = last_bit_helper<T, BitMask, BitMask == 0>::value;\n};\n\n\ntemplate <typename T, T BitMask, bool Normalized>\nstruct dilated_int\n{\n    typedef T                                       value_type;\n    typedef dilated_int<T, BitMask, Normalized>     self;\n    \n    typedef masking<T, BitMask, Normalized>         clean_carry;\n    typedef masking<T, BitMask, !Normalized>        init_carry;\n\n    static T const       bit_mask = BitMask,\n\t                 anti_mask = ~BitMask,    \n\t                 dilated_zero = Normalized ? 0 : anti_mask,\n\t\t\t dilated_one = dilated_zero + last_bit<T, bit_mask>::value;\nprotected:\n    // masked_dilation_tables<T, bit_mask>   mask_tables;\n    // masked_dilation_tables<T, anti_mask>  anti_tables; probably not needed\n      \n// will be protected later\npublic:              \n    T i;\n\n    void dilate(T x)\n    {\n\t\tstatic const T to_switch_on = Normalized ? 0 : anti_mask;\n\t\t// auto aa = mask<bit_mask>(x) | to_switch_on;\n\t\t// auto ab = mask<static_cast<T>(bit_mask)>(x) | to_switch_on\n\t\ti = mask<bit_mask>(x) | to_switch_on;\n    }\n\npublic:\n\n    // Default constructor\n    dilated_int()\n    {\n\ti = Normalized ? 0 : anti_mask;\n    }\n    \n    // Only works for odd and even bits and 4-byte-int at this point !!!!!!!!!!!!!!!!!!!\n    explicit dilated_int(T x)\n    {\n\tdilate(x);\n    }\n\n    // Only works for odd and even bits and 4-byte-int at this point !!!!!!!!!!!!!!!!!!!\n    T undilate()\n    {\n\treturn unmask<bit_mask>(i);\n    }\n\n    T dilated_value() const\n    {\n\treturn i;\n    }\n\n    self& operator= (self const& x)\n    {\n\ti = x.i;\n\treturn *this;\n    }\n\n    self& operator= (T x)\n    {\n\tdilate(x);\n\treturn *this;\n    }\n\n    self& operator++ ()\n    {\n\tstatic T const x = Normalized ? bit_mask : T(-1);\n\ti -= x;\n\tclean_carry()(i);\n\treturn *this;\n    }\n\n    self operator++ (int)\n    {\n\tself tmp(*this);\n\t++*this;\n\treturn tmp;\n    }\n\n    self& operator+= (self const& x)\n    {\n\tinit_carry()(i);\n\ti+= x.i;\n\tclean_carry()(i);\n\treturn *this;\n    }\n\n    self operator+ (self const& x)\n    {\n\tself tmp(*this);\n\treturn tmp += x;\n    }\n\n    self& operator-- ()\n    { \n\ti -= dilated_one;\n\tclean_carry()(i);\n\treturn *this;\n    }\n\n    self operator-- (int)\n    {\n\tself tmp(*this);\n\t--*this;\n\treturn tmp;\n    }\n\n    self& operator-= (self const& x)\n    {\n\ti -= x.i;\n\tclean_carry()(i);\n\treturn *this;\n    }\n\t\n    self operator- (self const& x) const\n    {\n\tself tmp(*this);\n\treturn tmp -= x;\n    }\n    \n    // advance in both directions, special care is needed for negative values\n    self& advance(long inc)\n    {\n\tvalue_type incv(inc >= 0 ? inc : -inc);\n\tself incd(incv);\n\tif (inc >= 0)\n\t    operator+=(incd);\n\telse\n\t    operator-=(incd);\n\treturn *this;\n    }\n\n    bool operator== (self const& x) const\n    {\n\treturn i == x.i;\n    }\n\n    bool operator!= (self const& x) const\n    {\n\treturn i != x.i;\n    }\n\n    bool operator<= (self const& x) const\n    {\n\treturn i <= x.i;\n    }\n\n    bool operator< (self const& x) const\n    {\n\treturn i < x.i;\n    }\n\n    bool operator>= (self const& x) const\n    {\n\treturn i >= x.i;\n    }\n\n    bool operator> (self const& x) const\n    {\n\treturn i > x.i;\n    }\n\n\n};\n\n} // namespace mtl::dilated\n\nusing dilated::dilated_int;\n\n} // namespace mtl\n\ntemplate <typename T, T BitMask, bool Normalized>\ninline std::ostream& operator<< (std::ostream& os, mtl::dilated::dilated_int<T, BitMask, Normalized> d)\n{\n    os.setf(std::ios_base::hex, std::ios_base::basefield);\n    return os << d.i;\n}\n\n#endif // MTL_DILATED_INT_INCLUDE\n", "meta": {"hexsha": "e61f9113d8749d0fe4b234ae19f1a8b36aa54ed1", "size": 5179, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/numeric/mtl/detail/dilated_int.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/dilated_int.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/dilated_int.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": 20.0736434109, "max_line_length": 103, "alphanum_fraction": 0.6082255262, "num_tokens": 1447, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6001883735630721, "lm_q2_score": 0.5350984286266115, "lm_q1q2_score": 0.3211598555735616}}
{"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\n#include <cstdio>\n#include <cstdlib>\n#include <stdexcept>\n#include <boost/lexical_cast.hpp>\n\n#include \"kernelregressor.hpp\"\n\n#include \"log.hpp\"\n#include \"ublas_extra.hpp\"\n\n\nnamespace bayesopt\n{\n  KernelRegressor::KernelRegressor(size_t dim, Parameters parameters,\n\t\t\t\t   const Dataset& data,\n\t\t\t\t   MeanModel& mean, randEngine& eng):\n    NonParametricProcess(dim,parameters,data,mean,eng), \n    mRegularizer(parameters.noise),\n    mKernel(dim, parameters),\n    mScoreType(parameters.sc_type),\n    mLearnType(parameters.l_type),\n    mLearnAll(parameters.l_all)\n  { }\n\n  KernelRegressor::~KernelRegressor(){}\n\n\n\n  void KernelRegressor::updateSurrogateModel()\n  {\n    const vectord lastX = mData.getLastSampleX();\n    vectord newK = computeCrossCorrelation(lastX);\n    newK(newK.size()-1) += mRegularizer;   // We add it to the last element\n    utils::cholesky_add_row(mL,newK);\n    precomputePrediction(); \n  } // updateSurrogateModel\n\n\n  void KernelRegressor::computeCholeskyCorrelation()\n  {\n    size_t nSamples = mData.getNSamples();\n    mL.resize(nSamples,nSamples);\n  \n    //  const matrixd K = computeCorrMatrix();\n    matrixd K(nSamples,nSamples);\n    computeCorrMatrix(K);\n    size_t line_error = utils::cholesky_decompose(K,mL);\n    if (line_error) \n      {\n\tthrow std::runtime_error(\"Cholesky decomposition error at line \" + \n\t\t\t\t boost::lexical_cast<std::string>(line_error));\n      }\n  }\n\n  matrixd KernelRegressor::computeDerivativeCorrMatrix(int dth_index)\n  {\n    const size_t nSamples = mData.getNSamples();\n    matrixd corrMatrix(nSamples,nSamples);\n    mKernel.computeDerivativeCorrMatrix(mData.mX,corrMatrix,dth_index);\n    return corrMatrix;\n  }\n\n} //namespace bayesopt\n", "meta": {"hexsha": "7a65735a87d51628d5eb653a13a576d0cdf3c112", "size": 2659, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "external/bayesopt/src/kernelregressor.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/kernelregressor.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/kernelregressor.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": 30.5632183908, "max_line_length": 75, "alphanum_fraction": 0.68597217, "num_tokens": 624, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7025300573952052, "lm_q2_score": 0.4571367168274948, "lm_q1q2_score": 0.3211522839102756}}
{"text": "/*\n\nCopyright (c) 2015, Project OSRM contributors\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without modification,\nare permitted provided that the following conditions are met:\n\nRedistributions of source code must retain the above copyright notice, this list\nof conditions and the following disclaimer.\nRedistributions in binary form must reproduce the above copyright notice, this\nlist of conditions and the following disclaimer in the documentation and/or\nother materials provided with the distribution.\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\n#ifndef HIDDEN_MARKOV_MODEL\n#define HIDDEN_MARKOV_MODEL\n\n#include \"../util/integer_range.hpp\"\n\n#include <boost/assert.hpp>\n\n#include <cmath>\n\n#include <limits>\n#include <vector>\n\nnamespace osrm\n{\nnamespace matching\n{\nstatic const double log_2_pi = std::log(2. * M_PI);\nstatic const double IMPOSSIBLE_LOG_PROB = -std::numeric_limits<double>::infinity();\nstatic const double MINIMAL_LOG_PROB = std::numeric_limits<double>::lowest();\nstatic const std::size_t INVALID_STATE = std::numeric_limits<std::size_t>::max();\n} // namespace matching\n} // namespace osrm\n\n// closures to precompute log -> only simple floating point operations\nstruct EmissionLogProbability\n{\n    double sigma_z;\n    double log_sigma_z;\n\n    EmissionLogProbability(const double sigma_z) : sigma_z(sigma_z), log_sigma_z(std::log(sigma_z))\n    {\n    }\n\n    double operator()(const double distance) const\n    {\n        return -0.5 * (osrm::matching::log_2_pi + (distance / sigma_z) * (distance / sigma_z)) -\n               log_sigma_z;\n    }\n};\n\nstruct TransitionLogProbability\n{\n    double beta;\n    double log_beta;\n    TransitionLogProbability(const double beta) : beta(beta), log_beta(std::log(beta)) {}\n\n    double operator()(const double d_t) const { return -log_beta - d_t / beta; }\n};\n\ntemplate <class CandidateLists> struct HiddenMarkovModel\n{\n    std::vector<std::vector<double>> viterbi;\n    std::vector<std::vector<std::pair<unsigned, unsigned>>> parents;\n    std::vector<std::vector<float>> path_lengths;\n    std::vector<std::vector<bool>> pruned;\n    std::vector<std::vector<bool>> suspicious;\n    std::vector<bool> breakage;\n\n    const CandidateLists &candidates_list;\n    const EmissionLogProbability &emission_log_probability;\n\n    HiddenMarkovModel(const CandidateLists &candidates_list,\n                      const EmissionLogProbability &emission_log_probability)\n        : breakage(candidates_list.size()), candidates_list(candidates_list),\n          emission_log_probability(emission_log_probability)\n    {\n        viterbi.resize(candidates_list.size());\n        parents.resize(candidates_list.size());\n        path_lengths.resize(candidates_list.size());\n        suspicious.resize(candidates_list.size());\n        pruned.resize(candidates_list.size());\n        breakage.resize(candidates_list.size());\n        for (const auto i : osrm::irange<std::size_t>(0u, candidates_list.size()))\n        {\n            const auto& num_candidates = candidates_list[i].size();\n            // add empty vectors\n            if (num_candidates > 0)\n            {\n                viterbi[i].resize(num_candidates);\n                parents[i].resize(num_candidates);\n                path_lengths[i].resize(num_candidates);\n                suspicious[i].resize(num_candidates);\n                pruned[i].resize(num_candidates);\n            }\n        }\n\n        clear(0);\n    }\n\n    void clear(std::size_t initial_timestamp)\n    {\n        BOOST_ASSERT(viterbi.size() == parents.size() && parents.size() == path_lengths.size() &&\n                     path_lengths.size() == pruned.size() && pruned.size() == breakage.size());\n\n        for (const auto t : osrm::irange(initial_timestamp, viterbi.size()))\n        {\n            std::fill(viterbi[t].begin(), viterbi[t].end(), osrm::matching::IMPOSSIBLE_LOG_PROB);\n            std::fill(parents[t].begin(), parents[t].end(), std::make_pair(0u, 0u));\n            std::fill(path_lengths[t].begin(), path_lengths[t].end(), 0);\n            std::fill(suspicious[t].begin(), suspicious[t].end(), true);\n            std::fill(pruned[t].begin(), pruned[t].end(), true);\n        }\n        std::fill(breakage.begin() + initial_timestamp, breakage.end(), true);\n    }\n\n    std::size_t initialize(std::size_t initial_timestamp)\n    {\n        auto num_points = candidates_list.size();\n        do\n        {\n            BOOST_ASSERT(initial_timestamp < num_points);\n\n            for (const auto s : osrm::irange<std::size_t>(0u, viterbi[initial_timestamp].size()))\n            {\n                viterbi[initial_timestamp][s] =\n                    emission_log_probability(candidates_list[initial_timestamp][s].second);\n                parents[initial_timestamp][s] = std::make_pair(initial_timestamp, s);\n                pruned[initial_timestamp][s] =\n                    viterbi[initial_timestamp][s] < osrm::matching::MINIMAL_LOG_PROB;\n                suspicious[initial_timestamp][s] = false;\n\n                breakage[initial_timestamp] =\n                    breakage[initial_timestamp] && pruned[initial_timestamp][s];\n            }\n\n            ++initial_timestamp;\n        } while (initial_timestamp < num_points && breakage[initial_timestamp - 1]);\n\n        if (initial_timestamp >= num_points)\n        {\n            return osrm::matching::INVALID_STATE;\n        }\n\n        BOOST_ASSERT(initial_timestamp > 0);\n        --initial_timestamp;\n\n        BOOST_ASSERT(breakage[initial_timestamp] == false);\n\n        return initial_timestamp;\n    }\n};\n\n#endif // HIDDEN_MARKOV_MODEL\n", "meta": {"hexsha": "15aa35b8b6849f501d6b971140f57a2b4f34f60b", "size": 6288, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "data_structures/hidden_markov_model.hpp", "max_stars_repo_name": "Mapotempo/osrm-backend", "max_stars_repo_head_hexsha": "a62c10321c0a269e218ab4164c4ccd132048f271", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2016-11-29T15:02:40.000Z", "max_stars_repo_stars_event_max_datetime": "2016-11-29T15:02:40.000Z", "max_issues_repo_path": "data_structures/hidden_markov_model.hpp", "max_issues_repo_name": "Mapotempo/osrm-backend", "max_issues_repo_head_hexsha": "a62c10321c0a269e218ab4164c4ccd132048f271", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-02-04T18:10:57.000Z", "max_issues_repo_issues_event_max_datetime": "2019-02-04T18:10:57.000Z", "max_forks_repo_path": "data_structures/hidden_markov_model.hpp", "max_forks_repo_name": "Mapotempo/osrm-backend", "max_forks_repo_head_hexsha": "a62c10321c0a269e218ab4164c4ccd132048f271", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.7719298246, "max_line_length": 99, "alphanum_fraction": 0.6723918575, "num_tokens": 1363, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6791786991753931, "lm_q2_score": 0.47268347662043286, "lm_q1q2_score": 0.32103654877276794}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\n// This file is manually converted from PROJ4\n\n// Copyright (c) 2008-2012 Barend Gehrels, Amsterdam, the Netherlands.\n\n// Use, modification and distribution is subject to the Boost Software License,\n// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n\n// This file is converted from PROJ4, http://trac.osgeo.org/proj\n// PROJ4 is originally written by Gerald Evenden (then of the USGS)\n// PROJ4 is maintained by Frank Warmerdam\n// PROJ4 is converted to Geometry Library by Barend Gehrels (Geodan, Amsterdam)\n\n// Original copyright notice:\n\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the \"Software\"),\n// to deal in the Software without restriction, including without limitation\n// the rights to use, copy, modify, merge, publish, distribute, sublicense,\n// and/or sell copies of the Software, and to permit persons to whom the\n// Software is furnished to do so, subject to the following conditions:\n\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n// DEALINGS IN THE SOFTWARE.\n\n#ifndef BOOST_GEOMETRY_PROJECTIONS_IMPL_PJ_ELL_SET_HPP\n#define BOOST_GEOMETRY_PROJECTIONS_IMPL_PJ_ELL_SET_HPP\n\n#include <string>\n#include <vector>\n\n#include <boost/geometry/util/math.hpp>\n\n#include <boost/geometry/extensions/gis/projections/impl/pj_ellps.hpp>\n#include <boost/geometry/extensions/gis/projections/impl/pj_param.hpp>\n\nnamespace boost { namespace geometry { namespace projections {\n\nnamespace detail {\n\n/* set ellipsoid parameters a and es */\nstatic const double SIXTH =  .1666666666666666667; /* 1/6 */\nstatic const double RA4 = .04722222222222222222; /* 17/360 */\nstatic const double RA6 = .02215608465608465608; /* 67/3024 */\nstatic const double RV4 = .06944444444444444444; /* 5/72 */\nstatic const double RV6 = .04243827160493827160; /* 55/1296 */\n\n/* initialize geographic shape parameters */\ninline void pj_ell_set(std::vector<pvalue>& parameters, double &a, double &es)\n{\n    double b = 0.0;\n    double e = 0.0;\n    std::string name;\n\n    /* check for varying forms of ellipsoid input */\n    a = es = 0.;\n\n    /* R takes precedence */\n    if (pj_param(parameters, \"tR\").i)\n        a = pj_param(parameters, \"dR\").f;\n    else { /* probable elliptical figure */\n\n        /* check if ellps present and temporarily append its values to pl */\n        name = pj_param(parameters, \"sellps\").s;\n        if (! name.empty())\n        {\n            const int n = sizeof(pj_ellps) / sizeof(pj_ellps[0]);\n            int index = -1;\n            for (int i = 0; i < n && index == -1; i++)\n            {\n                if(pj_ellps[i].id == name)\n                {\n                    index = i;\n                }\n            }\n\n            if (index == -1) { throw proj_exception(-9); }\n\n            parameters.push_back(pj_mkparam(pj_ellps[index].major));\n            parameters.push_back(pj_mkparam(pj_ellps[index].ell));\n        }\n        a = pj_param(parameters, \"da\").f;\n        if (pj_param(parameters, \"tes\").i) /* eccentricity squared */\n            es = pj_param(parameters, \"des\").f;\n        else if (pj_param(parameters, \"te\").i) { /* eccentricity */\n            e = pj_param(parameters, \"de\").f;\n            es = e * e;\n        } else if (pj_param(parameters, \"trf\").i) { /* recip flattening */\n            es = pj_param(parameters, \"drf\").f;\n            if (!es) {\n                throw proj_exception(-10);\n            }\n            es = 1./ es;\n            es = es * (2. - es);\n        } else if (pj_param(parameters, \"tf\").i) { /* flattening */\n            es = pj_param(parameters, \"df\").f;\n            es = es * (2. - es);\n        } else if (pj_param(parameters, \"tb\").i) { /* minor axis */\n            b = pj_param(parameters, \"db\").f;\n            es = 1. - (b * b) / (a * a);\n        }     /* else es == 0. and sphere of radius a */\n        if (!b)\n            b = a * sqrt(1. - es);\n        /* following options turn ellipsoid into equivalent sphere */\n        if (pj_param(parameters, \"bR_A\").i) { /* sphere--area of ellipsoid */\n            a *= 1. - es * (SIXTH + es * (RA4 + es * RA6));\n            es = 0.;\n        } else if (pj_param(parameters, \"bR_V\").i) { /* sphere--vol. of ellipsoid */\n            a *= 1. - es * (SIXTH + es * (RV4 + es * RV6));\n            es = 0.;\n        } else if (pj_param(parameters, \"bR_a\").i) { /* sphere--arithmetic mean */\n            a = .5 * (a + b);\n            es = 0.;\n        } else if (pj_param(parameters, \"bR_g\").i) { /* sphere--geometric mean */\n            a = sqrt(a * b);\n            es = 0.;\n        } else if (pj_param(parameters, \"bR_h\").i) { /* sphere--harmonic mean */\n            a = 2. * a * b / (a + b);\n            es = 0.;\n        } else {\n            int i = pj_param(parameters, \"tR_lat_a\").i;\n            if (i || /* sphere--arith. */\n                pj_param(parameters, \"tR_lat_g\").i) { /* or geom. mean at latitude */\n                double tmp;\n\n                tmp = sin(pj_param(parameters, i ? \"rR_lat_a\" : \"rR_lat_g\").f);\n                if (geometry::math::abs(tmp) > geometry::math::half_pi<double>()) {\n                    throw proj_exception(-11);\n                }\n                tmp = 1. - es * tmp * tmp;\n                a *= i ? .5 * (1. - es + tmp) / ( tmp * sqrt(tmp)) :\n                    sqrt(1. - es) / tmp;\n                es = 0.;\n            }\n        }\n    }\n\n    /* some remaining checks */\n    if (es < 0.)\n        { throw proj_exception(-12); }\n    if (a <= 0.)\n        { throw proj_exception(-13); }\n}\n\n} // namespace detail\n}}} // namespace boost::geometry::projections\n\n#endif // BOOST_GEOMETRY_PROJECTIONS_IMPL_PJ_ELL_SET_HPP\n", "meta": {"hexsha": "98f84917e13a959d8031dc62a7ca6c76e61ae825", "size": 6267, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "3party/boost/boost/geometry/extensions/gis/projections/impl/pj_ell_set.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/impl/pj_ell_set.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/impl/pj_ell_set.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": 39.664556962, "max_line_length": 85, "alphanum_fraction": 0.5872028084, "num_tokens": 1634, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6959583250334526, "lm_q2_score": 0.46101677931231594, "lm_q1q2_score": 0.3208484655425162}}
{"text": "/**\n *  staticplan.cpp\n *\n *  Generate a static plan for a planar vehicle to satisfy a DBA\n *  by using abstraction-based control synthesis.\n *\n *  Created by Yinan Li on Feb. 8, 2021.\n *  Hybrid Systems Group, University of Waterloo.\n */\n\n\n#include <iostream>\n#include <fstream>\n#include <sstream>\n#include <iomanip>\n#include <cstdlib>\n#include <sys/stat.h>\n#include <boost/algorithm/string.hpp>\n\n#include \"src/DBAparser.h\"\n#include \"src/abstraction.hpp\"\n\n#include \"src/bsolver.hpp\"\n#include \"src/patcher.h\"\n\n#include \"src/hdf5io.h\"\n\n#include \"car.hpp\"\n\n\nint main(int argc, char *argv[])\n{\n    /**\n     * Default values\n     **/\n    std::string specfile;\n    double eta[]{0.2, 0.2, 0.2}; /* partition precision */\n\n    /* Input arguments:\n     * carAbst dbafile precision(e.g. 0.2 0.2 0.2)\n     */\n    if (argc < 2 || argc > 5) {\n\tstd::cout << \"Improper number of arguments.\\n\";\n\tstd::exit(1);\n    }\n    specfile = std::string(argv[1]);\n    if (argc > 2 && argc < 4) {\n\tstd::cout << \"Input precision should be of 3-dim, e.g. 0.2 0.2 0.2.\\n\";\n\tstd::exit(1);\n    }\n    if (argc == 5) {\n\tfor(int i = 2; i < 5; ++i)\n\t    eta[i-2] = std::atof(argv[i]);\n    }\n    std::cout << \"Partition precision: \" << eta[0] << ' '\n\t      << eta[1] << ' ' << eta[2] << '\\n';\n\n    clock_t tb, te;\n    /* set the state space */\n    const double theta = 3.5;\n    double xlb[] = {0, 0, -theta};\n    double xub[] = {10, 10, theta};\n    /* set the control values */\n    double ulb[] = {-1.0, -1.0};\n    double uub[] = {1.0, 1.0};\n    double mu[] = {0.3, 0.3};\n    /* define the control system */\n    rocs::DTCntlSys<carde> car(\"DBA\", tau, carde::n, carde::m);\n    car.init_workspace(xlb, xub);\n    car.init_inputset(mu, ulb, uub);\n\n\n    /**\n     * Construct and save the abstraction\n     */\n    // const double eta[] = {0.2, 0.2, 0.2}; /* set precision */\n    rocs::abstraction<rocs::DTCntlSys<carde>> abst(&car);\n    abst.init_state(eta, xlb, xub);\n    std::cout << \"The number of abstraction states: \" << abst._x._nv << '\\n';\n    /* Assign the label of avoid area to -1 */\n    rocs::UintSmall nAvoid = 6;\n    double obs[6][4] = {\n\t{0.0, 1.0, 4.6, 6.4},\n\t{2.0, 3.0, 0.0, 3.6},\n\t{3.5, 4.5, 8.5, 10.0}, //{3.5, 4.5, 7.5, 10.0},\n\t{5.5, 6.5, 0.0, 1.0},\n\t{5.5, 6.5, 3.4, 5.5}, //{5.5, 6.5, 3.4, 6.5},\n\t{6.5, 10.0, 4.5, 5.5} //{6.5, 10.0, 5.5, 6.5}\n    };\n    auto label_avoid = [&obs, &nAvoid, &abst, &eta](size_t i) {\n    \t\t     std::vector<double> x(abst._x._dim);\n    \t\t     abst._x.id_to_val(x, i);\n    \t\t     double c1= eta[0]/2.0; //+1e-10;\n    \t\t     double c2= eta[1]/2.0; //+1e-10;\n    \t\t     for(size_t i = 0; i < nAvoid; ++i) {\n    \t\t\t if ((obs[i][0]-c1) <= x[0] && x[0] <= (obs[i][1]+c1) &&\n    \t\t\t     (obs[i][2]-c2) <= x[1] && x[1] <= (obs[i][3]+c2))\n    \t\t\t     return -1;\n    \t\t     }\n    \t\t     return 0;\n    \t\t };\n    abst.assign_labels(label_avoid);\n    abst.assign_label_outofdomain(-1); // out of domain is banned\n    std::vector<size_t> obstacles;\n    for (size_t i = 0; i < abst._x._nv; ++i) {\n    \tif (abst._labels[i] < 0)\n    \t    obstacles.push_back(i);\n    }\n    /* Compute abstraction */\n    std::string suffix;\n    for(auto &item : eta) {\n\tstd::stringstream ss;\n    \tss << std::setprecision(1);\n\tss << item;\n\tsuffix += '-';\n\tsuffix += ss.str();\n    }\n    std::string transfile = \"abstfull\" + suffix + \".h5\";\n    struct stat buffer;\n    float tabst;\n    if(stat(transfile.c_str(), &buffer) == 0) {\n\t/* Read from a file */\n\tstd::cout << \"Transitions have been computed. Reading transitions...\\n\";\n\trocs::h5FileHandler transRdr(transfile, H5F_ACC_RDONLY);\n\ttb = clock();\n\ttransRdr.read_transitions(abst._ts);\n\tte = clock();\n\ttabst = (float)(te - tb)/CLOCKS_PER_SEC;\n\tstd::cout << \"Time of reading abstraction: \" << tabst << '\\n';\n\tstd::cout << \"# of transitions: \" << abst._ts._ntrans << '\\n';\n    } else {\n\tstd::cout << \"Transitions haven't been computed. Computing transitions...\\n\";\n\t/* Robustness margins */\n\tdouble e1[] = {0,0,0};\n\tdouble e2[] = {0,0,0};\n\ttb = clock();\n\tabst.assign_transitions(e1, e2);\n\t// abst.assign_transitions();\n\tte = clock();\n\ttabst = (float)(te - tb)/CLOCKS_PER_SEC;\n\tstd::cout << \"Time of computing abstraction: \" << tabst << '\\n';\n\tstd::cout << \"# of transitions: \" << abst._ts._ntrans << '\\n';\n\t/* Write abstraction to file */\n\trocs::h5FileHandler transWtr(transfile, H5F_ACC_TRUNC);\n\ttransWtr.write_transitions(abst._ts);\n\ttransWtr.write_array<size_t>(obstacles, \"obs\");\n\ttransWtr.write_array<double>(eta, carde::n, \"eta\");\n\ttransWtr.write_2d_array<double>(abst._x._data, \"xgrid\");\n\ttransWtr.write_problem_setting< rocs::DTCntlSys<carde> >(car);\n    }\n\n\n    /**\n     * Read DBA from dba*.txt file\n     */\n    std::cout << \"Reading the specification...\\n\";\n    rocs::UintSmall nAP = 0, nNodes = 0, q0 = 0;\n    std::vector<rocs::UintSmall> acc;\n    std::vector<std::vector<rocs::UintSmall>> arrayM;\n    if (!rocs::read_spec(specfile, nNodes, nAP, q0, arrayM, acc))\n\tstd::exit(1);\n    std::vector<std::string> tokens;\n    boost::split(tokens, specfile, boost::is_any_of(\".\"));\n\n\n    /*\n     * Assign labels to states: has to be consistent with the dba file.\n     */\n    rocs::UintSmall nGoal = 3;\n    double e = tau/2.0;\n    double goal[3][4] = {{0.5+e, 2.0-e, 7.5+e, 9.5-e},\n\t\t\t {8.0, 0.8-e, 8.0, 0.8-e}, // {5.5, 0.5-e, 8.5, 0.5-e},\n\t\t\t {7.5+e, 9.5-e, 0.8+e, 3.0-e}}; //{7.5+e, 9.5-e, 0.8+e, 4.0-e}\n    auto label_target = [&goal, &nGoal, &abst, &eta](size_t i) {\n\t\t      std::vector<double> x(abst._x._dim);\n\t\t      abst._x.id_to_val(x, i);\n\t\t      // double c1= eta[0]/2.0; //+1e-10;\n\t\t      // double c2= eta[1]/2.0; //+1e-10;\n\t\t      double xl = x[0] - eta[0]/2.;\n\t\t      double xr = x[0] + eta[0]/2.;\n\t\t      double yl = x[1] - eta[1]/2.;\n\t\t      double yr = x[1] + eta[1]/2.;\n\t\t      boost::dynamic_bitset<> label(nGoal, false); // n is the number of goals\n\t\t      for(rocs::UintSmall i = 0; i < nGoal; ++i) {\n\t\t\t  if(i != 1) {\n\t\t\t  label[2-i] = (goal[i][0] <= xl && xr <= goal[i][1] &&\n\t\t\t\t\tgoal[i][2] <= yl && yr <= goal[i][3])\n\t\t\t      ? true: false;\n\t\t\t  } else {\n\t\t\t      double rxr = xr - goal[i][0];\n\t\t\t      double rxl = xl - goal[i][0];\n\t\t\t      double ryr = yr - goal[i][2];\n\t\t\t      double ryl = yl - goal[i][2];\n\t\t\t      double xsqr = (rxr*rxr) < (rxl*rxl) ? (rxl*rxl) : (rxr*rxr);\n\t\t\t      double ysqr = (ryr*ryr) < (ryl*ryl) ? (ryl*ryl) : (ryr*ryr);\n\t\t\t      label[2-i] = (xsqr+ysqr)<goal[i][1]*goal[i][3] ? true : false;\n\t\t\t  }\n\t\t      }\n\t\t      return label.to_ulong();\n\t\t  };\n    abst.assign_labels(label_target);\n    \n    std::cout << \"Save labels to file.\\n\";\n    std::string labelfile = \"labels_\" + tokens[0] + \"_\" + transfile;\n    rocs::h5FileHandler labelWtr(labelfile, H5F_ACC_TRUNC);\n    labelWtr.write_array<int>(abst._labels, \"labels\");\n    std::cout << \"Specification assignment is done.\\n\";\n\n\n    /**\n     * Solve a Buchi game on the product of NTS and DBA.\n     */\n    std::cout << \"Start solving a Buchi game on the product of the abstraction and DBA...\\n\";\n    rocs::BSolver solver; // memories will be allocated for psolver\n    solver.construct_dba((int)nAP, (int)nNodes, (int)q0, acc, arrayM);\n    tb = clock();\n    solver.load_abstraction(abst);\n    solver.generate_product(abst);\n    solver.solve_buchigame_on_product();\n    te = clock();\n    float tsyn = (float)(te - tb)/CLOCKS_PER_SEC;\n    std::cout << \"Time of synthesizing controller: \" << tsyn << '\\n';\n\n\n    /**\n     * Display and save memoryless controllers.\n     */\n    std::string datafile = \"controller_\" + tokens[0] + \"_\";\n    for(int i = 0; i < 3; ++i) {\n    \tstd::stringstream ss;\n    \tss << std::setprecision(1);\n    \tss << eta[i];\n    \tdatafile += ss.str();\n    \tif (i < 2)\n    \t    datafile += \"-\";\n    }\n    datafile += \".h5\";\n    std::cout << \"Writing the controller...\\n\";\n    // solver.write_controller_to_txt(const_cast<char*>(datafile.c_str()));\n    rocs::h5FileHandler ctlrWtr(datafile, H5F_ACC_TRUNC);\n    ctlrWtr.write_problem_setting< rocs::DTCntlSys<carde> >(car);\n    // ctlrWtr.write_2d_array<double>(targetPts, \"G\");\n    ctlrWtr.write_array<double>(eta, carde::n, \"eta\");\n    ctlrWtr.write_2d_array<double>(abst._x._data, \"xgrid\");\n    ctlrWtr.write_discrete_controller(&(solver._sol));\n    std::cout << \"Controller writing is done.\\n\";\n\n    std::cout << \"Total time of used (abstraction+synthesis): \" << tabst+tsyn << '\\n';\n\n\n    /**\n     * Create a patcher and save the winning graph\n     */\n    std::string winfile = \"gwin.h5\";\n    rocs::Patcher local;\n    std::cout << \"Extracting the winning graph...\\n\";\n    tb = clock();\n    local.initialize_winning_graph(solver._sol);\n    te = clock();\n    std::cout << \"Time of extracting the winning graph: \" << (float)(te - tb)/CLOCKS_PER_SEC << '\\n';\n    \n    /* Save the winning graph to a file */\n    std::cout << \"Writing the winning graph to file...\\n\";\n    rocs::h5FileHandler graphWtr(winfile, H5F_ACC_TRUNC);\n    tb = clock();\n    if(graphWtr.write_winning_graph(local)) {\n    \tstd::cout << \"Error in saving the winning graph to file.\\n\";\n    \treturn 1;\n    }\n    te = clock();\n    std::cout << \"Time of writing the winning graph: \" << (float)(te - tb)/CLOCKS_PER_SEC << '\\n';\n\n    return 0;\n}\n", "meta": {"hexsha": "f3b0d3d571134c6c3305b1023742623901eb37ad", "size": 9099, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/collision-avoid/staticplan.cpp", "max_stars_repo_name": "yinanl/rocs", "max_stars_repo_head_hexsha": "bf2483903e39f4c0ea254a9ef56720a1259955ad", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/collision-avoid/staticplan.cpp", "max_issues_repo_name": "yinanl/rocs", "max_issues_repo_head_hexsha": "bf2483903e39f4c0ea254a9ef56720a1259955ad", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/collision-avoid/staticplan.cpp", "max_forks_repo_name": "yinanl/rocs", "max_forks_repo_head_hexsha": "bf2483903e39f4c0ea254a9ef56720a1259955ad", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.0872727273, "max_line_length": 101, "alphanum_fraction": 0.5688537202, "num_tokens": 3113, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6039318479832804, "lm_q2_score": 0.5312093733737563, "lm_q1q2_score": 0.320814258527653}}
{"text": "//==================================================//\r\n///\r\n/// @file   MyFFT.cpp\r\n/// @brief  Implementation of MyFFT.\r\n/// @author cogoto\r\n///\r\n/// [MyAll]\r\n/// Copyright (c) 2021 cogoto\r\n/// Released under the MIT license\r\n/// https://opensource.org/licenses/mit-license.php\r\n///\r\n//==================================================//\r\n\r\n#include \"MyFFT.hpp\"\r\n\r\n#include <algorithm>\r\n\r\n#include <chrono>\r\n\r\n#include <cstdint>\r\n\r\n#include <ctime>\r\n\r\n//#include <execution>\r\n\r\n#include <iostream>\r\n\r\n#include <iomanip>\r\n\r\n//#include <Eigen/Dense>\r\n\r\n#include <complex>\r\n\r\n#include <thread>\r\n\r\n#include <time.h>\r\n\r\n//\r\n\r\nnamespace MyAll {\r\n\r\n//\r\n\r\nusing namespace std;\r\n\r\n//using namespace Eigen;\r\n\r\n//using fint = int_fast32_t;\r\n\r\n//using ufint = uint_fast32_t;\r\n\r\n\r\n//--------------------------------------------------//\r\n///\r\n/// @brief  First process. Initialize member variables.\r\n///\r\n//--------------------------------------------------//\r\n\r\n\r\nMyFFT::MyFFT(const int &n_data__, const int &n_thread__) {\r\n\r\n    print_ = false;\r\n\r\n    MyFFT::Init(n_data__, n_thread__);\r\n\r\n};\r\n\r\n\r\n//--------------------------------------------------//\r\n///\r\n/// @brief   End process.\r\n///\r\n//--------------------------------------------------//\r\n\r\n\r\nMyFFT::~MyFFT() {\r\n\r\n};\r\n\r\n\r\n//--------------------------------------------------//\r\n///\r\n/// @brief   Initialize calculation parameters.\r\n/// @return  None.\r\n///\r\n//--------------------------------------------------//\r\n\r\n\r\nvoid MyFFT::Init(const int &n_data__, const int &n_thread__) {\r\n\r\n    if(!SetN(n_data__)) { exit(0); }\r\n\r\n    //\r\n\r\n    double theta = 2 * PI_ / n_;\r\n\r\n    complex<double> Wo = complex<double> (cos(theta), -sin(theta));\r\n\r\n    W_0_.reserve(n_half_);\r\n    W_0_.push_back(1.0L);\r\n    for(uint_fast32_t i=1;i<n_half_;i++) { W_0_.push_back(W_0_[i-1] * Wo); }\r\n\r\n    //\r\n\r\n    n_thread_ = n_thread__;\r\n\r\n    int n_cpu = static_cast<int>(thread::hardware_concurrency());\r\n\r\n    if(n_thread__ <= 0) {\r\n        n_thread_ = n_cpu - 1;\r\n        if(n_thread_ <= 0) { n_thread_ = 1; }\r\n    }\r\n    else if(n_thread_ > n_cpu) {\r\n        n_thread_ = n_cpu;\r\n    }\r\n\r\n    if(print_) { cout << \"[MyFFT] n_thread = \" << n_thread_ << endl; }\r\n\r\n    //cout << \"[MyFFT] n_thread = \" << n_thread_ << endl;\r\n\r\n    //\r\n\r\n    thread_exec_.reserve(n_thread_);\r\n    //for(int i=0;i<n_thread_;i++) { thread_exec_.push_back(0); }\r\n    for(int i=0;i<n_thread_;i++) { thread_exec_.push_back(-1); }\r\n\r\n    //\r\n\r\n    n_stream_ = static_cast<uint_fast32_t>(static_cast<double>(n_half_) / static_cast<double>(n_thread_));\r\n    n_stream_ += 1;\r\n\r\n    //cout << \":: \" << n_ << \" : \" << n_thread_ << \" : \" << n_half_ << \" : \" << n_step_ << \" : \" << endl;\r\n\r\n    //\r\n\r\n    vector<vector<uint_fast32_t>>().swap(iW_);\r\n    iW_.resize(n_step_);\r\n    for(auto &&it:iW_) {\r\n        //it.resize(n_);\r\n        it.reserve(n_);\r\n        for(uint_fast32_t i=0;i<n_;i++) { it.push_back(0); }\r\n    }\r\n\r\n    //iW_.resize(n_);\r\n\r\n    //W_.reserve(n_); // cannot resize the object! (It will occur core-dump)\r\n    //for(uint_fast32_t i=0;i<n_;i++) { W_.push_back(1.0L); }\r\n\r\n    //\r\n\r\n    vector<vector<uint_fast32_t>>().swap(m_);\r\n    m_.resize(n_step_);\r\n    for(auto &&it:m_) {\r\n        //it.resize(n_half_);\r\n        it.reserve(n_half_);\r\n        for(uint_fast32_t i=0;i<n_half_;i++) { it.push_back(0); }\r\n    }\r\n\r\n    //m_.reserve(n_half_);\r\n    //for(uint_fast32_t i=0;i<n_half_;i++) { m_.push_back(0); }\r\n\r\n    n_block_half_ = n_;\r\n\r\n    uint_fast32_t i0, sss;\r\n\r\n    for(uint_fast32_t s=0;s<n_step_;s++) {\r\n\r\n        n_block_ = n_block_half_;\r\n        n_block_half_ >>= 1;\r\n\r\n        i0 = 0;\r\n\r\n        for(uint_fast32_t i1=0; i1<n_block_half_; i1++) {\r\n\r\n            sss = (i1 << s);\r\n\r\n            for(uint_fast32_t i2=i1; i2<n_; i2+=n_block_) {\r\n                m_[s][i0] = i2;\r\n                iW_[s][i2] = sss;\r\n                i0++;\r\n            }\r\n\r\n        }\r\n\r\n    }\r\n\r\n    //\r\n\r\n    i_bit_rev_.resize(n_);\r\n\r\n    uint_fast32_t i2;\r\n\r\n    for(uint_fast32_t i1=0;i1<n_;i1++) {\r\n\r\n        i2 = i1;\r\n\r\n        i2 = (((i2 & 0xaaaaaaaa) >> 1) | ((i2 & 0x55555555) << 1));\r\n        i2 = (((i2 & 0xcccccccc) >> 2) | ((i2 & 0x33333333) << 2));\r\n        i2 = (((i2 & 0xf0f0f0f0) >> 4) | ((i2 & 0x0f0f0f0f) << 4));\r\n        i2 = (((i2 & 0xff00ff00) >> 8) | ((i2 & 0x00ff00ff) << 8));\r\n        i2 = ((i2 >> 16) | (i2 << 16)) >> (32 - n_step_);\r\n\r\n        if(i2 > i1) {\r\n            i_bit_rev_[i1] = i2;\r\n        }\r\n        else {\r\n            i_bit_rev_[i1] = i1;\r\n            //i_bit_rev_[i1] = -1;\r\n        }\r\n\r\n    }\r\n\r\n    //\r\n\r\n    window_func_name_ = \"\";\r\n\r\n    //SetWindow(\"\"); // rectangular window function\r\n\r\n    //\r\n\r\n    /*\r\n    uint_fast32_t thread_no = 0;\r\n\r\n    vector<thread> ths( n_thread_ );\r\n\r\n    for (auto &&th : ths) {\r\n\r\n        th = thread(\r\n            &MyFFT::_calc_butterfly,\r\n            this,\r\n            thread_no\r\n        );\r\n\r\n        thread_no++;\r\n\r\n    }\r\n\r\n    for (auto &&th : ths) {\r\n        try {\r\n            if(th.joinable()) {\r\n                th.join();\r\n            }\r\n        } catch(const std::system_error& e) {\r\n            cout << \"Caught system_error with code \" << e.code() << \" meaning \" << e.what() << endl;\r\n        }\r\n    }\r\n    */\r\n\r\n\r\n    //\r\n\r\n    return;\r\n\r\n};\r\n\r\n\r\n\r\n//--------------------------------------------------//\r\n///\r\n/// @brief   Sets the number of data.\r\n/// @return  bool.\r\n///\r\n//--------------------------------------------------//\r\n\r\n\r\nbool MyFFT::SetN(const int &n_data__) {\r\n\r\n    int n_check_pre = 0;\r\n    int n_check_now = 1;\r\n\r\n    for(int i=0;i<32;i++) {\r\n\r\n        n_check_pre = n_check_now;\r\n\r\n        n_check_now = (n_check_now << 1);\r\n\r\n        if(n_check_now == n_data__) { break; }\r\n\r\n        if(n_check_pre < n_data__ && n_data__ < n_check_now) {\r\n            cerr << \"[ERROR][MyFFT] The number of data is not a multiply of 2.\" << endl;\r\n            return false;\r\n        }\r\n\r\n    }\r\n\r\n    n_ = n_data__;\r\n\r\n    n_half_ = (n_ >> 1);\r\n\r\n    n_step_ = static_cast<uint_fast32_t>(log2(n_));\r\n\r\n    //coeff_amp_ = 2.0 / n_;\r\n\r\n    //coeff_amp_ = complex<double> (1.0 / n_, 0.0);\r\n\r\n    return true;\r\n\r\n}\r\n\r\n\r\n//--------------------------------------------------//\r\n///\r\n/// @brief     Control standard outputs of current status.\r\n/// @param[in] use__ : Print stdout? (yes=true, no=false)\r\n/// @return    None.\r\n///\r\n//--------------------------------------------------//\r\n\r\n\r\nvoid MyFFT::Print(const bool &use__){\r\n\r\n    print_ = use__;\r\n\r\n};\r\n\r\n\r\n//--------------------------------------------------//\r\n///\r\n/// @brief   Gets frequency values.\r\n/// @return  None.\r\n///\r\n//--------------------------------------------------//\r\n\r\n\r\nstd::vector<double> MyFFT::F(const double &df__, const double &offset__, const bool &wrap_back__) {\r\n\r\n    df_ = df__;\r\n\r\n    dt_ = 1 / (n_ * df_);\r\n\r\n    vector<double> f;\r\n\r\n    if(wrap_back__) { f.reserve(n_); }\r\n    else            { f.reserve(n_half_+1); }\r\n\r\n    for(uint_fast32_t i=0;i<=n_half_;i++) {\r\n        f.push_back(df_ * i + offset__);\r\n    }\r\n\r\n    //f[n_half_] *= -1;\r\n\r\n    if(wrap_back__) {\r\n\r\n        for(int i=(n_half_-1);i>0;i--) {\r\n            f.push_back(-1 * f[i]);\r\n        }\r\n\r\n    }\r\n\r\n    return f;\r\n\r\n}\r\n\r\n\r\n//--------------------------------------------------//\r\n///\r\n/// @brief   Gets time values.\r\n/// @return  None.\r\n///\r\n//--------------------------------------------------//\r\n\r\n\r\nstd::vector<double> MyFFT::T(const double &dt__, const double &offset__) {\r\n\r\n    dt_ = dt__;\r\n\r\n    df_ = 1 / (n_ * dt_);\r\n\r\n    vector<double> t;\r\n\r\n    t.reserve(n_);\r\n\r\n    for(uint_fast32_t i=0;i<n_;i++) {\r\n        t.push_back(dt_ * i + offset__);\r\n    }\r\n\r\n    return t;\r\n\r\n}\r\n\r\n\r\n//--------------------------------------------------//\r\n///\r\n/// @brief   Executing FFT\r\n/// @return  None.\r\n///\r\n//--------------------------------------------------//\r\n\r\n\r\nbool MyFFT::_FFT_CT_multi(const vector<double> &t__, vector<complex<double>> &f__) {\r\n\r\n    if(n_ != static_cast<uint_fast32_t>(t__.size())) { return false; }\r\n\r\n    chrono::system_clock::time_point start, end;\r\n    //chrono::system_clock::time_point start1, end1;\r\n\r\n    //struct timespec ts;\r\n    //ts.tv_sec  = 0;\r\n    //ts.tv_nsec = 0;\r\n\r\n    start = chrono::system_clock::now();\r\n\r\n    //f_ = &f__;\r\n\r\n    vector<complex<double>> ().swap(f_);\r\n    f_.reserve(n_);\r\n    for(const auto &it:t__) {\r\n        f_.push_back(complex<double> (it, 0.0));\r\n    }\r\n\r\n    //end = chrono::system_clock::now();\r\n    //cout << \"[FFT_CT] [init val] = \" << fixed << setw(9) << right << chrono::duration_cast<chrono::nanoseconds>(end-start).count() << endl;\r\n\r\n    //\r\n\r\n    //start = chrono::system_clock::now();\r\n    cout << \":\" << endl;\r\n    vector<thread> ths( n_thread_ );\r\n\r\n    //end = chrono::system_clock::now();\r\n    //cout << \"[FFT_CT] [prep ths] = \" << fixed << setw(9) << right << chrono::duration_cast<chrono::nanoseconds>(end-start).count() << endl;\r\n\r\n    //\r\n\r\n    //for (int i=0;i<n_thread_;i++) { thread_exec_[i] = 0; }\r\n\r\n    //start = chrono::system_clock::now();\r\n\r\n    uint_fast32_t thread_no = 0;\r\n\r\n    thread_init_cnt_ = 0;\r\n\r\n    for (auto &&th : ths) {\r\n\r\n        uint_fast32_t i_begin = n_stream_ * thread_no;\r\n        uint_fast32_t i_end   = i_begin + n_stream_;\r\n\r\n        if(i_end > n_half_) { i_end = n_half_; }\r\n\r\n        th = thread(\r\n            &MyFFT::_calc_butterfly,\r\n            this,\r\n            thread_no,\r\n            i_begin,\r\n            i_end\r\n        );\r\n\r\n        //nanosleep(&ts, NULL);\r\n\r\n        thread_no++;\r\n\r\n    }\r\n\r\n    //end = chrono::system_clock::now();\r\n    //cout << \"[FFT_CT] [make ths] = \" << fixed << setw(9) << right << chrono::duration_cast<chrono::nanoseconds>(end-start).count() << endl;\r\n\r\n    //\r\n\r\n    //start = chrono::system_clock::now();\r\n\r\n    //while(thread_init_cnt_ < n_thread_) {\r\n    //    continue;\r\n    //}\r\n\r\n    while(1) {\r\n        {\r\n            lock_guard<mutex> lock(mtx_thread_);\r\n            //lock_guard<recursive_mutex> lock(mtx_thread_);\r\n            if(thread_init_cnt_ == n_thread_) { break; }\r\n        }\r\n    }\r\n\r\n    //end = chrono::system_clock::now();\r\n    //cout << \"[FFT_CT] [wait ini] = \" << fixed << setw(9) << right << chrono::duration_cast<chrono::nanoseconds>(end-start).count() << endl;\r\n\r\n    //\r\n\r\n    start = chrono::system_clock::now();\r\n\r\n    n_block_half_ = n_;\r\n\r\n    thread_cnt_ = 0;\r\n\r\n    for(s_=0;s_<n_step_;s_++) {\r\n    //for(uint_fast32_t s=1;s<=n_step_;s++) {\r\n\r\n        n_block_ = n_block_half_;\r\n        n_block_half_ >>= 1;\r\n\r\n        //s_ = s;\r\n\r\n        //\r\n\r\n        //start1 = chrono::system_clock::now();\r\n\r\n        /*{\r\n            lock_guard<mutex> lock(mtx_thread_);\r\n            //lock_guard<recursive_mutex> lock(mtx_thread_);\r\n            n_calc_ = 0;\r\n            for (int i=0;i<n_thread_;i++) {\r\n                thread_exec_[i] = 1;\r\n            }\r\n        }*/\r\n\r\n\r\n        {\r\n            unique_lock<std::mutex> wait_lock(mtx_wait_);\r\n            thread_ready_ = true;\r\n        }\r\n\r\n        cond_.notify_all();\r\n\r\n        //end1 = chrono::system_clock::now();\r\n        //cout << \"[FFT_CT] [loop] [exec ths] = \" << fixed << setw(9) << right << chrono::duration_cast<chrono::nanoseconds>(end1-start1).count() << endl;\r\n\r\n        //\r\n\r\n        /*\r\n        start1 = chrono::system_clock::now();\r\n\r\n        //int i_test = 0;\r\n\r\n        for(;;) {\r\n            {\r\n                lock_guard<mutex> lock(mtx_thread_);\r\n                if(thread_cnt_ >= 0) {\r\n                    cout << \":: \" << thread_cnt_ << endl;\r\n                    break;\r\n                }\r\n            }\r\n        }\r\n\r\n        end1 = chrono::system_clock::now();\r\n        cout << \"[FFT_CT] [loop] [test] = \" << fixed << setw(9) << right << chrono::duration_cast<chrono::nanoseconds>(end1-start1).count() << endl;\r\n        */\r\n\r\n        //\r\n\r\n        //{\r\n            //lock_guard<mutex> lock(mtx_thread_);\r\n            //start1 = chrono::system_clock::now();\r\n            //cout << \"[FFT_CT] [loop] wait st = \" << time_.HMS_nsec() << endl;\r\n        //}\r\n\r\n        int i = 0;\r\n        //while(1) {\r\n        for(;;) {\r\n            {\r\n                lock_guard<mutex> lock(mtx_thread_);\r\n                //lock_guard<recursive_mutex> lock(mtx_thread_);\r\n                //cout << thread_cnt_ << \":\" << n_thread_ << endl;\r\n                if(thread_cnt_ == n_thread_) { break; }\r\n            }\r\n            //if(thread_cnt_ >= n_thread_) {\r\n                //cout << \"wait count = \" << i << endl;\r\n            //    break;\r\n            //}\r\n            i++;\r\n            //if(i==30) {cout << thread_cnt_ << endl;}\r\n            //cout << thread_cnt_ << \" \" ;\r\n            //cout << i << \" \" ;\r\n            //nanosleep(&ts, NULL);\r\n            //continue;\r\n        }\r\n\r\n        thread_cnt_ = 0;\r\n\r\n        thread_ready_ = false;\r\n\r\n        /*{\r\n            lock_guard<mutex> lock(mtx_thread_);\r\n            //cout << \"[FFT_CT] [loop] wait et = \" << time_.HMS_nsec() << endl;\r\n            cout << \"wait loop n = \" << i << endl ;\r\n            //end1 = chrono::system_clock::now();\r\n            //cout << \"[FFT_CT] [loop] [wait ths] = \" << fixed << setw(9) << right << chrono::duration_cast<chrono::nanoseconds>(end1-start1).count() << endl;\r\n        }*/\r\n\r\n    }\r\n\r\n    //\r\n\r\n    {\r\n        lock_guard<mutex> lock(mtx_thread_);\r\n        //lock_guard<recursive_mutex> lock(mtx_thread_);\r\n        for (int i=0;i<n_thread_;i++) {\r\n            thread_exec_[i] = -1;\r\n        }\r\n    }\r\n\r\n    //\r\n\r\n    for (auto &&th : ths) {\r\n        try {\r\n            if(th.joinable()) {\r\n                th.join();\r\n            }\r\n        } catch(const std::system_error& e) {\r\n            cerr << \"[FFT_CT] Caught system_error with code \" << e.code() << \" meaning \" << e.what() << endl;\r\n            return false;\r\n        }\r\n    }\r\n\r\n    //end = chrono::system_clock::now();\r\n    //cout << \"[FFT_CT] [exec fft] = \" << fixed << setw(9) << right << chrono::duration_cast<chrono::nanoseconds>(end-start).count() << endl;\r\n\r\n    //\r\n    // Reverse bits\r\n    //\r\n\r\n    //start = chrono::system_clock::now();\r\n\r\n    complex<double> tmp_swap;\r\n\r\n    int i1 = 0;\r\n\r\n    for(const auto &i2 : i_bit_rev_) {\r\n        tmp_swap = f_[i1];\r\n        f_[i1] = f_[i2];\r\n        f_[i2] = tmp_swap;\r\n        i1++;\r\n    }\r\n\r\n    /*\r\n    uint_fast32_t i2;\r\n\r\n    for(uint_fast32_t i1=0;i1<n_;i1++) {\r\n        if(i_bit_rev_[i1] != -1) {\r\n            i2 = i_bit_rev_[i1];\r\n            tmp_swap = f_[i1];\r\n            f_[i1] = f_[i2];\r\n            f_[i2] = tmp_swap;\r\n        }\r\n    }\r\n    */\r\n\r\n    /*\r\n    uint_fast32_t i2;\r\n\r\n    for(uint_fast32_t i1=0;i1<n_;i1++) {\r\n\r\n        i2 = i1;\r\n\r\n        i2 = (((i2 & 0xaaaaaaaa) >> 1) | ((i2 & 0x55555555) << 1));\r\n        i2 = (((i2 & 0xcccccccc) >> 2) | ((i2 & 0x33333333) << 2));\r\n        i2 = (((i2 & 0xf0f0f0f0) >> 4) | ((i2 & 0x0f0f0f0f) << 4));\r\n        i2 = (((i2 & 0xff00ff00) >> 8) | ((i2 & 0x00ff00ff) << 8));\r\n        i2 = ((i2 >> 16) | (i2 << 16)) >> (32 - n_step_);\r\n\r\n        if(i2 > i1) {\r\n            tmp_swap = f_[i1];\r\n            f_[i1] = f_[i2];\r\n            f_[i2] = tmp_swap;\r\n        }\r\n\r\n    }\r\n    */\r\n\r\n    //end = chrono::system_clock::now();\r\n    //cout << \"[FFT_CT] [bit rev.] = \" << fixed << setw(9) << right << chrono::duration_cast<chrono::nanoseconds>(end-start).count() << endl;\r\n\r\n    //\r\n\r\n    //start = chrono::system_clock::now();\r\n\r\n    f__ = f_;\r\n\r\n    //end = chrono::system_clock::now();\r\n    //cout << \"[FFT_CT] [copy val] = \" << fixed << setw(9) << right << chrono::duration_cast<chrono::nanoseconds>(end-start).count() << endl;\r\n\r\n    //\r\n\r\n    return true;\r\n\r\n\r\n};\r\n\r\n\r\n//--------------------------------------------------//\r\n\r\n\r\nvoid MyFFT::_calc_butterfly(\r\n    uint_fast32_t thread_no__,\r\n    uint_fast32_t i_begin__,\r\n    uint_fast32_t i_end__\r\n) {\r\n\r\n    //chrono::system_clock::time_point start, end;\r\n\r\n    uint_fast32_t m1, m2, n_step;\r\n\r\n    complex<double> tmp;\r\n\r\n    //uint_fast32_t n_block_half = n_block_half_;\r\n\r\n    {\r\n        lock_guard<mutex> lock(mtx_thread_);\r\n        //lock_guard<recursive_mutex> lock(mtx_thread_);\r\n        //unique_lock<mutex> lock(mtx_thread_);\r\n        thread_exec_[thread_no__] = 0;\r\n        thread_init_cnt_++;\r\n        //cout << \"[_calc_butterfly] init end : \" << thread_no__ << endl;\r\n        n_step = n_step_;\r\n    }\r\n\r\n    //sleep(1);\r\n    //this_thread::sleep_for(chrono::nanoseconds(1));\r\n\r\n    //\r\n\r\n    //int thread_exec = 0;\r\n\r\n    //uint_fast32_t n_calc;\r\n\r\n    uint_fast32_t n_block_half;\r\n\r\n\r\n\r\n    for(uint_fast32_t s=0;s<n_step;s++) {\r\n\r\n    //while(thread_exec_[thread_no__] >= 0) {\r\n        //while(1) {\r\n\r\n        //this_thread::sleep_for(chrono::nanoseconds(1));\r\n\r\n        //cout << \"th \" << thread_no__ << \" sts = \" << thread_exec_[thread_no__] << endl;\r\n\r\n        /*\r\n        {\r\n            lock_guard<mutex> lock(mtx_thread_);\r\n            //lock_guard<recursive_mutex> lock(mtx_thread_);\r\n            thread_exec = thread_exec_[thread_no__];\r\n        }\r\n        */\r\n\r\n        {\r\n            unique_lock<std::mutex> wait_lock(mtx_wait_);\r\n\r\n            // データの準備ができるまで待機してから処理する\r\n            cond_.wait(wait_lock, [this] { return thread_ready_; });\r\n\r\n        //if(thread_exec_[thread_no__] == 1) {\r\n\r\n            //start = chrono::system_clock::now();\r\n\r\n            {\r\n                lock_guard<mutex> lock(mtx_thread_);\r\n                thread_exec_[thread_no__] = 0;\r\n                n_block_half = n_block_half_;\r\n                //cout << \"[CALC] \" << thread_no__ << \" : st = \" << time_.HMS_nsec() << endl;\r\n            }\r\n\r\n            //{\r\n            //    lock_guard<mutex> lock(mtx_thread_);\r\n            //    //lock_guard<recursive_mutex> lock(mtx_thread_);\r\n            //    thread_exec_[thread_no__] = 0;\r\n            //}\r\n\r\n            for(uint_fast32_t i=i_begin__;i<i_end__;i++) {\r\n                m1 = m_[s_][i];\r\n                m2 = m1 + n_block_half;\r\n                tmp = f_[m1] - f_[m2];\r\n                f_[m1] += f_[m2];\r\n                f_[m2] = tmp * W_0_[iW_[s_][m1]];\r\n            }\r\n\r\n            /*\r\n            while(1) {\r\n\r\n                {\r\n                    lock_guard<mutex> lock(mtx_thread_);\r\n                    n_calc = n_calc_;\r\n                    n_calc_++;\r\n                    if(n_calc_ >= n_half_) { break; }\r\n                }\r\n\r\n                m1 = m_[s_][n_calc];\r\n                m2 = m1 + n_block_half;\r\n                tmp = f_[m1] - f_[m2];\r\n                f_[m1] += f_[m2];\r\n                f_[m2] = tmp * W_0_[iW_[s_][m1]];\r\n\r\n            }\r\n            */\r\n\r\n            //end = chrono::system_clock::now();\r\n\r\n            {\r\n                lock_guard<mutex> lock(mtx_thread_);\r\n                //lock_guard<recursive_mutex> lock(mtx_thread_);\r\n                //unique_lock<mutex> lock(mtx_thread_);\r\n                thread_cnt_++;\r\n                //cout << \"[CALC] \" << thread_no__ << \" : et = \" << time_.HMS_nsec() << endl;\r\n                //cout << \"[CALC] \" << thread_no__ << \" : dt =  \" << fixed << setw(15) << right << chrono::duration_cast<chrono::nanoseconds>(end-start).count() << endl;\r\n            }\r\n\r\n            //thread_ready_ = false;\r\n\r\n        }\r\n\r\n        //if(thread_exec < 0) { break; }\r\n\r\n        //this_thread::sleep_for(chrono::nanoseconds(100));\r\n\r\n    }\r\n\r\n    return;\r\n\r\n};\r\n\r\n/*\r\nvoid MyFFT::_calc_butterfly(\r\n    uint_fast32_t i_begin__,\r\n    uint_fast32_t i_end__,\r\n    uint_fast32_t &Nb_half__,\r\n    vector<complex<double>> &f__,\r\n    vector<complex<double>> &W__,\r\n    vector<uint_fast32_t> &w__,\r\n    vector<uint_fast32_t> &m__\r\n) {\r\n\r\n    uint_fast32_t i1;\r\n    uint_fast32_t i2;\r\n    complex<double> tmp;\r\n\r\n    //cout << \"[begin, end] = [\" << i_begin__ << \", \" << i_end__ << \"]\" << endl;\r\n\r\n    if(calc_butterfly_) {\r\n\r\n        for(uint_fast32_t i=i_begin__;i<i_end__;i++) {\r\n            i1 = m__[i];\r\n            i2 = i1 + Nb_half__;\r\n            tmp = f__[i1] - f__[i2];\r\n            f__[i1] += f__[i2];\r\n            f__[i2] = tmp * W__[w__[i1]];\r\n        }\r\n\r\n    }\r\n\r\n\r\n    return;\r\n\r\n};\r\n*/\r\n\r\n\r\n//--------------------------------------------------//\r\n///\r\n/// @brief   Implementation of multi-thread FFT with a number of data.\r\n/// @return  None.\r\n///\r\n//--------------------------------------------------//\r\n\r\n\r\nvoid MyFFT::_calc_fft(\r\n    const uint_fast32_t &thread_no__,\r\n    vector<vector<complex<double>>> &x__,\r\n    const int &n_set__,\r\n    int &i_set__\r\n) {\r\n\r\n    int i_set;\r\n    uint_fast32_t n;\r\n    vector<int> i_bit_rev;\r\n\r\n    {\r\n        unique_lock<std::mutex> wait_lock(mtx_wait_);\r\n        i_bit_rev = i_bit_rev_;\r\n        n = n_;\r\n    }\r\n\r\n    while(1) {\r\n\r\n        {\r\n            unique_lock<std::mutex> wait_lock(mtx_wait_);\r\n\r\n            i_set__++;\r\n            i_set = i_set__;\r\n\r\n            if(i_set__ >= n_set__) { break; }\r\n\r\n            //cout << \"[_calc_fft] th.no = \" << thread_no__ << \", i_set = \" << i_set__;\r\n            //cout << \", size = \" << x__.size() << \", \" <<  x__[i_set].size() << endl;\r\n\r\n        }\r\n\r\n        _FFT_CT(x__[i_set], n, i_bit_rev);\r\n\r\n        //cout << \"[_calc_fft] fin \" << endl;\r\n\r\n    }\r\n\r\n    return;\r\n\r\n}\r\n\r\n\r\n//--------------------------------------------------//\r\n///\r\n/// @brief   Executing FFT with a number of data.\r\n/// @return  None.\r\n///\r\n//--------------------------------------------------//\r\n\r\n\r\nbool MyFFT::FFT(\r\n    const vector<complex<double>> &t__,\r\n    vector<vector<complex<double>>> &f__,\r\n    bool zero_padding__\r\n) {\r\n\r\n    int n_set = static_cast<int>(t__.size()/n_);\r\n\r\n    if(zero_padding__) { n_set++; }\r\n\r\n    vector<vector<complex<double>>> ().swap(f__);\r\n    vector<complex<double>> f_part;\r\n\r\n    f__.reserve(n_set);\r\n    f_part.resize(n_);\r\n\r\n    uint_fast32_t i1 = 0;\r\n\r\n    for(const auto &it : t__) {\r\n\r\n        f_part[i1] = it;\r\n\r\n        i1++;\r\n\r\n        if(i1 >= n_) {\r\n            f__.push_back(f_part);\r\n            i1 = 0;\r\n        }\r\n\r\n    }\r\n\r\n    //cout << \"size = \" << f__.size() << endl;\r\n    //cout << \"part size =\";\r\n    //for(const auto &it:f__) { cout << \" \" << it.size() << \",\"; }\r\n    //cout << endl;\r\n\r\n    if(zero_padding__) {\r\n        for(uint_fast32_t i2=i1;i2<n_;i2++) {\r\n            f_part[i2] = complex<double> (0.0, 0.0);\r\n        }\r\n        f__.push_back(f_part);\r\n    }\r\n\r\n    //\r\n\r\n    if(window_func_name_ != \"\") {\r\n        for(auto &&it : f__) {\r\n            ApplyWindow(it);\r\n        }\r\n    }\r\n\r\n    //\r\n\r\n    vector<thread> ths( n_thread_ );\r\n\r\n    uint_fast32_t thread_no = 0;\r\n\r\n    int i_set = -1;\r\n\r\n    for (auto &&th : ths) {\r\n\r\n        th = thread(\r\n            &MyFFT::_calc_fft,\r\n            this,\r\n            thread_no,\r\n            std::ref(f__),\r\n            std::ref(n_set),\r\n            std::ref(i_set)\r\n        );\r\n\r\n        thread_no++;\r\n\r\n    }\r\n\r\n    for (auto &&th : ths) {\r\n        try {\r\n            if(th.joinable()) {\r\n                th.join();\r\n            }\r\n        } catch(const std::system_error& e) {\r\n            cout << \"Caught system_error with code \" << e.code() << \" meaning \" << e.what() << endl;\r\n        }\r\n    }\r\n\r\n    return true;\r\n\r\n}\r\n\r\n\r\n//--------------------------------------------------//\r\n\r\n\r\nbool MyFFT::FFT(\r\n    const vector<double> &t__,\r\n    vector<vector<complex<double>>> &f__,\r\n    bool zero_padding__\r\n) {\r\n\r\n    vector<complex<double>> t;\r\n    t.reserve(t__.size());\r\n    for(const auto &it:t__) {\r\n        t.push_back(complex<double> (it, 0.0));\r\n    }\r\n\r\n    return FFT(t, f__);\r\n\r\n}\r\n\r\n\r\n//--------------------------------------------------//\r\n\r\n/*\r\nvector<vector<complex<double>>> MyFFT::FFT(\r\n    const vector<double> &t__,\r\n    bool zero_padding__\r\n) {\r\n\r\n    vector<complex<double>> t;\r\n    t.reserve(t__.size());\r\n    for(const auto &it:t__) {\r\n        t.push_back(complex<double> (it, 0.0));\r\n    }\r\n\r\n    vector<vector<complex<double>>> f;\r\n\r\n    FFT(t, f);\r\n\r\n    return f;\r\n\r\n}\r\n*/\r\n\r\n\r\n//--------------------------------------------------//\r\n\r\n\r\nbool MyFFT::FFT(\r\n    const vector<complex<double>> &t__,\r\n    vector<complex<double>> &f__,\r\n    bool zero_padding__\r\n) {\r\n\r\n    vector<vector<complex<double>>> f;\r\n\r\n    FFT(t__, f);\r\n\r\n    vector<complex<double>> ().swap(f__);\r\n    f__.resize(n_);\r\n    complex<double> zero(0.0, 0.0);\r\n\r\n    for(auto &&it : f__) { it = zero; }\r\n\r\n    for(auto &&it1 : f) {\r\n\r\n        int i = 0;\r\n\r\n        for(auto &&it2 : it1) {\r\n\r\n            f__[i] += it2;\r\n            i++;\r\n\r\n        }\r\n\r\n    }\r\n\r\n    return true;\r\n\r\n}\r\n\r\n\r\n//--------------------------------------------------//\r\n\r\n\r\nbool MyFFT::FFT(\r\n    const vector<double> &t__,\r\n    vector<complex<double>> &f__,\r\n    bool zero_padding__\r\n) {\r\n\r\n    vector<complex<double>> t;\r\n    t.reserve(t__.size());\r\n    for(const auto &it:t__) {\r\n        t.push_back(complex<double> (it, 0.0));\r\n    }\r\n\r\n    return FFT(t, f__);\r\n\r\n}\r\n\r\n\r\n//--------------------------------------------------//\r\n\r\n\r\nvector<complex<double>> MyFFT::FFT(\r\n    const vector<double> &t__,\r\n    bool zero_padding__\r\n) {\r\n\r\n    vector<complex<double>> t;\r\n    t.reserve(t__.size());\r\n    for(const auto &it:t__) {\r\n        t.push_back(complex<double> (it, 0.0));\r\n    }\r\n\r\n    vector<complex<double>> f;\r\n\r\n    FFT(t, f);\r\n\r\n    return f;\r\n\r\n}\r\n\r\n\r\n//--------------------------------------------------//\r\n///\r\n/// @brief   Executing FFT\r\n/// @return  None.\r\n///\r\n//--------------------------------------------------//\r\n\r\n\r\nbool MyFFT::_FFT_CT(\r\n    vector<complex<double>> &x__,\r\n    uint_fast32_t &n__,\r\n    vector<int> &i_bit_rev__\r\n) {\r\n\r\n    double thetaT = PI_ / n__;;\r\n    uint_fast32_t k = n__;\r\n\r\n    uint_fast32_t n;\r\n    complex<double> T;\r\n    complex<double> tmp;\r\n    complex<double> phiT = complex<double>(cos(thetaT), -sin(thetaT));\r\n\r\n    //\r\n\r\n    while(k > 1) {\r\n\r\n        n = k;\r\n        k >>= 1;\r\n        phiT = phiT * phiT;\r\n        T = 1.0L;\r\n\r\n        for (uint_fast32_t l = 0; l < k; l++) {\r\n\r\n            for (uint_fast32_t a = l; a < n__; a += n) {\r\n\r\n                uint_fast32_t b = a + k;\r\n                tmp = x__[a] - x__[b];\r\n                x__[a] += x__[b];\r\n                x__[b] = tmp * T;\r\n\r\n            }\r\n\r\n            T *= phiT;\r\n\r\n        }\r\n\r\n    }\r\n\r\n    //\r\n    // Reverse bits\r\n    //\r\n\r\n    complex<double> tmp_swap;\r\n\r\n    int i1 = 0;\r\n\r\n    for(const auto &i2 : i_bit_rev__) {\r\n        tmp_swap = x__[i1];\r\n        x__[i1] = x__[i2];\r\n        x__[i2] = tmp_swap;\r\n        i1++;\r\n    }\r\n\r\n    return true;\r\n\r\n}\r\n\r\n\r\n//--------------------------------------------------//\r\n///\r\n/// @brief   Executing FFT with the specified number of data, sequentialy.\r\n/// @return  None.\r\n///\r\n//--------------------------------------------------//\r\n\r\n\r\nbool MyFFT::FFT_CT_seq(const vector<complex<double>> &t__, vector<complex<double>> &f__) {\r\n\r\n    if(static_cast<uint_fast32_t>(t__.size()) != n_) {\r\n        cerr << \"[ERROR][MyFFT] The number of input data is not a multiply of 2.\" << endl;\r\n        return false;\r\n    }\r\n\r\n    //\r\n\r\n    f__ = t__;\r\n\r\n    if(window_func_name_ != \"\") { ApplyWindow(f__); }\r\n\r\n    if(_FFT_CT_seq(f__)) {\r\n\r\n        for(auto &&it : f__) {\r\n            it /= n_; // Correcting the amplitude.\r\n        }\r\n\r\n        return true;\r\n\r\n    } else {\r\n\r\n        return false;\r\n\r\n    }\r\n\r\n}\r\n\r\n\r\n//--------------------------------------------------//\r\n\r\n\r\nbool MyFFT::FFT_CT_seq(const vector<double> &t__, vector<complex<double>> &f__) {\r\n\r\n    if(static_cast<uint_fast32_t>(t__.size()) != n_) {\r\n        cerr << \"[ERROR][MyFFT] The number of input data is not a multiply of 2.\" << endl;\r\n        return false;\r\n    }\r\n\r\n    //\r\n\r\n    vector<complex<double>> ().swap(f__);\r\n    f__.reserve(n_);\r\n    for(const auto &it:t__) {\r\n        f__.push_back(complex<double> (it, 0.0));\r\n    }\r\n\r\n    if(window_func_name_ != \"\") { ApplyWindow(f__); }\r\n\r\n    if(_FFT_CT_seq(f__)) {\r\n\r\n        for(auto &&it : f__) {\r\n            it /= n_; // Correcting the amplitude.\r\n        }\r\n\r\n        return true;\r\n\r\n    } else {\r\n\r\n        return false;\r\n\r\n    }\r\n\r\n}\r\n\r\n\r\n//--------------------------------------------------//\r\n\r\n\r\nvector<complex<double>> MyFFT::FFT_CT_seq(const vector<double> &t__) {\r\n\r\n    vector<complex<double>> f;\r\n\r\n    if(static_cast<uint_fast32_t>(t__.size()) != n_) {\r\n        cerr << \"[ERROR][MyFFT] The number of input data is not a multiply of 2.\" << endl;\r\n        return f;\r\n    }\r\n\r\n    //\r\n\r\n    if(FFT_CT_seq(t__, f)) {\r\n\r\n        for(auto &&it : f) {\r\n            it /= n_; // Correcting the amplitude.\r\n        }\r\n\r\n    } else {\r\n\r\n        vector<complex<double>> ().swap(f);\r\n\r\n    }\r\n\r\n    return f;\r\n\r\n}\r\n\r\n\r\n//--------------------------------------------------//\r\n///\r\n/// @brief   Executing inverted FFT\r\n/// @return  None.\r\n///\r\n//--------------------------------------------------//\r\n\r\n\r\nbool MyFFT::IFFT_CT_seq(const vector<complex<double>> &f__, vector<complex<double>> &t__) {\r\n\r\n    if(!Preparing_IFFT(f__, t__)) { return false; }\r\n\r\n    //\r\n\r\n    if(_FFT_CT_seq(t__)) {\r\n\r\n        for(auto &&it : t__) { it = conj(it); }\r\n\r\n        return true;\r\n\r\n    } else {\r\n\r\n        return false;\r\n\r\n    }\r\n\r\n}\r\n\r\n\r\n//--------------------------------------------------//\r\n\r\n\r\nbool MyFFT::IFFT_CT_seq(const vector<complex<double>> &f__, vector<double> &t__) {\r\n\r\n    vector<complex<double>> t;\r\n\r\n    if(!Preparing_IFFT(f__, t)) { return false; }\r\n\r\n    //\r\n\r\n    if(_FFT_CT_seq(t)) {\r\n\r\n        for(auto &&it : t) { it = conj(it); }\r\n\r\n    } else {\r\n\r\n        return false;\r\n\r\n    }\r\n\r\n    //\r\n\r\n    vector<double> ().swap(t__);\r\n    t__.reserve(n_);\r\n\r\n    for(const auto &it : t) {\r\n        t__.push_back(it.real());\r\n    }\r\n\r\n    return true;\r\n\r\n}\r\n\r\n\r\n//--------------------------------------------------//\r\n\r\n\r\nvector<complex<double>> MyFFT::IFFT_CT_seq(const vector<complex<double>> &f__) {\r\n\r\n    vector<complex<double>> t;\r\n\r\n    if(!Preparing_IFFT(f__, t)) { return t; }\r\n\r\n    //\r\n\r\n    if(_FFT_CT_seq(t)) {\r\n\r\n        for(auto &&it : t) { it = conj(it); }\r\n\r\n    } else {\r\n\r\n        vector<complex<double>> ().swap(t);\r\n\r\n    }\r\n\r\n    return t;\r\n\r\n}\r\n\r\n\r\n//--------------------------------------------------//\r\n\r\n\r\nbool MyFFT::Preparing_IFFT(const vector<complex<double>> &f__, vector<complex<double>> &t__) {\r\n\r\n    if(static_cast<uint_fast32_t>(f__.size()) == n_) {\r\n\r\n        t__ = f__;\r\n\r\n    }\r\n    else if(static_cast<uint_fast32_t>(f__.size()) == (n_half_ + 1)) {\r\n\r\n        vector<complex<double>> ().swap(t__);\r\n        t__.reserve(n_);\r\n\r\n        for(const auto &it : f__) {\r\n            t__.push_back(it);\r\n        }\r\n\r\n        for(int i=n_half_; i>0; i--) {\r\n            t__.push_back(t__[i]);\r\n        }\r\n\r\n    }\r\n    else {\r\n\r\n        cerr << \"[ERROR][MyFFT] The number of input data is irregular. : \" << f__.size() << endl;\r\n        return false;\r\n\r\n    }\r\n\r\n    //\r\n\r\n    for(auto &&it : t__) { it = conj(it); }\r\n\r\n    return true;\r\n\r\n}\r\n\r\n\r\n//--------------------------------------------------//\r\n///\r\n/// @brief   Executing FFT\r\n/// @return  None.\r\n///\r\n//--------------------------------------------------//\r\n\r\n\r\nbool MyFFT::_FFT_CT_seq(vector<complex<double>> &x__) {\r\n\r\n    uint_fast32_t n;\r\n\r\n    uint_fast32_t N;\r\n    double thetaT;\r\n\r\n    {\r\n        unique_lock<std::mutex> wait_lock(mtx_wait_);\r\n\r\n        N = n_;\r\n        thetaT = PI_ / N;\r\n    }\r\n\r\n    uint_fast32_t k = N;\r\n\r\n    complex<double> T;\r\n    complex<double> tmp;\r\n    complex<double> phiT = complex<double>(cos(thetaT), -sin(thetaT));\r\n\r\n    //\r\n\r\n    while(k > 1) {\r\n\r\n        n = k;\r\n        k >>= 1;\r\n        phiT = phiT * phiT;\r\n        T = 1.0L;\r\n\r\n        for (uint_fast32_t l = 0; l < k; l++) {\r\n\r\n            for (uint_fast32_t a = l; a < N; a += n) {\r\n\r\n                uint_fast32_t b = a + k;\r\n\r\n                tmp = x__[a] - x__[b];\r\n                x__[a] += x__[b];\r\n                x__[b] = tmp * T;\r\n\r\n            }\r\n\r\n            T *= phiT;\r\n\r\n        }\r\n\r\n    }\r\n\r\n    //\r\n    // Reverse bits\r\n    //\r\n\r\n    complex<double> tmp_swap;\r\n\r\n    int i1 = 0;\r\n\r\n    {\r\n        unique_lock<std::mutex> wait_lock(mtx_wait_);\r\n\r\n        for(const auto &i2 : i_bit_rev_) {\r\n            tmp_swap = x__[i1];\r\n            x__[i1] = x__[i2];\r\n            x__[i2] = tmp_swap;\r\n            i1++;\r\n        }\r\n    }\r\n\r\n    return true;\r\n\r\n}\r\n\r\n\r\n//--------------------------------------------------//\r\n///\r\n/// @brief     GSts the window function.\r\n/// @param[in] window_func_name__ : name of window function\r\n///            @arg \"hanning\"  = Hanning(Hann) window function\r\n///            @arg \"hamming\"  = Hamming window function\r\n///            @arg \"blackman\" = Blackman window function\r\n///            @arg \"flat-top\" = Flat top window function\r\n///            @arg \"\" or others = rectangular window function\r\n/// @return    None.\r\n///\r\n//--------------------------------------------------//\r\n\r\n\r\nvoid MyFFT::SetWindow(const string &window_func_name__, const bool &use_acf__) {\r\n\r\n    window_func_name_ = window_func_name__;\r\n\r\n    use_acf_ = use_acf__;\r\n\r\n    //\r\n\r\n    vector<double> ().swap(wf_);\r\n    wf_.resize(n_);\r\n\r\n    double coeff = 2 * PI_ / n_;\r\n\r\n    double sum = 0;\r\n\r\n    int i = 0;\r\n\r\n    if(window_func_name_ == \"hanning\") {\r\n\r\n        for(auto &&it : wf_) {\r\n            it = 0.5 - 0.5 * cos(coeff * i);\r\n            sum += it;\r\n            i++;\r\n        }\r\n        acf_ = n_ / sum;\r\n\r\n    }\r\n    else if(window_func_name_ == \"hamming\") {\r\n\r\n        for(auto &&it : wf_) {\r\n            it = 0.54 - 0.46 * cos(coeff * i);\r\n            sum += it;\r\n            i++;\r\n        }\r\n        acf_ = n_ / sum;\r\n\r\n    }\r\n    else if(window_func_name_ == \"blackman\") {\r\n\r\n        for(auto &&it : wf_) {\r\n            it = 0.42 - 0.5 * cos(coeff * i) + 0.08 * cos(2 * coeff * i);\r\n            sum += it;\r\n            i++;\r\n        }\r\n        acf_ = n_ / sum;\r\n\r\n    }\r\n    else if(window_func_name_ == \"flat-top\") {\r\n\r\n        for(auto &&it : wf_) {\r\n            it   = 1 - 1.93 * cos(coeff * i);\r\n            it  +=  1.29  * cos(2 * coeff * i);\r\n            it  += -0.388 * cos(3 * coeff * i);\r\n            it  +=  0.032 * cos(4 * coeff * i);\r\n            sum += it;\r\n            i++;\r\n        }\r\n        acf_ = n_ / sum;\r\n\r\n    }\r\n    else {\r\n\r\n        for(auto &&it : wf_) { it = 1.0; i++; }\r\n        acf_ = 1.0;\r\n\r\n    }\r\n\r\n    return;\r\n\r\n\r\n}\r\n\r\n\r\n//--------------------------------------------------//\r\n///\r\n/// @brief      Gets the window function.\r\n/// @param[out] wf__ : the window function array\r\n/// @return     None.\r\n///\r\n//--------------------------------------------------//\r\n\r\n\r\nvoid MyFFT::GetWindow(std::vector<double> &wf__) {\r\n\r\n    wf__ = wf_;\r\n\r\n    return;\r\n\r\n}\r\n\r\n\r\n//--------------------------------------------------//\r\n///\r\n/// @brief      Applys the window function to time data.\r\n/// @param[out] w__ : the window function array\r\n/// @return     None.\r\n///\r\n//--------------------------------------------------//\r\n\r\n\r\nvoid MyFFT::ApplyWindow(vector<complex<double>> &t__) {\r\n\r\n    uint_fast32_t n = t__.size();\r\n\r\n    if(n >= n_) {\r\n\r\n        if(use_acf_) {\r\n            for(uint_fast32_t i=0;i<n_;i++) { t__[i] = acf_ * wf_[i] * t__[i]; }\r\n        } else {\r\n            for(uint_fast32_t i=0;i<n_;i++) { t__[i] = wf_[i] * t__[i]; }\r\n        }\r\n\r\n        if(t__.size() > n_) {\r\n            t__.resize(n_);\r\n        }\r\n\r\n    }\r\n\r\n    return;\r\n\r\n}\r\n\r\n\r\n/*\r\n//--------------------------------------------------//\r\n///\r\n/// @brief   Flat top window function\r\n/// @return  None.\r\n///\r\n//--------------------------------------------------//\r\n\r\n\r\nvoid MyFFT::GetWF_FlatTop(std::vector<double> &w__) {\r\n\r\n    vector<double> ().swap(w__);\r\n    w__.resize(n_);\r\n\r\n    double coeff = 2 * PI_ / n_;\r\n\r\n    int i = 0;\r\n\r\n    for(auto &&it : w__) {\r\n        it  = 1 - 1.93 * cos(coeff * i)\r\n        it +=  1.29  * cos(2 * coeff * i)\r\n        it += -0.388 * cos(3 * coeff * i)\r\n        it += +0.032 * cos(4 * coeff * i)\r\n        i++;\r\n    }\r\n\r\n    return;\r\n\r\n}\r\n*/\r\n\r\n//--------------------------------------------------//\r\n///\r\n/// @brief   Converting data.\r\n/// @return  None.\r\n///\r\n//--------------------------------------------------//\r\n\r\n\r\nbool MyFFT::C2RI(const vector<complex<double>> &c__, vector<double> &c_real__, vector<double> &c_imag__) {\r\n\r\n    int n = c__.size();\r\n\r\n    if(n == 0 || (n%2) != 0) {\r\n        return false;\r\n    }\r\n\r\n    vector<double> ().swap(c_real__);\r\n    vector<double> ().swap(c_imag__);\r\n\r\n    c_real__.reserve(n);\r\n    c_imag__.reserve(n);\r\n\r\n    for(const auto &it : c__) {\r\n        c_real__.push_back(it.real());\r\n        c_imag__.push_back(it.imag());\r\n    }\r\n\r\n    return true;\r\n\r\n}\r\n\r\n\r\n//--------------------------------------------------//\r\n\r\n\r\nbool MyFFT::RI2C(const vector<double> &c_real__, const vector<double> &c_imag__, vector<complex<double>> &c__) {\r\n\r\n    int n_real = c_real__.size();\r\n    int n_imag = c_imag__.size();\r\n\r\n    if(n_real == 0 || n_real != n_imag) {\r\n        return false;\r\n    }\r\n\r\n    vector<complex<double>> ().swap(c__);\r\n\r\n    c__.reserve(n_real);\r\n\r\n    for(int i=0;i<n_real;i++) {\r\n        c__.push_back(complex<double> (c_real__[i], c_imag__[i]));\r\n    }\r\n\r\n    return true;\r\n\r\n}\r\n\r\n\r\n//--------------------------------------------------//\r\n\r\n\r\nbool MyFFT::C2AP(const vector<complex<double>> &c__, vector<double> &c_amp__, vector<double> &c_phas__) {\r\n\r\n    int n = c__.size();\r\n    int n_half = n / 2;\r\n\r\n    if(n == 0 || (n%2) != 0) {\r\n        return false;\r\n    }\r\n\r\n    vector<double> ().swap(c_amp__);\r\n    vector<double> ().swap(c_phas__);\r\n\r\n    c_amp__.reserve(n_half + 1);\r\n    c_phas__.reserve(n_half + 1);\r\n\r\n    for(int i=0;i<=n_half;i++) {\r\n        c_amp__.push_back(abs(c__[i]));\r\n        c_phas__.push_back(arg(c__[i]));\r\n    }\r\n\r\n    for(int i=0;i<n_half;i++) {\r\n        c_amp__[n_half-i] += abs(c__[n_half+i]);\r\n    }\r\n\r\n    return true;\r\n\r\n}\r\n\r\n\r\n//--------------------------------------------------//\r\n\r\n\r\nbool MyFFT::AP2C(const vector<double> &c_amp__, const vector<double> &c_phas__, vector<complex<double>> &c__) {\r\n\r\n    int n_amp  = c_amp__.size();\r\n    int n_phas = c_phas__.size();\r\n\r\n    if(n_amp == 0 || n_amp != n_phas) {\r\n        return false;\r\n    }\r\n\r\n    int n = (n_amp -1) * 2;\r\n\r\n    vector<complex<double>> ().swap(c__);\r\n\r\n    c__.reserve(n);\r\n\r\n    c__.push_back(complex<double> (c_amp__[0]*cos(c_phas__[0]), c_amp__[0]*sin(c_phas__[0])));\r\n\r\n    for(int i=1;i<n_amp;i++) {\r\n        c__.push_back(complex<double> (0.5 * c_amp__[i]*cos(c_phas__[i]), 0.5 * c_amp__[i]*sin(c_phas__[i])));\r\n    }\r\n\r\n    //cout << \"00\" << endl;\r\n\r\n    for(int i=n_amp-2;i>0;i--) {\r\n        c__.push_back(conj(c__[i]));\r\n    }\r\n\r\n    //cout << \"01 : \" << c__.size() << endl;\r\n\r\n    return true;\r\n\r\n}\r\n\r\n\r\n//--------------------------------------------------//\r\n\r\n\r\n};\r\n", "meta": {"hexsha": "6af6e45a067c64fcccb221785ae97e7f8d7a5d84", "size": 38445, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "MyFFT/MyFFT.cpp", "max_stars_repo_name": "cogoto/MyAll", "max_stars_repo_head_hexsha": "20d8b65fd8c8fdd1806b7175e8f54aee223db3a5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "MyFFT/MyFFT.cpp", "max_issues_repo_name": "cogoto/MyAll", "max_issues_repo_head_hexsha": "20d8b65fd8c8fdd1806b7175e8f54aee223db3a5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "MyFFT/MyFFT.cpp", "max_forks_repo_name": "cogoto/MyAll", "max_forks_repo_head_hexsha": "20d8b65fd8c8fdd1806b7175e8f54aee223db3a5", "max_forks_repo_licenses": ["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.3702056698, "max_line_length": 170, "alphanum_fraction": 0.4379243075, "num_tokens": 10063, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6039318337259583, "lm_q2_score": 0.5312093733737563, "lm_q1q2_score": 0.3208142509540299}}
{"text": "/*\n    Copyright 2016 Emanuele Vespa, Imperial College London\n    Redistribution and use in source and binary forms, with or without\n    modification, are permitted provided that the following conditions are met:\n\n    1. Redistributions of source code must retain the above copyright notice, 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 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\" 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#ifndef OCTANT_OPS_HPP\n#define OCTANT_OPS_HPP\n#include \"utils/morton_utils.hpp\"\n#include \"utils/math_utils.h\"\n#include \"octree_defines.h\"\n#include <iostream>\n#include <bitset>\n#include <Eigen/Dense>\n\nnamespace se {\n  namespace keyops {\n\n    inline se::key_t code(const se::key_t octant_key) {\n      return octant_key & ~SCALE_MASK;\n    }\n\n    inline int depth(const se::key_t octant_key) {\n      return octant_key & SCALE_MASK;\n}\n\n    inline se::key_t encode(const int x, const int y, const int z,\n        const int depth, const int voxel_depth) {\n      const int offset = MAX_BITS - voxel_depth + depth - 1;\n      return (compute_morton(x, y, z) & MASK[offset] & ~SCALE_MASK) | depth;\n    }\n\n    inline Eigen::Vector3i decode(const se::key_t octant_key) {\n      return unpack_morton(octant_key & ~SCALE_MASK);\n    }\n  }\n\n/*\n * Algorithm 5 of p4est paper: https://epubs.siam.org/doi/abs/10.1137/100791634\n */\ninline Eigen::Vector3i face_neighbour(const se::key_t octant_key,\n    const unsigned int face, const unsigned int l,\n    const unsigned int voxel_depth) {\n  Eigen::Vector3i octant_coord = se::keyops::decode(octant_key);\n  const unsigned int octant_size = 1 << (voxel_depth - l);\n  octant_coord.x() = octant_coord.x() + ((face == 0) ? -octant_size : (face == 1) ? octant_size : 0);\n  octant_coord.y() = octant_coord.y() + ((face == 2) ? -octant_size : (face == 3) ? octant_size : 0);\n  octant_coord.z() = octant_coord.z() + ((face == 4) ? -octant_size : (face == 5) ? octant_size : 0);\n  return {octant_coord.x(), octant_coord.y(), octant_coord.z()};\n}\n\n/*\n * \\brief Return true if node is a descendant of ancestor\n * \\param[in] octant_key\n * \\param[in] ancestor_key\n * \\param[in] voxel_depth  Max/voxel depth of the tree the keys refer to.\n * \\return True if octant_key is a descendant of the ancestor_key or if\n *         they are equal.\n */\ninline bool descendant(const se::key_t octant_key,\n                       const se::key_t ancestor_key,\n                       const int       voxel_depth) {\n  const int depth = se::keyops::depth(octant_key);\n  const int ancestor_depth = se::keyops::depth(ancestor_key);\n  // MAX_BITS is used for the maximum voxel depth given the size of the se::key_t\n  const int idx = MAX_BITS - voxel_depth + ancestor_depth - 1;\n  const se::key_t ancestor_key_code = se::keyops::code(ancestor_key);\n  const se::key_t octant_key_code = se::keyops::code(octant_key) & MASK[idx];\n  return (depth >= ancestor_depth) && (ancestor_key_code ^ octant_key_code) == 0;\n}\n\n/*\n * \\brief Computes the parent's morton code of a given octant\n * \\param octant_key\n * \\param voxel_depth max depth of the tree on which the octant lives\n */\ninline se::key_t parent(const se::key_t& octant_key, const int voxel_depth) {\n  const int depth = se::keyops::depth(octant_key) - 1;\n  const int idx = MAX_BITS - voxel_depth + depth - 1;\n  return (octant_key & MASK[idx]) | depth;\n}\n\n/*\n * \\brief Computes the octants's id in its local brotherhood\n * \\param octant_key\n * \\param depth of octant\n * \\param voxel_depth max depth of the tree on which the octant lives\n */\ninline int child_idx(se::key_t octant_key, const int depth,\n    const int voxel_depth) {\n  int shift = voxel_depth - depth;\n  octant_key = se::keyops::code(octant_key) >> shift*3;\n  int idx = (octant_key & 0x01) | (octant_key & 0x02) | (octant_key & 0x04);\n  return idx;\n}\n\n/*\n * \\brief Computes the octants's id in its local brotherhood\n * \\param octant_key\n * \\param depth of octant\n * \\param voxel_depth max depth of the tree on which the octant lives\n */\ninline int child_idx(se::key_t octant_key, const int voxel_depth) {\n  int shift = voxel_depth - se::keyops::depth(octant_key);\n  octant_key = se::keyops::code(octant_key) >> shift*3;\n  int idx = (octant_key & 0x01) | (octant_key & 0x02) | (octant_key & 0x04);\n  return idx;\n}\n\n/*\n * \\brief Computes the octants's corner which is not shared with its siblings\n * \\param octant_key\n * \\param depth of octant\n * \\param voxel_depth max depth of the tree on which the octant lives\n */\ninline Eigen::Vector3i far_corner(const se::key_t octant_key, const int depth,\n    const int voxel_depth) {\n  const unsigned int octant_size = 1 << (voxel_depth - depth);\n  const int child_idx = se::child_idx(octant_key, depth, voxel_depth);\n  const Eigen::Vector3i octant_coord = se::keyops::decode(octant_key);\n  return Eigen::Vector3i(octant_coord.x() + ( child_idx & 1)       * octant_size,\n                         octant_coord.y() + ((child_idx & 2) >> 1) * octant_size,\n                         octant_coord.z() + ((child_idx & 4) >> 2) * octant_size);\n}\n\n/*\n * \\brief Computes the non-sibling neighbourhood around an octants. In the\n * special case in which the octant lies on an edge, neighbour are duplicated\n * as movement outside the enclosing cube is forbidden.\n * \\param result 7-vector containing the neighbours\n * \\param octant_key\n * \\param depth of octant\n * \\param voxel_depth max depth of the tree on which the octant lives\n */\ninline void exterior_neighbours(se::key_t result[7],\n    const se::key_t octant_key, const int depth, const int voxel_depth) {\n\n  const int child_idx = se::child_idx(octant_key, depth, voxel_depth);\n  Eigen::Vector3i dir = Eigen::Vector3i((child_idx & 1) ? 1 : -1,\n                                        (child_idx & 2) ? 1 : -1,\n                                        (child_idx & 4) ? 1 : -1);\n  Eigen::Vector3i base_coord = far_corner(octant_key, depth, voxel_depth);\n  dir.x() = se::math::in(base_coord.x() + dir.x() , 0, (1 << voxel_depth) - 1) ? dir.x() : 0;\n  dir.y() = se::math::in(base_coord.y() + dir.y() , 0, (1 << voxel_depth) - 1) ? dir.y() : 0;\n  dir.z() = se::math::in(base_coord.z() + dir.z() , 0, (1 << voxel_depth) - 1) ? dir.z() : 0;\n\n result[0] = se::keyops::encode(base_coord.x() + dir.x(), base_coord.y() + 0, base_coord.z() + 0,\n     depth, voxel_depth);\n result[1] = se::keyops::encode(base_coord.x() + 0, base_coord.y() + dir.y(), base_coord.z() + 0,\n     depth, voxel_depth);\n result[2] = se::keyops::encode(base_coord.x() + dir.x(), base_coord.y() + dir.y(), base_coord.z() + 0,\n     depth, voxel_depth);\n result[3] = se::keyops::encode(base_coord.x() + 0, base_coord.y() + 0, base_coord.z() + dir.z(),\n     depth, voxel_depth);\n result[4] = se::keyops::encode(base_coord.x() + dir.x(), base_coord.y() + 0, base_coord.z() + dir.z(),\n     depth, voxel_depth);\n result[5] = se::keyops::encode(base_coord.x() + 0, base_coord.y() + dir.y(), base_coord.z() + dir.z(),\n     depth, voxel_depth);\n result[6] = se::keyops::encode(base_coord.x() + dir.x(), base_coord.y() + dir.y(),\n     base_coord.z() + dir.z(), depth, voxel_depth);\n}\n\n/*\n * \\brief Computes the six face neighbours of an octant. These are stored in an\n * 4x6 matrix in which each column represents the homogeneous coordinates of a\n * neighbouring octant. The neighbours along the x axis come first, followed by\n * neighbours along the y axis and finally along the z axis. All coordinates are\n * clamped to be in the range between [0, max_size] where max size is given\n * by pow(2, voxel_depth).\n * \\param res 4x6 matrix containing the neighbours\n * \\param octant_coord octant coordinates\n * \\param depth depth of the octant\n * \\param voxel_depth max depth of the tree on which the octant lives\n */\n\nstatic inline void one_neighbourhood(Eigen::Ref<Eigen::Matrix<int, 4, 6>> res,\n    const Eigen::Vector3i& octant_coord, const int depth, const int voxel_depth) {\n  const Eigen::Vector3i base_coord = octant_coord;\n  const int size = 1 << voxel_depth;\n  const int step = 1 << (voxel_depth - depth);\n  Eigen::Matrix<int, 4, 6> cross;\n  res <<\n    -step, step,     0,    0,     0,    0,\n        0,    0, -step, step,     0,    0,\n        0,    0,     0,    0, -step, step,\n        0,    0,     0,    0,     0,    0;\n    res.colwise() += base_coord.homogeneous();\n    res = res.unaryExpr([size](const int a) {\n        return std::max(std::min(a, size-1), 0);\n        });\n}\n\n/*\n * \\brief Computes the six face neighbours of an octant. These are stored in an\n * 4x6 matrix in which each column represents the homogeneous coordinates of a\n * neighbouring octant. The neighbours along the x axis come first, followed by\n * neighbours along the y axis and finally along the z axis. All coordinates are\n * clamped to be in the range between [0, max_size] where max size is given\n * by pow(2, voxel_depth).\n * \\param res 4x6 matrix containing the neighbours\n * \\param octant octant key\n * \\param voxel_depth max depth of the tree on which the octant lives\n */\n\nstatic inline void one_neighbourhood(Eigen::Ref<Eigen::Matrix<int, 4, 6>> res,\n    const se::key_t octant_key, const int voxel_depth) {\n  one_neighbourhood(res, se::keyops::decode(octant_key), se::keyops::depth(octant_key),\n      voxel_depth);\n}\n\n/*\n * \\brief Computes the morton number of all siblings around an octant,\n * including itself.\n * \\param result 8-vector containing the neighbours\n * \\param octant\n * \\param voxel_depth max depth of the tree on which the octant lives\n */\ninline void siblings(se::key_t result[8],\n    const se::key_t octant_key, const int voxel_depth) {\n  const int depth = (octant_key & SCALE_MASK);\n  const int shift = 3 * (voxel_depth - depth);\n  const se::key_t parent_key = parent(octant_key, voxel_depth) + 1; // set-up next depth\n  for(int i = 0; i < 8; ++i) {\n    result[i] = parent_key | (i << shift);\n  }\n}\n}\n#endif\n", "meta": {"hexsha": "6c4cfe80d2a902e70490f8cbcd1c3e6135917004", "size": 10931, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "se_core/include/se/octant_ops.hpp", "max_stars_repo_name": "hexagon-geo-surv/supereight-public", "max_stars_repo_head_hexsha": "29a978956d2b169a3f34eed9bc374e325551c10b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "se_core/include/se/octant_ops.hpp", "max_issues_repo_name": "hexagon-geo-surv/supereight-public", "max_issues_repo_head_hexsha": "29a978956d2b169a3f34eed9bc374e325551c10b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "se_core/include/se/octant_ops.hpp", "max_forks_repo_name": "hexagon-geo-surv/supereight-public", "max_forks_repo_head_hexsha": "29a978956d2b169a3f34eed9bc374e325551c10b", "max_forks_repo_licenses": ["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.5498007968, "max_line_length": 103, "alphanum_fraction": 0.6830116183, "num_tokens": 3044, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.66192288918838, "lm_q2_score": 0.48438008427698437, "lm_q1q2_score": 0.3206222648499325}}
{"text": "/* pcmsolver_copyright_start */\n/*\n *     PCMSolver, an API for the Polarizable Continuum Model\n *     Copyright (C) 2013-2016 Roberto Di Remigio, Luca Frediani and contributors\n *     \n *     This file is part of PCMSolver.\n *     \n *     PCMSolver is free software: you can redistribute it and/or modify\n *     it under the terms of the GNU Lesser General Public License as published by\n *     the Free Software Foundation, either version 3 of the License, or\n *     (at your option) any later version.\n *     \n *     PCMSolver is distributed in the hope that it will be useful,\n *     but WITHOUT ANY WARRANTY; without even the implied warranty of\n *     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n *     GNU Lesser General Public License for more details.\n *     \n *     You should have received a copy of the GNU Lesser General Public License\n *     along with PCMSolver.  If not, see <http://www.gnu.org/licenses/>.\n *     \n *     For information on the complete list of contributors to the\n *     PCMSolver API, see: <http://pcmsolver.readthedocs.io/>\n */\n/* pcmsolver_copyright_end */\n\n#ifndef GREENSFUNCTION_HPP\n#define GREENSFUNCTION_HPP\n\n#include <iosfwd>\n\n#include \"Config.hpp\"\n\n#include <Eigen/Core>\n\n#include \"DerivativeTypes.hpp\"\n#include \"IGreensFunction.hpp\"\n#include \"utils/Stencils.hpp\"\n\n/*! \\file GreensFunction.hpp\n *  \\class GreensFunction\n *  \\brief Templated interface for Green's functions\n *  \\author Luca Frediani and Roberto Di Remigio\n *  \\date 2012-2014\n *  \\tparam DerivativeTraits evaluation strategy for the function and its derivatives\n *  \\tparam IntegratorPolicy policy for the calculation of the matrix represenation of S and D\n *  \\tparam ProfilePolicy    dielectric profile type\n */\n\ntemplate <typename DerivativeTraits,\n          typename IntegratorPolicy,\n          typename ProfilePolicy,\n          typename Derived>\nclass GreensFunction: public IGreensFunction\n{\npublic:\n    GreensFunction() : delta_(1.0e-04), integrator_(IntegratorPolicy()) {}\n    GreensFunction(double f) : delta_(1.0e-04), integrator_(IntegratorPolicy(f)) {}\n    virtual ~GreensFunction() {}\n    /*! Returns value of the directional derivative of the\n     *  Greens's function for the pair of points p1, p2:\n     *  \\f$ \\nabla_{\\mathbf{p_1}}G(\\mathbf{p}_1, \\mathbf{p}_2)\\cdot \\mathbf{n}_{\\mathbf{p}_1}\\f$\n     *  Notice that this method returns the directional derivative with respect\n     *  to the source point.\n     *  \\param[in] normal_p1 the normal vector to p1\n     *  \\param[in]        p1 first point\n     *  \\param[in]        p2 second point\n     */\n    virtual double derivativeSource(const Eigen::Vector3d & normal_p1,\n                            const Eigen::Vector3d & p1, const Eigen::Vector3d & p2) const\n    {\n        DerivativeTraits t1[3], t2[3];\n        t1[0] = p1(0); t1[1] = p1(1); t1[2] = p1(2);\n        t1[0][1] = normal_p1(0); t1[1][1] = normal_p1(1); t1[2][1] = normal_p1(2);\n        t2[0] = p2(0); t2[1] = p2(1); t2[2] = p2(2);\n        return this->operator()(t1, t2)[1];\n    }\n    /*! Returns value of the directional derivative of the\n     *  Greens's function for the pair of points p1, p2:\n     *  \\f$ \\nabla_{\\mathbf{p_2}}G(\\mathbf{p}_1, \\mathbf{p}_2)\\cdot \\mathbf{n}_{\\mathbf{p}_2}\\f$\n     *  Notice that this method returns the directional derivative with respect\n     *  to the probe point.\n     *  \\param[in] normal_p2 the normal vector to p2\n     *  \\param[in]        p1 first point\n     *  \\param[in]        p2 second point\n     */\n    virtual double derivativeProbe(const Eigen::Vector3d & normal_p2,\n                                   const Eigen::Vector3d & p1, const Eigen::Vector3d & p2) const __final\n    {\n        DerivativeTraits t1[3], t2[3];\n        t1[0] = p1(0); t1[1] = p1(1); t1[2] = p1(2);\n        t2[0] = p2(0); t2[1] = p2(1); t2[2] = p2(2);\n        t2[0][1] = normal_p2(0); t2[1][1] = normal_p2(1); t2[2][1] = normal_p2(2);\n        return this->operator()(t1, t2)[1];\n    }\n    /*! Returns full gradient of Greens's function for the pair of points p1, p2:\n     *  \\f$ \\nabla_{\\mathbf{p_1}}G(\\mathbf{p}_1, \\mathbf{p}_2)\\f$\n     *  Notice that this method returns the gradient with respect to the source point.\n     *  \\param[in] p1 first point\n     *  \\param[in] p2 second point\n     */\n    Eigen::Vector3d gradientSource(const Eigen::Vector3d & p1,\n                                           const Eigen::Vector3d & p2) const\n    {\n        return (Eigen::Vector3d() << derivativeSource(Eigen::Vector3d::UnitX(), p1, p2),\n                derivativeSource(Eigen::Vector3d::UnitY(), p1, p2),\n                derivativeSource(Eigen::Vector3d::UnitZ(), p1, p2)).finished();\n    }\n    /*! Returns full gradient of Greens's function for the pair of points p1, p2:\n     *  \\f$ \\nabla_{\\mathbf{p_2}}G(\\mathbf{p}_1, \\mathbf{p}_2)\\f$\n     *  Notice that this method returns the gradient with respect to the probe point.\n     *  \\param[in] p1 first point\n     *  \\param[in] p2 second point\n     */\n    Eigen::Vector3d gradientProbe(const Eigen::Vector3d & p1,\n                                          const Eigen::Vector3d & p2) const\n    {\n        return (Eigen::Vector3d() << derivativeProbe(Eigen::Vector3d::UnitX(), p1, p2),\n                derivativeProbe(Eigen::Vector3d::UnitY(), p1, p2),\n                derivativeProbe(Eigen::Vector3d::UnitZ(), p1, p2)).finished();\n    }\n\n    /*! Whether the Green's function describes a uniform environment */\n    virtual bool uniform() const __final __override { return profiles::uniform(this->profile_); }\n    /*! Returns a dielectric permittivity profile */\n    virtual Permittivity permittivity() const __final __override { return this->profile_; }\n\n    friend std::ostream & operator<<(std::ostream & os, GreensFunction & gf) {\n        return gf.printObject(os);\n    }\nprotected:\n    /*! Evaluates the Green's function given a pair of points\n     *  \\param[in] source the source point\n     *  \\param[in]  probe the probe point\n     */\n    virtual DerivativeTraits operator()(DerivativeTraits * source, DerivativeTraits * probe) const = 0;\n    /*! Returns value of the kernel of the \\f$\\mathcal{S}\\f$ integral operator, i.e. the value of the\n     *  Greens's function for the pair of points p1, p2: \\f$ G(\\mathbf{p}_1, \\mathbf{p}_2)\\f$\n     *  \\param[in] p1 first point\n     *  \\param[in] p2 second point\n     *  \\note Relies on the implementation of operator() in the subclasses and that is all subclasses\n     *  need to implement. Thus this method is marked __final.\n     */\n    virtual double kernelS_impl(const Eigen::Vector3d & p1, const Eigen::Vector3d & p2) const __final __override\n    {\n        DerivativeTraits sp[3], pp[3];\n        sp[0] = p1(0); sp[1] = p1(1); sp[2] = p1(2);\n        pp[0] = p2(0); pp[1] = p2(1); pp[2] = p2(2);\n        return this->operator()(sp, pp)[0];\n    }\n    virtual std::ostream & printObject(std::ostream & os) __override\n    {\n        os << \"Green's Function\" << std::endl;\n        return os;\n    }\n    double delta_;\n    IntegratorPolicy integrator_;\n    ProfilePolicy profile_;\n};\n\ntemplate <typename IntegratorPolicy,\n          typename ProfilePolicy,\n          typename Derived>\nclass GreensFunction<Numerical, IntegratorPolicy, ProfilePolicy, Derived>: public IGreensFunction\n{\npublic:\n    GreensFunction() : delta_(1.0e-04), integrator_(IntegratorPolicy()) {}\n    GreensFunction(double f) : delta_(1.0e-04), integrator_(IntegratorPolicy(f)) {}\n    virtual ~GreensFunction() {}\n    /*! Returns value of the directional derivative of the\n     *  Greens's function for the pair of points p1, p2:\n     *  \\f$ \\nabla_{\\mathbf{p_1}}G(\\mathbf{p}_1, \\mathbf{p}_2)\\cdot \\mathbf{n}_{\\mathbf{p}_1}\\f$\n     *  Notice that this method returns the directional derivative with respect\n     *  to the source point.\n     *  \\param[in] normal_p1 the normal vector to p1\n     *  \\param[in]        p1 first point\n     *  \\param[in]        p2 second point\n     */\n    virtual double derivativeSource(const Eigen::Vector3d & normal_p1,\n                            const Eigen::Vector3d & p1, const Eigen::Vector3d & p2) const\n    {\n        return threePointStencil(pcm::bind(&GreensFunction<Numerical, IntegratorPolicy, ProfilePolicy, Derived>::kernelS, this, pcm::_1, pcm::_2),\n                                p1, p2, normal_p1, this->delta_);\n    }\n    /*! Returns value of the directional derivative of the\n     *  Greens's function for the pair of points p1, p2:\n     *  \\f$ \\nabla_{\\mathbf{p_2}}G(\\mathbf{p}_1, \\mathbf{p}_2)\\cdot \\mathbf{n}_{\\mathbf{p}_2}\\f$\n     *  Notice that this method returns the directional derivative with respect\n     *  to the probe point.\n     *  \\param[in] normal_p2 the normal vector to p2\n     *  \\param[in]        p1 first point\n     *  \\param[in]        p2 second point\n     */\n    virtual double derivativeProbe(const Eigen::Vector3d & normal_p2,\n                                   const Eigen::Vector3d & p1, const Eigen::Vector3d & p2) const __final\n    {\n        return threePointStencil(pcm::bind(&GreensFunction<Numerical, IntegratorPolicy, ProfilePolicy, Derived>::kernelS, this, pcm::_1, pcm::_2),\n                                p2, p1, normal_p2, this->delta_);\n    }\n    /*! Returns full gradient of Greens's function for the pair of points p1, p2:\n     *  \\f$ \\nabla_{\\mathbf{p_1}}G(\\mathbf{p}_1, \\mathbf{p}_2)\\f$\n     *  Notice that this method returns the gradient with respect to the source point.\n     *  \\param[in] p1 first point\n     *  \\param[in] p2 second point\n     */\n    Eigen::Vector3d gradientSource(const Eigen::Vector3d & p1,\n                                           const Eigen::Vector3d & p2) const\n    {\n        return (Eigen::Vector3d() << derivativeSource(Eigen::Vector3d::UnitX(), p1, p2),\n                derivativeSource(Eigen::Vector3d::UnitY(), p1, p2),\n                derivativeSource(Eigen::Vector3d::UnitZ(), p1, p2)).finished();\n    }\n    /*! Returns full gradient of Greens's function for the pair of points p1, p2:\n     *  \\f$ \\nabla_{\\mathbf{p_2}}G(\\mathbf{p}_1, \\mathbf{p}_2)\\f$\n     *  Notice that this method returns the gradient with respect to the probe point.\n     *  \\param[in] p1 first point\n     *  \\param[in] p2 second point\n     */\n    Eigen::Vector3d gradientProbe(const Eigen::Vector3d & p1,\n                                          const Eigen::Vector3d & p2) const\n    {\n        return (Eigen::Vector3d() << derivativeProbe(Eigen::Vector3d::UnitX(), p1, p2),\n                derivativeProbe(Eigen::Vector3d::UnitY(), p1, p2),\n                derivativeProbe(Eigen::Vector3d::UnitZ(), p1, p2)).finished();\n    }\n\n    /*! Whether the Green's function describes a uniform environment */\n    virtual bool uniform() const __final __override { return profiles::uniform(this->profile_); }\n    /*! Returns a dielectric permittivity profile */\n    virtual Permittivity permittivity() const __final __override { return this->profile_; }\n\n    friend std::ostream & operator<<(std::ostream & os, GreensFunction & gf) {\n        return gf.printObject(os);\n    }\nprotected:\n    /*! Evaluates the Green's function given a pair of points\n     *  \\param[in] source the source point\n     *  \\param[in]  probe the probe point\n     */\n    virtual Numerical operator()(Numerical * source, Numerical * probe) const = 0;\n    /*! Returns value of the kernel of the \\f$\\mathcal{S}\\f$ integral operator, i.e. the value of the\n     *  Greens's function for the pair of points p1, p2: \\f$ G(\\mathbf{p}_1, \\mathbf{p}_2)\\f$\n     *  \\param[in] p1 first point\n     *  \\param[in] p2 second point\n     *  \\note Relies on the implementation of operator() in the subclasses and that is all subclasses\n     *  need to implement. Thus this method is marked __final.\n     */\n    virtual double kernelS_impl(const Eigen::Vector3d & p1, const Eigen::Vector3d & p2) const __final __override\n    {\n        return this->operator()(const_cast<Numerical *>(p1.data()), const_cast<Numerical *>(p2.data()));\n    }\n    virtual std::ostream & printObject(std::ostream & os) __override\n    {\n        os << \"Green's Function\" << std::endl;\n        return os;\n    }\n    double delta_;\n    IntegratorPolicy integrator_;\n    ProfilePolicy profile_;\n};\n\n#endif // GREENSFUNCTION_HPP\n", "meta": {"hexsha": "8ae6485fd457d0816001864818ab17d4556f0a4d", "size": 12174, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "external/PCMSolver/PCMSolver-source/src/green/GreensFunction.hpp", "max_stars_repo_name": "robertodr/externalize", "max_stars_repo_head_hexsha": "c7b1dda2009dab329a6efb580c57ef8e1494cf3b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2017-02-15T22:16:34.000Z", "max_stars_repo_stars_event_max_datetime": "2017-02-15T22:16:34.000Z", "max_issues_repo_path": "external/PCMSolver/PCMSolver-source/src/green/GreensFunction.hpp", "max_issues_repo_name": "robertodr/externalize", "max_issues_repo_head_hexsha": "c7b1dda2009dab329a6efb580c57ef8e1494cf3b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "external/PCMSolver/PCMSolver-source/src/green/GreensFunction.hpp", "max_forks_repo_name": "robertodr/externalize", "max_forks_repo_head_hexsha": "c7b1dda2009dab329a6efb580c57ef8e1494cf3b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 46.465648855, "max_line_length": 146, "alphanum_fraction": 0.6317562017, "num_tokens": 3456, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6619228758499941, "lm_q2_score": 0.48438008427698437, "lm_q1q2_score": 0.320622258389084}}
{"text": "/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\n * Filename    : sphdec.hpp                                                                            *\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 : Function prototypes for sphdec.cpp                                                    *\n * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */\n\n#ifndef SPHDEC_HPP\n#define SPHDEC_HPP\n\n#include <armadillo>\n#include <vector>\n#include <complex>\n#include <limits>\n\nstd::vector<int> sphdec(const arma::vec &y, const arma::mat &R, const std::vector<int> &S,\n\t\t\t\t\t\tint &counter, double radius=std::numeric_limits<double>::max());\nstd::vector<int> sphdec_spherical_shaping(const arma::vec &y, const arma::mat &HR, const arma::mat &R, const std::vector<int> &S,\n\t\t\t\t\t\t\t\t\t\t  int &counter, double P, double radius=std::numeric_limits<double>::max());\nstd::vector<int> sphdec_wrapper(const std::vector<arma::cx_mat> &bases, const arma::mat Rorig,\n\t\t\t\t\t\t\t\tconst arma::cx_mat &H, const arma::cx_mat &X, const arma::cx_mat &N, \n\t\t\t\t\t\t\t\tconst std::vector<int> &symbset, int &visited_nodes, double radius=std::numeric_limits<double>::max());\n\n#endif /* SPHDEC_HPP */", "meta": {"hexsha": "da5cc4acbe60c242b61fb5e25e6d74ae7485aacb", "size": 1856, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/sphdec.hpp", "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/sphdec.hpp", "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/sphdec.hpp", "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": 66.2857142857, "max_line_length": 129, "alphanum_fraction": 0.4595905172, "num_tokens": 446, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6513548646660543, "lm_q2_score": 0.4921881357207956, "lm_q1q2_score": 0.3205891365326564}}
{"text": "#ifndef VIENNACL_LINALG_LANCZOS_HPP_\n#define VIENNACL_LINALG_LANCZOS_HPP_\n\n/* =========================================================================\n   Copyright (c) 2010-2014, Institute for Microelectronics,\n                            Institute for Analysis and Scientific Computing,\n                            TU Wien.\n   Portions of this software are copyright by UChicago Argonne, LLC.\n\n                            -----------------\n                  ViennaCL - The Vienna Computing Library\n                            -----------------\n\n   Project Head:    Karl Rupp                   rupp@iue.tuwien.ac.at\n\n   (A list of authors and contributors can be found in the PDF manual)\n\n   License:         MIT (X11), see file LICENSE in the base directory\n============================================================================= */\n\n/** @file viennacl/linalg/lanczos.hpp\n*   @brief Generic interface for the Lanczos algorithm.\n*\n*   Contributed by Guenther Mader and Astrid Rupp.\n*/\n\n#include <cmath>\n#include <vector>\n#include \"viennacl/vector.hpp\"\n#include \"viennacl/compressed_matrix.hpp\"\n#include \"viennacl/linalg/prod.hpp\"\n#include \"viennacl/linalg/inner_prod.hpp\"\n#include \"viennacl/linalg/norm_2.hpp\"\n#include \"viennacl/io/matrix_market.hpp\"\n#include \"viennacl/linalg/bisect.hpp\"\n#include <boost/random.hpp>\n#include <boost/random/mersenne_twister.hpp>\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/matrix_proxy.hpp>\n#include <boost/numeric/ublas/matrix_expression.hpp>\n#include <boost/numeric/ublas/matrix_sparse.hpp>\n#include <boost/numeric/ublas/vector.hpp>\n#include <boost/numeric/ublas/operation.hpp>\n#include <boost/numeric/ublas/vector_expression.hpp>\n#include <boost/numeric/ublas/io.hpp>\n\nnamespace viennacl\n{\nnamespace linalg\n{\n\n/** @brief A tag for the lanczos algorithm.\n*/\nclass lanczos_tag\n{\npublic:\n\n  enum\n  {\n    partial_reorthogonalization = 0,\n    full_reorthogonalization,\n    no_reorthogonalization\n  };\n\n  /** @brief The constructor\n  *\n  * @param factor                 Exponent of epsilon - tolerance for batches of Reorthogonalization\n  * @param numeig                 Number of eigenvalues to be returned\n  * @param met                    Method for Lanczos-Algorithm: 0 for partial Reorthogonalization, 1 for full Reorthogonalization and 2 for Lanczos without Reorthogonalization\n  * @param krylov                 Maximum krylov-space size\n  */\n\n  lanczos_tag(double factor = 0.75,\n              vcl_size_t numeig = 10,\n              int met = 0,\n              vcl_size_t krylov = 100) : factor_(factor), num_eigenvalues_(numeig), method_(met), krylov_size_(krylov) {}\n\n  /** @brief Sets the number of eigenvalues */\n  void num_eigenvalues(vcl_size_t numeig){ num_eigenvalues_ = numeig; }\n\n    /** @brief Returns the number of eigenvalues */\n  vcl_size_t num_eigenvalues() const { return num_eigenvalues_; }\n\n    /** @brief Sets the exponent of epsilon */\n  void factor(double fct) { factor_ = fct; }\n\n  /** @brief Returns the exponent */\n  double factor() const { return factor_; }\n\n  /** @brief Sets the size of the kylov space */\n  void krylov_size(vcl_size_t max) { krylov_size_ = max; }\n\n  /** @brief Returns the size of the kylov space */\n  vcl_size_t  krylov_size() const { return krylov_size_; }\n\n  /** @brief Sets the reorthogonalization method */\n  void method(int met){ method_ = met; }\n\n  /** @brief Returns the reorthogonalization method */\n  int method() const { return method_; }\n\n\nprivate:\n  double factor_;\n  vcl_size_t num_eigenvalues_;\n  int method_; // see enum defined above for possible values\n  vcl_size_t krylov_size_;\n};\n\n\nnamespace detail\n{\n  /**\n  *   @brief Implementation of the Lanczos PRO algorithm\n  *\n  *   @param A            The system matrix\n  *   @param r            Random start vector\n  *   @param size         Size of krylov-space\n  *   @param tag          Lanczos_tag with several options for the algorithm\n  *   @return             Returns the eigenvalues (number of eigenvalues equals size of krylov-space)\n  */\n\n  template< typename MatrixT, typename VectorT >\n  std::vector<\n          typename viennacl::result_of::cpu_value_type<typename MatrixT::value_type>::type\n          >\n  lanczosPRO (MatrixT const& A, VectorT & r, vcl_size_t size, lanczos_tag const & tag)\n  {\n    typedef typename viennacl::result_of::value_type<MatrixT>::type        ScalarType;\n    typedef typename viennacl::result_of::cpu_value_type<ScalarType>::type    CPU_ScalarType;\n\n\n    // generation of some random numbers, used for lanczos PRO algorithm\n    boost::mt11213b mt;\n    boost::normal_distribution<CPU_ScalarType> N(0, 1);\n    boost::bernoulli_distribution<CPU_ScalarType> B(0.5);\n    boost::triangle_distribution<CPU_ScalarType> T(-1, 0, 1);\n\n    boost::variate_generator<boost::mt11213b&, boost::normal_distribution<CPU_ScalarType> >     get_N(mt, N);\n    boost::variate_generator<boost::mt11213b&, boost::bernoulli_distribution<CPU_ScalarType> >  get_B(mt, B);\n    boost::variate_generator<boost::mt11213b&, boost::triangle_distribution<CPU_ScalarType> >   get_T(mt, T);\n\n\n    long i, k, retry, reorths;\n    std::vector<long> l_bound(size/2), u_bound(size/2);\n    bool second_step;\n    CPU_ScalarType squ_eps, eta, temp, eps, retry_th;\n    vcl_size_t n = r.size();\n    std::vector< std::vector<CPU_ScalarType> > w(2, std::vector<CPU_ScalarType>(size));\n    CPU_ScalarType cpu_beta;\n\n    boost::numeric::ublas::vector<CPU_ScalarType> s(n);\n\n    VectorT t(n);\n    CPU_ScalarType inner_rt;\n    ScalarType vcl_beta;\n    ScalarType vcl_alpha;\n    std::vector<CPU_ScalarType> alphas, betas;\n    boost::numeric::ublas::matrix<CPU_ScalarType> Q(n, size);\n\n    second_step = false;\n    eps = std::numeric_limits<CPU_ScalarType>::epsilon();\n    squ_eps = std::sqrt(eps);\n    retry_th = 1e-2;\n    eta = std::exp(std::log(eps) * tag.factor());\n    reorths = 0;\n    retry = 0;\n\n    vcl_beta = viennacl::linalg::norm_2(r);\n\n    r /= vcl_beta;\n\n    detail::copy_vec_to_vec(r,s);\n    boost::numeric::ublas::column(Q, 0) = s;\n\n    VectorT u = viennacl::linalg::prod(A, r);\n    vcl_alpha = viennacl::linalg::inner_prod(u, r);\n    alphas.push_back(vcl_alpha);\n    w[0][0] = 1;\n    betas.push_back(vcl_beta);\n\n    long batches = 0;\n    for (i = 1;i < static_cast<long>(size); i++)\n    {\n      r = u - vcl_alpha * r;\n      vcl_beta = viennacl::linalg::norm_2(r);\n\n      betas.push_back(vcl_beta);\n      r = r / vcl_beta;\n\n      vcl_size_t index = vcl_size_t(i % 2);\n      w[index][vcl_size_t(i)] = 1;\n      k = (i + 1) % 2;\n      w[index][0] = (betas[1] * w[vcl_size_t(k)][1] + (alphas[0] - vcl_alpha) * w[vcl_size_t(k)][0] - betas[vcl_size_t(i) - 1] * w[index][0]) / vcl_beta + eps * 0.3 * get_N() * (betas[1] + vcl_beta);\n\n      for (vcl_size_t j = 1; j < vcl_size_t(i - 1); j++)\n      {\n              w[index][j] = (betas[j + 1] * w[vcl_size_t(k)][j + 1] + (alphas[j] - vcl_alpha) * w[vcl_size_t(k)][j] + betas[j] * w[vcl_size_t(k)][j - 1] - betas[vcl_size_t(i) - 1] * w[index][j]) / vcl_beta + eps * 0.3 * get_N() * (betas[j + 1] + vcl_beta);\n      }\n      w[index][vcl_size_t(i) - 1] = 0.6 * eps * CPU_ScalarType(n) * get_N() * betas[1] / vcl_beta;\n\n      if (second_step)\n      {\n        for (vcl_size_t j = 0; j < vcl_size_t(batches); j++)\n        {\n          l_bound[vcl_size_t(j)]++;\n          u_bound[vcl_size_t(j)]--;\n\n          for (k = l_bound[j];k < u_bound[j];k++)\n          {\n            detail::copy_vec_to_vec(boost::numeric::ublas::column(Q, vcl_size_t(k)), t);\n            inner_rt = viennacl::linalg::inner_prod(r,t);\n            r = r - inner_rt * t;\n            w[index][vcl_size_t(k)] = 1.5 * eps * get_N();\n            reorths++;\n          }\n        }\n        temp = viennacl::linalg::norm_2(r);\n        r = r / temp;\n        vcl_beta = vcl_beta * temp;\n        second_step = false;\n      }\n      batches = 0;\n\n      for (vcl_size_t j = 0; j < vcl_size_t(i); j++)\n      {\n        if (std::fabs(w[index][j]) >= squ_eps)\n        {\n          detail::copy_vec_to_vec(boost::numeric::ublas::column(Q, j), t);\n          inner_rt = viennacl::linalg::inner_prod(r,t);\n          r = r - inner_rt * t;\n          w[index][j] = 1.5 * eps * get_N();\n          k = long(j) - 1;\n          reorths++;\n          while (k >= 0 && std::fabs(w[index][vcl_size_t(k)]) > eta)\n          {\n            detail::copy_vec_to_vec(boost::numeric::ublas::column(Q, vcl_size_t(k)), t);\n            inner_rt = viennacl::linalg::inner_prod(r,t);\n            r = r - inner_rt * t;\n            w[index][vcl_size_t(k)] = 1.5 * eps * get_N();\n            k--;\n            reorths++;\n          }\n          l_bound[vcl_size_t(batches)] = k + 1;\n          k = long(j) + 1;\n\n          while (k < i && std::fabs(w[index][vcl_size_t(k)]) > eta)\n          {\n            detail::copy_vec_to_vec(boost::numeric::ublas::column(Q, vcl_size_t(k)), t);\n            inner_rt = viennacl::linalg::inner_prod(r,t);\n            r = r - inner_rt * t;\n            w[index][vcl_size_t(k)] = 1.5 * eps * get_N();\n            k++;\n            reorths++;\n          }\n          u_bound[vcl_size_t(batches)] = k - 1;\n          batches++;\n          j = vcl_size_t(k);\n        }\n      }\n\n      if (batches > 0)\n      {\n        temp = viennacl::linalg::norm_2(r);\n        r = r / temp;\n        vcl_beta = vcl_beta * temp;\n        second_step = true;\n\n        while (temp < retry_th)\n        {\n          for (vcl_size_t j = 0; j < vcl_size_t(i); j++)\n          {\n            detail::copy_vec_to_vec(boost::numeric::ublas::column(Q, vcl_size_t(k)), t);\n            inner_rt = viennacl::linalg::inner_prod(r,t);\n            r = r - inner_rt * t;\n            reorths++;\n          }\n          retry++;\n          temp = viennacl::linalg::norm_2(r);\n          r = r / temp;\n          vcl_beta = vcl_beta * temp;\n        }\n      }\n\n      detail::copy_vec_to_vec(r,s);\n      boost::numeric::ublas::column(Q, vcl_size_t(i)) = s;\n\n      cpu_beta = vcl_beta;\n      s = - cpu_beta * boost::numeric::ublas::column(Q, vcl_size_t(i - 1));\n      detail::copy_vec_to_vec(s, u);\n      u += viennacl::linalg::prod(A, r);\n      vcl_alpha = viennacl::linalg::inner_prod(u, r);\n      alphas.push_back(vcl_alpha);\n    }\n\n    return bisect(alphas, betas);\n  }\n\n\n  /**\n  *   @brief Implementation of the lanczos algorithm without reorthogonalization\n  *\n  *   @param A            The system matrix\n  *   @param r            Random start vector\n  *   @param size         Size of krylov-space\n  *   @return             Returns the eigenvalues (number of eigenvalues equals size of krylov-space)\n  */\n  template<typename MatrixT, typename VectorT>\n  std::vector<\n          typename viennacl::result_of::cpu_value_type<typename MatrixT::value_type>::type\n          >\n  lanczos (MatrixT const& A, VectorT & r, vcl_size_t size, lanczos_tag)\n  {\n    typedef typename viennacl::result_of::value_type<MatrixT>::type        ScalarType;\n    typedef typename viennacl::result_of::cpu_value_type<ScalarType>::type    CPU_ScalarType;\n\n    ScalarType vcl_beta;\n    ScalarType vcl_alpha;\n    std::vector<CPU_ScalarType> alphas, betas;\n    CPU_ScalarType norm;\n    vcl_size_t n = r.size();\n    VectorT u(n), t(n);\n    boost::numeric::ublas::vector<CPU_ScalarType> s(r.size()), u_zero(n), q(n);\n    boost::numeric::ublas::matrix<CPU_ScalarType> Q(n, size);\n\n    u_zero = boost::numeric::ublas::zero_vector<CPU_ScalarType>(n);\n    detail::copy_vec_to_vec(u_zero, u);\n    norm = norm_2(r);\n\n    for (vcl_size_t i = 0;i < size; i++)\n    {\n      r /= norm;\n      vcl_beta = norm;\n\n      detail::copy_vec_to_vec(r,s);\n      boost::numeric::ublas::column(Q, i) = s;\n\n      u += prod(A, r);\n      vcl_alpha = inner_prod(u, r);\n      r = u - vcl_alpha * r;\n      norm = norm_2(r);\n\n      q = boost::numeric::ublas::column(Q, i);\n      detail::copy_vec_to_vec(q, t);\n\n      u = - norm * t;\n      alphas.push_back(vcl_alpha);\n      betas.push_back(vcl_beta);\n      s.clear();\n    }\n\n    return bisect(alphas, betas);\n  }\n\n  /**\n  *   @brief Implementation of the Lanczos FRO algorithm\n  *\n  *   @param A            The system matrix\n  *   @param r            Random start vector\n  *   @param size         Size of krylov-space\n  *   @return             Returns the eigenvalues (number of eigenvalues equals size of krylov-space)\n  */\n  template< typename MatrixT, typename VectorT >\n  std::vector<\n          typename viennacl::result_of::cpu_value_type<typename MatrixT::value_type>::type\n          >\n  lanczosFRO (MatrixT const& A, VectorT & r, vcl_size_t size, lanczos_tag)\n  {\n    typedef typename viennacl::result_of::value_type<MatrixT>::type            NumericType;\n    typedef typename viennacl::result_of::cpu_value_type<NumericType>::type    CPU_NumericType;\n\n    CPU_NumericType temp;\n    CPU_NumericType norm;\n    NumericType vcl_beta;\n    NumericType vcl_alpha;\n    std::vector<CPU_NumericType> alphas, betas;\n    vcl_size_t n = r.size();\n    VectorT u(n), t(n);\n    NumericType inner_rt;\n    boost::numeric::ublas::vector<CPU_NumericType> u_zero(n), s(r.size()), q(n);\n    boost::numeric::ublas::matrix<CPU_NumericType> Q(n, size);\n\n    long reorths = 0;\n    norm = norm_2(r);\n\n\n    for (vcl_size_t i = 0; i < size; i++)\n    {\n      r /= norm;\n\n      for (vcl_size_t j = 0; j < i; j++)\n      {\n        q = boost::numeric::ublas::column(Q, j);\n        detail::copy_vec_to_vec(q, t);\n        inner_rt = viennacl::linalg::inner_prod(r,t);\n        r = r - inner_rt * t;\n        reorths++;\n      }\n      temp = viennacl::linalg::norm_2(r);\n      r = r / temp;\n      vcl_beta = temp * norm;\n      detail::copy_vec_to_vec(r,s);\n      boost::numeric::ublas::column(Q, i) = s;\n\n      u += viennacl::linalg::prod(A, r);\n      vcl_alpha = viennacl::linalg::inner_prod(u, r);\n      r = u - vcl_alpha * r;\n      norm = viennacl::linalg::norm_2(r);\n      q = boost::numeric::ublas::column(Q, i);\n      detail::copy_vec_to_vec(q, t);\n      u = - norm * t;\n      alphas.push_back(vcl_alpha);\n      betas.push_back(vcl_beta);\n    }\n\n    return bisect(alphas, betas);\n  }\n\n} // end namespace detail\n\n/**\n*   @brief Implementation of the calculation of eigenvalues using lanczos\n*\n*   @param matrix        The system matrix\n*   @param tag           Tag with several options for the lanczos algorithm\n*   @return              Returns the n largest eigenvalues (n defined in the lanczos_tag)\n*/\ntemplate<typename MatrixT>\nstd::vector< typename viennacl::result_of::cpu_value_type<typename MatrixT::value_type>::type >\neig(MatrixT const & matrix, lanczos_tag const & tag)\n{\n  typedef typename viennacl::result_of::value_type<MatrixT>::type           NumericType;\n  typedef typename viennacl::result_of::cpu_value_type<NumericType>::type   CPU_NumericType;\n  typedef typename viennacl::result_of::vector_for_matrix<MatrixT>::type    VectorT;\n\n  boost::mt11213b mt;\n  boost::normal_distribution<CPU_NumericType>    N(0, 1);\n  boost::bernoulli_distribution<CPU_NumericType> B(0.5);\n  boost::triangle_distribution<CPU_NumericType>  T(-1, 0, 1);\n\n  boost::variate_generator<boost::mt11213b&, boost::normal_distribution<CPU_NumericType> >     get_N(mt, N);\n  boost::variate_generator<boost::mt11213b&, boost::bernoulli_distribution<CPU_NumericType> >  get_B(mt, B);\n  boost::variate_generator<boost::mt11213b&, boost::triangle_distribution<CPU_NumericType> >   get_T(mt, T);\n\n  std::vector<CPU_NumericType> eigenvalues;\n  vcl_size_t matrix_size = matrix.size1();\n  VectorT r(matrix_size);\n  std::vector<CPU_NumericType> s(matrix_size);\n\n  for (vcl_size_t i=0; i<s.size(); ++i)\n    s[i] = 3.0 * get_B() + get_T() - 1.5;\n\n  detail::copy_vec_to_vec(s,r);\n\n  vcl_size_t size_krylov = (matrix_size < tag.krylov_size()) ? matrix_size\n                                                              : tag.krylov_size();\n\n  switch (tag.method())\n  {\n    case lanczos_tag::partial_reorthogonalization:\n      eigenvalues = detail::lanczosPRO(matrix, r, size_krylov, tag);\n      break;\n    case lanczos_tag::full_reorthogonalization:\n      eigenvalues = detail::lanczosFRO(matrix, r, size_krylov, tag);\n      break;\n    case lanczos_tag::no_reorthogonalization:\n      eigenvalues = detail::lanczos(matrix, r, size_krylov, tag);\n      break;\n  }\n\n  std::vector<CPU_NumericType> largest_eigenvalues;\n\n  for (vcl_size_t i = 1; i<=tag.num_eigenvalues(); i++)\n    largest_eigenvalues.push_back(eigenvalues[size_krylov-i]);\n\n\n  return largest_eigenvalues;\n}\n\n\n\n\n} // end namespace linalg\n} // end namespace viennacl\n#endif\n", "meta": {"hexsha": "d44b679edb5dcabb8a1dcce30e4e9a0f568303ec", "size": 16371, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "viennacl/linalg/lanczos.hpp", "max_stars_repo_name": "ddemidov/viennacl-dev", "max_stars_repo_head_hexsha": "0f7de9cd28e54a5ca8f7c2ab03263bc56bf004ef", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2016-08-23T17:05:21.000Z", "max_stars_repo_stars_event_max_datetime": "2016-08-23T17:06:24.000Z", "max_issues_repo_path": "viennacl/linalg/lanczos.hpp", "max_issues_repo_name": "ddemidov/viennacl-dev", "max_issues_repo_head_hexsha": "0f7de9cd28e54a5ca8f7c2ab03263bc56bf004ef", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "viennacl/linalg/lanczos.hpp", "max_forks_repo_name": "ddemidov/viennacl-dev", "max_forks_repo_head_hexsha": "0f7de9cd28e54a5ca8f7c2ab03263bc56bf004ef", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.6851851852, "max_line_length": 256, "alphanum_fraction": 0.6123633254, "num_tokens": 4722, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6893056295505784, "lm_q2_score": 0.46490157137338844, "lm_q1q2_score": 0.32045927033458665}}
{"text": "/* Siconos is a program dedicated to modeling, simulation and control\n * of non smooth dynamical systems.\n *\n * Copyright 2016 INRIA.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n*/\n\n#include \"SiconosConfig.h\"\n\n#pragma GCC diagnostic ignored \"-Wunused-local-typedefs\"\n\n#include <boost/numeric/ublas/lu.hpp>\n#include <boost/numeric/ublas/operation.hpp>\n#include <boost/numeric/ublas/operation_sparse.hpp>\n\n//#define BIND_FORTRAN_LOWERCASE_UNDERSCORE\n#include <boost/numeric/bindings/ublas/vector_proxy.hpp>\n#include <boost/numeric/bindings/ublas/matrix_proxy.hpp>\n#include <boost/numeric/bindings/trans.hpp>\n#include <boost/numeric/bindings/blas.hpp>\n#include <boost/numeric/bindings/lapack.hpp>\n#include <boost/numeric/bindings/ublas/vector.hpp>\n#include <boost/numeric/bindings/ublas/matrix.hpp>\n#include <boost/numeric/bindings/std/vector.hpp>\n\nnamespace lapack = boost::numeric::bindings::lapack;\n\n\n#include \"SiconosVector.hpp\"\n#include \"cholesky.hpp\"\n#include \"SimpleMatrix.hpp\"\n#include \"BlockMatrixIterators.hpp\"\n#include \"BlockMatrix.hpp\"\n\n#include \"SiconosAlgebra.hpp\"\n\nusing namespace Siconos;\n\nvoid SimpleMatrix::PLUFactorizationInPlace()\n{\n  if (_isPLUFactorized)\n  {\n    std::cout << \"SimpleMatrix::PLUFactorizationInPlace warning: this matrix is already PLUFactorized. \" << std::endl;\n    return;\n  }\n  if (_num == 1)\n  {\n    if (!_ipiv)\n      _ipiv.reset(new VInt(size(0)));\n    else\n      _ipiv->resize(size(0));\n    int info = lapack::getrf(*mat.Dense, *_ipiv);\n    if (info != 0)\n    {\n      _isPLUFactorized = false;\n      SiconosMatrixException::selfThrow(\"SimpleMatrix::PLUFactorizationInPlace failed: the matrix is singular.\");\n    }\n    else _isPLUFactorized = true;\n  }\n  else\n  {\n    int info = cholesky_decompose(*sparse());\n    // \\warning: VA 24/11/2010: work only for symmetric matrices. Should be replaced by efficient implementatation (e.g. mumps )\n    if (info != 0)\n    {\n      display();\n      _isPLUFactorized = false;\n      std::cout << \"Problem in Cholesky Decomposition for the row number\" << info   << std::endl;\n      SiconosMatrixException::selfThrow(\"SimpleMatrix::PLUFactorizationInPlace failed. \");\n    }\n    else _isPLUFactorized = true;\n  }\n\n}\n\nvoid SimpleMatrix::PLUInverseInPlace()\n{\n  if (!_isPLUFactorized)\n    PLUFactorizationInPlace();\n  if (_num != 1)\n    SiconosMatrixException::selfThrow(\" SimpleMatrix::PLUInverseInPlace: only implemented for dense matrices.\");\n\n#if defined(HAVE_ATLAS) && defined(OUTSIDE_FRAMEWORK_BLAS)\n  int info = lapack::getri(*mat.Dense, *_ipiv);   // solve from factorization\n\n  if (info != 0)\n    SiconosMatrixException::selfThrow(\"SimpleMatrix::PLUInverseInPlace failed, the matrix is singular.\");\n\n  _isPLUInversed = true;\n#else\n  SiconosMatrixException::selfThrow(\"SimpleMatrix::PLUInverseInPlace not implemented with lapack.\");\n#endif\n}\n\nvoid SimpleMatrix::PLUForwardBackwardInPlace(SiconosMatrix &B)\n{\n  if (B.isBlock())\n    SiconosMatrixException::selfThrow(\"SimpleMatrix PLUForwardBackwardInPlace(B) failed at solving Ax = B. Not yet implemented for a BlockMatrix B.\");\n  int info = 0;\n\n  if (_num == 1)\n  {\n    if (!_isPLUFactorized) // call gesv => LU-factorize+solve\n    {\n      // solve system:\n      if (!_ipiv)\n        _ipiv.reset(new VInt(size(0)));\n      else\n        _ipiv->resize(size(0));\n      info = lapack::gesv(*mat.Dense, *_ipiv, *(B.dense()));\n      _isPLUFactorized = true;\n\n      /*\n        ublas::vector<double> S(std::max(size(0),size(1)));\n        ublas::matrix<double, ublas::column_major> U(size(0),size(1));\n        ublas::matrix<double, ublas::column_major> VT(size(0),size(1));\n\n        int ierr = lapack::gesdd(*mat.Dense, S, U, VT);\n        printf(\"info = %d, ierr = %d, emax = %f, emin = %f , cond = %f\\n\",info,ierr,S(0),S(2),S(0)/S(2));\n      */\n      // B now contains solution:\n    }\n    else // call getrs: only solve using previous lu-factorization\n      if (B.num() == 1)\n        info = lapack::getrs(*mat.Dense, *_ipiv, *(B.dense()));\n      else\n        SiconosMatrixException::selfThrow(\" SimpleMatrix::PLUInverseInPlace: only implemented for dense matrices in RHS.\");\n  }\n  else\n  {\n    if (!_isPLUFactorized) // call first PLUFactorizationInPlace\n    {\n      PLUFactorizationInPlace();\n    }\n    // and then solve\n    if (B.num() == 1)\n    {\n      inplace_solve(*sparse(), *(B.dense()), ublas::lower_tag());\n      inplace_solve(ublas::trans(*sparse()), *(B.dense()), ublas::upper_tag());\n    }\n    else if (B.num() == 4)\n    {\n      inplace_solve(*sparse(), *(B.sparse()), ublas::lower_tag());\n      inplace_solve(ublas::trans(*sparse()), *(B.sparse()), ublas::upper_tag());\n    }\n    else\n      SiconosMatrixException::selfThrow(\" SimpleMatrix::PLUInverseInPlace: only implemented for dense ans sparse matrices in RHS.\");\n    info = 0 ;\n  }\n  //  SiconosMatrixException::selfThrow(\" SimpleMatrix::PLUInverseInPlace: only implemented for dense matrices.\");\n\n\n\n  if (info != 0)\n    SiconosMatrixException::selfThrow(\"SimpleMatrix::PLUForwardBackwardInPlace failed.\");\n}\n\nvoid SimpleMatrix::PLUForwardBackwardInPlace(SiconosVector &B)\n{\n  if (B.isBlock())\n    SiconosMatrixException::selfThrow(\"SimpleMatrix PLUForwardBackwardInPlace(V) failed. Not yet implemented for V being a BlockVector.\");\n\n\n  DenseMat tmpB(B.size(), 1);\n  ublas::column(tmpB, 0) = *(B.dense()); // Conversion of vector to matrix. Temporary solution.\n  int info;\n\n  if (_num == 1)\n  {\n    if (!_isPLUFactorized) // call gesv => LU-factorize+solve\n    {\n      // solve system:\n      if (!_ipiv)\n        _ipiv.reset(new VInt(size(0)));\n      else\n        _ipiv->resize(size(0));\n\n      info = lapack::gesv(*mat.Dense, *_ipiv, tmpB);\n      _isPLUFactorized = true;\n\n      /*\n        ublas::matrix<double> COPY(*mat.Dense);\n        ublas::vector<double> S(std::max(size(0),size(1)));\n        ublas::matrix<double, ublas::column_major> U(size(0),size(1));\n        ublas::matrix<double, ublas::column_major> VT(size(0),size(1));\n\n        int ierr = lapack::gesdd(COPY, S, U, VT);\n        printf(\"info = %d, ierr = %d, emax = %f, emin = %f , cond = %f\\n\",info,ierr,S(0),S(2),S(0)/S(2));\n      */\n      // B now contains solution:\n    }\n    else // call getrs: only solve using previous lu-factorization\n      info = lapack::getrs(*mat.Dense, *_ipiv, tmpB);\n  }\n  else\n  {\n    if (!_isPLUFactorized) // call first PLUFactorizationInPlace\n    {\n      PLUFactorizationInPlace();\n    }\n    // and then solve\n    inplace_solve(*sparse(), tmpB, ublas::lower_tag());\n    inplace_solve(ublas::trans(*sparse()), tmpB, ublas::upper_tag());\n    info = 0;\n  }\n  if (info != 0)\n    SiconosMatrixException::selfThrow(\"SimpleMatrix::PLUForwardBackwardInPlace failed.\");\n  else\n  {\n    noalias(*(B.dense())) = ublas::column(tmpB, 0);\n  }\n}\n\nvoid SimpleMatrix::resetLU()\n{\n  if (_ipiv) _ipiv->clear();\n  _isPLUFactorized = false;\n  _isPLUInversed = false;\n}\n\nvoid SimpleMatrix::resetQR()\n{\n  _isQRFactorized = false;\n\n}\n// const SimpleMatrix operator * (const SimpleMatrix & A, const SimpleMatrix& B )\n// {\n//   return (DenseMat)prod(*A.dense() , *B.dense());\n//   //  return A;\n// }\n\nvoid SimpleMatrix::SolveByLeastSquares(SiconosMatrix &B)\n{\n  if (B.isBlock())\n    SiconosMatrixException::selfThrow(\"SimpleMatrix::SolveByLeastSquares(Siconos Matrix &B) failed. Not yet implemented for M being a BlockMatrix.\");\n  int info = 0;\n#ifdef USE_OPTIMAL_WORKSPACE\n  info += lapack::gels(*mat.Dense, *(B.dense()), lapack::optimal_workspace());\n#endif\n#ifdef USE_MINIMAL_WORKSPACE\n  info += lapack::gels(*mat.Dense, *(B.dense()), lapack::minimal_workspace());\n#endif\n  if (info != 0)\n    SiconosMatrixException::selfThrow(\"SimpleMatrix::SolveByLeastSquares failed.\");\n}\n\n\n\n\nvoid SimpleMatrix::SolveByLeastSquares(SiconosVector &B)\n{\n  if (B.isBlock())\n    SiconosMatrixException::selfThrow(\"SimpleMatrix::SolveByLeastSquares(SiconosVector &B) failed. Not yet implemented for V being a BlockVector.\");\n\n  DenseMat tmpB(B.size(), 1);\n  ublas::column(tmpB, 0) = *(B.dense()); // Conversion of vector to matrix. Temporary solution.\n  int info = 0;\n\n#ifdef USE_OPTIMAL_WORKSPACE\n  info += lapack::gels(*mat.Dense, tmpB, lapack::optimal_workspace());\n#endif\n#ifdef USE_MINIMAL_WORKSPACE\n  info += lapack::gels(*mat.Dense, tmpB, lapack::minimal_workspace());\n#endif\n  if (info != 0)\n  {\n    std::cout << \"info = \" << info << std::endl;\n    SiconosMatrixException::selfThrow(\"SimpleMatrix::SolveByLeastSquares failed.\");\n  }\n  else\n  {\n    noalias(*(B.dense())) = ublas::column(tmpB, 0);\n  }\n\n}\n\n/*\nvoid polePlacement(const SiconosMatrix& A, const SiconosVector& B, SiconosVector& P, bool transpose)\n{\n  unsigned int n = A.size(0);\n  DenseMat AA(n, n);\n  DenseMat Q(n, n);\n  DenseVect tau(n);\n  DenseVect BB(n);\n  noalias(AA) = (*A.dense());\n  lapack::gehrd(1, n, AA, tau);\n  lapack::orghr(n, 1, n, Q, tau);\n  noalias(BB) = prod(Q, *B.dense());\n}\n*/\n", "meta": {"hexsha": "84d4ca9da60117090d9f47fa484b8baa88ffb754", "size": 9316, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "kernel/src/utils/SiconosAlgebra/SimpleMatrixSolvers.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/SimpleMatrixSolvers.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/SimpleMatrixSolvers.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": 30.8476821192, "max_line_length": 150, "alphanum_fraction": 0.6706741091, "num_tokens": 2683, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6893056167854461, "lm_q2_score": 0.4649015713733885, "lm_q1q2_score": 0.3204592644000567}}
{"text": "/*-------------------------------------------------------------\nCopyright 2019 Wenxin Liu, Kartik Mohta, Giuseppe Loianno\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n--------------------------------------------------------------*/\n\n#include \"sdd_vio/vo_stereo.h\"\n\n#include <iostream>\n#include \"sdd_vio/utils/math_utils.h\"\n#include <algorithm>\n#include <math.h>\n#include <ros/ros.h>\n#include <cmath>\n#include <assert.h>\n#include <boost/thread.hpp>\n#include \"sdd_vio/utils/ros_params_helper.h\"\n#include \"sdd_vio/utils/timer.hpp\"\n#include <ctime>\n#include <opencv2/core/eigen.hpp>\n\n\n\n\nnamespace sdd_vio {\n\n/*\n * Optimization using Forward Compositional Approach\n *\n * Input:\n *      img_curr: current frame image\n *      ilay: the index of tracking layer in the image pyramid. 0 is the largest layer for tracking.\n * Return:\n *      T_curr: current transformation matrix from keyframe to current frame\n *      T_wb: transformation between current robot frame to world frame\n *      T_: transformation between current camera frame to initial camera frame\n *      v_: velocity of current body frame\n * Use of private class variables:\n *      feat_3D_[ilay]: the vector of 3D points in keyframe\n *      intensities_[ilay]: the vector of pixel intensities in keyframe\n *      mask_[ilay]: indicator of whether points are in view\n * LMA params as private variables:\n *      lambda_\n *      up_factor_\n *      down_factor_\n *\n */\n    void VoStereo::optimize_fca(const cv::Mat& img_curr, Eigen::Isometry3f& T_curr, Eigen::Isometry3f& T_wb, Eigen::Isometry3f& T, Eigen::Vector3f& v, int ilay) {\n\n\n        /* obtain gradient image of the current frame */\n        cv::Mat Gx_mat, Gy_mat;\n        cv::Sobel(img_curr, Gx_mat, CV_32F, 1, 0, 3);\n        cv::Sobel(img_curr, Gy_mat, CV_32F, 0, 1, 3);\n\n\n        /* masked Jacobian matrix and error vector - remove points outside projection */\n        Eigen::MatrixXf J_masked;  // every time J_masked is re-calculated for every pixel inside the view\n        Eigen::VectorXf error_masked;\n        Eigen::VectorXf W;  // diagonal weight matrix for Huber estimation\n\n\n        /* Jacobian and error vector of IMU */\n        Eigen::MatrixXf J_imu;\n        Eigen::VectorXf r_imu;\n        Eigen::MatrixXf Z_imu;  // inverse covariance of imu errors\n        J_imu.resize(9,9);\n        initJacobian_imu_fca(J_imu);\n        r_imu.resize(9);\n//        Eigen::VectorXf inv_cov_imu(9);\n//        inv_cov_imu << weight_R_,weight_R_,weight_R_, weight_v_,weight_v_,weight_v_,weight_p_,weight_p_,weight_p_;\n//        Z_imu = inv_cov_imu.asDiagonal();\n        Z_imu = Cov_meas_.inverse();\n//        std::cout<<\"Z_imu:\\n\"<<Z_imu<<\"\\n\";\n\n\n        /* Levenberg Marquardt */\n        float lambda = lambda_;  // initial lambda is equal to the initial one set\n        float up = up_factor_;\n        float down = down_factor_;\n        bool if_break = false;\n\n\n        int npts_in;  // number of points remained in view\n        perc_ = 1.;  // percentage of points remained in view\n        float err_init, err_last = 0;\n\n\n        /* begins optimization iteration */\n        for (int iter=0; iter<max_num_iter_; ++iter)\n        {\n            /* first iteration */\n            if (iter == 0) {\n\n                /* calculate error and Jacobian given initial transformation */\n                getError_fca(img_curr, Gx_mat, Gy_mat, T_curr, T_wb, J_masked, error_masked, W, npts_in, ilay);\n                getError_imu_fca(T_wb, v, r_imu, J_imu);\n\n\n                perc_ = 100*npts_in/num_feat_pts_[ilay];\n                float err_mean = get_error_mean(error_masked, r_imu);\n                err_init = err_mean;\n                err_last = err_mean;\n\n            }\n\n            using Mat9 = Eigen::Matrix<float, 9, 9>;\n            using Vec9 = Eigen::Matrix<float, 9, 1>;\n\n            if (use_lma_ == false)\n            {\n                /* obtain H and b */\n                const Mat9 H = beta_*J_masked.transpose() * W.asDiagonal() * J_masked + alpha_ * (J_imu.transpose() * Z_imu * J_imu);  // H = J^t * W * J\n                const Vec9 b = beta_*J_masked.transpose() * (W.asDiagonal() * error_masked) + alpha_ * (J_imu.transpose() * (Z_imu * r_imu));  // b = J^t * w * e\n\n                /* get delta increment */\n                const Vec9 delta = -H.ldlt().solve(b);\n//                std::cout<<\"delta: \\n\"<<delta<<\"\\n\";\n\n                update_optimization_step(delta, T_wb, v, T, T_curr);\n\n\n                /* calculate error vector and Jacobian given transformation */\n                getError_fca(img_curr, Gx_mat, Gy_mat, T_curr, T_wb, J_masked, error_masked, W, npts_in, ilay);\n                getError_imu_fca(T_wb, v, r_imu, J_imu);\n//                std::cout << \"r_imu: \\n\"<<r_imu<<\"\\n\";\n\n\n                perc_ = 100*npts_in/num_feat_pts_[ilay];\n                float err_mean = get_error_mean(error_masked, r_imu);\n                float err_diff = (err_mean - err_last)/err_last;\n                err_last = err_mean;\n\n\n                /* terminal output */\n                if (verbose_) {\n                    std::cout << \"iteration = \"<<iter<<\", err = \"<< err_mean<<\", derr = \"<<err_diff<<std::endl;\n                }\n\n                /* Stop condition - if error is going up or decreased below target or reach max iterations */\n                if (err_diff>0 || -err_diff < target_derr_ || iter == max_num_iter_-1)\n                    if_break = true;\n\n                /* end of optimization */\n                if (if_break) {\n                    ROS_INFO_STREAM(\"iteration \"<<iter<<\"--------\");\n                    ROS_INFO(\"err/initial err: %g/%g\", err_mean, err_init);\n                    if (err_mean > err_init)\n                      ROS_WARN_STREAM(\"bad convergence - err/initial err: \"<<err_mean<<\"/\"<<err_init<<\", iteration\"<<iter);\n                    break;\n                }\n\n            }\n            else  // use lma\n            {\n\n                /* temporary T_curr, is error goes up in subloop can switch back */\n                Eigen::Isometry3f T_curr_temp;\n                Eigen::Isometry3f T_wb_temp;\n                Eigen::Isometry3f T_temp;\n                Eigen::Vector3f v_temp;\n\n\n                /* LMA */\n                float mult = lambda;\n                bool ill = true;  // if ill conditioned (error increase)\n                int lmit = 0;  // number of iterations while ill=true\n\n                /* obtain H and b */\n                const Mat9 H = beta_* J_masked.transpose() * W.asDiagonal() * J_masked + alpha_ * (J_imu.transpose() * Z_imu * J_imu);  // H = J^t * W * J\n                const Vec9 b = beta_* J_masked.transpose() * (W.asDiagonal() * error_masked) + alpha_ * (J_imu.transpose() * (Z_imu * r_imu));  // b = J^t * w * e\n\n                float err_mean = 0, err_diff = 0;\n                /* LMA wrapper of subloop */\n                while ((ill==true) && (iter<max_num_iter_) && (lmit<5))\n                {\n\n                    /* lma update on H */\n                    const Mat9 H_curr = H + Mat9(mult * H.diagonal().asDiagonal());\n\n\n                    /* get delta increment */\n                    const Vec9 delta = -H_curr.ldlt().solve(b);\n//                    std::cout<<\"delta: \\n\"<<delta<<\"\\n\";\n\n\n                    T_curr_temp = T_curr;\n                    T_wb_temp = T_wb;\n                    T_temp = T;\n                    v_temp = v;\n                    update_optimization_step(delta, T_wb_temp, v_temp, T_temp, T_curr_temp);\n\n\n                    /* calculate error vector and Jacobian given transformation */\n                    getError_fca(img_curr, Gx_mat, Gy_mat, T_curr_temp, T_wb_temp, J_masked, error_masked, W, npts_in, ilay);\n                    getError_imu_fca(T_wb, v_temp, r_imu, J_imu);\n//                    std::cout<<\"J_imu: \\n\"<<J_imu<<\"\\n\";\n//                    std::cout << \"r_imu: \\n\"<<r_imu<<\"\\n\";\n\n\n                    perc_ = 100*npts_in/num_feat_pts_[ilay];\n                    err_mean = get_error_mean(error_masked, r_imu);\n                    err_diff = (err_mean - err_last)/err_last;\n\n                    ill = (err_diff > 0);  // if error larger than before, set ill = true, try increase lambda.\n\n                    /* terminal output */\n                    if (verbose_) {\n                        std::cout << \"iteration = \"<<iter<<\", lambda = \"<<lambda<<\", err = \"<<\n                            err_mean<<\", derr = \"<<err_diff<<std::endl;\n                    }\n\n                    /* if ill=true, higher lambda by up factor, count as one iteration */\n                    if (ill) {\n                          lambda *= up;\n                        mult = lambda;\n                        iter++;\n                    }\n                    lmit++;\n                }\n\n                err_last  = err_mean;\n\n                /* update T with the one that makes error smaller or the last try */\n                T_curr = T_curr_temp;\n                T = T_temp;\n                T_wb = T_wb_temp;\n                v = v_temp;\n\n                /* if error doesn't get higher for quite some time, this term will bring lambda down eventually */\n                if (lambda > 1e-8)  // make sure doesn't overflow\n                    lambda *= (1/down);\n\n                /* if LM iterations didn't decrease the error, stop */\n                if (ill) {\n                    //ROS_WARN_STREAM(\"bad convergence!\");\n                    if_break = true;\n                }\n\n                /* if error is decreased below target or reach max iterations */\n                if (-err_diff < target_derr_ || iter == max_num_iter_-1)\n                    if_break = true;\n\n                /* end of optimization */\n                if (if_break) {\n                    ROS_INFO_STREAM(\"iteration \"<<iter<<\"--------\");\n                    ROS_INFO(\"err/initial err: %g/%g\", err_mean, err_init);\n                    if (err_mean > err_init)\n                      ROS_WARN_STREAM(\"bad convergence - err/initial err: \"<<err_mean<<\"/\"<<err_init<<\", iteration\"<<iter);\n                    break;\n                }\n\n            }\n\n        } // for (int iter=0;\n\n    }\n\n\n/*\n * Update optimization targets given delta\n *\n */\n    void VoStereo::update_optimization_step(const Eigen::Matrix<float, 9, 1>& delta, Eigen::Isometry3f &T_wb, Eigen::Vector3f &v, Eigen::Isometry3f &T, Eigen::Isometry3f &T_curr)\n    {\n        /* update current transformation */\n        const Eigen::Vector3f delta_phi = delta.segment<3>(0);\n        const Eigen::Matrix3f R_delta = exp_SO3(delta_phi);\n        const Eigen::Vector3f t_delta = delta.segment<3>(3);\n        const Eigen::Vector3f v_delta = delta.segment<3>(6);\n\n        // update T_wb and v\n        T_wb.linear() = T_wb.rotation() * R_delta;\n        T_wb.translation() += t_delta;\n        v += v_delta;\n\n        // update T and T_curr\n        T = T_bc_inv_ * T_wb * T_bc_;\n        T_curr = T.inverse() * T_kf_;\n    }\n\n\n/*\n * Obtain err_mean for convergence evaluation\n *\n */\n    float VoStereo::get_error_mean(const Eigen::VectorXf& error_masked, const Eigen::VectorXf& r_imu)\n    {\n        int npts_in = error_masked.size();\n        float err_photo = error_masked.transpose()*error_masked; // sum of square errors\n        // these are raw square errors - not weighed by huber weights\n        // photometric part is the mean pixel intensity error, plus the IMU observation square error weighted by optimization weight alpha_\n        float err_mean = beta_ * sqrt(err_photo/npts_in) / error_scale_factor_ + alpha_*(r_imu.transpose()*r_imu).value();\n        return err_mean;\n    }\n\n\n\n /*\n  * initialize imu jacobian with the parts that do not change in iterations\n  *\n  */\n    void VoStereo::initJacobian_imu_fca(Eigen::MatrixXf &J_imu)\n    {\n        /* these are the parts that do not change through iterations */\n        J_imu.setZero();\n        Eigen::Matrix3f R_i = T_wb_last_.rotation();\n        J_imu.block<3,3>(6,3) = R_i.transpose();\n        J_imu.block<3,3>(3,6) = R_i.transpose();\n    }\n\n/*\n * obtain imu error vector and update imu jacobian\n * Input:\n *      T_wb: current robot pose in world frame\n *      v: current robot velocity in world frame\n * Output:\n *      r_imu: 9x1 vector of imu errors\n *      J_imu: 9x9 jacobian of state (phi,p,v of current robot frame in world) with respect to imu errors\n *\n */\n    void VoStereo::getError_imu_fca(const Eigen::Isometry3f &T_wb, const Eigen::Vector3f &v, Eigen::VectorXf &r_imu, Eigen::MatrixXf &J_imu)\n    {\n\n        Eigen::Matrix3f R_i = T_wb_last_.rotation();  // rotation w.r.t. world frame of last body frame\n        Eigen::Matrix3f R_j = T_wb.rotation();  // rotation w.r.t. world frame of current body frame\n        Eigen::Vector3f p_i = T_wb_last_.translation();  // position of last robot frame in world\n        Eigen::Vector3f p_j = T_wb.translation();  // position of current robot frame in world\n\n        Eigen::Matrix3f R_err = R_meas_.transpose() * R_i.transpose() * R_j;\n        Eigen::Vector3f r_R_imu = log_SO3(R_err);\n        Eigen::Vector3f r_v_imu = R_i.transpose() * (v - v_last_ - g_*t_meas_) - v_meas_;\n        Eigen::Vector3f r_p_imu = R_i.transpose() * (p_j - p_i - v_last_*t_meas_ - 0.5*g_*t_meas_*t_meas_) - p_meas_;\n\n        r_imu.block<3,1>(0,0) = r_R_imu;\n        r_imu.block<3,1>(3,0) = r_v_imu;\n        r_imu.block<3,1>(6,0) = r_p_imu;\n\n        J_imu.block<3,3>(0,0) = log_Jacobian(r_R_imu);\n\n    }\n\n\n\n/*\n * Get error, Jacobian, and huber weights for Forward Compositional Apporach.\n *\n * Input:\n *      img_curr: current frame image, for getting pixel intensities\n *      Gx: current image gradient image on x direction\n *      Gy: current image gradient image on y direction\n *      ilay: the pyramid layer of current image\n *      T_curr: currently optimized transformation\n * Output:\n *      npts_in: the number of points falling in current camera view\n *      J_masked: Jacobian of the points in-view\n *      error_masked: error of the points in-view\n *      r_imu: 9x1 vector of IMU integrated observation error\n *      W: Huber weight for the points in-view\n * Use of class member:\n * Updates:\n *      mask_[ilay]: indicator of points in-view\n * Data-in:\n *      num_feat_pts_[ilay]\n *      feat_3D_[ilay]\n *      intensities_[ilay]\n *\n */\n    void VoStereo::getError_fca(const cv::Mat& img_curr,\n                                const cv::Mat& Gx_mat,\n                                const cv::Mat& Gy_mat,\n                                const Eigen::Isometry3f& T_curr,\n                                const Eigen::Isometry3f& T_wb,\n                                Eigen::MatrixXf& J_masked,\n                                Eigen::VectorXf& error_masked,\n                                Eigen::VectorXf& W,\n                                int& npts_in,\n                                const int ilay)\n    {\n\n        /* transformation of 3D point in keyframe to current frame and reproject */\n        vector_aligned<Eigen::Vector3f> feat_3D_curr;  // 3D points in current camera's frame\n        vector_aligned<Eigen::Vector2f> feat_pixels_curr;  // 2D pixel coordinates in current image\n        transform3D(feat_3D_[ilay], feat_3D_curr, T_curr, num_feat_pts_[ilay]);\n        cam_->get2DPixels(feat_3D_curr, feat_pixels_curr, num_feat_pts_[ilay], ilay);\n\n\n        /* update mask and obtain gradients of reprojected points in current frame */\n        npts_in = 0;\n        std::vector<float> Gx, Gy;  // gradients of points in view\n        std::vector<int> index;  // vector of size npts_in storing the corresponding index value\n        std::vector<float> error_vec;  // error vector\n\n        const float scale = error_scale_factor_; // Arbitrary scaling for better numerical conditioning\n        for (int i=0; i<num_feat_pts_[ilay]; ++i) {\n            if (inBound(feat_pixels_curr[i](0), feat_pixels_curr[i](1), 0, ilay)) {\n                Gx.push_back(scale * interpolate_gradient(feat_pixels_curr[i](0), feat_pixels_curr[i](1), Gx_mat));\n                Gy.push_back(scale * interpolate_gradient(feat_pixels_curr[i](0), feat_pixels_curr[i](1), Gy_mat));\n                error_vec.push_back(scale * (intensities_[ilay][i]-interpolate(feat_pixels_curr[i](0),feat_pixels_curr[i](1),img_curr)));\n                index.push_back(i);\n\n//                mask_[ilay][i] = 1;\n                npts_in += 1;\n            }\n//            else\n//                mask_[ilay][i] = 0;\n        }\n\n\n        /* obtain photometric error for points in-view */\n        error_masked = Eigen::Map<Eigen::VectorXf, Eigen::Unaligned>(error_vec.data(), error_vec.size());\n\n\n\n        /* obtain jacobian matrix for photometric error with respect to state */\n        getJacobian_fca(Gx, Gy, feat_3D_curr, index, T_curr, T_wb, J_masked, ilay, npts_in);\n\n\n        if (use_huber_)\n        {\n            /* find standard deviation of the error vector and compute W */\n            float r_mean = error_masked.mean();\n            Eigen::VectorXf r_hat = error_masked.array() - r_mean;  // normalize by removing the mean (original order)\n            float sigma = sqrt(((r_hat.array()).square()).sum()/npts_in);  // standard deviation\n            // std::cout << \"sigma: \" << sigma << std::endl;\n\n            W.resize(npts_in);\n            for (int i=0; i<npts_in; ++i) {\n                if (fabs(r_hat[i]) < 1.345*sigma)\n                    W[i] = 1;\n                else\n                    W[i] = (1.345*sigma)/fabs(r_hat[i]);\n                if(use_weights_)\n                    W[i] = W[i] * c_/(c_+error_masked[i]*error_masked[i]);\n\n            }\n        }\n        else {\n\n            W.resize(npts_in);\n            W = Eigen::VectorXf::Constant(npts_in,1);\n\n            if(use_weights_)\n                for (int i=0; i<npts_in; ++i) {\n                    W[i]=c_/(c_+error_masked[i]*error_masked[i]);\n                    //std::cout<<\"W\" << W[i];\n                }\n            //std::cout<<\"W =\"<<W;\n        }\n\n\n\n    }\n\n\n\n\n/*\n * Compute the Jacobian matrix for Forward Compositional Approach (FCA)\n * Called every iteration\n *\n * Input:\n *      Gx: gradient vector in x direction of current image\n *      Gy: gradient vector in y direction of current image\n *      feat_3D_curr: 3D feature points represented in current frame, of size num_feat_pts[ilay]\n *      index: vector of index for each point in-view, of size npts_in, ranges within num_feat_pts[ilay]\n *      T_curr: current transformation from keyframe to current frame. p_curr = T_curr * p_kf\n *      T_wb: transformation from current body frame to world frame. p_w = T_wb * p_b\n *      ilay: number of layer we're optimizing on\n *      npts_in: number of points in-view\n * Output:\n *      J: jacobian of size npts_in x 6, photometric error with respect to delta rotation phi in so(3) and delta translation p.\n *\n *\n */\n    void VoStereo::getJacobian_fca(const std::vector<float>& Gx, const std::vector<float>& Gy,\n                                   const vector_aligned<Eigen::Vector3f>& feat_3D_curr, const std::vector<int> &index,\n                                   const Eigen::Isometry3f& T_curr, const Eigen::Isometry3f& T_wb, Eigen::MatrixXf& J, const int ilay, const int npts_in)\n    {\n//        std::cout<<\"+++++calculating jacobian \\n\";\n//        int id_ind = 475;\n\n        Eigen::Matrix<float,3,3> R_cb = T_bc_inv_.rotation();\n        Eigen::Matrix<float,3,3> R_wb = T_wb.rotation();\n\n        J.resize(npts_in,9);\n        J.setZero();\n        Eigen::Matrix<float,1,3> J_i_phi; // Jacobian of one point on rotation\n        Eigen::Matrix<float,1,3> J_i_p;  // Jacobian of one point on position\n        Eigen::Matrix<float,1,2> J_grad; // gradient jacobian\n        Eigen::Matrix<float,2,3> J_proj; // projection jacobian\n        Eigen::Matrix<float,3,3> J_SO3;  // exponential jacobian\n\n        float fx = focal_pyr_[ilay];\n        float fy = focal_pyr_[ilay];\n\n//        std::cout<<\"fx: \"<<fx<<\"\\n\";\n//        bool jacobianhasnan = false;\n//        bool jacobianhasinf = false;\n//        bool jacobian_too_large = false;\n\n        for (int i=0; i < npts_in; ++i)\n        {\n            /* calculate for each point the 1x6 Jacobian */\n            Eigen::Vector3f p_curr;  // point in current frame\n            p_curr(0) = feat_3D_curr[index[i]](0);\n            p_curr(1) = feat_3D_curr[index[i]](1);\n            p_curr(2) = feat_3D_curr[index[i]](2);\n\n            Eigen::Vector3f p_kf;  // point in keyframe\n            p_kf(0) = feat_3D_[ilay][index[i]](0);\n            p_kf(1) = feat_3D_[ilay][index[i]](1);\n            p_kf(2) = feat_3D_[ilay][index[i]](2);\n\n\n            Eigen::Vector4f p_kf_homo = unproject3d(p_kf); // homogeneous coordinate in keyframe\n            Eigen::Vector4f p_hat_homo = T_bc_ * T_curr * p_kf_homo;\n            Eigen::Vector3f p_hat = project3d(p_hat_homo);  // point p_i prime in jacobian formulation\n\n            J_grad(0,0) = Gx[i];\n            J_grad(0,1) = Gy[i];\n\n            J_proj(0,0) = fx/p_curr(2);\n            J_proj(1,0) = 0;\n            J_proj(0,1) = 0;\n            J_proj(1,1) = fy/p_curr(2);\n            J_proj(0,2) = -fx*p_curr(0)/(p_curr(2)*p_curr(2));\n            J_proj(1,2) = -fy*p_curr(1)/(p_curr(2)*p_curr(2));\n\n            J_SO3 << 0,-p_hat(2),p_hat(1),\n                    p_hat(2),0,-p_hat(0),\n                    -p_hat(1),p_hat(0),0;  // [p_hat]x\n\n            J_i_phi = - J_grad * J_proj * R_cb * J_SO3;\n            J_i_p = J_grad * J_proj * R_cb * R_wb.transpose();\n\n//            if (i==id_ind)\n//            {\n//                std::cout<<\"J_grad: \\n\"<<J_grad<<\"\\n\";\n//                std::cout<<\"J_proj: \\n\"<<J_proj<<\"\\n\";\n//                std::cout<<\"J_SO3: \\n\"<<J_SO3<<\"\\n\";\n//                std::cout<<\"J_i_p: \\n\"<<J_i_p<<\"\\n\";\n//                std::cout<<\"J_i_phi: \\n\"<<J_i_phi<<\"\\n\";\n//            }\n\n            /* assign J_i to J */\n            J.block<1,3>(i,0) = J_i_phi;\n            J.block<1,3>(i,3) = J_i_p;\n\n            /* for debug - will print out info if nan values found */\n\n//            for (int k=0; k<6; ++k){\n//                if (std::isnan(J(i,k)))\n//                    jacobianhasnan = true;\n//                if (std::isinf(J(i,k)))\n//                    jacobianhasinf = true;\n//                if(J(i,k) > error_scale_factor_ * 1e8)\n//                {\n//                    jacobian_too_large = true;\n//                    ROS_WARN_STREAM(\"jacobian too large! i: \" << i << \", Index[i]: \" << index[i] << \" / \" << num_feat_pts_[ilay] << \"\\nJ.row: \"<< J.row(i));\n//                    std::cout<<\"J_grad: \\n\"<<J_grad<<\"\\n\";\n//                    std::cout<<\"J_proj: \\n\"<<J_proj<<\"\\n\";\n//                    std::cout<<\"J_SO3: \\n\"<<J_SO3<<\"\\n\";\n//                    std::cout<<\"J_i_p: \\n\"<<J_i_p<<\"\\n\";\n//                    std::cout<<\"J_i_phi: \\n\"<<J_i_phi<<\"\\n\";\n//                }\n//            }\n\n            /* for debug */\n        }\n//        if (jacobianhasnan)\n//            std::cout << \"Jacobian has nan\"<< std::endl;\n//        if (jacobianhasinf)\n//            std::cout <<\"Jacobian has inf\"<<std::endl;\n    }\n\n\n}\n", "meta": {"hexsha": "0ccea0d19e40d03135d8ee8cda3a2b47602d0862", "size": 23353, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/vo_stereo_3.cpp", "max_stars_repo_name": "mfkiwl/sdd_vio", "max_stars_repo_head_hexsha": "dcd8cbb3f140d4eb9569ede4e94c36cc818aa557", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 67.0, "max_stars_repo_stars_event_min_datetime": "2020-08-20T01:24:02.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-26T11:43:45.000Z", "max_issues_repo_path": "src/vo_stereo_3.cpp", "max_issues_repo_name": "mfkiwl/sdd_vio", "max_issues_repo_head_hexsha": "dcd8cbb3f140d4eb9569ede4e94c36cc818aa557", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/vo_stereo_3.cpp", "max_forks_repo_name": "mfkiwl/sdd_vio", "max_forks_repo_head_hexsha": "dcd8cbb3f140d4eb9569ede4e94c36cc818aa557", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 17.0, "max_forks_repo_forks_event_min_datetime": "2020-09-15T18:16:36.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-22T09:04:35.000Z", "avg_line_length": 39.6485568761, "max_line_length": 178, "alphanum_fraction": 0.5503361452, "num_tokens": 6128, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6893056040203135, "lm_q2_score": 0.46490157137338844, "lm_q1q2_score": 0.3204592584655264}}
{"text": "/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */\n\n/*\n Copyright (C) 2000, 2001, 2002, 2003 RiskMap srl\n Copyright (C) 2003, 2004, 2005, 2006, 2007 StatPro Italia srl\n Copyright (C) 2006, 2008 Ferdinando Ametrano\n\n This file is part of QuantLib, a free-software/open-source library\n for financial quantitative analysts and developers - http://quantlib.org/\n\n QuantLib is free software: you can redistribute it and/or modify it\n under the terms of the QuantLib license.  You should have received a\n copy of the license along with this program; if not, please email\n <quantlib-dev@lists.sf.net>. The license is also available online at\n <http://quantlib.org/license.shtml>.\n\n This program is distributed in the hope that it will be useful, but WITHOUT\n ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n FOR A PARTICULAR PURPOSE.  See the license for more details.\n*/\n\n/*! \\file vanillaswap.hpp\n    \\brief Simple fixed-rate vs Libor swap\n*/\n\n#ifndef quantlib_vanilla_swap_hpp\n#define quantlib_vanilla_swap_hpp\n\n#include <ql/instruments/swap.hpp>\n#include <ql/time/daycounter.hpp>\n#include <ql/time/schedule.hpp>\n#include <boost/optional.hpp>\n\nnamespace QuantLib {\n\n    class IborIndex;\n\n    //! Plain-vanilla swap: fix vs floating leg\n    /*! \\ingroup instruments\n\n        If no payment convention is passed, the convention of the\n        floating-rate schedule is used.\n\n        \\warning if <tt>Settings::includeReferenceDateCashFlows()</tt>\n                 is set to <tt>true</tt>, payments occurring at the\n                 settlement date of the swap might be included in the\n                 NPV and therefore affect the fair-rate and\n                 fair-spread calculation. This might not be what you\n                 want.\n\n        \\test\n        - the correctness of the returned value is tested by checking\n          that the price of a swap paying the fair fixed rate is null.\n        - the correctness of the returned value is tested by checking\n          that the price of a swap receiving the fair floating-rate\n          spread is null.\n        - the correctness of the returned value is tested by checking\n          that the price of a swap decreases with the paid fixed rate.\n        - the correctness of the returned value is tested by checking\n          that the price of a swap increases with the received\n          floating-rate spread.\n        - the correctness of the returned value is tested by checking\n          it against a known good value.\n    */\n    class VanillaSwap : public Swap {\n      public:\n        enum Type { Receiver = -1, Payer = 1 };\n        class arguments;\n        class results;\n        class engine;\n        VanillaSwap(\n            Type type,\n            Real nominal,\n            const Schedule& fixedSchedule,\n            Rate fixedRate,\n            const DayCounter& fixedDayCount,\n            const Schedule& floatSchedule,\n            const boost::shared_ptr<IborIndex>& iborIndex,\n            Spread spread,\n            const DayCounter& floatingDayCount,\n            boost::optional<BusinessDayConvention> paymentConvention =\n                                                                 boost::none);\n        //! \\name Inspectors\n        //@{\n        Type type() const;\n        Real nominal() const;\n\n        const Schedule& fixedSchedule() const;\n        Rate fixedRate() const;\n        const DayCounter& fixedDayCount() const;\n\n        const Schedule& floatingSchedule() const;\n        const boost::shared_ptr<IborIndex>& iborIndex() const;\n        Spread spread() const;\n        const DayCounter& floatingDayCount() const;\n\n        BusinessDayConvention paymentConvention() const;\n\n        const Leg& fixedLeg() const;\n        const Leg& floatingLeg() const;\n        //@}\n\n        //! \\name Results\n        //@{\n        Real fixedLegBPS() const;\n        Real fixedLegNPV() const;\n        Rate fairRate() const;\n\n        Real floatingLegBPS() const;\n        Real floatingLegNPV() const;\n        Spread fairSpread() const;\n        //@}\n        // other\n        void setupArguments(PricingEngine::arguments* args) const;\n        void fetchResults(const PricingEngine::results*) const;\n      private:\n        void setupExpired() const;\n        Type type_;\n        Real nominal_;\n        Schedule fixedSchedule_;\n        Rate fixedRate_;\n        DayCounter fixedDayCount_;\n        Schedule floatingSchedule_;\n        boost::shared_ptr<IborIndex> iborIndex_;\n        Spread spread_;\n        DayCounter floatingDayCount_;\n        BusinessDayConvention paymentConvention_;\n        // results\n        mutable Rate fairRate_;\n        mutable Spread fairSpread_;\n    };\n\n\n    //! %Arguments for simple swap calculation\n    class VanillaSwap::arguments : public Swap::arguments {\n      public:\n        arguments() : type(Receiver),\n                      nominal(Null<Real>()) {}\n        Type type;\n        Real nominal;\n\n        std::vector<Date> fixedResetDates;\n        std::vector<Date> fixedPayDates;\n        std::vector<Time> floatingAccrualTimes;\n        std::vector<Date> floatingResetDates;\n        std::vector<Date> floatingFixingDates;\n        std::vector<Date> floatingPayDates;\n\n        std::vector<Real> fixedCoupons;\n        std::vector<Spread> floatingSpreads;\n        std::vector<Real> floatingCoupons;\n        void validate() const;\n    };\n\n    //! %Results from simple swap calculation\n    class VanillaSwap::results : public Swap::results {\n      public:\n        Rate fairRate;\n        Spread fairSpread;\n        void reset();\n    };\n\n    class VanillaSwap::engine : public GenericEngine<VanillaSwap::arguments,\n                                                     VanillaSwap::results> {};\n\n\n    // inline definitions\n\n    inline VanillaSwap::Type VanillaSwap::type() const {\n        return type_;\n    }\n\n    inline Real VanillaSwap::nominal() const {\n        return nominal_;\n    }\n\n    inline const Schedule& VanillaSwap::fixedSchedule() const {\n        return fixedSchedule_;\n    }\n\n    inline Rate VanillaSwap::fixedRate() const {\n        return fixedRate_;\n    }\n\n    inline const DayCounter& VanillaSwap::fixedDayCount() const {\n        return fixedDayCount_;\n    }\n\n    inline const Schedule& VanillaSwap::floatingSchedule() const {\n        return floatingSchedule_;\n    }\n\n    inline const boost::shared_ptr<IborIndex>& VanillaSwap::iborIndex() const {\n        return iborIndex_;\n    }\n\n    inline Spread VanillaSwap::spread() const {\n        return spread_;\n    }\n\n    inline const DayCounter& VanillaSwap::floatingDayCount() const {\n        return floatingDayCount_;\n    }\n\n    inline BusinessDayConvention VanillaSwap::paymentConvention() const {\n        return paymentConvention_;\n    }\n\n    inline const Leg& VanillaSwap::fixedLeg() const {\n        return legs_[0];\n    }\n\n    inline const Leg& VanillaSwap::floatingLeg() const {\n        return legs_[1];\n    }\n\n    std::ostream& operator<<(std::ostream& out,\n                             VanillaSwap::Type t);\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 Copyright (C) 2003, 2004, 2005, 2006, 2007 StatPro Italia srl\n Copyright (C) 2007 Ferdinando Ametrano\n\n This file is part of QuantLib, a free-software/open-source library\n for financial quantitative analysts and developers - http://quantlib.org/\n\n QuantLib is free software: you can redistribute it and/or modify it\n under the terms of the QuantLib license.  You should have received a\n copy of the license along with this program; if not, please email\n <quantlib-dev@lists.sf.net>. The license is also available online at\n <http://quantlib.org/license.shtml>.\n\n This program is distributed in the hope that it will be useful, but WITHOUT\n ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n FOR A PARTICULAR PURPOSE.  See the license for more details.\n*/\n\n#include <ql/cashflows/fixedratecoupon.hpp>\n#include <ql/cashflows/iborcoupon.hpp>\n#include <ql/cashflows/cashflowvectors.hpp>\n#include <ql/cashflows/cashflows.hpp>\n#include <ql/cashflows/couponpricer.hpp>\n#include <ql/indexes/iborindex.hpp>\n#include <ql/termstructures/yieldtermstructure.hpp>\n\nnamespace QuantLib {\n\n    inline VanillaSwap::VanillaSwap(\n                     Type type,\n                     Real nominal,\n                     const Schedule& fixedSchedule,\n                     Rate fixedRate,\n                     const DayCounter& fixedDayCount,\n                     const Schedule& floatSchedule,\n                     const boost::shared_ptr<IborIndex>& iborIndex,\n                     Spread spread,\n                     const DayCounter& floatingDayCount,\n                     boost::optional<BusinessDayConvention> paymentConvention)\n    : Swap(2), type_(type), nominal_(nominal),\n      fixedSchedule_(fixedSchedule), fixedRate_(fixedRate),\n      fixedDayCount_(fixedDayCount),\n      floatingSchedule_(floatSchedule), iborIndex_(iborIndex), spread_(spread),\n      floatingDayCount_(floatingDayCount) {\n\n        if (paymentConvention)\n            paymentConvention_ = *paymentConvention;\n        else\n            paymentConvention_ = floatingSchedule_.businessDayConvention();\n\n        legs_[0] = FixedRateLeg(fixedSchedule_)\n            .withNotionals(nominal_)\n            .withCouponRates(fixedRate_, fixedDayCount_)\n            .withPaymentAdjustment(paymentConvention_);\n\n        legs_[1] = IborLeg(floatingSchedule_, iborIndex_)\n            .withNotionals(nominal_)\n            .withPaymentDayCounter(floatingDayCount_)\n            .withPaymentAdjustment(paymentConvention_)\n            .withSpreads(spread_);\n        for (Leg::const_iterator i = legs_[1].begin(); i < legs_[1].end(); ++i)\n            registerWith(*i);\n\n        switch (type_) {\n          case Payer:\n            payer_[0] = -1.0;\n            payer_[1] = +1.0;\n            break;\n          case Receiver:\n            payer_[0] = +1.0;\n            payer_[1] = -1.0;\n            break;\n          default:\n            QL_FAIL(\"Unknown vanilla-swap type\");\n        }\n    }\n\n    inline void VanillaSwap::setupArguments(PricingEngine::arguments* args) const {\n\n        Swap::setupArguments(args);\n\n        VanillaSwap::arguments* arguments =\n            dynamic_cast<VanillaSwap::arguments*>(args);\n\n        if (!arguments)  // it's a swap engine...\n            return;\n\n        arguments->type = type_;\n        arguments->nominal = nominal_;\n\n        const Leg& fixedCoupons = fixedLeg();\n\n        arguments->fixedResetDates = arguments->fixedPayDates =\n            std::vector<Date>(fixedCoupons.size());\n        arguments->fixedCoupons = std::vector<Real>(fixedCoupons.size());\n\n        for (Size i=0; i<fixedCoupons.size(); ++i) {\n            boost::shared_ptr<FixedRateCoupon> coupon =\n                boost::dynamic_pointer_cast<FixedRateCoupon>(fixedCoupons[i]);\n\n            arguments->fixedPayDates[i] = coupon->date();\n            arguments->fixedResetDates[i] = coupon->accrualStartDate();\n            arguments->fixedCoupons[i] = coupon->amount();\n        }\n\n        const Leg& floatingCoupons = floatingLeg();\n\n        arguments->floatingResetDates = arguments->floatingPayDates =\n            arguments->floatingFixingDates =\n            std::vector<Date>(floatingCoupons.size());\n        arguments->floatingAccrualTimes =\n            std::vector<Time>(floatingCoupons.size());\n        arguments->floatingSpreads =\n            std::vector<Spread>(floatingCoupons.size());\n        arguments->floatingCoupons = std::vector<Real>(floatingCoupons.size());\n        for (Size i=0; i<floatingCoupons.size(); ++i) {\n            boost::shared_ptr<IborCoupon> coupon =\n                boost::dynamic_pointer_cast<IborCoupon>(floatingCoupons[i]);\n\n            arguments->floatingResetDates[i] = coupon->accrualStartDate();\n            arguments->floatingPayDates[i] = coupon->date();\n\n            arguments->floatingFixingDates[i] = coupon->fixingDate();\n            arguments->floatingAccrualTimes[i] = coupon->accrualPeriod();\n            arguments->floatingSpreads[i] = coupon->spread();\n            try {\n                arguments->floatingCoupons[i] = coupon->amount();\n            } catch (Error&) {\n                arguments->floatingCoupons[i] = Null<Real>();\n            }\n        }\n    }\n\n    inline Rate VanillaSwap::fairRate() const {\n        calculate();\n        QL_REQUIRE(fairRate_ != Null<Rate>(), \"result not available\");\n        return fairRate_;\n    }\n\n    inline Spread VanillaSwap::fairSpread() const {\n        calculate();\n        QL_REQUIRE(fairSpread_ != Null<Spread>(), \"result not available\");\n        return fairSpread_;\n    }\n\n    inline Real VanillaSwap::fixedLegBPS() const {\n        calculate();\n        QL_REQUIRE(legBPS_[0] != Null<Real>(), \"result not available\");\n        return legBPS_[0];\n    }\n\n    inline Real VanillaSwap::floatingLegBPS() const {\n        calculate();\n        QL_REQUIRE(legBPS_[1] != Null<Real>(), \"result not available\");\n        return legBPS_[1];\n    }\n\n    inline Real VanillaSwap::fixedLegNPV() const {\n        calculate();\n        QL_REQUIRE(legNPV_[0] != Null<Real>(), \"result not available\");\n        return legNPV_[0];\n    }\n\n    inline Real VanillaSwap::floatingLegNPV() const {\n        calculate();\n        QL_REQUIRE(legNPV_[1] != Null<Real>(), \"result not available\");\n        return legNPV_[1];\n    }\n\n    inline void VanillaSwap::setupExpired() const {\n        Swap::setupExpired();\n        legBPS_[0] = legBPS_[1] = 0.0;\n        fairRate_ = Null<Rate>();\n        fairSpread_ = Null<Spread>();\n    }\n\n    inline void VanillaSwap::fetchResults(const PricingEngine::results* r) const {\n        static const Spread basisPoint = 1.0e-4;\n\n        Swap::fetchResults(r);\n\n        const VanillaSwap::results* results =\n            dynamic_cast<const VanillaSwap::results*>(r);\n        if (results) { // might be a swap engine, so no error is thrown\n            fairRate_ = results->fairRate;\n            fairSpread_ = results->fairSpread;\n        } else {\n            fairRate_ = Null<Rate>();\n            fairSpread_ = Null<Spread>();\n        }\n\n        if (fairRate_ == Null<Rate>()) {\n            // calculate it from other results\n            if (legBPS_[0] != Null<Real>())\n                fairRate_ = fixedRate_ - NPV_/(legBPS_[0]/basisPoint);\n        }\n        if (fairSpread_ == Null<Spread>()) {\n            // ditto\n            if (legBPS_[1] != Null<Real>())\n                fairSpread_ = spread_ - NPV_/(legBPS_[1]/basisPoint);\n        }\n    }\n\n    inline void VanillaSwap::arguments::validate() const {\n        Swap::arguments::validate();\n        QL_REQUIRE(nominal != Null<Real>(), \"nominal null or not set\");\n        QL_REQUIRE(fixedResetDates.size() == fixedPayDates.size(),\n                   \"number of fixed start dates different from \"\n                   \"number of fixed payment dates\");\n        QL_REQUIRE(fixedPayDates.size() == fixedCoupons.size(),\n                   \"number of fixed payment dates different from \"\n                   \"number of fixed coupon amounts\");\n        QL_REQUIRE(floatingResetDates.size() == floatingPayDates.size(),\n                   \"number of floating start dates different from \"\n                   \"number of floating payment dates\");\n        QL_REQUIRE(floatingFixingDates.size() == floatingPayDates.size(),\n                   \"number of floating fixing dates different from \"\n                   \"number of floating payment dates\");\n        QL_REQUIRE(floatingAccrualTimes.size() == floatingPayDates.size(),\n                   \"number of floating accrual Times different from \"\n                   \"number of floating payment dates\");\n        QL_REQUIRE(floatingSpreads.size() == floatingPayDates.size(),\n                   \"number of floating spreads different from \"\n                   \"number of floating payment dates\");\n        QL_REQUIRE(floatingPayDates.size() == floatingCoupons.size(),\n                   \"number of floating payment dates different from \"\n                   \"number of floating coupon amounts\");\n    }\n\n    inline void VanillaSwap::results::reset() {\n        Swap::results::reset();\n        fairRate = Null<Rate>();\n        fairSpread = Null<Spread>();\n    }\n\n    inline std::ostream& operator<<(std::ostream& out,\n                             VanillaSwap::Type t) {\n        switch (t) {\n          case VanillaSwap::Payer:\n            return out << \"Payer\";\n          case VanillaSwap::Receiver:\n            return out << \"Receiver\";\n          default:\n            QL_FAIL(\"unknown VanillaSwap::Type(\" << Integer(t) << \")\");\n        }\n    }\n\n}\n\n\n#endif\n", "meta": {"hexsha": "e1c3666718da4cfc9348c0fa21e6b7856d499a91", "size": 16615, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ql/instruments/vanillaswap.hpp", "max_stars_repo_name": "markxio/Quantuccia", "max_stars_repo_head_hexsha": "ebe71a1b9c2a9ee7fc4ea918a9602f100316869d", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 29.0, "max_stars_repo_stars_event_min_datetime": "2017-03-20T14:17:39.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-22T08:00:52.000Z", "max_issues_repo_path": "ql/instruments/vanillaswap.hpp", "max_issues_repo_name": "markxio/Quantuccia", "max_issues_repo_head_hexsha": "ebe71a1b9c2a9ee7fc4ea918a9602f100316869d", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 10.0, "max_issues_repo_issues_event_min_datetime": "2017-04-02T14:34:07.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-13T05:31:12.000Z", "max_forks_repo_path": "ql/instruments/vanillaswap.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": 34.8322851153, "max_line_length": 83, "alphanum_fraction": 0.6130003009, "num_tokens": 3645, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.607663184043154, "lm_q2_score": 0.5273165233795671, "lm_q1q2_score": 0.32043083759539404}}
{"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\nboost::mt19937 r;\n\nconst double sigma2_y0 = 10000;\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 Ey_fn(const int p, const int j, const vector<double>& y0i,const vector<double>& Ri, vector<double>& Ey_ij,const Mcmc& mc)\n{\n    Ey_ij.at(0) = y0i.at(j);\n    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))*(exp(mc.xx().at(p).at(j*mc.op().nt()+t-1))*Ri.at(t-1)-Ey_ij.at(t-1)*(1-Ri.at(t-1)));\n        if (Ey_ij.at(t)<=0) return true;\n    }\n    return false;\n}\n\n\ndouble sum_sq(const int p, const int j, const vector<double>& y0i, const vector<double>& Ri,const Mcmc& mc)\n{\n    double sum2=0;\n    vector<double> Ey_ij(mc.op().nt());\n    if (Ey_fn(p,j,y0i,Ri,Ey_ij,mc)) return NAN;\n    for (int t=0; t<mc.op().nt(); t++) for (unsigned q=0;q<mc.yy().at(p).size();q++) {\n        sum2 += pow(mc.yy().at(p).at(q).at(j*mc.op().nt()+t)-log(Ey_ij.at(t)),2);\n    }\n    return sum2;\n}\n\n\ndouble sum_sq(const int p, const vector<double>& y0i, const vector<double>& Ri,const Mcmc& mc,const int s=0)\n{\n    double sum2=0;\n    for (int j=0; j<mc.op().nrep(); j++) {\n        bool flag=false;\n        for (unsigned q=0;q<mc.yy().at(p).size();q++) if (obs(mc.yy().at(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());\n            if (Ey_fn(p,j,y0i,Ri,Ey_ij,mc)) return NAN;\n            for (int t=s; t<mc.op().nt(); t++) for (unsigned q=0;q<mc.yy().at(p).size();q++) {\n                sum2 += pow(mc.yy().at(p).at(q).at(j*mc.op().nt()+t)-log(Ey_ij.at(t)),2);\n            }\n        }\n    }\n    return sum2;\n}\n\n\nboost::random::normal_distribution<> ugaussian(0,1);\nboost::uniform_real<> uniform(0,1);\nvoid Mcmc::update_y0(const int p)\n{\n    for (int j=0;j<op().nrep();j++) {\n        bool flag=false;\n        for (unsigned q=0;q<yy().at(p).size();q++) if (obs(yy().at(p).at(q).at(j*op().nt()))) {\n            flag=true;\n            break;\n        }\n        if (flag) {\n            vector<double> newy0p(y0().at(p));\n            newy0p.at(j) *= exp(ugaussian(r));\n            double logr = -sum_sq(p,j,newy0p,RR().at(p),*this)/tau2().at(p)/2;\n            logr -= -sum_sq(p,j,y0().at(p),RR().at(p),*this)/tau2().at(p)/2;\n            logr += -pow(log(newy0p.at(j)),2)/2/sigma2_y0;\n            logr -= -pow(log(y0().at(p).at(j)),2)/2/sigma2_y0;\n            if (logr>0 or uniform(r)<exp(logr)) {\n                d_y0.at(p).at(j) = newy0p.at(j);\n            }\n        }\n    }\n}\n\n\nvoid Mcmc::update_R(const int p)\n{\n    vector<double> newRp;\n    int s=-1;\n    for (int t=0;t<op().nt()-1;t++) {\n        if (CPS().at(p).at(t)==1) {\n            s = t+1;\n            newRp = RR().at(p);\n            newRp.at(t) = inv_logit(logit(RR().at(p).at(t))+ugaussian(r));\n        } else {\n            newRp.at(t) = newRp.at(t-1);\n        }\n        if (CPS().at(p).at(t+1)==0) continue;\n        double logr = -sum_sq(p,y0().at(p),newRp,*this,s)/tau2().at(p)/2;\n        logr -= -sum_sq(p,y0().at(p),RR().at(p),*this,s)/tau2().at(p)/2;\n        logr += log(pq(newRp.at(t)))-log(pq(RR().at(p).at(t)));\n        if (logr>0 or uniform(r)<exp(logr)) {\n            d_RR.at(p) = newRp;\n        }\n    }\n}\n\n\n\n\nvoid Mcmc::update_CPS(const int p)\n{\n    const vector<double>& Rp=RR().at(p);\n    for (int cp=1;cp<op().nt()-1;cp++) {\n        vector<double> newRp(Rp);\n        int l_time_index=-1, r_time_index=-1;\n        for (int t=cp-1;l_time_index<0;t--) if (CPS().at(p).at(t)==1) l_time_index=t;\n        for (int t=cp+1;r_time_index<0;t++) if (CPS().at(p).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 (CPS().at(p).at(cp)==0) {\n            const double u = uniform(r);\n            const double newRleft = inv_logit(logit(Rp.at(cp))+r_time/t_time*logit(u));\n            const double newRright = inv_logit(logit(Rp.at(cp))-l_time/t_time*logit(u));\n            for (int t=l_time_index;t<cp;t++) newRp.at(t) = newRleft;\n            for (int t=cp;t<r_time_index;t++) newRp.at(t) = newRright;\n            if (d_prior) logr += d_varphi.at(p).at(cp);\n            //if (d_prior) logr += varphi_fn(p,cp,*this,d_mo);\n            logr += 2*log(newRleft*(1-newRright)+newRright*(1-newRleft))-log(pq(Rp.at(cp)));\n        } else {\n            const double mergedR = inv_logit((l_time*logit(Rp.at(cp-1))+r_time*logit(Rp.at(cp)))/t_time);\n            for (int t=l_time_index;t<r_time_index;t++) newRp.at(t)=mergedR;\n            if (d_prior) logr -= d_varphi.at(p).at(cp);\n            //if (d_prior) logr -= varphi_fn(p,cp,*this,d_mo);\n            logr -= 2*log(Rp.at(cp-1)*(1-Rp.at(cp))+Rp.at(cp)*(1-Rp.at(cp-1)))-log(pq(mergedR));\n        }\n        logr += -sum_sq(p,y0().at(p),newRp,*this,l_time_index+1)/tau2().at(p)/2;\n        logr -= -sum_sq(p,y0().at(p),Rp,*this,l_time_index+1)/tau2().at(p)/2;\n        if (logr>0 or uniform(r)<exp(logr)) {\n            d_RR.at(p) = newRp;\n            d_CPS.at(p).at(cp)=1-CPS().at(p).at(cp);\n        }\n    }\n}\n\n\n\n\nvoid Mcmc::tau_hyperparams()\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.txt\");\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_varphi(vector<vector<double> >()),d_xx(pr.xx()),d_yy(pr.yy())//,d_nobs(pr.nobs())\n{\n    Construct();\n}\n\n\nMcmc::Mcmc(const Pre& pr,const vector<vector<double> >& varphi) : d_op(pr.op()),d_prior(true),d_varphi(varphi),d_xx(pr.xx()),d_yy(pr.yy())//,d_nobs(pr.nobs())\n{\n    Construct();\n}\n\n\n\n\nvoid Mcmc::Construct()\n{\n    d_y0.assign(yy().size(),vector<double>(op().nrep()));\n    for (unsigned p=0;p<yy().size();p++) for (int j=0;j<op().nrep();j++) {\n        double sum=0;\n        for (unsigned q=0;q<yy().at(p).size();q++) sum+=yy().at(p).at(q).at(j*op().nt());\n        d_y0.at(p).at(j)=exp(sum/yy().at(p).size());\n    }\n    d_RR.assign(yy().size(),vector<double> (op().nt(),.9));\n    d_CPS.assign(yy().size(),vector<int> (op().nt(),1));\n    d_CPSum.assign(yy().size(),vector<int> (op().nt()));\n\n    tau_hyperparams();\n    ofstream y0_ofs(\"s_y0\");\n    ofstream RR_ofs(\"s_RR\");\n    ofstream tau2_ofs(\"s_tau2\");\n    if (not tau2_ofs) throw runtime_error(\"can't open s_tau2\");\n    ofstream CPS_ofs(\"s_CPS\");\n    ofstream xRyD_ofs(\"s_xRyD\");\n    ofstream loglike_ofs(\"s_loglike\");\n\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<yy().size(); p++) {\n            update_y0(p);\n            update_R(p);\n            update_CPS(p);\n        }\n\n        if (iter>op().nburn() and iter%op().nthin()==0) {\n            ns++;\n\n            for (unsigned p=0;p<yy().size();p++) {\n                tau2_ofs<<d_tau2.at(p)<<'\\t';\n                for (int j=0;j<op().nrep();j++) y0_ofs<<d_y0.at(p).at(j)<<'\\t';\n                for (int t=0;t<op().nt()-1;t++) {\n                    RR_ofs<<d_RR.at(p).at(t)<<'\\t';\n                }\n                for (int t=1;t<op().nt()-1;t++) {\n                    CPS_ofs<<d_CPS.at(p).at(t)<<'\\t';\n                    d_CPSum.at(p).at(t)+=d_CPS.at(p).at(t);\n                }\n\n            }\n\n            y0_ofs<<'\\n';\n            tau2_ofs<<'\\n';\n            RR_ofs<<'\\n';\n            CPS_ofs<<'\\n';\n\n            double loglike = 0;\n            for (unsigned p=0;p<yy().size();p++) for (unsigned q=0;q<yy().at(p).size();q++) for (int j=0;j<op().nrep();j++) {\n                if (obs(yy().at(p).at(q).at(j*op().nt()))) {\n                    vector<double> Ey_ij(op().nt());\n                    if (Ey_fn(p,j,d_y0.at(p),d_RR.at(p),Ey_ij,*this)) throw runtime_error(\"fit\");\n                    for (int t=0;t<op().nt();t++) {\n                        xRyD_ofs << log(Ey_ij.at(t)) << '\\t';\n                        //likelihood\n                        loglike += -log(d_tau2.at(p))-pow(yy().at(p).at(q).at(j*op().nt()+t)-log(Ey_ij.at(t)),2)/d_tau2.at(p)/2;\n                    }\n                } else for (int t=0;t<op().nt();t++) xRyD_ofs << \"NA\\t\";\n            }\n            xRyD_ofs<<'\\n';\n            loglike_ofs << loglike << '\\n';\n        }\n    }\n    cout<<'\\n';\n}\n", "meta": {"hexsha": "4555388b120e9d5e62a7dc9a12ab6d6a287535e0", "size": 10709, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "peca_core/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_core/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_core/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": 36.9275862069, "max_line_length": 158, "alphanum_fraction": 0.4911756467, "num_tokens": 3457, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.626124191181315, "lm_q2_score": 0.5117166047041654, "lm_q1q2_score": 0.3203981452344442}}
{"text": "// Copyright (C) 1996-2016 by Synge Todo <wistaria@phys.s.u-tokyo.ac.jp>\n//\n// Distributed under the Boost Software License, Version 1.0. (See accompanying\n// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n#ifndef MATH_POWER_HPP\n#define MATH_POWER_HPP\n\n#include <boost/type_traits/is_arithmetic.hpp>\n#include <boost/utility/enable_if.hpp>\n#include <complex>\n\nnamespace math {\n\nusing boost::is_arithmetic;\nusing boost::enable_if;\nusing boost::disable_if;\n\nnamespace detail {\n\ntemplate<typename T>\nstruct power_traits {\n  typedef T power_type;\n};\n  \ntemplate<typename T>\nstruct power_traits<std::complex<T> > {\n  typedef T power_type;\n};\n\n} // end namespace detail\n\n//\n// function power2 and p2\n//\n\n#ifndef BOOST_NO_SFINAE\n\ntemplate<typename T>\ntypename detail::power_traits<T>::power_type\npower2(T t, typename enable_if<is_arithmetic<T> >::type* = 0) { return t * t; }\n\ntemplate<typename T>\ntypename detail::power_traits<T>::power_type\npower2(T const& t, typename disable_if<is_arithmetic<T> >::type* = 0) { return t * t; }\n\ntemplate<typename T>\ntypename detail::power_traits<T>::power_type\np2(T t, typename enable_if<is_arithmetic<T> >::type* = 0) { return power2(t); }\n\ntemplate<typename T>\ntypename detail::power_traits<T>::power_type\np2(T const& t, typename disable_if<is_arithmetic<T> >::type* = 0) { return power2(t); }\n\n#else\n  \ntemplate<typename T>\ntypename detail::power_traits<T>::power_type\npower2(T const& t) { return t * t; }\n\ntemplate<typename T>\ntypename detail::power_traits<T>::power_type\np2(T const& t) { return power2(t); }\n\n#endif\n\ntemplate<typename T>\ntypename detail::power_traits<std::complex<T> >::power_type\npower2(std::complex<T> const& t) { return power2(real(t)) + power2(imag(t)); }\n\n//\n// function power3 and p3\n//\n\n#ifndef BOOST_NO_SFINAE\n\ntemplate<typename T>\ntypename detail::power_traits<T>::power_type\npower3(T t, typename enable_if<is_arithmetic<T> >::type* = 0) { return t * t * t; }\n\ntemplate<typename T>\ntypename detail::power_traits<T>::power_type\npower3(T const& t, typename disable_if<is_arithmetic<T> >::type* = 0) { return t * t * t; }\n\ntemplate<typename T>\ntypename detail::power_traits<T>::power_type\np3(T t, typename enable_if<is_arithmetic<T> >::type* = 0) { return power3(t); }\n\ntemplate<typename T>\ntypename detail::power_traits<T>::power_type\np3(T const& t, typename disable_if<is_arithmetic<T> >::type* = 0) { return power3(t); }\n\n#else\n  \ntemplate<typename T>\ntypename detail::power_traits<T>::power_type\npower3(T const& t) { return t * t * t; }\n\ntemplate<typename T>\ntypename detail::power_traits<T>::power_type\np3(T const& t) { return power3(t); }\n\n#endif\n\n//\n// function power4 and p4\n//\n\n#ifndef BOOST_NO_SFINAE\n\ntemplate<typename T>\ntypename detail::power_traits<T>::power_type\npower4(T t, typename enable_if<is_arithmetic<T> >::type* = 0) { return power2(power2(t)); }\n\ntemplate<typename T>\ntypename detail::power_traits<T>::power_type\npower4(T const& t, typename disable_if<is_arithmetic<T> >::type* = 0) { return power2(power2(t)); }\n\ntemplate<typename T>\ntypename detail::power_traits<T>::power_type\np4(T t, typename enable_if<is_arithmetic<T> >::type* = 0) { return power4(t); }\n\ntemplate<typename T>\ntypename detail::power_traits<T>::power_type\np4(T const& t, typename disable_if<is_arithmetic<T> >::type* = 0) { return power4(t); }\n\n#else\n  \ntemplate<typename T>\ntypename detail::power_traits<T>::power_type\npower4(T const& t) { return power2(power2(t)); }\n\ntemplate<typename T>\ntypename detail::power_traits<T>::power_type\np4(T const& t) { return power4(t); }\n\n#endif\n\n//\n// function power6 and p6\n//\n\n#ifndef BOOST_NO_SFINAE\n\ntemplate<typename T>\ntypename detail::power_traits<T>::power_type\npower6(T t, typename enable_if<is_arithmetic<T> >::type* = 0) { return power3(power2(t)); }\n\ntemplate<typename T>\ntypename detail::power_traits<T>::power_type\npower6(T const& t, typename disable_if<is_arithmetic<T> >::type* = 0) { return power3(power2(t)); }\n\ntemplate<typename T>\ntypename detail::power_traits<T>::power_type\np6(T t, typename enable_if<is_arithmetic<T> >::type* = 0) { return power6(t); }\n\ntemplate<typename T>\ntypename detail::power_traits<T>::power_type\np6(T const& t, typename disable_if<is_arithmetic<T> >::type* = 0) { return power6(t); }\n\n#else\n  \ntemplate<typename T>\ntypename detail::power_traits<T>::power_type\npower6(T const& t) { return power3(power2(t)); }\n\ntemplate<typename T>\ntypename detail::power_traits<T>::power_type\np6(T const& t) { return power6(t); }\n\n#endif\n\n} // end namespace math\n\n#endif // MATH_POWER_HPP\n", "meta": {"hexsha": "c04d8313d21f6aaa5dacf7f0593ec3ab5440595a", "size": 4531, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "clstatphys/clstatphys/tools/power.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": "clstatphys/clstatphys/tools/power.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": "clstatphys/clstatphys/tools/power.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": 25.7443181818, "max_line_length": 99, "alphanum_fraction": 0.7261090267, "num_tokens": 1245, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6261241772283035, "lm_q2_score": 0.5117166047041654, "lm_q1q2_score": 0.32039813809445655}}
{"text": "/*\n\t@author herumi\n\n\ttiny calculator 2\n\tThis program generates a function to calc the value of\n\tpolynomial given by user in run-time.\n\tuse boost::spirit::qi\n*/\n#ifdef _WIN32\n\t#pragma warning(disable : 4127) // for boost(constant condition)\n\t#pragma warning(disable : 4512) // for boost\n\t#pragma warning(disable : 4819)\n#endif\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_container.hpp>\n#include <boost/spirit/include/phoenix_bind.hpp>\n#include <boost/timer.hpp>\n\n#include <stdio.h>\n#include <assert.h>\n#include <string>\n#include <vector>\n#define XBYAK_NO_OP_NAMES\n#include \"xbyak/xbyak.h\"\n\nenum Operand {\n\tOpAdd,\n\tOpSub,\n\tOpMul,\n\tOpDiv,\n\tOpNeg,\n\tOpImm,\n\tOpVarX\n};\n\nstruct Code {\n\tOperand op_;\n\tdouble val_;\n\tCode(Operand op)\n\t\t: op_(op)\n\t\t, val_(0)\n\t{\n\t}\n\tCode(double val)\n\t\t: op_(OpImm)\n\t\t, val_(val)\n\t{\n\t}\n};\n\ntypedef std::vector<Code> CodeSet;\n\nstruct Vm {\n\tCodeSet code_;\n\tdouble operator()(double x) const\n\t{\n\t\tconst size_t maxStack = 16;\n\t\tdouble stack[maxStack];\n\t\tdouble *p = stack;\n\t\tCodeSet::const_iterator pc = code_.begin();\n\n\t\twhile (pc != code_.end()) {\n\t\t\tswitch (pc->op_) {\n\t\t\tcase OpVarX:\n\t\t\t\t*p++ = x;\n\t\t\t\tbreak;\n\t\t\tcase OpImm:\n\t\t\t\t*p++ = pc->val_;\n\t\t\t\tbreak;\n\t\t\tcase OpNeg:\n\t\t\t\tp[-1] = -p[-1];\n\t\t\t\tbreak;\n\t\t\tcase OpAdd:\n\t\t\t\t--p;\n\t\t\t\tp[-1] += p[0];\n\t\t\t\tbreak;\n\t\t\tcase OpSub:\n\t\t\t\t--p;\n\t\t\t\tp[-1] -= p[0];\n\t\t\t\tbreak;\n\t\t\tcase OpMul:\n\t\t\t\t--p;\n\t\t\t\tp[-1] *= p[0];\n\t\t\t\tbreak;\n\t\t\tcase OpDiv:\n\t\t\t\t--p;\n\t\t\t\tp[-1] /= p[0];\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\t++pc;\n\t\t\tassert(p < stack + maxStack);\n\t\t}\n\t\treturn p[-1];\n\t}\n};\n\nclass Jit : public Xbyak::CodeGenerator {\nprivate:\n\tenum {\n\t\tMAX_CONST_NUM = 32\n\t};\n\tMIE_ALIGN(16) double constTbl_[MAX_CONST_NUM];\n\tXbyak::uint64_t negConst_;\n\tsize_t constTblPos_;\n#ifdef XBYAK32\n\tconst Xbyak::Reg32& varTbl_;\n\tconst Xbyak::Reg32& tbl_;\n#else\n\tconst Xbyak::Reg64& tbl_;\n#endif\n\tint regIdx_;\npublic:\n\t/*\n\t\tdouble jit(double x);\n\t\t@note 32bit: x : [esp+4], return fp0\n\t\t      64bit: x [rcx](win), xmm0(gcc), return xmm0\n\t*/\n\tJit()\n\t\t: negConst_(Xbyak::uint64_t(1) << 63)\n\t\t, constTblPos_(0)\n#ifdef XBYAK32\n\t\t, varTbl_(eax)\n\t\t, tbl_(edx)\n#elif defined(XBYAK64_WIN)\n\t\t, tbl_(rcx)\n#else\n\t\t, tbl_(rdi)\n#endif\n\t\t, regIdx_(-1)\n\t{\n#ifdef XBYAK32\n\t\tlea(varTbl_, ptr [esp+4]);\n#else\n#ifdef XBYAK64_WIN\n\t\tmovaps(ptr [rsp + 8], xm6); // save xm6, xm7\n\t\tmovaps(ptr [rsp + 8 + 16], xm7);\n#endif\n\t\tmovaps(xm7, xm0); // save xm0\n#endif\n\t\tmov(tbl_, (size_t)constTbl_);\n\t}\n\tvoid genPush(double n)\n\t{\n\t\tif (constTblPos_ >= MAX_CONST_NUM) throw;\n\t\tconstTbl_[constTblPos_] = n;\n\t\tif (regIdx_ == 7) throw;\n\t\tmovsd(Xbyak::Xmm(++regIdx_), ptr[tbl_ + constTblPos_ * sizeof(double)]);\n\t\tconstTblPos_++;\n\t}\n\tvoid genVarX()\n\t{\n#ifdef XBYAK32\n\t\tif (regIdx_ == 7) throw;\n\t\tmovsd(Xbyak::Xmm(++regIdx_), ptr[varTbl_]);\n#else\n\t\tif (regIdx_ == 6) throw;\n\t\tmovsd(Xbyak::Xmm(++regIdx_), xm7);\n#endif\n\t}\n\tvoid genAdd()\n\t{\n\t\taddsd(Xbyak::Xmm(regIdx_ - 1), Xbyak::Xmm(regIdx_)); regIdx_--;\n\t}\n\tvoid genSub()\n\t{\n\t\tsubsd(Xbyak::Xmm(regIdx_ - 1), Xbyak::Xmm(regIdx_)); regIdx_--;\n\t}\n\tvoid genMul()\n\t{\n\t\tmulsd(Xbyak::Xmm(regIdx_ - 1), Xbyak::Xmm(regIdx_)); regIdx_--;\n\t}\n\tvoid genDiv()\n\t{\n\t\tdivsd(Xbyak::Xmm(regIdx_ - 1), Xbyak::Xmm(regIdx_)); regIdx_--;\n\t}\n\tvoid genNeg()\n\t{\n\t\txorpd(Xbyak::Xmm(regIdx_), ptr [tbl_ + MAX_CONST_NUM * sizeof(double)]);\n\t}\n\tvoid complete()\n\t{\n#ifdef XBYAK32\n\t\tsub(esp, 8);\n\t\tmovsd(ptr [esp], xm0);\n\t\tfld(qword [esp]);\n\t\tadd(esp, 8);\n#else\n#ifdef XBYAK64_WIN\n\t\tmovaps(xm6, ptr [rsp + 8]);\n\t\tmovaps(xm7, ptr [rsp + 8 + 16]);\n#endif\n#endif\n\t\tret();\n\t}\n};\n\ntemplate<typename Iterator>\nstruct Parser : boost::spirit::qi::grammar<Iterator, boost::spirit::ascii::space_type> {\n\tboost::spirit::qi::rule<Iterator, boost::spirit::ascii::space_type> expression, term, factor;\n\tCodeSet& code_;\n\tParser(CodeSet& code)\n\t\t: Parser::base_type(expression)\n\t\t, code_(code)\n\t{\n\t\tnamespace qi = boost::spirit::qi;\n\t\tusing namespace qi::labels;\n\n\t\tusing boost::phoenix::ref;\n\t\tusing boost::phoenix::push_back;\n\n\t\texpression = term >> *(('+' > term[push_back(ref(code_), OpAdd)])\n\t\t\t\t\t\t\t | ('-' > term[push_back(ref(code_), OpSub)]));\n\n\t\tterm = factor >> *(('*' > factor[push_back(ref(code_), OpMul)])\n\t\t\t\t\t\t | ('/' > factor[push_back(ref(code_), OpDiv)]));\n\n\t\tfactor = qi::double_[push_back(ref(code_), _1)]\n\t\t\t\t| qi::lit('x')[push_back(ref(code_), OpVarX)]\n\t\t\t\t| ('(' > expression > ')')\n\t\t\t\t| ('-' > factor[push_back(ref(code_), OpNeg)])\n\t\t\t\t| ('+' > factor);\n\t}\n};\n\ntemplate<typename Iterator>\nstruct ParserJit : boost::spirit::qi::grammar<Iterator, boost::spirit::ascii::space_type> {\n\tboost::spirit::qi::rule<Iterator, boost::spirit::ascii::space_type> expression, term, factor;\n\tJit code_;\n\tParserJit()\n\t\t: ParserJit::base_type(expression)\n\t{\n\t\tnamespace qi = boost::spirit::qi;\n\t\tusing namespace qi::labels;\n\n\t\tusing boost::phoenix::ref;\n\t\tusing boost::phoenix::push_back;\n\t\tusing boost::phoenix::bind;\n\n\t\texpression = term >> *(('+' > term[bind(&Jit::genAdd, ref(code_))])\n\t\t\t\t\t\t\t | ('-' > term[bind(&Jit::genSub, ref(code_))]));\n\n\t\tterm = factor >> *(('*' > factor[bind(&Jit::genMul, ref(code_))])\n\t\t\t\t\t\t | ('/' > factor[bind(&Jit::genDiv, ref(code_))]));\n\n\t\tfactor = qi::double_[bind(&Jit::genPush, ref(code_), _1)]\n\t\t\t\t| qi::lit('x')[bind(&Jit::genVarX, ref(code_))]\n\t\t\t\t| ('(' > expression > ')')\n\t\t\t\t| ('-' > factor[bind(&Jit::genNeg, ref(code_))])\n\t\t\t\t| ('+' > factor);\n\t}\n};\n\ntemplate<class Func>\nvoid Test(const char *msg, const Func& f)\n{\n\tprintf(\"%s:\", msg);\n\tboost::timer t;\n\tdouble sum = 0;\n\tfor (double x = 0; x < 1000; x += 0.0001) {\n\t\tsum += f(x);\n\t}\n\tprintf(\"sum=%f, %fsec\\n\", sum, t.elapsed());\n}\n\nint main(int argc, char *argv[])\n{\n\tif (argc < 2) {\n\t\tfprintf(stderr, \"input formula\\n\");\n\t\treturn 1;\n\t}\n\tconst std::string str(argv[1]);\n\n\ttry {\n\t\tVm vm;\n\t\tParser<std::string::const_iterator> parser(vm.code_);\n\t\tParserJit<std::string::const_iterator> parserJit;\n\n\t\tconst std::string::const_iterator end = str.end();\n\n\t\tstd::string::const_iterator i = str.begin();\n\t\tif (!phrase_parse(i, end, parser, boost::spirit::ascii::space) || i != end) {\n\t\t\tputs(\"err 1\");\n\t\t\treturn 1;\n\t\t}\n\t\tprintf(\"ret=%f\\n\", vm(2.3));\n\n\t\ti = str.begin();\n\t\tif (!phrase_parse(i, end, parserJit, boost::spirit::ascii::space) || i != end) {\n\t\t\tputs(\"err 2\");\n\t\t\treturn 1;\n\t\t}\n\t\tparserJit.code_.complete();\n\t\tdouble (*jit)(double) = parserJit.code_.getCode<double (*)(double)>();\n\n\t\tTest(\"VM \", vm);\n\t\tTest(\"JIT\", jit);\n\t} catch (...) {\n\t\tfprintf(stderr, \"err\\n\");\n\t}\n}\n", "meta": {"hexsha": "a13d2cf56529654d81f2398b75e182699f35b834", "size": 6488, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "externals/xbyak/sample/calc2.cpp", "max_stars_repo_name": "Esigodini/dynarmic", "max_stars_repo_head_hexsha": "664de9eaaf10bee0fdd5e88f4f125cb9c3df5c54", "max_stars_repo_licenses": ["0BSD"], "max_stars_count": 1575.0, "max_stars_repo_stars_event_min_datetime": "2015-02-04T12:24:23.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T09:42:02.000Z", "max_issues_repo_path": "externals/xbyak/sample/calc2.cpp", "max_issues_repo_name": "Esigodini/dynarmic", "max_issues_repo_head_hexsha": "664de9eaaf10bee0fdd5e88f4f125cb9c3df5c54", "max_issues_repo_licenses": ["0BSD"], "max_issues_count": 366.0, "max_issues_repo_issues_event_min_datetime": "2016-09-02T06:37:43.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-11T18:38:24.000Z", "max_forks_repo_path": "externals/xbyak/sample/calc2.cpp", "max_forks_repo_name": "Esigodini/dynarmic", "max_forks_repo_head_hexsha": "664de9eaaf10bee0fdd5e88f4f125cb9c3df5c54", "max_forks_repo_licenses": ["0BSD"], "max_forks_count": 259.0, "max_forks_repo_forks_event_min_datetime": "2015-02-13T11:06:32.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T13:00:03.000Z", "avg_line_length": 21.4125412541, "max_line_length": 94, "alphanum_fraction": 0.6180641184, "num_tokens": 2210, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5660185351961016, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.3203769821855404}}
{"text": "///////////////////////////////////////////////////////////////////////////////\n// BSD 3-Clause License\n//\n// Copyright (C) 2021, University of Edinburgh\n// Copyright note valid unless otherwise stated in individual files.\n// All rights reserved.\n///////////////////////////////////////////////////////////////////////////////\n\n#ifndef CROCODDYL_CORE_NUMDIFF_RESIDUAL_HPP_\n#define CROCODDYL_CORE_NUMDIFF_RESIDUAL_HPP_\n\n#include <boost/function.hpp>\n#include \"crocoddyl/multibody/fwd.hpp\"\n#include \"crocoddyl/core/residual-base.hpp\"\n\nnamespace crocoddyl {\n\n/**\n * @brief This class computes the numerical differentiation of a residual model.\n *\n * It computes Jacobian of the residual model via numerical differentiation, i.e., \\f$\\mathbf{R_x}\\f$\n * and \\f$\\mathbf{R_u}\\f$ which denote the Jacobians of the residual function\n * \\f$\\mathbf{r}(\\mathbf{x},\\mathbf{u})\\f$.\n *\n * \\sa `ResidualModelAbstractTpl()`, `calcDiff()`\n */\ntemplate <typename _Scalar>\nclass ResidualModelNumDiffTpl : public ResidualModelAbstractTpl<_Scalar> {\n public:\n  EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n\n  typedef _Scalar Scalar;\n  typedef ResidualDataAbstractTpl<Scalar> ResidualDataAbstract;\n  typedef ResidualModelAbstractTpl<Scalar> Base;\n  typedef ResidualDataNumDiffTpl<Scalar> Data;\n  typedef DataCollectorAbstractTpl<Scalar> DataCollectorAbstract;\n  typedef MathBaseTpl<Scalar> MathBase;\n  typedef typename MathBaseTpl<Scalar>::VectorXs VectorXs;\n  typedef typename MathBaseTpl<Scalar>::MatrixXs MatrixXs;\n  typedef boost::function<void(const VectorXs&, const VectorXs&)> ReevaluationFunction;\n\n  /**\n   * @brief Initialize the numdiff residual model\n   *\n   * @param model  Residual model that we want to apply the numerical differentiation\n   */\n  explicit ResidualModelNumDiffTpl(const boost::shared_ptr<Base>& model);\n\n  /**\n   * @brief Initialize the numdiff residual model\n   */\n  virtual ~ResidualModelNumDiffTpl();\n\n  /**\n   * @brief @copydoc Base::calc()\n   */\n  virtual void calc(const boost::shared_ptr<ResidualDataAbstract>& data, const Eigen::Ref<const VectorXs>& x,\n                    const Eigen::Ref<const VectorXs>& u);\n\n  /**\n   * @brief @copydoc Base::calc(const boost::shared_ptr<ResidualDataAbstract>& data, const Eigen::Ref<const VectorXs>&\n   * x)\n   */\n  virtual void calc(const boost::shared_ptr<ResidualDataAbstract>& data, const Eigen::Ref<const VectorXs>& x);\n\n  /**\n   * @brief @copydoc Base::calcDiff()\n   */\n  virtual void calcDiff(const boost::shared_ptr<ResidualDataAbstract>& data, const Eigen::Ref<const VectorXs>& x,\n                        const Eigen::Ref<const VectorXs>& u);\n\n  /**\n   * @brief @copydoc Base::calcDiff(const boost::shared_ptr<ResidualDataAbstract>& data, const Eigen::Ref<const\n   * VectorXs>& x)\n   */\n  virtual void calcDiff(const boost::shared_ptr<ResidualDataAbstract>& data, const Eigen::Ref<const VectorXs>& x);\n\n  /**\n   * @brief @copydoc Base::createData()\n   */\n  virtual boost::shared_ptr<ResidualDataAbstract> createData(DataCollectorAbstract* const data);\n\n  /**\n   * @brief Return the original residual model\n   */\n  const boost::shared_ptr<Base>& get_model() const;\n\n  /**\n   * @brief Return the disturbance value used by the numdiff routine\n   */\n  const Scalar get_disturbance() const;\n\n  /**\n   * @brief Modify the disturbance value used by the numdiff routine\n   */\n  void set_disturbance(const Scalar disturbance);\n\n  /**\n   * @brief Register functions that updates the shared data computed for a system rollout\n   * The updated data is used to evaluate of the gradient and hessian.\n   *\n   * @param reevals are the registered functions.\n   */\n  void set_reevals(const std::vector<ReevaluationFunction>& reevals);\n\n protected:\n  using Base::nu_;\n  using Base::state_;\n  using Base::unone_;\n\n private:\n  /**\n   * @brief Make sure that when we finite difference the residual model, the user\n   * does not face unknown behaviour because of the finite differencing of a\n   * quaternion around pi. This behaviour might occur if ResidualModelState and\n   * FloatingInContact differential model are used together.\n   *\n   * For full discussions see issue\n   * https://gepgitlab.laas.fr/loco-3d/crocoddyl/issues/139\n   *\n   * @param x is the state at which the check is performed.\n   */\n  void assertStableStateFD(const Eigen::Ref<const VectorXs>& /*x*/);\n\n  boost::shared_ptr<Base> model_;              //!< Residual model hat we want to apply the numerical differentiation\n  Scalar disturbance_;                         //!< Disturbance used in the numerical differentiation routine\n  std::vector<ReevaluationFunction> reevals_;  //!< Functions that needs execution before calc or calcDiff\n};\n\ntemplate <typename _Scalar>\nstruct ResidualDataNumDiffTpl : public ResidualDataAbstractTpl<_Scalar> {\n  EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n\n  typedef _Scalar Scalar;\n  typedef MathBaseTpl<Scalar> MathBase;\n  typedef ResidualDataAbstractTpl<Scalar> Base;\n  typedef DataCollectorAbstractTpl<Scalar> DataCollectorAbstract;\n  typedef ActivationDataAbstractTpl<Scalar> ActivationDataAbstract;\n  typedef typename MathBaseTpl<Scalar>::VectorXs VectorXs;\n\n  /**\n   * @brief Initialize the numdiff residual data\n   *\n   * @tparam Model is the type of the `ResidualModelAbstractTpl`.\n   * @param model is the object to compute the numerical differentiation from.\n   */\n  template <template <typename Scalar> class Model>\n  explicit ResidualDataNumDiffTpl(Model<Scalar>* const model, DataCollectorAbstract* const shared_data)\n      : Base(model, shared_data),\n        dx(model->get_state()->get_ndx()),\n        xp(model->get_state()->get_nx()),\n        du(model->get_nu()),\n        up(model->get_nu()) {\n    dx.setZero();\n    xp.setZero();\n    du.setZero();\n    up.setZero();\n\n    const std::size_t& ndx = model->get_model()->get_state()->get_ndx();\n    const std::size_t& nu = model->get_model()->get_nu();\n    data_0 = model->get_model()->createData(shared_data);\n    for (std::size_t i = 0; i < ndx; ++i) {\n      data_x.push_back(model->get_model()->createData(shared_data));\n    }\n    for (std::size_t i = 0; i < nu; ++i) {\n      data_u.push_back(model->get_model()->createData(shared_data));\n    }\n  }\n\n  virtual ~ResidualDataNumDiffTpl() {}\n\n  using Base::r;\n  using Base::Ru;\n  using Base::Rx;\n  using Base::shared;\n\n  VectorXs dx;  //!< State disturbance.\n  VectorXs xp;  //!< The integrated state from the disturbance on one DoF \"\\f$ \\int x dx_i \\f$\".\n  VectorXs du;  //!< Control disturbance.\n  VectorXs up;  //!< The integrated control from the disturbance on one DoF \"\\f$ \\int u du_i = u + du \\f$\".\n  boost::shared_ptr<Base> data_0;                //!< The data at the approximation point.\n  std::vector<boost::shared_ptr<Base> > data_x;  //!< The temporary data associated with the state variation.\n  std::vector<boost::shared_ptr<Base> > data_u;  //!< The temporary data associated with the control variation.\n};\n\n}  // namespace crocoddyl\n\n/* --- Details -------------------------------------------------------------- */\n/* --- Details -------------------------------------------------------------- */\n/* --- Details -------------------------------------------------------------- */\n#include \"crocoddyl/core/numdiff/residual.hxx\"\n\n#endif  // CROCODDYL_CORE_NUMDIFF_RESIDUAL_HPP_\n", "meta": {"hexsha": "d4051562c0b9233d383076fe02fe4a5b1be11e26", "size": 7220, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/crocoddyl/core/numdiff/residual.hpp", "max_stars_repo_name": "spykspeigel/crocoddyl", "max_stars_repo_head_hexsha": "0500e398861564b6986d99206a1e0ccec0d66a33", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/crocoddyl/core/numdiff/residual.hpp", "max_issues_repo_name": "spykspeigel/crocoddyl", "max_issues_repo_head_hexsha": "0500e398861564b6986d99206a1e0ccec0d66a33", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/crocoddyl/core/numdiff/residual.hpp", "max_forks_repo_name": "spykspeigel/crocoddyl", "max_forks_repo_head_hexsha": "0500e398861564b6986d99206a1e0ccec0d66a33", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-01-05T03:09:55.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-05T03:09:55.000Z", "avg_line_length": 37.2164948454, "max_line_length": 118, "alphanum_fraction": 0.6761772853, "num_tokens": 1743, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5621765155565326, "lm_q2_score": 0.5698526514141572, "lm_q1q2_score": 0.3203577779526623}}
{"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#include <iostream>\n#include <sstream>\n#include <iomanip>\n#include <cassert>\n\n#include <boost/math/constants/constants.hpp>\n\n#include \"NGLMExt.hpp\"\n#include \"NTris.hpp\"\n\nvoid NTris::add( const glm::vec3& a, const glm::vec3& b, const glm::vec3& c)\n{\n    unsigned i = verts.size(); verts.push_back(a); \n    unsigned j = verts.size(); verts.push_back(b); \n    unsigned k = verts.size(); verts.push_back(c); \n    glm::uvec3 tri(i,j,k);\n    tris.push_back(tri);\n}  \n\nunsigned NTris::get_num_tri() const \n{\n    return tris.size();\n}\n\nunsigned NTris::get_num_vert() const \n{\n    return verts.size();\n}\n\n\nvoid NTris::get_vert( unsigned i, glm::vec3& v ) const \n{\n    v = verts[i] ; \n}\nvoid NTris::get_normal( unsigned /*i*/, glm::vec3& n ) const \n{\n    n.x = 0  ; \n    n.y = 0  ; \n    n.z = 0  ; \n}\nvoid NTris::get_uv( unsigned /*i*/, glm::vec3& uv ) const \n{\n    uv.x = 0  ; \n    uv.y = 0  ; \n    uv.z = 0  ; \n}\n\n\n\nvoid NTris::get_tri(unsigned i, glm::uvec3& t) const \n{\n    t = tris[i] ; \n}\nvoid NTris::get_tri(unsigned i, glm::uvec3& t, glm::vec3& a, glm::vec3& b, glm::vec3& c ) const \n{\n    t = tris[i] ; \n    a = verts[t.x]; \n    b = verts[t.y]; \n    c = verts[t.z]; \n}\n\n\n\nstd::string NTris::brief() const \n{\n    std::stringstream ss ; \n\n    ss << \"NTris\"\n       << \" nf \" << std::setw(5) << tris.size() \n       << \" nv \" << std::setw(5) << verts.size() \n       ;\n\n    return ss.str();\n}\n\nvoid NTris::dump(const char* msg) const \n{\n    std::cout << msg << \" \" << brief() << std::endl ;\n\n    glm::uvec3 t ; \n    glm::vec3 a ; \n    glm::vec3 b ; \n    glm::vec3 c ; \n\n    unsigned ntri = get_num_tri();\n    for(unsigned i=0 ; i < ntri ; i++)\n    {\n        get_tri(i, t, a,b,c );\n\n        std::cout << \" t \" << std::setw(20) << glm::to_string(t) \n                  << \" a \" << std::setw(20) << glm::to_string(a) \n                  << \" b \" << std::setw(20) << glm::to_string(b)\n                  << \" c \" << std::setw(20) << glm::to_string(c)\n                  << std::endl\n                  ; \n\n    }\n\n}\n\n\nNTris* NTris::make_sphere( unsigned n_polar, unsigned n_azimuthal, float ctmin, float ctmax ) \n{\n\n    /*\n \n                                  t0             t1            ct0       \n\n            t = 0                  0             1/n_polar      +1   \n\n            t = n_polar - 1      1 - 1/n_polar     1            -1   \n\n\n\n                 -  ct0\n                    max_exclude:  ct1 > zmax \n                 -  ct1               - ct0\n    zmax     +-----------------+        max_straddle\n            /    -              \\     - ct1\n           /                     \\\n          /      -                \\   - ct0\n    zmin +-------------------------+    min_straddle\n                 - ct0                - ct1\n                   min_exclude:  ct0 < zmin\n                 - ct1\n\n    */\n \n    assert(ctmax > ctmin && ctmax <= 1.f && ctmin >= -1.f);\n\n\n    NTris* tris = new NTris ; \n\n    float pi = boost::math::constants::pi<float>() ;\n\n    for(unsigned t=0 ; t < n_polar ; t++)\n    {\n        double t0 = 1.0f*pi*float(t)/n_polar ; \n        double t1 = 1.0f*pi*float(t+1)/n_polar ;\n\n        double st0,st1,ct0,ct1 ;\n        sincos_<double>(t0, st0, ct0 ); \n        sincos_<double>(t1, st1, ct1 ); \n        assert( ct0 > ct1 );\n\n        bool max_exclude  = ct1 > ctmax ;\n        bool max_straddle = ctmax <= ct0 && ctmax > ct1 ; \n        bool min_straddle = ctmin <= ct0 && ctmin > ct1 ; \n        bool min_exclude  = ct0 < ctmin ;  \n\n        if(max_exclude || min_exclude ) \n        {\n            continue ; \n        }\n        else if(max_straddle)\n        {\n            sincos_<double>(acos(ctmax), st0, ct0 ); \n        }\n        else if(min_straddle) \n        {\n            sincos_<double>(acos(ctmin), st1, ct1 ); \n        }\n\n        for(unsigned 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 x00( st0*cp0, st0*sp0, ct0 );\n            glm::vec3 x10( st0*cp1, st0*sp1, ct0 );\n\n            glm::vec3 x01( st1*cp0, st1*sp0, ct1 );\n            glm::vec3 x11( st1*cp1, st1*sp1, ct1 );\n\n   \n            if( t == 0 || t == n_polar - 1) \n            {\n                tris->add(x00,x01,x11); \n            }\n            else\n            {\n                tris->add(x00,x01,x10);\n                tris->add(x10,x01,x11); \n            }\n        }\n    } \n    return tris ; \n}\n\n\n\n\n", "meta": {"hexsha": "56398eadcf4fce992e4b8757e6ce87f1ff6a9d85", "size": 5241, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "npy/NTris.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/NTris.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/NTris.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": 24.2638888889, "max_line_length": 96, "alphanum_fraction": 0.4815874833, "num_tokens": 1602, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5698526660244838, "lm_q2_score": 0.5621765008857981, "lm_q1q2_score": 0.3203577778060876}}
{"text": "//! Implementation of the input_parser.\n\n#include <iostream>\n#include <sstream>\n#include <fstream>\n#include <string>\n#include <vector>\n#include <map>\n#include <utility>\n#include <stack>\n#include <algorithm>\n#include <Eigen/Dense>\n#include \"../include/ply.h\"\n#include \"../include/input_parser.h\"\n\n\n//! The subscript of the laminate code. e.g. [0/45/45/90]8s4. 8 is the pre_count,\n//! s is the has_symmetry, and 4 is the post_count.\nstruct SubscriptInfo {\n    int pre_count;\n    bool has_symmetry;\n    int post_count;\n};\n\n//! Read material_data file and return the format into a map.\nstd::map<std::string, Properties> \n    load_material_data(const std::string& filename);\n\n//! Parse the laminate code and return a pair in which the first elemnt is the\n//! vector containing ply angles, and the second element is the SubscriptInfo\n//! of the given laminate. \nstd::pair<std::vector<double>, SubscriptInfo> \n    laminate_code_parser(std::string laminate_code);\n\n// Parse the trailing info of the laminate code and return the info into the\n// SubscriptInfo struct.\nSubscriptInfo subscript_parser(std::string subscript);\n\n//! Convert the laminate information into a vector of ply objects.\nstd::vector<ply> build_laminate_vector(\n    const std::pair<std::vector<double>, SubscriptInfo>& layout_info,\n    std::vector<std::string>& ply_materials,\n    const std::vector<double>& ply_thickness, \n    const std::map<std::string, Properties>& material_map);\n\n//! Strip the left and right square bracket of a string.\nstd::string strip_bracket(std::string input_str);\n\n//! Convert the string inside bracket into vector of doubles.\nstd::vector<double> strs_to_vector(std::string code);\n\n//! Convert the string inside bracket into vector of strings. Used for the\n//! material data parsing.\nstd::vector<std::string> mat_str_to_vector(std::string strings);\n\nusing std::string;\nusing std::cin; using std::cout; using std::endl;\nusing std::vector; using std::map; using std::stack; using std::pair;\n\nvector<string> read_composite_input(const string& filename) {\n    vector<string> result;\n    string line;\n    std::ifstream file(filename);\n    if (file.is_open()) {\n        while (getline(file, line)) {\n            if(line.find(\"[\") != string::npos && \n                line.find(\"]\") != string::npos) {\n                string::size_type l_bracket_pos = line.find(\"[\");\n                result.push_back(line.substr(l_bracket_pos));\n            }\n        }\n    }\n    return result;\n}\n\nvector<ply> get_ply_vector(vector<string>& input_strings, \n    const string& material_data_filename) {\n        \n        map<string, Properties> material_data = \n            load_material_data(material_data_filename);\n\n        pair<vector<double>, SubscriptInfo> layout_info =\n            laminate_code_parser(input_strings[0]);\n\n        string material_strings = strip_bracket(input_strings[1]);\n        vector<string> ply_materials = \n            mat_str_to_vector(material_strings);\n        \n        string thickness_strings = strip_bracket(input_strings[2]);\n\n        vector<double> ply_thickness =\n            strs_to_vector(thickness_strings);\n            \n        vector<ply> laminate = build_laminate_vector(layout_info, \n            ply_materials, ply_thickness, material_data);\n    \n    return laminate;\n    }\n\nEigen::Matrix<double, 6, 1> get_load_vector(string& input_string) {\n    string load_string = strip_bracket(input_string);\n    vector<double> load_stl_vector = strs_to_vector(load_string);\n    Eigen::Matrix<double, 6, 1> load_vector(load_stl_vector.data());\n    return load_vector;\n\n}\n\ndouble get_minimum_ply_thickness(string& thickness_strings_with_brackets) {\n    string thickness_strings = strip_bracket(thickness_strings_with_brackets);\n    vector<double> ply_thickness =\n        strs_to_vector(thickness_strings);\n    auto min_it = std::min_element(ply_thickness.begin(), \n                                    ply_thickness.end());\n    \n    double minimum = *min_it;\n    \n    return minimum;\n}\n\nmap<string, Properties> load_material_data(const string& filename) {\n    map<string, Properties> data;\n    string line;\n    std::ifstream input_file(filename);\n    if (input_file.is_open()) {\n        string material_name;\n        Properties p;\n        input_file.ignore(500, '\\n');  // Ignore the first line\n        while (!input_file.eof()) {\n            input_file >> material_name >> p.E1 >> p.E2 >> p.nu12 >> p.G12;\n            if (!input_file) {\n                cout << \"Error: file corrupted. Lines After \" \n                    \"corrupted line are not read.\"<< endl;\n                break;\n            }\n            data.insert({material_name, p});\n        }\n    } else {\n        cout << \"Error: Cannot open file.\" ;\n    }\n    return data;\n}\n\nstring strip_bracket(string input_str) {\n    std::size_t left_bracket_pos = input_str.find(\"[\");\n    std::size_t right_bracket_pos = input_str.find(\"]\");\n    return input_str.substr(left_bracket_pos+1, \n        right_bracket_pos-left_bracket_pos-1);\n\n}\n\npair<vector<double>, SubscriptInfo> laminate_code_parser(string laminate_code) {\n    std::size_t left_bracket_pos = laminate_code.find(\"[\");\n    std::size_t right_bracket_pos = laminate_code.find(\"]\");\n    pair<vector<double>, SubscriptInfo> result;\n    if (left_bracket_pos == string::npos || right_bracket_pos == string::npos\n        || left_bracket_pos > right_bracket_pos) {\n            cout << \"Invalid laminate code input.\" << endl;\n        return result;\n    }\n    string theta_string = laminate_code.substr(left_bracket_pos+1, \n        right_bracket_pos-left_bracket_pos-1);\n    string subscript_string = laminate_code.substr(right_bracket_pos+1, \n        laminate_code.size()-right_bracket_pos-1);\n    result.first = strs_to_vector(theta_string);\n    result.second = subscript_parser(subscript_string);\n    return result;\n}\n\nvector<ply> build_laminate_vector(\n    const pair<vector<double>, SubscriptInfo>& layout_info,\n    vector<string>& ply_materials,\n    const vector<double>& ply_thickness, \n    const std::map<string, Properties>& material_map) {\n        \n        vector<double> theta_vec = layout_info.first;\n        SubscriptInfo info = layout_info.second;\n\n        vector<ply> laminate_vec;\n        stack<ply> ply_stack;\n        \n        // It's not optimized in that we don't need the stack operation if \n        // we don't have the symmetry subscript, but this arrangement \n        // makes the code less redundant.\n        for (int i = 1; i <= info.pre_count; i++) {\n            auto theta_it = theta_vec.begin();\n            auto mat_it = ply_materials.begin();\n            auto t_it = ply_thickness.begin();\n            for (; theta_it != theta_vec.end(); theta_it++, mat_it++, t_it++) {\n                ply local_ply(*mat_it, material_map.at(*mat_it), \n                    *theta_it, *t_it);\n                laminate_vec.push_back(local_ply);\n                ply_stack.push(local_ply); // for symmetric condition\n            }\n        }\n\n        if (info.has_symmetry) {\n            while (!ply_stack.empty()) {\n                laminate_vec.push_back(ply_stack.top());\n                ply_stack.pop();\n            }\n        }\n\n        if (info.post_count > 1) {\n            vector<ply> laminate_copy(laminate_vec);\n            for (int i = 2; i <= info.post_count; i++) {\n                for (auto it = laminate_copy.begin(); \n                    it != laminate_copy.end(); it++) {\n                    laminate_vec.push_back(*it);\n                }\n\n            }\n        }\n\n    \n    return laminate_vec;\n\n}\n\nstd::vector<double> strs_to_vector(string theta_string) {\n    std::replace(theta_string.begin(), theta_string.end(), '/', ' ');\n    std::replace(theta_string.begin(), theta_string.end(), ',', ' ');\n    std::istringstream theta_stream(theta_string);\n    std::vector<double> theta_vec;\n    double theta;\n    while (theta_stream >> theta) {\n        theta_vec.push_back(theta);\n    }\n\n    return theta_vec;\n}\n\nstd::vector<string> mat_str_to_vector(string strings) {\n    std::replace(strings.begin(), strings.end(), ',', ' ');\n    std::istringstream stream(strings);\n    std::vector<string> vec;\n    string single_string;\n    while (stream >> single_string) {\n        vec.push_back(single_string);\n    }\n    return vec;\n}\n\nSubscriptInfo subscript_parser(string subscript) {\n    SubscriptInfo info;\n    std::size_t s_pos = subscript.find(\"s\");\n    if (s_pos != string::npos) {  // subscript contains an 's'\n        info.has_symmetry = true;\n\n        if (s_pos != 0) {  // subscript not at the beginning\n            string pre_repetition_string = subscript.substr(0, s_pos);\n            if (std::stoi(pre_repetition_string) > 0) {\n                info.pre_count = std::stoi(pre_repetition_string);\n            } else {\n                info.pre_count = 1;\n            }\n        } else {\n            info.pre_count = 1;\n        }\n\n        if (s_pos != subscript.size() - 1) {  // subscript not at the end\n            string post_repetition_string = \n                subscript.substr(s_pos+1, subscript.size());\n            info.post_count = std::stoi(post_repetition_string);\n        } else {\n            info.post_count = 1;\n        }\n\n    } else {\n        string pre_repetition_string = subscript.substr(0, subscript.size());\n        info.pre_count = std::stoi(pre_repetition_string);\n        info.has_symmetry = false;\n        info.post_count = 0;\n    }\n    return info;\n}", "meta": {"hexsha": "60fa056b750e2cb118307aa26d9d27c27045c579", "size": 9383, "ext": "cc", "lang": "C++", "max_stars_repo_path": "lib/input_parser.cc", "max_stars_repo_name": "quentin-tw/laminate_calc", "max_stars_repo_head_hexsha": "d70718ab1092e502f8e467c57d1284eddf8836f2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "lib/input_parser.cc", "max_issues_repo_name": "quentin-tw/laminate_calc", "max_issues_repo_head_hexsha": "d70718ab1092e502f8e467c57d1284eddf8836f2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lib/input_parser.cc", "max_forks_repo_name": "quentin-tw/laminate_calc", "max_forks_repo_head_hexsha": "d70718ab1092e502f8e467c57d1284eddf8836f2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.12, "max_line_length": 81, "alphanum_fraction": 0.6352978791, "num_tokens": 2100, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5698526514141571, "lm_q2_score": 0.5621765008857981, "lm_q1q2_score": 0.3203577695925053}}
{"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\n *\n * \\brief The main file for the NMF matrix factorization algorithm.\n *\n */\n\n#include <graphlab/util/stl_util.hpp>\n#include <graphlab.hpp>\n#include <graphlab/engine/gl3engine.hpp>\n#include <Eigen/Dense>\n#include \"eigen_serialization.hpp\"\n#include <graphlab/macros_def.hpp>\n\n#define VERTEX_DELTA_TASK_ID 0\n\ntypedef Eigen::VectorXd vec_type;\ntypedef Eigen::MatrixXd mat_type;\n\n//when using negative node id range, we are not allowed to use\n//0 and 1 so we add 2.\nconst static int SAFE_NEG_OFFSET=2;\nstatic bool debug;\nint iter = 0;\nenum { PHASE1, PHASE2};\nint phase = PHASE1;\ndouble epsilon = 1e-16;\n\nbool isuser(uint node){\n  return ((int)node) >= 0;\n}\n\n/**\n * \\ingroup toolkit_matrix_pvecization\n *\n * \\brief the vertex data type which contains the latent pvec.\n *\n * Each row and each column in the matrix corresponds to a different\n * vertex in the SGD graph.  Associated with each vertex is a pvec\n * (vector) of latent parameters that represent that vertex.  The goal\n * of the SGD algorithm is to find the values for these latent\n * parameters such that the non-zero entries in the matrix can be\n * predicted by taking the dot product of the row and column pvecs.\n */\nstruct vertex_data {\n  /**\n   * \\brief A shared \"constant\" that specifies the number of latent\n   * values to use.\n   */\n  static size_t NLATENT;\n  /** \\brief The latent pvec for this vertex */\n  vec_type pvec;\n\n  int nupdates;\n\n  /**\n   * \\brief Simple default constructor which randomizes the vertex\n   *  data\n   */\n  vertex_data() { if (debug) pvec = vec_type::Ones(NLATENT); else randomize(); }\n  /** \\brief Randomizes the latent pvec */\n  void randomize() { pvec.resize(NLATENT); pvec.setRandom(); }\n  /** \\brief Save the vertex data to a binary archive */\n  void save(graphlab::oarchive& arc) const {\n    arc << pvec;\n  }\n  /** \\brief Load the vertex data from a binary archive */\n  void load(graphlab::iarchive& arc) {\n    arc >> pvec;\n  }\n}; // end of vertex data\n\nstd::size_t hash_value(vertex_data const& b) {\n  return b.nupdates;\n}\n\n\n/**\n * \\brief The edge data stores the entry in the matrix.\n *\n * In addition the edge data sgdo stores the most recent error estimate.\n */\nstruct edge_data : public graphlab::IS_POD_TYPE {\n  /**\n   * \\brief The type of data on the edge;\n   *\n   * \\li *Train:* the observed value is correct and used in training\n   * \\li *Validate:* the observed value is correct but not used in training\n   * \\li *Predict:* The observed value is not correct and should not be\n   *        used in training.\n   */\n  enum data_role_type { TRAIN, VALIDATE, PREDICT  };\n\n  /** \\brief the observed value for the edge */\n  float obs;\n\n  /** \\brief The train/validation/test designation of the edge */\n  data_role_type role;\n\n  /** \\brief basic initialization */\n  edge_data(float obs = 0, data_role_type role = PREDICT) :\n    obs(obs), role(role) { }\n\n}; // end of edge data\n\nstd::size_t hash_value(edge_data const& b) {\n  return boost::hash_value(b.obs);\n}\n\n\n/**\n * \\brief The graph type is defined in terms of the vertex and edge\n * data.\n */\ntypedef graphlab::distributed_graph<vertex_data, edge_data> graph_type;\ntypedef graphlab::gl3engine<graph_type> engine_type;\n\n\nvec_type x1;\nvec_type x2;\nvec_type * px;\n\nbool isuser_node(const graph_type::vertex_type& vertex){\n  return isuser(vertex.id());\n}\n\n\n/**\n * \\brief The graph loader function is a line parser used for\n * distributed graph construction.\n */\ninline bool graph_loader(graph_type& graph,\n                         const std::string& filename,\n                         const std::string& line) {\n  ASSERT_FALSE(line.empty());\n  // Determine the role of the data\n  edge_data::data_role_type role = edge_data::TRAIN;\n  if(boost::ends_with(filename,\".validate\")) role = edge_data::VALIDATE;\n  else if(boost::ends_with(filename, \".predict\")) role = edge_data::PREDICT;\n  // Parse the line\n  std::stringstream strm(line);\n  graph_type::vertex_id_type source_id(-1), target_id(-1);\n  float obs(0);\n  strm >> source_id >> target_id;\n\n  // for test files (.predict) no need to read the actual rating value.\n  if(role == edge_data::TRAIN || role == edge_data::VALIDATE) {\n    strm >> obs;\n  }\n  target_id = -(graphlab::vertex_id_type(target_id + SAFE_NEG_OFFSET));\n\n  // Create an edge and add it to the graph\n  graph.add_edge(source_id, target_id, edge_data(obs, role));\n  return true; // successful load\n} // end of graph_loader\n\n\n\nvoid vertex_delta(graph_type::vertex_type& vtx, const vec_type& delta) {\n  if (delta.sum() != 0)\n    vtx.data().pvec.array() *= delta.array() / px->array(); \n  for (uint i=0; i< vertex_data::NLATENT; i++)\n    if (vtx.data().pvec[i] < epsilon)\n      vtx.data().pvec[i] = epsilon;\n}\n\nvoid nmf_function(engine_type::context_type& context,\n                  graph_type::edge_type& edge) {\n  double pred = edge.source().data().pvec.dot(edge.target().data().pvec);\n  if (pred == 0)\n     logstream(LOG_FATAL)<<\"Got into numerical error!\" << std::endl;    \n  vec_type delta;\n  delta = (phase == PHASE1 ? edge.target().data().pvec : edge.source().data().pvec) * edge.data().obs / pred;\n  context.send_delta(VERTEX_DELTA_TASK_ID, phase == PHASE1 ? edge.source() : edge.target(), delta);\n}\n\n\nvec_type count_edges(const graph_type::edge_type& edge) {\n  vec_type ret = vec_type::Zero(2);\n  if (edge.data().role == edge_data::TRAIN){\n    ret[0] = 1;\n  }\n  else if (edge.data().role == edge_data::VALIDATE){\n    ret[1] = 1;\n  }\n  if (edge.data().obs < 0)\n    logstream(LOG_FATAL)<<\"Found a negative entry in matirx row \" << edge.source().id() << \" with value: \" << edge.data().obs << std::endl;\n  return ret;\n}\n\nvoid verify_rows(\n    graph_type::vertex_type& vertex){\n        if (isuser(vertex.id()) && vertex.num_out_edges() == 0)\n          logstream(LOG_FATAL)<<\"NMF algorithm can not work when the row \" << vertex.id() << \" of the matrix contains all zeros\" << std::endl;\n}\n\nvec_type pre_iter( const graph_type::vertex_type & vertex){\n  return vertex.data().pvec;\n}\n\n\nvoid sync_function(engine_type::context_type& context,\n                   graph_type::vertex_type& vertex) {\n  context.synchronize(vertex);\n}\n\n/**\n * \\brief Given an edge compute the error associated with that edge\n */\ndouble extract_l2_error(const graph_type::edge_type & edge) {\n  double pred =\n      edge.source().data().pvec.dot(edge.target().data().pvec);\n  double rmse = (edge.data().obs - pred) * (edge.data().obs - pred);\n  return rmse;\n} // end of extract_l2_error\n\n\n\nsize_t vertex_data::NLATENT = 20;\n\n\n\nint main(int argc, char** argv) {\n  global_logger().set_log_level(LOG_INFO);\n  global_logger().set_log_to_console(true);\n\n  // Parse command line options -----------------------------------------------\n  const std::string description =\n      \"Compute the ALS factorization of a matrix.\";\n  graphlab::command_line_options clopts(description);\n  std::string input_dir;\n  size_t interval = 0;\n  size_t ITERATIONS = 10;\n  std::string exec_type = \"synchronous\";\n  clopts.attach_option(\"matrix\", input_dir,\n                       \"The directory containing the matrix file\");\n  clopts.add_positional(\"matrix\");\n  clopts.attach_option(\"D\", vertex_data::NLATENT,\n                       \"Number of latent parameters to use.\");\n  clopts.attach_option(\"interval\", interval,\n                       \"The time in seconds between error reports\");\n  clopts.attach_option(\"iterations\", ITERATIONS,\n                       \"number of NMF iterations\");\n  if(!clopts.parse(argc, argv) || input_dir == \"\") {\n    std::cout << \"Error in parsing command line arguments.\" << std::endl;\n    clopts.print_description();\n    return EXIT_FAILURE;\n  }\n  ///! Initialize control plain using mpi\n  graphlab::mpi_tools::init(argc, argv);\n  graphlab::distributed_control dc;\n\n  dc.cout() << \"Loading graph.\" << std::endl;\n  graphlab::timer timer;\n  graph_type graph(dc, clopts);\n  graph.load(input_dir, graph_loader);\n  dc.cout() << \"Loading graph. Finished in \"\n            << timer.current_time() << std::endl;\n\n  dc.cout() << \"Finalizing graph.\" << std::endl;\n  timer.start();\n  graph.finalize();\n  dc.cout() << \"Finalizing graph. Finished in \"\n            << timer.current_time() << std::endl;\n\n  if (!graph.num_edges() || !graph.num_vertices())\n     logstream(LOG_FATAL)<< \"Failed to load graph. Check your input path: \" << input_dir << std::endl;     \n\n\n\n  dc.cout()\n      << \"========== Graph statistics on proc \" << dc.procid()\n      << \" ===============\"\n      << \"\\n Num vertices: \" << graph.num_vertices()\n      << \"\\n Num edges: \" << graph.num_edges()\n      << \"\\n Num replica: \" << graph.num_replicas()\n      << \"\\n Replica to vertex ratio: \"\n      << float(graph.num_replicas())/graph.num_vertices()\n      << \"\\n --------------------------------------------\"\n      << \"\\n Num local own vertices: \" << graph.num_local_own_vertices()\n      << \"\\n Num local vertices: \" << graph.num_local_vertices()\n      << \"\\n Replica to own ratio: \"\n      << (float)graph.num_local_vertices()/graph.num_local_own_vertices()\n      << \"\\n Num local edges: \" << graph.num_local_edges()\n      //<< \"\\n Begin edge id: \" << graph.global_eid(0)\n        << \"\\n Edge balance ratio: \"\n        << float(graph.num_local_edges())/graph.num_edges()\n        << std::endl;\n\n  dc.cout() << \"Creating engine\" << std::endl;\n\n\n  engine_type engine(dc, graph, clopts);\n  vec_type edge_count = graph.map_reduce_edges<vec_type>(count_edges);\n  dc.cout()<<\"Training edges: \" << edge_count[0] << \" validation edges: \" << edge_count[1] << std::endl;\n\n  graphlab::vertex_set left = graph.select(isuser_node);\n  graphlab::vertex_set right = ~left;\n  graph.transform_vertices(verify_rows, left);\n\n  engine.register_vertex_delta<vec_type>(VERTEX_DELTA_TASK_ID, vertex_delta);\n\n  dc.cout() << \"Running NMF\" << std::endl;\n\n  timer.start();\n  for (size_t i = 0;i < ITERATIONS; ++i) {\n    phase = PHASE1;\n    x1 = graph.map_reduce_vertices<vec_type>(pre_iter,right);\n    px = &x1;\n    dc.cout() <<\"x1 is: \" << x1 << std::endl;\n\n    engine.parfor_all_local_edges(nmf_function); //todo - only left\n    engine.parfor_all_local_vertices(sync_function); //todo - only left\n    engine.wait();\n\n    phase = PHASE2;\n\n    x2 = graph.map_reduce_vertices<vec_type>(pre_iter,left);\n    px = &x2;\n    dc.cout() <<\"x2 is: \" << x2 << std::endl;\n\n    engine.parfor_all_local_edges(nmf_function); //todo only right\n    engine.parfor_all_local_vertices(sync_function); //todo only right\n    engine.wait();\n   \n    double rmse = graph.map_reduce_edges<double>(extract_l2_error);\n    dc.cout() << \"RMSE = \" << sqrt(rmse / graph.num_edges()) << std::endl;\n \n  }\n\n\n\n\n  const double runtime = timer.current_time();\n  dc.cout() << \"----------------------------------------------------------\"\n            << std::endl\n            << \"Final Runtime (seconds):   \" << runtime;\n\n  // Compute the final training error -----------------------------------------\n  dc.cout() << \"Final error: \" << std::endl;\n\n\n  graphlab::mpi_tools::finalize();\n  return EXIT_SUCCESS;\n} // end of main\n\n\n\n", "meta": {"hexsha": "cb2b603104b7fbfad0a3c15d95955a3400a01b68", "size": 11697, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "toolkits/collaborative_filtering/warp_nmf.cpp", "max_stars_repo_name": "coreyp1/graphlab", "max_stars_repo_head_hexsha": "637be90021c5f83ab7833ca15c48e76039057969", "max_stars_repo_licenses": ["ECL-2.0", "Apache-2.0"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2017-11-19T11:46:55.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-08T22:45:55.000Z", "max_issues_repo_path": "toolkits/collaborative_filtering/warp_nmf.cpp", "max_issues_repo_name": "coreyp1/graphlab", "max_issues_repo_head_hexsha": "637be90021c5f83ab7833ca15c48e76039057969", "max_issues_repo_licenses": ["ECL-2.0", "Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "toolkits/collaborative_filtering/warp_nmf.cpp", "max_forks_repo_name": "coreyp1/graphlab", "max_forks_repo_head_hexsha": "637be90021c5f83ab7833ca15c48e76039057969", "max_forks_repo_licenses": ["ECL-2.0", "Apache-2.0"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2015-12-15T12:12:23.000Z", "max_forks_repo_forks_event_max_datetime": "2019-10-16T16:48:40.000Z", "avg_line_length": 31.4435483871, "max_line_length": 142, "alphanum_fraction": 0.6493117893, "num_tokens": 2968, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.640635854839898, "lm_q2_score": 0.5, "lm_q1q2_score": 0.320317927419949}}
{"text": "/**\n * @author Andre Anjos <andre.anjos@idiap.ch>\n * @date Sun  4 Mar 10:02:45 2012 CET\n *\n * @brief Implementation of the SVM training methods\n *\n * Copyright (C) 2011-2014 Idiap Research Institute, Martigny, Switzerland\n */\n\n#include <bob.learn.libsvm/trainer.h>\n#include <boost/format.hpp>\n#include <boost/make_shared.hpp>\n#include <bob.core/logging.h>\n\n#ifdef BOB_DEBUG\n//remove newline\n#include <boost/algorithm/string/trim.hpp>\nstatic std::string strip(const char* s) {\n  std::string t(s);\n  boost::algorithm::trim(t);\n  return t;\n}\n#endif\n\nstatic void debug_libsvm(const char* s) {\n  TDEBUG1(\"[libsvm-\" << LIBSVM_VERSION << \"] \" << strip(s));\n}\n\nbob::learn::libsvm::Trainer::Trainer(\n    bob::learn::libsvm::machine_t machine_type,\n    bob::learn::libsvm::kernel_t kernel_type,\n    double cache_size,\n    double eps,\n    bool shrinking,\n    bool probability\n    )\n{\n  m_param.svm_type = machine_type;\n  m_param.kernel_type = kernel_type;\n  m_param.degree = 3;\n  m_param.gamma = 0.;\n  m_param.coef0 = 0.;\n  m_param.cache_size = cache_size;\n  m_param.eps = eps;\n  m_param.C = 1;\n  m_param.nu = 0.5;\n  m_param.p = 0.1;\n  m_param.shrinking = shrinking;\n  m_param.probability = probability;\n\n  //extracted from the data\n  m_param.nr_weight = 0;\n  m_param.weight_label = 0;\n  m_param.weight = 0;\n}\n\nbob::learn::libsvm::Trainer::~Trainer() { }\n\n/**\n * Erases an SVM problem:\n *\n * struct svm_problem {\n *   int l; //number of entries\n *   double* y; //labels\n *   svm_node** x; //each set terminated with a -1 index entry\n * };\n *\n * At svm-train the nodes for each entry are allocated globally, what is\n * probably more efficient from the allocation perspective. It still requires\n * libsvm to scan the data twice to understand how many nodes need to be\n * allocated globally.\n */\nstatic void delete_problem(svm_problem* p) {\n  delete[] p->y; //all labels\n  delete[] p->x[0]; //all entries\n  delete[] p->x; //entry pointers\n  delete p;\n}\n\n/**\n * Allocates an svm_problem matrix\n */\nstatic svm_problem* new_problem(size_t entries) {\n  svm_problem* retval = new svm_problem;\n  retval->l = (int)entries;\n  retval->y = new double[entries];\n  typedef svm_node* svm_node_ptr;\n  retval->x = new svm_node_ptr[entries];\n  for (size_t k=0; k<entries; ++k) retval->x[k] = 0;\n  return retval;\n}\n\n/**\n * Converts the input arrayset data into an svm_problem matrix, used by libsvm\n * training routines. Updates \"gamma\" at the svm_parameter's.\n */\nstatic boost::shared_ptr<svm_problem> data2problem\n(const std::vector<blitz::Array<double, 2> >& data,\n const blitz::Array<double,1>& sub, const blitz::Array<double,1>& div,\n svm_parameter& param) {\n\n  //counts the number of samples required\n  size_t entries = 0;\n  for (size_t k=0; k<data.size(); ++k)\n    entries += data[k].extent(blitz::firstDim);\n\n  //allocates the container that will represent the problem; at this stage, we\n  //allocate entries for each vector, but not the space in which feature will\n  //be put at. This will come next.\n  boost::shared_ptr<svm_problem> problem(new_problem(entries),\n      std::ptr_fun(delete_problem));\n\n  //choose labels.\n  if(param.svm_type==ONE_CLASS)\n  {\n    if ((data.size() != 1)) {\n      boost::format m(\"Only support a singular entry for one class. Your are training ONE_CLASS svm classifier. You passed me a list of %d arraysets.\");\n      m % data.size();\n      throw std::runtime_error(m.str());\n    }\n  }\n  else {\n    if ((data.size() <= 1) | (data.size() > 16)) {\n      boost::format m(\"Only supports SVMs for binary or multi-class classification problems (up to 16 classes). You passed me a list of %d arraysets.\");\n      m % data.size();\n      throw std::runtime_error(m.str());\n    }\n  }\n\n  std::vector<double> labels;\n  labels.reserve(data.size());\n  if (data.size() == 1) {\n    //oc-svm only support one class. \n    labels.push_back(+1.);\n  }\n  else if (data.size() == 2) {\n    //keep libsvm ordering\n    labels.push_back(+1.);\n    labels.push_back(-1.);\n  }\n  else { //data.size() == 3, 4, ..., 16\n    for (size_t k=0; k<data.size(); ++k) labels.push_back(k+1);\n  }\n\n  //just count how many nodes we need; unfortunately we have no other choice\n  //than doing a 2-pass instantiation here as libsvm has a very weird way to\n  //optimize data access in which it requires all nodes to be allocated in a\n  //single shot.\n  size_t nodes = 0; //total number of nodes to be allocated\n  blitz::Range all=blitz::Range::all();\n  int n_features = data[0].extent(blitz::secondDim);\n  blitz::Array<double,1> d(n_features); //for temporary feature manipulation\n\n  for (size_t k=0; k<data.size(); ++k) {\n    for (int i=0; i<data[k].extent(blitz::firstDim); ++i) {\n      d = (data[k](i,all)-sub)/div; //eval and copy in 1 instruction\n      for (int p=0; p<d.extent(blitz::firstDim); ++p) {\n        if (d(p)) {\n          ++nodes;\n        }\n      }\n      ++nodes; //one extra for the termination node \"index == -1\"\n    }\n  }\n\n  //allocates all the nodes, set first entry, a la libsvm\n  svm_node* all_nodes = new svm_node[nodes];\n\n  //iterates over each class data and fills the svm_node's\n  int max_index = 0; //data width\n  size_t sample = 0; //sample counter\n  size_t node = 0; //node counter\n\n  for (size_t k=0; k<data.size(); ++k) {\n    for (int i=0; i<data[k].extent(blitz::firstDim); ++i) {\n      problem->x[sample] = &all_nodes[node]; //setup current sample base pointer\n      d = (data[k](i,all)-sub)/div; //eval and copy in 1 instruction\n      for (blitz::sizeType p=0; p<d.size(); ++p) {\n        if (d(p)) {\n          int index = p+1; //starts indexing at 1\n          all_nodes[node].index = index;\n          all_nodes[node].value = d(p);\n          if ( index > max_index ) max_index = index;\n          ++node; //index within the current sample\n        }\n      }\n      //marks end of sequence\n      all_nodes[node].index = -1;\n      all_nodes[node].value = 0;\n      problem->y[sample] = labels[k];\n      ++node;\n      ++sample;\n    }\n  }\n\n  //extracted from svm-train.c\n  if (param.gamma == 0. && max_index > 0) {\n    param.gamma = 1.0/max_index;\n  }\n\n  //do not support pre-computed kernels...\n  if (param.kernel_type == PRECOMPUTED) {\n    throw std::runtime_error(\"We currently dod not support PRECOMPUTED kernels in these bindings to libsvm\");\n  }\n\n  return problem;\n}\n\n/**\n * A wrapper, to standardize the freeing of the svm_model\n */\nstatic void svm_model_free(svm_model*& m) {\n#if LIBSVM_VERSION >= 300\n  svm_free_and_destroy_model(&m);\n#else\n  svm_destroy_model(m);\n#endif\n}\n\nbob::learn::libsvm::Machine* bob::learn::libsvm::Trainer::train\n(const std::vector<blitz::Array<double, 2> >& data,\n const blitz::Array<double,1>& input_subtraction,\n const blitz::Array<double,1>& input_division) const {\n\n  //sanity check of input arraysets\n  int n_features = data[0].extent(blitz::secondDim);\n\n  for (size_t cl=0; cl<data.size(); ++cl) {\n    if (data[cl].extent(blitz::secondDim) != n_features) {\n      boost::format m(\"number of features (columns) of array for class %u (%d) does not match that of array for class 0 (%d)\");\n      m % cl % data[cl].extent(blitz::secondDim) % n_features;\n      throw std::runtime_error(m.str());\n    }\n  }\n\n  //converts the input arraysets into something libsvm can digest\n  double save_gamma = m_param.gamma; ///< the next method may update it!\n  boost::shared_ptr<svm_problem> problem =\n    data2problem(data, input_subtraction, input_division,\n        const_cast<svm_parameter&>(m_param) ///< temporary cast\n        );\n\n  //checks parametrization to make sure all is alright.\n  const char* error_msg = svm_check_parameter(problem.get(), &m_param);\n\n  if (error_msg) {\n    const_cast<double&>(m_param.gamma) = save_gamma;\n    boost::format m(\"libsvm-%d reports: %s\");\n    m % libsvm_version % error_msg;\n    std::runtime_error(m.str());\n  }\n\n  //do the training, returns the new machine\n#if LIBSVM_VERSION >= 291\n  svm_set_print_string_function(debug_libsvm);\n#else\n  boost::format m(\"libsvm-%d does not support debugging stream setting\");\n  m % libsvm_version;\n  debug_libsvm(m.str().c_str());\n#endif\n  boost::shared_ptr<svm_model> model(svm_train(problem.get(), &m_param),\n      std::ptr_fun(svm_model_free));\n\n  const_cast<double&>(m_param.gamma) = save_gamma;\n\n  //save newly created machine to file, reload from there to get rid of memory\n  //dependencies due to the poorly implemented memory model in libsvm\n  boost::shared_ptr<svm_model> new_model =\n    bob::learn::libsvm::svm_unpickle(bob::learn::libsvm::svm_pickle(model));\n\n  auto retval = new bob::learn::libsvm::Machine(new_model);\n\n  //sets up the scaling parameters given as input\n  retval->setInputSubtraction(input_subtraction);\n  retval->setInputDivision(input_division);\n\n  return retval;\n}\n\nbob::learn::libsvm::Machine* bob::learn::libsvm::Trainer::train\n(const std::vector<blitz::Array<double,2> >& data) const {\n  int n_features = data[0].extent(blitz::secondDim);\n\n  blitz::Array<double,1> sub(n_features);\n  sub = 0.;\n  blitz::Array<double,1> div(n_features);\n  div = 1.;\n  return train(data, sub, div);\n}\n\n", "meta": {"hexsha": "9450289233cfc793aa3f5830048eea75e0cbd82c", "size": 9001, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "bob/learn/libsvm/cpp/trainer.cpp", "max_stars_repo_name": "bioidiap/bob.learn.libsvm", "max_stars_repo_head_hexsha": "5b67e87b865904e48131e8ca543d684f3e4cd378", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2016-03-09T05:53:19.000Z", "max_stars_repo_stars_event_max_datetime": "2016-03-09T05:53:19.000Z", "max_issues_repo_path": "bob/learn/libsvm/cpp/trainer.cpp", "max_issues_repo_name": "bioidiap/bob.learn.libsvm", "max_issues_repo_head_hexsha": "5b67e87b865904e48131e8ca543d684f3e4cd378", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 8.0, "max_issues_repo_issues_event_min_datetime": "2015-02-17T12:10:40.000Z", "max_issues_repo_issues_event_max_datetime": "2016-05-31T16:28:00.000Z", "max_forks_repo_path": "bob/learn/libsvm/cpp/trainer.cpp", "max_forks_repo_name": "bioidiap/bob.learn.libsvm", "max_forks_repo_head_hexsha": "5b67e87b865904e48131e8ca543d684f3e4cd378", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2015-11-10T14:27:14.000Z", "max_forks_repo_forks_event_max_datetime": "2016-05-31T14:31:00.000Z", "avg_line_length": 30.9312714777, "max_line_length": 152, "alphanum_fraction": 0.6650372181, "num_tokens": 2530, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5583269943353745, "lm_q2_score": 0.5736784074525098, "lm_q1q2_score": 0.3203001409480641}}
{"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 <ThermalOperator.hh>\n#include <instantiation.hh>\n\n#include <deal.II/base/index_set.h>\n#include <deal.II/grid/filtered_iterator.h>\n#include <deal.II/matrix_free/fe_evaluation.h>\n\nnamespace adamantine\n{\n\ntemplate <int dim, int fe_degree, typename MemorySpaceType>\nThermalOperator<dim, fe_degree, MemorySpaceType>::ThermalOperator(\n    MPI_Comm const &communicator,\n    std::shared_ptr<MaterialProperty<dim>> material_properties)\n    : _communicator(communicator), _material_properties(material_properties),\n      _inverse_mass_matrix(\n          new dealii::LA::distributed::Vector<double, MemorySpaceType>())\n{\n  _matrix_free_data.tasks_parallel_scheme =\n      dealii::MatrixFree<dim, double>::AdditionalData::partition_color;\n  _matrix_free_data.mapping_update_flags = dealii::update_gradients |\n                                           dealii::update_JxW_values |\n                                           dealii::update_quadrature_points;\n}\n\ntemplate <int dim, int fe_degree, typename MemorySpaceType>\nvoid ThermalOperator<dim, fe_degree, MemorySpaceType>::reinit(\n    dealii::DoFHandler<dim> const &dof_handler,\n    dealii::AffineConstraints<double> const &affine_constraints,\n    dealii::QGaussLobatto<1> const &quad)\n{\n  _matrix_free.reinit(dof_handler, affine_constraints, quad, _matrix_free_data);\n}\n\ntemplate <int dim, int fe_degree, typename MemorySpaceType>\nvoid ThermalOperator<dim, fe_degree, MemorySpaceType>::reinit(\n    dealii::DoFHandler<dim> const &dof_handler,\n    dealii::AffineConstraints<double> const &affine_constraints,\n    dealii::QGauss<1> const &quad)\n{\n  _matrix_free.reinit(dof_handler, affine_constraints, quad, _matrix_free_data);\n}\n\ntemplate <int dim, int fe_degree, typename MemorySpaceType>\nvoid ThermalOperator<dim, fe_degree, MemorySpaceType>::\n    compute_inverse_mass_matrix(\n        dealii::DoFHandler<dim> const &dof_handler,\n        dealii::AffineConstraints<double> const &affine_constraints)\n{\n  // Compute the inverse of the mass matrix\n  dealii::QGaussLobatto<1> mass_matrix_quad(fe_degree + 1);\n  dealii::MatrixFree<dim, double> mass_matrix_free;\n  typename dealii::MatrixFree<dim, double>::AdditionalData mf_data;\n  mf_data.tasks_parallel_scheme =\n      dealii::MatrixFree<dim, double>::AdditionalData::partition_color;\n  mf_data.mapping_update_flags = dealii::update_values |\n                                 dealii::update_JxW_values |\n                                 dealii::update_quadrature_points;\n\n  mass_matrix_free.reinit(dof_handler, affine_constraints, mass_matrix_quad,\n                          mf_data);\n  mass_matrix_free.initialize_dof_vector(*_inverse_mass_matrix);\n  dealii::VectorizedArray<double> one =\n      dealii::make_vectorized_array(static_cast<double>(1.));\n  dealii::FEEvaluation<dim, fe_degree, fe_degree + 1, 1, double> fe_eval(\n      mass_matrix_free);\n  unsigned int const n_q_points = fe_eval.n_q_points;\n  for (unsigned int cell = 0; cell < mass_matrix_free.n_macro_cells(); ++cell)\n  {\n    fe_eval.reinit(cell);\n    for (unsigned int q = 0; q < n_q_points; ++q)\n      fe_eval.submit_value(one, q);\n    fe_eval.integrate(true, false);\n    fe_eval.distribute_local_to_global(*_inverse_mass_matrix);\n  }\n  _inverse_mass_matrix->compress(dealii::VectorOperation::add);\n  unsigned int const local_size = _inverse_mass_matrix->local_size();\n  for (unsigned int k = 0; k < local_size; ++k)\n  {\n    if (_inverse_mass_matrix->local_element(k) > 1e-15)\n      _inverse_mass_matrix->local_element(k) =\n          1. / _inverse_mass_matrix->local_element(k);\n    else\n      _inverse_mass_matrix->local_element(k) = 0.;\n  }\n}\n\ntemplate <int dim, int fe_degree, typename MemorySpaceType>\nvoid ThermalOperator<dim, fe_degree, MemorySpaceType>::clear()\n{\n  _matrix_free.clear();\n  _inverse_mass_matrix->reinit(0);\n}\n\ntemplate <int dim, int fe_degree, typename MemorySpaceType>\nvoid ThermalOperator<dim, fe_degree, MemorySpaceType>::vmult(\n    dealii::LA::distributed::Vector<double, MemorySpaceType> &dst,\n    dealii::LA::distributed::Vector<double, MemorySpaceType> const &src) const\n{\n  dst = 0.;\n  vmult_add(dst, src);\n}\n\ntemplate <int dim, int fe_degree, typename MemorySpaceType>\nvoid ThermalOperator<dim, fe_degree, MemorySpaceType>::Tvmult(\n    dealii::LA::distributed::Vector<double, MemorySpaceType> &dst,\n    dealii::LA::distributed::Vector<double, MemorySpaceType> const &src) const\n{\n  dst = 0.;\n  Tvmult_add(dst, src);\n}\n\ntemplate <int dim, int fe_degree, typename MemorySpaceType>\nvoid ThermalOperator<dim, fe_degree, MemorySpaceType>::vmult_add(\n    dealii::LA::distributed::Vector<double, MemorySpaceType> &dst,\n    dealii::LA::distributed::Vector<double, MemorySpaceType> const &src) const\n{\n  // Execute the matrix-free matrix-vector multiplication\n  _matrix_free.cell_loop(&ThermalOperator::local_apply, this, dst, src);\n\n  // Because cell_loop resolves the constraints, the constrained dofs are not\n  // called they stay at zero. Thus, we need to force the value on the\n  // constrained dofs by hand. The variable scaling is used so that we get the\n  // right order of magnitude.\n  // TODO: for now the value of scaling is set to 1\n  double const scaling = 1.;\n  std::vector<unsigned int> const &constrained_dofs =\n      _matrix_free.get_constrained_dofs();\n  for (auto &dof : constrained_dofs)\n    dst.local_element(dof) += scaling * src.local_element(dof);\n}\n\ntemplate <int dim, int fe_degree, typename MemorySpaceType>\nvoid ThermalOperator<dim, fe_degree, MemorySpaceType>::Tvmult_add(\n    dealii::LA::distributed::Vector<double, MemorySpaceType> &dst,\n    dealii::LA::distributed::Vector<double, MemorySpaceType> const &src) const\n{\n  // The system of equation is symmetric so we can use vmult_add\n  vmult_add(dst, src);\n}\n\ntemplate <int dim, int fe_degree, typename MemorySpaceType>\nvoid ThermalOperator<dim, fe_degree, MemorySpaceType>::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  dealii::FEEvaluation<dim, fe_degree, fe_degree + 1, 1, double> fe_eval(data);\n  dealii::Tensor<1, dim> unit_tensor;\n  for (unsigned int i = 0; i < dim; ++i)\n    unit_tensor[i] = 1.;\n\n  // Loop over the \"cells\". Note that we don't really work on a cell but on a\n  // set of quadrature point.\n  for (unsigned int cell = cell_range.first; cell < cell_range.second; ++cell)\n  {\n    // Reinit fe_eval on the current cell\n    fe_eval.reinit(cell);\n    // Store in a local vector the local values of src\n    fe_eval.read_dof_values(src);\n    // Evaluate only the function gradients on the reference cell\n    fe_eval.evaluate(false, true);\n    // Apply the Jacobian of the transformation, multiply by the variable\n    // coefficients and the quadrature points\n    for (unsigned int q = 0; q < fe_eval.n_q_points; ++q)\n      fe_eval.submit_gradient(-_inv_rho_cp(cell, q) *\n                                  _thermal_conductivity(cell, q) *\n                                  fe_eval.get_gradient(q),\n                              q);\n    // Sum over the quadrature points.\n    fe_eval.integrate(false, true);\n    fe_eval.distribute_local_to_global(dst);\n  }\n}\n\ntemplate <int dim, int fe_degree, typename MemorySpaceType>\nvoid ThermalOperator<dim, fe_degree, MemorySpaceType>::\n    evaluate_material_properties(\n        dealii::LA::distributed::Vector<double, dealii::MemorySpace::Host> const\n            &temperature)\n{\n  // Update the state of the materials\n  _material_properties->update(_matrix_free.get_dof_handler(), temperature);\n\n  unsigned int const n_cells = _matrix_free.n_macro_cells();\n  dealii::FEEvaluation<dim, fe_degree, fe_degree + 1, 1, double> fe_eval(\n      _matrix_free);\n  _inv_rho_cp.reinit(n_cells, fe_eval.n_q_points);\n  _thermal_conductivity.reinit(n_cells, fe_eval.n_q_points);\n  for (unsigned int cell = 0; cell < n_cells; ++cell)\n    for (unsigned int q = 0; q < fe_eval.n_q_points; ++q)\n      for (unsigned int i = 0; i < _matrix_free.n_components_filled(cell); ++i)\n      {\n        typename dealii::DoFHandler<dim>::cell_iterator cell_it =\n            _matrix_free.get_cell_iterator(cell, i);\n        // Cast to Triangulation<dim>::cell_iterator to access the material_id\n        typename dealii::Triangulation<dim>::active_cell_iterator cell_tria(\n            cell_it);\n\n        _thermal_conductivity(cell, q)[i] = _material_properties->get(\n            cell_tria, StateProperty::thermal_conductivity);\n\n        _inv_rho_cp(cell, q)[i] =\n            1. / (_material_properties->get(cell_tria, StateProperty::density) *\n                  _material_properties->get(cell_tria,\n                                            StateProperty::specific_heat));\n        _cell_it_to_mf_cell_map[cell_it] = std::make_pair(cell, i);\n      }\n}\n} // namespace adamantine\n\nINSTANTIATE_DIM_FEDEGREE_HOST(TUPLE(ThermalOperator))\n", "meta": {"hexsha": "a3a2f8f0443ed828794dbc87861bffe77c1e7d96", "size": 9220, "ext": "cc", "lang": "C++", "max_stars_repo_path": "source/ThermalOperator.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/ThermalOperator.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/ThermalOperator.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": 41.7194570136, "max_line_length": 80, "alphanum_fraction": 0.7132321041, "num_tokens": 2297, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7185943925708561, "lm_q2_score": 0.44552953503957266, "lm_q1q2_score": 0.32015502560413767}}
{"text": "//Copyright (c) 2008-2016 Emil Dotchevski and Reverge Studios, Inc.\r\n\r\n//Distributed under the Boost Software License, Version 1.0. (See accompanying\r\n//file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\r\n\r\n#ifndef BOOST_QVM_2923BE84E16CD6AE529049F1F1BBE9EB\r\n#define BOOST_QVM_2923BE84E16CD6AE529049F1F1BBE9EB\r\n\r\n//This file was generated by a program. Do not edit manually.\r\n\r\n#include <boost/qvm/assert.hpp>\r\n#include <boost/qvm/deduce_mat.hpp>\r\n#include <boost/qvm/deduce_vec.hpp>\r\n#include <boost/qvm/enable_if.hpp>\r\n#include <boost/qvm/error.hpp>\r\n#include <boost/qvm/inline.hpp>\r\n#include <boost/qvm/mat_traits.hpp>\r\n#include <boost/qvm/throw_exception.hpp>\r\n\r\nnamespace\r\nboost\r\n    {\r\n    namespace\r\n    qvm\r\n        {\r\n        template <class A,class B>\r\n        BOOST_QVM_INLINE_OPERATIONS\r\n        typename lazy_enable_if_c<\r\n            mat_traits<A>::rows==2 && mat_traits<B>::rows==2 &&\r\n            mat_traits<A>::cols==2 && mat_traits<B>::cols==2,\r\n            deduce_mat2<A,B,2,2> >::type\r\n        operator+( A const & a, B const & b )\r\n            {\r\n            typedef typename deduce_mat2<A,B,2,2>::type R;\r\n            BOOST_QVM_STATIC_ASSERT(mat_traits<R>::rows==2);\r\n            BOOST_QVM_STATIC_ASSERT(mat_traits<R>::cols==2);\r\n            R r;\r\n            mat_traits<R>::template write_element<0,0>(r)=mat_traits<A>::template read_element<0,0>(a)+mat_traits<B>::template read_element<0,0>(b);\r\n            mat_traits<R>::template write_element<0,1>(r)=mat_traits<A>::template read_element<0,1>(a)+mat_traits<B>::template read_element<0,1>(b);\r\n            mat_traits<R>::template write_element<1,0>(r)=mat_traits<A>::template read_element<1,0>(a)+mat_traits<B>::template read_element<1,0>(b);\r\n            mat_traits<R>::template write_element<1,1>(r)=mat_traits<A>::template read_element<1,1>(a)+mat_traits<B>::template read_element<1,1>(b);\r\n            return r;\r\n            }\r\n\r\n        namespace\r\n        sfinae\r\n            {\r\n            using ::boost::qvm::operator+;\r\n            }\r\n\r\n        namespace\r\n        qvm_detail\r\n            {\r\n            template <int R,int C>\r\n            struct plus_mm_defined;\r\n\r\n            template <>\r\n            struct\r\n            plus_mm_defined<2,2>\r\n                {\r\n                static bool const value=true;\r\n                };\r\n            }\r\n\r\n        template <class A,class B>\r\n        BOOST_QVM_INLINE_OPERATIONS\r\n        typename lazy_enable_if_c<\r\n            mat_traits<A>::rows==2 && mat_traits<B>::rows==2 &&\r\n            mat_traits<A>::cols==1 && mat_traits<B>::cols==1,\r\n            deduce_mat2<A,B,2,1> >::type\r\n        operator+( A const & a, B const & b )\r\n            {\r\n            typedef typename deduce_mat2<A,B,2,1>::type R;\r\n            BOOST_QVM_STATIC_ASSERT(mat_traits<R>::rows==2);\r\n            BOOST_QVM_STATIC_ASSERT(mat_traits<R>::cols==1);\r\n            R r;\r\n            mat_traits<R>::template write_element<0,0>(r)=mat_traits<A>::template read_element<0,0>(a)+mat_traits<B>::template read_element<0,0>(b);\r\n            mat_traits<R>::template write_element<1,0>(r)=mat_traits<A>::template read_element<1,0>(a)+mat_traits<B>::template read_element<1,0>(b);\r\n            return r;\r\n            }\r\n\r\n        namespace\r\n        sfinae\r\n            {\r\n            using ::boost::qvm::operator+;\r\n            }\r\n\r\n        namespace\r\n        qvm_detail\r\n            {\r\n            template <int R,int C>\r\n            struct plus_mm_defined;\r\n\r\n            template <>\r\n            struct\r\n            plus_mm_defined<2,1>\r\n                {\r\n                static bool const value=true;\r\n                };\r\n            }\r\n\r\n        template <class A,class B>\r\n        BOOST_QVM_INLINE_OPERATIONS\r\n        typename lazy_enable_if_c<\r\n            mat_traits<A>::rows==1 && mat_traits<B>::rows==1 &&\r\n            mat_traits<A>::cols==2 && mat_traits<B>::cols==2,\r\n            deduce_mat2<A,B,1,2> >::type\r\n        operator+( A const & a, B const & b )\r\n            {\r\n            typedef typename deduce_mat2<A,B,1,2>::type R;\r\n            BOOST_QVM_STATIC_ASSERT(mat_traits<R>::rows==1);\r\n            BOOST_QVM_STATIC_ASSERT(mat_traits<R>::cols==2);\r\n            R r;\r\n            mat_traits<R>::template write_element<0,0>(r)=mat_traits<A>::template read_element<0,0>(a)+mat_traits<B>::template read_element<0,0>(b);\r\n            mat_traits<R>::template write_element<0,1>(r)=mat_traits<A>::template read_element<0,1>(a)+mat_traits<B>::template read_element<0,1>(b);\r\n            return r;\r\n            }\r\n\r\n        namespace\r\n        sfinae\r\n            {\r\n            using ::boost::qvm::operator+;\r\n            }\r\n\r\n        namespace\r\n        qvm_detail\r\n            {\r\n            template <int R,int C>\r\n            struct plus_mm_defined;\r\n\r\n            template <>\r\n            struct\r\n            plus_mm_defined<1,2>\r\n                {\r\n                static bool const value=true;\r\n                };\r\n            }\r\n\r\n        template <class A,class B>\r\n        BOOST_QVM_INLINE_OPERATIONS\r\n        typename lazy_enable_if_c<\r\n            mat_traits<A>::rows==2 && mat_traits<B>::rows==2 &&\r\n            mat_traits<A>::cols==2 && mat_traits<B>::cols==2,\r\n            deduce_mat2<A,B,2,2> >::type\r\n        operator-( A const & a, B const & b )\r\n            {\r\n            typedef typename deduce_mat2<A,B,2,2>::type R;\r\n            BOOST_QVM_STATIC_ASSERT(mat_traits<R>::rows==2);\r\n            BOOST_QVM_STATIC_ASSERT(mat_traits<R>::cols==2);\r\n            R r;\r\n            mat_traits<R>::template write_element<0,0>(r)=mat_traits<A>::template read_element<0,0>(a)-mat_traits<B>::template read_element<0,0>(b);\r\n            mat_traits<R>::template write_element<0,1>(r)=mat_traits<A>::template read_element<0,1>(a)-mat_traits<B>::template read_element<0,1>(b);\r\n            mat_traits<R>::template write_element<1,0>(r)=mat_traits<A>::template read_element<1,0>(a)-mat_traits<B>::template read_element<1,0>(b);\r\n            mat_traits<R>::template write_element<1,1>(r)=mat_traits<A>::template read_element<1,1>(a)-mat_traits<B>::template read_element<1,1>(b);\r\n            return r;\r\n            }\r\n\r\n        namespace\r\n        sfinae\r\n            {\r\n            using ::boost::qvm::operator-;\r\n            }\r\n\r\n        namespace\r\n        qvm_detail\r\n            {\r\n            template <int R,int C>\r\n            struct minus_mm_defined;\r\n\r\n            template <>\r\n            struct\r\n            minus_mm_defined<2,2>\r\n                {\r\n                static bool const value=true;\r\n                };\r\n            }\r\n\r\n        template <class A,class B>\r\n        BOOST_QVM_INLINE_OPERATIONS\r\n        typename lazy_enable_if_c<\r\n            mat_traits<A>::rows==2 && mat_traits<B>::rows==2 &&\r\n            mat_traits<A>::cols==1 && mat_traits<B>::cols==1,\r\n            deduce_mat2<A,B,2,1> >::type\r\n        operator-( A const & a, B const & b )\r\n            {\r\n            typedef typename deduce_mat2<A,B,2,1>::type R;\r\n            BOOST_QVM_STATIC_ASSERT(mat_traits<R>::rows==2);\r\n            BOOST_QVM_STATIC_ASSERT(mat_traits<R>::cols==1);\r\n            R r;\r\n            mat_traits<R>::template write_element<0,0>(r)=mat_traits<A>::template read_element<0,0>(a)-mat_traits<B>::template read_element<0,0>(b);\r\n            mat_traits<R>::template write_element<1,0>(r)=mat_traits<A>::template read_element<1,0>(a)-mat_traits<B>::template read_element<1,0>(b);\r\n            return r;\r\n            }\r\n\r\n        namespace\r\n        sfinae\r\n            {\r\n            using ::boost::qvm::operator-;\r\n            }\r\n\r\n        namespace\r\n        qvm_detail\r\n            {\r\n            template <int R,int C>\r\n            struct minus_mm_defined;\r\n\r\n            template <>\r\n            struct\r\n            minus_mm_defined<2,1>\r\n                {\r\n                static bool const value=true;\r\n                };\r\n            }\r\n\r\n        template <class A,class B>\r\n        BOOST_QVM_INLINE_OPERATIONS\r\n        typename lazy_enable_if_c<\r\n            mat_traits<A>::rows==1 && mat_traits<B>::rows==1 &&\r\n            mat_traits<A>::cols==2 && mat_traits<B>::cols==2,\r\n            deduce_mat2<A,B,1,2> >::type\r\n        operator-( A const & a, B const & b )\r\n            {\r\n            typedef typename deduce_mat2<A,B,1,2>::type R;\r\n            BOOST_QVM_STATIC_ASSERT(mat_traits<R>::rows==1);\r\n            BOOST_QVM_STATIC_ASSERT(mat_traits<R>::cols==2);\r\n            R r;\r\n            mat_traits<R>::template write_element<0,0>(r)=mat_traits<A>::template read_element<0,0>(a)-mat_traits<B>::template read_element<0,0>(b);\r\n            mat_traits<R>::template write_element<0,1>(r)=mat_traits<A>::template read_element<0,1>(a)-mat_traits<B>::template read_element<0,1>(b);\r\n            return r;\r\n            }\r\n\r\n        namespace\r\n        sfinae\r\n            {\r\n            using ::boost::qvm::operator-;\r\n            }\r\n\r\n        namespace\r\n        qvm_detail\r\n            {\r\n            template <int R,int C>\r\n            struct minus_mm_defined;\r\n\r\n            template <>\r\n            struct\r\n            minus_mm_defined<1,2>\r\n                {\r\n                static bool const value=true;\r\n                };\r\n            }\r\n\r\n        template <class A,class B>\r\n        BOOST_QVM_INLINE_OPERATIONS\r\n        typename enable_if_c<\r\n            mat_traits<A>::rows==2 && mat_traits<B>::rows==2 &&\r\n            mat_traits<A>::cols==2 && mat_traits<B>::cols==2,\r\n            A &>::type\r\n        operator+=( A & a, B const & b )\r\n            {\r\n            mat_traits<A>::template write_element<0,0>(a)+=mat_traits<B>::template read_element<0,0>(b);\r\n            mat_traits<A>::template write_element<0,1>(a)+=mat_traits<B>::template read_element<0,1>(b);\r\n            mat_traits<A>::template write_element<1,0>(a)+=mat_traits<B>::template read_element<1,0>(b);\r\n            mat_traits<A>::template write_element<1,1>(a)+=mat_traits<B>::template read_element<1,1>(b);\r\n            return a;\r\n            }\r\n\r\n        namespace\r\n        sfinae\r\n            {\r\n            using ::boost::qvm::operator+=;\r\n            }\r\n\r\n        namespace\r\n        qvm_detail\r\n            {\r\n            template <int R,int C>\r\n            struct plus_eq_mm_defined;\r\n\r\n            template <>\r\n            struct\r\n            plus_eq_mm_defined<2,2>\r\n                {\r\n                static bool const value=true;\r\n                };\r\n            }\r\n\r\n        template <class A,class B>\r\n        BOOST_QVM_INLINE_OPERATIONS\r\n        typename enable_if_c<\r\n            mat_traits<A>::rows==2 && mat_traits<B>::rows==2 &&\r\n            mat_traits<A>::cols==1 && mat_traits<B>::cols==1,\r\n            A &>::type\r\n        operator+=( A & a, B const & b )\r\n            {\r\n            mat_traits<A>::template write_element<0,0>(a)+=mat_traits<B>::template read_element<0,0>(b);\r\n            mat_traits<A>::template write_element<1,0>(a)+=mat_traits<B>::template read_element<1,0>(b);\r\n            return a;\r\n            }\r\n\r\n        namespace\r\n        sfinae\r\n            {\r\n            using ::boost::qvm::operator+=;\r\n            }\r\n\r\n        namespace\r\n        qvm_detail\r\n            {\r\n            template <int R,int C>\r\n            struct plus_eq_mm_defined;\r\n\r\n            template <>\r\n            struct\r\n            plus_eq_mm_defined<2,1>\r\n                {\r\n                static bool const value=true;\r\n                };\r\n            }\r\n\r\n        template <class A,class B>\r\n        BOOST_QVM_INLINE_OPERATIONS\r\n        typename enable_if_c<\r\n            mat_traits<A>::rows==1 && mat_traits<B>::rows==1 &&\r\n            mat_traits<A>::cols==2 && mat_traits<B>::cols==2,\r\n            A &>::type\r\n        operator+=( A & a, B const & b )\r\n            {\r\n            mat_traits<A>::template write_element<0,0>(a)+=mat_traits<B>::template read_element<0,0>(b);\r\n            mat_traits<A>::template write_element<0,1>(a)+=mat_traits<B>::template read_element<0,1>(b);\r\n            return a;\r\n            }\r\n\r\n        namespace\r\n        sfinae\r\n            {\r\n            using ::boost::qvm::operator+=;\r\n            }\r\n\r\n        namespace\r\n        qvm_detail\r\n            {\r\n            template <int R,int C>\r\n            struct plus_eq_mm_defined;\r\n\r\n            template <>\r\n            struct\r\n            plus_eq_mm_defined<1,2>\r\n                {\r\n                static bool const value=true;\r\n                };\r\n            }\r\n\r\n        template <class A,class B>\r\n        BOOST_QVM_INLINE_OPERATIONS\r\n        typename enable_if_c<\r\n            mat_traits<A>::rows==2 && mat_traits<B>::rows==2 &&\r\n            mat_traits<A>::cols==2 && mat_traits<B>::cols==2,\r\n            A &>::type\r\n        operator-=( A & a, B const & b )\r\n            {\r\n            mat_traits<A>::template write_element<0,0>(a)-=mat_traits<B>::template read_element<0,0>(b);\r\n            mat_traits<A>::template write_element<0,1>(a)-=mat_traits<B>::template read_element<0,1>(b);\r\n            mat_traits<A>::template write_element<1,0>(a)-=mat_traits<B>::template read_element<1,0>(b);\r\n            mat_traits<A>::template write_element<1,1>(a)-=mat_traits<B>::template read_element<1,1>(b);\r\n            return a;\r\n            }\r\n\r\n        namespace\r\n        sfinae\r\n            {\r\n            using ::boost::qvm::operator-=;\r\n            }\r\n\r\n        namespace\r\n        qvm_detail\r\n            {\r\n            template <int R,int C>\r\n            struct minus_eq_mm_defined;\r\n\r\n            template <>\r\n            struct\r\n            minus_eq_mm_defined<2,2>\r\n                {\r\n                static bool const value=true;\r\n                };\r\n            }\r\n\r\n        template <class A,class B>\r\n        BOOST_QVM_INLINE_OPERATIONS\r\n        typename enable_if_c<\r\n            mat_traits<A>::rows==2 && mat_traits<B>::rows==2 &&\r\n            mat_traits<A>::cols==1 && mat_traits<B>::cols==1,\r\n            A &>::type\r\n        operator-=( A & a, B const & b )\r\n            {\r\n            mat_traits<A>::template write_element<0,0>(a)-=mat_traits<B>::template read_element<0,0>(b);\r\n            mat_traits<A>::template write_element<1,0>(a)-=mat_traits<B>::template read_element<1,0>(b);\r\n            return a;\r\n            }\r\n\r\n        namespace\r\n        sfinae\r\n            {\r\n            using ::boost::qvm::operator-=;\r\n            }\r\n\r\n        namespace\r\n        qvm_detail\r\n            {\r\n            template <int R,int C>\r\n            struct minus_eq_mm_defined;\r\n\r\n            template <>\r\n            struct\r\n            minus_eq_mm_defined<2,1>\r\n                {\r\n                static bool const value=true;\r\n                };\r\n            }\r\n\r\n        template <class A,class B>\r\n        BOOST_QVM_INLINE_OPERATIONS\r\n        typename enable_if_c<\r\n            mat_traits<A>::rows==1 && mat_traits<B>::rows==1 &&\r\n            mat_traits<A>::cols==2 && mat_traits<B>::cols==2,\r\n            A &>::type\r\n        operator-=( A & a, B const & b )\r\n            {\r\n            mat_traits<A>::template write_element<0,0>(a)-=mat_traits<B>::template read_element<0,0>(b);\r\n            mat_traits<A>::template write_element<0,1>(a)-=mat_traits<B>::template read_element<0,1>(b);\r\n            return a;\r\n            }\r\n\r\n        namespace\r\n        sfinae\r\n            {\r\n            using ::boost::qvm::operator-=;\r\n            }\r\n\r\n        namespace\r\n        qvm_detail\r\n            {\r\n            template <int R,int C>\r\n            struct minus_eq_mm_defined;\r\n\r\n            template <>\r\n            struct\r\n            minus_eq_mm_defined<1,2>\r\n                {\r\n                static bool const value=true;\r\n                };\r\n            }\r\n\r\n        template <class A,class B>\r\n        BOOST_QVM_INLINE_OPERATIONS\r\n        typename lazy_enable_if_c<\r\n            mat_traits<A>::rows==2 && mat_traits<A>::cols==2 && is_scalar<B>::value,\r\n            deduce_mat<A> >::type\r\n        operator*( A const & a, B b )\r\n            {\r\n            typedef typename deduce_mat<A>::type R;\r\n            R r;\r\n            mat_traits<R>::template write_element<0,0>(r)=mat_traits<A>::template read_element<0,0>(a)*b;\r\n            mat_traits<R>::template write_element<0,1>(r)=mat_traits<A>::template read_element<0,1>(a)*b;\r\n            mat_traits<R>::template write_element<1,0>(r)=mat_traits<A>::template read_element<1,0>(a)*b;\r\n            mat_traits<R>::template write_element<1,1>(r)=mat_traits<A>::template read_element<1,1>(a)*b;\r\n            return r;\r\n            }\r\n\r\n        namespace\r\n        sfinae\r\n            {\r\n            using ::boost::qvm::operator*;\r\n            }\r\n\r\n        namespace\r\n        qvm_detail\r\n            {\r\n            template <int R,int C>\r\n            struct mul_ms_defined;\r\n\r\n            template <>\r\n            struct\r\n            mul_ms_defined<2,2>\r\n                {\r\n                static bool const value=true;\r\n                };\r\n            }\r\n\r\n        template <class A,class B>\r\n        BOOST_QVM_INLINE_OPERATIONS\r\n        typename lazy_enable_if_c<\r\n            mat_traits<A>::rows==2 && mat_traits<A>::cols==1 && is_scalar<B>::value,\r\n            deduce_mat<A> >::type\r\n        operator*( A const & a, B b )\r\n            {\r\n            typedef typename deduce_mat<A>::type R;\r\n            R r;\r\n            mat_traits<R>::template write_element<0,0>(r)=mat_traits<A>::template read_element<0,0>(a)*b;\r\n            mat_traits<R>::template write_element<1,0>(r)=mat_traits<A>::template read_element<1,0>(a)*b;\r\n            return r;\r\n            }\r\n\r\n        namespace\r\n        sfinae\r\n            {\r\n            using ::boost::qvm::operator*;\r\n            }\r\n\r\n        namespace\r\n        qvm_detail\r\n            {\r\n            template <int R,int C>\r\n            struct mul_ms_defined;\r\n\r\n            template <>\r\n            struct\r\n            mul_ms_defined<2,1>\r\n                {\r\n                static bool const value=true;\r\n                };\r\n            }\r\n\r\n        template <class A,class B>\r\n        BOOST_QVM_INLINE_OPERATIONS\r\n        typename lazy_enable_if_c<\r\n            mat_traits<A>::rows==1 && mat_traits<A>::cols==2 && is_scalar<B>::value,\r\n            deduce_mat<A> >::type\r\n        operator*( A const & a, B b )\r\n            {\r\n            typedef typename deduce_mat<A>::type R;\r\n            R r;\r\n            mat_traits<R>::template write_element<0,0>(r)=mat_traits<A>::template read_element<0,0>(a)*b;\r\n            mat_traits<R>::template write_element<0,1>(r)=mat_traits<A>::template read_element<0,1>(a)*b;\r\n            return r;\r\n            }\r\n\r\n        namespace\r\n        sfinae\r\n            {\r\n            using ::boost::qvm::operator*;\r\n            }\r\n\r\n        namespace\r\n        qvm_detail\r\n            {\r\n            template <int R,int C>\r\n            struct mul_ms_defined;\r\n\r\n            template <>\r\n            struct\r\n            mul_ms_defined<1,2>\r\n                {\r\n                static bool const value=true;\r\n                };\r\n            }\r\n\r\n        template <class A,class B>\r\n        BOOST_QVM_INLINE_OPERATIONS\r\n        typename enable_if_c<\r\n            mat_traits<A>::rows==2 && mat_traits<A>::cols==2 && is_scalar<B>::value,\r\n            A &>::type\r\n        operator*=( A & a, B b )\r\n            {\r\n            mat_traits<A>::template write_element<0,0>(a)*=b;\r\n            mat_traits<A>::template write_element<0,1>(a)*=b;\r\n            mat_traits<A>::template write_element<1,0>(a)*=b;\r\n            mat_traits<A>::template write_element<1,1>(a)*=b;\r\n            return a;\r\n            }\r\n\r\n        namespace\r\n        sfinae\r\n            {\r\n            using ::boost::qvm::operator*=;\r\n            }\r\n\r\n        namespace\r\n        qvm_detail\r\n            {\r\n            template <int R,int C>\r\n            struct mul_eq_ms_defined;\r\n\r\n            template <>\r\n            struct\r\n            mul_eq_ms_defined<2,2>\r\n                {\r\n                static bool const value=true;\r\n                };\r\n            }\r\n\r\n        template <class A,class B>\r\n        BOOST_QVM_INLINE_OPERATIONS\r\n        typename enable_if_c<\r\n            mat_traits<A>::rows==2 && mat_traits<A>::cols==1 && is_scalar<B>::value,\r\n            A &>::type\r\n        operator*=( A & a, B b )\r\n            {\r\n            mat_traits<A>::template write_element<0,0>(a)*=b;\r\n            mat_traits<A>::template write_element<1,0>(a)*=b;\r\n            return a;\r\n            }\r\n\r\n        namespace\r\n        sfinae\r\n            {\r\n            using ::boost::qvm::operator*=;\r\n            }\r\n\r\n        namespace\r\n        qvm_detail\r\n            {\r\n            template <int R,int C>\r\n            struct mul_eq_ms_defined;\r\n\r\n            template <>\r\n            struct\r\n            mul_eq_ms_defined<2,1>\r\n                {\r\n                static bool const value=true;\r\n                };\r\n            }\r\n\r\n        template <class A,class B>\r\n        BOOST_QVM_INLINE_OPERATIONS\r\n        typename enable_if_c<\r\n            mat_traits<A>::rows==1 && mat_traits<A>::cols==2 && is_scalar<B>::value,\r\n            A &>::type\r\n        operator*=( A & a, B b )\r\n            {\r\n            mat_traits<A>::template write_element<0,0>(a)*=b;\r\n            mat_traits<A>::template write_element<0,1>(a)*=b;\r\n            return a;\r\n            }\r\n\r\n        namespace\r\n        sfinae\r\n            {\r\n            using ::boost::qvm::operator*=;\r\n            }\r\n\r\n        namespace\r\n        qvm_detail\r\n            {\r\n            template <int R,int C>\r\n            struct mul_eq_ms_defined;\r\n\r\n            template <>\r\n            struct\r\n            mul_eq_ms_defined<1,2>\r\n                {\r\n                static bool const value=true;\r\n                };\r\n            }\r\n\r\n        template <class A,class B>\r\n        BOOST_QVM_INLINE_OPERATIONS\r\n        typename lazy_enable_if_c<\r\n            mat_traits<A>::rows==2 && mat_traits<A>::cols==2 && is_scalar<B>::value,\r\n            deduce_mat<A> >::type\r\n        operator/( A const & a, B b )\r\n            {\r\n            typedef typename deduce_mat<A>::type R;\r\n            R r;\r\n            mat_traits<R>::template write_element<0,0>(r)=mat_traits<A>::template read_element<0,0>(a)/b;\r\n            mat_traits<R>::template write_element<0,1>(r)=mat_traits<A>::template read_element<0,1>(a)/b;\r\n            mat_traits<R>::template write_element<1,0>(r)=mat_traits<A>::template read_element<1,0>(a)/b;\r\n            mat_traits<R>::template write_element<1,1>(r)=mat_traits<A>::template read_element<1,1>(a)/b;\r\n            return r;\r\n            }\r\n\r\n        namespace\r\n        sfinae\r\n            {\r\n            using ::boost::qvm::operator/;\r\n            }\r\n\r\n        namespace\r\n        qvm_detail\r\n            {\r\n            template <int R,int C>\r\n            struct div_ms_defined;\r\n\r\n            template <>\r\n            struct\r\n            div_ms_defined<2,2>\r\n                {\r\n                static bool const value=true;\r\n                };\r\n            }\r\n\r\n        template <class A,class B>\r\n        BOOST_QVM_INLINE_OPERATIONS\r\n        typename lazy_enable_if_c<\r\n            mat_traits<A>::rows==2 && mat_traits<A>::cols==1 && is_scalar<B>::value,\r\n            deduce_mat<A> >::type\r\n        operator/( A const & a, B b )\r\n            {\r\n            typedef typename deduce_mat<A>::type R;\r\n            R r;\r\n            mat_traits<R>::template write_element<0,0>(r)=mat_traits<A>::template read_element<0,0>(a)/b;\r\n            mat_traits<R>::template write_element<1,0>(r)=mat_traits<A>::template read_element<1,0>(a)/b;\r\n            return r;\r\n            }\r\n\r\n        namespace\r\n        sfinae\r\n            {\r\n            using ::boost::qvm::operator/;\r\n            }\r\n\r\n        namespace\r\n        qvm_detail\r\n            {\r\n            template <int R,int C>\r\n            struct div_ms_defined;\r\n\r\n            template <>\r\n            struct\r\n            div_ms_defined<2,1>\r\n                {\r\n                static bool const value=true;\r\n                };\r\n            }\r\n\r\n        template <class A,class B>\r\n        BOOST_QVM_INLINE_OPERATIONS\r\n        typename lazy_enable_if_c<\r\n            mat_traits<A>::rows==1 && mat_traits<A>::cols==2 && is_scalar<B>::value,\r\n            deduce_mat<A> >::type\r\n        operator/( A const & a, B b )\r\n            {\r\n            typedef typename deduce_mat<A>::type R;\r\n            R r;\r\n            mat_traits<R>::template write_element<0,0>(r)=mat_traits<A>::template read_element<0,0>(a)/b;\r\n            mat_traits<R>::template write_element<0,1>(r)=mat_traits<A>::template read_element<0,1>(a)/b;\r\n            return r;\r\n            }\r\n\r\n        namespace\r\n        sfinae\r\n            {\r\n            using ::boost::qvm::operator/;\r\n            }\r\n\r\n        namespace\r\n        qvm_detail\r\n            {\r\n            template <int R,int C>\r\n            struct div_ms_defined;\r\n\r\n            template <>\r\n            struct\r\n            div_ms_defined<1,2>\r\n                {\r\n                static bool const value=true;\r\n                };\r\n            }\r\n\r\n        template <class A,class B>\r\n        BOOST_QVM_INLINE_OPERATIONS\r\n        typename enable_if_c<\r\n            mat_traits<A>::rows==2 && mat_traits<A>::cols==2 && is_scalar<B>::value,\r\n            A &>::type\r\n        operator/=( A & a, B b )\r\n            {\r\n            mat_traits<A>::template write_element<0,0>(a)/=b;\r\n            mat_traits<A>::template write_element<0,1>(a)/=b;\r\n            mat_traits<A>::template write_element<1,0>(a)/=b;\r\n            mat_traits<A>::template write_element<1,1>(a)/=b;\r\n            return a;\r\n            }\r\n\r\n        namespace\r\n        sfinae\r\n            {\r\n            using ::boost::qvm::operator/=;\r\n            }\r\n\r\n        namespace\r\n        qvm_detail\r\n            {\r\n            template <int R,int C>\r\n            struct div_eq_ms_defined;\r\n\r\n            template <>\r\n            struct\r\n            div_eq_ms_defined<2,2>\r\n                {\r\n                static bool const value=true;\r\n                };\r\n            }\r\n\r\n        template <class A,class B>\r\n        BOOST_QVM_INLINE_OPERATIONS\r\n        typename enable_if_c<\r\n            mat_traits<A>::rows==2 && mat_traits<A>::cols==1 && is_scalar<B>::value,\r\n            A &>::type\r\n        operator/=( A & a, B b )\r\n            {\r\n            mat_traits<A>::template write_element<0,0>(a)/=b;\r\n            mat_traits<A>::template write_element<1,0>(a)/=b;\r\n            return a;\r\n            }\r\n\r\n        namespace\r\n        sfinae\r\n            {\r\n            using ::boost::qvm::operator/=;\r\n            }\r\n\r\n        namespace\r\n        qvm_detail\r\n            {\r\n            template <int R,int C>\r\n            struct div_eq_ms_defined;\r\n\r\n            template <>\r\n            struct\r\n            div_eq_ms_defined<2,1>\r\n                {\r\n                static bool const value=true;\r\n                };\r\n            }\r\n\r\n        template <class A,class B>\r\n        BOOST_QVM_INLINE_OPERATIONS\r\n        typename enable_if_c<\r\n            mat_traits<A>::rows==1 && mat_traits<A>::cols==2 && is_scalar<B>::value,\r\n            A &>::type\r\n        operator/=( A & a, B b )\r\n            {\r\n            mat_traits<A>::template write_element<0,0>(a)/=b;\r\n            mat_traits<A>::template write_element<0,1>(a)/=b;\r\n            return a;\r\n            }\r\n\r\n        namespace\r\n        sfinae\r\n            {\r\n            using ::boost::qvm::operator/=;\r\n            }\r\n\r\n        namespace\r\n        qvm_detail\r\n            {\r\n            template <int R,int C>\r\n            struct div_eq_ms_defined;\r\n\r\n            template <>\r\n            struct\r\n            div_eq_ms_defined<1,2>\r\n                {\r\n                static bool const value=true;\r\n                };\r\n            }\r\n\r\n        template <class A,class B>\r\n        BOOST_QVM_INLINE_OPERATIONS\r\n        typename enable_if_c<\r\n            mat_traits<A>::rows==2 && mat_traits<B>::rows==2 &&\r\n            mat_traits<A>::cols==2 && mat_traits<B>::cols==2,\r\n            A &>::type\r\n        assign( A & a, B const & b )\r\n            {\r\n            mat_traits<A>::template write_element<0,0>(a)=mat_traits<B>::template read_element<0,0>(b);\r\n            mat_traits<A>::template write_element<0,1>(a)=mat_traits<B>::template read_element<0,1>(b);\r\n            mat_traits<A>::template write_element<1,0>(a)=mat_traits<B>::template read_element<1,0>(b);\r\n            mat_traits<A>::template write_element<1,1>(a)=mat_traits<B>::template read_element<1,1>(b);\r\n            return a;\r\n            }\r\n\r\n        namespace\r\n        sfinae\r\n            {\r\n            using ::boost::qvm::assign;\r\n            }\r\n\r\n        namespace\r\n        qvm_detail\r\n            {\r\n            template <int R,int C>\r\n            struct assign_mm_defined;\r\n\r\n            template <>\r\n            struct\r\n            assign_mm_defined<2,2>\r\n                {\r\n                static bool const value=true;\r\n                };\r\n            }\r\n\r\n        template <class A,class B>\r\n        BOOST_QVM_INLINE_OPERATIONS\r\n        typename enable_if_c<\r\n            mat_traits<A>::rows==2 && mat_traits<B>::rows==2 &&\r\n            mat_traits<A>::cols==1 && mat_traits<B>::cols==1,\r\n            A &>::type\r\n        assign( A & a, B const & b )\r\n            {\r\n            mat_traits<A>::template write_element<0,0>(a)=mat_traits<B>::template read_element<0,0>(b);\r\n            mat_traits<A>::template write_element<1,0>(a)=mat_traits<B>::template read_element<1,0>(b);\r\n            return a;\r\n            }\r\n\r\n        namespace\r\n        sfinae\r\n            {\r\n            using ::boost::qvm::assign;\r\n            }\r\n\r\n        namespace\r\n        qvm_detail\r\n            {\r\n            template <int R,int C>\r\n            struct assign_mm_defined;\r\n\r\n            template <>\r\n            struct\r\n            assign_mm_defined<2,1>\r\n                {\r\n                static bool const value=true;\r\n                };\r\n            }\r\n\r\n        template <class A,class B>\r\n        BOOST_QVM_INLINE_OPERATIONS\r\n        typename enable_if_c<\r\n            mat_traits<A>::rows==1 && mat_traits<B>::rows==1 &&\r\n            mat_traits<A>::cols==2 && mat_traits<B>::cols==2,\r\n            A &>::type\r\n        assign( A & a, B const & b )\r\n            {\r\n            mat_traits<A>::template write_element<0,0>(a)=mat_traits<B>::template read_element<0,0>(b);\r\n            mat_traits<A>::template write_element<0,1>(a)=mat_traits<B>::template read_element<0,1>(b);\r\n            return a;\r\n            }\r\n\r\n        namespace\r\n        sfinae\r\n            {\r\n            using ::boost::qvm::assign;\r\n            }\r\n\r\n        namespace\r\n        qvm_detail\r\n            {\r\n            template <int R,int C>\r\n            struct assign_mm_defined;\r\n\r\n            template <>\r\n            struct\r\n            assign_mm_defined<1,2>\r\n                {\r\n                static bool const value=true;\r\n                };\r\n            }\r\n\r\n        template <class R,class A>\r\n        BOOST_QVM_INLINE_OPERATIONS\r\n        typename enable_if_c<\r\n            mat_traits<R>::rows==2 && mat_traits<A>::rows==2 &&\r\n            mat_traits<R>::cols==2 && mat_traits<A>::cols==2,\r\n            R>::type\r\n        convert_to( A const & a )\r\n            {\r\n            R r;\r\n            mat_traits<R>::template write_element<0,0>(r) = mat_traits<A>::template read_element<0,0>(a);\r\n            mat_traits<R>::template write_element<0,1>(r) = mat_traits<A>::template read_element<0,1>(a);\r\n            mat_traits<R>::template write_element<1,0>(r) = mat_traits<A>::template read_element<1,0>(a);\r\n            mat_traits<R>::template write_element<1,1>(r) = mat_traits<A>::template read_element<1,1>(a);\r\n            return r;\r\n            }\r\n\r\n        namespace\r\n        sfinae\r\n            {\r\n            using ::boost::qvm::convert_to;\r\n            }\r\n\r\n        namespace\r\n        qvm_detail\r\n            {\r\n            template <int R,int C>\r\n            struct convert_to_m_defined;\r\n\r\n            template <>\r\n            struct\r\n            convert_to_m_defined<2,2>\r\n                {\r\n                static bool const value=true;\r\n                };\r\n            }\r\n\r\n        template <class R,class A>\r\n        BOOST_QVM_INLINE_OPERATIONS\r\n        typename enable_if_c<\r\n            mat_traits<R>::rows==2 && mat_traits<A>::rows==2 &&\r\n            mat_traits<R>::cols==1 && mat_traits<A>::cols==1,\r\n            R>::type\r\n        convert_to( A const & a )\r\n            {\r\n            R r;\r\n            mat_traits<R>::template write_element<0,0>(r) = mat_traits<A>::template read_element<0,0>(a);\r\n            mat_traits<R>::template write_element<1,0>(r) = mat_traits<A>::template read_element<1,0>(a);\r\n            return r;\r\n            }\r\n\r\n        namespace\r\n        sfinae\r\n            {\r\n            using ::boost::qvm::convert_to;\r\n            }\r\n\r\n        namespace\r\n        qvm_detail\r\n            {\r\n            template <int R,int C>\r\n            struct convert_to_m_defined;\r\n\r\n            template <>\r\n            struct\r\n            convert_to_m_defined<2,1>\r\n                {\r\n                static bool const value=true;\r\n                };\r\n            }\r\n\r\n        template <class R,class A>\r\n        BOOST_QVM_INLINE_OPERATIONS\r\n        typename enable_if_c<\r\n            mat_traits<R>::rows==1 && mat_traits<A>::rows==1 &&\r\n            mat_traits<R>::cols==2 && mat_traits<A>::cols==2,\r\n            R>::type\r\n        convert_to( A const & a )\r\n            {\r\n            R r;\r\n            mat_traits<R>::template write_element<0,0>(r) = mat_traits<A>::template read_element<0,0>(a);\r\n            mat_traits<R>::template write_element<0,1>(r) = mat_traits<A>::template read_element<0,1>(a);\r\n            return r;\r\n            }\r\n\r\n        namespace\r\n        sfinae\r\n            {\r\n            using ::boost::qvm::convert_to;\r\n            }\r\n\r\n        namespace\r\n        qvm_detail\r\n            {\r\n            template <int R,int C>\r\n            struct convert_to_m_defined;\r\n\r\n            template <>\r\n            struct\r\n            convert_to_m_defined<1,2>\r\n                {\r\n                static bool const value=true;\r\n                };\r\n            }\r\n\r\n        template <class A,class B>\r\n        BOOST_QVM_INLINE_OPERATIONS\r\n        typename enable_if_c<\r\n            mat_traits<A>::rows==2 && mat_traits<B>::rows==2 &&\r\n            mat_traits<A>::cols==2 && mat_traits<B>::cols==2,\r\n            bool>::type\r\n        operator==( A const & a, B const & b )\r\n            {\r\n            return\r\n                mat_traits<A>::template read_element<0,0>(a)==mat_traits<B>::template read_element<0,0>(b) &&\r\n                mat_traits<A>::template read_element<0,1>(a)==mat_traits<B>::template read_element<0,1>(b) &&\r\n                mat_traits<A>::template read_element<1,0>(a)==mat_traits<B>::template read_element<1,0>(b) &&\r\n                mat_traits<A>::template read_element<1,1>(a)==mat_traits<B>::template read_element<1,1>(b);\r\n            }\r\n\r\n        namespace\r\n        sfinae\r\n            {\r\n            using ::boost::qvm::operator==;\r\n            }\r\n\r\n        namespace\r\n        qvm_detail\r\n            {\r\n            template <int R,int C>\r\n            struct eq_mm_defined;\r\n\r\n            template <>\r\n            struct\r\n            eq_mm_defined<2,2>\r\n                {\r\n                static bool const value=true;\r\n                };\r\n            }\r\n\r\n        template <class A,class B>\r\n        BOOST_QVM_INLINE_OPERATIONS\r\n        typename enable_if_c<\r\n            mat_traits<A>::rows==2 && mat_traits<B>::rows==2 &&\r\n            mat_traits<A>::cols==1 && mat_traits<B>::cols==1,\r\n            bool>::type\r\n        operator==( A const & a, B const & b )\r\n            {\r\n            return\r\n                mat_traits<A>::template read_element<0,0>(a)==mat_traits<B>::template read_element<0,0>(b) &&\r\n                mat_traits<A>::template read_element<1,0>(a)==mat_traits<B>::template read_element<1,0>(b);\r\n            }\r\n\r\n        namespace\r\n        sfinae\r\n            {\r\n            using ::boost::qvm::operator==;\r\n            }\r\n\r\n        namespace\r\n        qvm_detail\r\n            {\r\n            template <int R,int C>\r\n            struct eq_mm_defined;\r\n\r\n            template <>\r\n            struct\r\n            eq_mm_defined<2,1>\r\n                {\r\n                static bool const value=true;\r\n                };\r\n            }\r\n\r\n        template <class A,class B>\r\n        BOOST_QVM_INLINE_OPERATIONS\r\n        typename enable_if_c<\r\n            mat_traits<A>::rows==1 && mat_traits<B>::rows==1 &&\r\n            mat_traits<A>::cols==2 && mat_traits<B>::cols==2,\r\n            bool>::type\r\n        operator==( A const & a, B const & b )\r\n            {\r\n            return\r\n                mat_traits<A>::template read_element<0,0>(a)==mat_traits<B>::template read_element<0,0>(b) &&\r\n                mat_traits<A>::template read_element<0,1>(a)==mat_traits<B>::template read_element<0,1>(b);\r\n            }\r\n\r\n        namespace\r\n        sfinae\r\n            {\r\n            using ::boost::qvm::operator==;\r\n            }\r\n\r\n        namespace\r\n        qvm_detail\r\n            {\r\n            template <int R,int C>\r\n            struct eq_mm_defined;\r\n\r\n            template <>\r\n            struct\r\n            eq_mm_defined<1,2>\r\n                {\r\n                static bool const value=true;\r\n                };\r\n            }\r\n\r\n        template <class A,class B>\r\n        BOOST_QVM_INLINE_OPERATIONS\r\n        typename enable_if_c<\r\n            mat_traits<A>::rows==2 && mat_traits<B>::rows==2 &&\r\n            mat_traits<A>::cols==2 && mat_traits<B>::cols==2,\r\n            bool>::type\r\n        operator!=( A const & a, B const & b )\r\n            {\r\n            return\r\n                !(mat_traits<A>::template read_element<0,0>(a)==mat_traits<B>::template read_element<0,0>(b)) ||\r\n                !(mat_traits<A>::template read_element<0,1>(a)==mat_traits<B>::template read_element<0,1>(b)) ||\r\n                !(mat_traits<A>::template read_element<1,0>(a)==mat_traits<B>::template read_element<1,0>(b)) ||\r\n                !(mat_traits<A>::template read_element<1,1>(a)==mat_traits<B>::template read_element<1,1>(b));\r\n            }\r\n\r\n        namespace\r\n        sfinae\r\n            {\r\n            using ::boost::qvm::operator!=;\r\n            }\r\n\r\n        namespace\r\n        qvm_detail\r\n            {\r\n            template <int R,int C>\r\n            struct neq_mm_defined;\r\n\r\n            template <>\r\n            struct\r\n            neq_mm_defined<2,2>\r\n                {\r\n                static bool const value=true;\r\n                };\r\n            }\r\n\r\n        template <class A,class B>\r\n        BOOST_QVM_INLINE_OPERATIONS\r\n        typename enable_if_c<\r\n            mat_traits<A>::rows==2 && mat_traits<B>::rows==2 &&\r\n            mat_traits<A>::cols==1 && mat_traits<B>::cols==1,\r\n            bool>::type\r\n        operator!=( A const & a, B const & b )\r\n            {\r\n            return\r\n                !(mat_traits<A>::template read_element<0,0>(a)==mat_traits<B>::template read_element<0,0>(b)) ||\r\n                !(mat_traits<A>::template read_element<1,0>(a)==mat_traits<B>::template read_element<1,0>(b));\r\n            }\r\n\r\n        namespace\r\n        sfinae\r\n            {\r\n            using ::boost::qvm::operator!=;\r\n            }\r\n\r\n        namespace\r\n        qvm_detail\r\n            {\r\n            template <int R,int C>\r\n            struct neq_mm_defined;\r\n\r\n            template <>\r\n            struct\r\n            neq_mm_defined<2,1>\r\n                {\r\n                static bool const value=true;\r\n                };\r\n            }\r\n\r\n        template <class A,class B>\r\n        BOOST_QVM_INLINE_OPERATIONS\r\n        typename enable_if_c<\r\n            mat_traits<A>::rows==1 && mat_traits<B>::rows==1 &&\r\n            mat_traits<A>::cols==2 && mat_traits<B>::cols==2,\r\n            bool>::type\r\n        operator!=( A const & a, B const & b )\r\n            {\r\n            return\r\n                !(mat_traits<A>::template read_element<0,0>(a)==mat_traits<B>::template read_element<0,0>(b)) ||\r\n                !(mat_traits<A>::template read_element<0,1>(a)==mat_traits<B>::template read_element<0,1>(b));\r\n            }\r\n\r\n        namespace\r\n        sfinae\r\n            {\r\n            using ::boost::qvm::operator!=;\r\n            }\r\n\r\n        namespace\r\n        qvm_detail\r\n            {\r\n            template <int R,int C>\r\n            struct neq_mm_defined;\r\n\r\n            template <>\r\n            struct\r\n            neq_mm_defined<1,2>\r\n                {\r\n                static bool const value=true;\r\n                };\r\n            }\r\n\r\n        template <class A>\r\n        BOOST_QVM_INLINE_OPERATIONS\r\n        typename lazy_enable_if_c<\r\n            mat_traits<A>::rows==2 && mat_traits<A>::cols==2,\r\n            deduce_mat<A> >::type\r\n        operator-( A const & a )\r\n            {\r\n            typedef typename deduce_mat<A>::type R;\r\n            R r;\r\n            mat_traits<R>::template write_element<0,0>(r)=-mat_traits<A>::template read_element<0,0>(a);\r\n            mat_traits<R>::template write_element<0,1>(r)=-mat_traits<A>::template read_element<0,1>(a);\r\n            mat_traits<R>::template write_element<1,0>(r)=-mat_traits<A>::template read_element<1,0>(a);\r\n            mat_traits<R>::template write_element<1,1>(r)=-mat_traits<A>::template read_element<1,1>(a);\r\n            return r;\r\n            }\r\n\r\n        namespace\r\n        sfinae\r\n            {\r\n            using ::boost::qvm::operator-;\r\n            }\r\n\r\n        namespace\r\n        qvm_detail\r\n            {\r\n            template <int R,int C>\r\n            struct minus_m_defined;\r\n\r\n            template <>\r\n            struct\r\n            minus_m_defined<2,2>\r\n                {\r\n                static bool const value=true;\r\n                };\r\n            }\r\n\r\n        template <class A>\r\n        BOOST_QVM_INLINE_OPERATIONS\r\n        typename lazy_enable_if_c<\r\n            mat_traits<A>::rows==2 && mat_traits<A>::cols==1,\r\n            deduce_mat<A> >::type\r\n        operator-( A const & a )\r\n            {\r\n            typedef typename deduce_mat<A>::type R;\r\n            R r;\r\n            mat_traits<R>::template write_element<0,0>(r)=-mat_traits<A>::template read_element<0,0>(a);\r\n            mat_traits<R>::template write_element<1,0>(r)=-mat_traits<A>::template read_element<1,0>(a);\r\n            return r;\r\n            }\r\n\r\n        namespace\r\n        sfinae\r\n            {\r\n            using ::boost::qvm::operator-;\r\n            }\r\n\r\n        namespace\r\n        qvm_detail\r\n            {\r\n            template <int R,int C>\r\n            struct minus_m_defined;\r\n\r\n            template <>\r\n            struct\r\n            minus_m_defined<2,1>\r\n                {\r\n                static bool const value=true;\r\n                };\r\n            }\r\n\r\n        template <class A>\r\n        BOOST_QVM_INLINE_OPERATIONS\r\n        typename lazy_enable_if_c<\r\n            mat_traits<A>::rows==1 && mat_traits<A>::cols==2,\r\n            deduce_mat<A> >::type\r\n        operator-( A const & a )\r\n            {\r\n            typedef typename deduce_mat<A>::type R;\r\n            R r;\r\n            mat_traits<R>::template write_element<0,0>(r)=-mat_traits<A>::template read_element<0,0>(a);\r\n            mat_traits<R>::template write_element<0,1>(r)=-mat_traits<A>::template read_element<0,1>(a);\r\n            return r;\r\n            }\r\n\r\n        namespace\r\n        sfinae\r\n            {\r\n            using ::boost::qvm::operator-;\r\n            }\r\n\r\n        namespace\r\n        qvm_detail\r\n            {\r\n            template <int R,int C>\r\n            struct minus_m_defined;\r\n\r\n            template <>\r\n            struct\r\n            minus_m_defined<1,2>\r\n                {\r\n                static bool const value=true;\r\n                };\r\n            }\r\n\r\n        template <class A>\r\n        BOOST_QVM_INLINE_OPERATIONS\r\n        typename enable_if_c<\r\n            mat_traits<A>::rows==2 && mat_traits<A>::cols==2,\r\n            typename mat_traits<A>::scalar_type>::type\r\n        determinant( A const & a )\r\n            {\r\n            typedef typename mat_traits<A>::scalar_type T;\r\n            T const a00=mat_traits<A>::template read_element<0,0>(a);\r\n            T const a01=mat_traits<A>::template read_element<0,1>(a);\r\n            T const a10=mat_traits<A>::template read_element<1,0>(a);\r\n            T const a11=mat_traits<A>::template read_element<1,1>(a);\r\n            T det=(a00*a11-a01*a10);\r\n            return det;\r\n            }\r\n\r\n        namespace\r\n        sfinae\r\n            {\r\n            using ::boost::qvm::determinant;\r\n            }\r\n\r\n        namespace\r\n        qvm_detail\r\n            {\r\n            template <int D>\r\n            struct determinant_defined;\r\n\r\n            template <>\r\n            struct\r\n            determinant_defined<2>\r\n                {\r\n                static bool const value=true;\r\n                };\r\n            }\r\n\r\n        template <class A,class B>\r\n        BOOST_QVM_INLINE_OPERATIONS\r\n        typename lazy_enable_if_c<\r\n            mat_traits<A>::rows==2 && mat_traits<A>::cols==2 && is_scalar<B>::value,\r\n            deduce_mat<A> >::type\r\n        inverse( A const & a, B det )\r\n            {\r\n            typedef typename mat_traits<A>::scalar_type T;\r\n            BOOST_QVM_ASSERT(det!=scalar_traits<B>::value(0));\r\n            T const a00=mat_traits<A>::template read_element<0,0>(a);\r\n            T const a01=mat_traits<A>::template read_element<0,1>(a);\r\n            T const a10=mat_traits<A>::template read_element<1,0>(a);\r\n            T const a11=mat_traits<A>::template read_element<1,1>(a);\r\n            T const f=scalar_traits<T>::value(1)/det;\r\n            typedef typename deduce_mat<A>::type R;\r\n            R r;\r\n            mat_traits<R>::template write_element<0,0>(r)= f*a11;\r\n            mat_traits<R>::template write_element<0,1>(r)=-f*a01;\r\n            mat_traits<R>::template write_element<1,0>(r)=-f*a10;\r\n            mat_traits<R>::template write_element<1,1>(r)= f*a00;\r\n            return r;\r\n            }\r\n\r\n        template <class A>\r\n        BOOST_QVM_INLINE_OPERATIONS\r\n        typename lazy_enable_if_c<\r\n            mat_traits<A>::rows==2 && mat_traits<A>::cols==2,\r\n            deduce_mat<A> >::type\r\n        inverse( A const & a )\r\n            {\r\n            typedef typename mat_traits<A>::scalar_type T;\r\n            T det=determinant(a);\r\n            if( det==scalar_traits<T>::value(0) )\r\n                BOOST_QVM_THROW_EXCEPTION(zero_determinant_error());\r\n            return inverse(a,det);\r\n            }\r\n\r\n        namespace\r\n        sfinae\r\n            {\r\n            using ::boost::qvm::inverse;\r\n            }\r\n\r\n        namespace\r\n        qvm_detail\r\n            {\r\n            template <int D>\r\n            struct inverse_m_defined;\r\n\r\n            template <>\r\n            struct\r\n            inverse_m_defined<2>\r\n                {\r\n                static bool const value=true;\r\n                };\r\n            }\r\n\r\n        template <class A,class B>\r\n        BOOST_QVM_INLINE_OPERATIONS\r\n        typename lazy_enable_if_c<\r\n            mat_traits<A>::rows==2 && mat_traits<B>::rows==2 &&\r\n            mat_traits<A>::cols==2 && mat_traits<B>::cols==2,\r\n            deduce_mat2<A,B,2,2> >::type\r\n        operator*( A const & a, B const & b )\r\n            {\r\n            typedef typename mat_traits<A>::scalar_type Ta;\r\n            typedef typename mat_traits<B>::scalar_type Tb;\r\n            Ta const a00 = mat_traits<A>::template read_element<0,0>(a);\r\n            Ta const a01 = mat_traits<A>::template read_element<0,1>(a);\r\n            Ta const a10 = mat_traits<A>::template read_element<1,0>(a);\r\n            Ta const a11 = mat_traits<A>::template read_element<1,1>(a);\r\n            Tb const b00 = mat_traits<B>::template read_element<0,0>(b);\r\n            Tb const b01 = mat_traits<B>::template read_element<0,1>(b);\r\n            Tb const b10 = mat_traits<B>::template read_element<1,0>(b);\r\n            Tb const b11 = mat_traits<B>::template read_element<1,1>(b);\r\n            typedef typename deduce_mat2<A,B,2,2>::type R;\r\n            BOOST_QVM_STATIC_ASSERT(mat_traits<R>::rows==2);\r\n            BOOST_QVM_STATIC_ASSERT(mat_traits<R>::cols==2);\r\n            R r;\r\n            mat_traits<R>::template write_element<0,0>(r)=a00*b00+a01*b10;\r\n            mat_traits<R>::template write_element<0,1>(r)=a00*b01+a01*b11;\r\n            mat_traits<R>::template write_element<1,0>(r)=a10*b00+a11*b10;\r\n            mat_traits<R>::template write_element<1,1>(r)=a10*b01+a11*b11;\r\n            return r;\r\n            }\r\n\r\n        namespace\r\n        sfinae\r\n            {\r\n            using ::boost::qvm::operator*;\r\n            }\r\n\r\n        namespace\r\n        qvm_detail\r\n            {\r\n            template <int R,int CR,int C>\r\n            struct mul_mm_defined;\r\n\r\n            template <>\r\n            struct\r\n            mul_mm_defined<2,2,2>\r\n                {\r\n                static bool const value=true;\r\n                };\r\n            }\r\n\r\n        template <class A,class B>\r\n        BOOST_QVM_INLINE_OPERATIONS\r\n        typename enable_if_c<\r\n            mat_traits<A>::rows==2 && mat_traits<B>::rows==2 &&\r\n            mat_traits<A>::cols==2 && mat_traits<B>::cols==2,\r\n            A &>::type\r\n        operator*=( A & a, B const & b )\r\n            {\r\n            typedef typename mat_traits<A>::scalar_type Ta;\r\n            typedef typename mat_traits<B>::scalar_type Tb;\r\n            Ta const a00 = mat_traits<A>::template read_element<0,0>(a);\r\n            Ta const a01 = mat_traits<A>::template read_element<0,1>(a);\r\n            Ta const a10 = mat_traits<A>::template read_element<1,0>(a);\r\n            Ta const a11 = mat_traits<A>::template read_element<1,1>(a);\r\n            Tb const b00 = mat_traits<B>::template read_element<0,0>(b);\r\n            Tb const b01 = mat_traits<B>::template read_element<0,1>(b);\r\n            Tb const b10 = mat_traits<B>::template read_element<1,0>(b);\r\n            Tb const b11 = mat_traits<B>::template read_element<1,1>(b);\r\n            mat_traits<A>::template write_element<0,0>(a)=a00*b00+a01*b10;\r\n            mat_traits<A>::template write_element<0,1>(a)=a00*b01+a01*b11;\r\n            mat_traits<A>::template write_element<1,0>(a)=a10*b00+a11*b10;\r\n            mat_traits<A>::template write_element<1,1>(a)=a10*b01+a11*b11;\r\n            return a;\r\n            }\r\n\r\n        namespace\r\n        sfinae\r\n            {\r\n            using ::boost::qvm::operator*=;\r\n            }\r\n\r\n        namespace\r\n        qvm_detail\r\n            {\r\n            template <int D>\r\n            struct mul_eq_mm_defined;\r\n\r\n            template <>\r\n            struct\r\n            mul_eq_mm_defined<2>\r\n                {\r\n                static bool const value=true;\r\n                };\r\n            }\r\n\r\n        template <class A,class B>\r\n        BOOST_QVM_INLINE_OPERATIONS\r\n        typename lazy_enable_if_c<\r\n            mat_traits<A>::rows==2 && mat_traits<B>::rows==2 &&\r\n            mat_traits<A>::cols==2 && mat_traits<B>::cols==1,\r\n            deduce_mat2<A,B,2,1> >::type\r\n        operator*( A const & a, B const & b )\r\n            {\r\n            typedef typename mat_traits<A>::scalar_type Ta;\r\n            typedef typename mat_traits<B>::scalar_type Tb;\r\n            Ta const a00 = mat_traits<A>::template read_element<0,0>(a);\r\n            Ta const a01 = mat_traits<A>::template read_element<0,1>(a);\r\n            Ta const a10 = mat_traits<A>::template read_element<1,0>(a);\r\n            Ta const a11 = mat_traits<A>::template read_element<1,1>(a);\r\n            Tb const b00 = mat_traits<B>::template read_element<0,0>(b);\r\n            Tb const b10 = mat_traits<B>::template read_element<1,0>(b);\r\n            typedef typename deduce_mat2<A,B,2,1>::type R;\r\n            BOOST_QVM_STATIC_ASSERT(mat_traits<R>::rows==2);\r\n            BOOST_QVM_STATIC_ASSERT(mat_traits<R>::cols==1);\r\n            R r;\r\n            mat_traits<R>::template write_element<0,0>(r)=a00*b00+a01*b10;\r\n            mat_traits<R>::template write_element<1,0>(r)=a10*b00+a11*b10;\r\n            return r;\r\n            }\r\n\r\n        namespace\r\n        sfinae\r\n            {\r\n            using ::boost::qvm::operator*;\r\n            }\r\n\r\n        namespace\r\n        qvm_detail\r\n            {\r\n            template <int R,int CR,int C>\r\n            struct mul_mm_defined;\r\n\r\n            template <>\r\n            struct\r\n            mul_mm_defined<2,2,1>\r\n                {\r\n                static bool const value=true;\r\n                };\r\n            }\r\n\r\n        template <class A,class B>\r\n        BOOST_QVM_INLINE_OPERATIONS\r\n        typename lazy_enable_if_c<\r\n            mat_traits<A>::rows==1 && mat_traits<B>::rows==2 &&\r\n            mat_traits<A>::cols==2 && mat_traits<B>::cols==2,\r\n            deduce_mat2<A,B,1,2> >::type\r\n        operator*( A const & a, B const & b )\r\n            {\r\n            typedef typename mat_traits<A>::scalar_type Ta;\r\n            typedef typename mat_traits<B>::scalar_type Tb;\r\n            Ta const a00 = mat_traits<A>::template read_element<0,0>(a);\r\n            Ta const a01 = mat_traits<A>::template read_element<0,1>(a);\r\n            Tb const b00 = mat_traits<B>::template read_element<0,0>(b);\r\n            Tb const b01 = mat_traits<B>::template read_element<0,1>(b);\r\n            Tb const b10 = mat_traits<B>::template read_element<1,0>(b);\r\n            Tb const b11 = mat_traits<B>::template read_element<1,1>(b);\r\n            typedef typename deduce_mat2<A,B,1,2>::type R;\r\n            BOOST_QVM_STATIC_ASSERT(mat_traits<R>::rows==1);\r\n            BOOST_QVM_STATIC_ASSERT(mat_traits<R>::cols==2);\r\n            R r;\r\n            mat_traits<R>::template write_element<0,0>(r)=a00*b00+a01*b10;\r\n            mat_traits<R>::template write_element<0,1>(r)=a00*b01+a01*b11;\r\n            return r;\r\n            }\r\n\r\n        namespace\r\n        sfinae\r\n            {\r\n            using ::boost::qvm::operator*;\r\n            }\r\n\r\n        namespace\r\n        qvm_detail\r\n            {\r\n            template <int R,int CR,int C>\r\n            struct mul_mm_defined;\r\n\r\n            template <>\r\n            struct\r\n            mul_mm_defined<1,2,2>\r\n                {\r\n                static bool const value=true;\r\n                };\r\n            }\r\n\r\n        }\r\n    }\r\n\r\n#endif\r\n", "meta": {"hexsha": "105ebde2eaf77db1301d0460348f241af1c08cad", "size": 54083, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ios/Pods/boost-for-react-native/boost/qvm/gen/mat_operations2.hpp", "max_stars_repo_name": "rudylee/expo", "max_stars_repo_head_hexsha": "b3e65a7a5b205f14a3eb6cd6fa8d13c8d663b1cc", "max_stars_repo_licenses": ["Apache-2.0", "MIT"], "max_stars_count": 8805.0, "max_stars_repo_stars_event_min_datetime": "2015-11-03T00:52:29.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T22:30:03.000Z", "max_issues_repo_path": "ios/Pods/boost-for-react-native/boost/qvm/gen/mat_operations2.hpp", "max_issues_repo_name": "rudylee/expo", "max_issues_repo_head_hexsha": "b3e65a7a5b205f14a3eb6cd6fa8d13c8d663b1cc", "max_issues_repo_licenses": ["Apache-2.0", "MIT"], "max_issues_count": 14694.0, "max_issues_repo_issues_event_min_datetime": "2015-02-24T15:13:42.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T13:16:45.000Z", "max_forks_repo_path": "ios/Pods/boost-for-react-native/boost/qvm/gen/mat_operations2.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.7775757576, "max_line_length": 149, "alphanum_fraction": 0.4817595178, "num_tokens": 12397, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7185943805178139, "lm_q2_score": 0.44552953503957266, "lm_q1q2_score": 0.3201550202341514}}
{"text": "//==========================================================================\n//  This file is part of HMMlib.\n//\n//  HMMlib is free software: you can redistribute it and/or modify\n//  it under the terms of the GNU Lesser General Public License as\n//  published by the Free Software Foundation, either version 3 of\n//  the License, or (at your option) any later version.\n//\n//  HMMlib 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//  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 HMMlib. If not, see\n//  <http://www.gnu.org/licenses/>.\n//\n//  Copyright (C) 2010  Bioinformatics Research Centre, Aarhus University.\n//  Author: Andreas Sand (asand@birc.au.dk)\n//==========================================================================\n\n#ifndef HMM_HPP\n#define HMM_HPP\n\n#include <boost/shared_ptr.hpp>\n\n#include <vector>\n#include <cmath>\n#include <assert.h>\nusing namespace std;\n\n#include \"HMMlib/hmm_matrix.hpp\"\n#include \"HMMlib/hmm_vector.hpp\"\n#include \"HMMlib/sse_operator_traits.hpp\"\n\n#include <pmmintrin.h>\n\n#ifdef WITH_OMP\n#include <omp.h>\n#endif\n\ntypedef std::vector<unsigned int> sequence;\n\nnamespace hmmlib {\n\n  /**\n   * \\class HMM\n   *\n   * \\brief Encapsulates the representation of a Hidden Markov\n   * Model.\n   *\n   * This class encapsulates the representation of a Hidden Markov\n   * Model. A hidden Markov model is composed by a transition matrix,\n   * an emission matrix and a vector of initial state probabilities.\n   * Five classical HMM algorithms are supported: Viterbi, forward,\n   * backward, Baum-Welch and posterior decoding.  The algorithms are\n   * optimized using the SSE instruction set and parallelized using\n   * OpenMP as described in <a\n   * href=\"http://birc.au.dk/~asand/papers/HiBi10_hmmlib.pdf\">HMMlib:\n   * A C++ Library for General Hidden Markov Models Exploiting Modern\n   * CPUs</a>.\n   *\n   * Possible values of \\a float_type are: \\a double or \\a float.\n   *\n   * Possible values of sse_float_type are: \\a double, \\a float, \\a\n   * __m128d or __m128. If \\a float_type is \\a double, sse_float_type\n   * must be either \\a __m128d (default) or \\a double. If \\a\n   * float_type is \\a float, sse_float_type must be either \\a __m128\n   * (default) or \\a float.\n   *\n   *\n   * \\author Andreas Sand (asand@birc.au.dk)\n   * \\see http://birc.au.dk/~asand/papers/HiBi10_hmmlib.pdf\n   */\n  template < typename float_type, \n\t     typename sse_float_type = typename FloatTraits<float_type>::sse_type>\n  class HMM {\n\t\t\n    typedef SSEOperatorTraits<float_type, sse_float_type> sse_operations_traits;\n\t\t\n    boost::shared_ptr< HMMVector<float_type, sse_float_type> > initial_prob;\n    boost::shared_ptr< HMMMatrix<float_type, sse_float_type> > trans_prob;\n    boost::shared_ptr< HMMMatrix<float_type, sse_float_type> > emission_prob;\n\t\t\n    const int no_states;\n    const int alphabet_size;\n    \n  public :\n    /**\n     * \\brief Constructs an HMM with the indicated initial state\n     * probabilities, transition probabilities and emission\n     * probabilities.\n     *\n     * Constructs an HMM with the indicated initial state\n     * probabilities, transition probabilities and emission\n     * probabilities.\n     *\n     * \\param initial_prob   The vector of initial state probabilities, in which the \\f$i\\f$th entry must be the probability of the model initially being in state i. The entries in \\a initial_prob must sum to 1.\n     * \\param trans_prob     The matrix of transition probabilities, in which the \\f$i,j\\f$th entry must be the probability of the transition from state i to state j. Each row in T must sum to 1.\n     * \\param emission_prob  The matrix of emission probabilities, in which the \\f$i,j\\f$th entry must be the probabilities of state \\f$j\\f$ emitting the \\f$i\\f$th alphabet symbol. Each column must sum to 1.\n     *\n     * Possible values of \\a float_type are: \\a double or \\a float.\n     *\n     * Possible values of sse_float_type are: \\a double, \\a float, \\a\n     * __m128d or __m128. If \\a float_type is \\a double, sse_float_type\n     * must be either \\a __m128d (default) or \\a double. If \\a\n     * float_type is \\a float, sse_float_type must be either \\a __m128\n     * (default) or \\a float.\n     *\n     * \\pre The size of \\a initial_prob must match the number of rows in \\a trans_prob, the number of columns in trans_prob and the number columns in emission_prob.\n     */\n    HMM(boost::shared_ptr< HMMVector<float_type, sse_float_type> > initial_prob,\n\tboost::shared_ptr< HMMMatrix<float_type, sse_float_type> > trans_prob,\n\tboost::shared_ptr< HMMMatrix<float_type, sse_float_type> > emission_prob);\n\n    // field accessors and mutators\n    const HMMVector<float_type,sse_float_type> &get_initial_probs() { return *initial_prob; }\n    const HMMMatrix<float_type,sse_float_type> &get_trans_probs() { return *trans_prob; }\n    const HMMMatrix<float_type,sse_float_type> &get_emission_probs() { return *emission_prob; }\n    const int get_no_states() const { return no_states; }\n    const int get_alphabet_size() const { return alphabet_size; }\n    \n\n    // algorithms\n    /**\n     * \\brief Runs the forward dynamic programming algorithm.\n     *\n     * Fills in the forward dynamic programming table, \\a F.\n     *\n     * \\param obsseq    The observed sequence of emissions.\n     * \\param F         The forward dynamic programming table (to be filled in).\n     * \\param scales    The scaling factors (to be filled in).\n     *\n     * After running this function, the \\f$i,j\\f$th entry in \\a F will be:\n     * \\f[f_{ij} = c_i e_{s_i,j} \\sum_l f_{i-1,l}t_{l, j},\\f]\n     * and the \\f$i\\f$th entry in \\a scales, \\f$c_i\\f$, will be the factor normalizing\n     * \\f$ \\sum_j e_{s_i,j}  \\sum_l f_{i-1,l}t_{l, j}\\f$.\n     *\n     * \\pre The number of states in the model must match the number of columns in \\a F.\n     * \\pre The number of observations in \\a obsseq must match the number of rows in \\a F and the size of \\a scales.\n     */\n    void forward(const sequence &obsseq,\n\t\t HMMVector<float_type, sse_float_type> &scales,\n\t\t HMMMatrix<float_type, sse_float_type> &F);\n    \n    /**\n     * \\brief Runs the backward dynamic programming algorithm.\n     *\n     * Fills in the backward dynamic programming table, \\a B.\n     *\n     * \\param obsseq    The observed sequence of emissions.\n     * \\param B         The backward dynamic programming table (to be filled in).\n     * \\param scales    The scaling factors from the forward algorithm.\n     *\n     * After running this function, the \\f$i,j\\f$th entry in \\a B will be:\n     * \\f[b_{ij} = c_{i+1}\\sum_l e_{s_{i+1},l} t_{jl} b_{i+1,l}.\\f]\n     *\n     * \\pre The number of states in the model must match the number of columns in \\a B.  \n     * \\pre The number of observations in \\a obsseq must match the number of rows in \\a B and the size of \\a scales.\n     * \\pre \\a scales must have been filled out using \\a forward().\n     */\n    void backward(const sequence &obsseq,\n\t\t  const HMMVector<float_type, sse_float_type> &scales,\n\t\t  HMMMatrix<float_type, sse_float_type> &B);\n\n    /**\n     * \\brief Computes the loglikelihood of the model generating an observed sequence.\n     *\n     * Computes the loglikelihood of the model generating an observed sequence, based on the vector of scaling factors computed by the \\a forward() function.\n     *\n     * \\param scales    The vector of scaling factors computed by the \\a forward() function.\n     * \\returns         The loglikelihood.\n     *\n     * \\pre \\a scales must have been filled out using \\a forward().\n     */\n    float_type likelihood(const HMMVector<float_type, sse_float_type> &scales); \n\n    /**\n     * \\brief Computes \\f$\\Theta=(pi_{counts}, T_{counts}, E_{counts})\\f$ such that\n     * \\f$P(obsseq \\vert \\Theta)\\f$ is maximized.\n     *\n     * Computes \\f$\\Theta=(pi_{counts}, T_{counts}, E_{counts})\\f$ such that\n     * \\f$P(obsseq \\vert \\Theta)\\f$ is maximized.\n     *\n     * \\param obsseq    The observed sequence of emissions.\n     * \\param F         The forward dynamic programming table computed by \\a forward().\n     * \\param B         The backward dynamic programming table table computed by \\a backward().\n     * \\param scales    The scalling factors from the forward algorithms computed by \\a forward().\n     * \\param pi_counts The estimated initial state probability vector (to be filled in).\n     * \\param T_counts  The estimated transition matrix (to be filled in).\n     * \\param E_counts  The estimated emission matrix (to be filled in).\n     *\n     * \\pre \\a F, \\a scales and \\a B must have been filled in using the \\a forward() and \\a backward() functions.\n     * \\pre The number of states in the model must match the number of columns in \\a F and \\a B.\n     * \\pre The number of observations in \\a obsseq must match the number of rows in \\a F and \\a B and the size of \\a scales.\n     * \\pre The number of states in the model must match the size of \\a pi_counts, the number of rows in \\a T_counts, the number of columns in \\a T_counts and the number of columns in \\a E_counts.\n     * \\pre The alphabet size of the model must match the number of rows in \\a E_counts.\n     */\n    void baum_welch(const sequence &obsseq,\n\t\t    const HMMMatrix<float_type, sse_float_type> &F,\n\t\t    const HMMMatrix<float_type, sse_float_type> &B, \n\t\t    const HMMVector<float_type, sse_float_type> &scales,\n\t\t    HMMVector<float_type, sse_float_type> &pi_counts,\n\t\t    HMMMatrix<float_type, sse_float_type> &T_counts,\n\t\t    HMMMatrix<float_type, sse_float_type> &E_counts);\n    \n    /**\n     * \\brief Computes the maximum likelihood sequence of hidden states.\n     *\n     * Computes the maximum likelihood sequence of hidden states.\n     *\n     * \\param obsseq    The observed sequence of emissions.\n     * \\param hiddenseq The sequence of hidden states (to be filled in).\n     *\n     * \\returns         The loglikelihood of the probability of \\a hiddenseq, given that \\a obsseq is emitted.\n     *\n     * \\a hiddenseq is filled in using the Viterbi algorithm (computing in log space).\n     *\n     * \\pre The size of hiddenseq must match the size of obsseq.\n     */\n    float_type viterbi(const sequence &obsseq,\n\t\t       sequence &hiddenseq);\n\n    /**\n     * \\brief Computes the posterior decoding of \\a obsseq.\n     *\n     * Computes the posterior decoding of \\a obsseq.\n     *\n     * \\param obsseq    The observed sequence of emissions.\n     * \\param F         The forward dynamic programming table computed by \\a forward().\n     * \\param B         The backward dynamic programming table computed by \\a backward().\n     * \\param scales    The vector of scaling factors computed by \\a forward().\n     * \\param post      The matrix of posterior decoding probabilities (to be filled in).\n     *\n     * After running this function the \\f$i,j\\f$th entry in \\a post\n     * will be the probability with which the ith observed symbol in\n     * obsseq was emitted by the the jth state:\n     * \\f[P(z_i = j \\vert s) = \\frac{f_{ij}b_{ij}}{c_i}.\\f]\n     *\n     * \\pre \\a F, \\a B and \\a scales must have been fill in using the \\a forward() and \\a backward() functions.\n     * \\pre the number of rows in \\a post must match the size of obsseq, and the number of columns in \\a post must match the number of states in the model.\n     */\n    void posterior_decoding(const sequence &obsseq,\n\t\t\t    const HMMMatrix<float_type, sse_float_type> &F,\n\t\t\t    const HMMMatrix<float_type, sse_float_type> &B, \n\t\t\t    const HMMVector<float_type, sse_float_type> &scales, \n\t\t\t    HMMMatrix<float_type, sse_float_type> &post);\n    \n    friend class AllocatorTraits<float_type, sse_float_type>;\n    friend class OperatorTraits<float_type, sse_float_type>;\n  };\n\n  // ###############################################\n  // ########## Implementation comes here ##########\n  // ###############################################\n  template <typename float_type, typename sse_float_type>\n  HMM<float_type,sse_float_type>::HMM(boost::shared_ptr< HMMVector<float_type, sse_float_type> > initial_prob,\n\t\t\t\t       boost::shared_ptr< HMMMatrix<float_type, sse_float_type> > trans_prob,\n\t\t\t\t       boost::shared_ptr< HMMMatrix<float_type, sse_float_type> > emission_prob)\n    : \n    initial_prob(initial_prob), \n    trans_prob(trans_prob), \n    emission_prob(emission_prob),\n    no_states(initial_prob->get_size()),\n    alphabet_size(emission_prob->get_no_rows()) {\n    assert(trans_prob->get_no_columns() == no_states);\n    assert(trans_prob->get_no_rows() == no_states);\n    assert(emission_prob->get_no_columns() == no_states);\n    assert(emission_prob->get_no_rows() == alphabet_size);\n  }\n\n\n  template <typename float_type, typename sse_float_type>\n  void\n  HMM<float_type, sse_float_type>::forward(const sequence &obsseq,\n\t\t\t\t\t    HMMVector<float_type, sse_float_type> &scales,\n\t\t\t\t\t    HMMMatrix<float_type, sse_float_type> &F) {\t\t\n    // just making it a bit easier on ourselves...\n    const HMMVector<float_type, sse_float_type> &pi = *initial_prob;\n    const HMMMatrix<float_type, sse_float_type> &T = *trans_prob;\n    const HMMMatrix<float_type, sse_float_type> &E = *emission_prob;\n\t\t\n    HMMMatrix<float_type, sse_float_type> &T_t = *(new HMMMatrix<float_type, sse_float_type>(T.get_no_columns(), T.get_no_rows()));\n    T.transpose(T_t);\n\t\t\n    const int length = obsseq.size();\n    const int no_chunks = F.get_no_chunks_per_row();\n\t\t\n    // sanity check\n    assert(F.get_no_columns() == no_states);\n    assert(F.get_no_rows() == length);\n    assert(scales.get_size() == length);\n\t\t\n    // nice to have\n    sse_float_type ones;\n    sse_operations_traits::set_all(ones, (float_type) 1.0);\n\t\t\n    // initialise\n    unsigned int x = obsseq[0];\n    sse_float_type scale;\n    sse_operations_traits::set_all(scale, (float_type) 0.0);\n    int sc;\n    for(sc = 0; sc < no_chunks; ++sc) {\n      sse_float_type temp = pi.get_chunk(sc) * E.get_chunk(x,sc);\n      F.get_chunk(0, sc) = temp;\n      scale += temp;\n    }\n\n    float_type scale_float = 0;\n    sse_operations_traits::sum(scale);\n    scale_float = 1 / *((float_type *) &scale); \n    scales(0) = scale_float;\n\t\t\n    // scale first column of F\n    sse_operations_traits::set_all(scale, scale_float);\n    int chunk;\n    for(chunk = 0; chunk < no_chunks; ++chunk)\n      F.get_chunk(0,chunk) *= scale;\n\n    for(int i = 1; i < length; ++i) { // filling in i'th row of F: F(i, -)\n      x = obsseq[i];\n      #ifdef WITH_OMP\n      #pragma omp parallel for\n      #endif\n      for(int j = 0; j < no_states; ++j) { // filling in F(i,j)\n\tsse_float_type prob_sum;\n\tsse_operations_traits::set_all(prob_sum, (float_type) 0.0);\n\tfor(int c = 0; c < no_chunks; ++c)\n\t  prob_sum += F.get_chunk(i-1, c) * T_t.get_chunk(j, c);\n\tsse_operations_traits::sum(prob_sum);\n\tsse_operations_traits::store(F(i,j), prob_sum);\n      }\n\n      sse_operations_traits::set_all(scale, (float_type) 0.0);\n      for(int c = 0; c < no_chunks; ++c) {\n\tF.get_chunk(i, c) *= E.get_chunk(x,c);\n\tscale += F.get_chunk(i, c);\n      }\n      sse_operations_traits::sum(scale);\n      sse_operations_traits::store(scales(i), scale);\n\n\t\t\t\n      // normalize i'th column\n      scales(i) = 1.0 / scales(i);\n      sse_operations_traits::set_all(scale, scales(i));\n      for(int chunk = 0; chunk < no_chunks; ++chunk)\n\tF.get_chunk(i,chunk) *= scale;\n    }\n  }\n\t\n  template <typename float_type, typename sse_float_type>\n  void\n  HMM<float_type, sse_float_type>::backward(const sequence &obsseq,\n\t\t\t\t\t     const HMMVector<float_type, sse_float_type> &scales,\n\t\t\t\t\t     HMMMatrix<float_type, sse_float_type> &B) {\n    // just making it a little easier on ourselves...\n    const HMMMatrix<float_type, sse_float_type> &T = *trans_prob;\n    const HMMMatrix<float_type, sse_float_type> &E = *emission_prob;\n\n    // boost::shared_ptr<HMMMatrix<float_type, sse_float_type> > T_t_ptr(new HMMMatrix<float_type, sse_float_type>(T.get_no_columns(), T.get_no_rows()));\n    // HMMMatrix<float_type, sse_float_type> &T_t = *T_t_ptr;\n    // T.transpose(T_t);\n\n    const int length = obsseq.size();\n    const int no_chunks = B.get_no_chunks_per_row();\n\t\t\n    // sanity check\n    assert(B.get_no_columns() == no_states);\n    assert(B.get_no_rows() == length);\n    assert(scales.get_size() == length);\n\t\t\n    // Fill in the last column of B\n    sse_float_type scale;\n    sse_operations_traits::set_all(scale, scales(length - 1));\n    int sc;\n    for(sc = 0; sc < no_chunks; ++sc)\n      B.get_chunk(length-1,sc) = scale;\n\t\t\n    // Recursion\n    for(int i = length - 1; i > 0; --i) { // fill in the (i-1)'th row of B\n      int x = obsseq[i];\n      #ifdef WITH_OMP\n      #pragma omp parallel for\n      #endif\n      for(int s = 0; s < no_states; ++s) { // fill in B(i-1,s)\n\tsse_float_type prob_sum;\n\tsse_operations_traits::set_all(prob_sum, 0.0);\n\n\tfor(int chunk = 0; chunk < no_chunks; ++chunk)\n\t  prob_sum += T.get_chunk(s, chunk) * E.get_chunk(x, chunk) * B.get_chunk(i, chunk);\n\n\tsse_operations_traits::sum(prob_sum);\n\tfloat_type sum;\n\tsse_operations_traits::store(sum, prob_sum);\n\tB(i-1,s) = sum * scales(i-1);\n      }\n    }\n  }\n\t\n  template <typename float_type, typename sse_float_type>\n  float_type\n  HMM<float_type, sse_float_type>::likelihood(const HMMVector<float_type, sse_float_type> &scales) {\n    float_type likelihood = 0.0;\n    for (int s = 0; s < scales.get_size(); ++s) {\n      likelihood -= std::log(scales(s));\n    }\n    return likelihood;\n  }\n\t\n  template <typename float_type, typename sse_float_type>\n  void\n  HMM<float_type, sse_float_type>::baum_welch(const sequence &obsseq,\n\t\t\t\t\t       const HMMMatrix<float_type, sse_float_type> &F,\n\t\t\t\t\t       const HMMMatrix<float_type, sse_float_type> &B, \n\t\t\t\t\t       const HMMVector<float_type, sse_float_type> &scales,\n\t\t\t\t\t       HMMVector<float_type, sse_float_type> &new_pi,\n\t\t\t\t\t       HMMMatrix<float_type, sse_float_type> &new_T,\n\t\t\t\t\t       HMMMatrix<float_type, sse_float_type> &new_E) {\n\t\t\n    // easier reference\n    HMMMatrix<float_type, sse_float_type> &T = *trans_prob;\n    HMMMatrix<float_type, sse_float_type> &E = *emission_prob;\n\t\t\n    const int length = obsseq.size();\n    const int no_chunks = B.get_no_chunks_per_row();\n\t\t\n    // sanity check\n    assert(new_T.get_no_columns() == no_states);\n    assert(new_T.get_no_rows() ==  no_states);\n    assert(new_E.get_no_columns() == no_states);\n    assert(new_E.get_no_rows() == alphabet_size);\n    assert(new_pi.get_size() == no_states);\n    assert(scales.get_size() == length);\n    assert(F.get_no_rows() == length);\n    assert(F.get_no_columns() == no_states);\n    assert(B.get_no_rows() == length);\n    assert(B.get_no_columns() == no_states);\n\t\t\n    // initialise\n    new_pi.reset();\n    new_T.reset();\n    new_E.reset();\n\n    // compute counts\n    HMMVector<float_type, sse_float_type> pi_counts(no_states);\n    HMMMatrix<float_type, sse_float_type> T_counts(no_states, no_states);\n    HMMMatrix<float_type, sse_float_type> E_counts(alphabet_size, no_states);\n\t\t\n    // compute new_pi and initialize E_counts\n    unsigned x = obsseq[0];\n    sse_float_type scale;\n    sse_operations_traits::set_all(scale, (float_type) (1.0/scales(0)));\n    for (int sc = 0; sc < no_chunks; ++sc) {\n      sse_float_type temp = (F.get_chunk(0,sc) * B.get_chunk(0,sc)) * scale;\n      new_pi.get_chunk(sc) = temp;\n      E_counts.get_chunk(x, sc) += temp;\n    }\n\t\t\n    // compute transition and emission counts\n    for (int i = 1; i < length; ++i) {\n      x = obsseq[i];\n      #ifdef WITH_OMP\n      #pragma omp parallel for\n      #endif\n      for(int j = 0; j < no_states; ++j) {\n\t// transition counts\n\tsse_float_type prev_forward;\n\tsse_operations_traits::set_all(prev_forward, F(i-1, j));\n\tfor(int chunk = 0; chunk < no_chunks; ++chunk) {\n\t  T_counts.get_chunk(j, chunk) += prev_forward * \n\t    T.get_chunk(j,chunk) * \n\t    E.get_chunk(x,chunk) * \n\t    B.get_chunk(i,chunk);\n\t}\n      }\n      // emission counts\n      sse_operations_traits::set_all(scale, (float_type) (1.0/scales(i)));\n      for(int chunk = 0; chunk < no_chunks; ++chunk)\n\tE_counts.get_chunk(x,chunk) += F.get_chunk(i, chunk) * \n\t  B.get_chunk(i, chunk) * scale;\n    }\n\n    // compute new_T and new_E by normalizing counts\n    for (int s = 0; s < no_states; ++s) {\n      // transition probabilities\n      float_type sum = 0.0;\n      for (int dst_state = 0; dst_state < no_states; ++dst_state)\n        sum += T_counts(s, dst_state);\n      for (int dst_state = 0; dst_state < no_states; ++dst_state)\n        new_T(s, dst_state) = T_counts(s, dst_state) / sum;\n\n      // emission probabilities\n      sum = 0.0;\n      for (int sym = 0; sym < alphabet_size; ++sym)\n        sum += E_counts(sym, s);\n      for (int sym = 0; sym < alphabet_size; ++sym)\n        new_E(sym, s) = E_counts(sym, s) / sum;\n    }\n  }\n\n  template <typename float_type, typename sse_float_type>\n  float_type\n  HMM<float_type, sse_float_type>::viterbi(const sequence &obsseq, sequence &hiddenseq) {\n    // just making it a bit easier on ourselves...\n    const HMMVector<float_type, sse_float_type> &pi = *initial_prob;\n    const HMMMatrix<float_type, sse_float_type> &T = *trans_prob;\n    const HMMMatrix<float_type, sse_float_type> &E = *emission_prob;\n    \n    // sanity check\n    assert(obsseq.size() == hiddenseq.size());\n\n    // Set up internal data structures\n    const int length = obsseq.size();\n    \n    HMMMatrix<float_type, sse_float_type> path_probs(length, no_states);\n    \n    const int no_chunks = path_probs.get_no_chunks_per_row();\n    \n    boost::shared_ptr<HMMMatrix<float_type, sse_float_type> > T_t_ptr(new HMMMatrix<float_type, sse_float_type>(T.get_no_columns(), T.get_no_rows()));\n    boost::shared_ptr<HMMMatrix<float_type, sse_float_type> > T_t_log_ptr(new HMMMatrix<float_type, sse_float_type>(T.get_no_rows(), T.get_no_columns()));\n    HMMMatrix<float_type, sse_float_type> &T_t_log = *T_t_log_ptr;\n    \n    boost::shared_ptr<HMMMatrix<float_type, sse_float_type> > E_log_ptr(new HMMMatrix<float_type, sse_float_type>(E.get_no_rows(), E.get_no_columns()));\n    HMMMatrix<float_type, sse_float_type> &E_log = *E_log_ptr;\n\n    // construct T_t_log and E_log\n    T.transpose(*T_t_ptr);\n    (*T_t_ptr).log(T_t_log);\n    E.log(E_log);\n\n    // Fill first column of path_probs\n    int x = obsseq[0];\n    for (int i = 0; i < no_states; ++i) {\n      path_probs(0, i) = std::log(pi(i)) + E_log(x, i);\n    }\n\n    // Recursion\n    for(int i = 1; i < length; ++i) { // fill ith row of path_probs\n      x = obsseq[i];\n      #ifdef WITH_OMP\n      #pragma omp parallel for\n      #endif\n      for(int s = 0; s < no_states; ++s) { // fill path_probs(i,s)\n\tsse_float_type max, tmp;\n\tsse_operations_traits::set_all(max, -INFINITY);\n\tfor(int c = 0; c < no_chunks - 1; ++c) { // no_chunks-1 since we don't want to take the max of some garbage.\n\t  tmp = path_probs.get_chunk(i-1, c) + T_t_log.get_chunk(s, c);\n\t  sse_operations_traits::max(max, tmp);\n\t}\n\tfloat_type float_max = sse_operations_traits::hmax(max);\n\tint floats_per_chunk = sizeof(sse_float_type) / sizeof(float_type);\n\tfor(int c = (no_chunks - 1) * floats_per_chunk; c < path_probs.get_no_columns(); ++c)\n\t  float_max = std::max(float_max, path_probs(i-1,c) + T_t_log(s,c));\n\tpath_probs(i, s) = float_max;\n      }\n\n      for(int c = 0; c < no_chunks; ++c) { \n\tpath_probs.get_chunk(i,c) += E_log.get_chunk(x,c);\n      }\n    }\n\n    // Backtracking - final row\n    float_type loglikelihood = -INFINITY;\n    int hidden_state = 0;\n    for(int i = 0; i < no_states; ++i) {\n      if (path_probs(length - 1, i) > loglikelihood) {\n\tloglikelihood = path_probs(length - 1, i);\n\thidden_state = i;\n      }\n    }\n    hiddenseq[length - 1] = hidden_state;\n    \n    // Backtracking - recursion\n    for (unsigned i = length - 1; i > 0; --i) {\n      float_type max = -INFINITY;\n      float_type tmp;\n      int maxidx = 0;\n      for (int s = 0; s < no_states; ++s) {\n\ttmp = path_probs(i-1, s) + T_t_log(hidden_state, s);\n\tif(tmp > max) {\n\t  max = tmp;\n\t  maxidx = s;\n\t}\n      }\n      hidden_state = maxidx;\n      hiddenseq[i-1] = hidden_state;\n    }\n\n    return loglikelihood;\n  }\n  \n  template <typename float_type, typename sse_float_type>\n  void\n  HMM<float_type, sse_float_type>::posterior_decoding(const sequence &obsseq,\n\t\t\t\t\t\t       const HMMMatrix<float_type, sse_float_type> &F,\n\t\t\t\t\t\t       const HMMMatrix<float_type, sse_float_type> &B, \n\t\t\t\t\t\t       const HMMVector<float_type, sse_float_type> &scales, \n\t\t\t\t\t\t       HMMMatrix<float_type, sse_float_type> &post) {\n    const int length = obsseq.size();\n    const int no_chunks = F.get_no_chunks_per_row();\n    #ifdef WITH_OMP\n    #pragma omp parallel for\n    #endif\n    for (int i = 0; i < length; ++i) {\n      sse_float_type scale;\n      sse_operations_traits::set_all(scale, (float_type) (1.0/scales(i)));\n      for (int chunk = 0; chunk < no_chunks; ++chunk) {\n\tpost.get_chunk(i, chunk) = F.get_chunk(i, chunk) * B.get_chunk(i, chunk) * scale;\n      }\n    }\n  }\n  \n} // end of namespace\n\n#endif\n", "meta": {"hexsha": "ac4b173ea4e21398fc4dd73bdbd45d9931fdaa48", "size": 24974, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Trash/sandbox/hmm/HMMlib-1.0.2/HMMlib/hmm.hpp", "max_stars_repo_name": "ruslankuzmin/julia", "max_stars_repo_head_hexsha": "2ad5bfb9c9684b1c800e96732a9e2f1e844b856f", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 36.0, "max_stars_repo_stars_event_min_datetime": "2015-03-02T09:30:35.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-11T07:07:57.000Z", "max_issues_repo_path": "Trash/sandbox/hmm/HMMlib-1.0.2/HMMlib/hmm.hpp", "max_issues_repo_name": "ruslankuzmin/julia", "max_issues_repo_head_hexsha": "2ad5bfb9c9684b1c800e96732a9e2f1e844b856f", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2016-04-01T21:28:24.000Z", "max_issues_repo_issues_event_max_datetime": "2018-03-30T21:39:28.000Z", "max_forks_repo_path": "Trash/sandbox/hmm/HMMlib-1.0.2/HMMlib/hmm.hpp", "max_forks_repo_name": "ruslankuzmin/julia", "max_forks_repo_head_hexsha": "2ad5bfb9c9684b1c800e96732a9e2f1e844b856f", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 17.0, "max_forks_repo_forks_event_min_datetime": "2015-03-02T18:48:45.000Z", "max_forks_repo_forks_event_max_datetime": "2019-03-12T06:44:08.000Z", "avg_line_length": 40.5422077922, "max_line_length": 211, "alphanum_fraction": 0.6601265316, "num_tokens": 6872, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7310585903489891, "lm_q2_score": 0.4378234991142019, "lm_q1q2_score": 0.3200746300840903}}
{"text": "#ifndef STAN_MATH_REV_MAT_FUN_MULTIPLY_HPP\n#define STAN_MATH_REV_MAT_FUN_MULTIPLY_HPP\n\n#include <stan/math/prim/mat/fun/Eigen.hpp>\n#include <stan/math/prim/mat/fun/typedefs.hpp>\n#include <stan/math/rev/scal/fun/value_of_rec.hpp>\n#include <stan/math/rev/scal/fun/value_of.hpp>\n#include <stan/math/rev/mat/fun/to_var.hpp>\n#include <stan/math/rev/core.hpp>\n#include <stan/math/prim/mat/fun/value_of_rec.hpp>\n#include <stan/math/prim/mat/err/check_multiplicable.hpp>\n#include <stan/math/prim/scal/err/check_not_nan.hpp>\n#include <boost/math/tools/promotion.hpp>\n#include <boost/utility/enable_if.hpp>\n#include <boost/type_traits.hpp>\n\nnamespace stan {\n  namespace math {\n\n    /**\n     * This is a subclass of the vari class for matrix\n     * multiplication A * B where A is N by M and B\n     * is M by K.\n     *\n     * The class stores the structure of each matrix,\n     * the double values of A and B, and pointers to\n     * the varis for A and B if A or B is a var. It\n     * also instantiates and stores pointers to\n     * varis for all elements of A * B.\n     *\n     * @tparam TA Scalar type for matrix A\n     * @tparam RA Rows for matrix A\n     * @tparam CA Columns for matrix A, Rows for matrix B\n     * @tparam TB Scalar type for matrix B\n     * @tparam CB Columns for matrix B\n     */\n    template <typename TA, int RA, int CA, typename TB, int CB>\n    class multiply_mat_vari : public vari {\n    public:\n      int A_rows_, A_cols_, B_cols_, A_size_, B_size_;\n      double* Ad_;\n      double* Bd_;\n      vari** variRefA_;\n      vari** variRefB_;\n      vari** variRefAB_;\n\n      /**\n       * Constructor for multiply_mat_vari.\n       *\n       * All memory allocated in\n       * ChainableStack's stack_alloc arena.\n       *\n       * It is critical for the efficiency of this object\n       * that the constructor create new varis that aren't\n       * popped onto the var_stack_, but rather are\n       * popped onto the var_nochain_stack_. This is\n       * controlled to the second argument to\n       * vari's constructor.\n       *\n       * @param A matrix\n       * @param B matrix\n       */\n      multiply_mat_vari(const Eigen::Matrix<TA, RA, CA>& A,\n                        const Eigen::Matrix<TB, CA, CB>& B)\n        : vari(0.0),\n          A_rows_(A.rows()), A_cols_(A.cols()),\n          B_cols_(B.cols()), A_size_(A.size()), B_size_(B.size()),\n          Ad_(ChainableStack::memalloc_.alloc_array<double>(A_size_)),\n          Bd_(ChainableStack::memalloc_.alloc_array<double>(B_size_)),\n          variRefA_(ChainableStack::memalloc_.alloc_array<vari*>(A_size_)),\n          variRefB_(ChainableStack::memalloc_.alloc_array<vari*>(B_size_)),\n          variRefAB_(ChainableStack::memalloc_.alloc_array<vari*>(A_rows_\n                                                                  * B_cols_)) {\n        using Eigen::Map;\n        using Eigen::MatrixXd;\n        for (size_type i = 0; i < A.size(); ++i) {\n          variRefA_[i] = A.coeffRef(i).vi_;\n          Ad_[i] = A.coeffRef(i).val();\n        }\n        for (size_type i = 0; i < B.size(); ++i) {\n          variRefB_[i] = B.coeffRef(i).vi_;\n          Bd_[i] = B.coeffRef(i).val();\n        }\n        MatrixXd AB\n          = Map<MatrixXd>(Ad_, A_rows_, A_cols_)\n          * Map<MatrixXd>(Bd_, A_cols_, B_cols_);\n        for (size_type i = 0; i < AB.size(); ++i)\n          variRefAB_[i] = new vari(AB.coeffRef(i), false);\n      }\n\n      virtual void chain() {\n        using Eigen::MatrixXd;\n        using Eigen::Map;\n        MatrixXd adjAB(A_rows_, B_cols_);\n        MatrixXd adjA(A_rows_, A_cols_);\n        MatrixXd adjB(A_cols_, B_cols_);\n\n        for (size_type i = 0; i < adjAB.size(); ++i)\n          adjAB(i) = variRefAB_[i]->adj_;\n        adjA = adjAB\n          * Map<MatrixXd>(Bd_, A_cols_, B_cols_).transpose();\n        adjB = Map<MatrixXd>(Ad_, A_rows_, A_cols_).transpose()\n          * adjAB;\n        for (size_type i = 0; i < A_size_; ++i)\n          variRefA_[i]->adj_ += adjA(i);\n        for (size_type i = 0; i < B_size_; ++i)\n          variRefB_[i]->adj_ += adjB(i);\n      }\n    };\n\n    /**\n     * This is a subclass of the vari class for matrix\n     * multiplication A * B where A is 1 by M and B\n     * is M by 1.\n     *\n     * The class stores the structure of each matrix,\n     * the double values of A and B, and pointers to\n     * the varis for A and B if A or B is a var. It\n     * also instantiates and stores pointers to\n     * varis for all elements of A * B.\n     *\n     * @tparam TA Scalar type for matrix A\n     * @tparam CA Columns for matrix A, Rows for matrix B\n     * @tparam TB Scalar type for matrix B\n     */\n    template <typename TA, int CA, typename TB>\n    class multiply_mat_vari<TA, 1, CA, TB, 1> : public vari {\n    public:\n      int size_;\n      double* Ad_;\n      double* Bd_;\n      vari** variRefA_;\n      vari** variRefB_;\n      vari* variRefAB_;\n\n      /**\n       * Constructor for multiply_mat_vari.\n       *\n       * All memory allocated in\n       * ChainableStack's stack_alloc arena.\n       *\n       * It is critical for the efficiency of this object\n       * that the constructor create new varis that aren't\n       * popped onto the var_stack_, but rather are\n       * popped onto the var_nochain_stack_. This is\n       * controlled to the second argument to\n       * vari's constructor.\n       *\n       * @param A row vector\n       * @param B vector\n       */\n      multiply_mat_vari(const Eigen::Matrix<TA, 1, CA>& A,\n                        const Eigen::Matrix<TB, CA, 1>& B)\n        : vari(0.0),\n          size_(A.cols()),\n          Ad_(ChainableStack::memalloc_.alloc_array<double>(size_)),\n          Bd_(ChainableStack::memalloc_.alloc_array<double>(size_)),\n          variRefA_(ChainableStack::memalloc_.alloc_array<vari*>(size_)),\n          variRefB_(ChainableStack::memalloc_.alloc_array<vari*>(size_)) {\n        using Eigen::Map;\n        using Eigen::VectorXd;\n        using Eigen::RowVectorXd;\n        for (size_type i = 0; i < size_; ++i) {\n          variRefA_[i] = A.coeffRef(i).vi_;\n          Ad_[i] = A.coeffRef(i).val();\n        }\n        for (size_type i = 0; i < size_; ++i) {\n          variRefB_[i] = B.coeffRef(i).vi_;\n          Bd_[i] = B.coeffRef(i).val();\n        }\n        double AB = Map<RowVectorXd>(Ad_, 1, size_)\n          * Map<VectorXd>(Bd_, size_, 1);\n        variRefAB_ = new vari(AB, false);\n      }\n\n      virtual void chain() {\n        using Eigen::VectorXd;\n        using Eigen::RowVectorXd;\n        using Eigen::Map;\n        double adjAB;\n        RowVectorXd adjA(size_);\n        VectorXd adjB(size_);\n\n        adjAB = variRefAB_->adj_;\n        adjA = adjAB\n          * Map<VectorXd>(Bd_, size_, 1).transpose();\n        adjB = Map<RowVectorXd>(Ad_, 1, size_).transpose()\n          * adjAB;\n        for (size_type i = 0; i < size_; ++i)\n          variRefA_[i]->adj_ += adjA(i);\n        for (size_type i = 0; i < size_; ++i)\n          variRefB_[i]->adj_ += adjB(i);\n      }\n    };\n\n    /**\n     * This is a subclass of the vari class for matrix\n     * multiplication A * B where A is an N by M\n     * matrix of double and B is M by K.\n     *\n     * The class stores the structure of each matrix,\n     * the double values of A and B, and pointers to\n     * the varis for A and B if A or B is a var. It\n     * also instantiates and stores pointers to\n     * varis for all elements of A * B.\n     *\n     * @tparam RA Rows for matrix A\n     * @tparam CA Columns for matrix A, Rows for matrix B\n     * @tparam TB Scalar type for matrix B\n     * @tparam CB Columns for matrix B\n     */\n    template <int RA, int CA, typename TB, int CB>\n    class multiply_mat_vari<double, RA, CA, TB, CB> : public vari {\n    public:\n      int A_rows_, A_cols_, B_cols_, A_size_, B_size_;\n      double* Ad_;\n      double* Bd_;\n      vari** variRefB_;\n      vari** variRefAB_;\n\n      /**\n       * Constructor for multiply_mat_vari.\n       *\n       * All memory allocated in\n       * ChainableStack's stack_alloc arena.\n       *\n       * It is critical for the efficiency of this object\n       * that the constructor create new varis that aren't\n       * popped onto the var_stack_, but rather are\n       * popped onto the var_nochain_stack_. This is\n       * controlled to the second argument to\n       * vari's constructor.\n       *\n       * @param A row vector\n       * @param B vector\n       */\n      multiply_mat_vari(const Eigen::Matrix<double, RA, CA>& A,\n                        const Eigen::Matrix<TB, CA, CB>& B)\n        : vari(0.0),\n          A_rows_(A.rows()), A_cols_(A.cols()),\n          B_cols_(B.cols()), A_size_(A.size()), B_size_(B.size()),\n          Ad_(ChainableStack::memalloc_.alloc_array<double>(A_size_)),\n          Bd_(ChainableStack::memalloc_.alloc_array<double>(B_size_)),\n          variRefB_(ChainableStack::memalloc_.alloc_array<vari*>(B_size_)),\n          variRefAB_(ChainableStack::memalloc_.alloc_array<vari*>(A_rows_\n                                                                  * B_cols_)) {\n        using Eigen::MatrixXd;\n        using Eigen::Map;\n        for (size_type i = 0; i < A.size(); ++i)\n          Ad_[i] = A.coeffRef(i);\n        for (size_type i = 0; i < B.size(); ++i) {\n          variRefB_[i] = B.coeffRef(i).vi_;\n          Bd_[i] = B.coeffRef(i).val();\n        }\n        MatrixXd AB\n          = Map<MatrixXd>(Ad_, A_rows_, A_cols_)\n          * Map<MatrixXd>(Bd_, A_cols_, B_cols_);\n        for (size_type i = 0; i < AB.size(); ++i)\n          variRefAB_[i] = new vari(AB.coeffRef(i), false);\n      }\n\n      virtual void chain() {\n        using Eigen::MatrixXd;\n        using Eigen::Map;\n        MatrixXd adjAB(A_rows_, B_cols_);\n        MatrixXd adjB(A_cols_, B_cols_);\n\n        for (size_type i = 0; i < adjAB.size(); ++i)\n          adjAB(i) = variRefAB_[i]->adj_;\n        adjB = Map<MatrixXd>(Ad_, A_rows_, A_cols_).transpose()\n          * adjAB;\n        for (size_type i = 0; i < B_size_; ++i)\n          variRefB_[i]->adj_ += adjB(i);\n      }\n    };\n\n    /**\n     * This is a subclass of the vari class for matrix\n     * multiplication A * B where A is a double\n     * row vector of length M and B is a vector of\n     * length M.\n     *\n     * The class stores the structure of each matrix,\n     * the double values of A and B, and pointers to\n     * the varis for A and B if A or B is a var. It\n     * also instantiates and stores pointers to\n     * varis for all elements of A * B.\n     *\n     * @tparam CA Columns for matrix A, Rows for matrix B\n     * @tparam TB Scalar type for matrix B\n     */\n    template <int CA, typename TB>\n    class multiply_mat_vari<double, 1, CA, TB, 1> : public vari {\n    public:\n      int size_;\n      double* Ad_;\n      double* Bd_;\n      vari** variRefB_;\n      vari* variRefAB_;\n\n      /**\n       * Constructor for multiply_mat_vari.\n       *\n       * All memory allocated in\n       * ChainableStack's stack_alloc arena.\n       *\n       * It is critical for the efficiency of this object\n       * that the constructor create new varis that aren't\n       * popped onto the var_stack_, but rather are\n       * popped onto the var_nochain_stack_. This is\n       * controlled to the second argument to\n       * vari's constructor.\n       *\n       * @param A row vector\n       * @param B vector\n       */\n      multiply_mat_vari(const Eigen::Matrix<double, 1, CA>& A,\n                        const Eigen::Matrix<TB, CA, 1>& B)\n        : vari(0.0),\n          size_(A.cols()),\n          Ad_(ChainableStack::memalloc_.alloc_array<double>(size_)),\n          Bd_(ChainableStack::memalloc_.alloc_array<double>(size_)),\n          variRefB_(ChainableStack::memalloc_.alloc_array<vari*>(size_)) {\n        using Eigen::Map;\n        using Eigen::VectorXd;\n        using Eigen::RowVectorXd;\n        for (size_type i = 0; i < size_; ++i)\n          Ad_[i] = A.coeffRef(i);\n        for (size_type i = 0; i < size_; ++i) {\n          variRefB_[i] = B.coeffRef(i).vi_;\n          Bd_[i] = B.coeffRef(i).val();\n        }\n        double AB\n          = Eigen::Map<RowVectorXd>(Ad_, 1, size_)\n          * Eigen::Map<VectorXd>(Bd_, size_, 1);\n        variRefAB_ = new vari(AB, false);\n      }\n\n      virtual void chain() {\n        using Eigen::RowVectorXd;\n        using Eigen::VectorXd;\n        using Eigen::Map;\n        double adjAB;\n        VectorXd adjB(size_);\n\n        adjAB = variRefAB_->adj_;\n        adjB = Map<RowVectorXd>(Ad_, 1, size_).transpose()\n          * adjAB;\n        for (size_type i = 0; i < size_; ++i)\n          variRefB_[i]->adj_ += adjB(i);\n      }\n    };\n\n    /**\n     * This is a subclass of the vari class for matrix\n     * multiplication A * B where A is N by M and B\n     * is an M by K matrix of doubles.\n     *\n     * The class stores the structure of each matrix,\n     * the double values of A and B, and pointers to\n     * the varis for A and B if A or B is a var. It\n     * also instantiates and stores pointers to\n     * varis for all elements of A * B.\n     *\n     * @tparam TA Scalar type for matrix A\n     * @tparam RA Rows for matrix A\n     * @tparam CA Columns for matrix A, Rows for matrix B\n     * @tparam CB Columns for matrix B\n     */\n    template <typename TA, int RA, int CA, int CB>\n    class multiply_mat_vari<TA, RA, CA, double, CB> : public vari {\n    public:\n      int A_rows_, A_cols_, B_cols_, A_size_, B_size_;\n      double* Ad_;\n      double* Bd_;\n      vari** variRefA_;\n      vari** variRefAB_;\n\n      /**\n       * Constructor for multiply_mat_vari.\n       *\n       * All memory allocated in\n       * ChainableStack's stack_alloc arena.\n       *\n       * It is critical for the efficiency of this object\n       * that the constructor create new varis that aren't\n       * popped onto the var_stack_, but rather are\n       * popped onto the var_nochain_stack_. This is\n       * controlled to the second argument to\n       * vari's constructor.\n       *\n       * @param A row vector\n       * @param B vector\n       */\n      multiply_mat_vari(const Eigen::Matrix<TA, RA, CA>& A,\n                        const Eigen::Matrix<double, CA, CB>& B)\n        : vari(0.0),\n          A_rows_(A.rows()), A_cols_(A.cols()),\n          B_cols_(B.cols()), A_size_(A.size()), B_size_(B.size()),\n          Ad_(ChainableStack::memalloc_.alloc_array<double>(A_size_)),\n          Bd_(ChainableStack::memalloc_.alloc_array<double>(B_size_)),\n          variRefA_(ChainableStack::memalloc_.alloc_array<vari*>(A_size_)),\n          variRefAB_(ChainableStack::memalloc_.alloc_array<vari*>(A_rows_\n                                                                  * B_cols_)) {\n        using Eigen::Map;\n        using Eigen::MatrixXd;\n        for (size_type i = 0; i < A_size_; ++i) {\n          variRefA_[i] = A.coeffRef(i).vi_;\n          Ad_[i] = A.coeffRef(i).val();\n        }\n        for (size_type i = 0; i < B_size_; ++i) {\n          Bd_[i] = B.coeffRef(i);\n        }\n        MatrixXd AB\n          = Map<MatrixXd>(Ad_, A_rows_, A_cols_)\n          * Map<MatrixXd>(Bd_, A_cols_, B_cols_);\n        for (size_type i = 0; i < AB.size(); ++i)\n          variRefAB_[i] = new vari(AB.coeffRef(i), false);\n      }\n\n      virtual void chain() {\n        using Eigen::MatrixXd;\n        using Eigen::Map;\n        MatrixXd adjAB(A_rows_, B_cols_);\n        MatrixXd adjA(A_rows_, A_cols_);\n\n        for (size_type i = 0; i < adjAB.size(); ++i)\n          adjAB(i) = variRefAB_[i]->adj_;\n        adjA = adjAB * Map<MatrixXd>(Bd_, A_cols_, B_cols_).transpose();\n        for (size_type i = 0; i < A_size_; ++i)\n          variRefA_[i]->adj_ += adjA(i);\n      }\n    };\n\n    /**\n     * This is a subclass of the vari class for matrix\n     * multiplication A * B where A is a row\n     * vector of length M and B is a vector of length M\n     * of doubles.\n     *\n     * The class stores the structure of each matrix,\n     * the double values of A and B, and pointers to\n     * the varis for A and B if A or B is a var. It\n     * also instantiates and stores pointers to\n     * varis for all elements of A * B.\n     *\n     * @tparam TA Scalar type for matrix A\n     * @tparam RA Rows for matrix A\n     * @tparam CA Columns for matrix A, Rows for matrix B\n     * @tparam TB Scalar type for matrix B\n     * @tparam CB Columns for matrix B\n     */\n    template <typename TA, int CA>\n    class multiply_mat_vari<TA, 1, CA, double, 1> : public vari {\n    public:\n      int size_;\n      double* Ad_;\n      double* Bd_;\n      vari** variRefA_;\n      vari* variRefAB_;\n\n      /**\n       * Constructor for multiply_mat_vari.\n       *\n       * All memory allocated in\n       * ChainableStack's stack_alloc arena.\n       *\n       * It is critical for the efficiency of this object\n       * that the constructor create new varis that aren't\n       * popped onto the var_stack_, but rather are\n       * popped onto the var_nochain_stack_. This is\n       * controlled to the second argument to\n       * vari's constructor.\n       *\n       * @param A row vector\n       * @param B vector\n       */\n      multiply_mat_vari(const Eigen::Matrix<TA, 1, CA>& A,\n                        const Eigen::Matrix<double, CA, 1>& B)\n        : vari(0.0),\n          size_(A.cols()),\n          Ad_(ChainableStack::memalloc_.alloc_array<double>(size_)),\n          Bd_(ChainableStack::memalloc_.alloc_array<double>(size_)),\n          variRefA_(ChainableStack::memalloc_.alloc_array<vari*>(size_)) {\n        using Eigen::Map;\n        using Eigen::VectorXd;\n        using Eigen::RowVectorXd;\n        for (size_type i = 0; i < size_; ++i) {\n          variRefA_[i] = A.coeffRef(i).vi_;\n          Ad_[i] = A.coeffRef(i).val();\n        }\n        for (size_type i = 0; i < size_; ++i)\n          Bd_[i] = B.coeffRef(i);\n        double AB\n          = Map<RowVectorXd>(Ad_, 1, size_)\n          * Map<VectorXd>(Bd_, size_, 1);\n        variRefAB_ = new vari(AB, false);\n      }\n\n      virtual void chain() {\n        using Eigen::Map;\n        using Eigen::VectorXd;\n        using Eigen::RowVectorXd;\n        double adjAB;\n        RowVectorXd adjA(size_);\n\n        adjAB = variRefAB_->adj_;\n        adjA = adjAB\n          * Map<VectorXd>(Bd_, size_, 1).transpose();\n        for (size_type i = 0; i < size_; ++i)\n          variRefA_[i]->adj_ += adjA(i);\n      }\n    };\n\n    /**\n     * Return the product of two scalars.\n     * @tparam T1 scalar type of v\n     * @tparam T2 scalar type of c\n     * @param[in] v First scalar\n     * @param[in] c Specified scalar\n     * @return Product of scalars\n     */\n    template <typename T1, typename T2>\n    inline typename\n    boost::enable_if_c<\n      (boost::is_scalar<T1>::value || boost::is_same<T1, var>::value)\n      && (boost::is_scalar<T2>::value || boost::is_same<T2, var>::value),\n      typename boost::math::tools::promote_args<T1, T2>::type>::type\n    multiply(const T1& v, const T2& c) {\n      return v * c;\n    }\n\n    /**\n     * Return the product of scalar and matrix.\n     * @tparam T1 scalar type v\n     * @tparam T2 scalar type matrix m\n     * @tparam R2 Rows matrix m\n     * @tparam C2 Columns matrix m\n     * @param[in] c Specified scalar\n     * @param[in] m Matrix\n     * @return Product of scalar and matrix\n     */\n    template<typename T1, typename T2, int R2, int C2>\n    inline Eigen::Matrix<var, R2, C2>\n    multiply(const T1& c, const Eigen::Matrix<T2, R2, C2>& m) {\n      // TODO(trangucci) pull out to eliminate overpromotion of one side\n      // move to matrix.hpp w. promotion?\n      return to_var(m) * to_var(c);\n    }\n\n    /**\n     * Return the product of scalar and matrix.\n     * @tparam T1 scalar type matrix m\n     * @tparam T2 scalar type v\n     * @tparam R1 Rows matrix m\n     * @tparam C1 Columns matrix m\n     * @param[in] c Specified scalar\n     * @param[in] m Matrix\n     * @return Product of scalar and matrix\n     */\n    template<typename T1, int R1, int C1, typename T2>\n    inline Eigen::Matrix<var, R1, C1>\n    multiply(const Eigen::Matrix<T1, R1, C1>& m, const T2& c) {\n      // TODO(trangucci) pull out to eliminate overpromotion of one side\n      // move to matrix.hpp w. promotion?\n      return to_var(m) * to_var(c);\n    }\n\n    /**\n     * Return the product of two matrices.\n     * @tparam TA scalar type matrix A\n     * @tparam RA Rows matrix A\n     * @tparam CA Columns matrix A\n     * @tparam TB scalar type matrix B\n     * @tparam RB Rows matrix B\n     * @tparam CB Columns matrix B\n     * @param[in] A Matrix\n     * @param[in] B Matrix\n     * @return Product of scalar and matrix.\n     */\n    template <typename TA, int RA, int CA, typename TB, int CB>\n    inline typename\n    boost::enable_if_c<boost::is_same<TA, var>::value\n                       || boost::is_same<TB, var>::value,\n                       Eigen::Matrix<var, RA, CB> >::type\n    multiply(const Eigen::Matrix<TA, RA, CA> &A,\n             const Eigen::Matrix<TB, CA, CB> &B) {\n      check_multiplicable(\"multiply\", \"A\", A, \"B\", B);\n      check_not_nan(\"multiply\", \"A\", A);\n      check_not_nan(\"multiply\", \"B\", B);\n\n      // Memory managed with the arena allocator.\n      multiply_mat_vari<TA, RA, CA, TB, CB> *baseVari\n        = new multiply_mat_vari<TA, RA, CA, TB, CB>(A, B);\n      Eigen::Matrix<var, RA, CB> AB_v(A.rows(), B.cols());\n      for (size_type i = 0; i < AB_v.size(); ++i) {\n        AB_v.coeffRef(i).vi_ = baseVari->variRefAB_[i];\n      }\n      return AB_v;\n    }\n\n    /**\n     * Return the scalar product of a row vector and\n     * a vector.\n     * @tparam TA scalar type row vector A\n     * @tparam CA Columns matrix A\n     * @tparam TB scalar type vector B\n     * @param[in] A Row vector\n     * @param[in] B Column vector\n     * @return Scalar product of row vector and vector\n     */\n    template <typename TA, int CA, typename TB>\n    inline typename\n    boost::enable_if_c<boost::is_same<TA, var>::value\n                       || boost::is_same<TB, var>::value, var>::type\n    multiply(const Eigen::Matrix<TA, 1, CA> &A,\n             const Eigen::Matrix<TB, CA, 1> &B) {\n      check_multiplicable(\"multiply\", \"A\", A, \"B\", B);\n      check_not_nan(\"multiply\", \"A\", A);\n      check_not_nan(\"multiply\", \"B\", B);\n\n      // Memory managed with the arena allocator.\n      multiply_mat_vari<TA, 1, CA, TB, 1> *baseVari\n        = new multiply_mat_vari<TA, 1, CA, TB, 1>(A, B);\n      var AB_v;\n      AB_v.vi_ = baseVari->variRefAB_;\n      return AB_v;\n    }\n  }\n}\n#endif\n", "meta": {"hexsha": "c49b379953245d25a6f80b8dd73afb02a5165d69", "size": 22178, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "cmdstan/stan/lib/stan_math/stan/math/rev/mat/fun/multiply.hpp", "max_stars_repo_name": "yizhang-cae/torsten", "max_stars_repo_head_hexsha": "dc82080ca032325040844cbabe81c9a2b5e046f9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cmdstan/stan/lib/stan_math/stan/math/rev/mat/fun/multiply.hpp", "max_issues_repo_name": "yizhang-cae/torsten", "max_issues_repo_head_hexsha": "dc82080ca032325040844cbabe81c9a2b5e046f9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cmdstan/stan/lib/stan_math/stan/math/rev/mat/fun/multiply.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": 35.0917721519, "max_line_length": 79, "alphanum_fraction": 0.5726395527, "num_tokens": 6066, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7122321964553657, "lm_q2_score": 0.44939263446475963, "lm_q1q2_score": 0.32007190311569905}}
{"text": "#include <cmath>\n#include <algorithm>\n\n#include \"boost/geometry/geometry.hpp\"\n#include <boost/container_hash/hash.hpp>\n#include <memory>\n\n#include \"lsst/pex/exceptions.h\"\n#include \"lsst/geom/Extent.h\"\n#include \"lsst/afw/geom/polygon/Polygon.h\"\n\n#include \"lsst/afw/table/io/OutputArchive.h\"\n#include \"lsst/afw/table/io/InputArchive.h\"\n#include \"lsst/afw/table/io/CatalogVector.h\"\n#include \"lsst/afw/table/aggregates.h\"\n#include \"lsst/afw/table/io/Persistable.hpp\"\n\ntypedef lsst::afw::geom::polygon::Polygon::Point LsstPoint;\ntypedef lsst::afw::geom::polygon::Polygon::Box LsstBox;\ntypedef std::vector<LsstPoint> LsstRing;\ntypedef boost::geometry::model::polygon<LsstPoint> BoostPolygon;\ntypedef boost::geometry::model::box<LsstPoint> BoostBox;\ntypedef boost::geometry::model::linestring<LsstPoint> BoostLineString;\n\nnamespace boost {\nnamespace geometry {\nnamespace traits {\n\n// Setting up LsstPoint\ntemplate <>\nstruct tag<LsstPoint> {\n    typedef point_tag type;\n};\ntemplate <>\nstruct coordinate_type<LsstPoint> {\n    typedef LsstPoint::Element type;\n};\ntemplate <>\nstruct coordinate_system<LsstPoint> {\n    typedef cs::cartesian type;\n};\ntemplate <>\nstruct dimension<LsstPoint> : boost::mpl::int_<2> {};\ntemplate <std::size_t dim>\nstruct access<LsstPoint, dim> {\n    static double get(LsstPoint const& p) { return p[dim]; }\n    static void set(LsstPoint& p, LsstPoint::Element const& value) { p[dim] = value; }\n};\n\n// Setting up LsstBox\n//\n// No setters, because it's inefficient (can't set individual elements of lsst::geom::Box2D directly).\n// For box outputs from boost::geometry we'll use BoostBox and then convert.\ntemplate <>\nstruct tag<LsstBox> {\n    typedef box_tag type;\n};\ntemplate <>\nstruct point_type<LsstBox> {\n    typedef LsstPoint type;\n};\ntemplate <>\nstruct indexed_access<LsstBox, 0, 0> {\n    static double get(LsstBox const& box) { return box.getMinX(); }\n};\ntemplate <>\nstruct indexed_access<LsstBox, 1, 0> {\n    static double get(LsstBox const& box) { return box.getMaxX(); }\n};\ntemplate <>\nstruct indexed_access<LsstBox, 0, 1> {\n    static double get(LsstBox const& box) { return box.getMinY(); }\n};\ntemplate <>\nstruct indexed_access<LsstBox, 1, 1> {\n    static double get(LsstBox const& box) { return box.getMaxY(); }\n};\n\n// Setting up LsstRing\ntemplate <>\nstruct tag<LsstRing> {\n    typedef ring_tag type;\n};\n// template<> struct range_value<LsstRing> { typedef LsstPoint type; };\n}  // namespace traits\n}  // namespace geometry\n}  // namespace boost\n\nnamespace {\n\n/// @internal Convert BoostBox to LsstBox\nLsstBox boostBoxToLsst(BoostBox const& box) { return LsstBox(box.min_corner(), box.max_corner()); }\n\n/// @internal Convert box to corners\nstd::vector<LsstPoint> boxToCorners(LsstBox const& box) {\n    std::vector<LsstPoint> corners;\n    corners.reserve(4);\n    corners.push_back(box.getMin());\n    corners.push_back(LsstPoint(box.getMaxX(), box.getMinY()));\n    corners.push_back(box.getMax());\n    corners.push_back(LsstPoint(box.getMinX(), box.getMaxY()));\n    return corners;\n}\n\n/**\n * @internal Sub-sample a line\n *\n * Add `num` points to `vector` between `first` and `second`\n */\nvoid addSubSampledEdge(std::vector<LsstPoint>& vertices,  // Vector of points to which to add\n                       LsstPoint const& first,            // First vertex defining edge\n                       LsstPoint const& second,           // Second vertex defining edge\n                       size_t const num                   // Number of parts to divide edge into\n) {\n    lsst::geom::Extent2D const delta = (second - first) / num;\n    vertices.push_back(first);\n    for (size_t i = 1; i < num; ++i) {\n        vertices.push_back(first + delta * i);\n    }\n}\n\n/// @internal Calculate area of overlap between polygon and pixel\ndouble pixelOverlap(BoostPolygon const& poly, int const x, int const y) {\n    std::vector<BoostPolygon> overlap;  // Overlap between pixel and polygon\n    LsstBox const pixel(lsst::geom::Point2D(x - 0.5, y - 0.5), lsst::geom::Point2D(x + 0.5, y + 0.5));\n    boost::geometry::intersection(poly, pixel, overlap);\n    double area = 0.0;\n    for (std::vector<BoostPolygon>::const_iterator i = overlap.begin(); i != overlap.end(); ++i) {\n        double const polyArea = boost::geometry::area(*i);\n        area += std::min(polyArea, 1.0);  // remove any rounding error\n    }\n    return area;\n}\n\n/// @internal Set each pixel in a row to the amount of overlap with polygon\nvoid pixelRowOverlap(std::shared_ptr<lsst::afw::image::Image<float>> const image, BoostPolygon const& poly,\n                     int const xStart, int const xStop, int const y) {\n    int x = xStart;\n    for (lsst::afw::image::Image<float>::x_iterator i = image->x_at(x - image->getX0(), y - image->getY0());\n         x <= xStop; ++i, ++x) {\n        *i = pixelOverlap(poly, x, y);\n    }\n}\n\n}  // anonymous namespace\n\nnamespace lsst {\nnamespace afw {\n\ntemplate std::shared_ptr<geom::polygon::Polygon> table::io::PersistableFacade<\n        geom::polygon::Polygon>::dynamicCast(std::shared_ptr<table::io::Persistable> const&);\n\nnamespace geom {\nnamespace polygon {\n\n/// @internal Stream vertices\nstd::ostream& operator<<(std::ostream& os, std::vector<LsstPoint> const& vertices) {\n    os << \"[\";\n    size_t num = vertices.size();\n    for (size_t i = 0; i < num - 1; ++i) {\n        os << vertices[i] << \",\";\n    }\n    os << vertices[vertices.size() - 1] << \"]\";\n    return os;\n}\n\n/// @internal Stream BoostPolygon\nstd::ostream& operator<<(std::ostream& os, BoostPolygon const& poly) {\n    return os << \"BoostPolygon(\" << poly.outer() << \")\";\n}\n\nstd::ostream& operator<<(std::ostream& os, Polygon const& poly) {\n    os << poly.toString();\n    return os;\n}\n\nstruct Polygon::Impl {\n    Impl() : poly() {}\n    explicit Impl(Polygon::Box const& box) : poly() {\n        boost::geometry::assign(poly, box);\n        // Assignment from a box is correctly handled by BoostPolygon, so doesn't need a \"check()\"\n    }\n    explicit Impl(std::vector<LsstPoint> const& vertices) : poly() {\n        boost::geometry::assign(poly, vertices);\n        check();  // because the vertices might not have the correct orientation (CW vs CCW) or be open\n    }\n    explicit Impl(BoostPolygon const& _poly) : poly(_poly) {}\n\n    void check() { boost::geometry::correct(poly); }\n\n    /// @internal Convert collection of Boost polygons to our own\n    static std::vector<std::shared_ptr<Polygon>> convertBoostPolygons(\n            std::vector<BoostPolygon> const& boostPolygons);\n\n    template <class PolyT>\n    bool overlaps(PolyT const& other) const {\n        return !boost::geometry::disjoint(poly, other);\n    }\n\n    template <class PolyT>\n    std::shared_ptr<Polygon> intersectionSingle(PolyT const& other) const;\n\n    template <class PolyT>\n    std::vector<std::shared_ptr<Polygon>> intersection(PolyT const& other) const;\n\n    template <class PolyT>\n    std::shared_ptr<Polygon> unionSingle(PolyT const& other) const;\n\n    template <class PolyT>\n    std::vector<std::shared_ptr<Polygon>> union_(PolyT const& other) const;\n\n    template <class PolyT>\n    std::vector<std::shared_ptr<Polygon>> symDifference(PolyT const& other) const;\n\n    BoostPolygon poly;\n};\n\nstd::vector<std::shared_ptr<Polygon>> Polygon::Impl::convertBoostPolygons(\n        std::vector<BoostPolygon> const& boostPolygons) {\n    std::vector<std::shared_ptr<Polygon>> lsstPolygons;\n    lsstPolygons.reserve(boostPolygons.size());\n    for (std::vector<BoostPolygon>::const_iterator i = boostPolygons.begin(); i != boostPolygons.end(); ++i) {\n        std::shared_ptr<Polygon> tmp(new Polygon(std::shared_ptr<Polygon::Impl>(new Polygon::Impl(*i))));\n        lsstPolygons.push_back(tmp);\n    }\n    return lsstPolygons;\n}\n\ntemplate <class PolyT>\nstd::shared_ptr<Polygon> Polygon::Impl::intersectionSingle(PolyT const& other) const {\n    std::vector<BoostPolygon> result;\n    boost::geometry::intersection(poly, other, result);\n    if (result.size() == 0) {\n        throw LSST_EXCEPT(SinglePolygonException, \"Polygons have no intersection\");\n    }\n    if (result.size() > 1) {\n        throw LSST_EXCEPT(\n                SinglePolygonException,\n                (boost::format(\"Multiple polygons (%d) created by intersection()\") % result.size()).str());\n    }\n    return std::shared_ptr<Polygon>(new Polygon(std::shared_ptr<Impl>(new Impl(result[0]))));\n}\n\ntemplate <class PolyT>\nstd::vector<std::shared_ptr<Polygon>> Polygon::Impl::intersection(PolyT const& other) const {\n    std::vector<BoostPolygon> boostResult;\n    boost::geometry::intersection(poly, other, boostResult);\n    return convertBoostPolygons(boostResult);\n}\n\ntemplate <class PolyT>\nstd::shared_ptr<Polygon> Polygon::Impl::unionSingle(PolyT const& other) const {\n    std::vector<BoostPolygon> result;\n    boost::geometry::union_(poly, other, result);\n    if (result.size() != 1) {\n        throw LSST_EXCEPT(\n                SinglePolygonException,\n                (boost::format(\"Multiple polygons (%d) created by union_()\") % result.size()).str());\n    }\n    return std::shared_ptr<Polygon>(new Polygon(std::shared_ptr<Impl>(new Impl(result[0]))));\n}\n\ntemplate <class PolyT>\nstd::vector<std::shared_ptr<Polygon>> Polygon::Impl::union_(PolyT const& other) const {\n    std::vector<BoostPolygon> boostResult;\n    boost::geometry::union_(poly, other, boostResult);\n    return convertBoostPolygons(boostResult);\n}\n\ntemplate <class PolyT>\nstd::vector<std::shared_ptr<Polygon>> Polygon::Impl::symDifference(PolyT const& other) const {\n    std::vector<BoostPolygon> boostResult;\n    boost::geometry::sym_difference(poly, other, boostResult);\n    return convertBoostPolygons(boostResult);\n}\n\nPolygon::Polygon(Polygon const&) = default;\nPolygon::Polygon(Polygon&&) = default;\nPolygon& Polygon::operator=(Polygon const&) = default;\nPolygon& Polygon::operator=(Polygon&&) = default;\n\nPolygon::~Polygon() = default;\n\nPolygon::Polygon(Polygon::Box const& box) : _impl(new Polygon::Impl(box)) {}\n\nPolygon::Polygon(std::vector<LsstPoint> const& vertices) : _impl(new Polygon::Impl(vertices)) {}\n\nPolygon::Polygon(Polygon::Box const& box, afw::geom::TransformPoint2ToPoint2 const& transform)\n        : _impl(new Polygon::Impl()) {\n    auto corners = transform.applyForward(boxToCorners(box));\n    boost::geometry::assign(_impl->poly, corners);\n    _impl->check();\n}\n\nPolygon::Polygon(Polygon::Box const& box, lsst::geom::AffineTransform const& transform)\n        : _impl(new Polygon::Impl()) {\n    std::vector<LsstPoint> corners = boxToCorners(box);\n    for (std::vector<LsstPoint>::iterator p = corners.begin(); p != corners.end(); ++p) {\n        *p = transform(*p);\n    }\n    boost::geometry::assign(_impl->poly, corners);\n    _impl->check();\n}\n\nsize_t Polygon::getNumEdges() const {\n    // boost::geometry::models::polygon uses a \"closed\" polygon: the start/end point is included twice\n    return boost::geometry::num_points(_impl->poly) - 1;\n}\n\nPolygon::Box Polygon::getBBox() const {\n    return boostBoxToLsst(boost::geometry::return_envelope<BoostBox>(_impl->poly));\n}\n\nLsstPoint Polygon::calculateCenter() const {\n    return boost::geometry::return_centroid<LsstPoint>(_impl->poly);\n}\n\ndouble Polygon::calculateArea() const { return boost::geometry::area(_impl->poly); }\n\ndouble Polygon::calculatePerimeter() const { return boost::geometry::perimeter(_impl->poly); }\n\nstd::vector<std::pair<LsstPoint, LsstPoint>> Polygon::getEdges() const {\n    std::vector<LsstPoint> const vertices = getVertices();\n    std::vector<std::pair<LsstPoint, LsstPoint>> edges;\n    edges.reserve(getNumEdges());\n    for (std::vector<LsstPoint>::const_iterator i = vertices.begin(), j = vertices.begin() + 1;\n         j != vertices.end(); ++i, ++j) {\n        edges.push_back(std::make_pair(*i, *j));\n    }\n    return edges;\n}\n\nstd::vector<LsstPoint> Polygon::getVertices() const { return _impl->poly.outer(); }\n\nstd::vector<LsstPoint>::const_iterator Polygon::begin() const { return _impl->poly.outer().begin(); }\n\nstd::vector<LsstPoint>::const_iterator Polygon::end() const {\n    return _impl->poly.outer().end() - 1;  // Note removal of final \"closed\" point\n}\n\nbool Polygon::operator==(Polygon const& other) const {\n    return boost::geometry::equals(_impl->poly, other._impl->poly);\n}\n\nstd::size_t Polygon::hash_value() const noexcept {\n    // boost::hash allows hash functions to throw, but the container hashes throw\n    // only if the element [geom::Point] has a throwing hash\n    static boost::hash<BoostPolygon::ring_type> polygonHash;\n    return polygonHash(_impl->poly.outer());\n}\n\nbool Polygon::contains(LsstPoint const& point) const { return boost::geometry::within(point, _impl->poly); }\n\nbool Polygon::overlaps(Polygon const& other) const { return _impl->overlaps(other._impl->poly); }\n\nbool Polygon::overlaps(Box const& box) const { return _impl->overlaps(box); }\n\nstd::shared_ptr<Polygon> Polygon::intersectionSingle(Polygon const& other) const {\n    return _impl->intersectionSingle(other._impl->poly);\n}\n\nstd::shared_ptr<Polygon> Polygon::intersectionSingle(Box const& box) const {\n    return _impl->intersectionSingle(box);\n}\n\nstd::vector<std::shared_ptr<Polygon>> Polygon::intersection(Polygon const& other) const {\n    return _impl->intersection(other._impl->poly);\n}\n\nstd::vector<std::shared_ptr<Polygon>> Polygon::intersection(Box const& box) const {\n    return _impl->intersection(box);\n}\n\nstd::shared_ptr<Polygon> Polygon::unionSingle(Polygon const& other) const {\n    return _impl->unionSingle(other._impl->poly);\n}\n\nstd::shared_ptr<Polygon> Polygon::unionSingle(Box const& box) const { return _impl->unionSingle(box); }\n\nstd::vector<std::shared_ptr<Polygon>> Polygon::union_(Polygon const& other) const {\n    return _impl->union_(other._impl->poly);\n}\n\nstd::vector<std::shared_ptr<Polygon>> Polygon::union_(Box const& box) const { return _impl->union_(box); }\n\nstd::vector<std::shared_ptr<Polygon>> Polygon::symDifference(Polygon const& other) const {\n    return _impl->symDifference(other._impl->poly);\n}\n\nstd::vector<std::shared_ptr<Polygon>> Polygon::symDifference(Box const& box) const {\n    return _impl->symDifference(box);\n}\n\nstd::shared_ptr<Polygon> Polygon::simplify(double const distance) const {\n    BoostPolygon result;\n    boost::geometry::simplify(_impl->poly, result, distance);\n    return std::shared_ptr<Polygon>(new Polygon(std::shared_ptr<Impl>(new Impl(result))));\n}\n\nstd::shared_ptr<Polygon> Polygon::convexHull() const {\n    BoostPolygon hull;\n    boost::geometry::convex_hull(_impl->poly, hull);\n    return std::shared_ptr<Polygon>(new Polygon(std::shared_ptr<Impl>(new Impl(hull))));\n}\n\nstd::shared_ptr<Polygon> Polygon::transform(TransformPoint2ToPoint2 const& transform) const {\n    auto newVertices = transform.applyForward(getVertices());\n    return std::shared_ptr<Polygon>(new Polygon(std::shared_ptr<Impl>(new Impl(newVertices))));\n}\n\nstd::shared_ptr<Polygon> Polygon::transform(lsst::geom::AffineTransform const& transform) const {\n    std::vector<LsstPoint> vertices;  // New vertices\n    vertices.reserve(getNumEdges());\n    for (std::vector<LsstPoint>::const_iterator i = _impl->poly.outer().begin();\n         i != _impl->poly.outer().end(); ++i) {\n        vertices.push_back(transform(*i));\n    }\n    return std::shared_ptr<Polygon>(new Polygon(std::shared_ptr<Impl>(new Impl(vertices))));\n}\n\nstd::shared_ptr<Polygon> Polygon::subSample(size_t num) const {\n    std::vector<LsstPoint> vertices;  // New vertices\n    vertices.reserve(getNumEdges() * num);\n    std::vector<std::pair<Point, Point>> edges = getEdges();\n    for (std::vector<std::pair<Point, Point>>::const_iterator i = edges.begin(); i != edges.end(); ++i) {\n        addSubSampledEdge(vertices, i->first, i->second, num);\n    }\n    return std::shared_ptr<Polygon>(new Polygon(std::shared_ptr<Impl>(new Impl(vertices))));\n}\n\nstd::shared_ptr<Polygon> Polygon::subSample(double maxLength) const {\n    std::vector<LsstPoint> vertices;  // New vertices\n    vertices.reserve(getNumEdges() + static_cast<size_t>(::ceil(calculatePerimeter() / maxLength)));\n    std::vector<std::pair<Point, Point>> edges = getEdges();\n    for (std::vector<std::pair<Point, Point>>::const_iterator i = edges.begin(); i != edges.end(); ++i) {\n        Point const &p1 = i->first, p2 = i->second;\n        double const dist = ::sqrt(p1.distanceSquared(p2));\n        addSubSampledEdge(vertices, p1, p2, static_cast<size_t>(::ceil(dist / maxLength)));\n    }\n    return std::shared_ptr<Polygon>(new Polygon(std::shared_ptr<Impl>(new Impl(vertices))));\n}\n\nstd::shared_ptr<afw::image::Image<float>> Polygon::createImage(lsst::geom::Box2I const& bbox) const {\n    typedef afw::image::Image<float> Image;\n    std::shared_ptr<Image> image = std::make_shared<Image>(bbox);\n    image->setXY0(bbox.getMin());\n    *image = 0.0;\n    lsst::geom::Box2D bounds = getBBox();  // Polygon bounds\n    int xMin = std::max(static_cast<int>(bounds.getMinX()), bbox.getMinX());\n    int xMax = std::min(static_cast<int>(::ceil(bounds.getMaxX())), bbox.getMaxX());\n    int yMin = std::max(static_cast<int>(bounds.getMinY()), bbox.getMinY());\n    int yMax = std::min(static_cast<int>(::ceil(bounds.getMaxY())), bbox.getMaxY());\n    for (int y = yMin; y <= yMax; ++y) {\n        double const yPixelMin = (double)y - 0.5, yPixelMax = (double)y + 0.5;\n        BoostPolygon row;  // A polygon of row y\n        boost::geometry::assign(\n                row, LsstBox(lsst::geom::Point2D(xMin, yPixelMin), lsst::geom::Point2D(xMax, yPixelMax)));\n        std::vector<BoostPolygon> intersections;\n        boost::geometry::intersection(_impl->poly, row, intersections);\n\n        if (intersections.size() == 1 && boost::geometry::num_points(intersections[0]) == 5) {\n            // This row is fairly tame, and should have a long run of pixels within the polygon\n            BoostPolygon const& row = intersections[0];\n            std::vector<double> top, bottom;\n            top.reserve(2);\n            bottom.reserve(2);\n            bool failed = false;\n            for (std::vector<Point>::const_iterator i = row.outer().begin(); i != row.outer().end() - 1;\n                 ++i) {\n                double const xCoord = i->getX(), yCoord = i->getY();\n                if (yCoord == yPixelMin) {\n                    bottom.push_back(xCoord);\n                } else if (yCoord == yPixelMax) {\n                    top.push_back(xCoord);\n                } else {\n                    failed = true;\n                    break;\n                }\n            }\n            if (!failed && top.size() == 2 && bottom.size() == 2) {\n                std::sort(top.begin(), top.end());\n                std::sort(bottom.begin(), bottom.end());\n                int const xMin = std::min(top[0], bottom[0]);\n                int const xStart = ::ceil(std::max(top[0], bottom[0])) + 1;\n                int const xStop = std::min(top[1], bottom[1]) - 1;\n                int const xMax = ::ceil(std::max(top[1], bottom[1]));\n                pixelRowOverlap(image, _impl->poly, std::max(xMin, bbox.getMinX()),\n                                std::min(xStart, bbox.getMaxX()), y);\n                int x = xStart;\n                for (Image::x_iterator i = image->x_at(std::max(xStart, bbox.getMinX()) - image->getX0(),\n                                                       y - image->getY0());\n                     x <= std::min(xStop, bbox.getMaxX()); ++i, ++x) {\n                    *i = 1.0;\n                }\n                pixelRowOverlap(image, _impl->poly, std::max(xStop, bbox.getMinX()),\n                                std::min(xMax, bbox.getMaxX()), y);\n                continue;\n            }\n        }\n\n        // Last resort: do each pixel independently...\n        for (std::vector<BoostPolygon>::const_iterator p = intersections.begin(); p != intersections.end();\n             ++p) {\n            double xMinRow = xMax, xMaxRow = xMin;\n            std::vector<LsstPoint> const vertices = p->outer();\n            for (std::vector<LsstPoint>::const_iterator q = vertices.begin(); q != vertices.end(); ++q) {\n                double const x = q->getX();\n                if (x < xMinRow) xMinRow = x;\n                if (x > xMaxRow) xMaxRow = x;\n            }\n\n            pixelRowOverlap(image, _impl->poly, std::max(static_cast<int>(xMinRow), bbox.getMinX()),\n                            std::min(static_cast<int>(::ceil(xMaxRow)), bbox.getMaxX()), y);\n        }\n    }\n    return image;\n}\n\n// -------------- Table-based Persistence -------------------------------------------------------------------\n\n/*\n *\n */\nnamespace {\n\nstruct PolygonSchema {\n    afw::table::Schema schema;\n    afw::table::PointKey<double> vertices;\n\n    static PolygonSchema const& get() {\n        static PolygonSchema instance;\n        return instance;\n    }\n\n    // No copying\n    PolygonSchema(const PolygonSchema&) = delete;\n    PolygonSchema& operator=(const PolygonSchema&) = delete;\n\n    // No moving\n    PolygonSchema(PolygonSchema&&) = delete;\n    PolygonSchema& operator=(PolygonSchema&&) = delete;\n\nprivate:\n    PolygonSchema()\n            : schema(),\n              vertices(afw::table::PointKey<double>::addFields(schema, \"vertices\", \"list of vertex points\",\n                                                               \"\")) {}\n};\n\nclass PolygonFactory : public table::io::PersistableFactory {\npublic:\n    explicit PolygonFactory(std::string const& name) : table::io::PersistableFactory(name) {}\n\n    std::shared_ptr<table::io::Persistable> read(InputArchive const& archive,\n                                                 CatalogVector const& catalogs) const override {\n        static PolygonSchema const& keys = PolygonSchema::get();\n\n        LSST_ARCHIVE_ASSERT(catalogs.size() == 1u);\n        afw::table::BaseCatalog const& cat = catalogs.front();\n\n        std::vector<LsstPoint> vertices;\n        for (afw::table::BaseCatalog::const_iterator iter = cat.begin(); iter != cat.end(); ++iter) {\n            vertices.push_back(iter->get(keys.vertices));\n        }\n        std::shared_ptr<Polygon> result(new Polygon(vertices));\n        return result;\n    }\n};\n\nstd::string getPolygonPersistenceName() { return \"Polygon\"; }\n\nPolygonFactory registration(getPolygonPersistenceName());\n\n}  // anonymous namespace\n\nstd::string Polygon::getPersistenceName() const { return getPolygonPersistenceName(); }\n\nvoid Polygon::write(OutputArchiveHandle& handle) const {\n    static PolygonSchema const& keys = PolygonSchema::get();\n    afw::table::BaseCatalog catalog = handle.makeCatalog(keys.schema);\n\n    std::vector<LsstPoint> vertices = this->getVertices();\n    for (std::vector<LsstPoint>::const_iterator i = vertices.begin(); i != vertices.end(); ++i) {\n        std::shared_ptr<afw::table::BaseRecord> record = catalog.addNew();\n        record->set(keys.vertices, *i);\n    }\n\n    handle.saveCatalog(catalog);\n}\n\nstd::shared_ptr<typehandling::Storable> Polygon::cloneStorable() const {\n    return std::make_unique<Polygon>(*this);\n}\n\nstd::string Polygon::toString() const {\n    std::stringstream buffer;\n    buffer << \"Polygon(\" << this->getVertices() << \")\";\n    return buffer.str();\n}\n\nbool Polygon::equals(typehandling::Storable const& other) const noexcept {\n    return singleClassEquals(*this, other);\n}\n\n}  // namespace polygon\n}  // namespace geom\n}  // namespace afw\n}  // namespace lsst\n", "meta": {"hexsha": "046ed79cf09f326d411465d88bd16f2a10b29509", "size": 23193, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/afw/geom/polygon/Polygon.cc", "max_stars_repo_name": "DarkEnergySurvey/cosmicRays", "max_stars_repo_head_hexsha": "5c29bd9fc4a9f37e298e897623ec98fff4a8d539", "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/afw/geom/polygon/Polygon.cc", "max_issues_repo_name": "DarkEnergySurvey/cosmicRays", "max_issues_repo_head_hexsha": "5c29bd9fc4a9f37e298e897623ec98fff4a8d539", "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/afw/geom/polygon/Polygon.cc", "max_forks_repo_name": "DarkEnergySurvey/cosmicRays", "max_forks_repo_head_hexsha": "5c29bd9fc4a9f37e298e897623ec98fff4a8d539", "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": 38.0837438424, "max_line_length": 110, "alphanum_fraction": 0.6501530634, "num_tokens": 5780, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7122321964553657, "lm_q2_score": 0.44939263446475963, "lm_q1q2_score": 0.32007190311569905}}
{"text": "//=============================================================================================================\n/**\n * @file     filterkernel.cpp\n * @author   Lorenz Esch <lesch@mgh.harvard.edu>;\n *           Ruben Doerfel <Ruben.Doerfel@tu-ilmenau.de>;\n *           Christoph Dinh <chdinh@nmr.mgh.harvard.edu>\n * @since    0.1.0\n * @date     February, 2014\n *\n * @section  LICENSE\n *\n * Copyright (C) 2014, Lorenz Esch, Ruben Doerfel, 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    Contains all FilterKernel.\n *\n */\n\n//=============================================================================================================\n// INCLUDES\n//=============================================================================================================\n\n#include \"filterkernel.h\"\n\n#include <utils/mnemath.h>\n\n#include \"parksmcclellan.h\"\n#include \"cosinefilter.h\"\n\n#include <iostream>\n\n//=============================================================================================================\n// QT INCLUDES\n//=============================================================================================================\n\n#include <QDebug>\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// USED NAMESPACES\n//=============================================================================================================\n\nusing namespace RTPROCESSINGLIB;\nusing namespace Eigen;\nusing namespace UTILSLIB;\n\n\n\n//=============================================================================================================\n// INIT STATIC MEMBERS\n//=============================================================================================================\n\nQVector<RTPROCESSINGLIB::FilterParameter> FilterKernel::m_designMethods ({\n    FilterParameter(QString(\"Cosine\"), QString(\"A cosine filter\")),\n    FilterParameter(QString(\"Tschebyscheff\"), QString(\"A tschebyscheff filter\"))\n//    FilterParameter(QString(\"External\"), QString(\"An external filter\"))\n});\nQVector<RTPROCESSINGLIB::FilterParameter> FilterKernel::m_filterTypes ({\n    FilterParameter(QString(\"LPF\"), QString(\"An LPF filter\")),\n    FilterParameter(QString(\"HPF\"), QString(\"An HPF filter\")),\n    FilterParameter(QString(\"BPF\"), QString(\"A BPF filter\")),\n    FilterParameter(QString(\"NOTCH\"), QString(\"A NOTCH filter\")),\n    FilterParameter(QString(\"UNKNOWN\"), QString(\"An UNKNOWN filter\"))\n});\n\n//=============================================================================================================\n// DEFINE MEMBER METHODS\n//=============================================================================================================\n\nFilterKernel::FilterKernel()\n: m_iFilterType(m_filterTypes.indexOf(FilterParameter(\"BPF\")))\n, m_iFilterOrder(80)\n, m_sFilterName(\"Unknown\")\n, m_dParksWidth(0.1)\n, m_iDesignMethod(m_designMethods.indexOf(FilterParameter(\"Cosine\")))\n, m_dCenterFreq(0.5)\n, m_dBandwidth(0.1)\n, m_sFreq(1000)\n, m_dLowpassFreq(40)\n, m_dHighpassFreq(4)\n{\n    designFilter();\n}\n\n//=============================================================================================================\n\nFilterKernel::FilterKernel(const QString& sFilterName,\n                           int iFilterType,\n                           int iOrder,\n                           double dCenterfreq,\n                           double dBandwidth,\n                           double dParkswidth,\n                           double dSFreq,\n                           int iDesignMethod)\n: m_iDesignMethod(iDesignMethod)\n, m_iFilterType(iFilterType)\n, m_sFreq(dSFreq)\n, m_dCenterFreq(dCenterfreq)\n, m_dBandwidth(dBandwidth)\n, m_dParksWidth(dParkswidth)\n, m_iFilterOrder(iOrder)\n, m_sFilterName(sFilterName)\n{\n    if(iOrder < 9) {\n       qWarning() << \"[FilterKernel::FilterKernel] Less than 9 taps were provided. Setting number of taps to 9.\";\n    }\n\n    designFilter();\n}\n\n//=============================================================================================================\n\nvoid FilterKernel::prepareFilter(int iDataSize)\n{\n    int iFftLength, exp;\n\n    iFftLength = iDataSize + m_vecCoeff.cols();\n    exp = ceil(MNEMath::log2(iFftLength));\n    iFftLength = pow(2, exp);\n\n    // Transform coefficients anew if needed\n    if(m_vecCoeff.cols() != (iFftLength/2+1)) {\n        fftTransformCoeffs(iFftLength);\n    }\n}\n\n//=============================================================================================================\n\nRowVectorXd FilterKernel::applyConvFilter(const RowVectorXd& vecData,\n                                          bool bKeepOverhead) const\n{\n    //Do zero padding or mirroring depending on user input\n    RowVectorXd vecDataZeroPad = RowVectorXd::Zero(2*m_vecCoeff.cols() + vecData.cols());\n    RowVectorXd vecFilteredTime = RowVectorXd::Zero(2*m_vecCoeff.cols() + vecData.cols());\n\n    vecDataZeroPad.segment(m_vecCoeff.cols(), vecData.cols()) = vecData;\n\n    //Do the convolution\n    for(int i = m_vecCoeff.cols(); i < vecFilteredTime.cols(); i++) {\n        vecFilteredTime(i-m_vecCoeff.cols()) = vecDataZeroPad.segment(i-m_vecCoeff.cols(),m_vecCoeff.cols()) * m_vecCoeff.transpose();\n    }\n\n    //Return filtered data\n    if(!bKeepOverhead) {\n        return vecFilteredTime.segment(m_vecCoeff.cols()/2, vecData.cols());\n    }\n\n    return vecFilteredTime.head(vecData.cols()+m_vecCoeff.cols());\n}\n\n//=============================================================================================================\n\nvoid FilterKernel::applyFftFilter(RowVectorXd& vecData,\n                                  bool bKeepOverhead)\n{\n    #ifdef EIGEN_FFTW_DEFAULT\n    fftw_make_planner_thread_safe();\n    #endif\n\n    // Make sure we always have the correct FFT length for the given input data and filter overlap\n    int iFftLength = vecData.cols() + m_vecCoeff.cols();\n    int exp = ceil(MNEMath::log2(iFftLength));\n    iFftLength = pow(2, exp);\n\n    // Transform coefficients anew if needed\n    if(m_vecFftCoeff.cols() != (iFftLength/2+1)) {\n        fftTransformCoeffs(iFftLength);\n    }\n\n    //generate fft object\n    Eigen::FFT<double> fft;\n    fft.SetFlag(fft.HalfSpectrum);\n\n    // Zero padd if necessary. Please note: The zero padding in Eigen's FFT is only working for column vectors -> We have to zero pad manually here\n    int iOriginalSize = vecData.cols();\n    if (vecData.cols() < iFftLength) {\n        int iResidual = iFftLength - vecData.cols();\n        vecData.conservativeResize(iFftLength);\n        vecData.tail(iResidual).setZero();\n    }\n\n    //fft-transform data sequence\n    RowVectorXcd vecFreqData;\n    fft.fwd(vecFreqData, vecData, iFftLength);\n\n    //perform frequency-domain filtering\n    vecFreqData = m_vecFftCoeff.array() * vecFreqData.array();\n\n    //inverse-FFT\n    fft.inv(vecData, vecFreqData);\n\n    //Return filtered data\n    if(!bKeepOverhead) {\n        vecData = vecData.segment(m_vecCoeff.cols()/2, iOriginalSize).eval();\n    } else {\n        vecData = vecData.head(iOriginalSize + m_vecCoeff.cols()).eval();\n    }\n}\n\n//=============================================================================================================\n\nQString FilterKernel::getName() const\n{\n    return m_sFilterName;\n}\n\n//=============================================================================================================\n\nvoid FilterKernel::setName(const QString& sFilterName)\n{\n    m_sFilterName = sFilterName;\n}\n\n//=============================================================================================================\n\ndouble FilterKernel::getSamplingFrequency() const\n{\n    return m_sFreq;\n}\n\n//=============================================================================================================\n\nvoid FilterKernel::setSamplingFrequency(double dSFreq)\n{\n    m_sFreq = dSFreq;\n}\n\n//=============================================================================================================\n\nint FilterKernel::getFilterOrder() const\n{\n    return m_iFilterOrder;\n}\n\n//=============================================================================================================\n\nvoid FilterKernel::setFilterOrder(int iOrder)\n{\n    m_iFilterOrder = iOrder;\n}\n\n//=============================================================================================================\n\ndouble FilterKernel::getCenterFrequency() const\n{\n    return m_dCenterFreq;\n}\n\n//=============================================================================================================\n\nvoid FilterKernel::setCenterFrequency(double dCenterFreq)\n{\n    m_dCenterFreq = dCenterFreq;\n}\n\n//=============================================================================================================\n\ndouble FilterKernel::getBandwidth() const\n{\n    return m_dBandwidth;\n}\n\n//=============================================================================================================\n\nvoid FilterKernel::setBandwidth(double dBandwidth)\n{\n    m_dBandwidth = dBandwidth;\n}\n\n//=============================================================================================================\n\ndouble FilterKernel::getParksWidth() const\n{\n    return m_dParksWidth;\n}\n\n//=============================================================================================================\n\nvoid FilterKernel::setParksWidth(double dParksWidth)\n{\n    m_dParksWidth = dParksWidth;\n}\n\n//=============================================================================================================\n\ndouble FilterKernel::getHighpassFreq() const\n{\n    return m_dHighpassFreq;\n}\n\n//=============================================================================================================\n\nvoid FilterKernel::setHighpassFreq(double dHighpassFreq)\n{\n    m_dHighpassFreq = dHighpassFreq;\n}\n\n//=============================================================================================================\n\ndouble FilterKernel::getLowpassFreq() const\n{\n    return m_dLowpassFreq;\n}\n\n//=============================================================================================================\n\nvoid FilterKernel::setLowpassFreq(double dLowpassFreq)\n{\n    m_dLowpassFreq = dLowpassFreq;\n}\n\n//=============================================================================================================\n\nEigen::RowVectorXd FilterKernel::getCoefficients() const\n{\n    return m_vecCoeff;\n}\n\n//=============================================================================================================\n\nvoid FilterKernel::setCoefficients(const Eigen::RowVectorXd& vecCoeff)\n{\n    m_vecCoeff = vecCoeff;\n}\n\n//=============================================================================================================\n\nEigen::RowVectorXcd FilterKernel::getFftCoefficients() const\n{\n    return m_vecFftCoeff;\n}\n\n//=============================================================================================================\n\nvoid FilterKernel::setFftCoefficients(const Eigen::RowVectorXcd& vecFftCoeff)\n{\n    m_vecFftCoeff = vecFftCoeff;\n}\n\n//=============================================================================================================\n\nbool FilterKernel::fftTransformCoeffs(int iFftLength)\n{\n    #ifdef EIGEN_FFTW_DEFAULT\n        fftw_make_planner_thread_safe();\n    #endif\n\n    if(m_vecCoeff.cols() > iFftLength) {\n        std::cout <<\"[FilterKernel::fftTransformCoeffs] The number of filter taps is bigger than the FFT length.\"<< std::endl;\n        return false;\n    }\n\n    //generate fft object\n    Eigen::FFT<double> fft;\n    fft.SetFlag(fft.HalfSpectrum);\n\n    // Zero padd if necessary. Please note: The zero padding in Eigen's FFT is only working for column vectors -> We have to zero pad manually here\n    RowVectorXd vecInputFft;\n    if (m_vecCoeff.cols() < iFftLength) {\n        vecInputFft.setZero(iFftLength);\n        vecInputFft.block(0,0,1,m_vecCoeff.cols()) = m_vecCoeff;\n    } else {\n        vecInputFft = m_vecCoeff;\n    }\n\n    //fft-transform filter coeffs\n    RowVectorXcd vecFreqData;\n    fft.fwd(vecFreqData, vecInputFft, iFftLength);\n    m_vecFftCoeff = vecFreqData;;\n\n    return true;\n}\n\n//=============================================================================================================\n\nvoid FilterKernel::designFilter()\n{\n    // Make sure we only use a minimum needed FFT size\n    int iFftLength = m_iFilterOrder;\n    int exp = ceil(MNEMath::log2(iFftLength));\n    iFftLength = pow(2, exp);\n\n    switch(m_iDesignMethod) {\n        case 1: {\n            ParksMcClellan filter(m_iFilterOrder,\n                                  m_dCenterFreq,\n                                  m_dBandwidth,\n                                  m_dParksWidth,\n                                  static_cast<ParksMcClellan::TPassType>(m_iFilterType));\n            m_vecCoeff = filter.FirCoeff;\n\n            //fft-transform m_vecCoeff in order to be able to perform frequency-domain filtering\n            fftTransformCoeffs(iFftLength);\n\n            break;\n        }\n\n        case 0: {\n            CosineFilter filtercos;\n\n            switch(m_iFilterType) {\n                case 0:\n                    filtercos = CosineFilter(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                                             static_cast<CosineFilter::TPassType>(m_iFilterType));\n\n                    break;\n\n                case 1:\n                    filtercos = CosineFilter(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                                             static_cast<CosineFilter::TPassType>(m_iFilterType));\n\n                    break;\n\n                case 2:\n                    filtercos = CosineFilter(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                                             static_cast<CosineFilter::TPassType>(m_iFilterType));\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_vecCoeff.resize(m_iFilterOrder);\n\n            m_vecCoeff.head(m_iFilterOrder/2) = filtercos.m_vecCoeff.tail(m_iFilterOrder/2);\n            m_vecCoeff.tail(m_iFilterOrder/2) = filtercos.m_vecCoeff.head(m_iFilterOrder/2);\n\n            //Now generate the fft version of the shortened impulse response\n            fftTransformCoeffs(iFftLength);\n\n            break;\n        }\n    }\n\n    switch(m_iFilterType) {\n        case 0:\n            m_dLowpassFreq = 0;\n            m_dHighpassFreq = m_dCenterFreq*(m_sFreq/2);\n        break;\n\n        case 1:\n            m_dLowpassFreq = m_dCenterFreq*(m_sFreq/2);\n            m_dHighpassFreq = 0;\n        break;\n\n        case 2:\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\nRTPROCESSINGLIB::FilterParameter FilterKernel::getDesignMethod() const\n{\n    if(m_iDesignMethod < 0){\n        return m_designMethods.at(0);\n    }\n    return m_designMethods.at(m_iDesignMethod);\n}\n\n//=============================================================================================================\n\nRTPROCESSINGLIB::FilterParameter FilterKernel::getFilterType() const\n{\n    if(m_iFilterType < 0){\n        return m_filterTypes.at(0);\n    }\n    return m_filterTypes.at(m_iFilterType);\n}\n\n//=============================================================================================================\n\nvoid FilterKernel::setDesignMethod(int iDesignMethod)\n{\n    if(iDesignMethod < 0){\n        m_iDesignMethod = 0;\n    } else {\n        m_iDesignMethod = iDesignMethod;\n    }\n}\n\n//=============================================================================================================\n\nvoid FilterKernel::setFilterType(int iFilterType)\n{\n    if(iFilterType < 0){\n        m_iFilterType = 0;\n    } else {\n        m_iFilterType = iFilterType;\n    }\n}\n\n//=============================================================================================================\n\nFilterParameter::FilterParameter()\n:FilterParameter(\"Unknown\", \"\")\n{\n}\n\n//=============================================================================================================\n\nFilterParameter::FilterParameter(QString sName)\n:FilterParameter(sName,\"\")\n{  \n}\n\n//=============================================================================================================\n\nFilterParameter::FilterParameter(QString sName,\n                           QString sDescription)\n: m_sName(sName)\n, m_sDescription(sDescription)\n{\n\n}\n\n//=============================================================================================================\n\nQString FilterParameter::getName() const\n{\n    return m_sName;\n}\n", "meta": {"hexsha": "92ddc31eaca32ceb92a2fd4167ac1cfd35dbd1a5", "size": 19632, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libraries/rtprocessing/helpers/filterkernel.cpp", "max_stars_repo_name": "Youssef-Zarca/mne-cpp", "max_stars_repo_head_hexsha": "a4b4c7219873b1af4e0275e967447e68f97e5c14", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "libraries/rtprocessing/helpers/filterkernel.cpp", "max_issues_repo_name": "Youssef-Zarca/mne-cpp", "max_issues_repo_head_hexsha": "a4b4c7219873b1af4e0275e967447e68f97e5c14", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "libraries/rtprocessing/helpers/filterkernel.cpp", "max_forks_repo_name": "Youssef-Zarca/mne-cpp", "max_forks_repo_head_hexsha": "a4b4c7219873b1af4e0275e967447e68f97e5c14", "max_forks_repo_licenses": ["BSD-3-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.6855123675, "max_line_length": 159, "alphanum_fraction": 0.4674511002, "num_tokens": 3676, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5813031051514763, "lm_q2_score": 0.5506073655352404, "lm_q1q2_score": 0.3200697713049092}}
{"text": "/*\n * Copyright (c) 2013, Christian Gehring, Hannes Sommer, Paul Furgale, Remo Diethelm\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *     * Redistributions of source code must retain the above copyright\n *       notice, this list of conditions and the following disclaimer.\n *     * Redistributions in binary form must reproduce the above copyright\n *       notice, this list of conditions and the following disclaimer in the\n *       documentation and/or other materials provided with the distribution.\n *     * Neither the name of the Autonomous Systems Lab, ETH Zurich nor the\n *       names of its contributors may be used to endorse or promote products\n *       derived from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL Christian Gehring, Hannes Sommer, Paul Furgale,\n * Remo Diethelm BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,\n * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE\n * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n*/\n\n#pragma once\n\n#include <Eigen/Core>\n\n#include \"kindr/math/LinearAlgebra.hpp\"\n#include \"kindr/common/common.hpp\"\n#include \"kindr/common/assert_macros.hpp\"\n#include \"kindr/common/assert_macros_eigen.hpp\"\n#include \"kindr/rotations/RotationDiffBase.hpp\"\n#include \"kindr/rotations/Rotation.hpp\"\n\nnamespace kindr {\n\n/*! \\class RotationMatrixDiff\n * \\brief Time derivative of a rotation matrix.\n *\n * This class implements the time derivative of a rotation matrix using a Eigen::Matrix<Scalar, 3, 3> as data storage.\n *\n * \\tparam PrimType_  Primitive data type of the coordinates.\n * \\ingroup rotations\n */\ntemplate<typename PrimType_>\nclass RotationMatrixDiff : public RotationDiffBase<RotationMatrixDiff<PrimType_>>, private Eigen::Matrix<PrimType_, 3, 3> {\n private:\n  /*! \\brief The base type.\n   */\n  typedef Eigen::Matrix<PrimType_, 3, 3> Base;\n\n public:\n  /*! \\brief The implementation type.\n   *  The implementation type is always an Eigen object.\n   */\n  typedef Base Implementation;\n\n  typedef Base Matrix3x3;\n\n\n  /*! \\brief The primitive type.\n   *  Float/Double\n   */\n  typedef PrimType_ Scalar;\n\n  RotationMatrixDiff()\n    : Base(Base::Zero()) {\n  }\n\n  /*! \\brief Constructor using Eigen::Matrix<Scalar, 3, 3>.\n   *  \\param other   Eigen::Matrix<Scalar, 3, 3>\n   */\n  explicit RotationMatrixDiff(const Base& other) // explicit on purpose\n    : Base(other) {\n  }\n\n  /*! \\brief Constructor using nine scalars.\n   *  \\param r11     entry in row 1, col 1\n   *  \\param r12     entry in row 1, col 2\n   *  \\param r13     entry in row 1, col 3\n   *  \\param r21     entry in row 2, col 1\n   *  \\param r22     entry in row 2, col 2\n   *  \\param r23     entry in row 2, col 3\n   *  \\param r31     entry in row 3, col 1\n   *  \\param r32     entry in row 3, col 2\n   *  \\param r33     entry in row 3, col 3\n   */\n  RotationMatrixDiff(Scalar r11, Scalar r12, Scalar r13,\n                     Scalar r21, Scalar r22, Scalar r23,\n                     Scalar r31, Scalar r32, Scalar r33) {\n    *this << r11,r12,r13,r21,r22,r23,r31,r32,r33;\n  }\n\n  /*! \\brief Constructor using a time derivative with a different parameterization\n   *\n   * \\param rotation  rotation\n   * \\param other     other time derivative\n   */\n  template<typename RotationDerived_, typename OtherDerived_>\n  inline explicit RotationMatrixDiff(const RotationBase<RotationDerived_>& rotation, const RotationDiffBase<OtherDerived_>& other)\n    : Base(internal::RotationDiffConversionTraits<RotationMatrixDiff, OtherDerived_, RotationDerived_>::convert(rotation.derived(), other.derived()).toImplementation()){\n  }\n\n\n  /*! \\brief Cast to another representation of the time derivative of a rotation\n   *  \\param other   other rotation\n   *  \\returns reference\n   */\n  template<typename OtherDerived_, typename RotationDerived_>\n  OtherDerived_ cast(const RotationBase<RotationDerived_>& rotation) const {\n    return internal::RotationDiffConversionTraits<OtherDerived_, RotationMatrixDiff, RotationDerived_>::convert(rotation.derived(), *this);\n  }\n\n  /*! \\brief Cast to the implementation type.\n   *  \\returns the implementation (recommended only for advanced users)\n   */\n  inline Implementation& toImplementation() {\n    return static_cast<Implementation&>(*this);\n  }\n\n  /*! \\brief Cast to the implementation type.\n   *  \\returns the implementation (recommended only for advanced users)\n   */\n  inline const Implementation& toImplementation() const {\n    return static_cast<const Implementation&>(*this);\n  }\n\n  /*! \\brief Reading access to the time derivative of the rotation matrix.\n   *  \\returns rotation matrix (matrix) with reading access\n   */\n  inline const Matrix3x3& matrix() const {\n    return this->toImplementation();\n  }\n\n  /*! \\brief Writing access to the time derivative of the rotation matrix.\n   *  \\returns rotation matrix (matrix) with writing access\n   */\n  inline Matrix3x3& matrix() {\n    return this->toImplementation();\n  }\n\n  /*! \\brief Sets all time derivatives to zero.\n   *  \\returns reference\n   */\n  RotationMatrixDiff& setZero() {\n    this->toImplementation().setZero();\n    return *this;\n  }\n\n  /*! \\brief Used for printing the object with std::cout.\n   *  \\returns std::stream object\n   */\n  friend std::ostream& operator << (std::ostream& out, const RotationMatrixDiff& diff) {\n    out << diff.toImplementation();\n    return out;\n  }\n};\n\n\n//! \\brief Time derivative of a rotation quaternion with primitive type double\ntypedef RotationMatrixDiff<double> RotationMatrixDiffPD;\n//! \\brief Time derivative of a rotation quaternion with primitive type float\ntypedef RotationMatrixDiff<float> RotationMatrixDiffPF;\n//! \\brief Time derivative of a rotation quaternion with primitive type double\ntypedef RotationMatrixDiff<double> RotationMatrixDiffD;\n//! \\brief Time derivative of a rotation quaternion with primitive type float\ntypedef RotationMatrixDiff<float> RotationMatrixDiffF;\n\n\nnamespace internal {\n\ntemplate<typename PrimType_>\nclass RotationDiffConversionTraits<RotationMatrixDiff<PrimType_>, LocalAngularVelocity<PrimType_>, RotationMatrix<PrimType_>> {\n public:\n  inline static RotationMatrixDiff<PrimType_> convert(const RotationMatrix<PrimType_>& rotationMatrix, const LocalAngularVelocity<PrimType_>& angularVelocity) {\n    return RotationMatrixDiff<PrimType_>(rotationMatrix.matrix()*getSkewMatrixFromVector(angularVelocity.vector()));\n  }\n};\n\ntemplate<typename PrimType_>\nclass RotationDiffConversionTraits<RotationMatrixDiff<PrimType_>, GlobalAngularVelocity<PrimType_>, RotationMatrix<PrimType_>> {\n public:\n  inline static RotationMatrixDiff<PrimType_> convert(const RotationMatrix<PrimType_>& rotationMatrix, const GlobalAngularVelocity<PrimType_>& angularVelocity) {\n    return RotationMatrixDiff<PrimType_>(getSkewMatrixFromVector(angularVelocity.vector())*rotationMatrix.matrix());\n  }\n};\n\n} // namespace internal\n} // namespace kindr\n", "meta": {"hexsha": "334ae385ee5e64331eae4e3e13ebee54d0ec85d0", "size": 7538, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/kindr/rotations/RotationMatrixDiff.hpp", "max_stars_repo_name": "meyerj/kindr", "max_stars_repo_head_hexsha": "a5ef954dcc2cbba8de36e36e03f6922c9c486463", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 126.0, "max_stars_repo_stars_event_min_datetime": "2015-06-17T12:49:52.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-02T13:39:04.000Z", "max_issues_repo_path": "include/kindr/rotations/RotationMatrixDiff.hpp", "max_issues_repo_name": "meyerj/kindr", "max_issues_repo_head_hexsha": "a5ef954dcc2cbba8de36e36e03f6922c9c486463", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 41.0, "max_issues_repo_issues_event_min_datetime": "2015-01-12T10:39:58.000Z", "max_issues_repo_issues_event_max_datetime": "2018-07-31T13:24:52.000Z", "max_forks_repo_path": "include/kindr/rotations/RotationMatrixDiff.hpp", "max_forks_repo_name": "meyerj/kindr", "max_forks_repo_head_hexsha": "a5ef954dcc2cbba8de36e36e03f6922c9c486463", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 80.0, "max_forks_repo_forks_event_min_datetime": "2015-11-06T02:47:00.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-25T10:26:18.000Z", "avg_line_length": 38.6564102564, "max_line_length": 169, "alphanum_fraction": 0.7346776333, "num_tokens": 1758, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5813030761371503, "lm_q2_score": 0.5506073655352404, "lm_q1q2_score": 0.32006975532940757}}
{"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 \"vertex_ellipse.h\"\n\n#include \"g2o/stuff/macros.h\"\n#include \"g2o/stuff/misc.h\"\n\n#ifdef G2O_HAVE_OPENGL\n#include \"g2o/EXTERNAL/freeglut/freeglut_minimal.h\"\n#include \"g2o/stuff/opengl_primitives.h\"\n#include \"g2o/stuff/opengl_wrapper.h\"\n#endif\n\n#include <Eigen/Eigenvalues>\n#include <iomanip>\n\nusing namespace std;\n\nnamespace g2o {\n\nVertexEllipse::VertexEllipse()\n    : RobotData(),\n      _covariance(Matrix3F::Zero()),\n      _UMatrix(Matrix2F::Zero()),\n      _singularValues(Vector2F::Zero()) {}\n\nVertexEllipse::~VertexEllipse() {}\n\nvoid VertexEllipse::_updateSVD() const {\n  Eigen::SelfAdjointEigenSolver<Matrix2F> eigenSolver(\n      _covariance.block<2, 2>(0, 0));\n  _UMatrix = eigenSolver.eigenvectors();\n  _singularValues = eigenSolver.eigenvalues();\n}\n\nbool VertexEllipse::read(std::istream& is) {\n  float cxx, cxy, cxt, cyy, cyt, ctt;\n  is >> cxx >> cxy >> cxt >> cyy >> cyt >> ctt;\n  _covariance(0, 0) = cxx;\n  _covariance(0, 1) = cxy;\n  _covariance(0, 2) = cxt;\n  _covariance(1, 0) = cxy;\n  _covariance(1, 1) = cyy;\n  _covariance(1, 2) = cyt;\n  _covariance(2, 0) = cxt;\n  _covariance(2, 1) = cyt;\n  _covariance(2, 2) = ctt;\n\n  _updateSVD();\n\n  int size;\n  is >> size;\n  for (int i = 0; i < size; i++) {\n    float x, y;\n    is >> x >> y;\n    addMatchingVertex(x, y);\n  }\n\n  return true;\n}\n\nbool VertexEllipse::write(std::ostream& os) const {\n  os << _covariance(0, 0) << \" \" << _covariance(0, 1) << \" \"\n     << _covariance(0, 2) << \" \" << _covariance(1, 1) << \" \"\n     << _covariance(1, 2) << \" \" << _covariance(2, 2) << \" \";\n\n  os << _matchingVertices.size() << \" \";\n  for (size_t i = 0; i < _matchingVertices.size(); i++) {\n    os << _matchingVertices[i].x() << \" \" << _matchingVertices[i].y() << \" \";\n  }\n\n  return os.good();\n}\n\n#ifdef G2O_HAVE_OPENGL\nVertexEllipseDrawAction::VertexEllipseDrawAction()\n    : DrawAction(typeid(VertexEllipse).name()) {\n  _scaleFactor = 0;\n}\n\nbool VertexEllipseDrawAction::refreshPropertyPtrs(\n    HyperGraphElementAction::Parameters* params_) {\n  if (!DrawAction::refreshPropertyPtrs(params_)) return false;\n  if (_previousParams) {\n    _scaleFactor =\n        _previousParams->makeProperty<DoubleProperty>(_typeName + \"::\", 1);\n  } else {\n    _scaleFactor = 0;\n  }\n  return true;\n}\n\nHyperGraphElementAction* VertexEllipseDrawAction::operator()(\n    HyperGraph::HyperGraphElement* element,\n    HyperGraphElementAction::Parameters* params_) {\n  if (typeid(*element).name() != _typeName) return nullptr;\n\n  refreshPropertyPtrs(params_);\n  if (!_previousParams) {\n    return this;\n  }\n  if (_show && !_show->value()) return this;\n\n  VertexEllipse* that = dynamic_cast<VertexEllipse*>(element);\n\n  glPushMatrix();\n\n  float sigmaTheta = sqrt(that->covariance()(2, 2));\n  float x = 0.1f * cosf(sigmaTheta);\n  float y = 0.1f * sinf(sigmaTheta);\n\n  glColor3f(1.f, 0.7f, 1.f);\n  glBegin(GL_LINE_STRIP);\n  glVertex3f(x, y, 0);\n  glVertex3f(0, 0, 0);\n  glVertex3f(x, -y, 0);\n  glEnd();\n\n  glColor3f(0.f, 1.f, 0.f);\n  for (size_t i = 0; i < that->matchingVertices().size(); i++) {\n    glBegin(GL_LINES);\n    glVertex3f(0, 0, 0);\n    glVertex3f(that->matchingVertices()[i].x(), that->matchingVertices()[i].y(),\n               0);\n    glEnd();\n  }\n\n  Matrix2F rot = that->U();\n  float angle = std::atan2(rot(1, 0), rot(0, 0));\n  glRotatef(angle * 180.0 / const_pi(), 0., 0., 1.);\n  Vector2F sv = that->singularValues();\n  glScalef(sqrt(sv(0)), sqrt(sv(1)), 1);\n\n  glColor3f(1.f, 0.7f, 1.f);\n  glBegin(GL_LINE_LOOP);\n  for (int i = 0; i < 36; i++) {\n    float rad = i * const_pi() / 18.0;\n    glVertex2f(std::cos(rad), std::sin(rad));\n  }\n  glEnd();\n\n  glPopMatrix();\n  return this;\n}\n#endif\n\n}  // namespace g2o\n", "meta": {"hexsha": "4fc8b462b9dac9e88c3ca6a730d29903826ee3d5", "size": 5070, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "3rdparty/g2o/g2o/types/data/vertex_ellipse.cpp", "max_stars_repo_name": "Refstop/VSLAM_Example", "max_stars_repo_head_hexsha": "060b9419f79f035d1c9ebfa75ad46e2e9a53e992", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "3rdparty/g2o/g2o/types/data/vertex_ellipse.cpp", "max_issues_repo_name": "Refstop/VSLAM_Example", "max_issues_repo_head_hexsha": "060b9419f79f035d1c9ebfa75ad46e2e9a53e992", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "3rdparty/g2o/g2o/types/data/vertex_ellipse.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": 29.476744186, "max_line_length": 80, "alphanum_fraction": 0.6715976331, "num_tokens": 1500, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5506073507867328, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.3200697547438054}}
{"text": "/*\n * _build_in.cpp\n *\n *  Created on: 2013-2-14\n *      Author: fasiondog\n */\n\n#include <boost/python.hpp>\n#include <hikyuu/indicator/build_in.h>\n\nusing namespace hku;\nusing namespace boost::python;\n\nIndicator (*PRICELIST2)(const PriceList&, int) = PRICELIST;\nIndicator (*PRICELIST3)(const Indicator&, int) = PRICELIST;\nIndicator (*PRICELIST4)(int) = PRICELIST;\n\nIndicator (*KDATA1)(const KData&) = KDATA;\nIndicator (*KDATA3)() = KDATA;\n\nIndicator (*OPEN1)(const KData&) = OPEN;\nIndicator (*OPEN3)() = OPEN;\n\nIndicator (*HIGH1)(const KData&) = HIGH;\nIndicator (*HIGH3)() = HIGH;\n\nIndicator (*LOW1)(const KData&) = LOW;\nIndicator (*LOW3)() = LOW;\n\nIndicator (*CLOSE1)(const KData&) = CLOSE;\nIndicator (*CLOSE3)() = CLOSE;\n\nIndicator (*AMO1)(const KData&) = AMO;\nIndicator (*AMO3)() = AMO;\n\nIndicator (*VOL1)(const KData&) = VOL;\nIndicator (*VOL3)() = VOL;\n\nIndicator (*KDATA_PART1)(const KData& kdata, const string& part) = KDATA_PART;\nIndicator (*KDATA_PART3)(const string& part) = KDATA_PART;\n\nIndicator (*AMA_1)(int, int, int) = AMA;\nIndicator (*AMA_2)(const Indicator&, int, int, int) = AMA;\n\nIndicator (*ATR_1)(int) = ATR;\nIndicator (*ATR_2)(const Indicator&, int) = ATR;\n\nIndicator (*DIFF_1)() = DIFF;\nIndicator (*DIFF_2)(const Indicator&) = DIFF;\n\nIndicator (*MA_1)(int) = MA;\nIndicator (*MA_2)(const IndParam&) = MA;\nIndicator (*MA_3)(const Indicator&, const IndParam&) = MA;\nIndicator (*MA_4)(const Indicator&, const Indicator&) = MA;\nIndicator (*MA_5)(const Indicator&, int) = MA;\n\nIndicator (*SMA_1)(int, double) = SMA;\nIndicator (*SMA_2)(const Indicator&, int, double) = SMA;\n\nIndicator (*EMA_1)(int) = EMA;\nIndicator (*EMA_2)(const Indicator&, int) = EMA;\n\nIndicator (*MACD_1)(int, int, int) = MACD;\nIndicator (*MACD_2)(const Indicator&, int, int, int) = MACD;\n// BOOST_PYTHON_FUNCTION_OVERLOADS(MACD_1_overload, MACD, 0, 3);\n// BOOST_PYTHON_FUNCTION_OVERLOADS(MACD_2_overload, MACD, 1, 4);\n\nIndicator (*REF_1)(int) = REF;\nIndicator (*REF_2)(const Indicator&, int) = REF;\n\nIndicator (*SAFTYLOSS_1)(int n1, int n2, double p) = SAFTYLOSS;\nIndicator (*SAFTYLOSS_2)(const Indicator&, int n1, int n2, double p) = SAFTYLOSS;\n// BOOST_PYTHON_FUNCTION_OVERLOADS(SAFTYLOSS_1_overload, SAFTYLOSS, 0, 3);\n// BOOST_PYTHON_FUNCTION_OVERLOADS(SAFTYLOSS_2_overload, SAFTYLOSS, 1, 4);\n\nIndicator (*STDEV_1)(int) = STDEV;\nIndicator (*STDEV_2)(const IndParam&) = STDEV;\nIndicator (*STDEV_3)(const Indicator&, const IndParam&) = STDEV;\nIndicator (*STDEV_4)(const Indicator&, const Indicator&) = STDEV;\nIndicator (*STDEV_5)(const Indicator&, int) = STDEV;\n\nIndicator (*STDP_1)(int) = STDP;\nIndicator (*STDP_2)(const IndParam&) = STDP;\nIndicator (*STDP_3)(const Indicator&, const IndParam&) = STDP;\nIndicator (*STDP_4)(const Indicator&, const Indicator&) = STDP;\nIndicator (*STDP_5)(const Indicator&, int) = STDP;\n\nIndicator (*HHV_1)(int) = HHV;\nIndicator (*HHV_2)(const IndParam&) = HHV;\nIndicator (*HHV_3)(const Indicator&, const Indicator&) = HHV;\nIndicator (*HHV_4)(const Indicator&, const IndParam&) = HHV;\nIndicator (*HHV_5)(const Indicator&, int) = HHV;\n\nIndicator (*LLV_1)(int) = LLV;\nIndicator (*LLV_2)(const IndParam&) = LLV;\nIndicator (*LLV_3)(const Indicator&, const IndParam&) = LLV;\nIndicator (*LLV_4)(const Indicator&, const Indicator&) = LLV;\nIndicator (*LLV_5)(const Indicator&, int) = LLV;\n\nIndicator (*VIGOR_1)(const KData&, int) = VIGOR;\nIndicator (*VIGOR_2)(int) = VIGOR;\n\nIndicator (*CVAL_1)(double, size_t) = CVAL;\nIndicator (*CVAL_2)(const Indicator&, double, int) = CVAL;\n\nIndicator (*LIUTONGPAN_1)() = LIUTONGPAN;\nIndicator (*LIUTONGPAN_2)(const KData&) = LIUTONGPAN;\n\nIndicator (*HSL_1)() = HSL;\nIndicator (*HSL_2)(const KData&) = HSL;\n\nIndicator (*IF_1)(const Indicator&, const Indicator&, const Indicator&) = IF;\nIndicator (*IF_2)(const Indicator&, price_t, const Indicator&) = IF;\nIndicator (*IF_3)(const Indicator&, const Indicator&, price_t) = IF;\nIndicator (*IF_4)(const Indicator&, price_t, price_t) = IF;\n\nIndicator (*COUNT_1)(int) = COUNT;\nIndicator (*COUNT_2)(const IndParam&) = COUNT;\nIndicator (*COUNT_3)(const Indicator&, const Indicator&) = COUNT;\nIndicator (*COUNT_4)(const Indicator&, const IndParam&) = COUNT;\nIndicator (*COUNT_5)(const Indicator&, int) = COUNT;\n\nIndicator (*SUM_1)(int) = SUM;\nIndicator (*SUM_2)(const IndParam&) = SUM;\nIndicator (*SUM_3)(const Indicator&, const IndParam&) = SUM;\nIndicator (*SUM_4)(const Indicator&, const Indicator&) = SUM;\nIndicator (*SUM_5)(const Indicator&, int) = SUM;\n\nIndicator (*ABS_1)() = ABS;\nIndicator (*ABS_2)(price_t) = ABS;\nIndicator (*ABS_3)(const Indicator&) = ABS;\n\nIndicator (*NOT_1)() = NOT;\nIndicator (*NOT_2)(const Indicator&) = NOT;\n\nIndicator (*SGN_1)() = SGN;\nIndicator (*SGN_2)(price_t) = SGN;\nIndicator (*SGN_3)(const Indicator&) = SGN;\n\nIndicator (*EXP_1)() = EXP;\nIndicator (*EXP_2)(price_t) = EXP;\nIndicator (*EXP_3)(const Indicator&) = EXP;\n\nIndicator (*MAX_1)(const Indicator&, const Indicator&) = MAX;\nIndicator (*MAX_2)(const Indicator&, price_t) = MAX;\nIndicator (*MAX_3)(price_t, const Indicator&) = MAX;\n\nIndicator (*MIN_1)(const Indicator&, const Indicator&) = MIN;\nIndicator (*MIN_2)(const Indicator&, price_t) = MIN;\nIndicator (*MIN_3)(price_t, const Indicator&) = MIN;\n\nIndicator (*BETWEEN_1)(const Indicator&, const Indicator&, const Indicator&) = BETWEEN;\nIndicator (*BETWEEN_2)(const Indicator&, const Indicator&, price_t) = BETWEEN;\nIndicator (*BETWEEN_3)(const Indicator&, price_t, const Indicator&) = BETWEEN;\nIndicator (*BETWEEN_4)(const Indicator&, price_t, price_t) = BETWEEN;\nIndicator (*BETWEEN_5)(price_t, const Indicator&, const Indicator&) = BETWEEN;\nIndicator (*BETWEEN_6)(price_t, const Indicator&, price_t) = BETWEEN;\nIndicator (*BETWEEN_7)(price_t, price_t, const Indicator&) = BETWEEN;\nIndicator (*BETWEEN_8)(price_t, price_t, price_t) = BETWEEN;\n\nIndicator (*LN_1)() = LN;\nIndicator (*LN_2)(price_t) = LN;\nIndicator (*LN_3)(const Indicator&) = LN;\n\nIndicator (*LOG_1)() = LOG;\nIndicator (*LOG_2)(price_t) = LOG;\nIndicator (*LOG_3)(const Indicator&) = LOG;\n\nIndicator (*HHVBARS_1)(int) = HHVBARS;\nIndicator (*HHVBARS_2)(const IndParam&) = HHVBARS;\nIndicator (*HHVBARS_3)(const Indicator&, const IndParam&) = HHVBARS;\nIndicator (*HHVBARS_4)(const Indicator&, const Indicator&) = HHVBARS;\nIndicator (*HHVBARS_5)(const Indicator&, int) = HHVBARS;\n\nIndicator (*LLVBARS_1)(int) = LLVBARS;\nIndicator (*LLVBARS_2)(const IndParam&) = LLVBARS;\nIndicator (*LLVBARS_3)(const Indicator&, const IndParam&) = LLVBARS;\nIndicator (*LLVBARS_4)(const Indicator&, const Indicator&) = LLVBARS;\nIndicator (*LLVBARS_5)(const Indicator&, int) = LLVBARS;\n\nIndicator (*POW_1)(int) = POW;\nIndicator (*POW_2)(const IndParam&) = POW;\nIndicator (*POW_3)(const Indicator&, int) = POW;\nIndicator (*POW_4)(const Indicator&, const IndParam&) = POW;\nIndicator (*POW_5)(const Indicator&, const Indicator&) = POW;\nIndicator (*POW_6)(price_t, int) = POW;\n\nIndicator (*SQRT_1)() = SQRT;\nIndicator (*SQRT_2)(const Indicator&) = SQRT;\nIndicator (*SQRT_3)(price_t) = SQRT;\n\nIndicator (*ROUND_1)(int) = ROUND;\nIndicator (*ROUND_2)(const Indicator&, int) = ROUND;\nIndicator (*ROUND_3)(price_t, int) = ROUND;\n\nIndicator (*ROUNDUP_1)(int) = ROUNDUP;\nIndicator (*ROUNDUP_2)(const Indicator&, int) = ROUNDUP;\nIndicator (*ROUNDUP_3)(price_t, int) = ROUNDUP;\n\nIndicator (*ROUNDDOWN_1)(int) = ROUNDDOWN;\nIndicator (*ROUNDDOWN_2)(const Indicator&, int) = ROUNDDOWN;\nIndicator (*ROUNDDOWN_3)(price_t, int) = ROUNDDOWN;\n\nIndicator (*FLOOR_1)() = FLOOR;\nIndicator (*FLOOR_2)(const Indicator&) = FLOOR;\nIndicator (*FLOOR_3)(price_t) = FLOOR;\n\nIndicator (*CEILING_1)() = CEILING;\nIndicator (*CEILING_2)(const Indicator&) = CEILING;\nIndicator (*CEILING_3)(price_t) = CEILING;\n\nIndicator (*INTPART_1)() = INTPART;\nIndicator (*INTPART_2)(const Indicator&) = INTPART;\nIndicator (*INTPART_3)(price_t) = INTPART;\n\nIndicator (*EXIST_1)(int) = EXIST;\nIndicator (*EXIST_2)(const IndParam&) = EXIST;\nIndicator (*EXIST_3)(const Indicator&, const IndParam&) = EXIST;\nIndicator (*EXIST_4)(const Indicator&, const Indicator&) = EXIST;\nIndicator (*EXIST_5)(const Indicator&, int) = EXIST;\n\nIndicator (*EVERY_1)(int) = EVERY;\nIndicator (*EVERY_2)(const IndParam&) = EVERY;\nIndicator (*EVERY_3)(const Indicator&, const IndParam&) = EVERY;\nIndicator (*EVERY_4)(const Indicator&, const Indicator&) = EVERY;\nIndicator (*EVERY_5)(const Indicator&, int) = EVERY;\n\nIndicator (*LAST_1)(int, int) = LAST;\nIndicator (*LAST_2)(const Indicator&, int, int) = LAST;\n\nIndicator (*SIN_1)() = SIN;\nIndicator (*SIN_2)(const Indicator&) = SIN;\nIndicator (*SIN_3)(price_t) = SIN;\n\nIndicator (*ASIN_1)() = ASIN;\nIndicator (*ASIN_2)(const Indicator&) = ASIN;\nIndicator (*ASIN_3)(price_t) = ASIN;\n\nIndicator (*COS_1)() = COS;\nIndicator (*COS_2)(const Indicator&) = COS;\nIndicator (*COS_3)(price_t) = COS;\n\nIndicator (*ACOS_1)() = ACOS;\nIndicator (*ACOS_2)(const Indicator&) = ACOS;\nIndicator (*ACOS_3)(price_t) = ACOS;\n\nIndicator (*TAN_1)() = TAN;\nIndicator (*TAN_2)(const Indicator&) = TAN;\nIndicator (*TAN_3)(price_t) = TAN;\n\nIndicator (*ATAN_1)() = ATAN;\nIndicator (*ATAN_2)(const Indicator&) = ATAN;\nIndicator (*ATAN_3)(price_t) = ATAN;\n\nIndicator (*REVERSE_1)() = REVERSE;\nIndicator (*REVERSE_2)(const Indicator&) = REVERSE;\nIndicator (*REVERSE_3)(price_t) = REVERSE;\n\nIndicator (*MOD_1)(const Indicator&, const Indicator&) = MOD;\nIndicator (*MOD_2)(const Indicator&, price_t) = MOD;\nIndicator (*MOD_3)(price_t, const Indicator&) = MOD;\nIndicator (*MOD_4)(price_t, price_t) = MOD;\n\nIndicator (*VAR_1)(int) = VAR;\nIndicator (*VAR_2)(const IndParam&) = VAR;\nIndicator (*VAR_3)(const Indicator&, const IndParam&) = VAR;\nIndicator (*VAR_4)(const Indicator&, const Indicator&) = VAR;\nIndicator (*VAR_5)(const Indicator&, int) = VAR;\n\nIndicator (*VARP_1)(int) = VARP;\nIndicator (*VARP_2)(const IndParam&) = VARP;\nIndicator (*VARP_3)(const Indicator&, const IndParam&) = VARP;\nIndicator (*VARP_4)(const Indicator&, const Indicator&) = VARP;\nIndicator (*VARP_5)(const Indicator&, int) = VARP;\n\nIndicator (*CROSS_1)(const Indicator&, const Indicator&) = CROSS;\nIndicator (*CROSS_2)(const Indicator&, price_t) = CROSS;\nIndicator (*CROSS_3)(price_t, const Indicator&) = CROSS;\nIndicator (*CROSS_4)(price_t, price_t) = CROSS;\n\nIndicator (*LONGCROSS_1)(const Indicator&, const Indicator&, int) = LONGCROSS;\nIndicator (*LONGCROSS_2)(const Indicator&, price_t, int) = LONGCROSS;\nIndicator (*LONGCROSS_3)(price_t, const Indicator&, int) = LONGCROSS;\nIndicator (*LONGCROSS_4)(price_t, price_t, int) = LONGCROSS;\n\nIndicator (*FILTER_1)(int) = FILTER;\nIndicator (*FILTER_2)(const IndParam&) = FILTER;\nIndicator (*FILTER_3)(const Indicator&, const IndParam&) = FILTER;\nIndicator (*FILTER_4)(const Indicator&, const Indicator&) = FILTER;\nIndicator (*FILTER_5)(const Indicator&, int) = FILTER;\n\nIndicator (*BARSSINCE_1)() = BARSSINCE;\nIndicator (*BARSSINCE_2)(const Indicator&) = BARSSINCE;\nIndicator (*BARSSINCE_3)(price_t) = BARSSINCE;\n\nIndicator (*BARSLAST_1)() = BARSLAST;\nIndicator (*BARSLAST_2)(const Indicator&) = BARSLAST;\nIndicator (*BARSLAST_3)(price_t) = BARSLAST;\n\nIndicator (*SUMBARS_1)(double) = SUMBARS;\nIndicator (*SUMBARS_2)(const IndParam&) = SUMBARS;\nIndicator (*SUMBARS_3)(const Indicator&, const IndParam&) = SUMBARS;\nIndicator (*SUMBARS_4)(const Indicator&, const Indicator&) = SUMBARS;\nIndicator (*SUMBARS_5)(const Indicator&, double) = SUMBARS;\n\nIndicator (*BARSCOUNT_1)() = BARSCOUNT;\nIndicator (*BARSCOUNT_2)(const Indicator&) = BARSCOUNT;\n\nIndicator (*BACKSET_1)(int) = BACKSET;\nIndicator (*BACKSET_2)(const IndParam&) = BACKSET;\nIndicator (*BACKSET_3)(const Indicator&, const IndParam&) = BACKSET;\nIndicator (*BACKSET_4)(const Indicator&, const Indicator&) = BACKSET;\nIndicator (*BACKSET_5)(const Indicator&, int) = BACKSET;\n\nIndicator (*TIMELINE_1)() = TIMELINE;\nIndicator (*TIMELINE_2)(const KData&) = TIMELINE;\n\nIndicator (*TIMELINEVOL_1)() = TIMELINEVOL;\nIndicator (*TIMELINEVOL_2)(const KData&) = TIMELINEVOL;\n\nIndicator (*DEVSQ_1)(int) = DEVSQ;\nIndicator (*DEVSQ_2)(const IndParam&) = DEVSQ;\nIndicator (*DEVSQ_3)(const Indicator&, const Indicator&) = DEVSQ;\nIndicator (*DEVSQ_4)(const Indicator&, const IndParam&) = DEVSQ;\nIndicator (*DEVSQ_5)(const Indicator&, int) = DEVSQ;\n\nIndicator (*ROC_1)(int) = ROC;\nIndicator (*ROC_2)(const IndParam&) = ROC;\nIndicator (*ROC_3)(const Indicator&, const IndParam&) = ROC;\nIndicator (*ROC_4)(const Indicator&, const Indicator&) = ROC;\nIndicator (*ROC_5)(const Indicator&, int) = ROC;\n\nIndicator (*ROCP_1)(int) = ROCP;\nIndicator (*ROCP_2)(const IndParam&) = ROCP;\nIndicator (*ROCP_3)(const Indicator&, const IndParam&) = ROCP;\nIndicator (*ROCP_4)(const Indicator&, const Indicator&) = ROCP;\nIndicator (*ROCP_5)(const Indicator&, int) = ROCP;\n\nIndicator (*ROCR_1)(int) = ROCR;\nIndicator (*ROCR_2)(const IndParam&) = ROCR;\nIndicator (*ROCR_3)(const Indicator&, const IndParam&) = ROCR;\nIndicator (*ROCR_4)(const Indicator&, const Indicator&) = ROCR;\nIndicator (*ROCR_5)(const Indicator&, int) = ROCR;\n\nIndicator (*ROCR100_1)(int) = ROCR100;\nIndicator (*ROCR100_2)(const IndParam&) = ROCR100;\nIndicator (*ROCR100_3)(const Indicator&, const IndParam&) = ROCR100;\nIndicator (*ROCR100_4)(const Indicator&, const Indicator&) = ROCR100;\nIndicator (*ROCR100_5)(const Indicator&, int) = ROCR100;\n\nIndicator (*AD_1)() = AD;\nIndicator (*AD_2)(const KData&) = AD;\n\nIndicator (*COST_1)(double x) = COST;\nIndicator (*COST_2)(const KData&, double x) = COST;\n\nIndicator (*ALIGN_1)(const DatetimeList&) = ALIGN;\nIndicator (*ALIGN_2)(const Indicator&, const DatetimeList&) = ALIGN;\nIndicator (*ALIGN_3)(const Indicator&, const Indicator&) = ALIGN;\nIndicator (*ALIGN_4)(const Indicator&, const KData&) = ALIGN;\n\nIndicator (*DROPNA_1)() = DROPNA;\nIndicator (*DROPNA_2)(const Indicator&) = DROPNA;\n\nIndicator (*AVEDEV_1)(const Indicator&, int) = AVEDEV;\nIndicator (*AVEDEV_2)(const Indicator&, const IndParam&) = AVEDEV;\nIndicator (*AVEDEV_3)(const Indicator&, const Indicator&) = AVEDEV;\n\nIndicator (*DOWNNDAY_1)(const Indicator&, int) = DOWNNDAY;\nIndicator (*DOWNNDAY_2)(const Indicator&, const IndParam&) = DOWNNDAY;\nIndicator (*DOWNNDAY_3)(const Indicator&, const Indicator&) = DOWNNDAY;\n\nIndicator (*UPNDAY_1)(const Indicator&, int) = UPNDAY;\nIndicator (*UPNDAY_2)(const Indicator&, const IndParam&) = UPNDAY;\nIndicator (*UPNDAY_3)(const Indicator&, const Indicator&) = UPNDAY;\n\nIndicator (*NDAY_1)(const Indicator&, const Indicator&, int) = NDAY;\nIndicator (*NDAY_2)(const Indicator&, const Indicator&, const Indicator&) = NDAY;\nIndicator (*NDAY_3)(const Indicator&, const Indicator&, const IndParam&) = NDAY;\n\nvoid export_Indicator_build_in() {\n    def(\"KDATA\", KDATA1);\n    def(\"KDATA\", KDATA3, R\"(KDATA([data])\n\n    包装KData成Indicator，用于其他指标计算\n\n    :param data: KData 或 具有6个返回结果的Indicator（如KDATA生成的Indicator）\n    :rtype: Indicator)\");\n\n    def(\"CLOSE\", CLOSE1);\n    def(\"CLOSE\", CLOSE3, R\"(CLOSE([data])\n\n    获取收盘价，包装KData的收盘价成Indicator\n\n    :param data: 输入数据（KData 或 Indicator）\n    :rtype: Indicator)\");\n\n    def(\"OPEN\", OPEN1);\n    def(\"OPEN\", OPEN3, R\"(OPEN([data])\n\n    获取开盘价，包装KData的开盘价成Indicator\n\n    :param data: 输入数据（KData 或 Indicator） \n    :rtype: Indicator)\");\n\n    def(\"HIGH\", HIGH1);\n    def(\"HIGH\", HIGH3, R\"(HIGH([data])\n\n    获取最高价，包装KData的最高价成Indicator\n\n    :param data: 输入数据（KData 或 Indicator） \n    :rtype: Indicator)\");\n\n    def(\"LOW\", LOW1);\n    def(\"LOW\", LOW3, R\"(LOW([data])\n\n    获取最低价，包装KData的最低价成Indicator\n\n    :param data: 输入数据（KData 或 Indicator） \n    :rtype: Indicator)\");\n\n    def(\"AMO\", AMO1);\n    def(\"AMO\", AMO3, R\"(AMO([data])\n\n    获取成交金额，包装KData的成交金额成Indicator\n    \n    :param data: 输入数据（KData 或 Indicator）\n    :rtype: Indicator)\");\n\n    def(\"VOL\", VOL1);\n    def(\"VOL\", VOL3, R\"(VOL([data])\n\n    获取成交量，包装KData的成交量成Indicator\n\n    :param data: 输入数据（KData 或 Indicator）\n    :rtype: Indicator)\");\n\n    def(\"KDATA_PART\", KDATA_PART1, (arg(\"data\"), arg(\"kpart\")));\n    def(\"KDATA_PART\", KDATA_PART3, (arg(\"kpart\")), R\"(KDATA_PART([data, kpart])\n\n    根据字符串选择返回指标KDATA/OPEN/HIGH/LOW/CLOSE/AMO/VOL，如:KDATA_PART(\"CLOSE\")等同于CLOSE()\n\n    :param data: 输入数据（KData 或 Indicator） \n    :param string kpart: KDATA|OPEN|HIGH|LOW|CLOSE|AMO|VOL\n    :rtype: Indicator)\");\n\n    def(\"PRICELIST\", PRICELIST2, (arg(\"data\"), arg(\"discard\") = 0));\n    def(\"PRICELIST\", PRICELIST3, (arg(\"data\"), arg(\"result_index\") = 0));\n    def(\"PRICELIST\", PRICELIST4, (arg(\"result_index\") = 0));\n\n    def(\"SMA\", SMA_1, (arg(\"n\") = 22, arg(\"m\") = 2.0));\n    def(\"SMA\", SMA_2, (arg(\"data\"), arg(\"n\") = 22, arg(\"m\") = 2.0), R\"(SMA([data, n=22, m=2])\n\n    求移动平均\n\n    用法：若Y=SMA(X,N,M) 则 Y=[M*X+(N-M)*Y')/N,其中Y'表示上一周期Y值\n\n    :param Indicator data: 输入数据\n    :param int n: 时间窗口\n    :param float m: 系数\n    :rtype: Indicator)\");\n\n    def(\"EMA\", EMA_1, (arg(\"n\") = 22));\n    def(\"EMA\", EMA_2, (arg(\"data\"), arg(\"n\") = 22), R\"(EMA([data, n=22])\n\n    指数移动平均线(Exponential Moving Average)\n\n    :param data: 输入数据\n    :param int n: 计算均值的周期窗口，必须为大于0的整数 \n    :rtype: Indicator)\");\n\n    def(\"MA\", MA_1, (arg(\"n\") = 22));\n    def(\"MA\", MA_2, (arg(\"n\")));\n    def(\"MA\", MA_3, (arg(\"data\"), arg(\"n\")));\n    def(\"MA\", MA_4, (arg(\"data\"), arg(\"n\")));\n    def(\"MA\", MA_5, (arg(\"data\"), arg(\"n\") = 22), R\"(MA([data, n=22])\n\n    简单移动平均\n\n    :param Indicator data: 输入数据\n    :param int|Indicator|IndParam n: 时间窗口\n    :rtype: Indicator)\");\n\n    def(\"AMA\", AMA_1, (arg(\"n\") = 10, arg(\"fast_n\") = 2, arg(\"slow_n\") = 30));\n    def(\"AMA\", AMA_2, (arg(\"data\"), arg(\"n\") = 10, arg(\"fast_n\") = 2, arg(\"slow_n\") = 30),\n        R\"(AMA([data, n=10, fast_n=2, slow_n=30])\n\n    佩里.J 考夫曼（Perry J.Kaufman）自适应移动平均 [BOOK1]_\n\n    :param Indicator data: 输入数据\n    :param int n: 计算均值的周期窗口，必须为大于2的整数\n    :param int fast_n: 对应快速周期N\n    :param int slow_n: 对应慢速EMA线的N值\n    :rtype: Indicator\n\n    * result(0): AMA\n    * result(1): ER)\");\n\n    def(\"ATR\", ATR_1, (arg(\"n\") = 14));\n    def(\"ATR\", ATR_2, (arg(\"data\"), arg(\"n\") = 14), R\"(ATR([data, n=14])\n\n    平均真实波幅(Average True Range)\n\n    :param Indicator data 待计算的源数据\n    :param int n: 计算均值的周期窗口，必须为大于1的整数\n    :rtype: Indicator)\");\n\n    def(\"MACD\", MACD_1, (arg(\"n1\") = 12, arg(\"n2\") = 26, arg(\"n3\") = 9));\n    def(\"MACD\", MACD_2, (arg(\"data\"), arg(\"n1\") = 12, arg(\"n2\") = 26, arg(\"n3\") = 9),\n        R\"(MACD([data, n1=12, n2=26, n3=9])\n\n    平滑异同移动平均线\n\n    :param Indicator data: 输入数据\n    :param int n1: 短期EMA时间窗\n    :param int n2: 长期EMA时间窗\n    :param int n3: （短期EMA-长期EMA）EMA平滑时间窗\n    :rtype: 具有三个结果集的 Indicator\n\n    * result(0): MACD_BAR：MACD直柱，即MACD快线－MACD慢线\n    * result(1): DIFF: 快线,即（短期EMA-长期EMA）\n    * result(2): DEA: 慢线，即快线的n3周期EMA平滑)\");\n\n    def(\"VIGOR\", VIGOR_1, (arg(\"kdata\"), arg(\"n\") = 2));\n    def(\"VIGOR\", VIGOR_2, (arg(\"n\") = 2), R\"(VIGOR([kdata, n=2])\n\n    亚历山大.艾尔德力度指数 [BOOK2]_\n\n    计算公式：（收盘价今－收盘价昨）＊成交量今\n\n    :param KData data: 输入数据\n    :param int n: EMA平滑窗口\n    :rtype: Indicator)\");\n\n    def(\"SAFTYLOSS\", SAFTYLOSS_1, (arg(\"n1\") = 10, arg(\"n2\") = 3, arg(\"p\") = 2.0));\n    def(\"SAFTYLOSS\", SAFTYLOSS_2, (arg(\"data\"), arg(\"n1\") = 10, arg(\"n2\") = 3, arg(\"p\") = 2.0),\n        R\"(SAFTYLOSS([data, n1=10, n2=3, p=2.0])\n\n    亚历山大 艾尔德安全地带止损线，参见 [BOOK2]_\n\n    计算说明：在回溯周期内（一般为10到20天），将所有向下穿越的长度相加除以向下穿越的次数，得到噪音均值（即回溯期内所有最低价低于前一日最低价的长度除以次数），并用今日最低价减去（前日噪音均值乘以一个倍数）得到该止损线。为了抵消波动并且保证止损线的上移，在上述结果的基础上再取起N日（一般为3天）内的最高值\n\n    :param Indicator data: 输入数据\n    :param int n1: 计算平均噪音的回溯时间窗口\n    :param int n2: 对初步止损线去n2日内的最高值\n    :param float p: 噪音系数\n    :rtype: Indicator)\");\n\n    def(\"DIFF\", DIFF_1);\n    def(\"DIFF\", DIFF_2, R\"(DIFF([data])\n\n    差分指标，即data[i] - data[i-1]\n\n    :param Indicator data: 输入数据\n    :rtype: Indicator)\");\n\n    def(\"REF\", REF_1, (arg(\"n\")));\n    def(\"REF\", REF_2, (arg(\"data\"), arg(\"n\")), R\"(REF([data, n])\n\n    向前引用 （即右移），引用若干周期前的数据。\n\n    用法：REF(X，A)　引用A周期前的X值。\n\n    :param Indicator data: 输入数据\n    :param int n: 引用n周期前的值，即右移n位\n    :rtype: Indicator)\");\n\n    def(\"STDEV\", STDEV_1, (arg(\"n\") = 10));\n    def(\"STDEV\", STDEV_2, (arg(\"n\")));\n    def(\"STDEV\", STDEV_3, (arg(\"data\"), arg(\"n\")));\n    def(\"STDEV\", STDEV_4, (arg(\"data\"), arg(\"n\")));\n    def(\"STDEV\", STDEV_5, (arg(\"data\"), arg(\"n\") = 10), R\"(STDEV([data, n=10])\n\n    计算N周期内样本标准差\n\n    :param Indicator data: 输入数据\n    :param int|Indicator|IndParam n: 时间窗口\n    :rtype: Indicator)\");\n\n    def(\"STDP\", STDP_1, (arg(\"n\") = 10));\n    def(\"STDP\", STDP_2, (arg(\"n\")));\n    def(\"STDP\", STDP_3, (arg(\"data\"), arg(\"n\")));\n    def(\"STDP\", STDP_4, (arg(\"data\"), arg(\"n\")));\n    def(\"STDP\", STDP_5, (arg(\"data\"), arg(\"n\") = 10), R\"(STDP([data, n=10])\n\n    总体标准差，STDP(X,N)为X的N日总体标准差\n\n    :param data: 输入数据\n    :param int n: 时间窗口\n    :rtype: Indicator)\");\n\n    def(\"POS\", POS, (arg(\"block\"), arg(\"query\"), arg(\"sg\")));\n\n    def(\"HHV\", HHV_1, (arg(\"n\") = 20));\n    def(\"HHV\", HHV_2, (arg(\"n\")));\n    def(\"HHV\", HHV_3, (arg(\"data\"), arg(\"n\")));\n    def(\"HHV\", HHV_4, (arg(\"data\"), arg(\"n\")));\n    def(\"HHV\", HHV_5, (arg(\"data\"), arg(\"n\") = 20), R\"(HHV([data, n=20])\n\n    N日内最高价，N=0则从第一个有效值开始。\n\n    :param Indicator data: 输入数据\n    :param int|Indicator|IndParam n: N日时间窗口\n    :rtype: Indicator)\");\n\n    def(\"LLV\", LLV_1, (arg(\"n\") = 20));\n    def(\"LLV\", LLV_2, (arg(\"n\")));\n    def(\"LLV\", LLV_3, (arg(\"data\"), arg(\"n\")));\n    def(\"LLV\", LLV_4, (arg(\"data\"), arg(\"n\")));\n    def(\"LLV\", LLV_5, (arg(\"data\"), arg(\"n\") = 20), R\"(LLV([data, n=20])\n\n    N日内最低价，N=0则从第一个有效值开始。\n\n    :param data: 输入数据\n    :param int|Indicator|IndParam n: N日时间窗口\n    :rtype: Indicator)\");\n\n    def(\"CVAL\", CVAL_1, (arg(\"value\") = 0.0, arg(\"discard\") = 0));\n    def(\"CVAL\", CVAL_2, (arg(\"data\"), arg(\"value\") = 0.0, arg(\"discard\") = 0),\n        R\"(CVAL([data, value=0.0, discard=0])\n\n    data 为 Indicator 实例，创建和 data 等长的常量指标，其值和为value，抛弃长度discard和data一样\n\n    :param Indicator data: Indicator实例\n    :param float value: 常数值\n    :param int discard: 抛弃数量\n    :rtype: Indicator)\");\n\n    def(\"LIUTONGPAN\", LIUTONGPAN_1);\n    def(\"LIUTONGPAN\", LIUTONGPAN_2, R\"(LIUTONGPAN(kdata)\n\n   获取流通盘（单位：万股），同 CAPITAL\n\n   :param KData kdata: k线数据\n   :rtype: Indicator)\");\n\n    def(\"HSL\", HSL_1);\n    def(\"HSL\", HSL_2, R\"(HSL(kdata)\n\n    获取换手率，等于 VOL(k) / CAPITAL(k)\n\n    :param KData kdata: k线数据\n    :rtype: Indicator)\");\n\n    def(\"WEAVE\", WEAVE, R\"(WEAVE(ind1, ind2)\n\n    将ind1和ind2的结果组合在一起放在一个Indicator中。如ind = WEAVE(ind1, ind2), 则此时ind包含多个结果，按ind1、ind2的顺序存放。\n    \n    :param Indicator ind1: 指标1\n    :param Indicator ind2: 指标2\n    :rtype: Indicator)\");\n\n    def(\"IF\", IF_1);\n    def(\"IF\", IF_2);\n    def(\"IF\", IF_3);\n    def(\"IF\", IF_4, R\"(IF(x, a, b)\n\n    条件函数, 根据条件求不同的值。\n\n    用法：IF(X,A,B)若X不为0则返回A,否则返回B\n\n    例如：IF(CLOSE>OPEN,HIGH,LOW)表示该周期收阳则返回最高值,否则返回最低值\n\n    :param Indicator x: 条件指标\n    :param Indicator a: 待选指标 a\n    :param Indicator b: 待选指标 b\n    :rtype: Indicator)\");\n\n    def(\"COUNT\", COUNT_1, (arg(\"n\") = 20));\n    def(\"COUNT\", COUNT_2, (arg(\"n\")));\n    def(\"COUNT\", COUNT_3, (arg(\"data\"), arg(\"n\")));\n    def(\"COUNT\", COUNT_4, (arg(\"data\"), arg(\"n\")));\n    def(\"COUNT\", COUNT_5, (arg(\"data\"), arg(\"n\") = 20), R\"(COUNT([data, n=20])\n\n    统计满足条件的周期数。\n\n    用法：COUNT(X,N),统计N周期中满足X条件的周期数,若N=0则从第一个有效值开始。\n\n    例如：COUNT(CLOSE>OPEN,20)表示统计20周期内收阳的周期数\n\n    :param Indicator data: 条件\n    :param int|Indicator|IndParam n: 周期\n    :rtype: Indicator)\");\n\n    def(\"SUM\", SUM_1, (arg(\"n\") = 20));\n    def(\"SUM\", SUM_2, (arg(\"n\")));\n    def(\"SUM\", SUM_3, (arg(\"data\"), arg(\"n\")));\n    def(\"SUM\", SUM_4, (arg(\"data\"), arg(\"n\")));\n    def(\"SUM\", SUM_5, (arg(\"data\"), arg(\"n\") = 20), R\"(SUM([data, n=20])\n\n    求总和。SUM(X,N),统计N周期中X的总和,N=0则从第一个有效值开始。\n\n    :param Indicator data: 输入数据\n    :param int|Indicator|IndParam n: 时间窗口\n    :rtype: Indicator)\");\n\n    def(\"ABS\", ABS_1);\n    def(\"ABS\", ABS_2);\n    def(\"ABS\", ABS_3, R\"(ABS([data])\n\n    求绝对值\n\n    :param Indicator data: 输入数据\n    :rtype: Indicator)\");\n\n    def(\"NOT\", NOT_1);\n    def(\"NOT\", NOT_2, R\"(NOT([data])\n\n    求逻辑非。NOT(X)返回非X,即当X=0时返回1，否则返回0。\n\n    :param Indicator data: 输入数据\n    :rtype: Indicator)\");\n\n    def(\"SGN\", SGN_1);\n    def(\"SGN\", SGN_2);\n    def(\"SGN\", SGN_3, R\"(SGN([data])\n\n    求符号值, SGN(X)，当 X>0, X=0, X<0分别返回 1, 0, -1。\n\n    :param Indicator data: 输入数据\n    :rtype: Indicator)\");\n\n    def(\"EXP\", EXP_1);\n    def(\"EXP\", EXP_2);\n    def(\"EXP\", EXP_3, R\"(EXP([data])\n\n    EXP(X)为e的X次幂\n\n    :param Indicator data: 输入数据\n    :rtype: Indicator)\");\n\n    def(\"MAX\", MAX_1);\n    def(\"MAX\", MAX_2);\n    def(\"MAX\", MAX_3, R\"(MAX(ind1, ind2)\n\n    求最大值, MAX(A,B)返回A和B中的较大值。\n\n    :param Indicator ind1: A\n    :param Indicator ind2: B\n    :rtype: Indicator)\");\n\n    def(\"MIN\", MIN_1);\n    def(\"MIN\", MIN_2);\n    def(\"MIN\", MIN_3, R\"(MIN(ind1, ind2)\n\n    求最小值, MIN(A,B)返回A和B中的较小值。\n\n    :param Indicator ind1: A\n    :param Indicator ind2: B\n    :rtype: Indicator)\");\n\n    def(\"BETWEEN\", BETWEEN_1);\n    def(\"BETWEEN\", BETWEEN_2);\n    def(\"BETWEEN\", BETWEEN_3);\n    def(\"BETWEEN\", BETWEEN_4);\n    def(\"BETWEEN\", BETWEEN_5);\n    def(\"BETWEEN\", BETWEEN_6);\n    def(\"BETWEEN\", BETWEEN_7);\n    def(\"BETWEEN\", BETWEEN_8, R\"(BETWEEN(a, b, c)\n\n    介于(介于两个数之间)\n\n    用法：BETWEEN(A,B,C)表示A处于B和C之间时返回1，否则返回0\n\n    例如：BETWEEN(CLOSE,MA(CLOSE,10),MA(CLOSE,5))表示收盘价介于5日均线和10日均线之间\n\n    :param Indicator a: A\n    :param Indicator b: B\n    :param Indicator c: C\n    :rtype: Indicator)\");\n\n    def(\"LN\", LN_1);\n    def(\"LN\", LN_2);\n    def(\"LN\", LN_3, R\"(LN([data])\n\n    求自然对数, LN(X)以e为底的对数\n\n    :param data: 输入数据\n    :rtype: Indicator)\");\n\n    def(\"LOG\", LOG_1);\n    def(\"LOG\", LOG_2);\n    def(\"LOG\", LOG_3, R\"(LOG([data])\n\n    以10为底的对数\n\n    :param data: 输入数据\n    :rtype: Indicator)\");\n\n    def(\"HHVBARS\", HHVBARS_1, (arg(\"n\") = 20));\n    def(\"HHVBARS\", HHVBARS_2, (arg(\"n\")));\n    def(\"HHVBARS\", HHVBARS_3, (arg(\"data\"), arg(\"n\")));\n    def(\"HHVBARS\", HHVBARS_4, (arg(\"data\"), arg(\"n\")));\n    def(\"HHVBARS\", HHVBARS_5, (arg(\"data\"), arg(\"n\") = 20), R\"(HHVBARS([data, n=20])\n\n    上一高点位置 求上一高点到当前的周期数。\n\n    用法：HHVBARS(X,N):求N周期内X最高值到当前周期数N=0表示从第一个有效值开始统计\n\n    例如：HHVBARS(HIGH,0)求得历史新高到到当前的周期数\n\n    :param Indicator data: 输入数据\n    :param int|Indicator|IndParam n: N日时间窗口\n    :rtype: Indicator)\");\n\n    def(\"LLVBARS\", LLVBARS_1, (arg(\"n\") = 20));\n    def(\"LLVBARS\", LLVBARS_2, (arg(\"n\")));\n    def(\"LLVBARS\", LLVBARS_3, (arg(\"data\"), arg(\"n\")));\n    def(\"LLVBARS\", LLVBARS_4, (arg(\"data\"), arg(\"n\")));\n    def(\"LLVBARS\", LLVBARS_5, (arg(\"data\"), arg(\"n\") = 20), R\"(LLVBARS([data, n=20])\n\n    上一低点位置 求上一低点到当前的周期数。\n\n    用法：LLVBARS(X,N):求N周期内X最低值到当前周期数N=0表示从第一个有效值开始统计\n\n    例如：LLVBARS(HIGH,20)求得20日最低点到当前的周期数\n\n    :param data: 输入数据\n    :param int|Indicator|IndParam n: N日时间窗口\n    :rtype: Indicator)\");\n\n    def(\"POW\", POW_1, (arg(\"n\")));\n    def(\"POW\", POW_2, (arg(\"n\")));\n    def(\"POW\", POW_3, (arg(\"data\"), arg(\"n\")));\n    def(\"POW\", POW_4, (arg(\"data\"), arg(\"n\")));\n    def(\"POW\", POW_5, (arg(\"data\"), arg(\"n\")));\n    def(\"POW\", POW_6), (arg(\"data\"), arg(\"n\"), R\"(POW(data, n)\n\n    乘幂\n\n    用法：POW(A,B)返回A的B次幂\n\n    例如：POW(CLOSE,3)求得收盘价的3次方\n\n    :param data: 输入数据\n    :param int|Indicator|IndParam n: 幂\n    :rtype: Indicator)\");\n\n    def(\"SQRT\", SQRT_1);\n    def(\"SQRT\", SQRT_2);\n    def(\"SQRT\", SQRT_3, R\"(SQRT([data])\n\n    开平方\n\n    用法：SQRT(X)为X的平方根\n\n    例如：SQRT(CLOSE)收盘价的平方根\n\n    :param data: 输入数据\n    :rtype: Indicator)\");\n\n    def(\"ROUND\", ROUND_1, (arg(\"ndigits\") = 2));\n    def(\"ROUND\", ROUND_2, (arg(\"data\"), arg(\"ndigits\") = 2));\n    def(\"ROUND\", ROUND_3, (arg(\"data\"), arg(\"ndigits\") = 2), R\"(ROUND([data, ndigits=2])\n\n    四舍五入\n\n    :param data: 输入数据\n    :param int ndigits: 保留的小数点后位数\n    :rtype: Indicator)\");\n\n    def(\"ROUNDUP\", ROUNDUP_1, (arg(\"ndigits\") = 2));\n    def(\"ROUNDUP\", ROUNDUP_2, (arg(\"data\"), arg(\"ndigits\") = 2));\n    def(\"ROUNDUP\", ROUNDUP_3, (arg(\"data\"), arg(\"ndigits\") = 2), R\"(ROUNDUP([data, ndigits=2])\n\n    向上截取，如10.1截取后为11\n\n    :param data: 输入数据\n    :param int ndigits: 保留的小数点后位数\n    :rtype: Indicator)\");\n\n    def(\"ROUNDDOWN\", ROUNDDOWN_1, (arg(\"ndigits\") = 2));\n    def(\"ROUNDDOWN\", ROUNDDOWN_2, (arg(\"data\"), arg(\"ndigits\") = 2));\n    def(\"ROUNDDOWN\", ROUNDDOWN_3, (arg(\"data\"), arg(\"ndigits\") = 2), R\"(ROUND([data, ndigits=2])\n\n    四舍五入\n\n    :param data: 输入数据\n    :param int ndigits: 保留的小数点后位数\n    :rtype: Indicator)\");\n\n    def(\"FLOOR\", FLOOR_1);\n    def(\"FLOOR\", FLOOR_2);\n    def(\"FLOOR\", FLOOR_3, R\"(FLOOR([data])\n\n    向下舍入(向数值减小方向舍入)取整\n\n    用法：FLOOR(A)返回沿A数值减小方向最接近的整数\n\n    例如：FLOOR(12.3)求得12\n\n    :param data: 输入数据\n    :rtype: Indicator)\");\n\n    def(\"CEILING\", CEILING_1);\n    def(\"CEILING\", CEILING_2);\n    def(\"CEILING\", CEILING_3, R\"(CEILING([data])\n\n    向上舍入(向数值增大方向舍入)取整\n   \n    用法：CEILING(A)返回沿A数值增大方向最接近的整数\n   \n    例如：CEILING(12.3)求得13；CEILING(-3.5)求得-3\n   \n    :param data: 输入数据\n    :rtype: Indicator)\");\n\n    def(\"INTPART\", INTPART_1);\n    def(\"INTPART\", INTPART_2);\n    def(\"INTPART\", INTPART_3, R\"(INTPART([data])\n\n    取整(绝对值减小取整，即取得数据的整数部分)\n\n    :param data: 输入数据\n    :rtype: Indicator)\");\n\n    def(\"EXIST\", EXIST_1, (arg(\"n\") = 20));\n    def(\"EXIST\", EXIST_2, (arg(\"n\")));\n    def(\"EXIST\", EXIST_3, (arg(\"data\"), arg(\"n\")));\n    def(\"EXIST\", EXIST_4, (arg(\"data\"), arg(\"n\")));\n    def(\"EXIST\", EXIST_5, (arg(\"data\"), arg(\"n\") = 20), R\"(EXIST([data, n=20])\n\n    存在, EXIST(X,N) 表示条件X在N周期有存在\n\n    :param data: 输入数据\n    :param int|Indicator|IndParam n: 计算均值的周期窗口，必须为大于0的整数 \n    :rtype: Indicator)\");\n\n    def(\"EVERY\", EVERY_1, (arg(\"n\") = 20));\n    def(\"EVERY\", EVERY_2, (arg(\"n\")));\n    def(\"EVERY\", EVERY_3, (arg(\"data\"), arg(\"n\")));\n    def(\"EVERY\", EVERY_4, (arg(\"data\"), arg(\"n\")));\n    def(\"EVERY\", EVERY_5, (arg(\"data\"), arg(\"n\") = 20), R\"(EVERY([data, n=20])\n\n    一直存在\n\n    用法：EVERY (X,N) 表示条件X在N周期一直存在\n\n    例如：EVERY(CLOSE>OPEN,10) 表示前10日内一直是阳线\n\n    :param data: 输入数据\n    :param int|Indicator|IndParam n: 计算均值的周期窗口，必须为大于0的整数 \n    :rtype: Indicator)\");\n\n    def(\"LAST\", LAST_1, (arg(\"m\") = 10, arg(\"n\") = 5));\n    def(\"LAST\", LAST_2, (arg(\"data\"), arg(\"m\") = 10, arg(\"n\") = 5), R\"(LAST([data, m=10, n=5])\n\n    区间存在。\n\n    用法：LAST (X,M,N) 表示条件 X 在前 M 周期到前 N 周期存在。\n\n    例如：LAST(CLOSE>OPEN,10,5) 表示从前10日到前5日内一直阳线。\n\n    :param data: 输入数据\n    :param int m: m周期\n    :param int n: n周期\n    :rtype: Indicator)\");\n\n    def(\"SIN\", SIN_1);\n    def(\"SIN\", SIN_2);\n    def(\"SIN\", SIN_3, R\"(SIN([data])\n\n    正弦值\n\n    :param Indicator data: 输入数据\n    :rtype: Indicator)\");\n\n    def(\"ASIN\", ASIN_1);\n    def(\"ASIN\", ASIN_2);\n    def(\"ASIN\", ASIN_3, R\"(ASIN([data])\n\n    反正弦值\n\n    :param Indicator data: 输入数据\n    :rtype: Indicator)\");\n\n    def(\"COS\", COS_1);\n    def(\"COS\", COS_2);\n    def(\"COS\", COS_3, R\"(COS([data])\n\n    余弦值\n\n    :param Indicator data: 输入数据\n    :rtype: Indicator)\");\n\n    def(\"ACOS\", ACOS_1);\n    def(\"ACOS\", ACOS_2);\n    def(\"ACOS\", ACOS_3, R\"(ACOS([data])\n\n    反余弦值\n\n    :param Indicator data: 输入数据\n    :rtype: Indicator)\");\n\n    def(\"TAN\", TAN_1);\n    def(\"TAN\", TAN_2);\n    def(\"TAN\", TAN_3, R\"(TAN([data])\n\n    正切值\n\n    :param Indicator data: 输入数据\n    :rtype: Indicato)\");\n\n    def(\"ATAN\", ATAN_1);\n    def(\"ATAN\", ATAN_2);\n    def(\"ATAN\", ATAN_3, R\"(ATAN([data])\n\n    反正切值\n\n    :param Indicator data: 输入数据\n    :rtype: Indicator)\");\n\n    def(\"REVERSE\", REVERSE_1);\n    def(\"REVERSE\", REVERSE_2);\n    def(\"REVERSE\", REVERSE_3, R\"(REVERSE([data])\n\n    求相反数，REVERSE(X)返回-X\n\n    :param Indicator data: 输入数据\n    :rtype: Indicator)\");\n\n    def(\"MOD\", MOD_1);\n    def(\"MOD\", MOD_2);\n    def(\"MOD\", MOD_3);\n    def(\"MOD\", MOD_4, R\"(MOD(ind1, ind2)\n\n    取整后求模。该函数仅为兼容通达信。实际上，指标求模可直接使用 % 操作符\n\n    用法：MOD(A,B)返回A对B求模\n\n    例如：MOD(26,10) 返回 6\n\n    :param Indicator ind1:\n    :param Indicator ind2:\n    :rtype: Indicator)\");\n\n    def(\"VAR\", VAR_1, (arg(\"n\") = 10));\n    def(\"VAR\", VAR_2, (arg(\"n\")));\n    def(\"VAR\", VAR_3, (arg(\"data\"), arg(\"n\")));\n    def(\"VAR\", VAR_4, (arg(\"data\"), arg(\"n\")));\n    def(\"VAR\", VAR_5, (arg(\"data\"), arg(\"n\") = 10), R\"(VAR([data, n=10])\n\n    估算样本方差, VAR(X,N)为X的N日估算样本方差\n\n    :param Indicator data: 输入数据\n    :param int|Indicator|IndParam n: 时间窗口\n    :rtype: Indicator)\");\n\n    def(\"VARP\", VARP_1, (arg(\"n\") = 10));\n    def(\"VARP\", VARP_2, (arg(\"n\")));\n    def(\"VARP\", VARP_3, (arg(\"data\"), arg(\"n\")));\n    def(\"VARP\", VARP_4, (arg(\"data\"), arg(\"n\")));\n    def(\"VARP\", VARP_5, (arg(\"data\"), arg(\"n\") = 10), R\"(VARP([data, n=10])\n\n    总体样本方差, VARP(X,N)为X的N日总体样本方差\n\n    :param Indicator data: 输入数据\n    :param int n|Indicator|IndParam: 时间窗口\n    :rtype: Indicator)\");\n\n    def(\"UPNDAY\", UPNDAY_1, (arg(\"data\"), arg(\"n\") = 3));\n    def(\"UPNDAY\", UPNDAY_2, (arg(\"data\"), arg(\"n\")));\n    def(\"UPNDAY\", UPNDAY_3, (arg(\"data\"), arg(\"n\")), R\"(UPNDAY(data[, n=3])\n\n    连涨周期数, UPNDAY(CLOSE,M)表示连涨M个周期\n\n    :param Indicator data: 输入数据\n    :param int|Indicator|IndParam n: 时间窗口\n    :rtype: Indicator)\");\n\n    def(\"DOWNNDAY\", DOWNNDAY_1, (arg(\"data\"), arg(\"n\") = 3));\n    def(\"DOWNNDAY\", DOWNNDAY_2, (arg(\"data\"), arg(\"n\")));\n    def(\"DOWNNDAY\", DOWNNDAY_3, (arg(\"data\"), arg(\"n\")), R\"(DOWNNDAY(data[, n=3])\n\n    连跌周期数, DOWNNDAY(CLOSE,M)表示连涨M个周期\n\n    :param Indicator data: 输入数据\n    :param int|Indicator|IndParam n: 时间窗口\n    :rtype: Indicator)\");\n\n    def(\"NDAY\", NDAY_1, (arg(\"x\"), arg(\"y\"), arg(\"n\") = 3));\n    def(\"NDAY\", NDAY_1, (arg(\"x\"), arg(\"y\"), arg(\"n\")));\n    def(\"NDAY\", NDAY_3, (arg(\"x\"), arg(\"y\"), arg(\"n\")), R\"(NDAY(x, y[, n=3])\n\n    连大, NDAY(X,Y,N)表示条件X>Y持续存在N个周期\n\n    :param Indicator x:\n    :param Indicator y:\n    :param int|Indicator|IndParam n: 时间窗口\n    :rtype: Indicator)\");\n\n    def(\"CROSS\", CROSS_1);\n    def(\"CROSS\", CROSS_2);\n    def(\"CROSS\", CROSS_3);\n    def(\"CROSS\", CROSS_4, R\"(CROSS(x, y)\n\n    交叉函数\n\n    :param x: 变量或常量，判断交叉的第一条线\n    :param y: 变量或常量，判断交叉的第二条线\n    :rtype: Indicator)\");\n\n    def(\"LONGCROSS\", LONGCROSS_1, (arg(\"a\"), arg(\"b\"), arg(\"n\") = 3));\n    def(\"LONGCROSS\", LONGCROSS_2, (arg(\"a\"), arg(\"b\"), arg(\"n\") = 3));\n    def(\"LONGCROSS\", LONGCROSS_3, (arg(\"a\"), arg(\"b\"), arg(\"n\") = 3));\n    def(\"LONGCROSS\", LONGCROSS_4, (arg(\"a\"), arg(\"b\"), arg(\"n\") = 3), R\"(LONGCROSS(a, b[, n=3])\n\n    两条线维持一定周期后交叉\n\n    用法：LONGCROSS(A,B,N)表示A在N周期内都小于B，本周期从下方向上穿过B时返 回1，否则返回0\n\n    例如：LONGCROSS(MA(CLOSE,5),MA(CLOSE,10),5)表示5日均线维持5周期后与10日均线交金叉\n\n    :param Indicator a:\n    :param Indicator b:\n    :param int n:\n    :rtype: Indicator)\");\n\n    def(\"FILTER\", FILTER_1, (arg(\"n\") = 5));\n    def(\"FILTER\", FILTER_2, (arg(\"n\")));\n    def(\"FILTER\", FILTER_3, (arg(\"data\"), arg(\"n\")));\n    def(\"FILTER\", FILTER_4, (arg(\"data\"), arg(\"n\")));\n    def(\"FILTER\", FILTER_5, (arg(\"data\"), arg(\"n\") = 5), R\"(FILTER([data, n=5])\n\n    信号过滤, 过滤连续出现的信号。\n\n    用法：FILTER(X,N): X 满足条件后，删除其后 N 周期内的数据置为 0。\n\n    例如：FILTER(CLOSE>OPEN,5) 查找阳线，5 天内再次出现的阳线不被记录在内。\n\n    :param Indicator data: 输入数据\n    :param int|Indicaot|IndParam n: 过滤周期\n    :rtype: Indicator)\");\n\n    def(\"BARSSINCE\", BARSSINCE_1);\n    def(\"BARSSINCE\", BARSSINCE_2);\n    def(\"BARSSINCE\", BARSSINCE_3, R\"(BARSSINCE([data])\n\n    第一个条件成立位置到当前的周期数。\n\n    用法：BARSSINCE(X):第一次X不为0到现在的天数。\n\n    例如：BARSSINCE(HIGH>10)表示股价超过10元时到当前的周期数\n\n    :param Indicator data: 输入数据\n    :rtype: Indicator)\");\n\n    def(\"BARSLAST\", BARSLAST_1);\n    def(\"BARSLAST\", BARSLAST_2);\n    def(\"BARSLAST\", BARSLAST_3, R\"(BARSLAST([data])\n\n    上一次条件成立位置 上一次条件成立到当前的周期数。\n\n    用法：BARSLAST(X): 上一次 X 不为 0 到现在的天数。\n\n    例如：BARSLAST(CLOSE/REF(CLOSE,1)>=1.1) 表示上一个涨停板到当前的周期数\n\n    :param Indicator data: 输入数据\n    :rtype: Indicator)\");\n\n    def(\"SUMBARS\", SUMBARS_1, (arg(\"a\")));\n    def(\"SUMBARS\", SUMBARS_2, (arg(\"a\")));\n    def(\"SUMBARS\", SUMBARS_3, (arg(\"data\"), arg(\"a\")));\n    def(\"SUMBARS\", SUMBARS_4, (arg(\"data\"), arg(\"a\")));\n    def(\"SUMBARS\", SUMBARS_5, (arg(\"data\"), arg(\"a\")), R\"(SUMBARS([data,] a)\n\n    累加到指定周期数, 向前累加到指定值到现在的周期数\n\n    用法：SUMBARS(X,A):将X向前累加直到大于等于A,返回这个区间的周期数\n\n    例如：SUMBARS(VOL,CAPITAL)求完全换手到现在的周期数\n\n    :param Indicator data: 输入数据\n    :param float a|Indicator|IndParam: 指定累加和\n    :rtype: Indicator)\");\n\n    def(\"BARSCOUNT\", BARSCOUNT_1);\n    def(\"BARSCOUNT\", BARSCOUNT_2, R\"(BARSCOUNT([data])\n\n    有效值周期数, 求总的周期数。\n\n    用法：BARSCOUNT(X)第一个有效数据到当前的天数。\n\n    例如：BARSCOUNT(CLOSE)对于日线数据取得上市以来总交易日数，对于1分钟线取得当日交易分钟数。\n\n    :param Indicator data: 输入数据\n    :rtype: Indicator)\");\n\n    def(\"BACKSET\", BACKSET_1, (arg(\"n\") = 2));\n    def(\"BACKSET\", BACKSET_2, (arg(\"n\")));\n    def(\"BACKSET\", BACKSET_3, (arg(\"data\"), arg(\"n\")));\n    def(\"BACKSET\", BACKSET_4, (arg(\"data\"), arg(\"n\")));\n    def(\"BACKSET\", BACKSET_5, (arg(\"data\"), arg(\"n\") = 2), R\"(BACKSET([data, n=2])\n\n    向前赋值将当前位置到若干周期前的数据设为1。\n\n    用法：BACKSET(X,N),X非0,则将当前位置到N周期前的数值设为1。\n\n    例如：BACKSET(CLOSE>OPEN,2)若收阳则将该周期及前一周期数值设为1,否则为0\n\n    :param Indicator data: 输入数据\n    :param int|Indicator|IndParam n: N周期\n    :rtype: Indicator)\");\n\n    def(\"TIMELINE\", TIMELINE_1);\n    def(\"TIMELINE\", TIMELINE_2, R\"(TIMELINE([k])\n\n    分时价格数据\n\n    :param KData k: 上下文\n    :rtype: Indicator)\");\n\n    def(\"TIMELINEVOL\", TIMELINEVOL_1);\n    def(\"TIMELINEVOL\", TIMELINEVOL_2, R\"(TIMELINEVOL([k])\n\n    分时成交量数据\n\n    :param KData k: 上下文\n    :rtype: Indicator)\");\n\n    def(\"DMA\", DMA, R\"(DMA(ind, a)\n\n    动态移动平均\n\n    用法：DMA(X,A),求X的动态移动平均。\n\n    算法：若Y=DMA(X,A) 则 Y=A*X+(1-A)*Y',其中Y'表示上一周期Y值。\n\n    例如：DMA(CLOSE,VOL/CAPITAL)表示求以换手率作平滑因子的平均价\n\n    :param Indicator ind: 输入数据\n    :param Indicator a: 动态系数\n    :rtype: Indicator)\");\n\n    def(\"AVEDEV\", AVEDEV_1, (arg(\"data\"), arg(\"n\") = 22));\n    def(\"AVEDEV\", AVEDEV_2, (arg(\"data\"), arg(\"n\")));\n    def(\"AVEDEV\", AVEDEV_3, (arg(\"data\"), arg(\"n\")), R\"(AVEDEV(data[, n=22])\n\n    平均绝对偏差，求X的N日平均绝对偏差\n\n    :param Indicator data: 输入数据\n    :param int|Indicator|IndParam n: 时间窗口\n    :rtype: Indicator)\");\n\n    def(\"DEVSQ\", DEVSQ_1, (arg(\"n\") = 10));\n    def(\"DEVSQ\", DEVSQ_2, (arg(\"n\")));\n    def(\"DEVSQ\", DEVSQ_3, (arg(\"data\"), arg(\"n\")));\n    def(\"DEVSQ\", DEVSQ_4, (arg(\"data\"), arg(\"n\")));\n    def(\"DEVSQ\", DEVSQ_5, (arg(\"data\"), arg(\"n\") = 10), R\"(DEVSQ([data, n=10])\n\n    数据偏差平方和，求X的N日数据偏差平方和\n\n    :param Indicator data: 输入数据\n    :param int|Indicator n: 时间窗口\n    :rtype: Indicator)\");\n\n    def(\"ROC\", ROC_1, (arg(\"n\") = 10));\n    def(\"ROC\", ROC_2, (arg(\"n\")));\n    def(\"ROC\", ROC_3, (arg(\"data\"), arg(\"n\")));\n    def(\"ROC\", ROC_4, (arg(\"data\"), arg(\"n\")));\n    def(\"ROC\", ROC_5, (arg(\"data\"), arg(\"n\") = 10), R\"(ROC([data, n=10])\n\n    变动率指标: ((price / prevPrice)-1)*100\n\n    :param data: 输入数据\n    :param int n: 时间窗口\n    :rtype: Indicator)\");\n\n    def(\"ROCP\", ROCP_1, (arg(\"n\") = 10));\n    def(\"ROCP\", ROCP_2, (arg(\"n\")));\n    def(\"ROCP\", ROCP_3, (arg(\"data\"), arg(\"n\")));\n    def(\"ROCP\", ROCP_4, (arg(\"data\"), arg(\"n\")));\n    def(\"ROCP\", ROCP_5, (arg(\"data\"), arg(\"n\") = 10), R\"(ROCP([data, n=10])\n\n    变动率指标: (price - prevPrice) / prevPrice\n\n    :param data: 输入数据\n    :param int n: 时间窗口\n    :rtype: Indicator)\");\n\n    def(\"ROCR\", ROCR_1, (arg(\"n\") = 10));\n    def(\"ROCR\", ROCR_2, (arg(\"n\")));\n    def(\"ROCR\", ROCR_3, (arg(\"data\"), arg(\"n\")));\n    def(\"ROCR\", ROCR_4, (arg(\"data\"), arg(\"n\")));\n    def(\"ROCR\", ROCR_5, (arg(\"data\"), arg(\"n\") = 10), R\"(ROCR([data, n=10])\n\n    变动率指标: (price / prevPrice)\n\n    :param data: 输入数据\n    :param int n|Indicator|IndParam: 时间窗口\n    :rtype: Indicator)\");\n\n    def(\"ROCR100\", ROCR100_1, (arg(\"n\") = 10));\n    def(\"ROCR100\", ROCR100_2, (arg(\"n\")));\n    def(\"ROCR100\", ROCR100_3, (arg(\"data\"), arg(\"n\")));\n    def(\"ROCR100\", ROCR100_4, (arg(\"data\"), arg(\"n\")));\n    def(\"ROCR100\", ROCR100_5, (arg(\"data\"), arg(\"n\") = 10), R\"(ROCR100([data, n=10])\n\n    变动率指标: (price / prevPrice) * 100\n\n    :param data: 输入数据\n    :param int|Indicator|IndParam n: 时间窗口\n    :rtype: Indicator)\");\n\n    def(\"AD\", AD_1);\n    def(\"AD\", AD_2, R\"(AD(kdata)\n\n   累积/派发线\n\n   :param KData kdata: k线数据\n   :rtype: Indicator)\");\n\n    def(\"COST\", COST_1, (arg(\"x\") = 10.0));\n    def(\"COST\", COST_2, (arg(\"k\"), arg(\"x\") = 10.0), R\"(COST(k[, x=10.0])\n\n    成本分布\n\n    用法：COST(k, X) 表示X%获利盘的价格是多少\n\n    例如：COST(k, 10),表示10%获利盘的价格是多少，即有10%的持仓量在该价格以下，其余90%在该价格以上，为套牢盘 该函数仅对日线分析周期有效\n\n    :param KData k: 关联的K线数据\n    :param float x: x%获利价格, 0~100\n    :rtype: Indicator)\");\n\n    def(\"ALIGN\", ALIGN_1);\n    def(\"ALIGN\", ALIGN_2);\n    def(\"ALIGN\", ALIGN_3);\n    def(\"ALIGN\", ALIGN_4, R\"(ALIGN(data, ref):\n\n    按指定的参考日期对齐\n\n    :param Indicator data: 输入数据\n    :param ref: 指定做为日期参考的 DatetimeList、Indicator 或 KData\n    :retype: Indicator)\");\n\n    def(\"DROPNA\", DROPNA_1);\n    def(\"DROPNA\", DROPNA_2, R\"(DROPNA([data])\n\n    删除 nan 值\n\n    :param Indicator data: 输入数据\n    :rtype: Indicator)\");\n\n    def(\"ADVANCE\", ADVANCE,\n        (arg(\"query\") = KQueryByIndex(-100), arg(\"market\") = \"SH\", arg(\"stk_type\") = STOCKTYPE_A,\n         arg(\"ignore_context\") = false),\n        R\"(ADVANCE([query=Query(-100), market='SH', stk_type='constant.STOCKTYPE_A'])\n\n    上涨家数。当存在指定上下文且 ignore_context 为 false 时，将忽略 query, market, stk_type 参数。\n\n    :param Query query: 查询条件\n    :param str market: 所属市场，等于 \"\" 时，获取所有市场\n    :param int stk_type: 证券类型, 大于 constant.STOCKTYPE_TMP 时，获取所有类型证券\n    :param bool ignore_context: 是否忽略上下文。忽略时，强制使用 query, market, stk_type 参数。\n    :rtype: Indicator)\");\n\n    def(\"DECLINE\", DECLINE,\n        (arg(\"query\") = KQueryByIndex(-100), arg(\"market\") = \"SH\", arg(\"stk_type\") = STOCKTYPE_A,\n         arg(\"ignore_context\") = false),\n        R\"(DECLINE([query=Query(-100), market='SH', stk_type='constant.STOCKTYPE_A'])\n\n    下跌家数。当存在指定上下文且 ignore_context 为 false 时，将忽略 query, market, stk_type 参数。\n\n    :param Query query: 查询条件\n    :param str market: 所属市场，等于 \"\" 时，获取所有市场\n    :param int stk_type: 证券类型, 大于 constant.STOCKTYPE_TMP 时，获取所有类型证券\n    :param bool ignore_context: 是否忽略上下文。忽略时，强制使用 query, market, stk_type 参数。\n    :rtype: Indicator)\");\n}\n", "meta": {"hexsha": "c002280266085fced8b0cee43b87886c3a0848bc", "size": 40816, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "hikyuu_pywrap/indicator/_build_in.cpp", "max_stars_repo_name": "kknet/hikyuu", "max_stars_repo_head_hexsha": "650814c3e1d32894ccc1263a0fecd6693028d2e3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-03-07T09:23:15.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-07T09:23:15.000Z", "max_issues_repo_path": "hikyuu_pywrap/indicator/_build_in.cpp", "max_issues_repo_name": "kknet/hikyuu", "max_issues_repo_head_hexsha": "650814c3e1d32894ccc1263a0fecd6693028d2e3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "hikyuu_pywrap/indicator/_build_in.cpp", "max_forks_repo_name": "kknet/hikyuu", "max_forks_repo_head_hexsha": "650814c3e1d32894ccc1263a0fecd6693028d2e3", "max_forks_repo_licenses": ["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.7709700948, "max_line_length": 156, "alphanum_fraction": 0.6266415131, "num_tokens": 16086, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6113819591324416, "lm_q2_score": 0.523420348936324, "lm_q1q2_score": 0.32000975838247603}}
{"text": "//  (C) Copyright Nick Thompson 2019.\n//  Use, modification and distribution are subject to the\n//  Boost Software License, Version 1.0. (See accompanying file\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n#ifndef BOOST_MATH_INTERPOLATORS_CARDINAL_TRIGONOMETRIC_HPP\n#define BOOST_MATH_INTERPOLATORS_CARDINAL_TRIGONOMETRIC_HPP\n#include <memory>\n#include <boost/math/interpolators/detail/cardinal_trigonometric_detail.hpp>\n\nnamespace boost { namespace math { namespace interpolators {\n\ntemplate<class RandomAccessContainer>\nclass cardinal_trigonometric\n{\npublic:\n    using Real = typename RandomAccessContainer::value_type;\n    cardinal_trigonometric(RandomAccessContainer const & v, Real t0, Real h)\n    {\n        m_impl = std::make_shared<interpolators::detail::cardinal_trigonometric_detail<Real>>(v.data(), v.size(), t0, h);\n    }\n\n    Real operator()(Real t) const\n    {\n        return m_impl->operator()(t);\n    }\n\n    Real prime(Real t) const\n    {\n        return m_impl->prime(t);\n    }\n\n    Real double_prime(Real t) const\n    {\n        return m_impl->double_prime(t);\n    }\n\n    Real period() const\n    {\n        return m_impl->period();\n    }\n\n    Real integrate() const\n    {\n        return m_impl->integrate();\n    }\n\n    Real squared_l2() const\n    {\n        return m_impl->squared_l2();\n    }\n\nprivate:\n    std::shared_ptr<interpolators::detail::cardinal_trigonometric_detail<Real>> m_impl;\n};\n\n}}}\n#endif\n", "meta": {"hexsha": "28a58c8b286161540d1139f4f8826b1e669f76a9", "size": 1443, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ReactNativeFrontend/ios/Pods/boost/boost/math/interpolators/cardinal_trigonometric.hpp", "max_stars_repo_name": "Harshitha91/Tmdb-react-native-node", "max_stars_repo_head_hexsha": "e06e3f25a7ee6946ef07a1f524fdf62e48424293", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 597.0, "max_stars_repo_stars_event_min_datetime": "2018-07-17T10:59:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T07:59:36.000Z", "max_issues_repo_path": "ReactNativeFrontend/ios/Pods/boost/boost/math/interpolators/cardinal_trigonometric.hpp", "max_issues_repo_name": "Harshitha91/Tmdb-react-native-node", "max_issues_repo_head_hexsha": "e06e3f25a7ee6946ef07a1f524fdf62e48424293", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 626.0, "max_issues_repo_issues_event_min_datetime": "2015-02-05T18:12:27.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-20T13:19:18.000Z", "max_forks_repo_path": "ReactNativeFrontend/ios/Pods/boost/boost/math/interpolators/cardinal_trigonometric.hpp", "max_forks_repo_name": "Harshitha91/Tmdb-react-native-node", "max_forks_repo_head_hexsha": "e06e3f25a7ee6946ef07a1f524fdf62e48424293", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 243.0, "max_forks_repo_forks_event_min_datetime": "2015-01-17T17:46:32.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-07T12:56:26.000Z", "avg_line_length": 24.4576271186, "max_line_length": 121, "alphanum_fraction": 0.693000693, "num_tokens": 362, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6825737214979745, "lm_q2_score": 0.46879062662624377, "lm_q1q2_score": 0.31998416261964263}}
{"text": "#include \"libsnark/gadgetlib1/gadgets/basic_gadgets.hpp\"\r\n#include \"libsnark/zk_proof_systems/ppzksnark/r1cs_ppzksnark/r1cs_ppzksnark.hpp\"\r\n#include \"libsnark/common/default_types/r1cs_ppzksnark_pp.hpp\"\r\n#include \"libsnark/common/utils.hpp\"\r\n#include <boost/optional.hpp>\r\n\r\nusing namespace libsnark;\r\nusing namespace std;\r\n\r\n#include \"gadget_neg.hpp\"\r\n\r\n\r\ntemplate<typename ppzksnark_ppT>\r\nr1cs_ppzksnark_keypair<ppzksnark_ppT> generate_keypair_neg(const int jw[2][32])\r\n{\r\n    typedef Fr<ppzksnark_ppT> FieldT;\r\n\r\n    //根据预先定义的计算门和约束生成公共参数秘钥对\r\n    //证明生成端若需要采用对应的公共秘钥生成证明数据成功，则必须使两端的数据符合预先定于的计算约束(R1+X=R2+R3)\r\n    //如此，当验证端根据对应的验证秘钥验证证明数据为真时，验证者就能够相信对应的交易中是符合预定义的计算约束的，而不是生成假证明以通过检查\r\n    protoboard<FieldT> pb;\r\n    l_gadget_neg<FieldT> g(pb);\r\n    g.generate_r1cs_constraints();\r\n    const r1cs_constraint_system<FieldT> constraint_system = pb.get_constraint_system();\r\n\r\n    cout << \"Number of R1CS constraints: \" << constraint_system.num_constraints() << endl;\r\n\r\n    return r1cs_ppzksnark_generator<ppzksnark_ppT>(constraint_system);\r\n}\r\n\r\ntemplate<typename ppzksnark_ppT>\r\nboost::optional<r1cs_ppzksnark_proof<ppzksnark_ppT>> generate_proof_neg(r1cs_ppzksnark_proving_key<ppzksnark_ppT> proving_key,\r\n                                                                   const std::vector<bit_vector> &hash_input_vec,\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tconst std::vector<bit_vector> &hash_output_vec,\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tconst std::vector<bit_vector> &input_vec,\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tconst std::vector<bit_vector> &output_vec,\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tconst bit_vector &x,\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t   const int jw[2][32]\r\n                                                                   )\r\n{\r\n    typedef Fr<ppzksnark_ppT> FieldT;\r\n\r\n    protoboard<FieldT> pb;\r\n    l_gadget_neg<FieldT> g(pb);\r\n    g.generate_r1cs_constraints();\r\n    g.generate_r1cs_witness(hash_input_vec, hash_output_vec, input_vec, output_vec, x);\r\n\r\n    if (!pb.is_satisfied()) {\r\n      std::cout << \"System not satisfied!\" << std::endl;\r\n        return boost::none;\r\n    }\r\n\r\n    return r1cs_ppzksnark_prover<ppzksnark_ppT>(proving_key, pb.primary_input(), pb.auxiliary_input());\r\n}\r\n\r\ntemplate<typename ppzksnark_ppT>\r\nbool verify_proof(r1cs_ppzksnark_verification_key<ppzksnark_ppT> verification_key,\r\n                  r1cs_ppzksnark_proof<ppzksnark_ppT> proof,\r\n                  const std::vector<bit_vector> &hash_input_vec,\r\n\t\t\t\t  const std::vector<bit_vector> &hash_output_vec,\r\n\t\t\t\t  const bit_vector &x\r\n                 )\r\n{\r\n    typedef Fr<ppzksnark_ppT> FieldT;\r\n\r\n    const r1cs_primary_input<FieldT> input = l_input_map<FieldT>(hash_input_vec, hash_output_vec, x);\r\n\r\n    std::cout << \"**** After l_input_map *****\" << std::endl;\r\n\r\n    return r1cs_ppzksnark_verifier_strong_IC<ppzksnark_ppT>(verification_key, input, proof);\r\n\r\n}\r\n\r\n\r\n", "meta": {"hexsha": "6512aaea52a25dc38f892363c3310d9ca4993a5b", "size": 2793, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/libMultiInput/snark.hpp", "max_stars_repo_name": "dasenlinCode/lightning_circuit", "max_stars_repo_head_hexsha": "e6eb12623e13bfe62489726c732bf563c17c5169", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-06-19T02:54:11.000Z", "max_stars_repo_stars_event_max_datetime": "2019-07-01T05:11:27.000Z", "max_issues_repo_path": "src/libMultiInput/snark.hpp", "max_issues_repo_name": "dasenlinCode/lightning_circuit", "max_issues_repo_head_hexsha": "e6eb12623e13bfe62489726c732bf563c17c5169", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/libMultiInput/snark.hpp", "max_forks_repo_name": "dasenlinCode/lightning_circuit", "max_forks_repo_head_hexsha": "e6eb12623e13bfe62489726c732bf563c17c5169", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2019-06-28T12:11:00.000Z", "max_forks_repo_forks_event_max_datetime": "2019-11-15T08:48:53.000Z", "avg_line_length": 37.24, "max_line_length": 127, "alphanum_fraction": 0.6752595775, "num_tokens": 853, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.7057850402140659, "lm_q2_score": 0.45326184801538616, "lm_q1q2_score": 0.3199054316290411}}
{"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_A61EC088D31511DFA59D2B03E0D72085\n#define UUID_A61EC088D31511DFA59D2B03E0D72085\n\n#include <boost/qvm/vec_mat_operations2.hpp>\n#include <boost/qvm/vec_mat_operations3.hpp>\n#include <boost/qvm/vec_mat_operations4.hpp>\n\nnamespace boost {\nnamespace qvm {\n////////////////////////////////////////////////\n\nnamespace qvm_detail {\ntemplate <int M, int N> struct mul_mv_defined {\n  static bool const value = false;\n};\n} // namespace qvm_detail\n\ntemplate <class A, class B>\nBOOST_QVM_INLINE_OPERATIONS typename lazy_enable_if_c<\n    is_mat<A>::value && is_vec<B>::value &&\n        mat_traits<A>::cols == vec_traits<B>::dim &&\n        !qvm_detail::mul_mv_defined<mat_traits<A>::rows,\n                                    mat_traits<A>::cols>::value,\n    deduce_vec2<A, B, mat_traits<A>::rows>>::type\noperator*(A const &a, B const &b) {\n  typedef typename deduce_vec2<A, B, mat_traits<A>::rows>::type R;\n  R r;\n  for (int i = 0; i < mat_traits<A>::rows; ++i) {\n    typedef typename vec_traits<R>::scalar_type Tr;\n    Tr x(scalar_traits<Tr>::value(0));\n    for (int j = 0; j < mat_traits<A>::cols; ++j)\n      x += mat_traits<A>::read_element_idx(i, j, a) *\n           vec_traits<B>::read_element_idx(j, b);\n    vec_traits<R>::write_element_idx(i, r) = x;\n  }\n  return r;\n}\n\nnamespace qvm_detail {\ntemplate <int M, int N> struct mul_vm_defined {\n  static bool const value = false;\n};\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_mat<B>::value &&\n        vec_traits<A>::dim == mat_traits<B>::rows &&\n        !qvm_detail::mul_vm_defined<mat_traits<B>::rows,\n                                    mat_traits<B>::cols>::value,\n    deduce_vec2<A, B, mat_traits<B>::cols>>::type\noperator*(A const &a, B const &b) {\n  typedef typename deduce_vec2<A, B, mat_traits<B>::cols>::type R;\n  R r;\n  for (int i = 0; i < mat_traits<B>::cols; ++i) {\n    typedef typename vec_traits<R>::scalar_type Tr;\n    Tr x(scalar_traits<Tr>::value(0));\n    for (int j = 0; j < mat_traits<B>::rows; ++j)\n      x += vec_traits<A>::read_element_idx(j, a) *\n           mat_traits<B>::read_element_idx(j, i, b);\n    vec_traits<R>::write_element_idx(i, r) = x;\n  }\n  return r;\n}\n\n////////////////////////////////////////////////\n\ntemplate <class A, class B>\nBOOST_QVM_INLINE_OPERATIONS\n    typename lazy_enable_if_c<mat_traits<A>::rows == 4 &&\n                                  mat_traits<A>::cols == 4 &&\n                                  vec_traits<B>::dim == 3,\n                              deduce_vec2<A, B, 3>>::type\n    transform_point(A const &a, B const &b) {\n  typedef typename mat_traits<A>::scalar_type Ta;\n  typedef typename vec_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 a02 = mat_traits<A>::template read_element<0, 2>(a);\n  Ta const a03 = mat_traits<A>::template read_element<0, 3>(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  Ta const a12 = mat_traits<A>::template read_element<1, 2>(a);\n  Ta const a13 = mat_traits<A>::template read_element<1, 3>(a);\n  Ta const a20 = mat_traits<A>::template read_element<2, 0>(a);\n  Ta const a21 = mat_traits<A>::template read_element<2, 1>(a);\n  Ta const a22 = mat_traits<A>::template read_element<2, 2>(a);\n  Ta const a23 = mat_traits<A>::template read_element<2, 3>(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  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      a00 * b0 + a01 * b1 + a02 * b2 + a03;\n  vec_traits<R>::template write_element<1>(r) =\n      a10 * b0 + a11 * b1 + a12 * b2 + a13;\n  vec_traits<R>::template write_element<2>(r) =\n      a20 * b0 + a21 * b1 + a22 * b2 + a23;\n  return r;\n}\n\ntemplate <class A, class B>\nBOOST_QVM_INLINE_OPERATIONS\n    typename lazy_enable_if_c<mat_traits<A>::rows == 4 &&\n                                  mat_traits<A>::cols == 4 &&\n                                  vec_traits<B>::dim == 3,\n                              deduce_vec2<A, B, 3>>::type\n    transform_vector(A const &a, B const &b) {\n  typedef typename mat_traits<A>::scalar_type Ta;\n  typedef typename vec_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 a02 = mat_traits<A>::template read_element<0, 2>(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  Ta const a12 = mat_traits<A>::template read_element<1, 2>(a);\n  Ta const a20 = mat_traits<A>::template read_element<2, 0>(a);\n  Ta const a21 = mat_traits<A>::template read_element<2, 1>(a);\n  Ta const a22 = mat_traits<A>::template read_element<2, 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  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) = a00 * b0 + a01 * b1 + a02 * b2;\n  vec_traits<R>::template write_element<1>(r) = a10 * b0 + a11 * b1 + a12 * b2;\n  vec_traits<R>::template write_element<2>(r) = a20 * b0 + a21 * b1 + a22 * b2;\n  return r;\n}\n\n////////////////////////////////////////////////\n\nnamespace sfinae {\nusing ::boost::qvm::operator*;\nusing ::boost::qvm::transform_point;\nusing ::boost::qvm::transform_vector;\n} // namespace sfinae\n\n////////////////////////////////////////////////\n} // namespace qvm\n} // namespace boost\n\n#endif\n", "meta": {"hexsha": "3243d9da24f237e989ddfba6ee1ce865ccad980e", "size": 6147, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "libs/boost_1_72_0/boost/qvm/vec_mat_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_mat_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_mat_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": 40.4407894737, "max_line_length": 79, "alphanum_fraction": 0.6269725069, "num_tokens": 1801, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7057850278370112, "lm_q2_score": 0.45326184801538616, "lm_q1q2_score": 0.31990542601899447}}
{"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#include <boost/geometry.hpp>\n#include <boost/geometry/geometries/point_xy.hpp>\n#include <boost/geometry/geometries/polygon.hpp>\n\n#if BOOST_VERSION < 105600\n#  include <boost/geometry/multi/geometries/multi_polygon.hpp>\n#else\n#  include <boost/geometry/geometries/multi_polygon.hpp>\n#endif\n\n#include \"dbglog/dbglog.hpp\"\n\n#include \"nonconvexclip.hpp\"\n#include \"triangulate.hpp\"\n\nnamespace bg = boost::geometry;\n\nnamespace geometry {\n\ntypedef bg::model::d2::point_xy<double> Point;\ntypedef bg::model::polygon<Point, false, false> Polygon; // ccw, unclosed\ntypedef bg::model::multi_polygon<Polygon> MultiPolygon;\ntypedef Polygon::ring_type Ring;\n\nnamespace {\n\ntemplate<typename List>\nstd::vector<Point> bgPoints(const List &list)\n{\n    std::vector<Point> result;\n    result.reserve(list.size() + 1);\n    for (const auto &p : list) {\n        result.emplace_back(p(0), p(1));\n    }\n    return result;\n}\n\ninline math::Points2d ringPoints(const Ring &ring)\n{\n    math::Points2d result;\n    result.reserve(ring.size());\n    for (const auto &p : ring) {\n        result.emplace_back(p.x(), p.y());\n    }\n    return result;\n}\n\ninline double checkCcw(const math::Point2 &a, const math::Point2 &b\n                       , const math::Point2 &c)\n{\n    return math::crossProduct(math::Point2(math::normalize(b - a))\n                              , math::Point2(math::normalize(c - a)));\n}\n\ninline double area(const math::Triangle2d &t) {\n    return 0.5 * std::abs(math::crossProduct( math::Point2(t[1] - t[0])\n                                            , math::Point2(t[2] - t[0])));\n}\n\n} // namespace\n\nmath::Triangles3d clipTriangleNonconvex(const math::Triangle3d &tri_,\n                                        const math::MultiPolygon &clipRegion)\n{\n    math::Triangle3d tri(tri_);\n\n    // tri -> tri2\n    math::Triangle2d tri2;\n    for (int i = 0; i < 3; i++) {\n        tri2[i](0) = tri[i](0);\n        tri2[i](1) = tri[i](1);\n    }\n\n    bool flip = false;\n    double ccw(checkCcw(tri2[0], tri2[1], tri2[2]));\n\n    // convert clipRegion to boost MultiPolygon\n    MultiPolygon clipMultiPoly;\n    for (const auto &pts : clipRegion) {\n        Polygon part;\n        bg::assign_points(part, bgPoints(pts));\n        clipMultiPoly.push_back(part);\n    }\n\n    if (std::abs(ccw) < 1e-4)\n    {\n        // TODO: handle exactly vertical triangles properly\n        if (bg::within(Point{tri[0](0), tri[0](1)}, clipMultiPoly) &&\n            bg::within(Point{tri[1](0), tri[1](1)}, clipMultiPoly) &&\n            bg::within(Point{tri[2](0), tri[2](1)}, clipMultiPoly))\n        {\n            LOG(debug)\n                << \"Including near vertical triangle, all vertices lie inside.\";\n            return {tri};\n        } else {\n            LOG(debug) << \"Excluding near vertical triangle, \"\n                          \"not all vertices lie inside.\";\n            return {};\n        }\n    }\n\n    // ensure counter-clockwise orientation for clipping\n    if (ccw < 0.0) {\n        std::swap(tri[1], tri[2]);\n        std::swap(tri2[1], tri2[2]);\n        flip = true;\n    }\n\n    // convert input to 2D polygons\n    Polygon trianglePoly;\n    bg::assign_points(trianglePoly, bgPoints(tri));\n\n    // calculate intersection\n    std::deque<Polygon> isect;\n    bg::intersection(trianglePoly, clipMultiPoly, isect);\n\n    // triangulate\n    math::MultiPolygon isect2;\n    isect2.reserve(isect.size());\n    for (const auto &poly : isect) {\n        isect2.push_back(ringPoints(poly.outer()));\n        for (const auto &ring : poly.inners()) {\n            isect2.push_back(ringPoints(ring));\n        }\n    }\n\n    math::Triangles2d tris2(generalPolyTriangulate(isect2));\n\n    // work around boost errorneously returning whole polygon as intersection\n    // check area of input triangle against area of the result, should be same\n    // or less. Definitelly it should not be significantly bigger.\n    double interArea(0.0);\n    for (const auto &t2 : tris2) {\n        interArea += area(t2);\n    }\n    if (interArea > (area(tri2) * 1.1) ) { // 1.1 for numerical stability\n        LOG(warn1) << \"Throwing away spurious intersection (ratio of areas: \"\n                   << interArea / area(tri2) << \").\";\n        return {};\n    }\n\n\n    // restore Z coords\n    math::Triangles3d tris3;\n    tris3.reserve(tris2.size());\n    for (const auto &t2 : tris2)\n    {\n        math::Triangle3d t3;\n        for (int i = 0; i < 3; i++)\n        {\n            math::Point3 l(math::barycentricCoords(t2[i], tri2));\n            t3[i](0) = t2[i](0);\n            t3[i](1) = t2[i](1);\n            t3[i](2) = l(0)*tri[0](2) +\n                       l(1)*tri[1](2) +\n                       l(2)*tri[2](2);\n        }\n        if (flip) {\n            std::swap(t3[1], t3[2]);\n        }\n        tris3.push_back(t3);\n    }\n\n    return tris3;\n}\n\n\nmath::Point3 barycentric3D(const math::Point3 &p, const math::Point3 &a,\n                           const math::Point3 &b, const math::Point3 &c)\n{\n    typedef math::Point3 P3;\n    double abp = norm_2(math::crossProduct(P3(b - a), P3(p - a)));\n    double bcp = norm_2(math::crossProduct(P3(c - b), P3(p - b)));\n    double cap = norm_2(math::crossProduct(P3(a - c), P3(p - c)));\n    double nor = 1.0 / (abp + bcp + cap);\n    return {bcp*nor, cap*nor, abp*nor};\n}\n\n\nstd::tuple<math::Triangles3d, math::Triangles2d>\n    clipTexturedTriangleNonconvex(const math::Triangle3d &tri,\n                                  const math::Triangle2d &uv,\n                                  const math::MultiPolygon &clipRegion)\n{\n    std::tuple<math::Triangles3d, math::Triangles2d> result;\n    auto &tris3(std::get<0>(result));\n    auto &uvs(std::get<1>(result));\n\n    // clip the geometry first\n    tris3 = clipTriangleNonconvex(tri, clipRegion);\n\n    // if one same triangle -> copy texcoorsds\n    // this clearly solves degen cases.\n    if ((tris3.size() == 1) && (tris3[0] == tri)) {\n        uvs.push_back(uv);\n        return result;\n    }\n\n    // interpolate UV coords\n    uvs.reserve(tris3.size());\n    for (const auto &t3 : tris3)\n    {\n        math::Triangle2d t2;\n        for (int i = 0; i < 3; i++)\n        {\n            math::Point3 l(barycentric3D(t3[i], tri[0], tri[1], tri[2]));\n            for (int j = 0; j < 2; j++) {\n                t2[i](j) = l(0)*uv[0](j) + l(1)*uv[1](j) + l(2)*uv[2](j);\n            }\n        }\n        uvs.push_back(t2);\n    }\n\n    return result;\n}\n\n} // namespace geometry\n", "meta": {"hexsha": "a806276bc8277e92ebf09a345ec669582b4730bc", "size": 7722, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "geometry/nonconvexclip.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/nonconvexclip.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/nonconvexclip.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": 31.6475409836, "max_line_length": 80, "alphanum_fraction": 0.6004921005, "num_tokens": 2090, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7057850278370112, "lm_q2_score": 0.45326184801538616, "lm_q1q2_score": 0.31990542601899447}}
{"text": "#ifndef RECONST3D_CREATE_OPTIMIZER\n#define RECONST3D_CREATE_OPTIMIZER\n\n#include <Eigen/Geometry>\n\n#include <g2o/core/block_solver.h>\n#include <g2o/core/sparse_optimizer.h>\n#include <g2o/core/solver.h>\n#include <g2o/solvers/cholmod/linear_solver_cholmod.h>\n#include <g2o/solvers/csparse/linear_solver_csparse.h>\n#include <g2o/core/optimization_algorithm_levenberg.h>\n#include <g2o/core/optimization_algorithm_gauss_newton.h>\n#include <g2o/core/robust_kernel_impl.h>\n\n#include <opencv2/core/core.hpp>\n#include <opencv2/rgbd/rgbd.hpp>\n#include <opencv2/core/eigen.hpp>\n#include <opencv2/calib3d/calib3d.hpp>\n\n#include <opencv_candidate_reconst3d/reconst3d.hpp>\n\ntypedef g2o::BlockSolver< g2o::BlockSolverTraits<6, 3> >  G2OBlockSolver;\ntypedef g2o::LinearSolver< G2OBlockSolver::PoseMatrixType> G2OLinearSolver;\ntypedef g2o::LinearSolverCholmod<G2OBlockSolver::PoseMatrixType> G2OLinearCholmodSolver;\ntypedef g2o::LinearSolverCSparse<G2OBlockSolver::PoseMatrixType> G2OLinearCSparseSolver;\n\nconst std::string DEFAULT_LINEAR_SOLVER_TYPE = \"cholmod\"; //\"csparse\";\nconst std::string DEFAULT_NON_LINEAR_SOLVER_TYPE  = \"GN\";\n\n// get norms\n//\nstatic inline\nfloat tvecNorm(const cv::Mat& Rt)\n{\n    return cv::norm(Rt(cv::Rect(3,0,1,3)));\n}\n\nstatic inline\nfloat rvecNormDegrees(const cv::Mat& Rt)\n{\n    cv::Mat rvec;\n    cv::Rodrigues(Rt(cv::Rect(0,0,3,3)), rvec);\n    return cv::norm(rvec) * 180. / CV_PI;\n}\n\n// convertions\n//\ninline\nEigen::Vector3d cvtPoint_ocv2egn(const cv::Point3f& ocv_p)\n{\n    Eigen::Vector3d egn_p;\n    egn_p[0] = ocv_p.x;\n    egn_p[1] = ocv_p.y;\n    egn_p[2] = ocv_p.z;\n\n    return egn_p;\n}\n\ninline\ncv::Mat cvtIsometry_egn2ocv(const Eigen::Isometry3d& egn_o)\n{\n    Eigen::Matrix3d eigenRotation = egn_o.rotation();\n    Eigen::Matrix<double,3,1> eigenTranslation = egn_o.translation();\n\n    cv::Mat R, t;\n    eigen2cv(eigenRotation, R);\n    eigen2cv(eigenTranslation, t);\n    t = t.reshape(1,3);\n\n    cv::Mat ocv_o = cv::Mat::eye(4,4,CV_64FC1);\n    R.copyTo(ocv_o(cv::Rect(0,0,3,3)));\n    t.copyTo(ocv_o(cv::Rect(3,0,1,3)));\n\n    return ocv_o;\n}\n\n// corresps\ninline\nvoid set2shorts(int& dst, int short_v1, int short_v2)\n{\n    unsigned short* ptr = reinterpret_cast<unsigned short*>(&dst);\n    ptr[0] = static_cast<unsigned short>(short_v1);\n    ptr[1] = static_cast<unsigned short>(short_v2);\n}\n\ninline\nvoid get2shorts(int src, int& short_v1, int& short_v2)\n{\n    typedef union { int vint32; unsigned short vuint16[2]; } s32tou16;\n    const unsigned short* ptr = (reinterpret_cast<s32tou16*>(&src))->vuint16;\n    short_v1 = ptr[0];\n    short_v2 = ptr[1];\n}\n\nint computeCorrespsFiltered(const cv::Mat& K, const cv::Mat& K_inv, const cv::Mat& Rt,\n                            const cv::Mat& depth0, const cv::Mat& validMask0,\n                            const cv::Mat& depth1, const cv::Mat& selectMask1, float maxDepthDiff,\n                            cv::Mat& corresps,\n                            const cv::Mat& normals0, const cv::Mat& normals1,\n                            const cv::Mat& image0, const cv::Mat& image1,\n                            float maxColorDiff = FLT_MAX);\n\nvoid selectPosesSubset(const std::vector<cv::Mat>& poses,\n                       const std::vector<int>& indices,\n                       std::vector<int>& selectedIndices, size_t count);\n\n// create solver\n//\ninline\nG2OLinearSolver* createLinearSolver(const std::string& type)\n{\n    G2OLinearSolver* solver = 0;\n    if(type == \"cholmod\")\n        solver = new G2OLinearCholmodSolver();\n    else if(type == \"csparse\")\n    {\n        solver = new G2OLinearCSparseSolver();\n    }\n    else\n    {\n        CV_Assert(0);\n    }\n\n    return solver;\n}\n\ninline\nG2OBlockSolver* createBlockSolver(G2OLinearSolver* linearSolver)\n{\n    return new G2OBlockSolver(linearSolver);\n}\n\ninline\ng2o::OptimizationAlgorithm* createNonLinearSolver(const std::string& type, G2OBlockSolver* blockSolver)\n{\n    g2o::OptimizationAlgorithm* solver = 0;\n    if(type == \"GN\")\n        solver = new g2o::OptimizationAlgorithmGaussNewton(blockSolver);\n    else if(type == \"LM\")\n        solver = new g2o::OptimizationAlgorithmLevenberg(blockSolver);\n    else\n        CV_Assert(0);\n\n    return solver;\n}\n\ninline\ng2o::SparseOptimizer* createOptimizer(g2o::OptimizationAlgorithm* solver)\n{\n    g2o::SparseOptimizer* optimizer = new g2o::SparseOptimizer();\n    optimizer->setAlgorithm(solver);\n    optimizer->setVerbose(true);\n    return optimizer;\n}\n\n// graph opt\n\n// Restore refined camera poses from the graph.\nvoid getSE3Poses(g2o::SparseOptimizer* optimizer, const std::vector<int>& frameIndices, std::vector<cv::Mat>& poses);\n\n// Fill the given graph by vertices and edges for the camera pose refinement geometrically.\n// Each vertex is a camera pose. Each edge constraint is the odometry between linked vertices.\nvoid fillGraphSE3(g2o::SparseOptimizer* optimizer,\n                  const std::vector<cv::Mat>& poses, const std::vector<PosesLink>& posesLinks,\n                  std::vector<int>& frameIndices);\n\n// Refine camera poses geometrically\nvoid refineGraphSE3(const std::vector<cv::Mat>& poses, const std::vector<PosesLink>& posesLinks,\n                    std::vector<cv::Mat>& refinedPoses, std::vector<int>& frameIndices);\n\nvoid refineGraphSE3Segment(const std::vector<cv::Mat>& odometryPoses,\n                           const std::vector<cv::Mat>& partiallyRefinedPoses,\n                           const std::vector<int>& refinedFrameIndices,\n                           std::vector<cv::Mat>& refinedAllPoses);\n\n\n\n// Graph with 2 types of edges: odometry and Rgbd+ICP for correspondences.\n// TODO we need next iteration of the code refactoring\nvoid fillGraphSE3RgbdICP(g2o::SparseOptimizer* optimizer, int pyramidLevel,\n                         const std::vector<cv::Ptr<cv::OdometryFrame> >& frames,\n                         const std::vector<cv::Mat>& poses, const std::vector<PosesLink>& posesLinks, const cv::Mat& cameraMatrix,\n                         std::vector<int>& frameIndices, \n                         double maxTranslation, double maxRotation, double maxDepthDiff);\n\n// Refine camera poses by graph with odometry edges and Rgbd+ICP edges\nvoid refineGraphSE3RgbdICP(const std::vector<cv::Ptr<cv::RgbdFrame> >& frames,\n                           const std::vector<cv::Mat>& poses, const std::vector<PosesLink>& posesLinks, const cv::Mat& cameraMatrix,\n                           float pointsPart, std::vector<cv::Mat>& refinedPoses, std::vector<int>& frameIndices);\n\n\nvoid refineGraphSE3RgbdICPModel(std::vector<cv::Ptr<cv::RgbdFrame> >& frames,\n                                const std::vector<cv::Mat>& poses, const std::vector<PosesLink>& posesLinks, const cv::Mat& cameraMatrix,\n                                std::vector<cv::Mat>& refinedPoses, std::vector<int>& frameIndices);\n\n#endif\n", "meta": {"hexsha": "de6c38b9e54033a07eb2bbc863bec039186cfb8c", "size": 6773, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Chapter08/chapter8_tutorials/opencv_candidate/src/reconst3d/graph_optimizations.hpp", "max_stars_repo_name": "PacktPublishing/Robot-Operating-System-Cookbook", "max_stars_repo_head_hexsha": "d94ef672a483782922ca8b134f6de749af8e0a10", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 53.0, "max_stars_repo_stars_event_min_datetime": "2018-09-13T05:11:03.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-28T04:09:58.000Z", "max_issues_repo_path": "Chapter08/chapter8_tutorials/opencv_candidate/src/reconst3d/graph_optimizations.hpp", "max_issues_repo_name": "PacktPublishing/Robot-Operating-System-Cookbook", "max_issues_repo_head_hexsha": "d94ef672a483782922ca8b134f6de749af8e0a10", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2018-09-30T08:32:22.000Z", "max_issues_repo_issues_event_max_datetime": "2019-04-12T13:37:43.000Z", "max_forks_repo_path": "Chapter08/chapter8_tutorials/opencv_candidate/src/reconst3d/graph_optimizations.hpp", "max_forks_repo_name": "PacktPublishing/Robot-Operating-System-Cookbook", "max_forks_repo_head_hexsha": "d94ef672a483782922ca8b134f6de749af8e0a10", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 31.0, "max_forks_repo_forks_event_min_datetime": "2018-09-16T06:05:13.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-10T18:10:37.000Z", "avg_line_length": 34.3807106599, "max_line_length": 137, "alphanum_fraction": 0.6711944485, "num_tokens": 1866, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7057850278370112, "lm_q2_score": 0.4532618480153861, "lm_q1q2_score": 0.31990542601899447}}
{"text": "//==============================================================================\n//         Copyright 2003 - 2012   LASMEA UMR 6602 CNRS/Univ. Clermont II\n//         Copyright 2009 - 2013   LRI    UMR 8623 CNRS/Univ Paris Sud XI\n//\n//          Distributed under the Boost Software License, Version 1.0.\n//                 See accompanying file LICENSE.txt or copy at\n//                     http://www.boost.org/LICENSE_1_0.txt\n//==============================================================================\n#ifndef NT2_LINALG_FUNCTIONS_TIED_NSEIG_HPP_INCLUDED\n#define NT2_LINALG_FUNCTIONS_TIED_NSEIG_HPP_INCLUDED\n\n#include <nt2/linalg/functions/nseig.hpp>\n#include <boost/dispatch/attributes.hpp>\n#include <nt2/core/container/table/table.hpp>\n#include <nt2/include/functions/balance.hpp>\n#include <nt2/include/functions/from_diag.hpp>\n#include <nt2/include/functions/gebak.hpp>\n#include <nt2/include/functions/gebal.hpp>\n#include <nt2/include/functions/geev_w.hpp>\n#include <nt2/include/functions/geev_wvr.hpp>\n#include <nt2/include/functions/geev_wvrvl.hpp>\n#include <nt2/include/functions/height.hpp>\n#include <nt2/include/functions/of_size.hpp>\n#include <nt2/include/functions/resize.hpp>\n#include <nt2/include/functions/tie.hpp>\n#include <nt2/linalg/details/utility/lapack_verify.hpp>\n#include <nt2/sdk/meta/as_real.hpp>\n#include <nt2/linalg/options.hpp>\n#include <nt2/core/container/dsl/as_terminal.hpp>\n\nnamespace nt2 { namespace ext\n{\n  BOOST_DISPATCH_IMPLEMENT  ( nseig_, tag::cpu_\n                            , (A0)\n                            , (scalar_<unspecified_<A0> >)\n                            )\n  {\n    typedef A0 result_type;\n\n    BOOST_FORCEINLINE result_type operator()(const A0& a0) const\n    {\n      return a0;\n    }\n  };\n\n  BOOST_DISPATCH_IMPLEMENT  ( nseig_, 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  BOOST_DISPATCH_IMPLEMENT  ( nseig_, tag::cpu_\n                            , (A0)(A1)(A2)\n                            , (scalar_<unspecified_<A0> >)\n                              (unspecified_<A1>)\n                              (unspecified_<A2>)\n                            )\n  {\n    typedef A0 result_type;\n\n    BOOST_FORCEINLINE result_type operator()(const A0& a0, const A1&, const A2&) const\n    {\n      return a0;\n    }\n  };\n\n  //============================================================================\n  //Eig computations\n  //============================================================================\n  BOOST_DISPATCH_IMPLEMENT  ( nseig_, tag::cpu_\n                            , (A0)(N0)(A1)(N1)\n                            , ((node_<A0, nt2::tag::nseig_\n                                    , N0, nt2::container::domain\n                                      >\n                              ))\n                              ((node_<A1, nt2::tag::tie_\n                                    , N1, nt2::container::domain\n                                     >\n                              ))\n                            )\n  {\n    typedef void  result_type;\n    typedef typename boost::proto::result_of::child_c<A0&,0>::value_type    child0;\n    typedef typename child0::value_type                                     type_t;\n    typedef typename nt2::meta::as_real<type_t>::type                      rtype_t;\n    typedef typename nt2::meta::as_complex<rtype_t>::type                  ctype_t;\n    typedef nt2::memory::container<tag::table_, ctype_t, nt2::_2D> desired_semantic;\n\n    BOOST_FORCEINLINE result_type operator()( A0& a0, A1& a1 ) const\n    {\n      eval(a0, a1, N0(), N1());\n    }\n\n    //==========================================================================\n    /// INTERNAL ONLY - W = NSEIG(A)\n    BOOST_FORCEINLINE\n    void eval ( A0& a0, A1& a1\n              , boost::mpl::long_<1> const&\n              , boost::mpl::long_<1> const&\n              ) const\n    {\n      eval1_2(a0, a1, nt2::policy<ext::vector_>());\n    }\n\n    /// INTERNAL ONLY - W = NSEIG(A, matrix_/vector_)\n    BOOST_FORCEINLINE\n    void eval ( A0& a0, A1& a1\n              , boost::mpl::long_<2> const&\n              , boost::mpl::long_<1> const&\n              ) const\n    {\n      eval1_2(a0, a1, boost::proto::value(boost::proto::child_c<1>(a0)));\n    }\n\n    /// INTERNAL ONLY: 1o 2i\n    BOOST_FORCEINLINE\n    void eval1_2 ( A0& a0, A1& a1\n                 , nt2::policy<ext::vector_> const &\n                 ) const\n    {\n      nt2::container::table<type_t> work;\n      NT2_AS_TERMINAL_INOUT(desired_semantic, a, boost::proto::child_c<0>(a0), work);\n      NT2_AS_TERMINAL_OUT  (desired_semantic, w, boost::proto::child_c<0>(a1));\n      w.resize(of_size(height(a), 1));\n      NT2_LAPACK_VERIFY(nt2::geev_w( boost::proto::value(a)\n                                   , boost::proto::value(w)));\n      boost::proto::child_c<0>(a1) = w;\n    }\n\n    /// INTERNAL ONLY: 1o 2i\n    BOOST_FORCEINLINE\n    void eval1_2 ( A0& a0, A1& a1\n                 , nt2::policy<ext::matrix_> const &\n                 ) const\n    {\n      nt2::container::table<type_t> work;\n      NT2_AS_TERMINAL_INOUT(desired_semantic, a, boost::proto::child_c<0>(a0), work);\n      nt2::container::table <ctype_t, _2D > w(of_size(height(a), 1));\n      NT2_LAPACK_VERIFY(nt2::geev_w( boost::proto::value(a)\n                                  , boost::proto::value(w)\n                                  ));\n      boost::proto::child_c<0>(a1) = from_diag(w); //from_diag doesnt support aliasing currently\n    }\n\n    //==========================================================================\n    /// INTERNAL ONLY - [VR, W]= NSEIG(A)\n    BOOST_FORCEINLINE\n    void eval ( A0& a0, A1& a1\n              , boost::mpl::long_<1> const&\n              , boost::mpl::long_<2> const&\n              ) const\n    {\n      eval2_2(a0, a1,nt2::policy<ext::matrix_>());\n    }\n\n\n    //==========================================================================\n    /// INTERNAL ONLY - [VR, W]= NSEIG(A,  matrix_/vector_/balance_/no_balance_)\n    BOOST_FORCEINLINE\n    void eval ( A0& a0, A1& a1\n              , boost::mpl::long_<2> const&\n              , boost::mpl::long_<2> const&\n              ) const\n    {\n      eval2_2(a0, a1, boost::proto::value(boost::proto::child_c<1>(a0)));\n    }\n\n   /// INTERNAL ONLY: 2o 2i\n    BOOST_FORCEINLINE\n    void eval2_2 ( A0& a0, A1& a1\n                 , nt2::policy<ext::vector_> const &\n                 ) const\n    {\n      nt2::container::table<type_t> work;\n      NT2_AS_TERMINAL_INOUT(desired_semantic,  a, boost::proto::child_c<0>(a0), work);\n      NT2_AS_TERMINAL_OUT  (desired_semantic, vr, boost::proto::child_c<0>(a1));\n      NT2_AS_TERMINAL_OUT  (desired_semantic,  w, boost::proto::child_c<1>(a1));\n      size_t n = height(a);\n      w.resize(of_size(n, 1));\n      vr.resize(of_size(n, n));\n      NT2_LAPACK_VERIFY(nt2::geev_wvr( boost::proto::value(a)\n                                     , boost::proto::value(w)\n                                     , boost::proto::value(vr)\n                                     ));\n      boost::proto::child_c<1>(a1) = w;\n      boost::proto::child_c<0>(a1) = vr;\n    }\n\n    /// INTERNAL ONLY: 2o 2i\n    BOOST_FORCEINLINE\n    void eval2_2 ( A0& a0, A1& a1\n                 , nt2::policy<ext::matrix_> const &\n                 ) const\n    {\n      nt2::container::table<type_t> work;\n      NT2_AS_TERMINAL_INOUT(desired_semantic,  a, boost::proto::child_c<0>(a0), work);\n      NT2_AS_TERMINAL_OUT  (desired_semantic, vr, boost::proto::child_c<0>(a1));\n      size_t n = height(a);\n      nt2::container::table<ctype_t> w(of_size(n, 1));\n      vr.resize(of_size(n, n));\n      NT2_LAPACK_VERIFY(nt2::geev_wvr( boost::proto::value(a)\n                                     , boost::proto::value(w)\n                                     , boost::proto::value(vr)\n                                     ));\n      boost::proto::child_c<1>(a1) = from_diag(w);\n      boost::proto::child_c<0>(a1) = vr;\n    }\n\n    /// INTERNAL ONLY: 2o 2i\n    BOOST_FORCEINLINE\n    void eval2_2 ( A0& a0, A1& a1\n                 , nt2::policy<ext::balance_> const &\n                 ) const\n    {\n      eval2_3(a0, a1\n             , nt2::policy<ext::matrix_>()\n             , nt2::policy<ext::balance_>());\n    }\n\n    /// INTERNAL ONLY: 2o 2i\n    BOOST_FORCEINLINE\n    void eval2_2 ( A0& a0, A1& a1\n                 , nt2::policy<ext::no_balance_> const &\n                 ) const\n    {\n      eval2_3(a0, a1\n             , nt2::policy<ext::matrix_>()\n             , nt2::policy<ext::no_balance_>());\n    }\n\n    //==========================================================================\n    /// INTERNAL ONLY - [VR, W, VL]= NSEIG(A)\n    BOOST_FORCEINLINE\n    void eval ( A0& a0, A1& a1\n              , boost::mpl::long_<1> const&\n              , boost::mpl::long_<3> const&\n              ) const\n    {\n      eval3_3( a0, a1\n             , nt2::policy<ext::matrix_>()\n             , nt2::policy<ext::no_balance_>());\n    }\n\n    //==========================================================================\n    /// INTERNAL ONLY - [VR, W, VL]= NSEIG(A, vector_/matrix_/balance_/no_balance_)\n    BOOST_FORCEINLINE\n    void eval ( A0& a0, A1& a1\n              , boost::mpl::long_<2> const&\n              , boost::mpl::long_<3> const&\n              ) const\n    {\n      eval3_2(a0, a1, boost::proto::value(boost::proto::child_c<1>(a0)));\n    }\n\n    /// INTERNAL ONLY: 3o 2i\n    BOOST_FORCEINLINE\n    void eval3_2 ( A0& a0, A1& a1\n                 , nt2::policy<ext::matrix_> const &\n                 ) const\n    {\n      nt2::container::table<type_t> work;\n      NT2_AS_TERMINAL_INOUT(desired_semantic,  a, boost::proto::child_c<0>(a0), work);\n      NT2_AS_TERMINAL_OUT  (desired_semantic, vr, boost::proto::child_c<0>(a1));\n      NT2_AS_TERMINAL_OUT  (desired_semantic, vl, boost::proto::child_c<2>(a1));\n      size_t n = height(a);\n      nt2::container::table<ctype_t> w(of_size(n, 1));\n      vr.resize(of_size(n, n));\n      vl.resize(of_size(n, n));\n      NT2_LAPACK_VERIFY(nt2::geev_wvrvl( boost::proto::value(a)\n                                       , boost::proto::value(w)\n                                       , boost::proto::value(vr)\n                                       , boost::proto::value(vl)\n                                       ));\n      boost::proto::child_c<1>(a1) = from_diag(w);\n      boost::proto::child_c<0>(a1) = vr;\n      boost::proto::child_c<2>(a1) = vl;\n    }\n\n    /// INTERNAL ONLY: 3o 2i\n    BOOST_FORCEINLINE\n    void eval3_2 ( A0& a0, A1& a1\n                 , nt2::policy<ext::vector_> const &\n                 ) const\n    {\n      nt2::container::table<type_t> work;\n      NT2_AS_TERMINAL_INOUT(desired_semantic,  a, boost::proto::child_c<0>(a0), work);\n      NT2_AS_TERMINAL_OUT  (desired_semantic, vr, boost::proto::child_c<0>(a1));\n      NT2_AS_TERMINAL_OUT  (desired_semantic,  w, boost::proto::child_c<1>(a1));\n      NT2_AS_TERMINAL_OUT  (desired_semantic, vl, boost::proto::child_c<2>(a1));\n      size_t n = height(a);\n      vr.resize(of_size(n, n));\n      vl.resize(of_size(n, n));\n      w.resize(of_size(n, 1));\n      NT2_LAPACK_VERIFY(nt2::geev_wvrvl( boost::proto::value(a)\n                                       , boost::proto::value(w)\n                                       , boost::proto::value(vr)\n                                       , boost::proto::value(vl)\n                                       ));\n      boost::proto::child_c<1>(a1) = w;\n      boost::proto::child_c<0>(a1) = vr;\n      boost::proto::child_c<2>(a1) = vl;\n    }\n\n    /// INTERNAL ONLY: 3o 2i\n    template < class T> BOOST_FORCEINLINE\n    void eval3_2 ( A0& a0, A1& a1\n                 , nt2::policy<ext::no_balance_> const &\n                 ) const\n    {\n      eval3_3(a0, a1\n             , nt2::policy<ext::matrix_>()\n             , nt2::policy<ext::no_balance_>());\n    }\n\n    /// INTERNAL ONLY: 3o 2i\n    template < class T> BOOST_FORCEINLINE\n    void eval3_2 ( A0& a0, A1& a1\n                 ,  nt2::policy<ext::balance_> const &\n                 ) const\n    {\n      eval3_3(a0, a1, nt2::policy<ext::matrix_>(), nt2::policy<ext::balance_>());\n    }\n\n    //==========================================================================\n    /// INTERNAL ONLY - [W]= NSEIG(A, matrix_/vector_, balance_/no_balance_)\n    BOOST_FORCEINLINE\n    void eval ( A0& a0, A1& a1\n              , boost::mpl::long_<3> const&\n              , boost::mpl::long_<1> const&\n              ) const\n    {\n      eval1_3(a0, a1\n             , boost::proto::value(boost::proto::child_c<1>(a0))\n             , boost::proto::value(boost::proto::child_c<2>(a0)));\n    }\n\n    /// INTERNAL ONLY: 1o 3i\n    template < class T >\n    BOOST_FORCEINLINE\n    void eval1_3 ( A0& a0, A1& a1\n                 , T const &\n                 ,  nt2::policy<ext::no_balance_> const &\n                 ) const\n    {\n      eval1_2(a0, a1, T());\n    }\n\n    /// INTERNAL ONLY: 1o 3i\n    template < class T >\n    BOOST_FORCEINLINE\n    void eval1_3 ( A0& a0, A1& a1\n                 ,  nt2::policy<ext::vector_>  const &\n                 ,  nt2::policy<ext::balance_> const &\n                 ) const\n    {\n      nt2::container::table<type_t> a = boost::proto::child_c<0>(a0);\n      nt2::container::table<type_t> b = balance(a);\n      boost::proto::child_c<0>(a1) = nseig(b, nt2::policy<ext::vector_>());\n    }\n    /// INTERNAL ONLY: 1o 3i\n    BOOST_FORCEINLINE\n    void eval1_3 ( A0& a0, A1& a1\n                 ,  nt2::policy<ext::matrix_>  const &\n                 ,  nt2::policy<ext::balance_> const &\n                 ) const\n    {\n      nt2::container::table<type_t> a = boost::proto::child_c<0>(a0);\n      nt2::container::table<type_t> b = balance(a);\n      boost::proto::child_c<0>(a1) = nseig(b); //as_temporary(b));\n\n    }\n    //==========================================================================\n    /// INTERNAL ONLY - [V, W]= NSEIG(A, matrix_/vector_, balance_/no_balance_)\n    BOOST_FORCEINLINE\n    void eval ( A0& a0, A1& a1\n              , boost::mpl::long_<3> const&\n              , boost::mpl::long_<2> const&\n              ) const\n    {\n      eval2_3(a0, a1\n             , boost::proto::value(boost::proto::child_c<1>(a0))\n             , boost::proto::value(boost::proto::child_c<2>(a0)));\n    }\n\n    /// INTERNAL ONLY: 2o 3i\n    template < class T> BOOST_FORCEINLINE\n    void eval2_3 ( A0& a0, A1& a1\n                 ,  T  const &\n                 ,  nt2::policy<ext::no_balance_> const &\n                 ) const\n    {\n      eval2_2 (a0, a1, T());\n    }\n\n    /// INTERNAL ONLY: 2o 3i\n    BOOST_FORCEINLINE\n    void eval2_3 ( A0& a0, A1& a1\n                 ,  nt2::policy<ext::vector_>  const &\n                 ,  nt2::policy<ext::balance_> const &\n                 ) const\n    {\n      nt2::container::table<type_t> work;\n      NT2_AS_TERMINAL_INOUT(desired_semantic,  a, boost::proto::child_c<0>(a0), work);\n      NT2_AS_TERMINAL_OUT  (desired_semantic,  v, boost::proto::child_c<0>(a1));\n      NT2_AS_TERMINAL_OUT  (desired_semantic,  w, boost::proto::child_c<1>(a1));\n\n      nt2_la_int ilo, ihi;\n      nt2_la_int n = height(a);\n      nt2::container::table<rtype_t> scale(of_size(n, 1));\n      NT2_LAPACK_VERIFY(gebal(boost::proto::value(a)\n                             , boost::proto::value(scale)\n                             , ilo, ihi, 'B'));\n      tie(v, w) = nseig(a, nt2::policy<ext::vector_>());\n      NT2_LAPACK_VERIFY(gebak( boost::proto::value(v)\n                             , boost::proto::value(scale)\n                             , ilo, ihi, 'B', 'R'));\n      boost::proto::child_c<1>(a1) = w;\n      boost::proto::child_c<0>(a1) = v;\n    }\n\n    /// INTERNAL ONLY: 2o 3i\n    BOOST_FORCEINLINE\n    void eval2_3 ( A0& a0, A1& a1\n                 ,  nt2::policy<ext::matrix_>  const &\n                 ,  nt2::policy<ext::balance_> const &\n                 ) const\n    {\n      nt2::container::table<type_t> work;\n      NT2_AS_TERMINAL_INOUT(desired_semantic,  a, boost::proto::child_c<0>(a0), work);\n      NT2_AS_TERMINAL_OUT  (desired_semantic,  v, boost::proto::child_c<0>(a1));\n      NT2_AS_TERMINAL_OUT  (desired_semantic,  w, boost::proto::child_c<1>(a1));\n      nt2_la_int ilo, ihi;\n      nt2_la_int n = height(a);\n      nt2::container::table<rtype_t> scale(of_size(n, 1));\n      NT2_LAPACK_VERIFY(gebal( boost::proto::value(a)\n                             , boost::proto::value(scale)\n                             , ilo, ihi, 'B'));\n      tie(v, w) = nseig(a, nt2::policy<ext::matrix_>());\n      NT2_LAPACK_VERIFY(gebak( boost::proto::value(v)\n                             , boost::proto::value(scale)\n                             , ilo, ihi, 'B', 'R'));\n      boost::proto::child_c<1>(a1) = w;\n      boost::proto::child_c<0>(a1) = v;\n    }\n\n\n    //==========================================================================\n    /// INTERNAL ONLY - [VR, W, VL]= NSEIG(A, matrix_/vector_, balance_/no_balance_)\n    BOOST_FORCEINLINE\n    void eval ( A0& a0, A1& a1\n              , boost::mpl::long_<3> const&\n              , boost::mpl::long_<3> const&\n              ) const\n    {\n      eval3_3(a0, a1\n             , boost::proto::value(boost::proto::child_c<1>(a0))\n             , boost::proto::value(boost::proto::child_c<2>(a0)));\n    }\n\n     /// INTERNAL ONLY: 3o 3i\n    BOOST_FORCEINLINE\n    void eval3_3( A0& a0, A1& a1\n                 ,  nt2::policy<ext::vector_>  const &\n                 ,  nt2::policy<ext::no_balance_> const &\n                 ) const\n    {\n      nt2::container::table<type_t> work;\n      NT2_AS_TERMINAL_INOUT(desired_semantic,  a, boost::proto::child_c<0>(a0), work);\n      tie( boost::proto::child_c<0>(a1)\n         , boost::proto::child_c<1>(a1)\n         , boost::proto::child_c<2>(a1)) = nseig(a, nt2::policy<ext::vector_>());\n    }\n\n     /// INTERNAL ONLY: 3o 3i\n    BOOST_FORCEINLINE\n    void eval3_3( A0& a0, A1& a1\n                 ,  nt2::policy<ext::matrix_>  const &\n                 ,  nt2::policy<ext::no_balance_> const &\n                 ) const\n    {\n      nt2::container::table<type_t> work;\n      NT2_AS_TERMINAL_INOUT(desired_semantic,  a, boost::proto::child_c<0>(a0), work);\n      NT2_AS_TERMINAL_OUT  (desired_semantic, vr, boost::proto::child_c<0>(a1));\n      NT2_AS_TERMINAL_OUT  (desired_semantic, vl, boost::proto::child_c<2>(a1));\n      nt2_la_int n = height(a);\n      nt2::container::table<ctype_t> w(of_size(n, 1));\n      tie( vr, w, vl) = nseig(a, nt2::policy<ext::vector_>());\n      boost::proto::child_c<1>(a1) =  from_diag(w);\n      boost::proto::child_c<0>(a1) = vr;\n      boost::proto::child_c<2>(a1) = vl;\n    }\n\n    /// INTERNAL ONLY: 3o 3i\n    BOOST_FORCEINLINE\n    void eval3_3( A0& a0, A1& a1\n                 ,  nt2::policy<ext::vector_>  const &\n                 ,  nt2::policy<ext::balance_> const &\n                 ) const\n    {\n      nt2::container::table<type_t> work;\n      NT2_AS_TERMINAL_INOUT(desired_semantic,  a, boost::proto::child_c<0>(a0), work);\n      NT2_AS_TERMINAL_OUT  (desired_semantic, vr, boost::proto::child_c<0>(a1));\n      NT2_AS_TERMINAL_OUT  (desired_semantic, vl, boost::proto::child_c<2>(a1));\n      NT2_AS_TERMINAL_OUT  (desired_semantic,  w, boost::proto::child_c<1>(a1));\n      nt2_la_int ilo, ihi;\n      nt2_la_int n = height(a);\n      nt2::container::table<rtype_t> scale(of_size(n, 1));\n      NT2_LAPACK_VERIFY(gebal(boost::proto::value(a)\n                             , boost::proto::value(scale)\n                             , ilo, ihi, 'B'));\n      tie(vr, w, vl) = nseig(a, nt2::policy<ext::vector_>(), nt2::policy<ext::no_balance_>());\n      NT2_LAPACK_VERIFY(gebak(boost::proto::value(vr),\n                              boost::proto::value(scale)\n                             , ilo, ihi, 'B', 'R'));\n      NT2_LAPACK_VERIFY(gebak(boost::proto::value(vl)\n                             , boost::proto::value(scale)\n                             , ilo, ihi, 'B', 'L'));\n      boost::proto::child_c<1>(a1) = w;\n      boost::proto::child_c<0>(a1) = vr;\n      boost::proto::child_c<2>(a1) = vl;\n    }\n\n    /// INTERNAL ONLY\n    BOOST_FORCEINLINE\n    void eval3_3 ( A0& a0, A1& a1\n                 ,  nt2::policy<ext::matrix_>  const &\n                 ,  nt2::policy<ext::balance_> const &\n                 ) const\n    {\n      nt2::container::table<type_t> work;\n      NT2_AS_TERMINAL_INOUT(desired_semantic,  a, boost::proto::child_c<0>(a0), work);\n      NT2_AS_TERMINAL_OUT  (desired_semantic, vr, boost::proto::child_c<0>(a1));\n      NT2_AS_TERMINAL_OUT  (desired_semantic, vl, boost::proto::child_c<2>(a1));\n      NT2_AS_TERMINAL_OUT  (desired_semantic,  w, boost::proto::child_c<1>(a1));\n      nt2_la_int ilo, ihi;\n      nt2_la_int n = height(a);\n      nt2::container::table<rtype_t> scale(of_size(n, 1));\n      NT2_LAPACK_VERIFY(gebal(boost::proto::value(a), boost::proto::value(scale), ilo, ihi, 'B'));\n      tie(vr, w, vl) = nseig(a, nt2::policy<ext::matrix_>(), nt2::policy<ext::no_balance_>());\n      NT2_LAPACK_VERIFY(gebak(boost::proto::value(vr),\n                              boost::proto::value(scale), ilo, ihi, 'B', 'R'));\n      NT2_LAPACK_VERIFY(gebak(boost::proto::value(vl),\n                              boost::proto::value(scale), ilo, ihi, 'B', 'L'));\n      boost::proto::child_c<1>(a1) = w;\n      boost::proto::child_c<0>(a1) = vr;\n      boost::proto::child_c<2>(a1) = vl;\n    }\n\n  };\n} }\n\n#endif\n\n\n", "meta": {"hexsha": "64295a2ec5dd98314ebcc358e1d60c6ffcbba498", "size": 21450, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/core/linalg/include/nt2/linalg/functions/tied/nseig.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/tied/nseig.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/tied/nseig.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.0994671403, "max_line_length": 98, "alphanum_fraction": 0.5037296037, "num_tokens": 6175, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5851011542032313, "lm_q2_score": 0.5467381519846138, "lm_q1q2_score": 0.3198971237731392}}
{"text": "/****************************************************************************\n * Copyright (c) 2017-2021 by the ArborX authors                            *\n * All rights reserved.                                                     *\n *                                                                          *\n * This file is part of the ArborX library. ArborX is                       *\n * distributed under a BSD 3-clause license. For the licensing terms see    *\n * the LICENSE file in the top-level directory.                             *\n *                                                                          *\n * SPDX-License-Identifier: BSD-3-Clause                                    *\n ****************************************************************************/\n\n#include <ArborX.hpp>\n#include <ArborX_Ray.hpp>\n#include <ArborX_Version.hpp>\n\n#include <Kokkos_Core.hpp>\n\n#include <boost/program_options.hpp>\n\n#include <iostream>\n#include <random>\n\ntemplate <typename MemorySpace>\nstruct SpheresToBoxes\n{\n  Kokkos::View<ArborX::Sphere *, MemorySpace> _spheres;\n};\n\ntemplate <typename MemorySpace>\nstruct ArborX::AccessTraits<SpheresToBoxes<MemorySpace>, ArborX::PrimitivesTag>\n{\n  using memory_space = MemorySpace;\n\n  KOKKOS_FUNCTION static std::size_t\n  size(const SpheresToBoxes<MemorySpace> &stob)\n  {\n    return stob._spheres.extent(0);\n  }\n  KOKKOS_FUNCTION static ArborX::Box\n  get(SpheresToBoxes<MemorySpace> const &stobs, std::size_t const i)\n  {\n    auto const &sphere = stobs._spheres(i);\n    auto const &c = sphere.centroid();\n    auto const r = sphere.radius();\n    return {{c[0] - r, c[1] - r, c[2] - r}, {c[0] + r, c[1] + r, c[2] + r}};\n  }\n};\n\ntemplate <typename MemorySpace>\nstruct Rays\n{\n  Kokkos::View<ArborX::Experimental::Ray *, MemorySpace> _rays;\n};\n\ntemplate <typename MemorySpace>\nstruct ArborX::AccessTraits<Rays<MemorySpace>, ArborX::PredicatesTag>\n{\n  using memory_space = MemorySpace;\n\n  KOKKOS_FUNCTION static std::size_t size(const Rays<MemorySpace> &rays)\n  {\n    return rays._rays.extent(0);\n  }\n  KOKKOS_FUNCTION static auto get(Rays<MemorySpace> const &rays, std::size_t i)\n  {\n    return attach(intersects(rays._rays(i)), (int)i);\n  }\n};\n\ntemplate <typename MemorySpace>\nstruct AccumRaySphereInterDist\n{\n  Kokkos::View<ArborX::Sphere *, MemorySpace> _spheres;\n  Kokkos::View<float *, MemorySpace> _accumulator;\n\n  template <typename Predicate>\n  KOKKOS_FUNCTION void operator()(Predicate const &predicate,\n                                  int const primitive_index) const\n  {\n    auto const &ray = ArborX::getGeometry(predicate);\n    auto const &sphere = _spheres(primitive_index);\n\n    float const length = overlapDistance(ray, sphere);\n    int const i = getData(predicate);\n\n    Kokkos::atomic_add(&_accumulator(i), length);\n  }\n};\n\nint main(int argc, char *argv[])\n{\n  using ExecutionSpace = Kokkos::DefaultExecutionSpace;\n  using MemorySpace = ExecutionSpace::memory_space;\n\n  Kokkos::ScopeGuard guard(argc, argv);\n\n  namespace bpo = boost::program_options;\n\n  int num_spheres;\n  int num_rays;\n  float L;\n\n  bpo::options_description desc(\"Allowed options\");\n  // clang-format off\n  desc.add_options()\n    ( \"help\", \"help message\" )\n    (\"spheres\", bpo::value<int>(&num_spheres)->default_value(100), \"number of spheres\")\n    (\"rays\", bpo::value<int>(&num_rays)->default_value(10000), \"number of rays\")\n    (\"L\", bpo::value<float>(&L)->default_value(100.0), \"size of the domain\")\n    ;\n  // clang-format on\n  bpo::variables_map vm;\n  bpo::store(bpo::command_line_parser(argc, argv).options(desc).run(), vm);\n  bpo::notify(vm);\n\n  if (vm.count(\"help\") > 0)\n  {\n    std::cout << desc << '\\n';\n    return 1;\n  }\n\n  std::cout << \"ArborX version: \" << ArborX::version() << std::endl;\n  std::cout << \"ArborX hash   : \" << ArborX::gitCommitHash() << std::endl;\n  std::cout << \"Kokkos version: \" << KokkosExt::version() << std::endl;\n\n  std::uniform_real_distribution<float> uniform{0.0, 1.0};\n  std::default_random_engine gen;\n  auto rand_uniform = [&]() { return uniform(gen); };\n\n  // Random parameters for Gaussian distribution of radii\n  const float mu_R = 1.0;\n  const float sigma_R = mu_R / 3.0;\n\n  std::normal_distribution<> normal{mu_R, sigma_R};\n  auto rand_normal = [&]() { return std::max(normal(gen), 0.0); };\n\n  // Construct spheres\n  //\n  // The centers of spheres are uniformly sampling the domain. The radii of\n  // spheres have Gaussian (mu_R, sigma_R) sampling.\n  Kokkos::View<ArborX::Sphere *, MemorySpace> spheres(\n      Kokkos::view_alloc(Kokkos::WithoutInitializing, \"spheres\"), num_spheres);\n  auto spheres_host = Kokkos::create_mirror_view(spheres);\n  for (int i = 0; i < num_spheres; ++i)\n  {\n    spheres_host(i) = {\n        {rand_uniform() * L, rand_uniform() * L, rand_uniform() * L},\n        rand_normal()};\n  }\n  Kokkos::deep_copy(spheres, spheres_host);\n\n  // Construct rays\n  //\n  // The origins of rays are uniformly sampling the bottom surface of the\n  // domain. The direction vectors are uniformly sampling of a cosine-weighted\n  // hemisphere, It requires expressing the direction vector in the spherical\n  // coordinates as:\n  //    {sinpolar * cosazimuth, sinpolar * sinazimuth, cospolar}\n  // A detailed description can be found in the slides here (slide 47):\n  // https://cg.informatik.uni-freiburg.de/course_notes/graphics2_08_renderingEquation.pdf\n  Kokkos::View<ArborX::Experimental::Ray *, MemorySpace> rays(\n      Kokkos::view_alloc(Kokkos::WithoutInitializing, \"rays\"), num_rays);\n  auto rays_host = Kokkos::create_mirror_view(rays);\n\n  for (int i = 0; i < num_rays; ++i)\n  {\n    float xi_1 = rand_uniform();\n    float xi_2 = rand_uniform();\n\n    rays_host(i) = {ArborX::Point{rand_uniform() * L, rand_uniform() * L, 0.f},\n                    ArborX::Experimental::Vector{\n                        float(std::cos(2 * M_PI * xi_2) * std::sqrt(xi_1)),\n                        float(std::sin(2 * M_PI * xi_2) * std::sqrt(xi_1)),\n                        std::sqrt(1.f - xi_1)}};\n  }\n  Kokkos::deep_copy(rays, rays_host);\n\n  Kokkos::Timer timer;\n\n  ExecutionSpace exec_space{};\n\n  exec_space.fence();\n  timer.reset();\n  ArborX::BVH<MemorySpace> bvh{exec_space,\n                               SpheresToBoxes<MemorySpace>{spheres}};\n\n  Kokkos::View<float *, MemorySpace> accumulator(\"accumulator\", num_rays);\n  bvh.query(exec_space, Rays<MemorySpace>{rays},\n            AccumRaySphereInterDist<MemorySpace>{spheres, accumulator});\n  exec_space.fence();\n  auto time = timer.seconds();\n\n  auto accumulator_avg =\n      ArborX::accumulate(exec_space, accumulator, 0.f) / num_rays;\n\n  printf(\"time          : %.3f   [%.3fM ray/sec]\\n\", time,\n         num_rays / (1000000 * time));\n  printf(\"ray avg       : %.3f\\n\", accumulator_avg);\n\n  return EXIT_SUCCESS;\n}\n", "meta": {"hexsha": "6acf362183b5e8af721e203bfcf2eaa5ac34f779", "size": 6741, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/raytracing/example_raytracing.cpp", "max_stars_repo_name": "aprokop/ArborX", "max_stars_repo_head_hexsha": "db12a146f1eefc9adc19aaa145dbb21c6489da25", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-10-10T00:41:43.000Z", "max_stars_repo_stars_event_max_datetime": "2019-10-10T00:41:43.000Z", "max_issues_repo_path": "examples/raytracing/example_raytracing.cpp", "max_issues_repo_name": "aprokop/ArborX", "max_issues_repo_head_hexsha": "db12a146f1eefc9adc19aaa145dbb21c6489da25", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-05-07T01:31:37.000Z", "max_issues_repo_issues_event_max_datetime": "2021-02-20T16:31:13.000Z", "max_forks_repo_path": "examples/raytracing/example_raytracing.cpp", "max_forks_repo_name": "aprokop/ArborX", "max_forks_repo_head_hexsha": "db12a146f1eefc9adc19aaa145dbb21c6489da25", "max_forks_repo_licenses": ["BSD-3-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": 90, "alphanum_fraction": 0.6224595757, "num_tokens": 1755, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5851011542032312, "lm_q2_score": 0.546738151984614, "lm_q1q2_score": 0.3198971237731392}}
{"text": "/*******************************************************************************\n *\n * Data structures for the symbolic manipulation of linear constraints.\n *\n * Author: Arnaud J. Venet (arnaud.j.venet@nasa.gov)\n * Contributor: Jorge A. Navas (jorge.navas@sri.com)\n *\n * Notices:\n *\n * Copyright (c) 2011 United States Government as represented by the\n * Administrator of the National Aeronautics and Space Administration.\n * All Rights Reserved.\n *\n * Disclaimers:\n *\n * No Warranty: THE SUBJECT SOFTWARE IS PROVIDED \"AS IS\" WITHOUT ANY WARRANTY OF\n * ANY KIND, EITHER EXPRESSED, IMPLIED, OR STATUTORY, INCLUDING, BUT NOT LIMITED\n * TO, ANY WARRANTY THAT THE SUBJECT SOFTWARE WILL CONFORM TO SPECIFICATIONS,\n * ANY IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE,\n * OR FREEDOM FROM INFRINGEMENT, ANY WARRANTY THAT THE SUBJECT SOFTWARE WILL BE\n * ERROR FREE, OR ANY WARRANTY THAT DOCUMENTATION, IF PROVIDED, WILL CONFORM TO\n * THE SUBJECT SOFTWARE. THIS AGREEMENT DOES NOT, IN ANY MANNER, CONSTITUTE AN\n * ENDORSEMENT BY GOVERNMENT AGENCY OR ANY PRIOR RECIPIENT OF ANY RESULTS,\n * RESULTING DESIGNS, HARDWARE, SOFTWARE PRODUCTS OR ANY OTHER APPLICATIONS\n * RESULTING FROM USE OF THE SUBJECT SOFTWARE.  FURTHER, GOVERNMENT AGENCY\n * DISCLAIMS ALL WARRANTIES AND LIABILITIES REGARDING THIRD-PARTY SOFTWARE,\n * IF PRESENT IN THE ORIGINAL SOFTWARE, AND DISTRIBUTES IT \"AS IS.\"\n *\n * Waiver and Indemnity:  RECIPIENT AGREES TO WAIVE ANY AND ALL CLAIMS AGAINST\n * THE UNITED STATES GOVERNMENT, ITS CONTRACTORS AND SUBCONTRACTORS, AS WELL\n * AS ANY PRIOR RECIPIENT.  IF RECIPIENT'S USE OF THE SUBJECT SOFTWARE RESULTS\n * IN ANY LIABILITIES, DEMANDS, DAMAGES, EXPENSES OR LOSSES ARISING FROM SUCH\n * USE, INCLUDING ANY DAMAGES FROM PRODUCTS BASED ON, OR RESULTING FROM,\n * RECIPIENT'S USE OF THE SUBJECT SOFTWARE, RECIPIENT SHALL INDEMNIFY AND HOLD\n * HARMLESS THE UNITED STATES GOVERNMENT, ITS CONTRACTORS AND SUBCONTRACTORS,\n * AS WELL AS ANY PRIOR RECIPIENT, TO THE EXTENT PERMITTED BY LAW.\n * RECIPIENT'S SOLE REMEDY FOR ANY SUCH MATTER SHALL BE THE IMMEDIATE,\n * UNILATERAL TERMINATION OF THIS AGREEMENT.\n *\n ******************************************************************************/\n\n#pragma once\n\n#include <crab/common/types.hpp>\n#include <crab/numbers/bignums.hpp>\n#include <crab/domains/patricia_trees.hpp>\n\n#include <boost/container/flat_map.hpp>\n#include <boost/functional/hash_fwd.hpp> // for hash_combine\n#include <boost/iterator/transform_iterator.hpp>\n#include <boost/optional.hpp>\n\n#include <functional>\n#include <memory>\n#include <unordered_map>\n#include <unordered_set>\n#include <vector>\n#include <ostream>\n\nnamespace ikos {\n\ntemplate <typename Number, typename VariableName> class linear_expression {\n\npublic:\n  typedef Number number_t;\n  typedef VariableName varname_t;\n  typedef variable<Number, VariableName> variable_t;\n  typedef linear_expression<Number, VariableName> linear_expression_t;\n  typedef std::pair<Number, variable_t> component_t;\n  typedef patricia_tree_set<variable_t> variable_set_t;\n\nprivate:\n  typedef boost::container::flat_map<variable_t, Number> map_t;\n  typedef std::shared_ptr<map_t> map_ptr;\n  typedef typename map_t::value_type pair_t;\n\n  map_ptr _map;\n  Number _cst;\n\n  linear_expression(map_ptr map, Number cst) : _map(map), _cst(cst) {}\n\n  linear_expression(const map_t &map, Number cst)\n      : _map(std::make_shared<map_t>()), _cst(cst) {\n    *this->_map = map;\n  }\n\n  void add(variable_t x, Number n) {\n    typename map_t::iterator it = this->_map->find(x);\n    if (it != this->_map->end()) {\n      Number r = it->second + n;\n      if (r == 0) {\n        this->_map->erase(it);\n      } else {\n        it->second = r;\n      }\n    } else {\n      if (n != 0) {\n        this->_map->insert(pair_t(x, n));\n      }\n    }\n  }\n\n  struct tr_value_ty\n      : public std::unary_function<typename map_t::value_type, component_t> {\n    tr_value_ty() {}\n    component_t operator()(const typename map_t::value_type &kv) const {\n      return {kv.second, kv.first};\n    }\n  };\n\npublic:\n  typedef boost::transform_iterator<tr_value_ty, typename map_t::iterator>\n      iterator;\n  typedef boost::transform_iterator<tr_value_ty, typename map_t::const_iterator>\n      const_iterator;\n\n  linear_expression() : _map(std::make_shared<map_t>()), _cst(0) {}\n\n  linear_expression(Number n) : _map(std::make_shared<map_t>()), _cst(n) {}\n\n  linear_expression(int64_t n)\n      : _map(std::make_shared<map_t>()), _cst(Number(n)) {}\n\n  linear_expression(variable_t x) : _map(std::make_shared<map_t>()), _cst(0) {\n    this->_map->insert(pair_t(x, Number(1)));\n  }\n\n  linear_expression(Number n, variable_t x)\n      : _map(std::make_shared<map_t>()), _cst(0) {\n    this->_map->insert(pair_t(x, n));\n  }\n\n  linear_expression(const linear_expression_t &e) = default;\n  \n  linear_expression(linear_expression_t &&e) = default;\n \n  linear_expression_t &operator=(const linear_expression_t &e) = default;\n\n  linear_expression_t &operator=(linear_expression_t &&e) = default;\n  \n  const_iterator begin() const {\n    return boost::make_transform_iterator(_map->begin(), tr_value_ty());\n  }\n\n  const_iterator end() const {\n    return boost::make_transform_iterator(_map->end(), tr_value_ty());\n  }\n\n  iterator begin() {\n    return boost::make_transform_iterator(_map->begin(), tr_value_ty());\n  }\n\n  iterator end() {\n    return boost::make_transform_iterator(_map->end(), tr_value_ty());\n  }\n\n  size_t hash() const {\n    size_t res = 0;\n    for (const_iterator it = begin(), et = end(); it != et; ++it) {\n      boost::hash_combine(res, std::make_pair((*it).second, (*it).first));\n    }\n    boost::hash_combine(res, _cst);\n    return res;\n  }\n\n  // syntactic equality\n  bool equal(const linear_expression_t &o) const {\n    if (is_constant()) {\n      if (!o.is_constant()) {\n        return false;\n      } else {\n        return (constant() == o.constant());\n      }\n    } else {\n      if (constant() != o.constant()) {\n        return false;\n      }\n\n      if (size() != o.size()) {\n        return false;\n      } else {\n        for (const_iterator it = begin(), jt = o.begin(), et = end(); it != et;\n             ++it, ++jt) {\n          if (((*it).first != (*jt).first) || ((*it).second != (*jt).second)) {\n            return false;\n          }\n        }\n        return true;\n      }\n    }\n  }\n\n  bool is_constant() const { return (this->_map->size() == 0); }\n\n  Number constant() const { return this->_cst; }\n\n  std::size_t size() const { return this->_map->size(); }\n\n  Number operator[](variable_t x) const {\n    typename map_t::const_iterator it = this->_map->find(x);\n    if (it != this->_map->end()) {\n      return it->second;\n    } else {\n      return 0;\n    }\n  }\n\n  template <typename RenamingMap>\n  linear_expression_t rename(const RenamingMap &map) const {\n    Number cst(this->_cst);\n    linear_expression_t new_exp(cst);\n    for (auto v : this->variables()) {\n      auto const it = map.find(v);\n      if (it != map.end()) {\n        variable_t v_out((*it).second);\n        new_exp = new_exp + this->operator[](v) * v_out;\n      } else {\n        new_exp = new_exp + this->operator[](v) * v;\n      }\n    }\n    return new_exp;\n  }\n\n  linear_expression_t operator+(Number n) const {\n    linear_expression_t r(this->_map, this->_cst + n);\n    return r;\n  }\n\n  linear_expression_t operator+(int64_t n) const {\n    return this->operator+(Number(n));\n  }\n\n  linear_expression_t operator+(variable_t x) const {\n    linear_expression_t r(*this->_map, this->_cst);\n    r.add(x, Number(1));\n    return r;\n  }\n\n  linear_expression_t operator+(const linear_expression_t &e) const {\n    linear_expression_t r(*this->_map, this->_cst + e._cst);\n    for (typename map_t::const_iterator it = e._map->begin();\n         it != e._map->end(); ++it) {\n      r.add(it->first, it->second);\n    }\n    return r;\n  }\n\n  linear_expression_t operator-(Number n) const { return this->operator+(-n); }\n\n  linear_expression_t operator-(int64_t n) const {\n    return this->operator+(-Number(n));\n  }\n\n  linear_expression_t operator-(variable_t x) const {\n    linear_expression_t r(*this->_map, this->_cst);\n    r.add(x, Number(-1));\n    return r;\n  }\n\n  linear_expression_t operator-() const { return this->operator*(Number(-1)); }\n\n  linear_expression_t operator-(const linear_expression_t &e) const {\n    linear_expression_t r(*this->_map, this->_cst - e._cst);\n    for (typename map_t::const_iterator it = e._map->begin();\n         it != e._map->end(); ++it) {\n      r.add(it->first, -it->second);\n    }\n    return r;\n  }\n\n  linear_expression_t operator*(Number n) const {\n    if (n == 0) {\n      return linear_expression_t();\n    } else {\n      map_ptr map = std::make_shared<map_t>();\n      for (typename map_t::const_iterator it = this->_map->begin();\n           it != this->_map->end(); ++it) {\n        Number c = n * it->second;\n        if (c != 0) {\n          map->insert(pair_t(it->first, c));\n        }\n      }\n      return linear_expression_t(map, n * this->_cst);\n    }\n  }\n\n  linear_expression_t operator*(int64_t n) const {\n    return operator*(Number(n));\n  }\n\n  variable_set_t variables() const {\n    variable_set_t variables;\n    for (const_iterator it = this->begin(); it != this->end(); ++it) {\n      variables += it->second;\n    }\n    return variables;\n  }\n\n  bool is_well_typed() const {\n    typename variable_t::bitwidth_t b;\n    crab::variable_type type;\n    for (const_iterator it = begin(), et = end(); it != et; ++it) {\n      variable_t v = it->second;\n      if (it == begin()) {\n        b = v.get_bitwidth();\n        type = v.get_type();\n      } else {\n        if (v.get_bitwidth() != b || v.get_type() != type) {\n          return false;\n        }\n      }\n    }\n    return true;\n  }\n\n  boost::optional<variable_t> get_variable() const {\n    if (this->is_constant())\n      return boost::optional<variable_t>();\n    else {\n      if ((this->constant() == 0) && (this->size() == 1)) {\n        const_iterator it = this->begin();\n        Number coeff = it->first;\n        if (coeff == 1)\n          return boost::optional<variable_t>(it->second);\n      }\n      return boost::optional<variable_t>();\n    }\n  }\n\n  void write(crab::crab_os &o) const {\n    for (typename map_t::const_iterator it = this->_map->begin();\n         it != this->_map->end(); ++it) {\n      Number n = it->second;\n      variable_t v = it->first;\n      if (n > 0 && it != this->_map->begin()) {\n        o << \"+\";\n      }\n      if (n == -1) {\n        o << \"-\";\n      } else if (n != 1) {\n        o << n << \"*\";\n      }\n      o << v;\n    }\n    if (this->_cst > 0 && this->_map->size() > 0) {\n      o << \"+\";\n    }\n    if (this->_cst != 0 || this->_map->size() == 0) {\n      o << this->_cst;\n    }\n  }\n\n  // for dgb\n  void dump() { write(crab::outs()); }\n\n}; // class linear_expression\n\ntemplate <typename Number, typename VariableName>\ninline crab::crab_os &\noperator<<(crab::crab_os &o, const linear_expression<Number, VariableName> &e) {\n  e.write(o);\n  return o;\n}\n\n/* used by boost::hash_combine */\ntemplate <typename Number, typename VariableName>\ninline std::size_t\nhash_value(const linear_expression<Number, VariableName> &e) {\n  return e.hash();\n}\n\ntemplate <typename Number, typename VariableName>\nstruct linear_expression_hasher {\n  size_t operator()(const linear_expression<Number, VariableName> &e) const {\n    return e.hash();\n  }\n};\n\ntemplate <typename Number, typename VariableName>\nstruct linear_expression_equal {\n  bool operator()(const linear_expression<Number, VariableName> &e1,\n                  const linear_expression<Number, VariableName> &e2) const {\n    return e1.equal(e2);\n  }\n};\n\ntemplate <typename Number, typename VariableName>\nusing linear_expression_unordered_set =\n    std::unordered_set<linear_expression<Number, VariableName>,\n                       linear_expression_hasher<Number, VariableName>,\n                       linear_expression_equal<Number, VariableName>>;\n\ntemplate <typename Number, typename VariableName, typename Value>\nusing linear_expression_unordered_map =\n    std::unordered_map<linear_expression<Number, VariableName>, Value,\n                       linear_expression_hasher<Number, VariableName>,\n                       linear_expression_equal<Number, VariableName>>;\n\ntemplate <typename Number, typename VariableName>\ninline linear_expression<Number, VariableName>\noperator*(Number n, variable<Number, VariableName> x) {\n  return linear_expression<Number, VariableName>(n, x);\n}\n\ntemplate <typename Number, typename VariableName>\ninline linear_expression<Number, VariableName>\noperator*(int64_t n, variable<Number, VariableName> x) {\n  return linear_expression<Number, VariableName>(Number(n), x);\n}\n\ntemplate <typename Number, typename VariableName>\ninline linear_expression<Number, VariableName>\noperator*(variable<Number, VariableName> x, Number n) {\n  return linear_expression<Number, VariableName>(n, x);\n}\n\ntemplate <typename Number, typename VariableName>\ninline linear_expression<Number, VariableName>\noperator*(variable<Number, VariableName> x, int64_t n) {\n  return linear_expression<Number, VariableName>(Number(n), x);\n}\n\ntemplate <typename Number, typename VariableName>\ninline linear_expression<Number, VariableName>\noperator*(Number n, const linear_expression<Number, VariableName> &e) {\n  return e.operator*(n);\n}\n\ntemplate <typename Number, typename VariableName>\ninline linear_expression<Number, VariableName>\noperator*(int64_t n, const linear_expression<Number, VariableName> &e) {\n  return e.operator*(n);\n}\n\ntemplate <typename Number, typename VariableName>\ninline linear_expression<Number, VariableName>\noperator+(variable<Number, VariableName> x, Number n) {\n  return linear_expression<Number, VariableName>(x).operator+(n);\n}\n\ntemplate <typename Number, typename VariableName>\ninline linear_expression<Number, VariableName>\noperator+(variable<Number, VariableName> x, int64_t n) {\n  return linear_expression<Number, VariableName>(x).operator+(n);\n}\n\ntemplate <typename Number, typename VariableName>\ninline linear_expression<Number, VariableName>\noperator+(Number n, variable<Number, VariableName> x) {\n  return linear_expression<Number, VariableName>(x).operator+(n);\n}\n\ntemplate <typename Number, typename VariableName>\ninline linear_expression<Number, VariableName>\noperator+(int64_t n, variable<Number, VariableName> x) {\n  return linear_expression<Number, VariableName>(x).operator+(n);\n}\n\ntemplate <typename Number, typename VariableName>\ninline linear_expression<Number, VariableName>\noperator+(variable<Number, VariableName> x, variable<Number, VariableName> y) {\n  return linear_expression<Number, VariableName>(x).operator+(y);\n}\n\ntemplate <typename Number, typename VariableName>\ninline linear_expression<Number, VariableName>\noperator+(Number n, const linear_expression<Number, VariableName> &e) {\n  return e.operator+(n);\n}\n\ntemplate <typename Number, typename VariableName>\ninline linear_expression<Number, VariableName>\noperator+(int64_t n, const linear_expression<Number, VariableName> &e) {\n  return e.operator+(n);\n}\n\ntemplate <typename Number, typename VariableName>\ninline linear_expression<Number, VariableName>\noperator+(variable<Number, VariableName> x,\n          const linear_expression<Number, VariableName> &e) {\n  return e.operator+(x);\n}\n\ntemplate <typename Number, typename VariableName>\ninline linear_expression<Number, VariableName>\noperator-(variable<Number, VariableName> x, Number n) {\n  return linear_expression<Number, VariableName>(x).operator-(n);\n}\n\ntemplate <typename Number, typename VariableName>\ninline linear_expression<Number, VariableName>\noperator-(variable<Number, VariableName> x, int64_t n) {\n  return linear_expression<Number, VariableName>(x).operator-(n);\n}\n\ntemplate <typename Number, typename VariableName>\ninline linear_expression<Number, VariableName>\noperator-(Number n, variable<Number, VariableName> x) {\n  return linear_expression<Number, VariableName>(Number(-1), x).operator+(n);\n}\n\ntemplate <typename Number, typename VariableName>\ninline linear_expression<Number, VariableName>\noperator-(int64_t n, variable<Number, VariableName> x) {\n  return linear_expression<Number, VariableName>(Number(-1), x).operator+(n);\n}\n\ntemplate <typename Number, typename VariableName>\ninline linear_expression<Number, VariableName>\noperator-(variable<Number, VariableName> x, variable<Number, VariableName> y) {\n  return linear_expression<Number, VariableName>(x).operator-(y);\n}\n\ntemplate <typename Number, typename VariableName>\ninline linear_expression<Number, VariableName>\noperator-(Number n, const linear_expression<Number, VariableName> &e) {\n  return linear_expression<Number, VariableName>(n).operator-(e);\n}\n\ntemplate <typename Number, typename VariableName>\ninline linear_expression<Number, VariableName>\noperator-(int64_t n, const linear_expression<Number, VariableName> &e) {\n  return linear_expression<Number, VariableName>(Number(n)).operator-(e);\n}\n\ntemplate <typename Number, typename VariableName>\ninline linear_expression<Number, VariableName>\noperator-(variable<Number, VariableName> x,\n          const linear_expression<Number, VariableName> &e) {\n  return linear_expression<Number, VariableName>(Number(1), x).operator-(e);\n}\n\ntemplate <typename Number, typename VariableName> class linear_constraint {\n\npublic:\n  typedef Number number_t;\n  typedef VariableName varname_t;\n  typedef linear_constraint<Number, VariableName> linear_constraint_t;\n  typedef variable<Number, VariableName> variable_t;\n  typedef linear_expression<Number, VariableName> linear_expression_t;\n  typedef patricia_tree_set<variable_t> variable_set_t;\n  typedef enum { EQUALITY, DISEQUATION, INEQUALITY, STRICT_INEQUALITY } kind_t;\n  typedef typename linear_expression_t::iterator iterator;\n  typedef typename linear_expression_t::const_iterator const_iterator;\n\nprivate:\n  kind_t _kind;\n  linear_expression_t _expr;\n  // This flag has meaning only if _kind == INEQUALITY or STRICT_INEQUALITY.\n  // If true the inequality is signed otherwise unsigned.\n  // By default all constraints are signed.\n  bool _signedness;\n\npublic:\n  linear_constraint() : _kind(EQUALITY), _signedness(true) {}\n\n  linear_constraint(const linear_expression_t &expr, kind_t kind)\n      : _kind(kind), _expr(expr), _signedness(true) {}\n\n  linear_constraint(const linear_expression_t &expr, kind_t kind,\n                    bool signedness)\n      : _kind(kind), _expr(expr), _signedness(signedness) {\n    if (_kind != INEQUALITY && _kind != STRICT_INEQUALITY) {\n      CRAB_ERROR(\"Only inequalities can have signedness information\");\n    }\n  }\n\n  linear_constraint(const linear_constraint_t &c) = default;\n\n  linear_constraint(linear_constraint_t &&c) = default;\n  \n  linear_constraint_t &operator=(const linear_constraint_t &c) = default;\n  \n  linear_constraint_t &operator=(linear_constraint_t &&c) = default;\n  \n  static linear_constraint_t get_true() {\n    linear_constraint_t res(linear_expression_t(Number(0)), EQUALITY);\n    return res;\n  }\n\n  static linear_constraint_t get_false() {\n    linear_constraint_t res(linear_expression_t(Number(0)), DISEQUATION);\n    return res;\n  }\n\n  bool is_tautology() const {\n    switch (this->_kind) {\n    case DISEQUATION:\n      return (this->_expr.is_constant() && this->_expr.constant() != 0);\n    case EQUALITY:\n      return (this->_expr.is_constant() && this->_expr.constant() == 0);\n    case INEQUALITY:\n      return (this->_expr.is_constant() && this->_expr.constant() <= 0);\n    case STRICT_INEQUALITY:\n      return (this->_expr.is_constant() && this->_expr.constant() < 0);\n    default:\n      CRAB_ERROR(\"Unreachable\");\n    }\n  }\n\n  bool is_contradiction() const {\n    switch (this->_kind) {\n    case DISEQUATION:\n      return (this->_expr.is_constant() && this->_expr.constant() == 0);\n    case EQUALITY:\n      return (this->_expr.is_constant() && this->_expr.constant() != 0);\n    case INEQUALITY:\n      return (this->_expr.is_constant() && this->_expr.constant() > 0);\n    case STRICT_INEQUALITY:\n      return (this->_expr.is_constant() && this->_expr.constant() >= 0);\n    default:\n      CRAB_ERROR(\"Unreachable\");\n    }\n  }\n\n  bool is_inequality() const { return (this->_kind == INEQUALITY); }\n\n  bool is_strict_inequality() const {\n    return (this->_kind == STRICT_INEQUALITY);\n  }\n\n  bool is_equality() const { return (this->_kind == EQUALITY); }\n\n  bool is_disequation() const { return (this->_kind == DISEQUATION); }\n\n  const linear_expression_t &expression() const { return this->_expr; }\n\n  kind_t kind() const { return this->_kind; }\n\n  bool is_signed() const {\n    if (_kind != INEQUALITY && _kind != STRICT_INEQUALITY) {\n      CRAB_WARN(\"Only inequalities have signedness\");\n    }\n    return _signedness;\n  }\n\n  bool is_unsigned() const { return (!is_signed()); }\n\n  void set_signed() {\n    if (_kind == INEQUALITY || _kind == STRICT_INEQUALITY) {\n      _signedness = true;\n    } else {\n      CRAB_WARN(\"Only inequalities have signedness\");\n    }\n  }\n\n  void set_unsigned() {\n    if (_kind == INEQUALITY || _kind == STRICT_INEQUALITY) {\n      _signedness = false;\n    } else {\n      CRAB_WARN(\"Only inequalities have signedness\");\n    }\n  }\n\n  const_iterator begin() const { return this->_expr.begin(); }\n\n  const_iterator end() const { return this->_expr.end(); }\n\n  iterator begin() { return this->_expr.begin(); }\n\n  iterator end() { return this->_expr.end(); }\n\n  Number constant() const { return -this->_expr.constant(); }\n\n  std::size_t size() const { return this->_expr.size(); }\n\n  // syntactic equality\n  bool equal(const linear_constraint_t &o) const {\n    return (_kind == o._kind && _signedness == o._signedness &&\n            _expr.equal(o._expr));\n  }\n\n  size_t hash() const {\n    size_t res = 0;\n    boost::hash_combine(res, _expr);\n    boost::hash_combine(res, _kind);\n    if (_kind == INEQUALITY || _kind == STRICT_INEQUALITY) {\n      boost::hash_combine(res, _signedness);\n    }\n    return res;\n  }\n\n  index_t index() const {\n    // XXX: to store linear constraints in patricia trees\n    // Ufff, the indexes may not be unique. Check that patricia\n    // trees are ok with that.\n    return (index_t)hash();\n  }\n\n  Number operator[](variable_t x) const { return this->_expr.operator[](x); }\n\n  variable_set_t variables() const { return this->_expr.variables(); }\n\n  bool is_well_typed() const { return _expr.is_well_typed(); }\n\n  linear_constraint_t negate() const;\n\n  template <typename RenamingMap>\n  linear_constraint_t rename(const RenamingMap &map) const {\n    linear_expression_t e = this->_expr.rename(map);\n    return linear_constraint_t(e, this->_kind, is_signed());\n  }\n\n  void write(crab::crab_os &o) const {\n    if (this->is_contradiction()) {\n      o << \"false\";\n    } else if (this->is_tautology()) {\n      o << \"true\";\n    } else {\n      linear_expression_t e = this->_expr - this->_expr.constant();\n      o << e;\n      switch (this->_kind) {\n      case INEQUALITY: {\n        if (is_signed()) {\n          o << \" <= \";\n        } else {\n          o << \" <=_u \";\n        }\n        break;\n      }\n      case STRICT_INEQUALITY: {\n        if (is_signed()) {\n          o << \" < \";\n        } else {\n          o << \" <_u \";\n        }\n        break;\n      }\n      case EQUALITY: {\n        o << \" = \";\n        break;\n      }\n      case DISEQUATION: {\n        o << \" != \";\n        break;\n      }\n      }\n      Number c = -this->_expr.constant();\n      o << c;\n    }\n  }\n\n  // for dgb\n  void dump() { write(crab::outs()); }\n\n}; // class linear_constraint\n\ntemplate <typename Number, typename VariableName>\ninline crab::crab_os &\noperator<<(crab::crab_os &o, const linear_constraint<Number, VariableName> &c) {\n  c.write(o);\n  return o;\n}\n\nnamespace linear_constraint_impl {\n\ntemplate <typename Number, typename VariableName>\nlinear_constraint<Number, VariableName>\nnegate_inequality(const linear_constraint<Number, VariableName> &c) {\n  typedef linear_expression<Number, VariableName> linear_expression_t;\n  typedef linear_constraint<Number, VariableName> linear_constraint_t;\n  assert(c.is_inequality());\n  // default implementation: negate(e <= 0) = e > 0\n  linear_expression_t e(-c.expression());\n  return linear_constraint_t(e, linear_constraint_t::kind_t::STRICT_INEQUALITY,\n                             c.is_signed());\n}\n\n// Specialized version for z_number\ntemplate <typename VariableName>\nlinear_constraint<z_number, VariableName>\nnegate_inequality(const linear_constraint<z_number, VariableName> &c) {\n  typedef linear_expression<z_number, VariableName> linear_expression_t;\n  typedef linear_constraint<z_number, VariableName> linear_constraint_t;\n  assert(c.is_inequality());\n  // negate(e <= 0) = e >= 1\n  linear_expression_t e(-(c.expression() - 1));\n  return linear_constraint_t(e, linear_constraint_t::kind_t::INEQUALITY,\n                             c.is_signed());\n}\n\ntemplate <typename Number, typename VariableName>\nlinear_constraint<Number, VariableName> strict_to_non_strict_inequality(\n    const linear_constraint<Number, VariableName> &c) {\n  typedef linear_constraint<Number, VariableName> linear_constraint_t;\n  assert(c.is_strict_inequality());\n  // Default implementation: do nothing\n  // Given constraint e < 0 we could return two linear constraints: e <= 0 and e\n  // != 0. The linear interval solver lowers strict inequalities in that way.\n  return c;\n}\n\n// Specialized version for z_number\ntemplate <typename VariableName>\nlinear_constraint<z_number, VariableName> strict_to_non_strict_inequality(\n    const linear_constraint<z_number, VariableName> &c) {\n  typedef linear_expression<z_number, VariableName> linear_expression_t;\n  typedef linear_constraint<z_number, VariableName> linear_constraint_t;\n  assert(c.is_strict_inequality());\n  // e < 0 --> e <= -1\n  linear_expression_t e(c.expression() + 1);\n  return linear_constraint_t(e, linear_constraint_t::kind_t::INEQUALITY,\n                             c.is_signed());\n}\n} // end namespace linear_constraint_impl\n\ntemplate <typename Number, typename VariableName>\nlinear_constraint<Number, VariableName>\nlinear_constraint<Number, VariableName>::negate() const {\n  typedef linear_constraint<Number, VariableName> linear_constraint_t;\n  typedef linear_expression<Number, VariableName> linear_expression_t;\n\n  if (is_tautology()) {\n    return get_false();\n  } else if (is_contradiction()) {\n    return get_true();\n  } else {\n    switch (kind()) {\n    case INEQUALITY: {\n      // negate_inequality tries to take advantage if we use z_number.\n      return linear_constraint_impl::negate_inequality(*this);\n    }\n    case STRICT_INEQUALITY: {\n      // negate(x + y < 0)  <-->  x + y >= 0 <--> -x -y <= 0\n      linear_expression_t e = -this->_expr;\n      return linear_constraint_t(e, INEQUALITY, is_signed());\n    }\n    case EQUALITY:\n      return linear_constraint_t(this->_expr, DISEQUATION);\n    case DISEQUATION:\n      return linear_constraint_t(this->_expr, EQUALITY);\n    default:\n      CRAB_ERROR(\"Cannot negate linear constraint\");\n    }\n  }\n}\n\ntemplate <typename Number, typename VariableName>\ninline linear_constraint<Number, VariableName>\noperator<=(const linear_expression<Number, VariableName> &e, Number n) {\n  return linear_constraint<Number, VariableName>(\n      e - n, linear_constraint<Number, VariableName>::INEQUALITY);\n}\n\ntemplate <typename Number, typename VariableName>\ninline linear_constraint<Number, VariableName>\noperator<=(const linear_expression<Number, VariableName> &e, int64_t n) {\n  return linear_constraint<Number, VariableName>(\n      e - n, linear_constraint<Number, VariableName>::INEQUALITY);\n}\n\ntemplate <typename Number, typename VariableName>\ninline linear_constraint<Number, VariableName>\noperator<=(Number n, const linear_expression<Number, VariableName> &e) {\n  return linear_constraint<Number, VariableName>(\n      n - e, linear_constraint<Number, VariableName>::INEQUALITY);\n}\n\ntemplate <typename Number, typename VariableName>\ninline linear_constraint<Number, VariableName>\noperator<=(int64_t n, const linear_expression<Number, VariableName> &e) {\n  return linear_constraint<Number, VariableName>(\n      n - e, linear_constraint<Number, VariableName>::INEQUALITY);\n}\n\ntemplate <typename Number, typename VariableName>\ninline linear_constraint<Number, VariableName>\noperator<=(const linear_expression<Number, VariableName> &e,\n           variable<Number, VariableName> x) {\n  return linear_constraint<Number, VariableName>(\n      e - x, linear_constraint<Number, VariableName>::INEQUALITY);\n}\n\ntemplate <typename Number, typename VariableName>\ninline linear_constraint<Number, VariableName>\noperator<=(variable<Number, VariableName> x,\n           const linear_expression<Number, VariableName> &e) {\n  return linear_constraint<Number, VariableName>(\n      x - e, linear_constraint<Number, VariableName>::INEQUALITY);\n}\n\ntemplate <typename Number, typename VariableName>\ninline linear_constraint<Number, VariableName>\noperator<=(variable<Number, VariableName> x, Number n) {\n  return linear_constraint<Number, VariableName>(\n      x - n, linear_constraint<Number, VariableName>::INEQUALITY);\n}\n\ntemplate <typename Number, typename VariableName>\ninline linear_constraint<Number, VariableName>\noperator<=(variable<Number, VariableName> x, int64_t n) {\n  return linear_constraint<Number, VariableName>(\n      x - n, linear_constraint<Number, VariableName>::INEQUALITY);\n}\n\ntemplate <typename Number, typename VariableName>\ninline linear_constraint<Number, VariableName>\noperator<=(Number n, variable<Number, VariableName> x) {\n  return linear_constraint<Number, VariableName>(\n      n - x, linear_constraint<Number, VariableName>::INEQUALITY);\n}\n\ntemplate <typename Number, typename VariableName>\ninline linear_constraint<Number, VariableName>\noperator<=(int64_t n, variable<Number, VariableName> x) {\n  return linear_constraint<Number, VariableName>(\n      n - x, linear_constraint<Number, VariableName>::INEQUALITY);\n}\n\ntemplate <typename Number, typename VariableName>\ninline linear_constraint<Number, VariableName>\noperator<=(variable<Number, VariableName> x, variable<Number, VariableName> y) {\n  return linear_constraint<Number, VariableName>(\n      x - y, linear_constraint<Number, VariableName>::INEQUALITY);\n}\n\ntemplate <typename Number, typename VariableName>\ninline linear_constraint<Number, VariableName>\noperator<=(const linear_expression<Number, VariableName> &e1,\n           const linear_expression<Number, VariableName> &e2) {\n  return linear_constraint<Number, VariableName>(\n      e1 - e2, linear_constraint<Number, VariableName>::INEQUALITY);\n}\n\ntemplate <typename Number, typename VariableName>\ninline linear_constraint<Number, VariableName>\noperator>=(const linear_expression<Number, VariableName> &e, Number n) {\n  return linear_constraint<Number, VariableName>(\n      n - e, linear_constraint<Number, VariableName>::INEQUALITY);\n}\n\ntemplate <typename Number, typename VariableName>\ninline linear_constraint<Number, VariableName>\noperator>=(const linear_expression<Number, VariableName> &e, int64_t n) {\n  return linear_constraint<Number, VariableName>(\n      n - e, linear_constraint<Number, VariableName>::INEQUALITY);\n}\n\ntemplate <typename Number, typename VariableName>\ninline linear_constraint<Number, VariableName>\noperator>=(Number n, const linear_expression<Number, VariableName> &e) {\n  return linear_constraint<Number, VariableName>(\n      e - n, linear_constraint<Number, VariableName>::INEQUALITY);\n}\n\ntemplate <typename Number, typename VariableName>\ninline linear_constraint<Number, VariableName>\noperator>=(int64_t n, const linear_expression<Number, VariableName> &e) {\n  return linear_constraint<Number, VariableName>(\n      e - n, linear_constraint<Number, VariableName>::INEQUALITY);\n}\n\ntemplate <typename Number, typename VariableName>\ninline linear_constraint<Number, VariableName>\noperator>=(const linear_expression<Number, VariableName> &e,\n           variable<Number, VariableName> x) {\n  return linear_constraint<Number, VariableName>(\n      x - e, linear_constraint<Number, VariableName>::INEQUALITY);\n}\n\ntemplate <typename Number, typename VariableName>\ninline linear_constraint<Number, VariableName>\noperator>=(variable<Number, VariableName> x,\n           const linear_expression<Number, VariableName> &e) {\n  return linear_constraint<Number, VariableName>(\n      e - x, linear_constraint<Number, VariableName>::INEQUALITY);\n}\n\ntemplate <typename Number, typename VariableName>\ninline linear_constraint<Number, VariableName>\noperator>=(variable<Number, VariableName> x, Number n) {\n  return linear_constraint<Number, VariableName>(\n      n - x, linear_constraint<Number, VariableName>::INEQUALITY);\n}\n\ntemplate <typename Number, typename VariableName>\ninline linear_constraint<Number, VariableName>\noperator>=(variable<Number, VariableName> x, int64_t n) {\n  return linear_constraint<Number, VariableName>(\n      n - x, linear_constraint<Number, VariableName>::INEQUALITY);\n}\n\ntemplate <typename Number, typename VariableName>\ninline linear_constraint<Number, VariableName>\noperator>=(Number n, variable<Number, VariableName> x) {\n  return linear_constraint<Number, VariableName>(\n      x - n, linear_constraint<Number, VariableName>::INEQUALITY);\n}\n\ntemplate <typename Number, typename VariableName>\ninline linear_constraint<Number, VariableName>\noperator>=(int64_t n, variable<Number, VariableName> x) {\n  return linear_constraint<Number, VariableName>(\n      x - n, linear_constraint<Number, VariableName>::INEQUALITY);\n}\n\ntemplate <typename Number, typename VariableName>\ninline linear_constraint<Number, VariableName>\noperator>=(variable<Number, VariableName> x, variable<Number, VariableName> y) {\n  return linear_constraint<Number, VariableName>(\n      y - x, linear_constraint<Number, VariableName>::INEQUALITY);\n}\n\ntemplate <typename Number, typename VariableName>\ninline linear_constraint<Number, VariableName>\noperator>=(const linear_expression<Number, VariableName> &e1,\n           const linear_expression<Number, VariableName> &e2) {\n  return linear_constraint<Number, VariableName>(\n      e2 - e1, linear_constraint<Number, VariableName>::INEQUALITY);\n}\n\ntemplate <typename Number, typename VariableName>\ninline linear_constraint<Number, VariableName>\noperator<(const linear_expression<Number, VariableName> &e, Number n) {\n  return linear_constraint<Number, VariableName>(\n      e - n, linear_constraint<Number, VariableName>::STRICT_INEQUALITY);\n}\n\ntemplate <typename Number, typename VariableName>\ninline linear_constraint<Number, VariableName>\noperator<(const linear_expression<Number, VariableName> &e, int64_t n) {\n  return linear_constraint<Number, VariableName>(\n      e - n, linear_constraint<Number, VariableName>::STRICT_INEQUALITY);\n}\n\ntemplate <typename Number, typename VariableName>\ninline linear_constraint<Number, VariableName>\noperator<(Number n, const linear_expression<Number, VariableName> &e) {\n  return linear_constraint<Number, VariableName>(\n      n - e, linear_constraint<Number, VariableName>::STRICT_INEQUALITY);\n}\n\ntemplate <typename Number, typename VariableName>\ninline linear_constraint<Number, VariableName>\noperator<(int64_t n, const linear_expression<Number, VariableName> &e) {\n  return linear_constraint<Number, VariableName>(\n      n - e, linear_constraint<Number, VariableName>::STRICT_INEQUALITY);\n}\n\ntemplate <typename Number, typename VariableName>\ninline linear_constraint<Number, VariableName>\noperator<(const linear_expression<Number, VariableName> &e,\n          variable<Number, VariableName> x) {\n  return linear_constraint<Number, VariableName>(\n      e - x, linear_constraint<Number, VariableName>::STRICT_INEQUALITY);\n}\n\ntemplate <typename Number, typename VariableName>\ninline linear_constraint<Number, VariableName>\noperator<(variable<Number, VariableName> x,\n          const linear_expression<Number, VariableName> &e) {\n  return linear_constraint<Number, VariableName>(\n      x - e, linear_constraint<Number, VariableName>::STRICT_INEQUALITY);\n}\n\ntemplate <typename Number, typename VariableName>\ninline linear_constraint<Number, VariableName>\noperator<(variable<Number, VariableName> x, Number n) {\n  return linear_constraint<Number, VariableName>(\n      x - n, linear_constraint<Number, VariableName>::STRICT_INEQUALITY);\n}\n\ntemplate <typename Number, typename VariableName>\ninline linear_constraint<Number, VariableName>\noperator<(variable<Number, VariableName> x, int64_t n) {\n  return linear_constraint<Number, VariableName>(\n      x - n, linear_constraint<Number, VariableName>::STRICT_INEQUALITY);\n}\n\ntemplate <typename Number, typename VariableName>\ninline linear_constraint<Number, VariableName>\noperator<(Number n, variable<Number, VariableName> x) {\n  return linear_constraint<Number, VariableName>(\n      n - x, linear_constraint<Number, VariableName>::STRICT_INEQUALITY);\n}\n\ntemplate <typename Number, typename VariableName>\ninline linear_constraint<Number, VariableName>\noperator<(int64_t n, variable<Number, VariableName> x) {\n  return linear_constraint<Number, VariableName>(\n      n - x, linear_constraint<Number, VariableName>::STRICT_INEQUALITY);\n}\n\ntemplate <typename Number, typename VariableName>\ninline linear_constraint<Number, VariableName>\noperator<(variable<Number, VariableName> x, variable<Number, VariableName> y) {\n  return linear_constraint<Number, VariableName>(\n      x - y, linear_constraint<Number, VariableName>::STRICT_INEQUALITY);\n}\n\ntemplate <typename Number, typename VariableName>\ninline linear_constraint<Number, VariableName>\noperator<(const linear_expression<Number, VariableName> &e1,\n          const linear_expression<Number, VariableName> &e2) {\n  return linear_constraint<Number, VariableName>(\n      e1 - e2, linear_constraint<Number, VariableName>::STRICT_INEQUALITY);\n}\n\ntemplate <typename Number, typename VariableName>\ninline linear_constraint<Number, VariableName>\noperator>(const linear_expression<Number, VariableName> &e, Number n) {\n  return linear_constraint<Number, VariableName>(\n      n - e, linear_constraint<Number, VariableName>::STRICT_INEQUALITY);\n}\n\ntemplate <typename Number, typename VariableName>\ninline linear_constraint<Number, VariableName>\noperator>(const linear_expression<Number, VariableName> &e, int64_t n) {\n  return linear_constraint<Number, VariableName>(\n      n - e, linear_constraint<Number, VariableName>::STRICT_INEQUALITY);\n}\n\ntemplate <typename Number, typename VariableName>\ninline linear_constraint<Number, VariableName>\noperator>(Number n, const linear_expression<Number, VariableName> &e) {\n  return linear_constraint<Number, VariableName>(\n      e - n, linear_constraint<Number, VariableName>::STRICT_INEQUALITY);\n}\n\ntemplate <typename Number, typename VariableName>\ninline linear_constraint<Number, VariableName>\noperator>(int64_t n, const linear_expression<Number, VariableName> &e) {\n  return linear_constraint<Number, VariableName>(\n      e - n, linear_constraint<Number, VariableName>::STRICT_INEQUALITY);\n}\n\ntemplate <typename Number, typename VariableName>\ninline linear_constraint<Number, VariableName>\noperator>(const linear_expression<Number, VariableName> &e,\n          variable<Number, VariableName> x) {\n  return linear_constraint<Number, VariableName>(\n      x - e, linear_constraint<Number, VariableName>::STRICT_INEQUALITY);\n}\n\ntemplate <typename Number, typename VariableName>\ninline linear_constraint<Number, VariableName>\noperator>(variable<Number, VariableName> x,\n          const linear_expression<Number, VariableName> &e) {\n  return linear_constraint<Number, VariableName>(\n      e - x, linear_constraint<Number, VariableName>::STRICT_INEQUALITY);\n}\n\ntemplate <typename Number, typename VariableName>\ninline linear_constraint<Number, VariableName>\noperator>(variable<Number, VariableName> x, Number n) {\n  return linear_constraint<Number, VariableName>(\n      n - x, linear_constraint<Number, VariableName>::STRICT_INEQUALITY);\n}\n\ntemplate <typename Number, typename VariableName>\ninline linear_constraint<Number, VariableName>\noperator>(variable<Number, VariableName> x, int64_t n) {\n  return linear_constraint<Number, VariableName>(\n      n - x, linear_constraint<Number, VariableName>::STRICT_INEQUALITY);\n}\n\ntemplate <typename Number, typename VariableName>\ninline linear_constraint<Number, VariableName>\noperator>(Number n, variable<Number, VariableName> x) {\n  return linear_constraint<Number, VariableName>(\n      x - n, linear_constraint<Number, VariableName>::STRICT_INEQUALITY);\n}\n\ntemplate <typename Number, typename VariableName>\ninline linear_constraint<Number, VariableName>\noperator>(int64_t n, variable<Number, VariableName> x) {\n  return linear_constraint<Number, VariableName>(\n      x - n, linear_constraint<Number, VariableName>::STRICT_INEQUALITY);\n}\n\ntemplate <typename Number, typename VariableName>\ninline linear_constraint<Number, VariableName>\noperator>(variable<Number, VariableName> x, variable<Number, VariableName> y) {\n  return linear_constraint<Number, VariableName>(\n      y - x, linear_constraint<Number, VariableName>::STRICT_INEQUALITY);\n}\n\ntemplate <typename Number, typename VariableName>\ninline linear_constraint<Number, VariableName>\noperator>(const linear_expression<Number, VariableName> &e1,\n          const linear_expression<Number, VariableName> &e2) {\n  return linear_constraint<Number, VariableName>(\n      e2 - e1, linear_constraint<Number, VariableName>::STRICT_INEQUALITY);\n}\n\ntemplate <typename Number, typename VariableName>\ninline linear_constraint<Number, VariableName>\noperator==(const linear_expression<Number, VariableName> &e, Number n) {\n  return linear_constraint<Number, VariableName>(\n      e - n, linear_constraint<Number, VariableName>::EQUALITY);\n}\n\ntemplate <typename Number, typename VariableName>\ninline linear_constraint<Number, VariableName>\noperator==(const linear_expression<Number, VariableName> &e, int64_t n) {\n  return linear_constraint<Number, VariableName>(\n      e - n, linear_constraint<Number, VariableName>::EQUALITY);\n}\n\ntemplate <typename Number, typename VariableName>\ninline linear_constraint<Number, VariableName>\noperator==(Number n, const linear_expression<Number, VariableName> &e) {\n  return linear_constraint<Number, VariableName>(\n      e - n, linear_constraint<Number, VariableName>::EQUALITY);\n}\n\ntemplate <typename Number, typename VariableName>\ninline linear_constraint<Number, VariableName>\noperator==(int64_t n, const linear_expression<Number, VariableName> &e) {\n  return linear_constraint<Number, VariableName>(\n      e - n, linear_constraint<Number, VariableName>::EQUALITY);\n}\n\ntemplate <typename Number, typename VariableName>\ninline linear_constraint<Number, VariableName>\noperator==(const linear_expression<Number, VariableName> &e,\n           variable<Number, VariableName> x) {\n  return linear_constraint<Number, VariableName>(\n      e - x, linear_constraint<Number, VariableName>::EQUALITY);\n}\n\ntemplate <typename Number, typename VariableName>\ninline linear_constraint<Number, VariableName>\noperator==(variable<Number, VariableName> x,\n           const linear_expression<Number, VariableName> &e) {\n  return linear_constraint<Number, VariableName>(\n      e - x, linear_constraint<Number, VariableName>::EQUALITY);\n}\n\ntemplate <typename Number, typename VariableName>\ninline linear_constraint<Number, VariableName>\noperator==(variable<Number, VariableName> x, Number n) {\n  return linear_constraint<Number, VariableName>(\n      x - n, linear_constraint<Number, VariableName>::EQUALITY);\n}\n\ntemplate <typename Number, typename VariableName>\ninline linear_constraint<Number, VariableName>\noperator==(variable<Number, VariableName> x, int64_t n) {\n  return linear_constraint<Number, VariableName>(\n      x - n, linear_constraint<Number, VariableName>::EQUALITY);\n}\n\ntemplate <typename Number, typename VariableName>\ninline linear_constraint<Number, VariableName>\noperator==(Number n, variable<Number, VariableName> x) {\n  return linear_constraint<Number, VariableName>(\n      x - n, linear_constraint<Number, VariableName>::EQUALITY);\n}\n\ntemplate <typename Number, typename VariableName>\ninline linear_constraint<Number, VariableName>\noperator==(int64_t n, variable<Number, VariableName> x) {\n  return linear_constraint<Number, VariableName>(\n      x - n, linear_constraint<Number, VariableName>::EQUALITY);\n}\n\ntemplate <typename Number, typename VariableName>\ninline linear_constraint<Number, VariableName>\noperator==(variable<Number, VariableName> x, variable<Number, VariableName> y) {\n  return linear_constraint<Number, VariableName>(\n      x - y, linear_constraint<Number, VariableName>::EQUALITY);\n}\n\ntemplate <typename Number, typename VariableName>\ninline linear_constraint<Number, VariableName>\noperator==(const linear_expression<Number, VariableName> &e1,\n           const linear_expression<Number, VariableName> &e2) {\n  return linear_constraint<Number, VariableName>(\n      e1 - e2, linear_constraint<Number, VariableName>::EQUALITY);\n}\n\ntemplate <typename Number, typename VariableName>\ninline linear_constraint<Number, VariableName>\noperator!=(const linear_expression<Number, VariableName> &e, Number n) {\n  return linear_constraint<Number, VariableName>(\n      e - n, linear_constraint<Number, VariableName>::DISEQUATION);\n}\n\ntemplate <typename Number, typename VariableName>\ninline linear_constraint<Number, VariableName>\noperator!=(const linear_expression<Number, VariableName> &e, int64_t n) {\n  return linear_constraint<Number, VariableName>(\n      e - n, linear_constraint<Number, VariableName>::DISEQUATION);\n}\n\ntemplate <typename Number, typename VariableName>\ninline linear_constraint<Number, VariableName>\noperator!=(Number n, const linear_expression<Number, VariableName> &e) {\n  return linear_constraint<Number, VariableName>(\n      e - n, linear_constraint<Number, VariableName>::DISEQUATION);\n}\n\ntemplate <typename Number, typename VariableName>\ninline linear_constraint<Number, VariableName>\noperator!=(int64_t n, const linear_expression<Number, VariableName> &e) {\n  return linear_constraint<Number, VariableName>(\n      e - n, linear_constraint<Number, VariableName>::DISEQUATION);\n}\n\ntemplate <typename Number, typename VariableName>\ninline linear_constraint<Number, VariableName>\noperator!=(const linear_expression<Number, VariableName> &e,\n           variable<Number, VariableName> x) {\n  return linear_constraint<Number, VariableName>(\n      e - x, linear_constraint<Number, VariableName>::DISEQUATION);\n}\n\ntemplate <typename Number, typename VariableName>\ninline linear_constraint<Number, VariableName>\noperator!=(variable<Number, VariableName> x,\n           const linear_expression<Number, VariableName> &e) {\n  return linear_constraint<Number, VariableName>(\n      e - x, linear_constraint<Number, VariableName>::DISEQUATION);\n}\n\ntemplate <typename Number, typename VariableName>\ninline linear_constraint<Number, VariableName>\noperator!=(variable<Number, VariableName> x, Number n) {\n  return linear_constraint<Number, VariableName>(\n      x - n, linear_constraint<Number, VariableName>::DISEQUATION);\n}\n\ntemplate <typename Number, typename VariableName>\ninline linear_constraint<Number, VariableName>\noperator!=(variable<Number, VariableName> x, int64_t n) {\n  return linear_constraint<Number, VariableName>(\n      x - n, linear_constraint<Number, VariableName>::DISEQUATION);\n}\n\ntemplate <typename Number, typename VariableName>\ninline linear_constraint<Number, VariableName>\noperator!=(Number n, variable<Number, VariableName> x) {\n  return linear_constraint<Number, VariableName>(\n      x - n, linear_constraint<Number, VariableName>::DISEQUATION);\n}\n\ntemplate <typename Number, typename VariableName>\ninline linear_constraint<Number, VariableName>\noperator!=(int64_t n, variable<Number, VariableName> x) {\n  return linear_constraint<Number, VariableName>(\n      x - n, linear_constraint<Number, VariableName>::DISEQUATION);\n}\n\ntemplate <typename Number, typename VariableName>\ninline linear_constraint<Number, VariableName>\noperator!=(variable<Number, VariableName> x, variable<Number, VariableName> y) {\n  return linear_constraint<Number, VariableName>(\n      x - y, linear_constraint<Number, VariableName>::DISEQUATION);\n}\n\ntemplate <typename Number, typename VariableName>\ninline linear_constraint<Number, VariableName>\noperator!=(const linear_expression<Number, VariableName> &e1,\n           const linear_expression<Number, VariableName> &e2) {\n  return linear_constraint<Number, VariableName>(\n      e1 - e2, linear_constraint<Number, VariableName>::DISEQUATION);\n}\n\n/* used by boost::hash_combine */\ntemplate <typename Number, typename VariableName>\ninline std::size_t\nhash_value(const linear_constraint<Number, VariableName> &c) {\n  return c.hash();\n}\n\ntemplate <typename Number, typename VariableName>\nstruct linear_constraint_hasher {\n  size_t operator()(const linear_constraint<Number, VariableName> &c) const {\n    return c.hash();\n  }\n};\n\ntemplate <typename Number, typename VariableName>\nstruct linear_constraint_equal {\n  bool operator()(const linear_constraint<Number, VariableName> &c1,\n                  const linear_constraint<Number, VariableName> &c2) const {\n    return c1.equal(c2);\n  }\n};\n\ntemplate <typename Number, typename VariableName>\nusing linear_constraint_unordered_set =\n    std::unordered_set<linear_constraint<Number, VariableName>,\n                       linear_constraint_hasher<Number, VariableName>,\n                       linear_constraint_equal<Number, VariableName>>;\n\ntemplate <typename Number, typename VariableName, typename Value>\nusing linear_constraint_unordered_map =\n    std::unordered_map<linear_constraint<Number, VariableName>, Value,\n                       linear_constraint_hasher<Number, VariableName>,\n                       linear_constraint_equal<Number, VariableName>>;\n\ntemplate <typename Number, typename VariableName>\nclass linear_constraint_system {\n\npublic:\n  typedef Number number_t;\n  typedef VariableName varname_t;\n  typedef linear_expression<Number, VariableName> linear_expression_t;\n  typedef linear_constraint<Number, VariableName> linear_constraint_t;\n  typedef linear_constraint_system<Number, VariableName>\n      linear_constraint_system_t;\n  typedef variable<Number, VariableName> variable_t;\n  typedef patricia_tree_set<variable_t> variable_set_t;\n\nprivate:\n  typedef std::vector<linear_constraint_t> cst_collection_t;\n\npublic:\n  typedef typename cst_collection_t::iterator iterator;\n  typedef typename cst_collection_t::const_iterator const_iterator;\n\nprivate:\n  cst_collection_t _csts;\n\npublic:\n  linear_constraint_system() {}\n\n  linear_constraint_system(const linear_constraint_t &cst) {\n    _csts.push_back(cst);\n  }\n\n  linear_constraint_system(const linear_constraint_system_t &o) = default;\n\n  linear_constraint_system(linear_constraint_system_t &&o) = default;\n\n  linear_constraint_system_t &operator=(const linear_constraint_system_t &o) = default;\n  \n  linear_constraint_system_t &operator=(linear_constraint_system_t &&o) = default;\n  \n  linear_constraint_system_t &operator+=(const linear_constraint_t &c) {\n    if (!std::any_of(\n            _csts.begin(), _csts.end(),\n            [c](const linear_constraint_t &c1) { return c1.equal(c); })) {\n      _csts.push_back(c);\n    }\n    return *this;\n  }\n\n  linear_constraint_system_t &operator+=(const linear_constraint_system_t &s) {\n    for (auto c : s) {\n      if (!std::any_of(\n              _csts.begin(), _csts.end(),\n              [c](const linear_constraint_t &c1) { return c1.equal(c); })) {\n        _csts.push_back(c);\n      }\n    }\n    return *this;\n  }\n\n  linear_constraint_system_t\n  operator+(const linear_constraint_system_t &s) const {\n    linear_constraint_system_t r;\n    r.operator+=(s);\n    r.operator+=(*this);\n    return r;\n  }\n\n  /**\n     Replace pairs e<=0 and -e<=0 with e==0\n  **/\n  linear_constraint_system_t normalize() const {\n    linear_expression_unordered_set<number_t, varname_t> expr_set;\n    linear_expression_unordered_map<number_t, varname_t, unsigned> index_map;\n    std::vector<bool> toremove(_csts.size(), false); // indexes to be removed\n    linear_constraint_system_t out;\n\n    for (unsigned i = 0, e = _csts.size(); i < e; ++i) {\n      if (_csts[i].is_inequality()) {\n        linear_expression_t exp = _csts[i].expression();\n        if (expr_set.find(-exp) == expr_set.end()) {\n          // remember the index and the expression\n          index_map.insert({exp, i});\n          expr_set.insert(exp);\n        } else {\n          // we found exp<=0 and -exp<= 0\n          unsigned j = index_map[-exp];\n          if (_csts[i].is_signed() == _csts[j].is_signed()) {\n            toremove[i] = true;\n            toremove[j] = true;\n            bool insert_pos = true;\n            if (exp.size() == 1 && (*(exp.begin())).first < 0) {\n              // unary equality: we choose the one with the positive position.\n              insert_pos = false;\n            }\n            if (!insert_pos) {\n              out += linear_constraint_t(-exp, linear_constraint_t::EQUALITY);\n            } else {\n              out += linear_constraint_t(exp, linear_constraint_t::EQUALITY);\n            }\n          }\n        }\n      }\n    }\n\n    for (unsigned i = 0, e = _csts.size(); i < e; ++i) {\n      if (!toremove[i]) {\n        out += _csts[i];\n      }\n    }\n\n    return out;\n  }\n\n  const_iterator begin() const { return _csts.begin(); }\n\n  const_iterator end() const { return _csts.end(); }\n\n  iterator begin() { return _csts.begin(); }\n\n  iterator end() { return _csts.end(); }\n\n  variable_set_t variables() const {\n    variable_set_t variables;\n    for (auto c : *this)\n      variables |= c.variables();\n    return variables;\n  }\n\n  // TODO: expensive linear operation.\n  // XXX: We can keep track of whether the system is false in an\n  // incremental manner.\n  bool is_false() const {\n    if (_csts.empty())\n      return false; // empty is considered true\n\n    for (auto it = this->begin(); it != this->end(); ++it) {\n      auto c = *it;\n      if (!c.is_contradiction()) {\n        return false;\n      }\n    }\n    return true; // all constraints are false\n  }\n\n  bool is_true() const { return _csts.empty(); }\n\n  std::size_t size() const { return _csts.size(); }\n\n  void write(crab::crab_os &o) const {\n    o << \"{\";\n    for (const_iterator it = this->begin(); it != this->end();) {\n      auto c = *it;\n      o << c;\n      ++it;\n      if (it != end()) {\n        o << \"; \";\n      }\n    }\n    o << \"}\";\n  }\n\n  // for dgb\n  void dump() { write(crab::outs()); }\n\n  std::string get_string(){\n    crab::crab_string_os ss;\n    write(ss);\n    return ss.str();\n  }\n\n}; // class linear_constraint_system\n\ntemplate <typename Number, typename VariableName>\ninline crab::crab_os &\noperator<<(crab::crab_os &o,\n           const linear_constraint_system<Number, VariableName> &sys) {\n  sys.write(o);\n  return o;\n}\n\n// This class contains a disjunction of linear constraints (i.e., DNF form)\ntemplate <typename Number, typename VariableName>\nclass disjunctive_linear_constraint_system {\n\npublic:\n  typedef Number number_t;\n  typedef VariableName varname_t;\n  typedef linear_constraint<Number, VariableName> linear_constraint_t;\n  typedef linear_constraint_system<Number, VariableName>\n      linear_constraint_system_t;\n  typedef disjunctive_linear_constraint_system<Number, VariableName> this_type;\n\nprivate:\n  typedef std::vector<linear_constraint_system_t> cst_collection_t;\n  cst_collection_t _csts;\n  bool _is_false;\n\npublic:\n  typedef typename cst_collection_t::iterator iterator;\n  typedef typename cst_collection_t::const_iterator const_iterator;\n\n  disjunctive_linear_constraint_system(bool is_false = false)\n      : _is_false(is_false) {}\n\n  explicit disjunctive_linear_constraint_system(\n      const linear_constraint_system_t &cst)\n      : _is_false(false) {\n    if (cst.is_false()) {\n      _is_false = true;\n    } else {\n      _csts.push_back(cst);\n    }\n  }\n\n  disjunctive_linear_constraint_system(const this_type &o) = default;\n\n  disjunctive_linear_constraint_system(this_type &&o) = default;\n\n  this_type &operator=(const this_type &o) = default;\n\n  this_type &operator=(this_type &&o) = default;\n\n\n  bool is_false() const { return _is_false; }\n\n  bool is_true() const { return (!is_false() && _csts.empty()); }\n\n  // make true\n  void clear() {\n    _is_false = false;\n    _csts.clear();\n  }\n\n  /*\n    c1 or ... or cn  += true  ==> error\n    c1 or ... or cn  += false ==> c1 or .. or cn\n    c1 or ... or cn  += c     ==> c1 or ... or cn or c\n  */\n  this_type &operator+=(const linear_constraint_system_t &cst) {\n    if (cst.is_true()) {\n      // adding true should make the whole thing true\n      // but we prefer to raise an error for now.\n      CRAB_ERROR(\"Disjunctive linear constraint: cannot add true\");\n    }\n\n    if (!cst.is_false()) {\n      _csts.push_back(cst);\n      _is_false = false;\n    }\n    return *this;\n  }\n\n  /*\n    c1 or ... or cn  += true  ==> error\n    c1 or ... or cn  += false ==> c1 or .. or cn\n    c1 or ... or cn  += d1 or ... or dn   ==> c1 or ... or cn or d1 or ... or dn\n  */\n  this_type &operator+=(const this_type &s) {\n    if (s.is_true()) {\n      // adding true should make the whole thing true\n      // but we prefer to raise an error for now.\n      CRAB_ERROR(\"Disjunctive linear constraint: cannot add true\");\n    }\n    if (!s.is_false()) {\n      for (const linear_constraint_system_t &c : s) {\n        this->operator+=(c);\n      }\n    }\n    return *this;\n  }\n\n  this_type operator+(const this_type &s) const {\n    this_type r;\n    r.operator+=(s);\n    r.operator+=(*this);\n    return r;\n  }\n\n  // To enumerate all the conjunctions\n  const_iterator begin() const {\n    if (is_false())\n      CRAB_ERROR(\n          \"Disjunctive Linear constraint: trying to call begin() when false\");\n    return _csts.begin();\n  }\n\n  const_iterator end() const {\n    if (is_false())\n      CRAB_ERROR(\n          \"Disjunctive Linear constraint: trying to call end() when false\");\n    return _csts.end();\n  }\n\n  iterator begin() {\n    if (is_false())\n      CRAB_ERROR(\n          \"Disjunctive Linear constraint: trying to call begin() when false\");\n    return _csts.begin();\n  }\n\n  iterator end() {\n    if (is_false())\n      CRAB_ERROR(\n          \"Disjunctive Linear constraint: trying to call end() when false\");\n    return _csts.end();\n  }\n\n  // Return the number of conjunctions\n  std::size_t size() const { return _csts.size(); }\n\n  void write(crab::crab_os &o) const {\n    if (is_false()) {\n      o << \"_|_\";\n    } else if (is_true()) {\n      o << \"{}\";\n    } else if (size() == 1) {\n      o << _csts[0];\n    } else {\n      assert(size() > 1);\n      for (const_iterator it = this->begin(); it != this->end();) {\n        auto c = *it;\n        o << c;\n        ++it;\n        if (it != end()) {\n          o << \" or \\n\";\n        }\n      }\n    }\n  }\n\n  std::string get_string(){\n    crab::crab_string_os ss;\n    write(ss);\n    return ss.str();\n  }\n};\n\ntemplate <typename Number, typename VariableName>\ninline crab::crab_os &operator<<(\n    crab::crab_os &o,\n    const disjunctive_linear_constraint_system<Number, VariableName> &sys) {\n  sys.write(o);\n  return o;\n}\n\n} // namespace ikos\n\nnamespace std {\n/**  specialization of std::hash for linear expressions and constraints **/\ntemplate <typename Number, typename VariableName>\nstruct hash<ikos::linear_expression<Number, VariableName>> {\n  using linear_expression_t = ikos::linear_expression<Number, VariableName>;\n  size_t operator()(const linear_expression_t &e) const { return e.hash(); }\n};\n\ntemplate <typename Number, typename VariableName>\nstruct hash<ikos::linear_constraint<Number, VariableName>> {\n  using linear_constraint_t = ikos::linear_constraint<Number, VariableName>;\n  size_t operator()(const linear_constraint_t &c) const { return c.hash(); }\n};\n\n} // end namespace std\n", "meta": {"hexsha": "289c71fa2648f5747f9a512c9d6009465d11f4ef", "size": 59584, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/crab/domains/linear_constraints.hpp", "max_stars_repo_name": "yugeshk/crab", "max_stars_repo_head_hexsha": "4a266d8ccde170d60573076fa12645f6c29a887f", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2021-05-19T17:35:30.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-17T04:03:21.000Z", "max_issues_repo_path": "include/crab/domains/linear_constraints.hpp", "max_issues_repo_name": "yugeshk/crab", "max_issues_repo_head_hexsha": "4a266d8ccde170d60573076fa12645f6c29a887f", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/crab/domains/linear_constraints.hpp", "max_forks_repo_name": "yugeshk/crab", "max_forks_repo_head_hexsha": "4a266d8ccde170d60573076fa12645f6c29a887f", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-01-15T11:20:30.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-15T11:20:30.000Z", "avg_line_length": 33.950997151, "max_line_length": 87, "alphanum_fraction": 0.7079417293, "num_tokens": 14334, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5851011397337391, "lm_q2_score": 0.5467381519846138, "lm_q1q2_score": 0.31989711586211583}}
{"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_DMAT_MULT_INCLUDE\n#define MTL_SMAT_DMAT_MULT_INCLUDE\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/concept/collection.hpp>\n#include <boost/numeric/mtl/utility/tag.hpp>\n#include <boost/numeric/mtl/utility/category.hpp>\n#include <boost/numeric/mtl/utility/flatcat.hpp>\n#include <boost/numeric/meta_math/loop1.hpp>\n#include <boost/numeric/mtl/interface/vpt.hpp>\n\n\nnamespace mtl { namespace functor {\n\ntemplate <typename Assign= assign::assign_sum,\n\t  typename Backup= no_op>     // To allow 2nd parameter, is ignored\nstruct gen_smat_dmat_mult\n{\n    template <typename MatrixA, typename MatrixB, typename MatrixC>\n    void operator()(MatrixA const& a, MatrixB const& b, MatrixC& c)\n    {\n\tvampir_trace<4018> tracer;\n\tapply(a, b, c, typename OrientedCollection<MatrixA>::orientation());\n    }\n\nprivate:\n    template <typename MatrixA, typename MatrixB, typename MatrixC>\n    void apply(MatrixA const& a, MatrixB const& b, MatrixC& c, tag::row_major)\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         \n        typedef typename range_generator<nz, a_cur_type>::type     a_icur_type;            \n        typedef typename range_generator<all, b_cur_type>::type    b_icur_type;          \n        typedef typename range_generator<iter::all, c_cur_type>::type    c_icur_type;            \n\n\ttypename traits::col<MatrixA>::type             col_a(a); \n\ttypename traits::const_value<MatrixA>::type     value_a(a); \n\ttypename traits::const_value<MatrixB>::type     value_b(b); \n\n\tif (Assign::init_to_zero) set_to_zero(c);\n\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\n\t    b_cur_type bc= begin<col>(b), bend= end<col>(b);\n\t    for (c_icur_type cic= begin<iter::all>(cc); bc != bend; ++bc, ++cic) { \n\t\t    \n\t\ttypename MatrixC::value_type c_tmp(*cic);\n\t\tfor (a_icur_type aic= begin<nz>(ac), aiend= end<nz>(ac); aic != aiend; ++aic) {\n\n\t\t    typename Collection<MatrixA>::size_type     ca= col_a(*aic);   // column of non-zero\n\n\t\t    b_icur_type bic= begin<all>(bc);\n\t\t    bic+= ca;\n\t\t    Assign::update(c_tmp, value_a(*aic) * value_b(*bic));\n\t\t}\n\t\t*cic= c_tmp;\n\t    }\n\t}\n    }\n\n\n    template <typename MatrixA, typename MatrixB, typename MatrixC>\n    void apply(MatrixA const& a, MatrixB const& b, MatrixC& c, tag::col_major)\n    {\n\tusing namespace tag;\n\tusing traits::range_generator;  \n        typedef typename range_generator<col, MatrixA>::type       a_cur_type;             \n        typedef typename range_generator<nz, a_cur_type>::type     a_icur_type;            \n\n\ttypename traits::row<MatrixA>::type             row_a(a); \n\ttypename traits::const_value<MatrixA>::type     value_a(a); \n\n\tif (Assign::init_to_zero) set_to_zero(c);\n\n\tunsigned rb= 0; // traverse all rows of b\n\tfor (a_cur_type ac= begin<col>(a), aend= end<col>(a); ac != aend; ++ac, ++rb)\n\t    for (a_icur_type aic= begin<nz>(ac), aiend= end<nz>(ac); aic != aiend; ++aic) {\n\t\ttypename Collection<MatrixA>::size_type     ra= row_a(*aic);   // row in A and C\n\t\ttypename Collection<MatrixA>::value_type    va= value_a(*aic); // value of non-zero\n\n\t\tfor (unsigned cb= 0; cb < num_cols(b); ++cb) // column in B and C\n\t\t    Assign::update(c(ra, cb), va * b(rb, cb));\n\t    }\n    }\n};\n\n\n// =======================\n// Unrolled \n// required has_2D_layout\n// =======================\n\n// Define defaults if not yet given as Compiler flag\n#ifndef MTL_SMAT_DMAT_MULT_TILING1\n#  define MTL_SMAT_DMAT_MULT_TILING1 8\n#endif\n\ntemplate <unsigned long Index0, unsigned long Max0, typename Assign>\nstruct gen_tiling_smat_dmat_mult_block\n    : public meta_math::loop1<Index0, Max0>\n{\n    typedef meta_math::loop1<Index0, Max0>                                    base;\n    typedef gen_tiling_smat_dmat_mult_block<base::next_index0, Max0, Assign>  next_t;\n\n    template <typename Value, typename ValueA, typename ValueB, typename Size>\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     const ValueA& va, ValueB *begin_b, const Size& bci)\n    {\n\ttmp00+= va * *(begin_b + base::index0 * 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      va, 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, k + base::index0), 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\t\n\ntemplate <unsigned long Max0, typename Assign>\nstruct gen_tiling_smat_dmat_mult_block<Max0, Max0, Assign>\n    : public meta_math::loop1<Max0, Max0>\n{\n    typedef meta_math::loop1<Max0, Max0>                                    base;\n\n    template <typename Value, typename ValueA, typename ValueB, typename Size>\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     const ValueA& va, ValueB *begin_b, const Size& bci)\n    {\n\ttmp00+= va * *(begin_b + base::index0 * 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, k + base::index0), tmp00);\n    }\n};\n\n\ntemplate <unsigned long Tiling1= MTL_SMAT_DMAT_MULT_TILING1,\n\t  typename Assign= assign::assign_sum,\n\t  typename Backup= gen_smat_dmat_mult<Assign> >\nstruct gen_tiling_smat_dmat_mult\n{\n    template <typename MatrixA, typename MatrixB, typename MatrixC>\n    void operator()(MatrixA const& a, MatrixB const& b, MatrixC& c)\n    {\n    vampir_trace<4019> tracer;\n\tapply(a, b, c, traits::layout_flatcat<MatrixC>());\n    }\n\nprivate:\n    template <typename MatrixA, typename MatrixB, typename MatrixC>\n    void apply(MatrixA const& a, MatrixB const& b, MatrixC& c, tag::universe)\n    {\n\tBackup()(a, b, c);\n    }\n\n    template <typename MatrixA, typename MatrixB, typename MatrixC>\n    void apply(MatrixA const& a, MatrixB const& b, MatrixC& c, tag::flat<tag::has_2D_layout>)\n    {\n\tapply2(a, b, c, typename OrientedCollection<MatrixA>::orientation());\n    }\n\n    template <typename MatrixA, typename MatrixB, typename MatrixC>\n    void apply2(MatrixA const& a, MatrixB const& b, MatrixC& c, tag::col_major)\n    {\n\t// may be I'll write an optimized version later\n\tBackup()(a, b, c);\n    }\n\n\n    template <typename MatrixA, typename MatrixB, typename MatrixC>\n    void apply2(MatrixA const& a, MatrixB const& b, MatrixC& c, tag::row_major)\n    {\n\tusing namespace tag;\n\tusing traits::range_generator;  \n\n\ttypedef gen_tiling_smat_dmat_mult_block<1, Tiling1, Assign>  block;\n\ttypedef typename Collection<MatrixA>::size_type              size_type;\n\ttypedef typename Collection<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        typedef typename range_generator<row, MatrixA>::type         a_cur_type;             \n        typedef typename range_generator<nz, a_cur_type>::type       a_icur_type;            \n\n\ttypename traits::col<MatrixA>::type             col_a(a); \n\ttypename traits::const_value<MatrixA>::type     value_a(a); \n\n\tif (Assign::init_to_zero) set_to_zero(c);\n\n\tsize_type i_max= num_cols(b), i_block= Tiling1 * (i_max / Tiling1);\n\tsize_t bci= i_max > 1 ? &b(0, 1) - &b(0, 0) : 1; // offset of incrementing B's column if more than 1 column\n\n\tsize_type rc= 0; // start in row 0\n\tfor (a_cur_type ac= begin<row>(a), aend= end<row>(a); ac != aend; ++ac, ++rc) {\n\n\t    for (size_type i= 0; i < i_block; i+= Tiling1) {\n\t    \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\n\t\tfor (a_icur_type aic= begin<nz>(ac), aiend= end<nz>(ac); aic != aiend; ++aic) {\n\t\t    typename Collection<MatrixA>::size_type     ca= col_a(*aic);   // column of non-zero\n\t\t    typename Collection<MatrixA>::value_type    va= value_a(*aic); // value of non-zero\n\n\t\t    // Element in first vector in block to be multiplied with va; rb==ca\n\t\t    const typename MatrixB::value_type *begin_b= &b(ca, i); \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 va, begin_b, bci); \n\t\t}\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, rc, i);\n\t    }\t\n\n\t    for (size_type i= i_block; i < i_max; i++) {\n\t\tvalue_type tmp00= z;\n\t\tfor (a_icur_type aic= begin<nz>(ac), aiend= end<nz>(ac); aic != aiend; ++aic) {\n\t\t    typename Collection<MatrixA>::size_type     ca= col_a(aic);   // column of non-zero\n\t\t    tmp00+= value_a(*aic) * b(ca, i);\n\t\t}\n\t\tAssign::update(c(rc, i), tmp00);\n\t    }\n\t}\n    }\n};\n\n\n\n\n}} // namespace mtl::functor\n\n#endif // MTL_SMAT_DMAT_MULT_INCLUDE\n", "meta": {"hexsha": "9c8c00aa8978bd31b0d71d9691674dff15a43f74", "size": 10472, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/numeric/mtl/operation/smat_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": "lib/mtl4/boost/numeric/mtl/operation/smat_dmat_mult.hpp", "max_issues_repo_name": "spraetor/amdis2", "max_issues_repo_head_hexsha": "53c45c81a65752a8fafbb54f9ae6724a86639dcd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-04-17T12:35:32.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-03T15:46:25.000Z", "max_forks_repo_path": "lib/mtl4/boost/numeric/mtl/operation/smat_dmat_mult.hpp", "max_forks_repo_name": "spraetor/amdis2", "max_forks_repo_head_hexsha": "53c45c81a65752a8fafbb54f9ae6724a86639dcd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2019-12-01T13:40:30.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-14T08:39:54.000Z", "avg_line_length": 38.5, "max_line_length": 108, "alphanum_fraction": 0.6488731856, "num_tokens": 3081, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.585101139733739, "lm_q2_score": 0.5467381519846138, "lm_q1q2_score": 0.3198971158621158}}
{"text": "//=============================================================================\n//\n//  CLASS NConstraintInterfaceADOLC\n//\n//=============================================================================\n\n#ifndef COMISO_NCONSTRAINTINTERFACEADOLC_HH\n#define COMISO_NCONSTRAINTINTERFACEADOLC_HH\n\n//== COMPILE-TIME PACKAGE REQUIREMENTS ========================================\n#include <CoMISo/Config/config.hh>\n#if COMISO_ADOLC_AVAILABLE\n#if COMISO_EIGEN3_AVAILABLE\n\n//== INCLUDES =================================================================\n\n#include <CoMISo/Config/CoMISoDefines.hh>\n#include \"SuperSparseMatrixT.hh\"\n\n#include <adolc/adolc.h>\n#include <adolc/adouble.h>\n#include <adolc/drivers/drivers.h>\n#include <adolc/sparse/sparsedrivers.h>\n#include <adolc/taping.h>\n\n#include \"NConstraintInterface.hh\"\n\n#include \"TapeIDSingleton.hh\"\n\n#define EIGEN_YES_I_KNOW_SPARSE_MODULE_IS_NOT_STABLE_YET\n#include <Eigen/Sparse>\n\n//== FORWARDDECLARATIONS ======================================================\n\n//== NAMESPACES ===============================================================\n\nnamespace COMISO {\n\n//== CLASS DEFINITION =========================================================\n\n/** \\class NProblemInterfaceADOLC NProblemInterfaceADOLC.hpp\n\n    The problem interface using automatic differentiation.\n */\nclass COMISODLLEXPORT NConstraintInterfaceADOLC : public NConstraintInterface {\npublic:\n\n    // Define Sparse Datatypes\n    typedef NConstraintInterface::SVectorNC SVectorNC;\n    typedef NConstraintInterface::SMatrixNC SMatrixNC;\n\n    typedef NConstraintInterface::ConstraintType ConstraintType;\n\n    /// Default constructor\n    NConstraintInterfaceADOLC(int _n_unknowns,\n    \t\tconst ConstraintType _type = NC_EQUAL,\n    \t\tdouble _eps = 1e-6) :\n        NConstraintInterface(_type, _eps),\n        n_unknowns_(_n_unknowns),\n        tape_available_(false),\n        use_tape_(true),\n        tape_(static_cast<short int>(TapeIDSingleton::Instance()->requestId())),\n        dense_hessian_(NULL),\n        sparse_nz_(0),\n\t\tsparse_r_ind_p_(NULL),\n\t\tsparse_c_ind_p_(NULL),\n\t\tsparse_val_p_(NULL) {\n\n    }\n\n    /// Destructor\n    virtual ~NConstraintInterfaceADOLC() {\n\n    \tcleanup_sparse_hessian();\n\n        TapeIDSingleton::Instance()->releaseId(static_cast<size_t>(tape_));\n    }\n\n    /**\n     * \\brief Only override this function\n     */\n    virtual adouble eval_c_adouble(const adouble* _x) = 0;\n\npublic:\n\n    virtual int n_unknowns() {\n        return n_unknowns_;\n    }\n\n    virtual double eval_constraint(const double* _x) {\n\n        double y = 0.0;\n\n        if(!tape_available_ || !use_tape_) {\n\n        \tadouble y_d = 0.0;\n\n//        \tif(active_vars_.get() == NULL)\n//        \t\tactive_vars_.reset(new adouble[n_unknowns_]);\n\n        \tadouble* xa = new adouble[n_unknowns_];\n\n\t\t\ttrace_on(tape_); // Start taping\n\n\t\t\t// Fill data vector\n\t\t\tfor(int i = 0; i < n_unknowns_; ++i)\n\t\t\t\txa[i] <<= _x[i];\n\n\t\t\t// Call virtual function to compute\n\t\t\t// functional value\n\t\t\ty_d = eval_c_adouble(xa);\n\n\t\t\ty_d >>= y;\n\n\t\t\ttrace_off();\n\n#ifdef ADOLC_STATS\n\t\t\tprint_stats();\n#endif\n\n\t\t\tdelete[] xa;\n\n\t\t\ttape_available_ = true;\n\n        } else {\n\n        \tint ec = function(tape_, 1, n_unknowns_, const_cast<double*>(_x), &y);\n\n#ifdef ADOLC_RET_CODES\n\t\t\tstd::cout << \"Info: function() returned code \" << ec << std::endl;\n#endif\n\n\t\t\t// tape not valid anymore? retape and evaluate again\n\t\t\tif(ec < 0)\n\t\t\t{\n\t\t\t  tape_available_ = false;\n\t\t\t  return eval_constraint(_x);\n\t\t\t}\n        }\n\n        return y;\n    }\n\n    virtual void eval_gradient(const double* _x, SVectorNC& _g) {\n\n        if(!tape_available_ || !use_tape_) {\n\n        \t// Evaluate original functional\n            eval_constraint(_x);\n        }\n\n//        if(gradient_.get() == NULL)\n//        \tgradient_.reset(new double[n_unknowns_]);\n\n        double* grad_p = new double[n_unknowns_];\n\n        _g.resize(n_unknowns_);\n        _g.setZero();\n\n        // Evaluate gradient\n\t\tint ec = gradient(tape_, n_unknowns_, _x, grad_p);\n\n\t\t// Check if retaping is required\n\t\tif(ec < 0)\n\t\t{\n#ifdef ADOLC_RET_CODES\n\t\t\tstd::cout << __FUNCTION__ << \" invokes retaping of function due to discontinuity! Return code: \" << ec << std::endl;\n#endif\n\n\t\t\ttape_available_ = false;\n\t\t\teval_gradient(_x,_g);\n\t\t}\n\n#ifdef ADOLC_RET_CODES\n        std::cout << \"Info: gradient() returned code \" << ec << std::endl;\n#endif\n\n        for(int i = 0; i < n_unknowns_; ++i) {\n            _g.coeffRef(i) += grad_p[i];\n        }\n\n        delete[] grad_p;\n    }\n\n    virtual void eval_hessian(const double* _x, SMatrixNC& _H) {\n\n        _H.resize(n_unknowns_, n_unknowns_);\n\n        // tape update required?\n\t\tif (!tape_available_ || !use_tape_)\n\t\t\teval_constraint(_x);\n\n\t\t/*\n\t\t * Hessian matrix is sparse\n\t\t */\n\t\tif(sparse_hessian()) {\n\n\t\t\tint opt[2] = {0, 0};\n\n\t\t\tbool sparsity_pattern_available = bool(sparse_r_ind_p_);\n\n\t\t\tint ec = sparse_hess(tape_, n_unknowns_,\n\t\t\t\t\tsparsity_pattern_available, _x, &sparse_nz_,\n\t\t\t\t\t&sparse_r_ind_p_, &sparse_c_ind_p_, &sparse_val_p_, opt);\n\n\t\t\tif (ec < 0) {\n#ifdef ADOLC_RET_CODES\n\t\t\t\tstd::cout << __FUNCTION__ << \" invokes retaping of function due to discontinuity! Return code: \" << ec << std::endl;\n#endif\n\t\t\t\t// Retape function if return code indicates discontinuity\n\t\t\t\ttape_available_ = false;\n\t\t\t\teval_constraint(_x);\n\t\t\t\tec = sparse_hess(tape_, n_unknowns_,\n\t\t\t\t\t\tsparsity_pattern_available, _x, &sparse_nz_,\n\t\t\t\t\t\t&sparse_r_ind_p_, &sparse_c_ind_p_, &sparse_val_p_,\topt);\n\t\t\t}\n\n\t\t\t// data should be available now\n\t\t\tassert(sparse_r_ind_p_ != NULL);\n\t\t\tassert(sparse_c_ind_p_ != NULL);\n\t\t\tassert(sparse_val_p_ != NULL);\n\n#ifdef ADOLC_RET_CODES\n\t\t\tstd::cout << \"Info: sparse_hessian() returned code \" << ec << std::endl;\n#endif\n\n\t\t\t// Store data\n\t\t\tfor (int i = 0; i < sparse_nz_; ++i) {\n\n\t\t\t\t_H(sparse_r_ind_p_[i], sparse_c_ind_p_[i]) = sparse_val_p_[i];\n\n\t\t\t\t// Provide also upper diagonal part?\n\t\t\t\tif (sparse_r_ind_p_[i] != sparse_c_ind_p_[i])\n\t\t\t\t\t_H(sparse_c_ind_p_[i], sparse_r_ind_p_[i]) = sparse_val_p_[i];\n\t\t\t}\n\n\t\t} else {\n\t\t\t/*\n\t\t\t * Hessian matrix is dense\n\t\t\t */\n\t\t\tallocate_dense_hessian();\n\n\t\t\tint ec = hessian(tape_, n_unknowns_, const_cast<double*>(_x),\n\t\t\t\t\tdense_hessian_);\n\n\t\t\tif (ec < 0) {\n#ifdef ADOLC_RET_CODES\n\t\t\t\tstd::cout << __FUNCTION__ << \" invokes retaping of function due to discontinuity! Return code: \" << ec << std::endl;\n#endif\n\t\t\t\t// Retape function if return code indicates discontinuity\n\t\t\t\ttape_available_ = false;\n\t\t\t\teval_constraint(_x);\n\t\t\t\tec = hessian(tape_, n_unknowns_, const_cast<double*>(_x),\n\t\t\t\t\t\tdense_hessian_);\n\t\t\t}\n\n#ifdef ADOLC_RET_CODES\n\t\t\tstd::cout << \"Info: hessian() returned code \" << ec << std::endl;\n#endif\n\n\t\t\tfor (int i = 0; i < n_unknowns_; ++i) {\n\t\t\t\t// Diagonal\n\t\t\t\t_H(i, i) = dense_hessian_[i][i];\n\t\t\t\tfor (int j = 0; j < i; ++j) {\n\t\t\t\t\t_H(i, j) = dense_hessian_[i][j];\n\t\t\t\t\t// Also store upper diagonal part\n\t\t\t\t\t_H(j, i) = dense_hessian_[i][j];\n\t\t\t\t}\n\t\t\t}\n\t\t}\n    }\n\n    /** \\brief Use tape\n     * Set this to false if the energy functional\n     * is discontinuous (so that the operator tree\n     * has to be re-established at each evaluation)\n     */\n    bool use_tape() const {\n        return use_tape_;\n    }\n\n    void use_tape(bool _b) {\n        use_tape_ = _b;\n    }\n\n    /**\n     * \\brief Provide information to make computations\n     * as efficient as possible.\n     */\n    virtual bool is_linear()         const { return false; }\n    virtual bool constant_gradient() const { return false; }\n\n    /**\n     * \\brief Indicate whether the hessian is sparse.\n     * If so, the computations (as well as the memory\n     * consumption) can be performed more efficiently.\n     */\n    virtual bool constant_hessian () const { return false;}\n\nprivate:\n\n\tvoid allocate_dense_hessian() {\n\t\tif (!dense_hessian_) {\n\t\t\tdense_hessian_ = new double*[n_unknowns_];\n\t\t\tfor (int i = 0; i < n_unknowns_; ++i)\n\t\t\t\tdense_hessian_[i] = new double[i + 1];\n\t\t}\n\n\t\t// store #unknowns to access in destructor\n\t\tsparse_nz_ = n_unknowns_;\n\t}\n\n\tvoid cleanup_dense_hessian() {\n\t\tif (dense_hessian_) {\n\t\t\tfor (int i = 0; i < sparse_nz_; ++i)\n\t\t\t\tdelete[] dense_hessian_[i];\n\n\t\t\tdelete[] dense_hessian_;\n\t\t}\n\t}\n\n\tvoid cleanup_sparse_hessian() {\n\n\t\tif (sparse_r_ind_p_ != NULL)\n\t\t\tdelete[] sparse_r_ind_p_;\n\t\tif (sparse_c_ind_p_ != NULL)\n\t\t\tdelete[] sparse_c_ind_p_;\n\t\tif (sparse_val_p_ != NULL)\n\t\t\tdelete[] sparse_val_p_;\n\t}\n\n    void print_stats() {\n\n    \tsize_t tape_stats[11];\n    \ttapestats(tape_, tape_stats);\n\t\tstd::cout << \"Status values for tape \" << tape_ << std::endl;\n\t\tstd::cout << \"===============================================\" << std::endl;\n\t\tstd::cout << \"Number of independent variables:\\t\" << tape_stats[0] << std::endl;\n\t\tstd::cout << \"Number of dependent variables:\\t\\t\" << tape_stats[1] << std::endl;\n\t\tstd::cout << \"Max. number of live active variables:\\t\" << tape_stats[2] << std::endl;\n\t\tstd::cout << \"Size of value stack:\\t\\t\\t\" << tape_stats[3] << std::endl;\n\t\tstd::cout << \"Buffer size:\\t\\t\\t\\t\" << tape_stats[4] << std::endl;\n\t\tstd::cout << \"Total number of operations recorded:\\t\" << tape_stats[5] << std::endl;\n\t\tstd::cout << \"Other stats [6]:\\t\\t\\t\" << tape_stats[6] << std::endl;\n\t\tstd::cout << \"Other stats [7]:\\t\\t\\t\" << tape_stats[7] << std::endl;\n\t\tstd::cout << \"Other stats [8]:\\t\\t\\t\" << tape_stats[8] << std::endl;\n\t\tstd::cout << \"Other stats [9]:\\t\\t\\t\" << tape_stats[9] << std::endl;\n\t\tstd::cout << \"Other stats [10]:\\t\\t\\t\" << tape_stats[10] << std::endl;\n\t\tstd::cout << \"===============================================\" << std::endl;\n    }\n\n    // Number of unknowns\n    int n_unknowns_;\n\n    bool tape_available_;\n    bool use_tape_;\n\n    SMatrixNC constant_hessian_;\n\n    const short int tape_;\n\n//    std::auto_ptr<adouble> active_vars_;\n//    std::auto_ptr<double> gradient_;\n\n    // dense hessian (if required)\n    double** dense_hessian_;\n\n    // Sparse hessian data\n\tint sparse_nz_;\n\tunsigned int* sparse_r_ind_p_;\n\tunsigned int* sparse_c_ind_p_;\n\tdouble* sparse_val_p_ ;\n};\n\n//=============================================================================\n}// namespace COMISO\n//=============================================================================\n#endif // COMISO_ADOLC_AVAILABLE\n//=============================================================================\n#endif // COMISO_EIGEN3_AVAILABLE\n//=============================================================================\n#endif // ACG_NCONSTRAINTINTERFACEAD_HH defined\n//=============================================================================\n\n", "meta": {"hexsha": "64041107847bbfa5b10b1242146bd77e68ec38e9", "size": 10468, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/libigl/external/CoMISo/NSolver/NConstraintInterfaceADOLC.hpp", "max_stars_repo_name": "josefgraus/self_similiarity", "max_stars_repo_head_hexsha": "c032daa3009f60fdc8a52c437a07c6e3ba2efe4b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 216.0, "max_stars_repo_stars_event_min_datetime": "2018-09-09T11:53:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-19T13:41:35.000Z", "max_issues_repo_path": "libigl/external/CoMISo/NSolver/NConstraintInterfaceADOLC.hpp", "max_issues_repo_name": "liminchen/DOT", "max_issues_repo_head_hexsha": "26525fba815fb081e90676321e42d0a60ecb0cb1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 13.0, "max_issues_repo_issues_event_min_datetime": "2018-10-23T08:29:09.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-08T06:45:34.000Z", "max_forks_repo_path": "ACAP_linux/3rd/CoMISo/NSolver/NConstraintInterfaceADOLC.hpp", "max_forks_repo_name": "shubhMaheshwari/Automatic-Unpaired-Shape-Deformation-Transfer", "max_forks_repo_head_hexsha": "8c9afe017769f9554706bcd267b6861c4c144999", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 41.0, "max_forks_repo_forks_event_min_datetime": "2018-09-13T08:50:41.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-23T00:33:54.000Z", "avg_line_length": 27.1896103896, "max_line_length": 120, "alphanum_fraction": 0.5888421857, "num_tokens": 2776, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6297746213017459, "lm_q2_score": 0.5078118642792044, "lm_q1q2_score": 0.31980702451896953}}
{"text": "//\n// Created by david on 6/7/2018.\n//\n\n#include <random>\n#include \"ImageGraph.h\"\n#include <boost/graph/boykov_kolmogorov_max_flow.hpp>\n#include \"graph_cut.h\"\n\n\nnamespace {\n    using namespace Gadgetron;\n    static std::mt19937 rng_state(4242);\n\n\n    template<unsigned int D>\n    void update_regularization_edge(ImageGraph<D> &graph, const hoNDArray<uint16_t> &field_map,\n                                    const hoNDArray<uint16_t> &proposed_field_map,\n                                    const hoNDArray<float> &second_deriv, const size_t idx, const size_t idx2,\n                                    const size_t edge_idx, float scaling) {\n\n        int f_value1 = field_map[idx];\n        int pf_value1 = proposed_field_map[idx];\n        int f_value2 = field_map[idx2];\n        int pf_value2 = proposed_field_map[idx2];\n        int a = std::norm(f_value1 - f_value2);\n        int b = std::norm(f_value1 - pf_value2);\n        int c = std::norm(pf_value1 - f_value2);\n        int d = std::norm(pf_value1 - pf_value2);\n\n        float weight = b + c - a - d;\n\n        assert(weight >= 0);\n        float lambda = std::max(std::min(second_deriv[idx], second_deriv[idx2]), 0.0f) * scaling;\n        weight *= lambda;\n\n        assert(lambda >= 0);\n\n        auto &capacity_map = graph.edge_capacity_map;\n\n        capacity_map[edge_idx] += weight;\n        {\n            float aq = lambda * (c - a);\n\n            if (aq > 0) {\n                capacity_map[graph.edge_from_source(idx)] += aq;\n\n            } else {\n                capacity_map[graph.edge_to_sink(idx)] -= aq;\n            }\n        }\n\n        {\n            float aj = lambda * (d - c);\n            if (aj > 0) {\n                capacity_map[graph.edge_from_source(idx2)] += aj;\n\n            } else {\n                capacity_map[graph.edge_to_sink(idx2)] -= aj;\n            }\n        }\n\n\n    }\n\n    template<unsigned int D>\n    ImageGraph<D> make_graph(const hoNDArray<uint16_t> &field_map, const hoNDArray<uint16_t> &proposed_field_map,\n                             const hoNDArray<float> &residual_diff_map, const hoNDArray<float> &second_deriv) {\n\n        const auto dims = vector_td<int,3>(field_map.get_size(0),field_map.get_size(1),field_map.get_size(2));\n\n        vector_td<int,D> graph_dims;\n        for (int i = 0; i < D; i++) graph_dims[i] = dims[i];\n\n        ImageGraph<D> graph = ImageGraph<D>(graph_dims);\n\n        auto &capacity_map = graph.edge_capacity_map;\n        //Add regularization edges\n\n        for (size_t kz = 0; kz < dims[2]; kz++) {\n            for (size_t ky = 0; ky < dims[1]; ky++) {\n                for (size_t kx = 0; kx < dims[0]; kx++) {\n                    size_t idx = kz*dims[1]*dims[0]+ky * dims[0] + kx;\n\n\n                    if (kx < (dims[0] - 1)) {\n                        size_t idx2 = idx + 1;\n\n                        update_regularization_edge(graph, field_map, proposed_field_map, second_deriv, idx, idx2,\n                                                   graph.edge(idx, idx2).first, 1);\n                    }\n\n\n                    if (ky < (dims[1] - 1)) {\n                        size_t idx2 = idx + dims[0];\n                        update_regularization_edge(graph, field_map, proposed_field_map, second_deriv, idx, idx2,\n                                                   graph.edge(idx, idx2).first, 1);\n                    }\n\n                    if (kz < (dims[2] - 1)) {\n                        size_t idx2 = idx + dims[0]*dims[1];\n                        update_regularization_edge(graph, field_map, proposed_field_map, second_deriv, idx, idx2,\n                                                   graph.edge(idx, idx2).first, 1);\n                    }\n\n                    float residual_diff = residual_diff_map[idx];\n\n                    if (residual_diff > 0) {\n                        capacity_map[graph.edge_to_sink(idx)] += int(residual_diff);\n\n                    } else {\n                        capacity_map[graph.edge_from_source(idx)] -= int(residual_diff);\n                    }\n\n                }\n            }\n        }\n\n        return graph;\n    }\n\n    template<unsigned int DIMS>\n    std::vector<boost::default_color_type>\n    graph_cut(const hoNDArray<uint16_t> &field_map_index, const hoNDArray<uint16_t> &proposed_field_map_index,\n              const hoNDArray<float> &lambda_map, const hoNDArray<float> &residual_diff_map) {\n\n        ImageGraph<DIMS> graph = make_graph<DIMS>(field_map_index, proposed_field_map_index, residual_diff_map,\n                                                  lambda_map);\n\n        float flow = boost::boykov_kolmogorov_max_flow(graph, graph.source_vertex, graph.sink_vertex);\n\n        return std::move(graph.color_map);\n    }\n\n}\nnamespace Gadgetron {\n\n\n    hoNDArray<uint16_t>\n    update_field_map(const hoNDArray<uint16_t> &field_map_index, const hoNDArray<uint16_t> &proposed_field_map_index,\n                     const hoNDArray<float> &residuals_map, const hoNDArray<float> &lambda_map) {\n\n\n        hoNDArray<float> residual_diff_map(field_map_index.dimensions());\n        const auto X = field_map_index.get_size(0);\n        const auto Y = field_map_index.get_size(1);\n        const auto Z = field_map_index.get_size(2);\n\n        for (size_t kz = 0; kz < Z; kz++) {\n            for (size_t ky = 0; ky < Y; ky++) {\n                for (size_t kx = 0; kx < X; kx++) {\n                    residual_diff_map(kx, ky,kz) = residuals_map(field_map_index(kx, ky,kz), kx, ky,kz) -\n                                                residuals_map(proposed_field_map_index(kx, ky,kz), kx, ky,kz);\n\n\n                }\n            }\n        }\n\n\n        std::vector<boost::default_color_type> color_map;\n        if (Z == 1) {\n            color_map = graph_cut<2>(field_map_index, proposed_field_map_index, lambda_map,\n                                     residual_diff_map);\n        } else {\n            color_map = graph_cut<3>(field_map_index, proposed_field_map_index, lambda_map, residual_diff_map);\n        }\n\n\n\n        auto result = field_map_index;\n        size_t updated_voxels = 0;\n        for (size_t i = 0; i < field_map_index.get_number_of_elements(); i++) {\n            if (color_map[i] != boost::default_color_type::black_color) {\n                updated_voxels++;\n                result[i] = proposed_field_map_index[i];\n            }\n        }\n\n        return result;\n\n    }\n\n}", "meta": {"hexsha": "a9d3b1613cd5d9302e417636763f3a6f34472c1b", "size": 6339, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "toolboxes/fatwater/graph_cut.cpp", "max_stars_repo_name": "roopchansinghv/gadgetron", "max_stars_repo_head_hexsha": "fb6c56b643911152c27834a754a7b6ee2dd912da", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-02-22T21:06:36.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-22T21:06:36.000Z", "max_issues_repo_path": "toolboxes/fatwater/graph_cut.cpp", "max_issues_repo_name": "apd47/gadgetron", "max_issues_repo_head_hexsha": "073e84dabe77d2dae3b3dd9aa4bf9edbf1f890f2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "toolboxes/fatwater/graph_cut.cpp", "max_forks_repo_name": "apd47/gadgetron", "max_forks_repo_head_hexsha": "073e84dabe77d2dae3b3dd9aa4bf9edbf1f890f2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.4510869565, "max_line_length": 117, "alphanum_fraction": 0.537624231, "num_tokens": 1506, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6548947425132315, "lm_q2_score": 0.4882833952958347, "lm_q1q2_score": 0.3197742284357521}}
{"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 * This file contains an example of graphlab used for discrete loopy\n * belief propagation in a pairwise markov random field to denoise a\n * synthetic noisy image.\n *\n *  \\author Joseph Gonzalez\n */\n\n// INCLUDES ===================================================================>\n\n// Including Standard Libraries\n#include <cstdlib>\n#include <cassert>\n#include <cstring>\n#include <fstream>\n#include <iostream>\n#include <vector>\n#include <string>\n#include <algorithm>\n#include <limits>\n#include <cmath>\n\n#include <boost/program_options.hpp>\n\n\n#include <graphlab.hpp>\n\n#include \"image.hpp\"\n\n\n// Include the macro for the for each operation\n#include <graphlab/macros_def.hpp>\n\n\n\n\n// STRUCTS (Edge and Vertex data) =============================================>\n\n/**\n * The data associated with each directed edge in the pairwise markov\n * random field\n */\nstruct edge_data {\n  graphlab::unary_factor message;\n  graphlab::unary_factor old_message;\n}; // End of edge data\n\n\n/**\n * The data associated with each variable in the pairwise markov\n * random field\n */\nstruct vertex_data {\n  graphlab::unary_factor potential;\n  graphlab::unary_factor belief;\n}; // End of vertex data\n\n\ntypedef graphlab::graph<vertex_data, edge_data> graph_type;\ntypedef graphlab::types<graph_type> gl_types;\n\ngl_types::glshared<graphlab::binary_factor> EDGE_FACTOR;\ngl_types::glshared<double> BOUND;\ngl_types::glshared<double> DAMPING;\n\n\n// GraphLab Update Function ===================================================>\n\n/** Construct denoising ising model based on the image */\nvoid construct_graph(image& img,\n                     size_t num_rings,\n                     double sigma,\n                     gl_types::graph& graph);\n\n/** \n * The core belief propagation update function.  This update satisfies\n * the graphlab update_function interface.  \n */\nvoid bp_update(gl_types::iscope& scope, \n               gl_types::icallback& scheduler);\n               \n\n// Command Line Parsing =======================================================>\n\nstruct options {\n  size_t ncpus;\n  double bound;\n  double damping;\n  size_t num_rings;\n  size_t rows;\n  size_t cols;\n  double sigma;\n  double lambda;\n  size_t splash_size;\n  std::string smoothing;\n  std::string engine;\n  std::string scope;\n  std::string scheduler;\n  std::string orig_fn;\n  std::string noisy_fn;\n  std::string pred_fn;\n  std::string pred_type;\n  std::string visualizer;\n  std::string partmethod;\n  size_t clustersize;\n};\n\n\n// MAIN =======================================================================>\nint main(int argc, char** argv) {\n  std::cout << \"This program creates and denoises a synthetic \" << std::endl\n            << \"image using loopy belief propagation inside \" << std::endl\n            << \"the graphlab framework.\" << std::endl;\n\n  // set the global logger\n  global_logger().set_log_level(LOG_WARNING);\n  global_logger().set_log_to_console(true);\n\n\n  double bound = 1E-4;\n  double damping = 0.1;\n  size_t colors = 5;\n  size_t rows = 200;\n  size_t cols = 200;\n  double sigma = 2;\n  double lambda = 2;\n  std::string smoothing = \"laplace\";\n  std::string orig_fn = \"source_img.pgm\";\n  std::string noisy_fn = \"noisy_img.pgm\";\n  std::string pred_fn = \"pred_img.pgm\";\n  std::string pred_type = \"map\";\n\n\n\n\n  // Parse command line arguments --------------------------------------------->\n  graphlab::command_line_options clopts(\"Loopy BP image denoising\");\n  clopts.attach_option(\"bound\",\n                       &bound, bound,\n                       \"Residual termination bound\");\n  clopts.attach_option(\"damping\",\n                       &damping, damping,\n                       \"The amount of message damping (higher = more damping)\");\n  clopts.attach_option(\"colors\",\n                       &colors, colors,\n                       \"The number of colors in the noisy image\");\n  clopts.attach_option(\"rows\",\n                       &rows, rows,\n                       \"The number of rows in the noisy image\");\n  clopts.attach_option(\"cols\",\n                       &cols, cols,\n                       \"The number of columns in the noisy image\");\n  clopts.attach_option(\"sigma\",\n                       &sigma, sigma,\n                       \"Standard deviation of noise.\");\n  clopts.attach_option(\"lambda\",\n                       &lambda, lambda,\n                       \"Smoothness parameter (larger => smoother).\");\n  clopts.attach_option(\"smoothing\",\n                       &smoothing, smoothing,\n                       \"Options are {square, laplace}\");\n  clopts.attach_option(\"orig\",\n                       &orig_fn, orig_fn,\n                       \"Original image file name.\");\n  clopts.attach_option(\"noisy\",\n                       &noisy_fn, noisy_fn,\n                       \"Noisy image file name.\");\n  clopts.attach_option(\"pred\",\n                       &pred_fn, pred_fn,\n                       \"Predicted image file name.\");\n  clopts.attach_option(\"pred_type\",\n                       &pred_type, pred_type,\n                       \"Predicted image type {map, exp}\");\n  \n\n  clopts.set_scheduler_type(\"splash(splash_size=100)\");\n  clopts.set_scope_type(\"edge\");\n  \n\n  bool success = clopts.parse(argc, argv);\n  if(!success) {    \n    return EXIT_FAILURE;\n  }\n\n\n  \n  std::cout << \"ncpus:          \" << clopts.get_ncpus() << std::endl\n            << \"bound:          \" << bound << std::endl\n            << \"damping:        \" << damping << std::endl\n            << \"colors:         \" << colors << std::endl\n            << \"rows:           \" << rows << std::endl\n            << \"cols:           \" << cols << std::endl\n            << \"sigma:          \" << sigma << std::endl\n            << \"lambda:         \" << lambda << std::endl\n            << \"smoothing:      \" << smoothing << std::endl\n            << \"engine:         \" << clopts.get_engine_type() << std::endl\n            << \"scope:          \" << clopts.get_scope_type() << std::endl\n            << \"scheduler:      \" << clopts.get_scheduler_type() << std::endl\n            << \"orig_fn:        \" << orig_fn << std::endl\n            << \"noisy_fn:       \" << noisy_fn << std::endl\n            << \"pred_fn:        \" << pred_fn << std::endl\n            << \"pred_type:      \" << pred_type << std::endl;\n\n  \n  \n\n  // Create synthetic images -------------------------------------------------->\n  // Creating image for denoising\n  std::cout << \"Creating a synthetic image. \" << std::endl;\n  image img(rows, cols);\n  img.paint_sunset(colors);\n  std::cout << \"Saving image. \" << std::endl;\n  img.save(orig_fn.c_str());\n  std::cout << \"Corrupting Image. \" << std::endl;\n  img.corrupt(sigma);\n  std::cout << \"Saving corrupted image. \" << std::endl;\n  img.save(noisy_fn.c_str());\n\n\n \n  \n  \n  // Create the graph --------------------------------------------------------->\n  gl_types::core core;\n  // Set the engine options\n  core.set_engine_options(clopts);\n  \n  std::cout << \"Constructing pairwise Markov Random Field. \" << std::endl;\n  construct_graph(img, colors, sigma, core.graph());\n\n  \n  // Setup global shared variables -------------------------------------------->\n  // Initialize the edge agreement factor \n  std::cout << \"Initializing shared edge agreement factor. \" << std::endl;\n\n  // dummy variables 0 and 1 and num_rings by num_rings\n  graphlab::binary_factor edge_potential(0, colors, 0, colors);\n  // Set the smoothing type\n  if(smoothing == \"square\") {\n    edge_potential.set_as_agreement(lambda);\n  } else if (smoothing == \"laplace\") {\n    edge_potential.set_as_laplace(lambda);\n  } else {\n    std::cout << \"Invalid smoothing stype!\" << std::endl;\n    return EXIT_FAILURE;\n  }\n  std::cout << edge_potential << std::endl;\n  \n  EDGE_FACTOR.set(edge_potential);\n  BOUND.set(bound);\n  DAMPING.set(damping);\n  \n\n\n  // Running the engine ------------------------------------------------------->\n  core.sched_options().add_option(\"update_function\",bp_update);\n\n  std::cout << \"Running the engine. \" << std::endl;\n\n  \n  // Add the bp update to all vertices\n  core.add_task_to_all(bp_update, 100.0);\n  // Starte the engine\n  double runtime = core.start();\n  \n  size_t update_count = core.last_update_count();\n  std::cout << \"Finished Running engine in \" << runtime \n            << \" seconds.\" << std::endl\n            << \"Total updates: \" << update_count << std::endl\n            << \"Efficiency: \" << (double(update_count) / runtime)\n            << \" updates per second \"\n            << std::endl;  \n\n\n  // Saving the output -------------------------------------------------------->\n  /*std::cout << \"Rendering the cleaned image. \" << std::endl;\n  if(pred_type == \"map\") {\n    for(size_t v = 0; v < core.graph().num_vertices(); ++v) {\n      const vertex_data& vdata = core.graph().vertex_data(v);\n      img.pixel(v) = vdata.belief.max_asg();    \n    }\n  } else if(pred_type == \"exp\") {\n    for(size_t v = 0; v < core.graph().num_vertices(); ++v) {\n      const vertex_data& vdata = core.graph().vertex_data(v);\n      img.pixel(v) = vdata.belief.expectation();\n    }\n  } else {\n    std::cout << \"Invalid prediction type! : \" << pred_type\n              << std::endl;\n    return EXIT_FAILURE;\n  }\n  std::cout << \"Saving cleaned image. \" << std::endl;\n  img.save(pred_fn.c_str());\n */\n  std::cout << \"Done!\" << std::endl;\n  return EXIT_SUCCESS;\n} // End of main\n\n\n\n\n// Implementations\n// ============================================================>\nvoid bp_update(gl_types::iscope& scope, \n               gl_types::icallback& scheduler) {\n  //  std::cout << scope.vertex();;\n  //  std::getchar();\n\n  // Get the shared data\n  double bound = BOUND.get_val();\n  double damping = DAMPING.get_val();\n\n  // Grab the state from the scope\n  // ---------------------------------------------------------------->\n  // Get the vertex data\n  vertex_data& v_data = scope.vertex_data();\n  \n  // Get the in and out edges by reference\n  gl_types::edge_list in_edges = scope.in_edge_ids();\n  gl_types::edge_list out_edges = scope.out_edge_ids();\n  assert(in_edges.size() == out_edges.size()); // Sanity check\n\n  // Flip the old and new messages to improve safety when using the\n  // unsynch scope\n  foreach(graphlab::edge_id_t ineid, in_edges) {   \n    // Get the in and out edge data\n    edge_data& in_edge = scope.edge_data(ineid);\n    // Since we are about to receive the current message make it the\n    // old message\n    in_edge.old_message = in_edge.message;\n  }\n\n  // Compute the belief\n  // ---------------------------------------------------------------->\n  // Initialize the belief as the value of the factor\n  v_data.belief = v_data.potential;\n  foreach(graphlab::edge_id_t ineid, in_edges) {\n    // Get the message\n    const edge_data& e_data = scope.edge_data(ineid);\n    // Notice we now use the old message since neighboring vertices\n    // could be changing the new messages\n    v_data.belief.times( e_data.old_message );\n  }\n  v_data.belief.normalize(); // finally normalize the belief\n  \n  // Compute outbound messages\n  // ---------------------------------------------------------------->\n\n  boost::shared_ptr<const graphlab::binary_factor> edge_factor_ptr = EDGE_FACTOR.get_ptr();\n  const graphlab::binary_factor &edge_factor = *edge_factor_ptr;\n  \n  // Send outbound messages\n  graphlab::unary_factor cavity, tmp_msg;\n  for(size_t i = 0; i < in_edges.size(); ++i) {\n    // Get the edge ids\n    graphlab::edge_id_t outeid = out_edges[i];\n    graphlab::edge_id_t ineid = in_edges[i];\n    // CLEVER HACK: Here we are expoiting the sorting of the edge ids\n    // to do fast O(1) time edge reversal\n    assert(scope.target(outeid) == scope.source(ineid));\n    // Get the in and out edge data\n    const edge_data& in_edge = scope.edge_data(ineid);\n    edge_data& out_edge = scope.edge_data(outeid);\n    \n    // Compute cavity\n    cavity = v_data.belief;\n    cavity.divide(in_edge.old_message); // Make the cavity a cavity\n    cavity.normalize();\n\n\n    // convolve cavity with the edge factor storing the result in the\n    // temporary message\n    tmp_msg.resize(out_edge.message.arity());\n    tmp_msg.var() = out_edge.message.var();\n    tmp_msg.convolve(edge_factor, cavity);\n    tmp_msg.normalize();\n\n    // Damp the message\n    tmp_msg.damp(out_edge.message, damping);\n    \n    // Compute message residual\n    double residual = tmp_msg.residual(out_edge.old_message);\n    \n    // Assign the out message\n    out_edge.message = tmp_msg;\n    \n    if(residual > bound) {\n      gl_types::update_task task(scope.target(outeid), bp_update);      \n      scheduler.add_task(task, residual);\n    }    \n  }\n} // end of BP_update\n\n\nvoid construct_graph(image& img,\n                     size_t num_rings,\n                     double sigma,\n                     gl_types::graph& graph) {\n  // Construct a single blob for the vertex data\n  vertex_data vdata;\n  vdata.potential.resize(num_rings);\n  vdata.belief.resize(num_rings);\n  vdata.belief.uniform();\n  vdata.potential.uniform();\n  vdata.belief.normalize();\n  vdata.potential.normalize();\n  // Add all the vertices\n  double sigmaSq = sigma*sigma;\n  for(size_t i = 0; i < img.rows(); ++i) {\n    for(size_t j = 0; j < img.cols(); ++j) {\n      // initialize the potential and belief\n      uint32_t pixel_id = img.vertid(i, j);\n      vdata.potential.var() = vdata.belief.var() = pixel_id;\n      // Set the node potential\n      double obs = img.pixel(i, j);\n      for(size_t pred = 0; pred < num_rings; ++pred) {\n        vdata.potential.logP(pred) = \n          -(obs - pred)*(obs - pred) / (2.0 * sigmaSq);\n      }\n      vdata.potential.normalize();\n      // Store the actual data in the graph\n      size_t vertid = graph.add_vertex(vdata);\n      // Ensure that we are using a consistent numbering\n      assert(vertid == img.vertid(i, j));\n    } // end of for j in cols\n  } // end of for i in rows\n\n  // Add the edges\n  edge_data edata;\n  edata.message.resize(num_rings);\n  edata.message.uniform();\n  edata.message.normalize();\n  edata.old_message = edata.message;\n  \n  for(size_t i = 0; i < img.rows(); ++i) {\n    for(size_t j = 0; j < img.cols(); ++j) {\n      size_t vertid = img.vertid(i,j);\n      if(i-1 < img.rows()) {\n        edata.message.var() = img.vertid(i-1, j);\n        edata.old_message.var() = edata.message.var();\n        graph.add_edge(vertid, img.vertid(i-1, j), edata);\n      }\n      if(i+1 < img.rows()) {\n        edata.message.var() = img.vertid(i+1, j);\n        edata.old_message.var() = edata.message.var();\n        graph.add_edge(vertid, img.vertid(i+1, j), edata);\n      }\n      if(j-1 < img.cols()) {\n        edata.message.var() = img.vertid(i, j-1);\n        edata.old_message.var() = edata.message.var();\n        graph.add_edge(vertid, img.vertid(i, j-1), edata);\n      } if(j+1 < img.cols()) {\n        edata.message.var() = img.vertid(i, j+1);\n        edata.old_message.var() = edata.message.var();\n        graph.add_edge(vertid, img.vertid(i, j+1), edata);\n      }\n    } // end of for j in cols\n  } // end of for i in rows\n  graph.finalize();  \n} // End of construct graph\n\n\n", "meta": {"hexsha": "cd53a59cf3711d9bfc566e3dd8a0407889a64fb6", "size": 15676, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "demoapps/image_denoise/loopybp_denoise.cpp", "max_stars_repo_name": "iivek/graphlab-cmu-mirror", "max_stars_repo_head_hexsha": "028321757ea979e6a0859687e37933be375153eb", "max_stars_repo_licenses": ["ECL-2.0", "Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-08-01T06:32:58.000Z", "max_stars_repo_stars_event_max_datetime": "2018-08-01T06:32:58.000Z", "max_issues_repo_path": "demoapps/image_denoise/loopybp_denoise.cpp", "max_issues_repo_name": "iivek/graphlab-cmu-mirror", "max_issues_repo_head_hexsha": "028321757ea979e6a0859687e37933be375153eb", "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": "demoapps/image_denoise/loopybp_denoise.cpp", "max_forks_repo_name": "iivek/graphlab-cmu-mirror", "max_forks_repo_head_hexsha": "028321757ea979e6a0859687e37933be375153eb", "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": 32.2551440329, "max_line_length": 91, "alphanum_fraction": 0.5801224802, "num_tokens": 3781, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.588889130767832, "lm_q2_score": 0.5428632831725053, "lm_q1q2_score": 0.3196862869532281}}
{"text": "/*****************************************************************************/\n/*  Copyright (c) 2017, Aleksandrs Ecins                                     */\n/*  All rights reserved.                                                     */\n/*                                                                           */\n/*  Redistribution and use in source and binary forms, with or without       */\n/*  modification, are permitted provided that the following conditions       */\n/*  are met:                                                                 */\n/*                                                                           */\n/*  1. Redistributions of source code must retain the above copyright        */\n/*  notice, this list of conditions and the following disclaimer.            */\n/*                                                                           */\n/*  2. Redistributions in binary form must reproduce the above copyright     */\n/*  notice, this list of conditions and the following disclaimer in the      */\n/*  documentation and/or other materials provided with the distribution.     */\n/*                                                                           */\n/*  3. Neither the name of the copyright holder nor the names of its         */\n/*  contributors may be used to endorse or promote products derived from     */\n/*  this software without specific prior written permission.                 */\n/*                                                                           */\n/*  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS      */\n/*  \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT        */\n/*  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR    */\n/*  A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT     */\n/*  HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,   */\n/*  SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT         */\n/*  LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,    */\n/*  DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY    */\n/*  THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT      */\n/*  (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE    */\n/*  OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.     */\n/*****************************************************************************/\n\n#ifndef BRON_KERBOSCH_HPP\n#define BRON_KERBOSCH_HPP\n\n// Boost includes\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/bron_kerbosch_all_cliques.hpp>\n\n// Utilities includes\n#include <graph/graph.hpp>\n\nstruct CliqueVisitor\n{\n  typedef boost::adjacency_list<boost::vecS, boost::vecS, boost::undirectedS> GraphBoost;\n  typedef boost::property_map<GraphBoost, boost::vertex_index_t>::type IndexMap;\n  \n  // Constructor\n  CliqueVisitor (IndexMap& index, std::list<std::list<int> >& cliques)\n    : index_(index)\n    , cliques_(cliques)\n  { }\n\n  // This function is called for every clique\n  template <typename Clique, typename Graph>\n  void clique(const Clique& c, const Graph& g)\n  {   \n    std::list<int> curClique;\n    \n    // Iterate over the clique\n    for(typename Clique::const_iterator i = c.begin(); i != c.end(); ++i)\n      curClique.push_back(index_[*i]);\n\n    cliques_.push_back(curClique);\n  }\n  \n  IndexMap& index_;\n  std::list<std::list<int> >& cliques_;\n};\n\nnamespace utl\n{\n  /** \\brief Find all maximal cliques in a graph using the Bron-Kerbosch\n   * algorithm.\n   *  \\param[in]  graph   input graph\n   *  \\param[out] cliques output cliques\n   *  \\param[in]  min_clique_size minimum size of a valid clique\n   *  \\note this is a wrapper around Bron-Kerbosch implementation in Boost library\n   */\n  int bronKerbosch  ( const utl::Graph &graph,\n                      std::list<std::list<int> > &cliques,\n                      const int min_clique_size = 2\n                    )\n  {\n    typedef boost::adjacency_list<boost::vecS, boost::vecS, boost::undirectedS> GraphBoost;\n    typedef boost::property_map<GraphBoost, boost::vertex_index_t>::type IndexMap;\n    \n    // Convert to Boost graph\n    GraphBoost graphBoost (graph.getNumVertices());\n    IndexMap index = get(boost::vertex_index, graphBoost);\n\n    for (int edgeId = 0; edgeId < graph.getNumEdges(); edgeId++)\n    {\n      utl::Edge edge;\n      graph.getEdge(edgeId, edge);\n      boost::add_edge(edge.vtx1Id_, edge.vtx2Id_, graphBoost);\n    }\n    \n    // Find cliques\n    CliqueVisitor visitor(index, cliques);\n    boost::bron_kerbosch_all_cliques(graphBoost, visitor, min_clique_size); \n        \n    return cliques.size();\n  }\n}\n\n# endif // BRON_KERBOSCH_HPP", "meta": {"hexsha": "290a69b49ec8f2cbecce8f0b0ec798ac8057577d", "size": 4722, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "utilities/graph/bron_kerbosch.hpp", "max_stars_repo_name": "Cznielsen/symseg", "max_stars_repo_head_hexsha": "b1c1e1e2f21f6a3d8b65e4f68d3516bc0bbbf06e", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 51.0, "max_stars_repo_stars_event_min_datetime": "2017-05-15T15:16:19.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-01T22:37:29.000Z", "max_issues_repo_path": "utilities/graph/bron_kerbosch.hpp", "max_issues_repo_name": "Cznielsen/symseg", "max_issues_repo_head_hexsha": "b1c1e1e2f21f6a3d8b65e4f68d3516bc0bbbf06e", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2017-05-31T05:32:53.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-08T01:35:49.000Z", "max_forks_repo_path": "utilities/graph/bron_kerbosch.hpp", "max_forks_repo_name": "Cznielsen/symseg", "max_forks_repo_head_hexsha": "b1c1e1e2f21f6a3d8b65e4f68d3516bc0bbbf06e", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 12.0, "max_forks_repo_forks_event_min_datetime": "2017-08-08T17:43:07.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-29T17:59:08.000Z", "avg_line_length": 44.1308411215, "max_line_length": 91, "alphanum_fraction": 0.5766624312, "num_tokens": 1004, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5428632683808533, "lm_q2_score": 0.5888891307678321, "lm_q1q2_score": 0.31968627824258505}}
{"text": "// This file is part of LatNet Builder.\n//\n// Copyright (C) 2012-2021  The LatNet Builder author's, supervised by Pierre L'Ecuyer, Universite de Montreal.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//     http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\n#include \"latbuilder/Norm/IB.h\"\n#include \"latbuilder/WeightsDispatcher.h\"\n#include \"latbuilder/Util.h\"\n\n#include <vector>\n#include <cmath>\n#include <boost/math/tools/polynomial.hpp>\n\nnamespace LatBuilder { namespace Norm {\n\nnamespace SumHelperIB{\n\n typedef boost::math::tools::polynomial<double> RealPolynomial;\n\n   template <typename WEIGHTS>\n   struct SumHelper {\n      Real operator()(\n            const WEIGHTS& weights,\n            Real lambda,\n            Dimension dimension,\n            unsigned int alpha\n            ) const\n      {\n         throw std::runtime_error(\"IB normalization not implemented for these weights.\");\n         return 1.;\n      }\n   };\n\n\n#define DECLARE_IB_SUM(weight_type) \\\n      template <> \\\n      class SumHelper<weight_type> { \\\n      public: \\\n         Real operator()( \\\n               const weight_type& weights, \\\n               Real lambda, \\\n               Dimension dimension, \\\n               unsigned int alpha \\\n               ) const; \\\n      }\\\n\n   DECLARE_IB_SUM(LatBuilder::CombinedWeights);\n   DECLARE_IB_SUM(LatBuilder::Interlaced::IPODWeights<LatBuilder::Kernel::IB>);\n   DECLARE_IB_SUM(LatBuilder::Interlaced::IPDWeights<LatBuilder::Kernel::IB>);\n\n#undef DECLARE_IB_SUM\n\n   //===========================================================================\n   // combined weights\n   //===========================================================================\n\n   // Separating sumCombined() from\n   // SumHelper<LatBuilder::CombinedWeights>::operator() is a workaround for\n   // LLVM/clang++.\n   Real sumCombined(\n         const CombinedWeights& weights,\n         Real lambda,\n         Dimension dimension,\n         unsigned int alpha\n         )\n   {\n      Real val = 0.0;\n      for (const auto& w : weights.list())\n         val += WeightsDispatcher::dispatch<SumHelper>(*w, lambda, dimension, alpha);\n      return val;\n   }\n\n   Real SumHelper<LatBuilder::CombinedWeights>::operator()(\n         const CombinedWeights& weights,\n         Real lambda,\n         Dimension dimension,\n         unsigned int alpha\n         ) const\n   {\n      return sumCombined(weights, lambda, dimension, alpha);\n   }\n\n\n   //===========================================================================\n   // interlaced projection-dependent weights\n   //===========================================================================\n\n   Real SumHelper<LatBuilder::Interlaced::IPDWeights<LatBuilder::Kernel::IB>>::operator()(\n         const LatBuilder::Interlaced::IPDWeights<LatBuilder::Kernel::IB>& weights,\n         Real lambda,\n         Dimension dimension,\n         unsigned int alpha\n         ) const\n   { \n      unsigned int interlacingFactor = weights.interlacingFactor();\n      Dimension j0 = (Dimension) std::ceil( (double) dimension / interlacingFactor);\n      Dimension d0 = dimension - (j0 - 1) * interlacingFactor;\n      Real gTilde = std::max(pow(intPow(2.0,std::min(alpha, interlacingFactor))-2,-lambda), 1 / (pow(2.0, lambda * std::min(alpha, interlacingFactor)) - 2));\n\n      Real g0 = 1;\n      for(Dimension l = 1; l <= d0; ++l)\n      {\n            g0 *= 1 + pow(2.0, lambda * (interlacingFactor - l)) * gTilde;\n      }\n      Real g = g0;\n      g0 -= 1;\n      for(Dimension l = d0 + 1; l <= interlacingFactor; ++l)\n      {\n            g *= 1 + pow(2.0, lambda * (interlacingFactor - l)) * gTilde;\n      }\n      g -= 1.0;\n      Real val = 0.0;\n      for (Dimension largestIndex = 0; largestIndex < j0; largestIndex++) {\n         // iterate only through projections that have a weight\n         for (const auto& pw : weights.getBaseWeights().getWeightsForLargestIndex(largestIndex)) {\n            const auto& proj = pw.first;\n            const auto& weight = pw.second;\n            if (weight)\n            {\n                  if (largestIndex < j0 - 1)\n                  {\n                        val += pow(weight, lambda) * intPow(g, proj.size());\n                  }\n                  else\n                  {\n                        val += pow(weight, lambda) * g0 * intPow(g, proj.size() - 1);\n                  }\n            }\n         }\n      }\n\n      return val;\n   }\n\n   //===========================================================================\n   // IPOD weights\n   //===========================================================================\n\n   Real SumHelper<LatBuilder::Interlaced::IPODWeights<LatBuilder::Kernel::IB>>::operator()(\n         const LatBuilder::Interlaced::IPODWeights<LatBuilder::Kernel::IB>& weights,\n         Real lambda,\n         Dimension dimension,\n         unsigned int alpha\n         ) const\n   {\n      unsigned int interlacingFactor = weights.interlacingFactor();\n      Dimension j0 = (Dimension) std::ceil( (double) dimension / interlacingFactor);\n      Dimension d0 = dimension - (j0 - 1) * interlacingFactor;\n      Real gTilde = std::max(pow(intPow(2.0,std::min(alpha, interlacingFactor))-2,-lambda), 1 / (pow(2.0, lambda * std::min(alpha, interlacingFactor)) - 2));\n\n      Real g0 = 1;\n      for(Dimension l = 1; l <= d0; ++l)\n      {\n            g0 *= 1 + pow(2.0, lambda * (interlacingFactor - l)) * gTilde;\n      }\n      Real g = g0;\n      g0 -= 1;\n      for(Dimension l = d0 + 1; l <= interlacingFactor; ++l)\n      {\n            g *= 1 + pow(2.0, lambda * (interlacingFactor - l)) * gTilde;\n      }\n      g -= 1.0;\n\n      Real val = g0 * pow(weights.getWeightForCoordinate(j0 - 1) * weights.getWeightForOrder(1), lambda);\n      RealPolynomial acc{1.0};\n      for(Dimension coord = 0; coord < j0 - 1; ++coord)\n      {\n            acc *= RealPolynomial{{pow(weights.getWeightForCoordinate(coord), lambda) * g, 1.0}};\n      }\n      for(Dimension degree = 0; degree < j0 - 1; ++degree)\n      {\n            val += acc[degree] * (pow(weights.getWeightForOrder(j0 - 1 - degree),lambda) + g0 * pow(weights.getWeightForCoordinate(j0 - 1) * weights.getWeightForOrder(j0 - degree), lambda)) ;\n      }\n      return val;\n  }\n\n}\n\nIB::IB(unsigned int alpha, const LatticeTester::Weights& weights, Real normType):\n   NormAlphaBase<IB>(alpha, normType),\n   m_weights(weights)\n{}\n\ntemplate <LatticeType LR, EmbeddingType L>\nReal IB::value(\n      Real lambda,\n      const SizeParam<LR, L>& sizeParam,\n      Dimension dimension,\n      Real norm\n      ) const\n{\n   norm = 1.0 / (norm * (sizeParam.numPoints() - 1.0));\n   Real val = WeightsDispatcher::dispatch<SumHelperIB::SumHelper>(\n         m_weights,\n         lambda,\n         dimension,\n         alpha()\n         );\n\n   return pow(val * norm, 1.0 / lambda);\n}\n\ntemplate Real IB::value<LatticeType::ORDINARY, EmbeddingType::UNILEVEL>(Real, const SizeParam<LatticeType::ORDINARY, EmbeddingType::UNILEVEL>&, Dimension, Real) const;\ntemplate Real IB::value<LatticeType::ORDINARY, EmbeddingType::MULTILEVEL>(Real, const SizeParam<LatticeType::ORDINARY, EmbeddingType::MULTILEVEL>&, Dimension, Real) const;\n\ntemplate Real IB::value<LatticeType::POLYNOMIAL, EmbeddingType::UNILEVEL>(Real, const SizeParam<LatticeType::POLYNOMIAL, EmbeddingType::UNILEVEL>&, Dimension, Real) const;\ntemplate Real IB::value<LatticeType::POLYNOMIAL, EmbeddingType::MULTILEVEL>(Real, const SizeParam<LatticeType::POLYNOMIAL, EmbeddingType::MULTILEVEL>&, Dimension, Real) const;\n\n}}\n", "meta": {"hexsha": "0498550c22ba3fee8b07fc7cb736c63554f9417a", "size": 7890, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/LatBuilder/Norm/IB.cc", "max_stars_repo_name": "YochevedDarmon/latnetbuilder", "max_stars_repo_head_hexsha": "7df3a7ba89e10ca51d4af347b75cdb0987e5151c", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2020-01-21T06:08:51.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-24T16:11:31.000Z", "max_issues_repo_path": "src/LatBuilder/Norm/IB.cc", "max_issues_repo_name": "YochevedDarmon/latnetbuilder", "max_issues_repo_head_hexsha": "7df3a7ba89e10ca51d4af347b75cdb0987e5151c", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2019-10-31T07:49:28.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-03T12:07:49.000Z", "max_forks_repo_path": "src/LatBuilder/Norm/IB.cc", "max_forks_repo_name": "YochevedDarmon/latnetbuilder", "max_forks_repo_head_hexsha": "7df3a7ba89e10ca51d4af347b75cdb0987e5151c", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2016-07-27T19:25:26.000Z", "max_forks_repo_forks_event_max_datetime": "2018-05-22T20:00:47.000Z", "avg_line_length": 35.7013574661, "max_line_length": 191, "alphanum_fraction": 0.578833967, "num_tokens": 1947, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6992544335934766, "lm_q2_score": 0.45713671682749485, "lm_q1q2_score": 0.31965487599999143}}
{"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_BIPC_HPP\n#define BOOST_GEOMETRY_PROJECTIONS_BIPC_HPP\n\n#include <boost/geometry/util/math.hpp>\n#include <boost/math/special_functions/hypot.hpp>\n\n#include <boost/geometry/srs/projections/impl/base_static.hpp>\n#include <boost/geometry/srs/projections/impl/base_dynamic.hpp>\n#include <boost/geometry/srs/projections/impl/projects.hpp>\n#include <boost/geometry/srs/projections/impl/factory_entry.hpp>\n\nnamespace boost { namespace geometry\n{\n\nnamespace srs { namespace par4\n{\n    struct bipc {};\n\n}} //namespace srs::par4\n\nnamespace projections\n{\n    #ifndef DOXYGEN_NO_DETAIL\n    namespace detail { namespace bipc\n    {\n\n            static const double epsilon = 1e-10;\n            static const double epsilon10 = 1e-10;\n            static const double one_plus_eps = 1.000000001;\n            static const int n_iter = 10;\n            static const double lamB = -.34894976726250681539;\n            static const double n = .63055844881274687180;\n            static const double F = 1.89724742567461030582;\n            static const double Azab = .81650043674686363166;\n            static const double Azba = 1.82261843856185925133;\n            static const double const_T = 1.27246578267089012270;\n            static const double rhoc = 1.20709121521568721927;\n            static const double cAzc = .69691523038678375519;\n            static const double sAzc = .71715351331143607555;\n            static const double C45 = .70710678118654752469;\n            static const double S45 = .70710678118654752410;\n            static const double C20 = .93969262078590838411;\n            static const double S20 = -.34202014332566873287;\n            static const double R110 = 1.91986217719376253360;\n            static const double R104 = 1.81514242207410275904;\n\n            struct par_bipc\n            {\n                int    noskew;\n            };\n\n            // template class, using CRTP to implement forward/inverse\n            template <typename T, typename Parameters>\n            struct base_bipc_spheroid\n                : public base_t_fi<base_bipc_spheroid<T, Parameters>, T, Parameters>\n            {\n                par_bipc m_proj_parm;\n\n                inline base_bipc_spheroid(const Parameters& par)\n                    : base_t_fi<base_bipc_spheroid<T, Parameters>, T, Parameters>(*this, par)\n                {}\n\n                // FORWARD(s_forward)  spheroid\n                // Project coordinates from geographic (lon, lat) to cartesian (x, y)\n                inline void fwd(T& lp_lon, T& lp_lat, T& xy_x, T& xy_y) const\n                {\n                    static const T half_pi = detail::half_pi<T>();\n                    static const T pi = detail::pi<T>();\n\n                    T cphi, sphi, tphi, t, al, Az, z, Av, cdlam, sdlam, r;\n                    int tag;\n\n                    cphi = cos(lp_lat);\n                    sphi = sin(lp_lat);\n                    cdlam = cos(sdlam = lamB - lp_lon);\n                    sdlam = sin(sdlam);\n                    if (fabs(fabs(lp_lat) - half_pi) < epsilon10) {\n                        Az = lp_lat < 0. ? pi : 0.;\n                        tphi = HUGE_VAL;\n                    } else {\n                        tphi = sphi / cphi;\n                        Az = atan2(sdlam , C45 * (tphi - cdlam));\n                    }\n                    if( (tag = (Az > Azba)) ) {\n                        cdlam = cos(sdlam = lp_lon + R110);\n                        sdlam = sin(sdlam);\n                        z = S20 * sphi + C20 * cphi * cdlam;\n                        if (fabs(z) > 1.) {\n                            if (fabs(z) > one_plus_eps)\n                                BOOST_THROW_EXCEPTION( projection_exception(error_tolerance_condition) );\n                            else\n                                z = z < 0. ? -1. : 1.;\n                        } else\n                            z = acos(z);\n                        if (tphi != HUGE_VAL)\n                            Az = atan2(sdlam, (C20 * tphi - S20 * cdlam));\n                        Av = Azab;\n                        xy_y = rhoc;\n                    } else {\n                        z = S45 * (sphi + cphi * cdlam);\n                        if (fabs(z) > 1.) {\n                            if (fabs(z) > one_plus_eps)\n                                BOOST_THROW_EXCEPTION( projection_exception(error_tolerance_condition) );\n                            else\n                                z = z < 0. ? -1. : 1.;\n                        } else\n                            z = acos(z);\n                        Av = Azba;\n                        xy_y = -rhoc;\n                    }\n                    if (z < 0.) {\n                        BOOST_THROW_EXCEPTION( projection_exception(error_tolerance_condition) );\n                    }\n                    r = F * (t = pow(tan(.5 * z), n));\n                    if ((al = .5 * (R104 - z)) < 0.) {\n                        BOOST_THROW_EXCEPTION( projection_exception(error_tolerance_condition) );\n                    }\n                    al = (t + pow(al, n)) / const_T;\n                    if (fabs(al) > 1.) {\n                        if (fabs(al) > one_plus_eps)\n                            BOOST_THROW_EXCEPTION( projection_exception(error_tolerance_condition) );\n                        else\n                            al = al < 0. ? -1. : 1.;\n                    } else\n                        al = acos(al);\n                    if (fabs(t = n * (Av - Az)) < al)\n                        r /= cos(al + (tag ? t : -t));\n                    xy_x = r * sin(t);\n                    xy_y += (tag ? -r : r) * cos(t);\n                    if (this->m_proj_parm.noskew) {\n                        t = xy_x;\n                        xy_x = -xy_x * cAzc - xy_y * sAzc;\n                        xy_y = -xy_y * cAzc + t * sAzc;\n                    }\n                }\n\n                // INVERSE(s_inverse)  spheroid\n                // Project coordinates from cartesian (x, y) to geographic (lon, lat)\n                inline void inv(T& xy_x, T& xy_y, T& lp_lon, T& lp_lat) const\n                {\n                    T t, r, rp, rl, al, z, fAz, Az, s, c, Av;\n                    int neg, i;\n\n                    if (this->m_proj_parm.noskew) {\n                        t = xy_x;\n                        xy_x = -xy_x * cAzc + xy_y * sAzc;\n                        xy_y = -xy_y * cAzc - t * sAzc;\n                    }\n                    if( (neg = (xy_x < 0.)) ) {\n                        xy_y = rhoc - xy_y;\n                        s = S20;\n                        c = C20;\n                        Av = Azab;\n                    } else {\n                        xy_y += rhoc;\n                        s = S45;\n                        c = C45;\n                        Av = Azba;\n                    }\n                    rl = rp = r = boost::math::hypot(xy_x, xy_y);\n                    fAz = fabs(Az = atan2(xy_x, xy_y));\n                    for (i = n_iter; i ; --i) {\n                        z = 2. * atan(pow(r / F,1 / n));\n                        al = acos((pow(tan(.5 * z), n) +\n                           pow(tan(.5 * (R104 - z)), n)) / const_T);\n                        if (fAz < al)\n                            r = rp * cos(al + (neg ? Az : -Az));\n                        if (fabs(rl - r) < epsilon)\n                            break;\n                        rl = r;\n                    }\n                    if (! i)\n                        BOOST_THROW_EXCEPTION( projection_exception(error_tolerance_condition) );\n                    Az = Av - Az / n;\n                    lp_lat = asin(s * cos(z) + c * sin(z) * cos(Az));\n                    lp_lon = atan2(sin(Az), c / tan(z) - s * cos(Az));\n                    if (neg)\n                        lp_lon -= R110;\n                    else\n                        lp_lon = lamB - lp_lon;\n                }\n\n                static inline std::string get_name()\n                {\n                    return \"bipc_spheroid\";\n                }\n\n            };\n\n            // Bipolar conic of western hemisphere\n            template <typename Parameters>\n            inline void setup_bipc(Parameters& par, par_bipc& proj_parm)\n            {\n                proj_parm.noskew = pj_get_param_b(par.params, \"ns\");\n                par.es = 0.;\n            }\n\n    }} // namespace detail::bipc\n    #endif // doxygen\n\n    /*!\n        \\brief Bipolar conic of western hemisphere 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         - ns (boolean)\n        \\par Example\n        \\image html ex_bipc.gif\n    */\n    template <typename T, typename Parameters>\n    struct bipc_spheroid : public detail::bipc::base_bipc_spheroid<T, Parameters>\n    {\n        inline bipc_spheroid(const Parameters& par) : detail::bipc::base_bipc_spheroid<T, Parameters>(par)\n        {\n            detail::bipc::setup_bipc(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::bipc, bipc_spheroid, bipc_spheroid)\n\n        // Factory entry(s)\n        template <typename T, typename Parameters>\n        class bipc_entry : public detail::factory_entry<T, Parameters>\n        {\n            public :\n                virtual base_v<T, Parameters>* create_new(const Parameters& par) const\n                {\n                    return new base_v_fi<bipc_spheroid<T, Parameters>, T, Parameters>(par);\n                }\n        };\n\n        template <typename T, typename Parameters>\n        inline void bipc_init(detail::base_factory<T, Parameters>& factory)\n        {\n            factory.add_to_factory(\"bipc\", new bipc_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_BIPC_HPP\n\n", "meta": {"hexsha": "3e2efbdcfb01ea45bfda8d0fd68ffdb0e0ed3eb9", "size": 11982, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/geometry/srs/projections/proj/bipc.hpp", "max_stars_repo_name": "jonasdmentia/geometry", "max_stars_repo_head_hexsha": "097f6fdbe98118be82cd1917cc72c3c6a37bdf30", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/boost/geometry/srs/projections/proj/bipc.hpp", "max_issues_repo_name": "jonasdmentia/geometry", "max_issues_repo_head_hexsha": "097f6fdbe98118be82cd1917cc72c3c6a37bdf30", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/boost/geometry/srs/projections/proj/bipc.hpp", "max_forks_repo_name": "jonasdmentia/geometry", "max_forks_repo_head_hexsha": "097f6fdbe98118be82cd1917cc72c3c6a37bdf30", "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.4797297297, "max_line_length": 106, "alphanum_fraction": 0.5045902187, "num_tokens": 2745, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6992544210587585, "lm_q2_score": 0.45713671682749474, "lm_q1q2_score": 0.31965487026991146}}
{"text": "/*\n * Copyright (C) 2021 Open Source Robotics Foundation\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n */\n\n/*\n * Development of this module has been funded by the Monterey Bay Aquarium\n * Research Institute (MBARI) and the David and Lucile Packard Foundation\n */\n\n#include \"HydrodynamicsPlugin.hh\"\n\n#include <Eigen/Eigen>\n\n#include <ignition/msgs.hh>\n\nnamespace tethys\n{\n\nclass HydrodynamicsPrivateData\n{\n  /// \\brief Values to set via Plugin Parameters.\n  /// Plugin Parameter: Added mass in surge, X_\\dot{u}.\n  public: double paramXdotU;\n\n  /// \\brief Plugin Parameter: Added mass in sway, Y_\\dot{v}.\n  public: double paramYdotV;\n\n  /// \\brief Plugin Parameter: Added mass in heave, Z_\\dot{w}.\n  public: double paramZdotW;\n\n  /// \\brief Plugin Parameter: Added mass in roll, K_\\dot{p}.\n  public: double paramKdotP;\n\n  /// \\brief Plugin Parameter: Added mass in pitch, M_\\dot{q}.\n  public: double paramMdotQ;\n\n  /// \\brief Plugin Parameter: Added mass in yaw, N_\\dot{r}.\n  public: double paramNdotR;\n\n  /// \\brief Plugin Parameter: Linear drag in surge.\n  public: double paramXu;\n\n  /// \\brief Plugin Parameter: Quadratic drag in surge.\n  public: double paramXuu;\n\n  /// \\brief Plugin Parameter: Linear drag in sway.\n  public: double paramYv;\n\n  /// \\brief Plugin Parameter: Quadratic drag in sway.\n  public: double paramYvv;\n\n  /// \\brief Plugin Parameter: Linear drag in heave.\n  public: double paramZw;\n\n  /// \\brief Plugin Parameter: Quadratic drag in heave.\n  public: double paramZww;\n\n  /// \\brief Plugin Parameter: Linear drag in roll.\n  public: double paramKp;\n\n  /// \\brief Plugin Parameter: Quadratic drag in roll.\n  public: double paramKpp;\n\n  /// \\brief Plugin Parameter: Linear drag in pitch.\n  public: double paramMq;\n\n  /// \\brief Plugin Parameter: Quadratic drag in pitch.\n  public: double paramMqq;\n\n  /// \\brief Plugin Parameter: Linear drag in yaw.\n  public: double paramNr;\n\n  /// \\brief Plugin Parameter: Quadratic drag in yaw.\n  public: double paramNrr;\n\n  /// \\brief Plugin Parameter: Disable coriolis as part of equation. This is\n  /// occasionally useful for testing.\n  public: bool enableCoriolis = true;\n\n  /// \\brief Water density [kg/m^3].\n  public: double waterDensity;\n\n  /// \\brief Water current [m/s].\n  public: ignition::math::Vector3d waterCurrent {0.0, 0.0, 0.0};\n\n  public: Eigen::VectorXd prevState;\n\n  public: Eigen::VectorXd prevStateDot;\n\n  /// \\brief Update current during simulation\n  public: void UpdateCurrent(\n    const ignition::msgs::Vector3d &_msg)\n  {\n    std::lock_guard<std::mutex> lock(this->mtx);\n    this->waterCurrent = ignition::msgs::Convert(_msg);\n  }\n\n  /// Link entity\n  public: ignition::gazebo::Entity linkEntity;\n\n  public: ignition::transport::Node node;\n\n  public: std::mutex mtx;\n};\n\n\nvoid AddAngularVelocityComponent(\n  const ignition::gazebo::Entity &_entity,\n  ignition::gazebo::EntityComponentManager &_ecm)\n{\n  if (!_ecm.Component<ignition::gazebo::components::AngularVelocity>(\n      _entity))\n  {\n    _ecm.CreateComponent(_entity,\n      ignition::gazebo::components::AngularVelocity());\n  }\n    // Create an angular velocity component if one is not present.\n  if (!_ecm.Component<ignition::gazebo::components::WorldAngularVelocity>(\n      _entity))\n  {\n    _ecm.CreateComponent(_entity,\n      ignition::gazebo::components::WorldAngularVelocity());\n  }\n}\n\nvoid AddWorldPose (\n  const ignition::gazebo::Entity &_entity,\n  ignition::gazebo::EntityComponentManager &_ecm)\n{\n  if (!_ecm.Component<ignition::gazebo::components::WorldPose>(\n      _entity))\n  {\n    _ecm.CreateComponent(_entity,\n      ignition::gazebo::components::WorldPose());\n  }\n}\n\nvoid AddWorldLinearVelocity(\n  const ignition::gazebo::Entity &_entity,\n  ignition::gazebo::EntityComponentManager &_ecm)\n{\n  if (!_ecm.Component<ignition::gazebo::components::WorldLinearVelocity>(\n      _entity))\n  {\n    _ecm.CreateComponent(_entity,\n      ignition::gazebo::components::WorldLinearVelocity());\n  }\n}\n\ndouble SdfParamDouble(\n    const std::shared_ptr<const sdf::Element> &_sdf,\n    const std::string &_field,\n    double _default)\n{\n  if(!_sdf->HasElement(_field))\n  {\n    return _default;\n  }\n  return _sdf->Get<double>(_field);\n}\n\n\nHydrodynamicsPlugin::HydrodynamicsPlugin()\n  : dataPtr(std::make_unique<HydrodynamicsPrivateData>())\n{\n}\n\nvoid HydrodynamicsPlugin::Configure(\n  const ignition::gazebo::Entity &_entity,\n  const std::shared_ptr<const sdf::Element> &_sdf,\n  ignition::gazebo::EntityComponentManager &_ecm,\n  ignition::gazebo::EventManager &/*_eventMgr*/\n)\n{\n  this->dataPtr->waterDensity     = SdfParamDouble(_sdf, \"waterDensity\", 997.7735);\n  this->dataPtr->paramXdotU       = SdfParamDouble(_sdf, \"xDotU\"       , 5);\n  this->dataPtr->paramYdotV       = SdfParamDouble(_sdf, \"yDotV\"       , 5);\n  this->dataPtr->paramZdotW       = SdfParamDouble(_sdf, \"zDotW\"       , 0.1);\n  this->dataPtr->paramKdotP       = SdfParamDouble(_sdf, \"kDotP\"       , 0.1);\n  this->dataPtr->paramMdotQ       = SdfParamDouble(_sdf, \"mDotQ\"       , 0.1);\n  this->dataPtr->paramNdotR       = SdfParamDouble(_sdf, \"nDotR\"       , 1);\n  this->dataPtr->paramXu          = SdfParamDouble(_sdf, \"xU\"          , 20);\n  this->dataPtr->paramXuu         = SdfParamDouble(_sdf, \"xUU\"         , 0);\n  this->dataPtr->paramYv          = SdfParamDouble(_sdf, \"yV\"          , 20);\n  this->dataPtr->paramYvv         = SdfParamDouble(_sdf, \"yVV\"         , 0);\n  this->dataPtr->paramZw          = SdfParamDouble(_sdf, \"zW\"          , 20);\n  this->dataPtr->paramZww         = SdfParamDouble(_sdf, \"zWW\"         , 0);\n  this->dataPtr->paramKp          = SdfParamDouble(_sdf, \"kP\"          , 20);\n  this->dataPtr->paramKpp         = SdfParamDouble(_sdf, \"kPP\"         , 0);\n  this->dataPtr->paramMq          = SdfParamDouble(_sdf, \"mQ\"          , 20);\n  this->dataPtr->paramMqq         = SdfParamDouble(_sdf, \"mQQ\"         , 0);\n  this->dataPtr->paramNr          = SdfParamDouble(_sdf, \"nR\"          , 20);\n  this->dataPtr->paramNrr         = SdfParamDouble(_sdf, \"nRR\"         , 0);\n\n  _sdf->Get<bool>(\"enable_coriolis\", this->dataPtr->enableCoriolis, true);\n\n  // Create model object, to access convenient functions\n  auto model = ignition::gazebo::Model(_entity);\n  auto link_name = _sdf->Get<std::string>(\"link_name\");\n  this->dataPtr->linkEntity = model.LinkByName(_ecm, link_name);\n\n  if (ignition::gazebo::kNullEntity == this->dataPtr->linkEntity)\n  {\n    ignerr << \"Failed to find link named [\" << link_name << \"] in model [\"\n           << model.Name(_ecm) << \"]. Plugin failed to initialize.\" << std::endl;\n    return;\n  }\n\n  this->dataPtr->prevState = Eigen::VectorXd::Zero(6);\n  this->dataPtr->prevStateDot = Eigen::VectorXd::Zero(6);\n\n  AddWorldPose(this->dataPtr->linkEntity, _ecm);\n  AddAngularVelocityComponent(this->dataPtr->linkEntity, _ecm);\n  AddWorldLinearVelocity(this->dataPtr->linkEntity, _ecm);\n\n  std::string ns;\n  std::string currentTopic {\"/ocean_current\"};\n  if (_sdf->HasElement(\"namespace\"))\n  {\n    ns = _sdf->Get<std::string>(\"namespace\");\n    currentTopic = ignition::transport::TopicUtils::AsValidTopic(\n        \"/model/\" + ns + \"/ocean_current\");\n  }\n\n  this->dataPtr->node.Subscribe(\n    currentTopic,\n    &HydrodynamicsPrivateData::UpdateCurrent,\n    this->dataPtr.get());\n\n  if(_sdf->HasElement(\"default_current\"))\n  {\n    this->dataPtr->waterCurrent =\n      _sdf->Get<ignition::math::Vector3d>(\"default_current\");\n  }\n}\n\nvoid HydrodynamicsPlugin::PreUpdate(\n      const ignition::gazebo::UpdateInfo &_info,\n      ignition::gazebo::EntityComponentManager &_ecm)\n{\n  if(_info.paused)\n    return;\n\n  // These variables are named following Fossen's scheme in \"Guidance and Control\n  // of Ocean Vehicles.\" The `state` vector contains the ship's current velocity\n  // in the formate [x_vel, y_vel, z_vel, roll_vel, pitch_vel, yaw_vel].\n  // `stateDot` consists of the first derivative in time of the state vector.\n  // `Cmat` corresponds to the Centripetal matrix\n  // `Dmat` is the drag matrix\n  // `Ma` is the added mass.\n  Eigen::VectorXd stateDot = Eigen::VectorXd(6);\n  Eigen::VectorXd state    = Eigen::VectorXd(6);\n  Eigen::MatrixXd Cmat     = Eigen::MatrixXd::Zero(6, 6);\n  Eigen::MatrixXd Dmat     = Eigen::MatrixXd::Zero(6, 6);\n  Eigen::MatrixXd Ma = Eigen::MatrixXd::Zero(6,6);\n\n  std::lock_guard<std::mutex> lock(this->dataPtr->mtx);\n  // Get vehicle state\n  ignition::gazebo::Link baseLink(this->dataPtr->linkEntity);\n  auto linearVelocity =\n    _ecm.Component<ignition::gazebo::components::WorldLinearVelocity>(this->dataPtr->linkEntity);\n  auto rotationalVelocity = baseLink.WorldAngularVelocity(_ecm);\n\n  if(!linearVelocity)\n  {\n    ignerr <<\"no linear vel\" <<\"\\n\";\n    return;\n  }\n\n  // Transform state to local frame\n  auto pose = baseLink.WorldPose(_ecm);\n  // Since we are transforming angular and linear velocity we only care about\n  // rotation\n  auto localLinearVelocity = pose->Rot().Inverse() *\n    (linearVelocity->Data() - this->dataPtr->waterCurrent);\n  auto localRotationalVelocity = pose->Rot().Inverse() * *rotationalVelocity;\n\n  state(0) = localLinearVelocity.X();\n  state(1) = localLinearVelocity.Y();\n  state(2) = localLinearVelocity.Z();\n\n  state(3) = localRotationalVelocity.X();\n  state(4) = localRotationalVelocity.Y();\n  state(5) = localRotationalVelocity.Z();\n\n  auto dt = (double)_info.dt.count()/1e9;\n\n  auto alpha = 0.9;\n  stateDot = alpha * (state - this->dataPtr->prevState)/dt\n    + (1-alpha) * this->dataPtr->prevStateDot;\n\n  this->dataPtr->prevStateDot = stateDot;\n\n  this->dataPtr->prevState = state;\n\n  // Added mass according to Fossen's equations (p 37)\n  Ma(0,0) = this->dataPtr->paramXdotU;\n  Ma(1,1) = this->dataPtr->paramYdotV;\n  Ma(2,2) = this->dataPtr->paramZdotW;\n  Ma(3,3) = this->dataPtr->paramKdotP;\n  Ma(4,4) = this->dataPtr->paramMdotQ;\n  Ma(5,5) = this->dataPtr->paramNdotR;\n  const Eigen::VectorXd kAmassVec = - Ma * stateDot;\n\n  // Coriollis and Centripetal forces for under water vehicles (Fossen P. 37)\n  // Note: this is significantly different from VRX because we need to account\n  // for the under water vehicle's additional DOF\n  Cmat(0,4) = - this->dataPtr->paramZdotW * state(2);\n  Cmat(0,5) = - this->dataPtr->paramYdotV * state(1);\n  Cmat(1,3) = this->dataPtr->paramZdotW * state(2);\n  Cmat(1,5) = - this->dataPtr->paramXdotU * state(0);\n  Cmat(2,3) = - this->dataPtr->paramYdotV * state(1);\n  Cmat(2,4) = this->dataPtr->paramXdotU * state(0);\n  Cmat(3,1) = - this->dataPtr->paramZdotW * state(2);\n  Cmat(3,2) = this->dataPtr->paramYdotV * state(1);\n  Cmat(3,4) = - this->dataPtr->paramNdotR * state(5);\n  Cmat(3,5) = this->dataPtr->paramMdotQ * state(4);\n  Cmat(4,0) = this->dataPtr->paramZdotW * state(2);\n  Cmat(4,2) = - this->dataPtr->paramXdotU * state(0);\n  Cmat(4,3) = this->dataPtr->paramNdotR * state(5);\n  Cmat(4,5) = - this->dataPtr->paramKdotP * state(3);\n  Cmat(5,0) = this->dataPtr->paramZdotW * state(2);\n  Cmat(5,1) = this->dataPtr->paramXdotU * state(0);\n  Cmat(5,3) = - this->dataPtr->paramMdotQ * state(4);\n  Cmat(5,4) = this->dataPtr->paramKdotP * state(3);\n  const Eigen::VectorXd kCmatVec = - Cmat * state;\n\n  // Damping forces (Fossen P. 43)\n  Dmat(0,0) = - this->dataPtr->paramXu - this->dataPtr->paramXuu * abs(state(0));\n  Dmat(1,1) = - this->dataPtr->paramYv - this->dataPtr->paramYvv * abs(state(1));\n  Dmat(2,2) = - this->dataPtr->paramZw - this->dataPtr->paramZww * abs(state(2));\n  Dmat(3,3) = - this->dataPtr->paramKp - this->dataPtr->paramKpp * abs(state(3));\n  Dmat(4,4) = - this->dataPtr->paramMq - this->dataPtr->paramMqq * abs(state(4));\n  Dmat(5,5) = - this->dataPtr->paramNr - this->dataPtr->paramNrr * abs(state(5));\n\n  const Eigen::VectorXd kDvec = Dmat * state;\n\n  Eigen::VectorXd kTotalWrench = kAmassVec +  kDvec;\n\n  if (this->dataPtr->enableCoriolis)\n    kTotalWrench += kCmatVec;\n\n  ignition::math::Vector3d totalForce(-kTotalWrench(0),  -kTotalWrench(1), -kTotalWrench(2));\n  ignition::math::Vector3d totalTorque(-kTotalWrench(3),  -kTotalWrench(4), -kTotalWrench(5));\n\n  baseLink.AddWorldWrench(_ecm, pose->Rot()*(totalForce), pose->Rot()*totalTorque);\n}\n\n};\n\nIGNITION_ADD_PLUGIN(\n  tethys::HydrodynamicsPlugin,\n  ignition::gazebo::System,\n  tethys::HydrodynamicsPlugin::ISystemConfigure,\n  tethys::HydrodynamicsPlugin::ISystemPreUpdate)\n", "meta": {"hexsha": "52ea9abf27bce9b10f730f9ddee68d0a4e4009ae", "size": 12720, "ext": "cc", "lang": "C++", "max_stars_repo_path": "lrauv_ignition_plugins/src/HydrodynamicsPlugin.cc", "max_stars_repo_name": "osrf/lrauv", "max_stars_repo_head_hexsha": "2efa79e10682def98f8277fe313ffd1488708b1e", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 24.0, "max_stars_repo_stars_event_min_datetime": "2021-11-03T18:45:41.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T17:53:29.000Z", "max_issues_repo_path": "lrauv_ignition_plugins/src/HydrodynamicsPlugin.cc", "max_issues_repo_name": "osrf/lrauv", "max_issues_repo_head_hexsha": "2efa79e10682def98f8277fe313ffd1488708b1e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 105.0, "max_issues_repo_issues_event_min_datetime": "2021-11-04T03:15:55.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T20:48:01.000Z", "max_forks_repo_path": "lrauv_ignition_plugins/src/HydrodynamicsPlugin.cc", "max_forks_repo_name": "osrf/lrauv", "max_forks_repo_head_hexsha": "2efa79e10682def98f8277fe313ffd1488708b1e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-03-18T14:16:47.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-18T14:16:47.000Z", "avg_line_length": 34.4715447154, "max_line_length": 97, "alphanum_fraction": 0.6774371069, "num_tokens": 3887, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6442250928250375, "lm_q2_score": 0.49609382947091946, "lm_q1q2_score": 0.3195960933408314}}
{"text": "//  (C) Copyright Nick Thompson 2019.\n//  Use, modification and distribution are subject to the\n//  Boost Software License, Version 1.0. (See accompanying file\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n#ifndef BOOST_MATH_INTERPOLATORS_DETAIL_CARDINAL_TRIGONOMETRIC_HPP\n#define BOOST_MATH_INTERPOLATORS_DETAIL_CARDINAL_TRIGONOMETRIC_HPP\n#include <cmath>\n#include <stdexcept>\n#include <fftw3.h>\n#include <boost/math/constants/constants.hpp>\n\n#ifdef BOOST_HAS_FLOAT128\n#include <quadmath.h>\n#endif\n\nnamespace boost { namespace math { namespace interpolators { namespace detail {\n\ntemplate<typename Real>\nclass cardinal_trigonometric_detail {\npublic:\n  cardinal_trigonometric_detail(const Real* data, size_t length, Real t0, Real h)\n  {\n    m_data = data;\n    m_length = length;\n    m_t0 = t0;\n    m_h = h;\n    throw std::domain_error(\"Not implemented.\");\n  }\nprivate:\n  size_t m_length;\n  Real m_t0;\n  Real m_h;\n  Real* m_data;\n};\n\ntemplate<>\nclass cardinal_trigonometric_detail<float> {\npublic:\n  cardinal_trigonometric_detail(const float* data, size_t length, float t0, float h) : m_t0{t0}, m_h{h}\n  {\n    if (length == 0)\n    {\n      throw std::logic_error(\"At least one sample is required.\");\n    }\n    if (h <= 0)\n    {\n      throw std::logic_error(\"The step size must be > 0\");\n    }\n    // The period sadly must be stored, since the complex vector has length that cannot be used to recover the period:\n    m_T = m_h*length;\n    m_complex_vector_size = length/2 + 1;\n    m_gamma = fftwf_alloc_complex(m_complex_vector_size);\n    // The const_cast is legitimate: FFTW does not change the data as long as FFTW_ESTIMATE is provided.\n    fftwf_plan plan = fftwf_plan_dft_r2c_1d(length, const_cast<float*>(data), m_gamma, FFTW_ESTIMATE);\n    // FFTW says a null plan is impossible with the basic interface we are using, and I have no reason to doubt them.\n    // But it just feels weird not to check this:\n    if (!plan)\n    {\n      throw std::logic_error(\"A null fftw plan was created.\");\n    }\n\n    fftwf_execute(plan);\n    fftwf_destroy_plan(plan);\n\n    float denom = length;\n    for (size_t k = 0; k < m_complex_vector_size; ++k)\n    {\n      m_gamma[k][0] /= denom;\n      m_gamma[k][1] /= denom;\n    }\n\n    if (length % 2 == 0)\n    {\n      m_gamma[m_complex_vector_size -1][0] /= 2;\n      // numerically, m_gamma[m_complex_vector_size -1][1] should be zero . . .\n      // I believe, but need to check, that FFTW guarantees that it is identically zero.\n    }\n  }\n\n  cardinal_trigonometric_detail(const cardinal_trigonometric_detail& old)  = delete;\n\n  cardinal_trigonometric_detail& operator=(const cardinal_trigonometric_detail&) = delete;\n\n  cardinal_trigonometric_detail(cardinal_trigonometric_detail &&) = delete;\n\n  float operator()(float t) const\n  {\n    using std::sin;\n    using std::cos;\n    using boost::math::constants::two_pi;\n    using std::exp;\n    float s = m_gamma[0][0];\n    float x = two_pi<float>()*(t - m_t0)/m_T;\n    fftwf_complex z;\n    // boost::math::cos_pi with a redefinition of x? Not now . . .\n    z[0] = cos(x);\n    z[1] = sin(x);\n    fftwf_complex b{0, 0};\n    // u = b*z\n    fftwf_complex u;\n    for (size_t k = m_complex_vector_size - 1; k >= 1; --k) {\n      u[0] = b[0]*z[0] - b[1]*z[1];\n      u[1] = b[0]*z[1] + b[1]*z[0];\n      b[0] = m_gamma[k][0] + u[0];\n      b[1] = m_gamma[k][1] + u[1];\n    }\n\n    s += 2*(b[0]*z[0] - b[1]*z[1]);\n    return s;\n  }\n\n  float prime(float t) const\n  {\n      using std::sin;\n      using std::cos;\n      using boost::math::constants::two_pi;\n      using std::exp;\n      float x = two_pi<float>()*(t - m_t0)/m_T;\n      fftwf_complex z;\n      z[0] = cos(x);\n      z[1] = sin(x);\n      fftwf_complex b{0, 0};\n      // u = b*z\n      fftwf_complex u;\n      for (size_t k = m_complex_vector_size - 1; k >= 1; --k)\n      {\n        u[0] = b[0]*z[0] - b[1]*z[1];\n        u[1] = b[0]*z[1] + b[1]*z[0];\n        b[0] = k*m_gamma[k][0] + u[0];\n        b[1] = k*m_gamma[k][1] + u[1];\n      }\n      // b*z = (b[0]*z[0] - b[1]*z[1]) + i(b[1]*z[0] + b[0]*z[1])\n      return -2*two_pi<float>()*(b[1]*z[0] + b[0]*z[1])/m_T;\n  }\n\n  float double_prime(float t) const\n  {\n      using std::sin;\n      using std::cos;\n      using boost::math::constants::two_pi;\n      using std::exp;\n      float x = two_pi<float>()*(t - m_t0)/m_T;\n      fftwf_complex z;\n      z[0] = cos(x);\n      z[1] = sin(x);\n      fftwf_complex b{0, 0};\n      // u = b*z\n      fftwf_complex u;\n      for (size_t k = m_complex_vector_size - 1; k >= 1; --k)\n      {\n        u[0] = b[0]*z[0] - b[1]*z[1];\n        u[1] = b[0]*z[1] + b[1]*z[0];\n        b[0] = k*k*m_gamma[k][0] + u[0];\n        b[1] = k*k*m_gamma[k][1] + u[1];\n      }\n      // b*z = (b[0]*z[0] - b[1]*z[1]) + i(b[1]*z[0] + b[0]*z[1])\n      return -2*two_pi<float>()*two_pi<float>()*(b[0]*z[0] - b[1]*z[1])/(m_T*m_T);\n  }\n\n  float period() const\n  {\n    return m_T;\n  }\n\n  float integrate() const\n  {\n    return m_T*m_gamma[0][0];\n  }\n\n  float squared_l2() const\n  {\n    float s = 0;\n    // Always add smallest to largest for accuracy.\n    for (size_t i = m_complex_vector_size - 1; i >= 1; --i)\n    {\n        s += (m_gamma[i][0]*m_gamma[i][0] + m_gamma[i][1]*m_gamma[i][1]);\n    }\n    s *= 2;\n    s += m_gamma[0][0]*m_gamma[0][0];\n    return s*m_T;\n  }\n\n\n  ~cardinal_trigonometric_detail()\n  {\n    if (m_gamma)\n    {\n      fftwf_free(m_gamma);\n      m_gamma = nullptr;\n    }\n  }\n\n\nprivate:\n  float m_t0;\n  float m_h;\n  float m_T;\n  fftwf_complex* m_gamma;\n  size_t m_complex_vector_size;\n};\n\n\ntemplate<>\nclass cardinal_trigonometric_detail<double> {\npublic:\n  cardinal_trigonometric_detail(const double* data, size_t length, double t0, double h) : m_t0{t0}, m_h{h}\n  {\n    if (length == 0)\n    {\n      throw std::logic_error(\"At least one sample is required.\");\n    }\n    if (h <= 0)\n    {\n      throw std::logic_error(\"The step size must be > 0\");\n    }\n    m_T = m_h*length;\n    m_complex_vector_size = length/2 + 1;\n    m_gamma = fftw_alloc_complex(m_complex_vector_size);\n    fftw_plan plan = fftw_plan_dft_r2c_1d(length, const_cast<double*>(data), m_gamma, FFTW_ESTIMATE);\n    if (!plan)\n    {\n      throw std::logic_error(\"A null fftw plan was created.\");\n    }\n\n    fftw_execute(plan);\n    fftw_destroy_plan(plan);\n\n    double denom = length;\n    for (size_t k = 0; k < m_complex_vector_size; ++k)\n    {\n      m_gamma[k][0] /= denom;\n      m_gamma[k][1] /= denom;\n    }\n\n    if (length % 2 == 0)\n    {\n      m_gamma[m_complex_vector_size -1][0] /= 2;\n    }\n  }\n\n  cardinal_trigonometric_detail(const cardinal_trigonometric_detail& old)  = delete;\n\n  cardinal_trigonometric_detail& operator=(const cardinal_trigonometric_detail&) = delete;\n\n  cardinal_trigonometric_detail(cardinal_trigonometric_detail &&) = delete;\n\n  double operator()(double t) const\n  {\n    using std::sin;\n    using std::cos;\n    using boost::math::constants::two_pi;\n    using std::exp;\n    double s = m_gamma[0][0];\n    double x = two_pi<double>()*(t - m_t0)/m_T;\n    fftw_complex z;\n    z[0] = cos(x);\n    z[1] = sin(x);\n    fftw_complex b{0, 0};\n    // u = b*z\n    fftw_complex u;\n    for (size_t k = m_complex_vector_size - 1; k >= 1; --k)\n    {\n      u[0] = b[0]*z[0] - b[1]*z[1];\n      u[1] = b[0]*z[1] + b[1]*z[0];\n      b[0] = m_gamma[k][0] + u[0];\n      b[1] = m_gamma[k][1] + u[1];\n    }\n\n    s += 2*(b[0]*z[0] - b[1]*z[1]);\n    return s;\n  }\n\n  double prime(double t) const\n  {\n      using std::sin;\n      using std::cos;\n      using boost::math::constants::two_pi;\n      using std::exp;\n      double x = two_pi<double>()*(t - m_t0)/m_T;\n      fftw_complex z;\n      z[0] = cos(x);\n      z[1] = sin(x);\n      fftw_complex b{0, 0};\n      // u = b*z\n      fftw_complex u;\n      for (size_t k = m_complex_vector_size - 1; k >= 1; --k)\n      {\n        u[0] = b[0]*z[0] - b[1]*z[1];\n        u[1] = b[0]*z[1] + b[1]*z[0];\n        b[0] = k*m_gamma[k][0] + u[0];\n        b[1] = k*m_gamma[k][1] + u[1];\n      }\n      // b*z = (b[0]*z[0] - b[1]*z[1]) + i(b[1]*z[0] + b[0]*z[1])\n      return -2*two_pi<double>()*(b[1]*z[0] + b[0]*z[1])/m_T;\n  }\n\n  double double_prime(double t) const\n  {\n      using std::sin;\n      using std::cos;\n      using boost::math::constants::two_pi;\n      using std::exp;\n      double x = two_pi<double>()*(t - m_t0)/m_T;\n      fftw_complex z;\n      z[0] = cos(x);\n      z[1] = sin(x);\n      fftw_complex b{0, 0};\n      // u = b*z\n      fftw_complex u;\n      for (size_t k = m_complex_vector_size - 1; k >= 1; --k)\n      {\n        u[0] = b[0]*z[0] - b[1]*z[1];\n        u[1] = b[0]*z[1] + b[1]*z[0];\n        b[0] = k*k*m_gamma[k][0] + u[0];\n        b[1] = k*k*m_gamma[k][1] + u[1];\n      }\n      // b*z = (b[0]*z[0] - b[1]*z[1]) + i(b[1]*z[0] + b[0]*z[1])\n      return -2*two_pi<double>()*two_pi<double>()*(b[0]*z[0] - b[1]*z[1])/(m_T*m_T);\n  }\n\n  double period() const\n  {\n    return m_T;\n  }\n\n  double integrate() const\n  {\n    return m_T*m_gamma[0][0];\n  }\n\n  double squared_l2() const\n  {\n    double s = 0;\n    for (size_t i = m_complex_vector_size - 1; i >= 1; --i)\n    {\n        s += (m_gamma[i][0]*m_gamma[i][0] + m_gamma[i][1]*m_gamma[i][1]);\n    }\n    s *= 2;\n    s += m_gamma[0][0]*m_gamma[0][0];\n    return s*m_T;\n  }\n\n  ~cardinal_trigonometric_detail()\n  {\n    if (m_gamma)\n    {\n      fftw_free(m_gamma);\n      m_gamma = nullptr;\n    }\n  }\n\nprivate:\n  double m_t0;\n  double m_h;\n  double m_T;\n  fftw_complex* m_gamma;\n  size_t m_complex_vector_size;\n};\n\n\ntemplate<>\nclass cardinal_trigonometric_detail<long double> {\npublic:\n  cardinal_trigonometric_detail(const long double* data, size_t length, long double t0, long double h) : m_t0{t0}, m_h{h}\n  {\n    if (length == 0)\n    {\n      throw std::logic_error(\"At least one sample is required.\");\n    }\n    if (h <= 0)\n    {\n      throw std::logic_error(\"The step size must be > 0\");\n    }\n    m_T = m_h*length;\n    m_complex_vector_size = length/2 + 1;\n    m_gamma = fftwl_alloc_complex(m_complex_vector_size);\n    fftwl_plan plan = fftwl_plan_dft_r2c_1d(length, const_cast<long double*>(data), m_gamma, FFTW_ESTIMATE);\n    if (!plan)\n    {\n      throw std::logic_error(\"A null fftw plan was created.\");\n    }\n\n    fftwl_execute(plan);\n    fftwl_destroy_plan(plan);\n\n    long double denom = length;\n    for (size_t k = 0; k < m_complex_vector_size; ++k)\n    {\n      m_gamma[k][0] /= denom;\n      m_gamma[k][1] /= denom;\n    }\n\n    if (length % 2 == 0) {\n      m_gamma[m_complex_vector_size -1][0] /= 2;\n    }\n  }\n\n  cardinal_trigonometric_detail(const cardinal_trigonometric_detail& old)  = delete;\n\n  cardinal_trigonometric_detail& operator=(const cardinal_trigonometric_detail&) = delete;\n\n  cardinal_trigonometric_detail(cardinal_trigonometric_detail &&) = delete;\n\n  long double operator()(long double t) const\n  {\n    using std::sin;\n    using std::cos;\n    using boost::math::constants::two_pi;\n    using std::exp;\n    long double s = m_gamma[0][0];\n    long double x = two_pi<long double>()*(t - m_t0)/m_T;\n    fftwl_complex z;\n    z[0] = cos(x);\n    z[1] = sin(x);\n    fftwl_complex b{0, 0};\n    fftwl_complex u;\n    for (size_t k = m_complex_vector_size - 1; k >= 1; --k)\n    {\n      u[0] = b[0]*z[0] - b[1]*z[1];\n      u[1] = b[0]*z[1] + b[1]*z[0];\n      b[0] = m_gamma[k][0] + u[0];\n      b[1] = m_gamma[k][1] + u[1];\n    }\n\n    s += 2*(b[0]*z[0] - b[1]*z[1]);\n    return s;\n  }\n\n  long double prime(long double t) const\n  {\n      using std::sin;\n      using std::cos;\n      using boost::math::constants::two_pi;\n      using std::exp;\n      long double x = two_pi<long double>()*(t - m_t0)/m_T;\n      fftwl_complex z;\n      z[0] = cos(x);\n      z[1] = sin(x);\n      fftwl_complex b{0, 0};\n      // u = b*z\n      fftwl_complex u;\n      for (size_t k = m_complex_vector_size - 1; k >= 1; --k)\n      {\n        u[0] = b[0]*z[0] - b[1]*z[1];\n        u[1] = b[0]*z[1] + b[1]*z[0];\n        b[0] = k*m_gamma[k][0] + u[0];\n        b[1] = k*m_gamma[k][1] + u[1];\n      }\n      // b*z = (b[0]*z[0] - b[1]*z[1]) + i(b[1]*z[0] + b[0]*z[1])\n      return -2*two_pi<long double>()*(b[1]*z[0] + b[0]*z[1])/m_T;\n  }\n\n  long double double_prime(long double t) const\n  {\n      using std::sin;\n      using std::cos;\n      using boost::math::constants::two_pi;\n      using std::exp;\n      long double x = two_pi<long double>()*(t - m_t0)/m_T;\n      fftwl_complex z;\n      z[0] = cos(x);\n      z[1] = sin(x);\n      fftwl_complex b{0, 0};\n      // u = b*z\n      fftwl_complex u;\n      for (size_t k = m_complex_vector_size - 1; k >= 1; --k)\n      {\n        u[0] = b[0]*z[0] - b[1]*z[1];\n        u[1] = b[0]*z[1] + b[1]*z[0];\n        b[0] = k*k*m_gamma[k][0] + u[0];\n        b[1] = k*k*m_gamma[k][1] + u[1];\n      }\n      // b*z = (b[0]*z[0] - b[1]*z[1]) + i(b[1]*z[0] + b[0]*z[1])\n      return -2*two_pi<long double>()*two_pi<long double>()*(b[0]*z[0] - b[1]*z[1])/(m_T*m_T);\n  }\n\n  long double period() const\n  {\n    return m_T;\n  }\n\n  long double integrate() const\n  {\n    return m_T*m_gamma[0][0];\n  }\n\n  long double squared_l2() const\n  {\n    long double s = 0;\n    for (size_t i = m_complex_vector_size - 1; i >= 1; --i)\n    {\n        s += (m_gamma[i][0]*m_gamma[i][0] + m_gamma[i][1]*m_gamma[i][1]);\n    }\n    s *= 2;\n    s += m_gamma[0][0]*m_gamma[0][0];\n    return s*m_T;\n  }\n\n  ~cardinal_trigonometric_detail()\n  {\n    if (m_gamma)\n    {\n      fftwl_free(m_gamma);\n      m_gamma = nullptr;\n    }\n  }\n\nprivate:\n  long double m_t0;\n  long double m_h;\n  long double m_T;\n  fftwl_complex* m_gamma;\n  size_t m_complex_vector_size;\n};\n\n#ifdef BOOST_HAS_FLOAT128\ntemplate<>\nclass cardinal_trigonometric_detail<__float128> {\npublic:\n  cardinal_trigonometric_detail(const __float128* data, size_t length, __float128 t0, __float128 h) : m_t0{t0}, m_h{h}\n  {\n    if (length == 0)\n    {\n      throw std::logic_error(\"At least one sample is required.\");\n    }\n    if (h <= 0)\n    {\n      throw std::logic_error(\"The step size must be > 0\");\n    }\n    m_T = m_h*length;\n    m_complex_vector_size = length/2 + 1;\n    m_gamma = fftwq_alloc_complex(m_complex_vector_size);\n    fftwq_plan plan = fftwq_plan_dft_r2c_1d(length, reinterpret_cast<__float128*>(const_cast<__float128*>(data)), m_gamma, FFTW_ESTIMATE);\n    if (!plan)\n    {\n      throw std::logic_error(\"A null fftw plan was created.\");\n    }\n\n    fftwq_execute(plan);\n    fftwq_destroy_plan(plan);\n\n    __float128 denom = length;\n    for (size_t k = 0; k < m_complex_vector_size; ++k)\n    {\n      m_gamma[k][0] /= denom;\n      m_gamma[k][1] /= denom;\n    }\n    if (length % 2 == 0)\n    {\n      m_gamma[m_complex_vector_size -1][0] /= 2;\n    }\n  }\n\n  cardinal_trigonometric_detail(const cardinal_trigonometric_detail& old)  = delete;\n\n  cardinal_trigonometric_detail& operator=(const cardinal_trigonometric_detail&) = delete;\n\n  cardinal_trigonometric_detail(cardinal_trigonometric_detail &&) = delete;\n\n  __float128 operator()(__float128 t) const\n  {\n    using std::sin;\n    using std::cos;\n    using boost::math::constants::two_pi;\n    using std::exp;\n    __float128 s = m_gamma[0][0];\n    __float128 x = two_pi<__float128>()*(t - m_t0)/m_T;\n    fftwq_complex z;\n    z[0] = cosq(x);\n    z[1] = sinq(x);\n    fftwq_complex b{0, 0};\n    fftwq_complex u;\n    for (size_t k = m_complex_vector_size - 1; k >= 1; --k)\n    {\n      u[0] = b[0]*z[0] - b[1]*z[1];\n      u[1] = b[0]*z[1] + b[1]*z[0];\n      b[0] = m_gamma[k][0] + u[0];\n      b[1] = m_gamma[k][1] + u[1];\n    }\n\n    s += 2*(b[0]*z[0] - b[1]*z[1]);\n    return s;\n  }\n\n  __float128 prime(__float128 t) const\n  {\n      using std::sin;\n      using std::cos;\n      using boost::math::constants::two_pi;\n      using std::exp;\n      __float128 x = two_pi<__float128>()*(t - m_t0)/m_T;\n      fftwq_complex z;\n      z[0] = cosq(x);\n      z[1] = sinq(x);\n      fftwq_complex b{0, 0};\n      // u = b*z\n      fftwq_complex u;\n      for (size_t k = m_complex_vector_size - 1; k >= 1; --k)\n      {\n        u[0] = b[0]*z[0] - b[1]*z[1];\n        u[1] = b[0]*z[1] + b[1]*z[0];\n        b[0] = k*m_gamma[k][0] + u[0];\n        b[1] = k*m_gamma[k][1] + u[1];\n      }\n      // b*z = (b[0]*z[0] - b[1]*z[1]) + i(b[1]*z[0] + b[0]*z[1])\n      return -2*two_pi<__float128>()*(b[1]*z[0] + b[0]*z[1])/m_T;\n  }\n\n  __float128 double_prime(__float128 t) const\n  {\n      using std::sin;\n      using std::cos;\n      using boost::math::constants::two_pi;\n      using std::exp;\n      __float128 x = two_pi<__float128>()*(t - m_t0)/m_T;\n      fftwq_complex z;\n      z[0] = cosq(x);\n      z[1] = sinq(x);\n      fftwq_complex b{0, 0};\n      // u = b*z\n      fftwq_complex u;\n      for (size_t k = m_complex_vector_size - 1; k >= 1; --k)\n      {\n        u[0] = b[0]*z[0] - b[1]*z[1];\n        u[1] = b[0]*z[1] + b[1]*z[0];\n        b[0] = k*k*m_gamma[k][0] + u[0];\n        b[1] = k*k*m_gamma[k][1] + u[1];\n      }\n      // b*z = (b[0]*z[0] - b[1]*z[1]) + i(b[1]*z[0] + b[0]*z[1])\n      return -2*two_pi<__float128>()*two_pi<__float128>()*(b[0]*z[0] - b[1]*z[1])/(m_T*m_T);\n  }\n\n  __float128 period() const\n  {\n    return m_T;\n  }\n\n  __float128 integrate() const\n  {\n    return m_T*m_gamma[0][0];\n  }\n\n  __float128 squared_l2() const\n  {\n    __float128 s = 0;\n    for (size_t i = m_complex_vector_size - 1; i >= 1; --i)\n    {\n      s += (m_gamma[i][0]*m_gamma[i][0] + m_gamma[i][1]*m_gamma[i][1]);\n    }\n    s *= 2;\n    s += m_gamma[0][0]*m_gamma[0][0];\n    return s*m_T;\n  }\n\n  ~cardinal_trigonometric_detail()\n  {\n    if (m_gamma)\n    {\n      fftwq_free(m_gamma);\n      m_gamma = nullptr;\n    }\n  }\n\n\nprivate:\n  __float128 m_t0;\n  __float128 m_h;\n  __float128 m_T;\n  fftwq_complex* m_gamma;\n  size_t m_complex_vector_size;\n};\n#endif\n\n}}}}\n#endif\n", "meta": {"hexsha": "e7b239ad907747108f9721182da9ad278dd0a825", "size": 17471, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ReactNativeFrontend/ios/Pods/boost/boost/math/interpolators/detail/cardinal_trigonometric_detail.hpp", "max_stars_repo_name": "Harshitha91/Tmdb-react-native-node", "max_stars_repo_head_hexsha": "e06e3f25a7ee6946ef07a1f524fdf62e48424293", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 597.0, "max_stars_repo_stars_event_min_datetime": "2018-07-17T10:59:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T07:59:36.000Z", "max_issues_repo_path": "ReactNativeFrontend/ios/Pods/boost/boost/math/interpolators/detail/cardinal_trigonometric_detail.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/math/interpolators/detail/cardinal_trigonometric_detail.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": 112.0, "max_forks_repo_forks_event_min_datetime": "2018-07-26T04:36:34.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T02:29:34.000Z", "avg_line_length": 25.8064992614, "max_line_length": 138, "alphanum_fraction": 0.5602999256, "num_tokens": 6120, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7772998611746911, "lm_q2_score": 0.411110869232168, "lm_q1q2_score": 0.31955642158157077}}
{"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 inf.ethz.ch)\n\n#include \"estimators/affine_transform.h\"\n\n#include <Eigen/SVD>\n\n#include \"util/logging.h\"\n\nnamespace colmap {\n\nstd::vector<AffineTransformEstimator::M_t> AffineTransformEstimator::Estimate(\n    const std::vector<X_t>& points1, const std::vector<Y_t>& points2) {\n  CHECK_EQ(points1.size(), points2.size());\n  CHECK_GE(points1.size(), 3);\n\n  // Sets up the linear system that we solve to obtain a least squared solution\n  // for the affine transformation.\n  Eigen::MatrixXd C(2 * points1.size(), 6);\n  C.setZero();\n  Eigen::VectorXd b(2 * points1.size(), 1);\n\n  for (size_t i = 0; i < points1.size(); ++i) {\n    const Eigen::Vector2d& x1 = points1[i];\n    const Eigen::Vector2d& x2 = points2[i];\n\n    C(2 * i, 0) = x1(0);\n    C(2 * i, 1) = x1(1);\n    C(2 * i, 2) = 1.0f;\n    b(2 * i) = x2(0);\n\n    C(2 * i + 1, 3) = x1(0);\n    C(2 * i + 1, 4) = x1(1);\n    C(2 * i + 1, 5) = 1.0f;\n    b(2 * i + 1) = x2(1);\n  }\n\n  const Eigen::VectorXd nullspace =\n      C.jacobiSvd(Eigen::ComputeThinU | Eigen::ComputeThinV).solve(b);\n\n  Eigen::Map<const Eigen::Matrix<double, 3, 2>> A_t(nullspace.data());\n\n  const std::vector<M_t> models = {A_t.transpose()};\n  return models;\n}\n\nvoid AffineTransformEstimator::Residuals(const std::vector<X_t>& points1,\n                                         const std::vector<Y_t>& points2,\n                                         const M_t& A,\n                                         std::vector<double>* residuals) {\n  CHECK_EQ(points1.size(), points2.size());\n\n  residuals->resize(points1.size());\n\n  // Note that this code might not be as nice as Eigen expressions,\n  // but it is significantly faster in various tests.\n\n  const double A_00 = A(0, 0);\n  const double A_01 = A(0, 1);\n  const double A_02 = A(0, 2);\n  const double A_10 = A(1, 0);\n  const double A_11 = A(1, 1);\n  const double A_12 = A(1, 2);\n\n  for (size_t i = 0; i < points1.size(); ++i) {\n    const double s_0 = points1[i](0);\n    const double s_1 = points1[i](1);\n    const double d_0 = points2[i](0);\n    const double d_1 = points2[i](1);\n\n    const double pd_0 = A_00 * s_0 + A_01 * s_1 + A_02;\n    const double pd_1 = A_10 * s_0 + A_11 * s_1 + A_12;\n\n    const double dd_0 = d_0 - pd_0;\n    const double dd_1 = d_1 - pd_1;\n\n    (*residuals)[i] = dd_0 * dd_0 + dd_1 * dd_1;\n  }\n}\n\n}  // namespace colmap\n", "meta": {"hexsha": "fdf467f7db28acb5fcc26470c67bb1a0aab397a1", "size": 3992, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/estimators/affine_transform.cc", "max_stars_repo_name": "sunbirddy/colmap", "max_stars_repo_head_hexsha": "9099ccedd5a1d6ad209f9e37c45f2a3291326528", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2021-11-15T09:56:21.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-28T07:31:37.000Z", "max_issues_repo_path": "src/estimators/affine_transform.cc", "max_issues_repo_name": "sunbirddy/colmap", "max_issues_repo_head_hexsha": "9099ccedd5a1d6ad209f9e37c45f2a3291326528", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-12-28T06:39:57.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-28T06:39:57.000Z", "max_forks_repo_path": "src/estimators/affine_transform.cc", "max_forks_repo_name": "sunbirddy/colmap", "max_forks_repo_head_hexsha": "9099ccedd5a1d6ad209f9e37c45f2a3291326528", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-09-11T20:22:49.000Z", "max_forks_repo_forks_event_max_datetime": "2019-09-11T20:22:49.000Z", "avg_line_length": 36.2909090909, "max_line_length": 79, "alphanum_fraction": 0.6563126253, "num_tokens": 1118, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6150878414043814, "lm_q2_score": 0.519521321952093, "lm_q1q2_score": 0.31955124848306354}}
{"text": "#include <GL/freeglut.h>\n#include <vector>\n#include <Eigen/Eigen>\n#include <iostream>\n#include <iomanip>\n\n#include \"../../example_func_x_jacobian.h\"\n#include \"../../constraints_jacobian.h\"\n\n#define RENDER_PSI 0\n#define RENDER_OBJECTIVE_FUNC 1\n#define RENDER_OBJECTIVE_FUNC_WITH_CONTRAINT 2\n\nint render_type = RENDER_PSI;\n\n\nconst unsigned int window_width = 1920;\nconst unsigned int window_height = 1080;\nint mouse_old_x, mouse_old_y;\nint mouse_buttons = 0;\nfloat rotate_x = 0.0, rotate_y = 0.0;\nfloat translate_z = -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\ndouble x_result = 0;\ndouble x_trg = 1;\n\nstd::vector<double> path_result;\ndouble contraint_a = 1.0;\ndouble contraint_x_trg = 3;\ndouble weight_constraint = 1;\nint constraint_type = 0;\n\nvoid obs_eq_constraint(double &delta, double a, double x, double x_trg, int type)\n{\n\tif(type == 0){\n\t\tobservation_equation_constraint(delta, a, x, x_trg);\n\t}else{\n\t\tobservation_equation_sq_constraint(delta, a, x, x_trg);\n\t}\n}\nvoid obs_eq_constraint_jacobian(Eigen::Matrix<double, 1, 1> &j, double a, double x, double x_trg, int type)\n{\n\tif(type == 0){\n\t\tobservation_equation_constraint_jacobian(j, a, x, x_trg);\n\t}else{\n\t\tobservation_equation_sq_constraint_jacobian(j, a, x, x_trg);\n\t}\n}\n\nint main(int argc, char *argv[]){\n\tpath_result.push_back(x_result);\n\tif (false == initGL(&argc, argv)) {\n\t\treturn 4;\n\t}\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(\"simple_optimization_problem_func_x_with_constraints\");\n\tglutDisplayFunc(display);\n\tglutKeyboardFunc(keyboard);\n\tglutMotionFunc(motion);\n\n\t// default initialization\n\tglClearColor(1.0, 1.0, 1.0, 1.0);\n\tglEnable(GL_DEPTH_TEST);\n\n\t// viewport\n\tglViewport(0, 0, window_width, window_height);\n\n\t// projection\n\tglMatrixMode(GL_PROJECTION);\n\tglLoadIdentity();\n\tgluPerspective(60.0, (GLfloat) window_width / (GLfloat) window_height, 0.01,\n\t\t\t10000.0);\n\tglutReshapeFunc(reshape);\n\n\treturn true;\n}\n\nvoid display() {\n\tglClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);\n\n\tglMatrixMode(GL_MODELVIEW);\n\tglLoadIdentity();\n\tglTranslatef(translate_x, translate_y, translate_z);\n\tglRotatef(rotate_x, 1.0, 0.0, 0.0);\n\tglRotatef(rotate_y, 0.0, 0.0, 1.0);\n\n\tglLineWidth(2);\n\n\tswitch(render_type){\n\t\tcase RENDER_PSI:{\n\t\t\tglColor3f(1,0,0);\n\t\t\tglBegin(GL_LINE_STRIP);\n\t\t\tfor(double x = -1000; x <=1000; x+=0.01){\n\t\t\t\tdouble y;\n\t\t\t\texample_func_x(y,x);\n\t\t\t\tglVertex3f(x,y,0);\n\t\t\t}\n\t\t\tglEnd();\n\n\t\t\tglPointSize(20);\n\t\t\tglColor3f(0,0,1);\n\t\t\tglBegin(GL_POINTS);\n\t\t\t\tdouble y;\n\t\t\t\texample_func_x(y,x_result);\n\t\t\t\tglVertex3f(x_result, y, 0);\n\t\t\tglEnd();\n\t\t\tglPointSize(1);\n\n\t\t\tglColor3f(0,1,0);\n\t\t\tglBegin(GL_LINE_STRIP);\n\t\t\tfor(const auto &x:path_result){\n\t\t\t\tdouble y;\n\t\t\t\texample_func_x(y,x);\n\t\t\t\tglVertex3f(x,y,0);\n\t\t\t}\n\t\t\tglEnd();\n\n\t\t\tglColor3f(0,0,1);\n\t\t\tglBegin(GL_LINE_STRIP);\n\t\t\tfor(double x = -1000; x <=1000; x+=0.01){\n\t\t\t\tdouble c;\n\t\t\t\tobs_eq_constraint(c,contraint_a,x,contraint_x_trg, constraint_type);\n\t\t\t\tglVertex3f(x,c,0);\n\t\t\t}\n\t\t\tglEnd();\n\n\t\t\tglColor3f(0,0,0);\n\t\t\tglBegin(GL_LINES);\n\t\t\t\tglVertex3f(-1000, x_trg, 0);\n\t\t\t\tglVertex3f(1000, x_trg, 0);\n\t\t\tglEnd();\n\t\tbreak;\n\t\t}\n\t\tcase RENDER_OBJECTIVE_FUNC:{\n\t\t\tglColor3f(1,0,0);\n\t\t\tglBegin(GL_LINE_STRIP);\n\t\t\tfor(double x = -1000; x <=1000; x+=0.01){\n\t\t\t\tdouble y;\n\t\t\t\tobservation_equation_example_func_x(y,x,x_trg);\n\t\t\t\tglVertex3f(x,y*y,0);\n\t\t\t}\n\t\t\tglEnd();\n\n\t\t\tglPointSize(20);\n\t\t\tglColor3f(0,0,1);\n\t\t\tglBegin(GL_POINTS);\n\t\t\t\tdouble y;\n\t\t\t\tobservation_equation_example_func_x(y,x_result,x_trg);\n\t\t\t\tglVertex3f(x_result, y*y, 0);\n\t\t\tglEnd();\n\t\t\tglPointSize(1);\n\n\t\t\tglColor3f(0,1,0);\n\t\t\tglBegin(GL_LINE_STRIP);\n\t\t\tfor(const auto &x:path_result){\n\t\t\t\tdouble y;\n\t\t\t\tobservation_equation_example_func_x(y,x,x_trg);\n\t\t\t\tglVertex3f(x,y*y,0);\n\t\t\t}\n\t\t\tglEnd();\n\n\t\t\tglColor3f(0,0,1);\n\t\t\tglBegin(GL_LINE_STRIP);\n\t\t\tfor(double x = -1000; x <=1000; x+=0.01){\n\t\t\t\tdouble c;\n\t\t\t\tobs_eq_constraint(c,contraint_a,x,contraint_x_trg, constraint_type);\n\t\t\t\tglVertex3f(x,c*c,0);\n\t\t\t}\n\t\t\tglEnd();\n\n\t\t\tglColor3f(0,0,0);\n\t\t\tglBegin(GL_LINES);\n\t\t\t\tglVertex3f(-1000, 0, 0);\n\t\t\t\tglVertex3f(1000, 0, 0);\n\t\t\tglEnd();\n\t\t\tbreak;\n\t\t}\n\t\tcase RENDER_OBJECTIVE_FUNC_WITH_CONTRAINT:{\n\t\t\tglColor3f(1,0,0);\n\t\t\tglBegin(GL_LINE_STRIP);\n\t\t\tfor(double x = -1000; x <=1000; x+=0.01){\n\t\t\t\tdouble y;\n\t\t\t\tobservation_equation_example_func_x(y,x,x_trg);\n\t\t\t\tdouble c;\n\t\t\t\tobs_eq_constraint(c,contraint_a,x,contraint_x_trg, constraint_type);\n\t\t\t\tglVertex3f(x,y*y + c*c,0);\n\t\t\t}\n\t\t\tglEnd();\n\n\t\t\tglPointSize(20);\n\t\t\tglColor3f(0,0,1);\n\t\t\tglBegin(GL_POINTS);\n\t\t\t\tdouble y;\n\t\t\t\tobservation_equation_example_func_x(y,x_result,x_trg);\n\t\t\t\tdouble c;\n\t\t\t\tobs_eq_constraint(c,contraint_a,x_result,contraint_x_trg, constraint_type);\n\t\t\t\tglVertex3f(x_result, y*y + c*c,0);\n\t\t\tglEnd();\n\t\t\tglPointSize(1);\n\n\t\t\tglColor3f(0,1,0);\n\t\t\tglBegin(GL_LINE_STRIP);\n\t\t\tfor(const auto &x:path_result){\n\t\t\t\tdouble y;\n\t\t\t\tobservation_equation_example_func_x(y,x,x_trg);\n\t\t\t\tdouble c;\n\t\t\t\tobs_eq_constraint(c,contraint_a,x,contraint_x_trg, constraint_type);\n\t\t\t\tglVertex3f(x,y*y + c*c,0);\n\t\t\t}\n\t\t\tglEnd();\n\n\t\t\tglColor3f(0,0,0);\n\t\t\tglBegin(GL_LINES);\n\t\t\t\tglVertex3f(-1000, 0, 0);\n\t\t\t\tglVertex3f(1000, 0, 0);\n\t\t\tglEnd();\n\t\t\tbreak;\n\t\t}\n\t}\n\tglutSwapBuffers();\n}\n\n\n\nvoid keyboard(unsigned char key, int /*x*/, int /*y*/) {\n\tswitch (key) {\n\t\tcase (27): {\n\t\t\tglutDestroyWindow(glutGetWindow());\n\t\t\treturn;\n\t\t}\n\t\tcase 'o':{\n\t\t\tstd::vector<Eigen::Triplet<double>> tripletListA;\n\t\t\tstd::vector<Eigen::Triplet<double>> tripletListP;\n\t\t\tstd::vector<Eigen::Triplet<double>> tripletListB;\n\n\t\t\tdouble delta;\n\t\t\tobservation_equation_example_func_x(delta, x_result, x_trg);\n\n\t\t\tEigen::Matrix<double, 1, 1> jacobian;\n\t\t\tobservation_equation_example_func_x_jacobian(jacobian, x_result);\n\n\t\t\tint ir = 0;\n\t\t\tint ic = 0;\n\t\t\ttripletListA.emplace_back(ir, ic, -jacobian(0,0));\n\t\t\ttripletListP.emplace_back(ir, ir,  1);\n\t\t\ttripletListB.emplace_back(ir, 0,  delta);\n\n\t\t\tint number_of_columns = 1;\n\t\t\tEigen::SparseMatrix<double> matA(tripletListB.size(), number_of_columns);\n\t\t\tEigen::SparseMatrix<double> matP(tripletListB.size(), tripletListB.size());\n\t\t\tEigen::SparseMatrix<double> matB(tripletListB.size(), 1);\n\n\t\t\tmatA.setFromTriplets(tripletListA.begin(), tripletListA.end());\n\t\t\tmatP.setFromTriplets(tripletListP.begin(), tripletListP.end());\n\t\t\tmatB.setFromTriplets(tripletListB.begin(), tripletListB.end());\n\n\t\t\tEigen::SparseMatrix<double> AtPA(number_of_columns, number_of_columns);\n\t\t\tEigen::SparseMatrix<double> AtPB(number_of_columns, 1);\n\n\t\t\t{\n\t\t\tEigen::SparseMatrix<double> AtP = matA.transpose() * matP;\n\t\t\tAtPA = (AtP) * matA;\n\t\t\tAtPB = (AtP) * matB;\n\t\t\t}\n\n\t\t\tstd::cout << \"AtPA.size: \" << AtPA.size() << std::endl;\n\t\t\tstd::cout << \"AtPB.size: \" << AtPB.size() << std::endl;\n\n\t\t\tstd::cout << \"start solving AtPA=AtPB\" << std::endl;\n\t\t\tEigen::SimplicialCholesky<Eigen::SparseMatrix<double>> solver(AtPA);\n\n\t\t\tstd::cout << \"x = solver.solve(AtPB)\" << std::endl;\n\t\t\tEigen::SparseMatrix<double> x = solver.solve(AtPB);\n\n\t\t\tstd::vector<double> h_x;\n\n\t\t\tfor (int k=0; k<x.outerSize(); ++k){\n\t\t\t\tfor (Eigen::SparseMatrix<double>::InnerIterator it(x,k); it; ++it){\n\t\t\t\t\th_x.push_back(it.value());\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif(h_x.size() == number_of_columns){\n\t\t\t\tfor(size_t i = 0 ; i < h_x.size(); i++){\n\t\t\t\t\tstd::cout << h_x[i] << std::endl;\n\t\t\t\t}\n\t\t\t\tstd::cout << \"AtPA=AtPB SOLVED\" << std::endl;\n\t\t\t\tstd::cout << \"update\" << std::endl;\n\n\t\t\t\tx_result += h_x[0];\n\t\t\t\tpath_result.push_back(x_result);\n\t\t\t}else{\n\t\t\t\tstd::cout << \"AtPA=AtPB FAILED\" << std::endl;\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t\tcase 'c':{\n\t\t\tstd::vector<Eigen::Triplet<double>> tripletListA;\n\t\t\tstd::vector<Eigen::Triplet<double>> tripletListP;\n\t\t\tstd::vector<Eigen::Triplet<double>> tripletListB;\n\n\t\t\tdouble delta;\n\t\t\tobservation_equation_example_func_x(delta, x_result, x_trg);\n\n\t\t\tEigen::Matrix<double, 1, 1> jacobian;\n\t\t\tobservation_equation_example_func_x_jacobian(jacobian, x_result);\n\n\t\t\tint ir = 0;\n\t\t\tint ic = 0;\n\t\t\ttripletListA.emplace_back(ir, ic, -jacobian(0,0));\n\t\t\ttripletListP.emplace_back(ir, ir,  1.0);\n\t\t\ttripletListB.emplace_back(ir, 0,  delta);\n\n\t\t\tir = tripletListB.size();\n\t\t\tobs_eq_constraint(delta, contraint_a, x_result, contraint_x_trg, constraint_type);\n\t\t    obs_eq_constraint_jacobian(jacobian, contraint_a, x_result, contraint_x_trg, constraint_type);\n\t\t    tripletListA.emplace_back(ir, ic,  -jacobian(0,0));\n\t\t\ttripletListP.emplace_back(ir, ir,  weight_constraint);\n\t\t\ttripletListB.emplace_back(ir, 0,  delta);\n\n\t\t\tint number_of_columns = 1;\n\t\t\tEigen::SparseMatrix<double> matA(tripletListB.size(), number_of_columns);\n\t\t\tEigen::SparseMatrix<double> matP(tripletListB.size(), tripletListB.size());\n\t\t\tEigen::SparseMatrix<double> matB(tripletListB.size(), 1);\n\n\t\t\tmatA.setFromTriplets(tripletListA.begin(), tripletListA.end());\n\t\t\tmatP.setFromTriplets(tripletListP.begin(), tripletListP.end());\n\t\t\tmatB.setFromTriplets(tripletListB.begin(), tripletListB.end());\n\n\t\t\tEigen::SparseMatrix<double> AtPA(number_of_columns, number_of_columns);\n\t\t\tEigen::SparseMatrix<double> AtPB(number_of_columns, 1);\n\n\t\t\t{\n\t\t\tEigen::SparseMatrix<double> AtP = matA.transpose() * matP;\n\t\t\tAtPA = (AtP) * matA;\n\t\t\tAtPB = (AtP) * matB;\n\t\t\t}\n\n\t\t\tstd::cout << \"AtPA.size: \" << AtPA.size() << std::endl;\n\t\t\tstd::cout << \"AtPB.size: \" << AtPB.size() << std::endl;\n\n\t\t\tstd::cout << \"start solving AtPA=AtPB\" << std::endl;\n\t\t\tEigen::SimplicialCholesky<Eigen::SparseMatrix<double>> solver(AtPA);\n\n\t\t\tstd::cout << \"x = solver.solve(AtPB)\" << std::endl;\n\t\t\tEigen::SparseMatrix<double> x = solver.solve(AtPB);\n\n\t\t\tstd::vector<double> h_x;\n\n\t\t\tfor (int k=0; k<x.outerSize(); ++k){\n\t\t\t\tfor (Eigen::SparseMatrix<double>::InnerIterator it(x,k); it; ++it){\n\t\t\t\t\th_x.push_back(it.value());\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif(h_x.size() == number_of_columns){\n\t\t\t\tfor(size_t i = 0 ; i < h_x.size(); i++){\n\t\t\t\t\tstd::cout << h_x[i] << std::endl;\n\t\t\t\t}\n\t\t\t\tstd::cout << \"AtPA=AtPB SOLVED\" << std::endl;\n\t\t\t\tstd::cout << \"update\" << std::endl;\n\n\t\t\t\tx_result += h_x[0];\n\t\t\t\tpath_result.push_back(x_result);\n\t\t\t}else{\n\t\t\t\tstd::cout << \"AtPA=AtPB FAILED\" << std::endl;\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t\tcase 'r':{\n\t\t\tx_result = ((rand()%1000000)/1000000.0f - 0.5) * 2.0 * 20;\n\t\t\tpath_result.clear();\n\t\t\tpath_result.push_back(x_result);\n\t\t\tbreak;\n\t\t}\n\t\tcase '-':{\n\t\t\tcontraint_a -= 0.01;\n\t\t\tif(contraint_a < 0)contraint_a= 0.01;\n\t\t\tbreak;\n\t\t}\n\t\tcase '=':{\n\t\t\tcontraint_a += 0.01;\n\t\t\tbreak;\n\t\t}\n\t\tcase 'd':{\n\t\t\tcontraint_x_trg -= 0.1;\n\t\t\tbreak;\n\t\t}\n\t\tcase 'i':{\n\t\t\tcontraint_x_trg += 0.1;\n\t\t\tbreak;\n\t\t}\n\t\tcase '1':{\n\t\t\trender_type = RENDER_PSI;\n\t\t\tbreak;\n\t\t}\n\t\tcase '2':{\n\t\t\trender_type = RENDER_OBJECTIVE_FUNC;\n\t\t\tbreak;\n\t\t}\n\t\tcase '3':{\n\t\t\trender_type = RENDER_OBJECTIVE_FUNC_WITH_CONTRAINT;\n\t\t\tbreak;\n\t\t}\n\t\tcase 'y':{\n\t\t\tx_trg += 0.1;\n\t\t\tstd::cout << \"x_trg: \" << x_trg << std::endl;\n\t\t\tbreak;\n\t\t}\n\t\tcase 't':{\n\t\t\tx_trg -= 0.1;\n\t\t\tstd::cout << \"x_trg: \" << x_trg << std::endl;\n\t\t\tbreak;\n\t\t}\n\t\tcase 'q':{\n\t\t\tx_result-=0.1;\n\t\t\tpath_result.clear();\n\t\t\tpath_result.push_back(x_result);\n\t\t\tbreak;\n\t\t}\n\t\tcase 'w':{\n\t\t\tx_result+=0.1;\n\t\t\tpath_result.clear();\n\t\t\tpath_result.push_back(x_result);\n\t\t\tbreak;\n\t\t}\n\t\tcase '4':{\n\t\t\tconstraint_type = 0;\n\t\t\tbreak;\n\t\t}\n\t\tcase '5':{\n\t\t\tconstraint_type = 1;\n\t\t\tbreak;\n\t\t}\n\t\tcase '6':{\n\t\t\tweight_constraint /=10;\n\t\t\tstd::cout << \"weight_constraint: \" << weight_constraint << std::endl;\n\t\t\tbreak;\n\t\t}\n\t\tcase '7':{\n\t\t\tweight_constraint *=10;\n\t\t\tstd::cout << \"weight_constraint: \" << weight_constraint << std::endl;\n\t\t\tbreak;\n\t\t}\n\t}\n\tprintHelp();\n\tglutPostRedisplay();\n}\n\n\nvoid mouse(int button, int state, int x, int y) {\n\tif (state == GLUT_DOWN) {\n\t\tmouse_buttons |= 1 << button;\n\t} else if (state == GLUT_UP) {\n\t\tmouse_buttons = 0;\n\t}\n\n\tmouse_old_x = x;\n\tmouse_old_y = y;\n}\n\nvoid motion(int x, int y) {\n\tfloat dx, dy;\n\tdx = (float) (x - mouse_old_x);\n\tdy = (float) (y - mouse_old_y);\n\n\tif (mouse_buttons & 1) {\n\t\trotate_x += dy * 0.2f;\n\t\trotate_y += dx * 0.2f;\n\n\t} else if (mouse_buttons & 4) {\n\t\ttranslate_z += dy * 0.05f;\n\t} else if (mouse_buttons & 3) {\n\t\ttranslate_x += dx * 0.05f;\n\t\ttranslate_y -= dy * 0.05f;\n\t}\n\n\tmouse_old_x = x;\n\tmouse_old_y = y;\n\n\tglutPostRedisplay();\n}\n\nvoid reshape(int w, int h) {\n\tglViewport(0, 0, (GLsizei) w, (GLsizei) h);\n\tglMatrixMode(GL_PROJECTION);\n\tglLoadIdentity();\n\tgluPerspective(60.0, (GLfloat) w / (GLfloat) h, 0.01, 10000.0);\n\tglMatrixMode(GL_MODELVIEW);\n\tglLoadIdentity();\n}\n\nvoid printHelp() {\n\tstd::cout << \"-------help-------\" << std::endl;\n\tstd::cout << \"o: optimize\" << std::endl;\n\tstd::cout << \"c: optimize with constaint\" << std::endl;\n\tstd::cout << \"-: contraint_a -= 0.01\" << std::endl;\n\tstd::cout << \"=: contraint_a += 0.01\" << std::endl;\n\tstd::cout << \"d: contraint_x_trg -= 0.1\" << std::endl;\n\tstd::cout << \"i: contraint_x_trg += 0.1\" << std::endl;\n\tstd::cout << \"1: RENDER_PSI\" << std::endl;\n\tstd::cout << \"2: RENDER_OBJECTIVE_FUNC\" << std::endl;\n\tstd::cout << \"3: RENDER_OBJECTIVE_FUNC_WITH_CONTRAINT\" << std::endl;\n\tstd::cout << \"y: x_trg += 0.1\" << std::endl;\n\tstd::cout << \"t: x_trg -= 0.1\" << std::endl;\n\tstd::cout << \"q: x_result-=0.1\" << std::endl;\n\tstd::cout << \"w: x_result+=0.1\" << std::endl;\n\tstd::cout << \"4: constraint_type linear\" << std::endl;\n\tstd::cout << \"5: constraint_type squared\" << std::endl;\n\tstd::cout << \"6: weight_constraint /=10\" << std::endl;\n\tstd::cout << \"7: weight_constraint *=10\" << std::endl;\n\tstd::cout << \"r: random initial guess\" << std::endl;\n}\n\n\n\n\n\n\n\n", "meta": {"hexsha": "97aa67dc134c2d62cdb575e8395021292bbf4c06", "size": 13721, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "codes/c++Examples/src/simple_optimization_problem_func_x_with_constraints.cpp", "max_stars_repo_name": "michalpelka/observation_equations", "max_stars_repo_head_hexsha": "023ba4cd57d738447ed118279fdb4c06ae5746f8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "codes/c++Examples/src/simple_optimization_problem_func_x_with_constraints.cpp", "max_issues_repo_name": "michalpelka/observation_equations", "max_issues_repo_head_hexsha": "023ba4cd57d738447ed118279fdb4c06ae5746f8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "codes/c++Examples/src/simple_optimization_problem_func_x_with_constraints.cpp", "max_forks_repo_name": "michalpelka/observation_equations", "max_forks_repo_head_hexsha": "023ba4cd57d738447ed118279fdb4c06ae5746f8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.2688766114, "max_line_length": 107, "alphanum_fraction": 0.6522119379, "num_tokens": 4466, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5926665999540698, "lm_q2_score": 0.5389832206876841, "lm_q1q2_score": 0.31943735283726377}}
{"text": "#include <cassert>\n#include <iostream>\n#include <fstream>\n#include <sstream>\n#include <cmath>\n#include <iomanip>\n#include <armadillo>\n\n#include \"constant.hpp\"\n#include \"mt_random.hpp\"\n\nusing namespace std;\n\nnamespace willow {\n\n// global variables\nconst  int m_nnhc  = 4;\nstatic int m_nbead;\nstatic int m_nstep;\nstatic int m_irst;\nstatic int m_nref;\nstatic double m_dt;\nstatic double m_dt_ref;\nstatic double m_gfree_nm;\n\nstatic double m_Dmorse; // (De) in Morse potential: De (1 - exp(-a*x))**2\nstatic double m_ZPE;\nstatic double m_omega;\nstatic double m_omega_p2;\nstatic double m_temp_nm;\nstatic double m_beta_nm;\nstatic double m_ekin_nm;\n\nconst  double delt_x = 4.e-3;\n\nstatic arma::vec prob_dx;      // (0:399)\n\nstatic double     m_mass;     \n\nstatic arma::mat  m_tmat_nm;  // (m_nbead, m_nbead)\nstatic arma::vec  m_fict_mass;// (m_nbead)\n\nstatic arma::vec  m_rbath_nm; // (m_nnhc)\nstatic arma::mat  m_vbath_nm; //\nstatic arma::mat  m_qmass_nm; //\n\n// one-dimensional system\n// Cartesian Coordinate \nstatic arma::vec  m_pos_qm;   // (m_nbead)\nstatic arma::vec  m_grd_qm;   // (m_nbead)\n\n// Normal Mode\nstatic arma::vec  m_pos_nm;   // (m_nbead)\nstatic arma::vec  m_vel_nm;   // (m_nbead)\nstatic arma::vec  m_grd_nm;   // (m_nbead)\nstatic arma::vec  m_grd_nm_spr; //(m_nbead)\n  \n\nstatic void sample_rho ()\n{\n\n  // QM (beads)\n  \n  for (auto ib = 0; ib < m_nbead; ++ib) {\n\n    // distribution of beads around pos(0) \n    // \\rho(x) = \\varrho (x1 - X1)  \n    double dx   = m_pos_qm(ib); \n    int    id1  = (int) round(dx/delt_x) + 200;\n    if (id1 >= 0 && id1 < 400) prob_dx (id1) += 1;\n    \n  }\n  \n}\n\n\nvoid nm_nhc_integrate ()\n{\n  // Nose-Hoover Chain Method\n  \n  const double dt_ref  = m_dt_ref;\n  const double dt_ref2 = 0.5*dt_ref;\n  const double dt_ref4 = 0.5*dt_ref2;\n  const double dt_ref8 = 0.5*dt_ref4;\n\n  // m_nnhc = 4\n  arma::vec4 rbath;\n  arma::vec4 vbath;\n  arma::vec4 fbath;\n  arma::vec4 qmass;\n  \n  \n  // ---\n  // \n  double ekin_nm = 0.0;\n  \n  for (size_t ib = 1; ib < m_nbead; ++ib) {\n    \n    double mass = m_fict_mass (ib);\n    double v    = m_vel_nm(ib);\n    \n    ekin_nm += mass * v * v;\n      \n  }\n\n  //---\n    \n  vbath = m_vbath_nm;\n  rbath = m_rbath_nm;\n  qmass = m_qmass_nm;\n\n  // ihc = 0\n  fbath(0) = (ekin_nm - m_gfree_nm*m_ekin_nm)/qmass(0);\n    \n  for (size_t ihc = 1; ihc < m_nnhc; ++ihc) {\n    fbath(ihc) =\n      (qmass(ihc-1)*vbath(ihc-1)*vbath(ihc-1)\t- m_ekin_nm) / qmass(ihc);\n  }\n  \n  // Update Thermostat Velocities\n  \n  vbath(m_nnhc-1) = vbath(m_nnhc-1) + fbath(m_nnhc-1)*dt_ref4;\n    \n  for (auto ihc = 1; ihc < m_nnhc; ++ihc) {\n    const auto jhc     = m_nnhc - ihc;\n    const double vfact = exp (-vbath(jhc)*dt_ref8);\n    const double vtmp  = vbath(jhc-1);\n    vbath(jhc-1) = vtmp*vfact*vfact + fbath(jhc-1)*vfact*dt_ref4;\n  }\n  \n  // Update atomic velocities\n  const double pvfact = exp(-vbath(0)*dt_ref2);\n    \n  ekin_nm  = ekin_nm*pvfact*pvfact;\n    \n  // Update thermostat forces\n  \n  fbath(0) = (ekin_nm - m_gfree_nm*m_ekin_nm)/qmass(0);\n    \n  for (auto ihc = 0; ihc < m_nnhc; ++ihc) {\n    rbath(ihc) += vbath(ihc)*dt_ref2;\n  }\n  \n  // Update Thermostat velocities\n  \n  for (auto ihc = 0; ihc < m_nnhc-1; ++ihc) {\n    const double vfact = exp(-vbath(ihc+1)*dt_ref8);\n    const double vtmp  = vbath(ihc);\n    \n    vbath(ihc) = vtmp*vfact*vfact + fbath(ihc)*vfact*dt_ref4;\n    fbath(ihc+1) =\n      (qmass(ihc)*vbath(ihc)*vbath(ihc) - m_ekin_nm)/qmass(ihc+1);\n  }\n  \n  vbath(m_nnhc-1) += fbath(m_nnhc-1)*dt_ref4;\n  \n  \n  // backup\n  m_vbath_nm = vbath;\n  m_rbath_nm = rbath;\n  \n  // update velocities of normal modes\n  for (auto ib = 1; ib < m_nbead; ++ib)\n    m_vel_nm(ib) *= pvfact;\n\n  \n}\n\n\n\nvoid nm_pos_update ()\n{\n  \n  m_pos_nm += m_dt_ref * m_vel_nm;\n\n}\n\n\n\n\nvoid nm_grad_spring ()\n{\n  \n  //\n  // centroid gradient is zero\n  //\n  m_grd_nm_spr(0) = 0.0;\n  \n  //\n  // Gradients from the Springs between 'neighboring' beads\n  //\n  \n  for (size_t ib = 1; ib < m_nbead; ++ib) {\n    \n    const double fact = m_fict_mass(ib)*m_omega_p2;\n\n    m_grd_nm_spr(ib) = fact * m_pos_nm(ib);\n  }\n  \n  \n}\n\n\n\n\n\nvoid nm_pos_trans ()\n{\n  //\n  // normal mode (nm) ---> Cartesian (qm)\n  // pos_nm --->  pos_qm\n  \n  for (auto ib = 0; ib < m_nbead; ++ib) {\n    \n    double pos_x = 0.0;\n    \n    for (auto jb = 0; jb < m_nbead; ++jb) {\n      pos_x += m_tmat_nm(ib,jb)*m_pos_nm(jb);\n    }\n    \n    m_pos_qm(ib) = pos_x;\n  }\n\n}\n\n\n\n\nvoid nm_grad_trans ()\n{\n\n  m_grd_nm.zeros();\n  \n  for (size_t ib = 0; ib < m_nbead; ++ib) {\n    for (size_t jb = 0; jb < m_nbead; ++jb) {\n      m_grd_nm(ib) += m_tmat_nm(jb,ib)*m_grd_qm(jb);\n    }\n  }\n\n}\n\n\n\n\nvoid nm_pos_init () \n{\n\n  {// centroid particle\n    m_pos_nm(0) = 0.0;\n  }\n\n  { // beads : normal mode\n    const double dbead = m_nbead;\n    const double usigma = 0.02*ang2bohr; // sigma_x = 0.02 A\n    \n    \n    for (size_t ib = 1; ib < m_nbead; ++ib) {\n      \n      double mass05 = sqrt(m_fict_mass(ib));\n      m_pos_nm(ib) = usigma*rnd::gaus_dev()/mass05;\n      \n    }\n  } // beads\n\n}\n\n\nvoid nm_vel_init ()\n{\n\n  // ---- centroid ----\n  {\n    // Here, vel_nm(ib = 0) zero\n    m_vel_nm(0) = 0.0;\n  }\n  \n  { // velocities for bead particles (or nm-mode particles)\n\n    for (size_t ib = 1; ib < m_nbead; ++ib) {\n\t\n      double mass   = m_fict_mass(ib);\n      double vsigma = sqrt (m_ekin_nm/mass);\n\n      double v = vsigma*rnd::gaus_dev();\n\n      m_vel_nm(ib) = v; \n\t\n    }\n      \n    // --- one particle on one-dimensional harmonic oscillator\n    // no correction of translational and rotational motions \n    \n    // Scale Velocity \n    double ekin_nm = 0.0;\n    \n    for (size_t ib = 1; ib < m_nbead; ++ib) {\n      \n      double mass  = m_fict_mass(ib);\n      double v     = m_vel_nm(ib);\n      ekin_nm += mass * v*v;\n      \n    }\n\n    double temp  = ekin_nm / (m_gfree_nm*boltz);\n    double scale = sqrt(m_temp_nm / temp);\n    \n    for (size_t ib = 1; ib < m_nbead; ++ib) {\n\n      m_vel_nm(ib) *= scale;\n\t\n    }\n\t\n    \n  } // velocities for bead particles\n\n}\n\n\n\nvoid nm_vel_update ()\n{\n\n  // (ib = 0) belongs to the centroid velocity\n\n  \n  //---\n  const double dt2 = 0.5*m_dt;\n  \n  for (size_t ib = 1; ib < m_nbead; ++ib) {\n    double mass   = m_fict_mass(ib); \n    double factor = dt2/mass;\n    m_vel_nm(ib) -= factor*m_grd_nm(ib);\n  }\n\n}\n\n\n\n\nvoid nm_vel_spring_update ()\n{\n\n  double dt2 = 0.5*m_dt_ref;\n  \n  for (size_t ib = 1; ib < m_nbead; ++ib) {\n    \n    double mass   = m_fict_mass(ib); \n    double factor = dt2/mass;\n    m_vel_nm(ib) -=\n      factor*m_grd_nm_spr(ib);\n  }\n\n\n}\n\n\ndouble nm_pot_grad ()\n{\n  \n  // beads: normal mode ---> cartesian\n  //        pos_nm ----> pos_qm\n  nm_pos_trans ();\n  \n  double u_vib = 0.0;\n  \n  m_grd_qm.zeros();\n\n  //\n  // force constant: reduced_mass*omega*omega\n  //\n  \n  double k_val = m_mass*m_omega*m_omega;\n\n  // Harmonic Oscilltor\n  // U = 0.5 * k * x**2\n  //\n  for (size_t ib = 0; ib < m_nbead; ib++) {\n    \n    // call your potential.\n    double dx      = m_pos_qm(ib); \n    double en_harm = 0.5*k_val*dx*dx;\n    m_grd_qm(ib)   =  k_val*dx;\n      \n    u_vib += en_harm;\n  } // ib\n    \n\n  // ---\n  double d_nbead = m_nbead;\n  u_vib /= d_nbead;\n  \n  m_grd_qm /= d_nbead;\n  \n  //\n  // cartesian gradient ---> normal mode gradient\n  //\n  nm_grad_trans ();\n  \n  \n  return u_vib;\n  \n}\n\n\nvoid nm_report (const int& istep,\n\t\tconst double& u_vib,\n\t\tdouble& E_eff) \n{\n  // kinetic energy for beads\n  double ekin_nm = 0.0;\n  \n  for (auto ib = 1; ib < m_nbead; ++ib) {\n    double mass = m_fict_mass(ib);\n    double v    = m_vel_nm(ib); \n    ekin_nm += mass*v*v;\n  }\n  \n\n  ekin_nm = 0.5*ekin_nm;\n  double temp_nm = 2.0*ekin_nm/(m_gfree_nm*boltz);\n\n  // Harmonic Potential of springs between neighboring beads\n\n  double qkin_nm = 0.0;\n  for (auto ib = 1; ib < m_nbead; ++ib) {\n    double fact  = 0.5*m_fict_mass(ib)*m_omega_p2;\n    double q     = m_pos_nm(ib);\n    qkin_nm += fact*q*q;\n  \n  }\n  \n  double ebath_nm = 0.0;\n\n  arma::vec4 qmass = m_qmass_nm;\n  ebath_nm += 0.5*qmass(0)*m_vbath_nm(0)*m_vbath_nm(0);\n  ebath_nm += m_gfree_nm*m_ekin_nm*m_rbath_nm(0);\n\n  for (auto ihc = 1; ihc < m_nnhc; ++ihc) {\n    ebath_nm += 0.5*qmass(ihc)*m_vbath_nm(ihc)*m_vbath_nm(ihc);\n    ebath_nm += m_ekin_nm*m_rbath_nm(ihc);\n  }\n\n  E_eff = qkin_nm + u_vib; // <E_eff> = E_ZPE\n  double H_sys = ekin_nm + E_eff; // Hamiltonian of the system\n  double H_tot = H_sys + ebath_nm; // Total H.\n\n  // unit convert\n  E_eff *= au_kcal;\n  H_sys *= au_kcal;\n  H_tot *= au_kcal;\n\n  printf (\" %8d %14.6f %14.6f %14.6f %14.6f %10.2f \\n\",\n\t  (istep+1), H_tot, H_sys, E_eff, \n\t  u_vib*au_kcal, temp_nm);\n  \n  fflush (stdout);\n  \n}\n\n\n\nvoid read_restart_nm (int& istep0)\n{\n\n  // read a restart file\n  std::string str_rst;\n\n  std::ifstream ifs_rst (\"pimdrr.sav\");\n  assert (ifs_rst.good());\n  \n  std::ostringstream oss;\n  \n  oss << ifs_rst.rdbuf();\n  \n  str_rst = oss.str();\n\n  \n  std::istringstream is (str_rst);\n\n  std::string line;\n  std::getline (is, line); // istep\n  std::istringstream istep_ss (line);\n  istep_ss >> istep0;\n  \n  // ib = 0 is for centroids\n  for (auto ib = 1; ib < m_nbead; ++ib) {\n    std::getline (is, line);\n    std::istringstream iss_pos (line);\n    \n    iss_pos >> m_pos_nm(ib); \n  \n    std::getline (is, line);\n    std::istringstream iss_vel (line);\n\n    iss_vel >> m_vel_nm(ib); \n  }\n\n  for (auto ihc = 0; ihc < m_nnhc; ++ihc) {\n    std::getline (is,line);\n    std::istringstream iss (line);\n\n    iss >> m_rbath_nm(ihc); \n  }\n\n  // position and velocity of the centroid particle\n  m_pos_nm(0) = 0.0; \n  m_vel_nm(0) = 0.0; \n  \n}\n\n\nvoid write_restart_nm (const int& istep)\n{\n\n  FILE *ofs_rst = fopen (\"pimdrr.sav\", \"w\");\n\n  fprintf( ofs_rst, \" %10d \\n\", istep+1);\n\n  // ib = 0 is for centroids\n  for (auto ib = 1; ib < m_nbead; ++ib) {\n    fprintf (ofs_rst, \"  %E   \\n\", m_pos_nm(ib) );\n    fprintf (ofs_rst, \"  %E   \\n\", m_vel_nm(ib) );\n  }\n\n  for (auto ihc = 0; ihc < m_nnhc; ++ihc) {\n    fprintf (ofs_rst, \"  %E   %E   %E \\n\",\n\t     m_rbath_nm(ihc),\n\t     m_vbath_nm(ihc),\n\t     m_qmass_nm(ihc) );\n  }\n  \n  fclose (ofs_rst);\n\n}\n\n\nvoid write_prob_bin (int& nsamp)\n{\n\n  double zeta2   = m_mass*m_omega; // (unit 1/bohr**2)\n  \n  arma::vec p_dx = prob_dx/(m_nbead*(nsamp+1)*delt_x);\n  \n  std::ofstream ofs_rho (\"prob_bin_rho.dat\");\n  // psi_0\n  // zeta2 = mass*omega*(x*x)\n  // debug\n  const double zt    = sqrt(zeta2/M_PI); \n\n  for (auto ib = 0; ib < 400; ++ib) {\n    double  x  = (ib - 200)*delt_x;\n    double  x2 =  x* x;\n    double rho =  zt*exp(-zeta2*x2);\n    ofs_rho << x << \"   \"  << p_dx(ib)\n\t   << \"  \" << rho << endl;\n  }\n\n  ofs_rho.close();\n\n}\n\n\nvoid wpimd_run ()\n{\n\n  //\n  // This is a sample code,\n  // in which WPIMD is running at T (thermal temperature) = 0 K.\n  // \n  \n  int istep0 = 0;\n\n  if (m_irst == 1) {\n    read_restart_nm (istep0);\n  }\n  \n  // initial gradients and potential energy\n  double u_vib = nm_pot_grad ();\n\n  double e_eff = 0.0;\n  double sum_e_eff = 0.0;\n  int    ncount    = 0;\n  \n  nm_grad_spring ();\n\n  if (m_irst == 0)\n    nm_report (istep0-1, u_vib, e_eff);\n\n  for (auto istep = 0; istep < m_nstep; ++istep) {\n\n    nm_vel_update ();\n\n    for (auto iref = 0; iref < m_nref; ++iref) {\n      nm_nhc_integrate ();\n      nm_vel_spring_update();\n      nm_pos_update ();\n      nm_grad_spring();\n      nm_vel_spring_update();\n      nm_nhc_integrate ();\n    }\n\n    u_vib   = nm_pot_grad ();\n    \n    sample_rho ();\n    \n    nm_vel_update ();\n    \n    if ( (istep+1)%500 == 0) {\n      nm_report (istep+istep0, u_vib, e_eff);\n      sum_e_eff += e_eff;\n      ncount++;\n    }\n    \n    if ( (istep+1)%5000 == 0) {\n      write_restart_nm   (istep+istep0);\n      write_prob_bin (istep);\n    }\n    \n  }\n\n\n  cout << \"AVE E_eff \" << sum_e_eff / ncount << endl;\n  \n\n}\n\n\n\n\nvoid wpimd_init ()\n{\n\n  // one-dimensional system\n  m_gfree_nm = m_nbead;\n  \n  // ZPE = 0.5 * hbar * omega\n  // ZPE(au) = 0.5 * omega\n  m_omega    = 2.0*m_ZPE;\n\n  // Eq. (14)\n  // temperature for the bead motions\n  m_temp_nm  = m_omega/(m_nbead*boltz);\n\n  double dbead = m_nbead;\n  double omega_p = sqrt(dbead)*boltz*m_temp_nm;\n  m_omega_p2 = omega_p * omega_p;\n  m_beta_nm  = 1.0 / (boltz*m_temp_nm);\n  m_ekin_nm  = boltz*m_temp_nm;\n  \n  // mem alloc\n\n  m_tmat_nm   = arma::mat (m_nbead, m_nbead, arma::fill::zeros);\n  m_fict_mass = arma::vec (m_nbead, arma::fill::zeros);\n\n  m_rbath_nm  = arma::vec (m_nnhc,  arma::fill::zeros);\n  m_vbath_nm  = arma::vec (m_nnhc,  arma::fill::zeros);\n  m_qmass_nm  = arma::vec (m_nnhc,  arma::fill::zeros);\n\n  // one-dimensional system \n  m_pos_qm    = arma::vec (m_nbead, arma::fill::zeros); \n  m_pos_nm    = arma::vec (m_nbead, arma::fill::zeros);\n  \n  m_vel_nm    = arma::vec (m_nbead, arma::fill::zeros);\n  \n  m_grd_qm    = arma::vec (m_nbead, arma::fill::zeros);\n  m_grd_nm    = arma::vec (m_nbead, arma::fill::zeros);\n  m_grd_nm_spr= arma::vec (m_nbead, arma::fill::zeros);\n\n\n  // --- initiate the normal mode matrix.\n  for (size_t i = 0; i < m_nbead; ++i) {\n    m_tmat_nm(i, 0) = 1.0;\n  }\n    \n  for (size_t i = 0; i < m_nbead/2; ++i) {\n    m_tmat_nm(2*i,   m_nbead-1) = -1.0;\n    m_tmat_nm(2*i+1, m_nbead-1) =  1.0;\n  }\n\n  double dnorm = sqrt (2.0);\n    \n  for (size_t i = 0; i < m_nbead; ++i) {\n    const double di    = i+1;\n    const double phase = 2.0*di*(M_PI/dbead);\n    for (size_t j = 0; j < (m_nbead-2)/2; ++j) {\n      const double dj    = j+1;\n      m_tmat_nm(i, 2*j+1) = dnorm*cos(phase*dj);\n      m_tmat_nm(i, 2*j+2) = dnorm*sin(phase*dj);\n    }\n  }\n\n  \n  // --- mass init ---\n  double mass = m_mass;\n\n  m_fict_mass(0)         = mass;\n  m_fict_mass(m_nbead-1) = 4.0*dbead*mass;\n\n  for (auto ib = 1; ib < m_nbead/2; ++ib) {\n    double val = 2.0*(1.0 - cos (2.0*ib*(M_PI/dbead)))*dbead*mass;\n    m_fict_mass(2*ib-1) = val;\n    m_fict_mass(2*ib  ) = val;\n  }\n  \n\n  // bath init for beads\n  \n  m_qmass_nm(0) = m_gfree_nm*m_ekin_nm/m_omega_p2;\n    \n  for (size_t ihc = 1; ihc < m_nnhc; ++ihc) {\n    m_qmass_nm(ihc) = m_ekin_nm/m_omega_p2;\n  }\n\n\n  nm_pos_init ();\n  nm_vel_init ();\n  \n  prob_dx      = arma::vec(400, arma::fill::zeros);\n  \n}\n\n\nvoid read_input (const std::string& fname)\n{\n\n  std::ifstream is_input(fname);\n  std::ostringstream oss;\n  oss << is_input.rdbuf();\n\n  std::istringstream ss (oss.str());\n\n  m_nstep = 1000;\n  m_dt   = 0.5; // fsec\n  m_irst = 0;\n  \n  m_nbead = 8;\n  m_nref  = 10;\n  m_ZPE   = 0.0; // kcal/mol\n\n  m_mass  = 1.0*amu2au; // amu --> au\n  \n  std::string line;\n\n  while(getline(ss, line)) {\n    std::istringstream iss (line);\n    std::string keyword;\n    std::string val;\n    iss >> keyword >> val;\n\n    if (keyword == \"nstep\") {\n      m_nstep = stoi (val);\n    }\n    else if (keyword == \"dt\") {\n      m_dt = stod(val);\n    }\n    else if (keyword == \"l_restart\") {\n      m_irst = stoi(val);\n    }\n    else if (keyword == \"nbead\") {\n      m_nbead = stoi(val);\n    }\n    else if (keyword == \"nref\") {\n      m_nref  = stoi(val);\n    }\n    else if (keyword == \"ZPE\") {\n      m_ZPE  = stod(val)/au_kcal; // kcal/mol ---> au\n    }\n    else if (keyword == \"mass1\") {\n      m_mass = stod(val)*amu2au; // amu --> au\n    }\n    //else if (keyword == \"mass2\") {\n    //  m_mass(1) = stod(val)*amu2au; // amu --> au\n    //}\n    \n  }\n\n  // -- time : [fs] ---> [au]\n  m_dt  = m_dt * (1.0e-15/au_time);\n\n  m_dt_ref = m_dt/m_nref;\n  \n}\n\n\n} // namespace willow\n\n\nint main (int argc, char *argv[])\n{\n\n  cout << std::setprecision (6);\n  cout << std::fixed;\n\n\n  //--- read an input file --\n  const std::string fname = (argc > 1) ? argv[1] : \"sample1.inp\";\n\n  willow::read_input (fname);\n\n  willow::wpimd_init ();\n  willow::wpimd_run ();\n\n  return 0;\n  \n}\n", "meta": {"hexsha": "3f4b3cd5d59f3c34deba42fae757ec6785fed292", "size": 15392, "ext": "cc", "lang": "C++", "max_stars_repo_path": "wpimd1.cc", "max_stars_repo_name": "swillow/w-pimd", "max_stars_repo_head_hexsha": "aee1dee3a0e4bfc68e271b00b5116b1b95380cbc", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "wpimd1.cc", "max_issues_repo_name": "swillow/w-pimd", "max_issues_repo_head_hexsha": "aee1dee3a0e4bfc68e271b00b5116b1b95380cbc", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "wpimd1.cc", "max_forks_repo_name": "swillow/w-pimd", "max_forks_repo_head_hexsha": "aee1dee3a0e4bfc68e271b00b5116b1b95380cbc", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-09-30T09:34:32.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-16T13:39:30.000Z", "avg_line_length": 19.0967741935, "max_line_length": 73, "alphanum_fraction": 0.5741294179, "num_tokens": 5643, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7490872243177518, "lm_q2_score": 0.42632159254749036, "lm_q1q2_score": 0.3193520584281231}}
{"text": "/*\n * Copyright (c) 2019 Nobuyuki Umetani\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n\n#include \"delfem2/v23m3q.h\"\n\n\n#if defined(__APPLE__) && defined(__MACH__)\n#include <OpenGL/gl.h>\n#include <OpenGL/glu.h>\n#elif defined(__MINGW32__) // probably I'm using Qt and don't want to use GLUT\n#include <GL/glu.h>\n#elif defined(_WIN32)\n#include <windows.h>\n#include <GL/glu.h>\n#else\n#include <GL/glu.h>\n#endif\n\n#if defined(__APPLE__) && defined(__MACH__)\n#include \"Eigen/Dense\"\n#else\n#include <Eigen/Dense>\n#endif\n\n#include \"delfem2/eigen/eigen_rigidbody.h\"\n\nvoid myUpdateMinMaxXYZ\n(double bb[6],\n const CVector3 p)\n{\n  const double x = p.x;\n  const double y = p.y;\n  const double z = p.z;\n  if( bb[0] > bb[1] ){\n    bb[0] = bb[1] = x;\n    bb[2] = bb[3] = y;\n    bb[4] = bb[5] = z;\n    return;\n  }\n  bb[0] = (bb[0] < x) ? bb[0] : x;\n  bb[1] = (bb[1] > x) ? bb[1] : x;\n  bb[2] = (bb[2] < y) ? bb[2] : y;\n  bb[3] = (bb[3] > y) ? bb[3] : y;\n  bb[4] = (bb[4] < z) ? bb[4] : z;\n  bb[5] = (bb[5] > z) ? bb[5] : z;\n}\n\n// -----------------------------------------------\n\nvoid EdEd_Potential\n(double& energy,\n CVector3& dEdu,\n CVector3& dEdw,\n const CVector3& cg,\n const CVector3& u,\n const double mass,\n const CVector3& g       // floor normal\n)\n{\n  energy = mass*(u*g);\n  dEdu = mass*g;\n  dEdw = CVector3(0,0,0);\n}\n\nvoid EdEddE_Exforce\n(double& energy,\n CVector3& dEdu, CVector3& dEdw,\n CMatrix3&  ddEddu,  CMatrix3&  ddEddw, CMatrix3&  ddEdudw,\n const CVector3& cg, // the center of gravity\n const CVector3& pex, // external force position\n const CVector3& fex, // external force\n const CVector3& u, // displacement\n const CMatrix3& R // rigid rotation\n)\n{\n  CVector3 Rv = R * (pex-cg);\n  CVector3 qex = Rv + cg + u; // current external force position\n  energy = +qex*fex;\n  dEdu = +fex;\n  dEdw = +Rv^fex;\n  ddEddu  = CMatrix3(0.0);\n  ddEddw  = +Mat3_Spin(fex)*Mat3_Spin(Rv);\n  ddEdudw = CMatrix3(0.0);\n}\n\nvoid EdEddE_Contact\n(double& energy,\n CVector3& dEdu, CVector3& dEdw,\n CMatrix3&  ddEddu,  CMatrix3&  ddEddw, CMatrix3&  ddEdudw,\n const CVector3& cg, // the center of gravity\n const CVector3& cp, // contact position\n const CVector3& u, // displacement\n const CMatrix3& R, // rigid rotation\n const double cont_stiff,\n const CVector3& n       // floor normal\n)\n{\n  CVector3 Rv = R * (cp-cg);\n  CVector3 cq = Rv + cg + u;\n  energy = 0.5*(cq*n)*(cq*n)*cont_stiff;\n  dEdu = ((cq*n)*cont_stiff)*n;\n  dEdw = ((cq*n)*cont_stiff)*(Rv^n);\n  ddEddu  = cont_stiff*Mat3_OuterProduct(n,n);\n  ddEddw  = cont_stiff*Mat3_OuterProduct(Rv^n,Rv^n) + ((cq*n)*cont_stiff)*Mat3_Spin(n)*Mat3_Spin(Rv);\n  ddEdudw = cont_stiff*Mat3_OuterProduct(Rv^n,n);\n}\n\nvoid EdEddE_ContactFriction\n(double& energy,\n CVector3& dEdu, CVector3& dEdw,\n CMatrix3&  ddEddu,  CMatrix3&  ddEddw, CMatrix3&  ddEdudw,\n const CVector3& cg, // the center of gravity\n const CVector3& cp, // contact position\n const CVector3& u, // displacement\n const CMatrix3& R, // rigid rotation\n const double cont_stiff\n )\n{\n  CVector3 Rv = R * (cp-cg);\n  CVector3 cq = Rv + cg + u;\n  energy = 0.5*(cq-cp)*(cq-cp)*cont_stiff;\n  dEdu = cont_stiff*(cq-cp);\n  dEdw = cont_stiff*(Rv^(cq-cp));\n  ddEddu  = cont_stiff*CMatrix3::Identity();\n  //    ddEddw  = -cont_stiff*CMatrix3::OuterProduct(Rv,Rv) + cont_stiff*CMatrix3::Spin(Rv)*CMatrix3::Spin(cq-cp);\n  ddEddw  = -cont_stiff*Mat3_Spin(Rv)*Mat3_Spin(Rv) + cont_stiff*Mat3_Spin(cq-cp)*Mat3_Spin(Rv);\n  ddEdudw = cont_stiff*Mat3_Spin(Rv);\n}\n\n\nvoid EdEddE_Joint\n(double& energy,\n CVector3& dEdu0, CVector3& dEdw0, CVector3& dEdu1, CVector3& dEdw1,\n ////\n CMatrix3& ddEdu0du0,  CMatrix3& ddEdu0dw0, CMatrix3& ddEdu0du1, CMatrix3& ddEdu0dw1, CMatrix3& ddEdw0dw0,\n CMatrix3& ddEdw0du1,  CMatrix3& ddEdw0dw1, CMatrix3& ddEdu1du1, CMatrix3& ddEdu1dw1, CMatrix3& ddEdw1dw1,\n ////\n const double trans_stiff,\n const double rot_stiff,\n const CVector3& pj,\n ////\n const CVector3& cg0,  const CVector3& u0,  const CMatrix3& R0,\n const CVector3& cg1,  const CVector3& u1,  const CMatrix3& R1\n )\n{\n  CVector3 Rv0 = R0 * (pj-cg0);\n  CVector3 qj0 = Rv0 + cg0 + u0; // after deformation joint pos relative to rigid body 0\n  \n  CVector3 Rv1 = R1 * (pj-cg1);\n  CVector3 qj1 = Rv1 + cg1 + u1; // after deformation joint pos relative to rigid body 1\n  \n  energy = 0.5*trans_stiff*(qj0 - qj1).DLength();\n  \n  dEdu0 = trans_stiff*(qj0-qj1);\n  dEdw0 = trans_stiff*(Rv0^(qj0-qj1));\n  \n  dEdu1 = trans_stiff*(qj1-qj0);\n  dEdw1 = trans_stiff*(Rv1^(qj1-qj0));\n  \n  ddEdu0du0 =  trans_stiff*CMatrix3::Identity();\n  ddEdu0du1 = -trans_stiff*CMatrix3::Identity();\n  ddEdu0dw0 = +trans_stiff*Mat3_Spin(Rv0);\n  ddEdu0dw1 = -trans_stiff*Mat3_Spin(Rv1);\n  \n  ddEdw0dw0 = -trans_stiff*Mat3_Spin(Rv0)*Mat3_Spin(Rv0) + trans_stiff*Mat3_Spin(qj0-qj1)*Mat3_Spin(Rv0);\n  ddEdw0du1 = +trans_stiff*Mat3_Spin(Rv0);\n  ddEdw0dw1 = +trans_stiff*Mat3_Spin(Rv1)*Mat3_Spin(Rv0);\n  \n  ddEdu1du1 =  trans_stiff*CMatrix3::Identity();\n  ddEdu1dw1 = +trans_stiff*Mat3_Spin(Rv1);\n  \n  ddEdw1dw1 = -trans_stiff*Mat3_Spin(Rv1)*Mat3_Spin(Rv1) + trans_stiff*Mat3_Spin(qj1-qj0)*Mat3_Spin(Rv1);\n  \n  CVector3 av(0,0,0);\n  CMatrix3 davdw0, davdw1;\n  {\n    for(unsigned int i=0;i<3;i++){\n      CVector3 r0( R0.mat[0*3+i], R0.mat[1*3+i], R0.mat[2*3+i] );\n      CVector3 r1( R1.mat[0*3+i], R1.mat[1*3+i], R1.mat[2*3+i] );\n      av += (r0^r1);\n      davdw0 += Mat3_Spin(r1)*Mat3_Spin(r0);\n      davdw1 -= Mat3_Spin(r0)*Mat3_Spin(r1);\n    }\n    av *= 0.5;\n    davdw0 *= 0.5;\n    davdw1 *= 0.5;\n  }\n  energy += 0.5*rot_stiff*av.DLength();\n  \n  CMatrix3 m0,m1,m2;\n  for(unsigned int i=0;i<3;i++){\n    CVector3 r0( R0.mat[0*3+i], R0.mat[1*3+i], R0.mat[2*3+i] );\n    CVector3 r1( R1.mat[0*3+i], R1.mat[1*3+i], R1.mat[2*3+i] );\n    dEdw0 += 0.5*rot_stiff*r0^(r1^av);\n    dEdw1 -= 0.5*rot_stiff*r1^(r0^av);\n    ddEdw0dw0 += 0.5*rot_stiff*( Mat3_Spin(r1^av)*Mat3_Spin(r0) + Mat3_Spin(r0)*Mat3_Spin(r1)*davdw0 );\n    ddEdw1dw1 -= 0.5*rot_stiff*( Mat3_Spin(r0^av)*Mat3_Spin(r1) + Mat3_Spin(r1)*Mat3_Spin(r0)*davdw1 );\n    ddEdw0dw1 -= 0.5*rot_stiff*(  Mat3_Spin(r1)*Mat3_Spin(av)*Mat3_Spin(r0)\n                                + Mat3_Spin(r1)*Mat3_Spin(r0)*davdw0 );\n  }\n}\n\n\nCVector3 rand_vec(double s)\n{\n  CVector3 v;\n  v.x = s*rand()/(RAND_MAX+1.0);\n  v.y = s*rand()/(RAND_MAX+1.0);\n  v.z = s*rand()/(RAND_MAX+1.0);\n  return v;\n}\n\nCMatrix3 rand_rot()\n{\n  double s = 3.5;\n  CVector3 v;\n  v.x = s*rand()/(RAND_MAX+1.0);\n  v.y = s*rand()/(RAND_MAX+1.0);\n  v.z = s*rand()/(RAND_MAX+1.0);\n  CMatrix3 R;  R.SetRotMatrix_Cartesian(v.x,v.y,v.z);\n  return R;\n}\n\nvoid CheckDiff_Contact()\n{\n  double energy = 0.0;\n  CVector3 dEdu,dEdw;\n  CMatrix3 ddEddu, ddEddw, ddEdudw;\n  double epsilon = 1.0e-5;\n  const double cont_stiff = 1.0e+3;\n  CVector3 cg = rand_vec(1.0);\n  CVector3 cp = rand_vec(1.0);\n  CVector3 u  = rand_vec(1.0);\n  CMatrix3  R  = rand_rot();\n  CVector3 n(0,0,1);\n  EdEddE_Contact(energy,\n                 dEdu,dEdw,  ddEddu,ddEddw,ddEdudw,\n                 cg,cp,u,R,\n                 cont_stiff,n);\n  for(unsigned int idim=0;idim<3;idim++){\n    CVector3 dEdu_, dEdw_;\n    CMatrix3 ddEddu_, ddEddw_, ddEdudw_;\n    double energy_ = 0.0;\n    CVector3 u_ = u;\n    u_[idim] += epsilon;\n    EdEddE_Contact(energy_,  dEdu_,dEdw_,   ddEddu_,ddEddw_,ddEdudw_,\n                   cg,cp,u_,R,\n                   cont_stiff,n);\n    std::cout << \"dEdu \" << idim << \" --> \"  << (energy_-energy)/epsilon << \" \" << dEdu[idim] << std::endl;\n    for(unsigned int jdim=0;jdim<3;jdim++){\n      std::cout << \" ddEddu  \" << idim << \" \" << jdim << \" --> \" << (dEdu_[jdim]-dEdu[jdim])/epsilon << \" \" << ddEddu.mat[jdim*3+idim] << std::endl;\n    }\n    for(unsigned int jdim=0;jdim<3;jdim++){\n      std::cout << \" ddEdudw \" << idim << \" \" << jdim << \" --> \" << (dEdw_[jdim]-dEdw[jdim])/epsilon << \" \" << ddEdudw.mat[jdim*3+idim] << std::endl;\n    }\n  }\n  for(unsigned int idim=0;idim<3;idim++){\n    CVector3 dEdu_, dEdw_;\n    CMatrix3 ddEddu_, ddEddw_, ddEdudw_;\n    double energy_ = 0.0;\n    CVector3 w(0,0,0);\n    w[idim] = epsilon;\n    CMatrix3 dR; dR.SetRotMatrix_Cartesian(w.x,w.y,w.z);\n    CMatrix3 R_ = dR*R;\n    EdEddE_Contact(energy_,  dEdu_,dEdw_,   ddEddu_,ddEddw_,ddEdudw_,\n                   cg,cp,u,R_,\n                   cont_stiff,n);\n    std::cout << \"dEdw \" << idim << \" --> \" << (energy_-energy)/epsilon << \" \" << dEdw[idim] << std::endl;\n    for(unsigned int jdim=0;jdim<3;jdim++){\n      std::cout << \" ddEdudw \" << idim << \" \" << jdim << \" --> \" << (dEdu_[jdim]-dEdu[jdim])/epsilon << \" \" << ddEdudw.mat[idim*3+jdim] << std::endl;\n    }\n    for(unsigned int jdim=0;jdim<3;jdim++){\n      std::cout << \" ddEddw  \" << idim << \" \" << jdim << \" --> \" << (dEdw_[jdim]-dEdw[jdim])/epsilon << \" \" << ddEddw.mat[jdim*3+idim] << std::endl;\n    }\n  }\n}\n\n\nvoid CheckDiff_ContactFriction()\n{\n  double energy = 0.0;\n  CVector3 dEdu,dEdw;\n  CMatrix3 ddEddu, ddEddw, ddEdudw;\n  double epsilon = 1.0e-5;\n  const double cont_stiff = 1.0e+3;\n  CVector3 cg = rand_vec(1.0);\n  CVector3 cp = rand_vec(1.0);\n  CVector3 u  = rand_vec(1.0);\n  CMatrix3  R  = rand_rot();\n  EdEddE_ContactFriction(energy,\n                         dEdu,dEdw,  ddEddu,ddEddw,ddEdudw,\n                         cg,cp,u,R,\n                         cont_stiff);\n  for(unsigned int idim=0;idim<3;idim++){\n    CVector3 dEdu_, dEdw_;\n    CMatrix3 ddEddu_, ddEddw_, ddEdudw_;\n    double energy_ = 0.0;\n    CVector3 u_ = u;\n    u_[idim] += epsilon;\n    EdEddE_ContactFriction(energy_,  dEdu_,dEdw_,   ddEddu_,ddEddw_,ddEdudw_,\n                           cg,cp,u_,R,\n                           cont_stiff);\n    std::cout << \"dEdu \" << idim << \" --> \"  << (energy_-energy)/epsilon << \" \" << dEdu[idim] << std::endl;\n    for(unsigned int jdim=0;jdim<3;jdim++){\n      std::cout << \" ddEddu  \" << idim << \" \" << jdim << \" --> \" << (dEdu_[jdim]-dEdu[jdim])/epsilon << \" \" << ddEddu.mat[jdim*3+idim] << std::endl;\n    }\n    for(unsigned int jdim=0;jdim<3;jdim++){\n      std::cout << \" ddEdudw \" << idim << \" \" << jdim << \" --> \" << (dEdw_[jdim]-dEdw[jdim])/epsilon << \" \" << ddEdudw.mat[jdim*3+idim] << std::endl;\n    }\n  }\n  for(unsigned int idim=0;idim<3;idim++){\n    CVector3 dEdu_, dEdw_;\n    CMatrix3 ddEddu_, ddEddw_, ddEdudw_;\n    double energy_ = 0.0;\n    CVector3 w(0,0,0);\n    w[idim] = epsilon;\n    CMatrix3 dR; dR.SetRotMatrix_Cartesian(w.x,w.y,w.z);\n    CMatrix3 R_ = dR*R;\n    EdEddE_ContactFriction(energy_,  dEdu_,dEdw_,   ddEddu_,ddEddw_,ddEdudw_,\n                           cg,cp,u,R_,\n                           cont_stiff);\n    std::cout << \"dEdw \" << idim << \" --> \" << (energy_-energy)/epsilon << \" \" << dEdw[idim] << std::endl;\n    for(unsigned int jdim=0;jdim<3;jdim++){\n      std::cout << \" ddEdudw \" << idim << \" \" << jdim << \" --> \" << (dEdu_[jdim]-dEdu[jdim])/epsilon << \" \" << ddEdudw.mat[idim*3+jdim] << std::endl;\n    }\n    for(unsigned int jdim=0;jdim<3;jdim++){\n      std::cout << \" ddEddw  \" << idim << \" \" << jdim << \" --> \" << (dEdw_[jdim]-dEdw[jdim])/epsilon << \" \" << ddEddw.mat[jdim*3+idim] << std::endl;\n    }\n    \n  }\n}\n\n\n\nvoid CheckDiff_Exforce()\n{\n  double energy = 0.0;\n  CVector3 dEdu,dEdw;\n  CMatrix3 ddEddu, ddEddw, ddEdudw;\n  double epsilon = 1.0e-5;\n  CVector3 cg = rand_vec(1.0);\n  CVector3 u  = rand_vec(1.0);\n  CVector3 fex = rand_vec(1.0);\n  CVector3 pex = rand_vec(1.0);\n  CMatrix3  R  = rand_rot();\n  CVector3 n(0,0,1);\n  EdEddE_Exforce(energy,\n                 dEdu,dEdw,  ddEddu,ddEddw,ddEdudw,\n                 cg,pex,fex,u,R);\n  for(unsigned int idim=0;idim<3;idim++){\n    CVector3 dEdu_, dEdw_;\n    CMatrix3 ddEddu_, ddEddw_, ddEdudw_;\n    double energy_ = 0.0;\n    CVector3 u_ = u;\n    u_[idim] += epsilon;\n    EdEddE_Exforce(energy_,  dEdu_,dEdw_,   ddEddu_,ddEddw_,ddEdudw_,\n                   cg,pex,fex,u_,R);\n    std::cout << \"dEdu \" << idim << \" --> \"  << (energy_-energy)/epsilon << \" \" << dEdu[idim] << std::endl;\n    for(unsigned int jdim=0;jdim<3;jdim++){\n      std::cout << \" ddEddu  \" << idim << \" \" << jdim << \" --> \" << (dEdu_[jdim]-dEdu[jdim])/epsilon << \" \" << ddEddu.mat[jdim*3+idim] << std::endl;\n    }\n    for(unsigned int jdim=0;jdim<3;jdim++){\n      std::cout << \" ddEdudw \" << idim << \" \" << jdim << \" --> \" << (dEdw_[jdim]-dEdw[jdim])/epsilon << \" \" << ddEdudw.mat[jdim*3+idim] << std::endl;\n    }\n  }\n  for(unsigned int idim=0;idim<3;idim++){\n    CVector3 dEdu_, dEdw_;\n    CMatrix3 ddEddu_, ddEddw_, ddEdudw_;\n    double energy_ = 0.0;\n    CVector3 w(0,0,0);\n    w[idim] = epsilon;\n    CMatrix3 dR; dR.SetRotMatrix_Cartesian(w.x,w.y,w.z);\n    CMatrix3 R_ = dR*R;\n    EdEddE_Exforce(energy_,  dEdu_,dEdw_,   ddEddu_,ddEddw_,ddEdudw_,\n                   cg,pex,fex,u,R_);\n    std::cout << \"dEdw \" << idim << \" --> \" << (energy_-energy)/epsilon << \" \" << dEdw[idim] << std::endl;\n    for(unsigned int jdim=0;jdim<3;jdim++){\n      std::cout << \" ddEdudw \" << idim << \" \" << jdim << \" --> \" << (dEdu_[jdim]-dEdu[jdim])/epsilon << \" \" << ddEdudw.mat[idim*3+jdim] << std::endl;\n    }\n    for(unsigned int jdim=0;jdim<3;jdim++){\n      std::cout << \" ddEddw  \" << idim << \" \" << jdim << \" --> \" << (dEdw_[jdim]-dEdw[jdim])/epsilon << \" \" << ddEddw.mat[jdim*3+idim] << std::endl;\n    }\n  }\n}\n\n\n\n\nvoid CheckDiff_Joint()\n{\n  double energy = 0.0;\n  CVector3 dEdu0(0,0,0);\n  CVector3 dEdw0(0,0,0);\n  CVector3 dEdu1(0,0,0);\n  CVector3 dEdw1(0,0,0);\n  CMatrix3 ddEdu0du0;\n  CMatrix3 ddEdu0dw0;\n  CMatrix3 ddEdu0du1;\n  CMatrix3 ddEdu0dw1;\n  CMatrix3 ddEdw0dw0;\n  CMatrix3 ddEdw0du1;\n  CMatrix3 ddEdw0dw1;\n  CMatrix3 ddEdu1du1;\n  CMatrix3 ddEdu1dw1;\n  CMatrix3 ddEdw1dw1;\n  double epsilon = 1.0e-5;\n  const double trans_stiff = 1.0e+3;\n  const double rot_stiff = 1.0e+3;\n  CVector3 pj  = rand_vec(1.0);\n  ////\n  CVector3 cg0 = rand_vec(1.0);\n  CVector3 cp0 = rand_vec(1.0);\n  CVector3 u0  = rand_vec(1.0);\n  CMatrix3  R0  = rand_rot();\n  ////\n  CVector3 cg1 = rand_vec(1.0);\n  CVector3 cp1 = rand_vec(1.0);\n  CVector3 u1  = rand_vec(1.0);\n  CMatrix3  R1  = rand_rot();\n  ////\n  EdEddE_Joint(energy,\n               dEdu0, dEdw0, dEdu1,dEdw1,\n               ddEdu0du0, ddEdu0dw0, ddEdu0du1, ddEdu0dw1, ddEdw0dw0, ddEdw0du1, ddEdw0dw1, ddEdu1du1, ddEdu1dw1, ddEdw1dw1,\n               trans_stiff, rot_stiff, pj,\n               cg0, u0, R0,\n               cg1, u1, R1);\n  for(unsigned int kdim=0;kdim<3;kdim++){\n    CVector3 dEdu0_, dEdw0_, dEdu1_, dEdw1_;\n    CMatrix3 ddEdu0du0_, ddEdu0dw0_, ddEdu0du1_, ddEdu0dw1_, ddEdw0dw0_, ddEdw0du1_, ddEdw0dw1_, ddEdu1du1_, ddEdu1dw1_, ddEdw1dw1_;\n    double energy_ = 0.0;\n    CVector3 u0_ = u0;\n    u0_[kdim] += epsilon;\n    EdEddE_Joint(energy_, dEdu0_,dEdw0_, dEdu1_,dEdw1_,\n                 ddEdu0du0_, ddEdu0dw0_, ddEdu0du1_, ddEdu0dw1_, ddEdw0dw0_, ddEdw0du1_, ddEdw0dw1_, ddEdu1du1_, ddEdu1dw1_, ddEdw1dw1_,\n                 trans_stiff, rot_stiff, pj,\n                 cg0, u0_, R0,\n                 cg1, u1,  R1);\n    std::cout << \"dEdu0: \" << kdim << \" -->  \" << (energy_-energy)/epsilon << \" \" << dEdu0[kdim] << std::endl;\n    for(unsigned int idim=0;idim<3;idim++){\n      std::cout << \" ddEdu0du0 \" << kdim << \" \" << idim << \" --> \" << (dEdu0_[idim]-dEdu0[idim])/epsilon << \" \" << ddEdu0du0.mat[idim*3+kdim] << std::endl;\n    }\n    for(unsigned int idim=0;idim<3;idim++){\n      std::cout << \" ddEdw0du0 \" << kdim << \" \" << idim << \" --> \" << (dEdw0_[idim]-dEdw0[idim])/epsilon << \" \" << ddEdu0dw0.mat[idim*3+kdim] << std::endl;\n    }\n    for(unsigned int idim=0;idim<3;idim++){\n      std::cout << \"*ddEdu1du0 \" << kdim << \" \" << idim << \" --> \" << (dEdu1_[idim]-dEdu1[idim])/epsilon << \" \" << ddEdu0du1.mat[idim*3+kdim] << std::endl;\n    }\n    for(unsigned int idim=0;idim<3;idim++){\n      std::cout << \"*ddEdw1du0 \" << kdim << \" \" << idim << \" --> \" << (dEdw1_[idim]-dEdw1[idim])/epsilon << \" \" << ddEdu0dw1.mat[idim*3+kdim] << std::endl;\n    }\n  }\n  for(unsigned int jdim=0;jdim<3;jdim++){\n    CVector3 dEdu0_, dEdw0_, dEdu1_, dEdw1_;\n    CMatrix3 ddEdu0du0_, ddEdu0dw0_, ddEdu0du1_, ddEdu0dw1_, ddEdw0dw0_, ddEdw0du1_, ddEdw0dw1_, ddEdu1du1_, ddEdu1dw1_, ddEdw1dw1_;\n    double energy_ = 0.0;\n    CVector3 w(0,0,0);\n    w[jdim] = epsilon;\n    CMatrix3 dR; dR.SetRotMatrix_Cartesian(w.x,w.y,w.z);\n    CMatrix3 R0_ = dR*R0;\n    EdEddE_Joint(energy_, dEdu0_,dEdw0_, dEdu1_,dEdw1_,\n                 ddEdu0du0_, ddEdu0dw0_, ddEdu0du1_, ddEdu0dw1_, ddEdw0dw0_, ddEdw0du1_, ddEdw0dw1_, ddEdu1du1_, ddEdu1dw1_, ddEdw1dw1_,\n                 trans_stiff, rot_stiff, pj,\n                 cg0, u0, R0_,\n                 cg1, u1, R1);\n    std::cout << \"dEdw0: \" << jdim << \" -->  \" << (energy_-energy)/epsilon << \" \" << dEdw0[jdim] << std::endl;\n    for(unsigned int idim=0;idim<3;idim++){\n      std::cout << \" ddEdu0dw0 \" << jdim << \" \" << idim << \" --> \" << (dEdu0_[idim]-dEdu0[idim])/epsilon << \" \" << ddEdu0dw0.mat[jdim*3+idim] << std::endl;\n    }\n    for(unsigned int idim=0;idim<3;idim++){\n      std::cout << \" ddEdw0dw0 \" << jdim << \" \" << idim << \" --> \" << (dEdw0_[idim]-dEdw0[idim])/epsilon << \" \" << ddEdw0dw0.mat[idim*3+jdim] << std::endl;\n    }\n    for(unsigned int idim=0;idim<3;idim++){\n      std::cout << \" ddEdu1dw0 \" << jdim << \" \" << idim << \" --> \" << (dEdu1_[idim]-dEdu1[idim])/epsilon << \" \" << ddEdw0du1.mat[idim*3+jdim] << std::endl;\n    }\n    for(unsigned int idim=0;idim<3;idim++){\n      std::cout << \" ddEdw1dw0 \" << jdim << \" \" << idim << \" --> \" << (dEdw1_[idim]-dEdw1[idim])/epsilon << \" \" << ddEdw0dw1.mat[idim*3+jdim] << std::endl;\n    }\n  }\n  \n  for(unsigned int jdim=0;jdim<3;jdim++){\n    CVector3 dEdu0_, dEdw0_, dEdu1_, dEdw1_;\n    CMatrix3 ddEdu0du0_, ddEdu0dw0_, ddEdu0du1_, ddEdu0dw1_, ddEdw0dw0_, ddEdw0du1_, ddEdw0dw1_, ddEdu1du1_, ddEdu1dw1_, ddEdw1dw1_;\n    double energy_ = 0.0;\n    CVector3 u1_ = u1;\n    u1_[jdim] += epsilon;\n    EdEddE_Joint(energy_, dEdu0_,dEdw0_, dEdu1_,dEdw1_,\n                 ddEdu0du0_, ddEdu0dw0_, ddEdu0du1_, ddEdu0dw1_, ddEdw0dw0_, ddEdw0du1_, ddEdw0dw1_, ddEdu1du1_, ddEdu1dw1_, ddEdw1dw1_,\n                 trans_stiff, rot_stiff, pj,\n                 cg0, u0, R0,\n                 cg1, u1_,R1);\n    std::cout << \"dEdu1: \" << jdim << \" -->  \" << (energy_-energy)/epsilon << \" \" << dEdu1[jdim] << std::endl;\n    for(unsigned int idim=0;idim<3;idim++){\n      std::cout << \" ddEdu0du1 \" << jdim << \" \" << idim << \" --> \" << (dEdu0_[idim]-dEdu0[idim])/epsilon << \" \" << ddEdu0du1.mat[jdim*3+idim] << std::endl;\n    }\n    for(unsigned int idim=0;idim<3;idim++){\n      std::cout << \" ddEdw0du1 \" << jdim << \" \" << idim << \" --> \" << (dEdw0_[idim]-dEdw0[idim])/epsilon << \" \" << ddEdw0du1.mat[jdim*3+idim] << std::endl;\n    }\n    for(unsigned int idim=0;idim<3;idim++){\n      std::cout << \" ddEdu1du1 \" << jdim << \" \" << idim << \" --> \" << (dEdu1_[idim]-dEdu1[idim])/epsilon << \" \" << ddEdu1du1.mat[idim*3+jdim] << std::endl;\n    }\n    for(unsigned int idim=0;idim<3;idim++){\n      std::cout << \"*ddEdw1du1 \" << jdim << \" \" << idim << \" --> \" << (dEdw1_[idim]-dEdw1[idim])/epsilon << \" \" << ddEdu1dw1.mat[idim*3+jdim] << std::endl;\n    }\n  }\n  \n  for(unsigned int jdim=0;jdim<3;jdim++){\n    CVector3 dEdu0_, dEdw0_, dEdu1_, dEdw1_;\n    CMatrix3 ddEdu0du0_, ddEdu0dw0_, ddEdu0du1_, ddEdu0dw1_, ddEdw0dw0_, ddEdw0du1_, ddEdw0dw1_, ddEdu1du1_, ddEdu1dw1_, ddEdw1dw1_;\n    double energy_ = 0.0;\n    CVector3 w(0,0,0);\n    w[jdim] = epsilon;\n    CMatrix3 dR; dR.SetRotMatrix_Cartesian(w.x,w.y,w.z);\n    CMatrix3 R1_ = dR*R1;\n    EdEddE_Joint(energy_, dEdu0_,dEdw0_, dEdu1_,dEdw1_,\n                 ddEdu0du0_, ddEdu0dw0_, ddEdu0du1_, ddEdu0dw1_,\n                 ddEdw0dw0_, ddEdw0du1_, ddEdw0dw1_,\n                 ddEdu1du1_, ddEdu1dw1_,\n                 ddEdw1dw1_,\n                 trans_stiff, rot_stiff, pj,\n                 cg0, u0, R0,\n                 cg1, u1, R1_);\n    std::cout << \"dEdw1: \" << jdim << \" -->  \" << (energy_-energy)/epsilon << \" \" << dEdw1[jdim] << std::endl;\n    for(unsigned int idim=0;idim<3;idim++){\n      std::cout << \" ddEdu0dw1 \" << jdim << \" \" << idim << \" --> \" << (dEdu0_[idim]-dEdu0[idim])/epsilon << \" \" << ddEdu0dw1.mat[jdim*3+idim] << std::endl;\n    }\n    for(unsigned int idim=0;idim<3;idim++){\n      std::cout << \" ddEdw0dw1 \" << jdim << \" \" << idim << \" --> \" << (dEdw0_[idim]-dEdw0[idim])/epsilon << \" \" << ddEdw0dw1.mat[jdim*3+idim] << std::endl;\n    }\n    for(unsigned int idim=0;idim<3;idim++){\n      std::cout << \" ddEdu1dw1 \" << jdim << \" \" << idim << \" --> \" << (dEdu1_[idim]-dEdu1[idim])/epsilon << \" \" << ddEdu1dw1.mat[jdim*3+idim] << std::endl;\n    }\n    for(unsigned int idim=0;idim<3;idim++){\n      std::cout << \" ddEdw1dw1 \" << jdim << \" \" << idim << \" --> \" << (dEdw1_[idim]-dEdw1[idim])/epsilon << \" \" << ddEdw1dw1.mat[idim*3+jdim] << std::endl;\n    }\n  }\n  \n}\n\n\n\n\n///////////////////////////////////////////////////////////////////////////\n\n\nCRigidBodyAssembly_Static::CRigidBodyAssembly_Static()\n{\n  nitr = 30;\n  damping_ratio = 0.01;\n  ////\n  n = CVector3(0,1,0); // normal direction of floor (should be an unit vector)\n  gravity = CVector3(0,-10,0); // gravity\n  ////\n  cont_stiff = 1.0e+4; // contact_stiffness (insensitive)\n  trans_stiff = 1.0e+4; // joint_translation_stiffness (insensitive)\n  rot_stiff = 1.0e+9; // joint_rotation_stiffness (insensitive)\n\n  scale_force = 0.10; //0.5;\n  scale_torque = 0.05; //0.5;\n\n  is_draw_deformed = false; //false\n  is_draw_skeleton = false; //false;\n  is_draw_force = false; //false;\n  is_draw_section = true; //true;\n  is_draw_grid = false; //true;\n  is_draw_section_moment = false; //false;\n  \n//  SetExample();\n//  this->Solve();\n  this->is_draw_skeleton = true;\n  this->is_draw_force = true;\n  this->is_draw_grid = true;\n}\n\nCRigidBodyAssembly_Static::CRigidBodyAssembly_Static\n(const std::vector<CRigidBody>& aRB,\n const std::vector<CJoint>& aJ)\n{\n  \n  nitr = 30;\n  damping_ratio = 0.01;\n  ////\n  n = CVector3(0,1,0); // normal direction of floor (should be an unit vector)\n  gravity = CVector3(0,-10,0); // gravity\n  ////\n  cont_stiff = 1.0e+4; // contact_stiffness (insensitive)\n  trans_stiff = 1.0e+4; // joint_translation_stiffness (insensitive)\n  rot_stiff = 1.0e+9; // joint_rotation_stiffness (insensitive)\n  \n  scale_force = 0.10; //0.5;\n  scale_torque = 0.05; //0.5;\n  \n  this->aRigidBody = aRB;\n  this->aJoint = aJ;\n//  this->Solve();\n  this->is_draw_skeleton = true;\n  this->is_draw_force = true;\n  this->is_draw_grid = true;\n}\n\nvoid CRigidBodyAssembly_Static::AddRigidBody(const double centre_of_mass[3],\n                  const double mass,\n                  const std::vector<double>& contact_points)\n{\n  const std::vector<double> pcg(centre_of_mass,centre_of_mass+3);\n  CRigidBody rb(mass, pcg);\n  const int ncp = (int)contact_points.size()/3;\n  for(int icp=0;icp<ncp;icp++) {\n    CVector3 pc(contact_points[icp*3+0],contact_points[icp*3+1],contact_points[icp*3+2]);\n    rb.aCP.push_back(pc);\n  }\n  aRigidBody.push_back(rb);\n}\n\nvoid CRigidBodyAssembly_Static::AddJoint(const double position[3],\n              const int body_index1,\n              const int body_index2){\n  CJoint j(body_index1, body_index2,\n           std::vector<double>(position,position+3) );\n//  j.p = CVector3(position[0], position[1], position[2]);\n//  j.irb0 = body_index1;\n//  j.irb1 = body_index2;\n  aJoint.push_back(j);\n}\n\nvoid CRigidBodyAssembly_Static::ClearProblem(){\n  aRigidBody.clear();\n  aJoint.clear();\n//  aPlate.clear();\n}\n\n\nvoid AddMatrix(Eigen::MatrixXd& M,\n               unsigned int i0, unsigned int j0,\n               const CMatrix3& m,\n               bool isnt_inverse)\n{\n  if( isnt_inverse ){\n    for(unsigned int idim=0;idim<3;idim++){\n      for(unsigned int jdim=0;jdim<3;jdim++){\n        M(i0+idim,j0+jdim) += m.mat[idim*3+jdim];\n      }\n    }\n  }\n  else{\n    for(unsigned int idim=0;idim<3;idim++){\n      for(unsigned int jdim=0;jdim<3;jdim++){\n        M(i0+idim,j0+jdim) += m.mat[jdim*3+idim];\n      }\n    }\n  }\n}\n\n\nvoid EdEddE_Total\n(double& E,\n Eigen::VectorXd& dE,\n Eigen::MatrixXd& ddE,\n ////\n const std::vector<CRigidBody>& aRigidBody,\n const std::vector<CJoint>& aJoint,\n ////\n const CVector3 n,\n const CVector3 gravity,\n const double cont_stiff,\n const double trans_stiff,\n const double rot_stiff,\n bool is_friction\n )\n{\n  E = 0;\n  ddE.setConstant(0);\n  dE.setConstant(0); // u0,w0, u1,w1, ....\n  \n  ////\n  for(unsigned int irb=0;irb<aRigidBody.size();irb++){\n    const CRigidBody& rb = aRigidBody[irb];\n    CVector3 cg = rb.cg;\n    {\n      double e = 0;\n      CVector3 du, dw;\n      EdEd_Potential(e, du, dw,\n                       cg, rb.u, rb.m,\n                       gravity);\n      E += e;\n      for(unsigned int idim=0;idim<3;idim++){\n        dE[irb*6+0+idim] += du[idim];\n        dE[irb*6+3+idim] += dw[idim];\n      }\n    }\n    for(std::size_t icp=0;icp<rb.aCP.size();icp++){\n      CVector3 cp = rb.aCP[icp];\n      double e = 0;\n      CVector3 du, dw;\n      CMatrix3 ddu,ddw,dudw;\n      if( is_friction ){\n        EdEddE_ContactFriction(e,\n                                 du,dw,  ddu,ddw,dudw,\n                                 cg,cp,rb.u,rb.R,\n                                 cont_stiff);\n      }\n      else{\n        EdEddE_Contact(e,\n                         du,dw,  ddu,ddw,dudw,\n                         cg,cp,rb.u,rb.R,\n                         cont_stiff,n);\n      }\n      E += e;\n      for(unsigned int idim=0;idim<3;idim++){\n        dE[irb*6+0+idim] += du[idim];\n        dE[irb*6+3+idim] += dw[idim];\n      }\n      for(unsigned int idim=0;idim<3;idim++){\n        for(unsigned int jdim=0;jdim<3;jdim++){\n          ddE(irb*6+0+idim,irb*6+0+jdim) += ddu.mat[idim*3+jdim];\n        }\n      }\n      AddMatrix(ddE, irb*6+0, irb*6+0, ddu,  true );\n      AddMatrix(ddE, irb*6+0, irb*6+3, dudw, false);\n      ////\n      AddMatrix(ddE, irb*6+3, irb*6+0, dudw, true );\n      AddMatrix(ddE, irb*6+3, irb*6+3, ddw,  true );\n    }\n    for(std::size_t iexf=0;iexf<rb.aExForce.size();iexf++){\n      CVector3 pex = rb.aExForce[iexf].first;\n      CVector3 fex = rb.aExForce[iexf].second;\n      double e = 0;\n      CVector3 du, dw;\n      CMatrix3 ddu,ddw,dudw;\n      EdEddE_Exforce(e,\n                       du,dw,  ddu,ddw,dudw,\n                       cg,pex,fex, rb.u,rb.R);\n      E += e;\n      for(int idim=0;idim<3;idim++){\n        dE[irb*6+0+idim] += du[idim];\n        dE[irb*6+3+idim] += dw[idim];\n      }\n      for(unsigned int idim=0;idim<3;idim++){\n        for(unsigned int jdim=0;jdim<3;jdim++){\n          ddE(irb*6+0+idim,irb*6+0+jdim) += ddu.mat[idim*3+jdim];\n        }\n      }\n      AddMatrix(ddE, irb*6+0, irb*6+0, ddu,  true );\n      AddMatrix(ddE, irb*6+0, irb*6+3, dudw, false);\n      ////\n      AddMatrix(ddE, irb*6+3, irb*6+0, dudw, true );\n      AddMatrix(ddE, irb*6+3, irb*6+3, ddw,  true );\n    }\n  }\n  for(const auto & joint : aJoint){\n    CVector3 pj = joint.p;\n    int irb0 = joint.irb0;\n    int irb1 = joint.irb1;\n    const CRigidBody& rb0 = aRigidBody[irb0];\n    const CRigidBody& rb1 = aRigidBody[irb1];\n    {\n      double e = 0;\n      CVector3 du0, dw0, du1, dw1;\n      CMatrix3 du0du0, du0dw0, du0du1, du0dw1, dw0dw0, dw0du1, dw0dw1, du1du1, du1dw1, dw1dw1;\n      EdEddE_Joint(e,\n                     du0, dw0, du1, dw1,\n                     du0du0, du0dw0, du0du1, du0dw1, dw0dw0, dw0du1, dw0dw1, du1du1, du1dw1, dw1dw1,\n                     trans_stiff, rot_stiff, pj,\n                     rb0.cg, rb0.u, rb0.R,\n                     rb1.cg, rb1.u, rb1.R);\n      E += e;\n      for(int idim=0;idim<3;idim++){\n        dE[irb0*6+0+idim] += du0[idim];\n        dE[irb0*6+3+idim] += dw0[idim];\n      }\n      for(int idim=0;idim<3;idim++){\n        dE[irb1*6+0+idim] += du1[idim];\n        dE[irb1*6+3+idim] += dw1[idim];\n      }\n      AddMatrix(ddE, irb0*6+0, irb0*6+0, du0du0, true );\n      AddMatrix(ddE, irb0*6+0, irb0*6+3, du0dw0, false);\n      AddMatrix(ddE, irb0*6+0, irb1*6+0, du0du1, false);\n      AddMatrix(ddE, irb0*6+0, irb1*6+3, du0dw1, false);\n      ////\n      AddMatrix(ddE, irb0*6+3, irb0*6+0, du0dw0, true );\n      AddMatrix(ddE, irb0*6+3, irb0*6+3, dw0dw0, true );\n      AddMatrix(ddE, irb0*6+3, irb1*6+0, dw0du1, false);\n      AddMatrix(ddE, irb0*6+3, irb1*6+3, dw0dw1, false);\n      ////\n      AddMatrix(ddE, irb1*6+0, irb0*6+0, du0du1, true );\n      AddMatrix(ddE, irb1*6+0, irb0*6+3, dw0du1, true );\n      AddMatrix(ddE, irb1*6+0, irb1*6+0, du1du1, true );\n      AddMatrix(ddE, irb1*6+0, irb1*6+3, du1dw1, false);\n      ////\n      AddMatrix(ddE, irb1*6+3, irb0*6+0, du0dw1, true );\n      AddMatrix(ddE, irb1*6+3, irb0*6+3, dw0dw1, true );\n      AddMatrix(ddE, irb1*6+3, irb1*6+0, du1dw1, true );\n      AddMatrix(ddE, irb1*6+3, irb1*6+3, dw1dw1, true );\n    }\n  }\n}\n\n\n////////////////////////////////////////////////////////////////////////////////////////////////\n////////////////////////////////////////////////////////////////////////////////////////////////\n////////////////////////////////////////////////////////////////////////////////////////////////\n\n// solve one iteration\nvoid CRigidBodyAssembly_Static::SolveOneIteration()\n/*\n(\n std::vector<CRigidBody>& aRigidBody,\n std::vector<CJoint>& aJoint,\n ////\n double damping_ratio,\n ////\n const CVector3 n,\n const CVector3 gravity,\n const double cont_stiff,\n const double trans_stiff,\n const double rot_stiff)*/\n{\n  int nDof = (int)aRigidBody.size()*6;\n  double E = 0;\n\tEigen::VectorXd dE(nDof);\n\tEigen::MatrixXd ddE(nDof,nDof);\n  EdEddE_Total(E,dE,ddE,\n               aRigidBody,aJoint,\n               n,gravity,cont_stiff,trans_stiff,rot_stiff,true);\n  std::cout << \"energy : \" << E << std::endl;\n  /////\n\tEigen::VectorXd b(nDof);\n\tEigen::MatrixXd A(nDof,nDof);\n  b = -dE;\n  A = ddE;\n  for(int i=0;i<nDof;i++){\n    A(i,i) += damping_ratio;\n  }\n\tEigen::VectorXd x = A.partialPivLu().solve(b);\n  for(std::size_t irb=0;irb<aRigidBody.size();irb++){\n    CRigidBody& rb = aRigidBody[irb];\n    for(int idim=0;idim<3;idim++){\n      rb.u[idim] += x(irb*6+0+idim);\n    }\n    {\n      CVector3 w;\n      w.x = x(irb*6+3+0);\n      w.y = x(irb*6+3+1);\n      w.z = x(irb*6+3+2);\n      CMatrix3 dR; dR.SetRotMatrix_Cartesian(w.x,w.y,w.z);\n      rb.R = dR*rb.R;\n    }\n  }\n}\n\nvoid CRigidBodyAssembly_Static::Solve_InterPlane()\n/*\n(std::vector<CRigidBody>& aRigidBody,\n std::vector<CJoint>& aJoint,\n ////\n double damping_ratio,\n int nitr,\n ////\n const CVector3 n,\n const CVector3 gravity,\n const double cont_stiff,\n const double trans_stiff,\n const double rot_stiff)\n */\n{\n  for(int itr=0;itr<nitr;itr++){\n    //SolveOneIteration(aRigidBody, aJoint, damping_ratio, n,gravity,cont_stiff,trans_stiff,rot_stiff);\n      SolveOneIteration();\n  }\n  ComputeForces();\n}\n\nvoid CRigidBodyAssembly_Static::ComputeForces()\n/*\n(std::vector<CRigidBody>& aRigidBody,\n std::vector<CJoint>& aJoint,\n ////\n const CVector3 n,\n const double cont_stiff, \n const double trans_stiff,\n const double rot_stiff)\n */\n{\n  \n  for(auto & irb : aRigidBody){\n    CRigidBody& rb = irb;\n    const int ncp = (int)irb.aCP.size();\n    rb.aCForce.resize(ncp);\n    for(int icp=0;icp<ncp;icp++){\n      const CVector3& cp = irb.aCP[icp];\n      CVector3 Rv = rb.R * (cp-rb.cg);\n      CVector3 cq = Rv + rb.cg + rb.u;\n      rb.aCForce[icp] = ((cq*n)*cont_stiff)*n;\n    }\n  }  \n  for(auto & joint : aJoint){\n    CVector3 pj = joint.p;\n    int irb0 = joint.irb0;\n    int irb1 = joint.irb1;\n    const CRigidBody& rb0 = aRigidBody[irb0];\n    const CRigidBody& rb1 = aRigidBody[irb1];\n    \n    CVector3 cg0 = rb0.cg;\n    CVector3 u0  = rb0.u;\n    CMatrix3  R0  = rb0.R;\n    \n    CVector3 cg1 = rb1.cg;\n    CVector3 u1  = rb1.u;\n    CMatrix3  R1  = rb1.R;\n    \n    CVector3 trans_f; // translation_force\n    {\n      CVector3 Rv0 = R0 * (pj-cg0);\n      CVector3 qj0 = Rv0 + cg0 + u0; // after deformation joint pos relative to rigid body 0\n      CVector3 Rv1 = R1 * (pj-cg1);\n      CVector3 qj1 = Rv1 + cg1 + u1; // after deformation joint pos relative to rigid body 1\n      trans_f = trans_stiff*(qj0 - qj1);\n    }\n    \n    CVector3 torque_f; // rotation_force\n    {\n      CVector3 av(0,0,0);\n      for(int i=0;i<3;i++){\n        CVector3 r0( R0.mat[0*3+i], R0.mat[1*3+i], R0.mat[2*3+i] );\n        CVector3 r1( R1.mat[0*3+i], R1.mat[1*3+i], R1.mat[2*3+i] );\n        av += (r0^r1);\n      }\n      av *= 0.5;\n      torque_f = rot_stiff*av;\n    }\n    joint.linear = trans_f;\n    joint.torque = torque_f;\n  }\n}\n\n//void CRigidBodyAssembly_Static::PrintJointForce()\n/*\n(const std::vector<CRigidBody>& aRigidBody,\n const std::vector<CJoint>& aJoint,\n ////\n const double trans_stiff,\n const double rot_stiff)\n */\n/*\n{\n  std::cout << \"force on joint\" << std::endl;\n    \n  for(unsigned int ij=0;ij<aJoint.size();ij++){\n    const CJoint& joint = aJoint[ij];\n    CVector3 pj = joint.p;\n    int irb0 = joint.irb0;\n    int irb1 = joint.irb1;\n    const CRigidBody& rb0 = aRigidBody[irb0];\n    const CRigidBody& rb1 = aRigidBody[irb1];\n    \n    CVector3 cg0 = rb0.cg;\n    CVector3 u0  = rb0.u;\n    CMatrix3  R0  = rb0.R;\n    \n    CVector3 cg1 = rb1.cg;\n    CVector3 u1  = rb1.u;\n    CMatrix3  R1  = rb1.R;\n    \n    CVector3 trans_f; // translation_force\n    {\n      CVector3 Rv0 = R0 * (pj-cg0);\n      CVector3 qj0 = Rv0 + cg0 + u0; // after deformation joint pos relative to rigid body 0\n      CVector3 Rv1 = R1 * (pj-cg1);\n      CVector3 qj1 = Rv1 + cg1 + u1; // after deformation joint pos relative to rigid body 1\n      trans_f = trans_stiff*(qj0 - qj1);\n    }\n    \n    CVector3 torque_f; // rotation_force\n    {\n      CVector3 av(0,0,0);\n      for(unsigned int i=0;i<3;i++){\n        CVector3 r0( R0.mat[0*3+i], R0.mat[1*3+i], R0.mat[2*3+i] );\n        CVector3 r1( R1.mat[0*3+i], R1.mat[1*3+i], R1.mat[2*3+i] );\n        av += (r0^r1);\n      }\n      av *= 0.5;\n      torque_f = rot_stiff*av;\n    }\n    \n    std::cout << \"force of joint: \" << ij << std::endl;\n    std::cout << \"  trans_force:  \" << trans_f.x << \" \" << trans_f.y << \" \" << trans_f.z << std::endl;\n    std::cout << \"  torque_force: \" << torque_f.x << \" \" << torque_f.y << \" \" << torque_f.z << std::endl;\n  }\n}\n */\n\n\n\n// Setting problem here\nvoid CRigidBodyAssembly_Static::SetExample()\n{\n  aRigidBody.clear();\n  aJoint.clear();\n  \n  { // making plane 0\n    CRigidBody rb(1.0, CVector3(0,1,0).stlvec() );\n    aRigidBody.push_back(rb);\n  }\n  { // making plane 1\n    CRigidBody rb(0.1, CVector3(-1, 0.5, -1).stlvec());\n    rb.addCP(CVector3(-1.1,0,-1.1).stlvec());\n    aRigidBody.push_back(rb);\n  }\n  { // making plane 2\n    CRigidBody rb(0.1, CVector3(-1,0.5,+1).stlvec() );\n    rb.addCP( CVector3(-1.1,0,+1.1).stlvec() );\n    aRigidBody.push_back(rb);\n  }\n  { // making plane 3\n    CRigidBody rb(0.1, CVector3(+1,0.5,-1).stlvec() );\n    rb.addCP( CVector3(+1.1,0,-1.1).stlvec() );\n    aRigidBody.push_back(rb);\n  }\n  { // making plane 4\n    CRigidBody rb(0.1, CVector3(+1,0.5,+1).stlvec() );\n    rb.addCP( CVector3(+1.1,0,+1.1).stlvec() );\n    aRigidBody.push_back(rb);\n  }\n  \n  \n  { // joint 0\n    CJoint jt(0,1, CVector3(-1,+1,-1).stlvec() );\n    aJoint.push_back(jt);\n  }\n  { // joint 1\n    CJoint jt(0,2, CVector3(-1,+1,+1).stlvec() );\n    aJoint.push_back(jt);\n  }\n  { // joint 2\n    CJoint jt(0,3, CVector3(+1,+1,-1).stlvec() );\n    aJoint.push_back(jt);\n  }\n  { // joint 3\n    CJoint jt(0,4, CVector3(+1,+1,+1).stlvec() );\n    aJoint.push_back(jt);\n  }\n}\n\n\nstatic void myGlVertex3d(const CVector3& v){\n  ::glVertex3d(v.x,v.y,v.z);\n}\n\nstd::vector<double> CRigidBodyAssembly_Static::MinMaxXYZ() const\n{\n  double bb[6] = {1,-1, 0,0, 0,0};\n  for(const auto & rb : aRigidBody){\n    myUpdateMinMaxXYZ(bb, rb.cg);\n  }\n  for(const auto & j : aJoint){\n    myUpdateMinMaxXYZ(bb, j.p);\n  }\n  std::vector<double> res(bb,bb+6);\n  return res;\n}\n\n\n\n", "meta": {"hexsha": "162f21c815bcb2207fd68ebbfeae9c4be25469ea", "size": 35246, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "include/delfem2/eigen/eigen_rigidbody.cpp", "max_stars_repo_name": "fixedchaos/delfem2", "max_stars_repo_head_hexsha": "c8a7a000ec6a51c44bc45bc6ad0d0106d9315ade", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 153.0, "max_stars_repo_stars_event_min_datetime": "2018-08-16T21:51:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T10:34:48.000Z", "max_issues_repo_path": "include/delfem2/eigen/eigen_rigidbody.cpp", "max_issues_repo_name": "mmer547/delfem2", "max_issues_repo_head_hexsha": "4f4b28931c96467ac30948e6b3f83150ea530c92", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 63.0, "max_issues_repo_issues_event_min_datetime": "2018-08-16T21:53:34.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-22T13:50:34.000Z", "max_forks_repo_path": "include/delfem2/eigen/eigen_rigidbody.cpp", "max_forks_repo_name": "mmer547/delfem2", "max_forks_repo_head_hexsha": "4f4b28931c96467ac30948e6b3f83150ea530c92", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 18.0, "max_forks_repo_forks_event_min_datetime": "2018-12-17T05:39:15.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-16T08:21:16.000Z", "avg_line_length": 33.0328022493, "max_line_length": 155, "alphanum_fraction": 0.5767746695, "num_tokens": 13817, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6926419831347361, "lm_q2_score": 0.4610167793123159, "lm_q1q2_score": 0.31931957628127144}}
{"text": "/**\n * @file\n * @copyright This code is licensed under the 3-clause BSD license.\\n\n *            Copyright ETH Zurich, Laboratory of Physical Chemistry, Reiher Group.\\n\n *            See LICENSE.txt for details.\n */\n\n#include \"NDDODensityGuess.h\"\n#include <Sparrow/Implementations/Nddo/Utils/ParameterUtils/ElementParameters.h>\n#include <Utils/DataStructures/DensityMatrix.h>\n#include <Utils/DataStructures/MatrixWithDerivatives.h>\n#include <Utils/Math/DerivOrderEnum.h>\n#include <Utils/Scf/MethodInterfaces/OverlapCalculator.h>\n#include <Utils/Typenames.h>\n#include <Eigen/Core>\n\nnamespace Scine {\nnamespace Sparrow {\n\nnamespace nddo {\n\nNDDODensityGuess::NDDODensityGuess(const Utils::ElementTypeCollection& elements, const ElementParameters& elementParameters,\n                                   Utils::OverlapCalculator& overlapCalculator, const int& nElectrons, const int& nAOs)\n  : elements_(elements),\n    elementParameters_(elementParameters),\n    overlapCalculator_(overlapCalculator),\n    nElectrons_(nElectrons),\n    nAOs_(nAOs) {\n}\n\nUtils::DensityMatrix NDDODensityGuess::calculateGuess() const {\n  Eigen::MatrixXd P = Eigen::MatrixXd::Zero(nAOs_, nAOs_);\n\n  // stewart1990:\n  // The guess is very crude: all off-diagonal matrix elements are set to zero, and\n  // all on-diagonal terms on any atom are set equal to the core charge of that atom divided by the\n  // number of atomic orbitals.\n\n  // Alain:\n  // Same as above, but, for off-diagonal elements,\n  // use overlap matrix times factor for first guess of density matrix.\n  // Division by two found by testing, seems to work better with it than without\n  if (nAOs_ != 0) {\n    overlapCalculator_.calculateOverlap(Utils::DerivativeOrder::Zero);\n    P = overlapCalculator_.getOverlap().getMatrixXd() * nElectrons_ / (2 * nAOs_);\n  }\n\n  for (int i = 0; i < nAOs_; i++)\n    for (int j = i + 1; j < nAOs_; j++)\n      P(i, j) = P(j, i);\n\n  // stewart 1990\n  int index = 0;\n  for (auto e : elements_) {\n    double nEl = elementParameters_.get(e).coreCharge();\n    auto nAOs = elementParameters_.get(e).nAOs();\n    for (int j = 0; j < nAOs; j++) {\n      P(index, index) = nEl / nAOs;\n      index++;\n    }\n  }\n\n  Utils::DensityMatrix d;\n  d.setDensity(std::move(P), nElectrons_);\n  return d;\n}\n\n} // namespace nddo\n} // namespace Sparrow\n} // namespace Scine\n", "meta": {"hexsha": "98fddf9d0ed74919e3676b3d7f9b2931c3edf60d", "size": 2317, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Sparrow/Sparrow/Implementations/Nddo/Utils/NDDODensityGuess.cpp", "max_stars_repo_name": "qcscine/sparrow", "max_stars_repo_head_hexsha": "387e56ed8da78e10d96861758c509f7c375dcf07", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 45.0, "max_stars_repo_stars_event_min_datetime": "2019-06-12T20:04:00.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-28T21:43:54.000Z", "max_issues_repo_path": "src/Sparrow/Sparrow/Implementations/Nddo/Utils/NDDODensityGuess.cpp", "max_issues_repo_name": "qcscine/sparrow", "max_issues_repo_head_hexsha": "387e56ed8da78e10d96861758c509f7c375dcf07", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 12.0, "max_issues_repo_issues_event_min_datetime": "2019-06-12T23:53:57.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-28T18:35:57.000Z", "max_forks_repo_path": "src/Sparrow/Sparrow/Implementations/Nddo/Utils/NDDODensityGuess.cpp", "max_forks_repo_name": "qcscine/sparrow", "max_forks_repo_head_hexsha": "387e56ed8da78e10d96861758c509f7c375dcf07", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 11.0, "max_forks_repo_forks_event_min_datetime": "2019-06-22T22:52:51.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-11T16:59:59.000Z", "avg_line_length": 32.6338028169, "max_line_length": 124, "alphanum_fraction": 0.6935692706, "num_tokens": 625, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6926419704455588, "lm_q2_score": 0.4610167793123159, "lm_q1q2_score": 0.3193195704313478}}
{"text": "/*\n * srkin.cpp\n *\n *  Created on: Jul 9, 2014\n *      Author: Shirong\n */\n\n#ifndef __SRKIN_CPP_\n#define __SRKIN_CPP_\n\n#include \"../../include/srkin/srkin.h\"\n\n#include <boost/property_tree/ptree.hpp> //for property_tree\n#include <boost/property_tree/json_parser.hpp> //for json_reader\n#include <boost/optional/optional.hpp> //for optional\n\nnamespace srkin_sr {\n\n\tsrkin::srkin(std::string cwd_sr_in, rsp::temperature_t t, rsp::pressure_t p, rsp::volume_t v) :RU_sk(8.3144621E7), RUC_sk(1.9872041), PA_sk(1.01325E6)\n\t{\n\t\tset_cwd(cwd_sr_in);\n\t\tset_temperature(t);\n\t\tset_pressure(p);\n\t\tset_volume(v);\n\n\n\t\trsp::relationshipParser::read_chem_out_ele_spe(this->element_v_sk, this->species_v_sk, this->spe_name_index_map_sk, this->cwd_sk + \"/input/chem.out\");\n\t\trsp::relationshipParser::read_chem_out_reaction(this->species_v_sk, this->reaction_v_sk, this->spe_name_index_map_sk, this->cwd_sk + \"/input/chem.out\");\n\n\t\trsp::relationshipParser::set_reaction_net_reactant_product(this->reaction_v_sk);\n\t\trsp::relationshipParser::set_spe_sk_info(this->species_v_sk, this->reaction_v_sk);\n\n\t\tread_initial_spe_concentration(this->species_v_sk.size(), \"/input/setting.json\");\n\n\t\t//set prefactor_A\n\t\tfor (std::size_t i = 0; i < this->reaction_v_sk.size(); ++i) {\n\t\t\tthis->reaction_v_sk[i].rate_constant = cal_reaction_rate_coef(i, this->temperature_sk, this->pressure_sk);\n\t\t}\n\n\t}\n\n\tsrkin::~srkin()\n\t{\n\t}\n\n\tvoid srkin::read_initial_spe_concentration(const std::size_t nkk, std::string filename)\n\t{\n\t\t//configurations, read configuration file named \"setting.json\"\n\t\tboost::property_tree::ptree pt;\n\t\t//read configuration file \"setting.cfg\"\n\t\tboost::property_tree::read_json(this->cwd_sk + std::string(\"/input/setting.json\"), pt, std::locale());\n\n\t\tthis->species_conc_v_sk.resize(nkk);\n\n\t\t//read with json_parser as property_tree\n\t\t//nice and easy\n\t\tfor (auto &key1 : pt.get_child(\"chem_init.species_index_concentration\")) {\n\t\t\tspecies_conc_v_sk[boost::lexical_cast<std::size_t>(key1.first)] = key1.second.get_value<double>();\n\t\t}\n\n\t}\n\n\tstd::string srkin::get_cwd()\n\t{\n\t\treturn this->cwd_sk;\n\t}\n\n\tvoid srkin::set_cwd(std::string cwd_in)\n\t{\n\t\tthis->cwd_sk = cwd_in;\n\t}\n\n\trsp::temperature_t srkin::get_temperature()\n\t{\n\t\treturn this->temperature_sk;\n\t}\n\n\tvoid srkin::set_temperature(rsp::temperature_t t_in)\n\t{\n\t\tthis->temperature_sk = t_in;\n\t}\n\n\trsp::volume_t srkin::get_volume()\n\t{\n\t\treturn this->volume_sk;\n\t}\n\n\tvoid srkin::set_volume(rsp::volume_t volume_in)\n\t{\n\t\tthis->volume_sk = volume_in;\n\t}\n\n\trsp::pressure_t srkin::get_pressure()\n\t{\n\t\treturn this->pressure_sk;\n\t}\n\n\tvoid srkin::set_pressure(rsp::pressure_t pressure_in)\n\t{\n\t\tthis->pressure_sk = pressure_in;\n\t}\n\n\tconst std::vector<rsp::concentration_t>& srkin::get_species_conc_v() const\n\t{\n\t\t// TODO: insert return statement here\n\t\treturn this->species_conc_v_sk;\n\t}\n\n\tvoid srkin::set_species_conc_v(const std::size_t spe_ind, const double conc)\n\t{\n\t\tthis->species_conc_v_sk[spe_ind] = conc;\n\t}\n\n\tvoid srkin::set_species_conc_v(const double speConcV[])\n\t{\n\t\tfor (std::size_t i = 0; i < this->species_conc_v_sk.size(); ++i) {\n\t\t\tthis->species_conc_v_sk[i] = speConcV[i];\n\t\t}\n\t}\n\n\tdouble srkin::cal_reaction_rate_coef(std::size_t reaction_ind, rsp::temperature_t T, rsp::pressure_t P)\n\t{\n\t\tif (T == 0)\n\t\t\treturn this->reaction_v_sk[reaction_ind].prefactor_A;\n\t\telse if (this->reaction_v_sk[reaction_ind].delta == 0)\n\t\t\treturn this->reaction_v_sk[reaction_ind].prefactor_A;\n\t\telse\n\t\t\treturn this->reaction_v_sk[reaction_ind].prefactor_A* pow(T, this->reaction_v_sk[reaction_ind].delta) * exp(-this->reaction_v_sk[reaction_ind].barrier_E / T / this->RUC_sk);\n\t}\n\n\tvoid srkin::set_reaction_rate_coef(std::size_t reaction_ind, rsp::temperature_t T, rsp::pressure_t P)\n\t{\n\t\tthis->reaction_v_sk[reaction_ind].rate_constant = this->cal_reaction_rate_coef(reaction_ind, T, P);\n\t}\n\n\tvoid srkin::cal_reaction_rate(const std::size_t reaction_ind)\n\t{\n\n\t\tthis->reaction_v_sk[reaction_ind].reaction_rate = this->reaction_v_sk[reaction_ind].rate_constant;\n\t\tfor (std::size_t i = 0; i < reaction_v_sk[reaction_ind].reactant.size(); ++i) {\n\t\t\tthis->reaction_v_sk[reaction_ind].reaction_rate *= pow(this->species_conc_v_sk[reaction_v_sk[reaction_ind].reactant[i].first], reaction_v_sk[reaction_ind].reactant[i].second);\n\t\t}\n\t}\n\n\tvoid srkin::cal_reaction_rate()\n\t{\n\t\tfor (std::size_t i = 0; i < this->reaction_v_sk.size(); ++i)\n\t\t\tcal_reaction_rate(i);\n\t}\n\n\tvoid srkin::cal_reaction_rate(const double * T, const double * C, double * FWDK, double * REVK)\n\t{\n\t\tset_temperature(*T);\n\t\tset_species_conc_v(C);\n\t\tfor (std::size_t i = 0; i < this->reaction_v_sk.size(); ++i) {\n\t\t\tcal_reaction_rate(i);\n\t\t\tFWDK[i] = this->reaction_v_sk[i].reaction_rate;\n\t\t\tREVK[i] = 0.0;\n\t\t}\n\t}\n\n\tvoid srkin_sr::srkin::cal_reaction_rate_discrete(const std::size_t reaction_ind)\n\t{\n\n\t\tthis->reaction_v_sk[reaction_ind].reaction_rate = this->reaction_v_sk[reaction_ind].rate_constant;\n\t\tfor (std::size_t i = 0; i < reaction_v_sk[reaction_ind].reactant.size(); ++i) {\n\t\t\t//check, number of species must be not less than the stoichoimetric coefficient\n\t\t\tif (this->species_conc_v_sk[reaction_v_sk[reaction_ind].reactant[i].first] < reaction_v_sk[reaction_ind].reactant[i].second) {\n\t\t\t\tthis->reaction_v_sk[reaction_ind].reaction_rate = 0.0;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\telse\n\t\t\t\tthis->reaction_v_sk[reaction_ind].reaction_rate *= pow(this->species_conc_v_sk[reaction_v_sk[reaction_ind].reactant[i].first], reaction_v_sk[reaction_ind].reactant[i].second);\n\t\t}\n\t}\n\n\tvoid srkin_sr::srkin::cal_reaction_rate_discrete()\n\t{\n\t\tfor (std::size_t i = 0; i < this->reaction_v_sk.size(); ++i)\n\t\t\tcal_reaction_rate_discrete(i);\n\t}\n\n\trsp::reaction_rate_t srkin::get_reaction_rate(const std::size_t reaction_ind)\n\t{\n\t\treturn this->reaction_v_sk[reaction_ind].reaction_rate;\n\t}\n\n\trsp::reaction_rate_t srkin::cal_spe_destruction_rate(const std::size_t spe_ind)\n\t{\n\t\tdouble spe_dr_tp = 0.0;\n\t\tfor (std::size_t i = 0; i < species_v_sk[spe_ind].reaction_k_index_s_coef_v.size(); ++i) {\n\t\t\tspe_dr_tp += reaction_v_sk[species_v_sk[spe_ind].reaction_k_index_s_coef_v[i].first].reaction_rate *species_v_sk[spe_ind].reaction_k_index_s_coef_v[i].second;\n\t\t}\n\t\treturn spe_dr_tp;\n\t}\n\n\tvoid srkin::cal_spe_destruction_rate(const double * T, const double * C, double * CDOT, double * DDOT)\n\t{\n\t\tset_temperature(*T);\n\t\tset_species_conc_v(C);\n\t\tcal_reaction_rate();\n\n\t\tfor (std::size_t i = 0; i < this->species_v_sk.size(); ++i) {\n\t\t\tCDOT[i] = 0.0;\n\t\t\tDDOT[i] = cal_spe_destruction_rate(i);\n\t\t}\n\t}\n\n} /*namespace srkin_sr */\n\n#endif /* __SRKIN_CPP_ */\n\n\n\n", "meta": {"hexsha": "3581e9de530be5aba6ed700351e406ba724f3cef", "size": 6505, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/srkin/srkin.cpp", "max_stars_repo_name": "AdamPI314/SOHR", "max_stars_repo_head_hexsha": "eec472ec98c69ce58d8dee1bc5bfc4a2bf9063c6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2017-08-11T23:29:56.000Z", "max_stars_repo_stars_event_max_datetime": "2020-07-22T18:13:50.000Z", "max_issues_repo_path": "src/srkin/srkin.cpp", "max_issues_repo_name": "AdamPI314/SOHR", "max_issues_repo_head_hexsha": "eec472ec98c69ce58d8dee1bc5bfc4a2bf9063c6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/srkin/srkin.cpp", "max_forks_repo_name": "AdamPI314/SOHR", "max_forks_repo_head_hexsha": "eec472ec98c69ce58d8dee1bc5bfc4a2bf9063c6", "max_forks_repo_licenses": ["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.2558139535, "max_line_length": 179, "alphanum_fraction": 0.7271329746, "num_tokens": 1965, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6334102636778401, "lm_q2_score": 0.5039061705290805, "lm_q1q2_score": 0.31917934034371553}}
{"text": "/*\n * Copyright (c) 2013, Christian Gehring, Hannes Sommer, Paul Furgale, Remo Diethelm\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *     * Redistributions of source code must retain the above copyright\n *       notice, this list of conditions and the following disclaimer.\n *     * Redistributions in binary form must reproduce the above copyright\n *       notice, this list of conditions and the following disclaimer in the\n *       documentation and/or other materials provided with the distribution.\n *     * Neither the name of the Autonomous Systems Lab, ETH Zurich nor the\n *       names of its contributors may be used to endorse or promote products\n *       derived from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL Christian Gehring, Hannes Sommer, Paul Furgale,\n * Remo Diethelm BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,\n * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE\n * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n*/\n\n#ifndef KINDR_ROTATIONS_EIGEN_ANGLEAXIS_HPP_\n#define KINDR_ROTATIONS_EIGEN_ANGLEAXIS_HPP_\n\n#include <cmath>\n\n#include <Eigen/Geometry>\n\n#include \"kindr/common/common.hpp\"\n#include \"kindr/common/assert_macros_eigen.hpp\"\n#include \"kindr/rotations/RotationBase.hpp\"\n#include \"kindr/rotations/eigen/RotationEigenFunctions.hpp\"\n\nnamespace kindr {\nnamespace rotations {\nnamespace eigen_impl {\n\n/*! \\class AngleAxis\n * \\brief Implementation of an angle axis rotation based on Eigen::AngleAxis\n *\n *  The following two typedefs are provided for convenience:\n *   - \\ref eigen_impl::AngleAxisAD \"AngleAxisAD\" for active rotation and primitive type double\n *   - \\ref eigen_impl::AngleAxisAF \"AngleAxisAF\" for active rotation and primitive type float\n *   - \\ref eigen_impl::AngleAxisPD \"AngleAxisPD\" for passive rotation and primitive type double\n *   - \\ref eigen_impl::AngleAxisPF \"AngleAxisPF\" for passive rotation and primitive type float\n *\n *  \\tparam PrimType_ the primitive type of the data (double or float)\n *  \\tparam Usage_ the rotation usage which is either active or passive\n *\n *  \\ingroup rotations\n */\ntemplate<typename PrimType_, enum RotationUsage Usage_>\nclass AngleAxis : public AngleAxisBase<AngleAxis<PrimType_, Usage_>, Usage_> {\n private:\n  /*! \\brief The base type.\n   */\n  typedef Eigen::AngleAxis<PrimType_> Base;\n\n  /*! Data container\n   */\n  Base angleAxis_;\n\n public:\n  /*! \\brief The implementation type.\n   *  The implementation type is always an Eigen object.\n   */\n  typedef Base Implementation;\n  /*! \\brief The primitive type.\n   *  Float/Double\n   */\n  typedef PrimType_ Scalar;\n  /*! \\brief The axis type is a 3D vector.\n   */\n  typedef Eigen::Matrix<PrimType_, 3, 1> Vector3;\n\n  /*! \\brief All four parameters stored in a vector [angle; axis]\n   */\n  typedef Eigen::Matrix<PrimType_, 4, 1> Vector4;\n\n  /*! \\brief Default constructor using identity rotation.\n   */\n  AngleAxis()\n    : angleAxis_(Base::Identity()) {\n  }\n\n  /*! \\brief Constructor using four scalars.\n   *  In debug mode, an assertion is thrown if the rotation vector has not unit length.\n   *  \\param angle     rotation angle\n   *  \\param v1      first entry of the rotation axis vector\n   *  \\param v2      second entry of the rotation axis vector\n   *  \\param v3      third entry of the rotation axis vector\n   */\n  AngleAxis(Scalar angle, Scalar v1, Scalar v2, Scalar v3)\n    : angleAxis_(angle,Vector3(v1,v2,v3)) {\n    KINDR_ASSERT_SCALAR_NEAR_DBG(std::runtime_error, this->axis().norm(), static_cast<Scalar>(1), static_cast<Scalar>(1e-4), \"Input rotation axis has not unit length.\");\n  }\n\n  /*! \\brief Constructor using angle and axis.\n   * In debug mode, an assertion is thrown if the rotation vector has not unit length.\n   * \\param angle   rotation angle\n   * \\param axis     rotation vector with unit length (Eigen vector)\n   */\n  AngleAxis(Scalar angle, const Vector3& axis)\n    : angleAxis_(angle,axis) {\n    KINDR_ASSERT_SCALAR_NEAR_DBG(std::runtime_error, this->axis().norm(), static_cast<Scalar>(1), static_cast<Scalar>(1e-4), \"Input rotation axis has not unit length.\");\n  }\n\n\n  /*! \\brief Constructor using a 4x1matrix.\n   * In debug mode, an assertion is thrown if the rotation vector has not unit length.\n   * \\param vector     4x1-matrix with [angle; axis]\n   */\n  AngleAxis(const Vector4& vector)\n    : angleAxis_(vector(0),vector.template block<3,1>(1,0)) {\n    KINDR_ASSERT_SCALAR_NEAR_DBG(std::runtime_error, this->axis().norm(), static_cast<Scalar>(1), static_cast<Scalar>(1e-4), \"Input rotation axis has not unit length.\");\n  }\n\n  /*! \\brief Constructor using Eigen::AngleAxis.\n   *  In debug mode, an assertion is thrown if the rotation vector has not unit length.\n   *  \\param other   Eigen::AngleAxis<PrimType_>\n   */\n  explicit AngleAxis(const Base& other) // explicit on purpose\n    : angleAxis_(other) {\n    KINDR_ASSERT_SCALAR_NEAR_DBG(std::runtime_error, this->axis().norm(), static_cast<Scalar>(1), static_cast<Scalar>(1e-4), \"Input rotation axis has not unit length.\");\n  }\n\n  /*! \\brief Constructor using another rotation.\n   *  \\param other   other rotation\n   */\n  template<typename OtherDerived_>\n  inline explicit AngleAxis(const RotationBase<OtherDerived_, Usage_>& other)\n    : angleAxis_(internal::ConversionTraits<AngleAxis, OtherDerived_>::convert(other.derived()).toImplementation()) {\n  }\n\n  /*! \\brief Assignment operator using another rotation.\n   *  \\param other   other rotation\n   *  \\returns reference\n   */\n  template<typename OtherDerived_>\n  AngleAxis& operator =(const RotationBase<OtherDerived_, Usage_>& other) {\n    this->toImplementation() = internal::ConversionTraits<AngleAxis, OtherDerived_>::convert(other.derived()).toImplementation();\n    return *this;\n  }\n\n  /*! \\brief Parenthesis operator to convert from another rotation.\n   *  \\param other   other rotation\n   *  \\returns reference\n   */\n  template<typename OtherDerived_>\n  AngleAxis& operator ()(const RotationBase<OtherDerived_, Usage_>& other) {\n    this->toImplementation() = internal::ConversionTraits<AngleAxis, OtherDerived_>::convert(other.derived()).toImplementation();\n    return *this;\n  }\n\n  /*! \\brief Returns the inverse of the rotation.\n   *  \\returns the inverse of the rotation\n   */\n  AngleAxis inverted() const {\n    Base inverse = this->toImplementation().inverse();\n    inverse.angle() = -inverse.angle();\n    inverse.axis() = -inverse.axis();\n    return AngleAxis(inverse);\n  }\n\n  /*! \\brief Inverts the rotation.\n   *  \\returns reference\n   */\n  AngleAxis& invert() {\n    *this = this->inverted();\n    return *this;\n  }\n\n  /*! \\brief Cast to the implementation type.\n   *  \\returns the implementation for direct manipulation (recommended only for advanced users)\n   */\n  inline Implementation& toImplementation() {\n    return static_cast<Implementation&>(angleAxis_);\n  }\n\n  /*! \\brief Cast to the implementation type.\n   *  \\returns the implementation for direct manipulation (recommended only for advanced users)\n   */\n  inline const Implementation& toImplementation() const {\n    return static_cast<const Implementation&>(angleAxis_);\n  }\n\n  /*! \\brief Returns the rotation angle.\n   *  \\returns rotation angle (scalar)\n   */\n  inline Scalar angle() const {\n    return angleAxis_.angle();\n  }\n\n  /*! \\brief Sets the rotation angle.\n   */\n  inline void setAngle(Scalar angle) {\n    angleAxis_.angle() = angle;\n  }\n\n  /*! \\brief Returns the rotation axis.\n   *  \\returns rotation axis (vector)\n   */\n  inline const Vector3& axis() const {\n    return angleAxis_.axis();\n  }\n\n  /*! \\brief Sets the rotation axis.\n   */\n  inline void setAxis(const Vector3& axis) {\n    angleAxis_.axis() = axis;\n    KINDR_ASSERT_SCALAR_NEAR_DBG(std::runtime_error, this->axis().norm(), static_cast<Scalar>(1), static_cast<Scalar>(1e-4), \"Input rotation axis has not unit length.\");\n  }\n\n  /*! \\brief Sets the rotation axis.\n   */\n  inline void setAxis(Scalar v1, Scalar v2, Scalar v3) {\n    angleAxis_.axis() = Vector3(v1,v2,v3);\n    KINDR_ASSERT_SCALAR_NEAR_DBG(std::runtime_error, this->axis().norm(), static_cast<Scalar>(1), static_cast<Scalar>(1e-4), \"Input rotation axis has not unit length.\");\n  }\n\n  /*! \\brief Sets angle-axis from a 4x1-matrix\n   */\n  inline void setVector(const Vector4& vector) {\n    this->setAngle(vector(0));\n    this->setAxis(vector.template block<3,1>(1,0));\n  }\n\n  /*! \\returns the angle and axis in a 4x1 vector [angle; axis].\n   */\n  inline Vector4 vector() const {\n    Vector4 vector;\n    vector(0) = angle();\n    vector.template block<3,1>(1,0) = axis();\n    return vector;\n  }\n\n\n  /*! \\brief Sets the rotation to identity.\n   *  \\returns reference\n   */\n  AngleAxis& setIdentity() {\n    this->setAngle(static_cast<Scalar>(0));\n    this->setAxis(static_cast<Scalar>(1), static_cast<Scalar>(0), static_cast<Scalar>(0));\n    return *this;\n  }\n\n  /*! \\brief Returns a unique angle axis rotation with angle in [0,pi].\n   *  This function is used to compare different rotations.\n   *  \\returns copy of the angle axis rotation which is unique\n   */\n  AngleAxis getUnique() const {\n    AngleAxis aa(kindr::common::floatingPointModulo(angle()+M_PI,2*M_PI)-M_PI, axis()); // first wraps angle into [-pi,pi)\n    if(aa.angle() > 0)  {\n      return aa;\n    } else if(aa.angle() < 0) {\n      if(aa.angle() != -M_PI) {\n        return AngleAxis(-aa.angle(),-aa.axis());\n      } else { // angle == -pi, so axis must be viewed further, because -pi,axis does the same as -pi,-axis\n\n        if(aa.axis()[0] < 0) {\n          return AngleAxis(-aa.angle(),-aa.axis());\n        } else if(aa.axis()[0] > 0) {\n          return AngleAxis(-aa.angle(),aa.axis());\n        } else { // v1 == 0\n\n          if(aa.axis()[1] < 0) {\n            return AngleAxis(-aa.angle(),-aa.axis());\n          } else if(aa.axis()[1] > 0) {\n            return AngleAxis(-aa.angle(),aa.axis());\n          } else { // v2 == 0\n\n            if(aa.axis()[2] < 0) { // v3 must be -1 or 1\n              return AngleAxis(-aa.angle(),-aa.axis());\n            } else  {\n              return AngleAxis(-aa.angle(),aa.axis());\n            }\n          }\n        }\n      }\n    } else { // angle == 0\n      return AngleAxis();\n    }\n  }\n\n  /*! \\brief Modifies the angle axis rotation such that the lies angle in [0,pi).\n   *  \\returns reference\n   */\n  AngleAxis& setUnique() {\n    *this = getUnique();\n    return *this;\n  }\n\n  /*! \\brief Concenation operator.\n   *  This is explicitly specified, because Eigen provides also an operator*.\n   *  \\returns the concenation of two rotations\n   */\n  using AngleAxisBase<AngleAxis<PrimType_, Usage_>, Usage_>::operator*;\n\n  /*! \\brief Used for printing the object with std::cout.\n   *  \\returns std::stream object\n   */\n  friend std::ostream& operator << (std::ostream& out, const AngleAxis& a) {\n    out << a.angle() << \", \" << a.axis().transpose();\n    return out;\n  }\n};\n\n//! \\brief Active angle axis rotation with double primitive type\ntypedef AngleAxis<double, RotationUsage::ACTIVE>  AngleAxisAD;\n//! \\brief Active angle axis rotation with float primitive type\ntypedef AngleAxis<float,  RotationUsage::ACTIVE>  AngleAxisAF;\n//! \\brief Passive angle axis rotation with double primitive type\ntypedef AngleAxis<double, RotationUsage::PASSIVE> AngleAxisPD;\n//! \\brief Passive angle axis rotation with float primitive type\ntypedef AngleAxis<float,  RotationUsage::PASSIVE> AngleAxisPF;\n\n\n\n} // namespace eigen_impl\n\n\nnamespace internal {\n\ntemplate<typename PrimType_, enum RotationUsage Usage_>\nclass get_scalar<eigen_impl::AngleAxis<PrimType_, Usage_>> {\n public:\n  typedef PrimType_ Scalar;\n};\n\ntemplate<typename PrimType_, enum RotationUsage Usage_>\nclass get_matrix3X<eigen_impl::AngleAxis<PrimType_, Usage_>>{\n public:\n  typedef int  IndexType;\n\n  template <IndexType Cols>\n  using Matrix3X = Eigen::Matrix<PrimType_, 3, Cols>;\n};\n\n\ntemplate<typename PrimType_>\nclass get_other_usage<eigen_impl::AngleAxis<PrimType_, RotationUsage::ACTIVE>> {\n public:\n  typedef eigen_impl::AngleAxis<PrimType_, RotationUsage::PASSIVE> OtherUsage;\n};\n\ntemplate<typename PrimType_>\nclass get_other_usage<eigen_impl::AngleAxis<PrimType_, RotationUsage::PASSIVE>> {\n public:\n  typedef eigen_impl::AngleAxis<PrimType_, RotationUsage::ACTIVE> OtherUsage;\n};\n\n/* -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------\n * Conversion Traits\n * ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- */\ntemplate<typename DestPrimType_, typename SourcePrimType_, enum RotationUsage Usage_>\nclass ConversionTraits<eigen_impl::AngleAxis<DestPrimType_, Usage_>, eigen_impl::AngleAxis<SourcePrimType_, Usage_>> {\n public:\n  inline static eigen_impl::AngleAxis<DestPrimType_, Usage_> convert(const eigen_impl::AngleAxis<SourcePrimType_, Usage_>& a) {\n    return eigen_impl::AngleAxis<DestPrimType_, Usage_>(a.toImplementation().template cast<DestPrimType_>());\n  }\n};\n\ntemplate<typename DestPrimType_, typename SourcePrimType_, enum RotationUsage Usage_>\nclass ConversionTraits<eigen_impl::AngleAxis<DestPrimType_, Usage_>, eigen_impl::RotationVector<SourcePrimType_, Usage_>> {\n public:\n  inline static eigen_impl::AngleAxis<DestPrimType_, Usage_> convert(const eigen_impl::RotationVector<SourcePrimType_, Usage_>& rotationVector) {\n    typedef typename eigen_impl::RotationVector<SourcePrimType_, Usage_>::Scalar Scalar;\n\n    const eigen_impl::RotationVector<DestPrimType_, Usage_> rv(rotationVector);\n\n    if (rv.toImplementation().norm() < common::internal::NumTraits<Scalar>::dummy_precision()) {\n      return eigen_impl::AngleAxis<DestPrimType_, Usage_>();\n    }\n    return eigen_impl::AngleAxis<DestPrimType_, Usage_>(rv.toImplementation().norm(), rv.toImplementation().normalized());\n  }\n};\n\ntemplate<typename DestPrimType_, typename SourcePrimType_, enum RotationUsage Usage_>\nclass ConversionTraits<eigen_impl::AngleAxis<DestPrimType_, Usage_>, eigen_impl::RotationQuaternion<SourcePrimType_, Usage_>> {\n public:\n  inline static eigen_impl::AngleAxis<DestPrimType_, Usage_> convert(const eigen_impl::RotationQuaternion<SourcePrimType_, Usage_>& q) {\n    return eigen_impl::AngleAxis<DestPrimType_, Usage_>(eigen_impl::eigen_internal::getAngleAxisFromQuaternion<SourcePrimType_, DestPrimType_>(q.toImplementation()));\n  }\n};\n\ntemplate<typename DestPrimType_, typename SourcePrimType_, enum RotationUsage Usage_>\nclass ConversionTraits<eigen_impl::AngleAxis<DestPrimType_, Usage_>, eigen_impl::RotationMatrix<SourcePrimType_, Usage_>> {\n public:\n  inline static eigen_impl::AngleAxis<DestPrimType_, Usage_> convert(const eigen_impl::RotationMatrix<SourcePrimType_, Usage_>& rotationMatrix) {\n//    return eigen_impl::AngleAxis<DestPrimType_, Usage_>(eigen_impl::getAngleAxisFromRotationMatrix<SourcePrimType_, DestPrimType_>(rotationMatrix.toImplementation()));\n//    return eigen_impl::AngleAxis<DestPrimType_, Usage_>(eigen_impl::eigen_internal::getAngleAxisFromRotationMatrix<SourcePrimType_, DestPrimType_>(rotationMatrix.toImplementation()));\n\n//   if (Usage_ == RotationUsage::ACTIVE) {\n//     return eigen_impl::AngleAxis<DestPrimType_, Usage_>(eigen_impl::eigen_internal::getAngleAxisFromRotationMatrix<SourcePrimType_, DestPrimType_>(rotationMatrix.matrix()));\n//\n//   }\n//   if (Usage_ == RotationUsage::PASSIVE) {\n//     return eigen_impl::AngleAxis<DestPrimType_, Usage_>(eigen_impl::eigen_internal::getAngleAxisFromRotationMatrix<SourcePrimType_, DestPrimType_>(rotationMatrix.toImplementation()));\n//\n//   }\n//\n   return eigen_impl::AngleAxis<DestPrimType_, Usage_>(eigen_impl::eigen_internal::getAngleAxisFromRotationMatrix<SourcePrimType_, DestPrimType_>(rotationMatrix.toImplementation()));\n\n  }\n};\n\ntemplate<typename DestPrimType_, typename SourcePrimType_, enum RotationUsage Usage_>\nclass ConversionTraits<eigen_impl::AngleAxis<DestPrimType_, Usage_>, eigen_impl::EulerAnglesXyz<SourcePrimType_, Usage_>> {\n public:\n  inline static eigen_impl::AngleAxis<DestPrimType_, Usage_> convert(const eigen_impl::EulerAnglesXyz<SourcePrimType_, Usage_>& xyz) {\n    return eigen_impl::AngleAxis<DestPrimType_, Usage_>(eigen_impl::eigen_internal::getAngleAxisFromRpy<SourcePrimType_, DestPrimType_>(xyz.toImplementation()));\n  }\n};\n\ntemplate<typename DestPrimType_, typename SourcePrimType_, enum RotationUsage Usage_>\nclass ConversionTraits<eigen_impl::AngleAxis<DestPrimType_, Usage_>, eigen_impl::EulerAnglesZyx<SourcePrimType_, Usage_>> {\n public:\n  inline static eigen_impl::AngleAxis<DestPrimType_, Usage_> convert(const eigen_impl::EulerAnglesZyx<SourcePrimType_, Usage_>& zyx) {\n    return eigen_impl::AngleAxis<DestPrimType_, Usage_>(eigen_impl::eigen_internal::getAngleAxisFromYpr<SourcePrimType_, DestPrimType_>(zyx.toImplementation()));\n  }\n};\n\n/* -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------\n * Multiplication Traits\n * ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- */\n\n/* -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------\n * Rotation Traits\n * ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- */\n\n\n\n/* -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------\n * Comparison Traits\n * ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- */\ntemplate<typename PrimType_, enum RotationUsage Usage_>\nclass ComparisonTraits<eigen_impl::AngleAxis<PrimType_, Usage_>, eigen_impl::AngleAxis<PrimType_, Usage_>> {\n public:\n  inline static bool isEqual(const eigen_impl::AngleAxis<PrimType_, Usage_>& a, const eigen_impl::AngleAxis<PrimType_, Usage_>& b){\n    const double tolPercent = 0.01;\n    return common::eigen::compareRelative(a.angle(), b.angle(), tolPercent) &&\n        common::eigen::compareRelative(a.axis().x(), b.axis().x(), tolPercent) &&\n        common::eigen::compareRelative(a.axis().y(), b.axis().y(), tolPercent) &&\n        common::eigen::compareRelative(a.axis().z(), b.axis().z(), tolPercent);\n  }\n};\n\n/* -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------\n * Fixing Traits\n * ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- */\ntemplate<typename PrimType_, enum RotationUsage Usage_>\nclass FixingTraits<eigen_impl::AngleAxis<PrimType_, Usage_>> {\n public:\n  inline static void fix(eigen_impl::AngleAxis<PrimType_, Usage_>& aa) {\n    aa.setAxis(aa.axis().normalized());\n  }\n};\n\n} // namespace internal\n} // namespace rotations\n} // namespace kindr\n\n\n#endif /* KINDR_ROTATIONS_EIGEN_ANGLEAXIS_HPP_ */\n", "meta": {"hexsha": "9f32f0c60284cb6206d5da8ca2531b19db7a74af", "size": 20453, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "IHMCPerception/third-party/kindr/include/kindr/rotations/eigen/AngleAxis.hpp", "max_stars_repo_name": "wxmerkt/ihmc-open-robotics-software", "max_stars_repo_head_hexsha": "2c47c9a9bd999e7811038e99c3888683f9973a2a", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 170.0, "max_stars_repo_stars_event_min_datetime": "2016-02-01T18:58:50.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-17T05:28:01.000Z", "max_issues_repo_path": "IHMCPerception/third-party/kindr/include/kindr/rotations/eigen/AngleAxis.hpp", "max_issues_repo_name": "wxmerkt/ihmc-open-robotics-software", "max_issues_repo_head_hexsha": "2c47c9a9bd999e7811038e99c3888683f9973a2a", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 162.0, "max_issues_repo_issues_event_min_datetime": "2016-01-29T17:04:29.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-10T16:25:37.000Z", "max_forks_repo_path": "IHMCPerception/third-party/kindr/include/kindr/rotations/eigen/AngleAxis.hpp", "max_forks_repo_name": "wxmerkt/ihmc-open-robotics-software", "max_forks_repo_head_hexsha": "2c47c9a9bd999e7811038e99c3888683f9973a2a", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 83.0, "max_forks_repo_forks_event_min_datetime": "2016-01-28T22:49:01.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T03:11:24.000Z", "avg_line_length": 43.3326271186, "max_line_length": 217, "alphanum_fraction": 0.6443553513, "num_tokens": 4578, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.596433160611502, "lm_q2_score": 0.5350984286266115, "lm_q1q2_score": 0.3191504470240181}}
{"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 <vector>\n#include <math.h>\n#include <string>\n#include <boost/lexical_cast.hpp>\n#include \"analysistool.h\"\n#include <votca/tools/histogram.h>\n#include <votca/csg/version.h>\n#include \"bondedstatistics.h\"\n#include \"tabulatedpotential.h\"\n\nusing namespace std;\nusing namespace boost;\n\nTabulatedPotential::TabulatedPotential()\n{\n    _tab_smooth1 = _tab_smooth2 = 0;\n    _T = 300;\n}\n\nvoid TabulatedPotential::Register(map<string, AnalysisTool *> &lib)\n{\n    lib[\"tab\"] = this;\n    lib[\"hist\"] = this;\n}\n\nvoid TabulatedPotential::Command(BondedStatistics &bs, string cmd, vector<string> &args)\n{\n    if(args[0] == \"set\") {\n        if(cmd == \"hist\") 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 = lexical_cast<int>(args[2]);       \n                    else if(args[1] == \"smooth_pot\")\n                        _tab_smooth2 = lexical_cast<int>(args[2]);       \n                    else if(args[1] == \"T\")\n                        _T = 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: \" << _T << endl;\n            }\n        }\n    }\n    else if(args.size() >= 2) {\n        if(cmd == \"hist\") WriteHistogram(bs, args);\n        else if(cmd == \"tab\") WritePotential(bs, args);\n    }\n    else cout << \"wrong number of arguments\" << endl;\n}\n\n\nvoid TabulatedPotential::Help(string cmd, vector<string> &args)\n{\n    if(args.size() == 0) {\n        if(cmd == \"tab\") {\n            cout << \"tab <file> <selection>\\n\"\n                 << \"Calculate tabulated potential by inverting the distribution function. \"\n                    \"Statistics is calculated using all interactions in selection.\\n\"\n                    \"see also: help tab set\\n\\n\"\n                    \"example:\\ntab set scale bond\\ntab U_bond.txt *:bond:*\\n\";\n        }\n        if(cmd == \"hist\") {\n            cout << \"hist <file> <selection>\\n\"\n                 << \"Calculate distribution function for selection. \"\n                    \"Statistics is calculated using all interactions in selection.\\n\"\n                    \"see also: help hist set\\n\\n\"\n                    \"example: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 << \" set\\\"\"\n                    \" for a list of available options. To get help on a 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, 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, 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 << \"set auto <value>\\n\"\n                 \"can be 1 for automatically determine the interval for the \"\n                 \"table (min, max, extend will be ignored) or 0 to use min/max as specified\\n\";\n            return;\n        }\n        if(args[1] == \"extend\") {\n            cout << cmd << \"set extend <value>\\n\"\n                 \"should only be used with auto=0. Can be 1 for extend the interval \"\n                 \"if values are out of bounds (min/max) \"\n                 \"or 0 to ignore values which are out of the interal\\n\";\n            return;\n        }\n        if(args[1] == \"scale\") {\n            cout << cmd << \"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 << cmd << \"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 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 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\nbool TabulatedPotential::SetOption(Histogram::options_t &op, const vector<string> &args)\n{\n    if(args.size() >2) {\n        if(args[1] == \"n\")\n            op._n = lexical_cast<int>(args[2]);       \n        else if(args[1] == \"min\") {\n            op._min = lexical_cast<double>(args[2]);\n        }\n        else if(args[1] == \"max\")\n            op._max = lexical_cast<double>(args[2]);\n        else if(args[1] == \"periodic\")\n            op._periodic = lexical_cast<bool>(args[2]);\n        else if(args[1] == \"auto\")\n            op._auto_interval = lexical_cast<bool>(args[2]);\n        else if(args[1] == \"extend\")\n            op._extend_interval = lexical_cast<bool>(args[2]);\n        else if(args[1] == \"normalize\")\n            op._normalize = 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        }\n        else {\n            return false;        \n        }\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::WriteHistogram(BondedStatistics &bs, vector<string> &args)\n{\n    ofstream out;\n    DataCollection<double>::selection *sel = NULL;\n\n    for(size_t i=1; i<args.size(); i++)\n        sel = bs.BondedValues().select(args[i], sel);\n    Histogram h(_hist_options);\n    h.ProcessData(sel);\n    out.open(args[0].c_str());\n/*    out << \"# histogram, created csg version \" <<  VERSION_STR  << endl;\n    out << \"# n = \" << _hist_options._n << endl;\n    out << \"# min = \" << _hist_options._min << endl;\n    out << \"# max = \" << _hist_options._max << endl;\n    out << \"# periodic = \" << _hist_options._periodic << endl;\n    out << \"# auto = \" << _hist_options._auto_interval << endl;\n    out << \"# extend = \" << _hist_options._extend_interval << endl;\n    out << \"# scale = \" << _hist_options._scale << endl;*/\n    out << h ;\n    out.close();\n    cout << \"histogram created using \" << sel->size() << \" data-rows, written to \" << args[0] << endl;    \n    delete sel;\n}\n\n\nvoid TabulatedPotential::CalcForce(vector<double> &U, vector<double> &F, double dx, bool bPeriodic)\n{\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\nvoid TabulatedPotential::WritePotential(BondedStatistics &bs, vector<string> &args)\n{\n   ofstream out;\n    DataCollection<double>::selection *sel = NULL;\n\n    for(size_t i=1; i<args.size(); i++)\n        sel = bs.BondedValues().select(args[i], sel);\n    Histogram h(_tab_options);\n    h.ProcessData(sel);\n    for(int i=0; i<_tab_smooth1; ++i)\n        Smooth(h.getPdf(), _tab_options._periodic);\n    BoltzmannInvert(h.getPdf(), _T);\n    for(int i=0; i<_tab_smooth2; ++i)\n        Smooth(h.getPdf(), _tab_options._periodic);\n    out.open(args[0].c_str());\n    \n/*       out << \"# tabulated potential, created csg version \" VERSION_STR  << endl;\n    out << \"# n = \" << _tab_options._n << endl;\n    out << \"# min = \" << _tab_options._min << endl;\n    out << \"# max = \" << _tab_options._max << endl;\n    out << \"# periodic = \" << _tab_options._periodic << endl;\n    out << \"# auto = \" << _tab_options._auto_interval << endl;\n    out << \"# extend = \" << _tab_options._extend_interval << endl;\n    out << \"# scale = \" << _tab_options._scale << endl;\n    out << \"# smooth_pdf = \" << _tab_smooth1 << endl;\n    out << \"# smooth_pot = \" << _tab_smooth2 << endl;\n    out << \"# T = \" << _T << endl;*/\n\n    vector<double> F;\n    \n    CalcForce(h.getPdf(), F, h.getInterval(), _tab_options._periodic);\n    for(int i=0; i<h.getN(); i++) {\n        out << h.getMin() + h.getInterval()*((double)i) << \" \" << h.getPdf()[i] << \" \" << F[i] << endl;\n    }\n    out.close();\n    cout << \"histogram created using \" << sel->size() << \" data-rows, written to \" << args[0] << endl;\n    delete sel;\n}\n\nvoid TabulatedPotential::Smooth(vector<double> &data, bool bPeriodic)\n{\n    double old[3];\n    int n=data.size();\n    if(bPeriodic) {\n        old[0] = data[n-3];\n        old[1] = data[n-2];\n    }\n    else {\n        old[0] = data[0];\n        old[1] = data[0];\n    }\n    size_t i;\n    for(i=0; i<data.size()-2; i++) {\n        old[2] = data[i];\n        data[i] = (old[0] + 2.*old[1] + 3.*data[i] + 2.*data[i+1] + data[i+2])/9.;\n        old[0]=old[1];\n        old[1]=old[2];;\n    }\n    if(bPeriodic) {\n        data[i] = (old[0] + 2.*old[1] + 3.*data[i] + 2.*data[i+1] + data[0])/9.;\n        old[0]=old[1];old[1]=data[i];\n        data[n-1] = data[0];\n    }\n    else {\n        data[i] = (old[0] + 2.*old[1] + 3.*data[i] + 3.*data[i+1])/9.;\n        old[0]=old[1];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, double T)\n{\n    double _min, _max;\n    \n    _min = numeric_limits<double>::max();\n    _max = numeric_limits<double>::min();\n    \n    for(size_t i=0; i<data.size(); i++) {\n        _max = max(data[i], _max);\n        if(data[i] > 0) _min = min(data[i], _min);\n    }\n    _max = -8.3109*T*log(_max)*0.001;\n    _min = -8.3109*T*log(_min)*0.001-_max;\n    \n    for(size_t i=0; i<data.size(); i++) {\n        if(data[i] == 0) data[i] = _min;\n        else\n            data[i] = -8.3109*T*log(data[i])*0.001 - _max;\n    }\n}\n", "meta": {"hexsha": "9f81bffc854df59dac6dd423fd8f3f14df9bf5bf", "size": 12322, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/csg_boltzmann/tabulatedpotential.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/csg_boltzmann/tabulatedpotential.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/csg_boltzmann/tabulatedpotential.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": 35.408045977, "max_line_length": 118, "alphanum_fraction": 0.5099009901, "num_tokens": 3344, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5350984286266116, "lm_q2_score": 0.5964331462646255, "lm_q1q2_score": 0.31915043934702714}}
{"text": "// deal.II includes ----------------------------------------------\n#include <deal.II/dofs/dof_handler.h>\n#include <deal.II/fe/fe_q.h>\n#include <deal.II/grid/grid_in.h>\n#include <deal.II/lac/vector.h>\n\n#include <deal.II/numerics/data_out.h>\n\n// system includes -----------------------------------------------\n#include <hdf5.h>\n#include <omp.h>\n#include <yaml-cpp/yaml.h>\n#include <Eigen/Dense>\n#include <algorithm>\n#include <boost/filesystem.hpp>\n#include <boost/lexical_cast.hpp>\n#include <boost/program_options.hpp>\n#include <ctime>\n#include <fstream>\n#include <iostream>\n// from eigen unsupported\n#include <Eigen/KroneckerProduct>\n\n// own includes --------------------------------------------------\n#include \"aux/eigen2hdf.hpp\"\n#include \"aux/message.hpp\"\n#include \"aux/timer.hpp\"\n#include \"grid_transfer.hpp\"\n#include \"init/import/load_coefficients.hpp\"\n#include \"post_processing/energy.hpp\"\n#include \"post_processing/mass.hpp\"\n#include \"post_processing/momentum.hpp\"\n\n#include \"l2errors.hpp\"\n#include \"spectral/basis/indexer.hpp\"\n// class SimpleGridHandler, Solution\n#include \"grid/grid_tools.hpp\"\n#include \"outer_product_helper.hpp\"\n#include \"solution_handler.hpp\"\n#include \"spectral_transfer_matrix.hpp\"\n\n#include \"export/data_out_hdf5.hpp\"\n\nusing namespace boltzmann;\nusing namespace std;\n\nconst int dim = 2;\n\nnamespace bf = boost::filesystem;\nnamespace po = boost::program_options;\n\ntemplate <typename SPECTRAL_BASIS>\nvoid make_overlap(std::vector<double>& S, const SPECTRAL_BASIS& spectral_basis)\n{\n  typedef typename SPECTRAL_BASIS::elem_t elem_t;\n\n  // angular basis\n  typedef typename std::tuple_element<0, typename SPECTRAL_BASIS::elem_t::container_t>::type\n      angular_elem_t;\n  typename elem_t::Acc::template get<angular_elem_t> acc_ang;\n\n  // inverse mass matrix\n  S.resize(spectral_basis.n_dofs());\n  for (unsigned int j = 0; j < spectral_basis.n_dofs(); ++j) {\n    auto& elem = spectral_basis.get_elem(j);\n    if (acc_ang(elem).get_id().l == 0)\n      S[j] = numbers::PI;\n    else\n      S[j] = numbers::PI / 2;\n  }\n}\n\ntypedef dealii::DoFHandler<dim> dh_t;\ntypedef dealii::Vector<double> vector_t;\n\nint main(int argc, char* argv[])\n{\n  // #pragma omp parallel\n  // {\n  //   #pragma omp master\n  //   {\n  //     int num_threads = omp_get_num_threads();\n  //     Eigen::setNbThreads(num_threads);\n  //     cout << \"Eigen is using \" << Eigen::nbThreads() << \" threads \\n\";\n  //   }\n\n  // }\n\n  boltzmann::Timer<> timer;\n\n  po::options_description options(\"options\");\n  options.add_options()\n      (\"config,c\", po::value<string>()->required(), \"config file\")\n      (\"help,h\", \"help\");\n  po::variables_map vm;\n  po::store(po::parse_command_line(argc, argv, options), vm);\n  if (vm.count(\"help\")) {\n    cout << options << \"\\n\";\n    return 0;\n  }\n\n  po::notify(vm);\n\n  string config_name = vm[\"config\"].as<string>();\n\n  if (!boost::filesystem::is_regular_file(config_name)) {\n    cout << \"config file not found\\n\";\n    return 1;\n  }\n\n  // load yaml config\n  YAML::Node config = YAML::LoadFile(config_name);\n\n  string str_input_grid = config[\"input\"][\"grid\"].as<string>();\n  string str_input_path = config[\"input\"][\"path\"].as<string>();\n\n  string str_ref_grid = config[\"reference\"][\"grid\"].as<string>();\n  string str_ref_path = config[\"reference\"][\"path\"].as<string>();\n\n  auto cwd = bf::current_path();\n\n  // initialize working directory\n  bf::path working_dir = bf::path(str_input_path) / bf::path(\"convergence_plots\");\n  bf::create_directory(working_dir);\n\n  // initialize logfile\n  std::time_t result = std::time(nullptr);\n  cout << argv[0] << \"at: \" << asctime(localtime(&result)) << \", executed in \" << cwd.c_str()\n       << endl\n       << setw(14) << \"Solution: \" << (working_dir / bf::path(str_input_path)).c_str() << setw(14)\n       << \"Reference: \" << (working_dir / bf::path(str_ref_path)).c_str() << endl;\n\n  // ------------------------------------------------------------------------------------------\n  // transfer matrix\n  dealii::FE_Q<dim> fe(1);\n  auto ref_grid_ptr = make_shared<SimpleGridHandler>(str_ref_path, str_ref_grid);\n  auto grid_ptr = make_shared<SimpleGridHandler>(str_input_path, str_input_grid);\n\n  const auto& ref_dh = ref_grid_ptr->get_dofhandler();\n  const auto& input_dh = grid_ptr->get_dofhandler();\n\n  cout << \"Reference mesh: \" << ref_dh.get_triangulation().n_used_vertices() << \" vertices, \"\n       << ref_dh.get_triangulation().n_active_cells() << \" cells.\" << endl;\n\n  timer.start();\n  GridTransfer<dim> grid_transfer;\n  grid_transfer.init(ref_dh, input_dh);\n  const auto& Tx = grid_transfer.get_transfer_matrix();\n  print_timer(timer.stop(), \"init GridTransfer\");\n\n  // output to hdf5\n  hid_t file;\n  file = H5Fcreate((working_dir / bf::path(\"transfer_matrix.h5\")).c_str(),\n                   H5F_ACC_TRUNC,\n                   H5P_DEFAULT,\n                   H5P_DEFAULT);\n  eigen2hdf::save_sparse(file, \"Tx\", Tx);\n\n  // spectral transfer matrix\n  auto Tv =\n      spectral_transfer_matrix(ref_grid_ptr->get_spectral_basis(), grid_ptr->get_spectral_basis());\n  eigen2hdf::save_sparse(file, \"Tv\", Tv);\n\n  // timer.start();\n  // Eigen::SparseMatrix<double> T = Eigen::kroneckerProduct(Tx, Tv);\n  // print_timer(timer.stop(), \"kroneckerProduct\");\n  // timer.start();\n  // eigen2hdf::save_sparse(file, \"T\", T);\n  // print_timer(timer.stop(), \"dump transfer matrix\");\n\n  // ------------------------------------------------------------------------------------------\n  // load solution filenames from config\n  // S contains (b_i (v), b_i (v))_R^2\n  vector<double> S;\n  make_overlap(S, ref_grid_ptr->get_spectral_basis());\n\n  // load permutations from `vertex2dofidx.dat`\n  std::vector<unsigned int> ref_perm(ref_grid_ptr->get_dofhandler().n_dofs());\n  std::vector<unsigned int> input_perm(grid_ptr->get_dofhandler().n_dofs());\n  // load permutation from ``\n  load_permutation(ref_perm, str_ref_path);\n  load_permutation(input_perm, str_input_path);\n\n  auto ref_perm_tmp = v2d_permutation_vector(ref_dh);\n  auto input_perm_tmp = v2d_permutation_vector(input_dh);\n\n  Mass mass(ref_grid_ptr->get_spectral_basis());\n  Momentum momentum(ref_grid_ptr->get_spectral_basis());\n  Energy energy(ref_grid_ptr->get_spectral_basis());\n\n  dealii::Vector<double> vmass(ref_dh.n_dofs());\n  dealii::Vector<double> venergy(ref_dh.n_dofs());\n  dealii::Vector<double> vux(ref_dh.n_dofs());  // momentum x\n  dealii::Vector<double> vuy(ref_dh.n_dofs());  // momnetum y\n\n  unsigned int nsteps = config[\"timesteps\"].size();\n  cout << \"__ERRORS__\\n\";\n  cout << setw(15) << \"# i\" << setw(15) << \"t\" << setw(15) << \"l2_squared\" << setw(15)\n       << \"l2_m_squared\" << setw(15) << \"l2_u_squared\" << setw(15) << \"l2_e_squared\" << endl;\n\n  for (unsigned int i = 0; i < nsteps; ++i) {\n    string str_h5loc_ref = config[\"timesteps\"][i][\"reference\"][\"data\"].as<string>();\n    string str_h5loc_inp = config[\"timesteps\"][i][\"input\"][\"data\"].as<string>();\n    double time = config[\"timesteps\"][i][\"time\"].as<double>();\n\n    Eigen::VectorXd v_inp;  // approximate solution\n    Eigen::VectorXd v_ref;  // reference solution\n\n    load_solution_vector(v_inp, str_input_path, str_h5loc_inp);\n    load_solution_vector(v_ref, str_ref_path, str_h5loc_ref);\n\n    // transform to vertex ordering\n    to_vertex_ordering(v_inp, input_perm);\n    to_vertex_ordering(v_ref, ref_perm);\n\n    // transform to active dofhandler ordering\n    to_dof_ordering(v_inp, input_perm_tmp);\n    to_dof_ordering(v_ref, ref_perm_tmp);\n\n    // Eigen::VectorXd v_sol = T*v_inp;\n    Eigen::VectorXd v_sol(v_ref.size());\n    sparse_outer_product_multiply(v_sol, Tx, Tv, v_inp);\n\n    Errors errors;\n    double l2_error_sq =\n        errors.compute(ref_dh, v_sol.data(), v_ref.data(), S, ref_grid_ptr->get_indexer());\n\n    Eigen::VectorXd vdiff = v_sol - v_ref;\n    mass.compute(vmass.begin(), vdiff.data(), ref_dh.n_dofs());\n    energy.compute(venergy.begin(), vdiff.data(), ref_dh.n_dofs());\n    momentum.compute(vux.begin(), vuy.begin(), vdiff.data(), ref_dh.n_dofs());\n    std::for_each(vmass.begin(), vmass.end(), [](double v) { return std::abs(v); });\n    std::for_each(venergy.begin(), venergy.end(), [](double v) { return std::abs(v); });\n    std::transform(vux.begin(), vux.end(), vuy.begin(), vux.begin(), [](double x, double y) {\n      return std::sqrt(x * x + y * y);\n    });\n\n    double l2diff_m = l2norm(ref_dh, vmass);\n    double l2diff_u = l2norm(ref_dh, vux);\n    double l2diff_e = l2norm(ref_dh, venergy);\n\n    cout << setw(15) << i << setw(15) << time << setw(15) << scientific << setprecision(5)\n         << l2_error_sq << setw(15) << scientific << setprecision(5) << l2diff_m << setw(15)\n         << scientific << setprecision(5) << l2diff_u << setw(15) << scientific << setprecision(5)\n         << l2diff_e << endl;\n\n    // output\n    {\n      // dealii::DataOut<dim> data_out;\n      dealii::DataOutHDF<dim> data_out;\n      // data_out.attach_triangulation(ref_dh.get_triangulation());\n      data_out.attach_dof_handler(ref_dh);\n      const auto& cell_wise_error = errors.get_cell_wise_error();\n      //      cout << \"cell_wise_error.size = \" << cell_wise_error.size() << endl;\n      data_out.add_data_vector(cell_wise_error, \"error^2\");\n      data_out.add_data_vector(vmass, \"err_mass\");\n      data_out.add_data_vector(venergy, \"err_energy\");\n      data_out.add_data_vector(vux, \"err_abs(u)\");\n      //  data_out.add_data_vector(tmp_out, \"test_direct\");\n      data_out.build_patches();\n\n      dealii::DataOutBase::VtkFlags flags;\n      data_out.set_flags(flags);\n      // auto fname = \"errors\" + boost::lexical_cast<string>(i) + \".vtk\";\n      // std::ofstream vtk_output((working_dir / bf::path(fname)).c_str());\n      // data_out.write_vtk(vtk_output);\n      // vtk_output.close();\n      typedef dealii::DataOutBase::DataOutFilterFlags data_out_filter_flags;\n      dealii::DataOutBase::DataOutFilter data_out_filter(data_out_filter_flags(true, true));\n      data_out.write_filtered_data(data_out_filter);\n      string filename =\n          (working_dir / bf::path(\"output\" + boost::lexical_cast<string>(i) + \".h5\")).c_str();\n      string mesh_filename = (working_dir / bf::path(\"mesh.hdf5\")).c_str();\n      data_out.write_hdf5(filename, data_out_filter);\n      auto xdmf_entry = data_out.create_xdmf_entry(data_out_filter, mesh_filename, filename, time);\n\n      auto xdmf_file = working_dir / bf::path(\"solution.xdmf\");\n      std::ofstream fout(xdmf_file.c_str(), std::ios_base::out | std::ios_base::app);\n      fout << xdmf_entry.get_xdmf_content(1) << std::endl;\n      fout.close();\n\n      if (i == 0) {\n        data_out.write_mesh(mesh_filename, data_out_filter);\n      }\n    }\n  }\n\n  H5Fclose(file);\n\n  return 0;\n}\n", "meta": {"hexsha": "aab9b998017a48f469509c308ea126b0d3c012c3", "size": 10609, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "applications/convergence_plots/main.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": "applications/convergence_plots/main.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": "applications/convergence_plots/main.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.3321917808, "max_line_length": 99, "alphanum_fraction": 0.6528419267, "num_tokens": 2817, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6187804337438501, "lm_q2_score": 0.5156199157230157, "lm_q1q2_score": 0.3190555150980551}}
{"text": "#include \"HilbertOrder3D.hpp\"\n#include \"HilbertOrder3D_Utils.hpp\"\n#include <boost/array.hpp>\n#include <algorithm>\n#include <ctime>\n#include <iostream>\n#ifdef RICH_MPI\n#include <mpi.h>\n#endif\n\n\n#define NUMBER_OF_SHAPES 24\n#define MAX_ROTATION_LENGTH 5\n#define PI 3.14159\n\nusing namespace std;\n\n// The elementary Hilbert Curve shape:\nclass HilbertCurve3D_shape\n{\npublic:\n\t// Constructor\n\tHilbertCurve3D_shape();\n\t// Comparison:\n\tbool operator==(HilbertCurve3D_shape & shape);\n\t// An array of the 7 unit vector steps defining the shape:\n\tboost::array<Vector3D, 7> m_vShapePoints;\n\n};\n// Constructor - uses the reference Hilbert curve shape:\nHilbertCurve3D_shape::HilbertCurve3D_shape() : m_vShapePoints(boost::array<Vector3D, 7>())\n{\n\tm_vShapePoints[0] = Vector3D(0, 0, -1);\n\tm_vShapePoints[1] = Vector3D(0, 1, 0);\n\tm_vShapePoints[2] = Vector3D(0, 0, 1);\n\tm_vShapePoints[3] = Vector3D(-1, 0, 0);\n\tm_vShapePoints[4] = Vector3D(0, 0, -1);\n\tm_vShapePoints[5] = Vector3D(0, -1, 0);\n\tm_vShapePoints[6] = Vector3D(0, 0, 1);\n}\n\n// Compare to a given Hilbert curve shape by comparing pairs of shape points:\nbool HilbertCurve3D_shape::operator==(HilbertCurve3D_shape & shape)\n{\n\tbool b = true;\n\tfor (std::size_t ii = 0; ii < m_vShapePoints.size(); ++ii)\n\t{\n\t\tb = b && (m_vShapePoints[ii] == shape.m_vShapePoints[ii]);\n\t}\n\n\treturn b;\n}\n\n// The Hilbert Curve class:\nclass HilbertCurve3D\n{\npublic:\n\t// Constructor\n\tHilbertCurve3D(void);\n\t// Calculate the Hilbert curve distance of a given point, given a required number of iterations:\n\tunsigned long long int Hilbert3D_xyz2d(Vector3D const & rvPoint, int numOfIterations);\n\nprivate:\n\t// Rotate a shape according to a given rotation scheme (in-place):\n\tvoid RotateShape(int iShapeIndex, vector<int> vAxes);\n\t// Rotate a shape according to rotation index, and return the rotated shape:\n\tvoid RotateShape(HilbertCurve3D_shape const & roShape, HilbertCurve3D_shape & roShapeOut, int iRotationIndex);\n\t/*!\n\t\\brief Returns the rotation scheme, according to a rotation index\n\t\\param piRotation - a pointer to the output rotation scheme vector\n\t\\param iRotationIndex - the desired rotation index\n\t\\return The rotation scheme length (the size of the array given by piRotation)\n\t*/\n\tint GetRotation(int * piRotation, int iRotationIndex);\n\t// Find the index of a given shape object:\n\tint FindShapeIndex(HilbertCurve3D_shape & roShape);\n\t// Create the recursion rule:\n\tvoid BuildRecursionRule();\n\t// Create the shape order, for all shapes (the order of octants):\n\tvoid BuildShapeOrder();\n\n\t// Stores all rotated shapes:\n\tboost::array<HilbertCurve3D_shape, NUMBER_OF_SHAPES> m_vRotatedShapes;\n\t// Stores all rotation schemes:\n\tboost::array < vector<int>, NUMBER_OF_SHAPES > m_vRotations;\n\n\t// An array of the 8 integers defining the recursion rule of the shape:\n\tboost::array< boost::array<int, 8> , NUMBER_OF_SHAPES> m_vShapeRecursion;\n\n\t// A 2x2x2 matrix indicating the 3 dimensional shape order\n\t// array< array<int , 8 > , NUMBER_OF_SHAPES > m_mShapeOrder;\n\tint m_mShapeOrder[NUMBER_OF_SHAPES][2][2][2];\n};\n\n// Constructor - performs all required initiallizations and preprocessing:\nHilbertCurve3D::HilbertCurve3D() :m_vRotatedShapes(boost::array<HilbertCurve3D_shape, NUMBER_OF_SHAPES> ()), m_vRotations(boost::array < vector<int>, NUMBER_OF_SHAPES >()),\nm_vShapeRecursion(boost::array< boost::array<int, 8> , NUMBER_OF_SHAPES>())\n{\n\tint rot[MAX_ROTATION_LENGTH];\n\tint iRotLength;\n\tfor (int iRotIndex = 1; iRotIndex < NUMBER_OF_SHAPES; ++iRotIndex)\n\t{\n\t\tiRotLength = GetRotation(rot, iRotIndex);\n\t\tm_vRotations[iRotIndex].assign(rot, rot + iRotLength);\n\t}\n\n\tfor (int ii = 1; ii < NUMBER_OF_SHAPES; ++ii)\n\t{\n\t\tRotateShape(ii, m_vRotations[ii]);\n\t}\n\n\tBuildRecursionRule();\n\tBuildShapeOrder();\n}\n\n// FindShapeIndex - returns the index of a shape:\nint HilbertCurve3D::FindShapeIndex(HilbertCurve3D_shape & roShape)\n{\n\tfor (int ii = 0; ii < NUMBER_OF_SHAPES; ++ii)\n\t{\n\t\tif (roShape == m_vRotatedShapes[ii])\n\t\t{\n\t\t\treturn ii;\n\t\t}\n\t}\n\t// TODO - manage this kind of return value (error)\n\treturn -1;\n}\n\nvoid HilbertCurve3D::BuildRecursionRule()\n{\n\t// Reference recursion rule:\n\tm_vShapeRecursion[0][0] = 12;\n\tm_vShapeRecursion[0][1] = 16;\n\tm_vShapeRecursion[0][2] = 16;\n\tm_vShapeRecursion[0][3] = 2;\n\tm_vShapeRecursion[0][4] = 2;\n\tm_vShapeRecursion[0][5] = 14;\n\tm_vShapeRecursion[0][6] = 14;\n\tm_vShapeRecursion[0][7] = 10;\n\n\tHilbertCurve3D_shape oTempShape;\n\t// What about ii=0? not necessary \n\tfor (int ii = 0; ii < NUMBER_OF_SHAPES; ++ii)\n\t{\n\t\tfor (int jj = 0; jj < 8; ++jj)\n\t\t{\n\t\t\t// Rotate the appropriate block of the reference recursion rule, according to the ii rotation scheme:\n\t\t\tRotateShape(m_vRotatedShapes[m_vShapeRecursion[0][jj]], oTempShape, ii);\n\t\t\t// Find the shape index of the rotated shape:\n\t\t\tm_vShapeRecursion[ii][jj] = FindShapeIndex(oTempShape);\n\t\t}\n\t}\n\n\treturn;\n}\n\n// Return the rotation scheme of the ii rotation (manually precalculated):\nint HilbertCurve3D::GetRotation(int * piRotation, int iRotationIndex)\n{\n\tswitch (iRotationIndex)\n\t{\n\tcase 1:\n\t\tpiRotation[0] = 1;\n\t\treturn 1;\n\tcase 2:\n\t\tpiRotation[0] = 1;\n\t\tpiRotation[1] = 1;\n\t\treturn 2;\n\tcase 3:\n\t\tpiRotation[0] = 1;\n\t\tpiRotation[1] = 1;\n\t\tpiRotation[2] = 1;\n\t\treturn 3;\n\t\n\tcase 4:\n\t\tpiRotation[0] = 2;\n\t\treturn 1;\n\tcase 5:\n\t\tpiRotation[0] = 2;\n\t\tpiRotation[1] = 2;\n\t\treturn 2;\n\tcase 6:\n\t\tpiRotation[0] = 2;\n\t\tpiRotation[1] = 2;\n\t\tpiRotation[2] = 2;\n\t\treturn 3;\n\n\tcase 7:\n\t\tpiRotation[0] = 3;\n\t\treturn 1;\n\tcase 8:\n\t\tpiRotation[0] = 3;\n\t\tpiRotation[1] = 3;\n\t\treturn 2;\n\tcase 9:\n\t\tpiRotation[0] = 3;\n\t\tpiRotation[1] = 3;\n\t\tpiRotation[2] = 3;\n\t\treturn 3;\n\n\tcase 10:\n\t\tpiRotation[0] = 1;\n\t\tpiRotation[1] = 2;\n\t\treturn 2;\n\tcase 11:\n\t\tpiRotation[0] = 2;\n\t\tpiRotation[1] = 1;\n\t\treturn 2;\n\tcase 12:\n\t\tpiRotation[0] = 3;\n\t\tpiRotation[1] = 1;\n\t\treturn 2;\n\tcase 13:\n\t\tpiRotation[0] = 2;\n\t\tpiRotation[1] = 3;\n\t\treturn 2;\n\n\tcase 14:\n\t\tpiRotation[0] = 1;\n\t\tpiRotation[1] = 1;\n\t\tpiRotation[2] = 1;\n\t\tpiRotation[3] = 3;\n\t\treturn 4;\n\tcase 15:\n\t\tpiRotation[0] = 2;\n\t\tpiRotation[1] = 2;\n\t\tpiRotation[2] = 2;\n\t\tpiRotation[3] = 1;\n\t\treturn 4;\n\tcase 16:\n\t\tpiRotation[0] = 3;\n\t\tpiRotation[1] = 3;\n\t\tpiRotation[2] = 3;\n\t\tpiRotation[3] = 2;\n\t\treturn 4;\n\tcase 17:\n\t\tpiRotation[0] = 3;\n\t\tpiRotation[1] = 2;\n\t\tpiRotation[2] = 3;\n\t\tpiRotation[3] = 2;\n\t\treturn 4;\n\tcase 18:\n\t\tpiRotation[0] = 3;\n\t\tpiRotation[1] = 2;\n\t\tpiRotation[2] = 2;\n\t\treturn 3;\n\n\tcase 19:\n\t\tpiRotation[0] = 1;\n\t\tpiRotation[1] = 1;\n\t\tpiRotation[2] = 1;\n\t\tpiRotation[3] = 2;\n\t\tpiRotation[4] = 2;\n\t\treturn 5;\n\tcase 20:\n\t\tpiRotation[0] = 3;\n\t\tpiRotation[1] = 3;\n\t\tpiRotation[2] = 2;\n\t\treturn 3;\n\tcase 21:\n\t\tpiRotation[0] = 3;\n\t\tpiRotation[1] = 3;\n\t\tpiRotation[2] = 1;\n\t\treturn 3;\n\tcase 22:\n\t\tpiRotation[0] = 2;\n\t\tpiRotation[1] = 2;\n\t\tpiRotation[2] = 3;\n\t\treturn 3;\n\tcase 23:\n\t\tpiRotation[0] = 1;\n\t\tpiRotation[1] = 1;\n\t\tpiRotation[2] = 2;\n\t\treturn 3;\n\n\tdefault:\n\t\treturn 0;\n\t\tbreak;\n\t}\n}\n\n// Rotate a shape:\nvoid HilbertCurve3D::RotateShape(int iShapeIndex, vector<int> vAxes)\n{\n\tint iSign = 0;\n\n\tfor (std::size_t ii = 0; ii < 7; ++ii)\n\t{\n\t\tfor (std::size_t iAx = 0; iAx < vAxes.size(); ++iAx)\n\t\t{\n\t\t\t// A trick to find the sign of vAxes[iAx]:\n\t\t\tiSign = (vAxes[iAx] > 0) - (vAxes[iAx] < 0);\n\n\t\t\tswitch (abs(vAxes[iAx]))\n\t\t\t{\n\t\t\tcase 1:\n\t\t\t\tm_vRotatedShapes[iShapeIndex].m_vShapePoints[ii].RotateX( iSign * PI / 2 );\n\t\t\t\tbreak;\n\t\t\tcase 2:\n\t\t\t\tm_vRotatedShapes[iShapeIndex].m_vShapePoints[ii].RotateY( iSign * PI / 2 );\n\t\t\t\tbreak;\n\t\t\tcase 3:\n\t\t\t\tm_vRotatedShapes[iShapeIndex].m_vShapePoints[ii].RotateZ( iSign * PI / 2 );\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\t// Round off the results:\n\t\tm_vRotatedShapes[iShapeIndex].m_vShapePoints[ii].Round();\n\t}\n}\n\nvoid HilbertCurve3D::RotateShape(HilbertCurve3D_shape const & roShape, HilbertCurve3D_shape & roShapeOut , int iRotationIndex)\n{\n\tint iSign = 0;\n\n\tvector<int> vAxes = m_vRotations[iRotationIndex];\n\troShapeOut = roShape;\n\n\tfor (int ii = 0; ii < 7; ++ii)\n\t{\n\t\tfor (std::size_t iAx = 0; iAx < vAxes.size(); ++iAx)\n\t\t{\n\t\t\t// A trick to find the sign of vAxes[iAx]:\n\t\t\tiSign = (vAxes[iAx] > 0) - (vAxes[iAx] < 0);\n\n\t\t\tswitch (abs(vAxes[iAx]))\n\t\t\t{\n\t\t\tcase 1:\n\t\t\t\troShapeOut.m_vShapePoints[ii].RotateX(iSign * PI / 2);\n\t\t\t\tbreak;\n\t\t\tcase 2:\n\t\t\t\troShapeOut.m_vShapePoints[ii].RotateY(iSign * PI / 2);\n\t\t\t\tbreak;\n\t\t\tcase 3:\n\t\t\t\troShapeOut.m_vShapePoints[ii].RotateZ(iSign * PI / 2);\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\t// Round off the results:\n\t\troShapeOut.m_vShapePoints[ii].Round();\n\t}\n\n\treturn;\n}\n\nvoid HilbertCurve3D::BuildShapeOrder()\n{\n\tboost::array<int, 8> vShapeVerticesX;\n\tboost::array<int, 8> vShapeVerticesY;\n\tboost::array<int, 8> vShapeVerticesZ;\n\n\tvShapeVerticesX[0] = 0;\n\tvShapeVerticesY[0] = 0;\n\tvShapeVerticesZ[0] = 0;\n\n\tfor (std::size_t iShapeInd = 0; iShapeInd < NUMBER_OF_SHAPES; ++iShapeInd)\n\t{\n\t\tfor (std::size_t ii = 0; ii < m_vRotatedShapes[iShapeInd].m_vShapePoints.size(); ++ii)\n\t\t{\n\t\t\tvShapeVerticesX[ii + 1] = (int)(vShapeVerticesX[ii] + m_vRotatedShapes[iShapeInd].m_vShapePoints[ii].x);\n\t\t\tvShapeVerticesY[ii + 1] = (int)(vShapeVerticesY[ii] + m_vRotatedShapes[iShapeInd].m_vShapePoints[ii].y);\n\t\t\tvShapeVerticesZ[ii + 1] = (int)(vShapeVerticesZ[ii] + m_vRotatedShapes[iShapeInd].m_vShapePoints[ii].z);\n\t\t}\n\n\t\tint iMinX = *min_element(vShapeVerticesX.begin(), vShapeVerticesX.end());\n\t\tint iMinY = *min_element(vShapeVerticesY.begin(), vShapeVerticesY.end());\n\t\tint iMinZ = *min_element(vShapeVerticesZ.begin(), vShapeVerticesZ.end());\n\n\t\tfor (std::size_t jj = 0; jj < vShapeVerticesX.size(); ++jj)\n\t\t{\n\t\t\tvShapeVerticesX[jj] -= iMinX;\n\t\t\tvShapeVerticesY[jj] -= iMinY;\n\t\t\tvShapeVerticesZ[jj] -= iMinZ;\n\t\t}\n\n\t\tfor (std::size_t kk = 0; kk < vShapeVerticesX.size(); ++kk)\n\t\t{\n\t\t\tm_mShapeOrder[iShapeInd][vShapeVerticesX[kk]][vShapeVerticesY[kk]][vShapeVerticesZ[kk]] = static_cast<int>(kk);\n\t\t}\n\t}\n\n\treturn;\n}\n\nunsigned long long int HilbertCurve3D::Hilbert3D_xyz2d(Vector3D const & rvPoint, int numOfIterations)\n{\n\t// Extract the coordinates:\n\tdouble x = rvPoint.x;\n\tdouble y = rvPoint.y;\n\tdouble z = rvPoint.z;\n\n\t// The output distance along the 3D-Hilbert Curve:\n\tunsigned long long int d = 0;\n\n\t// The current shape index:\n\tint iCurrentShape = 0;\n\t// The octant number:\n\tint iOctantNum = 0;\n\t// A temp variable - storing the current (negative) power of 2\n\tdouble dbPow2;\n\t// Variables indicating the current octant:\n\tbool bX, bY, bZ;\n\tfor (int iN = 1; iN <= numOfIterations; ++iN)\n\t{\n\t\t// Calculate the current power of 0.5:\n\t\tdbPow2 = ((double)1) / (1 << iN);\n\t\tbX = x > dbPow2;\n\t\tbY = y > dbPow2;\n\t\tbZ = z > dbPow2;\n\n\t\tx -= dbPow2*bX;\n\t\ty -= dbPow2*bY;\n\t\tz -= dbPow2*bZ;\n\n\t\t// Multiply the distance by 8 (for every recursion iteration):\n\t\td = d << 3;\n\t\tiOctantNum = m_mShapeOrder[iCurrentShape][bX][bY][bZ];\n\t\td = d + iOctantNum;\n\t\tiCurrentShape = m_vShapeRecursion[iCurrentShape][iOctantNum];\n\t}\n\n\treturn d;\n}\n\nvector<std::size_t> GetGlobalHibertIndeces(vector<Vector3D> const& cor,Vector3D const& ll,Vector3D const& ur,size_t &Hmax)\n{\n\tvector<std::size_t> res;\n#ifdef RICH_MPI\n\tint Nlocal = static_cast<int>(cor.size());\n\tint Ntotal = Nlocal;\n\tMPI_Allreduce(&Nlocal, &Ntotal, 1, MPI_INT, MPI_SUM, MPI_COMM_WORLD);\n#endif\n\tstd::size_t Niter = 20;\n\tHmax = static_cast<size_t>(std::pow(static_cast<size_t>(2), static_cast<size_t>(3*Niter)));\n\tHilbertCurve3D oHilbert;\n\tVector3D dx = ur - ll,vtemp;\n\tstd::size_t Ncor = cor.size();\n\tres.resize(Ncor);\n\tfor (size_t i = 0; i < Ncor; ++i)\n\t{\n\t\tvtemp.x = (cor[i].x - ll.x) / dx.x;\n\t\tvtemp.y = (cor[i].y - ll.y) / dx.y;\n\t\tvtemp.z = (cor[i].z - ll.z) / dx.z;\n\t\tres[i]=static_cast<size_t>(oHilbert.Hilbert3D_xyz2d(vtemp,static_cast<int>(Niter)));\n\t}\n\treturn res;\n}\n\nvector<std::size_t> HilbertOrder3D(vector<Vector3D> const& cor)\n{\n\t// If only 1 or 2 points are provided - do not reorder them\n\tif ( 2 >= cor.size() )\n\t{\n\t\tvector<std::size_t> vIndSort( cor.size() );\n\t\tfor (std::size_t ii = 0; ii < cor.size(); ++ii)\n\t\t{\n\t\t\tvIndSort[ii] = ii;\n\t\t}\n\t\treturn vIndSort;\n\t}\n\t// Create a 3D-Hilbert Curve Object:\n\tHilbertCurve3D oHilbert;\n\n\t// Allocate an output vector:\n\tsize_t N = cor.size();\n\tvector<unsigned long long int> vOut;\n\tvOut.resize(N);\n\t\n\t// Estimate the number of required iterations:\n\tint numOfIterations = EstimateHilbertIterationNum(cor);\n\n\tvector<Vector3D> vAdjustedPoints;\n\n\t// Adjust the points coordinates to the unit cube:\n\tAdjustPoints(cor, vAdjustedPoints);\n\n\t// Run throught the points, and calculate the Hilbert distance of each:\n\tfor (size_t ii = 0; ii < N; ++ii)\n\t{\n\t\tvOut[ii]=oHilbert.Hilbert3D_xyz2d(vAdjustedPoints[ii], numOfIterations+8);\n\t\t//vOut.push_back(oHilbert.Hilbert3D_xyz2d(vAdjustedPoints[ii], 2));\n\t}\n\t// Get the sorting indices:\n\tvector<std::size_t> vIndSort;\n\tordered(vOut, vIndSort);\n\t// Reorder the Hilbert distances vector (according to the sorting indices):\n\treorder( vOut, vIndSort );\n\n\t// Find indices with repeated Hilbert distance:\n\tvector<vector<std::size_t> > vEqualIndices;\n\tFindEqualIndices(vOut, vEqualIndices);\n\t\n\t// If all points have different Hilbert distances, return the sorting indices:\n\tif (vEqualIndices.empty())\n\t{\n\t\treturn vIndSort;\n\t}\n\telse\n\t{\n\t\tfor (std::size_t ii = 0; ii < vEqualIndices.size(); ++ii)\n\t\t{\n\t\t\tvector<Vector3D> vPointsInner(vEqualIndices[ii].size() );\n\t\t\tvector<std::size_t> vIndInner(vEqualIndices[ii].size());\n\t\t\tvector<std::size_t> vIndSortInner(vEqualIndices[ii].size());\n\t\t\tvector<std::size_t> vIndSortInner_cpy(vEqualIndices[ii].size());\n\n\t\t\t// Store the points with the equal indices\n\t\t\tfor (std::size_t jj = 0; jj < vEqualIndices[ii].size() ; ++jj)\n\t\t\t{\n\t\t\t\tvIndInner[jj] = vIndSort[vEqualIndices[ii][jj]];\n\t\t\t\tvPointsInner[jj] = cor[vIndInner[jj]];\n\t\t\t\tvIndSortInner_cpy[jj] = vIndSort[vIndInner[jj]];\n\t\t\t}\n\t\t\t\n\t\t\t// Sort the repeated points:\n\t\t\tvIndSortInner = HilbertOrder3D(vPointsInner);\n\t//\t\tvector<std::size_t> vIndSortTemp = vIndSort;\n\t\t\tfor (std::size_t kk = 0; kk < vIndSortInner.size(); ++kk)\n\t\t\t{\n\t\t\t\tvIndSort[vIndInner[kk]] = vIndSortInner_cpy[vIndSortInner[kk]];\n\t\t\t}\n\t\t}\n\n\t\t// Return the sorting indices:\n\t\treturn vIndSort;\n\t}\n}", "meta": {"hexsha": "8464595dae0007771730339d669727acdb158344", "size": 13901, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lib/SurfacingAlgorithms/huji-rich-Elad3DFast/source/3D/GeometryCommon/HilbertOrder3D.cpp", "max_stars_repo_name": "GalaxyHunters/Vivid", "max_stars_repo_head_hexsha": "f724e5671b650433d0c26319c86231bd3b246e4e", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "lib/SurfacingAlgorithms/huji-rich-Elad3DFast/source/3D/GeometryCommon/HilbertOrder3D.cpp", "max_issues_repo_name": "GalaxyHunters/Vivid", "max_issues_repo_head_hexsha": "f724e5671b650433d0c26319c86231bd3b246e4e", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 222.0, "max_issues_repo_issues_event_min_datetime": "2018-07-25T18:13:57.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-10T14:54:04.000Z", "max_forks_repo_path": "lib/SurfacingAlgorithms/huji-rich-Elad3DFast/source/3D/GeometryCommon/HilbertOrder3D.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": 26.1296992481, "max_line_length": 172, "alphanum_fraction": 0.6826846989, "num_tokens": 4797, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6187804337438501, "lm_q2_score": 0.5156199157230156, "lm_q1q2_score": 0.31905551509805496}}
{"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-2009 Zuse Institute Berlin                            */\n/*                                                                           */\n/*  KASKADE 7 is distributed under the terms of the ZIB Academic License.    */\n/*    see $KASKADE/academic.txt                                              */\n/*                                                                           */\n/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */\n\n#ifndef SCHURBLOCKLU_SOLVER_HH\n#define SCHURBLOCKLU_SOLVER_HH\n\n/**\n * @file\n * @brief  Routines for the solution of (sparse) linear systems\n * @author Anton Schiela\n */\n\n#include <iostream>\n#include <memory> // std::unique_ptr\n\n#include \"dune/common/fmatrix.hh\"\n#include \"dune/istl/matrix.hh\"\n\n#include \"linalg/umfpack_solve.hh\"\n\n#include \"linalg/linearsystem.hh\"\n#include \"linalg/simpleLAPmatrix.hh\"\n\n#include <boost/timer/timer.hpp>\n\nnamespace Kaskade\n{\n\n/** \\ingroup linalg \n *\\ brief Adapter class for DUNE::IterativeSolver\n */\n\n\nvoid printVec(std::vector<double> const&v, int vend=1000000);\n\n\ntemplate<class Factorization=UMFFactorization<double> >\nclass BlockLUFactorization\n{\npublic:\n/// needs a matrix\n  static const bool needMatrix = true;\ntemplate<class Sys>\nBlockLUFactorization(Sys const& lin, int start2, int end2, int start3, int end3)\n  {\n    MatrixAsTriplet<double> matL;\n    lin.getMatrixBlocks(matL,start3,end3,start2,end2);\n    matA.resize(0);\n    lin.getMatrixBlocks(matA,start2,end2,start2,end2);\n    std::cout << \"Inner, \" << std::flush;\n    boost::timer::cpu_timer timer;\n    factoredL.reset(new Factorization(matL.nrows(),\n                                      2,\n                                      matL.ridx, \n                                      matL.cidx, \n                                      matL.data,\n                                      MatrixProperties::GENERAL));\n    std::cout << \"Finished: \" << (double)(timer.elapsed().user)/1e9 << \" sec.\" << std::endl;\n  }\n\n  void resetBlock22(MatrixAsTriplet<double>const & matA_) { matA = matA_; };\n    \n  void solve(std::vector<double>const& rhs, std::vector<double>& sol, int nr=1);\n  MatrixAsTriplet<double> matA;\n  std::unique_ptr<Factorization> factoredL;\n};\n\nstruct BlockSchurParameters\n{\n  BlockSchurParameters(bool reg_)\n    : refactorizeInner(true), refactorizeOuter(true)\n  {\n    if(reg_) regularizationMethod=AddId; else regularizationMethod=None;\n  }\n\n  BlockSchurParameters(bool reg_, bool innerf_, bool outerf_)\n    : refactorizeInner(innerf_), refactorizeOuter(outerf_)\n  {\n    if(reg_) regularizationMethod=AddId; else regularizationMethod=None;\n  }\n\n  bool refactorizeInner, refactorizeOuter;\n  typedef enum { None=0, AddId=1, CG = 2} RegularizationMethod;\n\n  RegularizationMethod regularizationMethod;\n};\n\n\n/// Solver, which is especially designed for the hyperthermia planning problem. \ntemplate<class Factorization>\nclass DirectBlockSchurSolver\n{\npublic:\n  int start1, end1, start2, end2, start3, end3;\n\n/// needs a matrix\n  static const bool needMatrix = true;\n\n  DirectBlockSchurSolver(bool doregularize = false) : \n    start1(0), end1(1), \n    start2(1), end2(2), \n    start3(2), end3(3),\n    report(false), paras(doregularize)\n  {}\n\n  void ax(std::vector<double>& sol, std::vector<double>const &r) const;\n\n  void resolve(std::vector<double>& sol, SparseLinearSystem const& lin) const;\n\n  void resolveAdjAndNormal(std::vector<double>& sol, SparseLinearSystem const& lin) const;\n\n  void resolveNormal(std::vector<double>& sol, SparseLinearSystem const& lin,std::vector<double>const *addrhs=0);\n\n  void solve(std::vector<double>& sol,\n             SparseLinearSystem const& lin);\n\n  void solveAdjAndNormal(std::vector<double>& sol,\n             SparseLinearSystem const& lin);\n\n  void solveTCG(std::vector<double>& sol1, std::vector<double>& sol2,\n                SparseLinearSystem const& linT, SparseLinearSystem const& linN, std::vector<double>const & normalStep, double nu0);\n\n  /// Solves always exactly\n  void setRelativeAccuracy(double) {}\n\n  /// Always exact solution\n  double getRelativeAccuracy() {return 0.0;}\n\n  void onChangedLinearization() {flushFactorization(); }\n\n  void flushFactorization() \n  { \n    if(factorization.get() && paras.refactorizeInner) factorization.reset(); \n    mC.setSize(0,0);\n    B.resize(0);\n    AinvB.resize(0);\n    matANormal.flush();\n  }\n\n  bool report;\n\n  /// Always exact solution\n  double getAbsoluteAccuracy() {return 0.0;}\n\n  bool improvementPossible() { return false; }\n\n  void resetParameters(BlockSchurParameters const& p_) { paras=p_; }\n\nprivate:\n  void resolveN(std::vector<double>& sol, std::vector<double>const &r,std::vector<double>const &s,std::vector<double>const &t) const;\n\n  void tsolve(std::vector<double>& sol1,std::vector<double>& sol2, \n              std::vector<double>const &r,std::vector<double>const &s,std::vector<double>const &t) const;\n\n  void fwd(std::vector<double>& sol, std::vector<double>const &r,std::vector<double>const &s,std::vector<double>const &t) const;\n  void bwd(std::vector<double>& sol, std::vector<double>const &x2,std::vector<double>const &s,std::vector<double>const &t) const;\n\n\n  void buildNewSchurComplement(SparseLinearSystem const& lin,int task);\n\n  std::unique_ptr<BlockLUFactorization<Factorization> > factorization;\n  MatrixAsTriplet<double> matANormal;\n  Dune::Matrix<Dune::FieldMatrix<double,1,1> > mC,mCNormal;\n  std::vector<double> B,AinvB;\n\n  int rowsB, colsBC, rowsC;\n  int rows1, rows2, rows3;\n\n  BlockSchurParameters paras;\n\n};\n\n\nclass ModifiedSparseSystem : public SparseLinearSystem\n{\npublic:\n  ModifiedSparseSystem(SparseLinearSystem const &lin_, MatrixAsTriplet<double> const& mat_, MatrixAsTriplet<double> const& mat2_\n                       , std::vector<double> const& scaling_) :\n    scaling(scaling_), lin(&lin_), mat(mat_), mat2(mat2_)\n  {\n  }\n\n  virtual int rows(int rbegin, int rend) const { return lin->rows(rbegin,rend);}\n  virtual int cols(int colbegin, int colend) const { return lin->cols(colbegin,colend);}\n\n  /// Return matrix blocks of the linear system in triplet format \n  virtual void getMatrixBlocks(MatrixAsTriplet<double>& m, int rbegin, int rend, int colbegin, int colend) const\n  {\n    lin->getMatrixBlocks(m,rbegin,rend,colbegin,colend);\n    MatrixAsTriplet<double> mm(mat);\n    mm *= -1.0;\n    if(rbegin==0 && colbegin == 0) m+=mm;\n  }\n\n  void resetLin(SparseLinearSystem const& lin_)\n  {\n    lin=&lin_;\n  }\n\n  /// value of function\n  virtual double getValue() const { return lin->getValue();}\n\n  /// Return components of the right hand side of the linear system\n  virtual void getRHSBlocks(std::vector<double>& rhs, int rbegin, int rend) const \n  {\n    rhs.resize(0);\n    lin->getRHSBlocks(rhs,rbegin,rend);\n    if(rbegin==0)\n    {\n      std::vector<double> t(lin->rows(3,4),0.0);\n      std::vector<double> Mt(lin->rows(0,1),0.0);\n      lin->getRHSBlocks(t,3,4);\n      for(int i=0; i<t.size();++i)\n      {\n        t[i] *=scaling[i];\n      }\n      mat2.ax(Mt,t);\n      for(int i=0; i<Mt.size();++i)\n      {\n//        std::cout << Mt[i] << std::endl;\n      }\n      for(int i=0; i<lin->rows(0,1); ++i)\n        rhs[i] -= Mt[i];\n    }\n  }\n\n\n  /// number of column blocks\n  virtual int nColBlocks() const { return lin->nColBlocks();};\n\n  /// number of row blocks\n  virtual int nRowBlocks() const { return lin->nRowBlocks();};\nprivate:\n  std::vector<double> scaling;\n  SparseLinearSystem const* lin;\n  MatrixAsTriplet<double> mat;\n  MatrixAsTriplet<double> mat2;\n};\n\n\n/// Solver, which is especially designed for the hyperthermia planning problem with amplitude ratio\ntemplate<class Factorization>\nclass ARDirectBlockSchurSolver\n{\npublic:\n/// needs a matrix\n  static const bool needMatrix = true;\n\n  ARDirectBlockSchurSolver(bool doregularize = false) : report(false), DBSSolver(doregularize), justsolved(false) \n{\n}\n\n  void resolve(std::vector<double>& sol, SparseLinearSystem const& lin) const;\n\n  void solve(std::vector<double>& sol,\n             SparseLinearSystem const& lin);\n\n  /// Solves always exactly\n  void setRelativeAccuracy(double) {}\n\n  /// Always exact solution\n  double getRelativeAccuracy() {return 0.0;}\n\n  void onChangedLinearization() {flushFactorization(); }\n\n  void flushFactorization() \n  { \n    DBSSolver.flushFactorization();\n    F.setSize(0,0);\n    FT.setSize(0,0);\n    FTVinv.setSize(0,0);\n    FTVinvF.setSize(0,0);\n    Vinv.setSize(0,0);\n  }\n\n  bool report;\n\n  /// Always exact solution\n  double getAbsoluteAccuracy() {return 0.0;}\n\n  bool improvementPossible() { return false; }\n\n\nprivate:\n  std::vector<double> scaling;\n  DirectBlockSchurSolver<Factorization> DBSSolver;\n  Dune::Matrix<Dune::FieldMatrix<double,1,1> > Vinv,F,FT, FTVinv, FTVinvF;\n  std::unique_ptr<MatrixAsTriplet<double> > L,FTVi;\n  std::unique_ptr<ModifiedSparseSystem> linMod;\n  bool justsolved;\n};\n\n}  // namespace Kaskade\n#endif\n", "meta": {"hexsha": "886b35cebc6707c75a7a3a79ce6c5ad838fc611f", "size": 9241, "ext": "hh", "lang": "C++", "max_stars_repo_path": "Kaskade/linalg/schurblocklu_solve.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/schurblocklu_solve.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/schurblocklu_solve.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": 30.3980263158, "max_line_length": 133, "alphanum_fraction": 0.6391083216, "num_tokens": 2449, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6187804337438501, "lm_q2_score": 0.5156199157230156, "lm_q1q2_score": 0.31905551509805496}}
{"text": "// Copyright 2020 The Defold Foundation\n// Licensed under the Defold License version 1.0 (the \"License\"); you may not use\n// this file except in compliance with the License.\n//\n// You may obtain a copy of the License, together with FAQs at\n// https://www.defold.com/license\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 <stdio.h>\n#include <string.h>\n#include <stdlib.h>\n#include <assert.h>\n#include \"shared_library.h\"\n#include \"crypt.h\"\n\n#include <dlib/endian.h>\n#include <mbedtls/md5.h>\n#include <mbedtls/base64.h>\n#include <mbedtls/sha1.h>\n#include <mbedtls/sha256.h>\n#include <mbedtls/sha512.h>\n#include <mbedtls/pk.h>\n#include <mbedtls/pk_internal.h>\n#include <mbedtls/rsa.h>\n#include <mbedtls/entropy.h>\n#include <mbedtls/ctr_drbg.h>\n//Added by dotGears\n#include <mbedtls/md.h>\n\n#include <dlib/log.h> // For debugging the manifest verification issue\n\nnamespace dmCrypt\n{\n    const uint32_t NUM_ROUNDS = 32;\n\n    static inline uint64_t EncryptXTea(uint64_t v, uint32_t* key)\n    {\n        uint32_t v0 = (uint32_t) (v >> 32);\n        uint32_t v1 = (uint32_t) (v & 0xffffffff);\n\n        uint32_t sum = 0, delta = 0x9e3779b9;\n        for (uint32_t i = 0; i < NUM_ROUNDS; i++) {\n            v0 += (((v1 << 4) ^ (v1 >> 5)) + v1) ^ (sum + dmEndian::ToHost(key[sum & 3]));\n            sum += delta;\n            v1 += (((v0 << 4) ^ (v0 >> 5)) + v0) ^ (sum + dmEndian::ToHost(key[(sum>>11) & 3]));\n        }\n        uint64_t ret = dmEndian::ToHost((((uint64_t) v0) << 32 | v1));\n        return ret;\n    }\n\n    static void EncryptXTeaCTR(uint8_t* data, uint32_t datalen, const uint8_t* key, uint32_t keylen)\n    {\n        assert(keylen <= 16);\n        const uint32_t block_len = 8;\n        uint8_t paddedkey[16] = {0};\n        memcpy(paddedkey, key, keylen);\n\n        uint64_t counter = 0;\n\n        uint32_t i = 0;\n        uint64_t* d = (uint64_t*) data;\n        for (i = 0; i < datalen / block_len; i++) {\n            uint64_t enc_counter = EncryptXTea(counter, (uint32_t*) paddedkey);\n            d[i] ^= enc_counter;\n            data += block_len;\n            counter++;\n        }\n\n        uint64_t enc_counter = EncryptXTea(counter, (uint32_t*) paddedkey);\n        uint32_t rest = datalen & (block_len - 1);\n        uint8_t* ec = (uint8_t*) &enc_counter;\n        for (uint32_t j = 0; j < rest; j++) {\n            data[j] ^= ec[j];\n        }\n    }\n\n    Result Encrypt(Algorithm algo, uint8_t* data, uint32_t datalen, const uint8_t* key, uint32_t keylen)\n    {\n        EncryptXTeaCTR(data, datalen, key, keylen);\n        return RESULT_OK;\n    }\n\n    Result Decrypt(Algorithm algo, uint8_t* data, uint32_t datalen, const uint8_t* key, uint32_t keylen)\n    {\n        EncryptXTeaCTR(data, datalen, key, keylen);\n        return RESULT_OK;\n    }\n\n    // Same as rsa_alt_decrypt_wrap() except with a MBEDTLS_RSA_PUBLIC\n    static int rsa_alt_decrypt_public_wrap( void *ctx,\n                        const unsigned char *input, size_t ilen,\n                        unsigned char *output, size_t *olen, size_t osize,\n                        int (*f_rng)(void *, unsigned char *, size_t), void *p_rng )\n    {\n        mbedtls_rsa_context * rsa = (mbedtls_rsa_context *) ctx;\n\n        if( ilen != mbedtls_rsa_get_len( rsa ) )\n            return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );\n\n        return( mbedtls_rsa_pkcs1_decrypt( rsa, f_rng, p_rng,\n                    MBEDTLS_RSA_PUBLIC, olen, input, output, osize ) );\n    }\n\n    Result Decrypt(const uint8_t* key, uint32_t keylen, const uint8_t* data, uint32_t datalen, uint8_t** output, uint32_t* outputlen)\n    {\n        // https://tls.mbed.org/discussions/generic/parsing-public-key-from-memory\n        Result result = RESULT_OK;\n\n        const char* pers = \"defold_pk_decrypt\";\n        mbedtls_pk_context pk;\n        mbedtls_entropy_context entropy;\n        mbedtls_ctr_drbg_context ctr_drbg;\n        mbedtls_pk_init(&pk);\n        mbedtls_ctr_drbg_init( &ctr_drbg );\n        mbedtls_entropy_init( &entropy );\n\n        uint32_t signature_hash_len = MBEDTLS_MD_MAX_SIZE;\n\n        int ret;\n        if( ( ret = mbedtls_ctr_drbg_seed( &ctr_drbg, mbedtls_entropy_func, &entropy, (const unsigned char *) pers, strlen(pers) ) ) != 0 )\n        {\n            dmLogError(\"Decrypt: mbedtls_ctr_drbg_seed failed: %d\", ret);\n            result = RESULT_ERROR;\n            goto exit;\n        }\n\n        if ((ret = mbedtls_pk_parse_public_key(&pk, key, keylen) != 0))\n        {\n            dmLogError(\"Decrypt: mbedtls_pk_parse_public_key failed: %d\", ret);\n            result = RESULT_ERROR;\n            goto exit;\n        }\n\n        *output = (uint8_t*)malloc(signature_hash_len);\n        size_t _outputlen;\n        if ((ret = rsa_alt_decrypt_public_wrap(pk.pk_ctx,\n                    data, datalen,\n                    (uint8_t*)*output, &_outputlen, signature_hash_len,\n                    mbedtls_ctr_drbg_random, &ctr_drbg )) != 0)\n        {\n            dmLogError(\"Decrypt: rsa_alt_decrypt_public_wrap failed: %d\", ret);\n            free(*output);\n            result = RESULT_ERROR;\n            goto exit;\n        }\n\n        *outputlen = (uint32_t)_outputlen;\n\n    exit:\n        mbedtls_ctr_drbg_free( &ctr_drbg );\n        mbedtls_entropy_free( &entropy );\n        mbedtls_pk_free(&pk);\n        return result;\n    }\n\n    void HashSha1(const uint8_t* buf, uint32_t buflen, uint8_t* digest)\n    {\n        mbedtls_sha1_context ctx;\n        mbedtls_sha1_init(&ctx);\n        mbedtls_sha1_starts_ret(&ctx);\n        mbedtls_sha1_update_ret(&ctx, (const unsigned char*)buf, (size_t)buflen);\n        int ret = mbedtls_sha1_finish_ret(&ctx, (unsigned char*)digest);\n        mbedtls_sha1_free(&ctx);\n        if (ret != 0) {\n            memset(digest, 0, 20);\n        }\n    }\n\n    void HashSha256(const uint8_t* buf, uint32_t buflen, uint8_t* digest)\n    {\n        int ret = mbedtls_sha256_ret((const unsigned char*)buf, (size_t)buflen, (unsigned char*)digest, 0);\n        if (ret != 0) {\n            memset(digest, 0, 20);\n        }\n    }\n\n    void HashSha512(const uint8_t* buf, uint32_t buflen, uint8_t* digest)\n    {\n        int ret = mbedtls_sha512_ret((const unsigned char*)buf, (size_t)buflen, (unsigned char*)digest, 0);\n        if (ret != 0) {\n            memset(digest, 0, 20);\n        }\n    }\n\n    void HashMd5(const uint8_t* buf, uint32_t buflen, uint8_t* digest)\n    {\n        int ret = mbedtls_md5_ret((const unsigned char*)buf, (size_t)buflen, (unsigned char*)digest);\n        if (ret != 0) {\n            memset(digest, 0, 20);\n        }\n    }\n\n    bool Base64Encode(const uint8_t* src, uint32_t src_len, uint8_t* dst, uint32_t* dst_len)\n    {\n        size_t out_len = 0;\n        int r = mbedtls_base64_encode(dst, *dst_len, &out_len, src, src_len);\n        if (r != 0)\n        {\n            if (*dst_len == 0)\n                *dst_len = (uint32_t)out_len; // Seems to return 1 more than necessary, but better to err on the safe side! (see test_crypt.cpp)\n            else\n                *dst_len = 0xFFFFFFFF;\n            return false;\n        }\n        *dst_len = (uint32_t)out_len;\n        return true;\n    }\n\n    bool Base64Decode(const uint8_t* src, uint32_t src_len, uint8_t* dst, uint32_t* dst_len)\n    {\n        size_t out_len = 0;\n        int r = mbedtls_base64_decode(dst, *dst_len, &out_len, src, src_len);\n        if (r != 0)\n        {\n            if (*dst_len == 0)\n                *dst_len = (uint32_t)out_len;\n            else\n                *dst_len = 0xFFFFFFFF;\n            return false;\n        }\n        *dst_len = (uint32_t)out_len;\n        return true;\n    }\n    \n    /* Added by dotGears/TrungB\n     * This function will sign your content with given private key by RSA PKCS v15, and digest with SHA256.\n     */\n    unsigned char * RS256SignKey( unsigned char * signing_content, unsigned char * private_key )\n    {\n        int ret = 1;\n        mbedtls_pk_context pk;\n        mbedtls_entropy_context entropy;\n        mbedtls_ctr_drbg_context ctr_drbg;\n        \n        mbedtls_pk_init( &pk );\n        mbedtls_entropy_init( &entropy );\n        mbedtls_ctr_drbg_init( &ctr_drbg );\n\n        unsigned char hash[32];\n        unsigned char buf[MBEDTLS_MPI_MAX_SIZE]; // As [1024]\n        \n        size_t  olen = 0, \n                dlen = 344+1, \n                buflen = 256;\n        unsigned char dst[344+1]; \n\n        const char * pers = \"rsa_sign_pss\";\n        size_t pkey_len = strlen((char*)private_key)+1;\n        /* \n         * Key Sign need a Random Generator Function, so here's one : \n         */\n        if(( ret = mbedtls_ctr_drbg_seed( &ctr_drbg,  mbedtls_entropy_func,  &entropy, (const unsigned char *) pers, strlen( pers ))) != 0 )\n        {\n             printf( \"\\ncrypt -- error: mbedtls_ctr_drbg_seed returned %d\", ret ); \n             goto exit;\n        }\n        /* \n         * Parse private key, wonder why pkey_len had to +1 ? \n         */\n        if(( ret = mbedtls_pk_parse_key( &pk, private_key, pkey_len, NULL, NULL)) != 0)\n        {\n            printf( \"  ! mbedtls_pk_parse_public_keyfile returned %d\", ret );      \n            goto exit;\n        }\n        /* \n         * Check for valid RSA key. \n         */\n        if( !mbedtls_pk_can_do( &pk, MBEDTLS_PK_RSA )) \n        {\n            printf( \"\\ncrypt -- error: Key is not an RSA key: %s\\n\", private_key); \n            goto exit;\n        }\n        /* \n         * Important: MBEDTLS_RSA_PKCS_V21 won't work for Google OAuth v2, but V15. \n         */\n        mbedtls_rsa_set_padding( mbedtls_pk_rsa(pk), MBEDTLS_RSA_PKCS_V15, MBEDTLS_MD_SHA256 );\n        /*\n         * Compute the SHA-256 hash of the input file.\n         */\n        if(( ret = mbedtls_md(mbedtls_md_info_from_type(MBEDTLS_MD_SHA256), signing_content, strlen((char*)signing_content), hash)) != 0 )\n        {\n            printf( \"\\ncrypt -- mbedtls_md_info_from_type\\n\" );                    \n            goto exit;\n        }\n        /*\n         * then calculate the RSA signature of the hash.\n         */\n        if(( ret = mbedtls_pk_sign(&pk, MBEDTLS_MD_SHA256, hash, 0, buf, &olen, mbedtls_ctr_drbg_random, &ctr_drbg)) != 0 )\n        {\n            printf( \"\\ncrypt -- error: mbedtls_pk_sign returned %d\\n\", ret );      \n            goto exit;\n        }\n        /* \n         * encode given signature > base64\n         */\n        mbedtls_base64_encode(dst, dlen, &olen, buf, buflen);\n\n    exit:\n        /*\n         * free resources.\n         */\n        mbedtls_ctr_drbg_free( &ctr_drbg );\n        mbedtls_entropy_free( &entropy );\n        mbedtls_pk_free(&pk);\n        \n        return dst;\n    }\n}\n\n\nextern \"C\" {\n    DM_DLLEXPORT int EncryptXTeaCTR(uint8_t* data, uint32_t datalen, const uint8_t* key, uint32_t keylen)\n    {\n        return dmCrypt::Encrypt(dmCrypt::ALGORITHM_XTEA, data, datalen, key, keylen);\n    }\n\n    DM_DLLEXPORT int DecryptXTeaCTR(uint8_t* data, uint32_t datalen, const uint8_t* key, uint32_t keylen)\n    {\n        return dmCrypt::Decrypt(dmCrypt::ALGORITHM_XTEA, data, datalen, key, keylen);\n    }\n\n}\n", "meta": {"hexsha": "0e2e21a476ed833b3c0d8f1b673dfcb9c2e2885d", "size": 11205, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "engine/dlib/src/dlib/crypt.cpp", "max_stars_repo_name": "dotgears/defold", "max_stars_repo_head_hexsha": "440d28c5489b877ab8a1280b9de9673b7ad69405", "max_stars_repo_licenses": ["ECL-2.0", "Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-07-12T20:22:37.000Z", "max_stars_repo_stars_event_max_datetime": "2020-07-12T20:22:37.000Z", "max_issues_repo_path": "engine/dlib/src/dlib/crypt.cpp", "max_issues_repo_name": "dotgears/defold", "max_issues_repo_head_hexsha": "440d28c5489b877ab8a1280b9de9673b7ad69405", "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": "engine/dlib/src/dlib/crypt.cpp", "max_forks_repo_name": "dotgears/defold", "max_forks_repo_head_hexsha": "440d28c5489b877ab8a1280b9de9673b7ad69405", "max_forks_repo_licenses": ["ECL-2.0", "Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-07-06T08:54:02.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-06T08:54:02.000Z", "avg_line_length": 34.2660550459, "max_line_length": 144, "alphanum_fraction": 0.5855421687, "num_tokens": 3044, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7905303186696747, "lm_q2_score": 0.4035668537353746, "lm_q1q2_score": 0.3190318334879437}}
{"text": "/**\n * @file DynamicsOptimizer.hpp\n * @author Brahayam Ponton (brahayam.ponton@tuebingen.mpg.de)\n * @license License BSD-3-Clause\n * @copyright Copyright (c) 2019, New York University and Max Planck Gesellschaft.\n * @date 2019-10-08\n */\n\n#pragma once\n\n#include <string>\n#include <vector>\n#include <iostream>\n#include <Eigen/Eigen>\n\n#include <solver/interface/Solver.hpp>\n#include <momentumopt/utilities/Clock.hpp>\n#include <momentumopt/setting/PlannerSetting.hpp>\n#include <momentumopt/kinopt/KinematicsState.hpp>\n#include <momentumopt/cntopt/ContactPlanInterface.hpp>\n\nnamespace momentumopt {\n\n  /**\n   * Helper class to define a linear approximation of a friction cone.\n   */\n  struct FrictionCone\n  {\n    typedef Eigen::Matrix< double, 4, 3> ConeMat;\n    void getCone(double fcoeff, FrictionCone::ConeMat& cone_mat)\n    {\n      if (fcoeff <= 0.001) { fcoeff = 0.001; }\n      Eigen::Vector3d fconevec = Eigen::Vector3d(0.5*sqrt(2.0), 0.5*sqrt(2.0), -fcoeff); fconevec.normalize();\n      Eigen::Matrix3d fconemat = Eigen::Matrix3d::Identity();\n      double angle = 2*M_PI/4;\n      fconemat(0,0) = cos(angle);    fconemat(0,1) = -sin(angle);\n      fconemat(1,0) = sin(angle);    fconemat(1,1) =  cos(angle);\n      for (int i=0; i<4; i++) {\n        cone_mat.row(i) = fconevec;\n        fconevec = fconemat * fconevec;\n      }\n    }\n  };\n\n  /*! main class of the dynamics optimization problem  */\n  class DynamicsOptimizer\n  {\n    public:\n      EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n\n    public:\n      /*! default class constructor and destructor */\n\t  DynamicsOptimizer(){}\n      ~DynamicsOptimizer(){}\n\n      /**\n       * function to initialize and configure the optimization\n       * @param[in]  PlannerSetting               setting of planner configuration variables\n       */\n      void initialize(PlannerSetting& planner_setting);\n\n      /**\n       * function to parse equations and objective into optimization problem and attempt to find a solution\n       * @param[in]  ini_state                    initial state of the robot\n       * @param[in]  contact_plan                 container of contact sequence to be used for dynamics planning\n       * @param[in]  kin_sequence                 kinematics sequence to be used as momentum tracking reference (can be zeros).\n       * @param[in]  update_tracking_objective    changes weights from regulation to tracking of momentum in ref_sequence\n       * @return     ExitCode                     flag that indicates the optimization result (for example: optimal, infeasible)\n       */\n      solver::ExitCode optimize(const DynamicsState& ini_state, ContactPlanInterface* contact_plan,\n                                const KinematicsSequence& kin_sequence, bool update_tracking_objective = false);\n\n      /**\n       * this function gives access to the optimized motion plan\n       * @return     DynamicsSequence             reference to dynamics sequence, which is a collection of dynamic states,\n       *                                          each of which contains information about all variables, all end-effectors\n       *                                          of the motion plan for one time step\n       */\n      DynamicsSequence& dynamicsSequence() { return dyn_sequence_; }\n      const DynamicsSequence& dynamicsSequence() const { return dyn_sequence_; }\n\n      /*! function to have access to time required to solve the optimization problem */\n      const double& solveTime() const { return solve_time_; }\n\n    private:\n      /*! Getter and setter methods for getting the planner variables  */\n      inline PlannerSetting& getSetting() { return *planner_setting_; }\n      inline const PlannerSetting& getSetting() const { return *planner_setting_; }\n\n      /*! helper functions for the optimization problem */\n      const ContactType& contactType(int time_id, int eff_id) const;\n      Eigen::Matrix3d contactRotation(int time_id, int eff_id) const;\n      double contactLocation(int time_id, int eff_id, int axis_id) const;\n\n      /**\n       * function to initialize optimization variables: type [continuous or binary],\n       * guess value [if any], upper and lower bounds for the variable\n       */\n      void initializeOptimizationVariables();\n\n      /**\n       * function to add each variable to the Model and assign a unique identifier\n       * to it, to be used by the optimizer to construct the problem\n       * @param[in]  opt_var                      helper optimization variable for model predictive control\n       * @param[in]  model                        instance of solver interface to collect constraints, objective and solve problem\n       * @param[in]  vars                         vector of optimization variables\n       */\n      void addVariableToModel(const solver::OptimizationVariable& opt_var, solver::Model& model, std::vector<solver::Var>& vars);\n\n      /**\n       * functions to update tracking objective for momentum from penalty to tracking\n       * and attempt to find a solution to the optimization problem\n       * @param[in]  ref_sequence                 dynamics sequence to be used as momentum tracking reference (can be zeros).\n       * @param[in]  is_first_time                flag to indicate if this is the first time the solution is being constructed\n       */\n      void internalOptimize(const KinematicsSequence& kin_sequence, bool is_first_time = false);\n      void updateTrackingObjective();\n\n      /**\n       * functions that transfers optimal solution from model to helper class OptimizationVariable,\n       * from helper class OptimizationVariable to dynamics sequence to be accessed by the user, and\n       * from dynamics sequence to a file.\n       * @param[in]  opt_var                      helper optimization variable for model predictive control\n       * @param[in]  ref_sequence                 dynamics sequence to be used as momentum tracking reference (can be zeros).\n       */\n      void saveSolution(solver::OptimizationVariable& opt_var);\n      void storeSolution();\n      void saveToFile(const KinematicsSequence& kin_sequence);\n\n    private:\n      /*! Variables required for optimization */\n      PlannerSetting* planner_setting_;\n\n      /**\n       * class that stores all information about the problem, interfaces between high level definition\n       * of the problem and its corresponding mathematical construction to solve it with a solver instance\n       */\n      solver::Model model_;\n\n      /*! helper variables to construct linear and quadratic expressions */\n      solver::LinExpr lin_cons_;\n      solver::DCPQuadExpr quad_objective_, quad_cons_;\n\n      /*! exit code of the optimization problem */\n      solver::ExitCode exitcode_;\n\n      /**\n       * c++ vector containing all problem variables defined by the user. Does not include extra\n       * variables required to write the problem in standard conic form.\n       */\n      std::vector<solver::Var> vars_;\n\n      /**\n       * initial configuration of the robot, including center of mass position, linear and angular momenta,\n       * end-effectors configurations: activation, position, orientation\n       */\n      DynamicsState ini_state_;\n\n      /*! simple helper class to build a linear approximation of a friction cone */\n      FrictionCone friction_cone_;\n      FrictionCone::ConeMat cone_matrix_;\n\n      /**\n       * dynamics sequence of dynamic states. This is the main interface between the user\n       * and the planner. The user can find in this variable all the optimization results\n       */\n      DynamicsSequence dyn_sequence_;\n\n      /**\n       * helper class to store information about the contact plan, such as surfaces,\n       * position and orientation of a sequence of contacts\n       */\n      ContactPlanInterface* contact_plan_;\n\n      /*! clock for timing purposes */\n      Clock timer_;\n\n      /*! type for optimization variable: continuous 'C' or binary 'B' and type of heuristic */\n      char variable_type_;\n\n      /*! helper boolean variables for the optimization problem */\n      bool has_converged_;\n\n      /*! helper integer variables for the optimization problem */\n      int size_, num_vars_;\n\n      /*! helper double variables for the optimization problem */\n      double solve_time_, convergence_err_, last_convergence_err_;\n\n      /*! helper vector variables for the optimization problem */\n      Eigen::Vector3d com_pos_goal_, weight_desired_com_tracking_;\n\n      /*! helper optimization variables for the optimization problem */\n      solver::OptimizationVariable dt_, com_, lmom_, amom_, lmomd_, amomd_;\n      std::array<solver::OptimizationVariable, Problem::n_endeffs_> frc_world_, trq_local_, cop_local_, ub_var_, lb_var_;\n\n      /*! helper matrices and vectors for the optimization problem */\n      solver::OptimizationVariable::OptVector solution_;\n      solver::OptimizationVariable::OptMatrix mat_lb_, mat_ub_, mat_guess_, com_guess_, lmom_guess_, amom_guess_;\n  };\n\n}\n", "meta": {"hexsha": "3bb791d858cac02b402d9578d3da0a58a0ee41ea", "size": 8892, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "momentumopt/include/momentumopt/dynopt/DynamicsOptimizer.hpp", "max_stars_repo_name": "machines-in-motion/kino-dynamic-opt", "max_stars_repo_head_hexsha": "ba9188eea6b80b102b1d0880470bedc0faa5e243", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 26.0, "max_stars_repo_stars_event_min_datetime": "2019-11-18T17:39:43.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-18T00:38:22.000Z", "max_issues_repo_path": "momentumopt/include/momentumopt/dynopt/DynamicsOptimizer.hpp", "max_issues_repo_name": "machines-in-motion/kino_dynamic_opt", "max_issues_repo_head_hexsha": "ba9188eea6b80b102b1d0880470bedc0faa5e243", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 25.0, "max_issues_repo_issues_event_min_datetime": "2019-11-11T19:54:51.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-07T13:41:47.000Z", "max_forks_repo_path": "momentumopt/include/momentumopt/dynopt/DynamicsOptimizer.hpp", "max_forks_repo_name": "machines-in-motion/kino-dynamic-opt", "max_forks_repo_head_hexsha": "ba9188eea6b80b102b1d0880470bedc0faa5e243", "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": 43.802955665, "max_line_length": 130, "alphanum_fraction": 0.6707152497, "num_tokens": 1873, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6584175005616829, "lm_q2_score": 0.48438008427698437, "lm_q1q2_score": 0.31892432441150936}}
{"text": "/*********************************************************************************\n *  OKVIS - Open Keyframe-based Visual-Inertial SLAM\n *  Copyright (c) 2015, Autonomous Systems Lab / ETH Zurich\n *\n *  Redistribution and use in source and binary forms, with or without\n *  modification, are permitted provided that the following conditions are met:\n * \n *   * Redistributions of source code must retain the above copyright notice,\n *     this list of conditions and the following disclaimer.\n *   * Redistributions in binary form must reproduce the above copyright notice,\n *     this list of conditions and the following disclaimer in the documentation\n *     and/or other materials provided with the distribution.\n *   * Neither the name of Autonomous Systems Lab / ETH Zurich nor the names of\n *     its contributors may be used to endorse or promote products derived from\n *     this software without specific prior written permission.\n *\n *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n *  AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n *  IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n *  ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\n *  LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n *  CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n *  SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n *  INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n *  CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n *  ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n *  POSSIBILITY OF SUCH DAMAGE.\n *\n *  Created on: Jan 7, 2014\n *      Author: Stefan Leutenegger (s.leutenegger@imperial.ac.uk)\n *********************************************************************************/\n\n/**\n * @file ode.hpp\n * @brief File for ODE integration functionality.\n * @author Stefan Leutenegger\n */\n\n#ifndef INCLUDE_OKVIS_CERES_ODE_ODE_HPP_\n#define INCLUDE_OKVIS_CERES_ODE_ODE_HPP_\n\n#include <Eigen/Core>\n#include <okvis/kinematics/Transformation.hpp>\n#include <okvis/kinematics/operators.hpp>\n#include <okvis/FrameTypedefs.hpp>\n#include <okvis/Measurements.hpp>\n#include <okvis/Variables.hpp>\n#include <okvis/assert_macros.hpp>\n\n/// \\brief okvis Main namespace of this package.\nnamespace okvis {\n/// \\brief ceres Namespace for ceres-related functionality implemented in okvis.\nnamespace ceres {\n/// \\brief ode Namespace for functionality related to ODE integration implemented in okvis.\nnamespace ode {\n\n// to make things a bit faster than using angle-axis conversion:\ninline double sinc(double x) {\n  if (fabs(x) > 1e-6) {\n   return sin(x) / x;\n   } else{\n    static const double c_2 = 1.0 / 6.0;\n    static const double c_4 = 1.0 / 120.0;\n    static const double c_6 = 1.0 / 5040.0;\n    const double x_2 = x * x;\n    const double x_4 = x_2 * x_2;\n    const double x_6 = x_2 * x_2 * x_2;\n    return 1.0 - c_2 * x_2 + c_4 * x_4 - c_6 * x_6;\n  }\n}\n\n// world-centric velocities\ninline void evaluateContinuousTimeOde(const Eigen::Vector3d& gyr, const Eigen::Vector3d& acc, double g,\n                                          const Eigen::Vector3d& p_WS_W, const Eigen::Quaterniond& q_WS,\n                                          const okvis::SpeedAndBias& sb, Eigen::Vector3d& p_WS_W_dot,\n                                          Eigen::Vector4d& q_WS_dot, okvis::SpeedAndBias& sb_dot,\n                                          Eigen::Matrix<double, 15, 15>* F_c_ptr = 0){\n  // \"true\" rates and accelerations\n  const Eigen::Vector3d omega_S = gyr - sb.segment<3>(3);\n  const Eigen::Vector3d acc_S = acc - sb.tail<3>();\n\n  // nonlinear states\n  // start with the pose\n  p_WS_W_dot = sb.head<3>();\n\n  // now the quaternion\n  Eigen::Vector4d dq;\n  q_WS_dot.head<3>() = 0.5 * omega_S;\n  q_WS_dot[3] = 0.0;\n  Eigen::Matrix3d C_WS = q_WS.toRotationMatrix();\n\n  // the rest is straightforward\n  // consider Earth's radius. Model the Earth as a sphere, since we neither\n  // know the position nor yaw (except if coupled with GPS and magnetometer).\n  Eigen::Vector3d G = -p_WS_W - Eigen::Vector3d(0, 0, 6371009); // vector to Earth center\n  sb_dot.head<3>() = (C_WS * acc_S + g * G.normalized()); // s\n  // biases\n  sb_dot.tail<6>().setZero();\n\n  // linearized system:\n  if (F_c_ptr) {\n    F_c_ptr->setZero();\n    F_c_ptr->block<3, 3>(0, 6) += Eigen::Matrix3d::Identity();\n    F_c_ptr->block<3, 3>(3, 9) -= C_WS;\n    F_c_ptr->block<3, 3>(6, 3) -= okvis::kinematics::crossMx(C_WS * acc_S);\n    F_c_ptr->block<3, 3>(6, 12) -= C_WS;\n  }\n}\n\n\n/*/ robo-centric velocities\n__inline__ void evaluateContinuousTimeOde(\n    const Eigen::Vector3d& gyr, const Eigen::Vector3d& acc, double g,\n    const Eigen::Vector3d& p_WS_W, const Eigen::Quaterniond& q_WS,\n    const okvis::SpeedAndBias& sb, Eigen::Vector3d& p_WS_W_dot,\n    Eigen::Vector4d& q_WS_dot, okvis::SpeedAndBias& sb_dot,\n    Eigen::Matrix<double, 15, 15>* F_c_ptr = 0) {\n\n  // \"true\" rates and accelerations\n  const Eigen::Vector3d omega_S = gyr - sb.segment<3>(3);\n  const Eigen::Vector3d acc_S = acc - sb.tail<3>();\n\n  // rotation matrix\n  Eigen::Matrix3d C_WS = q_WS.toRotationMatrix();\n  Eigen::Matrix3d C_SW = C_WS.transpose();\n\n  // nonlinear states\n  // start with the pose\n  p_WS_W_dot = C_WS*sb.head<3>();\n\n  // now the quaternion\n  Eigen::Vector4d dq;\n  q_WS_dot.head<3>() = 0.5 * omega_S;\n  q_WS_dot[3] = 0.0;\n\n  // the rest is straightforward\n  // consider Earth's radius. Model the Earth as a sphere, since we neither\n  // know the position nor yaw (except if coupled with GPS and magnetometer).\n  Eigen::Vector3d G = -p_WS_W - Eigen::Vector3d(0, 0, 6371009);  // vector to Earth center\n  Eigen::Vector3d g_W = g * G.normalized();\n  sb_dot.head<3>() = acc_S - okvis::kinematics::crossMx(omega_S)*sb.head<3>() + C_SW * g_W;\n  // biases\n  sb_dot.tail<6>().setZero();\n  //sb_dot.tail<3>()=-sb.tail<3>()/360.0;\n\n  // linearized system:\n  if (F_c_ptr) {\n    F_c_ptr->setZero();\n    F_c_ptr->block<3, 3>(0, 3)  += -okvis::kinematics::crossMx(C_WS * sb.head<3>());\n    F_c_ptr->block<3, 3>(0, 6)  += C_WS;\n    F_c_ptr->block<3, 3>(3, 9)  += -C_WS;\n    F_c_ptr->block<3, 3>(6, 3)  += C_SW * okvis::kinematics::crossMx(g_W);\n    F_c_ptr->block<3, 3>(6, 6)  += -okvis::kinematics::crossMx(omega_S);\n    F_c_ptr->block<3, 3>(6, 9)  += -okvis::kinematics::crossMx(sb.head<3>());\n    F_c_ptr->block<3, 3>(6, 12) += -Eigen::Matrix3d::Identity();\n    //F_c_ptr->block<3, 3>(12, 12) = - 1.0/360.0*Eigen::Matrix3d::Identity();\n  }\n}*/\n\ninline void integrateOneStep_RungeKutta(\n    const Eigen::Vector3d& gyr_0, const Eigen::Vector3d& acc_0,\n    const Eigen::Vector3d& gyr_1, const Eigen::Vector3d& acc_1, double g,\n    double sigma_g_c, double sigma_a_c, double sigma_gw_c, double sigma_aw_c,\n    double dt, Eigen::Vector3d& p_WS_W, Eigen::Quaterniond& q_WS,\n    okvis::SpeedAndBias& sb, Eigen::Matrix<double, 15, 15>* P_ptr = 0,\n    Eigen::Matrix<double, 15, 15>* F_tot_ptr = 0) {\n\n  Eigen::Vector3d k1_p_WS_W_dot;\n  Eigen::Vector4d k1_q_WS_dot;\n  okvis::SpeedAndBias k1_sb_dot;\n  Eigen::Matrix<double, 15, 15> k1_F_c;\n  evaluateContinuousTimeOde(gyr_0, acc_0, g, p_WS_W, q_WS, sb, k1_p_WS_W_dot,\n                            k1_q_WS_dot, k1_sb_dot, &k1_F_c);\n\n  Eigen::Vector3d p_WS_W1 = p_WS_W;\n  Eigen::Quaterniond q_WS1 = q_WS;\n  okvis::SpeedAndBias sb1 = sb;\n  // state propagation:\n  p_WS_W1 += k1_p_WS_W_dot * 0.5 * dt;\n  Eigen::Quaterniond dq;\n  double theta_half = k1_q_WS_dot.head<3>().norm() * 0.5 * dt;\n  double sinc_theta_half = sinc(theta_half);\n  double cos_theta_half = cos(theta_half);\n  dq.vec() = sinc_theta_half * k1_q_WS_dot.head<3>() * 0.5 * dt;\n  dq.w() = cos_theta_half;\n  q_WS1 = q_WS * dq;\n  sb1 += k1_sb_dot * 0.5 * dt;\n\n  Eigen::Vector3d k2_p_WS_W_dot;\n  Eigen::Vector4d k2_q_WS_dot;\n  okvis::SpeedAndBias k2_sb_dot;\n  Eigen::Matrix<double, 15, 15> k2_F_c;\n  evaluateContinuousTimeOde(0.5 * (gyr_0 + gyr_1), 0.5 * (acc_0 + acc_1), g,\n                            p_WS_W1, q_WS1, sb1, k2_p_WS_W_dot, k2_q_WS_dot,\n                            k2_sb_dot, &k2_F_c);\n\n  Eigen::Vector3d p_WS_W2 = p_WS_W;\n  Eigen::Quaterniond q_WS2 = q_WS;\n  okvis::SpeedAndBias sb2 = sb;\n  // state propagation:\n  p_WS_W2 += k2_p_WS_W_dot * dt;\n  theta_half = k2_q_WS_dot.head<3>().norm() * dt;\n  sinc_theta_half = sinc(theta_half);\n  cos_theta_half = cos(theta_half);\n  dq.vec() = sinc_theta_half * k2_q_WS_dot.head<3>() * dt;\n  dq.w() = cos_theta_half;\n  //std::cout<<dq.transpose()<<std::endl;\n  q_WS2 = q_WS2 * dq;\n  sb2 += k1_sb_dot * dt;\n\n  Eigen::Vector3d k3_p_WS_W_dot;\n  Eigen::Vector4d k3_q_WS_dot;\n  okvis::SpeedAndBias k3_sb_dot;\n  Eigen::Matrix<double, 15, 15> k3_F_c;\n  evaluateContinuousTimeOde(0.5 * (gyr_0 + gyr_1), 0.5 * (acc_0 + acc_1), g,\n                            p_WS_W2, q_WS2, sb2, k3_p_WS_W_dot, k3_q_WS_dot,\n                            k3_sb_dot, &k3_F_c);\n\n  Eigen::Vector3d p_WS_W3 = p_WS_W;\n  Eigen::Quaterniond q_WS3 = q_WS;\n  okvis::SpeedAndBias sb3 = sb;\n  // state propagation:\n  p_WS_W3 += k3_p_WS_W_dot * dt;\n  theta_half = k3_q_WS_dot.head<3>().norm() * dt;\n  sinc_theta_half = sinc(theta_half);\n  cos_theta_half = cos(theta_half);\n  dq.vec() = sinc_theta_half * k3_q_WS_dot.head<3>() * dt;\n  dq.w() = cos_theta_half;\n  //std::cout<<dq.transpose()<<std::endl;\n  q_WS3 = q_WS3 * dq;\n  sb3 += k3_sb_dot * dt;\n\n  Eigen::Vector3d k4_p_WS_W_dot;\n  Eigen::Vector4d k4_q_WS_dot;\n  okvis::SpeedAndBias k4_sb_dot;\n  Eigen::Matrix<double, 15, 15> k4_F_c;\n  evaluateContinuousTimeOde(gyr_1, acc_1, g, p_WS_W3, q_WS3, sb3, k4_p_WS_W_dot,\n                            k4_q_WS_dot, k4_sb_dot, &k4_F_c);\n\n  // now assemble\n  p_WS_W +=\n      (k1_p_WS_W_dot + 2 * (k2_p_WS_W_dot + k3_p_WS_W_dot) + k4_p_WS_W_dot) * dt\n          / 6.0;\n  Eigen::Vector3d theta_half_vec = (k1_q_WS_dot.head<3>()\n      + 2 * (k2_q_WS_dot.head<3>() + k3_q_WS_dot.head<3>())\n      + k4_q_WS_dot.head<3>()) * dt / 6.0;\n  theta_half = theta_half_vec.norm();\n  sinc_theta_half = sinc(theta_half);\n  cos_theta_half = cos(theta_half);\n  dq.vec() = sinc_theta_half * theta_half_vec;\n  dq.w() = cos_theta_half;\n  q_WS = q_WS * dq;\n  sb += (k1_sb_dot + 2 * (k2_sb_dot + k3_sb_dot) + k4_sb_dot) * dt / 6.0;\n\n  q_WS.normalize(); // do not accumulate errors!\n\n  if (F_tot_ptr) {\n    // compute state transition matrix\n    Eigen::Matrix<double, 15, 15>& F_tot = *F_tot_ptr;\n    const Eigen::Matrix<double, 15, 15>& J1 = k1_F_c;\n    const Eigen::Matrix<double, 15, 15> J2=k2_F_c*(Eigen::Matrix<double, 15, 15>::Identity()+0.5*dt*J1);\n    const Eigen::Matrix<double, 15, 15> J3=k3_F_c*(Eigen::Matrix<double, 15, 15>::Identity()+0.5*dt*J2);\n    const Eigen::Matrix<double, 15, 15> J4=k4_F_c*(Eigen::Matrix<double, 15, 15>::Identity()+dt*J3);\n    Eigen::Matrix<double, 15, 15> F = Eigen::Matrix<double, 15, 15>::Identity()\n        + dt * (J1+2*(J2+J3)+J4) / 6.0;\n        //+ dt * J1;\n    //std::cout<<F<<std::endl;\n    F_tot = (F * F_tot).eval();\n\n    if (P_ptr) {\n      Eigen::Matrix<double, 15, 15>& cov = *P_ptr;\n      cov = F * (cov * F.transpose()).eval();\n\n      // add process noise\n      const double Q_g = sigma_g_c * sigma_g_c * dt;\n      const double Q_a = sigma_a_c * sigma_a_c * dt;\n      const double Q_gw = sigma_gw_c * sigma_gw_c * dt;\n      const double Q_aw = sigma_aw_c * sigma_aw_c * dt;\n      cov(3, 3) += Q_g;\n      cov(4, 4) += Q_g;\n      cov(5, 5) += Q_g;\n      cov(6, 6) += Q_a;\n      cov(7, 7) += Q_a;\n      cov(8, 8) += Q_a;\n      cov(9, 9) += Q_gw;\n      cov(10, 10) += Q_gw;\n      cov(11, 11) += Q_gw;\n      cov(12, 12) += Q_aw;\n      cov(13, 13) += Q_aw;\n      cov(14, 14) += Q_aw;\n\n      // force symmetric - TODO: is this really needed here?\n      // cov = 0.5 * cov + 0.5 * cov.transpose().eval();\n    }\n  }\n\n}\n\n}\n\n}  // namespace ceres\n}  // namespace okvis\n\n#endif /* INCLUDE_OKVIS_CERES_ODE_ODE_HPP_ */\n", "meta": {"hexsha": "0b352e3a020efae01772eb434c7f523b3917e456", "size": 11892, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "okvis_ceres/include/okvis/ceres/ode/ode.hpp", "max_stars_repo_name": "arielji/okvis", "max_stars_repo_head_hexsha": "14bb8ca659c1539ee39c8ebf7409c9dbeb7563d5", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-04-02T14:58:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-02T14:58:42.000Z", "max_issues_repo_path": "okvis_ceres/include/okvis/ceres/ode/ode.hpp", "max_issues_repo_name": "arielji/okvis", "max_issues_repo_head_hexsha": "14bb8ca659c1539ee39c8ebf7409c9dbeb7563d5", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "okvis_ceres/include/okvis/ceres/ode/ode.hpp", "max_forks_repo_name": "arielji/okvis", "max_forks_repo_head_hexsha": "14bb8ca659c1539ee39c8ebf7409c9dbeb7563d5", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2019-08-05T17:01:09.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-17T19:48:23.000Z", "avg_line_length": 38.9901639344, "max_line_length": 104, "alphanum_fraction": 0.6429532459, "num_tokens": 3851, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6477982315512488, "lm_q2_score": 0.49218813572079556, "lm_q1q2_score": 0.3188386039104374}}
{"text": "/**\n * @file\n * @license BSD 3-clause\n * @copyright Copyright (c) 2020, New York University and Max Planck\n * Gesellschaft\n *\n * @brief Implements the \"Walking Control Based on Step Timing Adaptation\" foot\n * trajectory QP. The pdf can be found in https://arxiv.org/abs/1704.01271, and\n * in the `doc/` folder in this repository.\n */\n\n#pragma once\n\n#include <eigen-quadprog/QuadProg.h>\n#include <Eigen/Eigen>\n#include <chrono>\n#include <iostream>\n#include <limits>\n#define RESET \"\\033[0m\"\n#define RED \"\\033[31m\"  /* Red */\n#define BLUE \"\\033[34m\" /* Blue */\n#define MAX_VAR 500\n#define EPSILON 1e-9\n\nnamespace reactive_planners\n{\n/**\n * @brief\n */\nclass DynamicallyConsistentEndEffectorTrajectory\n{\n    /*\n     * Private methods\n     */\npublic:\n    /** @brief Constructor. */\n    DynamicallyConsistentEndEffectorTrajectory();\n\n    /** @brief Destructor. */\n    ~DynamicallyConsistentEndEffectorTrajectory();\n\n    bool compute(const Eigen::Ref<const Eigen::Vector3d>& start_pose,\n                 const Eigen::Ref<const Eigen::Vector3d>& current_pose,\n                 const Eigen::Ref<const Eigen::Vector3d>& current_velocity,\n                 const Eigen::Ref<const Eigen::Vector3d>& target_pose,\n                 const double& start_time,\n                 const double& current_time,\n                 const double& end_time,\n                 const bool& is_left_leg_in_contact);\n\n    void update_robot_status(Eigen::Ref<Eigen::Vector3d> next_pose,\n                             Eigen::Ref<Eigen::Vector3d> next_velocity,\n                             Eigen::Ref<Eigen::Vector3d> next_acceleration);\n\n    /** @brief Get all the forces until landing foot. Returns the number of\n     * forces.*/\n    int get_forces(Eigen::Ref<Eigen::VectorXd> forces,\n                   Eigen::Ref<Eigen::Vector3d> next_pose,\n                   Eigen::Ref<Eigen::Vector3d> next_velocity,\n                   Eigen::Ref<Eigen::Vector3d> next_acceleration);\n\n    /** @brief Display the matrices of the Problem. */\n    void print_solver() const;\n\n    /** @brief Convert the inner data to a string format. */\n    std::string to_string() const;\n\n    /*\n     * Getters\n     */\n\n    /** @brief Get the height of the flying foot. */\n    double get_mid_air_height() const\n    {\n        return mid_air_height_;\n    }\n\n    /*\n     * Setters\n     */\n    /** @brief Set the height of the flying foot.\n     *\n     * @param mid_air_height\n     */\n    void set_planner_loop(double planner_loop)\n    {\n        planner_loop_ = planner_loop;\n        init_acceleration_velocity_terms();\n    }\n\n    /** @brief Set the height of the flying foot.\n     *\n     * @param mid_air_height\n     */\n    void set_mid_air_height(double mid_air_height)\n    {\n        mid_air_height_ = mid_air_height;\n    }\n\n    /**\n     * @brief return cost.\n     *\n     * @return double\n     */\n    double cost()\n    {\n        x_opt_.resize(nb_var_);\n        x_opt_ = qp_solver_.result();\n        return (0.5 * x_opt_.transpose() * Q_ * x_opt_ +\n                q_.transpose() * x_opt_)(0, 0);\n    }\n\n    /**\n     * @brief Return the slack values from the last solution.\n     **/\n    const Eigen::Vector3d& get_slack_variables() const\n    {\n        return slack_variables_;\n    }\n\n    double calculate_t_min(\n        const Eigen::Ref<const Eigen::Vector3d>& current_pose,\n        const Eigen::Ref<const Eigen::Vector3d>& current_velocity,\n        const bool& is_left_leg_in_contact);\n    /*\n     * Private methods\n     */\nprivate:\n    /** @brief resize QP variable at each step.\n     */\n    void resize_matrices()\n    {\n        Q_.resize(nb_var_, nb_var_);\n        Q_.setZero();\n        q_.resize(nb_var_);\n        q_.setZero();\n\n        A_eq_.resize(nb_eq_, nb_var_);\n        A_eq_.setZero();\n        B_eq_.resize(nb_eq_);\n        B_eq_.setZero();\n\n        A_ineq_.resize(nb_ineq_, nb_var_);\n        A_ineq_.setZero();\n        B_ineq_.resize(nb_ineq_);\n        B_ineq_.setZero();\n        qp_solver_.problem(nb_var_, nb_eq_, nb_ineq_);\n    }\n    /** @brief resize QP variable at each step.\n     */\n    void resize_matrices_t_min(int index)\n    {\n        Q_t_min_.resize(3 * index, 3 * index);\n        Q_t_min_ = Eigen::MatrixXd::Identity(3 * index, 3 * index);\n        q_t_min_.resize(3 * index);\n        q_t_min_.setZero();\n\n        A_eq_t_min_.resize(2, 3 * index);\n        A_eq_t_min_.setZero();\n        B_eq_t_min_.resize(2);\n        B_eq_t_min_.setZero();\n\n        A_ineq_t_min_.resize(2 * 3 * index, 3 * index);\n        A_ineq_t_min_.setZero();\n        B_ineq_t_min_.resize(2 * 3 * index);\n        B_ineq_t_min_.setZero();\n        qp_solver_t_min_.problem(3 * index, 2, 2 * 3 * index);\n    }\n\n    /** @brief initialie acceleration_terms and velocity_terms.\n     */\n    void init_acceleration_velocity_terms();\n\n    /*\n     * Constant problem parameters.\n     */\n\n    /** @brief Flying foot apex to be reach mid-air. */\n    double mid_air_height_;\n\n    /** @brief Number of force variables in the optimization problem on the\n     * one of the axes. */\n    int nb_local_sampling_time_;\n\n    /** @brief non_linear_terms.\n     */\n    Eigen::Vector3d h_c;\n\n    /*\n     * Variable problem parameters.\n     */\n\n    /** @brief affect of forces_x to the positions.\n     * There are two separate matrices for each leg.\n     */\n    Eigen::MatrixXd* position_terms_F_x_;\n\n    /** @brief affect of forces_y to the positions.\n     * There are two separate matrices for each leg.\n     */\n    Eigen::MatrixXd* position_terms_F_y_;\n\n    /** @brief affect of forces_z to the positions.\n     * There are two separate matrices for each leg.\n     */\n    Eigen::MatrixXd* position_terms_F_z_;\n\n    /** @brief Desired velocity. */\n    Eigen::Vector3d v_des_;\n\n    /** @brief Slack variable values corresponding to last solution. */\n    Eigen::Vector3d slack_variables_;\n\n    /** @brief affect of non_linear_terms in position. */\n    Eigen::MatrixXd* non_linear_terms;\n\n    /** @brief Initial position before the motion. */\n    Eigen::Vector3d start_pose_;\n\n    /** @brief Current position. */\n    Eigen::Vector3d current_pose_;\n\n    /** @brief Previous computed position from the QP. */\n    Eigen::Vector3d previous_solution_pose_;\n\n    /** @brief Current velocity. */\n    Eigen::Vector3d current_velocity_;\n\n    /** @brief Current acceleration. */\n    Eigen::Vector3d current_acceleration_;\n\n    /** @brief Target pose after the motion. */\n    Eigen::Vector3d target_pose_;\n\n    /** @brief Initial time. */\n    double start_time_;\n\n    /** @brief Current time. */\n    double current_time_;\n\n    /** @brief Last end time register when we computed the QP. */\n    double last_end_time_seen_;\n\n    /** @brief Control loop. */\n    double control_loop_;\n\n    /** @brief planner loop. */\n    double planner_loop_;\n\n    /*\n     * QP variables\n     */\n\n    /** @brief Number of variables in the optimization problem. */\n    int nb_var_;\n\n    /** @brief Number of equality constraints in the optimization problem. */\n    int nb_eq_;\n\n    /** @brief Number of inequality in the optimization problem. */\n    int nb_ineq_;\n\n    /** @brief Quadratic program solver.\n     *\n     * This is an eigen wrapper around the quad_prog fortran solver.\n     */\n    Eigen::QuadProgDense qp_solver_;\n\n    /** @brief Quadratic program solver.\n     *\n     * This is an eigen wrapper around the quad_prog fortran solver.\n     */\n    Eigen::QuadProgDense qp_solver_t_min_;\n\n    /** @brief Solution of the optimization problem.\n     * @see DynamicallyConsistentEndEffectorTrajectory */\n    Eigen::VectorXd x_opt_;\n\n    /** @brief Quadratic term of the quadratic cost.\n     * @see DynamicallyConsistentEndEffectorTrajectory */\n    Eigen::MatrixXd Q_;\n    /** @brief Quadratic term of the quadratic cost.\n     * @see DynamicallyConsistentEndEffectorTrajectory */\n    Eigen::MatrixXd Q_t_min_;\n\n    /** @brief inverse estimation of mass matrix.\n     * @see DynamicallyConsistentEndEffectorTrajectory */\n    Eigen::MatrixXd* M_inv_;\n\n    /** @brief Is the left foot in contact? otherwise the right foot is. */\n    bool is_left_leg_in_contact_;\n\n    /** @brief Quadratic term added to the quadratic cost in order regularize\n     * the system.\n     * @see DynamicallyConsistentEndEffectorTrajectory */\n    Eigen::MatrixXd Q_regul_;\n\n    /** @brief Cost weights for forces. */\n    double cost_;\n\n    /** @brief Cost weights for the epsilon_z_mid. */\n    double cost_epsilon_z_mid_;\n\n    /** @brief Cost weights for the epsilon_x. */\n    double cost_epsilon_x_;\n\n    /** @brief Cost weights for the epsilon_y. */\n    double cost_epsilon_y_;\n\n    /** @brief Cost weights for the epsilon_z. */\n    double cost_epsilon_z_;\n\n    /** @brief Cost weights for the epsilon_z. */\n    double cost_epsilon_vel_;\n\n    /** @brief Linear term of the quadratic cost.\n     * @see DynamicallyConsistentEndEffectorTrajectory */\n    Eigen::VectorXd q_;\n\n    /** @brief Linear equality matrix.\n     * @see DynamicallyConsistentEndEffectorTrajectory */\n    Eigen::MatrixXd A_eq_;\n\n    /** @brief Linear equality vector.\n     * @see DynamicallyConsistentEndEffectorTrajectory */\n    Eigen::VectorXd B_eq_;\n\n    /** @brief Linear inequality matrix.\n     * @see DynamicallyConsistentEndEffectorTrajectory */\n    Eigen::MatrixXd A_ineq_;\n\n    /** @brief Linear inequality vector.\n     * @see DynamicallyConsistentEndEffectorTrajectory */\n    Eigen::VectorXd B_ineq_;\n\n    /** @brief Linear term of the quadratic cost.\n     * @see DynamicallyConsistentEndEffectorTrajectory */\n    Eigen::VectorXd q_t_min_;\n\n    /** @brief Linear equality matrix.\n     * @see DynamicallyConsistentEndEffectorTrajectory */\n    Eigen::MatrixXd A_eq_t_min_;\n\n    /** @brief Linear equality vector.\n     * @see DynamicallyConsistentEndEffectorTrajectory */\n    Eigen::VectorXd B_eq_t_min_;\n\n    /** @brief Linear inequality matrix.\n     * @see DynamicallyConsistentEndEffectorTrajectory */\n    Eigen::MatrixXd A_ineq_t_min_;\n\n    /** @brief Linear inequality vector.\n     * @see DynamicallyConsistentEndEffectorTrajectory */\n    Eigen::VectorXd B_ineq_t_min_;\n};\n\n}  // namespace reactive_planners\n", "meta": {"hexsha": "9f91bd6541ead0cbb1909d2ea9ae7abcf4cbd27d", "size": 10025, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/reactive_planners/dynamically_consistent_end_effector_trajectory.hpp", "max_stars_repo_name": "Lhumd/reactive_planners-1", "max_stars_repo_head_hexsha": "5d8bd04da3d06fb2f968aa23a0c6713dcd773f44", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2021-09-13T10:25:50.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-27T21:55:25.000Z", "max_issues_repo_path": "include/reactive_planners/dynamically_consistent_end_effector_trajectory.hpp", "max_issues_repo_name": "Lhumd/reactive_planners-1", "max_issues_repo_head_hexsha": "5d8bd04da3d06fb2f968aa23a0c6713dcd773f44", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-11-28T04:02:31.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-18T16:33:43.000Z", "max_forks_repo_path": "include/reactive_planners/dynamically_consistent_end_effector_trajectory.hpp", "max_forks_repo_name": "Lhumd/reactive_planners-1", "max_forks_repo_head_hexsha": "5d8bd04da3d06fb2f968aa23a0c6713dcd773f44", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-09-15T09:07:01.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-16T21:28:10.000Z", "avg_line_length": 28.0027932961, "max_line_length": 79, "alphanum_fraction": 0.64159601, "num_tokens": 2434, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6477982179521103, "lm_q2_score": 0.4921881357207956, "lm_q1q2_score": 0.31883859721710284}}
{"text": "//-----------------------------------------------------------------------------\n// Created on: 16 February 2019\n//-----------------------------------------------------------------------------\n// Copyright (c) 2019-present, 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_MeshOBB.h>\n\n// asiAlgo includes\n#include <asiAlgo_Utils.h>\n\n// OCCT includes\n#include <BRepBuilderAPI_Transform.hxx>\n#include <BRepPrimAPI_MakeBox.hxx>\n\n// Eigen includes\n#pragma warning(push, 0)\n#include <Eigen/Dense>\n#pragma warning(pop)\n\n// STL includes\n#include <vector>\n\n#undef COUT_DEBUG\n#if defined COUT_DEBUG\n  #pragma message(\"===== warning: COUT_DEBUG is enabled\")\n#endif\n\n#undef DRAW_DEBUG\n#if defined DRAW_DEBUG\n  #pragma message(\"===== warning: DRAW_DEBUG is enabled\")\n#endif\n\n//-----------------------------------------------------------------------------\n\nstatic 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\nasiAlgo_MeshOBB::asiAlgo_MeshOBB(const Handle(Poly_Triangulation)& mesh,\n                                 ActAPI_ProgressEntry              progress,\n                                 ActAPI_PlotterEntry               plotter)\n//\n: ActAPI_IAlgorithm (progress, plotter),\n  m_input           (mesh)\n{}\n\n//-----------------------------------------------------------------------------\n\nbool asiAlgo_MeshOBB::Perform()\n{\n  // Check if triangulation exists.\n  if ( m_input.IsNull() || !m_input->NbNodes() )\n  {\n    this->GetProgress().SendLogMessage( LogErr(Normal) << \"Cannot build OBB for empty triangulation.\" );\n    return false;\n  }\n\n  // Calculate principal axes.\n  gp_Ax1 ax_X, ax_Y, ax_Z;\n  gp_XYZ mu;\n  //\n  this->calculateByCovariance(ax_X, ax_Y, ax_Z, mu);\n\n  { // Imperative drawing\n    // NOTE: that looks a bit funny, but in order to visualize the just calculated\n    //       principal axes of OBB we use AABB as it gives us hint for sizing.\n\n    double xMin, yMin, zMin, xMax, yMax, zMax;\n    asiAlgo_Utils::Bounds(m_input, xMin, yMin, zMin, xMax, yMax, zMax);\n    //\n    gp_Pnt bndMin(xMin, yMin, zMin), bndMax(xMax, yMax, zMax);\n    const double magnitude = bndMax.Distance(bndMin)*0.1;\n\n    this->GetPlotter().DRAW_VECTOR_AT(mu, ax_X.Direction().XYZ()*magnitude, Color_Red);\n    this->GetPlotter().DRAW_VECTOR_AT(mu, ax_Y.Direction().XYZ()*magnitude, Color_Green);\n    this->GetPlotter().DRAW_VECTOR_AT(mu, ax_Z.Direction().XYZ()*magnitude, Color_Blue);\n  }\n\n  /* =============================================\n   *  Calculate extremities on the principal axes\n   * ============================================= */\n\n  double ax_X_param_max = -RealLast(),\n         ax_Y_param_max = -RealLast(),\n         ax_Z_param_max = -RealLast();\n  double ax_X_param_min =  RealLast(),\n         ax_Y_param_min =  RealLast(),\n         ax_Z_param_min =  RealLast();\n  //\n  const TColgp_Array1OfPnt& nodes = m_input->Nodes();\n  //\n  for ( int i = nodes.Lower(); i <= nodes.Upper(); ++i )\n  {\n    const gp_Pnt& P = nodes(i);\n    //\n    const double node_X = P.X();\n    const double node_Y = P.Y();\n    const double node_Z = P.Z();\n    //\n    gp_XYZ p(node_X, node_Y, node_Z);\n    gp_Vec p_local = p - mu;\n\n    const double ax_X_param = p_local.Dot( ax_X.Direction() );\n    const double ax_Y_param = p_local.Dot( ax_Y.Direction() );\n    const double ax_Z_param = p_local.Dot( ax_Z.Direction() );\n\n    if ( ax_X_param > ax_X_param_max )\n      ax_X_param_max = ax_X_param;\n    //\n    if ( ax_Y_param > ax_Y_param_max )\n      ax_Y_param_max = ax_Y_param;\n    //\n    if ( ax_Z_param > ax_Z_param_max )\n      ax_Z_param_max = ax_Z_param;\n    //\n    if ( ax_X_param < ax_X_param_min )\n      ax_X_param_min = ax_X_param;\n    //\n    if ( ax_Y_param < ax_Y_param_min )\n      ax_Y_param_min = ax_Y_param;\n    //\n    if ( ax_Z_param < ax_Z_param_min )\n      ax_Z_param_min = ax_Z_param;\n  }\n\n#if defined DRAW_DEBUG\n  { // Imperative drawing.\n    const gp_XYZ ax_X_max = mu + ax_X.Direction().XYZ()*ax_X_param_max;\n    const gp_XYZ ax_Y_max = mu + ax_Y.Direction().XYZ()*ax_Y_param_max;\n    const gp_XYZ ax_Z_max = mu + ax_Z.Direction().XYZ()*ax_Z_param_max;\n    //\n    const gp_XYZ ax_X_min = mu + ax_X.Direction().XYZ()*ax_X_param_min;\n    const gp_XYZ ax_Y_min = mu + ax_Y.Direction().XYZ()*ax_Y_param_min;\n    const gp_XYZ ax_Z_min = mu + ax_Z.Direction().XYZ()*ax_Z_param_min;\n\n    this->Plotter().DRAW_POINT(ax_X_max, Color_Red);\n    this->Plotter().DRAW_POINT(ax_Y_max, Color_Green);\n    this->Plotter().DRAW_POINT(ax_Z_max, Color_Blue);\n    //\n    this->Plotter().DRAW_POINT(ax_X_min, Color_Magenta);\n    this->Plotter().DRAW_POINT(ax_Y_min, Color_Yellow);\n    this->Plotter().DRAW_POINT(ax_Z_min, Color_Violet);\n  }\n#endif\n\n  /* =====================\n   *  STAGE 4: Set result\n   * ===================== */\n\n  // Set placement and corner positions to the result.\n  gp_Ax3 ax3_placement( mu, ax_Z.Direction(), ax_X.Direction() );\n  gp_Pnt corner_min(ax_X_param_min, ax_Y_param_min, ax_Z_param_min);\n  gp_Pnt corner_max(ax_X_param_max, ax_Y_param_max, ax_Z_param_max);\n  //\n  m_obb.Placement      = ax3_placement;\n  m_obb.LocalCornerMin = corner_min;\n  m_obb.LocalCornerMax = corner_max;\n\n  return true;\n}\n\n//-----------------------------------------------------------------------------\n\nconst asiAlgo_OBB& asiAlgo_MeshOBB::GetResult() const\n{\n  return m_obb;\n}\n\n//-----------------------------------------------------------------------------\n\ngp_Trsf asiAlgo_MeshOBB::GetResultTrsf() const\n{\n  gp_Trsf T;\n  T.SetTransformation(m_obb.Placement);\n  T.Invert();\n  return T;\n}\n\n//-----------------------------------------------------------------------------\n\nTopoDS_Solid asiAlgo_MeshOBB::GetResultBox() const\n{\n  gp_Trsf T = this->GetResultTrsf();\n\n  // Build a properly located box solid representing OBB\n  TopoDS_Shape solid;\n  try\n  {\n    BRepPrimAPI_MakeBox mkOBB(m_obb.LocalCornerMin, m_obb.LocalCornerMax);\n    solid = BRepBuilderAPI_Transform(mkOBB.Solid(), T, true);\n  }\n  catch ( ... ) {}\n\n  return TopoDS::Solid(solid);\n}\n\n//-----------------------------------------------------------------------------\n\nvoid asiAlgo_MeshOBB::calculateByCovariance(gp_Ax1& xAxis,\n                                            gp_Ax1& yAxis,\n                                            gp_Ax1& zAxis,\n                                            gp_XYZ& meanVertex) const\n{\n  // Get number of nodes.\n  const int nNodes = m_input->NbNodes();\n\n  /* =======================\n   *  Calculate mean vertex\n   * ======================= */\n\n  gp_XYZ mu;\n  const TColgp_Array1OfPnt& nodes = m_input->Nodes();\n  //\n  for ( int i = nodes.Lower(); i <= nodes.Upper(); ++i )\n  {\n    const gp_Pnt& P = nodes(i);\n\n    const double node_X = P.X();\n    const double node_Y = P.Y();\n    const double node_Z = P.Z();\n\n    mu += gp_XYZ(node_X, node_Y, node_Z);\n  }\n  mu /= nNodes;\n\n  this->GetPlotter().DRAW_TRIANGULATION(m_input, Color_Magenta, 0.5);\n  this->GetPlotter().DRAW_POINT(mu, Color_Red);\n\n  /* =====================\n   *  Calculate main axes\n   * ===================== */\n\n  Eigen::Matrix3d C;\n  for ( int j = 1; j <= 3; ++j )\n  {\n    for ( int k = 1; k <= 3; ++k )\n    {\n      C(j-1, k-1) = 0.0; // TODO: is that necessary?\n    }\n  }\n\n  for ( int i = nodes.Lower(); i <= nodes.Upper(); ++i )\n  {\n    const gp_Pnt& P = nodes(i);\n    //\n    const double node_X = P.X();\n    const double node_Y = P.Y();\n    const double node_Z = P.Z();\n    //\n    gp_XYZ p(node_X, node_Y, node_Z);\n    gp_XYZ p_dash = p - mu;\n\n    for ( int j = 1; j <= 3; ++j )\n    {\n      for ( int k = 1; k <= 3; ++k )\n      {\n        C(j-1, k-1) += ( p_dash.Coord(j)*p_dash.Coord(k) );\n      }\n    }\n  }\n\n  for ( int j = 1; j <= 3; ++j )\n  {\n    for ( int k = 1; k <= 3; ++k )\n    {\n      C(j-1, k-1) /= (nNodes);\n    }\n  }\n\n  Eigen::EigenSolver<Eigen::Matrix3d> EigenSolver(C);\n\n#if defined COUT_DEBUG\n  std::cout << \"\\tThe eigen values of A are:\" << std::endl << EigenSolver.eigenvalues() << std::endl;\n  std::cout << \"\\tThe matrix of eigenvectors, V, is:\" << std::endl << EigenSolver.eigenvectors() << std::endl << std::endl;\n#endif\n\n  Eigen::Vector3cd v1 = EigenSolver.eigenvectors().col(0);\n  Eigen::Vector3cd v2 = EigenSolver.eigenvectors().col(1);\n  Eigen::Vector3cd v3 = EigenSolver.eigenvectors().col(2);\n\n  gp_Vec V[3] = { gp_Vec( v1.x().real(), v1.y().real(), v1.z().real() ),\n                  gp_Vec( v2.x().real(), v2.y().real(), v2.z().real() ),\n                  gp_Vec( v3.x().real(), v3.y().real(), v3.z().real() ) };\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 ax_X(mu, V[lambda[0].second]);\n  gp_Ax1 ax_Y(mu, V[lambda[1].second]);\n  gp_Ax1 ax_Z(mu, V[lambda[2].second]);\n\n  // Check if the system is right-handed.\n  const double ang = ax_X.Direction().AngleWithRef( ax_Y.Direction(), ax_Z.Direction() );\n  if ( ang < 0 )\n    ax_X.Reverse();\n\n  // Store results.\n  meanVertex = mu;\n  xAxis      = ax_X;\n  yAxis      = ax_Y;\n  zAxis      = ax_Z;\n}\n", "meta": {"hexsha": "dba4b3d42fb92f0e1a425dc5ef49f1689a84824a", "size": 10902, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/asiAlgo/mesh/asiAlgo_MeshOBB.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/mesh/asiAlgo_MeshOBB.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/mesh/asiAlgo_MeshOBB.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": 32.350148368, "max_line_length": 123, "alphanum_fraction": 0.5802605027, "num_tokens": 2870, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6477982043529715, "lm_q2_score": 0.4921881357207955, "lm_q1q2_score": 0.31883859052376795}}
{"text": "//  boost quaternion.hpp header file\r\n\r\n//  (C) Copyright Hubert Holin 2001.\r\n//  Distributed under the Boost Software License, Version 1.0. (See\r\n//  accompanying file LICENSE_1_0.txt or copy at\r\n//  http://www.boost.org/LICENSE_1_0.txt)\r\n\r\n// See http://www.boost.org for updates, documentation, and revision history.\r\n\r\n#ifndef BOOST_QUATERNION_HPP\r\n#define BOOST_QUATERNION_HPP\r\n\r\n#include <boost/config.hpp> // for BOOST_NO_STD_LOCALE\r\n#include <boost/math_fwd.hpp>\r\n#include <boost/detail/workaround.hpp>\r\n#include <boost/type_traits/is_convertible.hpp>\r\n#include <boost/utility/enable_if.hpp>\r\n#ifndef    BOOST_NO_STD_LOCALE\r\n#  include <locale>                                    // for the \"<<\" operator\r\n#endif /* BOOST_NO_STD_LOCALE */\r\n\r\n#include <complex>\r\n#include <iosfwd>                                    // for the \"<<\" and \">>\" operators\r\n#include <sstream>                                    // for the \"<<\" operator\r\n\r\n#include <boost/math/special_functions/sinc.hpp>    // for the Sinus cardinal\r\n#include <boost/math/special_functions/sinhc.hpp>    // for the Hyperbolic Sinus cardinal\r\n#include <boost/math/tools/cxx03_warn.hpp>\r\n\r\n#if defined(BOOST_NO_CXX11_NOEXCEPT) || defined(BOOST_NO_CXX11_RVALUE_REFERENCES) || defined(BOOST_NO_SFINAE_EXPR)\r\n#include <boost/type_traits/is_pod.hpp>\r\n#endif\r\n\r\nnamespace boost\r\n{\r\n   namespace math\r\n   {\r\n\r\n      namespace detail {\r\n\r\n#if !defined(BOOST_NO_CXX11_NOEXCEPT) && !defined(BOOST_NO_CXX11_RVALUE_REFERENCES) && !defined(BOOST_NO_SFINAE_EXPR)\r\n\r\n         template <class T>\r\n         struct is_trivial_arithmetic_type_imp\r\n         {\r\n            typedef boost::integral_constant<bool,\r\n               noexcept(std::declval<T&>() += std::declval<T>())\r\n               && noexcept(std::declval<T&>() -= std::declval<T>())\r\n               && noexcept(std::declval<T&>() *= std::declval<T>())\r\n               && noexcept(std::declval<T&>() /= std::declval<T>())\r\n            > type;\r\n         };\r\n\r\n         template <class T>\r\n         struct is_trivial_arithmetic_type : public is_trivial_arithmetic_type_imp<T>::type {};\r\n#else\r\n\r\n         template <class T>\r\n         struct is_trivial_arithmetic_type : public boost::is_pod<T> {};\r\n\r\n#endif\r\n\r\n      }\r\n\r\n#ifndef BOOST_NO_CXX14_CONSTEXPR\r\n      namespace constexpr_detail\r\n      {\r\n         template <class T>\r\n         constexpr void swap(T& a, T& b)\r\n         {\r\n            T t(a);\r\n            a = b;\r\n            b = t;\r\n         }\r\n       }\r\n#endif\r\n\r\n       template<typename T>\r\n        class quaternion\r\n        {\r\n        public:\r\n            \r\n            typedef T value_type;\r\n            \r\n            \r\n            // constructor for H seen as R^4\r\n            // (also default constructor)\r\n            \r\n            BOOST_CONSTEXPR explicit            quaternion( T const & requested_a = T(),\r\n                                            T const & requested_b = T(),\r\n                                            T const & requested_c = T(),\r\n                                            T const & requested_d = T())\r\n            :   a(requested_a),\r\n                b(requested_b),\r\n                c(requested_c),\r\n                d(requested_d)\r\n            {\r\n                // nothing to do!\r\n            }\r\n            \r\n            \r\n            // constructor for H seen as C^2\r\n                \r\n            BOOST_CONSTEXPR explicit            quaternion( ::std::complex<T> const & z0,\r\n                                            ::std::complex<T> const & z1 = ::std::complex<T>())\r\n            :   a(z0.real()),\r\n                b(z0.imag()),\r\n                c(z1.real()),\r\n                d(z1.imag())\r\n            {\r\n                // nothing to do!\r\n            }\r\n            \r\n            \r\n            // UNtemplated copy constructor\r\n            BOOST_CONSTEXPR quaternion(quaternion const & a_recopier)\r\n               : a(a_recopier.R_component_1()),\r\n               b(a_recopier.R_component_2()),\r\n               c(a_recopier.R_component_3()),\r\n               d(a_recopier.R_component_4()) {}\r\n#ifndef BOOST_NO_CXX11_RVALUE_REFERENCES\r\n            BOOST_CONSTEXPR quaternion(quaternion && a_recopier)\r\n               : a(std::move(a_recopier.R_component_1())),\r\n               b(std::move(a_recopier.R_component_2())),\r\n               c(std::move(a_recopier.R_component_3())),\r\n               d(std::move(a_recopier.R_component_4())) {}\r\n#endif\r\n            \r\n            // templated copy constructor\r\n            \r\n            template<typename X>\r\n            BOOST_CONSTEXPR explicit            quaternion(quaternion<X> const & a_recopier)\r\n            :   a(static_cast<T>(a_recopier.R_component_1())),\r\n                b(static_cast<T>(a_recopier.R_component_2())),\r\n                c(static_cast<T>(a_recopier.R_component_3())),\r\n                d(static_cast<T>(a_recopier.R_component_4()))\r\n            {\r\n                // nothing to do!\r\n            }\r\n            \r\n            \r\n            // destructor\r\n            // (this is taken care of by the compiler itself)\r\n            \r\n            \r\n            // accessors\r\n            //\r\n            // Note:    Like complex number, quaternions do have a meaningful notion of \"real part\",\r\n            //            but unlike them there is no meaningful notion of \"imaginary part\".\r\n            //            Instead there is an \"unreal part\" which itself is a quaternion, and usually\r\n            //            nothing simpler (as opposed to the complex number case).\r\n            //            However, for practicality, there are accessors for the other components\r\n            //            (these are necessary for the templated copy constructor, for instance).\r\n            \r\n            BOOST_CONSTEXPR T real() const\r\n            {\r\n               return(a);\r\n            }\r\n\r\n            BOOST_CONSTEXPR quaternion<T> unreal() const\r\n            {\r\n               return(quaternion<T>(static_cast<T>(0), b, c, d));\r\n            }\r\n\r\n            BOOST_CONSTEXPR T R_component_1() const\r\n            {\r\n               return(a);\r\n            }\r\n\r\n            BOOST_CONSTEXPR T R_component_2() const\r\n            {\r\n               return(b);\r\n            }\r\n\r\n            BOOST_CONSTEXPR T R_component_3() const\r\n            {\r\n               return(c);\r\n            }\r\n\r\n            BOOST_CONSTEXPR T R_component_4() const\r\n            {\r\n               return(d);\r\n            }\r\n\r\n            BOOST_CONSTEXPR ::std::complex<T> C_component_1() const\r\n            {\r\n               return(::std::complex<T>(a, b));\r\n            }\r\n\r\n            BOOST_CONSTEXPR ::std::complex<T> C_component_2() const\r\n            {\r\n               return(::std::complex<T>(c, d));\r\n            }\r\n\r\n            BOOST_CXX14_CONSTEXPR void swap(quaternion& o)\r\n            {\r\n#ifndef BOOST_NO_CXX14_CONSTEXPR\r\n               using constexpr_detail::swap;\r\n#else\r\n               using std::swap;\r\n#endif\r\n               swap(a, o.a);\r\n               swap(b, o.b);\r\n               swap(c, o.c);\r\n               swap(d, o.d);\r\n            }\r\n\r\n            // assignment operators\r\n            \r\n            template<typename X>\r\n            BOOST_CXX14_CONSTEXPR quaternion<T> &        operator = (quaternion<X> const  & a_affecter)\r\n            {\r\n               a = static_cast<T>(a_affecter.R_component_1());\r\n               b = static_cast<T>(a_affecter.R_component_2());\r\n               c = static_cast<T>(a_affecter.R_component_3());\r\n               d = static_cast<T>(a_affecter.R_component_4());\r\n\r\n               return(*this);\r\n            }\r\n\r\n            BOOST_CXX14_CONSTEXPR quaternion<T> &        operator = (quaternion<T> const & a_affecter)\r\n            {\r\n               a = a_affecter.a;\r\n               b = a_affecter.b;\r\n               c = a_affecter.c;\r\n               d = a_affecter.d;\r\n\r\n               return(*this);\r\n            }\r\n#ifndef BOOST_NO_CXX11_RVALUE_REFERENCES\r\n            BOOST_CXX14_CONSTEXPR quaternion<T> &        operator = (quaternion<T> && a_affecter)\r\n            {\r\n               a = std::move(a_affecter.a);\r\n               b = std::move(a_affecter.b);\r\n               c = std::move(a_affecter.c);\r\n               d = std::move(a_affecter.d);\r\n\r\n               return(*this);\r\n            }\r\n#endif\r\n            BOOST_CXX14_CONSTEXPR quaternion<T> &        operator = (T const & a_affecter)\r\n            {\r\n               a = a_affecter;\r\n\r\n               b = c = d = static_cast<T>(0);\r\n\r\n               return(*this);\r\n            }\r\n\r\n            BOOST_CXX14_CONSTEXPR quaternion<T> &        operator = (::std::complex<T> const & a_affecter)\r\n            {\r\n               a = a_affecter.real();\r\n               b = a_affecter.imag();\r\n\r\n               c = d = static_cast<T>(0);\r\n\r\n               return(*this);\r\n            }\r\n\r\n            // other assignment-related operators\r\n            //\r\n            // NOTE:    Quaternion multiplication is *NOT* commutative;\r\n            //            symbolically, \"q *= rhs;\" means \"q = q * rhs;\"\r\n            //            and \"q /= rhs;\" means \"q = q * inverse_of(rhs);\"\r\n            //\r\n            // Note2:   Each operator comes in 2 forms - one for the simple case where\r\n            //          type T throws no exceptions, and one exception-safe version\r\n            //          for the case where it might.\r\n         private:\r\n            BOOST_CXX14_CONSTEXPR quaternion<T> &        do_add(T const & rhs, const boost::true_type&)\r\n            {\r\n               a += rhs;\r\n               return *this;\r\n            }\r\n            BOOST_CXX14_CONSTEXPR quaternion<T> &        do_add(T const & rhs, const boost::false_type&)\r\n            {\r\n               quaternion<T> result(a + rhs, b, c, d); // exception guard\r\n               swap(result);\r\n               return *this;\r\n            }\r\n            BOOST_CXX14_CONSTEXPR quaternion<T> &        do_add(std::complex<T> const & rhs, const boost::true_type&)\r\n            {\r\n               a += std::real(rhs);\r\n               b += std::imag(rhs);\r\n               return *this;\r\n            }\r\n            BOOST_CXX14_CONSTEXPR quaternion<T> &        do_add(std::complex<T> const & rhs, const boost::false_type&)\r\n            {\r\n               quaternion<T> result(a + std::real(rhs), b + std::imag(rhs), c, d); // exception guard\r\n               swap(result);\r\n               return *this;\r\n            }\r\n            template <class X>\r\n            BOOST_CXX14_CONSTEXPR quaternion<T> &        do_add(quaternion<X> const & rhs, const boost::true_type&)\r\n            {\r\n               a += rhs.R_component_1();\r\n               b += rhs.R_component_2();\r\n               c += rhs.R_component_3();\r\n               d += rhs.R_component_4();\r\n               return *this;\r\n            }\r\n            template <class X>\r\n            BOOST_CXX14_CONSTEXPR quaternion<T> &        do_add(quaternion<X> const & rhs, const boost::false_type&)\r\n            {\r\n               quaternion<T> result(a + rhs.R_component_1(), b + rhs.R_component_2(), c + rhs.R_component_3(), d + rhs.R_component_4()); // exception guard\r\n               swap(result);\r\n               return *this;\r\n            }\r\n\r\n            BOOST_CXX14_CONSTEXPR quaternion<T> &        do_subtract(T const & rhs, const boost::true_type&)\r\n            {\r\n               a -= rhs;\r\n               return *this;\r\n            }\r\n            BOOST_CXX14_CONSTEXPR quaternion<T> &        do_subtract(T const & rhs, const boost::false_type&)\r\n            {\r\n               quaternion<T> result(a - rhs, b, c, d); // exception guard\r\n               swap(result);\r\n               return *this;\r\n            }\r\n            BOOST_CXX14_CONSTEXPR quaternion<T> &        do_subtract(std::complex<T> const & rhs, const boost::true_type&)\r\n            {\r\n               a -= std::real(rhs);\r\n               b -= std::imag(rhs);\r\n               return *this;\r\n            }\r\n            BOOST_CXX14_CONSTEXPR quaternion<T> &        do_subtract(std::complex<T> const & rhs, const boost::false_type&)\r\n            {\r\n               quaternion<T> result(a - std::real(rhs), b - std::imag(rhs), c, d); // exception guard\r\n               swap(result);\r\n               return *this;\r\n            }\r\n            template <class X>\r\n            BOOST_CXX14_CONSTEXPR quaternion<T> &        do_subtract(quaternion<X> const & rhs, const boost::true_type&)\r\n            {\r\n               a -= rhs.R_component_1();\r\n               b -= rhs.R_component_2();\r\n               c -= rhs.R_component_3();\r\n               d -= rhs.R_component_4();\r\n               return *this;\r\n            }\r\n            template <class X>\r\n            BOOST_CXX14_CONSTEXPR quaternion<T> &        do_subtract(quaternion<X> const & rhs, const boost::false_type&)\r\n            {\r\n               quaternion<T> result(a - rhs.R_component_1(), b - rhs.R_component_2(), c - rhs.R_component_3(), d - rhs.R_component_4()); // exception guard\r\n               swap(result);\r\n               return *this;\r\n            }\r\n\r\n            BOOST_CXX14_CONSTEXPR quaternion<T> &        do_multiply(T const & rhs, const boost::true_type&)\r\n            {\r\n               a *= rhs;\r\n               b *= rhs;\r\n               c *= rhs;\r\n               d *= rhs;\r\n               return *this;\r\n            }\r\n            BOOST_CXX14_CONSTEXPR quaternion<T> &        do_multiply(T const & rhs, const boost::false_type&)\r\n            {\r\n               quaternion<T> result(a * rhs, b * rhs, c * rhs, d * rhs); // exception guard\r\n               swap(result);\r\n               return *this;\r\n            }\r\n\r\n            BOOST_CXX14_CONSTEXPR quaternion<T> &        do_divide(T const & rhs, const boost::true_type&)\r\n            {\r\n               a /= rhs;\r\n               b /= rhs;\r\n               c /= rhs;\r\n               d /= rhs;\r\n               return *this;\r\n            }\r\n            BOOST_CXX14_CONSTEXPR quaternion<T> &        do_divide(T const & rhs, const boost::false_type&)\r\n            {\r\n               quaternion<T> result(a / rhs, b / rhs, c / rhs, d / rhs); // exception guard\r\n               swap(result);\r\n               return *this;\r\n            }\r\n         public:\r\n\r\n            BOOST_CXX14_CONSTEXPR quaternion<T> &        operator += (T const & rhs) { return do_add(rhs, detail::is_trivial_arithmetic_type<T>()); }\r\n            BOOST_CXX14_CONSTEXPR quaternion<T> &        operator += (::std::complex<T> const & rhs) { return do_add(rhs, detail::is_trivial_arithmetic_type<T>()); }\r\n            template<typename X> BOOST_CXX14_CONSTEXPR quaternion<T> & operator += (quaternion<X> const & rhs) { return do_add(rhs, detail::is_trivial_arithmetic_type<T>()); }\r\n\r\n            BOOST_CXX14_CONSTEXPR quaternion<T> &        operator -= (T const & rhs) { return do_subtract(rhs, detail::is_trivial_arithmetic_type<T>()); }\r\n            BOOST_CXX14_CONSTEXPR quaternion<T> &        operator -= (::std::complex<T> const & rhs) { return do_subtract(rhs, detail::is_trivial_arithmetic_type<T>()); }\r\n            template<typename X> BOOST_CXX14_CONSTEXPR quaternion<T> & operator -= (quaternion<X> const & rhs) { return do_subtract(rhs, detail::is_trivial_arithmetic_type<T>()); }\r\n            \r\n            BOOST_CXX14_CONSTEXPR quaternion<T> &        operator *= (T const & rhs) { return do_multiply(rhs, detail::is_trivial_arithmetic_type<T>()); }\r\n            \r\n            BOOST_CXX14_CONSTEXPR quaternion<T> &        operator *= (::std::complex<T> const & rhs)\r\n            {\r\n                T    ar = rhs.real();\r\n                T    br = rhs.imag();\r\n                quaternion<T> result(a*ar - b*br, a*br + b*ar, c*ar + d*br, -c*br+d*ar);\r\n                swap(result);\r\n                return(*this);\r\n            }\r\n            \r\n            template<typename X>\r\n            BOOST_CXX14_CONSTEXPR quaternion<T> &        operator *= (quaternion<X> const & rhs)\r\n            {\r\n                T    ar = static_cast<T>(rhs.R_component_1());\r\n                T    br = static_cast<T>(rhs.R_component_2());\r\n                T    cr = static_cast<T>(rhs.R_component_3());\r\n                T    dr = static_cast<T>(rhs.R_component_4());\r\n                \r\n                quaternion<T> result(a*ar - b*br - c*cr - d*dr, a*br + b*ar + c*dr - d*cr, a*cr - b*dr + c*ar + d*br, a*dr + b*cr - c*br + d*ar);\r\n                swap(result);\r\n                return(*this);\r\n            }\r\n            \r\n            BOOST_CXX14_CONSTEXPR quaternion<T> &        operator /= (T const & rhs) { return do_divide(rhs, detail::is_trivial_arithmetic_type<T>()); }\r\n            \r\n            BOOST_CXX14_CONSTEXPR quaternion<T> &        operator /= (::std::complex<T> const & rhs)\r\n            {\r\n                T    ar = rhs.real();\r\n                T    br = rhs.imag();\r\n                T    denominator = ar*ar+br*br;\r\n                quaternion<T> result((+a*ar + b*br) / denominator, (-a*br + b*ar) / denominator, (+c*ar - d*br) / denominator, (+c*br + d*ar) / denominator);\r\n                swap(result);\r\n                return(*this);\r\n            }\r\n            \r\n            template<typename X>\r\n            BOOST_CXX14_CONSTEXPR quaternion<T> &        operator /= (quaternion<X> const & rhs)\r\n            {\r\n                T    ar = static_cast<T>(rhs.R_component_1());\r\n                T    br = static_cast<T>(rhs.R_component_2());\r\n                T    cr = static_cast<T>(rhs.R_component_3());\r\n                T    dr = static_cast<T>(rhs.R_component_4());\r\n                \r\n                T    denominator = ar*ar+br*br+cr*cr+dr*dr;\r\n                quaternion<T> result((+a*ar+b*br+c*cr+d*dr)/denominator, (-a*br+b*ar-c*dr+d*cr)/denominator, (-a*cr+b*dr+c*ar-d*br)/denominator, (-a*dr-b*cr+c*br+d*ar)/denominator);\r\n                swap(result);\r\n                return(*this);\r\n            }\r\n        private:\r\n           T a, b, c, d;\r\n            \r\n        };\r\n\r\n// swap:\r\ntemplate <class T>\r\nBOOST_CXX14_CONSTEXPR void swap(quaternion<T>& a, quaternion<T>& b) { a.swap(b); }\r\n        \r\n// operator+\r\ntemplate <class T1, class T2>\r\ninline BOOST_CONSTEXPR typename boost::enable_if_c<boost::is_convertible<T2, T1>::value, quaternion<T1> >::type\r\noperator + (const quaternion<T1>& a, const T2& b)\r\n{\r\n   return quaternion<T1>(static_cast<T1>(a.R_component_1() + b), a.R_component_2(), a.R_component_3(), a.R_component_4());\r\n}\r\ntemplate <class T1, class T2>\r\ninline BOOST_CONSTEXPR typename boost::enable_if_c<boost::is_convertible<T1, T2>::value, quaternion<T2> >::type\r\noperator + (const T1& a, const quaternion<T2>& b)\r\n{\r\n   return quaternion<T2>(static_cast<T2>(b.R_component_1() + a), b.R_component_2(), b.R_component_3(), b.R_component_4());\r\n}\r\ntemplate <class T1, class T2>\r\ninline BOOST_CONSTEXPR typename boost::enable_if_c<boost::is_convertible<T2, T1>::value, quaternion<T1> >::type\r\noperator + (const quaternion<T1>& a, const std::complex<T2>& b)\r\n{\r\n   return quaternion<T1>(a.R_component_1() + std::real(b), a.R_component_2() + std::imag(b), a.R_component_3(), a.R_component_4());\r\n}\r\ntemplate <class T1, class T2>\r\ninline BOOST_CONSTEXPR typename boost::enable_if_c<boost::is_convertible<T1, T2>::value, quaternion<T2> >::type\r\noperator + (const std::complex<T1>& a, const quaternion<T2>& b)\r\n{\r\n   return quaternion<T1>(b.R_component_1() + real(a), b.R_component_2() + imag(a), b.R_component_3(), b.R_component_4());\r\n}\r\ntemplate <class T>\r\ninline BOOST_CONSTEXPR quaternion<T> operator + (const quaternion<T>& a, const quaternion<T>& b)\r\n{\r\n   return quaternion<T>(a.R_component_1() + b.R_component_1(), a.R_component_2() + b.R_component_2(), a.R_component_3() + b.R_component_3(), a.R_component_4() + b.R_component_4());\r\n}\r\n// operator-\r\ntemplate <class T1, class T2>\r\ninline BOOST_CONSTEXPR typename boost::enable_if_c<boost::is_convertible<T2, T1>::value, quaternion<T1> >::type\r\noperator - (const quaternion<T1>& a, const T2& b)\r\n{\r\n   return quaternion<T1>(static_cast<T1>(a.R_component_1() - b), a.R_component_2(), a.R_component_3(), a.R_component_4());\r\n}\r\ntemplate <class T1, class T2>\r\ninline BOOST_CONSTEXPR typename boost::enable_if_c<boost::is_convertible<T1, T2>::value, quaternion<T2> >::type\r\noperator - (const T1& a, const quaternion<T2>& b)\r\n{\r\n   return quaternion<T2>(static_cast<T2>(a - b.R_component_1()), -b.R_component_2(), -b.R_component_3(), -b.R_component_4());\r\n}\r\ntemplate <class T1, class T2>\r\ninline BOOST_CONSTEXPR typename boost::enable_if_c<boost::is_convertible<T2, T1>::value, quaternion<T1> >::type\r\noperator - (const quaternion<T1>& a, const std::complex<T2>& b)\r\n{\r\n   return quaternion<T1>(a.R_component_1() - std::real(b), a.R_component_2() - std::imag(b), a.R_component_3(), a.R_component_4());\r\n}\r\ntemplate <class T1, class T2>\r\ninline BOOST_CONSTEXPR typename boost::enable_if_c<boost::is_convertible<T1, T2>::value, quaternion<T2> >::type\r\noperator - (const std::complex<T1>& a, const quaternion<T2>& b)\r\n{\r\n   return quaternion<T1>(real(a) - b.R_component_1(), imag(a) - b.R_component_2(), -b.R_component_3(), -b.R_component_4());\r\n}\r\ntemplate <class T>\r\ninline BOOST_CONSTEXPR quaternion<T> operator - (const quaternion<T>& a, const quaternion<T>& b)\r\n{\r\n   return quaternion<T>(a.R_component_1() - b.R_component_1(), a.R_component_2() - b.R_component_2(), a.R_component_3() - b.R_component_3(), a.R_component_4() - b.R_component_4());\r\n}\r\n\r\n// operator*\r\ntemplate <class T1, class T2>\r\ninline BOOST_CONSTEXPR typename boost::enable_if_c<boost::is_convertible<T2, T1>::value, quaternion<T1> >::type\r\noperator * (const quaternion<T1>& a, const T2& b)\r\n{\r\n   return quaternion<T1>(static_cast<T1>(a.R_component_1() * b), a.R_component_2() * b, a.R_component_3() * b, a.R_component_4() * b);\r\n}\r\ntemplate <class T1, class T2>\r\ninline BOOST_CONSTEXPR typename boost::enable_if_c<boost::is_convertible<T1, T2>::value, quaternion<T2> >::type\r\noperator * (const T1& a, const quaternion<T2>& b)\r\n{\r\n   return quaternion<T2>(static_cast<T2>(a * b.R_component_1()), a * b.R_component_2(), a * b.R_component_3(), a * b.R_component_4());\r\n}\r\ntemplate <class T1, class T2>\r\ninline BOOST_CXX14_CONSTEXPR typename boost::enable_if_c<boost::is_convertible<T2, T1>::value, quaternion<T1> >::type\r\noperator * (const quaternion<T1>& a, const std::complex<T2>& b)\r\n{\r\n   quaternion<T1> result(a);\r\n   result *= b;\r\n   return result;\r\n}\r\ntemplate <class T1, class T2>\r\ninline BOOST_CXX14_CONSTEXPR typename boost::enable_if_c<boost::is_convertible<T1, T2>::value, quaternion<T2> >::type\r\noperator * (const std::complex<T1>& a, const quaternion<T2>& b)\r\n{\r\n   quaternion<T1> result(a);\r\n   result *= b;\r\n   return result;\r\n}\r\ntemplate <class T>\r\ninline BOOST_CXX14_CONSTEXPR quaternion<T> operator * (const quaternion<T>& a, const quaternion<T>& b)\r\n{\r\n   quaternion<T> result(a);\r\n   result *= b;\r\n   return result;\r\n}\r\n\r\n// operator/\r\ntemplate <class T1, class T2>\r\ninline BOOST_CONSTEXPR typename boost::enable_if_c<boost::is_convertible<T2, T1>::value, quaternion<T1> >::type\r\noperator / (const quaternion<T1>& a, const T2& b)\r\n{\r\n   return quaternion<T1>(a.R_component_1() / b, a.R_component_2() / b, a.R_component_3() / b, a.R_component_4() / b);\r\n}\r\ntemplate <class T1, class T2>\r\ninline BOOST_CXX14_CONSTEXPR typename boost::enable_if_c<boost::is_convertible<T1, T2>::value, quaternion<T2> >::type\r\noperator / (const T1& a, const quaternion<T2>& b)\r\n{\r\n   quaternion<T2> result(a);\r\n   result /= b;\r\n   return result;\r\n}\r\ntemplate <class T1, class T2>\r\ninline BOOST_CXX14_CONSTEXPR typename boost::enable_if_c<boost::is_convertible<T2, T1>::value, quaternion<T1> >::type\r\noperator / (const quaternion<T1>& a, const std::complex<T2>& b)\r\n{\r\n   quaternion<T1> result(a);\r\n   result /= b;\r\n   return result;\r\n}\r\ntemplate <class T1, class T2>\r\ninline BOOST_CXX14_CONSTEXPR typename boost::enable_if_c<boost::is_convertible<T1, T2>::value, quaternion<T2> >::type\r\noperator / (const std::complex<T1>& a, const quaternion<T2>& b)\r\n{\r\n   quaternion<T2> result(a);\r\n   result /= b;\r\n   return result;\r\n}\r\ntemplate <class T>\r\ninline BOOST_CXX14_CONSTEXPR quaternion<T> operator / (const quaternion<T>& a, const quaternion<T>& b)\r\n{\r\n   quaternion<T> result(a);\r\n   result /= b;\r\n   return result;\r\n}\r\n        \r\n        \r\n        template<typename T>\r\n        inline BOOST_CONSTEXPR const quaternion<T>&             operator + (quaternion<T> const & q)\r\n        {\r\n            return q;\r\n        }\r\n        \r\n        \r\n        template<typename T>\r\n        inline BOOST_CONSTEXPR quaternion<T>                    operator - (quaternion<T> const & q)\r\n        {\r\n            return(quaternion<T>(-q.R_component_1(),-q.R_component_2(),-q.R_component_3(),-q.R_component_4()));\r\n        }\r\n        \r\n        \r\n        template<typename R, typename T>\r\n        inline BOOST_CONSTEXPR typename boost::enable_if_c<boost::is_convertible<R, T>::value, bool>::type operator == (R const & lhs, quaternion<T> const & rhs)\r\n        {\r\n            return    (\r\n                        (rhs.R_component_1() == lhs)&&\r\n                        (rhs.R_component_2() == static_cast<T>(0))&&\r\n                        (rhs.R_component_3() == static_cast<T>(0))&&\r\n                        (rhs.R_component_4() == static_cast<T>(0))\r\n                    );\r\n        }\r\n        \r\n        \r\n        template<typename T, typename R>\r\n        inline BOOST_CONSTEXPR typename boost::enable_if_c<boost::is_convertible<R, T>::value, bool>::type operator == (quaternion<T> const & lhs, R const & rhs)\r\n        {\r\n           return rhs == lhs;\r\n        }\r\n        \r\n        \r\n        template<typename T>\r\n        inline BOOST_CONSTEXPR bool                                operator == (::std::complex<T> const & lhs, quaternion<T> const & rhs)\r\n        {\r\n            return    (\r\n                        (rhs.R_component_1() == lhs.real())&&\r\n                        (rhs.R_component_2() == lhs.imag())&&\r\n                        (rhs.R_component_3() == static_cast<T>(0))&&\r\n                        (rhs.R_component_4() == static_cast<T>(0))\r\n                    );\r\n        }\r\n        \r\n        \r\n        template<typename T>\r\n        inline BOOST_CONSTEXPR bool                                operator == (quaternion<T> const & lhs, ::std::complex<T> const & rhs)\r\n        {\r\n           return rhs == lhs;\r\n        }\r\n        \r\n        \r\n        template<typename T>\r\n        inline BOOST_CONSTEXPR bool                                operator == (quaternion<T> const & lhs, quaternion<T> const & rhs)\r\n        {\r\n            return    (\r\n                        (rhs.R_component_1() == lhs.R_component_1())&&\r\n                        (rhs.R_component_2() == lhs.R_component_2())&&\r\n                        (rhs.R_component_3() == lhs.R_component_3())&&\r\n                        (rhs.R_component_4() == lhs.R_component_4())\r\n                    );\r\n        }\r\n                \r\n        template<typename R, typename T> inline BOOST_CONSTEXPR bool operator != (R const & lhs, quaternion<T> const & rhs) { return !(lhs == rhs); }\r\n        template<typename T, typename R> inline BOOST_CONSTEXPR bool operator != (quaternion<T> const & lhs, R const & rhs) { return !(lhs == rhs); }\r\n        template<typename T> inline BOOST_CONSTEXPR bool operator != (::std::complex<T> const & lhs, quaternion<T> const & rhs) { return !(lhs == rhs); }\r\n        template<typename T> inline BOOST_CONSTEXPR bool operator != (quaternion<T> const & lhs, ::std::complex<T> const & rhs) { return !(lhs == rhs); }\r\n        template<typename T> inline BOOST_CONSTEXPR bool operator != (quaternion<T> const & lhs, quaternion<T> const & rhs) { return !(lhs == rhs); }\r\n        \r\n        \r\n        // Note:    we allow the following formats, with a, b, c, and d reals\r\n        //            a\r\n        //            (a), (a,b), (a,b,c), (a,b,c,d)\r\n        //            (a,(c)), (a,(c,d)), ((a)), ((a),c), ((a),(c)), ((a),(c,d)), ((a,b)), ((a,b),c), ((a,b),(c)), ((a,b),(c,d))\r\n        template<typename T, typename charT, class traits>\r\n        ::std::basic_istream<charT,traits> &    operator >> (    ::std::basic_istream<charT,traits> & is,\r\n                                                                quaternion<T> & q)\r\n        {\r\n            \r\n#ifdef    BOOST_NO_STD_LOCALE\r\n#else\r\n            const ::std::ctype<charT> & ct = ::std::use_facet< ::std::ctype<charT> >(is.getloc());\r\n#endif /* BOOST_NO_STD_LOCALE */\r\n            \r\n            T    a = T();\r\n            T    b = T();\r\n            T    c = T();\r\n            T    d = T();\r\n            \r\n            ::std::complex<T>    u = ::std::complex<T>();\r\n            ::std::complex<T>    v = ::std::complex<T>();\r\n            \r\n            charT    ch = charT();\r\n            char    cc;\r\n            \r\n            is >> ch;                                        // get the first lexeme\r\n            \r\n            if    (!is.good())    goto finish;\r\n            \r\n#ifdef    BOOST_NO_STD_LOCALE\r\n            cc = ch;\r\n#else\r\n            cc = ct.narrow(ch, char());\r\n#endif /* BOOST_NO_STD_LOCALE */\r\n            \r\n            if    (cc == '(')                            // read \"(\", possible: (a), (a,b), (a,b,c), (a,b,c,d), (a,(c)), (a,(c,d)), ((a)), ((a),c), ((a),(c)), ((a),(c,d)), ((a,b)), ((a,b),c), ((a,b),(c)), ((a,b,),(c,d,))\r\n            {\r\n                is >> ch;                                    // get the second lexeme\r\n                \r\n                if    (!is.good())    goto finish;\r\n                \r\n#ifdef    BOOST_NO_STD_LOCALE\r\n                cc = ch;\r\n#else\r\n                cc = ct.narrow(ch, char());\r\n#endif /* BOOST_NO_STD_LOCALE */\r\n                \r\n                if    (cc == '(')                        // read \"((\", possible: ((a)), ((a),c), ((a),(c)), ((a),(c,d)), ((a,b)), ((a,b),c), ((a,b),(c)), ((a,b,),(c,d,))\r\n                {\r\n                    is.putback(ch);\r\n                    \r\n                    is >> u;                                // we extract the first and second components\r\n                    a = u.real();\r\n                    b = u.imag();\r\n                    \r\n                    if    (!is.good())    goto finish;\r\n                    \r\n                    is >> ch;                                // get the next lexeme\r\n                    \r\n                    if    (!is.good())    goto finish;\r\n                    \r\n#ifdef    BOOST_NO_STD_LOCALE\r\n                    cc = ch;\r\n#else\r\n                    cc = ct.narrow(ch, char());\r\n#endif /* BOOST_NO_STD_LOCALE */\r\n                    \r\n                    if        (cc == ')')                    // format: ((a)) or ((a,b))\r\n                    {\r\n                        q = quaternion<T>(a,b);\r\n                    }\r\n                    else if    (cc == ',')                // read \"((a),\" or \"((a,b),\", possible: ((a),c), ((a),(c)), ((a),(c,d)), ((a,b),c), ((a,b),(c)), ((a,b,),(c,d,))\r\n                    {\r\n                        is >> v;                            // we extract the third and fourth components\r\n                        c = v.real();\r\n                        d = v.imag();\r\n                        \r\n                        if    (!is.good())    goto finish;\r\n                        \r\n                        is >> ch;                                // get the last lexeme\r\n                        \r\n                        if    (!is.good())    goto finish;\r\n                        \r\n#ifdef    BOOST_NO_STD_LOCALE\r\n                        cc = ch;\r\n#else\r\n                        cc = ct.narrow(ch, char());\r\n#endif /* BOOST_NO_STD_LOCALE */\r\n                        \r\n                        if    (cc == ')')                    // format: ((a),c), ((a),(c)), ((a),(c,d)), ((a,b),c), ((a,b),(c)) or ((a,b,),(c,d,))\r\n                        {\r\n                            q = quaternion<T>(a,b,c,d);\r\n                        }\r\n                        else                            // error\r\n                        {\r\n                            is.setstate(::std::ios_base::failbit);\r\n                        }\r\n                    }\r\n                    else                                // error\r\n                    {\r\n                        is.setstate(::std::ios_base::failbit);\r\n                    }\r\n                }\r\n                else                                // read \"(a\", possible: (a), (a,b), (a,b,c), (a,b,c,d), (a,(c)), (a,(c,d))\r\n                {\r\n                    is.putback(ch);\r\n                    \r\n                    is >> a;                                // we extract the first component\r\n                    \r\n                    if    (!is.good())    goto finish;\r\n                    \r\n                    is >> ch;                                // get the third lexeme\r\n                    \r\n                    if    (!is.good())    goto finish;\r\n                    \r\n#ifdef    BOOST_NO_STD_LOCALE\r\n                    cc = ch;\r\n#else\r\n                    cc = ct.narrow(ch, char());\r\n#endif /* BOOST_NO_STD_LOCALE */\r\n                    \r\n                    if        (cc == ')')                    // format: (a)\r\n                    {\r\n                        q = quaternion<T>(a);\r\n                    }\r\n                    else if    (cc == ',')                // read \"(a,\", possible: (a,b), (a,b,c), (a,b,c,d), (a,(c)), (a,(c,d))\r\n                    {\r\n                        is >> ch;                            // get the fourth lexeme\r\n                        \r\n                        if    (!is.good())    goto finish;\r\n                        \r\n#ifdef    BOOST_NO_STD_LOCALE\r\n                        cc = ch;\r\n#else\r\n                        cc = ct.narrow(ch, char());\r\n#endif /* BOOST_NO_STD_LOCALE */\r\n                        \r\n                        if    (cc == '(')                // read \"(a,(\", possible: (a,(c)), (a,(c,d))\r\n                        {\r\n                            is.putback(ch);\r\n                            \r\n                            is >> v;                        // we extract the third and fourth component\r\n                            \r\n                            c = v.real();\r\n                            d = v.imag();\r\n                            \r\n                            if    (!is.good())    goto finish;\r\n                            \r\n                            is >> ch;                        // get the ninth lexeme\r\n                            \r\n                            if    (!is.good())    goto finish;\r\n                            \r\n#ifdef    BOOST_NO_STD_LOCALE\r\n                            cc = ch;\r\n#else\r\n                            cc = ct.narrow(ch, char());\r\n#endif /* BOOST_NO_STD_LOCALE */\r\n                            \r\n                            if    (cc == ')')                // format: (a,(c)) or (a,(c,d))\r\n                            {\r\n                                q = quaternion<T>(a,b,c,d);\r\n                            }\r\n                            else                        // error\r\n                            {\r\n                                is.setstate(::std::ios_base::failbit);\r\n                            }\r\n                        }\r\n                        else                        // read \"(a,b\", possible: (a,b), (a,b,c), (a,b,c,d)\r\n                        {\r\n                            is.putback(ch);\r\n                            \r\n                            is >> b;                        // we extract the second component\r\n                            \r\n                            if    (!is.good())    goto finish;\r\n                            \r\n                            is >> ch;                        // get the fifth lexeme\r\n                            \r\n                            if    (!is.good())    goto finish;\r\n                            \r\n#ifdef    BOOST_NO_STD_LOCALE\r\n                            cc = ch;\r\n#else\r\n                            cc = ct.narrow(ch, char());\r\n#endif /* BOOST_NO_STD_LOCALE */\r\n                            \r\n                            if    (cc == ')')                // format: (a,b)\r\n                            {\r\n                                q = quaternion<T>(a,b);\r\n                            }\r\n                            else if    (cc == ',')        // read \"(a,b,\", possible: (a,b,c), (a,b,c,d)\r\n                            {\r\n                                is >> c;                    // we extract the third component\r\n                                \r\n                                if    (!is.good())    goto finish;\r\n                                \r\n                                is >> ch;                    // get the seventh lexeme\r\n                                \r\n                                if    (!is.good())    goto finish;\r\n                                \r\n#ifdef    BOOST_NO_STD_LOCALE\r\n                                cc = ch;\r\n#else\r\n                                cc = ct.narrow(ch, char());\r\n#endif /* BOOST_NO_STD_LOCALE */\r\n                                \r\n                                if        (cc == ')')        // format: (a,b,c)\r\n                                {\r\n                                    q = quaternion<T>(a,b,c);\r\n                                }\r\n                                else if    (cc == ',')    // read \"(a,b,c,\", possible: (a,b,c,d)\r\n                                {\r\n                                    is >> d;                // we extract the fourth component\r\n                                    \r\n                                    if    (!is.good())    goto finish;\r\n                                    \r\n                                    is >> ch;                // get the ninth lexeme\r\n                                    \r\n                                    if    (!is.good())    goto finish;\r\n                                    \r\n#ifdef    BOOST_NO_STD_LOCALE\r\n                                    cc = ch;\r\n#else\r\n                                    cc = ct.narrow(ch, char());\r\n#endif /* BOOST_NO_STD_LOCALE */\r\n                                    \r\n                                    if    (cc == ')')        // format: (a,b,c,d)\r\n                                    {\r\n                                        q = quaternion<T>(a,b,c,d);\r\n                                    }\r\n                                    else                // error\r\n                                    {\r\n                                        is.setstate(::std::ios_base::failbit);\r\n                                    }\r\n                                }\r\n                                else                    // error\r\n                                {\r\n                                    is.setstate(::std::ios_base::failbit);\r\n                                }\r\n                            }\r\n                            else                        // error\r\n                            {\r\n                                is.setstate(::std::ios_base::failbit);\r\n                            }\r\n                        }\r\n                    }\r\n                    else                                // error\r\n                    {\r\n                        is.setstate(::std::ios_base::failbit);\r\n                    }\r\n                }\r\n            }\r\n            else                                        // format:    a\r\n            {\r\n                is.putback(ch);\r\n                \r\n                is >> a;                                    // we extract the first component\r\n                \r\n                if    (!is.good())    goto finish;\r\n                \r\n                q = quaternion<T>(a);\r\n            }\r\n            \r\n            finish:\r\n            return(is);\r\n        }\r\n        \r\n        \r\n        template<typename T, typename charT, class traits>\r\n        ::std::basic_ostream<charT,traits> &    operator << (    ::std::basic_ostream<charT,traits> & os,\r\n                                                                quaternion<T> const & q)\r\n        {\r\n            ::std::basic_ostringstream<charT,traits>    s;\r\n\r\n            s.flags(os.flags());\r\n#ifdef    BOOST_NO_STD_LOCALE\r\n#else\r\n            s.imbue(os.getloc());\r\n#endif /* BOOST_NO_STD_LOCALE */\r\n            s.precision(os.precision());\r\n            \r\n            s << '('    << q.R_component_1() << ','\r\n                        << q.R_component_2() << ','\r\n                        << q.R_component_3() << ','\r\n                        << q.R_component_4() << ')';\r\n            \r\n            return os << s.str();\r\n        }\r\n        \r\n        \r\n        // values\r\n        \r\n        template<typename T>\r\n        inline BOOST_CONSTEXPR T real(quaternion<T> const & q)\r\n        {\r\n            return(q.real());\r\n        }\r\n        \r\n        \r\n        template<typename T>\r\n        inline BOOST_CONSTEXPR quaternion<T> unreal(quaternion<T> const & q)\r\n        {\r\n            return(q.unreal());\r\n        }\r\n                \r\n        template<typename T>\r\n        inline T sup(quaternion<T> const & q)\r\n        {\r\n            using    ::std::abs;\r\n            return (std::max)((std::max)(abs(q.R_component_1()), abs(q.R_component_2())), (std::max)(abs(q.R_component_3()), abs(q.R_component_4())));\r\n        }\r\n        \r\n        \r\n        template<typename T>\r\n        inline T l1(quaternion<T> const & q)\r\n        {\r\n           using    ::std::abs;\r\n           return abs(q.R_component_1()) + abs(q.R_component_2()) + abs(q.R_component_3()) + abs(q.R_component_4());\r\n        }\r\n        \r\n        \r\n        template<typename T>\r\n        inline T abs(quaternion<T> const & q)\r\n        {\r\n            using    ::std::abs;\r\n            using    ::std::sqrt;\r\n            \r\n            T            maxim = sup(q);    // overflow protection\r\n            \r\n            if    (maxim == static_cast<T>(0))\r\n            {\r\n                return(maxim);\r\n            }\r\n            else\r\n            {\r\n                T    mixam = static_cast<T>(1)/maxim;    // prefer multiplications over divisions\r\n                \r\n                T a = q.R_component_1() * mixam;\r\n                T b = q.R_component_2() * mixam;\r\n                T c = q.R_component_3() * mixam;\r\n                T d = q.R_component_4() * mixam;\r\n\r\n                a *= a;\r\n                b *= b;\r\n                c *= c;\r\n                d *= d;\r\n                \r\n                return(maxim * sqrt(a + b + c + d));\r\n            }\r\n            \r\n            //return(sqrt(norm(q)));\r\n        }\r\n        \r\n        \r\n        // Note:    This is the Cayley norm, not the Euclidean norm...\r\n        \r\n        template<typename T>\r\n        inline BOOST_CXX14_CONSTEXPR T norm(quaternion<T>const  & q)\r\n        {\r\n            return(real(q*conj(q)));\r\n        }\r\n        \r\n        \r\n        template<typename T>\r\n        inline BOOST_CONSTEXPR quaternion<T> conj(quaternion<T> const & q)\r\n        {\r\n            return(quaternion<T>(   +q.R_component_1(),\r\n                                    -q.R_component_2(),\r\n                                    -q.R_component_3(),\r\n                                    -q.R_component_4()));\r\n        }\r\n        \r\n        \r\n        template<typename T>\r\n        inline quaternion<T>                    spherical(  T const & rho,\r\n                                                            T const & theta,\r\n                                                            T const & phi1,\r\n                                                            T const & phi2)\r\n        {\r\n            using ::std::cos;\r\n            using ::std::sin;\r\n            \r\n            //T    a = cos(theta)*cos(phi1)*cos(phi2);\r\n            //T    b = sin(theta)*cos(phi1)*cos(phi2);\r\n            //T    c = sin(phi1)*cos(phi2);\r\n            //T    d = sin(phi2);\r\n            \r\n            T    courrant = static_cast<T>(1);\r\n            \r\n            T    d = sin(phi2);\r\n            \r\n            courrant *= cos(phi2);\r\n            \r\n            T    c = sin(phi1)*courrant;\r\n            \r\n            courrant *= cos(phi1);\r\n            \r\n            T    b = sin(theta)*courrant;\r\n            T    a = cos(theta)*courrant;\r\n            \r\n            return(rho*quaternion<T>(a,b,c,d));\r\n        }\r\n        \r\n        \r\n        template<typename T>\r\n        inline quaternion<T>                    semipolar(  T const & rho,\r\n                                                            T const & alpha,\r\n                                                            T const & theta1,\r\n                                                            T const & theta2)\r\n        {\r\n            using ::std::cos;\r\n            using ::std::sin;\r\n            \r\n            T    a = cos(alpha)*cos(theta1);\r\n            T    b = cos(alpha)*sin(theta1);\r\n            T    c = sin(alpha)*cos(theta2);\r\n            T    d = sin(alpha)*sin(theta2);\r\n            \r\n            return(rho*quaternion<T>(a,b,c,d));\r\n        }\r\n        \r\n        \r\n        template<typename T>\r\n        inline quaternion<T>                    multipolar( T const & rho1,\r\n                                                            T const & theta1,\r\n                                                            T const & rho2,\r\n                                                            T const & theta2)\r\n        {\r\n            using ::std::cos;\r\n            using ::std::sin;\r\n            \r\n            T    a = rho1*cos(theta1);\r\n            T    b = rho1*sin(theta1);\r\n            T    c = rho2*cos(theta2);\r\n            T    d = rho2*sin(theta2);\r\n            \r\n            return(quaternion<T>(a,b,c,d));\r\n        }\r\n        \r\n        \r\n        template<typename T>\r\n        inline quaternion<T>                    cylindrospherical(  T const & t,\r\n                                                                    T const & radius,\r\n                                                                    T const & longitude,\r\n                                                                    T const & latitude)\r\n        {\r\n            using ::std::cos;\r\n            using ::std::sin;\r\n            \r\n            \r\n            \r\n            T    b = radius*cos(longitude)*cos(latitude);\r\n            T    c = radius*sin(longitude)*cos(latitude);\r\n            T    d = radius*sin(latitude);\r\n            \r\n            return(quaternion<T>(t,b,c,d));\r\n        }\r\n        \r\n        \r\n        template<typename T>\r\n        inline quaternion<T>                    cylindrical(T const & r,\r\n                                                            T const & angle,\r\n                                                            T const & h1,\r\n                                                            T const & h2)\r\n        {\r\n            using ::std::cos;\r\n            using ::std::sin;\r\n            \r\n            T    a = r*cos(angle);\r\n            T    b = r*sin(angle);\r\n            \r\n            return(quaternion<T>(a,b,h1,h2));\r\n        }\r\n        \r\n        \r\n        // transcendentals\r\n        // (please see the documentation)\r\n        \r\n        \r\n        template<typename T>\r\n        inline quaternion<T>                    exp(quaternion<T> const & q)\r\n        {\r\n            using    ::std::exp;\r\n            using    ::std::cos;\r\n            \r\n            using    ::boost::math::sinc_pi;\r\n            \r\n            T    u = exp(real(q));\r\n            \r\n            T    z = abs(unreal(q));\r\n            \r\n            T    w = sinc_pi(z);\r\n            \r\n            return(u*quaternion<T>(cos(z),\r\n                w*q.R_component_2(), w*q.R_component_3(),\r\n                w*q.R_component_4()));\r\n        }\r\n        \r\n        \r\n        template<typename T>\r\n        inline quaternion<T>                    cos(quaternion<T> const & q)\r\n        {\r\n            using    ::std::sin;\r\n            using    ::std::cos;\r\n            using    ::std::cosh;\r\n            \r\n            using    ::boost::math::sinhc_pi;\r\n            \r\n            T    z = abs(unreal(q));\r\n            \r\n            T    w = -sin(q.real())*sinhc_pi(z);\r\n            \r\n            return(quaternion<T>(cos(q.real())*cosh(z),\r\n                w*q.R_component_2(), w*q.R_component_3(),\r\n                w*q.R_component_4()));\r\n        }\r\n        \r\n        \r\n        template<typename T>\r\n        inline quaternion<T>                    sin(quaternion<T> const & q)\r\n        {\r\n            using    ::std::sin;\r\n            using    ::std::cos;\r\n            using    ::std::cosh;\r\n            \r\n            using    ::boost::math::sinhc_pi;\r\n            \r\n            T    z = abs(unreal(q));\r\n            \r\n            T    w = +cos(q.real())*sinhc_pi(z);\r\n            \r\n            return(quaternion<T>(sin(q.real())*cosh(z),\r\n                w*q.R_component_2(), w*q.R_component_3(),\r\n                w*q.R_component_4()));\r\n        }\r\n        \r\n        \r\n        template<typename T>\r\n        inline quaternion<T>                    tan(quaternion<T> const & q)\r\n        {\r\n            return(sin(q)/cos(q));\r\n        }\r\n        \r\n        \r\n        template<typename T>\r\n        inline quaternion<T>                    cosh(quaternion<T> const & q)\r\n        {\r\n            return((exp(+q)+exp(-q))/static_cast<T>(2));\r\n        }\r\n        \r\n        \r\n        template<typename T>\r\n        inline quaternion<T>                    sinh(quaternion<T> const & q)\r\n        {\r\n            return((exp(+q)-exp(-q))/static_cast<T>(2));\r\n        }\r\n        \r\n        \r\n        template<typename T>\r\n        inline quaternion<T>                    tanh(quaternion<T> const & q)\r\n        {\r\n            return(sinh(q)/cosh(q));\r\n        }\r\n        \r\n        \r\n        template<typename T>\r\n        quaternion<T>                            pow(quaternion<T> const & q,\r\n                                                    int n)\r\n        {\r\n            if        (n > 1)\r\n            {\r\n                int    m = n>>1;\r\n                \r\n                quaternion<T>    result = pow(q, m);\r\n                \r\n                result *= result;\r\n                \r\n                if    (n != (m<<1))\r\n                {\r\n                    result *= q; // n odd\r\n                }\r\n                \r\n                return(result);\r\n            }\r\n            else if    (n == 1)\r\n            {\r\n                return(q);\r\n            }\r\n            else if    (n == 0)\r\n            {\r\n                return(quaternion<T>(static_cast<T>(1)));\r\n            }\r\n            else    /* n < 0 */\r\n            {\r\n                return(pow(quaternion<T>(static_cast<T>(1))/q,-n));\r\n            }\r\n        }\r\n    }\r\n}\r\n\r\n#endif /* BOOST_QUATERNION_HPP */\r\n", "meta": {"hexsha": "c83b62466719e8f9ef8ed33b69f947cd97ccbe2a", "size": 50386, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "deps/boost/include/boost/math/quaternion.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/quaternion.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/quaternion.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": 40.1482071713, "max_line_length": 221, "alphanum_fraction": 0.4182907951, "num_tokens": 10627, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6001883735630722, "lm_q2_score": 0.5312093733737563, "lm_q1q2_score": 0.31882568982665355}}
{"text": "#pragma once\n\n#include <Eigen/Core>\n#include <autodiff/autodiff_types.hpp>\n\n/**\n * @namespace ipc::rigid:\n * @brief\n */\nnamespace ipc::rigid {\n\ntemplate <typename T> using Vector2T = Eigen::Matrix<T, 2, 1>;\n\n/**\n * @brief Given toi returns the position \\f$\\alpha\\f$ along the\n * \\f$edge_{ij}\\f$ where the impact between vertex \\f$k\\f$ and\n * \\f$edge_{ij}\\f$  takes place.\n *\n *   @param[in]   V_{i,j,k}       : vertex positions\n *   @param[in]   U_{i,j,k}       : vertex displacements\n *   @param[in]   toi             : time of impact\n *\n *   @param[out]  alpha          : position along the \\f$edge_{ij}\\f$ where\n * the impact takes place\n *\n * @return true if a valid \\f$\\alpha\\f$ exists.\n */\ntemplate <typename T>\nbool temporal_parameterization_to_spatial(\n    const Eigen::Vector2d& Vi,\n    const Eigen::Vector2d& Vj,\n    const Eigen::Vector2d& Vk,\n    const Vector2T<T>& Ui,\n    const Vector2T<T>& Uj,\n    const Vector2T<T>& Uk,\n    const T& toi,\n    T& alpha);\n\n/**\n * Computes the time of impact between an \\f$edge_{ij}\\f$ and vertex \\f$k\\f$\n *\n *   @param[in]   V_{i,j,k}       : vertex positions\n *   @param[in]   U_{i,j,k}       : vertex displacements\n *\n *   @param[out]  toi             : time of FIRST impact\n *\n * @return true if an impact happens at time \\f$ t \\in [0, 1]\\f$\n */\ntemplate <typename T>\nbool compute_edge_vertex_time_of_impact(\n    const Eigen::Vector2d& Vi,\n    const Eigen::Vector2d& Vj,\n    const Eigen::Vector2d& Vk,\n    const Vector2T<T>& Ui,\n    const Vector2T<T>& Uj,\n    const Vector2T<T>& Uk,\n    T& toi,\n    T& alpha);\n\ntemplate <typename T>\nbool compute_edge_vertex_time_of_impact(\n    const Eigen::Vector2d& Vi,\n    const Eigen::Vector2d& Vj,\n    const Eigen::Vector2d& Vk,\n    const Vector2T<T>& Ui,\n    const Vector2T<T>& Uj,\n    const Vector2T<T>& Uk,\n    T& toi)\n{\n    T alpha;\n    return compute_edge_vertex_time_of_impact(\n        Vi, Vj, Vk, Ui, Uj, Uk, toi, alpha);\n}\n\n} // namespace ipc::rigid\n\n#include \"edge_vertex_ccd.tpp\"\n", "meta": {"hexsha": "c6454f3c1ddf309e4be4080dbd3d15480fe206bb", "size": 1977, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/ccd/linear/edge_vertex_ccd.hpp", "max_stars_repo_name": "ipc-sim/rigid-ipc", "max_stars_repo_head_hexsha": "d839af457236e7363b14c2e482a01d8160fa447e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 71.0, "max_stars_repo_stars_event_min_datetime": "2021-09-08T13:16:43.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-27T10:23:33.000Z", "max_issues_repo_path": "src/ccd/linear/edge_vertex_ccd.hpp", "max_issues_repo_name": "ipc-sim/rigid-ipc", "max_issues_repo_head_hexsha": "d839af457236e7363b14c2e482a01d8160fa447e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2021-09-08T00:16:20.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-05T17:44:08.000Z", "max_forks_repo_path": "src/ccd/linear/edge_vertex_ccd.hpp", "max_forks_repo_name": "ipc-sim/rigid-ipc", "max_forks_repo_head_hexsha": "d839af457236e7363b14c2e482a01d8160fa447e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-09-18T15:15:38.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-21T15:15:38.000Z", "avg_line_length": 25.3461538462, "max_line_length": 76, "alphanum_fraction": 0.6211431462, "num_tokens": 616, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.600188359260205, "lm_q2_score": 0.5312093733737563, "lm_q1q2_score": 0.3188256822288364}}
{"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#include <boost/unordered_set.hpp>\n#include <graphlab.hpp>\n#include <graphlab/macros_def.hpp>\n#include \"../../src/graphlab/util/timer.hpp\"\n/**\n *\n * In this program we implement the \"k-core\" decomposition algorithm.\n * We use a parallel variant of\n * \n * V. Batagelj and M. Zaversnik, An O(m) algorithm for cores\n * decomposition of networks,\n *\n *  - Essentially, recursively remove everything with degree 1\n *  - Then recursively remove everything with degree 2\n *  - etc.\n */\n\n/*\n * Each vertex maintains a \"degree\" count. If this value\n * is 0, the vertex is \"deleted\"\n */\ntypedef int vertex_data_type;\n\n/*\n * Don't need any edges\n */\ntypedef graphlab::empty edge_data_type;\n\n/*\n * Define the type of the graph\n */\ntypedef graphlab::distributed_graph<vertex_data_type,\n                                    edge_data_type> graph_type;\n\n// The current K to compute\nsize_t CURRENT_K;\n\n\nsize_t ITERATIONS = 0;\n\n/*\n * The core K-core implementation.\n * The basic concept is simple.\n * Each vertex maintains a count of the number of adjacent edges.\n * If a vertex receives a message, the message contains the number of\n * adjacent edges deleted. The vertex then updates its counter.\n * If the counter falls below K, it deletes itself\n * (set the adjacent count to 0) and signals each of its neighbors\n * with a message of 1.\n */\nclass k_core :\n  public graphlab::ivertex_program<graph_type,\n                                   graphlab::empty, // gathers are integral\n                                   int>,   // messages are integral\n  public graphlab::IS_POD_TYPE  {\npublic:\n  // the last received message\n  int msg;\n  \n  /* Each vertex can only signal once. I set this flag\n   * if it is the first time this vertex falls below K, so I can\n   * initiate scattering\n   */\n  bool just_deleted;\n  \n  k_core():msg(0),just_deleted(false) { }\n\n  /* The message contains the number of adjacent edges deleted.\n   * Store the message in the program, and reset the just_deleted flag\n   */\n  void init(icontext_type& context, const vertex_type& vertex,\n            const message_type& message) {\n    msg = message;\n    just_deleted = false;\n  }\n\n  // gather is never invoked\n  edge_dir_type gather_edges(icontext_type& context,\n                             const vertex_type& vertex) const {\n    return graphlab::NO_EDGES;\n  }\n\n  /* On apply, if the vertex has not yet been deleted,\n   * decrement the counter on the vertex.\n   * If the adjacency count of the vertex falls below K,\n   * the vertex shall be deleted.\n   * We set the vertex data to 0 to designate that it is deleted\n   * and Set the just_deleted flag to signal the neighbors in scatter\n   */\n  void apply(icontext_type& context, vertex_type& vertex,\n             const gather_type& unused) {\n    if (vertex.data() > 0) {\n      vertex.data() -= msg;\n      if (vertex.data() < CURRENT_K) {\n        just_deleted = true;\n        vertex.data() = 0;\n      }\n    }\n  } \n\n  /*\n   * If the vertex is deleted, we signal all neighbors on the scatter\n   */\n  edge_dir_type scatter_edges(icontext_type& context,\n                              const vertex_type& vertex) const {\n    return just_deleted ?\n      graphlab::ALL_EDGES : graphlab::NO_EDGES;\n  }\n\n  /*\n   * For each neighboring vertex, if it is not yet deleted,\n   * signal it.\n   */\n  void scatter(icontext_type& context,\n               const vertex_type& vertex,\n               edge_type& edge) const {\n    vertex_type other = edge.source().id() == vertex.id() ?\n      edge.target() : edge.source();\n    if (other.data() > 0) {\n      context.signal(other, 1);\n    }\n  }\n  \n};\n\n// type of the synchronous_engine\ntypedef graphlab::synchronous_engine<k_core> engine_type;\n\n/*\n * Called before any graph operation is performed.\n * Initializes all vertex data to the number of adjacent edges.\n * Can be called from a graph.transform_vertices()\n */\nvoid initialize_vertex_values(graph_type::vertex_type& v) {\n  v.data() = v.num_in_edges() + v.num_out_edges();\n}\n\n/*\n * Signals all non-deleted vertices with degree less than K.\n * Can be called from an engine.map_reduce_vertices()\n * We return empty since no reduction is performed. Only the map.\n */\ngraphlab::empty signal_vertices_at_k(engine_type::icontext_type& ctx,\n                                     const graph_type::vertex_type& vertex) {\n  if (vertex.data() > 0 && vertex.data() < CURRENT_K) {\n    ctx.signal(vertex, 0);\n  }\n  return graphlab::empty();\n}\n\n/*\n * Counts the number of un-deleted vertices.\n */\nsize_t count_active_vertices(const graph_type::vertex_type& vertex) {\n  return vertex.data() > 0;\n}\n\n/*\n * Counts the degree of each un-deleted vertex. Half of this\n * will be the size of the K-core graph.\n */\nsize_t double_count_active_edges(const graph_type::vertex_type& vertex) {\n  return (size_t) vertex.data();\n}\n\n\n\n/*\n * Saves the graph in a tsv format with the condition that\n * the adjacent vertices have not yet been deleted.\n * This allows saving of the k-core graph.\n */\nstruct save_core_at_k {\n  std::string save_vertex(graph_type::vertex_type) { return \"\"; }\n  std::string save_edge(graph_type::edge_type e) {\n    if (e.source().data() > 0 && e.target().data() > 0) {\n      return graphlab::tostr(e.source().id()) + \"\\t\" +\n        graphlab::tostr(e.target().id()) + \"\\n\";\n    }\n    else return \"\";\n  }\n};\n    \nint main(int argc, char** argv) {\n  std::cout << \"Computes a k-core decomposition of a graph.\\n\\n\";\n\n  graphlab::command_line_options clopts\n    (\"K-Core decomposition. This program \"\n     \"computes the K-Core decomposition of a graph, for K ranging from [kmin] \"\n     \"to [kmax]. The size of the remaining K-core graph at each K is printed. \"\n     \"The [savecores] allow the saving of each K-Core graph in a TSV format\"\n     );\n  std::string prefix, format;\n  size_t kmin = 0;\n  size_t kmax = (size_t)(-1);\n  std::string savecores;\n  clopts.attach_option(\"graph\", prefix,\n                       \"Graph input. reads all graphs matching prefix*\");\n  clopts.attach_option(\"format\", format,\n                       \"The graph format\");\n  clopts.attach_option(\"kmin\", kmin,\n                       \"Compute the k-Core for k the range [kmin,kmax]\");\n  clopts.attach_option(\"kmax\", kmax,\n                       \"Compute the k-Core for k the range [kmin,kmax]\");\n  clopts.attach_option(\"savecores\", savecores,\n                       \"If non-empty, will save tsv of each core with prefix [savecores].K.\");\n\tclopts.attach_option(\"iterations\", ITERATIONS,\n                       \"If set, will force the use of the synchronous engine\"\n                       \"overriding any engine option set by the --engine parameter. \"\n                       \"Runs complete (non-dynamic) PageRank for a fixed \"\n                       \"number of iterations. Also overrides the iterations \"\n                       \"option in the engine\");\n\tsize_t powerlaw = 0;\n  clopts.attach_option(\"powerlaw\", powerlaw,\n                       \"Generate a synthetic powerlaw degree graph. \");\n  double alpha = 2.1, beta = 2.2;\n  clopts.attach_option(\"alpha\", alpha,\n                         \"Power-law constant for indegree \");\n  clopts.attach_option(\"beta\", beta,\n                         \"Power-law constant for outdegree \");\n  std::string result_file;\n  clopts.attach_option(\"result_file\", result_file,\n                       \"If set, will save the test result to the\"\n                       \"specific file\");\n\n  if(!clopts.parse(argc, argv)) return EXIT_FAILURE;\n  if (kmax < kmin) {\n    std::cout << \"kmax must be at least as large as kmin\\n\";\n    clopts.print_description();\n    return EXIT_FAILURE;\n  }\n  \n  // Initialize control plane using mpi\n  graphlab::mpi_tools::init(argc, argv);\n  graphlab::distributed_control dc;\n  \n  if (ITERATIONS) {\n    // make sure this is the synchronous engine\n    dc.cout() << \"--iterations set. Forcing Synchronous engine, and running \"\n              << \"for \" << ITERATIONS << \" iterations.\" << std::endl;\n    //clopts.get_engine_args().set_option(\"type\", \"synchronous\");\n    clopts.get_engine_args().set_option(\"max_iterations\", ITERATIONS);\n    clopts.get_engine_args().set_option(\"sched_allv\", true);\n  }\n  \n  int ntrials = 20;\n  int trial_results1[20];\n  double trial_results2[20][8];\n  uint32_t seed_set[20] = {1492133106, 680965948, 2040586311, 73972395, 942196338, 819390547, 1643934785, 1707678784, 401305863, 1051761031, 956889080, 1387946621, 1523349375, 1620677309, 592759340, 1459650384, 1406812251, 349206043, 255545576, 1070228652};\n  for(int i = 0; i < ntrials; i++)\n  {\n  \n\t\t// random seed\n\t\t// dc.cout() << seed_set[i] << std::endl;\n\t\tclopts.get_graph_args().set_option(\"seed\", seed_set[i]);\n  \n\t  // load graph\n\t  graph_type graph(dc, clopts);\n\t  \n\t  if(powerlaw > 0) { // make a synthetic graph\n\t\t  dc.cout() << \"Loading synthetic Powerlaw graph.\" << std::endl;\n\t\t  graph.load_synthetic_powerlaw(powerlaw, alpha, beta, 100000000);\n\t\t}\n\t\telse if (prefix.length() > 0) { // Load the graph from a file\n\t\t\tif(dc.procid() == 24)\n\t\t  std::cout << \"Loading graph in format: \"<< format << std::endl;\n\t\t  graph.load_format(prefix, format);\n\t\t}\n\t\telse {\n\t\t  dc.cout() << \"graph or powerlaw option must be specified\" << std::endl;\n\t\t  clopts.print_description();\n\t\t  return 0;\n\t\t}\n\n\t  graphlab::timer timer;\n\t  timer.start();\n\t  graph.finalize();\n\t  const double ingress_time = timer.current_time();\n\t  dc.cout() << \"Finalizing graph. Finished in \"\n\t\t  << ingress_time << std::endl;\n\t  dc.cout() << \"Number of vertices: \" << graph.num_vertices() << std::endl\n\t\t\t\t<< \"Number of edges:    \" << graph.num_edges() << std::endl;\n\n\t  timer.start();\n\t  graphlab::synchronous_engine<k_core> engine(dc, graph, clopts);\n\n\t  // initialize the vertex data with the degree\n\t  graph.transform_vertices(initialize_vertex_values);\n\n\t  // for each K value\n\t  for (CURRENT_K = kmin; CURRENT_K <= kmax; CURRENT_K++) {\n\t\t// signal all vertices with degree less than K\n\t\tengine.map_reduce_vertices<graphlab::empty>(signal_vertices_at_k);\n\t\t// recursively delete all vertices with degree less than K\n\t\tengine.start();\n\t\t// count the number of vertices and edges remaining\n\t\tsize_t numv = graph.map_reduce_vertices<size_t>(count_active_vertices);\n\t\tsize_t nume = graph.map_reduce_vertices<size_t>(double_count_active_edges) / 2;\n\t\tif (numv == 0) break;\n\t\t// Output the size of the graph\n\t\tdc.cout() << \"K=\" << CURRENT_K << \":  #V = \"\n\t\t\t\t  << numv << \"   #E = \" << nume << std::endl;\n\n\t\t// Saves the result if requested\n\t\tif (savecores != \"\") {\n\t\t  graph.save(savecores + \".\" + graphlab::tostr(CURRENT_K) + \".\",\n\t\t\t\t\t save_core_at_k(),\n\t\t\t\t\t false, /* no compression */ \n\t\t\t\t\t false, /* do not save vertex */\n\t\t\t\t\t true, /* save edge */ \n\t\t\t\t\t clopts.get_ncpus()); /* one file per machine */\n\t\t}\n\t  }\n\t  const double runtime = timer.current_time();\n\n\t  if(dc.procid() == 0) {\n          std::cout << graph.num_replicas() << \"\\t\"\n                    << (double)graph.num_replicas()/graph.num_vertices() << \"\\t\"\n                    << graph.get_edge_balance() << \"\\t\"\n                    << graph.get_vertex_balance() << \"\\t\"\n                    << ingress_time << \"\\t\"\n\t\t\t\t\t<< runtime << \"\\t\"\n                    << engine.get_exec_time() << \"\\t\"\n                    << engine.get_one_itr_time() << \"\\t\"\n                    << engine.get_compute_balance() << \"\\t\"\n                    << std::endl;\n          trial_results1[i] = graph.num_replicas();\n          trial_results2[i][0] = (double)graph.num_replicas()/graph.num_vertices();\n          trial_results2[i][1] = graph.get_edge_balance();\n          trial_results2[i][2] = graph.get_vertex_balance() ;\n          trial_results2[i][3] = ingress_time;\n          trial_results2[i][4] = runtime;\n          trial_results2[i][5] = engine.get_exec_time();\n          trial_results2[i][6] = engine.get_one_itr_time();\n          trial_results2[i][7] = engine.get_compute_balance();\n\n          if(result_file != \"\") {\n              std::cout << \"saving the result to \" << result_file << std::endl;\n              std::ofstream fout(result_file.c_str(), std::ios::app);\n              if(powerlaw > 0) {\n                  fout << \"powerlaw synthetic: \" << powerlaw << \"\\t\"\n                      << alpha << \"\\t\" << beta << \"\\t\" << dc.numprocs() << std::endl;\n              }\n              else {\n                  fout << \"real-world graph: \" << prefix << \"\\t\"\n                      << graph.num_vertices() << \"\\t\" << graph.num_edges()\n                      << \"\\t\" << dc.numprocs() << std::endl;\n              }\n              std::string ingress_method = \"\";\n              clopts.get_graph_args().get_option(\"ingress\", ingress_method);\n              fout << ingress_method << \"\\t\";\n              fout << graph.num_replicas() << \"\\t\"\n                  << (double)graph.num_replicas()/graph.num_vertices() << \"\\t\"\n                  << graph.get_edge_balance() << \"\\t\"\n                  << graph.get_vertex_balance() << \"\\t\"\n                  << ingress_time << \"\\t\"\n\t\t\t\t  << runtime << \"\\t\"\n                  << engine.get_exec_time() << \"\\t\"\n                  << engine.get_one_itr_time() << \"\\t\"\n                  << engine.get_compute_balance() << \"\\t\"\n                  << std::endl;\n              fout.close();\n          }\n      }\n  \n  }\n  \n  graphlab::mpi_tools::finalize();\n  return EXIT_SUCCESS;\n} // End of main\n\n", "meta": {"hexsha": "e9de336a821d47d7a880e97682be76641e0704bf", "size": 13973, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "toolkits/graph_analytics/kcore.cpp", "max_stars_repo_name": "xcgoner/powerlore", "max_stars_repo_head_hexsha": "c95ab1ca5a3636eaf5fb9c4feeaddcb96bb2d6ee", "max_stars_repo_licenses": ["ECL-2.0", "Apache-2.0"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2019-02-20T07:41:57.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-29T00:52:29.000Z", "max_issues_repo_path": "toolkits/graph_analytics/kcore.cpp", "max_issues_repo_name": "xcgoner/powerlore", "max_issues_repo_head_hexsha": "c95ab1ca5a3636eaf5fb9c4feeaddcb96bb2d6ee", "max_issues_repo_licenses": ["ECL-2.0", "Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "toolkits/graph_analytics/kcore.cpp", "max_forks_repo_name": "xcgoner/powerlore", "max_forks_repo_head_hexsha": "c95ab1ca5a3636eaf5fb9c4feeaddcb96bb2d6ee", "max_forks_repo_licenses": ["ECL-2.0", "Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-05-27T12:40:52.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-27T12:40:52.000Z", "avg_line_length": 35.3746835443, "max_line_length": 257, "alphanum_fraction": 0.6154011308, "num_tokens": 3449, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5312093733737562, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.31882568222883634}}
{"text": "//  Copyright Benjamin Sobotta 2012\n\n//  Use, modification and distribution are subject to the\n//  Boost Software License, Version 1.0. (See accompanying file\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n#ifndef BOOST_STATS_SKEW_NORMAL_HPP\n#define BOOST_STATS_SKEW_NORMAL_HPP\n\n// http://en.wikipedia.org/wiki/Skew_normal_distribution\n// http://azzalini.stat.unipd.it/SN/\n// Also:\n// Azzalini, A. (1985). \"A class of distributions which includes the normal ones\".\n// Scand. J. Statist. 12: 171-178.\n\n#include <boost/math/distributions/fwd.hpp> // TODO add skew_normal distribution to fwd.hpp!\n#include <boost/math/special_functions/owens_t.hpp> // Owen's T function\n#include <boost/math/distributions/complement.hpp>\n#include <boost/math/distributions/normal.hpp>\n#include <boost/math/distributions/detail/common_error_handling.hpp>\n#include <boost/math/constants/constants.hpp>\n#include <boost/math/tools/tuple.hpp>\n#include <boost/math/tools/roots.hpp> // Newton-Raphson\n#include <boost/assert.hpp>\n#include <boost/math/distributions/detail/generic_mode.hpp> // pdf max finder.\n\n#include <utility>\n#include <algorithm> // std::lower_bound, std::distance\n\nnamespace boost{ namespace math{\n\n  namespace detail\n  {\n    template <class RealType, class Policy>\n    inline bool check_skew_normal_shape(\n      const char* function,\n      RealType shape,\n      RealType* result,\n      const Policy& pol)\n    {\n      if(!(boost::math::isfinite)(shape))\n      {\n        *result =\n          policies::raise_domain_error<RealType>(function,\n          \"Shape parameter is %1%, but must be finite!\",\n          shape, pol);\n        return false;\n      }\n      return true;\n    }\n\n  } // namespace detail\n\n  template <class RealType = double, class Policy = policies::policy<> >\n  class skew_normal_distribution\n  {\n  public:\n    typedef RealType value_type;\n    typedef Policy policy_type;\n\n    skew_normal_distribution(RealType l_location = 0, RealType l_scale = 1, RealType l_shape = 0)\n      : location_(l_location), scale_(l_scale), shape_(l_shape)\n    { // Default is a 'standard' normal distribution N01. (shape=0 results in the normal distribution with no skew)\n      static const char* function = \"boost::math::skew_normal_distribution<%1%>::skew_normal_distribution\";\n\n      RealType result;\n      detail::check_scale(function, l_scale, &result, Policy());\n      detail::check_location(function, l_location, &result, Policy());\n      detail::check_skew_normal_shape(function, l_shape, &result, Policy());\n    }\n\n    RealType location()const\n    { \n      return location_;\n    }\n\n    RealType scale()const\n    { \n      return scale_;\n    }\n\n    RealType shape()const\n    { \n      return shape_;\n    }\n\n\n  private:\n    //\n    // Data members:\n    //\n    RealType location_;  // distribution location.\n    RealType scale_;    // distribution scale.\n    RealType shape_;    // distribution shape.\n  }; // class skew_normal_distribution\n\n  typedef skew_normal_distribution<double> skew_normal;\n\n  template <class RealType, class Policy>\n  inline const std::pair<RealType, RealType> range(const skew_normal_distribution<RealType, Policy>& /*dist*/)\n  { // Range of permissible values for random variable x.\n    using boost::math::tools::max_value;\n    return std::pair<RealType, RealType>(\n       std::numeric_limits<RealType>::has_infinity ? -std::numeric_limits<RealType>::infinity() : -max_value<RealType>(), \n       std::numeric_limits<RealType>::has_infinity ? std::numeric_limits<RealType>::infinity() : max_value<RealType>()); // - to + max value.\n  }\n\n  template <class RealType, class Policy>\n  inline const std::pair<RealType, RealType> support(const skew_normal_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\n    using boost::math::tools::max_value;\n    return std::pair<RealType, RealType>(-max_value<RealType>(),  max_value<RealType>()); // - to + max value.\n  }\n\n  template <class RealType, class Policy>\n  inline RealType pdf(const skew_normal_distribution<RealType, Policy>& dist, const RealType& x)\n  {\n    const RealType scale = dist.scale();\n    const RealType location = dist.location();\n    const RealType shape = dist.shape();\n\n    static const char* function = \"boost::math::pdf(const skew_normal_distribution<%1%>&, %1%)\";\n\n    RealType result = 0;\n    if(false == detail::check_scale(function, scale, &result, Policy()))\n    {\n      return result;\n    }\n    if(false == detail::check_location(function, location, &result, Policy()))\n    {\n      return result;\n    }\n    if(false == detail::check_skew_normal_shape(function, shape, &result, Policy()))\n    {\n      return result;\n    }\n    if((boost::math::isinf)(x))\n    {\n       return 0; // pdf + and - infinity is zero.\n    }\n    // Below produces MSVC 4127 warnings, so the above used instead.\n    //if(std::numeric_limits<RealType>::has_infinity && abs(x) == std::numeric_limits<RealType>::infinity())\n    //{ // pdf + and - infinity is zero.\n    //  return 0;\n    //}\n    if(false == detail::check_x(function, x, &result, Policy()))\n    {\n      return result;\n    }\n\n    const RealType transformed_x = (x-location)/scale;\n\n    normal_distribution<RealType, Policy> std_normal;\n\n    result = pdf(std_normal, transformed_x) * cdf(std_normal, shape*transformed_x) * 2 / scale;\n\n    return result;\n  } // pdf\n\n  template <class RealType, class Policy>\n  inline RealType cdf(const skew_normal_distribution<RealType, Policy>& dist, const RealType& x)\n  {\n    const RealType scale = dist.scale();\n    const RealType location = dist.location();\n    const RealType shape = dist.shape();\n\n    static const char* function = \"boost::math::cdf(const skew_normal_distribution<%1%>&, %1%)\";\n    RealType result = 0;\n    if(false == detail::check_scale(function, scale, &result, Policy()))\n    {\n      return result;\n    }\n    if(false == detail::check_location(function, location, &result, Policy()))\n    {\n      return result;\n    }\n    if(false == detail::check_skew_normal_shape(function, shape, &result, Policy()))\n    {\n      return result;\n    }\n    if((boost::math::isinf)(x))\n    {\n      if(x < 0) return 0; // -infinity\n      return 1; // + infinity\n    }\n    // These produce MSVC 4127 warnings, so the above used instead.\n    //if(std::numeric_limits<RealType>::has_infinity && x == std::numeric_limits<RealType>::infinity())\n    //{ // cdf +infinity is unity.\n    //  return 1;\n    //}\n    //if(std::numeric_limits<RealType>::has_infinity && x == -std::numeric_limits<RealType>::infinity())\n    //{ // cdf -infinity is zero.\n    //  return 0;\n    //}\n    if(false == detail::check_x(function, x, &result, Policy()))\n    {\n      return result;\n    }\n\n    const RealType transformed_x = (x-location)/scale;\n\n    normal_distribution<RealType, Policy> std_normal;\n\n    result = cdf(std_normal, transformed_x) - owens_t(transformed_x, shape)*static_cast<RealType>(2);\n\n    return result;\n  } // cdf\n\n  template <class RealType, class Policy>\n  inline RealType cdf(const complemented2_type<skew_normal_distribution<RealType, Policy>, RealType>& c)\n  {\n    const RealType scale = c.dist.scale();\n    const RealType location = c.dist.location();\n    const RealType shape = c.dist.shape();\n    const RealType x = c.param;\n\n    static const char* function = \"boost::math::cdf(const complement(skew_normal_distribution<%1%>&), %1%)\";\n\n    if((boost::math::isinf)(x))\n    {\n      if(x < 0) return 1; // cdf complement -infinity is unity.\n      return 0; // cdf complement +infinity is zero\n    }\n    // These produce MSVC 4127 warnings, so the above used instead.\n    //if(std::numeric_limits<RealType>::has_infinity && x == std::numeric_limits<RealType>::infinity())\n    //{ // cdf complement +infinity is zero.\n    //  return 0;\n    //}\n    //if(std::numeric_limits<RealType>::has_infinity && x == -std::numeric_limits<RealType>::infinity())\n    //{ // cdf complement -infinity is unity.\n    //  return 1;\n    //}\n    RealType result = 0;\n    if(false == detail::check_scale(function, scale, &result, Policy()))\n      return result;\n    if(false == detail::check_location(function, location, &result, Policy()))\n      return result;\n    if(false == detail::check_skew_normal_shape(function, shape, &result, Policy()))\n      return result;\n    if(false == detail::check_x(function, x, &result, Policy()))\n      return result;\n\n    const RealType transformed_x = (x-location)/scale;\n\n    normal_distribution<RealType, Policy> std_normal;\n\n    result = cdf(complement(std_normal, transformed_x)) + owens_t(transformed_x, shape)*static_cast<RealType>(2);\n    return result;\n  } // cdf complement\n\n  template <class RealType, class Policy>\n  inline RealType location(const skew_normal_distribution<RealType, Policy>& dist)\n  {\n    return dist.location();\n  }\n\n  template <class RealType, class Policy>\n  inline RealType scale(const skew_normal_distribution<RealType, Policy>& dist)\n  {\n    return dist.scale();\n  }\n\n  template <class RealType, class Policy>\n  inline RealType shape(const skew_normal_distribution<RealType, Policy>& dist)\n  {\n    return dist.shape();\n  }\n\n  template <class RealType, class Policy>\n  inline RealType mean(const skew_normal_distribution<RealType, Policy>& dist)\n  {\n    BOOST_MATH_STD_USING  // for ADL of std functions\n\n    using namespace boost::math::constants;\n\n    //const RealType delta = dist.shape() / sqrt(static_cast<RealType>(1)+dist.shape()*dist.shape());\n\n    //return dist.location() + dist.scale() * delta * root_two_div_pi<RealType>();\n\n    return dist.location() + dist.scale() * dist.shape() / sqrt(pi<RealType>()+pi<RealType>()*dist.shape()*dist.shape()) * root_two<RealType>();\n  }\n\n  template <class RealType, class Policy>\n  inline RealType variance(const skew_normal_distribution<RealType, Policy>& dist)\n  {\n    using namespace boost::math::constants;\n\n    const RealType delta2 = static_cast<RealType>(1) / (static_cast<RealType>(1)+static_cast<RealType>(1)/(dist.shape()*dist.shape()));\n    //const RealType inv_delta2 = static_cast<RealType>(1)+static_cast<RealType>(1)/(dist.shape()*dist.shape());\n\n    RealType variance = dist.scale()*dist.scale()*(static_cast<RealType>(1)-two_div_pi<RealType>()*delta2);\n    //RealType variance = dist.scale()*dist.scale()*(static_cast<RealType>(1)-two_div_pi<RealType>()/inv_delta2);\n\n    return variance;\n  }\n\n  namespace detail\n  {\n    /*\n      TODO No closed expression for mode, so use max of pdf.\n    */\n    \n    template <class RealType, class Policy>\n    inline RealType mode_fallback(const skew_normal_distribution<RealType, Policy>& dist)\n    { // mode.\n        static const char* function = \"mode(skew_normal_distribution<%1%> const&)\";\n        const RealType scale = dist.scale();\n        const RealType location = dist.location();\n        const RealType shape = dist.shape();\n        \n        RealType result;\n        if(!detail::check_scale(\n          function,\n          scale, &result, Policy())\n          ||\n        !detail::check_skew_normal_shape(\n          function,\n          shape,\n          &result,\n          Policy()))\n        return result;\n\n        if( shape == 0 )\n        {\n          return location;\n        }\n\n        if( shape < 0 )\n        {\n          skew_normal_distribution<RealType, Policy> D(0, 1, -shape);\n          result = mode_fallback(D);\n          result = location-scale*result;\n          return result;\n        }\n        \n        BOOST_MATH_STD_USING\n\n        // 21 elements\n        static const RealType shapes[] = {\n          0.0,\n          1.000000000000000e-004,\n          2.069138081114790e-004,\n          4.281332398719396e-004,\n          8.858667904100824e-004,\n          1.832980710832436e-003,\n          3.792690190732250e-003,\n          7.847599703514606e-003,\n          1.623776739188722e-002,\n          3.359818286283781e-002,\n          6.951927961775606e-002,\n          1.438449888287663e-001,\n          2.976351441631319e-001,\n          6.158482110660261e-001,\n          1.274274985703135e+000,\n          2.636650898730361e+000,\n          5.455594781168514e+000,\n          1.128837891684688e+001,\n          2.335721469090121e+001,\n          4.832930238571753e+001,\n          1.000000000000000e+002};\n\n        // 21 elements\n        static const RealType guess[] = {\n          0.0,\n          5.000050000525391e-005,\n          1.500015000148736e-004,\n          3.500035000350010e-004,\n          7.500075000752560e-004,\n          1.450014500145258e-003,\n          3.050030500305390e-003,\n          6.250062500624765e-003,\n          1.295012950129504e-002,\n          2.675026750267495e-002,\n          5.525055250552491e-002,\n          1.132511325113255e-001,\n          2.249522495224952e-001,\n          3.992539925399257e-001,\n          5.353553535535358e-001,\n          4.954549545495457e-001,\n          3.524535245352451e-001,\n          2.182521825218249e-001,\n          1.256512565125654e-001,\n          6.945069450694508e-002,\n          3.735037350373460e-002\n        };\n\n        const RealType* result_ptr = std::lower_bound(shapes, shapes+21, shape);\n\n        typedef typename std::iterator_traits<RealType*>::difference_type diff_type;\n        \n        const diff_type d = std::distance(shapes, result_ptr);\n        \n        BOOST_ASSERT(d > static_cast<diff_type>(0));\n\n        // refine\n        if(d < static_cast<diff_type>(21)) // shape smaller 100\n        {\n          result = guess[d-static_cast<diff_type>(1)]\n            + (guess[d]-guess[d-static_cast<diff_type>(1)])/(shapes[d]-shapes[d-static_cast<diff_type>(1)])\n            * (shape-shapes[d-static_cast<diff_type>(1)]);\n        }\n        else // shape greater 100\n        {\n          result = 1e-4;\n        }\n\n        skew_normal_distribution<RealType, Policy> helper(0, 1, shape);\n        \n        result = detail::generic_find_mode_01(helper, result, function);\n        \n        result = result*scale + location;\n        \n        return result;\n    } // mode_fallback\n    \n    \n    /*\n     * TODO No closed expression for mode, so use f'(x) = 0\n     */\n    template <class RealType, class Policy>\n    struct skew_normal_mode_functor\n    { \n      skew_normal_mode_functor(const boost::math::skew_normal_distribution<RealType, Policy> dist)\n        : distribution(dist)\n      {\n      }\n\n      boost::math::tuple<RealType, RealType> operator()(RealType const& x)\n      {\n        normal_distribution<RealType, Policy> std_normal;\n        const RealType shape = distribution.shape();\n        const RealType pdf_x = pdf(distribution, x);\n        const RealType normpdf_x = pdf(std_normal, x);\n        const RealType normpdf_ax = pdf(std_normal, x*shape);\n        RealType fx = static_cast<RealType>(2)*shape*normpdf_ax*normpdf_x - x*pdf_x;\n        RealType dx = static_cast<RealType>(2)*shape*x*normpdf_x*normpdf_ax*(static_cast<RealType>(1) + shape*shape) + pdf_x + x*fx;\n        // return both function evaluation difference f(x) and 1st derivative f'(x).\n        return boost::math::make_tuple(fx, -dx);\n      }\n    private:\n      const boost::math::skew_normal_distribution<RealType, Policy> distribution;\n    };\n    \n  } // namespace detail\n  \n  template <class RealType, class Policy>\n  inline RealType mode(const skew_normal_distribution<RealType, Policy>& dist)\n  {\n    const RealType scale = dist.scale();\n    const RealType location = dist.location();\n    const RealType shape = dist.shape();\n\n    static const char* function = \"boost::math::mode(const skew_normal_distribution<%1%>&, %1%)\";\n\n    RealType result = 0;\n    if(false == detail::check_scale(function, scale, &result, Policy()))\n      return result;\n    if(false == detail::check_location(function, location, &result, Policy()))\n      return result;\n    if(false == detail::check_skew_normal_shape(function, shape, &result, Policy()))\n      return result;\n\n    if( shape == 0 )\n    {\n      return location;\n    }\n\n    if( shape < 0 )\n    {\n      skew_normal_distribution<RealType, Policy> D(0, 1, -shape);\n      result = mode(D);\n      result = location-scale*result;\n      return result;\n    }\n\n    // 21 elements\n    static const RealType shapes[] = {\n      0.0,\n      static_cast<RealType>(1.000000000000000e-004),\n      static_cast<RealType>(2.069138081114790e-004),\n      static_cast<RealType>(4.281332398719396e-004),\n      static_cast<RealType>(8.858667904100824e-004),\n      static_cast<RealType>(1.832980710832436e-003),\n      static_cast<RealType>(3.792690190732250e-003),\n      static_cast<RealType>(7.847599703514606e-003),\n      static_cast<RealType>(1.623776739188722e-002),\n      static_cast<RealType>(3.359818286283781e-002),\n      static_cast<RealType>(6.951927961775606e-002),\n      static_cast<RealType>(1.438449888287663e-001),\n      static_cast<RealType>(2.976351441631319e-001),\n      static_cast<RealType>(6.158482110660261e-001),\n      static_cast<RealType>(1.274274985703135e+000),\n      static_cast<RealType>(2.636650898730361e+000),\n      static_cast<RealType>(5.455594781168514e+000),\n      static_cast<RealType>(1.128837891684688e+001),\n      static_cast<RealType>(2.335721469090121e+001),\n      static_cast<RealType>(4.832930238571753e+001),\n      static_cast<RealType>(1.000000000000000e+002)\n    };\n\n    // 21 elements\n    static const RealType guess[] = {\n      0.0,\n      static_cast<RealType>(5.000050000525391e-005),\n      static_cast<RealType>(1.500015000148736e-004),\n      static_cast<RealType>(3.500035000350010e-004),\n      static_cast<RealType>(7.500075000752560e-004),\n      static_cast<RealType>(1.450014500145258e-003),\n      static_cast<RealType>(3.050030500305390e-003),\n      static_cast<RealType>(6.250062500624765e-003),\n      static_cast<RealType>(1.295012950129504e-002),\n      static_cast<RealType>(2.675026750267495e-002),\n      static_cast<RealType>(5.525055250552491e-002),\n      static_cast<RealType>(1.132511325113255e-001),\n      static_cast<RealType>(2.249522495224952e-001),\n      static_cast<RealType>(3.992539925399257e-001),\n      static_cast<RealType>(5.353553535535358e-001),\n      static_cast<RealType>(4.954549545495457e-001),\n      static_cast<RealType>(3.524535245352451e-001),\n      static_cast<RealType>(2.182521825218249e-001),\n      static_cast<RealType>(1.256512565125654e-001),\n      static_cast<RealType>(6.945069450694508e-002),\n      static_cast<RealType>(3.735037350373460e-002)\n    };\n\n    const RealType* result_ptr = std::lower_bound(shapes, shapes+21, shape);\n\n    typedef typename std::iterator_traits<RealType*>::difference_type diff_type;\n    \n    const diff_type d = std::distance(shapes, result_ptr);\n    \n    BOOST_ASSERT(d > static_cast<diff_type>(0));\n\n    // TODO: make the search bounds smarter, depending on the shape parameter\n    RealType search_min = 0; // below zero was caught above\n    RealType search_max = 0.55f; // will never go above 0.55\n\n    // refine\n    if(d < static_cast<diff_type>(21)) // shape smaller 100\n    {\n      // it is safe to assume that d > 0, because shape==0.0 is caught earlier\n      result = guess[d-static_cast<diff_type>(1)]\n        + (guess[d]-guess[d-static_cast<diff_type>(1)])/(shapes[d]-shapes[d-static_cast<diff_type>(1)])\n        * (shape-shapes[d-static_cast<diff_type>(1)]);\n    }\n    else // shape greater 100\n    {\n      result = 1e-4f;\n      search_max = guess[19]; // set 19 instead of 20 to have a safety margin because the table may not be exact @ shape=100\n    }\n    \n    const int get_digits = policies::digits<RealType, Policy>();// get digits from policy, \n    boost::uintmax_t m = policies::get_max_root_iterations<Policy>(); // and max iterations.\n\n    skew_normal_distribution<RealType, Policy> helper(0, 1, shape);\n\n    result = tools::newton_raphson_iterate(detail::skew_normal_mode_functor<RealType, Policy>(helper), result,\n      search_min, search_max, get_digits, m);\n    \n    result = result*scale + location;\n\n    return result;\n  }\n  \n\n  \n  template <class RealType, class Policy>\n  inline RealType skewness(const skew_normal_distribution<RealType, Policy>& dist)\n  {\n    BOOST_MATH_STD_USING  // for ADL of std functions\n    using namespace boost::math::constants;\n\n    static const RealType factor = four_minus_pi<RealType>()/static_cast<RealType>(2);\n    const RealType delta = dist.shape() / sqrt(static_cast<RealType>(1)+dist.shape()*dist.shape());\n\n    return factor * pow(root_two_div_pi<RealType>() * delta, 3) /\n      pow(static_cast<RealType>(1)-two_div_pi<RealType>()*delta*delta, static_cast<RealType>(1.5));\n  }\n\n  template <class RealType, class Policy>\n  inline RealType kurtosis(const skew_normal_distribution<RealType, Policy>& dist)\n  {\n    return kurtosis_excess(dist)+static_cast<RealType>(3);\n  }\n\n  template <class RealType, class Policy>\n  inline RealType kurtosis_excess(const skew_normal_distribution<RealType, Policy>& dist)\n  {\n    using namespace boost::math::constants;\n\n    static const RealType factor = pi_minus_three<RealType>()*static_cast<RealType>(2);\n\n    const RealType delta2 = static_cast<RealType>(1) / (static_cast<RealType>(1)+static_cast<RealType>(1)/(dist.shape()*dist.shape()));\n\n    const RealType x = static_cast<RealType>(1)-two_div_pi<RealType>()*delta2;\n    const RealType y = two_div_pi<RealType>() * delta2;\n\n    return factor * y*y / (x*x);\n  }\n\n  namespace detail\n  {\n\n    template <class RealType, class Policy>\n    struct skew_normal_quantile_functor\n    { \n      skew_normal_quantile_functor(const boost::math::skew_normal_distribution<RealType, Policy> dist, RealType const& p)\n        : distribution(dist), prob(p)\n      {\n      }\n\n      boost::math::tuple<RealType, RealType> operator()(RealType const& x)\n      {\n        RealType c = cdf(distribution, x);\n        RealType fx = c - prob;  // Difference cdf - value - to minimize.\n        RealType dx = pdf(distribution, x); // pdf is 1st derivative.\n        // return both function evaluation difference f(x) and 1st derivative f'(x).\n        return boost::math::make_tuple(fx, dx);\n      }\n    private:\n      const boost::math::skew_normal_distribution<RealType, Policy> distribution;\n      RealType prob; \n    };\n\n  } // namespace detail\n\n  template <class RealType, class Policy>\n  inline RealType quantile(const skew_normal_distribution<RealType, Policy>& dist, const RealType& p)\n  {\n    const RealType scale = dist.scale();\n    const RealType location = dist.location();\n    const RealType shape = dist.shape();\n\n    static const char* function = \"boost::math::quantile(const skew_normal_distribution<%1%>&, %1%)\";\n\n    RealType result = 0;\n    if(false == detail::check_scale(function, scale, &result, Policy()))\n      return result;\n    if(false == detail::check_location(function, location, &result, Policy()))\n      return result;\n    if(false == detail::check_skew_normal_shape(function, shape, &result, Policy()))\n      return result;\n    if(false == detail::check_probability(function, p, &result, Policy()))\n      return result;\n\n    // Compute initial guess via Cornish-Fisher expansion.\n    RealType x = -boost::math::erfc_inv(2 * p, Policy()) * constants::root_two<RealType>();\n\n    // Avoid unnecessary computations if there is no skew.\n    if(shape != 0)\n    {\n      const RealType skew = skewness(dist);\n      const RealType exk = kurtosis_excess(dist);\n\n      x = x + (x*x-static_cast<RealType>(1))*skew/static_cast<RealType>(6)\n      + x*(x*x-static_cast<RealType>(3))*exk/static_cast<RealType>(24)\n      - x*(static_cast<RealType>(2)*x*x-static_cast<RealType>(5))*skew*skew/static_cast<RealType>(36);\n    } // if(shape != 0)\n\n    result = standard_deviation(dist)*x+mean(dist);\n\n    // handle special case of non-skew normal distribution.\n    if(shape == 0)\n      return result;\n\n    // refine the result by numerically searching the root of (p-cdf)\n\n    const RealType search_min = range(dist).first;\n    const RealType search_max = range(dist).second;\n\n    const int get_digits = policies::digits<RealType, Policy>();// get digits from policy, \n    boost::uintmax_t m = policies::get_max_root_iterations<Policy>(); // and max iterations.\n\n    result = tools::newton_raphson_iterate(detail::skew_normal_quantile_functor<RealType, Policy>(dist, p), result,\n      search_min, search_max, get_digits, m);\n\n    return result;\n  } // quantile\n\n  template <class RealType, class Policy>\n  inline RealType quantile(const complemented2_type<skew_normal_distribution<RealType, Policy>, RealType>& c)\n  {\n    const RealType scale = c.dist.scale();\n    const RealType location = c.dist.location();\n    const RealType shape = c.dist.shape();\n\n    static const char* function = \"boost::math::quantile(const complement(skew_normal_distribution<%1%>&), %1%)\";\n    RealType result = 0;\n    if(false == detail::check_scale(function, scale, &result, Policy()))\n      return result;\n    if(false == detail::check_location(function, location, &result, Policy()))\n      return result;\n    if(false == detail::check_skew_normal_shape(function, shape, &result, Policy()))\n      return result;\n    RealType q = c.param;\n    if(false == detail::check_probability(function, q, &result, Policy()))\n      return result;\n\n    skew_normal_distribution<RealType, Policy> D(-location, scale, -shape);\n\n    result = -quantile(D, q);\n\n    return result;\n  } // quantile\n\n\n} // namespace math\n} // namespace boost\n\n// This include must be at the end, *after* the accessors\n// for this distribution have been defined, in order to\n// keep compilers that support two-phase lookup happy.\n#include <boost/math/distributions/detail/derived_accessors.hpp>\n\n#endif // BOOST_STATS_SKEW_NORMAL_HPP\n\n\n", "meta": {"hexsha": "f348347ede996badb9cdb911cc616eaea1fa7089", "size": 25552, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "contrib/libboost/boost_1_62_0/boost/math/distributions/skew_normal.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/skew_normal.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/skew_normal.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": 35.4888888889, "max_line_length": 144, "alphanum_fraction": 0.665036005, "num_tokens": 6630, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6688802735722128, "lm_q2_score": 0.47657965106367595, "lm_q1q2_score": 0.3187747273824213}}
{"text": "#include <vector>\n#include <boost/random/mersenne_twister.hpp>\n#include <boost/random/uniform_int_distribution.hpp>\n\n#include <kanooth/numbers/lowlevel/generic_has_double.hpp>\n#include <kanooth/numbers/lowlevel/generic_sim_double.hpp>\n#include <kanooth/numbers/lowlevel/low_double_int.hpp>\n#include <kanooth/number_bits.hpp>\n#include <kanooth/fixed_width_ints.hpp>\n\n#include \"common/stopwatch.hpp\"\n\nboost::random::mt19937 gen;\n\ntemplate <typename T>\nvoid random_array(T* begin, T* end)\n{\n    boost::random::uniform_int_distribution<T> rand;\n    while (begin != end)\n        *begin++ = rand(gen);\n}\n\ntemplate <typename LOWLEVEL>\nclass tester {\npublic:\n    tester(unsigned _length) : length(_length)\n    {\n        digit_type* r;\n        for (unsigned k = 0; k < count; ++k) {\n            r = new digit_type[length];\n            random_array(r, r + length);\n            a.push_back(r);\n            r = new digit_type[length];\n            random_array(r, r + length);\n            b.push_back(r);\n            c.push_back(new digit_type[length]);\n        }\n        random_array(&scalar, &scalar + 1);\n    }\n    \n    ~tester()\n    {\n        for (unsigned k = 0; k < count; ++k) {\n            delete[] a[k];\n            delete[] b[k];\n            delete[] c[k];\n        }\n    }\n    \n    double test_add()\n    {\n        stopwatch<> timer;\n\n        unsigned reps = length > 10000 ? 1 : 10000/length;\n        for (unsigned j = 0; j < reps; ++j)\n            for (unsigned k = 0; k < count; ++k)\n                LOWLEVEL::add(c[k], a[k], length, b[k], length);        \n        \n        return 0.000000001 * count * reps * length * digit_bits / timer.seconds();\n    }\n    \n    double test_sub()\n    {\n        stopwatch<> timer;\n\n        unsigned reps = length > 10000 ? 1 : 10000/length;\n        for (unsigned j = 0; j < reps; ++j)\n            for (unsigned k = 0; k < count; ++k)\n                LOWLEVEL::sub(c[k], a[k], length, b[k], length);        \n        \n        return 0.000000001 * count * reps * length * digit_bits / timer.seconds();\n    }\n    \n    double test_mul_1()\n    {\n        stopwatch<> timer;\n\n        unsigned reps = length > 10000 ? 1 : 10000/length;\n        for (unsigned j = 0; j < reps; ++j)\n            for (unsigned k = 0; k < count; ++k)\n                LOWLEVEL::mul_1(c[k], a[k], length, b[k][0]);\n        \n        return 0.000000001 * count * reps * length * digit_bits / timer.seconds();\n    }\n    \n    void run()\n    {\n        std::cout.flags(std::ios::fixed);\n        std::cout.precision(2);\n        std::cout << \"add       \" << test_add() << \" Gbit/s\" << std::endl;\n        std::cout << \"sub       \" << test_sub() << \" Gbit/s\" << std::endl;\n        std::cout << \"mul_1     \" << test_mul_1() << \" Gbit/s\" << std::endl;\n    }\nprivate:\n    typedef typename LOWLEVEL::digit_type digit_type;\n    static const unsigned digit_bits = kanooth::number_bits<digit_type>::value;\n    static const unsigned count = 10000;\n    const unsigned length;\n    std::vector<digit_type*> a;\n    std::vector<digit_type*> b;\n    std::vector<digit_type*> c;\n    digit_type scalar;\n};\n\nint main()\n{\n    //tester<kanooth::numbers::lowlevel::generic_has_double<kanooth::uint64_t, kanooth::uint128_t> >(1000).run();\n    tester<kanooth::numbers::lowlevel::generic_has_double<kanooth::uint32_t, kanooth::uint64_t> >(1000).run();\n    //tester<kanooth::numbers::lowlevel::generic_has_double<kanooth::uint16_t, kanooth::uint32_t> >(1000).run();\n    //tester<kanooth::numbers::lowlevel::generic_has_double<kanooth::uint64_t, kanooth::numbers::lowlevel::low_double_int<kanooth::uint64_t> > >(1000).run();\n    tester<kanooth::numbers::lowlevel::generic_sim_double<kanooth::uint64_t> >(1000).run();\n    \n    /*tester<kanooth::numbers::lowlevel::generic_has_double<kanooth::uint16_t, kanooth::uint32_t> >(1000).run();\n    tester<kanooth::numbers::lowlevel::generic_has_double<kanooth::uint16_t, kanooth::numbers::lowlevel::low_double_int<kanooth::uint16_t> > >(1000).run();\n    tester<kanooth::numbers::lowlevel::generic_sim_double<kanooth::uint16_t> >(1000).run();*/\n\n    /*tester<kanooth::numbers::lowlevel::generic_has_double<kanooth::uint64_t, kanooth::uint128_t> >(1000).run();\n    tester<kanooth::numbers::lowlevel::generic_has_double<kanooth::uint64_t, kanooth::numbers::lowlevel::low_double_int<kanooth::uint64_t> > >(1000).run();\n    tester<kanooth::numbers::lowlevel::generic_sim_double<kanooth::uint64_t> >(1000).run();*/\n\n    return 0;\n}\n", "meta": {"hexsha": "deda22fba25f6991a7c632c9079db52b44b4c9bf", "size": 4431, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/lowlevel_perf.cpp", "max_stars_repo_name": "janmarthedal/kanooth-numbers", "max_stars_repo_head_hexsha": "2c6ce4f588bdd26826c20a84154881d84a70191c", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2017-10-02T13:29:54.000Z", "max_stars_repo_stars_event_max_datetime": "2018-04-24T18:17:18.000Z", "max_issues_repo_path": "test/lowlevel_perf.cpp", "max_issues_repo_name": "janmarthedal/kanooth-numbers", "max_issues_repo_head_hexsha": "2c6ce4f588bdd26826c20a84154881d84a70191c", "max_issues_repo_licenses": ["BSL-1.0"], "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/lowlevel_perf.cpp", "max_forks_repo_name": "janmarthedal/kanooth-numbers", "max_forks_repo_head_hexsha": "2c6ce4f588bdd26826c20a84154881d84a70191c", "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.0243902439, "max_line_length": 157, "alphanum_fraction": 0.6066350711, "num_tokens": 1245, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6688802603710085, "lm_q2_score": 0.476579651063676, "lm_q1q2_score": 0.31877472109099597}}
{"text": "#pragma once\n#include \"math.h\"\n#include <boost/config.hpp>\n#include <type_traits>\n\nnamespace std { template <class T> class complex; }\n///\n\nnamespace coreutil {\n\nBOOST_FORCEINLINE constexpr math_constant::math_constant(long double value)\n    : value(value) {}\n\ntemplate <class T>\nBOOST_FORCEINLINE constexpr math_constant::operator T() const {\n  return value;\n}\n\nnamespace math_constants_detail {\n\ntemplate <class T> struct is_compatible_operand;\ntemplate <class T> struct is_compatible_operand<std::complex<T>>\n    : public is_compatible_operand<T> {};\ntemplate <class T> struct is_compatible_operand\n    : public std::is_floating_point<T> {};\n\n}  // namespace math_constants_detail\n\n#define COREUTIL_MATH_TYPE_CHECK(op, t)                                 \\\n  static_assert(math_constants_detail::is_compatible_operand<t>(),      \\\n                \"cannot perform '\" #op \"' between a math constant and non-floating point type \" #t)\n#define COREUTIL_MATH_DEFINE_UNOP(op)                                   \\\n  BOOST_FORCEINLINE constexpr math_constant operator op(math_constant a) { return math_constant(op a.value); }\n#define COREUTIL_MATH_DEFINE_BINOP(op)                                  \\\n  BOOST_FORCEINLINE constexpr math_constant operator op(math_constant a, math_constant b) { return math_constant(a.value op b.value); } \\\n  template <class T> BOOST_FORCEINLINE constexpr T operator op(math_constant a, T b) { COREUTIL_MATH_TYPE_CHECK(op, T); return T(a.value) op b; } \\\n  template <class T> BOOST_FORCEINLINE constexpr T operator op(T a, math_constant b) { COREUTIL_MATH_TYPE_CHECK(op, T); return a op T(b.value); }\n#define COREUTIL_MATH_DEFINE_OPASSIGN(op)   \\\n  template <class T> BOOST_FORCEINLINE constexpr T &operator op(T &a, math_constant b) { COREUTIL_MATH_TYPE_CHECK(op, T); return a op T(b.value); }\n#define COREUTIL_MATH_DEFINE_COMPARISON(op)                             \\\n  BOOST_FORCEINLINE constexpr bool operator op(math_constant a, math_constant b) { return a.value op b.value; } \\\n  template <class T> BOOST_FORCEINLINE constexpr bool operator op(math_constant a, T b) { COREUTIL_MATH_TYPE_CHECK(op, T); return T(a.value) op b; } \\\n  template <class T> BOOST_FORCEINLINE constexpr bool operator op(T a, math_constant b) { COREUTIL_MATH_TYPE_CHECK(op, T); return a op T(b.value); }\n\nCOREUTIL_MATH_DEFINE_UNOP(+);\nCOREUTIL_MATH_DEFINE_UNOP(-);\nCOREUTIL_MATH_DEFINE_BINOP(+);\nCOREUTIL_MATH_DEFINE_BINOP(-);\nCOREUTIL_MATH_DEFINE_BINOP(*);\nCOREUTIL_MATH_DEFINE_BINOP(/);\nCOREUTIL_MATH_DEFINE_OPASSIGN(+=);\nCOREUTIL_MATH_DEFINE_OPASSIGN(-=);\nCOREUTIL_MATH_DEFINE_OPASSIGN(*=);\nCOREUTIL_MATH_DEFINE_OPASSIGN(/=);\nCOREUTIL_MATH_DEFINE_COMPARISON(==);\nCOREUTIL_MATH_DEFINE_COMPARISON(!=);\nCOREUTIL_MATH_DEFINE_COMPARISON(<);\nCOREUTIL_MATH_DEFINE_COMPARISON(>);\nCOREUTIL_MATH_DEFINE_COMPARISON(<=);\nCOREUTIL_MATH_DEFINE_COMPARISON(>=);\n\n#undef COREUTIL_MATH_TYPE_CHECK\n#undef COREUTIL_MATH_DEFINE_UNOP\n#undef COREUTIL_MATH_DEFINE_BINOP\n#undef COREUTIL_MATH_DEFINE_OPASSIGN\n#undef COREUTIL_MATH_DEFINE_COMPARISON\n\n}  // namespace coreutil\n", "meta": {"hexsha": "8ca5378d03f4820eb8f3d75f439ffd779a05fb84", "size": 3053, "ext": "tcc", "lang": "C++", "max_stars_repo_path": "sources/coreutil/math.tcc", "max_stars_repo_name": "jpcima/coreutil", "max_stars_repo_head_hexsha": "8ec6acec90738919116e71e3a7ea5fe012793ad4", "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": "sources/coreutil/math.tcc", "max_issues_repo_name": "jpcima/coreutil", "max_issues_repo_head_hexsha": "8ec6acec90738919116e71e3a7ea5fe012793ad4", "max_issues_repo_licenses": ["BSL-1.0"], "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/coreutil/math.tcc", "max_forks_repo_name": "jpcima/coreutil", "max_forks_repo_head_hexsha": "8ec6acec90738919116e71e3a7ea5fe012793ad4", "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.2463768116, "max_line_length": 150, "alphanum_fraction": 0.7494267933, "num_tokens": 710, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6688802603710086, "lm_q2_score": 0.47657965106367595, "lm_q1q2_score": 0.31877472109099597}}
{"text": "#include <boost/math/special_functions/next.hpp>\n#include <boost/random.hpp>\n\n#include <limits>\n\n#include \"caffe/common.hpp\"\n#include \"caffe/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 (alpha == 0) {\n    memset(Y, 0, sizeof(Dtype) * N);  // NOLINT(caffe/alt_fn)\n    return;\n  }\n  for (int i = 0; i < N; ++i) {\n    Y[i] = alpha;\n  }\n}\n\ntemplate void caffe_set<int>(const int N, const int alpha, int* Y);\ntemplate void caffe_set<unsigned int>(const int N, const unsigned int alpha, unsigned int* Y);\ntemplate void caffe_set<float>(const int N, const float alpha, float* Y);\ntemplate void caffe_set<double>(const int N, const double alpha, double* Y);\n\ntemplate <>\nvoid caffe_add_scalar(const int N, const float alpha, float* Y) {\n  for (int i = 0; i < N; ++i) {\n    Y[i] += alpha;\n  }\n}\n\ntemplate <>\nvoid caffe_add_scalar(const int N, const double alpha, double* Y) {\n  for (int i = 0; i < N; ++i) {\n    Y[i] += alpha;\n  }\n}\n\ntemplate <typename Dtype>\nvoid caffe_copy(const int N, const Dtype* X, Dtype* Y) {\n  if (X != Y) {\n    if (Caffe::mode() == Caffe::GPU) {\n#ifndef CPU_ONLY\n      // NOLINT_NEXT_LINE(caffe/alt_fn)\n      CUDA_CHECK(cudaMemcpy(Y, X, sizeof(Dtype) * N, cudaMemcpyDefault));\n#else\n      NO_GPU;\n#endif\n    } else {\n      memcpy(Y, X, sizeof(Dtype) * N);  // NOLINT(caffe/alt_fn)\n    }\n  }\n}\ntemplate void caffe_copy<int>(const int N, const int* X, int* Y);\ntemplate void caffe_copy<unsigned int>(const int N, const unsigned int* X,\n    unsigned int* Y);\ntemplate void caffe_copy<float>(const int N, const float* X, float* Y);\ntemplate void caffe_copy<double>(const int N, const double* X, double* Y);\n\n\ntemplate <typename Dtype>\nvoid caffe_copy_subarray(const Dtype* src_p, const vector<int>& src_shape,\n                         Dtype*       trg_p, const vector<int>& trg_shape,\n                         const vector<int>& src_offset,\n                         const vector<int>& copy_shape,\n                         const vector<int>& trg_offset) {\n//  VLOG(1) << \"copy_subarray called with \\n\"\n//            << \"src_shape=\" << toString( src_shape) << \"\\n\"\n//            << \"trg_shape=\" << toString( trg_shape) << \"\\n\"\n//            << \"src_offset=\" << toString( src_offset) << \"\\n\"\n//            << \"copy_shape=\" << toString( copy_shape) << \"\\n\"\n//            << \"trg_offset=\" << toString( trg_offset) << \"\\n\";\n  int num_axes = src_shape.size();\n  CHECK_LT(num_axes, 10) << \"only 10 axes are supported\";\n  CHECK_EQ(src_shape.size(), trg_shape.size()) << \"target must have same number of axes\";\n  CHECK_EQ(src_shape.size(), src_offset.size());\n  CHECK_EQ(src_shape.size(), copy_shape.size());\n  CHECK_EQ(src_shape.size(), trg_offset.size());\n\n  int N[10];   // copy shape\n  int so[10];  // src offset\n  int to[10];  // trg offset\n  int ss[10];  // src stride\n  int ts[10];  // trg stride\n  int axes_offset = 10 - num_axes;\n  for (int i = 0; i < axes_offset; ++i) {\n    N[i] = 1;\n    so[i] = 0;\n    to[i] = 0;\n    ss[i] = 0;  // dummy value, will be multiplied with zero anyway\n    ts[i] = 0;  // dummy value, will be multiplied with zero anyway\n  }\n\n  for (int i = 0; i < num_axes; ++i) {\n    N[ axes_offset + i] = copy_shape[i];\n    so[axes_offset + i] = src_offset[i];\n    to[axes_offset + i] = trg_offset[i];\n  }\n\n  ss[9] = 1;\n  ts[9] = 1;\n  for (int i = num_axes-1; i > 0; --i) {\n    ss[axes_offset + i - 1] = src_shape[i] * ss[axes_offset + i];\n    ts[axes_offset + i - 1] = trg_shape[i] * ts[axes_offset + i];\n  }\n//  VLOG(1) << \"resulting 10d vectors\\n\"\n//            << \"N=\" << toString(N,10) << \"\\n\"\n//            << \"so=\" << toString(so,10) << \"\\n\"\n//            << \"to=\" << toString(to,10) << \"\\n\"\n//            << \"ss=\" << toString(ss,10) << \"\\n\"\n//            << \"ts=\" << toString(ts,10) << \"\\n\";\n\n  int copy_nelem = N[9];\n  for (                int i0 = 0; i0 < N[0]; ++i0) { int s0  =      ss[0] * (i0 + so[0]); int t0 =      ts[0] * (i0 + to[0]);\n    for (              int i1 = 0; i1 < N[1]; ++i1) { int s1  = s0 + ss[1] * (i1 + so[1]); int t1 = t0 + ts[1] * (i1 + to[1]);\n      for (            int i2 = 0; i2 < N[2]; ++i2) { int s2  = s1 + ss[2] * (i2 + so[2]); int t2 = t1 + ts[2] * (i2 + to[2]);\n        for (          int i3 = 0; i3 < N[3]; ++i3) { int s3  = s2 + ss[3] * (i3 + so[3]); int t3 = t2 + ts[3] * (i3 + to[3]);\n          for (        int i4 = 0; i4 < N[4]; ++i4) { int s4  = s3 + ss[4] * (i4 + so[4]); int t4 = t3 + ts[4] * (i4 + to[4]);\n            for (      int i5 = 0; i5 < N[5]; ++i5) { int s5  = s4 + ss[5] * (i5 + so[5]); int t5 = t4 + ts[5] * (i5 + to[5]);\n              for (    int i6 = 0; i6 < N[6]; ++i6) { int s6  = s5 + ss[6] * (i6 + so[6]); int t6 = t5 + ts[6] * (i6 + to[6]);\n                for (  int i7 = 0; i7 < N[7]; ++i7) { int s7  = s6 + ss[7] * (i7 + so[7]); int t7 = t6 + ts[7] * (i7 + to[7]);\n                  for (int i8 = 0; i8 < N[8]; ++i8) { int s8  = s7 + ss[8] * (i8 + so[8]); int t8 = t7 + ts[8] * (i8 + to[8]);\n                    caffe_copy(copy_nelem, src_p + s8 + so[9], trg_p + t8 + to[9]);\n                  }\n                }\n              }\n            }\n          }\n        }\n      }\n    }\n  }\n}\n\ntemplate void caffe_copy_subarray<int>(         const int*          src_p, const vector<int>& src_shape, int*          trg_p, const vector<int>& trg_shape, const vector<int>& src_offset, const vector<int>& copy_shape, const vector<int>& trg_offset);\ntemplate void caffe_copy_subarray<unsigned int>(const unsigned int* src_p, const vector<int>& src_shape, unsigned int* trg_p, const vector<int>& trg_shape, const vector<int>& src_offset, const vector<int>& copy_shape, const vector<int>& trg_offset);\ntemplate void caffe_copy_subarray<float>(       const float*        src_p, const vector<int>& src_shape, float*        trg_p, const vector<int>& trg_shape, const vector<int>& src_offset, const vector<int>& copy_shape, const vector<int>& trg_offset);\ntemplate void caffe_copy_subarray<double>(      const double*       src_p, const vector<int>& src_shape, double*       trg_p, const vector<int>& trg_shape, const vector<int>& src_offset, const vector<int>& copy_shape, const vector<int>& trg_offset);\n\ntemplate <>\nvoid caffe_scal<float>(const int N, const float alpha, float *X) {\n  cblas_sscal(N, alpha, X, 1);\n}\n\ntemplate <>\nvoid caffe_scal<double>(const int N, const double alpha, double *X) {\n  cblas_dscal(N, alpha, X, 1);\n}\n\ntemplate <>\nvoid caffe_cpu_axpby<float>(const int N, const float alpha, const float* X,\n                            const float beta, float* Y) {\n  cblas_saxpby(N, alpha, X, 1, beta, Y, 1);\n}\n\ntemplate <>\nvoid caffe_cpu_axpby<double>(const int N, const double alpha, const double* X,\n                             const double beta, double* Y) {\n  cblas_daxpby(N, alpha, X, 1, beta, Y, 1);\n}\n\ntemplate <>\nvoid caffe_add<float>(const int n, const float* a, const float* b,\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_sqrt<float>(const int n, const float* a, float* y) {\n  vsSqrt(n, a, y);\n}\n\ntemplate <>\nvoid caffe_sqrt<double>(const int n, const double* a, double* y) {\n  vdSqrt(n, a, y);\n}\n\ntemplate <>\nvoid caffe_exp<float>(const int n, const float* a, float* y) {\n  vsExp(n, a, y);\n}\n\ntemplate <>\nvoid caffe_exp<double>(const int n, const double* a, double* y) {\n  vdExp(n, a, y);\n}\n\ntemplate <>\nvoid caffe_log<float>(const int n, const float* a, float* y) {\n  vsLn(n, a, y);\n}\n\ntemplate <>\nvoid caffe_log<double>(const int n, const double* a, double* y) {\n  vdLn(n, a, y);\n}\n\ntemplate <>\nvoid caffe_abs<float>(const int n, const float* a, float* y) {\n    vsAbs(n, a, y);\n}\n\ntemplate <>\nvoid caffe_abs<double>(const int n, const double* a, double* y) {\n    vdAbs(n, a, y);\n}\n\nunsigned int caffe_rng_rand() {\n  return (*caffe_rng())();\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\ntemplate <typename Dtype>\nvoid caffe_rng_bernoulli(const int n, const Dtype p, int* r) {\n  CHECK_GE(n, 0);\n  CHECK(r);\n  CHECK_GE(p, 0);\n  CHECK_LE(p, 1);\n  boost::bernoulli_distribution<Dtype> random_distribution(p);\n  boost::variate_generator<caffe::rng_t*, boost::bernoulli_distribution<Dtype> >\n      variate_generator(caffe_rng(), random_distribution);\n  for (int i = 0; i < n; ++i) {\n    r[i] = variate_generator();\n  }\n}\n\ntemplate\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  boost::bernoulli_distribution<Dtype> random_distribution(p);\n  boost::variate_generator<caffe::rng_t*, boost::bernoulli_distribution<Dtype> >\n      variate_generator(caffe_rng(), random_distribution);\n  for (int i = 0; i < n; ++i) {\n    r[i] = static_cast<unsigned int>(variate_generator());\n  }\n}\n\ntemplate\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 <typename Dtype>\nsize_t caffe_randi_arbitrary_cdf(const size_t n, const Dtype* cdf) {\n  CHECK_GT(n, 0);\n  CHECK(cdf);\n  Dtype maxValue = cdf[n-1];\n  Dtype r;\n  caffe_rng_uniform( 1, Dtype(0), maxValue, &r);\n  const Dtype* p = std::lower_bound( cdf, cdf + n, r);\n  return p - cdf;\n}\n\ntemplate\nsize_t caffe_randi_arbitrary_cdf(const size_t n, const float* cdf);\n\ntemplate\nsize_t caffe_randi_arbitrary_cdf(const size_t n, const double* cdf);\n\ntemplate <typename Dtype>\nvoid caffe_rand_pos_arbitrary_cdf(const Dtype* cdf, int nz, int ny, int nx,\n                                  int* z, int* y, int* x) {\n  // sample a random index and map it to coordinates\n  size_t idx = caffe_randi_arbitrary_cdf( nz * ny * nx, cdf);\n  *z = idx / (ny * nx);\n  idx = idx - *z * ny * nx;\n  *y = idx / nx;\n  *x = idx - *y * nx;\n}\n\ntemplate\nvoid caffe_rand_pos_arbitrary_cdf(const float* cdf, int nz, int ny, int nx,\n                                  int* z, int* y, int* x);\ntemplate\nvoid caffe_rand_pos_arbitrary_cdf(const double* cdf, int nz, int ny, int nx,\n                                  int* z, int* y, int* x);\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 <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 <>\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 <typename Dtype>\nvoid caffe_cpu_cumsum(const size_t n, const Dtype* x, Dtype* y) {\n  CHECK_GE(n, 0);\n  CHECK(x);\n  CHECK(y);\n  if( n == 0) return;\n  Dtype cumsum = 0;\n  for (size_t i = 0; i < n; ++i) {\n    cumsum += x[i];\n    y[i] = cumsum;\n  }\n}\n\ntemplate\nvoid caffe_cpu_cumsum(const size_t n, const float* x, float* y);\n\ntemplate\nvoid caffe_cpu_cumsum(const size_t n, const double* x, double* y);\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": "a47e6b9e50c9d255ddf05c8dce56a61263792b9c", "size": 16452, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/caffe/util/math_functions.cpp", "max_stars_repo_name": "Andeling/caffe_unet", "max_stars_repo_head_hexsha": "f713104e5c76eea1b618b21b3a3f303dd673081c", "max_stars_repo_licenses": ["Intel", "BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/caffe/util/math_functions.cpp", "max_issues_repo_name": "Andeling/caffe_unet", "max_issues_repo_head_hexsha": "f713104e5c76eea1b618b21b3a3f303dd673081c", "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": "Andeling/caffe_unet", "max_forks_repo_head_hexsha": "f713104e5c76eea1b618b21b3a3f303dd673081c", "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": 31.6384615385, "max_line_length": 249, "alphanum_fraction": 0.6150012157, "num_tokens": 5091, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.668880247169804, "lm_q2_score": 0.47657965106367595, "lm_q1q2_score": 0.3187747147995705}}
{"text": "/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */\n\n/*\n Copyright (C) 2008 Andreas Gaida\n Copyright (C) 2008 Ralph Schreyer\n Copyright (C) 2008 Klaus Spanderen\n Copyright (C) 2014 Johannes Göttker-Schnetmann\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 triplebandlinearop.hpp\n    \\brief general triple band linear operator\n*/\n\n#ifndef quantlib_triple_band_linear_op_hpp\n#define quantlib_triple_band_linear_op_hpp\n\n#include <ql/methods/finitedifferences/operators/fdmlinearop.hpp>\n#if !defined(QL_USE_STD_UNIQUE_PTR)\n#include <boost/shared_array.hpp>\n#endif\n#include <memory>\n\nnamespace QuantLib {\n\n    class FdmMesher;\n    \n    class TripleBandLinearOp : public FdmLinearOp {\n      public:\n        TripleBandLinearOp(Size direction,\n                           const ext::shared_ptr<FdmMesher>& mesher);\n\n        TripleBandLinearOp(const TripleBandLinearOp& m);\n        TripleBandLinearOp(TripleBandLinearOp&& m) QL_NOEXCEPT;\n        #ifdef QL_USE_DISPOSABLE\n        TripleBandLinearOp(const Disposable<TripleBandLinearOp>& m);\n        #endif\n        TripleBandLinearOp& operator=(const TripleBandLinearOp& m);\n        TripleBandLinearOp& operator=(TripleBandLinearOp&& m) QL_NOEXCEPT;\n        #ifdef QL_USE_DISPOSABLE\n        TripleBandLinearOp& operator=(const Disposable<TripleBandLinearOp>& m);\n        #endif\n\n        Disposable<Array> apply(const Array& r) const override;\n        Disposable<Array> solve_splitting(const Array& r, Real a,\n                                          Real b = 1.0) const;\n\n        Disposable<TripleBandLinearOp> mult(const Array& u) const;\n        // interpret u as the diagonal of a diagonal matrix, multiplied on LHS\n        Disposable<TripleBandLinearOp> multR(const Array& u) const;\n        // interpret u as the diagonal of a diagonal matrix, multiplied on RHS\n        Disposable<TripleBandLinearOp> add(const TripleBandLinearOp& m) const;\n        Disposable<TripleBandLinearOp> add(const Array& u) const;\n\n        // some very basic linear algebra routines\n        void axpyb(const Array& a, const TripleBandLinearOp& x,\n                   const TripleBandLinearOp& y, const Array& b);\n\n        void swap(TripleBandLinearOp& m);\n\n#if !defined(QL_NO_UBLAS_SUPPORT)\n        Disposable<SparseMatrix> toMatrix() const override;\n#endif\n\n      protected:\n        TripleBandLinearOp() = default;\n\n        Size direction_;\n        #if !defined(QL_USE_STD_UNIQUE_PTR)\n        boost::shared_array<Size> i0_, i2_;\n        boost::shared_array<Size> reverseIndex_;\n        boost::shared_array<Real> lower_, diag_, upper_;\n        #else\n        std::unique_ptr<Size[]> i0_, i2_;\n        std::unique_ptr<Size[]> reverseIndex_;\n        std::unique_ptr<Real[]> lower_, diag_, upper_;\n        #endif\n\n        ext::shared_ptr<FdmMesher> mesher_;\n    };\n\n\n    inline TripleBandLinearOp::TripleBandLinearOp(TripleBandLinearOp&& m) QL_NOEXCEPT {\n        swap(m);\n    }\n\n    inline TripleBandLinearOp& TripleBandLinearOp::operator=(const TripleBandLinearOp& m) {\n        TripleBandLinearOp tmp(m);\n        swap(tmp);\n        return *this;\n    }\n\n    inline TripleBandLinearOp& TripleBandLinearOp::operator=(TripleBandLinearOp&& m) QL_NOEXCEPT {\n        swap(m);\n        return *this;\n    }\n\n}\n\n#endif\n", "meta": {"hexsha": "f3056323c7da80c5632d6798e7657bc4eafb2e40", "size": 3895, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ql/methods/finitedifferences/operators/triplebandlinearop.hpp", "max_stars_repo_name": "autoantwort/QuantLib", "max_stars_repo_head_hexsha": "3261dde01de1b9c7ceb6c0cd1a2920da6e38eb3c", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-02-27T22:25:54.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-27T22:25:54.000Z", "max_issues_repo_path": "ql/methods/finitedifferences/operators/triplebandlinearop.hpp", "max_issues_repo_name": "autoantwort/QuantLib", "max_issues_repo_head_hexsha": "3261dde01de1b9c7ceb6c0cd1a2920da6e38eb3c", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 16.0, "max_issues_repo_issues_event_min_datetime": "2020-11-23T08:00:31.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-28T07:57:41.000Z", "max_forks_repo_path": "ql/methods/finitedifferences/operators/triplebandlinearop.hpp", "max_forks_repo_name": "fabianfh/QuantLib", "max_forks_repo_head_hexsha": "44230ddeb91629015ff6ff9aa079b07912dd2002", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2016-11-01T13:51:45.000Z", "max_forks_repo_forks_event_max_datetime": "2016-11-01T13:51:45.000Z", "avg_line_length": 34.4690265487, "max_line_length": 98, "alphanum_fraction": 0.6919127086, "num_tokens": 945, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.668880247169804, "lm_q2_score": 0.47657965106367595, "lm_q1q2_score": 0.3187747147995705}}
{"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_MOD_STER_HPP\n#define BOOST_GEOMETRY_PROJECTIONS_MOD_STER_HPP\n\n#include <boost/geometry/util/math.hpp>\n#include <boost/math/special_functions/hypot.hpp>\n\n#include <boost/geometry/srs/projections/impl/base_static.hpp>\n#include <boost/geometry/srs/projections/impl/base_dynamic.hpp>\n#include <boost/geometry/srs/projections/impl/projects.hpp>\n#include <boost/geometry/srs/projections/impl/factory_entry.hpp>\n#include <boost/geometry/srs/projections/impl/aasincos.hpp>\n#include <boost/geometry/srs/projections/impl/pj_zpoly1.hpp>\n\nnamespace boost { namespace geometry\n{\n\nnamespace srs { namespace par4\n{\n    struct mil_os {}; // Miller Oblated Stereographic\n    struct lee_os {}; // Lee Oblated Stereographic\n    struct gs48 {}; // Mod. Stereographic of 48 U.S.\n    struct alsk {}; // Mod. Stereographic of Alaska\n    struct gs50 {}; // Mod. Stereographic of 50 U.S.\n\n}} //namespace srs::par4\n\nnamespace projections\n{\n    #ifndef DOXYGEN_NO_DETAIL\n    namespace detail { namespace mod_ster\n    {\n\n            static const double epsilon = 1e-12;\n\n            template <typename T>\n            struct par_mod_ster\n            {\n                pj_complex<T> *zcoeff;\n                T          cchio, schio;\n                int        n;\n            };\n\n            /* based upon Snyder and Linck, USGS-NMD */\n\n            // template class, using CRTP to implement forward/inverse\n            template <typename T, typename Parameters>\n            struct base_mod_ster_ellipsoid\n                : public base_t_fi<base_mod_ster_ellipsoid<T, Parameters>, T, Parameters>\n            {\n                par_mod_ster<T> m_proj_parm;\n\n                inline base_mod_ster_ellipsoid(const Parameters& par)\n                    : base_t_fi<base_mod_ster_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& lp_lon, T& lp_lat, T& xy_x, T& xy_y) const\n                {\n                    static const T half_pi = detail::half_pi<T>();\n\n                    T sinlon, coslon, esphi, chi, schi, cchi, s;\n                    pj_complex<T> p;\n\n                    sinlon = sin(lp_lon);\n                    coslon = cos(lp_lon);\n                    esphi = this->m_par.e * sin(lp_lat);\n                    chi = 2. * atan(tan((half_pi + lp_lat) * .5) *\n                        pow((1. - esphi) / (1. + esphi), this->m_par.e * .5)) - half_pi;\n                    schi = sin(chi);\n                    cchi = cos(chi);\n                    s = 2. / (1. + this->m_proj_parm.schio * schi + this->m_proj_parm.cchio * cchi * coslon);\n                    p.r = s * cchi * sinlon;\n                    p.i = s * (this->m_proj_parm.cchio * schi - this->m_proj_parm.schio * cchi * coslon);\n                    p = pj_zpoly1(p, this->m_proj_parm.zcoeff, this->m_proj_parm.n);\n                    xy_x = p.r;\n                    xy_y = p.i;\n                }\n\n                // INVERSE(e_inverse)  ellipsoid\n                // Project coordinates from cartesian (x, y) to geographic (lon, lat)\n                inline void inv(T& xy_x, T& xy_y, T& lp_lon, T& lp_lat) const\n                {\n                    static const T half_pi = detail::half_pi<T>();\n\n                    int nn;\n                    pj_complex<T> p, fxy, fpxy, dp;\n                    T den, rh = 0, z, sinz = 0, cosz = 0, chi, phi = 0, dphi, esphi;\n\n                    p.r = xy_x;\n                    p.i = xy_y;\n                    for (nn = 20; nn ;--nn) {\n                        fxy = pj_zpolyd1(p, this->m_proj_parm.zcoeff, this->m_proj_parm.n, &fpxy);\n                        fxy.r -= xy_x;\n                        fxy.i -= xy_y;\n                        den = fpxy.r * fpxy.r + fpxy.i * fpxy.i;\n                        dp.r = -(fxy.r * fpxy.r + fxy.i * fpxy.i) / den;\n                        dp.i = -(fxy.i * fpxy.r - fxy.r * fpxy.i) / den;\n                        p.r += dp.r;\n                        p.i += dp.i;\n                        if ((fabs(dp.r) + fabs(dp.i)) <= epsilon)\n                            break;\n                    }\n                    if (nn) {\n                        rh = boost::math::hypot(p.r, p.i);\n                        z = 2. * atan(.5 * rh);\n                        sinz = sin(z);\n                        cosz = cos(z);\n                        lp_lon = this->m_par.lam0;\n                        if (fabs(rh) <= epsilon) {\n                            /* if we end up here input coordinates were (0,0).\n                             * pj_inv() adds P->lam0 to lp.lam, this way we are\n                             * sure to get the correct offset */\n                            lp_lon = 0.0;\n                            lp_lat = this->m_par.phi0;\n                            return;\n                        }\n                        chi = aasin(cosz * this->m_proj_parm.schio + p.i * sinz * this->m_proj_parm.cchio / rh);\n                        phi = chi;\n                        for (nn = 20; nn ;--nn) {\n                            esphi = this->m_par.e * sin(phi);\n                            dphi = 2. * atan(tan((half_pi + chi) * .5) *\n                                pow((1. + esphi) / (1. - esphi), this->m_par.e * .5)) - half_pi - phi;\n                            phi += dphi;\n                            if (fabs(dphi) <= epsilon)\n                                break;\n                        }\n                    }\n                    if (nn) {\n                        lp_lat = phi;\n                        lp_lon = atan2(p.r * sinz, rh * this->m_proj_parm.cchio * cosz - p.i *\n                            this->m_proj_parm.schio * sinz);\n                    } else\n                        lp_lon = lp_lat = HUGE_VAL;\n                }\n\n                static inline std::string get_name()\n                {\n                    return \"mod_ster_ellipsoid\";\n                }\n\n            };\n\n            template <typename Parameters, typename T>\n            inline void setup(Parameters& par, par_mod_ster<T>& proj_parm)  /* general initialization */\n            {\n                static T const half_pi = detail::half_pi<T>();\n\n                T esphi, chio;\n\n                if (par.es != 0.0) {\n                    esphi = par.e * sin(par.phi0);\n                    chio = 2. * atan(tan((half_pi + par.phi0) * .5) *\n                        pow((1. - esphi) / (1. + esphi), par.e * .5)) - half_pi;\n                } else\n                    chio = par.phi0;\n                proj_parm.schio = sin(chio);\n                proj_parm.cchio = cos(chio);\n            }\n\n\n            /* Miller Oblated Stereographic */\n            template <typename Parameters, typename T>\n            inline void setup_mil_os(Parameters& par, par_mod_ster<T>& proj_parm)\n            {\n                static const T d2r = geometry::math::d2r<T>();\n\n                static pj_complex<T> AB[] = {\n                    {0.924500, 0.},\n                    {0.,       0.},\n                    {0.019430, 0.}\n                };\n\n                proj_parm.n = 2;\n                par.lam0 = d2r * 20.;\n                par.phi0 = d2r * 18.;\n                proj_parm.zcoeff = AB;\n                par.es = 0.;\n\n                setup(par, proj_parm);\n            }\n\n            /* Lee Oblated Stereographic */\n            template <typename Parameters, typename T>\n            inline void setup_lee_os(Parameters& par, par_mod_ster<T>& proj_parm)\n            {\n                static const T d2r = geometry::math::d2r<T>();\n\n                static pj_complex<T> AB[] = {\n                    { 0.721316,   0.},\n                    { 0.,         0.},\n                    {-0.0088162, -0.00617325}\n                };\n\n                proj_parm.n = 2;\n                par.lam0 = d2r * -165.;\n                par.phi0 = d2r * -10.;\n                proj_parm.zcoeff = AB;\n                par.es = 0.;\n\n                setup(par, proj_parm);\n            }\n\n            // Mod. Stererographics of 48 U.S.\n            template <typename Parameters, typename T>\n            inline void setup_gs48(Parameters& par, par_mod_ster<T>& proj_parm)\n            {\n                static const T d2r = geometry::math::d2r<T>();\n\n                static pj_complex<T> AB[] = { /* 48 United States */\n                    { 0.98879,  0.},\n                    { 0.,       0.},\n                    {-0.050909, 0.},\n                    { 0.,       0.},\n                    { 0.075528, 0.}\n                };\n\n                proj_parm.n = 4;\n                par.lam0 = d2r * -96.;\n                par.phi0 = d2r * -39.;\n                proj_parm.zcoeff = AB;\n                par.es = 0.;\n                par.a = 6370997.;\n\n                setup(par, proj_parm);\n            }\n\n            // Mod. Stererographics of Alaska\n            template <typename Parameters, typename T>\n            inline void setup_alsk(Parameters& par, par_mod_ster<T>& proj_parm)\n            {\n                static const T d2r = geometry::math::d2r<T>();\n\n                static pj_complex<T> ABe[] = { /* Alaska ellipsoid */\n                    { .9945303, 0.},\n                    { .0052083, -.0027404},\n                    { .0072721,  .0048181},\n                    {-.0151089, -.1932526},\n                    { .0642675, -.1381226},\n                    { .3582802, -.2884586}\n                };\n\n                static pj_complex<T> ABs[] = { /* Alaska sphere */\n                    { .9972523, 0.},\n                    { .0052513, -.0041175},\n                    { .0074606,  .0048125},\n                    {-.0153783, -.1968253},\n                    { .0636871, -.1408027},\n                    { .3660976, -.2937382}\n                };\n\n                proj_parm.n = 5;\n                par.lam0 = d2r * -152.;\n                par.phi0 = d2r * 64.;\n                if (par.es != 0.0) { /* fixed ellipsoid/sphere */\n                    proj_parm.zcoeff = ABe;\n                    par.a = 6378206.4;\n                    par.e = sqrt(par.es = 0.00676866);\n                } else {\n                    proj_parm.zcoeff = ABs;\n                    par.a = 6370997.;\n                }\n\n                setup(par, proj_parm);\n            }\n\n            // Mod. Stererographics of 50 U.S.\n            template <typename Parameters, typename T>\n            inline void setup_gs50(Parameters& par, par_mod_ster<T>& proj_parm)\n            {\n                static const T d2r = geometry::math::d2r<T>();\n\n                static pj_complex<T> ABe[] = { /* GS50 ellipsoid */\n                    { .9827497, 0.},\n                    { .0210669,  .0053804},\n                    {-.1031415, -.0571664},\n                    {-.0323337, -.0322847},\n                    { .0502303,  .1211983},\n                    { .0251805,  .0895678},\n                    {-.0012315, -.1416121},\n                    { .0072202, -.1317091},\n                    {-.0194029,  .0759677},\n                    {-.0210072,  .0834037}\n                };\n                static pj_complex<T> ABs[] = { /* GS50 sphere */\n                    { .9842990, 0.},\n                    { .0211642,  .0037608},\n                    {-.1036018, -.0575102},\n                    {-.0329095, -.0320119},\n                    { .0499471,  .1223335},\n                    { .0260460,  .0899805},\n                    { .0007388, -.1435792},\n                    { .0075848, -.1334108},\n                    {-.0216473,  .0776645},\n                    {-.0225161,  .0853673}\n                };\n\n                proj_parm.n = 9;\n                par.lam0 = d2r * -120.;\n                par.phi0 = d2r * 45.;\n                if (par.es != 0.0) { /* fixed ellipsoid/sphere */\n                    proj_parm.zcoeff = ABe;\n                    par.a = 6378206.4;\n                    par.e = sqrt(par.es = 0.00676866);\n                } else {\n                    proj_parm.zcoeff = ABs;\n                    par.a = 6370997.;\n                }\n\n                setup(par, proj_parm);\n            }\n\n    }} // namespace detail::mod_ster\n    #endif // doxygen\n\n    /*!\n        \\brief Miller Oblated Stereographic projection\n        \\ingroup projections\n        \\tparam Geographic latlong point type\n        \\tparam Cartesian xy point type\n        \\tparam Parameters parameter type\n        \\par Projection characteristics\n         - Azimuthal (mod)\n        \\par Example\n        \\image html ex_mil_os.gif\n    */\n    template <typename T, typename Parameters>\n    struct mil_os_ellipsoid : public detail::mod_ster::base_mod_ster_ellipsoid<T, Parameters>\n    {\n        inline mil_os_ellipsoid(const Parameters& par) : detail::mod_ster::base_mod_ster_ellipsoid<T, Parameters>(par)\n        {\n            detail::mod_ster::setup_mil_os(this->m_par, this->m_proj_parm);\n        }\n    };\n\n    /*!\n        \\brief Lee Oblated Stereographic projection\n        \\ingroup projections\n        \\tparam Geographic latlong point type\n        \\tparam Cartesian xy point type\n        \\tparam Parameters parameter type\n        \\par Projection characteristics\n         - Azimuthal (mod)\n        \\par Example\n        \\image html ex_lee_os.gif\n    */\n    template <typename T, typename Parameters>\n    struct lee_os_ellipsoid : public detail::mod_ster::base_mod_ster_ellipsoid<T, Parameters>\n    {\n        inline lee_os_ellipsoid(const Parameters& par) : detail::mod_ster::base_mod_ster_ellipsoid<T, Parameters>(par)\n        {\n            detail::mod_ster::setup_lee_os(this->m_par, this->m_proj_parm);\n        }\n    };\n\n    /*!\n        \\brief Mod. Stererographics of 48 U.S. projection\n        \\ingroup projections\n        \\tparam Geographic latlong point type\n        \\tparam Cartesian xy point type\n        \\tparam Parameters parameter type\n        \\par Projection characteristics\n         - Azimuthal (mod)\n        \\par Example\n        \\image html ex_gs48.gif\n    */\n    template <typename T, typename Parameters>\n    struct gs48_ellipsoid : public detail::mod_ster::base_mod_ster_ellipsoid<T, Parameters>\n    {\n        inline gs48_ellipsoid(const Parameters& par) : detail::mod_ster::base_mod_ster_ellipsoid<T, Parameters>(par)\n        {\n            detail::mod_ster::setup_gs48(this->m_par, this->m_proj_parm);\n        }\n    };\n\n    /*!\n        \\brief Mod. Stererographics of Alaska projection\n        \\ingroup projections\n        \\tparam Geographic latlong point type\n        \\tparam Cartesian xy point type\n        \\tparam Parameters parameter type\n        \\par Projection characteristics\n         - Azimuthal (mod)\n        \\par Example\n        \\image html ex_alsk.gif\n    */\n    template <typename T, typename Parameters>\n    struct alsk_ellipsoid : public detail::mod_ster::base_mod_ster_ellipsoid<T, Parameters>\n    {\n        inline alsk_ellipsoid(const Parameters& par) : detail::mod_ster::base_mod_ster_ellipsoid<T, Parameters>(par)\n        {\n            detail::mod_ster::setup_alsk(this->m_par, this->m_proj_parm);\n        }\n    };\n\n    /*!\n        \\brief Mod. Stererographics of 50 U.S. projection\n        \\ingroup projections\n        \\tparam Geographic latlong point type\n        \\tparam Cartesian xy point type\n        \\tparam Parameters parameter type\n        \\par Projection characteristics\n         - Azimuthal (mod)\n        \\par Example\n        \\image html ex_gs50.gif\n    */\n    template <typename T, typename Parameters>\n    struct gs50_ellipsoid : public detail::mod_ster::base_mod_ster_ellipsoid<T, Parameters>\n    {\n        inline gs50_ellipsoid(const Parameters& par) : detail::mod_ster::base_mod_ster_ellipsoid<T, Parameters>(par)\n        {\n            detail::mod_ster::setup_gs50(this->m_par, this->m_proj_parm);\n        }\n    };\n\n    #ifndef DOXYGEN_NO_DETAIL\n    namespace detail\n    {\n\n        // Static projection\n        BOOST_GEOMETRY_PROJECTIONS_DETAIL_STATIC_PROJECTION(srs::par4::mil_os, mil_os_ellipsoid, mil_os_ellipsoid)\n        BOOST_GEOMETRY_PROJECTIONS_DETAIL_STATIC_PROJECTION(srs::par4::lee_os, lee_os_ellipsoid, lee_os_ellipsoid)\n        BOOST_GEOMETRY_PROJECTIONS_DETAIL_STATIC_PROJECTION(srs::par4::gs48, gs48_ellipsoid, gs48_ellipsoid)\n        BOOST_GEOMETRY_PROJECTIONS_DETAIL_STATIC_PROJECTION(srs::par4::alsk, alsk_ellipsoid, alsk_ellipsoid)\n        BOOST_GEOMETRY_PROJECTIONS_DETAIL_STATIC_PROJECTION(srs::par4::gs50, gs50_ellipsoid, gs50_ellipsoid)\n\n        // Factory entry(s)\n        template <typename T, typename Parameters>\n        class mil_os_entry : public detail::factory_entry<T, Parameters>\n        {\n            public :\n                virtual base_v<T, Parameters>* create_new(const Parameters& par) const\n                {\n                    return new base_v_fi<mil_os_ellipsoid<T, Parameters>, T, Parameters>(par);\n                }\n        };\n\n        template <typename T, typename Parameters>\n        class lee_os_entry : public detail::factory_entry<T, Parameters>\n        {\n            public :\n                virtual base_v<T, Parameters>* create_new(const Parameters& par) const\n                {\n                    return new base_v_fi<lee_os_ellipsoid<T, Parameters>, T, Parameters>(par);\n                }\n        };\n\n        template <typename T, typename Parameters>\n        class gs48_entry : public detail::factory_entry<T, Parameters>\n        {\n            public :\n                virtual base_v<T, Parameters>* create_new(const Parameters& par) const\n                {\n                    return new base_v_fi<gs48_ellipsoid<T, Parameters>, T, Parameters>(par);\n                }\n        };\n\n        template <typename T, typename Parameters>\n        class alsk_entry : public detail::factory_entry<T, Parameters>\n        {\n            public :\n                virtual base_v<T, Parameters>* create_new(const Parameters& par) const\n                {\n                    return new base_v_fi<alsk_ellipsoid<T, Parameters>, T, Parameters>(par);\n                }\n        };\n\n        template <typename T, typename Parameters>\n        class gs50_entry : public detail::factory_entry<T, Parameters>\n        {\n            public :\n                virtual base_v<T, Parameters>* create_new(const Parameters& par) const\n                {\n                    return new base_v_fi<gs50_ellipsoid<T, Parameters>, T, Parameters>(par);\n                }\n        };\n\n        template <typename T, typename Parameters>\n        inline void mod_ster_init(detail::base_factory<T, Parameters>& factory)\n        {\n            factory.add_to_factory(\"mil_os\", new mil_os_entry<T, Parameters>);\n            factory.add_to_factory(\"lee_os\", new lee_os_entry<T, Parameters>);\n            factory.add_to_factory(\"gs48\", new gs48_entry<T, Parameters>);\n            factory.add_to_factory(\"alsk\", new alsk_entry<T, Parameters>);\n            factory.add_to_factory(\"gs50\", new gs50_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_MOD_STER_HPP\n\n", "meta": {"hexsha": "cb22c955d22db9aca29a2e9fe0e76aadbb776bb8", "size": 20870, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/geometry/srs/projections/proj/mod_ster.hpp", "max_stars_repo_name": "jonasdmentia/geometry", "max_stars_repo_head_hexsha": "097f6fdbe98118be82cd1917cc72c3c6a37bdf30", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/boost/geometry/srs/projections/proj/mod_ster.hpp", "max_issues_repo_name": "jonasdmentia/geometry", "max_issues_repo_head_hexsha": "097f6fdbe98118be82cd1917cc72c3c6a37bdf30", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/boost/geometry/srs/projections/proj/mod_ster.hpp", "max_forks_repo_name": "jonasdmentia/geometry", "max_forks_repo_head_hexsha": "097f6fdbe98118be82cd1917cc72c3c6a37bdf30", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.9365671642, "max_line_length": 118, "alphanum_fraction": 0.5174413033, "num_tokens": 4979, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7217432182679956, "lm_q2_score": 0.44167300566462564, "lm_q1q2_score": 0.31877449653048556}}
{"text": "#include \"NormalMapBuilder.h\"\n\n#include <cmath>\n#include <algorithm>\n\n#include <cglib/vec.h>\n\n#include <boost/math/constants/constants.hpp>\n\nnamespace carto { namespace vt {\n    NormalMapBuilder::NormalMapBuilder(const std::array<float, 4>& rgbaHeightScale, std::uint8_t alpha) : _rgbaHeightScale(rgbaHeightScale), _alpha(alpha) {\n    }\n\n    std::shared_ptr<const Bitmap> NormalMapBuilder::buildNormalMapFromHeightMap(const TileId& tileId, const std::shared_ptr<const Bitmap>& bitmap) const {\n        if (!bitmap) {\n            return bitmap;\n        }\n\n        int width = bitmap->width;\n        int height = bitmap->height;\n        std::vector<std::uint32_t> data(width * height, 0);\n\n        auto getInterpolatedHeight = [&](int x, int y) {\n            int x0 = x, x1 = x;\n            int y0 = y, y1 = y;\n            if (x < 0) {\n                x0 = 0;\n                x1 = 1;\n            }\n            if (x >= width) {\n                x0 = width - 1;\n                x1 = width - 2;\n            }\n            if (y < 0) {\n                y0 = 0;\n                y1 = 1;\n            }\n            if (y >= height) {\n                y0 = height - 1;\n                y1 = height - 2;\n            }\n\n            if (x0 == x1 && y0 == y1) {\n                return unpackHeight(bitmap->data[(y0 * width) + x0]);\n            }\n            return 2 * unpackHeight(bitmap->data[(y0 * width) + x0]) - unpackHeight(bitmap->data[(y1 * width) + x1]);\n        };\n\n        if (width >= 2 && height >= 2) {\n            float heights[3][3];\n            for (int y = 0; y < height; y++) {\n                double y1 = boost::math::constants::pi<double>() * ((tileId.y + (height - y - 0.5) / height) / (1 << tileId.zoom) - 0.5);\n                double rz = std::tanh(y1);\n                double ss = std::sqrt(std::max(0.0, 1.0 - rz * rz));\n\n                for (int dy = 0; dy < 3; dy++) {\n                    heights[dy][1] = getInterpolatedHeight(-1, y + dy - 1);\n                    heights[dy][2] = getInterpolatedHeight( 0, y + dy - 1);\n                }\n                for (int x = 0; x < width; x++) {\n                    for (int dy = 0; dy < 3; dy++) {\n                        heights[dy][0] = heights[dy][1];\n                        heights[dy][1] = heights[dy][2];\n                        heights[dy][2] = getInterpolatedHeight(x + 1, y + dy - 1);\n                    }\n\n                    float dx = (heights[0][2] + 2 * heights[1][2] + heights[2][2]) - (heights[0][0] + 2 * heights[1][0] + heights[2][0]);\n                    float dy = (heights[2][0] + 2 * heights[2][1] + heights[2][2]) - (heights[0][0] + 2 * heights[0][1] + heights[0][2]);\n                    float dz = 8.0f * static_cast<float>(ss);\n\n                    data[y * width + x] = packNormal(dx, dy, dz);\n                }\n            }\n        }\n        return std::make_shared<Bitmap>(width, height, std::move(data));\n    }\n\n    float NormalMapBuilder::unpackHeight(std::uint32_t color) const {\n        union {\n            std::uint32_t u32;\n            std::uint8_t u8[sizeof(std::uint32_t)];\n        } packedColor;\n        packedColor.u32 = color;\n        float height = packedColor.u8[0] * _rgbaHeightScale[0];\n        height += packedColor.u8[1] * _rgbaHeightScale[1];\n        height += packedColor.u8[2] * _rgbaHeightScale[2];\n        height += packedColor.u8[3] * _rgbaHeightScale[3];\n        return height;\n    }\n\n    std::uint32_t NormalMapBuilder::packNormal(float dx, float dy, float dz) const {\n        union {\n            std::uint32_t u32;\n            std::uint8_t u8[sizeof(std::uint32_t)];\n        } packedNormal;\n        cglib::vec3<float> normal = cglib::unit(cglib::vec3<float>(dx, dy, dz));\n        packedNormal.u8[0] = static_cast<std::uint8_t>((normal(0) + 1.0f) * 127.5f);\n        packedNormal.u8[1] = static_cast<std::uint8_t>((normal(1) + 1.0f) * 127.5f);\n        packedNormal.u8[2] = static_cast<std::uint8_t>((normal(2) + 1.0f) * 127.5f);\n        packedNormal.u8[3] = _alpha;\n        return packedNormal.u32;\n    }\n} }\n", "meta": {"hexsha": "40f9f366fe2db8a9ef4c673775c29d59b5f705b7", "size": 4017, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "vt/src/vt/NormalMapBuilder.cpp", "max_stars_repo_name": "CartoDB/mobile-carto-libs", "max_stars_repo_head_hexsha": "c1def8e8d91a98adff1aaef440c5d207be8ffe52", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2018-06-27T17:43:35.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-29T18:50:49.000Z", "max_issues_repo_path": "vt/src/vt/NormalMapBuilder.cpp", "max_issues_repo_name": "CartoDB/mobile-carto-libs", "max_issues_repo_head_hexsha": "c1def8e8d91a98adff1aaef440c5d207be8ffe52", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 22.0, "max_issues_repo_issues_event_min_datetime": "2019-04-10T06:38:09.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-20T08:12:02.000Z", "max_forks_repo_path": "vt/src/vt/NormalMapBuilder.cpp", "max_forks_repo_name": "CartoDB/mobile-carto-libs", "max_forks_repo_head_hexsha": "c1def8e8d91a98adff1aaef440c5d207be8ffe52", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2019-03-12T10:25:20.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-28T10:18:56.000Z", "avg_line_length": 38.625, "max_line_length": 156, "alphanum_fraction": 0.4869305452, "num_tokens": 1175, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7217431943271999, "lm_q2_score": 0.4416730056646256, "lm_q1q2_score": 0.31877448595648233}}
{"text": "// Distributed under the MIT License.\n// See LICENSE.txt for details.\n\n#include \"PointwiseFunctions/AnalyticSolutions/GeneralRelativity/Tov.hpp\"\n\n// Need Boost MultiArray because it is used internally by ODEINT\n#include \"DataStructures/BoostMultiArray.hpp\"  // IWYU pragma: keep\n\n#include <algorithm>\n#include <array>\n#include <boost/numeric/odeint.hpp>  // IWYU pragma: keep\n#include <cmath>\n#include <cstddef>\n#include <functional>\n#include <ostream>\n#include <pup.h>\n#include <vector>\n\n#include \"DataStructures/DataVector.hpp\"\n#include \"DataStructures/Tensor/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/GenerateInstantiations.hpp\"\n#include \"Utilities/Gsl.hpp\"\n#include \"Utilities/MakeWithValue.hpp\"\n\n// IWYU pragma: no_include <boost/numeric/odeint/integrate/integrate_adaptive.hpp>\n// IWYU pragma: no_include <boost/numeric/odeint/stepper/controlled_runge_kutta.hpp>\n// IWYU pragma: no_include <boost/numeric/odeint/stepper/dense_output_runge_kutta.hpp>\n// IWYU pragma: no_include <boost/numeric/odeint/stepper/generation/make_dense_output.hpp>\n// IWYU pragma: no_include <boost/numeric/odeint/stepper/runge_kutta_dopri5.hpp>\n// IWYU pragma: no_include <complex>\n\n// IWYU pragma: no_forward_declare boost::numeric::odeint::controlled_runge_kutta\n// IWYU pragma: no_forward_declare EquationsOfState::EquationOfState\n// IWYU pragma: no_forward_declare Tensor\n\nnamespace {\n\nvoid lindblom_rhs(\n    const gsl::not_null<std::array<double, 2>*> dvars,\n    const std::array<double, 2>& vars, const double log_enthalpy,\n    const EquationsOfState::EquationOfState<true, 1>& 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  } else {\n    const double common_factor =\n        (1.0 - 2.0 * mass_over_radius) /\n        (4.0 * M_PI * radius_squared * pressure + mass_over_radius);\n    d_radius_squared = -2.0 * radius_squared * common_factor;\n    d_mass_over_radius =\n        -(4.0 * M_PI * radius_squared * energy_density - mass_over_radius) *\n        common_factor;\n  }\n}\n\nclass Observer {\n public:\n  void operator()(const std::array<double, 2>& vars,\n                  const double current_log_enthalpy) {\n    radius.push_back(std::sqrt(vars[0]));\n    mass_over_radius.push_back(vars[1]);\n    log_enthalpy.push_back(current_log_enthalpy);\n  }\n  std::vector<double> radius;\n  std::vector<double> mass_over_radius;\n  std::vector<double> log_enthalpy;\n};\n\n}  // namespace\n\nnamespace gr::Solutions {\n\nTovSolution::TovSolution(\n    const EquationsOfState::EquationOfState<true, 1>& equation_of_state,\n    const double central_mass_density,\n    const double log_enthalpy_at_outer_radius, const double absolute_tolerance,\n    const double relative_tolerance) {\n  std::array<double, 2> u_and_v = {{0.0, 0.0}};\n  std::array<double, 2> dudh_and_dvdh{};\n  const double central_log_enthalpy =\n      std::log(get(equation_of_state.specific_enthalpy_from_density(\n          Scalar<double>{central_mass_density})));\n  lindblom_rhs(&dudh_and_dvdh, u_and_v, central_log_enthalpy,\n               equation_of_state);\n  const double initial_step = -std::min(std::abs(1.0 / dudh_and_dvdh[0]),\n                                        std::abs(1.0 / dudh_and_dvdh[1]));\n  using StateDopri5 =\n      boost::numeric::odeint::runge_kutta_dopri5<std::array<double, 2>>;\n  boost::numeric::odeint::dense_output_runge_kutta<\n      boost::numeric::odeint::controlled_runge_kutta<StateDopri5>>\n      dopri5 = make_dense_output(absolute_tolerance, relative_tolerance,\n                                 StateDopri5{});\n  Observer observer{};\n  boost::numeric::odeint::integrate_adaptive(\n      dopri5,\n      [&equation_of_state](const std::array<double, 2>& lindblom_u_and_v,\n                           std::array<double, 2>& lindblom_dudh_and_dvdh,\n                           const double lindblom_enthalpy) {\n        return lindblom_rhs(&lindblom_dudh_and_dvdh, lindblom_u_and_v,\n                            lindblom_enthalpy, equation_of_state);\n      },\n      u_and_v, central_log_enthalpy, log_enthalpy_at_outer_radius, initial_step,\n      std::ref(observer));\n  outer_radius_ = observer.radius.back();\n  const double total_mass_over_radius = observer.mass_over_radius.back();\n  total_mass_ = total_mass_over_radius * outer_radius_;\n  injection_energy_ = sqrt(1. - 2. * total_mass_ / outer_radius_);\n  mass_over_radius_interpolant_ =\n      intrp::BarycentricRational(observer.radius, observer.mass_over_radius, 5);\n  // log_enthalpy(radius) is almost linear so an interpolant of order 3\n  // maximizes precision\n  log_enthalpy_interpolant_ =\n      intrp::BarycentricRational(observer.radius, observer.log_enthalpy, 3);\n}\n\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\nvoid TovSolution::pup(PUP::er& p) {  // NOLINT\n  p | outer_radius_;\n  p | total_mass_;\n  p | injection_energy_;\n  p | mass_over_radius_interpolant_;\n  p | log_enthalpy_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\nGENERATE_INSTANTIATIONS(INSTANTIATE, (double, DataVector))\n\n#undef DTYPE\n\n}  // namespace gr::Solutions\n", "meta": {"hexsha": "71eae776714a0aa94eb978070e43d9713a129a7f", "size": 7413, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/PointwiseFunctions/AnalyticSolutions/GeneralRelativity/Tov.cpp", "max_stars_repo_name": "cnhzsyb/spectre", "max_stars_repo_head_hexsha": "0e4e2956da06b1dbf3f7213e0ffd0c41feaf9b5f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/PointwiseFunctions/AnalyticSolutions/GeneralRelativity/Tov.cpp", "max_issues_repo_name": "cnhzsyb/spectre", "max_issues_repo_head_hexsha": "0e4e2956da06b1dbf3f7213e0ffd0c41feaf9b5f", "max_issues_repo_licenses": ["MIT"], "max_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": "cnhzsyb/spectre", "max_forks_repo_head_hexsha": "0e4e2956da06b1dbf3f7213e0ffd0c41feaf9b5f", "max_forks_repo_licenses": ["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.7307692308, "max_line_length": 90, "alphanum_fraction": 0.6993120194, "num_tokens": 1991, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7279754371026367, "lm_q2_score": 0.4378234991142019, "lm_q1q2_score": 0.318724753141467}}
{"text": "#include <boost/math/special_functions/next.hpp>\n#include <boost/random.hpp>\n\n#include <algorithm>\n#include <limits>\n#include <vector>\n\n#include \"caffe/common.hpp\"\n#include \"caffe/util/math_functions.hpp\"\n#include \"caffe/util/rng.hpp\"\n\nnamespace caffe {\n\ntemplate<>\nvoid caffe_cpu_gemm<float>(const CBLAS_TRANSPOSE TransA,\n    const CBLAS_TRANSPOSE TransB, const int M, 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\n#ifndef CPU_ONLY\ntemplate<>\nvoid caffe_cpu_gemm<float16>(const CBLAS_TRANSPOSE TransA,\n    const CBLAS_TRANSPOSE TransB, const int M, const int N, const int K,\n    const float16 alpha, const float16* A, const float16* B, const float16 beta,\n    float16* C) {\n  if (M <= 0 || N <= 0 || K <= 0) {\n    return;\n  }\n  std::vector<float> a(M*K), b(K*N), c(M*N);\n  caffe_cpu_convert(a.size(), A, &a.front());\n  caffe_cpu_convert(b.size(), B, &b.front());\n  caffe_cpu_convert(c.size(), C, &c.front());\n  const int lda = (TransA == CblasNoTrans) ? K : M;\n  const int ldb = (TransB == CblasNoTrans) ? N : K;\n  cblas_sgemm(CblasRowMajor, TransA, TransB, M, N, K, static_cast<float>(alpha), &a.front(),\n      lda, &b.front(), ldb, static_cast<float>(beta), &c.front(), N);\n  caffe_cpu_convert(c.size(), &c.front(), C);\n}\n#endif\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\n#ifndef CPU_ONLY\ntemplate <>\nvoid caffe_cpu_gemv<float16>(const CBLAS_TRANSPOSE TransA, const int M,\n    const int N, const float16 alpha, const float16* A, const float16* x,\n    const float16 beta, float16* y) {\n  if (M <= 0 || N <= 0) {\n    return;\n  }\n  const int lx = (TransA == CblasNoTrans) ? N : M;\n  const int ly = (TransA == CblasNoTrans) ? M : N;\n  std::vector<float> a(M*N), xv(lx), yv(ly);\n  caffe_cpu_convert(a.size(), A, &a.front());\n  caffe_cpu_convert(xv.size(), x, &xv.front());\n  caffe_cpu_convert(yv.size(), y, &yv.front());\n  cblas_sgemv(CblasRowMajor, TransA, M, N, static_cast<float>(alpha), &a.front(), N,\n      &xv.front(), 1, static_cast<float>(beta), &yv.front(), 1);\n  caffe_cpu_convert(yv.size(), &yv.front(), y);\n}\n#endif\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\n#ifndef CPU_ONLY\ntemplate<>\nvoid caffe_axpy<float16>(const int N, const float16 alpha, const float16* X,\n    float16* Y) {\n  for (int i = 0; i < N; ++i) {\n    Y[i] = alpha * X[i] + Y[i];\n  }\n}\n#endif\n\ntemplate <typename Dtype>\nvoid caffe_set(const int N, const Dtype alpha, Dtype* Y) {\n  if (alpha == 0) {\n    memset(Y, 0, sizeof(Dtype) * N);  // NOLINT(caffe/alt_fn)\n    return;\n  }\n  for (int i = 0; i < N; ++i) {\n    Y[i] = alpha;\n  }\n}\n\ntemplate void caffe_set<int>(const int N, const int alpha, int* Y);\ntemplate void caffe_set<float>(const int N, const float alpha, float* Y);\ntemplate void caffe_set<double>(const int N, const double alpha, double* Y);\n\n#ifndef CPU_ONLY\ntemplate void caffe_set<float16>(const int N, const float16 alpha, float16* Y);\n#endif\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\n#ifndef CPU_ONLY\ntemplate <>\nvoid caffe_add_scalar(const int N, const float16 alpha, float16* Y) {\n  for (int i = 0; i < N; ++i) {\n    Y[i] = Y[i] + alpha;\n  }\n}\n#endif\n\ntemplate <typename Dtype>\nvoid caffe_copy(const int N, const Dtype* X, Dtype* Y) {\n  if (X != Y) {\n    if (Caffe::mode() == Caffe::GPU) {\n#ifndef CPU_ONLY\n      caffe_gpu_memcpy(sizeof(Dtype) * N, X, Y);\n#else\n      NO_GPU;\n#endif\n    } else {\n      memcpy(Y, X, sizeof(Dtype) * N);  // NOLINT(caffe/alt_fn)\n    }\n  }\n}\n\ntemplate void caffe_copy<int>(const int N, const int* X, int* Y);\ntemplate void caffe_copy<unsigned int>(const int N, const unsigned int* X,\n    unsigned int* Y);\ntemplate void caffe_copy<float>(const int N, const float* X, float* Y);\ntemplate void caffe_copy<double>(const int N, const double* X, double* Y);\n\n#ifndef CPU_ONLY\ntemplate void caffe_copy<float16>(const int N, const float16* X, float16* Y);\n#endif\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\n#ifndef CPU_ONLY\ntemplate <>\nvoid caffe_scal<float16>(const int N, const float16 alpha, float16 *X) {\n  // cblas_hscal(N, alpha, X, 1); ?\n  for (int i = 0; i < N; ++i) {\n    X[i] = alpha * X[i];\n  }\n}\n#endif\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\n#ifndef CPU_ONLY\ntemplate <>\nvoid caffe_cpu_axpby<float16>(const int N, const float16 alpha,\n    const float16* X, const float16 beta, float16* Y) {\n  for (int i = 0; i < N; ++i) {\n    Y[i] = alpha * X[i] + beta * Y[i];\n  }\n}\n#endif\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\n#ifndef CPU_ONLY\ntemplate <>\nvoid caffe_add<float16>(const int n, const float16* a, const float16* b,\n    float16* y) {\n  for (int i = 0; i < n; ++i) {\n    y[i] = a[i] + b[i];\n  }\n}\n#endif\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\n#ifndef CPU_ONLY\ntemplate <>\nvoid caffe_sub<float16>(const int n, const float16* a, const float16* b,\n    float16* y) {\n  for (int i = 0; i < n; ++i) {\n    y[i] = a[i] - b[i];\n  }\n}\n#endif\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\n#ifndef CPU_ONLY\ntemplate <>\nvoid caffe_mul<float16>(const int n, const float16* a, const float16* b, float16* y) {\n  for (int i = 0; i < n; ++i) {\n    //  vhMul(n, a, b, y);\n    y[i] = a[i] * b[i];\n  }\n}\n#endif\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\n#ifndef CPU_ONLY\ntemplate <>\nvoid caffe_div<float16>(const int n, const float16* a, const float16* b, float16* y) {\n  //  vhDiv(n, a, b, y);\n  for (int i = 0; i < n; ++i) {\n    y[i] = a[i] / b[i];\n  }\n}\n#endif\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\n#ifndef CPU_ONLY\ntemplate <>\nvoid caffe_powx<float16>(const int n, const float16* a, const float16 b,\n    float16* y) {\n  for (int i = 0; i < n; ++i) {\n    y[i] = pow(static_cast<float>(a[i]), static_cast<float>(b));\n  }\n}\n#endif\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\n#ifndef CPU_ONLY\ntemplate <>\nvoid caffe_sqr<float16>(const int n, const float16* a, float16* y) {\n  vhSqr(n, a, y);\n}\n#endif\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\n#ifndef CPU_ONLY\ntemplate <>\nvoid caffe_exp<float16>(const int n, const float16* a, float16* y) {\n  vhExp(n, a, y);\n}\ntemplate <>\nvoid caffe_log<float16>(const int n, const float16* a, float16* y) {\n  vhLn(n, a, y);\n}\n#endif  // ! CPU_ONLY\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\n#ifndef CPU_ONLY\ntemplate <>\nvoid caffe_abs<float16>(const int n, const float16* a, float16* y) {\n  for (int i = 0; i < n; ++i) {\n    y[i] = fabs(a[i]);\n  }\n}\n#endif\n\nunsigned int caffe_rng_rand() {\n  return (*caffe_rng())();\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(int n, float a, float b, Dtype* r) {\n  CHECK_GE(n, 0);\n  CHECK(r);\n  CHECK_LE(a, b);\n  boost::uniform_real<float> random_distribution(a, caffe_nextafter<float>(b));\n  boost::variate_generator<caffe::rng_t*, boost::uniform_real<float> >\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>(int n, float a, float b, float* r);\n\ntemplate\nvoid caffe_rng_uniform<double>(int n, float a, float b, double* r);\n\n#ifndef CPU_ONLY\ntemplate\nvoid caffe_rng_uniform<float16>(int n, float a, float b, float16* r);\n#endif\n\ntemplate <typename Dtype>\nvoid caffe_rng_gaussian(int n, float a, float sigma, Dtype* r) {\n  CHECK_GE(n, 0);\n  CHECK(r);\n  CHECK_GT(sigma, 0);\n  boost::normal_distribution<float> random_distribution(a, sigma);\n  boost::variate_generator<caffe::rng_t*, boost::normal_distribution<float> >\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>(int n, float mu, float sigma, float* r);\n\ntemplate\nvoid caffe_rng_gaussian<double>(int n, float mu, float sigma, double* r);\n\n#ifndef CPU_ONLY\ntemplate\nvoid caffe_rng_gaussian<float16>(const int n, float mu, float sigma, float16* r);\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  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<int>(variate_generator());\n  }\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\n#ifndef CPU_ONLY\ntemplate<>\nvoid caffe_rng_bernoulli<float16>(const int n, const float16 p, int* r) {\n  caffe_rng_bernoulli(n, static_cast<const float>(p), r);\n}\n#endif\n\ntemplate <typename Dtype>\nvoid caffe_rng_bernoulli(const int n, const Dtype p, unsigned int* r) {\n  CHECK_GE(n, 0);\n  CHECK(r);\n  CHECK_GE(p, 0);\n  CHECK_LE(p, 1);\n  boost::bernoulli_distribution<Dtype> random_distribution(p);\n  boost::variate_generator<caffe::rng_t*, boost::bernoulli_distribution<Dtype> >\n      variate_generator(caffe_rng(), random_distribution);\n  for (int i = 0; i < n; ++i) {\n    r[i] = static_cast<unsigned int>(variate_generator());\n  }\n}\n\ntemplate\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\n#ifndef CPU_ONLY\ntemplate<>\nvoid caffe_rng_bernoulli<float16>(const int n, const float16 p,\n    unsigned int* r) {\n  caffe_rng_bernoulli(n, static_cast<const float>(p), r);\n}\n#endif\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\n#ifndef CPU_ONLY\ntemplate <>\nfloat16 caffe_cpu_strided_dot<float16>(const int n, const float16* x,\n    const int incx, const float16 *y, const int incy) {\n  float sum = 0.0f;\n  int idx_x, idx_y;\n  for (int i = 0; i < n; ++i) {\n    idx_x = i*incx;\n    idx_y = i*incy;\n    sum += x[idx_x] * y[idx_y];\n  }\n  return float16(sum);\n}\n#endif\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);\ntemplate\ndouble caffe_cpu_dot<double>(const int n, const double* x, const double* y);\n\n#ifndef CPU_ONLY\ntemplate\nfloat16 caffe_cpu_dot<float16>(const int n, const float16* x, const float16* y);\n#endif\n\ntemplate <>\nint caffe_cpu_hamming_distance<float>(const int n, const float* x,\n                                      const float* y) {\n  int dist = 0;\n  for (int i = 0; i < n; ++i) {\n    dist += __builtin_popcount(static_cast<uint32_t>(x[i]) ^\n                               static_cast<uint32_t>(y[i]));\n  }\n  return dist;\n}\n\ntemplate <>\nint caffe_cpu_hamming_distance<double>(const int n, const double* x,\n                                       const double* y) {\n  int dist = 0;\n  for (int i = 0; i < n; ++i) {\n    dist += __builtin_popcountl(static_cast<uint64_t>(x[i]) ^\n                                static_cast<uint64_t>(y[i]));\n  }\n  return dist;\n}\n\n#ifndef CPU_ONLY\ntemplate <>\nint caffe_cpu_hamming_distance<float16>(const int n, const float16* x,\n                                        const float16* y) {\n  int dist = 0;\n  for (int i = 0; i < n; ++i) {\n    dist += __builtin_popcount(x[i].getx() ^ y[i].getx());\n  }\n  return dist;\n}\n#endif\n\ntemplate <typename Dtype>\nDtype caffe_cpu_amax(const int n, const Dtype* x) {\n  Dtype y = 0.;\n  for (int i = 0; i < n; ++i) {\n    if (x[i] > 0)\n      y = std::max(y, x[i]);\n    else\n      y = std::max(y, -x[i]);\n  }\n  return y;\n}\n\ntemplate\nfloat caffe_cpu_amax<float>(const int n, const float* x);\ntemplate\ndouble caffe_cpu_amax<double>(const int n, const double* x);\n#ifndef CPU_ONLY\ntemplate\nfloat16 caffe_cpu_amax<float16>(const int n, const float16* x);\n#endif\n\ntemplate <>\nfloat caffe_cpu_asum<float>(const int n, const float* x) {\n  return cblas_sasum(n, x, 1);\n}\ntemplate <>\nfloat caffe_cpu_asum<double>(const int n, const double* x) {\n  return cblas_dasum(n, x, 1);\n}\n\n#ifndef CPU_ONLY\ntemplate <>\nfloat caffe_cpu_asum<float16>(const int n, const float16 *x) {\n  float sum = 0.0f;\n  for (int i = 0; i < n; ++i) {\n    sum += fabs(x[i]);\n  }\n  return sum;\n}\n#endif\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#ifndef CPU_ONLY\ntemplate <>\nvoid caffe_cpu_scale<float16>(const int n, const float16 alpha,\n    const float16 *x, float16 *y) {\n  for (int i = 0; i < n; i++) {\n    y[i] = alpha * x[i];\n  }\n}\n#endif\n\n// y[i]= max(a*x[i], b*y[i])\ntemplate <typename Dtype>\nvoid caffe_cpu_eltwise_max(const int N, const Dtype alpha, const Dtype* x,\n  const Dtype beta, Dtype* y) {\n  for (int i = 0; i < N; ++i) {\n    y[i] = std::max(alpha * x[i], beta * y[i]);\n  }\n}\ntemplate void caffe_cpu_eltwise_max<float>(const int N,\n    const float alpha, const float* x, const float beta, float* y);\ntemplate void caffe_cpu_eltwise_max<double>(const int N,\n    const double alpha, const double* x, const double beta, double* y);\n#ifndef CPU_ONLY\ntemplate void caffe_cpu_eltwise_max<float16>(const int N,\n    const float16 alpha, const float16* x, const float16 beta, float16* y);\n#endif\n\n// y[i]= min(a*x[i], b*y[i])\ntemplate <typename Dtype>\nvoid caffe_cpu_eltwise_min(const int N, const Dtype alpha, const Dtype* x,\n  const Dtype beta, Dtype* y) {\n  for (int i = 0; i < N; ++i) {\n    y[i] = std::min(alpha * x[i], beta * y[i]);\n  }\n}\ntemplate void caffe_cpu_eltwise_min<float>(const int N,\n    const float alpha, const float* x, const float beta, float* y);\ntemplate void caffe_cpu_eltwise_min<double>(const int N,\n    const double alpha, const double* x, const double beta, double* y);\n#ifndef CPU_ONLY\ntemplate void caffe_cpu_eltwise_min<float16>(const int N,\n    const float16 alpha, const float16* x, const float16 beta, float16* y);\n#endif\n\n\n}  // namespace caffe\n", "meta": {"hexsha": "436f862a5569d6b9e648d4d7fa37ab676dc5a82d", "size": 18218, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/caffe/util/math_functions.cpp", "max_stars_repo_name": "Luoyadan/dgx-1_caffe", "max_stars_repo_head_hexsha": "ca2c8a7c94d528d68f9630106a415f93be620dd4", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/caffe/util/math_functions.cpp", "max_issues_repo_name": "Luoyadan/dgx-1_caffe", "max_issues_repo_head_hexsha": "ca2c8a7c94d528d68f9630106a415f93be620dd4", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/caffe/util/math_functions.cpp", "max_forks_repo_name": "Luoyadan/dgx-1_caffe", "max_forks_repo_head_hexsha": "ca2c8a7c94d528d68f9630106a415f93be620dd4", "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.3646888567, "max_line_length": 92, "alphanum_fraction": 0.6478208365, "num_tokens": 5648, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7090191337850933, "lm_q2_score": 0.44939263446475963, "lm_q1q2_score": 0.31862797641760493}}
{"text": "#include <Eigen/Dense>\n#include \"control.hpp\"\n#include \"defines.hpp\"\n#include \"fad.hpp\"\n#include \"global_residual.hpp\"\n#include \"J2_small_strain.hpp\"\n#include \"material_params.hpp\"\n\nnamespace calibr8 {\n\nstatic ParameterList get_valid_local_residual_params() {\n  ParameterList p;\n  p.set<std::string>(\"type\", \"J2_small_strain\");\n  p.set<int>(\"nonlinear max iters\", 0);\n  p.set<double>(\"nonlinear absolute tol\", 0.);\n  p.set<double>(\"nonlinear relative tol\", 0.);\n  p.sublist(\"materials\");\n  return p;\n}\nstatic ParameterList get_valid_material_params() {\n  ParameterList p;\n  p.set<double>(\"E\", 0.);\n  p.set<double>(\"nu\", 0.);\n  p.set<double>(\"K\", 0.);\n  p.set<double>(\"Y\", 0.);\n  p.set<double>(\"cte\", 0.);\n  p.set<double>(\"delta_T\", 0.);\n  return p;\n}\n\ntemplate <typename T>\nJ2_small_strain<T>::J2_small_strain(ParameterList const& inputs, int ndims) {\n\n  this->m_params_list = inputs;\n  this->m_params_list.validateParameters(get_valid_local_residual_params(), 0);\n\n  int const num_residuals = 2;\n  int const num_params = 6;\n\n  this->m_num_residuals = num_residuals;\n  this->m_num_eqs.resize(num_residuals);\n  this->m_var_types.resize(num_residuals);\n  this->m_resid_names.resize(num_residuals);\n\n  this->m_resid_names[0] = \"pstrain\";\n  this->m_var_types[0] = SYM_TENSOR;\n  this->m_num_eqs[0] = get_num_eqs(SYM_TENSOR, ndims);\n\n  this->m_resid_names[1] = \"alpha\";\n  this->m_var_types[1] = SCALAR;\n  this->m_num_eqs[1] = get_num_eqs(SCALAR, ndims);\n\n  m_max_iters = inputs.get<int>(\"nonlinear max iters\");\n  m_abs_tol = inputs.get<double>(\"nonlinear absolute tol\");\n  m_rel_tol = inputs.get<double>(\"nonlinear relative tol\");\n\n}\n\ntemplate <typename T>\nJ2_small_strain<T>::~J2_small_strain() {\n}\n\ntemplate <typename T>\nvoid J2_small_strain<T>::init_params() {\n\n  int const num_params = 6;\n  this->m_params.resize(num_params);\n  this->m_param_names.resize(num_params);\n\n  this->m_param_names[0] = \"E\";\n  this->m_param_names[1] = \"nu\";\n  this->m_param_names[2] = \"K\";\n  this->m_param_names[3] = \"Y\";\n  this->m_param_names[4] = \"cte\";\n  this->m_param_names[5] = \"delta_T\";\n\n  int const num_elem_sets = this->m_elem_set_names.size();\n  resize(this->m_param_values, num_elem_sets, num_params);\n\n  ParameterList& all_material_params =\n      this->m_params_list.sublist(\"materials\", true);\n\n  for (int es = 0; es < num_elem_sets; ++es) {\n    std::string const& elem_set_name = this->m_elem_set_names[es];\n    ParameterList& material_params =\n        all_material_params.sublist(elem_set_name, true);\n    material_params.validateParameters(get_valid_material_params(), 0);\n    this->m_param_values[es][0] = material_params.get<double>(\"E\");\n    this->m_param_values[es][1] = material_params.get<double>(\"nu\");\n    this->m_param_values[es][2] = material_params.get<double>(\"K\");\n    this->m_param_values[es][3] = material_params.get<double>(\"Y\");\n    this->m_param_values[es][4] = material_params.get<double>(\"cte\");\n    this->m_param_values[es][5] = material_params.get<double>(\"delta_T\");\n  }\n\n  this->m_active_indices.resize(1);\n  this->m_active_indices[0].resize(1);\n  this->m_active_indices[0][0] = 0;\n}\n\ntemplate <typename T>\nvoid J2_small_strain<T>::init_variables_impl() {\n\n  int const ndims = this->m_num_dims;\n  int const pstrain_idx = 0;\n  int const alpha_idx = 1;\n\n  T const alpha = 0.0;\n  Tensor<T> const pstrain = minitensor::zero<T>(ndims);\n\n  this->set_scalar_xi(alpha_idx, alpha);\n  this->set_sym_tensor_xi(pstrain_idx, pstrain);\n\n}\n\ntemplate <>\nint J2_small_strain<double>::solve_nonlinear(RCP<GlobalResidual<double>>) {\n  return 0;\n}\n\ntemplate <>\nint J2_small_strain<FADT>::solve_nonlinear(RCP<GlobalResidual<FADT>> global) {\n\n  int path;\n\n  // pick an initial guess for the local variables\n  {\n    Tensor<FADT> const pstrain_old = this->sym_tensor_xi_prev(0);\n    Tensor<FADT> const pstrain = pstrain_old;\n    FADT const alpha_old = this->scalar_xi_prev(1);\n    FADT const alpha = alpha_old;\n    this->set_sym_tensor_xi(0, pstrain);\n    this->set_scalar_xi(1, alpha);\n    path = ELASTIC;\n  }\n\n  // newton iteration until convergence\n\n  int iter = 1;\n  double R_norm_0 = 1.;\n  bool converged = false;\n\n  while ((iter <= m_max_iters) && (!converged)) {\n\n    path = this->evaluate(global);\n\n    double const R_norm = this->norm_residual();\n    if (iter == 1) R_norm_0 = R_norm;\n    double const R_norm_rel = R_norm / R_norm_0;\n    if ((R_norm_rel < m_rel_tol) || (R_norm < m_abs_tol)) {\n      converged = true;\n      break;\n    }\n\n    EMatrix const J = this->eigen_jacobian();\n    EVector const R = this->eigen_residual();\n    EVector const dxi = J.fullPivLu().solve(-R);\n\n    this->add_to_sym_tensor_xi(0, dxi);\n    this->add_to_scalar_xi(1, dxi);\n\n    iter++;\n\n  }\n\n  // fail if convergence was not achieved\n  if ((iter > m_max_iters) && (!converged)) {\n    fail(\"J2_small_strain:solve_nonlinear failed in %d iterations\", m_max_iters);\n  }\n\n  return path;\n\n}\n\ntemplate <typename T>\nint J2_small_strain<T>::evaluate(\n    RCP<GlobalResidual<T>> global,\n    bool force_path,\n    int path_in) {\n\n  int path = ELASTIC;\n  int const ndims = this->m_num_dims;\n  double const sqrt_23 = std::sqrt(2./3.);\n  double const sqrt_32 = std::sqrt(3./2.);\n\n  T const E = this->m_params[0];\n  T const nu = this->m_params[1];\n  T const K = this->m_params[2];\n  T const Y = this->m_params[3];\n  T const mu = compute_mu(E, nu);\n\n  Tensor<T> const pstrain_old = this->sym_tensor_xi_prev(0);\n  T const alpha_old = this->scalar_xi_prev(1);\n\n  Tensor<T> const pstrain = this->sym_tensor_xi(0);\n  T const alpha = this->scalar_xi(1);\n\n  Tensor<T> const I = minitensor::eye<T>(ndims);\n  Tensor<T> const s = this->dev_cauchy(global);\n  T const s_mag = minitensor::norm(s);\n  Tensor<T> const n = s / s_mag;\n  T const sigma_yield = Y + K * alpha;\n  T const f = s_mag - sqrt_23 * sigma_yield;\n\n  Tensor<T> const grad_u_prev = global->grad_vector_x_prev(0);\n  Array2D<int> const& active_indices = this->active_indices();\n  T const dummy3 = this->params(active_indices[0][0]);\n\n  Tensor<T> R_pstrain;\n  T R_alpha;\n\n  if (!force_path) {\n    // plastic step\n    if (f > m_abs_tol || std::abs(f) < m_abs_tol) {\n      T const dgam = sqrt_32 * (alpha - alpha_old);\n      R_pstrain = (0. * dummy3 + 1.) * pstrain - pstrain_old - dgam * n + 0. * grad_u_prev;\n      R_alpha = (s_mag - sqrt_23 * sigma_yield) / val(mu) + 0. * dummy3;\n      path = PLASTIC;\n    }\n    // elastic step\n    else {\n      R_pstrain = (0. * dummy3 + 1.) * pstrain - pstrain_old + 0. * s + 0. * grad_u_prev;\n      R_alpha = alpha - alpha_old + 0. * dummy3 + 0. * s_mag;\n      path = ELASTIC;\n    }\n  }\n\n  // force the path\n  else {\n    path = path_in;\n    // plastic step\n    if (path == PLASTIC) {\n      T const dgam = sqrt_32 * (alpha - alpha_old);\n      R_pstrain = (0. * dummy3 + 1.) * pstrain - pstrain_old - dgam * n + 0. * grad_u_prev;\n      R_alpha = (s_mag - sqrt_23 * sigma_yield) / val(mu) + 0. * dummy3;\n    }\n    // elastic step\n    else {\n      R_pstrain = (0. * dummy3 + 1.) * pstrain - pstrain_old + 0. * s + 0. * grad_u_prev;\n      R_alpha = alpha - alpha_old + 0. * dummy3 + 0. * s_mag;\n    }\n  }\n\n  this->set_sym_tensor_R(0, R_pstrain);\n  this->set_scalar_R(1, R_alpha);\n\n  return path;\n\n}\n\ntemplate <typename T>\nTensor<T> J2_small_strain<T>::dev_cauchy(RCP<GlobalResidual<T>> global) {\n  int const ndims = global->num_dims();\n  Tensor<T> const I = minitensor::eye<T>(ndims);\n  T const E = this->m_params[0];\n  T const nu = this->m_params[1];\n  T const mu = E / (2. * (1. + nu));\n  Tensor<T> const pstrain = this->sym_tensor_xi(0);\n  Tensor<T> const grad_u = global->grad_vector_x(0);\n  Tensor<T> const eps = 0.5 * (grad_u + minitensor::transpose(grad_u));\n  Tensor<T> const dev_eps = eps - (minitensor::trace(eps) / 3.) * I;\n  return 2. * mu * (dev_eps - pstrain);\n}\n\ntemplate <typename T>\nTensor<T> J2_small_strain<T>::cauchy(RCP<GlobalResidual<T>> global, T p) {\n  int const ndims = global->num_dims();\n  T const E = this->m_params[0];\n  T const nu = this->m_params[1];\n  T const cte = this->m_params[4];\n  T const kappa = compute_kappa(E, nu);\n  T const delta_T = this->m_params[5];\n  Tensor<T> const I = minitensor::eye<T>(ndims);\n  Tensor<T> const dev_sigma = this->dev_cauchy(global);\n  Tensor<T> const sigma = dev_sigma - p * I - 3.*kappa*cte*delta_T*I;\n  return sigma;\n}\n\ntemplate class J2_small_strain<double>;\ntemplate class J2_small_strain<FADT>;\n\n}\n", "meta": {"hexsha": "2e381f87d9c18b1392c7050f364115a45c90a1c7", "size": 8320, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/J2_small_strain.cpp", "max_stars_repo_name": "sandialabs/calibr8", "max_stars_repo_head_hexsha": "a7be9213a49eb2b56f58041a2a88b0184382de4d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2021-08-31T00:33:36.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T17:10:28.000Z", "max_issues_repo_path": "src/J2_small_strain.cpp", "max_issues_repo_name": "sandialabs/calibr8", "max_issues_repo_head_hexsha": "a7be9213a49eb2b56f58041a2a88b0184382de4d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/J2_small_strain.cpp", "max_forks_repo_name": "sandialabs/calibr8", "max_forks_repo_head_hexsha": "a7be9213a49eb2b56f58041a2a88b0184382de4d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.3992932862, "max_line_length": 91, "alphanum_fraction": 0.6659855769, "num_tokens": 2593, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7341195385342971, "lm_q2_score": 0.43398146480389854, "lm_q1q2_score": 0.3185942726742763}}
{"text": "//==============================================================================\n//         Copyright 2003 - 2012   LASMEA UMR 6602 CNRS/Univ. Clermont II\n//         Copyright 2009 - 2012   LRI    UMR 8623 CNRS/Univ Paris Sud XI\n//\n//          Distributed under the Boost Software License, Version 1.0.\n//                 See accompanying file LICENSE.txt or copy at\n//                     http://www.boost.org/LICENSE_1_0.txt\n//==============================================================================\n#ifndef NT2_TRIGONOMETRIC_FUNCTIONS_SCALAR_IMPL_TRIGO_TRIG_REDUCTION_HPP_INCLUDED\n#define NT2_TRIGONOMETRIC_FUNCTIONS_SCALAR_IMPL_TRIGO_TRIG_REDUCTION_HPP_INCLUDED\n\n#include <nt2/include/functions/simd/rem_pio2_medium.hpp>\n#include <nt2/include/functions/simd/rem_pio2_cephes.hpp>\n#include <nt2/include/functions/simd/rem_pio2_straight.hpp>\n#include <nt2/include/functions/simd/rem_pio2.hpp>\n#include <nt2/include/functions/simd/logical_and.hpp>\n#include <nt2/include/functions/simd/split.hpp>\n#include <nt2/include/functions/simd/group.hpp>\n#include <nt2/include/functions/simd/fast_toint.hpp>\n#include <nt2/include/functions/simd/round2even.hpp>\n#include <nt2/include/functions/simd/if_else_allbits.hpp>\n#include <nt2/include/functions/simd/is_not_greater.hpp>\n#include <nt2/include/functions/simd/is_nez.hpp>\n#include <nt2/include/functions/simd/is_flint.hpp>\n#include <nt2/include/functions/simd/all.hpp>\n#include <nt2/include/functions/simd/inrad.hpp>\n#include <nt2/include/functions/simd/multiplies.hpp>\n#include <nt2/include/functions/simd/divides.hpp>\n#include <nt2/include/functions/simd/minus.hpp>\n#include <nt2/include/constants/zero.hpp>\n#include <nt2/include/constants/pi.hpp>\n#include <nt2/include/constants/pio_2.hpp>\n#include <nt2/include/constants/pio_4.hpp>\n#include <nt2/include/constants/half.hpp>\n#include <nt2/include/constants/two.hpp>\n#include <nt2/include/constants/_20_pi.hpp>\n#include <nt2/include/constants/oneo_90.hpp>\n#include <nt2/include/constants/_180.hpp>\n#include <nt2/include/constants/oneo_180.hpp>\n#include <nt2/include/constants/medium_pi.hpp>\n#include <nt2/include/constants/false.hpp>\n#include <nt2/sdk/meta/upgrade.hpp>\n#include <nt2/sdk/meta/as_integer.hpp>\n#include <nt2/sdk/meta/as_logical.hpp>\n#include <boost/simd/sdk/meta/is_upgradable.hpp>\n#include <boost/simd/sdk/config/enforce_precision.hpp>\n#include <boost/mpl/int.hpp>\n\n#include <boost/utility/enable_if.hpp>\n\nnamespace nt2 { namespace details\n{\n  template< class A0\n            , class unit_tag\n            , class style\n            , class mode\n            , class base_A0 = typename meta::scalar_of<A0>::type\n  >\n  struct trig_reduction;\n\n  // This class exposes the public static member:\n  // reduce:                to provide range reduction\n  //\n  // unit_tag allows to choose statically the scaling  among radian_tag, pi_tag, degree_tag\n  // meaning that the cosa function will (for example) define respectively\n  // x-->cos(x)          (radian_tag),\n  // x-->cos(p*x)        (pi_tag)\n  // x-->cos((pi/180)*x) (degree_tag)\n  //\n\n  // trigonometric reduction strategies in the [-pi/4, pi/4] range.\n  // these reductions are used in the accurate and fast\n  // trigonometric functions with different policies\n\n  template<class A0, class style, class mode>\n  struct trig_reduction < A0, radian_tag, style, mode>\n  {\n    typedef typename meta::scalar_of<A0>::type                         base_A0;\n    typedef typename meta::as_logical<A0>::type                        bA0;\n    typedef typename meta::as_integer<A0, signed>::type                int_type;\n    typedef typename boost::simd::meta::is_upgradable_on_ext<A0>::type conversion_allowed;\n\n    static BOOST_FORCEINLINE bA0 is_0_pio4_reduced(const A0&a0) { return boost::simd::is_ngt(a0, nt2::Pio_4<A0>()); }\n    static BOOST_FORCEINLINE bA0 is_0_pio2_reduced(const A0&a0) { return boost::simd::is_ngt(a0, nt2::Pio_2<A0>()); }\n    static BOOST_FORCEINLINE bA0 is_0_20pi_reduced(const A0&a0) { return boost::simd::is_ngt(a0, _20_pi<A0>()); }\n    static BOOST_FORCEINLINE bA0 is_0_mpi_reduced (const A0&a0) { return boost::simd::is_ngt(a0, Medium_pi<A0>()); }  //2^6pi\n    static BOOST_FORCEINLINE bA0 is_0_dmpi_reduced(const A0&a0) { return boost::simd::is_ngt(a0, single_constant<A0,0x49490fdb>()); }  //2^18pi\n\n    static BOOST_FORCEINLINE bA0 cot_invalid(const A0& ) { return False<bA0>(); }\n    static BOOST_FORCEINLINE bA0 tan_invalid(const A0& ) { return False<bA0>(); }\n\n    static BOOST_FORCEINLINE int_type reduce(const A0& x, A0& xr) { return inner_reduce(x, xr); }\n  private:\n    static BOOST_FORCEINLINE int_type inner_reduce(const A0& x, A0& xr)\n    {\n      A0 xx =  preliminary<mode>::clip(x);\n      return select_mode(xx, xr, boost::mpl::int_<mode::start>());\n    }\n\n    template < class Mode, bool clipped = Mode::clipped>\n    struct preliminary\n    {\n      static BOOST_FORCEINLINE A0 const& clip(const A0& x) { return x; }\n    };\n\n\n    template < class Mode>\n    struct preliminary<Mode, true>\n    {\n      static BOOST_FORCEINLINE A0 clip(const A0& x)\n      {\n        return clipto(x, boost::mpl::int_<Mode::range>());\n      }\n    private :\n      static BOOST_FORCEINLINE A0 clipto(const A0& x, boost::mpl::int_<r_0_pio4> const&)\n      {\n        return if_else_nan(is_0_pio4_reduced(x), x);\n      }\n      static BOOST_FORCEINLINE A0 clipto(const A0& x, boost::mpl::int_<r_0_20pi> const&)\n      {\n        return if_else_nan(is_0_20pi_reduced(x), x);\n      }\n      static BOOST_FORCEINLINE A0 clipto(const A0& x, boost::mpl::int_<r_0_mpi> const&)\n      {\n        return if_else_nan(is_0_mpi_reduced(x), x);\n      }\n      static BOOST_FORCEINLINE A0 clipto(const A0& x, boost::mpl::int_<r_0_dmpi> const&)\n      {\n        return if_else_nan(is_0_dmpi_reduced(x), x);\n      }\n    };\n\n    static BOOST_FORCEINLINE int_type\n    select_range( const A0& xx, A0& xr\n                , boost::mpl::true_ const&\n                , boost::mpl::int_<r_0_pio4> const&\n                )\n    {\n      xr = xx;\n      return Zero<int_type>();\n    }\n\n    static BOOST_FORCEINLINE int_type\n    select_range( const A0& xx, A0& xr\n                , boost::mpl::false_ const&\n                , boost::mpl::int_<r_0_pio4> const& r\n                )\n    {\n      if(nt2::all(is_0_pio4_reduced(xx)))\n        return select_range(xx,xr,boost::mpl::true_(), r);\n\n      return select_mode(xx,xr,boost::mpl::int_<r_0_pio2>());\n    }\n\n    static BOOST_FORCEINLINE int_type\n    select_mode(const A0& xx, A0& xr, boost::mpl::int_<r_0_pio4> const& r)\n    {\n      return select_range(xx,xr,boost::mpl::bool_<mode::range == r_0_pio4>(),r);\n    }\n\n    static BOOST_FORCEINLINE int_type select_mode(const A0& xx, A0& xr, boost::mpl::int_<r_0_pio2> const&)\n    {\n      if(nt2::all(is_0_pio2_reduced(xx)))\n        return rem_pio2_straight(xx, xr);\n      return select_mode(xx,xr,boost::mpl::int_<r_0_20pi>());\n    }\n\n    static BOOST_FORCEINLINE int_type\n    select_range( const A0& xx, A0& xr\n                , boost::mpl::true_ const&\n                , boost::mpl::int_<r_0_20pi> const&\n                )\n    {\n      return rem_pio2_cephes(xx, xr);\n    }\n\n    static BOOST_FORCEINLINE int_type\n    select_range( const A0& xx, A0& xr\n                , boost::mpl::false_ const&\n                , boost::mpl::int_<r_0_20pi> const& r\n                )\n    {\n      if(nt2::all(is_0_20pi_reduced(xx)))\n        return select_range(xx,xr,boost::mpl::true_(), r);\n\n      return select_mode(xx,xr,boost::mpl::int_<r_0_mpi>());\n    }\n\n    static BOOST_FORCEINLINE int_type\n    select_mode(const A0& xx, A0& xr, boost::mpl::int_< r_0_20pi> const& r)\n    {\n      return select_range(xx,xr,boost::mpl::bool_<mode::range == r_0_20pi>(),r);\n    }\n\n\n\n    static BOOST_FORCEINLINE int_type\n    select_range( const A0& xx, A0& xr\n                , boost::mpl::true_ const&\n                , boost::mpl::int_<r_0_mpi> const&\n                )\n    {\n      return rem_pio2_medium(xx, xr);\n    }\n\n    static BOOST_FORCEINLINE int_type\n    select_range( const A0& xx, A0& xr\n                , boost::mpl::false_ const&\n                , boost::mpl::int_<r_0_mpi> const& r\n                )\n    {\n      if(nt2::all(is_0_mpi_reduced(xx)))\n        return select_range(xx,xr,boost::mpl::true_(), r);\n\n      return select_mode(xx,xr,boost::mpl::int_<r_0_dmpi>());\n    }\n\n    static BOOST_FORCEINLINE int_type select_mode(const A0& xx, A0& xr, boost::mpl::int_< r_0_mpi> const& r)\n    {\n      return select_range(xx,xr,boost::mpl::bool_<mode::range == r_0_mpi>(),r);\n    }\n\n    static BOOST_FORCEINLINE int_type select_mode(const A0& xx, A0& xr, boost::mpl::int_< r_0_dmpi> const&)\n    {\n      if(nt2::all(is_0_dmpi_reduced(xx)))\n        return use_conversion(xx, xr, style(), conversion_allowed());\n      return rem_pio2(xx, xr);\n    }\n\n    static BOOST_FORCEINLINE int_type use_conversion(const A0 & xx,  A0& xr,  const style &, boost::mpl::false_)\n    {\n      return rem_pio2(xx, xr);\n    }\n\n    static BOOST_FORCEINLINE int_type use_conversion(const A0 & xx,  A0& xr,  const tag::not_simd_type &, boost::mpl::true_)\n    {\n      // all of x are in [0, 2^18*pi],  conversion to double is used to reduce\n      typedef typename meta::upgrade<A0>::type uA0;\n      typedef trig_reduction< uA0, radian_tag,  tag::not_simd_type, mode, double> aux_reduction;\n      uA0 ux = xx, uxr;\n      int_type n = static_cast<int_type>(aux_reduction::reduce(ux, uxr));\n      xr = static_cast<A0>(uxr);\n      return n;\n    }\n\n    static BOOST_FORCEINLINE int_type use_conversion(const A0 & x,  A0& xr,  const tag::simd_type &, boost::mpl::true_)\n    {\n      // all of x are in [0, 2^18*pi],  conversion to double is used to reduce\n      typedef typename meta::upgrade<A0>::type uA0;\n      typedef typename meta::upgrade<int_type>::type uint_type;\n      typedef trig_reduction< uA0, radian_tag,  tag::simd_type, mode, double> aux_reduction;\n      uA0 ux1, ux2, uxr1, uxr2;\n      nt2::split(x, ux1, ux2);\n      uint_type n1 = aux_reduction::reduce(ux1, uxr1);\n      uint_type n2 = aux_reduction::reduce(ux2, uxr2);\n      xr = nt2::group(uxr1, uxr2);\n      nt2::split(xr, ux1, ux2);\n      return nt2::group(n1, n2);\n    }\n  };\n\n  template<class A0, class style>\n  struct trig_reduction<A0,degree_tag, style, big_>\n  {\n    typedef typename meta::as_logical<A0>::type              bA0;\n    typedef typename meta::as_integer<A0, signed>::type int_type;\n\n    static BOOST_FORCEINLINE bA0 cot_invalid(const A0& x) { return logical_and(nt2::is_nez(x), is_flint(x*nt2::Oneo_180<A0>())); }\n    static BOOST_FORCEINLINE bA0 tan_invalid(const A0& x) { return nt2::is_flint((x-nt2::_90<A0>())*nt2::Oneo_180<A0>()); }\n\n    static BOOST_FORCEINLINE int_type reduce(const A0& x, A0& xr)\n    {\n      A0 xi = nt2::round2even(x*nt2::Oneo_90<A0>());\n      A0 x2 = x - xi * nt2::_90<A0>();\n\n      xr =  nt2::inrad(x2);\n      return nt2::fast_toint(xi);\n    }\n  };\n\n  #ifdef BOOST_SIMD_HAS_X87\n  template<class A0>\n  struct trig_reduction<A0,degree_tag, tag::not_simd_type, big_>\n  {\n    typedef typename meta::as_logical<A0>::type              bA0;\n    typedef typename meta::as_integer<A0, signed>::type int_type;\n\n    static BOOST_FORCEINLINE bA0 cot_invalid(const A0& x) { return logical_and(nt2::is_nez(x), is_flint(x/nt2::_180<A0>())); }\n    static BOOST_FORCEINLINE bA0 tan_invalid(const A0& x) { return nt2::is_flint((x-nt2::_90<A0>())/nt2::_180<A0>()); }\n\n    static BOOST_FORCEINLINE int_type reduce(const A0& x, A0& xr)\n    {\n      A0 xi = nt2::round2even(x*nt2::Oneo_90<A0>());\n      A0 x2 = x - xi * nt2::_90<A0>();\n\n      xr =  nt2::inrad(x2);\n      return nt2::fast_toint(xi);\n    }\n  };\n  #endif\n\n  template < class A0, class style>\n  struct trig_reduction < A0, pi_tag,  style, big_>\n  {\n    typedef typename meta::as_logical<A0>::type              bA0;\n    typedef typename meta::as_integer<A0, signed>::type int_type;\n\n    static BOOST_FORCEINLINE bA0 cot_invalid(const A0& x) { return logical_and(nt2::is_nez(x), nt2::is_flint(x)); }\n    static BOOST_FORCEINLINE bA0 tan_invalid(const A0& x) { return nt2::is_flint(x-nt2::Half<A0>()) ; }\n\n    static BOOST_FORCEINLINE int_type reduce(const A0& x,  A0& xr)\n    {\n      A0 xi = nt2::round2even(x*nt2::Two<A0>());\n      A0 x2 = x - xi * nt2::Half<A0>();\n      xr = x2*nt2::Pi<A0>();\n      return nt2::fast_toint(xi);\n    }\n  };\n} }\n\n#endif\n", "meta": {"hexsha": "a2a3b327476fa1205808fa95920908893d7ae5a6", "size": 12279, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/core/trigonometric/include/nt2/trigonometric/functions/scalar/impl/trigo/trig_reduction.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/trigonometric/include/nt2/trigonometric/functions/scalar/impl/trigo/trig_reduction.hpp", "max_issues_repo_name": "psiha/nt2", "max_issues_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "modules/core/trigonometric/include/nt2/trigonometric/functions/scalar/impl/trigo/trig_reduction.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.1335403727, "max_line_length": 143, "alphanum_fraction": 0.6442707061, "num_tokens": 3574, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6224593312018546, "lm_q2_score": 0.5117166047041654, "lm_q1q2_score": 0.31852277552903857}}
{"text": "// MIT License\n//\n// Copyright (c) 2021 Aditya Shridhar Hegde\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in all\n// copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n// SOFTWARE.\n\n#include <HEAAN.h>\n#include <cnpy.h>\n#include <errno.h>\n#include <sys/stat.h>\n\n#include <boost/program_options.hpp>\n#include <chrono>\n#include <ckp19/dataset.hpp>\n#include <ckp19/mean_shift.hpp>\n#include <ckp19/plaintext_clustering.hpp>\n#include <filesystem>\n#include <fstream>\n#include <nlohmann/json.hpp>\n#include <numeric>\n#include <string>\n\n#include \"utils.hpp\"\n\nnamespace fs = std::filesystem;\nnamespace bpo = boost::program_options;\nusing json = nlohmann::json;\nusing TimeUnit = std::chrono::system_clock::time_point;\n\nvoid benchmarkClustering(const bpo::variables_map &opts) {\n  long seed = opts[\"seed\"].as<long>();\n  long repeat = opts[\"repeat\"].as<long>();\n  long threads = opts[\"threads\"].as<long>();\n  std::string dataset = opts[\"dataset\"].as<std::string>();\n\n  srand(seed);\n  SetNumThreads(threads);\n\n  bool save_data = false;\n  fs::path output_dir;\n  if (opts.count(\"output\") > 0) {\n    save_data = true;\n    output_dir = fs::path(opts[\"output\"].as<std::string>());\n  }\n\n  long logq = opts[\"logq\"].as<long>();\n  long logp = opts[\"logp\"].as<long>();\n  long logt = opts[\"logt\"].as<long>();\n  long logq_boot = opts[\"logq-boot\"].as<long>();\n\n  long num_dusts = opts[\"dusts\"].as<long>();\n  long iterations = opts[\"iterations\"].as<long>();\n  long mode_kdegree = opts[\"mode-kdegree\"].as<long>();\n  long label_kdegree = opts[\"label-kdegree\"].as<long>();\n  long mode_inv_steps = opts[\"mode-invsteps\"].as<long>();\n  long label_inv_steps = opts[\"label-invsteps\"].as<long>();\n  long minidx_t = opts[\"min-idx-t\"].as<long>();\n\n  json info;\n\n  TimePoint start;\n  Ring ring;\n  SecretKey secretKey(ring);\n  Scheme scheme(secretKey, ring);\n  scheme.addLeftRotKeys(secretKey);\n  scheme.addRightRotKeys(secretKey);\n  TimePoint end;\n  info[\"stats\"][\"init_scheme\"] = end - start;\n\n  Dataset ds = Dataset::loadNpy(dataset);\n  ds.rescaleDatasetInPlace(0.5);\n\n  long logl = std::ceil(std::log2(ds[0].size() * num_dusts));\n  start = TimePoint();\n  scheme.addBootKey(secretKey, logl, logq_boot + logt);\n  end = TimePoint();\n  info[\"stats\"][\"gen_bootstrap_key\"] = end - start;\n\n  info[\"details\"] = {{\"seed\", seed},\n                     {\"repeat\", repeat},\n                     {\"threads\", threads},\n                     {\"dataset\", dataset},\n                     {\"logN\", logN},\n                     {\"logQ\", logQ},\n                     {\"logq\", logq},\n                     {\"logp\", logp},\n                     {\"logt\", logt},\n                     {\"logq-boot\", logq_boot},\n                     {\"logl\", logl},\n                     {\"dusts\", num_dusts},\n                     {\"iterations\", iterations},\n                     {\"mode-kdegree\", mode_kdegree},\n                     {\"label-kdegree\", label_kdegree},\n                     {\"mode-invsteps\", mode_inv_steps},\n                     {\"label-invsteps\", label_inv_steps},\n                     {\"min-idx-t\", minidx_t}};\n\n  std::cout << \"--- Information ---\\n\";\n  for (json::iterator it = info[\"details\"].begin(); it != info[\"details\"].end();\n       ++it) {\n    std::cout << it.key() << \" : \" << it.value() << \"\\n\";\n  }\n  std::cout << std::endl;\n\n  std::cout << \"--- Setup ---\\n\";\n  for (json::iterator it = info[\"stats\"].begin(); it != info[\"stats\"].end();\n       ++it) {\n    std::cout << it.key() << \" : \" << it.value() << \"\\n\";\n  }\n  std::cout << std::endl;\n\n  info[\"benchmarks\"] = json::array();\n\n  fs::create_directories(output_dir);\n  auto info_file = output_dir / \"info.json\";\n\n  for (long i = 0; i < repeat; ++i) {\n    std::cout << \"--- Repetition \" << i + 1 << \" ---\\n\";\n\n    json iter;\n\n    EncryptedDataset eds;\n    start = TimePoint();\n    ds.encryptSIMD(eds, scheme, num_dusts, Nh, logp, logq);\n    end = TimePoint();\n    iter[\"encrypt_dataset_time\"] = end - start;\n\n    if (i == 0) {\n      info[\"details\"][\"plaintext_points_per_ciphertext\"] = eds.npoints;\n      info[\"details\"][\"num_ciphertexts\"] = eds.points.size();\n      info[\"details\"][\"slots_used\"] = eds.log_slots;\n    }\n\n    MeanShift meanshift(scheme, eds.log_slots, logq, logq_boot, logp, logt,\n                        seed + i);\n\n    std::vector<Ciphertext> clabels;\n\n    TimePoint start;\n    meanshift.clusterSIMD(clabels, eds.points, eds.dim, eds.npoints, num_dusts,\n                          iterations, mode_kdegree, label_kdegree,\n                          mode_inv_steps, label_inv_steps, minidx_t);\n    TimePoint end;\n    iter[\"cluster_time\"] = end - start;\n\n    std::vector<double> olabels(ds.size() * num_dusts);\n    double decrypt_time = 0;\n    for (size_t p = 0; p < eds.points.size(); ++p) {\n      TimePoint start;\n      std::unique_ptr<complex<double>[]> output(\n          scheme.decrypt(secretKey, clabels[p]));\n      TimePoint end;\n      decrypt_time += end - start;\n\n      for (int i = 0; i < num_dusts; ++i) {\n        for (int j = 0; j < eds.npoints; ++j) {\n          // Store the final label as the value in the first dimension\n          olabels[p * eds.npoints * num_dusts + j * num_dusts + i] =\n              output[i * eds.npoints * eds.dim + j * eds.dim].real();\n        }\n      }\n    }\n    iter[\"decrypt_output_time\"] = decrypt_time;\n\n    if (save_data) {\n      info[\"benchmarks\"].push_back(iter);\n      saveJson(info, info_file);\n\n      auto data_file =\n          (output_dir / (\"rep_\" + std::to_string(i) + \".npy\")).string();\n      cnpy::npy_save(data_file, olabels.data(),\n                     {ds.size(), static_cast<unsigned long>(num_dusts)}, \"w\");\n    }\n  }\n\n  if (save_data) {\n    // Highest virutal memory usage and physical memory usage\n    info[\"stats\"][\"vmpeak\"] = getProcStatus(\"VmPeak:\");\n    info[\"stats\"][\"vmhwm\"] = getProcStatus(\"VmHWM:\");\n    saveJson(info, info_file);\n  }\n}\n\n// clang-format off\nbpo::options_description generic_program_options() {\n  bpo::options_description desc(\"Followig options are supported by config file too\");\n  desc.add_options()\n    (\"output,o\", bpo::value<std::string>(), \"Directory to save benchmarks and other data.\")\n    (\"seed\", bpo::value<long>()->default_value(2602), \"Seed used for RNG.\")\n    (\"repeat,r\", bpo::value<long>()->default_value(1), \"Number of times to run benchmarks.\")\n    (\"threads\", bpo::value<long>()->default_value(1), \"Number of threads to use.\")\n    (\"dataset\", bpo::value<std::string>()->required(), \"Path to dataset in npy format.\");\n\n  desc.add_options()\n    (\"logq\", bpo::value<long>()->default_value(logQ), \"Log of ciphertext modulus.\")\n    (\"logp\", bpo::value<long>()->default_value(30), \"Log of noise parameter.\")\n    (\"logt\", bpo::value<long>()->default_value(4), \"Log of bootstrap noise parameter.\")\n    (\"logq-boot\", bpo::value<long>()->default_value(40), \"Log of bootstrap ciphertext modulus.\");\n\n  desc.add_options()\n    (\"dusts\", bpo::value<long>()->required(), \"Number of dusts.\")\n    (\"iterations\", bpo::value<long>()->required(), \"Number of iterations for mode seeking.\")\n    (\"mode-kdegree\", bpo::value<long>()->required(), \"Log of kernel degree in mode seeking (\\\\Gamma_1).\")\n    (\"label-kdegree\", bpo::value<long>()->required(), \"Log of kernel degree in point labeling (\\\\Gamma_2).\")\n    (\"mode-invsteps\", bpo::value<long>()->required(), \"Number of iterations for inverse in mode seeking (\\\\zeta_1).\")\n    (\"label-invsteps\", bpo::value<long>()->required(), \"Number of iterations for inverse in point labeling (\\\\zeta_2).\")\n    (\"min-idx-t\", bpo::value<long>()->required(), \"Log of degree for minimum index algorithm (t).\");\n\n  return desc;\n}\n// clang-format on\n\nint main(int argc, char *argv[]) {\n  auto generic(generic_program_options());\n\n  bpo::options_description cmdline(\"Run CKP19 mean shift clustering.\");\n  cmdline.add(generic);\n  cmdline.add_options()(\n      \"config,c\", bpo::value<std::string>(),\n      \"Configuration file for easy specification of cmd line arguments.\")(\n      \"help,h\", \"Produce help message.\");\n\n  bpo::variables_map opts;\n  bpo::store(bpo::command_line_parser(argc, argv).options(cmdline).run(), opts);\n\n  if (opts.count(\"help\") != 0) {\n    std::cout << cmdline << std::endl;\n    return 0;\n  }\n\n  if (opts.count(\"config\") != 0) {\n    std::string cpath(opts[\"config\"].as<std::string>());\n    std::ifstream fin(cpath.c_str());\n\n    if (fin.fail()) {\n      std::cerr << \"Could not open configuration file at \" << cpath << \"\\n\";\n      return 1;\n    }\n\n    bpo::store(bpo::parse_config_file(fin, generic), opts);\n  }\n\n  try {\n    bpo::notify(opts);\n\n    // Check if output file already exists\n    if (fs::exists(opts[\"output\"].as<std::string>())) {\n      throw std::runtime_error(\"Output directory aready exists.\");\n    }\n  } catch (const std::exception &ex) {\n    std::cerr << ex.what() << std::endl;\n    return 1;\n  }\n\n  try {\n    benchmarkClustering(opts);\n  } catch (const std::exception &ex) {\n    std::cerr << ex.what() << \"\\nFatal error\" << std::endl;\n    return 1;\n  }\n\n  return 0;\n}\n", "meta": {"hexsha": "39f7ae0431b654f1dad1d337988493de8034cfe0", "size": 9880, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "he_meanshift/benchmark/cluster.cpp", "max_stars_repo_name": "encryptogroup/SoK_ppClustering", "max_stars_repo_head_hexsha": "6b008a09bfe3f3b8074e24059ac3e2aa6b87f227", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2021-06-18T08:09:46.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-19T05:41:24.000Z", "max_issues_repo_path": "he_meanshift/benchmark/cluster.cpp", "max_issues_repo_name": "encryptogroup/SoK_ppClustering", "max_issues_repo_head_hexsha": "6b008a09bfe3f3b8074e24059ac3e2aa6b87f227", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "he_meanshift/benchmark/cluster.cpp", "max_forks_repo_name": "encryptogroup/SoK_ppClustering", "max_forks_repo_head_hexsha": "6b008a09bfe3f3b8074e24059ac3e2aa6b87f227", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.2857142857, "max_line_length": 120, "alphanum_fraction": 0.6159919028, "num_tokens": 2573, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6370308082623217, "lm_q2_score": 0.5, "lm_q1q2_score": 0.31851540413116086}}
{"text": "#ifndef FIELD2_HPP_\n#define FIELD2_HPP_\n\n#pragma warning (disable : 4146)\n#include <NTL/ZZ_pEX.h>\n\n#include <variant>\n#include <iostream>\n#include <string>\n\nnamespace gadgetlib\n{\n\t// helper function\n\tconstexpr unsigned c_strlen(char const* str, unsigned count = 0)\n\t{\n\t\treturn ('\\0' == str[0]) ? count : c_strlen(str + 1, count + 1);\n\t}\n\n\t// destination \"template string\" type\n\ttemplate < char... tt_c >\n\tstruct exploded_string\n\t{\n\t};\n\n\t// struct to explode a `char const*` to an `exploded_string` type\n\ttemplate < typename T_StrProvider, unsigned t_len, char... tt_c >\n\tstruct explode_impl\n\t{\n\t\tusing result =\n\t\t\ttypename explode_impl < T_StrProvider, t_len - 1,\n\t\t\tT_StrProvider::str()[t_len - 1],\n\t\t\ttt_c... > ::result;\n\t};\n\n\ttemplate < typename T_StrProvider, char... tt_c >\n\tstruct explode_impl < T_StrProvider, 0, tt_c... >\n\t{\n\t\tusing result = exploded_string<tt_c...>;\n\t};\n\n\t// syntactical sugar\n\ttemplate < typename T_StrProvider >\n\tusing explode =\n\t\ttypename explode_impl < T_StrProvider,\n\t\tc_strlen(T_StrProvider::str()) > ::result;\n\n\n\ttemplate<typename STR_PROVIDER>\n\tclass Field\n\t{\n\tpublic:\n\t\tNTL::ZZ_p num_;\n\t\tstatic bool initialized_;\n\n\tprivate:\n\t\tvoid initialize()\n\t\t{\n\t\t\tif (!initialized_)\n\t\t\t{\n\t\t\t\tinitialized_ = true;\n\t\t\t\tNTL::ZZ chp = NTL::conv<NTL::ZZ>(STR_PROVIDER::str());\n\t\t\t\tNTL::ZZ_p::init(chp);\n\t\t\t}\n\n\t\t}\n\n\t\tNTL::ZZ hexToZZ(const std::string& hexVal)\n\t\t{\n\t\t\tauto convert_ch = [](char c) -> int\n\t\t\t{\n\t\t\t\tif (c >= '0' && c <= '9')\n\t\t\t\t\treturn (c - '0');\n\t\t\t\tif (c >= 'a' && c <= 'f')\n\t\t\t\t\treturn (c - 'a' + 10);\n\n\t\t\t};\n\n\t\t\tNTL::ZZ val;\n\t\t\tval = NTL::to_ZZ(0);\t//initialise the value to zero\n\n\t\t\tfor (unsigned i = 0; i < hexVal.length(); i++)\n\t\t\t{\n\t\t\t\tval *= 16;\n\t\t\t\tval += convert_ch(hexVal[i]);\n\n\t\t\t}\n\t\t\treturn val;\n\t\t}\n\n\tpublic:\n\t\t//static constexpr uint64_t safe_bitsize = SignificantBits<characteristics>::n;\n\t\t//static constexpr uint64_t chr = characteristics;\n\n\t\tField(size_t num)\n\t\t{\n\t\t\tinitialize();\n\t\t\tnum_ = num;\n\t\t}\n\n\t\tField()\n\t\t{\n\t\t\tinitialize();\n\t\t}\n\n\t\tField(const NTL::ZZ_p& num)\n\t\t{\n\t\t\tinitialize();\n\t\t\tnum_ = num;\n\t\t}\n\n\t\tField(const std::variant<uint32_t, std::string>& v)\n\t\t{\n\t\t\tinitialize();\n\t\t\t//uint32_t n;\n\t\t\tswitch (v.index())\n\t\t\t{\n\t\t\tcase 0:\n\t\t\t{\n\t\t\t\tNTL::ZZ num = NTL::conv<NTL::ZZ>(std::get<0>(v));\n\t\t\t\tnum_ = NTL::conv<NTL::ZZ_p>(num);;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase 1:\n\t\t\t\tNTL::ZZ int_num = hexToZZ(std::get<1>(v));\n\t\t\t\tnum_ = NTL::conv<NTL::ZZ_p>(int_num);\n\t\t\t\tbreak;\n\t\t\t};\n\t\t}\n\n\t\tField& operator+=(const Field& rhs)\n\t\t{\n\t\t\tthis->num_ += rhs.num_;\n\t\t\treturn *this;\n\t\t}\n\n\n\t\tField& operator-=(const Field& rhs)\n\t\t{\n\t\t\tthis->num_ -= rhs.num_;\n\t\t\treturn *this;\n\t\t}\n\n\t\tField& operator*=(const Field& rhs)\n\t\t{\n\t\t\tthis->num_ *= rhs.num_;\n\t\t\treturn *this;\n\t\t}\n\n\t\tField& operator-()\n\t\t{\n\t\t\tthis->num_ = -this->num_;\n\t\t\treturn *this;\n\t\t}\n\n\n\t\tField& operator/=(const Field& rhs)\n\t\t{\n\t\t\tthis->num_ = NTL::conv<NTL::ZZ_p>(NTL::rep(num_) / NTL::rep(rhs.num_));\n\t\t\treturn *this;\n\t\t}\n\n\t\tstatic Field one()\n\t\t{\n\t\t\treturn 1;\n\t\t}\n\n\t\toperator bool() const\n\t\t{\n\t\t\treturn num_ != 0;\n\t\t}\n\t};\n\n\ttemplate<typename STR_PROVIDER>\n\tField<STR_PROVIDER> operator+(const Field<STR_PROVIDER>& left,\n\t\tconst Field<STR_PROVIDER>& right)\n\t{\n\t\treturn Field<STR_PROVIDER>(left.num_ + right.num_);\n\t}\n\n\ttemplate<typename STR_PROVIDER>\n\tField<STR_PROVIDER> operator-(const Field<STR_PROVIDER>& left,\n\t\tconst Field<STR_PROVIDER>& right)\n\t{\n\t\treturn Field<STR_PROVIDER>(left.num_ - right.num_);\n\t}\n\n\ttemplate<typename STR_PROVIDER>\n\tField<STR_PROVIDER> operator*(const Field<STR_PROVIDER>& left,\n\t\tconst Field<STR_PROVIDER>& right)\n\t{\n\t\treturn Field<STR_PROVIDER>(left.num_ * right.num_);\n\t}\n\n\ttemplate<typename STR_PROVIDER>\n\tbool operator==(const Field<STR_PROVIDER>& left,\n\t\tconst Field<STR_PROVIDER>& right)\n\t{\n\t\treturn (left.num_ == right.num_);\n\t}\n\n\ttemplate<typename STR_PROVIDER>\n\tbool operator!=(const Field<STR_PROVIDER>& left,\n\t\tconst Field<STR_PROVIDER>& right)\n\t{\n\t\treturn (left.num_ != right.num_);\n\t}\n\n\ttemplate<typename STR_PROVIDER>\n\tField<STR_PROVIDER> operator%(const Field<STR_PROVIDER>& left,\n\t\tint right)\n\t{\n\t\tassert(right == 2);\n\t\treturn NTL::rem(rep(left.num_), right);\n\t}\n\n\ttemplate<typename STR_PROVIDER>\n\tstd::ostream& operator<< (std::ostream& stream, const Field<STR_PROVIDER>& elem)\n\t{\n\t\tstream << elem.num_;\n\t\treturn stream;\n\t}\n\n\ttemplate<typename STR_PROVIDER>\n\tbool Field<STR_PROVIDER>::initialized_ = false;\n}\n\n#endif\n", "meta": {"hexsha": "3ce8855802bc0f24c1192b15373a069ab1c9e20b", "size": 4357, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/Field2.hpp", "max_stars_repo_name": "BANKEX/gadget_lib", "max_stars_repo_head_hexsha": "7c29a69a3c639372dec380b5b7cf431aacd26da7", "max_stars_repo_licenses": ["Apache-2.0"], "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/Field2.hpp", "max_issues_repo_name": "BANKEX/gadget_lib", "max_issues_repo_head_hexsha": "7c29a69a3c639372dec380b5b7cf431aacd26da7", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/Field2.hpp", "max_forks_repo_name": "BANKEX/gadget_lib", "max_forks_repo_head_hexsha": "7c29a69a3c639372dec380b5b7cf431aacd26da7", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2018-08-13T15:12:28.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-20T17:14:33.000Z", "avg_line_length": 19.1096491228, "max_line_length": 81, "alphanum_fraction": 0.6373651595, "num_tokens": 1315, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6370307944803831, "lm_q2_score": 0.5, "lm_q1q2_score": 0.31851539724019157}}
{"text": "/*\n *  Copyright (c) 2010, INRIA, Project ALICE\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 *  * Neither the name of the ALICE Project-Team 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 *  If you modify this software, you should include a notice giving the\n *  name of the person performing the modification, the date of modification,\n *  and the reason for such modification.\n *\n *  Contact: Bruno Levy\n *\n *     Bruno.Levy@inria.fr\n *     http://alice.loria.fr\n *\n *     ALICE Project\n *     INRIA Lorraine, \n *     Campus Scientifique, BP 239\n *     54506 VANDOEUVRE LES NANCY CEDEX \n *     FRANCE\n *\n */\n\n\n#include <LpCVT/algebra/F_Lp.h>\n#include <LpCVT/algebra/voro_func.h>\n\n#ifdef CVT_MULTITHREAD\n#include <LpCVT/common/processor.h>\n#include <boost/thread.hpp>\n#include <boost/bind.hpp>\n#endif\n\nnamespace Geex {\n \n   \n   //==========================================================================\n\n    // Internal version: uses pointers instead of std::vectors for 'sym' and 'C'\n    // (used by both monothread and multithread implementations)\n    \n    double compute_F_Lp_internal(\n        bool volumic,                  // IN: false for surface meshing, true for volume meshing\n        unsigned int p,                // IN: Lp norm to be used\n        Mesh* mesh,                    // IN: the PLC\n        unsigned int nb,               // IN: number of integration simplices\n        const int* sym,                      // IN: 10 integers per integration simplex:\n                                       //   - index of x0\n                                       //   - symbolic representation of C1,C2,C3 (3 integers each)\n        const vec3* C,                       // IN: C vertices of integration simplices (3 per integration simplex) \n        const std::vector<vec3>& X,    // IN: vertices\n        const std::vector<plane3>& Q,  // IN: boundary facets\n        const std::vector<mat3>& M,    // IN: anisotropy matrix (one per integration simplex)\n        std::vector<double>& g         // OUT: gradient\n    ) {\n        assert(p >= 2 && p <= 16) ;\n        assert((p/2)*2 == p) ;\n        double f = 0.0 ;\n        if(volumic) {\n            switch(p) {\n            case 2: {\n                VoroFunc< IntegrationSimplex<2,TetVolume> > F ;\n                f = F.eval(mesh,nb,sym,C,X,Q,M,g) ;\n            } break ;\n            case 4: {\n                VoroFunc< IntegrationSimplex<4,TetVolume> > F ;\n                f = F.eval(mesh,nb,sym,C,X,Q,M,g) ;\n            } break ;\n            case 6: {\n                VoroFunc< IntegrationSimplex<6,TetVolume> > F ;\n                f = F.eval(mesh,nb,sym,C,X,Q,M,g) ;\n            } break ;\n            case 8: {\n                VoroFunc< IntegrationSimplex<8,TetVolume> > F ;\n                f = F.eval(mesh,nb,sym,C,X,Q,M,g) ;\n            } break ;\n            case 10: {\n                VoroFunc< IntegrationSimplex<10,TetVolume> > F ;\n                f = F.eval(mesh,nb,sym,C,X,Q,M,g) ;\n            } break ;\n            case 12: {\n                VoroFunc< IntegrationSimplex<12,TetVolume> > F ;\n                f = F.eval(mesh,nb,sym,C,X,Q,M,g) ;\n            } break ;\n            case 14: {\n                VoroFunc< IntegrationSimplex<14,TetVolume> > F ;\n                f = F.eval(mesh,nb,sym,C,X,Q,M,g) ;\n            } break ;\n            case 16: {\n                VoroFunc< IntegrationSimplex<16,TetVolume> > F ;\n                f = F.eval(mesh,nb,sym,C,X,Q,M,g) ;\n            } break ;\n            }\n        } else {\n            switch(p) {\n            case 2: {\n                VoroFunc< IntegrationSimplex<2,TriArea> > F ;\n                f = F.eval(mesh,nb,sym,C,X,Q,M,g) ;\n            } break ;\n            case 4: {\n                VoroFunc< IntegrationSimplex<4,TriArea> > F ;\n                f = F.eval(mesh,nb,sym,C,X,Q,M,g) ;\n            } break ;\n            case 6: {\n                VoroFunc< IntegrationSimplex<6,TriArea> > F ;\n                f = F.eval(mesh,nb,sym,C,X,Q,M,g) ;\n            } break ;\n            case 8: {\n                VoroFunc< IntegrationSimplex<8,TriArea> > F ;\n                f = F.eval(mesh,nb,sym,C,X,Q,M,g) ;\n            } break ;\n            case 10: {\n                VoroFunc< IntegrationSimplex<10,TriArea> > F ;\n                f = F.eval(mesh,nb,sym,C,X,Q,M,g) ;\n            } break ;\n            case 12: {\n                VoroFunc< IntegrationSimplex<12,TriArea> > F ;\n                f = F.eval(mesh,nb,sym,C,X,Q,M,g) ;\n            } break ;\n            case 14: {\n                VoroFunc< IntegrationSimplex<14,TriArea> > F ;\n                f = F.eval(mesh,nb,sym,C,X,Q,M,g) ;\n            } break ;\n            case 16: {\n                VoroFunc< IntegrationSimplex<16,TriArea> > F ;\n                f = F.eval(mesh,nb,sym,C,X,Q,M,g) ;\n            } break ;\n            }\n        }\n        return f ;\n    }\n   \n\n//=====================================================================\n\n\n#ifdef CVT_MULTITHREAD\n\n    /**\n     * Stores all the parameters required to evaluate F_Lp on a set of integration\n     * simplices. Manages also a local storage for the gradient.\n     */\n    class F_Lp_thread {\n    public:\n        void set_parameters(\n            bool volumic_in,                  // IN: false for surface meshing, true for volume meshing\n            unsigned int p_in,                // IN: Lp norm to be used\n            Mesh* mesh_in,                    // IN: the PLC\n            unsigned int nb_in,               // IN: number of integration simplices\n            const int* sym_in,                // IN: 10 integers per integration simplex:\n                                              //   - index of x0\n                                              //   - symbolic representation of C1,C2,C3 (3 integers each)\n            const vec3* C_in,                 // IN: C vertices of integration simplices (3 per integration simplex) \n            const std::vector<vec3>& X_in,    // IN: vertices\n            const std::vector<plane3>& Q_in,  // IN: boundary facets\n            const std::vector<mat3>& M_in     // IN: anisotropy matrix (one per integration simplex)\n        ) {\n            volumic = volumic_in ;\n            p = p_in ;\n            mesh = mesh_in ;\n            nb = nb_in ;\n            sym = sym_in ;\n            C = C_in ;\n            X = &X_in ;\n            Q = &Q_in ;\n            M = &M_in ;\n            g.resize(X->size()*3) ;\n        }\n\n        void run() {\n            std::fill(g.begin(), g.end(), 0.0) ;\n            f = compute_F_Lp_internal(volumic, p, mesh, nb, sym, C, *X, *Q, *M, g) ;\n        }\n\n        bool volumic ;\n        unsigned int p ;\n        Mesh* mesh ;\n        unsigned int nb ;\n        const int* sym ;\n        const vec3* C ;\n        const std::vector<vec3>* X ;\n        const std::vector<plane3>* Q ;\n        const std::vector<mat3>* M ;\n        double f ;\n        std::vector<double> g ;\n    } ;\n    \n    /**\n     * User API function, \n     * multithread implementation.\n     * 1) Partitions the set of integration simplices, \n     * 2) Calls compute_F_Lp_internal() in parallel,\n     * 3) Gathers the result.\n     */\n    double compute_F_Lp(\n        bool volumic,                  // IN: false for surface meshing, true for volume meshing\n        unsigned int p,                // IN: Lp norm to be used\n        Mesh* mesh,                    // IN: the PLC\n        const std::vector<int>& sym,   // IN: 10 integers per integration simplex:\n                                       //   - index of x0\n                                       //   - symbolic representation of C1,C2,C3 (3 integers each)\n        const std::vector<vec3>& C,    // IN: C vertices of integration simplices (3 per integration simplex) \n        const std::vector<vec3>& X,    // IN: vertices\n        const std::vector<plane3>& Q,  // IN: boundary facets\n        const std::vector<mat3>& M,    // IN: anisotropy matrix (one per integration simplex)\n        std::vector<double>& g         // OUT: gradient\n    ) {\n        // Get number of cores from Processor class.\n        unsigned int nb_threads = Processor::number_of_cores() ;\n        std::cerr << \"Evaluating F-Lp, using \" << nb_threads << \" threads \" << std::endl ;\n        std::vector<F_Lp_thread> threads(nb_threads) ;\n\n        unsigned int nb_integration_simplices = (unsigned int)sym.size() / 10 ;\n        unsigned int remaining = nb_integration_simplices ;\n        unsigned int batch_size = nb_integration_simplices / nb_threads ;\n\n        // Partition work (i.e. I and C arrays) into nb_threads blocs\n        const int*  cur_I = &sym[0] ;\n        const vec3* cur_C = &C[0] ;\n        for(unsigned int i=0; i<nb_threads-1; i++) {\n            threads[i].set_parameters(volumic, p, mesh, batch_size, cur_I, cur_C, X, Q, M) ;\n            cur_I += batch_size * 10 ;\n            cur_C += batch_size * 3 ;\n            remaining -= batch_size ;\n        }\n        threads[threads.size()-1].set_parameters(volumic, p, mesh, remaining, cur_I, cur_C, X, Q, M) ;\n\n        // Run the threads in parallel, using boost threads\n        //   Note: Intel TBB has lower thread creation overhead (has a thread pool),\n        // but we use here boost since LpCVT depends on CGAL that also depends on boost\n        // (and for large meshes, thread creation time is negligible).\n        boost::thread_group threads_impl ;\n        for(unsigned int i=0; i<threads.size(); i++) {\n            threads_impl.create_thread(boost::bind(&F_Lp_thread::run, &threads[i])) ;\n        }\n        threads_impl.join_all() ; // Waits for termination of all threads.\n\n        // Gather the result\n        double result = 0 ;\n        std::fill(g.begin(), g.end(), 0.0) ;\n        for(unsigned int i=0; i<threads.size(); i++) {\n            result += threads[i].f ;\n            for(unsigned int j=0; j<g.size(); j++) {\n                g[j] += threads[i].g[j] ;\n            }\n        }\n        return result ;\n    }   \n\n#else\n\n    /**\n     * User API function, \n     * monothread implementation.\n     * This is just a wrapper around compute_F_Lp_internal()\n     */\n    double compute_F_Lp(\n        bool volumic,                  // IN: false for surface meshing, true for volume meshing\n        unsigned int p,                // IN: Lp norm to be used\n        Mesh* mesh,                    // IN: the PLC\n        const std::vector<int>& sym,   // IN: 10 integers per integration simplex:\n                                       //   - index of x0\n                                       //   - symbolic representation of C1,C2,C3 (3 integers each)\n        const std::vector<vec3>& C,    // IN: C vertices of integration simplices (3 per integration simplex) \n        const std::vector<vec3>& X,    // IN: vertices\n        const std::vector<plane3>& Q,  // IN: boundary facets\n        const std::vector<mat3>& M,    // IN: anisotropy matrix (one per integration simplex)\n        std::vector<double>& g         // OUT: gradient\n    ) {\n        unsigned int nb = sym.size() / 10 ;\n        assert(sym.size() == nb*10) ;\n        assert(C.size() == nb*3) ;\n        return compute_F_Lp_internal(\n            volumic, p, mesh, nb,\n            &sym[0], &C[0], X, Q, M, g\n        ) ;\n    }   \n\n#endif\n\n}\n\n\n", "meta": {"hexsha": "9de177daf54a230937eb58f5a4e7fe6f7070658e", "size": 12559, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "CVUI/LpCVT/LpCVT/algebra/F_Lp.cpp", "max_stars_repo_name": "LeiYangJustin/CVUI4CellularSolid", "max_stars_repo_head_hexsha": "6fd13dfaf494d9e3800e95827502c4fd8a4f8210", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "CVUI/LpCVT/LpCVT/algebra/F_Lp.cpp", "max_issues_repo_name": "LeiYangJustin/CVUI4CellularSolid", "max_issues_repo_head_hexsha": "6fd13dfaf494d9e3800e95827502c4fd8a4f8210", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "CVUI/LpCVT/LpCVT/algebra/F_Lp.cpp", "max_forks_repo_name": "LeiYangJustin/CVUI4CellularSolid", "max_forks_repo_head_hexsha": "6fd13dfaf494d9e3800e95827502c4fd8a4f8210", "max_forks_repo_licenses": ["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.0424836601, "max_line_length": 117, "alphanum_fraction": 0.5289433872, "num_tokens": 3098, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7606506526772884, "lm_q2_score": 0.41869690935568665, "lm_q1q2_score": 0.3184820773753665}}
{"text": "//------------------------------------------------------------------------------\n// Construct a flaw distribution for a set of nodes according to a Weibull \n// (power-law) distribution.\n//------------------------------------------------------------------------------\n#include \"weibullFlawDistributionOwen.hh\"\n#include \"Utilities/globalNodeIDs.hh\"\n#include \"Utilities/mortonOrderIndices.hh\"\n#include \"NodeList/FluidNodeList.hh\"\n#include \"Field/Field.hh\"\n#include \"Field/FieldList.hh\"\n#include \"DataBase/DataBase.hh\"\n#include \"Distributed/Communicator.hh\"\n#include \"Utilities/allReduce.hh\"\n\n#include <boost/functional/hash.hpp>  // hash_combine\n\n#include <set>\n#include <algorithm>\n#include <limits>\n#include <unordered_map>\n#include <random>\n\nusing std::unordered_map;\nusing std::vector;\nusing std::string;\nusing std::pair;\nusing std::make_pair;\nusing std::cout;\nusing std::cerr;\nusing std::endl;\nusing std::min;\nusing std::max;\nusing std::abs;\n\nnamespace Spheral {\n\n//------------------------------------------------------------------------------\n// This version uses my own algorithm, stochastically seeding flaws in the range\n// [0, epsmax] where epsmax is chosen per node based on the nodal volume.\n//------------------------------------------------------------------------------\ntemplate<typename Dimension>\nField<Dimension, vector<double> >\nweibullFlawDistributionOwen(const unsigned seed,\n                            const double kWeibull,\n                            const double mWeibull,\n                            const FluidNodeList<Dimension>& nodeList,\n                            const int minFlawsPerNode,\n                            const double volumeMultiplier,\n                            const Field<Dimension, int>& mask) {\n\n  // Pre-conditions.\n  REQUIRE(kWeibull >= 0.0);\n  REQUIRE(mWeibull > 0.0);\n  REQUIRE(minFlawsPerNode > 0);\n  REQUIRE(mask.nodeListPtr() == &nodeList);\n\n  typedef typename Dimension::Scalar Scalar;\n  typedef KeyTraits::Key Key;\n\n  // Prepare the result.\n  Field<Dimension, vector<double> > flaws(\"Weibull flaw distribution\",\n                                          nodeList);\n\n  // Find the unique ordering to the nodes.\n  DataBase<Dimension> db;\n  db.appendNodeList(const_cast<FluidNodeList<Dimension>&>(nodeList));\n  FieldList<Dimension, Key> keyList = mortonOrderIndices(db);\n  const auto nglobal = db.globalNumInternalNodes();\n\n  // Is there anything to do?\n  if (nglobal > 0) {\n    const auto nlocal = nodeList.numInternalNodes();\n\n    // Identify the rank and number of domains.\n    const auto procID = Process::getRank();\n\n    // State for this NodeList.\n    const Field<Dimension, Scalar>& mass = nodeList.mass();\n    const Field<Dimension, Scalar>& rho = nodeList.massDensity();\n\n    // Construct a random number generator for each point.\n    // Note we hash with the ordering key to generate a unique but reproducible sequence for each point.\n    vector<std::mt19937> gens(nlocal);\n#pragma omp parallel for\n    for (auto i = 0u; i < nlocal; ++i) {\n      Key seedi = seed;\n      boost::hash_combine(seedi, keyList(0,i));\n      gens[i].seed(seedi);\n    }\n    vector<std::uniform_real_distribution<double>> uniform01(nlocal, std::uniform_real_distribution<double>(0.0, 1.0));\n\n    // Find the minimum and maximum node volumes.\n    double Vmin = std::numeric_limits<double>::max(), \n           Vmax = std::numeric_limits<double>::min();\n    for (auto i = 0u; i != nodeList.numInternalNodes(); ++i) {\n      if (mask(i) == 1) {\n        const double Vi = mass(i)/rho(i);\n        Vmin = min(Vmin, Vi);\n        Vmax = max(Vmax, Vi);\n      }\n    }\n    Vmin = allReduce(Vmin*volumeMultiplier, MPI_MIN, Communicator::communicator());\n    Vmax = allReduce(Vmax*volumeMultiplier, MPI_MAX, Communicator::communicator());\n    CHECK(Vmin > 0.0);\n    CHECK(Vmax >= Vmin);\n\n    // Compute the maximum strain we expect for the minimum volume.\n    const double epsMax2m = minFlawsPerNode/(kWeibull*Vmin);  // epsmax ** m\n\n    // Based on this compute the maximum number of flaws any node will have.  We'll use this to\n    // spin the random number generator without extra communiction.\n    const auto maxFlawsPerNode = std::max(1u, unsigned(kWeibull*Vmax*epsMax2m + 0.5));\n\n    // Generate the flaws on each node indepedently.\n    const double mInv = 1.0/mWeibull;\n    unsigned minNumFlaws = std::numeric_limits<int>::max();\n    unsigned maxNumFlaws = 0;\n    unsigned totalNumFlaws = 0;\n    double epsMin = std::numeric_limits<double>::max();\n    double epsMax = std::numeric_limits<double>::min();\n    double sumFlaws = 0.0;\n#pragma omp parallel for\n    for (auto i = 0u; i < nlocal; ++i) {\n      if (mask(i) == 1) {\n        CHECK(rho(i) > 0.0);\n        const auto Vi = mass(i)/rho(i) * volumeMultiplier;\n        CHECK(Vi > 0.0);\n        const auto numFlawsi = std::max(1u, std::min(maxFlawsPerNode, unsigned(kWeibull*Vi*epsMax2m + 0.5)));\n        const auto Ai = numFlawsi/(kWeibull*Vi);\n        CHECK(Ai > 0.0);\n        for (auto j = 0u; j < numFlawsi; ++j) {\n          flaws(i).push_back(pow(Ai * uniform01[i](gens[i]), mInv));\n        }\n        // Sort the flaws on each node by energy.\n        sort(flaws(i).begin(), flaws(i).end());\n#pragma omp critical\n        {\n          minNumFlaws = min(minNumFlaws, unsigned(flaws(i).size()));\n          maxNumFlaws = max(maxNumFlaws, unsigned(flaws(i).size()));\n          totalNumFlaws += flaws(i).size();\n          epsMin = min(epsMin, flaws(i).front());\n          epsMax = max(epsMax, flaws(i).back());\n          for (auto j = 0u; j < flaws(i).size(); ++j) sumFlaws += flaws(i)[j];\n        }\n      }\n    }\n\n    // Some diagnostic output.\n    const auto nused = std::max(1, mask.sumElements());\n    if (nglobal > 0) {\n      minNumFlaws = allReduce(minNumFlaws, MPI_MIN, Communicator::communicator());\n      maxNumFlaws = allReduce(maxNumFlaws, MPI_MAX, Communicator::communicator());\n      totalNumFlaws = allReduce(totalNumFlaws, MPI_SUM, Communicator::communicator());\n      epsMin = allReduce(epsMin, MPI_MIN, Communicator::communicator());\n      epsMax = allReduce(epsMax, MPI_MAX, Communicator::communicator());\n      sumFlaws = allReduce(sumFlaws, MPI_SUM, Communicator::communicator());\n    }\n    if (procID == 0) {\n      cerr << \"weibullFlawDistributionOwen: Min num flaws per node: \" << minNumFlaws << endl\n           << \"                             Max num flaws per node: \" << maxNumFlaws << endl\n           << \"                             Total num flaws       : \" << totalNumFlaws << endl\n           << \"                             Avg flaws per node    : \" << totalNumFlaws / nused << endl\n           << \"                             Min flaw strain       : \" << epsMin << endl\n           << \"                             Max flaw strain       : \" << epsMax << endl\n           << \"                             Avg node failure      : \" << sumFlaws / nused << endl;\n    }\n\n    // That's it.\n    BEGIN_CONTRACT_SCOPE\n    {\n      for (int i = 0; i != (int)nodeList.numInternalNodes(); ++i) {\n        if (mask(i) == 1) {\n          for (vector<double>::const_iterator itr = flaws(i).begin() + 1;\n               itr != flaws(i).end();\n               ++itr) ENSURE(*itr >= *(itr - 1));\n        }\n      }\n    }\n    END_CONTRACT_SCOPE\n  }\n\n  return flaws;\n}\n\n}\n\n", "meta": {"hexsha": "8daafac62708ec5e2f8b627165de0965f27a2355", "size": 7256, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/Damage/weibullFlawDistributionOwen.cc", "max_stars_repo_name": "jmikeowen/Spheral", "max_stars_repo_head_hexsha": "3e1082a7aefd6b328bd3ae24ca1a477108cfc3c4", "max_stars_repo_licenses": ["BSD-Source-Code", "BSD-3-Clause-LBNL", "FSFAP"], "max_stars_count": 22.0, "max_stars_repo_stars_event_min_datetime": "2018-07-31T21:38:22.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-29T08:58:33.000Z", "max_issues_repo_path": "src/Damage/weibullFlawDistributionOwen.cc", "max_issues_repo_name": "jmikeowen/Spheral", "max_issues_repo_head_hexsha": "3e1082a7aefd6b328bd3ae24ca1a477108cfc3c4", "max_issues_repo_licenses": ["BSD-Source-Code", "BSD-3-Clause-LBNL", "FSFAP"], "max_issues_count": 41.0, "max_issues_repo_issues_event_min_datetime": "2020-09-28T23:14:27.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-28T17:01:33.000Z", "max_forks_repo_path": "src/Damage/weibullFlawDistributionOwen.cc", "max_forks_repo_name": "jmikeowen/Spheral", "max_forks_repo_head_hexsha": "3e1082a7aefd6b328bd3ae24ca1a477108cfc3c4", "max_forks_repo_licenses": ["BSD-Source-Code", "BSD-3-Clause-LBNL", "FSFAP"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2019-12-01T07:00:06.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-15T21:12:39.000Z", "avg_line_length": 38.8021390374, "max_line_length": 119, "alphanum_fraction": 0.5836549063, "num_tokens": 1808, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6039318337259584, "lm_q2_score": 0.5273165233795671, "lm_q1q2_score": 0.31846323491861916}}
{"text": "//==============================================================================\n//         Copyright 2003 - 2011 LASMEA UMR 6602 CNRS/Univ. Clermont II\n//         Copyright 2009 - 2011 LRI    UMR 8623 CNRS/Univ Paris Sud XI\n//\n//          Distributed under the Boost Software License, Version 1.0.\n//                 See accompanying file LICENSE.txt or copy at\n//                     http://www.boost.org/LICENSE_1_0.txt\n//==============================================================================\n#ifndef BOOST_SIMD_TOOLBOX_ARITHMETIC_FUNCTIONS_SIMD_COMMON_HYPOT_HPP_INCLUDED\n#define BOOST_SIMD_TOOLBOX_ARITHMETIC_FUNCTIONS_SIMD_COMMON_HYPOT_HPP_INCLUDED\n\n#include <boost/simd/toolbox/arithmetic/functions/hypot.hpp>\n#include <boost/simd/include/functions/simd/tofloat.hpp>\n#include <boost/simd/include/functions/simd/abs.hpp>\n#include <boost/simd/include/functions/simd/min.hpp>\n#include <boost/simd/include/functions/simd/max.hpp>\n#include <boost/simd/include/functions/simd/is_inf.hpp>\n#include <boost/simd/include/functions/simd/is_nan.hpp>\n#include <boost/simd/include/functions/simd/logical_and.hpp>\n#include <boost/simd/include/functions/simd/logical_or.hpp>\n#include <boost/simd/include/functions/simd/plus.hpp>\n#include <boost/simd/include/functions/simd/minus.hpp>\n#include <boost/simd/include/functions/simd/unary_minus.hpp>\n#include <boost/simd/include/functions/simd/multiplies.hpp>\n#include <boost/simd/include/functions/simd/bitwise_and.hpp>\n#include <boost/simd/include/functions/simd/bitwise_or.hpp>\n#include <boost/simd/include/functions/simd/logical_or.hpp>\n#include <boost/simd/include/functions/simd/exponent.hpp>\n#include <boost/simd/include/functions/simd/ldexp.hpp>\n#include <boost/simd/include/functions/simd/if_else.hpp>\n#include <boost/simd/include/functions/simd/is_greater.hpp>\n#include <boost/simd/include/functions/simd/is_less.hpp>\n#include <boost/simd/include/functions/simd/sqrt.hpp>\n#include <boost/simd/include/functions/simd/any.hpp>\n#include <boost/simd/include/functions/simd/bitwise_cast.hpp>\n#include <boost/simd/include/constants/zero.hpp>\n#include <boost/simd/include/constants/inf.hpp>\n#include <boost/simd/include/functions/simd/max.hpp>\n#include <boost/simd/include/constants/int_splat.hpp>\n#include <boost/simd/sdk/simd/logical.hpp>\n#include <boost/dispatch/meta/as_floating.hpp>\n#include <boost/dispatch/meta/as_integer.hpp>\n\nnamespace boost { namespace simd { namespace ext\n{\n  BOOST_SIMD_FUNCTOR_IMPLEMENTATION( boost::simd::tag::hypot_, tag::cpu_\n                            , (A0)(X)\n                            , ((simd_<arithmetic_<A0>,X>))((simd_<arithmetic_<A0>,X>))\n                            )\n  {\n\n    typedef typename dispatch::meta::as_floating<A0>::type result_type;\n\n    BOOST_SIMD_FUNCTOR_CALL_REPEAT(2)\n    {\n      return boost::simd::hypot(tofloat(a0), tofloat(a1));\n    }\n  };\n\n  BOOST_SIMD_FUNCTOR_IMPLEMENTATION(boost::simd::tag::hypot_, tag::cpu_,\n                              (A0)(X),\n                              ((simd_<floating_<A0>,X>))\n                              ((simd_<floating_<A0>,X>))\n                            )\n  {\n    template < class T, class I = typename dispatch::meta::as_integer<T, signed>::type>\n    struct hypot_ctnts {};\n\n    template <class I, class CAT>\n    struct hypot_ctnts<simd::native<float, CAT>, I>\n    {\n      typedef I  int_type;\n      static inline int_type C1(){ return boost::simd::integral_constant<int_type, 50>();};\n      static inline int_type C2(){ return boost::simd::integral_constant<int_type, 60>();};\n      static inline int_type MC1(){ return boost::simd::integral_constant<int_type, -50>();};\n      static inline int_type MC2(){ return boost::simd::integral_constant<int_type, -60>();};\n      static inline int_type C3(){ return boost::simd::integral_constant<int_type, 0x00800000>();};\n      static inline int_type M1(){ return boost::simd::integral_constant<int_type, 0xfffff000>();};\n    };\n\n    template <class I, class CAT>\n    struct hypot_ctnts<simd::native<double, CAT>, I>\n    {\n      typedef I  int_type;\n      static inline int_type C1(){ return boost::simd::integral_constant<int_type, 500>();};\n      static inline int_type C2(){ return boost::simd::integral_constant<int_type, 600>();};\n      static inline int_type MC1(){ return boost::simd::integral_constant<int_type, -500>();};\n      static inline int_type MC2(){ return boost::simd::integral_constant<int_type, -600>();};\n      static inline int_type C3(){ return boost::simd::integral_constant<int_type, 0x0010000000000000ll>();}\n      static inline int_type M1(){ return boost::simd::integral_constant<int_type, 0xffffffff00000000ll>();};\n    };\n\n    typedef typename dispatch::meta::as_floating<A0>::type result_type;\n\n    BOOST_SIMD_FUNCTOR_CALL_REPEAT(2)\n    {\n      typedef typename dispatch::meta::as_integer<result_type>::type itype;\n      result_type r =  boost::simd::abs(a0);\n      result_type i =  boost::simd::abs(a1);\n      itype e =  exponent(boost::simd::max(i, r));\n      return  if_else( logical_or(logical_and(is_nan(a0), is_inf(a1)),\n                                  logical_and(is_nan(a1), is_inf(a0))),\n                       Inf<result_type>(),\n                       ldexp(sqrt(sqr(ldexp(r, -e))+sqr(ldexp(i, -e))), e)\n                       );\n//       typedef typename meta::as_logical<A0>::type bA0;\n//       typedef typename dispatch::meta::as_integer<A0, signed>::type int_type;\n//       typedef typename meta::as_logical<int_type>::type bint_type;\n//       typedef hypot_ctnts<A0, int_type> cts;\n//       A0 x =  boost::simd::abs(a0);\n//       A0 y =  boost::simd::abs(a1);\n//       bA0 tinf = is_inf(x+y);\n//       A0 a =  boost::simd::max(x, y);\n//       A0 b =  boost::simd::min(x, y);\n//       int_type ea =   exponent(a);\n//       int_type eb  =  exponent(b);\n//       bint_type te1 = gt(ea,cts::C1());\n//       bint_type te2 = lt(eb,cts::MC1());\n//       bool te3 = boost::simd::any(logical_or(te1, te2));\n//       int_type e = Zero<int_type>();\n//       if (te3)\n//       {\n//         e = select(te1, cts::MC2(), e);\n//         e = select(te2, cts::C1(),  e);\n//         a =  ldexp(a, e);\n//         b =  ldexp(b, e);\n//       }\n//       A0 w = a-b;\n//       bA0 test =  gt(w,b);\n//       A0 t1 = a& cts::M1();\n//       A0 t2 = a-t1;\n//       A0 w1_2  = (t1*t1-(b*(-b)-t2*(a+t1)));\n//       A0 y1 = b& cts::M1();\n//       A0 y2 = b - y1;\n//       t1 = bitwise_cast<A0>(bitwise_cast<int_type>(a)+cts::C3()) ;\n//       t2 = (a+a) - t1;\n//       A0 w2_2  = (t1*y1-(w*(-w)-(t1*y2+t2*b)));\n//       w =  select(test, w1_2, w2_2);\n//       w = boost::simd::sqrt(w);\n//       if (te3) w = ldexp(w, -e);\n//       return select(tinf, Inf<A0>(), w);\n    }\n  };\n} } }\n\n#endif\n", "meta": {"hexsha": "f30d1eb9a4eb3b28a3a3de636b04ba0dcd5bf0e7", "size": 6705, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/boost/simd/arithmetic/include/boost/simd/toolbox/arithmetic/functions/simd/common/hypot.hpp", "max_stars_repo_name": "timblechmann/nt2", "max_stars_repo_head_hexsha": "6c71f7063ca4e5975c9c019877e6b2fe07c9e4ce", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2016-09-14T00:23:53.000Z", "max_stars_repo_stars_event_max_datetime": "2018-01-14T12:51:18.000Z", "max_issues_repo_path": "modules/boost/simd/arithmetic/include/boost/simd/toolbox/arithmetic/functions/simd/common/hypot.hpp", "max_issues_repo_name": "timblechmann/nt2", "max_issues_repo_head_hexsha": "6c71f7063ca4e5975c9c019877e6b2fe07c9e4ce", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "modules/boost/simd/arithmetic/include/boost/simd/toolbox/arithmetic/functions/simd/common/hypot.hpp", "max_forks_repo_name": "timblechmann/nt2", "max_forks_repo_head_hexsha": "6c71f7063ca4e5975c9c019877e6b2fe07c9e4ce", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 45.612244898, "max_line_length": 109, "alphanum_fraction": 0.6199850858, "num_tokens": 1787, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7025300698514778, "lm_q2_score": 0.45326184801538616, "lm_q1q2_score": 0.3184300777472592}}
{"text": "/*\nCopyright 2009-2021 Nicolas Colombe\n\nPermission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n*/\n\n#pragma once\n\n#include <core/coredef.hpp>\n#include <core/pooledlist.hpp>\n#include <math/segment.hpp>\n#include <math/mathexp.hpp>\n\n#include <boost/rational.hpp>\n#include <boost/pool/object_pool.hpp>\n\nnamespace eXl\n{\n  template <typename IntReal = int32_t>\n  struct FastRational\n    :boost::less_than_comparable < FastRational<IntReal>,\n    boost::equality_comparable < FastRational<IntReal>,\n    boost::less_than_comparable2 < FastRational<IntReal>, IntReal,\n    boost::equality_comparable2 < FastRational<IntReal>, IntReal,\n    boost::addable < FastRational<IntReal>,\n    boost::subtractable < FastRational<IntReal>,\n    boost::multipliable < FastRational<IntReal>,\n    boost::dividable < FastRational<IntReal>,\n    boost::addable2 < FastRational<IntReal>, IntReal,\n    boost::subtractable2 < FastRational<IntReal>, IntReal,\n    boost::subtractable2_left < FastRational<IntReal>, IntReal,\n    boost::multipliable2 < FastRational<IntReal>, IntReal,\n    boost::dividable2 < FastRational<IntReal>, IntReal,\n    boost::dividable2_left < FastRational<IntReal>, IntReal,\n    boost::incrementable < FastRational<IntReal>,\n    boost::decrementable < FastRational<IntReal>\n    > > > > > > > > > > > > > > > >\n  {\n  public:\n\n    FastRational(IntReal iNum)\n      : m_N(iNum){}\n\n    FastRational(IntReal iNum, IntReal iDen)\n      : m_N(iNum)\n      , m_D(iDen)\n    {}\n\n    FastRational(FastRational const& iR)\n      : m_N(iR.m_N)\n      , m_D(iR.m_D)\n    {}\n\n    FastRational& operator=(IntReal i) { m_N = i; m_D = 1; return *this; }\n    FastRational& assign(IntReal n, IntReal d)\n    {\n      m_N = n;\n      m_D = d;\n      return *this;\n    }\n\n    IntReal numerator() const { return m_N; }\n    IntReal denominator() const { return m_D; }\n\n\n    FastRational& operator+= (const FastRational& r)\n    {\n      if(m_D == r.m_D)\n      {\n        m_N += r.m_N;\n      }\n      else\n      {\n        assign(m_N * r.m_D + r.m_N * m_D, m_D * r.m_D);\n        sanitize();\n      }\n      return *this;\n    }\n    FastRational& operator-= (const FastRational& r)\n    {\n      if(m_D == r.m_D)\n      {\n        m_N -= r.m_N;\n      }\n      else\n      {\n        assign(m_N * r.m_D - r.m_N * m_D, m_D * r.m_D);\n        sanitize();\n      }\n      return *this;\n    }\n    FastRational& operator*= (const FastRational& r)\n    {\n      assign(m_N * r.m_N, m_D * r.m_D);\n      sanitize();\n      return *this;\n    }\n    FastRational& operator/= (const FastRational& r)\n    {\n      assign(m_N * r.m_D, m_D * r.m_N);\n      sanitize();\n      return *this;\n    }\n\n    FastRational& operator+= (IntReal i) { m_N += i * m_D; return *this; }\n    FastRational& operator-= (IntReal i) { m_N -= i * m_D; return *this; }\n    FastRational& operator*= (IntReal i)\n    {\n      m_N *= i;\n      sanitize();\n    }\n    FastRational& operator/= (IntReal i)\n    {\n      m_D *= i;\n      sanitize();\n    }\n\n    const FastRational& operator++() { m_N += m_D; return *this; }\n    const FastRational& operator--() { m_N -= m_D; return *this; }\n    bool operator!() const { return !m_N; }\n\n    explicit operator bool() const { return operator !() ? false : true; }\n\n    explicit operator int() const\n    {\n      return m_N / m_D;\n    }\n\n    explicit operator float() const\n    {\n      return static_cast<float>(m_N) / m_D;\n    }\n\n    bool operator< (const FastRational& r) const\n    {\n      return (*this - r).m_N < 0;\n    }\n\n    bool operator== (const FastRational& r) const\n    {\n      return (*this - r).m_N == 0;\n    }\n\n    bool operator< (IntReal i) const\n    {\n      return m_N < i * m_D;\n    }\n\n    bool operator> (IntReal i) const\n    {\n      return m_N > i * m_D;\n    }\n\n    bool operator== (IntReal i) const\n    {\n      FastRational temp = *this;\n      temp.reduce();\n      return m_D == 1 && m_N == i;\n    }\n\n    void sanitize()\n    {\n      if (m_D < 0)\n      {\n        m_D *= -1;\n        m_N *= -1;\n      }\n    }\n\n    void reduce()\n    {\n      sanitize();\n\n      if (m_D == 1)\n      {\n        return;\n      }\n\n      IntReal pgcd = Math<IntReal>::PGCD(m_N, m_D);\n      m_N /= pgcd;\n      m_D /= pgcd;\n    }\n\n  protected:\n    IntReal m_N = 0;\n    IntReal m_D = 1;\n  };\n  \n  template <typename IntReal>\n  inline FastRational<IntReal> operator+ (const FastRational<IntReal>& r)\n  {\n    return r;\n  }\n\n  template <typename IntReal>\n  inline FastRational<IntReal> operator- (const FastRational<IntReal>& r)\n  {\n    return FastRational<IntReal>(-r.numerator(), r.denominator());\n  }\n\n  typedef /*boost::rational<int64_t>*/ /*float*/ FastRational<int64_t> QType;\n  typedef Vector2<QType> Vector2Q;\n\n  template <typename Real>\n  Vector2Q ToVec2Q(Vector2<Real> const& iVec)\n  {\n    return Vector2Q(iVec.X(), iVec.Y());\n  }\n\n  template <typename Real>\n  Vector2<Real> FromVec2Q(Vector2Q const& iVec)\n  {\n    return Vector2<Real>(static_cast<Real>(iVec.X()), static_cast<Real>(iVec.Y()));\n    //return Vector2<Real>(iVec.X().numerator() / iVec.X().denominator(), iVec.Y().numerator() / iVec.Y().denominator());\n  }\n\n  class EXL_MATH_API Intersector\n  {\n  public:\n\n    struct ActiveSegment\n    {\n      Vector2Q m_Point;\n      uint32_t m_Idx;\n    };\n\n    struct UserEvent\n    {\n      Vector2i m_Position;\n      uint32_t m_Idx;\n    };\n\n    typedef std::function<bool(Vector<ActiveSegment> const& iSweepLine, uint32_t iPosInSweepLine, Segment<QType> const& iCandidate)> Filter;\n    typedef std::function<void(Vector<ActiveSegment> const& iSweepLine, int32_t iLowSeg, int32_t iHighSeg, UserEvent const& iEvent)> EvtCallback;\n\n    struct Parameters\n    {\n      Filter m_Filter;\n      EvtCallback m_UsrEvtCb;\n      std::vector<UserEvent> m_UsrEvts;\n    };\n\n    Intersector();\n\n    Err IntersectSegments(Vector<Segmenti> const& iSegments, Vector<std::pair<uint32_t, Segmenti>>& oSegs, Parameters const& iParams = Parameters());\n\n  private:\n\n    struct Event\n    {\n      enum Type\n      {\n        Intersection,\n        End,\n        Start,\n        User,\n      };\n\n      Event(PooledList<uint32_t>::Pool& iPool, Vector2Q const& iPoint, uint32_t iSeg, Type iType);\n      Event(PooledList<uint32_t>::Pool& iPool, Vector2Q const& iPoint, uint32_t iSeg1, uint32_t iSeg2);\n      Event(Event const& iEvt);\n      Event& operator=(Event const& iEvt);\n      Event(Event&& iEvt);\n      Event& operator=(Event&& iEvt);\n\n      bool IsEmpty() const;\n\n      bool operator<(Event const& iOther) const;\n\n      Vector2Q m_Point;\n      mutable PooledList<uint32_t> m_SegmentsStart;\n      mutable PooledList<uint32_t> m_SegmentsInter;\n      mutable PooledList<uint32_t> m_SegmentsEnd;\n      //Type m_Type;\n    };\n\n    struct OrderedSeg\n    {\n      OrderedSeg(Segmenti const& iSeg, uint32_t iOrigSeg);\n\n      QType GetYAt(QType iX, Event const& iEvt) const;\n\n      Vector2Q m_Start;\n      Vector2Q m_End;\n      boost::optional<QType> m_Slope;\n      uint32_t m_OrigSeg;\n    };\n\n    void CheckIntersection(Event const& iEvt, OrderedSeg const& iSeg1, OrderedSeg const& iSeg2);\n    bool CheckIntersection(Event const& iEvt, OrderedSeg const& iSeg1, OrderedSeg const& iSeg2, boost::optional<Event>& outSeg);\n\n    void InsertEvent(Event&& iEvt);\n\n    void RemoveEvt(uint32_t iSeg1, uint32_t iSeg2);\n\n    void SortSegmentExtremities();\n\n    Vector<ActiveSegment> m_ActiveSegments;\n    Vector<uint32_t> m_SegInsertCount;\n    PooledList<uint32_t>::Pool m_SegListPool;\n    Vector<uint32_t> m_SortArray;\n\n    Vector<Event> m_EventQueue;\n\n    //MemoryPool m_EvtListAlloc;\n    //typedef std::multiset<Event, std::less<Event>, PooledAllocator<Event>> EventQueue;\n    //EventQueue m_EventQueue;\n    Vector<OrderedSeg> m_Segments;\n  };\n}", "meta": {"hexsha": "29df5f446bc948f217504017ff8453bce4a40ed8", "size": 8582, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/math/seginter.hpp", "max_stars_repo_name": "eXl-Nic/eXl", "max_stars_repo_head_hexsha": "a5a0f77f47db3179365c107a184bb38b80280279", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/math/seginter.hpp", "max_issues_repo_name": "eXl-Nic/eXl", "max_issues_repo_head_hexsha": "a5a0f77f47db3179365c107a184bb38b80280279", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/math/seginter.hpp", "max_forks_repo_name": "eXl-Nic/eXl", "max_forks_repo_head_hexsha": "a5a0f77f47db3179365c107a184bb38b80280279", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.3312101911, "max_line_length": 460, "alphanum_fraction": 0.6393614542, "num_tokens": 2399, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7025300573952054, "lm_q2_score": 0.4532618480153861, "lm_q1q2_score": 0.318430072101306}}
{"text": "#include \"../kontsevich_graph_series.hpp\"\n#include <ginac/ginac.h>\n#include <iostream>\n#include <fstream>\n#include <limits>\n#include \"../util/continued_fraction.hpp\"\n#include <Eigen/Dense>\n#include <Eigen/SparseCore>\n#include <Eigen/SparseQR>\n#include <Eigen/OrderingMethods>\nusing namespace std;\nusing namespace GiNaC;\n\ntypedef Eigen::Triplet<double> Triplet;\ntypedef Eigen::SparseMatrix<double> SparseMatrix;\n\ndouble threshold = 1e-5;\n\nint main(int argc, char* argv[])\n{\n    if (argc != 2 && argc != 3 && argc != 4 && argc != 5)\n    {\n        cout << \"Usage: \" << argv[0] << \" <graph-series-filename> [max-jacobiators] [max-jac-indegree] [--solve]\\n\\n\"\n             << \"Accepts only homogeneous power series: graphs with n internal vertices at order n.\\n\"\n             << \"The optional arguments [max-jacobiators] and [max-jac-indegree] restrict the types of differential consequences of Jacobi taken into account:\\n\"\n             << \"- [max-jacobiators] restricts the number of Jacobiators per differential consequence, while\\n\"\n             << \"- [max-jac-indegree] restricts the number of arrows falling on Jacobiators.\\n\"\n             << \"When the optional argument [--solve] is specified, the undetermined variables in the input are added to the linear system to-be-solved.\\n\";\n        return 1;\n    }\n\n    size_t max_jacobiators = numeric_limits<size_t>::max();\n    size_t max_jac_indegree = numeric_limits<size_t>::max();\n    if (argc == 3 || argc == 4 || argc == 5)\n        max_jacobiators = stoi(argv[2]);\n    if (argc == 4 || argc == 5)\n        max_jac_indegree = stoi(argv[3]);\n\n    // Reading in graph series\n    string graph_series_filename(argv[1]);\n    ifstream graph_series_file(graph_series_filename);\n    parser coefficient_reader;\n    bool homogeneous = true;\n    map<size_t, set< vector<size_t> > > in_degrees;\n    KontsevichGraphSeries<ex> graph_series = KontsevichGraphSeries<ex>::from_istream(graph_series_file,\n        [&coefficient_reader](std::string s) -> ex { return coefficient_reader(s); },\n        [&homogeneous, &in_degrees](KontsevichGraph graph, size_t order) -> bool\n                                   {\n                                       in_degrees[order].insert(graph.in_degrees());\n                                       return homogeneous &= graph.internal() == order;\n                                   }\n    );\n    size_t order = graph_series.precision();\n    if (!homogeneous)\n    {\n        cerr << \"Only accepting homogeneous power series: graphs with n internal vertices at order n.\\n\";\n        return 1;\n    }\n\n    // Find number of external vertices\n    // TODO: move to method in KontsevichGraphSum / KontsevichGraphSeries?\n    size_t external = 0;\n    for (size_t n = 0; n <= order; ++n)\n    {\n        if (graph_series[n].size() != 0)\n        {\n            external = graph_series[n].front().second.external();\n            break;\n        }\n    }\n\n    graph_series.reduce_mod_skew();\n\n    size_t counter = 0;\n    std::vector<symbol> coefficient_list;\n\n    if (argc == 5 && string(argv[4]) == \"--solve\")\n        for (auto namevar : coefficient_reader.get_syms())\n            coefficient_list.push_back(ex_to<symbol>(namevar.second));\n\n    std::map<symbol, KontsevichGraph, ex_is_less> kontsevich_jacobi_leibniz_graphs;\n\n    for (size_t n = 2; n <= order; ++n) // need at least 2 internal vertices for Jacobi\n    {\n        if (graph_series[n].size() == 0)\n            continue;\n\n        cout << \"h^\" << n << \":\\n\";\n\n        // First we choose the target vertices i,j,k of the Jacobiators (which contain 2 bivectors), in increasing order (without loss of generality)\n        \n        // Jacobi must have three distinct arguments, and not act on itself, but can act on other Jacobi\n\n        for (size_t k = 1; k <= min(n/2, max_jacobiators); ++k)\n        {\n            std::vector<size_t> jacobi_vertices(3*k, n + external);\n            CartesianProduct jacobi_indices(jacobi_vertices);\n            for (auto jacobi_index = jacobi_indices.begin(); jacobi_index != jacobi_indices.end(); ++jacobi_index)\n            {\n                bool accept = true;\n                for (size_t i = 0; i != k; ++i)\n                {\n                    if ((*jacobi_index)[i*3] >= (*jacobi_index)[i*3 + 1] || (*jacobi_index)[i*3 + 1] >= (*jacobi_index)[i*3 + 2]) // not strictly increasing\n                    {\n                        accept = false;\n                        break;\n                    }\n                }\n                if (!accept)\n                    continue;\n\n                // Then we choose the target vertices of the remaining n - 2*k bivectors, stored in a multi-index of length 2*(n-2*k)\n                // Here we have k fewer possible targets: out of the last 2*k internal vertices, the first k act as placeholders for the respective Jacobiators,\n                // to be replaced by the Leibniz rule later on\n                std::vector<size_t> remaining_edges(2*(n-2*k), n + external - k);\n                CartesianProduct indices(remaining_edges);\n                for (auto multi_index = indices.begin(); multi_index != indices.end(); ++multi_index)\n                {\n                    bool accept = true;\n                    for (size_t idx = 0; idx != n - 2*k; ++idx)\n                    {\n                        if ((*multi_index)[2*idx] >= (*multi_index)[2*idx+1])\n                        {\n                            accept = false; // accept only strictly increasing indices\n                            break;\n                        }\n                        // TODO: filter out tadpoles, maybe?\n                    }\n                    if (!accept)\n                        continue;\n\n                    // We build the list of targets for the graph, as described above (using i,j,k and the multi-index)\n                    std::vector<KontsevichGraph::VertexPair> targets(n);\n                    // first part:\n                    for (size_t idx = 0; idx != n - 2*k; ++idx)\n                        targets[idx] = {(*multi_index)[2*idx], (*multi_index)[2*idx+1]};\n                    // second part:\n                    for (size_t i = 0; i != k; ++i)\n                    {\n                        targets[n - 2*k + 2*i].first = KontsevichGraph::Vertex((*jacobi_index)[3*i]);\n                        targets[n - 2*k + 2*i].second = KontsevichGraph::Vertex((*jacobi_index)[3*i + 1]);\n                        targets[n - 2*k + 2*i + 1].first = KontsevichGraph::Vertex(n + external - 2*k + 2*i);\n                        targets[n - 2*k + 2*i + 1].second = KontsevichGraph::Vertex((*jacobi_index)[3*i + 2]);\n                    }\n\n                    KontsevichGraph template_graph(n, external, targets, 1, true);\n\n                    vector<size_t> indegrees = template_graph.in_degrees();\n                    if (in_degrees[n].find(indegrees) == in_degrees[n].end()) // skip terms\n                        continue;\n\n                    // Make vector of references to bad targets: those in first part with target >= (n + external - 2*k), the placeholders for the Jacobiators:\n                    std::map<KontsevichGraph::Vertex*, int> bad_targets;\n                    for (size_t idx = 0; idx != n - 2*k; ++idx) // look for bad targets in first part\n                    {\n                        if ((int)targets[idx].first >= (int)n + (int)external - 2*(int)k)\n                            bad_targets[&targets[idx].first] = (int)targets[idx].first - (n + external - 2*k);\n                        if ((int)targets[idx].second >= (int)n + (int)external - 2*(int)k)\n                            bad_targets[&targets[idx].second] = (int)targets[idx].second - (n + external - 2*k);\n                    }\n\n                    // Count number of arrows falling on Jacs:\n                    std::map<int, size_t> in_degree;\n                    bool acceptable = true;\n                    for (auto pair : bad_targets)\n                    {\n                        if (++in_degree[pair.second] == max_jac_indegree + 1)\n                        {\n                            acceptable = false;\n                            break;\n                        }\n                    }\n                    if (!acceptable)\n                        continue;\n\n                    KontsevichGraphSum<ex> graph_sum;\n\n                    // Replace bad targets by Leibniz rule:\n                    symbol coefficient(\"c_\" + to_string(k) + \"_\" + to_string(counter));\n                    std::vector<size_t> leibniz_sizes(bad_targets.size(), 2);\n                    CartesianProduct leibniz_indices(leibniz_sizes);\n                    for (auto leibniz_index = leibniz_indices.begin(); leibniz_index != leibniz_indices.end(); ++leibniz_index)\n                    {\n                        size_t idx = 0;\n                        for (auto& bad_target : bad_targets)\n                            *(bad_target.first) = KontsevichGraph::Vertex(external + n - 2*k + 2*(bad_target.second) + (*leibniz_index)[idx++]);\n\n                        for (size_t i = 0; i != k; ++i)\n                        {\n                            for (auto jacobi_targets_choice : std::vector< std::vector<KontsevichGraph::Vertex> >({ { targets[n-2*k+2*i].first, targets[n-2*k+2*i].second, targets[n-2*k+2*i+1].second },\n                                                                                                                    { targets[n-2*k+2*i].second, targets[n-2*k+2*i+1].second, targets[n-2*k+2*i].first },\n                                                                                                                    { targets[n-2*k+2*i+1].second, targets[n-2*k+2*i].first, targets[n-2*k+2*i].second } }))\n                            {\n                                // Set Jacobiator targets to one of the three permutatations\n                                targets[n-2*k+2*i].first = jacobi_targets_choice[0];\n                                targets[n-2*k+2*i].second = jacobi_targets_choice[1];\n                                targets[n-2*k+2*i+1].second = jacobi_targets_choice[2];\n\n                                KontsevichGraph graph(n, external, targets);\n\n                                graph_sum += KontsevichGraphSum<ex>({ { coefficient, graph } });\n                            }\n                        }\n                    }\n\n                    graph_sum.reduce_mod_skew();\n                    if (graph_sum.size() != 0)\n                    {\n                        cerr << \"\\r\" << ++counter;\n                        coefficient_list.push_back(coefficient);\n                        kontsevich_jacobi_leibniz_graphs[coefficient] = template_graph;\n                    }\n                    graph_series[n] -= graph_sum;\n                }\n            }\n        }\n    }\n\n    cout << \"\\nNumber of coefficients: \" << coefficient_list.size() << \"\\n\";\n    cout << \"\\nNumber of terms: \" << graph_series[order].size() << \"\\n\";\n    cout << \"\\nNumber of terms per coefficient: \" << (float)graph_series[order].size()/coefficient_list.size() << \"\\n\";\n\n    cout.flush();\n\n    cerr << \"\\nReducing...\\n\";\n    graph_series.reduce_mod_skew();\n\n    lst equations;\n\n    for (size_t n = 0; n <= order; ++n)\n        for (auto& term : graph_series[n])\n        {\n            cerr << term.second.encoding() << \"    \" << term.first << \"==0\\n\";\n            equations.append(term.first);\n        }\n\n    // Set up sparse matrix linear system\n\n    cerr << \"Setting up linear system for numerical solution...\\n\";\n    size_t rows = equations.nops();\n    size_t cols = coefficient_list.size();\n\n    Eigen::VectorXd b(rows);\n    SparseMatrix matrix(rows,cols);\n\n    std::vector<Triplet> tripletList;\n    size_t idx = 0;\n    for (ex equation : equations)\n    {\n        if (!is_a<add>(equation))\n            equation = lst({ equation });\n        for (ex term : equation)\n        {\n            if (!is_a<mul>(term))\n                term = lst({ term });\n            double prefactor = 1;\n            symbol coefficient(\"one\");\n            for (ex factor : term)\n            {\n                if (is_a<numeric>(factor))\n                    prefactor *= ex_to<numeric>(factor).to_double();\n                else if (is_a<symbol>(factor))\n                    coefficient = ex_to<symbol>(factor);\n            }\n            if (coefficient.get_name() == \"one\") // constant term\n                b(idx) = -prefactor;\n            else\n                tripletList.push_back(Triplet(idx,find(coefficient_list.begin(), coefficient_list.end(), coefficient) - coefficient_list.begin(), prefactor));\n                // NB: Eigen uses zero-based indices (contrast MATLAB, Mathematica)\n        }\n        ++idx;\n    }\n\n    matrix.setFromTriplets(tripletList.begin(), tripletList.end());\n    \n    cerr << \"Solving linear system numerically...\\n\";\n\n    Eigen::SparseQR< SparseMatrix, Eigen::COLAMDOrdering<int> > qr(matrix);\n    Eigen::VectorXd x = qr.solve(b);\n    \n    cerr << \"Residual norm = \" << (matrix * x - b).squaredNorm() << \"\\n\";\n\n    cerr << \"Rounding...\\n\";\n    x = x.unaryExpr([](double elem) { return fabs(elem) < threshold ? 0.0 : elem; });\n\n    cerr << \"Still a solution? Residual norm = \" << (matrix * x - b).squaredNorm() << \"\\n\";\n\n    cerr << \"Approximating numerical solution by rational solution...\\n\";\n\n    lst zero_substitution;\n    lst solution_substitution;\n    for (int i = 0; i != x.size(); i++)\n    {\n        ex result = best_rational_approximation(x.coeff(i), threshold);\n        if (result == 0)\n            zero_substitution.append(coefficient_list[i] == 0);\n        else\n            solution_substitution.append(coefficient_list[i] == result);\n    }\n\n    cerr << \"Substituting zeros...\\n\";\n\n    for (auto& order: graph_series)\n        for (auto& term : graph_series[order.first])\n            term.first = term.first.subs(zero_substitution);\n\n    cerr << \"Reducing zeros...\\n\";\n\n    graph_series.reduce_mod_skew();\n\n    for (size_t n = 0; n <= graph_series.precision(); ++n)\n    {\n        cout << \"h^\" << n << \":\\n\";\n        for (auto& term : graph_series[n])\n        {\n            cout << term.second.encoding() << \"    \" << term.first << \"\\n\";\n        }\n    }\n\n    cerr << \"Verifying solution...\\n\";\n\n    for (auto& order: graph_series)\n        for (auto& term : graph_series[order.first])\n            term.first = term.first.subs(solution_substitution);\n\n    graph_series.reduce_mod_skew();\n\n    cout << \"Do we really have a solution? \" << (graph_series == 0 ? \"Yes\" : \"No\") << \"\\n\";\n\n    if (graph_series == 0)\n    {\n        for (ex subs : solution_substitution)\n            cout << kontsevich_jacobi_leibniz_graphs[ex_to<symbol>(subs.lhs())].encoding() << \"    \" << subs << \"\\n\";\n    }\n}\n", "meta": {"hexsha": "8c6e4b26551873b9b628696f8eda9cff85d95ff4", "size": 14638, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/reduce_mod_jacobi.cpp", "max_stars_repo_name": "rburing/kontsevich_graph_series-", "max_stars_repo_head_hexsha": "20d443646d7047f5d273c2a44436ef7e5e9b63ca", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2017-10-04T20:07:55.000Z", "max_stars_repo_stars_event_max_datetime": "2019-09-16T17:54:51.000Z", "max_issues_repo_path": "tests/reduce_mod_jacobi.cpp", "max_issues_repo_name": "rburing/kontsevich_graph_series-cpp", "max_issues_repo_head_hexsha": "20d443646d7047f5d273c2a44436ef7e5e9b63ca", "max_issues_repo_licenses": ["MIT"], "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/reduce_mod_jacobi.cpp", "max_forks_repo_name": "rburing/kontsevich_graph_series-cpp", "max_forks_repo_head_hexsha": "20d443646d7047f5d273c2a44436ef7e5e9b63ca", "max_forks_repo_licenses": ["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.5654761905, "max_line_length": 204, "alphanum_fraction": 0.517488728, "num_tokens": 3432, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7401743620390163, "lm_q2_score": 0.4301473485858429, "lm_q1q2_score": 0.31838403932230064}}
{"text": "/*\n * To change this license header, choose License Headers in Project Properties.\n * To change this template file, choose Tools | Templates\n * and open the template in the editor.\n */\n\n#include <assert.h>\n\n#include <sstream>\n#include <fstream>\n#include <iomanip>\n#include <algorithm>\n#include <memory>\n#include <tuple>\n#include <vector>\n#include <math.h>\n#include <chrono>\n#include <stdlib.h>\n#include \"matcher.h\"\n#include <Eigen/Dense>\n//delete this probably\n#include <ctime>\n#include \"boost/filesystem.hpp\"\nnamespace fs = boost::filesystem;\n\nusing namespace std;\nusing namespace Eigen;\n\nnamespace PQ\n{\n\n\nMatcher::Matcher(string code_file)\n{\n    N = 200;\n    description.push_back(\"minutiae similarity\");\n\n    description.push_back(\"obtaining corr\");\n\n    description.push_back(\"second order fast\");\n\n    description.push_back(\"second order original\");\n\n    dist_N = 50;\n    table_dist.resize(dist_N*dist_N);\n    max_nrof_templates = 0;\n    int n = 0;\n    for(int i=0;i<dist_N; ++i)\n    {\n        for(int j=i;j<dist_N;++j)\n        {\n            table_dist[i*dist_N+j] = sqrt((i*16.0)*(i*16.0) +  (j*16.0)*(j*16.0));\n            table_dist[j*dist_N+i] = table_dist[i*dist_N+j];\n        }\n    }\n    //    load code book\n    ifstream is;\n    is.open(code_file, ifstream::binary);\n    // get length of file:\n    is.seekg(0, ios::end);\n    int length = is.tellg();\n\n    if( length<=0 )\n    {\n        cout<<\"codebook is empty!\"<<endl;\n    }\n    is.seekg(0, ios::beg);\n\n    nrof_subs = 0;\n    nrof_clusters=0;\n    sub_dim = 0;\n\n    is.read(reinterpret_cast<char*>(&nrof_subs),sizeof(short));\n    is.read(reinterpret_cast<char*>(&nrof_clusters),sizeof(short));\n    is.read(reinterpret_cast<char*>(&sub_dim),sizeof(short));\n\n    int len = nrof_subs*nrof_clusters*sub_dim;\n    if(len<=0)\n    {\n        cout<<\"codebook is empty!\"<<endl;\n    }\n\n    codewords = std::vector<float>(len);\n    float *pword = codewords.data();\n    for(int i=0;i<nrof_subs; ++i)\n    {\n        for(int j=0; j<nrof_clusters; ++j)\n        {\n            is.read(reinterpret_cast<char*>(pword),sizeof(float)*sub_dim);\n            pword += sub_dim;\n        }\n    }\n}\n\n\nint Matcher::List2List_matching(string latent_path, string rolled_path, string score_path)\n{\n    string template_file, score_file;\n\n    int nrof_latents = 0;\n    vector<fs::path> latent_template_files;\n    fs::directory_iterator end_itr;\n    for(fs::directory_iterator dir_itr(latent_path); dir_itr != end_itr; ++dir_itr)\n    {\n        if(dir_itr->path().extension() == \".dat\")\n        {\n            latent_template_files.push_back(dir_itr->path());\n            cout<<\"latent template file\"<<dir_itr->path()<<endl;\n            ++nrof_latents;\n        }\n    }\n    if(nrof_latents <= 0)\n    {\n        cout<<\"No latent templates found in directory: \"<<latent_path<<endl;\n        return -1;\n    }\n\n    int i,j,k;\n\n    int nrof_rolled = 0;\n    vector<fs::path> rolled_template_files;\n    for(fs::directory_iterator dir_itr(rolled_path); dir_itr != end_itr; ++dir_itr)\n    {\n    if(dir_itr->path().extension() == \".dat\")\n        {\n            rolled_template_files.push_back(dir_itr->path());\n            cout<<\"rolled template file\"<<dir_itr->path()<<endl;\n            ++nrof_rolled;\n        }\n    }\n    if(nrof_rolled <= 0)\n    {\n        cout<<\"No rolled templates found in directory: \"<<rolled_path<<endl;\n        return -1;\n    }\n    cout<<\"Gallery size: \"<<nrof_rolled<<endl;\n    {\n        using namespace std::chrono;\n        vector<high_resolution_clock::time_point> t(10);\n        duration<double, std::milli> time_span;\n        t[0] = high_resolution_clock::now();\n\n        for(i=0;i<nrof_latents; ++i)\n        {\n            vector<float> scores(nrof_rolled, -1);\n            cout<<latent_template_files[i]<<endl;\n\n            //load latent original template and create a latent FP object\n            LatentFPTemplate latent_FP{};\n            try {\n\t            latent_FP = load_latent_template(latent_template_files[i].string());\n\t    } catch (const std::exception&) {\n\t    \tcout<<\"No minutiae or texture templates found\"<<endl;\n                ofstream output;\n                output.open(score_path + latent_template_files[i].stem().string() + \".csv\");\n\n                output<<0<<endl;\n                output.close();\n\n                continue;\n\t    }\n            cout<<\"Latent minutiae templates: \"<<latent_FP.m_minu_templates.size()<<endl;\n            cout<<\"Latent texture templates: \"<<latent_FP.m_texture_templates.size()<<endl;\n            if(latent_FP.m_minu_templates.size()<=0 && latent_FP.m_texture_templates.size()<=0)\n            {\n\t\t\t\tcout<<\"No minutiae or texture templates found\"<<endl;\n                ofstream output;\n                output.open(score_path + latent_template_files[i].stem().string() + \".csv\");\n\n                output<<0<<endl;\n                output.close();\n\n                continue;\n            }\n\n            using namespace std::chrono;\n            high_resolution_clock::time_point t_start = high_resolution_clock::now();\n            int result = 0;\n\t        #pragma omp parallel for num_threads(8) schedule(static,16)\n            for(j=0;j<nrof_rolled; ++j)\n            {\n\n                RolledFPTemplate rolled_FP;\n                try {\n                \trolled_FP = load_rolled_template(rolled_template_files[j].string());\n                } catch (const std::exception&) {\n                    rolled_FP.m_minu_templates.clear();\n                    rolled_FP.m_texture_templates.clear();\n                }\n\n\t\t\t\tvector<float> score;\n\t\t\t\tresult = One2One_matching_selected_templates(latent_FP,rolled_FP,score);\n                if(result == 1){\n                    continue;\n                }\n                else if(result == 2){\n                    cout<<\"Comparison failed: rolled template is empty. Skipping.\"<<endl;\n                    continue;\n                }\n\t\t\t\tfloat final_score = score[0] + score[1] + score[2] + score[28]*0.3;\n                scores[j] = final_score;\n            }\n            if(result == 1){\n                cout<<\"Matching failed: latent template is empty. Skipping.\"<<endl;\n                continue;\n            }\n            auto t_end = high_resolution_clock::now();\n            duration<double, std::milli> duration = (t_end - t_start);\n\n\t\t\tofstream output;\n\t\t\toutput.open(score_path + latent_template_files[i].stem().string() + \".csv\");\n\n\t\t\tfor(j=0;j<nrof_rolled; ++j)\n\t\t\t{\n                output<<rolled_template_files[j]<<\",\"<<std::setprecision(3)<<std::fixed<<scores[j]<<endl;\n\t\t\t}\n\t\t\toutput.close();\n        }\n        t[1] = high_resolution_clock::now();\n        time_span = t[1] - t[0];\n        cout<<\"Total matching duration (ms): \"<<time_span.count()<<endl;\n\n\t\tauto timenow = chrono::system_clock::to_time_t(chrono::system_clock::now());\n    }\n    return 0;\n}\n\nint Matcher::One2List_matching(string latent_template_file_string, string rolled_list_file, string score_path)\n{\n\n    int i,j,k;\n\n    fs::path latent_template_file(latent_template_file_string);\n    string score_file = score_path + latent_template_file.stem().string() + \".csv\";\n\n    int nrof_rolled = 0;\n    vector<fs::path> rolled_template_files;\n    fs::directory_iterator end_itr;\n    for(fs::directory_iterator dir_itr(rolled_list_file); dir_itr != end_itr; ++dir_itr)\n    {\n    if(dir_itr->path().extension() == \".dat\")\n        {\n            rolled_template_files.push_back(dir_itr->path());\n            ++nrof_rolled;\n        }\n    }\n    if(nrof_rolled <= 0)\n    {\n        cout<<\"No rolled templates found in directory: \"<<rolled_list_file<<endl;\n        return -1;\n    }\n\n    // Create a vector of indices\n    // Allows us to output a sorted score list for use with the GUI\n    vector<int> ind(rolled_template_files.size(), 0);\n    for(int n = 0; n != rolled_template_files.size(); n++){\n        ind[n] = n;\n    }\n\n    {\n        using namespace std::chrono;\n        vector<high_resolution_clock::time_point> t(10);\n        duration<double, std::milli> time_span;\n        t[0] = high_resolution_clock::now();\n\n        vector<float> scores(nrof_rolled, -1);\n        cout<<\"Latent Query: \"<<latent_template_file<<endl;\n        cout<<\"Gallery size: \"<<nrof_rolled<<endl;\n\n\n        LatentFPTemplate latent_FP;\n        try {\n        \tlatent_FP = load_latent_template(latent_template_file.string());\n        } catch (const std::exception&) {\n            ofstream output;\n            output.open(score_file);\n\n            output<<0<<endl;\n            output.close();\n        }\n        if(latent_FP.m_minu_templates.size()<=0 && latent_FP.m_texture_templates.size()<=0)\n        {\n            ofstream output;\n            output.open(score_file);\n\n            output<<0<<endl;\n            output.close();\n\n        }\n\n        using namespace std::chrono;\n        high_resolution_clock::time_point t_start = high_resolution_clock::now();\n        int result = 0;\n        #pragma omp parallel for num_threads(8) schedule(static,16)\n        for(j=0;j<nrof_rolled; ++j)\n        {\n\n            RolledFPTemplate rolled_FP;\n            try {\n            \trolled_FP = load_rolled_template(rolled_template_files[j].string());\n\n            } catch (const std::exception&) {\n                rolled_FP.m_minu_templates.clear();\n                rolled_FP.m_texture_templates.clear();\n            }\n\n            vector<float> score;\n            result = One2One_matching_selected_templates(latent_FP,rolled_FP,score);\n            if(result == 1){\n                continue;\n            }\n            else if(result == 2){\n                cout<<\"Comparison failed: rolled template is empty. Skipping.\"<<endl;\n                continue;\n            }\n            float final_score = score[0] + score[1] + score[2] + score[28]*0.3;\n            scores[j] = final_score;\n        }\n        if(result == 1){\n            cout<<\"Matching failed: latent template is empty. Exiting.\"<<endl;\n            return 1;\n        }\n        auto t_end = high_resolution_clock::now();\n        duration<double, std::milli> duration = (t_end - t_start);\n        ofstream output;\n        output.open(score_file);\n\n        // Sort scores to create rank list\n        sort(ind.begin(), ind.end(), [&](const int& a, const int& b){\n                return (scores[a] > scores[b]);\n            }\n        );\n        output<<\"filename,score\"<<endl;\n        //generate correspondence files for top 24 only\n        cout<<\"Match Results\"<<endl;\n        cout<<\"----------------\"<<endl;\n        cout<<\"Rank     Filename      Score\"<<endl;\n        for(j=0; j<24; ++j)\n        {\n            if(j >= nrof_rolled){\n                break;\n            }\n            output<<to_string(j+1)<<rolled_template_files[ind[j]]<<\",\"<<scores[ind[j]]<<endl;\n            RolledFPTemplate rolled_FP;\n            try {\n\t            rolled_FP = load_rolled_template(rolled_template_files[ind[j]].string());\n\t    } catch (const std::exception&) {\n\t\t    rolled_FP.m_minu_templates.clear();\n                    rolled_FP.m_texture_templates.clear();\n\t    }\n            string latent_fname = latent_template_file.stem().string();\n            string rolled_fname = rolled_template_files[ind[j]].stem().string();\n            string corr_file = \"/LatentAFIS/scores/corr\" + latent_fname + \"_\" + rolled_fname;\n            vector<float> score;\n            One2One_matching_selected_templates(latent_FP,rolled_FP,score, true, corr_file);\n            cout<<to_string(j+1)<<\"        \"<<rolled_template_files[ind[j]].filename()<<\"       \"<<scores[ind[j]]<<endl;\n        }\n        output.close();\n        t[1] = high_resolution_clock::now();\n        time_span = t[1] - t[0];\n        cout<<\"Total matching duration (ms): \"<<time_span.count()<<endl;\n\n    }\n    return 0;\n}\n\nint Matcher::One2One_matching_all_templates(const LatentFPTemplate &latent_template, const RolledFPTemplate &rolled_template, vector<float> & score)\n{\n\n    score.resize(latent_template.m_minu_templates.size() + latent_template.m_texture_templates.size());\n    std::fill(score.begin(), score.end(), 0);\n\n   if(latent_template.m_minu_templates.size()<=0 && latent_template.m_texture_templates.size()<=0)\n   {\n        return 1;\n    }\n\n    if(rolled_template.m_minu_templates.size()<=0 && rolled_template.m_texture_templates.size()<=0)\n    {\n        return 2;\n    }\n    int i,j;\n\n    using namespace std::chrono;\n    vector<high_resolution_clock::time_point> t(10);\n\n    t[0] = high_resolution_clock::now();\n\n    for(i=0;i<latent_template.m_minu_templates.size() && rolled_template.m_minu_templates.size(); ++i)\n    {\n        float s = One2One_minutiae_matching(latent_template.m_minu_templates[i], rolled_template.m_minu_templates[0]);\n        score[i] = s;\n    }\n    t[1] = high_resolution_clock::now();\n\n    for(i=0;i<latent_template.m_texture_templates.size() && rolled_template.m_texture_templates.size()>0 ; ++i)\n    {\n        float s = One2One_texture_matching(latent_template.m_texture_templates[i], rolled_template.m_texture_templates[0]);\n        score[i+latent_template.m_minu_templates.size()] = s;\n    }\n\n   return 0;\n}\n\nint Matcher::One2One_matching_selected_templates(const LatentFPTemplate &latent_template, const RolledFPTemplate &rolled_template, vector<float> & score, bool save_corr, string corr_file)\nconst\n{\n    score.resize(latent_template.m_minu_templates.size() + latent_template.m_texture_templates.size());\n    std::fill(score.begin(), score.end(), 0);\n    vector<int> selected_ind{27-1, 3-1, 12-1};\n\n\n    if(latent_template.m_minu_templates.size()<=selected_ind[0] && latent_template.m_texture_templates.size()<=0)\n    {\n        return 1;\n    }\n\n    if(rolled_template.m_minu_templates.size()<=0 && rolled_template.m_texture_templates.size()<=0)\n    {\n        return 2;\n    }\n    int i,j;\n\n    using namespace std::chrono;\n    vector<high_resolution_clock::time_point> t(10);\n\n    t[0] = high_resolution_clock::now();\n\n\n    for(i=0;i<selected_ind.size() && rolled_template.m_minu_templates.size()>0; ++i)\n    {\n        int ind = selected_ind[i];\n        if(latent_template.m_minu_templates.size()<=ind)\n            continue;\n        string one_corr_file = corr_file + \"_\" + to_string(i) + \".csv\";\n        float s = One2One_minutiae_matching(latent_template.m_minu_templates[ind], rolled_template.m_minu_templates[0], save_corr, one_corr_file);\n        score[i] = s;\n    }\n    t[1] = high_resolution_clock::now();\n\n    for(i=0;i<min(1ul,latent_template.m_texture_templates.size()) && rolled_template.m_texture_templates.size()>0 ; ++i)\n    {\n        float s = One2One_texture_matching(latent_template.m_texture_templates[i], rolled_template.m_texture_templates[0]);\n        score[i+latent_template.m_minu_templates.size()] = s;\n    }\n\n    return 0;\n}\n\n\nfloat Matcher::One2One_minutiae_matching(const MinutiaeTemplate &latent_minu_template_in, const MinutiaeTemplate &rolled_minu_template_in, bool save_corr, string corr_file)\nconst\n{\n\t// XXX: Can we avoid the manipulation from eigen below and not dup?\n\tMinutiaeTemplate latent_minu_template(latent_minu_template_in);\n\tMinutiaeTemplate rolled_minu_template(rolled_minu_template_in);\n\n    // step 1: compute pairwise similarity between descriptors\n\n    int n_time = 0;\n    int i,j,k;\n\n    int des_len = rolled_minu_template.des_length();\n    if(des_len!=latent_minu_template.des_length()){\n        cout<<latent_minu_template.des_length()<<endl;\n\tcout<<rolled_minu_template.des_length()<<endl;\n\t}\n    assert(des_len == latent_minu_template.des_length());\n\n    float simi = 0.0;\n\n    using namespace std::chrono;\n    vector<high_resolution_clock::time_point> t(10);\n\n    Matrix<float, Eigen::Dynamic, Eigen::Dynamic> aa =  Map<Matrix<float, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>>(latent_minu_template.m_des.data(),latent_minu_template.m_minutiae.size(),des_len);\n    Matrix<float, Eigen::Dynamic, Eigen::Dynamic> bb =  Map<Matrix<float, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>>(rolled_minu_template.m_des.data(),rolled_minu_template.m_minutiae.size(),des_len);\n\n    MatrixXf  simi_matrix=aa*bb.transpose();\n\n    for(i=0; i<latent_minu_template.m_minutiae.size(); ++i)\n    {\n        for(j = 0; j<rolled_minu_template.m_minutiae.size(); ++j)\n        {\n            if(simi_matrix(i,j)<0)\n                simi_matrix(i,j) = 0;\n        }\n    }\n\n    //  step 2:  similarity normalization\n    VectorXf  rolled_simi_sum = simi_matrix.colwise().sum();\n    VectorXf  latent_simi_sum = simi_matrix.rowwise().sum();\n\n    int ind_1, ind_2 ;\n    vector<float> norm_simi_matrix(latent_minu_template.m_minutiae.size()*rolled_minu_template.m_minutiae.size());\n    float norm_simi=0.0;\n    for(i=0; i<latent_minu_template.m_minutiae.size(); ++i)\n    {\n        ind_1 = i*rolled_minu_template.m_minutiae.size();\n        for(j = 0; j<rolled_minu_template.m_minutiae.size(); ++j)\n        {\n            ind_2  = ind_1 + j;\n            norm_simi = simi_matrix(i,j)/(latent_simi_sum(i) + rolled_simi_sum(j) - simi_matrix(i,j)+0.000001); // //simi_matrix[ind_2]*\n            norm_simi_matrix[ind_2] = norm_simi;\n        }\n    }\n    // step 3: find top N correspondences using norm_simi_matrix;\n    // the sorting part can be replaced by a min-heap\n    std::vector<int> y(norm_simi_matrix.size());\n    std::iota(y.begin(), y.end(), 0);\n    auto comparator = [&norm_simi_matrix](int a, int b){ return norm_simi_matrix[a] > norm_simi_matrix[b]; };\n    std::sort(y.begin(), y.end(), comparator);\n\n    std::vector<tuple<float, int, int>>corr;\n    int topN = 120;\n    if(rolled_minu_template.m_minutiae.size()*latent_minu_template.m_minutiae.size()<topN)\n        topN = rolled_minu_template.m_minutiae.size()*latent_minu_template.m_minutiae.size();\n    for(i=0; i<topN ; ++i)\n    {\n        ind_1 = y[i]/rolled_minu_template.m_minutiae.size(); // latent minutiae  index\n        ind_2 = y[i] - ind_1*rolled_minu_template.m_minutiae.size(); // rolled minutiae index\n        simi = simi_matrix(ind_1,ind_2);\n        corr.push_back(make_tuple(simi,ind_1,ind_2));\n    }\n\n     // step 4: remove false correspondences using two graph matching\n    int d_thr = 30;\n    vector<tuple<float, int, int>> corr2 = LSS_R_Fast2_Dist_eigen(corr, latent_minu_template, rolled_minu_template, d_thr);\n\n\n    vector<tuple<float, int, int>> corr3  = LSS_R_Fast2(corr2, latent_minu_template, rolled_minu_template, d_thr);\n\n    if (save_corr){\n        ofstream output;\n        output.open(corr_file);\n        for(int i = 0; i < corr3.size(); i++){\n            output<<latent_minu_template.m_minutiae[get<1>(corr3[i])].x<<\",\"<<latent_minu_template.m_minutiae[get<1>(corr3[i])].y\n                <<\",\"<<rolled_minu_template.m_minutiae[get<2>(corr3[i])].x<<\",\"<<rolled_minu_template.m_minutiae[get<2>(corr3[i])].y<<endl;\n        }\n        output.close();\n    }\n\n\n    float score = 0.0;\n\n    for(i=0; i<corr3.size(); ++i)\n    {\n        score += get<0>(corr3[i]);\n    }\n    return score;\n\n}\n\nint Matcher::One2One_matching(string latent_file, string rolled_file)\n{\n    LatentFPTemplate latent_template{};\n    try {\n    \tload_latent_template(latent_file);\n    } catch (const std::exception&) {\n    \treturn (1);\n    }\n\n    RolledFPTemplate rolled_template{};\n    try {\n\t    rolled_template = load_rolled_template(rolled_file);\n    } catch (const std::exception&) {\n    \treturn (2);\n    }\n\n    vector<float> score;\n    int ret = One2One_matching_selected_templates(latent_template, rolled_template, score);\n\n    return ret;\n}\n\nfloat Matcher::One2One_texture_matching(const LatentTextureTemplate &latent_texture_template, const RolledTextureTemplatePQ &rolled_texture_template)\nconst\n{\n    // step 1: compute pairwise similarity between descriptors\n    int n_time = 0;\n    int i,j,k;\n\n    int des_len = rolled_texture_template.des_length();\n\n   std::unique_ptr<float[]> simi_matrix{new float[MaxNRolledMinu*MaxNLatentMinu]};\n   memset(simi_matrix.get(),0,MaxNRolledMinu*MaxNLatentMinu*sizeof(float));\n\n    const int numLatentMinutiae = std::min(latent_texture_template.m_minutiae.size(), MaxNLatentMinu);\n    const int numExemplarMinutiae = std::min(rolled_texture_template.m_minutiae.size(), MaxNRolledMinu);\n\n    float simi = 0.0;\n    float *p_latent_des, *p_latent_des0, *p_rolled_des;\n\n    using namespace std::chrono;\n    vector<high_resolution_clock::time_point> t(10);\n\n    t[n_time++] = high_resolution_clock::now();\n    float dist0=0.0, dist1= 0.0, dist2= 0, dist3=0.0, dist4 = 0.0; //, dist5, dist6,dist7, dist8;\n    int code1 = 0, code2 = 0, code3 = 0, code4=0;\n    float *p_dist_codewords0 = NULL, *p_dist_codewords1 = NULL, *p_dist_codewords2 =NULL;\n\n    /* Make a copy of the codewords from the latent texture template */\n    std::vector<float> latent_texture_template_m_dist_codewords_copy{latent_texture_template.m_dist_codewords};\n\n    int n=0;\n    int nrof_clusters3 = nrof_clusters*3, nrof_clusters2 = nrof_clusters*2;\n    const int method = 1;\n    if(method == 1)\n    {\n        for(i=0; i<numLatentMinutiae; ++i)\n        {\n            p_dist_codewords0 = latent_texture_template_m_dist_codewords_copy.data() + i*nrof_subs*nrof_clusters;\n            for(j=0; j<numExemplarMinutiae; ++j)\n            {\n                dist1 = 6.;\n                dist2 = 0.;\n                dist3 = 0.;\n                dist4 = 0.;\n                p_dist_codewords1 = p_dist_codewords0;\n                const unsigned char *p_des0 = rolled_texture_template.m_desPQ.data() + j* rolled_texture_template.des_length();\n                for(k=0; k<nrof_subs; k+=4, p_dist_codewords1+=4*nrof_clusters)\n                {\n                    code1 = *(p_des0+k);\n                    dist1 -= *(p_dist_codewords1 + code1);\n\n                    code2 = *(p_des0+k+1);\n                    dist2 -= *(p_dist_codewords1 + code2 + nrof_clusters);\n\n                    code3 = *(p_des0+k+2);\n                    dist3 -= *(p_dist_codewords1 + code3 + nrof_clusters2);\n\n                    code4 = *(p_des0+k+3);\n                    dist4 -= *(p_dist_codewords1 + code4 + nrof_clusters3);\n\n                }\n                simi_matrix[n++] = (dist1+dist2)+ (dist3+dist4);\n            }\n        }\n    }\n    else if (method==2)\n    {\n        int B1=64, B2 = 64;\n        for(i=0; i<numLatentMinutiae-B1; i+=B1)\n        {\n\n            for(j=0; j<numExemplarMinutiae-B2; j += B2)\n            {\n\n                for(int ii=i; ii<i+B1; ++ii)\n                {\n                    p_dist_codewords0 = latent_texture_template_m_dist_codewords_copy.data() + ii*nrof_subs*nrof_clusters;\n                    for(int jj=j; jj<j+B2; ++jj)\n                    {\n                       dist1 = 6.;\n                       dist2 = 0.;\n                       dist3 = 0.;\n                       dist4 = 0.;\n                       p_dist_codewords1 = p_dist_codewords0;\n                       const unsigned char *p_des0 = rolled_texture_template.m_desPQ.data() + jj* rolled_texture_template.des_length();\n\n\n                        for(k=0; k<nrof_subs; k+=4, p_dist_codewords1+=4*nrof_clusters)\n                        {\n                            code1 = *(p_des0+k);\n                            dist1 -= *(p_dist_codewords1 + code1);\n\n                            code2 = *(p_des0+k+1);\n                            dist2 -= *(p_dist_codewords1 + code2 + nrof_clusters);\n\n                            code3 = *(p_des0+k+2);\n                            dist3 -= *(p_dist_codewords1 + code3 + nrof_clusters2);\n\n                            code4 = *(p_des0+k+3);\n                            dist4 -= *(p_dist_codewords1 + code4 + nrof_clusters3);\n\n                        }\n                        simi_matrix[ii*numExemplarMinutiae+jj] = (dist1+dist2)+ (dist3+dist4);\n                    }\n                }\n            }\n        }\n    }\n    else if(method == 3)\n    {\n         int B1=64, B2 = 64;\n        for(i=0; i<numLatentMinutiae-B1; i+=B1)\n        {\n            p_dist_codewords0 = latent_texture_template_m_dist_codewords_copy.data() + i*nrof_subs*nrof_clusters;\n            for(j=0; j<numExemplarMinutiae-B2; j += B2)\n            {\n                p_dist_codewords1 = p_dist_codewords0;\n                const unsigned char *p_des0 = rolled_texture_template.m_desPQ.data() + j* rolled_texture_template.des_length();\n                for(int ii=i; ii<i+B1; ++ii)\n                {\n                    const unsigned char *p_des1 = p_des0;\n                    for(int jj=j; jj<j+B2; ++jj)\n                    {\n                       p_dist_codewords2 = p_dist_codewords1;\n                       dist1 = 6.;\n                       dist2 = 0.;\n                       dist3 = 0.;\n                       dist4 = 0.;\n\n                        for(k=0; k<nrof_subs; k+=4, p_dist_codewords2+=4*nrof_clusters)\n                        {\n                            code1 = *(p_des1+k);\n                            dist1 -= *(p_dist_codewords2 + code1);\n\n                            code2 = *(p_des1+k+1);\n                            dist2 -= *(p_dist_codewords2 + code2 + nrof_clusters);\n\n                            code3 = *(p_des1+k+2);\n                            dist3 -= *(p_dist_codewords2 + code3 + nrof_clusters2);\n\n                            code4 = *(p_des1+k+3);\n                            dist4 -= *(p_dist_codewords2 + code4 + nrof_clusters3);\n\n                        }\n                        simi_matrix[ii*numExemplarMinutiae+jj] = (dist1+dist2)+ (dist3+dist4);\n                        p_des1 +=  rolled_texture_template.des_length();\n                    }\n                    p_dist_codewords1 += nrof_subs*nrof_clusters;\n                }\n            }\n        }\n    }\n    else if(method==4)\n    {\n        for(i=0; i<numLatentMinutiae; ++i)\n        {\n            p_dist_codewords0 = latent_texture_template_m_dist_codewords_copy.data() + i*nrof_subs*nrof_clusters;\n            for(k=0; k<nrof_subs; ++k)\n            {\n                for(j=0; j<numExemplarMinutiae-4; j+=4)\n                {\n                    n = i*numExemplarMinutiae + j;\n                    const unsigned char *p_des0 = rolled_texture_template.m_desPQ.data() + j* rolled_texture_template.des_length() + k;\n                    const unsigned char *p_des1 = p_des0 + rolled_texture_template.des_length();\n                    const unsigned char *p_des2 = p_des1 + rolled_texture_template.des_length();\n                    const unsigned char *p_des3 = p_des2 + rolled_texture_template.des_length();\n\n                    dist0 -= *(p_dist_codewords0 + *p_des0);\n\n                    dist1 -= *(p_dist_codewords0 + *p_des1);\n\n                    dist2 -= *(p_dist_codewords0 + *p_des2);\n\n                    dist3 -= *(p_dist_codewords0 + *p_des3);\n\n                    simi_matrix[n] += dist0;\n                    simi_matrix[n+1] += dist1;\n                    simi_matrix[n+2] += dist2;\n                    simi_matrix[n+3] += dist3;\n                }\n            }\n        }\n    }\n    t[n_time] = high_resolution_clock::now();\n    duration<double, std::milli> time_span = t[n_time] - t[n_time-1];\n\n    vector<float> time(10);\n    time[n_time-1]+=time_span.count() ;  // minutiae similarity\n    n_time++;\n\n//\n    std::vector<tuple<float, int, int>>tmp_corr(numLatentMinutiae), corr(N);\n    float max_val;\n    float *psimi = simi_matrix.get();\n    int max_index;\n    for(i=0;i<numLatentMinutiae; ++i)\n    {\n\n        max_index = std::distance(psimi, std::max_element(psimi, psimi+numExemplarMinutiae));\n        max_val = *(psimi + max_index);\n        tmp_corr[i] = make_tuple(max_val,i,max_index);\n\n        psimi += numExemplarMinutiae;\n    }\n    if(tmp_corr.size()>N)\n    {\n        std::vector<int> y(tmp_corr.size());\n        std::iota(y.begin(), y.end(), 0);\n        auto comparator = [&tmp_corr](int a, int b){ return get<0>(tmp_corr[a]) > get<0>(tmp_corr[b]); };\n        std::sort(y.begin(), y.end(), comparator);\n\n        for(i=0;i<N; ++i)\n        {\n            corr[i] = tmp_corr[y[i]];\n        }\n    }\n    else\n        corr = tmp_corr;\n    t[n_time] = high_resolution_clock::now();\n\n    time_span = t[n_time] - t[n_time-1];\n\n    time[n_time-1]+=time_span.count() ;  // obtaining initial correspondences\n    n_time++;\n\n     // step 4: remove false correspondences using two graph matching\n    int d_thr = 30;\n    vector<tuple<float, int, int>> corr2 = LSS_R_Fast2_Dist_lookup(corr, latent_texture_template, rolled_texture_template, d_thr);\n\n\n    t[n_time] = high_resolution_clock::now();\n    time_span = t[n_time] - t[n_time-1];\n    time[n_time-1]+=time_span.count() ;   // second order graph matching: distance\n    n_time++;\n\n    vector<tuple<float, int, int>> corr3  = LSS_R_Fast2(corr2, latent_texture_template, rolled_texture_template, d_thr);\n\n\n    t[n_time] = high_resolution_clock::now();\n    time_span = t[n_time] - t[n_time-1];\n    time[n_time-1]+=time_span.count() ;   // second order graph matching: original\n    n_time++;\n\n    float score = 0.0;\n\n    for(i=0; i<corr3.size(); ++i)\n    {\n        score += get<0>(corr3[i]);\n    }\n    return score;\n\n}\n\nLatentFPTemplate Matcher::load_latent_template(const std::string &tname) const\n{\n\tstd::ifstream is{tname, ifstream::binary};\n\tif (!is)\n\t\tthrow std::runtime_error{\"Could not open \" + tname};\n\n\tis.seekg(0, std::ios_base::end);\n\tstd::vector<uint8_t> buf(is.tellg());\n\tis.seekg(0, std::ios_base::beg);\n\n\tis.read(reinterpret_cast<char *>(buf.data()), buf.size());\n\treturn (load_latent_template(buf));\n}\n\nLatentFPTemplate Matcher::load_latent_template(const std::vector<uint8_t> &buf) const\n{\n    LatentFPTemplate fp_template{};\n    /*\n     * FIXME: When using dynamic-sized containers, these maximums aren't\n     *        necessary. Preserving them for historical reasons (we probably\n     *        don't want to search when there's >2000 minutiae anyway).\n     */\n    static const short Max_Nrof_Minutiae = 2*1000; // including virtual minutiae. We only consider top 1000 minutiae including both real and virtual minutiae for each template.\n    static const short Max_Des_Length = 192;\n    static const short Max_BlkSize = 100;\n\n    std::istringstream is{\n        {reinterpret_cast<const char *>(buf.data()), buf.size()},\n        std::istringstream::binary};\n\n    // get length of file:\n    is.seekg(0, ios::end);\n    int length = is.tellg();\n\n    if( length<=0 )\n    {\n            throw std::runtime_error{\"Length of latent template is 0\"};\n    }\n    is.seekg(0, ios::beg);\n    short header[12];\n    short h,w,blkH,blkW;\n    unsigned char nrof_minu_template,nrof_texture_template;\n    short nrof_minutiae;\n\n\n    short nrof_minutiae_feature;\n    short des_len;\n    int i,j;\n\n    std::vector<short> x{};\n    std::vector<short> y{};\n    std::vector<float> ori{};\n    std::vector<float> des{};\n\n    for(int i=0; i<12; i++){\n        is.read(reinterpret_cast<char*>(&header[i]),sizeof(short));\n    }\n    /*\n     * FIXME: Seen at least once where a template appears corrupt (possibly\n     *        because an image was too large? it was a palm), so fail fast\n     *        before we trigger a segfault allocating one of the internal\n     *        structures.\n     */\n    static const short expectedHeader[12] = {\n        1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};\n    if (memcmp(header, expectedHeader, 12 * sizeof(short)) != 0) {\n    \tthrow std::runtime_error{\"Template appears corrupt (invalid header)\"};\n    }\n\n    is.read(reinterpret_cast<char*>(&h),sizeof(short));\n    is.read(reinterpret_cast<char*>(&w),sizeof(short));\n    is.read(reinterpret_cast<char*>(&blkH),sizeof(short));\n    is.read(reinterpret_cast<char*>(&blkW),sizeof(short));\n    is.read(reinterpret_cast<char*>(&nrof_minu_template),sizeof(unsigned char));\n    if(blkH>50)\n        blkH = 50;\n    if(blkW>50)\n        blkW = 50;\n    for(i=0;i<nrof_minu_template; ++i)\n    {\n        is.read(reinterpret_cast<char*>(&nrof_minutiae),sizeof(short));\n        if(nrof_minutiae<=0)\n            continue;\n        if(nrof_minutiae>Max_Nrof_Minutiae)\n        {\n            throw std::runtime_error{\"Number of minutiae is larger than \"\n                \"Max Number of Minutiae (latent): \" +\n                std::to_string(nrof_minutiae) + \">\" +\n                std::to_string(Max_Nrof_Minutiae)};\n        }\n        if(blkH>Max_BlkSize || blkW>Max_BlkSize)\n        {\n            throw std::runtime_error{\"The size of the ridge flow is larger \"\n                \"than maximum size: \" + std::to_string(Max_BlkSize)};\n        }\n        x.resize(nrof_minutiae);\n        is.read(reinterpret_cast<char*>(x.data()),sizeof(short)*nrof_minutiae);\n        y.resize(nrof_minutiae);\n        is.read(reinterpret_cast<char*>(y.data()),sizeof(short)*nrof_minutiae);\n        ori.resize(nrof_minutiae);\n        is.read(reinterpret_cast<char*>(ori.data()),sizeof(float)*nrof_minutiae);\n        is.read(reinterpret_cast<char*>(&des_len),sizeof(short));\n\n        des.resize(nrof_minutiae * des_len);\n        is.read(reinterpret_cast<char*>(des.data()),sizeof(float)*nrof_minutiae*des_len);\n\n        MinutiaeTemplate minu_template(nrof_minutiae,x,y,ori,des,blkH, blkW);\n        fp_template.add_template(minu_template);\n    }\n\n    is.read(reinterpret_cast<char*>(&nrof_texture_template),sizeof(unsigned char));\n\n   for(i=0;i<nrof_texture_template; ++i)\n    {\n        is.read(reinterpret_cast<char*>(&nrof_minutiae),sizeof(short));\n        if(nrof_minutiae<=0)\n            continue;\n        if(nrof_minutiae>Max_Nrof_Minutiae)\n        {\n            throw std::runtime_error{\"Number of minutiae is larger than Max \"\n                \"Number of Minutiae: \" + std::to_string(nrof_minutiae) + \">\" +\n                std::to_string(Max_Nrof_Minutiae)};\n        }\n        x.resize(nrof_minutiae);\n        is.read(reinterpret_cast<char*>(x.data()),sizeof(short)*nrof_minutiae);\n        y.resize(nrof_minutiae);\n        is.read(reinterpret_cast<char*>(y.data()),sizeof(short)*nrof_minutiae);\n        ori.resize(nrof_minutiae);\n        is.read(reinterpret_cast<char*>(ori.data()),sizeof(float)*nrof_minutiae);\n        is.read(reinterpret_cast<char*>(&des_len),sizeof(short));\n        des.resize(nrof_minutiae * des_len);\n        is.read(reinterpret_cast<char*>(des.data()),sizeof(float)*nrof_minutiae*des_len);\n\n\n        LatentTextureTemplate texture_template(nrof_minutiae,x,y,ori,des);\n        texture_template.compute_dist_to_codewords(this->codewords, nrof_subs,  sub_dim,  nrof_clusters);\n        fp_template.add_texture_template(texture_template);\n    }\n\n    return (fp_template);\n}\n\nRolledFPTemplate Matcher::load_rolled_template(const string &tname) const\n{\n\tstd::ifstream is{tname, ifstream::binary};\n\tif (!is)\n\t\tthrow std::runtime_error{\"Could not open \" + tname};\n\n\tis.seekg(0, std::ios_base::end);\n\tstd::vector<uint8_t> buf(is.tellg());\n\tis.seekg(0, std::ios_base::beg);\n\n\tis.read(reinterpret_cast<char *>(buf.data()), buf.size());\n\treturn (load_rolled_template(buf));\n}\n\nRolledFPTemplate Matcher::load_rolled_template(const std::vector<uint8_t> &buf) const\n{\n    RolledFPTemplate fp_template{};\n    /*\n     * FIXME: When using dynamic-sized containers, these maximums aren't\n     *        necessary. Preserving them for historical reasons (we probably\n     *        don't want to search when there's >2000 minutiae anyway).\n     */\n    static const short Max_Nrof_Minutiae = 2*1000; // including virtual minutiae. We only consider top 1000 minutiae including both real and virtual minutiae for each template.\n    static const short Max_Des_Length = 192;\n    static const short Max_BlkSize = 100;\n\n    std::istringstream is{\n        {reinterpret_cast<const char *>(buf.data()), buf.size()},\n        std::istringstream::binary};\n\n    // get length of file:\n    is.seekg(0, ios::end);\n    int length = is.tellg();\n\n    if( length<=10 )\n    {\n        throw std::runtime_error{\"Size of rolled template is \" +\n            std::to_string(length) + \" (<= 10)\"};\n    }\n    is.seekg(0, ios::beg);\n    short header[12];\n    short h,w,blkH,blkW;\n    unsigned char nrof_minu_template,nrof_texture_template;\n    short nrof_minutiae;\n\n\n    short nrof_minutiae_feature;\n    short des_len=96;\n    int i,j;\n\n    std::vector<short> x{};\n    std::vector<short> y{};\n    std::vector<float> ori{};\n\n    std::vector<float> des{};\n\n    for(int i=0; i<12; i++){\n        is.read(reinterpret_cast<char*>(&header[i]),sizeof(short));\n    }\n    /*\n     * FIXME: Seen at least once where a template appears corrupt (possibly\n     *        because an image was too large? it was a palm), so fail fast\n     *        before we trigger a segfault allocating one of the internal\n     *        structures.\n     */\n    static const short expectedHeader[12] = {\n        1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};\n    if (memcmp(header, expectedHeader, 12 * sizeof(short)) != 0) {\n    \tthrow std::runtime_error{\"Template appears corrupt (invalid header)\"};\n    }\n\n    is.read(reinterpret_cast<char*>(&h),sizeof(short));\n    is.read(reinterpret_cast<char*>(&w),sizeof(short));\n    is.read(reinterpret_cast<char*>(&blkH),sizeof(short));\n    is.read(reinterpret_cast<char*>(&blkW),sizeof(short));\n    is.read(reinterpret_cast<char*>(&nrof_minu_template),sizeof(unsigned char));\n    if(blkH>50)\n        blkH = 50;\n    if(blkW>50)\n        blkW = 50;\n    for(i=0;i<nrof_minu_template; ++i)\n    {\n        is.read(reinterpret_cast<char*>(&nrof_minutiae),sizeof(short));\n        if(nrof_minutiae<=0)\n            continue;\n        if(nrof_minutiae>Max_Nrof_Minutiae)\n        {\n            throw std::runtime_error{\"Number of minutiae is larger than Max \"\n                \"Number of Minutiae: \" + std::to_string(nrof_minutiae) + \">\" +\n                std::to_string(Max_Nrof_Minutiae)};\n        }\n        if(blkH>Max_BlkSize || blkW>Max_BlkSize)\n        {\n            throw std::runtime_error{\"The size of the ridge flow is larger \"\n                \"than maximum size: \" + std::to_string(Max_BlkSize)};\n        }\n        x.resize(nrof_minutiae);\n        is.read(reinterpret_cast<char*>(x.data()),sizeof(short)*nrof_minutiae);\n        y.resize(nrof_minutiae);\n        is.read(reinterpret_cast<char*>(y.data()),sizeof(short)*nrof_minutiae);\n        ori.resize(nrof_minutiae);\n        is.read(reinterpret_cast<char*>(ori.data()),sizeof(float)*nrof_minutiae);\n        is.read(reinterpret_cast<char*>(&des_len),sizeof(short));\n\n        des.resize(nrof_minutiae * des_len);\n        is.read(reinterpret_cast<char*>(des.data()),sizeof(float)*nrof_minutiae*des_len);\n\n        MinutiaeTemplate minu_template(nrof_minutiae,x,y,ori,des,blkH, blkW);\n        fp_template.add_template(minu_template);\n    }\n\n    is.read(reinterpret_cast<char*>(&nrof_texture_template),sizeof(unsigned char));\n\n   for(i=0;i<nrof_texture_template; ++i)\n    {\n        is.read(reinterpret_cast<char*>(&nrof_minutiae),sizeof(short));\n        if(nrof_minutiae<=0)\n            continue;\n        if(nrof_minutiae>Max_Nrof_Minutiae)\n        {\n            throw std::runtime_error{\"Number of minutiae is larger than Max \"\n                \"Number of Minutiae: \" + std::to_string(nrof_minutiae) + \">\" +\n                std::to_string(Max_Nrof_Minutiae)};\n        }\n        x.resize(nrof_minutiae);\n        is.read(reinterpret_cast<char*>(x.data()),sizeof(short)*nrof_minutiae);\n        y.resize(nrof_minutiae);\n        is.read(reinterpret_cast<char*>(y.data()),sizeof(short)*nrof_minutiae);\n        ori.resize(nrof_minutiae);\n        is.read(reinterpret_cast<char*>(ori.data()),sizeof(float)*nrof_minutiae);\n        is.read(reinterpret_cast<char*>(&des_len),sizeof(short));\n        des.resize(nrof_minutiae * des_len);\n        is.read(reinterpret_cast<char*>(des.data()),sizeof(float)*nrof_minutiae*des_len);\n\n        RolledTextureTemplatePQ texture_template(nrof_minutiae,x,y,ori,des);\n        fp_template.add_texture_template(texture_template);\n    }\n\n    return (fp_template);\n}\n\nvector<tuple<float, int, int>>  Matcher::LSS_R_Fast2_Dist(vector<tuple<float, int, int>> &corr, const SingleTemplate & latent_template, const SingleTemplate & rolled_template, float d_thr)\nconst\n{\n    int num = corr.size();\n    vector<float> H(num*num);\n\n    vector<short> flag_latent(latent_template.m_minutiae.size()),flag_rolled(rolled_template.m_minutiae.size());\n\n    int i,j,k;\n\n    float dist_1, dist_2, dist;\n    float dx_1, dy_1, dx_2, dy_2;\n\n    for(i=0; i<num-1; ++i)\n    {\n        const MinuPoint p_latent_minutia_1 = latent_template.m_minutiae[get<1>(corr[i])];\n        const MinuPoint p_rolled_minutia_1 = rolled_template.m_minutiae[get<2>(corr[i])];\n        for(j=i+1; j<num;++j)\n        {\n            const MinuPoint p_latent_minutia_2 = latent_template.m_minutiae[get<1>(corr[j])];\n            const MinuPoint p_rolled_minutia_2 = rolled_template.m_minutiae[get<2>(corr[j])];\n\n            dx_1 = p_latent_minutia_1.x-p_latent_minutia_2.x;\n            dx_2 = p_rolled_minutia_1.x-p_rolled_minutia_2.x;\n\n            dy_1 = p_latent_minutia_1.y-p_latent_minutia_2.y;\n            dy_2 = p_rolled_minutia_1.y-p_rolled_minutia_2.y;\n\n            dist_1 = (dx_1*dx_1)+(dy_1*dy_1);\n            dist_1 = sqrt(dist_1);\n\n\n            dist_2 = (dx_2*dx_2)+(dy_2*dy_2);\n            dist_2 = sqrt(dist_2);\n\n            dist = fabs(dist_1-dist_2);\n\n            H[i*num+j] = (30-dist)/(25.0);\n            if(H[i*num+j]>1)\n                H[i*num+j] = 1.0;\n            else if(H[i*num+j]<0)\n                H[i*num+j] = 0.0;\n\n            H[j*num+i] = H[i*num+j];\n        }\n    }\n\n    vector<float> S(num),S1(num);\n\n    float s0 = 1.0/num;\n    for(i=0; i<num; ++i)\n        S[i] = get<0>(corr[i]);\n\n\n    float sum = 0.0;\n    for(i=0;i<5 ; ++i)\n    {\n        sum = 0.0;\n        for(j=0;j<num; ++j)\n        {\n            S1[j] = 0;\n            for(k=0; k<num;++k)\n            {\n                //if(H[j*num+k])\n                S1[j] += H[j*num+k]*S[k];\n            }\n            sum += S1[j];\n        }\n        sum = 1.0/(sum+0.0001);\n        for(j=0;j<num; ++j)\n        {\n            S[j] = S1[j]*sum;\n        }\n    }\n\n    // sort the S\n    // the sorting part can be replaced by a min-heap\n    std::vector<int> y(S.size());\n    std::iota(y.begin(), y.end(), 0);\n    auto comparator = [&S](int a, int b){ return S[a] > S[b]; };\n    std::sort(y.begin(), y.end(), comparator);\n\n    vector<tuple<float, int, int>>  new_corr;\n    vector<int>  selected_ind;\n    short ind;\n    for(i=0; i<num; ++i)\n    {\n        ind = y[i];\n        if(S[ind]<0.0001)\n            break;\n        if((flag_latent[get<1>(corr[ind])] == 1) || (flag_rolled[get<2>(corr[ind])] == 1))\n            continue;\n\n        if(i==0)\n        {\n            selected_ind.push_back(ind);\n            new_corr.push_back(make_tuple(get<0>(corr[ind]),get<1>(corr[ind]),get<2>(corr[ind])));\n\n            flag_latent[get<1>(corr[ind])] = 1;\n            flag_rolled[get<2>(corr[ind])] = 1;\n        }\n        else\n        {\n            int found =0;\n            for(j=0;j<selected_ind.size(); ++j)\n            {\n                if(H[ind*num+selected_ind[j]]<0.00001)\n                {\n                    found = 1;\n                    break;\n                }\n            }\n            if(found==0)\n            {\n                selected_ind.push_back(ind);\n                new_corr.push_back(make_tuple(get<0>(corr[ind]),get<1>(corr[ind]),get<2>(corr[ind])));\n\n                flag_latent[get<1>(corr[ind])] = 1;\n                flag_rolled[get<2>(corr[ind])] = 1;\n            }\n        }\n    }\n\n    return new_corr;\n}\n\nvector<tuple<float, int, int>>  Matcher::LSS_R_Fast2_Dist_lookup(vector<tuple<float, int, int>> &corr, const SingleTemplate & latent_template, const SingleTemplate & rolled_template, float d_thr)\nconst\n{\n    int num = corr.size();\n    std::unique_ptr<float[]> H{new float [num*num]()};\n    vector<short> flag_latent(latent_template.m_minutiae.size()),flag_rolled(rolled_template.m_minutiae.size());\n\n    int i,j,k;\n\n    float dist_1, dist_2, dist;\n    int  dx_1, dy_1, dx_2, dy_2;\n\n    for(i=0; i<num-1; ++i)\n    {\n        const MinuPoint p_latent_minutia_1 = latent_template.m_minutiae[get<1>(corr[i])];\n        const MinuPoint p_rolled_minutia_1 = rolled_template.m_minutiae[get<2>(corr[i])];\n        for(j=i+1; j<num;++j)\n        {\n            const MinuPoint p_latent_minutia_2 = latent_template.m_minutiae[get<1>(corr[j])];\n            const MinuPoint p_rolled_minutia_2 = rolled_template.m_minutiae[get<2>(corr[j])];\n\n            dx_1 = p_latent_minutia_1.x-p_latent_minutia_2.x;\n            dx_2 = p_rolled_minutia_1.x-p_rolled_minutia_2.x;\n\n            dx_1 = abs(dx_1);\n            dx_2 = abs(dx_2);\n            dy_1 = p_latent_minutia_1.y-p_latent_minutia_2.y;\n            dy_2 = p_rolled_minutia_1.y-p_rolled_minutia_2.y;\n\n            dy_1 = abs(dy_1);\n            dy_2 = abs(dy_2);\n\n            if((dx_1>=dist_N) || (dx_2>=dist_N) || (dy_1>=dist_N) || (dy_2>=dist_N))\n                continue;\n\n            dist_1 = table_dist[dx_1*dist_N+dy_1];\n\n            dist_2 = table_dist[dx_2*dist_N+dy_2];\n\n            dist = fabs(dist_1-dist_2);\n            if(dist>d_thr)\n                continue;\n\n            H[i*num+j] = (30-dist)/(25.0);\n            if(H[i*num+j]>1)\n                H[i*num+j] = 1.0;\n            else if(H[i*num+j]<0)\n                H[i*num+j] = 0.0;\n            H[j*num+i] = H[i*num+j];\n        }\n    }\n\n    Matrix<float, Eigen::Dynamic, Eigen::Dynamic> aa =  Map<Matrix<float, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>>(H.get(),num,num);\n\n    float sum = 0.0;\n    VectorXf b(num);\n    VectorXf c;\n    for(i=0; i<num; ++i)\n        b(i) = get<0>(corr[i]);\n    for(i=0;i<3 ; ++i)\n    {\n        c = aa*b;\n        sum = c.sum();\n        b = c*(1./(sum+0.00001));\n    }\n\n    vector<float> S(num);\n    for(i=0;i<num; ++i)\n    {\n        S[i] = b(i);\n    }\n\n    // sort S\n    std::vector<int> y(S.size());\n    std::iota(y.begin(), y.end(), 0);\n    auto comparator = [&S](int a, int b){ return S[a] > S[b]; };\n    std::sort(y.begin(), y.end(), comparator);\n\n\n    vector<tuple<float, int, int>>  new_corr;\n    vector<int>  selected_ind;\n    short ind;\n    for(i=0; i<num; ++i)\n    {\n\n        ind = y[i];\n        if(S[ind]<0.0001)\n            break;\n        if((flag_latent[get<1>(corr[ind])] == 1) || (flag_rolled[get<2>(corr[ind])] == 1))\n            continue;\n\n        if(i==0)\n        {\n            selected_ind.push_back(ind);\n            new_corr.push_back(make_tuple(get<0>(corr[ind]),get<1>(corr[ind]),get<2>(corr[ind])));\n\n            flag_latent[get<1>(corr[ind])] = 1;\n            flag_rolled[get<2>(corr[ind])] = 1;\n        }\n        else\n        {\n            int found = 0;\n            for(j=0;j<selected_ind.size(); ++j)\n            {\n                if(H[ind*num+selected_ind[j]]<0.00001)\n                {\n                    found = 1;\n                    break;\n                }\n            }\n            if(found==0)\n            {\n                selected_ind.push_back(ind);\n                new_corr.push_back(make_tuple(get<0>(corr[ind]),get<1>(corr[ind]),get<2>(corr[ind])));\n\n                flag_latent[get<1>(corr[ind])] = 1;\n                flag_rolled[get<2>(corr[ind])] = 1;\n            }\n        }\n    }\n\n    return new_corr;\n}\n\nvector<tuple<float, int, int>>  Matcher::LSS_R_Fast2_Dist_eigen(vector<tuple<float, int, int>> &corr, const SingleTemplate & latent_template, const SingleTemplate & rolled_template, float d_thr)\nconst\n{\n    int num = corr.size();\n    std::unique_ptr<float[]> H{new float [num*num]()};\n\n    vector<short> flag_latent(latent_template.m_minutiae.size()),flag_rolled(rolled_template.m_minutiae.size());\n\n    int i,j,k;\n\n    MinuPoint *p_latent_minutia_1, *p_latent_minutia_2, *p_rolled_minutia_1, *p_rolled_minutia_2;\n    float dist_1, dist_2, dist;\n    float dx_1, dy_1, dx_2, dy_2;\n\n    for(i=0; i<num-1; ++i)\n    {\n        const MinuPoint p_latent_minutia_1 = latent_template.m_minutiae[get<1>(corr[i])];\n        const MinuPoint p_rolled_minutia_1 = rolled_template.m_minutiae[get<2>(corr[i])];\n        for(j=i+1; j<num;++j)\n        {\n            const MinuPoint p_latent_minutia_2 = latent_template.m_minutiae[get<1>(corr[j])];\n            const MinuPoint p_rolled_minutia_2 = rolled_template.m_minutiae[get<2>(corr[j])];\n\n            dx_1 = p_latent_minutia_1.x-p_latent_minutia_2.x;\n            dx_2 = p_rolled_minutia_1.x-p_rolled_minutia_2.x;\n\n\n            dy_1 = p_latent_minutia_1.y-p_latent_minutia_2.y;\n            dy_2 = p_rolled_minutia_1.y-p_rolled_minutia_2.y;\n\n\n            dist_1 = (dx_1*dx_1)+(dy_1*dy_1);\n            dist_1 = sqrt(dist_1);\n\n            dist_2 = (dx_2*dx_2)+(dy_2*dy_2);\n            dist_2 = sqrt(dist_2);\n            dist = fabs(dist_1-dist_2);\n           if(dist>d_thr)\n                continue;\n\n            H[i*num+j] = (30-dist)/(25.0);\n            if(H[i*num+j]>1)\n                H[i*num+j] = 1.0;\n            else if(H[i*num+j]<0)\n                H[i*num+j] = 0.0;\n\n            H[j*num+i] = H[i*num+j];\n        }\n    }\n\n    Matrix<float, Eigen::Dynamic, Eigen::Dynamic> aa =  Map<Matrix<float, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>>(H.get(),num,num);\n\n    float sum = 0.0;\n    VectorXf b(num);\n    VectorXf c;\n    for(i=0; i<num; ++i)\n        b(i) = get<0>(corr[i]);\n    for(i=0;i<5 ; ++i)\n    {\n        c = aa*b;\n        sum = c.sum();\n        b = c*(1./(sum+0.00001));\n    }\n\n    vector<float> S(num);\n    for(i=0;i<num; ++i)\n    {\n        S[i] = b(i);\n    }\n    // sort the S\n    // the sorting part can be replaced by a min-heap\n    std::vector<int> y(S.size());\n    std::iota(y.begin(), y.end(), 0);\n    auto comparator = [&S](int a, int b){ return S[a] > S[b]; };\n    std::sort(y.begin(), y.end(), comparator);\n\n    vector<tuple<float, int, int>>  new_corr;\n    vector<int>  selected_ind;\n    short ind;\n    for(i=0; i<num; ++i)\n    {\n\n        ind = y[i];\n        if(S[ind]<0.0001)\n            break;\n        if((flag_latent[get<1>(corr[ind])] == 1) || (flag_rolled[get<2>(corr[ind])] == 1))\n            continue;\n\n        if(i==0)\n        {\n            selected_ind.push_back(ind);\n            new_corr.push_back(make_tuple(get<0>(corr[ind]),get<1>(corr[ind]),get<2>(corr[ind])));\n\n            flag_latent[get<1>(corr[ind])] = 1;\n            flag_rolled[get<2>(corr[ind])] = 1;\n        }\n        else\n        {\n            int found =0;\n            for(j=0;j<selected_ind.size(); ++j)\n            {\n                if(H[ind*num+selected_ind[j]]<0.00001)\n                {\n                    found = 1;\n                    break;\n                }\n            }\n            if(found==0)\n            {\n                selected_ind.push_back(ind);\n                new_corr.push_back(make_tuple(get<0>(corr[ind]),get<1>(corr[ind]),get<2>(corr[ind])));\n\n                flag_latent[get<1>(corr[ind])] = 1;\n                flag_rolled[get<2>(corr[ind])] = 1;\n            }\n        }\n    }\n\n    return new_corr;\n}\n\nvector<tuple<float, int, int>>  Matcher::LSS_R_Fast2(vector<tuple<float, int, int>> &corr, const SingleTemplate & latent_template, const SingleTemplate & rolled_template, int d_thr)\nconst\n{\n    int num = corr.size();\n    vector<bool> H(num*num);\n    vector<short> flag_latent(latent_template.m_minutiae.size()),flag_rolled(rolled_template.m_minutiae.size());\n\n    int i,j,k;\n\n    float dist_1, dist_2;\n    float angle_1, angle_2, angle_diff;\n    float line_angle_1, line_angle_2;\n    float dx_1,dx_2,dy_1,dy_2;\n\n\n    for(i=0; i<num-1; ++i)\n    {\n        const MinuPoint p_latent_minutia_1 = latent_template.m_minutiae[get<1>(corr[i])];\n        const MinuPoint p_rolled_minutia_1 = rolled_template.m_minutiae[get<2>(corr[i])];\n        for(j=i+1; j<num;++j)\n        {\n            const MinuPoint p_latent_minutia_2 = latent_template.m_minutiae[get<1>(corr[j])];\n            const MinuPoint p_rolled_minutia_2 = rolled_template.m_minutiae[get<2>(corr[j])];\n\n            angle_1 = p_latent_minutia_1.ori-p_latent_minutia_2.ori;\n            angle_1 = adjust_angle(angle_1);\n\n            angle_2 = p_rolled_minutia_1.ori-p_rolled_minutia_2.ori;\n            angle_2 = adjust_angle(angle_2);\n\n            angle_diff = fabs(angle_1 - angle_2);\n\n            if(angle_diff>PI)\n               angle_diff = 2*PI - angle_diff;\n\n\n\n            if(angle_diff>PI/4.)\n                continue;\n\n            dx_1 = p_latent_minutia_1.x-p_latent_minutia_2.x;\n            dy_1 = p_latent_minutia_1.y-p_latent_minutia_2.y;\n\n\n\n            line_angle_1 = -atan2(dy_1,dx_1);\n            angle_1 = p_latent_minutia_1.ori - line_angle_1;\n            angle_1 = adjust_angle(angle_1);\n\n\n            dx_2 = p_rolled_minutia_1.x-p_rolled_minutia_2.x;\n            dy_2 = p_rolled_minutia_1.y-p_rolled_minutia_2.y;\n\n            line_angle_2 = -atan2(dy_2,dx_2);\n            angle_2 = p_rolled_minutia_1.ori - line_angle_2;\n            angle_2 = adjust_angle(angle_2);\n\n            angle_diff = fabs(angle_1 - angle_2);\n\n            if(angle_diff>PI)\n               angle_diff = 2*PI - angle_diff;\n            if(angle_diff>PI/6.)\n                continue;\n\n\n\n            angle_1 = p_latent_minutia_2.ori - line_angle_1;\n            angle_1 = adjust_angle(angle_1);\n\n\n            angle_2 = p_rolled_minutia_2.ori - line_angle_2;\n            angle_2 = adjust_angle(angle_2);\n\n            angle_diff = fabs(angle_1 - angle_2);\n\n            if(angle_diff>PI)\n               angle_diff = 2*PI - angle_diff;\n            if(angle_diff>PI/6.)\n                continue;\n\n            H[i*num+j] = true;\n            H[j*num+i] = true;\n        }\n    }\n\n    vector<float> S(num),S1(num);\n\n    float s0 = 1.0/num;\n    for(i=0; i<num; ++i)\n        S[i] = s0;\n\n    float sum = 0.0;\n    for(i=0;i<5 ; ++i)\n    {\n        sum = 0.0;\n        for(j=0;j<num; ++j)\n        {\n            S1[j] = 0;\n            for(k=0; k<num;++k)\n            {\n                if(H[j*num+k])\n                   S1[j] += S[k];\n            }\n            sum += S1[j];\n        }\n        sum = 1.0/(sum+0.00001);\n        for(j=0;j<num; ++j)\n        {\n            S[j] = S1[j]*sum;\n        }\n    }\n\n    s0 = 0.0;\n\n    // sort the S\n    // the sorting part can be replaced by a min-heap\n    std::vector<int> y(S.size());\n    std::iota(y.begin(), y.end(), 0);\n    auto comparator = [&S](int a, int b){ return S[a] > S[b]; };\n    std::sort(y.begin(), y.end(), comparator);\n\n\n    vector<tuple<float, int, int>>  new_corr;\n    vector<int> selected_ind;\n    short ind;\n    for(i=0; i<num; ++i)\n    {\n        ind = y[i];\n        if(S[ind]<0.001)\n            break;\n        if((flag_latent[get<1>(corr[ind])] == 1) || (flag_rolled[get<2>(corr[ind])] == 1))\n            continue;\n\n          if(i==0)\n        {\n            selected_ind.push_back(ind);\n            new_corr.push_back(make_tuple(get<0>(corr[ind]),get<1>(corr[ind]),get<2>(corr[ind])));\n\n            flag_latent[get<1>(corr[ind])] = 1;\n            flag_rolled[get<2>(corr[ind])] = 1;\n        }\n        else\n        {\n            int found =0;\n            for(j=0;j<selected_ind.size(); ++j)\n            {\n                if(!H[ind*num+selected_ind[j]])\n                {\n                    found = 1;\n                    break;\n                }\n            }\n            if(found==0)\n            {\n                selected_ind.push_back(ind);\n                new_corr.push_back(make_tuple(get<0>(corr[ind]),get<1>(corr[ind]),get<2>(corr[ind])));\n\n                flag_latent[get<1>(corr[ind])] = 1;\n                flag_rolled[get<2>(corr[ind])] = 1;\n            }\n\n        }\n    }\n\n    return new_corr;\n}\n\nfloat Matcher::adjust_angle(float angle)\nconst\n{\n    if(angle>PI)\n        angle -= 2*PI;\n    else if (angle<-PI)\n    {\n        angle += 2*PI;\n    }\n    return angle;\n}\n}\n", "meta": {"hexsha": "7f2c41c2a3d549856e635d17e376f879a2b43855", "size": 55173, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "matching/matcher.cpp", "max_stars_repo_name": "gfiumara/MSU-LatentAFIS", "max_stars_repo_head_hexsha": "682464b0bc4501977f1304c51e2638c0ee89d87c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "matching/matcher.cpp", "max_issues_repo_name": "gfiumara/MSU-LatentAFIS", "max_issues_repo_head_hexsha": "682464b0bc4501977f1304c51e2638c0ee89d87c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "matching/matcher.cpp", "max_forks_repo_name": "gfiumara/MSU-LatentAFIS", "max_forks_repo_head_hexsha": "682464b0bc4501977f1304c51e2638c0ee89d87c", "max_forks_repo_licenses": ["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.236746988, "max_line_length": 206, "alphanum_fraction": 0.5763688761, "num_tokens": 15002, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7401743620390162, "lm_q2_score": 0.43014734858584286, "lm_q1q2_score": 0.3183840393223006}}
{"text": "// This function is used to conduct the Polyhedron Projection using Double Description Method\n\n#include \"RobotInfo.h\"\n#include \"CommonHeader.h\"\n#include <setoper.h>\n#include <cdd.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <time.h>\n#include <math.h>\n#include <string.h>\n#include <bits/stdc++.h>\n#include <sstream>\n#include <iterator>\n#include <boost/algorithm/string.hpp>\n\nstatic string cone_file_name = \"CCV\";\n\nstatic double eps = 1e-8;\n\nstatic void String2Coordinates(const string& str_line, std::vector<Vector3>& ConeVertices)\n{\n  // This function is used to transform string into coordinates\n  std::istringstream buf(str_line);\n  std::istream_iterator<std::string> beg(buf), end;\n  std::vector<std::string> tokens(beg, end); // done!\n  int Type = std::stoi (tokens[0]);\n  switch (Type)\n  {\n    case 1:\n    {\n      double x = std::stod(tokens[1]);\n      double y = std::stod(tokens[2]);\n      Vector3 ConeVertex(x, y, 0.0);\n      ConeVertices.push_back(ConeVertex);\n    }\n    break;\n    default:\n    break;\n  }\n}\n\nstatic bool INEEmptyValidator()\n{\n  // This function is used to make sure that if the cone_file_name + \".ext\" is empty then no need to read it anymore.\n  string cone_file_path = cone_file_name + \".ext\";\n  ifstream ConeInfofile (cone_file_path);\n  string str_line;\n  string keyword=\"region found empty\";\n  bool ValidFlag = true;\n  if (ConeInfofile.is_open())\n  {\n    while (getline (ConeInfofile, str_line))\n    {\n      int EmptyPos = str_line.find(keyword);\n      if (EmptyPos != string::npos)\n      {\n        ValidFlag =  false;\n      }\n    }\n    ConeInfofile.close();\n  }\n  else std::cerr << \"Unable to open\" + cone_file_name + \".ext for Empty Validation\"<<std::endl;\n  return ValidFlag;\n}\n\nstatic bool INEZeroValidator()\n{\n  // This function is used to make sure that if the cone_file_name + \".ext\" is empty then no need to read it anymore.\n  string cone_file_path = cone_file_name + \".ext\";\n  ifstream ConeInfofile (cone_file_path);\n  string str_line;\n  string keyword=\"begin\";\n  bool ValidFlag = true;\n  bool StartFlag = false;\n  if (ConeInfofile.is_open())\n  {\n    while (getline (ConeInfofile, str_line))\n    {\n      switch (StartFlag)\n      {\n        case true:\n        {\n          vector<string> strs;\n          boost::split(strs,str_line, boost::is_any_of(\"  \"));\n          if(strs[0]==\"0\")\n          {\n            ValidFlag = false;\n          }\n          StartFlag = false;\n        }\n        break;\n        default:\n        {\n        }\n        break;\n      }\n      int ZeroPos = str_line.find(keyword);\n      if (ZeroPos != string::npos)\n      {\n        StartFlag =  true;;\n      }\n    }\n    ConeInfofile.close();\n  }\n  else std::cerr << \"Unable to open\" + cone_file_name + \".ext for Zero Validation\"<<std::endl;\n  return ValidFlag;\n}\n\nstatic std::vector<Vector3> INEReader()\n{\n  std::vector<Vector3>  ConeVertices;\n\n  bool EmptyFlag = INEEmptyValidator();\n  bool ZeroFlag = INEZeroValidator();\n\n  switch (EmptyFlag)\n  {\n    case false:\n    {\n      std::printf(\"INE File Empty Failure!\\n\");\n      return ConeVertices;\n    }\n    break;\n    default:\n    {\n\n    }\n    break;\n  }\n\n  switch (ZeroFlag)\n  {\n    case false:\n    {\n      std::printf(\"INE File Zero Failure!\\n\");\n      return ConeVertices;\n    }\n    break;\n    default:\n    {\n\n    }\n    break;\n  }\n\n  // This function is used to read in the cone file.\n  string cone_file_path = cone_file_name + \".ext\";\n  ifstream ConeInfofile (cone_file_path);\n\n  string str_line;\n  string start_keyword=\"real\";\n  string end_keyword=\"end\";\n\n  int valid_flag = 0;\n  if (ConeInfofile.is_open())\n  {\n    while (getline (ConeInfofile, str_line))\n    {\n      int start_pos = str_line.find(start_keyword);\n      int end_pos = str_line.find(end_keyword);\n      if(end_pos != string::npos)\n      {\n        valid_flag = 0;\n      }\n      switch (valid_flag)\n      {\n        case 1:\n        {\n          String2Coordinates(str_line, ConeVertices);\n        }\n        break;\n        default:\n        break;\n      }\n      if (start_pos != string::npos)\n      {\n        valid_flag = 1;\n      }\n    }\n    ConeInfofile.close();\n  }\n  else std::cerr << \"Unable to open\" + cone_file_name + \".ext\"<<std::endl;\n\n  return ConeVertices;\n}\n\nstatic void INEWriter(const std::vector<Vector3>& ConeInequalities)\n{\n  // It has been noticed that based on the pure cddlib, the generated vertices are not correct.\n  // As a result, a file write/read process has to be conducted.\n  string cone_file_path = cone_file_name + \".ine\";\n  ofstream ConeInfofile (cone_file_path);\n  /*\n      Header\n  */\n  ConeInfofile<<\"H-representation\"<<endl;\n  ConeInfofile<<\"begin\"<<endl;\n  ConeInfofile<<\" \"<<std::to_string(ConeInequalities.size())<<\" 3 real\"<<endl;\n\n  for (int i = 0; i < ConeInequalities.size(); i++)\n  {\n    Vector3 ConeInequality = ConeInequalities[i];\n    ConeInfofile<<\"\\t\"<<std::to_string(ConeInequality.x)<<\" \"<<std::to_string(ConeInequality.y)<<\" \"<<std::to_string(ConeInequality.z)<<endl;\n  }\n  ConeInfofile<<\"end\"<<endl;\n  ConeInfofile.close();\n}\n\nstatic Matrix PolyhedralProjection(const std::vector<Vector3> & ActContactPositions, const std::vector<Vector3> & ConeUnit, const int & EdgeNo, int &FailureFlag)\n{\n  // This function is used to project the feasible contact wrench cone\n  /*\n    For each of the vector in ConeUnit, a new projected Conic Vector should be computed.\n  */\n  dd_PolyhedraPtr poly;\n  dd_MatrixPtr A, B, G;\n  dd_rowrange m;\n  dd_colrange d;\n  dd_ErrorType err;\n\n  FailureFlag = 0;\n\n  dd_set_global_constants();                  /* First, this must be called to use cddlib. */\n\n  m = ConeUnit.size();\n  d = 6 + 1;        // Here 6 means the force and momentum balance\n\n  A = dd_CreateMatrix(m,d);\n  for (int i = 0; i < ConeUnit.size(); i++)\n  {\n    for (int j = 0; j < d; j++)\n    {\n      dd_set_d(A->matrix[i][j], 0.0);\n    }\n    int EleIndex = floor(i/EdgeNo);\n    Vector3 ContactPos = ActContactPositions[EleIndex];\n    // Give the value into A matrix.\n    Vector3 ConeUnit_i = ConeUnit[i] - ContactPos;\n    dd_set_d(A->matrix[i][1], ConeUnit_i.x);\n    dd_set_d(A->matrix[i][2], ConeUnit_i.y);\n    dd_set_d(A->matrix[i][3], ConeUnit_i.z);\n\n    Vector3 pcrossf = cross(ContactPos, ConeUnit_i);\n    dd_set_d(A->matrix[i][4], pcrossf.x);\n    dd_set_d(A->matrix[i][5], pcrossf.y);\n    dd_set_d(A->matrix[i][6], pcrossf.z);\n  }\n\n  A->representation = dd_Generator;\n  poly=dd_DDMatrix2Poly(A, &err);\n\n  G=dd_CopyGenerators(poly);\n  // dd_WriteMatrix(stdout,G);   printf(\"\\n\");\n  B=dd_CopyInequalities(poly);\n  // dd_WriteMatrix(stdout,B);   printf(\"\\n\");\n\n  Matrix H;\n  if (err!=dd_NoError)\n  {\n    // printf(\"PolyhedralProjection: Given Matrix is not compatiable!\\n\");\n    FailureFlag = 1;\n    dd_FreeMatrix(A);\n    dd_FreeMatrix(B);\n    dd_FreeMatrix(G);\n    dd_FreePolyhedra(poly);\n\n    dd_free_global_constants();  /* At the end, this must be called. */\n\n    return H;\n  }\n\n  H.resize(B->rowsize, B->colsize-1);\n\n  for (int i = 0; i < B->rowsize; i++)\n  {\n    for (int j = 0; j < B->colsize-1; j++)\n    {\n      H(i,j) = *B->matrix[i][j+1];\n    }\n  }\n  dd_FreeMatrix(A);\n  dd_FreeMatrix(B);\n  dd_FreeMatrix(G);\n  dd_FreePolyhedra(poly);\n\n  dd_free_global_constants();  /* At the end, this must be called. */\n  H.setNegative(H);\n  return H;\n}\n\nstatic std::vector<Vector3> CentroidalCone(const Matrix& H, const Vector3& COMPos, const Vector3& COMVel)\n{\n  // This function is used to calcualte the centroidal Cone based on the H matrix\n  Vector3 g(0.0, 0.0, -9.81);\n  // According to the Zero-Step Capturability Paper there are three terms to be computed.\n  Vector a_lhs(6);\n  Vector3 v = COMVel;\n  v.setNormalized(v);\n\n  // For term a,\n  a_lhs[0] = 1.0;\n  a_lhs[1] = 1.0;\n  a_lhs[2] = 1.0;\n  Vector3 mczerocrossv = 1.0 * cross(COMPos, v);\n  a_lhs[3] = mczerocrossv.x;\n  a_lhs[4] = mczerocrossv.y;\n  a_lhs[5] = mczerocrossv.z;\n\n  // For term b,\n  Vector b_lhs(6);\n  Vector3 mgcrossv = 1.0 * cross(g, v);\n  b_lhs[0] = 0.0;\n  b_lhs[1] = 0.0;\n  b_lhs[2] = 0.0;\n  b_lhs[3] = mgcrossv.x;\n  b_lhs[4] = mgcrossv.y;\n  b_lhs[5] = mgcrossv.z;\n\n  // For term d,\n  Vector d_rhs(6);\n  Vector3 mczerocrossg = 1.0 * cross(COMPos, g);\n  d_rhs[0] = 0.0;\n  d_rhs[1] = 0.0;\n  d_rhs[2] = 1.0 * -9.81;\n  d_rhs[3] = mczerocrossg.x;\n  d_rhs[4] = mczerocrossg.y;\n  d_rhs[5] = mczerocrossg.z;\n\n  Vector Ha, Hb, Hd;\n  H.mul(a_lhs,Ha);\n  H.mul(b_lhs,Hb);\n  H.mul(d_rhs,Hd);\n\n  /*\n    For each of the vector in ConeUnit, a new projected Conic Vector should be computed.\n  */\n  dd_PolyhedraPtr poly;\n  dd_MatrixPtr A, B, G;\n  dd_rowrange m;\n  dd_colrange d;\n  dd_ErrorType err;\n\n  dd_set_global_constants();                  /* First, this must be called to use cddlib. */\n\n  m = Ha.size();\n  d = 2 + 1;\n\n  A = dd_CreateMatrix(m,d);\n  for (int i = 0; i < m; i++)\n  {\n    dd_set_d(A->matrix[i][0], Hd[i]);\n    dd_set_d(A->matrix[i][1], -1.0 * Hb[i]);\n    dd_set_d(A->matrix[i][2], -1.0 * Ha[i]);\n  }\n  A->representation = dd_Inequality;\n  poly=dd_DDMatrix2Poly(A, &err);  /* compute the second (generator) representation */\n  std::vector<Vector3> ConeVertices;\n  if (err!=dd_NoError)\n  {\n    printf(\"CentroidalCone: Given Matrix is not compatiable!\\n\");\n    dd_FreeMatrix(A);\n    dd_FreePolyhedra(poly);\n    dd_free_global_constants();  /* At the end, this must be called. */\n    return ConeVertices;\n  }\n  G=dd_CopyGenerators(poly);\n  // dd_WriteMatrix(stdout,G);   printf(\"\\n\");\n  B=dd_CopyInequalities(poly);\n  // dd_WriteMatrix(stdout,B);   printf(\"\\n\");\n\n  std::vector<Vector3> ConeInequalities;\n  ConeInequalities.reserve(B->rowsize);\n  for (int i = 0; i < B->rowsize; i++)\n  {\n    Vector3 ConeInequality(*B->matrix[i][0], *B->matrix[i][1], *B->matrix[i][2]);\n    ConeInequalities.push_back(ConeInequality);\n  }\n  dd_FreeMatrix(A);\n  dd_FreeMatrix(B);\n  dd_FreeMatrix(G);\n  dd_FreePolyhedra(poly);\n\n  dd_free_global_constants();  /* At the end, this must be called. */\n\n  string del_command = \"rm -f \" + cone_file_name + \".*\";\n  const char *delete_command = del_command.c_str();\n  std::system(delete_command);\n\n  switch (ConeInequalities.size())\n  {\n    case 0:\n    {\n      return ConeVertices;\n    }\n    break;\n    case 1:\n    {\n      return ConeVertices;\n    }\n    break;\n    case 2:\n    {\n      return ConeVertices;\n    }\n    break;\n    case 3:\n    {\n      return ConeVertices;\n    }\n    break;\n    default:\n    {\n    }\n    break;\n  }\n\n  INEWriter(ConeInequalities);\n\n  string cone_command = \"./../../../cddplus/cddf+ \" + cone_file_name + \".ine\";\n\n  // Convert string to const char * as system requires\n  // parameter of type const char *\n  const char *command = cone_command.c_str();\n  std::system(command);\n\n  ConeVertices = INEReader();\n\n  // string del_command = \"rm -f \" + cone_file_name + \".*\";\n  // const char *delete_command = del_command.c_str();\n  // std::system(delete_command);\n\n  return ConeVertices;\n}\n\nstatic std::pair<double, double> IntegratorLDS(const double & alpha, const double & alphadot, double & alphaddot, const double & beta, const double & gamma, const double & alphaupp)\n{\n  // This function is used to integrate the system dynamics according to the a-addot figure\n  /*\n  Here: alphaddot = beta + gamma * alpha,         alphalow<=alpha<=alphaupp\n  */\n  std::pair <double, double> ResPair;\n\n  if (gamma>eps)\n  {\n    double omega = sqrt(gamma);\n    double arg = -1.0 * alphadot/(omega * (alpha + beta/gamma));\n    if((arg * arg)<=1.0)\n    {\n      double t = 1.0/omega * atanh(arg);\n      double alpha_t = cosh(omega * t) * alpha + sinh(omega * t) * alphadot/omega + (cosh(omega * t) - 1.0) * (beta/gamma);\n      if(alpha_t<=alphaupp)\n      {\n        alphaddot = beta + (alpha_t - alpha) * gamma;\n        ResPair = std::make_pair(alpha_t, 0.0);\n        return ResPair;\n      }\n    }\n    double A = alpha + beta/gamma;\n    double B = alphadot/omega;\n    double C = -alphaupp - beta/gamma;\n    double InLog = (sqrt(B * B + C * C - A * A) - C)/(A + B);\n    double t = 1.0/omega * log(InLog);\n    double alpha_t = cosh(omega * t) * alpha + sinh(omega*t)/omega * alphadot + (cosh(omega * t)- 1.0) * beta/gamma;\n    double alphadot_t = omega * sinh(omega * t) * alpha + cosh(omega*t) * alphadot + omega * sinh(omega * t) * beta/gamma;\n    alphaddot = beta + (alpha_t - alpha) * gamma;\n    ResPair = std::make_pair(alphaupp, alphadot_t);\n    return ResPair;\n  }\n  else\n  {\n    if (gamma<-eps)\n    {\n      // std::cout<<\"Needs to be careful since gamma is negative!\"<<std::endl;\n      // system(\"pause\");\n      std::complex<double> omega(0.0, sqrt(-1.0 * gamma));                          // This is an imaginary number.\n      std::complex<double> arg = -1.0 * alphadot/(omega * (alpha + beta/gamma));    // This is an imaginary number.\n      std::complex<double> t = 1.0/omega * atanh(arg);                              // This is a real number.\n      std::complex<double> alpha_t = cosh(omega * t) + sinh(omega * t) * alphadot/omega + (cosh(omega * t)-1.0) * (beta/gamma); // This is also a real number.\n      double alpha_t_real = real(alpha_t);\n      if(alpha_t_real <= alphaupp)\n      {\n        alphaddot = beta + (alpha_t_real - alpha) * gamma;\n        ResPair = std::make_pair(alpha_t_real, 0.0);\n        return ResPair;\n      }\n      std::complex<double> A = alpha + beta/gamma;\n      std::complex<double> B = alphadot/omega;\n      std::complex<double> C = -alphaupp - beta/gamma;\n      std::complex<double> InLog = (-sqrt(B * B + C * C - A * A) - C)/(A + B);\n      t = 1.0/omega * log(InLog);\n      std::complex<double> alphadot_t_complex = omega * sinh(omega * t) * alpha + cosh(omega*t) * alphadot + omega * sinh(omega * t) * beta/gamma;\n      std::complex<double> alpha_t_complex = cosh(omega * t) * alpha + sinh(omega*t)/omega * alphadot + (cosh(omega * t)- 1.0) * beta/gamma;\n      alpha_t_real = real(alpha_t_complex);\n      double alphadot_t = real(alphadot_t_complex);\n      alphadot_t = sqrt(alphadot_t * alphadot_t);\n      alphaddot = beta + (alpha_t_real - alpha) * gamma;\n      ResPair = std::make_pair(alphaupp, alphadot_t);\n      return ResPair;\n    }\n    else\n    {\n      double alpha_t = alpha - 0.5 * alphadot * alphadot/beta;\n      if(alpha_t<=alphaupp)\n      {\n        alphaddot = beta + (alpha_t - alpha) * gamma;\n        ResPair = std::make_pair(alpha_t, 0.0);\n        return ResPair;\n      }\n      double t = (-alphadot + sqrt(alphadot * alphadot - 2.0 * beta * (alpha - alphaupp)))/beta;\n      alpha_t = alphaupp;\n      double alphadot_t = alphadot + t * beta;\n      alphaddot = beta + (alpha_t - alpha) * gamma;\n      ResPair = std::make_pair(alpha_t, alphadot_t);\n      return ResPair;\n    }\n  }\n  return ResPair;\n}\n\nstatic double LinearInter(const Vector2& LeftPt, const Vector2& RightPt, const double& x_new)\n{\n  // This function is used to calculate the value for y_new based on the LeftPt and Rightpt.\n  double x_offset = x_new - LeftPt.x;\n  double k = (RightPt.y - LeftPt.y)/(RightPt.x - LeftPt.x);\n  double y_new = LeftPt.y + k * x_offset;\n  return y_new;\n}\n\nstatic void AccLinearCoeff(const double & Alpha, const std::vector<Vector2> & Path, double & Beta, double & Gamma, double & AlphaUpp, const double & AlphaFeasMax)\n{\n  // This function is used to find out the linear coefficients for acceleration function.\n  for (int i = 0; i < Path.size()-1; i++)\n  {\n    if((Alpha>=Path[i].x)&&(Alpha<=Path[i+1].x))\n    {\n      // This is used to bound the range of alpha.\n      Vector2 LeftPt = Path[i];\n      Vector2 RightPt = Path[i+1];\n\n      Gamma = (RightPt.y - LeftPt.y)/(RightPt.x - LeftPt.x);\n      Beta = LeftPt.y - Gamma * LeftPt.x;\n\n      if(RightPt.y<0)\n      {\n        AlphaUpp = RightPt.x;\n      }\n      else\n      {\n        AlphaUpp = LeftPt.x - LeftPt.y/Gamma;\n      }\n    }\n  }\n  if(AlphaUpp>=AlphaFeasMax)\n  {\n    AlphaUpp = AlphaFeasMax;\n  }\n}\n\nstatic int LinearCoeff(const double & alpha, const FacetInfo & FacetObj, const int & Flag, double & beta_i, double & gamma_i, double & alphaupp_i)\n{\n  // This function is used to calculate the linear coefficient: alphaddot = beta_i + gamma_i * alpha.\n  std::vector<int> EdgeIndices;\n  std::vector<Vector2> LeftPts, RightPts;\n  std::vector<double> InterAlphaddot;\n  for (int i = 0; i < FacetObj.FacetEdges.size(); i++)\n  {\n    double alphaleft = FacetObj.FacetEdges[i].first.x - alpha;\n    double alpharight = FacetObj.FacetEdges[i].second.x - alpha;\n    if(((alphaleft<=0)&&(alpharight>=0))||((alphaleft >=0)&&(alpharight<=0)))\n    {\n      // Then we switch the order of first, second to make sure that the second point is on the right.\n      Vector2 LeftPt, RightPt;\n      if(FacetObj.FacetEdges[i].second.x>FacetObj.FacetEdges[i].first.x)\n      {\n        LeftPt.x = FacetObj.FacetEdges[i].first.x;\n        LeftPt.y = FacetObj.FacetEdges[i].first.y;\n\n        RightPt.x = FacetObj.FacetEdges[i].second.x;\n        RightPt.y = FacetObj.FacetEdges[i].second.y;\n      }\n      else\n      {\n        LeftPt.x = FacetObj.FacetEdges[i].second.x;\n        LeftPt.y = FacetObj.FacetEdges[i].second.y;\n\n        RightPt.x = FacetObj.FacetEdges[i].first.x;\n        RightPt.y = FacetObj.FacetEdges[i].first.y;\n      }\n      if((RightPt.x - alpha)>0)\n      {\n        // This means that we only choose the point on the right side\n        EdgeIndices.push_back(i);\n        LeftPts.push_back(LeftPt);\n        RightPts.push_back(RightPt);\n        double alphaddot = LinearInter(LeftPt, RightPt, alpha);\n        InterAlphaddot.push_back(alphaddot);\n      }\n    }\n  }\n  if(InterAlphaddot.size() ==0)\n  {\n    // This means that the current region does not contain the origin to search for the feasible solution.\n    return 2;\n  }\n\n  // In this case, we should sort alpha values according to the linear splines.\n  int AlphaIndex;\n  switch (Flag)\n  {\n    case 0:\n    {\n      AlphaIndex = std::max_element(InterAlphaddot.begin(), InterAlphaddot.end()) - InterAlphaddot.begin();\n    }\n    break;\n    case 1:\n    {\n      AlphaIndex = std::min_element(InterAlphaddot.begin(), InterAlphaddot.end()) - InterAlphaddot.begin();\n    }\n    break;\n    default:\n    break;\n  }\n  Vector2 LeftPt = LeftPts[AlphaIndex];\n  Vector2 RightPt = RightPts[AlphaIndex];\n\n  gamma_i = (RightPt.y - LeftPt.y)/(RightPt.x - LeftPt.x);\n  beta_i = InterAlphaddot[AlphaIndex];\n  if(RightPt.y<0)\n  {\n    alphaupp_i = RightPt.x;\n  }\n  else\n  {\n    alphaupp_i = LeftPt.x - LeftPt.y/gamma_i;\n  }\n  return 1;\n}\n\nstatic Vector2 AppendPoint(const Vector2 & Point, const FacetInfo & FacetObj, bool & PointAdditionFlag)\n{\n  Vector2 NextPoint;\n  for (int i = 0; i < FacetObj.FacetEdges.size(); i++)\n  {\n    double FirstCom_x = FacetObj.FacetEdges[i].first.x - Point.x;\n    double FirstCom_y = FacetObj.FacetEdges[i].first.y - Point.y;\n    double FirstComVal = FirstCom_x * FirstCom_x + FirstCom_y * FirstCom_y;\n\n    double SecondCom_x = FacetObj.FacetEdges[i].second.x - Point.x;\n    double SecondCom_y = FacetObj.FacetEdges[i].second.y - Point.y;\n    double SecondComVal = SecondCom_x * SecondCom_x + SecondCom_y * SecondCom_y;\n\n    if(FirstComVal<eps)\n    {\n      // This means that First Point is the Point\n      if(SecondCom_x>0)\n      {\n        NextPoint.x = FacetObj.FacetEdges[i].second.x;\n        NextPoint.y = FacetObj.FacetEdges[i].second.y;\n\n        PointAdditionFlag = true;\n        return NextPoint;\n      }\n    }\n\n    if(SecondComVal<eps)\n    {\n      if(FirstCom_x>0)\n      {\n        NextPoint.x = FacetObj.FacetEdges[i].first.x;\n        NextPoint.y = FacetObj.FacetEdges[i].first.y;\n\n        PointAdditionFlag = true;\n        return NextPoint;\n      }\n    }\n  }\n  PointAdditionFlag = false;\n  return NextPoint;\n}\n\nstatic void FindPathToTheEnd(std::vector<Vector2> & Path, const FacetInfo & FacetObj)\n{\n  bool PointAdditionFlag = true;\n  while(PointAdditionFlag)\n  {\n    // try to find the path connecting to the last point from path\n    Vector2 NextPoint;\n    NextPoint = AppendPoint(Path[Path.size()-1], FacetObj, PointAdditionFlag);\n    switch (PointAdditionFlag)\n    {\n      case true:\n      {\n        Path.push_back(NextPoint);\n      }\n      break;\n      default:\n      {\n      }\n      break;\n    }\n  }\n}\n\nstatic bool PathToTheEnd(const FacetInfo & FacetObj, std::vector<Vector2> & UpperPath, std::vector<Vector2> & LowerPath)\n{\n  // This function is used to find the path from 0 to the end.\n  bool PathFlag = false;\n  std::vector<Vector2> StartPointsLeft, StartPointsRight;\n  std::vector<int> InterSegIndices;\n  for (int i = 0; i < FacetObj.FacetEdges.size(); i++)\n  {\n    // The first element is the alpha while the second element is the alpha ddot.\n    double Sign = FacetObj.FacetEdges[i].first.x * FacetObj.FacetEdges[i].second.x;\n    if (Sign<0)\n    {\n      double delta_y = FacetObj.FacetEdges[i].first.y - FacetObj.FacetEdges[i].second.y;\n      double delta_x = FacetObj.FacetEdges[i].first.x - FacetObj.FacetEdges[i].second.x;\n      double k = delta_y/delta_x;\n\n      double StartPointLeft_y = FacetObj.FacetEdges[i].first.y - k * FacetObj.FacetEdges[i].first.x;\n      Vector2 StartPointLeft(0.0, StartPointLeft_y);\n      StartPointsLeft.push_back(StartPointLeft);\n      if(FacetObj.FacetEdges[i].first.x>FacetObj.FacetEdges[i].second.x)\n      {\n        Vector2 StartPointRight(FacetObj.FacetEdges[i].first.x, FacetObj.FacetEdges[i].first.y);\n        StartPointsRight.push_back(StartPointRight);\n      }\n      else\n      {\n        Vector2 StartPointRight(FacetObj.FacetEdges[i].second.x, FacetObj.FacetEdges[i].second.y);\n        StartPointsRight.push_back(StartPointRight);\n      }\n      InterSegIndices.push_back(i);\n    }\n    else\n    {\n      if(Sign == 0)\n      {\n        double FirstAtZero = FacetObj.FacetEdges[i].first.x * FacetObj.FacetEdges[i].first.x;\n        if(FirstAtZero<eps)\n        {\n          if(FacetObj.FacetEdges[i].first.x<FacetObj.FacetEdges[i].second.x)\n          {\n            Vector2 StartPointLeft(FacetObj.FacetEdges[i].first.x, FacetObj.FacetEdges[i].first.y);\n            Vector2 StartPointRight(FacetObj.FacetEdges[i].second.x, FacetObj.FacetEdges[i].second.y);\n            StartPointsLeft.push_back(StartPointLeft);\n            StartPointsRight.push_back(StartPointRight);\n            InterSegIndices.push_back(i);\n          }\n        }\n        else\n        {\n          if(FacetObj.FacetEdges[i].first.x>FacetObj.FacetEdges[i].second.x)\n          {\n            Vector2 StartPointLeft(FacetObj.FacetEdges[i].second.x, FacetObj.FacetEdges[i].second.y);\n            Vector2 StartPointRight(FacetObj.FacetEdges[i].first.x, FacetObj.FacetEdges[i].first.y);\n            StartPointsLeft.push_back(StartPointLeft);\n            StartPointsRight.push_back(StartPointRight);\n            InterSegIndices.push_back(i);\n          }\n        }\n      }\n    }\n  }\n\n  switch (StartPointsLeft.size())\n  {\n    case 0:\n    {\n      return false;\n    }\n    break;\n    case 3:\n    {\n      std::cerr<<\"Intersections cannot have more than 2 segments!\"<<endl;\n      return false;\n    }\n    break;\n    default:\n    {\n    }\n    break;\n  }\n\n  // Now the job is to figure out which one is at top and which one is at bottom.\n  if(StartPointsLeft[0].y > StartPointsLeft[1].y)\n  {\n    UpperPath.push_back(StartPointsLeft[0]);\n    UpperPath.push_back(StartPointsRight[0]);\n\n    LowerPath.push_back(StartPointsLeft[1]);\n    LowerPath.push_back(StartPointsRight[1]);\n  }\n  else\n  {\n    UpperPath.push_back(StartPointsLeft[1]);\n    UpperPath.push_back(StartPointsRight[1]);\n\n    LowerPath.push_back(StartPointsLeft[0]);\n    LowerPath.push_back(StartPointsRight[0]);\n  }\n\n  // Alright, let's find the path from this point to the most right end.\n   FindPathToTheEnd(UpperPath, FacetObj);\n   FindPathToTheEnd(LowerPath, FacetObj);\n\n  return true;\n}\n\nstatic bool TooFastCaseValidation(const double & AlphadotInit, const std::vector<Vector2> & UppPath, const double & AlphaFeasMin, const double & AlphaFeasMax)\n{\n  // This main purpose of this function is to validate whether robot can reach feasible alpha region.\n  // This computation will be terminated if any of these two conditions has been triggered.\n  // 1. alpha reaches feasible region.\n  // 2. alphadot has been declined to zero.\n  double Alpha = 0.0;\n  double Alphadot = AlphadotInit;\n  double Beta = 0.0;\n  double Gamma = 0.0;\n  double AlphaUpp = 0.0;\n  double Alphaddot = 0.0;\n\n  int IterLimit = 20;\n  for (int i = 0; i < IterLimit; i++)\n  {\n    AccLinearCoeff(Alpha, UppPath, Beta, Gamma, AlphaUpp, AlphaFeasMax);\n    std::pair<double, double> AlphaNAlphadot = IntegratorLDS(Alpha, Alphadot, Alphaddot, Beta, Gamma, AlphaUpp);\n    Alpha = AlphaNAlphadot.first;\n    Alphadot = AlphaNAlphadot.second;\n\n    // Condition 1\n    if(Alpha>=AlphaFeasMin)\n    {\n      return true;\n    }\n\n    // Condition 2\n    if((Alphadot==0.0)&&(Alpha<AlphaFeasMin))\n    {\n      return false;\n    }\n  }\n  return false;\n}\n\nstatic bool ZSCEvaluation(const double & AlphadotInit, const std::vector<Vector2> & LowPath, const std::vector<Vector2> & UppPath, const double & AlphaFeasMin, const double & AlphaFeasMax, const double & AlphaMax)\n{\n  // This function is used to conduct the evaluation of ZSC.\n  int MaxIter = 100;\n  int CurIter = 0;\n  double Alpha = 0.0;\n  double Alphadot = AlphadotInit;\n  double Alphaddot = 0.0;\n\n  double Beta = 0.0;\n  double Gamma = 0.0;\n  double AlphaUpp = 0.0;          // This is the Upper Bound for a certain integration.\n\n  bool StabilizedFlag = false;\n  while (CurIter<MaxIter)\n  {\n    if((Alphadot>-eps)&&(Alphadot<eps))\n    {\n      // In this case, Alphadot vanishes!\n      if((Alpha=AlphaFeasMin)&&(Alpha<=AlphaFeasMax))\n      {\n        // C3.1\n        // Tested!\n        StabilizedFlag = true;\n        // std::printf(\"C3.1\\n\");\n        return StabilizedFlag;\n      }\n      if(Alpha<AlphaFeasMin)\n      {\n        // C3.2\n        // This is an annoying case.\n        StabilizedFlag = TooFastCaseValidation(AlphadotInit, UppPath, AlphaFeasMin, AlphaFeasMax);\n        // std::printf(\"C3.2\\n\");\n        return StabilizedFlag;\n      }\n      if(Alpha>AlphaFeasMax)\n      {\n        // C3.3\n        StabilizedFlag = false;\n        // std::printf(\"C3.3\\n\");\n        return StabilizedFlag;\n      }\n    }\n    else\n    {\n      // In this case, robot's centroidal velocity is not zero.\n      if(Alpha>=AlphaFeasMax)\n      {\n        // C1: Velocity is too large to be compensated!\n        // Tested!\n        StabilizedFlag = false;\n        // std::printf(\"C1\\n\");\n        return StabilizedFlag;\n      }\n      if(Alpha>=AlphaMax)\n      {\n        // C2: Position arrives at the position where constraints will be violated!\n        // Tested!\n        StabilizedFlag = false;\n        // std::printf(\"C2\\n\");\n        return StabilizedFlag;\n      }\n    }\n    AccLinearCoeff(Alpha, LowPath, Beta, Gamma, AlphaUpp, AlphaFeasMax);\n    std::pair<double, double> AlphaNAlphadot = IntegratorLDS(Alpha, Alphadot, Alphaddot, Beta, Gamma, AlphaUpp);\n    Alpha = AlphaNAlphadot.first;\n    Alphadot = AlphaNAlphadot.second;\n\n    // std::printf(\"Alpha: %f and Alphadot: %f\\n\", Alpha, Alphadot);\n    CurIter = CurIter + 1;\n  }\n  return StabilizedFlag;\n}\n\nstatic bool ZSCInner(const std::vector<Vector3> & ActContactPositions, const std::vector<Vector3> & ConeUnit, const int & EdgeNo, const Vector3& COMPos, const Vector3& COMVel)\n{\n  int HFailureFlag;\n  Matrix H = PolyhedralProjection(ActContactPositions, ConeUnit, EdgeNo, HFailureFlag);\n  switch (HFailureFlag)\n  {\n    case 1:\n    {\n      // This means that Zero-step capturability method does not work\n      return false;\n    }\n    break;\n    default:\n    break;\n  }\n\n  std::vector<Vector3> ConeVertices = CentroidalCone(H, COMPos, COMVel);\n  if(ConeVertices.size()<3)\n  {\n    // In this case, there is no need to conduct further computation.\n    return false;\n  }\n\n  int CollinearFlag = CollinearTest(ActContactPositions);\n  switch (CollinearFlag)\n  {\n    case 1:\n    {\n      return false;\n    }\n    break;\n    default:\n    break;\n  }\n\n  int FacetFlag = 0;\n  FacetInfo FacetObj = FlatContactHullGeneration(ConeVertices, FacetFlag);\n  switch (FacetFlag)\n  {\n    case 0:\n    {\n      return false;\n    }\n    break;\n    default:\n    break;\n  }\n\n  // Now let's compute the maximum deaccelerated velocity.\n  bool StabilizedFlag = true;\n  /*\n    The first job is to compute the intersection where the acceleration vanishes.\n  */\n  std::vector<double> AlphaFeasible;\n  std::vector<double> AlphaTotal(FacetObj.FacetEdges.size());\n  for (int i = 0; i < FacetObj.FacetEdges.size(); i++)\n  {\n    // The first element is the alpha while the second element is the alpha ddot.\n    double Sign = FacetObj.FacetEdges[i].first.y * FacetObj.FacetEdges[i].second.y;\n    if (Sign<0)\n    {\n      double delta_y = FacetObj.FacetEdges[i].first.y - FacetObj.FacetEdges[i].second.y;\n      double delta_x = FacetObj.FacetEdges[i].first.x - FacetObj.FacetEdges[i].second.x;\n      double k = delta_y/delta_x;\n      double Alpha = FacetObj.FacetEdges[i].first.x - FacetObj.FacetEdges[i].first.y/k;\n      AlphaFeasible.push_back(Alpha);\n    }\n    else\n    {\n      if(Sign == 0)\n      {\n        double FirstAtZero = FacetObj.FacetEdges[i].first.y * FacetObj.FacetEdges[i].first.y;\n        if(FirstAtZero<eps)\n        {\n          AlphaFeasible.push_back(FacetObj.FacetEdges[i].first.x);\n        }\n        else\n        {\n          AlphaFeasible.push_back(FacetObj.FacetEdges[i].second.x);\n        }\n      }\n    }\n    AlphaTotal[i] = FacetObj.FacetEdges[i].first.x;\n  }\n  switch (AlphaFeasible.size())\n  {\n    case 0:\n    {\n      return false;\n    }\n    break;\n    default:\n    break;\n  }\n\n  double AlphaFeasMin = *std::min_element(AlphaFeasible.begin(), AlphaFeasible.end());\n  double AlphaFeasMax = *std::max_element(AlphaFeasible.begin(), AlphaFeasible.end());\n\n  double AlphaTotalMin = *std::min_element(AlphaTotal.begin(), AlphaTotal.end());\n  double AlphaTotalMax = *std::max_element(AlphaTotal.begin(), AlphaTotal.end());\n\n  std::vector<Vector2> UpperPath, LowerPath;\n  PathToTheEnd(FacetObj, UpperPath, LowerPath);\n\n  switch (UpperPath.size())\n  {\n    case 0:\n    {\n      return false;\n    }\n    break;\n    case 1:\n    {\n      return false;\n    }\n    break;\n    default:\n    {\n    }\n    break;\n  }\n\n  switch (LowerPath.size())\n  {\n    case 0:\n    {\n      return false;\n    }\n    break;\n    case 1:\n    {\n      return false;\n    }\n    break;\n    default:\n    {\n    }\n    break;\n  }\n\n  double AlphadotInit = sqrt(COMVel.x * COMVel.x + COMVel.y * COMVel.y + COMVel.z * COMVel.z);\n\n  StabilizedFlag = ZSCEvaluation(AlphadotInit, LowerPath, UpperPath, AlphaFeasMin, AlphaFeasMax, AlphaTotalMax);\n\n  return StabilizedFlag;\n}\n\ndouble ZeroStepCapturabilityGenerator(const std::vector<Vector3> & ActContactPositions, const std::vector<Vector3> & ConeUnit, const int & EdgeNo, const Vector3& COMPos, const Vector3& COMVel)\n{\n  // This function is used to generate the solution for zero capturability failure metric.\n  bool StabilizedFlag;\n  try\n  {\n    StabilizedFlag = ZSCInner(ActContactPositions, ConeUnit, EdgeNo, COMPos, COMVel);\n  }\n  catch(...)\n  {\n    StabilizedFlag = false;\n  }\n  double ZSCObj = 1.0;\n  switch (StabilizedFlag)\n  {\n    case true:\n    {\n      // This means that the robot can be stabilized using this method.\n      ZSCObj = 0.0;\n    }\n    break;\n    default:\n    {\n      // This means that the robot cannot be stabilized using this metric.\n      ZSCObj = 1.0;\n    }\n    break;\n  }\n  return ZSCObj;\n}\n", "meta": {"hexsha": "546e24185b54a2125be7f08481f3b66b500a3fc6", "size": 31101, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/ZeroStepCapturability.cpp", "max_stars_repo_name": "ShihaoWang/Stabilizability-Analysis-with-Polytopic-Viability-Kernel", "max_stars_repo_head_hexsha": "56261f283871b8662e4e08c0a024f4df924bf9b9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/ZeroStepCapturability.cpp", "max_issues_repo_name": "ShihaoWang/Stabilizability-Analysis-with-Polytopic-Viability-Kernel", "max_issues_repo_head_hexsha": "56261f283871b8662e4e08c0a024f4df924bf9b9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/ZeroStepCapturability.cpp", "max_forks_repo_name": "ShihaoWang/Stabilizability-Analysis-with-Polytopic-Viability-Kernel", "max_forks_repo_head_hexsha": "56261f283871b8662e4e08c0a024f4df924bf9b9", "max_forks_repo_licenses": ["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.325136612, "max_line_length": 213, "alphanum_fraction": 0.6296582103, "num_tokens": 9125, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5660185351961015, "lm_q2_score": 0.5621765008857981, "lm_q1q2_score": 0.3182023195530493}}
{"text": "/**************************************************************************\n\n    This file is part of the C++ library \"homog2d\", dedicated to\n    handle 2D lines and points, see https://github.com/skramm/homog2d\n\n    Author & Copyright 2019-2021 Sebastien Kramm\n\n    Contact: firstname.lastname@univ-rouen.fr\n\n    Licence: MPL v2\n\n\tThis Source Code Form is subject to the terms of the Mozilla Public\n\tLicense, v. 2.0. If a copy of the MPL was not distributed with this\n\tfile, You can obtain one at https://mozilla.org/MPL/2.0/.\n\n**************************************************************************/\n\n/**\n\\file homog2d.hpp\n\\brief single header file, implements some 2D homogeneous stuff.\nSee https://github.com/skramm/homog2d\n*/\n\n#ifndef HG_HOMOG2D_HPP\n#define HG_HOMOG2D_HPP\n\n#include <cmath>\n#include <iostream>\n#include <algorithm>\n#include <numeric>\n#include <set>\n#include <list>\n#include <vector>\n#include <iomanip>\n#include <cassert>\n#include <sstream>\n#include <type_traits>\n\n#ifdef HOMOG2D_USE_EIGEN\n\t#include <Eigen/Dense>\n#endif\n\n#define HOMOG2D_VERSION 2.6\n\n#ifdef HOMOG2D_USE_OPENCV\n\t#include \"opencv2/imgproc.hpp\"\n#endif\n\n#if 0\n\t#define HOMOG2D_START std::cout << \"START: \" << __PRETTY_FUNCTION__ << \"()\\n\"\n#else\n\t#define HOMOG2D_START\n#endif\n\n#if 0\n\t#define HOMOG2D_LOG(a) std::cout << \"-line \" << __LINE__ << \": \" << a << '\\n'\n#else\n\t#define HOMOG2D_LOG(a) {;}\n#endif\n\n/// Assert debug macro, used internally if \\c HOMOG2D_DEBUGMODE is defined\n#define HOMOG2D_DEBUG_ASSERT(a,b) \\\n\t{ \\\n\t\tif( (a) == false ) \\\n\t\t{ \\\n\t\t\tstd::cerr << \"Homog2d assert failure, version:\" << HOMOG2D_VERSION \\\n\t\t\t\t<< \", line:\" << __LINE__ << \"\\n -details: \" << b << '\\n'; \\\n\t\t\tstd::cout << \"homog2d: internal failure, please check stderr and report this\\n\"; \\\n\t\t\tstd::exit(1); \\\n\t\t} \\\n\t}\n\n#define HOMOG2D_CHECK_ROW_COL \\\n\tif( r > 2 ) \\\n\t\tthrow std::runtime_error( \"Error: invalid row value: r=\" + std::to_string(r) ); \\\n\tif( c > 2 ) \\\n\t\tthrow std::runtime_error( \"Error: invalid col value: r=\" + std::to_string(r) )\n\n#define HOMOG2D_CHECK_IS_NUMBER(T) \\\n\tstatic_assert( std::is_arithmetic<T>::value && !std::is_same<T, bool>::value, \"Type of value must be numerical\" )\n\n/// Internal type used for numerical computations, possible\tvalues: \\c double, <code>long double</code>\n#if !defined(HOMOG2D_INUMTYPE)\n\t#define HOMOG2D_INUMTYPE double\n#endif\n\n/// Error throw wrapper macro\n#define HOMOG2D_THROW_ERROR_1( msg ) \\\n\t{ \\\n\t\tstd::ostringstream oss; \\\n\t\toss << \"homog2d: line \" <<  __LINE__  << \", \" << + __FUNCTION__ << \"(): \" << msg; \\\n\t\tthrow std::runtime_error( oss.str() ); \\\n\t}\n\n/// Error throw wrapper macro\n#define HOMOG2D_THROW_ERROR_2( f, msg ) \\\n\tthrow std::runtime_error( std::string(\"homog2d: line \") + std::to_string( __LINE__ ) + \", \" + f + \"(): \" + msg )\n\nnamespace h2d {\n\n/// Holds the types needed for policy based design\nnamespace type {\n\nstruct IsLine   {};\nstruct IsPoint  {};\nstruct IsHomogr {};\nstruct IsEpipmat {};\n\n} // namespace type\n\n\nnamespace detail {\n\n\ttemplate<typename FPT> class Matrix_;\n\n\t/// Helper class for Root (Point/Line) type, used as a trick to allow partial specialization of member functions\n\ttemplate<typename> struct RootHelper {};\n\n\t/// Helper class for Root (Point/Line) type, used only to get the underlying floating-point type, see Dtype and Root::dtype()\n\ttemplate<typename> struct RootDataType {};\n\n#ifdef HOMOG2D_FUTURE_STUFF\n\t/// Helper class for Matrix type\n\ttemplate<typename T1>\n\tstruct HelperMat {};\n\n\ttemplate<>\n\tstruct HelperMat<type::IsHomogr>\n\t{\n\t\tusing M_OtherType = IsEpipmat;\n\t};\n\n\ttemplate<>\n\tstruct HelperMat<type::IsEpipmat>\n\t{\n\t\tusing M_OtherType = IsHomogr;\n\t};\n#endif\n\n    template<typename> struct HelperPL;\n\n    template<>\n    struct HelperPL<type::IsPoint>\n    {\n        using OtherType = type::IsLine;\n    };\n\n    template<>\n    struct HelperPL<type::IsLine>\n    {\n        using OtherType = type::IsPoint;\n    };\n\n\t/// A trick used in static_assert, so it aborts only if function is instanciated\n\ttemplate<typename T>\n\tstruct AlwaysFalse {\n\t\tenum { value = false };\n\t};\n\n} // namespace detail\n\n// forward declarations\ntemplate<typename LP,typename FPT> class Root;\ntemplate<typename LP,typename FPT> class Hmatrix_;\n\ntemplate<typename T>\nusing Homogr_  =  Hmatrix_<type::IsHomogr,T>;\n#ifdef HOMOG2D_FUTURE_STUFF\ntemplate<typename T>\nusing Epipmat_ =  Hmatrix_<type::IsEpipmat,T>;\n#endif\n\ntemplate<typename FPT> class Segment_;\ntemplate<typename FPT> class Polyline_;\ntemplate<typename FPT> class Circle_;\ntemplate<typename FPT> class FRect_;\ntemplate<typename FPT> class Ellipse_;\n\ntemplate<typename T>\nusing Point2d_ = Root<type::IsPoint,T>;\ntemplate<typename T>\nusing Line2d_  = Root<type::IsLine,T>;\n\n//------------------------------------------------------------------\n/// Holds drawing related code, independent of back-end library\nnamespace img {\n\n/// Opaque data structure, will hold the image type, depending on back-end library\n/**\nTo expand it, you need to add code for the other library for the\ntwo function cols() and rows(), bounded in a \"#define\" block, and define the drawing functions\n*/\ntemplate<typename T>\nstruct Image\n{\n\tT real_img;\n\tImage() = default;\n\tImage( T& m ): real_img(m)\n\t{}\n\tT& getReal()\n\t{\n\t\treturn real_img;\n\t}\n#ifdef HOMOG2D_USE_OPENCV\n\tint cols() const { return real_img.cols; }\n\tint rows() const { return real_img.rows; }\n#endif\n\n//#ifdef HOMOG2D_SOME_OTHER_LIB\n//\tint cols() const { return real_img.???; }\n//\tint rows() const { return real_img.???; }\n//#endif\n\n};\n\n} // namespace img\n\n/////////////////////////////////////////////////////////////////////////////\n// SECTION  - PUBLIC ENUM DECLARATIONS\n/////////////////////////////////////////////////////////////////////////////\n\n/// Used in Line2d::getValue() and getOrthogonalLine()\nenum class GivenCoord: uint8_t { X, Y };\n\n/// Used in line constructor, to instanciate a H or V line, see \\ref Root( LineDir, T )\nenum class LineDir: uint8_t { H, V };\n\n/// Used in Polyline_ constructors\nenum class IsClosed: uint8_t { Yes, No };\n\n/// Type of Root object, see Root::type()\nenum class Type: uint8_t { Line2d, Point2d };\n\n/// Type of underlying floating point, see Root::dtype()\nenum class Dtype: uint8_t { Float, Double, LongDouble };\n\ninline const char* getString( Type t )\n{\n\treturn t==Type::Line2d ? \"Line2d\" : \"Point2d\";\n}\n\nnamespace detail {\n\n// forward declaration\ntemplate<typename FPT1,typename FPT2,typename FPT3>\nvoid product( Matrix_<FPT1>&, const Matrix_<FPT2>&, const Matrix_<FPT3>& );\n\n\n//------------------------------------------------------------------\n/// Private free function, get top-left and bottom-right points from two arbitrary points\ntemplate<typename FPT>\nstd::pair<Point2d_<FPT>,Point2d_<FPT>>\ngetCorrectPoints( const Point2d_<FPT>& p0, const Point2d_<FPT>& p1 )\n{\n#ifndef HOMOG2D_NOCHECKS\n\tif(\n\t\t   std::fabs( p0.getX() - p1.getX() ) < Point2d_<FPT>::nullOrthogDistance()\n\t\t|| std::fabs( p0.getY() - p1.getY() ) < Point2d_<FPT>::nullOrthogDistance()\n\t)\n\t\tHOMOG2D_THROW_ERROR_1(\n\t\t\t\"a coordinate of the 2 points is identical, does not define a rectangle:\\n p0=\" << p0 << \" p1=\" << p1\n\t\t);\n#endif\n\tPoint2d_<FPT> p00( std::min(p0.getX(), p1.getX()), std::min(p0.getY(), p1.getY()) );\n\tPoint2d_<FPT> p11( std::max(p0.getX(), p1.getX()), std::max(p0.getY(), p1.getY()) );\n\treturn std::make_pair( p00, p11 );\n}\n\ntemplate<typename T>\nusing matrix_t = std::array<std::array<T,3>,3>;\n\n//------------------------------------------------------------------\n/// A simple wrapper over a 3x3 matrix, provides root functionalities\n/**\nHomogeneous (thus the 'mutable' attribute).\n*/\ntemplate<typename FPT>\nclass Matrix_\n{\n\ttemplate<typename T> friend class Matrix_;\n\n\ttemplate<typename T1,typename T2,typename FPT1,typename FPT2>\n\tfriend void\n\tproduct( Root<T1,FPT1>&, const detail::Matrix_<FPT2>&, const Root<T2,FPT1>& );\n\n\ttemplate<typename FPT1,typename FPT2,typename FPT3>\n\tfriend void\n\tproduct( Matrix_<FPT1>&, const Matrix_<FPT2>&, const Matrix_<FPT3>& );\n\nprivate:\n\tstatic HOMOG2D_INUMTYPE _zeroDeterminantValue; /// Used in matrix inversion\n\tstatic HOMOG2D_INUMTYPE _zeroDenomValue;       /// The value under which e wont divide\n\nprotected:\n\tmutable matrix_t<FPT> _mdata;\n\tmutable bool          _isNormalized = false;\n\npublic:\n/// Constructor\n\tMatrix_()\n\t{\n\t\tp_fillZero();\n\t}\n\n/// Copy-Constructor\n\ttemplate<typename FPT2>\n\tMatrix_( const Matrix_<FPT2>& other )\n\t{\n\t\tfor( int i=0; i<3; i++ )\n\t\t\tfor( int j=0; j<3; j++ )\n\t\t\t\t_mdata[i][j] = other._mdata[i][j];\n\t\t_isNormalized = other._isNormalized;\n\t}\n\n\tmatrix_t<FPT>&       getRaw()       { return _mdata; }\n\tconst matrix_t<FPT>& getRaw() const { return _mdata; }\n\n/*\ttemplate<typename T>\n\tvoid set( size_t r, size_t c, T v )\n\t{\n\t\t#ifndef HOMOG2D_NOCHECKS\n\t\t\tHOMOG2D_CHECK_ROW_COL;\n\t\t#endif\n\t\t_mdata[r][c] = v;\n\t}*/\n\n\tconst FPT& value( size_t r, size_t c ) const\n\t{\n\t\t#ifndef HOMOG2D_NOCHECKS\n\t\t\tHOMOG2D_CHECK_ROW_COL;\n\t\t#endif\n\t\treturn _mdata[r][c];\n\t}\n\tFPT& value( size_t r, size_t c )\n\t{\n\t\t#ifndef HOMOG2D_NOCHECKS\n\t\t\tHOMOG2D_CHECK_ROW_COL;\n\t\t#endif\n\t\treturn _mdata[r][c];\n\t}\n\n/// Return determinant of matrix\n/**\nSee https://en.wikipedia.org/wiki/Determinant\n*/\n\tHOMOG2D_INUMTYPE determ() const\n\t{\n\t\tauto det = _mdata[0][0] * p_det2x2( {1,1, 1,2, 2,1, 2,2} );\n\t\tdet     -= _mdata[0][1] * p_det2x2( {1,0, 1,2, 2,0, 2,2} );\n\t\tdet     += _mdata[0][2] * p_det2x2( {1,0, 1,1, 2,0, 2,1} );\n\t\treturn det;\n\t}\n\n/// Transpose and return matrix\n\tMatrix_& transpose()\n\t{\n\t\tmatrix_t<FPT> out;\n\t\tfor( int i=0; i<3; i++ )\n\t\t\tfor( int j=0; j<3; j++ )\n\t\t\t\tout[i][j] = _mdata[j][i];\n\t\t_mdata = out;\n\t\t_isNormalized = false;\n\t\treturn *this;\n\t}\n\n/// Inverse matrix\n\tMatrix_& inverse()\n\t{\n\t\tauto det = determ();\n\t\tif( std::abs(det) < nullDeterValue() )\n\t\t\tHOMOG2D_THROW_ERROR_1( \"matrix is not invertible, det=\" << std::scientific << std::abs(det) );\n\n\t\tauto adjugate = p_adjugate();\n\t\tp_divideAll(adjugate, det);\n\t\t_mdata = adjugate._mdata;\n\t\t_isNormalized = false;\n\t\treturn *this;\n\t}\n\tbool isNormalized() const { return _isNormalized; }\n\nprotected:\n\tvoid p_normalize( int r, int c ) const\n\t{\n#ifndef HOMOG2D_NOCHECKS\n\t\tif( std::fabs(_mdata[r][c]) < nullDenomValue() )\n\t\t\tHOMOG2D_THROW_ERROR_1(\n\t\t\t\t\"Unable to normalize matrix, value at (\"\n\t\t\t\t\t<< r << ',' << c << \") less than \" << nullDenomValue()\n\t\t\t);\n#endif\n\t\tp_divideBy( r, c );\n\t\tif( std::signbit( _mdata[r][c] ) )\n\t\t\tfor( auto& li: _mdata )\n\t\t\t\tfor( auto& e: li )\n\t\t\t\t\te = -e;\n\t\t_isNormalized = true;\n\t}\n\n#if 0\n/// Used by copy constructor\n/** \\todo maybe integrate into CC ? Not used anywhere else... */\n\ttemplate<typename FPT2>\n\tvoid p_copyTo( const Matrix_<FPT2>& other )\n\t{\n\t\tfor( int i=0; i<3; i++ )\n\t\t\tfor( int j=0; j<3; j++ )\n\t\t\t\tother._mdata[i][j] = _mdata[i][j];\n\t}\n#endif\n\n/// Divide all elements by the value at (r,c), used for normalization.\n/** No need to check value, done by caller */\n\tvoid p_divideBy( size_t r, size_t c ) const\n\t{\n//\t\tassert( std::fabs( _mdata[r][c] ) > 1000*std::numeric_limits<FPT>::epsilon() );\n\t\tfor( auto& li: _mdata )\n\t\t\tfor( auto& e: li )\n\t\t\t\te /= _mdata[r][c];\n\t}\n\n\tvoid p_fillZero()\n\t{\n\t\tfor( auto& li: _mdata )\n\t\t\tfor( auto& e: li )\n\t\t\t\te = 0.;\n\t}\n\tvoid p_fillEye()\n\t{\n\t\tp_fillZero();\n\t\t_mdata[0][0] = 1.;\n\t\t_mdata[1][1] = 1.;  // \"eye\" matrix => unit transformation\n\t\t_mdata[2][2] = 1.;\n\t}\n\n\ttemplate<typename T>\n\tvoid p_fillWith( const T& in )\n\t{\n\t\tfor( auto i=0; i<3; i++ )\n\t\t\tfor( auto j=0; j<3; j++ )\n\t\t\t\t_mdata[i][j] = in[i][j];\n\t\t_isNormalized = false;\n\t}\n\n/// Divide all elements of \\c mat by \\v value\n\ttemplate<typename FPT2>\n\tvoid p_divideAll( detail::Matrix_<FPT>& mat, FPT2 value ) const\n\t{\n\t\tfor( int i=0; i<3; i++ )\n\t\t\tfor( int j=0; j<3; j++ )\n\t\t\t\tmat._mdata[i][j] /= value;\n\t\t_isNormalized = false;\n\t}\n\n/// Matrix multiplication\n\tfriend Matrix_ operator * ( const Matrix_& h1, const Matrix_& h2 )\n\t{\n\t\tHOMOG2D_START;\n\t\tMatrix_ out;\n\t\tproduct( out, h1, h2 );\n\t\treturn out;\n\t}\n\nprivate:\n\tHOMOG2D_INUMTYPE p_det2x2( const std::vector<int>& v ) const\n\t{\n\t\tauto det = static_cast<HOMOG2D_INUMTYPE>( _mdata[v[0]][v[1]] ) * _mdata[v[6]][v[7]];\n\t\tdet -=     static_cast<HOMOG2D_INUMTYPE>( _mdata[v[2]][v[3]] ) * _mdata[v[4]][v[5]];\n\t\treturn det;\n\t}\n/// Computes adjugate matrix, see https://en.wikipedia.org/wiki/Adjugate_matrix#3_%C3%97_3_generic_matrix\n\tdetail::Matrix_<FPT> p_adjugate() const\n\t{\n\t\tdetail::Matrix_<FPT> mat_out;\n\t\tmatrix_t<FPT>& out = mat_out._mdata;\n\n\t\tout[ 0 ][ 0 ] =  p_det2x2( {1,1, 1,2, 2,1, 2,2} );\n\t\tout[ 0 ][ 1 ] = -p_det2x2( {0,1, 0,2, 2,1, 2,2} );\n\t\tout[ 0 ][ 2 ] =  p_det2x2( {0,1, 0,2, 1,1, 1,2} );\n\n\t\tout[ 1 ][ 0 ] = -p_det2x2( {1,0, 1,2, 2,0, 2,2} );\n\t\tout[ 1 ][ 1 ] =  p_det2x2( {0,0, 0,2, 2,0, 2,2} );\n\t\tout[ 1 ][ 2 ] = -p_det2x2( {0,0, 0,2, 1,0, 1,2} );\n\n\t\tout[ 2 ][ 0 ] =  p_det2x2( {1,0, 1,1, 2,0, 2,1} );\n\t\tout[ 2 ][ 1 ] = -p_det2x2( {0,0, 0,1, 2,0, 2,1} );\n\t\tout[ 2 ][ 2 ] =  p_det2x2( {0,0, 0,1, 1,0, 1,1} );\n\n\t\treturn mat_out;\n\t}\n\n\tfriend std::ostream&\n\toperator << ( std::ostream& f, const Matrix_& h )\n\t{\n\t\tfor( const auto& li: h._mdata )\n\t\t{\n\t\t\tf << \"| \";\n\t\t\tfor( const auto& e: li )\n\t\t\t\tf << std::setw(6) << e << ' ';\n\t\t\tf << \" |\\n\";\n\t\t}\n\t\treturn f;\n\t}\n\npublic:\n\tstatic HOMOG2D_INUMTYPE& nullDeterValue() { return _zeroDeterminantValue; }\n\tstatic HOMOG2D_INUMTYPE& nullDenomValue() { return _zeroDenomValue; }\n\nprivate:\n\n}; // class Matrix_\n\ntemplate<typename T1,typename T2,typename FPT1,typename FPT2>\nvoid\nproduct( Root<T1,FPT1>&, const detail::Matrix_<FPT2>&, const Root<T2,FPT1>& );\n\n\n} // namespace detail\n\n//------------------------------------------------------------------\n/// A 2D homography, defining a planar transformation\n/**\nTo define an affine or rigid transformation, you can use:\n- setRotation()\n- setTranslation()\n- setScale()\n\nTo add an affine or rigid transformation to the current one, you can use:\n- addRotation()\n- addTranslation()\n- addScale()\n\nTo return to unit transformation, use init()\n\nImplemented as a 3x3 matrix\n\nTemplated by Floating-Point Type (FPT) and by type M (type::IsEpipmat or type::IsHomogr)\n */\ntemplate<typename M,typename FPT>\nclass Hmatrix_ : public detail::Matrix_<FPT>\n{\n\ttemplate<typename T1,typename T2> friend class Root;\n\n\ttemplate<typename T,typename U>\n\tfriend Line2d_<T>\n\toperator * ( const Homogr_<U>&, const Line2d_<T>& );\n\n\ttemplate<typename T,typename U>\n\tfriend Point2d_<T>\n\toperator * ( const Homogr_<U>&, const Point2d_<T>& );\n\n\ttemplate<typename T,typename U,typename V>\n\tfriend Root<typename detail::HelperPL<T>::OtherType,V>\n\toperator * ( const Hmatrix_<type::IsEpipmat,U>& h, const Root<T,V>& in );\n\npublic:\n\n/// \\name Constructors\n///@{\n\n\t/// Default constructor, initialize to unit transformation\n\tHmatrix_()\n\t{\n\t\tinit();\n\t}\n\n/// Constructor, set homography to a rotation matrix of angle \\c val\n\ttemplate<typename T>\n\texplicit Hmatrix_( T val )\n\t{\n\t\tHOMOG2D_CHECK_IS_NUMBER(T);\n\t\tinit();\n\t\tsetRotation( val );\n\t}\n\n/// Constructor, set homography to a translation matrix ( see Hmatrix_( T ) )\n\ttemplate<typename T1,typename T2>\n\texplicit Hmatrix_( T1 tx, T2 ty )\n\t{\n\t\tHOMOG2D_CHECK_IS_NUMBER(T1);\n\t\tHOMOG2D_CHECK_IS_NUMBER(T2);\n\t\tinit();\n\t\tsetTranslation( tx, ty );\n\t}\n\n/// Constructor, used to fill with a vector of vector matrix\n/** \\warning\n- Input matrix \\b must be 3 x 3, but type can be anything that can be copied to \\c double\n- no checking is done on validity of matrix as an homography.\nThus some assert can get triggered elsewhere.\n*/\n\ttemplate<typename T>\n\tHmatrix_( const std::vector<std::vector<T>>& in )\n\t{\n#ifndef HOMOG2D_NOCHECKS\n\t\tHOMOG2D_CHECK_IS_NUMBER(T);\n\t\tif( in.size() != 3 )\n\t\t\tHOMOG2D_THROW_ERROR_1( \"Invalid line size for input: \" << in.size() );\n\t\tfor( auto li: in )\n\t\t\tif( li.size() != 3 )\n\t\t\t\tHOMOG2D_THROW_ERROR_1( \"Invalid column size for input: \" << li.size() );\n#endif\n\t\tdetail::Matrix_<FPT>::p_fillWith( in );\n\t\tnormalize();\n\t}\n\n/// Constructor, used to fill with a std::array\n\ttemplate<typename T>\n\tHmatrix_( const std::array<std::array<T,3>,3>& in )\n\t{\n\t\tHOMOG2D_CHECK_IS_NUMBER(T);\n\t\tdetail::Matrix_<FPT>::p_fillWith( in );\n\t}\n\n/// Copy-constructor\n\tHmatrix_( const Hmatrix_<M,FPT>& other )\n\t\t: detail::Matrix_<FPT>( other)\n\t\t, _hasChanged   ( true )\n\t\t, _hmt          (  nullptr )\n\t{\n\t\tdetail::Matrix_<FPT>::getRaw() = other.getRaw();\n\t}\n\n#ifdef HOMOG2D_USE_OPENCV\n/// Constructor used to initialise with a cv::Mat, call the assignment operator\n\tHmatrix_( const cv::Mat& mat )\n\t{\n\t\t*this = mat;\n\t}\n#endif\n///@}\n\n/// Assignment operator\n\tHmatrix_& operator = ( const Hmatrix_<M,FPT>& other )\n\t{\n\t\tif( this != &other )\n\t\t\tdetail::Matrix_<FPT>::getRaw() = other.getRaw();\n\t\t_hasChanged = true;\n\t\treturn *this;\n\t}\n\n/// Inverse matrix\n\tHmatrix_& inverse()\n\t{\n\t\tdetail::Matrix_<FPT>::inverse();\n\t\tnormalize();\n\t\treturn *this;\n\t}\n\n#if 0\n/// Setter \\warning No normalization is done, as this can be done\n/// several times to store values, we therefore must not normalize in between\n\ttemplate<typename T>\n\tvoid set(\n\t\tsize_t r, ///< row\n\t\tsize_t c, ///< col\n\t\tT      v  ///< value\n\t)\n\t{\n\t\t#ifndef HOMOG2D_NOCHECKS\n\t\t\tHOMOG2D_CHECK_ROW_COL;\n\t\t#endif\n\t\t_data[r][c] = v;\n\t\t_isNormalized = false;\n\t\t_hasChanged = true;\n\t}\n\n/// Getter\n\tFPT get( size_t r, size_t c ) const\n\t{\n\t\t#ifndef HOMOG2D_NOCHECKS\n\t\t\tHOMOG2D_CHECK_ROW_COL;\n\t\t#endif\n\t\treturn _data[r][c];\n\t}\n\n\tdetail::Matrix_<FPT>&       getMat()       { return static_cast<detail::Matrix_<FPT>>(*this); }\n\tconst detail::Matrix_<FPT>& getMat() const { return static_cast<detail::Matrix_<FPT>>(*this); }\n#endif // 0\n\n\tvoid init()\n\t{\n\t\timpl_mat_init0( detail::RootHelper<M>() );\n\t}\n\n/// \\name Adding/assigning a transformation\n///@{\n\n/// Adds a translation \\c tx,ty to the matrix\n\ttemplate<typename T>\n\tHmatrix_& addTranslation( T tx, T ty )\n\t{\n\t\tHOMOG2D_CHECK_IS_NUMBER(T);\n\t\tHmatrix_ out;\n\t\tout.setTranslation( tx, ty );\n\t\t*this = out * *this;\n\t\treturn *this;\n\t}\n/// Sets the matrix as a translation \\c tx,ty\n\ttemplate<typename T1,typename T2>\n\tHmatrix_& setTranslation( T1 tx, T2 ty )\n\t{\n\t\tHOMOG2D_CHECK_IS_NUMBER(T1);\n\t\tHOMOG2D_CHECK_IS_NUMBER(T2);\n\t\tinit();\n\t\tauto& mat = detail::Matrix_<FPT>::_mdata;\n\t\tmat[0][2] = tx;\n\t\tmat[1][2] = ty;\n\t\tdetail::Matrix_<FPT>::_isNormalized = true;\n\t\t_hasChanged = true;\n\t\treturn *this;\n\t}\n/// Adds a rotation with an angle \\c theta (radians) to the matrix\n\ttemplate<typename T>\n\tHmatrix_& addRotation( T theta )\n\t{\n\t\tHOMOG2D_CHECK_IS_NUMBER(T);\n\t\tHmatrix_ out;\n\t\tout.setRotation( theta );\n\t\t*this = out * *this;\n\t\treturn *this;\n\t}\n/// Sets the matrix as a rotation with an angle \\c theta (radians)\n\ttemplate<typename T>\n\tHmatrix_& setRotation( T theta )\n\t{\n\t\tHOMOG2D_CHECK_IS_NUMBER(T);\n\t\tauto& mat = detail::Matrix_<FPT>::_mdata;\n\t\tinit();\n\t\tmat[0][0] = mat[1][1] = std::cos(theta);\n\t\tmat[1][0] = std::sin(theta);\n\t\tmat[0][1] = -mat[1][0];\n\t\tdetail::Matrix_<FPT>::_isNormalized = true;\n\t\t_hasChanged = true;\n\t\treturn *this;\n\t}\n/// Adds the same scale factor to the matrix\n\ttemplate<typename T>\n\tHmatrix_& addScale( T k )\n\t{\n\t\tHOMOG2D_CHECK_IS_NUMBER(T);\n\t\treturn this->addScale( k, k );\n\t}\n/// Adds a scale factor to the matrix\n\ttemplate<typename T1,typename T2>\n\tHmatrix_& addScale( T1 kx, T2 ky )\n\t{\n\t\tHOMOG2D_CHECK_IS_NUMBER(T1);\n\t\tHOMOG2D_CHECK_IS_NUMBER(T2);\n\t\tHmatrix_ out;\n\t\tout.setScale( kx, ky );\n\t\t*this = out * *this;\n\t\t_hasChanged = true;\n\t\treturn *this;\n\t}\n/// Sets the matrix as a scaling transformation (same on two axis)\n\ttemplate<typename T>\n\tHmatrix_& setScale( T k )\n\t{\n\t\tHOMOG2D_CHECK_IS_NUMBER(T);\n\t\treturn setScale( k, k );\n\t}\n/// Sets the matrix as a scaling transformation\n\ttemplate<typename T1,typename T2>\n\tHmatrix_& setScale( T1 kx, T2 ky )\n\t{\n\t\tHOMOG2D_CHECK_IS_NUMBER(T1);\n\t\tHOMOG2D_CHECK_IS_NUMBER(T2);\n\t\tinit();\n\t\tauto& mat = detail::Matrix_<FPT>::_mdata;\n\t\tmat[0][0] = kx;\n\t\tmat[1][1] = ky;\n\t\tdetail::Matrix_<FPT>::_isNormalized = true;\n\t\t_hasChanged = true;\n\t\treturn *this;\n\t}\n///@}\n\n\ttemplate<typename T>\n\tvoid applyTo( T& ) const;\n\n#ifdef HOMOG2D_USE_OPENCV\n\tvoid copyTo( cv::Mat&, int type=CV_64F ) const;\n\tHmatrix_& operator = ( const cv::Mat& );\n#endif\n\n/// Homography normalisation\n\tvoid normalize() const\n\t{\n\t\tdetail::Matrix_<FPT>::p_normalize(2,2);\n\t\t_hasChanged = true;\n\t}\n\n\tvoid buildFrom4Points( const std::vector<Point2d_<FPT>>&, const std::vector<Point2d_<FPT>>&, int method=1 );\n\n/// Matrix multiplication, call the base class product\n\tfriend Hmatrix_ operator * ( const Hmatrix_& h1, const Hmatrix_& h2 )\n\t{\n\t\tHmatrix_ out;\n\t\tdetail::product( out, static_cast<detail::Matrix_<FPT>>(h1), static_cast<detail::Matrix_<FPT>>(h2) ) ;\n\t\tout.normalize();\n\t\tout._hasChanged = true;\n\t\treturn out;\n\t}\n\n/// Comparison operator. Does normalization if required\n/**\nThis does an absolute comparison of all matrix elements, one by one,\nand if one differs more than the threshold, it will return false\n*/\n\tbool operator == ( const Hmatrix_& h ) const\n\t{\n\t\tauto& data = detail::Matrix_<FPT>::_mdata;\n\n\t\tif( !detail::Matrix_<FPT>::isNormalized() )\n\t\t\tnormalize();\n\t\tif( !h.isNormalized() )\n\t\t\th.normalize();\n\n\t\tfor( int i=0; i<3; i++ )\n\t\t\tfor( int j=0; j<3; j++ )\n\t\t\t\tif( std::fabs(\n\t\t\t\t\tstatic_cast<HOMOG2D_INUMTYPE>( data[i][j] ) - h.value(i,j) )\n\t\t\t\t\t>= detail::Matrix_<FPT>::nullDeterValue()\n\t\t\t\t)\n\t\t\t\t\treturn false;\n\t\treturn true;\n\t}\n/// Comparison operator. Does normalization if required\n\tbool operator != ( const Hmatrix_& h ) const\n\t{\n\t\treturn !(*this == h);\n\t}\n\n//////////////////////////\n//   PRIVATE FUNCTIONS  //\n//////////////////////////\n\nprivate:\n#ifdef HOMOG2D_FUTURE_STUFF\n/// Implementation for epipolar matrices: initialize to aligned axis\n\tvoid impl_mat_init0( const detail::RootHelper<type::IsEpipmat>& )\n\t{\n\t\t_data.fillZero();\n\t\t_data[2][1] = 1.;\n\t\t_data[1][2] = 1.;\n\t\t_isNormalized = true;\n\t}\n#endif\n\n/// Implementation for homographies: initialize to unit transformation\n\tvoid impl_mat_init0( const detail::RootHelper<type::IsHomogr>& )\n\t{\n\t\tdetail::Matrix_<FPT>::p_fillEye();\n\t\tdetail::Matrix_<FPT>::_isNormalized = true;\n\t}\n\n//////////////////////////\n//      DATA SECTION    //\n//////////////////////////\nprivate:\n\tmutable bool _hasChanged   = true;\n\tmutable std::unique_ptr<detail::Matrix_<FPT>> _hmt; ///< used to store \\f$ H^{-1} \\f$, but only if required\n\n\tfriend std::ostream& operator << ( std::ostream& f, const Hmatrix_& h )\n\t{\n\t\tf << \"Hmatrix:\\n\"\n\t\t\t<< static_cast<const detail::Matrix_<FPT>&>(h);\n\t\treturn f;\n\t}\n\n}; // class Hmatrix_\n\n\nnamespace img {\n\n//------------------------------------------------------------------\n/// Point drawing style, see DrawParams\nenum class PtStyle: uint8_t\n{\n\tPlus,   ///< \"+\" symbol\n\tTimes,  ///< \"times\" symbol\n\tStar,   ///< \"*\" symbol\n\tDiam    ///< diamond\n};\n\nnamespace priv {\n/// Color drawing (internal use), see DrawParams\nstruct Color\n{\n\tuint8_t r = 80;\n\tuint8_t g = 80;\n\tuint8_t b = 80;\n};\n\n} // namespace priv\n\n//------------------------------------------------------------------\n/// Draw parameters, independent of back-end library\nclass DrawParams\n{\n\n/// Inner struct, holds the values. Needed so we can assign a default value as static member\n\tstruct Dp_values\n\t{\n\t\tpriv::Color _color;\n\t\tint         _lineThickness = 1;\n\t\tint         _lineType      = 1; // 1 for cv::LINE_AA, 2 for cv::LINE_8\n\t\tint         _ptDelta       = 8;           ///< pixels, used for drawing points\n\t\tPtStyle     _ptStyle       = PtStyle::Plus;\n\t\tbool        _enhancePoint  = false;       ///< to draw selected points\n\n#ifdef HOMOG2D_USE_OPENCV\n\t\tcv::Scalar color() const\n\t\t{\n\t\t\treturn cv::Scalar( _color.b, _color.g, _color.r );\n\t\t}\n#endif // HOMOG2D_USE_OPENCV\n\t};\n\npublic:\n\tDp_values _dpValues;\n\nprivate:\n\tstatic Dp_values& p_getDefault()\n\t{\n\t\tstatic Dp_values s_defValue;\n\t\treturn s_defValue;\n\t}\n\npublic:\n\tDrawParams()\n\t{\n\t\t_dpValues = p_getDefault();\n\t}\n\tvoid setDefault()\n\t{\n\t\tp_getDefault() = this->_dpValues;\n\t}\n\tstatic void resetDefault()\n\t{\n\t\tp_getDefault() = Dp_values();\n\t}\n\tDrawParams& setPointStyle( PtStyle ps )\n\t{\n\t\tif( (int)ps > (int)PtStyle::Diam )\n\t\t\tthrow std::runtime_error( \"Error: invalid value for point style\");\n\t\t_dpValues._ptStyle = ps;\n\t\treturn *this;\n\t}\n\tDrawParams& setPointSize( int ps )\n\t{\n\t\tassert( ps>1 );\n\t\t_dpValues._ptDelta = ps;\n\t\treturn *this;\n\t}\n\tDrawParams& setThickness( int t )\n\t{\n\t\tassert( t>0 );\n\t\t_dpValues._lineThickness = t;\n\t\treturn *this;\n\t}\n\tDrawParams& setColor( uint8_t r, uint8_t g, uint8_t b )\n\t{\n\t\t_dpValues._color = priv::Color{r,g,b};\n\t\treturn *this;\n\t}\n\tDrawParams& selectPoint()\n\t{\n\t\t_dpValues._enhancePoint = true;\n\t\treturn *this;\n\t}\n}; // class DrawParams\n\n} // namespace img\n\n//------------------------------------------------------------------\nnamespace detail {\n\n/// Holds 9 parameters of ellipse\ntemplate<typename T>\nstruct EllParams\n{\n\tT x0, y0; ///< center\n\tT theta = 0.; ///< angle\n\tT sint, cost;\n\tT a, b;\n\tT a2, b2; ///< squared values of a and b\n\n\ttemplate<typename U>\n\tfriend std::ostream& operator << ( std::ostream& f, const EllParams<U>& par )\n\t{\n\t\tf << \"EllParams: origin=\" << par.x0 << \",\" << par.y0\n\t\t\t<< \" angle=\" << par.theta *180./M_PI\n\t\t\t<< \" a=\" << par.a << \" b=\" << par.b\n\t\t\t<< '\\n';\n\t\treturn f;\n\n\t}\n}; // struct EllParams\n\n} // namespace detail\n\n//------------------------------------------------------------------\n/// Ellipse as a conic in matrix form.\n/**\nThis enables its projection using homography\n\nSee:\n- https://en.wikipedia.org/wiki/Ellipse#General_ellipse\n- https://en.wikipedia.org/wiki/Matrix_representation_of_conic_sections\n\nGeneral equation of an ellipse:\n\\f[\nA x^2 + B x y + C y^2 + D x + E y + F = 0\n\\f]\nIt can be written as a 3 x 3 matrix:\n\\f[\n\\begin{bmatrix}\n  A & B/2 & D/2 \\\\\n  B/2 & C & E/2 \\\\\n  D/2 & E/2 & F\n\\end{bmatrix}\n\\f]\n\nMatrix coefficients computed from center x0,y0, major and minor distances (a,b) and angle theta:\n\\f[\n\\begin{aligned}\n  A &=   a^2 \\sin^2\\theta + b^2 \\cos^2\\theta \\\\\n  B &=  2\\left(b^2 - a^2\\right) \\sin\\theta \\cos\\theta \\\\\n  C &=   a^2 \\cos^2\\theta + b^2 \\sin^2\\theta \\\\\n  D &= -2A x_\\circ   -  B y_\\circ \\\\\n  E &= - B x_\\circ   - 2C y_\\circ \\\\\n  F &=   A x_\\circ^2 +  B x_\\circ y_\\circ + C y_\\circ^2 - a^2 b^2\n\\end{aligned}\n\\f]\n\nHomography projection: https://math.stackexchange.com/a/2320082/133647\n\n\\f[\nQ' = H^{-T} \\cdot Q \\cdot H^{-1}\n\\f]\n\n*/\ntemplate<typename FPT>\nclass Ellipse_: public detail::Matrix_<FPT>\n{\npublic:\n\tusing FType = FPT;\n\n\ttemplate<typename T> friend class Ellipse_;\n\n\ttemplate<typename FPT1,typename FPT2>\n\tfriend Ellipse_<FPT1>\n\toperator * ( const Homogr_<FPT2>&, const Circle_<FPT1>& );\n\n\ttemplate<typename FPT1,typename FPT2>\n\tfriend Ellipse_<FPT1>\n\toperator * ( const Homogr_<FPT2>&, const Ellipse_<FPT1>& );\n\npublic:\n/// \\name Constructors\n///@{\n\n/// Default constructor: centered at (0,0), major=2, minor=1\n\tEllipse_(): Ellipse_( 0., 0., 2., 1., 0. )\n\t{}\n\n/// Constructor 1\n\ttemplate<typename T1,typename T2=double,typename T3=double>\n\tEllipse_( const Point2d_<T1>& pt, T2 major=2., T2 minor=1., T3 angle=0. )\n\t\t: Ellipse_( pt.getX(), pt.getY(), major, minor, angle )\n\t{}\n\n/// Constructor 2\n\ttemplate<typename T1,typename T2=double,typename T3=double>\n\texplicit Ellipse_( T1 x, T1 y, T2 major=2., T2 minor=1., T3 angle=0. )\n\t{\n\t\tHOMOG2D_CHECK_IS_NUMBER(T1);\n\t\tHOMOG2D_CHECK_IS_NUMBER(T2);\n\t\tHOMOG2D_CHECK_IS_NUMBER(T3);\n\t\tif( major<minor )\n\t\t\tstd::swap( major, minor );\n\t\tp_init( x, y, major, minor, angle );\n\t}\n\n/// Constructor 3, import from circle\n\texplicit Ellipse_( const Circle_<FPT>& cir )\n\t{\n\t\tp_init( cir.center().getX(), cir.center().getY(), cir.radius(), cir.radius(), 0. );\n\t}\n\n/// Copy-Constructor\n\ttemplate<typename FPT2>\n\tEllipse_( const Ellipse_<FPT2>& other )\n\t\t: detail::Matrix_<FPT>( other )\n\t{}\n///@}\n\n\ttemplate<typename T1, typename T2>\n\tvoid translate( T1 dx, T2 dy )\n\t{\n\t\tHOMOG2D_CHECK_IS_NUMBER( T1 );\n\t\tHOMOG2D_CHECK_IS_NUMBER( T2 );\n\t\tauto par = p_getParams<HOMOG2D_INUMTYPE>();\n\t\tp_init( par.x0+dx, par.y0+dy, par.a, par.b, par.theta );\n\t}\n\n\ttemplate<typename FPT2>\n\tbool pointIsInside( const Point2d_<FPT2>& ) const;\n\n\ttemplate<typename T>\n\tvoid draw( img::Image<T>&, img::DrawParams dp=img::DrawParams() ) const;\n\n/// \\name attributes\n///@{\n\tbool isCircle( HOMOG2D_INUMTYPE thres=1.E-10 ) const;\n\tPoint2d_<FPT>    center() const;\n\tPolyline_<FPT>   getBB()  const;\n\tHOMOG2D_INUMTYPE angle()  const;\n\tstd::pair<HOMOG2D_INUMTYPE,HOMOG2D_INUMTYPE> getMajMin() const;\n///@}\n\n\tHOMOG2D_INUMTYPE area() const\n\t{\n\t\tauto par = p_getParams();\n\t\treturn M_PI * par.a * par.b;\n\t}\n\n\tstd::pair<Line2d_<FPT>,Line2d_<FPT>> getAxisLines() const;\n\n\ttemplate<typename T>\n\tfriend std::ostream&\n\toperator << ( std::ostream& f, const Ellipse_<T>& ell );\n\n//////////////////////////\n//   PRIVATE FUNCTIONS  //\n//////////////////////////\nprivate:\n/// private constructor, needed in friend function only\n/**\nThis is not public, because: 1-useless 2-not guarantee would be given that the input\nis indeed a valid ellipse\n*/\n\texplicit Ellipse_( const detail::Matrix_<FPT>& mat ): detail::Matrix_<FPT>( mat )\n\t{}\n\n\ttemplate<typename T>\n\tdetail::EllParams<T> p_getParams() const;\n\ttemplate<typename T>\n\tdetail::EllParams<T> p_computeParams() const;\n\n/// Called by all the constructors, fills the matrix.\n\tvoid p_init( double x0, double y0, double a, double b, double theta=0. )\n\t{\n\t\tauto& data = detail::Matrix_<FPT>::_mdata;\n\t\tHOMOG2D_INUMTYPE sin1 = std::sin(theta);\n\t\tHOMOG2D_INUMTYPE cos1 = std::cos(theta);\n\t\tHOMOG2D_INUMTYPE sin2 = sin1 * sin1;\n\t\tHOMOG2D_INUMTYPE cos2 = cos1 * cos1;\n\t\tHOMOG2D_INUMTYPE a2   = a*a;\n\t\tHOMOG2D_INUMTYPE b2   = b*b;\n\n\t\tHOMOG2D_INUMTYPE A = a2*sin2 + b2*cos2;\n\t\tHOMOG2D_INUMTYPE B = 2.*(b2-a2) * std::sin(theta) * std::cos(theta);\n\t\tHOMOG2D_INUMTYPE C = a2 * cos2 + b2 * sin2;\n\t\tHOMOG2D_INUMTYPE D = -2.*A * x0 -    B * y0;\n\t\tHOMOG2D_INUMTYPE E =   - B * x0 - 2.*C * y0;\n\t\tHOMOG2D_INUMTYPE F = A*x0*x0 + B*x0*y0 + C*y0*y0 - a2*b2;\n\n\t\tdata[0][0] = A;\n\t\tdata[1][1] = C;\n\t\tdata[2][2] = F;\n\n\t\tdata[0][1] = data[1][0] = B / 2.;\n\t\tdata[0][2] = data[2][0] = D / 2.;\n\t\tdata[1][2] = data[2][1] = E / 2.;\n\n#ifdef HOMOG2D_OPTIMIZE_SPEED\n\t\t_epHasChanged = false;\n\t\t_par.a = a;\n\t\t_par.b = b;\n\t\t_par.a2 = a2;\n\t\t_par.b2 = b2;\n\t\t_par.theta = theta;\n\t\t_par.sint = sin1;\n\t\t_par.cost = cos1;\n\t\t_par.x0 = x0;\n\t\t_par.y0 = y0;\n#endif\n\t}\n\n//////////////////////////\n//      DATA SECTION    //\n//////////////////////////\n// (matrix is inherited from base class)\n#ifdef HOMOG2D_OPTIMIZE_SPEED\n\tmutable bool _epHasChanged = true;   ///< if true, means we need to recompute parameters\n\tmutable detail::EllParams<FPT> _par;\n#endif\n}; // class Ellipse\n\n\n//------------------------------------------------------------------\nnamespace detail {\n\n// forward declaration of template instanciation\ntemplate<typename T1,typename T2,typename FPT1,typename FPT2>\nRoot<T1,FPT1> crossProduct( const Root<T2,FPT1>&, const Root<T2,FPT2>& );\n\nstruct Inters_1 {};\nstruct Inters_2 {};\n\n/// Common stuff for intersection code\nstruct IntersectCommon\n{\nprotected:\n\tbool _doesIntersect = false;\npublic:\n\tbool operator()() const\n\t{\n\t\treturn _doesIntersect;\n\t}\n};\n\n/// Base class for intersection, gets specialized\ntemplate<typename T,typename FPT>\nstruct Intersect {};\n\n//------------------------------------------------------------------\n/// One point intersection\ntemplate<typename FPT>\nclass Intersect<Inters_1,FPT>: public IntersectCommon\n{\n\ttemplate<typename U>\n\tfriend class ::h2d::Segment_;\n\n\tpublic:\n\t\tPoint2d_<FPT>\n\t\tget() const\n\t\t{\n\t\t\tif( !_doesIntersect )\n\t\t\t\tHOMOG2D_THROW_ERROR_1( \"No intersection points\" );\n\t\t\treturn _ptIntersect;\n\t\t}\n\t\tvoid set( const Point2d_<FPT>& pt )\n\t\t{\n\t\t\t_ptIntersect = pt;\n\t\t\t_doesIntersect = true;\n\t\t}\n\t\tsize_t size() const { return _doesIntersect?1:0; }\n\n\t\tIntersect() {}\n\t\tIntersect( const Point2d_<FPT>& ptInter )\n\t\t\t: _ptIntersect(ptInter)\n\t\t{\n\t\t\t_doesIntersect = true;\n\t\t}\n/// To enable conversions from different floating-point types\n\t\ttemplate<typename FPT2>\n\t\tIntersect( const Intersect<Inters_1,FPT2>& other )\n\t\t\t: IntersectCommon( other )\n\t\t{\n\t\t\t_ptIntersect   = other._ptIntersect;\n\t\t}\n\n\tprivate:\n\t\tPoint2d_<FPT> _ptIntersect;\n};\n\n//------------------------------------------------------------------\n/// Two points intersection\ntemplate<typename FPT>\nclass Intersect<Inters_2,FPT>: public IntersectCommon\n{\n\ttemplate<typename U,typename V>\n\tfriend class ::h2d::Root;\n\n\tpublic:\n\t\tIntersect() {}\n\t\tIntersect( const Point2d_<FPT>& p1, const Point2d_<FPT>& p2 )\n\t\t\t: _ptIntersect_1(p1), _ptIntersect_2(p2)\n\t\t{\n\t\t\t\t_doesIntersect = true;\n\t\t}\n/// To enable conversions from different floating-point types\n\t\ttemplate<typename FPT2>\n\t\tIntersect( const Intersect<Inters_2,FPT2>& other )\n\t\t\t: IntersectCommon( other )\n\t\t{\n\t\t\tauto ppts = other.get();\n\t\t\t_ptIntersect_1 = ppts.first;\n\t\t\t_ptIntersect_2 = ppts.second;\n\t\t}\n\t\tsize_t size() const { return _doesIntersect?2:0; }\n\n\t\tstd::pair<Point2d_<FPT>,Point2d_<FPT>>\n\t\tget() const\n\t\t{\n\t\t\tif( !_doesIntersect )\n\t\t\t\tHOMOG2D_THROW_ERROR_1( \"No intersection points\" );\n\t\t\treturn std::make_pair( _ptIntersect_1, _ptIntersect_2 );\n\t\t}\n\n\tprivate:\n\t\tPoint2d_<FPT> _ptIntersect_1, _ptIntersect_2;\n\n\tfriend std::ostream& operator << ( std::ostream& f, const Intersect<Inters_2,FPT>& inters )\n\t{\n\t\tf << \"bool=\" << inters._doesIntersect\n\t\t\t<< \" p1:\" << inters._ptIntersect_1\n\t\t\t<< \" p2:\" << inters._ptIntersect_2;\n\t\treturn f;\n\t}\n};\n\n//------------------------------------------------------------------\n/// Multiple points intersections\ntemplate<typename FPT>\nclass IntersectM\n{\nprivate:\n\tmutable std::vector<Point2d_<FPT>> _vecInters; ///< mutable, because it can get sorted in const functions\npublic:\n\tIntersectM() {}\n/// To enable conversions from different floating-point types\n\ttemplate<typename FPT2>\n\tIntersectM( const IntersectM<FPT2>& other )\n\t{\n\t\t_vecInters.resize( other.size() );\n\t\tauto it = _vecInters.begin();\n\t\tfor( const auto& elem: other.get() )\n\t\t\t*it++ = elem; // automatic type conversion\n\t}\n\n\tbool operator()() const\n\t{\n\t\treturn !_vecInters.empty();\n\t}\n\tsize_t size() const { return _vecInters.size(); }\n\tvoid add( const Point2d_<FPT>& pt )\n\t{\n\t\t_vecInters.push_back(pt);\n\t}\n\n\tvoid add( const std::vector<Point2d_<FPT>>& vpt )\n\t{\n\t\tfor( const auto& pt: vpt )\n\t\t\t_vecInters.push_back(pt);\n\t}\n\n/// Returns the intersection points, sorted\n\tstd::vector<Point2d_<FPT>> get() const\n\t{\n\t\tstd::sort( std::begin(_vecInters), std::end(_vecInters) );\n\t\treturn _vecInters;\n\t}\n\tfriend std::ostream&\n\toperator << ( std::ostream& f, IntersectM i )\n\t{\n\t\tf << \"IntersectM: size=\" << i.size() << '\\n' << i._vecInters;\n\t\treturn f;\n\t}\n};\n\n//------------------------------------------------------------------\n/// Helper class, holds result of intersections of two FRect_\n/// \\sa FRect_::intersectArea()\ntemplate<typename T>\nclass RectArea\n{\nprivate:\n\tbool      _success = false;\n\tFRect_<T> _area;\n\npublic:\n\tRectArea() = default;\n\tRectArea( const FRect_<T>& r ) : _success(true), _area(r)\n\t{}\n\tbool operator()() const\n\t{\n\t\treturn _success;\n\t}\n\n\tFRect_<T> get() const\n\t{\n\t\tassert( _success );\n\t\treturn _area;\n\t}\n};\n\n\n} // namespace detail\n\n\n//------------------------------------------------------------------\n/// A Flat Rectangle, modeled by its two opposite points\ntemplate<typename FPT>\nclass FRect_\n{\npublic:\n\tusing FType = FPT;\n\n\ttemplate<typename T> friend class FRect_;\n\nprivate:\n\tPoint2d_<FPT> _ptR1,_ptR2;\n\npublic:\n/** \\name Constructors */\n///@{\n/// Default constructor, initialize rectangle to (0,0)-(1,1)\n\tFRect_()\n\t{\n\t\t_ptR2.set( 1., 1. );\n\t}\n/// Constructor from 2 points\n\ttemplate<typename FPT2>\n\tFRect_( const Point2d_<FPT2>& pa, const Point2d_<FPT2>& pb )\n\t{\n\t\tset( pa, pb );\n\t}\n\n/// Constructor from center point, width and height\n\ttemplate<typename FPT2,typename T1, typename T2>\n\tFRect_( const Point2d_<FPT2>& p0, T1 w, T2 h )\n\t{\n\t\tHOMOG2D_CHECK_IS_NUMBER(T1);\n\t\tHOMOG2D_CHECK_IS_NUMBER(T2);\n\t\tset(\n\t\t\tPoint2d_<FPT>( p0.getX()-0.5L*w, p0.getY()-0.5L*h ),\n\t\t\tPoint2d_<FPT>( p0.getX()+0.5L*w, p0.getY()+0.5L*h )\n\t\t);\n\t}\n\n/// Constructor from x1, y1, x2, y2 (need to be all the same type)\n\ttemplate<typename T>\n\tFRect_( T x1, T y1, T x2, T y2 )\n\t{\n\t\tHOMOG2D_CHECK_IS_NUMBER(T);\n\t\tset( Point2d_<FPT>(x1,y1), Point2d_<FPT>(x2,y2) );\n\t}\n\n/// Copy-Constructor\n\ttemplate<typename FPT2>\n\tFRect_( const FRect_<FPT2>& other )\n\t\t: _ptR1(other._ptR1),_ptR2(other._ptR2)\n\t{}\n///@}\n\nprivate:\n/// Private constructor from 4 points, used in intersectArea( const FRect_& )\n\ttemplate<typename T>\n\tFRect_(\n\t\tconst Point2d_<T>& pt1,\n\t\tconst Point2d_<T>& pt2,\n\t\tconst Point2d_<T>& pt3,\n\t\tconst Point2d_<T>& pt4\n\t)\n\t{\n\t\tHOMOG2D_LOG( \"pt1\" << pt1 << \" pt2=\"<< pt2 << \" pt3=\" << pt3 << \" pt4=\" << pt4 );\n\t\tauto x0 = std::min( pt1.getX(), pt2.getX() );\n\t\tx0 = std::min( x0, pt3.getX() );\n\t\tx0 = std::min( x0, pt4.getX() );\n\t\tauto y0 = std::min( pt1.getY(), pt2.getY() );\n\t\ty0 = std::min( x0, pt3.getY() );\n\t\ty0 = std::min( x0, pt4.getY() );\n\n\t\tauto x1 = std::max( pt1.getX(), pt2.getX() );\n\t\tx1 = std::max( x1, pt3.getX() );\n\t\tx1 = std::max( x1, pt4.getX() );\n\t\tauto y1 = std::max( pt1.getY(), pt2.getY() );\n\t\ty1 = std::max( y1, pt3.getY() );\n\t\ty1 = std::max( y1, pt4.getY() );\n\n\t\t_ptR1 = Point2d_<FPT>(x0,y0);\n\t\t_ptR2 = Point2d_<FPT>(x1,y1);\n\t\tHOMOG2D_LOG( \"ptR1=\" <<_ptR1 << \" _ptR2=\" << _ptR2 );\n\t}\n\npublic:\n\tvoid set( const Point2d_<FPT>& pa, const Point2d_<FPT>& pb )\n\t{\n\t\tauto ppts = detail::getCorrectPoints( pa, pb );\n\t\t_ptR1 = ppts.first;\n\t\t_ptR2 = ppts.second;\n\t}\n\n/// \\name Attributes access\n///@{\n\tHOMOG2D_INUMTYPE height() const { return  _ptR2.getY() - _ptR1.getY(); }\n\tHOMOG2D_INUMTYPE width()  const { return  _ptR2.getX() - _ptR1.getX(); }\n\tHOMOG2D_INUMTYPE area()   const { return height() * width(); }\n\tHOMOG2D_INUMTYPE length() const { return 2.*height() + 2.*width(); }\n\n/// Returns the 2 major points of the rectangle\n/// \\sa getPts( const FRect_<FPT>& )\n\tstd::pair<Point2d_<FPT>,Point2d_<FPT>>\n\tgetPts() const\n\t{\n\t\treturn std::make_pair( _ptR1, _ptR2 );\n\t}\n\n\tPoint2d_<FPT> center() const\n\t{\n\t\treturn Point2d_<FPT>(\n\t\t\t(static_cast<HOMOG2D_INUMTYPE>(_ptR1.getX() ) + _ptR2.getX() ) * 0.5,\n\t\t\t(static_cast<HOMOG2D_INUMTYPE>(_ptR1.getY() ) + _ptR2.getY() ) * 0.5\n\t\t);\n\t}\n\n\tCircle_<FPT> getBoundingCircle() const;\n///@}\n\n\ttemplate<typename T1, typename T2>\n\tvoid translate( T1 dx, T2 dy )\n\t{\n\t\tHOMOG2D_CHECK_IS_NUMBER( T1 );\n\t\tHOMOG2D_CHECK_IS_NUMBER( T2 );\n\t\t_ptR1.set( _ptR1.getX() + dx, _ptR1.getY() + dy );\n\t\t_ptR2.set( _ptR2.getX() + dx, _ptR2.getY() + dy );\n\t}\n\n\n/// \\name Union/intersection area\n///@{\n\ttemplate<typename FPT2>\n\tPolyline_<FPT> unionArea( const FRect_<FPT2>& other ) const;\n\ttemplate<typename FPT2>\n\tdetail::RectArea<FPT> intersectArea( const FRect_<FPT2>& other ) const;\n\ttemplate<typename FPT2>\n\tPolyline_<FPT> operator | ( const FRect_<FPT2>& other ) const\n\t{\n\t\treturn this->unionArea( other );\n\t}\n\ttemplate<typename FPT2>\n\tdetail::RectArea<FPT> operator & ( const FRect_<FPT2>& other ) const\n\t{\n\t\treturn this->intersectArea( other );\n\t}\n///@}\n\n/// Returns the 4 points of the rectangle, starting from \"smallest\" one, and\n/// in clockwise order\n/**\n\\verbatim\n\n p1 +------+ p2\n    |      |\n    |      |\n    |      |\n p0 +------+ p3\n\n\\endverbatim\n\\sa get4Pts( const FRect_<FPT>& )\n*/\n\tstd::array<Point2d_<FPT>,4>\n\tget4Pts() const\n\t{\n\t\tstd::array<Point2d_<FPT>,4> arr;\n\t\tarr[0] = _ptR1;\n\t\tarr[1] = Point2d_<FPT>( _ptR1.getX(), _ptR2.getY() );\n\t\tarr[2] = _ptR2;\n\t\tarr[3] = Point2d_<FPT>( _ptR2.getX(), _ptR1.getY() );\n\t\treturn arr;\n\t}\n\n/// Returns the 4 segments of the rectangle, starting with the first vertical one\n/**\n\\verbatim\n      s1\n   +------+p2\n   |      |\ns0 |      | s2\n   |      |\n p1+------+\n      s3\n\\endverbatim\n\\sa \\ref h2d::getSegs( const FRect_& )\n*/\n\tstd::array<Segment_<FPT>,4>\n\tgetSegs() const\n\t{\n\t\tauto pts = get4Pts();\n\t\tstd::array<Segment_<FPT>,4> out;\n\t\tout[0] = Segment_<FPT>( pts[0], pts[1] );\n\t\tout[1] = Segment_<FPT>( pts[1], pts[2] );\n\t\tout[2] = Segment_<FPT>( pts[2], pts[3] );\n\t\tout[3] = Segment_<FPT>( pts[3], pts[0] );\n\t\treturn out;\n\t}\n/// Returns true if rectangle is inside \\c shape (circle or rectangle)\n/// \\todo maybe add some SFINAE to enable only for Circle_ or FRect_?\n\ttemplate<typename T>\n\tbool isInside( const T& shape )\n\t{\n\t\tfor( const auto& pt: get4Pts() )\n\t\t\tif( !pt.isInside( shape ) )\n\t\t\t\treturn false;\n\t\treturn true;\n\t}\n\n/// \\name Intersection functions\n///@{\n\n/// FRect/Line intersection\n\ttemplate<typename FPT2>\n\tdetail::Intersect<detail::Inters_2,FPT> intersects( const Line2d_<FPT2>& line ) const\n\t{\n\t\tHOMOG2D_START;\n\t\treturn line.intersects( *this );\n\t}\n\n/// FRect/Segment intersection\n\ttemplate<typename FPT2>\n\tdetail::IntersectM<FPT> intersects( const Segment_<FPT2>& seg ) const\n\t{\n\t\tHOMOG2D_START;\n\t\tdetail::IntersectM<FPT> out;\n\t\tfor( const auto& rseg: getSegs() )\n\t\t{\n\t\t\tauto inters = rseg.intersects( seg ); // call of Segment/Segment\n\t\t\tif( inters() )\n\t\t\t{\n\t\t\t\tauto pt =  inters.get();\n\t\t\t\tbool addPoint = true;\n\t\t\t\tif( out.size() == 1 ) // if we have already one\n\t\t\t\t\tif( out.get()[0] == pt )\n\t\t\t\t\t\taddPoint = false;\n\t\t\t\tif( addPoint )\n\t\t\t\t\tout.add( pt );\n\t\t\t\tif( out.size() == 2 )\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\treturn out;\n\t}\n\n/// FRect/Circle intersection\n\ttemplate<typename FPT2>\n\tdetail::IntersectM<FPT> intersects( const Circle_<FPT2>& circle ) const\n\t{\n\t\tHOMOG2D_START;\n\t\treturn p_intersects_R_C( circle );\n\t}\n\n/// FRect/Polyline intersection\n\ttemplate<typename FPT2>\n\tdetail::IntersectM<FPT> intersects( const Polyline_<FPT2>& pl ) const\n\t{\n\t\tHOMOG2D_START;\n\t\treturn pl.intersects( *this );\n\t}\n\n/// FRect/FRect intersection\n\ttemplate<typename FPT2>\n\tdetail::IntersectM<FPT> intersects( const FRect_<FPT2>& rect ) const\n\t{\n\t\tHOMOG2D_START;\n\t\tif( *this == rect )\n\t\t\treturn detail::IntersectM<FPT>();\n\t\treturn p_intersects_R_C( rect );\n\t}\n///@}\n\n/// \\name Operators\n///@{\n\ttemplate<typename FPT2>\n\tbool operator == ( const FRect_<FPT2>& other ) const\n\t{\n\t\tif( _ptR1 != other._ptR1 )\n\t\t\treturn false;\n\t\tif( _ptR2 != other._ptR2 )\n\t\t\treturn false;\n\t\treturn true;\n\t}\n\ttemplate<typename FPT2>\n\tbool operator != ( const FRect_<FPT2>& other ) const\n\t{\n\t\treturn !( *this == other );\n\t}\n///@}\n\n\ttemplate<typename T>\n\tfriend std::ostream&\n\toperator << ( std::ostream& f, const FRect_<T>& r );\n\n\ttemplate<typename T>\n\tvoid draw( img::Image<T>&, img::DrawParams dp=img::DrawParams() ) const;\n\nprivate:\n\ttemplate<typename FPT2>\n\tstd::vector<Point2d_<FPT>> p_pointsInside( const FRect_<FPT2>& other ) const\n\t{\n\t\tstd::vector<Point2d_<FPT>> out;\n\t\tfor( const auto& pt: get4Pts() )\n\t\t\tif( pt.isInside( other ) )\n\t\t\t\tout.push_back( pt );\n\t\treturn out;\n\t}\n\n/// Intersection of FRect vs FRect or Circle\n/**\n- We use a \\c std::set to avoid having multiple times the same point.\n- second arg is used to fetch the indexes of intersecting segments, when needed\n*/\n\ttemplate<typename T>\n\tdetail::IntersectM<FPT> p_intersects_R_C( const T& other ) const\n\t{\n\t\tstd::set<Point2d_<FPT>> pts;\n\t\tfor( const auto& rseg: getSegs() )\n\t\t{\n\t\t\tauto inters = rseg.intersects( other ); // call of Segment/FRect => FRect/Segment, or Segment/Circle\n\t\t\tif( inters() )\n\t\t\t{\n\t\t\t\tauto vpts = inters.get();\n\t\t\t\tassert( vpts.size() < 3 );\n\t\t\t\tif( vpts.size() > 0 )\n\t\t\t\t\tpts.insert( vpts[0] );\n\t\t\t\tif( vpts.size() > 1 )\n\t\t\t\t\tpts.insert( vpts[1] );\n\t\t\t}\n\t\t}\n\t\tdetail::IntersectM<FPT> out;\n\t\tfor( const auto& elem: pts )\n\t\t\tout.add( elem );\n\t\treturn out;\n\t}\n\n}; // class FRect_\n\n\n//------------------------------------------------------------------\n/// A circle\ntemplate<typename FPT>\nclass Circle_\n{\npublic:\n\tusing FType = FPT;\n\n\ttemplate<typename T> friend class Circle_;\n\nprivate:\n\tFPT           _radius;\n\tPoint2d_<FPT> _center;\n\npublic:\n/// \\name Constructors\n///@{\n\n/// Default constructor, unit-radius circle at (0,0)\n\tCircle_() : _radius(1.)\n\t{}\n\n/// Constructor 2, given radius circle at (0,0)\n\ttemplate<typename T>\n\texplicit Circle_( T rad )\n\t\t: Circle_( Point2d_<FPT>(), rad )\n\t{\n\t\tHOMOG2D_CHECK_IS_NUMBER(T);\n\t}\n\n/// Constructor 3: point and radius\n\ttemplate<typename T1, typename T2>\n\tCircle_( const Point2d_<T1>& center, T2 rad )\n\t\t: _radius(rad), _center(center)\n\t{\n\t\tif( std::abs(rad) < Point2d_<FPT>::nullDistance() )\n\t\t\tHOMOG2D_THROW_ERROR_1( \"radius must not be 0\" );\n\t}\n\n/// Constructor 4: x, y, radius\n\ttemplate<typename T1, typename T2>\n\tCircle_( T1 x, T1 y, T2 rad )\n\t\t: Circle_( Point2d_<FPT>(x,y), rad )\n\t{\n\t\tHOMOG2D_CHECK_IS_NUMBER(T1);\n\t\tHOMOG2D_CHECK_IS_NUMBER(T2);\n\t}\n\n/// Copy-Constructor\n\ttemplate<typename FPT2>\n\tCircle_( const Circle_<FPT2>& other )\n\t\t: _radius(other._radius), _center(other._center)\n\t{}\n///@}\n\n/// \\name Attributes access\n///@{\n\tFPT&       radius()       { return _radius; }\n\tconst FPT& radius() const { return _radius; }\n\n\tPoint2d_<FPT>       center()       { return _center; }\n\tconst Point2d_<FPT> center() const { return _center; }\n\n/// Returns Bounding Box\n\tFRect_<FPT> getBB() const\n\t{\n\t\treturn FRect_<FPT>(\n\t\t\t_center.getX()-_radius, _center.getY()-_radius,\n\t\t\t_center.getX()+_radius, _center.getY()+_radius\n\t\t);\n\t}\n///@}\n\n\tvoid set( const Point2d_<FPT>& center, FPT rad )\n\t{\n\t\t_radius = rad;\n\t\t_center = center;\n\t}\n\n\ttemplate<typename T1, typename T2>\n\tvoid translate( T1 dx, T2 dy )\n\t{\n\t\tHOMOG2D_CHECK_IS_NUMBER( T1 );\n\t\tHOMOG2D_CHECK_IS_NUMBER( T2 );\n\t\t_center.translate( dx, dy );\n\t}\n\n/// Returns true if circle is inside \\c other circle\n\ttemplate<typename FPT2>\n\tbool isInside( const Circle_<FPT2>& other ) const\n\t{\n\t\treturn( _radius + _center.distTo( other.center() ) < other.radius() );\n\t}\n\n/// Returns true if circle is inside rectangle defined by \\c p1 and \\c p2\n\ttemplate<typename FPT2>\n\tbool isInside( const Point2d_<FPT2>& p1, const Point2d_<FPT2>& p2 ) const\n\t{\n\t\treturn implC_isInside( detail::getCorrectPoints( p1, p2 ) );\n\t}\n\n/// Returns true if circle is inside flat rectangle \\c rect\n\ttemplate<typename FPT2>\n\tbool isInside( const FRect_<FPT2>& rect )\n\t{\n\t\treturn implC_isInside( rect.getPts() );\n\t}\n\n/// \\name Intersection\n///@{\n\n/// Circle/Line intersection\n\ttemplate<typename FPT2>\n\tdetail::Intersect<detail::Inters_2,FPT>\n\tintersects( const Line2d_<FPT2>& li ) const\n\t{\n\t\tHOMOG2D_START;\n\t\treturn li.intersects( *this );\n\t}\n\n/// Circle/Segment intersection\n\ttemplate<typename FPT2>\n\tdetail::IntersectM<FPT>\n\tintersects( const Segment_<FPT2>& seg ) const\n\t{\n\t\tHOMOG2D_START;\n\t\treturn seg.intersects( *this );\n\t}\n\n// Circle/Circle intersection\n\ttemplate<typename FPT2>\n\tdetail::Intersect<detail::Inters_2,FPT>\n\tintersects( const Circle_<FPT2>& seg ) const;\n\n/// Circle/FRect intersection\n\ttemplate<typename FPT2>\n\tdetail::IntersectM<FPT> intersects( const FRect_<FPT2>& rect ) const\n\t{\n\t\tHOMOG2D_START;\n\t\treturn rect.intersects( * this );\n\t}\n\n/// Circle/Polyline intersection\n\ttemplate<typename FPT2>\n\tdetail::IntersectM<FPT> intersects( const Polyline_<FPT2>& pl ) const\n\t{\n\t\tHOMOG2D_START;\n\t\treturn pl.intersects( * this );\n\t}\n///@}\n\nprivate:\n\ttemplate<typename FPT2>\n\tbool implC_isInside( const std::pair<Point2d_<FPT2>, Point2d_<FPT2>>& ppts ) const\n\t{\n\t\tconst auto& p1 = ppts.first;\n\t\tconst auto& p2 = ppts.second;\n\t\tHOMOG2D_INUMTYPE rad = _radius;   // convert to highest precision\n\t\tif( _center.getX() + rad < p2.getX() )\n\t\t\tif( _center.getX() - rad > p1.getX() )\n\t\t\t\tif( _center.getY() + rad < p2.getY() )\n\t\t\t\t\tif( _center.getY() - rad > p1.getY() )\n\t\t\t\t\t\treturn true;\n\t\treturn false;\n\t}\n\npublic:\n/// \\name Operators\n///@{\n\ttemplate<typename FPT2>\n\tbool operator == ( const Circle_<FPT2>& other ) const\n\t{\n\t\tif( _radius != other._radius )\n\t\t\treturn false;\n\t\tif( _center != other._center )\n\t\t\treturn false;\n\t\treturn true;\n\t}\n\ttemplate<typename FPT2>\n\tbool operator != ( const Circle_<FPT2>& other ) const\n\t{\n\t\treturn !( *this == other );\n\t}\n///@}\n\n\ttemplate<typename T>\n\tfriend std::ostream&\n\toperator << ( std::ostream& f, const Circle_<T>& r );\n\n\ttemplate<typename T>\n\tvoid draw( img::Image<T>&, img::DrawParams dp=img::DrawParams() ) const;\n\n}; // class Circle_\n\n//------------------------------------------------------------------\n/// Return circle passing through 4 points of flat rectangle\ntemplate<typename FPT>\nCircle_<FPT>\nFRect_<FPT>::getBoundingCircle() const\n{\n\tauto pts = get4Pts();\n\tauto seg1 = pts[1] * pts[3];\n\tauto seg2 = pts[0] * pts[2];\n\n\tauto middle_pt = seg1 * seg2;\n\treturn Circle_<FPT>( middle_pt, middle_pt.distTo( pts[0] ) );\n}\n\n\n/*\n/// Constructor: build Ellipse from Circle\n/// \\todo finish this\ntemplate<typename FPT>\nEllipse_<FPT>::Ellipse_( const Circle_<FPT>& cir )\n{\n\tp_init( cir.center().getX(), cir.center().getY(), radius(), radius(), 0. );\n}\n*/\n\n//------------------------------------------------------------------\n/// Holds private stuff\nnamespace priv {\n\n/// Private free function, swap the points so that \\c ptA.x <= \\c ptB.x, and if equal, sorts on y\ntemplate<typename FPT>\nvoid\nfix_order( Point2d_<FPT>& ptA, Point2d_<FPT>& ptB )\n{\n#if 0\n\tif( ptA.getX() > ptB.getX() )\n\t\tstd::swap( ptA, ptB );\n\telse\n\t\tif( ptA.getX() == ptB.getX() )\n\t\t\tif( ptA.getY() > ptB.getY() )\n\t\t\t\tstd::swap( ptA, ptB );\n#else\n\tif( !(ptA < ptB) )\n\t\tstd::swap( ptA, ptB );\n#endif\n}\n\n\n/// Helper function, factorized here for the two impl_getPoints_A() implementations\ntemplate<typename FPT, typename FPT2>\nstd::pair<Point2d_<FPT>,Point2d_<FPT>>\ngetPoints_B2( const Point2d_<FPT>& pt, FPT2 dist, const Line2d_<FPT>& li )\n{\n\tauto arr = li.get();\n\tconst HOMOG2D_INUMTYPE a = static_cast<HOMOG2D_INUMTYPE>(arr[0]);\n\tconst HOMOG2D_INUMTYPE b = static_cast<HOMOG2D_INUMTYPE>(arr[1]);\n\tauto coeff = static_cast<HOMOG2D_INUMTYPE>(dist) / std::sqrt( a*a + b*b );\n\n\tPoint2d_<FPT> pt1(\n        pt.getX() -  b * coeff,\n        pt.getY() +  a * coeff\n\t);\n\tPoint2d_<FPT> pt2(\n        pt.getX() +  b * coeff,\n        pt.getY() -  a * coeff\n\t);\n\tfix_order( pt1, pt2 );\n\treturn std::make_pair( pt1, pt2 );\n}\n\n/// Helper function for impl_getOrthogonalLine_A() and impl_getOrthogonalLine_B()\ntemplate<typename T1,typename T2>\nLine2d_<T1>\ngetOrthogonalLine_B2( const Point2d_<T2>& pt, const Line2d_<T1>& li )\n{\n\tauto arr = li.get();\n\tLine2d_<T1> out(\n\t\t-arr[1],\n\t\tarr[0],\n\t\tarr[1] * pt.getX() - arr[0] * pt.getY()\n\t);\n\tout.p_normalizeLine();\n\treturn out;\n}\n\n#ifdef HOMOG2D_DEBUGMODE\ntemplate<typename T>\nvoid printVector( const std::vector<T>& v, std::string msg=std::string() )\n{\n\tstd::cout << \"vector: \";\n\tif( !msg.empty() )\n\t\tstd::cout << msg;\n\tstd::cout << \" #=\" << v.size() << '\\n';\n\tfor( const auto& elem: v )\n\t\tstd::cout << elem << \"-\";\n\tstd::cout << '\\n';\n}\ntemplate<typename T,size_t N>\nvoid printArray( const std::array<T,N>& v, std::string msg=std::string() )\n{\n\tstd::cout << \"array: \";\n\tif( msg.empty() )\n\t\tstd::cout << msg;\n\tstd::cout << \" #=\" << N<< '\\n';\n\tfor( const auto& elem: v )\n\t\tstd::cout << elem << \"-\";\n\tstd::cout << '\\n';\n}\ntemplate<typename T>\nvoid printVectorPairs( const std::vector<std::pair<T,T>>& v )\n{\n\tstd::cout << \"vector of pairs: #=\" << v.size() << '\\n';\n\tfor( const auto& elem: v )\n\t\tstd::cout << \" [\" << (int)elem.first << \"-\" << (int)elem.second << \"] \";\n\tstd::cout << '\\n';\n}\n#endif\n} // namespace priv\n\n//------------------------------------------------------------------\n/// Base class, will be instanciated as a \\ref Point2d or a \\ref Line2d\n/**\nParameters:\n- LP: Line or Point\n- FPT: Floating Point Type\n*/\ntemplate<typename LP,typename FPT>\nclass Root\n{\npublic:\n\tusing FType = FPT;\n\nprivate:\n\ttemplate<typename U,typename V> friend class Hmatrix_;\n\n// This is needed so we can convert from, say, Point2d_<float> to Point2d_<double>\n\ttemplate<typename U,typename V> friend class Root;\n\n\ttemplate<typename FPT1,typename FPT2>\n\tfriend Point2d_<FPT1>\n\toperator * ( const Line2d_<FPT1>&, const Line2d_<FPT2>& );\n\n\ttemplate<typename FPT1,typename FPT2>\n\tfriend Line2d_<FPT1>\n\toperator * ( const Point2d_<FPT1>&, const Point2d_<FPT2>& );\n\n\ttemplate<typename T,typename U>\n\tfriend Line2d_<T>\n\toperator * ( const Homogr_<U>&, const Line2d_<T>& );\n\n\ttemplate<typename T1,typename T2,typename FPT1,typename FPT2>\n\tfriend Root<T1,FPT1>\n\tdetail::crossProduct( const Root<T2,FPT1>&, const Root<T2,FPT2>& );\n\n\ttemplate<typename U,typename V>\n\tfriend std::ostream&\n\toperator << ( std::ostream& f, const Root<U,V>& r );\n\n\ttemplate<typename T1,typename T2,typename FPT1,typename FPT2>\n\tfriend void\n\tdetail::product( Root<T1,FPT1>&, const detail::Matrix_<FPT2>&, const Root<T2,FPT1>& );\n\n\ttemplate<typename T1,typename T2>\n\tfriend Line2d_<T1>\n\tpriv::getOrthogonalLine_B2( const Root<type::IsPoint,T2>&, const Line2d_<T1>& );\n\npublic:\n\n/// Constructor: build a point from two lines\n\ttemplate<typename FPT2>\n\tRoot( const Line2d_<FPT2>& v1, const Line2d_<FPT2>& v2 )\n\t{\n#ifndef HOMOG2D_NOCHECKS\n\t\tif( v1.isParallelTo(v2) )\n\t\t\tHOMOG2D_THROW_ERROR_1( \"unable to build point from these two lines, are parallel\" );\n#endif\n\t\t*this = detail::crossProduct<type::IsPoint>( v1, v2 );\n\t}\n\n/// Constructor: build a line from two points\n\ttemplate<typename FPT2>\n\tRoot( const Point2d_<FPT2>& v1, const Point2d_<FPT2>& v2 )\n\t{\n#ifndef HOMOG2D_NOCHECKS\n\t\tif( v1 == v2 )\n\t\t\tHOMOG2D_THROW_ERROR_1( \"unable to build line from these two points, are the same: \" << v1 );\n#endif\n\t\t*this = detail::crossProduct<type::IsLine>( v1, v2 );\n\t\tp_normalizeLine();\n\t}\n\n/// Constructor: copy-constructor for lines\n/**\n\\todo We should be able to declare this \"explicit\". This fails at present when attempting\nto convert a line (or point) from double to float, but I don't get why...\n*/\n\ttemplate<typename T>\n//\t\texplicit\n\tRoot( const Line2d_<T>& li )\n\t{\n\t\timpl_init_1_Line<T>( li, detail::RootHelper<LP>() );\n\t}\n\n/// Constructor with single arg of type \"Point\"\n/**\nThis will call one of the two overloads of \\c impl_init_1_Point(), depending on type of object:\n- if type is a point, then it can be seen as a copy-constructor\n- if type is a line, this will build a line from (0,0] to \\c pt\n*/\n\ttemplate<typename T>\n\tRoot( const Point2d_<T>& pt )\n\t{\n\t\timpl_init_1_Point<T>( pt, detail::RootHelper<LP>() );\n\t}\n\n/// Constructor: build from two numerical values, depends on the type\n\ttemplate<typename T1,typename T2>\n\tRoot( const T1& v1, const T2& v2 )\n\t{\n\t\tHOMOG2D_CHECK_IS_NUMBER(T1);\n\t\tHOMOG2D_CHECK_IS_NUMBER(T2);\n\t\timpl_init_2( v1, v2, detail::RootHelper<LP>() );\n\t}\n\n/// Constructor of line/point from 3 values\n\ttemplate<typename T>\n\tRoot( T v0, T v1, T v2 )\n\t{\n\t\tHOMOG2D_CHECK_IS_NUMBER(T);\n\t\t_v[0] = v0;\n\t\t_v[1] = v1;\n\t\t_v[2] = v2;\n\t}\n\n/// Constructor of line from 4 values x1,y1,x2,y2\n\ttemplate<typename T>\n\tRoot( T x1, T y1, T x2, T y2 )\n\t{\n\t\tHOMOG2D_CHECK_IS_NUMBER(T);\n\t\timpl_init_4( x1, y1, x2, y2, detail::RootHelper<LP>() );\n\t}\n\n/// Default constructor, depends on the type\n\tRoot()\n\t{\n\t\timpl_init( detail::RootHelper<LP>() );\n\t}\n\n/// Constructor of horizontal/vertical line\n\ttemplate<typename T>\n\tRoot( LineDir orient, T value )\n\t{\n\t\tHOMOG2D_CHECK_IS_NUMBER(T);\n\t\timpl_init_or( orient, value, detail::RootHelper<LP>() );\n\t}\n\nprivate:\n\ttemplate<typename T,typename U>\n\tvoid p_copyFrom( const Root<T,U>& other )\n\t{\n\t\t_v[0] = static_cast<FPT>(other._v[0]);\n\t\t_v[1] = static_cast<FPT>(other._v[1]);\n\t\t_v[2] = static_cast<FPT>(other._v[2]);\n\t}\n\t/// Arg is a point, object is a point => copy-constructor\n\ttemplate<typename T>\n\tvoid impl_init_1_Point( const Point2d_<T>& pt, const detail::RootHelper<type::IsPoint>& )\n\t{\n\t\tp_copyFrom( pt );\n\t}\n\t/// Arg is a point, object is a line: we build the line passing though (0,0) ant the given point\n\ttemplate<typename T>\n\tvoid impl_init_1_Point( const Point2d_<T>& pt, const detail::RootHelper<type::IsLine>& )\n\t{\n\t\t*this = detail::crossProduct<type::IsLine>( pt, Point2d_<FPT>() );\n\t\tp_normalizeLine();\n\t}\n\n\t/// Arg is a line, object is a point: ILLEGAL INSTANCIATION\n\ttemplate<typename T>\n\tvoid impl_init_1_Line( const Line2d_<T>&, const detail::RootHelper<type::IsPoint>& )\n\t{\n\t\tstatic_assert( detail::AlwaysFalse<LP>::value, \"Invalid: you cannot build a point from a line\" );\n\t}\n\t/// Arg is a line, object is a line => copy-constructor\n\ttemplate<typename T>\n\tvoid impl_init_1_Line( const Line2d_<T>& li, const detail::RootHelper<type::IsLine>& )\n\t{\n\t\tp_copyFrom( li );\n\t}\n\n\ttemplate<typename T>\n\tvoid impl_init_or( LineDir, T, const detail::RootHelper<type::IsPoint>& )\n\t{\n\t\tstatic_assert( detail::AlwaysFalse<LP>::value, \"Invalid: you cannot build a horiz/vertical point\" );\n\t}\n\ttemplate<typename T>\n\tvoid impl_init_or( LineDir dir, T value, const detail::RootHelper<type::IsLine>& )\n\t{\n\t\t_v[2] = -value;\n\t\tif( dir == LineDir::V )\n\t\t{\n\t\t\t_v[0] = 1.; _v[1] = 0.;\n\t\t}\n\t\telse  // = LineDir::H\n\t\t{\n\t\t\t_v[0] = 0.; _v[1] = 1.;\n\t\t}\n\t}\n\n\ttemplate<typename T>\n\tvoid impl_init_4( T, T, T, T, const detail::RootHelper<type::IsPoint>& )\n\t{\n\t\tstatic_assert( detail::AlwaysFalse<LP>::value, \"Invalid: you cannot build a point from 4 values\" );\n\t}\n\ttemplate<typename T>\n\tvoid impl_init_4( T x1, T y1, T x2, T y2, const detail::RootHelper<type::IsLine>& )\n\t{\n\t\t*this = Point2d_<HOMOG2D_INUMTYPE>(x1, y1) * Point2d_<HOMOG2D_INUMTYPE>(x2, y2);\n\t}\n\npublic:\n\tType type() const\n\t{\n\t\treturn impl_type( detail::RootHelper<LP>() );\n\t}\n\tDtype dtype() const\n\t{\n\t\treturn impl_dtype( detail::RootDataType<FPT>() );\n\t}\n\nprivate:\n\tType impl_type( const detail::RootHelper<type::IsPoint>& ) const\n\t{\n\t\treturn Type::Point2d;\n\t}\n\tType impl_type( const detail::RootHelper<type::IsLine>& ) const\n\t{\n\t\treturn Type::Line2d;\n\t}\n\n\tDtype impl_dtype( const detail::RootDataType<float>& ) const\n\t{\n\t\treturn Dtype::Float;\n\t}\n\tDtype impl_dtype( const detail::RootDataType<double>& ) const\n\t{\n\t\treturn Dtype::Double;\n\t}\n\tDtype impl_dtype( const detail::RootDataType<long double>& ) const\n\t{\n\t\treturn Dtype::LongDouble;\n\t}\n\npublic:\n\tFPT\n\tgetCoord( GivenCoord gc, FPT other ) const\n\t{\n\t\treturn impl_getCoord( gc, other, detail::RootHelper<LP>() );\n\t}\n\n\tPoint2d_<FPT>\n\tgetPoint( GivenCoord gc, FPT other ) const\n\t{\n\t\treturn impl_getPoint( gc, other, detail::RootHelper<LP>() );\n\t}\n\n\t/// Returns a pair of points that are lying on line at distance \\c dist from a point defined by one of its coordinates.\n\ttemplate<typename FPT2>\n\tstd::pair<Point2d_<FPT>,Point2d_<FPT>>\n\tgetPoints( GivenCoord gc, FPT coord, FPT2 dist ) const\n\t{\n\t\treturn impl_getPoints_A( gc, coord, dist, detail::RootHelper<LP>() );\n\t}\n\n\t/// Returns a pair of points that are lying on line at distance \\c dist from point \\c pt, assuming that one is lying on the line.\n\ttemplate<typename FPT2>\n\tstd::pair<Point2d_<FPT>,Point2d_<FPT>>\n\tgetPoints( const Point2d_<FPT>& pt, FPT2 dist ) const\n\t{\n\t\treturn impl_getPoints_B( pt, dist, detail::RootHelper<LP>() );\n\t}\n\n\t/// Returns an orthogonal line to the one it is called on, at a point defined by one of its coordinates.\n\tLine2d_<FPT>\n\tgetOrthogonalLine( GivenCoord gc, FPT other ) const\n\t{\n\t\treturn impl_getOrthogonalLine_A( gc, other, detail::RootHelper<LP>() );\n\t}\n\n\t/// Returns an orthogonal line to the one it is called on, at point \\c pt, assuming that one is lying on the line.\n\tLine2d_<FPT>\n\tgetOrthogonalLine( const Point2d_<FPT>& pt ) const\n\t{\n\t\treturn impl_getOrthogonalLine_B( pt, detail::RootHelper<LP>() );\n\t}\n\n\t/// Returns an parallel line to the one it is called on, with \\c pt lying on it.\n\tLine2d_<FPT>\n\tgetParallelLine( const Point2d_<FPT>& pt ) const\n\t{\n\t\treturn impl_getParallelLine( pt, detail::RootHelper<LP>() );\n\t}\n\n\t/// Returns the pair of parallel lines at a distance \\c dist from line.\n\ttemplate<typename T>\n\tstd::pair<Line2d_<FPT>,Line2d_<FPT>>\n\tgetParallelLines( T dist ) const\n\t{\n\t\treturn impl_getParallelLines( dist, detail::RootHelper<LP>() );\n\t}\n\n\tFPT getX() const { return impl_getX( detail::RootHelper<LP>() ); }\n\tFPT getY() const { return impl_getY( detail::RootHelper<LP>() ); }\n\n\ttemplate<typename T1,typename T2>\n\tvoid translate( T1 dx, T2 dy )\n\t{\n\t\tHOMOG2D_CHECK_IS_NUMBER( T1 );\n\t\tHOMOG2D_CHECK_IS_NUMBER( T2 );\n\t\timpl_move( dx, dy, detail::RootHelper<LP>() );\n\t}\n\n\tstd::array<FPT,3> get() const { return impl_get( detail::RootHelper<LP>() ); }\n\n\ttemplate<typename T1,typename T2>\n\tvoid set( T1 x, T2 y ) { impl_set( x, y, detail::RootHelper<LP>() ); }\n\n\ttemplate<typename FPT2>\n\tHOMOG2D_INUMTYPE distTo( const Point2d_<FPT2>& pt ) const\n\t{\n\t\treturn impl_distToPoint( pt, detail::RootHelper<LP>() );\n\t}\n\ttemplate<typename FPT2>\n\tHOMOG2D_INUMTYPE distTo( const Line2d_<FPT2>& li ) const\n\t{\n\t\treturn impl_distToLine( li, detail::RootHelper<LP>() );\n\t}\n\n\ttemplate<typename T,typename FPT2>\n\tbool isParallelTo( const Root<T,FPT2>& li ) const\n\t{\n\t\treturn impl_isParallelTo( li, detail::RootHelper<T>() );\n\t}\n\ttemplate<typename T>\n\tbool isParallelTo( const Segment_<T>& seg ) const\n\t{\n\t\treturn impl_isParallelTo( seg.getLine(), detail::RootHelper<LP>() );\n\t}\n/// Returns angle in rad. between the lines. \\sa h2d::getAngle()\n/**\nPlease check out warning described in impl_getAngle()\n*/\n\ttemplate<typename T,typename FPT2>\n\tHOMOG2D_INUMTYPE getAngle( const Root<T,FPT2>& other ) const\n\t{\n\t\treturn impl_getAngle( other, detail::RootHelper<T>() );\n\t}\n\n/// Returns angle in rad. between line and segment \\c seg. \\sa  h2d::getAngle()\n\ttemplate<typename FPT2>\n\tHOMOG2D_INUMTYPE getAngle( const Segment_<FPT2>& seg ) const\n\t{\n\t\treturn impl_getAngle( seg.getLine(), detail::RootHelper<LP>() );\n\t}\n\nprivate:\n\tFPT impl_getX( const detail::RootHelper<type::IsPoint>& ) const\n\t{\n\t\treturn _v[0]/_v[2];\n\t}\n\tFPT impl_getY( const detail::RootHelper<type::IsPoint>& ) const\n\t{\n\t\treturn _v[1]/_v[2];\n\t}\n\n\tstd::array<FPT,3> impl_get( const detail::RootHelper<type::IsPoint>& ) const\n\t{\n\t\tstatic_assert( detail::AlwaysFalse<LP>::value, \"illegal for points\" );\n\t}\n\tstd::array<FPT,3> impl_get( const detail::RootHelper<type::IsLine>& ) const\n\t{\n\t\treturn std::array<FPT,3> { _v[0], _v[1], _v[2] };\n\t}\n\ttemplate<typename T1,typename T2>\n\tvoid impl_set( T1 x, T2 y, const detail::RootHelper<type::IsPoint>& )\n\t{\n\t\t_v[0] = x;\n\t\t_v[1] = y;\n\t\t_v[2] = 1.;\n\t}\n\ttemplate<typename T1,typename T2>\n\tvoid impl_set( T1, T2, const detail::RootHelper<type::IsLine>& )\n\t{\n\t\tstatic_assert( detail::AlwaysFalse<LP>::value, \"Invalid call for lines\" );\n\t}\n\n\ttemplate<typename T1,typename T2>\n\tvoid impl_move( T1 dx, T2 dy, const detail::RootHelper<type::IsPoint>& )\n\t{\n\t\t_v[0] = static_cast<HOMOG2D_INUMTYPE>(_v[0]) / _v[2] + dx;\n\t\t_v[1] = static_cast<HOMOG2D_INUMTYPE>(_v[1]) / _v[2] + dy;\n\t\t_v[2] = 1.;\n\t}\n\ttemplate<typename T1,typename T2>\n\tvoid impl_move( T1 dx, T2 dy, const detail::RootHelper<type::IsLine>& )\n\t{\n\t\tstatic_assert( detail::AlwaysFalse<LP>::value, \"Invalid call for lines\" );\n\t}\n\n\ttemplate<typename FPT2>\n\tHOMOG2D_INUMTYPE impl_distToPoint( const Point2d_<FPT2>&, const detail::RootHelper<type::IsPoint>& ) const;\n\ttemplate<typename FPT2>\n\tHOMOG2D_INUMTYPE impl_distToPoint( const Point2d_<FPT2>&, const detail::RootHelper<type::IsLine>&  ) const;\n\ttemplate<typename FPT2>\n\tHOMOG2D_INUMTYPE impl_distToLine(  const Line2d_<FPT2>&,  const detail::RootHelper<type::IsPoint>& ) const;\n\ttemplate<typename FPT2>\n\tHOMOG2D_INUMTYPE impl_distToLine(  const Line2d_<FPT2>&,  const detail::RootHelper<type::IsLine>&  ) const;\n\n\tHOMOG2D_INUMTYPE impl_getAngle(     const Root<LP,FPT>&, const detail::RootHelper<type::IsLine>&  ) const;\n\tHOMOG2D_INUMTYPE impl_getAngle(     const Root<LP,FPT>&, const detail::RootHelper<type::IsPoint>& ) const;\n\n\ttemplate<typename FPT2>\n\tbool impl_isParallelTo( const Root<LP,FPT2>&, const detail::RootHelper<type::IsLine>&  ) const;\n\ttemplate<typename FPT2>\n\tbool impl_isParallelTo( const Root<LP,FPT2>&, const detail::RootHelper<type::IsPoint>& ) const;\n\n\tFPT impl_getCoord( GivenCoord gc, FPT other, const detail::RootHelper<type::IsLine>& ) const;\n\tFPT impl_getCoord( GivenCoord gc, FPT other, const detail::RootHelper<type::IsPoint>& ) const;\n\n\tPoint2d_<FPT> impl_getPoint( GivenCoord gc, FPT other, const detail::RootHelper<type::IsLine>& ) const;\n\tPoint2d_<FPT> impl_getPoint( GivenCoord gc, FPT other, const detail::RootHelper<type::IsPoint>& ) const;\n\n\ttemplate<typename FPT2>\n\tstd::pair<Point2d_<FPT>,Point2d_<FPT>> impl_getPoints_A( GivenCoord gc, FPT coord, FPT2 dist, const detail::RootHelper<type::IsLine>& ) const;\n\ttemplate<typename FPT2>\n\tstd::pair<Point2d_<FPT>,Point2d_<FPT>> impl_getPoints_A( GivenCoord gc, FPT coord, FPT2 dist, const detail::RootHelper<type::IsPoint>& ) const;\n\ttemplate<typename FPT2>\n\tstd::pair<Point2d_<FPT>,Point2d_<FPT>> impl_getPoints_B( const Point2d_<FPT>&, FPT2 dist, const detail::RootHelper<type::IsLine>& ) const;\n\ttemplate<typename FPT2>\n\tstd::pair<Point2d_<FPT>,Point2d_<FPT>> impl_getPoints_B( const Point2d_<FPT>&, FPT2 dist, const detail::RootHelper<type::IsPoint>& ) const;\n\n\tvoid impl_op_stream( std::ostream&, const Point2d_<FPT>& ) const;\n\tvoid impl_op_stream( std::ostream&, const Line2d_<FPT>&  ) const;\n\npublic:\n/// Line/Line intersection\n\ttemplate<typename FPT2>\n\tdetail::Intersect<detail::Inters_1,FPT> intersects( const Line2d_<FPT2>& other ) const\n\t{\n\t\tdetail::Intersect<detail::Inters_1,FPT> out;\n\t\tif( this->isParallelTo( other ) )\n\t\t\treturn out;\n\t\t out.set( *this * other );\n\t\t return out;\n\t}\n/// Line/FRect intersection\n\ttemplate<typename FPT2>\n\tdetail::Intersect<detail::Inters_2,FPT> intersects( const Point2d_<FPT2>& pt1, const Point2d_<FPT2>& pt2 ) const\n\t{\n\t\tHOMOG2D_START;\n\t\treturn intersects( FRect_<FPT2>( pt1, pt2 ) ) ;\n\t}\n/// Line/FRect intersection\n\ttemplate<typename FPT2>\n\tdetail::Intersect<detail::Inters_2,FPT> intersects( const FRect_<FPT2>& rect ) const\n\t{\n\t\tHOMOG2D_START;\n\t\treturn impl_intersectsFRect( rect, detail::RootHelper<LP>() );\n\t}\n\n/// Line/Segment intersection\n/** \\warning no implementation for points */\n\ttemplate<typename FPT2>\n\tdetail::Intersect<detail::Inters_1,FPT> intersects( const Segment_<FPT2>& seg ) const\n\t{\n\t\tHOMOG2D_START;\n\t\treturn seg.intersects( *this );\n\t}\n\n/// Line/Circle intersection\n/** <br>The Sfinae below is needed to avoid ambiguity with the other 2 args function (with 2 points defining a FRect, see above) */\n\ttemplate<\n\t\ttypename T,\n\t\ttypename std::enable_if<\n\t\t\t(std::is_arithmetic<T>::value && !std::is_same<T,bool>::value)\n\t\t\t,T\n\t\t>::type* = nullptr\n\t>\n\tdetail::Intersect<detail::Inters_2,FPT> intersects( const Point2d_<FPT>& pt0, T radius ) const\n\t{\n\t\tHOMOG2D_START;\n\t\treturn impl_intersectsCircle( pt0, radius, detail::RootHelper<LP>() );\n\t}\n/// Line/Circle intersection\n\ttemplate<typename T>\n\tdetail::Intersect<detail::Inters_2,FPT> intersects( const Circle_<T>& cir ) const\n\t{\n\t\tHOMOG2D_START;\n\t\treturn impl_intersectsCircle( cir.center(), cir.radius(), detail::RootHelper<LP>() );\n\t}\n/// Line/Polyline intersection\n\ttemplate<typename FPT2>\n\tdetail::IntersectM<FPT> intersects( const Polyline_<FPT2>& pl ) const\n\t{\n\t\tHOMOG2D_START;\n\t\treturn pl.intersects( *this );\n\t}\n\n/// Point is inside flat rectangle\n\tbool isInside( const Point2d_<FPT>& pt1, const Point2d_<FPT>& pt2 ) const\n\t{\n\t\treturn impl_isInsideRect( FRect_<FPT>(pt1, pt2), detail::RootHelper<LP>() );\n\t}\n\n/// Point is inside FRect\n\ttemplate<typename FPT2>\n\tbool isInside( const FRect_<FPT2>& rect ) const\n\t{\n\t\treturn impl_isInsideRect( rect, detail::RootHelper<LP>() );\n\t}\n\n/// Point is inside circle\n\ttemplate<typename T>\n\tbool isInside( const Point2d_<FPT>& center, T radius ) const\n\t{\n\t\tHOMOG2D_CHECK_IS_NUMBER(T);\n\t\treturn impl_isInsideCircle( center, radius, detail::RootHelper<LP>() );\n\t}\n/// Point is inside Circle\n\ttemplate<typename T>\n\tbool isInside( Circle_<T> cir ) const\n\t{\n\t\tHOMOG2D_CHECK_IS_NUMBER(T);\n\t\treturn impl_isInsideCircle( cir.center(), cir.radius(), detail::RootHelper<type::IsPoint>() );\n\t}\n\n/// Point is inside Ellipse\n\ttemplate<typename FPT2>\n\tbool isInside( const Ellipse_<FPT2>& ell ) const\n\t{\n\t\treturn impl_isInsideEllipse( ell, detail::RootHelper<LP>() );\n\t}\n\n//////////////////////////\n//       OPERATORS      //\n//////////////////////////\n\tbool operator == ( const Root<LP,FPT>& other ) const\n\t{\n\t\treturn impl_op_equal( other, detail::RootHelper<LP>() );\n\t}\n\tbool operator != ( const Root<LP,FPT>& other ) const\n\t{\n\t\treturn !(*this == other);\n\t}\n\tbool operator < ( const Root<LP,FPT>& other ) const\n\t{\n\t\treturn impl_op_sort( other, detail::RootHelper<LP>() );\n\t}\n\n\ttemplate<typename T>\n\tbool draw( img::Image<T>& img, img::DrawParams dp=img::DrawParams() ) const;\n\n#ifdef HOMOG2D_USE_OPENCV\n\ttemplate<typename RT>\n\tRT getCvPt() const { return RT( getX(), getY() ); }\n\n\tcv::Point2i getCvPti() const { return impl_getCvPt( detail::RootHelper<LP>(), cv::Point2i() ); }\n\tcv::Point2d getCvPtd() const { return impl_getCvPt( detail::RootHelper<LP>(), cv::Point2d() ); }\n\tcv::Point2f getCvPtf() const { return impl_getCvPt( detail::RootHelper<LP>(), cv::Point2f() ); }\n\n/// Constructor: build from a single OpenCv point.\n\ttemplate<typename T>\n\tRoot( cv::Point_<T> pt )\n\t{\n\t\timpl_init_opencv( pt, detail::RootHelper<LP>() );\n\t}\n#endif // HOMOG2D_USE_OPENCV\n\n\tstatic HOMOG2D_INUMTYPE& nullAngleValue()     { return _zeroAngleValue; }\n\tstatic HOMOG2D_INUMTYPE& nullDistance()       { return _zeroDistance; }\n\tstatic HOMOG2D_INUMTYPE& nullOffsetValue()    { return _zeroOffset; }\n\tstatic HOMOG2D_INUMTYPE& nullOrthogDistance() { return _zeroOrthoDistance; }\n\tstatic HOMOG2D_INUMTYPE& nullDenom()          { return _zeroDenom; }\n\n//////////////////////////\n//      DATA SECTION    //\n//////////////////////////\n\nprivate:\n\tstd::array<FPT,3> _v; ///< data, uses the template parameter FPT (for \"Floating Point Type\")\n\n\tstatic HOMOG2D_INUMTYPE _zeroAngleValue;       /// Used in isParallel();\n\tstatic HOMOG2D_INUMTYPE _zeroDistance;         /// Used to define points as identical\n\tstatic HOMOG2D_INUMTYPE _zeroOffset;           /// Used to compare lines\n\tstatic HOMOG2D_INUMTYPE _zeroOrthoDistance;    /// Used to check for different points on a flat rectangle, see Root::getCorrectPoints()\n\tstatic HOMOG2D_INUMTYPE _zeroDenom;            /// Used to check for null denominator\n\n//////////////////////////\n//   PRIVATE FUNCTIONS  //\n//////////////////////////\nprivate:\n\tvoid p_normalizeLine() const { impl_normalizeLine( detail::RootHelper<LP>() ); }\n\n\ttemplate<typename FPT2>\n\tdetail::Intersect<detail::Inters_2,FPT>\n\timpl_intersectsFRect( const FRect_<FPT2>& rect, const detail::RootHelper<type::IsLine>& ) const;\n\n\ttemplate<typename FPT2>\n\tdetail::Intersect<detail::Inters_2,FPT>\n\timpl_intersectsFRect( const FRect_<FPT2>& rect, const detail::RootHelper<type::IsPoint>& ) const;\n\n\ttemplate<typename T>\n\tdetail::Intersect<detail::Inters_2,FPT>\n\timpl_intersectsCircle( const Point2d_<FPT>& pt, T radius, const detail::RootHelper<type::IsLine>& ) const;\n\n\ttemplate<typename T>\n\tdetail::Intersect<detail::Inters_2,FPT>\n\timpl_intersectsCircle( const Point2d_<FPT>& pt, T radius, const detail::RootHelper<type::IsPoint>& ) const;\n\n/*\t\ttemplate<typename FPT2>\n\tdetail::IntersectM<FPT>\n\timpl_intersectsPolyline( const Polyline_<FPT2>& pl, const detail::RootHelper<type::IsLine>& ) const;\n\ttemplate<typename FPT2>\n\tdetail::IntersectM<FPT>\n\timpl_intersectsPolyline( const Polyline_<FPT2>& pl, const detail::RootHelper<type::IsPoint>& ) const;\n*/\n\ttemplate<typename FPT2>\n\tbool impl_isInsideRect( const FRect_<FPT2>&, const detail::RootHelper<type::IsPoint>& ) const;\n\ttemplate<typename FPT2>\n\tbool impl_isInsideRect( const FRect_<FPT2>&, const detail::RootHelper<type::IsLine>&  ) const;\n\n\ttemplate<typename FPT2>\n\tbool impl_isInsideEllipse( const Ellipse_<FPT2>&, const detail::RootHelper<type::IsPoint>& ) const;\n\ttemplate<typename FPT2>\n\tbool impl_isInsideEllipse( const Ellipse_<FPT2>&, const detail::RootHelper<type::IsLine>& ) const;\n\n\ttemplate<typename T>\n\tbool impl_isInsideCircle( const Point2d_<FPT>&, T radius, const detail::RootHelper<type::IsLine>&  ) const;\n\ttemplate<typename T>\n\tbool impl_isInsideCircle( const Point2d_<FPT>&, T radius, const detail::RootHelper<type::IsPoint>& ) const;\n\n\tvoid impl_normalizeLine( const detail::RootHelper<type::IsLine>& ) const;\n\n\tLine2d_<FPT> impl_getOrthogonalLine_A( GivenCoord gc, FPT val, const detail::RootHelper<type::IsLine>&  ) const;\n\tLine2d_<FPT> impl_getOrthogonalLine_A( GivenCoord gc, FPT val, const detail::RootHelper<type::IsPoint>& ) const;\n\tLine2d_<FPT> impl_getOrthogonalLine_B( const Point2d_<FPT>&,   const detail::RootHelper<type::IsLine>&  ) const;\n\tLine2d_<FPT> impl_getOrthogonalLine_B( const Point2d_<FPT>&,   const detail::RootHelper<type::IsPoint>& ) const;\n\tLine2d_<FPT> impl_getParallelLine( const Point2d_<FPT>&, const detail::RootHelper<type::IsLine>&  ) const;\n\tLine2d_<FPT> impl_getParallelLine( const Point2d_<FPT>&, const detail::RootHelper<type::IsPoint>& ) const;\n\n\ttemplate<typename T>\n\tstd::pair<Line2d_<FPT>,Line2d_<FPT>> impl_getParallelLines( T, const detail::RootHelper<type::IsLine>&  ) const;\n\ttemplate<typename T>\n\tstd::pair<Line2d_<FPT>,Line2d_<FPT>> impl_getParallelLines( T, const detail::RootHelper<type::IsPoint>& ) const;\n\n\tbool impl_op_equal( const Root<LP,FPT>&, const detail::RootHelper<type::IsLine>&  ) const;\n\tbool impl_op_equal( const Root<LP,FPT>&, const detail::RootHelper<type::IsPoint>& ) const;\n\n\tbool impl_op_sort( const Root<LP,FPT>&, const detail::RootHelper<type::IsLine>&  ) const;\n\tbool impl_op_sort( const Root<LP,FPT>&, const detail::RootHelper<type::IsPoint>& ) const;\n\n\tPoint2d_<FPT> impl_op_product( const Line2d_<FPT>& , const Line2d_<FPT>& , const detail::RootHelper<type::IsPoint>& ) const;\n\tLine2d_<FPT>  impl_op_product( const Point2d_<FPT>&, const Point2d_<FPT>&, const detail::RootHelper<type::IsLine>&  ) const;\n\n#ifdef HOMOG2D_USE_OPENCV\n\ttemplate<typename OPENCVT>\n\tOPENCVT impl_getCvPt( const detail::RootHelper<type::IsPoint>&, const OPENCVT& ) const;\n\n/// Build point from Opencv point\n\ttemplate<typename T>\n\tvoid impl_init_opencv( cv::Point_<T> pt, const detail::RootHelper<type::IsPoint>& )\n\t{\n\t\timpl_init_2( pt.x, pt.y, detail::RootHelper<type::IsPoint>() );\n\t}\n/// Build line from Opencv point\n\ttemplate<typename T>\n\tvoid impl_init_opencv( cv::Point_<T> pt, const detail::RootHelper<type::IsLine>& )\n\t{\n\t\tPoint2d_<FPT> p(pt);\n\t\timpl_init_1_Point<FPT>( p, detail::RootHelper<type::IsLine>() );\n\t}\n#endif // HOMOG2D_USE_OPENCV\n\n\ttemplate<typename T>\n\tbool impl_draw( img::Image<T>& img, img::DrawParams dp, const detail::RootHelper<type::IsPoint>& ) const;\n\ttemplate<typename T>\n\tbool impl_draw( img::Image<T>& img, img::DrawParams dp, const detail::RootHelper<type::IsLine>& ) const;\n\n\t/// Called by default constructor, overload for lines\n\tvoid impl_init( const detail::RootHelper<type::IsLine>& )\n\t{\n\t\t_v[0] = 1.;\n\t\t_v[1] = 0.;\n\t\t_v[2] = 0.;\n\t}\n\t/// Called by default constructor, overload for points. Initialize to (0,0)\n\tvoid impl_init( const detail::RootHelper<type::IsPoint>& )\n\t{\n\t\t_v[0] = 0.;\n\t\t_v[1] = 0.;\n\t\t_v[2] = 1.;\n\t}\n\ttemplate<typename T1,typename T2>\n\tvoid impl_init_2( const T1&, const T2&, const detail::RootHelper<type::IsPoint>& );\n\ttemplate<typename T1,typename T2>\n\tvoid impl_init_2( const T1&, const T2&, const detail::RootHelper<type::IsLine>& );\n\n}; // class Root\n\n/////////////////////////////////////////////////////////////////////////////\n// SECTION  - INSTANCIATION OF STATIC VARIABLES\n/////////////////////////////////////////////////////////////////////////////\n\ntemplate<typename LP,typename FPT>\nHOMOG2D_INUMTYPE Root<LP,FPT>::_zeroAngleValue = 0.001; // 1 thousand of a radian (tan = 0.001 too)\n\ntemplate<typename LP,typename FPT>\nHOMOG2D_INUMTYPE Root<LP,FPT>::_zeroDistance = 1E-8;\n\ntemplate<typename LP,typename FPT>\nHOMOG2D_INUMTYPE Root<LP,FPT>::_zeroOrthoDistance = 1E-18;\n\ntemplate<typename LP,typename FPT>\nHOMOG2D_INUMTYPE Root<LP,FPT>::_zeroDenom = 1E-10;\n\ntemplate<typename LP,typename FPT>\nHOMOG2D_INUMTYPE Root<LP,FPT>::_zeroOffset = 1E-15;\n\ntemplate<typename FPT>\nHOMOG2D_INUMTYPE detail::Matrix_<FPT>::_zeroDeterminantValue = 1E-20;\ntemplate<typename FPT>\nHOMOG2D_INUMTYPE detail::Matrix_<FPT>::_zeroDenomValue = 1E-15;\n\n\n/////////////////////////////////////////////////////////////////////////////\n// SECTION  - OPENCV API CODE\n/////////////////////////////////////////////////////////////////////////////\n\n#ifdef HOMOG2D_USE_OPENCV\ntemplate<typename FPT>\nFRect_<FPT> getFRect( cv::Mat& mat )\n{\n\tif(  mat.cols == 0 || mat.rows == 0 )\n\t\tHOMOG2D_THROW_ERROR_1(\n\t\t\t\"Illegal values: cols=\" << mat.cols << \", rows=\" << mat.rows\n\t\t);\n\n\treturn FRect_<FPT>(\n\t\tPoint2d_<FPT>(),                      // (0,0)\n\t\tPoint2d_<FPT>( mat.cols, mat.rows )   // (w,h)\n\t);\n}\n\n/// Free function to return an OpenCv point\n/**\n- RT: return type\n- FPT: Floating Point Type\n\nUser code needs to provide the requested type as template argument:\n\\code\nauto p1 = getCvPt<cv::Point2di>( pt );\nauto p2 = getCvPt<cv::Point2df>( pt );\nauto p3 = getCvPt<cv::Point2dd>( pt );\n\\endcode\n*/\ntemplate<typename RT,typename FPT>\nRT\ngetCvPt( const Point2d_<FPT>& pt )\n{\n\treturn pt.template getCvPt<RT>();\n}\n\n/// Free function to return an OpenCv point (double)\ntemplate<typename FPT>\ncv::Point2d\ngetCvPtd( const Point2d_<FPT>& pt )\n{\n\treturn pt.getCvPtd();\n}\n/// Free function to return an OpenCv point (float)\ntemplate<typename FPT>\ncv::Point2f\ngetCvPtf( const Point2d_<FPT>& pt )\n{\n\treturn pt.getCvPtf();\n}\n/// Free function to return an OpenCv point (integer)\ntemplate<typename FPT>\ncv::Point2i\ngetCvPti( const Point2d_<FPT>& pt )\n{\n\treturn pt.getCvPti();\n}\n\n/// Free function, returns a vector of OpenCv points from a vector of points\n/**\n- RT: return type\n- FPT: Floating Point Type\n\nUser code needs to provide the requested type as template argument:\n\\code\nauto v1 = getCvPts<cv::Point2di>( myvec );\nauto v2 = getCvPts<cv::Point2df>( myvec );\nauto v3 = getCvPts<cv::Point2dd>( myvec );\n\\endcode\n*/\ntemplate<typename RT,typename FPT>\nstd::vector<RT>\ngetCvPts( const std::vector<Point2d_<FPT>>& vpt )\n{\n\tstd::vector<RT> vout( vpt.size() );\n\tauto it = vout.begin();\n\tfor( const auto& pt: vpt )\n\t\t*it++ = getCvPt<RT>(pt);\n\treturn vout;\n}\n#endif // HOMOG2D_USE_OPENCV\n\n\n//------------------------------------------------------------------\n/// This namespace holds some private stuff\nnamespace detail {\n\n//------------------------------------------------------------------\n/// Private free function, returns true if point \\c pt is inside the rectangle defined by (\\c p00 , \\c p11)\ntemplate<typename FPT1,typename FPT2>\nbool\nptIsInside( const Point2d_<FPT1>& pt, const Point2d_<FPT2>& p00, const Point2d_<FPT2>& p11 )\n{\n//\tif( pt.getX() >= p00.getX() && pt.getX() <= p11.getX() )\n//\t\tif( pt.getY() >= p00.getY() && pt.getY() <= p11.getY() )\n\tif( pt.getX() > p00.getX() && pt.getX() < p11.getX() )\n\t\tif( pt.getY() > p00.getY() && pt.getY() < p11.getY() )\n\t\t\treturn true;\n\treturn false;\n}\n\n\n#ifdef HOMOG2D_USE_EIGEN\n///  Build Homography from 2 sets of 4 points, using Eigen\n/**\nSee\n- https://eigen.tuxfamily.org/dox/group__TutorialLinearAlgebra.html\n- https://eigen.tuxfamily.org/dox/group__DenseMatrixManipulation__chapter.html\n*/\ntemplate<typename FPT>\nHomogr_<FPT>\nbuildFrom4Points_Eigen(\n\tconst std::vector<Point2d_<FPT>>& vpt1, ///< source points\n\tconst std::vector<Point2d_<FPT>>& vpt2  ///< destination points\n)\n{\n\tEigen::MatrixXd A = Eigen::MatrixXd::Zero(8,8);\n\tEigen::VectorXd b(8);\n\n\tfor( int i=0; i<4; i++ )\n\t{\n\t\tauto u1 = vpt1[i].getX();\n\t\tauto v1 = vpt1[i].getY();\n\t\tauto u2 = vpt2[i].getX();\n\t\tauto v2 = vpt2[i].getY();\n\n\t\tb(2*i)   = u2;\n\t\tb(2*i+1) = v2;\n\n\t\tA(i*2,0) = A(i*2+1,3) = u1;\n\t\tA(i*2,1) = A(i*2+1,4) = v1;\n\t\tA(i*2,2) = A(i*2+1,5) = 1.;\n\n\t\tA(i*2,6)   = - u1 * u2;\n\t\tA(i*2,7)   = - v1 * u2;\n\t\tA(i*2+1,6) = - u1 * v2;\n\t\tA(i*2+1,7) = - v1 * v2;\n\t}\n\n\n#if 0\n\tEigen::VectorXd X = A.ldlt().solve(b); // for some reason this does not work...\n#else\n\tEigen::MatrixXd Ai = A.inverse();\n\tEigen::VectorXd X = Ai * b;\n#endif\n\n\tHomogr_<FPT> H;\n\tfor( int i=0; i<8; i++ )\n\t\tH.set( i/3, i%3, X(i) );\n\tH.set(2, 2, 1.);\n\n\treturn H;\n}\n#endif\n\n//------------------------------------------------------------------\n#ifdef HOMOG2D_USE_OPENCV\n///  Build Homography from 2 sets of 4 points, using Opencv\n/**\n- see https://docs.opencv.org/master/d9/d0c/group__calib3d.html#ga4abc2ece9fab9398f2e560d53c8c9780\n\n\\note With current Opencv installed on current machine, it seems that \\c cv::getPerspectiveTransform()\nrequires that the points are \"CV_32F\" (\\c float), and NOT double.\n*/\ntemplate<typename FPT>\nHomogr_<FPT>\nbuildFrom4Points_Opencv (\n\tconst std::vector<Point2d_<FPT>>& vpt1, ///< source points\n\tconst std::vector<Point2d_<FPT>>& vpt2  ///< destination points\n)\n{\n\tconst auto& src = getCvPts<cv::Point2f>( vpt1 );\n\tconst auto& dst = getCvPts<cv::Point2f>( vpt2 );\n\treturn cv::getPerspectiveTransform( src, dst ); // automatic type conversion to Hmatrix_\n}\n#endif\n\n} // namespace detail\n\n//------------------------------------------------------------------\n/// Build Homography from 2 sets of 4 points (free function)\ntemplate<typename FPT>\nHomogr_<FPT>\nbuildFrom4Points(\n\tconst std::vector<Point2d_<FPT>>& vpt1,     ///< source points\n\tconst std::vector<Point2d_<FPT>>& vpt2,     ///< destination points\n\tint                               method=1  ///< 0: Eigen, 1: Opencv\n)\n{\n\tHomogr_<FPT> H;\n\tH.buildFrom4Points( vpt1, vpt2, method );\n\treturn H;\n}\n\n//------------------------------------------------------------------\n/// Build Homography from 2 sets of 4 points\n/**\n- Requires either Eigen or Opencv\n- we build a 8x8 matrix A and a 8x1 vector B, and get the solution from X = A^-1 B\n- see this for details:\nhttps://skramm.lautre.net/files/misc/Kramm_compute_H_from_4pts.pdf\n\n\\sa free function: h2d::buildFrom4Points()\n\n\\todo fix this so that user can provide a std::array of points\n*/\ntemplate<typename M,typename FPT>\nvoid\nHmatrix_<M,FPT>::buildFrom4Points(\n\tconst std::vector<Point2d_<FPT>>& vpt1,   ///< source points\n\tconst std::vector<Point2d_<FPT>>& vpt2,   ///< destination points\n\tint                               method  ///< 0: Eigen, 1: Opencv (default)\n)\n{\n\tif( vpt1.size() != 4 )\n\t\tHOMOG2D_THROW_ERROR_1( \"invalid vector size for source points, should be 4, value=\" << vpt1.size() );\n\tif( vpt2.size() != 4 )\n\t\tHOMOG2D_THROW_ERROR_1( \"invalid vector size for dest points, should be 4, value=\" << vpt2.size() );\n\tassert( method == 0 || method == 1 );\n\n\tif( method == 0 )\n\t{\n#ifdef HOMOG2D_USE_EIGEN\n\t\t*this = detail::buildFrom4Points_Eigen( vpt1, vpt2 );\n#else\n\t\tthrow std::runtime_error( \"Unable, build without Eigen support\" );\n#endif\n\t}\n\telse\n\t{\n#ifdef HOMOG2D_USE_OPENCV\n\t\t*this = detail::buildFrom4Points_Opencv( vpt1, vpt2 );\n#else\n\t\tthrow std::runtime_error( \"Unable, build without Opencv support\" );\n#endif\n\t}\n}\n\n//------------------------------------------------------------------\n/// A line segment, defined by two points\n/**\n- Storage: \"smallest\" point is always stored as first element (see constructor)\n*/\ntemplate<typename FPT>\nclass Segment_\n{\npublic:\n\tusing FType = FPT;\n\n\ttemplate<typename T> friend class Segment_;\n\nprivate:\n\tPoint2d_<FPT> _ptS1, _ptS2;\n\npublic:\n/// \\name Constructors\n///@{\n\n/// Default constructor: initializes segment to (0,0)--(1,1)\n\tSegment_(): _ptS2(1.,1.)\n\t{}\n/// Contructor 2: build segment from two points\n\tSegment_( Point2d_<FPT> p1, Point2d_<FPT> p2 )\n\t\t: _ptS1(p1), _ptS2(p2)\n\t{\n#ifndef HOMOG2D_NOCHECKS\n\t\tif( p1 == p2 )\n\t\t\tHOMOG2D_THROW_ERROR_1( \"cannot build a segment with two identical points: \" << p1 << \" and \" << p2 );\n#endif\n\t\tpriv::fix_order( _ptS1, _ptS2 );\n\t}\n\n/// Contructor 3: build segment from two points coordinates, call constructor 2\n\ttemplate<typename T>\n\tSegment_( T x1, T y1, T x2, T y2 )\n\t\t: Segment_( Point2d_<FPT>(x1,y1), Point2d_<FPT>(x2,y2) )\n\t{\n\t\tHOMOG2D_CHECK_IS_NUMBER(T);\n\t}\n\n/// Copy-Constructor\n\ttemplate<typename FPT2>\n\tSegment_( const Segment_<FPT2>& other )\n\t\t: _ptS1(other._ptS1), _ptS2(other._ptS2)\n\t{}\n///@}\n\n/// Setter\n\tvoid set( const Point2d_<FPT>& p1, const Point2d_<FPT>& p2 )\n\t{\n#ifndef HOMOG2D_NOCHECKS\n\t\tif( p1 == p2 )\n\t\t\tHOMOG2D_THROW_ERROR_1( \"cannot define a segment with two identical points\" << p1 << \" and \" << p2 );\n#endif\n\t\t_ptS1 = p1;\n\t\t_ptS2 = p2;\n\t\tpriv::fix_order( _ptS1, _ptS2 );\n\t}\n\n/// \\name Attributes access\n///@{\n\n/// Get segment length\n\tHOMOG2D_INUMTYPE length() const\n\t{\n\t\treturn _ptS1.distTo( _ptS2 );\n\t}\n\n/// Returns Bounding Box\n\tFRect_<FPT> getBB() const\n\t{\n\t\treturn FRect_<FPT>(\t_ptS1. _ptS2 );\n\t}\n\n/// Get angle between segment and other segment/line\n\ttemplate<typename U>\n\tHOMOG2D_INUMTYPE getAngle( const U& other ) const\n\t{\n\t\treturn other.getAngle( this->getLine() );\n\t}\n///@}\n\n/// \\name Operators\n///@{\n\tbool operator == ( const Segment_& s2 ) const\n\t{\n\t\tif( _ptS1 != s2._ptS1 )\n\t\t\treturn false;\n\t\tif( _ptS2 != s2._ptS2 )\n\t\t\treturn false;\n\t\treturn true;\n\t}\n\tbool operator != ( const Segment_& s2 ) const\n\t{\n\t\treturn !(*this == s2);\n\t}\n///@}\n\n/// Returns the points as a std::pair\n/** The one with smallest x coordinate will be returned as \"first\". If x-coordinate are equal, then\nthe one with smallest y-coordinate will be returned first */\n\tstd::pair<Point2d_<FPT>,Point2d_<FPT>>\n\tgetPts() const\n\t{\n\t\treturn std::make_pair( _ptS1, _ptS2 );\n\t}\n\n/// Segment \"isInside\", S can be Circle or FRect\n\ttemplate<typename S>\n\tbool isInside( const S& shape ) const\n\t{\n\t\tif( !_ptS1.isInside( shape ) )\n\t\t\treturn false;\n\t\tif( !_ptS2.isInside( shape ) )\n\t\t\treturn false;\n\t\treturn true;\n\t}\n\n/// Returns supporting line\n\tLine2d_<FPT> getLine() const\n\t{\n\t\treturn _ptS1 * _ptS2;\n\t}\n\n/// \\name Intersection functions\n///@{\n\ttemplate<typename FPT2>\n\tdetail::Intersect<detail::Inters_1,FPT> intersects( const Segment_<FPT2>& ) const;\n\ttemplate<typename FPT2>\n\tdetail::Intersect<detail::Inters_1,FPT> intersects( const Line2d_<FPT2>&  ) const;\n\ttemplate<typename FPT2>\n\tdetail::IntersectM<FPT>                 intersects( const Circle_<FPT2>&  ) const;\n/// Segment/FRect intersection\n\ttemplate<typename FPT2>\n\tdetail::IntersectM<FPT> intersects( const FRect_<FPT2>& r ) const\n\t{\n\t\tHOMOG2D_START;\n\t\treturn r.intersects( *this );\n\t}\n\n/// Segment/Polyline intersection\n\ttemplate<typename FPT2>\n\tdetail::IntersectM<FPT> intersects( const Polyline_<FPT2>& other ) const\n\t{\n\t\tHOMOG2D_START;\n\t\treturn other.intersects( *this );\n\t}\n///@}\n\n\ttemplate<typename T>\n\tbool isParallelTo( const T& other ) const\n\t{\n\t\tstatic_assert(\n\t\t\tstd::is_same<T,Segment_<FPT>>::value ||\n\t\t\tstd::is_same<T,Line2d_<FPT>>::value,\n\t\t\t\"type needs to be a segment or a line\" );\n\t\treturn getLine().isParallelTo( other );\n\t}\n\n\t/// Returns point that at middle distance between \\c p1 and \\c p2\n\tPoint2d_<FPT>\n\tgetMiddlePoint() const\n\t{\n\t\treturn Point2d_<FPT>(\n\t\t\t( _ptS1.getX() + _ptS2.getX() ) / 2.,\n\t\t\t( _ptS1.getY() + _ptS2.getY() ) / 2.\n\t\t);\n\t}\n\n\ttemplate<typename T>\n\tvoid draw( img::Image<T>&, img::DrawParams dp=img::DrawParams() ) const;\n\n\ttemplate<typename T>\n\tfriend std::ostream&\n\toperator << ( std::ostream& f, const Segment_<T>& seg );\n\n}; // class Segment_\n\n\n/// Circle/Circle intersection\n/**\nRef:\n- https://stackoverflow.com/questions/3349125/\n\n\\todo benchmark the two approaches below\n*/\ntemplate<typename FPT>\ntemplate<typename FPT2>\ndetail::Intersect<detail::Inters_2,FPT>\nCircle_<FPT>::intersects( const Circle_<FPT2>& other ) const\n{\n\tHOMOG2D_START;\n\n\tif( *this == other )\n\t\treturn detail::Intersect<detail::Inters_2,FPT>();\n\n\tHOMOG2D_INUMTYPE r1 = _radius;\n\tHOMOG2D_INUMTYPE r2 = other._radius;\n\tPoint2d_<HOMOG2D_INUMTYPE> pt1 = _center;\n\tPoint2d_<HOMOG2D_INUMTYPE> pt2 = other._center;\n\n#if 0\n\tHOMOG2D_INUMTYPE d  = _center.distTo( other._center );\n\tif( d > r1 + r2 )                                     // no intersection\n\t\treturn detail::Intersect<detail::Inters_2,FPT>();\n\n\tif( d < std::abs( r1 - r2 ) )                         // no intersection: one circle inside the other\n\t\treturn detail::Intersect<detail::Inters_2,FPT>();\n\tauto a = (r1*r1 - r2*r2 + d*d) / 2. / d;\n#else\n\tHOMOG2D_INUMTYPE x1 = pt1.getX();\n\tHOMOG2D_INUMTYPE y1 = pt1.getY();\n\tHOMOG2D_INUMTYPE x2 = pt2.getX();\n\tHOMOG2D_INUMTYPE y2 = pt2.getY();\n\tHOMOG2D_INUMTYPE d_squared = (x1-x2)*(x1-x2) + (y1-y2)*(y1-y2);\n\n\tif( d_squared > r1*r1 + r2*r2 + 2.*r1*r2 )              // no intersection\n\t\treturn detail::Intersect<detail::Inters_2,FPT>();\n\n\tif( d_squared < ( r1*r1 + r2*r2 - 2.*r1*r2 ) )          // no intersection: one circle inside the other\n\t\treturn detail::Intersect<detail::Inters_2,FPT>();\n\n\tauto d = std::sqrt( d_squared );\n\tauto a = (r1*r1 - r2*r2 + d_squared) / 2. / d;\n#endif\n\n\tauto h = std::sqrt( r1*r1 - a*a );\n\n\tPoint2d_<FPT> P0(\n\t\t( pt2.getX() - pt1.getX() ) * a / d + pt1.getX(),\n\t\t( pt2.getY() - pt1.getY() ) * a / d + pt1.getY()\n\t);\n\n\tPoint2d_<FPT> pt3(\n\t\tP0.getX() + h*( pt1.getY() - pt2.getY() ) / d,\n\t\tP0.getY() - h*( pt1.getX() - pt2.getX() ) / d\n\t);\n\tPoint2d_<FPT> pt4(\n\t\tP0.getX() - h*( pt1.getY() - pt2.getY() ) / d,\n\t\tP0.getY() + h*( pt1.getX() - pt2.getX() ) / d\n\t);\n\treturn detail::Intersect<detail::Inters_2,FPT>( pt3, pt4 );\n}\n\n//------------------------------------------------------------------\nnamespace priv {\n\n/// Traits class, used in intersects() for Polyline\ntemplate<typename T> struct IsShape              : std::false_type {};\ntemplate<typename T> struct IsShape<Circle_<T>>  : std::true_type  {};\ntemplate<typename T> struct IsShape<FRect_<T>>   : std::true_type  {};\ntemplate<typename T> struct IsShape<Segment_<T>> : std::true_type  {};\ntemplate<typename T> struct IsShape<Line2d_<T>>  : std::true_type  {};\ntemplate<typename T> struct IsShape<Polyline_<T>>: std::true_type  {};\n//template<typename T> struct IsShape<Ellipse_<T>>:  std::true_type  {};\n\n/// Traits class used in operator * ( const Hmatrix_<type::IsHomogr,FPT>& h, const Cont& vin ),\n/// used to detect if container is valid\ntemplate <typename T>               struct Is_Container: std::false_type { };\ntemplate <typename T,std::size_t N> struct Is_Container<std::array<T,N>>:     std::true_type { };\ntemplate <typename... Ts>           struct Is_Container<std::vector<Ts...>> : std::true_type { };\ntemplate <typename... Ts>           struct Is_Container<std::list<Ts...  >> : std::true_type { };\n\n/// Traits class used to detect if container \\c T is a \\c std::array\n/** (because allocation is different, see \\ref alloc() ) */\ntemplate <typename T>\nstruct Is_std_array: std::false_type {};\ntemplate <typename V, size_t n>\nstruct Is_std_array<std::array<V, n>>: std::true_type {};\n\n\n//------------------------------------------------------------------\n/// A value that needs some computing, associated with its flag\ntemplate<typename T>\nclass ValueFlag\n{\nprivate:\n\tT    _value;\n\tbool _valIsCorrect = false;\npublic:\n\tvoid set( T v )\n\t{\n\t\t_value = v;\n\t\t_valIsCorrect = true;\n\t}\n\tT value() const    { return _value; }\n\tvoid setBad()      { _valIsCorrect = false; }\n\tbool isBad() const { return !_valIsCorrect; }\n};\n\n\n//------------------------------------------------------------------\n/// Holds attribute of a Polyline, allows storage of last computed value, through the use of ValueFlag\nstruct PolylineAttribs\n{\n\tpriv::ValueFlag<HOMOG2D_INUMTYPE> _length;\n\tpriv::ValueFlag<HOMOG2D_INUMTYPE> _area;\n\tpriv::ValueFlag<bool>             _isPolygon;\n\tvoid setBad()\n\t{\n\t\t_length.setBad();\n\t\t_area.setBad();\n\t\t_isPolygon.setBad();\n\t}\n};\n\n} // namespace priv\n\n//------------------------------------------------------------------\n/// Polyline, can be closed or not\n/**\n\\warning When closed, In order to be able to compare two objects describing the same structure\nbut potentially in different order, the comparison operator will proceed a sorting.<br>\nThe consequence is that when adding points, if you have done a comparison before, you might not\nadd point after the one you thought!\n*/\ntemplate<typename FPT>\nclass Polyline_\n{\n\ttemplate<typename T> friend class Polyline_;\n\nprivate:\n\tmutable std::vector<Point2d_<FPT>> _plinevec;\n\tbool _isClosed = false;\n\tmutable bool _plIsNormalized = false;\n\tmutable priv::PolylineAttribs _attribs;    ///< Attributes. Will get stored upon computing.\n\npublic:\n/// \\name Constructors\n///@{\n\n/// Default constructor\n\tPolyline_( IsClosed ic=IsClosed::No )\n\t{\n\t\tif( ic == IsClosed::Yes )\n\t\t\t_isClosed = true;\n\t}\n/// Constructor for single point\n\ttemplate<typename FPT2>\n\tPolyline_( const Point2d_<FPT2>& pt, IsClosed ic=IsClosed::No )\n\t{\n\t\t_plinevec.push_back( pt );\n\t\tif( ic == IsClosed::Yes )\n\t\t\t_isClosed = true;\n\t}\n/// Constructor for single point as x,y\n\ttemplate<typename FPT2>\n\tPolyline_( FPT2 x, FPT2 y, IsClosed ic = IsClosed::No )\n\t\t: Polyline_(Point2d_<FPT>(x,y), ic )\n\t{}\n\n/// Constructor from FRect. Default behavior is closed\n\ttemplate<typename FPT2>\n\tPolyline_( const FRect_<FPT2>& rect, IsClosed ic=IsClosed::Yes )\n\t{\n\t\tfor( const auto& pt: rect.get4Pts() )\n\t\t\t_plinevec.push_back( pt );\n\t\t_isClosed = ( ic == IsClosed::Yes ? true : false );\n\t}\n\n/// Constructor from a vector of points. Default: Open\n\ttemplate<typename FPT2>\n\tPolyline_( const std::vector<Point2d_<FPT2>>& vec, IsClosed ic=IsClosed::No )\n\t{\n\t\tset( vec );\n\t\t_isClosed = ( ic == IsClosed::Yes ? true : false );\n\t}\n\n/// Copy-Constructor\n/** Can't use standard initialization, because vector might have different types */\n\ttemplate<typename FPT2>\n\tPolyline_( const Polyline_<FPT2>& other )\n\t\t: _isClosed(other._isClosed)\n\t{\n\t\tset( other._plinevec );\n\t}\n///@}\n\n/// \\name Attributes access\n///@{\n\n/// Returns the number of points\n\tsize_t size() const { return _plinevec.size(); }\n\n\tHOMOG2D_INUMTYPE length()    const;\n\tHOMOG2D_INUMTYPE area()      const;\n\tbool             isPolygon() const;\n\tFRect_<FPT>      getBB()     const;\n\n/// Returns the number of segments\n\tsize_t nbSegs() const\n\t{\n\t\tif( size() == 0 )\n\t\t\treturn 0;\n\t\tif( size() < 3 )     // if 1 or 2, then 0 or 1 segment\n\t\t\treturn size() - 1;\n\t\treturn size() - 1 + (size_t)_isClosed;\n\t}\n\n\tconst bool& isClosed() const { return _isClosed; }\n\tbool&       isClosed()       { _attribs.setBad(); return _isClosed; }\n///@}\n\n/// \\name Data access\n///@{\n\n/// Returns the points (reference)\n\tstd::vector<Point2d_<FPT>>& getPts()\n\t{\n\t\t_attribs.setBad();  // because we send the non-const reference\n\t\t_plIsNormalized=false;\n\t\treturn _plinevec;\n\t}\n/// Returns the points (const reference)\n\tconst std::vector<Point2d_<FPT>>& getPts() const\n\t{\n\t\treturn _plinevec;\n\t}\n\n/// Returns the segments of the polyline\n\tstd::vector<Segment_<FPT>> getSegs() const\n\t{\n\t\tstd::vector<Segment_<FPT>> out;\n\t\tif( size() < 2 ) // nothing to draw\n\t\t\treturn out;\n\n\t\tfor( size_t i=0; i<size()-1; i++ )\n\t\t{\n\t\t\tconst auto& pt1 = _plinevec[i];\n\t\t\tconst auto& pt2 = _plinevec[i+1];\n\t\t\tout.push_back( Segment_<FPT>( pt1,pt2) );\n\t\t}\n\t\tif( _isClosed )\n\t\t\tout.push_back( Segment_<FPT>(_plinevec.front(),_plinevec.back() ) );\n\t\treturn out;\n\t}\n\n\n/// Returns one point of the polyline.\n\tPoint2d_<FPT> getPoint( size_t idx ) const\n\t{\n#ifndef HOMOG2D_NOCHECKS\n\t\tif( idx >= size() )\n\t\t\tHOMOG2D_THROW_ERROR_1( \"requesting point \" << idx\n\t\t\t\t<< \", only has \"  << size()\n\t\t\t);\n#endif\n\t\treturn _plinevec[idx];\n\t}\n\n/// Returns one segment of the polyline.\n/**\nSegment \\c n is the one between point \\c n and point \\c n+1\n*/\n\tSegment_<FPT> getSegment( size_t idx ) const\n\t{\n#ifndef HOMOG2D_NOCHECKS\n\t\tif( idx >= nbSegs() )\n\t\t\tHOMOG2D_THROW_ERROR_1( \"requesting segment \" << idx\n\t\t\t\t<< \", only has \"  << nbSegs()\n\t\t\t);\n\n\t\tif( size() < 2 ) // nothing to draw\n\t\t\tHOMOG2D_THROW_ERROR_1( \"no segment \" << idx );\n#endif\n//\t\t\tauto lastPoint = _isClosed?\n\t\treturn Segment_<FPT>(\n\t\t\t_plinevec[idx],\n\t\t\t_plinevec[idx+1==nbSegs()&&_isClosed?0:idx+1]\n\t\t);\n\t}\n\n/// Clear all\n\tvoid clear()\n\t{\n\t\t_plinevec.clear();\n\t\t_plIsNormalized=false;\n\t\t_attribs.setBad();\n\t}\n\n\ttemplate<typename T1,typename T2>\n\tvoid translate( T1 dx, T2 dy )\n\t{\n\t\tHOMOG2D_CHECK_IS_NUMBER( T1 );\n\t\tHOMOG2D_CHECK_IS_NUMBER( T2 );\n\t\tfor( auto& pt: _plinevec )\n\t\t\tpt.translate( dx, dy );\n\t}\n\n/// Add single point as x,y\n/**\n\\warning this will add the new point after the previous one \\b only if the object has \\b not\nbeen normalized. This normalizing operation will happen if you a comparison (== or !=)\n*/\n\ttemplate<typename FPT1,typename FPT2>\n\tvoid add( FPT1 x, FPT2 y )\n\t{\n\t\t_attribs.setBad();\n\t\tadd( Point2d_<FPT>( x, y ) );\n\t}\n\n/// Add single point\n/**\n\\warning this will add the new point after the previous one \\b only if the object has \\b not\nbeen normalized. This normalizing operation will happen if you a comparison (== or !=)\n*/\n\ttemplate<typename FPT2>\n\tvoid add( const Point2d_<FPT2>& pt )\n\t{\n#ifndef HOMOG2D_NOCHECKS\n\t\tif( size() )\n\t\t\tif( pt == _plinevec.back() )\n\t\t\t\tHOMOG2D_THROW_ERROR_1(\n\t\t\t\t\t\"cannot add a point identical to previous one: pt=\" << pt << \" size=\" << size()\n\t\t\t\t);\n#endif\n\t\t_attribs.setBad();\n\t\t_plIsNormalized=false;\n\t\t_plinevec.push_back( pt );\n\t}\n\n/// Set from vector of points (discards previous points)\n\ttemplate<typename FPT2>\n\tvoid set( const std::vector<Point2d_<FPT2>>& vec )\n\t{\n\t\t_attribs.setBad();\n\t\t_plIsNormalized=false;\n\t\t_plinevec.resize( vec.size() );\n\t\tauto it = std::begin( _plinevec );\n\t\tfor( const auto& pt: vec )   // copying one by one will\n\t\t\t*it++ = pt;              // allow type conversions (std::copy implies same type)\n\t}\n\n\n/// Add vector of points\n/**\n\\warning this will add the new points after the previous one \\b only if the object has \\b not\nbeen normalized. This normalizing operation will happen if you a comparison (== or !=)\n*/\n\ttemplate<typename FPT2>\n\tvoid add( const std::vector<Point2d_<FPT2>>& vec )\n\t{\n\t\tif( vec.size() == 0 )\n\t\t\treturn;\n\t\t_attribs.setBad();\n\t\t_plIsNormalized=false;\n\t\t_plinevec.reserve( _plinevec.size() + vec.size() );\n\t\tfor( const auto& pt: vec )  // we cannot use std::copy because vec might not hold points of same type\n\t\t\t_plinevec.push_back( pt );\n\t}\n///@}\n\n/// \\name Operators\n///@{\n\ttemplate<typename FPT2>\n\tbool operator == ( const Polyline_<FPT2>& other ) const\n\t{\n\t\tif( size() != other.size() )          // for quick exit\n\t\t\treturn false;\n\t\tif( isClosed() != other.isClosed() )  // for quick exit\n\t\t\treturn false;\n\n\t\tif( isClosed() )          // if operating on a closed polygon, we\n\t\t{                         // first \"normalize\" the points (i.e. sort them)\n\t\t\tp_normalizePL();\n\t\t\tother.p_normalizePL();\n\t\t}\n\n\t\tauto it = other._plinevec.begin();\n\t\tfor( const auto& elem: _plinevec )\n\t\t\tif( *it++ != elem )\n\t\t\t\treturn false;\n\t\treturn true;\n\t}\n\n\ttemplate<typename FPT2>\n\tbool operator != ( const Polyline_<FPT2>& other ) const\n\t{\n\t\treturn !( *this == other );\n\t}\n///@}\n\n/// Polyline intersection with Line, Segment, FRect, Circle\n\ttemplate<\n\t\ttypename T,\n\t\ttypename std::enable_if<\n\t\t\tpriv::IsShape<T>::value,\n\t\t\tT\n\t\t>::type* = nullptr\n\t>\n\tdetail::IntersectM<FPT> intersects( const T& other ) const\n\t{\n\t\tdetail::IntersectM<FPT> out;\n\t\tfor( const auto& pseg: getSegs() )\n\t\t{\n\t\t\tauto inters = pseg.intersects( other );\n\t\t\tif( inters() )\n\t\t\t\tout.add( inters.get() );\n\t\t}\n\t\treturn out;\n\t}\n\n\ttemplate<typename T>\n\tbool\n\tisInside( const T& cont ) const\n\t{\n\t\tfor( const auto& pt: getPts() )\n\t\t\tif( !pt.isInside( cont ) )\n\t\t\t\treturn false;\n\t\treturn true;\n\t}\n\n\ttemplate<typename T>\n\tfriend std::ostream&\n\toperator << ( std::ostream& f, const Polyline_<T>& pl );\n\n\ttemplate<typename T>\n\tvoid draw( img::Image<T>&, img::DrawParams dp=img::DrawParams() ) const;\n\n#ifdef HOMOG2D_TEST_MODE\n/// this is only needed for testing\n\tbool isNormalized() const { return _plIsNormalized; }\n#endif\n\nprivate:\n\tvoid p_normalizePL() const\n\t{\n\t\tassert( isClosed() );   // should not do this if not closed !\n\t\tif( !_plIsNormalized )\n\t\t{\n\t\t\tstd::sort( _plinevec.begin(), _plinevec.end() );\n\t\t\t_plIsNormalized=true;\n\t\t}\n\t}\n\n}; // class Polyline_\n\n//------------------------------------------------------------------\nnamespace priv {\n\n/// Returns the bounding box of points in vector/list/array \\c vpts\n/**\n\\todo This loops twice on the points. Maybe some improvement here.\n*/\ntemplate<\n\ttypename T,\n\ttypename std::enable_if<\n\t\tpriv::Is_Container<T>::value,\n\t\tT\n\t>::type* = nullptr\n>\nFRect_<typename T::value_type::FType>\ngetPointsBB( const T& vpts )\n{\n\tusing FPT = typename T::value_type::FType;\n#ifndef HOMOG2D_NOCHECKS\n\tif( vpts.empty() )\n\t\tHOMOG2D_THROW_ERROR_1( \"cannot get bounding box of empty set\" );\n#endif\n\tauto mm_x = std::minmax_element(\n\t\tstd::begin( vpts ),\n\t\tstd::end( vpts ),\n\t\t[]                  // lambda\n\t\t( const Point2d_<FPT>& pt1, const Point2d_<FPT>& pt2 )\n\t\t{\n\t\t\treturn pt1.getX() < pt2.getX();\n\t\t}\n\t);\n\tauto mm_y = std::minmax_element(\n\t\tstd::begin( vpts ),\n\t\tstd::end( vpts ),\n\t\t[]                  // lambda\n\t\t( const Point2d_<FPT>& pt1, const Point2d_<FPT>& pt2 )\n\t\t{\n\t\t\treturn pt1.getY() < pt2.getY();\n\t\t}\n\t);\n\n\treturn FRect_<typename T::value_type::FType>(\n\t\tmm_x.first->getX(),  mm_y.first->getY(),\n\t\tmm_x.second->getX(), mm_y.second->getY()\n\t);\n}\n\n} // namespace priv\n\n//------------------------------------------------------------------\n/// Returns true if object is a polygon (i.e. no segment crossing)\ntemplate<typename FPT>\nbool\nPolyline_<FPT>::isPolygon() const\n{\n\tif( size()<3 )       // needs at least 3 points to be a polygon\n\t\treturn false;\n\n\tif( !_isClosed )   // cant be a polygon if\n\t\treturn false;  // it's not closed\n\n\tif( _attribs._isPolygon.isBad() )\n\t{\n\t\tauto nbs = nbSegs();\n\t\tsize_t i=0;\n\t\tbool notDone = true;\n\t\tbool hasIntersections = false;\n\t\tdo\n\t\t{\n\t\t\tauto seg1 = getSegment(i);\n\t\t\tauto lastone = i==0?nbs-1:nbs;\n\t\t\tfor( auto j=i+2; j<lastone; j++ )\n\t\t\t\tif( getSegment(j).intersects(seg1)() )\n\t\t\t\t{\n\t\t\t\t\tnotDone = false;\n\t\t\t\t\thasIntersections = true;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\ti++;\n\t\t}\n\t\twhile( i<nbs && notDone );\n\t\t_attribs._isPolygon.set( !hasIntersections );\n\t}\n\treturn _attribs._isPolygon.value();\n}\n\n//------------------------------------------------------------------\n/// Returns length\ntemplate<typename FPT>\nHOMOG2D_INUMTYPE\nPolyline_<FPT>::length() const\n{\n\tif( _attribs._length.isBad() )\n\t{\n\t\tHOMOG2D_INUMTYPE sum = 0.;\n\t\tfor( const auto& seg: getSegs() )\n\t\t\tsum += static_cast<HOMOG2D_INUMTYPE>( seg.length() );\n\t\t_attribs._length.set( sum );\n\t}\n\treturn _attribs._length.value();\n}\n\n//------------------------------------------------------------------\n/// Returns area of polygon\ntemplate<typename FPT>\nHOMOG2D_INUMTYPE\nPolyline_<FPT>::area() const\n{\n\tif( !isPolygon() )  // implies that is both closed and has no intersections\n\t\treturn 0.;\n\n\tif( _attribs._area.isBad() )\n\t{\n\t\tHOMOG2D_INUMTYPE area = 0.;\n\t\tfor( size_t i=0; i<size(); i++ )\n\t\t{\n\t\t\tauto j = (i == size()-1 ? 0 : i+1);\n\t\t\tauto pt1 = _plinevec[i];\n\t\t\tauto pt2 = _plinevec[j];\n\t\t\tarea += static_cast<HOMOG2D_INUMTYPE>(pt1.getX()) * pt2.getY();\n\t\t\tarea -= static_cast<HOMOG2D_INUMTYPE>(pt1.getY()) * pt2.getX();\n\t\t}\n\t\t_attribs._area.set( std::abs(area / 2.) );\n\t}\n\treturn _attribs._area.value();\n}\n\n//------------------------------------------------------------------\n/// Returns Rectangle of the intersection area, will throw if no intersection area\n/**\n3 situations need to be considered, depending on the number of intersection points:\n\n- A: 2 points on same segment => 2 points inside.\n\\verbatim\n  +------+                   +------+\n  |      |                   |      |\n  |   +--+-----+          +--+----+ |\n  |   |  |     |          |  |    | |\n  |   |  |     |    or    |  |    | |  or ...\n  |   +--+-----+          +--+----+ |\n  |      |                   |      |\n  +------+                   +------+\n\\endverbatim\n\n- B: 2 points on different segments => for each rectangle, 1 point is inside the other.\n\\verbatim\n  +------+\n  |      |\n  |      |\n  |   +--+-----+\n  |   |  |     |   or ...\n  +---+--+     |\n      |        |\n      +--------+\n\\endverbatim\n\n- C: 3 points\n\\verbatim\n  +------+-----+\n  |      |     |\n  |      |     |\n  +------+-----+\n  |      |\n  +------+\n\\endverbatim\n\n- D: 4 points: the intersection rectangle is made of these 4 points\n\\verbatim\n     +------+\n     |      |\n  +--+------+-----+\n  |  |      |     |\n  |  |      |     |\n  +--+------+-----+\n     |      |\n     +------+\n\\endverbatim\n*/\ntemplate<typename FPT>\ntemplate<typename FPT2>\ndetail::RectArea<FPT>\nFRect_<FPT>::intersectArea( const FRect_<FPT2>& other ) const\n{\n\tauto inter = this->intersects( other );\n\n\tif( !inter() )                        // rectangles do not intersect\n\t\treturn detail::RectArea<FPT>();\n\n\tif( inter.size() < 2 )                // only one intersection point\n\t\treturn detail::RectArea<FPT>();\n\n\tif( inter.size() == 4 )  // 4 intersection points => case \"D\"\n\t\treturn detail::RectArea<FPT>(FRect_<FPT>( inter.get().at(0), inter.get().at(3) ) );\n\n\tif( inter.size() == 3 )  // 3 intersection points => case \"C\"\n\t{\n\t\tauto v = inter.get();\n\n\t\tauto xmin = std::min( v[0].getX(), std::min( v[1].getX(),v[2].getX() ) );\n\t\tauto ymin = std::min( v[0].getY(), std::min( v[1].getY(),v[2].getY() ) );\n\t\tauto xmax = std::max( v[0].getX(), std::max( v[1].getX(),v[2].getX() ) );\n\t\tauto ymax = std::max( v[0].getY(), std::max( v[1].getY(),v[2].getY() ) );\n#ifndef HOMOG2D_DEBUGMODE\n\t\tassert( xmax-xmin > Point2d_<FPT>::nullOrthogDistance() );\n\t\tassert( ymax-ymin > Point2d_<FPT>::nullOrthogDistance() );\n#else\n\t\tHOMOG2D_DEBUG_ASSERT(\n\t\t\t( ( xmax-xmin > Point2d_<FPT>::nullOrthogDistance() )\n\t\t\t&&\n\t\t\t( ymax-ymin > Point2d_<FPT>::nullOrthogDistance() )) ,\n\t\t\tstd::scientific\n\t\t\t<< \"this=\" << *this << \" other=\" << other\n\t\t\t<< \"\\nxmax=\" << xmax << \" xmin=\" << xmin\n\t\t\t<< \"\\nymax=\" << ymax << \" ymin=\" << ymin\n\t\t\t<< \"\\nnod=\" << Point2d_<FPT>::nullOrthogDistance()\n\t\t);\n#endif\n\t\treturn detail::RectArea<FPT>( FRect_<FPT>( xmin, ymin, xmax,ymax ) );\n\t}\n\n#ifndef HOMOG2D_DEBUGMODE\n\tassert( inter.size() == 2 );\n#else\n\tHOMOG2D_DEBUG_ASSERT(\n\t\tinter.size() == 2,\n\t\t\"inter.size()=\" << inter.size() << \"\\n-this=\" << *this << \"\\n-other=\" << other\n\t\t<<\"\\n-inter:\" << inter\n\t);\n#endif\n\tconst auto& r1 = *this;\n\tconst auto& r2 = other;\n\tHOMOG2D_LOG( \"r1=\"<<r1 << \" r2=\"<<r2 );\n\tauto v1 = r1.p_pointsInside( r2 );\n\tauto v2 = r2.p_pointsInside( r1 );\n\tauto c1 = v1.size();\n\tauto c2 = v2.size();\n\tHOMOG2D_LOG( \"c1=\" << c1 << \" c2=\" << c2 );\n\n\tif( c1==0 && c2==0 ) // unable, rectangles share a segment\n\t\treturn detail::RectArea<FPT>();\n\n\tassert(\n\t\t( c1==1 && c2==1 )\n\t\t||\n\t\t( c1==0 && c2==2 )\n\t\t||\n\t\t( c2==0 && c1==2 )\n\t);\n\tif( c1==1 || c2==1 ) // only 1 point inside => the rectangle is defined by the intersection points\n\t\treturn detail::RectArea<FPT>( FRect_<FPT>( inter.get().at(0), inter.get().at(1) ) );\n\n// here: 2 points inside, then build rectangle using the 4 points:\n// the 2 inside, and the two intersection points\n\tassert( c1 == 2 || c2 == 2 );\n\n\tif( c1 == 2 )\n\t\treturn detail::RectArea<FPT>(\n\t\t\tFRect_<FPT>(\n\t\t\t\tinter.get().at(0),\n\t\t\t\tinter.get().at(1),\n\t\t\t\tv1.at(0),\n\t\t\t\tv1.at(1)\n\t\t\t)\n\t\t);\n\treturn detail::RectArea<FPT>(\n\t\tFRect_<FPT>(\n\t\t\tinter.get().at(0),\n\t\t\tinter.get().at(1),\n\t\t\tv2.at(0),\n\t\t\tv2.at(1)\n\t\t)\n\t);\n}\n\nnamespace priv {\n/// Common stuff for FRect_ union, see FRect_::unionArea()\nnamespace runion {\n//------------------------------------------------------------------\ntemplate<typename T>\nstruct Index\n{\n\tT       value;\n\tuint8_t rect_idx=0;   // 0 means none\n\n\tIndex() = default;\n\tIndex( T v, uint8_t r )\n\t\t: value(v), rect_idx(r)\n\t{}\n\tfriend bool operator < ( const Index& i1, const Index& i2 )\n\t{\n\n\t\tif( i1.value == i2.value )\n\t\t\treturn i1.rect_idx < i2.rect_idx;\n\t\treturn i1.value < i2.value;\n\t}\n\tfriend std::ostream& operator << ( std::ostream& f, const Index& idx )\n\t{\n\t\tf << idx.value << \" \";\n\t\treturn f;\n\t}\n};\n\nstruct Cell\n{\n\tbool isCorner = false;\n\tCell() = default;\n\ttemplate<typename T>\n\tCell( const Index<T>& ix, const Index<T>& iy )\n\t{\n\t\tif( ix.rect_idx == iy.rect_idx )\n\t\t\tisCorner = true;\n\t}\n};\n\n\nusing Table  = std::array<std::array<Cell,4>,4>;\nusing PCoord = std::pair<uint8_t,uint8_t>;\n\nenum class Direction: uint8_t { N, E, S, W };\n\n/* NEEDED TO DEBUG\nconst char* getString( Direction dir )\n{\n\tswitch( dir )\n\t{\n\t\tcase Direction::W: return \"W\"; break;\n\t\tcase Direction::S: return \"S\"; break;\n\t\tcase Direction::E: return \"E\"; break;\n\t\tcase Direction::N: return \"N\"; break;\n\t}\n\treturn 0; // to avoid a warning\n}*/\n\nenum class Turn: uint8_t { Left, Right };\n\ninline Direction turn( Direction dir, Turn turn )\n{\n\tswitch( dir )\n\t{\n\t\tcase Direction::W:\n\t\t\treturn turn == Turn::Left ? Direction::S : Direction::N;\n\t\tcase Direction::S:\n\t\t\treturn turn == Turn::Left ? Direction::E : Direction::W;\n\t\tcase Direction::E:\n\t\t\treturn turn == Turn::Left ? Direction::N : Direction::S;\n\t\tcase Direction::N:\n\t\t\treturn turn == Turn::Left ? Direction::W : Direction::E;\n\t}\n\treturn Direction::N; // to avoid a warning\n}\n\ninline void\nmoveToNextCell( uint8_t& row, uint8_t& col, const Direction& dir )\n{\n\tswitch( dir )\n\t{\n\t\tcase Direction::N: row--; break;\n\t\tcase Direction::S: row++; break;\n\t\tcase Direction::E: col++; break;\n\t\tcase Direction::W: col--; break;\n\t}\n}\n\ninline std::vector<PCoord>\nparseTable( Table& table)\n{\n\tbool firstTime = true;\n\tbool done = false;\n\tuint8_t row = 0;\n\tuint8_t col = 0;\n\tDirection dir = Direction::E;\n\tstd::vector<PCoord> out;\n\tdo\n\t{\n\t\tif( table[row][col].isCorner )\n\t\t{\n\t\t\tauto new_pair = std::make_pair(row,col);\n\t\t\tif( out.size() > 0 )\n\t\t\t\tif( new_pair == out.front() && out.size() > 2 )\n\t\t\t\t\tdone = true;\n\t\t\tif( !done )\n\t\t\t\tout.push_back( new_pair );\n\t\t\tif( firstTime )\n\t\t\t\tfirstTime = false;\n\t\t\telse\n\t\t\t\tdir = turn( dir, Turn::Right );\n\t\t}\n\t\telse\n\t\t{\n\t\t\tif( ( row==2 || row==1 ) && ( col==2 || col==1 ) )\n\t\t\t{\n\t\t\t\tout.push_back( std::make_pair(row,col) );\n\t\t\t\tdir = turn( dir, Turn::Left );\n\t\t\t}\n\t\t}\n\t\tmoveToNextCell( row, col, dir );\n\t}\n\twhile( !done );\n\treturn out;\n}\n\n#ifdef HOMOG2D_DEBUGMODE\nvoid\nprintTable( const Table& t, std::string msg )\n{\n\tstd::cout << \"Table: \" << msg << \"\\n  | \";\n\tfor( uint8_t r=0;r<4; r++ )\n\t\tstd::cout << (int)r << \" \";\n\tstd::cout << \"\\n--|---------|\\n\";\n\tfor( uint8_t r=0;r<4; r++ )\n\t{\n\t\tstd::cout << (int)r << \" | \";\n\t\tfor( uint8_t c=0;c<4; c++ )\n\t\t\tstd::cout << (t[r][c].isCorner?'F':'.') << \" \";\n\t\tstd::cout << \"|\\n\";\n\t}\n}\n#endif\n//------------------------------------------------------------------\ntemplate<typename FPT>\nPolyline_<FPT>\nconvertToCoord(\n\tconst std::vector<PCoord>&      v_coord, ///< vector of coordinate indexes\n\tconst std::array<Index<FPT>,4>& vx,      ///< holds x-coordinates\n\tconst std::array<Index<FPT>,4>& vy       ///< holds y-coordinates\n)\n{\n\tstd::vector<Point2d_<FPT>> v_pts;\n\tfor( const auto& elem: v_coord )\n\t{\n\t\tauto id_x = elem.first;\n\t\tauto id_y = elem.second;\n\t\tassert( id_x<4 && id_y<4 );\n//\t\tstd::cout << \"[\" << (int)id_x << \"-\" << (int)id_y\n//\t\t\t<< \"]: value=\" << vx[id_x].value << \",\" << vy[id_y].value << '\\n';\n\t\tauto pt = Point2d_<FPT>( vx[id_x].value, vy[id_y].value );\n\t\tif( v_pts.empty() )\n\t\t\tv_pts.push_back( pt );\n\t\telse                             // add to vector only  if not same as previous\n\t\t{                                // and not same as first\n\t\t\tif( v_pts.back() != pt && v_pts.front() != pt )\n\t\t\t\tv_pts.push_back( pt );\n\t\t}\n\t}\n//\tprintVector( v_pts, \"polyline\" );\n\treturn Polyline_<FPT>( v_pts, IsClosed::Yes );\n}\n\n} // namespace priv\n} // namespace runion\n//------------------------------------------------------------------\n/// Computes the polygon of the union of two rectangles\n/**\nAlgorithm:\n - build vectors of x and y coordinates (4 elements)\n - build table x-y (4x4), with corners tagged\n - parse the table by turning right at each corner, and left if position is not one the outside row/col\n*/\ntemplate<typename FPT>\ntemplate<typename FPT2>\nPolyline_<FPT>\nFRect_<FPT>::unionArea( const FRect_<FPT2>& other ) const\n{\n\tusing namespace priv::runion;\n\n\tif( !this->intersects(other)() )  // if no intersection,\n\t\treturn Polyline_<FPT>();      // return empty polygon\n\n/* step 0: make sure the rect with highest x is first.\n This is needed to avoid this kind of situation in table:\n\n  F F . .\n  . . F F\n  . . F F\n  F F . .\n\n  That would happen if we have an identical x in the two rect\n  (thus,they DO intersect), because when sorting, the rect with smallest index\n  (1 or 2) is placed first in the vector of coordinates */\n\tconst auto* pr1 = this;\n\tconst auto* pr2 = &other;\n\tif( pr1->getPts().first.getX() < pr2->getPts().first.getX() )\n\t\tstd::swap( pr1, pr2 );\n\tconst auto& r1 = *pr1;\n\tconst auto& r2 = *pr2;\n//\tstd::cout << \"r1=\" << r1 << \"\\n\";\n//\tstd::cout << \"r2=\" << r2 << \"\\n\";\n// STEP 0 END\n\n\tif( r1 == r2 )                    // if identical rectangles,\n\t\treturn Polyline_<FPT>( r1 );  // return one of them as a polygon\n\n// step 1: build vectors of coordinates and sort them\n\tstd::array<Index<FPT>,4> vx, vy;\n\tint i=0;\n\tvx[i++] = Index<FPT>( r1.getPts().first.getX(),  1);\n\tvx[i++] = Index<FPT>( r1.getPts().second.getX(), 1 );\n\tvx[i++] = Index<FPT>( r2.getPts().first.getX(),  2 );\n\tvx[i++] = Index<FPT>( r2.getPts().second.getX(), 2 );\n\n\ti=0;\n\tvy[i++] = Index<FPT>( r1.getPts().first.getY(),  1 );\n\tvy[i++] = Index<FPT>( r1.getPts().second.getY(), 1 );\n\tvy[i++] = Index<FPT>( r2.getPts().first.getY(),  2 );\n\tvy[i++] = Index<FPT>( r2.getPts().second.getY(), 2 );\n\n\tstd::sort( vx.begin(), vx.end() );\n\tstd::sort( vy.begin(), vy.end() );\n//\tpriv::printArray( vx, \"vx\"); priv::printArray( vy, \"vy\");\n\n// step 2: fill table\\n\";\n\tTable table;\n\tfor( int r=0;r<4; r++ )\n\t\tfor( int c=0;c<4; c++ )\n\t\t\ttable[r][c] = Cell( vx[r], vy[c] );\n//\tprintTable( table, \"after step 2\" );\n\n// step 3: parse table\n\tauto vpts = parseTable( table );\n//\tpriv::printVectorPairs( vpts );\n\n// step 4: convert back vector of coordinates indexes into vector of coordinates\n\treturn convertToCoord( vpts, vx, vy );\n}\n\n/// Returns Bounding Box\ntemplate<typename FPT>\nFRect_<FPT>\nPolyline_<FPT>::getBB() const\n{\n\treturn priv::getPointsBB( getPts() );\n}\n\n\n//------------------------------------------------------------------\nnamespace detail {\n\n/// Used in isBetween()\nenum class Rounding: uint8_t { Yes, No };\n\n/// Helper function\ntemplate<typename T1,typename T2>\nbool\nisBetween( T1 v, T2 v1, T2 v2 )\n{\n\tHOMOG2D_CHECK_IS_NUMBER(T1);\n\tHOMOG2D_CHECK_IS_NUMBER(T2);\n//std::cout << std::scientific << std::setprecision(18);\n//HOMOG2D_LOG(\"v=\"<<v << \" v1=\" << v1 << \" v2=\" << v2 );\n\tif( v >= std::min( v1, v2 ) )\n\t\tif( v <= std::max( v1, v2 ) )\n\t\t\treturn true;\n\treturn false;\n}\n\n/// Does some small rounding (if requested), to avoid some numerical issues\n/// \\todo provide access to the coefficient in API\ntemplate<typename FPT>\nlong double\ndoRounding( FPT value, Rounding r )\n{\n\tif( r == Rounding::No )\n\t\treturn value;\n\tlong double coeff=1E6;\n\treturn std::llroundl( value * coeff ) / coeff;\n}\n\n/// Helper function, checks if \\c pt is in the area defined by \\c pt1 and \\c pt2\ntemplate<typename T1,typename T2>\nbool\nisInArea(\n\tconst Point2d_<T1>& pt,\n\tconst Point2d_<T2>& pt1,\n\tconst Point2d_<T2>& pt2,\n\tRounding r = Rounding::No\n)\n{\n\tHOMOG2D_START;\n\tif( isBetween( doRounding(pt.getX(), r), pt1.getX(), pt2.getX() ) )\n\t\tif( isBetween( doRounding(pt.getY(), r), pt1.getY(), pt2.getY() ) )\n\t\t\treturn true;\n\treturn false;\n}\n\n//------------------------------------------------------------------\n/// See getPtLabel( const Point2d_<FPT>& pt, const Circle_<FPT2>& circle )\nenum class PtTag: uint8_t\n{\n\tInside, Outside, OnEdge\n};\n\n/// Returns a label characterizing point \\c pt, related to \\c circle\ntemplate<typename FPT,typename FPT2>\nPtTag\ngetPtLabel( const Point2d_<FPT>& pt, const Circle_<FPT2>& circle )\n{\n\tif( pt.isInside( circle ) )\n\t\treturn PtTag::Inside;\n\tif(\n\t\tstd::abs( pt.distTo( circle.center() ) - circle.radius() )\n\t\t< Point2d_<FPT>::nullDistance()\n\t)\n\t\treturn PtTag::OnEdge;\n\treturn PtTag::Outside;\n}\n#if 0\n/// Debug, can be removed after\nvoid\nprintTag( std::string txt, PtTag tag )\n{\n\tstd::cout << \"point \" << txt << \": \";\n\tswitch( tag )\n\t{\n\t\tcase PtTag::Inside: std::cout << \"Inside\\n\"; break;\n\t\tcase PtTag::Outside: std::cout << \"Outside\\n\"; break;\n\t\tcase PtTag::OnEdge: std::cout << \"OnEdge\\n\"; break;\n\t}\n}\n#endif\n} // namespace detail\n\n//------------------------------------------------------------------\n/// Segment/Segment intersection\n/**\nAlgorithm:<br>\nWe check if the intersection point lies in between the range of both segments, both on x and on y\n*/\ntemplate<typename FPT>\ntemplate<typename FPT2>\ndetail::Intersect<detail::Inters_1,FPT>\nSegment_<FPT>::intersects( const Segment_<FPT2>& s2 ) const\n{\n\tHOMOG2D_START;\n\tif( *this == s2 )              // same segment => no intersection\n\t\treturn detail::Intersect<detail::Inters_1,FPT>();\n\n\tLine2d_<HOMOG2D_INUMTYPE> l1 = getLine();\n\tLine2d_<HOMOG2D_INUMTYPE> l2 = s2.getLine();\n\tif( l1.isParallelTo( l2 ) )                                // if parallel,\n\t\t\treturn detail::Intersect<detail::Inters_1,FPT>();  // then, no intersection\n\n\tconst auto& ptA1 = getPts().first;\n\tconst auto& ptA2 = getPts().second;\n\tconst auto& ptB1 = s2.getPts().first;\n\tconst auto& ptB2 = s2.getPts().second;\n\n\tauto ptInter = l1 * l2;   // intersection point\n\n\tif( detail::isInArea( ptInter, ptA1, ptA2 ) )\n\t\tif( detail::isInArea( ptInter, ptB1, ptB2 ) )\n\t\t\treturn detail::Intersect<detail::Inters_1,FPT>( ptInter );\n\n\treturn detail::Intersect<detail::Inters_1,FPT>(); // no intersection\n}\n\n//------------------------------------------------------------------\n/// Segment/Line intersection\n/**\nAlgorithm:<br>\nWe check if the intersection point lies in between the range of the segment, both on x and on y\n*/\ntemplate<typename FPT>\ntemplate<typename FPT2>\ndetail::Intersect<detail::Inters_1,FPT>\nSegment_<FPT>::intersects( const Line2d_<FPT2>& li1 ) const\n{\n\tHOMOG2D_START;\n//\tHOMOG2D_LOG( \"seg=\" << *this << \" line=\" << li1 );\n\tdetail::Intersect<detail::Inters_1,FPT> out;\n\tauto li2 = getLine();\n\n\tif( li1.isParallelTo( li2 ) ) // if parallel, no intersection\n\t\treturn out;\n\n\tout._ptIntersect = li1 * li2;   // intersection point\n\n\tconst auto& pi   = out._ptIntersect;\n\tconst auto& ptA1 = getPts().first;\n\tconst auto& ptA2 = getPts().second;\n\n//\tHOMOG2D_LOG( \"pi=\" << pi << \" ptA1=\" <<ptA1  << \" ptA2=\" <<ptA2 );\n\tif( detail::isInArea( pi, ptA1, ptA2, detail::Rounding::Yes ) )\n\t\tout._doesIntersect = true;\n//\telse\n//\t\tHOMOG2D_LOG( \"Is NOT in area\" );\n\treturn out;\n}\n\n//------------------------------------------------------------------\n/// Segment/Circle intersection\n/**\nFor each point of the segment, we need to consider 3 different situations\n - point is inside (PI)\n - point is outside (PO)\n - point is on the edge (PE)\n\nThat makes 6 different situations to handle:\n\n - S1: PI-PI => no intersection\n - S2: PI-PO => 1 intersection\n - S3: PI-PE => 1 intersection\n - S4: PO-PO => depends on the support line:\n  - S4A: if line does NOT intersects circle, no intersection pts\n  - S4B: if line does intersects circle, and intersections point in segment area => 2 intersection pts\n  - S4C: if line does intersects circle, and intersections point NOT in segment area => no intersection pts\n - S5: PO-PE => 1 intersection\n - S6: PE-PE => 2 intersections\n*/\ntemplate<typename FPT>\ntemplate<typename FPT2>\ndetail::IntersectM<FPT>\nSegment_<FPT>::intersects( const Circle_<FPT2>& circle ) const\n{\n\tHOMOG2D_START;\n\tusing detail::PtTag;\n\n\tauto tag_ptS1 = detail::getPtLabel( _ptS1, circle );\n\tauto tag_ptS2 = detail::getPtLabel( _ptS2, circle );\n\n\tif( tag_ptS1 == PtTag::Inside )\n\t\tif( tag_ptS2 == PtTag::Inside )\n\t\t\treturn detail::IntersectM<FPT>();\n\n\tauto int_lc = getLine().intersects( circle );\n\tif( !int_lc() )\n\t\treturn detail::IntersectM<FPT>();\n\n\tauto p_pts = int_lc.get();      // get the line intersection points\n\tconst auto& p1 = p_pts.first;\n\tconst auto& p2 = p_pts.second;\n\n\tif(\n\t\t( tag_ptS1 == PtTag::Inside  && tag_ptS2 == PtTag::Outside )\n\t\t||\n\t\t( tag_ptS1 == PtTag::Outside && tag_ptS2 == PtTag::Inside )\n\t)\n\t{\n\t\tdetail::IntersectM<FPT> out;\n        if( detail::isInArea( p1, _ptS1, _ptS2 ) )  // check which one of the intersections\n\t\t\tout.add( p1 );                          // points is inside\n\t\telse\n\t\t\tout.add( p2 );\n\t\treturn out;\n\t}\n\n\tdetail::IntersectM<FPT> out;\n\tif( tag_ptS1 == PtTag::Outside &&  tag_ptS2 == PtTag::Outside ) // both outside\n\t{\n\t\tif( !detail::isInArea( p1, _ptS1, _ptS2 ) ) //could have done for p2, doesn't matter\n\t\t\treturn detail::IntersectM<FPT>();\n\t\tout.add( p1 );\n\t\tout.add( p2 );\n\t\treturn out;\n\t}\n\n\tif( tag_ptS1 == PtTag::OnEdge )\n\t\tout.add( _ptS1 );\n\tif( tag_ptS2 == PtTag::OnEdge )\n\t\tout.add( _ptS2 );\n\n\treturn out;\n}\n\n/////////////////////////////////////////////////////////////////////////////\n// SECTION  - STREAMING OPERATORS\n/////////////////////////////////////////////////////////////////////////////\n\n//------------------------------------------------------------------\n/// Overload for points\ntemplate<typename LP,typename FPT>\nvoid\nRoot<LP,FPT>::impl_op_stream( std::ostream& f, const Point2d_<FPT>& r ) const\n{\n\tf\n//\t<< std::scientific << std::setprecision(25)\n\t << '[' << r.getX() << ',' << r.getY() << \"]\";\n}\n\n/// Overload for lines\ntemplate<typename LP,typename FPT>\nvoid\nRoot<LP,FPT>::impl_op_stream( std::ostream& f, const Line2d_<FPT>& r ) const\n{\n\tf << '[' << r._v[0] << ',' << r._v[1] << ',' << r._v[2] << \"]\";\n}\n\n/// Stream operator, free function, call member function pseudo operator impl_op_stream()\ntemplate<typename LP,typename FPT>\nstd::ostream&\noperator << ( std::ostream& f, const Root<LP,FPT>& r )\n{\n\tr.impl_op_stream( f, r );\n\treturn f;\n}\n\n/// Stream operator for a container of points/lines, free function\ntemplate<\n\ttypename T,\n\ttypename std::enable_if<\n\t\tpriv::Is_Container<T>::value,\n\t\tT\n\t>::type* = nullptr\n>\nstd::ostream&\noperator << ( std::ostream& f, const T& vec )\n{\n\tfor( const auto& elem: vec )\n\t\tf << elem << '\\n';\n\treturn f;\n}\n\n/// Stream operator for a pair of points/lines, free function\ntemplate<typename LP1,typename LP2,typename FPT>\nstd::ostream&\noperator << ( std::ostream& f, const std::pair<Root<LP1,FPT>,Root<LP2,FPT>>& pr )\n{\n\tf << \"std::pair (\" << getString(pr.first.type()) << \"-\" << getString(pr.second.type())\n\t\t<< \"):\\n -first=\"  << pr.first\n\t\t<< \"\\n -second=\" << pr.second\n\t\t<< ' ';\n\treturn f;\n}\n\ntemplate<typename T>\nstd::ostream&\noperator << ( std::ostream& f, const FRect_<T>& r )\n{\n\tf << \"pt1: \" << r._ptR1 << \" pt2: \" << r._ptR2;\n\treturn f;\n}\n\ntemplate<typename T>\nstd::ostream&\noperator << ( std::ostream& f, const Circle_<T>& r )\n{\n\tf << \"center: \" << r._center << \", radius=\" << r._radius;\n\treturn f;\n}\n\ntemplate<typename T>\nstd::ostream&\noperator << ( std::ostream& f, const Segment_<T>& seg )\n{\n\tf << seg._ptS1 << \"-\" << seg._ptS2;\n\treturn f;\n}\n\ntemplate<typename T>\nstd::ostream&\noperator << ( std::ostream& f, const Polyline_<T>& pl )\n{\n\tf << \"Polyline: \";\n\tif( !pl.size() )\n\t\tf << \"empty\";\n\telse\n\t{\n\t\tfor( const auto& pt: pl._plinevec )\n\t\t\tf << pt << \"-\";\n\t\tf << (pl._isClosed ? \"CLOSED\" : \"NOT-CLOSED\");\n\t}\n\tf << '\\n';\n\treturn f;\n}\n\ntemplate<typename T>\nstd::ostream&\noperator << ( std::ostream& f, const Ellipse_<T>& ell )\n{\n\tauto par = ell.template p_getParams<HOMOG2D_INUMTYPE>();\n\tf << par;\n\treturn f;\n}\n\n\n/////////////////////////////////////////////////////////////////////////////\n// SECTION  - MEMBER FUNCTION IMPLEMENTATION: CLASS Ellipse_\n/////////////////////////////////////////////////////////////////////////////\n\n//------------------------------------------------------------------\n/// Returns standard parameters from matrix coeffs\ntemplate<typename FPT>\ntemplate<typename T>\ndetail::EllParams<T>\nEllipse_<FPT>::p_getParams() const\n{\n#ifdef HOMOG2D_OPTIMIZE_SPEED\n\tif( _epHasChanged )\n\t{\n\t\t_par = p_computeParams<T>();\n\t\t_epHasChanged = false;\n\t}\n\treturn _par;\n#else\n\treturn p_computeParams<T>();\n#endif // HOMOG2D_OPTIMIZE_SPEED\n}\n//------------------------------------------------------------------\n/// Compute and returns standard parameters from matrix coeffs\n/**\n\\note In the checking below, we **cannot** print the matrix using the\n<< operator, because it call this function, thus it would enter\nan infinite loop (an eventually SO).\n*/\ntemplate<typename FPT>\ntemplate<typename T>\ndetail::EllParams<T>\nEllipse_<FPT>::p_computeParams() const\n{\n\tauto& m = detail::Matrix_<FPT>::_mdata;\n\tHOMOG2D_INUMTYPE A = m[0][0];\n\tHOMOG2D_INUMTYPE C = m[1][1];\n\tHOMOG2D_INUMTYPE F = m[2][2];\n\tHOMOG2D_INUMTYPE B = 2. * m[0][1];\n\tHOMOG2D_INUMTYPE D = 2. * m[0][2];\n\tHOMOG2D_INUMTYPE E = 2. * m[1][2];\n\n\tdetail::EllParams<T> par;  // theta already set to zero\n\n\tauto denom = B*B - 4. * A * C;\n\n#ifndef HOMOG2D_NOCHECKS\n\tif( std::abs(denom) < detail::Matrix_<FPT>::nullDenomValue() )\n\t\tHOMOG2D_THROW_ERROR_1(\n\t\t\t\"unable to compute parameters, denom=\" << std::scientific << std::setprecision(15) << denom\n\t\t);\n#endif\n\n\tpar.x0 = ( 2.*C*D - B*E ) / denom;\n\tpar.y0 = ( 2.*A*E - B*D ) / denom;\n\tauto common_ab = 2. * ( A*E*E + C*D*D - B*D*E + denom*F );\n\tauto AmC = A-C;\n\tauto AmC2 = AmC*AmC;\n\tauto sqr = std::sqrt(AmC2+B*B);\n\tpar.a = -std::sqrt( common_ab * ( A+C+sqr ) )/ denom;\n\tpar.b = -std::sqrt( common_ab * ( A+C-sqr ) )/ denom;\n\n\tpar.a2 = par.a * par.a;\n\tpar.b2 = par.b * par.b;\n\tif( std::abs(B) < detail::Matrix_<FPT>::nullDenomValue() )\n\t{\n\t\tif( A > C )\n\t\t\tpar.theta = 90.;\n\t}\n\telse\n\t{\n\t\tauto t = (C - A - sqr) / B;\n\t\tpar.theta = std::atan( t );\n\t}\n\tpar.sint = std::sin( par.theta );\n\tpar.cost = std::cos( par.theta );\n\treturn par;\n}\n\n//------------------------------------------------------------------\n/// Returns true if ellipse is a circle\n/**\nUsing the matrix represention, if A = C and B = 0, then the ellipse is a circle\n\nYou can provide the 0 threshold as and argument\n*/\ntemplate<typename FPT>\nbool\nEllipse_<FPT>::isCircle( HOMOG2D_INUMTYPE thres ) const\n{\n\tauto& m = detail::Matrix_<FPT>::_mdata;\n\tHOMOG2D_INUMTYPE A  = m[0][0];\n\tHOMOG2D_INUMTYPE C  = m[1][1];\n\tHOMOG2D_INUMTYPE B2 = m[0][1];\n\tif( std::abs(A-C) < thres )\n\t\tif( std::abs(B2)*2. < thres )\n\t\t\treturn true;\n\treturn false;\n}\n\n/// Returns center of ellipse\n/// \\sa center( const T& )\ntemplate<typename FPT>\nPoint2d_<FPT>\nEllipse_<FPT>::center() const\n{\n\tauto par = p_getParams<HOMOG2D_INUMTYPE>();\n\treturn Point2d_<FPT>( par.x0, par.y0 );\n}\n\ntemplate<typename FPT>\nstd::pair<HOMOG2D_INUMTYPE,HOMOG2D_INUMTYPE>\nEllipse_<FPT>::getMajMin() const\n{\n\tauto par = p_getParams<HOMOG2D_INUMTYPE>();\n\treturn std::make_pair( par.a, par.b );\n}\n\n/// Returns angle of ellipse\n/// \\sa angle( const Ellipse_& )\ntemplate<typename FPT>\nHOMOG2D_INUMTYPE\nEllipse_<FPT>::angle() const\n{\n\tauto par = p_getParams<HOMOG2D_INUMTYPE>();\n\treturn par.theta;\n}\n\n//------------------------------------------------------------------\n/// Returns pair of axis lines of ellipse\ntemplate<typename FPT>\nstd::pair<Line2d_<FPT>,Line2d_<FPT>>\nEllipse_<FPT>::getAxisLines() const\n{\n\tauto par = p_getParams<HOMOG2D_INUMTYPE>();\n\tauto dy = par.sint * par.a;\n\tauto dx = par.cost * par.a;\n\tPoint2d_<FPT> ptA(\n\t\tpar.x0 + dx,\n\t\tpar.y0 + dy\n\t);\n\tauto pt0 = Point2d_<HOMOG2D_INUMTYPE>( par.x0, par.y0 );\n\n\tauto li_H = ptA * pt0;\n\tauto li_V = li_H.getOrthogonalLine( pt0 );\n\treturn std::make_pair( li_H, li_V );\n}\n\n//------------------------------------------------------------------\n/// Returns bounding box of ellipse\n/**\nAlgorithm:\n - build line \\c liH going through major axis, by using center point and\n point on semi-major axis, intersecting ellipse\n - get opposite point \\x ptB, lying on line and at distance \\c a\n - get the two parallel lines to \\c liH, at a distance \\c b\n - get the two orthogonal lines at \\c ptA and \\c ptB\n\n*/\ntemplate<typename FPT>\nPolyline_<FPT>\nEllipse_<FPT>::getBB() const\n{\n// step 1: build ptA using angle\n\tauto par = p_getParams<HOMOG2D_INUMTYPE>();\n\tauto dy = par.sint * par.a;\n\tauto dx = par.cost * par.a;\n\tPoint2d_<FPT> ptA(\n\t\tpar.x0 + dx,\n\t\tpar.y0 + dy\n\t);\n\tauto pt0 = Point2d_<HOMOG2D_INUMTYPE>( par.x0, par.y0 );\n\n// step 2: build main-axis line, going through center and ptA\n\tauto li_H = ptA * pt0;\n\n// step 3: get ptB, using line and distance\n\tauto ppts = li_H.getPoints( pt0, par.a );\n\tauto ptB = ppts.first;\n\tif( ptB == ptA )\n\t\tptB = ppts.second;\n\n\tauto para = getParallelLines( li_H, par.b );\n\tauto li_V1 = li_H.getOrthogonalLine( ptA );\n\tauto li_V2 = li_H.getOrthogonalLine( ptB );\n\n\tPolyline_<FPT> out( IsClosed::Yes );\n#ifndef\tHOMOG2D_DEBUGMODE\n\tout.add( para.first  * li_V1 );\n\tout.add( para.second * li_V1 );\n\tout.add( para.second * li_V2 );\n\tout.add( para.first  * li_V2 );\n#else\n\tauto p1 = para.first  * li_V1;\n\tauto p2 = para.second * li_V1;\n\tauto p3 = para.second * li_V2;\n\tauto p4 = para.first  * li_V2;\n\tHOMOG2D_DEBUG_ASSERT(\n\t\t( p2!=p1 && p3!=p2 && p4!=p3 ),\n\t\t\"p1=\" << p1 << \" p2=\" << p2 << \" p3=\" << p3 << \" p4=\" << p4\n\t\t<< \"\\n para.1=\" << para.first\n\t\t<< \"\\n li_V1=\" << li_V1\n\t\t<< \"\\n ptA=\" << ptA\n\t\t<< \"\\n ptB=\" << ptB\n\t\t<< \"\\n \" << ppts\n\t);\n\tout.add( p1 );\n\tout.add( p2 );\n\tout.add( p3 );\n\tout.add( p4 );\n#endif\n\treturn out;\n}\n\n//------------------------------------------------------------------\n/// Returns true if point is inside ellipse\n/**\ntaken from https://stackoverflow.com/a/16814494/193789\n*/\ntemplate<typename FPT>\ntemplate<typename FPT2>\nbool\nEllipse_<FPT>::pointIsInside( const Point2d_<FPT2>& pt ) const\n{\n\tHOMOG2D_INUMTYPE x = pt.getX();\n\tHOMOG2D_INUMTYPE y = pt.getY();\n\n\tauto par = p_getParams<HOMOG2D_INUMTYPE>();\n\tconst auto& x0 = par.x0;\n\tconst auto& y0 = par.y0;\n\n\tauto v1 = par.cost * (x-x0) + par.sint * (y-y0);\n\tHOMOG2D_INUMTYPE sum = v1*v1 / par.a2;\n\n\tauto v2 = par.sint * (x-x0) - par.cost * (y-y0);\n\tsum += v2*v2 / par.b2;\n\tif( sum < 1. )\n\t\treturn true;\n\treturn false;\n\n}\n\n/////////////////////////////////////////////////////////////////////////////\n// SECTION  - MEMBER FUNCTION IMPLEMENTATION: CLASS Root\n/////////////////////////////////////////////////////////////////////////////\n\n//------------------------------------------------------------------\n/// Normalize to unit length, and make sure \\c a is always >0\n/**\n\\todo Checkout: in what situation will we be unable to normalize?\nIs the test below relevant? Clarify.\n*/\ntemplate<typename LP,typename FPT>\nvoid\nRoot<LP,FPT>::impl_normalizeLine( const detail::RootHelper<type::IsLine>& ) const\n{\n\tauto sq = std::hypot( _v[0], _v[1] );\n\tif( sq <= std::numeric_limits<double>::epsilon() )\n\t\tthrow std::runtime_error( \"unable to normalize line, sq=\" + std::to_string(sq) );\n\n\tfor( int i=0; i<3; i++ )\n\t\tconst_cast<Root<LP,FPT>*>(this)->_v[i] /= sq; // needed to remove constness\n\n\tif( std::signbit(_v[0]) ) // a always >0\n\t\tfor( int i=0; i<3; i++ )\n\t\t\tconst_cast<Root<LP,FPT>*>(this)->_v[i] = -_v[i];\n\n\tif( _v[0] == 0. ) // then, change sign so that b>0\n\t\tif( std::signbit(_v[1]) )\n\t\t{\n\t\t\tconst_cast<Root<LP,FPT>*>(this)->_v[1] = - _v[1];\n\t\t\tconst_cast<Root<LP,FPT>*>(this)->_v[2] = - _v[2];\n\t\t}\n}\n\n//------------------------------------------------------------------\ntemplate<typename LP,typename FPT>\nFPT\nRoot<LP,FPT>::impl_getCoord( GivenCoord, FPT, const detail::RootHelper<type::IsPoint>& ) const\n{\n\tstatic_assert( detail::AlwaysFalse<LP>::value, \"Invalid: you cannot call getCoord() on a point\" );\n}\n\ntemplate<typename LP,typename FPT>\nFPT\nRoot<LP,FPT>::impl_getCoord( GivenCoord gc, FPT other, const detail::RootHelper<type::IsLine>& ) const\n{\n\tconst auto a = static_cast<HOMOG2D_INUMTYPE>( _v[0] );\n\tconst auto b = static_cast<HOMOG2D_INUMTYPE>( _v[1] );\n\tauto denom = ( gc == GivenCoord::X ? b : a );\n#ifndef HOMOG2D_NOCHECKS\n\tif( std::abs(denom) < nullDenom() )\n\t\tHOMOG2D_THROW_ERROR_2( \"getCoord\", \"null denominator encountered\" );\n#endif\n\tif( gc == GivenCoord::X )\n\t\treturn ( -a * other - _v[2] ) / b;\n\telse\n\t\treturn ( -b * other - _v[2] ) / a;\n}\n\n\ntemplate<typename LP,typename FPT>\nPoint2d_<FPT>\nRoot<LP,FPT>::impl_getPoint( GivenCoord, FPT, const detail::RootHelper<type::IsPoint>& ) const\n{\n\tstatic_assert( detail::AlwaysFalse<LP>::value, \"Invalid: you cannot call getPoint() on a point\" );\n}\n\ntemplate<typename LP,typename FPT>\nPoint2d_<FPT>\nRoot<LP,FPT>::impl_getPoint( GivenCoord gc, FPT other, const detail::RootHelper<type::IsLine>& ) const\n{\n\tauto coord = impl_getCoord( gc, other, detail::RootHelper<type::IsLine>() );\n\tif( gc == GivenCoord::X )\n\t\treturn Point2d_<FPT>( other, coord );\n\treturn Point2d_<FPT>( coord, other );\n}\n\n//------------------------------------------------------------------\n/// ILLEGAL INSTANCIATION\ntemplate<typename LP,typename FPT>\ntemplate<typename FPT2>\nstd::pair<Point2d_<FPT>,Point2d_<FPT>>\nRoot<LP,FPT>::impl_getPoints_A( GivenCoord, FPT, FPT2, const detail::RootHelper<type::IsPoint>& ) const\n{\n\tstatic_assert( detail::AlwaysFalse<LP>::value, \"Invalid: you cannot call getPoints() on a point\" );\n}\ntemplate<typename LP,typename FPT>\ntemplate<typename FPT2>\nstd::pair<Point2d_<FPT>,Point2d_<FPT>>\nRoot<LP,FPT>::impl_getPoints_B( const Point2d_<FPT>&, FPT2, const detail::RootHelper<type::IsPoint>& ) const\n{\n\tstatic_assert( detail::AlwaysFalse<LP>::value, \"Invalid: you cannot call getPoints() on a point\" );\n}\n\n/// Returns pair of points on line at distance \\c dist from point on line at coord \\c coord. Implementation for lines\ntemplate<typename LP,typename FPT>\ntemplate<typename FPT2>\nstd::pair<Point2d_<FPT>,Point2d_<FPT>>\nRoot<LP,FPT>::impl_getPoints_A( GivenCoord gc, FPT coord, FPT2 dist, const detail::RootHelper<type::IsLine>& ) const\n{\n\tconst auto pt = impl_getPoint( gc, coord, detail::RootHelper<type::IsLine>() );\n\treturn priv::getPoints_B2( pt, dist, *this );\n}\n\n/// Returns pair of points on line at distance \\c dist from point on line at coord \\c coord. Implementation for lines\ntemplate<typename LP,typename FPT>\ntemplate<typename FPT2>\nstd::pair<Point2d_<FPT>,Point2d_<FPT>>\nRoot<LP,FPT>::impl_getPoints_B( const Point2d_<FPT>& pt, FPT2 dist, const detail::RootHelper<type::IsLine>& ) const\n{\n#ifndef HOMOG2D_NOCHECKS\n\tif( this->distTo( pt ) > nullDistance() )\n\t{\n\t\tstd::cerr << \"distance=\" << std::scientific << this->distTo( pt ) << \" nD=\" << nullDistance() << \"\\n\";\n\t\tHOMOG2D_THROW_ERROR_2( \"getPoints\", \"point is not on line\" );\n\t}\n#endif\n\n\treturn priv::getPoints_B2( pt, dist, *this );\n}\n\n\n//------------------------------------------------------------------\n/// Illegal instanciation\ntemplate<typename LP,typename FPT>\nLine2d_<FPT>\nRoot<LP,FPT>::impl_getOrthogonalLine_A( GivenCoord, FPT, const detail::RootHelper<type::IsPoint>& ) const\n{\n\tstatic_assert( detail::AlwaysFalse<LP>::value, \"Invalid: you cannot call getOrthogonalLine() on a point\" );\n}\n\n/// Illegal instanciation\ntemplate<typename LP,typename FPT>\nLine2d_<FPT>\nRoot<LP,FPT>::impl_getOrthogonalLine_B( const Point2d_<FPT>&, const detail::RootHelper<type::IsPoint>& ) const\n{\n\tstatic_assert( detail::AlwaysFalse<LP>::value, \"Invalid: you cannot call getOrthogonalLine() on a point\" );\n}\n\n/// Returns an orthogonal line, implementation of getOrthogonalLine().\ntemplate<typename LP,typename FPT>\nLine2d_<FPT>\nRoot<LP,FPT>::impl_getOrthogonalLine_A( GivenCoord gc, FPT val, const detail::RootHelper<type::IsLine>& ) const\n{\n\tauto other_val = impl_getCoord( gc, val, detail::RootHelper<type::IsLine>() );\n\n\tPoint2d_<FPT> pt( other_val, val ) ;\n\tif( gc == GivenCoord::X )\n\t\tpt.set( val, other_val );\n\n\treturn priv::getOrthogonalLine_B2( pt, *this );\n}\n\n/// Returns an orthogonal line, implementation of getOrthogonalLine().\ntemplate<typename LP,typename FPT>\nLine2d_<FPT>\nRoot<LP,FPT>::impl_getOrthogonalLine_B( const Point2d_<FPT>& pt, const detail::RootHelper<type::IsLine>& ) const\n{\n#ifndef HOMOG2D_NOCHECKS\n\tif( this->distTo( pt ) > nullDistance() )\n\t{\n\t\tstd::cerr << \"distance=\" << std::scientific << this->distTo( pt ) << \" nD=\" << nullDistance() << \"\\n\";\n\t\tHOMOG2D_THROW_ERROR_2( \"getOrthogonalLine\", \"point is not on line\" );\n\t}\n#endif\n\n\treturn priv::getOrthogonalLine_B2( pt, *this );\n}\n\n//------------------------------------------------------------------\n/// Illegal instanciation\ntemplate<typename LP,typename FPT>\nLine2d_<FPT>\nRoot<LP,FPT>::impl_getParallelLine( const Point2d_<FPT>&, const detail::RootHelper<type::IsPoint>& ) const\n{\n\tstatic_assert( detail::AlwaysFalse<LP>::value, \"Invalid: you cannot call getParallelLine() on a point\" );\n}\n\n/// Returns an parallel line, implementation of getParallelLine().\ntemplate<typename LP,typename FPT>\nLine2d_<FPT>\nRoot<LP,FPT>::impl_getParallelLine( const Point2d_<FPT>& pt, const detail::RootHelper<type::IsLine>& ) const\n{\n\tLine2d_<FPT> out = *this;\n\tout._v[2] = static_cast<HOMOG2D_INUMTYPE>(-_v[0]) * pt.getX() - _v[1] * pt.getY();\n\tout.p_normalizeLine();\n\treturn out;\n}\n\n//------------------------------------------------------------------\n/// Illegal instanciation\ntemplate<typename LP,typename FPT>\ntemplate<typename T>\nstd::pair<Line2d_<FPT>,Line2d_<FPT>>\nRoot<LP,FPT>::impl_getParallelLines( T, const detail::RootHelper<type::IsPoint>& ) const\n{\n\tstatic_assert( detail::AlwaysFalse<LP>::value, \"Invalid: you cannot call getParallelLines() on a point\" );\n}\n\n/// Implementation for lines\ntemplate<typename LP,typename FPT>\ntemplate<typename T>\nstd::pair<Line2d_<FPT>,Line2d_<FPT>>\nRoot<LP,FPT>::impl_getParallelLines( T dist, const detail::RootHelper<type::IsLine>& ) const\n{\n\tLine2d_<FPT> l1 = *this;\n\tLine2d_<FPT> l2 = *this;\n\tl1._v[2] = static_cast<HOMOG2D_INUMTYPE>(this->_v[2]) + dist;\n\tl2._v[2] = static_cast<HOMOG2D_INUMTYPE>(this->_v[2]) - dist;\n\treturn std::make_pair( l1, l2 );\n}\n\n//------------------------------------------------------------------\n/// Comparison operator, used for lines\n/**\nDefinition: two lines will be equal:\n- if they are not parallel\nAND\n- if their offset (3 third value) is less than nullOffsetValue()\n*/\ntemplate<typename LP,typename FPT>\nbool\nRoot<LP,FPT>::impl_op_equal( const Root<LP,FPT>& other, const detail::RootHelper<type::IsLine>& ) const\n{\n\tif( !this->isParallelTo( other ) )\n\t\treturn false;\n\n\tif( std::fabs( _v[2] - other._v[2] ) > nullOffsetValue() )\n\t\treturn false;\n\n\treturn true;\n}\n\n/// Comparison operator, used for points\ntemplate<typename LP,typename FPT>\nbool\nRoot<LP,FPT>::impl_op_equal( const Root<LP,FPT>& other, const detail::RootHelper<type::IsPoint>& ) const\n{\n\tauto dist = this->distTo( other );\n\tif( dist < nullDistance() )\n\t\treturn true;\n\treturn false;\n}\n\n//------------------------------------------------------------------\n/// Sorting operator, for points\ntemplate<typename LP,typename FPT>\nbool\nRoot<LP,FPT>::impl_op_sort( const Root<LP,FPT>& other, const detail::RootHelper<type::IsPoint>& ) const\n{\n\tif( getX() < other.getX() )\n\t\treturn true;\n\tif( getX() > other.getX() )\n\t\treturn false;\n\tif( getY() < other.getY() )\n\t\treturn true;\n\treturn false;\n}\n/// Sorting operator, for lines\ntemplate<typename LP,typename FPT>\nbool\nRoot<LP,FPT>::impl_op_sort( const Root<LP,FPT>&, const detail::RootHelper<type::IsLine>& ) const\n{\n\tstatic_assert( detail::AlwaysFalse<LP>::value, \"Invalid < operator: you cannot sort lines\" );\n\treturn false; // to avoid a warning\n}\n\n//------------------------------------------------------------------\n/// Inner implementation details\nnamespace detail {\n\n\t/// Cross product, see https://en.wikipedia.org/wiki/Cross_product#Coordinate_notation\n\ttemplate<typename Out,typename In,typename FPT1,typename FPT2>\n\tRoot<Out,FPT1> crossProduct( const Root<In,FPT1>& r1, const Root<In,FPT2>& r2 )\n\t{\n\t\tauto r1_a = static_cast<HOMOG2D_INUMTYPE>(r1._v[0]);\n\t\tauto r1_b = static_cast<HOMOG2D_INUMTYPE>(r1._v[1]);\n\t\tauto r1_c = static_cast<HOMOG2D_INUMTYPE>(r1._v[2]);\n\t\tauto r2_a = static_cast<HOMOG2D_INUMTYPE>(r2._v[0]);\n\t\tauto r2_b = static_cast<HOMOG2D_INUMTYPE>(r2._v[1]);\n\t\tauto r2_c = static_cast<HOMOG2D_INUMTYPE>(r2._v[2]);\n\n\t\tRoot<Out,FPT1> res;\n\t\tres._v[0] = static_cast<FPT1>( r1_b * r2_c  - r1_c * r2_b );\n\t\tres._v[1] = static_cast<FPT1>( r1_c * r2_a  - r1_a * r2_c );\n\t\tres._v[2] = static_cast<FPT1>( r1_a * r2_b  - r1_b * r2_a );\n\n\t\treturn res;\n\t}\n} // namespace detail\n\n\n//------------------------------------------------------------------\n///////////////////////////////////////////\n// CONSTRUCTORS\n///////////////////////////////////////////\n\n/// Points overload: generic init from two numeric args\ntemplate<typename LP, typename FPT>\ntemplate<typename T1,typename T2>\nvoid\nRoot<LP,FPT>::impl_init_2( const T1& v1, const T2& v2, const detail::RootHelper<type::IsPoint>& )\n{\n\t_v[0] = v1;\n\t_v[1] = v2;\n\t_v[2] = 1.;\n}\n\n/// Lines overload: generic init from two numeric args\ntemplate<typename LP, typename FPT>\ntemplate<typename T1,typename T2>\nvoid\nRoot<LP,FPT>::impl_init_2( const T1& v1, const T2& v2, const detail::RootHelper<type::IsLine>& )\n{\n\tPoint2d_<FPT> pt1;                // 0,0\n\tPoint2d_<FPT> pt2(v1,v2);\n\t*this = detail::crossProduct<type::IsLine>( pt1, pt2 );\n\tp_normalizeLine();\n}\n\n/// Overload for point to point distance\ntemplate<typename LP, typename FPT>\ntemplate<typename FPT2>\nHOMOG2D_INUMTYPE\nRoot<LP,FPT>::impl_distToPoint( const Point2d_<FPT2>& pt, const detail::RootHelper<type::IsPoint>& ) const\n{\n\treturn static_cast<double>(\n\t\tstd::hypot(\n\t\t\tstatic_cast<HOMOG2D_INUMTYPE>( getX() ) - static_cast<HOMOG2D_INUMTYPE>( pt.getX() ),\n\t\t\tstatic_cast<HOMOG2D_INUMTYPE>( getY() ) - static_cast<HOMOG2D_INUMTYPE>( pt.getY() )\n\t\t)\n\t);\n}\n//------------------------------------------------------------------\n/// Returns distance between the line and point \\b pt. overload for line to point distance.\n/**\nhttp://mathworld.wolfram.com/Point-LineDistance2-Dimensional.html\n<pre>\n        | a.x0 + b.y0 + c |\n  d = -----------------------\n         sqrt( a*a + b*b )\n</pre>\n\\todo Do we really require computation of hypot ? (because the line is supposed to be normalized, i.e. h=1 ?)\n*/\ntemplate<typename LP, typename FPT>\ntemplate<typename FPT2>\nHOMOG2D_INUMTYPE\nRoot<LP,FPT>::impl_distToPoint( const Point2d_<FPT2>& pt, const detail::RootHelper<type::IsLine>& ) const\n{\n\treturn std::fabs( _v[0] * pt.getX() + _v[1] * pt.getY() + _v[2] ) / std::hypot( _v[0], _v[1] );\n}\n\n/// overload for line to point distance\ntemplate<typename LP, typename FPT>\ntemplate<typename FPT2>\nHOMOG2D_INUMTYPE\nRoot<LP,FPT>::impl_distToLine( const Line2d_<FPT2>& li, const detail::RootHelper<type::IsPoint>& ) const\n{\n\treturn li.distTo( *this );\n}\n\n/// overload for line to line distance. Aborts build if instanciated (distance between two lines makes no sense).\ntemplate<typename LP, typename FPT>\ntemplate<typename FPT2>\nHOMOG2D_INUMTYPE\nRoot<LP,FPT>::impl_distToLine( const Line2d_<FPT2>&, const detail::RootHelper<type::IsLine>& ) const\n{\n\tstatic_assert( detail::AlwaysFalse<LP>::value, \"Invalid: you cannot compute distance between two lines\" );\n\treturn 0.;    // to avoid warning message on build\n}\n\n//------------------------------------------------------------------\n/// Free function, returns the angle (in Rad) between two lines/ or segments\n/// \\sa Segment_::getAngle()\n/// \\sa Line2d_::getAngle()\ntemplate<typename T1,typename T2>\nHOMOG2D_INUMTYPE\ngetAngle( const T1& li1, const T2& li2 )\n{\n\treturn li1.getAngle( li2 );\n}\n\ntemplate<typename LP, typename FPT>\ntemplate<typename FPT2>\nbool\nRoot<LP,FPT>::impl_isParallelTo( const Root<LP,FPT2>& li, const detail::RootHelper<type::IsLine>& ) const\n{\n\tif( getAngle(li) < Root::nullAngleValue() )\n\t\treturn true;\n\treturn false;\n}\ntemplate<typename LP, typename FPT>\ntemplate<typename FPT2>\nbool\nRoot<LP,FPT>::impl_isParallelTo( const Root<LP,FPT2>&, const detail::RootHelper<type::IsPoint>& ) const\n{\n\tstatic_assert( detail::AlwaysFalse<LP>::value, \"Invalid: you cannot use IsParallel() with a point\" );\n\treturn false;    // to avoid a warning message on build\n}\n\n//------------------------------------------------------------------\n/// Returns the angle (in rad.) between the line and the other one.\n/**\n- The returned value will be in the range <code> [0, M_PI/2] </code>\n\nIf the lines \\f$ (a_0,a_1,a_2) \\f$ and \\f$ (b_0,b_1,b_2) \\f$ are correctly normalized (should be, but...)\nthen the angle between them is \\f$ \\alpha = acos( a_0*b_0 + a_1*b_1) \\f$. <br>\nHowever, in \"some situations\", even if the lines have been previously normalized (which is the case here)\nwe can encounter numerical issues, so here we \"reinforce the normalization and compute:\n\\f[\n\\alpha = acos \\left(\n\t\\frac{a_0*b_0 + a_1*b_1} { \\sqrt{ a_0*a_0 + a_1*a_1 } * \\sqrt{ b_0*b_0 + b_1*b_1 } }\n\\right)\n\\f]\nIn some situations, the value inside the parenthesis \"may\" be equal to \\f$ 1+\\epsilon \\f$\n(typically, something like \"1.0000000000123\").\nThis is out of bounds for the \\f$ acos() \\f$ function, that will then return \"nan\"\n(thus induce some failure further on). <br>\nTo avoid this, a checking is done, and any value higher than 1 will be truncated.\nThis is logged on \\c std::cerr so that the user may take that into consideration.\n\n\\todo more investigation needed ! : what are the exact situation that will lead to this event?\n*/\ntemplate<typename LP, typename FPT>\nHOMOG2D_INUMTYPE\nRoot<LP,FPT>::impl_getAngle( const Root<LP,FPT>& li, const detail::RootHelper<type::IsLine>& ) const\n{\n\tHOMOG2D_INUMTYPE l1_a = _v[0];\n\tHOMOG2D_INUMTYPE l1_b = _v[1];\n\tHOMOG2D_INUMTYPE l2_a = li._v[0];\n\tHOMOG2D_INUMTYPE l2_b = li._v[1];\n\tHOMOG2D_INUMTYPE res = l1_a * l2_a + l1_b * l2_b;\n\n\tres /= std::sqrt( (l1_a*l1_a + l1_b*l1_b) * (l2_a*l2_a + l2_b*l2_b) );\n\tHOMOG2D_INUMTYPE fres = std::abs(res);\n\tif( fres > 1.0 )\n\t{\n\t\tstd::cerr << \"homog2d: angle computation overflow detected, value \"\n\t\t\t<< std::scientific << std::setprecision(20)\n\t\t\t<< fres << \", truncated to 1.0\\n\";\n\t\tfres = 1.0;\n\t}\n\treturn std::acos( fres );\n}\n\ntemplate<typename LP, typename FPT>\nHOMOG2D_INUMTYPE\nRoot<LP,FPT>::impl_getAngle( const Root<LP,FPT>&, const detail::RootHelper<type::IsPoint>& ) const\n{\n\tstatic_assert( detail::AlwaysFalse<LP>::value, \"cannot get angle of a point\" );\n\treturn 0.; // to avoid a warning\n}\n\n\n//------------------------------------------------------------------\n/// Returns true if point is inside (or on the edge) of a flat rectangle defined by (p0,p1)\ntemplate<typename LP, typename FPT>\ntemplate<typename FPT2>\nbool\nRoot<LP,FPT>::impl_isInsideRect( const FRect_<FPT2>& rect, const detail::RootHelper<type::IsPoint>& ) const\n{\n\tauto pair_pts = rect.getPts();\n\tconst auto& p00 = pair_pts.first;\n\tconst auto& p11 = pair_pts.second;\n\treturn detail::ptIsInside( *this, p00, p11 );\n}\ntemplate<typename LP, typename FPT>\ntemplate<typename FPT2>\nbool\nRoot<LP,FPT>::impl_isInsideRect( const FRect_<FPT2>&, const detail::RootHelper<type::IsLine>& ) const\n{\n\tstatic_assert( detail::AlwaysFalse<LP>::value, \"cannot use isInside(Rectangle) with a line\" );\n\treturn false; // to avoid a warning\n}\n\n//------------------------------------------------------------------\ntemplate<typename LP, typename FPT>\ntemplate<typename T>\nbool\nRoot<LP,FPT>::impl_isInsideCircle( const Point2d_<FPT>& center, T radius, const detail::RootHelper<type::IsPoint>& ) const\n{\n\tif( distTo( center ) < radius )\n\t\treturn true;\n\treturn false;\n}\ntemplate<typename LP, typename FPT>\ntemplate<typename T>\nbool\nRoot<LP,FPT>::impl_isInsideCircle( const Point2d_<FPT>&, T, const detail::RootHelper<type::IsLine>& ) const\n{\n\tstatic_assert( detail::AlwaysFalse<LP>::value, \"cannot use isInside(Circle) with a line\" );\n\treturn false; // to avoid a warning\n}\n\n\n//------------------------------------------------------------------\ntemplate<typename LP, typename FPT>\ntemplate<typename FPT2>\nbool\nRoot<LP,FPT>::impl_isInsideEllipse( const Ellipse_<FPT2>& ell, const detail::RootHelper<type::IsPoint>& ) const\n{\n\treturn ell.pointIsInside( *this );\n}\n\ntemplate<typename LP, typename FPT>\ntemplate<typename FPT2>\nbool\nRoot<LP,FPT>::impl_isInsideEllipse( const Ellipse_<FPT2>&, const detail::RootHelper<type::IsLine>& ) const\n{\n\tstatic_assert( detail::AlwaysFalse<LP>::value, \"cannot use isInside(Ellipse) with a line\" );\n\treturn false; // to avoid a warning\n}\n\n\n//------------------------------------------------------------------\n/// Intersection of line and circle: implementation for points\ntemplate<typename LP, typename FPT>\ntemplate<typename T>\ndetail::Intersect<detail::Inters_2,FPT>\nRoot<LP,FPT>::impl_intersectsCircle( const Point2d_<FPT>&, T, const detail::RootHelper<type::IsPoint>& ) const\n{\n\tstatic_assert( detail::AlwaysFalse<LP>::value, \"cannot use intersects(Circle) with a point\" );\n}\n\n/// Line/Circle intersection: implementation\n/// For computation details, checkout http://skramm.lautre.net/files/misc/intersect_circle_line.pdf\ntemplate<typename LP, typename FPT>\ntemplate<typename T>\ndetail::Intersect<detail::Inters_2,FPT>\nRoot<LP,FPT>::impl_intersectsCircle(\n\tconst Point2d_<FPT>& pt,       ///< circle origin\n\tT                    radius,   ///< radius\n\tconst detail::RootHelper<type::IsLine>&  ///< dummy arg, needed so that this overload is only called for lines\n) const\n{\n\tdetail::Intersect<detail::Inters_2,FPT> out;\n\tHOMOG2D_CHECK_IS_NUMBER(T);\n\tconst HOMOG2D_INUMTYPE a = static_cast<HOMOG2D_INUMTYPE>(_v[0]); // just to lighten a bit...\n\tconst HOMOG2D_INUMTYPE b = static_cast<HOMOG2D_INUMTYPE>(_v[1]);\n\tconst HOMOG2D_INUMTYPE c = static_cast<HOMOG2D_INUMTYPE>(_v[2]);\n\n// step 1: translate to origin\n\tauto cp = pt.getX() * a + pt.getY() * b + c;\n\n// step 2: compute distance\tbetween center (origin) and middle point\n\tauto a2b2 = a * a + b * b;\n\tauto d0 = std::abs(cp) / std::sqrt( a2b2 );\n\tif( radius < d0 )                            // if less than radius,\n\t\treturn out;                         // no intersection\n\n\tauto d2 = radius*radius - d0*d0;\n\n// step 3: compute coordinates of middle point B\n\tauto xb = - a * cp / a2b2;\n\tauto yb = - b * cp / a2b2;\n\n// step 4: compute coordinates of intersection points, with center at (0,0)\n\tauto m  = std::sqrt( d2 / a2b2 );\n\tauto x1 = xb + m*b;\n\tauto y1 = yb - m*a;\n\n\tauto x2 = xb - m*b;\n\tauto y2 = yb + m*a;\n\n// last step: translate back\n\tout._ptIntersect_1.set( x1 + pt.getX(), y1 + pt.getY() );\n\tout._ptIntersect_2.set( x2 + pt.getX(), y2 + pt.getY() );\n\tout._doesIntersect = true;\n\n\tpriv::fix_order( out._ptIntersect_1, out._ptIntersect_2 );\n\treturn out;\n}\n//------------------------------------------------------------------\n/// Overload used when attempting to use that on a point\ntemplate<typename LP, typename FPT>\ntemplate<typename FPT2>\ndetail::Intersect<detail::Inters_2,FPT>\nRoot<LP,FPT>::impl_intersectsFRect( const FRect_<FPT2>&, const detail::RootHelper<type::IsPoint>& ) const\n{\n\tstatic_assert( detail::AlwaysFalse<LP>::value, \"Invalid: you cannot call intersects(FRect) on a point\" );\n}\n\n/// Line/FRect intersection\ntemplate<typename LP, typename FPT>\ntemplate<typename FPT2>\ndetail::Intersect<detail::Inters_2,FPT>\nRoot<LP,FPT>::impl_intersectsFRect( const FRect_<FPT2>& rect, const detail::RootHelper<type::IsLine>& ) const\n{\n\tHOMOG2D_START;\n\n//\tstd::cout << \"Line/FRect intersection, line=\" << *this << \" rect=\" << rect << \"\\n\";\n\tstd::vector<Point2d_<FPT>> pti;\n\tfor( const auto seg: rect.getSegs() )\n\t{\n\t\tauto ppts_seg = seg.getPts();\n\t\tauto inters = seg.intersects( *this );\n\t\tif( inters() )\n\t\t{\n\t\t\tbool storePoint(true);\n\t\t\tauto pt = inters.get();\n\t\t\tif( pt == ppts_seg.first || pt == ppts_seg.second )  // if point is one of the segments\n\t\t\t\tif( pti.size() == 1 )                            // AND if there is already one\n\t\t\t\t\tif( pti[0] == pt )                           // AND that one is already stored\n\t\t\t\t\t\tstorePoint = false;\n\t\t\tif( storePoint )\n\t\t\t\tpti.push_back( pt );\n\n\t\t\tif( pti.size() == 2 )  // already got 2, done\n\t\t\t\tbreak;\n\t\t}\n\t}\n\n#ifndef HOMOG2D_DEBUGMODE\n\tassert( pti.size() == 0 || pti.size() == 2 ); // only two points\n#else\n\tHOMOG2D_DEBUG_ASSERT(\n\t\t( pti.size() == 0 || pti.size() == 2 ),\n\t\t\"Line/FRect intersection:\" << std::scientific << std::setprecision(15) << \"\\n -line=\" << *this << \"\\n -frect=\" << rect\n\t\t\t\t\t\t<< \"\\n -pti.size()=\" << pti.size()\n\t);\n#endif\n\n\tif( pti.empty() )\n\t\treturn detail::Intersect<detail::Inters_2,FPT>();\n\n\tpriv::fix_order( pti[0], pti[1] );\n\treturn detail::Intersect<detail::Inters_2,FPT>( pti[0], pti[1] );\n}\n\n//------------------------------------------------------------------\n/// Draw lines or points\ntemplate<typename LP,typename FPT>\ntemplate<typename T>\nbool Root<LP,FPT>::draw( img::Image<T>& img, img::DrawParams dp ) const\n{\n\treturn impl_draw( img, dp, detail::RootHelper<LP>() );\n}\n\n\n/////////////////////////////////////////////////////////////////////////////\n// SECTION  - PRODUCT OPERATORS DEFINITIONS (HELPER FUNCTIONS)\n/////////////////////////////////////////////////////////////////////////////\n\n//------------------------------------------------------------------\n/// Apply homography to a vector/array/list (type T) of points or lines.\ntemplate<typename W,typename FPT>\ntemplate<typename T>\nvoid\nHmatrix_<W,FPT>::applyTo( T& vin ) const\n{\n\tfor( auto& elem: vin )\n\t\telem = *this * elem;\n}\n\nnamespace detail {\n\n/// Implementation of product 3x3 by 3x3\n\ntemplate<typename FPT1,typename FPT2,typename FPT3>\nvoid\nproduct(\n\tMatrix_<FPT1>&       out,\n\tconst Matrix_<FPT2>& h1,\n\tconst Matrix_<FPT3>& h2\n)\n{\n\tout.p_fillZero();\n\tfor( int i=0; i<3; i++ )\n\t\tfor( int j=0; j<3; j++ )\n\t\t\tfor( int k=0; k<3; k++ )\n\t\t\t\tout.value(i,j) +=\n\t\t\t\t\tstatic_cast<HOMOG2D_INUMTYPE>( h1.value(i,k) ) * h2.value(k,j);\n}\n\n/// Implementation of product 3x3 by 3x1\n/**\n- T1 and T2: type::IsLine or type::IsPoint (same but also different)\n*/\ntemplate<typename T1,typename T2,typename FPT1,typename FPT2>\nvoid\nproduct(\n\tRoot<T1,FPT1>&       out,\n\tconst Matrix_<FPT2>& h,\n\tconst Root<T2,FPT1>& in\n)\n{\n\tfor( int i=0; i<3; i++ )\n\t{\n\t\tauto sum  = static_cast<HOMOG2D_INUMTYPE>(h._mdata[i][0]) * in._v[0];\n\t\tsum      += h._mdata[i][1] * in._v[1];\n\t\tsum      += h._mdata[i][2] * in._v[2];\n\t\tout._v[i] = sum;\n\t}\n}\n\n} // namespace detail\n\n/////////////////////////////////////////////////////////////////////////////\n// SECTION  - PRODUCT OPERATORS DEFINITIONS\n/////////////////////////////////////////////////////////////////////////////\n\n/// Free function template, product of two lines, returns a point\ntemplate<typename FPT,typename FPT2>\nPoint2d_<FPT>\noperator * ( const Line2d_<FPT>& lhs, const Line2d_<FPT2>& rhs )\n{\n#ifndef HOMOG2D_NOCHECKS\n\tif( lhs.isParallelTo(rhs) )\n\t\tHOMOG2D_THROW_ERROR_1( \"lines are parallel, unable to compute product:\\nlhs=\"\n\t\t\t<< lhs << \" rhs=\" << rhs\n\t\t);\n#endif\n\n\treturn detail::crossProduct<type::IsPoint,type::IsLine,FPT>(lhs, rhs);\n}\n\n/// Free function template, product of two segments, returns a point\ntemplate<typename FPT,typename FPT2>\nPoint2d_<FPT>\noperator * ( const Segment_<FPT>& lhs, const Segment_<FPT2>& rhs )\n{\n\treturn lhs.getLine() * rhs.getLine();\n}\n\n/// Free function template, product of two points, returns a line\ntemplate<typename FPT,typename FPT2>\nLine2d_<FPT>\noperator * ( const Point2d_<FPT>& lhs, const Point2d_<FPT2>& rhs )\n{\n#ifndef HOMOG2D_NOCHECKS\n\tif( lhs == rhs )\n\t\tHOMOG2D_THROW_ERROR_1( \"points are identical, unable to compute product:\" << lhs );\n#endif\n\tLine2d_< FPT> line = detail::crossProduct<type::IsLine,type::IsPoint,FPT>(lhs, rhs);\n\tline.p_normalizeLine();\n\treturn line;\n}\n\n#ifdef HOMOG2D_FUTURE_STUFF\n/// Apply Epipolar matrix to a point or line, this will return the opposite type.\n/// Free function, templated by point or line\ntemplate<typename T,typename U,typename V>\nRoot<typename detail::HelperPL<T>::OtherType,V>\noperator * ( const Hmatrix_<type::IsEpipmat,U>& h, const Root<T,V>& in )\n{\n\tRoot<typename detail::HelperPL<T>::OtherType,V> out;\n\tdetail::product( out, h._data, in );\n\treturn out;\n}\n#endif\n\n/// Free function, apply homography to a point.\ntemplate<typename T,typename U>\nPoint2d_<T>\noperator * ( const Homogr_<U>& h, const Point2d_<T>& in )\n{\n\tPoint2d_<T> out;\n\tdetail::product( out, h, in );\n\treturn out;\n}\n\n/// Free function, apply homography to a line.\ntemplate<typename T,typename U>\nLine2d_<T>\noperator * ( const Homogr_<U>& h, const Line2d_<T>& in )\n{\n\tif( h._hmt == nullptr )             // if H^-T\tnot allocated yet, do it\n\t{\n\t\th._hmt = std::unique_ptr<detail::Matrix_<U>>( new detail::Matrix_<U>() );\n\t\th._hasChanged = true;\n\t}\n\n\tif( h._hasChanged )                  // if homography has changed, recompute inverse and transposed\n\t{\n\t\tauto hi = h;\n\t\tauto mat_inv = hi.inverse().transpose();\n\t\t*h._hmt = mat_inv;\n\t\th._hasChanged = false;\n\t}\n\n\tLine2d_<T> out;\n\tdetail::product( out, *h._hmt, in );\n\tout.p_normalizeLine();\n\treturn out;\n}\n\n/// Apply homography to a Segment\ntemplate<typename FPT1,typename FPT2>\nSegment_<FPT1>\noperator * ( const Homogr_<FPT2>& h, const Segment_<FPT1>& seg )\n{\n\tconst auto& pts = seg.getPts();\n\tPoint2d_<FPT1> pt1 = h * pts.first;\n\tPoint2d_<FPT1> pt2 = h * pts.second;\n\treturn Segment_<FPT1>( pt1, pt2 );\n}\n\n/// Apply homography to a Polyline\ntemplate<typename FPT1,typename FPT2>\nPolyline_<FPT1>\noperator * ( const Homogr_<FPT2>& h, const Polyline_<FPT1>& pl )\n{\n\tPolyline_<FPT1> out;\n\tconst auto& pts = pl.getPts();\n\tfor( const auto pt: pts )\n\t\tout.add( h * pt );\n\tout.isClosed() = pl.isClosed();\n\treturn out;\n}\n\n/// Apply homography to a flat rectangle produces a closed polyline\ntemplate<typename FPT1,typename FPT2>\nPolyline_<FPT1>\noperator * ( const Homogr_<FPT2>& h, const FRect_<FPT1>& rin )\n{\n\tPolyline_<FPT1> out( IsClosed::Yes );\n\tfor( const auto& pt: rin.get4Pts() )\n\t\tout.add( h * pt );\n\treturn out;\n}\n\n/// Apply homography to a Ellipse, produces an Ellipse\n/**\n\\f[\nQ' = H^{-T} \\cdot Q \\cdot H^{-1}\n\\f]\n*/\ntemplate<typename FPT1,typename FPT2>\nEllipse_<FPT1>\noperator * ( const Homogr_<FPT2>& h, const Ellipse_<FPT1>& ell_in )\n{\n\tauto hm = static_cast<detail::Matrix_<FPT2>>(h);\n\thm.inverse();\n\tauto hmt = hm;\n\thmt.transpose();\n\n\tconst auto& ell_in2 = static_cast<detail::Matrix_<FPT1>>(ell_in);\n\tauto prod = hmt * ell_in2 * hm;\n\n\tEllipse_<FPT1> out( prod );\n\treturn out;\n}\n\n/// Apply homography to a Circle, produces an Ellipse\n/** Converts the circle to an ellipse, then calls the corresponding code */\ntemplate<typename FPT1,typename FPT2>\nEllipse_<FPT1>\noperator * ( const Homogr_<FPT2>& h, const Circle_<FPT1>& cir )\n{\n\tEllipse_<FPT1> ell_in( cir );\n\treturn h * ell_in;\n}\n\n//------------------------------------------------------------------\nnamespace priv {\n\n/// Allocation for \\c std::array container\ntemplate<\n\ttypename Cont,\n\ttypename std::enable_if<\n\t\tIs_std_array<Cont>::value,\n\t\tCont\n\t>::type* = nullptr\n>\nCont\nalloc( std::size_t /* unused here */ )\n{\n\treturn Cont();\n}\n\n/// Allocation for \\c std::vector and \\c std::list container\ntemplate<\n\ttypename Cont,\n\ttypename std::enable_if<\n\t\t!Is_std_array<Cont>::value,\n\t\tCont\n\t>::type* = nullptr\n>\nCont\nalloc( std::size_t nb )\n{\n\treturn Cont(nb);\n}\n\n} // namespace priv\n\n//------------------------------------------------------------------\n/// Used to proceed multiple products, whatever the container (\\c std::list, \\c std::vector, or \\c std::array).\n/// Returned container is of same type as given input\ntemplate<typename FPT,typename Cont>\ntypename std::enable_if<priv::Is_Container<Cont>::value,Cont>::type\noperator * (\n\tconst Hmatrix_<type::IsHomogr,FPT>& h,    ///< Matrix\n\tconst Cont&                         vin   ///< Input container\n)\n{\n\tCont vout = priv::alloc<Cont>( vin.size() );\n\tauto it = std::begin( vout );\n\tfor( const auto& elem: vin )\n\t\t*it++ = h * elem;\n\treturn vout;\n}\n\n/////////////////////////////////////////////////////////////////////////////\n// SECTION  - FREE FUNCTIONS\n/////////////////////////////////////////////////////////////////////////////\n\ntemplate<typename FPT>\nFPT getX( const Point2d_<FPT>& pt) { return pt.getX(); }\ntemplate<typename FPT>\nFPT getY( const Point2d_<FPT>& pt) { return pt.getY(); }\n\n\ntemplate<typename FPT1,typename FPT2>\nPolyline_<FPT1>\nunionArea( const FRect_<FPT1>& r1, const FRect_<FPT2>& r2 )\n{\n\treturn r1.unionArea(r2);\n}\n\ntemplate<typename FPT1,typename FPT2>\ndetail::RectArea<FPT1>\nintersectArea(  const FRect_<FPT1>& r1, const FRect_<FPT2>& r2 )\n{\n\treturn r1.intersectArea(r2);\n}\n\n/// Returns circle passing through 4 points of flat rectangle (free function)\ntemplate<typename FPT>\nCircle_<FPT>\ngetBoundingCircle( const FRect_<FPT>& rect )\n{\n\treturn rect.getBoundingCircle();\n}\n\n/// Returns true if is a polygon (free function)\n///  \\sa Polyline_::isPolygon()\ntemplate<typename FPT>\nbool\nisPolygon( const Polyline_<FPT>& pl )\n{\n\treturn pl.isPolygon();\n}\n\n/// Returns the number of segments (free function)\n/// \\sa Polyline_::nbSegs()\ntemplate<typename FPT>\nsize_t nbSegs( const Polyline_<FPT>& pl )\n{\n\treturn pl.nbSegs();\n}\n\n/// Get segment length (free function)\n/// \\sa Segment_::length()\ntemplate<typename FPT>\nHOMOG2D_INUMTYPE\nlength( const Segment_<FPT>& seg )\n{\n\treturn seg.length();\n}\n\n/// Returns length (free function)\n/// \\sa Polyline_::length()\ntemplate<typename FPT>\nHOMOG2D_INUMTYPE\nlength( const Polyline_<FPT>& pl )\n{\n\treturn pl.length();\n}\n\n/// Returns the segments of the polyline (free function)\n/// \\sa Polyline_::getSegs()\ntemplate<typename FPT>\nstd::vector<Segment_<FPT>>\ngetSegs( const Polyline_<FPT>& pl )\n{\n\treturn pl.getSegs();\n}\n\n/// Returns the number of points (free function)\n/// \\sa Polyline_::size()\ntemplate<typename FPT>\nsize_t size( const Polyline_<FPT>& pl )\n{\n\treturn pl.size();\n}\n\n/// Returns Bounding Box of Ellipse_ (free function)\n/// \\sa Ellipse_::getBB()\ntemplate<typename FPT>\nPolyline_<FPT>\ngetBB( const Ellipse_<FPT>& ell )\n{\n\treturn ell.getBB();\n}\n\n\n/// Returns Bounding Box of Segment_ (free function)\n/// \\sa Segment_::getBB()\ntemplate<typename FPT>\nFRect_<FPT>\ngetBB( const Segment_<FPT>& seg )\n{\n\treturn seg.getBB();\n}\n\n/// Returns Bounding Box of Circle_ (free function)\n/// \\sa Circle_::getBB()\ntemplate<typename FPT>\nFRect_<FPT>\ngetBB( const Circle_<FPT>& cir )\n{\n\treturn cir.getBB();\n}\n\n/// Returns Bounding Box of Polyline_ (free function)\n/// \\sa FRect_::getBB()\ntemplate<typename FPT>\nFRect_<FPT>\ngetBB( const Polyline_<FPT>& pl )\n{\n\treturn pl.getBB();\n}\n\n/// Returns Bounding Box of arbitrary container holding points (free function)\ntemplate<\n\ttypename T,\n\ttypename std::enable_if<\n\t\tpriv::Is_Container<T>::value,\n\t\tT\n\t>::type* = nullptr\n>\n//FRect_<typename T::value_type::FType> // if we dont have C++14 but only C++11\nauto\ngetBB( const T& vpts )\n{\n\treturn priv::getPointsBB( vpts );\n}\n\n//------------------------------------------------------------------\n/// Returns the points of Segment as a std::pair (free function)\n/// \\sa Segment_::getPts()\ntemplate<typename FPT>\nstd::pair<Point2d_<FPT>,Point2d_<FPT>>\ngetPts( const Segment_<FPT>& seg )\n{\n\treturn seg.getPts();\n}\n\n/// Returns Segment supporting line (free function)\n/// \\sa Segment_::getLine()\ntemplate<typename FPT>\nLine2d_<FPT> getLine( const Segment_<FPT>& seg )\n{\n\treturn seg.getLine();\n}\n\n//------------------------------------------------------------------\n/// Free function, returns segment between two circle centers\ntemplate<typename FPT1,typename FPT2>\nSegment_<FPT1>\ngetSegment( const Circle_<FPT1>& c1, const Circle_<FPT2>& c2 )\n{\n\treturn Segment_<FPT1>( c1.center(), c2.center() );\n}\n\n/// Free function, returns line between two circle centers\ntemplate<typename FPT1,typename FPT2,typename FPT3>\nLine2d_<FPT1>\ngetLine( const Circle_<FPT2>& c1, const Circle_<FPT3>& c2 )\n{\n\treturn Line2d_<FPT1>( c1.center(), c2.center() );\n}\n\n/// Free function, returns middle point of segment\n/// \\sa Segment_::getMiddlePoint()\ntemplate<typename FPT>\nPoint2d_<FPT>\ngetMiddlePoint( const Segment_<FPT>& seg )\n{\n\treturn seg.getMiddlePoint();\n}\n\n/// Free function, returns middle point of set of segments\n/**\n\\sa Segment_::getMiddlePoint()\n- input: set of segments\n- output: set of points (same container)\n*/\n\ntemplate<typename FPT>\nstd::vector<Point2d_<FPT>>\ngetMiddlePoints( const std::vector<Segment_<FPT>>& vsegs )\n{\n\tstd::vector<Point2d_<FPT>> vout( vsegs.size() );\n\n\tauto it = std::begin( vout );\n\tfor( const auto& seg: vsegs )\n\t\t*it++ = getMiddlePoint( seg );\n\treturn vout;\n}\n\n/// Free function, returns segments of the rectangle\n/// \\sa FRect_::getSegs()\ntemplate<typename FPT>\nstd::array<Segment_<FPT>,4>\ngetSegs( const FRect_<FPT>& seg )\n{\n\treturn seg.getSegs();\n}\n\n/// Free function, returns the pair of segments tangential to the two circles\ntemplate<typename FPT1,typename FPT2>\nstd::pair<Segment_<FPT1>,Segment_<FPT1>>\ngetTanSegs( const Circle_<FPT1>& c1, const Circle_<FPT2>& c2 )\n{\n#ifndef HOMOG2D_NOCHECKS\n\tif( c1 == c2 )\n\t\tHOMOG2D_THROW_ERROR_1( \"c1 and c2 identical\" );\n#endif\n\n\tauto li0 = Line2d_<FPT1>( c1.center(), c2.center() );\n\tauto li1 = li0.getOrthogonalLine( c1.center() );\n\tauto li2 = li0.getOrthogonalLine( c2.center() );\n\n\tconst auto ri1 = li1.intersects( c1 );\n\tconst auto ri2 = li2.intersects( c2 );\n\tassert( ri1() && ri2() );\n\tconst auto& ppts1 = ri1.get();\n\tconst auto& ppts2 = ri2.get();\n\n\treturn std::make_pair(\n\t\tSegment_<FPT1>( ppts1.first,  ppts2.first  ),\n\t\tSegment_<FPT1>( ppts1.second, ppts2.second )\n\t);\n}\n\n/// Returns the 4 points of the rectangle (free function)\n/// \\sa FRect_::get4Pts()\ntemplate<typename FPT>\nstd::array<Point2d_<FPT>,4>\nget4Pts( const FRect_<FPT>& rect )\n{\n\treturn rect.get4Pts();\n}\n\n/// Returns the 2 major points of the rectangle (free function)\n/// \\sa FRect_::getPts()\ntemplate<typename FPT>\nstd::pair<Point2d_<FPT>,Point2d_<FPT>>\ngetPts( const FRect_<FPT>& rect )\n{\n\treturn rect.getPts();\n}\n\n/// Free function\ntemplate<typename FPT>\nHOMOG2D_INUMTYPE height( const FRect_<FPT>& rect )\n{\n\treturn rect.height();\n}\n/// Free function\ntemplate<typename FPT>\nHOMOG2D_INUMTYPE width( const FRect_<FPT>& rect )\n{\n\treturn rect.width();\n}\n\n/// Free function\n/// \\sa FRect_::area()\ntemplate<typename FPT>\nHOMOG2D_INUMTYPE area( const FRect_<FPT>& rect )\n{\n\treturn rect.area();\n}\n\n/// Free function\n/// \\sa Ellipse_::area()\ntemplate<typename FPT>\nHOMOG2D_INUMTYPE area( const Ellipse_<FPT>& ell )\n{\n\treturn ell.area();\n}\n\n/// Free function\ntemplate<typename FPT>\nHOMOG2D_INUMTYPE length( const FRect_<FPT>& rect )\n{\n\treturn rect.length();\n}\n\n//------------------------------------------------------------------\n/// Returns the 2 parallel lines at distance \\c dist from \\c li\ntemplate<typename FPT,typename T>\nstd::pair<Line2d_<FPT>,Line2d_<FPT>>\ngetParallelLines( const Line2d_<FPT>& li, T dist )\n{\n\treturn li.getParallelLines( dist );\n}\n\n/// Returns the distance between 2 parallel lines (free function)\n/**\n- ref: https://en.wikipedia.org/wiki/Distance_between_two_parallel_lines\n\nWe first check that the two lines are indeed parallel.\nThis should ensure that a1=a2 and b1=b2.\nBut due to numeric issues they could by slightly different. In order to gain accuracy,\nwe use the geometric mean of these.\n*/\ntemplate<typename FPT>\nHOMOG2D_INUMTYPE\ngetParallelDistance( const Line2d_<FPT>& li1, const Line2d_<FPT>& li2 )\n{\n#ifndef HOMOG2D_NOCHECKS\n\tif( !li1.isParallelTo(li2) )\n\t\tHOMOG2D_THROW_ERROR_1( \"lines are not parallel\" );\n#endif\n\tconst auto ar1 = li1.get();\n\tconst auto ar2 = li2.get();\n\tconst HOMOG2D_INUMTYPE a1 = ar1[0];\n\tconst HOMOG2D_INUMTYPE b1 = ar1[1];\n\tconst HOMOG2D_INUMTYPE c1 = ar1[2];\n\tconst HOMOG2D_INUMTYPE a2 = ar2[0];\n\tconst HOMOG2D_INUMTYPE b2 = ar2[1];\n\tconst HOMOG2D_INUMTYPE c2 = ar2[2];\n\n\tHOMOG2D_INUMTYPE a = std::sqrt( a1*a2 );\n\tHOMOG2D_INUMTYPE b = std::sqrt( b1*b2 );\n\treturn std::abs( c1 - c2 ) / std::sqrt( a*a + b*b );\n}\n\n/// Return angle of ellipse (free function)\n/// \\sa Ellipse_::angle()\ntemplate<typename FPT>\nHOMOG2D_INUMTYPE\nangle( const Ellipse_<FPT>& ell )\n{\n\treturn ell.angle();\n}\n\n/// Return center of Circle_ or Ellipse_ (free function)\n/// \\sa Ellipse_::center()\n/// \\sa Circle_::center()\ntemplate<typename T>\nPoint2d_<typename T::FType>\ncenter(const T& other )\n{\n\treturn other.center();\n}\n\n/// Returns true if ellipse is a circle\n/// \\sa Ellipse_::isCircle()\ntemplate<typename FPT>\nbool\nisCircle( const Ellipse_<FPT>& ell, HOMOG2D_INUMTYPE thres=1.E-10 )\n{\n\treturn ell.isCircle( thres );\n}\n\n/// Returns ellipse axis lines\n/// \\sa Ellipse_::getAxisLines()\ntemplate<typename FPT>\nstd::pair<Line2d_<FPT>,Line2d_<FPT>>\ngetAxisLines( const Ellipse_<FPT>& ell )\n{\n\treturn ell.getAxisLines();\n}\n\n/////////////////////////////////////////////////////////////////////////////\n// SECTION  - GENERIC DRAWING FREE FUNCTIONS (BACK-END INDEPENDENT)\n/////////////////////////////////////////////////////////////////////////////\n\n//------------------------------------------------------------------\n/// Free function, draws any of the primitives\ntemplate<\n\ttypename U,\n\ttypename Prim,\n\ttypename std::enable_if<\n\t\tpriv::IsShape<Prim>::value,\n\t\tPrim\n\t>::type* = nullptr\n>\nvoid draw( img::Image<U>& img, const Prim& prim, const img::DrawParams& dp=img::DrawParams() )\n{\n\tprim.draw( img, dp );\n}\n\n/// Free function, draws a set of points or lines\n/**\nTemplate type can be std::array<type> or std::vector<type>, with \\c type being Point2d or \\c Line2d\n*/\ntemplate<\n\ttypename U,\n\ttypename T,\n\ttypename std::enable_if<\n\t\tpriv::Is_Container<T>::value,\n\t\tT\n\t>::type* = nullptr\n>\nvoid draw( img::Image<U>& img, const T& cont, const img::DrawParams& dp=img::DrawParams() )\n{\n\tfor( const auto& elem: cont )\n\t\telem.draw( img, dp );\n}\n//------------------------------------------------------------------\n/// Free function, draws a pair of points\n/**\nTemplate type can be std::array<type> or std::vector<type>, with \\c type being Point2d or \\c Line2d\n*/\ntemplate<typename T,typename U>\nvoid draw( img::Image<U>& img, const std::pair<T,T>& ppts, const img::DrawParams& dp=img::DrawParams() )\n{\n\tppts.first.draw( img, dp );\n\tppts.second.draw( img, dp );\n}\n\nnamespace detail {\n\n/// Private helper function, used by Root<IsPoint>::draw()\ntemplate<typename T>\nvoid\ndrawPt( img::Image<T>& img, img::PtStyle ps, std::vector<Point2d_<float>> vpt, const img::DrawParams& dp, bool drawDiag=false )\n{\n\tauto delta  = dp._dpValues._ptDelta;\n\tauto delta2 = std::round( 0.85 * delta);\n\tswitch( ps )\n\t{\n\t\tcase img::PtStyle::Times:\n\t\t\tvpt[0].translate( -delta2, +delta2 );\n\t\t\tvpt[1].translate( +delta2, -delta2 );\n\t\t\tvpt[2].translate( +delta2, +delta2 );\n\t\t\tvpt[3].translate( -delta2, -delta2 );\n\t\tbreak;\n\n\t\tcase img::PtStyle::Plus:\n\t\tcase img::PtStyle::Diam:\n\t\t\tvpt[0].translate( -delta2, 0.      );\n\t\t\tvpt[1].translate( +delta2, 0.      );\n\t\t\tvpt[2].translate( 0.,      -delta2 );\n\t\t\tvpt[3].translate( 0.,      +delta2 );\n\t\tbreak;\n\t\tdefault: assert(0);\n\t}\n\tif( !drawDiag )\n\t{\n\t\tSegment_<float> s1( vpt[0], vpt[1] );\n\t\tSegment_<float> s2( vpt[2], vpt[3] );\n\t\ts1.draw( img, dp );\n\t\ts2.draw( img, dp );\n\t}\n\telse // draw 4 diagonal lines\n\t{\n\t\tSegment_<float>( vpt[0], vpt[2] ).draw( img, dp ); //, dp._dpValues.color(), dp._dpValues._enhancePoint?2:1 );\n\t\tSegment_<float>( vpt[2], vpt[1] ).draw( img, dp ); //, dp._dpValues.color(), dp._dpValues._enhancePoint?2:1 );\n\t\tSegment_<float>( vpt[1], vpt[3] ).draw( img, dp ); //, dp._dpValues.color(), dp._dpValues._enhancePoint?2:1 );\n\t\tSegment_<float>( vpt[0], vpt[3] ).draw( img, dp ); //, dp._dpValues.color(), dp._dpValues._enhancePoint?2:1 );\n\t}\n}\n\n} // namespace detail\n\n//------------------------------------------------------------------\n/// Draw Polyline, independent of back-end library (calls the segment drawing function)\ntemplate<typename FPT>\ntemplate<typename T>\nvoid\nPolyline_<FPT>::draw( img::Image<T>& img, img::DrawParams dp ) const\n{\n\tif( size() < 2 ) // nothing to draw\n\t\treturn;\n\n\tfor( size_t i=0; i<size()-1; i++ )\n\t{\n\t\tconst auto& pt1 = _plinevec[i];\n\t\tconst auto& pt2 = _plinevec[i+1];\n\t\tassert( pt1 != pt2 );\n\t\tSegment_<FPT>(pt1,pt2).draw( img, dp );\n//\t\t\tcv::putText( mat, std::to_string(i), getCvPti(pt1), cv::FONT_HERSHEY_PLAIN, 1.0, cv::Scalar(10,100,10) );\n\t}\n\tif( size() < 3 ) // no last segment\n\t\treturn;\n\tif( _isClosed )\n\t\tSegment_<FPT>(_plinevec.front(),_plinevec.back() ).draw( img, dp );\n}\n\n\n/////////////////////////////////////////////////////////////////////////////\n// SECTION  - OPENCV BINDING - GENERAL\n/////////////////////////////////////////////////////////////////////////////\n\n//------------------------------------------------------------------\n#ifdef HOMOG2D_USE_OPENCV\n/// Return Opencv 2D point\ntemplate<typename LP, typename FPT>\ntemplate<typename OPENCVT>\nOPENCVT\nRoot<LP,FPT>::impl_getCvPt( const detail::RootHelper<type::IsPoint>&, const OPENCVT& ) const\n{\n\treturn OPENCVT( getX(),getY() );\n}\n\n//------------------------------------------------------------------\n/// Copy matrix to Opencv \\c cv::Mat\n/**\nThe output matrix is passed by reference to avoid issues with Opencv copy operator, and is allocated here.\n\nUser can pass a type as second argument: CV_32F for \\c float, CV_64F for \\c double (default)\n*/\ntemplate<typename W,typename FPT>\nvoid\nHmatrix_<W,FPT>::copyTo( cv::Mat& mat, int type ) const\n{\n\tauto& data = detail::Matrix_<FPT>::_mdata;\n#ifndef HOMOG2D_NOCHECKS\n\tif( type != CV_64F && type != CV_32F )\n\t\tthrow std::runtime_error( \"invalid OpenCv matrix type\" );\n#endif\n\tmat.create( 3, 3, type ); // default:CV_64F\n\tsize_t i=0;\n\tswitch( type )\n\t{\n\t\tcase CV_64F:\n\t\t\tfor( auto it = mat.begin<double>(); it != mat.end<double>(); it++, i++ )\n\t\t\t\t*it = data[i/3][i%3];\n\t\t\tbreak;\n\t\tcase CV_32F:\n\t\t\tfor( auto it = mat.begin<float>(); it != mat.end<float>(); it++, i++ )\n\t\t\t\t*it = data[i/3][i%3];\n\t\t\tbreak;\n\t\tdefault: assert(0);\n\t}\n}\n//------------------------------------------------------------------\n/// Get homography from Opencv \\c cv::Mat\ntemplate<typename W,typename FPT>\nHmatrix_<W,FPT>&\nHmatrix_<W,FPT>::operator = ( const cv::Mat& mat )\n{\n#ifndef HOMOG2D_NOCHECKS\n\tif( mat.rows != 3 || mat.cols != 3 )\n\t\tthrow std::runtime_error( \"invalid matrix size, rows=\" + std::to_string(mat.rows) + \" cols=\" + std::to_string(mat.cols) );\n\tif( mat.channels() != 1 )\n\t\tthrow std::runtime_error( \"invalid matrix nb channels: \" + std::to_string(mat.channels() ) );\n#endif\n\tauto type = mat.type();\n#ifndef HOMOG2D_NOCHECKS\n\tif( type != CV_64F && type != CV_32F )\n\t\tthrow std::runtime_error( \"invalid matrix type\" );\n#endif\n\tsize_t i=0;\n\n\tauto& data = detail::Matrix_<FPT>::_mdata;\n\tswitch( type )\n\t{\n\t\tcase CV_64F:\n\t\t\tfor( auto it = mat.begin<double>(); it != mat.end<double>(); it++, i++ )\n\t\t\t\tdata[i/3][i%3] = *it;\n\t\t\tbreak;\n\t\tcase CV_32F:\n\t\t\tfor( auto it = mat.begin<float>(); it != mat.end<float>(); it++, i++ )\n\t\t\t\tdata[i/3][i%3] = *it;\n\t\t\tbreak;\n\t\tdefault: assert(0);\n\t}\n\treturn *this;\n}\n#endif // HOMOG2D_USE_OPENCV\n\n/////////////////////////////////////////////////////////////////////////////\n// SECTION  - CLASS DRAWING MEMBER FUNCTIONS (OpenCv)\n/////////////////////////////////////////////////////////////////////////////\n\n#ifdef HOMOG2D_USE_OPENCV\n//------------------------------------------------------------------\n/// Draw points on Cv::Mat: implementation\n/// Returns false if point not in image\ntemplate<typename LP, typename FPT>\ntemplate<typename T>\nbool\nRoot<LP,FPT>::impl_draw( img::Image<T>& img, img::DrawParams dp, const detail::RootHelper<type::IsPoint>& ) const\n{\n\tif( getX()<0 || getX()>=img.cols() )\n\t\treturn false;\n\tif( getY()<0 || getY()>=img.rows() )\n\t\treturn false;\n\n\tstd::vector<Point2d_<float>> vpt( 4, *this );\n\tswitch( dp._dpValues._ptStyle )\n\t{\n\t\tcase img::PtStyle::Plus:   // \"+\" symbol\n\t\t\tdetail::drawPt( img, img::PtStyle::Plus,  vpt, dp );\n\t\tbreak;\n\n\t\tcase img::PtStyle::Star:\n\t\t\tdetail::drawPt( img, img::PtStyle::Plus,  vpt, dp );\n\t\t\tdetail::drawPt( img, img::PtStyle::Times, vpt, dp );\n\t\tbreak;\n\n\t\tcase img::PtStyle::Diam:\n\t\t\tdetail::drawPt( img, img::PtStyle::Plus,  vpt, dp, true );\n\t\tbreak;\n\n\t\tcase img::PtStyle::Times:      // \"times\" symbol\n\t\t\tdetail::drawPt( img, img::PtStyle::Times, vpt, dp );\n\t\tbreak;\n\n\t\tdefault: assert(0);\n\t}\n\treturn true;\n}\n\n//------------------------------------------------------------------\n/// Draw Lines on Cv::Mat: implementation\n/**\nReturns false if line is not in image.\n\nSteps:\n -# builds the 4 corner points of the image\n -# build the 4 corresponding lines (borders of the image)\n -# find the intersection points between the line and these 4 lines. Should find 2\n -# draw a line between these 2 points\n*/\ntemplate<typename LP, typename FPT>\ntemplate<typename T>\nbool\nRoot<LP,FPT>::impl_draw( img::Image<T>& img, img::DrawParams dp, const detail::RootHelper<type::IsLine>& ) const\n{\n\tassert( img.rows() > 2 );\n\tassert( img.cols() > 2 );\n\n\tPoint2d_<FPT> pt1; // 0,0\n\tPoint2d_<FPT> pt2( img.cols()-1, img.rows()-1 );\n    auto ri = this->intersects( pt1,  pt2 );\n    if( ri() )\n    {\n    \tauto ppts = ri.get();\n\t\tcv::Point2d ptcv1 = ppts.first.getCvPtd();\n\t\tcv::Point2d ptcv2 = ppts.second.getCvPtd();\n\t\tcv::line(\n\t\t\timg.getReal(),\n\t\t\tptcv1,\n\t\t\tptcv2,\n\t\t\tdp._dpValues.color(),\n\t\t\tdp._dpValues._lineThickness,\n\t\t\tdp._dpValues._lineType==1?cv::LINE_AA:cv::LINE_8\n\t\t);\n\t\treturn true;\n\t}\n\treturn false;\n}\n\n/// Draw FRect_\ntemplate<typename FPT>\ntemplate<typename T>\nvoid\nFRect_<FPT>::draw( img::Image<T>& img, img::DrawParams dp ) const\n{\n\tcv::rectangle(\n\t\timg.getReal(),\n\t\t_ptR1.getCvPti(),\n\t\t_ptR2.getCvPti(),\n\t\tdp._dpValues.color(),\n\t\tdp._dpValues._lineThickness,\n\t\tdp._dpValues._lineType==1?cv::LINE_AA:cv::LINE_8\n\t);\n}\n\n//------------------------------------------------------------------\n/// Draw Segment_\ntemplate<typename FPT>\ntemplate<typename T>\nvoid\nSegment_<FPT>::draw( img::Image<T>& img, img::DrawParams dp ) const\n{\n\tcv::line(\n\t\timg.getReal(),\n\t\t_ptS1.getCvPtd(),\n\t\t_ptS2.getCvPtd(),\n\t\tdp._dpValues.color(),\n\t\tdp._dpValues._lineThickness,\n\t\tdp._dpValues._lineType==1?cv::LINE_AA:cv::LINE_8\n\t);\n}\n\n//------------------------------------------------------------------\n/// Draw Circle_\ntemplate<typename FPT>\ntemplate<typename T>\nvoid\nCircle_<FPT>::draw( img::Image<T>& img, img::DrawParams dp ) const\n{\n\tcv::circle(\n\t\timg.getReal(),\n\t\t_center.getCvPti(),\n\t\tstatic_cast<int>(_radius),\n\t\tdp._dpValues.color(),\n\t\tdp._dpValues._lineThickness,\n\t\tdp._dpValues._lineType==1?cv::LINE_AA:cv::LINE_8\n\t);\n}\n\n//------------------------------------------------------------------\n/// Draw ellipse using Opencv\n/**\n- see https://docs.opencv.org/3.4/d6/d6e/group__imgproc__draw.html#ga28b2267d35786f5f890ca167236cbc69\n*/\ntemplate<typename FPT>\ntemplate<typename T>\nvoid\nEllipse_<FPT>::draw( img::Image<T>& img, img::DrawParams dp )  const\n{\n\tauto par = p_getParams<HOMOG2D_INUMTYPE>();\n\tcv::ellipse(\n\t\timg.getReal(),\n\t\tcv::Point( par.x0,par.y0 ),\n\t\tcv::Size( par.a, par.b ),\n\t\tpar.theta*180./M_PI,\n\t\t0., 360.,\n\t\tdp._dpValues.color(),\n\t\tdp._dpValues._lineThickness,\n\t\tdp._dpValues._lineType==1?cv::LINE_AA:cv::LINE_8\n\t);\n}\n\n//------------------------------------------------------------------\n#endif // HOMOG2D_USE_OPENCV\n\n\n/////////////////////////////////////////////////////////////////////////////\n// SECTION  - TYPEDEFS\n/////////////////////////////////////////////////////////////////////////////\n\n/// Default line type, uses \\c double as numerical type\nusing Line2d = Line2d_<double>;\n\n/// Default point type, uses \\c double as numerical type\nusing Point2d = Root<type::IsPoint,double>;\n\n/// Default homography (3x3 matrix) type, uses \\c double as numerical type\nusing Homogr = Homogr_<double>;\n\n/// Default homogeneous matrix, uses \\c double as numerical type\nusing Epipmat = Hmatrix_<type::IsEpipmat,double>;\n\n/// Default segment type\nusing Segment = Segment_<double>;\n\n/// Default circle type\nusing Circle = Circle_<double>;\n\n/// Default rectangle type\nusing FRect = FRect_<double>;\n\n/// Default polyline type\nusing Polyline = Polyline_<double>;\n\n/// Default ellipse type\nusing Ellipse = Ellipse_<double>;\n\n// float types\nusing Line2dF  = Line2d_<float>;\nusing Point2dF = Root<type::IsPoint,float>;\nusing HomogrF  = Homogr_<float>;\nusing SegmentF = Segment_<float>;\nusing CircleF  = Circle_<float>;\nusing FRectF   = FRect_<float>;\nusing PolylineF= Polyline_<float>;\nusing EllipseF = Ellipse_<float>;\n\n// double types\nusing Line2dD  = Line2d_<double>;\nusing Point2dD = Root<type::IsPoint,double>;\nusing HomogrD  = Homogr_<double>;\nusing SegmentD = Segment_<double>;\nusing CircleD  = Circle_<double>;\nusing FRectD   = FRect_<double>;\nusing PolylineD= Polyline_<double>;\nusing EllipseD = Ellipse_<double>;\n\n// long double types\nusing Line2dL  = Line2d_<long double>;\nusing Point2dL = Root<type::IsPoint,long double>;\nusing HomogrL  = Homogr_<long double>;\nusing SegmentL = Segment_<long double>;\nusing CircleL  = Circle_<long double>;\nusing FRectL   = FRect_<long double>;\nusing PolylineL= Polyline_<long double>;\nusing EllipseL = Ellipse_<long double>;\n\n} // namespace h2d end\n\n\n#endif // HG_HOMOG2D_HPP\n\n", "meta": {"hexsha": "b26483a84b360b3712df1e603b004c28c8f31da6", "size": 177570, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/homog2d.hpp", "max_stars_repo_name": "Gathering-Folds/tessellate", "max_stars_repo_head_hexsha": "0542d9ba8e1645bfa5f86976b1ce434bda56459d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-08-08T16:23:13.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-08T16:23:13.000Z", "max_issues_repo_path": "include/homog2d.hpp", "max_issues_repo_name": "gatheringfolds/tessellate", "max_issues_repo_head_hexsha": "0542d9ba8e1645bfa5f86976b1ce434bda56459d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/homog2d.hpp", "max_forks_repo_name": "gatheringfolds/tessellate", "max_forks_repo_head_hexsha": "0542d9ba8e1645bfa5f86976b1ce434bda56459d", "max_forks_repo_licenses": ["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.5302325581, "max_line_length": 144, "alphanum_fraction": 0.6361829138, "num_tokens": 54636, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5698526514141571, "lm_q2_score": 0.5583269943353744, "lm_q1q2_score": 0.3181641180781101}}
{"text": "﻿// File: geometry.hpp\n// Project: core\n// Created Date: 14/04/2021\n// Author: Shun Suzuki\n// -----\n// Last Modified: 22/09/2021\n// Modified By: Shun Suzuki (suzuki@hapis.k.u-tokyo.ac.jp)\n// -----\n// Copyright (c) 2021 Hapis Lab. All rights reserved.\n//\n\n#pragma once\n\n#if _MSC_VER\n#pragma warning(push)\n#pragma warning(disable : 6031 6255 6294 26450 26451 26454 26495 26812)\n#endif\n#if defined(__GNUC__) && !defined(__llvm__)\n#pragma GCC diagnostic push\n#pragma GCC diagnostic ignored \"-Wmaybe-uninitialized\"\n#endif\n#include <Eigen/Dense>\n#if _MSC_VER\n#pragma warning(pop)\n#endif\n#if defined(__GNUC__) && !defined(__llvm__)\n#pragma GCC diagnostic pop\n#endif\n\n#include <map>\n#include <memory>\n#include <utility>\n#include <vector>\n\n#include \"hardware_defined.hpp\"\n\nnamespace autd {\nnamespace core {\n\nclass Geometry;\nusing GeometryPtr = std::unique_ptr<Geometry>;\n\nusing Vector3 = Eigen::Matrix<double, 3, 1>;\nusing Vector4 = Eigen::Matrix<double, 4, 1>;\nusing Matrix4X4 = Eigen::Matrix<double, 4, 4>;\nusing Quaternion = Eigen::Quaternion<double>;\n\n/**\n * \\brief Device contains an AUTD device geometry.\n */\nstruct Device {\n  Device(const Vector3& position, const Quaternion& quaternion)\n      : x_direction(quaternion * Vector3(1, 0, 0)),\n        y_direction(quaternion * Vector3(0, 1, 0)),\n        z_direction(quaternion * Vector3(0, 0, 1)),\n        global_trans_positions(std::make_unique<Vector3[]>(NUM_TRANS_IN_UNIT)) {\n    const Eigen::Transform<double, 3, Eigen::Affine> transform_matrix = Eigen::Translation<double, 3>(position) * quaternion;\n    auto index = 0;\n    for (size_t y = 0; y < NUM_TRANS_Y; y++)\n      for (size_t x = 0; x < NUM_TRANS_X; x++) {\n        if (is_missing_transducer(x, y)) continue;\n        const Vector4 local_pos = Vector4(static_cast<double>(x) * TRANS_SPACING_MM, static_cast<double>(y) * TRANS_SPACING_MM, 0, 1);\n        const Vector4 global_pos = transform_matrix * local_pos;\n        global_trans_positions[index++] = Vector3(global_pos[0], global_pos[1], global_pos[2]);\n      }\n    g2l = transform_matrix.inverse();\n  }\n\n  Device(const Vector3& position, const Vector3& euler_angles)\n      : Device(position, Eigen::AngleAxis<double>(euler_angles.x(), Vector3::UnitZ()) * Eigen::AngleAxis<double>(euler_angles.y(), Vector3::UnitY()) *\n                             Eigen::AngleAxis<double>(euler_angles.z(), Vector3::UnitZ())) {}\n\n  Vector3 x_direction;\n  Vector3 y_direction;\n  Vector3 z_direction;\n  std::unique_ptr<Vector3[]> global_trans_positions;\n  Eigen::Transform<double, 3, Eigen::Affine> g2l;\n};\n\n/**\n * @brief Geometry of all devices\n */\nclass Geometry {\n public:\n  Geometry() : _wavelength(8.5), _attenuation(0) {}\n  ~Geometry() = default;\n  Geometry(const Geometry& v) noexcept = default;\n  Geometry& operator=(const Geometry& obj) = default;\n  Geometry(Geometry&& obj) = default;\n  Geometry& operator=(Geometry&& obj) = default;\n\n  /**\n   * @brief  Add new device with position and rotation. Note that the transform is done with order: Translate -> Rotate\n   * @param position Position of transducer #0, which is the one at the lower-left corner.\n   * (The lower-left corner is the one with the two missing transducers.)\n   * @param euler_angles ZYZ convention euler angle of the device\n   * @param group Grouping ID of the device\n   * @return an id of added device\n   */\n  size_t add_device(const Vector3& position, const Vector3& euler_angles, const size_t group = 0) {\n    const auto device_id = this->_devices.size();\n    this->_devices.emplace_back(position, euler_angles);\n    this->_group_map[device_id] = group;\n    return device_id;\n  }\n\n  /**\n   * @brief Same as add_device(const Vector3&, const Vector3&, const size_t), but using quaternion rather than zyz euler angles.\n   * @param position Position of transducer #0, which is the one at the lower-left corner.\n   * @param quaternion rotation quaternion of the device.\n   * @param group Grouping ID\n   * @return an id of added device\n   */\n  size_t add_device(const Vector3& position, const Quaternion& quaternion, const size_t group = 0) {\n    const auto device_id = this->_devices.size();\n    this->_devices.emplace_back(position, quaternion);\n    this->_group_map[device_id] = group;\n    return device_id;\n  }\n\n  /**\n   * @brief Delete device\n   * @param idx Index of the device to delete\n   * @return an index of deleted device\n   */\n  size_t del_device(const size_t idx) {\n    this->_devices.erase(this->_devices.begin() + idx);\n    return idx;\n  }\n\n  /**\n   * @brief Clear all devices\n   */\n  void clear_devices() { std::vector<Device>().swap(this->_devices); }\n\n  /**\n   * @brief ultrasound wavelength\n   */\n  double& wavelength() noexcept { return this->_wavelength; }\n\n  /**\n   * @brief attenuation coefficient\n   */\n  double& attenuation_coefficient() noexcept { return this->_attenuation; }\n\n  /**\n   * @brief Number of devices\n   */\n  [[nodiscard]] size_t num_devices() const noexcept { return this->_devices.size(); }\n\n  /**\n   * @brief Number of transducers\n   */\n  [[nodiscard]] size_t num_transducers() const noexcept { return this->num_devices() * NUM_TRANS_IN_UNIT; }\n\n  /**\n   * @brief Convert device ID into group ID\n   */\n  [[nodiscard]] size_t group_id_for_device_idx(const size_t device_idx) const { return this->_group_map.at(device_idx); }\n\n  /**\n   * @brief Position of a transducer specified by id\n   */\n  [[nodiscard]] const Vector3& position(const size_t global_transducer_idx) const {\n    const auto local_trans_id = global_transducer_idx % NUM_TRANS_IN_UNIT;\n    return position(device_idx_for_trans_idx(global_transducer_idx), local_trans_id);\n  }\n\n  /**\n   * @brief Position of a transducer specified by id\n   */\n  [[nodiscard]] const Vector3& position(const size_t device_idx, const size_t local_transducer_idx) const {\n    return this->_devices[device_idx].global_trans_positions[local_transducer_idx];\n  }\n\n  /**\n   * @brief Convert a global position to a local position\n   */\n  [[nodiscard]] Vector3 to_local_position(const size_t device_idx, const Vector3& global_position) const {\n    const Vector4 homo = Vector4(global_position[0], global_position[1], global_position[2], 1);\n    const Vector4 local_position = this->_devices[device_idx].g2l * homo;\n    return Vector3(local_position[0], local_position[1], local_position[2]);\n  }\n\n  /**\n   * @brief Normalized direction of a device\n   */\n  [[nodiscard]] const Vector3& direction(const size_t device_idx) const { return this->_devices[device_idx].z_direction; }\n\n  /**\n   * @brief Normalized long-axis direction of a device\n   */\n  [[nodiscard]] const Vector3& x_direction(const size_t device_idx) const { return this->_devices[device_idx].x_direction; }\n\n  /**\n   * @brief Normalized short-axis direction of a device\n   */\n  [[nodiscard]] const Vector3& y_direction(const size_t device_idx) const { return this->_devices[device_idx].y_direction; }\n\n  /**\n   * @brief Same as the direction()\n   */\n  [[nodiscard]] const Vector3& z_direction(const size_t device_idx) const { return this->_devices[device_idx].z_direction; }\n\n  /**\n   * @brief Convert transducer index into device index\n   */\n  [[nodiscard]] static size_t device_idx_for_trans_idx(const size_t transducer_idx) { return transducer_idx / NUM_TRANS_IN_UNIT; }\n\n private:\n  std::vector<Device> _devices;\n  std::map<size_t, size_t> _group_map;\n  double _wavelength;\n  double _attenuation;\n};\n}  // namespace core\n}  // namespace autd\n", "meta": {"hexsha": "e0affb9be4b156b47a7e215ee70e89d282af2c4d", "size": 7400, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "client/include/autd3/core/geometry.hpp", "max_stars_repo_name": "shinolab/autd3-library-software", "max_stars_repo_head_hexsha": "19a09e462c8a85ac965a110edfedb234cd155272", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2019-12-26T03:28:59.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-26T12:22:56.000Z", "max_issues_repo_path": "client/include/autd3/core/geometry.hpp", "max_issues_repo_name": "shinolab/autd3-library-software", "max_issues_repo_head_hexsha": "19a09e462c8a85ac965a110edfedb234cd155272", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 19.0, "max_issues_repo_issues_event_min_datetime": "2021-04-26T18:34:38.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-16T04:47:58.000Z", "max_forks_repo_path": "client/include/autd3/core/geometry.hpp", "max_forks_repo_name": "shinolab/autd3-library-software", "max_forks_repo_head_hexsha": "19a09e462c8a85ac965a110edfedb234cd155272", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2020-06-21T05:10:04.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-03T07:05:56.000Z", "avg_line_length": 33.9449541284, "max_line_length": 150, "alphanum_fraction": 0.7009459459, "num_tokens": 1886, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6959583376458152, "lm_q2_score": 0.45713671682749474, "lm_q1q2_score": 0.31814810952012895}}
{"text": "#include \"SRKSpinTracker.h\"\n#include <iostream>\n#include <algorithm>\n#pragma GCC diagnostic ignored \"-Wunused-local-typedefs\"\n#include <boost/numeric/odeint.hpp>\n\n#include \"SRKODEState.h\"\n\nusing namespace boost::numeric::odeint;\nusing namespace std;\n\n//typedef runge_kutta_cash_karp54< SRKMotionState > error_stepper_type;\ntypedef runge_kutta_dopri5<SRKODEState, SRKSpinFloat> error_stepper_type;\n\ntypedef controlled_runge_kutta<error_stepper_type> controlled_stepper_type;\n\n//#define SRKSPINTRACKERDEBUG 1\n\nSRKSpinTracker::SRKSpinTracker()\n{\n\teps_abs = 1.e-7;\n\teps_rel = 1.e-7;\n\tinitialStepSize = 0.01;\n\tstepsTaken = 0;\n\tconstStepper = false;\n}\nSRKSpinTracker::SRKSpinTracker(SRKGlobalField* theField):\n\tSRKSpinTracker()\n{\n\ttheEquationOfMotion.setGlobalField(theField);\n}\n\nSRKSpinTracker::~SRKSpinTracker()\n{\n\n}\n\nvoid SRKSpinTracker::trackSpin(SRKODEState& theState, double timeToTrack, std::vector<SRKODEState>* stepRecord, std::vector<double>* stepTimes)\n{\n\trunge_kutta4<SRKODEState, SRKSpinFloat> stepper;\n\tcontrolled_stepper_type controlled_stepper(default_error_checker<SRKSpinFloat, range_algebra, default_operations>(SRKSpinFloat(eps_abs), SRKSpinFloat(eps_rel), SRKSpinFloat(1.0), SRKSpinFloat(1.0)));\n\n#ifdef SRKSPINTRACKERDEBUG\n\tcout <<\"PRESPIN TRACKING\";\n\tprintMotionState(theState);\n#endif\n\n\tif(stepRecord != nullptr)\n\t{\n\t\tif(constStepper)\n\t\t{\n\t\t\tintegrate_const(stepper, theEquationOfMotion, theState, SRKSpinFloat(0.0), SRKSpinFloat(timeToTrack), SRKSpinFloat(initialStepSize), pushBackStateAndTime(stepRecord, stepTimes));\n\t\t}\n\t\telse\n\t\t{\n\t\t\tintegrate_adaptive(controlled_stepper, theEquationOfMotion, theState, theState[8], theState[8] + SRKSpinFloat(timeToTrack), SRKSpinFloat(initialStepSize), pushBackStateAndTime(stepRecord, stepTimes));\n\t\t}\n\n\t}\n\telse\n\t{\n\t\tif(constStepper)\n\t\t{\n\t\t\tintegrate_const(stepper, theEquationOfMotion, theState, SRKSpinFloat(0.0), SRKSpinFloat(timeToTrack), SRKSpinFloat(initialStepSize));\n\t\t}\n\t\telse\n\t\t{\n\t\t\tintegrate_adaptive(controlled_stepper, theEquationOfMotion, theState, theState[8], theState[8] + SRKSpinFloat(timeToTrack), SRKSpinFloat(initialStepSize));\n\t\t}\n\t}\n\ttheState[8] += timeToTrack;\n\n#ifdef SRKSPINTRACKERDEBUG\n\tcout <<\"PostSpin TRACKING\";\n\tprintMotionState(theState);\n#endif\n\n}\n\nvoid SRKSpinTracker::trackSpinAltA(SRKODEState& theState, double timeToTrack, std::vector<SRKODEState>* stepRecord, std::vector<double>* stepTimes)\n{\n\tSRKSpinFloat timeToTrackConv(timeToTrack);\n\terror_stepper_type theStepper;\n\tSRKSpinFloat dt = SRKSpinFloat(initialStepSize);\n\tSRKSpinFloat t0 = theState[8];  //Initial time simulation started at\n\tSRKSpinFloat deltaPhi;\n\tSRKSpinFloat val;\n\tSRKODEState previousState(9);\n\tSRKODEState stateError(9);\n\tbool potentialLastStep = false;\n\tfor (;;)\n\t{\n\n\t\tpreviousState = theState;\n\t\ttheStepper.do_step(theEquationOfMotion, theState, theState[8], dt, stateError);\n\t\tdeltaPhi = theState[6] - previousState[6];\n\t\tif(deltaPhi > SRKSpinFloat(.785)) //if it rotates greater than pi slow it down!\n\t\t{\n\t\t\tdt = dt * SRKSpinFloat(.5) / deltaPhi;\n\t\t\ttheState = previousState;\n\t\t\tpotentialLastStep = false;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tval = abs(stateError[6]);\n//\t\t\tval/=(eps_abs+eps_rel*abs(deltaPhi));\n\t\t\tval /= (SRKSpinFloat(eps_rel) * abs(deltaPhi));\n\t\t\tif(val > SRKSpinFloat(1.)) //too much error, slow down and repeat\n\t\t\t{\n//\t\t\t\tSRKSpinFloat a=(SRKSpinFloat(0.9)*SRKSpinFloat(pow(val,SRKSpinFloat(-1.)/(SRKSpinFloat(theStepper.error_order_value) - SRKSpinFloat(1.)))));\n\t\t\t\tSRKSpinFloat a = SRKSpinFloat(0);\n\t\t\t\tSRKSpinFloat b = SRKSpinFloat(0.2);\n\t\t\t\tdt = dt * max(a, b);\n\t\t\t\ttheState = previousState;\n\t\t\t\tpotentialLastStep = false;\n\t\t\t}\n\t\t\telse if(val < SRKSpinFloat(0.5))\n\t\t\t{\n\t\t\t\ttheState[8] += dt;\n\t\t\t\tstepsTaken++;\n\t\t\t\tif(stepRecord != nullptr && stepTimes != nullptr)\n\t\t\t\t{\n\t\t\t\t\tstepRecord->push_back(theState);\n\t\t\t\t\tstepTimes->push_back(static_cast<double>(theState[8]));\n\t\t\t\t}\n\t\t\t\tif(potentialLastStep) //If potential last step worked we break!\n\t\t\t\t{\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\n//\t\t\t\tSRKSpinFloat a=SRKSpinFloat(0.9)*SRKSpinFloat(pow(val,SRKSpinFloat(-1.)/SRKSpinFloat(theStepper.order_value )));\n\t\t\t\tSRKSpinFloat a = SRKSpinFloat(0);\n\t\t\t\tSRKSpinFloat b = SRKSpinFloat(5);\n\t\t\t\tdt = dt * max(a, b);\n\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\ttheState[8] += dt;\n\t\t\t\tstepsTaken++;\n\t\t\t\tif(stepRecord != nullptr && stepTimes != nullptr)\n\t\t\t\t{\n\t\t\t\t\tstepRecord->push_back(theState);\n\t\t\t\t\tstepTimes->push_back(static_cast<double>(theState[8]));\n\t\t\t\t}\n\t\t\t\tif(potentialLastStep) //If potential last step worked we break!\n\t\t\t\t{\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\n\t\t}\n\n\t\tif(theState[8] + dt > t0 + timeToTrackConv)\n\t\t{\n\t\t\tdt = t0 + timeToTrackConv - theState[8];\n\t\t\tpotentialLastStep = true;\n\t\t}\n\n\t}\n\n}\n", "meta": {"hexsha": "6ca4fb99623e838e39a74a51efb1fe200f9952fb", "size": 4629, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/SRKSpinTracker.cpp", "max_stars_repo_name": "nEDM-TUM/SRK", "max_stars_repo_head_hexsha": "523ebfc88dbc6f39f14fe37ba7a8f1570834cfc4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/SRKSpinTracker.cpp", "max_issues_repo_name": "nEDM-TUM/SRK", "max_issues_repo_head_hexsha": "523ebfc88dbc6f39f14fe37ba7a8f1570834cfc4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/SRKSpinTracker.cpp", "max_forks_repo_name": "nEDM-TUM/SRK", "max_forks_repo_head_hexsha": "523ebfc88dbc6f39f14fe37ba7a8f1570834cfc4", "max_forks_repo_licenses": ["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.3987730061, "max_line_length": 203, "alphanum_fraction": 0.7280190106, "num_tokens": 1431, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6959583250334526, "lm_q2_score": 0.45713671682749474, "lm_q1q2_score": 0.31814810375455493}}
{"text": "/*\n * This file is a part of the TChecker project.\n *\n * See files AUTHORS and LICENSE for copyright details.\n *\n */\n\n#include <boost/dynamic_bitset.hpp>\n\n#include \"tchecker/dbm/refdbm.hh\"\n#include \"tchecker/refzg/semantics.hh\"\n\nnamespace tchecker {\n\nnamespace refzg {\n\n/* Semantics functions */\n\n/*!\n  \\brief Compute initial zone with reference clocks w.r.t. standard semantics\n  \\note see tchecker::refzg::standard_semantics_t::initial\n*/\ntchecker::state_status_t standard_initial(tchecker::dbm::db_t * rdbm, tchecker::reference_clock_variables_t const & r,\n                                          boost::dynamic_bitset<> const & delay_allowed,\n                                          tchecker::clock_constraint_container_t const & invariant, tchecker::integer_t spread)\n{\n  tchecker::refdbm::zero(rdbm, r);\n\n  if (tchecker::refdbm::bound_spread(rdbm, r, spread) == tchecker::dbm::EMPTY)\n    return tchecker::STATE_CLOCKS_EMPTY_SPREAD;\n\n  if (tchecker::refdbm::constrain(rdbm, r, invariant) == tchecker::dbm::EMPTY)\n    return tchecker::STATE_CLOCKS_SRC_INVARIANT_VIOLATED;\n\n  return tchecker::STATE_OK;\n}\n\n/*!\n  \\brief Compute next zone with reference clocks w.r.t. standard semantics\n  \\note see tchecker::refzg::standard_semantics_t::next\n*/\ntchecker::state_status_t\nstandard_next(tchecker::dbm::db_t * rdbm, tchecker::reference_clock_variables_t const & r,\n              boost::dynamic_bitset<> const & src_delay_allowed, tchecker::clock_constraint_container_t const & src_invariant,\n              boost::dynamic_bitset<> const & sync_ref_clocks, tchecker::clock_constraint_container_t const & guard,\n              tchecker::clock_reset_container_t const & clkreset, boost::dynamic_bitset<> const & tgt_delay_allowed,\n              tchecker::clock_constraint_container_t const & tgt_invariant, tchecker::integer_t spread)\n{\n  if (src_delay_allowed.any()) {\n    tchecker::refdbm::asynchronous_open_up(rdbm, r, src_delay_allowed);\n\n    if (tchecker::refdbm::constrain(rdbm, r, src_invariant) == tchecker::dbm::EMPTY)\n      return tchecker::STATE_CLOCKS_SRC_INVARIANT_VIOLATED; // should never occur\n  }\n\n  if (tchecker::refdbm::bound_spread(rdbm, r, spread) == tchecker::dbm::EMPTY)\n    return tchecker::STATE_CLOCKS_EMPTY_SPREAD;\n\n  if (tchecker::refdbm::synchronize(rdbm, r, sync_ref_clocks) == tchecker::dbm::EMPTY)\n    return tchecker::STATE_CLOCKS_EMPTY_SYNC;\n\n  if (tchecker::refdbm::constrain(rdbm, r, guard) == tchecker::dbm::EMPTY)\n    return tchecker::STATE_CLOCKS_GUARD_VIOLATED;\n\n  tchecker::refdbm::reset(rdbm, r, clkreset);\n\n  if (tchecker::refdbm::constrain(rdbm, r, tgt_invariant) == tchecker::dbm::EMPTY)\n    return tchecker::STATE_CLOCKS_TGT_INVARIANT_VIOLATED;\n\n  return tchecker::STATE_OK;\n}\n\n/*!\n  \\brief Compute initial zone with reference clocks w.r.t. elapsed semantics\n  \\note see tchecker::refzg::elapsed_semantics_t::initial\n*/\ntchecker::state_status_t elapsed_initial(tchecker::dbm::db_t * rdbm, tchecker::reference_clock_variables_t const & r,\n                                         boost::dynamic_bitset<> const & delay_allowed,\n                                         tchecker::clock_constraint_container_t const & invariant, tchecker::integer_t spread)\n{\n  tchecker::refdbm::zero(rdbm, r);\n\n  if (tchecker::refdbm::constrain(rdbm, r, invariant) == tchecker::dbm::EMPTY)\n    return tchecker::STATE_CLOCKS_SRC_INVARIANT_VIOLATED;\n\n  if (delay_allowed.any()) {\n    tchecker::refdbm::asynchronous_open_up(rdbm, r, delay_allowed);\n\n    if (tchecker::refdbm::constrain(rdbm, r, invariant) == tchecker::dbm::EMPTY)\n      return tchecker::STATE_CLOCKS_SRC_INVARIANT_VIOLATED;\n  }\n\n  if (tchecker::refdbm::bound_spread(rdbm, r, spread) == tchecker::dbm::EMPTY)\n    return tchecker::STATE_CLOCKS_EMPTY_SPREAD;\n\n  return tchecker::STATE_OK;\n}\n\n/*!\n  \\brief Compute next zone with reference clocks w.r.t. elapsed semantics\n  \\note see tchecker::refzg::elapsed_semantics_t::next\n*/\ntchecker::state_status_t\nelapsed_next(tchecker::dbm::db_t * rdbm, tchecker::reference_clock_variables_t const & r,\n             boost::dynamic_bitset<> const & src_delay_allowed, tchecker::clock_constraint_container_t const & src_invariant,\n             boost::dynamic_bitset<> const & sync_ref_clocks, tchecker::clock_constraint_container_t const & guard,\n             tchecker::clock_reset_container_t const & clkreset, boost::dynamic_bitset<> const & tgt_delay_allowed,\n             tchecker::clock_constraint_container_t const & tgt_invariant, tchecker::integer_t spread)\n{\n  if (tchecker::refdbm::constrain(rdbm, r, src_invariant) == tchecker::dbm::EMPTY)\n    return tchecker::STATE_CLOCKS_SRC_INVARIANT_VIOLATED;\n\n  if (tchecker::refdbm::synchronize(rdbm, r, sync_ref_clocks) == tchecker::dbm::EMPTY)\n    return tchecker::STATE_CLOCKS_EMPTY_SYNC;\n\n  if (tchecker::refdbm::constrain(rdbm, r, guard) == tchecker::dbm::EMPTY)\n    return tchecker::STATE_CLOCKS_GUARD_VIOLATED;\n\n  tchecker::refdbm::reset(rdbm, r, clkreset);\n\n  if (tchecker::refdbm::constrain(rdbm, r, tgt_invariant) == tchecker::dbm::EMPTY)\n    return tchecker::STATE_CLOCKS_TGT_INVARIANT_VIOLATED;\n\n  if (tgt_delay_allowed.any()) {\n    tchecker::refdbm::asynchronous_open_up(rdbm, r, tgt_delay_allowed);\n\n    if (tchecker::refdbm::constrain(rdbm, r, tgt_invariant) == tchecker::dbm::EMPTY)\n      return tchecker::STATE_CLOCKS_TGT_INVARIANT_VIOLATED;\n  }\n\n  if (tchecker::refdbm::bound_spread(rdbm, r, spread) == tchecker::dbm::EMPTY)\n    return tchecker::STATE_CLOCKS_EMPTY_SPREAD;\n\n  return tchecker::STATE_OK;\n}\n\n/* standard_semantics_t */\n\ntchecker::state_status_t standard_semantics_t::initial(tchecker::dbm::db_t * rdbm,\n                                                       tchecker::reference_clock_variables_t const & r,\n                                                       boost::dynamic_bitset<> const & delay_allowed,\n                                                       tchecker::clock_constraint_container_t const & invariant,\n                                                       tchecker::integer_t spread)\n{\n  return tchecker::refzg::standard_initial(rdbm, r, delay_allowed, invariant, spread);\n}\n\ntchecker::state_status_t standard_semantics_t::next(\n    tchecker::dbm::db_t * rdbm, tchecker::reference_clock_variables_t const & r,\n    boost::dynamic_bitset<> const & src_delay_allowed, tchecker::clock_constraint_container_t const & src_invariant,\n    boost::dynamic_bitset<> const & sync_ref_clocks, tchecker::clock_constraint_container_t const & guard,\n    tchecker::clock_reset_container_t const & clkreset, boost::dynamic_bitset<> const & tgt_delay_allowed,\n    tchecker::clock_constraint_container_t const & tgt_invariant, tchecker::integer_t spread)\n{\n  return tchecker::refzg::standard_next(rdbm, r, src_delay_allowed, src_invariant, sync_ref_clocks, guard, clkreset,\n                                        tgt_delay_allowed, tgt_invariant, spread);\n}\n\n/* elapsed_semantics_t */\n\ntchecker::state_status_t elapsed_semantics_t::initial(tchecker::dbm::db_t * rdbm,\n                                                      tchecker::reference_clock_variables_t const & r,\n                                                      boost::dynamic_bitset<> const & delay_allowed,\n                                                      tchecker::clock_constraint_container_t const & invariant,\n                                                      tchecker::integer_t spread)\n{\n  return tchecker::refzg::elapsed_initial(rdbm, r, delay_allowed, invariant, spread);\n}\n\ntchecker::state_status_t\nelapsed_semantics_t::next(tchecker::dbm::db_t * rdbm, tchecker::reference_clock_variables_t const & r,\n                          boost::dynamic_bitset<> const & src_delay_allowed,\n                          tchecker::clock_constraint_container_t const & src_invariant,\n                          boost::dynamic_bitset<> const & sync_ref_clocks, tchecker::clock_constraint_container_t const & guard,\n                          tchecker::clock_reset_container_t const & clkreset, boost::dynamic_bitset<> const & tgt_delay_allowed,\n                          tchecker::clock_constraint_container_t const & tgt_invariant, tchecker::integer_t spread)\n{\n  return tchecker::refzg::elapsed_next(rdbm, r, src_delay_allowed, src_invariant, sync_ref_clocks, guard, clkreset,\n                                       tgt_delay_allowed, tgt_invariant, spread);\n}\n\n/* synchronizable_standard_semantics_t */\n\ntchecker::state_status_t synchronizable_standard_semantics_t::initial(tchecker::dbm::db_t * rdbm,\n                                                                      tchecker::reference_clock_variables_t const & r,\n                                                                      boost::dynamic_bitset<> const & delay_allowed,\n                                                                      tchecker::clock_constraint_container_t const & invariant,\n                                                                      tchecker::integer_t spread)\n{\n  tchecker::state_status_t status = tchecker::refzg::standard_initial(rdbm, r, delay_allowed, invariant, spread);\n  if (status != tchecker::STATE_OK)\n    return status;\n\n  if (!tchecker::refdbm::is_synchronizable(rdbm, r))\n    return tchecker::STATE_ZONE_EMPTY_SYNC;\n\n  return tchecker::STATE_OK;\n}\n\ntchecker::state_status_t synchronizable_standard_semantics_t::next(\n    tchecker::dbm::db_t * rdbm, tchecker::reference_clock_variables_t const & r,\n    boost::dynamic_bitset<> const & src_delay_allowed, tchecker::clock_constraint_container_t const & src_invariant,\n    boost::dynamic_bitset<> const & sync_ref_clocks, tchecker::clock_constraint_container_t const & guard,\n    tchecker::clock_reset_container_t const & clkreset, boost::dynamic_bitset<> const & tgt_delay_allowed,\n    tchecker::clock_constraint_container_t const & tgt_invariant, tchecker::integer_t spread)\n{\n  tchecker::state_status_t status = tchecker::refzg::standard_next(rdbm, r, src_delay_allowed, src_invariant, sync_ref_clocks,\n                                                                   guard, clkreset, tgt_delay_allowed, tgt_invariant, spread);\n  if (status != tchecker::STATE_OK)\n    return status;\n\n  if (!tchecker::refdbm::is_synchronizable(rdbm, r))\n    return tchecker::STATE_ZONE_EMPTY_SYNC;\n\n  return tchecker::STATE_OK;\n}\n\n/* synchronizable_elapsed_semantics_t */\n\ntchecker::state_status_t synchronizable_elapsed_semantics_t::initial(tchecker::dbm::db_t * rdbm,\n                                                                     tchecker::reference_clock_variables_t const & r,\n                                                                     boost::dynamic_bitset<> const & delay_allowed,\n                                                                     tchecker::clock_constraint_container_t const & invariant,\n                                                                     tchecker::integer_t spread)\n{\n  tchecker::state_status_t status = tchecker::refzg::elapsed_initial(rdbm, r, delay_allowed, invariant, spread);\n  if (status != tchecker::STATE_OK)\n    return status;\n\n  if (!tchecker::refdbm::is_synchronizable(rdbm, r))\n    return tchecker::STATE_ZONE_EMPTY_SYNC;\n\n  return tchecker::STATE_OK;\n}\n\ntchecker::state_status_t synchronizable_elapsed_semantics_t::next(\n    tchecker::dbm::db_t * rdbm, tchecker::reference_clock_variables_t const & r,\n    boost::dynamic_bitset<> const & src_delay_allowed, tchecker::clock_constraint_container_t const & src_invariant,\n    boost::dynamic_bitset<> const & sync_ref_clocks, tchecker::clock_constraint_container_t const & guard,\n    tchecker::clock_reset_container_t const & clkreset, boost::dynamic_bitset<> const & tgt_delay_allowed,\n    tchecker::clock_constraint_container_t const & tgt_invariant, tchecker::integer_t spread)\n{\n  tchecker::state_status_t status = tchecker::refzg::elapsed_next(rdbm, r, src_delay_allowed, src_invariant, sync_ref_clocks,\n                                                                  guard, clkreset, tgt_delay_allowed, tgt_invariant, spread);\n  if (status != tchecker::STATE_OK)\n    return status;\n\n  if (!tchecker::refdbm::is_synchronizable(rdbm, r))\n    return tchecker::STATE_ZONE_EMPTY_SYNC;\n\n  return tchecker::STATE_OK;\n}\n\n/* factory */\n\ntchecker::refzg::semantics_t * semantics_factory(enum tchecker::refzg::semantics_type_t semantics)\n{\n  switch (semantics) {\n  case tchecker::refzg::STANDARD_SEMANTICS:\n    return new tchecker::refzg::standard_semantics_t{};\n  case tchecker::refzg::ELAPSED_SEMANTICS:\n    return new tchecker::refzg::elapsed_semantics_t{};\n  case tchecker::refzg::SYNC_STANDARD_SEMANTICS:\n    return new tchecker::refzg::synchronizable_standard_semantics_t{};\n  case tchecker::refzg::SYNC_ELAPSED_SEMANTICS:\n    return new tchecker::refzg::synchronizable_elapsed_semantics_t{};\n  default:\n    throw std::invalid_argument(\"Unknown semantics over zones with reference clocks\");\n  }\n}\n\n} // end of namespace refzg\n\n} // end of namespace tchecker", "meta": {"hexsha": "475dafaf8dfcb2f500436dbf0c304913a6150b75", "size": 12905, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/refzg/semantics.cc", "max_stars_repo_name": "arnabSur/tchecker", "max_stars_repo_head_hexsha": "24ba7703068a41c6e9c613b4ef80ad6c788e65bc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2019-08-12T12:22:07.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-18T01:48:27.000Z", "max_issues_repo_path": "src/refzg/semantics.cc", "max_issues_repo_name": "arnabSur/tchecker", "max_issues_repo_head_hexsha": "24ba7703068a41c6e9c613b4ef80ad6c788e65bc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 40.0, "max_issues_repo_issues_event_min_datetime": "2019-07-03T04:31:19.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T03:40:43.000Z", "max_forks_repo_path": "src/refzg/semantics.cc", "max_forks_repo_name": "arnabSur/tchecker", "max_forks_repo_head_hexsha": "24ba7703068a41c6e9c613b4ef80ad6c788e65bc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2019-07-04T06:40:49.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-03T15:51:50.000Z", "avg_line_length": 47.098540146, "max_line_length": 128, "alphanum_fraction": 0.6799690043, "num_tokens": 3121, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6959583124210896, "lm_q2_score": 0.4571367168274948, "lm_q1q2_score": 0.3181480979889808}}
{"text": "/*\r\n * Copyright (c) 2011 Adrian Michel\r\n * http://www.amichel.com\r\n *\r\n * Permission to use, copy, modify, distribute and sell this \r\n * software and its documentation for any purpose is hereby \r\n * granted without fee, provided that both the above copyright \r\n * notice and this permission notice appear in all copies and in \r\n * the supporting documentation. \r\n *  \r\n * This library is distributed in the hope that it will be \r\n * useful. However, Adrian Michel makes no representations about\r\n * the suitability of this software for any purpose.  It is \r\n * provided \"as is\" without any express or implied warranty. \r\n * \r\n * Should you find this library useful, please email \r\n * info@amichel.com with a link or other reference \r\n * to your work. \r\n*/\r\n\r\n\r\n#ifndef DE_MUTATION_STRATEGY_HPP_INCLUDED\r\n#define DE_MUTATION_STRATEGY_HPP_INCLUDED\r\n\r\n// MS compatible compilers support #pragma once\r\n\r\n#if defined(_MSC_VER) && (_MSC_VER >= 1020)\r\n#pragma once\r\n#endif\r\n\r\n#include \"population.hpp\"\r\n\r\n#define URN_DEPTH 5\r\n\r\n#include <boost/tuple/tuple.hpp>\r\n\r\nnamespace de\r\n{\r\n\r\n/**\r\n * Parameters used by mutation strategies \r\n * weight factor, crossover factor and dither factor which is \r\n * calculated from the previous two \r\n * \r\n * @author adrian (12/1/2011)\r\n */\r\nclass mutation_strategy_arguments\r\n{\r\nprivate:\r\n\tconst double m_weight;\r\n\tconst double m_crossover;\r\n\tconst double m_dither;\r\n\r\npublic:\r\n\t/**\r\n\t * constructs a mutation_strategy_arguments object. \r\n\t *  \r\n\t * Besides the weight and crossover factors, which are supplied \r\n\t * by the calling code, this object holds a dither factor, which \r\n\t * is calculated upon construction, and is used by some mutation\r\n\t * strtegies.\r\n\t * \r\n\t * @author adrian (12/4/2011)\r\n\t * \r\n\t * @param weight weight factor which is a double between 0-2 as \r\n\t *  \t\t\t defined by the differential evolution algorithm\r\n\t * @param crossover crossover factor which is a double between \r\n\t *  \t\t\t\t0-1 as defined by the differential evolution\r\n\t *  \t\t\t\talgorithm\r\n\t */\r\n\tmutation_strategy_arguments( double weight, double crossover )\r\n\t: m_weight( weight ), m_crossover( crossover ), m_dither(  weight + genrand() * ( 1.0 - weight ) )\r\n\t{\r\n\t\t// todo: test or assert that weight and crossover are within bounds (0-1, 0-2 or something)\r\n\t}\r\n\r\n\t/**\r\n\t * returns the weight factor\r\n\t * \r\n\t * @author adrian (12/4/2011)\r\n\t * \r\n\t * @return double \r\n\t */\r\n\tdouble weight() const { return m_weight; }\r\n\t/**\r\n\t * returns the crossover factor\r\n\t * \r\n\t * @author adrian (12/4/2011)\r\n\t * \r\n\t * @return double \r\n\t */\r\n\tdouble crossover() const { return m_crossover; }\r\n\t/**\r\n\t * returns the dither factor\r\n\t * \r\n\t * @author adrian (12/4/2011)\r\n\t * \r\n\t * @return double \r\n\t */\r\n\tdouble dither() const { return m_dither; }\r\n};\r\n\r\n/**\r\n * A an abstract based class for mutation strategies \r\n *  \r\n * A mutation strategy defines how varaibles values are adjusted \r\n * during the optimization process \r\n * \r\n * @author adrian (12/1/2011)\r\n */\r\nclass mutation_strategy\r\n{\r\nprivate:\r\n\tmutation_strategy_arguments m_args;\r\n\tsize_t m_varCount;\r\n\r\nprotected:\r\n\t/**\r\n\t * Used to generate a set of 4 random size_t numbers \r\n\t * by the mutation strategy as indexes\r\n\t *  \r\n\t * The numbers must all be different, and also different from an\r\n\t * index supplied externally \r\n\t * \r\n\t * @author adrian (12/1/2011)\r\n\t */\r\n\tclass Urn\r\n\t{\r\n\t\tsize_t m_urn[ URN_DEPTH ];\r\n\r\n\tpublic:\r\n\t\t/**\r\n\t\t * Constructs an urn object\r\n\t\t * \r\n\t\t * @author adrian (12/4/2011)\r\n\t\t * \r\n\t\t * @param NP upper limit (exclusive) for the generated random \r\n\t\t *  \t\t numbers\r\n\t\t * @param avoid value to avoid when generating the random \r\n\t\t *  \t\t\tnumbers\r\n\t\t */\r\n\t\tUrn( size_t NP, size_t avoid )\r\n\t\t{\r\n\t\t\tdo m_urn[ 0 ] = genintrand( 0, NP, true ) ; while( m_urn[ 0 ] == avoid ) ;\r\n\t\t\tdo m_urn[ 1 ] = genintrand( 0, NP, true ) ; while( m_urn[ 1 ] == m_urn[ 0 ] || m_urn[ 1 ] == avoid );\r\n\t\t\tdo m_urn[ 2 ] = genintrand( 0, NP, true ) ; while( m_urn[ 2 ] == m_urn[ 1 ] || m_urn[ 2 ] == m_urn[ 0 ] || m_urn[ 2  ] == avoid );\r\n\t\t\tdo m_urn[ 3 ] = genintrand( 0, NP, true ) ; while( m_urn[ 3 ] == m_urn[ 2 ] || m_urn[ 3 ] == m_urn[ 1 ] || m_urn[ 3 ] == m_urn[ 0 ] || m_urn[ 3 ] == avoid );\r\n\t\t}\r\n\r\n\t\t/**\r\n\t\t * returns one of the four generated random numbers\r\n\t\t * \r\n\t\t * @author adrian (12/4/2011)\r\n\t\t * \r\n\t\t * @param index the index of the random number to return, can be \r\n\t\t *  \t\t\tbetween 0-3\r\n\t\t * \r\n\t\t * @return size_t \r\n\t\t */\r\n\t\tsize_t operator[]( size_t index ) const { assert( index < 4 ); return m_urn[ index ]; }\r\n\t};\r\n\r\n\r\npublic:\r\n\tvirtual ~mutation_strategy()\r\n\t{\r\n\t}\r\n\r\n\t/**\r\n\t * constructs a mutation strategy\r\n\t * \r\n\t * @author adrian (12/4/2011)\r\n\t * \r\n\t * @param varCount number of variables\r\n\t * @param args mutation strategy arguments\r\n\t */\r\n\tmutation_strategy( size_t varCount, const mutation_strategy_arguments& args )\r\n\t: m_args( args ), m_varCount( varCount )\r\n\t{\r\n\t}\r\n\r\n\t/**\r\n\t * type for the tuple returned by the operator() member.\r\n\t */\r\n\ttypedef boost::tuple< individual_ptr, de::DVectorPtr > mutation_info;\r\n\r\n\t/**\r\n\t * performs the mutation\r\n\t * \r\n\t * @author adrian (12/4/2011)\r\n\t * \r\n\t * @param pop a reference to the current population\r\n\t * @param bestIt the best individual of the previous generation\r\n\t * @param i the current individual index\r\n\t * \r\n\t * @return mutation_info tuple containing the mutated individual \r\n\t *  \t   and a vector of doubles of the same size as the\r\n\t *  \t   number of variables, used as origin to generate new\r\n\t *  \t   values in case they exceed the limits imposed by the\r\n\t *  \t   corresponding constraints\r\n\t */\r\n\tvirtual mutation_info operator()( const population& pop, individual_ptr bestIt, size_t i ) = 0;\r\n\r\n\t/**\r\n\t * returns the number of variables\r\n\t * \r\n\t * @author adrian (12/4/2011)\r\n\t * \r\n\t * @return size_t \r\n\t */\r\n\tsize_t varCount() const { return m_varCount; }\r\n\r\n\t/**\r\n\t * returns the weight factor\r\n\t * \r\n\t * @author adrian (12/4/2011)\r\n\t * \r\n\t * @return double \r\n\t */\r\n\tdouble weight() const { return m_args.weight(); }\r\n\r\n\t/**\r\n\t * returns the crossover factor\r\n\t * \r\n\t * @author adrian (12/4/2011)\r\n\t * \r\n\t * @return double \r\n\t */\r\n\tdouble crossover() const { return m_args.crossover(); }\r\n\r\n\t/**\r\n\t * returns the dither factor\r\n\t * \r\n\t * @author adrian (12/4/2011)\r\n\t * \r\n\t * @return double \r\n\t */\r\n\tdouble dither() const { return m_args.dither(); }\r\n};\r\n\r\ntypedef boost::shared_ptr< mutation_strategy > mutation_strategy_ptr;\r\n\r\n/**\r\n * Mutation strategy #1\r\n * \r\n * @author adrian (12/1/2011)\r\n */\r\nclass mutation_strategy_1 : public mutation_strategy\r\n{\r\npublic:\r\n\t/**\r\n\t * constructs a mutation strategy # 1\r\n\t * \r\n\t * @author adrian (12/4/2011)\r\n\t * \r\n\t * @param varCount number of variables\r\n\t * @param args mutation strategy arguments\r\n\t */\r\n\tmutation_strategy_1( size_t varCount, const mutation_strategy_arguments& args )\r\n\t: mutation_strategy( varCount, args )\r\n\t{\r\n\t}\r\n\r\n\t/**\r\n\t * performs the mutation\r\n\t * \r\n\t * @author adrian (12/4/2011)\r\n\t * \r\n\t * @param pop a reference to the current population\r\n\t * @param bestIt the best individual of the previous generation\r\n\t * @param i the current individual index\r\n\t * \r\n\t * @return mutation_info tuple containing the mutated individual \r\n\t *  \t   and a vector of doubles of the same size as the\r\n\t *  \t   number of variables, used as origin to generate new\r\n\t *  \t   values in case they exceed the limits imposed by the\r\n\t *  \t   corresponding constraints\r\n\t */\r\n\tmutation_info operator()( const population& pop, individual_ptr bestIt, size_t i )\r\n\t{\r\n\t\tassert( bestIt );\r\n\r\n\t\tde::DVectorPtr origin( boost::make_shared< de::DVector >( varCount() ) );\r\n\t\tindividual_ptr tmpInd( boost::make_shared< individual >( *pop[ i ]->vars() ) );\r\n\t\tUrn urn( pop.size(), i );\r\n\t\t\r\n\r\n\t\t// make sure j is within bounds\r\n\t\tsize_t j = genintrand( 0, varCount(), true );\r\n\t\tsize_t k = 0;\r\n\r\n\t\tdo\r\n\t\t{\r\n\t\t\t(*tmpInd->vars())[ j ] = (*pop[ urn[ 0 ] ]->vars() )[ j ] + weight() * ( (*pop[ urn[ 1 ] ]->vars() )[ j ] - (*pop[ urn[ 2 ] ]->vars())[ j ] );\r\n\r\n\t\t\tj = ++j % varCount();\r\n\t\t\t++k;\r\n\t\t} while( genrand() < crossover() && k < varCount() );\r\n\r\n\t\torigin = pop[ urn[ 0 ] ]->vars();\r\n\r\n\t\treturn mutation_info( tmpInd, origin );\r\n\t}\r\n\r\n};\r\n\r\n/**\r\n * mutation strategy # 2\r\n * \r\n * @author adrian (12/4/2011)\r\n */\r\nclass mutation_strategy_2 : public mutation_strategy\r\n{\r\npublic:\r\n\t/**\r\n\t * constructs a mutation strategy # 2\r\n\t * \r\n\t * @author adrian (12/4/2011)\r\n\t * \r\n\t * @param varCount number of variables\r\n\t * @param args mutation strategy arguments\r\n\t */\r\n\tmutation_strategy_2( size_t varCount, const mutation_strategy_arguments& args )\r\n\t: mutation_strategy( varCount, args )\r\n\t{\r\n\t}\r\n\r\n\t/**\r\n\t * performs the mutation\r\n\t * \r\n\t * @author adrian (12/4/2011)\r\n\t * \r\n\t * @param pop a reference to the current population\r\n\t * @param bestIt the best individual of the previous generation\r\n\t * @param i the current individual index\r\n\t * \r\n\t * @return mutation_info tuple containing the mutated individual \r\n\t *  \t   and a vector of doubles of the same size as the\r\n\t *  \t   number of variables, used as origin to generate new\r\n\t *  \t   values in case they exceed the limits imposed by the\r\n\t *  \t   corresponding constraints\r\n\t */\r\n\tmutation_info operator()( const population& pop, individual_ptr bestIt, size_t i )\r\n\t{\r\n\t\tassert( bestIt );\r\n\r\n\t\tde::DVectorPtr origin( boost::make_shared< de::DVector >( varCount() ) );\r\n\t\tindividual_ptr tmpInd( boost::make_shared< individual >( *pop[ i ]->vars() ) );\r\n\t\tUrn urn( pop.size(), i );\r\n\t\t\r\n\r\n\t\t// make sure j is within bounds\r\n\t\tsize_t j = genintrand( 0, varCount(), true );\r\n\t\tsize_t k = 0;\r\n\r\n\t\tdo\r\n\t\t{\r\n\t\t\t(*tmpInd->vars())[ j ] = (*tmpInd->vars())[ j ] + \r\n\t\t\t\tweight() * ( (*bestIt->vars() )[ j ] - (*tmpInd->vars())[ j ] ) +\r\n\t\t\t\tweight() * ( (*pop[ urn[ 1 ] ]->vars() )[ j ] - (*pop[ urn[ 2 ] ]->vars())[ j ] );\r\n\r\n\t\t\tj = ++j % varCount();\r\n\t\t\t++k;\r\n\t\t} while( genrand() < crossover() && k < varCount() );\r\n\r\n\t\torigin = pop[ urn[ 0 ] ]->vars();\r\n\r\n\t\treturn mutation_info( tmpInd, origin );\r\n\t}\r\n\r\n};\r\n\r\n/**\r\n * mutation strategy # 3\r\n * \r\n * @author adrian (12/4/2011)\r\n */\r\nclass mutation_strategy_3 : public mutation_strategy\r\n{\r\npublic:\r\n\t/**\r\n\t * constructs a mutation strategy # 3\r\n\t * \r\n\t * @author adrian (12/4/2011)\r\n\t * \r\n\t * @param varCount number of variables\r\n\t * @param args mutation strategy arguments\r\n\t */\r\n\tmutation_strategy_3( size_t varCount, const mutation_strategy_arguments& args )\r\n\t: mutation_strategy( varCount, args )\r\n\t{\r\n\t}\r\n\r\n\t/**\r\n\t * performs the mutation\r\n\t * \r\n\t * @author adrian (12/4/2011)\r\n\t * \r\n\t * @param pop a reference to the current population\r\n\t * @param bestIt the best individual of the previous generation\r\n\t * @param i the current individual index\r\n\t * \r\n\t * @return mutation_info tuple containing the mutated individual \r\n\t *  \t   and a vector of doubles of the same size as the\r\n\t *  \t   number of variables, used as origin to generate new\r\n\t *  \t   values in case they exceed the limits imposed by the\r\n\t *  \t   corresponding constraints\r\n\t */\r\n\tmutation_info operator()( const population& pop, individual_ptr bestIt, size_t i )\r\n\t{\r\n\t\tassert( bestIt );\r\n\r\n\t\tde::DVectorPtr origin( boost::make_shared< de::DVector >( varCount() ) );\r\n\t\tindividual_ptr tmpInd( boost::make_shared< individual >( *pop[ i ]->vars() ) );\r\n\t\tUrn urn( pop.size(), i );\r\n\t\t\r\n\r\n\t\t// make sure j is within bounds\r\n\t\tsize_t j = genintrand( 0, varCount(), true );\r\n\t\tsize_t k = 0;\r\n\r\n\t\tdo\r\n\t\t{\r\n\t\t\tdouble jitter = (0.0001* genrand() + weight() );\r\n\r\n\t\t\t(*tmpInd->vars())[ j ] = (*bestIt->vars() )[ j ] + jitter * ( (*pop[ urn[ 1 ] ]->vars() )[ j ] - (*pop[ urn[ 2 ] ]->vars())[ j ] );\r\n\r\n\t\t\tj = ++j % varCount();\r\n\t\t\t++k;\r\n\t\t} while( genrand() < crossover() && k < varCount() );\r\n\r\n\t\torigin = pop[ urn[ 0 ] ]->vars();\r\n\r\n\t\treturn mutation_info( tmpInd, origin );\r\n\t}\r\n};\r\n\r\n/**\r\n * mutation strategy # 4\r\n * \r\n * @author adrian (12/4/2011)\r\n */\r\nclass mutation_strategy_4 : public mutation_strategy\r\n{\r\npublic:\r\n\t/**\r\n\t * constructs a mutation strategy # 4\r\n\t * \r\n\t * @author adrian (12/4/2011)\r\n\t * \r\n\t * @param varCount number of variables\r\n\t * @param args mutation strategy arguments\r\n\t */\r\n\tmutation_strategy_4( size_t varCount, const mutation_strategy_arguments& args )\r\n\t: mutation_strategy( varCount, args )\r\n\t{\r\n\t}\r\n\r\n\t/**\r\n\t * performs the mutation\r\n\t * \r\n\t * @author adrian (12/4/2011)\r\n\t * \r\n\t * @param pop a reference to the current population\r\n\t * @param bestIt the best individual of the previous generation\r\n\t * @param i the current individual index\r\n\t * \r\n\t * @return mutation_info tuple containing the mutated individual \r\n\t *  \t   and a vector of doubles of the same size as the\r\n\t *  \t   number of variables, used as origin to generate new\r\n\t *  \t   values in case they exceed the limits imposed by the\r\n\t *  \t   corresponding constraints\r\n\t */\r\n\tmutation_info operator()( const population& pop, individual_ptr bestIt, size_t i )\r\n\t{\r\n\t\tassert( bestIt );\r\n\r\n\t\tde::DVectorPtr origin( boost::make_shared< de::DVector >( varCount() ) );\r\n\t\tindividual_ptr tmpInd( boost::make_shared< individual >( *pop[ i ]->vars() ) );\r\n\t\tUrn urn( pop.size(), i );\r\n\t\t\r\n\r\n\t\t// make sure j is within bounds\r\n\t\tsize_t j = genintrand( 0, varCount(), true );\r\n\t\tsize_t k = 0;\r\n\r\n\t\tdouble factor( weight() + genrand() * ( 1.0 - weight() ) );\r\n\r\n\t\tdo\r\n\t\t{\r\n\t\t\tdouble jitter = (0.0001* genrand() + weight() );\r\n\r\n\t\t\t(*tmpInd->vars())[ j ] = (*pop[ urn[ 0 ] ]->vars() )[ j ] +\r\n\t\t\t\tfactor * ( (*pop[ urn[ 1 ] ]->vars() )[ j ] - (*pop[ urn[ 2 ] ]->vars())[ j ] );\r\n\r\n\t\t\tj = ++j % varCount();\r\n\t\t\t++k;\r\n\t\t} while( genrand() < crossover() && k < varCount() );\r\n\r\n\t\torigin = pop[ urn[ 0 ] ]->vars();\r\n\r\n\t\treturn mutation_info( tmpInd, origin );\r\n\t}\r\n\r\n};\r\n\r\n\r\n\r\n/**\r\n * Mutation strategy # 5\r\n * \r\n * @author adrian (12/1/2011)\r\n */\r\nclass mutation_strategy_5 : public mutation_strategy\r\n{\r\n\r\npublic:\r\n\t/**\r\n\t * constructs a mutation strategy # 5\r\n\t * \r\n\t * @author adrian (12/4/2011)\r\n\t * \r\n\t * @param varCount number of variables\r\n\t * @param args mutation strategy arguments\r\n\t */\r\n\tmutation_strategy_5( size_t varCount, const mutation_strategy_arguments& args )\r\n\t: mutation_strategy( varCount, args )\r\n\t{\r\n\t}\r\n\r\n\t/**\r\n\t * performs the mutation\r\n\t * \r\n\t * @author adrian (12/4/2011)\r\n\t * \r\n\t * @param pop a reference to the current population\r\n\t * @param bestIt the best individual of the previous generation\r\n\t * @param i the current individual index\r\n\t * \r\n\t * @return mutation_info tuple containing the mutated individual \r\n\t *  \t   and a vector of doubles of the same size as the\r\n\t *  \t   number of variables, used as origin to generate new\r\n\t *  \t   values in case they exceed the limits imposed by the\r\n\t *  \t   corresponding constraints\r\n\t */\r\n\tmutation_info operator()( const population& pop, individual_ptr bestIt, size_t i )\r\n\t{\r\n\t\tassert( bestIt );\r\n\r\n\t\tde::DVectorPtr origin( boost::make_shared< de::DVector >( varCount() ) );\r\n\t\tindividual_ptr tmpInd( boost::make_shared< individual >( *pop[ i ]->vars() ) );\r\n\t\tUrn urn( pop.size(), i );\r\n\r\n\t\t// make sure j is within bounds\r\n\t\tsize_t j = genintrand( 0, varCount(), true );\r\n\t\tsize_t k = 0;\r\n\r\n\t\tdo\r\n\t\t{\r\n\t\t\t(*tmpInd->vars())[ j ] = (*pop[ urn[ 0 ] ]->vars() )[ j ] + dither() * ( (*pop[ urn[ 1 ] ]->vars() )[ j ] - (*pop[ urn[ 2 ] ]->vars() )[ j ] );\r\n\r\n\t\t\tj = ++j % varCount();\r\n\t\t\t++k;\r\n\t\t} while( genrand() < crossover() && k < varCount() );\r\n\r\n\t\torigin = pop[ urn[ 0 ] ]->vars();\r\n\t\treturn mutation_info( tmpInd, origin );\r\n\t}\r\n\r\n};\r\n\r\n}\r\n\r\n#endif //DE_MUTATION_STRATEGY_HPP_INCLUDED\r\n", "meta": {"hexsha": "a1c2083919d227d7d18ac9725fe8cd5a2838f37d", "size": 15414, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/de/mutation_strategy.hpp", "max_stars_repo_name": "gchoinka/gpcxx", "max_stars_repo_head_hexsha": "143398d8a12cdc39735e6ef50c3f8a44a6e6360f", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 21.0, "max_stars_repo_stars_event_min_datetime": "2015-05-15T08:01:37.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-12T07:28:54.000Z", "max_issues_repo_path": "third_party/de/mutation_strategy.hpp", "max_issues_repo_name": "gchoinka/gpcxx", "max_issues_repo_head_hexsha": "143398d8a12cdc39735e6ef50c3f8a44a6e6360f", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2015-03-26T23:48:04.000Z", "max_issues_repo_issues_event_max_datetime": "2016-02-29T14:16:37.000Z", "max_forks_repo_path": "third_party/de/mutation_strategy.hpp", "max_forks_repo_name": "gchoinka/gpcxx", "max_forks_repo_head_hexsha": "143398d8a12cdc39735e6ef50c3f8a44a6e6360f", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2015-02-12T21:39:01.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-01T05:14:08.000Z", "avg_line_length": 26.8069565217, "max_line_length": 161, "alphanum_fraction": 0.618269106, "num_tokens": 4363, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5544704796847396, "lm_q2_score": 0.5736784074525098, "lm_q1q2_score": 0.31808774176497057}}
{"text": "// Copyright 2021 Apex.AI, Inc.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//     http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//\n// Co-developed by Tier IV, Inc. and Apex.AI, Inc.\n\n#ifndef MEASUREMENT_CONVERSION__EIGEN_UTILS_HPP_\n#define MEASUREMENT_CONVERSION__EIGEN_UTILS_HPP_\n\n#include <Eigen/Geometry>\n\n\nnamespace autoware\n{\nnamespace common\n{\nnamespace state_estimation\n{\n\n///\n/// @brief      This class describes a data storage order.\n///\nenum class DataStorageOrder\n{\n  kRowMajor,\n  kColumnMajor\n};\n\nnamespace detail\n{\n///\n/// @brief      A functor to compute an index in the data array.\n///\nclass Index\n{\npublic:\n  ///\n  /// @brief      Create an index functor.\n  ///\n  /// @param[in]  start_index    The start index at which to start the count.\n  /// @param[in]  stride         The stride of the data, i.e., step to the next row or column.\n  /// @param[in]  storage_order  How the data should be stored in memory.\n  ///\n  Index(\n    const std::int32_t start_index,\n    const std::int32_t stride,\n    const DataStorageOrder storage_order)\n  : m_start_index{start_index}, m_stride{stride}, m_storage_order{storage_order} {}\n\n  ///\n  /// @brief      Compute an index using the stored starting index, stride and storage order.\n  ///\n  /// @param[in]  row   Query row\n  /// @param[in]  col   Query column\n  ///\n  /// @return     A 1D index in the underlying data array\n  ///\n  std::size_t operator()(const Eigen::Index row, const Eigen::Index col) const\n  {\n    switch (m_storage_order) {\n      case DataStorageOrder::kRowMajor:\n        return static_cast<std::size_t>(m_start_index + row * m_stride + col);\n      case DataStorageOrder::kColumnMajor:\n        return static_cast<std::size_t>(m_start_index + col * m_stride + row);\n    }\n    throw std::runtime_error(\"Unexpected storage order\");\n  }\n\nprivate:\n  std::int32_t m_start_index{};\n  std::int32_t m_stride{};\n  DataStorageOrder m_storage_order{};\n};\n}  // namespace detail\n\n///\n/// @brief      Downscale the isometry to a lower dimension if needed.\n///\n/// @param[in]  isometry              The isometry transform\n///\n/// @tparam     kStateDimensionality  Dimensionality of the space.\n/// @tparam     FloatT                Type of scalar.\n///\n/// @return     Downscaled isometry.\n///\ntemplate<std::int32_t kStateDimensionality, typename FloatT>\nstatic constexpr Eigen::Transform<\n  FloatT, kStateDimensionality, Eigen::TransformTraits::Isometry> downscale_isometry(\n  const Eigen::Transform<FloatT, 3, Eigen::TransformTraits::Isometry> & isometry)\n{\n  static_assert(kStateDimensionality <= 3, \"We only handle scaling the isometry down.\");\n  using Isometry = Eigen::Transform<\n    FloatT, kStateDimensionality, Eigen::TransformTraits::Isometry>;\n  Isometry result{Isometry::Identity()};\n  result.linear() = isometry.rotation()\n    .template block<kStateDimensionality, kStateDimensionality>(0, 0);\n  result.translation() = isometry.translation().topRows(kStateDimensionality);\n  return result;\n}\n\n///\n/// @brief      Transform a given array to an Eigen matrix using the specified stride and a starting\n///             index within this array.\n///\n/// @details    The function converts a given array into an Eigen matrix using the given starting\n///             index and stride. The function will take the number of rows and columns from the\n///             provided parameters and will iterate the given array as many times as needed to fill\n///             all elements of the resulting matrix. It is assumed that there are no gaps between\n///             the elements in a single row but that the columns are spaced `stride` apart.\n///\n/// @note       The storage order only refers to the storage order expected from the array, not from\n///             the Eigen matrix. The Eigen matrices are expected to be column-major as per default.\n///\n/// @throws     std::runtime_error  if there is not enough elements in the array to perform a full\n///                                 conversion of all the asked elements.\n///\n/// @param[in]  array          The given array (e.g. a covariance array from a message)\n/// @param[in]  start_index    The start index of the first element in an array to be copied\n/// @param[in]  stride         How big the step to the next row is in terms of indices in the array\n/// @param[in]  storage_order  The storage order of the data in the input array (row-major for ROS)\n///\n/// @tparam     kRows          Number of rows in the resulting matrix\n/// @tparam     kCols          Number of columns in the resulting matrix\n/// @tparam     ScalarT        Scalar type (inferred)\n/// @tparam     kSize          Size of the input array (inferred)\n///\n/// @return     An Eigen matrix that stores the requested data.\n///\ntemplate<std::int32_t kRows, std::int32_t kCols, typename ScalarT, std::size_t kSize>\nEigen::Matrix<ScalarT, kRows, kCols> array_to_matrix(\n  const std::array<ScalarT, kSize> & array,\n  const std::int32_t start_index,\n  const std::int32_t stride,\n  const DataStorageOrder storage_order)\n{\n  using Mat = Eigen::Matrix<ScalarT, kRows, kCols>;\n  const detail::Index index{start_index, stride, storage_order};\n  Mat res{Mat::Zero()};\n  const auto max_index = index(res.rows() - 1, res.cols() - 1);\n  if (max_index >= array.size()) {\n    throw std::runtime_error(\n            \"Trying to access out of bound memory at index \" +\n            std::to_string(max_index) + \" of an array with size: \" + std::to_string(array.size()));\n  }\n\n  for (auto col = 0; col < kCols; ++col) {\n    for (auto row = 0; row < kRows; ++row) {\n      res(row, col) = array[index(row, col)];\n    }\n  }\n  return res;\n}\n\n///\n/// @brief      Sets data in an array from a given Eigen matrix.\n///\n/// @note       The storage order only refers to the storage order expected from the array, not from\n///             the Eigen matrix. The Eigen matrices are expected to be column-major as per default.\n///\n/// @param      array          The array for which the data is set\n/// @param[in]  matrix         The matrix that has the data that is to be copied\n/// @param[in]  start_index    The start index in the output data array\n/// @param[in]  stride         The step that brings the index to the next row/column\n/// @param[in]  storage_order  The storage order of the output data\n///\n/// @tparam     kRows          Number of rows in the input matrix, inferred by the compiler.\n/// @tparam     kCols          Number of columns in the input matrix, inferred by the compiler.\n/// @tparam     ScalarT        Type of underlying data elements, inferred by the compiler.\n/// @tparam     kSize          Size of the input matrix, inferred by the compiler.\n///\ntemplate<std::int32_t kRows, std::int32_t kCols, typename ScalarT, std::size_t kSize>\nvoid set_from_matrix(\n  std::array<ScalarT, kSize> & array,\n  const Eigen::Matrix<ScalarT, kRows, kCols> & matrix,\n  const std::int32_t start_index,\n  const std::int32_t stride,\n  const DataStorageOrder storage_order)\n{\n  const detail::Index index{start_index, stride, storage_order};\n  const auto max_index = index(matrix.rows() - 1, matrix.cols() - 1);\n  if (max_index >= array.size()) {\n    throw std::runtime_error(\n            \"Trying to access out of bound memory at index \" +\n            std::to_string(max_index) + \" of an array with size: \" + std::to_string(array.size()));\n  }\n  for (auto col = 0; col < kCols; ++col) {\n    for (auto row = 0; row < kRows; ++row) {\n      array[index(row, col)] = matrix(row, col);\n    }\n  }\n}\n\n\n///\n/// @brief      Get a slice of a given matrix.\n///\n/// @details    Given two sequences for rows and for columns generate a new matrix that contains\n///             only rows and columns in those sequences.\n///\n/// @param[in]  matrix         The given matrix\n/// @param[in]  sequence_rows  The sequence of rows to include in the slice\n/// @param[in]  sequence_cols  The sequence of columns to include in the slice\n///\n/// @tparam     ScalarT        Type of underlying data\n/// @tparam     kRows          Number of rows in a query matrix\n/// @tparam     kCols          Number of columns in a query matrix\n/// @tparam     kSeqRowsSize   Number of rows in the slice\n/// @tparam     kSeqColsSize   Number of columns in the slice\n///\n/// @return     A matrix representing a slice of the original matrix.\n///\ntemplate<\n  typename ScalarT,\n  std::int32_t kRows,\n  std::int32_t kCols,\n  std::size_t kSeqRowsSize,\n  std::size_t kSeqColsSize>\nEigen::Matrix<\n  ScalarT, static_cast<std::int32_t>(kSeqRowsSize), static_cast<std::int32_t>(kSeqColsSize)>\nslice(\n  const Eigen::Matrix<ScalarT, kRows, kCols> matrix,\n  const std::array<Eigen::Index, kSeqRowsSize> & sequence_rows,\n  const std::array<Eigen::Index, kSeqColsSize> & sequence_cols)\n{\n  using Mat = Eigen::Matrix<\n    ScalarT, static_cast<std::int32_t>(kSeqRowsSize), static_cast<std::int32_t>(kSeqColsSize)>;\n  Mat res{Mat::Zero()};\n  for (auto col = 0UL; col < kSeqColsSize; ++col) {\n    for (auto row = 0UL; row < kSeqRowsSize; ++row) {\n      res(static_cast<Eigen::Index>(row), static_cast<Eigen::Index>(col)) =\n        matrix(sequence_rows[row], sequence_cols[col]);\n    }\n  }\n  return res;\n}\n\n}  // namespace state_estimation\n}  // namespace common\n}  // namespace autoware\n\n\n#endif  // MEASUREMENT_CONVERSION__EIGEN_UTILS_HPP_\n", "meta": {"hexsha": "f3eeca28dd34c5670fc29ece3867b0ce8ad5d769", "size": 9685, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/common/measurement_conversion/include/measurement_conversion/eigen_utils.hpp", "max_stars_repo_name": "ruvus/auto", "max_stars_repo_head_hexsha": "25ae62d6e575cae40212356eed43ec3e76e9a13e", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 19.0, "max_stars_repo_stars_event_min_datetime": "2021-05-28T06:14:21.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-10T10:03:08.000Z", "max_issues_repo_path": "src/common/measurement_conversion/include/measurement_conversion/eigen_utils.hpp", "max_issues_repo_name": "ruvus/auto", "max_issues_repo_head_hexsha": "25ae62d6e575cae40212356eed43ec3e76e9a13e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 222.0, "max_issues_repo_issues_event_min_datetime": "2021-10-29T22:00:27.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-29T20:56:34.000Z", "max_forks_repo_path": "src/common/measurement_conversion/include/measurement_conversion/eigen_utils.hpp", "max_forks_repo_name": "ruvus/auto", "max_forks_repo_head_hexsha": "25ae62d6e575cae40212356eed43ec3e76e9a13e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 14.0, "max_forks_repo_forks_event_min_datetime": "2021-05-29T14:59:17.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-10T10:03:09.000Z", "avg_line_length": 38.2806324111, "max_line_length": 100, "alphanum_fraction": 0.6740320083, "num_tokens": 2422, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5736784220301065, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.31808774140079743}}
{"text": "/**\n * @file wykobi.hpp\n * @author Han Luo <han.luo@gmail.com>\n *\n * @copyright Copyright (c) 2021\n *\n */\n/*\n(***********************************************************************)\n(*                                                                     *)\n(* Wykobi Computational Geometry Library                               *)\n(* Release Version 0.0.5                                               *)\n(* http://www.wykobi.com                                               *)\n(* Copyright (c) 2005-2019 Arash Partow, All Rights Reserved.          *)\n(*                                                                     *)\n(* The Wykobi computational geometry library and its components are    *)\n(* supplied under the terms of the open source MIT License.            *)\n(* The contents of the Wykobi computational geometry library and its   *)\n(* components may not be copied or disclosed except in accordance with *)\n(* the terms of the MIT License.                                       *)\n(*                                                                     *)\n(* URL: https://opensource.org/licenses/MIT                            *)\n(*                                                                     *)\n(***********************************************************************)\n*/\n\n\n#ifndef INCLUDE_WYKOBI\n#define INCLUDE_WYKOBI\n\n\n#include <limits>\n#include <algorithm>\n#include <iterator>\n#include <ostream>\n#include <vector>\n#include <cassert>\n#include <iomanip>\n#include <Eigen/Dense>\n#include \"wykobi_math.hpp\"\n\n#ifndef CURRENT_FUNCTION\n#if defined(__GNUC__) || (defined(__ICC) && (__ICC >= 600))\n# define CURRENT_FUNCTION __PRETTY_FUNCTION__\n#elif defined(__FUNCSIG__)\n# define CURRENT_FUNCTION __FUNCSIG__\n#elif (defined(__INTEL_COMPILER) && (__INTEL_COMPILER >= 600))\n# define CURRENT_FUNCTION __FUNCTION__\n#elif defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901)\n# define CURRENT_FUNCTION __func__\n#elif defined(__cplusplus) && (__cplusplus >= 201103)\n# define CURRENT_FUNCTION __func__\n#else\n# define CURRENT_FUNCTION \"(unknown)\"\n#endif\n#endif\n\n#ifndef wykobi_error_msg_if\n#include <stdexcept>\n#include <sstream>\n#define wykobi_error_msg_if(X, Y)                \\\n  do {                                    \\\n    if (X) {                              \\\n      std::stringstream ss;               \\\n      ss << \"\\033[1;31m\" << CURRENT_FUNCTION << \"\\033[0m \" << Y << std::endl;  \\\n      throw std::runtime_error(ss.str()); \\\n    }                                     \\\n  } while (0)\n#endif\n\nnamespace wykobi\n{\n\n   static const char VERSION_INFORMATION[] = \"Wykobi Version 0.0.5\";\n   static const char AUTHOR_INFORMATION[]  = \"Arash Partow\";\n   static const char EPOCH_VERSION[]       = \"C578AC5A:35A4123B:DF32F721\";\n\n   #ifndef WYKOBI\n    #define WYKOBI\n   #endif\n\n\n   /****************************************************************************/\n   /********************[ Basic Geometric Structure Types ]*********************/\n   /****************************************************************************/\n\n   /************[ Geometric Entity ]*************/\n    class geometric_entity{};\n\n    enum geometric_type  {\n                          ePoint2D,\n                          ePoint3D,\n                          eSegment2D,\n                          eSegment3D,\n                          eRectangle,\n                          eBox,\n                          eLine2D,\n                          eLine3D,\n                          eTriangle2D,\n                          eTriangle3D,\n                          eQuadix2D,\n                          eQuadix3D,\n                          eRay2D,\n                          eRay3D,\n                          eCircle,\n                          eSphere\n                         };\n\n\n   /**************[ Vertex type ]***************/\n\n   template <typename T, std::size_t D>\n   class pointnd;\n\n   template <typename T = Float>\n   class point2d : public geometric_entity\n   {\n   public:\n\n      typedef T           type;\n      typedef const type& const_reference;\n      typedef       type& reference;\n\n      point2d() : x(T(0.0)), y(T(0.0)){}\n      point2d(T _x, T _y) : x(_x), y(_y) {}\n      point2d(const pointnd<T,2>& point) : x(point[0]), y(point[1]){}\n      point2d(const Eigen::Vector2d& p) : x(static_cast<T>(p(0))), y(static_cast<T>(p(1))) {}\n     ~point2d(){}\n\n      inline point2d<T>& operator=(const pointnd<T,2>& point)\n      {\n         x = point[0];\n         y = point[1];\n         return *this;\n      }\n\n      inline point2d<T>& operator=(const Eigen::Vector2d& p)\n      {\n        x = static_cast<T>(p(0));\n        y = static_cast<T>(p(1));\n        return *this;\n      }\n\n      inline reference       operator()(const std::size_t& index)       { return ((0 == index)? x : y); }\n      inline const_reference operator()(const std::size_t& index) const { return ((0 == index)? x : y); }\n\n      inline reference       operator[](const std::size_t& index)       { return ((0 == index)? x : y); }\n      inline const_reference operator[](const std::size_t& index) const { return ((0 == index)? x : y); }\n\n      friend std::ostream& operator<<(std::ostream& os, const point2d& p) {\n         os << std::scientific\n            << std::showpoint\n            << std::setprecision(std::numeric_limits<T>::max_digits10)\n            << \"[\" << p.x << \", \" << p.y << \"]\";\n         return os;\n      }\n\n      inline point2d<T> operator-() const {\n        return point2d(-x, -y);\n      }\n\n      T x,y;\n   };\n   template <typename T> inline point2d<T> operator*(const point2d<T>& point, const T& scale);\n   template <typename T> inline point2d<T> operator*(const T& scale, const point2d<T>& point);\n   template <typename T> inline point2d<T> operator+(const point2d<T>& p1, const point2d<T>& p2);\n   template <typename T>\n   inline point2d<T> operator-(const point2d<T>& p1) {\n      return point2d<T>(-p1.x, -p1.y);\n   }\n\n   template <typename T = Float>\n   class point3d : public geometric_entity\n   {\n   public:\n\n      typedef T           Type;\n      typedef const Type& const_reference;\n      typedef       Type& reference;\n\n      point3d() : x(T(0.0)), y(T(0.0)), z(T(0.0)){}\n      point3d(T _x, T _y, T _z) : x(_x), y(_y), z(_z) {}\n      point3d(const pointnd<T,3>& point) : x(point[0]), y(point[1]), z(point[2]){}\n      point3d(const Eigen::Vector3d& p) : x(static_cast<T>(p(0))), y(static_cast<T>(p(1))), z(static_cast<T>(p(2))) {}\n     ~point3d(){}\n\n      inline point3d<T>& operator=(const pointnd<T,3>& point)\n      {\n         x = point[0];\n         y = point[1];\n         z = point[2];\n         return *this;\n      }\n\n      inline point3d<T>& operator=(const Eigen::Vector3d& p)\n      {\n        x = static_cast<T>(p(0));\n        y = static_cast<T>(p(1));\n        z = static_cast<T>(p(2));\n        return *this;\n      }\n\n      inline reference       operator()(const std::size_t& index)       { return value(index); }\n      inline const_reference operator()(const std::size_t& index) const { return value(index); }\n\n      inline reference       operator[](const std::size_t& index)       { return value(index); }\n      inline const_reference operator[](const std::size_t& index) const { return value(index); }\n\n      friend std::ostream& operator<<(std::ostream& os, const point3d& p) {\n         os << std::scientific\n            << std::showpoint\n            << std::setprecision(std::numeric_limits<T>::max_digits10)\n            << \"[\" << p.x << \", \" << p.y  << \", \" << p.z << \"]\";\n         return os;\n      }\n\n      inline point3d<T> operator-() const {\n        return point3d(-x, -y, -z);\n      }\n\n      T x,y,z;\n   private:\n      inline reference value(const std::size_t& index)\n      {\n         switch(index)\n         {\n            case 0  : return x;\n            case 1  : return y;\n            case 2  : return z;\n            default : return x;\n         }\n      }\n\n      inline const_reference value(const std::size_t& index) const\n      {\n         switch(index)\n         {\n            case 0  : return x;\n            case 1  : return y;\n            case 2  : return z;\n            default : return x;\n         }\n      }\n   };\n   template <typename T> inline point3d<T> operator*(const point3d<T>& point, const T& scale);\n   template <typename T> inline point3d<T> operator*(const T& scale, const point3d<T>& point);\n   template <typename T> inline point3d<T> operator+(const point3d<T>& p1, const point3d<T>& p2);\n   template <typename T>\n   inline point3d<T> operator-(const point3d<T>& p1) {\n      return point3d<T>(-p1.x, -p1.y, -p1.z);\n   }\n   template <typename T, std::size_t D>\n   class pointnd : public geometric_entity\n   {\n   public:\n\n      typedef const T& const_reference;\n      typedef       T& reference;\n\n      pointnd(){ clear(); }\n      pointnd(const T& v0) { v[0] = v0; }\n      pointnd(const T& v0, const T& v1) { v[0] = v0; v[1] = v1; }\n      pointnd(const T& v0,const T& v1, const T& v2) { v[0] = v0; v[1] = v1; v[2] = v2; }\n      pointnd(const T& v0,const T& v1, const T& v2, const T& v3) { v[0] = v0; v[1] = v1; v[2] = v2; v[3] = v3; }\n      pointnd(const pointnd<T,D>& point)\n      {\n         for (std::size_t i = 0; i < D; ++i) v[i] = point.v[i];\n      }\n\n      pointnd(const point2d<T>& point)\n      {\n         for (std::size_t i = 0; i < D; ++i) v[i] = point[i];\n      }\n\n      pointnd(const point3d<T>& point)\n      {\n         for (std::size_t i = 0; i < D; ++i) v[i] = point[i];\n      }\n\n     ~pointnd(){}\n\n      void clear()\n      {\n         for (std::size_t i = 0; i < D; ++i) v[i] = T(0.0);\n      }\n\n      inline pointnd<T,D>& operator=(const pointnd<T,D>& point)\n      {\n         if (this == &point) return *this;\n         for (std::size_t i = 0; i < D; ++i) v[i] = point.v[i];\n         return *this;\n      }\n\n      inline pointnd<T,D>& operator=(const point2d<T>& point)\n      {\n         if (D == 2)\n         {\n            v[0] = point.x;\n            v[1] = point.y;\n         }\n         return *this;\n      }\n\n      inline pointnd<T,D>& operator=(const point3d<T>& point)\n      {\n         if (D == 3)\n         {\n            v[0] = point.x;\n            v[1] = point.y;\n            v[2] = point.z;\n         }\n         return *this;\n      }\n\n      inline reference       operator()(const std::size_t& index)       { return v[index]; }\n      inline const_reference operator()(const std::size_t& index) const { return v[index]; }\n\n      inline reference       operator[](const std::size_t& index)       { return v[index]; }\n      inline const_reference operator[](const std::size_t& index) const { return v[index]; }\n\n      friend std::ostream& operator<<(std::ostream& os, const pointnd<T, D>& p) {\n         os << \"[\" << p.v[0];\n         if (D > 1) {\n         for (std::size_t i = 1; i < D; ++i) os << \", \" << p.v[i];\n         }\n         os << \"]\";\n         return os;\n      }\n   protected:\n      T v[D];\n   };\n\n   template <typename T, std::size_t Dimension>\n   class define_point_type      { public: typedef pointnd<T,Dimension> PointType; };\n\n   template <typename T>\n   class define_point_type<T,2> { public: typedef point2d<T> PointType; };\n\n   template <typename T>\n   class define_point_type<T,3> { public: typedef point3d<T> PointType; };\n\n\n   /************[      Segment Type     ]************/\n   template <typename T, std::size_t Dimension>\n   class segment : public geometric_entity\n   {\n   public:\n\n      const static std::size_t PointCount = 2;\n\n      typedef typename define_point_type<T,Dimension>::PointType PointType;\n      typedef const PointType& const_reference;\n      typedef       PointType& reference;\n\n      segment(T x1, T y1, T x2, T y2) {\n         _data[0] = point2d<T>(x1, y1);\n         _data[1] = point2d<T>(x2, y2);\n         calculate_norm();\n      };\n\n      segment(T x1, T y1, T z1, T x2, T y2, T z2) {\n         _data[0] = point3d<T>(x1, y1, z1);\n         _data[1] = point3d<T>(x2, y2, z2);\n         calculate_norm();\n      };\n\n      segment(const point2d<T>& point1, const point2d<T>& point2) : _data{point1, point2} {\n         calculate_norm();\n\n      };\n      segment(const point3d<T>& point1, const point3d<T>& point2) : _data{point1, point2} {\n         calculate_norm();\n      };\n\n      segment(const Eigen::Vector3d& p1, const Eigen::Vector3d& p2)\n      {\n         _data[0] = point3d<T>(p1);\n         _data[1] = point3d<T>(p2);\n         calculate_norm();\n      }\n\n      segment(const Eigen::Vector2d& p1, const Eigen::Vector2d& p2)\n      {\n         _data[0] = point2d<T>(p1);\n         _data[1] = point2d<T>(p2);\n         calculate_norm();\n      }\n\n     ~segment(){}\n\n   private:\n\n      PointType _data[PointCount];\n      Float    _len;\n      void calculate_norm() {\n         _len = T(0.0);\n         for (size_t i = 0; i < Dimension; ++i) {\n            _len += static_cast<Float>((_data[0][i] - _data[1][i]) * (_data[0][i] - _data[1][i]));\n         }\n         _len = sqrt(_len);\n      }\n\n   public:\n\n      inline reference       operator [](const std::size_t& index)       { return _data[index]; }\n      inline const_reference operator [](const std::size_t& index) const { return _data[index]; }\n      inline std::size_t     size       ()                               { return PointCount;   }\n\n      template<typename S, std::size_t E>\n      friend inline S segment_norm(const segment<S,E>& seg);\n\n      friend std::ostream& operator<<(std::ostream& os, const segment& l) {\n         os << \"Segment with points: \" << l._data[0] << \", \" << l._data[1];\n         return os;\n      }\n   };\n\n\n   /************[       Line Type       ]************/\n   template <typename T, std::size_t Dimension>\n   class line : public geometric_entity\n   {\n   public:\n      typedef typename define_point_type<T,Dimension>::PointType PointType;\n      typedef const PointType& const_reference;\n      typedef       PointType& reference;\n\n      const static std::size_t PointCount = 2;\n\n      line(const PointType& point1, const PointType& point2)\n      {\n         _data[0] = point1;\n         _data[1] = point2;\n      };\n\n      // FIXME: Dirty\n      line(const Eigen::Vector3d& p1, const Eigen::Vector3d& p2)\n      {\n         _data[0] = point3d<T>(p1);\n         _data[1] = point3d<T>(p2);\n      }\n\n      line(const Eigen::Vector2d& p1, const Eigen::Vector2d& p2)\n      {\n         _data[0] = point2d<T>(p1);\n         _data[1] = point2d<T>(p2);\n      }\n\n      line(T x1, T y1, T x2, T y2) {\n         _data[0] = point2d<T>(x1, y1);\n         _data[1] = point2d<T>(x2, y2);\n      };\n\n      line(T x1, T y1, T z1, T x2, T y2, T z2) {\n         _data[0] = point3d<T>(x1, y1, z1);\n         _data[1] = point3d<T>(x2, y2, z2);\n      };\n\n      line(){}\n     ~line(){}\n\n   private:\n\n      PointType _data[PointCount];\n\n   public:\n      inline reference       operator [](const std::size_t& index)       { return _data[index]; }\n      inline const_reference operator [](const std::size_t& index) const { return _data[index]; }\n      inline std::size_t     size       ()                               { return PointCount;   }\n\n      friend std::ostream& operator<<(std::ostream& os, const line& l) {\n         os << \"Line with points: \" << l._data[0] << \", \" << l._data[1];\n         return os;\n      }\n   };\n\n\n   /************[     Triangle Type     ]************/\n   template <typename T, std::size_t Dimension>\n   class triangle : public geometric_entity\n   {\n   public:\n\n      const static std::size_t PointCount = 3;\n      typedef typename define_point_type<T,Dimension>::PointType PointType;\n      typedef const PointType& const_reference;\n      typedef       PointType& reference;\n\n      triangle(T x1, T y1, T x2, T y2, T x3, T y3) : _data{PointType(x1,y1), PointType(x2,y2), PointType(x3,y3)} {}\n      triangle(T x1, T y1, T z1, T x2, T y2, T z2, T x3, T y3, T z3) : _data{PointType(x1,y1,z1), PointType(x2,y2,z2), PointType(x3,y3,z3)} {}\n      triangle(const PointType& p1, const PointType& p2, const PointType& p3) : _data{p1, p2, p3} {}\n\n      triangle(){}\n     ~triangle(){}\n\n   private:\n      PointType _data[PointCount];\n\n   public:\n      inline reference       operator [](const std::size_t& index)       { return _data[index]; }\n      inline const_reference operator [](const std::size_t& index) const { return _data[index]; }\n      inline std::size_t     size       ()                         const { return PointCount;   }\n\n      friend std::ostream& operator<<(std::ostream& os, const triangle& l) {\n         os << \"Triangle with points: \" << l._data[0] << \", \" << l._data[1] << \", \" << l._data[2];\n         return os;\n      }\n   };\n\n\n   /************[       Rectangle       ]************/\n   template <typename T>\n   class rectangle : public geometric_entity\n   {\n   public:\n\n      const static std::size_t PointCount = 2;\n\n      rectangle(){}\n     ~rectangle(){}\n\n      typedef typename define_point_type<T,2>::PointType PointType;\n      typedef const PointType& const_reference;\n      typedef       PointType& reference;\n\n   private:\n\n      PointType _data[PointCount];\n\n   public:\n\n      inline reference       operator [](const std::size_t& index)       { return _data[index]; }\n      inline const_reference operator [](const std::size_t& index) const { return _data[index]; }\n      inline std::size_t     size       ()                         const { return PointCount;   }\n   };\n\n\n   /************[      Quadix Type      ]************/\n   template <typename T, std::size_t Dimension>\n   class quadix : public geometric_entity\n   {\n   public:\n\n      const static std::size_t PointCount = 4;\n\n      quadix(){}\n     ~quadix(){}\n\n      typedef typename define_point_type<T,Dimension>::PointType PointType;\n      typedef const PointType& const_reference;\n      typedef       PointType& reference;\n\n   private:\n\n      PointType _data[PointCount];\n\n   public:\n\n      inline reference       operator [](const std::size_t& index)       { return _data[index]; }\n      inline const_reference operator [](const std::size_t& index) const { return _data[index]; }\n      inline std::size_t     size       ()                         const { return PointCount;   }\n   };\n\n   /************[     Polygon Type      ]************/\n   template <typename T, std::size_t Dimension>\n   class polygon : public geometric_entity\n   {\n   public:\n      typedef typename define_point_type<T,Dimension>::PointType PointType;\n      typedef const PointType& const_reference;\n      typedef PointType& reference;\n\n      polygon(const std::size_t initial_size = 0) : _data(initial_size){}\n      polygon(const std::vector<PointType>& p) : _data(p){}\n\n     ~polygon(){}\n\n\n\n   private:\n\n      std::vector<PointType> _data;\n\n   public:\n\n      typedef typename std::vector<PointType>::iterator iterator;\n      typedef typename std::vector<PointType>::const_iterator const_iterator;\n      typedef PointType value_type;\n\n   public:\n\n      inline reference       operator [](const std::size_t& index)       { return _data[index];                }\n      inline const_reference operator [](const std::size_t& index) const { return _data[index];                }\n      inline void            push_back  (const PointType&  value)        { _data.push_back(value);             }\n      inline void            reserve    (const std::size_t amount)       { _data.reserve(amount);              }\n      inline void            clear      ()                         const { _data.clear();                      }\n      inline void            clear      ()                               { _data.clear();                      }\n      inline void            erase      (const std::size_t index)        { _data.erase(_data.begin() + index); }\n      inline std::size_t     size       ()                         const { return _data.size();                }\n      inline const_iterator  begin      ()                         const { return _data.begin();               }\n      inline iterator        begin      ()                               { return _data.begin();               }\n      inline const_iterator  end        ()                         const { return _data.end();                 }\n      inline iterator        end        ()                               { return _data.end();                 }\n      inline reference       front      ()                               { return _data.front();               }\n      inline const_reference front      ()                         const { return _data.front();               }\n      inline reference       back       ()                               { return _data.back();                }\n      inline const_reference back       ()                         const { return _data.back();                }\n      inline void            reverse    ()                               { std::reverse(_data.begin(),_data.end());}\n   };\n\n   /************[      Circle Type      ]************/\n   template <typename T>\n   class circle : public geometric_entity { public: T x,y,radius; };\n\n\n   /************[      Sphere Type      ]************/\n   template <typename T>\n   class sphere : public geometric_entity { public: T x,y,z,radius; };\n\n   /************[   Hypersphere Type    ]************/\n   template <typename T, std::size_t Dimension>\n   class hypersphere : public geometric_entity\n   {\n   public:\n\n      typedef typename define_point_type<T,Dimension>::PointType PointType;\n      typedef const PointType& const_reference;\n      typedef PointType& reference;\n\n      PointType center;\n      T radius;\n   };\n\n   /************[  CircularArc Type   ]**************/\n   template <typename T>\n   class circular_arc : public geometric_entity\n   {\n   public:\n\n      T   x1,y1;\n      T   x2,y2;\n      T   cx,cy;\n      T   px,py;\n      T   angle1;\n      T   angle2;\n      int orientation;\n   };\n\n   /************[      Bezier Type      ]************/\n   enum BezierType {\n                    eQuadraticBezier = 2,\n                    eCubicBezier     = 3\n                   };\n\n   /************[ Quadratic Bezier Type ]************/\n   template <typename T, std::size_t Dimension>\n   class quadratic_bezier : public geometric_entity\n   {\n   public:\n\n      const static std::size_t PointCount = 3;\n      const static BezierType  Type       = eQuadraticBezier;\n\n      quadratic_bezier(){}\n     ~quadratic_bezier(){}\n\n      typedef typename define_point_type<T,Dimension>::PointType PointType;\n      typedef const PointType& const_reference;\n      typedef       PointType& reference;\n\n   private:\n\n      PointType _data[PointCount];\n\n   public:\n\n      inline reference       operator [](const std::size_t& index)       { return _data[index]; }\n      inline const_reference operator [](const std::size_t& index) const { return _data[index]; }\n      inline std::size_t     size     ()                           const { return PointCount;   }\n   };\n\n\n   /************[   Cubic Bezier Type   ]************/\n   template <typename T, std::size_t Dimension>\n   class cubic_bezier : public geometric_entity\n   {\n   public:\n\n      const static std::size_t PointCount = 4;\n      const static BezierType  Type       = eCubicBezier;\n\n      cubic_bezier(){}\n     ~cubic_bezier(){}\n\n      typedef typename define_point_type<T,Dimension>::PointType PointType;\n      typedef const PointType& const_reference;\n      typedef       PointType& reference;\n\n   private:\n\n      PointType _data[PointCount];\n\n   public:\n\n      inline reference       operator [](const std::size_t& index)       { return _data[index]; }\n      inline const_reference operator [](const std::size_t& index) const { return _data[index]; }\n      inline std::size_t     size     ()                           const { return PointCount;   }\n   };\n\n   template <typename T, unsigned int Dimension, BezierType BType>\n   class define_bezier_type;\n\n   template <typename T>\n   class define_bezier_type<T,2,eQuadraticBezier> { public: typedef quadratic_bezier<T,2> BezierType; };\n\n   template <typename T>\n   class define_bezier_type<T,3,eQuadraticBezier> { public: typedef quadratic_bezier<T,3> BezierType; };\n\n   template <typename T>\n   class define_bezier_type<T,2,eCubicBezier>     { public: typedef cubic_bezier<T,2> BezierType;     };\n\n   template <typename T>\n   class define_bezier_type<T,3,eCubicBezier>     { public: typedef cubic_bezier<T,3> BezierType;     };\n\n\n   /************[  Bezier Coefficients  ]************/\n   template <typename T, unsigned int Dimension, BezierType Type>\n   struct bezier_coefficients\n   {\n      typedef typename define_point_type<T,Dimension>::PointType PointType;\n      typedef const PointType& const_reference;\n      typedef       PointType& reference;\n\n      PointType value[Type];\n   };\n\n\n   /************[    Curve Point Type   ]************/\n   template <typename T, std::size_t Dimension>\n   class curve_point : public geometric_entity\n   {\n   public:\n\n      curve_point(){}\n     ~curve_point(){}\n\n      const static std::size_t PointCount = 1;\n      typedef typename define_point_type<T,Dimension>::PointType PointType;\n      typedef const PointType& const_reference;\n      typedef       PointType& reference;\n\n   private:\n\n      PointType _data[PointCount];\n\n   public:\n\n      inline reference       operator ()()       { return _data[0];     }\n      inline const_reference operator ()() const { return _data[0];     }\n      inline std::size_t     size     ()   const { return PointCount;   }\n\n      T t;\n   };\n\n\n   /************[      Vector Type      ]************/\n\n   template <typename T, std::size_t D>\n   class vectornd;\n\n   template <typename T>\n   class vector2d : public point2d<T>\n   {\n   public:\n\n      vector2d(const T& _x = T(0.0), const T& _y = T(0.0)) : point2d<T>(_x, _y) {}\n      vector2d(const Eigen::Vector2d& vec) : point2d<T> (vec) {}\n      vector2d(const point2d<T>& p) : point2d<T>(p.x, p.y) {}\n\n      inline vector2d<T>& operator=(const vectornd<T,2>& vec)\n      {\n         point2d<T>::x = vec[0];\n         point2d<T>::y = vec[1];\n         return *this;\n      }\n\n      inline vector2d<T> operator-() {\n        return vector2d(-point2d<T>::x, -point2d<T>::y);\n      }\n   };\n   template <typename T> inline vector2d<T> operator+(const vector2d<T>& v1, const vector2d<T>& v2);\n   template <typename T> inline vector2d<T> operator-(const vector2d<T>& v1, const vector2d<T>& v2);\n   template <typename T> inline vector2d<T> operator*(const vector2d<T>& v1, const T& scale);\n   template <typename T> inline vector2d<T> operator*(const T& scale, const vector2d<T>& v1);\n   template <typename T> inline vector2d<T> operator/(const vector2d<T>& v1, const T& scale);\n   template <typename T>\n   inline vector2d<T> operator-(const vector2d<T>& p1) {\n      return vector2d<T>(-p1.x, -p1.y, -p1.z);\n   }\n\n   template <typename T>\n   class vector3d : public point3d<T>\n   {\n   public:\n\n      vector3d(const T& _x = T(0.0), const T& _y = T(0.0), const T& _z = T(0.0)) : point3d<T>(_x, _y, _z) {}\n      vector3d(const point3d<T>& p) : point3d<T>(p.x, p.y, p.z) {}\n      vector3d(const Eigen::Vector3d& vec) : point3d<T> (vec) {}\n\n      inline vector3d<T>& operator=(const vectornd<T,3>& vec)\n      {\n         point3d<T>::x = vec[0];\n         point3d<T>::y = vec[1];\n         point3d<T>::z = vec[2];\n         return *this;\n      }\n\n      inline vector3d<T> operator-() {\n        return vector3d(-point3d<T>::x, -point3d<T>::y, -point3d<T>::z);\n      }\n   };\n   template <typename T> inline vector3d<T> operator+(const vector3d<T>& v1, const vector3d<T>& v2);\n   template <typename T> inline vector3d<T> operator-(const vector3d<T>& v1, const vector3d<T>& v2);\n   template <typename T> inline vector3d<T> operator*(const vector3d<T>& v1, const T& scale);\n   template <typename T> inline vector3d<T> operator*(const T& scale, const vector3d<T>& v1);\n   template <typename T> inline vector3d<T> operator/(const vector3d<T>& v1, const T& scale);\n   template <typename T>\n   inline vector3d<T> operator-(const vector3d<T>& p1) {\n      return vector3d<T>(-p1.x, -p1.y, -p1.z);\n   }\n\n   template <typename T, std::size_t D>\n   class vectornd : public pointnd<T,D>\n   {\n   public:\n\n      vectornd()\n      {\n         pointnd<T,D>::clear();\n      }\n\n      vectornd(const T& v0)\n      {\n         pointnd<T,D>::v[0] = v0;\n      }\n\n      vectornd(const T& v0, const T& v1)\n      {\n         pointnd<T,D>::v[0] = v0;\n         pointnd<T,D>::v[1] = v1;\n      }\n\n      vectornd(const T& v0,const T& v1, const T& v2)\n      {\n         pointnd<T,D>::v[0] = v0;\n         pointnd<T,D>::v[1] = v1;\n         pointnd<T,D>::v[2] = v2;\n      }\n\n      vectornd(const T& v0,const T& v1, const T& v2, const T& v3)\n      {\n         pointnd<T,D>::v[0] = v0;\n         pointnd<T,D>::v[1] = v1;\n         pointnd<T,D>::v[2] = v2;\n         pointnd<T,D>::v[3] = v3;\n      }\n\n      vectornd(const vectornd<T,D>& vec)\n      : pointnd<T,D>()\n      {\n         for (std::size_t i = 0; i < D; ++i) (*this)[i] = vec[i];\n      }\n\n      vectornd(const vector2d<T>& vec)\n      {\n         (*this)[0] = vec.x;\n         (*this)[1] = vec.y;\n      }\n\n      vectornd(const vector3d<T>& vec)\n      {\n         (*this)[0] = vec.x;\n         (*this)[1] = vec.y;\n         (*this)[2] = vec.z;\n      }\n   };\n\n   template <typename T, std::size_t Dimension>\n   class define_vector_type { public: typedef vectornd<T,Dimension> VectorType; };\n\n   template <typename T>\n   class define_vector_type<T,2> { public: typedef vector2d<T> VectorType; };\n\n   template <typename T>\n   class define_vector_type<T,3> { public: typedef vector3d<T> VectorType; };\n\n   template <typename T, std::size_t Dimension>\n   class define_eigen_vector { public: typedef Eigen::Matrix<T,Dimension,1> EigenVector; };\n\n   template<> class define_eigen_vector<double,3> { public: typedef Eigen::Vector3d EigenVector; };\n   template<> class define_eigen_vector<double,2> { public: typedef Eigen::Vector2d EigenVector; };\n\n   /************[        Ray Type       ]************/\n   template <typename T, std::size_t Dimension>\n   class ray : public geometric_entity\n   {\n   public:\n\n     typedef typename define_point_type<T,Dimension>::PointType   PointType;\n     typedef typename define_vector_type<T,Dimension>::VectorType VectorType;\n\n      ray(T x1, T y1, T x2, T y2) : origin(x1, y1), direction(normalize(vector2d<T>(x2,y2))) {};\n      ray(T x1, T y1, T z1, T x2, T y2, T z2) : origin(x1, y1, z1), direction(normalize(vector3d<T>(x2,y2,z2))) {};\n      ray(const PointType& _or, const VectorType& _dir) : origin(_or), direction(normalize(_dir)) {};\n      ray(const PointType& p1,  const PointType& p2) : origin(p1), direction(normalize(p2-p1)) {};\n      ray(const Eigen::Vector2d& _or, const Eigen::Vector2d& _dir) : origin(_or), direction(_dir) {};\n      ray(const Eigen::Vector3d& _or, const Eigen::Vector3d& _dir) : origin(_or), direction(_dir) {};\n      ray();\n     ~ray(){}\n\n      PointType  origin;\n      VectorType direction;\n   };\n\n   /************[       Plane Type      ]************/\n   template <typename T,std::size_t Dimension>\n   class plane : public geometric_entity\n   {\n   public:\n\n     typedef typename define_point_type<T,Dimension>::PointType   PointType;\n     typedef typename define_vector_type<T,Dimension>::VectorType VectorType;\n\n      plane(){}\n     ~plane(){}\n\n     plane(PointType p, VectorType n) {\n        normal = normalize(n);\n        constant = -dot_product(p, n);\n     }\n\n      // The distance of the origin to the plane, it will be negtive if\n      // the origin is in the opposite direction of vector normal, i.e.\n      // below the plane\n      T          constant;\n      // The normal vector to the plane\n      VectorType normal;\n   };\n\n   /************[        Box Type       ]************/\n   template <typename T, std::size_t Dimension>\n   class box : public geometric_entity\n   {\n   public:\n\n      const static std::size_t PointCount = 2;\n\n      box(){}\n     ~box(){}\n\n      typedef typename define_point_type<T,Dimension>::PointType PointType;\n      typedef const PointType& const_reference;\n      typedef       PointType& reference;\n\n   private:\n\n      PointType _data[PointCount];\n\n   public:\n\n      inline reference       operator [](const std::size_t& index)       { return _data[index]; }\n      inline const_reference operator [](const std::size_t& index) const { return _data[index]; }\n      inline std::size_t     size     ()                           const { return PointCount;   }\n   };\n\n   enum eInclusion {\n                    eFully,\n                    ePartially,\n                    eOutside,\n                    eUnknown\n                   };\n\n   enum eTriangleType {\n                       etEquilateral,\n                       etIsosceles,\n                       etRight,\n                       etScalene,\n                       etObtuse,\n                       etUnknown\n                      };\n\n\n   /**********[ Orientation constants ]**********/\n   const int RightHandSide        = -1;\n   const int LeftHandSide         = +1;\n   const int Clockwise            = -1;\n   const int CounterClockwise     = +1;\n   const int CollinearOrientation =  0;\n   const int AboveOrientation     = +1;\n   const int BelowOrientation     = -1;\n   const int CoplanarOrientation  =  0;\n   const int PointInside          = +1;\n   const int PointOutside         = -1;\n   const int Cocircular           =  0;\n   const int Cospherical          =  0;\n\n   /********[       Clipping Codes        ]********/\n   const int CLIP_BOTTOM = 1;\n   const int CLIP_TOP    = 2;\n   const int CLIP_LEFT   = 4;\n   const int CLIP_RIGHT  = 8;\n\n   /************[ Trigonometry Tables ]************/\n   template <typename T>\n   class trig_luts\n   {\n   public:\n\n      const static unsigned int TableSize = 360;\n\n      trig_luts()\n      {\n         for (std::size_t i = 0; i < 360; ++i)\n         {\n            sin_[i] = T(std::sin((1.0 * i) * PIDiv180));\n            cos_[i] = T(std::cos((1.0 * i) * PIDiv180));\n            tan_[i] = T(std::tan((1.0 * i) * PIDiv180));\n         }\n      }\n\n      inline const T& sin(const unsigned int angle) const { return sin_[angle]; }\n      inline const T& cos(const unsigned int angle) const { return cos_[angle]; }\n      inline const T& tan(const unsigned int angle) const { return tan_[angle]; }\n\n   private:\n\n      std::vector<T> sin_;\n      std::vector<T> cos_;\n      std::vector<T> tan_;\n   };\n\n   /************[ General Definitions ]************/\n   typedef segment <Float,2> segment2d;\n   typedef line    <Float,2> line2d;\n   typedef ray     <Float,2> ray2d;\n   typedef triangle<Float,2> triangle2d;\n   typedef quadix  <Float,2> quadix2d;\n\n   typedef segment <Float,3> segment3d;\n   typedef line    <Float,3> line3d;\n   typedef ray     <Float,3> ray3d;\n   typedef triangle<Float,3> triangle3d;\n   typedef quadix  <Float,3> quadix3d;\n\n   template <typename T> T epsilon();\n   template<> inline double epsilon<double>() { return static_cast<double>(Epsilon_Medium); }\n   template<> inline  float epsilon<float> () { return static_cast<float> (Epsilon_Low   ); }\n\n   /**\n    * @brief Check the position of vector (px,py) relative\n    *        to vector (x1,y1)--(x2,y2) for RHS coordinate\n    *\n    * @return int +1 if the point is on the left\n    *             -1 if the point is on the right\n    *              0 if the point is on the line\n    */\n   template <typename T>\n   inline int orientation(const T& x1, const T& y1,\n                          const T& x2, const T& y2,\n                          const T& px, const T& py);\n\n   /**\n    * @brief Check the position of vector (px,py) relative\n    *        to a plane. The plane is formed by vector (1 -> 2)\n    *        and vector (1 -> 3). The plane normal direction is\n    *        (1->2)x(1->3). For example, orientation(0,0,0, 1,0,0, 0,1,0, 0,0,1)\n    *        will result in AboveOrientation.\n    * @return int\n    */\n   template <typename T>\n   inline int orientation(const T& x1, const T& y1, const T& z1,\n                          const T& x2, const T& y2, const T& z2,\n                          const T& x3, const T& y3, const T& z3,\n                          const T& px, const T& py, const T& pz);\n\n   /**\n    * @brief Check the position of vector (px,py) relative\n    *        to vector (x1,y1)--(x2,y2) for RHS coordinate\n    *        Robust version, eps = Epsilon\n    * @return int\n    */\n   template <typename T>\n   inline int robust_orientation(const T& x1, const T& y1,\n                                 const T& x2, const T& y2,\n                                 const T& px, const T& py);\n\n   /**\n    * @brief Check the position of vector (px,py) relative\n    *        to a plane. The plane is formed by vector (1 -> 2)\n    *        and vector (1 -> 3). The plane normal direction is\n    *        (1->2)x(1->3).\n    *        Robust version, eps = Epsilon\n    * @return int\n    */\n   template <typename T>\n   inline int robust_orientation(const T& x1, const T& y1, const T& z1,\n                                 const T& x2, const T& y2, const T& z2,\n                                 const T& x3, const T& y3, const T& z3,\n                                 const T& px, const T& py, const T& pz);\n\n   template <typename T>\n   inline int orientation(const point2d<T>& point1, const point2d<T>& point2, const T& px, const T& py);\n\n   template <typename T>\n   inline int orientation(const point2d<T>& point1, const point2d<T>& point2, const point2d<T>& point3);\n\n   template <typename T>\n   inline int orientation(const line<T,2>& line, const point2d<T>& point);\n\n   template <typename T>\n   inline int orientation(const segment<T,2>& segment, const point2d<T>& point);\n\n   template <typename T>\n   inline int orientation(const triangle<T,2>& triangle);\n\n   template <typename T>\n   inline int orientation(const point3d<T>& point1, const point3d<T>& point2, const point3d<T>& point3, const T& px, const T& py, const T& pz);\n\n   template <typename T>\n   inline int orientation(const point3d<T>& point1, const point3d<T>& point2, const point3d<T>& point3, const point3d<T>& point4);\n\n   template <typename T>\n   inline int orientation(const triangle<T,3>& triangle, const point3d<T>& point);\n\n   /**\n    * @brief Check if point (p1x, p1y) and (p2x, p2y) are on different sides of the\n    *        line (x1,y1) --- (x2,y2). If either of the point is on the line, return false\n    *\n    * @return true on different sides\n    * @return false  on the same side\n    */\n   template <typename T>\n   inline bool differing_orientation(const T& x1,  const T& y1,\n                                     const T& x2,  const T& y2,\n                                     const T& p1x, const T& p1y,\n                                     const T& p2x, const T& p2y);\n\n   template <typename T>\n   inline bool differing_orientation(const point2d<T>& p1, const point2d<T>& p2,\n                                     const point2d<T>& q1, const point2d<T>& q2);\n\n   /**\n    * @brief Given a circle made by three points, check whether another point is\n    *        in the circle, algorithm is from https://bit.ly/2LQ2jY3\n    *        return Cocircular, PointInside or PointOutside\n    *\n    *        If the three points are colinear, also return PointOutside\n    *\n    * @return int\n    */\n   template <typename T>\n   inline int in_circle(const T& x1, const T& y1,\n                        const T& x2, const T& y2,\n                        const T& x3, const T& y3,\n                        const T& px, const T& py);\n\n   template <typename T>\n   inline int in_circle(const point2d<T>& point1,\n                        const point2d<T>& point2,\n                        const point2d<T>& point3,\n                        const point2d<T>& point4);\n\n   template <typename T>\n   inline int in_circle(const triangle<T,2>& triangle, const point2d<T>& point);\n\n   template <typename T>\n   inline int in_sphere(const T& x1, const T& y1, const T& z1,\n                        const T& x2, const T& y2, const T& z2,\n                        const T& x3, const T& y3, const T& z3,\n                        const T& x4, const T& y4, const T& z4,\n                        const T& px, const T& py, const T& pz);\n\n   template <typename T>\n   inline int in_sphere(const point3d<T>& point1,\n                        const point3d<T>& point2,\n                        const point3d<T>& point3,\n                        const point3d<T>& point4,\n                        const point2d<T>& point5);\n\n   template <typename T>\n   inline int in_sphere(const quadix<T,3>& quadix, const point3d<T>& point);\n\n   /**\n    * @brief Calculate the signed area of a triangle formed by (x1, y1), (x2, y2)\n    *        and (px, py). It the tree points are in counterclockwise order\n    *        the result is positive. Otherwise, it's negative\n    *\n    * @return T > 0 if the points are in counterclockwise order\n    */\n   template <typename T>\n   inline T signed_area(const T& x1, const T& y1,\n                        const T& x2, const T& y2,\n                        const T& px, const T& py);\n\n   template <typename T>\n   inline T signed_area(const point2d<T>& point1, const point2d<T>& point2, const T& px, const T& py);\n\n   template <typename T>\n   inline T signed_area(const point2d<T>& point1, const point2d<T>& point2, const point2d<T>& point3);\n\n   template <typename T>\n   inline T signed_area(const segment<T,2>& segment, const point2d<T>& point);\n\n   /**\n    * @brief Calculate the signed volume of tetrahedron. The bottom plane\n    *        is formed by (1 -> 3) x (1 -> 2). If p is above the plane, the\n    *        sign will be positive. The sign is the same as orientation(**args)\n    */\n   template <typename T>\n   inline T signed_volume(const T& x1, const T& y1, const T& z1,\n                          const T& x2, const T& y2, const T& z2,\n                          const T& x3, const T& y3, const T& z3,\n                          const T& px, const T& py, const T& pz);\n\n   template <typename T>\n   inline T signed_volume(const point3d<T>& point1, const point3d<T>& point2, const point3d<T>& point3, const T& px, const T& py, const T& pz);\n\n   template <typename T>\n   inline T signed_volume(const point3d<T>& point1, const point3d<T>& point2, const point3d<T>& point3, const point3d<T>& point4);\n\n   template <typename T>\n   inline T signed_volume(const triangle<T,3>& triangle, const point3d<T>& point);\n\n   /**\n    * @brief Check whether the three given points are collinear.\n    *        If they are collinear, the cross product v<sub>12</sub> x v<sub>34</sub>=0\n    */\n   template <typename T>\n   inline bool collinear(const T& x1, const T& y1,\n                         const T& x2, const T& y2,\n                         const T& x3, const T& y3,\n                         const T& epsilon = T(Epsilon));\n\n   template <typename T>\n   inline bool collinear(const T& x1, const T& y1, const T& z1,\n                         const T& x2, const T& y2, const T& z2,\n                         const T& x3, const T& y3, const T& z3,\n                         const T& epsilon = T(Epsilon));\n\n\n   template <typename T>\n   inline bool collinear(const point2d<T>& point1, const point2d<T>& point2, const point2d<T>& point3);\n\n   template <typename T>\n   inline bool collinear(const point3d<T>& point1, const point3d<T>& point2, const point3d<T>& point3);\n\n   /**\n    * @brief A robust check of collinearity. It may also work when two points collapse\n    */\n   template <typename T>\n   inline bool robust_collinear(const T& x1, const T& y1,\n                                const T& x2, const T& y2,\n                                const T& x3, const T& y3, const T& epsilon = T(Epsilon));\n   template <typename T>\n   inline bool robust_collinear(const point2d<T>& point1, const point2d<T>& point2, const point2d<T>& point3, const T& epsilon = T(Epsilon));\n\n   template <typename T>\n   inline bool robust_collinear(const line<T,2>& line, const point2d<T>& point, const T& epsilon = T(Epsilon));\n\n   template <typename T>\n   inline bool robust_collinear(const line<T,3>& line, const point3d<T>& point, const T& epsilon = T(Epsilon));\n\n   template <typename T>\n   inline bool robust_collinear(const T& x1, const T& y1, const T& z1,\n                                const T& x2, const T& y2, const T& z2,\n                                const T& x3, const T& y3, const T& z3, const T& epsilon = T(Epsilon));\n   template <typename T>\n   inline bool robust_collinear(const point3d<T>& point1, const point3d<T>& point2, const point3d<T>& point3, const T& epsilon = T(Epsilon));\n\n   /**\n    * @brief Check whether (px, py) is on the line segment (x1,y1)--(x2,y2)\n    */\n   template <typename T>\n   inline bool is_point_collinear(const T& x1, const T& y1,\n                                  const T& x2, const T& y2,\n                                  const T& px, const T& py,\n                                  const bool robust = false);\n   template <typename T>\n   inline bool is_point_collinear(const point2d<T>& point1,\n                                  const point2d<T>& point2,\n                                  const point2d<T>& point3,\n                                  const bool robust = false);\n\n   template <typename T>\n   inline bool is_point_collinear(const point2d<T>& point1,\n                                  const point2d<T>& point2,\n                                  const T& px, const T& py,\n                                  const bool robust = false);\n   template <typename T>\n   inline bool is_point_collinear(const segment<T,2>& segment,\n                                  const point2d<T>&   point,\n                                  const bool robust = false);\n\n   /**\n    * @brief Check whether (px,py,pz) is on the line segment (x1,y1,z1)--(x2,y2,z2)\n    */\n   template <typename T>\n   inline bool is_point_collinear(const T& x1, const T& y1, const T& z1,\n                                  const T& x2, const T& y2, const T& z2,\n                                  const T& px, const T& py, const T& pz,\n                                  const bool robust = false);\n\n   template <typename T>\n   inline bool is_point_collinear(const point3d<T>& point1,\n                                  const point3d<T>& point2,\n                                  const point3d<T>& point3,\n                                  const bool robust = false);\n\n   template <typename T>\n   inline bool is_point_collinear(const segment<T,3>& segment,\n                                  const point3d<T>& point,\n                                  const bool robust = false);\n\n   /**\n    * @brief Check whether the four points are on the same plane by comparing\n    *        the distance from a point to the plane formed by the other three\n    *        points. If the first points are collinear, the four points must\n    *        be on the same plane.\n    *\n    * @param epsilon The threshold for the coplanar check\n    * @return true\n    * @return false\n    */\n   template <typename T> inline bool robust_coplanar(const point3d<T> point1,\n                                                     const point3d<T> point2,\n                                                     const point3d<T> point3,\n                                                     const point3d<T> point4,\n                                                     const T& epsilon = T(Epsilon));\n\n   template <typename T> inline bool coplanar(const line<T,3>& line1, const line<T,3>& line2);\n   template <typename T> inline bool coplanar(const ray<T,3>& ray1, const ray<T,3>& ray2);\n   template <typename T> inline bool coplanar(const ray<T,3>& ray1, const segment<T,3>& segment1);\n   template <typename T> inline bool coplanar(const segment<T,3>& segment1, const segment<T,3>& segment2);\n   template <typename T> inline bool coplanar(const triangle<T,3>& triangle1, const triangle<T,3>& triangle2);\n   template <typename T> inline bool coplanar(const quadix<T,3>& quadix1, const quadix<T,3>& quadix2);\n\n   template <typename T> inline bool cocircular(const T& x1, const T& y1,\n                                                const T& x2, const T& y2,\n                                                const T& x3, const T& y3,\n                                                const T& x4, const T& y4,\n                                                const T& epsilon = T(Epsilon));\n\n   template <typename T> inline bool cocircular(const point2d<T>& point1,\n                                                const point2d<T>& point2,\n                                                const point2d<T>& point3,\n                                                const point2d<T>& point4,\n                                                const T& epsilon = T(Epsilon));\n\n   template <typename T> inline bool cocircular(const triangle<T,2>& triangle,\n                                                const point2d<T>& point,\n                                                const T& epsilon = T(Epsilon));\n\n   template <typename T> inline bool cocircular(const circle<T>& circle,\n                                                const point2d<T>& point,\n                                                const T& epsilon = T(Epsilon));\n\n   template <typename T> inline bool is_skinny_triangle(const T& x1, const T& y1,\n                                                        const T& x2, const T& y2,\n                                                        const T& x3, const T& y3);\n\n   template <typename T> inline bool is_skinny_triangle(const point2d<T>& point1,\n                                                        const point2d<T>& point2,\n                                                        const point2d<T>& point3);\n\n   template <typename T> inline bool is_skinny_triangle(const triangle<T,2>& triangle);\n\n   template <typename T>\n   inline bool intersect(T x1, T y1,\n                         T x2, T y2,\n                         T x3, T y3,\n                         T x4, T y4);\n\n   template <typename T>\n   inline bool intersect(const point2d<T>& point1,\n                         const point2d<T>& point2,\n                         const point2d<T>& point3,\n                         const point2d<T>& point4);\n\n   template <typename T>\n   inline bool intersect(const segment<T,2>& segment1, const segment<T,2>& segment2);\n\n   template <typename T>\n   inline bool intersect(T x1, T y1, T z1,\n                         T x2, T y2, T z2,\n                         T x3, T y3, T z3,\n                         T x4, T y4, T z4);\n\n   template <typename T>\n   inline bool intersect(const point3d<T>& point1,\n                         const point3d<T>& point2,\n                         const point3d<T>& point3,\n                         const point3d<T>& point4);\n\n   inline bool intersect(const Eigen::Vector3d& point1,\n                         const Eigen::Vector3d& point2,\n                         const Eigen::Vector3d& point3,\n                         const Eigen::Vector3d& point4);\n\n   template <typename T>\n   inline bool intersect(const segment<T,3>& segment1, const segment<T,3>&  segment2);\n\n   template <typename T> inline bool intersect(const segment<T,2>& segment, const rectangle<T>& rectangle);\n   template <typename T> inline bool intersect(const segment<T,2>& segment, const triangle<T,2>& triangle);\n   template <typename T> inline bool intersect(const segment<T,2>& segment, const quadix<T,2>& quadix);\n   template <typename T> inline bool intersect(const segment<T,2>& segment, const line<T,2>& line);\n   template <typename T> inline bool intersect(const segment<T,2>& segment, const circle<T>& circle);\n   template <typename T> inline bool intersect(const segment<T,2>& segment, const quadratic_bezier<T,2>& bezier, const std::size_t& steps = 1000);\n   template <typename T> inline bool intersect(const segment<T,2>& segment, const cubic_bezier<T,2>& bezier, const std::size_t& steps = 1000);\n   template <typename T> inline bool intersect(const segment<T,3>& segment, const line<T,3>& line);\n   template <typename T> inline bool intersect(const segment<T,3>& segment, const box<T,3>& box);\n   template <typename T> inline bool intersect(const segment<T,3>& segment, const sphere<T>& sphere);\n   template <typename T> inline bool intersect(const segment<T,3>& segment, const plane<T,3>& plane);\n   template <typename T> inline bool intersect(const segment<T,3>& segment, const quadratic_bezier<T,3>& bezier, const std::size_t& steps = 1000);\n   template <typename T> inline bool intersect(const segment<T,3>& segment, const cubic_bezier<T,3>& bezier, const std::size_t& steps = 1000);\n   template <typename T> inline bool intersect(const line<T,2>& line, const triangle<T,2>& triangle);\n   template <typename T> inline bool intersect(const line<T,2>& line, const quadix<T,2>& quadix);\n   template <typename T> inline bool intersect(const line<T,2>& line1, const line<T,2>& line2);\n   template <typename T> inline bool intersect(const line<T,2>& line, const circle<T>& circle);\n   template <typename T> inline bool intersect(const line<T,2>& line, const quadratic_bezier<T,2>& bezier, const std::size_t& steps = 1000);\n   template <typename T> inline bool intersect(const line<T,2>& line, const cubic_bezier<T,2>& bezier, const std::size_t& steps = 1000);\n   template <typename T> inline bool intersect(const line<T,3>& line, const triangle<T,3>& triangle);\n   template <typename T> inline bool intersect(const line<T,3>& line, const plane<T,3>& plane);\n   template <typename T> inline bool intersect(const line<T,3>& line, const sphere<T>& sphere);\n   template <typename T> inline bool intersect(const line<T,3>& line, const quadratic_bezier<T,3>& bezier, const std::size_t& steps = 1000);\n   template <typename T> inline bool intersect(const line<T,3>& line, const cubic_bezier<T,3>& bezier, const std::size_t& steps = 1000);\n   template <typename T> inline bool intersect(const triangle<T,2>& triangle, const circle<T>& circle);\n   template <typename T> inline bool intersect(const triangle<T,2>& triangle, const rectangle<T>& rectangle);\n   template <typename T> inline bool intersect(const triangle<T,2>& triangle, const quadratic_bezier<T,2>& bezier, const std::size_t& steps = 1000);\n   template <typename T> inline bool intersect(const triangle<T,2>& triangle, const cubic_bezier<T,2>& bezier, const std::size_t& steps = 1000);\n   template <typename T> inline bool intersect(const rectangle<T>& rectangle1, const rectangle<T>& rectangle2);\n   template <typename T> inline bool intersect(const triangle<T,2>& triangle1, const triangle<T,2>& triangle2);\n   template <typename T> inline bool intersect(const rectangle<T>& rectangle, const circle<T>& circle);\n   template <typename T> inline bool intersect(const rectangle<T>& rectangle, const quadratic_bezier<T,2>& bezier, const std::size_t& steps = 1000);\n   template <typename T> inline bool intersect(const rectangle<T>& rectangle, const cubic_bezier<T,2>& bezier, const std::size_t& steps = 1000);\n   template <typename T> inline bool intersect(const quadix<T,2>& quadix, const quadratic_bezier<T,2>& bezier, const std::size_t& steps = 1000);\n   template <typename T> inline bool intersect(const quadix<T,2>& quadix, const cubic_bezier<T,2>& bezier, const std::size_t& steps = 1000);\n   template <typename T> inline bool intersect(const circle<T>& circle1, const circle<T>& circle2);\n   template <typename T> inline bool intersect(const circle<T>& circle, const quadratic_bezier<T,2>& bezier, const std::size_t& steps = 1000);\n   template <typename T> inline bool intersect(const circle<T>& circle, const cubic_bezier<T,2>& bezier, const std::size_t& steps = 1000);\n   template <typename T> inline bool intersect(const box<T,3>& box, const sphere<T>& sphere);\n   template <typename T> inline bool intersect(const sphere<T>& sphere1, const sphere<T>& sphere2);\n   template <typename T> inline bool intersect(const sphere<T>& sphere, const quadratic_bezier<T,3>& bezier, const std::size_t& steps = 1000);\n   template <typename T> inline bool intersect(const sphere<T>& sphere, const cubic_bezier<T,3>& bezier, const std::size_t& steps = 1000);\n\n   /**\n    * @brief Check whether two rays intersect.\n    *\n    * @tparam T\n    * @param ray1\n    * @param ray2\n    * @return true\n    * @return false\n    */\n   template <typename T> inline bool intersect(const ray<T,2>& ray1, const ray<T,2>& ray2);\n   template <typename T> inline bool intersect(const ray<T,3>& ray1, const ray<T,3>& ray2);\n   template <typename T> inline bool intersect(const ray<T,2>& ray, const segment<T,2>& segment);\n   template <typename T> inline bool intersect(const ray<T,3>& ray, const segment<T,3>& segment);\n   template <typename T> inline bool intersect(const ray<T,2>& ray, const rectangle<T>& rectangle);\n   template <typename T> inline bool intersect(const ray<T,3>& ray, const box<T,3>& box);\n   template <typename T> inline bool intersect(const ray<T,2>& ray, const triangle<T,2>& triangle);\n   /**\n    * @brief Check whether a 3D ray intersects with a triangle. It uses Moller–Trumbore ray-triangle intersection algorithm.\n    *        Its implementation is similar to the one in Wikipedia. The only difference is that if the origin of the ray is\n    *        in the triangle, it will also return true.\n    *\n    * @tparam T\n    * @param ray\n    * @param triangle\n    * @return true\n    * @return false\n    */\n   template <typename T> inline bool intersect(const ray<T,3>& ray, const triangle<T,3>& triangle);\n   template <typename T> inline bool intersect(const ray<T,2>& ray, const quadix<T,2>& quadix);\n   template <typename T> inline bool intersect(const ray<T,2>& ray, const circle<T>& circle);\n   template <typename T> inline bool intersect(const ray<T,3>& ray, const sphere<T>& sphere);\n   template <typename T> inline bool intersect(const ray<T,3>& ray, const plane<T,3>& plane);\n   template <typename T> inline bool intersect(const ray<T,2>& ray, const polygon<T,2>& polygon);\n   template <typename T> inline bool intersect(const plane<T,3>& plane1, const plane<T,3>& plane2);\n   template <typename T> inline bool intersect(const plane<T,3>& plane, const sphere<T>& sphere);\n   template <typename T> inline bool intersect(const plane<T,3>& plane, const line<T,3>& line);\n\n   template <typename T>\n   inline bool simple_intersect(const T& x1, const T& y1,\n                                const T& x2, const T& y2,\n                                const T& x3, const T& y3,\n                                const T& x4, const T& y4);\n\n   template <typename T>\n   inline bool simple_intersect(const point2d<T>& point1, const point2d<T>& point2,\n                                const point2d<T>& point3, const point2d<T>& point4);\n\n   template <typename T>\n   inline bool simple_intersect(const segment<T,2>& segment1, const segment<T,2>& segment2);\n\n   template <typename T> inline bool intersect_vertical_horizontal(const segment<T,2>& segment1, const segment<T,2>& segment2);\n   template <typename T> inline bool intersect_vertical_vertical(const segment<T,2>& segment1, const segment<T,2>& segment2);\n   template <typename T> inline bool intersect_horizontal_horizontal(const segment<T,2>& segment1, const segment<T,2>& segment2);\n\n   /**\n    * @brief Calculate the intersection point of two line segments assuming they intersect.\n    *        The line segments are bounded by the four points (x1, y1), (x2, y2), (x3, y3) (x4, y4)\n    */\n   template <typename T>\n   inline bool intersection_point(T  x1, T  y1,\n                                  T  x2, T  y2,\n                                  T  x3, T  y3,\n                                  T  x4, T  y4,\n                                  T& ix, T& iy);\n\n   template <typename T>\n   inline bool intersection_point(const point2d<T>& point1,\n                                  const point2d<T>& point2,\n                                  const point2d<T>& point3,\n                                  const point2d<T>& point4,\n                                        T& ix,       T& iy);\n\n   template <typename T>\n   inline point2d<T> intersection_point(const point2d<T>& point1,\n                                        const point2d<T>& point2,\n                                        const point2d<T>& point3,\n                                        const point2d<T>& point4);\n   template <typename T>\n   inline point2d<T> intersection_point(const segment<T,2>& segment1,\n                                        const segment<T,2>& segment2);\n\n   template <typename T>\n   inline bool intersection_point(const segment<T,2>& segment1,\n                                  const segment<T,2>& segment2,\n                                  point2d<T>& point);\n\n   template <typename T>\n   inline bool intersection_point(T  x1, T  y1, T  z1,\n                                  T  x2, T  y2, T  z2,\n                                  T  x3, T  y3, T  z3,\n                                  T  x4, T  y4, T  z4,\n                                  T& ix, T& iy, T& iz);\n\n   template <typename T>\n   inline bool intersection_point(const point3d<T>& point1,\n                                  const point3d<T>& point2,\n                                  const point3d<T>& point3,\n                                  const point3d<T>& point4,\n                                        T& ix, T& iy, T& iz);\n\n   template <typename T>\n   inline point3d<T> intersection_point(const point3d<T>& point1,\n                                        const point3d<T>& point2,\n                                        const point3d<T>& point3,\n                                        const point3d<T>& point4);\n\n   template <typename T>\n   inline point3d<T> intersection_point(const segment<T,3>& segment1,\n                                        const segment<T,3>& segment2);\n\n   template <typename T>\n   inline bool intersection_point(const segment<T,3>& segment1,\n                                  const segment<T,3>& segment2,\n                                  point3d<T> &point);\n\n   inline Eigen::Vector3d intersection_point(const Eigen::Vector3d& point1,\n                                             const Eigen::Vector3d& point2,\n                                             const Eigen::Vector3d& point3,\n                                             const Eigen::Vector3d& point4);\n\n   template <typename T>\n   inline point2d<T> intersection_point(const segment<T,2>& segment,\n                                        const line<T,2>& line);\n\n   template <typename T>\n   inline point3d<T> intersection_point(const segment<T,3>& segment,\n                                        const line<T,3>& line);\n   template <typename T>\n   inline bool intersection_point(const segment<T,3>& segment,\n                                        const line<T,3>& line,\n                                        Eigen::Vector3d& ipoint);\n\n   /**\n    * @brief Calculate the intersection point of a segment and a plane. If there is no intersction point\n    *        or the line is in the plane, the function will return (+inf, +inf, +inf). This is different\n    *        from intersect(const segment<T,3>& segment, const plane<T,3>& plane)\n    */\n   template <typename T>\n   inline point3d<T> intersection_point(const segment<T,3>& segment,\n                                        const plane<T,3>& plane);\n\n   template <typename T, typename OutputIterator>\n   inline void intersection_point(const segment<T,2>& segment,\n                                  const quadratic_bezier<T,2>& bezier,\n                                  OutputIterator out,\n                                  const std::size_t& steps = 1000);\n\n   template <typename T, typename OutputIterator>\n   inline void intersection_point(const segment<T,2>& segment,\n                                  const cubic_bezier<T,2>& bezier,\n                                  OutputIterator out,\n                                  const std::size_t& steps = 1000);\n\n   template <typename T, typename OutputIterator>\n   inline void intersection_point(const segment<T,3>& segment,\n                                  const quadratic_bezier<T,3>& bezier,\n                                  OutputIterator out,\n                                  const std::size_t& steps = 1000);\n\n   template <typename T, typename OutputIterator>\n   inline void intersection_point(const segment<T,3>& segment,\n                                  const cubic_bezier<T,3>& bezier,\n                                  OutputIterator out,\n                                  const std::size_t& steps = 1000);\n\n   /**\n    * @brief Calculate intersection point of two lines. If the lines are\n    *        parallel to each other or collinear, return a degenerated point\n    *\n    * @tparam T\n    * @param line1\n    * @param line2\n    * @return point2d<T>\n    */\n   template <typename T>\n   inline point2d<T> intersection_point(const line<T,2>& line1,\n                                        const line<T,2>& line2);\n\n   template <typename T>\n   inline point3d<T> intersection_point(const line<T,3>& line1,\n                                        const line<T,3>& line2);\n\n   template <typename T>\n   inline void intersection_point(const circle<T>&  circle1,\n                                  const circle<T>&  circle2,\n                                        point2d<T>& point1,\n                                        point2d<T>& point2);\n\n   template <typename T, typename OutputIterator>\n   inline void intersection_point(const segment<T,2>&  segment,\n                                  const triangle<T,2>& triangle,\n                                  OutputIterator out);\n\n   template <typename T>\n   inline void intersection_point(const line<T,3>&     line,\n                                  const triangle<T,3>& triangle,\n                                  point3d<T>&          ipoint);\n\n   template <typename T>\n   inline point3d<T> intersection_point(const line<T,3>& line,\n                                  const plane<T,3>&      plane);\n\n   template <typename T, typename OutputIterator>\n   inline void intersection_point(const T& x1, const T& y1,\n                                  const T& x2, const T& y2,\n                                  const T& cx, const T& cy,\n                                  const T& radius,\n                                  OutputIterator out);\n\n   template <typename T, typename OutputIterator>\n   inline void intersection_point(const segment<T,2>& segment,\n                                  const circle<T>&    circle,\n                                  OutputIterator out);\n\n   template <typename T, typename OutputIterator>\n   inline void intersection_point(const line<T,2>& line,\n                                  const circle<T>& circle,\n                                  OutputIterator out);\n\n   template <typename T, typename OutputIterator>\n   inline void intersection_point(const segment<T,3>& segment,\n                                  const sphere<T>&    sphere,\n                                  OutputIterator out);\n\n   template <typename T, typename OutputIterator>\n   inline void intersection_point(const line<T,3>& line,\n                                  const sphere<T>& sphere,\n                                  OutputIterator out);\n\n   /**\n    * @brief Calculate the intersecting point of two rays.\n    * @details The function could return the following results\n    *          - 1 with some value of point: The rays intersect at exact one point (including the edge)\n    *          - 0 with degenerated point:   The rays don't intersect at all\n    *          - 1 with degenerated point:   The ray intersect at more than one point.\n    *\n    * @tparam T\n    * @param ray1\n    * @param ray2\n    * @param point\n    * @return int\n    */\n   template <typename T>\n   inline int intersection_point(const ray<T,2>& ray1, const ray<T,2>& ray2, point2d<T>& point);\n\n   template <typename T>\n   inline point2d<T> intersection_point(const ray<T,2>& ray1, const ray<T,2>& ray2);\n\n   /**\n    * @brief Calculate the intersecting point of a ray and a segment\n    * @details The function could return the following results\n    *          - 1 or -1 with some value of point: They intersect at one point. +1 if the ray points to the LHS of the segment, vice verse\n    *          - 0 with degenerated point:   They don't intersect at all\n    *          - 2 or -2 with some value of point: They intersect at the ray origin. +2 if they have the same direction, vice verse\n    *          - 3 or -3 with degenerate point: They intersect at more than one point. +3 if they have the same direction.\n    *         If robust is false, the code only check condition 1, -1. Other conditions will give 0;\n    *\n    * @tparam T\n    * @param ray1\n    * @param ray2\n    * @param point\n    * @param robust\n    * @return int\n    */\n   template <typename T>\n   inline int intersection_point(const ray<T,2>& ray1, const segment<T,2>& segment, point2d<T>& point, bool robust = true);\n\n   template <typename T>\n   inline point2d<T> intersection_point(const ray<T,2>& ray, const segment<T,2>& segment);\n\n   template <typename T>\n   inline point3d<T> intersection_point(const ray<T,3>& ray, const segment<T,3>& segment);\n\n   /**\n    * @brief Calculate the intersecting point of a ray and a triangle\n    * @details The function could return the following results\n    *          -\n    *\n    * @tparam T\n    * @param ray\n    * @param triangle\n    * @param point\n    * @param robust\n    * @return int\n    */\n   template <typename T>\n   inline int intersection_point(const ray<T,3>& ray, const triangle<T,3>& triangle, point3d<T>& point, bool robust = true);\n\n   template <typename T>\n   inline int intersection_point(const ray<T,3>& ray, const polygon<T,3>& polygon, point3d<T>& point, bool robust = true);\n\n   template <typename T>\n   inline point3d<T> intersection_point(const ray<T,3>& ray, const triangle<T,3>& triangle);\n\n   template <typename T>\n   inline point3d<T> intersection_point(const ray<T,3>& ray, const plane<T,3>& plane);\n\n   template <typename T, typename OutputIterator>\n   inline void intersection_point(const ray<T,2>& ray, const circle<T>& circle, OutputIterator out);\n\n   template <typename T, typename OutputIterator>\n   inline void intersection_point(const ray<T,3>& ray, const sphere<T>& sphere, OutputIterator out);\n\n   template <typename T>\n   inline void intersection_point_line_to_line(const T& x1, const T& y1, const T& z1,\n                                               const T& x2, const T& y2, const T& z2,\n                                               const T& x3, const T& y3, const T& z3,\n                                               const T& x4, const T& y4, const T& z4,\n                                                     T& Ix,       T& Iy,       T& Iz);\n\n   template <typename T>\n   inline T normalize_angle(const T& angle);\n\n   template <typename T>\n   inline T vertical_mirror(const T& angle);\n\n   template <typename T>\n   inline T horizontal_mirror(const T& angle);\n\n   template <typename T>\n   inline unsigned int quadrant(const T& angle);\n\n   template <typename T>\n   inline unsigned int quadrant(const T& x, const T& y);\n\n   template <typename T>\n   inline unsigned int quadrant(const point2d<T>& point);\n\n   template <typename T>\n   inline T vertex_angle(const T& x1, const T& y1,\n                         const T& x2, const T& y2,\n                         const T& x3, const T& y3);\n\n   template <typename T>\n   inline T vertex_angle(const point2d<T>& point1,\n                         const point2d<T>& point2,\n                         const point2d<T>& point3);\n\n   template <typename T>\n   inline T vertex_angle(const T& x1, const T& y1, const T& z1,\n                         const T& x2, const T& y2, const T& z2,\n                         const T& x3, const T& y3, const T& z3);\n\n   template <typename T>\n   inline T vertex_angle(const point3d<T>& point1,\n                         const point3d<T>& point2,\n                         const point3d<T>& point3);\n\n   template <typename T>\n   inline T oriented_vertex_angle(const T& x1, const T& y1,\n                                  const T& x2, const T& y2,\n                                  const T& x3, const T& y3,\n                                  const int orient = Clockwise);\n   template <typename T>\n   inline T oriented_vertex_angle(const point2d<T>& point1,\n                                  const point2d<T>& point2,\n                                  const point2d<T>& point3,\n                                  const int orient = Clockwise);\n   template <typename T>\n   inline T cartesian_angle(const T& x, const T& y);\n\n   template <typename T>\n   inline T cartesian_angle(const point2d<T>& point);\n\n   template <typename T>\n   inline T robust_cartesian_angle(const T& x, const T& y);\n\n   template <typename T>\n   inline T robust_cartesian_angle(const point2d<T>& point);\n\n   template <typename T>\n   inline T cartesian_angle(const T& x, const T& y, const T& ox, const T& oy);\n\n   template <typename T>\n   inline T cartesian_angle(const point2d<T>& point, const point2d<T>& origin);\n\n   template <typename T>\n   inline T robust_cartesian_angle(const T& x, const T& y, const T& ox, const T& oy);\n\n   template <typename T>\n   inline T robust_cartesian_angle(const point2d<T>& point, const point2d<T>& origin);\n\n\n   template <typename T>\n   inline bool parallel(const T& x1, const T& y1,\n                        const T& x2, const T& y2,\n                        const T& x3, const T& y3,\n                        const T& x4, const T& y4,\n                        const T& epsilon = T(Epsilon));\n\n   template <typename T>\n   inline bool parallel(const point2d<T>& point1,\n                        const point2d<T>& point2,\n                        const point2d<T>& point3,\n                        const point2d<T>& point4,\n                        const T& epsilon = T(Epsilon));\n\n   template <typename T>\n   inline bool parallel(const segment<T,2>& segment1,\n                        const segment<T,2>& segment2,\n                        const T& epsilon = T(Epsilon));\n\n   template <typename T>\n   inline bool parallel(const line<T,2>& line1,\n                        const line<T,2>& line2,\n                        const T& epsilon = T(Epsilon));\n\n   template <typename T>\n   inline bool parallel(const T& x1, const T& y1, const T& z1,\n                        const T& x2, const T& y2, const T& z2,\n                        const T& x3, const T& y3, const T& z3,\n                        const T& x4, const T& y4, const T& z4,\n                        const T& epsilon = T(Epsilon));\n\n   template <typename T>\n   inline bool parallel(const point3d<T>& point1,\n                        const point3d<T>& point2,\n                        const point3d<T>& point3,\n                        const point3d<T>& point4,\n                        const T& epsilon = T(Epsilon));\n\n   template <typename T>\n   inline bool parallel(const segment<T,3>& segment1,\n                        const segment<T,3>& segment2,\n                        const T& epsilon = T(Epsilon));\n\n   template <typename T>\n   inline bool parallel(const line<T,3>& line1,\n                        const line<T,3>& line2,\n                        const T& epsilon = T(Epsilon));\n\n   template <typename T>\n   inline bool robust_parallel(const T& x1, const T& y1,\n                               const T& x2, const T& y2,\n                               const T& x3, const T& y3,\n                               const T& x4, const T& y4,\n                               const T& epsilon = T(Epsilon));\n\n   template <typename T>\n   inline bool robust_parallel(const point2d<T>& point1,\n                               const point2d<T>& point2,\n                               const point2d<T>& point3,\n                               const point2d<T>& point4,\n                               const T& epsilon = T(Epsilon));\n\n   template <typename T>\n   inline bool robust_parallel(const segment<T,2>& segment1,\n                               const segment<T,2>& segment2,\n                               const T& epsilon = T(Epsilon));\n\n   template <typename T>\n   inline bool robust_parallel(const line<T,2>& line1,\n                               const line<T,2>& line2,\n                               const T& epsilon = T(Epsilon));\n\n   template <typename T>\n   inline bool robust_parallel(const line<T,2>& line,\n                               const segment<T,2>& segment,\n                               const T& epsilon = T(Epsilon));\n\n   template <typename T>\n   inline bool robust_parallel(const T& x1, const T& y1, const T& z1,\n                               const T& x2, const T& y2, const T& z2,\n                               const T& x3, const T& y3, const T& z3,\n                               const T& x4, const T& y4, const T& z4,\n                               const T& epsilon = T(Epsilon));\n\n   template <typename T>\n   inline bool robust_parallel(const point3d<T>& point1,\n                               const point3d<T>& point2,\n                               const point3d<T>& point3,\n                               const point3d<T>& point4,\n                               const T& epsilon = T(Epsilon));\n\n   template <typename T>\n   inline bool robust_parallel(const segment<T,3>& segment1,\n                               const segment<T,3>& segment2,\n                               const T& epsilon = T(Epsilon));\n\n   template <typename T>\n   inline bool robust_parallel(const line<T,3>& line1,\n                               const line<T,3>& line2,\n                               const T& epsilon = T(Epsilon));\n\n   template <typename T>\n   inline bool robust_parallel(const line<T,3>& line,\n                               const segment<T,3>& segment,\n                               const T& epsilon = T(Epsilon));\n\n\n   template <typename T>\n   inline bool perpendicular(const T& x1, const T& y1,\n                             const T& x2, const T& y2,\n                             const T& x3, const T& y3,\n                             const T& x4, const T& y4,\n                             const T& epsilon = T(Epsilon));\n\n   template <typename T>\n   inline bool perpendicular(const point2d<T>& point1,\n                             const point2d<T>& point2,\n                             const point2d<T>& point3,\n                             const point2d<T>& point4,\n                             const T& epsilon = T(Epsilon));\n\n   template <typename T>\n   inline bool perpendicular(const segment<T,2>& segment1,\n                             const segment<T,2>& segment2,\n                             const T& epsilon = T(Epsilon));\n\n   template <typename T>\n   inline bool perpendicular(const line<T,2>& line1,\n                             const line<T,2>& line2,\n                             const T& epsilon = T(Epsilon));\n\n   template <typename T>\n   inline bool perpendicular(const line<T,2>& line,\n                             const segment<T,2>& segment,\n                             const T& epsilon = T(Epsilon));\n\n   template <typename T>\n   inline bool perpendicular(const T& x1, const T& y1, const T& z1,\n                             const T& x2, const T& y2, const T& z2,\n                             const T& x3, const T& y3, const T& z3,\n                             const T& x4, const T& y4, const T& z4,\n                             const T& epsilon = T(Epsilon));\n\n   template <typename T>\n   inline bool perpendicular(const point3d<T>& point1,\n                             const point3d<T>& point2,\n                             const point3d<T>& point3,\n                             const point3d<T>& point4,\n                             const T& epsilon = T(Epsilon));\n\n   template <typename T>\n   inline bool perpendicular(const segment<T,3>& segment1,\n                             const segment<T,3>& segment2,\n                             const T& epsilon = T(Epsilon));\n\n   template <typename T>\n   inline bool perpendicular(const line<T,3>& line,\n                             const segment<T,3>& segment,\n                             const T& epsilon = T(Epsilon));\n\n   template <typename T>\n   inline bool perpendicular(const line<T,3>& line1,\n                             const line<T,3>& line2,\n                             const T& epsilon = T(Epsilon));\n\n   template <typename T>\n   inline bool robust_perpendicular(const T& x1, const T& y1,\n                                    const T& x2, const T& y2,\n                                    const T& x3, const T& y3,\n                                    const T& x4, const T& y4,\n                                    const T& epsilon = T(Epsilon));\n\n   template <typename T>\n   inline bool robust_perpendicular(const point2d<T>& point1,\n                                    const point2d<T>& point2,\n                                    const point2d<T>& point3,\n                                    const point2d<T>& point4,\n                                    const T& epsilon = T(Epsilon));\n\n   template <typename T>\n   inline bool robust_perpendicular(const segment<T,2>& segment1,\n                                    const segment<T,2>& segment2,\n                                    const T& epsilon = T(Epsilon));\n\n   template <typename T>\n   inline bool robust_perpendicular(const line<T,2>& line1,\n                                    const line<T,2>& line2,\n                                    const T& epsilon = T(Epsilon));\n\n   template <typename T>\n   inline bool robust_perpendicular(const T& x1, const T& y1, const T& z1,\n                                    const T& x2, const T& y2, const T& z2,\n                                    const T& x3, const T& y3, const T& z3,\n                                    const T& x4, const T& y4, const T& z4,\n                                    const T& epsilon = T(Epsilon));\n\n   template <typename T>\n   inline bool robust_perpendicular(const point3d<T>& point1,\n                                    const point3d<T>& point2,\n                                    const point3d<T>& point3,\n                                    const point3d<T>& point4,\n                                    const T& epsilon = T(Epsilon));\n\n   template <typename T>\n   inline bool robust_perpendicular(const segment<T,3>& segment1,\n                                    const segment<T,3>& segment2,\n                                    const T& epsilon = T(Epsilon));\n\n   template <typename T>\n   inline bool robust_perpendicular(const line<T,3>& line1,\n                                    const line<T,3>& line2,\n                                    const T& epsilon = T(Epsilon));\n\n   template <typename T>\n   inline bool robust_perpendicular(const line<T,2>& line,\n                                    const segment<T,2>& segment,\n                                    const T& epsilon = T(Epsilon));\n\n   template <typename T>\n   inline bool line_to_line_intersect(const T& x1, const T& y1,\n                                      const T& x2, const T& y2,\n                                      const T& x3, const T& y3,\n                                      const T& x4, const T& y4);\n   template <typename T>\n   inline bool line_to_line_intersect(const line<T,2>& line1, const line<T,2>& line2);\n\n   template <typename T>\n   inline bool rectangle_to_rectangle_intersect(const T& x1, const T& y1,\n                                                const T& x2, const T& y2,\n                                                const T& x3, const T& y3,\n                                                const T& x4, const T& y4);\n\n   template <typename T>\n   inline bool rectangle_to_rectangle_intersect(const rectangle<T>& rectangle1,\n                                                const rectangle<T>& rectangle2);\n\n   template <typename T>\n   inline bool box_to_box_intersect(const T& x1, const T& y1, const T& z1,\n                                    const T& x2, const T& y2, const T& z2,\n                                    const T& x3, const T& y3, const T& z3,\n                                    const T& x4, const T& y4, const T& z4);\n\n   template <typename T>\n   inline bool box_to_box_intersect(const box<T,3>& box1, const box<T,3>& box2);\n\n   template< typename T, unsigned int Dimension, typename Simplex, typename Bezier>\n   inline bool simplex_to_bezier_intersect(const Simplex& simplex,\n                                           const Bezier& bezier,\n                                           const std::size_t& steps);\n\n   template< typename T, unsigned int Dimension, typename Bezier, typename Iterator>\n   inline bool simplex_to_bezier_intersect(const Iterator& begin,\n                                           const Iterator& end,\n                                           const Bezier& bezier,\n                                           const std::size_t& steps);\n\n   template <typename T>\n   inline bool rectangle_within_rectangle(const T& x1, const T& y1,\n                                          const T& x2, const T& y2,\n                                          const T& x3, const T& y3,\n                                          const T& x4, const T& y4);\n\n   template <typename T>\n   inline bool rectangle_within_rectangle(const rectangle<T>& rectangle1,\n                                          const rectangle<T>& rectangle2);\n\n   template <typename T>\n   inline bool box_within_box(const T& x1, const T& y1, const T& z1,\n                              const T& x2, const T& y2, const T& z2,\n                              const T& x3, const T& y3, const T& z3,\n                              const T& x4, const T& y4, const T& z4);\n\n   template <typename T>\n   inline bool box_within_box(const box<T,3>& box1, const box<T,3>& box2);\n\n\n   template <typename T>\n   inline bool circle_within_rectangle(const T&  x, const T&  y, const T& radius,\n                                       const T& x1, const T& y1,\n                                       const T& x2, const T& y2);\n\n   template <typename T>\n   inline bool circle_within_rectangle(const circle<T>& circle, const rectangle<T>& rectangle);\n\n   template <typename T>\n   inline bool triangle_within_rectangle(const T& x1, const T& y1,\n                                         const T& x2, const T& y2,\n                                         const T& x3, const T& y3,\n                                         const T& x4, const T& y4,\n                                         const T& x5, const T& y5);\n   template <typename T>\n   inline bool triangle_within_rectangle(const triangle<T,2>& triangle, const rectangle<T>& rectangle);\n\n   template <typename T>\n   inline bool segment_within_rectangle(const T& x1, const T& y1,\n                                        const T& x2, const T& y2,\n                                        const T& x3, const T& y3,\n                                        const T& x4, const T& y4);\n\n   template <typename T>\n   inline bool segment_within_rectangle(const segment<T,2>& segment, const rectangle<T>& rectangle);\n\n\n   template <typename T>\n   inline bool quadix_within_rectangle(const T& x1, const T& y1,\n                                       const T& x2, const T& y2,\n                                       const T& x3, const T& y3,\n                                       const T& x4, const T& y4,\n                                       const T& x5, const T& y5,\n                                       const T& x6, const T& y6);\n\n   template <typename T>\n   inline bool quadix_within_rectangle(const quadix<T,2>& quadix, const rectangle<T>& rectangle);\n\n   template <typename T>\n   inline bool polygon_within_rectangle(const polygon<T,2>& polygon, const rectangle<T>& rectangle);\n\n   template <typename T>\n   inline bool sphere_within_box(const T&  x, const T&  y, const T&  z, const T& radius,\n                                 const T& x1, const T& y1, const T& z1,\n                                 const T& x2, const T& y2, const T& z2);\n\n   template <typename T>\n   inline bool sphere_within_box(const sphere<T>& sphere, const box<T,3>& box);\n\n   template <typename T>\n   inline bool triangle_within_box(const T& x1, const T& y1, const T& z1,\n                                   const T& x2, const T& y2, const T& z2,\n                                   const T& x3, const T& y3, const T& z3,\n                                   const T& x4, const T& y4, const T& z4,\n                                   const T& x5, const T& y5, const T& z5);\n   template <typename T>\n   inline bool triangle_within_box(const triangle<T,3>& triangle, const box<T,3>& box);\n\n   template <typename T>\n   inline bool segment_within_box(const T& x1, const T& y1, const T& z1,\n                                  const T& x2, const T& y2, const T& z2,\n                                  const T& x3, const T& y3, const T& z3,\n                                  const T& x4, const T& y4, const T& z4) ;\n\n   template <typename T>\n   inline bool segment_within_box(const segment<T,3>& segment, const box<T,3>& box);\n\n\n   template <typename T>\n   inline bool quadix_within_box(const T& x1, const T& y1, const T& z1,\n                                 const T& x2, const T& y2, const T& z2,\n                                 const T& x3, const T& y3, const T& z3,\n                                 const T& x4, const T& y4, const T& z4,\n                                 const T& x5, const T& y5, const T& z5,\n                                 const T& x6, const T& y6, const T& z6);\n\n   template <typename T>\n   inline bool quadix_within_box(const quadix<T,3>& quadix, const box<T,3>& box);\n\n   template <typename T>\n   inline bool polygon_within_box(const polygon<T,3>& polygon, const box<T,3>& box);\n\n   template <typename T>\n   inline bool circle_in_circle(const circle<T>& circle1, const circle<T>& circle2);\n\n   template <typename T>\n   inline bool is_tangent(const segment<T,2>& segment, const circle<T>& circle);\n\n   template <typename T>\n   inline bool point_of_reflection(const T& sx1, const T& sy1,\n                                   const T& sx2, const T& sy2,\n                                   const T& p1x, const T& p1y,\n                                   const T& p2x, const T& p2y,\n                                         T& rpx,       T& rpy);\n   template <typename T>\n   inline bool point_of_reflection(const segment<T,2>& segment,\n                                   const point2d<T>&   point1,\n                                   const point2d<T>&   point2,\n                                         point2d<T>&   reflection_point);\n\n   template <typename T> inline segment<T,2> edge(const triangle<T,2>& triangle, const std::size_t& edge_index);\n   template <typename T> inline segment<T,3> edge(const triangle<T,3>& triangle, const std::size_t& edge_index);\n   template <typename T> inline segment<T,2> edge(const quadix<T,2>& quadix, const std::size_t& edge_index);\n   template <typename T> inline segment<T,3> edge(const quadix<T,3>& quadix, const std::size_t& edge_index);\n   template <typename T> inline segment<T,2> edge(const rectangle<T>& rectangle, const std::size_t& edge);\n   template <typename T> inline segment<T,2> edge(const polygon<T,2>& polygon, const std::size_t& edge);\n   template <typename T> inline segment<T,3> edge(const polygon<T,3>& polygon, const std::size_t& edge);\n\n   template <typename T> inline segment<T,2> opposing_edge(const triangle<T,2>& triangle, const std::size_t& corner);\n   template <typename T> inline segment<T,3> opposing_edge(const triangle<T,3>& triangle, const std::size_t& corner);\n\n   template <typename T> inline segment<T,2> reverse_segment(const segment<T,2>& segment);\n   template <typename T> inline segment<T,3> reverse_segment(const segment<T,3>& segment);\n\n   template <typename T> inline point2d<T> rectangle_corner(const rectangle<T>& rectangle, const std::size_t& corner_index);\n   template <typename T> inline point3d<T> box_corner(const box<T,3>& box, const std::size_t& corner_index);\n\n   template <typename T> inline line<T,2> triangle_bisector(const triangle<T,2>& triangle, const std::size_t& bisector);\n   template <typename T> inline line<T,3> triangle_bisector(const triangle<T,3>& triangle, const std::size_t& bisector);\n\n   template <typename T>\n   inline line<T,2> triangle_external_bisector(const triangle<T,2>& triangle,\n                                               const std::size_t& corner,\n                                               const std::size_t& opposing_corner);\n\n   template <typename T>\n   inline line<T,3> triangle_external_bisector(const triangle<T,3>& triangle,\n                                               const std::size_t& corner,\n                                               const std::size_t& opposing_corner);\n\n   template <typename T> inline line<T,2> triangle_median(const triangle<T,2>& triangle, const std::size_t& median);\n   template <typename T> inline line<T,3> triangle_median(const triangle<T,3>& triangle, const std::size_t& median);\n\n   template <typename T> inline line<T,2> triangle_symmedian(const triangle<T,2>& triangle, const std::size_t& symmedian);\n   template <typename T> inline line<T,3> triangle_symmedian(const triangle<T,3>& triangle, const std::size_t& symmedian);\n\n   template <typename T> inline line<T,2> euler_line(const triangle<T,2>& triangle);\n   template <typename T> inline line<T,3> euler_line(const triangle<T,3>& triangle);\n\n   template <typename T> inline point2d<T> exmedian_point(const triangle<T,2>& triangle, const std::size_t& corner);\n   template <typename T> inline point3d<T> exmedian_point(const triangle<T,3>& triangle, const std::size_t& corner);\n\n   template <typename T> inline point2d<T> feuerbach_point(const triangle<T,2>& triangle);\n\n   template <typename T>\n   inline line<T,2> confined_triangle_median(const triangle<T,2>& triangle,const point2d<T>& point, const std::size_t& median);\n\n   template <typename T>\n   inline line<T,3> confined_triangle_median(const triangle<T,3>& triangle,const point3d<T>& point, const std::size_t& median);\n\n   template <typename T> inline line<T,2> create_parallel_line_on_point(const line<T,2>& line, const point2d<T>& point);\n   template <typename T> inline line<T,3> create_parallel_line_on_point(const line<T,3>& line, const point3d<T>& point);\n\n   template <typename T> inline segment<T,2> create_parallel_segment_on_point(const line<T,2>& line, const point2d<T>& point);\n   template <typename T> inline segment<T,3> create_parallel_segment_on_point(const line<T,3>& line, const point3d<T>& point);\n\n   template <typename T>\n   inline bool point_in_rectangle(const T& px, const T& py,\n                                  const T& x1, const T& y1,\n                                  const T& x2, const T& y2);\n\n   template <typename T>\n   inline bool point_in_rectangle(const point2d<T>& point,\n                                  const T& x1, const T& y1,\n                                  const T& x2, const T& y2);\n\n   template <typename T>\n   inline bool point_in_rectangle(const T& px, const T& py, const rectangle<T>& rectangle);\n\n   template <typename T>\n   inline bool point_in_rectangle(const point2d<T>& point, const rectangle<T>& rectangle);\n\n   template <typename T>\n   inline bool point_in_rectangle(const point2d<T>& point, const point2d<T>& rect_point1, point2d<T>& rect_point2);\n\n   template <typename T>\n   inline bool point_in_rectangle(const point2d<T>& point, const segment<T,2>& segment);\n\n   template <typename T>\n   inline bool point_in_box(const T& px, const T& py, const T& pz,\n                            const T& x1, const T& y1, const T& z1,\n                            const T& x2, const T& y2, const T& z2);\n\n   template <typename T>\n   inline bool point_in_box(const point3d<T>& point,\n                            const T& x1, const T& y1, const T& z1,\n                            const T& x2, const T& y2, const T& z2);\n\n   template <typename T>\n   inline bool point_in_box(const T& px, const T& py, const T& pz, const box<T,3>& box);\n\n   template <typename T>\n   inline bool point_in_box(const point3d<T>& point, const box<T,3>& box);\n\n   template <typename T>\n   inline bool point_in_box(const point3d<T>& point, const point3d<T>& box_point1, const point3d<T>& box_point2);\n\n   template <typename T>\n   inline bool point_in_box(const point3d<T>& point, const segment<T,3>& segment);\n\n   /**\n    * @brief Check whether a point is in the triangle (including on the edge of the triangle) or not\n    *\n    * @tparam T\n    * @param px\n    * @param py\n    * @param x1\n    * @param y1\n    * @param x2\n    * @param y2\n    * @param x3\n    * @param y3\n    * @return true\n    * @return false\n    */\n   template <typename T>\n   inline bool point_in_triangle(const T& px, const T& py,\n                                 const T& x1, const T& y1,\n                                 const T& x2, const T& y2,\n                                 const T& x3, const T& y3);\n   template <typename T>\n   inline bool point_in_triangle(const point2d<T>& point,\n                                 const point2d<T>& point1,\n                                 const point2d<T>& point2,\n                                 const point2d<T>& point3);\n\n\n   template <typename T>\n   inline bool point_in_triangle(const T& px, const T& py, const triangle<T,2>& triangle);\n\n   template <typename T>\n   inline bool point_in_triangle(const point2d<T>& point, const triangle<T,2>& triangle);\n\n   template <typename T>\n   inline bool point_in_plane(T px, T py, T pz, const plane<T,3>& plane);\n\n   template <typename T>\n   inline bool point_in_plane(const point3d<T> point, const plane<T,3>& plane);\n\n   template <typename T>\n   inline bool segment_in_plane(const segment<T,3> seg, const plane<T,3>& plane);\n\n   /**\n    * @brief Check whether a point is in the quadrangle (including on the edge of the quadrangle)\n    *\n    * @tparam T\n    * @param px\n    * @param py\n    * @param x1\n    * @param y1\n    * @param x2\n    * @param y2\n    * @param x3\n    * @param y3\n    * @param x4\n    * @param y4\n    * @return true\n    * @return false\n    */\n   template <typename T>\n   inline bool point_in_quadix(const T& px, const T& py,\n                               const T& x1, const T& y1,\n                               const T& x2, const T& y2,\n                               const T& x3, const T& y3,\n                               const T& x4, const T& y4);\n\n   template <typename T>\n   inline bool point_in_quadix(const point2d<T>& point,\n                               const point2d<T>& point1,\n                               const point2d<T>& point2,\n                               const point2d<T>& point3,\n                               const point2d<T>& point4);\n\n   template <typename T>\n   inline bool point_in_quadix(const T& px, const T& py,\n                               const quadix<T,2>& quadix);\n   template <typename T>\n   inline bool point_in_quadix(const point2d<T>&  point,\n                               const quadix<T,2>& quadix);\n\n   template <typename T>\n   inline bool point_in_circle(const T& px, const T& py, const T& cx, const T& cy, const T& radius);\n\n   template <typename T>\n   inline bool point_in_circle(const T& px, const T& py, const circle<T>& circle);\n\n   template <typename T>\n   inline bool point_in_circle(const point2d<T>& point, const circle<T>& circle);\n\n   template <typename T>\n   inline bool point_in_sphere(const T& px, const T& py, const T& pz, const T& cx, const T& cy, const T& cz, const T& radius);\n\n   template <typename T>\n   inline bool point_in_sphere(const T& px, const T& py, const T& pz, const sphere<T>& sphere);\n\n   template <typename T>\n   inline bool point_in_sphere(const point3d<T>& point, const sphere<T>& sphere);\n\n   template <typename T>\n   inline bool point_in_three_point_circle(const T& px, const T& py,\n                                           const T& x1, const T& y1,\n                                           const T& x2, const T& y2,\n                                           const T& x3, const T& y3);\n\n   template <typename T>\n   inline bool point_in_three_point_circle(const point2d<T>& point,\n                                           const point2d<T>& point1,\n                                           const point2d<T>& point2,\n                                           const point2d<T>& point3);\n\n   template <typename T>\n   inline bool point_in_three_point_circle(const point2d<T>& point, const triangle<T,2> triangle);\n\n   template <typename T>\n   inline bool point_in_focus_area(const T& px, const T& py,\n                                   const T& x1, const T& y1,\n                                   const T& x2, const T& y2,\n                                   const T& x3, const T& y3);\n   template <typename T>\n   inline bool point_in_focus_area(const point2d<T>& point,\n                                   const point2d<T>& point1,\n                                   const point2d<T>& point2,\n                                   const point2d<T>& point3);\n\n   template <typename T>\n   inline bool point_on_segment(const point2d<T>& point, const segment<T,2>& segment);\n\n   template <typename T>\n   inline bool point_on_segment(const point3d<T>& point, const segment<T,3>& segment);\n\n   template <typename T>\n   inline bool point_on_ray(const T& px, const T& py,\n                            const T& ox, const T& oy,\n                            const T& dx, const T& dy);\n\n   template <typename T>\n   inline bool point_on_ray(const T& px, const T& py, const T& pz,\n                            const T& ox, const T& oy, const T& oz,\n                            const T& dx, const T& dy, const T& dz);\n\n   template <typename T>\n   inline bool point_on_ray(const point2d<T>& point, const ray<T,2>& ray);\n\n   template <typename T>\n   inline bool point_on_ray(const point3d<T>& point, const ray<T,3>& ray);\n\n   template <typename T>\n   inline bool point_on_rectangle(const T& px, const T& py,\n                                  const T& x1, const T& y1,\n                                  const T& x2, const T& y2);\n\n   template <typename T>\n   inline bool point_on_rectangle(const point2d<T>& point,\n                                  const T& x1, const T& y1,\n                                  const T& x2, const T& y2);\n\n   template <typename T>\n   inline bool point_on_rectangle(const T& px, const T& py, const rectangle<T>& rectangle);\n\n   template <typename T>\n   inline bool point_on_rectangle(const point2d<T>& point, const rectangle<T>& rectangle);\n\n   template <typename T>\n   inline bool point_on_triangle(const T& px, const T& py,\n                                 const T& x1, const T& y1,\n                                 const T& x2, const T& y2,\n                                 const T& x3, const T& y3);\n   template <typename T>\n   inline bool point_on_triangle(const point2d<T>& point,\n                                 const point2d<T>& point1,\n                                 const point2d<T>& point2,\n                                 const point2d<T>& point3);\n\n\n   template <typename T>\n   inline bool point_on_triangle(const T& px, const T& py, const triangle<T,2>& triangle);\n\n   template <typename T>\n   inline bool point_on_triangle(const point2d<T>& point, const triangle<T,2>& triangle);\n\n   template <typename T>\n   inline bool point_on_quadix(const T& px, const T& py,\n                               const T& x1, const T& y1,\n                               const T& x2, const T& y2,\n                               const T& x3, const T& y3,\n                               const T& x4, const T& y4);\n\n   template <typename T>\n   inline bool point_on_quadix(const point2d<T>& point,\n                               const point2d<T>& point1,\n                               const point2d<T>& point2,\n                               const point2d<T>& point3,\n                               const point2d<T>& point4);\n\n   template <typename T>\n   inline bool point_on_quadix(const T& px, const T& py,\n                               const quadix<T,2>& quadix);\n   template <typename T>\n   inline bool point_on_quadix(const point2d<T>&  point,\n                               const quadix<T,2>& quadix);\n\n   template <typename T>\n   inline bool point_on_circle(const T& px, const T& py, const T& cx, const T& cy, const T& radius);\n\n   template <typename T>\n   inline bool point_on_circle(const T& px, const T& py, const circle<T>& circle);\n\n   template <typename T>\n   inline bool point_on_circle(const point2d<T>& point, const circle<T>& circle);\n\n   template <typename T>\n   inline bool point_on_bezier(const point2d<T>& point, const quadratic_bezier<T,2>& bezier, const std::size_t& steps = 1000, const T& fuzzy = T(Epsilon));\n\n   template <typename T>\n   inline bool point_on_bezier(const point2d<T>& point, const cubic_bezier<T,2>& bezier, const std::size_t& steps = 1000, const T& fuzzy = T(Epsilon));\n\n   template <typename T>\n   inline bool point_on_bezier(const point3d<T>& point, const quadratic_bezier<T,3>& bezier, const std::size_t& steps = 1000, const T& fuzzy = T(Epsilon));\n\n   template <typename T>\n   inline bool point_on_bezier(const point3d<T>& point, const cubic_bezier<T,3>& bezier, const std::size_t& steps = 1000, const T& fuzzy = T(Epsilon));\n\n   template <typename T>\n   inline point2d<T> isogonal_conjugate(const point2d<T>& point, const triangle<T,2>& triangle);\n\n   template <typename T>\n   inline point3d<T> isogonal_conjugate(const point3d<T>& point, const triangle<T,3>& triangle);\n\n   template <typename T>\n   inline point2d<T> cyclocevian_conjugate(const point2d<T>& point, const triangle<T,2>& triangle);\n\n   template <typename T>\n   inline point2d<T> symmedian_point(const triangle<T,2>& triangle);\n\n   template <typename T>\n   inline point3d<T> symmedian_point(const triangle<T,3>& triangle);\n\n   template <typename T>\n   inline void create_equilateral_triangle(const T& x1, const T& y1,\n                                           const T& x2, const T& y2,\n                                                 T& x3,       T& y3);\n\n   template <typename T>\n   inline void create_equilateral_triangle(const point2d<T>& point1,\n                                           const point2d<T>& point2,\n                                                 point2d<T>& point3);\n\n   template <typename T>\n   inline triangle<T,2> create_equilateral_triangle(const T& x1, const T& y1,\n                                                    const T& x2, const T& y2);\n\n   template <typename T>\n   inline triangle<T,2> create_equilateral_triangle(const point2d<T>& point1,\n                                                    const point2d<T>& point2);\n\n   template <typename T> inline triangle<T,2> create_equilateral_triangle(const T& cx, const T& cy, const T& side_length);\n   template <typename T> inline triangle<T,2> create_equilateral_triangle(const point2d<T>& center_point, const T& side_length);\n\n   template <typename T> inline triangle<T,2> create_isosceles_triangle(const point2d<T>& point1, const point2d<T>& point2, const T& angle);\n   template <typename T> inline triangle<T,2> create_isosceles_triangle(const segment<T,2>& segment, const T& angle);\n\n   template <typename T> inline triangle<T,2> create_triangle(const point2d<T>& point1, const point2d<T>& point2, const T& angle1, const T& angle2);\n   template <typename T> inline triangle<T,2> create_triangle(const segment<T,2>& segment, const T& angle1, const T& angle2);\n\n   template <typename T> inline triangle<T,2> create_morley_triangle(const triangle<T,2>& triangle);\n\n   template <typename T> inline triangle<T,2> create_cevian_triangle(const triangle<T,2>& triangle, const point2d<T>& point);\n   template <typename T> inline triangle<T,3> create_cevian_triangle(const triangle<T,3>& triangle, const point3d<T>& point);\n\n   template <typename T> inline triangle<T,2> create_anticevian_triangle(const triangle<T,2>& triangle, const point2d<T>& point);\n   template <typename T> inline triangle<T,3> create_anticevian_triangle(const triangle<T,3>& triangle, const point3d<T>& point);\n\n   template <typename T> inline triangle<T,2> create_anticomplementary_triangle(const triangle<T,2>& triangle);\n   template <typename T> inline triangle<T,3> create_anticomplementary_triangle(const triangle<T,3>& triangle);\n\n   template <typename T> inline triangle<T,2> create_inner_napoleon_triangle(const triangle<T,2>& triangle);\n\n   template <typename T> inline triangle<T,2> create_outer_napoleon_triangle(const triangle<T,2>& triangle);\n\n   template <typename T> inline triangle<T,2> create_inner_vecten_triangle(const triangle<T,2>& triangle);\n\n   template <typename T> inline triangle<T,2> create_outer_vecten_triangle(const triangle<T,2>& triangle);\n\n   template <typename T> inline triangle<T,2> create_medial_triangle(const triangle<T,2>& triangle);\n   template <typename T> inline triangle<T,3> create_medial_triangle(const triangle<T,3>& triangle);\n\n   template <typename T> inline triangle<T,2> create_contact_triangle(const triangle<T,2>& triangle);\n   template <typename T> inline triangle<T,3> create_contact_triangle(const triangle<T,3>& triangle);\n\n   template <typename T> inline triangle<T,2> create_symmedial_triangle(const triangle<T,2>& triangle, const point2d<T>& point);\n\n   template <typename T> inline triangle<T,2> create_orthic_triangle(const triangle<T,2>& triangle);\n   template <typename T> inline triangle<T,3> create_orthic_triangle(const triangle<T,3>& triangle);\n\n   template <typename T> inline triangle<T,2> create_pedal_triangle(const point2d<T>& point, const triangle<T,2>& triangle);\n   template <typename T> inline triangle<T,3> create_pedal_triangle(const point3d<T>& point, const triangle<T,3>& triangle);\n\n   template <typename T> inline triangle<T,2> create_antipedal_triangle(const point2d<T>& point, const triangle<T,2>& triangle);\n\n   template <typename T> inline triangle<T,2> create_excentral_triangle(const triangle<T,2>& triangle);\n   template <typename T> inline triangle<T,3> create_excentral_triangle(const triangle<T,3>& triangle);\n\n   template <typename T> inline triangle<T,2> create_incentral_triangle(const triangle<T,2>& triangle);\n   template <typename T> inline triangle<T,3> create_incentral_triangle(const triangle<T,3>& triangle);\n\n   template <typename T> inline triangle<T,2> create_intouch_triangle(const triangle<T,2>& triangle);\n\n   template <typename T> inline triangle<T,2> create_extouch_triangle(const triangle<T,2>& triangle);\n   template <typename T> inline triangle<T,3> create_extouch_triangle(const triangle<T,3>& triangle);\n\n   template <typename T> inline triangle<T,2> create_feuerbach_triangle(const triangle<T,2>& triangle);\n\n   template <typename T> inline triangle<T,2> create_circumcevian_triangle(const triangle<T,2>& triangle, const point2d<T>& point);\n\n   template <typename T> inline triangle<T,2> create_circummedial_triangle(const triangle<T,2>& triangle);\n\n   template <typename T> inline triangle<T,2> create_first_brocard_triangle(const triangle<T,2>& triangle);\n\n   template <typename T> inline void create_right_triangle(const wykobi::point2d<T>& p1, const wykobi::point2d<T>& p2,\n                                                          wykobi::point2d<T>& c1, wykobi::point2d<T>& c2);\n\n   template <typename T>\n   inline void create_equilateral_quadix(const T& x1, const T& y1,\n                                         const T& x2, const T& y2,\n                                               T& x3,       T& y3,\n                                               T& x4,       T& y4);\n\n   template <typename T>\n   inline void create_equilateral_quadix(const point2d<T>& point1,\n                                         const point2d<T>& point2,\n                                               point2d<T>& point3,\n                                               point2d<T>& point4);\n\n   template <typename T>\n   inline quadix<T,2> create_equilateral_quadix(const T& x1, const T& y1,\n                                                const T& x2, const T& y2);\n\n   template <typename T>\n   inline quadix<T,2> create_equilateral_quadix(const point2d<T>& point1,\n                                                const point2d<T>& point2);\n\n   template <typename T>\n   inline quadix<T,2> create_equilateral_quadix(const segment<T,2>& segment);\n\n   template <typename T>\n   inline quadix<T,2> create_equilateral_quadix(const T& cx, const T& cy, const T& side_length);\n\n   template <typename T>\n   inline quadix<T,2> create_equilateral_quadix(const point2d<T>& center_point, const T& side_length);\n\n   template <typename T>\n   inline void torricelli_point(const T& x1, const T& y1,\n                                const T& x2, const T& y2,\n                                const T& x3, const T& y3,\n                                      T& px,       T& py);\n\n   template <typename T>\n   inline point2d<T> torricelli_point(const point2d<T>& point1,\n                                      const point2d<T>& point2,\n                                      const point2d<T>& point3);\n\n   template <typename T>\n   inline point2d<T> torricelli_point(const triangle<T,2>& triangle);\n\n   template <typename T> inline bool trilateration(const T& c0x, const T& c0y, const T& c0r,\n                                                   const T& c1x, const T& c1y, const T& c1r,\n                                                   const T& c2x, const T& c2y, const T& c2r,\n                                                         T&  px,       T&  py);\n\n   template <typename T> inline point2d<T> trilateration(const circle<T>& c0, const circle<T>& c1, const circle<T>& c2);\n\n   template <typename T>\n   inline void incenter(const T& x1, const T& y1,\n                        const T& x2, const T& y2,\n                        const T& x3, const T& y3,\n                              T& px,       T& py);\n\n   template <typename T>\n   inline void incenter(const T& x1, const T& y1, const T& z1,\n                        const T& x2, const T& y2, const T& z2,\n                        const T& x3, const T& y3, const T& z3,\n                              T& px,       T& py,       T& pz);\n\n   template <typename T>\n   inline point2d<T> incenter(const point2d<T>& point1,\n                              const point2d<T>& point2,\n                              const point2d<T>& point3);\n\n   template <typename T>\n   inline point3d<T> incenter(const point3d<T>& point1,\n                              const point3d<T>& point2,\n                              const point3d<T>& point3);\n\n   template <typename T>\n   inline point2d<T> incenter(const triangle<T,2>& triangle);\n\n   template <typename T>\n   inline point3d<T> incenter(const triangle<T,3>& triangle);\n\n   template <typename T>\n   inline void circumcenter(const T& x1, const T& y1,\n                            const T& x2, const T& y2,\n                            const T& x3, const T& y3,\n                                  T& px,       T& py);\n\n   template <typename T>\n   inline void circumcenter(const T& x1, const T& y1, const T& z1,\n                            const T& x2, const T& y2, const T& z2,\n                            const T& x3, const T& y3, const T& z3,\n                                  T& px,       T& py,       T& pz);\n\n\n   template <typename T>\n   inline point2d<T> circumcenter(const point2d<T>& point1,\n                                  const point2d<T>& point2,\n                                  const point2d<T>& point3);\n\n   template <typename T>\n   inline point3d<T> circumcenter(const point3d<T>& point1,\n                                  const point3d<T>& point2,\n                                  const point3d<T>& point3);\n\n   template <typename T>\n   inline point2d<T> circumcenter(const triangle<T,2>& triangle);\n\n   template <typename T>\n   inline point3d<T> circumcenter(const triangle<T,3>& triangle);\n\n   template <typename T>\n   inline circle<T> circumcircle(const T& x1, const T& y1,\n                                 const T& x2, const T& y2,\n                                 const T& x3, const T& y3);\n\n   template <typename T>\n   inline circle<T> circumcircle(const point2d<T>& point1,\n                                 const point2d<T>& point2,\n                                 const point2d<T>& point3);\n\n   template <typename T>\n   inline circle<T> circumcircle(const triangle<T,2>& triangle);\n\n   template <typename T>\n   inline sphere<T> circumsphere(const T& x1, const T& y1, const T& z1,\n                                 const T& x2, const T& y2, const T& z2,\n                                 const T& x3, const T& y3, const T& z3);\n\n   template <typename T>\n   inline sphere<T> circumsphere(const point3d<T>& point1,\n                                 const point3d<T>& point2,\n                                 const point3d<T>& point3);\n\n   template <typename T>\n   inline sphere<T> circumsphere(const triangle<T,3>& triangle);\n\n\n   template <typename T>\n   inline circle<T> inscribed_circle(const T& x1, const T& y1,\n                                     const T& x2, const T& y2,\n                                     const T& x3, const T& y3);\n\n   template <typename T>\n   inline circle<T> inscribed_circle(const point2d<T>& point1,\n                                     const point2d<T>& point2,\n                                     const point2d<T>& point3);\n\n   template <typename T>\n   inline circle<T> inscribed_circle(const triangle<T,2>& triangle);\n\n   template <typename T>\n   inline sphere<T> inscribed_sphere(const T& x1, const T& y1, const T& z1,\n                                     const T& x2, const T& y2, const T& z2,\n                                     const T& x3, const T& y3, const T& z3);\n\n   template <typename T>\n   inline sphere<T> inscribed_sphere(const point3d<T>& point1,\n                                     const point3d<T>& point2,\n                                     const point3d<T>& point3);\n\n   template <typename T>\n   inline sphere<T> inscribed_sphere(const triangle<T,3>& triangle);\n\n   template <typename T>\n   inline circle<T> nine_point_circle(const T& x1, const T& y1,\n                                      const T& x2, const T& y2,\n                                      const T& x3, const T& y3);\n\n   template <typename T>\n   inline circle<T> nine_point_circle(const point2d<T>& point1,\n                                      const point2d<T>& point2,\n                                      const point2d<T>& point3);\n\n   template <typename T>\n   inline circle<T> nine_point_circle(const triangle<T,2>& triangle);\n\n   template <typename T>\n   inline point2d<T> orthocenter(const triangle<T,2>& triangle);\n\n   template <typename T>\n   inline point3d<T> orthocenter(const triangle<T,3>& triangle);\n\n   template <typename T>\n   inline point2d<T> excenter(const triangle<T,2>& triangle, const std::size_t& corner);\n\n   template <typename T>\n   inline point3d<T> excenter(const triangle<T,3>& triangle, const std::size_t& corner);\n\n   template <typename T>\n   inline circle<T> excircle(const triangle<T,2>& triangle, const std::size_t& i);\n\n   template <typename T>\n   inline circle<T> mandart_circle(const triangle<T,2>& triangle);\n\n   template <typename T>\n   inline circle<T> brocard_circle(const triangle<T,2>& triangle);\n\n   template <typename T>\n   inline circle<T> invert_circle_across_circle(const circle<T>& circle1, const circle<T>& circle2);\n\n   template <typename T>\n   inline sphere<T> invert_sphere_across_sphere(const sphere<T>& sphere1, const sphere<T>& sphere2);\n\n   template <typename T>\n   inline void circle_tangent_points(const circle<T>& circle, const point2d<T>& point, point2d<T>& point1, point2d<T>& point2);\n\n   template <typename T>\n   inline void circle_internal_tangent_lines(const circle<T>& circle0,\n                                             const circle<T>& circle1,\n                                             std::vector< line<T,2> >& lines);\n\n   template <typename T>\n   inline void circle_internal_tangent_segments(const circle<T>& circle0,\n                                                const circle<T>& circle1,\n                                                std::vector< segment<T,2> >& segments);\n\n   template <typename T>\n   inline void circle_outer_tangent_lines(const circle<T>& circle0,\n                                          const circle<T>& circle1,\n                                          std::vector< line<T,2> >& lines);\n\n   template <typename T>\n   inline void circle_outer_tangent_segments(const circle<T>& circle0,\n                                             const circle<T>& circle1,\n                                             std::vector< segment<T,2> >& segments);\n\n   template <typename T>\n   inline line<T,2> tangent_line(const circle<T>& circle, const point2d<T>& point);\n\n   template <typename T>\n   inline line<T,2> create_line_from_bisector(const T& x1, const T& y1,\n                                              const T& x2, const T& y2,\n                                              const T& x3, const T& y3);\n\n   template <typename T>\n   inline segment<T,2> create_segment_from_bisector(const T& x1, const T& y1,\n                                                    const T& x2, const T& y2,\n                                                    const T& x3, const T& y3);\n\n   template <typename T>\n   inline ray<T,2> create_ray_from_bisector(const T& x1, const T& y1,\n                                            const T& x2, const T& y2,\n                                            const T& x3, const T& y3);\n\n   template <typename T>\n   inline line<T,3> create_line_from_bisector(const T& x1, const T& y1, const T& z1,\n                                              const T& x2, const T& y2, const T& z2,\n                                              const T& x3, const T& y3, const T& z3);\n\n   template <typename T>\n   inline segment<T,3> create_segment_from_bisector(const T& x1, const T& y1, const T& z1,\n                                                    const T& x2, const T& y2, const T& z2,\n                                                    const T& x3, const T& y3, const T& z3);\n\n   template <typename T>\n   inline ray<T,3> create_ray_from_bisector(const T& x1, const T& y1, const T& z1,\n                                            const T& x2, const T& y2, const T& z2,\n                                            const T& x3, const T& y3, const T& z3);\n\n   template <typename T> inline line<T,2> create_line_from_bisector(const point2d<T>& point1,const point2d<T>& point2,const point2d<T>& point3);\n   template <typename T> inline segment<T,2> create_segment_from_bisector(const point2d<T>& point1,const point2d<T>& point2,const point2d<T>& point3);\n   template <typename T> inline ray<T,2> create_ray_from_bisector(const point2d<T>& point1,const point2d<T>& point2,const point2d<T>& point3);\n   template <typename T> inline line<T,3> create_line_from_bisector(const point3d<T>& point1,const point3d<T>& point2,const point3d<T>& point3);\n   template <typename T> inline segment<T,3> create_segment_from_bisector(const point3d<T>& point1,const point3d<T>& point2,const point3d<T>& point3);\n   template <typename T> inline ray<T,3> create_ray_from_bisector(const point3d<T>& point1,const point3d<T>& point2,const point3d<T>& point3);\n\n   template <typename T> inline line<T,2> create_perpendicular_bisector(const T& x1, const T& y1,const T& x2, const T& y2);\n   template <typename T> inline line<T,2> create_perpendicular_bisector(const point2d<T>& point1, const point2d<T>& point2);\n   template <typename T> inline line<T,2> create_perpendicular_bisector(const segment<T,2>& segment);\n\n   template <typename T> inline line<T,2> create_perpendicular_line_at_end_point(const line<T,2>& line);\n\n   template <typename T>\n   inline void closest_point_on_segment_from_point(const T& x1, const T& y1,\n                                                   const T& x2, const T& y2,\n                                                   const T& px, const T& py,\n                                                         T& nx,       T& ny);\n\n   template <typename T>\n   inline void closest_point_on_segment_from_point(const T& x1, const T& y1, const T& z1,\n                                                   const T& x2, const T& y2, const T& z2,\n                                                   const T& px, const T& py, const T& pz,\n                                                         T& nx,       T& ny,       T& nz);\n\n   template <typename T>\n   inline void closest_point_on_line_from_point(const T& x1, const T& y1,\n                                                const T& x2, const T& y2,\n                                                const T& px, const T& py,\n                                                      T& nx,       T& ny);\n\n   template <typename T>\n   inline void closest_point_on_line_from_point(const T& x1, const T& y1, const T& z1,\n                                                const T& x2, const T& y2, const T& z2,\n                                                const T& px, const T& py, const T& pz,\n                                                      T& nx,       T& ny,       T& nz);\n\n   template <typename T>\n   inline void order_sensitive_closest_point_on_segment_from_point(const T& x1, const T& y1,\n                                                                   const T& x2, const T& y2,\n                                                                   const T& px, const T& py,\n                                                                         T& nx,       T& ny);\n\n   template <typename T>\n   inline void order_sensitive_closest_point_on_segment_from_point(const T& x1, const T& y1, const T& z1,\n                                                                   const T& x2, const T& y2, const T& z2,\n                                                                   const T& px, const T& py, const T& pz,\n                                                                         T& nx,       T& ny,       T& nz);\n\n   template <typename T>\n   inline void order_sensitive_closest_point_on_line_from_point(const T& x1, const T& y1,\n                                                                const T& x2, const T& y2,\n                                                                const T& px, const T& py,\n                                                                      T& nx,       T& ny);\n\n   template <typename T>\n   inline void order_sensitive_closest_point_on_line_from_point(const T& x1, const T& y1, const T& z1,\n                                                                const T& x2, const T& y2, const T& z2,\n                                                                const T& px, const T& py, const T& pz,\n                                                                      T& nx,       T& ny,       T& nz);\n\n   template <typename T>\n   inline void closest_point_on_ray_from_point(const T& ox, const T& oy,\n                                               const T& dx, const T& dy,\n                                               const T& px, const T& py,\n                                                     T& nx,       T& ny);\n\n   template <typename T>\n   inline void closest_point_on_ray_from_point(const T& ox, const T& oy, const T& oz,\n                                               const T& dx, const T& dy, const T& dz,\n                                               const T& px, const T& py, const T& pz,\n                                                     T& nx,       T& ny,       T& nz);\n\n   template <typename T>\n   inline point2d<T> closest_point_on_segment_from_point(const T& x1, const T& y1,\n                                                         const T& x2, const T& y2,\n                                                         const T& px, const T& py);\n\n   template <typename T>\n   inline point3d<T> closest_point_on_segment_from_point(const T& x1, const T& y1, const T& z1,\n                                                         const T& x2, const T& y2, const T& z2,\n                                                         const T& px, const T& py, const T& pz);\n\n   template <typename T>\n   inline point2d<T> closest_point_on_segment_from_point(const segment<T,2>& segment, const point2d<T>& point);\n\n   template <typename T>\n   inline point3d<T> closest_point_on_segment_from_point(const segment<T,3>& segment, const point3d<T>& point);\n\n   template <typename T>\n   inline point2d<T> closest_point_on_line_from_point(const T& x1, const T& y1,\n                                                      const T& x2, const T& y2,\n                                                      const T& px, const T& py);\n\n   template <typename T>\n   inline point3d<T> closest_point_on_line_from_point(const T& x1, const T& y1, const T& z1,\n                                                      const T& x2, const T& y2, const T& z2,\n                                                      const T& px, const T& py, const T& pz);\n\n   template <typename T>\n   inline point2d<T> closest_point_on_line_from_point(const line<T,2>& line, const point2d<T>& point);\n\n   template <typename T>\n   inline point3d<T> closest_point_on_line_from_point(const line<T,3>& line, const point3d<T>& point);\n\n\n   template <typename T>\n   inline point2d<T> closest_point_on_ray_from_point(const T& ox, const T& oy,\n                                                     const T& dx, const T& dy,\n                                                     const T& px, const T& py);\n\n   template <typename T>\n   inline point3d<T> closest_point_on_ray_from_point(const T& ox, const T& oy, const T& oz,\n                                                     const T& dx, const T& dy, const T& dz,\n                                                     const T& px, const T& py, const T& pz);\n\n   template <typename T>\n   inline point2d<T> closest_point_on_ray_from_point(const ray<T,2>& ray, const point2d<T>& point);\n\n   template <typename T>\n   inline point3d<T> closest_point_on_ray_from_point(const ray<T,3>& ray, const point3d<T>& point);\n\n   template <typename T>\n   inline void closest_point_on_triangle_from_point(const T& x1, const T& y1,\n                                                    const T& x2, const T& y2,\n                                                    const T& x3, const T& y3,\n                                                    const T& px, const T& py,\n                                                          T& nx,       T& ny);\n\n   template <typename T>\n   inline point2d<T> closest_point_on_triangle_from_point(const T& x1, const T& y1,\n                                                          const T& x2, const T& y2,\n                                                          const T& x3, const T& y3,\n                                                          const T& px, const T& py);\n\n   template <typename T>\n   inline point2d<T> closest_point_on_triangle_from_point(const triangle<T,2>& triangle, const T& px, const T& py);\n\n   template <typename T>\n   inline point2d<T> closest_point_on_triangle_from_point(const triangle<T,2>& triangle, const point2d<T>& point);\n\n   template <typename T>\n   inline void closest_point_on_triangle_from_point(const T& x1, const T& y1, const T& z1,\n                                                    const T& x2, const T& y2, const T& z2,\n                                                    const T& x3, const T& y3, const T& z3,\n                                                    const T& px, const T& py, const T& pz,\n                                                          T& nx,       T& ny,       T& nz);\n\n   template <typename T>\n   inline point3d<T> closest_point_on_triangle_from_point(const T& x1, const T& y1, const T& z1,\n                                                          const T& x2, const T& y2, const T& z2,\n                                                          const T& x3, const T& y3, const T& z3,\n                                                          const T& px, const T& py, const T& pz);\n\n   template <typename T>\n   inline point3d<T> closest_point_on_triangle_from_point(const triangle<T,3>& triangle, const T& px, const T& py, const T& pz);\n\n   template <typename T>\n   inline point3d<T> closest_point_on_triangle_from_point(const triangle<T,3>& triangle, const point3d<T>& point);\n\n   template <typename T>\n   inline void closest_point_on_rectangle_from_point(const T& x1, const T& y1,\n                                                     const T& x2, const T& y2,\n                                                     const T& px, const T& py,\n                                                           T& nx,       T& ny);\n\n   template <typename T>\n   inline point2d<T> closest_point_on_rectangle_from_point(const T& x1, const T& y1,\n                                                           const T& x2, const T& y2,\n                                                           const T& px, const T& py);\n\n   template <typename T>\n   inline point2d<T> closest_point_on_rectangle_from_point(const rectangle<T>& rectangle, const T& px, const T& py);\n\n   template <typename T>\n   inline point2d<T> closest_point_on_rectangle_from_point(const rectangle<T>& rectangle, const point2d<T>& point);\n\n   template <typename T>\n   inline void closest_point_on_box_from_point(const T& x1, const T& y1, const T& z1,\n                                               const T& x2, const T& y2, const T& z2,\n                                               const T& px, const T& py, const T& pz,\n                                                     T& nx,       T& ny,       T& nz);\n\n   template <typename T>\n   inline point3d<T> closest_point_on_box_from_point(const T& x1, const T& y1, const T& z1,\n                                                     const T& x2, const T& y2, const T& z2,\n                                                     const T& px, const T& py, const T& pz);\n\n   template <typename T>\n   inline point3d<T> closest_point_on_box_from_point(const box<T,3>& box, const T& px, const T& py, const T& pz);\n\n   template <typename T>\n   inline point3d<T> closest_point_on_box_from_point(const box<T,3>& box, const point3d<T>& point);\n\n   template <typename T>\n   inline void closest_point_on_quadix_from_point(const T& x1, const T& y1,\n                                                  const T& x2, const T& y2,\n                                                  const T& x3, const T& y3,\n                                                  const T& x4, const T& y4,\n                                                  const T& px, const T& py,\n                                                        T& nx,       T& ny);\n\n   template <typename T>\n   inline point2d<T> closest_point_on_quadix_from_point(const T& x1, const T& y1,\n                                                        const T& x2, const T& y2,\n                                                        const T& x3, const T& y3,\n                                                        const T& x4, const T& y4,\n                                                        const T& px, const T& py);\n   template <typename T>\n   inline point2d<T> closest_point_on_quadix_from_point(const quadix<T,2>& quadix, const point2d<T>& point);\n\n   template <typename T>\n   inline point2d<T> closest_point_on_circle_from_point(const circle<T>&  circle,\n                                                        const point2d<T>& point);\n\n   template <typename T>\n   inline point3d<T> closest_point_on_sphere_from_point(const sphere<T>&  sphere,\n                                                        const point3d<T>& point);\n\n   template <typename T>\n   inline point2d<T> closest_point_on_aabbb_from_point(const rectangle<T>& rectangle,\n                                                       const point2d<T>&   point);\n\n   template <typename T>\n   inline point2d<T> closest_point_on_circle_from_segment(const circle<T>&    circle,\n                                                          const segment<T,2>& segment);\n\n   template <typename T>\n   inline point3d<T> closest_point_on_sphere_from_segment(const sphere<T>&    sphere,\n                                                          const segment<T,3>& segment);\n\n   template <typename T>\n   inline point3d<T> closest_point_on_plane_from_point(const plane<T,3>& plane,\n                                                       const point3d<T>& point);\n\n   template <typename T>\n   inline point2d<T> closest_point_on_bezier_from_point(const quadratic_bezier<T,2>& bezier,\n                                                        const point2d<T>& point,\n                                                        const std::size_t& steps = 1000);\n\n   template <typename T>\n   inline point2d<T> closest_point_on_bezier_from_point(const cubic_bezier<T,2>& bezier,\n                                                        const point2d<T>& point,\n                                                        const std::size_t& steps = 1000);\n\n   template <typename T>\n   inline point3d<T> closest_point_on_bezier_from_point(const quadratic_bezier<T,3>& bezier,\n                                                        const point3d<T>& point,\n                                                        const std::size_t& steps = 1000);\n\n   template <typename T>\n   inline point3d<T> closest_point_on_bezier_from_point(const cubic_bezier<T,3>& bezier,\n                                                        const point3d<T>& point,\n                                                        const std::size_t& steps = 1000);\n\n   template <typename T>\n   inline point2d<T> closest_point_on_circle_from_circle(const circle<T>& circle1, const circle<T>& circle2);\n\n   template <typename T>\n   inline point3d<T> closest_point_on_sphere_from_sphere(const sphere<T>& sphere1, const sphere<T>& sphere2);\n\n   template <typename T>\n   inline point2d<T> closest_point_on_polygon_from_point(const polygon<T,2>& polygon, const point2d<T>& point);\n\n   template <typename T>\n   inline T minimum_distance_from_point_to_segment(const T& px, const T& py,\n                                                   const T& x1, const T& y1,\n                                                   const T& x2, const T& y2);\n\n   template <typename T>\n   inline T minimum_distance_from_point_to_segment(const T& px, const T& py, const T& pz,\n                                                   const T& x1, const T& y1, const T& z1,\n                                                   const T& x2, const T& y2, const T& z2);\n\n   template <typename T>\n   inline T minimum_distance_from_point_to_segment(const point2d<T>& point, const segment<T,2>& segment);\n\n   template <typename T>\n   inline T minimum_distance_from_point_to_segment(const point3d<T>& point, const segment<T,3>& segment);\n\n   template <typename T>\n   inline T minimum_distance_from_point_to_line(const T& px, const T& py,\n                                                const T& x1, const T& y1,\n                                                const T& x2, const T& y2);\n\n   template <typename T>\n   inline T minimum_distance_from_point_to_line(const T& px, const T& py, const T& pz,\n                                                const T& x1, const T& y1, const T& z1,\n                                                const T& x2, const T& y2, const T& z2);\n\n   template <typename T>\n   inline T minimum_distance_from_point_to_line(const point2d<T>& point, const line<T,2>& line);\n\n   template <typename T>\n   inline T minimum_distance_from_point_to_line(const point3d<T>& point, const line<T,3>& line);\n\n\n   template <typename T>\n   inline T minimum_distance_from_point_to_triangle(const T& px, const T& py,\n                                                    const T& x1, const T& y1,\n                                                    const T& x2, const T& y2,\n                                                    const T& x3, const T& y3);\n\n   template <typename T>\n   inline T minimum_distance_from_point_to_triangle(const point2d<T>& point, const triangle<T,2>& triangle);\n\n   template <typename T>\n   inline T minimum_distance_from_point_to_rectangle(const T& px, const T& py,\n                                                     const T& x1, const T& y1,\n                                                     const T& x2, const T& y2);\n\n   template <typename T>\n   inline T minimum_distance_from_point_to_rectangle(const point2d<T>& point, const rectangle<T>& rectangle);\n\n   template <typename T>\n   inline void segment_mid_point(const T&   x1, const T&   y1,\n                                 const T&   x2, const T&   y2,\n                                       T& midx,       T& midy);\n\n   template <typename T>\n   inline void segment_mid_point(const segment<T,2>& segment, T& midx, T& midy);\n\n   template <typename T>\n   inline point2d<T> segment_mid_point(const point2d<T>& point1, const point2d<T>& point2);\n\n   template <typename T>\n   inline point2d<T> segment_mid_point(const segment<T,2>& segment);\n\n   template <typename T>\n   inline void segment_mid_point(const T&   x1, const T&   y1, const T&   z1,\n                                 const T&   x2, const T&   y2, const T&   z2,\n                                       T& midx,       T& midy,       T& midz);\n\n   template <typename T>\n   inline void segment_mid_point(const segment<T,3>& segment, T& midx, T& midy, T& midz);\n\n   template <typename T>\n   inline point3d<T> segment_mid_point(const point3d<T>& point1, const point3d<T>& point2);\n\n   template <typename T>\n   inline point3d<T> segment_mid_point(const segment<T,3>& segment);\n\n   template <typename T>\n   inline void centroid(const T& x1, const T& y1,\n                        const T& x2, const T& y2,\n                              T&  x,       T&  y);\n\n   template <typename T>\n   inline point2d<T> centroid(const point2d<T>& point1, const point2d<T>& point2);\n\n   template <typename T>\n   inline point2d<T> centroid(const segment<T,2>& segment);\n\n   template <typename T>\n   inline void centroid(const T& x1, const T& y1,\n                        const T& x2, const T& y2,\n                        const T& x3, const T& y3,\n                              T&  x,       T&  y);\n\n   template <typename T>\n   inline void centroid(const T& x1, const T& y1, const T& z1,\n                        const T& x2, const T& y2, const T& z2,\n                        const T& x3, const T& y3, const T& z3,\n                              T&  x,       T&  y,       T& z);\n\n   template <typename T>\n   inline void centroid(const T& x1, const T& y1,\n                        const T& x2, const T& y2,\n                        const T& x3, const T& y3,\n                        const T& x4, const T& y4,\n                              T&  x,       T&  y);\n\n   template <typename T> inline void centroid(const triangle<T,2>& triangle, T& x, T& y);\n   template <typename T> inline void centroid(const triangle<T,3>& triangle, T& x, T& y,T& z);\n   template <typename T> inline void centroid(const quadix<T,2>& quadix, T& x, T& y);\n   template <typename T> inline void centroid(const rectangle<T>& rectangle, T& x, T& y);\n   template <typename T> inline void centroid(const box<T,3>& box, T& x, T& y, T& z);\n   template <typename T> inline void centroid(const polygon<T,2>& polygon, T& x, T& y);\n\n   template <typename T> inline point2d<T> centroid(const point2d<T>& point1, const point2d<T>& point2, const point2d<T>& point3);\n   template <typename T> inline point2d<T> centroid(const point2d<T>& point1, const point2d<T>& point2, const point2d<T>& point3, const point2d<T>& point4);\n   template <typename T> inline point2d<T> centroid(const triangle<T,2>& triangle);\n   template <typename T> inline point3d<T> centroid(const triangle<T,3>& triangle);\n   template <typename T> inline point2d<T> centroid(const quadix<T,2>& quadix);\n   template <typename T> inline point2d<T> centroid(const rectangle<T>& rectangle);\n   template <typename T> inline point3d<T> centroid(const box<T,3>& box);\n   template <typename T> inline point2d<T> centroid(const polygon<T,2>& polygon);\n\n   template <typename T> inline bool common_center(const circle<T>& circle1, const circle<T>& circle2);\n   template <typename T> inline bool common_center(const sphere<T>& sphere1, const sphere<T>& circle2);\n\n   template <typename T> inline bool point_in_convex_polygon(const T& px, const T& py, const polygon<T,2>& polygon);\n   template <typename T> inline bool point_in_convex_polygon(const point2d<T>& point, const polygon<T,2>& polygon);\n\n   template <typename T> inline bool point_on_polygon_edge(const T& px, const T& py, const polygon<T,2>& polygon);\n   template <typename T> inline bool point_on_polygon_edge(const point2d<T>& point, const polygon<T,2>& polygon);\n\n   /**\n    * @brief Test whether a point is in the polygon (including on the edge of the polygon) or not by ray casting algorithm\n    *\n    * @tparam T\n    * @param px\n    * @param py\n    * @param polygon\n    * @return true\n    * @return false\n    */\n   template <typename T> inline bool point_in_polygon(const T& px, const T& py, const polygon<T,2>& polygon);\n   template <typename T> inline bool point_in_polygon(const point2d<T>& point, const polygon<T,2>& polygon);\n\n   /**\n   * @brief Test whether a point is in the polygon (including on the edge of the polygon) or not by calculating winding number\n   *\n   * @tparam T\n   * @param px\n   * @param py\n   * @param polygon\n   * @return true\n   * @return false\n   */\n   template <typename T> inline bool point_in_polygon_winding_number(const T& px, const T& py, const polygon<T,2>& polygon);\n   template <typename T> inline bool point_in_polygon_winding_number(const point2d<T>& point, const polygon<T,2>& polygon);\n\n   template <typename T> inline bool convex_quadix(const quadix<T,2>& quadix);\n   template <typename T> inline bool convex_quadix(const quadix<T,3>& quadix);\n\n   template <typename T> inline bool is_convex_polygon(const polygon<T,2>& polygon);\n\n   template <typename T> inline polygon<T,2> remove_consecutive_collinear_points(const polygon<T,2>& polygon);\n\n   template <typename T, typename InputIterator, typename OutputIterator>\n   inline void remove_consecutive_collinear_points(const InputIterator begin, const InputIterator end, OutputIterator out);\n\n   template <typename T> inline bool convex_vertex(const std::size_t& index, const polygon<T,2>& polygon, const int& polygon_orientation = LeftHandSide);\n\n   template <typename T> inline bool collinear_vertex(const std::size_t& index, const polygon<T,2>& polygon);\n\n   template <typename T> inline bool vertex_is_ear(const std::size_t& index, const polygon<T,2>& polygon);\n\n   template <typename T> inline triangle<T,2> vertex_triangle(const std::size_t& index, const polygon<T,2> polygon);\n\n   template <typename T> inline int polygon_orientation(const polygon<T,2>& polygon);\n\n   template <typename T> inline bool is_equilateral_triangle(const triangle<T,2>& triangle);\n   template <typename T> inline bool is_equilateral_triangle(const triangle<T,3>& triangle);\n\n   template <typename T> inline bool is_isosceles_triangle(const triangle<T,2>& triangle);\n   template <typename T> inline bool is_isosceles_triangle(const triangle<T,3>& triangle);\n\n   template <typename T> inline bool is_right_triangle(const wykobi::triangle<T,2>& triangle);\n   template <typename T> inline bool is_right_triangle(const wykobi::triangle<T,3>& triangle);\n\n   template <typename T> inline bool are_perspective_triangles(const triangle<T,2>& triangle1, const triangle<T,2>& triangle2);\n   template <typename T> inline bool are_perspective_triangles(const triangle<T,3>& triangle1, const triangle<T,3>& triangle2);\n\n   template <typename T> inline line<T,2> perspectrix(const triangle<T,2>& triangle1, const triangle<T,2>& triangle2);\n   template <typename T> inline line<T,3> perspectrix(const triangle<T,3>& triangle1, const triangle<T,3>& triangle2);\n\n   template <typename T>\n   inline void mirror(const T& px, const T& py,\n                      const T& x1, const T& y1,\n                      const T& x2, const T& y2,\n                            T& nx,       T& ny);\n\n   template <typename T>\n   inline void mirror(const T& px, const T& py, const T& pz,\n                      const T& x1, const T& y1, const T& z1,\n                      const T& x2, const T& y2, const T& z2,\n                            T& nx,       T& ny,       T& nz);\n\n   template <typename T> inline point2d<T> mirror(const point2d<T>& point, const line<T,2>& mirror_axis);\n   template <typename T> inline segment<T,2> mirror(const segment<T,2>& segment, const line<T,2>& mirror_axis);\n   template <typename T> inline line<T,2> mirror(const line<T,2>& line, const wykobi::line<T,2>& mirror_axis);\n   template <typename T> inline rectangle<T> mirror(const rectangle<T>& rectangle, const line<T,2>& mirror_axis);\n   template <typename T> inline triangle<T,2> mirror(const triangle<T,2>& triangle, const line<T,2>& mirror_axis);\n   template <typename T> inline quadix<T,2> mirror(const quadix<T,2>& quadix, const line<T,2>& mirror_axis);\n   template <typename T> inline circle<T> mirror(const circle<T>& circle, const line<T,2>& mirror_axis);\n   template <typename T> inline polygon<T,2> mirror(const polygon<T,2>& polygon, const line<T,2>& mirror_axis);\n\n   template <typename T> inline point3d<T> mirror(const point3d<T>& point, const line<T,3>& mirror_axis);\n   template <typename T> inline segment<T,3> mirror(const segment<T,3>& segment, const line<T,3>& mirror_axis);\n   template <typename T> inline line<T,3> mirror(const line<T,3>& line, const wykobi::line<T,3>& mirror_axis);\n   template <typename T> inline box<T,3> mirror(const box<T,3>& box, const line<T,3>& mirror_axis);\n   template <typename T> inline triangle<T,3> mirror(const triangle<T,3>& triangle, const line<T,3>& mirror_axis);\n   template <typename T> inline quadix<T,3> mirror(const quadix<T,3>& quadix, const line<T,3>& mirror_axis);\n   template <typename T> inline sphere<T> mirror(const sphere<T>& sphere, const line<T,3>& mirror_axis);\n   template <typename T> inline polygon<T,3> mirror(const polygon<T,3>& polygon, const line<T,3>& mirror_axis);\n\n   template <typename T> inline point3d<T> mirror(const point3d<T>& point, const plane<T,3>& mirror_plane);\n   template <typename T> inline segment<T,3> mirror(const segment<T,3>& segment, const plane<T,3>& mirror_plane);\n   template <typename T> inline line<T,3> mirror(const line<T,3>& line, const plane<T,3>& mirror_plane);\n   template <typename T> inline box<T,3> mirror(const box<T,3>& box, const plane<T,3>& mirror_plane);\n   template <typename T> inline triangle<T,3> mirror(const triangle<T,3>& triangle, const plane<T,3>& mirror_plane);\n   template <typename T> inline quadix<T,3> mirror(const quadix<T,3>& quadix, const plane<T,3>& mirror_plane);\n   template <typename T> inline sphere<T> mirror(const sphere<T>& sphere, const plane<T,3>& mirror_plane);\n   template <typename T> inline polygon<T,3> mirror(const polygon<T,3>& polygon, const plane<T,3>& mirror_plane);\n\n   template <typename T>\n   inline void nonsymmetric_mirror(const T& px, const T& py,\n                                   const T& x1, const T& y1,\n                                   const T& x2, const T& y2,\n                                   const T& ratio,\n                                         T& nx,       T& ny);\n\n   template <typename T> inline point2d<T> nonsymmetric_mirror(const point2d<T>& point, const T& ratio, const line<T,2>& line);\n   template <typename T> inline segment<T,2> nonsymmetric_mirror(const segment<T,2>& segment, const T& ratio, const line<T,2>& line);\n   template <typename T> inline rectangle<T> nonsymmetric_mirror(const rectangle<T>& rectangle, const T& ratio, const line<T,2>& line);\n   template <typename T> inline triangle<T,2> nonsymmetric_mirror(const triangle<T,2>& triangle, const T& ratio, const line<T,2>& line);\n   template <typename T> inline quadix<T,2> nonsymmetric_mirror(const quadix<T,2>& quadix, const T& ratio, const line<T,2>& line);\n   template <typename T> inline circle<T> nonsymmetric_mirror(const circle<T>& circle, const T& ratio, const line<T,2>& line);\n   template <typename T> inline polygon<T,2> nonsymmetric_mirror(const polygon<T,2>& polygon, const T& ratio, const line<T,2>& line);\n\n   template <typename T> inline point3d<T> nonsymmetric_mirror(const point3d<T>& point, const T& ratio, const plane<T,3>& plane);\n   template <typename T> inline segment<T,3> nonsymmetric_mirror(const segment<T,3>& segment, const T& ratio, const plane<T,3>& plane);\n   template <typename T> inline box<T,3> nonsymmetric_mirror(const box<T,3>& box, const T& ratio, const plane<T,3>& plane);\n   template <typename T> inline triangle<T,3> nonsymmetric_mirror(const triangle<T,3>& triangle, const T& ratio, const plane<T,3>& plane);\n   template <typename T> inline quadix<T,3> nonsymmetric_mirror(const quadix<T,3>& quadix, const T& ratio, const plane<T,3>& plane);\n   template <typename T> inline circle<T> nonsymmetric_mirror(const sphere<T>& sphere, const T& ratio, const plane<T,3>& plane);\n   template <typename T> inline polygon<T,3> nonsymmetric_mirror(const polygon<T,3>& polygon, const T& ratio, const plane<T,3>& plane);\n\n   template <typename T> inline point2d<T> invert_point(const point2d<T>& point, const circle<T>& circle);\n   template <typename T> inline point3d<T> invert_point(const point3d<T>& point, const sphere<T>& sphere);\n\n   template <typename T> inline point2d<T> antipodal_point(const point2d<T>& point, const circle<T>& circle);\n   template <typename T> inline point3d<T> antipodal_point(const point3d<T>& point, const sphere<T>& sphere);\n\n   template <typename T> inline T distance(const T& x1, const T& y1, const T& x2, const T& y2);\n   template <typename T> inline T distance(const T& x1, const T& y1, const T& z1, const T& x2, const T& y2, const T& z2);\n   template <typename T> inline T distance(const point2d<T>& point1, const point2d<T>& point2);\n   template <typename T> inline T distance(const point3d<T>& point1, const point3d<T>& point2);\n   template <typename T> inline T distance(const curve_point<T,2>& point1, const curve_point<T,2>& point2);\n   template <typename T> inline T distance(const curve_point<T,3>& point1, const curve_point<T,3>& point2);\n   template <typename T> inline T distance(const point2d<T>& point, const segment<T,2>& segment);\n   template <typename T> inline T distance(const point3d<T>& point, const segment<T,3>& segment);\n   template <typename T> inline T distance(const point2d<T>& point, const rectangle<T>& rectangle);\n   template <typename T> inline T distance(const point2d<T>& point, const triangle<T,2>& triangle);\n   template <typename T> inline T distance(const point2d<T>& point, const quadix<T,2>& quadix);\n   template <typename T> inline T distance(const point2d<T>& point, const ray<T,2>& ray);\n   template <typename T> inline T distance(const point3d<T>& point, const ray<T,3>& ray);\n   template <typename T> inline T distance(const point3d<T>& point, const plane<T,3>& plane);\n   template <typename T> inline T distance(const line<T,2>& line1, const line<T,2>& line2);\n   template <typename T> inline T distance(const line<T,3>& line1, const line<T,3>& line2);\n   template <typename T> inline T distance(const segment<T,2>& segment1, const segment<T,2>& segment2);\n   template <typename T> inline T distance(const segment<T,3>& segment1, const segment<T,3>& segment2);\n   template <typename T> inline T distance(const segment<T,2>& segment);\n   template <typename T> inline T distance(const segment<T,3>& segment);\n   template <typename T> inline T distance(const segment<T,2>& segment, const triangle<T,2>& triangle);\n   template <typename T> inline T distance(const segment<T,3>& segment, const triangle<T,3>& triangle);\n   template <typename T> inline T distance(const segment<T,2>& segment, const rectangle<T>& rectangle);\n   template <typename T> inline T distance(const segment<T,2>& segment, const circle<T>& circle);\n   template <typename T> inline T distance(const triangle<T,2>& triangle1, const triangle<T,2>& triangle2);\n   template <typename T> inline T distance(const triangle<T,2>& triangle, const rectangle<T>& rectangle);\n   template <typename T> inline T distance(const rectangle<T>& rectangle1, const rectangle<T>& rectangle2);\n   template <typename T> inline T distance(const triangle<T,2>& triangle, const circle<T>& circle);\n   template <typename T> inline T distance(const rectangle<T>& rectangle, const circle<T>& circle);\n   template <typename T> inline T distance(const point2d<T>& point, const circle<T>& circle);\n   template <typename T> inline T distance(const circle<T>& circle1, const circle<T>& circle2);\n   template <typename T> inline T distance(const sphere<T>& sphere1, const sphere<T>& sphere2);\n\n   /**\n    * @brief Calculate the lay's distance. For two points, it's the square of the distance\n    */\n   template <typename T> inline T lay_distance(const T& x1, const T& y1, const T& x2, const T& y2);\n   template <typename T> inline T lay_distance(const T& x1, const T& y1, const T& z1, const T& x2, const T& y2, const T& z2);\n   template <typename T> inline T lay_distance(const point2d<T>& point1, const point2d<T>& point2);\n   template <typename T> inline T lay_distance(const point3d<T>& point1, const point3d<T>& point2);\n   template <typename T> inline T lay_distance(const point2d<T>& point, const triangle<T,2>& triangle);\n   template <typename T> inline T lay_distance(const point2d<T>& point, const quadix<T,2>& triangle);\n   template <typename T> inline T lay_distance(const point2d<T>& point, const ray<T,2>& ray);\n   template <typename T> inline T lay_distance(const point3d<T>& point, const ray<T,3>& ray);\n   template <typename T> inline T lay_distance(const point3d<T>& point, const plane<T,3>& plane);\n   template <typename T> inline T lay_distance(const segment<T,2>& segment1, const segment<T,2>& segment2);\n   template <typename T> inline T lay_distance(const segment<T,3>& segment1, const segment<T,3>& segment2);\n   template <typename T> inline T lay_distance(const line<T,3>& line1, const line<T,3>& line2);\n   template <typename T> inline T lay_distance(const segment<T,2>& segment);\n   template <typename T> inline T lay_distance(const segment<T,3>& segment);\n   template <typename T> inline T lay_distance(const segment<T,2>& segment, const triangle<T,2>& triangle);\n   template <typename T> inline T lay_distance(const segment<T,3>& segment, const triangle<T,3>& triangle);\n\n   template <typename T> inline T manhattan_distance(const T& x1, const T& y1, const T& x2, const T& y2);\n   template <typename T> inline T manhattan_distance(const T& x1, const T& y1, const T& z1, const T& x2, const T& y2, const T& z2);\n   template <typename T> inline T manhattan_distance(const point2d<T>& point1, const point2d<T>& point2);\n   template <typename T> inline T manhattan_distance(const point3d<T>& point1, const point3d<T>& point2);\n   template <typename T> inline T manhattan_distance(const point2d<T>& point, const ray<T,2>& ray);\n   template <typename T> inline T manhattan_distance(const point3d<T>& point, const ray<T,3>& ray);\n   template <typename T> inline T manhattan_distance(const segment<T,2>& segment);\n   template <typename T> inline T manhattan_distance(const segment<T,3>& segment);\n   template <typename T> inline T manhattan_distance(const circle<T>& circle1, const circle<T>& circle2);\n\n   template <typename T> inline T chebyshev_distance(const T& x1, const T& y1, const T& x2, const T& y2);\n   template <typename T> inline T chebyshev_distance(const T& x1, const T& y1, const T& z1, const T& x2, const T& y2, const T& z2);\n   template <typename T> inline T chebyshev_distance(const point2d<T>& point1, const point2d<T>& point2);\n   template <typename T> inline T chebyshev_distance(const point3d<T>& point1, const point3d<T>& point2);\n   template <typename T> inline T chebyshev_distance(const segment<T,2>& segment);\n   template <typename T> inline T chebyshev_distance(const segment<T,3>& segment);\n   template <typename T> inline T chebyshev_distance(const circle<T>& circle1, const circle<T>& circle2);\n\n   template <typename T> inline T inverse_chebyshev_distance(const T& x1, const T& y1, const T& x2, const T& y2);\n   template <typename T> inline T inverse_chebyshev_distance(const T& x1, const T& y1, const T& z1, const T& x2, const T& y2, const T& z2);\n   template <typename T> inline T inverse_chebyshev_distance(const point2d<T>& point1, const point2d<T>& point2);\n   template <typename T> inline T inverse_chebyshev_distance(const point3d<T>& point1, const point3d<T>& point2);\n   template <typename T> inline T inverse_chebyshev_distance(const segment<T,2>& segment);\n   template <typename T> inline T inverse_chebyshev_distance(const segment<T,3>& segment);\n   template <typename T> inline T inverse_chebyshev_distance(const circle<T>& circle1, const circle<T>& circle2);\n\n   template <typename T> inline point2d<T> minkowski_sum(const point2d<T>& point1, const point2d<T>& point2);\n   template <typename T> inline polygon<T,2> minkowski_sum(const rectangle<T>& rectangle1, const rectangle<T>& rectangle2);\n   template <typename T> inline polygon<T,2> minkowski_sum(const triangle<T,2>& triangle1, const triangle<T,2>& triangle2);\n   template <typename T> inline polygon<T,2> minkowski_sum(const quadix<T,2>& quadix1, const quadix<T,2>& quadix2);\n   template <typename T> inline polygon<T,2> minkowski_sum(const circle<T>& triangle, const circle<T>& circle);\n\n   template <typename T> inline polygon<T,2> minkowski_sum(const triangle<T,2>& triangle, const rectangle<T>& rectangle);\n   template <typename T> inline polygon<T,2> minkowski_sum(const triangle<T,2>& triangle, const quadix<T,2>& quadix);\n   template <typename T> inline polygon<T,2> minkowski_sum(const triangle<T,2>& triangle, const circle<T>& circle);\n   template <typename T> inline polygon<T,2> minkowski_sum(const quadix<T,2>& quadix, const circle<T>& circle);\n   template <typename T> inline polygon<T,2> minkowski_sum(const quadix<T,2>& quadix, const rectangle<T>& rectangle);\n   template <typename T> inline polygon<T,2> minkowski_sum(const rectangle<T>& rectangle, const circle<T>& circle);\n   template <typename T> inline polygon<T,2> minkowski_sum(const polygon<T,2>& polygon1, const polygon<T,2>& polygon2);\n\n   template <typename T> inline point2d<T> minkowski_difference(const point2d<T>& point1, const point2d<T>& point2);\n   template <typename T> inline polygon<T,2> minkowski_difference(const rectangle<T>& rectangle1, const rectangle<T>& rectangle2);\n   template <typename T> inline polygon<T,2> minkowski_difference(const triangle<T,2>& triangle1, const triangle<T,2>& triangle2);\n   template <typename T> inline polygon<T,2> minkowski_difference(const quadix<T,2>& quadix1, const quadix<T,2>& quadix2);\n   template <typename T> inline polygon<T,2> minkowski_difference(const circle<T>& triangle, const circle<T>& circle);\n\n   template <typename T> inline polygon<T,2> minkowski_difference(const triangle<T,2>& triangle, const rectangle<T>& rectangle);\n   template <typename T> inline polygon<T,2> minkowski_difference(const triangle<T,2>& triangle, const quadix<T,2>& quadix);\n   template <typename T> inline polygon<T,2> minkowski_difference(const triangle<T,2>& triangle, const circle<T>& circle);\n   template <typename T> inline polygon<T,2> minkowski_difference(const quadix<T,2>& quadix, const circle<T>& circle);\n   template <typename T> inline polygon<T,2> minkowski_difference(const quadix<T,2>& quadix, const rectangle<T>& rectangle);\n   template <typename T> inline polygon<T,2> minkowski_difference(const rectangle<T>& rectangle, const circle<T>& circle);\n   template <typename T> inline polygon<T,2> minkowski_difference(const polygon<T,2>& polygon1, const polygon<T,2>& polygon2);\n\n   template <typename T>\n   inline T distance_segment_to_segment(const T& x1, const T& y1,\n                                        const T& x2, const T& y2,\n                                        const T& x3, const T& y3,\n                                        const T& x4, const T& y4);\n\n   template <typename T>\n   inline T distance_segment_to_segment(const T& x1, const T& y1, const T& z1,\n                                        const T& x2, const T& y2, const T& z2,\n                                        const T& x3, const T& y3, const T& z3,\n                                        const T& x4, const T& y4, const T& z4);\n\n   /**\n    * @brief Calculate the square of the shortest distance between two 2D segments. For example\n    *        (0, 0, 1, 0, -2, 1, -1, 1) will give 2.\n    *\n    */\n   template <typename T>\n   inline T lay_distance_segment_to_segment(const T& x1, const T& y1,\n                                            const T& x2, const T& y2,\n                                            const T& x3, const T& y3,\n                                            const T& x4, const T& y4);\n\n   /**\n    * @brief Calculate the square of the shortest distance between two 2D segments. For example\n    *        (0,0,1, 0,1,1, 0,0.5,0.5, 0,1,0) will give 0.25.\n    *\n    */\n   template <typename T>\n   inline T lay_distance_segment_to_segment(const T& x1, const T& y1, const T& z1,\n                                            const T& x2, const T& y2, const T& z2,\n                                            const T& x3, const T& y3, const T& z3,\n                                            const T& x4, const T& y4, const T& z4);\n\n   template <typename T>\n   inline T distance_line_to_line_old(const T& x1, const T& y1,\n                                  const T& x2, const T& y2,\n                                  const T& x3, const T& y3,\n                                  const T& x4, const T& y4);\n\n   /**\n    * @brief Calculate the distance between two lines in 2D geometry. If the two lines are not parallel,\n    *        it will return 0.\n    * @return T Distance between the two lines\n    */\n   template <typename T>\n   inline T distance_line_to_line(const T& x1, const T& y1,\n                                  const T& x2, const T& y2,\n                                  const T& x3, const T& y3,\n                                  const T& x4, const T& y4);\n\n   template <typename T>\n   inline T distance_line_to_line(const T& x1, const T& y1, const T& z1,\n                                  const T& x2, const T& y2, const T& z2,\n                                  const T& x3, const T& y3, const T& z3,\n                                  const T& x4, const T& y4, const T& z4);\n\n   template <typename T>\n   inline T lay_distance_line_to_line(const T& x1, const T& y1,\n                                      const T& x2, const T& y2,\n                                      const T& x3, const T& y3,\n                                      const T& x4, const T& y4);\n\n   template <typename T>\n   inline T lay_distance_line_to_line(const T& x1, const T& y1, const T& z1,\n                                      const T& x2, const T& y2, const T& z2,\n                                      const T& x3, const T& y3, const T& z3,\n                                      const T& x4, const T& y4, const T& z4);\n\n   template <typename T>\n   inline T lay_distance_from_point_to_circle_center(const point2d<T>& point, const circle<T>& circle);\n\n   template <typename T>\n   inline T lay_distance_from_point_to_sphere_center(const point3d<T>& point, const sphere<T>& sphere);\n\n   template <typename T>\n   inline T distance_from_point_to_circle_center(const point2d<T>& point, const circle<T>& circle);\n\n   template <typename T>\n   inline T distance_from_point_to_sphere_center(const point3d<T>& point, const sphere<T>& sphere);\n\n   template <typename T>\n   inline T span_length(const rectangle<T>& rectangle);\n\n   template <typename T>\n   inline T span_length(const box<T,3>& box);\n\n   template <typename T>\n   inline void project_point_t(const T&  srcx, const T&  srcy,\n                               const T& destx, const T& desty,\n                               const T& t,\n                               T& nx, T& ny);\n\n   template <typename T>\n   inline void project_point_t(const T&  srcx, const T&  srcy, const T&  srcz,\n                               const T& destx, const T& desty, const T& destz,\n                               const T& t,\n                               T& nx, T& ny, T& nz);\n\n   template <typename T>\n   inline void project_point(const T&  srcx, const T&  srcy,\n                             const T& destx, const T& desty,\n                             const T& dist,\n                             T& nx, T& ny);\n\n   template <typename T>\n   inline void project_point(const T&  srcx, const T&  srcy, const T&  srcz,\n                             const T& destx, const T& desty, const T& destz,\n                             const T& dist,\n                             T& nx, T& ny, T& nz);\n\n   template <typename T>\n   inline void project_point(const T& px, const T& py, const T& angle, const T& distance, T& nx, T& ny);\n\n   template <typename T> inline void project_point0  (const T& px, const T& py, const T& distance, T& nx, T& ny);\n   template <typename T> inline void project_point45 (const T& px, const T& py, const T& distance, T& nx, T& ny);\n   template <typename T> inline void project_point90 (const T& px, const T& py, const T& distance, T& nx, T& ny);\n   template <typename T> inline void project_point135(const T& px, const T& py, const T& distance, T& nx, T& ny);\n   template <typename T> inline void project_point180(const T& px, const T& py, const T& distance, T& nx, T& ny);\n   template <typename T> inline void project_point225(const T& px, const T& py, const T& distance, T& nx, T& ny);\n   template <typename T> inline void project_point270(const T& px, const T& py, const T& distance, T& nx, T& ny);\n   template <typename T> inline void project_point315(const T& px, const T& py, const T& distance, T& nx, T& ny);\n\n   template <typename T>\n   inline point2d<T> project_point_t(const point2d<T>& source_point,\n                                     const point2d<T>& destination_point,\n                                     const T& t);\n\n   template <typename T>\n   inline point3d<T> project_point_t(const point3d<T>& source_point,\n                                     const point3d<T>& destination_point,\n                                     const T& t);\n\n   template <typename T>\n   inline point2d<T> project_point(const point2d<T>& source_point,\n                                   const point2d<T>& destination_point,\n                                   const T& distance);\n\n   template <typename T>\n   inline point3d<T> project_point(const point3d<T>& source_point,\n                                   const point3d<T>& destination_point,\n                                   const T& distance);\n\n   template <typename T>\n   inline point2d<T> project_point(const point2d<T>& point,\n                                   const T& angle,\n                                   const T& distance);\n\n   template <typename T> inline point2d<T> project_point0  (const point2d<T>& point, const T& distance);\n   template <typename T> inline point2d<T> project_point45 (const point2d<T>& point, const T& distance);\n   template <typename T> inline point2d<T> project_point90 (const point2d<T>& point, const T& distance);\n   template <typename T> inline point2d<T> project_point135(const point2d<T>& point, const T& distance);\n   template <typename T> inline point2d<T> project_point180(const point2d<T>& point, const T& distance);\n   template <typename T> inline point2d<T> project_point225(const point2d<T>& point, const T& distance);\n   template <typename T> inline point2d<T> project_point270(const point2d<T>& point, const T& distance);\n   template <typename T> inline point2d<T> project_point315(const point2d<T>& point, const T& distance);\n\n   template <typename T> inline point2d<T> project_object(const point2d<T>& point, const T& angle, const T& distance);\n   template <typename T> inline segment<T,2> project_object(const segment<T,2>& segment, const T& angle, const T& distance);\n   template <typename T> inline triangle<T,2> project_object(const triangle<T,2>& triangle, const T& angle, const T& distance);\n   template <typename T> inline quadix<T,2> project_object(const quadix<T,2>& quadix, const T& angle, const T& distance);\n   template <typename T> inline circle<T> project_object(const circle<T>& circle, const T& angle, const T& distance);\n   template <typename T> inline polygon<T,2> project_object(const polygon<T,2>& polygon, const T& angle, const T& distance);\n\n   template <typename T> inline segment<T,2> project_onto_axis(const point2d<T>& point, const line<T,2>& axis);\n   template <typename T> inline segment<T,2> project_onto_axis(const triangle<T,2>& triangle, const line<T,2>& axis);\n   template <typename T> inline segment<T,2> project_onto_axis(const rectangle<T>& rectangle, const line<T,2>& axis);\n   template <typename T> inline segment<T,2> project_onto_axis(const quadix<T,2>& quadix, const line<T,2>& axis);\n   template <typename T> inline segment<T,2> project_onto_axis(const circle<T>& circle, const line<T,2>& axis);\n   template <typename T> inline segment<T,2> project_onto_axis(const polygon<T,2>& polygon, const line<T,2>& axis);\n\n   template <typename T> inline segment<T,3> project_onto_axis(const point3d<T>& point, const line<T,3>& axis);\n   template <typename T> inline segment<T,3> project_onto_axis(const triangle<T,3>& triangle, const line<T,3>& axis);\n   template <typename T> inline segment<T,3> project_onto_axis(const box<T,3>& box, const line<T,3>& axis);\n   template <typename T> inline segment<T,3> project_onto_axis(const quadix<T,3>& quadix, const line<T,3>& axis);\n   template <typename T> inline segment<T,3> project_onto_axis(const sphere<T>& sphere, const line<T,3>& axis);\n   template <typename T> inline segment<T,3> project_onto_axis(const polygon<T,3>& polygon, const line<T,3>& axis);\n\n   template <typename T> inline point2d<T>    project_onto_plane(const point3d<T>&    point, int axis);\n   template <typename T> inline vector2d<T>   project_onto_plane(const vector3d<T>&   vec,   int axis);\n   template <typename T> inline segment<T,2>  project_onto_plane(const segment<T,3>&  seg,   int axis);\n   template <typename T> inline line<T,2>     project_onto_plane(const line<T,3>&     line,  int axis);\n   template <typename T> inline ray<T,2>      project_onto_plane(const ray<T,3>&      ray,   int axis);\n   template <typename T> inline triangle<T,2> project_onto_plane(const triangle<T,3>& tri,   int axis);\n\n   template <typename T> inline void calculate_bezier_coefficients(const quadratic_bezier<T,2>& bezier, T& ax, T& bx, T& ay, T& by);\n   template <typename T> inline void calculate_bezier_coefficients(const quadratic_bezier<T,3>& bezier, T& ax, T& bx, T& ay, T& by, T& az, T& bz);\n   template <typename T> inline void calculate_bezier_coefficients(const cubic_bezier<T,2>& bezier, T& ax, T& bx, T& cx, T& ay, T& by, T& cy);\n   template <typename T> inline void calculate_bezier_coefficients(const cubic_bezier<T,3>& bezier, T& ax, T& bx, T& cx, T& ay, T& by, T& cy, T& az, T& bz, T& cz);\n\n   template <typename T> inline void calculate_bezier_coefficients(const quadratic_bezier<T,2>& bezier,\n                                                                         bezier_coefficients<T,2,eQuadraticBezier>& coeffs);\n\n   template <typename T> inline void calculate_bezier_coefficients(const quadratic_bezier<T,3>& bezier,\n                                                                         bezier_coefficients<T,3,eQuadraticBezier>& coeffs);\n\n   template <typename T> inline void calculate_bezier_coefficients(const cubic_bezier<T,2>& bezier,\n                                                                         bezier_coefficients<T,2,eCubicBezier>& coeffs);\n\n   template <typename T> inline void calculate_bezier_coefficients(const cubic_bezier<T,3>& bezier,\n                                                                         bezier_coefficients<T,3,eCubicBezier>& coeffs);\n\n   template <typename T> inline point2d<T> create_point_on_bezier(const point2d<T>& start_point,\n                                                                  const T& ax, const T& bx,\n                                                                  const T& ay, const T& by,\n                                                                  const T& t);\n\n   template <typename T> inline point3d<T> create_point_on_bezier(const point3d<T>& start_point,\n                                                                  const T& ax, const T& bx,\n                                                                  const T& ay, const T& by,\n                                                                  const T& az, const T& bz,\n                                                                  const T& t);\n\n   template <typename T> inline point2d<T> create_point_on_bezier(const point2d<T>& start_point,\n                                                                 const T& ax, const T& bx, const T& cx,\n                                                                 const T& ay, const T& by, const T& cy, const T& t);\n\n   template <typename T> inline point3d<T> create_point_on_bezier(const point3d<T>& start_point,\n                                                                  const T& ax, const T& bx, const T& cx,\n                                                                  const T& ay, const T& by, const T& cy,\n                                                                  const T& az, const T& bz, const T& cz,\n                                                                  const T& t);\n\n   template <typename T> inline point2d<T> create_point_on_bezier(const point2d<T>& start_point,\n                                                                  const bezier_coefficients<T,2,eQuadraticBezier>& coeffs,\n                                                                  const T& t);\n\n   template <typename T> inline point3d<T> create_point_on_bezier(const point3d<T>& start_point,\n                                                                  const bezier_coefficients<T,3,eQuadraticBezier>& coeffs,\n                                                                  const T& t);\n\n   template <typename T> inline point2d<T> create_point_on_bezier(const point2d<T>& start_point,\n                                                                  const bezier_coefficients<T,2,eCubicBezier>& coeffs,\n                                                                  const T& t);\n\n   template <typename T> inline point3d<T> create_point_on_bezier(const point3d<T>& start_point,\n                                                                  const bezier_coefficients<T,3,eCubicBezier>& coeffs,\n                                                                  const T& t);\n\n   template <typename T, typename OutputIterator> inline void generate_bezier(const quadratic_bezier<T,2>& bezier, OutputIterator out, const std::size_t& point_count = 1000);\n   template <typename T, typename OutputIterator> inline void generate_bezier(const quadratic_bezier<T,3>& bezier, OutputIterator out, const std::size_t& point_count = 1000);\n   template <typename T, typename OutputIterator> inline void generate_bezier(const cubic_bezier<T,2>& bezier, OutputIterator out, const std::size_t& point_count = 1000);\n   template <typename T, typename OutputIterator> inline void generate_bezier(const cubic_bezier<T,3>& bezier, OutputIterator out, const std::size_t& point_count = 1000);\n\n   template <typename T> inline T bezier_curve_length(const quadratic_bezier<T,2>& bezier, const std::size_t& point_count);\n   template <typename T> inline T bezier_curve_length(const quadratic_bezier<T,3>& bezier, const std::size_t& point_count);\n   template <typename T> inline T bezier_curve_length(const cubic_bezier<T,2>& bezier, const std::size_t& point_count);\n   template <typename T> inline T bezier_curve_length(const cubic_bezier<T,3>& bezier, const std::size_t& point_count);\n\n   template <typename T> inline triangle<T,2> bezier_convex_hull(const quadratic_bezier<T,2>& bezier);\n   template <typename T> inline quadix<T,2> bezier_convex_hull(const cubic_bezier<T,2>& bezier);\n\n   template <typename T> inline segment<T,2> center_at_location(const segment<T,2>& segment, const T& x, const T& y);\n   template <typename T> inline segment<T,3> center_at_location(const segment<T,3>& segment, const T& x, const T& y, const T& z);\n   template <typename T> inline triangle<T,2> center_at_location(const triangle<T,2>& triangle, const T& x, const T& y);\n   template <typename T> inline rectangle<T> center_at_location(const rectangle<T>& rectangle, const T& x, const T& y);\n   template <typename T> inline box<T,3> center_at_location(const box<T,3>& box, const T& x, const T& y, const T& z);\n   template <typename T> inline quadix<T,2> center_at_location(const quadix<T,2>& quadix, const T& x, const T& y);\n   template <typename T> inline circle<T> center_at_location(const circle<T>& circle, const T& x, const T& y);\n   template <typename T> inline polygon<T,2> center_at_location(const polygon<T,2>& polygon, const T& x, const T& y);\n\n   template <typename T> inline segment<T,2> center_at_location(const segment<T,2>& segment, const point2d<T>& center_point);\n   template <typename T> inline segment<T,3> center_at_location(const segment<T,3>& segment, const point3d<T>& center_point);\n   template <typename T> inline triangle<T,2> center_at_location(const triangle<T,2>& triangle, const point2d<T>& center_point);\n   template <typename T> inline rectangle<T> center_at_location(const rectangle<T>& rectangle, const point2d<T>& center_point);\n   template <typename T> inline box<T,3> center_at_location(const box<T,3>& box, const point3d<T>& center_point);\n   template <typename T> inline quadix<T,2> center_at_location(const quadix<T,2>& quadix, const point2d<T>& center_point);\n   template <typename T> inline circle<T> center_at_location(const circle<T>& circle, const point2d<T>& center_point);\n   template <typename T> inline polygon<T,2> center_at_location(const polygon<T,2>& polygon, const point2d<T>& center_point);\n\n   template <typename T> inline void shorten_segment(T& x1, T& y1, T& x2, T& y2, const T& amount);\n   template <typename T> inline void shorten_segment(T& x1, T& y1, T& z1, T& x2, T& y2, T& z2, const T& amount);\n   template <typename T> inline segment<T,2> shorten_segment(const segment<T,2>& segment, const T& amount);\n   template <typename T> inline segment<T,3> shorten_segment(const segment<T,3>& segment, const T& amount);\n\n   template <typename T> inline void lengthen_segment(T& x1, T& y1, T& x2, T& y2, const T& amount);\n   template <typename T> inline void lengthen_segment(T& x1, T& y1, T& z1, T& x2, T& y2, T& z2, const T& amount);\n   template <typename T> inline segment<T,2> lengthen_segment(const segment<T,2>& segment, const T& amount);\n   template <typename T> inline segment<T,3> lengthen_segment(const segment<T,3>& segment, const T& amount);\n\n   template <typename T> inline int out_code(const point2d<T>& point, const rectangle<T>& rectangle);\n\n   template <typename T> inline bool clip(const T& x1, const T& y1,\n                                          const T& x2, const T& y2,\n                                          const T& x3, const T& y3,\n                                          const T& x4, const T& y4,\n                                                T& cx1,      T& cy1,\n                                                T& cx2,      T& cy2);\n\n   template <typename T> inline bool clip(const T& x1, const T& y1, const T& z1,\n                                          const T& x2, const T& y2, const T& z2,\n                                          const T& x3, const T& y3, const T& z3,\n                                          const T& x4, const T& y4, const T& z4,\n                                                T& cx1,      T& cy1,      T& cz1,\n                                                T& cx2,      T& cy2,      T& cz2);\n\n   template <typename T> inline bool clip(const segment<T,2>& src_segment, const rectangle<T>&  rectangle,  segment<T,2>& csegment);\n   template <typename T> inline bool clip(const segment<T,2>& src_segment, const triangle<T,2>& triangle,   segment<T,2>& csegment);\n   template <typename T> inline bool clip(const segment<T,2>& src_segment, const quadix<T,2>&   quadix,     segment<T,2>& csegment);\n   template <typename T> inline bool clip(const segment<T,2>& src_segment, const circle<T>&     circle,     segment<T,2>& csegment);\n   template <typename T> inline bool clip(const rectangle<T>&  rectangle1, const rectangle<T>&  rectangle2, rectangle<T>& crectangle);\n   template <typename T> inline bool clip(const box<T,3>&              box1, const box<T,3>&        box2,       box<T,3>&       cbox);\n\n   /**\n    * @brief Calculate the area of a triangle formed by the three points in 2D/3D\n    *\n    * @tparam T\n    * @param point1\n    * @param point2\n    * @param point3\n    * @return T\n    */\n   template <typename T> inline T area(const point2d<T>& point1, const point2d<T>& point2, const point2d<T>& point3);\n   template <typename T> inline T area(const point3d<T>& point1, const point3d<T>& point2, const point3d<T>& point3);\n\n   /**\n    * @brief Calculate the area of a triangle in 2D/3D\n    *\n    * @tparam T\n    * @param triangle\n    * @return T\n    */\n   template <typename T> inline T area(const triangle<T,2>& triangle);\n   template <typename T> inline T area(const triangle<T,3>& triangle);\n\n   /**\n    * @brief Calculate the area of a quadrilateral. The algorithm also works for quadrilateral with self intersection\n    *        Check detail algorithm here http://geomalgorithms.com/a01-_area.html\n    *\n    * @tparam T\n    * @param quadix\n    * @return T\n    */\n   template <typename T> inline T area(const quadix<T,2>& quadix);\n   template <typename T> inline T area(const quadix<T,3>& quadix);\n   template <typename T> inline T area(const rectangle<T>& rectangle);\n   template <typename T> inline T area(const circle<T>& circle);\n\n   /**\n    * @brief Calculate the area of a polygon.\n    *\n    * @tparam T\n    * @param polygon\n    * @return T\n    */\n   template <typename T> inline T area(const polygon<T,2>& polygon);\n   template <typename T> inline T area(const polygon<T,3>& polygon);\n\n   template <typename T> inline T perimeter(const point2d<T>& point1, const point2d<T>& point2, const point2d<T>& point3);\n   template <typename T> inline T perimeter(const point3d<T>& point1, const point3d<T>& point2, const point3d<T>& point3);\n   template <typename T> inline T perimeter(const triangle<T,2>& triangle);\n   template <typename T> inline T perimeter(const triangle<T,3>& triangle);\n   template <typename T> inline T perimeter(const quadix<T,2>& quadix);\n   template <typename T> inline T perimeter(const quadix<T,3>& quadix);\n   template <typename T> inline T perimeter(const rectangle<T>& rectangle);\n   template <typename T> inline T perimeter(const circle<T>& circle);\n   template <typename T> inline T perimeter(const polygon<T,2>& polygon);\n\n   template <typename T> inline void rotate(const T& rotation_angle, const T& x, const T& y, T& nx, T& ny);\n   template <typename T> inline void rotate(const T& rotation_angle, const T& x, const T& y, const T& ox, const T& oy, T& nx, T& ny);\n\n   template <typename T> inline point2d<T> rotate(const T& rotation_angle, const point2d<T>& point);\n   template <typename T> inline point2d<T> rotate(const T& rotation_angle, const point2d<T>& point, const point2d<T>& opoint);\n\n   template <typename T> inline segment<T,2> rotate(const T& rotation_angle, const segment<T,2>& segment);\n   template <typename T> inline segment<T,2> rotate(const T& rotation_angle, const segment<T,2>& segment, const point2d<T>& opoint);\n\n   template <typename T> inline triangle<T,2> rotate(const T& rotation_angle, const triangle<T,2>& triangle);\n   template <typename T> inline triangle<T,2> rotate(const T& rotation_angle, const triangle<T,2>& triangle, const point2d<T>& opoint);\n\n   template <typename T> inline quadix<T,2> rotate(const T& rotation_angle, const quadix<T,2>& quadix);\n   template <typename T> inline quadix<T,2> rotate(const T& rotation_angle, const quadix<T,2>& quadix, const point2d<T>& opoint);\n\n   template <typename T> inline polygon<T,2> rotate(const T& rotation_angle, const polygon<T,2>& polygon);\n   template <typename T> inline polygon<T,2> rotate(const T& rotation_angle, const polygon<T,2>& polygon, const point2d<T>& opoint);\n\n   template <typename T> inline void fast_rotate(const trig_luts<T>& lut,\n                                                 const int rotation_angle,\n                                                 const T& x, const T& y, T& nx, T& ny);\n\n   template <typename T> inline void fast_rotate(const trig_luts<T>& lut,\n                                                 const int rotation_angle,\n                                                 const T& x, const T& y, const T& ox, const T& oy, T& nx, T& ny);\n\n   template <typename T> inline point2d<T> fast_rotate(const trig_luts<T>& lut, const int rotation_angle, const point2d<T>& point);\n   template <typename T> inline point2d<T> fast_rotate(const trig_luts<T>& lut, const int rotation_angle, const point2d<T>& point, const point2d<T>& opoint);\n\n   template <typename T> inline segment<T,2> fast_rotate(const trig_luts<T>& lut, const int rotation_angle, const segment<T,2>& segment);\n   template <typename T> inline segment<T,2> fast_rotate(const trig_luts<T>& lut, const int rotation_angle, const segment<T,2>& segment, const point2d<T>& opoint);\n\n   template <typename T> inline triangle<T,2> fast_rotate(const trig_luts<T>& lut, const int rotation_angle, const triangle<T,2>& triangle);\n   template <typename T> inline triangle<T,2> fast_rotate(const trig_luts<T>& lut, const int rotation_angle, const triangle<T,2>& triangle, const point2d<T>& opoint);\n\n   template <typename T> inline quadix<T,2> fast_rotate(const trig_luts<T>& lut, const int rotation_angle, const quadix<T,2>& quadix);\n   template <typename T> inline quadix<T,2> fast_rotate(const trig_luts<T>& lut, const int rotation_angle, const quadix<T,2>& quadix, const point2d<T>& opoint);\n\n   template <typename T> inline polygon<T,2> fast_rotate(const trig_luts<T>& lut, const int rotation_angle, const polygon<T,2>& polygon);\n   template <typename T> inline polygon<T,2> fast_rotate(const trig_luts<T>& lut, const int rotation_angle, const polygon<T,2>& polygon, const point2d<T>& opoint);\n\n   template <typename T> inline void fast_rotate(const trig_luts<T>& lut,\n                                                 const int rx, const int ry, const int rz,\n                                                 const T& x, const T& y, const T& z, T& nx, T& ny, T& nz);\n\n   template <typename T> inline void fast_rotate(const trig_luts<T>& lut,\n                                                 const int rx, const int ry, const int rz,\n                                                 const T& x, const T& y, const T& z, const T& ox, const T& oy, const T& oz, T& nx, T& ny, T& nz);\n\n   template <typename T> inline point3d<T> fast_rotate(const trig_luts<T>& lut, const int rx, const int ry, const int rz, const point3d<T>& point);\n   template <typename T> inline point3d<T> fast_rotate(const trig_luts<T>& lut, const int rx, const int ry, const int rz, const point3d<T>& point, const point3d<T>& opoint);\n\n   template <typename T> inline segment<T,3> fast_rotate(const trig_luts<T>& lut, const int rx, const int ry, const int rz, const segment<T,3>& segment);\n   template <typename T> inline segment<T,3> fast_rotate(const trig_luts<T>& lut, const int rx, const int ry, const int rz, const segment<T,3>& segment, const point3d<T>& opoint);\n\n   template <typename T> inline triangle<T,3> fast_rotate(const trig_luts<T>& lut, const int rx, const int ry, const int rz, const triangle<T,3>& triangle);\n   template <typename T> inline triangle<T,3> fast_rotate(const trig_luts<T>& lut, const int rx, const int ry, const int rz, const triangle<T,3>& triangle, const point3d<T>& opoint);\n\n   template <typename T> inline quadix<T,3> fast_rotate(const trig_luts<T>& lut, const int rx, const int ry, const int rz, const quadix<T,3>& quadix);\n   template <typename T> inline quadix<T,3> fast_rotate(const trig_luts<T>& lut, const int rx, const int ry, const int rz, const quadix<T,3>& quadix, const point3d<T>& opoint);\n\n   template <typename T> inline polygon<T,3> fast_rotate(const trig_luts<T>& lut, const int rx, const int ry, const int rz, const polygon<T,3>& polygon);\n   template <typename T> inline polygon<T,3> fast_rotate(const trig_luts<T>& lut, const int rx, const int ry, const int rz, const polygon<T,3>& polygon, const point3d<T>& opoint);\n\n\n   template <typename T> inline point2d<T> translate(const T& dx, const T& dy, const point2d<T>& point);\n   template <typename T> inline line<T,2> translate(const T& dx, const T& dy, const line<T,2>& line);\n   template <typename T> inline segment<T,2> translate(const T& dx, const T& dy, const segment<T,2>& segment);\n   template <typename T> inline triangle<T,2> translate(const T& dx, const T& dy, const triangle<T,2>& triangle);\n   template <typename T> inline quadix<T,2> translate(const T& dx, const T& dy, const quadix<T,2>& quadix);\n   template <typename T> inline rectangle<T> translate(const T& dx, const T& dy, const rectangle<T>& rectangle);\n   template <typename T> inline circle<T> translate(const T& dx, const T& dy, const circle<T>& circle);\n   template <typename T> inline polygon<T,2> translate(const T& dx, const T& dy, const polygon<T,2>& polygon);\n\n   template <typename T> inline point2d<T> translate(const T& delta, const point2d<T>& point);\n   template <typename T> inline line<T,2> translate(const T& delta, const line<T,2>& line);\n   template <typename T> inline segment<T,2> translate(const T& delta, const segment<T,2>& segment);\n   template <typename T> inline triangle<T,2> translate(const T& delta, const triangle<T,2>& triangle);\n   template <typename T> inline quadix<T,2> translate(const T& delta, const quadix<T,2>& quadix);\n   template <typename T> inline rectangle<T> translate(const T& delta, const rectangle<T>& rectangle);\n   template <typename T> inline circle<T> translate(const T& delta, const circle<T>& circle);\n   template <typename T> inline polygon<T,2> translate(const T& delta, const polygon<T,2>& polygon);\n\n   template <typename T> inline point2d<T> translate(const vector2d<T>& v, const point2d<T>& point);\n   template <typename T> inline line<T,2> translate(const vector2d<T>& v, const line<T,2>& line);\n   template <typename T> inline segment<T,2> translate(const vector2d<T>& v, const segment<T,2>& segment);\n   template <typename T> inline triangle<T,2> translate(const vector2d<T>& v, const triangle<T,2>& triangle);\n   template <typename T> inline quadix<T,2> translate(const vector2d<T>& v, const quadix<T,2>& quadix);\n   template <typename T> inline rectangle<T> translate(const vector2d<T>& v, const rectangle<T>& rectangle);\n   template <typename T> inline circle<T> translate(const vector2d<T>& v, const circle<T>& circle);\n   template <typename T> inline polygon<T,2> translate(const vector2d<T>& v, const polygon<T,2>& polygon);\n\n   template <typename T> inline point3d<T> translate(const T& dx, const T& dy, const T& dz, const point3d<T>& point);\n   template <typename T> inline line<T,3> translate(const T& dx, const T& dy, const T& dz, const line<T,3>& line);\n   template <typename T> inline segment<T,3> translate(const T& dx, const T& dy, const T& dz, const segment<T,3>& segment);\n   template <typename T> inline triangle<T,3> translate(const T& dx, const T& dy, const T& dz, const triangle<T,3>& triangle);\n   template <typename T> inline quadix<T,3> translate(const T& dx, const T& dy, const T& dz, const quadix<T,3>& quadix);\n   template <typename T> inline box<T,3> translate(const T& dx, const T& dy, const T& dz, const box<T,3>& box);\n   template <typename T> inline sphere<T> translate(const T& dx, const T& dy, const T& dz, const sphere<T>& sphere);\n   template <typename T> inline polygon<T,3> translate(const T& dx, const T& dy, const T& dz, const polygon<T,3>& polygon);\n\n   template <typename T> inline point3d<T> translate(const T& delta, const point3d<T>& point);\n   template <typename T> inline line<T,3> translate(const T& delta, const line<T,3>& line);\n   template <typename T> inline segment<T,3> translate(const T& delta, const segment<T,3>& segment);\n   template <typename T> inline triangle<T,3> translate(const T& delta, const triangle<T,3>& triangle);\n   template <typename T> inline quadix<T,3> translate(const T& delta, const quadix<T,3>& quadix);\n   template <typename T> inline box<T,3> translate(const T& delta, const box<T,3>& box);\n   template <typename T> inline sphere<T> translate(const T& delta, const sphere<T>& sphere);\n   template <typename T> inline polygon<T,3> translate(const T& delta, const polygon<T,3>& polygon);\n\n   template <typename T> inline point3d<T> translate(const vector3d<T>& v, const point3d<T>& point);\n   template <typename T> inline line<T,3> translate(const vector3d<T>& v, const line<T,3>& line);\n   template <typename T> inline segment<T,3> translate(const vector3d<T>& v, const segment<T,3>& segment);\n   template <typename T> inline triangle<T,3> translate(const vector3d<T>& v, const triangle<T,3>& triangle);\n   template <typename T> inline quadix<T,3> translate(const vector3d<T>& v, const quadix<T,3>& quadix);\n   template <typename T> inline box<T,3> translate(const vector3d<T>& v, const box<T,3>& box);\n   template <typename T> inline sphere<T> translate(const vector3d<T>& v, const sphere<T>& sphere);\n   template <typename T> inline polygon<T,3> translate(const vector3d<T>& v, const polygon<T,3>& polygon);\n\n   // no static check here\n   // G = segment3d, Vector3d\n   template <typename T, class G> inline G translate(const Eigen::MatrixBase<T>& v, const G& geom);\n   // G = point3d or sphere\n   template <typename T, template<typename> class G> inline G<typename T::Scalar> translate(const Eigen::MatrixBase<T>& v, const G<typename T::Scalar>& geom);\n   // G = line, segment, triangle, quadix, box or polygon\n   template <typename T, template<typename, int> class G> inline G<typename T::Scalar, 3> translate(const Eigen::MatrixBase<T>& v, const G<typename T::Scalar, 3>& geom);\n\n   template <typename T> inline point2d<T> scale(const T& dx, const T& dy, const point2d<T>& point);\n   template <typename T> inline line<T,2> scale(const T& dx, const T& dy, const line<T,2>& line);\n   template <typename T> inline segment<T,2> scale(const T& dx, const T& dy, const segment<T,2>& segment);\n   template <typename T> inline triangle<T,2> scale(const T& dx, const T& dy, const triangle<T,2>& triangle);\n   template <typename T> inline quadix<T,2> scale(const T& dx, const T& dy, const quadix<T,2>& quadix);\n   template <typename T> inline rectangle<T> scale(const T& dx, const T& dy, const rectangle<T>& rectangle);\n   template <typename T> inline circle<T> scale(const T& dr, const circle<T>& circle);\n   template <typename T> inline polygon<T,2> scale(const T& dx, const T& dy, const polygon<T,2>& polygon);\n\n   template <typename T> inline point3d<T> scale(const T& dx, const T& dy, const T& dz, const point3d<T>& point);\n   template <typename T> inline line<T,3> scale(const T& dx, const T& dy, const T& dz, const line<T,3>& line);\n   template <typename T> inline segment<T,3> scale(const T& dx, const T& dy, const T& dz, const segment<T,3>& segment);\n   template <typename T> inline triangle<T,3> scale(const T& dx, const T& dy, const T& dz, const triangle<T,3>& triangle);\n   template <typename T> inline quadix<T,3> scale(const T& dx, const T& dy, const T& dz, const quadix<T,3>& quadix);\n   template <typename T> inline box<T,3> scale(const T& dx, const T& dy, const T& dz, const box<T,3>& box);\n   template <typename T> inline sphere<T> scale(const T& dr, const sphere<T>& sphere);\n   template <typename T> inline polygon<T,3> scale(const T& dx, const T& dy, const T& dz, const polygon<T,3>& polygon);\n\n   template <typename T> inline rectangle<T> aabb(const segment<T,2>& segment);\n   template <typename T> inline rectangle<T> aabb(const triangle<T,2>& triangle);\n   template <typename T> inline rectangle<T> aabb(const rectangle<T>& rectangle);\n   template <typename T> inline rectangle<T> aabb(const quadix<T,2>& quadix);\n   template <typename T> inline rectangle<T> aabb(const circle<T>& circle);\n   template <typename T> inline rectangle<T> aabb(const polygon<T,2>& polygon);\n\n   template <typename T> inline void aabb(const segment<T,2>& segment,   T& x1, T& y1, T& x2, T& y2);\n   template <typename T> inline void aabb(const triangle<T,2>& triangle, T& x1, T& y1, T& x2, T& y2);\n   template <typename T> inline void aabb(const rectangle<T>& rectangle, T& x1, T& y1, T& x2, T& y2);\n   template <typename T> inline void aabb(const quadix<T,2>& quadix,     T& x1, T& y1, T& x2, T& y2);\n   template <typename T> inline void aabb(const circle<T>& circle,       T& x1, T& y1, T& x2, T& y2);\n   template <typename T> inline void aabb(const polygon<T,2>& polygon,   T& x1, T& y1, T& x2, T& y2);\n\n   template <typename T> inline box<T,3> aabb(const segment<T,3>& segment);\n   template <typename T> inline box<T,3> aabb(const triangle<T,3>& triangle);\n   template <typename T> inline box<T,3> aabb(const box<T,3>& rectangle);\n   template <typename T> inline box<T,3> aabb(const quadix<T,3>& quadix);\n   template <typename T> inline box<T,3> aabb(const sphere<T>& sphere);\n   template <typename T> inline box<T,3> aabb(const polygon<T,3>& polygon);\n\n   template <typename T> inline void aabb(const segment<T,3>& segment,   T& x1, T& y1, T& z1, T& x2, T& y2, T& z2);\n   template <typename T> inline void aabb(const triangle<T,3>& triangle, T& x1, T& y1, T& z1, T& x2, T& y2, T& z2);\n   template <typename T> inline void aabb(const box<T,3>& box,             T& x1, T& y1, T& z1, T& x2, T& y2, T& z2);\n   template <typename T> inline void aabb(const quadix<T,3>& quadix,     T& x1, T& y1, T& z1, T& x2, T& y2, T& z2);\n   template <typename T> inline void aabb(const sphere<T>& sphere,       T& x1, T& y1, T& z1, T& x2, T& y2, T& z2);\n   template <typename T> inline void aabb(const polygon<T,3>& polygon,   T& x1, T& y1, T& z1, T& x2, T& y2, T& z2);\n\n   template <typename T> inline rectangle<T> update_rectangle(const rectangle<T>& rectangle, point2d<T>& point);\n   template <typename T> inline box<T,3> update_box(const box<T,3>& box, point3d<T>& point);\n   template <typename T> inline circle<T> update_circle(const circle<T>& circle, point2d<T>& point);\n   template <typename T> inline sphere<T> update_sphere(const sphere<T>& sphere, point3d<T>& point);\n\n   template <typename T> inline point2d<T> generate_point_on_segment(const segment<T,2>& segment, const T& t);\n   template <typename T> inline point3d<T> generate_point_on_segment(const segment<T,3>& segment, const T& t);\n   template <typename T> inline point2d<T> generate_point_on_ray(const ray<T,2>& ray, const T& t);\n   template <typename T> inline point3d<T> generate_point_on_ray(const ray<T,3>& ray, const T& t);\n\n   template <typename T> inline T generate_random_value(const T& range);\n\n   template <typename T> inline point2d<T> generate_random_point(const T& dx, const  T& dy);\n   template <typename T> inline point3d<T> generate_random_point(const T& dx, const T& dy, const T& dz);\n   template <typename T> inline point2d<T> generate_random_point(const segment<T,2>& segment);\n   template <typename T> inline point3d<T> generate_random_point(const segment<T,3>& segment);\n   template <typename T> inline point2d<T> generate_random_point(const triangle<T,2>& triangle);\n   template <typename T> inline point3d<T> generate_random_point(const triangle<T,3>& triangle);\n   template <typename T> inline point2d<T> generate_random_point(const quadix<T,2>& quadix);\n   template <typename T> inline point3d<T> generate_random_point(const quadix<T,3>& quadix);\n   template <typename T> inline point2d<T> generate_random_point(const rectangle<T>& rectangle);\n   template <typename T> inline point3d<T> generate_random_point(const box<T,3>& box);\n\n   template <typename T, typename OutputIterator> inline void generate_random_points(const T& x1, const T& y1, const  T& x2, const  T& y2, const std::size_t& point_count, OutputIterator out);\n   template <typename T, typename OutputIterator> inline void generate_random_points(const T& x1, const T& y1, const T& z1, const T& x2, const  T& y2, const  T& z2, const std::size_t& point_count, OutputIterator out);\n   template <typename T, typename OutputIterator> inline void generate_random_points(const rectangle<T>& rectangle, const std::size_t& point_count, OutputIterator out);\n   template <typename T, typename OutputIterator> inline void generate_random_points(const box<T,3>& box,           const std::size_t& point_count, OutputIterator out);\n   template <typename T, typename OutputIterator> inline void generate_random_points(const segment<T,2>& segment,   const std::size_t& point_count, OutputIterator out);\n   template <typename T, typename OutputIterator> inline void generate_random_points(const segment<T,3>& segment,   const std::size_t& point_count, OutputIterator out);\n   template <typename T, typename OutputIterator> inline void generate_random_points(const triangle<T,2>& triangle, const std::size_t& point_count, OutputIterator out);\n   template <typename T, typename OutputIterator> inline void generate_random_points(const triangle<T,3>& triangle, const std::size_t& point_count, OutputIterator out);\n   template <typename T, typename OutputIterator> inline void generate_random_points(const quadix<T,2>& quadix,     const std::size_t& point_count, OutputIterator out);\n   template <typename T, typename OutputIterator> inline void generate_random_points(const quadix<T,3>& quadix,     const std::size_t& point_count, OutputIterator out);\n   template <typename T, typename OutputIterator> inline void generate_random_points(const circle<T>& circle,       const std::size_t& point_count, OutputIterator out);\n\n   template <typename T> inline void generate_random_object(const T& x1, const T& y1, const T& x2, const T& y2, segment<T,2>& segment);\n   template <typename T> inline void generate_random_object(const T& x1, const T& y1, const T& x2, const T& y2, rectangle<T>& rectangle);\n   template <typename T> inline void generate_random_object(const T& x1, const T& y1, const T& x2, const T& y2, triangle<T,2>& triangle);\n   template <typename T> inline void generate_random_object(const T& x1, const T& y1, const T& x2, const T& y2, quadix<T,2>& quadix);\n   template <typename T> inline void generate_random_object(const T& x1, const T& y1, const T& x2, const T& y2, circle<T>& circle);\n   template <typename T> inline void generate_random_object(const T& x1, const T& y1, const T& z1, const T& x2, const T& y2, const T& z2, box<T,3>& box);\n\n   template <typename T>\n   inline triangle<T,2> right_shift(const triangle<T,2>& triangle, const std::size_t& shift);\n\n   template <typename T>\n   inline triangle<T,3> right_shift(const triangle<T,3>& triangle, const std::size_t& shift);\n\n   template <typename T>\n   inline quadix<T,2> right_shift(const quadix<T,2>& quadix, const std::size_t& shift);\n\n   template <typename T>\n   inline quadix<T,3> right_shift(const quadix<T,3>& quadix, const std::size_t& shift);\n\n   template <typename T> inline T vector_norm(const vector2d<T>& v);\n   template <typename T> inline T vector_norm(const vector3d<T>& v);\n   template <typename T, std::size_t Dimension> inline T segment_norm(const segment<T, Dimension>& v) {\n      return v._len;\n   }\n\n   template <typename T> inline T vector_square_norm(const vector2d<T>& v);\n   template <typename T> inline T vector_square_norm(const vector3d<T>& v);\n\n   template <typename T> inline vector2d<T> normalize(const vector2d<T>& v);\n   template <typename T> inline vector3d<T> normalize(const vector3d<T>& v);\n\n   /**\n    * @brief Calculate a normalized vector perpendicular to v in the counter-clockwise direction, i.e. left\n    *\n    * @tparam T\n    * @param v\n    * @return vector2d<T>\n    */\n   template <typename T> inline vector2d<T> create_perpendicular_vector(const vector2d<T>& v);\n   template <typename T> inline vector3d<T> create_perpendicular_vector(const vector3d<T>& v);\n   /**\n    * @brief Calculate a normalized vector that is\n    *           1. perpendicular to vector v\n    *           2. in the plane formed by vector v and w. The plane normal is v*u\n    *           3. pointing to the left of vector v\n    *\n    * @tparam T\n    * @param v\n    * @param w\n    * @return vector3d<T>\n    */\n   template <typename T> inline vector3d<T> create_perpendicular_vector(const vector3d<T>& v, const vector3d<T>& w);\n\n   template <typename T> inline T           operator*(const vector2d<T>& v1, const vector2d<T>& v2);\n   template <typename T> inline vector3d<T> operator*(const vector3d<T>& v1, const vector3d<T>& v2);\n\n   template <typename T> inline T dot_product(const vector2d<T>& v1, const vector2d<T>& v2);\n   template <typename T> inline T dot_product(const vector3d<T>& v1, const vector3d<T>& v2);\n\n   template <typename T> inline T perpendicular_product(const vector2d<T>& v1, const vector2d<T>& v2);\n   template <typename T> inline T triple_product(const vector3d<T>& v1, const vector3d<T>& v2, const vector3d<T>& v3);\n\n   template <typename T> inline point2d<T> operator+(const point2d<T>& point, const vector2d<T>& v);\n   template <typename T> inline point2d<T> operator+(const vector2d<T>& v, const point2d<T>& point);\n\n   template <typename T> inline point3d<T> operator+(const point3d<T>& point, const vector3d<T>& v);\n   template <typename T> inline point3d<T> operator+(const vector3d<T>& v, const point3d<T>& point);\n\n   template <typename T> inline vector2d<T> operator-(const point2d<T>& p1, const point2d<T>& p2);\n   template <typename T> inline vector3d<T> operator-(const point3d<T>& p1, const point3d<T>& p2);\n\n   template <typename T> inline bool is_equal(const T& val1, const T& val2, const T& epsilon);\n   template <typename T> inline bool is_equal(const point2d<T>& point1, const point2d<T>& point2, const T& epsilon);\n   template <typename T> inline bool is_equal(const point3d<T>& point1, const point3d<T>& point2, const T& epsilon);\n\n   template <typename T> inline bool is_equal(const vector2d<T>& vector1, const vector2d<T>& vector2, const T& epsilon);\n   template <typename T> inline bool is_equal(const vector3d<T>& vector1, const vector3d<T>& vector2, const T& epsilon);\n\n   template <typename T> inline bool is_equal(const T& val1, const T& val2);\n   template <typename T> inline bool is_equal(const point2d<T>& point1, const point2d<T>& point2);\n   template <typename T> inline bool is_equal(const point3d<T>& point1, const point3d<T>& point2);\n\n   template <typename T> inline bool is_equal(const vector2d<T>& vector1, const vector2d<T>& vector2);\n   template <typename T> inline bool is_equal(const vector3d<T>& vector1, const vector3d<T>& vector2);\n\n   template <typename T> inline bool is_equal(const rectangle<T>& rectangle1, const rectangle<T>& rectangle2);\n   template <typename T> inline bool is_equal(const circle<T>& circle1, const circle<T>& circle2);\n\n   template <typename T> inline bool is_equal(const box<T,3>& box1, const box<T,3>& box2);\n   template <typename T> inline bool is_equal(const sphere<T>& sphere1, const sphere<T>& sphere2);\n\n   template <typename T> inline bool not_equal(const T& val1, const T& val2, const T& epsilon);\n   template <typename T> inline bool not_equal(const point2d<T>& point1, const point2d<T>& point2, const T& epsilon);\n   template <typename T> inline bool not_equal(const point3d<T>& point1, const point3d<T>& point2, const T& epsilon);\n\n   template <typename T> inline bool not_equal(const T& val1, const T& val2);\n   template <typename T> inline bool not_equal(const point2d<T>& point1, const point2d<T>& point2);\n   template <typename T> inline bool not_equal(const point3d<T>& point1, const point3d<T>& point2);\n\n   template <typename T> inline bool not_equal(const rectangle<T>& rectangle1, const rectangle<T>& rectangle2);\n   template <typename T> inline bool not_equal(const circle<T>& circle1, const circle<T>& circle2);\n\n   template <typename T> inline bool not_equal(const box<T,3>& box1, const box<T,3>& box2);\n   template <typename T> inline bool not_equal(const sphere<T>& sphere1, const sphere<T>& sphere2);\n\n   template <typename T> inline bool less_than_or_equal(const T& val1, const T& val2, const T& epsilon);\n   template <typename T> inline bool less_than_or_equal(const T& val1, const T& val2);\n\n   template <typename T> inline bool greater_than_or_equal(const T& val1, const T& val2, const T& epsilon);\n   template <typename T> inline bool greater_than_or_equal(const T& val1, const T& val2);\n\n   template <typename T> inline bool operator < (const point2d<T>& point1, const point2d<T>& point2);\n   template <typename T> inline bool operator < (const point3d<T>& point1, const point3d<T>& point2);\n   template <typename T> inline bool operator > (const point2d<T>& point1, const point2d<T>& point2);\n   template <typename T> inline bool operator > (const point3d<T>& point1, const point3d<T>& point2);\n\n   template <typename T> inline bool operator == (const point2d<T>& point1, const point2d<T>& point2);\n   template <typename T> inline bool operator == (const point3d<T>& point1, const point3d<T>& point2);\n\n   template <typename T> inline bool is_degenerate(const T& x1, const T& y1, const T& x2, const T& y2);\n   template <typename T> inline bool is_degenerate(const segment<T,2>& segment);\n   template <typename T> inline bool is_degenerate(const line<T,2>& line);\n\n   template <typename T> inline bool is_degenerate(const T& x1, const T& y1, const T& z1, const T& x2, const T& y2, const T& z2);\n   template <typename T> inline bool is_degenerate(const segment<T,3>& segment);\n   template <typename T> inline bool is_degenerate(const line<T,3>& line);\n\n   template <typename T> inline bool is_degenerate(const triangle<T,2>& triangle);\n   template <typename T> inline bool is_degenerate(const triangle<T,3>& triangle);\n\n   template <typename T> inline bool is_degenerate(const quadix<T,2>& quadix);\n   template <typename T> inline bool is_degenerate(const quadix<T,3>& quadix);\n\n   template <typename T> inline bool is_degenerate(const rectangle<T>& rectangle);\n   template <typename T> inline bool is_degenerate(const circle<T>& circle);\n   template <typename T> inline bool is_degenerate(const sphere<T>& sphere);\n   template <typename T> inline bool is_degenerate(const circular_arc<T>& arc);\n\n   template <typename T> inline bool is_degenerate(const point2d<T>& point);\n   template <typename T> inline bool is_degenerate(const point3d<T>& point);\n\n   template <typename T> inline point2d<T> degenerate_point2d();\n   template <typename T> inline point3d<T> degenerate_point3d();\n   template <typename T> inline vector2d<T> degenerate_vector2d();\n   template <typename T> inline vector3d<T> degenerate_vector3d();\n   template <typename T> inline ray<T,2> degenerate_ray2d();\n   template <typename T> inline ray<T,3> degenerate_ray3d();\n   template <typename T> inline line<T,2> degenerate_line2d();\n   template <typename T> inline line<T,3> degenerate_line3d();\n   template <typename T> inline segment<T,2> degenerate_segment2d();\n   template <typename T> inline segment<T,3> degenerate_segment3d();\n   template <typename T> inline triangle<T,2> degenerate_triangle2d();\n   template <typename T> inline triangle<T,3> degenerate_triangle3d();\n   template <typename T> inline quadix<T,2> degenerate_quadix2d();\n   template <typename T> inline quadix<T,3> degenerate_quadix3d();\n   template <typename T> inline rectangle<T> degenerate_rectangle();\n   template <typename T> inline circle<T> degenerate_circle();\n   template <typename T> inline sphere<T> degenerate_sphere();\n\n   template <typename T> inline point2d<T> positive_infinite_point2d();\n   template <typename T> inline point2d<T> negative_infinite_point2d();\n   template <typename T> inline point3d<T> positive_infinite_point3d();\n   template <typename T> inline point3d<T> negative_infinite_point3d();\n\n   template <typename T> inline void swap(point2d<T>& point1, point2d<T>& point2);\n   template <typename T> inline void swap(point3d<T>& point1, point3d<T>& point2);\n\n   template <typename T> inline point2d<T> make_point(const T& x, const T& y);\n   template <typename T> inline point3d<T> make_point(const T& x, const T& y, const T& z);\n\n   inline point2d<double> make_point(const Eigen::Vector2d& v);\n   inline point3d<double> make_point(const Eigen::Vector3d& v);\n\n   template <typename T> inline point2d<T> make_point(const point3d<T> point);\n   template <typename T> inline point3d<T> make_point(const point2d<T> point, const T& z = T(0.0));\n\n   template <typename T> inline point2d<T> make_point(const circle<T>& circle);\n   template <typename T> inline point3d<T> make_point(const sphere<T>& sphere);\n\n   template <typename T> inline vector2d<T> make_vector(const T& x, const T& y);\n   template <typename T> inline vector3d<T> make_vector(const T& x, const T& y, const T& z);\n\n   template <typename T> inline vector2d<T> make_vector(const vector3d<T> v);\n   template <typename T> inline vector3d<T> make_vector(const vector2d<T> v, const T& z);\n\n   template <typename T> inline vector2d<T> make_vector(const point2d<T> point);\n   template <typename T> inline vector3d<T> make_vector(const point3d<T> point);\n\n   template <typename T> inline ray<T,2> make_ray(const T& ox, const T& oy, const T& dir_x, const T& dir_y);\n   template <typename T> inline ray<T,3> make_ray(const T& ox, const T& oy, const T& oz, const T& dir_x, const T& dir_y, const T& dir_z);\n\n   template <typename T> inline ray<T,2> make_ray(const point2d<T>& origin, const vector2d<T>& direction);\n   template <typename T> inline ray<T,3> make_ray(const point3d<T>& origin, const vector3d<T>& direction);\n   template <typename T> inline ray<T,2> make_ray(const point2d<T>& origin, const T& bearing);\n\n   template <typename T> inline ray<T,2> make_ray_with_points(const point2d<T>& point1, const point2d<T>& point2);\n   template <typename T> inline ray<T,3> make_ray_with_points(const point3d<T>& point1, const point3d<T>& point2);\n   ray<double,2> make_ray_with_points(const Eigen::Vector2d& point1, const Eigen::Vector2d& point2);\n   ray<double,3> make_ray_with_points(const Eigen::Vector3d& point1, const Eigen::Vector3d& point2);\n\n   ray<double,2> make_ray(const Eigen::Vector2d& origin, const Eigen::Vector2d& direction);\n   ray<double,3> make_ray(const Eigen::Vector3d& origin, const Eigen::Vector3d& direction);\n\n   template <typename T> inline curve_point<T,2> make_curve_point(const T& x, const T& y, const T& t);\n   template <typename T> inline curve_point<T,3> make_curve_point(const T& x, const T& y, const T& z, const T& t);\n\n   template <typename T> inline curve_point<T,2> make_curve_point(const point2d<T>& point, const T& t);\n   template <typename T> inline curve_point<T,3> make_curve_point(const point3d<T>& point, const T& t);\n\n   template <typename T> inline segment<T,2> make_segment(const T& x1, const T& y1, const T& x2, const T& y2);\n   template <typename T> inline segment<T,3> make_segment(const T& x1, const T& y1, const T& z1, const T& x2, const T& y2, const T& z2);\n\n   template <typename T> inline segment<T,2> make_segment(const point2d<T>& point1, const point2d<T>& point2);\n   template <typename T> inline segment<T,3> make_segment(const point3d<T>& point1, const point3d<T>& point2);\n\n   inline segment<double,2> make_segment(const Eigen::Vector2d& v, const Eigen::Vector2d& w);\n   inline segment<double,3> make_segment(const Eigen::Vector3d& v, const Eigen::Vector3d& w);\n\n   template <typename T> inline line<T,2> make_line(const T& x1, const T& y1, const T& x2, const T& y2);\n   template <typename T> inline line<T,3> make_line(const T& x1, const T& y1, const T& z1, const T& x2, const T& y2, const T& z2);\n\n   template <typename T> inline line<T,2> make_line(const point2d<T>& point1, const point2d<T>& point2);\n   template <typename T> inline line<T,3> make_line(const point3d<T>& point1, const point3d<T>& point2);\n\n   inline line<double,2> make_line(const Eigen::Vector2d& v, const Eigen::Vector2d& w);\n   inline line<double,3> make_line(const Eigen::Vector3d& v, const Eigen::Vector3d& w);\n\n   template <typename T> inline line<T,2> make_line(const segment<T,2>& segment);\n   template <typename T> inline line<T,3> make_line(const segment<T,3>& segment);\n\n   template <typename T> inline line<T,2> make_line(const ray<T,2>& ray);\n   template <typename T> inline line<T,3> make_line(const ray<T,3>& ray);\n\n   template <typename T> inline rectangle<T> make_rectangle(const T& x1, const T& y1, const T& x2, const T& y2);\n   template <typename T> inline rectangle<T> make_rectangle(const point2d<T>& point1, const point2d<T>& point2);\n\n   template <typename T> inline box<T,3> make_box(const T& x1, const T& y1, const T& z1, const T& x2, const T& y2, const T& z2);\n   template <typename T> inline box<T,3> make_box(const point3d<T>& point1, const point3d<T>& point2);\n\n   template <typename T> inline triangle<T,2> make_triangle(const T& x1, const T& y1,\n                                                            const T& x2, const T& y2,\n                                                            const T& x3, const T& y3);\n\n   template <typename T> inline triangle<T,3> make_triangle(const T& x1, const T& y1, const T& z1,\n                                                            const T& x2, const T& y2, const T& z2,\n                                                            const T& x3, const T& y3, const T& z3);\n\n   template <typename T> inline triangle<T,2> make_triangle(const point2d<T>& point1, const point2d<T>& point2, const point2d<T>& point3);\n   template <typename T> inline triangle<T,3> make_triangle(const point3d<T>& point1, const point3d<T>& point2, const point3d<T>& point3);\n   template <typename T> inline triangle<typename T::Scalar, 3> make_triangle(const Eigen::MatrixBase<T>& point1, const Eigen::MatrixBase<T>& point2, const Eigen::MatrixBase<T>& point3);\n   template <typename T, std::size_t Dimension>\n   inline triangle<T, Dimension> make_triangle(const polygon<T, Dimension>& p, std::size_t i, std::size_t j, std::size_t k);\n\n   template <typename T> inline quadix<T,2> make_quadix(const T& x1, const T& y1,\n                                                        const T& x2, const T& y2,\n                                                        const T& x3, const T& y3,\n                                                        const T& x4, const T& y4);\n\n   template <typename T> inline quadix<T,3> make_quadix(const T& x1, const T& y1, const T& z1,\n                                                        const T& x2, const T& y2, const T& z2,\n                                                        const T& x3, const T& y3, const T& z3,\n                                                        const T& x4, const T& y4, const T& z4);\n\n   template <typename T> inline quadix<T,2> make_quadix(const point2d<T>& point1, const point2d<T>& point2, const point2d<T>& point3, const point2d<T>& point4);\n   template <typename T> inline quadix<T,3> make_quadix(const point3d<T>& point1, const point3d<T>& point2, const point3d<T>& point3, const point3d<T>& point4);\n   template <typename T> inline quadix<typename T::Scalar,3> make_quadix(const Eigen::MatrixBase<T>& point1, const Eigen::MatrixBase<T>& point2, const Eigen::MatrixBase<T>& point3, const Eigen::MatrixBase<T>& point4);\n\n   template <typename T> inline quadix<T,2> make_quadix(const T& x1, const T& y1, const T& x2, const T& y2);\n   template <typename T> inline quadix<T,2> make_quadix(const rectangle<T>& rectangle);\n\n   template <typename T> inline circle<T> make_circle(const T& x, const T& y, const T& radius);\n   template <typename T> inline circle<T> make_circle(const point2d<T>& point, const T& radius);\n   template <typename T> inline circle<T> make_circle(const point2d<T>& point1, const point2d<T>& point2);\n   template <typename T> inline circle<T> make_circle(const point2d<T>& point1, const point2d<T>& point2, const point2d<T>& point3);\n   template <typename T> inline circle<T> make_circle(const triangle<T,2>& triangle);\n\n   template <typename T> inline sphere<T> make_sphere(const T& x, const T& y, const T& z, const T& radius);\n   template <typename T> inline sphere<T> make_sphere(const point3d<T>& point, const T& radius);\n   template <typename T> inline sphere<T> make_sphere(const point3d<T>& point1, const point3d<T>& point2);\n\n   /**\n    * @brief Make a plane object from three points. The plane normal direction is defined as\n    *        Vector(x1-->x2) cross product Vector(x1-->x3)\n    *\n    * @param check Sanity check whether the three points are collinear\n    * @return plane<T,3>\n    */\n   template <typename T> inline plane<T,3> make_plane(const T& x1, const T& y1, const T& z1,\n                                                      const T& x2, const T& y2, const T& z2,\n                                                      const T& x3, const T& y3, const T& z3,\n                                                      const bool check=true);\n\n   template <typename T> inline plane<T,3> make_plane(const T& px, const T& py, const T& pz,\n                                                      const T& nx, const T& ny, const T& nz);\n\n   template <typename T> inline plane<T,3> make_plane(const point3d<T>& point1,\n                                                      const point3d<T>& point2,\n                                                      const point3d<T>& point3,\n                                                      const bool check=true);\n\n   template <typename T> inline plane<T,3> make_plane(const point3d<T>& point,\n                                                      const vector3d<T>& normal);\n\n   template <typename T> inline plane<T,3> make_plane(const triangle<T,3>& triangle);\n\n   template <typename T, std::size_t D, typename InputIterator> inline polygon<T,D> make_polygon(const InputIterator begin, const InputIterator end);\n\n   template <typename T> inline polygon<T,2> make_polygon(const std::vector< point2d<T> >& point_list);\n   template <typename T> inline polygon<T,3> make_polygon(const std::vector< point3d<T> >& point_list);\n   template <typename T> inline polygon<typename T::Scalar,3> make_polygon(const std::vector< Eigen::MatrixBase<T> >& point_list);\n\n   template <typename T> inline polygon<T,2> make_polygon(const triangle<T,2>& triangle);\n   template <typename T> inline polygon<T,2> make_polygon(const quadix<T,2>& quadix);\n   template <typename T> inline polygon<T,2> make_polygon(const rectangle<T>& rectangle);\n   template <typename T> inline polygon<T,2> make_polygon(const circle<T>& circle, const unsigned int point_count = 360);\n\n} // wykobi namespace\n\n#include \"wykobi.inl\"\n\n#endif\n", "meta": {"hexsha": "9f5f69681c1c46ac02347a8de29e6a70c8c97e36", "size": 226099, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/wykobi.hpp", "max_stars_repo_name": "luohancfd/wykobi", "max_stars_repo_head_hexsha": "dd4d714206d871c3cad106e795a7cc259fdb7e21", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-11-09T21:20:04.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-09T21:20:04.000Z", "max_issues_repo_path": "include/wykobi.hpp", "max_issues_repo_name": "luohancfd/wykobi", "max_issues_repo_head_hexsha": "dd4d714206d871c3cad106e795a7cc259fdb7e21", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2021-02-24T06:37:26.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-25T23:17:26.000Z", "max_forks_repo_path": "include/wykobi.hpp", "max_forks_repo_name": "luohancfd/wykobi", "max_forks_repo_head_hexsha": "dd4d714206d871c3cad106e795a7cc259fdb7e21", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-02-21T00:20:28.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-21T00:20:28.000Z", "avg_line_length": 51.2579913852, "max_line_length": 217, "alphanum_fraction": 0.590462585, "num_tokens": 56369, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5736784074525096, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.3180877333179505}}
{"text": "// Copyright  (C)  2009  Ruben Smits <ruben dot smits at mech dot kuleuven dot be>\n\n// Version: 1.0\n// Author: Ruben Smits <ruben dot smits at mech dot kuleuven dot be>\n// Maintainer: Ruben Smits <ruben dot smits at mech dot kuleuven dot be>\n// URL: http://www.orocos.org/kdl\n\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 2.1 of the License, or (at your option) any later version.\n\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n// Lesser General Public License for more details.\n\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA\n\n#ifndef KDL_ARTICULATEDBODYINERTIA_HPP\n#define KDL_ARTICULATEDBODYINERTIA_HPP\n\n#include \"frames.hpp\"\n\n#include \"rotationalinertia.hpp\"\n#include \"rigidbodyinertia.hpp\"\n\n#include <Eigen/Core>\n\nnamespace KDL {\n    \n    /**\n     *\t\\brief 6D Inertia of a articulated body\n     *\n     *\tThe inertia is defined in a certain reference point and a certain reference base.\n     *\tThe reference point does not have to coincide with the origin of the reference frame.\n     */\n    class ArticulatedBodyInertia{\n    public:\n\n        /**\n         * \tThis constructor creates a zero articulated body inertia matrix,\n         */\n        ArticulatedBodyInertia(){\n            *this=ArticulatedBodyInertia::Zero();\n        }\n\n        /**\n         * \tThis constructor creates a cartesian space articulated body inertia matrix,\n         * \tthe arguments is a rigid body inertia.\n         */\n        ArticulatedBodyInertia(const RigidBodyInertia& rbi);\n\n        /**\n         * \tThis constructor creates a cartesian space inertia matrix,\n         * \tthe arguments are the mass, the vector from the reference point to cog and the rotational inertia in the cog.\n         */\n        explicit ArticulatedBodyInertia(double m, const Vector& oc=Vector::Zero(), const RotationalInertia& Ic=RotationalInertia::Zero());\n        \n        /**\n         * Creates an inertia with zero mass, and zero RotationalInertia\n         */\n        static inline ArticulatedBodyInertia Zero(){\n            return ArticulatedBodyInertia(Eigen::Matrix3d::Zero(),Eigen::Matrix3d::Zero(),Eigen::Matrix3d::Zero());\n        };\n        \n        \n        ~ArticulatedBodyInertia(){};\n        \n        friend ArticulatedBodyInertia operator*(double a,const ArticulatedBodyInertia& I);\n        friend ArticulatedBodyInertia operator+(const ArticulatedBodyInertia& Ia,const ArticulatedBodyInertia& Ib);\n        friend ArticulatedBodyInertia operator+(const ArticulatedBodyInertia& Ia,const RigidBodyInertia& Ib);\n        friend ArticulatedBodyInertia operator-(const ArticulatedBodyInertia& Ia,const ArticulatedBodyInertia& Ib);\n        friend ArticulatedBodyInertia operator-(const ArticulatedBodyInertia& Ia,const RigidBodyInertia& Ib);\n        friend Wrench operator*(const ArticulatedBodyInertia& I,const Twist& t);\n        friend ArticulatedBodyInertia operator*(const Frame& T,const ArticulatedBodyInertia& I);\n        friend ArticulatedBodyInertia operator*(const Rotation& R,const ArticulatedBodyInertia& I);\n\n        /**\n         * Reference point change with v the vector from the old to\n         * the new point expressed in the current reference frame\n         */\n        ArticulatedBodyInertia RefPoint(const Vector& p);\n\n        ArticulatedBodyInertia(const Eigen::Matrix3d& M,const Eigen::Matrix3d& H,const Eigen::Matrix3d& I);\n\n        Eigen::Matrix3d M;\n        Eigen::Matrix3d H;\n        Eigen::Matrix3d I;\n    };\n\n    /**\n     * Scalar product: I_new = double * I_old\n     */\n    ArticulatedBodyInertia operator*(double a,const ArticulatedBodyInertia& I);\n    /**\n     * addition I: I_new = I_old1 + I_old2, make sure that I_old1\n     * and I_old2 are expressed in the same reference frame/point,\n     * otherwise the result is worth nothing\n     */\n    ArticulatedBodyInertia operator+(const ArticulatedBodyInertia& Ia,const ArticulatedBodyInertia& Ib);\n    ArticulatedBodyInertia operator+(const ArticulatedBodyInertia& Ia,const RigidBodyInertia& Ib);\n    ArticulatedBodyInertia operator-(const ArticulatedBodyInertia& Ia,const ArticulatedBodyInertia& Ib);\n    ArticulatedBodyInertia operator-(const ArticulatedBodyInertia& Ia,const RigidBodyInertia& Ib);\n\n    /**\n     * calculate spatial momentum: h = I*v\n     * make sure that the twist v and the inertia are expressed in the same reference frame/point\n     */\n    Wrench operator*(const ArticulatedBodyInertia& I,const Twist& t);\n\n    /**\n     * Coordinate system transform Ia = T_a_b*Ib with T_a_b the frame from a to b.\n     */\n    ArticulatedBodyInertia operator*(const Frame& T,const ArticulatedBodyInertia& I);\n    /**\n     * Reference frame orientation change Ia = R_a_b*Ib with R_a_b\n     * the rotation of b expressed in a\n     */\n    ArticulatedBodyInertia operator*(const Rotation& R,const ArticulatedBodyInertia& I);\n\n}\n#endif\n", "meta": {"hexsha": "eaca55a65a08bc43e12a1fe613bc2fc75908563f", "size": 5266, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "RLSC1/vreprlsc/programming/include/kdl/articulatedbodyinertia.hpp", "max_stars_repo_name": "ichalkiad/RLSC_BaxterSimulation", "max_stars_repo_head_hexsha": "1a15f2b06521378af056a40c3765d7e6c6823596", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 742.0, "max_stars_repo_stars_event_min_datetime": "2017-07-05T02:49:36.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T12:55:43.000Z", "max_issues_repo_path": "RLSC1/vreprlsc/programming/include/kdl/articulatedbodyinertia.hpp", "max_issues_repo_name": "ichalkiad/RLSC_BaxterSimulation", "max_issues_repo_head_hexsha": "1a15f2b06521378af056a40c3765d7e6c6823596", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 73.0, "max_issues_repo_issues_event_min_datetime": "2017-07-06T12:50:51.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-07T08:07:07.000Z", "max_forks_repo_path": "RLSC1/vreprlsc/programming/include/kdl/articulatedbodyinertia.hpp", "max_forks_repo_name": "ichalkiad/RLSC_BaxterSimulation", "max_forks_repo_head_hexsha": "1a15f2b06521378af056a40c3765d7e6c6823596", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 425.0, "max_forks_repo_forks_event_min_datetime": "2017-07-04T22:03:29.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-29T06:59:06.000Z", "avg_line_length": 41.7936507937, "max_line_length": 138, "alphanum_fraction": 0.7031902773, "num_tokens": 1304, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6513548646660542, "lm_q2_score": 0.4882833952958347, "lm_q1q2_score": 0.31804576486159986}}
{"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 \"Utils/Geometry/GeometryUtilities.h\"\n#include \"Utils/Geometry/AtomCollection.h\"\n#include \"Utils/Geometry/ElementInfo.h\"\n#include \"Utils/Math/QuaternionFit.h\"\n#include <Eigen/Eigenvalues>\n#include <limits>\n\nnamespace Scine {\nnamespace Utils {\nnamespace Geometry {\n\nPositionCollection translatePositions(const PositionCollection& positions, const Eigen::Ref<Eigen::RowVector3d>& translation) {\n  PositionCollection pc = positions;\n  translatePositionsInPlace(pc, translation);\n  return pc;\n}\n\nvoid translatePositionsInPlace(PositionCollection& positions, const Eigen::Ref<Eigen::RowVector3d>& translation) {\n  positions.rowwise() += translation;\n}\n\nint getIndexOfClosestAtom(const PositionCollection& positions, const Position& targetPosition,\n                          double squaredDistanceConsideredZero) {\n  assert(positions.rows() != 0 && \"Cannot determine closest atom if there are no atoms!\");\n  double minimalDistanceSquared = std::numeric_limits<double>::max();\n  int closestAtom = 0;\n\n  auto nAtoms = static_cast<int>(positions.rows());\n\n  for (int i = 0; i < nAtoms; i++) {\n    double currentSquaredDistance = (positions.row(i) - targetPosition).squaredNorm();\n    if (currentSquaredDistance <= squaredDistanceConsideredZero)\n      continue;\n    if (currentSquaredDistance < minimalDistanceSquared) {\n      minimalDistanceSquared = currentSquaredDistance;\n      closestAtom = i;\n    }\n  }\n\n  return closestAtom;\n}\n\nint getIndexOfAtomInStructure(const AtomCollection& structure, const Atom& atom, double squaredDistanceConsideredZero) {\n  int index = 0;\n  ElementType element = atom.getElementType();\n  for (const auto& a : structure) {\n    if (a.getElementType() == element) { // First check whether the element types match\n      double squaredDistance = (a.getPosition() - atom.getPosition()).squaredNorm();\n      if (squaredDistance <= squaredDistanceConsideredZero) { // Check whether the atoms have basically the same position\n        return index;\n      }\n    }\n    index++;\n  }\n  throw std::runtime_error(\"The given atom was not found in the given structure.\");\n}\n\nEigen::MatrixXd positionVectorToMatrix(const Eigen::VectorXd& v) {\n  assert(v.size() % 3 == 0);\n\n  using namespace Eigen;\n  using RowMajorMatrix = Matrix<double, Dynamic, Dynamic, RowMajor>;\n\n  auto numberParticles = v.size() / 3;\n  Map<const RowMajorMatrix> mapMatrix(v.data(), numberParticles, 3);\n  return mapMatrix;\n}\n\nEigen::VectorXd positionMatrixToVector(const Eigen::MatrixXd& m) {\n  assert(m.cols() == 3);\n\n  using namespace Eigen;\n  using RowMajorMatrix = Matrix<double, Dynamic, Dynamic, RowMajor>;\n\n  RowMajorMatrix m2(m);\n  Map<const VectorXd> mapVector(m2.data(), m2.size());\n\n  return mapVector;\n}\n\nvoid alignPositions(const PositionCollection& reference, PositionCollection& positions) {\n  QuaternionFit fit(reference, positions);\n  positions = fit.getFittedData();\n}\n\nstd::vector<double> getMasses(const ElementTypeCollection& elements) {\n  std::vector<double> masses;\n  masses.reserve(elements.size());\n  std::transform(elements.begin(), elements.end(), std::back_inserter(masses), ElementInfo::mass);\n  return masses;\n}\n\nPosition getCenterOfMass(const PositionCollection& positions, const std::vector<double>& masses) {\n  Position P;\n  P.setZero();\n  double totalMass = 0;\n  for (int i = 0; i < positions.rows(); ++i) {\n    P += masses[i] * positions.row(i);\n    totalMass += masses[i];\n  }\n  P /= totalMass;\n  return P;\n}\n\nPosition getCenterOfMass(const AtomCollection& structure) {\n  auto masses = getMasses(structure.getElements());\n  return getCenterOfMass(structure.getPositions(), masses);\n}\n\nPosition getAveragePosition(const PositionCollection& positions) {\n  return positions.colwise().sum() / positions.rows();\n}\n\nEigen::Matrix3d calculateInertiaTensor(const PositionCollection& positions, const std::vector<double>& masses,\n                                       const Position& centerOfMass) {\n  double Ixx = 0, Iyy = 0, Izz = 0, Ixy = 0, Ixz = 0, Iyz = 0;\n  for (int i = 0; i < positions.rows(); ++i) {\n    double m = masses[i];\n    auto dp = positions.row(i) - centerOfMass;\n    double x = dp.x();\n    double y = dp.y();\n    double z = dp.z();\n    Ixx += m * (y * y + z * z);\n    Iyy += m * (x * x + z * z);\n    Izz += m * (x * x + y * y);\n    Ixy -= m * x * y;\n    Ixz -= m * x * z;\n    Iyz -= m * y * z;\n  }\n  Eigen::Matrix3d In;\n  In << Ixx, Ixy, Ixz, Ixy, Iyy, Iyz, Ixz, Iyz, Izz;\n  return In;\n}\n\nPrincipalMomentsOfInertia calculatePrincipalMoments(const PositionCollection& positions,\n                                                    const std::vector<double>& masses, const Position& centerOfMass) {\n  auto In = calculateInertiaTensor(positions, masses, centerOfMass);\n\n  Eigen::SelfAdjointEigenSolver<Eigen::Matrix3d> es;\n  es.compute(In);\n\n  PrincipalMomentsOfInertia pmi;\n  pmi.eigenvalues = es.eigenvalues();\n  pmi.eigenvectors = es.eigenvectors();\n  return pmi;\n}\n\nEigen::MatrixXd calculateTranslationAndRotationModes(const PositionCollection& positions, const ElementTypeCollection& elements) {\n  auto nAtoms = positions.rows();\n  auto masses = Utils::Geometry::getMasses(elements);\n  auto centerOfMass = Utils::Geometry::getCenterOfMass(positions, masses);\n  auto principalMoments = Utils::Geometry::calculatePrincipalMoments(positions, masses, centerOfMass);\n\n  const auto& X = principalMoments.eigenvectors;\n\n  Eigen::MatrixXd allRotoTranslationVectors(3 * nAtoms, 6);\n\n  for (int i = 0; i < nAtoms; ++i) {\n    // Translation\n    allRotoTranslationVectors.block(3 * i, 0, 3, 3) = Eigen::MatrixXd::Identity(3, 3);\n\n    // Rotation\n    Eigen::Vector3d P = X.transpose() * (positions.row(i) - centerOfMass).transpose();\n    Eigen::Matrix3d d;\n    d.col(0) = P.y() * X.col(2) - P.z() * X.col(1);\n    d.col(1) = P.z() * X.col(0) - P.x() * X.col(2);\n    d.col(2) = P.x() * X.col(1) - P.y() * X.col(0);\n\n    allRotoTranslationVectors.block(3 * i, 3, 3, 3) = d;\n  }\n\n  // look which roto-translational modes are valid\n  std::vector<int> validRotoTranslationModes;\n  for (int i = 0; i < 6; ++i) {\n    // The norm will be zero for \"invalid\" roto-translation modes (single atoms, linear molecules).\n    auto squaredNorm = allRotoTranslationVectors.col(i).squaredNorm();\n    if (squaredNorm > 0.1) {\n      validRotoTranslationModes.push_back(i);\n    }\n  }\n\n  // return only the valid modes\n  auto numberRotoTranslationModes = static_cast<int>(validRotoTranslationModes.size());\n  Eigen::MatrixXd rotoTranslationVectors(3 * nAtoms, numberRotoTranslationModes);\n  for (int i = 0; i < numberRotoTranslationModes; ++i) {\n    rotoTranslationVectors.col(i) = allRotoTranslationVectors.col(validRotoTranslationModes[i]);\n  }\n  rotoTranslationVectors.colwise().normalize();\n\n  return rotoTranslationVectors;\n}\n\nEigen::MatrixXd calculateRotTransFreeTransformMatrix(const PositionCollection& positions,\n                                                     const ElementTypeCollection& elements, bool massWeighted) {\n  auto rotoTranslation = calculateTranslationAndRotationModes(positions, elements);\n  // If mass-weighted Hessian shall be transformed the rotation and translation modes have to be adapted accordingly\n  if (massWeighted) {\n    int nAtoms = elements.size();\n    auto masses = Geometry::getMasses(elements);\n    for (int i = 0; i < nAtoms; ++i) {\n      rotoTranslation.middleRows(3 * i, 3) *= std::sqrt(masses[i]);\n    }\n    rotoTranslation.colwise().normalize();\n  }\n  auto nDims = rotoTranslation.rows();\n  auto numberRotoTranslationModes = rotoTranslation.cols();\n\n  srand(42);\n  Eigen::MatrixXd A = Eigen::MatrixXd::Random(nDims, nDims);\n\n  A.leftCols(numberRotoTranslationModes) = rotoTranslation;\n\n  // Orthogonalization\n  auto n = nDims;\n  auto m = nDims;\n  Eigen::MatrixXd R_1(n, n);\n  Eigen::MatrixXd Q_1(m, n);\n  for (int i = 0; i < n; ++i) {\n    R_1(i, i) = A.col(i).norm();\n    Q_1.col(i) = A.col(i) / R_1(i, i);\n    for (int j = i + 1; j < n; ++j) {\n      R_1(i, j) = Q_1.col(i).transpose() * A.col(j);\n      A.col(j) -= (Q_1.col(i) * R_1(i, j));\n    }\n  }\n\n  A.colwise().normalize();\n\n  return A.rightCols(nDims - numberRotoTranslationModes);\n}\n\n} /* namespace Geometry */\n} /* namespace Utils */\n} /* namespace Scine */\n", "meta": {"hexsha": "466fcbf9ee7fbced28cded7c11313e4ffd163d79", "size": 8384, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Utils/Utils/Geometry/GeometryUtilities.cpp", "max_stars_repo_name": "DockBio/utilities", "max_stars_repo_head_hexsha": "213ed5ac2a64886b16d0fee1fcecb34d36eea9e9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Utils/Utils/Geometry/GeometryUtilities.cpp", "max_issues_repo_name": "DockBio/utilities", "max_issues_repo_head_hexsha": "213ed5ac2a64886b16d0fee1fcecb34d36eea9e9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Utils/Utils/Geometry/GeometryUtilities.cpp", "max_forks_repo_name": "DockBio/utilities", "max_forks_repo_head_hexsha": "213ed5ac2a64886b16d0fee1fcecb34d36eea9e9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.7883817427, "max_line_length": 130, "alphanum_fraction": 0.6828482824, "num_tokens": 2199, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6513548511303336, "lm_q2_score": 0.48828339529583464, "lm_q1q2_score": 0.3180457582523322}}
{"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 <vw/Image.h>\n#include <vw/FileIO.h>\n\n#include <vw/Cartography/GeoReference.h>\n#include <vw/Cartography/GeoTransform.h>\n#include <vw/Image/ImageMath.h>\n#include <vw/Image/Algorithms.h>\n#include <vw/Math/Matrix.h>\n#include <vw/Math/Vector.h>\n#include <vw/Math/LinearAlgebra.h>\n#include <vw/FileIO/DiskImageView.h>\n#include <vw/tools/Common.h>\n\n/*\nImplements modified versions of finite difference opt.algorithms + fitting a plane to 9 points of a 3x3 window\n*/\n\n#include <boost/program_options.hpp>\nnamespace po = boost::program_options;\n\n#include <boost/filesystem/path.hpp>\nnamespace fs = boost::filesystem;\n\nusing namespace vw;\nusing namespace vw::math;\nusing namespace vw::cartography;\n\nenum Algorithm { HORN, SA, FH, PLANEFIT };\n\nstruct Options {\n  std::string input_file_name;\n  std::string output_prefix;\n  bool output_gradient;\n  bool output_aspect;\n  bool output_pretty; //probably more for debugging purposes than for anything else\n  Algorithm algorithm;\n  bool spherically_defined;\n};\n\n//basic utilities\n\nVector3 pixel_to_cart (Vector2 pos, double alt, 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),alt);\n  Vector3 loc_cartesian=GR.datum().geodetic_to_cartesian(loc_longlat3);\n  return loc_cartesian;\n}\n\ntemplate <class ImageT>\nVector3 pixel_to_cart (Vector2 pos, DiskImageView<ImageT> img, GeoReference GR) {\n  return pixel_to_cart(pos,img((int)pos[0],(int)pos[1]),GR);\n}\n\ndouble dist_from_2pi(double n) {\n  if( fabs(n+2*M_PI) < fabs(n) ) return n+2*M_PI;\n  if( fabs(n-2*M_PI) < fabs(n) ) return n-2*M_PI;\n  return n;\n}\n\n//utilities...\n\nVector2 gradient_aspect_from_normals(Vector3 center_normal, Vector3 plane_normal) {\n  //gradient angle is absval\n  double dotprod=dot_prod(plane_normal,center_normal);\n  double gradient_angle=acos(dotprod);\n  Vector3 surface_normal_on_sphere_tangent_plane=normalize(plane_normal-dot_prod(plane_normal,center_normal)*center_normal);\n\n  //get projection of (0,0,1) onto sphere tangent plane.\n  Vector3 north(0,0,1);\n  Vector3 north_projected=normalize(north-dot_prod(north,center_normal)*center_normal);\n\n  //find the angle between those two\n  double dotprod2=dot_prod(surface_normal_on_sphere_tangent_plane, north_projected);\n\n  //figure out which angle it is.\n  double aspect=acos(dotprod2);\n  if(dotprod2>1) { dotprod2=1; aspect=0;}\n  if(dotprod2<-1) { dotprod2=-1; aspect=0;}\n\n  if( dot_prod((cross_prod(north_projected,surface_normal_on_sphere_tangent_plane)),center_normal) < 0)\n    aspect=M_PI+aspect;\n  else\n    aspect=M_PI-aspect;\n\n  if(aspect>=2*M_PI)\n    aspect=aspect-2*M_PI;\n  return Vector2(aspect,gradient_angle);\n}\n\nVector2 gradient_aspect_from_dx_dy(double& dx, double& dy) {\n  //total gradient:\n  double gradient=norm_2(Vector2(dx,dy));\n  double gradient_angle=atan(gradient);\n  //aspect: dy/dx=tan(angle)\n  double aspect=atan(dy/dx);\n  if(dx<0) aspect=aspect+M_PI;\n  aspect=2*M_PI-aspect+M_PI/2;\n  if(aspect<0) aspect=2*M_PI+aspect;\n  if(aspect>=2*M_PI) aspect=aspect-2*M_PI*(int)(aspect/2/M_PI);\n  return Vector2(aspect,gradient_angle);\n}\n\nVector2 gradient_aspect_from_dtheta_dphi(double rho, double theta, double phi, double& dtheta, double& dphi, Vector3 center) {\n  double r_comp=1;\n  double theta_comp=dtheta/rho;\n  double phi_comp=1/(rho*sin(theta))*dphi;\n\n  double n_x=r_comp*sin(theta)*cos(phi)-phi_comp*sin(phi)+theta_comp*cos(theta)*cos(phi);\n  double n_y=r_comp*sin(theta)*sin(phi)+phi_comp*cos(phi)+theta_comp*cos(theta)*sin(phi);\n  double n_z=r_comp*cos(theta)-theta_comp*sin(theta);\n\n  Vector3 plane_normal=normalize(Vector3(n_x,n_y,n_z));\n  center=normalize(center);\n  return gradient_aspect_from_normals(center, plane_normal);\n}\n\ntemplate <class ImageT>\nVector2 uneven_grid (const ::Options& opt, int x, int y, DiskImageView<ImageT> img, GeoReference GR) {\n\n  Vector3 center=pixel_to_cart(Vector2(x,y),img,GR);\n  Vector3 center_normal=normalize(center);\n  Vector3 center_below=pixel_to_cart(Vector2(x,y),0,GR);\n\n  Vector3 north=Vector3(0,0,1);\n        Vector3 north_projected=normalize(north-dot_prod(north,center_normal)*center_normal);\n\n  //define temporary axis\n  Vector3 up_normal=normalize(north_projected);        //also theta hat\n  Vector3 third=normalize(cross_prod(up_normal,center_normal));     //also phi hat\n\n  //spherical\n  Vector2 lonlat=GR.pixel_to_lonlat(Vector2(x,y));\n  double lat=lonlat(1);\n  double lon=lonlat(0);\n\n  //rise= run*slope\n  Matrix<double> rises;  //rise over vector distance\n  Matrix<double> runs;  //components in either direction\n\n  //different ways of weighting neighbors.\n  if(opt.algorithm==HORN) { rises=Matrix<double>(12,1); runs=Matrix<double>(12,2); }\n  if(opt.algorithm==SA)   { rises=Matrix<double>(8,1); runs=Matrix<double>(8,2); }\n  if(opt.algorithm==FH)   { rises=Matrix<double>(4,1); runs=Matrix<double>(4,2); }\n\n  int ct=0;\n  for(int i=-1;i<=1;i++) {\n    for(int j=-1;j<=1;j++) {\n      if(i==0 && j==0) continue;\n      int repeat=1;\n      if(opt.algorithm==HORN) {\n        if((i==0 && j!=0) || (i!=0 && j==0)) //for horn, weight direct neighbors twice\n          repeat=2;\n      }\n      if(opt.algorithm==FH) {\n        if(i!=0 && j!=0) //ignore diagonals\n          continue;\n      }\n\n      for(int k=0;k<repeat;k++) {\n        if(!opt.spherically_defined) {\n          Vector3 neighbor=pixel_to_cart(Vector2(x+i,y+j),img,GR);\n          Vector3 neighbor_below_rescale=normalize(neighbor)*(norm_2(center_below)/dot_prod(normalize(neighbor),center_normal));\n          Vector3 v=neighbor_below_rescale-center_below;\n          //or, project both onto tangent plane...\n          rises(ct,0)=(img(x+i,y+j)-img(x,y))/norm_2(v);\n          v=normalize(v);\n          runs(ct,0)=dot_prod(v,up_normal);\n          runs(ct,1)=dot_prod(v,third);\n        } else {\n          rises(ct,0)=(img(x+i,y+j)-img(x,y));\n          Vector2 neighbor_lonlat=GR.pixel_to_lonlat(Vector2(x+i,y+j));\n          runs(ct,0)=(neighbor_lonlat[1]-lonlat[1])*M_PI/180.0;\n          runs(ct,1)=dist_from_2pi(neighbor_lonlat[0]-lonlat[0])*M_PI/180.0;\n        }\n        ct++;\n      }\n    }\n  }\n  //solve using least squares\n  //gradient components=(VtV)-1Vt * rises\n  Matrix<double> VtV(2,2);\n  VtV=transpose(runs)*runs;\n  Matrix<double> VtVinv(2,2);\n  VtVinv(0,0)=VtV(1,1);\n  VtVinv(1,1)=VtV(0,0);\n  VtVinv(0,1)=-VtV(0,1);\n  VtVinv(1,0)=-VtV(1,0);\n  VtVinv=VtVinv/(VtV(0,0)*VtV(1,1)-VtV(0,1)*VtV(1,0));\n\n  Matrix<double> ans=VtVinv*transpose(runs)*rises;\n\n  if(opt.spherically_defined) {\n    double rho=norm_2(center);\n    double phi=lon/180.0*M_PI;\n    double theta=(-lat+90.0)/180.0*M_PI;\n    double dtheta=ans(0,0);\n    double dphi=-ans(1,0);\n    return gradient_aspect_from_dtheta_dphi(rho, theta, phi, dtheta, dphi, center);\n  }\n  //otherwise,\n  return gradient_aspect_from_dx_dy(ans(0,1), ans(0,0));\n}\n\ntemplate <class ImageT>\nVector2 interpolate_plane (int x, int y, DiskImageView<ImageT> img, GeoReference GR) {\n  Matrix<double> A(9,4);\n  int i=0;\n  int j=0;\n  int ct=0;\n  Vector3 center_normal=pixel_to_cart(Vector2(x,y),img,GR);\n\n  for(i=-1;i<=1;i++) {\n    for(j=-1;j<=1;j++) {\n      Vector3 tmp=pixel_to_cart(Vector2(x+i,y+j),img,GR);\n      A(ct,0)=tmp(0);\n      A(ct,1)=tmp(1);\n      A(ct,2)=tmp(2);\n      A(ct,3)=1;\n      ct++;\n    }\n  }\n\n  Matrix<double> U;\n  Matrix<double> VT;\n  Vector<double> s;\n\n  svd(A, U, s, VT);\n  Vector<double> plane_normal(3);\n  plane_normal(0)=VT(3,0);\n  plane_normal(1)=VT(3,1);\n  plane_normal(2)=VT(3,2);\n  //normalize sphere normal\n  center_normal=normalize(center_normal);\n  plane_normal=normalize(plane_normal);\n  if(dot_prod(plane_normal,center_normal) <0) plane_normal=plane_normal*-1;\n  return gradient_aspect_from_normals(center_normal, plane_normal);\n}\n\ntemplate <class imageT>\nvoid do_slopemap (const ::Options &opt) { //not sure what the arguments are\n\n  GeoReference GR;\n  read_georeference( GR, opt.input_file_name );\n\n  DiskImageView<imageT> img(opt.input_file_name);\n\n  int x;\n  int y;\n\n  ImageView<double> gradient_angle;\n  ImageView<double> aspect;\n  ImageView<PixelHSV<double> > pretty;\n\n  if(opt.output_gradient)\n    gradient_angle.set_size(img.cols(),img.rows());\n  if(opt.output_aspect)\n    aspect.set_size(img.cols(),img.rows());\n  if(opt.output_pretty) pretty.set_size(img.cols(),img.rows());\n\n  for(x=1;x<img.cols()-1;x++) {\n    for(y=1;y<img.rows()-1;y++) {\n      Vector2 res;\n      //these are pretty similar...\n      if(opt.algorithm==PLANEFIT) res=interpolate_plane(x,y,img,GR);\n      else res=uneven_grid(opt, x,y,img,GR);\n\n      if(opt.output_aspect)   aspect(x,y) = res(0);\n      if(opt.output_gradient) gradient_angle(x,y) = res(1);\n      if(opt.output_pretty)   pretty(x,y) = PixelHSV<double>(res(0),res(1),(res(1))+0.2*fabs(M_PI-res(0)));//(res(1)/M_PI*2)*fabs(M_PI-res(0)));\n     }\n  }\n  ImageView<PixelRGB<uint8> > pretty2;\n\n  if(opt.output_pretty) {\n    select_channel(pretty,0)=normalize(select_channel(pretty,0),0,2*M_PI,0,1);\n    select_channel(pretty,1)=normalize(select_channel(pretty,1),0,M_PI/2,0.1,1);\n    select_channel(pretty,2)=normalize(select_channel(pretty,2),0.3,0.6);\n\n    pretty2=pixel_cast_rescale<PixelRGB<uint8> >( copy(pretty) );\n    pretty2=PixelRGB<uint8>(255,255,255)-pretty2;\n  }\n  //save everything to file\n  if(opt.output_gradient) write_georeferenced_image( opt.output_prefix + \"_gradient.tif\" , gradient_angle, GR);\n  if(opt.output_aspect)   write_georeferenced_image( opt.output_prefix + \"_aspect.tif\"   , aspect, GR);\n  if(opt.output_pretty)   write_image( opt.output_prefix + \"_pretty.tif\"   , pretty2);\n}\n\n\nint main( int argc, char *argv[] ) {\n\n  ::Options opt;\n  std::string algorithm_string;\n\n  po::options_description desc(\"Description: Outputs gradient and/or aspect at each point of an input DEM with altitude values\\n\\nUsage: slopemap [options] <input file> \\n\\nOptions\");\n  desc.add_options()\n    (\"help,h\", \"Display this help messsage\")\n    (\"input-file\", po::value<std::string>(&opt.input_file_name), \"Explicitly specify the input file\")\n    (\"output-prefix,o\", po::value<std::string>(&opt.output_prefix), \"Specify the output prefix\") //should add more description...\n    (\"no-aspect\", \"Do not output aspect\")\n    (\"no-gradient\", \"Do not output gradient\")\n    (\"pretty\", \"Output colored image.\")\n    (\"opt.algorithm\", po::value<std::string>(&algorithm_string)->default_value(\"horn\"), \"Choose an algorithm to calculate slope/aspect from [ horn, fh, sa, planefit ]. Horn: Horn's algorithm; FH: Fleming & Hoffer's (rook's case); SA: Sharpnack & Akin's (queen's case)\")\n    (\"spherical\", po::value<bool>(&opt.spherically_defined)->default_value(true), \"Spherical/elliptical datum (recommended); otherwise, a flat grid\");\n\n  po::positional_options_description p;\n  p.add(\"input-file\", 1);\n\n  po::variables_map vm;\n  try {\n    po::store( po::command_line_parser( argc, argv ).options(desc).positional(p).run(), vm );\n    po::notify( vm );\n  } catch (const po::error& e) {\n    std::cout << \"An error occured while parsing command line arguments.\\n\";\n    std::cout << \"\\t\" << e.what() << \"\\n\\n\";\n    std::cout << desc << std::endl;\n    return 1;\n  }\n\n  if( vm.count(\"help\") ) {\n    std::cout << desc << std::endl;\n    return 1;\n  }\n  if( vm.count(\"input-file\") != 1 ) {\n    std::cout << \"Error: Must specify exactly one input file!\\n\" << std::endl;\n    std::cout << desc << std::endl;\n    return 1;\n  }\n\n  if( opt.output_prefix == \"\" )\n    opt.output_prefix=fs::path(opt.input_file_name).replace_extension().string();\n\n  //checking strings\n\n  boost::to_lower(algorithm_string);\n  if( !(  algorithm_string == \"horn\" ||\n    algorithm_string == \"fh\" ||\n    algorithm_string == \"sa\" ||\n    algorithm_string == \"planefit\" ||\n\n    algorithm_string == \"\" ) ) { //it's okay if it isn't set?\n    vw_out() << \"Unknown opt.algorithm: \" << algorithm_string << \". Options are : [ horn, fh, sa, planefit ]\\n\";\n    exit(0);\n  }\n  else {\n    if(algorithm_string==\"horn\")\n      opt.algorithm=HORN;\n    else if(algorithm_string==\"fh\")\n      opt.algorithm=FH;\n    else if(algorithm_string==\"sa\")\n      opt.algorithm=SA;\n    else if(algorithm_string==\"planefit\")\n      opt.algorithm=PLANEFIT;\n  }\n\n  opt.output_aspect   = !(vm.count(\"no-aspect\"));\n  opt.output_gradient = !(vm.count(\"no-gradient\"));\n  opt.output_pretty   = vm.count(\"pretty\");\n\n  if(!opt.output_aspect && !opt.output_gradient && !opt.output_pretty) {\n    vw_out() << \"No output specified. Select at least one of [ gradient, output, pretty ].\\n\"\n             << std::endl;\n  }\n\n  try {\n    // Get the right pixel/channel type.\n    ImageFormat fmt = tools::taste_image(opt.input_file_name);\n\n    switch(fmt.pixel_format) {\n    case VW_PIXEL_GRAY:\n    case VW_PIXEL_GRAYA:\n    case VW_PIXEL_RGB:\n    case VW_PIXEL_RGBA:\n      switch(fmt.channel_type) {\n      case VW_CHANNEL_UINT8:  do_slopemap<PixelGray<uint8>   >(opt); break;\n      case VW_CHANNEL_INT16:  do_slopemap<PixelGray<int16>   >(opt); break;\n      case VW_CHANNEL_UINT16: do_slopemap<PixelGray<uint16>  >(opt); break;\n      case VW_CHANNEL_FLOAT32:do_slopemap<PixelGray<float32> >(opt); break;\n      case VW_CHANNEL_FLOAT64:do_slopemap<PixelGray<float64> >(opt); break;\n      default:                do_slopemap<PixelGray<float32> >(opt); break;\n      }\n      break;\n    default:\n      std::cout << \"Error: Unsupported pixel format.\\n\";\n      exit(0);\n    }\n  } catch (const Exception& e) {\n    std::cout << \"Error: \" << e.what() << std::endl;\n  }\n  return 0;\n\n}\n", "meta": {"hexsha": "80f5dbe8e5b9360375217597174c793a67153235", "size": 13601, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/vw/tools/slopemap.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/tools/slopemap.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/tools/slopemap.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": 34.0025, "max_line_length": 269, "alphanum_fraction": 0.6809058157, "num_tokens": 3961, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6619228758499943, "lm_q2_score": 0.480478678047907, "lm_q1q2_score": 0.31803982835807415}}
{"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_LAYER_LAYER_HPP\n#define SP_ALGO_NN_LAYER_LAYER_HPP\n\n#include <iosfwd>\n#include <boost/assert.hpp>\n#include \"../config.hpp\"\n#include \"../matrix.hpp\"\n#include \"../types.hpp\"\n#include \"params.hpp\"\n#include \"sp/util/types.hpp\"\n#include \"activation/op.hpp\"\n#include \"detail/layers.hpp\"\n\n\nSP_ALGO_NN_NAMESPACE_BEGIN\n\n/**\n * \\file Basic layer abstract class\n */\n\n/**\n * \\brief Abstract layer of neural network\n *\n * All possible layer types extend this base type.\n *\n * \\tparam Attached, if layer shares state with previous layer\n * \\tparam DefaultOutputRange when false, must implement out_range\n * \\tparam ConfiguresItself, when true, must implement\n *         '''configuration_impl(const size_t& batch_size, bool reset)'''\n *         and it must initialize weights and bias, if any\n */\ntemplate<\n    typename InputVolume,\n    typename OutputVolume,\n    typename Derived,\n    bool DefaultOutputRange = true,\n    bool ConfiguresItself = false\n>\nstruct layer {\n\n    using derived_type = Derived;\n\n    /**\n     * \\brief Input Dimensions\n     */\n    using input_dims = InputVolume;\n\n    /**\n     * \\brief Output Dimensions\n     */\n    using output_dims = OutputVolume;\n\n    constexpr static bool default_output_range = DefaultOutputRange;\n\n    constexpr static bool configures_itself = ConfiguresItself;\n\n    /**\n     * Validate InputDims\n     */\n    static_assert(util::is_instantiation_of_v<InputVolume, volume_dims>, \"InputDim template parameter must be an instance of input_dims\");\n\n    /**\n     * Validate OutputDims\n     */\n    static_assert(util::is_instantiation_of_v<OutputVolume, volume_dims>, \"InputDim template parameter must be an instance of input_dims\");\n\n    /**\n     * Feed forward propagation\n     *\n     * \\param input The input tensor\n     */\n    void forward_prop(tensor_4& input, tensor_4& output) {\n        BOOST_ASSERT_MSG(\n            detail::validate_dimensions<input_dims>(input),\n            \"Dimensions of input matches input dimension\"\n        );\n        BOOST_ASSERT_MSG(\n            detail::validate_dimensions<output_dims>(output),\n            \"Dimensions of output matches output dimensions\"\n        );\n        derived().forward_prop_impl(input, output);\n    }\n\n    /**\n     * Backward propagation\n     * \\param input The input tensor\n     * \\param output The output tensor\n     */\n    void backward_prop(     tensor_4& prev_out,\n                            tensor_4& prev_delta,\n                            tensor_4& curr_out,\n                            tensor_4& curr_delta) {\n        BOOST_ASSERT_MSG(\n            detail::validate_dimensions<input_dims>(prev_out),\n            \"Dimensions prev_out matches input dimension\"\n        );\n        BOOST_ASSERT_MSG(\n            detail::validate_dimensions<input_dims>(prev_delta),\n            \"Dimensions prev_delta matches input dimension\"\n        );\n        BOOST_ASSERT_MSG(\n            detail::validate_dimensions<output_dims>(curr_out),\n            \"Dimensions of curr_out matches input dimensions\"\n        );\n        BOOST_ASSERT_MSG(\n            detail::validate_dimensions<output_dims>(curr_delta),\n            \"Dimensions of current_delta matches output dimensions\"\n        );\n        derived().backward_prop_impl(prev_out, prev_delta, curr_out, curr_delta);\n    }\n\n    template<typename Optimizer>\n    void update_weights(Optimizer& optimizer) {\n        if constexpr (detail::has_weight_and_delta_v<derived_type>) {\n            update_weights(optimizer, wdeltas, derived().dw, derived().w);\n        }\n        if constexpr (detail::has_bias_and_delta_v<derived_type>) {\n            update_weights(optimizer, bdeltas, derived().db, derived().b);\n        }\n        clear_gradients();\n    }\n\n    /**\n     * \\brief Helper funciton which combines delta of the layer into a combined\n     *        state which then applies the combined delta to the updating tensor\n     * \\tparam optimizer the Optimizing strategy\n     * \\tparam combined the tensor to stored the combined delta state of all samples\n     * \\tparam updating the sensor that is to be updated via the optimizer\n     */\n    template<typename Optimizer, typename CombiningTensor, typename FromTensor, typename ToTensor>\n    void update_weights(Optimizer& optimizer, CombiningTensor& combined, FromTensor& delta, ToTensor& updating) {\n        const size_t samples = delta.dimension(0);\n        BOOST_ASSERT(samples >= 1);\n        /* Sum*/\n        combined = delta.chip(0, 0);\n        for(size_t s = 1; s < samples; ++s) {\n            /* add the other delta chips */\n            combined += delta.chip(s, 0);\n        }\n        if(samples > 1) {\n            const float_t reciprocal_batch_size = 1.0f / static_cast<float_t>(samples);\n            combined = combined * reciprocal_batch_size;\n        };\n        optimizer.template update(combined, updating);\n    }\n\n    void clear_gradients() {\n        if constexpr (detail::has_weight_and_delta_v<derived_type>) {\n            derived().dw.setZero();\n        }\n        if constexpr (detail::has_bias_and_delta_v<derived_type>) {\n            derived().db.setZero();\n        }\n    }\n\n    /**\n     * \\brief Configures layer. Must be called before use. It is undefined\n     *        behavior not to configure a layer before use.\n     */\n    void configure(const size_t& batch_size, bool reset = false) {\n        if constexpr(configures_itself) {\n            derived().configuration_impl(batch_size, reset);\n        } else {\n            default_configuration(batch_size, reset);\n        }\n    }\n\n    /**\n     * \\brief Default configuration behavior\n     * Can be called from a custom configure_impl in order to keep original default\n     * configuration, or alternatively called\n     */\n    void default_configuration(const size_t& batch_size, bool reset = false) {\n        if constexpr(detail::has_weight_and_delta_v<derived_type>) {\n            detail::prepare_weights<typename derived_type::weights_dims>(derived().w);\n            detail::prepare_and_zero_delta_weights<typename derived_type::weights_dims>(batch_size, derived().dw);\n            if(reset) {\n                detail::apply_weight_initializer(derived());\n            }\n        }\n        if constexpr(detail::has_bias_and_delta_v<derived_type>) {\n            detail::prepare_bias<typename derived_type::output_dims>(derived().b);\n            detail::prepare_and_zero_bias_delta<typename derived_type::output_dims>(batch_size, derived().db);\n            if(reset) {\n                detail::apply_bias_initializer(derived());\n            }\n        }\n        /* Always clear gradients */\n        clear_gradients();\n    }\n\n    /**\n     * Load the layer's weights from the input stream\n     * @param is\n     */\n    void load(std::istream& is) {\n        if constexpr(detail::has_weight_and_delta_v<derived_type>) {\n            auto& w = derived().w;\n            float_t tmp;\n            for(size_t i = 0, len = w.size(); i < len; ++i) {\n                is >> tmp;\n                w.data()[i] = tmp;\n            }\n        }\n        if constexpr(detail::has_bias_and_delta_v<derived_type>) {\n            auto& b = derived().b;\n            float_t tmp;\n            for(size_t i = 0, len = b.size(); i < len; ++i) {\n                is >> tmp;\n                b.data()[i] = tmp;\n            }\n        }\n    }\n\n    /**\n     * Save the layer's weights to the output stream\n     * @param os\n     */\n    void save(std::ostream& os) {\n        if constexpr(detail::has_weight_and_delta_v<derived_type>) {\n            auto& w = derived().w;\n            for(size_t i = 0, len = w.size(); i < len; ++i) {\n                os << w.data()[i] << \" \";\n            }\n        }\n        if constexpr(detail::has_bias_and_delta_v<derived_type>) {\n            auto& b = derived().b;\n            for(size_t i = 0, len = b.size(); i < len; ++i) {\n                os << b.data()[i] << \" \";\n            }\n        }\n    }\n\n    /**\n     * CRTP helper\n     */\n    const derived_type& derived() const {\n        return *static_cast<const derived_type*>(this);\n    }\n\n    /**\n     * CRTP helper\n     */\n    derived_type& derived() {\n        return *static_cast<derived_type*>(this);\n    }\n\n    /**\n     * \\brief Returns the output range of a layer\n     */\n    valid_range\n    range() {\n        if constexpr(default_output_range) {\n            return {-1.0f, 1.0f};\n        } else {\n            return derived().range_impl();\n        }\n    }\n\n    /**\n     * The target range of the layer for training purposes\n     * @return\n     */\n    valid_range target_range() {\n        return {0.0f, 1.0f};\n    }\n\n    /**\n     * Whether or not a layer is trainable\n     */\n    bool is_trainable;\n\n    /**\n     * \\brief Temporarily used in combine_grads\n     */\n    tensor_4 wdeltas;\n\n    /**\n     * \\brief Temporarily used in combine_grads\n     */\n    tensor_1 bdeltas;\n\n    /**\n     * \\brief Customization point for controlling weight initialization strategy of this layer\n     */\n    std::function<void(float_t*, float_t*, const size_t&, const size_t&)> weight_initializer;\n    /**\n     * \\brief Customization point for controlling bias initializaiton strategy of this layer\n     */\n    std::function<void(float_t*, float_t*, const size_t&, const size_t&)> bias_initializer;\n};\n\nSP_ALGO_NN_NAMESPACE_END\n\n#endif\t/* SP_ALGO_NN_LAYER_LAYER_HPP */\n\n", "meta": {"hexsha": "c994acc2beb516715f0ca5f2c3ec453ae589b36f", "size": 9499, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/sp/algo/nn/layer/layer.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/layer/layer.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/layer/layer.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": 31.1442622951, "max_line_length": 139, "alphanum_fraction": 0.6086956522, "num_tokens": 2096, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6619228758499941, "lm_q2_score": 0.48047867804790706, "lm_q1q2_score": 0.3180398283580741}}
{"text": "#include <mex.h>\n#include <Eigen/Core>\n#include <chrono>\n#include \"iris/iris.h\"\n\nusing namespace Eigen;\n\n// mxGetPrSafe and eigenToMatlab lovingly ripped off from the Drake toolbox: https://github.com/RobotLocomotion/drake\ndouble * mxGetPrSafe(const mxArray *pobj) {\n  if (!mxIsDouble(pobj)) mexErrMsgIdAndTxt(\"Iris:mxGetPrSafe:WrongType\", \"mxGetPr can only be called on arguments which correspond to Matlab doubles\");\n  return mxGetPr(pobj);\n}\n\nmxArray* eigenToMatlab(const MatrixXd &m)\n{\n  // this avoids zero initialization that would occur using mxCreateDoubleMatrix with nonzero dimensions.\n  // see https://classes.soe.ucsc.edu/ee264/Fall11/cmex.pdf, page 8\n  mxArray* pm = mxCreateDoubleMatrix(0, 0, mxREAL);\n  int rows = static_cast<int>(m.rows());\n  int cols = static_cast<int>(m.cols());\n  int numel = rows * cols;\n  mxSetM(pm, rows);\n  mxSetN(pm, cols);\n  if (numel)\n    mxSetData(pm, mxMalloc(sizeof(double) * numel));\n  memcpy(mxGetPr(pm), m.data(), sizeof(double)* numel);\n  return pm;\n}\n\nvoid mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) {\n  // auto begin = std::chrono::high_resolution_clock::now();\n\n  if (nrhs != 5 || nlhs > 6) {\n    mexErrMsgTxt(\"usage: [A, b, C, d, p_history, e_history] = inflate_regionmex(obstacles, A_bounds, b_bounds, start, options)\");\n  }\n\n  int narg = 0;\n\n  const mxArray* obstacles = prhs[narg];\n  if (!mxIsCell(obstacles)) {\n    mexErrMsgTxt(\"obstacles should be a cell array of matrices\");\n  }\n  narg++;\n\n  Map<MatrixXd> A_bounds(mxGetPrSafe(prhs[narg]), \n                         mxGetM(prhs[narg]),\n                         mxGetN(prhs[narg]));\n  narg++;\n  Map<VectorXd> b_bounds(mxGetPrSafe(prhs[narg]),\n                         mxGetNumberOfElements(prhs[narg]));\n  narg++;\n\n  Map<VectorXd> start(mxGetPrSafe(prhs[narg]),\n                      mxGetNumberOfElements(prhs[narg]));\n  narg++;\n\n  // mexPrintf(\"made maps\\n\");\n\n  const mxArray* options_ptr = prhs[narg];\n\n  const int dim = start.size();\n  if (A_bounds.cols() != dim) {\n    mexPrintf(\"Problem dimension was inferred to be %d from length of [start], so [A_bounds] should have %d columns\\n\", start.size(), A_bounds.cols());\n    mexErrMsgTxt(\"Dimension of problem does not match size of A_bounds\");\n  }\n  if (A_bounds.rows() != b_bounds.size()) {\n    mexErrMsgTxt(\"A_bounds and b_bounds should have the same number of rows\");\n  }\n\n  iris::IRISProblem problem(dim);\n  problem.setSeedPoint(start);\n\n  // mexPrintf(\"set seed\\n\");\n\n  const size_t n_obs = mxGetNumberOfElements(obstacles);\n  for (size_t i=0; i < n_obs; i++) {\n    const mxArray *obs_ptr = mxGetCell(obstacles, i);\n    Map<MatrixXd> obs(mxGetPrSafe(obs_ptr),\n                      mxGetM(obs_ptr),\n                      mxGetN(obs_ptr));\n    if (obs.rows() != dim) {\n      mexErrMsgTxt(\"Each obstacle should be of size M x N where M is the dimension of [start].\");\n    }\n    problem.addObstacle(obs);\n  }\n\n  // mexPrintf(\"added obstacles\\n\");\n\n  iris::IRISOptions options;\n  const mxArray *opt;\n  opt = mxGetField(options_ptr, 0, \"require_containment\");\n  if (opt) options.require_containment = static_cast<bool>(mxGetScalar(opt));\n\n  opt = mxGetField(options_ptr, 0, \"error_on_infeasible_start\");\n  if (opt) options.error_on_infeasible_start = static_cast<bool>(mxGetScalar(opt));\n\n  opt = mxGetField(options_ptr, 0, \"termination_threshold\");\n  if (opt) options.termination_threshold = mxGetScalar(opt);\n\n  opt = mxGetField(options_ptr, 0, \"iter_limit\");\n  if (opt) options.iter_limit = static_cast<int>(mxGetScalar(opt));\n\n  // mexPrintf(\"got options\\n\");\n\n  problem.setBounds(iris::Polyhedron(A_bounds, b_bounds));\n\n  // auto end = std::chrono::high_resolution_clock::now();\n  // auto elapsed = std::chrono::duration_cast<std::chrono::duration<float>>(end - begin);\n  // std::cout << \"pre-solve time: \" << elapsed.count() << \" s\" << std::endl;\n\n  iris::IRISRegion region;\n  std::unique_ptr<iris::IRISDebugData> debug;\n  // begin = std::chrono::high_resolution_clock::now();\n  try {\n    if (nlhs > 4) {\n      debug.reset(new iris::IRISDebugData());\n      region = iris::inflate_region(problem, options, debug.get());\n    } else {\n      region = iris::inflate_region(problem, options);\n    }\n  } catch (iris::InitialPointInfeasibleError &exception) {\n    mexErrMsgIdAndTxt(\"IRIS:InfeasibleStart\", \"Initial point is infeasible\");\n  }\n  // end = std::chrono::high_resolution_clock::now();\n  // elapsed = std::chrono::duration_cast<std::chrono::duration<float>>(end - begin);\n  // std::cout << \"solve time: \" << elapsed.count() << \" s\" << std::endl;\n\n  // begin = std::chrono::high_resolution_clock::now();\n  // mexPrintf(\"ran iris\\n\");\n\n  narg = 0;\n  if (nlhs > narg) plhs[narg] = eigenToMatlab(region.polyhedron.getA());\n  narg++;\n\n  if (nlhs > narg) plhs[narg] = eigenToMatlab(region.polyhedron.getB());\n  narg++;\n\n  if (nlhs > narg) plhs[narg] = eigenToMatlab(region.ellipsoid.getC());\n  narg++;\n\n  if (nlhs > narg) plhs[narg] = eigenToMatlab(region.ellipsoid.getD());\n  narg++;\n\n  if (nlhs > narg) {\n    const size_t n_polys[1] = {debug->polyhedron_history.size()};\n    plhs[narg] = mxCreateCellArray(1, n_polys);\n    for (int i=0; i < debug->polyhedron_history.size(); i++) {\n      const size_t dims[1] = {1};\n      const char* fields[2] = {\"A\", \"b\"};\n      mxArray* entry = mxCreateStructArray(1, dims, 2, fields);\n      mxSetField(entry, 0, \"A\", eigenToMatlab(debug->polyhedron_history[i].getA()));\n      mxSetField(entry, 0, \"b\", eigenToMatlab(debug->polyhedron_history[i].getB()));\n      mxSetCell(plhs[narg], i, entry);\n    }\n  }\n  narg++;\n\n  if (nlhs > narg) {\n    const size_t n_ellipsoids[1] = {debug->ellipsoid_history.size()};\n    plhs[narg] = mxCreateCellArray(1, n_ellipsoids);\n    for (int i=0; i < debug->ellipsoid_history.size(); i++) {\n      const size_t dims[1] = {1};\n      const char* fields[2] = {\"C\", \"d\"};\n      mxArray* entry = mxCreateStructArray(1, dims, 2, fields);\n      mxSetField(entry, 0, \"C\", eigenToMatlab(debug->ellipsoid_history[i].getC()));\n      mxSetField(entry, 0, \"d\", eigenToMatlab(debug->ellipsoid_history[i].getD()));\n      mxSetCell(plhs[narg], i, entry);\n    }\n  }\n  narg++;\n\n  // end = std::chrono::high_resolution_clock::now();\n  // elapsed = std::chrono::duration_cast<std::chrono::duration<float>>(end - begin);\n  // std::cout << \"post-solve time: \" << elapsed.count() << \" s\" << std::endl;\n}\n", "meta": {"hexsha": "eea1c23e188fdfcac4bd08d29e364c9f7ebee98a", "size": 6342, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "iris/matlab/+iris/inflate_regionmex.cpp", "max_stars_repo_name": "openhumanoids/iris-distro", "max_stars_repo_head_hexsha": "bb98593d70dacd388b8b51d224104d996bee0fd9", "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": "iris/matlab/+iris/inflate_regionmex.cpp", "max_issues_repo_name": "openhumanoids/iris-distro", "max_issues_repo_head_hexsha": "bb98593d70dacd388b8b51d224104d996bee0fd9", "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": "iris/matlab/+iris/inflate_regionmex.cpp", "max_forks_repo_name": "openhumanoids/iris-distro", "max_forks_repo_head_hexsha": "bb98593d70dacd388b8b51d224104d996bee0fd9", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.0340909091, "max_line_length": 151, "alphanum_fraction": 0.6543677073, "num_tokens": 1830, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6619228758499941, "lm_q2_score": 0.48047867804790706, "lm_q1q2_score": 0.3180398283580741}}
{"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/scene.h>\n#include <mitsuba/core/statistics.h>\n#include <boost/math/distributions/normal.hpp>\n\nMTS_NAMESPACE_BEGIN\n\n/*!\\plugin{adaptive}{Adaptive integrator}\n * \\order{13}\n * \\parameters{\n *     \\parameter{maxError}{\\Float}{Maximum relative error\n *         threshold\\default{0.05}}\n *     \\parameter{pValue}{\\Float}{\n *         Required p-value to accept a sample \\default{0.05}\n *     }\n *     \\parameter{maxSampleFactor}{\\Integer}{\n *         Maximum number of samples to be generated \\emph{relative} to the\n *         number of configured pixel samples. The adaptive integrator\n *         will stop after this many samples, regardless of whether\n *         or not the error criterion was satisfied.\n *         A negative value will be interpreted as $\\infty$.\n *         \\default{32---for instance, when 64 pixel samples are configured in\n *         the \\code{sampler}, this means that the adaptive integrator\n *         will give up after 32*64=2048 samples}\n *     }\n * }\n *\n * This ``meta-integrator'' repeatedly invokes a provided sub-integrator\n * until the computed radiance values satisfy a specified relative error bound\n * (5% by default) with a certain probability (95% by default). Internally,\n * it uses a Z-test to decide when to stop collecting samples. While repeatedly\n * applying a Z-test in this manner is not good practice in terms of\n * a rigorous statistical analysis, it provides a useful mathematically\n * motivated stopping criterion.\n *\n * \\begin{xml}[caption={An example how to make the \\pluginref{path} integrator adaptive}]\n * <integrator type=\"adaptive\">\n *     <integrator type=\"path\"/>\n * </integrator>\n * \\end{xml}\n *\n * \\remarks{\n *    \\item The adaptive integrator needs a variance estimate to work\n *     correctly. Hence, the underlying sample generator should be set to a reasonably\n *     large number of pixel samples (e.g. 64 or higher) so that this estimate can be obtained.\n *    \\item This plugin uses a relatively simplistic error heuristic that does not\n *    share information between pixels and only reasons about variance in image space.\n *    In the future, it will likely be replaced with something more robust.\n * }\n */\nclass AdaptiveIntegrator : public SamplingIntegrator {\npublic:\n\tAdaptiveIntegrator(const Properties &props) : SamplingIntegrator(props) {\n\t\t/* Maximum relative error threshold */\n\t\tm_maxError = props.getFloat(\"maxError\", 0.05f);\n\t\t/* Maximum number of samples to take (relative to the number of pixel samples\n\t\t   that were configured in the sampler). The sample collection\n\t\t   will stop after this many samples even if the variance is still\n\t\t   too high. A negative value will be interpreted as infinity. */\n\t\tm_maxSampleFactor = props.getInteger(\"maxSampleFactor\", 32);\n\t\t/* Required P-value to accept a sample. */\n\t\tm_pValue = props.getFloat(\"pValue\", 0.05f);\n\t\tm_verbose = props.getBoolean(\"verbose\", false);\n\t}\n\n\tAdaptiveIntegrator(Stream *stream, InstanceManager *manager)\n\t : SamplingIntegrator(stream, manager) {\n\t\tm_subIntegrator = static_cast<SamplingIntegrator *>(manager->getInstance(stream));\n\t\tm_maxSampleFactor = stream->readInt();\n\t\tm_maxError = stream->readFloat();\n\t\tm_quantile = stream->readFloat();\n\t\tm_averageLuminance = stream->readFloat();\n\t\tm_pValue = stream->readFloat();\n\t\tm_verbose = false;\n\t}\n\n\tvoid addChild(const std::string &name, ConfigurableObject *child) {\n\t\tconst Class *cClass = child->getClass();\n\n\t\tif (cClass->derivesFrom(MTS_CLASS(Integrator))) {\n\t\t\tif (!cClass->derivesFrom(MTS_CLASS(SamplingIntegrator)))\n\t\t\t\tLog(EError, \"The sub-integrator must be derived from the class SamplingIntegrator\");\n\t\t\tm_subIntegrator = static_cast<SamplingIntegrator *>(child);\n\t\t} else {\n\t\t\tIntegrator::addChild(name, child);\n\t\t}\n\t}\n\n\tvoid configureSampler(const Scene *scene, Sampler *sampler) {\n\t\tSamplingIntegrator::configureSampler(scene, sampler);\n\t\tm_subIntegrator->configureSampler(scene, sampler);\n\t}\n\n\tbool preprocess(const Scene *scene, RenderQueue *queue, const RenderJob *job,\n\t\t\tint sceneResID, int sensorResID, int samplerResID) {\n\t\tif (!SamplingIntegrator::preprocess(scene, queue, job, sceneResID, sensorResID, samplerResID))\n\t\t\treturn false;\n\t\tif (m_subIntegrator == NULL)\n\t\t\tLog(EError, \"No sub-integrator was specified!\");\n\t\tSampler *sampler = static_cast<Sampler *>(Scheduler::getInstance()->getResource(samplerResID, 0));\n\t\tSensor *sensor = static_cast<Sensor *>(Scheduler::getInstance()->getResource(sensorResID));\n\t\tif (sampler->getClass()->getName() != \"IndependentSampler\")\n\t\t\tLog(EError, \"The error-controlling integrator should only be \"\n\t\t\t\t\"used in conjunction with the independent sampler\");\n\t\tif (!m_subIntegrator->preprocess(scene, queue, job, sceneResID, sensorResID, samplerResID))\n\t\t\treturn false;\n\n\t\tVector2i filmSize = sensor->getFilm()->getSize();\n\t\tbool needsApertureSample = sensor->needsApertureSample();\n\t\tbool needsTimeSample = sensor->needsTimeSample();\n\t\tconst int nSamples = 10000;\n\t\tFloat luminance = 0;\n\n\t\tPoint2 apertureSample(0.5f);\n\t\tFloat timeSample = 0.5f;\n\t\tRadianceQueryRecord rRec(scene, sampler);\n\n\t\t/* Estimate the overall luminance on the image plane */\n\t\tfor (int i=0; i<nSamples; ++i) {\n\t\t\tsampler->generate(Point2i(0));\n\n\t\t\trRec.newQuery(RadianceQueryRecord::ERadiance, sensor->getMedium());\n\t\t\trRec.extra = RadianceQueryRecord::EAdaptiveQuery;\n\n\t\t\tPoint2 samplePos(rRec.nextSample2D());\n\t\t\tsamplePos.x *= filmSize.x;\n\t\t\tsamplePos.y *= filmSize.y;\n\n\t\t\tif (needsApertureSample)\n\t\t\t\tapertureSample = rRec.nextSample2D();\n\t\t\tif (needsTimeSample)\n\t\t\t\ttimeSample = rRec.nextSample1D();\n\n\t\t\tRayDifferential eyeRay;\n\t\t\tSpectrum sampleValue = sensor->sampleRay(\n\t\t\t\teyeRay, samplePos, apertureSample, timeSample);\n\n\t\t\tsampleValue *= m_subIntegrator->Li(eyeRay, rRec);\n\t\t\tluminance += sampleValue.getLuminance();\n\t\t}\n\n\t\tm_averageLuminance = luminance / nSamples;\n\n\t\tboost::math::normal dist(0, 1);\n\t\tm_quantile = (Float) boost::math::quantile(dist, 1-m_pValue/2);\n\t\tLog(EInfo, \"Configuring for a %.1f%% confidence interval, quantile=%f, avg. luminance=%f\",\n\t\t\t(1-m_pValue)*100, m_quantile, m_averageLuminance);\n\t\treturn true;\n\t}\n\n\tvoid renderBlock(const Scene *scene, const Sensor *sensor,\n\t\t\tSampler *sampler, ImageBlock *block, const bool &stop,\n\t\t\tconst std::vector< TPoint2<uint8_t> > &points) const {\n\t\ttypedef TSpectrum<Float, SPECTRUM_SAMPLES + 2> SpectrumAlphaWeight;\n\n\t\tbool needsApertureSample = sensor->needsApertureSample();\n\t\tbool needsTimeSample = sensor->needsTimeSample();\n\n\t\tif (sampler->getSampleCount() < 8)\n\t\t\tLog(EError, \"Starting the adaptive integrator with less than 8 \"\n\t\t\t\t\"samples per pixel does not make much sense -- giving up.\");\n\n\t\tRayDifferential eyeRay;\n\t\tRadianceQueryRecord rRec(scene, sampler);\n\n\t\tFloat diffScaleFactor = 1.0f /\n\t\t\tstd::sqrt((Float) sampler->getSampleCount());\n\n\t\tPoint2 apertureSample(0.5f);\n\t\tFloat timeSample = 0.5f;\n\t\tint borderSize = sensor->getFilm()->getReconstructionFilter()->getBorderSize();\n\n\t\tsize_t sampleCount;\n\t\tblock->clear();\n\n\t\tSpectrumAlphaWeight *target = (SpectrumAlphaWeight *) block->getBitmap()->getUInt8Data();\n\t\tSpectrumAlphaWeight *snapshot = (SpectrumAlphaWeight *) alloca(sizeof(SpectrumAlphaWeight)\n\t\t\t* (2*borderSize+1)*(2*borderSize+1));\n\n\t\tfor (size_t i=0; i<points.size(); ++i) {\n\t\t\tPoint2i offset = Point2i(points[i]) + Vector2i(block->getOffset());\n\t\t\tsampler->generate(offset);\n\n\t\t\t/* Before starting to place samples within the area of a single pixel, the\n\t\t\t   following takes a snapshot of all surrounding spectrum+weight+alpha\n\t\t\t   values. Those are then used later to ensure that adjacent pixels will\n\t\t\t   not be disproportionately biased by this pixel's contributions. */\n\t\t\tfor (int y=0; y<2*borderSize+1; ++y) {\n\t\t\t\tSpectrumAlphaWeight *src = target + ((y+points[i].y)\n\t\t\t\t\t* block->getBitmap()->getWidth() + points[i].x);\n\t\t\t\tSpectrumAlphaWeight *dst = snapshot + y*(2*borderSize+1);\n\t\t\t\tmemcpy(dst, src, sizeof(SpectrumAlphaWeight) * (2*borderSize+1));\n\t\t\t}\n\n\t\t\tFloat mean = 0, meanSqr = 0.0f;\n\t\t\tsampleCount = 0;\n\n\t\t\twhile (true) {\n\t\t\t\tif (stop)\n\t\t\t\t\treturn;\n\n\t\t\t\trRec.newQuery(RadianceQueryRecord::ESensorRay, sensor->getMedium());\n\t\t\t\trRec.extra = RadianceQueryRecord::EAdaptiveQuery;\n\n\t\t\t\tPoint2 samplePos(Point2(offset) + Vector2(rRec.nextSample2D()));\n\t\t\t\tif (needsApertureSample)\n\t\t\t\t\tapertureSample = rRec.nextSample2D();\n\t\t\t\tif (needsTimeSample)\n\t\t\t\t\ttimeSample = rRec.nextSample1D();\n\n\t\t\t\tSpectrum sampleValue = sensor->sampleRayDifferential(\n\t\t\t\t\teyeRay, samplePos, apertureSample, timeSample);\n\t\t\t\teyeRay.scaleDifferential(diffScaleFactor);\n\n\t\t\t\tsampleValue *= m_subIntegrator->Li(eyeRay, rRec);\n\n\t\t\t\tFloat sampleLuminance;\n\t\t\t\tif (block->put(samplePos, sampleValue, rRec.alpha)) {\n\t\t\t\t\t/* Check for problems with the sample */\n\t\t\t\t\tsampleLuminance = sampleValue.getLuminance();\n\t\t\t\t} else {\n\t\t\t\t\tsampleLuminance = 0.0f;\n\t\t\t\t}\n\t\t\t\t++sampleCount;\n\t\t\t\tsampler->advance();\n\n\t\t\t\t/* Numerically robust online variance estimation using an\n\t\t\t\t   algorithm proposed by Donald Knuth (TAOCP vol.2, 3rd ed., p.232) */\n\t\t\t\tconst Float delta = sampleLuminance - mean;\n\t\t\t\tmean += delta / sampleCount;\n\t\t\t\tmeanSqr += delta * (sampleLuminance - mean);\n\n\t\t\t\tif (m_maxSampleFactor >= 0 && sampleCount >= m_maxSampleFactor * sampler->getSampleCount()) {\n\t\t\t\t\tbreak;\n\t\t\t\t} else if (sampleCount >= sampler->getSampleCount()) {\n\t\t\t\t\t/* Variance of the primary estimator */\n\t\t\t\t\tconst Float variance = meanSqr / (sampleCount-1);\n\n\t\t\t\t\tFloat stdError = std::sqrt(variance/sampleCount);\n\n\t\t\t\t\t/* Half width of the confidence interval */\n\t\t\t\t\tFloat ciWidth = stdError * m_quantile;\n\n\t\t\t\t\t/* Relative error heuristic */\n\t\t\t\t\tFloat base = std::max(mean, m_averageLuminance * 0.01f);\n\n\t\t\t\t\tif (m_verbose && (sampleCount % 100) == 0)\n\t\t\t\t\t\tLog(EDebug, \"%i samples, mean=%f, stddev=%f, std error=%f, ci width=%f, max allowed=%f\", sampleCount, mean,\n\t\t\t\t\t\t\tstd::sqrt(variance), stdError, ciWidth, base * m_maxError);\n\n\t\t\t\t\tif (ciWidth <= m_maxError * base)\n\t\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t/* Ensure that a large amounts of samples in one pixel do not\n\t\t\t   bias neighboring pixels (due to the reconstruction filter) */\n\t\t\tFloat factor = 1.0f / sampleCount;\n\t\t\tfor (int y=0; y<2*borderSize+1; ++y) {\n\t\t\t\tSpectrumAlphaWeight *dst = target + ((y+points[i].y)\n\t\t\t\t\t* block->getBitmap()->getWidth() + points[i].x);\n\t\t\t\tSpectrumAlphaWeight *backup = snapshot + y*(2*borderSize+1);\n\n\t\t\t\tfor (int x=0; x<2*borderSize+1; ++x)\n\t\t\t\t\tdst[x] = backup[x] * (1-factor) + dst[x] * factor;\n\t\t\t}\n\t\t}\n\t}\n\n\tSpectrum Li(const RayDifferential &ray, RadianceQueryRecord &rRec) const {\n\t\treturn m_subIntegrator->Li(ray, rRec);\n\t}\n\n\tSpectrum E(const Scene *scene, const Intersection &its, const Medium *medium,\n\t\t\tSampler *sampler, int nSamples, bool includeIndirect) const {\n\t\treturn m_subIntegrator->E(scene, its, medium,\n\t\t\tsampler, nSamples, includeIndirect);\n\t}\n\n\tvoid serialize(Stream *stream, InstanceManager *manager) const {\n\t\tSamplingIntegrator::serialize(stream, manager);\n\t\tmanager->serialize(stream, m_subIntegrator.get());\n\n\t\tstream->writeInt(m_maxSampleFactor);\n\t\tstream->writeFloat(m_maxError);\n\t\tstream->writeFloat(m_quantile);\n\t\tstream->writeFloat(m_averageLuminance);\n\t\tstream->writeFloat(m_pValue);\n\t}\n\n\tvoid bindUsedResources(ParallelProcess *proc) const {\n\t\tm_subIntegrator->bindUsedResources(proc);\n\t}\n\n\tvoid wakeup(ConfigurableObject *parent,\n\t\t\tstd::map<std::string, SerializableObject *> &params) {\n\t\tm_subIntegrator->wakeup(this, params);\n\t}\n\n\tvoid cancel() {\n\t\tSamplingIntegrator::cancel();\n\t\tm_subIntegrator->cancel();\n\t}\n\n\tconst Integrator *getSubIntegrator(int idx) const {\n\t\tif (idx != 0)\n\t\t\treturn NULL;\n\t\treturn m_subIntegrator.get();\n\t}\n\n\tstd::string toString() const {\n\t\tstd::ostringstream oss;\n\t\toss << \"AdaptiveIntegrator[\" << endl\n\t\t\t<< \"  maxSamples = \" << m_maxSampleFactor << \",\" << endl\n\t\t\t<< \"  maxError = \" << m_maxError << \",\" << endl\n\t\t\t<< \"  quantile = \" << m_quantile << \",\" << endl\n\t\t\t<< \"  pvalue = \" << m_pValue << \",\" << endl\n\t\t\t<< \"  subIntegrator = \" << indent(m_subIntegrator->toString()) << endl\n\t\t\t<< \"]\";\n\t\treturn oss.str();\n\t}\n\n\tMTS_DECLARE_CLASS()\nprivate:\n\tref<SamplingIntegrator> m_subIntegrator;\n\tFloat m_maxError, m_quantile, m_pValue, m_averageLuminance;\n\tint m_maxSampleFactor;\n\tbool m_verbose;\n};\n\nMTS_IMPLEMENT_CLASS_S(AdaptiveIntegrator, false, SamplingIntegrator)\nMTS_EXPORT_PLUGIN(AdaptiveIntegrator, \"Adaptive integrator\");\nMTS_NAMESPACE_END\n", "meta": {"hexsha": "502c4e1d00d8f3f88fe72721b0bc808705da31c7", "size": 13056, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "mitsuba-af602c6fd98a/src/integrators/misc/adaptive.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/integrators/misc/adaptive.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/integrators/misc/adaptive.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": 37.1965811966, "max_line_length": 113, "alphanum_fraction": 0.7059589461, "num_tokens": 3480, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6619228758499942, "lm_q2_score": 0.480478678047907, "lm_q1q2_score": 0.3180398283580741}}
{"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// INCLUDES ===================================================================>\n\n// Including Standard Libraries\n#include <cstdlib>\n#include <cassert>\n#include <cstring>\n#include <fstream>\n#include <iostream>\n#include <vector>\n#include <string>\n#include <algorithm>\n#include <limits>\n#include <cmath>\n\n#include <boost/program_options.hpp>\n\n\n#include <distributed_graphlab.hpp>\n\n#include \"image.hpp\"\n\n\n// Include the macro for the for each operation\n#include <graphlab/macros_def.hpp>\n\n\n\n\n// STRUCTS (Edge and Vertex data) =============================================>\n\n/**\n * unused\n */\ntypedef char edge_data;\n\n\n/**\n * The data associated with each variable in the pairwise markov\n * random field\n */\nstruct vertex_data {\n  size_t sample;  \n  graphlab::unary_factor unary;\n  void save(graphlab::oarchive &oarc) const {\n    oarc << unary << sample;\n  }\n  \n  void load(graphlab::iarchive &iarc) {\n    iarc >> unary >> sample;\n  }\n}; // End of vertex data\n\n\ntypedef graphlab::distributed_graph<vertex_data, edge_data> graph_type;\ntypedef graphlab::distributed_types<graph_type> gl_types;\n\ngl_types::distributed_glshared<graphlab::binary_factor> EDGE_FACTOR;\n\n\n// GraphLab Update Function ===================================================>\n\n/** Construct denoising ising model based on the image */\nvoid construct_graph(image& img,\n                     size_t num_rings,\n                     double sigma,\n                     gl_types::memory_graph& distributed_graph);\n\n/** \n * The core gibbs update function.  This update satisfies\n * the graphlab update_function interface.  \n */\nvoid gibbs_update(gl_types::iscope& scope, \n                  gl_types::icallback& scheduler);\n               \n\n\n// MAIN =======================================================================>\nint main(int argc, char** argv) {\n  std::cout << \"This program creates and denoises a synthetic \" << std::endl\n            << \"image using gibbs sampling inside \" << std::endl\n            << \"the graphlab framework.\" << std::endl;\n\n  // set the global logger\n  global_logger().set_log_level(LOG_DEBUG);\n  global_logger().set_log_to_console(true);\n\n  bool makegraph = false;\n  size_t colors = 5;\n  size_t rows = 200;\n  size_t cols = 200;\n  double sigma = 1;\n  double lambda = 2;\n  std::string smoothing = \"square\";\n  std::string orig_fn = \"source_img.pgm\";\n  std::string noisy_fn = \"noisy_img.pgm\";\n  std::string pred_fn = \"pred_img.pgm\";\n\n\n\n\n  // Parse command line arguments --------------------------------------------->\n  graphlab::command_line_options clopts(\"Loopy BP image denoising\");\n  clopts.use_distributed_options();\n  clopts.attach_option(\"makegraph\",\n                       &makegraph, makegraph,\n                       \"Creates the disk distributed_graph\");\n  clopts.attach_option(\"colors\",\n                       &colors, colors,\n                       \"The number of colors in the noisy image\");\n  clopts.attach_option(\"rows\",\n                       &rows, rows,\n                       \"The number of rows in the noisy image\");\n  clopts.attach_option(\"cols\",\n                       &cols, cols,\n                       \"The number of columns in the noisy image\");\n  clopts.attach_option(\"sigma\",\n                       &sigma, sigma,\n                       \"Standard deviation of noise.\");\n  clopts.attach_option(\"lambda\",\n                       &lambda, lambda,\n                       \"Smoothness parameter (larger => smoother).\");\n  clopts.attach_option(\"smoothing\",\n                       &smoothing, smoothing,\n                       \"Options are {square, laplace}\");\n  clopts.attach_option(\"orig\",\n                       &orig_fn, orig_fn,\n                       \"Original image file name.\");\n  clopts.attach_option(\"noisy\",\n                       &noisy_fn, noisy_fn,\n                       \"Noisy image file name.\");\n  clopts.attach_option(\"pred\",\n                       &pred_fn, pred_fn,\n                       \"Predicted image file name.\");\n  \n\n  clopts.set_scheduler_type(\"multiqueue_fifo\");\n  clopts.set_scope_type(\"edge\");\n  \n\n  bool success = clopts.parse(argc, argv);\n  if(!success) {    \n    return EXIT_FAILURE;\n  }\n\n\n  \n  std::cout << \"ncpus:          \" << clopts.get_ncpus() << std::endl\n            << \"colors:         \" << colors << std::endl\n            << \"rows:           \" << rows << std::endl\n            << \"cols:           \" << cols << std::endl\n            << \"sigma:          \" << sigma << std::endl\n            << \"lambda:         \" << lambda << std::endl\n            << \"smoothing:      \" << smoothing << std::endl\n            << \"engine:         \" << clopts.get_engine_type() << std::endl\n            << \"scope:          \" << clopts.get_scope_type() << std::endl\n            << \"scheduler:      \" << clopts.get_scheduler_type() << std::endl\n            << \"orig_fn:        \" << orig_fn << std::endl\n            << \"noisy_fn:       \" << noisy_fn << std::endl\n            << \"pred_fn:        \" << pred_fn << std::endl;\n\n  \n\n  std::cout << \"Creating a synthetic image. \" << std::endl;\n  image img(rows, cols);\n  img.paint_sunset(colors);\n  std::cout << \"Saving image. \" << std::endl;\n  img.save(orig_fn.c_str());\n  std::cout << \"Corrupting Image. \" << std::endl;\n  img.corrupt(sigma);\n\n  if (makegraph) {\n    // Create synthetic images -------------------------------------------------->\n    // Creating image for denoising\n    std::cout << \"Saving corrupted image. \" << std::endl;\n    img.save(noisy_fn.c_str());\n    \n    std::cout << \"Constructing pairwise Markov Random Field. \" << std::endl;\n    gl_types::disk_graph dg(\"denoise\", 64);\n    gl_types::memory_graph g;\n\n    construct_graph(img, colors, sigma, g);\n    std::vector<graphlab::graph_partitioner::part_id_type> parts;\n    graphlab::graph_partitioner::metis_partition(g, 64, parts);\n    dg.create_from_graph(g, parts);\n    dg.finalize();\n    dg.make_memory_atoms();\n    return 0;\n  }\n\n  graphlab::mpi_tools::init(argc, argv);\n  \n  graphlab::dc_init_param param;\n  ASSERT_TRUE(graphlab::init_param_from_mpi(param));\n  // create distributed control\n  graphlab::distributed_control dc(param);\n  // Create the distributed_graph --------------------------------------------------------->\n  gl_types::distributed_core core(dc, \"denoise.idx\");\n  // Set the engine options\n  core.set_engine_options(clopts);\n  core.build_engine();\n\n  \n  // Setup global shared variables -------------------------------------------->\n  // Initialize the edge agreement factor \n  std::cout << \"Initializing shared edge agreement factor. \" << std::endl;\n\n  // dummy variables 0 and 1 and num_rings by num_rings\n  graphlab::binary_factor edge_potential(0, colors, 0, colors);\n  // Set the smoothing type\n  if(smoothing == \"square\") {\n    edge_potential.set_as_agreement(lambda);\n  } else if (smoothing == \"laplace\") {\n    edge_potential.set_as_laplace(lambda);\n  } else {\n    std::cout << \"Invalid smoothing stype!\" << std::endl;\n    return EXIT_FAILURE;\n  }\n  std::cout << edge_potential << std::endl;\n  \n  EDGE_FACTOR.set(edge_potential);\n  \n\n\n  // Running the engine ------------------------------------------------------->\n  core.sched_options().add_option(\"update_function\",gibbs_update);\n\n  std::cout << \"Running the engine. \" << std::endl;\n\n  \n  // Add the bp update to all vertices\n  core.add_task_to_all(gibbs_update, 100.0);\n  // Starte the engine\n  double runtime = core.start();\n  std::vector<vertex_data> all_vdata = core.graph().collect_vertices(0);\n  if (dc.procid() == 0) {\n    size_t update_count = core.last_update_count();\n    std::cout << \"Finished Running engine in \" << runtime \n              << \" seconds.\" << std::endl\n              << \"Total updates: \" << update_count << std::endl\n              << \"Efficiency: \" << (double(update_count) / runtime)\n              << \" updates per second \"\n              << std::endl;  \n\n\n    // Saving the output -------------------------------------------------------->\n    std::cout << \"Rendering the cleaned image. \" << std::endl;\n    for(size_t v = 0; v < all_vdata.size(); ++v) {\n      const vertex_data& vdata = all_vdata[v];\n      img.pixel(v) = vdata.sample;\n    }\n    std::cout << \"Saving cleaned image. \" << std::endl;\n    img.save(pred_fn.c_str());\n\n    std::cout << \"Done!\" << std::endl;\n  }\n  graphlab::mpi_tools::finalize();\n  return EXIT_SUCCESS;\n} // End of main\n\n\n\n\n// Implementations\n// ============================================================>\nvoid gibbs_update(gl_types::iscope& scope, \n               gl_types::icallback& scheduler) {\n\n  // Grab the state from the scope\n  // ---------------------------------------------------------------->\n  // Get the vertex data\n  vertex_data& v_data = scope.vertex_data();\n  \n  // Get the in and out edges by reference\n  gl_types::edge_list in_edges = scope.in_edge_ids();\n \n  graphlab::unary_factor u = v_data.unary;\n  graphlab::binary_factor efactor = EDGE_FACTOR.get_val();\n  \n  foreach(graphlab::edge_id_t ineid, in_edges) {   \n    size_t target_val = scope.const_neighbor_vertex_data(scope.source(ineid)).sample;\n    for (size_t i = 0;i < u.arity(); ++i) {\n      u.logP(i) += efactor.logP(target_val, i);\n    }\n  }\n  u.normalize();\n  v_data.sample = u.sample();\n} \n\n\nvoid construct_graph(image& img,\n                     size_t num_rings,\n                     double sigma,\n                     gl_types::memory_graph& distributed_graph) {\n  // Construct a single blob for the vertex data\n  vertex_data vdata;\n  vdata.unary.resize(num_rings);\n  // Add all the vertices\n  double sigmaSq = sigma*sigma;\n  for(size_t i = 0; i < img.rows(); ++i) {\n    for(size_t j = 0; j < img.cols(); ++j) {\n      // Set the node potential\n      double obs = img.pixel(i, j);\n      for(size_t pred = 0; pred < num_rings; ++pred) {\n        vdata.unary.logP(pred) = \n          -(obs - pred)*(obs - pred) / (2.0 * sigmaSq);\n      }\n      vdata.unary.normalize();\n      vdata.sample = graphlab::random::uniform<uint32_t>(0, num_rings - 1);\n      // Store the actual data in the distributed_graph\n      size_t vertid = distributed_graph.add_vertex(vdata);\n      // Ensure that we are using a consistent numbering\n      assert(vertid == img.vertid(i, j));\n    } // end of for j in cols\n  } // end of for i in rows\n\n  // Add the edges\n \n  for(size_t i = 0; i < img.rows(); ++i) {\n    for(size_t j = 0; j < img.cols(); ++j) {\n      size_t vertid = img.vertid(i,j);\n      if(i-1 < img.rows()) {\n        distributed_graph.add_edge(vertid, img.vertid(i-1, j), edge_data());\n      }\n      if(i+1 < img.rows()) {\n        distributed_graph.add_edge(vertid, img.vertid(i+1, j), edge_data());\n      }\n      if(j-1 < img.cols()) {\n        distributed_graph.add_edge(vertid, img.vertid(i, j-1), edge_data());\n      } if(j+1 < img.cols()) {\n        distributed_graph.add_edge(vertid, img.vertid(i, j+1), edge_data());\n      }\n    } // end of for j in cols\n  } // end of for i in rows\n  distributed_graph.compute_coloring();\n  distributed_graph.finalize();  \n} // End of construct distributed_graph\n\n\n", "meta": {"hexsha": "4bcd71a6b94bd704a512eccd318040929ddc6212", "size": 11693, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "demoapps/dist_image_gibbs/dist_image_gibbs.cpp", "max_stars_repo_name": "iivek/graphlab-cmu-mirror", "max_stars_repo_head_hexsha": "028321757ea979e6a0859687e37933be375153eb", "max_stars_repo_licenses": ["ECL-2.0", "Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-08-01T06:32:58.000Z", "max_stars_repo_stars_event_max_datetime": "2018-08-01T06:32:58.000Z", "max_issues_repo_path": "demoapps/dist_image_gibbs/dist_image_gibbs.cpp", "max_issues_repo_name": "iivek/graphlab-cmu-mirror", "max_issues_repo_head_hexsha": "028321757ea979e6a0859687e37933be375153eb", "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": "demoapps/dist_image_gibbs/dist_image_gibbs.cpp", "max_forks_repo_name": "iivek/graphlab-cmu-mirror", "max_forks_repo_head_hexsha": "028321757ea979e6a0859687e37933be375153eb", "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": 32.3011049724, "max_line_length": 92, "alphanum_fraction": 0.5728213461, "num_tokens": 2792, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5774953651858118, "lm_q2_score": 0.5506073655352404, "lm_q1q2_score": 0.3179732016337714}}
{"text": "// g2o - General Graph Optimization\r\n// Copyright (C) 2012 R. Kümmerle\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/Core>\r\n#include <Eigen/StdVector>\r\n#include <Eigen/Geometry>\r\n#include <iostream>\r\n\r\n#include \"g2o/stuff/command_args.h\"\r\n#include \"g2o/core/batch_stats.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/optimization_algorithm_levenberg.h\"\r\n#include \"g2o/core/base_vertex.h\"\r\n#include \"g2o/core/base_binary_edge.h\"\r\n#include \"g2o/solvers/dense/linear_solver_dense.h\"\r\n#include \"g2o/solvers/structure_only/structure_only_solver.h\"\r\n#include \"g2o/solvers/pcg/linear_solver_pcg.h\"\r\n\r\n#include \"EXTERNAL/ceres/autodiff.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 g2o;\r\nusing namespace std;\r\nusing namespace Eigen;\r\n\r\n/**\r\n * \\brief camera vertex which stores the parameters for a pinhole camera\r\n *\r\n * The parameters of the camera are \r\n * - rx,ry,rz representing the rotation axis, whereas the angle is given by ||(rx,ry,rz)||\r\n * - tx,ty,tz the translation of the camera\r\n * - f the focal length of the camera\r\n * - k1, k2 two radial distortion parameters\r\n */\r\nclass VertexCameraBAL : public BaseVertex<9, Eigen::VectorXd>\r\n{\r\n  public:\r\n    EIGEN_MAKE_ALIGNED_OPERATOR_NEW;\r\n    VertexCameraBAL()\r\n    {\r\n    }\r\n\r\n    virtual bool read(std::istream& /*is*/)\r\n    {\r\n      cerr << __PRETTY_FUNCTION__ << \" not implemented yet\" << endl;\r\n      return false;\r\n    }\r\n\r\n    virtual bool write(std::ostream& /*os*/) const\r\n    {\r\n      cerr << __PRETTY_FUNCTION__ << \" not implemented yet\" << endl;\r\n      return false;\r\n    }\r\n\r\n    virtual void setToOriginImpl()\r\n    {\r\n      cerr << __PRETTY_FUNCTION__ << \" not implemented yet\" << endl;\r\n    }\r\n\r\n    virtual void oplusImpl(const double* update)\r\n    {\r\n      Eigen::VectorXd::ConstMapType v(update, VertexCameraBAL::Dimension);\r\n      _estimate += v;\r\n    }\r\n};\r\n\r\n/**\r\n * \\brief 3D world feature\r\n *\r\n * A 3D point feature in the world\r\n */\r\nclass VertexPointBAL : public BaseVertex<3, Eigen::Vector3d>\r\n{\r\n  public:\r\n    EIGEN_MAKE_ALIGNED_OPERATOR_NEW;\r\n    VertexPointBAL()\r\n    {\r\n    }\r\n\r\n    virtual bool read(std::istream& /*is*/)\r\n    {\r\n      cerr << __PRETTY_FUNCTION__ << \" not implemented yet\" << endl;\r\n      return false;\r\n    }\r\n\r\n    virtual bool write(std::ostream& /*os*/) const\r\n    {\r\n      cerr << __PRETTY_FUNCTION__ << \" not implemented yet\" << endl;\r\n      return false;\r\n    }\r\n\r\n    virtual void setToOriginImpl()\r\n    {\r\n      cerr << __PRETTY_FUNCTION__ << \" not implemented yet\" << endl;\r\n    }\r\n\r\n    virtual void oplusImpl(const double* update)\r\n    {\r\n      Eigen::Vector3d::ConstMapType v(update);\r\n      _estimate += v;\r\n    }\r\n};\r\n\r\n/**\r\n * \\brief edge representing the observation of a world feature by a camera\r\n *\r\n * see: http://grail.cs.washington.edu/projects/bal/\r\n * We use a pinhole camera model; the parameters we estimate for each camera\r\n * area rotation R, a translation t, a focal length f and two radial distortion\r\n * parameters k1 and k2. The formula for projecting a 3D point X into a camera\r\n * R,t,f,k1,k2 is:\r\n * P  =  R * X + t       (conversion from world to camera coordinates)\r\n * p  = -P / P.z         (perspective division)\r\n * p' =  f * r(p) * p    (conversion to pixel coordinates) where P.z is the third (z) coordinate of P.\r\n *\r\n * In the last equation, r(p) is a function that computes a scaling factor to undo the radial\r\n * distortion:\r\n * r(p) = 1.0 + k1 * ||p||^2 + k2 * ||p||^4. \r\n *\r\n * This gives a projection in pixels, where the origin of the image is the\r\n * center of the image, the positive x-axis points right, and the positive\r\n * y-axis points up (in addition, in the camera coordinate system, the positive\r\n * z-axis points backwards, so the camera is looking down the negative z-axis,\r\n * as in OpenGL).\r\n */\r\nclass EdgeObservationBAL : public BaseBinaryEdge<2, Vector2d, VertexCameraBAL, VertexPointBAL>\r\n{\r\n  public:\r\n    EIGEN_MAKE_ALIGNED_OPERATOR_NEW;\r\n    EdgeObservationBAL()\r\n    {\r\n    }\r\n    virtual bool read(std::istream& /*is*/)\r\n    {\r\n      cerr << __PRETTY_FUNCTION__ << \" not implemented yet\" << endl;\r\n      return false;\r\n    }\r\n    virtual bool write(std::ostream& /*os*/) const\r\n    {\r\n      cerr << __PRETTY_FUNCTION__ << \" not implemented yet\" << endl;\r\n      return false;\r\n    }\r\n\r\n    template<typename T>\r\n    inline void cross(const T x[3], const T y[3], T result[3]) const\r\n    {\r\n      result[0] = x[1] * y[2] - x[2] * y[1];\r\n      result[1] = x[2] * y[0] - x[0] * y[2];\r\n      result[2] = x[0] * y[1] - x[1] * y[0];\r\n    }\r\n\r\n    template<typename T>\r\n    inline T dot(const T x[3], const T y[3]) const { return (x[0] * y[0] + x[1] * y[1] + x[2] * y[2]);}\r\n\r\n    template<typename T>\r\n    inline T squaredNorm(const T x[3]) const { return dot<T>(x, x);}\r\n\r\n    /**\r\n     * templatized function to compute the error as described in the comment above\r\n     */\r\n    template<typename T>\r\n    bool operator()(const T* camera, const T* point, T* error) const\r\n    {\r\n      // Rodrigues' formula for the rotation\r\n      T p[3];\r\n      T theta = sqrt(squaredNorm(camera));\r\n      if (theta > T(0)) {\r\n        T v[3];\r\n        v[0] = camera[0] / theta;\r\n        v[1] = camera[1] / theta;\r\n        v[2] = camera[2] / theta;\r\n        T cth = cos(theta);\r\n        T sth = sin(theta);\r\n\r\n        T vXp[3];\r\n        cross(v, point, vXp);\r\n        T vDotp = dot(v, point);\r\n        T oneMinusCth = T(1) - cth;\r\n\r\n        for (int i = 0; i < 3; ++i)\r\n          p[i] = point[i] * cth + vXp[i] * sth + v[i] * vDotp * oneMinusCth;\r\n      } else {\r\n        // taylor expansion for theta close to zero\r\n        T aux[3];\r\n        cross(camera, point, aux);\r\n        for (int i = 0; i < 3; ++i)\r\n          p[i] = point[i] + aux[i];\r\n      }\r\n\r\n      // translation of the camera\r\n      p[0] += camera[3];\r\n      p[1] += camera[4];\r\n      p[2] += camera[5];\r\n\r\n      // perspective division\r\n      T projectedPoint[2];\r\n      projectedPoint[0] = - p[0] / p[2];\r\n      projectedPoint[1] = - p[1] / p[2];\r\n\r\n      // conversion to pixel coordinates\r\n      T radiusSqr = projectedPoint[0]*projectedPoint[0] + projectedPoint[1]*projectedPoint[1];\r\n      T f         = T(camera[6]);\r\n      T k1        = T(camera[7]);\r\n      T k2        = T(camera[8]);\r\n      T r_p       = T(1) + k1 * radiusSqr + k2 * radiusSqr * radiusSqr;\r\n      T prediction[2];\r\n      prediction[0] = f * r_p * projectedPoint[0];\r\n      prediction[1] = f * r_p * projectedPoint[1];\r\n\r\n      error[0] = prediction[0] - T(measurement()(0));\r\n      error[1] = prediction[1] - T(measurement()(1));\r\n\r\n      return true;\r\n    }\r\n\r\n    void computeError()\r\n    {\r\n      const VertexCameraBAL* cam = static_cast<const VertexCameraBAL*>(vertex(0));\r\n      const VertexPointBAL* point = static_cast<const VertexPointBAL*>(vertex(1));\r\n\r\n      (*this)(cam->estimate().data(), point->estimate().data(), _error.data());\r\n    }\r\n\r\n    void linearizeOplus()\r\n    {\r\n      // use numeric Jacobians\r\n      //BaseBinaryEdge<2, Vector2d, VertexCameraBAL, VertexPointBAL>::linearizeOplus();\r\n      //return;\r\n\r\n      const VertexCameraBAL* cam = static_cast<const VertexCameraBAL*>(vertex(0));\r\n      const VertexPointBAL* point = static_cast<const VertexPointBAL*>(vertex(1));\r\n      typedef ceres::internal::AutoDiff<EdgeObservationBAL, double, VertexCameraBAL::Dimension, VertexPointBAL::Dimension> BalAutoDiff;\r\n\r\n      Matrix<double, Dimension, VertexCameraBAL::Dimension, Eigen::RowMajor> dError_dCamera;\r\n      Matrix<double, Dimension, VertexPointBAL::Dimension, Eigen::RowMajor> dError_dPoint;\r\n      double *parameters[] = { const_cast<double*>(cam->estimate().data()), const_cast<double*>(point->estimate().data()) };\r\n      double *jacobians[] = { dError_dCamera.data(), dError_dPoint.data() };\r\n      double value[Dimension];\r\n      bool diffState = BalAutoDiff::Differentiate(*this, parameters, Dimension, value, jacobians);\r\n\r\n      // copy over the Jacobians (convert row-major -> column-major)\r\n      if (diffState) {\r\n        _jacobianOplusXi = dError_dCamera;\r\n        _jacobianOplusXj = dError_dPoint;\r\n      } else {\r\n        assert(0 && \"Error while differentiating\");\r\n        _jacobianOplusXi.setZero();\r\n        _jacobianOplusXi.setZero();\r\n      }\r\n    }\r\n};\r\n\r\nint main(int argc, char** argv)\r\n{\r\n  int maxIterations;\r\n  bool verbose;\r\n  bool usePCG;\r\n  string outputFilename;\r\n  string inputFilename;\r\n  string statsFilename;\r\n  CommandArgs arg;\r\n  arg.param(\"i\", maxIterations, 5, \"perform n iterations\");\r\n  arg.param(\"o\", outputFilename, \"\", \"write points into a vrml file\");\r\n  arg.param(\"pcg\", usePCG, false, \"use PCG instead of the Cholesky\");\r\n  arg.param(\"v\", verbose, false, \"verbose output of the optimization process\");\r\n  arg.param(\"stats\", statsFilename, \"\", \"specify a file for the statistics\");\r\n  arg.paramLeftOver(\"graph-input\", inputFilename, \"\", \"file which will be processed\");\r\n\r\n  arg.parseArgs(argc, argv);\r\n\r\n  typedef g2o::BlockSolver< g2o::BlockSolverTraits<9, 3> >  BalBlockSolver;\r\n#ifdef G2O_HAVE_CHOLMOD\r\n  string choleskySolverName = \"CHOLMOD\";\r\n  typedef g2o::LinearSolverCholmod<BalBlockSolver::PoseMatrixType> BalLinearSolver;\r\n#elif defined G2O_HAVE_CSPARSE\r\n  string choleskySolverName = \"CSparse\";\r\n  typedef g2o::LinearSolverCSparse<BalBlockSolver::PoseMatrixType> BalLinearSolver;\r\n#else\r\n#error neither CSparse nor CHOLMOD are available\r\n#endif\r\n  typedef g2o::LinearSolverPCG<BalBlockSolver::PoseMatrixType> BalLinearSolverPCG;\r\n\r\n  g2o::SparseOptimizer optimizer;\r\n  std::unique_ptr<g2o::LinearSolver<BalBlockSolver::PoseMatrixType>> linearSolver;\r\n  if (usePCG) {\r\n    cout << \"Using PCG\" << endl;\r\n    linearSolver = g2o::make_unique<BalLinearSolverPCG>();\r\n  } else {\r\n    cout << \"Using Cholesky: \" << choleskySolverName << endl;\r\n    auto cholesky = g2o::make_unique<BalLinearSolver>();\r\n    cholesky->setBlockOrdering(true);\r\n    linearSolver = std::move(cholesky);\r\n  }\r\n  g2o::OptimizationAlgorithmLevenberg* solver = new g2o::OptimizationAlgorithmLevenberg(\r\n    g2o::make_unique<BalBlockSolver>(std::move(linearSolver)));\r\n\r\n  //solver->setUserLambdaInit(1);\r\n  optimizer.setAlgorithm(solver);\r\n  if (statsFilename.size() > 0){\r\n    optimizer.setComputeBatchStatistics(true);\r\n  }\r\n\r\n  vector<VertexPointBAL*> points;\r\n  vector<VertexCameraBAL*> cameras;\r\n\r\n  // parse BAL dataset\r\n  cout << \"Loading BAL dataset \" << inputFilename << endl;\r\n  {\r\n    ifstream ifs(inputFilename.c_str());\r\n    int numCameras, numPoints, numObservations;\r\n    ifs >> numCameras >> numPoints >> numObservations;\r\n\r\n    cerr << PVAR(numCameras) << \" \" << PVAR(numPoints) << \" \" << PVAR(numObservations) << endl;\r\n\r\n    int id = 0;\r\n    cameras.reserve(numCameras);\r\n    for (int i = 0; i < numCameras; ++i, ++id) {\r\n      VertexCameraBAL* cam = new VertexCameraBAL;\r\n      cam->setId(id);\r\n      optimizer.addVertex(cam);\r\n      cameras.push_back(cam);\r\n    }\r\n\r\n    points.reserve(numPoints);\r\n    for (int i = 0; i < numPoints; ++i, ++id) {\r\n      VertexPointBAL* p = new VertexPointBAL;\r\n      p->setId(id);\r\n      p->setMarginalized(true);\r\n      bool addedVertex = optimizer.addVertex(p);\r\n      if (! addedVertex) {\r\n        cerr << \"failing adding vertex\" << endl;\r\n      }\r\n      points.push_back(p);\r\n    }\r\n\r\n    // read in the observation\r\n    for (int i = 0; i < numObservations; ++i) {\r\n      int camIndex, pointIndex;\r\n      double obsX, obsY;\r\n      ifs >> camIndex >> pointIndex >> obsX >> obsY;\r\n\r\n      assert(camIndex >= 0 && (size_t)camIndex < cameras.size() && \"Index out of bounds\");\r\n      VertexCameraBAL* cam = cameras[camIndex];\r\n      assert(pointIndex >= 0 && (size_t)pointIndex < points.size() && \"Index out of bounds\");\r\n      VertexPointBAL* point = points[pointIndex];\r\n\r\n      EdgeObservationBAL* e = new EdgeObservationBAL;\r\n      e->setVertex(0, cam);\r\n      e->setVertex(1, point);\r\n      e->setInformation(Eigen::Matrix2d::Identity());\r\n      e->setMeasurement(Eigen::Vector2d(obsX, obsY));\r\n      bool addedEdge = optimizer.addEdge(e);\r\n      if (! addedEdge) {\r\n        cerr << \"error adding edge\" << endl;\r\n      }\r\n    }\r\n\r\n    // read in the camera params\r\n    Eigen::VectorXd cameraParameter(9);\r\n    for (int i = 0; i < numCameras; ++i) {\r\n      for (int j = 0; j < 9; ++j)\r\n        ifs >> cameraParameter(j);\r\n      VertexCameraBAL* cam = cameras[i];\r\n      cam->setEstimate(cameraParameter);\r\n    }\r\n\r\n    // read in the points\r\n    Eigen::Vector3d p;\r\n    for (int i = 0; i < numPoints; ++i) {\r\n      ifs >> p(0) >> p(1) >> p(2);\r\n\r\n      VertexPointBAL* point = points[i];\r\n      point->setEstimate(p);\r\n    }\r\n\r\n  }\r\n  cout << \"done.\" << endl;\r\n\r\n  cout << \"Initializing ... \" << flush;\r\n  optimizer.initializeOptimization();\r\n  cout << \"done.\" << endl;\r\n  optimizer.setVerbose(verbose);\r\n  cout << \"Start to optimize\" << endl;\r\n  optimizer.optimize(maxIterations);\r\n\r\n  if (statsFilename!=\"\"){\r\n    cerr << \"writing stats to file \\\"\" << statsFilename << \"\\\" ... \";\r\n    ofstream fout(statsFilename.c_str());\r\n    const BatchStatisticsContainer& bsc = optimizer.batchStatistics();\r\n    for (size_t i=0; i<bsc.size(); i++)\r\n      fout << bsc[i] << endl;\r\n    cerr << \"done.\" << endl;\r\n  }\r\n\r\n  // dump the points\r\n  if (outputFilename.size() > 0) {\r\n    ofstream fout(outputFilename.c_str()); // loadable with meshlab\r\n    fout \r\n      << \"#VRML V2.0 utf8\\n\"\r\n      << \"Shape {\\n\"\r\n      << \"  appearance Appearance {\\n\"\r\n      << \"    material Material {\\n\"\r\n      << \"      diffuseColor \" << 1 << \" \" << 0 << \" \" << 0 << \"\\n\"\r\n      << \"      ambientIntensity 0.2\\n\"\r\n      << \"      emissiveColor 0.0 0.0 0.0\\n\"\r\n      << \"      specularColor 0.0 0.0 0.0\\n\"\r\n      << \"      shininess 0.2\\n\"\r\n      << \"      transparency 0.0\\n\"\r\n      << \"    }\\n\"\r\n      << \"  }\\n\"\r\n      << \"  geometry PointSet {\\n\"\r\n      << \"    coord Coordinate {\\n\"\r\n      << \"      point [\\n\";\r\n    for (vector<VertexPointBAL*>::const_iterator it = points.begin(); it != points.end(); ++it) {\r\n      fout << (*it)->estimate().transpose() << endl;\r\n    }\r\n    fout << \"    ]\\n\" << \"  }\\n\" << \"}\\n\" << \"  }\\n\";\r\n  }\r\n  \r\n  return 0;\r\n}\r\n", "meta": {"hexsha": "cd4ac91c7b98e25fe1caf705910fc5d47ed34f0c", "size": 15595, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "slambook2/3rdparty/g2o/g2o/examples/bal/bal_example.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/bal/bal_example.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/bal/bal_example.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": 34.5022123894, "max_line_length": 136, "alphanum_fraction": 0.619301058, "num_tokens": 4169, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5774953651858117, "lm_q2_score": 0.5506073655352404, "lm_q1q2_score": 0.31797320163377135}}
{"text": "// Distributed under the MIT License.\n// See LICENSE.txt for details.\n\n#pragma once\n\n#include <array>\n#include <boost/functional/hash.hpp>\n#include <cstddef>\n#include <string>\n#include <unordered_map>\n#include <utility>\n\n#include \"DataStructures/SliceVariables.hpp\"\n#include \"DataStructures/Tags.hpp\"\n#include \"DataStructures/Tensor/EagerMath/DotProduct.hpp\"\n#include \"DataStructures/Tensor/EagerMath/Magnitude.hpp\"\n#include \"DataStructures/Tensor/Slice.hpp\"\n#include \"DataStructures/Tensor/Tensor.hpp\"\n#include \"DataStructures/Variables.hpp\"\n#include \"Domain/SizeOfElement.hpp\"\n#include \"Domain/Structure/Direction.hpp\"\n#include \"Domain/Structure/Element.hpp\"\n#include \"Domain/Tags.hpp\"\n#include \"Evolution/DiscontinuousGalerkin/NormalVectorTags.hpp\"\n#include \"Evolution/Systems/NewtonianEuler/Tags.hpp\"\n#include \"NumericalAlgorithms/LinearOperators/DefiniteIntegral.hpp\"\n#include \"NumericalAlgorithms/LinearOperators/MeanValue.hpp\"\n#include \"NumericalAlgorithms/Spectral/Mesh.hpp\"\n#include \"Utilities/ErrorHandling/Assert.hpp\"\n\n/// \\cond\ntemplate <size_t VolumeDim>\nclass ElementId;\n/// \\endcond\n\nnamespace NewtonianEuler {\nnamespace Limiters {\nnamespace Tci {\n\n/// \\ingroup LimitersGroup\n/// \\brief Implements the troubled-cell indicator from Krivodonova et al, 2004.\n///\n/// The KXRCF (these are the author initials) TCI is described in\n/// \\cite Krivodonova2004.\n///\n/// In summary, this TCI uses the size of discontinuities between neighboring DG\n/// elements to determine the smoothness of the solution. This works because the\n/// discontinuities converge rapidly for smooth solutions, therefore a large\n/// discontinuity suggests a lack of smoothness and the need to apply a limiter.\n///\n/// The reference sets the constant we call `kxrcf_constant` to 1. This should\n/// generally be a good threshold to use, though it might not be the optimal\n/// value (in balancing robustness vs accuracy) for any particular problem.\n///\n/// This implementation\n/// - does not support h- or p-refinement; this is checked by assertion.\n/// - chooses not to check external boundaries, because this adds complexity.\n///   However, by not checking external boundaries, the implementation may not\n///   be robust for problems that feed in shocks through boundary conditions.\ntemplate <size_t VolumeDim, typename PackagedData>\nbool kxrcf_indicator(\n    const double kxrcf_constant, const Scalar<DataVector>& cons_mass_density,\n    const tnsr::I<DataVector, VolumeDim>& cons_momentum_density,\n    const Scalar<DataVector>& cons_energy_density, const Mesh<VolumeDim>& mesh,\n    const Element<VolumeDim>& element,\n    const std::array<double, VolumeDim>& element_size,\n    const Scalar<DataVector>& det_logical_to_inertial_jacobian,\n    const typename evolution::dg::Tags::NormalCovectorAndMagnitude<\n        VolumeDim>::type& normals_and_magnitudes,\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  // Enforce restrictions on h-refinement, p-refinement\n  if (UNLIKELY(alg::any_of(element.neighbors(),\n                           [](const auto& direction_neighbors) noexcept {\n                             return direction_neighbors.second.size() != 1;\n                           }))) {\n    ERROR(\"The Kxrcf TCI does not yet support h-refinement\");\n    // Removing this limitation will require adapting the surface integrals to\n    // correctly acount for,\n    // - multiple (smaller) neighbors contributing to the integral\n    // - only a portion of a (larger) neighbor contributing to the integral\n  }\n  alg::for_each(neighbor_data, [&mesh](const auto& neighbor_and_data) noexcept {\n    if (UNLIKELY(neighbor_and_data.second.mesh != mesh)) {\n      ERROR(\"The Kxrcf TCI does not yet support p-refinement\");\n      // Removing this limitation will require generalizing the surface\n      // integrals to make sure the meshes are consistent.\n    }\n  });\n  // Check the mesh matches expectations:\n  // - the extents must be uniform, because the TCI expects a unique \"order\" for\n  //   the DG scheme. This shows up when computing the threshold parameter,\n  //   h^(degree+1)/2\n  // - the quadrature must be GL, because the current implementation doesn't\n  //   handle extrapolation to the boundary, though this could be changed.\n  // - the basis in principle could be changed, but until we need to change it\n  //   we just check it's the expected Legendre for simplicity\n  ASSERT(mesh == Mesh<VolumeDim>(mesh.extents(0), Spectral::Basis::Legendre,\n                                 Spectral::Quadrature::GaussLobatto),\n         \"The Kxrcf TCI expects a uniform LGL mesh, but got mesh = \" << mesh);\n\n  bool inflow_boundaries_present = false;\n  double inflow_area = 0.;\n  double inflow_delta_density = 0.;\n  double inflow_delta_energy = 0.;\n\n  // Skip boundary integrations on external boundaries. This choice might be\n  // problematic for evolutions (likely only simple test cases) that feed in\n  // shocks through the boundary condition: the limiter might fail to activate\n  // in the cell that touches the boundary.\n  //\n  // To properly compute the limiter at external boundaries we would need the\n  // limiter to know about the boundary condition, which may be difficult to\n  // do in a general way.\n  for (const auto& [neighbor, data] : neighbor_data) {\n    const auto& dir = neighbor.first;\n\n    // Check consistency of neighbor_data with element and normals\n    ASSERT(element.neighbors().contains(dir),\n           \"Received neighbor data from dir = \"\n               << dir << \", but element has no neighbor in this dir\");\n    ASSERT(normals_and_magnitudes.contains(dir),\n           \"Received neighbor data from dir = \"\n               << dir\n               << \", but normals_and_magnitudes has no normal in this dir\");\n    ASSERT(normals_and_magnitudes.at(dir).has_value(),\n           \"The normals_and_magnitudes are not up-to-date in dir = \" << dir);\n    const auto& normal = get<evolution::dg::Tags::NormalCovector<VolumeDim>>(\n        normals_and_magnitudes.at(dir).value());\n    const auto& magnitude_of_normal =\n        get<evolution::dg::Tags::MagnitudeOfNormal>(\n            normals_and_magnitudes.at(dir).value());\n\n    const size_t sliced_dim = dir.dimension();\n    const size_t index_of_slice =\n        (dir.side() == Side::Lower ? 0 : mesh.extents()[sliced_dim] - 1);\n    const auto momentum_on_slice = data_on_slice(\n        cons_momentum_density, mesh.extents(), sliced_dim, index_of_slice);\n    const auto momentum_dot_normal = dot_product(momentum_on_slice, normal);\n\n    // Skip boundaries with no significant inflow\n    // Note: the cutoff value here is small but arbitrarily chosen.\n    if (min(get(momentum_dot_normal)) > -1e-12) {\n      continue;\n    }\n    inflow_boundaries_present = true;\n\n    // This mask has value 1. for momentum_dot_normal < 0.\n    //                     0. for momentum_dot_normal >= 0.\n    const DataVector inflow_mask = 1. - step_function(get(momentum_dot_normal));\n    // Mask is then weighted pointwise by the Jacobian determinant giving\n    // surface integrals in inertial coordinates. This Jacobian determinant is\n    // given by the product of the volume Jacobian determinant with the\n    // magnitude of the unnormalized normal covectors.\n    const DataVector weighted_inflow_mask =\n        inflow_mask *\n        get(data_on_slice(det_logical_to_inertial_jacobian, mesh.extents(),\n                          sliced_dim, index_of_slice)) *\n        get(magnitude_of_normal);\n\n    inflow_area +=\n        definite_integral(weighted_inflow_mask, mesh.slice_away(sliced_dim));\n\n    // This is the step that is incompatible with h/p refinement. For use with\n    // h/p refinement, would need to correctly obtain the neighbor solution on\n    // the local grid points.\n    const auto neighbor_vars_on_slice = data_on_slice(\n        data.volume_data, mesh.extents(), sliced_dim, index_of_slice);\n\n    const auto density_on_slice = data_on_slice(\n        cons_mass_density, mesh.extents(), sliced_dim, index_of_slice);\n    const auto& neighbor_density_on_slice =\n        get<NewtonianEuler::Tags::MassDensityCons>(neighbor_vars_on_slice);\n    inflow_delta_density += definite_integral(\n        (get(density_on_slice) - get(neighbor_density_on_slice)) *\n            weighted_inflow_mask,\n        mesh.slice_away(sliced_dim));\n\n    const auto energy_on_slice = data_on_slice(\n        cons_energy_density, mesh.extents(), sliced_dim, index_of_slice);\n    const auto& neighbor_energy_on_slice =\n        get<NewtonianEuler::Tags::EnergyDensity>(neighbor_vars_on_slice);\n    inflow_delta_energy += definite_integral(\n        (get(energy_on_slice) - get(neighbor_energy_on_slice)) *\n            weighted_inflow_mask,\n        mesh.slice_away(sliced_dim));\n  }\n\n  if (not inflow_boundaries_present) {\n    // No boundaries had inflow, so not a troubled cell\n    return false;\n  }\n\n  // KXRCF take h to be the radius of the circumscribed circle\n  const double h = 0.5 * magnitude(element_size);\n  const double h_pow = pow(h, 0.5 * mesh.extents(0));\n\n  ASSERT(inflow_area > 0.,\n         \"Sanity check failed: negative area of inflow boundaries\");\n\n  const double norm_squared_density = mean_value(\n      get(det_logical_to_inertial_jacobian) * square(get(cons_mass_density)),\n      mesh);\n  ASSERT(norm_squared_density > 0.,\n         \"Sanity check failed: negative density norm over element\");\n  const double norm_density = sqrt(norm_squared_density);\n  const double ratio_for_density =\n      abs(inflow_delta_density) / (h_pow * inflow_area * norm_density);\n\n  const double norm_squared_energy = mean_value(\n      get(det_logical_to_inertial_jacobian) * square(get(cons_energy_density)),\n      mesh);\n  ASSERT(norm_squared_energy > 0.,\n         \"Sanity check failed: negative energy norm over element\");\n  const double norm_energy = sqrt(norm_squared_energy);\n  const double ratio_for_energy =\n      abs(inflow_delta_energy) / (h_pow * inflow_area * norm_energy);\n\n  return (ratio_for_density > kxrcf_constant or\n          ratio_for_energy > kxrcf_constant);\n}\n\n}  // namespace Tci\n}  // namespace Limiters\n}  // namespace NewtonianEuler\n", "meta": {"hexsha": "0ebb7509f22d63c10f1e0001c2060980dff1a27d", "size": 10223, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/Evolution/Systems/NewtonianEuler/Limiters/KxrcfTci.hpp", "max_stars_repo_name": "macedo22/spectre", "max_stars_repo_head_hexsha": "97b2b7ae356cf86830258cb5f689f1191fdb6ddd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-10-01T06:07:16.000Z", "max_stars_repo_stars_event_max_datetime": "2018-10-01T06:07:16.000Z", "max_issues_repo_path": "src/Evolution/Systems/NewtonianEuler/Limiters/KxrcfTci.hpp", "max_issues_repo_name": "macedo22/spectre", "max_issues_repo_head_hexsha": "97b2b7ae356cf86830258cb5f689f1191fdb6ddd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2018-06-04T20:26:40.000Z", "max_issues_repo_issues_event_max_datetime": "2018-07-27T14:54:55.000Z", "max_forks_repo_path": "src/Evolution/Systems/NewtonianEuler/Limiters/KxrcfTci.hpp", "max_forks_repo_name": "macedo22/spectre", "max_forks_repo_head_hexsha": "97b2b7ae356cf86830258cb5f689f1191fdb6ddd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 44.8377192982, "max_line_length": 80, "alphanum_fraction": 0.7179888487, "num_tokens": 2374, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6261241772283034, "lm_q2_score": 0.5078118642792044, "lm_q1q2_score": 0.3179532857085877}}
{"text": "/*\n Copyright (C) 2016 Quaternion Risk Management Ltd\n All rights reserved.\n\n This file is part of ORE, a free-software/open-source library\n for transparent pricing and risk analysis - http://opensourcerisk.org\n\n ORE is free software: you can redistribute it and/or modify it\n under the terms of the Modified BSD License.  You should have received a\n copy of the license along with this program.\n The license is also available online at <http://opensourcerisk.org>\n\n This program is distributed on the basis that it will form a useful\n contribution to risk analytics and model standardisation, but WITHOUT\n ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n FITNESS FOR A PARTICULAR PURPOSE. See the license for more details.\n*/\n\n#include <ql/instruments/makecapfloor.hpp>\n#include <ql/option.hpp>\n#include <ql/pricingengines/blackformula.hpp>\n#include <ql/pricingengines/capfloor/bacheliercapfloorengine.hpp>\n#include <ql/pricingengines/capfloor/blackcapfloorengine.hpp>\n#include <ql/utilities/dataformatters.hpp>\n#include <qle/termstructures/optionletstripper1.hpp>\n\n#include <boost/make_shared.hpp>\n\nusing boost::shared_ptr;\n\nnamespace QuantExt {\n\nOptionletStripper1::OptionletStripper1(const shared_ptr<QuantExt::CapFloorTermVolSurface>& termVolSurface,\n                                       const shared_ptr<IborIndex>& index, Rate switchStrike, Real accuracy,\n                                       Natural maxIter, const Handle<YieldTermStructure>& discount,\n                                       const VolatilityType type, const Real displacement, bool dontThrow,\n                                       const optional<VolatilityType> targetVolatilityType,\n                                       const optional<Real> targetDisplacement, Real dontThrowMinVol)\n    : OptionletStripper(termVolSurface, index, discount, targetVolatilityType ? *targetVolatilityType : type,\n                        targetDisplacement ? *targetDisplacement : displacement),\n      volQuotes_(nOptionletTenors_, std::vector<shared_ptr<SimpleQuote> >(nStrikes_)),\n      floatingSwitchStrike_(switchStrike == Null<Rate>() ? true : false), capFlooMatrixNotInitialized_(true),\n      switchStrike_(switchStrike), accuracy_(accuracy), maxIter_(maxIter), dontThrow_(dontThrow),\n      dontThrowMinVol_(dontThrowMinVol), inputVolatilityType_(type), inputDisplacement_(displacement) {\n\n    capFloorPrices_ = Matrix(nOptionletTenors_, nStrikes_);\n    optionletPrices_ = Matrix(nOptionletTenors_, nStrikes_);\n    capletVols_ = Matrix(nOptionletTenors_, nStrikes_);\n    capFloorVols_ = Matrix(nOptionletTenors_, nStrikes_);\n\n    Real firstGuess = 0.14; // guess is only used for shifted lognormal vols\n    optionletStDevs_ = Matrix(nOptionletTenors_, nStrikes_, firstGuess);\n\n    capFloors_ = CapFloorMatrix(nOptionletTenors_);\n    capFloorEngines_ = std::vector<std::vector<boost::shared_ptr<PricingEngine> > >(nOptionletTenors_);\n}\n\nvoid OptionletStripper1::performCalculations() const {\n\n    // update dates\n    const Date& referenceDate = termVolSurface_->referenceDate();\n    const DayCounter& dc = termVolSurface_->dayCounter();\n    shared_ptr<BlackCapFloorEngine> dummy(new BlackCapFloorEngine( // discounting does not matter here\n        iborIndex_->forwardingTermStructure(), 0.20, dc));\n    for (Size i = 0; i < nOptionletTenors_; ++i) {\n        CapFloor temp = MakeCapFloor(CapFloor::Cap, capFloorLengths_[i], iborIndex_,\n                                     0.04, // dummy strike\n                                     0 * Days)\n                            .withPricingEngine(dummy);\n        shared_ptr<FloatingRateCoupon> lFRC = temp.lastFloatingRateCoupon();\n        optionletDates_[i] = lFRC->fixingDate();\n        optionletPaymentDates_[i] = lFRC->date();\n        optionletAccrualPeriods_[i] = lFRC->accrualPeriod();\n        optionletTimes_[i] = dc.yearFraction(referenceDate, optionletDates_[i]);\n        atmOptionletRate_[i] = lFRC->indexFixing();\n    }\n\n    if (floatingSwitchStrike_) {\n        Rate averageAtmOptionletRate = 0.0;\n        for (Size i = 0; i < nOptionletTenors_; ++i) {\n            averageAtmOptionletRate += atmOptionletRate_[i];\n        }\n        switchStrike_ = averageAtmOptionletRate / nOptionletTenors_;\n    }\n\n    const Handle<YieldTermStructure>& discountCurve =\n        discount_.empty() ? iborIndex_->forwardingTermStructure() : discount_;\n\n    const std::vector<Rate>& strikes = termVolSurface_->strikes();\n    // initialize CapFloorMatrix\n    if (capFlooMatrixNotInitialized_) {\n        for (Size i = 0; i < nOptionletTenors_; ++i) {\n            capFloors_[i].resize(nStrikes_);\n            capFloorEngines_[i].resize(nStrikes_);\n        }\n        // construction might go here\n        for (Size j = 0; j < nStrikes_; ++j) {\n            for (Size i = 0; i < nOptionletTenors_; ++i) {\n                volQuotes_[i][j] = shared_ptr<SimpleQuote>(new SimpleQuote());\n                if (inputVolatilityType_ == ShiftedLognormal) {\n                    capFloorEngines_[i][j] = boost::make_shared<BlackCapFloorEngine>(\n                        discountCurve, Handle<Quote>(volQuotes_[i][j]), dc, inputDisplacement_);\n                } else if (inputVolatilityType_ == Normal) {\n                    capFloorEngines_[i][j] =\n                        boost::make_shared<BachelierCapFloorEngine>(discountCurve, Handle<Quote>(volQuotes_[i][j]), dc);\n                } else {\n                    QL_FAIL(\"unknown volatility type: \" << volatilityType_);\n                }\n            }\n        }\n        capFlooMatrixNotInitialized_ = false;\n    }\n\n    for (Size j = 0; j < nStrikes_; ++j) {\n        // using out-of-the-money options\n        CapFloor::Type capFloorType = strikes[j] < switchStrike_ ? CapFloor::Floor : CapFloor::Cap;\n        Option::Type optionletType = strikes[j] < switchStrike_ ? Option::Put : Option::Call;\n\n        Real previousCapFloorPrice = 0.0;\n        for (Size i = 0; i < nOptionletTenors_; ++i) {\n\n            capFloorVols_[i][j] = termVolSurface_->volatility(capFloorLengths_[i], strikes[j], true);\n            volQuotes_[i][j]->setValue(capFloorVols_[i][j]);\n            capFloors_[i][j] = MakeCapFloor(capFloorType, capFloorLengths_[i], iborIndex_, strikes[j], -0 * Days)\n                                   .withPricingEngine(capFloorEngines_[i][j]);\n            capFloorPrices_[i][j] = capFloors_[i][j]->NPV();\n            optionletPrices_[i][j] = capFloorPrices_[i][j] - previousCapFloorPrice;\n            previousCapFloorPrice = capFloorPrices_[i][j];\n            DiscountFactor d = discountCurve->discount(optionletPaymentDates_[i]);\n            DiscountFactor optionletAnnuity = optionletAccrualPeriods_[i] * d;\n            try {\n                if (volatilityType_ == ShiftedLognormal) {\n                    optionletStDevs_[i][j] = blackFormulaImpliedStdDev(\n                        optionletType, strikes[j], atmOptionletRate_[i], optionletPrices_[i][j], optionletAnnuity,\n                        displacement_, optionletStDevs_[i][j], accuracy_, maxIter_);\n                } else if (volatilityType_ == Normal) {\n                    optionletStDevs_[i][j] =\n                        std::sqrt(optionletTimes_[i]) *\n                        bachelierBlackFormulaImpliedVol(optionletType, strikes[j], atmOptionletRate_[i],\n                                                        optionletTimes_[i], optionletPrices_[i][j], optionletAnnuity);\n                } else {\n                    QL_FAIL(\"Unknown target volatility type: \" << volatilityType_);\n                }\n            } catch (std::exception& e) {\n                if (dontThrow_)\n                    optionletStDevs_[i][j] = dontThrowMinVol_; // really need a way to log this\n                else\n                    QL_FAIL(\"could not bootstrap optionlet:\"\n                            \"\\n type:    \"\n                            << optionletType << \"\\n strike:  \" << io::rate(strikes[j])\n                            << \"\\n atm:     \" << io::rate(atmOptionletRate_[i])\n                            << \"\\n price:   \" << optionletPrices_[i][j] << \"\\n annuity: \" << optionletAnnuity\n                            << \"\\n expiry:  \" << optionletDates_[i] << \"\\n error:   \" << e.what());\n            }\n            optionletVolatilities_[i][j] = optionletStDevs_[i][j] / std::sqrt(optionletTimes_[i]);\n        }\n    }\n}\n\nconst Matrix& OptionletStripper1::capletVols() const {\n    calculate();\n    return capletVols_;\n}\n\nconst Matrix& OptionletStripper1::capFloorPrices() const {\n    calculate();\n    return capFloorPrices_;\n}\n\nconst Matrix& OptionletStripper1::capFloorVolatilities() const {\n    calculate();\n    return capFloorVols_;\n}\n\nconst Matrix& OptionletStripper1::optionletPrices() const {\n    calculate();\n    return optionletPrices_;\n}\n\nRate OptionletStripper1::switchStrike() const {\n    if (floatingSwitchStrike_)\n        calculate();\n    return switchStrike_;\n}\n} // namespace QuantExt\n", "meta": {"hexsha": "2e15981a7eb752c2b614caadd7817ab1760b488a", "size": 8909, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "QuantExt/qle/termstructures/optionletstripper1.cpp", "max_stars_repo_name": "paul-giltinan/Engine", "max_stars_repo_head_hexsha": "49b6e142905ca2cce93c2ae46e9ac69380d9f7a1", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "QuantExt/qle/termstructures/optionletstripper1.cpp", "max_issues_repo_name": "paul-giltinan/Engine", "max_issues_repo_head_hexsha": "49b6e142905ca2cce93c2ae46e9ac69380d9f7a1", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "QuantExt/qle/termstructures/optionletstripper1.cpp", "max_forks_repo_name": "paul-giltinan/Engine", "max_forks_repo_head_hexsha": "49b6e142905ca2cce93c2ae46e9ac69380d9f7a1", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 47.8978494624, "max_line_length": 120, "alphanum_fraction": 0.6316084858, "num_tokens": 2168, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6261241772283034, "lm_q2_score": 0.5078118642792044, "lm_q1q2_score": 0.3179532857085877}}
{"text": "#include \"opt.hh\"\n#include \"io.hh\"\n#include \"key.hh\"\n#include \"random.hh\"\n\n#include <boost/numeric/odeint.hpp>\n\nnamespace boost {\n  //\n  namespace numeric {\n    //\n    namespace odeint {\n      //\n      template<>\n      struct is_resizeable<Coord::Cartesian> {\n\t//\n\ttypedef boost::true_type type;\n\t\n\tstatic const bool value = type::value;\n      };\n    }\n  }\n}\n\n/**********************************************************************************************************\n *************************************** HARDING POTENTIAL WRAPPER ****************************************\n **********************************************************************************************************/\n\ndouble Opt::HardPot::evaluate (const Cartesian& x) const\n{\n  const char funame [] = \"Opt::HardPot::evaluate: \";\n\n  if(atom_size() != x.atom_size()) {\n    //\n    std::cerr << funame << \"dimensions mismatch: \" << atom_size() << \" vs. \" << x.atom_size() << \"\\n\";\n\n    throw Error::Logic();\n  }\n  \n  return potential(x);\n}\n\n/**********************************************************************************************************\n ***************************** CONSTRAINED OPTIMIZATION IN CARTESIAN SPACE ********************************\n **********************************************************************************************************/\n\nint Opt::CcOpt::_grad_count;\n\nvoid Opt::CcOpt::execute (Coord::Cartesian& x) const\n{\n  const char funame [] = \"Opt::CcOpt::execute: \";\n\n  namespace odeint = boost::numeric::odeint;\n\n  double dtemp;\n  int    itemp;\n  \n  IO::Marker fumarker(funame);\n\n  _grad_count = 0;\n  \n  Cartesian grad(x.size());\n  \n  (*this)(x, grad);\n \n  dtemp = vlength(grad);\n\n  IO::log << IO::log_offset << \"initial gradient projection length = \" << dtemp << \"\\n\";\n  \n  if(dtemp <= _grad_tol) {\n    //\n    IO::log << IO::log_offset << \"gradient projection is small enough: no optimization necessary\\n\";\n\n    return;\n  }\n\n  if(_constrain.size() && use_constrain) {\n    //\n    IO::log << IO::log_offset << \"initial constrain values:\";\n\n    for(_con_t::const_iterator cit = _constrain.begin(); cit != _constrain.end(); ++cit) {\n      //\n      dtemp = (*cit)->evaluate(x);\n\n      switch((*cit)->type()) {\n\t//\n      case Coord::DISTANCE:\n\t//\n\tdtemp /= Phys_const::angstrom;\n\n\tbreak;\n      \n      case Coord::ANGLE:\n\t//\n\tdtemp *= 180. / M_PI;\n\n\tbreak;\n\n      case Coord::DIHEDRAL:\n\t//\n\tdtemp *= 180. / M_PI;\n\n\tbreak;\n      }\n    \n      IO::log << \"   \" << dtemp;\n    }\n  \n    IO::log << std::endl;\n  }\n  \n  try {\n    //\n    double time = 0.;\n    \n    while(1) {\n      //\n      IO::log << IO::log_offset\n\t      << std::setw(13) << \"time\"\n\t      << std::setw(13) << \"gradient\"\n\t      << std::setw(13) << \"target\"\n\t      << \"\\n\";\n\n      double tmax = time + _time_length;\n      \n      itemp = odeint::integrate(*this, x, time, tmax, _time_step);\n\n      time = tmax;\n    \n      IO::log << IO::log_offset << \"steps # = \" << itemp << std::endl;\n    }\n  } catch(_Fin) {\n    //\n    (*this)(x, grad);\n\n    dtemp = vlength(grad);\n    \n    IO::log << IO::log_offset << \"final gradient projection length  = \" << std::setw(13) << dtemp  << \"\\n\";\n    \n    IO::log << IO::log_offset << \"gradient calls #       = \" << std::setw(13) << _grad_count << \"\\n\";\n\n    if(_constrain.size() && use_constrain) {\n      //\n      IO::log << IO::log_offset << \"final constrain values:\";\n\n      for(_con_t::const_iterator cit = _constrain.begin(); cit != _constrain.end(); ++cit) {\n\t//\n\tdtemp = (*cit)->evaluate(x);\n\n\tswitch((*cit)->type()) {\n\t  //\n\tcase Coord::DISTANCE:\n\t  //\n\t  dtemp /= Phys_const::angstrom;\n\n\t  break;\n      \n\tcase Coord::ANGLE:\n\t  //\n\t  dtemp *= 180. / M_PI;\n\n\t  break;\n\n\tcase Coord::DIHEDRAL:\n\t  //\n\t  dtemp *= 180. / M_PI;\n\n\t  break;\n\t}\n    \n\tIO::log << \"   \" << dtemp;\n      }\n  \n      IO::log << std::endl;\n    }\n  }\n}\n\nvoid Opt::CcOpt::operator() (const Cartesian& x, Cartesian& dx, double time) const\n{\n  const char funame [] = \"Opt::CcOpt::operator(): \";\n\n  int    itemp;\n  double dtemp;\n\n  ++_grad_count;\n  \n  if(!x.size()) {\n    //\n    std::cerr << funame << \"zero configuration space vector dimension\\n\";\n\n    throw Error::Init();\n  }\n\n  dx.resize(x.size());\n  \n  for(int i = 0; i < dx.size(); ++i)\n    //\n    dx[i] = -pot()->grad(x, i);\n\n  if(use_constrain && _constrain.size()) {\n    //\n    // constrain subspace\n    //\n    std::vector<Cartesian> cspace(_constrain.size(), x);\n\n    int cc = 0;\n\n    for(_con_t::const_iterator cit = _constrain.begin(); cit != _constrain.end(); ++cit, ++cc) {\n      //\n      for(int i = 0; i < x.size(); ++i)\n\t//\n\tcspace[cc][i] = (*cit)->grad(x, i);\n\n      dtemp = normalize(cspace[cc]);\n\n      if(dtemp == 0.) {\n\t//\n\tstd::cerr << funame << \"zero constrain vector\\n\";\n\n\tthrow Error::Range();\n      }\n    \n      for(int d = 0; d < cc; ++d)\n\t//\n\torthogonalize(cspace[cc], cspace[d]);\n\n      if(cc) {\n\t//\n\tdtemp = normalize(cspace[cc]);\n    \n\tif(dtemp < _ci_tol) {\n\t  //\n\t  std::cerr << funame << \"constrains are linearly dependent: \" << dtemp << \" vs \" << _ci_tol << \"\\n\";\n\n\t  throw Error::Run();\n\t}\n      }\n    }\n\n    // potential gradient component, orthogonal to constrain subspace\n    //\n    for(cc = 0; cc < cspace.size(); ++cc)\n      //\n      orthogonalize(dx, cspace[cc]);\n  }\n  \n  if(time != 0.) {\n    //\n    dtemp = vlength(dx);\n\n    IO::log << IO::log_offset\n\t    << std::setw(13) << time\n\t    << std::setw(13) << dtemp\n\t    << std::setw(13) << _grad_tol\n\t    << std::endl;\n  \n    if(dtemp < _grad_tol)\n      //\n      throw _Fin();\n  }\n}\n\nvoid Opt::CcOpt::set (std::istream& from)\n{\n  const char funame [] = \"Opt::CcOpt::set:\";\n  \n    int    itemp;\n    double dtemp;\n\n  IO::Marker funame_marker(funame);\n\n  KeyGroup CcOptGroup;\n\n  Key  tol_key(\"GradientTolerance[a.u.]\"       );\n  Key  cit_key(\"ConstrainIndependenceTolerance\");\n  Key step_key(\"IntegrationStep\"               );\n  Key time_key(\"IntegrationTime\"               );\n    \n  std::string token, comment, stemp;\n\n  while(from >> token) {\n    //\n    // end of input\n    //\n    if(token == IO::end_key()) {\n      //\n      std::getline(from, comment);\n      //\n      break;\n    }\n    // gradient tolerance\n    //\n    else if(token == tol_key) {\n      //\n      if(!(from >> _grad_tol)) {\n\t//\n\tstd::cerr << funame << token << \": corrupted\\n\";\n\n\tthrow Error::Input();\n      }\n\n      if(_grad_tol <= 0.) {\n\t//\n\tstd::cerr << funame << token << \": out of range: \" << _grad_tol << \"\\n\";\n\n\tthrow Error::Range();\n      }\n    }\n    // constrain (local) independence tolerance\n    //\n    else if(token == cit_key) {\n      //\n      if(!(from >> _ci_tol)) {\n\t//\n\tstd::cerr << funame << token << \": corrupted\\n\";\n\n\tthrow Error::Input();\n      }\n\n      if(_ci_tol <= 0.) {\n\t//\n\tstd::cerr << funame << token << \": out of range: \" << _ci_tol << \"\\n\";\n\n\tthrow Error::Range();\n      }\n    }\n    // initial time step\n    //\n    else if(token == step_key) {\n      //\n      if(!(from >> _time_step)) {\n\t//\n\tstd::cerr << funame << token << \": corrupted\\n\";\n\n\tthrow Error::Input();\n      }\n\n      if(_time_step <= 0.) {\n\t//\n\tstd::cerr << funame << token << \": out of range: \" << _time_step << \"\\n\";\n\n\tthrow Error::Range();\n      }\n    }\n    // integration time\n    //\n    else if(token == time_key) {\n      //\n      if(!(from >> _time_length)) {\n\t//\n\tstd::cerr << funame << token << \": corrupted\\n\";\n\n\tthrow Error::Input();\n      }\n\n      if(_time_length <= 0.) {\n\t//\n\tstd::cerr << funame << token << \": out of range: \" << _time_length << \"\\n\";\n\n\tthrow Error::Range();\n      }\n    }\n    // unknown keyword\n    //\n    else if(IO::skip_comment(token, from)) {\n      //\n      std::cerr << funame << \"unknown keyword \" << token << \"\\n\";\n      \n      Key::show_all(std::cerr);\n      \n      std::cerr << \"\\n\";\n      \n      throw Error::Init();\n    }\n  }\n\n  if(!from) {\n    //\n    std::cerr << funame << \"corrupted\\n\";\n\n    throw Error::Input();\n  }\n}\n\n/********************************************************************************************************\n *********************** OPTIMIZATION AND IMPORTANCE SAMPLING IN Z-MATRIX COORDINATES********************\n ********************************************************************************************************/\n\n// gradient tolerance\n//\ndouble Opt::ZOpt::grad_tol = 1.e-5;\n\n// maximal optimization step\n//\ndouble Opt::ZOpt::max_opt_step = 0.1;\n\n// maximal number of optimization iterations\n//\nint Opt::ZOpt::max_opt_count = 100;\n\n// differentiation step\n//\ndouble Opt::ZOpt::diff_step = .001;\n\n// potential\n//\nConstSharedPointer<Coord::CartFun> Opt::ZOpt::pot;\n\ndouble Opt::ZOpt::_con_pot (const std::vector<double>& cpos) const\n{\n  const char funame [] = \"Opt::ZOpt::_con_pot: \";\n\n  int    itemp;\n  double dtemp;\n  \n  if(!pot) {\n    //\n    std::cerr << funame << \"potential not initialized\\n\";\n\n    throw Error::Init();\n  }\n\n  if(cpos.size() != _con_modes.size()) {\n    //\n    std::cerr << funame << \"number of conserved modes mismatch: \" << cpos.size() << \" vs \" << _con_modes.size() << \"\\n\";\n\n    throw Error::Logic();\n  }\n\n  ZData zpos = _zmin;\n\n  itemp = 0;\n  \n  for(mode_t::const_iterator cit = _con_modes.begin(); cit != _con_modes.end(); ++cit, ++itemp)\n    //\n    zpos[cit->first] = cpos[itemp];\n\n  return pot->evaluate((Cartesian)zpos);\n}\n\nLapack::Vector Opt::ZOpt::_con_grad () const\n{\n  int    itemp;\n  double dtemp;\n  \n  std::vector<double> cpos(_con_modes.size());\n\n  itemp = 0;\n  \n  for(mode_t::const_iterator cit = _con_modes.begin(); cit != _con_modes.end(); ++cit, ++itemp)\n    //\n    cpos[itemp] = _zmin[cit->first];\n\n  Lapack::Vector res(_con_modes.size());\n\n  for(int i  = 0; i < _con_modes.size(); ++i) {\n    //\n    cpos[i] += diff_step;\n\n    res[i] = _con_pot(cpos);\n\n    cpos[i] -= 2. * diff_step;\n\n    res[i] -= _con_pot(cpos);\n\n    cpos[i] += diff_step;\n    \n    res[i] /= 2. * diff_step;\n  }\n\n  return res;\n}\n\nLapack::SymmetricMatrix Opt::ZOpt::_con_hess () const\n{\n  int    itemp;\n  double dtemp;\n  \n  std::vector<double> cpos(_con_modes.size());\n\n  itemp = 0;\n  \n  for(mode_t::const_iterator cit = _con_modes.begin(); cit != _con_modes.end(); ++cit, ++itemp)\n    //\n    cpos[itemp] = _zmin[cit->first];\n\n  const double e0 = _con_pot(cpos);\n\n  Lapack::SymmetricMatrix res(_con_modes.size());\n\n  for(int i  = 0; i < _con_modes.size(); ++i)\n    //\n    for(int j  = i; j < _con_modes.size(); ++j)\n      //\n      if(i != j) {\n\t//\n\tcpos[i] += diff_step;\n\n\tcpos[j] += diff_step;\n\t\n\tres(i, j) = _con_pot(cpos);\n\n\tcpos[i] -= 2. * diff_step;\n\n\tres(i, j) -= _con_pot(cpos);\n\n\tcpos[j] -= 2. * diff_step;\n\n\tres(i, j) += _con_pot(cpos);\n\n\tcpos[i] += 2. * diff_step;\n\n\tres(i, j) -= _con_pot(cpos);\n\n\tcpos[i] -= diff_step;\n\t\n\tcpos[j] += diff_step;\n\t\n\tres(i, j) /= 4. * diff_step * diff_step;\n      }\n      else {\n\t//\n\tcpos[i] += diff_step;\n\t\n\tres(i, i) = _con_pot(cpos) - 2. * e0;\n\n\tcpos[i] -= 2. * diff_step;\n\n\tres(i, i) += _con_pot(cpos);\n\n\tcpos[i] += diff_step;\n\t\n\tres(i, i) /= diff_step * diff_step;\n      }\n\n  return res;\n}\n\nOpt::ZOpt::ZOpt (const ZData& zinit, const mode_t& cm) : _zmin(zinit), _con_modes(cm)\n{\n  const char funame [] = \"Opt::ZOpt::ZOpt: \";\n\n  IO::Marker fumark(funame);\n  \n  double dtemp;\n  int    itemp;\n\n  int count = 0;\n\n  IO::log << IO::log_offset << std::setw(5) << \"#\" << std::setw(13) << \"Grad[au]\" << std::setw(13) << \"Target\" << std::endl;\n  \n  while(count++ < max_opt_count) {\n    //\n    _fc_eval_sqrt = _con_hess().eigenvalues(&_fc_evec);\n\n    Lapack::Vector dx = _con_grad();\n    \n    dtemp = vlength(dx);\n\n    IO::log << IO::log_offset << std::setw(5) << count << std::setw(13) << dtemp << std::setw(13) << grad_tol << std::endl;\n    \n    if(dtemp < grad_tol)\n      //\n      break;\n\n    dx = dx * _fc_evec;\n\n    for(int i = 0; i < dx.size(); ++i) {\n      //\n      if(_fc_eval_sqrt[i] <= 0.) {\n\t//\n\tIO::log << IO::log_offset << i + 1 << \"-th force constant eigenvalue is negative\" << std::endl;\n\t\n\tif(dx[i] < 0.) {\n\t  //\n\t  dx[i] = -max_opt_step;\n\t}\n\telse if(dx[i] > 0.) {\n\t  //\n\t  dx[i] = max_opt_step;\n\t}\n      }\n      else {\n\t//\n\tdtemp = dx[i] / _fc_eval_sqrt[i];\n\n\tif(dtemp < -max_opt_step) {\n\t  //\n\t  dx[i] = -max_opt_step;\n\t}\n\telse if(dtemp > max_opt_step) {\n\t  //\n\t  dx[i] = max_opt_step;\n\t}\n\telse\n\t  //\n\t  dx[i] = dtemp;\n      }\n    }\n    \n    dx = _fc_evec * dx;\n\n    itemp = 0;\n\n    for(mode_t::const_iterator cit = _con_modes.begin(); cit != _con_modes.end(); ++cit, ++itemp) {\n      //\n      dtemp = _zmin[cit->first] - dx[itemp];\n\n      if(dtemp < cit->second.first) {\n\t//\n\tIO::log << IO::log_offset << cit->first << \" proposed value is below lower limit, \" << dtemp << \": clip it\" << std::endl;\n\t\n\t_zmin[cit->first] = cit->second.first;\n      }\n      else if(dtemp > cit->second.second) {\n\t//\n\tIO::log << IO::log_offset << cit->first << \" proposed value is above upper limit, \" << dtemp << \": clip it\" << std::endl;\n\t\n\t_zmin[cit->first] = cit->second.second;\n      }\n      else\n\t//\n\t_zmin[cit->first] = dtemp;\n    }\n  }\n\n  if(count > max_opt_count) {\n    //\n    IO::log << IO::log_offset << \"maximal number of iterations reached: no convergence\" << std::endl;\n\n    std::cerr << funame << \"maximal number of iterations reached: no convergence\\n\";\n\n    throw NoConv();\n  }\n\n  for(int i = 0; i < _con_modes.size(); ++i) {\n    //\n    dtemp = _fc_eval_sqrt[i];\n\n    if(dtemp <= 0.) {\n      //\n      std::cerr << funame << \"force constant matrix at minimum is not positively defined\\n\";\n\n      throw Error::Run();\n    }\n\n    _fc_eval_sqrt[i] = std::sqrt(dtemp);\n  }\n\n  _mass_factor = std::sqrt(product(_zmin.inertia_moments())) / Lapack::Cholesky(_zmin.mobility_matrix()).det_sqrt();\n\n  _ener_min = pot->evaluate((Cartesian)_zmin);\n}\n\ndouble Opt::ZOpt::anharmonic_correction (double temperature, int count_max, double* rerr, int* fail) const\n{\n  const char funame [] = \"Opt::ZOpt::anharmonic_correction: \";\n\n  static const double exp_pow_max = 100.;\n\n  double dtemp;\n  int    itemp;\n  bool   btemp;\n  \n  const double tsqrt = std::sqrt(temperature);\n\n  Lapack::Vector vtemp(_con_modes.size());\n\n  double res = 0., var =  0.;\n\n  int skip = 0;\n\n  // sampling cycle\n  //\n  for(int count = 0; count < count_max; ++count) {\n    //\n    double eref = 0.;\n\n    for(int i = 0; i < _con_modes.size(); ++i) {\n      //\n      dtemp = Random::norm();\n\n      eref += dtemp * dtemp;\n    \n      vtemp[i] = dtemp / _fc_eval_sqrt[i] * tsqrt;\n    }\n\n    eref *= temperature / 2.;\n\n    vtemp = _fc_evec * vtemp;\n\n    ZData ztemp = _zmin;\n\n    itemp = 0;\n\n    btemp = false;\n  \n    for(mode_t::const_iterator cit = _con_modes.begin(); cit != _con_modes.end(); ++cit, ++itemp) {\n      //\n      dtemp = ztemp[cit->first] + vtemp[itemp];\n\n      // check that the non-fluxional coordinate is in the allowed window\n      //\n      if(dtemp < cit->second.first || dtemp > cit->second.second) {\n\t//\n\tswitch(ztemp.type(cit->first)) {\n\t  //\n\tcase DISTANCE:\n\t  //\n\t  dtemp /= Phys_const::angstrom;\n\n\t  break;\n\t  \n\tdefault:\n\t  //\n\t  dtemp *= 180. / M_PI;\n\t}\n\n\tIO::log << funame << \"WARNING: T = \" << temperature / Phys_const::kelv\n\t\t<< \"K, z-matrix variable \" << cit->first << \" out of limits: \" << dtemp << \"\\n\";\n\n\t++skip;\n\t\n\tbtemp = true;\n\n\tbreak;\n      }\n\n      ztemp[cit->first] = dtemp;\n    }\n\n    if(btemp)\n      //\n      continue;\n\n    dtemp = (pot->evaluate((Cartesian)ztemp) - eref - _ener_min) / temperature;\n\n    if(dtemp > exp_pow_max)\n      //\n      continue;\n\n    if(dtemp < -exp_pow_max) {\n      //\n      IO::log << funame << \"WARNING: anharmonic correction too negative at T = \" << temperature / Phys_const::kelv << \"K: \"\n\t      << dtemp * temperature / Phys_const::kcal << \" kcal/mol: skipping the point\" << std::endl;\n\n      ++skip;\n      \n      continue;\n    }\n\n    dtemp = std::exp(-dtemp) / Lapack::Cholesky(ztemp.mobility_matrix()).det_sqrt()\n      * std::sqrt(product(ztemp.inertia_moments())) / mass_factor();\n\n    res += dtemp;\n\n    var += dtemp * dtemp;\n    //\n  }// sampling cycle\n  //\n\n  res /= (double)count_max;\n\n  var /= (double)count_max;\n\n  // relative error\n  //\n  if(rerr)\n    //\n    *rerr = std::sqrt(var - res * res) / res / std::sqrt((double)count_max);\n\n  // failed points #\n  //\n  if(fail)\n    //\n    *fail = skip;\n  \n  return res;\n}\n", "meta": {"hexsha": "9f3212f48ec779de0a1d42fd57d1fb8d7b2fc2df", "size": 16025, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/libmess/opt.cc", "max_stars_repo_name": "dsjense/MESS", "max_stars_repo_head_hexsha": "b54c161327e2e35a40bb3b71555bdc2eef7cd7f9", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 9.0, "max_stars_repo_stars_event_min_datetime": "2020-03-03T07:34:35.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-08T13:12:16.000Z", "max_issues_repo_path": "src/libmess/opt.cc", "max_issues_repo_name": "dsjense/MESS", "max_issues_repo_head_hexsha": "b54c161327e2e35a40bb3b71555bdc2eef7cd7f9", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2022-03-23T10:57:25.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T12:30:44.000Z", "max_forks_repo_path": "src/libmess/opt.cc", "max_forks_repo_name": "dsjense/MESS", "max_forks_repo_head_hexsha": "b54c161327e2e35a40bb3b71555bdc2eef7cd7f9", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2019-12-18T19:59:13.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-31T01:49:43.000Z", "avg_line_length": 20.5185659411, "max_line_length": 124, "alphanum_fraction": 0.5153822153, "num_tokens": 4694, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6723316860482763, "lm_q2_score": 0.4726834766204328, "lm_q1q2_score": 0.3178000788033766}}
{"text": "\n\n#include <NTL/ZZ_p.h>\n#include <NTL/FFT.h>\n\n#include <NTL/new.h>\n\n\nNTL_START_IMPL\n\n\nZZ_pInfoT::ZZ_pInfoT(const ZZ& NewP)\n{\n   if (NewP <= 1) Error(\"ZZ_pContext: p must be > 1\");\n\n   ref_count = 1;\n   p = NewP;\n   size = p.size();\n\n   ExtendedModulusSize = 2*size + \n                 (NTL_BITS_PER_LONG + NTL_ZZ_NBITS - 1)/NTL_ZZ_NBITS;\n\n   initialized = 0;\n   x = 0;\n   u = 0;\n   tbl = 0;\n   tbl1 = 0;\n\n   long i;\n   for (i = 0; i < MAX_ZZ_p_TEMPS; i++)\n      temps[i] = 0;\n\n   temps_top = 0;\n}\n\n\n\nvoid ZZ_pInfoT::init()\n{\n   ZZ B, M, M1, M2, M3;\n   long n, i;\n   long q, t;\n\n   initialized = 1;\n\n   sqr(B, p);\n\n   LeftShift(B, B, NTL_FFTMaxRoot+NTL_FFTFudge);\n\n   set(M);\n   n = 0;\n   while (M <= B) {\n      UseFFTPrime(n);\n      q = FFTPrime[n];\n      n++;\n      mul(M, M, q);\n   }\n\n   NumPrimes = n;\n   MaxRoot = CalcMaxRoot(q);\n\n\n   double fn = double(n);\n\n   if (8.0*fn*(fn+32) > NTL_FDOUBLE_PRECISION)\n      Error(\"modulus too big\");\n\n\n   if (8.0*fn*(fn+32) > NTL_FDOUBLE_PRECISION/double(NTL_SP_BOUND))\n      QuickCRT = 0;\n   else\n      QuickCRT = 1;\n\n\n   if (!(x = (double *) NTL_MALLOC(n, sizeof(double), 0)))\n      Error(\"out of space\");\n\n   if (!(u = (long *) NTL_MALLOC(n,  sizeof(long), 0)))\n      Error(\"out of space\");\n\n   ZZ_p_rem_struct_init(&rem_struct, n, p, FFTPrime);\n\n   ZZ_p_crt_struct_init(&crt_struct, n, p, FFTPrime);\n\n   if (ZZ_p_crt_struct_special(crt_struct)) return;\n\n   ZZ qq, rr;\n\n   DivRem(qq, rr, M, p);\n\n   NegateMod(MinusMModP, rr, p);\n\n   for (i = 0; i < n; i++) {\n      q = FFTPrime[i];\n\n      long tt = rem(qq, q);\n\n      mul(M2, p, tt);\n      add(M2, M2, rr); \n      div(M2, M2, q);  // = (M/q) rem p\n      \n\n      div(M1, M, q);\n      t = rem(M1, q);\n      t = InvMod(t, q);\n\n      mul(M3, M2, t);\n      rem(M3, M3, p);\n\n      ZZ_p_crt_struct_insert(crt_struct, i, M3);\n\n\n      x[i] = ((double) t)/((double) q);\n      u[i] = t;\n   }\n}\n\n\n\nZZ_pInfoT::~ZZ_pInfoT()\n{\n   long i;\n\n   for (i = 0; i < MAX_ZZ_p_TEMPS; i++)\n      if (temps[i]) delete temps[i];\n\n   if (initialized) {\n      ZZ_p_rem_struct_free(rem_struct);\n      ZZ_p_crt_struct_free(crt_struct);\n\n      free(x);\n      free(u);\n   }\n}\n\n\nZZ_pInfoT *ZZ_pInfo = 0; \n\ntypedef ZZ_pInfoT *ZZ_pInfoPtr;\n\n\nstatic \nvoid CopyPointer(ZZ_pInfoPtr& dst, ZZ_pInfoPtr src)\n{\n   if (src == dst) return;\n\n   if (dst) {\n      dst->ref_count--;\n\n      if (dst->ref_count < 0) \n         Error(\"internal error: negative ZZ_pContext ref_count\");\n\n      if (dst->ref_count == 0) delete dst;\n   }\n\n   if (src) {\n      if (src->ref_count == NTL_MAX_LONG)\n         Error(\"internal error: ZZ_pContext ref_count overflow\");\n\n      src->ref_count++;\n   }\n\n   dst = src;\n}\n   \n\n\nvoid ZZ_p::init(const ZZ& p)\n{\n   ZZ_pContext c(p);\n   c.restore();\n}\n\n\nZZ_pContext::ZZ_pContext(const ZZ& p)\n{\n   ptr = NTL_NEW_OP ZZ_pInfoT(p);\n}\n\nZZ_pContext::ZZ_pContext(const ZZ_pContext& a)\n{\n   ptr = 0;\n   CopyPointer(ptr, a.ptr);\n}\n\nZZ_pContext& ZZ_pContext::operator=(const ZZ_pContext& a)\n{\n   CopyPointer(ptr, a.ptr);\n   return *this;\n}\n\n\nZZ_pContext::~ZZ_pContext()\n{\n   CopyPointer(ptr, 0);\n}\n\nvoid ZZ_pContext::save()\n{\n   CopyPointer(ptr, ZZ_pInfo);\n}\n\nvoid ZZ_pContext::restore() const\n{\n   CopyPointer(ZZ_pInfo, ptr);\n}\n\n\n\nZZ_pBak::~ZZ_pBak()\n{\n   if (MustRestore)\n      CopyPointer(ZZ_pInfo, ptr);\n\n   CopyPointer(ptr, 0);\n}\n\nvoid ZZ_pBak::save()\n{\n   MustRestore = 1;\n   CopyPointer(ptr, ZZ_pInfo);\n}\n\n\nvoid ZZ_pBak::restore()\n{\n   MustRestore = 0;\n   CopyPointer(ZZ_pInfo, ptr);\n}\n\n\nZZ_pTemp::ZZ_pTemp()\n{\n   if (ZZ_pInfo->temps_top == MAX_ZZ_p_TEMPS)\n      Error(\"ZZ_p temporary: out of temps\");\n\n   pos = ZZ_pInfo->temps_top;\n   ZZ_pInfo->temps_top++;\n}\n\nZZ_pTemp::~ZZ_pTemp()\n{\n   ZZ_pInfo->temps_top--;\n}\n\nZZ_p& ZZ_pTemp::val() const\n{\n   if (!ZZ_pInfo->temps[pos]) \n      ZZ_pInfo->temps[pos] = NTL_NEW_OP ZZ_p;\n\n   return *(ZZ_pInfo->temps[pos]);\n}\n\n\n\n\nconst ZZ_p& ZZ_p::zero()\n{\n   static ZZ_p z(ZZ_p_NoAlloc);\n   return z;\n}\n\nZZ_p::DivHandlerPtr ZZ_p::DivHandler = 0;\n\nZZ_p::ZZ_p()\n{\n   _ZZ_p__rep.SetSize(ModulusSize());\n}\n   \n\nZZ_p::ZZ_p(INIT_VAL_TYPE, const ZZ& a) \n{\n   _ZZ_p__rep.SetSize(ModulusSize());\n   conv(*this, a);\n} \n\nZZ_p::ZZ_p(INIT_VAL_TYPE, long a)\n{\n   _ZZ_p__rep.SetSize(ModulusSize());\n   conv(*this, a);\n}\n\n\nvoid conv(ZZ_p& x, long a)\n{\n   if (a == 0)\n      clear(x);\n   else if (a == 1)\n      set(x);\n   else {\n      static ZZ y;\n\n      conv(y, a);\n      conv(x, y);\n   }\n}\n\nistream& operator>>(istream& s, ZZ_p& x)\n{\n   static ZZ y;\n\n   s >> y;\n   conv(x, y);\n\n   return s;\n}\n\nvoid div(ZZ_p& x, const ZZ_p& a, const ZZ_p& b)\n{\n   ZZ_pTemp TT; ZZ_p& T = TT.val(); \n\n   inv(T, b);\n   mul(x, a, T);\n}\n\nvoid inv(ZZ_p& x, const ZZ_p& a)\n{\n   if (InvModStatus(x._ZZ_p__rep, a._ZZ_p__rep, ZZ_p::modulus())) {\n      if (IsZero(a._ZZ_p__rep))\n         Error(\"ZZ_p: division by zero\");\n      else if (ZZ_p::DivHandler)\n         (*ZZ_p::DivHandler)(a);\n      else\n         Error(\"ZZ_p: division by non-invertible element\");\n   }\n}\n\nlong operator==(const ZZ_p& a, long b)\n{\n   if (b == 0)\n      return IsZero(a);\n\n   if (b == 1)\n      return IsOne(a);\n\n   ZZ_pTemp TT; ZZ_p& T = TT.val();\n   conv(T, b);\n   return a == T;\n}\n\n\n\nvoid add(ZZ_p& x, const ZZ_p& a, long b)\n{\n   ZZ_pTemp TT; ZZ_p& T = TT.val();\n   conv(T, b);\n   add(x, a, T);\n}\n\nvoid sub(ZZ_p& x, const ZZ_p& a, long b)\n{\n   ZZ_pTemp TT; ZZ_p& T = TT.val();\n   conv(T, b);\n   sub(x, a, T);\n}\n\nvoid sub(ZZ_p& x, long a, const ZZ_p& b)\n{\n   ZZ_pTemp TT; ZZ_p& T = TT.val();\n   conv(T, a);\n   sub(x, T, b);\n}\n\nvoid mul(ZZ_p& x, const ZZ_p& a, long b)\n{\n   ZZ_pTemp TT; ZZ_p& T = TT.val();\n   conv(T, b);\n   mul(x, a, T);\n}\n\nvoid div(ZZ_p& x, const ZZ_p& a, long b)\n{\n   ZZ_pTemp TT; ZZ_p& T = TT.val();\n   conv(T, b);\n   div(x, a, T);\n}\n\nvoid div(ZZ_p& x, long a, const ZZ_p& b)\n{\n   if (a == 1) {\n      inv(x, b);\n   }\n   else {\n      ZZ_pTemp TT; ZZ_p& T = TT.val();\n      conv(T, a);\n      div(x, T, b);\n   }\n}\n\nNTL_END_IMPL\n", "meta": {"hexsha": "224ff52d2676e7c66c81ed135d8b242562eff0fb", "size": 5877, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "RUNETag/WinNTL/src/ZZ_p.cpp", "max_stars_repo_name": "vshesh/RUNEtag", "max_stars_repo_head_hexsha": "800e93fb7c0560ea5a6261ffc60c02638a8cc8c9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2016-10-17T20:30:05.000Z", "max_stars_repo_stars_event_max_datetime": "2020-03-24T19:52:14.000Z", "max_issues_repo_path": "RUNETag/WinNTL/src/ZZ_p.cpp", "max_issues_repo_name": "vshesh/RUNEtag", "max_issues_repo_head_hexsha": "800e93fb7c0560ea5a6261ffc60c02638a8cc8c9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "RUNETag/WinNTL/src/ZZ_p.cpp", "max_forks_repo_name": "vshesh/RUNEtag", "max_forks_repo_head_hexsha": "800e93fb7c0560ea5a6261ffc60c02638a8cc8c9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2016-07-02T12:59:28.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-02T14:58:30.000Z", "avg_line_length": 15.0306905371, "max_line_length": 69, "alphanum_fraction": 0.5577675685, "num_tokens": 2079, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6893056040203135, "lm_q2_score": 0.46101677931231594, "lm_q1q2_score": 0.3177814495273755}}
{"text": "/* Copyright (c) 2020 C. Pattison\n * All rights reserved.\n * \n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n * \n * 1. Redistributions of source code must retain the above copyright notice, this\n *    list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright notice,\n *    this list of conditions and the following disclaimer in the documentation\n *    and/or other materials provided with the distribution.\n * \n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR\n * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n \n#pragma once\n#include <cassert>\n#include <algorithm>\n#include <utility>\n#include <complex>\n#include <cstdint>\n#include <exception>\n\n#include <Eigen/Dense>\n#include \"syk_types.hpp\"\n#include \"util.hpp\"\n\n/** Utilities for working with a Hamiltonian as a sum of Pauli operators\n */\nnamespace syk {\nusing namespace std::complex_literals;\n\n/** Pauli group\n */\n\nenum class AbstractPauli : short {I = 0, X = 1, Y = 2, Z = 3};\nenum class Sign : short {P = 1, M = -1};\nstruct Pauli { AbstractPauli m; Sign s; };\n\nSign operator*(Sign a, Sign b) {\n    return (a == b) ? Sign::P : Sign::M;\n}\n\nSign operator!(Sign a) {\n    return a * Sign::M;\n}\n\nPauli operator*(Pauli a, Pauli b) {\n    auto new_sign = a.s * b.s;\n    if( !(static_cast<int>(a.m) <= static_cast<int>(b.m)) ) {\n        std::swap(a, b);\n        new_sign = (\n                a.m == AbstractPauli::I \n            ||  b.m == AbstractPauli::I\n            ||  a.m == b.m) ? new_sign : !new_sign;\n    }\n    \n    if (a.m == AbstractPauli::I) { return Pauli {b.m, new_sign}; }\n    if (a.m == b.m) { return Pauli {AbstractPauli::I, new_sign}; }\n    return Pauli {\n        static_cast<AbstractPauli>(3 - (static_cast<int>(a.m) + static_cast<int>(b.m))%3),\n        new_sign};\n}\n\n/** Utilities for construction Hamiltonian as a sum of products of Paulis\n * This has a hard coded maximum number of qubits (20) for performance\n * If/When increased it should be a multiple of 4 to allow vectorization\n * \n * Constructing the full Hamiltonian is done coefficient-wise by going through each term in the sum\n * For each term we stop when we hit a 0\n * This is branch heavy but was about 2x faster than without the branch\n */\nstruct PauliRep {\n    static constexpr int kmax_qubits = 20;\n    using PauliString = std::array<Pauli, kmax_qubits>;\n    using PauliMatrix = Eigen::Matrix<std::complex<short>, 2, 2>;\n\n    struct Term {\n        PauliString pauli_op;\n        double weight;\n    };\n\nprotected:\n    int num_qubits_;\n\npublic:\n    PauliMatrix m_[4];\n\n    PauliRep(int num_qubits) : num_qubits_(num_qubits) {\n        if(num_qubits > kmax_qubits) { throw std::runtime_error(\"Number of qubits exceeds maximum support. Increase the compile time value\"); }\n\n        m_[0] << 1, 0,\n                0, 1;\n\n        m_[1] << 0, 1,  \n                1, 0;\n\n        m_[2] << 0, -1i,\n                1i, 0;\n\n        m_[3] << 1, 0,\n                0, -1;\n    }\n\n    /** Get sign\n     */\n    short repp(Sign a) const __attribute__((always_inline)) {\n        return static_cast<short>(a);\n    }\n\n    /** Get matrix for a one qubit Pauli\n     */\n    const PauliMatrix& repp(AbstractPauli a) const __attribute__((always_inline)) {\n        return m_[static_cast<short>(a)];\n    }\n\n    auto get_repp_factor(Pauli a) const __attribute__((always_inline)) {\n        return repp(a.m) * repp(a.s);\n    }\n\n    Pauli PauliI() const { return Pauli {AbstractPauli::I, Sign::P}; }\n    Pauli PauliX() const { return Pauli {AbstractPauli::X, Sign::P}; }\n    Pauli PauliY() const { return Pauli {AbstractPauli::Y, Sign::P}; }\n    Pauli PauliZ() const { return Pauli {AbstractPauli::Z, Sign::P}; }\n\n    /** Single Pauli matrix element\n     */\n    std::complex<short> get_pauli_element(int i, int j, Pauli p) const __attribute__((always_inline)) {\n        return repp(p.m)(i,j) * repp(p.s);\n    }\n\n    /** Convert a short taking values 0, +/- 1 to double\n     */\n    std::complex<double> zero_one_short_to_double(std::complex<short> a) const {\n        return std::complex<double>(\n            a.real() == 0 ? 0.0 : (a.real() > 0 ? 1.0 : -1.0),\n            a.imag() == 0 ? 0.0 : (a.imag() > 0 ? 1.0 : -1.0)\n        );\n    }\n\n    /** Get matrix element of a string of Paulis\n     * shorts everywhere to hopefully let the compiler do its thing\n     */\n    std::complex<double> get_matrix_element(int i, int j, const PauliString& string) {\n        std::complex<short> acc(1,0);\n        int max_level = num_qubits_ - 1;\n\n        #pragma GCC unroll 4\n        for(int level = 0; level <= max_level; ++level) {\n            int mask = 1 << level;\n            int sub_i = (i & mask) >> level;\n            int sub_j = (j & mask) >> level;\n            acc *= get_pauli_element(sub_i, sub_j, string[level]);\n            if(acc.real() == 0 && acc.imag() == 0) { break; }\n        }\n        return zero_one_short_to_double(acc);\n    }\n\n    /** Compute the Hamiltonian for some sum of terms\n     * Give only the cols/rows specified by subspace\n     * Subspace is usually 0 to (2^N - 1) but could be something else where symmetries exist\n     */\n    MatrixType get_hamiltonian(std::vector<Term> terms, std::vector<std::uint64_t> subspace) {\n        MatrixType hamiltonian = MatrixType::Zero(subspace.size(), subspace.size());\n\n        #pragma omp parallel for\n        for(int j = 0; j < subspace.size(); ++j) {\n            for(int i = 0; i < subspace.size(); ++i) {\n                double matrix_element_re = 0.0;\n                double matrix_element_im = 0.0;\n                auto num_terms = terms.size();\n\n                for(int k = 0; k < num_terms; ++k) {\n                    auto single_element = get_matrix_element(subspace[i], subspace[j], terms[k].pauli_op);\n                    matrix_element_re += terms[k].weight * single_element.real();\n                    matrix_element_im += terms[k].weight * single_element.imag();\n                }\n                hamiltonian(i,j) = std::complex<double>(matrix_element_re, matrix_element_im);\n            }\n        }\n\n        return hamiltonian;\n    }\n};\n}", "meta": {"hexsha": "88d461b0f73876d466751d5a085fb75c56e43a7f", "size": 6859, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/pauli.hpp", "max_stars_repo_name": "ChrisPattison/SYK", "max_stars_repo_head_hexsha": "f62b1e9519daf804409790d01316749d010c0db2", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/pauli.hpp", "max_issues_repo_name": "ChrisPattison/SYK", "max_issues_repo_head_hexsha": "f62b1e9519daf804409790d01316749d010c0db2", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/pauli.hpp", "max_forks_repo_name": "ChrisPattison/SYK", "max_forks_repo_head_hexsha": "f62b1e9519daf804409790d01316749d010c0db2", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.3556701031, "max_line_length": 143, "alphanum_fraction": 0.6225397288, "num_tokens": 1825, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5851011542032312, "lm_q2_score": 0.5428632831725052, "lm_q1q2_score": 0.3176299335587883}}
{"text": "//==============================================================================\n//         Copyright 2003 - 2011 LASMEA UMR 6602 CNRS/Univ. Clermont II\n//         Copyright 2009 - 2011 LRI    UMR 8623 CNRS/Univ Paris Sud XI\n//\n//          Distributed under the Boost Software License, Version 1.0.\n//                 See accompanying file LICENSE.txt or copy at\n//                     http://www.boost.org/LICENSE_1_0.txt\n//==============================================================================\n#ifndef NT2_POLYNOM_FUNCTIONS_EXPR_POLYVAL_HPP_INCLUDED\n#define NT2_POLYNOM_FUNCTIONS_EXPR_POLYVAL_HPP_INCLUDED\n#include <nt2/polynom/functions/polyval.hpp>\n#include <nt2/include/functions/fma.hpp>\n#include <nt2/include/functions/isempty.hpp>\n#include <nt2/include/functions/zeros.hpp>\n#include <nt2/include/functions/repnum.hpp>\n#include <nt2/include/functions/vandermonde.hpp>\n#include <nt2/include/functions/sqrt.hpp>\n#include <nt2/include/functions/sqr.hpp>\n#include <nt2/include/functions/sum.hpp>\n#include <nt2/include/constants/zero.hpp>\n#include <nt2/include/functions/inf.hpp>\n#include <nt2/include/functions/trsolve.hpp>\n#include <nt2/polynom/category.hpp>\n#include <nt2/sdk/meta/fusion.hpp>\n#include <boost/fusion/adapted/array.hpp>\n#include <nt2/include/functions/tie.hpp>\n#include <nt2/include/functions/transpose.hpp>\n#include <nt2/sdk/error/warning.hpp>\n#include <nt2/core/container/table/table.hpp>\n#include <nt2/core/container/colon/colon.hpp>\n\nnamespace nt2 { namespace ext\n{\n   BOOST_DISPATCH_IMPLEMENT  ( polyval_, tag::cpu_\n                            , (A0)(A1)\n                            , (scalar_<unspecified_<A0> > )(scalar_<unspecified_<A1> > )\n                            )\n  {\n\n    typedef A1 result_type;\n    NT2_FUNCTOR_CALL(2)\n    {\n      return a0*a1;\n    }\n  };\n\n  BOOST_DISPATCH_IMPLEMENT  ( polyval_, tag::cpu_\n                            , (A0)(A1)\n                            , (unspecified_<A0>)(scalar_<unspecified_<A1> > )\n                            )\n  {\n\n    typedef typename A0::value_type value_type;\n    typedef A1 result_type;\n    NT2_FUNCTOR_CALL(2)\n    {\n      if (isempty(a0)) return Zero<A1>();\n      value_type ans = a0(1);\n      for(size_t i = 2; i <= numel(a0); ++i)\n      {\n//       ans = fma(ans, a1, a0(i));\n        ans *= a1;\n        ans += a0(i);\n      }\n      return ans;\n    }\n  };\n\n\n  BOOST_DISPATCH_IMPLEMENT  ( polyval_, tag::cpu_\n                              , (A0)(N0)(A1)(N1)\n                              , ((node_<A0, nt2::tag::polyval_, N0, nt2::container::domain>))\n                              ((node_<A1, nt2::tag::tie_ , N1, nt2::container::domain>))\n                            )\n  {\n    typedef void                                                    result_type;\n    typedef typename boost::proto::result_of::child_c<A1&,0>::type       v_type;\n    typedef typename boost::proto::result_of::child_c<A0&,0>::type       p_type;\n    typedef typename boost::proto::result_of::child_c<A0&,1>::type       x_type;\n    typedef typename A0::value_type                                  value_type;\n    BOOST_FORCEINLINE result_type operator()( A0& a0, A1& a1 ) const\n    {\n      // Copy data in output first\n      v_type& v = boost::proto::child_c<0>(a1);\n      v.resize(a0.extent());\n      val(a0, a1, N1(), N0());\n    }\n\n  private:\n    template < class S,  class T, class U> BOOST_FORCEINLINE\n      void compute_val(S p, T x, U v)const\n    {\n      if (isempty(p))\n      {\n        v =  nt2::zeros(extent(x), meta::as_<value_type>());\n      }\n      else\n      {\n        v = repnum(p(1), size(x));\n        for(size_t i = 2; i <= numel(p); ++i)\n        {\n            //          v = fma(v, x, p(i));\n          v*= x;\n          v+= p(i);\n        }\n      }\n    }\n\n    template < class S,  class T, class U,  class V> BOOST_FORCEINLINE\n      void compute_delta(const S& x, const T& r,\n                         const U& df,  const V& normr,\n                         const size_t & nc,\n                         container::table<value_type>& delta)const\n    {\n      NT2_WARNING(nt2::is_eqz(value_type(df)), \"zero degree of freedom implies infinite error bounds.\");\n      BOOST_AUTO_TPL(vnd, nt2::vandermonde(x, nc));\n      BOOST_AUTO_TPL(err, nt2::trsolve(nt2::trans(r), nt2::trans(vnd),'L') );\n      value_type fact =   (normr/nt2::sqrt(value_type(df)));\n      delta(nt2::_) =nt2::sqrt(oneplus(sum(sqr(err),1)))*fact;\n    }\n\n    template < class T > BOOST_FORCEINLINE\n      void val(A0& a0, A1& a1,\n               boost::mpl::long_<1> const &, const T&) const\n    {\n      BOOST_AUTO_TPL(p,  boost::proto::child_c<0>(a0));\n      BOOST_AUTO_TPL(x,  boost::proto::child_c<1>(a0));\n      BOOST_AUTO_TPL(v,  boost::proto::child_c<0>(a1));\n      compute_val(p, x, v);\n    }\n\n    BOOST_FORCEINLINE\n    void val(A0& a0, A1& a1,\n             boost::mpl::long_<1> const &, boost::mpl::long_<3> const &) const\n    {\n      BOOST_AUTO_TPL(p,  boost::proto::child_c<0>(a0));\n      BOOST_AUTO_TPL(x,  boost::proto::child_c<1>(a0));\n      BOOST_AUTO_TPL(v,  boost::proto::child_c<0>(a1));\n      BOOST_AUTO_TPL(mu,  boost::proto::child_c<2>(a0));\n      compute_val(p, (x-mu(1))/mu(2), v);\n    }\n    BOOST_FORCEINLINE\n    void val(A0& a0, A1& a1,\n             boost::mpl::long_<1> const &, boost::mpl::long_<6> const &) const\n    {\n      BOOST_AUTO_TPL(p,  boost::proto::child_c<0>(a0));\n      BOOST_AUTO_TPL(x,  boost::proto::child_c<1>(a0));\n      BOOST_AUTO_TPL(v,  boost::proto::child_c<0>(a1));\n      BOOST_AUTO_TPL(mu,  boost::proto::child_c<5>(a0));\n      compute_val(p, (x-mu(1))/mu(2), v);\n    }\n    BOOST_FORCEINLINE\n    void val(A0& a0, A1& a1,\n             boost::mpl::long_<2> const &, boost::mpl::long_<5> const &) const\n    {\n      BOOST_AUTO_TPL(p,  boost::proto::child_c<0>(a0));\n      BOOST_AUTO_TPL(x,  boost::proto::child_c<1>(a0));\n      BOOST_AUTO_TPL(r,  boost::proto::child_c<2>(a0));\n      BOOST_AUTO_TPL(df, boost::proto::child_c<3>(a0));\n      BOOST_AUTO_TPL(nr, boost::proto::child_c<4>(a0));\n      BOOST_AUTO_TPL(v,  boost::proto::child_c<0>(a1));\n      compute_val(p, x, v);\n      container::table<value_type> delta(extent(x));\n      compute_delta(x, r, df, nr, nt2::numel(p), delta);\n      boost::proto::child_c<1>(a1) = delta;\n    }\n    BOOST_FORCEINLINE\n    void val(A0& a0, A1& a1,\n             boost::mpl::long_<2> const &, boost::mpl::long_<6> const &) const\n    {\n      BOOST_AUTO_TPL(p,  boost::proto::child_c<0>(a0));\n      BOOST_AUTO_TPL(x,  boost::proto::child_c<1>(a0));\n      BOOST_AUTO_TPL(r,  boost::proto::child_c<2>(a0));\n      BOOST_AUTO_TPL(df, boost::proto::child_c<3>(a0));\n      BOOST_AUTO_TPL(nr, boost::proto::child_c<4>(a0));\n      BOOST_AUTO_TPL(v,  boost::proto::child_c<0>(a1));\n      BOOST_AUTO_TPL(mu,  boost::proto::child_c<5>(a0));\n      BOOST_AUTO_TPL(xred, (x-mu(1))/mu(2));\n      compute_val(p, xred, v);\n      container::table<value_type> delta(of_size(extent(x)));\n      delta.resize(extent(x));\n      compute_delta(xred, r, df, nr, nt2::numel(p), delta);\n      boost::proto::child_c<1>(a1) = delta;\n    }\n\n  };\n} }\n\n\n#endif\n", "meta": {"hexsha": "0f1f5f48a20154ac8697eda5840f423ceaf44d4a", "size": 7041, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/core/polynom/include/nt2/polynom/functions/expr/polyval.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/polynom/include/nt2/polynom/functions/expr/polyval.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/polynom/include/nt2/polynom/functions/expr/polyval.hpp", "max_forks_repo_name": "psiha/nt2", "max_forks_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2017-12-02T12:59:17.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-31T12:46:14.000Z", "avg_line_length": 36.8638743455, "max_line_length": 104, "alphanum_fraction": 0.5615679591, "num_tokens": 2038, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6113819874558603, "lm_q2_score": 0.519521321952093, "lm_q1q2_score": 0.31762597834076645}}
{"text": "#include \"sandBox.h\"\n#include \"igl/edge_flaps.h\"\n#include \"igl/collapse_edge.h\"\n#include \"Eigen/dense\"\n#include <functional>\n#include <Eigen/Core>\n#include \"igl/opengl/ViewerCore.h\"\n#include \"igl/opengl/glfw/renderer.h\"\n#include \"igl/decimate.h\"\n#include \"igl/writeOBJ.h\"\n#include <igl/circulation.h>\n#include <igl/shortest_edge_and_midpoint.h>\n#include <igl/parallel_for.h>\n#include <igl/opengl/glfw/Viewer.h>\n#include <set>\n#include \"simplifier.h\"\n#include \"igl/swept_volume_bounding_box.h\"\n\n\nSandBox::SandBox() \n\t: \n\tobjectsData{ new std::vector<ObjectData*>{} }, \n\tlinksCounter{ 0 }, destIndex{ 0 }, \n\tfirstLinkIndex{ 1 }, \n\tlastLinkIndex{ 1 }, \n\tisCCD{ false },\n\txVelocity{-0.005},\n\tyVelocity{ 0 }\n{\n\n}\n\nSandBox::~SandBox()\n{\n    delete objectsData;\n}\n\nvoid SandBox::OnNewMeshLoad()\n{\n\tif (linksCounter > 0)\n\t{\n\t\tdata().MyTranslate(Eigen::Vector3d(0, 1.6, 0), true);\n\t\tparents.push_back(linksCounter);\n\t}\n\telse\n\t{\n\t\tparents.push_back(-1);\n\t}\n\n\tdata().add_points(Eigen::RowVector3d(0, 0, 0), Eigen::RowVector3d(0, 0, 1));\n\tdata().show_overlay_depth = false;\n\tdata().point_size = 10;\n\tdata().line_width = 2;\n\tdata().set_visible(true, 2);\n\tdata().show_faces = 3;\n\tdata().show_texture = 2;\n\n\tdata().dirty = 157; //this line prevents texture coordinates\n\tdata().MyScale(Eigen::Vector3d(1, 1, 1));\n\tdata().SetCenterOfRotation(Eigen::Vector3d(0, -0.8, 0));\n\n\tEigen::MatrixXd axis(7, 3);\n\taxis << 0, -0.8, 0, 0, -0.8, 1.6, 0, -0.8, -1.6, 0, 0.8, 0, 0, -2.4, 0, -1.6, -0.8, 0, 1.6, -0.8, 0;\n\tdata().add_points(axis, Eigen::RowVector3d(0, 0, 1));\n \tdata().add_edges(axis.row(0), axis.row(1), Eigen::RowVector3d(0, 0, 1));\n\tdata().add_edges(axis.row(0), axis.row(2), Eigen::RowVector3d(0, 0, 1));\n\tdata().add_edges(axis.row(0), axis.row(3), Eigen::RowVector3d(0, 1, 0));\n\tdata().add_edges(axis.row(0), axis.row(4), Eigen::RowVector3d(0, 1, 0));\n\tdata().add_edges(axis.row(0), axis.row(5), Eigen::RowVector3d(1, 0, 0));\n\tdata().add_edges(axis.row(0), axis.row(6), Eigen::RowVector3d(1, 0, 0));\n\n\tObjectData* od = new ObjectData();\n\tInitObjectData(*od, data().V, data().F);\n\tobjectsData->push_back(od);\n\tdata().AddBoundingBox(od->tree->m_box, Eigen::RowVector3d(0, 1, 0));\n\n \tlinksCounter++;\n\tlastLinkIndex = linksCounter;\n}\n\nvoid SandBox::Init(const std::string &config)\n{\n\tstd::string item_name;\n\tstd::ifstream nameFileout;\n\tnameFileout.open(config);\n\n\tif (!nameFileout.is_open())\n\t{\n\t\tstd::cout << \"Can't open file \" << config << std::endl;\n\t}\n\telse\n\t{\n\t\twhile (nameFileout >> item_name)\n\t\t{\n\t\t\tstd::cout << \"openning \" << item_name << std::endl;\n\t\t\tload_mesh_from_file(item_name);\n\n\t\t\tif (item_name.find(\"sphere\") != std::string::npos)\n\t\t\t{\n\t\t\t\tparents.push_back(-1);\n\t\t\t\tdata().add_points(Eigen::RowVector3d(0, 0, 0), Eigen::RowVector3d(0, 0, 1));\n\t\t\t\tdata().show_overlay_depth = false;\n\t\t\t\tdata().point_size = 10;\n\t\t\t\tdata().line_width = 2;\n\t\t\t\tdata().set_visible(false, 1);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tif (linksCounter > 0)\n\t\t\t\t{\n\t\t\t\t\tdata().MyTranslate(Eigen::Vector3d(0, 1.6, 0), true);\n\t\t\t\t\tparents.push_back(linksCounter);\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tparents.push_back(-1);\n\t\t\t\t}\n\n\t\t\t\tdata().add_points(Eigen::RowVector3d(0, 0, 0), Eigen::RowVector3d(0, 0, 1));\n\t\t\t\tdata().show_overlay_depth = false;\n\t\t\t\tdata().point_size = 10;\n\t\t\t\tdata().line_width = 2;\n\t\t\t\tdata().set_visible(false, 1);\n\n\t\t\t\tdata().dirty = 157; //this line prevents texture coordinates\n\t\t\t\tdata().MyScale(Eigen::Vector3d(1, 1, 1));\n\t\t\t\tdata().SetCenterOfRotation(Eigen::Vector3d(0, -0.8, 0));\n\n\t\t\t\tEigen::MatrixXd axis(7, 3);\n\t\t\t\taxis << \n\t\t\t\t\t   0, -0.8,    0, \n\t\t\t\t\t   0, -0.8,  1.6, \n\t\t\t\t\t   0, -0.8,\t-1.6, \n\t\t\t\t\t   0,  0.8,\t   0, \n\t\t\t\t\t   0, -2.4,    0, \n\t\t\t\t\t-1.6, -0.8,    0, \n\t\t\t\t\t 1.6, -0.8,\t   0;\n\n\t\t\t\tdata().add_points(axis, Eigen::RowVector3d(0, 0, 1));\n\t\t\t\tdata().add_edges(axis.row(0), axis.row(1), Eigen::RowVector3d(0, 0, 1));\n\t\t\t\tdata().add_edges(axis.row(0), axis.row(2), Eigen::RowVector3d(0, 0, 1));\n\t\t\t\tdata().add_edges(axis.row(0), axis.row(3), Eigen::RowVector3d(0, 1, 0));\n\t\t\t\tdata().add_edges(axis.row(0), axis.row(4), Eigen::RowVector3d(0, 1, 0));\n\t\t\t\tdata().add_edges(axis.row(0), axis.row(5), Eigen::RowVector3d(1, 0, 0));\n\t\t\t\tdata().add_edges(axis.row(0), axis.row(6), Eigen::RowVector3d(1, 0, 0));\n\n\t\t\t\tObjectData* od = new ObjectData();\n\t\t\t\tInitObjectData(*od, data().V, data().F);\n\t\t\t\tobjectsData->push_back(od);\n\t\t\t\tdata().AddBoundingBox(od->tree->m_box, Eigen::RowVector3d(0, 1, 0));\n\n\t\t\t\tlinksCounter++;\n\t\t\t}\n\t\t}\n\t\tlastLinkIndex = linksCounter;\n\t\tnameFileout.close();\n\t}\n\tdata().set_colors(Eigen::RowVector3d(0.9, 0.1, 0.1));\n\tisActive = false;\n}\n\nvoid SandBox::InitObjectData(ObjectData& od, Eigen::MatrixXd& V, Eigen::MatrixXi& F)\n{\n    \n    od.V = new Eigen::MatrixXd(V);\n    od.F = new Eigen::MatrixXi(F);\n    od.E = new Eigen::MatrixXi();\n    od.EF = new Eigen::MatrixXi();\n    od.EI = new Eigen::MatrixXi();\n    od.EMAP = new Eigen::VectorXi();\n    od.Q = new PriorityQueue();\n    od.num_collapsed = 0;\n    od.tree = new igl::AABB<Eigen::MatrixXd, 3>{};\n\n    igl::edge_flaps(*od.F, *od.E, *od.EMAP, *od.EF, *od.EI);\n\n    od.tree->init(*od.V, *od.F);\n\n    od.C = new Eigen::MatrixXd(od.E->rows(), od.V->cols());\n\n    ComputeNormals(od, data());\n\n    ComputeQMatrices(od);\n\n    ComputePriorityQueue(od);\n}\n\nvoid SandBox::ReInitObjectData(ObjectData& od)\n{\n    Eigen::MatrixXd V = *od.V; \n    Eigen::MatrixXi F = *od.F;\n\n    // Remove old object data\n    ObjectData* odToRemove = objectsData->at(selected_data_index);\n    ClearObjectData(*odToRemove);\n    delete odToRemove;\n\n    // Add new object data after collapsing edges \n    ObjectData* odToAdd = new ObjectData();\n    InitObjectData(*odToAdd, V, F);\n    objectsData->at(selected_data_index) = odToAdd;\n}\n\nvoid SandBox::ClearObjectData(ObjectData& od)\n{\n    delete od.V;\n    delete od.F;\n    delete od.EMAP;\n    delete od.E;\n    delete od.EF;\n    delete od.EI;\n    delete od.Q;\n    delete od.C;\n    delete od.F_NORMALS;\n\n    std::for_each(od.QMATRICES.begin(), od.QMATRICES.end(), [](Eigen::Matrix4d* m) -> void { delete m; });\n    od.QMATRICES.clear();\n}\n\nvoid SandBox::Simplify()\n{\n    ObjectData* objectToSimplify = objectsData->at(selected_data_index);\n    int num_to_collapse = std::ceil(0.05 * objectToSimplify->Q->size());\n    Simplify(num_to_collapse, *objectToSimplify);\n}\n\nvoid SandBox::Simplify(int num_to_collapse, ObjectData& od)\n{\n\n    if (!od.Q->empty())\n    {\n        bool something_collapsed = false;\n        for (int j = 0; j < num_to_collapse; j++)\n        {\n              if (!collapse_edge(od))\n            {\n                break;\n            }\n            something_collapsed = true;\n            od.num_collapsed++;\n        }\n         \n        if (something_collapsed)\n        {\n            data().clear();\n            data().set_mesh(*od.V, *od.F);\n            data().set_face_based(true);\n            data().dirty = 157; //this line prevents texture coordinates\n            ReInitObjectData(od);\n        }\n    }\n}\n\nvoid SandBox::MoveTo(double x, double y)\n{\n    data().TranslateInSystem(GetRotation(), Eigen::Vector3d(x, 0, 0));\n    data().TranslateInSystem(GetRotation(), Eigen::Vector3d(0, y, 0));\n    WhenTranslate();\n}\n\nvoid SandBox::Animate()\n{\n\tif (isActive)\n\t{\n\t\t\n\t\tif (isCCD)\n\t\t{\n\t\t\tIK_CCD();\n\t\t}\n\t\telse\n\t\t{\n\t\t\tIK_FABRIK();\n\t\t}\n\t}\n}\n\nbool SandBox::ObjectsCollide(igl::AABB<Eigen::MatrixXd, 3>* firstTree, igl::AABB<Eigen::MatrixXd, 3>* secondTree)\n{\n\tif (firstTree == nullptr || secondTree == nullptr)\n\t{\n\t\treturn false;\n\t}\n \tif (BoxesIntersect(firstTree->m_box, secondTree->m_box)) {\n\t\tif (firstTree->is_leaf() && secondTree->is_leaf())\n\t\t{\n\t\t\tdata_list.at(0).AddBoundingBox(firstTree->m_box, Eigen::RowVector3d(0, 1, 0));\n\t\t\tdata_list.at(1).AddBoundingBox(secondTree->m_box, Eigen::RowVector3d(0, 1, 0));\n\t\t\treturn true;\n\t\t}\n\t\telse if (!firstTree->is_leaf() && secondTree->is_leaf())\n\t\t{\n\t\t\treturn\tObjectsCollide(firstTree->m_left, secondTree) ||\n\t\t\t\t\tObjectsCollide(firstTree->m_right, secondTree);\n\t\t}\n\t\telse if (firstTree->is_leaf() && !secondTree->is_leaf())\n\t\t{\n\n\t\t\treturn  ObjectsCollide(firstTree, secondTree->m_left) ||\n\t\t\t\t\tObjectsCollide(firstTree, secondTree->m_right);\n\t\t}\n\t\telse if (!firstTree->is_leaf() && !secondTree->is_leaf())\n\t\t{\n\t\t\treturn  ObjectsCollide(firstTree->m_left, secondTree->m_left) ||\n\t\t\t\t\tObjectsCollide(firstTree->m_left, secondTree->m_right) ||\n\t\t\t\t\tObjectsCollide(firstTree->m_right, secondTree->m_left) ||\n\t\t\t\t\tObjectsCollide(firstTree->m_right, secondTree->m_right);\n\t\t}\n\t}\n\treturn false;\n}\n\nbool SandBox::BoxesIntersect(Eigen::AlignedBox <double, 3>& firstBox, Eigen::AlignedBox <double, 3>& secondBox)\n{\n\tEigen::Matrix4d firstTrans = data_list.at(0).MakeTransd();\n\tEigen::Matrix4d secondTrans = data_list.at(1).MakeTransd();\n\t \n\tEigen::Vector3d firstBoxCenter = firstBox.center();\n\tEigen::Vector3d secondBoxCenter = secondBox.center();\n\n\tEigen::Vector4d firstCenter = firstTrans * Eigen::Vector4d(firstBoxCenter(0), firstBoxCenter(1), firstBoxCenter(2), 1);\n\tEigen::Vector4d secondCenter = secondTrans * Eigen::Vector4d(secondBoxCenter(0), secondBoxCenter(1), secondBoxCenter(2), 1);\n\n\tEigen::Vector3d C0(firstCenter(0), firstCenter(1), firstCenter(2));\n\tEigen::Vector3d C1(secondCenter(0), secondCenter(1), secondCenter(2));\n\n\tEigen::Vector3d D = C1 - C0;\n\n\tEigen::Matrix3d A = data_list.at(0).GetRotation();\n\tEigen::Matrix3d B = data_list.at(1).GetRotation();\n\n\tEigen::Matrix3d A_matrix;\n\tA_matrix << A(0, 0), A(1, 0), A(2, 0),\n\t\t\t\tA(0, 1), A(1, 1), A(2, 1),\n\t\t\t\tA(0, 2), A(1, 2), A(2, 2);\n\n\tEigen::Matrix3d B_matrix;\n\tB_matrix << B(0, 0), B(1, 0), B(2, 0),\n\t\t\t\tB(0, 1), B(1, 1), B(2, 1),\n\t\t\t\tB(0, 2), B(1, 2), B(2, 2);\n\n\tEigen::RowVector3d a;\n\ta << firstBox.sizes()(0) / 2, firstBox.sizes()(1) / 2, firstBox.sizes()(2) / 2;\n\n\tEigen::RowVector3d b;\n\tb << secondBox.sizes()(0) / 2, secondBox.sizes()(1) / 2, secondBox.sizes()(2) / 2;\n\n\tEigen::Matrix3d C = A.transpose() * B;\n\n\tdouble R0, R1, R;\n\n\t// L = A0\n\tR0 = a(0);\n\tR1 = b(0) * abs(C(0, 0)) + b(1) * abs(C(0, 1)) + b(2) * abs(C(0, 2));\n\tR = (A_matrix.row(0) * D).norm();\n\tif (R > R0 + R1) return false;\n\n\t// L = A1\n\tR0 = a(1);\n\tR1 = b(0) * abs(C(1, 0)) + b(1) * abs(C(1, 1)) + b(2) * abs(C(1, 2));\n\tR = (A_matrix.row(1) * D).norm();\n\tif (R > R0 + R1) return false;\n\n\t// L = A2\n\tR0 = a(2);\n\tR1 = b(0) * abs(C(2, 0)) + b(1) * abs(C(2, 1)) + b(2) * abs(C(2, 2));\n\tR = (A_matrix.row(2) * D).norm();\n\tif (R > R0 + R1) return false;\n\n\t// L = B0\n\tR0 = a(0) * abs(C(0, 0)) + a(1) * abs(C(1, 0)) + a(2) * abs(C(2, 0));\n\tR1 = b(0);\n\tR = (B_matrix.row(0) * D).norm();\n\tif (R > R0 + R1) return false;\n\n\t// L = B1\n\tR0 = a(0) * abs(C(0, 1)) + a(1) * abs(C(1, 1)) + a(2) * abs(C(2, 1));\n\tR1 = b(1);\n\tR = (B_matrix.row(1) * D).norm();\n\tif (R > R0 + R1) return false;\n\n\t// L = B2\n\tR0 = a(0) * abs(C(0, 2)) + a(1) * abs(C(1, 2)) + a(2) * abs(C(2, 2));\n\tR1 = b(2);\n\tR = (B_matrix.row(2) * D).norm();\n\tif (R > R0 + R1) return false;\n\n\t// L = A0 x B0\n\tR0 = a(1) * abs(C(2, 0)) + a(2) * abs(C(1, 0));\n\tR1 = b(1) * abs(C(0, 2)) + b(2) * abs(C(0, 1));\n\tR = (C(1, 0) * A_matrix.row(2) * D - C(2, 0) * A_matrix.row(1) * D).norm();\n\tif (R > R0 + R1) return false;\n\n\t// L = A0 x B1\n\tR0 = a(1) * abs(C(2, 1)) + (a(2))*abs(C(1, 1));\n\tR1 = b(0) * abs(C(0, 2)) + b(2) * abs(C(0, 0));\n\tR = (C(1, 1) * A_matrix.row(2) * D - C(2, 1) * A_matrix.row(1) * D).norm();\n\tif (R > R0 + R1) return false;\n\n\t// L = A0 x B2\n\tR0 = a(1) * abs(C(2, 2)) + a(2) * abs(C(1, 2));\n\tR1 = b(0) * abs(C(0, 1)) + b(1) * abs(C(0, 0));\n\tR = (C(1, 2) * A_matrix.row(2) * D - C(2, 2) * A_matrix.row(1) * D).norm();\n\tif (R > R0 + R1) return false;\n\n\t// L = A1 x B0\n\tR0 = a(0) * abs(C(2, 0)) + a(2) * abs(C(0, 0));\n\tR1 = b(1) * abs(C(1, 2)) + b(2) * abs(C(1, 1));\n\tR = (C(2, 0) * A_matrix.row(0) * D - C(0, 0) * A_matrix.row(2) * D).norm();\n\tif (R > R0 + R1) return false;\n\n\t// L = A1 x B1\n\tR0 = a(0) * abs(C(2, 1)) + a(2) * abs(C(0, 1));\n\tR1 = b(0) * abs(C(1, 2)) + b(2) * abs(C(1, 0));\n\tR = (C(2, 1) * A_matrix.row(0) * D - C(0, 1) * A_matrix.row(2) * D).norm();\n\tif (R > R0 + R1) return false;\n\n\t/// L = A1 x B2\n\tR0 = a(0) * abs(C(2, 2)) + a(2) * abs(C(0, 2));\n\tR1 = b(0) * abs(C(1, 1)) + b(1) * abs(C(1, 0));\n\tR = (C(2, 2) * A_matrix.row(0) * D - C(0, 2) * A_matrix.row(2) * D).norm();\n\tif (R > R0 + R1) return false;\n\n\t// L = A2 x B0\n\tR0 = a(0) * abs(C(1, 0)) + a(1) * abs(C(0, 0));\n\tR1 = b(1) * abs(C(2, 2)) + b(2) * abs(C(2, 1));\n\tR = (C(0, 0) * A_matrix.row(1) * D - C(1, 0) * A_matrix.row(0) * D).norm();\n\tif (R > R0 + R1) return false;\n\n\t// L = A2 x B1\n\tR0 = a(0) * abs(C(1, 1)) + a(1) * abs(C(0, 1));\n\tR1 = b(0) * abs(C(2, 2)) + b(2) * abs(C(2, 0));\n\tR = (C(0, 1) * A_matrix.row(1) * D - C(1, 1) * A_matrix.row(0) * D).norm();\n\tif (R > R0 + R1) return false;\n\n\t// L = A2 x B2\n\tR0 = a(0) * abs(C(1, 2)) + a(1) * abs(C(0, 2));\n\tR1 = b(0) * abs(C(2, 1)) + b(1) * abs(C(2, 0));\n\tR = (C(0, 2) * A_matrix.row(1) * D - C(1, 2) * A_matrix.row(0) * D).norm();\n\tif (R > R0 + R1) return false;\n\treturn true;\n}\n\nvoid SandBox::SetVelocity(double x, double y)\n{\n\txVelocity = x;\n\tyVelocity = y;\n}\n\nvoid  SandBox::IK_CCD()\n{\n\tEigen::Matrix4d destTrans = data_list[destIndex].MakeTransd();\n\tEigen::Matrix4d firstTrans = data_list[firstLinkIndex].MakeTransd();\n\tEigen::Matrix4d lastTrans = data_list[lastLinkIndex].MakeTransd();\n\tEigen::Matrix4d lastParentsTrans = CalcParentsTrans(lastLinkIndex);\n\n\tEigen::Vector4d lowerTip(0, -0.8, 0, 1);\n\tEigen::Vector4d upperTip(0, 0.8, 0, 1);\n\n\tEigen::Vector3d dst = ExtractPosition(destTrans * Eigen::Vector4d(0, 0, 0, 1));\n\tEigen::Vector3d src = ExtractPosition(firstTrans * lowerTip);\n\tEigen::Vector3d tip = ExtractPosition(lastParentsTrans * lastTrans * upperTip).transpose();\n\n\tdouble distToDest = (dst - tip).norm();\n\tdouble absDistance = (dst - src).norm();\n\tdouble maxReach = linksCounter * 1.6;\n\tdouble threshold = 0.1;\n\n\tstd::cout << distToDest << std::endl;\n\n\tif (maxReach < absDistance) \n\t{\n\t\tstd::cout << \"Cant reach\" << std::endl;\n\t\tisActive = false;\n\t\treturn;\n\t}\n\n\tif (distToDest < threshold)\n\t{\n\t\tstd::cout << \"Reached\" << std::endl;\n\t\tisActive = false;\n\t\treturn;\n\t}\n\n\tfor (int i = firstLinkIndex + lastLinkIndex - 1; i >= firstLinkIndex; i--) \n\t{\n\t\tEigen::Matrix4d iParentsTrans = CalcParentsTrans(i);\n\t\tEigen::Matrix4d iTrans = data_list[i].MakeTransd();\n\t\tEigen::Vector3d D = dst;\n\t\tEigen::Vector3d R = ExtractPosition(iParentsTrans * iTrans * lowerTip);\n\t\tEigen::Vector3d E = ExtractPosition(lastParentsTrans * lastTrans * upperTip);\n\t\tEigen::Vector3d RD = D - R;\n\t\tEigen::Vector3d RE = E - R;\n\t\tfloat RD_dot_RE = RD.normalized().dot(RE.normalized());\n\t\tif (abs(RD_dot_RE) > 1)\n\t\t{\n\t\t\tstd::cout << \"Dot product greater then |1|, rounding value\" << std::endl;\n\t\t\tRD_dot_RE = RD_dot_RE > 0 ? 1 : -1;\n\t\t}\n\t\tdouble theta = acosf(RD_dot_RE);\n\t\tEigen::Matrix3d m = iParentsTrans.inverse().block(0, 0, 3, 3);\n\t\tEigen::Vector3d rotAxis = m * RD.cross(RE);\n\t\ttheta = theta / 10; // Smooth the rotation\n\t\tdata_list[i].MyRotate(rotAxis, -theta);\n\t}\n}\n\nvoid  SandBox::IK_FABRIK()\n{\n\tint n = linksCounter + 1;\n\tfloat di = 1.6;\n\n\tEigen::Matrix4d destTrans = data_list[destIndex].MakeTransd();\n\tEigen::Matrix4d firstTrans = data_list[firstLinkIndex].MakeTransd();\n\tEigen::Matrix4d lastTrans = data_list[lastLinkIndex].MakeTransd();\n\tEigen::Matrix4d lastParentsTrans = CalcParentsTrans(lastLinkIndex);\n\n\tEigen::Vector4d lowerTip(0, -0.8, 0, 1);\n\tEigen::Vector4d upperTip(0, 0.8, 0, 1);\n\n\tEigen::Vector3d t = ExtractPosition(destTrans * Eigen::Vector4d(0, 0, 0, 1));\n\tEigen::Vector3d p1 = ExtractPosition(firstTrans * lowerTip);\n\tEigen::Vector3d pn = ExtractPosition(lastParentsTrans * lastTrans * upperTip).transpose();\n\n\tfloat dist = (p1 - t).norm();\n\n\tif (dist > di * (n - 1))\n\t{\n\t\tstd::cout << \"The target is unreachable\" << std::endl;\n\t\tisActive = false;\n\t\treturn;\n\t}\n\n\tfloat difA = (pn - t).norm();\n\tfloat tol = 0.1;\n\n\tstd::cout << difA << std::endl;\n\n\tif (difA <= tol)\n\t{\n\t\tstd::cout << \"Reached target\" << std::endl;\n\t\tisActive = false;\n\t\treturn;\n\t}\n\n\tstd::vector<Eigen::Vector3d> p;\n\tp.push_back(Eigen::Vector3d::Identity()); // Dummy\n\tp.push_back(p1);\n\tfor (int i = 1; i <= linksCounter; i++)\n\t{\n\t\tp.push_back(ExtractPosition(data_list.at(i).MakeTransd() * CalcParentsTrans(i) * upperTip));\n\t}\n\n\tEigen::Vector3d b = p.at(1);\n\n\t// FORWARD REACHING\n\tp.at(n) = t;\n\n\tfor (int i = n - 1; i >= 1; i--)\n\t{\n\t\tEigen::Vector3d pi = p.at(i);\n\t\tEigen::Vector3d pi1 = p.at(i + 1);\n\t\tfloat ri = (pi1 - pi).norm();\n\t\tfloat li = di / ri;\n\t\tp.at(i) = ((1 - li) * pi1) + (li * pi);\n\t}\n\n\t// BACKWARD REACHING\n\tp.at(1) = b;\n\n\tfor (int i = 1; i <= n - 1; i++)\n\t{\n\t\tEigen::Vector3d pi = p.at(i);\n\t\tEigen::Vector3d pi1 = p.at(i + 1);\n\t\tfloat ri = (pi1 - pi).norm();\n\t\tfloat li = di / ri;\n\t\tp.at(i + 1) = ((1 - li) * pi) + (li * pi1);\n\t}\n\n\t// UPDATE JOINTS POSITIONS\n\tfor (int i = 1; i <= linksCounter; i++)\n\t{\n\t\tEigen::Matrix4d iParentsTrans = CalcParentsTrans(i);\n\t\tEigen::Matrix4d iTrans = data_list.at(i).MakeTransd();\n\t\tEigen::Vector3d D = p.at(i + 1);\n\t\tEigen::Vector3d R = ExtractPosition(iParentsTrans * iTrans * lowerTip);\n\t\tEigen::Vector3d E = ExtractPosition(iParentsTrans * iTrans * upperTip);\n\t\tEigen::Vector3d RD = D - R;\n\t\tEigen::Vector3d RE = E - R;\n\n\t\tEigen::Vector3d axis = RD.cross(RE).normalized();\n\t\tfloat RD_dot_RE = RD.normalized().dot(RE.normalized());\n\t\tif (abs(RD_dot_RE) > 1)\n\t\t{\n\t\t\tstd::cout << \"Dot product greater then |1|, rounding value\" << std::endl;\n\t\t\tRD_dot_RE = RD_dot_RE > 0 ? 1 : -1;\n\t\t}\n\t\tfloat theta = acosf(RD_dot_RE);\n\t\tEigen::Matrix4d m = iParentsTrans.inverse();\n\t\tEigen::Matrix3d m1;\n\t\tm1 <<\n\t\t\tm(0, 0), m(0, 1), m(0, 2),\n\t\t\tm(1, 0), m(1, 1), m(1, 2),\n\t\t\tm(2, 0), m(2, 1), m(2, 2);\n\n\t\tEigen::Vector3d rotAxis = m1 * RD.cross(RE);\n\t\ttheta = theta / 10; // Smooth the rotation\n\t\tdata_list.at(i).MyRotate(rotAxis, -theta);\n\t}\n}\n\nEigen::Vector3d SandBox::ExtractPosition(Eigen::Vector4d m)\n{\n\treturn Eigen::Vector3d(m(0), m(1), m(2));\n}\n\t", "meta": {"hexsha": "6087d828df2671824157b488e8dac6153af449d7", "size": 17725, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tutorial/sandBox/sandBox.cpp", "max_stars_repo_name": "danatzmi/Animation-Assignment3", "max_stars_repo_head_hexsha": "a9a9414c50c39d4c4048b6e3930774d3b0a55655", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tutorial/sandBox/sandBox.cpp", "max_issues_repo_name": "danatzmi/Animation-Assignment3", "max_issues_repo_head_hexsha": "a9a9414c50c39d4c4048b6e3930774d3b0a55655", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tutorial/sandBox/sandBox.cpp", "max_forks_repo_name": "danatzmi/Animation-Assignment3", "max_forks_repo_head_hexsha": "a9a9414c50c39d4c4048b6e3930774d3b0a55655", "max_forks_repo_licenses": ["Apache-2.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.8211382114, "max_line_length": 125, "alphanum_fraction": 0.6002820874, "num_tokens": 6657, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.611381973294151, "lm_q2_score": 0.519521321952093, "lm_q1q2_score": 0.3176259709834566}}
{"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 \"math/sparse_cholesky_llt.h\"\n\n#include <cholmod.h>\n#include <glog/logging.h>\n\n#include <Eigen/Core>\n#include <Eigen/SparseCore>\n\n// UF_long is deprecated but SuiteSparse_long is only available in\n// newer versions of SuiteSparse. So for older versions of\n// SuiteSparse, we define SuiteSparse_long to be the same as UF_long,\n// which is what recent versions of SuiteSparse do anyways.\n#ifndef SuiteSparse_long\n#define SuiteSparse_long UF_long\n#endif\n\nnamespace DAGSfM {\nnamespace {\n\ncholmod_sparse ViewAsCholmod(const Eigen::SparseMatrix<double>& const_mat) {\n  Eigen::SparseMatrix<double>& mat =\n      const_cast<Eigen::SparseMatrix<double>&>(const_mat);\n  cholmod_sparse res;\n  res.nzmax = mat.nonZeros();\n  res.nrow = mat.rows();\n  res.ncol = mat.cols();\n  res.p = mat.outerIndexPtr();\n  res.i = mat.innerIndexPtr();\n  res.x = mat.valuePtr();\n  res.sorted = 1;\n  if (mat.isCompressed()) {\n    res.packed = 1;\n  } else {\n    res.packed = 0;\n    res.nz = mat.innerNonZeroPtr();\n  }\n\n  // Set to 0 if the matrix is not symmetric.\n  res.stype = 1;\n  res.itype = CHOLMOD_INT;\n  res.xtype = CHOLMOD_REAL;\n  res.dtype = CHOLMOD_DOUBLE;\n  return res;\n}\n\ncholmod_dense ViewAsCholmod(const Eigen::VectorXd& const_vec) {\n  Eigen::VectorXd& vec = const_cast<Eigen::VectorXd&>(const_vec);\n  cholmod_dense res;\n  res.nrow = vec.rows();\n  res.ncol = vec.cols();\n  res.nzmax = res.nrow * res.ncol;\n  res.d = vec.size();\n  res.x = reinterpret_cast<void*>(vec.data());\n  res.z = 0;\n  res.xtype = CHOLMOD_REAL;\n  return res;\n}\n}  // namespace\n\n// A class for performing the choleksy decomposition of a sparse matrix using\n// CHOLMOD from SuiteSparse. This allows us to utilize the supernodal algorithms\n// which are not included with Eigen. The interface is meant to mimic the Eigen\n// linear solver interface except that it is not templated and requires sparse\n// matrices.\nSparseCholeskyLLt::SparseCholeskyLLt(const Eigen::SparseMatrix<double>& mat)\n    : cholmod_factor_(nullptr),\n      is_factorization_ok_(false),\n      is_analysis_ok_(false),\n      info_(Eigen::Success) {\n  cholmod_start(&cc_);\n  Compute(mat);\n}\n\nSparseCholeskyLLt::SparseCholeskyLLt()\n    : cholmod_factor_(nullptr),\n      is_factorization_ok_(false),\n      is_analysis_ok_(false),\n      info_(Eigen::Success) {\n  cholmod_start(&cc_);\n}\n\nSparseCholeskyLLt::~SparseCholeskyLLt() {\n  if (cholmod_factor_ != nullptr) {\n    cholmod_free_factor(&cholmod_factor_, &cc_);\n  }\n  cholmod_finish(&cc_);\n}\n\nvoid SparseCholeskyLLt::AnalyzePattern(const Eigen::SparseMatrix<double>& mat) {\n  // Release the current decomposition if there is one.\n  if (cholmod_factor_ != nullptr) {\n    cholmod_free_factor(&cholmod_factor_, &cc_);\n  }\n\n  // Get the cholmod view of the sparse matrix.\n  cholmod_sparse A = ViewAsCholmod(mat);\n\n  // Cholmod can try multiple re-ordering strategies to find a fill\n  // reducing ordering. Here we just tell it use AMD with automatic\n  // matrix dependence choice of supernodal versus simplicial\n  // factorization.\n  cc_.nmethods = 1;\n  cc_.method[0].ordering = CHOLMOD_AMD;\n  cc_.supernodal = CHOLMOD_AUTO;\n\n  // Perform symbolic analysis of the matrix.\n  cholmod_factor_ = cholmod_analyze(&A, &cc_);\n  if (VLOG_IS_ON(2)) {\n    cholmod_print_common(const_cast<char*>(\"Symbolic Analysis\"), &cc_);\n  }\n\n  if (cc_.status != CHOLMOD_OK) {\n    VLOG(2) << \"cholmod_analyze failed. error code: %d\" << cc_.status;\n    info_ = Eigen::NumericalIssue;\n    return;\n  }\n\n  is_analysis_ok_ = true;\n  is_factorization_ok_ = false;\n  info_ = Eigen::Success;\n}\n\nvoid SparseCholeskyLLt::Factorize(const Eigen::SparseMatrix<double>& mat) {\n  CHECK_NOTNULL(cholmod_factor_);\n  CHECK(is_analysis_ok_) << \"Cannot call Factorize() because symbolic analysis \"\n                            \"of the matrix (i.e. AnalyzePattern()) failed!\";\n  cholmod_sparse A = ViewAsCholmod(mat);\n\n  // Save the current print level and silence CHOLMOD, otherwise\n  // CHOLMOD is prone to dumping stuff to stderr, which can be\n  // distracting when the error (matrix is indefinite) is not a fatal\n  // failure.\n  const int old_print_level = cc_.print;\n  cc_.print = 0;\n\n  cc_.quick_return_if_not_posdef = 1;\n  int cholmod_status = cholmod_factorize(&A, cholmod_factor_, &cc_);\n  cc_.print = old_print_level;\n\n  // TODO(sameeragarwal): This switch statement is not consistent. It\n  // treats all kinds of CHOLMOD failures as warnings. Some of these\n  // like out of memory are definitely not warnings. The problem is\n  // that the return value Cholesky is two valued, but the state of\n  // the linear solver is really three valued. SUCCESS,\n  // NON_FATAL_FAILURE (e.g., indefinite matrix) and FATAL_FAILURE\n  // (e.g. out of memory).\n  switch (cc_.status) {\n    case CHOLMOD_NOT_INSTALLED:\n      LOG(ERROR) << \"CHOLMOD failure: Method not installed.\";\n      info_ = Eigen::InvalidInput;\n      return;\n    case CHOLMOD_OUT_OF_MEMORY:\n      LOG(ERROR) << \"CHOLMOD failure: Out of memory.\";\n      info_ = Eigen::NumericalIssue;\n      return;\n    case CHOLMOD_TOO_LARGE:\n      LOG(ERROR) << \"CHOLMOD failure: Integer overflow occured.\";\n      info_ = Eigen::NumericalIssue;\n      return;\n    case CHOLMOD_INVALID:\n      LOG(ERROR) << \"CHOLMOD failure: Invalid input.\";\n      info_ = Eigen::InvalidInput;\n      return;\n    case CHOLMOD_NOT_POSDEF:\n      LOG(ERROR) << \"CHOLMOD warning: Matrix not positive definite.\";\n      info_ = Eigen::NumericalIssue;\n      return;\n    case CHOLMOD_DSMALL:\n      LOG(ERROR) << \"CHOLMOD warning: D for LDL' or diag(L) or \"\n                    \"LL' has tiny absolute value.\";\n      info_ = Eigen::NumericalIssue;\n      return;\n    case CHOLMOD_OK:\n      // If everything is done successfully, set the appropriate flags to\n      // success and exit.\n      if (cholmod_status != 0) {\n        info_ = Eigen::Success;\n        is_factorization_ok_ = true;\n        return;\n      }\n      LOG(ERROR) << \"CHOLMOD failure: cholmod_factorize returned false \"\n                    \"but cholmod_common::status is CHOLMOD_OK.\";\n      info_ = Eigen::NumericalIssue;\n      return;\n    default:\n      LOG(ERROR) << \"Unknown cholmod return code: \" << cc_.status;\n      info_ = Eigen::InvalidInput;\n      return;\n  }\n}\n\nvoid SparseCholeskyLLt::Compute(const Eigen::SparseMatrix<double>& mat) {\n  AnalyzePattern(mat);\n  Factorize(mat);\n}\n\nEigen::ComputationInfo SparseCholeskyLLt::Info() { return info_; }\n\n// Using the cholesky decomposition, solve for x that minimizes\n//    lhs * x = rhs\n// where lhs is the factorized matrix.\nEigen::VectorXd SparseCholeskyLLt::Solve(const Eigen::VectorXd& rhs) {\n  CHECK_NOTNULL(cholmod_factor_);\n  CHECK(is_analysis_ok_) << \"Cannot call Solve() because symbolic analysis \"\n                            \"of the matrix (i.e. AnalyzePattern()) failed!\";\n  CHECK(is_factorization_ok_)\n      << \"Cannot call Solve() because numeric factorization \"\n         \"of the matrix (i.e. Factorize()) failed!\";\n\n  Eigen::VectorXd solution;\n  if (cc_.status != CHOLMOD_OK) {\n    LOG(ERROR) << \"cholmod_solve failed. CHOLMOD status is not CHOLMOD_OK\";\n    return solution;\n  }\n\n  // returns a cholmod_dense*\n  cholmod_dense b = ViewAsCholmod(rhs);\n  cholmod_dense* x = cholmod_solve(CHOLMOD_A, cholmod_factor_, &b, &cc_);\n  if (x == nullptr) {\n    info_ = Eigen::NumericalIssue;\n    return solution;\n  }\n  solution = Eigen::Map<Eigen::VectorXd>(reinterpret_cast<double*>(x->x),\n                                         x->nrow, x->ncol);\n  return solution;\n}\n\n}  // namespace DAGSfM\n", "meta": {"hexsha": "4b6a57794d88b7aa4219ae1f52dfc93035b21f43", "size": 10843, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/math/sparse_cholesky_llt.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/math/sparse_cholesky_llt.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/math/sparse_cholesky_llt.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": 36.7559322034, "max_line_length": 80, "alphanum_fraction": 0.7090288665, "num_tokens": 2678, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.611381973294151, "lm_q2_score": 0.519521321952093, "lm_q1q2_score": 0.3176259709834566}}
{"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\r\n#include <boost/thread/thread.hpp>\r\n#include \"../../include/comm/Comm.hpp\"\r\n#include \"../../include/interactive_mid_protocols/SigmaProtocolDlog.hpp\"\r\n#include \"../../include/interactive_mid_protocols/ZeroKnowledge.hpp\"\r\n#include \"../../include/primitives/DlogOpenSSL.hpp\"\r\n#include \"../../include/infra/Scanner.hpp\"\r\n#include \"../../include/infra/ConfigFile.hpp\"\r\n\r\nstruct SigmaDlogParams {\r\n\tbiginteger w;\r\n\tbiginteger p;\r\n\tbiginteger q;\r\n\tbiginteger g;\r\n\tint t;\r\n\tIpAddress proverIp;\r\n\tIpAddress verifierIp;\r\n\tint proverPort;\r\n\tint verifierPort;\r\n\tstring protocolName;\r\n\r\n\tSigmaDlogParams(biginteger w, biginteger p, biginteger q, biginteger g, int t, \r\n\t\tIpAddress proverIp, IpAddress verifierIp, int proverPort, int verifierPort,\r\n\t\tstring protocolName) {\r\n\t\tthis->w = w; // witness\r\n\t\tthis->p = p; // group order - must be prime\r\n\t\tthis->q = q; // sub group order - prime such that p=2q+1\r\n\t\tthis->g = g; // generator of Zq\r\n\t\tthis->t = t; // soundness param must be: 2^t<q\r\n\t\tthis->proverIp = proverIp;\r\n\t\tthis->verifierIp = verifierIp;\r\n\t\tthis->proverPort = proverPort;\r\n\t\tthis->verifierPort = verifierPort;\r\n\t\tthis->protocolName = protocolName;\r\n\t};\r\n};\r\n\r\nSigmaDlogParams readSigmaConfig(string config_file) {\r\n\tConfigFile cf(config_file);\r\n\tstring input_section = cf.Value(\"\", \"input_section\");\r\n\tbiginteger p = biginteger(cf.Value(input_section, \"p\"));\r\n\tbiginteger q = biginteger(cf.Value(input_section, \"q\"));\r\n\tbiginteger g = biginteger(cf.Value(input_section, \"g\"));\r\n\tbiginteger w = biginteger(cf.Value(input_section, \"w\"));\r\n\tint t = stoi(cf.Value(input_section, \"t\"));\r\n\tstring proverIpStr = cf.Value(\"\", \"proverIp\");\r\n\tstring verifierIpStr = cf.Value(\"\", \"verifierIp\");\r\n\tint proverPort = stoi(cf.Value(\"\", \"proverPort\"));\r\n\tint verifierPort = stoi(cf.Value(\"\", \"verifierPort\"));\r\n\tauto proverIp = IpAddress::from_string(proverIpStr);\r\n\tauto verifierIp = IpAddress::from_string(verifierIpStr);\r\n\tstring protocolName = cf.Value(\"\", \"protocolName\");\r\n\treturn SigmaDlogParams(w, p, q, g, t, proverIp, verifierIp, proverPort, verifierPort, protocolName);\r\n};\r\n\r\nvoid SigmaUsage() {\r\n\tstd::cerr << \"Usage: ./libscapi_examples <1(=prover)|2(=verifier)> config_file_path\" << std::endl;\r\n}\r\n\r\nclass ProverVerifierExample {\r\npublic:\r\n\tvirtual void prove(shared_ptr<CommParty> server, \r\n\t\tshared_ptr<SigmaDlogProverComputation> proverComputation, \r\n\t\tshared_ptr<DlogGroup> dg,\r\n\t\tshared_ptr<SigmaDlogProverInput> proverinput) = 0;\r\n\tvirtual bool verify(shared_ptr<CommParty> server,\r\n\t\tshared_ptr<SigmaDlogVerifierComputation> verifierComputation,\r\n\t\tshared_ptr<SigmaGroupElementMsg> msgA,\r\n\t\tshared_ptr<SigmaBIMsg> msgZ,\r\n\t\tshared_ptr<SigmaDlogCommonInput> commonInput,\r\n\t\tshared_ptr<DlogGroup> dg) = 0;\r\n};\r\n\r\nclass SimpleDlogSigma : public ProverVerifierExample {\r\npublic:\r\n\tvirtual void prove(shared_ptr<CommParty> server,\r\n\t\tshared_ptr<SigmaDlogProverComputation> proverComputation,\r\n\t\tshared_ptr<DlogGroup> dg,\r\n\t\tshared_ptr<SigmaDlogProverInput> proverinput) override {\r\n\t\tauto sp = new SigmaProtocolProver(server, proverComputation);\r\n\t\tcout << \"--> running simple sigma dlog prover\" << endl;\r\n\t\tsp->prove(proverinput);\r\n\t}\r\n\tvirtual bool verify(shared_ptr<CommParty> server,\r\n\t\tshared_ptr<SigmaDlogVerifierComputation> verifierComputation,\r\n\t\tshared_ptr<SigmaGroupElementMsg> msgA,\r\n\t\tshared_ptr<SigmaBIMsg> msgZ,\r\n\t\tshared_ptr<SigmaDlogCommonInput> commonInput,\r\n\t\tshared_ptr<DlogGroup> dg) override{\r\n\t\tauto v = new SigmaProtocolVerifier(server, verifierComputation, msgA, msgZ);\r\n\t\tcout << \"--> running simple sigma dlog verify\" << endl;\r\n\t\tbool verificationPassed = v->verify(commonInput.get());\r\n\t\tdelete v;\r\n\t\treturn verificationPassed;\r\n\t}\r\n};\r\n\r\nclass ZKFromSigma : public ProverVerifierExample {\r\npublic:\r\n\tvirtual void prove(shared_ptr<CommParty> server,\r\n\t\tshared_ptr<SigmaDlogProverComputation> proverComputation,\r\n\t\tshared_ptr<DlogGroup> dg,\r\n\t\tshared_ptr<SigmaDlogProverInput> proverinput) {\r\n\t\tcout << \"before creating ZK prover\" << endl;\r\n\t\tauto receiver = make_shared<CmtPedersenReceiver>(server, dg);\r\n\t\tauto sp = new ZKFromSigmaProver(server, proverComputation, receiver);\r\n\t\tcout << \"--> running ZK prover\" << endl;\r\n\t\tsp->prove(proverinput);\r\n\t}\r\n\tvirtual bool verify(shared_ptr<CommParty> server,\r\n\t\tshared_ptr<SigmaDlogVerifierComputation> verifierComputation,\r\n\t\tshared_ptr<SigmaGroupElementMsg> msgA,\r\n\t\tshared_ptr<SigmaBIMsg> msgZ,\r\n\t\tshared_ptr<SigmaDlogCommonInput> commonInput,\r\n\t\tshared_ptr<DlogGroup> dg) override {\r\n\t\tcout << \"before creating ZK verifier\" << endl;\r\n\t\tauto emptyTrap = make_shared<CmtRTrapdoorCommitPhaseOutput>();\r\n\t\tauto committer = make_shared<CmtPedersenCommitter>(server, dg);\r\n\t\tauto v = new ZKFromSigmaVerifier(server, verifierComputation, committer);\r\n\t\tcout << \"--> running ZK verify\" << endl;\r\n\t\tbool verificationPassed = v->verify(commonInput.get(), msgA, msgZ);\r\n\t\tdelete v;\r\n\t\treturn verificationPassed;\r\n\t}\r\n};\r\n\r\nclass PedersenZKSigma : public ProverVerifierExample {\r\npublic:\r\n\tvirtual void prove(shared_ptr<CommParty> server,\r\n\t\tshared_ptr<SigmaDlogProverComputation> proverComputation,\r\n\t\tshared_ptr<DlogGroup> dg,\r\n\t\tshared_ptr<SigmaDlogProverInput> proverinput) {\r\n\t\tauto sp = new ZKPOKFromSigmaCmtPedersenProver(server, proverComputation, dg);\r\n\t\tcout << \"--> running pedersen prover\" << endl;\r\n\t\tsp->prove(proverinput);\r\n\t}\r\n\tvirtual bool verify(shared_ptr<CommParty> server,\r\n\t\tshared_ptr<SigmaDlogVerifierComputation> verifierComputation,\r\n\t\tshared_ptr<SigmaGroupElementMsg> msgA,\r\n\t\tshared_ptr<SigmaBIMsg> msgZ,\r\n\t\tshared_ptr<SigmaDlogCommonInput> commonInput,\r\n\t\tshared_ptr<DlogGroup> dg) override {\r\n\t\tauto emptyTrap = make_shared<CmtRTrapdoorCommitPhaseOutput>();\r\n\t\tauto v = new ZKPOKFromSigmaCmtPedersenVerifier(server, verifierComputation, emptyTrap, dg);\r\n\t\tcout << \"--> running pedersen verify\" << endl;\r\n\t\tbool verificationPassed = v->verify(commonInput.get(), msgA, msgZ);\r\n\t\tdelete v;\r\n\t\treturn verificationPassed;\r\n\t}\r\n};\r\n\r\nclass ZKPOKFiatShamir : public ProverVerifierExample {\r\npublic:\r\n\tvirtual void prove(shared_ptr<CommParty> server,\r\n\t\tshared_ptr<SigmaDlogProverComputation> proverComputation,\r\n\t\tshared_ptr<DlogGroup> dg,\r\n\t\tshared_ptr<SigmaDlogProverInput> proverinput) {\r\n\t\tauto sp = new ZKPOKFiatShamirFromSigmaProver(server, proverComputation);\r\n\t\tcout << \"--> running Fiat Shamir prover\" << endl;\r\n\t\tvector<byte> cont;\r\n\t\tauto input = make_shared<ZKPOKFiatShamirProverInput>(proverinput, cont);\r\n\t\tsp->prove(input);\r\n\t}\r\n\tvirtual bool verify(shared_ptr<CommParty> server,\r\n\t\tshared_ptr<SigmaDlogVerifierComputation> verifierComputation,\r\n\t\tshared_ptr<SigmaGroupElementMsg> msgA,\r\n\t\tshared_ptr<SigmaBIMsg> msgZ,\r\n\t\tshared_ptr<SigmaDlogCommonInput> commonInput,\r\n\t\tshared_ptr<DlogGroup> dg) override {\r\n\t\tauto emptyTrap = make_shared<CmtRTrapdoorCommitPhaseOutput>();\r\n\t\tauto v = new ZKPOKFiatShamirFromSigmaVerifier(server, verifierComputation);\r\n\t\tcout << \"--> running Fiat Shamir verify\" << endl;\r\n\t\tvector<byte> cont;\r\n\t\tauto input = make_shared<ZKPOKFiatShamirCommonInput>(commonInput.get(), cont);\r\n\t\tbool verificationPassed = v->verify(input.get(), msgA, msgZ);\r\n\t\tdelete v;\r\n\t\treturn verificationPassed;\r\n\t}\r\n};\r\n\r\n\r\nshared_ptr<ProverVerifierExample> getProverVerifier(SigmaDlogParams sdp)\r\n{\r\n\tshared_ptr<ProverVerifierExample> sds;\r\n\tif(sdp.protocolName==\"Simple\")\r\n\t\tsds = make_shared<SimpleDlogSigma>();\r\n\telse if (sdp.protocolName == \"SimpleZK\")\r\n\t\tsds = make_shared<ZKFromSigma>();\r\n\telse if(sdp.protocolName==\"ZKPedersen\")\r\n\t\tsds = make_shared<PedersenZKSigma>();\r\n\telse if (sdp.protocolName == \"ZKFiatShamir\")\r\n\t\tsds = make_shared<ZKPOKFiatShamir>();\r\n\treturn sds;\r\n}\r\n", "meta": {"hexsha": "0f76b4507df3b741af5949a3ddee00840f1fb342", "size": 9414, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "examples/SigmaProtocols/SigmaProtocolExample.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": "examples/SigmaProtocols/SigmaProtocolExample.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": "examples/SigmaProtocols/SigmaProtocolExample.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": 42.0267857143, "max_line_length": 158, "alphanum_fraction": 0.732101126, "num_tokens": 2454, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5389832354982645, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.3174013690510067}}
{"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 <boost/graph/bellman_ford_shortest_paths.hpp>\n#include \"graph_types.hpp\"\n#include <boost/python.hpp>\n#include <boost/graph/iteration_macros.hpp>\n\nnamespace boost { namespace graph { namespace python {\n\n#define BGL_PYTHON_VISITOR maybe_bellman_ford_visitor\n#define BGL_PYTHON_EVENTS_HEADER <boost/graph/python/bellman_ford_events.hpp>\n#include <boost/graph/python/visitor.hpp>\n#undef BGL_PYTHON_EVENTS_HEADER\n#undef BGL_PYTHON_VISITOR\n\ntemplate<typename Graph>\nvoid\nbellman_ford_shortest_paths\n  (const Graph& g, \n   typename graph_traits<Graph>::vertex_descriptor s,\n   vector_property_map<\n     typename graph_traits<Graph>::vertex_descriptor,\n     typename property_map<Graph, vertex_index_t>::const_type>* in_predecessor,\n   vector_property_map<\n     float,\n     typename property_map<Graph, vertex_index_t>::const_type>* in_distance,\n   vector_property_map<\n     float,\n     typename property_map<Graph, edge_index_t>::const_type>* in_weight,\n   boost::python::object in_visitor)\n{\n  using boost::python::object;\n\n  typedef typename property_map<Graph, vertex_index_t>::const_type\n    VertexIndexMap;\n  typedef typename graph_traits<Graph>::vertex_descriptor Vertex;\n  typedef vector_property_map<Vertex, VertexIndexMap> PredecessorMap;\n  typedef vector_property_map<float, VertexIndexMap> DistanceMap;\n  typedef typename property_map<Graph, edge_index_t>::const_type\n    EdgeIndexMap;\n  typedef vector_property_map<float, EdgeIndexMap> WeightMap;\n\n  PredecessorMap predecessor = \n    in_predecessor? *in_predecessor\n    : PredecessorMap(num_vertices(g), get(vertex_index, g));\n\n  DistanceMap distance = \n    in_distance? *in_distance\n    : DistanceMap(num_vertices(g), get(vertex_index, g));\n\n  WeightMap weight = \n    in_weight? *in_weight\n    : WeightMap(num_edges(g), get(edge_index, g));\n\n  // If no weight map was provided, initialize every weight with 1.0\n  if (!in_weight) {\n    BGL_FORALL_EDGES_T(e, g, Graph)\n      put(weight, e, 1.0f);\n  }\n\n  if (in_visitor != object()) {\n    boost::bellman_ford_shortest_paths\n      (g, \n       root_vertex(s).\n       visitor(maybe_bellman_ford_visitor(in_visitor)).\n       predecessor_map(predecessor).\n       distance_map(distance).\n       weight_map(weight));\n  } else {\n    boost::bellman_ford_shortest_paths\n      (g, \n       root_vertex(s).\n       predecessor_map(predecessor).\n       distance_map(distance).\n       weight_map(weight));\n  }\n}\n\nvoid export_bellman_ford_shortest_paths()\n{\n  using boost::python::arg;\n  using boost::python::def;\n  using boost::python::object;\n\n#define UNDIRECTED_GRAPH(Name,Type)                                     \\\n  {                                                                     \\\n    typedef graph_traits<Type>::vertex_descriptor vertex_descriptor;    \\\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<vertex_descriptor, VertexIndexMap>      \\\n      VertexPredecessorMap;                                             \\\n    typedef vector_property_map<float, VertexIndexMap>                  \\\n      VertexDistanceMap;                                                \\\n    typedef vector_property_map<default_color_type, VertexIndexMap>     \\\n      VertexColorMap;                                                   \\\n    typedef vector_property_map<float, EdgeIndexMap>                    \\\n      EdgeWeightMap;                                                    \\\n                                                                        \\\n    def(\"bellman_ford_shortest_paths\",                                  \\\n        &boost::graph::python::bellman_ford_shortest_paths<Type>,       \\\n        (arg(\"graph\"),                                                  \\\n         arg(\"root_vertex\"),                                            \\\n         arg(\"predecessor_map\") = static_cast<VertexPredecessorMap*>(0), \\\n         arg(\"distance_map\") = static_cast<VertexDistanceMap*>(0),      \\\n         arg(\"weight_map\") = static_cast<EdgeWeightMap*>(0),            \\\n         arg(\"visitor\") = object()));                                   \\\n  }\n#include \"graphs.hpp\"\n}\n\n} } } // end namespace boost::graph::python\n", "meta": {"hexsha": "cabf5e0d56f88c6b6ae25064084e9473d9d3dc67", "size": 4547, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/bellman_ford_shortest_paths.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/bellman_ford_shortest_paths.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/bellman_ford_shortest_paths.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": 38.5338983051, "max_line_length": 79, "alphanum_fraction": 0.6327248735, "num_tokens": 980, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5888891451980403, "lm_q2_score": 0.5389832206876841, "lm_q1q2_score": 0.317401368106857}}
{"text": "//=======================================================================\r\n// Copyright 2013 University of Warsaw.\r\n// Authors: Piotr Wygocki \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_AUGMENT_HPP\r\n#define BOOST_GRAPH_AUGMENT_HPP\r\n\r\n#include <boost/graph/filtered_graph.hpp>\r\n\r\nnamespace boost {\r\nnamespace detail {\r\n\r\ntemplate <class Graph, class ResCapMap>\r\nfiltered_graph<const Graph, is_residual_edge<ResCapMap> >\r\nresidual_graph(const Graph& g, ResCapMap residual_capacity) {\r\n    return filtered_graph<const Graph, is_residual_edge<ResCapMap> >\r\n        (g, is_residual_edge<ResCapMap>(residual_capacity));\r\n}\r\n\r\ntemplate <class Graph, class PredEdgeMap, class ResCapMap,\r\n         class RevEdgeMap>\r\ninline void\r\naugment(const Graph& g, \r\n        typename graph_traits<Graph>::vertex_descriptor src,\r\n        typename graph_traits<Graph>::vertex_descriptor sink,\r\n        PredEdgeMap p, \r\n        ResCapMap residual_capacity,\r\n        RevEdgeMap reverse_edge)\r\n{\r\n    typename graph_traits<Graph>::edge_descriptor e;\r\n    typename graph_traits<Graph>::vertex_descriptor u;\r\n    typedef typename property_traits<ResCapMap>::value_type FlowValue;\r\n\r\n    // find minimum residual capacity along the augmenting path\r\n    FlowValue delta = (std::numeric_limits<FlowValue>::max)();\r\n    e = get(p, sink);\r\n    do {\r\n        BOOST_USING_STD_MIN();\r\n        delta = min BOOST_PREVENT_MACRO_SUBSTITUTION(delta, get(residual_capacity, e));\r\n        u = source(e, g);\r\n        e = get(p, u);\r\n    } while (u != src);\r\n\r\n    // push delta units of flow along the augmenting path\r\n    e = get(p, sink);\r\n    do {\r\n        put(residual_capacity, e, get(residual_capacity, e) - delta);\r\n        put(residual_capacity, get(reverse_edge, e), get(residual_capacity, get(reverse_edge, e)) + delta);\r\n        u = source(e, g);\r\n        e = get(p, u);\r\n    } while (u != src);\r\n}\r\n\r\n} // namespace detail\r\n} //namespace boost\r\n\r\n#endif /* BOOST_GRAPH_AUGMENT_HPP */\r\n\r\n", "meta": {"hexsha": "4a8c1ac589eb07e72acd68ea5cd39a77c9436aa9", "size": 2174, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ios/Pods/boost-for-react-native/boost/graph/detail/augment.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/detail/augment.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/detail/augment.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": 33.96875, "max_line_length": 108, "alphanum_fraction": 0.6315547378, "num_tokens": 489, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.588889130767832, "lm_q2_score": 0.5389832206876841, "lm_q1q2_score": 0.31740136032921684}}
{"text": "#include <cctbx/boost_python/flex_fwd.h>\n\n#include <cctbx/maptbx/fft.h>\n#include <cctbx/maptbx/average_densities.h>\n#include <cctbx/maptbx/standard_deviations_around_sites.hpp>\n#include <scitbx/boost_python/utils.h>\n#include <boost/python/module.hpp>\n#include <boost/python/class.hpp>\n#include <boost/python/def.hpp>\n#include <boost/python/args.hpp>\n#include <cctbx/maptbx/histogram.h>\n#include <cctbx/maptbx/resolution.h>\n#include <cctbx/maptbx/fsc.h>\n#include <cctbx/maptbx/sphericity.h>\n#include <cctbx/maptbx/mask.h>\n#include <cctbx/maptbx/utils.h>\n#include <cctbx/maptbx/connectivity.h>\n#include <cctbx/maptbx/marked_grid_points.h>\n#include <cctbx/maptbx/mask_utils.h>\n#include <cctbx/maptbx/map_accumulator.h>\n#include <cctbx/maptbx/ft_analytical_1d_point_scatterer_at_origin.h>\n#include <cctbx/maptbx/target_and_gradients.h>\n\nnamespace cctbx { namespace maptbx { namespace boost_python {\n\n  void wrap_grid_indices_around_sites();\n  void wrap_grid_tags();\n  void wrap_gridding();\n  void wrap_misc();\n  void wrap_peak_list();\n  void wrap_pymol_interface();\n  void wrap_statistics();\n  void wrap_structure_factors();\n  void wrap_coordinate_transformers();\n\n  template <typename FloatType, typename GridType>\n  struct map_accumulator_wrapper\n  {\n    //typedef map_accumulator<FloatType, GridType> w_t; // works too\n    typedef cctbx::maptbx::map_accumulator<FloatType, GridType> w_t;\n    static void wrap() {\n      using namespace boost::python;\n      class_<w_t>(\"map_accumulator\", no_init)\n        .def(init<af::int3 const&,\n             double const&,\n             double const&,\n             int const&,\n             bool,\n             bool >((arg(\"n_real\"),\n                     arg(\"smearing_b\"),\n                     arg(\"max_peak_scale\"),\n                     arg(\"smearing_span\"),\n                     arg(\"use_exp_table\"),\n                     arg(\"use_max_map\"))))\n        .def(\"as_median_map\", &w_t::as_median_map)\n        .def(\"add\", &w_t::add, (arg(\"map_data\")))\n        .def(\"at_index\", &w_t::at_index, (arg(\"n\")))\n        .def(\"int_to_float_at_index\", &w_t::int_to_float_at_index, (arg(\"n\")))\n      ;\n    }\n  };\n\n  template <typename FloatType>\n  struct ft_analytical_1d_point_scatterer_at_origin_wrapper\n  {\n    typedef ft_analytical_1d_point_scatterer_at_origin<FloatType> w_t;\n    static void wrap() {\n      using namespace boost::python;\n      class_<w_t>(\"ft_analytical_1d_point_scatterer_at_origin\", no_init)\n        .def(init<int const& >(\n                    (arg(\"N\"))))\n        .def(\"distances\", &w_t::distances)\n        .def(\"rho\", &w_t::rho)\n        .def(\"compute\", &w_t::compute,\n          (arg(\"miller_indices\"),arg(\"step\"),arg(\"left\"),\n            arg(\"right\"),arg(\"u_frac\")))\n      ;\n    }\n  };\n\nnamespace {\n\n  void init_module()\n  {\n    using namespace boost::python;\n\n    map_accumulator_wrapper<double, af::c_grid<3> >::wrap();\n    ft_analytical_1d_point_scatterer_at_origin_wrapper<double>::wrap();\n    wrap_grid_indices_around_sites();\n    wrap_grid_tags();\n    wrap_gridding();\n    wrap_misc();\n    wrap_peak_list();\n    wrap_pymol_interface();\n    wrap_statistics();\n    wrap_structure_factors();\n    wrap_coordinate_transformers();\n\n// Real-space target and gradients ---------------------------------------------\n    {\n      typedef cctbx::maptbx::target_and_gradients::diffmap::compute w_t;\n      class_<w_t>(\"target_and_gradients_diffmap\", no_init)\n        .def(init<uctbx::unit_cell const&,\n             af::const_ref<double, af::c_grid_padded<3> > const&,\n             af::const_ref<double, af::c_grid_padded<3> > const&,\n             double const&,\n             af::const_ref<scitbx::vec3<double> > const& >((\n                                    arg(\"unit_cell\"),\n                                    arg(\"map_target\"),\n                                    arg(\"map_current\"),\n                                    arg(\"step\"),\n                                    arg(\"sites_frac\"))))\n        .def(\"target\", &w_t::target)\n        .def(\"gradients\", &w_t::gradients)\n      ;\n    }\n\n    //- Magnification begin ----------------------------------------------------\n    {\n      typedef cctbx::maptbx::target_and_gradients::simple::magnification<double> w_t;\n      class_<w_t>(\"target_and_gradients_simple_magnification\", no_init)\n        .def(init<uctbx::unit_cell const&,\n             af::const_ref<double, af::c_grid_padded<3> > const&,\n             af::const_ref<scitbx::vec3<double> > const&,\n             scitbx::mat3<double> const& >((\n                                    arg(\"unit_cell\"),\n                                    arg(\"map_target\"),\n                                    arg(\"sites_cart\"),\n                                    arg(\"K\"))))\n        .def(init<uctbx::unit_cell const&,\n             af::const_ref<double, af::c_grid_padded<3> > const&,\n             af::const_ref<scitbx::vec3<double> > const&,\n             scitbx::vec3<double> const& >((\n                                    arg(\"unit_cell\"),\n                                    arg(\"map_target\"),\n                                    arg(\"sites_cart\"),\n                                    arg(\"K\"))))\n        .def(\"target\", &w_t::target)\n        .def(\"gradients\", &w_t::gradients)\n      ;\n    }\n\n    def(\"magnification_isotropic\",\n      (double(*)\n        (uctbx::unit_cell const&,\n         af::const_ref<double, af::c_grid_padded<3> > const&,\n         af::const_ref<scitbx::vec3<double> > const&))\n           cctbx::maptbx::target_and_gradients::simple::magnification_isotropic, (\n             arg(\"unit_cell\"),\n             arg(\"density_map\"),\n             arg(\"sites_cart\")));\n\n    def(\"magnification_anisotropic\",\n      (scitbx::vec3<double>(*)\n        (uctbx::unit_cell const&,\n         af::const_ref<double, af::c_grid_padded<3> > const&,\n         af::const_ref<scitbx::vec3<double> > const&))\n           cctbx::maptbx::target_and_gradients::simple::magnification_anisotropic, (\n             arg(\"unit_cell\"),\n             arg(\"density_map\"),\n             arg(\"sites_cart\")));\n    //- Magnification end ------------------------------------------------------\n\n    {\n      typedef cctbx::maptbx::target_and_gradients::simple::compute<double> w_t;\n      class_<w_t>(\"target_and_gradients_simple\", no_init)\n        .def(init<uctbx::unit_cell const&,\n             af::const_ref<double, af::c_grid_padded<3> > const&,\n             af::const_ref<scitbx::vec3<double> > const&,\n             double const&,\n             af::const_ref<bool> const& >((\n                                    arg(\"unit_cell\"),\n                                    arg(\"map_target\"),\n                                    arg(\"sites_cart\"),\n                                    arg(\"delta\"),\n                                    arg(\"selection\"))))\n        .def(init<uctbx::unit_cell const&,\n             af::const_ref<double, af::c_grid_padded<3> > const&,\n             af::const_ref<scitbx::vec3<double> > const&,\n             af::const_ref<bool> const&,\n             std::string const& >((\n                                    arg(\"unit_cell\"),\n                                    arg(\"map_target\"),\n                                    arg(\"sites_cart\"),\n                                    arg(\"selection\"),\n                                    arg(\"interpolation\"))))\n        .def(\"target\", &w_t::target)\n        .def(\"gradients\", &w_t::gradients)\n      ;\n    }\n\n    def(\"real_space_target_simple\",\n      (double(*)\n        (uctbx::unit_cell const&,\n         af::const_ref<double, af::c_grid_padded<3> > const&,\n         af::const_ref<scitbx::vec3<double> > const&,\n         af::const_ref<bool> const&))\n           cctbx::maptbx::target_and_gradients::simple::target, (\n             arg(\"unit_cell\"),\n             arg(\"density_map\"),\n             arg(\"sites_cart\"),\n             arg(\"selection\")));\n\n    def(\"real_space_target_simple_with_adjacent_similarity\",\n      (double(*)\n        (uctbx::unit_cell const&,\n         af::const_ref<double, af::c_grid_padded<3> > const&,\n         af::const_ref<scitbx::vec3<double> > const&,\n         af::const_ref<std::size_t > const&,\n         af::const_ref<double> const&))\n           cctbx::maptbx::target_and_gradients::simple::target_with_adjacent_similarity, (\n             arg(\"unit_cell\"),\n             arg(\"density_map\"),\n             arg(\"sites_cart\"),\n             arg(\"selection\"),\n             arg(\"weights\")));\n\n    def(\"real_space_target_simple\",\n      (double(*)\n        (uctbx::unit_cell const&,\n         af::const_ref<double, af::c_grid_padded<3> > const&,\n         af::const_ref<scitbx::vec3<double> > const&))\n           cctbx::maptbx::target_and_gradients::simple::target, (\n             arg(\"unit_cell\"),\n             arg(\"density_map\"),\n             arg(\"sites_cart\")));\n\n    def(\"real_space_target_simple\",\n      (double(*)\n        (uctbx::unit_cell const&,\n         af::const_ref<double, af::c_grid_padded<3> > const&,\n         af::const_ref<scitbx::vec3<double> > const&,\n         af::const_ref<std::size_t> const&))\n           cctbx::maptbx::target_and_gradients::simple::target, (\n             arg(\"unit_cell\"),\n             arg(\"density_map\"),\n             arg(\"sites_cart\"),\n             arg(\"selection\")));\n\n    def(\"real_space_target_simple\",\n      (double(*)\n        (af::const_ref<double, af::c_grid<3> > const&,\n         af::const_ref<scitbx::vec3<double> > const&))\n           cctbx::maptbx::target_and_gradients::simple::target, (\n             arg(\"density_map\"),\n             arg(\"sites_frac\")));\n\n    def(\"real_space_target_simple_per_site\",\n      (af::shared<double>(*)\n        (uctbx::unit_cell const&,\n         af::const_ref<double, af::c_grid_padded<3> > const&,\n         af::const_ref<scitbx::vec3<double> > const&))\n           cctbx::maptbx::target_and_gradients::simple::target_per_site, (\n             arg(\"unit_cell\"),\n             arg(\"density_map\"),\n             arg(\"sites_cart\")));\n\n    def(\"real_space_gradients_simple\",\n      (af::shared<scitbx::vec3<double> >(*)\n        (uctbx::unit_cell const&,\n         af::const_ref<double, af::c_grid_padded<3> > const&,\n         af::const_ref<scitbx::vec3<double> > const&,\n         double,\n         af::const_ref<bool> const&))\n           cctbx::maptbx::target_and_gradients::simple::gradients, (\n             arg(\"unit_cell\"),\n             arg(\"density_map\"),\n             arg(\"sites_cart\"),\n             arg(\"delta\"),\n             arg(\"selection\")));\n\n// -----------------------------------------------------------------------------\n\n    {\n      typedef grid_points_in_sphere_around_atom_and_distances w_t;\n\n      class_<w_t>(\"grid_points_in_sphere_around_atom_and_distances\", no_init)\n        .def(init<cctbx::uctbx::unit_cell const&,\n                  af::const_ref<double, af::c_grid<3> > const&,\n                  double const&,\n                  double const&,\n                  scitbx::vec3<double> const& >(\n                    (arg(\"unit_cell\"),\n                     arg(\"data\"),\n                     arg(\"radius\"),\n                     arg(\"shell\"),\n                     arg(\"site_frac\"))))\n        .def(\"data_at_grid_points\", &w_t::data_at_grid_points)\n        .def(\"data_at_grid_points_averaged\", &w_t::data_at_grid_points_averaged)\n        .def(\"distances\", &w_t::distances)\n      ;\n    }\n\n    {\n      typedef non_linear_map_modification_to_match_average_cumulative_histogram w_t;\n\n      class_<w_t>(\"non_linear_map_modification_to_match_average_cumulative_histogram\", no_init)\n        .def(init<af::const_ref<double, af::c_grid<3> > const&,\n                  af::const_ref<double, af::c_grid<3> > const& >(\n                    (arg(\"map_1\"),\n                     arg(\"map_2\"))))\n        .def(\"map_1\", &w_t::map_1)\n        .def(\"map_2\", &w_t::map_2)\n        .def(\"histogram_1\", &w_t::histogram_1)\n        .def(\"histogram_2\", &w_t::histogram_2)\n        .def(\"histogram_12\", &w_t::histogram_12)\n        .def(\"histogram_values\", &w_t::histogram_values)\n      ;\n    }\n\n    {\n      typedef d99 w_t;\n\n      class_<w_t>(\"d99\", no_init)\n        .def(init<\n          af::const_ref<std::complex<double> > const&,\n          af::const_ref<double> const&,\n          af::const_ref<miller::index<> > const&,\n          double const&,\n          double const& >(\n                    (arg(\"f\"),\n                     arg(\"d_spacings\"),\n                     arg(\"hkl\"),\n                     arg(\"d_min\"),\n                     arg(\"d_max\"))))\n        .def(\"d_min_cc9\",      &w_t::d_min_cc9)\n        .def(\"d_min_cc99\",     &w_t::d_min_cc99)\n        .def(\"d_min_cc999\",    &w_t::d_min_cc999)\n        .def(\"d_min_cc9999\",   &w_t::d_min_cc9999)\n        .def(\"d_min_cc99999\",  &w_t::d_min_cc99999)\n        .def(\"d_min_cc999999\", &w_t::d_min_cc999999)\n      ;\n    }\n\n    {\n      typedef fsc w_t;\n\n      class_<w_t>(\"fsc\", no_init)\n        .def(init<\n          af::const_ref<std::complex<double> > const&,\n          af::const_ref<std::complex<double> > const&,\n          af::const_ref<double> const&,\n          int const& >(\n                    (arg(\"f1\"),\n                     arg(\"f2\"),\n                     arg(\"d_spacings\"),\n                     arg(\"step\"))))\n        .def(\"fsc\",   &w_t::cc)\n        .def(\"d\",     &w_t::d)\n        .def(\"d_inv\", &w_t::d_inv)\n      ;\n    }\n\n    {\n      typedef histogram w_t;\n\n      class_<w_t>(\"histogram\", no_init)\n        .def(init<af::const_ref<double, af::c_grid<3> > const&,\n                  int const& >(\n                    (arg(\"map\"),\n                     arg(\"n_bins\"))))\n        .def(init<af::const_ref<double> const&,\n                  int const& >(\n                    (arg(\"map\"),\n                     arg(\"n_bins\"))))\n        .def(\"values\",    &w_t::values)\n        .def(\"c_values\",  &w_t::c_values)\n        .def(\"v_values\",  &w_t::v_values)\n        .def(\"bin_width\", &w_t::bin_width)\n        .def(\"arguments\", &w_t::arguments)\n      ;\n    }\n\n    {\n      typedef volume_scale w_t;\n\n      class_<w_t>(\"volume_scale\", no_init)\n        .def(init<af::const_ref<double, af::c_grid<3> > const&,\n                  int const& >(\n                    (arg(\"map\"),\n                     arg(\"n_bins\"))))\n        .def(\"map_data\", &w_t::map_data)\n        .def(\"v_values\", &w_t::v_values)\n      ;\n    }\n\n    {\n      typedef volume_scale_1d w_t;\n\n      class_<w_t>(\"volume_scale_1d\", no_init)\n        .def(init<af::const_ref<double> const&,\n                  int const& >(\n                    (arg(\"map\"),\n                     arg(\"n_bins\"))))\n        .def(\"map_data\", &w_t::map_data)\n        .def(\"v_values\", &w_t::v_values)\n      ;\n    }\n\n    {\n      typedef one_gaussian_peak_approximation w_t;\n\n      class_<w_t>(\"one_gaussian_peak_approximation\", no_init)\n        .def(init<af::const_ref<double> const&,\n                  af::const_ref<double> const&,\n                  bool const&,\n                  bool const& >(\n                    (arg(\"data_at_grid_points\"),\n                     arg(\"distances\"),\n                     arg(\"use_weights\"),\n                     arg(\"optimize_cutoff_radius\"))))\n        .def(\"a_real_space\", &w_t::a_real_space)\n        .def(\"b_real_space\", &w_t::b_real_space)\n        .def(\"a_reciprocal_space\", &w_t::a_reciprocal_space)\n        .def(\"b_reciprocal_space\", &w_t::b_reciprocal_space)\n        .def(\"gof\", &w_t::gof)\n        .def(\"cutoff_radius\", &w_t::cutoff_radius)\n        .def(\"weight_power\", &w_t::weight_power)\n        .def(\"first_zero_radius\", &w_t::first_zero_radius)\n      ;\n    }\n\n    {\n      typedef connectivity w_t;\n\n      class_<w_t>(\"connectivity\", no_init)\n        .def(init<af::const_ref<float, af::flex_grid<> > const&,\n                  float const&,\n                  bool >(\n                    (arg(\"map_data\"),\n                     arg(\"threshold\"),\n                     arg(\"wrapping\")=true)))\n        .def(init<af::const_ref<double, af::flex_grid<> > const&,\n                  double const&,\n                  bool >(\n                    (arg(\"map_data\"),\n                     arg(\"threshold\"),\n                     arg(\"wrapping\")=true)))\n        .def(init<af::const_ref<int, af::flex_grid<> > const&,\n                  int const&,\n                  bool >(\n                    (arg(\"map_data\"),\n                     arg(\"threshold\"),\n                     arg(\"wrapping\")=true)))\n        .def(\"result\",    &w_t::result)\n        .def(\"regions\",   &w_t::regions)\n        .def(\"volume_cutoff_mask\", &w_t::volume_cutoff_mask,\n                    (arg(\"volume_cutoff\")))\n        .def(\"get_blobs_boundaries\", &w_t::get_blobs_boundaries)\n        .def(\"expand_mask\", &w_t::expand_mask,\n                  (arg(\"id_to_expand\"),\n                   arg(\"expand_size\")))\n        .def(\"noise_elimination_two_cutoffs\",\n             &w_t::noise_elimination_two_cutoffs,\n                    (arg(\"connectivity_object_at_t1\"),\n                     arg(\"elimination_volume_threshold_at_t1\"),\n                     arg(\"zero_all_interblob_region\")=true))\n        .def(\"maximum_coors\", &w_t::maximum_coors)\n        .def(\"maximum_values\", &w_t::maximum_values)\n      ;\n    }\n    {\n      typedef marked_grid_points w_t;\n\n      class_<w_t>(\"marked_grid_points\", no_init)\n        .def(init<af::const_ref<bool, af::flex_grid<> > const&,\n                  int const&\n                  >(\n                    (arg(\"map_data\"),\n                     arg(\"every_nth_point\")\n                     )))\n        .def(\"result\",    &w_t::result)\n      ;\n    }\n\n    {\n      typedef sample_all_mask_regions w_t;\n      class_<w_t>(\"sample_all_mask_regions\", no_init)\n        .def(init<af::const_ref<int, af::flex_grid<> > const&,\n            af::shared<int> const&,\n            af::shared<int> const&,\n            cctbx::uctbx::unit_cell const& > ((\n              arg(\"mask\"),\n              arg(\"volumes\"),\n              arg(\"sampling_rates\"),\n              arg(\"unit_cell\"))))\n        .def(\"get_array\", &w_t::get_array,\n          (arg(\"n\")))\n      ;\n    }\n\n    {\n      typedef zero_boundary_box_map w_t;\n      class_<w_t>(\"zero_boundary_box_map\", no_init)\n        .def(init<af::const_ref<double, af::flex_grid<> > const&,\n            int const& > ((\n              arg(\"mask\"),\n              arg(\"boundary\"))))\n        .def(\"result\",    &w_t::result)\n      ;\n    }\n\n    def(\"copy\",\n      (af::versa<float, af::flex_grid<> >(*)\n        (af::const_ref<float, af::flex_grid<> > const&,\n         af::flex_grid<> const&)) maptbx::copy, (\n      arg(\"map\"),\n      arg(\"result_grid\")));\n    def(\"copy\",\n      (af::versa<double, af::flex_grid<> >(*)\n        (af::const_ref<double, af::flex_grid<> > const&,\n         af::flex_grid<> const&)) maptbx::copy, (\n      arg(\"map\"),\n      arg(\"result_grid\")));\n    def(\"copy\",\n      (af::versa<float, af::flex_grid<> >(*)\n        (af::const_ref<float, c_grid_padded_p1<3> > const&,\n         af::int3 const&,\n         af::int3 const&)) maptbx::copy, (\n      arg(\"map_unit_cell\"),\n      arg(\"first\"),\n      arg(\"last\")));\n    def(\"copy\",\n      (af::versa<double, af::flex_grid<> >(*)\n        (af::const_ref<double, c_grid_padded_p1<3> > const&,\n         af::int3 const&,\n         af::int3 const&)) maptbx::copy, (\n      arg(\"map_unit_cell\"),\n      arg(\"first\"),\n      arg(\"last\")));\n    def(\"copy_box\",\n      (af::versa<float, af::flex_grid<> >(*)\n        (af::const_ref<float, af::flex_grid<> > const&,\n         af::int3 const&,\n         af::int3 const&)) maptbx::copy_box, (\n      arg(\"map\"),\n      arg(\"first\"),\n      arg(\"last\")));\n    def(\"copy_box\",\n      (af::versa<double, af::flex_grid<> >(*)\n        (af::const_ref<double, af::flex_grid<> > const&,\n         af::int3 const&,\n         af::int3 const&)) maptbx::copy_box, (\n      arg(\"map\"),\n      arg(\"first\"),\n      arg(\"last\")));\n    def(\"unpad_in_place\",\n      (void(*)(af::versa<float, af::flex_grid<> >&))\n        maptbx::unpad_in_place, (arg(\"map\")));\n    def(\"unpad_in_place\",\n      (void(*)(af::versa<double, af::flex_grid<> >&))\n        maptbx::unpad_in_place, (arg(\"map\")));\n\n    def(\"fft_to_real_map_unpadded\",\n      (af::versa<double, af::c_grid<3> >(*)(\n        sgtbx::space_group const&,\n        af::tiny<int, 3> const&,\n        af::const_ref<miller::index<> > const&,\n        af::const_ref<std::complex<double> > const&))\n          maptbx::fft_to_real_map_unpadded, (\n            arg(\"space_group\"),\n            arg(\"n_real\"),\n            arg(\"miller_indices\"),\n            arg(\"data\")));\n\n    def(\"direct_summation_at_point\",\n      (std::complex<double>(*)(\n        af::const_ref<miller::index<> > const&,\n        af::const_ref<std::complex<double> > const&,\n        scitbx::vec3<double>))\n          maptbx::direct_summation_at_point, (\n            arg(\"miller_indices\"),\n            arg(\"data\"),\n            arg(\"site_frac\")));\n\n    def(\"cc_weighted_maps\",cc_weighted_maps);\n\n    def(\"kuwahara_filter\",\n      (void(*)\n        (af::ref<double, af::c_grid<3> >,\n         int const&)) kuwahara_filter, (\n      arg(\"map_data\"),\n      arg(\"index_span\")));\n\n    def(\"median_filter\",\n      (void(*)\n        (af::ref<double, af::c_grid<3> >,\n         int const&)) median_filter, (\n      arg(\"map_data\"),\n      arg(\"index_span\")));\n\n    def(\"remove_single_node_peaks\",\n      (void(*)\n        (af::ref<double, af::c_grid<3> >,\n         af::ref<double, af::c_grid_padded<3> >,\n         double const&,\n         int const&)) remove_single_node_peaks, (\n      arg(\"map_data\"),\n      arg(\"mask_data\"),\n      arg(\"cutoff\"),\n      arg(\"index_span\")));\n\n    def(\"map_box_average\",\n      (void(*)\n        (af::ref<double, af::c_grid<3> >,\n         double const&,\n         int const&)) map_box_average, (\n      arg(\"map_data\"),\n      arg(\"cutoff\"),\n      arg(\"index_span\")));\n\n    def(\"map_box_average\",\n      (void(*)\n        (af::ref<double, af::c_grid<3> >,\n         int const&)) map_box_average, (\n      arg(\"map_data\"),\n      arg(\"index_span\")));\n\n    def(\"center_of_mass\",\n      (cctbx::cartesian<>(*)\n        (af::const_ref<double, af::c_grid<3> > const&,\n         uctbx::unit_cell const&,\n         double const&)) center_of_mass, (\n      arg(\"map_data\"),\n      arg(\"unit_cell\"),\n      arg(\"cutoff\")));\n\n    def(\"fit_point_3d_grid_search\",\n      (cctbx::cartesian<>(*)\n        (cctbx::cartesian<> const&,\n         af::const_ref<double, af::c_grid<3> > const&,\n         uctbx::unit_cell const&,\n         double const&,\n         double const&)) fit_point_3d_grid_search, (\n      arg(\"site_cart\"),\n      arg(\"map_data\"),\n      arg(\"unit_cell\"),\n      arg(\"amplitude\"),\n      arg(\"increment\")));\n\n    def(\"sharpen\",\n      (void(*)\n        (af::ref<double, af::c_grid<3> >,\n         int const&,\n         int const&,\n         bool)) sharpen, (\n      arg(\"map_data\"),\n      arg(\"index_span\"),\n      arg(\"n_averages\"),\n      arg(\"allow_negatives\")));\n\n    def(\"gamma_compression\",\n      (void(*)\n        (af::ref<double, af::c_grid<3> >,\n         double const&)) gamma_compression, (\n      arg(\"map_data\"),\n      arg(\"gamma\")));\n\n    def(\"map_box_average\",\n      (void(*)\n        (af::ref<double, af::c_grid<3> >,\n         cctbx::uctbx::unit_cell const&,\n         double const&)) map_box_average, (\n      arg(\"map_data\"),\n      arg(\"unit_cell\"),\n      arg(\"radius\")));\n\n    def(\"hoppe_gassman_modification\",\n      (void(*)\n        (af::ref<double, af::c_grid<3> >,\n         double,\n         int)) hoppe_gassman_modification, (\n      arg(\"data\"),\n      arg(\"mean_scale\"),\n      arg(\"n_iterations\")));\n\n    def(\"hoppe_gassman_modification2\",\n      (void(*)\n        (af::ref<double, af::c_grid<3> >,\n         int)) hoppe_gassman_modification2, (\n      arg(\"data\"),\n      arg(\"n_iterations\")));\n\n    def(\"sphericity_tensor\",\n      (scitbx::sym_mat3<double>(*)\n        (af::const_ref<double, af::c_grid<3> > const&,\n          uctbx::unit_cell const&,\n         double const&,\n         cctbx::fractional<> const&)) sphericity_tensor, (\n      arg(\"map_data\"),\n      arg(\"unit_cell\"),\n      arg(\"radius\"),\n      arg(\"site_frac\")));\n\n    def(\"sphericity\",\n      (af::shared<double>(*)\n        (af::const_ref<double, af::c_grid<3> > const&,\n          uctbx::unit_cell const&,\n         double const&,\n         af::const_ref<scitbx::vec3<double> > const&)) sphericity, (\n      arg(\"map_data\"),\n      arg(\"unit_cell\"),\n      arg(\"radius\"),\n      arg(\"sites_frac\")));\n\n    def(\"average_densities\",\n      (af::shared<double>(*)\n        (uctbx::unit_cell const&,\n         af::const_ref<double, af::c_grid<3> > const&,\n         af::const_ref<scitbx::vec3<double> > const&,\n         float)) average_densities, (\n      arg(\"unit_cell\"),\n      arg(\"data\"),\n      arg(\"sites_frac\"),\n      arg(\"radius\")));\n\n    def(\"mask\",\n      (af::versa<double, af::c_grid<3> >(*)\n        (af::const_ref<scitbx::vec3<double> > const&,\n          uctbx::unit_cell const&,\n          af::tiny<int, 3> const&,\n          double const&,\n          double const&,\n          af::const_ref<double> const&,\n          bool const&)) mask, (\n      arg(\"sites_frac\"),\n      arg(\"unit_cell\"),\n      arg(\"n_real\"),\n      arg(\"mask_value_inside_molecule\"),\n      arg(\"mask_value_outside_molecule\"),\n      arg(\"radii\"),\n      arg(\"wrapping\")=true\n       ));\n\n    def(\"convert_to_non_negative\",\n      (void(*)\n        (af::ref<double, af::c_grid<3> >,\n         double)) convert_to_non_negative, (\n      arg(\"data\"),\n      arg(\"substitute_value\")));\n\n    def(\"flexible_boundary_mask\",\n      (void(*)\n        (af::ref<double, af::c_grid<3> >,\n         af::ref<double, af::c_grid<3> >)) flexible_boundary_mask, (\n      arg(\"data\"),\n      arg(\"mask\")));\n\n    def(\"negate_selected_in_place\",\n      (af::versa<double, af::c_grid_padded<3> >(*)\n        (af::const_ref<double, af::c_grid_padded<3> > const&,\n         std::vector<unsigned> const&)) negate_selected_in_place, (\n      arg(\"map_data\"),\n      arg(\"selection\")));\n\n    def(\"reset\",\n      (void(*)\n        (af::ref<double, af::c_grid<3> >,\n         double,\n         double,\n         double,\n         bool)) reset, (\n      arg(\"data\"),\n      arg(\"substitute_value\"),\n      arg(\"less_than_threshold\"),\n      arg(\"greater_than_threshold\"),\n      arg(\"use_and\")));\n\n    def(\"intersection\",\n      (void(*)\n        (af::ref<double, af::c_grid<3> >,\n         af::ref<double, af::c_grid<3> >,\n         af::ref<double> const&,\n         bool)) intersection, (\n      arg(\"map_data_1\"),\n      arg(\"map_data_2\"),\n      arg(\"thresholds\"),\n      arg(\"average\")));\n\n    def(\"rotate_translate_map\",\n      (af::versa<double, af::c_grid<3> >(*)\n        (uctbx::unit_cell const&,\n         af::const_ref<double, af::c_grid<3> > const&,\n         scitbx::mat3<double> const&,\n         scitbx::vec3<double> const&,\n         af::tiny<int, 3> const&,\n         af::tiny<int, 3> const&)) rotate_translate_map, (\n      arg(\"unit_cell\"),\n      arg(\"map_data\"),\n      arg(\"rotation_matrix\"),\n      arg(\"translation_vector\"),\n      arg(\"start\"),\n      arg(\"end\")));\n\n    def(\"rotate_translate_map\",\n      (af::versa<double, af::c_grid<3> >(*)\n        (uctbx::unit_cell const&,\n         af::const_ref<double, af::c_grid<3> > const&,\n         scitbx::mat3<double> const&,\n         scitbx::vec3<double> const& )) rotate_translate_map, (\n      arg(\"unit_cell\"),\n      arg(\"map_data\"),\n      arg(\"rotation_matrix\"),\n      arg(\"translation_vector\")));\n\n    def(\"superpose_maps\",\n      (af::versa<double, af::c_grid<3> >(*)\n        (uctbx::unit_cell const&,\n         uctbx::unit_cell const&,\n         af::const_ref<double, af::c_grid<3> > const&,\n         af::tiny<int, 3> const&,\n         scitbx::mat3<double> const&,\n         scitbx::vec3<double> const&,\n         bool wrap )) superpose_maps, (\n      arg(\"unit_cell_1\"),\n      arg(\"unit_cell_2\"),\n      arg(\"map_data_1\"),\n      arg(\"n_real_2\"),\n      arg(\"rotation_matrix\"),\n      arg(\"translation_vector\"),\n      arg(\"wrapping\")=true));\n\n    def(\"combine_and_maximize_maps\",\n      (af::versa<double, af::c_grid<3> >(*)\n        (af::const_ref<double, af::c_grid<3> > const&,\n         af::const_ref<double, af::c_grid<3> > const&,\n         af::tiny<int, 3> const& )) combine_and_maximize_maps, (\n      arg(\"map_data_1\"),\n      arg(\"map_data_2\"),\n      arg(\"n_real\")));\n\n    def(\"denmod_simple\",\n      (af::versa<double, af::c_grid<3> >(*)\n        (af::const_ref<double, af::c_grid<3> > const&,\n         af::tiny<int, 3> const&,\n         double,double)) denmod_simple, (\n      arg(\"map_data\"),\n      arg(\"n_real\"),\n      arg(\"cutoffp\"),\n      arg(\"cutoffm\")));\n\n    def(\"binarize\",\n      (void(*)\n        (af::ref<double, af::c_grid<3> >,\n         double const&,\n         double const&,\n         double const&)) binarize, (\n      arg(\"map_data\"),\n      arg(\"threshold\"),\n      arg(\"substitute_value_below\"),\n      arg(\"substitute_value_above\")));\n\n    def(\"truncate_special\",\n      (void(*)\n        (af::ref<int, af::c_grid<3> >,\n         af::ref<double, af::c_grid<3> >)) truncate_special, (\n      arg(\"mask\"),\n      arg(\"map_data\")));\n\n    def(\"combine_1\",\n      (void(*)\n        (af::ref<double, af::c_grid<3> >,\n         af::ref<double, af::c_grid<3> >)) combine_1, (\n      arg(\"map_data\"),\n      arg(\"diff_map\")));\n\n    def(\"truncate_between_min_max\",\n      (void(*)\n        (af::ref<double, af::c_grid<3> >,\n         double const&,\n         double const&)) truncate_between_min_max, (\n      arg(\"map_data\"),\n      arg(\"min\"),\n      arg(\"max\")));\n\n    def(\"truncate\",\n      (void(*)\n        (af::ref<double, af::c_grid<3> >,\n         double const&,\n         double const&,\n         double const&,\n         double const&)) truncate, (\n      arg(\"map_data\"),\n      arg(\"standard_deviation\"),\n      arg(\"by_sigma_less_than\"),\n      arg(\"scale_by\"),\n      arg(\"set_value\")));\n\n    def(\"fem_averaging_loop\",\n      (af::shared<std::complex<double> >(*)\n        (af::const_ref<std::complex<double> > const&,\n         af::const_ref<double> const&,\n         af::const_ref<double> const&,\n         double const&,\n         int const&,\n         int const&)) fem_averaging_loop, (\n      arg(\"map_coefficients\"),\n      arg(\"r_factors\"),\n      arg(\"sigma_over_f_obs\"),\n      arg(\"random_scale\"),\n      arg(\"random_seed\"),\n      arg(\"n_cycles\")));\n\n    def(\"conditional_solvent_region_filter\",\n      (af::versa<double, af::c_grid<3> >(*)\n        (af::const_ref<double, af::c_grid_padded<3> > const&,\n         af::const_ref<double, af::c_grid<3> > const&,\n         double const&)) conditional_solvent_region_filter, (\n      arg(\"bulk_solvent_mask\"),\n      arg(\"map_data\"),\n      arg(\"threshold\")));\n\n    def(\"update_f_part1_helper\",\n      (af::versa<double, af::c_grid<3> >(*)\n        (af::const_ref<int, af::c_grid_padded<3> > const&,\n         af::const_ref<double, af::c_grid<3> > const&,\n         int const&)) update_f_part1_helper, (\n      arg(\"connectivity_map\"),\n      arg(\"map_data\"),\n      arg(\"region_id\")));\n\n    def(\"map_sum_at_sites_frac\",\n      (double(*)\n        (af::const_ref<double, af::c_grid<3> > const&,\n         af::const_ref<scitbx::vec3<double> > const&)) map_sum_at_sites_frac, (\n      arg(\"map_data\"),\n      arg(\"sites_frac\")));\n\n    def(\"discrepancy_function\",\n      (af::shared<double>(*)\n        (af::const_ref<double> const&,\n         af::const_ref<double> const&,\n         af::const_ref<double> const&)) discrepancy_function, (\n      arg(\"map_1\"),\n      arg(\"map_2\"),\n      arg(\"cutoffs\")));\n\n    def(\"discrepancy_function\",\n      (af::shared<double>(*)\n        (af::const_ref<double, af::c_grid<3> > const&,\n         af::const_ref<double, af::c_grid<3> > const&,\n         af::const_ref<double> const&)) discrepancy_function, (\n      arg(\"map_1\"),\n      arg(\"map_2\"),\n      arg(\"cutoffs\")));\n\n    def(\"cc_complex_complex\",\n      (af::shared<double>(*)\n        (af::const_ref<std::complex<double> > const&,\n         af::const_ref<std::complex<double> > const&,\n         af::const_ref<double> const&,\n         af::const_ref<double> const&,\n         af::const_ref<double> const&,\n         double const&)) cc_complex_complex, (\n      arg(\"f_1\"),\n      arg(\"f_2\"),\n      arg(\"d_spacings\"),\n      arg(\"ss\"),\n      arg(\"d_mins\"),\n      arg(\"b_iso\")));\n\n    def(\"cc_complex_complex\",\n      (double(*)\n        (af::const_ref<std::complex<double> > const&,\n         af::const_ref<std::complex<double> > const&)) cc_complex_complex, (\n      arg(\"f_1\"),\n      arg(\"f_2\")));\n\n    def(\"cc_peak\",\n      (double(*)\n        (af::const_ref<double, af::c_grid<3> > const&,\n         af::const_ref<double, af::c_grid<3> > const&,\n         double const&)) cc_peak, (\n      arg(\"map_1\"),\n      arg(\"map_2\"),\n      arg(\"cutoff\")));\n\n    def(\"set_box_copy\",\n      (af::versa<double, af::c_grid<3> >(*)\n        (double const&,\n         af::ref<double, af::c_grid<3> >,\n         af::tiny<int, 3> const&,\n         af::tiny<int, 3> const&)) set_box_copy, (\n      arg(\"value\"),\n      arg(\"map_data_to\"),\n      arg(\"start\"),\n      arg(\"end\")));\n\n    def(\"set_box\",\n      (void(*)\n        (double const&,\n         af::ref<double, af::c_grid<3> >,\n         af::tiny<int, 3> const&,\n         af::tiny<int, 3> const&)) set_box, (\n      arg(\"value\"),\n      arg(\"map_data_to\"),\n      arg(\"start\"),\n      arg(\"end\")));\n\n    def(\"set_box\",\n      (void(*)\n        (af::const_ref<double, af::c_grid<3> > const&,\n         af::ref<double, af::c_grid<3> >,\n         af::tiny<int, 3> const&,\n         af::tiny<int, 3> const&)) set_box, (\n      arg(\"map_data_from\"),\n      arg(\"map_data_to\"),\n      arg(\"start\"),\n      arg(\"end\")));\n\n    def(\"copy_box\",\n      (void(*)\n        (af::const_ref<double, af::c_grid<3> > const&,\n         af::ref<double, af::c_grid<3> >,\n         af::tiny<int, 3> const&,\n         af::tiny<int, 3> const&)) copy_box, (\n      arg(\"map_data_from\"),\n      arg(\"map_data_to\"),\n      arg(\"start\"),\n      arg(\"end\")));\n\n    def(\"eight_point_interpolation\",\n      (double(*)\n        (af::const_ref<double, af::flex_grid<> > const&,\n         scitbx::vec3<double> const&)) eight_point_interpolation);\n    def(\"eight_point_interpolation\",\n      (double(*)\n        (af::const_ref<double, af::c_grid_padded<3> > const&,\n         scitbx::vec3<double> const&)) eight_point_interpolation);\n    def(\"eight_point_interpolation\",\n      (double(*)\n        (af::const_ref<double, af::c_grid<3> > const&,\n         scitbx::vec3<double> const&)) eight_point_interpolation);\n    def(\"eight_point_interpolation_with_gradients\",\n      (af::tiny<double, 4>(*)\n        (af::const_ref<double, af::c_grid_padded<3> > const&,\n         scitbx::vec3<double> const&,\n         scitbx::vec3<double> const&)) eight_point_interpolation_with_gradients);\n    def(\"quadratic_interpolation_with_gradients\",\n      (af::tiny<double, 4>(*)\n        (//af::const_ref<double, af::flex_grid<> > const&,\n         af::const_ref<double, af::c_grid_padded<3> > const&,\n         scitbx::vec3<double> const&,\n         scitbx::vec3<double> const&)) quadratic_interpolation_with_gradients);\n    def(\"closest_grid_point\",\n      (af::c_grid_padded<3>::index_type(*)\n        (af::flex_grid<> const&,\n         fractional<double> const&)) closest_grid_point);\n    def(\"tricubic_interpolation_with_gradients\",\n      (af::tiny<double, 4>(*)\n        (af::const_ref<double, af::c_grid_padded<3> > const&,\n         scitbx::vec3<double> const&,\n         scitbx::vec3<double> const&)) tricubic_interpolation_with_gradients);\n    def(\"tricubic_interpolation\",\n      (double(*)\n        (af::const_ref<double, af::c_grid_padded<3> > const&,\n         scitbx::vec3<double> const&)) tricubic_interpolation);\n    def(\"non_crystallographic_eight_point_interpolation\",\n      (double(*)\n        (af::const_ref<double, af::flex_grid<> > const&,\n         scitbx::mat3<double> const&,\n         scitbx::vec3<double> const&,\n         bool,\n         double const&))\n           non_crystallographic_eight_point_interpolation, (\n             arg(\"map\"),\n             arg(\"gridding_matrix\"),\n             arg(\"site_cart\"),\n             arg(\"allow_out_of_bounds\")=false,\n             arg(\"out_of_bounds_substitute_value\")=0));\n    def(\"asu_eight_point_interpolation\",\n      (double(*)\n        (af::const_ref<double, af::flex_grid<> > const&,\n         crystal::direct_space_asu::asu_mappings<double> &,\n         fractional<double> const&)) asu_eight_point_interpolation);\n\n    def(\"standard_deviations_around_sites\",\n      standard_deviations_around_sites, (\n        arg(\"unit_cell\"),\n        arg(\"density_map\"),\n        arg(\"sites_cart\"),\n        arg(\"site_radii\")));\n  }\n\n} // namespace <anonymous>\n}}} // namespace cctbx::maptbx::boost_python\n\nBOOST_PYTHON_MODULE(cctbx_maptbx_ext)\n{\n  cctbx::maptbx::boost_python::init_module();\n}\n", "meta": {"hexsha": "8848775175e3e4bdf0e354cdfc4c60e108c2a7cd", "size": 36303, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cctbx/maptbx/boost_python/maptbx_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": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cctbx/maptbx/boost_python/maptbx_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": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cctbx/maptbx/boost_python/maptbx_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": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.2445054945, "max_line_length": 95, "alphanum_fraction": 0.5302592072, "num_tokens": 9707, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7248702761768249, "lm_q2_score": 0.4378234991142019, "lm_q1q2_score": 0.31736524071961536}}
{"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 binaryCompare.cpp\n * @brief Implementing integer comparison in binary representation.\n */\n#include <algorithm>\n\n#include <NTL/BasicThreadPool.h>\n#include <helib/binaryArith.h>\n\n#define BPL_ESTIMATE (30)\n// FIXME: this should really be dynamic\n\n#ifdef HELIB_DEBUG\n#include <helib/debugging.h>\n#endif\n\nnamespace helib {\n\n// returns new v[i] = \\sum_{j>=i} old v[i]\nvoid runningSums(CtPtrs& v)\n{\n  HELIB_TIMER_START;\n  for (long i = lsize(v) - 1; i > 0; i--)\n    *v[i - 1] += *v[i];\n}\n\n// a recursive function that computes\n//      e*[i] = prod_{j>=i} e[i]  and  g*[i] = e*[i+1] \\cdot g[i]\n// This function is optimized, so that instead of all the e*[i]'s\n// it only computes e*[0] and the e*[i]'s that are used in the\n// computation of the g*[i]'d\nstatic void compProducts(const CtPtrs_slice& e, const CtPtrs_slice& g)\n{\n  long n = lsize(e);\n  if (n <= 1)\n    return; // nothing to do\n#ifdef HELIB_DEBUG\n  std::cout << \"compProducts(g[\" << g.start << \"..\" << (g.start + g.sz - 1)\n            << \"],e[\" << e.start << \"..\" << (e.start + e.sz - 1) << \"])\"\n            << std::endl;\n#endif\n\n  // split the array in two, second part has size the largest 2^l < n,\n  // and first part is the rest\n\n  long ell = NTL::NumBits(n - 1) - 1; // n/2 <= 2^l < n\n  long n1 = n - (1UL << ell);         // n1 \\in [1, n/2]\n\n  // Call the recursive procedure separately on the first and second parts\n  compProducts(CtPtrs_slice(e, 0, n1), CtPtrs_slice(g, 0, n1)); // first half\n  compProducts(CtPtrs_slice(e, n1, n - n1),\n               CtPtrs_slice(g, n1, n - n1)); // second half\n\n  // Multiply the first product in the 2nd part into every product in the 1st\n  NTL_EXEC_RANGE(1 + n1, first, last)\n  for (long i = first; i < last; i++) {\n    if (i == 0)\n      e[0]->multiplyBy(*e[n1]);\n    else if (i - 1 < g.size())\n      g[i - 1]->multiplyBy(*e[n1]);\n  }\n  NTL_EXEC_RANGE_END\n#ifdef HELIB_DEBUG\n  std::cout << \" g[\" << g.start << \"..\" << (g.start + g.sz - 1) << \"], \"\n            << \" e[\" << e.start << \"..\" << (e.start + e.sz - 1)\n            << \"]:\" << std::endl;\n  for (long i = 0; i < g.size(); i++)\n    decryptAndPrint((std::cout << \"   g[\" << (i + g.start) << \"] (\"\n                               << ((void*)g[i]) << \"): \"),\n                    *g[i],\n                    *dbgKey,\n                    *dbgEa,\n                    FLAG_PRINT_POLY);\n  for (long i = 0; i < e.size(); i++)\n    decryptAndPrint((std::cout << \"   e[\" << (i + e.start) << \"] (\"\n                               << ((void*)e[i]) << \"): \"),\n                    *e[i],\n                    *dbgKey,\n                    *dbgEa,\n                    FLAG_PRINT_POLY);\n\n  std::cout << std::endl;\n#endif\n}\n\n// Compute aeqb[i] = (a==b upto bit i), agtb[i] = (aeqb[i+1] and ai>bi)\n// We assume that b.size()>a.size()\nstatic void compEqGt(CtPtrs& aeqb,\n                     CtPtrs& agtb,\n                     const CtPtrs& a,\n                     const CtPtrs& b)\n{\n  HELIB_TIMER_START;\n  const Ctxt zeroCtxt(ZeroCtxtLike, *(b.ptr2nonNull()));\n  const Context& context = zeroCtxt.getContext();\n  DoubleCRT one(context, context.allPrimes());\n  one += 1L;\n\n  resize(aeqb, lsize(b), zeroCtxt);\n  resize(agtb, lsize(a), zeroCtxt);\n\n  // First compute the local bits e[i]=(a[i]==b[i]), gt[i]=(a[i]>b[i])\n  HELIB_NTIMER_START(compEqGt1);\n  long aSize = lsize(a);\n  NTL_EXEC_RANGE(aSize, first, last)\n  for (long i = first; i < last; i++) {\n    *aeqb[i] = *b[i];               // b\n    aeqb[i]->addConstant(one, 1.0); // b+1\n    *agtb[i] = *aeqb[i];            // b+1\n    *aeqb[i] += *a[i];              // a+b+1\n    agtb[i]->multiplyBy(*a[i]);     // a(b+1)\n  }\n  NTL_EXEC_RANGE_END\n  HELIB_NTIMER_STOP(compEqGt1);\n\n  // NOTE: Usually there isn't much gain in multi-threading the loop below,\n  //    but computing b[i] can be expensive in some implementations of CtPtrs\n  HELIB_NTIMER_START(compEqGt2);\n  if (lsize(b) - aSize > 1) {\n    NTL_EXEC_RANGE(lsize(b) - aSize, first, last)\n    for (long i = first; i < last; i++) {\n      *aeqb[i + aSize] = *b[i + aSize];       // b\n      aeqb[i + aSize]->addConstant(one, 1.0); // b+1\n    }\n    NTL_EXEC_RANGE_END\n  } else if (lsize(b) - aSize == 1) {\n    *aeqb[aSize] = *b[aSize];           // b\n    aeqb[aSize]->addConstant(one, 1.0); // b+1\n  }\n  HELIB_NTIMER_STOP(compEqGt2);\n\n#ifdef HELIB_DEBUG\n  for (long i = 0; i < lsize(b); i++)\n    decryptAndPrint((std::cout << \" e[\" << i << \"]: \"),\n                    *aeqb[i],\n                    *dbgKey,\n                    *dbgEa,\n                    FLAG_PRINT_POLY);\n  for (long i = 0; i < lsize(a); i++)\n    decryptAndPrint((std::cout << \" ag[\" << i << \"]: \"),\n                    *agtb[i],\n                    *dbgKey,\n                    *dbgEa,\n                    FLAG_PRINT_POLY);\n  std::cout << std::endl;\n#endif\n\n  // Call a recursive function to compute:\n  // e*_i = \\prod_{j>=i} aeqb_i, g*_i = aeqb*_{i+1} \\cdot agtb_i\n  HELIB_NTIMER_START(compEqGt3);\n  compProducts(CtPtrs_slice(aeqb, 0), CtPtrs_slice(agtb, 0));\n  runningSums(agtb); // now ag[i] = (a>b upto bit i)\n  HELIB_NTIMER_STOP(compEqGt3);\n}\n\n// Compares two integers in binary a,b.\n// Returns max(a,b), min(a,b) and indicator bits mu=(a>b) and ni=(a<b)\nvoid compareTwoNumbersImplementation(CtPtrs& max,\n                                     CtPtrs& min,\n                                     Ctxt& mu,\n                                     Ctxt& ni,\n                                     const CtPtrs& aa,\n                                     const CtPtrs& bb,\n                                     bool twosComplement,\n                                     std::vector<zzX>* unpackSlotEncoding,\n                                     bool cmp_only)\n{\n  HELIB_TIMER_START;\n  // make sure that lsize(b) >= lsize(a)\n  const CtPtrs& a = (lsize(bb) >= lsize(aa)) ? aa : bb;\n  const CtPtrs& b = (lsize(bb) >= lsize(aa)) ? bb : aa;\n  long aSize = lsize(a);\n  long bSize = lsize(b);\n  if (aSize < 1) { // a is empty\n    mu.clear();\n    ni.clear();\n    ni.addConstant(NTL::ZZ(1L));\n    vecCopy(max, b);\n    setLengthZero(min);\n    return;\n  }\n\n  // Check that we have enough levels, try to bootstrap otherwise\n  if (findMinBitCapacity({&a, &b}) <\n      (NTL::NumBits(bSize + 1) + 2) * mu.getContext().BPL())\n    packedRecrypt(a, b, unpackSlotEncoding);\n  if (findMinBitCapacity({&a, &b}) <\n      (NTL::NumBits(bSize) + 1) * mu.getContext().BPL())\n    // the bare minimum\n    throw LogicError(\"not enough levels for comparison\");\n\n  // NOTE: this procedure minimizes the number of multiplications,\n  //       but it may use one level too many. Can we optimize it?\n\n  /* We first compute for each position i the values\n   *   e[i] = (a==b upto position i)\n   *   ag[i] = (a>b upto position i)\n   */\n\n  // We use max, min to hold the intermediate values e, ag\n  CtPtrs& e = max;\n  CtPtrs& ag = min;\n  compEqGt(e, ag, a, b);\n\n  // We are now ready to compute the bits of the result.\n\n  HELIB_NTIMER_START(compResults);\n  mu = *ag[0]; // a > b\n  ni = *ag[0];\n  ni.addConstant(NTL::ZZ(1L)); // a <= b\n  ni += *e[0];                 // a < b\n\n  if (twosComplement) {\n    // mu, ni and ag need to be inverted iff the sign bits of a and b differ.\n    // Perform this by adding both sign bits.\n    const auto flipIfDifferentSign = [&](Ctxt& ctxt) {\n      (ctxt += *aa[aa.size() - 1]) += *bb[bb.size() - 1];\n    };\n    flipIfDifferentSign(mu);\n    flipIfDifferentSign(ni);\n    for (long i = 0; i < ag.size(); ++i)\n      flipIfDifferentSign(*ag[i]);\n  }\n  if (cmp_only) {\n    return;\n  }\n\n  NTL_EXEC_RANGE(aSize, first, last)\n  for (long i = first; i < last; i++) {\n    *max[i] = *a[i];\n    *max[i] -= *b[i];\n    max[i]->multiplyBy(*ag[i]);\n\n    *min[i] = *max[i];\n    *max[i] += *b[i];\n    *min[i] -= *a[i];\n  }\n  NTL_EXEC_RANGE_END\n  for (long i = aSize; i < bSize; i++)\n    *max[i] = *b[i];\n  HELIB_NTIMER_STOP(compResults);\n}\n\nvoid compareTwoNumbers(CtPtrs& max,\n                       CtPtrs& min,\n                       Ctxt& mu,\n                       Ctxt& ni,\n                       const CtPtrs& aa,\n                       const CtPtrs& bb,\n                       bool twosComplement,\n                       std::vector<zzX>* unpackSlotEncoding)\n{\n  compareTwoNumbersImplementation(max,\n                                  min,\n                                  mu,\n                                  ni,\n                                  aa,\n                                  bb,\n                                  twosComplement,\n                                  unpackSlotEncoding,\n                                  false);\n}\n\nvoid compareTwoNumbers(Ctxt& mu,\n                       Ctxt& ni,\n                       const CtPtrs& aa,\n                       const CtPtrs& bb,\n                       bool twosComplement,\n                       std::vector<zzX>* unpackSlotEncoding)\n{\n  NTL::Vec<Ctxt> aeqb;\n  NTL::Vec<Ctxt> agtb;\n  CtPtrs_VecCt eq(aeqb);\n  CtPtrs_VecCt gr(agtb);\n  compareTwoNumbersImplementation(eq,\n                                  gr,\n                                  mu,\n                                  ni,\n                                  aa,\n                                  bb,\n                                  twosComplement,\n                                  unpackSlotEncoding,\n                                  true);\n}\n\n} // namespace helib\n", "meta": {"hexsha": "3376a7a454bcf7e412ef077ff0b68e6c8109049f", "size": 9912, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/binaryCompare.cpp", "max_stars_repo_name": "jatanloya/HElib-PSI", "max_stars_repo_head_hexsha": "b5ec2844216ac87f1e20542e31ebb98363c14a6f", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1360.0, "max_stars_repo_stars_event_min_datetime": "2015-01-02T23:57:10.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T01:25:28.000Z", "max_issues_repo_path": "src/binaryCompare.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/binaryCompare.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": 33.2617449664, "max_line_length": 77, "alphanum_fraction": 0.5102905569, "num_tokens": 2882, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6297746074044134, "lm_q2_score": 0.5039061705290805, "lm_q1q2_score": 0.31734731071361305}}
{"text": "#include \"gaussfft.hpp\"\n\n#include <boost/python/numpy.hpp>\n\n//#include <chrono>\n#include <iostream>\n\n#include \"nrlib/iotools/stringtools.hpp\"\n#include \"nrlib/grid/grid.hpp\"\n#include \"nrlib/grid/grid2d.hpp\"\n#include \"nrlib/math/constants.hpp\"\n#include \"nrlib/random/random.hpp\"\n#include \"nrlib/variogram/variogram.hpp\"\n#include \"nrlib/variogram/gaussianfield.hpp\"\n\nnamespace bp = boost::python;\n\n/***************************/\nstd::string GaussFFT::Quote()\n{\n  return \"Arc, amplitude, and curvature sustain a similar relation to each other as time, motion, and velocity, or as volume, mass, and density.\";\n}\n\n/**********************************************************************************/\nstd::vector<size_t> GaussFFT::FindGridSizeAfterPadding(NRLib::Variogram * variogram,\n                                                       size_t             nx,\n                                                       double             dx,\n                                                       size_t             ny,\n                                                       double             dy,\n                                                       size_t             nz,\n                                                       double             dz)\n{\n  std::vector<size_t> out = NRLib::FindNDimPadding(*variogram,\n                                                   nx,\n                                                   dx,\n                                                   ny,\n                                                   dy,\n                                                   nz,\n                                                   dz);\n  // Add simulation grid size to that output reflects final grid size\n  // and not padding only\n  out[0] += nx;\n  if (out.size() > 1) {\n    out[1] += ny;\n    if (out.size() > 2) {\n      out[2] += nz;\n    }\n  }\n  return out;\n}\n\n/*********************************************************************/\nNRLib::Variogram * GaussFFT::CreateVariogram(const std::string & type,\n                                             double              range_x,\n                                             double              range_y,\n                                             double              range_z,\n                                             double              azimuth_angle,\n                                             double              dip_angle,\n                                             double              power)\n{\n  if (range_y < 0.0)\n    range_y = range_x;\n  if (range_z < 0.0)\n    range_z = range_x;\n\n  azimuth_angle *= NRLib::Degree;\n  dip_angle *= NRLib::Degree;\n\n  NRLib::Variogram::Type t;\n  std::string utype = NRLib::Uppercase(type);\n  if (utype == \"CONSTANT\")\n    t = NRLib::Variogram::CONSTANT;\n  else if (utype == \"EXPONENTIAL\")\n    t = NRLib::Variogram::EXPONENTIAL;\n  else if (utype == \"GAUSSIAN\")\n    t = NRLib::Variogram::GAUSSIAN;\n  else if (utype == \"GENERAL_EXPONENTIAL\")\n    t = NRLib::Variogram::GENERAL_EXPONENTIAL;\n  else if (utype == \"MATERN32\")\n    t = NRLib::Variogram::MATERN32;\n  else if (utype == \"MATERN52\")\n    t = NRLib::Variogram::MATERN52;\n  else if (utype == \"MATERN72\")\n    t = NRLib::Variogram::MATERN72;\n  else if (utype == \"SPHERICAL\")\n    t = NRLib::Variogram::SPHERICAL;\n  else\n    t = NRLib::Variogram::SPHERICAL;\n\n  return NRLib::Variogram::Create(t, power, range_x, range_y, range_z, azimuth_angle, dip_angle, 1.0);\n}\n\n/******************************************************************/\nbp::numpy::ndarray  GaussFFT::Simulate(NRLib::Variogram * variogram,\n                                       size_t             nx,\n                                       double             dx,\n                                       size_t             ny,\n                                       double             dy,\n                                       size_t             nz,\n                                       double             dz)\n{\n  return SimulateWithAdvancedSettings(variogram, nx, dx, ny, dy, nz, dz, -1, -1,-1, 1.0, 1.0, 1.0);\n}\n\n/***********************************************************************************/\nbp::numpy::ndarray  GaussFFT::SimulateWithAdvancedSettings(NRLib::Variogram * variogram,\n                                                           size_t             nx,\n                                                           double             dx,\n                                                           size_t             ny,\n                                                           double             dy,\n                                                           size_t             nz,\n                                                           double             dz,\n                                                           int                padding_x,\n                                                           int                padding_y,\n                                                           int                padding_z,\n                                                           double             scaling_x,\n                                                           double             scaling_y,\n                                                           double             scaling_z)\n{\n  try {\n    NRLib::Random::GetStartSeed();\n  }\n  catch (NRLib::Exception e) {\n    // NRLib::Random is not initialized yet. Use empty initializer:\n    NRLib::Random::Initialize();\n  }\n  std::vector<double> result;\n  if (ny <= 1U || dy < 0.0) {\n    result = GaussFFT::Simulate1D(variogram, nx, dx,                 padding_x,                       scaling_x                      );\n  }\n  else if (nz <= 1U || dz < 0.0) {\n    result = GaussFFT::Simulate2D(variogram, nx, dx, ny, dy,         padding_x, padding_y,            scaling_x, scaling_y           );\n  }\n  else {\n    result = GaussFFT::Simulate3D(variogram, nx, dx, ny, dy, nz, dz, padding_x, padding_y, padding_z, scaling_x, scaling_y, scaling_z);\n  }\n\n  bp::numpy::dtype dt = bp::numpy::dtype::get_builtin<double>();\n  bp::tuple shape = bp::make_tuple(result.size());\n  bp::tuple stride = bp::make_tuple(sizeof(double));\n  bp::object owner;\n  bp::numpy::ndarray np_result = bp::numpy::from_data(&result[0], dt, shape, stride, owner);\n  return np_result.copy();\n}\n\n/********************************************************************/\nstd::vector<double> GaussFFT::Simulate1D(NRLib::Variogram * variogram,\n                                         size_t             nx,\n                                         double             dx,\n                                         int                padding_x,\n                                         double             scaling_x)\n{\n  std::vector<double> values;\n  // Have to allocate memory (for some reason) before running the simulation\n  values.resize(nx);\n  NRLib::Simulate1DGaussianField(*variogram,\n                                 nx,\n                                 dx,\n                                 values,\n                                 NULL, // Will use NRLib::Random state\n                                 padding_x,\n                                 scaling_x);\n  return values;\n}\n\n/********************************************************************/\nstd::vector<double> GaussFFT::Simulate2D(NRLib::Variogram * variogram,\n                                         size_t             nx,\n                                         double             dx,\n                                         size_t             ny,\n                                         double             dy,\n                                         int                padding_x,\n                                         int                padding_y,\n                                         double             scaling_x,\n                                         double             scaling_y)\n{\n  std::vector<NRLib::Grid2D<double> > fields;\n  NRLib::Simulate2DGaussianField(*variogram,\n                                 nx,\n                                 dx,\n                                 ny,\n                                 dy,\n                                 1,\n                                 fields,\n                                 NULL, // Will use NRLib::Random state\n                                 padding_x,\n                                 padding_y,\n                                 scaling_x,\n                                 scaling_y);\n  return fields[0].GetStorage();\n}\n\n/*********************************************************************/\nstd::vector<double> GaussFFT::Simulate3D(NRLib::Variogram * variogram,\n                                         size_t             nx,\n                                         double             dx,\n                                         size_t             ny,\n                                         double             dy,\n                                         size_t             nz,\n                                         double             dz,\n                                         int                padding_x,\n                                         int                padding_y,\n                                         int                padding_z,\n                                         double             scaling_x,\n                                         double             scaling_y,\n                                         double             scaling_z)\n{\n  std::vector<NRLib::Grid<double> > fields;\n  NRLib::Simulate3DGaussianField(*variogram,\n                                 nx,\n                                 dx,\n                                 ny,\n                                 dy,\n                                 nz,\n                                 dz,\n                                 1,\n                                 fields,\n                                 padding_x,\n                                 padding_y,\n                                 padding_z,\n                                 scaling_x,\n                                 scaling_y,\n                                 scaling_z);\n  return fields[0].GetStorage();\n}\n", "meta": {"hexsha": "d46c92c78a8928cb729c5689d2c68745fcbae738", "size": 10058, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/gaussfft.cpp", "max_stars_repo_name": "equinor/gaussianfft", "max_stars_repo_head_hexsha": "3865dcd02fdba566be7be662da77f653950b51ac", "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/gaussfft.cpp", "max_issues_repo_name": "equinor/gaussianfft", "max_issues_repo_head_hexsha": "3865dcd02fdba566be7be662da77f653950b51ac", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-09-24T14:03:33.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-24T14:03:33.000Z", "max_forks_repo_path": "src/gaussfft.cpp", "max_forks_repo_name": "equinor/gaussianfft", "max_forks_repo_head_hexsha": "3865dcd02fdba566be7be662da77f653950b51ac", "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.5044247788, "max_line_length": 146, "alphanum_fraction": 0.3389341817, "num_tokens": 1678, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6297746074044134, "lm_q2_score": 0.5039061705290805, "lm_q1q2_score": 0.31734731071361305}}
{"text": "﻿#include \"comfi.hpp\"\n#include <armadillo>\n#include \"viennacl/matrix.hpp\"\n#include \"viennacl/matrix_proxy.hpp\"\n#include \"viennacl/forwards.h\"\n\nusing namespace arma;\n\nvcl_mat comfi::operators::jm1(const vcl_mat &xn, comfi::types::Context ctx) {\n  //make sure the dimension exists\n  if ((ctx.bc_down == comfi::types::DIMENSIONLESS) ||\n      (ctx.nz == 1)) {\n    return xn;\n  }\n  //shift values\n  vcl_mat xn_jm1(xn.size1(), xn.size2());\n  viennacl::range eq(0, ctx.num_of_eq);\n  static viennacl::range jm1(0, ctx.num_of_grid()-ctx.nx);\n  static viennacl::range j(ctx.nx, ctx.num_of_grid());\n  viennacl::project(xn_jm1, j, eq) = viennacl::project(xn, jm1, eq);\n\n  //boundary conditions\n  if (ctx.bc_down == comfi::types::NEUMANN) {\n    static viennacl::range edge(0, ctx.nx);\n    viennacl::project(xn_jm1, edge, eq) = viennacl::project(xn, edge, eq);\n  }\n  if (ctx.bc_down == comfi::types::PERIODIC) {\n    static viennacl::range start(ctx.num_of_grid()-ctx.nx, ctx.num_of_grid());\n    static viennacl::range edge(0, ctx.nx);\n    viennacl::project(xn_jm1, edge, eq) = viennacl::project(xn, start, eq);\n  }\n\n  return xn_jm1;\n}\n\nvcl_mat comfi::operators::jp1(const vcl_mat &xn, comfi::types::Context ctx) {\n\n  //make sure the dimension exists\n  if ((ctx.bc_up == comfi::types::DIMENSIONLESS) ||\n      (ctx.nz == 1)) {\n    return xn;\n  }\n  \n  //shift values\n  vcl_mat xn_jp1(xn.size1(), xn.size2());\n  static viennacl::range eq(0, ctx.num_of_eq);\n  static viennacl::range jp1(inds(0, 1, ctx), ctx.num_of_grid());\n  static viennacl::range j(0, ctx.num_of_grid()-ctx.nx);\n  viennacl::project(xn_jp1, j, eq) = viennacl::project(xn, jp1, eq);\n\n  //boundary conditions\n  if (ctx.bc_up == comfi::types::NEUMANN) {\n    static viennacl::range edge(ctx.num_of_grid()-ctx.nx, ctx.num_of_grid());\n    viennacl::project(xn_jp1, edge, eq) = viennacl::project(xn, edge, eq);\n  }\n  if (ctx.bc_up == comfi::types::PERIODIC) {\n    static viennacl::range edge(ctx.num_of_grid()-ctx.nx, ctx.num_of_grid());\n    static viennacl::range start(0, ctx.nx);\n    viennacl::project(xn_jp1, edge, eq) = viennacl::project(xn, start, eq);\n  }\n\n  return xn_jp1;\n}\n\nvcl_mat comfi::operators::ip1(const vcl_mat &xn, comfi::types::Context ctx) {\n\n  //make sure the dimension exists\n  if ((ctx.bc_right == comfi::types::DIMENSIONLESS) ||\n      (ctx.nx == 1)) {\n    return xn;\n  }\n\n  /* // TODO: Fix viennacl so that this method is working (preferred) */\n  /* //shift values */\n  /* vcl_mat xn_ip1(xn.size1(), xn.size2()); */\n  /* viennacl::range eq(0, xn.size1()); */\n  /* viennacl::range ip1[ctx.nz]; */\n  /* viennacl::range i[ctx.nz]; */\n  /* #pragma omp parallel for schedule(dynamic) */\n  /* for(uint j = 0; j < ctx.nz; j++) { */\n  /*    ip1[j] = viennacl::range(inds(1, j, ctx), inds(ctx.nx-1, j, ctx)+1); */\n  /*    i[j] = viennacl::range(inds(0, j, ctx), inds(ctx.nx-2, j, ctx)+1); */\n  /* } */\n  /* /1* #pragma omp parallel for *1/ */ \n  /* for(uint j = 0; j < ctx.nz; j++) { */\n  /*   viennacl::project(xn_ip1, eq, i[j]) = viennacl::project(xn, eq, ip1[j]); */\n  /* } */\n\n  /* //boundary conditions */\n  /* if (ctx.bc_right == comfi::types::NEUMANN) { */\n  /*   viennacl::slice eq(0, 1, ctx.num_of_eq); */\n  /*   viennacl::slice edge(inds(ctx.nx-1, 0, ctx), ctx.nx, ctx.nz); */\n  /*   viennacl::project(xn_ip1, edge, eq) = viennacl::project(xn, edge, eq); */\n  /* } */\n  /* if (ctx.bc_right == comfi::types::PERIODIC) { */\n  /*   viennacl::slice eq(0, 1, ctx.num_of_eq); */\n  /*   viennacl::slice edge(inds(ctx.nx-1, 0, ctx), ctx.nx, ctx.nz); */\n  /*   viennacl::slice start(0, ctx.nx, ctx.nz); */\n  /*   viennacl::project(xn_ip1, edge, eq) = viennacl::project(xn, start, eq); */\n  /* } */\n\n  static const sp_mat cpu_Pip1 = comfi::operators::buildPip1(ctx);\n  static vcl_sp_mat Pip1(ctx.num_of_grid(), ctx.num_of_grid());\n  static bool created = false;\n  if (!created) { viennacl::copy(cpu_Pip1, Pip1); created = true; }\n  vcl_mat xn_ip1 = viennacl::linalg::prod(Pip1, xn);\n\n  return xn_ip1;\n}\n\nvcl_mat comfi::operators::im1(const vcl_mat &xn, comfi::types::Context ctx) {\n  //make sure the dimension exists\n  if ((ctx.bc_left == comfi::types::DIMENSIONLESS) ||\n      (ctx.nx == 1)) {\n    return xn;\n  }\n  \n  /* // TODO: Make this method work through changing viennacl (preferred) */\n  /* //shift values */\n  /* vcl_mat xn_im1(xn.size1(), xn.size2()); */\n  /* viennacl::range eq(0, xn.size1()); */\n  /* viennacl::range im1[ctx.nz]; */\n  /* viennacl::range i[ctx.nz]; */\n  /* #pragma omp parallel for schedule(dynamic) */\n  /* for(uint j = 0; j < ctx.nz; j++) { */\n  /*   im1[j] = viennacl::range(inds(0, j, ctx), inds(ctx.nx()-2, j, ctx)+1); */\n  /*   i[j] = viennacl::range(inds(1, j, ctx), inds(ctx.nx()-1, j, ctx)+1); */\n  /* } */\n  /* for(uint j = 0; j < ctx.nz(); j++) { */\n  /*   viennacl::project(xn_im1, eq, i[j]) = viennacl::project(xn, eq, im1[j]); */\n  /* } */\n\n  /* //boundary conditions */\n  /* if (ctx.bc_left == comfi::types::NEUMANN) { */\n  /*   viennacl::slice eq(0, 1, ctx.num_of_eq); */\n  /*   viennacl::slice start(0, ctx.nx, ctx.nz); */\n  /*   viennacl::project(xn_im1, start, eq) = viennacl::project(xn, start, eq); */\n  /* } */\n  /* if (ctx.bc_left == comfi::types::PERIODIC) { */\n  /*   viennacl::slice eq(0, 1, ctx.num_of_eq); */\n  /*   viennacl::slice edge(inds(ctx.nx-1, 0, ctx), ctx.nx, ctx.nz); */\n  /*   viennacl::slice start(0, ctx.nx, ctx.nz); */\n  /*   viennacl::project(xn_im1, start, eq) = viennacl::project(xn, edge, eq); */\n  /* } */\n\n  static const sp_mat cpu_Pim1 = comfi::operators::buildPim1(ctx);\n  static vcl_sp_mat Pim1(ctx.num_of_grid(), ctx.num_of_grid());\n  static bool created = false;\n  if (!created) { viennacl::copy(cpu_Pim1, Pim1); created = true; }\n  vcl_mat xn_im1 = viennacl::linalg::prod(Pim1, xn);\n\n  return xn_im1;\n}\n\nconst sp_mat comfi::operators::buildPip1(comfi::types::Context &ctx) {\n  umat locations;\n  urowvec loci = zeros<urowvec>(ctx.num_of_grid());\n  urowvec locj = zeros<urowvec>(ctx.num_of_grid());\n  vec values = ones<vec>(ctx.num_of_grid());\n  const comfi::types::BoundaryCondition BC = ctx.bc_right;\n\n  #pragma omp parallel for collapse(2)\n  for (uint i=0; i<ctx.nx; i++){ for(uint j=0; j<ctx.nz; j++) {\n    // indexing\n    const int           ij = inds(i, j, ctx);\n    int                 ip1j = inds(i+1, j, ctx);\n\n    //BC\n    if (i==ctx.nx-1 && (BC==comfi::types::MIRROR || BC==comfi::types::NEUMANN)) { ip1j = ij; }\n    else if (i==ctx.nx-1 && BC==comfi::types::PERIODIC) { ip1j = inds(0, j, ctx); }\n    else if (BC==comfi::types::DIMENSIONLESS) { ip1j = inds(0, j, ctx); }\n\n    loci(ij) = ip1j;\n    locj(ij) = ij;\n  }}\n\n  locations.insert_rows(0, loci);\n  locations.insert_rows(1, locj);\n  return sp_mat(true, locations, values, ctx.num_of_grid(), ctx.num_of_grid());\n}\n\nconst sp_mat comfi::operators::buildPim1(comfi::types::Context &ctx) {\n  umat locations;\n  urowvec loci = zeros<urowvec>(ctx.num_of_grid());\n  urowvec locj = zeros<urowvec>(ctx.num_of_grid());\n  vec values = ones<vec>(ctx.num_of_grid());\n  const comfi::types::BoundaryCondition BC = ctx.bc_left;\n\n  #pragma omp parallel for collapse(2)\n  for (uint i=0; i<ctx.nx; i++){ for(uint j=0; j<ctx.nz; j++) {\n    // indexing\n    const int           ij = inds(i, j, ctx);\n    int                 im1j = inds(i-1, j, ctx);\n\n    //BC\n    if (i==0 && (BC==comfi::types::MIRROR || BC==comfi::types::NEUMANN)) { im1j = ij; }\n    else if (i==0 && BC==comfi::types::PERIODIC) { im1j = inds(ctx.nx-1, j, ctx);}\n    else if (BC==comfi::types::DIMENSIONLESS) { im1j = inds(0, j, ctx);}\n\n    loci(ij) = im1j;\n    locj(ij) = ij;\n  }}\n\n  locations.insert_rows(0, loci);\n  locations.insert_rows(1, locj);\n  return sp_mat(true, locations, values, ctx.num_of_grid(), ctx.num_of_grid());\n}\n\n/*\nvim: tabstop=2\nvim: shiftwidth=2\nvim: smarttab\nvim: expandtab\n*/\n", "meta": {"hexsha": "9e3ed2cbeffa21dbdfec38a3b654f106efc275f1", "size": 7748, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/operators.cpp", "max_stars_repo_name": "qalshidi/comfi", "max_stars_repo_head_hexsha": "59835f0ab4f54dea0ecb44405f583c9c06ad21bb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-06-17T22:10:35.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-17T22:10:35.000Z", "max_issues_repo_path": "src/operators.cpp", "max_issues_repo_name": "qalshidi/comfi", "max_issues_repo_head_hexsha": "59835f0ab4f54dea0ecb44405f583c9c06ad21bb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/operators.cpp", "max_forks_repo_name": "qalshidi/comfi", "max_forks_repo_head_hexsha": "59835f0ab4f54dea0ecb44405f583c9c06ad21bb", "max_forks_repo_licenses": ["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.0372093023, "max_line_length": 94, "alphanum_fraction": 0.6122870418, "num_tokens": 2719, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6297745935070808, "lm_q2_score": 0.5039061705290805, "lm_q1q2_score": 0.3173473037106614}}
{"text": "#include \"ros/ros.h\"\n#include \"cv_bridge/cv_bridge.h\"\n#include \"image_transport/image_transport.h\"\n#include \"sensor_msgs/Image.h\"\n#include \"sensor_msgs/image_encodings.h\"\n#include \"eigen3/Eigen/Core\"\n#include \"eigen3/Eigen/Dense\"\n#include \"opencv2/highgui/highgui.hpp\"\n#include \"opencv2/core/core.hpp\"\n#include \"opencv2/features2d/features2d.hpp\"\n#include <opencv2/calib3d/calib3d.hpp>\n#include <opencv2/core/eigen.hpp>\n#include <boost/foreach.hpp>\n#include <chrono>\n#include <pcl/io/pcd_io.h>\n// #include <pcl/common/impl/io.hpp>\n#include \"pcl_ros/point_cloud.h\"\n#include <pcl_conversions/pcl_conversions.h>\n#include <pcl/point_types.h>\n#include <pcl/PCLPointCloud2.h>\n#include <pcl/conversions.h>\n#include <pcl_ros/transforms.h>\n#include <sophus/se3.hpp>\n#include <iostream>\n#include <fstream>\n#include <pangolin/pangolin.h>\n#include \"geometry_msgs/PoseStamped.h\"\n\nusing namespace std;\nusing namespace Eigen;\nusing namespace cv;\nclass getXYZfromPoint\n{\n\nprivate:\n    ros::NodeHandle nh;\n    ros::Subscriber sub;\n    ros::Publisher pub;\n    sensor_msgs::Image image_;\n    geometry_msgs::PoseStamped robot_pose;\n    cv::Mat cvColorImgMat;\n    cv::Mat cvColorImgMat2;\n    cv::Mat r, t;\n    pcl::PCLPointCloud2 pcl_pc2;\n    pcl::PCLPointCloud2 pcl_pc2l;\n    uint8_t flag=0;\n    long int cnt = 0;\n    \n    typedef std::vector<Eigen::Vector2d, Eigen::aligned_allocator<Eigen::Vector2d>> VecVector2d;\n    typedef std::vector<Eigen::Vector3d, Eigen::aligned_allocator<Eigen::Vector3d>> VecVector3d;\n// cv::Mat color = cv::Mat::zeros(cv::Size(640,480,3),CV_64FC1);\npublic:\n    getXYZfromPoint(){\n        // sub = nh.subscribe<pcl::PointCloud<pcl::PointXYZ>>(\"/camera/depth_registered/points\",1,&getXYZfromPoint::callback,this);\n        sub = nh.subscribe(\"/camera/depth_registered/points\",5,&getXYZfromPoint::callback,this);\n        pub = nh.advertise<geometry_msgs::PoseStamped>(\"robot_pose\",1);\n    }\n    void callback(const sensor_msgs::PointCloud2ConstPtr& point){\n        cv::Point3f d;\n        std::vector<cv::Point3f> pts_3d,pts_3d_last;\n        std::vector<cv::Point2f> pts_2d,pts_2d_last;\n        vector<Isometry3d, Eigen::aligned_allocator<Isometry3d>> poses;\n        cnt = 0;\n        //当前帧数据\n        cv_bridge::CvImagePtr cvImagePtr;\n        pcl_conversions::toPCL(*point,pcl_pc2);\n        pcl::PointCloud<pcl::PointXYZ>::Ptr temp_cloud(new pcl::PointCloud<pcl::PointXYZ>);\n        pcl::PointCloud<pcl::PointXYZ>::Ptr temp_cloud_last(new pcl::PointCloud<pcl::PointXYZ>);\n        pcl::fromPCLPointCloud2(pcl_pc2,*temp_cloud);\n        //now we know image(x,y) → point2(y*640+x)\n        // BOOST_FOREACH(const pcl::PointXYZ& pt,temp_cloud->points){\n        //     cnt++;\n        //     if(isnan(pt.x)||isnan(pt.y)||isnan(pt.z))\n        //     continue;\n        //     ROS_INFO(\"cnt %d\",cnt);\n        //     ROS_INFO(\"%f %f %f\",pt.x,pt.y,pt.z);\n        // }\n        ROS_INFO(\"Cloud:width = %d,height = %d\",temp_cloud->width,temp_cloud->height);\n        try\n        {\n            pcl::toROSMsg(*point,image_);\n        }\n        catch(std::runtime_error e)\n        {\n            ROS_ERROR_STREAM(\"Error in converting cloud to image message: \" << e.what());\n        }\n        try{\n            cvImagePtr = cv_bridge::toCvCopy(image_,sensor_msgs::image_encodings::BGR8);\n        }catch(cv_bridge::Exception e){\n            ROS_ERROR_STREAM(\"Cv_bridge Exception:\" << e.what());\n            return;\n        }\n        cvColorImgMat = cvImagePtr->image;\n\n        //上一帧的数据\n        if(flag==0){//如果是第一次进入，则和第一帧解算相同\n            // pcl::PointCloud<pcl::PointXYZ>::Ptr temp_cloud_last(new pcl::PointCloud<pcl::PointXYZ>);\n            pcl::fromPCLPointCloud2(pcl_pc2,*temp_cloud_last);\n            cvColorImgMat2 = cvImagePtr->image;\n            flag =2;\n        }else{\n            // pcl::PointCloud<pcl::PointXYZ>::Ptr temp_cloud_last(new pcl::PointCloud<pcl::PointXYZ>);\n            pcl::fromPCLPointCloud2(pcl_pc2l,*temp_cloud_last);      \n            // cvColorImgMat2 = cvImagePtr->image;      \n        }\n        // cvColorImgMat2 = cvImagePtr->image;\n        std::vector<cv::KeyPoint> keypoints,keypoints2;\n        cv::Mat descriptors,descriptors2;\n        cv::Ptr<cv::FeatureDetector> detector = cv::ORB::create();\n        cv::Ptr<cv::DescriptorExtractor> descriptor = cv::ORB::create();\n        cv::Ptr<cv::DescriptorMatcher> matcher = cv::DescriptorMatcher::create(\"BruteForce-Hamming\");\n        std::chrono::steady_clock::time_point t1 = std::chrono::steady_clock::now();\n        detector->detect(cvColorImgMat,keypoints);\n        detector->detect(cvColorImgMat2,keypoints2);\n        descriptor->compute(cvColorImgMat,keypoints,descriptors);\n        descriptor->compute(cvColorImgMat2,keypoints2,descriptors2);\n        std::chrono::steady_clock::time_point t2 = std::chrono::steady_clock::now();\n        std::chrono::duration<double> time_used = std::chrono::duration_cast<std::chrono::duration<double>>(t2 - t1);\n        ROS_INFO(\"extract ORB cost = %f seconds\",time_used.count());\n\n        //match\n        std::vector<cv::DMatch> matches;\n        t1 = std::chrono::steady_clock::now();\n        try\n        {\n            matcher->match(descriptors,descriptors2,matches);\n        }\n        catch(const cv::Exception& e)\n        {\n            cout<< e.what() <<endl;\n        }\n        \n\n        t2 = std::chrono::steady_clock::now();\n        time_used = std::chrono::duration_cast<std::chrono::duration<double>>(t2 - t1);\n        ROS_INFO(\"match ORB cost %f seconds\",time_used.count());\n        \n        //chose better\n        auto min_max = std::minmax_element(matches.begin(),matches.end(),\n            [](const cv::DMatch &m1,const cv::DMatch &m2){return m1.distance < m2.distance;});\n        double min_dist = min_max.first->distance;\n        double max_dist = min_max.second->distance;\n        std::vector<cv::DMatch> good_matches;\n        for (int i = 0; i < descriptors.rows; i++){\n            if(matches[i].distance <= std::max(2 * min_dist,30.0))\n                good_matches.push_back(matches[i]);\n        }\n        cout << \"一共找到了 %d 组匹配点\" << good_matches.size() <<endl;\n        ofstream ofs;\n        ofs.open(\"/home/bonoy/data/ORBfeature.txt\",ios::app);\n        ofs << \"time \" << time_used.count() << \"num\" << good_matches.size() <<endl;\n        ofs.close();\n        //获取3D点\n        // BOOST_FOREACH(cv::DMatch m,good_matches){\n            cv::DMatch m;\n            for(int i=0;i<good_matches.size();i++){\n            m = good_matches[i];\n            d.x = temp_cloud_last->points[int(keypoints2[m.queryIdx].pt.y)*640 + int(keypoints2[m.queryIdx].pt.x)].x;\n            d.y = temp_cloud_last->points[int(keypoints2[m.queryIdx].pt.y)*640 + int(keypoints2[m.queryIdx].pt.x)].y;\n            d.z = temp_cloud_last->points[int(keypoints2[m.queryIdx].pt.y)*640 + int(keypoints2[m.queryIdx].pt.x)].z;      \n            if(isnan(d.x)||isnan(d.y)||isnan(d.z))\n                continue;\n            pts_3d.push_back(d);\n            pts_2d.push_back(keypoints[m.trainIdx].pt);\n            // cout << \"X: \"<<d.x << \" Y: \" << d.y << \" Z: \"<< d.z << endl;\n            // cout << \"x:\" << int(keypoints2[m.queryIdx].pt.x) << \" y:\" << int(keypoints2[m.queryIdx].pt.y) <<endl;\n            // cout << \"u:\" << int(525.0*(d.x/d.z)+319.5) << \" v:\" << int(525*(d.y/d.z)+239.5) <<endl;\n            // // ROS_INFO(\"u %d v %d\",i,121);\n        }\n        std::cout << \"3d-2s pairs: \" << pts_3d.size() << std::endl;\n        cv::Mat K = (cv::Mat_<double>(3, 3) << 525.0, 0, 319.5, 0, 525.0, 239.5, 0, 0, 1);\n        //Opencv 解位姿\n        t1 = std::chrono::steady_clock::now();\n        try{\n            cv::solvePnP(pts_3d, pts_2d, K, cv::Mat(), r, t, false,CV_ITERATIVE); \n        }catch(const cv::Exception& e)\n        {\n            cout<< e.what() <<endl;\n        }\n        // 调用OpenCV 的 PnP 求解，可选择EPNP，DLS等方法\n        cv::Mat R(3,3,CV_64FC1);\n        Eigen::Matrix3d rotation_matrix;\n        Eigen::Vector3d eigent;\n        cv::Rodrigues(r, R); // r为旋转向量形式，用Rodrigues公式转换为矩阵\n        t2 = std::chrono::steady_clock::now();\n        time_used = std::chrono::duration_cast<std::chrono::duration<double>>(t2 - t1);\n        std::cout << \"solve pnp in opencv cost time: \" << time_used.count() << \" seconds.\" << std::endl;\n\n        std::cout << \"R=\" << std::endl << R << std::endl;\n        std::cout << \"t=\" << std::endl << t << std::endl;\n        cv::cv2eigen(R,rotation_matrix);\n        cv::cv2eigen(t,eigent);\n        Eigen::Quaterniond qua(rotation_matrix);\n        robot_pose.header.stamp = point->header.stamp;\n        robot_pose.header.frame_id = \"robot_pose\";\n        robot_pose.pose.position.x = eigent(0);\n        robot_pose.pose.position.y = eigent(1);\n        robot_pose.pose.position.z = eigent(2);\n        robot_pose.pose.orientation.x = qua.x();\n        robot_pose.pose.orientation.y = qua.y();\n        robot_pose.pose.orientation.z = qua.z();\n        robot_pose.pose.orientation.w = qua.w();\n        pub.publish(robot_pose);\n\n        // Isometry3d Twr(qua);\n        // Twr.pretranslate(eigent);\n        // poses.push_back(Twr);\n        // DrawTrajectory(poses);\n        //gaussNewton 解位姿\n        // getXYZfromPoint::VecVector3d pts_3d_eigen;\n        // getXYZfromPoint::VecVector2d pts_2d_eigen;\n        // for (size_t i = 0; i < pts_3d.size(); ++i) {\n        //     pts_3d_eigen.push_back(Eigen::Vector3d(pts_3d[i].x, pts_3d[i].y, pts_3d[i].z));\n        //     pts_2d_eigen.push_back(Eigen::Vector2d(pts_2d[i].x, pts_2d[i].y));\n        // }\n        // std::cout << \"calling bundle adjustment by gauss newton \" << std::endl;\n        // Sophus::SE3d pose_gn;\n        // t1 = std::chrono::steady_clock::now();\n        // getXYZfromPoint::bundleAdjustmentGaussNewton(pts_3d_eigen,pts_2d_eigen,K,pose_gn);\n        // t2 = std::chrono::steady_clock::now();\n        // time_used = std::chrono::duration_cast<std::chrono::duration<double>>(t2 - t1);\n        // std::cout << \"solve pnp by gauss newton cost time: \" << time_used.count() << \" seconds.\" << std::endl;\n        //保存上一帧的数据\n        // pcl_pc2l = pcl_pc2;\n        pcl::copyPointCloud(*pcl_pc2,*pcl_pc2l);\n        cvColorImgMat.copyTo(cvColorImgMat2);\n        //draw answer\n        cv::Mat img_match;\n        cv::Mat img_goodmatch;\n        cv::drawMatches(cvColorImgMat,keypoints,cvColorImgMat2,keypoints2,good_matches,img_goodmatch);\n        cv::imshow(\"good matches\",img_goodmatch);\n        // cv::imshow(\"grayview\",cvGrayImgMat);\n        cv::waitKey(5);\n        // ROS_INFO(\"%f %f %f\",point->points[240000].b,point->points[240000].g,point->points[240000].r);\n    }\nvoid bundleAdjustmentGaussNewton(const getXYZfromPoint::VecVector3d &points_3d,const getXYZfromPoint::VecVector2d &points_2d,const cv::Mat &K,Sophus::SE3d &pose) {\n        typedef Eigen::Matrix<double,6,1> Vector6d;\n        const int iterations = 10;\n        double cost = 0,lastCost = 0;\n        double fx = K.at<double>(0,0);\n        double fy = K.at<double>(1,1);\n        double cx = K.at<double>(0,2);\n        double cy = K.at<double>(1,2);\n        for(int iter = 0;iter < iterations; iter++){\n            Eigen::Matrix<double,6,6> H = Eigen::Matrix<double,6,6>::Zero();\n            Vector6d b = Vector6d::Zero();\n            cost = 0;\n            //compute cost\n            for(int i = 0;i < points_3d.size(); i++){\n                Eigen::Vector3d pc = pose * points_3d[i];\n                double inv_z = 1.0 / pc[2];\n                double inv_z2 = inv_z * inv_z;\n                Eigen::Vector2d proj(fx * pc[0] / pc[2] + cx,fy * pc[1] / pc[2] + cy);\n                Eigen::Vector2d e = points_2d[i] - proj;\n                cost+=e.squaredNorm();\n\n                Eigen::Matrix<double,2,6> J;\n                J << -fx * inv_z,\n                0,\n                fx * pc[0] * inv_z2,\n                fx * pc[0] * pc[1] * inv_z2,\n                -fx - fx * pc[0] * pc[0] * inv_z2,\n                fx * pc[1] * inv_z,\n                0,\n                -fy * inv_z,\n                fy * pc[1] * inv_z2,\n                fy + fy * pc[1] * pc[1] * inv_z2,\n                -fy * pc[0] * pc[1] * inv_z2,\n                -fy * pc[0] * inv_z;\n\n                H += J.transpose() * J;\n                b += -J.transpose() * e;\n            }\n            Vector6d dx;\n            dx = H.ldlt().solve(b);\n            if(isnan(dx[0])){\n                std::cout << \"result is nan!\" << std::endl;\n                break;\n            }\n            \n            if(iter > 0 && cost >= lastCost){\n                // cost increase, update is not good\n                std::cout << \"cost: \" << cost << \", last cost: \" << lastCost << std::endl;\n                break;\n            }\n\n            //update estimation\n            pose = Sophus::SE3d::exp(dx) * pose;\n            lastCost = cost;\n            std::cout << \"iteration \" << iter << \" cost=\" << std::setprecision(12) << cost << std::endl;\n            if(dx.norm() < 1e-6){\n                break;\n            }\n        }\n        std::cout << \"pose by g-n \\n\" << pose.matrix() <<std::endl;\n        // return pose;\n    }\nvoid DrawTrajectory(vector<Isometry3d, Eigen::aligned_allocator<Isometry3d>> poses){\n    pangolin::CreateWindowAndBind(\"Trajectory Viewer\", 1024, 768);\n  glEnable(GL_DEPTH_TEST);\n  glEnable(GL_BLEND);\n  glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);\n\n  pangolin::OpenGlRenderState s_cam(\n    pangolin::ProjectionMatrix(1024, 768, 500, 500, 512, 389, 0.1, 1000),\n    pangolin::ModelViewLookAt(0, -0.1, -1.8, 0, 0, 0, 0.0, -1.0, 0.0)\n  );\n\n  pangolin::View &d_cam = pangolin::CreateDisplay()\n    .SetBounds(0.0, 1.0, 0.0, 1.0, -1024.0f / 768.0f)\n    .SetHandler(new pangolin::Handler3D(s_cam));\n  while (pangolin::ShouldQuit() == false) {\n    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);\n    d_cam.Activate(s_cam);\n    glClearColor(1.0f, 1.0f, 1.0f, 1.0f);\n    glLineWidth(2);\n    for (size_t i = 0; i < poses.size(); i++) {\n      // 画每个位姿的三个坐标轴\n      Vector3d Ow = poses[i].translation();\n      Vector3d Xw = poses[i] * (0.1 * Vector3d(1, 0, 0));\n      Vector3d Yw = poses[i] * (0.1 * Vector3d(0, 1, 0));\n      Vector3d Zw = poses[i] * (0.1 * Vector3d(0, 0, 1));\n      glBegin(GL_LINES);\n      glColor3f(1.0, 0.0, 0.0);\n      glVertex3d(Ow[0], Ow[1], Ow[2]);\n      glVertex3d(Xw[0], Xw[1], Xw[2]);\n      glColor3f(0.0, 1.0, 0.0);\n      glVertex3d(Ow[0], Ow[1], Ow[2]);\n      glVertex3d(Yw[0], Yw[1], Yw[2]);\n      glColor3f(0.0, 0.0, 1.0);\n      glVertex3d(Ow[0], Ow[1], Ow[2]);\n      glVertex3d(Zw[0], Zw[1], Zw[2]);\n      glEnd();\n    }\n    // 画出连线\n    for (size_t i = 0; i < poses.size(); i++) {\n      glColor3f(0.0, 0.0, 0.0);\n      glBegin(GL_LINES);\n      auto p1 = poses[i], p2 = poses[i + 1];\n      glVertex3d(p1.translation()[0], p1.translation()[1], p1.translation()[2]);\n      glVertex3d(p2.translation()[0], p2.translation()[1], p2.translation()[2]);\n      glEnd();\n    }\n    pangolin::FinishFrame();\n    pangolin::Quit();\n    //usleep(5000);   // sleep 5 ms\n  }\n}\n};\nint main(int argc, char *argv[])\n{\n    ros::init(argc,argv,\"getXYZRGBfrompoints\");\n    getXYZfromPoint get;\n    ros::spin();\n    return 0;\n}\n\n\n\n", "meta": {"hexsha": "1a7cbd710c8f8cc74dd9f79f53ad20f2f1b32aa7", "size": 14995, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/getXYZfromPoint.cpp", "max_stars_repo_name": "Bonoy0328/robot_description", "max_stars_repo_head_hexsha": "288af718fecf7122e35eb0cb8fead15fa72ca5e3", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/getXYZfromPoint.cpp", "max_issues_repo_name": "Bonoy0328/robot_description", "max_issues_repo_head_hexsha": "288af718fecf7122e35eb0cb8fead15fa72ca5e3", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/getXYZfromPoint.cpp", "max_forks_repo_name": "Bonoy0328/robot_description", "max_forks_repo_head_hexsha": "288af718fecf7122e35eb0cb8fead15fa72ca5e3", "max_forks_repo_licenses": ["Apache-2.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.6527777778, "max_line_length": 163, "alphanum_fraction": 0.5738579527, "num_tokens": 4461, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6548947290421275, "lm_q2_score": 0.4843800842769843, "lm_q1q2_score": 0.3172179640459785}}
{"text": "\n#include <QApplication>\n#include <QFileInfo>\n#include <QDir>\n#include \"GLPointCloudViewer.h\"\n#include \"QImageWidget.h\"\n#include \"QKinectGrabber.h\"\n#include \"QKinectIO.h\"\n#include <iostream>\n#include <iterator>\n#include <array>\n#include <memory>\n#include <time.h>\n\n#include \"Volumetric_helper.h\"\n#include \"Timer.h\"\n#include <Eigen/Dense>\n#include <cuda_runtime.h>\n#include <vector_types.h>\n#include \"cuda_kernels/cuda_kernels.h\"\n\n#include \"GLPointCloud.h\"\n\n#include \"helper_cuda.h\"\n#include \"helper_image.h\"\n\nstatic QVector3D colors[7] = {\n\tQVector3D(1, 0, 0), QVector3D(0, 1, 0), QVector3D(0, 0, 1),\n\tQVector3D(1, 1, 0), QVector3D(1, 0, 1), QVector3D(0, 1, 1),\n\tQVector3D(1, 1, 1) };\n\n\n\nstatic void export_obj_float4(const std::string& filename, const std::vector<float4>& vertices, const std::vector<float4>& normals)\n{\n\tstd::ofstream file;\n\tfile.open(filename);\n\t//for (const float4 v : vertices)\n\t//\tfile << std::fixed << \"v \" << v.x << ' ' << v.y << ' ' << v.z << std::endl;\n\t//for (const float4 n : normals)\n\t//\tfile << std::fixed << \"vn \" << n.x << ' ' << n.y << ' ' << n.z << std::endl;\n\n\tfor (int i = 0; i < vertices.size(); ++i)\n\t{\n\t\tconst float4& v = vertices[i];\n\t\tconst float4& n = normals[i];\n\t\tfile << std::fixed << \"v \"\n\t\t\t<< v.x << ' ' << v.y << ' ' << v.z << ' '\n\t\t\t<< ((n.x * 0.5) + 0.5) * 255 << ' ' << ((n.y * 0.5) + 0.5) * 255 << ' ' << ((n.z * 0.5) + 0.5) * 255\n\t\t\t<< std::endl;\n\t}\n\n\tfile.close();\n}\n\nvoid convert_normal_to_rgba(std::vector<float4>& normals)\n{\n\tfor (float4& n : normals)\n\t{\n\t\tn.x = (n.x * 0.5) + 0.5;\n\t\tn.y = (n.y * 0.5) + 0.5;\n\t\tn.z = (n.z * 0.5) + 0.5;\n\t\tn.w = (n.w * 0.5) + 0.5;\n\t}\n}\n\n\n\nvoid run_back_projection_with_normal_estimate(\n\tstd::vector<float4>& vertices,\n\tstd::vector<float4>& normals,\n\tconst std::vector<ushort>& depth_buffer,\n\tuint width,\n\tuint height,\n\tushort max_depth)\n{\n\tStopWatchInterface *kernel_timer = nullptr;\n\n\tushort* h_depth_buffer = (ushort*)depth_buffer.data();\n\n\tsize_t in_pitch, out_pitch;\n\n\tushort* d_depth_buffer = nullptr;\n\t// copy image data to array\n\tcheckCudaErrors(cudaMallocPitch(&d_depth_buffer, &in_pitch, sizeof(ushort) * width, height));\n\tcheckCudaErrors(cudaMemcpy2D(\n\t\td_depth_buffer,\n\t\tin_pitch,\n\t\th_depth_buffer,\n\t\tsizeof(ushort) * width,\n\t\tsizeof(ushort) * width,\n\t\theight,\n\t\tcudaMemcpyHostToDevice));\n\n\n\n\tfloat4* d_vertex_buffer;\n\tcheckCudaErrors(cudaMallocPitch(\n\t\t&d_vertex_buffer,\n\t\t&out_pitch,\n\t\twidth * sizeof(float4),\n\t\theight));\n\n\tfloat4* d_normal_buffer;\n\tcheckCudaErrors(cudaMallocPitch(\n\t\t&d_normal_buffer,\n\t\t&out_pitch,\n\t\twidth * sizeof(float4),\n\t\theight));\n\n\n\tsdkCreateTimer(&kernel_timer);\n\tsdkStartTimer(&kernel_timer);\n\n\tEigen::Matrix4f h_inverse_projection = perspective_matrix_inverse<float>(fov_y, aspect_ratio, near_plane, far_plane);\n\t//bilateralFilter_normal_estimate_float4((OutputPixelType*)dOutputImage, (InputPixelType*)dInputImage, width, height, in_pitch, out_pitch, max_depth, euclidean_delta, filter_radius, iterations, kernel_timer);\n\tback_projection_with_normal_estimation(d_vertex_buffer, d_normal_buffer, d_depth_buffer, width, height, max_depth, in_pitch, out_pitch, h_inverse_projection.data());\n\n\tcheckCudaErrors(cudaDeviceSynchronize());\n\tsdkStopTimer(&kernel_timer);\n\tstd::cout << \"Kernel Timer                              : \" << kernel_timer->getTime() << \" msec\" << std::endl;\n\tsdkDeleteTimer(&kernel_timer);\n\n\tvertices.resize(depth_buffer.size());\n\tnormals.resize(depth_buffer.size());\n\n\tcudaMemcpy2D(\n\t\tvertices.data(),\n\t\tsizeof(float4) * width,\n\t\td_vertex_buffer,\n\t\tout_pitch,\n\t\tsizeof(float4) * width,\n\t\theight,\n\t\tcudaMemcpyDeviceToHost);\n\n\tcudaMemcpy2D(\n\t\tnormals.data(),\n\t\tsizeof(float4) * width,\n\t\td_normal_buffer,\n\t\tout_pitch,\n\t\tsizeof(float4) * width,\n\t\theight,\n\t\tcudaMemcpyDeviceToHost);\n\n\n\tcheckCudaErrors(cudaFree(d_depth_buffer));\n\tcheckCudaErrors(cudaFree(d_vertex_buffer));\n\tcheckCudaErrors(cudaFree(d_normal_buffer));\n}\n\n\n\nvoid run_icp_with_normal_estimate(\n\tstd::vector<float4>& vertices_0,\n\tstd::vector<float4>& vertices_1,\n\tstd::vector<float4>& normals,\n\tstd::vector<ushort2>& indices,\n\tstd::vector<float>& distances,\n\tconst std::vector<ushort>& depth_buffer_0,\n\tconst std::vector<ushort>& depth_buffer_1,\n\tuint width,\n\tuint height,\n\tushort max_depth,\n\tconst ushort half_window_search_size)\n{\n\tStopWatchInterface *kernel_timer = nullptr;\n\n\tushort* h_depth_buffer_0 = (ushort*)depth_buffer_0.data();\n\tushort* h_depth_buffer_1 = (ushort*)depth_buffer_1.data();\n\n\tsize_t in_pitch, out_pitch, index_pitch, distance_pitch;\n\n\t\n\t//\n\t// copy depth buffer data to array\n\t// \n\tushort* d_depth_buffer_0 = nullptr;\n\tcheckCudaErrors(cudaMallocPitch(&d_depth_buffer_0, &in_pitch, sizeof(ushort) * width, height));\n\tcheckCudaErrors(cudaMemcpy2D(\n\t\td_depth_buffer_0,\n\t\tin_pitch,\n\t\th_depth_buffer_0,\n\t\tsizeof(ushort) * width,\n\t\tsizeof(ushort) * width,\n\t\theight,\n\t\tcudaMemcpyHostToDevice));\n\n\tushort* d_depth_buffer_1 = nullptr;\n\tcheckCudaErrors(cudaMallocPitch(&d_depth_buffer_1, &in_pitch, sizeof(ushort) * width, height));\n\tcheckCudaErrors(cudaMemcpy2D(\n\t\td_depth_buffer_1,\n\t\tin_pitch,\n\t\th_depth_buffer_1,\n\t\tsizeof(ushort) * width,\n\t\tsizeof(ushort) * width,\n\t\theight,\n\t\tcudaMemcpyHostToDevice));\n\n\n\t//\n\t// allocate vertex buffer in gpu\n\t// \n\tfloat4* d_vertex_buffer_0;\n\tcheckCudaErrors(cudaMallocPitch(\n\t\t&d_vertex_buffer_0,\n\t\t&out_pitch,\n\t\twidth * sizeof(float4),\n\t\theight));\n\n\tfloat4* d_vertex_buffer_1;\n\tcheckCudaErrors(cudaMallocPitch(\n\t\t&d_vertex_buffer_1,\n\t\t&out_pitch,\n\t\twidth * sizeof(float4),\n\t\theight));\n\n\t//\n\t//  allocate normal buffer in gpu\n\t//  \n\tfloat4* d_normal_buffer;\n\tcheckCudaErrors(cudaMallocPitch(\n\t\t&d_normal_buffer,\n\t\t&out_pitch,\n\t\twidth * sizeof(float4),\n\t\theight));\n\n\n\tsdkCreateTimer(&kernel_timer);\n\tsdkStartTimer(&kernel_timer);\n\n\tEigen::Matrix4f h_inverse_projection = perspective_matrix_inverse<float>(fov_y, aspect_ratio, near_plane, far_plane);\n\tback_projection_with_normal_estimation(d_vertex_buffer_0, d_normal_buffer, d_depth_buffer_0, width, height, max_depth, in_pitch, out_pitch, h_inverse_projection.data());\n\tback_projection_with_normal_estimation(d_vertex_buffer_1, d_normal_buffer, d_depth_buffer_1, width, height, max_depth, in_pitch, out_pitch, h_inverse_projection.data());\n\n\n\t//\n\t// allocate index buffer in gpu\n\t// \n\tushort2* d_index_buffer;\n\tcheckCudaErrors(cudaMallocPitch(\n\t\t&d_index_buffer,\n\t\t&index_pitch,\n\t\twidth * sizeof(ushort2),\n\t\theight));\n\n\t//\n\t// allocate index buffer in gpu\n\t// \n\tfloat* d_distances_buffer;\n\tcheckCudaErrors(cudaMallocPitch(\n\t\t&d_distances_buffer,\n\t\t&distance_pitch,\n\t\twidth * sizeof(float),\n\t\theight));\n\n\ticp_matching_vertices(d_index_buffer, d_distances_buffer, d_vertex_buffer_0, d_vertex_buffer_1, width, height, out_pitch, index_pitch, half_window_search_size);\n\t\n\n\tcheckCudaErrors(cudaDeviceSynchronize());\n\tsdkStopTimer(&kernel_timer);\n\tstd::cout << \"Kernel Timer                              : \" << kernel_timer->getTime() << \" msec\" << std::endl;\n\tsdkDeleteTimer(&kernel_timer);\n\n\tvertices_0.resize(depth_buffer_0.size());\n\tvertices_1.resize(depth_buffer_1.size());\n\tnormals.resize(depth_buffer_0.size());\n\tindices.resize(depth_buffer_0.size());\n\tdistances.resize(depth_buffer_0.size());\n\n\n\tcudaMemcpy2D(\n\t\tvertices_0.data(),\n\t\tsizeof(float4) * width,\n\t\td_vertex_buffer_0,\n\t\tout_pitch,\n\t\tsizeof(float4) * width,\n\t\theight,\n\t\tcudaMemcpyDeviceToHost);\n\n\tcudaMemcpy2D(\n\t\tvertices_1.data(),\n\t\tsizeof(float4) * width,\n\t\td_vertex_buffer_1,\n\t\tout_pitch,\n\t\tsizeof(float4) * width,\n\t\theight,\n\t\tcudaMemcpyDeviceToHost);\n\n\tcudaMemcpy2D(\n\t\tnormals.data(),\n\t\tsizeof(float4) * width,\n\t\td_normal_buffer,\n\t\tout_pitch,\n\t\tsizeof(float4) * width,\n\t\theight,\n\t\tcudaMemcpyDeviceToHost);\n\n\n\tcudaMemcpy2D(\n\t\tindices.data(),\n\t\tsizeof(ushort2) * width,\n\t\td_index_buffer,\n\t\tindex_pitch,\n\t\tsizeof(ushort2) * width,\n\t\theight,\n\t\tcudaMemcpyDeviceToHost);\n\n\tcudaMemcpy2D(\n\t\tdistances.data(),\n\t\tsizeof(float) * width,\n\t\td_distances_buffer,\n\t\tdistance_pitch,\n\t\tsizeof(float) * width,\n\t\theight,\n\t\tcudaMemcpyDeviceToHost);\n\t\n\n\tfor (int i = 0; i < width * height; ++i)\n\t{\n\t\tushort2 index = indices[i];\n\t\tint ii = index.y * width + index.x;\n\t\t//std::cout << index.x << \", \" << index.y << std::endl;\n\n\t\tif (ii > width * height)\n\t\t{\n\t\t\tstd::cout << ii << \" ---> \" << width * height << std::endl;\n\t\t}\n\t}\n\n\n\tcheckCudaErrors(cudaFree(d_depth_buffer_0));\n\tcheckCudaErrors(cudaFree(d_depth_buffer_1));\n\tcheckCudaErrors(cudaFree(d_vertex_buffer_0));\n\tcheckCudaErrors(cudaFree(d_vertex_buffer_1));\n\tcheckCudaErrors(cudaFree(d_normal_buffer));\n\tcheckCudaErrors(cudaFree(d_index_buffer));\n\tcheckCudaErrors(cudaFree(d_distances_buffer));\n}\n\n\nvoid convertKinectFrame2QImage(const KinectFrame& frame, QImage& depthImage)\n{\n\tQVector<QRgb> colorTable;\n\tfor (int i = 0; i < 256; ++i)\n\t\tcolorTable.push_back(qRgb(i, i, i));\n\tdepthImage = QImage(frame.depth_width(), frame.depth_height(), QImage::Format::Format_Indexed8);\n\tdepthImage.setColorTable(colorTable);\n\n\t// set pixels to depth image\n\tfor (int y = 0; y < depthImage.height(); y++)\n\t{\n\t\tfor (int x = 0; x < depthImage.width(); x++)\n\t\t{\n\t\t\tconst unsigned short depth = frame.depth[y * frame.depth_width() + x];\n\t\t\tdepthImage.scanLine(y)[x] = static_cast<uchar>((float)depth / (float)frame.depth_max_distance() * 255.f);;\n\t\t}\n\t}\n}\n\ntemplate<typename Type>\nvoid cpu_test(const KinectFrame frame_0, const KinectFrame& frame_1)//, std::vector<Eigen::Vector3f>& vertices_0, std::vector<Eigen::Vector3f>& vertices_1)\n{\n\tType window_width = 640.0f;\n\tType window_height = 480.0f;\n\tType near_plane = 0.1f;\n\tType far_plane = 10240.0f;\n\tType fovy = 60.0f;\n\tType aspect_ratio = window_width / window_height;\n\n\tEigen::Matrix<Type, 4, 4> proj_inv = perspective_matrix_inverse(fovy, aspect_ratio, near_plane, far_plane);\n\n\tstd::vector<Eigen::Matrix<Type, 3, 1>> vertices_0;\n\tstd::vector<Eigen::Matrix<Type, 3, 1>> vertices_1;\n\tvertices_0.clear();\n\tvertices_1.clear();\n\n\tint d = 0;\n\tfor (int y = 0; y < frame_0.depth_height(); ++y)\n\t{\n\t\tfor (int x = 0; x < frame_0.depth_width(); ++x)\n\t\t{\n\t\t\tEigen::Matrix<Type, 3, 1> v = window_coord_to_3d(Eigen::Matrix<Type, 2, 1>(x, y), (Type)frame_0.depth.at(d), proj_inv, (int)window_width, (int)window_height);\n\t\t\t++d;\n\n\t\t\tvertices_0.push_back(v);\n\t\t}\n\t}\n\n\td = 0;\n\tfor (int y = 0; y < frame_1.depth_height(); ++y)\n\t{\n\t\tfor (int x = 0; x < frame_1.depth_width(); ++x)\n\t\t{\n\t\t\tEigen::Matrix<Type, 3, 1> v = window_coord_to_3d(Eigen::Matrix<Type, 2, 1>(x, y), (Type)frame_1.depth.at(d), proj_inv, (int)window_width, (int)window_height);\n\t\t\t++d;\n\n\t\t\tvertices_1.push_back(v);\n\t\t}\n\t}\n\n\tEigen::Matrix<Type, 3, 3> R = Eigen::Matrix<Type, 3, 3>::Zero();\n\tEigen::Matrix<Type, 3, 1> t = Eigen::Matrix<Type, 3, 1>::Zero();\n\n\tComputeRigidTransform(vertices_0, vertices_1, R, t);\n\n\tstd::cout << std::fixed\n\t\t<< \"ComputeRigidTransform: \" << std::endl\n\t\t<< \"Rotate\" << std::endl << R << std::endl\n\t\t<< \"Translate\" << std::endl << t.transpose() << std::endl\n\t\t<< std::endl;\n}\n\nint main(int argc, char **argv)\n{\n\tsrand(time(NULL));\n\n\tstd::string filename_0 = \"../../data/knt_frames/frame_27.knt\";\n\tstd::string filename_1 = \"../../data/knt_frames/frame_27.knt\";\n\tushort half_window_search_size = 3;\n\tushort max_distance = 10;\n\n\tif (argc < 3)\n\t{\n\t\tstd::cerr << \"Usage: ICP_gpu.exe ../../data/knt_frames/frame_27.knt ../../data/knt_frames/frame_27.knt 3 10\"\n\t\t<< std::endl\n\t\t<< \"The app will continue with default parameters.\"\n\t\t<< std::endl;\n\t}\n\telse\n\t{\n\t\tfilename_0 = argv[1];\n\t\tfilename_1 = argv[2];\n\t}\n\t\n\tif (argc > 3)\n\t\thalf_window_search_size = atoi(argv[3]);\n\n\tif (argc > 4)\n\t\tmax_distance = atoi(argv[4]);\n\n\tTimer timer;\n\n\ttimer.start();\n\tKinectFrame frame_0, frame_1;\n\tQKinectIO::loadFrame(QString::fromStdString(filename_0), frame_0);\n\tQKinectIO::loadFrame(QString::fromStdString(filename_1), frame_1);\n\ttimer.print_interval(\"Importing kinect frames (.knt)            : \");\n\n\t//std::vector<Eigen::Vector3f> verts_0, verts_1;\n\t//cpu_test<float>(frame_0, frame_1);\n\t//return 0;\n\n\n\t\n\tstd::vector<float4> vertices_0, vertices_1, normals;\n\tstd::vector<ushort2> indices;\n\tstd::vector<float> distances;\n\tstd::vector<Eigen::Vector3f> vertices_00, vertices_11;\n\n\ttimer.start();\n\trun_icp_with_normal_estimate(\n\t\tvertices_0, \n\t\tvertices_1, \n\t\tnormals, \n\t\tindices, \n\t\tdistances,\n\t\tframe_0.depth, \n\t\tframe_1.depth,\n\t\tframe_0.depth_width(), \n\t\tframe_0.depth_height(), \n\t\tframe_0.depth_max_distance(), \n\t\thalf_window_search_size);\n\ttimer.print_interval(\"Running normal estimate in GPU            : \");\n\n\n\tvertices_1.clear();\n\tfor (const ushort2 index : indices)\n\t{\n\t\tfloat4 v = vertices_0.at(index.y * frame_0.depth_width() + index.x);\n\t\tvertices_1.push_back(v);\n\t}\n\n\n\t//for (int i = 0; i < vertices_0.size(); ++i)\n\t//{\n\t//\tconst float4& v0 = vertices_0.at(i);\n\t//\tconst float4& v1 = vertices_1.at(i);\n\n\t//\tif (v0.z > 0.1 && v1.z > 0.1)\n\t//\t{\n\t//\t\tvertices_00.push_back(Eigen::Vector3f((Eigen::Vector4f(v0.x, v0.y, v0.z, v0.w) / v0.w).head<3>()));\n\t//\t\tvertices_11.push_back(Eigen::Vector3f((Eigen::Vector4f(v1.x, v1.y, v1.z, v1.w) / v1.w).head<3>()));\n\t//\t}\n\t//}\n\n\n\tfor (int y = 0; y < frame_0.depth_height(); ++y)\n\t{\n\t\tfor (int x = 0; x < frame_0.depth_width(); ++x)\n\t\t{\n\t\t\tint i = y * frame_0.depth_width() + x;\n\n\t\t\tfloat distance = distances[i];\n\n\t\t\tif (distance > max_distance)\n\t\t\t\tcontinue;\n\n\t\t\tushort2 index = indices[i];\n\t\t\tint ii = index.y * frame_0.depth_width() + index.x;\n\n\t\t\tconst float4& v0 = vertices_0.at(ii);\n\t\t\tconst float4& v1 = vertices_1.at(ii);\n\n\t\t\tvertices_00.push_back(Eigen::Vector3f((Eigen::Vector4f(v0.x, v0.y, v0.z, v0.w) / v0.w).head<3>()));\n\t\t\tvertices_11.push_back(Eigen::Vector3f((Eigen::Vector4f(v1.x, v1.y, v1.z, v1.w) / v1.w).head<3>()));\n\n\t\t}\n\n\t}\n\n\n\tstd::cout << \"Vertices size \" << vertices_0.size() << \", \" << vertices_1.size() << std::endl;\n\tstd::cout << \"Vertices size \" << vertices_00.size() << \", \" << vertices_11.size() << std::endl;\n\n\n\tEigen::Matrix<float, 3, 3> R = Eigen::Matrix<float, 3, 3>::Zero();\n\tEigen::Matrix<float, 3, 1> t = Eigen::Matrix<float, 3, 1>::Zero();\n\n\tComputeRigidTransform(vertices_00, vertices_11, R, t);\n\n\tstd::cout << std::fixed\n\t\t<< \"ComputeRigidTransform: \" << std::endl\n\t\t<< \"Rotate\" << std::endl << R << std::endl\n\t\t<< \"Translate\" << std::endl << t.transpose() << std::endl\n\t\t<< std::endl;\n\n\n\treturn 0;\n\n\t//\n\t// Viewer\n\t//\n\tQApplication app(argc, argv);\n\n\tQSurfaceFormat format;\n\tformat.setDepthBufferSize(24);\n\tQSurfaceFormat::setDefaultFormat(format);\n\n\tGLPointCloudViewer glwidget;\n\tglwidget.resize(1024, 848);\n\tglwidget.move(0, 0);\n\tglwidget.setWindowTitle(\"Point Cloud\");\n\tglwidget.show();\n\n\t\n\n\t\n\tstd::shared_ptr<GLPointCloud> cloud_0(new GLPointCloud);\n\tcloud_0->initGL();\n\t//cloud_0->setVertices((float*)&vertices_0.data()[0], (uint)vertices_0.size(), 4);\n\tcloud_0->setVertices((float*)&vertices_00.data()[0], (uint)vertices_00.size(), 4);\n\tcloud_0->setColor(QVector3D(1, 0, 0));\n\t\n\tstd::shared_ptr<GLPointCloud> cloud_1(new GLPointCloud);\n\tcloud_1->initGL();\n\t//cloud_1->setVertices((float*)&vertices_1.data()[0], (uint)vertices_1.size(), 4);\n\tcloud_1->setVertices((float*)&vertices_11.data()[0], (uint)vertices_11.size(), 4);\n\tcloud_1->setColor(QVector3D(0, 0, 1));\n\n\tglwidget.addPointCloud(cloud_0);\n\tglwidget.addPointCloud(cloud_1);\n\n\tglwidget.setWeelSpeed(0.1f);\n\tglwidget.setPosition(0, 0, -0.5f);\n\n\t\n\t\n\n\treturn app.exec();\n}\n", "meta": {"hexsha": "a2934af5692d61e839acc452a6583bff855ecef6", "size": 15129, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/ICP_gpu.cpp", "max_stars_repo_name": "diegomazala/QtKinect", "max_stars_repo_head_hexsha": "c51819980af92b857d87a417d19c5f01d8fada77", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2016-08-04T14:14:11.000Z", "max_stars_repo_stars_event_max_datetime": "2018-05-27T13:46:13.000Z", "max_issues_repo_path": "src/ICP_gpu.cpp", "max_issues_repo_name": "diegomazala/QtKinect", "max_issues_repo_head_hexsha": "c51819980af92b857d87a417d19c5f01d8fada77", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/ICP_gpu.cpp", "max_forks_repo_name": "diegomazala/QtKinect", "max_forks_repo_head_hexsha": "c51819980af92b857d87a417d19c5f01d8fada77", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2015-12-08T06:22:46.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-15T10:29:17.000Z", "avg_line_length": 26.0395869191, "max_line_length": 209, "alphanum_fraction": 0.6880824906, "num_tokens": 4642, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7057850402140659, "lm_q2_score": 0.44939263446475963, "lm_q1q2_score": 0.3171745985876154}}
{"text": "/// \\file\n\n#include <iostream>\n#include <stdio.h>\n#include <fstream>\n#include <Eigen/Dense>\n#include \"Perceptron.hpp\"\n#include <cstdlib>\n#include <tbb/tbb.h>\n#include <tbb/task_scheduler_init.h>\n\n#define BLACK '#'\n#define WHITE '_'\n\n/// \\brief Permet de savoir si dans quelle mode lire les metadonnees d'un fichier IDX (low-endien ou big-endian)\n/// \\param f Pointeur sur la chaine de caractere contenant le nom du fichier IDX\n/// \\return le mode selon lequel lire le fichier IDX (0 ou 1)\n/// \\warning teste uniquement sur des processeurs Intel!!!\nint idxEndianness(char* f)\n{\n  int n = 0;\n  char* r = nullptr;\n  r = (char*)&n;\n  std::ifstream in(f, std::ifstream::in);\n  //On lit les 4 premiers octets\n  in.read(r, 4);\n  if(n != 2049 && n!= 2051)\n  {\n      return 0;\n  }\n  else\n  {\n      return 1;\n  }\n}\n\n/// \\brief Lire les metadonnees d'un fichier IDX (fonction recursive)\n/// \\param in Flux du fichier IDX a lire\n/// \\param mode Mode Mode pour lire le fichier selon l'endianness\n/// \\param n Reference vers la variable dans laquelle mettre la prochaine metadonnee a lire\n/// \\param args References vers les prochaines variable dans laquelle mettre les metadonnees suivantes a lire\n/// \\warning teste uniquement sur des processeurs Intel!!!\ntemplate<typename... Args>\nvoid idxMeta(std::ifstream& in, int mode, std::size_t& n, Args& ...args)\n{\n  char* r = nullptr;\n  r = (char*)&n;\n  //On lit les 4 premiers octets\n  in.read(r, 4);\n  //Sur Intel, on les inverses\n  if(mode==0)\n  {\n    char tmp;\n    tmp = r[0];\n    r[0] = r[3];\n    r[3] = tmp;\n    tmp = r[1];\n    r[1] = r[2];\n    r[2] = tmp;\n  }\n  idxMeta(in, mode, args...);\n}\n\n/// \\brief Dernier appel recursif de idxMeta\n/// \\warning teste uniquement sur des processeurs Intel!!!\ntemplate<>\nvoid idxMeta(std::ifstream& in, int mode, std::size_t& n)\n{\n  char* r = nullptr;\n  r = (char*)&n;\n  //On lit les 4 premiers octets\n  in.read(r, 4);\n  //Sur Intel, on les inverses\n  if(mode == 0)\n  {\n    char tmp;\n    tmp = r[0];\n    r[0] = r[3];\n    r[3] = tmp;\n    tmp = r[1];\n    r[1] = r[2];\n    r[2] = tmp;\n  }\n}\n\n/// \\brief On charge dans une entree-sortie de reseau le prochain element qui se trouve dans un fichier IDX\n/// \\param fin Flux du fichier IDX a lire\n/// \\param vout Reference vers l'entree-sortie de reseau dans laquelle on charge le prochain element du fichier\n/// \\param size Taille du prochain element a lire\n/// \\return Rien\n/// \\tparam t Type de l'entree-sortie de reseau dans laquelle on charge le prochain element du fichier IDX\n/// \\tparam SIZE Taille de l'entree-sortie de reseau dans laquelle on charge le prochain element du fichier IDX\n/// \\warning teste uniquement sur des processeurs Intel!!!\ntemplate<typename t, int SIZE>\nvoid nextIdx(std::ifstream& fin, neuralnetwork::InOut<t, SIZE>& vout, std::size_t size)\n{\n  for (int i = 0; i < size; ++i)\n  {\n    unsigned char r;\n    fin.read((char*)&r, 1);\n    vout(i) = r;   \n  }\n}\n\n/// \\brief Conversion d'un label entier en label vecteur pour la classification de caractere numerique\n/// \\param in Label entier\n/// \\param out Label vecteur en sortie\n/// \\return Rien\n/// \\tparam t Type d'entree du reseau (a priori un double)\n/// \\tparam INPUT_SIZE Taille d'entree du reseau\ntemplate<typename t, int INPUT_SIZE>\nvoid labelToVector(int in, neuralnetwork::InOut<t, INPUT_SIZE>& out)\n{\n    out << 0, 0, 0, 0, 0, 0, 0, 0, 0, 0;\n    out(in) = 1;\n}\n\n/// \\brief Affiche une entree-sortie de reseau contenant une images de MNIST (principalement utile au debugage)\n/// \\param rows Nombre de lignes de l'image (a priori 28)\n/// \\param cols Nombre de colonnes de l'image (a priori 28)\n/// \\param v Entree-sortie de reseau a afficher\n/// \\return Rien\n/// \\tparam t Type de l'entree-sortie de reseau a afficher\n/// \\tparam SIZE Taille de l'entree-sortie a afficher\ntemplate<typename t, int SIZE>\nvoid printInOut(std::size_t rows, std::size_t cols, neuralnetwork::InOut<t, SIZE> v)\n{\n  for(int i = 0; i < rows; ++i)\n  {\n    for(int j = 0; j < cols; ++j)\n    {\n      if (v(i*rows + j) != 0)\n      {\n        std::cout << BLACK;\n      }\n      else\n      {\n        std::cout << WHITE;\n      }\n    }\n    std::cout << std::endl;\n  }\n}\n\n/// \\brief Entrainement du reseau pour la classification de caracteres\n/// \\param pathImages Pointeur vers la chaine de caractere contenant le nom de fichier des images d'entrainement\n/// \\param pathLabels Pointeur vers la chaine de caractere contenant le nom de fichier des labels d'entrainement\n/// \\param net Reseau a entrainer\n/// \\param step Pas d'apprentissage\n/// \\param nbIter Nombre d'iterations a effectuer sur l'ensemble des images d'entrainement\n/// \\param nbImages Nombre d'images a charger en memoire simultanement\n/// \\return -1 en cas de probleme d'allocation memoires (trop d'images a charger simultanement)\n/// \\tparam DEPTH Profondeur du reseau de neurones\ntemplate<std::size_t DEPTH>\nint train(char* pathImages, char* pathLabels, neuralnetwork::Perceptron<DEPTH>& net, double step, std::size_t nbIter, std::size_t nbImages)\n{\n\n  std::size_t magicImTrain = 0, magicLabTrain = 0;\n  std::size_t nbImagesTrain = 0;\n  std::size_t rows = 0;\n  std::size_t cols = 0;\n  neuralnetwork::InOut<double, 784>* inIm = NULL;\n  neuralnetwork::InOut<double, 1>* inLab = NULL; \n  neuralnetwork::InOut<double, 10>* inLabVect = NULL;\n  int mode = idxEndianness(pathLabels);\n  //Si on a 0 en nombre d'exemples a charger en memoire on chargera tous les exemples de la base de donnees\n  if(nbImages == 0)\n  {\n    std::ifstream flabels(pathLabels, std::ifstream::in);\n    idxMeta(flabels, mode, magicLabTrain, nbImagesTrain);\n    nbImages = nbImagesTrain;\n    flabels.close();\n  }\n  \n  inIm = new neuralnetwork::InOut<double, 784> [nbImages];\n  inLab = new neuralnetwork::InOut<double, 1> [nbImages];\n  inLabVect = new neuralnetwork::InOut<double, 10> [nbImages];\n  if(inIm == NULL || inLab == NULL || inLabVect == NULL)\n  {\n    return -1;\n  }\n\n  //On entraine autant de fois que voulu\n  for(int iter = 0; iter < nbIter; ++iter)\n  {\n    std::cout << \"Iteration [\" << iter << \"/\" << nbIter << \"]\" << std::endl;\n    std::ifstream fimages(pathImages, std::ifstream::in);\n    std::ifstream flabels(pathLabels, std::ifstream::in);\n    idxMeta(flabels, mode, magicLabTrain, nbImagesTrain);\n    idxMeta(fimages, mode, magicImTrain, nbImagesTrain, rows, cols);\n    //Tant que l'on a pas fait tous les exemples\n    for(int n = 0; n < nbImagesTrain; n+=nbImages)\n    { \n      std::cout << \"Iteration [\" << n << \"/\" << nbImagesTrain << \"]\" << std::endl;\n      //On charge les exemples et les labels\n      for(int i = 0; i < nbImages; ++i)\n      {\n        //On charge l'exemple et le label\n        nextIdx(fimages, inIm[i], 784);\n        nextIdx(flabels, inLab[i], 1);\n        int valLab = inLab[i](0);\n        //Conversion du label en vecteur\n        labelToVector(valLab, inLabVect[i]);\n      }\n    //std::cout << \"Iteration \" << iter + 1 << \", entrainement avec les image de \" << n << \" a \" << n+nbImages << \"...\" << std::endl;\n    //On entraine sur le lot charge\n    net.parallel_backpropagation(inIm, inLabVect, nbImages, step);\n    //net.backpropagation(inIm, inLabVect, nbImages, step);\n    }\n    \n    fimages.close();\n    flabels.close();\n  }\n\n  delete [] inIm;\n  delete [] inLab;\n  delete [] inLabVect;\n  \n}\n  \n/// \\brief Test du reseau pour la classification de caracteres\n/// \\param pathImages Pointeur vers la chaine de caractere contenant le nom de fichier des images de test\n/// \\param pathLabels Pointeur vers la chaine de caractere contenant le nom de fichier des labels de test\n/// \\param net Reseau a tester \n/// \\return Pourcentage de reussite\n/// \\tparam DEPTH Profondeur du reseau de neurones\ntemplate<std::size_t DEPTH>\ndouble test(char* pathImages, char* pathLabels, neuralnetwork::Perceptron<DEPTH>& net)\n{\n  std::size_t magicImTrain = 0, magicLabTrain = 0, magicImTest = 0, magicLabTest = 0;\n  std::size_t nbImagesTrain = 0, nbImagesTest = 0;\n  std::size_t rows = 0;\n  std::size_t cols = 0;\n  neuralnetwork::InOut<double, 784> inImTest;\n  neuralnetwork::InOut<double, 1> inLabTest;\n  int mode = idxEndianness(pathLabels);  \n  std::ifstream fimagesTest(pathImages, std::ifstream::in);\n  std::ifstream flabelsTest(pathLabels, std::ifstream::in);\n  \n  idxMeta(flabelsTest, mode, magicLabTest, nbImagesTest);\n  idxMeta(fimagesTest, mode, magicImTest, nbImagesTest, rows, cols);\n  \n  int count = 0;\n  //Pour tous les exemples de tests\n  for(int i = 0; i < 10000; ++i)\n  {\n    neuralnetwork::InOut<double, 10> out;\n    neuralnetwork::InOut<double, 10> realOut;\n\n    //On charge les exemples avec leurs labels\n    nextIdx(fimagesTest, inImTest, 784);\n    nextIdx(flabelsTest, inLabTest, 1);\n    \n    //On convertit le label en vecteur\n    labelToVector(inLabTest(0), realOut);\n\n    //On fait evaluer l'exemple par le reseau de neurones\n    //net.feedForward(inImTest, out, false, false);\n    net.parallel_feedForward(inImTest, out);\n    \n    //Pour chaque element i du vecteur de sortie, s'il est superieur a 0.5, on estime que le reseau a trouve que l'exemple est i - 1\n    //Par exemple si le reseau renvoi [0.12, 0.23, 0.87, 0.34, 0.45, 0.47, 0.37, 0.28, 0.19 , 0.09] alors on interprete que le solution trouvee est [0, 0, 1, 0, 0, 0, 0, 0, 0, 0] et donc que le nombre trouve est 2\n    for(int j = 0; j < 10; ++j)\n    {\n      if(out(j) > 0.5)\n      {\n        out(j) = 1.0;\n      }\n      else\n      {\n        out(j) = 0.0;\n      }\n    }\n    //Si la bonne solution est trouvee, alors on incremente le coompteur\n    if(out == realOut)\n    {\n      ++count;\n    }\n  }\n  \n  //On retourne le pourcentage de reussite\n  return count*100.0/10000.0;\n\n}\n\n/// \\brief Itere un certain nombre de fois sur la base d'entrainement et apres chaque iteration test le reseau sur la base de test, le taux de reussite de chaque test est stocke dans un fichier\n/// \\param pathImTrain Pointeur vers la chaine de caractere contenant le nom de fichier des images d'entrainement\n/// \\param pathLabTrain Pointeur vers la chaine de caractere contenant le nom de fichier des labels d'entrainement\n/// \\param pathImTest Pointeur vers la chaine de caractere contenant le nom de fichier des images de test\n/// \\param pathLabTest Pointeur vers la chaine de caractere contenant le nom de fichier des labels de test\n/// \\param plot Pointeur vers la chaine de caractere contenant le nom de fichier dans lequel stocker les resultats\n/// \\param net Reseau a entrainer\n/// \\param step Pas d'apprentissage\n/// \\param nbIter Nombre d'iterations a effectuer sur l'ensemble des images d'entrainement\n/// \\param nbImages Nombre d'images a charger en memoire simultanement\n/// \\return Rien\n/// \\tparam DEPTH Profondeur du reseau de neurones\ntemplate<std::size_t DEPTH>\nvoid bench(char* pathImTrain, char* pathLabTrain, char* pathImTest, char* pathLabTest, char* plot, neuralnetwork::Perceptron<DEPTH>& net, double step, std::size_t nbIter, std::size_t nbImages)\n{\n  std::ofstream fplot(plot, std::ofstream::out);\n  for(int i = 0; i < nbIter; ++i)\n  {\n    train(pathImTrain, pathLabTrain, net, step, 1, nbImages);\n    double resTest = test(pathImTest, pathLabTest, net);\n    fplot << resTest << std::endl;\n  }\n}\n\n\nint main()\n{\n  char pathImTrain [] = \"../datas/imTrain\";\n  char pathLabTrain [] = \"../datas/labTrain\";\n  char pathImTest [] = \"../datas/imTest\";\n  char pathLabTest [] = \"../datas/labTest\";\n  char pathPlot [] = \"../benchmarks/plot.txt\";\n  \n  //tbb::task_scheduler_init init(4);\n \n  neuralnetwork::Perceptron<4>  net(\n    -0.0001,\n    0.0001,\n    784, \n    200, neuralnetwork::activation::SIGMOID, neuralnetwork::activation::D_SIGMOID,\n    200, neuralnetwork::activation::SIGMOID, neuralnetwork::activation::D_SIGMOID, \n    200, neuralnetwork::activation::SIGMOID, neuralnetwork::activation::D_SIGMOID, \n    10, neuralnetwork::activation::SIGMOID, neuralnetwork::activation::D_SIGMOID    \n  );\n    net.initGraph(0.1);\n    train(pathImTrain, pathLabTrain,  net, 0.1, 50, 1000);\n    double res = test(pathImTest, pathLabTest, net);\n    std::cout << \"reussite de \" << res << \" pourcents apres entrainement\" << std::endl;\n    \n\n  return 0;\n}\n", "meta": {"hexsha": "1b2e9fb135b63d354a84480c54fc808557c10bbb", "size": 12047, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/main.cpp", "max_stars_repo_name": "Deirdan/MNISTNN2", "max_stars_repo_head_hexsha": "9639bddeade5acbf81d5e9a5efeebab03a0eb5b1", "max_stars_repo_licenses": ["MIT"], "max_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": "Deirdan/MNISTNN2", "max_issues_repo_head_hexsha": "9639bddeade5acbf81d5e9a5efeebab03a0eb5b1", "max_issues_repo_licenses": ["MIT"], "max_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": "Deirdan/MNISTNN2", "max_forks_repo_head_hexsha": "9639bddeade5acbf81d5e9a5efeebab03a0eb5b1", "max_forks_repo_licenses": ["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.6420118343, "max_line_length": 213, "alphanum_fraction": 0.6717855068, "num_tokens": 3676, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6150878696277512, "lm_q2_score": 0.5156199157230156, "lm_q1q2_score": 0.31715155549971025}}
{"text": "#include \"ter.h\"\n\n#include <cstdio>\n#include <cassert>\n#include <iostream>\n#include <limits>\n#include <sstream>\n#include <tr1/unordered_map>\n#include <set>\n#include <valarray>\n#include <boost/functional/hash.hpp>\n#include <stdexcept>\n#include \"tdict.h\"\n\nconst bool ter_use_average_ref_len = true;\nconst int ter_short_circuit_long_sentences = -1;\n\nusing namespace std;\nusing namespace std::tr1;\n\nstruct COSTS {\n  static const float substitution;\n  static const float deletion;\n  static const float insertion;\n  static const float shift;\n};\nconst float COSTS::substitution = 1.0f;\nconst float COSTS::deletion = 1.0f;\nconst float COSTS::insertion = 1.0f;\nconst float COSTS::shift = 1.0f;\n\nstatic const int MAX_SHIFT_SIZE = 10;\nstatic const int MAX_SHIFT_DIST = 50;\n\nstruct Shift {\n  unsigned int d_;\n  Shift() : d_() {}\n  Shift(int b, int e, int m) : d_() {\n    begin(b);\n    end(e);\n    moveto(m);\n  }\n  inline int begin() const {\n    return d_ & 0x3ff;\n  }\n  inline int end() const {\n    return (d_ >> 10) & 0x3ff;\n  }\n  inline int moveto() const {\n    int m = (d_ >> 20) & 0x7ff;\n    if (m > 1024) { m -= 1024; m *= -1; }\n    return m;\n  }\n  inline void begin(int b) {\n    d_ &= 0xfffffc00u;\n    d_ |= (b & 0x3ff);\n  }\n  inline void end(int e) {\n    d_ &= 0xfff003ffu;\n    d_ |= (e & 0x3ff) << 10;\n  }\n  inline void moveto(int m) {\n    bool neg = (m < 0);\n    if (neg) { m *= -1; m += 1024; }\n    d_ &= 0xfffff;\n    d_ |= (m & 0x7ff) << 20;\n  }\n};\n\nclass TERScorerImpl {\n\n public:\n  enum TransType { MATCH, SUBSTITUTION, INSERTION, DELETION };\n\n  explicit TERScorerImpl(const vector<WordID>& ref) : ref_(ref) {\n    for (int i = 0; i < ref.size(); ++i)\n      rwexists_.insert(ref[i]);\n  }\n\n  float Calculate(const vector<WordID>& hyp, int* subs, int* ins, int* dels, int* shifts) const {\n    return CalculateAllShifts(hyp, subs, ins, dels, shifts);\n  }\n\n  inline int GetRefLength() const {\n    return ref_.size();\n  }\n\n private:\n  vector<WordID> ref_;\n  set<WordID> rwexists_;\n\n  typedef unordered_map<vector<WordID>, set<int>, boost::hash<vector<WordID> > > NgramToIntsMap;\n  mutable NgramToIntsMap nmap_;\n\n  static float MinimumEditDistance(\n      const vector<WordID>& hyp,\n      const vector<WordID>& ref,\n      vector<TransType>* path) {\n    vector<vector<TransType> > bmat(hyp.size() + 1, vector<TransType>(ref.size() + 1, MATCH));\n    vector<vector<float> > cmat(hyp.size() + 1, vector<float>(ref.size() + 1, 0));\n    for (int i = 0; i <= hyp.size(); ++i)\n      cmat[i][0] = i;\n    for (int j = 0; j <= ref.size(); ++j)\n      cmat[0][j] = j;\n    for (int i = 1; i <= hyp.size(); ++i) {\n      const WordID& hw = hyp[i-1];\n      for (int j = 1; j <= ref.size(); ++j) {\n        const WordID& rw = ref[j-1];\n\tfloat& cur_c = cmat[i][j];\n\tTransType& cur_b = bmat[i][j];\n\n        if (rw == hw) {\n          cur_c = cmat[i-1][j-1];\n          cur_b = MATCH;\n        } else {\n          cur_c = cmat[i-1][j-1] + COSTS::substitution;\n          cur_b = SUBSTITUTION;\n        }\n\tfloat cwoi = cmat[i-1][j];\n        if (cur_c > cwoi + COSTS::insertion) {\n          cur_c = cwoi + COSTS::insertion;\n          cur_b = INSERTION;\n        }\n        float cwod = cmat[i][j-1];\n        if (cur_c > cwod + COSTS::deletion) {\n          cur_c = cwod + COSTS::deletion;\n          cur_b = DELETION;\n        }\n      }\n    }\n\n    // trace back along the best path and record the transition types\n    path->clear();\n    int i = hyp.size();\n    int j = ref.size();\n    while (i > 0 || j > 0) {\n      if (j == 0) {\n        --i;\n        path->push_back(INSERTION);\n      } else if (i == 0) {\n        --j;\n        path->push_back(DELETION);\n      } else {\n        TransType t = bmat[i][j];\n        path->push_back(t);\n        switch (t) {\n          case SUBSTITUTION:\n          case MATCH:\n            --i; --j; break;\n          case INSERTION:\n            --i; break;\n          case DELETION:\n            --j; break;\n        }\n      }\n    }\n    reverse(path->begin(), path->end());\n    return cmat[hyp.size()][ref.size()];\n  }\n\n  void BuildWordMatches(const vector<WordID>& hyp, NgramToIntsMap* nmap) const {\n    nmap->clear();\n    set<WordID> exists_both;\n    for (int i = 0; i < hyp.size(); ++i)\n      if (rwexists_.find(hyp[i]) != rwexists_.end())\n        exists_both.insert(hyp[i]);\n    for (int start=0; start<ref_.size(); ++start) {\n      if (exists_both.find(ref_[start]) == exists_both.end()) continue;\n      vector<WordID> cp;\n      int mlen = min(MAX_SHIFT_SIZE, static_cast<int>(ref_.size() - start));\n      for (int len=0; len<mlen; ++len) {\n        if (len && exists_both.find(ref_[start + len]) == exists_both.end()) break;\n        cp.push_back(ref_[start + len]);\n\t(*nmap)[cp].insert(start);\n      }\n    }\n  }\n\n  static void PerformShift(const vector<WordID>& in,\n    int start, int end, int moveto, vector<WordID>* out) {\n    // cerr << \"ps: \" << start << \" \" << end << \" \" << moveto << endl;\n    out->clear();\n    if (moveto == -1) {\n      for (int i = start; i <= end; ++i)\n       out->push_back(in[i]);\n      for (int i = 0; i < start; ++i)\n       out->push_back(in[i]);\n      for (int i = end+1; i < in.size(); ++i)\n       out->push_back(in[i]);\n    } else if (moveto < start) {\n      for (int i = 0; i <= moveto; ++i)\n       out->push_back(in[i]);\n      for (int i = start; i <= end; ++i)\n       out->push_back(in[i]);\n      for (int i = moveto+1; i < start; ++i)\n       out->push_back(in[i]);\n      for (int i = end+1; i < in.size(); ++i)\n       out->push_back(in[i]);\n    } else if (moveto > end) {\n      for (int i = 0; i < start; ++i)\n       out->push_back(in[i]);\n      for (int i = end+1; i <= moveto; ++i)\n       out->push_back(in[i]);\n      for (int i = start; i <= end; ++i)\n       out->push_back(in[i]);\n      for (int i = moveto+1; i < in.size(); ++i)\n       out->push_back(in[i]);\n    } else {\n      for (int i = 0; i < start; ++i)\n       out->push_back(in[i]);\n      for (int i = end+1; (i < in.size()) && (i <= end + (moveto - start)); ++i)\n       out->push_back(in[i]);\n      for (int i = start; i <= end; ++i)\n       out->push_back(in[i]);\n      for (int i = (end + (moveto - start))+1; i < in.size(); ++i)\n       out->push_back(in[i]);\n    }\n    if (out->size() != in.size()) {\n      cerr << \"ps: \" << start << \" \" << end << \" \" << moveto << endl;\n      cerr << \"in=\" << TD::GetString(in) << endl;\n      cerr << \"out=\" << TD::GetString(*out) << endl;\n    }\n    assert(out->size() == in.size());\n    // cerr << \"ps: \" << TD::GetString(*out) << endl;\n  }\n\n  void GetAllPossibleShifts(const vector<WordID>& hyp,\n      const vector<int>& ralign,\n      const vector<bool>& herr,\n      const vector<bool>& rerr,\n      const int min_size,\n      vector<vector<Shift> >* shifts) const {\n    for (int start = 0; start < hyp.size(); ++start) {\n      vector<WordID> cp(1, hyp[start]);\n      NgramToIntsMap::iterator niter = nmap_.find(cp);\n      if (niter == nmap_.end()) continue;\n      bool ok = false;\n      int moveto;\n      for (set<int>::iterator i = niter->second.begin(); i != niter->second.end(); ++i) {\n        moveto = *i;\n        int rm = ralign[moveto];\n        ok = (start != rm &&\n              (rm - start) < MAX_SHIFT_DIST &&\n              (start - rm - 1) < MAX_SHIFT_DIST);\n        if (ok) break;\n      }\n      if (!ok) continue;\n      cp.clear();\n      for (int end = start + min_size - 1;\n           ok && end < hyp.size() && end < (start + MAX_SHIFT_SIZE); ++end) {\n        cp.push_back(hyp[end]);\n\tvector<Shift>& sshifts = (*shifts)[end - start];\n        ok = false;\n        NgramToIntsMap::iterator niter = nmap_.find(cp);\n        if (niter == nmap_.end()) break;\n        bool any_herr = false;\n        for (int i = start; i <= end && !any_herr; ++i)\n          any_herr = herr[i];\n        if (!any_herr) {\n          ok = true;\n          continue;\n        }\n        for (set<int>::iterator mi = niter->second.begin();\n             mi != niter->second.end(); ++mi) {\n          int moveto = *mi;\n\t  int rm = ralign[moveto];\n\t  if (! ((rm != start) &&\n\t        ((rm < start) || (rm > end)) &&\n\t\t(rm - start <= MAX_SHIFT_DIST) &&\n\t\t((start - rm - 1) <= MAX_SHIFT_DIST))) continue;\n          ok = true;\n\t  bool any_rerr = false;\n\t  for (int i = 0; (i <= end - start) && (!any_rerr); ++i)\n            any_rerr = rerr[moveto+i];\n\t  if (!any_rerr) continue;\n\t  for (int roff = 0; roff <= (end - start); ++roff) {\n\t    int rmr = ralign[moveto+roff];\n\t    if ((start != rmr) && ((roff == 0) || (rmr != ralign[moveto])))\n\t      sshifts.push_back(Shift(start, end, moveto + roff));\n\t  }\n        }\n      }\n    }\n  }\n\n  bool CalculateBestShift(const vector<WordID>& cur,\n                          const vector<WordID>& hyp,\n                          float curerr,\n                          const vector<TransType>& path,\n                          vector<WordID>* new_hyp,\n                          float* newerr,\n                          vector<TransType>* new_path) const {\n    vector<bool> herr, rerr;\n    vector<int> ralign;\n    int hpos = -1;\n    for (int i = 0; i < path.size(); ++i) {\n      switch (path[i]) {\n        case MATCH:\n\t  ++hpos;\n\t  herr.push_back(false);\n\t  rerr.push_back(false);\n\t  ralign.push_back(hpos);\n          break;\n        case SUBSTITUTION:\n\t  ++hpos;\n\t  herr.push_back(true);\n\t  rerr.push_back(true);\n\t  ralign.push_back(hpos);\n          break;\n        case INSERTION:\n\t  ++hpos;\n\t  herr.push_back(true);\n          break;\n\tcase DELETION:\n\t  rerr.push_back(true);\n\t  ralign.push_back(hpos);\n          break;\n      }\n    }\n#if 0\n    cerr << \"RALIGN: \";\n    for (int i = 0; i < rerr.size(); ++i)\n      cerr << ralign[i] << \" \";\n    cerr << endl;\n    cerr << \"RERR: \";\n    for (int i = 0; i < rerr.size(); ++i)\n      cerr << (bool)rerr[i] << \" \";\n    cerr << endl;\n    cerr << \"HERR: \";\n    for (int i = 0; i < herr.size(); ++i)\n      cerr << (bool)herr[i] << \" \";\n    cerr << endl;\n#endif\n\n    vector<vector<Shift> > shifts(MAX_SHIFT_SIZE + 1);\n    GetAllPossibleShifts(cur, ralign, herr, rerr, 1, &shifts);\n    float cur_best_shift_cost = 0;\n    *newerr = curerr;\n    vector<TransType> cur_best_path;\n    vector<WordID> cur_best_hyp;\n\n    bool res = false;\n    for (int i = shifts.size() - 1; i >=0; --i) {\n      float curfix = curerr - (cur_best_shift_cost + *newerr);\n      float maxfix = 2.0f * (1 + i) - COSTS::shift;\n      if ((curfix > maxfix) || ((cur_best_shift_cost == 0) && (curfix == maxfix))) break;\n      for (int j = 0; j < shifts[i].size(); ++j) {\n        const Shift& s = shifts[i][j];\n\tcurfix = curerr - (cur_best_shift_cost + *newerr);\n\tmaxfix = 2.0f * (1 + i) - COSTS::shift;  // TODO remove?\n        if ((curfix > maxfix) || ((cur_best_shift_cost == 0) && (curfix == maxfix))) continue;\n\tvector<WordID> shifted(cur.size());\n\tPerformShift(cur, s.begin(), s.end(), ralign[s.moveto()], &shifted);\n\tvector<TransType> try_path;\n\tfloat try_cost = MinimumEditDistance(shifted, ref_, &try_path);\n\tfloat gain = (*newerr + cur_best_shift_cost) - (try_cost + COSTS::shift);\n\tif (gain > 0.0f || ((cur_best_shift_cost == 0.0f) && (gain == 0.0f))) {\n\t  *newerr = try_cost;\n\t  cur_best_shift_cost = COSTS::shift;\n\t  new_path->swap(try_path);\n\t  new_hyp->swap(shifted);\n\t  res = true;\n\t  // cerr << \"Found better shift \" << s.begin() << \"...\" << s.end() << \" moveto \" << s.moveto() << endl;\n\t}\n      }\n    }\n\n    return res;\n  }\n\n  static void GetPathStats(const vector<TransType>& path, int* subs, int* ins, int* dels) {\n    *subs = *ins = *dels = 0;\n    for (int i = 0; i < path.size(); ++i) {\n      switch (path[i]) {\n        case SUBSTITUTION:\n\t  ++(*subs);\n        case MATCH:\n          break;\n        case INSERTION:\n          ++(*ins); break;\n\tcase DELETION:\n          ++(*dels); break;\n      }\n    }\n  }\n\n  float CalculateAllShifts(const vector<WordID>& hyp,\n      int* subs, int* ins, int* dels, int* shifts) const {\n    BuildWordMatches(hyp, &nmap_);\n    vector<TransType> path;\n    float med_cost = MinimumEditDistance(hyp, ref_, &path);\n    float edits = 0;\n    vector<WordID> cur = hyp;\n    *shifts = 0;\n    if (ter_short_circuit_long_sentences < 0 ||\n        ref_.size() < ter_short_circuit_long_sentences) {\n      while (true) {\n        vector<WordID> new_hyp;\n        vector<TransType> new_path;\n        float new_med_cost;\n        if (!CalculateBestShift(cur, hyp, med_cost, path, &new_hyp, &new_med_cost, &new_path))\n          break;\n        edits += COSTS::shift;\n        ++(*shifts);\n        med_cost = new_med_cost;\n        path.swap(new_path);\n        cur.swap(new_hyp);\n      }\n    }\n    GetPathStats(path, subs, ins, dels);\n    return med_cost + edits;\n  }\n};\n\nclass TERScore : public ScoreBase<TERScore> {\n  friend class TERScorer;\n\n public:\n  static const unsigned kINSERTIONS = 0;\n  static const unsigned kDELETIONS = 1;\n  static const unsigned kSUBSTITUTIONS = 2;\n  static const unsigned kSHIFTS = 3;\n  static const unsigned kREF_WORDCOUNT = 4;\n  static const unsigned kDUMMY_LAST_ENTRY = 5;\n\n TERScore() : stats(0,kDUMMY_LAST_ENTRY) {}\n  float ComputePartialScore() const { return 0.0;}\n  float ComputeScore() const {\n    float edits = static_cast<float>(stats[kINSERTIONS] + stats[kDELETIONS] + stats[kSUBSTITUTIONS] + stats[kSHIFTS]);\n    return edits / static_cast<float>(stats[kREF_WORDCOUNT]);\n  }\n  void ScoreDetails(string* details) const;\n  void PlusPartialEquals(const Score& rhs, int oracle_e_cover, int oracle_f_cover, int src_len){}\n  void PlusEquals(const Score& delta, const float scale) {\n    if (scale==1)\n      stats += static_cast<const TERScore&>(delta).stats;\n    if (scale==-1)\n      stats -= static_cast<const TERScore&>(delta).stats;\n    throw std::runtime_error(\"TERScore::PlusEquals with scale != +-1\");\n }\n  void PlusEquals(const Score& delta) {\n    stats += static_cast<const TERScore&>(delta).stats;\n  }\n\n  ScoreP GetZero() const {\n    return ScoreP(new TERScore);\n  }\n  ScoreP GetOne() const {\n    return ScoreP(new TERScore);\n  }\n  void Subtract(const Score& rhs, Score* res) const {\n    static_cast<TERScore*>(res)->stats = stats - static_cast<const TERScore&>(rhs).stats;\n  }\n  void Encode(std::string* out) const {\n    ostringstream os;\n    os << stats[kINSERTIONS] << ' '\n       << stats[kDELETIONS] << ' '\n       << stats[kSUBSTITUTIONS] << ' '\n       << stats[kSHIFTS] << ' '\n       << stats[kREF_WORDCOUNT];\n    *out = os.str();\n  }\n  bool IsAdditiveIdentity() const {\n    for (int i = 0; i < kDUMMY_LAST_ENTRY; ++i)\n      if (stats[i] != 0) return false;\n    return true;\n  }\n private:\n  valarray<int> stats;\n};\n\nScoreP TERScorer::ScoreFromString(const std::string& data) {\n  istringstream is(data);\n  TERScore* r = new TERScore;\n  is >> r->stats[TERScore::kINSERTIONS]\n     >> r->stats[TERScore::kDELETIONS]\n     >> r->stats[TERScore::kSUBSTITUTIONS]\n     >> r->stats[TERScore::kSHIFTS]\n     >> r->stats[TERScore::kREF_WORDCOUNT];\n  return ScoreP(r);\n}\n\nvoid TERScore::ScoreDetails(std::string* details) const {\n  char buf[200];\n  sprintf(buf, \"TER = %.2f, %3d|%3d|%3d|%3d (len=%d)\",\n     ComputeScore() * 100.0f,\n     stats[kINSERTIONS],\n     stats[kDELETIONS],\n     stats[kSUBSTITUTIONS],\n     stats[kSHIFTS],\n     stats[kREF_WORDCOUNT]);\n  *details = buf;\n}\n\nTERScorer::~TERScorer() {\n  for (vector<TERScorerImpl*>::iterator i = impl_.begin(); i != impl_.end(); ++i)\n    delete *i;\n}\n\nTERScorer::TERScorer(const vector<vector<WordID> >& refs) : impl_(refs.size()) {\n  for (int i = 0; i < refs.size(); ++i)\n    impl_[i] = new TERScorerImpl(refs[i]);\n}\n\nScoreP TERScorer::ScoreCCandidate(const vector<WordID>& hyp) const {\n  return ScoreP();\n}\n\nScoreP TERScorer::ScoreCandidate(const std::vector<WordID>& hyp) const {\n  float best_score = numeric_limits<float>::max();\n  TERScore* res = new TERScore;\n  int avg_len = 0;\n  for (int i = 0; i < impl_.size(); ++i)\n    avg_len += impl_[i]->GetRefLength();\n  avg_len /= impl_.size();\n  for (int i = 0; i < impl_.size(); ++i) {\n    int subs, ins, dels, shifts;\n    float score = impl_[i]->Calculate(hyp, &subs, &ins, &dels, &shifts);\n    // cerr << \"Component TER cost: \" << score << endl;\n    if (score < best_score) {\n      res->stats[TERScore::kINSERTIONS] = ins;\n      res->stats[TERScore::kDELETIONS] = dels;\n      res->stats[TERScore::kSUBSTITUTIONS] = subs;\n      res->stats[TERScore::kSHIFTS] = shifts;\n      if (ter_use_average_ref_len) {\n        res->stats[TERScore::kREF_WORDCOUNT] = avg_len;\n      } else {\n        res->stats[TERScore::kREF_WORDCOUNT] = impl_[i]->GetRefLength();\n      }\n\n      best_score = score;\n    }\n  }\n  return ScoreP(res);\n}\n", "meta": {"hexsha": "cacc5b0057f5a4badb292a802930568c69d01ee9", "size": 16414, "ext": "cc", "lang": "C++", "max_stars_repo_path": "mteval/ter.cc", "max_stars_repo_name": "agesmundo/FasterCubePruning", "max_stars_repo_head_hexsha": "f80150140b5273fd1eb0dfb34bdd789c4cbd35e6", "max_stars_repo_licenses": ["BSD-3-Clause-LBNL", "Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-06-03T00:44:01.000Z", "max_stars_repo_stars_event_max_datetime": "2019-06-03T00:44:01.000Z", "max_issues_repo_path": "mteval/ter.cc", "max_issues_repo_name": "jhclark/cdec", "max_issues_repo_head_hexsha": "237ddc67ffa61da310e19710f902d4771dc323c2", "max_issues_repo_licenses": ["BSD-3-Clause-LBNL", "Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "mteval/ter.cc", "max_forks_repo_name": "jhclark/cdec", "max_forks_repo_head_hexsha": "237ddc67ffa61da310e19710f902d4771dc323c2", "max_forks_repo_licenses": ["BSD-3-Clause-LBNL", "Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-02-19T12:44:54.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-19T12:44:54.000Z", "avg_line_length": 30.6231343284, "max_line_length": 118, "alphanum_fraction": 0.5611672962, "num_tokens": 5063, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6150878555160665, "lm_q2_score": 0.5156199157230157, "lm_q1q2_score": 0.31715154822344466}}
{"text": "#include \"CoordinateMatrixAnalysis.h\"\n\n#include \"CoordinateMatrix.h\"\n#include <macgyver/Exception.h>\n\n#include <boost/optional.hpp>\n\n#include <cmath>\n#include <iomanip>\n#include <iostream>\n\nnamespace Fmi\n{\nnamespace\n{\n// We discard any grid cell whose bbox exceeds 1000 kilometers in size\n\nconst double cell_size_limit = 1000 * 1000;\n\nenum class Handedness\n{\n  ClockwiseConvex,\n  CounterClockwiseConvex,\n  Invalid,\n  NotConvex,\n  Huge,\n  Oblong\n};\n\n// ----------------------------------------------------------------------\n/*!\n * A polygon is convex if all cross products of adjacent edges are of the same sign,\n * and the sign itself says whether the polygon is clockwise or not.\n * Ref: http://www.easywms.com/node/3602\n * We must disallow non-convex cells such as V-shaped ones, since the intersections\n * formulas may then produce values outside the cell.\n *\n * Note that we permit colinear adjacent edges, since for example in latlon grids\n * the poles are represented by multiple grid points. This test thus passes the\n * redundant case of a rectangle with no area, but the rest of the code can handle it.\n * empty boolean for such grid cells.\n */\n// ----------------------------------------------------------------------\n\nHandedness analyze_cell(\n    double x1, double y1, double x2, double y2, double x3, double y3, double x4, double y4)\n{\n  try\n  {\n    // Disallow cells with any invalid coordinates\n    if (std::isnan(x1) || std::isnan(y1) || std::isnan(x2) || std::isnan(y2) || std::isnan(x3) ||\n        std::isnan(y3) || std::isnan(x4) || std::isnan(y4))\n      return Handedness::Invalid;\n\n    // Check for oblong cells which typically occur at projection discontinuities. One could\n    // use the Polsby-Popper test here, but calculating the edge lengths in addition to the\n    // areas below would be slower tahn simply testing the cell bbox\n\n    const auto xmin = std::min(std::min(x1, x2), std::min(x3, x4));\n    const auto xmax = std::max(std::max(x1, x2), std::max(x3, x4));\n    const auto ymin = std::min(std::min(y1, y2), std::min(y3, y4));\n    const auto ymax = std::max(std::max(y1, y2), std::max(y3, y4));\n\n    const auto dx = xmax - xmin;\n    const auto dy = ymax - ymin;\n\n    // Empty cell?\n    if (dx == 0 || dy == 0)\n      return Handedness::Invalid;\n\n    // Huge cell? (most likely due to projection instabilities)\n    if (dx >= cell_size_limit || dy >= cell_size_limit)\n      return Handedness::Huge;\n\n    const auto ratio = dy / dx;\n\n    if (ratio < 0.01 || ratio > 100)\n      return Handedness::Oblong;\n\n    // Check for convexness and orientation\n\n    const auto area1 = (x2 - x1) * (y3 - y2) - (y2 - y1) * (x3 - x2);\n    const auto area2 = (x3 - x2) * (y4 - y3) - (y3 - y2) * (x4 - x3);\n    const auto area3 = (x4 - x3) * (y1 - y4) - (y4 - y3) * (x1 - x4);\n    const auto area4 = (x1 - x4) * (y2 - y1) - (y1 - y4) * (x2 - x1);\n\n    if (area1 <= 0 && area2 <= 0 && area3 <= 0 && area4 <= 0)\n      return Handedness::ClockwiseConvex;\n\n    if (area1 >= 0 && area2 >= 0 && area3 >= 0 && area4 >= 0)\n      return Handedness::CounterClockwiseConvex;\n\n    return Handedness::NotConvex;\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n\n}  // namespace\n\nCoordinateAnalysis analysis(const CoordinateMatrix& coords)\n{\n  try\n  {\n    const auto nx = coords.width();\n    const auto ny = coords.height();\n\n    BoolMatrix valid(nx - 1, ny - 1, true);\n    BoolMatrix clockwise(nx - 1, ny - 1, false);\n\n    std::size_t cw = 0;\n    std::size_t ccw = 0;\n    std::size_t bad = 0;\n\n#if 0\n    std::size_t huge = 0;\n    std::size_t oblong = 0;\n    std::size_t notconvex = 0;\n#endif\n\n    // Go through the coordinates once\n\n    for (std::size_t j = 0; j < ny - 1; j++)\n      for (std::size_t i = 0; i < nx - 1; i++)\n      {\n        auto hand = analyze_cell(coords.x(i, j),\n                                 coords.y(i, j),\n                                 coords.x(i, j + 1),\n                                 coords.y(i, j + 1),\n                                 coords.x(i + 1, j + 1),\n                                 coords.y(i + 1, j + 1),\n                                 coords.x(i + 1, j),\n                                 coords.y(i + 1, j));\n\n        if (hand == Handedness::ClockwiseConvex)\n        {\n          clockwise.set(i, j, true);\n          ++cw;\n        }\n        else if (hand == Handedness::CounterClockwiseConvex)\n        {\n          // clockwise.set(i, j, false);\n          ++ccw;\n        }\n        else\n        {\n          valid.set(i, j, false);\n          ++bad;\n#if 0\n          if (hand == Handedness::Huge)\n            ++huge;\n          else if (hand == Handedness::Oblong)\n            ++oblong;\n          else if (hand == Handedness::NotConvex)\n            ++notconvex;\n#endif\n        }\n      }\n\n    // The coordinates are likely to be upside done if there are many more CCW cells than CW cells\n\n    bool needs_flipping = (ccw > 2 * cw);\n\n    return CoordinateAnalysis{valid, clockwise, needs_flipping};\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n\n}  // namespace Fmi\n", "meta": {"hexsha": "757a74c229546ad5ca0a866e68ce894080636e3c", "size": 5084, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "gis/CoordinateMatrixAnalysis.cpp", "max_stars_repo_name": "fmidev/smartmet-library-gis", "max_stars_repo_head_hexsha": "3fd5e7ede8f04e262d7de3f884fb575d98ae956d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "gis/CoordinateMatrixAnalysis.cpp", "max_issues_repo_name": "fmidev/smartmet-library-gis", "max_issues_repo_head_hexsha": "3fd5e7ede8f04e262d7de3f884fb575d98ae956d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2017-03-01T10:15:38.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-11T10:53:26.000Z", "max_forks_repo_path": "gis/CoordinateMatrixAnalysis.cpp", "max_forks_repo_name": "fmidev/smartmet-library-gis", "max_forks_repo_head_hexsha": "3fd5e7ede8f04e262d7de3f884fb575d98ae956d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2017-09-16T15:14:06.000Z", "max_forks_repo_forks_event_max_datetime": "2017-09-16T15:14:06.000Z", "avg_line_length": 29.0514285714, "max_line_length": 98, "alphanum_fraction": 0.5597954367, "num_tokens": 1438, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.8006919925839875, "lm_q2_score": 0.3960681662740417, "lm_q1q2_score": 0.3171286092530485}}
{"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#if USE_LAPACK\n/* This whole file is used only if we are using lapack */\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/vector.hpp>\n\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\n#include \"solution/util/include/ublas-helpers.hpp\"\n\n#include \"solution/util/include/svd_invert_solve.hpp\"\n#include \"util/base/include/util.h\"\n\nnamespace ublas = boost::numeric::ublas;\n\n// Solve U*S*VT * x = b,\n// Where U,S,VT are the SVD of a matrix.  x will replace b on output\nint svdInvertSolve(const ublas::matrix<double,ublas::column_major> &U,\n                     const ublas::vector<double> &S,\n                     const ublas::matrix<double,ublas::column_major> &VT,\n                     ublas::vector<double> &b,\n                     std::ostream &logf)\n{\n  const double small = 1.0e-8;\n  int nsing = 0;\n  ublas::matrix<double,ublas::column_major> Utmp(U.size2(),U.size1()), Vtmp(VT.size2(),VT.size1());\n  ublas::matrix<double,ublas::column_major> Ainv(Vtmp.size1(),Utmp.size2());\n  ublas::vector<double> tmpvec(Vtmp.size2()); // able to store a row of VT (== a column of V)\n  \n\n  Utmp = ublas::trans(U);\n  Vtmp = ublas::trans(VT);\n\n  int nrow = Utmp.size1();\n  int ncol = Utmp.size2();\n\n  logf << \"Largest singular value = \" << S[0] << \"\\n\"; \n  \n  // multiply Utmp from the left by the inverse of the diagonal matrix S\n  double singthresh = S[0]*small;\n  for(int i=0;i<nrow;++i) {\n    double sinv = S[i];\n    if(sinv < singthresh) {\n      // Note that the elements of S are all >=0.  For \"sufficiently\n      // small\" singular values we set 1/s = 1/singthresh and log the singular\n      // component\n      double s= sinv;           // store for output without moving the meat of this branch down below all the output \n      nsing++;\n      sinv = 1.0/singthresh;    // keep the multiplier on this singular component \"reasonable\".\n      \n      // log the singular component (everything between here and the\n      // marker below is strictly diagnostic and not necessary for the\n      // algorithm.)\n      \n      // the columns of V (== trans(VT)) give the basis vectors for the nullspace\n      int kmax = 0;\n      double vtmax = fabs(Vtmp(0,i));\n      for(int k=0; k<Vtmp.size1(); ++k) {\n        tmpvec[k] = Vtmp(k,i);  // column i, kth entry\n        double vtabs = fabs(tmpvec[k]);\n        if(vtabs > vtmax) {\n          vtmax = vtabs;\n          kmax = k;\n        }\n      }\n      // suppress printing of small values.\n      double prnthresh = 1.0e-4*vtmax;\n      for(int k=0; k<tmpvec.size(); ++k)\n        if(fabs(tmpvec[k]) < prnthresh)\n          tmpvec[k] = 0.0;\n      \n      logf << \"Singular component:  s= \" << s\n           << \"  kmax= \" << kmax << \"  vtval= \" << vtmax\n           << \"  sinv set to: \" << sinv\n           << \"\\n\";\n      logf << tmpvec << \"\\n\"; \n      // end of singular component logging \n    }\n    else {\n      sinv = 1.0/sinv;\n    }\n    for(int j=0;j<ncol;++j)\n      Utmp(i,j) *= sinv;\n  }\n\n  Ainv = prod(Vtmp,Utmp);\n\n  ublas::vector<double> bb(b);\n  axpy_prod(Ainv,bb,b);\n\n  return nsing;\n}\n\n#endif\n", "meta": {"hexsha": "aea6f763e526e6089e36ca516969188b81259e32", "size": 4772, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cvs/objects/solution/util/source/svd_invert_solve.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/svd_invert_solve.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/svd_invert_solve.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.28125, "max_line_length": 117, "alphanum_fraction": 0.6582145851, "num_tokens": 1296, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.665410558746814, "lm_q2_score": 0.476579651063676, "lm_q1q2_score": 0.3171211319016423}}
{"text": "#include \"ScanMatch.h\"\n#include \"common/feature_utils.h\"\n#include \"common/math_utils.h\"\n#include \"common/nanoflann_pcl.h\"\n#include \"common/ros_utils.h\"\n#include \"common/transform_utils.h\"\n\n#include <pcl/kdtree/kdtree_flann.h>\n\n#include <Eigen/Eigenvalues>\n#include <Eigen/QR>\n\nnamespace lidar_slam {\n\nusing std::sqrt;\nusing std::fabs;\nusing std::asin;\nusing std::atan2;\nusing std::pow;\n\nScanMatch::ScanMatch(const size_t maxIterations)\n    : _maxIterations(maxIterations), _deltaTAbort(0.05), _deltaRAbort(0.05),\n      _useScore(true), _match_count(0), _fail_match_count(0), _total_score(0),\n      _score_threshold(800), _match_percentage_threshold(0.4),\n      _referenceCornerCloudDS(new CloudI()),\n      _referenceSurfCloudDS(new CloudI()), _CornerCloudDS(new CloudI()),\n      _SurfCloudDS(new CloudI()) {\n\n  _downSizeFilterCorner.setLeafSize(0.2, 0.2, 0.2);\n  _downSizeFilterSurf.setLeafSize(0.4, 0.4, 0.4);\n\n  _fineScore = false;\n}\n\nScanMatch::~ScanMatch() {\n  std::cout << \"[ScanMatch]\\n\"\n            << \" ,match_count:\" << _match_count\n            << \" ,fail_match_count:\" << _fail_match_count\n            << \" ,averageScore:\" << getAverageScore() << std::endl;\n}\n\ndouble ScanMatch::getScore(const CloudI &coeffCloud) {\n  double score = 0;\n  for (int i = 0; i < coeffCloud.points.size(); ++i) {\n    const PointI &p = coeffCloud.points[i];\n    score += std::exp(-fabs(p.intensity));\n  }\n  return score;\n}\n\nbool ScanMatch::scanMatchScan(const CloudIConPtr &referenceCornerCloud,\n                              const CloudIConPtr &referenceSurfCloud,\n                              const CloudIConPtr &CornerCloud,\n                              const CloudIConPtr &SurfCloud,\n                              Twist &transformf) {\n\n  if (referenceCornerCloud->points.size() < 50 ||\n      referenceSurfCloud->points.size() < 100) {\n    std::cout << \"reference cloud points too few.\" << std::endl;\n    return false;\n  }\n  Twist transform = transformf;\n\n  PointI pointSel, pointOri, pointProj, coeff;\n  std::vector<int> pointSearchInd(5, 0);\n  std::vector<float> pointSearchSqDis(5, 0);\n\n    nanoflann::KdTreeFLANN<PointI> kdtreeCorner;\n    nanoflann::KdTreeFLANN<PointI> kdtreeSurf;\n      /*\n  pcl::KdTreeFLANN<PointI> kdtreeCorner;\n  pcl::KdTreeFLANN<PointI> kdtreeSurf;\n  */\n\n  kdtreeCorner.setInputCloud(referenceCornerCloud);\n  kdtreeSurf.setInputCloud(referenceSurfCloud);\n\n  bool converge = false;\n  bool isDegenerate = false;\n  Eigen::Matrix<float, 6, 6> matP;\n\n  size_t CornerNum = CornerCloud->points.size();\n  size_t SurfNum = SurfCloud->points.size();\n\n  pcl::PointCloud<PointI> laserCloudOri;\n  pcl::PointCloud<PointI> coeffSel;\n\n  int line_match_count = 0;\n  int plane_match_count = 0;\n  size_t iterCount;\n  for (iterCount = 0; iterCount < _maxIterations; iterCount++) {\n    laserCloudOri.clear();\n    coeffSel.clear();\n    line_match_count = 0;\n    plane_match_count = 0;\n\n    for (int i = 0; i < CornerNum; i++) {\n      pointOri = CornerCloud->points[i];\n      pointAssociateToMap(transform, pointOri, pointSel);\n      kdtreeCorner.nearestKSearch(pointSel, 5, pointSearchInd,\n                                  pointSearchSqDis);\n      if (pointSearchSqDis[4] < 5.0) {\n        const Eigen::Vector3f &point = pointSel.getVector3fMap();\n        Eigen::Vector3f lineA, lineB;\n        if (findLine(*referenceCornerCloud, pointSearchInd, lineA, lineB)) {\n          PointI coefficients;\n          if (getCornerFeatureCoefficients(lineA, lineB, point, coefficients)) {\n            laserCloudOri.push_back(pointOri);\n            coeffSel.push_back(coefficients);\n          }\n          line_match_count++;\n        }\n      }\n    }\n\n    for (int i = 0; i < SurfNum; i++) {\n      pointOri = SurfCloud->points[i];\n      pointAssociateToMap(transform, pointOri, pointSel);\n      kdtreeSurf.nearestKSearch(pointSel, 5, pointSearchInd, pointSearchSqDis);\n      if (pointSearchSqDis[4] < 5.0) {\n        Eigen::Vector4f planeCoef;\n        if (findPlane(*referenceSurfCloud, pointSearchInd, 0.2, planeCoef)) {\n          PointI coefficients;\n          if (getSurfaceFeatureCoefficients(planeCoef, pointSel,\n                                            coefficients)) {\n            laserCloudOri.push_back(pointOri);\n            coeffSel.push_back(coefficients);\n          }\n          plane_match_count++;\n        }\n      }\n    }\n\n    float srx = transform.rot_x.sin();\n    float crx = transform.rot_x.cos();\n    float sry = transform.rot_y.sin();\n    float cry = transform.rot_y.cos();\n    float srz = transform.rot_z.sin();\n    float crz = transform.rot_z.cos();\n\n    size_t laserCloudSelNum = laserCloudOri.points.size();\n    if (laserCloudSelNum < 50) {\n      ROS_WARN(\"matched cloud points too few. Matched/Input:  %d / %d\", laserCloudSelNum, CornerNum+SurfNum);\n      break;\n    }\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      pointOri = laserCloudOri.points[i];\n      coeff = coeffSel.points[i];\n      /*\n      float arx = (crx * sry * srz * pointOri.x + crx * crz * sry * pointOri.y -\n                   srx * sry * pointOri.z) *\n                      coeff.x +\n                  (-srx * srz * pointOri.x - crz * srx * pointOri.y -\n                   crx * pointOri.z) *\n                      coeff.y +\n                  (crx * cry * srz * pointOri.x + crx * cry * crz * pointOri.y -\n                   cry * srx * pointOri.z) *\n                      coeff.z;\n\n      float ary = ((cry * srx * srz - crz * sry) * pointOri.x +\n                   (sry * srz + cry * crz * srx) * pointOri.y +\n                   crx * cry * pointOri.z) *\n                      coeff.x +\n                  ((-cry * crz - srx * sry * srz) * pointOri.x +\n                   (cry * srz - crz * srx * sry) * pointOri.y -\n                   crx * sry * pointOri.z) *\n                      coeff.z;\n\n      float arz = ((crz * srx * sry - cry * srz) * pointOri.x +\n                   (-cry * crz - srx * sry * srz) * pointOri.y) *\n                      coeff.x +\n                  (crx * crz * pointOri.x - crx * srz * pointOri.y) * coeff.y +\n                  ((sry * srz + cry * crz * srx) * pointOri.x +\n                   (crz * sry - cry * srx * srz) * pointOri.y) *\n                      coeff.z;\n        */\n        float arx = ((crz*sry*crx + srz*srx)* pointOri.y +(srz*crx-crz*sry*srx)* pointOri.z)*coeff.x +\n        ((srz*sry*crx-crz*srx)*pointOri.y -(srz*sry*srx+crz*crx)*pointOri.z)*coeff.y +\n        (cry*crx*pointOri.y-cry*srx*pointOri.z)*coeff.z;\n\n        float ary = (-crz*sry*pointOri.x+crz*cry*srx*pointOri.y+crz*cry*crx*pointOri.z)*coeff.x +\n        (-srz*sry*pointOri.x+srz*cry*srx*pointOri.y +srz*cry*crx*pointOri.z)*coeff.y +\n        (-cry*pointOri.x-sry*srx*pointOri.y-sry*crx*pointOri.z)*coeff.z;\n\n        float arz = (-srz*cry*pointOri.x -(srz*sry*srx+crz*crx)*pointOri.y+(crz*srx-srz*sry*crx)*pointOri.z)*coeff.x+\n        (crz*cry*pointOri.x+ (crz*sry*srx-srz*crx)*pointOri.y+crz*sry*crx+srz*srx*pointOri.z)*coeff.y+\n        0*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      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        if (matE(0, i) < eignThre[i]) {\n          for (int j = 0; j < 6; j++) {\n            matV2(i, j) = 0;\n          }\n          isDegenerate = true;\n        } else {\n          break;\n        }\n      }\n      matP = matV.inverse() * matV2;\n    }\n\n    if (isDegenerate) {\n      Eigen::Matrix<float, 6, 1> matX2(matX);\n      matX = matP * matX2;\n    }\n\n    transform.rot_x += matX(0, 0);\n    transform.rot_y += matX(1, 0);\n    transform.rot_z += matX(2, 0);\n    transform.pos.x() += matX(3, 0);\n    transform.pos.y() += matX(4, 0);\n    transform.pos.z() += matX(5, 0);\n\n    float deltaR =\n        sqrt(pow(rad2deg(matX(0, 0)), 2) + pow(rad2deg(matX(1, 0)), 2) +\n             pow(rad2deg(matX(2, 0)), 2));\n    float deltaT = sqrt(pow(matX(3, 0) * 100, 2) + pow(matX(4, 0) * 100, 2) +\n                        pow(matX(5, 0) * 100, 2));\n\n    // std::cout << \"iterator:\" << iterCount << std::endl;\n    // transform.print();\n    if (deltaR < _deltaRAbort && deltaT < _deltaTAbort) {\n      converge = true;\n      break;\n    }\n  }\n\n  if (converge && _useScore) {\n\n    double score = getScore(coeffSel);\n\n    double match_count = line_match_count + plane_match_count;\n    float percent = match_count / (CornerNum + SurfNum);\n    std::cout << \"scan match score:\" << score << \",per:\" << percent\n              << std::endl;\n\n    if (_fineScore) {\n      laserCloudOri.clear();\n      coeffSel.clear();\n      line_match_count = 0;\n      plane_match_count = 0;\n      for (int i = 0; i < CornerNum; i++) {\n        pointOri = CornerCloud->points[i];\n        pointAssociateToMap(transform, pointOri, pointSel);\n        kdtreeCorner.nearestKSearch(pointSel, 5, pointSearchInd,\n                                    pointSearchSqDis);\n        if (pointSearchSqDis[0] < 0.02) {\n          const Eigen::Vector3f &point = pointSel.getVector3fMap();\n          Eigen::Vector3f lineA, lineB;\n          if (findLine(*referenceCornerCloud, pointSearchInd, lineA, lineB)) {\n            PointI coefficients;\n            if (getCornerFeatureCoefficients(lineA, lineB, point,\n                                             coefficients)) {\n              laserCloudOri.push_back(pointOri);\n              coeffSel.push_back(coefficients);\n            }\n            line_match_count++;\n          }\n        }\n      }\n\n      for (int i = 0; i < SurfNum; i++) {\n        pointOri = SurfCloud->points[i];\n        pointAssociateToMap(transform, pointOri, pointSel);\n        kdtreeSurf.nearestKSearch(pointSel, 5, pointSearchInd,\n                                  pointSearchSqDis);\n        if (pointSearchSqDis[0] < 0.05) {\n          Eigen::Vector4f planeCoef;\n          if (findPlane(*referenceSurfCloud, pointSearchInd, 0.2, planeCoef)) {\n            PointI coefficients;\n            if (getSurfaceFeatureCoefficients(planeCoef, pointSel,\n                                              coefficients)) {\n              laserCloudOri.push_back(pointOri);\n              coeffSel.push_back(coefficients);\n            }\n            plane_match_count++;\n          }\n        }\n      }\n\n      double score2 = getScore(coeffSel);\n      match_count = line_match_count + plane_match_count;\n      float percent2 = match_count / (CornerNum + SurfNum);\n      std::cout << \"scan match score2:\" << score2 << \" ,per2:\" << percent2\n                << std::endl;\n    }\n\n    if (score < _score_threshold) {\n      transformf = transform;\n      _fail_match_count++;\n      std::cout << \"low score!!\" << score << \",per:\" << percent << std::endl;\n      return false;\n    }\n\n    if (percent < _match_percentage_threshold) {\n      transformf = transform;\n      _fail_match_count++;\n      std::cout << \"low percent!!\" << score << \",per:\" << percent << std::endl;\n      return false;\n    }\n    _total_score += score;\n    _match_count++;\n    transformf = transform;\n\n    return true;\n  }\n  //??? should we take the result when not converge?\n  transformf = transform;\n  _fail_match_count++;\n\n  return false;\n}\n\nbool ScanMatch::scanMatchScan(const CloudIConPtr &referenceCornerCloud,\n                              const CloudIConPtr &referenceSurfCloud,\n                              const CloudIConPtr &CornerCloud,\n                              const CloudIConPtr &SurfCloud,\n                              Eigen::Isometry3f &relative_pose) {\n  Twist transform;\n  convertTransform(relative_pose, transform);\n  bool success = scanMatchScan(referenceCornerCloud, referenceSurfCloud,\n                               CornerCloud, SurfCloud, transform);\n  convertTransform(transform, relative_pose);\n  return success;\n}\n\nbool ScanMatch::scanMatchLocal(const CloudIConPtr &referenceCornerCloud,\n                               const CloudIConPtr &referenceSurfCloud,\n                               const CloudIConPtr &CornerCloud,\n                               const CloudIConPtr &SurfCloud,\n                               Eigen::Isometry3f &relative_pose) {\n  Twist transform;\n  convertTransform(relative_pose, transform);\n  bool success = scanMatchLocal(referenceCornerCloud, referenceSurfCloud,\n                                CornerCloud, SurfCloud, transform);\n  convertTransform(transform, relative_pose);\n  return success;\n}\n\nbool ScanMatch::scanMatchLocal(const CloudIConPtr &referenceCornerCloud,\n                               const CloudIConPtr &referenceSurfCloud,\n                               const CloudIConPtr &CornerCloud,\n                               const CloudIConPtr &SurfCloud,\n                               Twist &transform) {\n  _referenceCornerCloudDS->clear();\n  _downSizeFilterCorner.setInputCloud(referenceCornerCloud);\n  _downSizeFilterCorner.filter(*_referenceCornerCloudDS);\n\n  _referenceSurfCloudDS->clear();\n  _downSizeFilterSurf.setInputCloud(referenceSurfCloud);\n  _downSizeFilterSurf.filter(*_referenceSurfCloudDS);\n\n  _CornerCloudDS->clear();\n  _downSizeFilterCorner.setInputCloud(CornerCloud);\n  _downSizeFilterCorner.filter(*_CornerCloudDS);\n\n  _SurfCloudDS->clear();\n  _downSizeFilterSurf.setInputCloud(SurfCloud);\n  _downSizeFilterSurf.filter(*_SurfCloudDS);\n\n  return scanMatchScan(_referenceCornerCloudDS, _referenceSurfCloudDS,\n                       _CornerCloudDS, _SurfCloudDS, transform);\n}\n\n} // end namespace lidar_slam\n", "meta": {"hexsha": "af70d1112d2ab74d1b29a071b59b05ae603d737c", "size": 14204, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "L_SLAM/src/scan_to_scan_match/ScanMatch.cpp", "max_stars_repo_name": "autonomy-lab-cooper/CooperMapper", "max_stars_repo_head_hexsha": "32f3efccabffdd134ea2dfcbd746b8ccce1ce1c0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 50.0, "max_stars_repo_stars_event_min_datetime": "2019-01-10T23:52:15.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-10T08:48:44.000Z", "max_issues_repo_path": "L_SLAM/src/scan_to_scan_match/ScanMatch.cpp", "max_issues_repo_name": "autonomy-lab-cooper/CooperMapper", "max_issues_repo_head_hexsha": "32f3efccabffdd134ea2dfcbd746b8ccce1ce1c0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2019-12-09T08:37:27.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-15T07:57:45.000Z", "max_forks_repo_path": "L_SLAM/src/scan_to_scan_match/ScanMatch.cpp", "max_forks_repo_name": "autonomy-lab-cooper/CooperMapper", "max_forks_repo_head_hexsha": "32f3efccabffdd134ea2dfcbd746b8ccce1ce1c0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 14.0, "max_forks_repo_forks_event_min_datetime": "2019-01-11T04:40:53.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-02T21:32:58.000Z", "avg_line_length": 35.421446384, "max_line_length": 117, "alphanum_fraction": 0.5862433117, "num_tokens": 4014, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6442251064863697, "lm_q2_score": 0.49218813572079556, "lm_q1q2_score": 0.3170799541460573}}
{"text": "#pragma once\n/**\n\n   @file KinematicVessel.hpp\n   @brief Kinematic planar vessel.\n\n*/\n\n#include <atomic>\n#include <chrono>\n#include <cinttypes>\n#include <memory>\n\n#include <boost/statechart/detail/memory.hpp>\n#include <boost/statechart/fifo_scheduler.hpp>\n#include <boost/statechart/event_base.hpp>\n\n#include <yaml-cpp/yaml.h>\n\n#ifdef _MSC_VER\n#pragma warning(push, 0)\n#endif\n#include <dds/pub/Publisher.hpp>\n#include <dds/sub/Subscriber.hpp>\n#ifdef _MSC_VER\n#pragma warning(pop)\n#endif\n\n#include <mimir/IAlgorithm.hpp>\n\nnamespace mimir\n{\n  namespace algorithm\n  {\n\n    /**\n       @brief Kinematic planar vessel numerical simulation model.\n\n       \\rst\n\n       This class implements a kinematic planar vessel that are controlled by inputs,\n       which are velocities and rate of turn.\n\n       .. math::\n          :nowrap:\n\n          \\begin{align}\n          \\boldsymbol{p} = \\begin{bmatrix}N\\\\E\\end{bmatrix} &\\in \\mathbb{R}^2 &\\text{position}\\\\\n          \\boldsymbol{\\psi} \\in \\mathbb{S} &&\\text{heading}\\\\\n          \\boldsymbol{v} = \\begin{bmatrix}u\\\\v\\end{bmatrix} &\\in \\mathbb{R}^2 &\\text{linear velocity}\\\\\n          \\boldsymbol{r} \\in \\mathbb{R} &&\\text{angular velocity}\\\\\n          x(t) = \\begin{bmatrix}\\boldsymbol{p}\\\\\\psi\\end{bmatrix}, &\\quad\\mathbb{R} \\to \\mathbb{R}^2 \\times \\mathbb{S}&\\text{state vector}\n          \\end{align}\n\n       .. math::\n          :nowrap:\n\n          \\begin{align}\n          \\dat x &= \\begin{bmatrix}\\cos(\\psi)& -\\sin(\\psi) &0\\\\\n                                  \\sin(\\psi)& \\cos(\\psi) & 0\\\\\n                                  0&0&1\n                                  \\end{bmatrix}\n                   \\begin{bmatrix}u\\\\v\\\\r\\end{bmatrix}\\\\\n          \\boldsymbol{u} &= \\begin{bmatrix}u\\\\v\\\\r\\end{bmatrix}\\\\\n          \\boldsymbol{y} &= x\n          \\end{align}\n\n\n       +----------------------+----------------------------+-------------------------------------+---------------+----------------+----------------------+-------------------+\n       | Name                 | Symbol                     | Description                         | Causality     | Variability    | Default              | Unit              |\n       +======================+============================+=====================================+===============+================+======================+===================+\n       | ``vessel_ctrl``      | :math:`u`                  | Desired: Surge, Sway rate of turn   | ``input``     | ``discrete``   | \\                    | [m/s, m/s, rad/s] |\n       +----------------------+----------------------------+-------------------------------------+---------------+----------------+----------------------+-------------------+\n       | ``kinematics``       | :math:`y`                  | ``fkin::Kinematics2D``              | ``output``    | ``continuous`` | \\                    | \\                 |\n       +----------------------+----------------------------+-------------------------------------+---------------+----------------+----------------------+-------------------+\n       | ``position_course``  | :math:`[p_0,\\psi_0]`       | Initial; North, East, Yaw           | ``parameter`` | ``fixed``      | :math:`[0, 50, 0]`   | m                 |\n       +----------------------+----------------------------+-------------------------------------+---------------+----------------+----------------------+-------------------+\n\n       .. warning::\n\n          This simulation model is very basic and has been abandoned in favor of a higher\n          fidelity model implemented using FMI :cite:`fmi2`.\n\n       \\endrst\n\n    */\n    class KinematicVessel : public IAlgorithm\n    {\n    public:\n      /**\n         @brief KinematicVessel constructor.\n\n         The constructor parses the specification from the given YAML\n         node. It establishes data structures and sets up DDS readers\n         and writers according to the input/output scheme of the\n         algorithm. The following YAML code block shows the expected\n         layout of the ``KinematicVessel`` map of a input config file. The\n         inputs, outputs, and initial conditions are communicated with\n         DDS communication. Common is their DDS topic and DDS\n         identifier. The specification is deemed self-explanatory.\n\n         \\rst\n\n         .. code-block:: yaml\n\n             time_step_ms: 200\n             inputs:\n               vessel_ctrl:                 # DDS type: fkin::IdVec3d\n                 topic: fkinVesselCtrl\n                 id: Vessel\n                 max_age_ms: -1\n             outputs:                       # DDS type: fkin::Kinematics2D\n               kinematics:\n                 topic: fkinKinematics2D\n                 id: Vessel\n             initial_conditions:\n               position_course:             # DDS type: fkin::IdVec3d\n                 topic: fkinPositionCourse\n                 id: Vessel\n                 max_wait_ms: 50\n                 fallback: [0, 50, 0]\n         \\endrst\n\n         @param [in] config YAML configuration from input file.\n         @param [in] scheduler State machine scheduler, needed to post events to state machine.\n         @param [in] machine State machine processor handle, needed to post events to state machine.\n         @param publisher DDS data writer to send data.\n         @param subscriber DDS data reader to receive data.\n      */\n      explicit KinematicVessel(\n          const YAML::Node& config,\n          boost::statechart::fifo_scheduler<>& scheduler,\n          boost::statechart::fifo_scheduler<>::processor_handle machine,\n          dds::pub::Publisher publisher,\n          dds::sub::Subscriber subscriber);\n      /// Destructor.\n      virtual ~KinematicVessel();\n      /// See base class.\n      virtual void solve(const std::atomic<bool>& cancel_token);\n      /// See base class.\n      virtual void initialize(const std::atomic<bool>& cancel_token);\n      /// See base class.\n      virtual void timer(const std::atomic<bool>& cancel_token);\n      /// Name identifier of algorithm.\n      virtual inline const char* name() { return \"KinematicVessel\"; }\n      /// Helper function that queues event to state machine.\n      void event(boost::statechart::event_base * const event);\n\n    private:\n      /// March simulation time one time step ahead.\n      inline void step_time() { m_next_step += m_time_step; }\n      KinematicVessel() = delete;\n      class Impl;\n      std::unique_ptr<Impl> m_impl; ///< Holds the implementation of the algorithm.\n      boost::statechart::fifo_scheduler<> & m_scheduler; ///< Members for state machine.\n      boost::statechart::fifo_scheduler<>::processor_handle m_stateMachine; ///< Member for state machine.\n      const std::chrono::milliseconds m_time_step; ///< Discrete time step.\n      std::chrono::steady_clock::time_point m_next_step; ///< Simulation time point.\n      const YAML::Node m_config; ///< YAML configuration for algorithm.\n    };\n\n  }\n}\n", "meta": {"hexsha": "3f98632f0a56cfaae262d43361cc201f44935d3f", "size": 6884, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/mimir/algorithm/KinematicVessel.hpp", "max_stars_repo_name": "sintef-ocean/mimir", "max_stars_repo_head_hexsha": "c1d9671ee61e543e631f04d8b343a8f5e9229f6f", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/mimir/algorithm/KinematicVessel.hpp", "max_issues_repo_name": "sintef-ocean/mimir", "max_issues_repo_head_hexsha": "c1d9671ee61e543e631f04d8b343a8f5e9229f6f", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/mimir/algorithm/KinematicVessel.hpp", "max_forks_repo_name": "sintef-ocean/mimir", "max_forks_repo_head_hexsha": "c1d9671ee61e543e631f04d8b343a8f5e9229f6f", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.9756097561, "max_line_length": 174, "alphanum_fraction": 0.4976757699, "num_tokens": 1529, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6442250928250375, "lm_q2_score": 0.49218813572079556, "lm_q1q2_score": 0.31707994742211165}}
{"text": "// File: shallow_copy_problems_type.cpp\n\n#include <iostream>\n#include <boost/numeric/mtl/mtl.hpp>\n\nusing namespace mtl;\n\nint main(int, char**)\n{\n    dense2D<double>     A(3, 3), B(3, 3);\n    dense2D<float>      C(3, 3);\n\n    A= 4.0;\n\n    B= A;               // Create an alias\n    B*= 2.0;            // Changes also A\n\n    C= A;               // Copies the values\n    C*= 2.0;            // A is unaffected\n\n    return 0;\n}\n", "meta": {"hexsha": "bd9fb38daf0e645fc1436b0aadbf8e53f3581e9f", "size": 425, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/mtl/examples/shallow_copy_problems_type.cpp", "max_stars_repo_name": "lit-uriy/mtl4-mirror", "max_stars_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_stars_repo_licenses": ["MTLL"], "max_stars_count": 24.0, "max_stars_repo_stars_event_min_datetime": "2019-03-26T15:25:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T10:00:45.000Z", "max_issues_repo_path": "libs/numeric/mtl/examples/shallow_copy_problems_type.cpp", "max_issues_repo_name": "lit-uriy/mtl4-mirror", "max_issues_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_issues_repo_licenses": ["MTLL"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-04-17T12:35:32.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-03T15:46:25.000Z", "max_forks_repo_path": "libs/numeric/mtl/examples/shallow_copy_problems_type.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": 18.4782608696, "max_line_length": 44, "alphanum_fraction": 0.5035294118, "num_tokens": 139, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.5964331462646255, "lm_q1q2_score": 0.31683087788656966}}
{"text": "#include \"hoCuNDArray_utils.h\"\n#include \"radial_utilities.h\"\n#include \"cuNDArray_fileio.h\"\n#include \"cuNDArray_math.h\"\n#include \"imageOperator.h\"\n#include \"identityOperator.h\"\n#include \"hoPartialDerivativeOperator.h\"\n#include \"hoCuConebeamProjectionOperator.h\"\n#include \"cuConvolutionOperator.h\"\n#include \"hoCuNDArray_blas.h\"\n#include \"hoCuNDArray_elemwise.h\"\n#include \"hoCuNDArray_blas.h\"\n#include \"cgSolver.h\"\n#include \"CBCT_acquisition.h\"\n#include \"complext.h\"\n#include \"encodingOperatorContainer.h\"\n#include \"vector_td_io.h\"\n#include \"hoPartialDerivativeOperator.h\"\n#include \"hoCuGPBBSolver.h\"\n#include \"hoCuTvOperator.h\"\n#include \"hoCuTvPicsOperator.h\"\n#include \"hoCuNCGSolver.h\"\n#include \"hoCuCgDescentSolver.h\"\n#include \"hoNDArray_utils.h\"\n#include \"cuPartialDifferenceOperator.h\"\n#include \"cuTvOperator.h\"\n#include \"cuTv1dOperator.h\"\n#include \"cuTvPicsOperator.h\"\n#include \"CBSubsetOperator.h\"\n#include \"osSPSSolver.h\"\n#include \"osMOMSolver.h\"\n#include \"cuOSMOMSolverD.h\"\n#include \"osMOMSolverD2.h\"\n#include \"hoCuNCGSolver.h\"\n#include \"osMOMSolverD3.h\"\n#include \"osMOMSolverL1.h\"\n#include \"osMOMSolverF.h\"\n#include \"osAHZCSolver.h\"\n#include \"ADMMSolver.h\"\n#include <iostream>\n#include <algorithm>\n#include <sstream>\n#include <math_constants.h>\n#include <boost/program_options.hpp>\n#include <boost/make_shared.hpp>\n#include <GPUTimer.h>\n#include <operators/cuGaussianFilterOperator.h>\n#include <multiplicationOperatorContainer.h>\n#include <cuDownsampleOperator.h>\n#include <operators/cuSmallConvOperator.h>\n#include <denoise/nonlocalMeans.h>\n#include <solvers/osMOMSolverW.h>\n#include <operators/cuTFFT.h>\n#include \"cuSolverUtils.h\"\n#include \"osPDsolver.h\"\n#include \"osLALMSolver.h\"\n#include \"osLALMSolver2.h\"\n#include \"cuATrousOperator.h\"\n#include \"hdf5_utils.h\"\n#include \"cuEdgeATrousOperator.h\"\n#include \"cuDCTOperator.h\"\n#include \"cuDCTDerivativeOperator.h\"\n#include \"dicomWriter.h\"\n#include \"conebeam_projection.h\"\n#include \"weightingOperator.h\"\n#include \"hoNDArray_math.h\"\n#include \"cuNCGSolver.h\"\n#include \"CT_acquisition.h\"\n#include \"cuScaleOperator.h\"\n#include \"cuTVPrimalDualOperator.h\"\n#include \"cuWTVPrimalDualOperator.h\"\n#include \"cuATVPrimalDualOperator.h\"\n#include \"cuSSTVPrimalDualOperator.h\"\n#include \"cuBilateralPriorPrimalDualOperator.h\"\n#include \"cuTV4DPrimalDualOperator.h\"\n#include \"CBSubsetWeightOperator.h\"\n#include \"BilateralPriorOperator.h\"\n#include \"cuPICSDualOperator.h\"\n#include \"cuTVTFFT.h\"\n\nusing namespace std;\nusing namespace Gadgetron;\n\nnamespace po = boost::program_options;\n\nboost::shared_ptr<hoCuNDArray<float>> downsample_projections(hoCuNDArray<float>* projections, unsigned int num_downsamples )\n{\n\n    if (num_downsamples == 0) return boost::make_shared<hoCuNDArray<float>>(*projections);\n\n    auto tmp = Gadgetron::downsample<float,2>(projections);\n\n    for (int k = 1; k < num_downsamples; k++)\n        tmp = Gadgetron::downsample<float,2>(tmp.get());\n\n    return boost::make_shared<hoCuNDArray<float>>(*tmp);\n}\n\n\n\nboost::shared_ptr<cuNDArray<float> > calculate_prior(boost::shared_ptr<CBCT_binning>  binning,boost::shared_ptr<CBCT_acquisition> ps, hoCuNDArray<float>& projections, std::vector<size_t> is_dims, floatd3 imageDimensions){\n    std::cout << \"Calculating FDK prior\" << std::endl;\n    boost::shared_ptr<CBCT_binning> binning_pics=binning->get_3d_binning();\n    std::vector<size_t> is_dims3d = is_dims;\n    is_dims3d.pop_back();\n    boost::shared_ptr< hoCuConebeamProjectionOperator >\n            Ep( new hoCuConebeamProjectionOperator() );\n    Ep->setup(ps,binning_pics,imageDimensions);\n    Ep->set_codomain_dimensions(ps->get_projections()->get_dimensions().get());\n    Ep->set_domain_dimensions(&is_dims3d);\n    Ep->set_use_filtered_backprojection(true);\n    boost::shared_ptr<hoCuNDArray<float> > prior3d(new hoCuNDArray<float>(&is_dims3d));\n    Ep->mult_MH(&projections,prior3d.get());\n\n    hoCuNDArray<float> tmp_proj(*ps->get_projections());\n    Ep->mult_M(prior3d.get(),&tmp_proj);\n    float s = dot(ps->get_projections().get(),&tmp_proj)/dot(&tmp_proj,&tmp_proj);\n    *prior3d *= s;\n    auto prior = boost::make_shared<cuNDArray<float>>(*prior3d);\n    return prior;\n}\n\n\n\n\nint main(int argc, char** argv)\n{\n\n    string acquisition_filename;\n    string outputFile;\n\n    uintd3 imageSize;\n    floatd3 voxelSize;\n    int device;\n    floatd2 scale_factor;\n    unsigned int iterations;\n    unsigned int subsets;\n    float rho,tau,nlm_noise,bil_weight;\n    float tv_weight,pics_weight, wavelet_weight,huber,sigma,dct_weight,sfr_weight,framelet_weight,atv_weight, sstv_weight;\n    float framelet_weight4d;\n    float tv_4d,atv_4d;\n    bool use_non_negativity;\n    int reg_iter;\n\n    po::options_description desc(\"Allowed options\");\n\n    desc.add_options()\n            (\"help\", \"produce help message\")\n            (\"acquisition,a\", po::value<string>(&acquisition_filename)->default_value(\"acquisition.hdf5\"), \"Acquisition data\")\n            (\"samples,n\",po::value<unsigned int>(),\"Number of samples per ray\")\n    (\"output,f\", po::value<string>(&outputFile)->default_value(\"reconstruction.hdf5\"), \"Output filename\")\n            (\"size,s\",po::value<uintd3>(&imageSize)->default_value(uintd3(512,512,1)),\"Image size in pixels\")\n            (\"binning,b\",po::value<string>(),\"Binning file for 4d reconstruction\")\n            (\"SAG\",\"Use exact SAG correction if present\")\n            (\"voxelSize,v\",po::value<floatd3>(&voxelSize)->default_value(floatd3(0.488f,0.488f,1.0f)),\"Voxel size in mm\")\n            (\"dimensions,d\",po::value<floatd3>(),\"Image dimensions in mm. Overwrites voxelSize.\")\n            (\"iterations,i\",po::value<unsigned int>(&iterations)->default_value(10),\"Number of iterations\")\n    (\"device\",po::value<int>(&device)->default_value(0),\"Number of the device to use (0 indexed)\")\n            (\"downsample,D\",po::value<floatd2>(&scale_factor)->default_value(floatd2(1,1)),\"Downsample projections this factor\")\n            (\"subsets,u\",po::value<unsigned int>(&subsets)->default_value(10),\"Number of subsets to use\")\n    (\"TV\",po::value<float>(&tv_weight)->default_value(0),\"Total variation weight in spatial dimensions\")\n            (\"TV4D\",po::value<float>(&tv_4d)->default_value(0),\"Total variation weight in temporal dimensions\")\n            (\"ATV4D\",po::value<float>(&atv_4d)->default_value(0),\"Advanced Total variation weight in temporal dimensions\")\n            (\"ATV\",po::value<float>(&atv_weight)->default_value(0),\"Advanced Total variation weight \")\n            (\"SSTV\",po::value<float>(&sstv_weight)->default_value(0),\"Scale space total variation weight \")\n            (\"PICS\",po::value<float>(&pics_weight)->default_value(0),\"PICS weight\")\n            (\"Wavelet,W\",po::value<float>(&wavelet_weight)->default_value(0),\"Weight of the wavelet operator\")\n            (\"Framelet\",po::value<float>(&framelet_weight)->default_value(0),\"Weight of the framelet operator\")\n            (\"Framelet4D\",po::value<float>(&framelet_weight4d)->default_value(0),\"Weight of the framelet operator\")\n            (\"Huber\",po::value<float>(&huber)->default_value(0),\"Huber weight\")\n            (\"use_prior\",\"Use an FDK prior\")\n            (\"use_non_negativity\",po::value<bool>(&use_non_negativity)->default_value(true),\"Prevent image from having negative attenuation\")\n            (\"sigma\",po::value<float>(&sigma)->default_value(0.1),\"Sigma for billateral filter\")\n            (\"DCT\",po::value<float>(&dct_weight)->default_value(0),\"DCT regularization\")\n            (\"SFR\",po::value<float>(&sfr_weight)->default_value(0),\"SFR regularization\")\n            (\"3D\",\"Only use binning for selecting valid projections\")\n            (\"tau\",po::value<float>(&tau)->default_value(1e-5),\"Tau value for solver\")\n            (\"reg_iter\",po::value<int>(&reg_iter)->default_value(2))\n            (\"bilateral-weight\",po::value<float>(&bil_weight)->default_value(0),\"Bilateral weight\")\n            (\"prior\",po::value<string>(),\"prior image\")\n            (\"projection_weights\",po::value<string>(),\"Array containing weights to be applied to the projections.\")\n\n            (\"NLM\",po::value<float>(&nlm_noise)->default_value(0),\"Use non-local means based on the 3d image\")\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        cout << desc << \"\\n\";\n        return 1;\n    }\n\n    std::stringstream command_line_string;\n    std::cout << \"Command line options:\" << std::endl;\n    for (po::variables_map::iterator it = vm.begin(); it != vm.end(); ++it){\n        boost::any a = it->second.value();\n        command_line_string << it->first << \": \";\n        if (a.type() == typeid(std::string)) command_line_string << it->second.as<std::string>();\n        else if (a.type() == typeid(int)) command_line_string << it->second.as<int>();\n        else if (a.type() == typeid(unsigned int)) command_line_string << it->second.as<unsigned int>();\n        else if (a.type() == typeid(float)) command_line_string << it->second.as<float>();\n        else if (a.type() == typeid(vector_td<float,3>)) command_line_string << it->second.as<vector_td<float,3> >();\n        else if (a.type() == typeid(vector_td<float,2>)) command_line_string << it->second.as<vector_td<float,2> >();\n        else if (a.type() == typeid(vector_td<int,3>)) command_line_string << it->second.as<vector_td<int,3> >();\n        else if (a.type() == typeid(vector_td<unsigned int,3>)) command_line_string << it->second.as<vector_td<unsigned int,3> >();\n        else if (a.type() == typeid(bool)) command_line_string << it->second.as<bool>();\n        else command_line_string << \"Unknown type\" << std::endl;\n        command_line_string << std::endl;\n    }\n    std::cout << command_line_string.str();\n\n    cudaSetDevice(device);\n    cudaDeviceReset();\n\n    //Really weird stuff. Needed to initialize the device?? Should find real bug.\n    cudaDeviceManager::Instance()->lockHandle();\n    cudaDeviceManager::Instance()->unlockHandle();\n\n\n    boost::shared_ptr<CBCT_acquisition> ps(new CBCT_acquisition());\n    ps->load(acquisition_filename);\n    ps->get_geometry()->print(std::cout);\n\n\n    float SDD = ps->get_geometry()->get_SDD();\n    float SAD = ps->get_geometry()->get_SAD();\n\n    boost::shared_ptr<CBCT_binning> binning(new CBCT_binning());\n    if (vm.count(\"binning\")){\n        std::cout << \"Loading binning data\" << std::endl;\n        binning->load(vm[\"binning\"].as<string>());\n        if (vm.count(\"3D\"))\n            binning = binning->get_3d_binning();\n    } else binning->set_as_default_3d_bin(ps->get_projections()->get_size(2));\n    binning->print(std::cout);\n\n    floatd3 imageDimensions;\n    if (vm.count(\"dimensions\")){\n        imageDimensions = vm[\"dimensions\"].as<floatd3>();\n        voxelSize = imageDimensions/imageSize;\n    }\n    else imageDimensions = voxelSize*imageSize;\n\n    float lengthOfRay_in_mm = norm(imageDimensions);\n    unsigned int numSamplesPerPixel = 3;\n    float minSpacing = min(voxelSize)/numSamplesPerPixel;\n\n    unsigned int numSamplesPerRay;\n    if (vm.count(\"samples\")) numSamplesPerRay = vm[\"samples\"].as<unsigned int>();\n    else numSamplesPerRay = ceil( lengthOfRay_in_mm / minSpacing );\n\n    float step_size_in_mm = lengthOfRay_in_mm / numSamplesPerRay;\n    size_t numProjs = ps->get_projections()->get_size(2);\n    size_t needed_bytes = 2 * prod(imageSize) * sizeof(float);\n    std::vector<size_t> is_dims = to_std_vector((uint64d3)imageSize);\n\n    std::cout << \"IS dimensions \" << is_dims[0] << \" \" << is_dims[1] << \" \" << is_dims[2] << std::endl;\n    std::cout << \"Image size \" << imageDimensions << std::endl;\n    std::cout << \"FRAMELET WEIGHT \" << framelet_weight << std::endl;\n    is_dims.push_back(binning->get_number_of_bins());\n\n    //scatter_correct(binning,ps,ps->get_projections().get(),is_dims,imageDimensions);\n\n    if (scale_factor[0] != 1 || scale_factor[1] != 1)\n        ps->downsample(scale_factor[0],scale_factor[1]);\n\n\n    //osLALMSolver<cuNDArray<float>> solver;\n    osMOMSolverD<cuNDArray<float>> solver;\n    //osMOMSolverW<cuNDArray<float>> solver;\n    //osMOMSolverL1<cuNDArray<float>> solver;\n    //osAHZCSolver<cuNDArray<float>> solver;\n    //osMOMSolverF<cuNDArray<float>> solver;\n    //ADMMSolver<cuNDArray<float>> solver;\n    solver.set_dump(false);\n\n\n    boost::shared_ptr<cuNDArray<float>> prior;\n    if (vm.count(\"use_prior\") ) {\n        auto projections = *ps->get_projections();\n        prior = calculate_prior(binning,ps,projections,is_dims,imageDimensions);\n        solver.set_x0(expand(prior.get(),binning->get_number_of_bins()));\n        //prior = calculate_weightImage(binning,ps,projections,is_dims,imageDimensions);\n//        solver.set_x0(prior);\n    }\n    if (vm.count(\"prior\")){\n        prior = boost::make_shared<cuNDArray<float>>(*read_nd_array<float>(vm[\"prior\"].as<string>().c_str()));\n    }\n\n    solver.set_max_iterations(iterations);\n    solver.set_output_mode(osSPSSolver<cuNDArray<float>>::OUTPUT_VERBOSE);\n    solver.set_tau(tau);\n    solver.set_non_negativity_constraint(use_non_negativity);\n    solver.set_huber(huber);\n    solver.set_reg_steps(reg_iter);\n    //solver.set_rho(rho);\n\n\n    if (atv_weight > 0) {\n\n\n        auto ATV = boost::make_shared<cuATVPrimalDualOperator<float>>(0.0);\n        ATV->set_weight(atv_weight);\n        solver.add_regularization_operator(ATV);\n\n\n\n    }\n\n    if (sstv_weight > 0){\n        auto SSTV = boost::make_shared<cuSSTVPrimalDualOperator<float>>();\n        SSTV->set_weight(sstv_weight);\n        solver.add_regularization_operator(SSTV);\n    }\n\n    if (tv_weight > 0) {\n\n        //auto TV = boost::make_shared<cuWTVPrimalDualOperator<float>>(0.0,1e-3);\n//\n\n        auto TV = boost::make_shared<cuTVPrimalDualOperator<float>>(0.0);\n        TV->set_weight(tv_weight);\n\n        solver.add_regularization_operator(TV);\n\n\n/*\n      auto Dx = boost::make_shared<cuPartialDifferenceOperator<float, 3>>(0);\n      Dx->set_weight(tv_weight);\n      Dx->set_domain_dimensions(&is_dims);\n      Dx->set_codomain_dimensions(&is_dims);\n\n      auto Dy = boost::make_shared<cuPartialDifferenceOperator<float, 3>>(1);\n      Dy->set_weight(tv_weight);\n      Dy->set_domain_dimensions(&is_dims);\n      Dy->set_codomain_dimensions(&is_dims);\n\n\n      auto Dz = boost::make_shared<cuPartialDifferenceOperator<float, 3>>(2);\n      Dz->set_weight(tv_weight);\n      Dz->set_domain_dimensions(&is_dims);\n      Dz->set_codomain_dimensions(&is_dims);\n      solver.add_regularization_group({Dx, Dy, Dz});\n*/\n\n\n\n\n\n\n    }\n    if (tv_4d > 0) {\n\n        auto Dt = boost::make_shared<cuPartialDifferenceOperator<float, 4>>(3);\n        Dt->set_weight(tv_4d);\n        Dt->set_domain_dimensions(&is_dims);\n        Dt->set_codomain_dimensions(&is_dims);\n        solver.add_regularization_operator(Dt);\n/**/\n\n    }\n    if (atv_4d > 0) {\n\n        auto TVF =  boost::make_shared<cuTVTFFT>();\n        TVF->set_weight(atv_4d);\n        TVF->set_domain_dimensions(&is_dims);\n        solver.add_regularization_operator(TVF);\n\n\n\n\n\n\n\n\n\n\n/*\n\t\t  auto Dt = boost::make_shared<cuTV4DPrimalDualOperator<float>>(0);\n\t\t  Dt->set_weight(atv_4d);\n\t\t  solver.add_regularization_operator(Dt);\n*/\n\n    }\n\n    if (framelet_weight > 0){\n        auto stencils = std::vector<vector_td<float,3>>({\n                                                                vector_td<float,3>(-std::sqrt(2.0f),0,std::sqrt(2.0f)),vector_td<float,3>(-1,2,-1),vector_td<float,3>(1,2,1) });\n        std::cout << \"Framelet weight \" << framelet_weight << std::endl;\n        for (int step_size = 0; step_size < 3; step_size++) {\n            for (auto stencil : stencils) {\n                std::cout << \"Adding operators \" << std::endl;\n                auto Rx = boost::make_shared<cuSmallConvOperator<float, 4, 3>>(stencil, 0,std::pow(2,step_size));\n                Rx->set_weight(framelet_weight);\n                Rx->set_domain_dimensions(&is_dims);\n                Rx->set_codomain_dimensions(&is_dims);\n\n\n                auto Ry = boost::make_shared<cuSmallConvOperator<float, 4, 3>>(stencil, 1,std::pow(2,step_size));\n                Ry->set_weight(framelet_weight);\n                Ry->set_domain_dimensions(&is_dims);\n                Ry->set_codomain_dimensions(&is_dims);\n\n\n                auto Rz = boost::make_shared<cuSmallConvOperator<float, 4, 3>>(stencil, 2,std::pow(2,step_size));\n                Rz->set_weight(framelet_weight);\n                Rz->set_domain_dimensions(&is_dims);\n                Rz->set_codomain_dimensions(&is_dims);\n                solver.add_regularization_group({Rx, Ry, Rz});\n//                solver.add_regularization_operator(Rx);\n//                solver.add_regularization_operator(Ry);\n//                solver.add_regularization_operator(Rz);\n\n\n            }\n        }\n    }\n    if (framelet_weight4d > 0){\n        auto stencils = std::vector<vector_td<float,3>>({\n                                                                vector_td<float,3>(-std::sqrt(2.0f),0,std::sqrt(2.0f)),vector_td<float,3>(-1,2,-1),vector_td<float,3>(1,2,1) });\n        for (int step_size = 0; step_size < 3; step_size++) {\n            for (auto stencil : stencils) {\n                auto Rt = boost::make_shared<cuSmallConvOperator<float, 4, 3>>(stencil, 3,std::pow(2,step_size));\n                Rt->set_weight(framelet_weight4d);\n                Rt->set_domain_dimensions(&is_dims);\n                Rt->set_codomain_dimensions(&is_dims);\n                solver.add_regularization_operator(Rt);\n            }\n        }\n    }\n\n\n\n\n    if (dct_weight > 0){\n        auto dctOp = boost::make_shared<cuDCTOperator<float>>();\n//        auto dctOp = boost::make_shared<cuTFFT>();\n        dctOp->set_domain_dimensions(&is_dims);\n        dctOp->set_weight(dct_weight);\n        solver.add_regularization_operator(dctOp);\n    }\n\n    if (sfr_weight > 0){\n        auto sfrOp = boost::make_shared<cuTFFT>();\n        sfrOp->set_domain_dimensions(&is_dims);\n        sfrOp->set_weight(sfr_weight);\n        solver.add_regularization_operator(sfrOp);\n    }\n\n\n\n\n    if (bil_weight > 0){\n        auto bilOp = boost::make_shared<cuBilateralPriorPrimalDualOperator>(0.002,3.0,prior);\n        bilOp->set_weight(bil_weight);\n        solver.add_regularization_operator(bilOp);\n\n        /*\n        auto bilOp = boost::make_shared<BilateralPriorOperator>();\n        bilOp->set_domain_dimensions(&is_dims);\n        bilOp->set_codomain_dimensions(&is_dims);\n        bilOp->set_weight(bil_weight);\n        bilOp->set_sigma_spatial(3.0);\n        bilOp->set_sigma_int(0.01);\n\n        bilOp->set_prior(cuBilPrior);\n        solver.add_regularization_operator(bilOp,0.01);\n         */\n    }\n\n    if (pics_weight > 0){\n        auto pics = boost::make_shared<cuPICSPrimalDualOperator<float>>();\n        pics->set_weight(pics_weight);\n        pics->set_prior(prior);\n        solver.add_regularization_operator(pics);\n    }\n\n    boost::shared_ptr<CBSubsetOperator<cuNDArray>> E;\n    if ( vm.count(\"projection_weights\")) {\n        auto weights = read_nd_array<float>(vm[\"projection_weights\"].as<string>().c_str());\n        if (scale_factor[0] != 1 || scale_factor[1] != 1) {\n            cuNDArray<float> tmp_weights(*weights);\n            auto dims = *tmp_weights.get_dimensions();\n\n\n            tmp_weights = downsample_projections(&tmp_weights,scale_factor[0],scale_factor[1]);\n\n\n            weights = tmp_weights.to_host();\n        }\n\n        if (!ps->get_projections()->dimensions_equal(weights.get()))\n            throw std::runtime_error(\"Weight dimensions must match that of the projection data\");\n        auto EW  = boost::make_shared<CBSubsetWeightOperator<cuNDArray>>(subsets);\n        EW->setup(ps,binning,imageDimensions,weights);\n        E = EW;\n    } else {\n        std::cout <<\"Normal projections\" << std::endl;\n        E = boost::make_shared<CBSubsetOperator<cuNDArray> >(subsets);\n\n        E->setup(ps, binning, imageDimensions);\n    }\n    E->set_domain_dimensions(&is_dims);\n    E->set_codomain_dimensions(ps->get_projections()->get_dimensions().get());\n\n\n    solver.set_encoding_operator(E);\n\n\n\n    auto projections = boost::make_shared<cuNDArray<float>>(*ps->get_projections());\n    std::cout << \"Projection norm:\" << nrm2(projections.get()) << std::endl;\n\n\n\n\n\n    boost::shared_ptr<cuNDArray<float>> result;\n    {\n        GPUTimer tim(\"Solver\");\n        result = solver.solve(projections.get());\n    }\n//\tglobal_timer.reset();\n    std::cout << \"Penguin\" << nrm2(result.get()) << std::endl;\n\n    std::cout << \"Result sum \" << asum(result.get()) << std::endl;\n\n    //apply_mask(result.get(),mask.get());\n\n    std::cout << \"Result sum \" << asum(result.get()) << std::endl;\n    //saveNDArray2HDF5(result.get(),outputFile,imageDimensions,vector_td<float,3>(0),command_line_string.str(),iterations);\n\n    write_nd_array(result.get(),\"reconstruction.real\");\n\n\n    if (wavelet_weight > 0){\n        osMOMSolverF<cuNDArray<float>> solverF;\n        solverF.set_max_iterations(10);\n        solverF.set_x0(result);\n        solverF.set_encoding_operator(E);\n        solverF.set_non_negativity_constraint(true);\n\n        auto wave = boost::make_shared<cuEdgeATrousOperator<float>>();\n\n        wave->set_sigma(sigma);\n        wave->set_domain_dimensions(&is_dims);\n        if (binning->get_number_of_bins() == 1)\n            wave->set_levels({2,2,2});\n        else\n            wave->set_levels({2,2,2,2});\n        wave->set_weight(wavelet_weight);\n        solverF.add_regularization_operator(wave);\n\n        result = solverF.solve(projections.get());\n\n    }\n/*\n\tif (nlm_noise > 0){\n\n\t\tfloat* result_data = result->get_data_ptr();\n\n\n\t\tfor (int i = 0; i < result->get_size(3); i++){\n\t\t\tcuNDArray<float> result_view(prior->get_dimensions(),result_data);\n\n\t\t\tnonlocal_means_ref(&result_view,prior.get(),nlm_noise);\n\t\t\tresult_data += result_view.get_number_of_elements();\n\t\t}\n\t}\n*/\n    saveNDArray2HDF5(result.get(),outputFile,imageDimensions,floatd3(0,0,0),command_line_string.str(),iterations);\n//\twrite_nd_array(result.get(),\"reconstruction.real\");\n    //write_dicom(result.get(),command_line_string.str(),imageDimensions);\n\n\n\n}\n", "meta": {"hexsha": "40ed5db764bc4c977e0452498b02727fe6d4f451", "size": 21965, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "xray/cuCBOS_reconstruct.cpp", "max_stars_repo_name": "ahsanjav/gt-tomography", "max_stars_repo_head_hexsha": "1f53d72672ccda417bc8966d8497af6d786e8935", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2017-06-26T13:41:55.000Z", "max_stars_repo_stars_event_max_datetime": "2019-06-10T11:06:27.000Z", "max_issues_repo_path": "xray/cuCBOS_reconstruct.cpp", "max_issues_repo_name": "ahsanjav/gt-tomography", "max_issues_repo_head_hexsha": "1f53d72672ccda417bc8966d8497af6d786e8935", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "xray/cuCBOS_reconstruct.cpp", "max_forks_repo_name": "ahsanjav/gt-tomography", "max_forks_repo_head_hexsha": "1f53d72672ccda417bc8966d8497af6d786e8935", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-09-27T14:37:29.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-27T14:37:29.000Z", "avg_line_length": 37.8706896552, "max_line_length": 221, "alphanum_fraction": 0.6628727521, "num_tokens": 5706, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7634837527911056, "lm_q2_score": 0.41489884579676883, "lm_q1q2_score": 0.3167685278176153}}
{"text": "/****************************************************************\n *\n * Copyright (c) 2011\n * All rights reserved.\n *\n * Hochschule Bonn-Rhein-Sieg\n * University of Applied Sciences\n * Computer Science Department\n *\n * +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n *\n * Author:\n * Jan Paulus, Nico Hochgeschwender, Michael Reckhaus, Azamat Shakhimardanov\n * Supervised by:\n * Gerhard K. Kraetzschmar\n *\n * +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n *\n * This sofware is published under a dual-license: GNU Lesser General Public\n * License LGPL 2.1 and BSD license. The dual-license implies that users of this\n * code may choose which terms they prefer.\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\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 Hochschule Bonn-Rhein-Sieg 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 program is free software: you can redistribute it and/or modify\n * it under the terms of the GNU Lesser General Public License LGPL as\n * published by the Free Software Foundation, either version 2.1 of the\n * License, or (at your option) any later version or the BSD license.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU Lesser General Public License LGPL and the BSD license for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License LGPL and BSD license along with this program.\n *\n ****************************************************************/\n\n#ifndef YOUBOT_UNITS_HPP\n#define\tYOUBOT_UNITS_HPP\n#include <boost/units/io.hpp>\n#include <boost/units/pow.hpp>\n#include <boost/units/systems/si.hpp>\n#include <boost/units/systems/temperature/celsius.hpp>\n#include <boost/units/cmath.hpp>\n#include <boost/units/make_scaled_unit.hpp>\n#include <boost/units/systems/si/prefixes.hpp>\n\n\nusing namespace boost::units;\nusing namespace boost::units::si;\nusing namespace boost::units::angle;\n\n//typedef boost::units::si::length meter;\nusing boost::units::si::meters;\nnamespace youbot {\n\ntypedef boost::units::make_scaled_unit<si::length, boost::units::scale<10, boost::units::static_rational<-3> > >::type millimeter;\ntypedef boost::units::make_scaled_unit<si::length, boost::units::scale<10, boost::units::static_rational<-2> > >::type centimeter;\nBOOST_UNITS_STATIC_CONSTANT(centimeters, centimeter);\n\n\ntypedef boost::units::make_scaled_unit<si::time, boost::units::scale<10, boost::units::static_rational<-3> > >::type millisecond;\n//BOOST_UNITS_STATIC_CONSTANT(millimeters, millimeter);\n\n} // namespace youbot\n\n#endif\t/* YOUBOT_UNITS_HPP */\n\n", "meta": {"hexsha": "d28b8019155c30d279fc7a214b2f877b1d82d808", "size": 3370, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "youbot/youbot_driver/include/youbot_driver/generic/Units.hpp", "max_stars_repo_name": "MrJaeqx/ESA--WORK", "max_stars_repo_head_hexsha": "50d5b397f634db98e2627a764c7731e76a4b3feb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2018-03-09T13:44:29.000Z", "max_stars_repo_stars_event_max_datetime": "2019-12-18T16:17:03.000Z", "max_issues_repo_path": "youbot/youbot_driver/include/youbot_driver/generic/Units.hpp", "max_issues_repo_name": "MrJaeqx/ESA--WORK", "max_issues_repo_head_hexsha": "50d5b397f634db98e2627a764c7731e76a4b3feb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 32.0, "max_issues_repo_issues_event_min_datetime": "2017-11-19T16:26:41.000Z", "max_issues_repo_issues_event_max_datetime": "2018-01-19T12:36:10.000Z", "max_forks_repo_path": "youbot/youbot_driver/include/youbot_driver/generic/Units.hpp", "max_forks_repo_name": "FontysAtWork/ESA-PROJ", "max_forks_repo_head_hexsha": "50d5b397f634db98e2627a764c7731e76a4b3feb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2017-11-19T12:45:37.000Z", "max_forks_repo_forks_event_max_datetime": "2017-11-19T12:45:37.000Z", "avg_line_length": 40.6024096386, "max_line_length": 130, "alphanum_fraction": 0.6792284866, "num_tokens": 736, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.63341027751814, "lm_q2_score": 0.5, "lm_q1q2_score": 0.31670513875907}}
{"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/*!\\file NE....cpp\n  \\brief \\ref EMNE_MULTIBODY - C++ input file, Time-Stepping version - O.B.\n\n  A multibody example.\n  Direct description of the model.\n  Simulation with a Time-Stepping scheme.\n*/\n\n#include \"SiconosKernel.hpp\"\n#include \"KneeJointR.hpp\"\n#include \"PrismaticJointR.hpp\"\n#include <boost/math/quaternion.hpp>\nusing namespace std;\n\n/* Given a position of a point in the Inertial Frame and the configuration vector q of a solid\n * returns a position in the spatial frame.\n */\nvoid fromInertialToSpatialFrame(double *positionInInertialFrame, double *positionInSpatialFrame, SP::SiconosVector  q  )\n{\ndouble q0 = q->getValue(3);\ndouble q1 = q->getValue(4);\ndouble q2 = q->getValue(5);\ndouble q3 = q->getValue(6);\n\n::boost::math::quaternion<double>    quatQ(q0, q1, q2, q3);\n::boost::math::quaternion<double>    quatcQ(q0, -q1, -q2, -q3);\n::boost::math::quaternion<double>    quatpos(0, positionInInertialFrame[0], positionInInertialFrame[1], positionInInertialFrame[2]);\n::boost::math::quaternion<double>    quatBuff;\n\n//perform the rotation\nquatBuff = quatQ * quatpos * quatcQ;\n\npositionInSpatialFrame[0] = quatBuff.R_component_2()+q->getValue(0);\npositionInSpatialFrame[1] = quatBuff.R_component_3()+q->getValue(1);\npositionInSpatialFrame[2] = quatBuff.R_component_4()+q->getValue(2);\n\n}\nvoid tipTrajectories(SP::SiconosVector  q, double * traj, double length)\n{\n  double positionInInertialFrame[3];\n  double positionInSpatialFrame[3];\n  // Output the position of the tip of beam1\n  positionInInertialFrame[0]=length/2;\n  positionInInertialFrame[1]=0.0;\n  positionInInertialFrame[2]=0.0;\n\n  fromInertialToSpatialFrame(positionInInertialFrame, positionInSpatialFrame, q  );\n  traj[0] = positionInSpatialFrame[0];\n  traj[1] = positionInSpatialFrame[1];\n  traj[2] = positionInSpatialFrame[2];\n\n\n  // std::cout <<  \"positionInSpatialFrame[0]\" <<  positionInSpatialFrame[0]<<std::endl;\n  // std::cout <<  \"positionInSpatialFrame[1]\" <<  positionInSpatialFrame[1]<<std::endl;\n  // std::cout <<  \"positionInSpatialFrame[2]\" <<  positionInSpatialFrame[2]<<std::endl;\n\n  positionInInertialFrame[0]=-length/2;\n  fromInertialToSpatialFrame(positionInInertialFrame, positionInSpatialFrame, q  );\n  traj[3]= positionInSpatialFrame[0];\n  traj[4] = positionInSpatialFrame[1];\n  traj[5] = positionInSpatialFrame[2];\n}\n\n\n\n\n\nint main(int argc, char* argv[])\n{\n  try\n  {\n\n\n    // ================= Creation of the model =======================\n\n    // User-defined main parameters\n    unsigned int nDof = 3;\n    unsigned int qDim = 7;\n    unsigned int nDim = 6;\n    double t0 = 0;                   // initial computation time\n    double T = 10.0;                  // final computation time\n    double h = 0.01;                // time step\n    int N = 1000;\n    double L1 = 1.0;\n    double theta = 1.0;              // theta for MoreauJeanOSI integrator\n    double g = 9.81; // Gravity\n    double m = 1.;\n\n    // -------------------------\n    // --- Dynamical systems ---\n    // -------------------------\n\n    FILE * pFile;\n    pFile = fopen(\"data.h\", \"w\");\n    if (pFile == NULL)\n    {\n      printf(\"fopen exampleopen filed!\\n\");\n      fclose(pFile);\n    }\n\n\n    cout << \"====> Model loading ...\" << endl << endl;\n\n    // -- Initial positions and velocities --\n\n    //First DS\n    SP::SiconosVector q10(new SiconosVector(qDim));\n    SP::SiconosVector v10(new SiconosVector(nDim));\n    SP::SimpleMatrix I1(new SimpleMatrix(3, 3));\n    v10->zero();\n    I1->eye();\n    I1->setValue(0, 0, 0.1);\n    // Initial position of the center of gravity CG1\n    (*q10)(0) = 0.5 * L1 / sqrt(2.0);\n    (*q10)(1) = 0;\n    (*q10)(2) = -0.5 * L1 / sqrt(2.0);\n    // Initial orientation (a quaternion that gives the rotation w.r.t the spatial frame)\n    // angle of the rotation Pi/4\n    double angle = M_PI / 4;\n    SiconosVector V1(3);\n    V1.zero();\n    // vector of the rotation (Y-axis)\n    V1.setValue(0, 0);\n    V1.setValue(1, 1);\n    V1.setValue(2, 0);\n    // construction of the quaternion\n    q10->setValue(3, cos(angle / 2));\n    q10->setValue(4, V1.getValue(0)*sin(angle / 2));\n    q10->setValue(5, V1.getValue(1)*sin(angle / 2));\n    q10->setValue(6, V1.getValue(2)*sin(angle / 2));\n\n    // -- The dynamical system --\n    SP::NewtonEulerDS beam1(new NewtonEulerDS(q10, v10, m, I1));\n    // -- Set external forces (weight) --\n    SP::SiconosVector weight(new SiconosVector(nDof));\n    (*weight)(2) = -m * g;\n    beam1->setFExtPtr(weight);\n\n    // --------------------\n    // --- Interactions ---\n    // --------------------\n    SP::NonSmoothLaw nslaw1(new EqualityConditionNSL(KneeJointR::numberOfConstraints()));\n\n    SP::SiconosVector P(new SiconosVector(3));\n    P->zero();\n    // Building the first knee joint for beam1\n    // input  - the concerned DS : beam1\n    //        - a point in the spatial frame (absolute frame) where the knee is defined P\n    SP::NewtonEulerR relation1(new KneeJointR(beam1, P));\n\n    SP::Interaction inter1(new Interaction(KneeJointR::numberOfConstraints(), nslaw1, relation1));\n\n    // -------------\n    // --- Model ---\n    // -------------\n    SP::Model myModel(new Model(t0, T));\n    // add the dynamical system in the non smooth dynamical system\n    myModel->nonSmoothDynamicalSystem()->insertDynamicalSystem(beam1);\n    // link the interaction and the dynamical system\n    myModel->nonSmoothDynamicalSystem()->link(inter1, beam1);\n    // ------------------\n    // --- Simulation ---\n    // ------------------\n\n\n    // -- (1) OneStepIntegrators --\n    SP::MoreauJeanCombinedProjectionOSI OSI(new MoreauJeanCombinedProjectionOSI(theta));\n\n\n    // -- (2) Time discretisation --\n    SP::TimeDiscretisation t(new TimeDiscretisation(t0, h));\n\n    // -- (3) one step non smooth problem\n    SP::OneStepNSProblem osnspb(new MLCP());\n    SP::OneStepNSProblem osnspb_pos(new MLCPProjectOnConstraints(SICONOS_MLCP_ENUM));\n\n    // -- (4) Simulation setup with (1) (2) (3)\n\n\n    SP::TimeSteppingCombinedProjection s(new TimeSteppingCombinedProjection(t, OSI, osnspb, osnspb_pos));\n    s->setProjectionMaxIteration(1000);\n    s->setConstraintTolUnilateral(1e-08);\n\n\n    // =========================== End of model definition ===========================\n\n    // ================================= Computation =================================\n\n    // --- Simulation initialization ---\n\n    cout << \"====> Initialisation ...\" << endl << endl;\n    myModel->initialize(s);\n\n\n    // --- Get the values to be plotted ---\n    // -> saved in a matrix dataPlot\n    unsigned int outputSize = 15 + 7;\n    SimpleMatrix dataPlot(N, outputSize);\n    SimpleMatrix beam1Plot(2,3*N);\n\n    SP::SiconosVector q1 = beam1->q();\n    SP::SiconosVector y= inter1->y(0);\n    SP::SiconosVector ydot= inter1->y(1);\n\n\n    // --- Time loop ---\n    cout << \"====> Start computation ... \" << endl << endl;\n    // ==== Simulation loop - Writing without explicit event handling =====\n    int k = 0;\n    boost::progress_display show_progress(N);\n\n    boost::timer time;\n    time.restart();\n    SP::SiconosVector yAux(new SiconosVector(3));\n    yAux->setValue(0, 1);\n    SP::SimpleMatrix Jaux(new SimpleMatrix(3, 3));\n    Index dimIndex(2);\n    Index startIndex(4);\n    fprintf(pFile, \"double T[%d*%d]={\", N + 1, outputSize);\n    double beamTipTrajectories[6];\n\n    for (k = 0; k < N-1; k++)\n    {\n      // solve ...\n      //s->newtonSolve(1e-4, 50);\n\n      s->advanceToEvent();\n      // --- Get values to be plotted ---\n      dataPlot(k, 0) =  s->nextTime();\n\n      dataPlot(k, 1) = (*q1)(0);\n      dataPlot(k, 2) = (*q1)(1);\n      dataPlot(k, 3) = (*q1)(2);\n      dataPlot(k, 4) = (*q1)(3);\n      dataPlot(k, 5) = (*q1)(4);\n      dataPlot(k, 6) = (*q1)(5);\n      dataPlot(k, 7) = (*q1)(6);\n      dataPlot(k, 8) = y->norm2();\n      dataPlot(k, 9) = ydot->norm2();\n\n\n      tipTrajectories(q1,beamTipTrajectories,L1);\n      beam1Plot(0,3*k) = beamTipTrajectories[0];\n      beam1Plot(0,3*k+1) = beamTipTrajectories[1];\n      beam1Plot(0,3*k+2) = beamTipTrajectories[2];\n      beam1Plot(1,3*k) = beamTipTrajectories[3];\n      beam1Plot(1,3*k+1) = beamTipTrajectories[4];\n      beam1Plot(1,3*k+2) = beamTipTrajectories[5];\n\n\n      for (unsigned int jj = 0; jj < outputSize; jj++)\n      {\n        if ((k || jj))\n          fprintf(pFile, \",\");\n        fprintf(pFile, \"%f\", dataPlot(k, jj));\n      }\n      fprintf(pFile, \"\\n\");\n       s->nextStep();\n      //s->processEvents();\n      ++show_progress;\n    }\n    fprintf(pFile, \"};\");\n    cout << endl << \"End of computation - Number of iterations done: \" << k - 1 << endl;\n    cout << \"Computation Time \" << time.elapsed()  << endl;\n\n    // --- Output files ---\n    cout << \"====> Output file writing ...\" << endl;\n    dataPlot.resize(k, outputSize);\n    ioMatrix::write(\"NE_1DS_1Knee_MLCP_MoreauJeanCombinedProjection.dat\", \"ascii\", dataPlot, \"noDim\");\n    ioMatrix::write(\"NE_1DS_1Knee_MLCP_beam1.dat\", \"ascii\", beam1Plot, \"noDim\");\n\n    SimpleMatrix dataPlotRef(dataPlot);\n    dataPlotRef.zero();\n    ioMatrix::read(\"NE_1DS_1Knee_MLCP_MoreauJeanCombinedProjection.ref\", \"ascii\", dataPlotRef);\n    std::cout << \"Error w.r.t. reference file : \" << (dataPlot - dataPlotRef).normInf() << std::endl;\n\n\n    if ((dataPlot - dataPlotRef).normInf() > 1e-7)\n    {\n      //(dataPlot - dataPlotRef).display();\n      std::cout << \"Warning. The results is rather different from the reference file.\" << std::endl;\n      return 1;\n    }\n\n    fclose(pFile);\n  }\n\n  catch (SiconosException e)\n  {\n    cout << e.report() << endl;\n  }\n  catch (...)\n  {\n    cout << \"Exception caught in NE_...cpp\" << endl;\n  }\n\n}\n", "meta": {"hexsha": "1064756b72489c911b4a2a5b45c20761b5b2655f", "size": 10205, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/Mechanics/JointsTests/NE_1DS_1Knee_MLCP_MoreauJeanCombinedProjection.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": "examples/Mechanics/JointsTests/NE_1DS_1Knee_MLCP_MoreauJeanCombinedProjection.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": "examples/Mechanics/JointsTests/NE_1DS_1Knee_MLCP_MoreauJeanCombinedProjection.cpp", "max_forks_repo_name": "siconos/siconos-deb", "max_forks_repo_head_hexsha": "2739a23f23d797dbfecec79d409e914e13c45c67", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.2943037975, "max_line_length": 132, "alphanum_fraction": 0.6153846154, "num_tokens": 2987, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6334102775181399, "lm_q2_score": 0.5, "lm_q1q2_score": 0.31670513875906997}}
{"text": "\n#include <algorithm>\n#include <numeric>\n#include <iostream>\n#include <set>\n#include <queue>\n#include <utility>\n#include <unordered_map>\n#include <unordered_set>\n#include <limits>\n#include <cmath>\n#include <ctime>\n#include <cassert>\n\n#include <boost/random.hpp>\n#include <boost/functional/hash.hpp>\n\n#include \"Factor.h\"\n#include \"DisjointSet.h\"\n#include \"DisjointSetBT.h\"\n#include \"RandomSource.h\"\n#include \"VAcyclicDecomposition.h\"\n\nnamespace Grante {\n\nconst unsigned int VAcyclicDecomposition::sa_steps = 20;\nconst double VAcyclicDecomposition::sa_t0 = 5.0;\nconst double VAcyclicDecomposition::sa_tfinal = 0.1;\n\nVAcyclicDecomposition::VAcyclicDecomposition(const FactorGraph* fg)\n\t: fg(fg), fgu(fg) {\n}\n\ndouble VAcyclicDecomposition::ComputeDecompositionGreedy(\n\tconst std::vector<double>& factor_weights,\n\tstd::vector<bool>& factor_is_removed) {\n\treturn (ComputeDecomposition(factor_weights, factor_is_removed,\n\t\t1, 1.0e-6, 1.0e-6));\n}\n\ndouble VAcyclicDecomposition::ComputeDecompositionSA(\n\tconst std::vector<double>& factor_weights,\n\tstd::vector<bool>& factor_is_removed) {\n\treturn (ComputeDecomposition(factor_weights, factor_is_removed,\n\t\tsa_steps, sa_t0, sa_tfinal));\n}\n\n// Compute solution based on iterative set packing heuristic\ndouble VAcyclicDecomposition::ComputeDecompositionSP(\n\tconst std::vector<double>& factor_weights,\n\tstd::vector<bool>& factor_is_removed) {\n\t// Throughout the algorithm, we keep a partition of the factor graph\n\t// variables\n\tconst std::vector<Factor*>& factors = fg->Factors();\n\tDisjointSet wset(fg->Cardinalities().size());\n\tstd::set<unsigned int> E;\n\tfor (unsigned int iter = 1; true; ++iter) {\n\t\t// Go through all the factors of the model and decide whether they are\n\t\t// still active.  A factor is inactive if any of the following\n\t\t// conditions are met:\n\t\t//\n\t\t// 1. All its adjacent variables are already mapped to one component,\n\t\t// 2. There are two or more factors joining the same components.\n\t\t//    If we would allow these factors to be active, the components\n\t\t//    could be merged, violating v-acyclicity.\n\t\t//\n\t\t// If 1. and 2. are false, the factor is 'active'.\n\t\tstd::unordered_map<std::set<unsigned int>, unsigned int,\n\t\t\tboost::hash<std::set<unsigned int> > > EF;\n\t\tstd::vector<bool> factor_active(factors.size(), true);\n\t\tfor (unsigned int fi = 0; fi < factors.size(); ++fi) {\n\t\t\tconst Factor* fac = factors[fi];\n\t\t\tconst std::vector<unsigned int>& fac_vars = fac->Variables();\n\n\t\t\t// Build mapped edge set\n\t\t\tE.clear();\n\t\t\tfor (unsigned int fvi = 0; fvi < fac_vars.size(); ++fvi)\n\t\t\t\tE.insert(wset.FindSet(fac_vars[fvi]));\n\t\t\t// -> All mapped to one component?\n\t\t\tif (E.size() == 1) {\n\t\t\t\tfactor_active[fi] = false;\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\t// Check whether the same component link exist already -> delete\n\t\t\tstd::unordered_map<std::set<unsigned int>,\n\t\t\t\tunsigned int>::const_iterator efi = EF.find(E);\n\t\t\tif (efi != EF.end()) {\n\t\t\t\tfactor_active[fi] = false;\n\t\t\t\tfactor_active[efi->second] = false;\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\t// Is active, add to dupe checking list\n\t\t\tEF[E] = fi;\n\t\t}\n\n\t\t// Solve set packing problem\n\t\tstd::vector<std::unordered_set<unsigned int> > S;\n\t\tstd::vector<double> S_weights;\n\t\tstd::vector<unsigned int> S_fi;\n\t\tstd::vector<bool> S_is_selected;\n\t\tfor (std::unordered_map<std::set<unsigned int>,\n\t\t\tunsigned int>::const_iterator efi = EF.begin(); efi != EF.end();\n\t\t\t++efi) {\n\t\t\tif (factor_active[efi->second] == false)\n\t\t\t\tcontinue;\n\n#if 0\n\t\t\tstd::cout << \"VASP iter \" << iter << \", adding:\";\n\t\t\tfor (std::set<unsigned int>::const_iterator\n\t\t\t\tesi = efi->first.begin(); esi != efi->first.end(); ++esi)\n\t\t\t\tstd::cout << \" \" << *esi;\n\t\t\tstd::cout << std::endl;\n#endif\n\n\t\t\t// Add, negative cost to benefit\n\t\t\tS.push_back(std::unordered_set<unsigned int>(\n\t\t\t\tefi->first.begin(), efi->first.end()));\n\t\t\tS_weights.push_back(factor_weights[efi->second]);\n\t\t\tS_fi.push_back(efi->second);\n\t\t}\n\t\t// No further merging possible -> break\n\t\tif (S.empty())\n\t\t\tbreak;\n\t\tGrante::VAcyclicDecomposition::ComputeSetPacking(\n\t\t\tS, S_weights, S_is_selected, 5);\t// TODO: make 5 configurable\n\n\t\t// Perform merging\n\t\tunsigned int merged = 0;\n\t\tfor (unsigned int si = 0; si < S.size(); ++si) {\n\t\t\tif (S_is_selected[si] == false)\n\t\t\t\tcontinue;\n\n\t\t\tconst std::vector<unsigned int>& fac_vars =\n\t\t\t\tfactors[S_fi[si]]->Variables();\n\t\t\tassert(fac_vars.size() >= 2);\n\t\t\tfor (unsigned int fvi = 1; fvi < fac_vars.size(); ++fvi) {\n\t\t\t\twset.Link(wset.FindSet(fac_vars[0]),\n\t\t\t\t\twset.FindSet(fac_vars[fvi]));\n\t\t\t}\n\t\t\tmerged += 1;\n\t\t}\n\t\t// This can happen due to symmetry, where the Lagrangian relaxation\n\t\t// method fails to identify a solution\n\t\tif (merged == 0)\n\t\t\tbreak;\n\t}\n\n\t// Reconstruct final solution: every factor not mapped to one component is\n\t// removed.\n\tfactor_is_removed.resize(factors.size());\n\tstd::fill(factor_is_removed.begin(), factor_is_removed.end(), true);\n\tdouble obj = 0.0;\n\tfor (unsigned int fi = 0; fi < factors.size(); ++fi) {\n\t\tconst Factor* fac = factors[fi];\n\t\tconst std::vector<unsigned int>& fac_vars = fac->Variables();\n\n\t\t// Build mapped edge set\n\t\tE.clear();\n\t\tfor (unsigned int fvi = 0; fvi < fac_vars.size(); ++fvi)\n\t\t\tE.insert(wset.FindSet(fac_vars[fvi]));\n\n\t\t// All mapped to one component? -> factor is kept\n\t\tif (E.size() == 1) {\n\t\t\tfactor_is_removed[fi] = false;\n\t\t\tobj += factor_weights[fi];\n\t\t}\n\t}\n\treturn (obj);\n}\n\ndouble VAcyclicDecomposition::ComputeSetPacking(\n\tconst std::vector<std::unordered_set<unsigned int> >& S,\n\tconst std::vector<double>& S_weights,\n\tstd::vector<bool>& S_is_selected, unsigned int lr_max_iter) {\n\tassert(S.size() == S_weights.size());\n\n\t// Random number generation\n\tboost::mt19937 rgen(RandomSource::GetGlobalRandomSeed());\n\tboost::uniform_real<double> rdestu;\t// range [0,1]\n\tboost::variate_generator<boost::mt19937,\n\t\tboost::uniform_real<double> > randu(rgen, rdestu);\n\n\t// Fast vertex->edgeset map, VE[v]: list of set indices\n\tstd::unordered_map<unsigned int, std::set<unsigned int> > VE;\n\t// Lagrange multipliers for constraints: \\sum_{e, v \\in e} x(e) <= 1.\n\tstd::unordered_map<unsigned int, double> V_mu;\n\tstd::unordered_map<unsigned int, double> V_mu_subg;\n\tfor (unsigned int si = 0; si < S.size(); ++si) {\n\t\tfor (std::unordered_set<unsigned int>::const_iterator\n\t\t\tssi = S[si].begin(); ssi != S[si].end(); ++ssi) {\n\t\t\tVE[*ssi].insert(si);\n\n\t\t\t// Minimally random initialization to prevent symmetry problems:\n\t\t\t// if many costs have the same weight, and we initialize all\n\t\t\t// multipliers to zero, then we are at a dual degenerate ridge of\n\t\t\t// the cost function, where the subgradient is symmetric: we never\n\t\t\t// manage to break the symmetry, producing trivial solutions.\n\t\t\tV_mu[*ssi] = 1.0e-3*randu();\n\t\t\tV_mu_subg[*ssi] = 0.0;\n\t\t}\n\t}\n\n\t// Current, possibly infeasible solution\n\tstd::vector<bool> cur_lr_solution(S.size(), false);\n\tstd::vector<bool> cur_feas_solution(S.size(), false);\n\tdouble upper_bound = std::numeric_limits<double>::infinity();\n\tdouble lower_bound = -std::numeric_limits<double>::infinity();\n\n\t// Perform Lagrangian relaxation iterations\n\tfor (unsigned int lr_iter = 1; lr_iter < lr_max_iter; ++lr_iter) {\n\t\t// Solve for x_e\n\t\tdouble cur_obj = 0.0;\n\t\tdouble feas_obj = 0.0;\n\t\tfor (unsigned int si = 0; si < S.size(); ++si) {\n\t\t\tdouble si_obj = S_weights[si];\n\t\t\tfor (std::unordered_set<unsigned int>::const_iterator\n\t\t\t\tssi = S[si].begin(); ssi != S[si].end(); ++ssi) {\n\t\t\t\tsi_obj += V_mu[*ssi];\n\t\t\t}\n\t\t\tcur_lr_solution[si] = (si_obj > 0.0) ? true : false;\n\t\t\tcur_obj += cur_lr_solution[si] ? si_obj : 0.0;\n\n\t\t\tcur_feas_solution[si] = cur_lr_solution[si];\n\t\t\tfeas_obj += cur_feas_solution[si] ? S_weights[si] : 0.0;\n\t\t}\n\t\t// - \\sum_v \\mu_v\n\t\tfor (std::unordered_map<unsigned int, double>::const_iterator\n\t\t\tvmi = V_mu.begin(); vmi != V_mu.end(); ++vmi) {\n\t\t\tcur_obj -= vmi->second;\n\t\t}\n\n\t\t// cur_obj provides a global upper bound on the solution\n\t\tif (cur_obj < upper_bound)\n\t\t\tupper_bound = cur_obj;\n\n\t\t// Check feasibility.  If solution is infeasible, produce a primal\n\t\t// feasible solution\n\t\tdouble cslackness = 0.0;\n\t\tdouble feasible = true;\n\t\tdouble subg_norm = 0.0;\n\t\tfor (std::unordered_map<unsigned int, double>::iterator\n\t\t\tvmi = V_mu.begin(); vmi != V_mu.end(); ++vmi) {\n\t\t\tdouble mu_v_sd = -1.0;\n\t\t\tconst std::set<unsigned int>& eset = VE[vmi->first];\n\t\t\tfor (std::set<unsigned int>::const_iterator ei = eset.begin();\n\t\t\t\tei != eset.end(); ++ei) {\n\t\t\t\tmu_v_sd += cur_lr_solution[*ei] ? 1.0 : 0.0;\n\t\t\t}\n\t\t\tcslackness += vmi->second * mu_v_sd;\n\n\t\t\t// Constraint is violated, adjust multiplier\n\t\t\tif (mu_v_sd > 0.0) {\n\t\t\t\tfeasible = false;\n\n\t\t\t\t// Remove sets until feasible\n\t\t\t\tdouble infeas_m = mu_v_sd;\n\t\t\t\tfor (std::set<unsigned int>::const_iterator ei = eset.begin();\n\t\t\t\t\tei != eset.end(); ++ei) {\n\t\t\t\t\t// Sufficient number of edges removed? -> done\n\t\t\t\t\tif (infeas_m <= 1.0e-8)\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\tif (cur_lr_solution[*ei] == false)\n\t\t\t\t\t\tcontinue;\n\n\t\t\t\t\tinfeas_m -= 1.0;\n\n\t\t\t\t\t// Was the set removed already? -> nothing to do\n\t\t\t\t\tif (cur_feas_solution[*ei] == false)\n\t\t\t\t\t\tcontinue;\n\n\t\t\t\t\t// Remove edge\n\t\t\t\t\tcur_feas_solution[*ei] = false;\n\t\t\t\t\tfeas_obj -= S_weights[*ei];\n\t\t\t\t}\n\t\t\t\tassert(infeas_m <= 1.0e-8);\n\t\t\t}\n\n\t\t\t// Adjust Lagrange multiplier by projected gradient method\n\t\t\tsubg_norm += mu_v_sd * mu_v_sd;\n\t\t\tV_mu_subg[vmi->first] = mu_v_sd;\n\t\t}\n\n\t\t// Compute step size: Polyak\n\t\tdouble beta_m = 1.0;\n\t\tdouble beta = (1.0 + beta_m) /\n\t\t\t(beta_m + static_cast<double>(lr_iter));\n\t\tdouble alpha = 0.0;\n\t\tif (subg_norm >= 1.0e-8) {\n\t\t\talpha = (beta * (cur_obj - feas_obj)) / subg_norm;\n\t\t}\n\t\tfor (std::unordered_map<unsigned int, double>::iterator\n\t\t\tvmi = V_mu_subg.begin(); vmi != V_mu_subg.end(); ++vmi) {\n\t\t\t// TODO: use subg_norm for LR mult update\n\t\t\tV_mu[vmi->first] -= alpha * vmi->second;\n\t\t\tV_mu[vmi->first] = std::min(0.0, V_mu[vmi->first]);\n\t\t}\n\n\t\t// Update lower bound and solution\n\t\tif (feas_obj > lower_bound) {\n\t\t\tlower_bound = feas_obj;\n\t\t\tS_is_selected = cur_feas_solution;\n\t\t}\n#if 0\n\t\tstd::cout << \"set packing LR iter \" << lr_iter\n\t\t\t<< \", lb \" << lower_bound << \", ub \" << upper_bound\n\t\t\t<< \", |subg| \" << std::sqrt(subg_norm)\n\t\t\t<< std::endl;\n#endif\n\n\t\t// Sufficient optimality condition:\n\t\t// primal feasible and \\mu'v(y(\\mu)) = cslackness = 0.\n\t\tif (feasible && std::fabs(cslackness) <= 1.0e-8) {\n\t\t\tS_is_selected = cur_lr_solution;\n\t\t\treturn (cur_obj);\n\t\t}\n\t}\n\treturn (lower_bound);\n}\n\ndouble VAcyclicDecomposition::ComputeDecomposition(\n\tconst std::vector<double>& factor_weights,\n\tstd::vector<bool>& factor_is_removed,\n\tunsigned int csa_steps, double csa_t0, double csa_tfinal) {\n\tconst std::vector<Factor*>& factors = fg->Factors();\n\tassert(factor_weights.size() == factors.size());\n\n\t// Initialization: all factors removed\n\tstd::unordered_set<unsigned int> removed_factors(factors.size());\n\tfor (unsigned int fi = 0; fi < factors.size(); ++fi)\n\t\tremoved_factors.insert(fi);\n\n\t// Components\n\tstd::vector<unsigned int> node_to_comp;\n\tconst std::vector<unsigned int>& card = fg->Cardinalities();\n\tnode_to_comp.reserve(card.size());\n\tstd::vector<std::unordered_set<unsigned int> > comps(card.size());\n\tfor (unsigned int ni = 0; ni < card.size(); ++ni) {\n\t\tnode_to_comp[ni] = ni;\n\t\tcomps[ni].insert(ni);\n\t}\n\n\t// Objective: weights of all included factors (zero)\n\tdouble obj = 0.0;\n\n\t// Best solution so far\n\tstd::unordered_set<unsigned int>\n\t\tbest_removed_factors(removed_factors);\n\tdouble best_obj = obj;\n\n\t// Random number generators: factor index\n\tboost::mt19937 rgen(static_cast<const boost::uint32_t>(\n\t\treinterpret_cast<size_t>(fg) ^ std::time(0))+14);\n\tboost::uniform_int<unsigned int> rdestd(0,\n\t\tstatic_cast<boost::uint32_t>(factors.size()-1));\n\tboost::variate_generator<boost::mt19937,\n\t\tboost::uniform_int<unsigned int> > rand_fi(rgen, rdestd);\n\n\t// Random number generator: Metropolis chain\n\tboost::mt19937 rgen2(static_cast<const boost::uint32_t>(\n\t\treinterpret_cast<size_t>(fg) ^ std::time(0))+13);\n\tboost::uniform_real<double> rdestu;\t// range [0,1]\n\tboost::variate_generator<boost::mt19937,\n\t\tboost::uniform_real<double> > rand_m(rgen2, rdestu);\n\n\t// Calculate exponential multiplier alpha such that T(sa_steps)=Tfinal.\n\tdouble alpha = std::exp(std::log(csa_tfinal / csa_t0) /\n\t\tstatic_cast<double>(csa_steps));\n\tfor (unsigned int k = 1; k <= csa_steps; ++k) {\n\t\t// Exponential schedule\n\t\tdouble temperature = csa_t0 * std::pow(alpha, static_cast<double>(k));\n#if 0\n\t\tstd::cout << \"iter \" << k << \", temp \" << temperature\n\t\t\t<< \", best obj \" << best_obj << std::endl;\n#endif\n\n\t\t// One epoch\n\t\tfor (unsigned int fi_d = 0; fi_d < factors.size(); ++fi_d) {\n\t\t\tunsigned int fi = rand_fi();\n\t\t\t// Special case of one pass: linear\n\t\t\tif (csa_steps == 1)\n\t\t\t\tfi = fi_d;\n\n\t\t\tdouble delta_E = std::numeric_limits<double>::signaling_NaN();\n\t\t\tbool is_in_G = (removed_factors.count(fi) == 0);\n\t\t\tif (is_in_G) {\n\t\t\t\t// Factor is currently in G, can be removed.\n\t\t\t\tdelta_E = -factor_weights[fi];\n\t\t\t} else {\n\t\t\t\t// Factor is currently removed, check whether it can be added.\n\t\t\t\tif (IsComponentBridge(node_to_comp, comps, fi) == false)\n\t\t\t\t\tcontinue;\t// not possible, reject\n\n\t\t\t\tdelta_E = factor_weights[fi];\n\t\t\t}\n\t\t\t// Reject\n\t\t\tif (delta_E <= 0.0 && rand_m() >= std::exp(delta_E/temperature))\n\t\t\t\tcontinue;\n\n\t\t\t// Accept\n\t\t\tif (is_in_G) {\n\t\t\t\t// Split components adjacent to the factor\n\t\t\t\tSplitComponents(removed_factors, node_to_comp, comps, fi);\n\t\t\t} else {\n\t\t\t\t// Merge components adjacent to the factor\n\t\t\t\tMergeComponents(node_to_comp, comps, factors[fi]);\n\t\t\t\tremoved_factors.erase(fi);\t// its in the graph now\n\t\t\t}\n\t\t\tobj += delta_E;\n\n\t\t\t// Keep track of best solution\n\t\t\tif (obj > best_obj) {\n\t\t\t\tbest_obj = obj;\n\t\t\t\tbest_removed_factors = removed_factors;\n\t\t\t}\n\t\t}\n\t}\n\n\t// Return list of removed factors\n\tfactor_is_removed.resize(factors.size());\n\tstd::fill(factor_is_removed.begin(), factor_is_removed.end(), false);\n\tfor (std::unordered_set<unsigned int>::const_iterator\n\t\tri = best_removed_factors.begin(); ri != best_removed_factors.end();\n\t\t++ri) {\n\t\tfactor_is_removed[*ri] = true;\n\t}\n\treturn (best_obj);\n}\n\nbool VAcyclicDecomposition::IsComponentBridge(\n\tstd::vector<unsigned int>& node_to_comp,\n\tstd::vector<std::unordered_set<unsigned int> >& comps,\n\tunsigned int factor_index) const {\n\tconst Factor* fac = fg->Factors()[factor_index];\n\tconst std::vector<unsigned int>& fvars = fac->Variables();\n\n\t// 1. Collect adjacent factor sets for each component\n\tstd::vector<std::unordered_set<unsigned int> >\n\t\tcomp_facset(fvars.size());;\n\tfor (unsigned int fvi = 0; fvi < fvars.size(); ++fvi) {\n\t\tconst std::unordered_set<unsigned int>& cur_vars =\n\t\t\tcomps[node_to_comp[fvars[fvi]]];\n\t\tassert(cur_vars.empty() == false);\n\t\tfor (std::unordered_set<unsigned int>::const_iterator\n\t\t\tcvi = cur_vars.begin(); cvi != cur_vars.end(); ++cvi) {\n\t\t\tconst std::set<unsigned int>& cur_facset =\n\t\t\t\tfgu.AdjacentFactors(*cvi);\n\t\t\tcomp_facset[fvi].insert(cur_facset.begin(), cur_facset.end());\n\t\t}\n\t\t// Do not consider the factor of interest\n\t\tcomp_facset[fvi].erase(factor_index);\n\t}\n\n\t// 2. Find factors that would link the components\n\tfor (unsigned int c1 = 0; c1 < comp_facset.size(); ++c1) {\n\t\tconst std::unordered_set<unsigned int>& c1_fset = comp_facset[c1];\n\t\tfor (unsigned int c2 = c1 + 1; c2 < comp_facset.size(); ++c2) {\n\t\t\tfor (std::unordered_set<unsigned int>::const_iterator\n\t\t\t\tc2i = comp_facset[c2].begin(); c2i != comp_facset[c2].end();\n\t\t\t\t++c2i) {\n\t\t\t\t// Check whether another factor between the components exists.\n\t\t\t\t// If so, factor_index is no bridge.\n\t\t\t\tif (c1_fset.count(*c2i) > 0)\n\t\t\t\t\treturn (false);\n\t\t\t}\n\t\t}\n\t}\n\treturn (true);\n}\n\nvoid VAcyclicDecomposition::SplitComponents(\n\tstd::unordered_set<unsigned int>& removed_factors,\n\tstd::vector<unsigned int>& node_to_comp,\n\tstd::vector<std::unordered_set<unsigned int> >& comps,\n\tunsigned int fac_index) const {\n\t// Obtain variable indices (these are all in the same component)\n\tconst Factor* fac = fg->Factors()[fac_index];\n\tconst std::vector<unsigned int>& fvar = fac->Variables();\n\tfor (unsigned int fvi = 0; fvi < fvar.size(); ++fvi) {\n\t\tassert(node_to_comp[fvar[fvi]] == node_to_comp[fvar[0]]);\n\t}\n\n\t// Save joined component, remove factor from graph\n#if 0\n\tstd::unordered_map<unsigned int> comp_old;\n\tcomp_old.swap(comps[node_to_comp[fvar[0]]]);\n#endif\n\tcomps[node_to_comp[fvar[0]]].clear();\n\tremoved_factors.insert(fac_index);\n\n\t// Relabel tree rooted in factor-adjacent node to a new component\n\t// FIXME: this seems to be very slow\n\tfor (unsigned int fvi = 0; fvi < fvar.size(); ++fvi) {\n\t\tunsigned int vi = fvar[fvi];\t// var and component index\n\t\tstd::unordered_set<unsigned int>& comp_vi = comps[vi];\n\t\tassert(comp_vi.empty());\n\n\t\t// store (var_idx, came_from_factor_index) in queue\n\t\tstd::queue<std::pair<unsigned int, unsigned int> > var_q;\n\t\tvar_q.push(std::pair<unsigned int, unsigned int>(vi, fac_index));\n\n\t\t// Recurse on tree-structured partial component, relabeling in the\n\t\t// process\n\t\twhile (var_q.empty() == false) {\n\t\t\tconst std::pair<unsigned int, unsigned int>& cur = var_q.front();\n\n\t\t\t// Relabel this node\n\t\t\tcomp_vi.insert(cur.first);\n\t\t\tnode_to_comp[cur.first] = vi;\n\n\t\t\t// Insert adjacent nodes\n\t\t\tconst std::set<unsigned int>& cur_facset =\n\t\t\t\tfgu.AdjacentFactors(cur.first);\n\t\t\tfor (std::set<unsigned int>::const_iterator\n\t\t\t\tfi = cur_facset.begin(); fi != cur_facset.end(); ++fi) {\n\t\t\t\tif (*fi == cur.second)\n\t\t\t\t\tcontinue;\t// this is the factor we came from\n\n\t\t\t\t// If factor is removed, skip\n\t\t\t\tif (removed_factors.count(*fi) > 0)\n\t\t\t\t\tcontinue;\n\n\t\t\t\t// Factor is valid, add all its variables except this one\n\t\t\t\tconst Factor* cur_factor = fg->Factors()[*fi];\n\t\t\t\tconst std::vector<unsigned int>& cur_facvar =\n\t\t\t\t\tcur_factor->Variables();\n\t\t\t\tfor (std::vector<unsigned int>::const_iterator\n\t\t\t\t\tcfvi = cur_facvar.begin(); cfvi != cur_facvar.end();\n\t\t\t\t\t++cfvi) {\n\t\t\t\t\tif (*cfvi == cur.first)\n\t\t\t\t\t\tcontinue;\t// do not add ourselves again\n\n\t\t\t\t\t// Put variable into the queue\n\t\t\t\t\tvar_q.push(std::pair<unsigned int, unsigned int>(\n\t\t\t\t\t\t*cfvi, *fi));\n\t\t\t\t}\n\t\t\t}\n\t\t\tvar_q.pop();\n\t\t}\n\t}\n}\n\nvoid VAcyclicDecomposition::MergeComponents(\n\tstd::vector<unsigned int>& node_to_comp,\n\tstd::vector<std::unordered_set<unsigned int> >& comps,\n\tconst Factor* fac) const {\n\t// Obtain component indices (these are all be disjoint)\n\tconst std::vector<unsigned int>& fvar = fac->Variables();\n\tstd::vector<unsigned int> comp_indices(fvar.size());\n\tfor (unsigned int fvi = 0; fvi < fvar.size(); ++fvi)\n\t\tcomp_indices[fvi] = node_to_comp[fvar[fvi]];\n\n\t// Map them all to the first component\n\tunsigned int target = comp_indices[0];\n\tfor (unsigned int ci = 1; ci < comp_indices.size(); ++ci) {\n\t\t// 1. relabel all nodes to the new component\n\t\tfor (std::unordered_set<unsigned int>::const_iterator\n\t\t\tsi = comps[comp_indices[ci]].begin();\n\t\t\tsi != comps[comp_indices[ci]].end(); ++si) {\n\t\t\tnode_to_comp[*si] = target;\n\t\t}\n\t\t// 2. merge component sets\n\t\tcomps[target].insert(comps[comp_indices[ci]].begin(),\n\t\t\tcomps[comp_indices[ci]].end());\n\t\tcomps[comp_indices[ci]].clear();\n\t}\n}\n\ndouble VAcyclicDecomposition::ComputeDecompositionExact(\n\tconst std::vector<double>& factor_weights,\n\tstd::vector<bool>& factor_is_removed, double opt_eps) {\n\t// Call reverse search enumeration function\n\tReverseSearch rsearch(this, factor_weights, opt_eps);\n\tdouble obj = rsearch.Search(factor_is_removed);\n\n\treturn (obj);\n}\n\nVAcyclicDecomposition::ReverseSearch::ReverseSearch(VAcyclicDecomposition* vac,\n\tconst std::vector<double>& factor_weights, double opt_eps)\n\t: factor_count(vac->fg->Factors().size()), factor_weights(factor_weights),\n\t\tvac(vac), best_global(0.0),\n\t\tbest_factor_is_removed(vac->fg->Factors().size(), true),\n\t\topt_eps(opt_eps) {\n}\n\ndouble VAcyclicDecomposition::ReverseSearch::Search(\n\tstd::vector<bool>& factor_is_removed_out) {\n\tstd::list<unsigned int> factor_in;\t// start with empty set\n\tstd::list<unsigned int> factor_cand;\n\tstd::set<unsigned int> factor_out;\n\tfor (unsigned int fi = 0; fi < factor_count; ++fi) {\n\t\tfactor_cand.push_back(fi);\n\t\tfactor_out.insert(fi);\n\t}\n\n\texamined = 0;\n\tstd::cout << \"SEARCH BEGIN\" << std::endl;\n\tDisjointSetBT dset(factor_count);\n\tRecurse(0.0, dset, factor_in, factor_cand, factor_out);\n\tstd::cout << \"SEARCH END\" << std::endl << std::endl;\n\n\tfactor_is_removed_out = best_factor_is_removed;\n\n\treturn (best_global);\n}\n\n// This has polynomial delay at O(F log F + F N(F)), where the output\n// operation is a an enumeration of a vac structure.  So in effect if the\n// maximum factor scope size N(F) is small, the runtime is an almost linear\n// function in the number of factors of the graph.\nstd::set<unsigned int>::const_iterator\nVAcyclicDecomposition::ReverseSearch::Recurse(double obj, DisjointSetBT& dset,\n\tstd::list<unsigned int>& factor_in, std::list<unsigned int>& factor_cand,\n\tstd::set<unsigned int>& factor_out)\n{\n\texamined += 1;\n\tif (examined % 1000000 == 1) {\n\t\tstd::cout << \"Recurse(obj=\" << obj << \", factor_in (\" << factor_in.size()\n\t\t\t<< \"), factor_cand (\" << factor_cand.size() << \"), \"\n\t\t\t<< \"factor_out (\" << factor_out.size() << \"))\"\n\t\t\t<< \" best: \" << best_global << std::endl;\n\t}\n\n\t// 1. Determine whether this tree is still vac.\n\t// When we find that it is not vac, return.\n\t//\n\t// Complexity: O(F log log F)\n\n\t// We need to check all factors not in factor_in\n\tfor (std::set<unsigned int>::const_iterator foi = factor_out.begin();\n\t\tfoi != factor_out.end(); ++foi) {\n\t\tconst Factor* fac = vac->fg->Factors()[*foi];\n\t\tconst std::vector<unsigned int>& fvars = fac->Variables();\n\n\t\tfor (unsigned int fvi1 = 0; fvi1 < fvars.size(); ++fvi1) {\n\t\t\tunsigned int root1 = dset.Find(fvars[fvi1]);\n\t\t\tfor (unsigned int fvi2 = fvi1 + 1; fvi2 < fvars.size(); ++fvi2) {\n\t\t\t\tunsigned int root2 = dset.Find(fvars[fvi2]);\n#if 0\n\t\t\t\tstd::cout << \"   fi \" << *foi << \", \" << fvars[fvi1]\n\t\t\t\t\t<< \"--\" << fvars[fvi2] << \" map to roots \"\n\t\t\t\t\t<< root1 << \"--\" << root2 << std::endl;\n#endif\n\n\t\t\t\tif (root1 == root2) {\n#if 0\n\t\t\t\t\tstd::cout << \"   * not vac, returning\" << std::endl;\n#endif\n\t\t\t\t\treturn (foi);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// 2. Current set is vac, so update objective\n\t//\n\t// Complexity: O(1)\n\tif (obj > best_global) {\n\t\tbest_global = obj;\n\t\tbest_factor_is_removed.resize(factor_count);\n\t\tstd::fill(best_factor_is_removed.begin(),\n\t\t\tbest_factor_is_removed.end(), true);\n\t\tfor (std::list<unsigned int>::const_iterator fil = factor_in.begin();\n\t\t\tfil != factor_in.end(); ++fil) {\n\t\t\tbest_factor_is_removed[*fil] = false;\n\t\t}\n\t\tstd::cout << \"   found new best vac with obj \" << obj << std::endl;\n\t}\n\n\t// 3. Compute bound and if it turns out that we cannot beat the best\n\t// solution so far, stop recursion\n\t//\n\t// Complexity: O(F)\n\tdouble obj_upper_bound = obj;\n\tfor (std::list<unsigned int>::const_iterator fci = factor_cand.begin();\n\t\tfci != factor_cand.end(); ++fci) {\n\t\tobj_upper_bound += std::max(0.0, factor_weights[*fci]);\n\t}\n#if 0\n\tif (examined % 10000 == 1) {\n\t\tstd::cout << \"   upper bound at this node: \" << obj_upper_bound << std::endl;\n\t}\n#endif\n\n\tif (obj_upper_bound <= best_global + opt_eps)\n\t\treturn (factor_out.end());\t// cannot beat best global one\n\n\t// 4. For all remaining factors, add and recurse\n\t//\n\t// Complexity: O(F N(F) + F log F) + recursion\n\t//  i) Sort by weight\n\tfactor_cand.sort(\n\t\t[this](unsigned int v1, unsigned int v2) -> bool {\n\t\t\treturn (this->factor_weights[v1] > this->factor_weights[v2]);\n\t\t});\n\n\t// ii) Recurse for each, greedily\n\tstd::list<unsigned int>::iterator fii = factor_cand.begin();\n\twhile (fii != factor_cand.end()) {\n\t\t// Skip factors that would not contribute anything to the objective\n\t\tunsigned int fi = *fii;\n\t\tif (factor_weights[fi] <= 0.0) {\n\t\t\t++fii;\n\t\t\tcontinue;\n\t\t}\n\n\t\tconst Factor* fac = vac->fg->Factors()[fi];\n\t\tunsigned int union_count = AddFactor(dset, fac);\n\n\t\t// Prepare recursion\n\t\tfactor_in.push_back(fi);\t// more factor into retained factor set\n\t\tfactor_out.erase(fi);\n\n\t\t// Note that here we change the list factor_cand, so that we realize\n\t\t// the reverse search ordering and avoid enumerating duplicates\n\t\tfii = factor_cand.erase(fii);\t// erase factor from candidate list\n\t\tstd::list<unsigned int> remaining_cand(fii, factor_cand.end());\n\n\t\t// Recurse\n\t\tstd::set<unsigned int>::iterator conflict_iter =\n\t\t\tRecurse(obj + factor_weights[fi], dset, factor_in,\n\t\t\t\tremaining_cand, factor_out);\n\n\t\t// Handling discovered vac conflicts in the remaining candidate set\n\t\tif (conflict_iter != factor_out.end()) {\n\t\t\tunsigned int conflict_fi = *conflict_iter;\n\n#if 0\n\t\t\tif (std::find(factor_cand.begin(), factor_cand.end(), conflict_fi)\n\t\t\t\t!= factor_cand.end()) {\n\t\t\t\tstd::cout << \"   removed conflict\" << std::endl;\n\t\t\t}\n#endif\n\t\t\tfactor_cand.remove_if([conflict_fi](unsigned int k) -> bool {\n\t\t\t\treturn (conflict_fi == k);\n\t\t\t});\n\t\t\tfii = factor_cand.begin();\n\t\t}\n\n\t\tfactor_out.insert(fi);\n\t\tfactor_in.pop_back();\n\n\t\t// Undo\n\t\tfor (unsigned int uc = 0; uc < union_count; ++uc)\n\t\t\tdset.Deunion();\n\t}\n\treturn (factor_out.end());\n}\n\nunsigned int VAcyclicDecomposition::ReverseSearch::AddFactor(DisjointSetBT& dset,\n\tconst Factor* fac) {\n\tconst std::vector<unsigned int>& fvars = fac->Variables();\n\tunsigned int union_count = 0;\n\n\t// Union all variables in the factor scope N(F)\n\tunsigned int root = dset.Find(fvars[0]);\n\tfor (unsigned int fvi = 1; fvi < fvars.size(); ++fvi) {\n\t\tunsigned int root2 = dset.Find(fvars[fvi]);\n\t\tassert(root != root2);\n\t\troot = dset.Union(root, root2);\n\t\tunion_count += 1;\n\t}\n\n\treturn (union_count);\n}\n\n}\n\n", "meta": {"hexsha": "743eb3c858afd11c47b6649aec534031d7fd14fe", "size": 25242, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "grante/VAcyclicDecomposition.cpp", "max_stars_repo_name": "pantonante/grante-bazel", "max_stars_repo_head_hexsha": "e3f22ec111463a7ae0686494422ab09f86b4d39a", "max_stars_repo_licenses": ["DOC"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "grante/VAcyclicDecomposition.cpp", "max_issues_repo_name": "pantonante/grante-bazel", "max_issues_repo_head_hexsha": "e3f22ec111463a7ae0686494422ab09f86b4d39a", "max_issues_repo_licenses": ["DOC"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "grante/VAcyclicDecomposition.cpp", "max_forks_repo_name": "pantonante/grante-bazel", "max_forks_repo_head_hexsha": "e3f22ec111463a7ae0686494422ab09f86b4d39a", "max_forks_repo_licenses": ["DOC"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.6968911917, "max_line_length": 81, "alphanum_fraction": 0.67435227, "num_tokens": 7350, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6187804337438501, "lm_q2_score": 0.5117166047041654, "lm_q1q2_score": 0.3166402226127737}}
{"text": "/*\n * Copyright [2019] [Christopher Syben]\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 * Links the cone-beam projector layer from python to the actual kernel implementation. Implemented according to Tensorflow API.\n * Implementation partially adapted from CONRAD\n * PYRO-NN is developed as an Open Source project under the Apache License, Version 2.0.\n*/\n#include \"tensorflow/core/framework/op.h\"\n#include \"tensorflow/core/framework/op_kernel.h\"\n#include \"tensorflow/core/framework/shape_inference.h\"\n#include \"helper_headers/helper_geometry_cpu.h\"\n#include \"helper_headers/helper_eigen.h\"\n#include <Eigen/QR>\n#include <typeinfo>\nusing namespace tensorflow; // NOLINT(build/namespaces)\nusing shape_inference::ShapeHandle; \n\n#define CUDA_OPERATOR_KERNEL \"ConeProjection3D\"\nREGISTER_OP(CUDA_OPERATOR_KERNEL)\n    .Input(\"volume: float\")\n    .Attr(\"volume_shape: shape\")\n    .Attr(\"projection_shape: shape\")\n    .Attr(\"volume_origin : tensor\")\n    .Attr(\"volume_spacing : tensor\")\n    .Attr(\"projection_matrices : tensor\")\n    .Attr(\"hardware_interp : bool = false\")\n    .Attr(\"step_size: float = 1.0\")\n    .Attr(\"projection_multiplier : float\")\n    .Output(\"output: float\")\n    .SetShapeFn( []( ::tensorflow::shape_inference::InferenceContext* c )\n    {\n      TensorShapeProto sp;\n      ShapeHandle sh;\n      ShapeHandle batch;\n      ShapeHandle out;\n      auto status = c->GetAttr( \"projection_shape\", &sp );\n      status.Update( c->MakeShapeFromShapeProto( sp, &sh ) );\n      c->Subshape(c->input(0),0,1,&batch);\n      c->Concatenate(batch, sh, &out);\n      c->set_output( 0, out );\n      return status;\n    } )\n    .Doc(R\"doc(\nComputes the 3D cone forward projection of the input based on the given the trajectory\n\noutput: A Tensor.\n  output = A_cone * x\n)doc\");\n\nvoid Cone_Projection_Kernel_Launcher(const float *volume_ptr, float *out, const float *inv_AR_matrix, const float *src_points, const int number_of_projections,\n                                    const int volume_width, const int volume_height, const int volume_depth, \n                                    const float volume_spacing_x, const float volume_spacing_y, const float volume_spacing_z,\n                                    const int detector_width, const int detector_height, const float step_size);\n\nvoid Cone_Projection_Kernel_Tex_Interp_Launcher(const float *volume_ptr, float *out, const float *inv_AR_matrix, const float *src_points, const int number_of_projections,\n                                                const int volume_width, const int volume_height, const int volume_depth, \n                                                const float volume_spacing_x, const float volume_spacing_y, const float volume_spacing_z,\n                                                const int detector_width, const int detector_height, const float step_size);\n\nclass ConeProjection3DOp : public OpKernel\n{\n    TensorShape volume_shape;\n    int volume_width, volume_height, volume_depth;\n\n    TensorShape projection_shape;\n    int detector_size_x, detector_size_y, number_of_projections;\n\n    float volume_origin_x, volume_origin_y, volume_origin_z;\n\n    float volume_spacing_x, volume_spacing_y, volume_spacing_z;\n\n    float step_size;\n    bool hardware_interp;\n\n    float projection_multiplier;\n\n    Eigen::Tensor<float, 3, Eigen::RowMajor> projection_matrices;\n    //TensorShape projection_matrices_shape;\n\n    Eigen::Tensor<float, 3, Eigen::RowMajor> inv_AR_matrix;\n    Eigen::Tensor<float, 2, Eigen::RowMajor> src_points;\n\n    \n\n  public:\n\n    \n    explicit ConeProjection3DOp(OpKernelConstruction *context) : OpKernel(context)\n    {\n        //get volume shape from attributes\n        OP_REQUIRES_OK(context, context->GetAttr(\"volume_shape\", &volume_shape));\n        volume_depth = volume_shape.dim_size(0);\n        volume_height = volume_shape.dim_size(1);\n        volume_width = volume_shape.dim_size(2);\n        //get detector shape from attributes\n        OP_REQUIRES_OK(context, context->GetAttr(\"projection_shape\", &projection_shape));\n        number_of_projections = projection_shape.dim_size(0);\n        detector_size_y = projection_shape.dim_size(1);\n        detector_size_x = projection_shape.dim_size(2);\n        //get volume origin from attributes\n        Tensor volume_origin_tensor;\n        OP_REQUIRES_OK(context, context->GetAttr(\"volume_origin\", &volume_origin_tensor));\n        auto volume_origin_eigen = volume_origin_tensor.tensor<float, 1>();\n        volume_origin_z = volume_origin_eigen(0);\n        volume_origin_y = volume_origin_eigen(1);\n        volume_origin_x = volume_origin_eigen(2);\n\n        //get volume spacing from attributes\n        Tensor volume_spacing_tensor;\n        OP_REQUIRES_OK(context, context->GetAttr(\"volume_spacing\", &volume_spacing_tensor));\n        auto volume_spacing_eigen = volume_spacing_tensor.tensor<float, 1>();\n        volume_spacing_z = volume_spacing_eigen(0);\n        volume_spacing_y = volume_spacing_eigen(1);\n        volume_spacing_x = volume_spacing_eigen(2);\n\n        //get ray vectors from attributes\n        Tensor projection_matrices_tensor;\n        OP_REQUIRES_OK(context, context->GetAttr(\"projection_matrices\", &projection_matrices_tensor));\n        auto projection_matrices_eigen = projection_matrices_tensor.tensor<float, 3>();\n        // projection_matrices_shape = projection_matrices_tensor.shape();\n        //Init src_point and inv_ar_matrix tensors\n        //get stepsize\n        OP_REQUIRES_OK(context, context->GetAttr(\"step_size\", &step_size));\n\n        //get hardware interpolation flag\n        OP_REQUIRES_OK(context, context->GetAttr(\"hardware_interp\", &hardware_interp));\n\n        //Projectionmultiplier for backprojection as gradient\n        OP_REQUIRES_OK(context, context->GetAttr(\"projection_multiplier\", &projection_multiplier));\n\n        src_points = Eigen::Tensor<float, 2, Eigen::RowMajor>(number_of_projections,3);\n        inv_AR_matrix = Eigen::Tensor<float, 3, Eigen::RowMajor>(number_of_projections,3,3);\n        \n        /*********************************************************************************************************************************************************************\n         * \n         *  P = [M | -MC] \n         *  M = KR\n         * 1. Extract Source Position (C) from P using SVD to calc right null space\n         * 2. Calculate M^-1 and multiply with a 3x3 Matrix containing 1/voxel_spacing on the diagonal matrix\n         * 3. Put src_points and inv_ar_matrix into the CUDA Kernel, like Cone-Projector from Conrad\n         * \n         * WARNING: The following code is not created under memory and runtime performance point of view.\n         *          A better conversion from Tensorflow Tensor to Eigen::Tensor and Eigen::Matrizes are probably neccessary !!!!\n         * ********************************************************************************************************************************************************************/\n\n        Eigen::Matrix3f scaling_matrix(3,3);\n        scaling_matrix.setZero();\n        scaling_matrix(0,0) = 1.0/volume_spacing_x;\n        scaling_matrix(1,1) = 1.0/volume_spacing_y;\n        scaling_matrix(2,2) = 1.0/volume_spacing_z;\n        src_points.setZero();\n        inv_AR_matrix.setZero();\n\n        //for each projection\n        for (int n = 0; n < number_of_projections; n++)\n        {            \n            Eigen::Matrix<float,3,4,Eigen::RowMajor> proj_mat(3,4);\n            proj_mat << projection_matrices_eigen(n,0,0), projection_matrices_eigen(n,0,1), projection_matrices_eigen(n,0,2), projection_matrices_eigen(n,0,3),\n                        projection_matrices_eigen(n,1,0), projection_matrices_eigen(n,1,1), projection_matrices_eigen(n,1,2), projection_matrices_eigen(n,1,3),\n                        projection_matrices_eigen(n,2,0), projection_matrices_eigen(n,2,1) ,projection_matrices_eigen(n,2,2), projection_matrices_eigen(n,2,3); \n\n            auto c = (Geometry::getCameraCenter(proj_mat) * -1).eval();\n\n            src_points(n,0) = -((volume_origin_x * scaling_matrix(0,0)) + c(0) * scaling_matrix(0,0));\n            src_points(n,1) = -((volume_origin_y * scaling_matrix(1,1)) + c(1) * scaling_matrix(1,1));\n            src_points(n,2) = -((volume_origin_z * scaling_matrix(2,2)) + c(2) * scaling_matrix(2,2));\n\n            Eigen::Matrix<float,3,3, Eigen::RowMajor> inverted_scaled_result = (scaling_matrix * proj_mat.block<3,3>(0,0).inverse()).eval();\n\n            //TODO: dont copy element-wise use Eigen::Map to map eigen::matrix to eigen::tensor\n            for(int j = 0; j < inverted_scaled_result.cols();++j){\n                for(int i = 0; i < inverted_scaled_result.rows(); ++i){\n                    inv_AR_matrix(n,j,i) = inverted_scaled_result(j,i);\n                }\n            }           \n        }\n    }\n\n    /*\n    https://github.com/tensorflow/tensorflow/issues/5902\n    tensorflow::GPUBFCAllocator* allocator = new tensorflow::GPUBFCAllocator(0, sizeof(float) * height * width * 3);\n    tensorflow::Tensor input_tensor = tensorflow::Tensor(allocator, tensorflow::DataType::DT_FLOAT, tensorflow::TensorShape( { 1, height, width, 3 }));\n    <copy output data from program A into the GPU memory allocated by input_tensor using a GPU->GPU copy>\n\n\n    https://stackoverflow.com/questions/39797095/tensorflow-custom-allocator-and-accessing-data-from-tensor\n\n    */\n\n    void Compute(OpKernelContext *context) override\n    {\n        // Grab the input tensor        \n        const Tensor &input_tensor = context->input(0);        \n        auto input = input_tensor.flat<float>();        \n        // Create an output tensor\n        TensorShape out_shape = TensorShape(\n          {input_tensor.shape().dim_size(0), projection_shape.dim_size(0), projection_shape.dim_size(1), projection_shape.dim_size(2)});\n        Tensor *output_tensor = nullptr;\n\n        // Check Batch size. Batch > 1 is not supported currently.\n        OP_REQUIRES(context, input_tensor.shape().dim_size(0) == 1,\n                errors::InvalidArgument(\"Batch dimension is mandatory ! Batch size > 1 is not supported in the current PYRO-NN-layers.\"));\n\n        OP_REQUIRES_OK(context, context->allocate_output(0, out_shape,\n                                                         &output_tensor));\n        \n        auto output = output_tensor->template flat<float>();\n\n        if(hardware_interp){\n            Cone_Projection_Kernel_Tex_Interp_Launcher(input.data(), output.data(), inv_AR_matrix.data(), src_points.data(), number_of_projections,\n                                        volume_width, volume_height, volume_depth, volume_spacing_x, volume_spacing_y, volume_spacing_z,\n                                        detector_size_x, detector_size_y, step_size);\n        }\n        else{\n            //TODO:\n            // allocate inv_ar_matrix, src_points with tensorflow context as temp memory.\n            // Call the cuda kernel launcher\n            Cone_Projection_Kernel_Launcher(input.data(), output.data(), inv_AR_matrix.data(), src_points.data(), number_of_projections,\n                                        volume_width, volume_height, volume_depth, volume_spacing_x, volume_spacing_y, volume_spacing_z,\n                                        detector_size_x, detector_size_y,step_size);\n        }\n    }\n};\n\nREGISTER_KERNEL_BUILDER(Name(CUDA_OPERATOR_KERNEL).Device(DEVICE_GPU), ConeProjection3DOp);\n", "meta": {"hexsha": "7c8b20612501a86d294ea7ff3e86674f783d8ba0", "size": 11886, "ext": "cc", "lang": "C++", "max_stars_repo_path": "cone_projector_3D_OPKernel.cc", "max_stars_repo_name": "theHamsta/PYRO-NN-Layers", "max_stars_repo_head_hexsha": "c776c3d7315f483937a7cebf667c6d491ecd57e6", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-05-25T07:19:54.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-25T07:19:54.000Z", "max_issues_repo_path": "cone_projector_3D_OPKernel.cc", "max_issues_repo_name": "theHamsta/PYRO-NN-Layers", "max_issues_repo_head_hexsha": "c776c3d7315f483937a7cebf667c6d491ecd57e6", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cone_projector_3D_OPKernel.cc", "max_forks_repo_name": "theHamsta/PYRO-NN-Layers", "max_forks_repo_head_hexsha": "c776c3d7315f483937a7cebf667c6d491ecd57e6", "max_forks_repo_licenses": ["Apache-2.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.9411764706, "max_line_length": 176, "alphanum_fraction": 0.6528689214, "num_tokens": 2604, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6926419831347362, "lm_q2_score": 0.4571367168274948, "lm_q1q2_score": 0.31663208210709837}}
{"text": "#include <iostream>\n#include <opencv2/core/core.hpp>\n#include <opencv2/features2d/features2d.hpp>\n#include <opencv2/highgui/highgui.hpp>\n#include <opencv2/calib3d/calib3d.hpp>\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n#include \"g2o/core/base_vertex.h\"\n#include \"g2o/core/base_binary_edge.h\"\n#include \"g2o/core/base_unary_edge.h\"\n#include <g2o/core/base_vertex.h>\n#include <g2o/core/base_unary_edge.h>\n#include <g2o/core/block_solver.h>\n#include <g2o/core/optimization_algorithm_levenberg.h>\n#include <g2o/solvers/csparse/linear_solver_csparse.h>\n#include <g2o/types/sba/types_six_dof_expmap.h>\n#include <chrono>\n#include <g2o/core/sparse_optimizer.h>\n#include <g2o/core/solver.h>\n#include <g2o/core/optimization_algorithm_gauss_newton.h>\n#include <g2o/solvers/dense/linear_solver_dense.h>\n#include<pybind11/pybind11.h>\n#include<pybind11/numpy.h>\n\nnamespace py = pybind11;\n\nusing namespace std;\nusing namespace cv;\nusing namespace g2o;\n\nclass EdgeProjection : public g2o::BaseBinaryEdge<2, Vector2D, VertexSBAPointXYZ, VertexSE3Expmap> {\npublic:\n  EIGEN_MAKE_ALIGNED_OPERATOR_NEW;\n\n  EdgeProjection(const Eigen::Matrix<double, 4, 4> &K,const Eigen::Matrix<double, 4, 9> &Cor,const int index ) : _K(K),_Cor(Cor),_index(index) {}\n\n  virtual void computeError() override {\n    // P3d----vertex0,T----vertex1\n    const VertexSBAPointXYZ *v0 = static_cast<const VertexSBAPointXYZ *> (_vertices[0]);\n    const VertexSE3Expmap* v1 = static_cast<const VertexSE3Expmap*>(_vertices[1]);\n    Eigen::Vector3d Di(v0->estimate());\n    Eigen::Vector4d Di_linear ;\n    Di_linear << Di(0),Di(1),Di(2),1.0;\n    Eigen::Matrix4d diagDi(Di_linear.asDiagonal());\n    // Eigen::Matrix<double, 4, 4> T;\n    g2o::SE3Quat T_quat=v1->estimate();\n    g2o::Matrix4D T= T_quat.to_homogeneous_matrix();\n    Eigen::Matrix<double, 4, 9> pos_pixel = _K  * T *diagDi * _Cor;\n    Eigen::Matrix<double, 2, 1> optimize;\n    pos_pixel.row(0) = pos_pixel.row(0).cwiseQuotient(pos_pixel.row(2));\n    pos_pixel.row(1) = pos_pixel.row(1).cwiseQuotient(pos_pixel.row(2));\n    // cout << \"_measurement\"<< endl<<_measurement<< endl;\n    optimize << pos_pixel(0,_index),pos_pixel(1,_index);\n    // cout << \"optimize\"<< endl<<optimize<< endl;\n    Vector2D obs(_measurement);\n    _error = obs- optimize;\n    // cout << \"_error\"<< endl<<_error<< endl;\n  }\n  // virtual void linearizeOplus(){};\n  virtual void linearizeOplus() override  {\n    VertexSE3Expmap * vj = static_cast<VertexSE3Expmap *>(_vertices[1]);\n    SE3Quat T(vj->estimate());\n    // vi是维度向量Di\n    VertexSBAPointXYZ* vi = static_cast<VertexSBAPointXYZ*>(_vertices[0]);\n    Eigen::Vector3d Di = vi->estimate();\n    // 把维度转化成车辆的角点\n    Eigen::Vector3d xyz (Di(0,0)*_Cor(0,_index),Di(1,0)*_Cor(1,_index),Di(2,0)*_Cor(2,_index));\n    Eigen::Vector3d xyz_trans = T.map(xyz);\n    double x = xyz_trans[0];\n    double y = xyz_trans[1];\n    double z = xyz_trans[2];\n    double z_2 = z*z;\n\n    Eigen::Matrix<double,2,3,Eigen::ColMajor> tmp;\n    tmp(0,0) = _K(0,0);\n    tmp(0,1) = 0;\n    tmp(0,2) = -x/z*_K(0,0);\n\n    tmp(1,0) = 0;\n    tmp(1,1) = _K(0,0);\n    tmp(1,2) = -y/z*_K(0,0);\n    // e_cp对维度求导\n    for(int vertex=0;vertex<9;vertex++){\n      Eigen::Vector3d corner_col((_Cor.col(vertex)).topRows(3));\n      Eigen::Matrix3d diagCor_col(corner_col.asDiagonal());\n      _jacobianOplusXi +=  -1./z * tmp * T.rotation().toRotationMatrix() * diagCor_col;  \n    }\n    _jacobianOplusXi = _jacobianOplusXi / 9;\n    // e_cp对位姿李代数求导\n    _jacobianOplusXj(0,0) =  x*y/z_2 *_K(0,0);\n    _jacobianOplusXj(0,1) = -(1+(x*x/z_2)) *_K(0,0);\n    _jacobianOplusXj(0,2) = y/z *_K(0,0);\n    _jacobianOplusXj(0,3) = -1./z *_K(0,0);\n    _jacobianOplusXj(0,4) = 0;\n    _jacobianOplusXj(0,5) = x/z_2 *_K(0,0);\n\n    _jacobianOplusXj(1,0) = (1+y*y/z_2) *_K(0,0);\n    _jacobianOplusXj(1,1) = -x*y/z_2 *_K(0,0);\n    _jacobianOplusXj(1,2) = -x/z *_K(0,0);\n    _jacobianOplusXj(1,3) = 0;\n    _jacobianOplusXj(1,4) = -1./z *_K(0,0);\n    _jacobianOplusXj(1,5) = y/z_2 *_K(0,0);\n}\n  virtual bool read(istream &in) {}\n\n  virtual bool write(ostream &out) const {}\n\nprivate:\n\n  Eigen::Matrix<double, 4, 9> _Cor;\n  Eigen::Matrix<double, 4, 4> _K;\n  int _index;\n};\n\n/**\n    input1:[w h l ry3d cx3d cy3d cz]\n    input2:[x0,y0,x1,y1,...]\n    input3:[f,cx,cy]  \n*/\npy::array_t<double> optimize(py::array_t<double>& input1, py::array_t<double>& input2,py::array_t<double>& input3,\n                             py::array_t<double>& score,py::array_t<double>& hm_score) {\n    // 获取input的信息\n    py::buffer_info buf1 = input1.request();\n    py::buffer_info buf2 = input2.request();\n    py::buffer_info buf3 = input3.request();\n    py::buffer_info buf_score = score.request();\n    py::buffer_info buf_hm_score = hm_score.request();\n    if (buf1.ndim !=1 || buf2.ndim !=1 || buf3.ndim !=1 || buf_score.ndim !=1 || buf_hm_score.ndim !=1 ){\n        throw std::runtime_error(\"Number of dimensions must be one\");\n    }\n    if (buf1.size !=7){\n        throw std::runtime_error(\"Input 3d bbox must match the format [w h l ry3d cx3d cy3d cz]\");\n    }\n    if (buf2.size !=18){\n        throw std::runtime_error(\"Input keypoints must match the format [x0,y0,x1,y1,...]\");\n    }\n    if (buf3.size !=3){\n        throw std::runtime_error(\"Input camera intrinsics must match the format [f,cx,cy]\");\n    }\n    if (buf_score.size !=1){\n        throw std::runtime_error(\"Input 2D bbox center score\");\n    }\n    if (buf_hm_score.size !=9){\n        throw std::runtime_error(\"Input 9 keypoints score\");\n    }\n    //获取numpy.ndarray 数据指针\n    double* ptr1 = (double*)buf1.ptr;\n    double* ptr2 = (double*)buf2.ptr;\n    double* ptr3 = (double*)buf3.ptr;\n    double* ptr_score = (double*)buf_score.ptr;\n    double* ptr_hm_score = (double*)buf_hm_score.ptr;\n    double w_3d = ptr1[0], h_3d = ptr1[1], l_3d = ptr1[2]; \n    double ry3d = ptr1[3];\n    double cx_3d = ptr1[4], cy_3d = ptr1[5], c_z = ptr1[6];\n    Eigen::Matrix<double, 4, 9> Cor;//l,h,w\n    Cor<< 1./2, 1./2, -1./2, -1./2, 1./2, 1./2, -1./2, -1./2, 0,\n        0,0,0,0,-1,-1,-1,-1,-1./2,\n        1./2, -1./2, -1./2, 1./2, 1./2, -1./2, -1./2, 1./2, 0,\n        1,1,1,1,1,1,1,1,1;\n    cout<<\"优化前:\"<<endl;\n    cout << \"角度 = \" << ry3d << endl;\n    cout<<\"3D bbox中心点坐标：\\t cx:\"<< cx_3d << \"\\t cy:\" <<\n    cy_3d<< \"\\t cz:\"  << c_z  <<endl;\n    cout<<\"3D bbox长宽高lhw : \\t L: \"<< l_3d<<\"\\t H: \"<<h_3d<<\"\\t W: \"<<w_3d<<endl;\n    Eigen::Matrix<double, 18, 1> keypoints_2d;\n    keypoints_2d.fill(0);\n    for(int i=0;i<18;i++){\n        keypoints_2d[i] = ptr2[i]; \n    }\n    \n\n    // 初始化g2o\n    typedef g2o::BlockSolver< g2o::BlockSolverTraits<6,3> > Block;  // pose 维度为 6, landmark 维度为 3\n\n    //Block::LinearSolverType* linearSolver = new g2o::LinearSolverCSparse<Block::PoseMatrixType>(); // 线性方程求解器\n    std::unique_ptr<Block::LinearSolverType> linearSolver ( new g2o::LinearSolverCSparse<Block::PoseMatrixType>());\n\n    //Block* solver_ptr = new Block ( linearSolver );\n    //std::unique_ptr<Block> solver_ptr ( new Block ( linearSolver));\n    std::unique_ptr<Block> solver_ptr ( new Block ( std::move(linearSolver)));     // 矩阵块求解器\n\n    //g2o::OptimizationAlgorithmLevenberg* solver = new g2o::OptimizationAlgorithmLevenberg ( solver_ptr);\n    g2o::OptimizationAlgorithmLevenberg* solver = new g2o::OptimizationAlgorithmLevenberg ( std::move(solver_ptr));\n\n    g2o::SparseOptimizer optimizer;\n\n    optimizer.setAlgorithm ( solver );\n    \n    // pose对应转移矩阵\n    g2o::VertexSE3Expmap* pose = new g2o::VertexSE3Expmap(); // camera pose\n    // 用theta对应的旋转矩阵初始化R_mat,c3d初始化平移向量t\n    Eigen::Matrix3d R_mat;\n    Eigen::Vector3d t_3d;\n    // 内参矩阵\n    Eigen::Matrix4d K_Mat ;\n    K_Mat << ptr3[0], 0,         ptr3[1],  0,\n            0,        ptr3[0],   ptr3[2],  0,\n            0,        0,         1.0,      0,\n            0,        0,         0,        1.0;\n    R_mat<< +cos(ry3d), 0, +sin(ry3d),\n            0, 1, 0,\n            -sin(ry3d), 0, cos(ry3d);\n    t_3d<< cx_3d, cy_3d, c_z;\n    // 把转移矩阵添加至图顶点\n    pose->setId ( 0 );\n    pose->setEstimate ( g2o::SE3Quat (\n                            R_mat,\n                            t_3d\n                        ));\n    optimizer.addVertex ( pose );\n\n    // 把Di当成第二个顶点\n    g2o::VertexSBAPointXYZ* point = new g2o::VertexSBAPointXYZ();\n    point->setId ( 1 );\n    point->setEstimate ( Eigen::Vector3d (l_3d,h_3d,w_3d));\n    point->setMarginalized ( true ); \n    optimizer.addVertex ( point );\n\n    // parameter: camera intrinsics\n    g2o::CameraParameters* camera = new g2o::CameraParameters (\n        ptr3[0], Eigen::Vector2d (ptr3[1], ptr3[2] ), 0\n    );\n    camera->setId ( 0 );\n    optimizer.addParameter ( camera );\n\n    // edges\n    int index = 1;\n    for(int i=0;i<9;i++){\n        EdgeProjection *edge = new EdgeProjection(K_Mat,Cor,i);\n        edge->setId ( index );\n        edge->setVertex ( 0, dynamic_cast<g2o::VertexSBAPointXYZ*> ( optimizer.vertex ( 1 ) ) );\n        edge->setVertex ( 1, pose );\n        edge->setMeasurement ( Eigen::Vector2d (keypoints_2d(i),keypoints_2d(i+9)));\n        edge->setParameterId ( 0,0 );\n        Eigen::Vector2d confidence(ptr_hm_score[i],ptr_score[0]);\n        Eigen::Matrix2d conviance_matrix(confidence.asDiagonal());\n        edge->setInformation ( conviance_matrix );\n        optimizer.addEdge ( edge ); \n        index++;\n    }\n\n    chrono::steady_clock::time_point t1 = chrono::steady_clock::now();\n    optimizer.setVerbose ( true );\n    optimizer.initializeOptimization();\n    optimizer.optimize ( 100 );\n    chrono::steady_clock::time_point t2 = chrono::steady_clock::now();\n    chrono::duration<double> time_used = chrono::duration_cast<chrono::duration<double>> ( t2-t1 );\n    cout<<\"优化过程耗时: \"<<time_used.count() <<\" 秒.\"<<endl;\n    cout<<\"优化后:\"<<endl;\n    Eigen::Isometry3d T( pose->estimate() );\n    Eigen::Vector3d euler_angles =pose->estimate().rotation().toRotationMatrix().eulerAngles( 0, 1, 2 );\n    cout << \"角度 = \" << euler_angles(1) << endl;\n    cout<<\"3D bbox中心点坐标：\\t cx:\"<< T.matrix()(0,3) << \"\\t cy:\" <<\n    T.matrix()(1,3)<< \"\\t cz:\"  <<T.matrix()(2,3)  <<endl;\n    cout<<\"3D bbox长宽高lhw: \\t L: \"<< point->estimate()(0)<<\"\\t H: \"<<point->estimate()(1)<<\"\\tW: \"<<point->estimate()(2)<<endl;\n    \n    auto result = py::array_t<double>(7);\n    py::buffer_info buf4 = result.request();\n    double* ptr4 = (double*)buf4.ptr;\n    ptr4[0] = point->estimate()(2);//w\n    ptr4[1] = point->estimate()(1);//h\n    ptr4[2] = point->estimate()(0);//l\n    ptr4[3] = euler_angles(1);     //ry3d\n    ptr4[4] = T.matrix()(0,3);     //cx\n    ptr4[5] = T.matrix()(1,3);     //cy\n    ptr4[6] = T.matrix()(2,3);     //cz\n    \n    return result;\n}\n\nPYBIND11_MODULE(energy, m) {\n\n    m.doc() = \"optimize using numpy and g2o!\";\n\n    m.def(\"optimize\", &optimize);\n}", "meta": {"hexsha": "ea9956fbd7511c628ced11db515cec915d17797a", "size": 10630, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/lib/utils/energy.cpp", "max_stars_repo_name": "kaixinbear/rtm", "max_stars_repo_head_hexsha": "f8ac9a48bd18b069681ec086323416ef3f69bad1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2020-03-20T10:16:06.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-04T05:39:58.000Z", "max_issues_repo_path": "src/lib/utils/.ipynb_checkpoints/energy-checkpoint.cpp", "max_issues_repo_name": "kaixinbear/rtm", "max_issues_repo_head_hexsha": "f8ac9a48bd18b069681ec086323416ef3f69bad1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2020-03-27T14:58:30.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-26T13:02:47.000Z", "max_forks_repo_path": "src/lib/utils/energy.cpp", "max_forks_repo_name": "kaixinbear/rtm", "max_forks_repo_head_hexsha": "f8ac9a48bd18b069681ec086323416ef3f69bad1", "max_forks_repo_licenses": ["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.5144927536, "max_line_length": 145, "alphanum_fraction": 0.6170272813, "num_tokens": 3735, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7772998508568417, "lm_q2_score": 0.40733340004593027, "lm_q1q2_score": 0.31662019110471185}}
{"text": "//---------------------------------------------------------------------------//\n// Copyright (c) 2018-2021 Mikhail Komarov <nemo@nil.foundation>\n// Copyright (c) 2021 Ilias Khairullin <ilias@nil.foundation>\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//    http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//---------------------------------------------------------------------------//\n\n#include <iostream>\n#include <filesystem>\n#include <fstream>\n#include <string>\n#include <functional>\n\n#include <boost/filesystem.hpp>\n#include <boost/program_options.hpp>\n#include <boost/test/unit_test.hpp>\n#include <boost/test/data/test_case.hpp>\n#include <boost/test/data/monomorphic.hpp>\n\n#include \"detail/r1cs_examples.hpp\"\n#include \"detail/sha256_component.hpp\"\n#include <nil/crypto3/zk/components/voting/encrypted_input_voting.hpp>\n\n#include <nil/crypto3/algebra/curves/bls12.hpp>\n#include <nil/crypto3/algebra/fields/bls12/base_field.hpp>\n#include <nil/crypto3/algebra/fields/bls12/scalar_field.hpp>\n#include <nil/crypto3/algebra/fields/arithmetic_params/bls12.hpp>\n#include <nil/crypto3/algebra/curves/params/multiexp/bls12.hpp>\n#include <nil/crypto3/algebra/curves/params/wnaf/bls12.hpp>\n#include <nil/crypto3/algebra/pairing/bls12.hpp>\n#include <nil/crypto3/algebra/pairing/mnt4.hpp>\n#include <nil/crypto3/algebra/pairing/mnt6.hpp>\n\n#include <nil/crypto3/zk/components/blueprint.hpp>\n#include <nil/crypto3/zk/components/blueprint_variable.hpp>\n#include <nil/crypto3/zk/components/disjunction.hpp>\n\n#include <nil/crypto3/zk/snark/systems/ppzksnark/r1cs_gg_ppzksnark.hpp>\n#include <nil/crypto3/zk/snark/systems/ppzksnark/r1cs_gg_ppzksnark/marshalling.hpp>\n\n#include <nil/crypto3/zk/snark/algorithms/generate.hpp>\n#include <nil/crypto3/zk/snark/algorithms/verify.hpp>\n#include <nil/crypto3/zk/snark/algorithms/prove.hpp>\n\n#include <nil/marshalling/status_type.hpp>\n#include <nil/crypto3/marshalling/zk/types/r1cs_gg_ppzksnark/primary_input.hpp>\n#include <nil/crypto3/marshalling/zk/types/r1cs_gg_ppzksnark/proof.hpp>\n#include <nil/crypto3/marshalling/zk/types/r1cs_gg_ppzksnark/verification_key.hpp>\n#include <nil/crypto3/marshalling/zk/types/r1cs_gg_ppzksnark/proving_key.hpp>\n\n#include <nil/crypto3/pubkey/algorithm/generate_keypair.hpp>\n#include <nil/crypto3/pubkey/algorithm/encrypt.hpp>\n#include <nil/crypto3/pubkey/algorithm/decrypt.hpp>\n#include <nil/crypto3/pubkey/algorithm/verify_encryption.hpp>\n#include <nil/crypto3/pubkey/algorithm/verify_decryption.hpp>\n#include <nil/crypto3/pubkey/algorithm/rerandomize.hpp>\n#include <nil/crypto3/pubkey/elgamal_verifiable.hpp>\n#include <nil/crypto3/pubkey/modes/verifiable_encryption.hpp>\n\n#include <nil/crypto3/random/algebraic_random_device.hpp>\n\nusing namespace nil::crypto3;\nusing namespace nil::crypto3::algebra;\nusing namespace nil::crypto3::pubkey;\nusing namespace nil::crypto3::marshalling;\nusing namespace nil::crypto3::zk;\n\ntemplate<typename FieldParams>\nvoid print_field_element(std::ostream &os, const typename fields::detail::element_fp<FieldParams> &e) {\n    std::cout << e.data << std::endl;\n}\n\ntemplate<typename FieldParams>\nvoid print_field_element(std::ostream &os, const typename fields::detail::element_fp2<FieldParams> &e) {\n    std::cout << e.data[0].data << \", \" << e.data[1].data << std::endl;\n}\n\ntemplate<typename CurveParams, typename Form, typename Coordinates>\ntypename std::enable_if<std::is_same<Coordinates, curves::coordinates::projective>::value ||\n                        std::is_same<Coordinates, curves::coordinates::jacobian_with_a4_0>::value ||\n                        std::is_same<Coordinates, curves::coordinates::inverted>::value>::type\n    print_curve_point(std::ostream &os, const curves::detail::curve_element<CurveParams, Form, Coordinates> &p) {\n    os << \"( X: [\";\n    print_field_element(os, p.X);\n    os << \"], Y: [\";\n    print_field_element(os, p.Y);\n    os << \"], Z:[\";\n    print_field_element(os, p.Z);\n    os << \"] )\" << std::endl;\n}\n\ntemplate<typename FieldType>\ncomponents::blueprint<FieldType> test_disjunction_component(size_t w) {\n\n    using field_type = FieldType;\n\n    std::size_t n = std::log2(w) + ((w > (1ul << std::size_t(std::log2(w)))) ? 1 : 0);\n\n    components::blueprint<field_type> bp;\n    components::blueprint_variable<field_type> output;\n    output.allocate(bp);\n\n    bp.set_input_sizes(1);\n\n    components::blueprint_variable_vector<field_type> inputs;\n    inputs.allocate(bp, n);\n\n    components::disjunction<field_type> d(bp, inputs, output);\n    d.generate_r1cs_constraints();\n\n    for (std::size_t j = 0; j < n; ++j) {\n        bp.val(inputs[j]) = typename field_type::value_type((w & (1ul << j)) ? 1 : 0);\n    }\n\n    d.generate_r1cs_witness();\n\n    BOOST_ASSERT(bp.val(output) == (w ? field_type::value_type::one() : field_type::value_type::zero()));\n    BOOST_ASSERT(bp.is_satisfied());\n\n    return bp;\n}\n\ntemplate<typename Curve, typename Endianness, typename ProofSystem>\nvoid process_basic_mode(const boost::program_options::variables_map &vm) {\n    using curve_type = Curve;\n    using endianness = Endianness;\n    using proof_system_type = ProofSystem;\n    using scalar_field_type = typename curve_type::scalar_field_type;\n\n    using unit_type = unsigned char;\n    using verification_key_marshalling_type =\n        types::r1cs_gg_ppzksnark_verification_key<nil::marshalling::field_type<endianness>,\n                                                  typename proof_system_type::verification_key_type>;\n    using proof_marshalling_type = types::r1cs_gg_ppzksnark_proof<nil::marshalling::field_type<endianness>,\n                                                                  typename proof_system_type::proof_type>;\n    using primary_input_marshalling_type =\n        types::r1cs_gg_ppzksnark_primary_input<nil::marshalling::field_type<endianness>,\n                                               typename proof_system_type::primary_input_type>;\n\n    std::cout << \"Blueprint generation started...\" << std::endl;\n    std::cout << \"R1CS generation started...\" << std::endl;\n    components::blueprint<scalar_field_type> bp = sha2_two_to_one_bp<scalar_field_type>();\n    std::cout << \"R1CS generation finished.\" << std::endl;\n    std::cout << \"Blueprint generation finished.\" << std::endl;\n\n    std::cout << \"Keys generation started...\" << std::endl;\n    const typename proof_system_type::keypair_type keypair =\n        zk::snark::generate<proof_system_type>(bp.get_constraint_system());\n    std::cout << \"Keys generation finished.\" << std::endl;\n\n    std::cout << \"Proving started...\" << std::endl;\n    const typename proof_system_type::proof_type proof =\n        zk::snark::prove<proof_system_type>(keypair.first, bp.primary_input(), bp.auxiliary_input());\n    std::cout << \"Proving finished.\" << std::endl;\n\n    std::cout << \"Marshalling started...\" << std::endl;\n    verification_key_marshalling_type filled_verification_key_val =\n        types::fill_r1cs_gg_ppzksnark_verification_key<typename proof_system_type::verification_key_type, endianness>(\n            keypair.second);\n\n    proof_marshalling_type filled_proof_val =\n        types::fill_r1cs_gg_ppzksnark_proof<typename proof_system_type::proof_type, endianness>(proof);\n\n    primary_input_marshalling_type filled_primary_input_val =\n        types::fill_r1cs_gg_ppzksnark_primary_input<typename proof_system_type::primary_input_type, endianness>(\n            bp.primary_input());\n\n    std::cout << \"Marshalling finished.\" << std::endl;\n\n    std::vector<unit_type> verification_key_byteblob;\n    verification_key_byteblob.resize(filled_verification_key_val.length(), 0x00);\n    auto write_iter = verification_key_byteblob.begin();\n\n    typename nil::marshalling::status_type status =\n        filled_verification_key_val.write(write_iter, verification_key_byteblob.size());\n\n    std::vector<unit_type> proof_byteblob;\n    proof_byteblob.resize(filled_proof_val.length(), 0x00);\n    write_iter = proof_byteblob.begin();\n\n    status = filled_proof_val.write(write_iter, proof_byteblob.size());\n\n    std::vector<unit_type> primary_input_byteblob;\n\n    primary_input_byteblob.resize(filled_primary_input_val.length(), 0x00);\n    auto primary_input_write_iter = primary_input_byteblob.begin();\n\n    status = filled_primary_input_val.write(primary_input_write_iter, primary_input_byteblob.size());\n\n    std::cout << \"Byteblobs filled.\" << std::endl;\n\n    if (vm.count(\"r1cs-verification-key-output\")) {\n        std::ofstream out(vm[\"r1cs-verification-key-output\"].as<std::filesystem::path>(), std::ios_base::binary);\n        for (const auto &v : verification_key_byteblob) {\n            out << v;\n        }\n        out.close();\n    }\n\n    if (vm.count(\"r1cs-proof-output\")) {\n        std::ofstream out(vm[\"r1cs-proof-output\"].as<std::filesystem::path>(), std::ios_base::binary);\n        for (const auto &v : proof_byteblob) {\n            out << v;\n        }\n        out.close();\n    }\n\n    if (vm.count(\"r1cs-primary-input-output\")) {\n        std::ofstream out(vm[\"r1cs-primary-input-output\"].as<std::filesystem::path>(), std::ios_base::binary);\n        for (const auto &v : primary_input_byteblob) {\n            out << v;\n        }\n        out.close();\n    }\n\n    // nil::marshalling::status_type provingProcessingStatus = nil::marshalling::status_type::success;\n    // typename proof_system_type::proving_key_type other =\n    //             nil::marshalling::verifier_input_deserializer_tvm<proof_system_type>::proving_key_process(\n    //                 proving_key_byteblob.cbegin(),\n    //                 proving_key_byteblob.cend(),\n    //                 provingProcessingStatus);\n\n    // BOOST_ASSERT(keypair.first == other);\n\n    if (vm.count(\"r1cs-verifier-input-output\")) {\n        std::vector<std::uint8_t> verifier_input_output_byteblob(proof_byteblob.begin(), proof_byteblob.end());\n\n        verifier_input_output_byteblob.insert(verifier_input_output_byteblob.end(), primary_input_byteblob.begin(),\n                                              primary_input_byteblob.end());\n        verifier_input_output_byteblob.insert(verifier_input_output_byteblob.end(), verification_key_byteblob.begin(),\n                                              verification_key_byteblob.end());\n\n        std::ofstream poutf(vm[\"r1cs-verifier-input-output\"].as<std::filesystem::path>(), std::ios_base::binary);\n        for (const auto &v : verifier_input_output_byteblob) {\n            poutf << v;\n        }\n        poutf.close();\n    }\n}\n\nstruct marshaling_verification_data_groth16_encrypted_input;\n\nstruct enc_input_policy {\n    using pairing_curve_type = curves::bls12_381;\n    using curve_type = curves::jubjub;\n    using base_points_generator_hash_type = hashes::sha2<256>;\n    using hash_params = hashes::find_group_hash_default_params;\n    using hash_component = components::pedersen<curve_type, base_points_generator_hash_type, hash_params>;\n    using hash_type = typename hash_component::hash_type;\n    using merkle_hash_component = hash_component;\n    using merkle_hash_type = typename merkle_hash_component::hash_type;\n    using field_type = typename hash_component::field_type;\n    static constexpr std::size_t arity = 2;\n    using voting_component =\n        components::encrypted_input_voting<arity, hash_component, merkle_hash_component, field_type>;\n    using merkle_proof_component = typename voting_component::merkle_proof_component;\n    using encryption_scheme_type = elgamal_verifiable<pairing_curve_type>;\n    using proof_system = typename encryption_scheme_type::proof_system_type;\n    static constexpr std::size_t msg_size = 7;\n    static constexpr std::size_t secret_key_bits = hash_type::digest_bits;\n    static constexpr std::size_t public_key_bits = secret_key_bits;\n};\n\nstruct marshaling_policy {\n    using scalar_field_value_type =\n        typename enc_input_policy::encryption_scheme_type::curve_type::scalar_field_type::value_type;\n    using proof_type = typename enc_input_policy::proof_system::proof_type;\n    using verification_key_type = typename enc_input_policy::proof_system::verification_key_type;\n    using proving_key_type = typename enc_input_policy::proof_system::proving_key_type;\n    using primary_input_type = typename enc_input_policy::proof_system::primary_input_type;\n    using elgamal_public_key_type = typename enc_input_policy::encryption_scheme_type::public_key_type;\n    using elgamal_private_key_type = typename enc_input_policy::encryption_scheme_type::private_key_type;\n    using elgamal_verification_key_type = typename enc_input_policy::encryption_scheme_type::verification_key_type;\n\n    using endianness = nil::marshalling::option::big_endian;\n    using r1cs_proof_marshaling_type =\n        nil::crypto3::marshalling::types::r1cs_gg_ppzksnark_proof<nil::marshalling::field_type<endianness>, proof_type>;\n    using r1cs_verification_key_marshaling_type =\n        nil::crypto3::marshalling::types::r1cs_gg_ppzksnark_extended_verification_key<\n            nil::marshalling::field_type<endianness>, verification_key_type>;\n    using r1cs_proving_key_marshalling_type =\n        nil::crypto3::marshalling::types::r1cs_gg_ppzksnark_proving_key<nil::marshalling::field_type<endianness>,\n                                                                        proving_key_type>;\n    using public_key_marshaling_type =\n        nil::crypto3::marshalling::types::elgamal_verifiable_public_key<nil::marshalling::field_type<endianness>,\n                                                                        elgamal_public_key_type>;\n    using secret_key_marshaling_type =\n        nil::crypto3::marshalling::types::elgamal_verifiable_private_key<nil::marshalling::field_type<endianness>,\n                                                                         elgamal_private_key_type>;\n    using verification_key_marshaling_type =\n        nil::crypto3::marshalling::types::elgamal_verifiable_verification_key<nil::marshalling::field_type<endianness>,\n                                                                              elgamal_verification_key_type>;\n    using ct_marshaling_type = nil::crypto3::marshalling::types::r1cs_gg_ppzksnark_encrypted_primary_input<\n        nil::marshalling::field_type<endianness>, enc_input_policy::encryption_scheme_type::cipher_type::first_type>;\n    using pinput_marshaling_type =\n        nil::crypto3::marshalling::types::r1cs_gg_ppzksnark_primary_input<nil::marshalling::field_type<endianness>,\n                                                                          primary_input_type>;\n\n    template<typename MarshalingType, typename InputObj, typename F>\n    static std::vector<std::uint8_t> serialize_obj(const InputObj &in_obj, const std::function<F> &f) {\n        MarshalingType filled_val = f(in_obj);\n        std::vector<std::uint8_t> blob(filled_val.length());\n        auto it = std::begin(blob);\n        nil::marshalling::status_type status = filled_val.write(it, blob.size());\n        return blob;\n    }\n\n    template<typename Path, typename Blob>\n    static void write_obj(const Path &path, std::initializer_list<Blob> blobs) {\n        if (std::filesystem::exists(path)) {\n            std::cout << \"File \" << path << \" exists and won't be overwritten.\" << std::endl;\n            return;\n        }\n        std::ofstream out(path, std::ios_base::binary);\n        for (const auto &blob : blobs) {\n            for (const auto b : blob) {\n                out << b;\n            }\n        }\n        out.close();\n    }\n\n    template<typename MarshalingType, typename ReturnType, typename InputBlob, typename F>\n    static ReturnType deserialize_obj(const InputBlob &blob, const std::function<F> &f) {\n        MarshalingType marshaling_obj;\n        auto it = std::cbegin(blob);\n        nil::marshalling::status_type status = marshaling_obj.read(it, blob.size());\n        return f(marshaling_obj);\n    }\n\n    template<typename Path>\n    static std::vector<std::uint8_t> read_obj(const Path &path) {\n        if (!std::filesystem::exists(path)) {\n            std::cerr << \"File \" << path << \" doesn't exist, make sure you created it.\" << std::endl;\n            std::exit(1);\n        }\n        std::ifstream in(path, std::ios_base::binary);\n        std::stringstream buffer;\n        buffer << in.rdbuf();\n        auto blob_str = buffer.str();\n        return {std::cbegin(blob_str), std::cend(blob_str)};\n    }\n\n    static void write_initial_phase_voter_data(const boost::program_options::variables_map &vm,\n                                               const std::vector<scalar_field_value_type> &voter_pubkey,\n                                               const std::vector<scalar_field_value_type> &voter_skey, std::size_t i) {\n        auto pubkey_blob = serialize_obj<pinput_marshaling_type>(\n            voter_pubkey,\n            std::function(nil::crypto3::marshalling::types::fill_r1cs_gg_ppzksnark_primary_input<primary_input_type,\n                                                                                                 endianness>));\n        if (vm.count(\"voter-public-key-output\")) {\n            auto filename = vm[\"voter-public-key-output\"].as<std::string>() + std::to_string(i) + \".bin\";\n            write_obj(std::filesystem::path(filename), {pubkey_blob});\n        }\n\n        auto sk_blob = serialize_obj<pinput_marshaling_type>(\n            voter_skey,\n            std::function(nil::crypto3::marshalling::types::fill_r1cs_gg_ppzksnark_primary_input<primary_input_type,\n                                                                                                 endianness>));\n        if (vm.count(\"voter-secret-key-output\")) {\n            auto filename = vm[\"voter-secret-key-output\"].as<std::string>() + std::to_string(i) + \".bin\";\n            write_obj(std::filesystem::path(filename), {sk_blob});\n        }\n    }\n\n    static void write_initial_phase_admin_data(const boost::program_options::variables_map &vm,\n                                               const proving_key_type &pk_crs, const verification_key_type &vk_crs,\n                                               const elgamal_public_key_type &pk_eid,\n                                               const elgamal_private_key_type &sk_eid,\n                                               const elgamal_verification_key_type &vk_eid,\n                                               const primary_input_type &eid, const primary_input_type &rt) {\n        auto pk_crs_blob = serialize_obj<r1cs_proving_key_marshalling_type>(\n            pk_crs,\n            std::function(\n                nil::crypto3::marshalling::types::fill_r1cs_gg_ppzksnark_proving_key<proving_key_type, endianness>));\n        if (vm.count(\"r1cs-proving-key-output\")) {\n            auto filename = vm[\"r1cs-proving-key-output\"].as<std::string>() + \".bin\";\n            write_obj(std::filesystem::path(filename), {pk_crs_blob});\n        }\n\n        auto vk_crs_blob = serialize_obj<r1cs_verification_key_marshaling_type>(\n            vk_crs,\n            std::function(\n                nil::crypto3::marshalling::types::fill_r1cs_gg_ppzksnark_verification_key<verification_key_type,\n                                                                                          endianness>));\n        if (vm.count(\"r1cs-verification-key-output\")) {\n            auto filename = vm[\"r1cs-verification-key-output\"].as<std::string>() + \".bin\";\n            write_obj(std::filesystem::path(filename), {vk_crs_blob});\n        }\n\n        auto pk_eid_blob = serialize_obj<public_key_marshaling_type>(\n            pk_eid,\n            std::function(nil::crypto3::marshalling::types::fill_public_key<elgamal_public_key_type, endianness>));\n        if (vm.count(\"public-key-output\")) {\n            auto filename = vm[\"public-key-output\"].as<std::string>() + \".bin\";\n            write_obj(std::filesystem::path(filename), {pk_eid_blob});\n        }\n\n        auto sk_eid_blob = serialize_obj<secret_key_marshaling_type>(\n            sk_eid,\n            std::function(nil::crypto3::marshalling::types::fill_private_key<elgamal_private_key_type, endianness>));\n        if (vm.count(\"secret-key-output\")) {\n            auto filename = vm[\"secret-key-output\"].as<std::string>() + \".bin\";\n            write_obj(std::filesystem::path(filename), {sk_eid_blob});\n        }\n\n        auto vk_eid_blob = serialize_obj<verification_key_marshaling_type>(\n            vk_eid,\n            std::function(\n                nil::crypto3::marshalling::types::fill_verification_key<elgamal_verification_key_type, endianness>));\n        if (vm.count(\"verification-key-output\")) {\n            auto filename = vm[\"verification-key-output\"].as<std::string>() + \".bin\";\n            write_obj(std::filesystem::path(filename), {vk_eid_blob});\n        }\n\n        auto eid_blob = serialize_obj<pinput_marshaling_type>(\n            eid,\n            std::function(nil::crypto3::marshalling::types::fill_r1cs_gg_ppzksnark_primary_input<primary_input_type,\n                                                                                                 endianness>));\n        if (vm.count(\"eid-output\")) {\n            auto filename = vm[\"eid-output\"].as<std::string>() + \".bin\";\n            write_obj(std::filesystem::path(filename), {eid_blob});\n        }\n\n        auto rt_blob = serialize_obj<pinput_marshaling_type>(\n            rt,\n            std::function(nil::crypto3::marshalling::types::fill_r1cs_gg_ppzksnark_primary_input<primary_input_type,\n                                                                                                 endianness>));\n        if (vm.count(\"rt-output\")) {\n            auto filename = vm[\"rt-output\"].as<std::string>() + \".bin\";\n            write_obj(std::filesystem::path(filename), {rt_blob});\n        }\n    }\n\n    static void write_data(std::size_t proof_idx, const boost::program_options::variables_map &vm,\n                           const verification_key_type &vk_crs, const elgamal_public_key_type &pk_eid,\n                           const proof_type &proof, const primary_input_type &pinput,\n                           const enc_input_policy::encryption_scheme_type::cipher_type::first_type &ct,\n                           const primary_input_type &eid, const primary_input_type &sn, const primary_input_type &rt) {\n        auto proof_blob = serialize_obj<r1cs_proof_marshaling_type>(\n            proof,\n            std::function(nil::crypto3::marshalling::types::fill_r1cs_gg_ppzksnark_proof<proof_type, endianness>));\n        if (vm.count(\"r1cs-proof-output\")) {\n            auto filename = vm[\"r1cs-proof-output\"].as<std::string>() + std::to_string(proof_idx) + \".bin\";\n            write_obj(std::filesystem::path(filename), {proof_blob});\n        }\n\n        auto pinput_blob = serialize_obj<pinput_marshaling_type>(\n            pinput,\n            std::function(nil::crypto3::marshalling::types::fill_r1cs_gg_ppzksnark_primary_input<primary_input_type,\n                                                                                                 endianness>));\n        if (vm.count(\"r1cs-primary-input-output\")) {\n            auto filename = vm[\"r1cs-primary-input-output\"].as<std::string>() + std::to_string(proof_idx) + \".bin\";\n            write_obj(std::filesystem::path(filename), {pinput_blob});\n        }\n\n        auto ct_blob = serialize_obj<ct_marshaling_type>(\n            ct,\n            std::function(nil::crypto3::marshalling::types::fill_r1cs_gg_ppzksnark_encrypted_primary_input<\n                          enc_input_policy::encryption_scheme_type::cipher_type::first_type, endianness>));\n        if (vm.count(\"cipher-text-output\")) {\n            auto filename = vm[\"cipher-text-output\"].as<std::string>() + std::to_string(proof_idx) + \".bin\";\n            write_obj(std::filesystem::path(filename), {ct_blob});\n        }\n\n        auto eid_blob = serialize_obj<pinput_marshaling_type>(\n            eid,\n            std::function(nil::crypto3::marshalling::types::fill_r1cs_gg_ppzksnark_primary_input<primary_input_type,\n                                                                                                 endianness>));\n\n        auto sn_blob = serialize_obj<pinput_marshaling_type>(\n            sn,\n            std::function(nil::crypto3::marshalling::types::fill_r1cs_gg_ppzksnark_primary_input<primary_input_type,\n                                                                                                 endianness>));\n        if (vm.count(\"sn-output\")) {\n            auto filename = vm[\"sn-output\"].as<std::string>() + std::to_string(proof_idx) + \".bin\";\n            write_obj(std::filesystem::path(filename), {sn_blob});\n        }\n\n        auto rt_blob = serialize_obj<pinput_marshaling_type>(\n            rt,\n            std::function(nil::crypto3::marshalling::types::fill_r1cs_gg_ppzksnark_primary_input<primary_input_type,\n                                                                                                 endianness>));\n\n        auto vk_crs_blob = serialize_obj<r1cs_verification_key_marshaling_type>(\n            vk_crs,\n            std::function(\n                nil::crypto3::marshalling::types::fill_r1cs_gg_ppzksnark_verification_key<verification_key_type,\n                                                                                          endianness>));\n        auto pk_eid_blob = serialize_obj<public_key_marshaling_type>(\n            pk_eid,\n            std::function(nil::crypto3::marshalling::types::fill_public_key<elgamal_public_key_type, endianness>));\n        if (vm.count(\"r1cs-verifier-input-output\")) {\n            auto filename = vm[\"r1cs-verifier-input-output\"].as<std::string>() + std::to_string(proof_idx) + \".bin\";\n            auto filename1 = vm[\"r1cs-verifier-input-output\"].as<std::string>() + std::string(\"_chunked\") +\n                             std::to_string(proof_idx) + \".bin\";\n            write_obj(std::filesystem::path(filename), {proof_blob, vk_crs_blob, pk_eid_blob, ct_blob, pinput_blob});\n            write_obj(std::filesystem::path(filename1),\n                      {proof_blob, vk_crs_blob, pk_eid_blob, ct_blob, eid_blob, sn_blob, rt_blob});\n        }\n    }\n\n    static void write_tally_phase_data(const boost::program_options::variables_map &vm,\n                                       const typename enc_input_policy::encryption_scheme_type::decipher_type &dec) {\n        nil::marshalling::status_type status;\n        std::vector<std::uint8_t> dec_proof_blob = nil::marshalling::pack<endianness>(dec.second, status);\n        if (vm.count(\"decryption-proof-output\")) {\n            auto filename = vm[\"decryption-proof-output\"].as<std::string>() + \".bin\";\n            write_obj(filename, {\n                                    dec_proof_blob,\n                                });\n\n            typename enc_input_policy::encryption_scheme_type::decipher_type::second_type constructed_val =\n                nil::marshalling::pack<endianness>(dec_proof_blob, status);\n            if (!(dec.second == constructed_val))\n                std::exit(10);\n        }\n\n        auto voting_res_blob = serialize_obj<pinput_marshaling_type>(\n            dec.first,\n            std::function(nil::crypto3::marshalling::types::fill_r1cs_gg_ppzksnark_primary_input<\n                          std::vector<scalar_field_value_type>, endianness>));\n        if (vm.count(\"voting-result-output\")) {\n            auto filename = vm[\"voting-result-output\"].as<std::string>() + \".bin\";\n            write_obj(filename, {\n                                    voting_res_blob,\n                                });\n        }\n    }\n\n    static std::vector<scalar_field_value_type> read_scalar_vector(const std::string &file_prefix) {\n        auto filename = file_prefix + \".bin\";\n        return deserialize_obj<pinput_marshaling_type, std::vector<scalar_field_value_type>>(\n            read_obj(filename),\n            std::function(nil::crypto3::marshalling::types::make_r1cs_gg_ppzksnark_primary_input<\n                          std::vector<scalar_field_value_type>, endianness>));\n    }\n\n    static std::vector<bool> read_bool_vector(const std::string &file_prefix) {\n        std::vector<bool> result;\n        for (const auto &i : read_scalar_vector(file_prefix)) {\n            result.emplace_back(i.data);\n        }\n        return result;\n    }\n\n    static std::vector<std::vector<bool>> read_voters_public_keys(const boost::program_options::variables_map &vm) {\n        std::size_t participants_number = 1 << vm[\"tree-depth\"].as<std::size_t>();\n        std::vector<std::vector<bool>> result;\n\n        for (auto i = 0; i < participants_number; i++) {\n            if (vm.count(\"voter-public-key-output\")) {\n                result.emplace_back(\n                    read_bool_vector(vm[\"voter-public-key-output\"].as<std::string>() + std::to_string(i)));\n            }\n        }\n        return result;\n    }\n\n    static elgamal_public_key_type read_pk_eid(const boost::program_options::variables_map &vm) {\n        auto pk_eid_blob = read_obj(vm[\"public-key-output\"].as<std::string>() + \".bin\");\n        return deserialize_obj<public_key_marshaling_type, elgamal_public_key_type>(\n            pk_eid_blob,\n            std::function(nil::crypto3::marshalling::types::make_public_key<elgamal_public_key_type, endianness>));\n    }\n\n    static elgamal_verification_key_type read_vk_eid(const boost::program_options::variables_map &vm) {\n        auto vk_eid_blob = read_obj(vm[\"verification-key-output\"].as<std::string>() + \".bin\");\n        return deserialize_obj<verification_key_marshaling_type, elgamal_verification_key_type>(\n            vk_eid_blob,\n            std::function(\n                nil::crypto3::marshalling::types::make_verification_key<elgamal_verification_key_type, endianness>));\n    }\n\n    static elgamal_private_key_type read_sk_eid(const boost::program_options::variables_map &vm) {\n        auto sk_eid_blob = read_obj(vm[\"secret-key-output\"].as<std::string>() + \".bin\");\n        return deserialize_obj<secret_key_marshaling_type, elgamal_private_key_type>(\n            sk_eid_blob,\n            std::function(nil::crypto3::marshalling::types::make_private_key<elgamal_private_key_type, endianness>));\n    }\n\n    static verification_key_type read_vk_crs(const boost::program_options::variables_map &vm) {\n        auto vk_crs_blob = read_obj(vm[\"r1cs-verification-key-output\"].as<std::string>() + \".bin\");\n        return deserialize_obj<r1cs_verification_key_marshaling_type, verification_key_type>(\n            vk_crs_blob, std::function(nil::crypto3::marshalling::types::make_r1cs_gg_ppzksnark_verification_key<\n                                       verification_key_type, endianness>));\n    }\n\n    static proving_key_type read_pk_crs(const boost::program_options::variables_map &vm) {\n        auto pk_crs_blob = read_obj(vm[\"r1cs-proving-key-output\"].as<std::string>() + \".bin\");\n        return deserialize_obj<r1cs_proving_key_marshalling_type, proving_key_type>(\n            pk_crs_blob,\n            std::function(\n                nil::crypto3::marshalling::types::make_r1cs_gg_ppzksnark_proving_key<proving_key_type, endianness>));\n    }\n\n    static proof_type read_proof(const boost::program_options::variables_map &vm, std::size_t proof_idx) {\n        auto proof_blob = read_obj(vm[\"r1cs-proof-output\"].as<std::string>() + std::to_string(proof_idx) + \".bin\");\n        return deserialize_obj<r1cs_proof_marshaling_type, proof_type>(\n            proof_blob,\n            std::function(nil::crypto3::marshalling::types::make_r1cs_gg_ppzksnark_proof<proof_type, endianness>));\n    }\n\n    static typename enc_input_policy::encryption_scheme_type::cipher_type::first_type\n        read_ct(const boost::program_options::variables_map &vm, std::size_t proof_idx) {\n        return deserialize_obj<ct_marshaling_type,\n                               typename enc_input_policy::encryption_scheme_type::cipher_type::first_type>(\n            read_obj(vm[\"cipher-text-output\"].as<std::string>() + std::to_string(proof_idx) + \".bin\"),\n            std::function(nil::crypto3::marshalling::types::make_r1cs_gg_ppzksnark_encrypted_primary_input<\n                          typename enc_input_policy::encryption_scheme_type::cipher_type::first_type, endianness>));\n    }\n\n    static typename enc_input_policy::encryption_scheme_type::decipher_type::second_type\n        read_decryption_proof(const boost::program_options::variables_map &vm) {\n        auto dec_proof_blob = read_obj(vm[\"decryption-proof-output\"].as<std::string>() + \".bin\");\n        nil::marshalling::status_type status;\n        return static_cast<typename enc_input_policy::encryption_scheme_type::decipher_type::second_type>(\n            nil::marshalling::pack<endianness>(dec_proof_blob, status));\n    }\n};\n\ntemplate<typename ValueType, std::size_t N>\ntypename std::enable_if<std::is_unsigned<ValueType>::value, std::vector<std::array<ValueType, N>>>::type\n    generate_random_data(std::size_t leaf_number) {\n    std::vector<std::array<ValueType, N>> v;\n    for (std::size_t i = 0; i < leaf_number; ++i) {\n        std::array<ValueType, N> leaf {};\n        std::generate(std::begin(leaf), std::end(leaf),\n                      [&]() { return std::rand() % (std::numeric_limits<ValueType>::max() + 1); });\n        v.emplace_back(leaf);\n    }\n    return v;\n}\n\nvoid process_encrypted_input_mode(const boost::program_options::variables_map &vm) {\n    using scalar_field_value_type = typename enc_input_policy::pairing_curve_type::scalar_field_type::value_type;\n\n    std::size_t tree_depth = 0;\n    if (vm.count(\"tree-depth\")) {\n        tree_depth = vm[\"tree-depth\"].as<std::size_t>();\n    } else {\n        std::cerr << \"Tree depth is not specified!\" << std::endl;\n        return;\n    }\n\n    std::size_t participants_number = 1 << tree_depth;\n    std::cout << \"There will be \" << participants_number << \" participants in voting.\" << std::endl;\n\n    auto secret_keys = generate_random_data<bool, enc_input_policy::secret_key_bits>(participants_number);\n    std::vector<std::array<bool, enc_input_policy::public_key_bits>> public_keys;\n    std::vector<std::vector<scalar_field_value_type>> public_keys_field;\n    std::vector<std::vector<scalar_field_value_type>> secret_keys_field;\n    auto j = 0;\n    for (const auto &sk : secret_keys) {\n        std::array<bool, enc_input_policy::hash_type::digest_bits> pk {};\n        hash<enc_input_policy::merkle_hash_type>(sk, std::begin(pk));\n        public_keys.emplace_back(pk);\n        std::vector<scalar_field_value_type> pk_field;\n        std::vector<scalar_field_value_type> sk_field;\n        std::cout << \"Public key of the Voter \" << j << \": \";\n        for (auto c : pk) {\n            std::cout << int(c);\n            pk_field.emplace_back(int(c));\n        }\n        for (auto c : sk) {\n            sk_field.emplace_back(int(c));\n        }\n        std::cout << std::endl;\n        public_keys_field.push_back(pk_field);\n        secret_keys_field.push_back(sk_field);\n        marshaling_policy::write_initial_phase_voter_data(vm, public_keys_field.back(), secret_keys_field.back(), j);\n        ++j;\n    }\n    std::cout << \"Participants key pairs generated.\" << std::endl;\n\n    std::cout << \"Merkle tree generation upon participants public keys started...\" << std::endl;\n    containers::merkle_tree<enc_input_policy::merkle_hash_type, enc_input_policy::arity> tree(public_keys);\n    std::vector<scalar_field_value_type> rt_field;\n    for (auto i : tree.root()) {\n        rt_field.emplace_back(int(i));\n    }\n    std::cout << \"Merkle tree generation finished.\" << std::endl;\n\n    const std::size_t eid_size = 64;\n    std::vector<bool> eid(eid_size);\n    std::vector<scalar_field_value_type> eid_field;\n    std::generate(eid.begin(), eid.end(), [&]() { return std::rand() % 2; });\n    std::cout << \"Voting session (eid) is: \";\n    for (auto i : eid) {\n        std::cout << int(i);\n        eid_field.emplace_back(int(i));\n    }\n    std::cout << std::endl;\n\n    std::cout << \"Voting system administrator generates R1CS...\" << std::endl;\n    components::blueprint<enc_input_policy::field_type> bp;\n    components::block_variable<enc_input_policy::field_type> m_block(bp, enc_input_policy::msg_size);\n    components::block_variable<enc_input_policy::field_type> eid_block(bp, eid.size());\n    components::digest_variable<enc_input_policy::field_type> sn_digest(bp,\n                                                                        enc_input_policy::hash_component::digest_bits);\n    components::digest_variable<enc_input_policy::field_type> root_digest(\n        bp, enc_input_policy::merkle_hash_component::digest_bits);\n    components::blueprint_variable_vector<enc_input_policy::field_type> address_bits_va;\n    address_bits_va.allocate(bp, tree_depth);\n    enc_input_policy::merkle_proof_component path_var(bp, tree_depth);\n    components::block_variable<enc_input_policy::field_type> sk_block(bp, enc_input_policy::secret_key_bits);\n    enc_input_policy::voting_component vote_var(bp, m_block, eid_block, sn_digest, root_digest, address_bits_va,\n                                                path_var, sk_block,\n                                                components::blueprint_variable<enc_input_policy::field_type>(0));\n    path_var.generate_r1cs_constraints();\n    vote_var.generate_r1cs_constraints();\n    std::cout << \"R1CS generation finished.\" << std::endl;\n    std::cout << \"Constraints number in the generated R1CS: \" << bp.num_constraints() << std::endl;\n    bp.set_input_sizes(vote_var.get_input_size());\n\n    std::cout << \"Administrator generates CRS...\" << std::endl;\n    typename enc_input_policy::proof_system::keypair_type gg_keypair =\n        snark::generate<enc_input_policy::proof_system>(bp.get_constraint_system());\n    std::cout << \"CRS generation finished.\" << std::endl;\n\n    std::cout << \"Administrator generates private, public and verification keys for El-Gamal verifiable encryption \"\n                 \"scheme...\"\n              << std::endl;\n    random::algebraic_random_device<typename enc_input_policy::pairing_curve_type::scalar_field_type> d;\n    std::vector<scalar_field_value_type> rnd;\n    for (std::size_t i = 0; i < enc_input_policy::msg_size * 3 + 2; ++i) {\n        rnd.emplace_back(d());\n    }\n    typename enc_input_policy::encryption_scheme_type::keypair_type keypair =\n        generate_keypair<enc_input_policy::encryption_scheme_type,\n                         modes::verifiable_encryption<enc_input_policy::encryption_scheme_type>>(\n            rnd, {gg_keypair, enc_input_policy::msg_size});\n    std::cout << \"Private, public and verification keys for El-Gamal verifiable encryption scheme generated.\"\n              << std::endl\n              << std::endl;\n    std::cout << \"====================================================================\" << std::endl << std::endl;\n\n    std::cout << \"Pre-init administrator marshalling started...\" << std::endl;\n    marshaling_policy::write_initial_phase_admin_data(vm, gg_keypair.first, gg_keypair.second, std::get<0>(keypair),\n                                                      std::get<1>(keypair), std::get<2>(keypair), eid_field, rt_field);\n    std::cout << \"Marshalling finished.\" << std::endl;\n\n    std::vector<typename enc_input_policy::encryption_scheme_type::cipher_type> ct_n;\n\n    for (std::size_t i = 0; i < participants_number; ++i) {\n\n        std::size_t proof_idx = i;\n        std::cout << \"Participant with index \" << proof_idx << \" (vote sender) generates its merkle copath.\"\n                  << std::endl;\n        containers::merkle_proof<enc_input_policy::merkle_hash_type, enc_input_policy::arity> path(tree, proof_idx);\n        auto tree_pk_leaf = tree[proof_idx];\n\n        std::vector<bool> m(enc_input_policy::msg_size, false);\n        m[std::rand() % m.size()] = true;\n        std::cout << \"Voter \" << proof_idx << \" is willing to vote with the following ballot: { \";\n        for (auto m_i : m) {\n            std::cout << int(m_i);\n        }\n        std::cout << \" }\" << std::endl;\n        std::vector<scalar_field_value_type> m_field;\n        m_field.reserve(m.size());\n        for (const auto m_i : m) {\n            m_field.emplace_back(std::size_t(m_i));\n        }\n\n        std::vector<bool> eid_sk;\n        std::copy(std::cbegin(eid), std::cend(eid), std::back_inserter(eid_sk));\n        std::copy(std::cbegin(secret_keys[proof_idx]), std::cend(secret_keys[proof_idx]), std::back_inserter(eid_sk));\n        std::vector<bool> sn = hash<enc_input_policy::hash_type>(eid_sk);\n        std::cout << \"Sender has following serial number (sn) in current session: \";\n        for (auto i : sn) {\n            std::cout << int(i);\n        }\n        std::cout << std::endl;\n\n        // BOOST_ASSERT(!bp.is_satisfied());\n        path_var.generate_r1cs_witness(path, true);\n        if (bp.is_satisfied())\n            std::exit(1);\n        address_bits_va.fill_with_bits_of_ulong(bp, path_var.address);\n        if (bp.is_satisfied())\n            std::exit(1);\n        if (address_bits_va.get_field_element_from_bits(bp) != path_var.address)\n            std::exit(1);\n        m_block.generate_r1cs_witness(m);\n        if (bp.is_satisfied())\n            std::exit(1);\n        eid_block.generate_r1cs_witness(eid);\n        if (bp.is_satisfied())\n            std::exit(1);\n        sk_block.generate_r1cs_witness(secret_keys[proof_idx]);\n        if (bp.is_satisfied())\n            std::exit(1);\n        vote_var.generate_r1cs_witness(tree.root(), sn);\n        if (!bp.is_satisfied())\n            std::exit(1);\n\n        std::cout << \"Voter \" << proof_idx << \" generates its vote consisting of proof and cipher text...\" << std::endl;\n        typename enc_input_policy::encryption_scheme_type::cipher_type cipher_text =\n            encrypt<enc_input_policy::encryption_scheme_type,\n                    modes::verifiable_encryption<enc_input_policy::encryption_scheme_type>>(\n                m_field, {d(), std::get<0>(keypair), gg_keypair, bp.primary_input(), bp.auxiliary_input()});\n        ct_n.push_back(cipher_text);\n        std::cout << \"Vote generated.\" << std::endl;\n\n        std::cout << \"Rerandomization of the cipher text and proof started...\" << std::endl;\n        std::vector<scalar_field_value_type> rnd_rerandomization;\n        for (std::size_t i = 0; i < 3; ++i) {\n            rnd_rerandomization.emplace_back(d());\n        }\n        typename enc_input_policy::encryption_scheme_type::cipher_type rerand_cipher_text =\n            rerandomize<enc_input_policy::encryption_scheme_type>(\n                rnd_rerandomization, cipher_text.first, {std::get<0>(keypair), gg_keypair, cipher_text.second});\n        std::cout << \"Rerandomization finished.\" << std::endl;\n\n        std::cout << \"Voter \" << proof_idx << \" marshalling started...\" << std::endl;\n        std::size_t eid_offset = m.size();\n        std::size_t sn_offset = eid_offset + eid.size();\n        std::size_t rt_offset = sn_offset + sn.size();\n        std::size_t rt_offset_end = rt_offset + tree.root().size();\n        typename enc_input_policy::proof_system::primary_input_type pinput = bp.primary_input();\n        if (std::cbegin(pinput) + rt_offset_end != std::cend(pinput))\n            std::exit(1);\n        if (eid_field != typename enc_input_policy::proof_system::primary_input_type {std::cbegin(pinput) + eid_offset,\n                                                                                      std::cbegin(pinput) + sn_offset})\n            std::exit(1);\n        if (rt_field != typename enc_input_policy::proof_system::primary_input_type {\n                            std::cbegin(pinput) + rt_offset, std::cbegin(pinput) + rt_offset_end})\n            std::exit(1);\n        marshaling_policy::write_data(proof_idx, vm, gg_keypair.second, std::get<0>(keypair), rerand_cipher_text.second,\n                                      typename enc_input_policy::proof_system::primary_input_type {\n                                          std::cbegin(pinput) + eid_offset, std::cend(pinput)},\n                                      rerand_cipher_text.first,\n                                      typename enc_input_policy::proof_system::primary_input_type {\n                                          std::cbegin(pinput) + eid_offset, std::cbegin(pinput) + sn_offset},\n                                      typename enc_input_policy::proof_system::primary_input_type {\n                                          std::cbegin(pinput) + sn_offset, std::cbegin(pinput) + rt_offset},\n                                      typename enc_input_policy::proof_system::primary_input_type {\n                                          std::cbegin(pinput) + rt_offset, std::cbegin(pinput) + rt_offset_end});\n        std::cout << \"Marshalling finished.\" << std::endl;\n\n        std::cout << \"Sender verifies rerandomized encrypted ballot and proof...\" << std::endl;\n        bool enc_verification_ans = verify_encryption<enc_input_policy::encryption_scheme_type>(\n            rerand_cipher_text.first,\n            {std::get<0>(keypair), gg_keypair.second, rerand_cipher_text.second,\n             typename enc_input_policy::proof_system::primary_input_type {std::cbegin(pinput) + m.size(),\n                                                                          std::cend(pinput)}});\n        if (!enc_verification_ans)\n            std::exit(1);\n        std::cout << \"Encryption verification of rerandomazed cipher text and proof finished.\" << std::endl;\n\n        std::cout << \"Administrator decrypts ballot from rerandomized cipher text and generates decryption proof...\"\n                  << std::endl;\n        typename enc_input_policy::encryption_scheme_type::decipher_type decipher_rerand_text =\n            decrypt<enc_input_policy::encryption_scheme_type,\n                    modes::verifiable_encryption<enc_input_policy::encryption_scheme_type>>(\n                rerand_cipher_text.first, {std::get<1>(keypair), std::get<2>(keypair), gg_keypair});\n        if (decipher_rerand_text.first.size() != m_field.size())\n            std::exit(1);\n        for (std::size_t i = 0; i < m_field.size(); ++i) {\n            if (decipher_rerand_text.first[i] != m_field[i])\n                std::exit(1);\n        }\n        std::cout << \"Decryption finished, decryption proof generated.\" << std::endl;\n\n        std::cout << \"Any voter could verify decryption using decryption proof...\" << std::endl;\n        bool dec_verification_ans = verify_decryption<enc_input_policy::encryption_scheme_type>(\n            rerand_cipher_text.first, decipher_rerand_text.first,\n            {std::get<2>(keypair), gg_keypair, decipher_rerand_text.second});\n        if (!dec_verification_ans)\n            std::exit(1);\n        std::cout << \"Decryption verification finished.\" << std::endl << std::endl;\n        std::cout << \"====================================================================\" << std::endl << std::endl;\n    }\n\n    std::cout << \"Tally results.\" << std::endl;\n    auto ct_it = std::cbegin(ct_n);\n    auto ct_ = ct_it->first;\n    ct_it++;\n    while (ct_it != std::cend(ct_n)) {\n        for (std::size_t i = 0; i < std::size(ct_); ++i) {\n            ct_[i] = ct_[i] + ct_it->first[i];\n        }\n        ct_it++;\n    }\n\n    std::cout << \"Deciphered results of voting:\" << std::endl;\n    typename enc_input_policy::encryption_scheme_type::decipher_type decipher_rerand_sum_text =\n        decrypt<enc_input_policy::encryption_scheme_type,\n                modes::verifiable_encryption<enc_input_policy::encryption_scheme_type>>(\n            ct_, {std::get<1>(keypair), std::get<2>(keypair), gg_keypair});\n    if (decipher_rerand_sum_text.first.size() != enc_input_policy::msg_size)\n        std::exit(1);\n    for (std::size_t i = 0; i < enc_input_policy::msg_size; ++i) {\n        std::cout << decipher_rerand_sum_text.first[i].data << \", \";\n    }\n    std::cout << std::endl;\n\n    std::cout << \"Tally phase marshalling started...\" << std::endl;\n    marshaling_policy::write_tally_phase_data(vm, decipher_rerand_sum_text);\n    std::cout << \"Marshalling finished.\" << std::endl;\n\n    std::cout << \"Verification of the deciphered tally result.\" << std::endl;\n    bool dec_verification_ans = verify_decryption<enc_input_policy::encryption_scheme_type>(\n        ct_, decipher_rerand_sum_text.first, {std::get<2>(keypair), gg_keypair, decipher_rerand_sum_text.second});\n    if (!dec_verification_ans)\n        std::exit(1);\n    std::cout << \"Verification succeeded\" << std::endl;\n}\n\nvoid process_encrypted_input_mode_init_voter_phase(const boost::program_options::variables_map &vm) {\n    using scalar_field_value_type = typename enc_input_policy::pairing_curve_type::scalar_field_type::value_type;\n\n    std::size_t proof_idx = vm[\"voter-idx\"].as<std::size_t>();\n    std::cout << \"Voter \" << proof_idx << \" generates its public and secret keys...\" << std::endl << std::endl;\n\n    auto secret_keys = generate_random_data<bool, enc_input_policy::secret_key_bits>(1);\n    std::vector<std::array<bool, enc_input_policy::public_key_bits>> public_keys;\n    std::array<bool, enc_input_policy::hash_type::digest_bits> pk {};\n    hash<enc_input_policy::merkle_hash_type>(secret_keys[0], std::begin(pk));\n    public_keys.emplace_back(pk);\n    std::vector<scalar_field_value_type> pk_field;\n    std::vector<scalar_field_value_type> sk_field;\n    std::cout << \"Public key of the Voter \" << proof_idx << \": \";\n    for (auto c : pk) {\n        std::cout << int(c);\n        pk_field.emplace_back(int(c));\n    }\n    for (auto c : secret_keys[0]) {\n        sk_field.emplace_back(int(c));\n    }\n    std::cout << std::endl;\n    marshaling_policy::write_initial_phase_voter_data(vm, pk_field, sk_field, proof_idx);\n    std::cout << \"Participants key pairs generated.\" << std::endl;\n}\n\nvoid process_encrypted_input_mode_init_admin_phase(const boost::program_options::variables_map &vm) {\n    using scalar_field_value_type = typename enc_input_policy::pairing_curve_type::scalar_field_type::value_type;\n\n    std::cout << \"Administrator pre-initializes voting session...\" << std::endl << std::endl;\n\n    std::size_t tree_depth = 0;\n    if (vm.count(\"tree-depth\")) {\n        tree_depth = vm[\"tree-depth\"].as<std::size_t>();\n    } else {\n        std::cerr << \"Tree depth is not specified!\" << std::endl;\n        return;\n    }\n\n    std::cout << \"Merkle tree generation upon participants public keys started...\" << std::endl;\n    auto public_keys = marshaling_policy::read_voters_public_keys(vm);\n    containers::merkle_tree<enc_input_policy::merkle_hash_type, enc_input_policy::arity> tree(public_keys);\n    std::vector<scalar_field_value_type> rt_field;\n    for (auto i : tree.root()) {\n        rt_field.emplace_back(int(i));\n    }\n    std::cout << \"Merkle tree generation finished.\" << std::endl;\n\n    const std::size_t eid_size = 64;\n    std::vector<bool> eid(eid_size);\n    std::vector<scalar_field_value_type> eid_field;\n    std::generate(eid.begin(), eid.end(), [&]() { return std::rand() % 2; });\n    std::cout << \"Voting session (eid) is: \";\n    for (auto i : eid) {\n        std::cout << int(i);\n        eid_field.emplace_back(int(i));\n    }\n    std::cout << std::endl;\n\n    std::cout << \"Voting system administrator generates R1CS...\" << std::endl;\n    components::blueprint<enc_input_policy::field_type> bp;\n    components::block_variable<enc_input_policy::field_type> m_block(bp, enc_input_policy::msg_size);\n    components::block_variable<enc_input_policy::field_type> eid_block(bp, eid.size());\n    components::digest_variable<enc_input_policy::field_type> sn_digest(bp,\n                                                                        enc_input_policy::hash_component::digest_bits);\n    components::digest_variable<enc_input_policy::field_type> root_digest(\n        bp, enc_input_policy::merkle_hash_component::digest_bits);\n    components::blueprint_variable_vector<enc_input_policy::field_type> address_bits_va;\n    address_bits_va.allocate(bp, tree_depth);\n    enc_input_policy::merkle_proof_component path_var(bp, tree_depth);\n    components::block_variable<enc_input_policy::field_type> sk_block(bp, enc_input_policy::secret_key_bits);\n    enc_input_policy::voting_component vote_var(bp, m_block, eid_block, sn_digest, root_digest, address_bits_va,\n                                                path_var, sk_block,\n                                                components::blueprint_variable<enc_input_policy::field_type>(0));\n    path_var.generate_r1cs_constraints();\n    vote_var.generate_r1cs_constraints();\n    std::cout << \"R1CS generation finished.\" << std::endl;\n    std::cout << \"Constraints number in the generated R1CS: \" << bp.num_constraints() << std::endl;\n    bp.set_input_sizes(vote_var.get_input_size());\n\n    std::cout << \"Administrator generates CRS...\" << std::endl;\n    typename enc_input_policy::proof_system::keypair_type gg_keypair =\n        snark::generate<enc_input_policy::proof_system>(bp.get_constraint_system());\n    std::cout << \"CRS generation finished.\" << std::endl;\n\n    std::cout << \"Administrator generates private, public and verification keys for El-Gamal verifiable encryption \"\n                 \"scheme...\"\n              << std::endl;\n    random::algebraic_random_device<typename enc_input_policy::pairing_curve_type::scalar_field_type> d;\n    std::vector<scalar_field_value_type> rnd;\n    for (std::size_t i = 0; i < enc_input_policy::msg_size * 3 + 2; ++i) {\n        rnd.emplace_back(d());\n    }\n    typename enc_input_policy::encryption_scheme_type::keypair_type keypair =\n        generate_keypair<enc_input_policy::encryption_scheme_type,\n                         modes::verifiable_encryption<enc_input_policy::encryption_scheme_type>>(\n            rnd, {gg_keypair, enc_input_policy::msg_size});\n    std::cout << \"Private, public and verification keys for El-Gamal verifiable encryption scheme generated.\"\n              << std::endl\n              << std::endl;\n    std::cout << \"====================================================================\" << std::endl << std::endl;\n\n    std::cout << \"Pre-init administrator marshalling started...\" << std::endl;\n    marshaling_policy::write_initial_phase_admin_data(vm, gg_keypair.first, gg_keypair.second, std::get<0>(keypair),\n                                                      std::get<1>(keypair), std::get<2>(keypair), eid_field, rt_field);\n    std::cout << \"Marshalling finished.\" << std::endl;\n}\n\nvoid process_encrypted_input_mode_vote_phase(const boost::program_options::variables_map &vm) {\n    using scalar_field_value_type = typename enc_input_policy::pairing_curve_type::scalar_field_type::value_type;\n\n    std::size_t tree_depth = 0;\n    if (vm.count(\"tree-depth\")) {\n        tree_depth = vm[\"tree-depth\"].as<std::size_t>();\n    } else {\n        std::cerr << \"Tree depth is not specified!\" << std::endl;\n        return;\n    }\n    std::size_t participants_number = 1 << tree_depth;\n\n    std::size_t proof_idx = vm[\"voter-idx\"].as<std::size_t>();\n    if (participants_number <= proof_idx) {\n        std::cerr << \"participants_number <= voter_idx\" << std::endl;\n        std::exit(1);\n    }\n    std::cout << \"Voter \" << proof_idx << \" generate encrypted ballot\" << std::endl << std::endl;\n\n    std::cout << \"Participant with index \" << proof_idx << \" (vote sender) generates its merkle copath.\" << std::endl;\n    auto public_keys = marshaling_policy::read_voters_public_keys(vm);\n    containers::merkle_tree<enc_input_policy::merkle_hash_type, enc_input_policy::arity> tree(public_keys);\n    std::vector<scalar_field_value_type> rt_field;\n    for (auto i : tree.root()) {\n        rt_field.emplace_back(int(i));\n    }\n    if (rt_field != marshaling_policy::read_scalar_vector(vm[\"rt-output\"].as<std::string>())) {\n        std::exit(2);\n    }\n    containers::merkle_proof<enc_input_policy::merkle_hash_type, enc_input_policy::arity> path(tree, proof_idx);\n    auto tree_pk_leaf = tree[proof_idx];\n\n    std::vector<bool> m(enc_input_policy::msg_size, false);\n    m[std::rand() % m.size()] = true;\n    std::cout << \"Voter \" << proof_idx << \" is willing to vote with the following ballot: { \";\n    for (auto m_i : m) {\n        std::cout << int(m_i);\n    }\n    std::cout << \" }\" << std::endl;\n    std::vector<typename enc_input_policy::pairing_curve_type::scalar_field_type::value_type> m_field;\n    m_field.reserve(m.size());\n    for (const auto m_i : m) {\n        m_field.emplace_back(std::size_t(m_i));\n    }\n\n    auto eid = marshaling_policy::read_bool_vector(vm[\"eid-output\"].as<std::string>());\n    auto sk = marshaling_policy::read_bool_vector(vm[\"voter-secret-key-output\"].as<std::string>() +\n                                                  std::to_string(proof_idx));\n    std::vector<bool> eid_sk;\n    std::copy(std::cbegin(eid), std::cend(eid), std::back_inserter(eid_sk));\n    std::copy(std::cbegin(sk), std::cend(sk), std::back_inserter(eid_sk));\n    std::vector<bool> sn = hash<enc_input_policy::hash_type>(eid_sk);\n    std::cout << \"Sender has following serial number (sn) in current session: \";\n    for (auto i : sn) {\n        std::cout << int(i);\n    }\n    std::cout << std::endl;\n\n    components::blueprint<enc_input_policy::field_type> bp;\n    components::block_variable<enc_input_policy::field_type> m_block(bp, enc_input_policy::msg_size);\n    components::block_variable<enc_input_policy::field_type> eid_block(bp, eid.size());\n    components::digest_variable<enc_input_policy::field_type> sn_digest(bp,\n                                                                        enc_input_policy::hash_component::digest_bits);\n    components::digest_variable<enc_input_policy::field_type> root_digest(\n        bp, enc_input_policy::merkle_hash_component::digest_bits);\n    components::blueprint_variable_vector<enc_input_policy::field_type> address_bits_va;\n    address_bits_va.allocate(bp, tree_depth);\n    enc_input_policy::merkle_proof_component path_var(bp, tree_depth);\n    components::block_variable<enc_input_policy::field_type> sk_block(bp, enc_input_policy::secret_key_bits);\n    enc_input_policy::voting_component vote_var(bp, m_block, eid_block, sn_digest, root_digest, address_bits_va,\n                                                path_var, sk_block,\n                                                components::blueprint_variable<enc_input_policy::field_type>(0));\n    path_var.generate_r1cs_constraints();\n    vote_var.generate_r1cs_constraints();\n    std::cout << \"R1CS generation finished.\" << std::endl;\n    std::cout << \"Constraints number in the generated R1CS: \" << bp.num_constraints() << std::endl;\n    bp.set_input_sizes(vote_var.get_input_size());\n\n    // BOOST_ASSERT(!bp.is_satisfied());\n    path_var.generate_r1cs_witness(path, true);\n    if (bp.is_satisfied())\n        std::exit(1);\n    address_bits_va.fill_with_bits_of_ulong(bp, path_var.address);\n    if (bp.is_satisfied())\n        std::exit(1);\n    if (address_bits_va.get_field_element_from_bits(bp) != path_var.address)\n        std::exit(1);\n    m_block.generate_r1cs_witness(m);\n    if (bp.is_satisfied())\n        std::exit(1);\n    eid_block.generate_r1cs_witness(eid);\n    if (bp.is_satisfied())\n        std::exit(1);\n    sk_block.generate_r1cs_witness(sk);\n    if (bp.is_satisfied())\n        std::exit(1);\n    vote_var.generate_r1cs_witness(tree.root(), sn);\n    if (!bp.is_satisfied())\n        std::exit(1);\n\n    std::cout << \"Voter \" << proof_idx << \" generates its vote consisting of proof and cipher text...\" << std::endl;\n    random::algebraic_random_device<typename enc_input_policy::pairing_curve_type::scalar_field_type> d;\n    auto pk_eid = marshaling_policy::read_pk_eid(vm);\n    typename enc_input_policy::proof_system::keypair_type gg_keypair = {marshaling_policy::read_pk_crs(vm),\n                                                                        marshaling_policy::read_vk_crs(vm)};\n    typename enc_input_policy::encryption_scheme_type::cipher_type cipher_text =\n        encrypt<enc_input_policy::encryption_scheme_type,\n                modes::verifiable_encryption<enc_input_policy::encryption_scheme_type>>(\n            m_field, {d(), pk_eid, gg_keypair, bp.primary_input(), bp.auxiliary_input()});\n    std::cout << \"Vote generated.\" << std::endl;\n\n    std::cout << \"Rerandomization of the cipher text and proof started...\" << std::endl;\n    std::vector<typename enc_input_policy::pairing_curve_type::scalar_field_type::value_type> rnd_rerandomization;\n    for (std::size_t i = 0; i < 3; ++i) {\n        rnd_rerandomization.emplace_back(d());\n    }\n    typename enc_input_policy::encryption_scheme_type::cipher_type rerand_cipher_text =\n        rerandomize<enc_input_policy::encryption_scheme_type>(rnd_rerandomization, cipher_text.first,\n                                                              {pk_eid, gg_keypair, cipher_text.second});\n    std::cout << \"Rerandomization finished.\" << std::endl;\n\n    std::cout << \"Voter \" << proof_idx << \" marshalling started...\" << std::endl;\n    std::size_t eid_offset = m.size();\n    std::size_t sn_offset = eid_offset + eid.size();\n    std::size_t rt_offset = sn_offset + sn.size();\n    std::size_t rt_offset_end = rt_offset + tree.root().size();\n    typename enc_input_policy::proof_system::primary_input_type pinput = bp.primary_input();\n    marshaling_policy::write_data(proof_idx, vm, gg_keypair.second, pk_eid, rerand_cipher_text.second,\n                                  typename enc_input_policy::proof_system::primary_input_type {\n                                      std::cbegin(pinput) + eid_offset, std::cend(pinput)},\n                                  rerand_cipher_text.first,\n                                  typename enc_input_policy::proof_system::primary_input_type {\n                                      std::cbegin(pinput) + eid_offset, std::cbegin(pinput) + sn_offset},\n                                  typename enc_input_policy::proof_system::primary_input_type {\n                                      std::cbegin(pinput) + sn_offset, std::cbegin(pinput) + rt_offset},\n                                  typename enc_input_policy::proof_system::primary_input_type {\n                                      std::cbegin(pinput) + rt_offset, std::cbegin(pinput) + rt_offset_end});\n    std::cout << \"Marshalling finished.\" << std::endl;\n\n    std::cout << \"Sender verifies rerandomized encrypted ballot and proof...\" << std::endl;\n    bool enc_verification_ans = verify_encryption<enc_input_policy::encryption_scheme_type>(\n        rerand_cipher_text.first,\n        {pk_eid, gg_keypair.second, rerand_cipher_text.second,\n         typename enc_input_policy::proof_system::primary_input_type {std::cbegin(pinput) + m.size(),\n                                                                      std::cend(pinput)}});\n    if (!enc_verification_ans)\n        std::exit(1);\n    std::cout << \"Encryption verification of rerandomazed cipher text and proof finished.\" << std::endl;\n}\n\nvoid process_encrypted_input_mode_vote_verify_phase(const boost::program_options::variables_map &vm) {\n}\n\nvoid process_encrypted_input_mode_tally_admin_phase(const boost::program_options::variables_map &vm) {\n    std::cout << \"Administrator processes tally phase - aggregates encrypted ballots, decrypts aggregated ballot, \"\n                 \"generate decryption proof...\"\n              << std::endl\n              << std::endl;\n\n    std::size_t tree_depth = 0;\n    if (vm.count(\"tree-depth\")) {\n        tree_depth = vm[\"tree-depth\"].as<std::size_t>();\n    } else {\n        std::cerr << \"Tree depth is not specified!\" << std::endl;\n        return;\n    }\n    std::size_t participants_number = 1 << tree_depth;\n\n    auto ct_agg = marshaling_policy::read_ct(vm, 0);\n    for (auto proof_idx = 1; proof_idx < participants_number; proof_idx++) {\n        auto ct_i = marshaling_policy::read_ct(vm, proof_idx);\n        if (std::size(ct_agg) != std::size(ct_i)) {\n            std::cerr << \"Wrong size of the ct\" << std::endl;\n            std::exit(2);\n        }\n        for (std::size_t i = 0; i < std::size(ct_i); ++i) {\n            ct_agg[i] = ct_agg[i] + ct_i[i];\n        }\n    }\n\n    auto sk_eid = marshaling_policy::read_sk_eid(vm);\n    auto vk_eid = marshaling_policy::read_vk_eid(vm);\n    typename enc_input_policy::proof_system::keypair_type gg_keypair = {marshaling_policy::read_pk_crs(vm),\n                                                                        marshaling_policy::read_vk_crs(vm)};\n    std::cout << \"Deciphered results of voting:\" << std::endl;\n    typename enc_input_policy::encryption_scheme_type::decipher_type decipher_rerand_sum_text =\n        decrypt<enc_input_policy::encryption_scheme_type,\n                modes::verifiable_encryption<enc_input_policy::encryption_scheme_type>>(ct_agg,\n                                                                                        {sk_eid, vk_eid, gg_keypair});\n    if (decipher_rerand_sum_text.first.size() != enc_input_policy::msg_size) {\n        std::cerr << \"Deciphered lens not equal\" << decipher_rerand_sum_text.first.size()\n                  << \" != \" << enc_input_policy::msg_size << std::endl;\n        std::exit(1);\n    }\n    for (std::size_t i = 0; i < enc_input_policy::msg_size; ++i) {\n        std::cout << decipher_rerand_sum_text.first[i].data << \", \";\n    }\n    std::cout << std::endl;\n\n    std::cout << \"Tally phase marshalling started...\" << std::endl;\n    marshaling_policy::write_tally_phase_data(vm, decipher_rerand_sum_text);\n    std::cout << \"Marshalling finished.\" << std::endl;\n}\n\nvoid process_encrypted_input_mode_tally_voter_phase(const boost::program_options::variables_map &vm) {\n    std::cout << \"Voter processes tally phase - aggregates encrypted ballots, verifies voting result using decryption \"\n                 \"proof...\"\n              << std::endl\n              << std::endl;\n\n    std::size_t tree_depth = 0;\n    if (vm.count(\"tree-depth\")) {\n        tree_depth = vm[\"tree-depth\"].as<std::size_t>();\n    } else {\n        std::cerr << \"Tree depth is not specified!\" << std::endl;\n        return;\n    }\n    std::size_t participants_number = 1 << tree_depth;\n\n    auto ct_agg = marshaling_policy::read_ct(vm, 0);\n    for (auto proof_idx = 1; proof_idx < participants_number; proof_idx++) {\n        auto ct_i = marshaling_policy::read_ct(vm, proof_idx);\n        if (std::size(ct_agg) != std::size(ct_i)) {\n            std::cerr << \"Wrong size of the ct\" << std::endl;\n            std::exit(2);\n        }\n        for (std::size_t i = 0; i < std::size(ct_i); ++i) {\n            ct_agg[i] = ct_agg[i] + ct_i[i];\n        }\n    }\n\n    auto vk_eid = marshaling_policy::read_vk_eid(vm);\n    typename enc_input_policy::proof_system::keypair_type gg_keypair = {marshaling_policy::read_pk_crs(vm),\n                                                                        marshaling_policy::read_vk_crs(vm)};\n    auto voting_result = marshaling_policy::read_scalar_vector(vm[\"voting-result-output\"].as<std::string>());\n    auto dec_proof = marshaling_policy::read_decryption_proof(vm);\n    std::cout << \"Verification of the deciphered tally result.\" << std::endl;\n    bool dec_verification_ans = verify_decryption<enc_input_policy::encryption_scheme_type>(\n        ct_agg, voting_result, {vk_eid, gg_keypair, dec_proof});\n    if (!dec_verification_ans)\n        std::exit(1);\n    std::cout << \"Verification succeeded\" << std::endl;\n    std::cout << \"Results of voting:\" << std::endl;\n    for (std::size_t i = 0; i < enc_input_policy::msg_size; ++i) {\n        std::cout << voting_result[i].data << \", \";\n    }\n    std::cout << std::endl;\n}\n\nint main(int argc, char *argv[]) {\n    std::srand(std::time(0));\n\n    std::string mode;\n    std::size_t tree_depth = 0;\n    boost::program_options::options_description desc(\n        \"R1CS Generic Group PreProcessing Zero-Knowledge Succinct Non-interactive ARgument of Knowledge \"\n        \"(https://eprint.iacr.org/2016/260.pdf) CLI Proof Generator.\");\n    // clang-format off\n    desc.add_options()\n    (\"help,h\", \"Display help message.\")\n    (\"version,v\", \"Display version.\")\n    (\"mode,m\", boost::program_options::value(&mode)->default_value(\"encrypted_input\"),\"Proof system processing mode, allowed values: basic, encrypted_input.\")\n    (\"phase,p\", boost::program_options::value<std::string>(),\"Execute protocol phase, allowed values:\\n\\t - init_voter (generate and write voters public and secret keys),\\n\\t - init_admin (generate and write CRS and ElGamal keys),\\n\\t - vote (read CRS and ElGamal keys, encrypt ballot and generate proof, then write them),\\n\\t - vote_verify (read voters' proofs and encrypted ballots and verify them),\\n\\t - tally_admin (read voters' encrypted ballots, aggregate encrypted ballots, decrypt aggregated ballot and generate decryption proof and write them),\\n\\t - tally_voter (read ElGamal verification and public keys, encrypted ballots, decrypted aggregated ballot, decryption proof and verify them).\")\n    (\"voter-idx,vidx\", boost::program_options::value<std::size_t>()->default_value(0),\"Voter index\")\n    (\"voter-public-key-output,vpko\", boost::program_options::value<std::string>()->default_value(\"voter_public_key\"),\"Voter public key\")\n    (\"voter-secret-key-output,vsko\", boost::program_options::value<std::string>()->default_value(\"voter_secret_key\"),\"Voter secret key\")\n    (\"r1cs-proof-output,rpo\", boost::program_options::value<std::string>()->default_value(\"r1cs_proof\"), \"Proof output path.\")\n    (\"r1cs-primary-input-output,rpio\", boost::program_options::value<std::string>()->default_value(\"r1cs_primary_input\"), \"Primary input output path.\")\n    (\"r1cs-proving-key-output,rpko\", boost::program_options::value<std::string>()->default_value(\"r1cs_proving_key\"), \"Proving key output path.\")\n    (\"r1cs-verification-key-output,rvko\", boost::program_options::value<std::string>()->default_value(\"r1cs_verification_key\"), \"Verification output path.\")\n    (\"r1cs-verifier-input-output,rvio\", boost::program_options::value<std::string>()->default_value(\"r1cs_verification_input\"), \"Verification input output path.\")\n    (\"public-key-output,pko\", boost::program_options::value<std::string>()->default_value(\"pk_eid\"), \"Public key output path (for encrypted_input mode only).\")\n    (\"verification-key-output,vko\", boost::program_options::value<std::string>()->default_value(\"vk_eid\"), \"Verification key output path (for encrypted_input mode only).\")\n    (\"secret-key-output,sko\", boost::program_options::value<std::string>()->default_value(\"sk_eid\"), \"Secret key output path (for encrypted_input mode only).\")\n    (\"cipher-text-output,cto\", boost::program_options::value<std::string>()->default_value(\"cipher_text\"), \"Cipher text output path (for encrypted_input mode only).\")\n    (\"decryption-proof-output,dpo\", boost::program_options::value<std::string>()->default_value(\"decryption_proof\"), \"Decryption proof output path (for encrypted_input mode only).\")\n    (\"voting-result-output,vro\", boost::program_options::value<std::string>()->default_value(\"voting_result\"), \"Voting result output path (for encrypted_input mode only).\")\n    (\"eid-output,eido\", boost::program_options::value<std::string>()->default_value(\"eid\"), \"Session id output path (for encrypted_input mode only).\")\n    (\"sn-output,sno\", boost::program_options::value<std::string>()->default_value(\"sn\"), \"Serial number output path (for encrypted_input mode only).\")\n    (\"rt-output,rto\", boost::program_options::value<std::string>()->default_value(\"rt\"), \"Session id output path (for encrypted_input mode only).\")\n    (\"tree-depth,td\", boost::program_options::value<std::size_t>()->default_value(tree_depth), \"Depth of Merkle tree built upon participants' public keys (for encrypted_input mode only).\");\n    // clang-format on\n\n    boost::program_options::variables_map vm;\n    boost::program_options::store(boost::program_options::command_line_parser(argc, argv).options(desc).run(), vm);\n    boost::program_options::notify(vm);\n\n    if (vm.count(\"help\") || argc < 2) {\n        std::cout << desc << std::endl;\n        return 0;\n    }\n\n    if (!vm.count(\"mode\")) {\n        std::cout << desc << std::endl;\n        return 0;\n    } else if (vm[\"mode\"].as<std::string>() == \"basic\") {\n        using curve_type = algebra::curves::bls12<381>;\n        using scalar_field_type = typename curve_type::scalar_field_type;\n        using endianness = nil::marshalling::option::big_endian;\n        using proof_system_type = zk::snark::r1cs_gg_ppzksnark<curve_type>;\n\n        process_basic_mode<curve_type, endianness, proof_system_type>(vm);\n    } else if (vm[\"mode\"].as<std::string>() == \"encrypted_input\") {\n        if (!vm.count(\"phase\")) {\n            process_encrypted_input_mode(vm);\n        } else {\n            if (vm[\"phase\"].as<std::string>() == \"init_voter\") {\n                process_encrypted_input_mode_init_voter_phase(vm);\n            } else if (vm[\"phase\"].as<std::string>() == \"init_admin\") {\n                process_encrypted_input_mode_init_admin_phase(vm);\n            } else if (vm[\"phase\"].as<std::string>() == \"vote\") {\n                process_encrypted_input_mode_vote_phase(vm);\n            } else if (vm[\"phase\"].as<std::string>() == \"vote_verify\") {\n                process_encrypted_input_mode_vote_verify_phase(vm);\n            } else if (vm[\"phase\"].as<std::string>() == \"tally_admin\") {\n                process_encrypted_input_mode_tally_admin_phase(vm);\n            } else if (vm[\"phase\"].as<std::string>() == \"tally_voter\") {\n                process_encrypted_input_mode_tally_voter_phase(vm);\n            } else {\n                std::cout << desc << std::endl;\n                return 0;\n            }\n        }\n    } else {\n        std::cout << desc << std::endl;\n        return 0;\n    }\n\n    return 0;\n}", "meta": {"hexsha": "44493a85bc0f0ff8fcb7acc23962ac3738a004bd", "size": 73822, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "bin/cli/src/main.cpp", "max_stars_repo_name": "marshall-rhea/ton-voting-protocol", "max_stars_repo_head_hexsha": "01acefb2108d6049504e6b3809ccf2e5b366298e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "bin/cli/src/main.cpp", "max_issues_repo_name": "marshall-rhea/ton-voting-protocol", "max_issues_repo_head_hexsha": "01acefb2108d6049504e6b3809ccf2e5b366298e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "bin/cli/src/main.cpp", "max_forks_repo_name": "marshall-rhea/ton-voting-protocol", "max_forks_repo_head_hexsha": "01acefb2108d6049504e6b3809ccf2e5b366298e", "max_forks_repo_licenses": ["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.3608247423, "max_line_length": 701, "alphanum_fraction": 0.6429113272, "num_tokens": 17171, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7490872243177518, "lm_q2_score": 0.42250463481418826, "lm_q1q2_score": 0.31649282415434565}}
{"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#include <iostream>\n#include <time/date.hpp>\n#include <base/error.hpp>\n#include <base/conversion.hpp>\n#include <boost/date_time/gregorian/gregorian.hpp>\n#include <boost/date_time/posix_time/posix_time_types.hpp>\n\nusing boost::posix_time::ptime;\nusing boost::posix_time::time_duration;\n\nnamespace MathFin {\n\n  // Helper functions used in other parts of the code.\n  namespace {\n    const boost::gregorian::date& serialNumberDateReference() {\n      static const boost::gregorian::date dateReference(\n        1899, boost::gregorian::Dec, 30);\n      return dateReference;\n    }\n\n#define compatibleEnums \\\n    (int(boost::date_time::Monday)      +1 == as_integer(Weekday::Monday) \\\n     && int(boost::date_time::Tuesday)  +1 == as_integer(Weekday::Tuesday) \\\n     && int(boost::date_time::Wednesday)+1 == as_integer(Weekday::Wednesday) \\\n     && int(boost::date_time::Thursday) +1 == as_integer(Weekday::Thursday) \\\n     && int(boost::date_time::Friday)   +1 == as_integer(Weekday::Friday) \\\n     && int(boost::date_time::Saturday) +1 == as_integer(Weekday::Saturday) \\\n     && int(boost::date_time::Sunday)   +1 == as_integer(Weekday::Sunday) \\\n     && int(boost::date_time::Jan) == as_integer(Month::January)        \\\n     && int(boost::date_time::Feb) == as_integer(Month::February)       \\\n     && int(boost::date_time::Mar) == as_integer(Month::March)          \\\n     && int(boost::date_time::Apr) == as_integer(Month::April)          \\\n     && int(boost::date_time::May) == as_integer(Month::May)            \\\n     && int(boost::date_time::Jun) == as_integer(Month::June)           \\\n     && int(boost::date_time::Jul) == as_integer(Month::July)           \\\n     && int(boost::date_time::Aug) == as_integer(Month::August)         \\\n     && int(boost::date_time::Sep) == as_integer(Month::September)      \\\n     && int(boost::date_time::Oct) == as_integer(Month::October)        \\\n     && int(boost::date_time::Nov) == as_integer(Month::November)       \\\n     && int(boost::date_time::Dec) == as_integer(Month::December))\n\n    template <bool compatible>\n    Weekday mapBoostDateType2MF(boost::gregorian::greg_weekday d) {\n      if (compatible) {\n        return Weekday(d.as_number() + 1);\n      } else {\n        switch (d) {\n        case boost::date_time::Monday   : return Weekday::Monday;\n        case boost::date_time::Tuesday  : return Weekday::Tuesday;\n        case boost::date_time::Wednesday: return Weekday::Wednesday;\n        case boost::date_time::Thursday : return Weekday::Thursday;\n        case boost::date_time::Friday   : return Weekday::Friday;\n        case boost::date_time::Saturday : return Weekday::Saturday;\n        case boost::date_time::Sunday   : return Weekday::Sunday;\n        default:\n          MF_FAIL(\"Unknown boost date_time day of week given\");\n        }\n      }\n    }\n\n    template <bool compatible>\n    Month mapBoostDateType2MF(boost::gregorian::greg_month m) {\n      if (compatible) {\n        return Month(m.as_number());\n      } else {\n        switch (m) {\n        case boost::date_time::Jan : return Month::January;\n        case boost::date_time::Feb : return Month::February;\n        case boost::date_time::Mar : return Month::March;\n        case boost::date_time::Apr : return Month::April;\n        case boost::date_time::May : return Month::May;\n        case boost::date_time::Jun : return Month::June;\n        case boost::date_time::Jul : return Month::July;\n        case boost::date_time::Aug : return Month::August;\n        case boost::date_time::Sep : return Month::September;\n        case boost::date_time::Oct : return Month::October;\n        case boost::date_time::Nov : return Month::November;\n        case boost::date_time::Dec : return Month::December;\n        default:\n          MF_FAIL(\"Unknown boost date_time month of week given\");\n        }\n      }\n    }\n\n    template <bool compatible>\n    boost::gregorian::greg_month mapMFDateType2Boost(Month m) {\n      if (compatible) {\n        return boost::gregorian::greg_month(as_integer(m));\n      } else {\n        switch (m) {\n        case Month::January  : return boost::date_time::Jan;\n        case Month::February : return boost::date_time::Feb;\n        case Month::March    : return boost::date_time::Mar;\n        case Month::April    : return boost::date_time::Apr;\n        case Month::May      : return boost::date_time::May;\n        case Month::June     : return boost::date_time::Jun;\n        case Month::July     : return boost::date_time::Jul;\n        case Month::August   : return boost::date_time::Aug;\n        case Month::September: return boost::date_time::Sep;\n        case Month::October  : return boost::date_time::Oct;\n        case Month::November : return boost::date_time::Nov;\n        case Month::December : return boost::date_time::Dec;\n        default:\n          MF_FAIL(\"Unknown boost date_time month of week given\");\n        }\n      }\n    }\n\n    boost::gregorian::date gregorianDate(Year y, Month m, Day d) {\n      MF_REQUIRE(y > 1900 && y < 2200,\n                 \"year \" << y << \" out of bound. It must be in [1901,2199]\");\n      MF_REQUIRE(Integer(m) > 0 && Integer(m) < 13,\n                 \"month \" << Integer(m)\n                 << \" outside January-December range [1,12]\");\n\n      const boost::gregorian::greg_month gregorianMonth =\n        mapMFDateType2Boost<compatibleEnums>(m);\n\n      const Day endOfMonthDay =\n        boost::gregorian::gregorian_calendar::end_of_month_day(y, gregorianMonth);\n      MF_REQUIRE(d <= endOfMonthDay && d > 0,\n                 \"Day outside month (\" << m << \") day-range \"\n                 << \"[1,\" << endOfMonthDay << \"]\");\n\n      return boost::gregorian::date(y, gregorianMonth, d);\n    }\n  }\n\n  // ---------------------------------------------------------------------------\n\n\n  Date::Date() : dateTime_(serialNumberDateReference()) {}\n\n  Date::Date(Date::serial_type serialNumber)\n    : dateTime_(serialNumberDateReference() + boost::gregorian::days(serialNumber)) {\n    checkSerialNumber(serialNumber);\n  }\n\n  Date::Date(Day d, Month m, Year y) : dateTime_(gregorianDate(y, m, d)) {}\n\n  Date::Date(const ptime& localTime) : dateTime_(localTime) {}\n\n  Date::Date(Day d,\n             Month m,\n             Year y,\n             Hour hours,\n             Minute minutes,\n             Second seconds,\n             Millisecond millisec,\n             Microsecond microsec)\n    : dateTime_(\n      gregorianDate(y, m, d),\n      boost::posix_time::time_duration(\n        hours, minutes, seconds,\n        millisec * (time_duration::ticks_per_second()/1000)\n        + microsec*(time_duration::ticks_per_second()/1000000)))\n  {}\n\n  // ---------------------------------------------------------------------------\n\n  Weekday Date::weekday() const {\n    return mapBoostDateType2MF<compatibleEnums>(dateTime_.date().day_of_week());\n  }\n\n  Day Date::dayOfMonth() const {\n    return dateTime_.date().day();\n  }\n\n  Day Date::dayOfYear() const {\n    return dateTime_.date().day_of_year();\n  }\n\n  Month Date::month() const {\n    return mapBoostDateType2MF<compatibleEnums>(dateTime_.date().month());\n  }\n\n  Year Date::year() const {\n    return dateTime_.date().year();\n  }\n\n  Date::serial_type Date::serialNumber() const {\n    const Date::serial_type n = (\n      dateTime_.date() - serialNumberDateReference()).days();\n    checkSerialNumber(n);\n    return n;\n  }\n\n  Hour Date::hours() const {\n    return dateTime_.time_of_day().hours();\n  }\n\n  Minute Date::minutes() const {\n    return dateTime_.time_of_day().minutes();\n  }\n\n  Second Date::seconds() const {\n    return dateTime_.time_of_day().seconds();\n  }\n\n  Millisecond Date::milliseconds() const {\n    return dateTime_.time_of_day().fractional_seconds()\n      / (ticksPerSecond()/1000);\n  }\n\n  Microsecond Date::microseconds() const {\n    return (dateTime_.time_of_day().fractional_seconds()\n            - milliseconds()*(time_duration::ticks_per_second()/1000))\n      / (ticksPerSecond()/1000000);\n  }\n\n  Time Date::fractionOfDay() const {\n    const time_duration t = dateTime_.time_of_day();\n    const Time seconds = (t.hours()*60.0 + t.minutes())*60.0 + t.seconds()\n      + Real(t.fractional_seconds()) / ticksPerSecond();\n    return seconds / 86400.0; // ignore any DST hocus-pocus\n  }\n\n  Time Date::fractionOfSecond() const {\n    return dateTime_.time_of_day().fractional_seconds()\n      / Real(ticksPerSecond());\n  }\n\n  Real Date::lengthOfYear() const {\n    return isLeap(year()) ? 366.0 : 365.0;\n  }\n\n  // ---------------------------------------------------------------------------\n  // static private members.\n\n  Date::serial_type Date::minimumSerialNumber() {\n    return 367;       // Jan 1st, 1901\n  }\n\n  Date::serial_type Date::maximumSerialNumber() {\n    return 109574;    // Dec 31st, 2199\n  }\n\n  void Date::checkSerialNumber(Date::serial_type serialNumber) {\n    // TODO\n    // Need to implement std::ostream& operator<<(std::ostream&, const Date&);\n    /*\n    MF_REQUIRE(serialNumber >= minimumSerialNumber() &&\n               serialNumber <= maximumSerialNumber(),\n               \"Date's serial number (\" << serialNumber << \") outside \"\n               \"allowed range [\" << minimumSerialNumber() <<\n               \"-\" << maximumSerialNumber() << \"], i.e. [\" <<\n               minDate() << \"-\" << maxDate() << \"]\");\n    */\n\n    MF_REQUIRE(serialNumber >= minimumSerialNumber() &&\n               serialNumber <= maximumSerialNumber(),\n               \"Date's serial number (\" << serialNumber << \") outside \"\n               \"allowed range [\" << minimumSerialNumber() <<\n               \", ... ,\" << maximumSerialNumber() << \"]\";\n      );\n  }\n\n  // ---------------------------------------------------------------------------\n  // static public methods\n\n  Date Date::todaysDate() {\n    boost::gregorian::date current_date(boost::gregorian::day_clock::local_day());\n    return Date(\n      Day(current_date.day()),\n      Month(current_date.month().as_number()),\n      Year(current_date.year())\n      );\n  }\n\n  Date Date::minDate() {\n    static const Date minimumDate(minimumSerialNumber());\n    return minimumDate;\n  }\n\n  Date Date::maxDate() {\n    static const Date maximumDate(maximumSerialNumber());\n    return maximumDate;\n  }\n\n  bool Date::isLeap(Year y) {\n    return boost::gregorian::gregorian_calendar::is_leap_year(y);\n  }\n\n  Date Date::endOfMonth(const Date& d) {\n    const Month m = d.month();\n    const Year y = d.year();\n    const Day eoM = boost::gregorian::gregorian_calendar::end_of_month_day(\n      d.year(), mapMFDateType2Boost<compatibleEnums>(d.month()));\n    return Date(eoM, m, y);\n  }\n\n  bool Date::isEndOfMonth(const Date& d) {\n    return d.dayOfMonth() ==\n      boost::gregorian::gregorian_calendar::end_of_month_day(\n        d.year(), mapMFDateType2Boost<compatibleEnums>(d.month()));\n  }\n\n  Date Date::nextWeekday(const Date& d, Weekday dayOfWeek) {\n    Weekday wd = d.weekday();\n    return d + ((wd > dayOfWeek ? 7 : 0) - as_integer(wd) + as_integer(dayOfWeek));\n  }\n\n  Date Date::nthWeekday(Size nth, Weekday dayOfWeek,\n                        Month m, Year y) {\n    MF_REQUIRE(nth>0,\n               \"zeroth day of week in a given (month, year) is undefined\");\n    MF_REQUIRE(nth<6,\n               \"no more than 5 weekday in a given (month, year)\");\n    Weekday first = Date(1, m, y).weekday();\n    Size skip = nth - (dayOfWeek >= first ? 1 : 0);\n    return Date((1 + as_integer(dayOfWeek) + skip * 7) - as_integer(first), m, y);\n  }\n\n  Date Date::localDateTime() {\n    return Date(boost::posix_time::microsec_clock::local_time());\n  }\n\n  Date Date::universalDateTime() {\n    return Date(boost::posix_time::microsec_clock::universal_time());\n  }\n\n  const Size Date::ticksPerSecond() {\n    return time_duration::ticks_per_second();\n  }\n\n  // ---------------------------------------------------------------------------\n  // date algebra\n\n  namespace {\n    void advance(ptime& dt, Integer n, TimeUnit units) {\n      if (units == TimeUnit::Days) {\n        dt += boost::gregorian::days(n);\n      } else if (units == TimeUnit::Weeks) {\n        dt += boost::gregorian::weeks(n);\n      } else if (units == TimeUnit::Months || units == TimeUnit::Years) {\n        const boost::gregorian::date date = dt.date();\n        const Day endOfMonthDay =\n          boost::gregorian::gregorian_calendar::end_of_month_day(\n            date.year(), date.month());\n        if (units == TimeUnit::Months) {\n          dt += boost::gregorian::months(n);\n        } else {\n          dt += boost::gregorian::years(n);\n        }\n        if (date.day() == endOfMonthDay) {\n          // avoid snap-to-end-of-month behavior of boost::date_time\n          const Day newEndOfMonthDay\n            = boost::gregorian::gregorian_calendar::end_of_month_day(\n              dt.date().year(),\n              dt.date().month()\n              );\n          if (newEndOfMonthDay > endOfMonthDay) {\n            dt -= boost::gregorian::days(newEndOfMonthDay - endOfMonthDay);\n          }\n        }\n      } else {\n        MF_FAIL(\"Unsupported time units: \" << units);\n      }\n    }\n  } // end anonymous namespace\n\n  Date Date::operator+(Date::serial_type days) const {\n    return Date(dateTime_ + boost::gregorian::days(days));\n  }\n\n  Date Date::operator-(Date::serial_type days) const {\n    return Date(dateTime_ - boost::gregorian::days(days));\n  }\n\n  Date Date::operator+(const Period& p) const {\n    ptime dateTime = dateTime_;\n    advance(dateTime, p.length(), p.units());\n    return Date(dateTime);\n  }\n\n  Date Date::operator-(const Period& p) const {\n    ptime dateTime = dateTime_;\n    advance(dateTime, -p.length(), p.units());\n    return Date(dateTime);\n  }\n\n  // ---------------------------------------------------------------------------\n\n  // difference in days between dates\n  Date::serial_type operator-(const Date& d1, const Date& d2) {\n    return (d1.dateTime().date() - d2.dateTime().date()).days();\n  }\n\n  // Difference in days (including fraction of days) between dates\n  Time daysBetween(const Date& d1, const Date& d2) {\n    const Date::serial_type days = d2 - d1;\n    return days + d2.fractionOfDay() - d1.fractionOfDay();\n  }\n\n  // ---------------------------------------------------------------------------\n\n  bool operator==(const Date& d1, const Date& d2) {\n    return (d1.dateTime() == d2.dateTime());\n  }\n\n  bool operator!=(const Date& d1, const Date& d2) {\n    return (d1.dateTime() != d2.dateTime());\n  }\n\n  bool operator<(const Date& d1, const Date& d2) {\n    return (d1.dateTime() < d2.dateTime());\n  }\n\n  bool operator<=(const Date& d1, const Date& d2) {\n    return (d1.dateTime() <= d2.dateTime());\n  }\n\n  bool operator>(const Date& d1, const Date& d2) {\n    return (d1.dateTime() > d2.dateTime());\n  }\n\n  bool operator>=(const Date& d1, const Date& d2) {\n    return (d1.dateTime() >= d2.dateTime());\n  }\n\n  // ---------------------------------------------------------------------------\n\n  std::ostream& operator<<(std::ostream& out, const Date& d) {\n    out << d.year() << \"-\"\n        << std::setw(2) << std::setfill('0') << as_integer(d.month()) << \"-\"\n        << std::setw(2) << std::setfill('0') << d.dayOfMonth()\n        << \"T\"\n        << std::setw(2) << std::setfill('0') << d.hours() << \":\"\n        << std::setw(2) << std::setfill('0') << d.minutes() << \":\"\n        << std::setw(2) << std::setfill('0') << d.seconds() << \",\"\n        << std::setw(3) << std::setfill('0') << d.milliseconds()\n        << std::setw(3) << std::setfill('0') << d.microseconds();\n\n    return out;\n  }\n\n  // ---------------------------------------------------------------------------\n\n\n}\n", "meta": {"hexsha": "848f9725094215f6ed76ec294b22188cbebb2b94", "size": 17033, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "time/date.cpp", "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.cpp", "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.cpp", "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": 35.5594989562, "max_line_length": 85, "alphanum_fraction": 0.5931427229, "num_tokens": 4230, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.600188359260205, "lm_q2_score": 0.5273165233795671, "lm_q1q2_score": 0.3164892389779779}}
{"text": "// Copyright 2020 Google LLC\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//     http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\n#include <boost/math/special_functions/beta.hpp>\n#include <boost/program_options.hpp>\n#include <iostream>\n#include <stdexcept>\n\n// Check values of Boost's `ibeta_derivative` implementation using double\n// precision (to match JavaScript as close as possible).\n// https://www.boost.org/doc/libs/1_73_0/libs/math/doc/html/math_toolkit/sf_beta/beta_derivative.html\n\nint main(int argc, char** argv) {\n  // Parameters for the derivative of the regularized incomplete beta function.\n  double a = 0;\n  double b = 0;\n  double x = 0;\n\n  try {\n    namespace po = boost::program_options;\n    po::options_description desc(\"Options\");\n    desc.add_options()(\"help,h\", \"print help message\")(\n        \"a,a\", po::value<double>(&a)->required(), \"parameter a\")(\n        \"b,b\", po::value<double>(&b)->required(), \"parameter b\")(\n        \"x,x\", po::value<double>(&x)->required(), \"parameter x\");\n\n    po::positional_options_description pos_options;\n    pos_options.add(\"a\", 1).add(\"b\", 1).add(\"x\", 1);\n\n    po::variables_map vm;\n    po::store(po::command_line_parser(argc, argv)\n                  .options(desc)\n                  .positional(pos_options)\n                  .run(),\n              vm);\n\n    if (vm.count(\"help\")) {\n      std::cout << \"Calculate ∂/∂x I_x(a, b) in double precision.\\n\"\n                << \"Usage:\\n\"\n                << \"  \" << argv[0] << \" <a> <b> <x>\\n\"\n                << \"  \" << argv[0] << \" --help\\n\";\n      return 1;\n    }\n\n    // Notify about missing arg(s) after --help.\n    po::notify(vm);\n  } catch (std::exception& e) {\n    std::cerr << \"Error: \" << e.what() << \"\\n\";\n    return 1;\n  }\n\n  std::cerr << \"ibeta_derivative(\" << a << \", \" << b << \", \" << x << \")\\n\";\n\n  // Most (all?) JS engines use SSE. In order to match, don't allow Boost to\n  // auto-promote to extended (80 bit) precision.\n  typedef boost::math::policies::policy<\n      boost::math::policies::promote_double<false> >\n      double_policy;\n\n  double ibeta_value = boost::math::ibeta_derivative(a, b, x, double_policy());\n\n  std::cout\n      // Make sure enough digits are printed.\n      << std::setprecision(std::numeric_limits<double>::max_digits10)\n      << ibeta_value << \"\\n\";\n}\n", "meta": {"hexsha": "0b4c01a90259580a0d2fb287eb714c357b456e94", "size": 2753, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "c++/ibeta-derivative-check.cpp", "max_stars_repo_name": "GoogleChromeLabs/lh-metrics-analysis", "max_stars_repo_head_hexsha": "8a50beb35b2158f95216ed9e7f6717cbb28b19b1", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2020-07-07T19:51:38.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-08T17:12:11.000Z", "max_issues_repo_path": "c++/ibeta-derivative-check.cpp", "max_issues_repo_name": "QPC-database/lh-metrics-analysis", "max_issues_repo_head_hexsha": "8a50beb35b2158f95216ed9e7f6717cbb28b19b1", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-07-14T15:40:40.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-21T23:11:41.000Z", "max_forks_repo_path": "c++/ibeta-derivative-check.cpp", "max_forks_repo_name": "QPC-database/lh-metrics-analysis", "max_forks_repo_head_hexsha": "8a50beb35b2158f95216ed9e7f6717cbb28b19b1", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2020-06-15T09:02:33.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-05T17:48:42.000Z", "avg_line_length": 35.2948717949, "max_line_length": 101, "alphanum_fraction": 0.6233200145, "num_tokens": 714, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6001883449573376, "lm_q2_score": 0.5273165233795671, "lm_q1q2_score": 0.3164892314358396}}
{"text": "/*=============================================================================\nCopyright 2018 Pranam Lashkari <plashkari628@gmail.com>\nCopyright 2019 Sarthak Singhal <singhalsarthak2007@gmail.com>\nCopyright 2020 Rohit Ranjan    <rohitrjn629@gmail.com>\n\nDistributed under the Boost Software License, Version 1.0. (See accompanying\nfile License.txt or copy at https://www.boost.org/LICENSE_1_0.txt)\n=============================================================================*/\n\n#ifndef BOOST_ASTRONOMY_COORDINATE_SPHERICAL_COSLAT_DIFFERENTIAL_HPP\n#define BOOST_ASTRONOMY_COORDINATE_SPHERICAL_COSLAT_DIFFERENTIAL_HPP\n\n#include <tuple>\n#include <type_traits>\n\n#include <math.h>\n#include <boost/geometry/strategies/strategy_transform.hpp>\n#include <boost/geometry/core/cs.hpp>\n#include <boost/geometry/geometries/point.hpp>\n#include <boost/geometry/algorithms/transform.hpp>\n#include <boost/geometry/algorithms/equals.hpp>\n#include <boost/static_assert.hpp>\n#include <boost/units/quantity.hpp>\n#include <boost/units/get_dimension.hpp>\n#include <boost/units/systems/si/dimensionless.hpp>\n#include <boost/units/systems/si/plane_angle.hpp>\n\n#include <boost/astronomy/detail/is_base_template_of.hpp>\n#include <boost/astronomy/coordinate/diff/base_differential.hpp>\n#include <boost/astronomy/coordinate/diff/cartesian_differential.hpp>\n#include <boost/astronomy/coordinate/diff/spherical_differential.hpp>\n\n\nnamespace boost { namespace astronomy { namespace coordinate {\n\nnamespace bu = boost::units;\nnamespace bg = boost::geometry;\n\n//!Represents the differential in spherical representation including cos(latitude) term\n//!Uses three components to represent a differential (dlatitude, dlongitude_coslat, ddistance)\n\ntemplate\n<\n    typename CoordinateType = double,\n    typename LatQuantity = bu::quantity<bu::si::plane_angle, CoordinateType>,\n    typename LonQuantity = bu::quantity<bu::si::plane_angle, CoordinateType>,\n    typename DistQuantity = bu::quantity<bu::si::dimensionless, CoordinateType>\n>\nstruct spherical_coslat_differential : public base_differential\n    <3, geometry::cs::spherical<radian>, CoordinateType>\n{\n    ///@cond INTERNAL\n    BOOST_STATIC_ASSERT_MSG(\n        ((std::is_same<typename bu::get_dimension<LatQuantity>::type,\n            bu::plane_angle_dimension>::value) &&\n            (std::is_same<typename bu::get_dimension<LonQuantity>::type,\n            bu::plane_angle_dimension>::value)),\n        \"Latitude and Longitude must be of plane angle type\");\n    BOOST_STATIC_ASSERT_MSG((std::is_floating_point<CoordinateType>::value),\n        \"CoordinateType must be a floating-point type\");\n    ///@endcond\n\npublic:\n    typedef LatQuantity quantity1;\n    typedef LonQuantity quantity2;\n    typedef DistQuantity quantity3;\n\n    //default constructor no initialization\n    spherical_coslat_differential() {}\n\n    //!constructs object from provided components of differential\n    spherical_coslat_differential\n    (\n        LatQuantity const& dlat,\n        LonQuantity const& dlon_coslat,\n        DistQuantity const& ddistance\n    )\n    {\n        this->set_dlat_dlon_coslat_ddist(dlat, dlon_coslat, ddistance);\n    }\n\n    //!constructs object from boost::geometry::model::point object\n    template\n    <\n        std::size_t OtherDimensionCount,\n        typename OtherCoordinateSystem,\n        typename OtherCoordinateType\n    >\n    spherical_coslat_differential\n    (\n        bg::model::point\n        <\n            OtherCoordinateType,\n            OtherDimensionCount,\n            OtherCoordinateSystem\n        > const& pointObject\n    )\n    {\n        bg::model::point<OtherCoordinateType, 3, bg::cs::cartesian> temp;\n        bg::transform(pointObject, temp);\n        bg::transform(temp, this->diff);\n    }\n\n    //copy constructor\n    spherical_coslat_differential\n    (\n        spherical_coslat_differential\n        <\n            CoordinateType,\n            LatQuantity,\n            LonQuantity,\n            DistQuantity\n        > const& other\n    )\n    {\n        this->diff = other.get_differential();\n    }\n\n    // !constructs object from any type of differential\n    template <typename Differential>\n    spherical_coslat_differential(Differential const& other)\n    {\n        BOOST_STATIC_ASSERT_MSG((boost::astronomy::detail::is_base_template_of\n            <boost::astronomy::coordinate::base_differential, Differential>::value),\n            \"No constructor found with given argument type\");\n\n        BOOST_STATIC_ASSERT_MSG(\n        ((std::is_same<typename bu::get_dimension<DistQuantity>::type,\n        typename bu::get_dimension<typename Differential::quantity3>::type>::value)),\n        \"Two differentials must have same dimensions\");\n\n        auto tempDiff = make_spherical_coslat_differential(other);\n        bg::model::point\n        <\n            typename std::conditional\n            <\n                sizeof(CoordinateType) >= sizeof(typename Differential::type),\n                CoordinateType,\n                typename Differential::type\n            >::type,\n            3,\n            bg::cs::spherical<radian>\n        > tempPoint;\n\n        bg::set<0>(tempPoint,\n            static_cast<\n            bu::quantity<bu::si::plane_angle, CoordinateType>\n            >(tempDiff.get_dlat()).value());\n        bg::set<1>(tempPoint,\n            static_cast<\n            bu::quantity<bu::si::plane_angle, CoordinateType>\n            >(tempDiff.get_dlon_coslat()).value());\n        bg::set<2>(tempPoint,\n            static_cast<DistQuantity>(tempDiff.get_ddist()).value());\n\n        this->diff = tempPoint;\n    }\n\n    //! returns the (dlat, dlon_coslat, ddistance) in the form of tuple\n    std::tuple<LatQuantity, LonQuantity, DistQuantity> get_dlat_dlon_coslat_ddist() const\n    {\n        return std::make_tuple(this->get_dlat(), this->get_dlon_coslat(),\n            this->get_ddist());\n    }\n\n    //!returns the dlat component of differential\n    LatQuantity get_dlat() const\n    {\n        return static_cast<LatQuantity>\n            (\n                bu::quantity<bu::si::plane_angle, CoordinateType>::from_value\n                    (bg::get<0>(this->diff))\n            );\n    }\n\n    //!returns the dlon_coslat component of differential\n    LonQuantity get_dlon_coslat() const\n    {\n        return static_cast<LonQuantity>\n            (\n                bu::quantity<bu::si::plane_angle, CoordinateType>::from_value\n                    (bg::get<1>(this->diff))\n            );\n    }\n\n    //!returns the ddistance component of differential\n    DistQuantity get_ddist() const\n    {\n        return DistQuantity::from_value(bg::get<2>(this->diff));\n    }\n\n    //!set value of (dlat, dlon_coslat, ddistance) in current object\n    void set_dlat_dlon_coslat_ddist\n    (\n        LatQuantity const& dlat,\n        LonQuantity const& dlon_coslat,\n        DistQuantity const& ddistance\n    )\n    {\n        this->set_dlat(dlat);\n        this->set_dlon_coslat(dlon_coslat);\n        this->set_ddist(ddistance);\n    }\n\n    //!set value of dlat component of differential\n    void set_dlat(LatQuantity const& dlat)\n    {\n        bg::set<0>\n            (\n            this->diff,\n            static_cast<bu::quantity<bu::si::plane_angle, CoordinateType>>(dlat).value()\n            );\n    }\n\n    //!set value of dlon_coslat component of differential\n    void set_dlon_coslat(LonQuantity const& dlon_coslat)\n    {\n        bg::set<1>\n            (\n            this->diff,\n            static_cast<bu::quantity<bu::si::plane_angle, CoordinateType>>\n                (dlon_coslat).value()\n            );\n    }\n\n    //!set value of ddistance component of differential\n    void set_ddist(DistQuantity const& ddistance)\n    {\n        bg::set<2>(this->diff, ddistance.value());\n    }\n\n    //!operator for addition of differential\n    template\n    <\n        typename Addend\n    >\n    spherical_coslat_differential\n    <\n        CoordinateType,\n        LatQuantity,\n        LonQuantity,\n        DistQuantity\n    >\n    operator +(Addend const& addend) const\n    {\n        auto cartesian1 = make_cartesian_differential\n            <CoordinateType, DistQuantity, DistQuantity, DistQuantity>(this->diff);\n        auto cartesian2 = make_cartesian_differential(addend);\n\n        auto temp = cartesian1 + cartesian2;\n\n        spherical_coslat_differential\n        <\n            CoordinateType,\n            LatQuantity,\n            LonQuantity,\n            DistQuantity\n        > result = make_spherical_coslat_differential(temp);\n\n        return result;\n    }\n\n    //!operator for multiplication of differential\n    template\n    <\n        typename OtherQuantity\n    >\n    auto operator *(OtherQuantity const& dt) const\n    {\n\n        spherical_coslat_differential\n            <CoordinateType, LatQuantity, LonQuantity, DistQuantity> temp(this->diff);\n\n        spherical_coslat_differential\n        <\n            CoordinateType,\n            LatQuantity,\n            LonQuantity,\n            bu::quantity<typename bu::multiply_typeof_helper\n            <\n                typename DistQuantity::unit_type,\n                typename OtherQuantity::unit_type>::type,\n                CoordinateType\n            >\n        > product\n        (\n            temp.get_dlat(),\n            temp.get_dlon_coslat(),\n            temp.get_ddist() * dt\n        );\n\n        return product;\n    }\n}; //spherical_coslat_differential\n\n//!constructs object from provided components of differential\ntemplate\n<\n    typename CoordinateType,\n    template <typename Unit1, typename CoordinateType_> class LatQuantity,\n    template <typename Unit2, typename CoordinateType_> class LonQuantity,\n    template <typename Unit3, typename CoordinateType_> class DistQuantity,\n    typename Unit1,\n    typename Unit2,\n    typename Unit3\n>\nspherical_coslat_differential\n<\n    CoordinateType,\n    LatQuantity<Unit1, CoordinateType>,\n    LonQuantity<Unit2, CoordinateType>,\n    DistQuantity<Unit3, CoordinateType>\n>\nmake_spherical_coslat_differential\n(\n    LatQuantity<Unit1, CoordinateType> const& dlat,\n    LonQuantity<Unit2, CoordinateType> const& dlon_coslat,\n    DistQuantity<Unit3, CoordinateType> const& ddist\n)\n{\n    return spherical_coslat_differential\n        <\n            CoordinateType,\n            LatQuantity<Unit1, CoordinateType>,\n            LonQuantity<Unit2, CoordinateType>,\n            DistQuantity<Unit3, CoordinateType>\n        >(dlat, dlon_coslat, ddist);\n}\n\n//!constructs object from provided components of differential with different units\ntemplate\n<\n    typename ReturnCoordinateType,\n    typename ReturnLatQuantity,\n    typename ReturnLonQuantity,\n    typename ReturnDistQuantity,\n    typename CoordinateType,\n    typename LatQuantity,\n    typename LonQuantity,\n    typename DistQuantity\n>\nspherical_coslat_differential\n<\n    ReturnCoordinateType,\n    ReturnLatQuantity,\n    ReturnLonQuantity,\n    ReturnDistQuantity\n>\nmake_spherical_coslat_differential\n(\n    spherical_coslat_differential\n    <\n        CoordinateType,\n        LatQuantity,\n        LonQuantity,\n        DistQuantity\n    > const& other\n)\n{\n    return make_spherical_coslat_differential(\n        static_cast<ReturnLatQuantity>(other.get_dlat()),\n        static_cast<ReturnLonQuantity>(other.get_dlon_coslat()),\n        static_cast<ReturnDistQuantity>(other.get_ddist())\n    );\n}\n\n//!constructs object from provided differential\ntemplate\n<\n    typename CoordinateType,\n    typename LatQuantity,\n    typename LonQuantity,\n    typename DistQuantity\n>\nspherical_coslat_differential\n<\n    CoordinateType,\n    LatQuantity,\n    LonQuantity,\n    DistQuantity\n>\nmake_spherical_coslat_differential\n(\n    spherical_coslat_differential\n    <\n        CoordinateType,\n        LatQuantity,\n        LonQuantity,\n        DistQuantity\n    > const& other\n)\n{\n    return spherical_coslat_differential\n        <\n            CoordinateType,\n            LatQuantity,\n            LonQuantity,\n            DistQuantity\n        >(other);\n}\n\n//!constructs object from boost::geometry::model::point object\ntemplate\n<\n    typename CoordinateType = double,\n    typename LatQuantity = bu::quantity<bu::si::plane_angle, CoordinateType>,\n    typename LonQuantity = bu::quantity<bu::si::plane_angle, CoordinateType>,\n    typename DistQuantity = bu::quantity<bu::si::dimensionless, CoordinateType>,\n    std::size_t OtherDimensionCount,\n    typename OtherCoordinateSystem,\n    typename OtherCoordinateType\n>\nspherical_coslat_differential\n<\n    CoordinateType,\n    LatQuantity,\n    LonQuantity,\n    DistQuantity\n>\nmake_spherical_coslat_differential\n(\n    bg::model::point\n    <\n        OtherCoordinateType,\n        OtherDimensionCount,\n        OtherCoordinateSystem\n    > const& pointObject\n)\n{\n    return spherical_coslat_differential\n        <\n            CoordinateType,\n            LatQuantity,\n            LonQuantity,\n            DistQuantity\n        >(pointObject);\n}\n\n//!constructs object from any type of differential\ntemplate\n<\n    typename OtherDifferential\n>\nauto make_spherical_coslat_differential\n(\n    OtherDifferential const& other\n)\n{\n    auto temp = make_spherical_differential(other);\n    typedef decltype(temp) spherical_type;\n\n    temp.set_dlon(temp.get_dlon() * cos(static_cast<bu::quantity\n        <bu::si::plane_angle, typename spherical_type::type>>(temp.get_dlat()).value()));\n\n    return spherical_coslat_differential\n        <\n            typename spherical_type::type,\n            bu::quantity<bu::si::plane_angle, typename spherical_type::type>,\n            bu::quantity<bu::si::plane_angle, typename spherical_type::type>,\n            typename spherical_type::quantity3\n        >(temp.get_differential());\n}\n\n//!constructs cartesian object from spherical_coslat_differential\n//function placed in this file to avoid circular dependency of header files\ntemplate\n<\n    typename CoordinateType,\n    template <typename Unit1, typename CoordinateType_> class LatQuantity,\n    template <typename Unit2, typename CoordinateType_> class LonQuantity,\n    template <typename Unit3, typename CoordinateType_> class DistQuantity,\n    typename Unit1,\n    typename Unit2,\n    typename Unit3\n>\nauto\nmake_cartesian_differential\n(\n    spherical_coslat_differential\n    <\n        CoordinateType,\n        LatQuantity<Unit1, CoordinateType>,\n        LonQuantity<Unit2, CoordinateType>,\n        DistQuantity<Unit3, CoordinateType>\n    > const& other\n)\n{\n    typedef spherical_coslat_differential\n    <\n        CoordinateType,\n        LatQuantity<Unit1, CoordinateType>,\n        LonQuantity<Unit2, CoordinateType>,\n        DistQuantity<Unit3, CoordinateType>\n    > spherical_type;\n    bg::model::point<typename spherical_type::type, 3, bg::cs::spherical<radian>> temp;\n\n    temp = other.get_differential();\n\n    bg::set<1>(temp, bg::get<1>(temp) / cos(bg::get<0>(temp)));\n\n    return cartesian_differential\n    <\n        typename spherical_type::type,\n        typename spherical_type::quantity3,\n        typename spherical_type::quantity3,\n        typename spherical_type::quantity3\n    >(temp);\n}\n\n}}} //namespace boost::astronomy::coordinate\n\n#endif // !BOOST_ASTRONOMY_COORDINATE_SPHERICAL_COSLAT_DIFFERENTIAL_HPP\n\n", "meta": {"hexsha": "9c0ab4fc5659e012b3c24b115032c556225eae10", "size": 15026, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/astronomy/coordinate/diff/spherical_coslat_differential.hpp", "max_stars_repo_name": "nitink25/astronomy", "max_stars_repo_head_hexsha": "0a1d137171b08d1014d4ff138b2a40a146f4f39b", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 75.0, "max_stars_repo_stars_event_min_datetime": "2019-05-14T13:53:02.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-03T20:37:18.000Z", "max_issues_repo_path": "include/boost/astronomy/coordinate/diff/spherical_coslat_differential.hpp", "max_issues_repo_name": "Zyro9922/astronomy", "max_issues_repo_head_hexsha": "56be0f8dfb103520ffbec0b793a92a531cd4b714", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 96.0, "max_issues_repo_issues_event_min_datetime": "2019-05-28T17:46:00.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-09T07:59:17.000Z", "max_forks_repo_path": "include/boost/astronomy/coordinate/diff/spherical_coslat_differential.hpp", "max_forks_repo_name": "Zyro9922/astronomy", "max_forks_repo_head_hexsha": "56be0f8dfb103520ffbec0b793a92a531cd4b714", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 29.0, "max_forks_repo_forks_event_min_datetime": "2019-05-13T21:09:50.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-04T06:24:39.000Z", "avg_line_length": 29.233463035, "max_line_length": 94, "alphanum_fraction": 0.66345002, "num_tokens": 3325, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6584175139669997, "lm_q2_score": 0.480478678047907, "lm_q1q2_score": 0.31635557671445336}}
{"text": "/*\nCopyright 2017 InitialDLab\n\nPermission is hereby granted, free of charge, to any person obtaining a copy of\nthis software and associated documentation files (the \"Software\"), to deal in\nthe Software without restriction, including without limitation the rights to\nuse, copy, modify, merge, publish, distribute, sublicense, and/or sell copies\nof the Software, and to permit persons to whom the Software is furnished to do\nso, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n*/\n#include \"aggragate_experiments.h\"\n\n#include <vector>\n#include <random>\n\n#include <boost/date_time/posix_time/posix_time.hpp>\n\n#include \"mongo_types.h\"\n#include \"experiments/Data_Source_Information.h\"\n#include \"experiments/experiment_utilities.h\"\n#include \"rtree/rtree.h\"\n\n// this experiment is using chernoff bounds to calculate expected error\n// delta is the expected probability of failure\n// alpha is the expected variation between the actual value and aggregated value\n// spread is the maximum - minimum value\n// omega is 2 * alpha / spread  (this is used to quantify error under various spreads)\n// r is the number of samples used for an aggregation.\n\nvoid aggragate_experiments::perform_listed_experiments_GEO()\n{\n    // experiment settings for easy modification\n    int n = 100; // the number of regions to test\n    long seed = 1L; // the seed to use.  Change for actual experiment;\n    float min_query_size = 0.01;\n    float max_query_size = 0.30;\n    std::uniform_real_distribution<float> cover_distribution(min_query_size, max_query_size);\n    std::default_random_engine generator;\n    generator.seed(seed);\n\n\n    std::vector<double> delta_to_test{ 0.10, 0.20, 0.30, 0.40, 0.50, 0.60, 0.70, 0.80 };\n    std::vector<double> omega_to_test{ 0.10, 0.20, 0.30, 0.40, 0.50, 0.60, 0.70, 0.80 };\n\n    // open the data\n    auto data_source = Data_Source_Information::get_data_information(Geolife);\n\n    std::vector<mongo_types::box3d> regions_to_test;\n\n    // randomly select several regions which we will test\n    for (int i = 0; i < n; i++)\n        regions_to_test.push_back(utilities::get_random_query_box(cover_distribution(generator), *data_source));\n\n    // test the listed experiments\n    perform_listed_experiments(data_source, regions_to_test, delta_to_test, omega_to_test);\n}\n\nvoid aggragate_experiments::perform_listed_experiments_OSM()\n{\n    // experiment settings for easy modification\n    int n = 1000; // the number of regions to test\n    long seed = 1L; // the seed to use.  Change for actual experiment;\n    float min_query_size = 0.01;\n    float max_query_size = 0.30;\n    std::uniform_real_distribution<float> cover_distribution(min_query_size, max_query_size);\n    std::default_random_engine generator;\n    generator.seed(seed);\n\n\n    std::vector<double> delta_to_test{ 0.10, 0.20, 0.30, 0.40, 0.50, 0.60, 0.70, 0.80 };\n    std::vector<double> omega_to_test{ 0.10, 0.20, 0.30, 0.40, 0.50, 0.60, 0.70, 0.80 };\n\n    // open the data\n    auto data_source = Data_Source_Information::get_data_information(OSM_nodes);\n\n    std::vector<mongo_types::box3d> regions_to_test;\n\n    // randomly select several regions which we will test\n    for (int i = 0; i < n; i++)\n        regions_to_test.push_back(utilities::get_random_query_box(cover_distribution(generator), *data_source));\n\n    // test the listed experiments\n    perform_listed_experiments(data_source, regions_to_test, delta_to_test, omega_to_test);\n}\n\n\nvoid aggragate_experiments::perform_listed_experiments(std::shared_ptr<Data_Source_Information> data_source,\n                                                       std::vector<mongo_types::box3d> &sample_ranges,\n                                                       std::vector<double> &delta_values,\n                                                       std::vector<double> &omega_values)\n{\n    // generate the exact queries for the experiments.\n    std::vector<streaming_aggragate_query_time> exact_results;\n    for (auto range : sample_ranges)\n    {\n        exact_results.emplace_back(range);\n    }\n\n    // scan through the data, gathering exact query data //\n    // (also printing the progress of the scan, because it can take a very long time) //\n    auto convert_function = data_source->get_convert_function();\n    long elements_to_read = data_source->get_element_count();\n    long elements_read = 0;\n    // open input file\n    std::fstream in_file(data_source->get_source_raw().c_str(), std::ios_base::in);\n    std::string str;\n    while (!in_file.eof())\n    {\n        std::getline(in_file, str);\n\n        // empty string are considered null, so don't enter any data from a zero length string\n        if (str.size() == 0)\n            continue;\n        mongo_types::sample_entry current_item(convert_function(str));\n\n        for (int i = 0; i < exact_results.size(); i++)\n            exact_results[i].submit(current_item);\n        //for (auto exact_query : exact_results)\n        //    exact_query.submit(current_item);\n\n        ++elements_read;\n\n        if (elements_read % 1000000 == 0)\n            std::cout << ((0.0 + elements_read) / elements_to_read) << std::endl;\n    }\n\n    // open the sampling tree\n    using rtree_t = rtree::rtree <\n        mongo_types::entry,\n        mongo_types::sample_entry,\n        mongo_types::box3d,\n        256,\n        256\n    >;\n    std::unique_ptr<rtree_t> rtree_ptr;\n    rtree_ptr.reset(new rtree_t(data_source->get_source_created()));\n\n    // perform the experiments for each delta and omega values\n    for (auto delta : delta_values) {\n        for (auto omega : omega_values) {\n            for (auto region : exact_results) {\n                boost::posix_time::ptime start_time{ boost::posix_time::second_clock::local_time() };\n\n                double spread = region.get_queryBox().max_corner().get<2>() - region.get_queryBox().min_corner().get<2>();\n                double alpha = omega * spread / 2.0;\n                int r = std::ceil(-(spread * spread / (2.0 * alpha)) * std::log(delta / 2.0));\n\n\n                // setup query which we will be doing the aggregation over\n                streaming_aggragate_query_time sampled_query(region.get_queryBox());\n                auto cursor = rtree_ptr->sample_query(sampled_query.get_queryBox());\n\n                 std::vector<mongo_types::sample_entry> samples;\n                samples.reserve(r);\n\n                // fulfill query and get submitted aggregation\n                int count = cursor.estimate_count();\n                // std::cerr << (1.0 * r / count) << std::endl;\n                cursor.get_samples(r, std::back_inserter(samples));\n                for (auto element : samples)\n                    sampled_query.submit(element);\n\n                write_experiment_entry(data_source->get_source_created(),\n                    start_time,\n                    delta,\n                    spread,\n                    r,\n                    omega,\n                    alpha,\n                    region,\n                    sampled_query);\n            }\n        }\n    }\n\n}\n\n\n\n\n\nvoid aggragate_experiments::open_outputfile()\n{\n    m_output.reset(new std::fstream{ m_outputFilename, std::fstream::out | std::fstream::app });\n\n    if (!m_output->tellp())\n    {\n        write_header();\n    }\n}\n\nvoid aggragate_experiments::write_header()\n{\n    *m_output << \"input file\" << m_dataSeperator\n        << \"Start time\"       << m_dataSeperator\n        << \"query box min\"    << m_dataSeperator\n        << \"query box max\"    << m_dataSeperator\n        << \"actual min\"       << m_dataSeperator\n        << \"actual max\"       << m_dataSeperator\n        << \"actual spread\"    << m_dataSeperator\n        << \"delta\"            << m_dataSeperator\n        << \"alpha\"            << m_dataSeperator\n        << \"spread\"           << m_dataSeperator\n        << \"r\"                << m_dataSeperator\n        << \"omega\"            << m_dataSeperator\n        << \"actual mean\"      << m_dataSeperator\n        << \"est mean\"         << m_dataSeperator\n        << \"within alpha\"\n        << std::endl;\n}\n\nvoid aggragate_experiments::write_experiment_entry(std::string inputFile,\n                                                   boost::posix_time::ptime start_time,\n                                                   double delta,\n                                                   double spread,\n                                                   int r,\n                                                   double omega,\n                                                   double alpha,\n                                                   streaming_aggragate_query_time actual,\n                                                   streaming_aggragate_query_time sampled)\n{\n    *m_output << start_time << m_dataSeperator\n        << start_time << m_dataSeperator\n         << '(' << actual.get_queryBox().min_corner().get<0>() << ',' << actual.get_queryBox().min_corner().get<1>() << ',' << actual.get_queryBox().min_corner().get<2>() << ')' << m_dataSeperator\n         << '(' << actual.get_queryBox().max_corner().get<0>() << ',' << actual.get_queryBox().max_corner().get<1>() << ',' << actual.get_queryBox().max_corner().get<2>() << ')' << m_dataSeperator\n        << actual.get_min()  << m_dataSeperator\n        << actual.get_max()  << m_dataSeperator\n        << (actual.get_max() - actual.get_min()) << m_dataSeperator\n        << delta             << m_dataSeperator\n        << alpha             << m_dataSeperator\n        << spread            << m_dataSeperator\n        << r                 << m_dataSeperator\n        << omega             << m_dataSeperator\n        << std::setprecision(10) << actual.get_avg()  << m_dataSeperator\n        << std::setprecision(10) << sampled.get_avg() << m_dataSeperator\n        << ((std::abs(actual.get_avg() - sampled.get_avg()) < alpha) ? \"1\" : \"0\")\n        << std::endl;\n\n}", "meta": {"hexsha": "d77f7dc1101cbf790181b848eba9dd8a409bc2e2", "size": 10362, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "experiments/aggragate_experiments.cpp", "max_stars_repo_name": "InitialDLab/SampleIndex", "max_stars_repo_head_hexsha": "c83d6f53f8419cdb78f49935f41eb39447918ced", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2017-09-30T22:34:57.000Z", "max_stars_repo_stars_event_max_datetime": "2019-07-18T21:21:35.000Z", "max_issues_repo_path": "experiments/aggragate_experiments.cpp", "max_issues_repo_name": "InitialDLab/SONAR-SamplingIndex", "max_issues_repo_head_hexsha": "c83d6f53f8419cdb78f49935f41eb39447918ced", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "experiments/aggragate_experiments.cpp", "max_forks_repo_name": "InitialDLab/SONAR-SamplingIndex", "max_forks_repo_head_hexsha": "c83d6f53f8419cdb78f49935f41eb39447918ced", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.448, "max_line_length": 196, "alphanum_fraction": 0.6135881104, "num_tokens": 2388, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6039318479832805, "lm_q2_score": 0.523420348936324, "lm_q1q2_score": 0.3161102186051677}}
{"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_LU_\n#define _BOOST_UBLAS_LU_\n\n#include <boost/numeric/ublas/operation.hpp>\n#include <boost/numeric/ublas/vector_proxy.hpp>\n#include <boost/numeric/ublas/matrix_proxy.hpp>\n#include <boost/numeric/ublas/vector.hpp>\n#include <boost/numeric/ublas/triangular.hpp>\n\n// LU factorizations in the spirit of LAPACK and Golub & van Loan\n\nnamespace boost { namespace numeric { namespace ublas {\n\n    template<class T = std::size_t, class A = unbounded_array<T> >\n    class permutation_matrix:\n        public vector<T, A> {\n    public:\n        typedef vector<T, A> vector_type;\n        typedef typename vector_type::size_type size_type;\n\n        // Construction and destruction\n        BOOST_UBLAS_INLINE\n        permutation_matrix (size_type size):\n            vector<T, A> (size) {\n            for (size_type i = 0; i < size; ++ i)\n                (*this) (i) = i;\n        }\n        BOOST_UBLAS_INLINE\n        ~permutation_matrix () {}\n\n        // Assignment\n        BOOST_UBLAS_INLINE\n        permutation_matrix &operator = (const permutation_matrix &m) {\n            vector_type::operator = (m);\n            return *this;\n        }\n    };\n\n    template<class PM, class MV>\n    BOOST_UBLAS_INLINE\n    void swap_rows (const PM &pm, MV &mv, vector_tag) {\n        typedef typename PM::size_type size_type;\n        typedef typename MV::value_type value_type;\n\n        size_type size = pm.size ();\n        for (size_type i = 0; i < size; ++ i) {\n            if (i != pm (i))\n                std::swap (mv (i), mv (pm (i)));\n        }\n    }\n    template<class PM, class MV>\n    BOOST_UBLAS_INLINE\n    void swap_rows (const PM &pm, MV &mv, matrix_tag) {\n        typedef typename PM::size_type size_type;\n        typedef typename MV::value_type value_type;\n\n        size_type size = pm.size ();\n        for (size_type i = 0; i < size; ++ i) {\n            if (i != pm (i))\n                row (mv, i).swap (row (mv, pm (i)));\n        }\n    }\n    // Dispatcher\n    template<class PM, class MV>\n    BOOST_UBLAS_INLINE\n    void swap_rows (const PM &pm, MV &mv) {\n        swap_rows (pm, mv, typename MV::type_category ());\n    }\n\n    // LU factorization without pivoting\n    template<class M>\n    typename M::size_type lu_factorize (M &m) {\n        typedef M matrix_type;\n        typedef typename M::size_type size_type;\n        typedef typename M::value_type value_type;\n\n#if BOOST_UBLAS_TYPE_CHECK\n        matrix_type cm (m);\n#endif\n        int singular = 0;\n        size_type size1 = m.size1 ();\n        size_type size2 = m.size2 ();\n        size_type size = (std::min) (size1, size2);\n        for (size_type i = 0; i < size; ++ i) {\n            matrix_column<M> mci (column (m, i));\n            matrix_row<M> mri (row (m, i));\n            if (m (i, i) != value_type/*zero*/()) {\n                project (mci, range (i + 1, size1)) *= value_type (1) / m (i, i);\n            } else if (singular == 0) {\n                singular = i + 1;\n            }\n            project (m, range (i + 1, size1), range (i + 1, size2)).minus_assign (\n                outer_prod (project (mci, range (i + 1, size1)),\n                            project (mri, range (i + 1, size2))));\n        }\n#if BOOST_UBLAS_TYPE_CHECK\n        BOOST_UBLAS_CHECK (singular != 0 ||\n                           detail::expression_type_check (prod (triangular_adaptor<matrix_type, unit_lower> (m),\n                                                                triangular_adaptor<matrix_type, upper> (m)), \n                                                          cm), internal_logic ());\n#endif\n        return singular;\n    }\n\n    // LU factorization with partial pivoting\n    template<class M, class PM>\n    typename M::size_type lu_factorize (M &m, PM &pm) {\n        typedef M matrix_type;\n        typedef typename M::size_type size_type;\n        typedef typename M::value_type value_type;\n\n#if BOOST_UBLAS_TYPE_CHECK\n        matrix_type cm (m);\n#endif\n        int singular = 0;\n        size_type size1 = m.size1 ();\n        size_type size2 = m.size2 ();\n        size_type size = (std::min) (size1, size2);\n        for (size_type i = 0; i < size; ++ i) {\n            matrix_column<M> mci (column (m, i));\n            matrix_row<M> mri (row (m, i));\n            size_type i_norm_inf = i + index_norm_inf (project (mci, range (i, size1)));\n            BOOST_UBLAS_CHECK (i_norm_inf < size1, external_logic ());\n            if (m (i_norm_inf, i) != value_type/*zero*/()) {\n                if (i_norm_inf != i) {\n                    pm (i) = i_norm_inf;\n                    row (m, i_norm_inf).swap (mri);\n                } else {\n                    BOOST_UBLAS_CHECK (pm (i) == i_norm_inf, external_logic ());\n                }\n                project (mci, range (i + 1, size1)) *= value_type (1) / m (i, i);\n            } else if (singular == 0) {\n                singular = i + 1;\n            }\n            project (m, range (i + 1, size1), range (i + 1, size2)).minus_assign (\n                outer_prod (project (mci, range (i + 1, size1)),\n                            project (mri, range (i + 1, size2))));\n        }\n#if BOOST_UBLAS_TYPE_CHECK\n        swap_rows (pm, cm);\n        BOOST_UBLAS_CHECK (singular != 0 ||\n                           detail::expression_type_check (prod (triangular_adaptor<matrix_type, unit_lower> (m),\n                                                                triangular_adaptor<matrix_type, upper> (m)), cm), internal_logic ());\n#endif\n        return singular;\n    }\n\n    template<class M, class PM>\n    typename M::size_type axpy_lu_factorize (M &m, PM &pm) {\n        typedef M matrix_type;\n        typedef typename M::size_type size_type;\n        typedef typename M::value_type value_type;\n        typedef vector<value_type> vector_type;\n\n#if BOOST_UBLAS_TYPE_CHECK\n        matrix_type cm (m);\n#endif\n        int singular = 0;\n        size_type size1 = m.size1 ();\n        size_type size2 = m.size2 ();\n        size_type size = (std::min) (size1, size2);\n#ifndef BOOST_UBLAS_LU_WITH_INPLACE_SOLVE\n        matrix_type mr (m);\n        mr.assign (zero_matrix<value_type> (size1, size2));\n        vector_type v (size1);\n        for (size_type i = 0; i < size; ++ i) {\n            matrix_range<matrix_type> lrr (project (mr, range (0, i), range (0, i)));\n            vector_range<matrix_column<matrix_type> > urr (project (column (mr, i), range (0, i)));\n            urr.assign (solve (lrr, project (column (m, i), range (0, i)), unit_lower_tag ()));\n            project (v, range (i, size1)).assign (\n                project (column (m, i), range (i, size1)) -\n                axpy_prod<vector_type> (project (mr, range (i, size1), range (0, i)), urr));\n            size_type i_norm_inf = i + index_norm_inf (project (v, range (i, size1)));\n            BOOST_UBLAS_CHECK (i_norm_inf < size1, external_logic ());\n            if (v (i_norm_inf) != value_type/*zero*/()) {\n                if (i_norm_inf != i) {\n                    pm (i) = i_norm_inf;\n                    std::swap (v (i_norm_inf), v (i));\n                    project (row (m, i_norm_inf), range (i + 1, size2)).swap (project (row (m, i), range (i + 1, size2)));\n                } else {\n                    BOOST_UBLAS_CHECK (pm (i) == i_norm_inf, external_logic ());\n                }\n                project (column (mr, i), range (i + 1, size1)).assign (\n                    project (v, range (i + 1, size1)) / v (i));\n                if (i_norm_inf != i) {\n                    project (row (mr, i_norm_inf), range (0, i)).swap (project (row (mr, i), range (0, i)));\n                }\n            } else if (singular == 0) {\n                singular = i + 1;\n            }\n            mr (i, i) = v (i);\n        }\n        m.assign (mr);\n#else\n        matrix_type lr (m);\n        matrix_type ur (m);\n        lr.assign (identity_matrix<value_type> (size1, size2));\n        ur.assign (zero_matrix<value_type> (size1, size2));\n        vector_type v (size1);\n        for (size_type i = 0; i < size; ++ i) {\n            matrix_range<matrix_type> lrr (project (lr, range (0, i), range (0, i)));\n            vector_range<matrix_column<matrix_type> > urr (project (column (ur, i), range (0, i)));\n            urr.assign (project (column (m, i), range (0, i)));\n            inplace_solve (lrr, urr, unit_lower_tag ());\n            project (v, range (i, size1)).assign (\n                project (column (m, i), range (i, size1)) -\n                axpy_prod<vector_type> (project (lr, range (i, size1), range (0, i)), urr));\n            size_type i_norm_inf = i + index_norm_inf (project (v, range (i, size1)));\n            BOOST_UBLAS_CHECK (i_norm_inf < size1, external_logic ());\n            if (v (i_norm_inf) != value_type/*zero*/()) {\n                if (i_norm_inf != i) {\n                    pm (i) = i_norm_inf;\n                    std::swap (v (i_norm_inf), v (i));\n                    project (row (m, i_norm_inf), range (i + 1, size2)).swap (project (row (m, i), range (i + 1, size2)));\n                } else {\n                    BOOST_UBLAS_CHECK (pm (i) == i_norm_inf, external_logic ());\n                }\n                project (column (lr, i), range (i + 1, size1)).assign (\n                    project (v, range (i + 1, size1)) / v (i));\n                if (i_norm_inf != i) {\n                    project (row (lr, i_norm_inf), range (0, i)).swap (project (row (lr, i), range (0, i)));\n                }\n            } else if (singular == 0) {\n                singular = i + 1;\n            }\n            ur (i, i) = v (i);\n        }\n        m.assign (triangular_adaptor<matrix_type, strict_lower> (lr) +\n                  triangular_adaptor<matrix_type, upper> (ur));\n#endif\n#if BOOST_UBLAS_TYPE_CHECK\n        swap_rows (pm, cm);\n        BOOST_UBLAS_CHECK (singular != 0 ||\n                           detail::expression_type_check (prod (triangular_adaptor<matrix_type, unit_lower> (m),\n                                                                triangular_adaptor<matrix_type, upper> (m)), cm), internal_logic ());\n#endif\n        return singular;\n    }\n\n    // LU substitution\n    template<class M, class E>\n    void lu_substitute (const M &m, vector_expression<E> &e) {\n        typedef const M const_matrix_type;\n        typedef vector<typename E::value_type> vector_type;\n\n#if BOOST_UBLAS_TYPE_CHECK\n        vector_type cv1 (e);\n#endif\n        inplace_solve (m, e, unit_lower_tag ());\n#if BOOST_UBLAS_TYPE_CHECK\n        BOOST_UBLAS_CHECK (detail::expression_type_check (prod (triangular_adaptor<const_matrix_type, unit_lower> (m), e), cv1), internal_logic ());\n        vector_type cv2 (e);\n#endif\n        inplace_solve (m, e, upper_tag ());\n#if BOOST_UBLAS_TYPE_CHECK\n        BOOST_UBLAS_CHECK (detail::expression_type_check (prod (triangular_adaptor<const_matrix_type, upper> (m), e), cv2), internal_logic ());\n#endif\n    }\n    template<class M, class E>\n    void lu_substitute (const M &m, matrix_expression<E> &e) {\n        typedef const M const_matrix_type;\n        typedef matrix<typename E::value_type> matrix_type;\n\n#if BOOST_UBLAS_TYPE_CHECK\n        matrix_type cm1 (e);\n#endif\n        inplace_solve (m, e, unit_lower_tag ());\n#if BOOST_UBLAS_TYPE_CHECK\n        BOOST_UBLAS_CHECK (detail::expression_type_check (prod (triangular_adaptor<const_matrix_type, unit_lower> (m), e), cm1), internal_logic ());\n        matrix_type cm2 (e);\n#endif\n        inplace_solve (m, e, upper_tag ());\n#if BOOST_UBLAS_TYPE_CHECK\n        BOOST_UBLAS_CHECK (detail::expression_type_check (prod (triangular_adaptor<const_matrix_type, upper> (m), e), cm2), internal_logic ());\n#endif\n    }\n    template<class M, class PMT, class PMA, class MV>\n    void lu_substitute (const M &m, const permutation_matrix<PMT, PMA> &pm, MV &mv) {\n        swap_rows (pm, mv);\n        lu_substitute (m, mv);\n    }\n    template<class E, class M>\n    void lu_substitute (vector_expression<E> &e, const M &m) {\n        typedef const M const_matrix_type;\n        typedef vector<typename E::value_type> vector_type;\n\n#if BOOST_UBLAS_TYPE_CHECK\n        vector_type cv1 (e);\n#endif\n        inplace_solve (e, m, upper_tag ());\n#if BOOST_UBLAS_TYPE_CHECK\n        BOOST_UBLAS_CHECK (detail::expression_type_check (prod (e, triangular_adaptor<const_matrix_type, upper> (m)), cv1), internal_logic ());\n        vector_type cv2 (e);\n#endif\n        inplace_solve (e, m, unit_lower_tag ());\n#if BOOST_UBLAS_TYPE_CHECK\n        BOOST_UBLAS_CHECK (detail::expression_type_check (prod (e, triangular_adaptor<const_matrix_type, unit_lower> (m)), cv2), internal_logic ());\n#endif\n    }\n    template<class E, class M>\n    void lu_substitute (matrix_expression<E> &e, const M &m) {\n        typedef const M const_matrix_type;\n        typedef matrix<typename E::value_type> matrix_type;\n\n#if BOOST_UBLAS_TYPE_CHECK\n        matrix_type cm1 (e);\n#endif\n        inplace_solve (e, m, upper_tag ());\n#if BOOST_UBLAS_TYPE_CHECK\n        BOOST_UBLAS_CHECK (detail::expression_type_check (prod (e, triangular_adaptor<const_matrix_type, upper> (m)), cm1), internal_logic ());\n        matrix_type cm2 (e);\n#endif\n        inplace_solve (e, m, unit_lower_tag ());\n#if BOOST_UBLAS_TYPE_CHECK\n        BOOST_UBLAS_CHECK (detail::expression_type_check (prod (e, triangular_adaptor<const_matrix_type, unit_lower> (m)), cm2), internal_logic ());\n#endif\n    }\n    template<class MV, class M, class PMT, class PMA>\n    void lu_substitute (MV &mv, const M &m, const permutation_matrix<PMT, PMA> &pm) {\n        swap_rows (pm, mv);\n        lu_substitute (mv, m);\n    }\n\n}}}\n\n#endif\n", "meta": {"hexsha": "73b5fed2b52322d4065c8585f20a667cef22e71c", "size": 14140, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost-1_34_1/boost/numeric/ublas/lu.hpp", "max_stars_repo_name": "memoryboxes/bitcoin_satoshi", "max_stars_repo_head_hexsha": "efbe7e393c1ae3ee9f26a3040c423f176b1e48cd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 12.0, "max_stars_repo_stars_event_min_datetime": "2019-10-29T01:42:55.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-14T18:33:43.000Z", "max_issues_repo_path": "include/boost-1_34_1/boost/numeric/ublas/lu.hpp", "max_issues_repo_name": "memoryboxes/bitcoin_satoshi", "max_issues_repo_head_hexsha": "efbe7e393c1ae3ee9f26a3040c423f176b1e48cd", "max_issues_repo_licenses": ["MIT"], "max_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-1_34_1/boost/numeric/ublas/lu.hpp", "max_forks_repo_name": "memoryboxes/bitcoin_satoshi", "max_forks_repo_head_hexsha": "efbe7e393c1ae3ee9f26a3040c423f176b1e48cd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2019-10-29T08:02:35.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-30T16:57:29.000Z", "avg_line_length": 41.2244897959, "max_line_length": 148, "alphanum_fraction": 0.5730551627, "num_tokens": 3669, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6224593452091672, "lm_q2_score": 0.5078118642792044, "lm_q1q2_score": 0.3160922405286801}}
{"text": "//\n// $Id: peakpickerqtof.hpp 6337 2014-06-06 20:04:10Z witek96 $\n//\n//\n// Original author: Witold Wolski <wewolski@gmail.com>\n//\n// Copyright : ETH Zurich\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\"); \n// you may not use this file except in compliance with the License. \n// You may obtain a copy of the License at \n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software \n// distributed under the License is distributed on an \"AS IS\" BASIS, \n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. \n// See the License for the specific language governing permissions and \n// limitations under the License.\n//\n\n#ifndef PEAKPICKER_H\n#define PEAKPICKER_H\n\n#include <boost/math/special_functions.hpp>\n#include \"pwiz/utility/findmf/base/resample/convert2dense.hpp\"\n#include \"pwiz/utility/findmf/base/filter/filter.hpp\"\n#include \"pwiz/utility/findmf/base/ms/simplepicker.hpp\"\n#include \"pwiz/utility/findmf/base/filter/gaussfilter.hpp\"\n#include \"pwiz/utility/findmf/base/base/interpolate.hpp\"\n#include \"pwiz/utility/findmf/base/resample/determinebinwidth.hpp\"\n#include \"pwiz/utility/findmf/base/base/copyif.hpp\"\n\nnamespace ralab{\n  namespace base{\n    namespace ms{\n\n\n      /// resamples spectrum, apply smoothing,\n      /// determines zero crossings,\n      /// integrates peaks.\n\n      template<typename TReal>\n      struct SimplePeakArea{\n        TReal integwith_;\n\n        SimplePeakArea(TReal integwith):integwith_(integwith){}\n\n        /// intagrates the peak intesnities\n        template<typename Tzerocross, typename Tintensity, typename Tout>\n        void operator()( Tzerocross beginZ,\n                         Tzerocross endZ,\n                         Tintensity intensity,\n                         Tintensity resmpled,\n                         Tout area)const\n        {\n          typedef typename std::iterator_traits<Tout>::value_type AreaType;\n          for( ; beginZ != endZ ; ++beginZ , ++area )\n          {\n            size_t idx = static_cast<size_t>( *beginZ );\n            size_t start = static_cast<size_t>( boost::math::round( idx - integwith_ ) );\n            size_t end = static_cast<size_t>( boost::math::round( idx + integwith_ + 2.) );\n            AreaType aread = 0.;\n            for( ; start != end ; ++start )\n            {\n              aread += *(resmpled + start);\n            }\n            *area = aread;\n          }\n        }\n      };\n\n      /// extends peak to the left and to the right to the next local minimum or a predefined threshol\n      /// or a maximum allowed extension.\n      template<typename TReal>\n      struct LocalMinPeakArea{\n        typedef TReal value_type;\n        TReal integwith_;\n        TReal threshold_;\n\n        LocalMinPeakArea(TReal integwith,//!<maximal allowed peak width +- in pixel\n                         TReal threshold = .1// minimum intensity\n            ):integwith_(integwith),threshold_(threshold){}\n\n\n\n        /// intagrates the peak intesnities\n        template< typename Tzerocross, typename Tintensity, typename Tout >\n        void operator()( Tzerocross beginZ,\n                         Tzerocross endZ,\n                         Tintensity intensity,\n                         Tintensity resampled,\n                         Tout area) const\n        {\n          typedef typename std::iterator_traits<Tout>::value_type AreaType;\n          for( ; beginZ != endZ ; ++beginZ , ++area )\n          {\n            size_t idx = static_cast<size_t>( *beginZ );\n            size_t start = static_cast<size_t>( boost::math::round( idx - integwith_ ) );\n            size_t end = static_cast<size_t>( boost::math::round( idx + integwith_ + 2) );\n\n            Tintensity st = intensity + start;\n            Tintensity en = intensity + end;\n            Tintensity center = intensity + idx;\n            std::ptrdiff_t x1 = std::distance(st, center);\n            std::ptrdiff_t y1 = std::distance(center,en);\n            mextend(st , en , center);\n            std::ptrdiff_t x2 = std::distance(intensity,st);\n            std::ptrdiff_t y2 = std::distance(intensity,en);\n            std::ptrdiff_t pp = std::distance(st,en);\n            AreaType areav = std::accumulate(resampled+x2,resampled+y2,0.);\n            *area = areav;\n          }\n        }\n\n      private:\n        ///exend peak to left and rigth\n        template<typename TInt >\n        void mextend( TInt &start, TInt &end, TInt idx) const\n        {\n          typedef typename std::iterator_traits<TInt>::value_type Intensitytype;\n          //\n          for(TInt intens = idx ; intens >= start;  --intens){\n            Intensitytype val1 = *intens;\n            Intensitytype val2 = *(intens-1);\n            if(val1 > threshold_){\n              if(val1 < val2 ){\n                start = intens;\n                break;\n              }\n            }\n            else{\n              start = intens;\n              break;\n            }\n          }\n\n          for(TInt intens = idx ; intens <= end;  ++intens){\n            Intensitytype val1 = *intens;\n            Intensitytype val2 = *(intens+1);\n            if(val1 > threshold_){\n              if(val1 < val2 ){\n                end = intens;\n                break;\n              }\n            }\n            else{\n              end = intens;\n              break;\n            }\n          }\n        }\n      };\n\n      /// resamples spectrum, apply smoothing,\n      /// determines zero crossings,\n      /// integrates peaks.\n      template<typename TReal, template <typename B> class TIntegrator >\n      struct PeakPicker{\n        typedef TReal value_type;\n        typedef TIntegrator<value_type> PeakIntegrator;\n\n        TReal resolution_;\n        ralab::base::resample::Convert2Dense c2d_; // resamples spectrum\n        std::vector<TReal> resampledmz_, resampledintensity_; // keeps result of convert to dense\n        std::vector<TReal> filter_, zerocross_, smoothedintensity_; // working variables\n        std::vector<TReal> peakmass_, peakarea_; //results\n        TReal smoothwith_;\n        TReal integrationWidth_;\n        ralab::base::ms::SimplePicker<TReal> simplepicker_;\n        ralab::base::resample::SamplingWith sw_;\n        PeakIntegrator integrator_;\n        TReal intensitythreshold_;\n        bool area_;\n        uint32_t maxnumbersofpeaks_;\n\n        PeakPicker(TReal resolution, //!< instrument resolution\n                   std::pair<TReal, TReal> & massrange, //!< mass range of spectrum\n                   TReal width = 2., //!< smooth width\n                   TReal intwidth = 2., //!< integration width used for area compuation\n                   TReal intensitythreshold = 10., // intensity threshold\n                   bool area = true,//!< compute area or height? default - height.\n                   uint32_t maxnumberofpeaks = 0, //!< maximum of peaks returned by picker\n                   double c2d = 1e-5  //!< instrument resampling with small default dissables automatic determination\n            ): resolution_(resolution),c2d_( c2d ) ,smoothwith_(width),\n          integrationWidth_(intwidth),sw_(),integrator_(integrationWidth_),\n          intensitythreshold_(intensitythreshold),area_(area),maxnumbersofpeaks_(maxnumberofpeaks)\n        {\n          c2d_.defBreak(massrange,ralab::base::resample::resolution2ppm(resolution));\n          c2d_.getMids(resampledmz_);\n          ralab::base::filter::getGaussianFilterQuantile(filter_,width);\n        }\n\n\n        template<typename Tmass, typename Tintensity>\n        void operator()(Tmass begmz, Tmass endmz, Tintensity begint )\n        {\n          typename std::iterator_traits<Tintensity>::value_type minint = *std::upper_bound(begint,begint+std::distance(begmz,endmz),0.1);\n          \n          //determine sampling with\n          double a = sw_(begmz,endmz);\n          //resmpale the spectrum\n          c2d_.am_ = a;\n          c2d_.convert2dense(begmz,endmz, begint, resampledintensity_);\n\n          //smooth the resampled spectrum\n          ralab::base::filter::filter(resampledintensity_ , filter_ , smoothedintensity_ , true);\n          //determine zero crossings\n          zerocross_.resize( smoothedintensity_.size()/2 );\n          size_t nrzerocross = simplepicker_( smoothedintensity_.begin( ) , smoothedintensity_.end() , zerocross_.begin(), zerocross_.size());\n\n          peakmass_.resize(nrzerocross);\n          //determine mass of zerocrossing\n          ralab::base::base::interpolate_linear( resampledmz_.begin() , resampledmz_.end() ,\n                                                 zerocross_.begin(),  zerocross_.begin()+nrzerocross ,\n                                                 peakmass_.begin());\n\n          //determine peak area\n          if(area_){\n            peakarea_.resize(nrzerocross);\n            integrator_( zerocross_.begin(), zerocross_.begin() + nrzerocross ,\n                         smoothedintensity_.begin(),resampledintensity_.begin(), peakarea_.begin() );\n          }else{\n            //determine intensity\n            peakarea_.resize(nrzerocross);\n            ralab::base::base::interpolate_cubic( smoothedintensity_.begin() , smoothedintensity_.end() ,\n                                                  zerocross_.begin(),  zerocross_.begin()+nrzerocross ,\n                                                  peakarea_.begin());\n          }\n\n          TReal threshold = static_cast<TReal>(minint) * intensitythreshold_;\n\n          if(maxnumbersofpeaks_ > 0){\n            double threshmax = getNToppeaks();\n            if(threshmax > threshold)\n              threshold = threshmax;\n          }\n\n\n          if(threshold > 0.01){\n            filter(threshold);\n          }\n        }\n\n        /// get min instensity of peak to qualify for max-intensity;\n        TReal getNToppeaks(){\n          TReal intthres  = 0.;\n          if(maxnumbersofpeaks_ < peakarea_.size())\n          {\n            std::vector<TReal> tmparea( peakarea_.begin() , peakarea_.end() );\n            std::nth_element(tmparea.begin(),tmparea.end() - maxnumbersofpeaks_ , tmparea.end());\n            intthres = *(tmparea.end() - maxnumbersofpeaks_);\n          }\n          return intthres;\n        }\n\n\n        /// clean the masses using the threshold\n        void filter(TReal threshold){\n          typename std::vector<TReal>::iterator a = ralab::base::utils::copy_if(peakarea_.begin(),peakarea_.end(),peakmass_.begin(),\n                                                                                peakmass_.begin(),boost::bind(std::greater<TReal>(),_1,threshold));\n          peakmass_.resize(std::distance(peakmass_.begin(),a));\n          typename std::vector<TReal>::iterator b = ralab::base::utils::copy_if(peakarea_.begin(),peakarea_.end(),\n                                                                                peakarea_.begin(),boost::bind(std::greater<TReal>(),_1,threshold));\n          peakarea_.resize(std::distance(peakarea_.begin(),b));\n          //int x = 1;\n        }\n\n        const std::vector<TReal> & getPeakMass(){\n          return peakmass_;\n        }\n\n        const std::vector<TReal> & getPeakArea(){\n          return peakarea_;\n        }\n\n        const std::vector<TReal> & getResampledMZ(){\n          return resampledmz_;\n        }\n\n        const std::vector<TReal> & getResampledIntensity(){\n          return resampledintensity_;\n        }\n\n        const std::vector<TReal> & getSmoothedIntensity(){\n          return smoothedintensity_;\n        }\n      };\n    }//ms\n  }//base\n}//ralab\n\n\n\n#endif // PEAKPICKER_H\n", "meta": {"hexsha": "5db956ca166863dcad0c5847af375a1e4734d1d9", "size": 11500, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "pwiz/utility/findmf/base/ms/peakpickerqtof.hpp", "max_stars_repo_name": "edyp-lab/pwiz-mzdb", "max_stars_repo_head_hexsha": "d13ce17f4061596c7e3daf9cf5671167b5996831", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 11.0, "max_stars_repo_stars_event_min_datetime": "2015-01-08T08:33:44.000Z", "max_stars_repo_stars_event_max_datetime": "2019-07-12T06:14:54.000Z", "max_issues_repo_path": "pwiz/utility/findmf/base/ms/peakpickerqtof.hpp", "max_issues_repo_name": "shze/pwizard-deb", "max_issues_repo_head_hexsha": "4822829196e915525029a808470f02d24b8b8043", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 61.0, "max_issues_repo_issues_event_min_datetime": "2015-05-27T11:20:11.000Z", "max_issues_repo_issues_event_max_datetime": "2019-12-20T15:06:21.000Z", "max_forks_repo_path": "pwiz/utility/findmf/base/ms/peakpickerqtof.hpp", "max_forks_repo_name": "shze/pwizard-deb", "max_forks_repo_head_hexsha": "4822829196e915525029a808470f02d24b8b8043", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2016-02-03T09:41:16.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-01T18:42:36.000Z", "avg_line_length": 38.8513513514, "max_line_length": 147, "alphanum_fraction": 0.575826087, "num_tokens": 2658, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6224593452091672, "lm_q2_score": 0.5078118642792044, "lm_q1q2_score": 0.3160922405286801}}
{"text": "// This file is part of libigl, a simple c++ geometry processing library.\n//\n// Copyright (C) 2016 Francisca Gil Ureta <gilureta@cs.nyu.edu>\n//\n// This Source Code Form is subject to the terms of the Mozilla Public License\n// v. 2.0. If a copy of the MPL was not distributed with this file, You can\n// obtain one at http://mozilla.org/MPL/2.0/.\n\n#include \"edge_topology.h\"\n#include \"sort_vectors_ccw.h\"\n#include \"streamlines.h\"\n#include \"per_face_normals.h\"\n#include \"polyvector_field_matchings.h\"\n#include \"segment_segment_intersect.h\"\n#include \"triangle_triangle_adjacency.h\"\n#include \"barycenter.h\"\n#include \"slice.h\"\n\n#include <Eigen/Geometry>\n\n\n\nIGL_INLINE void igl::streamlines_init(\n                                      const Eigen::MatrixXd V,\n                                      const Eigen::MatrixXi F,\n                                      const Eigen::MatrixXd &temp_field,\n                                      const bool treat_as_symmetric,\n                                      StreamlineData &data,\n                                      StreamlineState &state,\n                                      double percentage\n                                      ){\n  using namespace Eigen;\n  using namespace std;\n  \n  igl::edge_topology(V, F, data.E, data.F2E, data.E2F);\n  igl::triangle_triangle_adjacency(F, data.TT);\n  \n  // prepare vector field\n  // --------------------------\n  int half_degree = temp_field.cols() / 3;\n  int degree = treat_as_symmetric ? half_degree * 2 : half_degree;\n  data.degree = degree;\n  \n  Eigen::MatrixXd FN;\n  Eigen::VectorXi order;\n  Eigen::RowVectorXd sorted;\n  \n  igl::per_face_normals(V, F, FN);\n  data.field.setZero(F.rows(), degree * 3);\n  for (unsigned i = 0; i < F.rows(); ++i){\n    const Eigen::RowVectorXd &n = FN.row(i);\n    Eigen::RowVectorXd temp(1, degree * 3);\n    if (treat_as_symmetric)\n      temp << temp_field.row(i), -temp_field.row(i);\n    else\n      temp = temp_field.row(i);\n    igl::sort_vectors_ccw(temp, n, order, sorted);\n    \n    // project vectors to tangent plane\n    for (int j = 0; j < degree; ++j)\n    {\n      Eigen::RowVector3d pd = sorted.segment(j * 3, 3);\n      pd = (pd - (n.dot(pd)) * n).normalized();\n      data.field.block(i, j * 3, 1, 3) = pd;\n    }\n  }\n  Eigen::VectorXd curl;\n  igl::polyvector_field_matchings(data.field, V, F, false, treat_as_symmetric, data.match_ab, data.match_ba, curl);\n  \n  // create seeds for tracing\n  // --------------------------\n  Eigen::VectorXi samples;\n  int nsamples;\n  \n  nsamples = percentage * F.rows();\n  Eigen::VectorXd r;\n  r.setRandom(nsamples, 1);\n  r = (1 + r.array()) / 2.;\n  samples = (r.array() * F.rows()).cast<int>();\n  data.nsample = nsamples;\n  \n  Eigen::MatrixXd BC, BC_sample;\n  igl::barycenter(V, F, BC);\n  igl::slice(BC, samples, 1, BC_sample);\n  \n  // initialize state for tracing vector field\n  \n  state.start_point = BC_sample.replicate(degree,1);\n  state.end_point = state.start_point;\n  \n  state.current_face = samples.replicate(1, degree);\n  \n  state.current_direction.setZero(nsamples, degree);\n  for (int i = 0; i < nsamples; ++i)\n    for (int j = 0; j < degree; ++j)\n      state.current_direction(i, j) = j;\n  \n}\n\nIGL_INLINE void igl::streamlines_next(\n                                      const Eigen::MatrixXd V,\n                                      const Eigen::MatrixXi F,\n                                      const StreamlineData & data,\n                                      StreamlineState & state\n                                      ){\n  using namespace Eigen;\n  using namespace std;\n  \n  int degree = data.degree;\n  int nsample = data.nsample;\n  \n  state.start_point = state.end_point;\n  \n  for (int i = 0; i < degree; ++i)\n  {\n    for (int j = 0; j < nsample; ++j)\n    {\n      int f0 = state.current_face(j,i);\n      if (f0 == -1) // reach boundary\n        continue;\n      int m0 = state.current_direction(j, i);\n      \n      // the starting point of the vector\n      const Eigen::RowVector3d &p = state.start_point.row(j + nsample * i);\n      // the direction where we are trying to go\n      const Eigen::RowVector3d &r = data.field.block(f0, 3 * m0, 1, 3);\n      \n      \n      // new state,\n      int f1, m1;\n      \n      for (int k = 0; k < 3; ++k)\n      {\n        f1 = data.TT(f0, k);\n        \n        // edge vertices\n        const Eigen::RowVector3d &q = V.row(F(f0, k));\n        const Eigen::RowVector3d &qs = V.row(F(f0, (k + 1) % 3));\n        // edge direction\n        Eigen::RowVector3d s = qs - q;\n        \n        double u;\n        double t;\n        if (igl::segments_intersect(p, r, q, s, t, u))\n        {\n          // point on next face\n          state.end_point.row(j + nsample * i) = p + t * r;\n          state.current_face(j,i) = f1;\n          \n          // matching direction on next face\n          int e1 = data.F2E(f0, k);\n          if (data.E2F(e1, 0) == f0)\n            m1 = data.match_ab(e1, m0);\n          else\n            m1 = data.match_ba(e1, m0);\n          \n          state.current_direction(j, i) = m1;\n          break;\n        }\n        \n      }\n      \n      \n    }\n  }\n}\n", "meta": {"hexsha": "da98d8d237a88d751487f8800bd19f444849a5c6", "size": 5066, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Source/SprueEngine/Libs/igl/streamlines.cpp", "max_stars_repo_name": "Qt-Widgets/TexGraph", "max_stars_repo_head_hexsha": "8fe72cea1afcf5e235c810003bf4ee062bb3fc13", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 199.0, "max_stars_repo_stars_event_min_datetime": "2018-02-26T20:56:21.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-16T06:09:52.000Z", "max_issues_repo_path": "Source/SprueEngine/Libs/igl/streamlines.cpp", "max_issues_repo_name": "Qt-Widgets/TexGraph", "max_issues_repo_head_hexsha": "8fe72cea1afcf5e235c810003bf4ee062bb3fc13", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 10.0, "max_issues_repo_issues_event_min_datetime": "2018-03-20T02:49:58.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-29T01:13:22.000Z", "max_forks_repo_path": "Source/SprueEngine/Libs/igl/streamlines.cpp", "max_forks_repo_name": "Qt-Widgets/TexGraph", "max_forks_repo_head_hexsha": "8fe72cea1afcf5e235c810003bf4ee062bb3fc13", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 41.0, "max_forks_repo_forks_event_min_datetime": "2018-02-28T01:33:37.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-29T16:06:19.000Z", "avg_line_length": 30.3353293413, "max_line_length": 115, "alphanum_fraction": 0.5432293723, "num_tokens": 1332, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6224593312018546, "lm_q2_score": 0.5078118642792044, "lm_q1q2_score": 0.31609223341560055}}
{"text": "// This file is part of LatNet Builder.\n//\n// Copyright (C) 2012-2021  The LatNet Builder author's, supervised by Pierre L'Ecuyer, Universite de Montreal.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//     http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\n#include \"netbuilder/NetConstructionTraits.h\"\n\n#include \"latbuilder/SeqCombiner.h\"\n#include \"latbuilder/Traversal.h\"\n\n#include <boost/dynamic_bitset.hpp>\n#include <vector>\n#include <list>\n\n#include \"latbuilder/TextStream.h\"\n\nnamespace NetBuilder {\n\n    const std::string NetConstructionTraits<NetConstruction::SOBOL>::name = \"Sobol\";\n\n    typedef typename NetConstructionTraits<NetConstruction::SOBOL>::GenValue GenValue;\n\n    typedef typename NetConstructionTraits<NetConstruction::SOBOL>::SizeParameter SizeParameter;\n\n    bool NetConstructionTraits<NetConstruction::SOBOL>::checkGenValue(const GenValue& genValue, const SizeParameter& sizeParameter)\n    {\n        auto dimension = genValue.first;\n\n        if (dimension==0)\n        {\n            return (genValue.second.size()==1 && genValue.second.front()==0);\n        }\n\n        unsigned int degree = nthPrimitivePolynomialDegree(dimension);\n\n        if (genValue.second.size() != degree){\n            return false;\n        }\n\n        for(unsigned int j = 0; j < degree; ++j)\n        {\n              if (!(genValue.second[j] % 2 == 1)){ //each direction number is odd\n                  return false;\n              }\n              if (!(genValue.second[j]< (unsigned int) (2<<j))){ // each direction number is small enough\n                  return false;\n              }\n        }\n        return true;\n    }\n\n    unsigned int NetConstructionTraits<NetConstruction::SOBOL>::nRows(const SizeParameter& param) { return (unsigned int) param; }\n\n    unsigned int NetConstructionTraits<NetConstruction::SOBOL>::nCols(const SizeParameter& param) { return (unsigned int) param; }\n\n    static const std::array<unsigned int,21200> degrees =\n    {{\n        #include \"../data/primitive_polynomials_degrees.csv\"\n    }};\n\n    static const std::array<unsigned long,21200> representations =\n    {{\n        #include \"../data/primitive_polynomials_representations.csv\"\n    }};\n\n    NetConstructionTraits<NetConstruction::SOBOL>::PrimitivePolynomial  NetConstructionTraits<NetConstruction::SOBOL>::nthPrimitivePolynomial(Dimension n)\n    {\n        // primitive polynomials are hard-coded because their computation is really complex.\n        if (n>0 && n <= 21200)\n        return std::pair<unsigned int,uInteger>(degrees[n-1],representations[n-1]);\n        else{\n            return std::pair<unsigned int,uInteger>(0,0);\n        }\n    }\n\n    unsigned int  NetConstructionTraits<NetConstruction::SOBOL>::nthPrimitivePolynomialDegree(Dimension n)\n    {\n        // primitive polynomials are hard-coded because their computation is really complex.\n        if (n>0 && n <= 21200)\n        return degrees[n-1];\n        else{\n            return 0;\n        }\n    }\n\n    void makeIteration(GeneratingMatrix& mat, std::list<boost::dynamic_bitset<>>& reg, const boost::dynamic_bitset<>& mask, unsigned int k)\n    {\n        assert(k <= mat.nCols() && k<= mat.nRows());\n        boost::dynamic_bitset<> newDirNum = reg.front();\n        newDirNum.resize(k);\n        assert(reg.size()==mask.size());\n        unsigned j = 0;\n        for(boost::dynamic_bitset<> tmp : reg)\n        {\n            if (mask[j])\n            {\n                tmp.resize(k);\n                tmp = tmp << (reg.size()-j);\n                newDirNum ^= tmp;\n            }\n            ++j;\n        }\n        reg.pop_front();\n        for(unsigned int i = 0; i < k; ++i)\n        {\n            mat(i, k-1) = newDirNum[k-i-1];\n        }\n        reg.push_back(std::move(newDirNum));\n    }\n\n    GeneratingMatrix*  NetConstructionTraits<NetConstruction::SOBOL>::createGeneratingMatrix(const GenValue& genValue, const SizeParameter& sizeParam, const Dimension& dimension_j, const unsigned int nRows)\n    {\n        unsigned int m  = nCols(sizeParam);\n        unsigned int finalnRows = (nRows == 0)? m : nRows;\n        Dimension coord = genValue.first;\n\n        if (coord==0) // special case for the first dimension\n        {\n            GeneratingMatrix* tmp = new GeneratingMatrix(m,m);\n            for(unsigned int k = 0; k<m; ++k){\n            (*tmp)(k,k) = 1; // start with identity\n            }\n            return tmp;\n        }\n\n        // compute the vector defining the linear recurrence on the columns of the matrix\n        PrimitivePolynomial p = nthPrimitivePolynomial(coord);\n        auto degree = p.first;\n        auto poly_rep = p.second;\n        boost::dynamic_bitset<> mask(degree,(poly_rep << 1) + 1);\n        unsigned int matrixSize = std::max(degree,m);\n        GeneratingMatrix* tmp = new GeneratingMatrix(matrixSize, matrixSize);\n        std::list<boost::dynamic_bitset<>> reg;\n        unsigned int k = 1;\n        for(auto dirNum : genValue.second)\n        {\n            reg.push_back(boost::dynamic_bitset<>(k,dirNum));\n            for(unsigned int i = 0; i < k; ++i)\n            {\n                (*tmp)(i,k-1) = reg.back()[k-i-1];\n            }\n            ++k;\n        }\n        while (k<=matrixSize)\n        {\n            makeIteration(*tmp, reg, mask, k);\n            ++k;\n        }\n        tmp->resize(finalnRows, m);\n        return tmp;\n    }\n\n   NetConstructionTraits<NetConstruction::SOBOL>::GenValueSpaceCoordSeq::GenValueSpaceCoordSeq(Dimension coord):\n    m_coord(coord),\n    m_underlyingSeq(underlyingSeqs(coord))\n    {};\n\n\n    NetConstructionTraits<NetConstruction::SOBOL>::GenValueSpaceCoordSeq::const_iterator::const_iterator(const GenValueSpaceCoordSeq& seq):\n        m_coord(seq.coord()),\n        m_underlyingIterator(seq.underlyingSeq().begin()),\n        m_value(GenValue(m_coord, *m_underlyingIterator))\n    {};\n\n    NetConstructionTraits<NetConstruction::SOBOL>::GenValueSpaceCoordSeq::const_iterator::const_iterator(const GenValueSpaceCoordSeq& seq, end_tag):\n        m_coord(seq.coord()),\n        m_underlyingIterator(seq.underlyingSeq().end())\n    {};\n\n    bool NetConstructionTraits<NetConstruction::SOBOL>::GenValueSpaceCoordSeq::const_iterator::equal(const const_iterator& other) const\n    { \n        return m_underlyingIterator == other.m_underlyingIterator;\n    }\n\n    const NetConstructionTraits<NetConstruction::SOBOL>::GenValueSpaceCoordSeq::const_iterator::value_type& NetConstructionTraits<NetConstruction::SOBOL>::GenValueSpaceCoordSeq::const_iterator::dereference() const\n    { \n        return m_value;\n    }\n\n    void NetConstructionTraits<NetConstruction::SOBOL>::GenValueSpaceCoordSeq::const_iterator::increment()\n    {\n        if (m_underlyingIterator != m_underlyingIterator.seq().end())\n        {\n            ++m_underlyingIterator;\n            m_value = GenValue(m_coord, *m_underlyingIterator);\n        }\n    }\n\n    NetConstructionTraits<NetConstruction::SOBOL>::GenValueSpaceCoordSeq::const_iterator NetConstructionTraits<NetConstruction::SOBOL>::GenValueSpaceCoordSeq::begin() const\n    {\n        return const_iterator(*this);\n    }\n\n    NetConstructionTraits<NetConstruction::SOBOL>::GenValueSpaceCoordSeq::const_iterator NetConstructionTraits<NetConstruction::SOBOL>::GenValueSpaceCoordSeq::end() const\n    {\n        return const_iterator(*this, typename const_iterator::end_tag{} );\n    }\n\n    Dimension NetConstructionTraits<NetConstruction::SOBOL>::GenValueSpaceCoordSeq::coord() const\n    {\n        return m_coord;\n    }\n\n    size_t  NetConstructionTraits<NetConstruction::SOBOL>::GenValueSpaceCoordSeq::size() const\n    {\n        return m_underlyingSeq.size();\n    }\n\n    const LatBuilder::SeqCombiner<std::vector<uInteger>,LatBuilder::CartesianProduct>& NetConstructionTraits<NetConstruction::SOBOL>::GenValueSpaceCoordSeq::underlyingSeq() const\n    {\n        return m_underlyingSeq;\n    }\n\n    std::vector<std::vector<uInteger>> NetConstructionTraits<NetConstruction::SOBOL>::GenValueSpaceCoordSeq::underlyingSeqs(Dimension coord)\n    {\n        if (coord == 0)\n        {\n            return {{0}};\n        }\n        else\n        {\n            unsigned int size = nthPrimitivePolynomialDegree(coord);\n            std::vector<uInteger> dirNums{1};\n            dirNums.reserve( (1 << (size - 1))  - 1);\n\n            std::vector<std::vector<uInteger>> seqs;\n            seqs.reserve(size);\n            seqs.push_back(dirNums);\n\n            uInteger upperBound = 2;\n            for(unsigned int i = 1; i < size; ++i)\n            {\n                upperBound = 2 * upperBound;\n                for(uInteger k = dirNums.back() + 2; k < upperBound; k += 2)\n                {\n                    dirNums.push_back(k);\n                }\n                seqs.push_back(dirNums);\n            }\n            return seqs;\n        }\n    }\n\n    typename NetConstructionTraits<NetConstruction::SOBOL>::GenValueSpaceCoordSeq NetConstructionTraits<NetConstruction::SOBOL>::genValueSpaceCoord(Dimension coord, const SizeParameter& sizeParameter)\n    {\n        return GenValueSpaceCoordSeq(coord);\n    }\n\n    typename NetConstructionTraits<NetConstruction::SOBOL>::GenValueSpaceSeq NetConstructionTraits<NetConstruction::SOBOL>::genValueSpace(Dimension dimension, const SizeParameter& sizeParameter)\n    {\n        std::vector<GenValueSpaceCoordSeq> seqs;\n        seqs.reserve(dimension);\n        for(Dimension coord = 0; coord < dimension; ++coord)\n        {\n            seqs.push_back(genValueSpaceCoord(coord, sizeParameter));\n        }\n        return GenValueSpaceSeq(seqs);\n    }\n\n    std::string NetConstructionTraits<NetConstruction::SOBOL>::format(const std::vector<std::shared_ptr<GeneratingMatrix>>& genMatrices, const std::vector<std::shared_ptr<GenValue>>& genVals, const SizeParameter& sizeParameter, OutputStyle outputStyle, unsigned int interlacingFactor)\n    {\n        std::string res;\n        std::string dimension = std::to_string(genVals.size()/interlacingFactor);\n        unsigned int k = nCols(sizeParameter);\n\n        if (outputStyle == OutputStyle::TERMINAL){\n            res += \"Sobol Digital Net - Direction numbers =\\n\";\n            for (unsigned int coord = 0; coord < genVals.size(); coord++){\n                res+=\"  \";\n                for(const auto& dirNum : genVals[coord]->second)\n                {\n                    res+= std::to_string(dirNum);\n                    res+= \" \";\n                }\n                res.pop_back();\n                res+=\"\\n\";\n            }\n        }\n\n        else if (outputStyle == OutputStyle::SOBOLJK){\n            res += \"# Parameters for Sobol points, in JK format\\n\";\n            res += dimension + \"    # s = \" + dimension + \" dimensions\\n\";\n            if (interlacingFactor > 1){\n                res+= std::to_string(interlacingFactor) + \"    # Interlacing factor\" + \"\\n\";\n                res+= std::to_string(genVals.size()) + \"    # Number of components = interlacing factor x dimension\" + \"\\n\";\n            }\n            res += std::to_string(k) + \"    # k = \" + std::to_string(k) + \",  n = 2^\"+ std::to_string(k) + \" = \" + std::to_string((int)pow(2, k)) + \" points\\n\";\n            res +=\"#  d  a  m_{j,c}\\n\";\n            for (unsigned int coord = 1; coord < genVals.size(); coord++){\n                res+= std::to_string(coord +1) + \"  \";\n                PrimitivePolynomial p = nthPrimitivePolynomial(coord);\n                auto degree = p.first;\n                auto poly_rep = p.second;\n                res+= std::to_string(degree) + \"  \";\n                res+= std::to_string(poly_rep) + \"  \";\n                for(const auto& dirNum : genVals[coord]->second)\n                {\n                    res+= std::to_string(dirNum);\n                    res+= \" \";\n                }\n                res.pop_back();\n                res+=\"\\n\";\n                \n            }\n            res.pop_back();\n        }\n\n        else if (outputStyle == OutputStyle::SOBOL){\n            res += \"# Initial direction numbers m_{j,c} for Sobol points\\n\";\n            res += dimension + \"    # s = \" + dimension + \" dimensions\\n\";\n            if (interlacingFactor > 1){\n                res+= std::to_string(interlacingFactor) + \"    # Interlacing factor\" + \"\\n\";\n                res+= std::to_string(genVals.size()) + \"    # Number of components = interlacing factor x dimension\" + \"\\n\";\n            }\n            res += std::to_string(k) + \"    # k = \" + std::to_string(k) + \",  n = 2^\"+ std::to_string(k) + \" = \" + std::to_string((int)pow(2, k)) + \" points\\n\";\n            res +=\"# m_{j,c}, starting from the second coordinate\\n\";\n            for (unsigned int coord = 1; coord < genVals.size(); coord++){\n                for(const auto& dirNum : genVals[coord]->second)\n                {\n                    res += std::to_string(dirNum);\n                    res += \" \";\n                }\n                res.pop_back();\n                res+=\"\\n\";\n                \n            }\n            res.pop_back();                \n        }  \n        return res;\n    }  \n}\n\n\n", "meta": {"hexsha": "ca2c23fb66caf1180a390cd2802b781fed155cd9", "size": 13378, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/NetBuilder/NetConstructionTraits-SOBOL.cc", "max_stars_repo_name": "umontreal-simul/latnetbuilder", "max_stars_repo_head_hexsha": "7490a403974741b0ee62f0100a94043ed826b563", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2020-01-21T06:08:51.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-24T16:11:31.000Z", "max_issues_repo_path": "src/NetBuilder/NetConstructionTraits-SOBOL.cc", "max_issues_repo_name": "umontreal-simul/latbuilder", "max_issues_repo_head_hexsha": "7490a403974741b0ee62f0100a94043ed826b563", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2019-10-31T07:49:28.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-03T12:07:49.000Z", "max_forks_repo_path": "src/NetBuilder/NetConstructionTraits-SOBOL.cc", "max_forks_repo_name": "umontreal-simul/latbuilder", "max_forks_repo_head_hexsha": "7490a403974741b0ee62f0100a94043ed826b563", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2016-07-27T19:25:26.000Z", "max_forks_repo_forks_event_max_datetime": "2018-05-22T20:00:47.000Z", "avg_line_length": 38.7768115942, "max_line_length": 284, "alphanum_fraction": 0.5955299746, "num_tokens": 3151, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6370307944803832, "lm_q2_score": 0.49609382947091946, "lm_q1q2_score": 0.3160270463246756}}
{"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\n#ifndef _STEADYSTATEEXTRAPOLATIONRUNNER_HPP_\n#define _STEADYSTATEEXTRAPOLATIONRUNNER_HPP_\n\n#ifdef CHASTE_CVODE\n\n#include \"AbstractSteadyStateRunner.hpp\"\n#include <boost/circular_buffer.hpp>\n//#include \"VectorHelperFunctions.hpp\"\n\nclass SteadyStateExtrapolationRunner : public AbstractSteadyStateRunner\n{\n  \n  /**\n * This class is to get a cell model to steady state by using extrapolation.\n *\n * We use the Mixed Root Mean Square (MRMS) error to measure how far from the steady state \n * we are. The PMCC of the MRMS errors is then used to check whether we can approxiamte the \n * decay of the state variables with an exponential. We then use simple linear regression \n * to find this exponential and extrapolate the variables.\n */\n  \nprivate:\n  /* The number of points to use for our PMCC calculation and simple linear regression*/\n  const unsigned int mBufferSize = 50;\n  /*The maximum number of times we will attempt to extrapolate*/\n  const unsigned int mMaxJumps = 100;\n  /*The MRMS value for which we are close enough to the steady state that the absolute error in APD90 is probably less that 0.01ms*/ \n  const double mThreshold = 1.8e-07;\n  /** Relative and absolute tolerances */\n  const double TolRel = 1e-8;\n  const double TolAbs = 1e-8;\n  /** How far to extrapolate towards our approximation of the limit of the state variable. */\n  double  mExtrapolationCoefficient = 0.9;\n  /** The period and duration of the regular stimulus function */\n  double  mPeriod;\n  double  mDuration;\n  /**The terminal state variables of the last pace we calculated*/ \n  std::vector<double> mStateVariables;\n  /*The final state variables before the last extrapolation. This is used to reset in case an extrapolation causes an error*/\n  std::vector<double> mSafeStateVariables;\n\n  /** The stimulus used to pace the model - this must be a RegularStimulus */\n  boost::shared_ptr<RegularStimulus> mpStimulus;\n\n  /**Contains mBufferSize previous values of each state variable*/ \n  boost::circular_buffer<std::vector<double>>  mStatesBuffer;\n  /**Contains mBufferSize previous values of each state vMRMS value*/ \n  boost::circular_buffer<double> mMrmsBuffer;\n\n  /**Keeps track of the number of times we have extrapolated*/\n  unsigned int mJumps = 0;\n\n  /**Run the cell to steady state */\n  virtual void RunToSteadyStateImplementation();\n  \n  /**\n     * Calculate the MRMS error between two vectors\n     *\n     * @param A  The second vector\n     * @param B  The first  vector\n     */\n  double CalculateMrms(std::vector<double> A, std::vector<double> B);\n\n  /**\n     * Calculate the PMCC of a circular_buffer of variables. This is used to calculate the PMCC of the previous MRMS values.\n     *\n     * @param values The values that we are calculating the PMCC of. \n     */\n  \n  \n  double CalculatePMCC(boost::circular_buffer<double> values){\n    if(values.size()<=2 || values.size() <= 2){\n      return -NAN;\n    }\n    \n    const unsigned int N = values.size();\n    const double sum_x = N*(N-1)/2;\n    const double sum_x2 = (N-1)*N*(2*N-1)/6;\n    \n  double  sum_y = 0, sum_y2 = 0, sum_xy = 0;\n\n  for(unsigned int i = 0; i < N; i++){\n    sum_y += values[i];\n    sum_y2+= values[i]*values[i];\n    sum_xy+= i*values[i];\n  }\n  double pmcc = (N*sum_xy - sum_x*sum_y)/sqrt((N*sum_x2 - sum_x*sum_x)*(N*sum_y2 - sum_y*sum_y));\n  return pmcc;\n  }\n\n    /**\n     * Calculate the PMCC of a circular_buffer of (x,y) pairs. This is used to calculate the PMCC of the previous MRMS values.\n     *\n     * @param x The x values of the (x,y) pairs\n     * \n     * @param y The y values of the (x,y) pairs\n */\n  \n  \n  double CalculatePMCC(std::vector<double> x, std::vector<double> y){\n    const unsigned int N = x.size();\n    if(x.size() <= 2){\n      /*We don't have enough values*/\n      return -NAN;\n    }\n    double sum_x = 0, sum_x2 = 0, sum_y = 0, sum_y2 = 0, sum_xy = 0;\n\n    /*Calculate the required sums */\n    for(unsigned int i = 0; i < N; i++){\n      sum_x  += x[i];\n      sum_x2 += x[i]*x[i];\n      sum_y  += y[i];\n      sum_y2 += y[i]*y[i];\n      sum_xy += x[i]*y[i];\n    }\n    /*Return the PMCC*/\n    return (N*sum_xy - sum_x*sum_y)/sqrt((N*sum_x2 - sum_x*sum_x)*(N*sum_y2 - sum_y*sum_y));\n  }\n\n  /** \n   * Applies the extrapolation method to one state variable if it is sensible to do so. Returns\n   * true if the state variable has been extrapolated.\n   *\n   * @state_index The index of the state variable that we wish to extrapolate\n   */\n  bool ExtrapolateState(unsigned int state_index);\n\n   /** \n   * Applies the extrapolation method to every state variable\n   *\n   * @state_index The index of the state variable that we wish to extrapolate\n   */\n  bool ExtrapolateStates();\n\n  /** \n   * Simulates one pace and extrapolates the state variables if the PMCC\n   * of the previous MRMS values is approximately -1\n   */ \n  bool RunPace();\n  \npublic:\n/**\n     * Constructor of a helper class for getting action potential models to steady state.\n     *\n     * @param pModel  The cell model to run to steady state.\n     * @param period  The period for the model to be paced at.\n     */\n  \n  SteadyStateExtrapolationRunner(boost::shared_ptr<AbstractCvodeCell> pModel, double period)\n    : AbstractSteadyStateRunner(pModel), mPeriod(period){\n    /*This ensures that we are using a regular stimulus*/\n    mpStimulus = mpModel->UseCellMLDefaultStimulus();\n    mpStimulus->SetPeriod(mPeriod);\n    mDuration = mpStimulus->GetDuration();\n\n    \n    /* Set Solver Tolerances */\n    mpModel->SetTolerances(TolRel, TolAbs);\n\n    /* Set the maximum number of timesteps for CVODE to use. This prevents \n     * CV_TOO_MUCH_WORK errors */\n    mpModel->SetMaxSteps(1e5);\n\n    /* Initialise mStateVariables */\n    mStateVariables = mpModel->GetStdVecStateVariables();\n\n    /* Set the capacity of the circular buffers */\n    mMrmsBuffer.set_capacity(mBufferSize);\n    mStatesBuffer.set_capacity(mBufferSize);    \n  };\n  \n}; \n\n\n#endif // CHASTE_CVODE\n\n#endif // _STEADYSTATEEXTRAPOLATIONRUNNER_HPP_\n\n", "meta": {"hexsha": "aec2a7a6ed382b7f475248cce53bc15a1c0b0c31", "size": 7675, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "heart/src/odes/single_cell/SteadyStateExtrapolationRunner.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": "heart/src/odes/single_cell/SteadyStateExtrapolationRunner.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": "heart/src/odes/single_cell/SteadyStateExtrapolationRunner.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.6976744186, "max_line_length": 133, "alphanum_fraction": 0.7112703583, "num_tokens": 1952, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6370307944803831, "lm_q2_score": 0.4960938294709195, "lm_q1q2_score": 0.31602704632467554}}
{"text": "// The MIT License (MIT)\n// \n// Copyright (c) 2015 Christopher Jefferson\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 <stdio.h>\n#include <stdlib.h>\n#include <assert.h>\n#include <iostream>\n#include <signal.h>\n\n#include <boost/multiprecision/cpp_int.hpp>\n\nusing namespace boost::multiprecision;\n\n//  g++ shiftqueens-boost-1024.cc -I/usr/local/Cellar/boost/1.57.0/include/ -o shiftqueens-boost-1024 -O3\n// for i in `ls`; do  ../../shiftqueens-boost-1024 $(cat $i | tr -cd \" 0-9\") > ../results.d25/$i.info; done\n\n//#define PRINT_INFO\n\n#ifdef PRINT_INFO\n#define INFO(...) printf(__VA_ARGS__);\n#define PAD(x) pad(x);\n#define PRINTBITS(x) printBits(x)\n#else\n#define INFO(...)\n#define PAD(x)\n#define PRINTBITS(x)\n#endif\n\n//#define PRINT_SOL\n\n#ifdef PRINT_SOL\nstatic int sol[100];\n#endif\n\n#include <sys/resource.h>\n#include <sys/times.h>\n\ndouble gettime() {\n\tstruct rusage rusage;\n\tif ( getrusage( RUSAGE_SELF, &rusage ) != -1 )\n\t\treturn (double)rusage.ru_utime.tv_sec +\n\t\t\t(double)rusage.ru_utime.tv_usec / 1000000.0;\n\t\n\tstd::cerr << \"Fatal error in reading time\\n\";\n\texit(1);\n}\n\nvolatile int trig = false;\n\nvoid trigger_function(int /* signum */) {\n  trig = true;\n}\n\nvoid setup_timelimit(int timeout) {\n\tsignal(SIGXCPU, trigger_function);\n\tsignal(SIGALRM, trigger_function);\n\trlimit lim;\n\tlim.rlim_cur = timeout;\n\tlim.rlim_max = timeout + 5;\n\tsetrlimit(RLIMIT_CPU, &lim);\n}\n\nlong long node_count = 0;\n\nstatic int1024_t all;\nstatic const int1024_t zero = 0;\nstatic const int1024_t one = 1;\nstatic int depth;\nstatic int count = 0;\n\nint fillLeft[1024];\nint fillRight[1024];\nint skipDepth[1024];\n\n#ifdef PRINT_SOL\nvoid print_sol()\n{\n\tfor(int i = 0; i < depth; ++i)\n\t{\n\t\tif(skipDepth[i])\n\t\t\tprintf(\"-\");\n\t\telse\n\t\t\tprintf(\"|\");\n\t\tfor(int j = 0; j < depth; ++j)\n\t\t{\n\t\t\tif(1<<j == sol[i])\n\t\t\t\tprintf(\"#|\");\n\t\t\telse\n\t\t\t  printf(\" |\");\n\t\t}\n\t\tprintf(\"\\n\");\n\t\tfor(int j = 0; j < depth; ++j)\n\t\tprintf(\"--\");\n\t\tprintf(\"-\\n\");\n\t}\n\tprintf(\"\\n\");\n}\n#endif\n\n#ifdef PRINT_INFO\nvoid printBits(int1024_t bits)\n{\n\tfor(int i = 0; i < depth; ++i) {\n\t\tprintf(bits & one ? \"1\" : \"0\");\n\t\tbits = bits >> 1;\n\t}\n}\n#endif\n\nvoid pad(int curDepth)\n{ \n\t\tfor(int i=0; i < curDepth; ++i)\n\t\t\tprintf(\" \");\n}\n\nvoid print_info() {\n        std::cout << \"Solutions: \" << count << \" \";\n        std::cout << \"Nodes: \" << node_count << \" \";\n        std::cout << \"Timeout: \" << trig << \" \";\n        std::cout << \"Time: \" << gettime() << \"\\n\";\n}\n\n\nvoid tryFunc(int1024_t ld, int1024_t cols, int1024_t rd, int curDepth)\n{\n\t\tnode_count++;\n\t\tif(trig) {\n\t\t\tprint_info();\n\t\t\tstd::cout << \"Timeout Reached. Exiting.\\n\";\n\t\t\texit(0);\n\t\t}\n\t\tPAD(curDepth);\n\t\tPRINTBITS(ld);\n\t\tINFO(\",\");\n\t\tPRINTBITS(cols);\n\t\tINFO(\",\");\n\t\tPRINTBITS(rd);\n\t\tINFO(\":%d \", curDepth);\n\tif(curDepth == depth)\n\t{\n\t\tINFO(\"\\n\");\n\t\tcount++;\n\t\tstd::cout << \"Solution Found\\n\";\n#ifdef PRINT_SOL\n\t\tprint_sol();\n#endif\n\t\tprint_info();\n\t\t\n\t\texit(0);\n\t}\n\n\tint1024_t shiftld = ld << 1;\n\tint1024_t shiftrd = rd >> 1;\n\t\n\tassert((shiftld & one) == 0);\n\tassert((shiftrd & (one << (depth - 1))) == 0);\n\t\n\tif(fillLeft[curDepth+1])\n\t{\n\t\tINFO(\"*\");\n\t\tshiftld |= one;\n\t}\n\telse\n\tINFO(\" \");\n\t\n\tif(fillRight[curDepth+1])\n\t{\n\t\tINFO(\"*\");\n\t\tshiftrd |= one << (depth - 1);\n\t}\n\telse INFO(\" \");\n\t\n\t// If we already put a queen on this depth, skip it.\n\tif(skipDepth[curDepth])\n\t{\n\t\tINFO(\" -- skip\\n\");\n\t\treturn tryFunc(shiftld, cols, shiftrd, curDepth + 1);\n\t}\n\t\n\tPRINTBITS(shiftld);\n\t\tINFO(\",\");\n\t\tPRINTBITS(shiftrd);\n\t\tINFO(\"\\n\");\n\t\t\n\t{\n\t\tint1024_t poss = ~(ld | cols | rd) & all;\n\t\twhile(poss != zero) {\n\t\t\tint1024_t bit = poss & -poss;\n\t\t\tposs -= bit;\n#ifdef PRINT_SOL\n\t\t\tsol[curDepth] = bit;\n#endif\n\t\t\tPAD(curDepth);\n\t\t\tPRINTBITS(bit);\n\t\t\tINFO(\" added\\n\");\n\t\t\ttryFunc((bit<<1)|shiftld, cols|bit, (bit>>1)|shiftrd, curDepth + 1);\n\t\t}\n\t}\n}\n\nint main(int argc, char** argv)\n{\n\t// SETUP TIMELIMIT HERE\n\tsetup_timelimit(1800);\n\t\n\tif(argc % 2 != 0)\n\t{\n\t\tprintf(\"./shiftqueens n queen1x queen1y queen2x queen2y ...\\n\");\n\t\texit(1);\n\t}\n\t\n\tdepth = atoi(argv[1]);\n\tall = (one << depth) - 1;\n\t\n\tint1024_t cols = 0;\n\tint1024_t ld = 0;\n\tint1024_t rd = 0;\n\t\n\tprintf(\"%d\\n\", argc);\n\t\n\tfor(int i = 2; i < argc; i+=2)\n\t{\n\t\tint queenx = atoi(argv[i]);\n\t\tint queeny = atoi(argv[i+1]);\n\t\t// printf(\"%d,%d\\n\", queenx, queeny);\n\t\t\n\t\tif(skipDepth[queeny]) {\n\t\t\tprintf(\"inconsistent y\\n\");\n\t\t\texit(1);\n\t\t}\n\t\t\n\t\tskipDepth[queeny] = 1;\n#ifdef PRINT_SOL\n\t\tsol[queeny] = one << queenx;\n#endif\n\n\t\tint1024_t colpos = one << queenx;\n\t\tif((cols & colpos)!=zero) {\n\t\t\tprintf(\"Inconsistent start\\n\");\n\t\t\texit(1);\n\t\t}\n\t\tcols |= colpos;\n\t\t\n\t\t{\n\t\t\tint rightintersect = queenx + queeny;\n\t\t\tif(rightintersect < depth)\n\t\t\t{\n\t\t\t\tint1024_t newrd = one << rightintersect;\n\t\t\t\tif((rd & newrd)!=zero) {\n\t\t\t\t\tprintf(\"inconsistent diagonal\\n\");\n\t\t\t\t\texit(1);\n\t\t\t\t}\n\t\t\t\trd |= newrd;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\t\trightintersect -= (depth - 1);\n\t\t\t\t\tif(fillRight[rightintersect]) {\n\t\t\t\t\t\tprintf(\"inconsistent diagonal - type 2\\n\");\n\t\t\t\t\t\texit(1);\n\t\t\t\t\t}\n\t\t\t\t\tfillRight[rightintersect] = 1;\n\t\t\t}\n\t\t}\n\t\n\t\t{\n\t\t\tint leftintersect = queenx - queeny;\n\t\t\tif(leftintersect >= 0)\n\t\t\t{\n\t\t\t\tint1024_t newld = one << leftintersect;\n\t\t\t\tif((ld & newld)!=zero) {\n\t\t\t\t\tprintf(\"inconsistent left diagonal\\n\");\n\t\t\t\t\texit(1);\n\t\t\t\t}\n\t\t\t\tld |= newld;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\t\tleftintersect *= -1;\n\t\t\t\t\tif(fillLeft[leftintersect]) {\n\t\t\t\t\t\tprintf(\"inconsistent left diagonal - type 2\\n\");\n\t\t\t\t\t\texit(1);\n\t\t\t\t\t}\n\t\t\t\t\tfillLeft[leftintersect] = 1;\n\t\t\t}\n\t\t}\n}\n\n\t\n\tcount = 0;\n\ttryFunc(ld, cols, rd, 0);\n\tstd::cout << \"No solution\" << \"\\n\";\n\tprint_info();\n\texit(0);\n}\n", "meta": {"hexsha": "8ac2d980bbd32e4dc41e26859cf1872b81fe8d44", "size": 6512, "ext": "cc", "lang": "C++", "max_stars_repo_path": "Problems/prob079/models/shiftqueens-boost-1024.cc", "max_stars_repo_name": "pwn1/csplib", "max_stars_repo_head_hexsha": "093aaa6a532addfd92f7f2cb76bae064737f978e", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": 67.0, "max_stars_repo_stars_event_min_datetime": "2015-02-27T08:35:11.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-23T03:58:33.000Z", "max_issues_repo_path": "Problems/prob079/models/shiftqueens-boost-1024.cc", "max_issues_repo_name": "pwn1/csplib", "max_issues_repo_head_hexsha": "093aaa6a532addfd92f7f2cb76bae064737f978e", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": 162.0, "max_issues_repo_issues_event_min_datetime": "2015-02-23T00:37:18.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-29T12:40:25.000Z", "max_forks_repo_path": "Problems/prob079/models/shiftqueens-boost-1024.cc", "max_forks_repo_name": "pwn1/csplib", "max_forks_repo_head_hexsha": "093aaa6a532addfd92f7f2cb76bae064737f978e", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": 72.0, "max_forks_repo_forks_event_min_datetime": "2015-02-23T00:31:27.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-24T19:16:11.000Z", "avg_line_length": 20.673015873, "max_line_length": 107, "alphanum_fraction": 0.6183968059, "num_tokens": 2015, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5583269943353745, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.3160234274941507}}
{"text": "/***********************************************************************\n//      AUTHOR:  Zhengwei Xie (Mr), <xiezhengwei@hsc.pku.edu.cn>\n//      COMPANY:  Department of Pharmacology, School of Basic Medical\n//\t\t\t\tSciences, Peking University, \n//\t\t\t\t38 Xueyuan Lu, Haidian District, \n//\t\t\t\tBeijing, 100191, China\n//      VERSION:  1.0\n//      PAPER :  \n//\t\t\"Genome-scale fluxes were predicted under the guide of enzyme \n//\t\tabundance using a novel Hy-per-Cube Shrink Algorithm\"\n//\t\tZhengwei Xie, Tianyu Zhang and Qi Ouyang\n***********************************************************************/\n\n#include <map>\n#include <cmath>\n#include <ctime>\n#include <string>\n#include <iostream>\n#include <sstream>\n#include <fstream>\n#include <vector>\n#include <stdio.h>\n#include <glpk.h>\n#include <algorithm>\n#include <boost/algorithm/string.hpp>\n#include <iomanip>\n\n#include \"func.h\"\n\nusing namespace std;\nusing namespace boost;\n#define INFI 1e20\n#define ERR 1e-20\n#define UP 1\n#define LOW 0\n\nint BIO=1; \nint ROW = -1;\ndouble LOWCUT = 1e-1;\ndouble MaxFlux=0.0;\n\nmap<int,int> tp;\nvoid tp_init() {\n    tp[0] = GLP_FX;\n    tp[1] = GLP_DB;\n    tp[2] = GLP_LO;\n    tp[3] = GLP_UP;\n}\n\nint\nmain (int argc, char **argv)\n{\t\n\tBIO = 0;\n\tstring fname=\"\";\n\tstring confile=\"\";\n\tstring boundsfile=\"\";\n\tstring target_file=\"\";\n\tstring fvafile=\"\";\n\tstring flux_na=\"\";\n\tstring trace_na=\"\";\n\tstring method =\"ratio\";\n\tstring help=\"\";\n\tdouble mxx = 0;\n\ttp_init();\n\tfor(int i=1; i<argc; i++) {\n\t\tif(strcmp(argv[i],\"-i\") == 0) {\n\t\t\ti++;\n\t\t\tcout<<\"Model file : \"<<argv[i]<<endl;\n\t\t\tfname += argv[i];\n\t\t} else if(strcmp(argv[i],\"-c\") == 0) {\n\t\t\ti++;\n\t\t\tcout<<\"Constraint file (optional) : \"<<argv[i]<<endl;\n\t\t\tconfile += argv[i];\n\t\t} else if(strcmp(argv[i],\"-l\") == 0) {\n\t\t\ti++;\n\t\t\tcout<<\"Inputted boudary file, optional: \"<<argv[i]<<endl;\n\t\t\tboundsfile+= argv[i];\n\t\t} else if(strcmp(argv[i],\"-b\") == 0) {\n\t\t\ti++;\n\t\t\tcout<<\"Enzyme abundance file (EV) : \"<<argv[i]<<endl;\n\t\t\ttarget_file = argv[i];\n\t\t} else if(strcmp(argv[i],\"-o\") == 0) {\n\t\t\ti++;\n\t\t\tcout<<\"Fluxes output file (FV) : \"<<argv[i]<<endl;\n\t\t\tflux_na += argv[i];\n\t\t} else if(strcmp(argv[i],\"--row\") == 0) {\n\t\t\ti++;\n\t\t\tcout<<\"Number of row in EV file : \"<<argv[i]<<endl;\n\t\t\tROW = atoi(argv[i]);\n\t\t}  else if(strcmp(argv[i],\"--max\") == 0) {\n\t\t\ti++;\n\t\t\tcout<<\"Maximum value in EV (optional) : \"<<argv[i]<<endl;\n\t\t\tmxx = atof(argv[i]);\n\t\t} else if(strcmp(argv[i],\"--bio\") == 0) {\n\t\t\ti++;\n\t\t\tcout<<\"Column index of biomass flux: \"<<argv[i]<<endl;\n\t\t\tBIO = atoi(argv[i]);\n\t\t} else if(strcmp(argv[i],\"--fva\") == 0) {\n\t\t\ti++;\n\t\t\tcout<<\"Perform FVA and output the file in (optional) : \"<<argv[i]<<endl;\n\t\t\tfvafile += argv[i];\n\t\t} else if(strcmp(argv[i],\"-t\") == 0) {\n\t\t\ti++;\n\t\t\tcout<<\"Print trace and print to (optional) : \"<<argv[i]<<endl;\n\t\t\ttrace_na += argv[i];\n\t\t}  else if(strcmp(argv[i],\"-h\") == 0 || strcmp(argv[i],\"--help\") == 0 ) {\n\t\t\thelp += argv[i];\n\t\t}  else {\n\t\t\tcout<<\"Unrecognized option : \"<<argv[i]<<endl;\n\t\t\texit(0);\n\t\t}\n\t}\n\tif(fname.length() < 1 || help.length() > 0) {\n\t\tcout<<\"\t\tUsage : ./hcsa -i toy.mps --row 3 -b EV.txt -o flux.txt -t trace.txt\\n\";\n\t\tcout<<\"\t\t-i model.mps\\n\";\n\t\tcout<<\"\t\t-c constraint.txt: Extra Constraint file (optional)\\n\";\n\t\tcout<<\"\t\t-l boundary.txt: FVA file, Inputted boudary file, optional\\n\";\n\t\tcout<<\"\t\t-b EV.txt: Enzyme abundance file (EV)\\n\";\n\t\tcout<<\"\t\t-o flux.txt: Fluxes output file (FV) \\n\";\n\t\tcout<<\"\t\t--row N: Number of row in EV file\\n\";\n\t\tcout<<\"\t\t--max val: Maximum value in EV (optional) \\n\";\n\t\tcout<<\"\t\t--bio N: Column index of biomass flux\\n\";\n\t\tcout<<\"\t\t--fva variable.txt: Perform FVA and output the file in (optional) \\n\";\n\t\tcout<<\"\t\t-t tracefile.txt: print trace and print to (optional) \\n\";\n\t\tcout<<\"\t\t-h or --help : Print this help.\\n\";\n\t\texit(-1);\n\t}\n\tif(ROW <= 0) {\n\t\tcout<<\"Please specify the row number of target file\\n\";\n\t\tcout<<\"     --row N \\n\";\n\t\texit(-2);\n\t}\n\t//////////////////////////////////////////////////////////////\n\t//Loading input files\n\tglp_prob *lp=NULL;\n\tlp=glp_create_prob();\n\tglp_read_mps(lp,GLP_MPS_FILE,NULL,fname.c_str());\n\n\tcout<<\"Successfully read model from \"<<fname<<endl;\n\tif(strlen(confile.c_str()) > 0) {\n\t\tcout<<\"Constraint file is \"<<confile<<endl;\n\t\tget_constraints(lp,confile,tp);\n\t}\n\tfstream out2;\n\tif(flux_na.length() > 0) {\n\t\tout2.open(flux_na.c_str(),ios::out);\n\t\tcout<<\"Output file is :\"<<flux_na<<endl;\n\t} else {\n\t\tout2.open(\"internal_points\",ios::out);\n\t\tcout<<\"Output file is : internal_points. \"<<endl;\n\t}\t\n\tfstream out3;\n\tif(trace_na.length() > 0) {\n\t\tout3.open(trace_na.c_str(),ios::out);\n\t}    \n\t//////////////////////////////////////////////////////////////\n\t//FVA\n\tint N = glp_get_num_cols(lp);\n\tmap<int,double> lbs;\n\tmap<int,double> ubs;\n\tif(boundsfile.length()>0) {\n\t\tcout<<\"Got bounds from file : \"<<boundsfile<<endl;\n\t\treadbounds(&lbs,&ubs,boundsfile);\n\t} else {\n\t\tfor(int i=1;i<=N;i++) {\n\t\t\tglp_set_obj_coef(lp,i,0.);\n\t\t}\n\t\tcout<<\"Generating column bounds . . .\\n\";\n\t\tfor(int i=1;i<=N;i++) {\n\t\t\tglp_set_obj_coef(lp,i,1);\n\t\t\tglp_set_obj_dir(lp,GLP_MAX);\n\t\t\tglp_simplex(lp,NULL);\n\t\t\tubs[i] = glp_get_col_prim(lp,i);\n\t\t\tglp_set_obj_dir(lp,GLP_MIN);\n\t\t\tglp_simplex(lp,NULL);\n\t\t\tlbs[i] = glp_get_col_prim(lp,i);\n\t\t\tglp_set_obj_coef(lp,i,0);\n\t\t}\n\t}\n\n\t//////////////////////////////////////////////////////////////\n\t//\n\tcout<<\"Initializing directions . . .\\n\";\n\tsrand(time(0));\n\n\t//////////////////////////////////////////////////////////////\n\tvector<double> target;// = new double[row+1];\n\tfor(int i=1;i<=N+1;i++) {\n\t\ttarget.push_back(0.0);\n\t} \t\n\tread_target(target_file,&target,ROW);\n\n\tcout<<\"Running HCSA ... \"<<endl;\n\tvector<double> flux;\n\tfor(int i=1;i<=N+1;i++) {\n\t\tflux.push_back(0.0);\n\t} \n\thcsa(lp,lbs,ubs,&flux,&target,&out3,method,mxx);\n\tcout<<\"Printing out the flux distribution.\\n\";\n\tfor(int i=1;i<=N;i++) {\n\t\tout2<<flux[i]<<\"\\n\";\n\t}\n\n\t//////////////////////////////////////////////////////////////\n\treturn 0;\n}\n\n\n", "meta": {"hexsha": "91e87ebc5903c30afb46a9d0e87a6745ac448447", "size": 5860, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "main.cpp", "max_stars_repo_name": "kekegg/HCSA", "max_stars_repo_head_hexsha": "7095afc934e18eb3ad0c2d7ce5386dadd5f71483", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-03-29T10:09:04.000Z", "max_stars_repo_stars_event_max_datetime": "2018-03-29T10:09:04.000Z", "max_issues_repo_path": "main.cpp", "max_issues_repo_name": "kekegg/HCSA", "max_issues_repo_head_hexsha": "7095afc934e18eb3ad0c2d7ce5386dadd5f71483", "max_issues_repo_licenses": ["Apache-2.0"], "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": "kekegg/HCSA", "max_forks_repo_head_hexsha": "7095afc934e18eb3ad0c2d7ce5386dadd5f71483", "max_forks_repo_licenses": ["Apache-2.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.038277512, "max_line_length": 83, "alphanum_fraction": 0.5539249147, "num_tokens": 1794, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7154239957834734, "lm_q2_score": 0.4416730056646256, "lm_q1q2_score": 0.3159834665422831}}
{"text": "/*  LICENSE\n \n _This file is Copyright 2018 by the Image Processing and Analysis Group (BioImage Suite Team). Dept. of Radiology & Biomedical Imaging, Yale School of Medicine._\n \n BioImage Suite Web is licensed under the Apache License, Version 2.0 (the \"License\");\n \n - you may not use this software except in compliance with the License.\n - You may obtain a copy of the License at [http://www.apache.org/licenses/LICENSE-2.0](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 ENDLICENSE */\n\n#include \"bisEigenUtil.h\"\n#include <iostream>\n#include <Eigen/Dense>\n#include <string.h>\n\nnamespace bisEigenUtil {\n\n\n  Eigen::MatrixXf mapToEigenMatrix(bisSimpleMatrix<float>* m)\n  {\n    int rows=m->getNumRows();\n    int cols=m->getNumCols();\n    return Eigen::Map<Eigen::Matrix<float,Eigen::Dynamic,Eigen::Dynamic,Eigen::RowMajor> >(m->getData(),rows,cols);\n  }\n\n\n  Eigen::VectorXf mapToEigenVector(bisSimpleVector<float>* m)\n  {\n    int rows=m->getLength();\n    return Eigen::VectorXf::Map(m->getData(),rows);\n  }\n  \n  Eigen::MatrixXf mapImageToEigenMatrix(bisSimpleImage<float>* img)\n  {\n    int dim[5]; img->getDimensions(dim);\n    int rows=dim[3]*dim[4];\n    int cols=dim[0]*dim[1]*dim[2];\n    return Eigen::Map<Eigen::Matrix<float,Eigen::Dynamic,Eigen::Dynamic,Eigen::RowMajor> >(img->getData(),rows,cols);\n  }\n\n  // -----------------------------------------------------------------------------------------------------\n  // deserialize And Map\n  // -----------------------------------------------------------------------------------------------------\n  \n  int deserializeAndMapToEigenVector(bisSimpleVector<float>* s_vector,unsigned char* ptr,Eigen::VectorXf& output,int defaultsize,float defaultvalue,int debug)\n  {\n    if (ptr!=0)\n     {\n       if (s_vector->linkIntoPointer(ptr))\n\t {\n\t   if (debug)\n\t     std::cout << \"Using external vector \" << std::endl;\n\t   \n\t   output=bisEigenUtil::mapToEigenVector(s_vector);\n\t   return 1;\n\t }\n\n       std::unique_ptr<bisSimpleMatrix<float> > s_matrix(new bisSimpleMatrix<float>(\"vectormatrix\"));\n       if (!s_matrix->linkIntoPointer(ptr))\n\t {\n\t   std::cerr << \"Failed to deserialize vector\" << std::endl;\n\t   return 0;\n\t }\n\t   \n       int rows=s_matrix->getNumRows();\n       int cols=s_matrix->getNumCols();\n       if (cols!=1)\n\t {\n\t   std::cerr << \"Failed to deserialize vector multi-col matrix provided.\" << std::endl;\n\t   return 0;\n\t }\n\n       std::cout << \"wasm- Deserializing vector from single-column matrix.\" << std::endl;\n       output=Eigen::VectorXf::Map(s_matrix->getData(),rows);\n       return 1;\n     }\n\n    if (defaultsize>0)\n      {\n\toutput=Eigen::VectorXf::Zero(defaultsize);\n\tfor (int ia=0;ia<defaultsize;ia++)\n\t  output(ia)=defaultvalue;\n      }\n    return 2;\n  }\n\n\n  int deserializeAndMapToEigenMatrix(bisSimpleMatrix<float>* s_matrix,unsigned char* ptr,Eigen::MatrixXf& output,int debug)\n  {\n    if (ptr==0) {\n      std::cerr << \"Failed to deserialize matrix\" << std::endl;    \n      return 0;\n    }\n\n    if (s_matrix->linkIntoPointer(ptr))\n      {\n\tif (debug)\n\t  std::cout << \"Using external matrix \" << std::endl;\n\t\n\toutput=bisEigenUtil::mapToEigenMatrix(s_matrix);\n\treturn 1;\n      }\n    \n    \n    std::unique_ptr<bisSimpleVector<float> > s_vector(new bisSimpleVector<float>(\"matrixvector\"));\n    if (!s_vector->linkIntoPointer(ptr))\n      {\n\tstd::cerr << \"Failed to deserialize matrix as vector\" << std::endl;\n\treturn 0;\n      }\n    \n    int rows=s_vector->getLength();\n    std::cout << \"wasm- Deserializing matrix from vector.\" << std::endl;\n    output=Eigen::Map<Eigen::Matrix<float,Eigen::Dynamic,Eigen::Dynamic,Eigen::RowMajor> >(s_vector->getData(),rows,1);\n    return 1;\n  }\n\n  unsigned char* serializeAndReturn(Eigen::MatrixXf& mat,std::string name)\n  {\n    std::unique_ptr<bisSimpleMatrix<float> > out(bisEigenUtil::createSimpleMatrix(mat,name));\n    out->releaseOwnership();\n    return out->getRawArray();\n  }\n  \n  // -----------------------------------------------------------------------------------------------------\n  std::unique_ptr<bisSimpleMatrix< float> > createSimpleMatrix(Eigen::MatrixXf inp,std::string name)\n  {\n    std::unique_ptr<bisSimpleMatrix<float> > out (new bisSimpleMatrix<float>(name));\n    out->allocate(inp.rows(),inp.cols());\n    float* odata=out->getData();\n    int index=0;\n    \n    for (int row=0;row<inp.rows();row++)\n      {\n\tfor (int col=0;col<inp.cols();col++)\n\t  {\n\t    odata[index]=inp(row,col);\n\t    ++index;\n\t  }\n      }\n\n    return std::move(out);\n  }\n\n\n  std::unique_ptr<bisSimpleVector< float> > createSimpleVector(Eigen::VectorXf inp,std::string name)\n  {\n    \n    std::unique_ptr<bisSimpleVector<float> > out (new bisSimpleVector<float>(name));  \n\n    out->allocate(inp.rows());\n    float* odata=out->getData();\n\n    for (int row=0;row<inp.rows();row++)\n      odata[row]=inp(row);\n\n    return std::move(out);\n  }\n\n  // ---------------------------------------------------------\n  // Converted from BioImageSuite::vtkpxMatrix\n  Eigen::MatrixXf importFromMatlabV6(const unsigned char* bytepointer,int bytearraylength,std::string matrixname,int debug,int& out_ok)\n  {\n    out_ok=0;\n    static unsigned char* indataptr=0;\n    static int remaining=0;\n\n    long pt=(long)bytepointer;\n    indataptr=(unsigned char*)pt;\n    remaining=bytearraylength;\n    Eigen::MatrixXf outputMatrix=Eigen::MatrixXf::Zero(1,1);\n    \n    if (debug>1)\n      std::cout << \"pointer=\" << (long)indataptr << \" numbytes=\" << bytearraylength << \"\\t \" << remaining << std::endl;\n\n    \n    struct internal\n    {\n      static int readdata(void* outbuf,int sizeofelement,int numelements)\n      {\n\tint sz=numelements*sizeofelement;\n\tif (sz<=remaining)\n\t  {\n\t    memcpy(outbuf,indataptr,sz);\n\t    remaining=remaining-sz;\n\t    indataptr+=sz;\n\t    //\t    std::cout << \"read \" << sz << \" elements pointer=\" << (int)indataptr << \"\\t remaining=\" << remaining << std::endl;\n\t    return sz;\n\t  }\n\treturn 0;\n      }\n\n      static int skipahead(int sz)\n      {\n\tif (sz<remaining)\n\t  {\n\t    indataptr+=sz;\n\t    remaining=remaining-sz;\n\t    //\t    std::cout << \"skipping ahead \" << sz << \" elements pointer=\" << (int)indataptr << \"\\t remaining=\" << remaining << std::endl;\n\t    return sz;\n\t  }\n\treturn 0;\n      }\n      \n      static int swapint(int input) {\n\tint a=input;\n\tunsigned char* bytes=(unsigned char*)&a;\n\tunsigned char tmp;\n\t\n\ttmp=*bytes;\n\t*bytes=*(bytes+3);\n\t*(bytes+3)=tmp;\n\t\n\ttmp=*(bytes+1);\n\t*(bytes+1)=*(bytes+2);\n\t*(bytes+2)=tmp;\n\t\n\treturn a;\n      }\n      \n      static float swapfloat(float input) {\n\tfloat a=input;\n\tunsigned char* bytes=(unsigned char*)&a;\n\tunsigned char tmp;\n\t\n\ttmp=*bytes;\n\t*bytes=*(bytes+3);\n\t*(bytes+3)=tmp;\n\t\n\ttmp=*(bytes+1);\n\t*(bytes+1)=*(bytes+2);\n\t*(bytes+2)=tmp;\n\t\n\treturn a;\n      }\n\n      static short swapshort(short input) {\n\tshort a=input;\n\tunsigned char *bytes=(unsigned char*)&a;\n\tunsigned char tmp;\n\ttmp=*bytes;\n\t*bytes=*(bytes+1);\n\t*(bytes+1)=tmp;\n\treturn a;\n      }\n\n      static double swapdouble(double input) {\n\tdouble a=input;\n\tdouble b=input;\n\tunsigned char* ap=(unsigned char*)&a;\n\tunsigned char* bp=(unsigned char*)&b;\n\t\n\tap[0]=bp[7];\n\tap[1]=bp[6];\n\tap[2]=bp[5];\n\tap[3]=bp[4];\n\tap[4]=bp[3];\n\tap[5]=bp[2];\n\tap[6]=bp[1];\n\tap[7]=bp[0];\n\t\n\treturn a;\n      }\n\n    };\n\n\n    \n    char buffer[2000];\n    char name[2000];\n    \n    internal::readdata(buffer,1,116);\n    if (debug)\n      std::cout << \"Description = \" << buffer << std::endl;\n    \n    internal::readdata(buffer,1,8);\n    int ok=1;\n    for (int ia=0;ia<=7;ia++)\n      {\n\tint v=int(buffer[ia]);\n\tif (!(v==0 || v==32))\n\t  {\n\t    std::cerr << \"We have a problem with ia=\" << ia << std::endl;\n\t    ok=0;\n\t    ia=9;\n\t  }\n      }\n    \n    if (ok==0)\n      {\n\treturn outputMatrix;\n      }\n    internal::readdata(buffer,1,4);\n    if (debug>1)\n      std::cout << \"All Offset bytes are either zero or space OK!\" << std::endl;\n    \n    \n    int done=0;\n    int totalread=128;\n    int count=0;\n    \n    while (done==0)\n      {\n\tint dtype[2];\n\tint n=internal::readdata(dtype,sizeof(int),2);\n\ttotalread+=8;\n\tif (debug>1)\n\t  std::cout << \"n = \" << n << \" totalread= \" << totalread << std::endl << \"-----------------------------------------------------\" << std::endl;\n\tif (n<1)\n\t  {\n\t    done=1;\n\t  }\n\telse\n\t  {\n\t    int swap=0;\n\t    ++count;\n\t    if (dtype[0]<0 || dtype[0]>1024)\n\t      {\n\t\tdtype[0]=internal::swapint(dtype[0]);\n\t\tdtype[1]=internal::swapint(dtype[1]);\n\t\tswap=1;\n\t      }\n\t    if (debug>1)\n\t      std::cout << std::endl << \"dtype = \" << dtype[0] << \" , numbytes = \" << dtype[1] << std::endl;\n\t    if (dtype[0]!=14)\n\t      {\n\t\tif (debug>1)\n\t\t  {\n\t\t    std::cout << \"Not a matrix skipping ahead \" << dtype[1] << \" bytes\" << std::endl;\n\t\t    std::cout << \"Seaking ahead  \" << dtype[1] << \" bytes\" << std::endl;\n\t\t  }\n\t\tint toread=dtype[1];\n\t\t\n\t\t// Add padding\n\t\tint tmp=8*int(toread/8);\n\t\tif (tmp<toread)\n\t\t  {\n\t\t    toread=8+tmp;\n\t\t    //\t\t  std::cout  << \"Adding padding from \" << dtype[1] << \" to \" << toread << std::endl;\n\t\t  }\n\t\t\n\t\twhile (toread>0)\n\t\t  {\n\t\t    int n=toread;\n\t\t    if (toread>256) n=256;\n\t\t    totalread+=internal::readdata(buffer,1,n);\n\t\t    toread-=n;\n\t\t  }\n\t\tif (debug>1)\n\t\t  std::cout << \"Total read = \" << totalread << std::endl;\n\t      }\n\t    else\n\t      {\n\t\tif (debug)\n\t\t  std::cout << std::endl << \"Beginning to read matrix: \" << std::endl;\n\t\tint bytes_read=internal::readdata(buffer,1,16);\n\t\tint cl=(int)buffer[8];\n\t\t//\t      if (swap)\n\t\t//\t\tcl=internal::swapint(cl);\n\t\t\n\t\tint flags[6],length[1];\n\t\tbytes_read+=internal::readdata(flags,sizeof(int),5);\n\t\tif (swap)\n\t\t  {\n\t\t    //\t\t    length[0]=internal::swapint(length[0]);\n\t\t    for (int ic=0;ic<5;ic++)\n\t\t      flags[ic]=internal::swapint(flags[ic]);\n\t\t  }\n\t\t\n\t\t\n\t\t// Check for use of small element format\n\t\t//\n\t\tint test=int(flags[4] / 65536 );\n\t\tif (debug>1)\n\t\t  std::cout << \"***************** Is Small Element \" << test << std::endl;\n\t\tif (test==0)\n\t\t  {\n\t\t    length[0]=0;\n\t\t    bytes_read+=internal::readdata(length,sizeof(int),1);\n\t\t    if (swap)\n\t\t      length[0]=internal::swapint(length[0]);\n\t\t    flags[5]=length[0];\n\t\t    if (swap)\n\t\t      flags[5]=internal::swapint(flags[5]);\n\t\t    bytes_read+=internal::readdata(name,1,flags[5]);\n\t\t    name[flags[5]]=(char)0;\n\t\t    int rem=8-(flags[5]-int(flags[5]/8)*8);\n\t\t    if (debug>1)\n\t\t      std::cout << \"Remainder \" << rem << std::endl;\n\t\t    bytes_read+=internal::readdata(buffer,1,rem);\n\t\t  }\n\t\telse\n\t\t  {\n\t\t    const int tmp_mask=65535;\n\t\t    int nb=(flags[4] & tmp_mask);\n\t\t    if (debug>1)\n\t\t      std::cout << \"Small Element nb=\" << nb << \" test= \" << int(test/65536) << std::endl;\n\t\t    bytes_read+=internal::readdata(name,1,4);\n\t\t    name[nb]=(char)0;\n\t\t    flags[5]=0;\n\t\t  }\n\t\t\n\t\tint nfl[2];\n\t\tbytes_read+=internal::readdata(nfl,sizeof(int),2);\n\t\tif (swap)\n\t\t  {\n\t\t    nfl[0]=internal::swapint(nfl[0]);\n\t\t    nfl[1]=internal::swapint(nfl[1]);\n\t\t  }\n\t\tif (debug>1)\n\t\t  std::cout << \"Final Flags = \" << nfl[0] << \",\" << nfl[1] << std::endl;\n\t\t\n\t\t\n\t\tint numrows=flags[2];\n\t\tint numcols=flags[3];\n\t\tif (debug)\n\t\t  {\n\t\t    std::cout << \"Dimensions =\" << numrows << \"x\" << numcols << \", class = \" << cl << \", length = \" << flags[5] << std::endl;\n\t\t    std::cout << \"Name = \" << name << \", (bytes read= \" << bytes_read << \")\" << std::endl;\n\t\t  }\n\t\tint toread=dtype[1]-bytes_read;\n\t\tif (debug>1)\n\t\t  std::cout << \"To read (1) = \" << toread << std::endl;\n\n\t\t\n\t\tif (strcmp(name, matrixname.c_str())==0 || strlen(matrixname.c_str()) == 0)\n\t\t  {\n\t\t    if ( (cl==7 || cl==6))\n\t\t      {\n\t\t\tint numbytesneeded=4*numrows*numcols;\n\t\t\tif (cl==6)\n\t\t\t  numbytesneeded*=2;\n\n\t\t\tif (debug)\n\t\t\t  std::cout << \"Numbytes needed = \" << numbytesneeded << std::endl;\n\t\t\t\n\t\t\tif (debug>1)\n\t\t\t  std::cout << \"Beginning to read matrix \" << numbytesneeded << \" < \" <<  toread << std::endl;\n\n\t\t\tif (numbytesneeded<=toread)\n\t\t\t  {\n\t\t\t    outputMatrix=Eigen::MatrixXf::Zero(numrows,numcols);\n\t\t\t    if (cl==6)\n\t\t\t      {\n\t\t\t\tstd::unique_ptr<double> rd(new double[numrows]);\n\t\t\t\tfor (int ib=0;ib<numcols;ib++)\n\t\t\t\t  {\n\t\t\t\t    bytes_read+=internal::readdata(rd.get(),sizeof(double),numrows);\n\t\t\t\t    for (int ia=0;ia<numrows;ia++)\n\t\t\t\t      if (swap)\n\t\t\t\t\toutputMatrix(ia,ib)=float(internal::swapdouble(rd.get()[ia]));\n\t\t\t\t      else\n\t\t\t\t\toutputMatrix(ia,ib)=float(rd.get()[ia]);\n\t\t\t\t  }\n\t\t\t      }\n\t\t\t    else\n\t\t\t      {\n\t\t\t\tstd::unique_ptr<float> rf(new float[numrows]);\n\t\t\t\tfor (int ib=0;ib<numcols;ib++)\n\t\t\t\t  {\n\t\t\t\t    bytes_read+=internal::readdata(rf.get(),sizeof(float),numrows);\n\t\t\t\t    for (int ia=0;ia<numrows;ia++)\n\t\t\t\t      if (swap)\n\t\t\t\t\toutputMatrix(ia,ib)=(internal::swapfloat(rf.get()[ia]));\n\t\t\t\t      else\n\t\t\t\t\toutputMatrix(ia,ib)=(rf.get()[ia]);\n\t\t\t\t  }\n\t\t\t      }\n\t\t\t    \n\t\t\t    out_ok=1;\n\t\t\t    return outputMatrix;\n\t\t\t  }\n\t\t\telse\n\t\t\t  {\n\t\t\t    std::cerr << \"\\t\\t\\t can't read data not enough bytes\" << std::endl;\n\t\t\t  }\n\t\t      }\n\t\t    std::cout << \"Final To read (2) = \" << toread << std::endl;\n\t\t  }\n\t\telse\n\t\t  {\n\t\t    if (debug>1)\n\t\t      std::cout << \"Not the matrix we are looking for\" << std::endl;\n\t\t  }\n\t\t\n\t\twhile (toread>0)\n\t\t  {\n\t\t    int n=toread;\n\t\t    if (toread>256) n=256;\n\t\t    bytes_read+=internal::readdata(buffer,1,n);\n\t\t    toread-=n;\n\t\t  }\n\t\t\n\t\ttotalread+=bytes_read;\n\t      }\n\t  }\n      }\n    \n    return outputMatrix;\n    \n  }\n\n\n  // ---------------------------------------------------------------------------------------------\n  // Eigen Utilities\n  // ---------------------------------------------------------------------------------------------\n  void getMatrixDimensions(Eigen::MatrixXf& mat,int sz[2]) {\n    sz[0]=mat.rows();\n    sz[1]=mat.cols();\n  }\n\n  void resizeZeroVector(Eigen::VectorXf& vct,int numrows) {\n\n    if (numrows!=vct.rows())\n      {\n\tvct=Eigen::VectorXf::Zero(numrows);\n\treturn;\n      }\n\n    for (int i=0;i<numrows;i++)\n      vct(i)=0.0;\n  }\n  \n  void resizeZeroMatrix(Eigen::MatrixXf& mat,int sz[2]) {\n\n    int dim[2]; getMatrixDimensions(mat,dim);\n\n    if (dim[0]!=sz[0] || dim[1]!=sz[1])\n      {\n\tmat=Eigen::MatrixXf::Zero(sz[0],sz[1]);\n\treturn;\n      }\n\n    for (int i=0;i<sz[0];i++)\n      for (int j=0;j<sz[1];j++)\n\tmat(i,j)=0.0;\n  }\n\n  Eigen::MatrixXf createLSQMatrix(Eigen::MatrixXf& A) {\n    Eigen::MatrixXf At=A.transpose();\n    return ((At*A).inverse())*At;\n  }\n\n\n  int inPlaceMultiplyMV(Eigen::MatrixXf& A, Eigen::VectorXf& x, Eigen::VectorXf& b)\n  {\n    int dim[2]; getMatrixDimensions(A,dim);\n    // R * C  * C * 1 = R *1 \n\n    //    std::cout << \"Dim=\" << dim[0] << \",\" << dim[1] << \" x=\" << x.rows() << \" b=\" <<  b.rows() << \" \" << std::endl;\n    \n    if (dim[1]!=x.rows() || dim[0]!=b.rows())\n      return 0;\n\n    for (int i=0;i<dim[0];i++)\n      {\n\tfloat sum=0.0;\n\tfor (int j=0;j<dim[1];j++)\n\t  sum+=A(i,j)*x[j];\n\tb(i)=sum;\n      }\n\n    //    std::cout << \"b=\" << b << std::endl;\n    \n    return 1;\n  }\n\n\n  // -----------------------------------------------------------------------------------\n  int inPlaceMultiply(Eigen::MatrixXf& A, Eigen::MatrixXf& B, Eigen::MatrixXf& C)\n  {\n    int s1[2],s2[2],s3[2];\n    getMatrixDimensions(A,s1);\n    getMatrixDimensions(B,s2);\n    \n    if (s1[1]!=s2[0])\n      {\n\tstd::cerr << \"Cannot multiply matrices bad size! a=\" << s1[0] << \"x\" << s1[1] <<\", b=\" << s2[0] << \"x\" << s2[1] << std::endl;\n\treturn 0;\n      }\n    \n    s3[0]=s1[0];\n    s3[1]=s2[1];\n    \n    resizeZeroMatrix(C,s3);\n    \n    \n    for(int col = 0; col < s3[1]; col++)\n      {\n\tfor(int row = 0; row < s3[0]; row++)\n\t  {\n\t    float sum=0.0;\n\t    for(int i = 0; i < s1[1]; i++)\n\t      sum+=A(row,i)*B(i,col);\n\t    C(row,col)=sum;\n\t  }\n      }\n    return 1;\n  }\n  \n  int inPlaceMultiply3(Eigen::MatrixXf& a,Eigen::MatrixXf& b,Eigen::MatrixXf& c,Eigen::MatrixXf& result)\n  {\n    int s1[2],s2[2],s3[2];\n    getMatrixDimensions(a,s1);\n    getMatrixDimensions(b,s2);\n    getMatrixDimensions(c,s3);\n    \n    if (s1[1]!=s2[0] || s2[1]!=s3[0])\n      {\n\tstd::cerr << \"Cannot multiply3 matrices bad sizes \" << s1[0]<<\"*\" << s1[1] <<\", \" << s2[0] << \"*\" << s2[1] << \", \" << s3[0] << \"*\" << s3[1] << std::endl;\n\treturn 0;\n      }\n    \n    int s4[2] = { s1[0],s3[1] };\n    resizeZeroMatrix(result,s4);\n    \n    for(int col = 0; col < s4[1]; col++)\n      {\n\tfor(int row = 0; row < s4[0]; row++)\n\t  {\n\t    float sum=0.0;\n\t    for(int k = 0; k < s1[1] ; k++)\n\t      for (int l=0; l <  s2[1] ; l++ )\n\t\tsum+=a(row,k)*b(k,l)*c(l,col);\n\t    \n\t    result(row,col)=sum;\n\t  }\n      }\n    return 1;\n  }\n\n\n  \n}\n\n\n\n\n", "meta": {"hexsha": "5d03906dda20bc275d60682cfc7af4c2d3157f2f", "size": 16583, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cpp/bisEigenUtil.cpp", "max_stars_repo_name": "kellyrudder/beng406", "max_stars_repo_head_hexsha": "81a297f6ee831037ddc1d68c9496f9ece847282b", "max_stars_repo_licenses": ["Apache-2.0"], "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/bisEigenUtil.cpp", "max_issues_repo_name": "kellyrudder/beng406", "max_issues_repo_head_hexsha": "81a297f6ee831037ddc1d68c9496f9ece847282b", "max_issues_repo_licenses": ["Apache-2.0"], "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/bisEigenUtil.cpp", "max_forks_repo_name": "kellyrudder/beng406", "max_forks_repo_head_hexsha": "81a297f6ee831037ddc1d68c9496f9ece847282b", "max_forks_repo_licenses": ["Apache-2.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.6702786378, "max_line_length": 162, "alphanum_fraction": 0.5430862932, "num_tokens": 4977, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5698526514141571, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.31596646458854}}
{"text": "#ifndef GUNEROMEMBERSHIPCIRCUIT_H_\n#define GUNEROMEMBERSHIPCIRCUIT_H_\n\n#include <deque>\n#include <mutex>\n#include <boost/optional.hpp>\n#include <boost/static_assert.hpp>\n#include <libff/common/utils.hpp>\n#include <libsnark/common/default_types/r1cs_gg_ppzksnark_pp.hpp>\n#include <libsnark/common/default_types/r1cs_gg_ppzksnark_pp.hpp>\n#include <libsnark/relations/constraint_satisfaction_problems/r1cs/examples/r1cs_examples.hpp>\n#include <libsnark/zk_proof_systems/ppzksnark/r1cs_gg_ppzksnark/r1cs_gg_ppzksnark.hpp>\n#include <libsnark/zk_proof_systems/ppzksnark/r1cs_ppzksnark/r1cs_ppzksnark.hpp>\n#include <libsnark/zk_proof_systems/ppzksnark/uscs_ppzksnark/uscs_ppzksnark.hpp>\n#include <libff/algebra/fields/field_utils.hpp>\n#include <libff/algebra/scalar_multiplication/multiexp.hpp>\n#include <libsnark/common/default_types/r1cs_ppzksnark_pp.hpp>\n#include <libsnark/zk_proof_systems/ppzksnark/r1cs_ppzksnark/r1cs_ppzksnark.hpp>\n#include <libff/algebra/curves/edwards/edwards_pp.hpp>\n#include <libff/algebra/curves/mnt/mnt4/mnt4_pp.hpp>\n#include <libff/algebra/curves/mnt/mnt6/mnt6_pp.hpp>\n#include <libff/common/utils.hpp>\n#include <libff/algebra/curves/alt_bn128/alt_bn128_pp.hpp>\n\n#include <libsnark/gadgetlib1/gadgets/merkle_tree/merkle_tree_check_read_gadget.hpp>\n#include <libsnark/gadgetlib1/gadgets/merkle_tree/merkle_tree_check_update_gadget.hpp>\n\n#include \"gunero_merkle_tree.hpp\"\n#include \"guneromembership_gadget.hpp\"\n#include \"GuneroProof.hpp\"\n\nusing namespace libsnark;\n\nnamespace gunero {\n\nclass GuneroMembershipWitness{\npublic:\n    uint256 W;\n    uint8_t N_account;\n    uint256 V_account;\n\n    GuneroMembershipWitness() {}\n    GuneroMembershipWitness(\n        const uint256& pW,\n        const uint8_t& pN_account,\n        const uint256& pV_account\n    ) : W(pW),\n        N_account(pN_account),\n        V_account(pV_account)\n    {\n    }\n    ~GuneroMembershipWitness() {}\n\n    ADD_SERIALIZE_METHODS;\n\n    template <typename Stream, typename Operation>\n    inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) {\n        READWRITE(W);\n        READWRITE(N_account);\n        READWRITE(V_account);\n    }\n\n    friend std::ostream& operator<<(std::ostream &out, const GuneroMembershipWitness &witness)\n    {\n        ::Serialize(out, witness, 1, 1);\n\n        return out;\n    }\n\n    friend std::istream& operator>>(std::istream &in, GuneroMembershipWitness &witness)\n    {\n        ::Unserialize(in, witness, 1, 1);\n\n        return in;\n    }\n};\n\n///// MEMBERSHIP PROOF /////\n// Public Parameters:\n// Authorization Root Hash (W)\n// Account Status (N_account)\n// Account View Hash (V_account)\n\n// Private Parameters:\n// Account Secret Key (s_account)\n// alt: Account (A_account)\n// Authorization Merkle Path (M_account[160])\n// Account View Randomizer (r_account)\n\n//1) Obtain A_account from s_account through EDCSA (secp256k1) operations\n//1 alt) Obtain P_proof from s_account through PRF operations\n//2) Validate W == calc_root(A_account, N_account, M_account[160]) (User is authorized)\n//2 alt) Validate W == calc_root(A_account, keccak256(P_proof,N_account), M_account[160]) (User is authorized)\n//3) Validate V_account == keccak256(A_account, keccak256(W,r_account) (View Hash is consistent)\n//3) alt) Validate V_account == keccak256(P_proof, keccak256(W,r_account) (View Hash is consistent)\ntemplate<typename FieldT, typename BaseT, typename HashT, size_t tree_depth>\nclass GuneroMembershipCircuit\n{\npublic:\n    GuneroMembershipCircuit()\n    {}\n    ~GuneroMembershipCircuit() {}\n\n    void generate(\n        const std::string& r1csPath,\n        const std::string& pkPath,\n        const std::string& vkPath\n    ) {\n        protoboard<FieldT> pb;\n        guneromembership_gadget<FieldT, BaseT, HashT, tree_depth> gunero(pb);\n\n        gunero.generate_r1cs_constraints(r1csPath, pkPath, vkPath);\n    }\n\n    static void makeTestVariables(\n        const uint252& s_account,\n        const uint8_t& N_account,\n        const uint256& r_account,\n        libff::bit_vector& P_proof,\n        libff::bit_vector& leaf,\n        std::vector<gunero_merkle_authentication_node>& M_account,\n        libff::bit_vector& A_account_padded,\n        libff::bit_vector& W,\n        libff::bit_vector& view_hash_1,\n        libff::bit_vector& V_account\n    )\n    {\n        /* prepare test variables */\n#ifdef DEBUG\n        libff::print_header(\"Gunero prepare test variables\");\n#endif\n        M_account = std::vector<gunero_merkle_authentication_node>(tree_depth);\n\n        libff::bit_vector s_account_256(uint252_to_bool_vector_256(s_account));\n        assert(s_account_256.size() == HashT::get_digest_len());\n\n        libff::bit_vector N_account_lsb(uint256_to_bool_vector(uint8_to_uint256(N_account)));\n        assert(N_account_lsb.size() == HashT::get_digest_len());\n\n        {//P_proof = Hash(0000b | (s_account&252b), 0)\n            libff::bit_vector block(HashT::get_digest_len());\n            block.insert(block.begin(), s_account_256.begin(), s_account_256.end());\n            assert(block.at(0) == false);\n            assert(block.at(1) == false);\n            assert(block.at(2) == false);\n            assert(block.at(3) == false);\n\n            P_proof = HashT::get_hash(block);\n\n            block = P_proof;\n            block.insert(block.end(), N_account_lsb.begin(), N_account_lsb.end());\n            leaf = HashT::get_hash(block);//hash(P_proof,N_account)\n        }\n\n        // libff::bit_vector prev_hash(HashT::get_digest_len());\n        // std::generate(prev_hash.begin(), prev_hash.end(), [&]() { return std::rand() % 2; });\n        // leaf = prev_hash;\n        assert(leaf.size() == HashT::get_digest_len());\n        libff::bit_vector prev_hash = leaf;\n\n        // libff::bit_vector address_bits;\n        libff::bit_vector A_account(tree_depth);\n\n        size_t address = 0;\n        for (long level = tree_depth-1; level >= 0; --level)\n        {\n            //Generate random uncle position\n            const bool computed_is_right = (std::rand() % 2);\n            address |= (computed_is_right ? 1ul << (tree_depth-1-level) : 0);\n            // address_bits.push_back(computed_is_right);\n            A_account.at(level) = computed_is_right;\n\n            //Generate random uncle\n            libff::bit_vector uncle(HashT::get_digest_len());\n            std::generate(uncle.begin(), uncle.end(), [&]() { return std::rand() % 2; });\n\n            //Create block of prev_hash + uncle\n            libff::bit_vector block = prev_hash;\n            block.insert(computed_is_right ? block.begin() : block.end(), uncle.begin(), uncle.end());\n            //Compress block to new hash\n            libff::bit_vector h = HashT::get_hash(block);\n\n            //Add uncle to path\n            M_account[level] = uncle;\n\n            prev_hash = h;\n        }\n\n        W = prev_hash;\n\n        A_account_padded = libff::bit_vector(HashT::get_digest_len() - A_account.size());\n        A_account_padded.insert(A_account_padded.begin(), A_account.begin(), A_account.end());\n\n        assert(A_account_padded.size() == HashT::get_digest_len());\n\n        libff::bit_vector r_account_lsb(uint256_to_bool_vector(r_account));\n        assert(r_account_lsb.size() == HashT::get_digest_len());\n\n        {//view_hash_1 = hash(W, r_account_lsb)\n            libff::bit_vector block = W;\n            block.insert(block.end(), r_account_lsb.begin(), r_account_lsb.end());\n            view_hash_1 = HashT::get_hash(block);//hash(W, r_account_lsb)\n\n            //V_account = hash(P_proof, hash(W, r_account_lsb))\n            block = P_proof;\n            block.insert(block.end(), view_hash_1.begin(), view_hash_1.end());\n            V_account = HashT::get_hash(block);//hash(P_proof, view_hash_1)\n        }\n\n#ifdef DEBUG\n        printf(\"\\n\"); libff::print_indent(); libff::print_mem(\"after prepare test variables\"); libff::print_time(\"after prepare test variables\");\n#endif\n    }\n\n    static void calculateMerkleRoot(\n        const libff::bit_vector& A_account,\n        const libff::bit_vector& leaf,\n        const std::vector<gunero_merkle_authentication_node>& M_account,\n        libff::bit_vector& W\n    )\n    {\n        const bool UseNewFormat = false;\n\n#ifdef DEBUG\n        libff::print_header(\"Gunero calculateMerkleRoot()\");\n#endif\n        assert(M_account.size() == tree_depth);\n\n        // libff::bit_vector prev_hash(HashT::get_digest_len());\n        // std::generate(prev_hash.begin(), prev_hash.end(), [&]() { return std::rand() % 2; });\n        // leaf = prev_hash;\n        assert(leaf.size() == HashT::get_digest_len());\n        libff::bit_vector prev_hash = leaf;\n\n        // libff::bit_vector address_bits;\n        assert(A_account.size() == tree_depth);\n\n        // size_t address = 0;\n        for (long level = tree_depth-1; level >= 0; --level)\n        {\n            //A_account is accessed LSB but is processed as MSB (root) to LSB (leaf)\n            bool parameter_is_left;\n            if (UseNewFormat)\n            {\n                parameter_is_left = A_account.at(tree_depth-1-level);\n            }\n            else\n            {\n                parameter_is_left = !A_account.at(level);\n            }\n\n            // //Generate random uncle\n            // libff::bit_vector uncle(HashT::get_digest_len());\n            // std::generate(uncle.begin(), uncle.end(), [&]() { return std::rand() % 2; });\n            libff::bit_vector uncle = M_account[level];\n\n            //Create block of prev_hash + uncle\n            libff::bit_vector block = prev_hash;\n            block.insert((!parameter_is_left) ? block.begin() : block.end(), uncle.begin(), uncle.end());\n            //Compress block to new hash\n            libff::bit_vector h = HashT::get_hash(block);\n\n            // //Add uncle to path\n            // M_account[level] = uncle;\n\n            prev_hash = h;\n        }\n\n        W = prev_hash;\n\n#ifdef DEBUG\n        printf(\"\\n\"); libff::print_indent(); libff::print_mem(\"after calculateMerkleRoot()\"); libff::print_time(\"after calculateMerkleRoot()\");\n#endif\n    }\n\n    bool prove(\n        const uint256& pW,\n        const uint8_t& pN_account,\n        const uint256& pV_account,\n        const uint252& ps_account,\n        const std::vector<gunero_merkle_authentication_node>& pM_account,\n        const uint160& pA_account,\n        const uint256& pr_account,\n        const r1cs_ppzksnark_proving_key<BaseT>& pk,\n        const r1cs_ppzksnark_verification_key<BaseT>& vk,\n        GuneroProof& proof\n    )\n    {\n#ifdef DEBUG\n        libff::print_header(\"Gunero witness (proof)\");\n#endif\n\n        {\n            r1cs_primary_input<FieldT> primary_input;\n            r1cs_auxiliary_input<FieldT> aux_input;\n            {\n                protoboard<FieldT> pb;\n                {\n#ifdef DEBUG\n                    libff::print_header(\"Gunero guneromembership_gadget.load_r1cs_constraints()\");\n#endif\n\n                    guneromembership_gadget<FieldT, BaseT, HashT, tree_depth> gunero(pb);\n\n                    gunero.generate_r1cs_witness(\n                        pW,\n                        pN_account,\n                        pV_account,\n                        ps_account,\n                        pM_account,\n                        pA_account,\n                        pr_account\n                    );\n\n#ifdef DEBUG\n                    printf(\"\\n\"); libff::print_indent(); libff::print_mem(\"after guneromembership_gadget.load_r1cs_constraints()\"); libff::print_time(\"after guneromembership_gadget.load_r1cs_constraints()\");\n#endif\n                }\n\n                // The constraint system must be satisfied or there is an unimplemented\n                // or incorrect sanity check above. Or the constraint system is broken!\n                assert(pb.is_satisfied());\n\n                // TODO: These are copies, which is not strictly necessary.\n                primary_input = pb.primary_input();\n                aux_input = pb.auxiliary_input();\n\n                // Swap A and B if it's beneficial (less arithmetic in G2)\n                // In our circuit, we already know that it's beneficial\n                // to swap, but it takes so little time to perform this\n                // estimate that it doesn't matter if we check every time.\n                // pb.constraint_system.swap_AB_if_beneficial();\n\n                //Test witness_map()\n                {\n                    r1cs_primary_input<FieldT> primary_input_test = guneromembership_gadget<FieldT, BaseT, HashT, tree_depth>::witness_map(\n                        pW,\n                        pN_account,\n                        pV_account\n                    );\n                    assert(primary_input == primary_input_test);\n                }\n            }\n\n            r1cs_ppzksnark_proof<BaseT> r1cs_proof = r1cs_ppzksnark_prover<BaseT>(\n                pk,\n                primary_input,\n                aux_input\n            );\n\n            proof = GuneroProof(r1cs_proof);\n\n#ifdef DEBUG\n            printf(\"\\n\"); libff::print_indent(); libff::print_mem(\"after witness (proof)\"); libff::print_time(\"after witness (proof)\");\n#endif\n        }\n\n        //Verify\n        {\n            r1cs_primary_input<FieldT> primary_input = guneromembership_gadget<FieldT, BaseT, HashT, tree_depth>::witness_map(\n                pW,\n                pN_account,\n                pV_account\n            );\n\n            return r1cs_ppzksnark_verifier_strong_IC<BaseT>(vk, primary_input, proof.to_libsnark_proof<r1cs_ppzksnark_proof<BaseT>>());\n        }\n    }\n\n    bool verify(\n        const uint256& W,\n        const uint8_t& N_account,\n        const uint256& V_account,\n        const GuneroProof& proof,\n        const r1cs_ppzksnark_verification_key<BaseT>& vk,\n        const r1cs_ppzksnark_processed_verification_key<BaseT>& vk_precomp\n        )\n    {\n        try\n        {\n            r1cs_primary_input<FieldT> primary_input = guneromembership_gadget<FieldT, BaseT, HashT, tree_depth>::witness_map(\n                W,\n                N_account,\n                V_account\n            );\n\n            r1cs_ppzksnark_proof<BaseT> r1cs_proof = proof.to_libsnark_proof<r1cs_ppzksnark_proof<BaseT>>();\n\n            ProofVerifier<BaseT> verifierEnabled = ProofVerifier<BaseT>::Strict();\n\n            bool verified = verifierEnabled.check(\n                vk,\n                vk_precomp,\n                primary_input,\n                r1cs_proof\n            );\n\n#ifdef DEBUG\n            printf(\"\\n\"); libff::print_indent(); libff::print_mem(\"after verify\"); libff::print_time(\"after verify\");\n#endif\n\n            if (verified)\n            {\n                return true;\n            }\n            else\n            {\n                return false;\n            }\n        }\n        catch (...)\n        {\n            return false;\n        }\n    }\n};\n\n} // end namespace `gunero`\n\n#endif /* GUNEROMEMBERSHIPCIRCUIT_H_ */", "meta": {"hexsha": "3d6be5e3f60b3b756639b47e27db5fd0bb10fbac", "size": 14775, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/GuneroMembershipCircuit.hpp", "max_stars_repo_name": "GunClear/Silencer", "max_stars_repo_head_hexsha": "625b5ce0860af98763aa2ce14d6b406d5ef368e4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-10-17T22:27:54.000Z", "max_stars_repo_stars_event_max_datetime": "2018-10-17T22:27:54.000Z", "max_issues_repo_path": "src/GuneroMembershipCircuit.hpp", "max_issues_repo_name": "GunClear/Silencer", "max_issues_repo_head_hexsha": "625b5ce0860af98763aa2ce14d6b406d5ef368e4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 9.0, "max_issues_repo_issues_event_min_datetime": "2018-11-09T19:57:52.000Z", "max_issues_repo_issues_event_max_datetime": "2019-01-04T15:49:02.000Z", "max_forks_repo_path": "src/GuneroMembershipCircuit.hpp", "max_forks_repo_name": "GunClear/Silencer", "max_forks_repo_head_hexsha": "625b5ce0860af98763aa2ce14d6b406d5ef368e4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.1785714286, "max_line_length": 207, "alphanum_fraction": 0.6153637902, "num_tokens": 3604, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7090191337850933, "lm_q2_score": 0.4455295350395727, "lm_q1q2_score": 0.3158889650094332}}
{"text": "#include \"ICP.h\"\n\n#include <assert.h>\n#include <Eigen/Geometry>\n#include <Eigen/LU> \n#include <Eigen/SVD>\n\n\nnamespace ICP {\n\tANNkd_tree* create_kd_tree(\n\t\tconst Eigen::MatrixXd &_points,\n\t\tANNpointArray &_ann_points)\n\t{\n\t\tassert(_points.rows() == 3);\n\t\tassert(_points.cols() > 0);\n\n\t\tint dimension = 3;\n\t\tint num_points = static_cast<int>(_points.cols());\n\t\tANNkd_tree* ann_kd_tree;\n\n\t\t_ann_points = annAllocPts(num_points, dimension);\t// allocate data points\n\n\t\t// read data points\n\t\tfor (int point_index = 0; point_index < num_points; point_index++)\n\t\t{\n\t\t\tfor (int i = 0; i < dimension; i++)\n\t\t\t\t_ann_points[point_index][i] = _points.col(point_index)[i];\n\t\t}\n\n\t\tann_kd_tree = new ANNkd_tree(\t\t// build search structure\n\t\t\t_ann_points,\t\t\t\t\t// the data points\n\t\t\tnum_points,\t\t\t\t\t\t// number of points\n\t\t\tdimension);\t\t\t\t\t\t// dimension of space\n\n\t\treturn ann_kd_tree;\n\t}\n\n\ttemplate<typename T>\n\tvoid get_closest_points(\n\t\tANNkd_tree *_data_ann_kd_tree,\n\t\tconst Eigen::MatrixXd &_query_points,\n\t\tconst Eigen::MatrixBase<T> &_data_values,\n\t\tEigen::MatrixBase<T> &_closest_data_values)\n\t{\n\t\tassert(_data_ann_kd_tree->nPoints() > 0);\n\t\tassert(_query_points.rows() == 3);\n\t\tassert(_query_points.cols() > 0);\n\t\tassert(_data_values.rows() > 0);\n\t\tassert(_data_values.cols() == _data_ann_kd_tree->nPoints());\n\n\t\tint num_queries = static_cast<int>(_query_points.cols());\n\t\tint num_data = static_cast<int>(_data_values.cols());\n\t\tint dimension = static_cast<int>(_data_values.rows());\n\t\t_closest_data_values = Eigen::MatrixBase<T>::Zero(dimension, num_queries);\n\n\t\tANNpoint q = annAllocPt(3);\n\t\tANNidxArray nn_idx = new ANNidx[1];\n\t\tANNdistArray dd = new ANNdist[1];\n\n\t\tfor (int point_index = 0; point_index < num_queries; point_index++)\n\t\t{\n\t\t\tfor (unsigned int i = 0; i < 3; ++i)\n\t\t\t\tq[i] = _query_points.col(point_index)(i);\n\n\t\t\t_data_ann_kd_tree->annkSearch(q, 1, nn_idx, dd);\n\t\t\tint closest_Y_point_index = nn_idx[0];\n\t\t\tassert(closest_Y_point_index < num_data);\n\t\t\tassert(point_index < _closest_data_values.cols());\n\n\t\t\t_closest_data_values.col(point_index) = _data_values.col(closest_Y_point_index);\n\t\t}\n\n\t\t// Deallocate ANN.\n\t\tannDeallocPt(q);\n\t\tdelete[] nn_idx;\n\t\tdelete[] dd;\n\t}\n\n\tvoid get_closest_points(\n\t\tANNkd_tree *_data_ann_kd_tree,\n\t\tconst Eigen::MatrixXd &_query_points,\n\t\tEigen::VectorXd &_distances)\n\t{\n\t\tassert(_data_ann_kd_tree->nPoints() > 0);\n\t\tassert(_query_points.rows() == 3);\n\t\tassert(_query_points.cols() > 0);\n\n\t\tint num_queries = static_cast<int>(_query_points.cols());\n\t\t_distances = Eigen::VectorXd::Zero(num_queries);\n\n\t\tANNpoint q = annAllocPt(3);\n\t\tANNidxArray nn_idx = new ANNidx[1];\n\t\tANNdistArray dd = new ANNdist[1];\n\n\t\tfor (int point_index = 0; point_index < num_queries; point_index++)\n\t\t{\n\t\t\tfor (unsigned int i = 0; i < 3; ++i)\n\t\t\t\tq[i] = _query_points.col(point_index)(i);\n\n\t\t\t_data_ann_kd_tree->annkSearch(q, 1, nn_idx, dd);\n\t\t\tassert(point_index < _distances.rows());\n\t\t\t_distances[point_index] = std::sqrt(dd[0]);\n\t\t}\n\n\t\t// Deallocate ANN.\n\t\tannDeallocPt(q);\n\t\tdelete[] nn_idx;\n\t\tdelete[] dd;\n\t}\n\n\tdouble compute_rigid_transformation(const Eigen::MatrixXd &_X, const Eigen::MatrixXd &_Y,\n\t\tEigen::Matrix3d &_rotation_mat, Eigen::Vector3d &_translation_vec,\n\t\tconst double *_distance_threshold)\n\t{\n\t\t// Return: error (Minus error means that the computation is failed.)\n\n\t\tassert(_X.rows() == 3);\n\t\tassert(_Y.rows() == 3);\n\n\t\tif (_X.cols() == 0 || _Y.cols() == 0)\n\t\t{\n\t\t\tstd::cerr << \"Warning: No point exists.\" << std::endl;\n\t\t\treturn -1;\n\t\t}\n\n\t\tEigen::MatrixXd::Index X_num_points = _X.cols();\n\t\tEigen::MatrixXd::Index Y_num_points = _Y.cols();\n\n\t\tANNpointArray X_ann_points;\n\t\tANNkd_tree* X_ann_kd_tree = create_kd_tree(_X, X_ann_points);\n\n\t\tANNpointArray Y_ann_points;\n\t\tANNkd_tree* Y_ann_kd_tree = create_kd_tree(_Y, Y_ann_points);\n\t\t\n\t\tEigen::MatrixXd closest_X; \n\t\tEigen::MatrixXd closest_Y;\n\n\t\tget_closest_points(X_ann_kd_tree, _Y, _X, closest_X);\n\t\tget_closest_points(Y_ann_kd_tree, _X, _Y, closest_Y);\n\n\t\tannDeallocPts(X_ann_points); delete X_ann_kd_tree;\n\t\tannDeallocPts(Y_ann_points); delete Y_ann_kd_tree;\n\n\t\tassert(closest_X.cols() == Y_num_points);\n\t\tassert(closest_Y.cols() == X_num_points);\n\n\t\tEigen::MatrixXd::Index n = X_num_points + Y_num_points;\n\t\tEigen::MatrixXd all_X(3, n);\n\t\tEigen::MatrixXd all_Y(3, n);\n\n\t\tall_X << _X, closest_X;\n\t\tall_Y << closest_Y, _Y;\n\n\t\tassert(all_X.cols() == n);\n\t\tassert(all_Y.cols() == n);\n\n\t\tEigen::MatrixXd diff = all_X - all_Y;\n\t\tEigen::RowVectorXd squared_dists = (diff.array() * diff.array()).colwise().sum();\n\n\t\t// Hausdorff distance.\n\t\tdouble prev_error = std::sqrt(squared_dists.maxCoeff());\n\n\t\t// Partial ICP.\n\t\tif (_distance_threshold)\n\t\t{\n\t\t\t//std::cout << \"max_squared_dists = \" << squared_dists.maxCoeff() << std::endl;\n\t\t\t//std::cout << \"avg_squared_dists = \" << squared_dists.sum() / n << std::endl;\n\n\t\t\tdouble squared_distance_threshold = (*_distance_threshold) * (*_distance_threshold);\n\t\t\tEigen::MatrixXd::Index subset_n = (squared_dists.array() <= squared_distance_threshold).count();\n\t\t\tEigen::MatrixXd subset_all_X(3, subset_n);\n\t\t\tEigen::MatrixXd subset_all_Y(3, subset_n);\n\t\t\tEigen::MatrixXd subset_diff(3, subset_n);\n\t\t\tEigen::RowVectorXd subset_squared_dists(subset_n);\n\n\t\t\tint count = 0;\n\t\t\tfor (int i = 0; i < n; ++i)\n\t\t\t{\n\t\t\t\tif (squared_dists[i] <= squared_distance_threshold)\n\t\t\t\t{\n\t\t\t\t\tassert(count < subset_n);\n\t\t\t\t\tsubset_all_X.col(count) = all_X.col(i);\n\t\t\t\t\tsubset_all_Y.col(count) = all_Y.col(i);\n\t\t\t\t\tsubset_diff.col(count) = diff.col(i);\n\t\t\t\t\tsubset_squared_dists.col(count) = squared_dists.col(i);\n\t\t\t\t\t++count;\n\t\t\t\t}\n\t\t\t}\n\t\t\tassert(count == subset_n);\n\n\t\t\tn = subset_n;\n\t\t\tall_X.swap(subset_all_X);\n\t\t\tall_Y.swap(subset_all_Y);\n\t\t\tdiff.swap(subset_diff);\n\t\t\tsquared_dists.swap(subset_squared_dists);\n\t\t}\n\n\n\t\tif (n < MIN_NUM_ICP_POINT_PAIRS)\n\t\t{\n\t\t\tstd::cerr << \"Warning: Too few point pairs.\" << std::endl;\n\t\t\treturn -1;\n\t\t}\n\n\t\tEigen::Vector3d all_X_mean = all_X.rowwise().mean();\n\t\tEigen::Vector3d all_Y_mean = all_Y.rowwise().mean();\n\n\t\tEigen::MatrixXd centered_all_X = all_X.colwise() - all_X_mean;\n\t\tEigen::MatrixXd centered_all_Y = all_Y.colwise() - all_Y_mean;\n\n\t\tEigen::MatrixXd S = centered_all_X * centered_all_Y.transpose();\n\t\tassert(S.rows() == 3);\n\t\tassert(S.cols() == 3);\n\n\t\tEigen::JacobiSVD<Eigen::MatrixXd> svd(S, Eigen::ComputeFullU | Eigen::ComputeFullV);\n\n\t\tEigen::Matrix3d det_mat = Eigen::Matrix3d::Identity();\n\t\tdet_mat(2, 2) = (svd.matrixV() * svd.matrixU().transpose()).determinant();\n\n\t\t_rotation_mat = svd.matrixV() * det_mat * svd.matrixU().transpose();\n\t\t_translation_vec = all_Y_mean - _rotation_mat * all_X_mean;\n\n\t\tdiff = ((_rotation_mat * all_X).colwise() + _translation_vec) - all_Y;\n\t\tsquared_dists = (diff.array() * diff.array()).colwise().sum();\n\n\t\t// Hausdorff distance.\n\t\tdouble error = std::sqrt(squared_dists.maxCoeff());\n\t\tif (error > prev_error)\n\t\t\treturn -1;\n\n\t\treturn error;\n\t}\n\n\tdouble run_iterative_closest_points(Eigen::MatrixXd &_X, const Eigen::MatrixXd &_Y,\n\t\tEigen::Matrix3d &_rotation_mat, Eigen::Vector3d &_translation_vec,\n\t\tconst double *_distance_threshold)\n\t{\n\t\t_rotation_mat = Eigen::Matrix3d::Identity();\n\t\t_translation_vec = Eigen::Vector3d::Zero();\n\t\tdouble prev_error = std::numeric_limits<double>::max();\n\n\t\tconst unsigned int max_num_iterations = MAX_NUM_ICP_ITERATIONS;\n\t\tconst double min_angle_difference = static_cast<double>(MIN_ICP_ANGLE_DIFFERENCE) / 180.0 * M_PI;\n\t\tconst double min_translation = MIN_ICP_TRANSLATION;\n\n\t\tfor (unsigned int iteration = 0; iteration < max_num_iterations; ++iteration)\n\t\t{\n\t\t\tEigen::Matrix3d new_rotation_mat;\n\t\t\tEigen::Vector3d new_translation_vec;\n\t\t\tdouble error = compute_rigid_transformation(_X, _Y,\n\t\t\t\tnew_rotation_mat, new_translation_vec, _distance_threshold);\n\n\t\t\tif (error < 0)\n\t\t\t{\n\t\t\t\t// The transformation computation is failed.\n\t\t\t\tif (iteration == 0) return -1;\n\t\t\t\t//std::cout << \"[FINAL] error = \" << prev_error << std::endl;\n\t\t\t\treturn prev_error;\n\t\t\t}\n\t\t\telse if (error > prev_error)\n\t\t\t{\n\t\t\t\t// NOTE:\n\t\t\t\t// Continue only when the error value is decreasing.\n\t\t\t\t//std::cout << \"[FINAL] error = \" << prev_error << std::endl;\n\t\t\t\treturn prev_error;\n\t\t\t}\n\n\t\t\tprev_error = error;\n\t\t\t//std::cout << \"error = \" << prev_error << std::endl;\n\n\t\t\tEigen::AngleAxisd rotation_angle;\n\t\t\trotation_angle.fromRotationMatrix(new_rotation_mat);\n\t\t\tif (rotation_angle.angle() < min_angle_difference && new_translation_vec.norm() < min_translation)\n\t\t\t\treturn prev_error;\n\t\t\t\n\t\t\t_rotation_mat = new_rotation_mat * _rotation_mat;\n\t\t\t_translation_vec = new_rotation_mat * _translation_vec + new_translation_vec;\n\n\t\t\t_X = ((new_rotation_mat * _X).colwise() + new_translation_vec);\n\t\t}\n\n\t\treturn prev_error;\n\t}\n\n}\n", "meta": {"hexsha": "86cfec1dd5c51e7f8584b2cc6700cccce1cac698", "size": 8636, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/ICP.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/ICP.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/ICP.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": 30.1958041958, "max_line_length": 101, "alphanum_fraction": 0.693955535, "num_tokens": 2544, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5736783928749127, "lm_q2_score": 0.5506073655352404, "lm_q1q2_score": 0.3158715485653463}}
{"text": "// Copyright 2004 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// This program performs betweenness centrality (BC) clustering on the\r\n// actor collaboration graph available at\r\n// http://www.nd.edu/~networks/database/index.html and outputs the\r\n// result of clustering in Pajek format.\r\n//\r\n// This program mimics the BC clustering algorithm program implemented\r\n// by Shashikant Penumarthy for JUNG, so that we may compare results\r\n// and timings.\r\n#include <boost/graph/bc_clustering.hpp>\r\n#include <boost/graph/adjacency_list.hpp>\r\n#include <boost/graph/graph_traits.hpp>\r\n#include <fstream>\r\n#include <iostream>\r\n#include <string>\r\n#include <boost/tokenizer.hpp>\r\n#include <boost/lexical_cast.hpp>\r\n#include <map>\r\n\r\nusing namespace boost;\r\n\r\nstruct Actor\r\n{\r\n  Actor(int id = -1) : id(id) {}\r\n\r\n  int id;\r\n};\r\n\r\ntypedef adjacency_list<vecS, vecS, undirectedS, Actor,\r\n                       property<edge_centrality_t, double> > ActorGraph;\r\ntypedef graph_traits<ActorGraph>::vertex_descriptor Vertex;\r\ntypedef graph_traits<ActorGraph>::edge_descriptor Edge;\r\n\r\nvoid load_actor_graph(std::istream& in, ActorGraph& g)\r\n{\r\n  std::map<int, Vertex> actors;\r\n\r\n  std::string line;\r\n  while (getline(in, line)) {\r\n    std::vector<Vertex> actors_in_movie;\r\n\r\n    // Map from the actor numbers on this line to the actor vertices\r\n    typedef tokenizer<char_separator<char> > Tok;\r\n    Tok tok(line, char_separator<char>(\" \"));\r\n    for (Tok::iterator id = tok.begin(); id != tok.end(); ++id) {\r\n      int actor_id = lexical_cast<int>(*id);\r\n      std::map<int, Vertex>::iterator v = actors.find(actor_id);\r\n      if (v == actors.end()) {\r\n        Vertex new_vertex = add_vertex(Actor(actor_id), g);\r\n        actors[actor_id] = new_vertex;\r\n        actors_in_movie.push_back(new_vertex);\r\n      } else {\r\n        actors_in_movie.push_back(v->second);\r\n      }\r\n    }\r\n\r\n    for (std::vector<Vertex>::iterator i = actors_in_movie.begin();\r\n         i != actors_in_movie.end(); ++i) {\r\n      for (std::vector<Vertex>::iterator j = i + 1; \r\n           j != actors_in_movie.end(); ++j) {\r\n        if (!edge(*i, *j, g).second) add_edge(*i, *j, g);\r\n      }\r\n    }\r\n  }\r\n}\r\n\r\ntemplate<typename Graph, typename VertexIndexMap, typename VertexNameMap>\r\nstd::ostream& \r\nwrite_pajek_graph(std::ostream& out, const Graph& g, \r\n                  VertexIndexMap vertex_index, VertexNameMap vertex_name)\r\n{\r\n  out << \"*Vertices \" << num_vertices(g) << '\\n';\r\n  typedef typename graph_traits<Graph>::vertex_iterator vertex_iterator;\r\n  for (vertex_iterator v = vertices(g).first; v != vertices(g).second; ++v) {\r\n    out << get(vertex_index, *v)+1 << \" \\\"\" << get(vertex_name, *v) << \"\\\"\\n\";\r\n  }\r\n\r\n  out << \"*Edges\\n\";\r\n  typedef typename graph_traits<Graph>::edge_iterator edge_iterator;\r\n  for (edge_iterator e = edges(g).first; e != edges(g).second; ++e) {\r\n    out << get(vertex_index, source(*e, g))+1 << ' ' \r\n        << get(vertex_index, target(*e, g))+1 << \" 1.0\\n\"; // HACK!\r\n  }\r\n  return out;\r\n}\r\n\r\nclass actor_clustering_threshold : public bc_clustering_threshold<double>\r\n{\r\n  typedef bc_clustering_threshold<double> inherited;\r\n\r\n public:\r\n  actor_clustering_threshold(double threshold, const ActorGraph& g,\r\n                             bool normalize)\r\n    : inherited(threshold, g, normalize), iter(1) { }\r\n\r\n  bool operator()(double max_centrality, Edge e, const ActorGraph& g)\r\n  {\r\n    std::cout << \"Iter: \" << iter << \" Max Centrality: \" \r\n              << (max_centrality / dividend) << std::endl;\r\n    ++iter;\r\n    return inherited::operator()(max_centrality, e, g);\r\n  }\r\n\r\n private:\r\n  unsigned int iter;\r\n};\r\n\r\nint main(int argc, char* argv[])\r\n{\r\n  std::string in_file;\r\n  std::string out_file;\r\n  double threshold = -1.0;\r\n  bool normalize = false;\r\n\r\n  // Parse command-line options\r\n  {\r\n    int on_arg = 1;\r\n    while (on_arg < argc) {\r\n      std::string arg(argv[on_arg]);\r\n      if (arg == \"-in\") {\r\n        ++on_arg; assert(on_arg < argc);\r\n        in_file = argv[on_arg];\r\n      } else if (arg == \"-out\") {\r\n        ++on_arg; assert(on_arg < argc);\r\n        out_file = argv[on_arg];\r\n      } else if (arg == \"-threshold\") {\r\n        ++on_arg; assert(on_arg < argc);\r\n        threshold = lexical_cast<double>(argv[on_arg]);\r\n      } else if (arg == \"-normalize\") {\r\n        normalize = true;\r\n      } else {\r\n        std::cerr << \"Unrecognized parameter \\\"\" << arg << \"\\\".\\n\";\r\n        return -1;\r\n      }\r\n      ++on_arg;\r\n    }\r\n\r\n    if (in_file.empty() || out_file.empty() || threshold < 0) {\r\n      std::cerr << \"error: syntax is actor_clustering [options]\\n\\n\"\r\n                << \"options are:\\n\"\r\n                << \"\\t-in <infile>\\tInput file\\n\"\r\n                << \"\\t-out <outfile>\\tOutput file\\n\"\r\n                << \"\\t-threshold <value>\\tA threshold value\\n\"\r\n                << \"\\t-normalize\\tNormalize edge centrality scores\\n\";\r\n      return -1;\r\n    }\r\n  }\r\n\r\n  ActorGraph g;\r\n\r\n  // Load the actor graph\r\n  {\r\n    std::cout << \"Building graph.\" << std::endl;\r\n    std::ifstream in(in_file.c_str());\r\n    if (!in) {\r\n      std::cerr << \"Unable to open file \\\"\" << in_file << \"\\\" for input.\\n\";\r\n      return -2;\r\n    }\r\n    load_actor_graph(in, g);\r\n  }\r\n\r\n  // Run the algorithm\r\n  std::cout << \"Clusting...\" << std::endl;\r\n  betweenness_centrality_clustering(g, \r\n    actor_clustering_threshold(threshold, g, normalize), \r\n    get(edge_centrality, g));\r\n\r\n  // Output the graph\r\n  {\r\n    std::cout << \"Writing graph to file: \" << out_file << std::endl;\r\n    std::ofstream out(out_file.c_str());\r\n    if (!out) {\r\n      std::cerr << \"Unable to open file \\\"\" << out_file << \"\\\" for output.\\n\";\r\n      return -3;\r\n    }\r\n    write_pajek_graph(out, g, get(vertex_index, g), get(&Actor::id, g));\r\n  }\r\n  return 0;\r\n}\r\n", "meta": {"hexsha": "ab8bf3a26f6a790af34c9313fc65b765d929ed35", "size": 5999, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/graph/example/actor_clustering.cpp", "max_stars_repo_name": "zyiacas/boost-doc-zh", "max_stars_repo_head_hexsha": "689e5a3a0a4dbead1a960f7b039e3decda54aa2c", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 11.0, "max_stars_repo_stars_event_min_datetime": "2015-07-12T13:04:52.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-30T23:23:46.000Z", "max_issues_repo_path": "libs/graph/example/actor_clustering.cpp", "max_issues_repo_name": "sdfict/boost-doc-zh", "max_issues_repo_head_hexsha": "689e5a3a0a4dbead1a960f7b039e3decda54aa2c", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "libs/graph/example/actor_clustering.cpp", "max_forks_repo_name": "sdfict/boost-doc-zh", "max_forks_repo_head_hexsha": "689e5a3a0a4dbead1a960f7b039e3decda54aa2c", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2015-12-23T01:51:57.000Z", "max_forks_repo_forks_event_max_datetime": "2019-08-25T04:58:32.000Z", "avg_line_length": 31.9095744681, "max_line_length": 79, "alphanum_fraction": 0.5997666278, "num_tokens": 1518, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.5774953651858117, "lm_q1q2_score": 0.31573874874137037}}
{"text": "/**\n * @file imufilter.hpp\n * @brief Filter for obtaining roll/pitch/yaw data from the IMU on Skybotix VI-Sensor\n * @author Fernando Caballero, fcaballero@us.es\n * @author Francisco J Perez-Grau, fjperez@catec.aero\n * @date October 2016\n *\nCopyright (c) 2016, fcaballero, fjperezgrau\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without modification,\nare permitted provided that the following conditions are met:\n\n1. Redistributions of source code must retain the above copyright notice,\nthis list of conditions and the following disclaimer.\n\n2. Redistributions in binary form must reproduce the above copyright notice,\nthis list of conditions and the following disclaimer in the documentation\nand/or other materials provided with the distribution.\n\n3. Neither the name of the copyright holder nor the names of its contributors\nmay be used to endorse or promote products derived from this software without\nspecific 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, DATA,\nOR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\nWHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\nARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGE.\n */\n\n#ifndef __IMUFILTER_H__\n#define __IMUFILTER_H__\n\n#include <Eigen/Core>\n#include <Eigen/Dense>\n#include <sensor_msgs/Imu.h>\n#include <vector>\n\n// Convenient constants\n#define RAD2DEG(X) ( (X) * 57.2957795131)\n#define DEG2RAD(X) ( (X) * 0.01745329251)\n#define LIN2GRAV(X) ( (X) * 0.10197162)\n\n/**\n * @class ImuFilter\n * @brief Estimates IMU angles from acceleration and gyro data\n */\nclass ImuFilter\n{\npublic:\n\t\n    /** @brief Constructor\n     * @param T Prediction period (seconds)\n     * @param imuTopic Name of the IMU data topic\n     * @param calibTime Initial calibration time (seconds)\n     */\n    ImuFilter(double T, std::string imuTopic, double calibTime = 5.0)\n\t{\n        init_ = false;\n        T_ = T;\n        T2_ = T*T;\n        calibTime_ = calibTime;\n\n\t\t// IMU EKF parameters\n        accDev_ = 0.006;//0.001\n        gyrDev_ = 0.005;//0.01;\n        magDev_ = 0;\n        magXs_ = 1.0;\n        magYs_ = 1.0;\n        magZs_ = 1.0;\n        magXo_ = 0.0;\n        magYo_ = 0.0;\n        magZo_ = 0.0;\n        biaDev_ = 0.00001;//0.000001;\n        biaTh_ = 0.005; //0.001;\n\t\t\n        // Setup IMU data subscriber\n        sub_ = nh_.subscribe(imuTopic, 10, &ImuFilter::imuDataCallback, this);\n\t}\n\n\t\n    /** @brief Initialize EKF\n     * Input: vector of sensor_msgs::Imu\n     * The user must continue calling this function with new gyro data until it returns true\n     */\n\tbool initialize(void)\n\t{\n\t\tdouble gx_m, gy_m, gz_m, gx_m2, gy_m2, gz_m2, gx_d, gy_d, gz_d; \n\t\t\n\t\t// Compute mean value and mean square\n\t\tgx_m = gy_m = gz_m = gx_m2 = gy_m2 = gz_m2 = 0.0;\n        for(int i = 0; i < (int)calibData_.size(); i++)\n\t\t{\n            gx_m += calibData_[i].angular_velocity.x;\n            gy_m += calibData_[i].angular_velocity.y;\n            gz_m += calibData_[i].angular_velocity.z;\n            gx_m2 += calibData_[i].angular_velocity.x*calibData_[i].angular_velocity.x;\n            gy_m2 += calibData_[i].angular_velocity.y*calibData_[i].angular_velocity.y;\n            gz_m2 += calibData_[i].angular_velocity.z*calibData_[i].angular_velocity.z;\n\t\t}\n        gx_m = gx_m/(double)calibData_.size();\n        gy_m = gy_m/(double)calibData_.size();\n        gz_m = gz_m/(double)calibData_.size();\n        gx_m2 = gx_m2/(double)calibData_.size();\n        gy_m2 = gy_m2/(double)calibData_.size();\n        gz_m2 = gz_m2/(double)calibData_.size();\n\t\t//std::cout << \"gxM: \" << gx_m << \", gyM: \" << gy_m << \", gzM: \" << gz_m << std::endl;\n\t\t\n\t\t// Compute standar deviation of gyros\n\t\tgx_d = sqrt(gx_m2-gx_m*gx_m);\n\t\tgy_d = sqrt(gy_m2-gy_m*gy_m);\n\t\tgz_d = sqrt(gz_m2-gz_m*gz_m);\n\t\t//std::cout << \"gxDev: \" << gx_d << \", gyDev: \" << gy_d << \", gzDev: \" << gz_d << std::endl;\n\t\t\n\t\t// Initalize compass calibration\n        magCal_[0] = magXs_; magCal_[1] = magYs_; magCal_[2] = magZs_;\n        magCal_[3] = magXo_; magCal_[4] = magYo_; magCal_[5] = magZo_;\n\t\t\n\t\t// Initialize sensor variances\n        accVar_[0] = accDev_*accDev_; \taccVar_[1] = accDev_*accDev_; \taccVar_[2] = accDev_*accDev_;\t\t// Variance in g\n        gyrVar_[0] = gyrDev_*gyrDev_; gyrVar_[1] = gyrDev_*gyrDev_; gyrVar_[2] = gyrDev_*gyrDev_;\t// Variance in rad/s\n        magVar_[0] = magDev_*magDev_; \tmagVar_[1] = magDev_*magDev_; \tmagVar_[2] = magDev_*magDev_;\t// Variance in mGaus wth data normalized to 1\n        biaVar_[0] = biaDev_*biaDev_; biaVar_[1] = biaDev_*biaDev_; biaVar_[2] = biaDev_*biaDev_;\t// Variance in rad/s\n\t\t\n\t\t// Initialize accelerometer threshold\n        accTh_ = sqrt(accVar_[0]+accVar_[1]+accVar_[2]);\n\t\t\n\t\t// Initialize state vector x = [rx, ry, rz, gbx, gby, gbz]\n        rx_ = ry_ = rz_ = 0.0;\n        gbx_ = gx_m;\n        gby_ = gy_m;\n        gbz_ = gz_m;\n\t\t\n\t\t// Initialize covariance matrix\n        P_.setIdentity(6, 6);\n        P_(0,0) = M_PI_2;\n        P_(1,1) = M_PI_2;\n        P_(2,2) = M_PI_2;\n        P_(3,3) = 0.01*0.01;\n        P_(4,4) = 0.01*0.01;\n        P_(5,5) = 0.01*0.01;\n        /*P_(3,3) = biaVar_[0];\n        P_(4,4) = biaVar_[1];\n        P_(5,5) = biaVar_[2];*/\n\t\t\n        if(gx_d < biaTh_ && gy_d < biaTh_ && gz_d < biaTh_)\n\t\t{\n            init_ = true;\n            ROS_INFO(\"IMU filter initialized\");\n\t\t\n\t\t\treturn true;\n\t\t}\n\t\telse\n\t\t\treturn false;\n\t}\t\n\t\n    /** EKF prediction stage based on gyro information\n     * @param[in] gx Raw X gyro data (rad/s)\n     * @param[in] gy Raw Y gyro data (rad/s)\n     * @param[in] gz Raw Z gyro data (rad/s)\n     */\n\tbool predict(double gx, double gy, double gz)\n\t{\n\t\t// Check initialization \n        if(!init_)\n\t\t\treturn false;\n\t\t\n\t\t// Compute matrix F \n\t\tEigen::Matrix<double, 6, 6> F;\n        F(0,0) = 1, F(0,1) = 0, F(0,2) = 0, F(0,3) = -T_, F(0,4) = 0,   F(0,5) = 0;\n        F(1,0) = 0, F(1,1) = 1, F(1,2) = 0, F(1,3) = 0,  F(1,4) = -T_,  F(1,5) = 0;\n        F(2,0) = 0, F(2,1) = 0, F(2,2) = 1, F(2,3) = 0,  F(2,4) = 0,   F(2,5) = -T_;\n\t\tF(3,0) = 0, F(3,1) = 0, F(3,2) = 0, F(3,3) = 1,  F(3,4) = 0,   F(3,5) = 0;\n\t\tF(4,0) = 0, F(4,1) = 0, F(4,2) = 0, F(4,3) = 0,  F(4,4) = 1,   F(4,5) = 0;\n\t\tF(5,0) = 0, F(5,1) = 0, F(5,2) = 0, F(5,3) = 0,  F(5,4) = 0,   F(5,5) = 1;\n\n\t\t// Update covariance matrix\n        P_ = F*P_*F.transpose();\n        P_(0,0) += gyrVar_[0]*T2_;\n        P_(1,1) += gyrVar_[1]*T2_;\n        P_(2,2) += gyrVar_[2]*T2_;\n        P_(3,3) += biaVar_[0]*T_;\n        P_(4,4) += biaVar_[1]*T_;\n        P_(5,5) += biaVar_[2]*T_;\n\t\t\n\t\t// Update state vector\n        rx_ += T_*(gx - gbx_);\n        ry_ += T_*(gy - gby_);\n        rz_ += T_*(gz - gbz_);\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\treturn true; \n\t}\n\t\n    /** EKF update stage based on accelerometer information\n     * @param[in] ax Raw X accelerometer data (g)\n     * @param[in] ay Raw Y accelerometer data (g)\n     * @param[in] az Raw Z accelerometer data (g)\n     */\n\tbool update(double ax, double ay, double az)\n\t{\n\t\tdouble crx, srx, cry, sry, mod, y[3];\n\t\t\n\t\t// Check initialization \n        if(!init_)\n\t\t\treturn false;\n\t\t\n\t\t// Pre-compute constants\n        crx = cos(rx_);\n        cry = cos(ry_);\n        srx = sin(rx_);\n        sry = sin(ry_);\n\t\t\n\t\t// Create measurement jacobian H\n\t\tEigen::Matrix<double, 3, 6> H;\n\t\tH(0,0) = 0;\t\t\tH(0,1) = cry;\t\tH(0,2) = 0; H(0,3) = 0; H(0,4) = 0; H(0,5) = 0;\n\t\tH(1,0) = -crx*cry; \tH(1,1) = srx*sry; \tH(1,2) = 0; H(1,3) = 0; H(1,4) = 0; H(1,5) = 0;\n\t\tH(2,0) = cry*srx;\tH(2,1) = crx*sry;\tH(2,2) = 0; H(2,3) = 0; H(2,4) = 0; H(2,5) = 0;\n\t\t\n\t\t// Compute measurement noise jacoban R\n\t\tEigen::Matrix<double, 3, 3> R;\n\t\tmod = fabs(sqrt(ax*ax + ay*ay + az*az)-1);\n\t\tR.setZero(3, 3);\n        R(0,0) = accVar_[0];\n        R(1,1) = accVar_[1];\n        R(2,2) = accVar_[2];\n\t\t/*if(mod > accTh)\n\t\t{\n\t\t\tR(0,0) += 1.5*mod*mod;\n\t\t\tR(1,1) += 1.5*mod*mod;\n\t\t\tR(2,2) += 1.5*mod*mod;\n\t\t}*/\n\t\t\n\t\t// Compute innovation matrix\n\t\tEigen::Matrix<double, 3, 3> S;\n        S = H*P_*H.transpose()+R;\n\t\t\n\t\t// Compute kalman gain\n\t\tEigen::Matrix<double, 6, 3> K;\n        K = P_*H.transpose()*S.inverse();\n\t\t\n\t\t// Compute mean error\n\t\ty[0] = ax-sry;\n\t\ty[1] = ay+cry*srx;\n\t\ty[2] = az+crx*cry;\n\t\t\n\t\t// Compute new state vector\n        rx_ += K(0,0)*y[0]+K(0,1)*y[1]+K(0,2)*y[2];\n        ry_ += K(1,0)*y[0]+K(1,1)*y[1]+K(1,2)*y[2];\n        rz_ += K(2,0)*y[0]+K(2,1)*y[1]+K(2,2)*y[2];\n        gbx_ += K(3,0)*y[0]+K(3,1)*y[1]+K(3,2)*y[2];\n        gby_ += K(4,0)*y[0]+K(4,1)*y[1]+K(4,2)*y[2];\n        gbz_ += K(5,0)*y[0]+K(5,1)*y[1]+K(5,2)*y[2];\n\t\t\n\t\t// Compute new covariance matrix\n\t\tEigen::Matrix<double, 6, 6> I;\n\t\tI.setIdentity(6, 6);\n        P_ = (I-K*H)*P_;\n\t\t\n\t\treturn true;\n\t}\n\n    /** EKF update stage based on accelerometer information\n     * @param[in] ax Raw X accelerometer data (g)\n     * @param[in] ay Raw Y accelerometer data (g)\n     * @param[in] az Raw Z accelerometer data (g)\n     * @param[in] mx Raw X magnetometer data ()\n     * @param[in] my Raw Y magnetometer data ()\n     * @param[in] mz Raw Z magnetometer data ()\n     */\n\tbool update(double ax, double ay, double az, double mx, double my, double mz)\n\t{\n\t\tdouble crx, srx, cry, sry, crz, srz, mod, y[5], hx, hy;\n\t\t\n\t\t// Check initialization \n        if(!init_)\n\t\t\treturn false;\n\t\t\n\t\t// Remove distortion and normalize magnetometer\n        mx = (mx - magCal_[3])/magCal_[0];\n        my = (my - magCal_[4])/magCal_[1];\n        mz = (mz - magCal_[5])/magCal_[2];\n\t\tmod = sqrt(mx*mx + my*my + mz*mz);\n\t\tmx /= mod;\n\t\tmy /= mod;\n\t\tmz /= mod;\n\t\t\n\t\t// Pre-compute constants\n        crx = cos(rx_);\n        cry = cos(ry_);\n        crz = cos(rz_);\n        srx = sin(rx_);\n        sry = sin(ry_);\n        srz = sin(rz_);\n\t\t\n\t\t// Create measurement jacobian H\n\t\tEigen::Matrix<double, 5, 6> H;\n\t\tH(0,0) = 0;\t\t\tH(0,1) = cry;\t\tH(0,2) = 0; \tH(0,3) = 0; H(0,4) = 0; H(0,5) = 0;\n\t\tH(1,0) = -crx*cry; \tH(1,1) = srx*sry; \tH(1,2) = 0; \tH(1,3) = 0; H(1,4) = 0; H(1,5) = 0;\n\t\tH(2,0) = cry*srx;\tH(2,1) = crx*sry;\tH(2,2) = 0; \tH(2,3) = 0; H(2,4) = 0; H(2,5) = 0;\n\t\tH(3,0) = 0;\t\t\tH(3,1) = 0;\t\t\tH(3,2) = -srz; \tH(3,3) = 0; H(3,4) = 0; H(3,5) = 0;\n\t\tH(4,0) = 0;\t\t\tH(4,1) = 0;\t\t\tH(4,2) = -crz; \tH(4,3) = 0; H(4,4) = 0; H(4,5) = 0;\n\t\t\n        // Compute measurement noise jacobian R\n\t\tEigen::Matrix<double, 5, 5> R;\n\t\tmod = fabs(sqrt(ax*ax + ay*ay + az*az)-1);\n\t\tR.setZero(5, 5);\n        R(0,0) = accVar_[0];\n        R(1,1) = accVar_[1];\n        R(2,2) = accVar_[2];\n        R(3,3) = magVar_[0];\n        R(4,4) = magVar_[1];\n        if(mod > accTh_)\n\t\t{\n\t\t\tR(0,0) += 1.5*mod*mod;\n\t\t\tR(1,1) += 1.5*mod*mod;\n\t\t\tR(2,2) += 1.5*mod*mod;\n\t\t}\n\t\t\n\t\t// Compute innovation matrix\n\t\tEigen::Matrix<double, 5, 5> S;\n        S = H*P_*H.transpose()+R;\n\t\t\n        // Compute Kalman gain\n\t\tEigen::Matrix<double, 6, 5> K; \n        K = P_*H.transpose()*S.inverse();\n\t\t\n\t\t// Compute mean error\n\t\thx = mx*cry + mz*crx*sry + my*srx*sry;\n\t\thy = my*crx - mz*srx;\n\t\tmod = sqrt(hx*hx+hy*hy);\n\t\ty[0] = ax-sry;\n\t\ty[1] = ay+cry*srx;\n\t\ty[2] = az+crx*cry;\n\t\ty[3] = hx/mod-crz;\n\t\ty[4] = hy/mod+srz;\n\t\t\n\t\t// Compute new state vector\n        rx_ += K(0,0)*y[0]+K(0,1)*y[1]+K(0,2)*y[2]+K(0,3)*y[3]+K(0,4)*y[4];\n        ry_ += K(1,0)*y[0]+K(1,1)*y[1]+K(1,2)*y[2]+K(1,3)*y[3]+K(1,4)*y[4];\n        rz_ += K(2,0)*y[0]+K(2,1)*y[1]+K(2,2)*y[2]+K(2,3)*y[3]+K(2,4)*y[4];\n        gbx_ += K(3,0)*y[0]+K(3,1)*y[1]+K(3,2)*y[2]+K(3,3)*y[3]+K(3,4)*y[4];\n        gby_ += K(4,0)*y[0]+K(4,1)*y[1]+K(4,2)*y[2]+K(4,3)*y[3]+K(4,4)*y[4];\n        gbz_ += K(5,0)*y[0]+K(5,1)*y[1]+K(5,2)*y[2]+K(5,3)*y[3]+K(5,4)*y[4];\n\t\t\n\t\t// Compute new covariance matrix\n\t\tEigen::Matrix<double, 6, 6> I;\n\t\tI.setIdentity(6, 6);\n        P_ = (I-K*H)*P_;\n\t\t\n\t\treturn true;\n\t}\n\t\n    /** @brief Get estimated Euler angles in radians interval [-PI,PI] rad\n     * @param[out] rx Estimated roll (rad)\n     * @param[out] ry Estimated pitch (rad)\n     * @param[out] rz Estimated yaw (rad)\n     */\n    bool getAngles(double &rx, double &ry, double &rz)\n\t{\n        rx = Pi2PiRange(rx_);\n        ry = Pi2PiRange(ry_);\n        rz = Pi2PiRange(rz_);\n\t\treturn true;\n\t}\n\n    /** @brief Get estimated integrated Euler angles since last reset\n     * @param[out] rx Estimated integrated roll (rad)\n     * @param[out] ry Estimated integrated pitch (rad)\n     * @param[out] rz Estimated integrated yaw (rad)\n     */\n    bool getAngleIntegration(double &irx, double &iry, double &irz)\n    {\n        irx = irx_;\n        iry = iry_;\n        irz = irz_;\n        return true;\n    }\n\n    /** @brief Reset integrated angles\n     */\n    bool resetAngleIntegration(void)\n    {\n        irx_ = iry_ = irz_ = 0.0;\n        return true;\n    }\n\n    /** @brief Get estimated gyro biases in rad/s\n     * @param[out] gbx Estimated X gyro bias (rad/s)\n     * @param[out] gby Estimated Y gyro bias (rad/s)\n     * @param[out] gbz Estimated Z gyro bias (rad/s)\n     */\n    bool getBIAS(double &gbx, double &gby, double &gbz)\n\t{\n        gbx = gbx_;\n        gby = gby_;\n        gbz = gbz_;\n\t\t\n\t\treturn true;\n\t}\n\t\n    /** @brief IMU initialization return function\n     * @return Returns true if IMU initialized\n     */\n\tbool isInit(void)\n\t{\n        return init_;\n\t}\n\n    /** IMU sensor data callback\n     * @param[in] msg IMU data message\n     */\n\tvoid imuDataCallback(const sensor_msgs::Imu::ConstPtr& msg)\n\t{\n\t\t// Check for IMU initialization\n        if(!init_)\n\t\t{\n            calibData_.push_back(*msg);\n            if(calibData_.size() > calibTime_/T_)\n\t\t\t\tinitialize();\n\t\t\t\n\t\t\treturn;\n\t\t}\t\n\t\t\n\t\t// Process sensor data\n\t\tpredict(msg->angular_velocity.z, msg->angular_velocity.x, msg->angular_velocity.y);\n\t\tupdate(LIN2GRAV(msg->linear_acceleration.z), LIN2GRAV(msg->linear_acceleration.x), LIN2GRAV(msg->linear_acceleration.y));\n\n        // Integrate angle rates\n        irx_ += (msg->angular_velocity.z-gbx_)*T_;\n        iry_ += (msg->angular_velocity.x-gby_)*T_;\n        irz_ += (msg->angular_velocity.y-gbz_)*T_;\n    }\n\t\nprotected:\n\n    /** @brief Round down absolute function\n     * @param[in] value Input value\n     * @return Input value floored\n     */\n    double floorAbsolute( double value )\n\t{\n\t  if (value < 0.0)\n\t\treturn ceil( value );\n\t  else\n\t\treturn floor( value );\n\t}\n\n    /** @brief Convert angles into interval [-PI,PI] rad\n     * @param[in] contAngle Input angle (rad)\n     * @return Input angle in interval [-PI,PI] rad\n     */\n    double Pi2PiRange(double contAngle)\n\t{\n        double boundAngle = 0.0;\n        if(fabs(contAngle)<=M_PI)\n            boundAngle= contAngle;\n\t\telse\n\t\t{\n            if(contAngle > M_PI)\n                boundAngle = (contAngle-2*M_PI) - 2*M_PI*floorAbsolute((contAngle-M_PI)/(2*M_PI));\n\t\t\t\n            if(contAngle < - M_PI)\n                boundAngle = (contAngle+2*M_PI) - 2*M_PI*floorAbsolute((contAngle+M_PI)/(2*M_PI));\n\t\t}\n\t\t\n        return boundAngle;\n\t}\n\t\n\n    double calibTime_;      /**< IMU calibration time*/\n\n    double T_;                                  /**< IMU KF prediction period*/\n    double T2_;                                 /**< Squared IMU KF prediction period*/\n    double rx_, ry_, rz_, gbx_, gby_, gbz_;     /**< IMU KF state vector x = [rx, ry, rz, gbx, gby, gbz]*/\n    Eigen::MatrixXd P_;                         /**< IMU KF matrix*/\n\t\n    double magCal_[6];      /**< Sensor calib info [gainX, gainY, gainZ, offsetX, offsetY, offsetZ]*/\n\t\n    double accVar_[3];      /**< Accelerometers variances [varX, varY, varZ]*/\n    double magVar_[3];      /**< Magnetometers variances [varX, varY, varZ]*/\n    double gyrVar_[3];      /**< Gyroscopes variances [varX, varY, varZ]*/\n    double biaVar_[3];      /**< Bias variances [varX, varY, varZ]*/\n\t\n    double accTh_;          /**< Accelerometer threshold for filter updating*/\n\t\n    bool init_;             /**< Flag indicating if IMU has been initialized*/\n\t\n\t// EKF Parameters\n    double accDev_;\n    double gyrDev_;\n    double magDev_;\n    double biaDev_;\n    double biaTh_;\n    double magXs_;\n    double magYs_;\n    double magZs_;\n    double magXo_;\n    double magYo_;\n    double magZo_;\n\t\n    std::vector<sensor_msgs::Imu> calibData_;   /**< IMU data for initialization*/\n\t\n    ros::NodeHandle nh_;        /**< ROS node handler*/\n    ros::Subscriber sub_;       /**< IMU data subscriber*/\n\n    double irx_, iry_, irz_;    /**< Integrated angles since last reset*/\n};\n\n#endif\n\n\n\n\n\n\n\n\n", "meta": {"hexsha": "200ac13a9b6e27f024c8d3af6b4e20b5447b7e0d", "size": 16673, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/imufilter.hpp", "max_stars_repo_name": "abougouffa/viodom", "max_stars_repo_head_hexsha": "9ffac66ed04ca27b2a32e80424c19e7476b21ed1", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2017-12-15T05:56:03.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-07T15:52:22.000Z", "max_issues_repo_path": "src/imufilter.hpp", "max_issues_repo_name": "abougouffa/viodom", "max_issues_repo_head_hexsha": "9ffac66ed04ca27b2a32e80424c19e7476b21ed1", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-04-30T18:29:39.000Z", "max_issues_repo_issues_event_max_datetime": "2020-05-01T09:42:12.000Z", "max_forks_repo_path": "src/imufilter.hpp", "max_forks_repo_name": "abougouffa/viodom", "max_forks_repo_head_hexsha": "9ffac66ed04ca27b2a32e80424c19e7476b21ed1", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2017-07-16T09:17:42.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-31T16:04:40.000Z", "avg_line_length": 31.8187022901, "max_line_length": 145, "alphanum_fraction": 0.5678642116, "num_tokens": 6116, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7025300698514777, "lm_q2_score": 0.4493926344647597, "lm_q1q2_score": 0.3157118388812672}}
{"text": "/*\n  Copyright (c) 2012,2013,2014 Matthew H. Reilly (kb1vc)\n  All rights reserved.\n\n  Redistribution and use in source and binary forms, with or without\n  modification, are permitted provided that the following conditions are\n  met:\n\n  Redistributions of source code must retain the above copyright\n  notice, this list of conditions and the following disclaimer.\n  Redistributions in binary form must reproduce the above copyright\n  notice, this list of conditions and the following disclaimer in\n  the documentation and/or other materials provided with the\n  distribution.\n\n  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n  \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n  A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n  HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n  SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n  LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n  DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n  THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n  (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n  OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*/\n\n#include \"HilbertTransformer.hxx\"\n\n#include <iostream>\n#include <string.h>\n#include <fftw3.h>\n#include <boost/format.hpp>\n\nint dbgctr = 0;\n\nstatic unsigned int ipow(unsigned int x, unsigned int y) __attribute__ ((unused));\nstatic unsigned int ipow(unsigned int x, unsigned int y)\n{\n  unsigned int ret;\n  ret = 1;\n  unsigned int i;\n\n  for(i = 0; i < y; i++) {\n    ret *= x; \n  }\n\n  return ret; \n}\n\nSoDa::HilbertTransformer::HilbertTransformer(unsigned int inout_buffer_length,\n\t\t\t\t\t     unsigned int filter_length) :\n  SoDa::Base(\"HilbertTransformer\")\n{\n  // these are the salient dimensions for this Overlap/Save\n  // widget (for terminology, see Lyons pages 719ff\n  M = inout_buffer_length;\n\n  // now find N.\n  N = 4 * filter_length;\n  while(N < (M + filter_length)) {\n    N = N * 2; \n  }\n  // now that we have N, we can back-calculate Q.\n  Q = (N - M) + 1;\n\n  //  std::cerr << \"\\n\\nHILBERT picked N = \" << N << \" Q = \" << Q << \" M = \" << M << std::endl;\n\n\n  std::complex<float> htu[N], htl[N]; \n\n  // create the impulse response images\n  // There is probably a simpler way, but the obvious real/imag swap\n  // scheme doesn't work at all well. \n  HTu_filter = (std::complex<float> *) fftwf_malloc(sizeof(std::complex<float>) * N);\n  HTl_filter = (std::complex<float> *) fftwf_malloc(sizeof(std::complex<float>) * N);\n  Pass_U_filter = (std::complex<float> *) fftwf_malloc(sizeof(std::complex<float>) * N);\n  Pass_L_filter = (std::complex<float> *) fftwf_malloc(sizeof(std::complex<float>) * N);\n  fftwf_plan HTu_plan = fftwf_plan_dft_1d(N,\n\t\t\t\t\t (fftwf_complex *) htu, (fftwf_complex *) HTu_filter, \n\t\t\t\t\t FFTW_FORWARD, FFTW_ESTIMATE);\n  if(HTu_plan == NULL) {\n    throw SoDa::Exception(\"Hilbert had trouble creating HT upper plan...\\n\");\n  }\n  fftwf_plan HTl_plan = fftwf_plan_dft_1d(N,\n\t\t\t\t\t (fftwf_complex *) htl, (fftwf_complex *) HTl_filter, \n\t\t\t\t\t FFTW_FORWARD, FFTW_ESTIMATE);\n  if(HTl_plan == NULL) {\n    throw SoDa::Exception(\"Hilbert had trouble creating HT lower plan...\\n\");\n  }\n\n  // now build the time domain image of the filter.\n  unsigned int i, j;\n  for(i = 0; i < N; i++) {\n    htu[i] = htl[i] = std::complex<float>(0.0, 0.0);\n  }\n  // this is actually a scaled ht -- removing the Fs * 2 / pi scaling factor.\n  for(i = 0, j = (Q / 2); i < (Q / 2); i++) {\n    if((i & 1) != 0) {\n      htu[j + i] = std::complex<float>(1.0 / ((float) i), 0.0);\n      htu[j - i] = std::complex<float>(-1.0 / ((float) i), 0.0);\n      htl[j + i] = std::complex<float>(-1.0 / ((float) i), 0.0);\n      htl[j - i] = std::complex<float>(1.0 / ((float) i), 0.0);\n    }\n  } \n  fftwf_execute(HTu_plan);\n  fftwf_execute(HTl_plan);\n  // now we have the HT filter image\n  fftwf_destroy_plan(HTu_plan);\n  fftwf_destroy_plan(HTl_plan);\n\n  // now do the delay filter\n  fftwf_plan dly_plan = fftwf_plan_dft_1d(N,\n\t\t\t\t\t (fftwf_complex *) htu, (fftwf_complex *) Pass_U_filter, \n\t\t\t\t\t FFTW_FORWARD, FFTW_ESTIMATE);\n  // load up a new impulse response\n  for(i = 0; i < N; i++) htu[i] = std::complex<float>(0.0, 0.0);\n  htu[Q/2] = std::complex<float>(1.0, 0.0);\n  // now create the passthrough filter\n  fftwf_execute(dly_plan);\n  fftwf_destroy_plan(dly_plan); \n\n  // Do some equalization on the pass filter to fix the low frequency response\n  // to match the response of the HT filter.\n  for(i = 0; i < N; i++) {\n    float tumag = abs(HTu_filter[i]);\n    float tlmag = abs(HTl_filter[i]);\n    float pmag = abs(Pass_U_filter[i]);\n    float uadj = 1.0;\n    float ladj = 1.0;\n    if(pmag > 0.001) {\n      uadj = tumag / pmag;\n      ladj = tlmag / pmag;\n      if (uadj > 2) uadj = 1.0; \n      if (ladj > 2) ladj = 1.0; \n    }\n    Pass_L_filter[i] = ladj * Pass_U_filter[i]; \n    Pass_U_filter[i] = uadj * Pass_U_filter[i]; \n  }\n\n\n  // calculate the magnitudes of the two filters.\n  float hmag, pmag;\n  hmag = 0.0;\n  pmag = 0.0; \n  for(i = 0; i < N; i++) {\n    hmag += HTu_filter[i].real() * HTu_filter[i].real()\n      + HTu_filter[i].imag() * HTu_filter[i].imag();\n    pmag += Pass_U_filter[i].real() * Pass_U_filter[i].real()\n      + Pass_U_filter[i].imag() * Pass_U_filter[i].imag(); \n  }\n  \n  // now allocate all the storage vectors\n  fft_I_input = (std::complex<float> *) fftwf_malloc(sizeof(std::complex<float>) * (N + 128));\n  fft_Q_input = (std::complex<float> *) fftwf_malloc(sizeof(std::complex<float>) * (N + 128));\n  fft_I_output = (std::complex<float> *) fftwf_malloc(sizeof(std::complex<float>) * (N + 128));\n  fft_Q_output = (std::complex<float> *) fftwf_malloc(sizeof(std::complex<float>) * (N + 128));\n  ifft_I_input = (std::complex<float> *) fftwf_malloc(sizeof(std::complex<float>) * (N + 128));\n  ifft_Q_input = (std::complex<float> *) fftwf_malloc(sizeof(std::complex<float>) * (N + 128));\n  ifft_I_output = (std::complex<float> *) fftwf_malloc(sizeof(std::complex<float>) * (N + 128));\n  ifft_Q_output = (std::complex<float> *) fftwf_malloc(sizeof(std::complex<float>) * (N + 128));\n\n  // and create the plans\n  forward_I_plan = fftwf_plan_dft_1d(N,\n\t\t\t\t     (fftwf_complex *) fft_I_input, (fftwf_complex *) fft_I_output,\n\t\t\t\t     FFTW_FORWARD, FFTW_ESTIMATE);\n  if(forward_I_plan == NULL) {\n    throw SoDa::Exception(\"Hilbert had trouble creating forward I plan...\\n\");\n  }\n\n  forward_Q_plan = fftwf_plan_dft_1d(N,\n\t\t\t\t     (fftwf_complex *) fft_Q_input,\n\t\t\t\t     (fftwf_complex *) fft_Q_output,\n\t\t\t\t     FFTW_FORWARD, FFTW_ESTIMATE);\n  if(forward_Q_plan == NULL) {\n    throw SoDa::Exception(\"Hilbert had trouble creating forward Q plan...\\n\");\n  }\n\n  backward_I_plan = fftwf_plan_dft_1d(N, (fftwf_complex *) ifft_I_input,\n\t\t\t\t      (fftwf_complex *) ifft_I_output,\n\t\t\t\t      FFTW_BACKWARD, FFTW_ESTIMATE);\n  if(backward_I_plan == NULL) {\n    throw SoDa::Exception(\"Hilbert had trouble creating backward I plan...\\n\");\n  }\n  backward_Q_plan = fftwf_plan_dft_1d(N, (fftwf_complex *) ifft_Q_input,\n\t\t\t\t      (fftwf_complex *) ifft_Q_output,\n\t\t\t\t      FFTW_BACKWARD, FFTW_ESTIMATE);\n  if(backward_Q_plan == NULL) {\n    throw SoDa::Exception(\"Hilbert had trouble creating backward Q plan...\\n\");\n  }\n  // zero out the start of the fft_input buffer for the first iteration.\n  for(i = 0; i <= Q-1; i++) {\n    fft_I_input[i] = 0.0;\n    fft_Q_input[i] = 0.0;\n  }\n  \n  // finally, set the transform gain (1/N)\n  //   passthrough_gain = 1.0 / ((float) N); \n  //  H_transform_gain = 2.0 / (M_PI * 0.966 * ((float) N)); // 0.966 is a fudge factor\n  H_transform_gain = 2.0 / (M_PI * ((float) N)); \n  passthrough_gain = H_transform_gain;\n}\n\nunsigned int SoDa::HilbertTransformer::apply(std::complex<float> * inbuf,\n\t\t\t\t\t     std::complex<float> * outbuf,\n\t\t\t\t\t     bool pos_sided, float gain)\n{\n  unsigned int i, j;\n\n  std::complex<float> *HT_F;\n  std::complex<float> *PA_F;\n\n  if(pos_sided) {\n    HT_F = HTl_filter;\n    PA_F = Pass_L_filter; \n  }\n  else {\n    HT_F = HTu_filter;\n    PA_F = Pass_U_filter; \n  }\n  // Note we're using overlap-and-save  see the OSFilter implementation\n  // or Lyons pages 719ff\n  // copy the I channel to the tail of the input buffer.\n  memcpy(&(fft_I_input[Q-1]), inbuf, sizeof(std::complex<float>) * M);\n\n  // do a pass through\n  fftwf_execute(forward_I_plan); \n\n  // now save the tail of the input to the save buffer\n  memcpy(fft_I_input, &(inbuf[1 + (M - Q)]), sizeof(std::complex<float>) * (Q - 1));\n\n  // now apply the delay filter and the hilbert transform\n  for(i = 0; i < N; i++) {\n    ifft_Q_input[i] = fft_I_output[i] * HT_F[i]; \n    ifft_I_input[i] = fft_I_output[i] * PA_F[i]; \n  }\n  \n  // do the inverse fft for the I and Q channels\n  fftwf_execute(backward_I_plan);\n  fftwf_execute(backward_Q_plan);\n\n  // now put the two channels together\n  // Note that we're shifting the normal sampling window.  This is because the\n  // quadrature sampler is just not quite right for\n  for(i = 0, j = Q-1; i < M; i++, j++) {\n    // seems like it worked once... but apparent shift is same for either sideband\n    outbuf[i] = std::complex<float>(ifft_I_output[j].real() * passthrough_gain * gain,\n\t\t\t\t    ifft_Q_output[j].real() * H_transform_gain * gain);\n  }\n\n  dbgctr++;\n\n\n  return M; \n}\n\n\nunsigned int SoDa::HilbertTransformer::apply(float * inbuf,\n\t\t\t\t\t     std::complex<float> * outbuf,\n\t\t\t\t\t     bool pos_sided, float gain)\n{\n  unsigned int i;\n  // This creates an analytic signal from a single input buffer.\n\n  // Note we're using overlap-and-save  see the OSFilter implementation\n  // or Lyons pages 719ff\n  std::complex<float> cinbuf[M];\n\n\n  // copy the I channel to the tail of the input buffer.\n  for(i = 0; i < M; i++) {\n    cinbuf[i] = std::complex<float>(inbuf[i], 0.0); \n  }\n\n  // call the complex HT\n  return apply(cinbuf, outbuf, pos_sided, gain); \n\n  \n  return M; \n}\n\n\nunsigned int SoDa::HilbertTransformer::applyIQ(std::complex<float> * inbuf,\n\t\t\t\t\t       std::complex<float> * outbuf,\n\t\t\t\t\t       float gain)\n{\n  unsigned int i, j;\n  // This creates an analytic signal from a single input buffer.\n\n  // Note we're using overlap-and-save  see the OSFilter implementation\n  // or Lyons pages 719ff\n\n  // copy the I channel to the tail of the I input buffer.\n  // copy the I channel to the tail of the Q input buffer.\n  for(i = 0; i < M; i++) {\n    fft_I_input[i + (Q-1)] = std::complex<float>(inbuf[i].real(), 0.0); \n    fft_Q_input[i + (Q-1)] = std::complex<float>(inbuf[i].imag(), 0.0); \n  }\n\n  // do a the I (passthrough) and Q channel FFTs\n  fftwf_execute(forward_I_plan);\n  fftwf_execute(forward_Q_plan);\n  \n\n  // now save the tail of the input to the save buffer\n  for(i = 0; i < (Q - 1); i++) {\n    fft_I_input[i] = std::complex<float>(inbuf[i + 1 + (M - Q)].real(), 0.0); \n    fft_Q_input[i] = std::complex<float>(inbuf[i + 1 + (M - Q)].imag(), 0.0); \n  }\n\n  // now apply the delay filter (to I) and the hilbert transform (to Q)\n  for(i = 0; i < N; i++) {\n    ifft_Q_input[i] = fft_Q_output[i] * HTu_filter[i]; \n    ifft_I_input[i] = fft_I_output[i] * Pass_U_filter[i]; \n  }\n  \n  // do the inverse fft for the I and Q channels\n  fftwf_execute(backward_I_plan);\n  fftwf_execute(backward_Q_plan);\n\n  // now put the two channels together\n  // Note that we're shifting the normal sampling window.  This is because the\n  // quadrature sampler is just not quite right for\n  for(i = 0, j = Q-1; i < M; i++, j++) {\n    outbuf[i] = std::complex<float>(ifft_I_output[j].real() * passthrough_gain * gain,\n\t\t\t\t    ifft_Q_output[j].real() * H_transform_gain * gain);\n  }\n\n  dbgctr++;\n\n  return M; \n}\n\n\n\nstd::ostream & SoDa::HilbertTransformer::dump(std::ostream & os)\n{\n  unsigned int i, j;\n  for(i = 0; i < N; i++) {\n    j = i; \n    float mag = std::abs(HTl_filter[i]);\n    float ang = std::arg(HTl_filter[i]); \n    float pmag = std::abs(Pass_L_filter[i]);\n    float pang = std::arg(Pass_L_filter[i]); \n    os << boost::format(\"%d %f %f %f %f %f %f %f %f\\n\")\n      % j % HTu_filter[i].real() % HTu_filter[i].imag() % mag % ang % \n      Pass_U_filter[i].real() % Pass_U_filter[i].imag() % pmag % pang; \n  }\n  return os; \n}  \n", "meta": {"hexsha": "16bfbe1020be9b63157991ed2f5bcbe4b3824f89", "size": 12209, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "src/HilbertTransformer.cxx", "max_stars_repo_name": "kb1vc/SoDaRadio", "max_stars_repo_head_hexsha": "0a41fa3d795b1c93795ad62ad17bf2de5f60a752", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2017-10-27T16:01:05.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-16T08:12:42.000Z", "max_issues_repo_path": "src/HilbertTransformer.cxx", "max_issues_repo_name": "dd0vs/SoDaRadio", "max_issues_repo_head_hexsha": "0a41fa3d795b1c93795ad62ad17bf2de5f60a752", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 11.0, "max_issues_repo_issues_event_min_datetime": "2017-09-16T03:13:11.000Z", "max_issues_repo_issues_event_max_datetime": "2020-12-11T09:11:35.000Z", "max_forks_repo_path": "src/HilbertTransformer.cxx", "max_forks_repo_name": "dd0vs/SoDaRadio", "max_forks_repo_head_hexsha": "0a41fa3d795b1c93795ad62ad17bf2de5f60a752", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2017-09-13T12:47:43.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-02T20:54:25.000Z", "avg_line_length": 34.6846590909, "max_line_length": 96, "alphanum_fraction": 0.6493570317, "num_tokens": 3723, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.607663184043154, "lm_q2_score": 0.519521321952093, "lm_q1q2_score": 0.31569398067571736}}
{"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// 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// Example combining Boost.Geometry with Boost.Units\n\n#include <iostream>\n\n#include <boost/geometry/geometry.hpp>\n\n\n#include <boost/units/quantity.hpp> \n#include <boost/units/systems/si/length.hpp>\n#include <boost/units/systems/cgs/length.hpp>\n#include <boost/units/systems/si/io.hpp>\n\n\n// TEMPORARY this will go to somewhere within Boost.Geometry\nnamespace boost { namespace geometry\n{\n\nnamespace cs\n{\n\ntemplate <typename Unit>\nstruct units_cartesian {};\n\n}\n\nnamespace traits\n{\ntemplate<typename U>\nstruct cs_tag<cs::units_cartesian<U> >\n{\n    typedef cartesian_tag type;\n};\n\n}\n\n\nnamespace model\n{\n\n// Define a point type to interoperate with Boost.Units, having\n// 1. a constructor taking quantities\n// 2. defining a quantified coordinate system \n// Note that all values are still stored in \"normal\" types as double\ntemplate <typename U, std::size_t D = 2, typename T = double, typename CS = cs::units_cartesian<U> >\nclass quantity_point : public model::point<T, D, CS>\n{\n    typedef boost::units::quantity<U, T> qtype;\n\npublic :\n\n    // Templated constructor to allow constructing with other units then qtype,\n    // e.g. to convert from centimeters to meters\n    template <typename Q>\n    inline quantity_point(Q const& x, Q const& y)\n        : model::point<T, D, CS>(\n            qtype(x).value(), \n            qtype(y).value())\n    {}\n};\n\n}\n\n\n// Adapt quantity_point to the Point Concept\n#ifndef DOXYGEN_NO_TRAITS_SPECIALIZATIONS\nnamespace traits\n{\n\ntemplate <typename Units, std::size_t DimensionCount, typename CoordinateType, typename CoordinateSystem>\nstruct tag<model::quantity_point<Units, DimensionCount, CoordinateType, CoordinateSystem> >\n{\n    typedef point_tag type;\n};\n\ntemplate<typename Units, std::size_t DimensionCount, typename CoordinateType, typename CoordinateSystem>\nstruct coordinate_type<model::quantity_point<Units, DimensionCount, CoordinateType, CoordinateSystem> >\n{\n    typedef CoordinateType type;\n};\n\ntemplate<typename Units, std::size_t DimensionCount, typename CoordinateType, typename CoordinateSystem>\nstruct coordinate_system<model::quantity_point<Units, DimensionCount, CoordinateType, CoordinateSystem> >\n{\n    typedef CoordinateSystem type;\n};\n\ntemplate<typename Units, std::size_t DimensionCount, typename CoordinateType, typename CoordinateSystem>\nstruct dimension<model::quantity_point<Units, DimensionCount, CoordinateType, CoordinateSystem> >\n    : boost::mpl::int_<DimensionCount>\n{};\n\ntemplate<typename Units, std::size_t DimensionCount, typename CoordinateType, typename CoordinateSystem, std::size_t Dimension>\nstruct access<model::quantity_point<Units, DimensionCount, CoordinateType, CoordinateSystem>, Dimension >\n{\n    static inline CoordinateType get(\n        model::quantity_point<Units, DimensionCount, CoordinateType, CoordinateSystem> const& p)\n    {\n        return p.template get<Dimension>();\n    }\n\n    static inline void set(model::quantity_point<Units, DimensionCount, CoordinateType, CoordinateSystem>& p,\n        CoordinateType const& value)\n    {\n        p.template set<Dimension>(value);\n    }\n};\n\n} // namespace traits\n#endif // DOXYGEN_NO_TRAITS_SPECIALIZATIONS\n\n\n\n// For extra support for functions as distance,area,get,set\nnamespace units\n{\n    namespace detail\n    {\n        // Define an extra meta-function to get the units of a coordinate system\n        template <typename CS>\n        struct unit_dimension \n        {\n            // define it as dimensionless\n            // or MPL ASSERT\n        };\n\n        template <typename U>\n        struct unit_dimension<cs::units_cartesian<U> >\n        {\n            typedef U type;\n        };\n    }\n\n    // Define an extra metafunction to define the quantity of a Geometry type\n    template <typename Geometry, typename CT = typename coordinate_type<Geometry>::type>\n    struct quantity\n    {\n        typedef boost::units::quantity\n            <\n                typename detail::unit_dimension\n                    <\n                        typename coordinate_system<Geometry>::type\n                    >::type, \n                CT\n            > type;\n    };\n\n\n    template <typename Geometry1, typename Geometry2>\n    inline typename quantity<Geometry1, typename default_distance_result<Geometry1, Geometry2>::type>::type\n        distance(Geometry1 const& g1, Geometry2 const& g2)\n    {\n        typedef typename quantity<Geometry1, typename default_distance_result<Geometry1, Geometry2>::type>::type q;\n        return q::from_value(geometry::distance(g1, g2));\n    }\n\n    template <std::size_t Index, typename Point>\n    inline typename quantity<Point>::type get(Point const& p)\n    {\n        typedef typename quantity<Point>::type q;\n        return q::from_value(geometry::get<Index>(p));\n    }\n}\n\n}}\n// END TEMPORARY\n\n\n\nint main(void)\n{\n    using namespace boost::geometry;\n    using namespace boost::units;\n\n    // 1: using it directly\n    {\n        typedef model::quantity_point<si::length, 2> point;\n        point p1(1 * si::meter, 2 * si::meter);\n        point p2(3 * si::meter, 4 * si::meter);\n\n        std::cout << get<0>(p2) << std::endl;\n\n        // This is a little inconvenient:\n        quantity<si::length> d = distance(p1, p2) * si::meter;\n\n        std::cout << d << std::endl;\n    }\n\n    // 2: same but now using centimeters, and using boost::geometry::units::\n    {\n        typedef model::quantity_point<cgs::length, 2> point;\n        point p1(1 * si::meter, 2 * si::meter);\n        point p2(3 * si::meter, 4 * si::meter);\n\n        std::cout << boost::geometry::units::get<0>(p2) << std::endl;\n        quantity<cgs::length> d = boost::geometry::units::distance(p1, p2);\n        std::cout << d << std::endl;\n    }\n\n    return 0;\n}\n", "meta": {"hexsha": "8e8eba12cec1b53fb6be2e150a8983b51c8a5cb1", "size": 6095, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/geometry/extensions/example/units/08_units_example.cpp", "max_stars_repo_name": "ballisticwhisper/boost", "max_stars_repo_head_hexsha": "f72119ab640b564c4b983bd457457046b52af9ee", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2015-01-02T14:24:56.000Z", "max_stars_repo_stars_event_max_datetime": "2015-01-02T14:25:17.000Z", "max_issues_repo_path": "libs/geometry/extensions/example/units/08_units_example.cpp", "max_issues_repo_name": "ballisticwhisper/boost", "max_issues_repo_head_hexsha": "f72119ab640b564c4b983bd457457046b52af9ee", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2019-01-13T23:45:51.000Z", "max_issues_repo_issues_event_max_datetime": "2019-02-03T08:13:26.000Z", "max_forks_repo_path": "libs/geometry/extensions/example/units/08_units_example.cpp", "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": 28.8862559242, "max_line_length": 127, "alphanum_fraction": 0.681050041, "num_tokens": 1433, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6076631698328917, "lm_q2_score": 0.519521321952093, "lm_q1q2_score": 0.3156939732931831}}
{"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 \"typedefs.h\"\n#include \"strutil.h\"\n#include \"graphutil.h\"\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/graph_traits.hpp>\n#include <boost/graph/copy.hpp>\n#include <boost/graph/graph_utility.hpp>\n#include <boost/bimap.hpp>\n#include <iostream> \n#include <fstream>\n#include <csignal>\n#include <utility>\nusing namespace std;\nusing namespace boost;\n\nint main(int argc, char* argv[])\n{\n        vector<string> fname;\n        if( argc < 2 ){\n                cout << \"Usage: lt [filename]\\n\";\n                return 0;\n        } \n        for( uint i = 1; i < argc; ++i ) fname.push_back(argv[i]);\n\n        for( string& f : fname ){\n                cout << \"loading graph\\n\";\n\n                Graph g = load_graph(f);\n\n#ifdef GRAPH_TYPE_LIST\n                init_vert_propmap(g);\n#endif\n\n                uint n = num_vertices(g);\n\n                cout << \"n: \" << n << '\\n';\n                uint e = num_edges(g);\n\n                cout << \"starting lipton tarjan...\\n\";\n                print_graph(g);\n\n\t\ttry { \n\t\t\tPartition p = lipton_tarjan_separator(g);\n\t\t\tuint num_verts_finished = p.total_num_verts();\n\t\t\tcout << \"Finished!\\n\";\n\n                        p.print(&g);\n\n                        BOOST_ASSERT(p.verify_edges(g));\n\t\t\tBOOST_ASSERT(p.verify_sizes(g));\n\t\t\t//p.print(vmap2);\n\n\t\t\tcout << \"finished num verts: \" << num_verts_finished << '\\n';\n\t\t} catch (NotPlanarException e) {\n\t\t\tcout << \"cannot finish lipton-tarjan because graph is not planar\\n\";\n\t\t} catch (NoNontreeEdgeException e) {\n\t\t\tcout << \"cannot finish lipton-tarjan because I could not find a nontree edge out of \" << e.num_edges << \" edges\\n\";\n\t\t}\n        }\n}\n", "meta": {"hexsha": "dff11785c2b314be6f4330b57b2f71dcf75dc932", "size": 2021, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "main.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": "main.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": "main.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": 29.2898550725, "max_line_length": 118, "alphanum_fraction": 0.5482434438, "num_tokens": 474, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6076631698328916, "lm_q2_score": 0.519521321952093, "lm_q1q2_score": 0.31569397329318305}}
{"text": "// Copyright (c) 2009  GeometryFactory Sarl (France).\n// All rights reserved.\n//\n// This file is part of CGAL (www.cgal.org).\n//\n// $URL$\n// $Id$\n// SPDX-License-Identifier: GPL-3.0-or-later OR LicenseRef-Commercial\n//\n// Author(s)     : Fernando Cacciola <fernando.cacciola@geometryfactory.com>\n\n\n//#define ENABLE_TRACE\n\n#ifdef ENABLE_TRACE\n#  define TRACE(m) { std::ostringstream ss ; ss << m << std::endl ; trace(ss.str()); }\n#else\n#  define TRACE(m)\n#endif\n\n\n#include <fstream>\n#include <string>\n#include <sstream>\n#include <iomanip>\n#include <list>\n\nvoid trace( std::string s )\n{\n  static std::ofstream out(\"log.txt\");\n  out << s ;\n}\n\n#include <boost/shared_ptr.hpp>\n\n#include <QtGui>\n#include <QString>\n#include <QActionGroup>\n#include <QFileDialog>\n#include <QInputDialog>\n#include <QDragEnterEvent>\n#include <QDropEvent>\n#include <QSlider>\n#include <QProgressBar>\n#include <QMessageBox>\n\n#include <CGAL/basic.h>\n#include <CGAL/Cartesian_converter.h>\n#include <CGAL/Timer.h>\n#include <CGAL/Bbox_2.h>\n#include <CGAL/iterator.h>\n#include <CGAL/assertions_behaviour.h>\n#include <CGAL/Cartesian.h>\n#include <CGAL/Lazy_exact_nt.h>\n#include <CGAL/Polygon_2.h>\n#include <CGAL/Polygon_with_holes_2.h>\n#include <CGAL/Polygon_set_2.h>\n#include <CGAL/General_polygon_set_2.h>\n#include <CGAL/Iso_rectangle_2.h>\n#include <CGAL/CORE_algebraic_number_traits.h>\n#include <CGAL/Gps_circle_segment_traits_2.h>\n#include <CGAL/Arr_Bezier_curve_traits_2.h>\n#include <CGAL/Gps_traits_2.h>\n#include <CGAL/minkowski_sum_2.h>\n#include <CGAL/approximated_offset_2.h>\n#include <CGAL/Arrangement_2.h>\n#include <CGAL/Boolean_set_operations_2.h>\n\n#ifdef CGAL_USE_GMP\n  #include <CGAL/Gmpq.h>\n#else\n  #include <CGAL/MP_Float.h>\n  #include <CGAL/Quotient.h>\n#endif\n\n\n#include <CGAL/Qt/BezierCurves.h>\n#include <CGAL/Qt/CircularPolygons.h>\n#include <CGAL/Qt/GraphicsViewBezierPolygonInput.h>\n#include <CGAL/Qt/GraphicsViewCircularPolygonInput.h>\n//#include <CGAL/Qt/GraphicsViewGpsCircleInput.h>\n#include <CGAL/Qt/Converter.h>\n#include <CGAL/Qt/DemosMainWindow.h>\n#include <CGAL/Qt/utility.h>\n#include <CGAL/IO/Dxf_bsop_reader.h>\n\n// the two base classes\n#include \"ui_boolean_operations_2.h\"\n\n#include \"typedefs.h\"\n\n\nvoid show_warning( std::string aS )\n{\n  QMessageBox::warning(NULL,\"Warning\",QString(aS.c_str()) ) ;\n}\n\nvoid show_error( std::string aS )\n{\n  QMessageBox::critical(NULL,\"Critical Error\",QString(aS.c_str()) ) ;\n}\n\nvoid error( std::string aS )\n{\n  show_error(aS);\n\n  throw std::runtime_error(aS);\n}\n\nvoid error_handler ( char const* what, char const* expr, char const* file, int line, char const* msg )\n{\n  std::ostringstream ss ;\n\n  ss << \"CGAL error: \" << what << \" violation!\" << std::endl\n     << \"Expr: \" << expr << std::endl\n     << \"File: \" << file << std::endl\n     << \"Line: \" << line << std::endl;\n  if ( msg != 0)\n    ss << \"Explanation:\" << msg << std::endl;\n\n  error(ss.str());\n\n}\n\n\nenum { BLUE_GROUP, RED_GROUP, RESULT_GROUP } ;\n\nenum { CIRCULAR_TYPE, BEZIER_TYPE } ;\n\n\nQPen   sPens   [] = { QPen(QColor(0,0,255),0,Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin)\n                    , QPen(QColor(255,0,0),0,Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin)\n                    , QPen(QColor(0,255,0),0,Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin)\n                    } ;\n\nQBrush sBrushes[] = { QBrush(QColor(0,0,255,32 ))\n                    , QBrush(QColor(255,0,0,32 ))\n                    , QBrush(QColor(0,255,0,220))\n                    } ;\nstruct Rep_base\n{\n  virtual ~Rep_base() {}\n\n  virtual int type () const = 0 ;\n\n  virtual CGAL::Qt::GraphicsItem* gi() const = 0 ;\n  virtual CGAL::Qt::GraphicsItem* gi()       = 0 ;\n\n  virtual void set_pen  ( QPen   const& aPen   ) = 0 ;\n  virtual void set_brush( QBrush const& aBrush ) = 0 ;\n\n  virtual QRectF bounding_rect() const { return gi()->boundingRect() ; }\n\n  virtual bool is_empty() const = 0 ;\n\n  virtual void clear               ()                         = 0 ;\n  virtual void complement          ()                         = 0 ;\n  virtual void assign              ( Rep_base const& aOther ) = 0 ;\n  virtual void intersect           ( Rep_base const& aOther ) = 0 ;\n  virtual void join                ( Rep_base const& aOther ) = 0 ;\n  virtual void difference          ( Rep_base const& aOther ) = 0 ;\n  virtual void symmetric_difference( Rep_base const& aOther ) = 0 ;\n\n} ;\n\n\n\ntemplate<class GI_, class Set_>\nclass Rep : public Rep_base\n{\npublic:\n\n  typedef GI_  GI  ;\n  typedef Set_ Set ;\n\n  typedef Rep<GI,Set> Self ;\n\n  Rep() { mGI = new GI(&mSet) ; }\n\n  Set const& set() const { return mSet ; }\n  Set      & set()       { return mSet ; }\n\n  virtual CGAL::Qt::GraphicsItem* gi() const { return mGI; }\n  virtual CGAL::Qt::GraphicsItem* gi()       { return mGI; }\n\n  virtual void set_pen  ( QPen   const& aPen   ) { mGI->setPen  (aPen);   }\n  virtual void set_brush( QBrush const& aBrush ) { mGI->setBrush(aBrush); }\n\n  virtual bool is_empty() const { return mSet.is_empty() ; }\n\n  virtual void clear()\n  {\n    try\n    {\n      mSet.clear() ;\n    }\n    catch(...)\n    {\n      show_error(\"Exception thrown during boolean operation\");\n    }\n  }\n\n  virtual void complement()\n  {\n    try\n    {\n      mSet.complement();\n    }\n    catch(...)\n    {\n      show_error(\"Exception thrown during boolean operation\");\n    }\n  }\n\n  virtual void assign( Rep_base const& aOther )\n  {\n    try\n    {\n      mSet = cast(aOther).mSet;\n    }\n    catch(...)\n    {\n      show_error(\"Exception thrown during boolean operation\");\n    }\n  }\n\n  virtual void intersect( Rep_base const& aOther )\n  {\n    try\n    {\n      mSet.intersection( cast(aOther).mSet);\n    }\n    catch(...)\n    {\n      show_error(\"Exception thrown during boolean operation\");\n    }\n  }\n\n  virtual void join( Rep_base const& aOther )\n  {\n    try\n    {\n      mSet.join( cast(aOther).mSet);\n    }\n    catch(...)\n    {\n      show_error(\"Exception thrown during boolean operation\");\n    }\n  }\n\n  virtual void difference( Rep_base const& aOther )\n  {\n    try\n    {\n      mSet.difference( cast(aOther).mSet);\n    }\n    catch(...)\n    {\n      show_error(\"Exception thrown during boolean operation\");\n    }\n  }\n\n  virtual void symmetric_difference( Rep_base const& aOther )\n  {\n    try\n    {\n      mSet.symmetric_difference( cast(aOther).mSet);\n    }\n    catch(...)\n    {\n      show_error(\"Exception thrown during boolean operation\");\n    }\n  }\n\n  static Self const& cast( Rep_base const& aOther ) { return dynamic_cast<Self const&>(aOther); }\n  static Self      & cast( Rep_base      & aOther ) { return dynamic_cast<Self      &>(aOther); }\n\nprivate:\n\n  GI* mGI;\n  Set mSet ;\n} ;\n\nclass Circular_rep : public Rep<Circular_GI, Circular_polygon_set>\n{\n  typedef Rep<Circular_GI, Circular_polygon_set> Base ;\n\npublic:\n\n  Circular_rep () : Base() {}\n\n  virtual int type() const { return CIRCULAR_TYPE ; }\n} ;\n\nclass Bezier_rep : public Rep<Bezier_GI, Bezier_polygon_set>\n{\n  typedef Rep<Bezier_GI, Bezier_polygon_set> Base ;\n\npublic:\n\n\n  Bezier_rep () : Base() {}\n\n  virtual int type() const { return BEZIER_TYPE ; }\n} ;\n\nclass Curve_set\n{\n  typedef boost::shared_ptr<Rep_base> Rep_ptr ;\n\npublic:\n\n  Curve_set( int aType, QPen aPen, QBrush aBrush )\n  :\n    mPen  (aPen)\n  , mBrush(aBrush)\n  {\n    reset_type(aType);\n  }\n\n  void reset_type( int aType )\n  {\n    mRep = aType == CIRCULAR_TYPE ? Rep_ptr(new Circular_rep())\n                                  : Rep_ptr(new Bezier_rep  ()) ;\n\n    mRep->set_pen  (mPen);\n    mRep->set_brush(mBrush);\n  }\n\n  CGAL::Qt::GraphicsItem const* gi() const { return mRep->gi() ; }\n  CGAL::Qt::GraphicsItem*       gi()       { return mRep->gi() ; }\n\n  QRectF bounding_rect() const { return mRep->bounding_rect() ; }\n\n  bool is_empty() const { return !mRep || mRep->is_empty(); }\n\n  void clear      () { mRep->clear() ; }\n  void complement () { mRep->complement() ; }\n\n  void assign ( Curve_set const& aOther )\n  {\n    if ( is_circular() && aOther.is_circular() )\n    {\n      get_circular_rep()->assign( *aOther.get_circular_rep() ) ;\n    }\n    else if ( is_bezier() && aOther.is_bezier() )\n    {\n      get_bezier_rep()->assign( *aOther.get_bezier_rep() ) ;\n    }\n  }\n\n  void intersect( Curve_set const& aOther )\n  {\n    if ( is_circular() && aOther.is_circular() )\n    {\n      get_circular_rep()->intersect( *aOther.get_circular_rep() ) ;\n    }\n    else if ( is_bezier() && aOther.is_bezier() )\n    {\n      get_bezier_rep()->intersect( *aOther.get_bezier_rep() ) ;\n    }\n  }\n\n  void join ( Curve_set const& aOther )\n  {\n    if ( is_circular() && aOther.is_circular() )\n    {\n      get_circular_rep()->join( *aOther.get_circular_rep() ) ;\n    }\n    else if ( is_bezier() && aOther.is_bezier() )\n    {\n      get_bezier_rep()->join( *aOther.get_bezier_rep() ) ;\n    }\n  }\n\n  void difference( Curve_set const& aOther )\n  {\n    if ( is_circular() && aOther.is_circular() )\n    {\n      get_circular_rep()->difference( *aOther.get_circular_rep() ) ;\n    }\n    else if ( is_bezier() && aOther.is_bezier() )\n    {\n      get_bezier_rep()->difference( *aOther.get_bezier_rep() ) ;\n    }\n  }\n\n  void symmetric_difference( Curve_set const& aOther )\n  {\n    if ( is_circular() && aOther.is_circular() )\n    {\n      get_circular_rep()->symmetric_difference( *aOther.get_circular_rep() ) ;\n    }\n    else if ( is_bezier() && aOther.is_bezier() )\n    {\n      get_bezier_rep()->symmetric_difference( *aOther.get_bezier_rep() ) ;\n    }\n  }\n\n  Rep_base const& rep() const { return *mRep ; }\n  Rep_base&       rep()       { return *mRep ; }\n\n  bool is_circular() const { return mRep->type() == CIRCULAR_TYPE ; }\n  bool is_bezier  () const { return mRep->type() == BEZIER_TYPE ; }\n\n  Circular_rep const* get_circular_rep() const { return dynamic_cast<Circular_rep const*>( boost::get_pointer(mRep) ); }\n  Circular_rep      * get_circular_rep()       { return dynamic_cast<Circular_rep*      >( boost::get_pointer(mRep) ); }\n  Bezier_rep   const* get_bezier_rep  () const { return dynamic_cast<Bezier_rep   const*>( boost::get_pointer(mRep) ); }\n  Bezier_rep        * get_bezier_rep  ()       { return dynamic_cast<Bezier_rep  *      >( boost::get_pointer(mRep) ); }\n\n  Circular_polygon_set const& circular() const { return get_circular_rep()->set(); }\n  Circular_polygon_set      & circular()       { return get_circular_rep()->set(); }\n  Bezier_polygon_set   const& bezier  () const { return get_bezier_rep  ()->set(); }\n  Bezier_polygon_set        & bezier  ()       { return get_bezier_rep  ()->set(); }\n\nprivate:\n\n  QPen                        mPen ;\n  QBrush                      mBrush ;\n  boost::shared_ptr<Rep_base> mRep ;\n\n} ;\n\ntypedef std::vector<Curve_set> Curve_set_container ;\n\ntypedef Curve_set_container::const_iterator Curve_set_const_iterator ;\ntypedef Curve_set_container::iterator       Curve_set_iterator ;\n\n\nclass MainWindow :\n  public CGAL::Qt::DemosMainWindow,\n  public Ui::Boolean_operations_2\n{\n  Q_OBJECT\n\nprivate:\n\n  QGraphicsScene                                                   mScene;\n  bool                                                             mCircular_active ;\n  bool                                                             mBlue_active ;\n  Curve_set_container                                              mCurve_sets ;\n  Circular_region_source_container                                 mBlue_circular_sources ;\n  Circular_region_source_container                                 mRed_circular_sources ;\n  Bezier_region_source_container                                   mBlue_bezier_sources ;\n  Bezier_region_source_container                                   mRed_bezier_sources ;\n  CGAL::Qt::GraphicsViewBezierPolygonInput<Bezier_traits>*         mBezierInput ;\n  CGAL::Qt::GraphicsViewCircularPolygonInput<Gps_circular_kernel>* mCircularInput ;\n  //CGAL::Qt::GraphicsViewGpsCircleSegmentInput<Circular_curve>* mCircularInput ;\n  //CGAL::Qt::GraphicsViewGpsCircleInput<Circular_traits>*      mCircleInput ;\n\npublic:\n\n  MainWindow();\n\nprivate:\n\n  void dragEnterEvent(QDragEnterEvent *event);\n  void dropEvent(QDropEvent *event);\n  void zoomToFit();\n\nprotected slots:\n\n  void open( QString filename ) ;\n\npublic slots:\n\n  void processInput(CGAL::Object o);\n  void on_actionNew_triggered() ;\n  void on_actionOpenLinear_triggered() ;\n  void on_actionOpenDXF_triggered() ;\n  void on_actionOpenBezier_triggered() ;\n  void on_actionSaveBlue_triggered() ;\n  void on_actionSaveRed_triggered() ;\n  void on_actionSaveResult_triggered() ;\n  void on_actionIntersection_triggered() ;\n  void on_actionUnion_triggered() ;\n  void on_actionBlueMinusRed_triggered() ;\n  void on_actionRedMinusBlue_triggered() ;\n  void on_actionSymmDiff_triggered() ;\n  void on_actionMinkowskiSum_triggered();\n  void on_actionBlueComplement_triggered();\n  void on_actionRedComplement_triggered();\n  void on_actionAllBlue_triggered();\n  void on_actionAllRed_triggered();\n  void on_actionDeleteBlue_triggered();\n  void on_actionDeleteRed_triggered();\n  void on_actionRecenter_triggered();\n\n  void on_actionInsertBezier_toggled  (bool aChecked);\n  void on_actionInsertCircular_toggled(bool aChecked);\n  void on_actionInsertCircle_toggled  (bool aChecked);\n\n  void on_checkboxShowBlue_toggled      (bool aChecked) { ToogleView(BLUE_GROUP  ,aChecked); }\n  void on_checkboxShowRed_toggled       (bool aChecked) { ToogleView(RED_GROUP   ,aChecked); }\n  void on_checkboxShowResult_toggled    (bool aChecked) { ToogleView(RESULT_GROUP,aChecked); }\n\n  void on_radioMakeBlueActive_toggled(bool aChecked) { mBlue_active =  aChecked ; }\n  void on_radioMakeRedActive_toggled (bool aChecked) { mBlue_active = !aChecked ; }\n\nsignals:\n\n  void changed();\n\nprivate:\n\n  void modelChanged()\n  {\n    emit(changed());\n  }\n\n  bool ask_user_yesno( const char* aTitle, const char* aQuestion )\n  {\n    return QMessageBox::warning(this\n                               ,aTitle\n                               ,QString(aQuestion)\n                               ,\"&Yes\"\n                               ,\"&No\"\n                               ,QString::null\n                               , 1\n                               , 1\n                               ) == 0 ;\n  }\n\n  Curve_set& set( int aGroup ) { return mCurve_sets[aGroup] ; }\n\n  Curve_set& blue_set  () { return set(BLUE_GROUP)  ; }\n  Curve_set& red_set   () { return set(RED_GROUP)   ; }\n  Curve_set& result_set() { return set(RESULT_GROUP); }\n\n  int active_group() const { return mBlue_active ? BLUE_GROUP : RED_GROUP ; }\n\n  Curve_set& active_set()   { return set(active_group()) ; }\n\n  Circular_region_source_container const& blue_circular_sources() const { return mBlue_circular_sources ; }\n  Circular_region_source_container      & blue_circular_sources()       { return mBlue_circular_sources ; }\n\n  Circular_region_source_container const& red_circular_sources () const { return mRed_circular_sources ; }\n  Circular_region_source_container      & red_circular_sources ()       { return mRed_circular_sources ; }\n\n  Bezier_region_source_container const& blue_bezier_sources() const { return mBlue_bezier_sources ; }\n  Bezier_region_source_container      & blue_bezier_sources()       { return mBlue_bezier_sources ; }\n\n  Bezier_region_source_container const& red_bezier_sources () const { return mRed_bezier_sources ; }\n  Bezier_region_source_container      & red_bezier_sources ()       { return mRed_bezier_sources ; }\n\n  Bezier_region_source_container const& active_bezier_sources() const { return mBlue_active ? mBlue_bezier_sources : mRed_bezier_sources ; }\n  Bezier_region_source_container      & active_bezier_sources()       { return mBlue_active ? mBlue_bezier_sources : mRed_bezier_sources ; }\n\n  Circular_region_source_container const& active_circular_sources() const { return mBlue_active ? mBlue_circular_sources : mRed_circular_sources ; }\n  Circular_region_source_container      & active_circular_sources()       { return mBlue_active ? mBlue_circular_sources : mRed_circular_sources ; }\n\n  void SetViewBlue  ( bool aChecked ) { checkboxShowBlue  ->setChecked(aChecked); }\n  void SetViewRed   ( bool aChecked ) { checkboxShowRed   ->setChecked(aChecked); }\n  void SetViewResult( bool aChecked ) { checkboxShowResult->setChecked(aChecked); }\n\n  void ToogleView( int aGROUP, bool aChecked );\n\n  void link_GI ( CGAL::Qt::GraphicsItem* aGI )\n  {\n    QObject::connect(this, SIGNAL(changed()), aGI, SLOT(modelChanged()));\n    mScene.addItem( aGI );\n  }\n\n  void unlink_GI ( CGAL::Qt::GraphicsItem* aGI )\n  {\n    mScene.removeItem( aGI );\n    QObject::disconnect(this, SIGNAL(changed()), aGI, SLOT(modelChanged()));\n  }\n\n  void switch_set_type( Curve_set& aSet, int aType );\n\n  void switch_sets_type( int aType );\n\n  bool ensure_circular_mode();\n\n  bool ensure_bezier_mode();\n};\n\n\nMainWindow::MainWindow()\n  : DemosMainWindow()\n  , mCircular_active(true)\n  , mBlue_active(true)\n{\n  CGAL::set_error_handler  (error_handler);\n  CGAL::set_warning_handler(error_handler);\n\n  setupUi(this);\n\n  setAcceptDrops(true);\n\n  mCurve_sets.push_back( Curve_set(CIRCULAR_TYPE, sPens[BLUE_GROUP]  , sBrushes[BLUE_GROUP]  ) ) ;\n  mCurve_sets.push_back( Curve_set(CIRCULAR_TYPE, sPens[RED_GROUP]   , sBrushes[RED_GROUP]   ) ) ;\n  mCurve_sets.push_back( Curve_set(CIRCULAR_TYPE, sPens[RESULT_GROUP], sBrushes[RESULT_GROUP]) ) ;\n\n  for( Curve_set_iterator si = mCurve_sets.begin(); si != mCurve_sets.end() ; ++ si )\n    link_GI(si->gi()) ;\n\n  //\n  // Setup the mScene and the view\n  //\n  mScene.setItemIndexMethod(QGraphicsScene::NoIndex);\n  mScene.setSceneRect(-100, -100, 100, 100);\n  this->graphicsView->setScene(&mScene);\n  this->graphicsView->setMouseTracking(true);\n\n  // Turn the vertical axis upside down\n  this->graphicsView->scale(1, -1);\n\n  // The navigation adds zooming and translation functionality to the\n  // QGraphicsView\n  this->addNavigation(this->graphicsView);\n\n  this->setupStatusBar();\n  this->setupOptionsMenu();\n  this->addAboutDemo(\":/cgal/help/index.html\");\n  this->addAboutCGAL();\n\n  this->addRecentFiles(this->menuFile, this->actionQuit);\n\n  mBezierInput   = new CGAL::Qt::GraphicsViewBezierPolygonInput  <Bezier_traits>      (this, &mScene);\n  mCircularInput = new CGAL::Qt::GraphicsViewCircularPolygonInput<Gps_circular_kernel>(this, &mScene);\n  //mCircleInput   = new CGAL::Qt::GraphicsViewCircleInput       <Circular_traits>(this, &mScene);\n\n  QObject::connect(mBezierInput  , SIGNAL(generate(CGAL::Object)), this, SLOT(processInput(CGAL::Object)));\n  QObject::connect(mCircularInput, SIGNAL(generate(CGAL::Object)), this, SLOT(processInput(CGAL::Object)));\n  //QObject::connect(mCircleInput  , SIGNAL(generate(CGAL::Object)), this, SLOT(processInput(CGAL::Object)));\n\n  QObject::connect(this->actionQuit, SIGNAL(triggered()), this, SLOT(close()));\n  QObject::connect(this, SIGNAL(openRecentFile(QString)), this, SLOT(open(QString)));\n\n  QObject::connect(radioMakeBlueActive, SIGNAL(toggled(bool)), this, SLOT(on_radioMakeBlueActive_toggled (bool)));\n  QObject::connect(radioMakeRedActive , SIGNAL(toggled(bool)), this, SLOT(on_radioMakeRedActive_toggled(bool)));\n\n  QObject::connect(checkboxShowBlue   , SIGNAL(toggled(bool)), this, SLOT(on_checkboxShowBlue_toggled   (bool)));\n  QObject::connect(checkboxShowRed    , SIGNAL(toggled(bool)), this, SLOT(on_checkboxShowRed_toggled    (bool)));\n  QObject::connect(checkboxShowResult , SIGNAL(toggled(bool)), this, SLOT(on_checkboxShowResult_toggled (bool)));\n\n\n}\n\nvoid MainWindow::on_actionNew_triggered()\n{\n  for( Curve_set_iterator si = mCurve_sets.begin(); si != mCurve_sets.end() ; ++ si )\n    si->clear();\n\n  blue_circular_sources().clear();\n  blue_bezier_sources  ().clear();\n  red_circular_sources ().clear();\n  red_bezier_sources   ().clear();\n\n  SetViewBlue  (true);\n  SetViewRed   (true);\n  SetViewResult(true);\n\n  mCircular_active = true ;\n\n  radioMakeBlueActive->setChecked(true);\n\n  modelChanged();\n\n}\n\nvoid MainWindow::on_actionRecenter_triggered()\n{\n  zoomToFit();\n}\n\nvoid MainWindow::dragEnterEvent(QDragEnterEvent *event)\n{\n  if (event->mimeData()->hasFormat(\"text/uri-list\"))\n    event->acceptProposedAction();\n}\n\nvoid MainWindow::dropEvent(QDropEvent *event)\n{\n  QString filename = event->mimeData()->urls().at(0).path();\n  open(filename);\n  event->acceptProposedAction();\n}\n\nCircular_polygon linear_2_circ( Linear_polygon const& pgn )\n{\n  CGAL::Cartesian_converter<Linear_kernel,Gps_circular_kernel> convert ;\n\n  Circular_polygon rCP;\n\n  for( Linear_polygon::Edge_const_iterator ei = pgn.edges_begin(); ei != pgn.edges_end(); ++ei )\n  {\n    if  ( ei->source() != ei->target() )\n      rCP.push_back( Circular_X_monotone_curve( convert(ei->source()), convert(ei->target())) );\n  }\n\n  return rCP;\n}\n\nCircular_polygon_with_holes linear_2_circ( Linear_polygon_with_holes const& pwh )\n{\n  Circular_polygon_with_holes rCP( linear_2_circ(pwh.outer_boundary()) ) ;\n\n  for( Linear_polygon_with_holes::Hole_const_iterator hi = pwh.holes_begin(); hi != pwh.holes_end(); ++ hi )\n    rCP.add_hole( linear_2_circ(*hi)  );\n\n  return rCP;\n}\n\nbool read_linear ( QString aFileName, Circular_polygon_set& rSet, Circular_region_source_container& rSources )\n{\n  bool rOK = false ;\n\n  std::ifstream in_file (qPrintable(aFileName));\n\n  if ( in_file )\n  {\n    unsigned int n_regions ;\n    in_file >> n_regions;\n\n    for ( unsigned int r = 0 ; r < n_regions ; ++ r )\n    {\n      unsigned int n_boundaries;\n      in_file >> n_boundaries;\n\n      Circular_polygon outer ;\n      std::vector<Circular_polygon> holes ;\n\n      for ( unsigned int r = 0 ; r < n_boundaries ; ++ r )\n      {\n        Linear_polygon p ;\n        in_file >> p ;\n\n        if ( r == 0 )\n             outer = linear_2_circ(p);\n        else holes.push_back( linear_2_circ(p) );\n      }\n\n      Circular_polygon_with_holes pwh(outer,holes.begin(),holes.end());\n      rSources.push_back(pwh);\n      rSet.join(pwh) ;\n      rOK = true ;\n    }\n\n  }\n\n  return rOK ;\n}\n\nbool read_dxf ( QString aFileName, Circular_polygon_set& rSet, Circular_region_source_container& rSources )\n{\n  bool rOK = false ;\n\n  std::ifstream in_file (qPrintable(aFileName));\n\n  if ( in_file )\n  {\n    CGAL::Dxf_bsop_reader<Gps_circular_kernel>   reader;\n    std::vector<Circular_polygon>            circ_polygons;\n    std::vector<Circular_polygon_with_holes> circ_polygons_with_holes;\n\n    reader(in_file\n          ,std::back_inserter(circ_polygons)\n          ,std::back_inserter(circ_polygons_with_holes)\n          ,false\n          );\n\n    for ( std::vector<Circular_polygon>::iterator pit = circ_polygons.begin() ; pit != circ_polygons.end() ; ++ pit )\n      circ_polygons_with_holes.push_back( Circular_polygon_with_holes(*pit) ) ;\n\n    rSet.join( circ_polygons_with_holes.begin(), circ_polygons_with_holes.end() ) ;\n\n    std::copy(circ_polygons_with_holes.begin(), circ_polygons_with_holes.end(), std::back_inserter(rSources) );\n\n    rOK = true ;\n  }\n\n  return rOK ;\n}\n\nBezier_curve read_bezier_curve ( std::istream& is, bool aDoubleFormat )\n{\n  // Read the number of control points.\n  unsigned int  n;\n\n  is >> n;\n\n  // Read the control points.\n  std::vector<Bezier_rat_point> ctrl_pts;\n\n  for ( unsigned int k = 0; k < n; k++)\n  {\n    Bezier_rat_point p ;\n    if ( aDoubleFormat )\n    {\n      double x,y ;\n      is >> x >> y ;\n      Bezier_rational rx(static_cast<int> (1000 * x + 0.5), 1000);\n      Bezier_rational ry(static_cast<int> (1000 * y + 0.5), 1000);\n      p = Bezier_rat_point(rx,ry);\n    }\n    else\n    {\n      is >> p ;\n    }\n\n    if ( k == 0 || ctrl_pts[k-1] != p )\n    {\n      ctrl_pts.push_back(p) ;\n    }\n  }\n\n  std::vector<Bezier_rat_point> ctrl_pts2;\n\n  typedef std::vector<Bezier_rat_point>::const_iterator cp_const_iterator ;\n\n  cp_const_iterator beg  = ctrl_pts.begin();\n  cp_const_iterator end  = ctrl_pts.end  ();\n  cp_const_iterator last = end - 1 ;\n\n  ctrl_pts2.push_back(*beg);\n\n  if ( ctrl_pts.size() > 2 )\n  {\n    cp_const_iterator curr = beg ;\n    cp_const_iterator next1 = curr  + 1 ;\n    cp_const_iterator next2 = next1 + 1 ;\n\n    do\n    {\n      CGAL::Orientation lOrient = orientation(*curr,*next1,*next2);\n\n      if ( lOrient != CGAL::COLLINEAR )\n        ctrl_pts2.push_back(*next1);\n\n      ++ curr  ;\n      ++ next1 ;\n      ++ next2 ;\n\n    }\n    while ( next2 != end ) ;\n  }\n\n  ctrl_pts2.push_back(*last);\n\n  return Bezier_curve(ctrl_pts2.begin(),ctrl_pts2.end());\n}\n\nbool read_bezier ( QString aFileName, Bezier_polygon_set& rSet, Bezier_region_source_container& rSources  )\n{\n\n  bool rOK = false ;\n\n  std::ifstream in_file (qPrintable(aFileName));\n\n  if ( in_file )\n  {\n    try\n    {\n\n      std::string format ;\n      std::getline(in_file,format);\n\n      bool lDoubleFormat = ( format.length() >= 6 && format.substr(0,6) == \"DOUBLE\") ;\n\n      // Red the number of bezier polygon with holes\n      unsigned int n_regions ;\n      in_file >> n_regions;\n\n      for ( unsigned int r = 0 ; r < n_regions ; ++ r )\n      {\n        Bezier_polygon_vector bezier_polygons ;\n        Bezier_region_source  br_source ;\n\n        // Read the number of bezier curves.\n        unsigned int n_boundaries;\n        in_file >> n_boundaries;\n\n        for ( unsigned int b = 0 ; b < n_boundaries ; ++ b )\n        {\n          Bezier_boundary_source bb_source ;\n\n          // Read the number of bezier curves.\n          unsigned int n_curves;\n          in_file >> n_curves;\n\n          // Read the curves one by one, and construct the general polygon these\n          // curve form (the outer boundary and the holes inside it).\n\n          std::list<Bezier_X_monotone_curve> xcvs;\n\n          for ( unsigned int k = 0; k < n_curves; ++ k )\n          {\n            // Read the current curve and subdivide it into x-monotone subcurves.\n\n            std::list<CGAL::Object>                 x_objs;\n            std::list<CGAL::Object>::const_iterator xoit;\n            Bezier_X_monotone_curve                 xcv;\n            Bezier_traits                           traits;\n            Bezier_traits::Make_x_monotone_2        make_x_monotone = traits.make_x_monotone_2_object();\n\n            Bezier_curve b = read_bezier_curve(in_file, lDoubleFormat);\n\n            if ( b.number_of_control_points() >= 2 )\n            {\n              bb_source.push_back(b);\n              //TRACE( \"region \" << r << \" boundary \" << b << \" curve \" << k );\n\n              make_x_monotone (b, std::back_inserter (x_objs));\n\n              for (xoit = x_objs.begin(); xoit != x_objs.end(); ++xoit)\n              {\n                if (CGAL::assign (xcv, *xoit))\n                {\n                  //TRACE( \" X montonote: \" << xcv.source() << \" -> \" << xcv.target() << ( xcv.is_directed_right() ? \" RIGHT\":\" LEFT\") << ( xcv.is_vertical() ? \" VERTICAL\" : \"\")) ;\n                  xcvs.push_back (xcv);\n                }\n              }\n            }\n          }\n\n          Bezier_polygon  pgn (xcvs.begin(), xcvs.end());\n\n          CGAL::Orientation  orient = pgn.orientation();\n          //TRACE( \"  Orientation: \" << orient ) ;\n\n          if (( b == 0 && orient == CGAL::CLOCKWISE) || ( b > 0 && orient == CGAL::COUNTERCLOCKWISE))\n          {\n            //TRACE( \"Reversing orientation: \" ) ;\n            pgn.reverse_orientation();\n          }\n\n          br_source.push_back(bb_source);\n          bezier_polygons.push_back (pgn);\n        }\n\n        if ( bezier_polygons.size() > 0 )\n        {\n          Bezier_polygon_with_holes pwh(bezier_polygons.front());\n\n          if ( bezier_polygons.size() > 1 )\n          {\n            for ( Bezier_polygon_vector::const_iterator it = std::next(bezier_polygons.begin())\n                ; it != bezier_polygons.end()\n                ; ++ it\n                )\n              pwh.add_hole(*it);\n          }\n\n          if ( is_valid_polygon_with_holes(pwh, rSet.traits() ) )\n          {\n            rSet.join(pwh) ;\n            rSources.push_back(br_source);\n          }\n          else\n          {\n            show_warning( \"Bezier polygon is not valid\" );\n          }\n        }\n\n        rOK = true ;\n      }\n\n    }\n    catch(...)\n    {\n      show_error(\"Exception ocurred during reading of bezier polygon set.\");\n    }\n  }\n\n  return rOK ;\n}\n\nbool save_circular ( QString aFileName, Circular_polygon_set& rSet )\n{\n  bool rOK = false ;\n\n  return rOK ;\n}\n\nvoid save_bezier_polygon( std::ostream& out_file, Bezier_polygon const& aBP )\n{\n  typedef std::vector<Bezier_rat_point> Bezier_rat_point_vector ;\n\n  int cc = aBP.size() ;\n  int lc = cc - 1 ;\n\n  out_file << \"  \" <<  cc << std::endl ;\n\n  Bezier_rat_point lFirstP, lPrevP ;\n\n  int i = 0 ;\n\n  for ( Bezier_polygon::Curve_const_iterator cit = aBP.curves_begin() ; cit != aBP.curves_end() ; ++ cit, ++ i  )\n  {\n    Bezier_rat_point_vector lQ ;\n\n    CGAL::Qt::Bezier_helper::clip(*cit,lQ);\n\n    out_file << \"   \" << lQ.size() << std::endl ;\n\n    if ( i == 0 )\n      lFirstP = lQ.front();\n\n    if ( i == lc )\n      lQ.back() = lFirstP ;\n\n    for ( Bezier_rat_point_vector::const_iterator pit = lQ.begin() ; pit != lQ.end() ; ++ pit )\n    {\n      Bezier_rat_point lP = pit == lQ.begin() && i > 0 ? lPrevP : *pit ;\n\n      out_file << \"    \" << CGAL::to_double(lP.x()) << \" \" << CGAL::to_double(lP.y()) << std::endl ;\n\n      lPrevP = lP ;\n    }\n  }\n}\n\nbool save_bezier_result ( QString aFileName, Bezier_polygon_set const& aSet )\n{\n  bool rOK = false ;\n\n  std::ofstream out_file( qPrintable(aFileName) ) ;\n  if ( out_file )\n  {\n    out_file << \"DOUBLE\" << std::endl ;\n\n    std::vector<Bezier_polygon_with_holes> bpwh_container;\n\n    aSet.polygons_with_holes( std::back_inserter(bpwh_container) ) ;\n\n    out_file << bpwh_container.size() << std::endl ;\n\n    for( std::vector<Bezier_polygon_with_holes>::const_iterator rit = bpwh_container.begin(); rit != bpwh_container.end() ; ++ rit )\n    {\n      Bezier_polygon_with_holes bpwh = *rit ;\n\n      out_file << \" \" << ( 1 + bpwh.number_of_holes() ) << std::endl ;\n\n      save_bezier_polygon( out_file, bpwh.outer_boundary() ) ;\n\n      for ( Bezier_polygon_with_holes::Hole_const_iterator hit = bpwh.holes_begin() ; hit != bpwh.holes_end() ; ++ hit )\n        save_bezier_polygon(out_file, *hit);\n\n      rOK = true ;\n    }\n  }\n\n  return rOK ;\n\n}\n\nbool save_bezier_sources ( QString aFileName, Bezier_region_source_container const& aSources )\n{\n  bool rOK = false ;\n\n  std::ofstream out_file( qPrintable(aFileName) ) ;\n  if ( out_file )\n  {\n    out_file << std::setprecision(19);\n\n    out_file << \"DOUBLE\" << std::endl ;\n\n    out_file << aSources.size() << std::endl ;\n\n    for( Bezier_region_source_container::const_iterator rit = aSources.begin(); rit != aSources.end() ; ++ rit )\n    {\n      Bezier_region_source const& br = *rit ;\n\n      out_file << \"  \" << br.size() << std::endl ;\n\n      for( Bezier_region_source::const_iterator bit = br.begin(); bit != br.end() ; ++ bit )\n      {\n        Bezier_boundary_source const& bb = *bit ;\n\n        out_file << \"   \" << bb.size() << std::endl ;\n\n        for ( Bezier_boundary_source::const_iterator cit = bb.begin() ; cit != bb.end() ; ++ cit )\n        {\n          Bezier_curve const& bc = *cit ;\n\n          out_file << \"    \" << bc.number_of_control_points() << std::endl ;\n\n          for ( Bezier_curve::Control_point_iterator pit = bc.control_points_begin() ; pit != bc.control_points_end() ; ++ pit )\n          {\n            out_file << \"     \" << CGAL::to_double(pit->x()) << \" \" << CGAL::to_double(pit->y()) << std::endl ;\n          }\n        }\n      }\n    }\n\n    rOK = true ;\n  }\n\n  return rOK ;\n\n}\n\nvoid MainWindow::on_actionOpenLinear_triggered()\n{\n  open(QFileDialog::getOpenFileName(this, tr(\"Open Linear Polygon\"), \"../data\", tr(\"Linear Curve files (*.lps)\") ));\n}\n\nvoid MainWindow::on_actionOpenDXF_triggered()\n{\n  open(QFileDialog::getOpenFileName(this, tr(\"Open DXF\"), \"../data\", tr(\"DXF files (*.dxf)\") ));\n}\n\nvoid MainWindow::on_actionOpenBezier_triggered()\n{\n  open(QFileDialog::getOpenFileName(this, tr(\"Open Bezier Polygon\"), \"../data\", tr(\"Bezier Curve files (*.bps)\") ));\n}\nvoid MainWindow::on_actionSaveBlue_triggered()\n{\n  if ( mCircular_active )\n  {\n    if ( !save_circular(QFileDialog::getSaveFileName(this, tr(\"Save 'Q' Circular Polygon Set\"), \"../data\", tr(\"Linear Curve files (*.lps)\") )\n                       ,active_set().circular()\n                       )\n       )\n    {\n      show_error(\"Cannot save circular polygon set.\");\n    }\n\n  }\n  else\n  {\n    if ( !save_bezier_sources(QFileDialog::getSaveFileName(this, tr(\"Save 'Q' Bezier Polygon Set\"), \"../data\", tr(\"Bezier Curve files (*.bps)\") )\n                             ,blue_bezier_sources()\n                             )\n       )\n    {\n      show_error(\"Cannot save bezier polygon set.\");\n    }\n  }\n\n}\n\nvoid MainWindow::on_actionSaveRed_triggered()\n{\n  if ( mCircular_active )\n  {\n    if ( !save_circular(QFileDialog::getSaveFileName(this, tr(\"Save 'P' Circular Polygon Set\"), \"../data\", tr(\"Linear Curve files (*.lps)\") )\n                       ,red_set().circular()\n                       )\n       )\n    {\n      show_error(\"Cannot save circular polygon set.\");\n    }\n\n  }\n  else\n  {\n    if ( !save_bezier_sources(QFileDialog::getSaveFileName(this, tr(\"Save 'P' Bezier Polygon Set\"), \"../data\", tr(\"Bezier Curve files (*.bps)\") )\n                             ,red_bezier_sources()\n                             )\n       )\n    {\n      show_error(\"Cannot save bezier polygon set.\");\n    }\n  }\n\n}\n\n\nvoid MainWindow::on_actionSaveResult_triggered()\n{\n  if ( mCircular_active )\n  {\n    if ( !save_circular(QFileDialog::getSaveFileName(this, tr(\"Save Result Circular Polygon Set\"), \"../data\", tr(\"Linear Curve files (*.lps)\") )\n                       ,result_set().circular()\n                       )\n       )\n    {\n      show_error(\"Cannot save circular polygon set.\");\n    }\n\n  }\n  else\n  {\n    if ( !save_bezier_result(QFileDialog::getSaveFileName(this, tr(\"Save Result Bezier Polygon Set\"), \"../data\", tr(\"Bezier Curve files (*.bps)\") )\n                            ,result_set().bezier()\n                            )\n       )\n    {\n      show_error(\"Cannot save bezier polygon set.\");\n    }\n  }\n\n}\n\nvoid MainWindow::switch_set_type( Curve_set& aSet, int aType )\n{\n  unlink_GI( aSet.gi() ) ;\n\n  aSet.reset_type(aType);\n\n  link_GI( aSet.gi() ) ;\n\n  modelChanged();\n}\n\nvoid MainWindow::switch_sets_type( int aType )\n{\n  switch_set_type( blue_set  (), aType ) ;\n  switch_set_type( red_set   (), aType ) ;\n  switch_set_type( result_set(), aType ) ;\n\n}\n\nbool MainWindow::ensure_circular_mode()\n{\n  if ( ! mCircular_active )\n  {\n    bool lProceed = blue_set().is_empty() && red_set().is_empty() ;\n\n    if ( ! lProceed )\n      lProceed = ask_user_yesno(\"Linear/Circular mode switch\"\n                               ,\"You are about to load a linear or circular poygon, but there are bezier curves already loaded.\\n\" \\\n                                \"Both types are not interoperable. In order to proceed, the bezier curves must be removed first.\\n\" \\\n                                \"OK to remove and proceed?\\n\"\n                               ) ;\n\n    if ( lProceed )\n    {\n      switch_sets_type(CIRCULAR_TYPE);\n      mCircular_active = true ;\n    }\n  }\n  return mCircular_active ;\n}\n\nbool MainWindow::ensure_bezier_mode()\n{\n  if ( mCircular_active )\n  {\n    bool lProceed = blue_set().is_empty() && red_set().is_empty() ;\n\n    if ( ! lProceed )\n      lProceed = ask_user_yesno(\"Bezier mode switch\"\n                               ,\"You are about to load a Bezier curve, but there are linear and/or circular polygons already loaded.\\n\" \\\n                                \"Both types are not interoperable. In order to proceed, the polygons must be removed first.\\n\" \\\n                                \"OK to remove and proceed?\\n\"\n                               ) ;\n\n    if ( lProceed )\n    {\n      switch_sets_type(BEZIER_TYPE);\n      mCircular_active = false ;\n    }\n  }\n  return !mCircular_active ;\n}\n\nvoid MainWindow::open( QString fileName )\n{\n  if(! fileName.isEmpty())\n  {\n    bool lRead = false ;\n\n    if(fileName.endsWith(\".lps\"))\n    {\n      if ( ensure_circular_mode() )\n        lRead = read_linear(fileName,active_set().circular(), active_circular_sources() ) ;\n    }\n    else if (fileName.endsWith(\".dxf\"))\n    {\n      if ( ensure_circular_mode() )\n        lRead = read_dxf(fileName,active_set().circular(), active_circular_sources() ) ;\n    }\n    else if (fileName.endsWith(\".bps\"))\n    {\n      if ( ensure_bezier_mode() )\n        lRead = read_bezier(fileName,active_set().bezier(), active_bezier_sources() ) ;\n    }\n\n    if ( lRead )\n    {\n      modelChanged();\n      zoomToFit();\n      this->addToRecentFiles(fileName);\n\n    }\n  }\n}\n\nvoid MainWindow::on_actionInsertBezier_toggled(bool aChecked)\n{\n  if(aChecked)\n       mScene.installEventFilter(mBezierInput);\n  else mScene.removeEventFilter (mBezierInput);\n}\n\nvoid MainWindow::on_actionInsertCircular_toggled(bool aChecked)\n{\n  if(aChecked)\n       mScene.installEventFilter(mCircularInput);\n  else mScene.removeEventFilter (mCircularInput);\n}\n\nvoid MainWindow::on_actionInsertCircle_toggled(bool aChecked)\n{\n//  if(aChecked)\n//       mScene.installEventFilter(mCircleInput);\n//  else mScene.removeEventFilter (mCircleInput);\n}\n\nvoid MainWindow::processInput(CGAL::Object o )\n{\n  std::pair<Bezier_polygon,Bezier_boundary_source>     lBI ;\n  Circular_polygon lCI ;\n\n  if(CGAL::assign(lBI, o))\n  {\n    if ( ensure_bezier_mode() )\n    {\n      CGAL::Orientation o = lBI.first.orientation();\n      if ( o == CGAL::CLOCKWISE )\n        lBI.first.reverse_orientation();\n\n      active_set().bezier().join( Bezier_polygon_with_holes(lBI.first) ) ;\n\n      Bezier_region_source br ; br.push_back (lBI.second);\n\n      active_bezier_sources().push_back(br);\n\n    }\n  }\n  else if ( CGAL::assign(lCI, o) )\n  {\n    if ( ensure_circular_mode() )\n    {\n      CGAL::Orientation o = lCI.orientation();\n      if ( o == CGAL::CLOCKWISE )\n        lCI.reverse_orientation();\n\n      Circular_polygon_with_holes lCPWH(lCI);\n      active_set().circular().join(lCPWH) ;\n\n      active_circular_sources().push_back(lCPWH);\n    }\n  }\n  modelChanged();\n}\n\nvoid MainWindow::on_actionIntersection_triggered()\n{\n  bool lDone = false ;\n\n  QCursor old = this->cursor();\n  this->setCursor(Qt::WaitCursor);\n\n  if ( !blue_set().is_empty() && !red_set().is_empty() )\n  {\n    result_set().assign( red_set() ) ;\n    result_set().intersect(blue_set());\n    lDone = true ;\n  }\n\n  this->setCursor(old);\n\n  if ( lDone )\n  {\n    //SetViewBlue(false); SetViewRed(false); SetViewResult(true);\n\n    modelChanged();\n  }\n}\n\nvoid MainWindow::on_actionUnion_triggered()\n{\n  bool lDone = false ;\n\n  QCursor old = this->cursor();\n  this->setCursor(Qt::WaitCursor);\n\n  if ( !blue_set().is_empty() && !red_set().is_empty() )\n  {\n    result_set().assign( red_set() ) ;\n    result_set().join(blue_set());\n    lDone = true ;\n  }\n\n  this->setCursor(old);\n\n  if ( lDone )\n  {\n    //SetViewBlue(false);  SetViewRed(false);  SetViewResult(true);\n\n    modelChanged();\n  }\n}\n\nvoid MainWindow::on_actionBlueMinusRed_triggered()\n{\n  bool lDone = false ;\n\n  QCursor old = this->cursor();\n  this->setCursor(Qt::WaitCursor);\n\n  if ( !blue_set().is_empty() && !red_set().is_empty() )\n  {\n    result_set().assign( blue_set() ) ;\n    result_set().difference(red_set());\n    lDone = true ;\n  }\n\n  this->setCursor(old);\n\n  if ( lDone )\n  {\n    //SetViewBlue(false);  SetViewRed(false); SetViewResult(true);\n\n    modelChanged();\n  }\n}\n\nvoid MainWindow::on_actionRedMinusBlue_triggered()\n{\n  bool lDone = false ;\n\n  QCursor old = this->cursor();\n  this->setCursor(Qt::WaitCursor);\n\n  if ( !blue_set().is_empty() && !red_set().is_empty() )\n  {\n    result_set().assign( red_set() ) ;\n    result_set().difference(blue_set());\n    lDone = true ;\n  }\n\n  this->setCursor(old);\n\n  if ( lDone )\n  {\n    //SetViewBlue(false);  SetViewRed(false); SetViewResult(true);\n\n    modelChanged();\n  }\n}\n\nvoid MainWindow::on_actionSymmDiff_triggered()\n{\n  bool lDone = false ;\n\n  QCursor old = this->cursor();\n  this->setCursor(Qt::WaitCursor);\n\n  if ( !blue_set().is_empty() && !red_set().is_empty() )\n  {\n    result_set().assign( red_set() ) ;\n    result_set().symmetric_difference(blue_set());\n    lDone = true ;\n  }\n\n  this->setCursor(old);\n\n\n  if ( lDone )\n  {\n    //SetViewBlue(false); SetViewRed(false); SetViewResult(true);\n\n    modelChanged();\n  }\n}\n\nvoid MainWindow::on_actionMinkowskiSum_triggered()\n{\n}\n\nvoid MainWindow::on_actionBlueComplement_triggered()\n{\n  bool lDone = false ;\n\n  QCursor old = this->cursor();\n  this->setCursor(Qt::WaitCursor);\n\n  if ( !blue_set().is_empty() )\n  {\n    result_set().assign( blue_set() ) ;\n    result_set().complement();\n    lDone = true ;\n  }\n\n  this->setCursor(old);\n\n  if ( lDone )\n  {\n    //SetViewBlue(false); SetViewRed(false); SetViewResult(true);\n\n    modelChanged();\n  }\n}\n\nvoid MainWindow::on_actionRedComplement_triggered()\n{\n  bool lDone = false ;\n\n  QCursor old = this->cursor();\n  this->setCursor(Qt::WaitCursor);\n\n  if ( !red_set().is_empty() )\n  {\n    result_set().assign( red_set() ) ;\n    result_set().complement();\n    lDone = true ;\n  }\n\n  this->setCursor(old);\n\n  if ( lDone )\n  {\n    //SetViewBlue(false);  SetViewRed(false); SetViewResult(true);\n\n    modelChanged();\n  }\n}\n\nvoid MainWindow::on_actionAllBlue_triggered()\n{\n  bool lDone = false ;\n\n  bool lProceed = result_set().is_empty() ? ask_user_yesno(\"Store result\", \"Result is empty, all polygons will be deleted\\n continue anyway?\\n\")\n                                          : true ;\n\n  if ( lProceed )\n  {\n    blue_set().assign( result_set() ) ;\n    result_set().clear();\n    radioMakeRedActive->setChecked(true);\n    lDone = true ;\n  }\n\n  if ( lDone )\n  {\n    //SetViewBlue(true);  SetViewRed(false); SetViewResult(true);\n\n    modelChanged();\n  }\n}\n\nvoid MainWindow::on_actionAllRed_triggered()\n{\n  bool lDone = false ;\n\n  bool lProceed = result_set().is_empty() ? ask_user_yesno(\"Store result\", \"Result is empty, all polygons will be deleted\\n continue anyway?\\n\")\n                                          : true ;\n\n  if ( lProceed )\n  {\n    red_set().assign( result_set() ) ;\n    result_set().clear();\n    radioMakeBlueActive->setChecked(true);\n    lDone = true ;\n  }\n\n  if ( lDone )\n  {\n    //SetViewBlue(false); SetViewRed(true);  SetViewResult(true);\n\n    modelChanged();\n  }\n}\nvoid MainWindow::on_actionDeleteBlue_triggered()\n{\n  blue_set             ().clear();\n  blue_circular_sources().clear();\n  blue_bezier_sources  ().clear();\n\n  //SetViewBlue(true);SetViewRed(true); SetViewResult(true);\n\n  modelChanged();\n}\n\nvoid MainWindow::on_actionDeleteRed_triggered()\n{\n  red_set             ().clear();\n  red_circular_sources().clear();\n  red_bezier_sources  ().clear();\n\n  //SetViewBlue(true); SetViewRed(true); SetViewResult(true);\n\n  modelChanged();\n}\n\n\nvoid MainWindow::ToogleView( int aGROUP, bool aChecked )\n{\n  if ( aChecked )\n       set(aGROUP).gi()->show();\n  else set(aGROUP).gi()->hide();\n}\n\n\nvoid MainWindow::zoomToFit()\n{\n  boost::optional<QRectF> lTotalRect ;\n\n  for ( Curve_set_const_iterator si = mCurve_sets.begin() ; si != mCurve_sets.end() ; ++ si )\n  {\n    if ( !si->is_empty() )\n    {\n      QRectF lRect = si->bounding_rect();\n      if ( lTotalRect )\n           lTotalRect = *lTotalRect | lRect ;\n      else lTotalRect = lRect ;\n    }\n  }\n\n  if ( lTotalRect )\n  {\n    this->graphicsView->setSceneRect(*lTotalRect);\n    this->graphicsView->fitInView(*lTotalRect, Qt::KeepAspectRatio);\n  }\n}\n\n#include \"boolean_operations_2.moc\"\n#include <CGAL/Qt/resources.h>\n\nint main(int argc, char **argv)\n{\n  QApplication app(argc, argv);\n\n  app.setOrganizationDomain(\"geometryfactory.com\");\n  app.setOrganizationName(\"GeometryFactory\");\n  app.setApplicationName(\"Boolean_operations_2 demo\");\n\n  // Import resources from libCGALQt5.\n  CGAL_QT_INIT_RESOURCES;\n\n  MainWindow mainWindow;\n  mainWindow.show();\n  return app.exec();\n}\n\n\n", "meta": {"hexsha": "a8dd97b66c9d847d1caa9133dfa502710f36adbb", "size": 43507, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Boolean_set_operations_2/archive/demo/Boolean_set_operations_2_GraphicsView/boolean_operations_2.cpp", "max_stars_repo_name": "gaschler/cgal", "max_stars_repo_head_hexsha": "d1fe2afa18da5524db6d4946f42ca4b8d00e0bda", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-12-12T09:30:07.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-04T05:00:23.000Z", "max_issues_repo_path": "Boolean_set_operations_2/archive/demo/Boolean_set_operations_2_GraphicsView/boolean_operations_2.cpp", "max_issues_repo_name": "gaschler/cgal", "max_issues_repo_head_hexsha": "d1fe2afa18da5524db6d4946f42ca4b8d00e0bda", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-03-12T14:38:20.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-12T14:38:20.000Z", "max_forks_repo_path": "Boolean_set_operations_2/archive/demo/Boolean_set_operations_2_GraphicsView/boolean_operations_2.cpp", "max_forks_repo_name": "szobov/cgal", "max_forks_repo_head_hexsha": "e7b91b92b8c6949e3b62023bdd1e9f3ad8472626", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-03-05T04:18:59.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-05T04:18:59.000Z", "avg_line_length": 26.6260709914, "max_line_length": 180, "alphanum_fraction": 0.6280598524, "num_tokens": 11305, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5195213219520929, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.315693973293183}}
{"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/SizeParam.h\"\n#include \"latbuilder/Util.h\"\n#include <NTL/GF2XFactoring.h>\n\nnamespace LatBuilder {\n\n//===========================================================================================\ntemplate <LatticeType LR>\nSizeParam<LR,EmbeddingType::UNILEVEL>::SizeParam(SizeParam<LR,EmbeddingType::UNILEVEL>::Modulus modulus):\n   BasicSizeParam<SizeParam<LR,EmbeddingType::UNILEVEL>>(modulus)\n{}\n\n//===========================================================================================\n\ntemplate<>\nsize_t\nSizeParam<LatticeType::ORDINARY,EmbeddingType::UNILEVEL>::totient() const\n{\n   auto n = numPoints();\n   for (const auto& p : LatBuilder::primeFactors(n))\n      n = n * (p - 1) / p;\n   return n;\n}\n\ntemplate<>\nsize_t\nSizeParam<LatticeType::POLYNOMIAL,EmbeddingType::UNILEVEL>::totient() const\n{\n   auto polynomial = modulus();\n   auto n = intPow(2,deg(polynomial));\n   NTL::vector< NTL::Pair< NTL::GF2X, long > > factors ;\n   CanZass(factors, polynomial); // calls \"Cantor/Zassenhaus\" algorithm from <NTL/GF2XFactoring.h>\n   for (const auto& p : factors)\n      n = n * (intPow(2,deg(p.a)) - 1) / intPow(2,deg(p.a));\n   return n;\n}\n\n//================================================================================================\n\ntemplate <LatticeType LR>\nvoid\nSizeParam<LR,EmbeddingType::UNILEVEL>::normalize(Real& merit) const\n{ merit /= this->numPoints(); }\n\ntemplate <LatticeType LR>\nvoid\nSizeParam<LR,EmbeddingType::UNILEVEL>::normalize(RealVector& merit) const\n{ merit /= this->numPoints(); }\n\ntemplate <LatticeType LR>\nstd::ostream&\nSizeParam<LR, EmbeddingType::UNILEVEL>::format(std::ostream& os) const\n{ return os << this->modulus(); }\n\n//==================================================================================================\n\ntemplate class SizeParam<LatticeType::ORDINARY,EmbeddingType::UNILEVEL>;\ntemplate class SizeParam<LatticeType::POLYNOMIAL,EmbeddingType::UNILEVEL>;\ntemplate class SizeParam<LatticeType::DIGITAL,EmbeddingType::UNILEVEL>;\n\n}\n\n", "meta": {"hexsha": "51f1c6f95b61a3b5c9e859159beea9638cea9d8d", "size": 2714, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/LatBuilder/SizeParam-SIMPLE.cc", "max_stars_repo_name": "umontreal-simul/latnetbuilder", "max_stars_repo_head_hexsha": "7490a403974741b0ee62f0100a94043ed826b563", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2020-01-21T06:08:51.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-24T16:11:31.000Z", "max_issues_repo_path": "src/LatBuilder/SizeParam-SIMPLE.cc", "max_issues_repo_name": "umontreal-simul/latbuilder", "max_issues_repo_head_hexsha": "7490a403974741b0ee62f0100a94043ed826b563", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2019-10-31T07:49:28.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-03T12:07:49.000Z", "max_forks_repo_path": "src/LatBuilder/SizeParam-SIMPLE.cc", "max_forks_repo_name": "umontreal-simul/latbuilder", "max_forks_repo_head_hexsha": "7490a403974741b0ee62f0100a94043ed826b563", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2016-07-27T19:25:26.000Z", "max_forks_repo_forks_event_max_datetime": "2018-05-22T20:00:47.000Z", "avg_line_length": 34.3544303797, "max_line_length": 111, "alphanum_fraction": 0.6267501842, "num_tokens": 668, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5813031051514763, "lm_q2_score": 0.5428632831725051, "lm_q1q2_score": 0.3155681121809024}}
{"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_OCEA_HPP\n#define BOOST_GEOMETRY_PROJECTIONS_OCEA_HPP\n\n#include <boost/geometry/util/math.hpp>\n\n#include <boost/geometry/srs/projections/impl/base_static.hpp>\n#include <boost/geometry/srs/projections/impl/base_dynamic.hpp>\n#include <boost/geometry/srs/projections/impl/projects.hpp>\n#include <boost/geometry/srs/projections/impl/factory_entry.hpp>\n\nnamespace boost { namespace geometry\n{\n\nnamespace srs { namespace par4\n{\n    struct ocea {}; // Oblique Cylindrical Equal Area\n\n}} //namespace srs::par4\n\nnamespace projections\n{\n    #ifndef DOXYGEN_NO_DETAIL\n    namespace detail { namespace ocea\n    {\n            template <typename T>\n            struct par_ocea\n            {\n                T    rok;\n                T    rtk;\n                T    sinphi;\n                T    cosphi;\n                T    singam;\n                T    cosgam;\n            };\n\n            // template class, using CRTP to implement forward/inverse\n            template <typename T, typename Parameters>\n            struct base_ocea_spheroid\n                : public base_t_fi<base_ocea_spheroid<T, Parameters>, T, Parameters>\n            {\n                par_ocea<T> m_proj_parm;\n\n                inline base_ocea_spheroid(const Parameters& par)\n                    : base_t_fi<base_ocea_spheroid<T, Parameters>,\n                     T, Parameters>(*this, par) {}\n\n                // FORWARD(s_forward)  spheroid\n                // Project coordinates from geographic (lon, lat) to cartesian (x, y)\n                inline void fwd(T& lp_lon, T& lp_lat, T& xy_x, T& xy_y) const\n                {\n                    static const T pi = detail::pi<T>();\n\n                    T t;\n\n                    xy_y = sin(lp_lon);\n                    t = cos(lp_lon);\n                    xy_x = atan((tan(lp_lat) * this->m_proj_parm.cosphi + this->m_proj_parm.sinphi * xy_y) / t);\n                    if (t < 0.)\n                        xy_x += pi;\n                    xy_x *= this->m_proj_parm.rtk;\n                    xy_y = this->m_proj_parm.rok * (this->m_proj_parm.sinphi * sin(lp_lat) - this->m_proj_parm.cosphi * cos(lp_lat) * xy_y);\n                }\n\n                // INVERSE(s_inverse)  spheroid\n                // Project coordinates from cartesian (x, y) to geographic (lon, lat)\n                inline void inv(T& xy_x, T& xy_y, T& lp_lon, T& lp_lat) const\n                {\n                    T t, s;\n\n                    xy_y /= this->m_proj_parm.rok;\n                    xy_x /= this->m_proj_parm.rtk;\n                    t = sqrt(1. - xy_y * xy_y);\n                    lp_lat = asin(xy_y * this->m_proj_parm.sinphi + t * this->m_proj_parm.cosphi * (s = sin(xy_x)));\n                    lp_lon = atan2(t * this->m_proj_parm.sinphi * s - xy_y * this->m_proj_parm.cosphi,\n                        t * cos(xy_x));\n                }\n\n                static inline std::string get_name()\n                {\n                    return \"ocea_spheroid\";\n                }\n\n            };\n\n            // Oblique Cylindrical Equal Area\n            template <typename Parameters, typename T>\n            inline void setup_ocea(Parameters& par, par_ocea<T>& proj_parm)\n            {\n                static const T half_pi = detail::half_pi<T>();\n\n                T phi_0=0.0, phi_1, phi_2, lam_1, lam_2, lonz, alpha;\n\n                proj_parm.rok = 1. / par.k0;\n                proj_parm.rtk = par.k0;\n                /*If the keyword \"alpha\" is found in the sentence then use 1point+1azimuth*/\n                if ( pj_param_r(par.params, \"alpha\", alpha)) {\n                    /*Define Pole of oblique transformation from 1 point & 1 azimuth*/\n                    //alpha = pj_get_param_r(par.params, \"alpha\"); // set above\n                    lonz = pj_get_param_r(par.params, \"lonc\");\n                    /*Equation 9-8 page 80 (http://pubs.usgs.gov/pp/1395/report.pdf)*/\n                    proj_parm.singam = atan(-cos(alpha)/(-sin(phi_0) * sin(alpha))) + lonz;\n                    /*Equation 9-7 page 80 (http://pubs.usgs.gov/pp/1395/report.pdf)*/\n                    proj_parm.sinphi = asin(cos(phi_0) * sin(alpha));\n                /*If the keyword \"alpha\" is NOT found in the sentence then use 2points*/\n                } else {\n                    /*Define Pole of oblique transformation from 2 points*/\n                    phi_1 = pj_get_param_r(par.params, \"lat_1\");\n                    phi_2 = pj_get_param_r(par.params, \"lat_2\");\n                    lam_1 = pj_get_param_r(par.params, \"lon_1\");\n                    lam_2 = pj_get_param_r(par.params, \"lon_2\");\n                    /*Equation 9-1 page 80 (http://pubs.usgs.gov/pp/1395/report.pdf)*/\n                    proj_parm.singam = atan2(cos(phi_1) * sin(phi_2) * cos(lam_1) -\n                        sin(phi_1) * cos(phi_2) * cos(lam_2),\n                        sin(phi_1) * cos(phi_2) * sin(lam_2) -\n                        cos(phi_1) * sin(phi_2) * sin(lam_1) );\n\n                    /* take care of P->lam0 wrap-around when +lam_1=-90*/\n                    if (lam_1 == -half_pi)\n                        proj_parm.singam = -proj_parm.singam;\n\n                    /*Equation 9-2 page 80 (http://pubs.usgs.gov/pp/1395/report.pdf)*/\n                    proj_parm.sinphi = atan(-cos(proj_parm.singam - lam_1) / tan(phi_1));\n                }\n                par.lam0 = proj_parm.singam + half_pi;\n                proj_parm.cosphi = cos(proj_parm.sinphi);\n                proj_parm.sinphi = sin(proj_parm.sinphi);\n                proj_parm.cosgam = cos(proj_parm.singam);\n                proj_parm.singam = sin(proj_parm.singam);\n                par.es = 0.;\n            }\n\n    }} // namespace detail::ocea\n    #endif // doxygen\n\n    /*!\n        \\brief Oblique Cylindrical Equal Area projection\n        \\ingroup projections\n        \\tparam Geographic latlong point type\n        \\tparam Cartesian xy point type\n        \\tparam Parameters parameter type\n        \\par Projection characteristics\n         - Cylindrical\n         - Spheroid\n        \\par Projection parameters\n         - lonc: Longitude (only used if alpha (or gamma) is specified) (degrees)\n         - alpha: Alpha (degrees)\n         - lat_1: Latitude of first standard parallel (degrees)\n         - lat_2: Latitude of second standard parallel (degrees)\n         - lon_1 (degrees)\n         - lon_2 (degrees)\n        \\par Example\n        \\image html ex_ocea.gif\n    */\n    template <typename T, typename Parameters>\n    struct ocea_spheroid : public detail::ocea::base_ocea_spheroid<T, Parameters>\n    {\n        inline ocea_spheroid(const Parameters& par) : detail::ocea::base_ocea_spheroid<T, Parameters>(par)\n        {\n            detail::ocea::setup_ocea(this->m_par, this->m_proj_parm);\n        }\n    };\n\n    #ifndef DOXYGEN_NO_DETAIL\n    namespace detail\n    {\n\n        // Static projection\n        BOOST_GEOMETRY_PROJECTIONS_DETAIL_STATIC_PROJECTION(srs::par4::ocea, ocea_spheroid, ocea_spheroid)\n\n        // Factory entry(s)\n        template <typename T, typename Parameters>\n        class ocea_entry : public detail::factory_entry<T, Parameters>\n        {\n            public :\n                virtual base_v<T, Parameters>* create_new(const Parameters& par) const\n                {\n                    return new base_v_fi<ocea_spheroid<T, Parameters>, T, Parameters>(par);\n                }\n        };\n\n        template <typename T, typename Parameters>\n        inline void ocea_init(detail::base_factory<T, Parameters>& factory)\n        {\n            factory.add_to_factory(\"ocea\", new ocea_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_OCEA_HPP\n", "meta": {"hexsha": "3ce5913a07a7e7851ea5279718bd812b6fa78716", "size": 9616, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/external/boost/boost_1_68_0/boost/geometry/srs/projections/proj/ocea.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/ocea.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/ocea.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": 41.094017094, "max_line_length": 140, "alphanum_fraction": 0.5846505824, "num_tokens": 2299, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7745833945721304, "lm_q2_score": 0.40733340004593027, "lm_q1q2_score": 0.31551368773018423}}
{"text": "//==============================================================================\n//         Copyright 2003 - 2012   LASMEA UMR 6602 CNRS/Univ. Clermont II\n//         Copyright 2009 - 2012   LRI    UMR 8623 CNRS/Univ Paris Sud XI\n//\n//          Distributed under the Boost Software License, Version 1.0.\n//                 See accompanying file LICENSE.txt or copy at\n//                     http://www.boost.org/LICENSE_1_0.txt\n//==============================================================================\n#ifndef BOOST_SIMD_ARITHMETIC_FUNCTIONS_FAST_HYPOT_HPP_INCLUDED\n#define BOOST_SIMD_ARITHMETIC_FUNCTIONS_FAST_HYPOT_HPP_INCLUDED\n#include <boost/simd/include/functor.hpp>\n#include <boost/dispatch/include/functor.hpp>\n\nnamespace boost { namespace simd { namespace tag\n  {\n    /*!\n      @brief  fast_hypot generic tag\n\n      Represents the fast_hypot function in generic contexts.\n\n      @par Models:\n      Hierarchy\n    **/\n    struct fast_hypot_ : ext::elementwise_<fast_hypot_>\n    {\n      /// @brief Parent hierarchy\n      typedef ext::elementwise_<fast_hypot_> parent;\n      template<class... Args>\n      static BOOST_FORCEINLINE BOOST_AUTO_DECLTYPE dispatch(Args&&... args)\n      BOOST_AUTO_DECLTYPE_BODY( dispatching_fast_hypot_( ext::adl_helper(), static_cast<Args&&>(args)... ) )\n    };\n  }\n  namespace ext\n  {\n    template<class Site>\n    BOOST_FORCEINLINE generic_dispatcher<tag::fast_hypot_, Site> dispatching_fast_hypot_(adl_helper, boost::dispatch::meta::unknown_<Site>, ...)\n    {\n      return generic_dispatcher<tag::fast_hypot_, Site>();\n    }\n    template<class... Args>\n    struct impl_fast_hypot_;\n  }\n  /*!\n    Computes \\f$(x^2 + y^2)^{1/2}\\f$\n\n    @par semantic:\n    For any given value @c x,  @c y of type @c T:\n\n    @code\n    T r = fast_hypot(x, y);\n    @endcode\n\n    The code is equivalent to:\n\n    @code\n    T r =sqrt(sqr(x)+sqr(y));\n    @endcode\n\n    Fast means that nothing is done to avoid overflow or inaccuracies\n    for large values. See @funcref{hypot} if that matters.\n\n    @param  a0\n    @param  a1\n\n    @return      a value of the same floating type as the input.\n  **/\n\n  BOOST_DISPATCH_FUNCTION_IMPLEMENTATION(tag::fast_hypot_, fast_hypot, 2)\n} }\n\n#endif\n\n\n", "meta": {"hexsha": "1084a3dbb29c716299845284a04ea3f9698caa1c", "size": 2200, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/boost/simd/base/include/boost/simd/arithmetic/functions/fast_hypot.hpp", "max_stars_repo_name": "feelpp/nt2", "max_stars_repo_head_hexsha": "4d121e2c7450f24b735d6cff03720f07b4b2146c", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 34.0, "max_stars_repo_stars_event_min_datetime": "2017-05-19T18:10:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-04T02:18:13.000Z", "max_issues_repo_path": "modules/boost/simd/base/include/boost/simd/arithmetic/functions/fast_hypot.hpp", "max_issues_repo_name": "feelpp/nt2", "max_issues_repo_head_hexsha": "4d121e2c7450f24b735d6cff03720f07b4b2146c", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "modules/boost/simd/base/include/boost/simd/arithmetic/functions/fast_hypot.hpp", "max_forks_repo_name": "feelpp/nt2", "max_forks_repo_head_hexsha": "4d121e2c7450f24b735d6cff03720f07b4b2146c", "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": 29.7297297297, "max_line_length": 144, "alphanum_fraction": 0.6172727273, "num_tokens": 563, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6513548782017745, "lm_q2_score": 0.4843800842769844, "lm_q1q2_score": 0.31550333079760046}}
{"text": "// This file is part of libigl, a simple c++ geometry processing library.\n//\n// Copyright (C) 2014 Olga Diamanti <olga.diam@gmail.com>\n//\n// This Source Code Form is subject to the terms of the Mozilla Public License\n// v. 2.0. If a copy of the MPL was not distributed with this file, You can\n// obtain one at http://mozilla.org/MPL/2.0/.\n\n#include \"LinSpaced.h\"\n#include \"n_polyvector.h\"\n#include \"edge_topology.h\"\n#include \"local_basis.h\"\n#include \"nchoosek.h\"\n#include \"slice.h\"\n#include \"polyroots.h\"\n#include \"igl_inline.h\"\n#include <Eigen/Sparse>\n\n#include <Eigen/Geometry>\n#include <iostream>\n#include <complex>\n\nnamespace igl {\n  template <typename DerivedV, typename DerivedF>\n  class PolyVectorFieldFinder\n  {\n  private:\n    const Eigen::PlainObjectBase<DerivedV> &V;\n    const Eigen::PlainObjectBase<DerivedF> &F; int numF;\n    const int n;\n\n    Eigen::MatrixXi EV; int numE;\n    Eigen::MatrixXi F2E;\n    Eigen::MatrixXi E2F;\n    Eigen::VectorXd K;\n\n    Eigen::VectorXi isBorderEdge;\n    int numInteriorEdges;\n    Eigen::Matrix<int,Eigen::Dynamic,2> E2F_int;\n    Eigen::VectorXi indInteriorToFull;\n    Eigen::VectorXi indFullToInterior;\n\n    DerivedV B1, B2, FN;\n\n    IGL_INLINE void computek();\n    IGL_INLINE void setFieldFromGeneralCoefficients(const  std::vector<Eigen::Matrix<std::complex<typename DerivedV::Scalar>, Eigen::Dynamic,1> > &coeffs,\n                                                    std::vector<Eigen::Matrix<typename DerivedV::Scalar, Eigen::Dynamic, 2> > &pv);\n    IGL_INLINE void computeCoefficientLaplacian(int n, Eigen::SparseMatrix<std::complex<typename DerivedV::Scalar> > &D);\n    IGL_INLINE void getGeneralCoeffConstraints(const Eigen::VectorXi &isConstrained,\n                                    const Eigen::Matrix<typename DerivedV::Scalar, Eigen::Dynamic, Eigen::Dynamic> &cfW,\n                                    int k,\n                                    Eigen::Matrix<std::complex<typename DerivedV::Scalar>, Eigen::Dynamic,1> &Ck);\n    IGL_INLINE void precomputeInteriorEdges();\n\n\n    IGL_INLINE void minQuadWithKnownMini(const Eigen::SparseMatrix<std::complex<typename DerivedV::Scalar> > &Q,\n                                         const Eigen::SparseMatrix<std::complex<typename DerivedV::Scalar> > &f,\n                                         const Eigen::VectorXi isConstrained,\n                                         const Eigen::Matrix<std::complex<typename DerivedV::Scalar>, Eigen::Dynamic, 1> &xknown,\n                                         Eigen::Matrix<std::complex<typename DerivedV::Scalar>, Eigen::Dynamic, 1> &x);\n\n  public:\n    IGL_INLINE PolyVectorFieldFinder(const Eigen::PlainObjectBase<DerivedV> &_V,\n                                     const Eigen::PlainObjectBase<DerivedF> &_F,\n                                     const int &_n);\n    IGL_INLINE bool solve(const Eigen::VectorXi &isConstrained,\n               const Eigen::Matrix<typename DerivedV::Scalar, Eigen::Dynamic, Eigen::Dynamic> &cfW,\n               Eigen::Matrix<typename DerivedV::Scalar, Eigen::Dynamic, Eigen::Dynamic> &output);\n\n  };\n}\n\ntemplate<typename DerivedV, typename DerivedF>\nIGL_INLINE igl::PolyVectorFieldFinder<DerivedV, DerivedF>::\n          PolyVectorFieldFinder(const Eigen::PlainObjectBase<DerivedV> &_V,\n                                const Eigen::PlainObjectBase<DerivedF> &_F,\n                                const int &_n):\nV(_V),\nF(_F),\nnumF(_F.rows()),\nn(_n)\n{\n\n  igl::edge_topology(V,F,EV,F2E,E2F);\n  numE = EV.rows();\n\n\n  precomputeInteriorEdges();\n\n  igl::local_basis(V,F,B1,B2,FN);\n\n  computek();\n\n};\n\n\ntemplate<typename DerivedV, typename DerivedF>\nIGL_INLINE void igl::PolyVectorFieldFinder<DerivedV, DerivedF>::\nprecomputeInteriorEdges()\n{\n  // Flag border edges\n  numInteriorEdges = 0;\n  isBorderEdge.setZero(numE,1);\n  indFullToInterior = -1*Eigen::VectorXi::Ones(numE,1);\n\n  for(unsigned i=0; i<numE; ++i)\n  {\n    if ((E2F(i,0) == -1) || ((E2F(i,1) == -1)))\n      isBorderEdge[i] = 1;\n      else\n      {\n        indFullToInterior[i] = numInteriorEdges;\n        numInteriorEdges++;\n      }\n  }\n\n  E2F_int.resize(numInteriorEdges, 2);\n  indInteriorToFull.setZero(numInteriorEdges,1);\n  int ii = 0;\n  for (int k=0; k<numE; ++k)\n  {\n    if (isBorderEdge[k])\n      continue;\n    E2F_int.row(ii) = E2F.row(k);\n    indInteriorToFull[ii] = k;\n    ii++;\n  }\n\n}\n\n\ntemplate<typename DerivedV, typename DerivedF>\nIGL_INLINE void igl::PolyVectorFieldFinder<DerivedV, DerivedF>::\nminQuadWithKnownMini(const Eigen::SparseMatrix<std::complex<typename DerivedV::Scalar> > &Q,\n                          const Eigen::SparseMatrix<std::complex<typename DerivedV::Scalar> > &f,\n                     const Eigen::VectorXi isConstrained,\n                          const Eigen::Matrix<std::complex<typename DerivedV::Scalar>, Eigen::Dynamic, 1> &xknown,\n                          Eigen::Matrix<std::complex<typename DerivedV::Scalar>, Eigen::Dynamic, 1> &x)\n{\n  int N = Q.rows();\n\n  int nc = xknown.rows();\n  Eigen::VectorXi known; known.setZero(nc,1);\n  Eigen::VectorXi unknown; unknown.setZero(N-nc,1);\n\n  int indk = 0, indu = 0;\n  for (int i = 0; i<N; ++i)\n    if (isConstrained[i])\n    {\n      known[indk] = i;\n      indk++;\n    }\n    else\n    {\n      unknown[indu] = i;\n      indu++;\n    }\n\n  Eigen::SparseMatrix<std::complex<typename DerivedV::Scalar> > Quu, Quk;\n\n  igl::slice(Q,unknown, unknown, Quu);\n  igl::slice(Q,unknown, known, Quk);\n\n\n  std::vector<typename Eigen::Triplet<std::complex<typename DerivedV::Scalar> > > tripletList;\n\n  Eigen::SparseMatrix<std::complex<typename DerivedV::Scalar> > fu(N-nc,1);\n\n  igl::slice(f,unknown, Eigen::VectorXi::Zero(1,1), fu);\n\n  Eigen::SparseMatrix<std::complex<typename DerivedV::Scalar> > rhs = (Quk*xknown).sparseView()+.5*fu;\n\n  Eigen::SparseLU< Eigen::SparseMatrix<std::complex<typename DerivedV::Scalar> > > solver;\n  solver.compute(-Quu);\n  if(solver.info()!=Eigen::Success)\n  {\n    std::cerr<<\"Decomposition failed!\"<<std::endl;\n    return;\n  }\n  Eigen::SparseMatrix<std::complex<typename DerivedV::Scalar> >  b  = solver.solve(rhs);\n  if(solver.info()!=Eigen::Success)\n  {\n    std::cerr<<\"Solving failed!\"<<std::endl;\n    return;\n  }\n\n  indk = 0, indu = 0;\n  x.setZero(N,1);\n  for (int i = 0; i<N; ++i)\n    if (isConstrained[i])\n      x[i] = xknown[indk++];\n    else\n      x[i] = b.coeff(indu++,0);\n\n}\n\n\n\ntemplate<typename DerivedV, typename DerivedF>\nIGL_INLINE bool igl::PolyVectorFieldFinder<DerivedV, DerivedF>::\n                     solve(const Eigen::VectorXi &isConstrained,\n                           const Eigen::Matrix<typename DerivedV::Scalar, Eigen::Dynamic, Eigen::Dynamic> &cfW,\n                           Eigen::Matrix<typename DerivedV::Scalar, Eigen::Dynamic, Eigen::Dynamic> &output)\n{\n\n  // polynomial is of the form:\n  // (-1)^0 z^(2n) +\n  // (-1)^1 c[0]z^(2n-2) +\n  // (-1)^2 c[1]z^(2n-4) +\n  // (-1)^3 c[2]z^(2n-6) +\n  // ... +\n  // (-1)^n c[n-1]\n\n  std::vector<Eigen::Matrix<std::complex<typename DerivedV::Scalar>, Eigen::Dynamic,1> > coeffs(n,Eigen::Matrix<std::complex<typename DerivedV::Scalar>, Eigen::Dynamic,1>::Zero(numF, 1));\n\n  for (int i =0; i<n; ++i)\n  {\n    int degree = 2*(i+1);\n\n    Eigen::Matrix<std::complex<typename DerivedV::Scalar>, Eigen::Dynamic,1> Ck;\n    getGeneralCoeffConstraints(isConstrained,\n                               cfW,\n                               i,\n                               Ck);\n\n    Eigen::SparseMatrix<std::complex<typename DerivedV::Scalar> > DD;\n    computeCoefficientLaplacian(degree, DD);\n    Eigen::SparseMatrix<std::complex<typename DerivedV::Scalar> > f; f.resize(numF,1);\n\n    minQuadWithKnownMini(DD, f, isConstrained, Ck, coeffs[i]);\n  }\n\n  std::vector<Eigen::Matrix<typename DerivedV::Scalar, Eigen::Dynamic, 2> > pv;\n  setFieldFromGeneralCoefficients(coeffs, pv);\n\n  output.setZero(numF,3*n);\n  for (int fi=0; fi<numF; ++fi)\n  {\n    const Eigen::Matrix<typename DerivedV::Scalar, 1, 3> &b1 = B1.row(fi);\n    const Eigen::Matrix<typename DerivedV::Scalar, 1, 3> &b2 = B2.row(fi);\n    for (int i=0; i<n; ++i)\n      output.block(fi,3*i, 1, 3) = pv[i](fi,0)*b1 + pv[i](fi,1)*b2;\n  }\n  return true;\n}\n\ntemplate<typename DerivedV, typename DerivedF>\nIGL_INLINE void igl::PolyVectorFieldFinder<DerivedV, DerivedF>::setFieldFromGeneralCoefficients(const  std::vector<Eigen::Matrix<std::complex<typename DerivedV::Scalar>, Eigen::Dynamic,1> > &coeffs,\n                                                            std::vector<Eigen::Matrix<typename DerivedV::Scalar, Eigen::Dynamic, 2> > &pv)\n{\n  pv.assign(n, Eigen::Matrix<typename DerivedV::Scalar, Eigen::Dynamic, 2>::Zero(numF, 2));\n  for (int i = 0; i <numF; ++i)\n  {\n\n    //    poly coefficients: 1, 0, -Acoeff, 0, Bcoeff\n    //    matlab code from roots (given there are no trailing zeros in the polynomial coefficients)\n    Eigen::Matrix<std::complex<typename DerivedV::Scalar>, Eigen::Dynamic,1> polyCoeff;\n    polyCoeff.setZero(2*n+1,1);\n    polyCoeff[0] = 1.;\n    int sign = 1;\n    for (int k =0; k<n; ++k)\n    {\n      sign = -sign;\n      int degree = 2*(k+1);\n      polyCoeff[degree] = (1.*sign)*coeffs[k](i);\n    }\n\n    Eigen::Matrix<std::complex<typename DerivedV::Scalar>, Eigen::Dynamic,1> roots;\n    igl::polyRoots<std::complex<typename DerivedV::Scalar>, typename DerivedV::Scalar >(polyCoeff,roots);\n\n    Eigen::VectorXi done; done.setZero(2*n,1);\n\n    Eigen::Matrix<std::complex<typename DerivedV::Scalar>, Eigen::Dynamic,1> u(n,1);\n    int ind =0;\n    for (int k=0; k<2*n; ++k)\n    {\n      if (done[k])\n        continue;\n      u[ind] = roots[k];\n      done[k] = 1;\n\n      int mini = -1;\n      double mind = 1e10;\n      for (int l =k+1; l<2*n; ++l)\n      {\n        double dist = abs(roots[l]+u[ind]);\n        if (dist<mind)\n        {\n          mind = dist;\n          mini = l;\n        }\n      }\n      done[mini] = 1;\n      ind ++;\n    }\n    for (int k=0; k<n; ++k)\n    {\n      pv[k](i,0) = real(u[k]);\n      pv[k](i,1) = imag(u[k]);\n    }\n  }\n\n}\n\n\ntemplate<typename DerivedV, typename DerivedF>\nIGL_INLINE void igl::PolyVectorFieldFinder<DerivedV, DerivedF>::computeCoefficientLaplacian(int n, Eigen::SparseMatrix<std::complex<typename DerivedV::Scalar> > &D)\n{\n  std::vector<Eigen::Triplet<std::complex<typename DerivedV::Scalar> > > tripletList;\n\n  // For every non-border edge\n  for (unsigned eid=0; eid<numE; ++eid)\n  {\n    if (!isBorderEdge[eid])\n    {\n      int fid0 = E2F(eid,0);\n      int fid1 = E2F(eid,1);\n\n      tripletList.push_back(Eigen::Triplet<std::complex<typename DerivedV::Scalar> >(fid0,\n                                           fid0,\n                                           std::complex<typename DerivedV::Scalar>(1.)));\n      tripletList.push_back(Eigen::Triplet<std::complex<typename DerivedV::Scalar> >(fid1,\n                                           fid1,\n                                           std::complex<typename DerivedV::Scalar>(1.)));\n      tripletList.push_back(Eigen::Triplet<std::complex<typename DerivedV::Scalar> >(fid0,\n                                           fid1,\n                                                                                     -1.*std::polar(1.,-1.*n*K[eid])));\n      tripletList.push_back(Eigen::Triplet<std::complex<typename DerivedV::Scalar> >(fid1,\n                                           fid0,\n                                                                                     -1.*std::polar(1.,1.*n*K[eid])));\n\n    }\n  }\n  D.resize(numF,numF);\n  D.setFromTriplets(tripletList.begin(), tripletList.end());\n\n\n}\n\ntemplate<typename DerivedV, typename DerivedF>\nIGL_INLINE void igl::PolyVectorFieldFinder<DerivedV, DerivedF>::getGeneralCoeffConstraints(const Eigen::VectorXi &isConstrained,\n                                                       const Eigen::Matrix<typename DerivedV::Scalar, Eigen::Dynamic, Eigen::Dynamic> &cfW,\n                                                       int k,\n                                                       Eigen::Matrix<std::complex<typename DerivedV::Scalar>, Eigen::Dynamic,1> &Ck)\n{\n  int numConstrained = isConstrained.sum();\n  Ck.resize(numConstrained,1);\n  int n = cfW.cols()/3;\n\n  Eigen::MatrixXi allCombs;\n  {\n    Eigen::VectorXi V = igl::LinSpaced<Eigen::VectorXi >(n,0,n-1);\n    igl::nchoosek(V,k+1,allCombs);\n  }\n\n\n  int ind = 0;\n  for (int fi = 0; fi <numF; ++fi)\n  {\n    const Eigen::Matrix<typename DerivedV::Scalar, 1, 3> &b1 = B1.row(fi);\n    const Eigen::Matrix<typename DerivedV::Scalar, 1, 3> &b2 = B2.row(fi);\n    if(isConstrained[fi])\n    {\n      std::complex<typename DerivedV::Scalar> ck(0);\n\n      for (int j = 0; j < allCombs.rows(); ++j)\n      {\n        std::complex<typename DerivedV::Scalar> tk(1.);\n        //collect products\n        for (int i = 0; i < allCombs.cols(); ++i)\n        {\n          int index = allCombs(j,i);\n\n          const Eigen::Matrix<typename DerivedV::Scalar, 1, 3> &w = cfW.block(fi,3*index,1,3);\n          typename DerivedV::Scalar w0 = w.dot(b1);\n          typename DerivedV::Scalar w1 = w.dot(b2);\n          std::complex<typename DerivedV::Scalar> u(w0,w1);\n          tk*= u*u;\n        }\n        //collect sum\n        ck += tk;\n      }\n      Ck(ind) = ck;\n      ind ++;\n    }\n  }\n\n\n}\n\ntemplate<typename DerivedV, typename DerivedF>\nIGL_INLINE void igl::PolyVectorFieldFinder<DerivedV, DerivedF>::computek()\n{\n  K.setZero(numE);\n  // For every non-border edge\n  for (unsigned eid=0; eid<numE; ++eid)\n  {\n    if (!isBorderEdge[eid])\n    {\n      int fid0 = E2F(eid,0);\n      int fid1 = E2F(eid,1);\n\n      Eigen::Matrix<typename DerivedV::Scalar, 1, 3> N0 = FN.row(fid0);\n      Eigen::Matrix<typename DerivedV::Scalar, 1, 3> N1 = FN.row(fid1);\n\n      // find common edge on triangle 0 and 1\n      int fid0_vc = -1;\n      int fid1_vc = -1;\n      for (unsigned i=0;i<3;++i)\n      {\n        if (F2E(fid0,i) == eid)\n          fid0_vc = i;\n        if (F2E(fid1,i) == eid)\n          fid1_vc = i;\n      }\n      assert(fid0_vc != -1);\n      assert(fid1_vc != -1);\n\n      Eigen::Matrix<typename DerivedV::Scalar, 1, 3> common_edge = V.row(F(fid0,(fid0_vc+1)%3)) - V.row(F(fid0,fid0_vc));\n      common_edge.normalize();\n\n      // Map the two triangles in a new space where the common edge is the x axis and the N0 the z axis\n      Eigen::Matrix<typename DerivedV::Scalar, 3, 3> P;\n      Eigen::Matrix<typename DerivedV::Scalar, 1, 3> o = V.row(F(fid0,fid0_vc));\n      Eigen::Matrix<typename DerivedV::Scalar, 1, 3> tmp = -N0.cross(common_edge);\n      P << common_edge, tmp, N0;\n//      P.transposeInPlace();\n\n\n      Eigen::Matrix<typename DerivedV::Scalar, 3, 3> V0;\n      V0.row(0) = V.row(F(fid0,0)) -o;\n      V0.row(1) = V.row(F(fid0,1)) -o;\n      V0.row(2) = V.row(F(fid0,2)) -o;\n\n      V0 = (P*V0.transpose()).transpose();\n\n//      assert(V0(0,2) < 1e-10);\n//      assert(V0(1,2) < 1e-10);\n//      assert(V0(2,2) < 1e-10);\n\n      Eigen::Matrix<typename DerivedV::Scalar, 3, 3> V1;\n      V1.row(0) = V.row(F(fid1,0)) -o;\n      V1.row(1) = V.row(F(fid1,1)) -o;\n      V1.row(2) = V.row(F(fid1,2)) -o;\n      V1 = (P*V1.transpose()).transpose();\n\n//      assert(V1(fid1_vc,2) < 10e-10);\n//      assert(V1((fid1_vc+1)%3,2) < 10e-10);\n\n      // compute rotation R such that R * N1 = N0\n      // i.e. map both triangles to the same plane\n      double alpha = -atan2(V1((fid1_vc+2)%3,2),V1((fid1_vc+2)%3,1));\n\n      Eigen::Matrix<typename DerivedV::Scalar, 3, 3> R;\n      R << 1,          0,            0,\n      0, cos(alpha), -sin(alpha) ,\n      0, sin(alpha),  cos(alpha);\n      V1 = (R*V1.transpose()).transpose();\n\n//      assert(V1(0,2) < 1e-10);\n//      assert(V1(1,2) < 1e-10);\n//      assert(V1(2,2) < 1e-10);\n\n      // measure the angle between the reference frames\n      // k_ij is the angle between the triangle on the left and the one on the right\n      Eigen::Matrix<typename DerivedV::Scalar, 1, 3> ref0 = V0.row(1) - V0.row(0);\n      Eigen::Matrix<typename DerivedV::Scalar, 1, 3> ref1 = V1.row(1) - V1.row(0);\n\n      ref0.normalize();\n      ref1.normalize();\n\n      double ktemp = atan2(ref1(1),ref1(0)) - atan2(ref0(1),ref0(0));\n\n      // just to be sure, rotate ref0 using angle ktemp...\n      Eigen::Matrix<typename DerivedV::Scalar, 2, 2> R2;\n      R2 << cos(ktemp), -sin(ktemp), sin(ktemp), cos(ktemp);\n\n      Eigen::Matrix<typename DerivedV::Scalar, 1, 2> tmp1 = R2*(ref0.head(2)).transpose();\n\n//      assert(tmp1(0) - ref1(0) < 1e-10);\n//      assert(tmp1(1) - ref1(1) < 1e-10);\n\n      K[eid] = ktemp;\n    }\n  }\n\n}\n\n\nIGL_INLINE void igl::n_polyvector(const Eigen::MatrixXd &V,\n                             const Eigen::MatrixXi &F,\n                             const Eigen::VectorXi& b,\n                             const Eigen::MatrixXd& bc,\n                             Eigen::MatrixXd &output)\n{\n  Eigen::VectorXi isConstrained = Eigen::VectorXi::Constant(F.rows(),0);\n  Eigen::MatrixXd cfW = Eigen::MatrixXd::Constant(F.rows(),bc.cols(),0);\n\n  for(unsigned i=0; i<b.size();++i)\n  {\n    isConstrained(b(i)) = 1;\n    cfW.row(b(i)) << bc.row(i);\n  }\n  if (b.size() == F.rows())\n  {\n    output = cfW;\n    return;\n  }\n\n  int n = cfW.cols()/3;\n  igl::PolyVectorFieldFinder<Eigen::MatrixXd, Eigen::MatrixXi> pvff(V,F,n);\n  pvff.solve(isConstrained, cfW, output);\n}\n\n\n#ifdef IGL_STATIC_LIBRARY\n// Explicit template instantiation\n#endif\n", "meta": {"hexsha": "80bd12945a6d8ff465f66a06f2760a4f72701ab9", "size": 17173, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "include/igl/n_polyvector.cpp", "max_stars_repo_name": "rushmash/libwetcloth", "max_stars_repo_head_hexsha": "24f16481c68952c3d2a91acd6e3b74eb091b66bc", "max_stars_repo_licenses": ["BSD-3-Clause-Clear"], "max_stars_count": 199.0, "max_stars_repo_stars_event_min_datetime": "2018-02-26T20:56:21.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-16T06:09:52.000Z", "max_issues_repo_path": "include/igl/n_polyvector.cpp", "max_issues_repo_name": "rushmash/libwetcloth", "max_issues_repo_head_hexsha": "24f16481c68952c3d2a91acd6e3b74eb091b66bc", "max_issues_repo_licenses": ["BSD-3-Clause-Clear"], "max_issues_count": 10.0, "max_issues_repo_issues_event_min_datetime": "2018-03-20T02:49:58.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-29T01:13:22.000Z", "max_forks_repo_path": "include/igl/n_polyvector.cpp", "max_forks_repo_name": "rushmash/libwetcloth", "max_forks_repo_head_hexsha": "24f16481c68952c3d2a91acd6e3b74eb091b66bc", "max_forks_repo_licenses": ["BSD-3-Clause-Clear"], "max_forks_count": 41.0, "max_forks_repo_forks_event_min_datetime": "2018-02-28T01:33:37.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-29T16:06:19.000Z", "avg_line_length": 33.0886319846, "max_line_length": 198, "alphanum_fraction": 0.5816106679, "num_tokens": 4939, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6513548782017745, "lm_q2_score": 0.48438008427698437, "lm_q1q2_score": 0.3155033307976004}}
{"text": "//==================================================================================================\n/*!\n  @file\n\n  @copyright 2016 NumScale SAS\n\n  Distributed under the Boost Software License, Version 1.0.\n  (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\n*/\n//==================================================================================================\n#ifndef BOOST_SIMD_ARCH_X86_SSE2_SIMD_FUNCTION_MAKE_HPP_INCLUDED\n#define BOOST_SIMD_ARCH_X86_SSE2_SIMD_FUNCTION_MAKE_HPP_INCLUDED\n\n#include <boost/simd/detail/overload.hpp>\n\nnamespace boost { namespace simd { namespace ext\n{\n  namespace bd = ::boost::dispatch;\n  namespace bs = ::boost::simd;\n\n  //------------------------------------------------------------------------------------------------\n  // make a pack of double\n  BOOST_DISPATCH_OVERLOAD ( make_\n                          , (typename Target, typename... Values)\n                          , bs::sse2_\n                          , bd::target_<bs::pack_<bd::double_<Target>,bs::sse_>>\n                          , bd::scalar_<bd::unspecified_<Values>>...\n                          )\n  {\n    using target_t  = typename Target::type;\n    using storage_t = typename target_t::storage_type;\n\n    static_assert ( sizeof...(Values) == 2\n                  , \"boost::simd::make - Invalid number of parameters\"\n                  );\n\n    BOOST_FORCEINLINE target_t operator()(Target const&, Values const&... vs) const BOOST_NOEXCEPT\n    {\n      return _mm_setr_pd(static_cast<typename target_t::value_type>(vs)...);\n    }\n  };\n\n  //------------------------------------------------------------------------------------------------\n  // make a pack of int64\n  BOOST_DISPATCH_OVERLOAD ( make_\n                          , (typename Target, typename V0, typename V1)\n                          , bs::sse2_\n                          , bd::target_<bs::pack_<bd::ints64_<Target>,bs::sse_>>\n                          , bd::scalar_<bd::unspecified_<V0>>\n                          , bd::scalar_<bd::unspecified_<V1>>\n                          )\n  {\n    using target_t  = typename Target::type;\n\n    BOOST_FORCEINLINE\n    target_t operator()(Target const&, V0 const& v0, V1 const& v1) const BOOST_NOEXCEPT\n    {\n      return _mm_set_epi64x(v1, v0);\n    }\n  };\n\n  //------------------------------------------------------------------------------------------------\n  // make a pack of int32\n  BOOST_DISPATCH_OVERLOAD ( make_\n                          , (typename Target, typename... Values)\n                          , bs::sse2_\n                          , bd::target_<bs::pack_<bd::ints32_<Target>,bs::sse_>>\n                          , bd::scalar_<bd::unspecified_<Values>>...\n                          )\n  {\n    using target_t  = typename Target::type;\n\n    static_assert ( sizeof...(Values) == 4\n                  , \"boost::simd::make - Invalid number of parameters\"\n                  );\n\n    BOOST_FORCEINLINE target_t operator()(Target const&, Values const&... vs) const BOOST_NOEXCEPT\n    {\n      return _mm_setr_epi32(static_cast<typename target_t::value_type>(vs)...);\n    }\n  };\n\n  //------------------------------------------------------------------------------------------------\n  // make a pack of int16\n  BOOST_DISPATCH_OVERLOAD ( make_\n                          , (typename Target, typename... Values)\n                          , bs::sse2_\n                          , bd::target_<bs::pack_<bd::ints16_<Target>,bs::sse_>>\n                          , bd::scalar_<bd::unspecified_<Values>>...\n                          )\n  {\n    using target_t  = typename Target::type;\n\n    static_assert ( sizeof...(Values) == 8\n                  , \"boost::simd::make - Invalid number of parameters\"\n                  );\n\n    BOOST_FORCEINLINE target_t operator()(Target const&, Values const&... vs) const BOOST_NOEXCEPT\n    {\n      return _mm_setr_epi16(static_cast<typename target_t::value_type>(vs)...);\n    }\n  };\n\n  //------------------------------------------------------------------------------------------------\n  // make a pack of int8\n  BOOST_DISPATCH_OVERLOAD ( make_\n                          , (typename Target, typename... Values)\n                          , bs::sse2_\n                          , bd::target_<bs::pack_<bd::ints8_<Target>,bs::sse_>>\n                          , bd::scalar_<bd::unspecified_<Values>>...\n                          )\n  {\n    using target_t  = typename Target::type;\n\n    static_assert ( sizeof...(Values) == 16\n                  , \"boost::simd::make - Invalid number of parameters\"\n                  );\n\n    BOOST_FORCEINLINE target_t operator()(Target const&, Values const&... vs) const BOOST_NOEXCEPT\n    {\n      return _mm_setr_epi8(static_cast<typename target_t::value_type>(vs)...);\n    }\n  };\n} } }\n\n#endif\n", "meta": {"hexsha": "e08ddc897aeae96eab8a6765cf649a44d10929c7", "size": 4773, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/simd/arch/x86/sse2/simd/function/make.hpp", "max_stars_repo_name": "yaeldarmon/boost.simd", "max_stars_repo_head_hexsha": "561316cc54bdc6353ca78f3b6d7e9120acd11144", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/boost/simd/arch/x86/sse2/simd/function/make.hpp", "max_issues_repo_name": "yaeldarmon/boost.simd", "max_issues_repo_head_hexsha": "561316cc54bdc6353ca78f3b6d7e9120acd11144", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/boost/simd/arch/x86/sse2/simd/function/make.hpp", "max_forks_repo_name": "yaeldarmon/boost.simd", "max_forks_repo_head_hexsha": "561316cc54bdc6353ca78f3b6d7e9120acd11144", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.5826771654, "max_line_length": 100, "alphanum_fraction": 0.4670018856, "num_tokens": 968, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6513548782017745, "lm_q2_score": 0.48438008427698437, "lm_q1q2_score": 0.3155033307976004}}
{"text": "#include <iostream>\n#include <vector>\n#include <cassert>\n#include <cstring>\n#include <limits>\n#include <mpi.h>\n//#include <Eigen/Eigenvalues>\n\nenum KernelType {CubicSpline = 0, WendlandC2 = 1, WendlandC4 = 2};\n\n#include \"particle_simulator.hpp\"\n#include \"hdr_time.hpp\"\n#include \"hdr_run.hpp\"\n#ifdef USE_INTRINSICS\n#include \"vector_x86.hpp\"\n#endif\n#include \"hdr_dimension.hpp\"\n#include \"hdr_kernel.hpp\"\n#include \"hdr_sph.hpp\"\n#include \"hdr_hgas.hpp\"\n#include \"hdr_bhns.hpp\"\n\nclass SPHAnalysis : public HelmholtzGas {\npublic:\n    SPHAnalysis() {\n        this->id    = 0;\n        this->istar = 0;\n        this->mass  = 0.;\n        this->pos   = 0.;\n        this->vel   = 0.;\n        this->uene  = 0.;\n        this->alph  = 0.;\n        this->alphu = 0.;\n        this->ksr   = 0.;\n        for(PS::S32 k = 0; k < NR::NumberOfNucleon; k++) {\n            this->cmps[k] = 0.;\n        }        \n    }\n\n    PS::F64 calcRadialVelocity() {\n        PS::F64 r2 = this->pos * this->pos;\n        PS::F64 rv = this->pos * this->vel;\n        return (rv / sqrt(r2));\n    }\n\n    void readAscii(FILE * fp) {\n        fscanf(fp, \"%lld%lld%lf\", &this->id, &this->istar, &this->mass);      //  3\n        fscanf(fp, \"%lf%lf%lf\", &this->pos[0], &this->pos[1], &this->pos[2]); //  6\n        fscanf(fp, \"%lf%lf%lf\", &this->vel[0], &this->vel[1], &this->vel[2]); //  9\n        fscanf(fp, \"%lf%lf%lf\", &this->acc[0], &this->acc[1], &this->acc[2]); // 12\n        fscanf(fp, \"%lf%lf%lf\", &this->uene, &this->alph, &this->alphu);      // 15\n        fscanf(fp, \"%lf%lf%6d\", &this->dens, &this->ksr,  &this->np);         // 18\n        fscanf(fp, \"%lf%lf%lf\", &this->vsnd, &this->pres, &this->temp);       // 21\n        fscanf(fp, \"%lf%lf%lf\", &this->divv, &this->rotv, &this->bswt);       // 24\n        fscanf(fp, \"%lf%lf%lf\", &this->pot,  &this->abar, &this->zbar);       // 27\n        fscanf(fp, \"%lf\",       &this->enuc);                                 // 28\n        fscanf(fp, \"%lf%lf%lf\", &this->vsmx, &this->udot, &this->dnuc);       // 31\n        for(PS::S32 k = 0; k < NuclearReaction::NumberOfNucleon; k++) {       // 32 -- 44\n            fscanf(fp, \"%lf\", &this->cmps[k]);\n        }\n        fscanf(fp, \"%lf\", &this->pot3);\n        fscanf(fp, \"%lf%lf%lf\", &this->tempmax[0], &this->tempmax[1], &this->tempmax[2]);\n        fscanf(fp, \"%lf\", &this->entr);\n    }\n\n};\n\nclass Shell {\npublic:\n    PS::S64 nump; // The number of particles in the shell\n    PS::F64 mass; // The total mass in the shell\n    PS::F64 ener; // The total internal energy in the shell\n    PS::F64 rvel; // Radial velocity in the shell\n    NR::Nucleon mele;\n\n    Shell() {\n        this->nump = 0;\n        this->mass = 0.;\n        this->ener = 0.;\n        this->rvel = 0.;\n        for(PS::S64 k = 0; k < NR::NumberOfNucleon; k++) {\n            this->mele[k] = 0.;\n        }\n    }\n\n    void increment(SPHAnalysis & sph) {\n        this->nump += 1;\n        this->mass += sph.mass;\n        this->ener += sph.mass * sph.uene;\n        this->rvel += sph.calcRadialVelocity();\n        for(PS::S64 k = 0; k < NR::NumberOfNucleon; k++) {\n            this->mele[k] += sph.mass * sph.cmps[k];\n        }\n    }\n\n    void reduceAddition(Shell sloc) {\n        this->nump = PS::Comm::getSum(sloc.nump);\n        this->mass = PS::Comm::getSum(sloc.mass);\n        this->ener = PS::Comm::getSum(sloc.ener);\n        this->rvel = PS::Comm::getSum(sloc.rvel);\n        for(PS::S64 k = 0; k < NR::NumberOfNucleon; k++) {\n            this->mele[k] = PS::Comm::getSum(sloc.mele[k]);\n        }\n    }\n\n};\n\ntemplate <class Tsph>\nvoid sphericalizeWhiteDwarf(PS::F64 rmax,\n                            PS::F64 drad,\n                            PS::F64vec axis,\n                            PS::F64    thinv,\n                            char * ofile,\n                            Tsph & sph) {\n\n    PS::F64 critcth = cos(M_PI / thinv);\n\n    PS::S64 nbin = (PS::S64)(rmax / drad) + 1;\n    Shell * sloc = (Shell *)malloc(sizeof(Shell) * nbin);\n    \n    for(PS::S64 i = 0; i < sph.getNumberOfParticleLocal(); i++) {\n        sph[i].pos = sph[i].pos;\n        sph[i].vel = sph[i].vel;\n        PS::F64 rad1 = sqrt(sph[i].pos * sph[i].pos);\n        PS::S64 ibin = (PS::S64)(rad1 / drad);\n        if(ibin >= nbin) {\n            continue;\n        }\n        PS::F64 cth  = (sph[i].pos * axis) / rad1;\n        if(cth < critcth) {\n            continue;\n        }\n        ///////////// Ad hoc method //////////////\n        if(sph[i].istar == 0 && sph[i].cmps[1] > 0.2 && rad1 < 3e10) {\n            for(PS::S64 k = 0; k < NR::NumberOfNucleon; k++) {\n                if(k != 12) {\n                    sph[i].cmps[k] = 0.;\n                } else {\n                    sph[i].cmps[k] = 1.;\n                }\n            }\n            //continue;\n        }\n        //////////////////////////////////////////\n        sloc[ibin].increment(sph[i]);\n    }\n\n    Shell * sglb = (Shell *)malloc(sizeof(Shell) * nbin);\n    for(PS::S64 ibin = 0; ibin < nbin; ibin++) {\n        sglb[ibin].reduceAddition(sloc[ibin]);\n    }\n    \n    if(PS::Comm::getRank() == 0) {\n        PS::S64 nshl = 0;\n        PS::F64 mass = 0.;\n        PS::F64 ener = 0.;\n        PS::F64 rvel = 0.;\n        PS::F64 rad0 = 0.;\n        PS::F64 menc = 0.;\n        NR::Nucleon mele;\n        FILE * fp = fopen(ofile, \"w\");\n        for(PS::S64 ibin = 0; ibin < nbin; ibin++) {\n            nshl += sglb[ibin].nump;\n            mass += sglb[ibin].mass;\n            rvel += sglb[ibin].rvel;\n            for(PS::S64 k = 0; k < NR::NumberOfNucleon; k++) {\n                mele[k] += sglb[ibin].mele[k];\n            }\n            if(nshl < 10000 && ibin != nbin - 1) {\n            //if(nshl < 1000 && ibin != nbin - 1) {\n            //if(nshl < 100 && ibin != nbin - 1) {\n            //if(nshl < 10 && ibin != nbin - 1) {\n                continue;\n            }\n\n            PS::F64 rad1   = drad * (ibin + 1);\n            rvel  = rvel / (PS::S64)nshl;\n            NR::Nucleon cmps;\n            for(PS::S64 k = 0; k < NR::NumberOfNucleon; k++) {\n                cmps[k] = mele[k] / mass;\n            }\n\n            fprintf(fp, \"%+e %+e\", \n                    rad1, rvel);\n            for(PS::S64 k = 0; k < NR::NumberOfNucleon; k++) {\n                fprintf(fp, \" %+e\", cmps[k]);\n            }\n            fprintf(fp, \"\\n\");\n            \n            nshl = 0;\n            mass = 0.;\n            rvel = 0.;\n            for(PS::S64 k = 0; k < NR::NumberOfNucleon; k++) {\n                mele[k] = 0.;\n            }\n            rad0 = rad1;\n        }\n        fclose(fp);\n    }\n\n    free(sloc);\n    free(sglb);\n                \n}\n\nint main(int argc, char ** argv) {\n    PS::Initialize(argc, argv);\n\n    PS::ParticleSystem<SPHAnalysis> sph;\n    sph.initialize();\n    sph.createParticle(0);\n    sph.setNumberOfParticleLocal(0);\n\n    char idir[1024], odir[1024];\n    PS::F64 rmax, drad, thinv;\n    PS::F64vec axis;\n    PS::S64 ibgn, iend;\n    FILE * fp = fopen(argv[1], \"r\");\n    fscanf(fp, \"%s\", idir);\n    fscanf(fp, \"%s\", odir);\n    fscanf(fp, \"%lf%lf%lf\", &rmax, &drad, &thinv);\n    fscanf(fp, \"%lf%lf%lf\", &axis[0], &axis[1], &axis[2]);\n    fscanf(fp, \"%lld%lld\", &ibgn, &iend);\n    fclose(fp);\n\n    {\n        PS::F64 vlen = sqrt(axis * axis);\n        axis = (1. / vlen) * axis;\n    }\n\n    for(PS::S64 itime = ibgn; itime <= iend; itime++) {        \n        char tfile[1024];\n        FILE *fp = NULL;\n        PS::S64 tdir = 0;\n        for(PS::S64 iidir = 0; iidir < 100; iidir++) {\n            sprintf(tfile, \"%s/t%02d/sph_t%04d_p%06d_i%06d.dat\", idir, iidir, itime,\n                    PS::Comm::getNumberOfProc(), 0);\n            fp = fopen(tfile, \"r\");\n            if(fp != NULL) {\n                tdir = iidir;\n                break;\n            }\n        }\n        if(fp == NULL) {\n            fprintf(stderr, \"%s is not found.\\n\", tfile);\n            continue;\n        }\n        fclose(fp);\n        \n        char sfile[1024];\n        sprintf(sfile, \"%s/t%02d/sph_t%04d\", idir, tdir, itime);\n        sph.readParticleAscii(sfile, \"%s_p%06d_i%06d.dat\");\n\n        char ofile[1024];\n        sprintf(ofile, \"%s/poly.dat\", odir);\n        sphericalizeWhiteDwarf(rmax, drad, axis, thinv, ofile, sph);\n\n    }\n\n    PS::Finalize();\n\n    return 0;\n}\n", "meta": {"hexsha": "231011a18bfbd9adea466f04bb9249268770082d", "size": 8175, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tool.hgas/sphericalizev/main.cpp", "max_stars_repo_name": "atrtnkw/sph", "max_stars_repo_head_hexsha": "c6bb3d7fd18f57c51fe60197706741e5a26e6ce4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2018-07-11T00:43:01.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-11T13:41:50.000Z", "max_issues_repo_path": "tool.hgas/sphericalizev/main.cpp", "max_issues_repo_name": "atrtnkw/sph", "max_issues_repo_head_hexsha": "c6bb3d7fd18f57c51fe60197706741e5a26e6ce4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tool.hgas/sphericalizev/main.cpp", "max_forks_repo_name": "atrtnkw/sph", "max_forks_repo_head_hexsha": "c6bb3d7fd18f57c51fe60197706741e5a26e6ce4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-01-06T14:22:25.000Z", "max_forks_repo_forks_event_max_datetime": "2020-01-06T14:22:25.000Z", "avg_line_length": 30.9659090909, "max_line_length": 89, "alphanum_fraction": 0.4556574924, "num_tokens": 2676, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6513548646660542, "lm_q2_score": 0.4843800842769844, "lm_q1q2_score": 0.3155033242411671}}
{"text": "/*\n * PseudoMeasurements.hpp\n *\n *  Created on: 02.08.2018\n *      Author: tomlucas\n */\n\n#ifndef ESTIMATORS_PSEUDOMEASUREMENTS_HPP_\n#define ESTIMATORS_PSEUDOMEASUREMENTS_HPP_\n\n#include <Eigen/Core>\n\n#include <glog/logging.h>\n#include <ceres/ceres.h>\n\n#include <Eigen_Utils.hpp>\n#include \"BatchEstimator.hpp\"\n\n\n/**\n * Setup a basic pseudo measurement so that other parts of the programm know its  dimensions\n */\n#define SETUP_PSEUDO_MEASUREMENT(MEASURE_DIM)  \\\n\tstatic constexpr int measure_dim=MEASURE_DIM; \\\n\tstatic constexpr int state_dim=estimator_type::MODEL_TYPE::outer_size; \\\n\ttemplate<typename T>\t\t\t\t\t\t\t\t\t\t\\\n\tusing MEASURE_TYPE=Eigen::Matrix<T,measure_dim,1>;\n\n/**\n * Setup a pseudo measurement which contains a manifold with different inner size\n */\n#define SETUP_PSEUDO_MEASUREMENT_WITH_MANIFOLD(MEASURE_DIM,MANIFOLD_DIM)  \\\n\tSETUP_PSEUDO_MEASUREMENT(MEASURE_DIM)   \\\n\tstatic constexpr int manifold_dim=MANIFOLD_DIM;   \\\n\ttemplate<typename T>\t\t\t\t\t\t\t\t\t\t\\\n\tusing MANIFOLD_TYPE=Eigen::Matrix<T,manifold_dim,1>;\n\n/**\n * Adds the necesarry function so that the UKF accepts the knowledge (for knowledge where alignment is not required)\n */\n#define ADD_UKF_FUNCTION_PASSER  \\\ntemplate<typename T>\t\t\\\nMEASURE_TYPE<T> operator()(const Eigen::Matrix<T,state_dim,1> &state,const ALIGNMENT_TYPE<T> &alignment, void * prior) const {\t\t\\\n\t\t\treturn this->operator()(state,prior);     \\\n\t\t}\n\nnamespace zavi\n::estimator::pseudo_measurement {\n\n\t/**\n\t * Struct to contain relevant data for a function as Prior Knowledge\n\t */\n\ttemplate<typename ukf_type>\n\tstruct FunctionMeasurement {\n\t\tFunctionMeasurement(const zavi::eigen_util::FuncCaller &function,std::shared_ptr<ukf_type> estimator ):function(function),ukf(estimator) {}\n\t\tzavi::eigen_util::FuncCaller function;\n\t\tstd::shared_ptr<ukf_type> ukf;\n\t};\n\t/**\n\t * pseudo measurement to return the position\n\t * @param state  the current estimated state\n\t * @param prior a maybe usefull prior\n\t * @return an expected position at state\n\t */\n\tinline Eigen::Matrix<double, 3, 1> position_measurement(const Eigen::Matrix<double,9,1> &state, void *prior) {\n\t\treturn state.block(0,0,3,1);\n\t}\n\n\n\t/**\n\t * Functor to calculate the shortest distance between a function and a point\n\t */\n\ttemplate <typename functor>\n\tclass DistanceFunctor {\n\tpublic:\n\t\t~DistanceFunctor() {}\n\t\tDistanceFunctor(functor & function):function(function),x(0),y(0),z(0) {};\n\t\ttemplate<typename T>\n\t\tbool operator()(const T * const time,T* residual) const {\n\t\t\tT func[3];\n\t\t\tfunction(time,(T* )func);\n\t\t\tresidual[0]=pow(x-func[0],2)+pow(y-func[1],2)+pow(z-func[2],2);\n\n\t\t\treturn true;\n\t\t}\n\n\tpublic:\n\t\t/**\n\t\t * Set the point to which to calculate the distance\n\t\t * @param point  point with x y z coordinates\n\t\t */\n\t\tvoid setPoint(const Eigen::Matrix<double,3,1> & point) {\n\t\t\tx=point(0,0);\n\t\t\ty=point(1,0);\n\t\t\tz=point(2,0);\n\t\t}\n\n\t\tfunctor function;     // evaluation function\n\tprivate:\n\n\t\tdouble x,y,z;// point coordinates\n\t};\n\n\t/**\n\t * Struct to contain relevant data for a function as Prior Knowledge\n\t */\n\ttemplate <typename functor,typename cov_type,typename ukf_type>\n\tstruct DistanceMeasurement {\n\t\tDistanceMeasurement(functor &function,const cov_type &cov, std::shared_ptr<ukf_type> estimator ):function(function),cov(cov),ukf(estimator) {}\n\t\tDistanceFunctor<functor> function;\n\t\tcov_type cov;\n\t\tstd::shared_ptr<ukf_type> ukf;\n\t};\n\t/**\n\t * pseudo measurement to return the distance to prior function\n\t * @param state  the current estimated state\n\t * @param prior a maybe usefull prior\n\t * @return an expected distance to function at state hard constriaint so it is always zero\n\t */\n\ttemplate <typename functor,typename ukf_type>\n\tEigen::Matrix<double, 3, 1> distance_measurement(const Eigen::Matrix<double,9,1> &state, void * prior) {\n\t\tDistanceMeasurement<functor,Eigen::Matrix3d,ukf_type> * container= static_cast<DistanceMeasurement<functor,Eigen::Matrix3d,ukf_type> *>(prior);\n\t\tcontainer->function.function.give_real=false;     // tell function that the solver is active\n\t\t// The variable to solve for with its initial value.\n\t\tstatic double initial_x = 0;\n\t\tdouble x = initial_x;\n\t\tcontainer->function.setPoint(state.block(0,0,3,1));\n\t\t// Build the problem.\n\t\t// Set up the only cost function (also known as residual). This uses\n\t\t// auto-differentiation to obtain the derivative (jacobian).\n\t\tceres::CostFunction* cost_function =\n\t\tnew ceres::AutoDiffCostFunction<DistanceFunctor<functor>, 1, 1>(new DistanceFunctor<functor>(container->function));\n\t\tceres::Problem problem;\n\n\t\tproblem.AddResidualBlock(cost_function, NULL, &x);\n\n\t\t// Run the solver!\n\t\tceres:: Solver::Options options;\n\t\toptions.linear_solver_type = ceres::DENSE_QR;\n\t\toptions.minimizer_progress_to_stdout = false;\n\t\toptions.max_num_line_search_step_size_iterations=10;\n\t\tceres::Solver::Summary summary;\n\t\tceres::Solve(options, &problem, &summary);\n\t\t//std::cout << summary.BriefReport() << std::endl;\n\t\tinitial_x=x;\n\t\tdouble result[3];\n\t\tcontainer->function.function(&x,(double *)result);\n\t\tEigen::Matrix<double,3,1> returner;\n\t\treturner(0,0)=result[0]-state(0,0);\n\t\treturner(1,0)=result[1]-state(1,0);\n\t\treturner(2,0)=result[2]-state(2,0);\n\n\t\tcontainer->function.function.give_real=true;// tell function that the solver is finished\n\t\treturn returner;\n\n\t}\n\t/**\n\t * pseudo measurement to return the distance to prior function\n\t * @param state  the current estimated state\n\t * @param prior a maybe usefull prior\n\t * @return an expected distance to function at state hard constriaint so it is always zero\n\t */\n\ttemplate <typename functor,typename ukf_type>\n\tEigen::Matrix<double, 1, 1> distance_measurement_single(const Eigen::Matrix<double,9,1> &state, void * prior) {\n\t\tDistanceMeasurement<functor,Eigen::Matrix<double,1,1>,ukf_type> * container= static_cast<DistanceMeasurement<functor,Eigen::Matrix<double,1,1>,ukf_type> *>(prior);\n\t\tcontainer->function.function.give_real=false;     // tell function that the solver is active\n\t\t// The variable to solve for with its initial value.\n\t\tstatic double initial_x = 0;\n\t\tdouble x = initial_x;\n\t\tcontainer->function.setPoint(state.block(0,0,3,1));\n\t\t// Build the problem.\n\t\t// Set up the only cost function (also known as residual). This uses\n\t\t// auto-differentiation to obtain the derivative (jacobian).\n\t\tceres::CostFunction* cost_function =\n\t\tnew ceres::AutoDiffCostFunction<DistanceFunctor<functor>, 1, 1>(new DistanceFunctor<functor>(container->function));\n\t\tceres::Problem problem;\n\n\t\tproblem.AddResidualBlock(cost_function, NULL, &x);\n\n\t\t// Run the solver!\n\t\tceres:: Solver::Options options;\n\t\toptions.linear_solver_type = ceres::DENSE_QR;\n\t\toptions.minimizer_progress_to_stdout = false;\n\t\toptions.max_num_line_search_step_size_iterations=10;\n\t\tceres::Solver::Summary summary;\n\t\tceres::Solve(options, &problem, &summary);\n\t\t//std::cout << summary.BriefReport() << std::endl;\n\t\tinitial_x=x;\n\t\tdouble result[1];\n\t\tcontainer->function(&x,(double *)result);\n\t\tEigen::Matrix<double,1,1> returner;\n\t\treturner(0,0)=result[0];\n\n\t\tcontainer->function.function.give_real=true;// tell function that the solver is finished\n\t\treturn returner;\n\n\t}\n\n\t/**\n\t *  a pseudo distance measurement with a given function as ground truth\n\t * @param plug  the imu plugin\n\t * @param estimator  the function measurement struct\n\t * @param time  time current time stamp\n\t */\n\ttemplate<typename functor,typename ukf_type>\n\tvoid pseudoDistanceFunctionMeasurement(plugin::SensorPlugin * plug,\n\t\t\tvoid* estimator, double time) {\n\t\tstatic double last_time=time-0.00001;\n\t\tDistanceMeasurement<functor,Eigen::Matrix3d,ukf_type> * container= static_cast<DistanceMeasurement<functor,Eigen::Matrix3d,ukf_type> *>(estimator);\n\t\t//plugin::IMU_Plugin *imu = static_cast<plugin::IMU_Plugin*>(plug);\n\t\tEigen::Matrix<double,3,1> zeros=Eigen::Matrix<double,3,1>::Zero();\n\t\tcontainer->ukf->measurementStep(zeros,time-last_time,distance_measurement<functor>,container->cov,container);\n\t\tlast_time=time;\n\t}\n\n\t/**\n\t *  a pseudo distance measurement with a given function as ground truth\n\t * @param plug  the imu plugin\n\t * @param estimator  the function measurement struct\n\t * @param time  time current time stamp\n\t */\n\ttemplate<typename functor,typename ukf_type>\n\tvoid pseudoDistanceFunctionMeasurementSingle(plugin::SensorPlugin * plug,\n\t\t\tvoid* estimator, double time) {\n\t\tstatic double last_time=time-0.00001;\n\t\tDistanceMeasurement<functor,Eigen::Matrix<double,1,1>,ukf_type> * container= static_cast<DistanceMeasurement<functor,Eigen::Matrix<double,1,1>,ukf_type> *>(estimator);\n\t\t//plugin::IMU_Plugin *imu = static_cast<plugin::IMU_Plugin*>(plug);\n\t\tEigen::Matrix<double,1,1> zeros=Eigen::Matrix<double,1,1>::Zero();\n\t\tcontainer->ukf->measurementStep(zeros,time-last_time,distance_measurement_single<functor>,container->cov,container);\n\t\tlast_time=time;\n\t}\n\n\n\n\t/**\n\t * This Struct encapsulates the driving forward constrain\n\t * The Velocity in y and z direction ( in body coordinates ) is 0\n\t * The Velocity in x must equal the norm of the velocity\n\t *\n\t * It requires the estimator as prior\n\t */\n\ttemplate<typename estimator_type>\n\tstruct DrivingForwardConstrain {\n\t\tSETUP_PSEUDO_MEASUREMENT(3)\n\t\ttemplate<typename T>\n\t\tMEASURE_TYPE<T> operator()(const Eigen::Matrix<T,state_dim,1> &state,void * prior) const {\n\t\t\testimator_type * estimator=static_cast<estimator_type*>(prior);\n\t\t\tMEASURE_TYPE<T> body_velocity=estimator->getBoxModel().getOrientation(state).transpose()*estimator->getBoxModel().getVelocity(state)-getTarget(state,prior);\n\t\t\treturn body_velocity;\n\n\t\t}\n\t\tADD_UKF_FUNCTION_PASSER\n\t\ttemplate<typename T>\n\t\tMEASURE_TYPE<T> getTarget(const Eigen::Matrix<T,state_dim,1> &state, void * prior) const {\n\t\t\testimator_type * estimator=static_cast<estimator_type*>(prior);\n\t\t\tMEASURE_TYPE<T> returner=MEASURE_TYPE<T>::Zero();\n\t\t\tT norm=estimator->getBoxModel().getVelocity(state).norm();\n\t\t\tif(norm !=0.)     // ceres jet infinity fix\n\t\t\treturner(0,0)=norm;\n\t\t\treturn returner;\n\n\t\t}\n\n\n\t\ttemplate<typename T>\n\t\tstatic constexpr MEASURE_TYPE<T> getTarget() {\n\t\t\treturn MEASURE_TYPE<T>::Zero();\n\t\t}\n\t\tstatic Eigen::Matrix<double,measure_dim,measure_dim> getNoise() {\n\t\t\treturn Eigen::Matrix<double,measure_dim,measure_dim>::Identity()*0.1;\n\t\t}\n\t};\n\n\t/**\n\t * This Struct encapsulates the driving forward constrain\n\t * The Velocity in y and z direction ( in body coordinates ) is 0\n\t *\n\t * It requires the estimator as prior\n\t */\n\ttemplate<typename estimator_type>\n\tstruct NoSideUpDriftConstrain {\n\t\tSETUP_PSEUDO_MEASUREMENT(2)\n\t\ttemplate<typename T>\n\t\tMEASURE_TYPE<T> operator()(const Eigen::Matrix<T,state_dim,1> &state, void * prior) const {\n\t\t\treturn ( (estimator_type::MODEL_TYPE::getOrientation(state).transpose()*estimator_type::MODEL_TYPE::getVelocity(state))) .template block<2,1>(1,0);\n\n\t\t}\n\t\tADD_UKF_FUNCTION_PASSER\n\t\ttemplate<typename T>\n\t\tstatic constexpr MEASURE_TYPE<T> getTarget() {\n\t\t\treturn MEASURE_TYPE<T>::Zero();\n\t\t}\n\t\tstatic Eigen::Matrix<double,measure_dim,measure_dim> getNoise() {\n\t\t\treturn Eigen::Matrix<double,measure_dim,measure_dim>::Identity()*0.1;\n\t\t}\n\t};\n\n\ttemplate<typename estimator_type>\n\tstruct OnlyRollConstrain {\n\t\tstatic constexpr int measure_dim=2;     // measurement dimension\n\t\tstatic constexpr int state_dim=estimator_type::MODEL_TYPE::outer_size;\n\t\ttemplate<typename T>\n\t\tusing MEASURE_TYPE=Eigen::Matrix<T,measure_dim,1>;\n\t\ttemplate<typename T>\n\t\tMEASURE_TYPE<T> operator()(const Eigen::Matrix<T,state_dim,1> &state, void * prior) const {\n\t\t\treturn eigen_util::inverseEulerRodriguez<T>(estimator_type::MODEL_TYPE::getOrientation(state)).template block<2,1>(1,0);\n\n\t\t}\n\n\t\tADD_UKF_FUNCTION_PASSER\n\t\ttemplate<typename T>\n\t\tstatic constexpr MEASURE_TYPE<T> getTarget() {\n\t\t\treturn MEASURE_TYPE<T>::Zero();\n\t\t}\n\t\tstatic Eigen::Matrix<double,measure_dim,measure_dim> getNoise() {\n\t\t\treturn Eigen::Matrix<double,measure_dim,measure_dim>::Identity()*0.01;\n\t\t}\n\t};\n\n\t/**\n\t * This Struct encapsulates the driving forward constrain\n\t * The Velocity in y and z direction ( in body coordinates ) is 0\n\t *\n\t * It requires the estimator as prior\n\t */\n\ttemplate<typename estimator_type, typename functor>\n\tstruct FunctionOrientationMeasurement {\n\n\t\tSETUP_PSEUDO_MEASUREMENT_WITH_MANIFOLD(3,3)\n\n\t\teigen_util::FuncCaller function;\n\t\tFunctionOrientationMeasurement<estimator_type,functor>() :function(functor()) {\n\n\t\t}\n\n\t\ttemplate<typename T>\n\t\tMEASURE_TYPE<T> operator()(const Eigen::Matrix<T,state_dim,1> &state, void * prior) const {\n\t\t\testimator_type* estimator= static_cast<estimator_type *>(prior);\n\t\t\treturn eigen_util::boxMinusOrientation(estimator->getBoxModel().getOrientation(state),eigen_util::orientationFromFunctor(state(estimator->getBoxModel().lambda_start,0),function,1e-5));\n\n\t\t}\n\t\tADD_UKF_FUNCTION_PASSER\n\n\t\ttemplate<typename T>\n\t\tstatic MANIFOLD_TYPE<T> boxminus(const MEASURE_TYPE<T> &a , const MEASURE_TYPE<T> &b) {\n\t\t\treturn eigen_util::wrapAngles(b-a);\n\t\t}\n\t\ttemplate<typename T>\n\t\tstatic MEASURE_TYPE<T> boxplus(const MEASURE_TYPE<T> &state , const MANIFOLD_TYPE<T> &delta) {\n\t\t\treturn eigen_util::wrapAngles(state+delta);\n\t\t}\n\n\n\t\ttemplate<typename T>\n\t\tstatic constexpr MEASURE_TYPE<T> getTarget() {\n\t\t\treturn MEASURE_TYPE<T>::Zero();\n\t\t}\n\t\tstatic Eigen::Matrix<double,measure_dim,measure_dim> getNoise() {\n\t\t\treturn Eigen::Matrix<double,measure_dim,measure_dim>::Identity()*0.3;\n\t\t}\n\t};\n\t/**\n\t * This Struct encapsulates the driving forward constrain\n\t * The Velocity in y and z direction ( in body coordinates ) is 0\n\t *\n\t * It requires the estimator as prior\n\t */\n\ttemplate<typename estimator_type, typename functor>\n\tstruct FunctionOrientationChangeMeasurement {\n\t\tSETUP_PSEUDO_MEASUREMENT(3)\n\n\t\teigen_util::FuncCaller function;\n\t\tFunctionOrientationChangeMeasurement<estimator_type,functor>() :function(functor()) {\n\n\t\t}\n\n\t\ttemplate<typename T>\n\t\tMEASURE_TYPE<T> operator()(const Eigen::Matrix<T,state_dim,1> &state, void * prior) const {\n\t\t\testimator_type* estimator= static_cast<estimator_type *>(prior);\n\t\t\tEigen::Matrix<T,3,1> current_axis=estimator->getBoxModel().getOrientationChange(state);\n\t\t\tEigen::Matrix<T,3,1> target_axis=eigen_util::boxMinusOrientation(eigen_util::orientationFromFunctor(state(estimator->getBoxModel().lambda_start,0)-1e-5,function,1e-5),eigen_util::orientationFromFunctor(state(estimator->getBoxModel().lambda_start,0)+1e-5,function,1e-5))/2e-5;\n\t\t\t//zavi::plot::liveStateDraw<6>(target_axis,\"target_axis\");\n\t\t\t/*if(current_axis.norm()!=0.)\n\t\t\tcurrent_axis.normalize();*/\n\t\t\t/*if(target_axis.norm() !=0.)\n\t\t\ttarget_axis.normalize();*/\n\t\t\treturn current_axis-target_axis*estimator->getBoxModel().getLambdaVelocity(state);\n\n\t\t}\n\t\tADD_UKF_FUNCTION_PASSER\n\n\t\ttemplate<typename T>\n\t\tstatic constexpr MEASURE_TYPE<T> getTarget() {\n\t\t\treturn MEASURE_TYPE<T>::Zero();\n\t\t}\n\t\tstatic Eigen::Matrix<double,measure_dim,measure_dim> getNoise() {\n\t\t\treturn Eigen::Matrix<double,measure_dim,measure_dim>::Identity()*0.5;\n\t\t}\n\t};\n\n\t/**\n\t * pseudo ukf measurement\n\t * @template measure_struct a struct with () operator to define the measure function\n\t * @template ukf_type the type of the estimator\n\t * @template measure_dim the size of the measurement\n\t * @template measurement a measurement object containing the wanted result\n\t * @template cov the covariance of the pseudo measurement\n\t */\n\ttemplate<template<typename,typename ...> class measure_struct,typename ukf_type,typename ... meas_args>\n\tvoid ukfMeasurement(plugin::SensorPlugin * plug,\n\t\t\tvoid* estimator, double time) {\n\t\tstatic double last_time=time-0.00001;\n\t\tstatic measure_struct<ukf_type,meas_args ...> measure_function=measure_struct<ukf_type,meas_args ...>();\n\t\tukf_type *ukf=static_cast<ukf_type*>(estimator);\n\t\tukf->measurementStep(measure_function.template getTarget<double>(),time-last_time,measure_function,measure_function.getNoise(),estimator);     // No Prior is given since the circle_prior does not need an object\n\t\tlast_time=time;\n\t}\n\t/**\n\t * pseudo ukf measurement for manifolds\n\t * @template measure_struct a struct with () operator to define the measure function\n\t * @template ukf_type the type of the estimator\n\t * @template measure_dim the size of the measurement\n\t * @template measurement a measurement object containing the wanted result\n\t * @template cov the covariance of the pseudo measurement\n\t */\n\ttemplate<template<typename,typename ...> class measure_struct,typename ukf_type,typename ... meas_args>\n\tvoid ukfManifoldMeasurement(plugin::SensorPlugin * plug,\n\t\t\tvoid* estimator, double time) {\n\t\tstatic double last_time=time-0.00001;\n\t\ttypedef measure_struct<ukf_type,meas_args ...> MEASURE_STRUCT;\n\t\tstatic MEASURE_STRUCT measure_function=MEASURE_STRUCT();\n\t\tukf_type *ukf=static_cast<ukf_type*>(estimator);\n\t\t//measure_function.template boxplus<double>(Eigen::Vector3d(), Eigen::Vector3d());\n\t\tukf->measurementStepManifold(measure_function.template getTarget<double>(),time-last_time,measure_function,measure_function.getNoise(),MEASURE_STRUCT::boxplus,MEASURE_STRUCT::boxminus,estimator);\n\t\tlast_time=time;\n\t}\n\n\n\t/**\n\t * A cost function comparing the 1 state with the required circle trajectory\n\t */\n\ttemplate<template <typename T> class STATE_TYPE_T,typename MEASUREMENT_FUNCTION, int measure_dim >\n\tstruct MeasurementDiffCostFunction {\n\t\ttemplate<typename T>\n\t\tusing MEASUREMENT_TYPE_T= Eigen::Matrix<T,measure_dim,1>;\n\t\tstatic inline MEASUREMENT_FUNCTION measurement_function=MEASUREMENT_FUNCTION();\n\t\tMeasurementDiffCostFunction(void * prior):prior(prior) {}\n\n\t\ttemplate<typename T>\n\t\tbool operator()(const T * const a,const T* const alignment, T* result)const {\n\t\t\tstatic Eigen::Matrix<double,measure_dim,measure_dim> stiffnes=measurement_function.getNoise().diagonal().cwiseInverse().cwiseSqrt().asDiagonal();\n\t\t\tstatic Eigen::Matrix<double,measure_dim,1> measurement=measurement_function.template getTarget<double>();\n\t\t\t(Eigen::Map<MEASUREMENT_TYPE_T<T> > (result))=stiffnes*(measurement_function.template operator()<T>(Eigen::Map<const STATE_TYPE_T<T> >(a),Eigen::Map<const ALIGNMENT_TYPE<T> >(alignment),prior)-measurement);\n\t\t\treturn true;\n\t\t}\n\n\t\ttemplate<typename T>\n\t\tbool operator()(const T * const a, T* result)const {\n\t\t\tstatic Eigen::Matrix<double,measure_dim,measure_dim> stiffnes=measurement_function.getNoise().diagonal().cwiseInverse().cwiseSqrt().asDiagonal();\n\t\t\tstatic Eigen::Matrix<double,measure_dim,1> measurement=measurement_function.template getTarget<double>();\n\t\t\t(Eigen::Map<MEASUREMENT_TYPE_T<T> > (result))=stiffnes*(measurement_function.template operator()<T>(Eigen::Map<const STATE_TYPE_T<T> >(a),prior)-measurement);\n\t\t\treturn true;\n\t\t}\n\t\tvoid * prior;\n\t};\n\t/**\n\t * Adds the circular constraint to the ceres problem\n\t * @param problem  ceres problem\n\t * @param states list of all states\n\t * @param inputs list of all inputs\n\t * @param time_diffs list of all time diffs\n\t */\n\n\ttemplate<template<typename> class MEASUREMENT_FUNCTION, typename ESTIMATOR_TYPE,bool with_alignment=false>\n\tstruct MeasurementConstraint: public ESTIMATOR_TYPE::BatchConstrain {\n\t\tstatic constexpr int measure_dim=MEASUREMENT_FUNCTION<ESTIMATOR_TYPE>::measure_dim;\n\t\tvirtual ~MeasurementConstraint() {};\n\t\ttypedef MeasurementDiffCostFunction<ESTIMATOR_TYPE::template STATE_TYPE_T,MEASUREMENT_FUNCTION<ESTIMATOR_TYPE>,measure_dim > COST_TYPE;\n\t\tvirtual void operator()(ceres::Problem &problem,double * states,double * alignment, int state_size,void* data,std::vector<double> &time_diffs, BatchEstimator<typename ESTIMATOR_TYPE::MODEL_TYPE> * estimator) {\n\t\t\tif(with_alignment) {\n\t\t\t\tceres::CostFunction* cost_function=new ceres::AutoDiffCostFunction<COST_TYPE,measure_dim,ESTIMATOR_TYPE::MODEL_TYPE::outer_size, ALIGNMENT_SIZE>(new COST_TYPE(estimator));\n\t\t\t\tfor(int i=0; i < state_size;i++) {\n\t\t\t\t\tproblem.AddResidualBlock(cost_function,NULL,&states[i*ESTIMATOR_TYPE::MODEL_TYPE::outer_size], alignment);\n\t\t\t\t}\n\t\t\t}\n\t\t\telse {\n\t\t\t\tceres::CostFunction* cost_function=new ceres::AutoDiffCostFunction<COST_TYPE,measure_dim,ESTIMATOR_TYPE::MODEL_TYPE::outer_size>(new COST_TYPE(estimator));\n\t\t\t\tfor(int i=0; i < state_size;i++) {\n\t\t\t\t\tproblem.AddResidualBlock(cost_function,NULL,&states[i*ESTIMATOR_TYPE::MODEL_TYPE::outer_size]);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t};\n\n}\n//zavi::estimator::pseudo_measurement\n\n#endif /* ESTIMATORS_PSEUDOMEASUREMENTS_HPP_ */\n", "meta": {"hexsha": "15d69fc9a3dcbbb4ae39bb7fe8f46e0a2da3c0dd", "size": 20103, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "SixdaysCode/Estimators/PseudoMeasurements.hpp", "max_stars_repo_name": "TomLKoller/ZaVI_TrackCycling", "max_stars_repo_head_hexsha": "7c23bc34e6e58c78ec249f6f55d4e70c7e91d315", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-06-15T07:20:08.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-15T07:20:08.000Z", "max_issues_repo_path": "SixdaysCode/Estimators/PseudoMeasurements.hpp", "max_issues_repo_name": "TomLKoller/ZaVI_TrackCycling", "max_issues_repo_head_hexsha": "7c23bc34e6e58c78ec249f6f55d4e70c7e91d315", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "SixdaysCode/Estimators/PseudoMeasurements.hpp", "max_forks_repo_name": "TomLKoller/ZaVI_TrackCycling", "max_forks_repo_head_hexsha": "7c23bc34e6e58c78ec249f6f55d4e70c7e91d315", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-06-15T07:20:19.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-15T07:20:19.000Z", "avg_line_length": 40.2865731463, "max_line_length": 278, "alphanum_fraction": 0.7493408944, "num_tokens": 5269, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6513548646660542, "lm_q2_score": 0.48438008427698437, "lm_q1q2_score": 0.31550332424116706}}
{"text": "// This file is part of snark, a generic and flexible library for robotics research\n// Copyright (c) 2011 The University of Sydney\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are met:\n// 1. Redistributions of source code must retain the above copyright\n//    notice, this list of conditions and the following disclaimer.\n// 2. Redistributions in binary form must reproduce the above copyright\n//    notice, this list of conditions and the following disclaimer in the\n//    documentation and/or other materials provided with the distribution.\n// 3. Neither the name of the University of Sydney nor the\n//    names of its contributors may be used to endorse or promote products\n//    derived from this software without specific prior written permission.\n//\n// NO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE\n// GRANTED BY THIS LICENSE.  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT\n// HOLDERS AND CONTRIBUTORS \\\"AS IS\\\" AND ANY EXPRESS OR IMPLIED\n// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\n// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\n// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR\n// BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE\n// OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN\n// IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n#include <cmath>\n#include <Eigen/Geometry>\n#include <boost/format.hpp>\n#include <comma/base/exception.h>\n#include <comma/math/compare.h>\n#include <snark/math/angle.h>\n#include \"coordinates.h\"\n\nnamespace snark { namespace spherical {\n\nconst double coordinates::epsilon = 1e-6;\n\nbool coordinates::operator==( const coordinates& rhs ) const\n{ return is_near( rhs, epsilon ); }\n\nbool coordinates::is_near( const coordinates& c, double epsilon ) const\n{\n    double dist = std::abs( longitude - c.longitude );\n    return comma::math::equal( latitude, c.latitude, epsilon ) && comma::math::equal( 0, std::min( dist, 2 * M_PI - dist ), epsilon );\n}\n\n/// limits longitude to [-PI, PI)\nstatic double limit( const double longitude )\n{\n    // todo: this is just a quick patch, not a real fix; what if longitude equals e.g. -3*M_PI?\n    // todo: seriously quick and dirty, to fix anti merridian crossing\n    return longitude < -M_PI ? longitude + 2 * M_PI : longitude >= M_PI ? longitude - 2 * M_PI : longitude;\n}\n\ncoordinates::coordinates( const double latitude, const double longitude ) : latitude( latitude ), longitude( limit( longitude ) )\n{\n}\n\ncoordinates::coordinates( const snark::bearing_elevation& be ) : latitude( be.elevation() ), longitude( limit( be.bearing() ) )\n{\n}\n\ncoordinates::coordinates( const Eigen::Vector3d& xyz )\n{\n    snark::range_bearing_elevation rbe( xyz );\n    latitude = rbe.elevation();\n    longitude = limit( rbe.bearing() );\n}\n\nEigen::Vector3d to_navigation_frame( const coordinates& c, const Eigen::Vector3d& v )\n{\n    const Eigen::Matrix3d& r1 = Eigen::AngleAxis< double >( -c.longitude, Eigen::Vector3d( 0, 0, 1 ) ).toRotationMatrix();\n    const Eigen::Matrix3d& r2 = Eigen::AngleAxis< double >( c.latitude + M_PI / 2, Eigen::Vector3d( 0, 1, 0 ) ).toRotationMatrix();\n    return r2 * r1 * v;\n}\n\ncoordinates& coordinates::operator+=( const coordinates& rhs )\n{\n    double d = latitude + rhs.latitude;\n    static const double epsilon = 0.00005;\n    if( comma::math::equal( d, M_PI / 2, epsilon ) ) { d = M_PI / 2; }\n    else if( comma::math::equal( d, -M_PI / 2, epsilon ) ) { d = -M_PI / 2; }\n    else if( d > M_PI / 2 || d < -M_PI / 2 ) { COMMA_THROW( comma::exception, \"adding \" << ( latitude * 180 / M_PI ) << \" and \" << ( rhs.latitude * 180 / M_PI ) << \" gives invalid latitude of \" << ( d * 180 / M_PI ) << \" degress\" ); }\n    latitude = d;\n    longitude += rhs.longitude;\n    while( longitude < -M_PI ) { longitude += 2 * M_PI; } // brutal, but mod() is slower in most cases, i think\n    while( this->longitude >= M_PI ) { longitude -= 2 * M_PI; } // brutal, but mod() is slower in most cases, i think\n    return *this;\n}\n\ncoordinates::operator std::string() const\n{\n    const std::pair< double, double >& c = to_degrees();\n    return (boost::format(\"%.2f\") % c.first ).str() + \",\" + (boost::format(\"%.2f\") % c.second).str();\n}\n\nbool coordinates::is_near( const Eigen::Vector3d& c, double _epsilon ) const\n{\n    return ( to_cartesian() - c ).lpNorm<Eigen::Infinity>() < _epsilon;\n}\n\ncoordinates coordinates::from_degrees(double latitude, double longitude)\n{\n    return coordinates( snark::math::radians( snark::math::degrees( latitude ) ).value,\n                        snark::math::radians( snark::math::degrees( longitude ) ).value );\n}\n\nstd::pair< double, double > coordinates::to_degrees() const\n{\n    return std::make_pair( snark::math::degrees( snark::math::radians( latitude ) ).value\n                         , snark::math::degrees( snark::math::radians( longitude ) ).value );\n}\n\n} } // namespace snark { namespace spherical {\n", "meta": {"hexsha": "0c0a38c5bc453204b6b1488d79a83babdf5b112b", "size": 5330, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "math/spherical_geometry/coordinates.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/spherical_geometry/coordinates.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/spherical_geometry/coordinates.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": 44.7899159664, "max_line_length": 234, "alphanum_fraction": 0.6915572233, "num_tokens": 1352, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6513548511303336, "lm_q2_score": 0.48438008427698437, "lm_q1q2_score": 0.3155033176847336}}
{"text": "//---------------------------------------------------------------------------//\n// Copyright (c) 2018-2020 Mikhail Komarov <nemo@nil.foundation>\n// Copyright (c) 2020 Nikita Kaskov <nbering@nil.foundation>\n//\n// MIT License\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in all\n// copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n// SOFTWARE.\n//---------------------------------------------------------------------------//\n\n#ifndef CRYPTO3_BLOCK_RIJNDAEL_HPP\n#define CRYPTO3_BLOCK_RIJNDAEL_HPP\n\n#include <boost/range/adaptor/sliced.hpp>\n\n#include <nil/crypto3/block/detail/block_stream_processor.hpp>\n#include <nil/crypto3/block/detail/cipher_modes.hpp>\n\n#include <nil/crypto3/block/detail/rijndael/rijndael_policy.hpp>\n#include <nil/crypto3/block/detail/rijndael/rijndael_impl.hpp>\n\n#if defined(CRYPTO3_HAS_RIJNDAEL_NI)\n\n#include <nil/crypto3/block/detail/rijndael/rijndael_ni_impl.hpp>\n\n#elif defined(CRYPTO3_HAS_RIJNDAEL_SSSE3) || BOOST_HW_SIMD_X86 >= BOOST_HW_SIMD_X86_SSSE3_VERSION\n\n#include <nil/crypto3/block/detail/rijndael/rijndael_ssse3_impl.hpp>\n\n#elif defined(CRYPTO3_HAS_RIJNDAEL_ARMV8)\n\n#include <nil/crypto3/block/detail/rijndael/rijndael_armv8_impl.hpp>\n\n#elif defined(CRYPTO3_HAS_RIJNDAEL_POWER8)\n\n#include <nil/crypto3/block/detail/rijndael/rijndael_power8_impl.hpp>\n\n#endif\n\n#include <nil/crypto3/block/detail/utilities/cpuid/cpuid.hpp>\n\nnamespace nil {\n    namespace crypto3 {\n        namespace block {\n\n            /*!\n             * @brief Rijndael. AES competition winner.\n             *\n             * @ingroup block\n             *\n             * Generic Rijndael cipher implementation. Contains AES-standardized\n             * cipher modifications with timing-attack and cache-line leaking\n             * attack preventing mechanisms. Optimized for particular architecture\n             * used.\n             * AES-standartized version comes in three variants, AES-128, AES-192,\n             * and AES-256.\n             *\n             * The standard 128-bit block cipher. Many modern platforms offer hardware\n             * acceleration. However, on platforms without hardware support, AES\n             * implementations typically are vulnerable to side channel attacks. For x86\n             * systems with SSSE3 but without AES-NI, crypto3 has an implementation which avoids\n             * known side channels.\n             *\n             * This implementation is intended to be based on table lookups which\n             * are known to be vulnerable to timing and cache based side channel\n             * attacks. Some countermeasures are used which may be helpful in some\n             * situations:\n             *\n             * - Only a single 256-word T-table is used, with rotations applied.\n             *   Most implementations use 4 T-tables which leaks much more\n             *   information via cache usage.\n             *\n             * - The TE and TD tables are computed at runtime to avoid flush+reload\n             *   attacks using clflush. As different processes will not share the\n             *   same underlying table data, an attacker can't manipulate another\n             *   processes cache lines via their shared reference to the library\n             *   read only segment.\n             *\n             * - Each cache line of the lookup tables is accessed at the beginning\n             *   of each call to encrypt or decrypt. (See the Z variable below)\n             *\n             * If available SSSE3 or AES-NI are used instead of this version, as both\n             * are faster and immune to side channel attacks.\n             *\n             * Some AES cache timing papers for reference:\n             *\n             * [Software mitigations to hedge AES against cache-based software side channel\n             * vulnerabilities](https://eprint.iacr.org/2006/052.pdf)\n             *\n             * [Cache Games - Bringing Access-Based Cache Attacks on AES to\n             * Practice](http://www.ieee-security.org/TC/SP2011/PAPERS/2011/paper031.pdf)\n             *\n             * [Cache-Collision Timing Attacks Against AES. Bonneau,\n             * Mironov](http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.88.4753)\n             *\n             * @tparam KeyBits Key length used in bits. Available values are: 128, 192, 256\n             * @tparam BlockBits Block length used in bits. Available values are: 128, 192, 256\n             */\n            template<std::size_t KeyBits, std::size_t BlockBits>\n            class rijndael {\n\n                BOOST_STATIC_ASSERT(KeyBits >= 128 && KeyBits <= 256 && KeyBits % 32 == 0);\n                BOOST_STATIC_ASSERT(BlockBits >= 128 && BlockBits <= 256 && BlockBits % 32 == 0);\n\n                constexpr static const std::size_t version = KeyBits;\n                typedef detail::rijndael_policy<KeyBits, BlockBits> policy_type;\n\n                typedef\n                    typename std::conditional<BlockBits == 128 && (KeyBits == 128 || KeyBits == 192 || KeyBits == 256),\n#if defined(CRYPTO3_HAS_RIJNDAEL_NI)\n                                              detail::rijndael_ni_impl<KeyBits, BlockBits, policy_type>,\n#elif defined(CRYPTO3_HAS_RIJNDAEL_SSSE3) || BOOST_HW_SIMD_X86 >= BOOST_HW_SIMD_X86_SSSE3_VERSION\n                                              detail::rijndael_ssse3_impl<KeyBits, BlockBits, policy_type>,\n#elif defined(CRYPTO3_HAS_RIJNDAEL_ARMV8)\n                                              detail::rijndael_armv8_impl<KeyBits, BlockBits, policy_type>,\n#elif defined(CRYPTO3_HAS_RIJNDAEL_POWER8)\n                                              detail::rijndael_power8_impl<KeyBits, BlockBits, policy_type>,\n#else\n                                              detail::rijndael_impl<KeyBits, BlockBits, policy_type>,\n#endif\n                                              detail::rijndael_impl<KeyBits, BlockBits, policy_type>>::type impl_type;\n\n                constexpr static const std::size_t key_schedule_words = policy_type::key_schedule_words;\n                constexpr static const std::size_t key_schedule_bytes = policy_type::key_schedule_bytes;\n                typedef typename policy_type::key_schedule_type key_schedule_type;\n\n            public:\n                constexpr static const std::size_t word_bits = policy_type::word_bits;\n                constexpr static const std::size_t word_bytes = policy_type::word_bytes;\n                typedef typename policy_type::word_type word_type;\n\n                constexpr static const std::size_t key_bits = policy_type::key_bits;\n                constexpr static const std::size_t key_words = policy_type::key_words;\n                //                typedef typename policy_type::key_schedule_word_type key_schedule_word_type;\n                typedef typename policy_type::key_type key_type;\n\n                constexpr static const std::size_t block_bits = policy_type::block_bits;\n                constexpr static const std::size_t block_words = policy_type::block_words;\n                typedef typename policy_type::block_type block_type;\n\n                constexpr static const std::uint8_t rounds = policy_type::rounds;\n                typedef typename policy_type::round_constants_type round_constants_type;\n\n                template<class Mode, typename StateAccumulator, std::size_t ValueBits>\n                struct stream_processor {\n                    struct params_type {\n                        constexpr static const std::size_t value_bits = ValueBits;\n                        constexpr static const std::size_t length_bits = policy_type::word_bits * 2;\n                    };\n\n                    typedef block_stream_processor<Mode, StateAccumulator, params_type> type;\n                };\n\n                typedef typename stream_endian::little_octet_big_bit endian_type;\n\n                rijndael(const key_type &key) : encryption_key({0}), decryption_key({0}) {\n                    impl_type::schedule_key(key, encryption_key, decryption_key);\n                }\n\n                virtual ~rijndael() {\n                    encryption_key.fill(0);\n                    decryption_key.fill(0);\n                }\n\n                inline block_type encrypt(const block_type &plaintext) const {\n                    return impl_type::encrypt_block(plaintext, encryption_key);\n                }\n\n                inline block_type decrypt(const block_type &plaintext) const {\n                    return impl_type::decrypt_block(plaintext, decryption_key);\n                }\n\n            protected:\n                key_schedule_type encryption_key, decryption_key;\n            };\n        }    // namespace block\n    }        // namespace crypto3\n}    // namespace nil\n\n#endif\n", "meta": {"hexsha": "c9fc1f751afe54dad1ad02ad525c4bd84f0c1b97", "size": 9605, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/nil/crypto3/block/rijndael.hpp", "max_stars_repo_name": "NilFoundation/crypto3-block", "max_stars_repo_head_hexsha": "94f9cc42ac0fa62c5ee54e7d678abf48ffa9eec5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-09-14T18:09:38.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-14T18:09:38.000Z", "max_issues_repo_path": "include/nil/crypto3/block/rijndael.hpp", "max_issues_repo_name": "tonlabs/crypto3-block", "max_issues_repo_head_hexsha": "d7eede022f6130797d28bc39eb312bff9afebf07", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 41.0, "max_issues_repo_issues_event_min_datetime": "2019-06-07T23:11:20.000Z", "max_issues_repo_issues_event_max_datetime": "2020-08-16T18:04:20.000Z", "max_forks_repo_path": "include/nil/crypto3/block/rijndael.hpp", "max_forks_repo_name": "tonlabs/crypto3-block", "max_forks_repo_head_hexsha": "d7eede022f6130797d28bc39eb312bff9afebf07", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-01-11T15:37:40.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-26T21:47:05.000Z", "avg_line_length": 49.0051020408, "max_line_length": 119, "alphanum_fraction": 0.6270692348, "num_tokens": 1982, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.66192288918838, "lm_q2_score": 0.476579651063676, "lm_q1q2_score": 0.31545897956045843}}
{"text": "/******************************************************************************\n * Copyright (C) 2013 by Jerome Maye                                          *\n * jerome.maye@gmail.com                                                      *\n *                                                                            *\n * This program is free software; you can redistribute it and/or modify       *\n * it under the terms of the Lesser 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 * Lesser GNU General Public License for more details.                        *\n *                                                                            *\n * You should have received a copy of the Lesser GNU General Public License   *\n * along with this program. If not, see <http://www.gnu.org/licenses/>.       *\n ******************************************************************************/\n\n#include \"aslam/calibration/algorithms/marginalize.h\"\n\n#include <cmath>\n\n#include <Eigen/Dense>\n\n#include <aslam/backend/CompressedColumnMatrix.hpp>\n\n#include \"aslam/calibration/exceptions/InvalidOperationException.h\"\n#include \"aslam/calibration/exceptions/OutOfBoundException.h\"\n\nnamespace aslam {\nnamespace calibration {\n\n/******************************************************************************/\n/* Methods                                                                    */\n/******************************************************************************/\n\ndouble colNorm(cholmod_sparse* A, size_t j) {\n    if (j >= A->ncol)\n        throw OutOfBoundException<size_t>(j, \"colNorm(): index must be lower than the number of columns\", __FILE__,\n                                          __LINE__);\n    const std::ptrdiff_t* col_ptr = reinterpret_cast<const std::ptrdiff_t*>(A->p);\n    const double* values = reinterpret_cast<const double*>(A->x);\n    const std::ptrdiff_t p = col_ptr[j];\n    const std::ptrdiff_t numElements = col_ptr[j + 1] - p;\n    double norm = 0;\n    for (std::ptrdiff_t i = 0; i < numElements; ++i) norm += values[p + i] * values[p + i];\n    return std::sqrt(norm);\n}\n\nEigen::MatrixXd marginalJacobian(cholmod_sparse* J_x, cholmod_sparse* J_thetat, cholmod_common* cholmod) {\n    // compute the QR factorization of J_x\n    SuiteSparseQR_factorization<double>* QR =\n        SuiteSparseQR_factorize<double>(SPQR_ORDERING_BEST, SPQR_DEFAULT_TOL, J_x, cholmod);\n    if (QR == NULL)\n        throw InvalidOperationException(\n            \"marginalJacobian(): \"\n            \"SuiteSparseQR_factorize failed\");\n\n    // compute the Jacobian of the reduced system\n    cholmod_sparse* J_thetatQFull = SuiteSparseQR_qmult<double>(SPQR_XQ, QR, J_thetat, cholmod);\n    if (J_thetatQFull == NULL) {\n        SuiteSparseQR_free(&QR, cholmod);\n        throw InvalidOperationException(\n            \"marginalJacobian(): \"\n            \"SuiteSparseQR_qmult failed\");\n    }\n    std::ptrdiff_t* colIndices = new std::ptrdiff_t[J_x->ncol];\n    for (size_t i = 0; i < J_x->ncol; ++i) colIndices[i] = i;\n    cholmod_sparse* J_thetatQ = cholmod_l_submatrix(J_thetatQFull, NULL, -1, colIndices, J_x->ncol, 1, 0, cholmod);\n    delete[] colIndices;\n    if (J_thetatQ == NULL) {\n        SuiteSparseQR_free(&QR, cholmod);\n        cholmod_l_free_sparse(&J_thetatQFull, cholmod);\n        throw InvalidOperationException(\n            \"marginalJacobian(): \"\n            \"cholmod_l_submatrix failed\");\n    }\n    cholmod_sparse* J_thetat2 = cholmod_l_aat(J_thetat, NULL, 0, 1, cholmod);\n    if (J_thetat2 == NULL) {\n        SuiteSparseQR_free(&QR, cholmod);\n        cholmod_l_free_sparse(&J_thetatQFull, cholmod);\n        cholmod_l_free_sparse(&J_thetatQ, cholmod);\n        throw InvalidOperationException(\n            \"marginalJacobian(): \"\n            \"cholmod_l_aat failed\");\n    }\n    cholmod_sparse* J_thetatQ2 = cholmod_l_aat(J_thetatQ, NULL, 0, 1, cholmod);\n    if (J_thetatQ2 == NULL) {\n        SuiteSparseQR_free(&QR, cholmod);\n        cholmod_l_free_sparse(&J_thetatQFull, cholmod);\n        cholmod_l_free_sparse(&J_thetatQ, cholmod);\n        cholmod_l_free_sparse(&J_thetat2, cholmod);\n        throw InvalidOperationException(\n            \"marginalJacobian(): \"\n            \"cholmod_l_aat failed\");\n    }\n    double alpha[2];\n    alpha[0] = 1;\n    double beta[2];\n    beta[0] = -1;\n    cholmod_sparse* Omega = cholmod_l_add(J_thetat2, J_thetatQ2, alpha, beta, 1, 0, cholmod);\n    if (Omega == NULL) {\n        SuiteSparseQR_free(&QR, cholmod);\n        cholmod_l_free_sparse(&J_thetatQFull, cholmod);\n        cholmod_l_free_sparse(&J_thetatQ, cholmod);\n        cholmod_l_free_sparse(&J_thetat2, cholmod);\n        cholmod_l_free_sparse(&J_thetatQ2, cholmod);\n        throw InvalidOperationException(\n            \"marginalJacobian(): \"\n            \"cholmod_l_add failed\");\n    }\n    aslam::backend::CompressedColumnMatrix<std::ptrdiff_t> OmegaCCM;\n    OmegaCCM.fromCholmodSparse(Omega);\n    Eigen::MatrixXd OmegaDense(Omega->nrow, Omega->ncol);\n    OmegaCCM.toDenseInto(OmegaDense);\n\n    // clean allocated memory\n    SuiteSparseQR_free(&QR, cholmod);\n    cholmod_l_free_sparse(&J_thetatQFull, cholmod);\n    cholmod_l_free_sparse(&J_thetatQ, cholmod);\n    cholmod_l_free_sparse(&J_thetat2, cholmod);\n    cholmod_l_free_sparse(&J_thetatQ2, cholmod);\n    cholmod_l_free_sparse(&Omega, cholmod);\n\n    return OmegaDense;\n}\n\ndouble marginalize(const aslam::backend::CompressedColumnMatrix<std::ptrdiff_t>& Jt, size_t j, Eigen::MatrixXd& NS,\n                   Eigen::MatrixXd& CS, Eigen::MatrixXd& Sigma, Eigen::MatrixXd& SigmaP, Eigen::MatrixXd& Omega,\n                   double normTol, double epsTol) {\n    // init cholmod\n    cholmod_common cholmod;\n    cholmod_l_start(&cholmod);\n\n    // convert to cholmod_sparse\n    cholmod_sparse JtCs;\n    const_cast<aslam::backend::CompressedColumnMatrix<std::ptrdiff_t>&>(Jt).getView(&JtCs);\n    cholmod_sparse* J = cholmod_l_transpose(&JtCs, 1, &cholmod);\n    if (J == NULL) {\n        cholmod_l_finish(&cholmod);\n        throw InvalidOperationException(\n            \"marginalize(): \"\n            \"cholmod_l_transpose failed\");\n    }\n\n    // extract the part corresponding to the state/landmarks/...\n    std::ptrdiff_t* colIndices = new std::ptrdiff_t[j];\n    for (size_t i = 0; i < j; ++i) colIndices[i] = i;\n    cholmod_sparse* J_x = cholmod_l_submatrix(J, NULL, -1, colIndices, j, 1, 0, &cholmod);\n    delete[] colIndices;\n    if (J_x == NULL) {\n        cholmod_l_free_sparse(&J, &cholmod);\n        cholmod_l_finish(&cholmod);\n        throw InvalidOperationException(\n            \"marginalize(): \"\n            \"cholmod_l_submatrix failed\");\n    }\n\n    // extract the part corresponding to the calibration parameters\n    colIndices = new std::ptrdiff_t[J->ncol - j];\n    for (size_t i = j; i < J->ncol; ++i) colIndices[i - j] = i;\n    cholmod_sparse* J_theta = cholmod_l_submatrix(J, NULL, -1, colIndices, J->ncol - j, 1, 0, &cholmod);\n    delete[] colIndices;\n    if (J_theta == NULL) {\n        cholmod_l_free_sparse(&J, &cholmod);\n        cholmod_l_free_sparse(&J_x, &cholmod);\n        cholmod_l_finish(&cholmod);\n        throw InvalidOperationException(\n            \"marginalize(): \"\n            \"cholmod_l_submatrix failed\");\n    }\n    cholmod_sparse* J_thetat = cholmod_l_transpose(J_theta, 1, &cholmod);\n    if (J_thetat == NULL) {\n        cholmod_l_free_sparse(&J, &cholmod);\n        cholmod_l_free_sparse(&J_x, &cholmod);\n        cholmod_l_free_sparse(&J_theta, &cholmod);\n        cholmod_l_finish(&cholmod);\n        throw InvalidOperationException(\n            \"marginalize(): \"\n            \"cholmod_l_transpose failed\");\n    }\n\n    // compute the marginal Jacobian\n    try {\n        Omega = marginalJacobian(J_x, J_thetat, &cholmod);\n    } catch (const InvalidOperationException& e) {\n        cholmod_l_free_sparse(&J, &cholmod);\n        cholmod_l_free_sparse(&J_x, &cholmod);\n        cholmod_l_free_sparse(&J_theta, &cholmod);\n        cholmod_l_free_sparse(&J_thetat, &cholmod);\n        cholmod_l_finish(&cholmod);\n        throw;\n    }\n\n    // scale J_x\n    cholmod_dense* G_x = cholmod_l_allocate_dense(J_x->ncol, 1, J_x->ncol, CHOLMOD_REAL, &cholmod);\n    if (G_x == NULL) {\n        cholmod_l_free_sparse(&J, &cholmod);\n        cholmod_l_free_sparse(&J_x, &cholmod);\n        cholmod_l_free_sparse(&J_theta, &cholmod);\n        cholmod_l_free_sparse(&J_thetat, &cholmod);\n        cholmod_l_finish(&cholmod);\n        throw InvalidOperationException(\n            \"marginalize(): \"\n            \"cholmod_l_allocate_dense failed\");\n    }\n    try {\n        double* values = reinterpret_cast<double*>(G_x->x);\n        for (size_t j = 0; j < J_x->ncol; ++j) {\n            const double normCol = colNorm(J_x, j);\n            if (normCol < normTol)\n                values[j] = 0.0;\n            else\n                values[j] = 1.0 / normCol;\n        }\n    } catch (const OutOfBoundException<size_t>& e) {\n        cholmod_l_free_sparse(&J, &cholmod);\n        cholmod_l_free_sparse(&J_x, &cholmod);\n        cholmod_l_free_sparse(&J_theta, &cholmod);\n        cholmod_l_free_sparse(&J_thetat, &cholmod);\n        cholmod_l_free_dense(&G_x, &cholmod);\n        cholmod_l_finish(&cholmod);\n        throw;\n    }\n    if (cholmod_l_scale(G_x, CHOLMOD_COL, J_x, &cholmod) == 0) {\n        cholmod_l_free_sparse(&J, &cholmod);\n        cholmod_l_free_sparse(&J_x, &cholmod);\n        cholmod_l_free_sparse(&J_theta, &cholmod);\n        cholmod_l_free_sparse(&J_thetat, &cholmod);\n        cholmod_l_free_dense(&G_x, &cholmod);\n        cholmod_l_finish(&cholmod);\n        throw InvalidOperationException(\n            \"marginalize(): \"\n            \"cholmod_l_scale failed\");\n    }\n    cholmod_l_free_dense(&G_x, &cholmod);\n\n    // scale J_thetat\n    cholmod_dense* G_theta = cholmod_l_allocate_dense(J_theta->ncol, 1, J_theta->ncol, CHOLMOD_REAL, &cholmod);\n    if (G_theta == NULL) {\n        cholmod_l_free_sparse(&J, &cholmod);\n        cholmod_l_free_sparse(&J_x, &cholmod);\n        cholmod_l_free_sparse(&J_theta, &cholmod);\n        cholmod_l_free_sparse(&J_thetat, &cholmod);\n        cholmod_l_finish(&cholmod);\n        throw InvalidOperationException(\n            \"marginalize(): \"\n            \"cholmod_l_allocate_dense failed\");\n    }\n    try {\n        double* values = reinterpret_cast<double*>(G_theta->x);\n        for (size_t j = 0; j < J_theta->ncol; ++j) {\n            const double normCol = colNorm(J_theta, j);\n            if (normCol < normTol)\n                values[j] = 0.0;\n            else\n                values[j] = 1.0 / normCol;\n        }\n    } catch (const OutOfBoundException<size_t>& e) {\n        cholmod_l_free_sparse(&J, &cholmod);\n        cholmod_l_free_sparse(&J_x, &cholmod);\n        cholmod_l_free_sparse(&J_theta, &cholmod);\n        cholmod_l_free_sparse(&J_thetat, &cholmod);\n        cholmod_l_free_dense(&G_theta, &cholmod);\n        cholmod_l_finish(&cholmod);\n        throw;\n    }\n    if (cholmod_l_scale(G_theta, CHOLMOD_ROW, J_thetat, &cholmod) == 0) {\n        cholmod_l_free_sparse(&J, &cholmod);\n        cholmod_l_free_sparse(&J_x, &cholmod);\n        cholmod_l_free_sparse(&J_theta, &cholmod);\n        cholmod_l_free_sparse(&J_thetat, &cholmod);\n        cholmod_l_free_dense(&G_theta, &cholmod);\n        cholmod_l_finish(&cholmod);\n        throw InvalidOperationException(\n            \"marginalize(): \"\n            \"cholmod_l_scale failed\");\n    }\n    cholmod_l_free_dense(&G_theta, &cholmod);\n\n    // compute the scaled marginal Jacobian\n    Eigen::MatrixXd OmegaScaled;\n    try {\n        OmegaScaled = marginalJacobian(J_x, J_thetat, &cholmod);\n    } catch (const InvalidOperationException& e) {\n        cholmod_l_free_sparse(&J, &cholmod);\n        cholmod_l_free_sparse(&J_x, &cholmod);\n        cholmod_l_free_sparse(&J_theta, &cholmod);\n        cholmod_l_free_sparse(&J_thetat, &cholmod);\n        cholmod_l_finish(&cholmod);\n        throw;\n    }\n\n    // clean cholmod\n    cholmod_l_free_sparse(&J, &cholmod);\n    cholmod_l_free_sparse(&J_x, &cholmod);\n    cholmod_l_free_sparse(&J_theta, &cholmod);\n    cholmod_l_free_sparse(&J_thetat, &cholmod);\n    cholmod_l_finish(&cholmod);\n\n    // compute the thin SVD of OmegaScaled\n    const Eigen::JacobiSVD<Eigen::MatrixXd> svdScaled(OmegaScaled, Eigen::ComputeThinU | Eigen::ComputeThinV);\n\n    // compute the numerical rank\n    size_t nrank = OmegaScaled.cols();\n    const Eigen::VectorXd& SScaled = svdScaled.singularValues();\n    const double tol = OmegaScaled.rows() * SScaled(0) * epsTol;\n    for (std::ptrdiff_t i = OmegaScaled.cols() - 1; i > 0; --i) {\n        if (SScaled(i) > tol)\n            break;\n        else\n            nrank--;\n    }\n\n    // compute the thin SVD of Omega\n    const Eigen::JacobiSVD<Eigen::MatrixXd> svd(Omega, Eigen::ComputeThinU | Eigen::ComputeThinV);\n    const Eigen::MatrixXd& V = svd.matrixV();\n\n    // compute the numerical column space\n    CS = V.block(0, 0, V.rows(), nrank);\n\n    // compute the numerical null space\n    NS = V.block(0, nrank, V.rows(), Omega.cols() - nrank);\n\n    // compute the projected covariance matrix\n    Eigen::MatrixXd invS(Eigen::MatrixXd::Zero(Omega.cols(), Omega.cols()));\n    SigmaP = Eigen::MatrixXd::Zero(nrank, nrank);\n    double svLogSum = 0;\n    const Eigen::VectorXd& S = svd.singularValues();\n    for (size_t i = 0; i < nrank; ++i) {\n        SigmaP(i, i) = 1.0 / S(i);\n        svLogSum = svLogSum + log2(S(i));\n        invS(i, i) = SigmaP(i, i);\n    }\n\n    // compute the covariance matrix\n    Sigma = V * invS * V.transpose();\n    return svLogSum;\n}\n\n}  // namespace calibration\n}  // namespace aslam\n", "meta": {"hexsha": "3c7d854ced6df0f450417ab94f7c07be484b038e", "size": 13946, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "aslam_incremental_calibration/incremental_calibration/src/algorithms/marginalize.cpp", "max_stars_repo_name": "chengfzy/kalibr", "max_stars_repo_head_hexsha": "fe9705b380b160dc939607135f7d30efa64ea2e9", "max_stars_repo_licenses": ["BSD-4-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "aslam_incremental_calibration/incremental_calibration/src/algorithms/marginalize.cpp", "max_issues_repo_name": "chengfzy/kalibr", "max_issues_repo_head_hexsha": "fe9705b380b160dc939607135f7d30efa64ea2e9", "max_issues_repo_licenses": ["BSD-4-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "aslam_incremental_calibration/incremental_calibration/src/algorithms/marginalize.cpp", "max_forks_repo_name": "chengfzy/kalibr", "max_forks_repo_head_hexsha": "fe9705b380b160dc939607135f7d30efa64ea2e9", "max_forks_repo_licenses": ["BSD-4-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.6588921283, "max_line_length": 115, "alphanum_fraction": 0.6054065682, "num_tokens": 3723, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6959583376458152, "lm_q2_score": 0.45326184801538616, "lm_q1q2_score": 0.31545136226305825}}
{"text": "#ifndef STAN_MATH_PRIM_PROB_NEG_BINOMIAL_2_RNG_HPP\n#define STAN_MATH_PRIM_PROB_NEG_BINOMIAL_2_RNG_HPP\n\n#include <stan/math/prim/meta.hpp>\n#include <stan/math/prim/err.hpp>\n#include <stan/math/prim/fun/constants.hpp>\n#include <stan/math/prim/fun/max_size.hpp>\n#include <boost/random/gamma_distribution.hpp>\n#include <boost/random/poisson_distribution.hpp>\n#include <boost/random/variate_generator.hpp>\n\nnamespace stan {\nnamespace math {\n\n/** \\ingroup prob_dists\n * Return a negative binomial random variate with the specified location and\n * precision parameters using the given random number generator.\n *\n * mu and phi can each be a scalar or a one-dimensional container. Any\n * non-scalar inputs must be the same size.\n *\n * @tparam T_loc type of location parameter\n * @tparam T_prec type of precision parameter\n * @tparam RNG type of random number generator\n * @param mu (Sequence of) positive location parameter(s)\n * @param phi (Sequence of) positive precision parameter(s)\n * @param rng random number generator\n * @return (Sequence of) negative binomial random variate(s)\n * @throw std::domain_error if mu or phi are nonpositive\n * @throw std::invalid_argument if non-scalar arguments are of different\n * sizes\n */\ntemplate <typename T_loc, typename T_prec, class RNG>\ninline typename VectorBuilder<true, int, T_loc, T_prec>::type\nneg_binomial_2_rng(const T_loc& mu, const T_prec& phi, RNG& rng) {\n  using boost::gamma_distribution;\n  using boost::variate_generator;\n  using boost::random::poisson_distribution;\n  static const char* function = \"neg_binomial_2_rng\";\n  check_positive_finite(function, \"Location parameter\", mu);\n  check_positive_finite(function, \"Precision parameter\", phi);\n  check_consistent_sizes(function, \"Location parameter\", mu,\n                         \"Precision parameter\", phi);\n\n  scalar_seq_view<T_loc> mu_vec(mu);\n  scalar_seq_view<T_prec> phi_vec(phi);\n  size_t N = max_size(mu, phi);\n  VectorBuilder<true, int, T_loc, T_prec> output(N);\n\n  for (size_t n = 0; n < N; ++n) {\n    double mu_div_phi = static_cast<double>(mu_vec[n]) / phi_vec[n];\n\n    // gamma_rng params must be positive and finite\n    check_positive_finite(function,\n                          \"Location parameter divided by the \"\n                          \"precision parameter\",\n                          mu_div_phi);\n\n    double rng_from_gamma = variate_generator<RNG&, gamma_distribution<> >(\n        rng, gamma_distribution<>(phi_vec[n], mu_div_phi))();\n\n    // same as the constraints for poisson_rng\n    check_less(function, \"Random number that came from gamma distribution\",\n               rng_from_gamma, POISSON_MAX_RATE);\n    check_not_nan(function, \"Random number that came from gamma distribution\",\n                  rng_from_gamma);\n    check_nonnegative(function,\n                      \"Random number that came from gamma distribution\",\n                      rng_from_gamma);\n\n    output[n] = variate_generator<RNG&, poisson_distribution<> >(\n        rng, poisson_distribution<>(rng_from_gamma))();\n  }\n\n  return output.data();\n}\n\n}  // namespace math\n}  // namespace stan\n#endif\n", "meta": {"hexsha": "4f93387bdfc0ea0291aeb42a0bcaaea707d251e6", "size": 3094, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "stan/math/prim/prob/neg_binomial_2_rng.hpp", "max_stars_repo_name": "HaoZeke/math", "max_stars_repo_head_hexsha": "fdf7f70dceed60f3b3f93137c6ac123a457b80a3", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-05-18T13:10:50.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-18T13:10:50.000Z", "max_issues_repo_path": "stan/math/prim/prob/neg_binomial_2_rng.hpp", "max_issues_repo_name": "HaoZeke/math", "max_issues_repo_head_hexsha": "fdf7f70dceed60f3b3f93137c6ac123a457b80a3", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2019-07-23T12:45:30.000Z", "max_issues_repo_issues_event_max_datetime": "2020-05-01T20:43:03.000Z", "max_forks_repo_path": "stan/math/prim/prob/neg_binomial_2_rng.hpp", "max_forks_repo_name": "SteveBronder/math", "max_forks_repo_head_hexsha": "3f21445458866897842878f65941c6bcb90641c2", "max_forks_repo_licenses": ["BSD-3-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.1975308642, "max_line_length": 78, "alphanum_fraction": 0.7120232708, "num_tokens": 710, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5851011542032312, "lm_q2_score": 0.5389832206876841, "lm_q1q2_score": 0.31535970452053885}}
{"text": "/*\n * Copyright (c) 2015-2016, Luca Fulchir<luca@fulchir.it>, All rights reserved.\n *\n * This file is part of \"libRaptorQ\".\n *\n * libRaptorQ is free software: you can redistribute it and/or modify\n * it under the terms of the GNU Lesser General Public License as\n * published by the Free Software Foundation, either version 3\n * of the License, or (at your option) any later version.\n *\n * libRaptorQ 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 * and a copy of the GNU Lesser General Public License\n * along with libRaptorQ.  If not, see <http://www.gnu.org/licenses/>.\n */\n\n#pragma once\n\n#include \"RaptorQ/v1/common.hpp\"\n#include \"RaptorQ/v1/degree.hpp\"\n#include \"RaptorQ/v1/Rand.hpp\"\n#include \"RaptorQ/v1/table2.hpp\"\n#include <cmath>\n#include <Eigen/Core>\n#include <vector>\n\nnamespace RaptorQ__v1 {\nnamespace Impl {\n\nclass RAPTORQ_LOCAL Tuple\n{\n    // d  1-30  LT-degree of encoded symbol\n    // a  0-(W-1)\n    // b  0-(W-1)\n    // d1 PI-degree of encoded symbol (2 or 3)\n    // a1 0-(P1-1)\n    // b1 0-(P1-1)\npublic:\n    Tuple() = default;\n    Tuple (const Tuple&) = default;\n    Tuple& operator= (const Tuple&) = default;\n    Tuple (Tuple&&) = default;\n    Tuple& operator= (Tuple&&) = default;\n    ~Tuple() = default;\n\n    uint16_t d, a, b, d1, a1, b1;   // great names. thanks rfc6330!\n};\n\nclass RAPTORQ_API Parameters\n{\npublic:\n    explicit Parameters (const uint16_t symbols);\n    Parameters() = delete;\n    Parameters (const Parameters&) = default;\n    Parameters& operator= (const Parameters&) = default;\n    Parameters (Parameters&&) = default;\n    Parameters& operator= (Parameters&&) = default;\n    ~Parameters() {}\n\n    uint16_t Deg (const uint32_t v) const;\n    Tuple tuple (const uint32_t ISI) const;\n    std::vector<uint16_t> get_idxs (const uint32_t ISI) const;\n\n    uint16_t K_padded, S, H, W, L, P, P1, U, B; // RFC 6330, pg 22\n    uint16_t J;\nprivate:\n    static bool is_prime (const uint16_t n);\n};\n\n\ninline Parameters::Parameters (const uint16_t symbols)\n{\n    uint16_t idx;\n    for (idx = 0; idx < RaptorQ__v1::Impl::K_padded.size(); ++idx) {\n        if (RaptorQ__v1::Impl::K_padded[idx] >= symbols) {\n            K_padded = RaptorQ__v1::Impl::K_padded[idx];\n            break;\n        }\n    }\n\n    J = RaptorQ__v1::Impl::J_K_padded[idx];\n    std::tie (S, H, W) = RaptorQ__v1::Impl::S_H_W [idx];\n\n    L = K_padded + S + H;\n    P = L - W;\n    U = P - H;\n    B = W - S;\n    P1 = P + 1;         // first prime number bigger than P. turns out its\n                        // always between 1 and 14 more numbers.\n    while (!is_prime (P1))  // so this while will be really quick anyway\n        ++P1;\n}\n\ninline bool Parameters::is_prime (const uint16_t n)\n{\n    // 1 as prime, don't care. Not in our scope anyway.\n    // thank you stackexchange for the code\n    if (n <= 3)\n        return true;\n    if (n % 2 == 0 || n % 3 == 0)\n        return false;\n\n    uint32_t i = 5;\n    uint32_t w = 2;\n    while (i * i <= n) {\n        if (n % i == 0)\n            return false;\n        i += w;\n        w = 6 - w;\n    }\n    return true;\n}\n\n\ninline uint16_t Parameters::Deg (const uint32_t v) const\n{\n    // rfc 6330, pg 27\n\n    for (uint16_t d = 0; d < RaptorQ__v1::Impl::degree_distribution.size();++d){\n        if (v < RaptorQ__v1::Impl::degree_distribution[d])\n            return (d < (W - 2)) ? d : (W - 2);\n    }\n    return 0;   // never get here, but don't make the compiler complain\n}\n\ninline Tuple RaptorQ__v1::Impl::Parameters::tuple (const uint32_t ISI) const\n{\n    RaptorQ__v1::Impl::Tuple ret;\n\n    // taken straight from RFC6330, pg 30\n    // so thank them for the *beautiful* names\n    // also, don't get confused with \"B\": this one is different,\n    // and thus named \"B1\"\n\n    size_t A = 53591 + J * 997;\n\n    if (A % 2 == 0)\n        ++A;\n    size_t B1 = 10267 * (J + 1);\n    uint32_t y = static_cast<uint32_t> (B1 + ISI * A);\n    uint32_t v = rnd_get (y, 0, static_cast<uint32_t> (std::pow(2, 20)));\n    ret.d = Deg (v);\n    ret.a = 1 + static_cast<uint16_t> (rnd_get (y, 1, W - 1));\n    ret.b = static_cast<uint16_t> (rnd_get (y, 2, W));\n    if (ret.d < 4) {\n        ret.d1 = 2 + static_cast<uint16_t> (rnd_get (ISI, 3, 2));\n    } else {\n        ret.d1 = 2;\n    }\n    ret.a1 = 1 + static_cast<uint16_t> (rnd_get (ISI, 4, P1 - 1));\n    ret.b1 = static_cast<uint16_t> (rnd_get (ISI, 5, P1));\n\n    return ret;\n}\n\ninline std::vector<uint16_t> Parameters::get_idxs (const uint32_t ISI) const\n{\n    // Needed to generate G_ENC: We need the ids of the symbols we would\n    // use on a \"Enc\" call. So this is the \"enc algorithm, but returns the\n    // indexes instead of computing the result.\n    // rfc6330, pg29\n\n    std::vector<uint16_t> ret;\n    Tuple t = tuple (ISI);\n\n    ret.reserve (t.d + t.d1);\n    ret.push_back (t.b);\n\n    for (uint16_t j = 1; j < t.d; ++j) {\n        t.b = (t.b + t.a) % W;\n        ret.push_back (t.b);\n    }\n    while (t.b1 >= P)\n        t.b1 = (t.b1 + t.a1) % P1;\n\n    ret.push_back (W + t.b1);\n    for (uint16_t j = 1; j < t.d1; ++j) {\n        t.b1 = (t.b1 + t.a1) % P1;\n        while (t.b1 >= P)\n            t.b1 = (t.b1 + t.a1) % P1;\n        ret.push_back (W + t.b1);\n    }\n    return ret;\n}\n\n}   // namespace Impl\n}   // namespace RaptorQ\n", "meta": {"hexsha": "87a3866427d0ead88d02cbad3dc2eb563a3acbd3", "size": 5448, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "internal/impl/libraptorq/swig/RaptorQ/v1/Parameters.hpp", "max_stars_repo_name": "pastelnetwork/go-raptorq", "max_stars_repo_head_hexsha": "70ea08ac7ea0022fd7967238c4ecb8f5e2af6e24", "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": "internal/impl/libraptorq/swig/RaptorQ/v1/Parameters.hpp", "max_issues_repo_name": "pastelnetwork/go-raptorq", "max_issues_repo_head_hexsha": "70ea08ac7ea0022fd7967238c4ecb8f5e2af6e24", "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": "internal/impl/libraptorq/swig/RaptorQ/v1/Parameters.hpp", "max_forks_repo_name": "pastelnetwork/go-raptorq", "max_forks_repo_head_hexsha": "70ea08ac7ea0022fd7967238c4ecb8f5e2af6e24", "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.375, "max_line_length": 80, "alphanum_fraction": 0.595814978, "num_tokens": 1755, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.640635868562172, "lm_q2_score": 0.49218813572079556, "lm_q1q2_score": 0.31531337382348806}}
{"text": "/*\n * Profile.cpp\n *\n *  Created on: Apr 16, 2011\n *      Author: tbabb\n */\n\n#include <time.h>\n#include <string>\n#include <iostream>\n\n#include <boost/iterator/counting_iterator.hpp>\n\n#include <geomc/function/Dual.h>\n#include <geomc/linalg/Vec.h>\n#include <geomc/linalg/Matrix.h>\n#include <geomc/random/RandomTools.h>\n#include <geomc/random/MTRand.h>\n#include <geomc/random/LCRand.h>\n#include <geomc/function/Path.h>\n#include <geomc/function/PerlinNoise.h>\n#include <geomc/function/Raster.h>\n#include <geomc/function/SphericalHarmonics.h>\n#include <geomc/shape/BinLatticePartition.h>\n#include <geomc/shape/Trace.h>\n#include <geomc/shape/Oriented.h>\n#include <geomc/shape/Intersect.h>\n#include <geomc/shape/Frustum.h>\n\n#include \"RandomBattery.h\"\n\n#define NUM_PROFILE_CASES 1024;\n\nusing namespace geom;\nusing namespace std;\n\ntemplate <typename T, index_t N> \nvoid fill_unit_vec_array(typename PointType<T,N>::point_t *dst, index_t n) {\n    Sampler<T> rntools = Sampler<T>();\n    \n    for (index_t i = 0; i < n; i++) {\n        dst[i] = rntools.template unit<N>();\n    }\n}\n\ntemplate <index_t N> void fill_unit_raw_vec_array(double dst[][N], index_t n) {\n    Sampler<double> rntools = Sampler<double>();\n    Vec<double,N> v;\n    \n    for (index_t i = 0; i < n; i++) {\n        v = rntools.template unit<N>();\n        for (index_t axis = 0; axis < N; axis++) {\n            dst[i][axis] = v[axis];\n        }\n    }\n}\n\ntemplate <typename T, index_t N> void fill_range_vec_array(Vec<T, N> *dst, index_t n, Vec<T,N> lo, Vec<T,N> hi) {\n    Sampler<double> rntools = Sampler<double>();\n    \n    for (index_t i = 0; i < n; i++) {\n        dst[i] = rntools.box(lo, hi);\n    }\n}\n\ntemplate <typename T, index_t N> void fill_range_vec_array(Vec<Dual<T>, N> *dst, index_t n, Vec<Dual<T>,N> lo, Vec<Dual<T>,N> hi) {\n    Sampler< Dual<T> > rntools = Sampler< Dual<T> >();\n    \n    for (index_t i = 0; i < n; i++) {\n        dst[i] = rntools.box(lo, hi);\n    }\n}\n\ndouble profile_vec_cross(index_t iters) {\n    const index_t n = NUM_PROFILE_CASES;\n    Vec3d v;\n    Vec3d *vecs_src = new Vec3d[n];\n    Vec3d *vecs_dst = new Vec3d[n];\n    \n    fill_unit_vec_array<double,3>(vecs_src, n);\n    \n    index_t idx = 0;\n    clock_t start = clock();\n    for (index_t i = 0; i < iters; i++) {\n        vecs_dst[idx % n] = vecs_src[idx % n].cross(vecs_src[(idx+1) % n]);\n        idx += 1;\n    }\n    clock_t end = clock();\n    \n    delete [] vecs_src;\n    delete [] vecs_dst;\n    return (end-start) / (double)CLOCKS_PER_SEC;\n}\n\ntemplate <index_t N> double profile_vec_add(index_t iters) {\n    index_t n = NUM_PROFILE_CASES;\n    Vec<double, N> *vecs_src_1 = new Vec<double,N>[n];\n    Vec<double, N> *vecs_src_2 = new Vec<double,N>[n];\n    Vec<double, N> *vecs_dst   = new Vec<double,N>[n];\n    \n    fill_unit_vec_array<double,N>(vecs_src_1, n);\n    fill_unit_vec_array<double,N>(vecs_src_2, n);\n    \n    index_t idx = 0;\n    clock_t start = clock();\n    for (index_t i = 0; i < iters; i++) {\n        vecs_dst[idx] = vecs_src_1[idx] + (vecs_src_2[idx]);\n        idx = (idx + 1) % n;\n    }\n    clock_t end = clock();\n    \n    delete [] vecs_src_1;\n    delete [] vecs_src_2;\n    delete [] vecs_dst;\n    \n    return (end-start) / (double)CLOCKS_PER_SEC;\n}\n\ntemplate <index_t N> double profile_vec_dot(index_t iters) {\n    index_t n = NUM_PROFILE_CASES;\n    Vec<double, N> *vecs_src_1 = new Vec<double,N>[n];\n    Vec<double, N> *vecs_src_2 = new Vec<double,N>[n];\n    double *vecs_dst = new double[n];\n    \n    fill_unit_vec_array<double,N>(vecs_src_1, n);\n    fill_unit_vec_array<double,N>(vecs_src_2, n);\n    \n    index_t idx = 0;\n    clock_t start = clock();\n    for (index_t i = 0; i < iters; i++) {\n        vecs_dst[idx] = vecs_src_1[idx].dot(vecs_src_2[idx]);\n        idx = (idx + 1) % n;\n    }\n    clock_t end = clock();\n    vecs_dst[0] += 1;\n    \n    delete [] vecs_src_1;\n    delete [] vecs_src_2;\n    delete [] vecs_dst;\n    \n    return (end-start) / (double)CLOCKS_PER_SEC;\n}\n\ntemplate <index_t N> double profile_vec_norm(index_t iters) {\n    index_t n = NUM_PROFILE_CASES;\n    Vec<double, N> *vecs_src = new Vec<double,N>[n];\n    double *vecs_dst = new double[n];\n    \n    fill_unit_vec_array<double,N>(vecs_src, n);\n    \n    index_t idx = 0;\n    clock_t start = clock();\n    for (index_t i = 0; i < iters; i++) {\n        vecs_dst[idx % n] = vecs_src[idx % n].mag();\n        idx += 1;\n    }\n    clock_t end = clock();\n    vecs_dst[0] += 1;\n    \n    delete [] vecs_src;\n    delete [] vecs_dst;\n    \n    return (end-start) / (double)CLOCKS_PER_SEC;\n}\n\ntemplate <index_t N> double profile_vec_norm2(index_t iters) {\n    index_t n = NUM_PROFILE_CASES;\n    Vec<double, N> *vecs_src = new Vec<double,N>[n];\n    double *vecs_dst = new double[n];\n    \n    fill_unit_vec_array<double,N>(vecs_src, n);\n    \n    index_t idx = 0;\n    clock_t start = clock();\n    for (index_t i = 0; i < iters; i++) {\n        vecs_dst[idx % n] = vecs_src[idx % n].mag2();\n        idx += 1;\n    }\n    clock_t end = clock();\n    vecs_dst[0] += 1; //shenanigans to prevent compiler from optimizing to a null loop.\n    \n    delete [] vecs_src;\n    delete [] vecs_dst;\n    \n    return (end-start) / (double)CLOCKS_PER_SEC;\n}\n\ntemplate <index_t N> double profile_vec_hash(index_t iters) {\n    index_t n = NUM_PROFILE_CASES;\n    Vec<double, N> *vecs_src = new Vec<double,N>[n];\n    index_t *vecs_dst= new index_t[n];\n    \n    fill_unit_vec_array<double,N>(vecs_src, n);\n    \n    index_t idx = 0;\n    clock_t start = clock();\n    for (index_t i = 0; i < iters; i++) {\n        vecs_dst[idx % n] = vecs_src[idx % n].hashcode();\n        idx += 1;\n    }\n    clock_t end = clock();\n    vecs_dst[0] += 1;\n    \n    delete [] vecs_src;\n    delete [] vecs_dst;\n    \n    return (end-start) / (double)CLOCKS_PER_SEC;\n}\n\n// XXX: TODO: HANDLE THIS\n\ntemplate <index_t N> double profile_raw_vec_add(index_t iters) {\n    index_t n = NUM_PROFILE_CASES;\n    double vecs_src1[n][N];\n    double vecs_src2[n][N];\n    double vecs_dst[n][N];\n    \n    fill_unit_raw_vec_array(vecs_src1, n);\n    fill_unit_raw_vec_array(vecs_src2, n);\n    \n    index_t idx = 0;\n    clock_t start = clock();\n    for (index_t i = 0; i < iters; i++) {\n        for (index_t axis = 0; axis < N; axis++) {\n            vecs_dst[idx][axis] = vecs_src1[idx][axis] + vecs_src2[idx][axis];\n        }\n        idx = (idx + 1) % n;\n    }\n    clock_t end = clock();\n    vecs_dst[0][0] += 1;\n    \n    return (end-start) / (double)CLOCKS_PER_SEC;\n}\n\ntemplate <index_t N> double profile_perlin(index_t iters) {\n    typedef typename PointType<double,N>::point_t point_t;\n    index_t n = NUM_PROFILE_CASES;\n    point_t range = point_t(100000);\n    point_t *vecs_src = new point_t[n];\n    PerlinNoise<double,N> perlin;\n    double *dest_vals = new double[n];\n    \n    fill_range_vec_array<double,N>(vecs_src, n, -range, range);\n    \n    index_t idx = 0;\n    clock_t start = clock();\n    for (index_t i = 0; i < iters; i++) {\n        dest_vals[idx] = perlin.eval(vecs_src[i % n]);\n        idx = (idx + 1) % n;\n    }\n    clock_t end = clock();\n    dest_vals[0] += 1;\n    \n    delete [] vecs_src;\n    delete [] dest_vals;\n    \n    return (end-start) / (double)CLOCKS_PER_SEC;\n}\n\ntemplate <typename T, index_t N> double profile_perlin_grad(index_t iters) {\n    typedef Dual<T> dual;\n    typedef typename PointType<dual,N>::point_t point_t;\n    \n    index_t n = NUM_PROFILE_CASES;\n    point_t range = point_t(10000);\n    point_t *vecs_src = new point_t[n];\n    PerlinNoise<dual,N> perlin;\n    dual *dest_vals = new dual[n];\n    \n    fill_range_vec_array<T,N>(vecs_src, n, -range, range);\n    \n    index_t idx = 0;\n    clock_t start = clock();\n    for (index_t i = 0; i < iters; i++) {\n        dest_vals[idx] = perlin.eval(vecs_src[i%n]);\n        idx = (idx + 1) % n;\n    }\n    clock_t end = clock();\n    \n    delete [] vecs_src;\n    delete [] dest_vals;\n    \n    return (end-start) / (double)CLOCKS_PER_SEC;\n}\n\ntemplate <typename T, index_t N> double profile_perlin_hard_grad(index_t iters) {\n    typedef typename PointType<T,N>::point_t point_t;\n    \n    index_t n = NUM_PROFILE_CASES;\n    point_t range = point_t(10000);\n    point_t *vecs_src = new point_t[n];\n    PerlinNoise<T,N> perlin;\n    point_t *dest_vals = new point_t[n];\n    \n    fill_range_vec_array<T,N>(vecs_src, n, -range, range);\n    \n    index_t idx = 0;\n    clock_t start = clock();\n    for (index_t i = 0; i < iters; i++) {\n        dest_vals[idx] = perlin.gradient(vecs_src[n]).second;\n        idx = (idx + 1) % n;\n    }\n    clock_t end = clock();\n    \n    delete [] vecs_src;\n    delete [] dest_vals;\n    \n    return (end-start) / (double)CLOCKS_PER_SEC;\n}\n\ntemplate <typename T> \ndouble profile_rayTriangleTest(index_t iters) {\n    Sampler<T> rvs;\n    static const index_t N = 3;\n    index_t n = std::sqrt(iters);\n    Ray<T,N>* rays = new Ray<T,N>[n];\n    Vec<T,N>* pts  = new Vec<T,N>[n*N];\n    \n    // generate n random rays; pts. \n    for (index_t i = 0; i < n; i++) {\n        rays[i].origin    = rvs.template unit<N>(2.0);\n        rays[i].direction = rvs.template unit<N>();\n        for (index_t j = 0; j < N; ++j) {\n            pts[i*N + j] = rvs.template unit<N>();\n        }\n    }\n    index_t hits = 0;\n\n    clock_t start = clock();\n    for (index_t i = 0; i < n; i++) {\n        Vec<T,N>* verts = pts + N * i;\n        for (index_t j = 0; j < n; ++j) {\n            hits += trace_tri(verts[0], verts[1], verts[2], rays[j], HIT_FRONT).hit;\n        }\n    }\n    clock_t end = clock();\n    \n    delete [] rays;\n\n    return (end-start) / (double)CLOCKS_PER_SEC;\n}\n\n\ntemplate <typename T, index_t N> \ndouble profile_raySimplexTest(index_t iters) {\n    Sampler<T> rvs;\n    index_t n = std::sqrt(iters);\n    Ray<T,N>* rays = new Ray<T,N>[n];\n    Vec<T,N>* pts  = new Vec<T,N>[n*N];\n    \n    // generate n random rays; pts. \n    for (index_t i = 0; i < n; i++) {\n        rays[i].origin    = rvs.template unit<N>(2.0);\n        rays[i].direction = rvs.template unit<N>();\n        for (index_t j = 0; j < N; ++j) {\n            pts[i*N + j] = rvs.template unit<N>();\n        }\n    }\n    index_t hits = 0;\n    Vec<T,N-1> srf_coords;\n    T s;\n\n    clock_t start = clock();\n    for (index_t i = 0; i < n; i++) {\n        Vec<T,N>* verts = pts + N * i;\n        for (index_t j = 0; j < n; ++j) {\n            hits += trace_simplex(verts, rays[j], &srf_coords, &s);\n        }\n    }\n    clock_t end = clock();\n    \n    delete [] rays;\n\n    return (end-start) / (double)CLOCKS_PER_SEC;\n}\n\n\ntemplate <typename T, index_t Bands> double profile_sh(index_t iters) {\n    SphericalHarmonics<T,Bands> sh;\n    index_t n = std::min(iters, (index_t)1000000);\n    Vec<T,3> *vs = new Vec<T,3>[n];\n    fill_unit_vec_array<T,3>(vs, n);\n    \n    clock_t start = clock();\n    for (index_t i = 0; i < iters; i++) {\n        Vec<T,3> v = vs[i % n];\n        sh.eval(v);\n    }\n    clock_t end = clock();\n    \n    delete [] vs;\n    \n    return (end-start) / (double)CLOCKS_PER_SEC;\n}\n\ntemplate <typename T, index_t Bands> double profile_sh_buffer(index_t iters) {\n    SphericalHarmonics<T,Bands> sh;\n    SphericalHarmonics<T,Bands> buf;\n    index_t n = std::min(iters, (index_t)1000000);\n    Vec<T,3> *vs = new Vec<T,3>[n];\n    fill_unit_vec_array<T,3>(vs, n);\n    T k = 0;\n    \n    clock_t start = clock();\n    for (index_t i = 0; i < iters; i++) {\n        Vec<T,3> v = vs[i % n];\n        spherical_harmonic_coeff(&buf, v.z, std::atan2(v.y, v.x));\n        k = sh.dot(buf);\n    }\n    clock_t end = clock();\n    \n    delete [] vs;\n    \n    return (end-start) / (double)CLOCKS_PER_SEC;\n}\n\ntemplate <typename T, index_t Bands> \nvoid test_sh_methods(index_t iters) {\n    SphericalHarmonics<T,Bands> sh;\n    SphericalHarmonics<T,Bands> buf;\n    index_t n = std::min(iters, (index_t)1000000);\n    Vec<T,3> *vs = new Vec<T,3>[n];\n    fill_unit_vec_array<T,3>(vs, n);\n    \n    std::fill(sh.coeffs.get(), sh.coeffs.get() + sh.size(), 1);\n    \n    T diff = 0;\n    T a_avg = 0;\n    T b_avg = 0;\n    \n    for (index_t i = 0; i < iters; i++) {\n        Vec<T,3> v = vs[i % n];\n        spherical_harmonic_coeff(&buf, v.z, std::atan2(v.y, v.x));\n        T a = sh.dot(buf);\n        T b = sh.eval(v);\n        a_avg += a;\n        b_avg += b;\n        diff  += std::abs(a-b);\n    }\n    \n    std::cout << \"avg sh diff: \" << diff / iters << std::endl;\n    std::cout << \"avg buf,std: \" << a_avg << \",\" << b_avg << std::endl;\n    \n    delete [] vs;\n}\n\ntemplate <typename T, index_t N> double profile_path(index_t iters) {\n    Path<T,N> p;\n    Sampler<T> rvs;\n    int n_knots = 50;\n    for (index_t i = 0; i < n_knots; i++) {\n        p.knots.push_back(Ray<T,N>(rvs.template box<N>(), rvs.template solidball<N>()));\n    }\n    clock_t start = clock();\n    for (index_t i = 0; i < iters; i++) {\n        p.eval(getRandom()->rand(0,n_knots));\n    }\n    clock_t end = clock();\n    return (end-start) / (double)CLOCKS_PER_SEC;\n}\n\ntemplate <typename T, index_t N, index_t Channels, Interpolation Interp> \ndouble profile_raster(index_t iters) {\n    static const index_t n = 128;\n    Vec<index_t,N> dim(n);\n    Raster<T,T,N,Channels> image(dim);\n    Vec<T,N> *coords = new Vec<T,N>[n];\n    Sampler<T> smp;\n    \n    // fill with random junk\n    // also make some random coords to use\n    for (index_t i = 0; i < n; i++) {\n        coords[i] = smp.box(Vec<T,N>::zeros, (Vec<T,N>)dim);\n        for (index_t j = 0; j < n; j++) {\n            image.set(Vec<index_t,N>(i,j), smp.template unit<Channels>());\n        }\n    }\n    \n    // sample in a bunch of random places.\n    clock_t start = clock();\n    for (index_t i = 0; i < iters; i++) {\n        image.template sample<EDGE_CLAMP,Interp>(coords[i % n]);\n    }\n    clock_t end = clock();\n    \n    delete [] coords;\n    \n    return (end-start) / (double)CLOCKS_PER_SEC;\n}\n\ntemplate <typename T> double profile_rotCtr(index_t iters) {\n    Sampler<T> rvs;\n    AffineTransform<T,3> xf;\n    clock_t start = clock();\n    for (index_t i = 0; i < iters; i++) {\n        T angle = rvs.rng->template rand<T>(0, 2*M_PI);\n        Vec<T,3> axis = rvs.template unit<3>();\n        Vec<T,3> ctr  = rvs.box(Vec<T,3>(-10,-10,-10), Vec<T,3>(10,10,10));\n        xf = rotation<T>(axis, ctr, angle);\n    }\n    clock_t end = clock();\n    return (end-start) / (double)CLOCKS_PER_SEC;\n}\n\ntemplate <typename M> double profile_mtxCopy(index_t iters) {\n    index_t rows = 5;\n    index_t cols = 5;\n    M m(rows,cols);\n    Random *rng = getRandom();\n    typedef typename M::elem_t T;\n    T *ary = new T[rows*cols+1];\n    for (index_t i = 0; i < rows*cols+1; i++) {\n        ary[i] = rng->rand(1.0);\n    }\n    clock_t start = clock();\n    for (index_t i = 0; i < iters; i++) {\n        std::copy(m.begin(), m.end(), ary); \n    }\n    clock_t end = clock();\n    \n    delete [] ary;\n    return (end-start) / (double)CLOCKS_PER_SEC;\n}\n\ntemplate <typename M> double profile_mtxRegionCopy(index_t iters) {\n    index_t rows = 5;\n    index_t cols = 5;\n    M m(rows,cols);\n    Random *rng = getRandom();\n    typedef typename M::elem_t T;\n    T *ary = new T[rows*cols+1];\n    for (index_t i = 0; i < rows*cols+1; i++) {\n        ary[i] = rng->rand(1.0);\n    }\n    clock_t start = clock();\n    for (index_t i = 0; i < iters; i++) {\n        MatrixRegion region(Vec<index_t,2>(1,1), Vec<index_t,2>(rows-1, cols-1));\n        std::copy(m.region_begin(region), m.region_end(region), ary);\n    }\n    clock_t end = clock();\n    \n    delete [] ary;\n    return (end-start) / (double)CLOCKS_PER_SEC;\n}\n\ntemplate <typename T, index_t N> double profile_mtxInverse(index_t iters) {\n    SimpleMatrix<T,N,N> mtx[2];\n    Random *rng = getRandom();\n    for (T *p = mtx[0].begin(); p != mtx[0].end(); p++) {\n        *p = rng->rand(1.0);\n    }\n    index_t x = 0;\n    clock_t start = clock();\n    for (index_t i = 0; i < iters; i++, x = !x) {\n        inv(&mtx[!x], mtx[x]);  \n    }\n    clock_t end = clock();\n    \n    return (end-start) / (double)CLOCKS_PER_SEC;\n}\n\ntemplate <typename T, index_t N> double profile_mtxInverseLU(index_t iters) {\n    SimpleMatrix<T,N,N> mtx[2];\n    Random *rng = getRandom();\n    for (T *p = mtx[0].begin(); p != mtx[0].end(); p++) {\n        *p = rng->rand(1.0);\n    }\n    index_t x = 0;\n    clock_t start = clock();\n    for (index_t i = 0; i < iters; i++, x = !x) {\n        PLUDecomposition<T,N,N> plu = plu_decompose(mtx[x]);\n        plu.inverse(&mtx[!x]);  \n    }\n    clock_t end = clock();\n    \n    return (end-start) / (double)CLOCKS_PER_SEC;\n}\n\ntemplate <typename T, index_t N>\nvoid randomOrient(AffineTransform<T,N> *xf) {\n    Sampler<T> smp;\n    Vec<T,N> basis[N];\n    for (index_t i = 0; i < N; i++) {\n        basis[i] = smp.template unit<N>();\n    }\n    orthonormalize(basis,N);\n    SimpleMatrix<T,N,N> rot(basis[0].begin());\n    *xf = transformation(rot);\n}\n\ntemplate <typename T>\nvoid randomOrient(AffineTransform<T,3> *xf) {\n    Sampler<T> smp;\n    Quat<T> q = smp.template unit<4>();\n    *xf = rotation(q);\n}\n\ntemplate <typename T>\nvoid randomOrient(AffineTransform<T,2> *xf) {\n    T angle =  M_PI * getRandom()->rand<T>(-1,1);\n    *xf = rotation(angle);\n}\n\ntemplate <typename T, index_t N>\nvoid randomBox(OrientedRect<T,N> *r) {\n    Sampler<T> smp;\n    \n    randomOrient(&r->xf);\n    r->xf *= scale(Vec<T,N>(getRandom()->rand<T>(2,8)));\n    r->xf *= translation(smp.template unit<N>());\n    Vec<T,N> b0 = smp.box(Vec<T,N>(-1), Vec<T,N>(1));\n    Vec<T,N> b1 = smp.box(Vec<T,N>(-1), Vec<T,N>(1));\n    r->shape = Rect<T,N>::spanning_corners(b0,b1);\n}\n\ntemplate <typename T, index_t N>\nvoid getCorners(const ViewFrustum<T,N>& f, Vec<T,N> p[1 << N]) {\n    typedef PointType<T,N-1> Pt;\n    const Frustum< Rect<T,N-1> >& f_i = f.shape;\n    typename Pt::point_t extreme[2] = { f_i.base.lo, f_i.base.hi };\n    Rect<T,1> h_clip = f_i.clipped_height();\n    \n    for (index_t k = 0; k < 2; k++) {\n        // for lower and upper extents\n        T h = k == 0 ? h_clip.lo : h_clip.hi;\n        for (index_t c = 0; c < (1 << (N-1)); c++) {\n            // for each corner of the base rect\n            Vec<T,N> pt;\n            for (index_t i = 0; i < N-1; i++) {\n                // for each coordinate of the corner point\n                pt[i] = Pt::iterator(extreme[(c & (1 << i)) != 0])[i];\n            }\n            pt[N-1] = 1;\n            pt *= h;\n            pt  = f.xf * pt;\n            p[c + ((k > 0) ? (1 <<(N-1)) : 0)] = pt;\n        }\n    }\n}\n\ntemplate <typename T, index_t N>\nvoid getCorners(const OrientedRect<T,N>& r, Vec<T,N> p[1 << N]) {\n    Vec<T,N> extreme[2] = { r.shape.lo, r.shape.hi };\n    \n    for (index_t i = 0; i < (1 << N); ++i) {\n        Vec<T,N> v;\n        for (index_t axis = 0; axis < N; ++axis) {\n            v[axis] = extreme[((i >> axis) & 1)][axis];\n        }\n        p[i] = r.xf * v;\n    }\n}\n\ntemplate <typename T>\nvoid randomFrustum(ViewFrustum<T,2>* f) {\n    Sampler<T> smp;\n    f->shape.height = Rect<T,1>::spanning_corners(\n                        getRandom()->rand<T>(-5,5), \n                        getRandom()->rand<T>(-5,5));\n    f->shape.base = Rect<T,1>::spanning_corners(\n                        getRandom()->rand<T>(-5), \n                        getRandom()->rand<T>( 5));\n    randomOrient(&f->xf);\n    f->xf *= scale(Vec<T,2>(getRandom()->rand(2,8)));\n    f->xf *= translation(smp.template unit<2>());\n}\n\ntemplate <typename T, index_t N>\nvoid randomFrustum(ViewFrustum<T,N>* f) {\n    Sampler<T> smp;\n    f->shape.height = Rect<T,1>::spanning_corners(\n                        getRandom()->rand<T>(-5,5), \n                        getRandom()->rand<T>(-5,5));\n    Vec<T,N-1> b0 = smp.box(Vec<T,N-1>(-5), Vec<T,N-1>(5));\n    Vec<T,N-1> b1 = smp.box(Vec<T,N-1>(-5), Vec<T,N-1>(5));\n    f->shape.base = Rect<T,N-1>::spanning_corners(b0, b1);\n    randomOrient(&f->xf);\n    f->xf *= scale(Vec<T,N>(getRandom()->rand(2,8)));\n    f->xf *= translation(smp.template unit<N>());\n}\n\ntemplate <typename T, index_t N> double profile_gjkIntersect(index_t iters) {\n    const index_t n = (index_t)std::ceil(std::sqrt(iters));\n    const index_t n_corners = 1 << N;\n    //Vec<T,N> *rects = new Vec<T,N>[n*n_corners];\n    OrientedRect<T,N> *rects = new OrientedRect<T,N>[n];\n    bool b = true;\n    for (index_t i = 0; i < n; i++) {\n        //OrientedRect<T,N> r;\n        randomBox(rects+i);\n        //r.getCorners(rects + n_corners*i);\n    }\n    \n    Vec<T,N> d;\n    index_t i0 = 0;\n    index_t i1 = 0;\n    clock_t start = clock();\n    for (index_t j = 0; j < iters; j++) {\n        i0 = (i0 + 1) % n;\n        if (i0 == 0) i1 = (i1 + 1) % n;\n        //b = b ^ gjk_intersect(rects + n_corners*i0, n_corners, rects + n_corners*i1, n_corners, &d);\n        b = b ^ gjk_intersect(rects[i0], rects[i1], &d);\n    }\n    clock_t end = clock();\n    delete [] rects;\n    \n    return (end-start) / (double)CLOCKS_PER_SEC;\n}\n\ntemplate <typename T, index_t N> double profile_OBB_intersect(index_t iters) {\n    const index_t n = (index_t)std::ceil(std::sqrt(iters));\n    OrientedRect<T,N> *boxes = new OrientedRect<T,N>[n];\n    bool b = true;\n    for (index_t i = 0; i < n; i++) {\n        randomBox(boxes + i);\n    }\n    \n    Vec<T,N> d;\n    index_t i0 = 0;\n    index_t i1 = 0;\n    clock_t start = clock();\n    bool SAT = false;\n    for (index_t j = 0; j < iters; j++) {\n        i0 = (i0 + 1) % n;\n        if (i0 == 0) i1 = (i1 + 1) % n;\n        SAT = SAT ^ boxes[i0].intersects(boxes[i1]);\n    }\n    clock_t end = clock();\n    \n    delete [] boxes;\n    \n    return (end-start) / (double)CLOCKS_PER_SEC;\n}\n\ntemplate <typename T, index_t N> double profile_OBB_bounds(index_t iters) {\n    index_t n = std::min(iters, (index_t)100000);\n    OrientedRect<T,N> *boxes = new OrientedRect<T,N>[n];\n    for (index_t i = 0; i < n; i++) randomBox(boxes + i);\n    \n    clock_t s = 0;\n    Vec<T,N> z;\n    \n    for (index_t k = 0; k < iters; k += n) {\n        index_t nn = std::min(iters - k, n);\n        \n        Rect<T,N> r;\n        \n        clock_t start = clock();\n        for (index_t j = 0; j < nn; j++) {\n            r  = boxes[j].bounds();\n            z += r.hi;\n        }\n        clock_t end = clock();\n        \n        s += end - start;\n    }\n    \n    delete [] boxes;\n    return s / (double)CLOCKS_PER_SEC;;\n}\n\n//#define EMIT_GJK_ERRS\n//#define EMIT_GJK_ALL\n\n// this is tautological for N > 3. OBBs use GJK directly!\ntemplate <typename T, index_t N> index_t test_gjkIntersect(index_t iters) {\n    const index_t n = (index_t)std::ceil(std::sqrt(iters));\n    OrientedRect<T,N>* boxes = new OrientedRect<T,N>[n];\n    bool b = true;\n    for (index_t i = 0; i < n; i++) {\n        randomBox(boxes + i);\n    }\n    const index_t n_corners = 1 << N;\n    \n    Vec<T,N> d;\n    index_t i0 = 0;\n    index_t i1 = 0;\n    index_t failures = 0;\n    index_t positive = 0;\n    index_t negative = 0;\n    for (index_t j = 0; j < iters; j++) {\n        i0 = (i0 + 1) % n;\n        if (i0 == 0) i1 = (i1 + 1) % n;\n        Vec<T,N> b0[n_corners];\n        Vec<T,N> b1[n_corners];\n        getCorners(boxes[i0], b0);\n        getCorners(boxes[i1], b1);\n        bool print = false;\n#ifdef EMIT_GJK_ALL\n        print = true;\n#endif\n        bool gjk = gjk_intersect(b0, n_corners, b1, n_corners, &d); //, print);\n        bool SAT = boxes[i0].intersects(boxes[i1]);\n        if (gjk != SAT) {\n#ifdef EMIT_GJK_ERRS\n            gjk_intersect(b0, n_corners, b1, n_corners, &d); //, true);\n            std::cout << \".\\n\";\n#endif\n            failures++;\n        }\n#ifdef EMIT_GJK_ALL\n        std::cout << \".\\n\";\n#endif\n        if (SAT) positive++;\n        else negative++;\n    }\n    \n    delete [] boxes;\n\n#if !defined(EMIT_GJK_ERRS) and !defined(EMIT_GJK_ALL)\n    std::cout << \"gjk \" << N << \"D failures: \" << failures;\n    std::cout << \" (\" << positive << \" overlapped \" << negative << \" disjoint)\" << std::endl;\n#endif\n    \n    return failures;\n}\n\n\ntemplate <typename T, index_t N> T test_gjkNearest(index_t iters) {\n    const index_t n = (index_t)std::ceil(std::sqrt(iters));\n    OrientedRect<T,N>* boxes = new OrientedRect<T,N>[n];\n    bool b = true;\n    for (index_t i = 0; i < n; i++) {\n        randomBox(boxes + i);\n    }\n    \n    Vec<T,N> d;\n    index_t i0 = 0;\n    index_t i1 = 0;\n    T olap_sum = 0;\n    T disj_sum = 0;\n    index_t olap_n = 0;\n    index_t disj_n = 0;\n    for (index_t j = 0; j < iters; j++) {\n        i0 = (i0 + 1) % n;\n        if (i0 == 0) i1 = (i1 + 1) % n;\n        OrientedRect<T,N>& b0 = boxes[i0];\n        OrientedRect<T,N>& b1 = boxes[i1];\n        \n        Vec<T,N> axi;\n        bool olap = minimal_separation_axis(b0, b1, &axi);\n        Vec<T,N> contact = b1.convexSupport(axi) + axi;\n        T dist = (b0.convexSupport(-axi) - contact).mag();\n        \n        // tally error\n        if (olap) {\n            olap_sum += dist;\n            olap_n++;\n        } else {\n            disj_sum += dist;\n            disj_n++;\n        }\n    }\n    \n    delete [] boxes;\n    \n    std::cout << \"gjk \" << N << \"D nearest axis:\" << std::endl;\n    std::cout << \"  overlap mean error:  \" << (olap_sum / olap_n) << std::endl;\n    std::cout << \"  disjoint mean error: \" << (disj_sum / disj_n) << std::endl;\n    return (olap_sum + disj_sum) / iters;\n}\n\ntemplate <typename T, index_t N> index_t test_frustumSupport(index_t iters) {\n    const index_t n = (index_t)std::ceil(std::sqrt(iters));\n    const index_t n_corners = 1 << N;\n    \n    Sampler<T> smp;\n    T err = 0;\n    \n    index_t failures = 0;\n    for (index_t j = 0; j < iters/100; j++) {\n        ViewFrustum<T,N> f;\n        randomFrustum(&f);\n        Vec<T,N> pts[n_corners];\n        getCorners(f, pts);\n        for (index_t k = 0; k < 100; k++) {\n            Vec<T,N> d = smp.template unit<N>();\n            Vec<T,N> p0 = f.convexSupport(d);\n            Vec<T,N> p1 = pts[0];\n            T dot0 = p1.dot(d);\n            // brute force find support point\n            for (index_t c = 1; c < n_corners; c++) {\n                T dot1 = pts[c].dot(d);\n                if (dot1 > dot0) {\n                    dot0 = dot1;\n                    p1 = pts[c];\n                }\n            }\n            if (p0 != p1) {\n                err += p1.dist(p0);\n                failures++;\n            }\n        }\n    }\n    \n    std::cout << \"frustum support \" << N << \"D failures: \" << failures;\n    std::cout << \" (\" << (100 * failures / (double)iters) << \"%)\";\n    std::cout << \" average mismatch: \" << (err / (double)iters) << std::endl;\n    \n    return failures;\n}\n\n\ntemplate <typename T, index_t N> void test_mtxInverse(index_t iters) {\n    SimpleMatrix<T,N,N> mtx[2];\n    Random *rng = getRandom();\n    for (T *p = mtx[0].begin(); p != mtx[0].end(); p++) {\n        *p = rng->rand(1.0);\n    }\n    std::cout << mtx[0];\n    index_t x = 0;\n    for (index_t i = 0; i < iters; i++, x = !x) {\n        inv(&mtx[!x], mtx[x]);\n        std::cout << mtx[!x];\n    }\n}\n\ntemplate <typename M> void test_mtxRegionCopy(index_t rows, index_t cols) {\n    M m(rows,cols);\n    typedef typename M::elem_t T;\n    const index_t subn = (rows-2)*(cols-2);\n    T *v = new T[subn];\n    \n    for (index_t i = 0; i < subn; i++) {\n        v[i] = 11*i;\n    }\n    \n    std::fill(m.begin(), m.end(), 1);\n    std::copy(v, v+subn, m.region_begin(1,1,rows-1, cols-1));\n    cout << m;\n}\n\ntemplate <typename T, index_t N> void test_OOBB() {\n    OrientedRect<T,N> r1;\n    OrientedRect<T,N> r2;\n    cout << \"box1 intersects box2: \" << r1.intersects(r2) << endl;\n}\n\ntemplate <typename T, index_t M, index_t N> void test_mtxArithmetic(index_t rows, index_t cols) {\n    SimpleMatrix<T,M,N> a(rows,cols);\n    SimpleMatrix<T,M,N> b(rows,cols);\n    SimpleMatrix<T,M,N == 0 ? 0 : N+1> bogus(rows,cols+1);\n    \n    cout << \"addTest:\" << endl;\n    cout << a + b << endl;\n    cout << a * 3 << endl;\n    cout << 3 * a << endl;\n    //correctly does not compile:\n    //cout << a + bogus << endl;\n}\n\ntemplate <index_t N> void test_permuteMatrix() {\n    PermutationMatrix<N> p;\n    PermutationMatrix<N> p1;\n    Vec<double,N> v;\n    Random *rng = getRandom();\n    for (index_t i = 0; i < N; i++) {\n        v[i] = i;\n    }\n    for (index_t i = 0; i < N*2; i++) {\n        p.swap_rows(rng->rand(N), rng->rand(N));\n        p1.swap_rows(rng->rand(N), rng->rand(N));\n    }\n    SimpleMatrix<double,N,N> m;\n    SimpleMatrix<double,N,N> minv;\n    SimpleMatrix<double,N,N> m_p1;\n    std::copy(p.begin(), p.end(),  m.begin());\n    std::copy(p1.begin(), p1.end(),  m_p1.begin());\n    inv(&minv, p);\n    bool correct = (p * p1) == (m * m_p1);\n    if (!correct) throw \"permutation matrix failure\";\n    cout << \"v: \" << v << endl;\n    cout << \"P: \" << endl << p << endl;\n    cout << \"P*v: \" << (p * v) << endl;\n    cout << \"M: \" << endl << m << endl;\n    cout << \"M*v: \" << (m * v) << endl;\n    cout << \"P * P1: \" << (p * p1) << endl;\n    cout << \"P * P1 correct? \" << correct << endl;\n    cout << \"P^-1: \" << endl << minv << endl;\n}\n\ntemplate <index_t M, index_t N> void test_simpleMatrix() {\n    SimpleMatrix<double, M, N> m;\n    SimpleMatrix<double, DYNAMIC_DIM, DYNAMIC_DIM> q(M,N);\n    m[0][1] = 5;\n    q[0][1] = 8;\n    cout << m << endl;\n    cout << q << endl;\n}\n\nvoid profile(std::string name, double (*fnc)(index_t), index_t iterations) {\n    double t = fnc(iterations);\n    std::cout << name << \" (\" << iterations << \" iters): \" << t << \" secs; \" << iterations/t << \" ops/sec\"  << std::endl;\n}\n\nvoid test_matrix_asplode() {\n    SimpleMatrix<double,4,4> mtx;\n    SimpleMatrix<double,2,5> other;\n    // correctly, won't compile:\n    // mtx * other;\n}\n\nvoid test_dual() {\n    typedef Dual<double> duald;\n    cout << \"sin(pi): \" << sin(duald(PI,1)) << endl;\n    cout << \"cos(pi): \" << cos(duald(PI,1)) << endl;\n    cout << \"tan(pi): \" << tan(duald(PI,1)) << endl;\n    cout << \"2x + 1, @x=3: \" << (duald(3,1) * 2 + 1) << endl;\n    cout << \"exp(1): \" << exp(duald(1,1)) << endl;\n    cout << \"pow(x,x) @x=2: \" << pow(duald(2,1), duald(2,1)) << endl;\n    cout << \"pow(x=2,2): \" << pow(duald(2,1), 2) << endl;\n    cout << endl;\n}\n\nusing geom::operator<<;\n\n#if defined(EMIT_GJK_ERRS) or defined(EMIT_GJK_ALL)\nint main(int argc, char** argv) {\n    test_gjkIntersect<double,3>(100000);\n    return 0;\n}\n#else\n\nint main(int argc, char** argv) {\n    Vec2d a2d;\n    Vec3d a3d;\n    Vec4d a4d;\n    \n    //test_gjkNearest<double,3>(1000);\n    \n    index_t iters = 10000000;\n    \n    assert(&a2d.get(0) == &a2d.x && &a2d.get(1) == &a2d.y);\n    assert(&a3d.get(0) == &a3d.x && &a3d.get(1) == &a3d.y && &a3d.get(2) == &a3d.z);\n    assert(&a4d.get(0) == &a4d.x && &a4d.get(1) == &a4d.y && &a4d.get(2) == &a4d.z && &a4d.get(3) == &a4d.w);\n    \n    test_permuteMatrix<5>();\n    test_simpleMatrix<4,3>();\n    test_mtxArithmetic<double,4,3>(4,3);\n    test_dual();\n    test_OOBB<double,3>();\n    test_gjkIntersect<double,2>(1000000);\n    test_gjkIntersect<double,3>(1000000);\n    // test_gjkNearest<double,2>(1000000);\n    // test_gjkNearest<double,3>(1000);\n    \n#ifdef ENABLE_FRUSTUM\n    test_frustumSupport<double,2>(1000000);\n    test_frustumSupport<double,3>(1000000);\n    test_frustumSupport<double,4>(1000000);\n    std::cout << std::endl;\n#endif\n    \n    profile(\"3d cross product\", profile_vec_cross, iters);\n    std::cout << std::endl;\n    \n    profile(\"2d add\", profile_vec_add<2>, iters);\n    profile(\"3d add\", profile_vec_add<3>, iters);\n    profile(\"4d add\", profile_vec_add<4>, iters);\n    profile(\"8d add\", profile_vec_add<8>, iters);\n    std::cout << std::endl;\n    \n    profile(\"2d raw add\", profile_raw_vec_add<2>, iters);\n    profile(\"3d raw add\", profile_raw_vec_add<3>, iters);\n    profile(\"4d raw add\", profile_raw_vec_add<4>, iters);\n    profile(\"8d raw add\", profile_raw_vec_add<8>, iters);\n    std::cout << std::endl;\n    \n    profile(\"2d norm\", profile_vec_norm<2>, iters);\n    profile(\"3d norm\", profile_vec_norm<3>, iters);\n    profile(\"4d norm\", profile_vec_norm<4>, iters);\n    profile(\"8d norm\", profile_vec_norm<8>, iters);\n    std::cout << std::endl;\n    \n    profile(\"2d norm2\", profile_vec_norm2<2>, iters);\n    profile(\"3d norm2\", profile_vec_norm2<3>, iters);\n    profile(\"4d norm2\", profile_vec_norm2<4>, iters);\n    profile(\"8d norm2\", profile_vec_norm2<8>, iters);\n    std::cout << std::endl;\n    \n    //profile(\"1d perlin\", profile_perlin<1>, iters/100);\n    profile(\"2d perlin\", profile_perlin<2>, iters/100);\n    profile(\"3d perlin\", profile_perlin<3>, iters/100);\n    profile(\"4d perlin\", profile_perlin<4>, iters/100);\n    profile(\"5d perlin\", profile_perlin<5>, iters/100);\n    std::cout << std::endl;\n    \n    //profile(\"1d perlin dual\", profile_perlin_grad<double,1>, iters/100);\n    profile(\"2d perlin dual\", profile_perlin_grad<double,2>, iters/100);\n    profile(\"3d perlin dual\", profile_perlin_grad<double,3>, iters/100);\n    profile(\"4d perlin dual\", profile_perlin_grad<double,4>, iters/100);\n    std::cout << std::endl;\n    \n    //profile(\"1d perlin grad\", profile_perlin_hard_grad<double,1>, iters/100);\n    profile(\"2d perlin grad\", profile_perlin_hard_grad<double,2>, iters/100);\n    profile(\"3d perlin grad\", profile_perlin_hard_grad<double,3>, iters/100);\n    profile(\"4d perlin grad\", profile_perlin_hard_grad<double,4>, iters/100);\n    std::cout << std::endl;\n    \n    profile(\"2d hash\", profile_vec_hash<2>, iters);\n    profile(\"3d hash\", profile_vec_hash<3>, iters);\n    profile(\"4d hash\", profile_vec_hash<4>, iters);\n    std::cout << std::endl;\n    \n    profile(\"2d dot\", profile_vec_dot<2>, iters);\n    profile(\"3d dot\", profile_vec_dot<3>, iters);\n    profile(\"4d dot\", profile_vec_dot<4>, iters);\n    profile(\"8d dot\", profile_vec_dot<8>, iters);\n    std::cout << std::endl;\n    \n    profile(\"ray3f-triangle hit\",     profile_rayTriangleTest<float>,       iters/10);\n    profile(\"ray3d-triangle hit\",     profile_rayTriangleTest<double>,      iters/10);\n    profile(\"ray3d-simplex hit\",      profile_raySimplexTest<double,3>,     iters/10);\n    profile(\"ray4d-simplex hit\",      profile_raySimplexTest<double,4>,     iters/10);\n    profile(\"ray5d-simplex hit\",      profile_raySimplexTest<double,5>,     iters/10);\n    \n    std::cout << std::endl;\n    \n    profile(\"2d path\", profile_path<double, 2>, iters);\n    profile(\"3d path\", profile_path<double, 3>, iters);\n    profile(\"4d path\", profile_path<double, 4>, iters);\n    profile(\"2f path\", profile_path<float, 2>,  iters);\n    profile(\"3f path\", profile_path<float, 3>,  iters);\n    profile(\"4f path\", profile_path<float, 4>,  iters);\n    std::cout << std::endl;\n    \n    profile(\"OBB 2f bounds\", profile_OBB_bounds<float,2>,  iters / 10);\n    profile(\"OBB 3f bounds\", profile_OBB_bounds<float,3>,  iters / 10);\n    profile(\"OBB 4f bounds\", profile_OBB_bounds<float,4>,  iters / 10);\n    profile(\"OBB 2d bounds\", profile_OBB_bounds<double,2>, iters / 10);\n    profile(\"OBB 3d bounds\", profile_OBB_bounds<double,3>, iters / 10);\n    profile(\"OBB 4d bounds\", profile_OBB_bounds<double,3>, iters / 10);\n    std::cout << std::endl;\n    \n    profile(\"sh  3f band\", profile_sh<float, 3>,  iters/10);\n    profile(\"sh  8f band\", profile_sh<float, 8>,  iters/50);\n    profile(\"sh 16f band\", profile_sh<float, 16>, iters/100);\n    profile(\"sh  3d band\", profile_sh<double, 3>,  iters/10);\n    profile(\"sh  8d band\", profile_sh<double, 8>,  iters/50);\n    profile(\"sh 16d band\", profile_sh<double, 16>, iters/100);\n    std::cout << std::endl;\n    \n    profile(\"2f->3f linear img sample\", profile_raster<float, 2, 3, INTERP_LINEAR>, iters/100);\n    profile(\"3f->3f linear img sample\", profile_raster<float, 3, 3, INTERP_LINEAR>, iters/100);\n    profile(\"2f->3f cubic img sample\",  profile_raster<float, 2, 3, INTERP_CUBIC>,  iters/100);\n    profile(\"3f->3f cubic img sample\",  profile_raster<float, 3, 3, INTERP_CUBIC>,  iters/100);\n    std::cout << std::endl;\n    \n    profile(\"5x5 mtxf region copy\",    profile_mtxRegionCopy<SimpleMatrix<float,0,0> >,    iters);\n    profile(\"5x5 mtxd region copy\",    profile_mtxRegionCopy<SimpleMatrix<double,0,0> >,   iters);\n    profile(\"5x5 diagf region copy\",   profile_mtxRegionCopy<DiagMatrix<float,5,5> >, iters);\n    std::cout << std::endl;\n\n    profile(\"5x5 mtxf copy\",    profile_mtxCopy<SimpleMatrix<float,0,0> >, iters/100);\n    profile(\"5x5 mtxd copy\",    profile_mtxCopy<SimpleMatrix<double,0,0> >, iters/100);\n    profile(\"5x5 diagf copy\",   profile_mtxCopy<DiagMatrix<float,5,5> >, iters/100);   // xxx: memory error in here?!\n    std::cout << std::endl;\n    \n    profile(\"2x2 mtxf inv\", profile_mtxInverse<float,2>,  iters/10);\n    profile(\"3x3 mtxf inv\", profile_mtxInverse<float,3>,  iters/10);\n    profile(\"4x4 mtxf inv\", profile_mtxInverse<float,4>,  iters/10);\n    profile(\"2x2 mtxd inv\", profile_mtxInverse<double,2>, iters/10);\n    profile(\"3x3 mtxd inv\", profile_mtxInverse<double,3>, iters/10);\n    profile(\"4x4 mtxd inv\", profile_mtxInverse<double,4>, iters/10);\n    profile(\"8x8 mtxd inv\", profile_mtxInverse<double,8>, iters/10);\n    std::cout << std::endl;\n    \n    profile(\"rotationd matrix\", profile_rotCtr<double>, iters/10);\n    profile(\"rotationf matrix\", profile_rotCtr<float>, iters/10);\n    std::cout << std::endl;\n    \n    profile(\"gjk float 2d\",  profile_gjkIntersect<float,2>,  1000000);\n    profile(\"gjk double 2d\", profile_gjkIntersect<double,2>, 1000000);\n    profile(\"gjk float 3d\",  profile_gjkIntersect<float,3>,  1000000);\n    profile(\"gjk double 3d\", profile_gjkIntersect<double,3>, 1000000);\n    profile(\"gjk float 4d\",  profile_gjkIntersect<float,4>,  100000);\n    profile(\"gjk double 4d\", profile_gjkIntersect<double,4>, 100000);\n    profile(\"gjk double 5d\", profile_gjkIntersect<double,5>, 100000);\n    std::cout << std::endl;\n    \n    profile(\"SAT 2D OBB double\", profile_OBB_intersect<double,2>, 1000000);\n    profile(\"SAT 3D OBB double\", profile_OBB_intersect<double,3>, 1000000);\n    std::cout << std::endl;\n\n    std::cout << \"sizeof vec2f: \" << sizeof(Vec<float,2>) << std::endl;\n    std::cout << \"sizeof vec3f: \" << sizeof(Vec<float,3>) << std::endl;\n    std::cout << \"sizeof vec4f: \" << sizeof(Vec<float,4>) << std::endl;\n    std::cout << \"sizeof vec2d: \" << sizeof(Vec<double,2>) << std::endl;\n    std::cout << \"sizeof vec3d: \" << sizeof(Vec<double,3>) << std::endl;\n    std::cout << \"sizeof vec4d: \" << sizeof(Vec<double,4>) << std::endl;\n    \n    try {\n        test_matrix_asplode();\n    } catch (GeomException &ex) {\n        std::cout << ex.what() << std::endl << std::endl;\n    }\n    \n    /*\n    std::cout << \"Mersenne Twister\" << std::endl << \"================================\" << std::endl;\n    RandomBattery bat = RandomBattery(new MTRand());\n    bat.runAll(iters);\n    std::cout << std::endl;\n    \n    std::cout << \"Linear Congruential\" << std::endl << \"================================\" << std::endl;\n    bat = RandomBattery(new LCRand());\n    bat.runAll(iters);\n    std::cout << std::endl;\n    */\n    \n    std::cout << \"done.\" << std::endl;\n    \n    return 0;\n}\n\n#endif\n\n", "meta": {"hexsha": "4c823736072d2dc8a0db0cd85c5c10c18cac5dc8", "size": 38491, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/profile.cpp", "max_stars_repo_name": "trbabb/geomc", "max_stars_repo_head_hexsha": "98685137a8e500403c0945c781b541f63108d2ec", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 35.0, "max_stars_repo_stars_event_min_datetime": "2015-07-22T20:33:08.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-28T00:16:16.000Z", "max_issues_repo_path": "test/profile.cpp", "max_issues_repo_name": "trbabb/geomc", "max_issues_repo_head_hexsha": "98685137a8e500403c0945c781b541f63108d2ec", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2015-08-13T14:28:07.000Z", "max_issues_repo_issues_event_max_datetime": "2018-03-29T00:04:47.000Z", "max_forks_repo_path": "test/profile.cpp", "max_forks_repo_name": "trbabb/geomc", "max_forks_repo_head_hexsha": "98685137a8e500403c0945c781b541f63108d2ec", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2016-10-03T10:30:55.000Z", "max_forks_repo_forks_event_max_datetime": "2016-12-06T18:14:18.000Z", "avg_line_length": 31.6277732128, "max_line_length": 131, "alphanum_fraction": 0.5681068302, "num_tokens": 12399, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.640635854839898, "lm_q2_score": 0.49218813572079556, "lm_q1q2_score": 0.3153133670695476}}
{"text": "#include <bsplines/BSplinePose.hpp>\n#include <sm/assert_macros.hpp>\n// boost::tie\n#include <boost/tuple/tuple.hpp>\n#include <sm/kinematics/transformations.hpp>\n\nusing namespace sm::kinematics;\nusing namespace bsplines;\n\nBSplinePose::BSplinePose(int splineOrder, const RotationalKinematics::Ptr& rotationalKinematics)\n    : BSpline(splineOrder), rotation_(rotationalKinematics) {}\n\nBSplinePose::~BSplinePose() {}\n\nEigen::Matrix4d BSplinePose::transformation(double tk) const { return curveValueToTransformation(eval(tk)); }\n\nEigen::Matrix4d BSplinePose::transformationAndJacobian(double tk, Eigen::MatrixXd* J,\n                                                       Eigen::VectorXi* coefficientIndices) const {\n    Eigen::MatrixXd JS;\n    Eigen::VectorXd p;\n    p = evalDAndJacobian(tk, 0, &JS, coefficientIndices);\n\n    Eigen::MatrixXd JT;\n    Eigen::Matrix4d T = curveValueToTransformationAndJacobian(p, &JT);\n\n    if (J) {\n        *J = JT * JS;\n    }\n\n    return T;\n}\n\nEigen::Matrix3d BSplinePose::orientationAndJacobian(double tk, Eigen::MatrixXd* J,\n                                                    Eigen::VectorXi* coefficientIndices) const {\n    Eigen::Matrix3d C;\n    Eigen::MatrixXd JS;\n    Eigen::VectorXd p;\n    p = evalDAndJacobian(tk, 0, &JS, coefficientIndices);\n\n    Eigen::Matrix3d S;\n    C = rotation_->parametersToRotationMatrix(p.tail<3>(), &S);\n\n    Eigen::MatrixXd JO = Eigen::MatrixXd::Zero(3, 6);\n    JO.block(0, 3, 3, 3) = S;\n    if (J) {\n        *J = JO * JS;\n    }\n\n    return C;\n}\n\nEigen::Matrix3d BSplinePose::inverseOrientationAndJacobian(double tk, Eigen::MatrixXd* J,\n                                                           Eigen::VectorXi* coefficientIndices) const {\n    Eigen::Matrix3d C;\n    Eigen::MatrixXd JS;\n    Eigen::VectorXd p;\n    p = evalDAndJacobian(tk, 0, &JS, coefficientIndices);\n\n    Eigen::Matrix3d S;\n    C = rotation_->parametersToRotationMatrix(p.tail<3>(), &S).transpose();\n\n    Eigen::MatrixXd JO = Eigen::MatrixXd::Zero(3, 6);\n    JO.block(0, 3, 3, 3) = S;\n    if (J) {\n        *J = -C * JO * JS;\n    }\n\n    return C;\n}\n\nEigen::Matrix4d BSplinePose::inverseTransformationAndJacobian(double tk, Eigen::MatrixXd* J,\n                                                              Eigen::VectorXi* coefficientIndices) const {\n    // std::cout << __FUNCTION__ << \"()\\n\";\n    // ASRL_THROW(std::runtime_error,\"Not Implemented\");\n    Eigen::MatrixXd JS;\n    Eigen::VectorXd p;\n    p = evalDAndJacobian(tk, 0, &JS, coefficientIndices);\n\n    Eigen::MatrixXd JT;\n    Eigen::Matrix4d T = curveValueToTransformationAndJacobian(p, &JT);\n    // Invert the transformation.\n    T.topLeftCorner<3, 3>().transposeInPlace();\n    T.topRightCorner<3, 1>() = (-T.topLeftCorner<3, 3>() * T.topRightCorner<3, 1>()).eval();\n\n    if (J) {\n        // The \"box times\" is the linearized transformation way of inverting the jacobian.\n        *J = -sm::kinematics::boxTimes(T) * JT * JS;\n    }\n\n    if (coefficientIndices) {\n        *coefficientIndices = localCoefficientVectorIndices(tk);\n    }\n\n    return T;\n}\n\nEigen::Matrix4d BSplinePose::inverseTransformation(double tk) const {\n    Eigen::Matrix4d T = curveValueToTransformation(eval(tk));\n    T.topLeftCorner<3, 3>().transposeInPlace();\n    T.topRightCorner<3, 1>() = (-T.topLeftCorner<3, 3>() * T.topRightCorner<3, 1>()).eval();\n    return T;\n}\n\nEigen::Vector4d BSplinePose::transformVectorAndJacobian(double tk, const Eigen::Vector4d& v_tk, Eigen::MatrixXd* J,\n                                                        Eigen::VectorXi* coefficientIndices) const {\n    Eigen::MatrixXd JT;\n    Eigen::Matrix4d T_n_vk = transformationAndJacobian(tk, &JT, coefficientIndices);\n    Eigen::Vector4d v_n = T_n_vk * v_tk;\n\n    if (J) {\n        *J = sm::kinematics::boxMinus(v_n) * JT;\n    }\n\n    return v_n;\n}\n\n// Position at certain time. p = x[:3]\nEigen::Vector3d BSplinePose::position(double tk) const { return eval(tk).head<3>(); }\n\n// Orientation at certain time, phi = x[3:], R = Exp(phi)\nEigen::Matrix3d BSplinePose::orientation(double tk) const {\n    return rotation_->parametersToRotationMatrix(eval(tk).tail<3>());\n}\n\nEigen::Matrix3d BSplinePose::inverseOrientation(double tk) const {\n    return rotation_->parametersToRotationMatrix(eval(tk).tail<3>()).transpose();\n}\n\n// v_W = dp/dt\nEigen::Vector3d BSplinePose::linearVelocity(double tk) const { return evalD(tk, 1).head<3>(); }\n\n// v_B = R_BW * v_W = R_WB^T * dp/dt\nEigen::Vector3d BSplinePose::linearVelocityBodyFrame(double tk) const {\n    Eigen::VectorXd r = evalD(tk, 0);\n    Eigen::Matrix3d C_wb = rotation_->parametersToRotationMatrix(r.tail<3>());\n    return C_wb.transpose() * evalD(tk, 1).head<3>();\n}\n\n// a_W = dp^2/dt^2\nEigen::Vector3d BSplinePose::linearAcceleration(double tk) const { return evalD(tk, 2).head<3>(); }\n\n// a_B = R_BW * a_W = R_WB^T * dp^2/dt^2\nEigen::Vector3d BSplinePose::linearAccelerationBodyFrame(double tk) const {\n    Eigen::VectorXd r = evalD(tk, 0);\n    Eigen::Matrix3d C_wb = rotation_->parametersToRotationMatrix(r.tail<3>());\n    return C_wb.transpose() * evalD(tk, 2).head<3>();\n}\n\nEigen::Vector3d BSplinePose::linearAccelerationAndJacobian(double tk, Eigen::MatrixXd* J,\n                                                           Eigen::VectorXi* coefficientIndices) const {\n    Eigen::Vector3d a = evalDAndJacobian(tk, 2, J, coefficientIndices).head<3>();\n    if (J) {\n        J->conservativeResize(3, J->cols());\n    }\n    return a;\n}\n\n// \\omega_w_{b,w} (angular velocity of the body frame as seen from the world frame, expressed in the world frame)\nEigen::Vector3d BSplinePose::angularVelocity(double tk) const {\n    Eigen::Vector3d omega;\n    Eigen::VectorXd r = evalD(tk, 0);\n    Eigen::VectorXd v = evalD(tk, 1);\n\n    // \\omega = S(\\bar \\theta) \\dot \\theta\n    omega = -rotation_->parametersToSMatrix(r.tail<3>()) * v.tail<3>();\n    return omega;\n}\n\n// \\omega_b_{w,b} (angular velocity of the world frame as seen from the body frame, expressed in the body frame)\nEigen::Vector3d BSplinePose::angularVelocityBodyFrame(double tk) const {\n    Eigen::Vector3d omega;\n    Eigen::VectorXd r = evalD(tk, 0);\n    Eigen::VectorXd v = evalD(tk, 1);\n    Eigen::Matrix3d S;\n    Eigen::Matrix3d C_w_b = rotation_->parametersToRotationMatrix(r.tail<3>(), &S);\n\n    // \\omega = S(\\bar \\theta) \\dot \\theta\n    omega = -C_w_b.transpose() * S * v.tail<3>();\n    return omega;\n}\n\n// \\omega_b_{w,b} (angular velocity of the world frame as seen from the body frame, expressed in the body frame)\nEigen::Vector3d BSplinePose::angularVelocityBodyFrameAndJacobian(double tk, Eigen::MatrixXd* J,\n                                                                 Eigen::VectorXi* coefficientIndices) const {\n    Eigen::Vector3d omega;\n    Eigen::Vector3d p;\n    Eigen::Vector3d pdot;\n    Eigen::MatrixXd Jp;\n    Eigen::MatrixXd Jpdot;\n    p = evalDAndJacobian(tk, 0, &Jp, NULL).tail<3>();\n    pdot = evalDAndJacobian(tk, 1, &Jpdot, coefficientIndices).tail<3>();\n\n    Eigen::MatrixXd Jr;\n    Eigen::Matrix3d C_w_b = inverseOrientationAndJacobian(tk, &Jr, NULL);\n\n    // Rearrange the spline jacobian matrices. Now Jpdot is the\n    // jacobian of p wrt the spline coefficients stacked on top\n    // of the jacobian of pdot wrt the spline coefficients.\n    Jpdot.block(0, 0, 3, Jpdot.cols()) = Jp.block(3, 0, 3, Jp.cols());\n\n    // std::cout << \"Jpdot\\n\" << Jpdot << std::endl;\n\n    Eigen::Matrix<double, 3, 6> Jo;\n    omega = -C_w_b * rotation_->angularVelocityAndJacobian(p, pdot, &Jo);\n    Jo = (-C_w_b * Jo).eval();\n    // std::cout << \"Jo:\\n\" << Jo << std::endl;\n    if (J) {\n        *J = Jo * Jpdot + sm::kinematics::crossMx(omega) * Jr;\n    }\n\n    return omega;\n}\n\n// \\omega_w_{b,w} (angular velocity of the body frame as seen from the world frame, expressed in the world frame)\nEigen::Vector3d BSplinePose::angularVelocityAndJacobian(double tk, Eigen::MatrixXd* J,\n                                                        Eigen::VectorXi* coefficientIndices) const {\n    Eigen::Vector3d omega;\n    Eigen::Vector3d p;\n    Eigen::Vector3d pdot;\n    Eigen::MatrixXd Jp;\n    Eigen::MatrixXd Jpdot;\n    p = evalDAndJacobian(tk, 0, &Jp, nullptr).tail<3>();\n    pdot = evalDAndJacobian(tk, 1, &Jpdot, coefficientIndices).tail<3>();\n\n    // Rearrange the spline jacobian matrices. Now Jpdot is the\n    // jacobian of p wrt the spline coefficients stacked on top\n    // of the jacobian of pdot wrt the spline coefficients.\n    Jpdot.block(0, 0, 3, Jpdot.cols()) = Jp.block(3, 0, 3, Jp.cols());\n\n    // std::cout << \"Jpdot\\n\" << Jpdot << std::endl;\n\n    Eigen::Matrix<double, 3, 6> Jo;\n    // FixMe by CC: seems like lost the minus \"-\"?\n    omega = rotation_->angularVelocityAndJacobian(p, pdot, &Jo);\n\n    // std::cout << \"Jo:\\n\" << Jo << std::endl;\n    if (J) {\n        *J = Jo * Jpdot;\n    }\n\n    return omega;\n}\n\n// \\omega_dot_b_{w,b} (angular acceleration of the world frame as seen from the body frame, expressed in the body frame)\nEigen::Vector3d BSplinePose::angularAccelerationBodyFrame(double tk) const {\n    Eigen::Vector3d omega;\n    Eigen::VectorXd r = evalD(tk, 0);\n    Eigen::VectorXd v = evalD(tk, 2);\n    Eigen::Matrix3d S;\n    Eigen::Matrix3d C_w_b = rotation_->parametersToRotationMatrix(r.tail<3>(), &S);\n\n    // \\omega = S(\\bar \\theta) \\dot \\theta\n    omega = -C_w_b.transpose() * S * v.tail<3>();\n    return omega;\n}\n\n// \\omega_dot_b_{w,b} (angular acceleration of the world frame as seen from the body frame, expressed in the body frame)\nEigen::Vector3d BSplinePose::angularAccelerationBodyFrameAndJacobian(double tk, Eigen::MatrixXd* J,\n                                                                     Eigen::VectorXi* coefficientIndices) const {\n    Eigen::Vector3d omega;\n    Eigen::Vector3d p;\n    Eigen::Vector3d pdot;\n    Eigen::MatrixXd Jp;\n    Eigen::MatrixXd Jpdot;\n    p = evalDAndJacobian(tk, 0, &Jp, NULL).tail<3>();\n    pdot = evalDAndJacobian(tk, 2, &Jpdot, coefficientIndices).tail<3>();\n\n    Eigen::MatrixXd Jr;\n    Eigen::Matrix3d C_w_b = inverseOrientationAndJacobian(tk, &Jr, NULL);\n\n    // Rearrange the spline jacobian matrices. Now Jpdot is the\n    // jacobian of p wrt the spline coefficients stacked on top\n    // of the jacobian of pdot wrt the spline coefficients.\n    Jpdot.block(0, 0, 3, Jpdot.cols()) = Jp.block(3, 0, 3, Jp.cols());\n\n    Eigen::Matrix<double, 3, 6> Jo;\n    omega = -C_w_b * rotation_->angularVelocityAndJacobian(p, pdot, &Jo);\n    Jo = (-C_w_b * Jo).eval();\n    if (J) {\n        *J = Jo * Jpdot + sm::kinematics::crossMx(omega) * Jr;\n    }\n\n    return omega;\n}\n\n// \\omega_dot_w_{b,w} (angular acceleration of the body frame as seen from the world frame, expressed in the world\n// frame)\nEigen::Vector3d BSplinePose::angularAccelerationAndJacobian(double tk, Eigen::MatrixXd* J,\n                                                            Eigen::VectorXi* coefficientIndices) const {\n    Eigen::Vector3d omega;\n    Eigen::Vector3d p;\n    Eigen::Vector3d pdot;\n    Eigen::MatrixXd Jp;\n    Eigen::MatrixXd Jpdot;\n    p = evalDAndJacobian(tk, 0, &Jp, NULL).tail<3>();\n    pdot = evalDAndJacobian(tk, 2, &Jpdot, coefficientIndices).tail<3>();\n\n    // Rearrange the spline jacobian matrices. Now Jpdot is the\n    // jacobian of p wrt the spline coefficients stacked on top\n    // of the jacobian of pdot wrt the spline coefficients.\n    Jpdot.block(0, 0, 3, Jpdot.cols()) = Jp.block(3, 0, 3, Jp.cols());\n\n    Eigen::Matrix<double, 3, 6> Jo;\n    // FixMe by CC: seems like lost the minus \"-\"?\n    omega = rotation_->angularVelocityAndJacobian(p, pdot, &Jo);\n    if (J) {\n        *J = Jo * Jpdot;\n    }\n\n    return omega;\n}\n\nvoid BSplinePose::initPoseSpline(double t0, double t1, const Eigen::Matrix4d& T_n_t0, const Eigen::Matrix4d& T_n_t1) {\n    Eigen::VectorXd v0 = transformationToCurveValue(T_n_t0);\n    Eigen::VectorXd v1 = transformationToCurveValue(T_n_t1);\n\n    initSpline(t0, t1, v0, v1);\n}\n\nvoid BSplinePose::initPoseSpline2(const Eigen::VectorXd& times, const Eigen::Matrix<double, 6, Eigen::Dynamic>& poses,\n                                  int numSegments, double lambda) {\n    initSpline2(times, poses, numSegments, lambda);\n}\n\nvoid BSplinePose::initPoseSpline3(const Eigen::VectorXd& times, const Eigen::Matrix<double, 6, Eigen::Dynamic>& poses,\n                                  int numSegments, double lambda) {\n    initSpline3(times, poses, numSegments, lambda);\n}\n\nvoid BSplinePose::initPoseSplineSparse(const Eigen::VectorXd& times,\n                                       const Eigen::Matrix<double, 6, Eigen::Dynamic>& poses, int numSegments,\n                                       double lambda) {\n    initSplineSparse(times, poses, numSegments, lambda);\n}\n\nvoid BSplinePose::initPoseSplineSparseKnots(const Eigen::VectorXd& times, const Eigen::MatrixXd& interpolationPoints,\n                                            const Eigen::VectorXd& knots, double lambda) {\n    initSplineSparseKnots(times, interpolationPoints, knots, lambda);\n}\n\nvoid BSplinePose::addPoseSegment(double tk, const Eigen::Matrix4d& T_n_tk) {\n    Eigen::VectorXd vk = transformationToCurveValue(T_n_tk);\n\n    addCurveSegment(tk, vk);\n}\n\nvoid BSplinePose::addPoseSegment2(double tk, const Eigen::Matrix4d& T_n_tk, double lambda) {\n    Eigen::VectorXd vk = transformationToCurveValue(T_n_tk);\n\n    addCurveSegment2(tk, vk, lambda);\n}\n\nEigen::Matrix4d BSplinePose::curveValueToTransformation(const Eigen::VectorXd& c) const {\n    SM_ASSERT_EQ_DBG(Exception, c.size(), 6, \"The curve value is an unexpected size!\");\n    Eigen::Matrix4d T = Eigen::Matrix4d::Identity();\n    T.topLeftCorner<3, 3>() = rotation_->parametersToRotationMatrix(c.tail<3>());\n    T.topRightCorner<3, 1>() = c.head<3>();\n\n    return T;\n}\n\nEigen::VectorXd BSplinePose::transformationToCurveValue(const Eigen::Matrix4d& T) const {\n    Eigen::VectorXd c(6);\n    c.head<3>() = T.topRightCorner<3, 1>();\n    c.tail<3>() = rotation_->rotationMatrixToParameters(T.topLeftCorner<3, 3>());\n\n    return c;\n}\n\nRotationalKinematics::Ptr BSplinePose::rotation() const { return rotation_; }\n\nEigen::Matrix4d BSplinePose::curveValueToTransformationAndJacobian(const Eigen::VectorXd& p, Eigen::MatrixXd* J) const {\n    SM_ASSERT_EQ_DBG(Exception, p.size(), 6, \"The curve value is an unexpected size!\");\n    Eigen::Matrix4d T = Eigen::Matrix4d::Identity();\n    Eigen::Matrix3d S;\n    T.topLeftCorner<3, 3>() = rotation_->parametersToRotationMatrix(p.tail<3>(), &S);\n    T.topRightCorner<3, 1>() = p.head<3>();\n\n    if (J) {\n        *J = Eigen::MatrixXd::Identity(6, 6);\n        J->topRightCorner<3, 3>() = -crossMx(p.head<3>()) * S;\n        J->bottomRightCorner<3, 3>() = S;\n    }\n\n    return T;\n}\n", "meta": {"hexsha": "f456713e39a38130323001b26e9f63ec922bad7e", "size": 14569, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "aslam_nonparametric_estimation/bsplines/src/BSplinePose.cpp", "max_stars_repo_name": "chengfzy/kalibr", "max_stars_repo_head_hexsha": "fe9705b380b160dc939607135f7d30efa64ea2e9", "max_stars_repo_licenses": ["BSD-4-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "aslam_nonparametric_estimation/bsplines/src/BSplinePose.cpp", "max_issues_repo_name": "chengfzy/kalibr", "max_issues_repo_head_hexsha": "fe9705b380b160dc939607135f7d30efa64ea2e9", "max_issues_repo_licenses": ["BSD-4-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "aslam_nonparametric_estimation/bsplines/src/BSplinePose.cpp", "max_forks_repo_name": "chengfzy/kalibr", "max_forks_repo_head_hexsha": "fe9705b380b160dc939607135f7d30efa64ea2e9", "max_forks_repo_licenses": ["BSD-4-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.645994832, "max_line_length": 120, "alphanum_fraction": 0.6424600178, "num_tokens": 4106, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.640635854839898, "lm_q2_score": 0.49218813572079556, "lm_q1q2_score": 0.3153133670695476}}
{"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 \"BlockMatrixIterators.hpp\"\n#include <boost/numeric/ublas/matrix_proxy.hpp>\n\n#include \"SimpleMatrix.hpp\"\n#include \"SiconosAlgebra.hpp\"\n\nusing namespace Siconos;\n\n\nvoid add(const SiconosMatrix & A, const SiconosMatrix& B, SiconosMatrix& C)\n{\n  // To compute C = A + B in an \"optimized\" way (in comparison with operator +)\n\n  if ((A.size(0) != B.size(0)) || (A.size(1) != B.size(1)))\n    SiconosMatrixException::selfThrow(\"Matrix addition: inconsistent sizes\");\n  if ((A.size(0) != C.size(0)) || (A.size(1) != C.size(1)))\n    SiconosMatrixException::selfThrow(\"Matrix addition: inconsistent sizes\");\n\n  unsigned int numA = A.num();\n  unsigned int numB = B.num();\n  unsigned int numC = C.num();\n\n  // === if C is zero or identity => read-only ===\n  if (numC == 6 || numC == 7)\n    SiconosMatrixException::selfThrow(\"Matrix addition ( add(A,B,C) ): wrong type for resulting matrix C (read-only: zero or identity).\");\n\n  // === common memory between A, B, C ===\n  if (&A == &C) // A and C have common memory\n  {\n    C += B;\n  }\n  else if (&B == &C)  // B and C have common memory\n  {\n    C += A;\n  }\n  else // No common memory between C and A or B.\n  {\n    if (numA == 6) // A = 0\n      C = B ;\n    else if (numB == 6) // B = 0\n      C = A;\n    else // A and B different from 0\n    {\n      if (numC == 0) // if C is Block\n      {\n        if (numA != 0) // A simple, whatever is B\n        {\n          C = A;\n          C += B;\n        }\n        else  // A Block\n        {\n          C = B;\n          C += A;\n        }\n      }\n      else // if C is a SimpleMatrix\n      {\n        if (numA == numB && numA != 0) // A and B are of the same type and NOT block\n        {\n          if (numC == numA)\n          {\n            if (numA == 1)\n              noalias(*C.dense()) = *A.dense() + *B.dense();\n            else if (numA == 2)\n              noalias(*C.triang()) = *A.triang() + *B.triang();\n            else if (numA == 3)\n              noalias(*C.sym()) = *A.sym() + *B.sym();\n            else if (numA == 4)\n              noalias(*C.sparse()) = *A.sparse() + *B.sparse();\n            else //if(numA==5)\n              noalias(*C.banded()) = *A.banded() + *B.banded();\n          }\n          else // C and A of different types.\n          {\n            if (numC != 1)\n              SiconosMatrixException::selfThrow(\"Matrix addition ( add(A,B,C) ): wrong type for resulting matrix C.\");\n            // Only dense matrices are allowed for output.\n\n            if (numA == 1)\n              noalias(*C.dense()) = *A.dense() + *B.dense();\n            else if (numA == 2)\n              noalias(*C.dense()) = *A.triang() + *B.triang();\n            else if (numA == 3)\n              noalias(*C.dense()) = *A.sym() + *B.sym();\n            else if (numA == 4)\n              noalias(*C.dense()) = *A.sparse() + *B.sparse();\n            else //if(numA==5)\n              noalias(*C.dense()) = *A.banded() + *B.banded();\n          }\n          C.resetLU();\n        }\n        else if (numA != 0 && numB != 0 && numA != numB) // A and B of different types and none is block\n        {\n          if (numC != 1)\n            SiconosMatrixException::selfThrow(\"Matrix addition ( add(A,B,C) ): wrong type for resulting matrix C.\");\n          // Only dense matrices are allowed for output.\n\n          if (numA == 1)\n            switch (numB)\n            {\n            case 2:\n              noalias(*C.dense()) = *A.dense() + *B.triang();\n              break;\n            case 3:\n              noalias(*C.dense()) = *A.dense() + *B.sym();\n              break;\n            case 4:\n              noalias(*C.dense()) = *A.dense() + *B.sparse();\n              break;\n            case 5:\n              noalias(*C.dense()) = *A.dense() + *B.banded();\n              break;\n            case 7:\n              noalias(*C.dense()) = *A.dense() + *B.identity();\n              break;\n            default:\n              SiconosMatrixException::selfThrow(\"Matrix function add(A,B,C): invalid type of matrix\");\n            }\n          else if (numA == 2)\n            switch (numB)\n            {\n            case 1:\n              noalias(*C.dense()) = *A.triang() + *B.dense();\n              break;\n            case 3:\n              noalias(*C.dense()) = *A.triang() + *B.sym();\n              break;\n            case 4:\n              noalias(*C.dense()) = *A.triang() + *B.sparse();\n              break;\n            case 5:\n              noalias(*C.dense()) = *A.triang() + *B.banded();\n              break;\n            case 7:\n              noalias(*C.dense()) = *A.triang() + *B.identity();\n              break;\n            default:\n              SiconosMatrixException::selfThrow(\"Matrix function add(A,B,C): invalid type of matrix\");\n            }\n          else if (numA == 3)\n            switch (numB)\n            {\n            case 1:\n              noalias(*C.dense()) = *A.sym() + *B.dense();\n              break;\n            case 2:\n              noalias(*C.dense()) = *A.sym() + *B.triang();\n              break;\n            case 4:\n              noalias(*C.dense()) = *A.sym() + *B.sparse();\n              break;\n            case 5:\n              noalias(*C.dense()) = *A.sym() + *B.banded();\n              break;\n            case 7:\n              noalias(*C.dense()) = *A.sym() + *B.identity();\n              break;\n            default:\n              SiconosMatrixException::selfThrow(\"Matrix function add(A,B,C): invalid type of matrix\");\n            }\n          else if (numA == 4)\n            switch (numB)\n            {\n            case 1:\n              noalias(*C.dense()) = *A.sparse() + *B.dense();\n              break;\n            case 2:\n              noalias(*C.dense()) = *A.sparse() + *B.triang();\n              break;\n            case 3:\n              noalias(*C.dense()) = *A.sparse() + *B.sym();\n              break;\n            case 5:\n              noalias(*C.dense()) = *A.sparse() + *B.banded();\n              break;\n            case 7:\n              noalias(*C.dense()) = *A.sparse() + *B.identity();\n              break;\n            default:\n              SiconosMatrixException::selfThrow(\"Matrix function add(A,B,C): invalid type of matrix\");\n            }\n          else if (numA == 5)\n            switch (numB)\n            {\n            case 1:\n              noalias(*C.dense()) = *A.banded() + *B.dense();\n              break;\n            case 2:\n              noalias(*C.dense()) = *A.banded() + *B.triang();\n              break;\n            case 3:\n              noalias(*C.dense()) = *A.banded() + *B.sym();\n              break;\n            case 4:\n              noalias(*C.dense()) = *A.banded() + *B.sparse();\n              break;\n            case 7:\n              noalias(*C.dense()) = *A.banded() + *B.identity();\n              break;\n            default:\n              SiconosMatrixException::selfThrow(\"Matrix function add(A,B,C): invalid type of matrix\");\n            }\n          else if (numA == 7)\n            switch (numB)\n            {\n            case 1:\n              noalias(*C.dense()) = *A.identity() + *B.dense();\n              break;\n            case 2:\n              noalias(*C.dense()) = *A.identity() + *B.triang();\n              break;\n            case 3:\n              noalias(*C.dense()) = *A.identity() + *B.sym();\n              break;\n            case 4:\n              noalias(*C.dense()) = *A.identity() + *B.sparse();\n              break;\n            case 5:\n              noalias(*C.dense()) = *A.identity() + *B.banded();\n              break;\n            default:\n              SiconosMatrixException::selfThrow(\"Matrix function add(A,B,C): invalid type of matrix\");\n            }\n          else\n            SiconosMatrixException::selfThrow(\"Matrix function add(A,B,C): invalid type of matrix\");\n          C.resetLU();\n        }\n        else // A and/or B is Block\n        {\n          if (numA != 0) // A Simple, whatever is B\n          {\n            C = A;\n            C += B;\n          }\n          else // A Block\n          {\n            C = B;\n            C += A;\n          }\n        }\n      }\n    }\n  }\n\n}\n\nvoid sub(const SiconosMatrix & A, const SiconosMatrix& B, SiconosMatrix& C)\n{\n  // To compute C = A - B in an \"optimized\" way (in comparison with operator +)\n\n  if ((A.size(0) != B.size(0)) || (A.size(1) != B.size(1)))\n    SiconosMatrixException::selfThrow(\"Matrix addition: inconsistent sizes\");\n  if ((A.size(0) != C.size(0)) || (A.size(1) != C.size(1)))\n    SiconosMatrixException::selfThrow(\"Matrix addition: inconsistent sizes\");\n\n  unsigned int numA = A.num();\n  unsigned int numB = B.num();\n  unsigned int numC = C.num();\n\n  // === if C is zero or identity => read-only ===\n  if (numC == 6 || numC == 7)\n    SiconosMatrixException::selfThrow(\"Matrix addition ( add(A,B,C) ): wrong type for resulting matrix C (read-only: zero or identity).\");\n\n  // === common memory between A, B, C ===\n  if (&A == &C) // A and C have common memory\n  {\n    C -= B;\n  }\n  else if (&B == &C)  // B and C have common memory\n  {\n    if (numB == 0 || numA == 0) // if A or B(C) is Block\n    {\n      C *= -1.0;\n      C += A;\n    }\n    else\n    {\n      if (numC == 0) // if C is Block\n      {\n        C = A;\n        C -= B;\n      }\n      else // if C is a SimpleMatrix\n      {\n        if (numA == numB && numA != 0) // A and B are of the same type and NOT block\n        {\n          if (numA == 1)\n            *C.dense() = *A.dense() - *B.dense();\n          else if (numA == 2)\n            *C.triang() = *A.triang() - *B.triang();\n          else if (numA == 3)\n            *C.sym() = *A.sym() - *B.sym();\n          else if (numA == 4)\n            *C.sparse() = *A.sparse() - *B.sparse();\n          else //if(numA==5)\n            *C.banded() = *A.banded() - *B.banded();\n        }\n        else if (numA != 0 && numB != 0 && numA != numB) // A and B of different types and none is block\n        {\n          if (numC != 1)  // => numB == 1\n            SiconosMatrixException::selfThrow(\"Matrix addition ( add(A,B,C) ): wrong type for resulting matrix C.\");\n          // Only dense matrices are allowed for output.\n\n          if (numA == 1)\n            *C.dense() = *A.dense() - *B.dense();\n          else if (numA == 2)\n            *C.dense() = *A.triang() - *B.dense();\n          else if (numA == 3)\n            *C.dense() = *A.sym() - *B.dense();\n          else if (numA == 4)\n            *C.dense() = *A.sparse() - *B.dense();\n          else if (numA == 5)\n            *C.dense() = *A.banded() - *B.dense();\n          else if (numA == 6)\n            *C.dense() = *A.zero_mat() - *B.dense();\n          else //if(numA==7)\n            *C.dense() = *A.identity() - *B.dense();\n        }\n        else // A and/or B is Block\n        {\n          C = A;\n          C -= B;\n        }\n        C.resetLU();\n      }\n    }\n  }\n  else // No common memory between C and A or B.\n  {\n    if (numB == 6) // B = 0\n      C = A;\n    else // B different from 0\n    {\n      if (numC == 0) // if C is Block\n      {\n        C = A;\n        C -= B;\n      }\n      else // if C is a SimpleMatrix\n      {\n        if (numA == numB && numA != 0) // A and B are of the same type and NOT block\n        {\n          if (numC == numA)\n          {\n            if (numA == 1)\n              noalias(*C.dense()) = *A.dense() - *B.dense();\n            else if (numA == 2)\n              noalias(*C.triang()) = *A.triang() - *B.triang();\n            else if (numA == 3)\n              noalias(*C.sym()) = *A.sym() - *B.sym();\n            else if (numA == 4)\n              noalias(*C.sparse()) = *A.sparse() - *B.sparse();\n            else //if(numA==5)\n              noalias(*C.banded()) = *A.banded() - *B.banded();\n          }\n          else // C and A of different types.\n          {\n            if (numC != 1)\n              SiconosMatrixException::selfThrow(\"Matrix addition ( add(A,B,C) ): wrong type for resulting matrix C.\");\n            // Only dense matrices are allowed for output.\n\n            if (numA == 1)\n              noalias(*C.dense()) = *A.dense() - *B.dense();\n            else if (numA == 2)\n              noalias(*C.dense()) = *A.triang() - *B.triang();\n            else if (numA == 3)\n              noalias(*C.dense()) = *A.sym() - *B.sym();\n            else if (numA == 4)\n              noalias(*C.dense()) = *A.sparse() - *B.sparse();\n            else //if(numA==5)\n              noalias(*C.dense()) = *A.banded() - *B.banded();\n          }\n          C.resetLU();\n        }\n        else if (numA != 0 && numB != 0 && numA != numB) // A and B of different types and none is block\n        {\n          if (numC != 1)\n            SiconosMatrixException::selfThrow(\"Matrix addition ( add(A,B,C) ): wrong type for resulting matrix C.\");\n          // Only dense matrices are allowed for output.\n\n          if (numA == 1)\n            switch (numB)\n            {\n            case 2:\n              noalias(*C.dense()) = *A.dense() - *B.triang();\n              break;\n            case 3:\n              noalias(*C.dense()) = *A.dense() - *B.sym();\n              break;\n            case 4:\n              noalias(*C.dense()) = *A.dense() - *B.sparse();\n              break;\n            case 5:\n              noalias(*C.dense()) = *A.dense() - *B.banded();\n              break;\n            case 7:\n              noalias(*C.dense()) = *A.dense() - *B.identity();\n              break;\n            default:\n              SiconosMatrixException::selfThrow(\"Matrix function add(A,B,C): invalid type of matrix\");\n            }\n          else if (numA == 2)\n            switch (numB)\n            {\n            case 1:\n              noalias(*C.dense()) = *A.triang() - *B.dense();\n              break;\n            case 3:\n              noalias(*C.dense()) = *A.triang() - *B.sym();\n              break;\n            case 4:\n              noalias(*C.dense()) = *A.triang() - *B.sparse();\n              break;\n            case 5:\n              noalias(*C.dense()) = *A.triang() - *B.banded();\n              break;\n            case 7:\n              noalias(*C.dense()) = *A.triang() - *B.identity();\n              break;\n            default:\n              SiconosMatrixException::selfThrow(\"Matrix function add(A,B,C): invalid type of matrix\");\n            }\n          else if (numA == 3)\n            switch (numB)\n            {\n            case 1:\n              noalias(*C.dense()) = *A.sym() - *B.dense();\n              break;\n            case 2:\n              noalias(*C.dense()) = *A.sym() - *B.triang();\n              break;\n            case 4:\n              noalias(*C.dense()) = *A.sym() - *B.sparse();\n              break;\n            case 5:\n              noalias(*C.dense()) = *A.sym() - *B.banded();\n              break;\n            case 7:\n              noalias(*C.dense()) = *A.sym() - *B.identity();\n              break;\n            default:\n              SiconosMatrixException::selfThrow(\"Matrix function add(A,B,C): invalid type of matrix\");\n            }\n          else if (numA == 4)\n            switch (numB)\n            {\n            case 1:\n              noalias(*C.dense()) = *A.sparse() - *B.dense();\n              break;\n            case 2:\n              noalias(*C.dense()) = *A.sparse() - *B.triang();\n              break;\n            case 3:\n              noalias(*C.dense()) = *A.sparse() - *B.sym();\n              break;\n            case 5:\n              noalias(*C.dense()) = *A.sparse() - *B.banded();\n              break;\n            case 7:\n              noalias(*C.dense()) = *A.sparse() - *B.identity();\n              break;\n            default:\n              SiconosMatrixException::selfThrow(\"Matrix function add(A,B,C): invalid type of matrix\");\n            }\n          else if (numA == 5)\n            switch (numB)\n            {\n            case 1:\n              noalias(*C.dense()) = *A.banded() - *B.dense();\n              break;\n            case 2:\n              noalias(*C.dense()) = *A.banded() - *B.triang();\n              break;\n            case 3:\n              noalias(*C.dense()) = *A.banded() - *B.sym();\n              break;\n            case 4:\n              noalias(*C.dense()) = *A.banded() - *B.sparse();\n              break;\n            case 7:\n              noalias(*C.dense()) = *A.banded() - *B.identity();\n              break;\n            default:\n              SiconosMatrixException::selfThrow(\"Matrix function add(A,B,C): invalid type of matrix\");\n            }\n          else if (numA == 6)\n            switch (numB)\n            {\n            case 1:\n              noalias(*C.dense()) = *A.zero_mat() - *B.dense();\n              break;\n            case 2:\n              noalias(*C.dense()) = *A.zero_mat() - *B.triang();\n              break;\n            case 3:\n              noalias(*C.dense()) = *A.zero_mat() - *B.sym();\n              break;\n            case 4:\n              noalias(*C.dense()) = *A.zero_mat() - *B.sparse();\n              break;\n            case 7:\n              noalias(*C.dense()) = *A.zero_mat() - *B.identity();\n              break;\n            default:\n              SiconosMatrixException::selfThrow(\"Matrix function add(A,B,C): invalid type of matrix\");\n            }\n          else if (numA == 7)\n            switch (numB)\n            {\n            case 1:\n              noalias(*C.dense()) = *A.identity() - *B.dense();\n              break;\n            case 2:\n              noalias(*C.dense()) = *A.identity() - *B.triang();\n              break;\n            case 3:\n              noalias(*C.dense()) = *A.identity() - *B.sym();\n              break;\n            case 4:\n              noalias(*C.dense()) = *A.identity() - *B.sparse();\n              break;\n            case 5:\n              noalias(*C.dense()) = *A.identity() - *B.banded();\n              break;\n            default:\n              SiconosMatrixException::selfThrow(\"Matrix function add(A,B,C): invalid type of matrix\");\n            }\n          else\n            SiconosMatrixException::selfThrow(\"Matrix function add(A,B,C): invalid type of matrix\");\n          C.resetLU();\n        }\n        else // A and/or B is Block\n        {\n          C = A;\n          C -= B;\n        }\n      }\n    }\n  }\n}\n\n\n", "meta": {"hexsha": "2d34dcd4635f27cc70f987466eeff2c7784f2b5d", "size": 18723, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "kernel/src/utils/SiconosAlgebra/SimpleMatrixArithmetic.cpp", "max_stars_repo_name": "siconos/siconos-deb", "max_stars_repo_head_hexsha": "2739a23f23d797dbfecec79d409e914e13c45c67", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "kernel/src/utils/SiconosAlgebra/SimpleMatrixArithmetic.cpp", "max_issues_repo_name": "siconos/siconos-deb", "max_issues_repo_head_hexsha": "2739a23f23d797dbfecec79d409e914e13c45c67", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "kernel/src/utils/SiconosAlgebra/SimpleMatrixArithmetic.cpp", "max_forks_repo_name": "siconos/siconos-deb", "max_forks_repo_head_hexsha": "2739a23f23d797dbfecec79d409e914e13c45c67", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.3149466192, "max_line_length": 138, "alphanum_fraction": 0.4340116434, "num_tokens": 4909, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6113819732941511, "lm_q2_score": 0.5156199157230157, "lm_q1q2_score": 0.3152407215445012}}
{"text": "/*\n * Copyright (c) 2016, 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 <boost/variant/apply_visitor.hpp>\n\n#include \"ctl.hh\"\n\nnamespace CTL {\n\nstd::unique_ptr<S_Formula> SatVisitor::operator () (const Formula::E_Literal& exp) const {\n\treturn nullary (exp, [&] () { return exp.value ? SatSet { tranSys.statesSet } : SatSet {}; });\n}\n\nstd::unique_ptr<S_Formula> SatVisitor::operator () (const Formula::E_Negation& exp) const {\n\treturn unary (exp, [&] (S_Formula& child) {\n\t\treturn tranSys.statesSet - child.sat;\n\t});\n}\n\nstd::unique_ptr<S_Formula> SatVisitor::operator () (const Formula::E_And& exp) const {\n\treturn binary (exp, [&] (S_Formula& left, S_Formula& right) {\n\t\treturn left.sat & right.sat;\n\t});\n}\n\nstd::unique_ptr<S_Formula> SatVisitor::operator () (const Formula::E_Or& exp) const {\n\treturn binary (exp, [&] (S_Formula& left, S_Formula& right) {\n\t\treturn left.sat | right.sat;\n\t});\n}\n\nstd::unique_ptr<S_Formula> SatVisitor::operator() (const Formula::E_Implication& exp) const {\n\treturn binary (exp, [&] (S_Formula& left, S_Formula& right) {\n\t\treturn (tranSys.statesSet - left.sat) | right.sat;\n\t});\n}\n\n\nstd::unique_ptr<S_Formula> SatVisitor::operator () (const Formula::E_ExistNext& exp) const {\n\treturn unary (exp, [&] (S_Formula& child) {\n\t\tstd::set<TS::State*> predecessors;\n\t\tfor (auto& s : child.sat) {\n\t\t\tpredecessors |= s->predecessors;\n\t\t}\n\n\t\treturn predecessors;\n\t});\n}\n\nstd::unique_ptr<S_Formula> SatVisitor::operator () (const Formula::E_ExistUntil& exp) const {\n\treturn binary (exp, [&] (S_Formula& left, S_Formula& right) {\n\t\tstd::set<TS::State*> T = right.sat;\n\t\tbool modified;\n\t\tdo {\n\t\t\tmodified = false;\n\t\t\tfor (TS::State* s : T) {\n\t\t\t\tfor (TS::State* p : s->predecessors) {\n\t\t\t\t\tif (left.sat.find (p) != left.sat.end () && T.find (p) != T.end ()) {\n\t\t\t\t\t\tT.insert (p);\n\t\t\t\t\t\tmodified = true;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t} while (modified);\n\n\t\treturn T;\n\t});\n}\n\nstd::unique_ptr<S_Formula> SatVisitor::operator () (const Formula::E_ExistAlways& exp) const {\n\treturn unary (exp, [&] (S_Formula& child) {\n\t\tstd::set<TS::State*> T = child.sat;\n\t\tbool modified;\n\t\tdo {\n\t\t\tmodified = false;\n\t\t\tusing I = std::set<TS::State*>::const_iterator;\n\t\t\tfor (I iter = T.cbegin (); iter != T.cend (); ) {\n\t\t\t\tI next = iter;\n\t\t\t\t++next;\n\t\t\t\tif (!((*iter)->successors && T)) {\n\t\t\t\t\tT.erase (iter);\n\t\t\t\t\tmodified = true;\n\t\t\t\t}\n\t\t\t\titer = next;\n\t\t\t}\n\t\t} while (modified);\n\n\t\treturn T;\n\t});\n}\n\nstd::unique_ptr<S_Formula> SatVisitor::operator() (const Formula::E_AllNext& exp) const {\n\treturn unary (exp, [&] (S_Formula& child) {\n\t\tstd::set<TS::State*> exclusivePredecessors;\n\t\tfor (auto& s : child.sat) {\n\t\t\tfor (auto& p : s->predecessors) {\n\t\t\t\tif (p->successors <= child.sat)\n\t\t\t\t\texclusivePredecessors.insert (p);\n\t\t\t}\n\t\t}\n\n\t\treturn exclusivePredecessors;\n\t});\n}\n\nstd::unique_ptr<S_Formula> SatVisitor::operator() (const Formula::E_AllUntil& exp) const {\n\treturn binary (exp, [&] (S_Formula& left, S_Formula& right) {\n\t\tstd::set<TS::State*> T = right.sat;\n\t\tbool modified;\n\t\tdo {\n\t\t\tmodified = false;\n\t\t\tfor (TS::State* s : T) {\n\t\t\t\tfor (TS::State* p : s->predecessors) {\n\n\t\t\t\t\tif (left.sat.find (p) != left.sat.end ()\n\t\t\t\t\t&&\ts->successors <= T\n\t\t\t\t\t&&\tT.find (p) != T.end ()) {\n\t\t\t\t\t\tT.insert (p);\n\t\t\t\t\t\tmodified = true;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t} while (modified);\n\n\t\treturn T;\n\t});\n}\n\nstd::unique_ptr<S_Formula> SatVisitor::operator() (const Formula::E_AllAlways& exp) const {\n\treturn unary (exp, [&] (S_Formula& child) {\n\t\tstd::set<TS::State*> T = child.sat;\n\t\tbool modified;\n\t\tdo {\n\t\t\tmodified = false;\n\t\t\tfor (TS::State* s : T) {\n\t\t\t\tif (!(s->successors <= T)) {\n\t\t\t\t\tT.erase (s);\n\t\t\t\t\tmodified = true;\n\t\t\t\t}\n\t\t\t}\n\t\t} while (modified);\n\n\t\treturn T;\n\t});\n}\n\n\nstd::unique_ptr<S_Formula> SatVisitor::operator () (const Formula::E_Label& exp) const {\n\treturn nullary (exp, [&] () {\n\t\tauto res = tranSys.labels.find (exp.name);\n\t\tif (res == tranSys.labels.end ())\n\t\t\tthrow std::runtime_error (\"Unknown label \\\"\" + exp.name + \"\\\" in formula\");\n\n\t\tstd::set<TS::State*> sat;\n\t\tfor (const auto s : tranSys.statesSet) {\n\t\t\tif (s->atomicPropositions.find (&res->second) != s->atomicPropositions.end ())\n\t\t\t\tsat.insert (s);\n\t\t}\n\n\t\treturn sat;\n\t});\n}\n\nstd::unique_ptr<S_Formula> SatVisitor::operator() (const Formula::E_Next&) const {\n\tthrow std::runtime_error (\"Illegal node in AST\");\n}\n\nstd::unique_ptr<S_Formula> SatVisitor::operator() (const Formula::E_Until&) const {\n\tthrow std::runtime_error (\"Illegal node in AST\");\n}\n\nstd::pair<bool, std::unique_ptr<S_Formula>> computeSat (const Formula::Expression& formula, TS::TranSys& ts) {\n\tstd::unique_ptr<S_Formula> res = boost::apply_visitor (SatVisitor { ts }, formula);\n\tbool s = ts.init <= res->sat;\n\treturn std::make_pair (s, std::move (res));\n}\n\nvoid S_Formula::print (std::ostream& os, size_t depth) {\n\tfor (size_t i = 0; i < depth; ++i) os << '\\t';\n\tos << \"Sat (\";\n\tstd::copy (strBegin, strEnd, std::ostreambuf_iterator<char> (os));\n\tos << \") = \";\n}\n\nvoid S_Nullary::print (std::ostream& os, size_t depth) {\n\tS_Formula::print (os, depth);\n\tos << sat << std::endl;\n}\n\nvoid S_Unary::print (std::ostream& os, size_t depth) {\n\tS_Formula::print (os, depth);\n\tos << sat << std::endl;\n\tchild->print (os, depth+1);\n}\n\nvoid S_Binary::print (std::ostream& os, size_t depth) {\n\tS_Formula::print (os, depth);\n\tos << sat << std::endl;\n\tleft->print (os, depth+1);\n\tright->print (os, depth+1);\n}\n\nstd::ostream& operator << (std::ostream& os, const SatSet& sat) {\n\tos << '{';\n\tbool next = false;\n\tfor (SatSet::const_iterator i = sat.cbegin (); i != sat.cend (); ++i) {\n\t\tif (next) {\n\t\t\tos << \", \";\n\t\t} else {\n\t\t\tnext = true;\n\t\t}\n\t\tos << (*i)->name;\n\t}\n\tos << '}';\n\treturn os;\n}\n\n}\n", "meta": {"hexsha": "2a57e0b717411b43054204a47a560431ca927de8", "size": 6914, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/ctl/ctl.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/ctl/ctl.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/ctl/ctl.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": 29.0504201681, "max_line_length": 119, "alphanum_fraction": 0.6485391958, "num_tokens": 1990, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6113819732941511, "lm_q2_score": 0.5156199157230156, "lm_q1q2_score": 0.31524072154450117}}
{"text": "#ifndef HOMOTOPY_BASE_HH\n#define HOMOTOPY_BASE_HH\n\n#include <vector>\n#include <memory> // unique_ptr\n#include <cmath>\n#include <fstream>\n\n#include \"dune/grid/config.h\"\n\n#include \"abstract_interface.hh\"\n#include \"algorithm_base.hh\"\n#include \"newton_damped.hh\"\n#include \"modelfunction.hh\"\n#include <boost/timer/timer.hpp>\n\nnamespace Kaskade\n{\n\nclass NewtonsMethod;\n\n  /** Abstract algorithm of interior point method.\n  */\nclass InteriorPointSqrtModel;\ntemplate<class IPF, class DomainVector> class InteriorPointTangentialPredictor;\nclass InteriorPointSlopeEstimate;\n\n\nclass InteriorPointParameters : IterationParameters\n{\npublic:\n  InteriorPointParameters(double mu_, double desiredAccuracy_, double desiredContraction_, int maxSteps_, double muFinal_, double relDist, double accfinal_,\n                          double reductionStart_,double reductionFactorBest_, double redWorst_=1-1e-4)\n    : IterationParameters(desiredAccuracy_, maxSteps_),\n      desiredContraction(desiredContraction_), \n      muFinal(muFinal_),\n      reductionFactorWorst(redWorst_),\n      firstStepFailureFactor(2.0),\n      reductionStart(reductionStart_),\n      relDistanceToPath(relDist),\n      accfinal(accfinal_),\n      reductionFactorBest(reductionFactorBest_),\n      maxTrialSteps(10)\n  {\n    reset();\n    mu=mu_;\n  }\n\n//Parameters with values that must be supplied by client\n  double desiredContraction, muFinal, reductionFactorWorst, firstStepFailureFactor, reductionStart, relDistanceToPath, accfinal, reductionFactorBest;\n  int maxTrialSteps;\n\n  virtual ~InteriorPointParameters() {}\n\n  int termination;\n\n  void reset()\n  {\n    IterationParameters::reset();\n    stepSuccessful=true;\n    correctorTermination=-1;\n  }\n\n  LoggedQuantity<double> mu, sigma;\n  \nprotected:\n\n  bool stepSuccessful; \n\n  int correctorTermination;\n\n\n  LoggedQuantity<double> deltaMu, j, jp, muTrial;\n\n  friend class HomotopyBase;\n  friend class InteriorPointSimple;\n  friend class InteriorPointSqrtModel;\n  template<class A, class B> friend class InteriorPointTangentialPredictor;\n  friend class InteriorPointSlopeEstimate;\n\n  virtual void doForAll(LQAction::ToDo td)\n  {\n    IterationParameters::doForAll(td);    \n    mu.doAction(td,\"mu\");\n    muTrial.doAction(td,\"muTrial\");\n    j.doAction(td,\"jp\");\n    jp.doAction(td,\"j\");\n    sigma.doAction(td,\"sigma\");\n    deltaMu.doAction(td,\"deltaMu\");\n  }\n\n\n};\n\n/// Base class for homotopy methods. Here, the main algorithm is programmed\nclass HomotopyBase : public Algorithm\n  {\n  public:\n    HomotopyBase(NewtonsMethod& n_, InteriorPointParameters& p_) :\n      corrector(n_), p(p_)\n    {}\n    virtual ~HomotopyBase()\n    { }\n\n    void solve(AbstractParameterFunctional* f,AbstractFunctionSpaceElement& x);\n  protected:\n\n/// Optional overload by derived class\n    virtual void initialize() {};\n\n/// Optional overload by derived class\n    virtual void finalize() {};\n\n    virtual void logQuantities();\n\n/// Default: classical predictor\n    virtual void computePredictor(int step);\n\n/// New mu if corrector was successful\n    virtual double muOnSuccess(int step) = 0;\n\n/// New mu if corrector failed\n    virtual double muOnFailure() = 0;\n\n/// mu for successful termination\n    virtual double muFinal() = 0;\n\n/// update of path parameters, e.g. eta and omega\n    virtual void updateModelOfHomotopy(int step) = 0;\n\n/// what should be done before corrector\n    virtual void initializeCorrector() = 0;\n\n/// what should be done after corrector\n    virtual void finalizeCorrector() = 0;\n\n/// make trial iterate to current iterate (on successful corrector)\n    virtual void updateIterate() = 0;\n\n/// make old iterate to current iterate (on failed corrector)\n    virtual void recoverIterate() = 0;\n\n/// estimate of length of homopoty path\n    virtual double lengthOfPath() = 0;\n\n/// convergence test. returns true if method converged and solution is found.\n    virtual int convergenceTest();\n    \n/// to be performed, if convergence of path has occured\n    virtual void finalizeHomotopy(){};\n\n/// output of a termination message\n    virtual void terminationMessage(int errorFlag);\n\n    NewtonsMethod& corrector;\n    InteriorPointParameters& p;\n    AbstractParameterFunctional* functional;\n\n    std::unique_ptr<AbstractFunctionSpaceElement> trialIterate;\n    int step;\n\n  private:\n\n    bool stepSuccessful();\n\n    void computeCorrector();\n    void computeGapParameter();\n    int runAlgorithm();\n  };\n\n/// Very simple implementation of homotopy method: fixed stepsize\nclass InteriorPointSimple : public HomotopyBase\n{\npublic:\n  InteriorPointSimple(NewtonsMethod& n_, InteriorPointParameters& p_) : \n    HomotopyBase(n_, p_) {}\n\n  virtual double muOnSuccess(int step) { return p.mu*p.reductionStart;};\n  virtual double muOnFailure() { return p.mu*p.reductionStart;};\n  virtual double muFinal() { return 1e-7;};\n\n  virtual void updateModelOfHomotopy(int step) {};\n\n  virtual void initializeCorrector() {};\n  virtual void finalizeCorrector() {};\n\n  virtual void updateIterate() {};\n  virtual void recoverIterate() {};\n\n  virtual double lengthOfPath() { return std::sqrt(p.mu); };\n};\n\n\nclass InteriorPointParametersSqrt : IterationParameters\n{\npublic:\n  InteriorPointParametersSqrt()\n    : IterationParameters(0.0,0)\n  {\n    reset();\n  }\n  friend class InteriorPointSqrtModel;\n  template<class A, class B> friend class InteriorPointTangentialPredictor;\n  friend class InteriorPointSlopeEstimate;\n\n  virtual ~InteriorPointParametersSqrt() {}\n  \nprotected:\n\n  LoggedQuantity<double> omega;\n  LoggedQuantity<double> eta;\n  LoggedQuantity<double> slope;\n  LoggedQuantity<double> curvature;  \n  LoggedQuantity<double> jpl;\n  LoggedQuantity<double> accuracyCorrector;\n  LoggedQuantity<int> newtonSum;\n  LoggedQuantity<double> timemeasured;\n\n  virtual void doForAll(LQAction::ToDo td)\n  {\n    omega.doAction(td,\"omega\");\n    eta.doAction(td,\"eta\");\n    slope.doAction(td,\"slope\");\n    curvature.doAction(td,\"curvature\");\n    jpl.doAction(td,\"jpl\");\n    accuracyCorrector.doAction(td,\"accuracyCorrector\");\n    newtonSum.doAction(td,\"newtonSum\");\n    timemeasured.doAction(td,\"timemeasured\");\n  }\n};\n\n\n/// InteriorPointMethod with a sqrt-model of the path: eta ~ mu^{-1/2}, omega ~mu^{-1/2}\nclass InteriorPointSqrtModel : public HomotopyBase\n{\npublic:\n  InteriorPointSqrtModel(NewtonsMethod& n_, AbstractNorm const& norm_, \n                         InteriorPointParameters& p_, AbstractNewtonDirection& solver_, \n                         AbstractNorm const* normPlain_=0) : \n    HomotopyBase(n_, p_),\n    norm(norm_),\n    solver(solver_),\n    normPlain(normPlain_)\n  {\n    if(!normPlain) normPlain = &norm;\n  }\n\n  virtual void initialize() { iterate=trialIterate->clone(); nNewton=0;};\n  virtual double muOnSuccess(int step);\n  virtual double muOnFailure();\n  virtual double muFinal() { return p.muFinal;};\n  virtual void updateModelOfHomotopy(int step); \n  virtual void initializeCorrector(); \n  virtual void finalizeCorrector() { nNewton += corrector.stepsPerformed(); pp.newtonSum=nNewton;};\n  virtual void updateIterate();\n  virtual void recoverIterate() { *trialIterate=*iterate; }\n  virtual double lengthOfPath() {if(pp.eta.isValid()) return 2*p.mu*pp.slope; else return 1e300;};\n  void printDiagnosis();\n\n  virtual void logQuantities()\n  {\n    HomotopyBase::logQuantities();\n    pp.logStep();\n    printDiagnosis();\n  }\n\nprivate:\n  std::unique_ptr<AbstractFunctionSpaceElement> iterate;\n  AbstractNorm const& norm;\n  AbstractNewtonDirection& solver;\n  InteriorPointParametersSqrt pp;\n  JModel jModel;\n  JModelLin jModelL;\n  AbstractNorm const* normPlain;\n  int nNewton;\n  boost::timer::cpu_timer overalltime;\n};\n\n/// Performs bisection algorithm to find a zero of a \n/**************************************************\n * Assumptions\n *\n *  a < b\n *\n *  Equation f with has double operator(double ) monotonically INCREASING\n *\n ************************************************************/\n\ntemplate<class Equation>\ndouble bisection(double a, double b, Equation const& f, double accuracy, int& iterations)\n{\n  iterations = 0;\n  double u;\n  do {\n    ++iterations;\n    u=(a+b)/2;\n    if(u == a) return b;\n    if(f(u) > 0) b=u; else a=u;\n  } \n  while(b-a >= accuracy && (a+b)/2 != a && (a+b)/2 != b && iterations<50);\n  if(iterations > 48) std::cout << \"Warning: bisection algorithm performed > 48 iterations\" << std::endl;\n  return u;  \n}\n\nclass InteriorPointSlopeEstimate : public HomotopyBase\n{\n\npublic:\n  InteriorPointSlopeEstimate(NewtonsMethod& n_, AbstractNorm const& norm_, InteriorPointParameters& p_, \n                          AbstractNewtonDirection& solver_, AbstractNorm const* normPlain_=0,\n                          NewtonsMethod* finalsolver_=0) : \n    HomotopyBase(n_, p_),\n    norm(norm_),\n    solver(solver_),\n    stp(0),\n    normPlain(normPlain_),\n    finalsolver(finalsolver_)\n  {\n    if(!normPlain_) normPlain=&norm;\n  }\n\n  virtual void initialize() { \n    iterate=trialIterate->clone(); \n    tangent=trialIterate->clone(); \n    nNewton=0;\n  };\n  virtual void finalize() {};\n\n  virtual double muOnSuccess(int step);\n\n  virtual double muOnFailure() { \n    p.sigma=0.5+p.sigma/2.0;    \n    return p.mu*p.sigma;\n  };\n\n  virtual double muFinal() { return p.muFinal;};\n\n  virtual void updateModelOfHomotopy(int step);\n\n  virtual void computePredictor(int step){}\n\n\n  virtual void initializeCorrector(); \n  virtual void finalizeCorrector() {    nNewton += corrector.stepsPerformed(); pp.newtonSum=nNewton;};\n\n  virtual void finalizeHomotopy();\n\n  virtual void updateIterate(); \n\n  virtual void recoverIterate() { *trialIterate=*iterate; }\n\n\n  virtual double lengthOfPath() \n  { \n    if(pp.eta.isValid())\n      return 2*p.mu*pp.slope; \n    else\n      return 1e300;\n  };\n\n  virtual void logQuantities()\n  {\n    HomotopyBase::logQuantities();\n    pp.logStep();\n    printDiagnosis();\n  }\n\n  void printDiagnosis();\n\nprivate:\n  std::unique_ptr<AbstractFunctionSpaceElement> iterate, tangent;\n\n  AbstractNorm const& norm;\n  AbstractNewtonDirection& solver;\n  InteriorPointParametersSqrt pp;\n  JModelLin jModelL;\n  int stp;\n  AbstractNorm const* normPlain;\n  NewtonsMethod* finalsolver;\n  int nNewton;\n  boost::timer::cpu_timer overalltime;\n};\n\n}  // namespace Kaskade\n\n#endif\n", "meta": {"hexsha": "bcc702ce35cb1b6ff3a5e6c4f31769a4b2c30c11", "size": 10164, "ext": "hh", "lang": "C++", "max_stars_repo_path": "Kaskade/algorithm/homotopy_base.hh", "max_stars_repo_name": "chenzongxiong/streambox", "max_stars_repo_head_hexsha": "76f95780d1bf6c02731e39d8ac73937cea352b95", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2019-07-03T14:03:31.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-19T10:18:49.000Z", "max_issues_repo_path": "Kaskade/algorithm/homotopy_base.hh", "max_issues_repo_name": "chenzongxiong/streambox", "max_issues_repo_head_hexsha": "76f95780d1bf6c02731e39d8ac73937cea352b95", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2020-02-17T12:01:31.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-09T22:02:36.000Z", "max_forks_repo_path": "Kaskade/algorithm/homotopy_base.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": 26.2635658915, "max_line_length": 156, "alphanum_fraction": 0.7047422275, "num_tokens": 2509, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.611381973294151, "lm_q2_score": 0.5156199157230157, "lm_q1q2_score": 0.31524072154450117}}
{"text": "//\n// Copyright (c) 2020 Kenshi Abe\n//\n\n#include \"Trainer.hpp\"\n\n#include <fstream>\n#include <iostream>\n#include <boost/archive/binary_iarchive.hpp>\n#include <boost/archive/binary_oarchive.hpp>\n#include <boost/filesystem.hpp>\n#include <boost/serialization/unordered_map.hpp>\n#include \"Node.hpp\"\n\nnamespace Trainer {\n\n/// @param mode variant of CFR algorithm\n/// @param seed random seed\n/// @param strategyPaths paths to the binary files that represent fixed strategies\ntemplate <typename T>\nTrainer<T>::Trainer(const std::string &mode, const uint32_t seed, const std::vector<std::string> &strategyPaths) : mEngine(seed), mNodeTouchedCnt(0), mModeStr(mode) {\n    mGame = new T(mEngine);\n    mFolderPath = \"../strategies/\" + mGame->name();\n    boost::filesystem::create_directories(mFolderPath);\n    mFixedStrategies = new std::unordered_map<std::string, Node *>[mGame->playerNum()];\n    mUpdate = new bool[mGame->playerNum()];\n    for (int i = 0; i < mGame->playerNum(); ++i) {\n        if (strategyPaths.size() >= i + 1 && !strategyPaths[i].empty()) {\n            std::cout << \"load strategy \\\"\" << strategyPaths[i] << \"\\\" as static player \" << i << std::endl;\n            std::ifstream ifs(strategyPaths[i]);\n            boost::archive::binary_iarchive ia(ifs);\n            ia >> mFixedStrategies[i];\n            ifs.close();\n            mUpdate[i] = false;\n        } else {\n            mUpdate[i] = true;\n        }\n    }\n}\n\ntemplate <typename T>\nTrainer<T>::~Trainer() {\n    for (auto &itr : mNodeMap) {\n        delete itr.second;\n    }\n    for (int i = 0; i < mGame->playerNum(); ++i) {\n        if (mUpdate[i]) {\n            continue;\n        }\n        for (auto &itr : mFixedStrategies[i]) {\n            delete itr.second;\n        }\n    }\n    delete[] mFixedStrategies;\n    delete[] mUpdate;\n    delete mGame;\n}\n\n/// @brief Calculate the expected payoff of each player\n/// @param game game\n/// @param strategies list of strategies for each player\n/// @return list of expected payoffs\ntemplate <typename T>\nstd::vector<float> Trainer<T>::CalculatePayoff(const T &game, const std::vector<std::function<const float *(const T &)>> &strategies) {\n    // return payoff for terminal states\n    if (game.done()) {\n        std::vector<float> payoffs(game.playerNum());\n        for (int i = 0; i < game.playerNum(); ++i) {\n            payoffs[i] = game.payoff(i);\n        }\n        return payoffs;\n    }\n\n    // chance node turn\n    const int actionNum = game.actionNum();\n    if (game.isChanceNode()) {\n        std::vector<float> nodeUtils(game.playerNum());\n        for (int i = 0; i < game.playerNum(); ++i) {\n            nodeUtils[i] = 0.0f;\n        }\n        for (int a = 0; a < actionNum; ++a) {\n            auto game_cp(game);\n            game_cp.step(a);\n            const float chanceProbability = game_cp.chanceProbability();\n            std::vector<float> utils = CalculatePayoff(game_cp, strategies);\n            for (int i = 0; i < game.playerNum(); ++i) {\n                nodeUtils[i] += chanceProbability * utils[i];\n            }\n        }\n        return nodeUtils;\n    }\n\n    // for each action, recursively calculate payoff with additional history and probability\n    const int player = game.currentPlayer();\n    std::vector<float> nodeUtils(game.playerNum());\n    for (int i = 0; i < game.playerNum(); ++i) {\n        nodeUtils[i] = 0.0f;\n    }\n    for (int a = 0; a < actionNum; ++a) {\n        auto game_cp(game);\n        game_cp.step(a);\n        std::vector<float> utils = CalculatePayoff(game_cp, strategies);\n        for (int i = 0; i < game.playerNum(); ++i) {\n            nodeUtils[i] += strategies[player](game)[a] * utils[i];\n        }\n    }\n    return nodeUtils;\n}\n\n/// @brief Execute the CFR algorithm to compute an approximate Nash equilibrium\n/// @param iterations number of iterations of CFR\ntemplate <typename T>\nvoid Trainer<T>::train(const int iterations) {\n    float utils[mGame->playerNum()];\n\n    for (int i = 0; i < iterations; ++i) {\n        for (int p = 0; p < mGame->playerNum(); ++p) {\n            if (!mUpdate[p]) {\n                continue;\n            }\n            if (mModeStr == \"vanilla\") {\n                mGame->reset(false);\n                utils[p] = CFR(*mGame, p, 1.0f, 1.0f);\n            } else {\n                mGame->reset();\n                if (mModeStr == \"chance\") {\n                    utils[p] = chanceSamplingCFR(*mGame, p, 1.0f, 1.0f);\n                } else if (mModeStr == \"external\") {\n                    utils[p] = externalSamplingCFR(*mGame, p);\n                } else if (mModeStr == \"outcome\") {\n                    utils[p] = std::get<0>(outcomeSamplingCFR(*mGame, p, i, 1.0f, 1.0f, 1.0f));\n                } else {\n                    assert(false);\n                }\n            }\n        }\n        if (i % 1000 == 0) {\n            std::cout << \"iteration:\" << i << \", cumulative nodes touched: \" << mNodeTouchedCnt << \", infosets num: \" << mNodeMap.size() << \", expected payoffs: (\";\n            for (int p = 0; p < mGame->playerNum(); ++p) {\n                std::cout << utils[p] << \",\";\n            }\n            std::cout << \")\" << std::endl;\n        }\n        if (i != 0 && i % 10000000 == 0) {\n            writeStrategyToBin(i);\n        }\n    }\n\n    writeStrategyToBin();\n}\n\n/// @brief Main procedure of vanilla CFR\n/// @param game game\n/// @param playerIndex player whose strategy is updated in the current iteration\n/// @param pi the probability of reaching the current game node if all players other than the acting player always choose actions leading to the current game node\n/// @param po the probability of reaching the current game node if the acting player always chooses actions leading to the current game node\n/// @return expected payoff of the specified player at the current game node\ntemplate <typename T>\nfloat Trainer<T>::CFR(const T &game, const int playerIndex, const float pi, const float po) {\n    ++mNodeTouchedCnt;\n\n    // return payoff for terminal states\n    if (game.done()) {\n        return game.payoff(playerIndex);\n    }\n\n    // chance node turn\n    const int actionNum = game.actionNum();\n    if (game.isChanceNode()) {\n        float nodeUtil = 0.0f;\n        for (int a = 0; a < actionNum; ++a) {\n            auto game_cp(game);\n            game_cp.step(a);\n            const float chanceProbability = game_cp.chanceProbability();\n            nodeUtil += chanceProbability * CFR(game_cp, playerIndex, pi, po * chanceProbability);\n        }\n        return nodeUtil;\n    }\n\n    // get information set string representation\n    std::string infoSet = game.infoSetStr();\n\n    // treat static player as chance node\n    const int player = game.currentPlayer();\n    if (!mUpdate[player]) {\n        float nodeUtil = 0.0f;\n        for (int a = 0; a < actionNum; ++a) {\n            auto game_cp(game);\n            game_cp.step(a);\n            const float chanceProbability = float(mFixedStrategies[player].at(infoSet)->averageStrategy()[a]);\n            nodeUtil += chanceProbability * CFR(game_cp, playerIndex, pi, po * chanceProbability);\n        }\n        return nodeUtil;\n    }\n\n    // get information set node or create it if nonexistant\n    Node *node = mNodeMap[infoSet];\n    if (node == nullptr) {\n        node = new Node(actionNum);\n        mNodeMap[infoSet] = node;\n    }\n\n    // get current strategy through regret-matching\n    const float *strategy = node->strategy();\n\n    // for each action, recursively call CFR with additional history and probability\n    float utils[actionNum];\n    float nodeUtil = 0;\n    for (int a = 0; a < actionNum; ++a) {\n        auto game_cp(game);\n        game_cp.step(a);\n        if (player == playerIndex) {\n            utils[a] = CFR(game_cp, playerIndex, pi * strategy[a], po);\n        } else {\n            utils[a] = CFR(game_cp, playerIndex, pi, po * strategy[a]);\n        }\n        nodeUtil += strategy[a] * utils[a];\n    }\n\n    if (player == playerIndex) {\n        // for each action, compute and accumulate counterfactual regret\n        for (int a = 0; a < actionNum; ++a) {\n            const float regret = utils[a] - nodeUtil;\n            const float regretSum = node->regretSum(a) + po * regret;\n            node->regretSum(a, regretSum);\n        }\n        // update average strategy across all training iterations\n        node->strategySum(strategy, pi);\n    }\n\n    return nodeUtil;\n}\n\n/// @brief Main procedure of chance-sampling MCCFR\n/// @param game game\n/// @param playerIndex player whose strategy is updated in the current iteration\n/// @param pi the probability of reaching the current game node if all players other than the acting player always choose actions leading to the current game node\n/// @param po the probability of reaching the current game node if the acting player and the chance player always choose actions leading to the current game node\n/// @return estimated expected payoff of the specified player at the current game node\ntemplate <typename T>\nfloat Trainer<T>::chanceSamplingCFR(const T &game, const int playerIndex, const float pi, const float po) {\n    ++mNodeTouchedCnt;\n\n    // return payoff for terminal states\n    if (game.done()) {\n        return game.payoff(playerIndex);\n    }\n\n    // get information set string representation\n    std::string infoSet = game.infoSetStr();\n\n    // treat static player as chance node\n    const int actionNum = game.actionNum();\n    const int player = game.currentPlayer();\n    if (!mUpdate[player]) {\n        auto game_cp(game);\n        auto strategy = mFixedStrategies[player].at(infoSet)->averageStrategy();\n        std::discrete_distribution<int> dist(strategy, strategy + actionNum);\n        game_cp.step(dist(mEngine));\n        return chanceSamplingCFR(game_cp, playerIndex, pi, po);\n    }\n\n    // get information set node or create it if nonexistant\n    Node *node = mNodeMap[infoSet];\n    if (node == nullptr) {\n        node = new Node(actionNum);\n        mNodeMap[infoSet] = node;\n    }\n\n    // get current strategy through regret-matching\n    const float *strategy = node->strategy();\n\n    // for each action, recursively call cfr with additional history and probability\n    float utils[actionNum];\n    float nodeUtil = 0;\n    for (int a = 0; a < actionNum; ++a) {\n        auto game_cp(game);\n        game_cp.step(a);\n        if (player == playerIndex) {\n            utils[a] = chanceSamplingCFR(game_cp, playerIndex, pi * strategy[a], po);\n        } else {\n            utils[a] = chanceSamplingCFR(game_cp, playerIndex, pi, po * strategy[a]);\n        }\n        nodeUtil += strategy[a] * utils[a];\n    }\n\n    if (player == playerIndex) {\n        // for each action, compute and accumulate counterfactual regret\n        for (int a = 0; a < actionNum; ++a) {\n            const float regret = utils[a] - nodeUtil;\n            const float regretSum = node->regretSum(a) + po * regret;\n            node->regretSum(a, regretSum);\n        }\n        // update average strategy across all training iterations\n        node->strategySum(strategy, pi);\n    }\n\n    return nodeUtil;\n}\n\n/// @brief Main procedure of external-sampling MCCFR\n/// @param game game\n/// @param playerIndex player whose strategy is updated in the current iteration\n/// @return estimated expected payoff of the specified player at the current game node\ntemplate <typename T>\nfloat Trainer<T>::externalSamplingCFR(const T &game, const int playerIndex) {\n    ++mNodeTouchedCnt;\n\n    // return payoff for terminal states\n    if (game.done()) {\n        return game.payoff(playerIndex);\n    }\n\n    // get information set string representation\n    std::string infoSet = game.infoSetStr();\n\n    // external sampling with stochastically-weighted averaging cannot treat static player\n    const int actionNum = game.actionNum();\n    const int player = game.currentPlayer();\n    assert(mUpdate[player] && \"External sampling with stochastically-weighted averaging cannot treat static player.\");\n\n    // get information set node or create it if nonexistant\n    Node *node = mNodeMap[infoSet];\n    if (node == nullptr) {\n        node = new Node(actionNum);\n        mNodeMap[infoSet] = node;\n    }\n\n    // get current strategy through regret-matching\n    const float *strategy = node->strategy();\n\n    // if current player is not the target player, sample a single action and recursively call cfr\n    if (player != playerIndex) {\n        auto game_cp(game);\n        std::discrete_distribution<int> dist(strategy, strategy + actionNum);\n        game_cp.step(dist(mEngine));\n        const float util = externalSamplingCFR(game_cp, playerIndex);\n        // update average strategy\n        node->strategySum(strategy, 1.0f);\n        return util;\n    }\n\n    // for each action, recursively call cfr with additional history and probability\n    float utils[actionNum];\n    float nodeUtil = 0;\n    for (int a = 0; a < actionNum; ++a) {\n        auto game_cp(game);\n        game_cp.step(a);\n        utils[a] = externalSamplingCFR(game_cp, playerIndex);\n        nodeUtil += strategy[a] * utils[a];\n    }\n\n    // for each action, compute and accumulate counterfactual regret\n    for (int a = 0; a < actionNum; ++a) {\n        const float regret = utils[a] - nodeUtil;\n        const float regretSum = node->regretSum(a) + regret;\n        node->regretSum(a, regretSum);\n    }\n\n    return nodeUtil;\n}\n\n/// @brief Main procedure of outcome-sampling MCCFR\n/// @param game game\n/// @param playerIndex player whose strategy is updated in the current iteration\n/// @param pi the probability of reaching the current game node if all players other than the acting player always choose actions leading to the current game node\n/// @param po the probability of reaching the current game node if the acting player and the chance player always choose actions leading to the current game node\n/// @param s the probability of reaching the current game node if the chance player always chooses actions leading to the current game node and the other players act according to the sample profile\n/// @return estimated expected payoff of the specified player at the current game node, and the probability of reaching the terminal game node if the chance player always chooses actions leading to the terminal game node\ntemplate <typename T>\nstd::tuple<float, float> Trainer<T>::outcomeSamplingCFR(const T &game, const int playerIndex, const int iteration , const float pi, const float po, const float s) {\n    ++mNodeTouchedCnt;\n\n    // return payoff for terminal states\n    if (game.done()) {\n        return std::make_tuple(game.payoff(playerIndex) / s, 1.0f);\n    }\n\n    // get information set string representation\n    std::string infoSet = game.infoSetStr();\n\n    // outcome sampling with stochastically-weighted averaging cannot treat static player\n    const int actionNum = game.actionNum();\n    const int player = game.currentPlayer();\n    assert(mUpdate[player] && \"Outcome sampling with stochastically-weighted averaging cannot treat static player.\");\n\n    // get information set node or create it if nonexistant\n    Node *node = mNodeMap[infoSet];\n    if (node == nullptr) {\n        node = new Node(actionNum);\n        mNodeMap[infoSet] = node;\n    }\n\n    // get current strategy through regret-matching\n    const float *strategy = node->strategy();\n\n    // if current player is the target player, sample a single action according to epsilon-on-policy\n    // otherwise, sample a single action according to the player's strategy\n    const float epsilon = 0.6;\n    float probability[actionNum];\n    if (player == playerIndex) {\n        for (int a = 0; a < actionNum; ++a) {\n            probability[a] = (epsilon / (float) actionNum) + (1.0f - epsilon) * strategy[a];\n        }\n    } else {\n        for (int a = 0; a < actionNum; ++a) {\n            probability[a] = strategy[a];\n        }\n    }\n    std::discrete_distribution<int> dist(probability, probability + actionNum);\n    const int action = dist(mEngine);\n\n    // for sampled action, recursively call cfr with additional history and probability\n    float util, pTail;\n    auto game_cp(game);\n    game_cp.step(action);\n    const float newPi = pi * (player == playerIndex ? strategy[action] : 1.0f);\n    const float newPo = po * (player == playerIndex ? 1.0f : strategy[action]);\n    std::tuple<float, float> ret = outcomeSamplingCFR(game_cp, playerIndex, iteration, newPi, newPo, s * probability[action]);\n    util = std::get<0>(ret);\n    pTail = std::get<1>(ret);\n    if (player == playerIndex) {\n        // for each action, compute and accumulate counterfactual regret\n        const float W = util * po;\n        for (int a = 0; a < actionNum; ++a) {\n            const float regret = a == action ? W * (1.0f - strategy[action]) * pTail : -W * pTail * strategy[action];\n            const float regretSum = node->regretSum(a) + regret;\n            node->regretSum(a, regretSum);\n        }\n    } else {\n        // update average strategy\n        node->strategySum(strategy, po / s);\n    }\n    return std::make_tuple(util, pTail * strategy[action]);\n}\n\n/// @brief Save the current average strategy as a binary file\n/// @param iteration current iteration\ntemplate <typename T>\nvoid Trainer<T>::writeStrategyToBin(const int iteration) const {\n    for (auto &itr : mNodeMap) {\n//        std::cout << itr.first << \":\";\n        for (int i = 0; i < itr.first.size(); ++i) {\n            std::cout << int(itr.first[i]);\n        }\n        std::cout << \":\";\n        for (int i = 0; i < itr.second->actionNum(); ++i) {\n            std::cout << itr.second->averageStrategy()[i] << \",\";\n        }\n        std::cout << std::endl;\n    }\n    std::string path = iteration > 0 ? \"strategy_\" + std::to_string(iteration)\n                                     : \"strategy\";\n    path += \"_\" + mModeStr + \".bin\";\n    std::ofstream ofs(mFolderPath + \"/\" + path);\n    boost::archive::binary_oarchive oa(ofs);\n    oa << mNodeMap;\n    ofs.close();\n}\n\n} // namespace\n\n", "meta": {"hexsha": "fa86e886f78a043a7d8d4a0d410e85749587b766", "size": 17837, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "RegretMinimization/Trainer/Trainer.cpp", "max_stars_repo_name": "bakanaouji/cpp-cfr", "max_stars_repo_head_hexsha": "636862e74286263690301cf9316ef5836137d5fd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 50.0, "max_stars_repo_stars_event_min_datetime": "2020-01-23T16:50:28.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T19:28:43.000Z", "max_issues_repo_path": "RegretMinimization/Trainer/Trainer.cpp", "max_issues_repo_name": "bakanaouji/cpp-cfr", "max_issues_repo_head_hexsha": "636862e74286263690301cf9316ef5836137d5fd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "RegretMinimization/Trainer/Trainer.cpp", "max_forks_repo_name": "bakanaouji/cpp-cfr", "max_forks_repo_head_hexsha": "636862e74286263690301cf9316ef5836137d5fd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2020-02-17T11:56:39.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-10T09:33:12.000Z", "avg_line_length": 38.524838013, "max_line_length": 220, "alphanum_fraction": 0.6193866682, "num_tokens": 4325, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.611381973294151, "lm_q2_score": 0.5156199157230156, "lm_q1q2_score": 0.3152407215445011}}
{"text": "// Copyright 2018 The Simons Foundation, Inc. - All Rights Reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//    http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\n#ifndef NETKET_LOCAL_OPERATOR_HPP\n#define NETKET_LOCAL_OPERATOR_HPP\n\n#include <mpi.h>\n#include <Eigen/Dense>\n#include <algorithm>\n#include <cassert>\n#include <complex>\n#include <iostream>\n#include <iterator>\n#include <limits>\n#include <map>\n#include <vector>\n#include \"Hilbert/abstract_hilbert.hpp\"\n#include \"Utils/kronecker_product.hpp\"\n#include \"Utils/next_variation.hpp\"\n#include \"abstract_operator.hpp\"\n\nnamespace netket {\n\n/**\n    Class for local operators acting on a list of sites and for generic local\n    Hilbert spaces.\n*/\n\nclass LocalOperator : public AbstractOperator {\n public:\n  using MelType = Complex;\n  using MatType = std::vector<std::vector<MelType>>;\n  using SiteType = std::vector<int>;\n  using MapType = std::map<std::vector<double>, int>;\n  using StateType = std::vector<std::vector<double>>;\n  using ConnType = std::vector<std::vector<int>>;\n  using VectorType = AbstractOperator::VectorType;\n  using VectorRefType = AbstractOperator::VectorRefType;\n  using VectorConstRefType = AbstractOperator::VectorConstRefType;\n\n private:\n  const AbstractHilbert &hilbert_;\n  std::vector<MatType> mat_;\n  std::vector<SiteType> sites_;\n\n  std::vector<MapType> invstate_;\n  std::vector<StateType> states_;\n  std::vector<ConnType> connected_;\n\n  double constant_;\n\n  std::size_t nops_;\n\n  static constexpr double mel_cutoff_ = 1.0e-6;\n\n public:\n  explicit LocalOperator(const AbstractHilbert &hilbert, double constant = 0.)\n      : hilbert_(hilbert), constant_(constant), nops_(0) {}\n\n  explicit LocalOperator(const AbstractHilbert &hilbert,\n                         const std::vector<MatType> &mat,\n                         const std::vector<SiteType> &sites,\n                         double constant = 0.)\n      : hilbert_(hilbert), constant_(constant) {\n    for (std::size_t i = 0; i < mat.size(); i++) {\n      Push(mat[i], sites[i]);\n    }\n    Init();\n  }\n\n  explicit LocalOperator(const AbstractHilbert &hilbert, const MatType &mat,\n                         const SiteType &sites, double constant = 0.)\n      : hilbert_(hilbert), constant_(constant) {\n    Push(mat, sites);\n    // TODO sort sites and swap columns of mat accordingly\n    Init();\n  }\n\n  void Push(const MatType &mat, const SiteType &sites) {\n    std::size_t found = std::distance(\n        sites_.begin(), std::find(sites_.begin(), sites_.end(), sites));\n    if (found < sites_.size()) {\n      for (std::size_t i = 0; i < mat_[found].size(); i++) {\n        for (std::size_t j = 0; j < mat_[found][i].size(); j++) {\n          mat_[found][i][j] += mat[i][j];\n        }\n      }\n    } else {\n      mat_.push_back(mat);\n      sites_.push_back(sites);\n    }\n  }\n\n  void Init() {\n    if (!hilbert_.IsDiscrete()) {\n      throw InvalidInputError(\n          \"Cannot construct operators on infinite local hilbert spaces\");\n    }\n    if (sites_.size() != mat_.size()) {\n      throw InvalidInputError(\n          \"Operators must specify a consistent set of acting_on specifiers\");\n    }\n\n    nops_ = mat_.size();\n\n    connected_.clear();\n    states_.clear();\n    invstate_.clear();\n\n    connected_.resize(nops_);\n    states_.resize(nops_);\n    invstate_.resize(nops_);\n\n    for (std::size_t op = 0; op < nops_; op++) {\n      const auto sites = sites_[op];\n      const auto mat = mat_[op];\n      auto &connected = connected_[op];\n      auto &states = states_[op];\n      auto &invstate = invstate_[op];\n\n      if (*std::max_element(sites.begin(), sites.end()) >= hilbert_.Size() ||\n          *std::min_element(sites.begin(), sites.end()) < 0) {\n        throw InvalidInputError(\"Operator acts on an invalid set of sites\");\n      }\n\n      auto localstates = hilbert_.LocalStates();\n      const auto localsize = localstates.size();\n\n      // Finding the non-zero matrix elements\n      const double epsilon = mel_cutoff_;\n\n      connected.resize(mat.size());\n\n      if (mat.size() != std::pow(localsize, sites.size())) {\n        throw InvalidInputError(\n            \"Matrix size in operator is inconsistent with Hilbert space\");\n      }\n\n      for (std::size_t i = 0; i < mat.size(); i++) {\n        for (std::size_t j = 0; j < mat[i].size(); j++) {\n          if (mat.size() != mat[i].size()) {\n            throw InvalidInputError(\n                \"Matrix size in operator is inconsistent with Hilbert space\");\n          }\n\n          if (i != j && std::abs(mat[i][j]) > epsilon) {\n            connected[i].push_back(j);\n          }\n        }\n      }\n\n      // Construct the mapping\n      // Internal index -> State\n      std::vector<double> st(sites.size(), 0);\n\n      do {\n        states.push_back(st);\n      } while (netket::next_variation(st.begin(), st.end(), localsize - 1));\n\n      for (std::size_t i = 0; i < states.size(); i++) {\n        for (std::size_t k = 0; k < states[i].size(); k++) {\n          states[i][k] = localstates[states[i][k]];\n        }\n      }\n\n      // Now construct the inverse mapping\n      // State -> Internal index\n      std::size_t k = 0;\n      for (auto state : states) {\n        invstate[state] = k;\n        k++;\n      }\n\n      assert(k == mat.size());\n    }\n  }\n\n  void FindConn(VectorConstRefType v, std::vector<Complex> &mel,\n                std::vector<std::vector<int>> &connectors,\n                std::vector<std::vector<double>> &newconfs) const override {\n    assert(v.size() == hilbert_.Size());\n\n    connectors.clear();\n    newconfs.clear();\n    mel.clear();\n\n    connectors.resize(1);\n    newconfs.resize(1);\n    mel.resize(1);\n\n    mel[0] = constant_;\n    connectors[0].resize(0);\n    newconfs[0].resize(0);\n\n    for (std::size_t opn = 0; opn < nops_; opn++) {\n      int st1 = StateNumber(v, opn);\n\n      assert(st1 < int(mat_[opn].size()));\n      assert(st1 < int(connected_[opn].size()));\n\n      mel[0] += (mat_[opn][st1][st1]);\n\n      // off-diagonal part\n      for (auto st2 : connected_[opn][st1]) {\n        connectors.push_back(sites_[opn]);\n        assert(st2 < int(states_[opn].size()));\n        newconfs.push_back(states_[opn][st2]);\n        mel.push_back(mat_[opn][st1][st2]);\n      }\n    }\n  }\n\n  // FindConn for a specific operator\n  void FindConn(std::size_t opn, VectorConstRefType v,\n                std::vector<Complex> &mel,\n                std::vector<std::vector<int>> &connectors,\n                std::vector<std::vector<double>> &newconfs) const {\n    assert(opn < mat_.size() && opn >= 0);\n\n    mel.resize(1, 0.);\n    connectors.resize(1);\n    newconfs.resize(1);\n\n    int st1 = StateNumber(v, opn);\n    assert(st1 < int(mat_[opn].size()));\n    assert(st1 < int(connected_[opn].size()));\n\n    mel[0] = (mat_[opn][st1][st1]);\n\n    // off-diagonal part\n    for (auto st2 : connected_[opn][st1]) {\n      connectors.push_back(sites_[opn]);\n      assert(st2 < int(states_[opn].size()));\n      newconfs.push_back(states_[opn][st2]);\n      mel.push_back(mat_[opn][st1][st2]);\n    }\n  }\n\n  inline int StateNumber(VectorConstRefType v, int opn) const {\n    // TODO use a mask instead of copies\n    std::vector<double> state(sites_[opn].size());\n    for (std::size_t i = 0; i < sites_[opn].size(); i++) {\n      state[i] = v(sites_[opn][i]);\n    }\n    return invstate_[opn].at(state);\n  }\n\n  // Product of two local operators, performing KroneckerProducts as necessary\n  friend LocalOperator operator*(const LocalOperator &lhs,\n                                 const LocalOperator &rhs) {\n    // TODO\n    // assert(lhs.Hilbert() == rhs.Hilbert());\n    // check if sites have intersections, in that case this algorithm is wrong\n    std::vector<MatType> mat;\n    std::vector<SiteType> sites;\n\n    for (std::size_t opn = 0; opn < lhs.mat_.size(); opn++) {\n      for (std::size_t opn1 = 0; opn1 < rhs.mat_.size(); opn1++) {\n        if (lhs.sites_[opn] == rhs.sites_[opn1]) {\n          mat.push_back(netket::MatrixProduct(lhs.mat_[opn], rhs.mat_[opn1]));\n          sites.push_back(lhs.sites_[opn]);\n        } else {\n          mat.push_back(\n              netket::KroneckerProduct(lhs.mat_[opn], rhs.mat_[opn1]));\n          SiteType sitesum = lhs.sites_[opn];\n          sitesum.insert(sitesum.end(), rhs.sites_[opn1].begin(),\n                         rhs.sites_[opn1].end());\n          sites.push_back(sitesum);\n        }\n      }\n    }\n    auto constant = lhs.constant_ * rhs.constant_;\n    auto opret = LocalOperator(lhs.GetHilbert(), mat, sites, constant);\n\n    if (std::abs(lhs.constant_) > mel_cutoff_) {\n      opret += lhs.constant_ * rhs;\n    }\n    if (std::abs(rhs.constant_) > mel_cutoff_) {\n      opret += rhs.constant_ * lhs;\n    }\n\n    return opret;\n  }\n\n  friend LocalOperator operator+(const LocalOperator &lhs,\n                                 const LocalOperator &rhs) {\n    assert(rhs.hilbert_.LocalStates().size() ==\n           lhs.hilbert_.LocalStates().size());\n\n    auto sites = lhs.sites_;\n    auto mat = lhs.mat_;\n\n    sites.insert(sites.end(), rhs.sites_.begin(), rhs.sites_.end());\n    mat.insert(mat.end(), rhs.mat_.begin(), rhs.mat_.end());\n\n    return LocalOperator(lhs.GetHilbert(), mat, sites,\n                         lhs.constant_ + rhs.constant_);\n  }\n\n  friend LocalOperator operator+(const LocalOperator &lhs, double constant) {\n    auto sites = lhs.sites_;\n    auto mat = lhs.mat_;\n\n    return LocalOperator(lhs.GetHilbert(), mat, sites,\n                         lhs.constant_ + constant);\n  }\n\n  LocalOperator &operator+=(const LocalOperator &rhs) {\n    assert(rhs.hilbert_.LocalStates().size() ==\n           this->hilbert_.LocalStates().size());\n\n    this->sites_.insert(this->sites_.end(), rhs.sites_.begin(),\n                        rhs.sites_.end());\n    this->mat_.insert(this->mat_.end(), rhs.mat_.begin(), rhs.mat_.end());\n    this->constant_ += rhs.constant_;\n    this->Init();\n\n    return *this;\n  }\n\n  LocalOperator &operator+=(double constant) {\n    this->constant_ += constant;\n    return *this;\n  }\n\n  template <class T>\n  friend LocalOperator operator*(T lhs, const LocalOperator &rhs) {\n    assert(std::imag(lhs) == 0.);\n    auto mat = rhs.mat_;\n    auto sites = rhs.sites_;\n\n    for (std::size_t opn = 0; opn < mat.size(); opn++) {\n      for (std::size_t i = 0; i < mat[opn].size(); i++) {\n        for (std::size_t j = 0; j < mat[opn][i].size(); j++)\n          mat[opn][i][j] *= lhs;\n      }\n    }\n\n    return LocalOperator(rhs.GetHilbert(), mat, sites,\n                         std::real(lhs * rhs.constant_));\n  }\n\n  const std::vector<MatType> &LocalMatrices() const { return mat_; }\n  const std::vector<SiteType> &ActingOn() const { return sites_; }\n\n  const AbstractHilbert &GetHilbert() const noexcept override {\n    return hilbert_;\n  }\n\n  std::size_t Size() const { return mat_.size(); }\n};  // namespace netket\n\n}  // namespace netket\n#endif\n", "meta": {"hexsha": "04fa39518e4b98cc198bdcdcafca630a95d15f57", "size": 11239, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "NetKet/Operator/local_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/local_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/local_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": 30.7076502732, "max_line_length": 78, "alphanum_fraction": 0.6029895898, "num_tokens": 2969, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6723316860482762, "lm_q2_score": 0.46879062662624377, "lm_q1q2_score": 0.31518279240325037}}
{"text": "//==================================================================================================\n/*!\n  @file\n\n  @copyright 2016 NumScale SAS\n\n  Distributed under the Boost Software License, Version 1.0.\n  (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\n*/\n//==================================================================================================\n#ifndef BOOST_SIMD_FUNCTION_COS_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_COS_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n\n /*!\n\n    @ingroup group-trigonometric\n    Function object implementing cos capabilities\n\n    cosine of the input in radians.\n\n    @par Semantic:\n\n    For every parameter of floating type\n\n    @code\n    auto r = cos(x);\n    @endcode\n\n    @par Notes\n    @c cos can be called with two parameters as :\n    @code\n    T r = cos(x, range_);\n    @endcode\n\n    or with a decorator as:\n\n    @code\n    T r = std_(cos)(x);\n    @endcode\n\n    or\n\n    @code\n    T r = restricted_(cos)(x);\n    @endcode\n\n\n    range is a tag that allows some control on the computation\n    accuracy and speed.\n\n    The control is on the reduction routine of the angle to the\n    \\f$[-\\pi/4, \\pi/4]\\f$ interval\n    they actually are 3 reduction routines protocol that respectly are\n    sufficient for small_, medium_ and big_ angle values to have within\n    cover test one ulp of difference with the according crlibm\n    (correctly rounded math library) result.\n\n    Each one covers respectively intervals \\f$[-A, A]\\f$ with :\n    @code\n    |--------------|---------------|-------------|\n    |              |   float  A    |  double  A  |\n    |--------------|---------------|-------------|\n    |    small_    |   20*Pi       | 20*Pi       |\n    |--------------|---------------|-------------|\n    |    medium_   |   2^6*Pi      | 2^18*Pi     |\n    |--------------|---------------|-------------|\n    |    big_      |   Inf         | Inf         |\n    |--------------|-----------------------------|\n    @endcode\n\n    In fact for each scalar singleton or simd vector of angles\n    there are two possibilities :\n    \\arg one is to test if all vector element(s) are in the proper range\n    for the consecutive increasing values of A until we reach a good\n    one or the last :\n    the corresponding template tags are small_, medium_ and big_\n    \\arg the second is to force directly a reduction method:\n    the corresponding template tags are direct_small_, direct_medium_\n    and direct_big_\n    @par\n    direct_small_ is NOT equivalent to small_ because there are also\n    two other methods for \\f$[0, \\pi/4]\\f$ (no reduction)\n    and \\f$[\\pi/4, \\pi/2]\\f$\n    (straight reduction) that are not considered in direct small_\n\n    Note that for float the direct_big_ case is both early an hyper costly and\n    shall be avoided whenever possible. To partially achieve this aim\n    when double are available on the platform, this part of reduction\n    is delegated to the double precision routines.\n\n    @par Advices\n    \\arg If there is no restrictions ever on your angles and you care for precision\n    use the default cos(x) or equivalently cos(x, big_)\n    \\arg if you do not care for precision you can use\n    cos(x, medium_) or cos(x, small_)\n    that will be accurate for their proper range and degrade in accuracy\n    with greater values.\n\n    @par\n    Now, the choice of direct or not relies on probabilities\n    computations:\n    assuming that a vector contains k elements and that testing all\n    values that are in an interval takes c cycles and the probability of a value\n    to be in interval \\f$[a, b]\\f$ is \\f$p(a, b)\\f$\n    the number of cycles used by a\n    direct\\f${}_i\\f$ method is simply the reduction time:\n    \\f$N(\\f$direct\\f${}_i)\\f$\n    On the other side the number of cycles for the non-direct methods will have a more\n    complicated expression :\n\n    \\f$\\hspace{5em}\\sum_{i=1}^{m} p(A_{i-1}, A_i)^k N(\\f$direct\\f${}_i)\\f$\n\n    @par\n    So the non direct methods will be interesting only if you want accurate\n    results everywhere and have anyhow a big proportion of small angles.\n    This is even more true (if possible) in simd and the more k is big, because\n    of the kth power.\n\n    @par\n    For instance in the medium_ float case:\n\n    \\arg if angles are equidistributed  on \\f$[0, 2^{16} \\pi]\\f$,\n    the \\f$p(0, 20\\pi)\\f$ will be\n    less than \\f$2^{-11}\\f$ and thus in sse2 there will be 1 quadruple over\n    1.76e+13 falling in the small_ case...\n\n    \\arg Even sorting will do no good because the sort cost will be against\n    the ratio of 1 successful quadruplet over 2048.\n    \\arg  Contrarily if your angles have a gaussian distribution with 0 mean and\n    \\f$10\\pi\\f$ standard deviation,  80% of the intervals will be in the \"small_\"\n    case (95% of the values).\n    \\arg Finally for those that are sure of their angles taking place in a fixed\n    range and want speed, three other template tags can be of choice:\n\n                clipped_very_small_, clipped_small_ and clipped_medium_\n\n    @par\n    they use the chosen reduction, but return Nan for any outsider.\n\n    @par Decorators\n\n    - std_ provides access to std::cos\n\n    - restricted_ is equivalent to the clipped_very_small_ tag\n\n    @see  sincos, cosd, cospi\n\n  **/\n  Value cos(Value const & v0);\n} }\n#endif\n\n#include <boost/simd/function/scalar/cos.hpp>\n#include <boost/simd/function/simd/cos.hpp>\n\n#endif\n", "meta": {"hexsha": "6d4f8bae51e976b8ad056fdca4777f3e5007ecd3", "size": 5416, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/function/cos.hpp", "max_stars_repo_name": "xmar/pythran", "max_stars_repo_head_hexsha": "dbf2e8b70ed1e4d4ac6b5f26ead4add940a72592", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2018-02-20T11:21:12.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-12T13:45:09.000Z", "max_issues_repo_path": "third_party/boost/simd/function/cos.hpp", "max_issues_repo_name": "xmar/pythran", "max_issues_repo_head_hexsha": "dbf2e8b70ed1e4d4ac6b5f26ead4add940a72592", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "third_party/boost/simd/function/cos.hpp", "max_forks_repo_name": "xmar/pythran", "max_forks_repo_head_hexsha": "dbf2e8b70ed1e4d4ac6b5f26ead4add940a72592", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2017-11-17T15:30:36.000Z", "max_forks_repo_forks_event_max_datetime": "2018-03-01T02:06:25.000Z", "avg_line_length": 33.6397515528, "max_line_length": 100, "alphanum_fraction": 0.6227843427, "num_tokens": 1359, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6893056295505783, "lm_q2_score": 0.4571367168274948, "lm_q1q2_score": 0.3151069123834607}}
{"text": "#define _USE_MATH_DEFINES\n/// code to make agents\n#include <vector>\n#include <cassert>\n#include <algorithm>\n#include <iostream>\n#include <random>\n\n#include <boost/foreach.hpp>\n\n#include <Rcpp.h>\n#include <RcppParallel.h>\n\n#include \"network.h\"\n#include \"landscape.h\"\n#include \"agents.h\"\n\n// to shuffle pop id\nvoid Population::shufflePop() {\n    if (order[0] == order[nAgents - 1])\n    {\n        for (size_t i = 0; i < static_cast<size_t>(nAgents); i++)\n        {\n            order[i] = i;\n        }\n        std::random_shuffle ( order.begin(), order.end() );\n    }\n    else {\n        std::random_shuffle ( order.begin(), order.end() );\n    }\n    \n}\n\n// to update agent Rtree\nvoid Population::updateRtree () {\n    // initialise rtree\n    bgi::rtree< value, bgi::quadratic<16> > tmpRtree;\n    for (int i = 0; i < nAgents; ++i)\n    {\n        point p = point(coordX[i], coordY[i]);\n        tmpRtree.insert(std::make_pair(p, i));\n    }\n    std::swap(agentRtree, tmpRtree);\n    tmpRtree.clear();\n}\n\n// uniform distribution for agent position\nstd::uniform_real_distribution<float> agent_ran_pos(0.0f, 1.f);\n\n// function for initial positions\nvoid Population::initPos(Resources food) {\n    for (size_t i = 0; i < static_cast<size_t>(nAgents); i++) {\n        coordX[i] = agent_ran_pos(rng) * food.dSize;\n        initX[i] = coordX[i];\n        coordY[i] = agent_ran_pos(rng) * food.dSize;\n        initY[i] = coordY[i];\n    }\n    updateRtree();\n}\n\n// set agent trait\nvoid Population::setTrait(const float mSize) {\n\n    // create a cauchy distribution, mSize is the scale\n    std::cauchy_distribution<float> agent_ran_trait(0.f, mSize);\n\n    for(int i = 0; i < nAgents; i++) {\n        sF[i] = agent_ran_trait(rng);\n        sH[i] = agent_ran_trait(rng);\n        sN[i] = agent_ran_trait(rng);\n    }\n}\n\nfloat get_distance(float x1, float x2, float y1, float y2) {\n    return std::sqrt(std::pow((x1 - x2), 2) + std::pow((y1 - y2), 2));\n}\n\n// general function for agents within distance\nstd::pair<int, int> Population::countAgents (\n    const float xloc, const float yloc) {\n    \n    int handlers = 0;\n    int nonhandlers = 0;\n    std::vector<value> near_agents;\n    // query for a simple box\n    agentRtree.query(bgi::satisfies([&](value const& v) {\n        return bg::distance(v.first, point(xloc, yloc)) < range_agents;}),\n        std::back_inserter(near_agents));\n\n    BOOST_FOREACH(value const& v, near_agents) {\n        \n        if(counter[v.second] > 0) handlers ++; else nonhandlers ++;\n    }\n    near_agents.clear();\n    // first element is number of near entities\n    // second is the identity of entities\n    return std::pair<int, int> {handlers, nonhandlers};\n}\n\n// function for near agent ids\nstd::vector<int> Population::getNeighbourId (\n    const float xloc, const float yloc) {\n    \n    std::vector<int> agent_id;\n    std::vector<value> near_agents;\n    // query for a simple box\n    // neighbours for associations are counted over the MOVEMENT RANGE\n    agentRtree.query(bgi::satisfies([&](value const& v) {\n        return bg::distance(v.first, point(xloc, yloc)) < range_move;}),\n        std::back_inserter(near_agents));\n\n    BOOST_FOREACH(value const& v, near_agents) {\n        agent_id.push_back(v.second);\n    }\n    near_agents.clear();\n    // first element is number of near entities\n    // second is the identity of entities\n    return agent_id;\n}\n\n// general function for items within distance\nint Population::countFood (\n    const Resources &food,\n    const float xloc, const float yloc) {\n\n    int nFood = 0;\n    std::vector<value> near_food;\n\n    // check any available\n    if (food.nAvailable > 0) {\n        // query for a simple box\n        food.rtree.query(bgi::satisfies([&](value const& v) {\n            return bg::distance(v.first, point(xloc, yloc)) < range_food;}),\n            std::back_inserter(near_food));\n\n        BOOST_FOREACH(value const& v, near_food) {\n            // count only which are available!\n            if (food.available[v.second]) {\n                nFood++;\n            }\n        }\n        near_food.clear();\n    }\n\n    return nFood;\n}\n\n// function for the nearest available food item\nstd::vector<int> Population::getFoodId (\n    const Resources &food,\n    const float xloc, const float yloc) {\n        \n    std::vector<int> food_id;\n    std::vector<value> near_food;\n    // check any available\n    if (food.nAvailable > 0) {\n        // query for a simple box\n        // food is accessed over the MOVEMENT RANGE\n        food.rtree.query(bgi::satisfies([&](value const& v) {\n            return bg::distance(v.first, point(xloc, yloc)) < range_move;}), \n            std::back_inserter(near_food));\n\n        BOOST_FOREACH(value const& v, near_food) {\n            // count only which are available!\n            if (food.available[v.second]) {\n                food_id.push_back(v.second);\n            }\n        }\n        near_food.clear();\n    }\n\n    // first element is number of near entities\n    // second is the identity of entities\n    return food_id;\n}\n\n/// rng for suitability\nstd::normal_distribution<float> noise(0.f, 0.01f);\nstd::cauchy_distribution<float> noise_cauchy(0.f, 0.001f);\n\n/// population movement function\nvoid Population::move(const Resources &food, const int nThreads) {\n\n    float twopi = 2.f * M_PI;\n    \n    // what increment for 3 samples in a circle around the agent\n    float increment = twopi / n_samples;\n    float angle = 0.f;\n    // for this increment what angles to sample at\n    std::vector<float> sample_angles (static_cast<int>(n_samples), 0.f);\n    for (int i_ = 0; i_ < static_cast<int>(n_samples); i_++)\n    {\n        sample_angles[i_] = angle;\n        angle += increment;\n    }\n\n    // make random noise for each individual and each sample\n    std::vector<std::vector<float> > noise_v (nAgents, std::vector<float>(static_cast<int>(n_samples), 0.f));\n    for (size_t i_ = 0; i_ < noise_v.size(); i_++)\n    {\n        for (size_t j_ = 0; j_ < static_cast<size_t>(n_samples); j_++)\n        {\n            noise_v[i_][j_] = noise(rng);\n        }\n    }    \n\n    shufflePop();\n    // loop over agents --- randomise\n    if (nThreads > 1) {\n        // any number above 1 will allow automatic n threads\n        tbb::task_scheduler_init _tbb(tbb::task_scheduler_init::automatic); // automatic for now\n        // try parallel\n        tbb::parallel_for(\n            tbb::blocked_range<unsigned>(1, order.size()),\n            [&](const tbb::blocked_range<unsigned>& r) {\n                for (unsigned i = r.begin(); i < r.end(); ++i) {\n                    int id = order[i];\n                    if (counter[id] > 0) {\n                        counter[id] --;\n                    }\n                    else {\n                        // first assess current location\n                        float sampleX = coordX[id];\n                        float sampleY = coordY[id]; \n\n                        float foodHere = 0.f;\n                        // count local food only if items are available\n                        if(food.nAvailable > 0) {\n                            foodHere = static_cast<float>(countFood(\n                                food, sampleX, sampleY\n                            ));\n                        }\n                        // count local handlers and non-handlers\n                        std::pair<int, int> agentCounts = countAgents(sampleX, sampleY);\n                        \n                        // get suitability current\n                        float suit_origin = (\n                            (sF[id] * foodHere) + (sH[id] * agentCounts.first) +\n                            (sN[id] * agentCounts.second)\n                        );\n\n                        float newX = sampleX;\n                        float newY = sampleY;\n                        // now sample at three locations around\n                        for(size_t j = 0; j < sample_angles.size(); j++) {\n                            float t1_ = static_cast<float>(cos(sample_angles[j]));\n                            float t2_ = static_cast<float>(sin(sample_angles[j]));\n                            \n                            // use range for agents to determine sample locs\n                            sampleX = coordX[id] + (range_agents * t1_);\n                            sampleY = coordY[id] + (range_agents * t2_);\n\n                            // crudely wrap sampling location\n                            if((sampleX > food.dSize) | (sampleX < 0.f)) {\n                                sampleX = std::fabs(std::fmod(sampleX, food.dSize));\n                            }\n                            if((sampleY > food.dSize) | (sampleY < 0.f)) {\n                                sampleY = std::fabs(std::fmod(sampleY, food.dSize));\n                            }\n\n                            // count food at sample locations if any available\n                            if(food.nAvailable > 0) {\n                                foodHere = static_cast<float>(countFood(\n                                    food, sampleX, sampleY\n                                ));\n                            }\n                            \n                            // count local handlers and non-handlers\n                            std::pair<int, int> agentCounts = countAgents(sampleX, sampleY);\n\n                            float suit_dest = (\n                                (sF[id] * foodHere) + (sH[id] * agentCounts.first) +\n                                (sN[id] * agentCounts.second) +\n                                noise_v[id][j] // add same very very small noise to all\n                            );\n\n                            if (suit_dest > suit_origin) {\n                                // where does the individual really go\n                                newX = coordX[id] + (range_move * t1_);\n                                newY = coordY[id] + (range_move * t2_);\n\n                                // crudely wrap MOVEMENT location\n                                if((newX > food.dSize) | (newX < 0.f)) {\n                                    newX = std::fabs(std::fmod(newX, food.dSize));\n                                }\n                                if((newY > food.dSize) | (newY < 0.f)) {\n                                    newY = std::fabs(std::fmod(newY, food.dSize));\n                                }\n\n                                assert(newX < food.dSize && newX > 0.f);\n                                assert(newY < food.dSize && newY > 0.f);\n                                suit_origin = suit_dest;\n                            }\n                        }\n                        // distance to be moved\n                        moved[id] += range_move;\n\n                        // set locations\n                        coordX[id] = newX; coordY[id] = newY;\n                    }\n                }\n            }\n        );\n    } else if (nThreads == 1) {\n        for (int i = 0; i < nAgents; ++i) {\n            int id = order[i];\n            if (counter[id] > 0) {\n                counter[id] --;\n            }\n            else {\n                // first assess current location\n                float sampleX = coordX[id];\n                float sampleY = coordY[id]; \n\n                float foodHere = 0.f;\n                // count local food only if items are available\n                if(food.nAvailable > 0) {\n                    foodHere = static_cast<float>(countFood(\n                        food, sampleX, sampleY\n                    ));\n                }\n                // count local handlers and non-handlers\n                std::pair<int, int> agentCounts = countAgents(sampleX, sampleY);\n                \n                // get suitability current\n                float suit_origin = (\n                    (sF[id] * foodHere) + (sH[id] * agentCounts.first) +\n                    (sN[id] * agentCounts.second)\n                );\n\n                float newX = sampleX;\n                float newY = sampleY;\n                // now sample at three locations around\n                for(size_t j = 0; j < sample_angles.size(); j++) {\n                    float t1_ = static_cast<float>(cos(sample_angles[j]));\n                    float t2_ = static_cast<float>(sin(sample_angles[j]));\n                    \n                    // use range for agents to determine sample locs\n                    sampleX = coordX[id] + (range_agents * t1_);\n                    sampleY = coordY[id] + (range_agents * t2_);\n\n                    // crudely wrap sampling location\n                    if((sampleX > food.dSize) | (sampleX < 0.f)) {\n                        sampleX = std::fabs(std::fmod(sampleX, food.dSize));\n                    }\n                    if((sampleY > food.dSize) | (sampleY < 0.f)) {\n                        sampleY = std::fabs(std::fmod(sampleY, food.dSize));\n                    }\n\n                    // count food at sample locations if any available\n                    if(food.nAvailable > 0) {\n                        foodHere = static_cast<float>(countFood(\n                            food, sampleX, sampleY\n                        ));\n                    }\n                    \n                    // count local handlers and non-handlers\n                    std::pair<int, int> agentCounts = countAgents(sampleX, sampleY);\n\n                    float suit_dest = (\n                        (sF[id] * foodHere) + (sH[id] * agentCounts.first) +\n                        (sN[id] * agentCounts.second) +\n                        noise_v[id][j] // add same very very small noise to all\n                    );\n\n                    if (suit_dest > suit_origin) {\n                        // where does the individual really go\n                        newX = coordX[id] + (range_move * t1_);\n                        newY = coordY[id] + (range_move * t2_);\n\n                        // crudely wrap MOVEMENT location\n                        if((newX > food.dSize) | (newX < 0.f)) {\n                            newX = std::fabs(std::fmod(newX, food.dSize));\n                        }\n                        if((newY > food.dSize) | (newY < 0.f)) {\n                            newY = std::fabs(std::fmod(newY, food.dSize));\n                        }\n\n                        assert(newX < food.dSize && newX > 0.f);\n                        assert(newY < food.dSize && newY > 0.f);\n                        suit_origin = suit_dest;\n                    }\n                }\n                // distance to be moved\n                moved[id] += range_move;\n\n                // set locations\n                coordX[id] = newX; coordY[id] = newY;\n            }\n        }\n\n    }\n    \n}\n\n// function to paralellise choice of forage item\nvoid Population::pickForageItem(const Resources &food, const int nThreads){\n    shufflePop();\n    // nearest food\n    std::vector<int> idTargetFood (nAgents, -1);\n\n    if (nThreads > 1)\n    {\n        // loop over agents --- no shuffling required here\n        tbb::task_scheduler_init _tbb(tbb::task_scheduler_init::automatic); // automatic for now\n        // try parallel foraging --- agents pick a target item\n        tbb::parallel_for(\n            tbb::blocked_range<unsigned>(1, order.size()),\n                [&](const tbb::blocked_range<unsigned>& r) {\n                for (unsigned i = r.begin(); i < r.end(); ++i) {\n                    if ((counter[i] > 0) | (food.nAvailable == 0)) { \n                        // nothing -- agent cannot forage or there is no food\n                    }\n                    else {\n                        // find nearest item ids\n                        std::vector<int> theseItems = getFoodId(food, coordX[i], coordY[i]);\n                        int thisItem = -1;\n\n                        // check near items count\n                        if(theseItems.size() > 0) {\n                            // take first item by default\n                            thisItem = theseItems[0];\n                            idTargetFood[i] = thisItem;\n                        }\n                    }\n                }\n            }\n        );\n    } else if (nThreads == 1)\n    {\n        for (int i = 0; i < nAgents; ++i) {\n            if ((counter[i] > 0) | (food.nAvailable == 0)) { \n                // nothing -- agent cannot forage or there is no food\n            }\n            else {\n                // find nearest item ids\n                std::vector<int> theseItems = getFoodId(food, coordX[i], coordY[i]);\n                int thisItem = -1;\n\n                // check near items count\n                if(theseItems.size() > 0) {\n                    // take first item by default\n                    thisItem = theseItems[0];\n                    idTargetFood[i] = thisItem;\n                }\n            }\n        }\n    }\n\n    forageItem = idTargetFood;\n}\n\n// function to exploitatively forage on picked forage items\nvoid Population::doForage(Resources &food) {\n    // all agents have picked a food item if they can forage\n    // now forage in a serial loop --- this cannot be parallelised\n    // this order is randomised\n    for (size_t i = 0; i < static_cast<size_t>(nAgents); i++)\n    {\n        int id = order[i];\n        if ((counter[id] > 0) | (food.nAvailable == 0)) {\n            // nothing\n        } else {\n            int thisItem = forageItem[id]; //the item picked by this agent\n            // check selected item is available\n            if (thisItem != -1)\n            {\n                counter[id] = handling_time;\n                intake[id] += 1.0; // increased here --- not as described.\n\n                // reset food availability\n                food.available[thisItem] = false;\n                food.counter[thisItem] = food.regen_time;\n                food.nAvailable --;\n            }\n        }\n    }\n}\n\nvoid Population::countAssoc(const int nThreads) {\n    for (int i = 0; i < nAgents; ++i) {\n        // count nearby agents and update raw associations\n        std::vector<int> nearby_agents = getNeighbourId(coordX[i], coordY[i]);\n        associations[i] += nearby_agents.size();\n\n        // loop over nearby agents and update association matrix\n        for (size_t j = 0; j < nearby_agents.size(); j++)\n        {\n            int target_agent = nearby_agents[j];\n            pbsn.adjMat (i, target_agent) += 1;\n        }\n    }\n}\n\n/// minor function to normalise vector\nstd::vector<float> Population::handleFitness() {\n    // sort vec fitness\n    std::vector<float> vecFitness = energy;\n    std::sort(vecFitness.begin(), vecFitness.end()); // sort to to get min-max\n    // scale to max fitness\n    float maxFitness = vecFitness[vecFitness.size()-1];\n    float minFitness = vecFitness[0];\n\n    // reset to energy\n    vecFitness = energy;\n    // rescale copied energy vector by min anx max fitness\n    for(size_t i = 0; i < static_cast<size_t>(nAgents); i++) {\n        vecFitness[i] = ((vecFitness[i]  - minFitness) / (maxFitness - minFitness)) +\n         noise(rng);\n    }\n    \n    return vecFitness;\n}\n\n// fun for replication\nvoid Population::Reproduce(const Resources food, const bool infect_percent, \n    const float dispersal, const float mProb, const float mSize) \n{\n    // std::bernoulli_distribution verticalInfect(0.01f);\n\n    // mutation probability and size distribution --- inefficient but oh well\n    std::bernoulli_distribution mutation_happens(mProb);\n    std::cauchy_distribution<float> mutation_size(0.0, mSize);\n\n    // choose the range over which individuals are dispersed\n    std::normal_distribution<float> sprout(0.f, dispersal);\n    std::vector<float> vecFitness;\n    //normalise intake if percent infect is not true\n    if (infect_percent) {\n         vecFitness = energy;\n    } else {\n        vecFitness = handleFitness();\n    }\n\n    // set up weighted lottery\n    std::discrete_distribution<> weightedLottery(vecFitness.begin(), vecFitness.end());\n\n    // get parent trait based on weighted lottery\n    std::vector<float> tmp_sF (nAgents, 0.f);\n    std::vector<float> tmp_sH (nAgents, 0.f);\n    std::vector<float> tmp_sN (nAgents, 0.f);\n    \n    // infected or not for vertical transmission\n    std::vector<bool> infected_2 (nAgents, false);\n\n    // reset infection source\n    srcInfect = std::vector<int> (nAgents, 0);\n\n    // reset associations\n    associations = std::vector<int> (nAgents, 0);\n\n    // reset distance moved\n    moved = std::vector<float> (nAgents, 0.f);\n\n    // reset adjacency matrix\n    pbsn.adjMat = Rcpp::NumericMatrix(nAgents, nAgents);\n\n    // positions\n    std::vector<float> coord_x_2 (nAgents, 0.f);\n    std::vector<float> coord_y_2 (nAgents, 0.f);\n    \n    for (int a = 0; a < nAgents; a++) {\n        size_t parent_id = static_cast<size_t>(weightedLottery(rng));\n\n        tmp_sF[a] = sF[parent_id];\n        tmp_sH[a] = sH[parent_id];\n        tmp_sN[a] = sN[parent_id];\n\n        // inherit positions from parent\n        coord_x_2[a] = coordX[parent_id] + sprout(rng);\n        coord_y_2[a] = coordY[parent_id] + sprout(rng);\n\n        // robustly wrap positions\n        if(coord_x_2[a] < 0.f) coord_x_2[a] = food.dSize + coord_x_2[a];\n        if(coord_x_2[a] > food.dSize) coord_x_2[a] = coord_x_2[a] - food.dSize;\n\n        if(coord_y_2[a] < 0.f) coord_y_2[a] = food.dSize + coord_y_2[a];\n        if(coord_y_2[a] > food.dSize) coord_y_2[a] = coord_y_2[a] - food.dSize;\n\n        // // vertical transmission of infection.\n        // if(infected[parent_id]) {\n        //     if(verticalInfect(rng)) {\n        //         infected_2[a] = true;\n        //         srcInfect[a] = 1;\n        //     }\n        // }\n    }\n\n    // swap infected and infected_2\n    std::swap(infected, infected_2);\n    infected_2.clear();\n\n    // swap coords --- this initialises individuals near their parent's position\n    std::swap(coordX, coord_x_2);\n    std::swap(coordY, coord_y_2);\n    coord_x_2.clear(); coord_y_2.clear();\n\n    // update initial positions!\n    initX = coordX;\n    initY = coordY;\n\n    // reset counter and time infected\n    counter = std::vector<int> (nAgents, 0);\n    timeInfected = std::vector<int> (nAgents, 0);\n    assert(static_cast<int>(counter.size()) == nAgents && \"counter size wrong\");\n\n    // mutate trait: trait shifts up or down with an equal prob\n    // trait mutation prob is mProb, in a two step process\n    for (int a = 0; a < nAgents; a++) {\n        if(mutation_happens(rng)) {\n            tmp_sF[a] = tmp_sF[a] + mutation_size(rng);\n        }\n        if(mutation_happens(rng)) {\n            tmp_sH[a] = tmp_sH[a] + mutation_size(rng);\n        }\n        if(mutation_happens(rng)) {\n            tmp_sN[a] = tmp_sN[a] + mutation_size(rng);\n        }\n    }\n    \n    // reset nInfected and count natal infections\n    // from vertical transmission\n    countInfected();\n\n    // swap trait matrices\n    std::swap(sF, tmp_sF);\n    std::swap(sH, tmp_sH);\n    std::swap(sN, tmp_sN);\n\n    tmp_sF.clear(); tmp_sH.clear(); tmp_sN.clear();\n    \n    // swap energy\n    std::vector<float> tmpEnergy (nAgents, 0.001);\n    std::swap(energy, tmpEnergy);\n    tmpEnergy.clear();\n\n    // swap intake\n    std::vector<float> tmpIntake (nAgents, 0.001);\n    std::swap(intake, tmpIntake);\n    tmpIntake.clear();\n}\n", "meta": {"hexsha": "bda7f68c916fc68535d6bbe76e589811ba50a773", "size": 23018, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/agents.cpp", "max_stars_repo_name": "pratikunterwegs/pathomove", "max_stars_repo_head_hexsha": "be6b509442d975909bae2a46cc01d94e74e32a41", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-03-16T11:20:02.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-16T11:20:02.000Z", "max_issues_repo_path": "src/agents.cpp", "max_issues_repo_name": "pratikunterwegs/pathomove", "max_issues_repo_head_hexsha": "be6b509442d975909bae2a46cc01d94e74e32a41", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2022-01-18T12:08:44.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-18T12:08:44.000Z", "max_forks_repo_path": "src/agents.cpp", "max_forks_repo_name": "pratikunterwegs/pathomove", "max_forks_repo_head_hexsha": "be6b509442d975909bae2a46cc01d94e74e32a41", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-01-18T20:29:28.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-18T20:29:28.000Z", "avg_line_length": 35.8535825545, "max_line_length": 109, "alphanum_fraction": 0.5125119472, "num_tokens": 5406, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6893056167854461, "lm_q2_score": 0.4571367168274948, "lm_q1q2_score": 0.3151069065480501}}
{"text": "#ifndef PARMCB_SVA_SIGNED_TBB_HPP_\n#define PARMCB_SVA_SIGNED_TBB_HPP_\n\n//    Copyright (C) Dimitrios Michail 2019 - 2021.\n// Distributed under the Boost Software License, Version 1.0.\n//    (See accompanying file LICENSE_1_0.txt or copy at\n//          https://www.boost.org/LICENSE_1_0.txt)\n\n#include <cstddef>\n#include <functional>\n#include <iostream>\n#include <iterator>\n#include <limits>\n#include <set>\n#include <vector>\n\n#include <boost/graph/graph_traits.hpp>\n#include <boost/property_map/property_map.hpp>\n#include <boost/tuple/detail/tuple_basic.hpp>\n#include <boost/timer/timer.hpp>\n#include <tbb/parallel_for.h>\n#include <tbb/parallel_reduce.h>\n#include <tbb/concurrent_vector.h>\n#include <tbb/task_group.h>\n\n#include <parmcb/detail/signed_dijkstra.hpp>\n#include <parmcb/forestindex.hpp>\n#include <parmcb/spvecgf2.hpp>\n#include <parmcb/util.hpp>\n\nnamespace parmcb {\n\n    namespace detail {\n\n        template<class Graph, class WeightMap>\n        struct OddCycleFinder {\n            typedef typename boost::graph_traits<Graph>::vertex_descriptor Vertex;\n            typedef typename boost::graph_traits<Graph>::edge_descriptor Edge;\n            typedef typename boost::property_traits<WeightMap>::value_type WeightType;\n\n            OddCycleFinder(const Graph &g, const WeightMap &weight_map, const ForestIndex<Graph> &forest_index,\n                    const std::vector<Vertex> &vertices) :\n                    g(g), weight_map(weight_map), forest_index(forest_index), vertices(vertices), compare(\n                            std::less<WeightType>()) {\n            }\n\n            std::tuple<std::set<Edge>, WeightType, bool> find(const SpVecGF2<std::size_t> &support) {\n                std::set<Edge> signed_edges;\n                convert_edges(support, std::inserter(signed_edges, signed_edges.end()), forest_index);\n                if (signed_edges.size() == 1) {\n                    return find_single_edge(*signed_edges.begin());\n                } else if (signed_edges.size() >= boost::num_vertices(g)) {\n                    return find_all_vertices(signed_edges);\n                } else {\n                    return find_less_than_vertices(signed_edges);\n                }\n            }\n\n            std::tuple<std::set<Edge>, WeightType, bool> find_single_edge(const Edge &se) {\n                std::tuple<std::set<Edge>, WeightType, bool> best;\n\n                auto se_v = boost::source(se, g);\n                auto se_u = boost::target(se, g);\n                auto res = bidirectional_signed_dijkstra(g, weight_map, std::set<Edge> { }, std::set<Edge> { se }, true,\n                        se_v, true, se_u, true, std::get<2>(best), std::get<1>(best));\n                if (std::get<2>(res) && std::get<0>(res).find(se) == std::get<0>(res).end()) {\n                    std::get<1>(res) += boost::get(weight_map, se);\n                    if (!std::get<2>(best) || compare(std::get<1>(res), std::get<1>(best))) {\n                        std::get<0>(res).insert(se);\n                        best = res;\n                    }\n                }\n                return best;\n            }\n\n            std::tuple<std::set<Edge>, WeightType, bool> find_all_vertices(const std::set<Edge> &signed_edges) {\n                typedef std::tuple<std::set<Edge>, WeightType, bool> cycle_t;\n                auto cycle_min = [&](const cycle_t &c1, const cycle_t &c2) {\n                    if (!std::get<2>(c1) || !std::get<2>(c2)) {\n                        if (std::get<2>(c1)) {\n                            return c1;\n                        } else {\n                            return c2;\n                        }\n                    }\n                    // both valid, compare\n                    if (!compare(std::get<1>(c2), std::get<1>(c1))) {\n                        return c1;\n                    }\n                    return c2;\n                };\n\n                return tbb::parallel_reduce(tbb::blocked_range<std::size_t>(0, boost::num_vertices(g)),\n                        std::make_tuple(std::set<Edge>(), (std::numeric_limits<WeightType>::max)(), false),\n                        [&](tbb::blocked_range<std::size_t> r, auto running_min) {\n                            for (std::size_t i = r.begin(); i < r.end(); i++) {\n                                auto v = vertices[i];\n                                const bool use_hidden_edges = false;\n                                auto res = bidirectional_signed_dijkstra(g, weight_map, signed_edges,\n                                        std::set<Edge> { }, use_hidden_edges, v, true, v, false,\n                                        std::get<2>(running_min), std::get<1>(running_min));\n                                if (std::get<2>(res)\n                                        && (!std::get<2>(running_min)\n                                                || compare(std::get<1>(res), std::get<1>(running_min)))) {\n                                    running_min = res;\n                                }\n                            }\n                            return running_min;\n                        },\n                        cycle_min);\n\n            }\n\n            std::tuple<std::set<Edge>, WeightType, bool> find_less_than_vertices(const std::set<Edge> &signed_edges) {\n                /*\n                 * Heuristic in case number of signed edges is small compared to the number of vertices.\n                 */\n                typedef std::tuple<std::set<Edge>, WeightType, bool> cycle_t;\n                auto cycle_min = [&](const cycle_t &c1, const cycle_t &c2) {\n                    if (!std::get<2>(c1) || !std::get<2>(c2)) {\n                        if (std::get<2>(c1)) {\n                            return c1;\n                        } else {\n                            return c2;\n                        }\n                    }\n                    // both valid, compare\n                    if (!compare(std::get<1>(c2), std::get<1>(c1))) {\n                        return c1;\n                    }\n                    return c2;\n                };\n\n                std::map<Edge, std::set<Edge>> hidden_edges_per_edge;\n                std::vector<Edge> signed_edges_as_vector;\n                std::set<Edge> tmp_signed_edges = signed_edges;\n                while (!tmp_signed_edges.empty()) {\n                    auto bit = tmp_signed_edges.begin();\n                    hidden_edges_per_edge.insert(std::make_pair(*bit, tmp_signed_edges));\n                    signed_edges_as_vector.push_back(*bit);\n                    tmp_signed_edges.erase(bit);\n                }\n                return tbb::parallel_reduce(tbb::blocked_range<std::size_t>(0, signed_edges_as_vector.size()),\n                        std::make_tuple(std::set<Edge>(), (std::numeric_limits<WeightType>::max)(), false),\n                        [&](tbb::blocked_range<std::size_t> r, auto running_min) {\n                            for (std::size_t i = r.begin(); i < r.end(); i++) {\n                                auto se = signed_edges_as_vector.at(i);\n                                auto se_v = boost::source(se, g);\n                                auto se_u = boost::target(se, g);\n                                auto hidden_edges = hidden_edges_per_edge.at(se);\n                                auto res = bidirectional_signed_dijkstra(g, weight_map, signed_edges, hidden_edges,\n                                        true, se_v, true, se_u, true, std::get<2>(running_min),\n                                        std::get<1>(running_min));\n                                if (std::get<2>(res) && std::get<0>(res).find(se) == std::get<0>(res).end()) {\n                                    std::get<1>(res) += boost::get(weight_map, se);\n                                    if (!std::get<2>(running_min)\n                                            || compare(std::get<1>(res), std::get<1>(running_min))) {\n                                        std::get<0>(res).insert(se);\n                                        running_min = res;\n                                    }\n                                }\n                            }\n                            return running_min;\n                        },\n                        cycle_min);\n            }\n\n            const Graph &g;\n            const WeightMap &weight_map;\n            const ForestIndex<Graph> &forest_index;\n            const std::vector<Vertex> &vertices;\n            const std::less<WeightType> compare;\n        };\n\n    }\n\n    template<class Graph, class WeightMap, class CycleOutputIterator>\n    typename boost::property_traits<WeightMap>::value_type mcb_sva_signed_tbb(const Graph &g, WeightMap weight_map,\n            CycleOutputIterator out, const std::size_t hardware_concurrency_hint = 0) {\n\n        typedef typename boost::graph_traits<Graph>::vertex_descriptor Vertex;\n        typedef typename boost::graph_traits<Graph>::vertex_iterator VertexIt;\n        typedef typename boost::graph_traits<Graph>::edge_descriptor Edge;\n        typedef typename boost::property_traits<WeightMap>::value_type WeightType;\n\n        /*\n         * Index the graph\n         */\n        ForestIndex<Graph> forest_index(g);\n        auto csd = forest_index.cycle_space_dimension();\n        std::cout << \"Cycle dimension \" << csd << std::endl;\n        std::vector<Vertex> vertices;\n        {\n            VertexIt vi, viend;\n            for (boost::tie(vi, viend) = boost::vertices(g); vi != viend; ++vi) {\n                vertices.push_back(*vi);\n            }\n        }\n\n        /*\n         * Initialize support vectors\n         */\n        tbb::concurrent_vector<SpVecGF2<std::size_t>> support;\n        tbb::parallel_for(tbb::blocked_range<std::size_t>(0, csd), [&](const tbb::blocked_range<std::size_t> &r) {\n            for (std::size_t i = r.begin(); i != r.end(); ++i) {\n                support.push_back(SpVecGF2<std::size_t> { i });\n            }\n        });\n\n        boost::timer::cpu_timer cycle_timer;\n        cycle_timer.stop();\n        boost::timer::cpu_timer support_timer;\n        support_timer.stop();\n\n        /*\n         * Main loop\n         */\n        WeightType mcb_weight = WeightType();\n        parmcb::detail::OddCycleFinder<Graph, WeightMap> odd_cycle_finder(g, weight_map, forest_index, vertices);\n        for (std::size_t k = 0; k < csd; k++) {\n            if (k % 250 == 0) {\n                std::cout << \"iteration = \" << k << std::endl;\n            }\n\n            /*\n             * Choose the sparsest support heuristic\n             */\n            auto min_support = k;\n            for (auto r = k + 1; r < csd; ++r) {\n                if (support[r].size() < support[min_support].size())\n                    min_support = r;\n            }\n            if (min_support != k) {  // swap\n                std::swap(support[k], support[min_support]);\n            }\n\n            /*\n             * Compute shortest odd cycle\n             */\n            cycle_timer.resume();\n            auto cycle = odd_cycle_finder.find(support[k]);\n            cycle_timer.stop();\n\n            /*\n             * Update support vectors\n             */\n            support_timer.resume();\n            std::set<std::size_t> cyclek;\n            convert_edges(std::get<0>(cycle), std::inserter(cyclek, cyclek.end()), forest_index);\n            tbb::parallel_for(tbb::blocked_range<std::size_t>(k + 1, csd),\n                    [&](const tbb::blocked_range<std::size_t> &r) {\n                        auto e = r.end();\n                        for (std::size_t i = r.begin(); i != e; ++i) {\n                            if (support[i] * cyclek == 1) {\n                                support[i] += support[k];\n                            }\n                        }\n                    });\n            support_timer.stop();\n\n            /*\n             * Report cycle\n             */\n            std::list<Edge> cyclek_edgelist;\n            std::copy(std::get<0>(cycle).begin(), std::get<0>(cycle).end(), std::back_inserter(cyclek_edgelist));\n            *out++ = cyclek_edgelist;\n            mcb_weight += std::get<1>(cycle);\n        }\n\n        std::cout << \"cycle   timer\" << cycle_timer.format();\n        std::cout << \"support timer\" << support_timer.format();\n\n        return mcb_weight;\n    }\n\n} // namespace parmcb\n\n#endif\n", "meta": {"hexsha": "55d239bbf4f87c95a7e27097610130589a72ae58", "size": 12243, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/parmcb/parmcb_sva_signed_tbb.hpp", "max_stars_repo_name": "d-michail/parmcb", "max_stars_repo_head_hexsha": "19d0b7eb01735600c851b969d9e5a87c78b8c711", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/parmcb/parmcb_sva_signed_tbb.hpp", "max_issues_repo_name": "d-michail/parmcb", "max_issues_repo_head_hexsha": "19d0b7eb01735600c851b969d9e5a87c78b8c711", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/parmcb/parmcb_sva_signed_tbb.hpp", "max_forks_repo_name": "d-michail/parmcb", "max_forks_repo_head_hexsha": "19d0b7eb01735600c851b969d9e5a87c78b8c711", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 43.8817204301, "max_line_length": 120, "alphanum_fraction": 0.4818263498, "num_tokens": 2620, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.689305616785446, "lm_q2_score": 0.4571367168274948, "lm_q1q2_score": 0.31510690654805007}}
{"text": "﻿//MIT License\n//\n//Copyright(c) 2020 Zheng Jiaqi @NUSComputing\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 <CGAL/Surface_mesh_parameterization/Discrete_conformal_map_parameterizer_3.h>\n#include <CGAL/Surface_mesh_parameterization/Discrete_authalic_parameterizer_3.h>\n#include <CGAL/Surface_mesh_parameterization/Square_border_parameterizer_3.h>\n#include <CGAL/Surface_mesh_parameterization/Two_vertices_parameterizer_3.h>\n#include <CGAL/Surface_mesh_parameterization/internal/Containers_filler.h>\n#include <CGAL/Surface_mesh_parameterization/ARAP_parameterizer_3.h>\n#include <CGAL/Surface_mesh_parameterization/LSCM_parameterizer_3.h>\n#include <CGAL/Exact_predicates_inexact_constructions_kernel.h>\n#include <CGAL/Polygon_mesh_processing/connected_components.h>\n#include <CGAL/Surface_mesh_parameterization/parameterize.h>\n#include <CGAL/Surface_mesh_parameterization/IO/File_off.h>\n#include <CGAL/Polygon_mesh_processing/detect_features.h>\n#include <CGAL/Polygon_mesh_processing/smooth_mesh.h>\n#include <CGAL/AABB_face_graph_triangle_primitive.h>\n#include <CGAL/Polygon_mesh_processing/measure.h>\n#include <CGAL/Polygon_mesh_processing/locate.h>\n#include <CGAL/Polygon_mesh_processing/remesh.h>\n#include <boost/property_map/property_map.hpp>\n#include <boost/function_output_iterator.hpp>\n#include <CGAL/boost/graph/Seam_mesh.h>\n#include <CGAL/boost/graph/iterator.h>\n#include <CGAL/disable_warnings.h>\n#include <CGAL/Simple_cartesian.h>\n#include <boost/unordered_map.hpp>\n#include <boost/unordered_set.hpp>\n#include <CGAL/Unique_hash_map.h>\n#include <CGAL/Polyhedron_3.h>\n#include <CGAL/Surface_mesh.h>\n#include <CGAL/AABB_traits.h>\n#include <CGAL/circulator.h>\n#include <CGAL/AABB_tree.h>\n#include <iostream>\n#include <fstream>\n#include <cstddef>\n#include <vector>\n\n#include \"gDel2D/gDel2D/GpuDelaunay.h\"\n#include \"gDel2D/gDel2D/PerfTimer.h\"\n#include \"gDel2D/gDel2D/CPU/PredWrapper.h\"\n#include \"gDel2D/DelaunayChecker.h\"\n#include \"delaunay.h\"\n\n#if defined(_WIN32)\n#include <Windows.h>\n#endif\n\n//#define OUTPUT_PARAMETERIZATION\n//#define VISUALIZE_TRIANGULATION\n#ifdef VISUALIZE_TRIANGULATION\n#include \"gDel2D/Visualizer.h\"\n#endif\n\ntypedef CGAL::Simple_cartesian<double>\tKernel;\n\n#include \"split.h\"\n#include \"weighting.h\"\n#include \"triangulation.h\"\n#include \"discretization.h\"\n#include \"constrains.h\"\n#include \"gcvt.h\"\n#include \"recover.h\"\n\ntypedef Kernel::Point_2\t\t\t\t\tPoint_2;\ntypedef Kernel::Point_3\t\t\t\t\tPoint_3;\ntypedef CGAL::Surface_mesh<Point_3>\t\tSurfMesh;\ntypedef CGAL::Surface_mesh<Point_2>\t\tMesh2D;\n\ntypedef boost::graph_traits<SurfMesh>::edge_descriptor\t\t\tSM_edge_descriptor;\ntypedef boost::graph_traits<SurfMesh>::halfedge_descriptor\t\tSM_halfedge_descriptor;\ntypedef boost::graph_traits<SurfMesh>::vertex_descriptor\t\tSM_vertex_descriptor;\n\ntypedef boost::graph_traits<Mesh2D>::edge_descriptor\t\t\tedge_2d;\ntypedef boost::graph_traits<Mesh2D>::halfedge_descriptor\t\thalfedge_2d;\ntypedef boost::graph_traits<Mesh2D>::vertex_descriptor\t\t\tvertex_2d;\n\ntypedef CGAL::Unique_hash_map<SM_halfedge_descriptor, Point_2>\tUV_uhm;\ntypedef CGAL::Unique_hash_map<SM_edge_descriptor, bool>\t\t\tSeam_edge_uhm;\ntypedef CGAL::Unique_hash_map<SM_vertex_descriptor, bool>\t\tSeam_vertex_uhm;\n\ntypedef boost::associative_property_map<UV_uhm>\t\t\t\t\tUV_pmap;\ntypedef boost::associative_property_map<Seam_edge_uhm>\t\t\tSeam_edge_pmap;\ntypedef boost::associative_property_map<Seam_vertex_uhm>\t\tSeam_vertex_pmap;\n\ntypedef CGAL::Seam_mesh<SurfMesh, Seam_edge_pmap, Seam_vertex_pmap>\tSeamMesh;\n\ntypedef boost::graph_traits<SeamMesh>::vertex_descriptor\t\tvertex_descriptor;\ntypedef boost::graph_traits<SeamMesh>::edge_descriptor\t\t\tedge_descriptor;\ntypedef boost::graph_traits<SeamMesh>::halfedge_descriptor\t\thalfedge_descriptor;\ntypedef boost::graph_traits<SeamMesh>::face_descriptor\t\t\tface_descriptor;\n\ntypedef boost::unordered_map<vertex_descriptor, vertex_2d>\t\t_3d_to_2d_uhm;\ntypedef boost::unordered_map<vertex_2d, vertex_descriptor>\t\t_2d_to_3d_uhm;\ntypedef boost::unordered_map<vertex_2d, double>\t\t\t\t\tweight_uhm;\n\ntypedef boost::associative_property_map<_3d_to_2d_uhm>\t\t\t_3d_to_2d_pmap;\ntypedef boost::associative_property_map<_2d_to_3d_uhm>\t\t\t_2d_to_3d_pmap;\ntypedef boost::associative_property_map<weight_uhm>\t\t\t\tweight_pmap;\n\nnamespace PMP = CGAL::Polygon_mesh_processing;\nnamespace SMP = CGAL::Surface_mesh_parameterization;\n\ntypedef PMP::Face_location<SurfMesh, Kernel::FT>\t\t\t\tFace_Location;\n\nint imageSize\t= 2048;\nint depth\t\t= 1;\nint maxIter\t\t= 1000;\nint vertices    = 20000;\ndouble scale, leftbound, lowerbound;\nfloat *densityMap;\nshort *Voronoi;\nbool *constrainMask;\n\nGDel2DInput\t\tDelInput;\nGDel2DOutput\tDelOutput;\n\nint main(int argc, char** argv)\n{\n\t// input surface mesh\n\tconst char* filename = argc > 1 ? argv[1] : \"data/horse.off\";\n\tstd::ifstream input(filename);\n\tSurfMesh surface;\n\tif (!input || !(input >> surface) || surface.is_empty()) {\n\t\tstd::cerr << \"Not a valid .off file.\" << std::endl;\n\t\treturn EXIT_FAILURE;\n\t}\n\tinput.close();\n\n\tdouble edge_length_limit = 0.72;\n\t\n\t// split long edges\n\tstd::vector<SM_edge_descriptor> constrain_vec;\n\tdetectConstrains(surface, constrain_vec);\n\tPMP::split_long_edges(constrain_vec, edge_length_limit, surface);\n\n\t// create seam mesh\n\tconst char* seamfile = \"data/horse.selection.txt\";\n\tSeam_edge_uhm seam_edge_uhm(false);\n\tSeam_edge_pmap seam_edges(seam_edge_uhm);\n\tSeam_vertex_uhm seam_vertex_uhm(false);\n\tSeam_vertex_pmap seam_vertices(seam_vertex_uhm);\n\tstd::vector<SM_edge_descriptor> seam_vec;\n\taddSeams(surface, seam_edges, seam_vec, seamfile);\n\tPMP::split_long_edges(seam_vec, edge_length_limit, surface, PMP::parameters::edge_is_constrained_map(seam_edges));\n\tgetSeamVertices(surface, seam_edges, seam_vertices);\n\n\tSeamMesh seam_mesh(surface, seam_edges, seam_vertices);\n\n\t// the property map stores the 2D points in the uv parameter space\n\tUV_uhm uv_uhm;\n\tUV_pmap uv_coord(uv_uhm);\n\n\t// a halfedge on the border\n\thalfedge_descriptor border_halfedge = PMP::longest_border(seam_mesh).first;\n\n\t// planar parameterization\n\t//typedef SMP::Square_border_uniform_parameterizer_3<SeamMesh> Border_parameterizer;\n\ttypedef SMP::ARAP_parameterizer_3<SeamMesh> Parameterizer;\n\tSMP::parameterize(seam_mesh, Parameterizer(), border_halfedge, uv_coord);\n\tprintf(\"Parameterization done. %f s\\n\", clock()*1.0 / CLOCKS_PER_SEC);\n#ifdef OUTPUT_PARAMETERIZATION\n\tstd::ofstream out(\"parameterization.off\");\n\tSMP::IO::output_uvmap_to_off(seam_mesh, border_halfedge, uv_coord, out);\n#endif\n\n\t// create 2d triangulation\n\tMesh2D mesh_2d;\n\t_3d_to_2d_uhm _32_uhm;\n\t_3d_to_2d_pmap vertex_3d_to_2d(_32_uhm);\n\t_2d_to_3d_uhm _23_uhm;\n\t_2d_to_3d_pmap vertex_2d_to_3d(_23_uhm);\n\tbuild_2d_triangulation(seam_mesh, border_halfedge, uv_coord, mesh_2d, vertex_3d_to_2d, vertex_2d_to_3d);\n\tprintf(\"Triangulation done. %f s\\n\", clock()*1.0 / CLOCKS_PER_SEC);\n\n\t// weighting vertices\n\tweight_uhm wgt_uhm;\n\tweight_pmap vertex_weight(wgt_uhm);\n\tweighting_vertices_with_area(seam_mesh, mesh_2d, vertex_3d_to_2d, vertex_weight);\n\tprintf(\"Weighting done. %f s\\n\", clock()*1.0 / CLOCKS_PER_SEC);\n\t\n\t// discretization\n\tdensityMap = (float *)malloc(imageSize * imageSize * sizeof(float));\n\tdiscretization(mesh_2d, vertex_weight, densityMap, imageSize, scale, leftbound, lowerbound);\n\tprintf(\"Discretization done. %f s\\n\", clock()*1.0 / CLOCKS_PER_SEC);\n\n\t// detect constrains\n\tstd::vector<std::pair<vertex_2d, vertex_2d> > constrain_edge;\n\tstd::unordered_set<vertex_2d> constrain_point;\n\tdetect_constrains(seam_mesh, vertex_3d_to_2d, constrain_edge, constrain_point);\n\tprintf(\"Detect constrains done. %f s\\n\", clock()*1.0 / CLOCKS_PER_SEC);\n\n\t// construct centroidal Voronoi diagram\n\tVoronoi = (short *)malloc(sizeof(short) * imageSize * imageSize * 2);\n\tconstrainMask = (bool *)malloc(sizeof(bool) * imageSize * imageSize);\n\tgenerateMask(mesh_2d, constrain_point, constrainMask, imageSize, scale, leftbound, lowerbound);\n\tcentroidalVoronoi(Voronoi, densityMap, constrainMask, vertices, imageSize, depth, maxIter);\n\tprintf(\"Centroidal Voronoi tessellation done. %f s\\n\", clock()*1.0 / CLOCKS_PER_SEC);\n\n\t// construct constraint Delaunay triangulation\n#ifdef VISUALIZE_TRIANGULATION\n\tVisualizer *vis = Visualizer::instance();\n\tif (vis->isEnable()) {\n\t\tvis->init(argc, argv, \"gDel2D\");\n\t\tvis->printHelp();\n\t}\n\tVisualizer::instance()->pause();\n#endif\n\tGpuDel gpuDel;\n\tPoint2HVec().swap(DelInput.pointVec);\n\tSegmentHVec().swap(DelInput.constraintVec);\n\tTriHVec().swap(DelOutput.triVec);\n\tTriOppHVec().swap(DelOutput.triOppVec);\n\tdelaunayInput(mesh_2d, Voronoi, constrainMask, constrain_point, constrain_edge, DelInput.pointVec, DelInput.constraintVec, imageSize, scale, leftbound, lowerbound);\n\t//printf(\"%d points, %d segments\", DelInput.pointVec.size(), DelInput.constraintVec.size());\n\tgpuDel.compute(DelInput, &DelOutput);\n\tprintf(\"Constraint Delaunay triangulation done. %f s\\n\", clock()*1.0 / CLOCKS_PER_SEC);\n\n\t// Parameter space -> surface\n\tSurfMesh resultMesh;\n\trecover(mesh_2d, seam_mesh, vertex_2d_to_3d, DelInput.pointVec, DelOutput.triVec, constrain_point, resultMesh);\n\tprintf(\"Recover done. %f s\\n\", clock()*1.0 / CLOCKS_PER_SEC);\n\n\t// compute average edge length\n\tdouble edge_sum = 0, edge_avg = 0;\n\tfor (auto e : resultMesh.edges()) {\n\t\tedge_sum += PMP::edge_length(e, resultMesh);\n\t}\n\tedge_avg = edge_sum / resultMesh.number_of_edges();\n\tprintf(\"Average edge length: %f\\n\", edge_sum / resultMesh.number_of_halfedges());\n\n\t// Output to off file\n\tstd::ofstream ostream(\"result.off\");\n\tostream << resultMesh;\n\n\tfree(densityMap);\n\tfree(Voronoi);\n\tfree(constrainMask);\n\n#ifdef VISUALIZE_TRIANGULATION\n\t// Visualize the constraint Delaunay triangualtion\n\tVisualizer::instance()->resume();\n\tVisualizer::instance()->addFrame(DelInput.pointVec, DelInput.constraintVec, DelOutput.triVec);\n\tvis->run();\n#endif\n\n\treturn EXIT_SUCCESS;\n}\n", "meta": {"hexsha": "c8579b139286b7a7261c69f3defff22dc38e8f7a", "size": 10755, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "source/main.cpp", "max_stars_repo_name": "orzzzjq/Surface-Remesher", "max_stars_repo_head_hexsha": "0feaace68725cf1496082c617d371efb910b3203", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2020-03-18T13:33:01.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T01:29:29.000Z", "max_issues_repo_path": "source/main.cpp", "max_issues_repo_name": "orzzzjq/Surface-Remesher", "max_issues_repo_head_hexsha": "0feaace68725cf1496082c617d371efb910b3203", "max_issues_repo_licenses": ["MIT"], "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/main.cpp", "max_forks_repo_name": "orzzzjq/Surface-Remesher", "max_forks_repo_head_hexsha": "0feaace68725cf1496082c617d371efb910b3203", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2020-03-28T07:18:11.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-22T16:50:35.000Z", "avg_line_length": 39.9814126394, "max_line_length": 165, "alphanum_fraction": 0.7910739191, "num_tokens": 2970, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6297746074044135, "lm_q2_score": 0.5, "lm_q1q2_score": 0.31488730370220674}}
{"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#include <iostream>\r\n\r\n#include <boost/units/units_fwd.hpp>\r\n\r\n#include <boost/units/base_dimension.hpp>\r\n#include <boost/units/base_unit.hpp>\r\n#include <boost/units/derived_dimension.hpp>\r\n#include <boost/units/make_system.hpp>\r\n#include <boost/units/io.hpp>\r\n#include <boost/units/quantity.hpp>\r\n#include <boost/units/static_constant.hpp>\r\n#include <boost/units/unit.hpp>\r\n\r\nnamespace boost {\r\n\r\nnamespace units {\r\n\r\nstruct length_base_dimension : boost::units::base_dimension<length_base_dimension,1> { };       ///> base dimension of length\r\nstruct time_base_dimension : boost::units::base_dimension<time_base_dimension,3> { };           ///> base dimension of time\r\n\r\ntypedef length_base_dimension::dimension_type    length_dimension;\r\ntypedef time_base_dimension::dimension_type      time_dimension;\r\n\r\nstruct length1_base_unit : base_unit<length1_base_unit,length_dimension,1>\r\n{\r\n    static std::string name()               { return \"length 1\"; }\r\n    static std::string symbol()             { return \"l1\"; }\r\n};\r\n\r\nstruct length2_base_unit : base_unit<length2_base_unit,length_dimension,2>\r\n{\r\n    static std::string name()               { return \"length2\"; }\r\n    static std::string symbol()             { return \"l2\"; }\r\n};\r\n\r\nstruct time1_base_unit : base_unit<time1_base_unit,time_dimension,3> \r\n{\r\n    static std::string name()               { return \"time1\"; }\r\n    static std::string symbol()             { return \"t1\"; }\r\n};\r\n\r\nstruct time2_base_unit : base_unit<time2_base_unit,time_dimension,4> \r\n{\r\n    static std::string name()               { return \"time2\"; }\r\n    static std::string symbol()             { return \"t2\"; }\r\n};\r\n\r\nnamespace s1 {\r\n\r\ntypedef make_system<length1_base_unit,time1_base_unit>::type   system;\r\n\r\n/// unit typedefs\r\ntypedef unit<dimensionless_type,system>     dimensionless;\r\n\r\ntypedef unit<length_dimension,system>       length;\r\ntypedef unit<time_dimension,system>         time;\r\n\r\n/// unit constants \r\nBOOST_UNITS_STATIC_CONSTANT(length1,length);\r\nBOOST_UNITS_STATIC_CONSTANT(time1,time);\r\n\r\n} // namespace s1\r\n\r\nnamespace s2 {\r\n\r\ntypedef make_system<length2_base_unit,time2_base_unit>::type   system;\r\n\r\n/// unit typedefs\r\ntypedef unit<dimensionless_type,system>     dimensionless;\r\n\r\ntypedef unit<length_dimension,system>       length;\r\ntypedef unit<time_dimension,system>         time;\r\n\r\n/// unit constants \r\nBOOST_UNITS_STATIC_CONSTANT(length2,length);\r\nBOOST_UNITS_STATIC_CONSTANT(time2,time);\r\n\r\n} // namespace s2\r\n\r\ntemplate<class X,class Y>\r\nstruct conversion_helper< quantity<s1::length,X>,quantity<s2::length,Y> >\r\n{\r\n    static quantity<s2::length,Y> convert(const quantity<s1::length,X>& source)\r\n    {\r\n        return quantity<s2::length,Y>::from_value(2.5*source.value());\r\n    }\r\n};\r\n\r\ntemplate<class X,class Y>\r\nstruct conversion_helper< quantity<s2::length,X>,quantity<s1::length,Y> >\r\n{\r\n    static quantity<s1::length,Y> convert(const quantity<s2::length,X>& source)\r\n    {\r\n        return quantity<s1::length,Y>::from_value((1.0/2.5)*source.value());\r\n    }\r\n};\r\n\r\ntemplate<class X,class Y>\r\nstruct conversion_helper< quantity<s1::time,X>,quantity<s2::time,Y> >\r\n{\r\n    static quantity<s2::time,Y> convert(const quantity<s1::time,X>& source)\r\n    {\r\n        return quantity<s2::time,Y>::from_value(0.5*source.value());\r\n    }\r\n};\r\n\r\n} // namespace units\r\n\r\n} // namespace boost\r\n\r\nint main(void)\r\n{\r\n    using namespace boost::units;\r\n\r\n    quantity<s1::length,float>  l1(1.0*s1::length1);\r\n    quantity<s2::length,double> l2(1.5*l1);\r\n    quantity<s1::length,float>  l3(2.0*l2/3.0);\r\n\r\n    quantity<s1::time,float>    t1(1.0*s1::time1);\r\n    quantity<s2::time,double>   t2(1.5*t1);\r\n//    quantity<s1::time,float>    t3(2.0*t2/3.0);\r\n    \r\n    return 0;\r\n}\r\n\r\n/*\r\n// 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#include <iostream>\r\n\r\n#include <boost/units/units_fwd.hpp>\r\n\r\n#include <boost/units/base_dimension.hpp>\r\n#include <boost/units/base_unit.hpp>\r\n#include <boost/units/derived_dimension.hpp>\r\n#include <boost/units/make_system.hpp>\r\n#include <boost/units/io.hpp>\r\n#include <boost/units/quantity.hpp>\r\n#include <boost/units/static_constant.hpp>\r\n#include <boost/units/unit.hpp>\r\n\r\nnamespace boost {\r\n\r\nnamespace units {\r\n\r\nstruct length_base_dimension : boost::units::base_dimension<length_base_dimension,1> { };       ///> base dimension of length\r\nstruct mass_base_dimension : boost::units::base_dimension<mass_base_dimension,2> { };           ///> base dimension of mass\r\nstruct time_base_dimension : boost::units::base_dimension<time_base_dimension,3> { };           ///> base dimension of time\r\n\r\ntypedef length_base_dimension::dimension_type    length_dimension;\r\ntypedef mass_base_dimension::dimension_type      mass_dimension;\r\ntypedef time_base_dimension::dimension_type      time_dimension;\r\n\r\nstruct centimeter_base_unit : base_unit<centimeter_base_unit,length_dimension,1>\r\n{\r\n    static std::string name()               { return \"centimeter\"; }\r\n    static std::string symbol()             { return \"cm\"; }\r\n};\r\n\r\nstruct gram_base_unit : base_unit<gram_base_unit,mass_dimension,2> \r\n{\r\n    static std::string name()               { return \"gram\"; }\r\n    static std::string symbol()             { return \"g\"; }\r\n};\r\n\r\nstruct second_base_unit : base_unit<second_base_unit,time_dimension,3> \r\n{\r\n    static std::string name()               { return \"second\"; }\r\n    static std::string symbol()             { return \"s\"; }\r\n};\r\n\r\nnamespace CG {\r\n\r\ntypedef make_system<centimeter_base_unit,gram_base_unit>::type   system;\r\n\r\n/// unit typedefs\r\ntypedef unit<dimensionless_type,system>     dimensionless;\r\n\r\ntypedef unit<length_dimension,system>       length;\r\ntypedef unit<mass_dimension,system>         mass;\r\n\r\n/// unit constants \r\nBOOST_UNITS_STATIC_CONSTANT(centimeter,length);\r\nBOOST_UNITS_STATIC_CONSTANT(gram,mass);\r\n\r\n} // namespace CG\r\n\r\nnamespace cgs {\r\n\r\ntypedef make_system<centimeter_base_unit,gram_base_unit,second_base_unit>::type system;\r\n\r\n/// unit typedefs\r\ntypedef unit<dimensionless_type,system>     dimensionless;\r\n\r\ntypedef unit<length_dimension,system>       length;\r\ntypedef unit<mass_dimension,system>         mass;\r\ntypedef unit<time_dimension,system>         time;\r\n\r\n/// unit constants \r\nBOOST_UNITS_STATIC_CONSTANT(centimeter,length);\r\nBOOST_UNITS_STATIC_CONSTANT(gram,mass);\r\nBOOST_UNITS_STATIC_CONSTANT(second,time);\r\n\r\n} // namespace cgs\r\n\r\nnamespace esu {\r\n\r\ntypedef make_system<centimeter_base_unit,\r\n                    gram_base_unit,\r\n                    second_base_unit>::type system;\r\n\r\n/// derived dimension for force in electrostatic units : L M T^-2\r\ntypedef derived_dimension<length_base_dimension,1,\r\n                          mass_base_dimension,1,\r\n                          time_base_dimension,-2>::type                                             force_dimension;\r\n                          \r\n/// derived dimension for charge in electrostatic units : L^3/2 M^1/2 T^-1\r\ntypedef make_dimension_list< mpl::list< dim<length_base_dimension,static_rational<3,2> >,\r\n                                        dim<mass_base_dimension,static_rational<1,2> >,\r\n                                        dim<time_base_dimension,static_rational<-1> > > >::type     charge_dimension; \r\n\r\n/// derived dimension for current in electrostatic units : L^3/2 M^1/2 T^-2\r\ntypedef make_dimension_list< mpl::list< dim<length_base_dimension,static_rational<3,2> >,\r\n                                        dim<mass_base_dimension,static_rational<1,2> >,\r\n                                        dim<time_base_dimension,static_rational<-2> > > >::type     current_dimension; \r\n\r\n/// derived dimension for electric potential in electrostatic units : L^1/2 M^1/2 T^-1\r\ntypedef make_dimension_list< mpl::list< dim<length_base_dimension,static_rational<1,2> >,\r\n                                        dim<mass_base_dimension,static_rational<1,2> >,\r\n                                        dim<time_base_dimension,static_rational<-1> > > >::type     electric_potential_dimension; \r\n\r\n/// derived dimension for electric field in electrostatic units : L^-1/2 M^1/2 T^-1\r\ntypedef make_dimension_list< mpl::list< dim<length_base_dimension,static_rational<-1,2> >,\r\n                                        dim<mass_base_dimension,static_rational<1,2> >,\r\n                                        dim<time_base_dimension,static_rational<-1> > > >::type     electric_field_dimension; \r\n\r\n/// unit typedefs\r\ntypedef unit<dimensionless_type,system>     dimensionless;\r\n\r\ntypedef unit<length_dimension,system>       length;\r\ntypedef unit<mass_dimension,system>         mass;\r\ntypedef unit<time_dimension,system>         time;\r\n\r\ntypedef unit<force_dimension,system>        force;\r\n\r\ntypedef unit<charge_dimension,system>               charge;\r\ntypedef unit<current_dimension,system>              current;\r\ntypedef unit<electric_potential_dimension,system>   electric_potential;\r\ntypedef unit<electric_field_dimension,system>       electric_field;\r\n\r\n/// unit constants \r\nBOOST_UNITS_STATIC_CONSTANT(centimeter,length);\r\nBOOST_UNITS_STATIC_CONSTANT(gram,mass);\r\nBOOST_UNITS_STATIC_CONSTANT(second,time);\r\n\r\nBOOST_UNITS_STATIC_CONSTANT(dyne,force);\r\n\r\nBOOST_UNITS_STATIC_CONSTANT(esu,charge);\r\nBOOST_UNITS_STATIC_CONSTANT(statvolt,electric_potential);\r\n\r\n} // namespace esu\r\n\r\ntemplate<class Y>\r\nquantity<esu::force,Y> coulombLaw(const quantity<esu::charge,Y>& q1,\r\n                                  const quantity<esu::charge,Y>& q2,\r\n                                  const quantity<esu::length,Y>& r)\r\n{\r\n    return q1*q2/(r*r);\r\n}\r\n\r\n} // namespace units\r\n\r\n} // namespace boost\r\n\r\nint main(void)\r\n{\r\n    using namespace boost::units;\r\n\r\n    quantity<CG::length>    cg_length(1.0*CG::centimeter);\r\n    quantity<cgs::length>   cgs_length(1.0*cgs::centimeter);\r\n    \r\n    std::cout << cg_length/cgs_length << std::endl;\r\n\r\n    std::cout << esu::gram*pow<2>(esu::centimeter/esu::second)/esu::esu << std::endl;\r\n    std::cout << esu::statvolt/esu::centimeter << std::endl;\r\n    \r\n    quantity<esu::charge>   q1 = 1.0*esu::esu,\r\n                            q2 = 2.0*esu::esu;\r\n    quantity<esu::length>   r = 1.0*esu::centimeter;\r\n    \r\n    std::cout << coulombLaw(q1,q2,r) << std::endl;\r\n    std::cout << coulombLaw(q1,q2,cgs_length) << std::endl;\r\n    \r\n    return 0;\r\n}\r\n*/\r\n", "meta": {"hexsha": "d9ae6fd1eb36b3054728b95cff1108a72a914cbc", "size": 10991, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/units/tutorial/tutorial_1.cpp", "max_stars_repo_name": "Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo", "max_stars_repo_head_hexsha": "eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 198.0, "max_stars_repo_stars_event_min_datetime": "2015-01-13T05:47:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-09T04:46:46.000Z", "max_issues_repo_path": "libs/boost/libs/units/tutorial/tutorial_1.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/units/tutorial/tutorial_1.cpp", "max_forks_repo_name": "flingone/frameworks_base_cmds_remoted", "max_forks_repo_head_hexsha": "4509d9f0468137ed7fd8d100179160d167e7d943", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 139.0, "max_forks_repo_forks_event_min_datetime": "2015-01-15T20:09:31.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-31T15:21:16.000Z", "avg_line_length": 34.8920634921, "max_line_length": 131, "alphanum_fraction": 0.6609043763, "num_tokens": 2576, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6297745935070806, "lm_q2_score": 0.5, "lm_q1q2_score": 0.3148872967535403}}
{"text": "#pragma once\n\n// deal.II includes\n#include <deal.II/base/types.h>\n#include <deal.II/dofs/dof_handler.h>\n#include <deal.II/fe/fe.h>\n#include <deal.II/fe/fe_face.h>\n#include <deal.II/fe/fe_values.h>\n\n#include <Eigen/Core>\n\n// system includes\n#include <map>\n#include <vector>\n\n\nnamespace boltzmann {\n\nclass FaceOrientation2D\n{\n protected:\n  static const int dimX = 2;\n  typedef dealii::DoFHandler<dimX> dof_handler_t;\n  typedef typename dof_handler_t::active_cell_iterator cell_it;\n  typedef dealii::types::global_dof_index size_type;\n\n  /// key: <cell iterator, face_idx>\n  typedef std::tuple<cell_it, int> key_t;\n  typedef struct\n  {\n    Eigen::Vector2d normal_vector;\n    /// DoF (vertex) indices right\n    size_type phys_idx_r;\n    /// DoF (vertex) indices left\n    size_type phys_idx_l;\n    double length;\n  } face_data_t;\n\n public:\n  typedef std::map<key_t, face_data_t> face_data_map_t;\n\n public:\n  void init(const dof_handler_t& dof_handler);\n\n  const face_data_map_t& get_faces_map() const { return face_data_map_; }\n\n  const std::vector<face_data_t>& get_faces() const { return faces_; }\n\n protected:\n  face_data_map_t face_data_map_;\n  std::vector<face_data_t> faces_;\n};\n\nvoid\nFaceOrientation2D::init(const dof_handler_t& dof_handler)\n{\n  // faces -> local fe dofs\n  std::array<std::array<size_type, 2>, 4> faces2localdofs;\n  faces2localdofs[0] = {0, 2};\n  faces2localdofs[1] = {1, 3};\n  faces2localdofs[2] = {0, 1};\n  faces2localdofs[3] = {2, 3};\n\n  const auto& fe = dof_handler.get_fe();\n  dealii::UpdateFlags update_flags = dealii::update_values | dealii::update_JxW_values |\n                                     dealii::update_quadrature_points |\n                                     dealii::update_normal_vectors;\n  dealii::QGauss<1> quad(1);\n  dealii::FEFaceValues<dimX, dimX> fe_face_values(fe, quad, update_flags);\n\n  const unsigned int dofs_per_cell = fe_face_values.dofs_per_cell;\n  std::vector<size_type> local_dof_indices(dofs_per_cell);\n\n  for (auto cell = dof_handler.begin_active(); cell != dof_handler.end(); ++cell) {\n    cell->get_dof_indices(local_dof_indices);\n    for (unsigned int face_idx = 0; face_idx < dealii::GeometryInfo<dimX>::faces_per_cell;\n         ++face_idx) {\n      if (cell->face(face_idx)->at_boundary()) {\n        // *** Face is located at boundary ***\n        fe_face_values.reinit(cell, face_idx);\n\n        // relevant FE dofs\n        const double nx = fe_face_values.normal_vector(0)[0];\n        const double ny = fe_face_values.normal_vector(0)[1];\n        face_data_t face_data;\n        face_data.normal_vector << nx, ny;\n\n        size_type phys_idx_l = local_dof_indices[faces2localdofs[face_idx][0]];\n        size_type phys_idx_r = local_dof_indices[faces2localdofs[face_idx][1]];\n        face_data.phys_idx_l = phys_idx_l;\n        face_data.phys_idx_r = phys_idx_r;\n        face_data.length = cell->face(face_idx)->measure();\n\n        auto key = std::make_tuple(cell, face_idx);\n        face_data_map_[key] = face_data;\n      }\n    }\n  }\n\n  for (auto it = face_data_map_.begin(); it != face_data_map_.end(); ++it) {\n    faces_.push_back(it->second);\n  }\n}\n\n}  // end namespace boltzmann\n", "meta": {"hexsha": "f9b73c9dc679183622dcbb0229fa3f9a929bbbe4", "size": 3142, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/grid/face_orientation.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/face_orientation.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/face_orientation.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.641509434, "max_line_length": 90, "alphanum_fraction": 0.6820496499, "num_tokens": 871, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6150878555160665, "lm_q2_score": 0.5117166047041654, "lm_q1q2_score": 0.31475066901944776}}
{"text": "// SNCOperators.cpp - Code for the SNC operator equations.\n// See SNCOperators.hpp for details.\n//\n// Copyright (c) 2016 Timothy Zhu.\n// Licensed under the MIT License. See LICENSE file for details.\n//\n\n#include <cassert>\n#include <cmath>\n#include <cstdlib>\n#include <stdint.h>\n#include <set>\n#include <vector>\n#include <limits>\n#include <Eigen/Core>\n#include <Eigen/Eigenvalues>\n#include \"ProcessedTrace.hpp\"\n#include \"time.hpp\"\n#include \"search.hpp\"\n#include \"NC.hpp\"\n#include \"MGF.hpp\"\n#include \"SNCOperators.hpp\"\n\nusing namespace std;\n\nconst uint64_t MMBPArrival::intervalWidth = ConvertSecondsToTime(1);\n\n// Check if there is a dependency between bound and this. A dependency exists if both bound and this share the same flow id in their dependency sets.\nbool DependencyParams::checkDependence(const DependencyParams* bound) const\n{\n    const set<FlowId>& A = getDependencies();\n    const set<FlowId>& B = bound->getDependencies();\n    set<FlowId>::const_iterator itA = A.begin();\n    set<FlowId>::const_iterator itB = B.begin();\n    while ((itA != A.end()) && (itB != B.end())) {\n        if (*itA == *itB) {\n            return true;\n        } else if (*itA < *itB) {\n            itA++;\n        } else {\n            itB++;\n        }\n    }\n    return false;\n}\n\n// Top-level function for analyzing a trace and initializing the MMBP parameters based on the analysis.\nvoid MMBPArrival::init(ProcessedTrace* pTrace)\n{\n    // Split trace into intervals of length intervalWidth\n    vector<double> intervals;\n    countArrivalIntervals(pTrace, intervals);\n    // Assign a state to each interval using the LAMBDA algorithm\n    vector<unsigned int> states;\n    vector<double> lambdas;\n    unsigned int numStates = determineStatesLAMBDA(intervals, states, lambdas, 2.0);\n    // Initialize the transition matrix between states\n    initTransitionMatrix(numStates, states);\n    // Initialize MGFs for each state\n    initMGFs(pTrace, numStates, states, lambdas);\n}\n\n// Count the number of arrivals in each interval in the trace pTrace and store the results in intervals.\nvoid MMBPArrival::countArrivalIntervals(ProcessedTrace* pTrace, vector<double>& intervals) const\n{\n    intervals.clear();\n    int count = 0;\n    uint64_t nextIntervalTime = intervalWidth;\n    ProcessedTraceEntry traceEntry;\n    pTrace->reset();\n    while (pTrace->nextEntry(traceEntry)) {\n        while (traceEntry.arrivalTime >= nextIntervalTime) {\n            intervals.push_back(count);\n            count = 0;\n            nextIntervalTime += intervalWidth;\n        }\n        count++;\n    }\n    intervals.push_back(count);\n}\n\n// Helper function for performing the LAMBDA algorithm.\ndouble MMBPArrival::LAMBDAAlgorithm(double a, void* params)\n{\n    LAMBDAParams_t* p = static_cast<LAMBDAParams_t*>(params);\n    double low = p->low;\n    double high = p->high;\n    vector<double>* pLambdas = p->pLambdas;\n    double lambda = sqrt(high + a * a / 4.0) - (a / 2.0);\n    lambda = lambda * lambda;\n    for (unsigned int state = pLambdas->size() - 1; state > 0; state--) {\n        if (lambda < low) {\n            return -numeric_limits<double>::infinity();\n        }\n        (*pLambdas)[state] = lambda;\n        lambda = sqrt(lambda) - a;\n        lambda = lambda * lambda;\n    }\n    (*pLambdas)[0] = lambda;\n    return lambda - a * sqrt(lambda);\n}\n\n// Assign a state to each interval in the trace using the LAMBDA algorithm. Returns number of states used, up to maxNumStates.\nunsigned int MMBPArrival::determineStatesLAMBDA(const vector<double>& intervals, vector<unsigned int>& states, vector<double>& lambdas, double a) const\n{\n    // Find largest and smallest interval size\n    LAMBDAParams_t params;\n    double& low = params.low;\n    double& high = params.high;\n    params.pLambdas = &lambdas;\n    low = intervals[0];\n    high = intervals[0];\n    for (unsigned int intervalIndex = 1; intervalIndex < intervals.size(); intervalIndex++) {\n        if (intervals[intervalIndex] < low) {\n            low = intervals[intervalIndex];\n        }\n        if (intervals[intervalIndex] > high) {\n            high = intervals[intervalIndex];\n        }\n    }\n    // Determine lambdas with LAMBDA algorithm\n    unsigned int numStates = maxNumStates;\n    lambdas.resize(numStates, 0);\n    if (isfinite(LAMBDAAlgorithm(a, &params))) {\n        // Maximum number of states used, search for best confidence interval for the max number of states to cover the range\n        a = binarySearchReverse(0, high, low, 0.01, LAMBDAAlgorithm, &params);\n        LAMBDAAlgorithm(a, &params);\n    } else {\n        // Less than the max number of states needed for a given confidence interval, remove unnecessary states\n        unsigned int unusedStates = 0;\n        for (unsigned int state = 0; state < lambdas.size(); state++) {\n            if (lambdas[state] > 0) {\n                lambdas[state - unusedStates] = lambdas[state];\n            } else {\n                unusedStates++;\n            }\n        }\n        numStates -= unusedStates;\n        lambdas.resize(numStates);\n    }\n    // Assign states to intervals\n    states.resize(intervals.size(), 0);\n    for (unsigned int intervalIndex = 0; intervalIndex < intervals.size(); intervalIndex++) {\n        states[intervalIndex] = 0;\n        for (unsigned int state = lambdas.size() - 1; state > 0; state--) {\n            double lambda = lambdas[state];\n            if (intervals[intervalIndex] > (lambda - a * sqrt(lambda))) {\n                states[intervalIndex] = state;\n                break;\n            }\n        }\n    }\n    return numStates;\n}\n\n// Initialize the transition matrix between states.\nvoid MMBPArrival::initTransitionMatrix(unsigned int numStates, const vector<unsigned int>& states)\n{\n    // Initialize transition matrix size\n    _transitionMatrix.resize(numStates);\n    for (unsigned int state = 0; state < numStates; state++) {\n        _transitionMatrix[state].resize(numStates);\n    }\n    // Calculate transition matrix\n    vector<uint64_t> stateDurations(numStates, 0);\n    unsigned int fromState = states[0];\n    stateDurations[fromState] += intervalWidth;\n    for (unsigned int stateIndex = 1; stateIndex < states.size(); stateIndex++) {\n        unsigned int toState = states[stateIndex];\n        stateDurations[toState] += intervalWidth;\n        _transitionMatrix[fromState][toState] += 1;\n        fromState = toState;\n    }\n    for (unsigned int fromState = 0; fromState < numStates; fromState++) {\n        double stateSteps = floor(ConvertTimeToSeconds(stateDurations[fromState]) / stepSize);\n        if (stateSteps == 0) {\n            stateSteps = 1;\n        }\n        double probTransition = 0;\n        _transitionMatrix[fromState][fromState] = 0;\n        for (unsigned int toState = 0; toState < numStates; toState++) {\n            _transitionMatrix[fromState][toState] /= stateSteps;\n            probTransition += _transitionMatrix[fromState][toState];\n        }\n        _transitionMatrix[fromState][fromState] = 1.0 - probTransition;\n    }\n}\n\n// Helper function for creating the MGF for a MMBP state.\nMGF* MMBPArrival::createMMBPStateMGF()\n{\n    return new MGFExponential();\n}\n\n// Initialize each MMBP state with its associated arrival rate and request size distribution, which is represented by a moment generating function (MGF).\nvoid MMBPArrival::initMGFs(ProcessedTrace* pTrace, unsigned int numStates, const vector<unsigned int>& states, const vector<double>& lambdas)\n{\n    // Initialize MGFs\n    _MGFs.resize(numStates);\n    for (unsigned int state = 0; state < numStates; state++) {\n        _MGFs[state] = createMMBPStateMGF();\n    }\n    // Estimate MGFs based on trace\n    uint64_t nextIntervalTime = intervalWidth;\n    unsigned int stateIndex = 0;\n    ProcessedTraceEntry traceEntry;\n    pTrace->reset();\n    while (pTrace->nextEntry(traceEntry)) {\n        while (traceEntry.arrivalTime >= nextIntervalTime) {\n            stateIndex++;\n            nextIntervalTime += intervalWidth;\n        }\n        unsigned int state = states[stateIndex];\n        _MGFs[state]->addSampleRequest(traceEntry);\n    }\n    // Set prob of generating a request for each MGF\n    for (unsigned int state = 0; state < numStates; state++) {\n        _MGFs[state]->setProbRequest(lambdas[state] * stepSize / ConvertTimeToSeconds(intervalWidth));\n    }\n}\n\n// Calculate the spectral radius of the matrix: Diag(_MGFs(theta)) * _transitionMatrix,\n// where Diag(_MGFs(theta)) is the diagonal matrix from evaluating each entry of _MGFs for a given theta value.\ndouble MMBPArrival::calcSpectralRadius(double theta) const\n{\n    if (_MGFs.size() == 2) {\n        // Hand-solved solution for 2 states\n        double MGF0 = _MGFs[0]->calcMGF(theta);\n        double MGF1 = _MGFs[1]->calcMGF(theta);\n        double L1 = (_transitionMatrix[0][0] * MGF0 + _transitionMatrix[1][1] * MGF1 + sqrt((_transitionMatrix[0][0] * MGF0 - _transitionMatrix[1][1] * MGF1) * (_transitionMatrix[0][0] * MGF0 - _transitionMatrix[1][1] * MGF1) + 4.0 * _transitionMatrix[0][1] * _transitionMatrix[1][0] * MGF0 * MGF1)) / 2.0;\n        double L2 = (_transitionMatrix[0][0] * MGF0 + _transitionMatrix[1][1] * MGF1 - sqrt((_transitionMatrix[0][0] * MGF0 - _transitionMatrix[1][1] * MGF1) * (_transitionMatrix[0][0] * MGF0 - _transitionMatrix[1][1] * MGF1) + 4.0 * _transitionMatrix[0][1] * _transitionMatrix[1][0] * MGF0 * MGF1)) / 2.0;\n        return max(fabs(L1), fabs(L2));\n    } else {\n        // Generic solution for n states\n        Eigen::MatrixXd m(_MGFs.size(), _MGFs.size());\n        for (unsigned int fromState = 0; fromState < _transitionMatrix.size(); fromState++) {\n            double stateMGF = _MGFs[fromState]->calcMGF(theta);\n            if (!isfinite(stateMGF)) {\n                return numeric_limits<double>::infinity();\n            }\n            for (unsigned int toState = 0; toState < _transitionMatrix[fromState].size(); toState++) {\n                m(fromState, toState) = stateMGF * _transitionMatrix[fromState][toState];\n            }\n        }\n        return m.eigenvalues().cwiseAbs().maxCoeff();\n    }\n}\n\n// Equations for the MMBPArrival operator, representing an arrival process of a flow as analyzed by its trace.\nvoid MMBPArrival::calcBound(double theta, double* sigma, double* rho) const\n{\n    *sigma = 0;\n    *rho = log(calcSpectralRadius(theta)) / theta;\n}\n\n// Equations for the ConstantService operator, representing a constant service process with rate c.\nvoid ConstantService::calcBound(double theta, double* sigma, double* rho) const\n{\n    *sigma = 0;\n    *rho = -_c;\n}\n\n// Equations for the AggregateArrival operator, representing the aggregation of two arrival processes A and B.\nvoid AggregateArrival::calcBound(double theta, double* sigma, double* rho) const\n{\n    double sigmaA, rhoA;\n    double sigmaB, rhoB;\n    _A->calcBound(getP() * theta, &sigmaA, &rhoA);\n    _B->calcBound(getQ() * theta, &sigmaB, &rhoB);\n    *sigma = sigmaA + sigmaB;\n    *rho = rhoA + rhoB;\n}\n\n// Equations for the ConvolutionService operator, representing the convolution of two service processes S and T.\nvoid ConvolutionService::calcBound(double theta, double* sigma, double* rho) const\n{\n    double sigmaS, rhoS;\n    double sigmaT, rhoT;\n    _S->calcBound(getP() * theta, &sigmaS, &rhoS);\n    _T->calcBound(getQ() * theta, &sigmaT, &rhoT);\n    // Handle the rhoS == rhoT case\n    if (rhoS == rhoT) {\n        rhoS *= 0.99;\n    }\n    *sigma = sigmaS + sigmaT - log(1.0 - exp(-theta * abs(rhoS - rhoT))) / theta;\n    *rho = max(rhoS, rhoT);\n}\n\n// Equations for the OutputArrival operator, representing the departure process of an arrival process A after leaving a queue with service process S.\nvoid OutputArrival::calcBound(double theta, double* sigma, double* rho) const\n{\n    double sigmaA, rhoA;\n    double sigmaS, rhoS;\n    _A->calcBound(getP() * theta, &sigmaA, &rhoA);\n    _S->calcBound(getQ() * theta, &sigmaS, &rhoS);\n    *sigma = sigmaA + sigmaS - log(1.0 - exp(theta * (rhoA + rhoS))) / theta;\n    *rho = rhoA;\n}\n\n// Equations for the LeftoverService operator, representing the remaining service process that is leftover once a queue with service process S has accounted for the behavior of an arrival process A.\nvoid LeftoverService::calcBound(double theta, double* sigma, double* rho) const\n{\n    double sigmaA, rhoA;\n    double sigmaS, rhoS;\n    _A->calcBound(getP() * theta, &sigmaA, &rhoA);\n    _S->calcBound(getQ() * theta, &sigmaS, &rhoS);\n    *sigma = sigmaA + sigmaS;\n    *rho = rhoA + rhoS;\n}\n\n// Calculate the latency bound for a given theta value. Each invocation with a positive theta produces a valid (but possibly sub-optimal) upper bound on latency.\ndouble LatencyBound::calcLatency(double theta) const\n{\n    double sigmaA, rhoA;\n    double sigmaS, rhoS;\n    _A->calcBound(getP() * theta, &sigmaA, &rhoA);\n    _S->calcBound(getQ() * theta, &sigmaS, &rhoS);\n    double latency = (log(_epsilon * (1.0 - exp(theta * (rhoA + rhoS)))) / theta - (sigmaA + sigmaS)) / rhoS;\n    return latency * stepSize;\n}\n\n// Optimize over the space of positive theta values to search for the theta value that produces the best (i.e., tightest) latency bound.\ndouble LatencyBound::calcTheta() const\n{\n    const double MIN_THETA = 1e-9;\n    const double INITIAL_THETA = 1000.0;\n    const double STEP_SIZE_DECREASE_FACTOR = 10.0;\n    const double INITIAL_STEP_SIZE = INITIAL_THETA / STEP_SIZE_DECREASE_FACTOR;\n    void* params = const_cast<LatencyBound*>(this);\n    double theta = INITIAL_THETA;\n    for (double stepSize = INITIAL_STEP_SIZE; stepSize >= MIN_THETA; stepSize /= STEP_SIZE_DECREASE_FACTOR) {\n        theta = minSearch(max(theta - (STEP_SIZE_DECREASE_FACTOR * stepSize), MIN_THETA), theta + (STEP_SIZE_DECREASE_FACTOR * stepSize), stepSize, calcLatency, params);\n    }\n    return theta;\n}\n\n// Static helper function used by calcTheta.\ndouble LatencyBound::calcLatency(double theta, void* params)\n{\n    const LatencyBound* p = static_cast<const LatencyBound*>(params);\n    return p->calcLatency(theta);\n}\n\n// Calculate the latency bound using an optimized theta value.\ndouble LatencyBound::calcLatency() const\n{\n    return calcLatency(calcTheta());\n}\n\n// Optimize the Hoelder dependency parameters. More research is needed to improve speed and accuracy.\ndouble LatencyBound::dependencyOptimization() const\n{\n    const vector<DependencyParams*>& bounds = getDependentBounds();\n    const unsigned int SEARCH_RANGE_DECREASE_COUNT = 25;\n    const double SEARCH_RANGE_DECREASE_FACTOR = 1.2;\n    const unsigned int ITERATION_COUNT = bounds.size() * 10;\n    double minLatency = calcLatency();\n    // Early exit if no dependencyParams to optimize\n    if (bounds.size() == 0) {\n        return minLatency;\n    }\n    // Optimize for the best Hoelder p value\n    vector<double> bestP(bounds.size());\n    for (unsigned int index = 0; index < bounds.size(); index++) {\n        bestP[index] = bounds[index]->getP();\n    }\n    srand(1); // use fixed seed to avoid different latency calculations across multiple calls\n    for (unsigned int i = 0; i < SEARCH_RANGE_DECREASE_COUNT; i++) {\n        // Randomly search within search space\n        for (unsigned int iter = 0; iter < ITERATION_COUNT; iter++) {\n            // Set p/q\n            for (unsigned int index = 0; index < bounds.size(); index++) {\n                DependencyParams* bound = bounds[index];\n                double searchRangeP = bound->getUpperP() - bound->getLowerP();\n                double searchRangeQ = bound->getUpperQ() - bound->getLowerQ();\n                double r = static_cast<double>(rand()) / static_cast<double>(RAND_MAX);\n                r *= searchRangeP + searchRangeQ;\n                if (r <= searchRangeP) {\n                    bound->setP(bound->getLowerP() + r);\n                } else {\n                    r -= searchRangeP;\n                    bound->setQ(bound->getLowerQ() + r);\n                }\n            }\n            // Check for better latency\n            double latency = calcLatency();\n            if (latency < minLatency) {\n                minLatency = latency;\n                for (unsigned int index = 0; index < bounds.size(); index++) {\n                    bestP[index] = bounds[index]->getP();\n                }\n            }\n        }\n        // Update search space\n        for (unsigned int index = 0; index < bounds.size(); index++) {\n            DependencyParams* bound = bounds[index];\n            bound->setP(bestP[index]);\n            double searchRangeP = bound->getUpperP() - bound->getLowerP();\n            searchRangeP /= SEARCH_RANGE_DECREASE_FACTOR;\n            double searchRangeQ = bound->getUpperQ() - bound->getLowerQ();\n            searchRangeQ /= SEARCH_RANGE_DECREASE_FACTOR;\n            bound->setLowerP(max(bound->getP() - (searchRangeP / 2.0), 1.001));\n            bound->setUpperP(bound->getLowerP() + searchRangeP);\n            bound->setLowerQ(max(bound->getQ() - (searchRangeQ / 2.0), 1.001));\n            bound->setUpperQ(bound->getLowerQ() + searchRangeQ);\n        }\n    }\n    return minLatency;\n}\n", "meta": {"hexsha": "558fa04a96ee7d335713d0d05f6d1ae6cc707df9", "size": 16915, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/SNC-Library/SNCOperators.cpp", "max_stars_repo_name": "timmyzhu/SNC-Meister", "max_stars_repo_head_hexsha": "7ecb5de94b4dae1c3c31d699bfe2289ab9f29abd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2016-09-28T19:45:01.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-19T08:01:28.000Z", "max_issues_repo_path": "src/SNC-Library/SNCOperators.cpp", "max_issues_repo_name": "timmyzhu/SNC-Meister", "max_issues_repo_head_hexsha": "7ecb5de94b4dae1c3c31d699bfe2289ab9f29abd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/SNC-Library/SNCOperators.cpp", "max_forks_repo_name": "timmyzhu/SNC-Meister", "max_forks_repo_head_hexsha": "7ecb5de94b4dae1c3c31d699bfe2289ab9f29abd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2017-02-12T05:59:25.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-15T08:18:49.000Z", "avg_line_length": 41.256097561, "max_line_length": 306, "alphanum_fraction": 0.6512562814, "num_tokens": 4355, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6825737214979746, "lm_q2_score": 0.46101677931231594, "lm_q1q2_score": 0.3146779387282179}}
{"text": "/* The MIT License\r\n\r\nCopyright (c) 2011 Sahab Yazdani\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\r\nall copies 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\r\nTHE SOFTWARE.\r\n*/\r\n\r\n#include \"stippler_impl.h\"\r\n\r\n#include <fstream>\r\n#include <limits>\r\n#include <cstring>\r\n\r\n#include <boost/random.hpp>\r\n\r\n#include \"VoronoiDiagramGenerator.h\"\r\n\r\nStippler::Stippler( const StipplingParameters &parameters )\r\n: IStippler(),\r\nvertsX(new float[parameters.points]), vertsY(new float[parameters.points]), radii(new float[parameters.points]),\r\ndisplacement(std::numeric_limits<float>::max()),\r\nimage(parameters.inputFile),\r\nparameters(parameters) {\r\n\tcreateInitialDistribution();\r\n}\r\n\r\nStippler::~Stippler() {\r\n\tdelete[] radii;\r\n\tdelete[] vertsX;\r\n\tdelete[] vertsY;\r\n}\r\n\r\nvoid Stippler::distribute() {\r\n\tcreateVoronoiDiagram();\r\n\tredistributeStipples();\r\n}\r\n\r\nfloat Stippler::getAverageDisplacement() {\r\n\treturn displacement;\r\n}\r\n\r\nvoid Stippler::createInitialDistribution() {\r\n\tusing std::ceil;\r\n\r\n\t// find initial distribution\r\n\tboost::mt19937 rng;\r\n\tboost::uniform_01<boost::mt19937, float> generator( rng );\r\n\r\n\tfloat w = (float)(image.getWidth() - 1), h = (float)(image.getHeight() - 1);\r\n\tfloat xC, yC;\r\n\r\n\tfor ( unsigned int i = 0; i < parameters.points; ) {\r\n\t\txC = generator() * w;\r\n\t\tyC = generator() * h;\r\n\r\n\t\t// do a nearest neighbour search on the vertices\r\n\t\tif ( ceil(generator() * 255.0f) <= image.getIntensity( xC, yC ) ) {\r\n\t\t\tvertsX[i] = xC;\r\n\t\t\tvertsY[i] = yC;\r\n\t\t\tradii[i] = 0.0f;\r\n\r\n\t\t\ti++;\r\n\t\t}\r\n\t}\r\n}\r\n\r\nvoid Stippler::getStipples( StipplePoint *dst ) {\r\n\tStipplePoint *workingPtr;\r\n\r\n\tfor (unsigned int i = 0; i < parameters.points; i++ ) {\r\n\t\tworkingPtr = &(dst[i]);\r\n\r\n\t\tworkingPtr->x = vertsX[i];\r\n\t\tworkingPtr->y = vertsY[i];\r\n\t\tworkingPtr->radius = radii[i];\r\n\r\n\t\timage.getColour(vertsX[i], vertsY[i], workingPtr->r, workingPtr->g, workingPtr->b); \r\n\t}\r\n}\r\n\r\nvoid Stippler::createVoronoiDiagram() {\r\n\tVoronoiDiagramGenerator generator;\r\n\r\n\tgenerator.generateVoronoi( vertsX, vertsY, parameters.points, \r\n\t\t0.0f, (float)(image.getWidth() - 1), 0.0f, (float)(image.getHeight() - 1) );\r\n\r\n\tedges.clear();\r\n\r\n\tPoint< float > p1, p2;\r\n\tEdge< float > edge;\r\n\r\n\tgenerator.resetIterator();\r\n\twhile ( generator.getNext( \r\n\t\tedge.begin.x, edge.begin.y, edge.end.x, edge.end.y,\r\n\t\tp1.x, p1.y, p2.x, p2.y ) ) {\r\n\r\n\t\tif ( edge.begin == edge.end ) {\r\n\t\t\tcontinue;\r\n\t\t}\r\n\r\n\t\tif ( edges.find( p1 ) == edges.end() ) {\r\n\t\t\tedges[p1] = EdgeList();\r\n\t\t}\r\n\t\tif ( edges.find( p2 ) == edges.end() ) {\r\n\t\t\tedges[p2] = EdgeList();\r\n\t\t}\r\n\t\tedges[p1].push_back( edge );\r\n\t\tedges[p2].push_back( edge );\r\n\t}\r\n}\r\n\r\nvoid Stippler::redistributeStipples() {\r\n\tusing std::pow;\r\n\tusing std::sqrt;\r\n\tusing std::pair;\r\n\tusing std::make_pair;\r\n\tusing std::vector;\r\n\r\n\tvector< pair< Point< float >, EdgeList > > vectorized;\r\n\tfor ( EdgeMap::iterator key_iter = edges.begin(); key_iter != edges.end(); ++key_iter ) {\r\n\t\tvectorized.push_back(make_pair(key_iter->first, key_iter->second));\r\n\t}\r\n\r\n\tfloat local_displacement = 0.0f;\r\n\r\n\t#pragma omp parallel for reduction(+:local_displacement)\r\n\tfor (int i = 0; i < (int)vectorized.size(); i++) {\r\n\t\tpair< Point< float >, EdgeList > item = vectorized[i];\r\n\t\tpair< Point<float>, float > centroid = calculateCellCentroid( item.first, item.second );\r\n\r\n\t\tradii[i] = centroid.second;\r\n\t\tvertsX[i] = centroid.first.x;\r\n\t\tvertsY[i] = centroid.first.y;\r\n\r\n\t\tlocal_displacement += sqrt( pow( item.first.x - centroid.first.x, 2.0f ) + pow( item.first.y - centroid.first.y, 2.0f ) );\r\n\t}\r\n\r\n\tdisplacement = local_displacement / vectorized.size(); // average out the displacement\r\n}\r\n\r\ninline Line<float> Stippler::createClipLine( float insideX, float insideY, float x1, float y1, float x2, float y2 ) {\r\n\tusing std::abs;\r\n\tusing std::numeric_limits;\r\n\r\n\tLine<float> l;\r\n\r\n\t// if the floating point version of the line collapsed down to one\r\n\t// point, then just ignore it all\r\n\tif (abs(x1 - x2) < numeric_limits<float>::epsilon() && abs(y1 - y2) < numeric_limits<float>::epsilon()) {\r\n\t\tl.a = .0f;\r\n\t\tl.b = .0f;\r\n\t\tl.c = .0f;\r\n\r\n\t\treturn l;\r\n\t}\r\n\r\n\tl.a = -(y1 - y2);\r\n\tl.b = x1 - x2;\r\n\tl.c = (y1 - y2) * x1 - (x1 - x2) * y1;\r\n\r\n\t// make sure the known inside point falls on the correct side of the clipping plane\r\n\tif ( insideX * l.a + insideY * l.b + l.c > 0.0f ) {\r\n\t\tl.a *= -1;\r\n\t\tl.b *= -1;\r\n\t\tl.c *= -1;\r\n\t}\r\n\r\n\treturn l;\r\n}\r\n\r\nstd::pair< Point<float>, float > Stippler::calculateCellCentroid( Point<float> &inside, EdgeList &edgeList ) {\r\n\tusing std::make_pair;\r\n\tusing std::numeric_limits;\r\n\tusing std::vector;\r\n\tusing std::floor;\r\n\tusing std::ceil;\r\n\tusing std::abs;\r\n\tusing std::sqrt;\r\n\tusing std::pow;\r\n\r\n\tvector< Line<float> > clipLines;\r\n\tExtents<float> extent = getCellExtents(edgeList);\r\n\r\n\tunsigned int x, y;\r\n\r\n\tfloat xDiff = ( extent.maxX - extent.minX );\r\n\tfloat yDiff = ( extent.maxY - extent.minY );\r\n\r\n\tunsigned int tileWidth = (unsigned int)ceil(xDiff) * parameters.subpixels;\r\n\tunsigned int tileHeight = (unsigned int)ceil(yDiff) * parameters.subpixels;\r\n\r\n\tfloat xStep = xDiff / (float)tileWidth;\r\n\tfloat yStep = yDiff / (float)tileHeight;\r\n\r\n\tfloat spotDensity, areaDensity = 0.0f, maxAreaDensity = 0.0f;\r\n\tfloat xSum = 0.0f;\r\n\tfloat ySum = 0.0f;\r\n\r\n\tfloat xCurrent;\r\n\tfloat yCurrent;\r\n\r\n\t// compute the clip lines\r\n\tfor ( EdgeList::iterator value_iter = edgeList.begin(); value_iter != edgeList.end(); ++value_iter ) {\r\n\t\tLine<float> l = createClipLine( inside.x, inside.y, \r\n\t\t\tvalue_iter->begin.x, value_iter->begin.y,\r\n\t\t\tvalue_iter->end.x, value_iter->end.y );\r\n\t\r\n\t\tif (l.a < numeric_limits<float>::epsilon() && abs(l.b) < numeric_limits<float>::epsilon()) {\r\n\t\t\tcontinue;\r\n\t\t}\r\n\r\n\t\tclipLines.push_back(l);\r\n\t}\r\n\r\n\tfor ( y = 0, yCurrent = extent.minY; y < tileHeight; ++y, yCurrent += yStep ) {\r\n\t\tfor ( x = 0, xCurrent = extent.minX; x < tileWidth; ++x, xCurrent += xStep ) {\r\n\t\t\t// a point is outside of the polygon if it is outside of all clipping planes\r\n\t\t\tbool outside = false;\r\n\t\t\tfor ( vector< Line<float> >::iterator iter = clipLines.begin(); iter != clipLines.end(); iter++ ) {\r\n\t\t\t\tif ( xCurrent * iter->a + yCurrent * iter->b + iter->c >= 0.0f ) {\r\n\t\t\t\t\toutside = true;\r\n\t\t\t\t\tbreak;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\tif (!outside) {\r\n\t\t\t\tspotDensity = image.getIntensity(xCurrent, yCurrent);\r\n\r\n\t\t\t\tareaDensity += spotDensity;\r\n\t\t\t\tmaxAreaDensity += 255.0f;\r\n\t\t\t\txSum += spotDensity * xCurrent;\r\n\t\t\t\tySum += spotDensity * yCurrent;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\tfloat area = areaDensity * xStep * yStep / 255.0f;\r\n\tfloat maxArea = maxAreaDensity * xStep * yStep / 255.0f;\r\n\r\n\tPoint<float> pt;\r\n\tif (areaDensity > numeric_limits<float>::epsilon()) {\r\n\t\tpt.x = xSum / areaDensity;\r\n\t\tpt.y = ySum / areaDensity;\r\n\t} else {\r\n\t\t// if for some reason, the cell is completely white, then the centroid does not move\r\n\t\tpt.x = inside.x;\r\n\t\tpt.y = inside.y;\r\n\t}\r\n\r\n\tfloat closest = numeric_limits<float>::max(),\r\n\t\t  farthest = numeric_limits<float>::min(),\r\n\t\t  distance;\r\n\tfloat x0 = pt.x, y0 = pt.y,\r\n\t      x1, x2, y1, y2;\r\n\r\n\tfor ( EdgeList::iterator value_iter = edgeList.begin(); value_iter != edgeList.end(); ++value_iter ) {\r\n\t\tx1 = value_iter->begin.x; x2 = value_iter->end.x;\r\n\t\ty1 = value_iter->begin.y; y2 = value_iter->end.y;\r\n\r\n\t\tdistance = abs( ( x2 - x1 ) * ( y1 - y0 ) - ( x1 - x0 ) * ( y2 - y1 ) ) / sqrt( pow( x2 - x1, 2.0f ) + pow( y2 - y1, 2.0f ) );\r\n\t\tif ( closest > distance ) {\r\n\t\t\tclosest = distance;\r\n\t\t}\r\n\t\tif ( farthest < distance ) {\r\n\t\t\tfarthest = distance;\r\n\t\t}\r\n\t}\r\n\r\n\tfloat radius;\r\n\tif ( parameters.noOverlap ) {\r\n\t\tradius = closest;\r\n\t} else {\r\n\t\tradius = farthest;\r\n\t}\r\n\tradius *= area / maxArea;\r\n\r\n\treturn make_pair( pt, radius );\r\n}\r\n\r\nExtents<float> Stippler::getCellExtents( Stippler::EdgeList &edgeList ) {\r\n\tusing std::numeric_limits;\r\n\r\n\tExtents<float> extent;\r\n\r\n\textent.minX = extent.minY = numeric_limits<float>::max();\r\n\textent.maxX = extent.maxY = numeric_limits<float>::min();\r\n\r\n\tfor ( EdgeList::iterator value_iter = edgeList.begin(); value_iter != edgeList.end(); ++value_iter ) {\r\n\t\tif ( value_iter->begin.x < extent.minX ) extent.minX = value_iter->begin.x;\r\n\t\tif ( value_iter->end.x < extent.minX ) extent.minX = value_iter->end.x;\r\n\t\tif ( value_iter->begin.y < extent.minY ) extent.minY = value_iter->begin.y;\r\n\t\tif ( value_iter->end.y < extent.minY ) extent.minY = value_iter->end.y;\r\n\r\n\t\tif ( value_iter->begin.x > extent.maxX ) extent.maxX = value_iter->begin.x;\r\n\t\tif ( value_iter->end.x > extent.maxX ) extent.maxX = value_iter->end.x;\r\n\t\tif ( value_iter->begin.y > extent.maxY ) extent.maxY = value_iter->begin.y;\r\n\t\tif ( value_iter->end.y > extent.maxY ) extent.maxY = value_iter->end.y;\r\n\t}\r\n\r\n\treturn extent;\r\n}\r\n\r\nbool operator==(Point<float> const& p1, Point<float> const& p2)\r\n{\r\n\tusing std::abs;\r\n\tusing std::numeric_limits;\r\n\r\n\treturn abs( p1.x - p2.x ) < numeric_limits<float>::epsilon() && \r\n\t\tabs( p1.y - p2.y ) < numeric_limits<float>::epsilon();\r\n}\r\n\r\nstd::size_t hash_value(Point<float> const& p) {\r\n\tusing std::size_t;\r\n\tusing boost::hash_combine;\r\n\r\n    size_t seed = 0;\r\n\r\n    hash_combine(seed, p.x);\r\n    hash_combine(seed, p.y);\r\n\r\n    return seed;\r\n}\r\n\r\n", "meta": {"hexsha": "82c2971de98e39a28740d744ea26b38061993860", "size": 9985, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "voronoi/stippler/stippler.cpp", "max_stars_repo_name": "StephenPArnold/CS633-hw3", "max_stars_repo_head_hexsha": "23771990a8fcfb71e629af66cb2f172e6dbda3a7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 39.0, "max_stars_repo_stars_event_min_datetime": "2015-05-13T18:17:48.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-17T22:17:10.000Z", "max_issues_repo_path": "voronoi/stippler/stippler.cpp", "max_issues_repo_name": "StephenPArnold/CS633-hw3", "max_issues_repo_head_hexsha": "23771990a8fcfb71e629af66cb2f172e6dbda3a7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2015-05-13T18:25:17.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-24T14:03:30.000Z", "max_forks_repo_path": "voronoi/stippler/stippler.cpp", "max_forks_repo_name": "StephenPArnold/CS633-hw3", "max_forks_repo_head_hexsha": "23771990a8fcfb71e629af66cb2f172e6dbda3a7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 17.0, "max_forks_repo_forks_event_min_datetime": "2015-04-20T12:44:27.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-31T05:07:05.000Z", "avg_line_length": 29.3676470588, "max_line_length": 129, "alphanum_fraction": 0.6493740611, "num_tokens": 2826, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6548947290421275, "lm_q2_score": 0.48047867804790706, "lm_q1q2_score": 0.31466295367070374}}
{"text": "/* Siconos is a program dedicated to modeling, simulation and control\n * of non smooth dynamical systems.\n *\n * Copyright 2016 INRIA.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n*/\n\n\n\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// 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\nusing namespace Siconos;\n\n\n\n//======================\n// Product of matrices\n//======================\n\nconst 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  if ((A.size(1) != B.size(0)))\n    SiconosMatrixException::selfThrow(\"Matrix function C=prod(A,B): inconsistent sizes\");\n\n  unsigned int numA = A.num();\n  unsigned int numB = B.num();\n\n  // == TODO: implement block product ==\n  if (numA == 0 || numB == 0)\n    SiconosMatrixException::selfThrow(\"Matrix product ( C=prod(A,B) ): not yet implemented for BlockMatrix objects.\");\n\n  if (numA == 7 || numB == 6) // A = identity or B = 0\n    return SimpleMatrix(B);\n\n  else if (numB == 7 || numA == 6) // 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 == 1)\n    {\n      if (numA == 1)\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 == 2)\n        return (DenseMat)(prod(*A.triang(), *B.dense()));\n      else if (numA == 3)\n        return (DenseMat)(prod(*A.sym(), *B.dense()));\n      else if (numA == 4)\n        return (DenseMat)(prod(*A.sparse(), *B.dense()));\n      else// if(numA==5)\n        return (DenseMat)(prod(*A.banded(), *B.dense()));\n    }\n    else if (numB == 2)\n    {\n      if (numA == 1)\n        return (DenseMat)(prod(*A.dense(), *B.triang()));\n      else if (numA == 2)\n        return (TriangMat)(prod(*A.triang(), *B.triang()));\n      else if (numA == 3)\n        return (DenseMat)(prod(*A.sym(), *B.triang()));\n      else if (numA == 4)\n        return (DenseMat)(prod(*A.sparse(), *B.triang()));\n      else //if(numA==5)\n        return (DenseMat)(prod(*A.banded(), *B.triang()));\n    }\n    else if (numB == 3)\n    {\n      if (numA == 1)\n        return (DenseMat)(prod(*A.dense(), *B.sym()));\n      else if (numA == 2)\n        return (DenseMat)(prod(*A.triang(), *B.sym()));\n      else if (numA == 3)\n        return (SymMat)(prod(*A.sym(), *B.sym()));\n      else if (numA == 4)\n        return (DenseMat)(prod(*A.sparse(), *B.sym()));\n      else // if (numA == 5)\n        return (DenseMat)(prod(*A.banded(), *B.sym()));\n    }\n    else if (numB == 4)\n    {\n      if (numA == 1)\n        return (DenseMat)(prod(*A.dense(), *B.sparse()));\n      else if (numA == 2)\n        return (DenseMat)(prod(*A.triang(), *B.sparse()));\n      else if (numA == 3)\n        return (DenseMat)(prod(*A.sym(), *B.sparse()));\n      else if (numA == 4)\n        return (SparseMat)(prod(*A.sparse(), *B.sparse()));\n      else //if(numA==5){\n        return (DenseMat)(prod(*A.banded(), *B.sparse()));\n    }\n    else //if(numB==5)\n    {\n      if (numA == 1)\n        return (DenseMat)(prod(*A.dense(), *B.banded()));\n      else if (numA == 2)\n        return (DenseMat)(prod(*A.triang(), *B.banded()));\n      else if (numA == 3)\n        return (DenseMat)(prod(*A.sym(), *B.banded()));\n      else if (numA == 4)\n        return (DenseMat)(prod(*A.sparse(), *B.banded()));\n      else //if(numA==5)\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//   unsigned int numA = A.num();\n//   unsigned int numB = B.num();\n//   unsigned int numC = C.num();\n//   if (numA == 0 || numB == 0 || numC == 0)\n//     SiconosMatrixException::selfThrow(\"Matrix function prod(A,B,C,index): inconsistent sizes\");\n//   // === if C is zero or identity => read-only ===\n//   if (numC == 6 || numC == 7)\n//     SiconosMatrixException::selfThrow(\"Matrix product ( prod(A,B,C,index) ): wrong type for resulting matrix C (read-only: zero or identity).\");\n\n\n//   if (numA == 7 || numC == 6) // A = identity or 0\n//     SiconosMatrixException::selfThrow(\"Matrix function prod(A,B,C,index): numA == 7 || numC == 6 not yet implemented\");\n\n//   int rawB = B.size(0);\n//   int colB = B.size(1);\n\n// }\nvoid prod(const SiconosMatrix& A, const SiconosMatrix& B, SiconosMatrix& C, bool init)\n{\n  // To compute C = A * B\n  assert(!(A.isPLUFactorized()) && \"A is PLUFactorized in prod !!\" );\n  assert(!(B.isPLUFactorized()) && \"B is PLUFactorized in prod !!\" );\n  if(!C.isBlock())\n    C.resetLU();\n\n  if ((A.size(1) != B.size(0)))\n    SiconosMatrixException::selfThrow(\"Matrix function prod(A,B,C): inconsistent sizes\");\n\n  if (A.size(0) != C.size(0) || B.size(1) != C.size(1))\n    SiconosMatrixException::selfThrow(\"Matrix function prod(A,B,C): inconsistent sizes\");\n\n  unsigned int numA = A.num();\n  unsigned int numB = B.num();\n  unsigned int numC = C.num();\n\n  // == TODO: implement block product ==\n  if (numA == 0 || numB == 0)\n    SiconosMatrixException::selfThrow(\"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 == 6 || numC == 7)\n    SiconosMatrixException::selfThrow(\"Matrix product ( prod(A,B,C) ): wrong type for resulting matrix C (read-only: zero or identity).\");\n\n\n  if (numA == 7) // A = identity ...\n  {\n    if (init)\n    {\n      if (&C != &B) C = B; // if C and B are two different objects.\n      // else nothing\n    }\n    else\n      C += B;\n  }\n\n  else if (numB == 7) // B = identity\n  {\n    if (init)\n    {\n      if (&C != &A) C = A; // if C and A are two different objects.\n      // else nothing\n    }\n    else\n      C += A;\n  }\n\n  else if (numA == 6 || numB == 6) // if A or B = 0\n  {\n    if (init)\n      C.zero();\n    //else nothing\n  }\n  else if (numC == 0) // if C is Block - Temp. solution\n  {\n    SimpleMatrix tmp(C);\n    prod(A, B, tmp, init);\n    C = tmp;\n  }\n  else // neither A or B is equal to identity or zero.\n  {\n    if (init)\n    {\n      if (&C == &A) // if common memory between A and C\n      {\n        switch (numA)\n        {\n        case 1:\n          if (numB == 1)\n          {\n            *C.dense()  = prod(*A.dense(), *B.dense());\n            //siconosBindings::blas::gemm(1.0, *A.dense(), *B.dense(), 0.0, *C.dense());\n          }\n          else if (numB == 2)\n            *C.dense()  = prod(*A.dense(), *B.triang());\n          else if (numB == 3)\n            *C.dense()  = prod(*A.dense(), *B.sym());\n          else if (numB == 4)\n            *C.dense()  = prod(*A.dense(), *B.sparse());\n          else //if(numB==5)\n            *C.dense() = prod(*A.dense(), *B.banded());\n          break;\n        case 2:\n          if (numB != 2)\n            SiconosMatrixException::selfThrow(\"Matrix function prod(A,B,C): wrong type for C (according to A and B types).\");\n          *C.triang() = prod(*A.triang(), *B.triang());\n          break;\n        case 3:\n          if (numB != 3)\n            SiconosMatrixException::selfThrow(\"Matrix function prod(A,B,C): wrong type for C (according to A and B types).\");\n          *C.sym() = prod(*A.sym(), *B.sym());\n          break;\n        case 4:\n          if (numB != 4)\n            SiconosMatrixException::selfThrow(\"Matrix function prod(A,B,C): wrong type for C (according to A and B types).\");\n          *C.sparse() = prod(*A.sparse(), *B.sparse());\n          break;\n        default:\n          SiconosMatrixException::selfThrow(\"Matrix function prod(A,B,C): wrong type for C (according to A and B types).\");\n        }\n      }\n      else if (&C == &B)\n      {\n        switch (numB)\n        {\n        case 1:\n          if (numA == 1)\n            *C.dense() = prod(*A.dense(), *B.dense());\n          else if (numA == 2)\n            *C.dense()  = prod(*A.triang(), *B.dense());\n          else if (numA == 3)\n            *C.dense()  = prod(*A.sym(), *B.dense());\n          else if (numA == 4)\n            *C.dense()  = prod(*A.sparse(), *B.dense());\n          else //if(numB==5)\n            *C.dense() = prod(*A.banded(), *B.dense());\n          break;\n        case 2:\n          if (numA != 2)\n            SiconosMatrixException::selfThrow(\"Matrix function prod(A,B,C): wrong type for C (according to A and B types).\");\n          *C.triang() = prod(*A.triang(), *B.triang());\n          break;\n        case 3:\n          if (numA != 3)\n            SiconosMatrixException::selfThrow(\"Matrix function prod(A,B,C): wrong type for C (according to A and B types).\");\n          *C.sym() = prod(*A.sym(), *B.sym());\n          break;\n        case 4:\n          if (numA != 4)\n            SiconosMatrixException::selfThrow(\"Matrix function prod(A,B,C): wrong type for C (according to A and B types).\");\n          *C.sparse() = prod(*A.sparse(), *B.sparse());\n          break;\n        default:\n          SiconosMatrixException::selfThrow(\"Matrix function prod(A,B,C): wrong type for C (according to A and B types).\");\n        }\n      }\n      else // if no alias between C and A or B.\n      {\n        switch (numC)\n        {\n        case 1:\n          if (numB == 1)\n          {\n            if (numA == 1)\n              noalias(*C.dense()) = prod(*A.dense(), *B.dense());\n            else if (numA == 2)\n              noalias(*C.dense()) = prod(*A.triang(), *B.dense());\n            else if (numA == 3)\n              noalias(*C.dense())  = prod(*A.sym(), *B.dense());\n            else if (numA == 4)\n              noalias(*C.dense()) = prod(*A.sparse(), *B.dense());\n            else// if(numA==5)\n              noalias(*C.dense())  = prod(*A.banded(), *B.dense());\n          }\n          else if (numB == 2)\n          {\n            if (numA == 1)\n              noalias(*C.dense())  = prod(*A.dense(), *B.triang());\n            else if (numA == 2)\n              noalias(*C.dense())  = prod(*A.triang(), *B.triang());\n            else if (numA == 3)\n              noalias(*C.dense())  = prod(*A.sym(), *B.triang());\n            else if (numA == 4)\n              noalias(*C.dense())  = prod(*A.sparse(), *B.triang());\n            else //if(numA==5)\n              noalias(*C.dense())  = prod(*A.banded(), *B.triang());\n          }\n          else if (numB == 3)\n          {\n            if (numA == 1)\n              noalias(*C.dense())  = prod(*A.dense(), *B.sym());\n            else if (numA == 2)\n              noalias(*C.dense())  = prod(*A.triang(), *B.sym());\n            else if (numA == 3)\n              noalias(*C.dense())  = prod(*A.sym(), *B.sym());\n            else if (numA == 4)\n              noalias(*C.dense())  = prod(*A.sparse(), *B.sym());\n            else // if (numA == 5)\n              noalias(*C.dense())  = prod(*A.banded(), *B.sym());\n          }\n          else if (numB == 4)\n          {\n            if (numA == 1)\n              noalias(*C.dense()) = prod(*A.dense(), *B.sparse());\n            else if (numA == 2)\n              noalias(*C.dense()) = prod(*A.triang(), *B.sparse());\n            else if (numA == 3)\n              noalias(*C.dense()) = prod(*A.sym(), *B.sparse());\n            else if (numA == 4)\n              noalias(*C.dense()) = prod(*A.sparse(), *B.sparse());\n            else //if(numA==5){\n              noalias(*C.dense()) = prod(*A.banded(), *B.sparse());\n          }\n          else //if(numB==5)\n          {\n            if (numA == 1)\n              noalias(*C.dense()) = prod(*A.dense(), *B.banded());\n            else if (numA == 2)\n              noalias(*C.dense()) = prod(*A.triang(), *B.banded());\n            else if (numA == 3)\n              noalias(*C.dense()) = prod(*A.sym(), *B.banded());\n            else if (numA == 4)\n              noalias(*C.dense()) = prod(*A.sparse(), *B.banded());\n            else //if(numA==5)\n              noalias(*C.dense()) = prod(*A.banded(), *B.banded());\n          }\n          break;\n        case 2:\n          if (numA != 2 || numB != 2)\n            SiconosMatrixException::selfThrow(\"Matrix function prod(A,B,C): wrong type for C (according to A and B types).\");\n          noalias(*C.triang()) = prod(*A.triang(), *B.triang());\n          break;\n        case 3:\n          if (numA != 3 || numB != 3)\n            SiconosMatrixException::selfThrow(\"Matrix function prod(A,B,C): wrong type for C (according to A and B types).\");\n          noalias(*C.sym()) = prod(*A.sym(), *B.sym());\n          break;\n        case 4:\n          if (numA != 4 || numB != 4)\n            SiconosMatrixException::selfThrow(\"Matrix function prod(A,B,C): wrong type for C (according to A and B types).\");\n          noalias(*C.sparse()) = prod(*A.sparse(), *B.sparse());\n          break;\n        default:\n          SiconosMatrixException::selfThrow(\"Matrix function prod(A,B,C): wrong type for C (according to A and B types).\");\n        }\n      }\n    }\n    else // += case\n    {\n      if (&C == &A) // if common memory between A and C\n      {\n        switch (numA)\n        {\n        case 1:\n          if (numB == 1)\n            *C.dense() += prod(*A.dense(), *B.dense());\n          else if (numB == 2)\n            *C.dense()  += prod(*A.dense(), *B.triang());\n          else if (numB == 3)\n            *C.dense()  += prod(*A.dense(), *B.sym());\n          else if (numB == 4)\n            *C.dense()  += prod(*A.dense(), *B.sparse());\n          else //if(numB==5)\n            *C.dense() += prod(*A.dense(), *B.banded());\n          break;\n        case 2:\n          if (numB != 2)\n            SiconosMatrixException::selfThrow(\"Matrix function prod(A,B,C): wrong type for C (according to A and B types).\");\n          *C.triang() += prod(*A.triang(), *B.triang());\n          break;\n        case 3:\n          if (numB != 3)\n            SiconosMatrixException::selfThrow(\"Matrix function prod(A,B,C): wrong type for C (according to A and B types).\");\n          *C.sym() += prod(*A.sym(), *B.sym());\n          break;\n        case 4:\n          if (numB != 4)\n            SiconosMatrixException::selfThrow(\"Matrix function prod(A,B,C): wrong type for C (according to A and B types).\");\n          *C.sparse() += prod(*A.sparse(), *B.sparse());\n          break;\n        default:\n          SiconosMatrixException::selfThrow(\"Matrix function prod(A,B,C): wrong type for C (according to A and B types).\");\n        }\n      }\n      else if (&C == &B)\n      {\n        switch (numB)\n        {\n        case 1:\n          if (numA == 1)\n            *C.dense() += prod(*A.dense(), *B.dense());\n          else if (numA == 2)\n            *C.dense()  += prod(*A.triang(), *B.dense());\n          else if (numA == 3)\n            *C.dense()  += prod(*A.sym(), *B.dense());\n          else if (numA == 4)\n            *C.dense()  += prod(*A.sparse(), *B.dense());\n          else //if(numB==5)\n            *C.dense() += prod(*A.banded(), *B.dense());\n          break;\n        case 2:\n          if (numA != 2)\n            SiconosMatrixException::selfThrow(\"Matrix function prod(A,B,C): wrong type for C (according to A and B types).\");\n          *C.triang() += prod(*A.triang(), *B.triang());\n          break;\n        case 3:\n          if (numA != 3)\n            SiconosMatrixException::selfThrow(\"Matrix function prod(A,B,C): wrong type for C (according to A and B types).\");\n          *C.sym() += prod(*A.sym(), *B.sym());\n          break;\n        case 4:\n          if (numA != 4)\n            SiconosMatrixException::selfThrow(\"Matrix function prod(A,B,C): wrong type for C (according to A and B types).\");\n          *C.sparse() += prod(*A.sparse(), *B.sparse());\n          break;\n        default:\n          SiconosMatrixException::selfThrow(\"Matrix function prod(A,B,C): wrong type for C (according to A and B types).\");\n        }\n      }\n      else // if no alias between C and A or B.\n      {\n        switch (numC)\n        {\n        case 1:\n          if (numB == 1)\n          {\n            if (numA == 1)\n              noalias(*C.dense()) += prod(*A.dense(), *B.dense());\n            else if (numA == 2)\n              noalias(*C.dense()) += prod(*A.triang(), *B.dense());\n            else if (numA == 3)\n              noalias(*C.dense())  += prod(*A.sym(), *B.dense());\n            else if (numA == 4)\n              noalias(*C.dense()) += prod(*A.sparse(), *B.dense());\n            else// if(numA==5)\n              noalias(*C.dense())  += prod(*A.banded(), *B.dense());\n          }\n          else if (numB == 2)\n          {\n            if (numA == 1)\n              noalias(*C.dense())  += prod(*A.dense(), *B.triang());\n            else if (numA == 2)\n              noalias(*C.dense())  += prod(*A.triang(), *B.triang());\n            else if (numA == 3)\n              noalias(*C.dense())  += prod(*A.sym(), *B.triang());\n            else if (numA == 4)\n              noalias(*C.dense())  += prod(*A.sparse(), *B.triang());\n            else //if(numA==5)\n              noalias(*C.dense())  += prod(*A.banded(), *B.triang());\n          }\n          else if (numB == 3)\n          {\n            if (numA == 1)\n              noalias(*C.dense())  += prod(*A.dense(), *B.sym());\n            else if (numA == 2)\n              noalias(*C.dense())  += prod(*A.triang(), *B.sym());\n            else if (numA == 3)\n              noalias(*C.dense())  += prod(*A.sym(), *B.sym());\n            else if (numA == 4)\n              noalias(*C.dense())  += prod(*A.sparse(), *B.sym());\n            else // if (numA == 5)\n              noalias(*C.dense())  += prod(*A.banded(), *B.sym());\n          }\n          else if (numB == 4)\n          {\n            if (numA == 1)\n              noalias(*C.dense()) += prod(*A.dense(), *B.sparse());\n            else if (numA == 2)\n              noalias(*C.dense()) += prod(*A.triang(), *B.sparse());\n            else if (numA == 3)\n              noalias(*C.dense()) += prod(*A.sym(), *B.sparse());\n            else if (numA == 4)\n              noalias(*C.dense()) += prod(*A.sparse(), *B.sparse());\n            else //if(numA==5){\n              noalias(*C.dense()) += prod(*A.banded(), *B.sparse());\n          }\n          else //if(numB==5)\n          {\n            if (numA == 1)\n              noalias(*C.dense()) += prod(*A.dense(), *B.banded());\n            else if (numA == 2)\n              noalias(*C.dense()) += prod(*A.triang(), *B.banded());\n            else if (numA == 3)\n              noalias(*C.dense()) += prod(*A.sym(), *B.banded());\n            else if (numA == 4)\n              noalias(*C.dense()) += prod(*A.sparse(), *B.banded());\n            else //if(numA==5)\n              noalias(*C.dense()) += prod(*A.banded(), *B.banded());\n          }\n          break;\n        case 2:\n          if (numA != 2 || numB != 2)\n            SiconosMatrixException::selfThrow(\"Matrix function prod(A,B,C): wrong type for C (according to A and B types).\");\n          noalias(*C.triang()) += prod(*A.triang(), *B.triang());\n          break;\n        case 3:\n          if (numA != 3 || numB != 3)\n            SiconosMatrixException::selfThrow(\"Matrix function prod(A,B,C): wrong type for C (according to A and B types).\");\n          noalias(*C.sym()) += prod(*A.sym(), *B.sym());\n          break;\n        case 4:\n          if (numA != 4 || numB != 4)\n            SiconosMatrixException::selfThrow(\"Matrix function prod(A,B,C): wrong type for C (according to A and B types).\");\n          noalias(*C.sparse()) += prod(*A.sparse(), *B.sparse());\n          break;\n        default:\n          SiconosMatrixException::selfThrow(\"Matrix function prod(A,B,C): wrong type for C (according to A and B types).\");\n        }\n      }\n    }\n  if(!C.isBlock())\n    C.resetLU();\n  }\n}\n\n\nvoid axpy_prod(const SiconosMatrix& A, const SiconosMatrix& B, SiconosMatrix& C, bool init)\n{\n  // To compute C = A * B (init = true) or C += A * B (init = false) using ublas axpy_prod.\n  if ((A.size(1) != B.size(0)))\n    SiconosMatrixException::selfThrow(\"Matrix function prod(A,B,C): inconsistent sizes\");\n\n  if (A.size(0) != C.size(0) || B.size(1) != C.size(1))\n    SiconosMatrixException::selfThrow(\"Matrix function prod(A,B,C): inconsistent sizes\");\n\n  assert(!(A.isPLUFactorized()) && \"A is PLUFactorized in prod !!\" );\n  assert(!(B.isPLUFactorized()) && \"B is PLUFactorized in prod !!\" );\n  if(!C.isBlock())\n    C.resetLU();\n  unsigned int numA = A.num();\n  unsigned int numB = B.num();\n  unsigned int numC = C.num();\n  // == TODO: implement block product ==\n  if (numA == 0 || numB == 0)\n    SiconosMatrixException::selfThrow(\"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 == 6 || numC == 7)\n    SiconosMatrixException::selfThrow(\"Matrix product ( prod(A,B,C) ): wrong type for resulting matrix C (read-only: zero or identity).\");\n\n\n  if (numA == 7) // A = identity ...\n  {\n    if (!init) C += B;\n    else\n    {\n      if (&C != &B)\n        C = B; // if C and B are two different objects.\n      // else nothing\n    }\n  }\n\n  else if (numB == 7) // B = identity\n  {\n    if (!init) C += A;\n    else\n    {\n      if (&C != &A) C = A; // if C and A are two different objects.\n      // else nothing\n    }\n  }\n\n  else if (numA == 6 || numB == 6) // if A or B = 0\n  {\n    if (init) C.zero(); // else nothing\n  }\n  else if (numC == 0) // 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    if (&C == &A) // if common memory between A and C\n    {\n      switch (numA)\n      {\n      case 1:\n        if (numB == 1)\n          ublas::axpy_prod(*A.dense(), *B.dense(), *A.dense(), init);\n        else if (numB == 2)\n          ublas::axpy_prod(*A.dense(), *B.triang(), *A.dense(), init);\n        else if (numB == 3)\n          ublas::axpy_prod(*A.dense(), *B.sym(), *A.dense(), init);\n        else if (numB == 4)\n          ublas::axpy_prod(*A.dense(), *B.sparse(), *A.dense(), init);\n        else //if(numB==5)\n          ublas::axpy_prod(*A.dense(), *B.banded(), *A.dense(), init);\n        break;\n      case 2:\n        //        if(numB != 2)\n        SiconosMatrixException::selfThrow(\"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(), *A.triang(), init);\n        break;\n      case 3:\n        //if(numB != 3)\n        SiconosMatrixException::selfThrow(\"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(), *A.sym(), init);\n        break;\n      case 4:\n        //        if(numB != 4)\n        SiconosMatrixException::selfThrow(\"Matrix function axpy_prod(A,B,C): wrong type for C (according to A and B types).\");\n        //ublas::axpy_prod(*A.sparse(), *B.sparse(), *A.sparse(),init);\n        break;\n      default:\n        SiconosMatrixException::selfThrow(\"Matrix function axpy_prod(A,B,C): wrong type for C (according to A and B types).\");\n      }\n    }\n    else if (&C == &B)\n    {\n      switch (numB)\n      {\n      case 1:\n        if (numA == 1)\n          ublas::axpy_prod(*A.dense(), *B.dense(), *B.dense(), init);\n        else if (numA == 2)\n          ublas::axpy_prod(*A.triang(), *B.dense(), *B.dense(), init);\n        else if (numA == 3)\n          ublas::axpy_prod(*A.sym(), *B.dense(), *B.dense(), init);\n        else if (numA == 4)\n          ublas::axpy_prod(*A.sparse(), *B.dense(), *B.dense(), init);\n        else //if(numB==5)\n          ublas::axpy_prod(*A.banded(), *B.dense(), *B.dense(), init);\n        break;\n      case 2:\n        //if(numA != 2)\n        SiconosMatrixException::selfThrow(\"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(),*B.triang(), init);\n        break;\n      case 3:\n        //        if(numA != 3)\n        SiconosMatrixException::selfThrow(\"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(), *B.sym(), init);\n        break;\n      case 4:\n        //        if(numA != 4)\n        SiconosMatrixException::selfThrow(\"Matrix function axpy_prod(A,B,C): wrong type for C (according to A and B types).\");\n        //ublas::axpy_prod(*A.sparse(), *B.sparse(), *B.sparse(), init);\n        break;\n      default:\n        SiconosMatrixException::selfThrow(\"Matrix function axpy_prod(A,B,C): wrong type for C (according to A and B types).\");\n      }\n    }\n    else // if no alias between C and A or B.\n    {\n      switch (numC)\n      {\n      case 1:\n        if (numB == 1)\n        {\n          if (numA == 1)\n            ublas::axpy_prod(*A.dense(), *B.dense(), *C.dense(), init);\n          else if (numA == 2)\n            ublas::axpy_prod(*A.triang(), *B.dense(), *C.dense(), init);\n          else if (numA == 3)\n            ublas::axpy_prod(*A.sym(), *B.dense(), *C.dense(), init);\n          else if (numA == 4)\n            ublas::axpy_prod(*A.sparse(), *B.dense(), *C.dense(), init);\n          else// if(numA==5)\n            ublas::axpy_prod(*A.banded(), *B.dense(), *C.dense(), init);\n        }\n        else if (numB == 2)\n        {\n          if (numA == 1)\n            ublas::axpy_prod(*A.dense(), *B.triang(), *C.dense(), init);\n          else if (numA == 2)\n            ublas::axpy_prod(*A.triang(), *B.triang(), *C.dense(), init);\n          else if (numA == 3)\n            ublas::axpy_prod(*A.sym(), *B.triang(), *C.dense(), init);\n          else if (numA == 4)\n            ublas::axpy_prod(*A.sparse(), *B.triang(), *C.dense(), init);\n          else //if(numA==5)\n            ublas::axpy_prod(*A.banded(), *B.triang(), *C.dense(), init);\n        }\n        else if (numB == 3)\n        {\n          if (numA == 1)\n            ublas::axpy_prod(*A.dense(), *B.sym(), *C.dense(), init);\n          else if (numA == 2)\n            ublas::axpy_prod(*A.triang(), *B.sym(), *C.dense(), init);\n          else if (numA == 3)\n            ublas::axpy_prod(*A.sym(), *B.sym(), *C.dense(), init);\n          else if (numA == 4)\n            ublas::axpy_prod(*A.sparse(), *B.sym(), *C.dense(), init);\n          else // if (numA == 5)\n            ublas::axpy_prod(*A.banded(), *B.sym(), *C.dense(), init);\n        }\n        else if (numB == 4)\n        {\n          if (numA == 1)\n            ublas::axpy_prod(*A.dense(), *B.sparse(), *C.dense(), init);\n          else if (numA == 2)\n            ublas::axpy_prod(*A.triang(), *B.sparse(), *C.dense(), init);\n          else if (numA == 3)\n            ublas::axpy_prod(*A.sym(), *B.sparse(), *C.dense(), init);\n          else if (numA == 4)\n            ublas::axpy_prod(*A.sparse(), *B.sparse(), *C.dense(), init);\n          else //if(numA==5){\n            ublas::axpy_prod(*A.banded(), *B.sparse(), *C.dense(), init);\n        }\n        else //if(numB==5)\n        {\n          if (numA == 1)\n            ublas::axpy_prod(*A.dense(), *B.banded(), *C.dense(), init);\n          else if (numA == 2)\n            ublas::axpy_prod(*A.triang(), *B.banded(), *C.dense(), init);\n          else if (numA == 3)\n            ublas::axpy_prod(*A.sym(), *B.banded(), *C.dense(), init);\n          else if (numA == 4)\n            ublas::axpy_prod(*A.sparse(), *B.banded(), *C.dense(), init);\n          else //if(numA==5)\n            ublas::axpy_prod(*A.banded(), *B.banded(), *C.dense(), init);\n        }\n        break;\n      case 2:\n        // if(numA!= 2 || numB != 2)\n        SiconosMatrixException::selfThrow(\"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 3:\n        //        if(numA!= 3 || numB != 3)\n        SiconosMatrixException::selfThrow(\"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 4:\n        if (numA != 4 || numB != 4)\n          SiconosMatrixException::selfThrow(\"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        SiconosMatrixException::selfThrow(\"Matrix function axpy_prod(A,B,C): wrong type for C (according to A and B types).\");\n      }\n    }\n  if(!C.isBlock())\n    C.resetLU();\n  }\n}\n\nvoid gemmtranspose(double a, const SiconosMatrix& A, const SiconosMatrix& B, double b, SiconosMatrix& C)\n{\n  if (A.isBlock() || B.isBlock() || C.isBlock())\n    SiconosMatrixException::selfThrow(\"gemm(...) not yet implemented for block matrices.\");\n  unsigned int numA = A.num();\n  unsigned int numB = B.num();\n  unsigned int numC = C.num();\n  if (numA != 1 || numB != 1 || numC != 1)\n    SiconosMatrixException::selfThrow(\"gemm(...) failed: reserved to dense matrices.\");\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\n  C.resetLU();\n}\n\nvoid gemm(double a, const SiconosMatrix& A, const SiconosMatrix& B, double b, SiconosMatrix& C)\n{\n  unsigned int numA = A.num();\n  unsigned int numB = B.num();\n  unsigned int numC = C.num();\n  assert(!(B.isPLUFactorized()) && \"B is PLUFactorized in prod !!\");\n  assert(!(A.isPLUFactorized()) && \"A is PLUFactorized in prod !!\");\n  C.resetLU();\n\n  // At the time, only dense output allowed \n  DenseMat * tmpC = NULL;\n  if (numA == 0 || numB == 0 || numC == 0)\n    SiconosMatrixException::selfThrow(\"gemm(...) not yet implemented for block matrices.\");\n\n  if (numA == 1 && numB == 1 && numC == 1)\n    siconosBindings::blas::gemm(a, *A.dense(), *B.dense(), b, *C.dense());\n  else if (numA == 1 && numB == 1 && numC != 1)\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    SiconosMatrixException::selfThrow(\"gemm(...) not yet implemented for these kinds of matrices.\");\n  C.resetLU();\n}\n\nvoid scal(double a, const SiconosMatrix& A, SiconosMatrix& B, bool init)\n{\n  // To compute B = a * A (init = true) or B += a*A (init = false).\n  assert(!(A.isPLUFactorized()) && \"A is PLUFactorized in prod !!\" );\n  if(!B.isBlock())\n    B.resetLU();\n\n  if (&A == &B)\n  {\n    if (init) B *= a;\n    else B *= (1.0 + a);\n  }\n  else\n  {\n    unsigned int numA = A.num();\n    unsigned int numB = B.num();\n\n    if (numB == 6 || numB == 7) // B = 0 or identity.\n      SiconosMatrixException::selfThrow(\"scal(a,A,B) : forbidden for B being a zero or identity matrix.\");\n\n    if (numA == 6)\n    {\n      if (init) B.zero(); // else nothing\n    }\n    else if (numA == 7)\n    {\n      if (init)\n      {\n        B.eye();\n        B *= a;\n      }\n      else\n      {\n        // Assuming B is square ...\n        for (unsigned int i = 0; i < B.size(0); ++i)\n          B(i, i) += a;\n      }\n    }\n    else\n    {\n      if (numA == numB) // if A and B are of the same type ...\n      {\n        switch (numA)\n        {\n\n        case 0: // A and B are block\n          if (isComparableTo(A, B))\n          {\n            const BlockMatrix& Aref = static_cast<const BlockMatrix&>(A);\n            BlockMatrix& Bref = static_cast<BlockMatrix&>(B);\n            BlocksIterator1 itB1;\n            BlocksIterator2 itB2;\n            ConstBlocksIterator1 itA1 = Aref._mat->begin1();\n            ConstBlocksIterator2 itA2;\n            for (itB1 = Bref._mat->begin1(); itB1 != Bref._mat->end1(); ++itB1)\n            {\n              itA2 = itA1.begin();\n              for (itB2 = itB1.begin(); itB2 != itB1.end(); ++itB2)\n              {\n                scal(a, **itA2++, **itB2, init);\n              }\n              itA1++;\n            }\n          }\n          else // if A and B are not \"block-consistent\"\n          {\n            if (init)\n            {\n              for (unsigned int i = 0; i < A.size(0); ++i)\n                for (unsigned int j = 0; j < A.size(1); ++j)\n                  B(i, j) = a * A(i, j);\n            }\n            else\n            {\n              for (unsigned int i = 0; i < A.size(0); ++i)\n                for (unsigned int j = 0; j < A.size(1); ++j)\n                  B(i, j) += a * A(i, j);\n            }\n          }\n          break;\n\n        case 1: // if both are dense\n          if (init)\n            noalias(*B.dense()) = a ** A.dense();\n          else\n            noalias(*B.dense()) += a ** A.dense();\n          break;\n        case 2:\n          if (init)\n            noalias(*B.triang()) = a ** A.triang();\n          else\n            noalias(*B.triang()) += a ** A.triang();\n          break;\n        case 3:\n          if (init)\n            noalias(*B.sym()) = a ** A.sym();\n          else\n            noalias(*B.sym()) += a ** A.sym();\n          break;\n        case 4:\n          if (init)\n            noalias(*B.sparse()) = a ** A.sparse();\n          else\n            noalias(*B.sparse()) += a ** A.sparse();\n          break;\n        case 5:\n          if (init)\n            noalias(*B.banded()) = a ** A.banded();\n          else\n            noalias(*B.banded()) += a ** A.banded();\n          break;\n        }\n      }\n      else // if A and B are of different types.\n      {\n        if (numA == 0 || numB == 0) // if A or B is block\n        {\n          if (init)\n          {\n            B = A;\n            B *= a;\n          }\n          else\n          {\n            SimpleMatrix tmp(A);\n            tmp *= a;\n            B += tmp; // bof bof ...\n          }\n        }\n        else\n        {\n          if (numB != 1)\n            SiconosMatrixException::selfThrow(\"scal(a,A,B) failed. A and B types do not fit together.\");\n\n          if (init)\n          {\n            switch (numB)\n            {\n            case 1:\n              noalias(*B.dense()) = a ** A.dense();\n              break;\n            case 2:\n              noalias(*B.dense()) = a ** A.triang();\n              break;\n            case 3:\n              noalias(*B.dense()) = a ** A.sym();\n              break;\n            case 4:\n              noalias(*B.dense()) = a ** A.sparse();\n              break;\n            case 5:\n              noalias(*B.dense()) = a ** A.banded();\n              break;\n            }\n          }\n          else\n\n          {\n            switch (numB)\n            {\n            case 1:\n              noalias(*B.dense()) += a ** A.dense();\n              break;\n            case 2:\n              noalias(*B.dense()) += a ** A.triang();\n              break;\n            case 3:\n              noalias(*B.dense()) += a ** A.sym();\n              break;\n            case 4:\n              noalias(*B.dense()) += a ** A.sparse();\n              break;\n            case 5:\n              noalias(*B.dense()) += a ** A.banded();\n              break;\n            }\n          }\n        }\n      }\n    }\n  }\n}\n\n\n", "meta": {"hexsha": "107b78c6a4324708e9e0a9a1ce446732ca3a9c08", "size": 36623, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "kernel/src/utils/SiconosAlgebra/SimpleMatrixBLAS3.cpp", "max_stars_repo_name": "siconos/siconos-deb", "max_stars_repo_head_hexsha": "2739a23f23d797dbfecec79d409e914e13c45c67", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "kernel/src/utils/SiconosAlgebra/SimpleMatrixBLAS3.cpp", "max_issues_repo_name": "siconos/siconos-deb", "max_issues_repo_head_hexsha": "2739a23f23d797dbfecec79d409e914e13c45c67", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "kernel/src/utils/SiconosAlgebra/SimpleMatrixBLAS3.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": 35.1805955812, "max_line_length": 147, "alphanum_fraction": 0.4918766895, "num_tokens": 10558, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6548947290421276, "lm_q2_score": 0.480478678047907, "lm_q1q2_score": 0.31466295367070374}}
{"text": "#include <boost/format.hpp>\n#include <iostream>\n#include <cmath>\n\nstruct show_resolution_save\n{\n  bool first;\n  float ass, bss, css;\n  show_resolution_save() : first(true) {}\n};\n\nstruct common\n{\n  float a, b, c;\n  show_resolution_save show_resolution_sve;\n  std::ostream & out_stream;\n  common(std::ostream& out_stream_) : out_stream(out_stream_) {}\n};\n\nvoid\nshow_resolution(common& cmn, int h, int k, int l)\n{\n  show_resolution_save& sve = cmn.show_resolution_sve;\n  if (sve.first) {\n    sve.first = false;\n    if (cmn.a <= 0 || cmn.b <= 0 || cmn.c <= 0) {\n      throw std::runtime_error(\n        \"invalid unit cell constants.\");\n    }\n    sve.ass = 1/(cmn.a*cmn.a);\n    sve.bss = 1/(cmn.b*cmn.b);\n    sve.css = 1/(cmn.c*cmn.c);\n  }\n  float dss = h*h*sve.ass + k*k*sve.bss + l*l*sve.css;\n  std::ostream& cout = cmn.out_stream;\n  if (dss == 0) {\n    cout << boost::format(\" %3d %3d %3d     infinity\\n\")\n      % h % k % l;\n  }\n  else {\n    cout << boost::format(\" %3d %3d %3d %12.6f\\n\")\n      % h % k % l % std::sqrt(1/dss);\n  }\n}\n\nvoid\nconv_recipe(common& cmn)\n{\n  cmn.a = 11.0;\n  cmn.b = 12.0;\n  cmn.c = 13.0;\n  show_resolution(cmn, 0, 0, 0);\n  show_resolution(cmn, 1, 2, 3);\n}\n\nint\nmain()\n{\n  common cmn(std::cout);\n  conv_recipe(cmn);\n  return 0;\n}\n", "meta": {"hexsha": "b98cf9e6c165337c2b4e9334bcd76269ccfbbc58", "size": 1252, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "dox/compcomm/newsletter09/conv_recipe.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": "dox/compcomm/newsletter09/conv_recipe.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": "dox/compcomm/newsletter09/conv_recipe.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": 19.873015873, "max_line_length": 64, "alphanum_fraction": 0.5918530351, "num_tokens": 445, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6548947290421275, "lm_q2_score": 0.480478678047907, "lm_q1q2_score": 0.3146629536707037}}
{"text": "#ifndef STAN_MATH_PRIM_MAT_PROB_BERNOULLI_LOGIT_GLM_LPMF_HPP\n#define STAN_MATH_PRIM_MAT_PROB_BERNOULLI_LOGIT_GLM_LPMF_HPP\n\n#include <stan/math/prim/scal/meta/is_constant_struct.hpp>\n#include <stan/math/prim/scal/meta/partials_return_type.hpp>\n#include <stan/math/prim/scal/meta/broadcast_array.hpp>\n#include <stan/math/prim/scal/meta/operands_and_partials.hpp>\n#include <stan/math/prim/scal/err/check_consistent_sizes.hpp>\n#include <stan/math/prim/scal/err/check_consistent_size.hpp>\n#include <stan/math/prim/scal/err/check_bounded.hpp>\n#include <stan/math/prim/scal/err/check_finite.hpp>\n#include <stan/math/prim/scal/fun/constants.hpp>\n#include <stan/math/prim/mat/fun/value_of.hpp>\n#include <stan/math/prim/scal/meta/include_summand.hpp>\n#include <stan/math/prim/mat/meta/is_vector.hpp>\n#include <stan/math/prim/scal/meta/scalar_seq_view.hpp>\n#include <stan/math/prim/scal/fun/size_zero.hpp>\n#include <boost/random/variate_generator.hpp>\n#include <cmath>\n\nnamespace stan {\nnamespace math {\n\n/**\n * Returns the log PMF of the Generalized Linear Model (GLM)\n * with Bernoulli distribution and logit link function.\n * The idea is that bernoulli_logit_glm_lpmf(y, x, alpha, beta) should\n * compute a more efficient version of bernoulli_logit_lpmf(y, alpha + x * beta)\n * by using analytically simplified gradients.\n * If containers are supplied, returns the log sum of the probabilities.\n * @tparam T_y type of binary vector of dependent variables (labels);\n * this can also be a single binary value;\n * @tparam T_x type of the matrix of independent variables (features); this\n * should be an Eigen::Matrix type whose number of rows should match the\n * length of y and whose number of columns should match the length of beta\n * @tparam T_alpha type of the intercept(s);\n * this can be a vector (of the same length as y) of intercepts or a single\n * value (for models with constant intercept);\n * @tparam T_beta type of the weight vector;\n * this can also be a single value;\n * @param y binary vector parameter\n * @param x design matrix\n * @param alpha intercept (in log odds)\n * @param beta weight vector\n * @return log probability or log sum of probabilities\n * @throw std::domain_error if x, beta or alpha is infinite.\n * @throw std::domain_error if y is not binary.\n * @throw std::invalid_argument if container sizes mismatch.\n */\n\ntemplate <bool propto, typename T_y, typename T_x, typename T_alpha,\n          typename T_beta>\ntypename return_type<T_x, T_alpha, T_beta>::type bernoulli_logit_glm_lpmf(\n    const T_y &y, const T_x &x, const T_alpha &alpha, const T_beta &beta) {\n  static const char *function = \"bernoulli_logit_glm_lpmf\";\n  typedef typename stan::partials_return_type<T_y, T_x, T_alpha, T_beta>::type\n      T_partials_return;\n\n  using Eigen::Dynamic;\n  using Eigen::Matrix;\n  using std::exp;\n\n  if (size_zero(y, x, beta))\n    return 0.0;\n\n  T_partials_return logp(0.0);\n\n  const size_t N = x.col(0).size();\n  const size_t M = x.row(0).size();\n\n  check_bounded(function, \"Vector of dependent variables\", y, 0, 1);\n  check_finite(function, \"Matrix of independent variables\", x);\n  check_finite(function, \"Weight vector\", beta);\n  check_finite(function, \"Intercept\", alpha);\n  check_consistent_size(function, \"Vector of dependent variables\", y, N);\n  check_consistent_size(function, \"Weight vector\", beta, M);\n  if (is_vector<T_alpha>::value)\n    check_consistent_sizes(function, \"Vector of intercepts\", alpha,\n                           \"Vector of dependent variables\", y);\n\n  if (!include_summand<propto, T_x, T_alpha, T_beta>::value)\n    return 0.0;\n\n  Matrix<T_partials_return, Dynamic, 1> signs(N, 1);\n  {\n    scalar_seq_view<T_y> y_vec(y);\n    for (size_t n = 0; n < N; ++n) {\n      signs[n] = 2 * y_vec[n] - 1;\n    }\n  }\n  Matrix<T_partials_return, Dynamic, 1> beta_dbl(M, 1);\n  {\n    scalar_seq_view<T_beta> beta_vec(beta);\n    for (size_t m = 0; m < M; ++m) {\n      beta_dbl[m] = value_of(beta_vec[m]);\n    }\n  }\n  Eigen::Array<T_partials_return, Dynamic, 1> ytheta\n      = signs.array() * (value_of(x) * beta_dbl).array();\n  scalar_seq_view<T_alpha> alpha_vec(alpha);\n\n  // Compute the log-density and handle extreme values gracefully\n  // using Taylor approximations.\n  // And compute the derivatives wrt theta.\n  static const double cutoff = 20.0;\n  Matrix<T_partials_return, Dynamic, 1> theta_derivative(N, 1);\n  T_partials_return theta_derivative_sum = 0;\n  T_partials_return exp_m_ythetan;\n  for (size_t n = 0; n < N; ++n) {\n    ytheta[n] += signs[n] * value_of(alpha_vec[n]);\n    exp_m_ythetan = exp(-ytheta[n]);\n    if (ytheta[n] > cutoff) {\n      logp -= exp_m_ythetan;\n      theta_derivative[n] = -exp_m_ythetan;\n    } else if (ytheta[n] < -cutoff) {\n      logp += ytheta[n];\n      theta_derivative[n] = signs[n];\n    } else {\n      logp -= log1p(exp_m_ythetan);\n      theta_derivative[n] = signs[n] * exp_m_ythetan / (exp_m_ythetan + 1);\n    }\n    if (!is_vector<T_alpha>::value)\n      theta_derivative_sum += theta_derivative[n];\n  }\n\n  // Compute the necessary derivatives.\n  operands_and_partials<T_x, T_alpha, T_beta> ops_partials(x, alpha, beta);\n  if (!is_constant_struct<T_beta>::value) {\n    ops_partials.edge3_.partials_ = value_of(x).transpose() * theta_derivative;\n  }\n  if (!is_constant_struct<T_x>::value) {\n    ops_partials.edge1_.partials_ = theta_derivative * beta_dbl.transpose();\n  }\n  if (!is_constant_struct<T_alpha>::value) {\n    if (is_vector<T_alpha>::value)\n      ops_partials.edge2_.partials_ = theta_derivative;\n    else\n      ops_partials.edge2_.partials_[0] = theta_derivative_sum;\n  }\n\n  return ops_partials.build(logp);\n}\n\ntemplate <typename T_y, typename T_x, typename T_alpha, typename T_beta>\ninline typename return_type<T_x, T_beta, T_alpha>::type\nbernoulli_logit_glm_lpmf(const T_y &y, const T_x &x, const T_alpha &alpha,\n                         const T_beta &beta) {\n  return bernoulli_logit_glm_lpmf<false>(y, x, alpha, beta);\n}\n}  // namespace math\n}  // namespace stan\n#endif\n", "meta": {"hexsha": "f55fcc957ce1df41cf4c06a6312f031e9e1b0799", "size": 5952, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "stan/math/prim/mat/prob/bernoulli_logit_glm_lpmf.hpp", "max_stars_repo_name": "jrmie/math", "max_stars_repo_head_hexsha": "2850ec262181075a5843968e805dc9ad1654e069", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "stan/math/prim/mat/prob/bernoulli_logit_glm_lpmf.hpp", "max_issues_repo_name": "jrmie/math", "max_issues_repo_head_hexsha": "2850ec262181075a5843968e805dc9ad1654e069", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "stan/math/prim/mat/prob/bernoulli_logit_glm_lpmf.hpp", "max_forks_repo_name": "jrmie/math", "max_forks_repo_head_hexsha": "2850ec262181075a5843968e805dc9ad1654e069", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.9019607843, "max_line_length": 80, "alphanum_fraction": 0.7163978495, "num_tokens": 1654, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7185943925708561, "lm_q2_score": 0.4378234991142019, "lm_q1q2_score": 0.3146175113992167}}
{"text": "//  ratio.hpp  ---------------------------------------------------------------//\r\n\r\n//  Copyright 2008 Howard Hinnant\r\n//  Copyright 2008 Beman Dawes\r\n//  Copyright 2009 Vicente J. Botet Escriba\r\n\r\n//  Distributed under the Boost Software License, Version 1.0.\r\n//  See http://www.boost.org/LICENSE_1_0.txt\r\n\r\n/*\r\n\r\nThis code was derived by Beman Dawes from Howard Hinnant's time2_demo prototype.\r\nMany thanks to Howard for making his code available under the Boost license.\r\nThe original code was modified to conform to Boost conventions and to section\r\n20.4 Compile-time rational arithmetic [ratio], of the C++ committee working\r\npaper N2798.\r\nSee http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2008/n2798.pdf.\r\n\r\ntime2_demo contained this comment:\r\n\r\n    Much thanks to Andrei Alexandrescu,\r\n                   Walter Brown,\r\n                   Peter Dimov,\r\n                   Jeff Garland,\r\n                   Terry Golubiewski,\r\n                   Daniel Krugler,\r\n                   Anthony Williams.\r\n*/\r\n\r\n// The way overflow is managed for ratio_less is taken from llvm/libcxx/include/ratio\r\n\r\n#ifndef BOOST_RATIO_DETAIL_RATIO_OPERATIONS_HPP\r\n#define BOOST_RATIO_DETAIL_RATIO_OPERATIONS_HPP\r\n\r\n#include <boost/ratio/config.hpp>\r\n#include <boost/ratio/detail/mpl/abs.hpp>\r\n#include <boost/ratio/detail/mpl/sign.hpp>\r\n#include <cstdlib>\r\n#include <climits>\r\n#include <limits>\r\n#include <boost/cstdint.hpp>\r\n#include <boost/type_traits/integral_constant.hpp>\r\n#include <boost/core/enable_if.hpp>\r\n#include <boost/integer_traits.hpp>\r\n\r\n//\r\n// We simply cannot include this header on gcc without getting copious warnings of the kind:\r\n//\r\n// boost/integer.hpp:77:30: warning: use of C99 long long integer constant\r\n//\r\n// And yet there is no other reasonable implementation, so we declare this a system header\r\n// to suppress these warnings.\r\n//\r\n#if defined(__GNUC__) && (__GNUC__ >= 4)\r\n#pragma GCC system_header\r\n#endif\r\n\r\nnamespace mars_boost {} namespace boost = mars_boost; namespace mars_boost\r\n{\r\n\r\n//----------------------------------------------------------------------------//\r\n//                                 helpers                                    //\r\n//----------------------------------------------------------------------------//\r\n\r\nnamespace ratio_detail\r\n{\r\n\r\n  template <mars_boost::intmax_t X, mars_boost::intmax_t Y, mars_boost::intmax_t = mpl::sign_c<mars_boost::intmax_t, Y>::value>\r\n  class br_add;\r\n\r\n  template <mars_boost::intmax_t X, mars_boost::intmax_t Y>\r\n  class br_add<X, Y, 1>\r\n  {\r\n      static const mars_boost::intmax_t min = mars_boost::integer_traits<mars_boost::intmax_t>::const_min;\r\n      static const mars_boost::intmax_t max = mars_boost::integer_traits<mars_boost::intmax_t>::const_max;\r\n\r\n      BOOST_RATIO_STATIC_ASSERT(X <= max - Y , BOOST_RATIO_OVERFLOW_IN_ADD, ());\r\n  public:\r\n      static const mars_boost::intmax_t value = X + Y;\r\n  };\r\n\r\n  template <mars_boost::intmax_t X, mars_boost::intmax_t Y>\r\n  class br_add<X, Y, 0>\r\n  {\r\n  public:\r\n      static const mars_boost::intmax_t value = X;\r\n  };\r\n\r\n  template <mars_boost::intmax_t X, mars_boost::intmax_t Y>\r\n  class br_add<X, Y, -1>\r\n  {\r\n      static const mars_boost::intmax_t min = mars_boost::integer_traits<mars_boost::intmax_t>::const_min;\r\n      static const mars_boost::intmax_t max = mars_boost::integer_traits<mars_boost::intmax_t>::const_max;\r\n\r\n      BOOST_RATIO_STATIC_ASSERT(min - Y <= X, BOOST_RATIO_OVERFLOW_IN_ADD, ());\r\n  public:\r\n      static const mars_boost::intmax_t value = X + Y;\r\n  };\r\n\r\n  template <mars_boost::intmax_t X, mars_boost::intmax_t Y, mars_boost::intmax_t = mpl::sign_c<mars_boost::intmax_t, Y>::value>\r\n  class br_sub;\r\n\r\n  template <mars_boost::intmax_t X, mars_boost::intmax_t Y>\r\n  class br_sub<X, Y, 1>\r\n  {\r\n      static const mars_boost::intmax_t min = mars_boost::integer_traits<mars_boost::intmax_t>::const_min;\r\n      static const mars_boost::intmax_t max = mars_boost::integer_traits<mars_boost::intmax_t>::const_max;\r\n\r\n      BOOST_RATIO_STATIC_ASSERT(min + Y <= X, BOOST_RATIO_OVERFLOW_IN_SUB, ());\r\n  public:\r\n      static const mars_boost::intmax_t value = X - Y;\r\n  };\r\n\r\n  template <mars_boost::intmax_t X, mars_boost::intmax_t Y>\r\n  class br_sub<X, Y, 0>\r\n  {\r\n  public:\r\n      static const mars_boost::intmax_t value = X;\r\n  };\r\n\r\n  template <mars_boost::intmax_t X, mars_boost::intmax_t Y>\r\n  class br_sub<X, Y, -1>\r\n  {\r\n      static const mars_boost::intmax_t min = mars_boost::integer_traits<mars_boost::intmax_t>::const_min;\r\n      static const mars_boost::intmax_t max = mars_boost::integer_traits<mars_boost::intmax_t>::const_max;\r\n\r\n      BOOST_RATIO_STATIC_ASSERT(X <= max + Y, BOOST_RATIO_OVERFLOW_IN_SUB, ());\r\n  public:\r\n      static const mars_boost::intmax_t value = X - Y;\r\n  };\r\n\r\n  template <mars_boost::intmax_t X, mars_boost::intmax_t Y>\r\n  class br_mul\r\n  {\r\n      static const mars_boost::intmax_t nan =\r\n          mars_boost::intmax_t(BOOST_RATIO_UINTMAX_C(1) << (sizeof(mars_boost::intmax_t) * CHAR_BIT - 1));\r\n      static const mars_boost::intmax_t min = mars_boost::integer_traits<mars_boost::intmax_t>::const_min;\r\n      static const mars_boost::intmax_t max = mars_boost::integer_traits<mars_boost::intmax_t>::const_max;\r\n\r\n      static const mars_boost::intmax_t a_x = mpl::abs_c<mars_boost::intmax_t, X>::value;\r\n      static const mars_boost::intmax_t a_y = mpl::abs_c<mars_boost::intmax_t, Y>::value;\r\n\r\n      BOOST_RATIO_STATIC_ASSERT(X != nan, BOOST_RATIO_OVERFLOW_IN_MUL, ());\r\n      BOOST_RATIO_STATIC_ASSERT(Y != nan, BOOST_RATIO_OVERFLOW_IN_MUL, ());\r\n      BOOST_RATIO_STATIC_ASSERT(a_x <= max / a_y, BOOST_RATIO_OVERFLOW_IN_MUL, ());\r\n  public:\r\n      static const mars_boost::intmax_t value = X * Y;\r\n  };\r\n\r\n  template <mars_boost::intmax_t Y>\r\n  class br_mul<0, Y>\r\n  {\r\n  public:\r\n      static const mars_boost::intmax_t value = 0;\r\n  };\r\n\r\n  template <mars_boost::intmax_t X>\r\n  class br_mul<X, 0>\r\n  {\r\n  public:\r\n      static const mars_boost::intmax_t value = 0;\r\n  };\r\n\r\n  template <>\r\n  class br_mul<0, 0>\r\n  {\r\n  public:\r\n      static const mars_boost::intmax_t value = 0;\r\n  };\r\n\r\n  // Not actually used but left here in case needed in future maintenance\r\n  template <mars_boost::intmax_t X, mars_boost::intmax_t Y>\r\n  class br_div\r\n  {\r\n      static const mars_boost::intmax_t nan = mars_boost::intmax_t(BOOST_RATIO_UINTMAX_C(1) << (sizeof(mars_boost::intmax_t) * CHAR_BIT - 1));\r\n      static const mars_boost::intmax_t min = mars_boost::integer_traits<mars_boost::intmax_t>::const_min;\r\n      static const mars_boost::intmax_t max = mars_boost::integer_traits<mars_boost::intmax_t>::const_max;\r\n\r\n      BOOST_RATIO_STATIC_ASSERT(X != nan, BOOST_RATIO_OVERFLOW_IN_DIV, ());\r\n      BOOST_RATIO_STATIC_ASSERT(Y != nan, BOOST_RATIO_OVERFLOW_IN_DIV, ());\r\n      BOOST_RATIO_STATIC_ASSERT(Y != 0, BOOST_RATIO_DIVIDE_BY_0, ());\r\n  public:\r\n      static const mars_boost::intmax_t value = X / Y;\r\n  };\r\n\r\n  // ratio arithmetic\r\n  template <class R1, class R2> struct ratio_add;\r\n  template <class R1, class R2> struct ratio_subtract;\r\n  template <class R1, class R2> struct ratio_multiply;\r\n  template <class R1, class R2> struct ratio_divide;\r\n\r\n  template <class R1, class R2>\r\n  struct ratio_add\r\n  {\r\n      //The nested typedef type shall be a synonym for ratio<T1, T2>::type where T1 has the value R1::num *\r\n      //R2::den + R2::num * R1::den and T2 has the value R1::den * R2::den.\r\n      // As the preceding doesn't works because of overflow on mars_boost::intmax_t we need something more elaborated.\r\n  private:\r\n      static const mars_boost::intmax_t gcd_n1_n2 = mpl::gcd_c<mars_boost::intmax_t, R1::num, R2::num>::value;\r\n      static const mars_boost::intmax_t gcd_d1_d2 = mpl::gcd_c<mars_boost::intmax_t, R1::den, R2::den>::value;\r\n  public:\r\n      // No need to normalize as ratio_multiply is already normalized\r\n      typedef typename ratio_multiply\r\n         <\r\n             ratio<gcd_n1_n2, R1::den / gcd_d1_d2>,\r\n             ratio\r\n             <\r\n                 mars_boost::ratio_detail::br_add\r\n                 <\r\n                     mars_boost::ratio_detail::br_mul<R1::num / gcd_n1_n2, R2::den / gcd_d1_d2>::value,\r\n                     mars_boost::ratio_detail::br_mul<R2::num / gcd_n1_n2, R1::den / gcd_d1_d2>::value\r\n                 >::value,\r\n                 R2::den\r\n             >\r\n         >::type type;\r\n  };\r\n  template <class R, mars_boost::intmax_t D>\r\n  struct ratio_add<R, ratio<0,D> >\r\n  {\r\n    typedef R type;\r\n  };\r\n\r\n  template <class R1, class R2>\r\n  struct ratio_subtract\r\n  {\r\n      //The nested typedef type shall be a synonym for ratio<T1, T2>::type where T1 has the value\r\n      // R1::num *R2::den - R2::num * R1::den and T2 has the value R1::den * R2::den.\r\n      // As the preceding doesn't works because of overflow on mars_boost::intmax_t we need something more elaborated.\r\n  private:\r\n      static const mars_boost::intmax_t gcd_n1_n2 = mpl::gcd_c<mars_boost::intmax_t, R1::num, R2::num>::value;\r\n      static const mars_boost::intmax_t gcd_d1_d2 = mpl::gcd_c<mars_boost::intmax_t, R1::den, R2::den>::value;\r\n  public:\r\n      // No need to normalize as ratio_multiply is already normalized\r\n      typedef typename ratio_multiply\r\n         <\r\n             ratio<gcd_n1_n2, R1::den / gcd_d1_d2>,\r\n             ratio\r\n             <\r\n                 mars_boost::ratio_detail::br_sub\r\n                 <\r\n                     mars_boost::ratio_detail::br_mul<R1::num / gcd_n1_n2, R2::den / gcd_d1_d2>::value,\r\n                     mars_boost::ratio_detail::br_mul<R2::num / gcd_n1_n2, R1::den / gcd_d1_d2>::value\r\n                 >::value,\r\n                 R2::den\r\n             >\r\n         >::type type;\r\n  };\r\n\r\n  template <class R, mars_boost::intmax_t D>\r\n  struct ratio_subtract<R, ratio<0,D> >\r\n  {\r\n    typedef R type;\r\n  };\r\n\r\n  template <class R1, class R2>\r\n  struct ratio_multiply\r\n  {\r\n      // The nested typedef type  shall be a synonym for ratio<R1::num * R2::den - R2::num * R1::den, R1::den * R2::den>::type.\r\n      // As the preceding doesn't works because of overflow on mars_boost::intmax_t we need something more elaborated.\r\n  private:\r\n     static const mars_boost::intmax_t gcd_n1_d2 = mpl::gcd_c<mars_boost::intmax_t, R1::num, R2::den>::value;\r\n     static const mars_boost::intmax_t gcd_d1_n2 = mpl::gcd_c<mars_boost::intmax_t, R1::den, R2::num>::value;\r\n  public:\r\n      typedef typename ratio\r\n         <\r\n             mars_boost::ratio_detail::br_mul<R1::num / gcd_n1_d2, R2::num / gcd_d1_n2>::value,\r\n             mars_boost::ratio_detail::br_mul<R2::den / gcd_n1_d2, R1::den / gcd_d1_n2>::value\r\n         >::type type;\r\n  };\r\n\r\n  template <class R1, class R2>\r\n  struct ratio_divide\r\n  {\r\n      // The nested typedef type  shall be a synonym for ratio<R1::num * R2::den, R2::num * R1::den>::type.\r\n      // As the preceding doesn't works because of overflow on mars_boost::intmax_t we need something more elaborated.\r\n  private:\r\n      static const mars_boost::intmax_t gcd_n1_n2 = mpl::gcd_c<mars_boost::intmax_t, R1::num, R2::num>::value;\r\n      static const mars_boost::intmax_t gcd_d1_d2 = mpl::gcd_c<mars_boost::intmax_t, R1::den, R2::den>::value;\r\n  public:\r\n      typedef typename ratio\r\n         <\r\n             mars_boost::ratio_detail::br_mul<R1::num / gcd_n1_n2, R2::den / gcd_d1_d2>::value,\r\n             mars_boost::ratio_detail::br_mul<R2::num / gcd_n1_n2, R1::den / gcd_d1_d2>::value\r\n         >::type type;\r\n  };\r\n  template <class R1, class R2>\r\n  struct is_evenly_divisible_by\r\n  {\r\n  private:\r\n      static const mars_boost::intmax_t gcd_n1_n2 = mpl::gcd_c<mars_boost::intmax_t, R1::num, R2::num>::value;\r\n      static const mars_boost::intmax_t gcd_d1_d2 = mpl::gcd_c<mars_boost::intmax_t, R1::den, R2::den>::value;\r\n  public:\r\n      typedef integral_constant<bool,\r\n             ((R2::num / gcd_n1_n2 ==1) && (R1::den / gcd_d1_d2)==1)\r\n      > type;\r\n  };\r\n\r\n  template <class T>\r\n  struct is_ratio : public mars_boost::false_type\r\n  {};\r\n  template <mars_boost::intmax_t N, mars_boost::intmax_t D>\r\n  struct is_ratio<ratio<N, D> > : public mars_boost::true_type\r\n  {};\r\n\r\n  template <class R1, class R2,\r\n            mars_boost::intmax_t Q1 = R1::num / R1::den, mars_boost::intmax_t M1 = R1::num % R1::den,\r\n            mars_boost::intmax_t Q2 = R2::num / R2::den, mars_boost::intmax_t M2 = R2::num % R2::den>\r\n  struct ratio_less1\r\n  {\r\n    static const bool value = Q1 < Q2;\r\n  };\r\n\r\n  template <class R1, class R2, mars_boost::intmax_t Q>\r\n  struct ratio_less1<R1, R2, Q, 0, Q, 0>\r\n  {\r\n    static const bool value = false;\r\n  };\r\n\r\n  template <class R1, class R2, mars_boost::intmax_t Q, mars_boost::intmax_t M2>\r\n  struct ratio_less1<R1, R2, Q, 0, Q, M2>\r\n  {\r\n    static const bool value = true;\r\n  };\r\n\r\n  template <class R1, class R2, mars_boost::intmax_t Q, mars_boost::intmax_t M1>\r\n  struct ratio_less1<R1, R2, Q, M1, Q, 0>\r\n  {\r\n    static const bool value = false;\r\n  };\r\n\r\n  template <class R1, class R2, mars_boost::intmax_t Q, mars_boost::intmax_t M1, mars_boost::intmax_t M2>\r\n  struct ratio_less1<R1, R2, Q, M1, Q, M2>\r\n  {\r\n    static const bool value = ratio_less1<ratio<R2::den, M2>, ratio<R1::den, M1>\r\n                                            >::value;\r\n  };\r\n\r\n  template <\r\n      class R1,\r\n      class R2,\r\n      mars_boost::intmax_t S1 = mpl::sign_c<mars_boost::intmax_t, R1::num>::value,\r\n    mars_boost::intmax_t S2 = mpl::sign_c<mars_boost::intmax_t, R2::num>::value\r\n>\r\n  struct ratio_less\r\n  {\r\n      static const bool value = S1 < S2;\r\n  };\r\n\r\n  template <class R1, class R2>\r\n  struct ratio_less<R1, R2, 1LL, 1LL>\r\n  {\r\n      static const bool value = ratio_less1<R1, R2>::value;\r\n  };\r\n\r\n  template <class R1, class R2>\r\n  struct ratio_less<R1, R2, -1LL, -1LL>\r\n  {\r\n      static const bool value = ratio_less1<ratio<-R2::num, R2::den>,\r\n                                            ratio<-R1::num, R1::den> >::value;\r\n  };\r\n\r\n\r\n}  // namespace ratio_detail\r\n\r\n}  // namespace mars_boost\r\n\r\n#endif  // BOOST_RATIO_HPP\r\n", "meta": {"hexsha": "a644f3d6e6ccf5b1f8396f6daaaea9233187c250", "size": 13996, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "mars/boost/ratio/detail/overflow_helpers.hpp", "max_stars_repo_name": "jonetomtom/mars", "max_stars_repo_head_hexsha": "3f11714e0aee826eb12bfd52496b59675125204a", "max_stars_repo_licenses": ["BSD-2-Clause", "Apache-2.0"], "max_stars_count": 17104.0, "max_stars_repo_stars_event_min_datetime": "2016-12-28T07:45:54.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T07:02:52.000Z", "max_issues_repo_path": "mars/boost/ratio/detail/overflow_helpers.hpp", "max_issues_repo_name": "wblzu/mars", "max_issues_repo_head_hexsha": "4396e753aee627a92b55ae7a1bc12b4d6f4f6445", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 964.0, "max_issues_repo_issues_event_min_datetime": "2016-12-28T08:13:33.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T13:36:40.000Z", "max_forks_repo_path": "mars/boost/ratio/detail/overflow_helpers.hpp", "max_forks_repo_name": "pengjinning/mars", "max_forks_repo_head_hexsha": "227aff64a5b819555091a7d6eae6727701e9fff0", "max_forks_repo_licenses": ["Apache-2.0", "BSD-2-Clause"], "max_forks_count": 3568.0, "max_forks_repo_forks_event_min_datetime": "2016-12-28T07:47:46.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T02:13:19.000Z", "avg_line_length": 38.0326086957, "max_line_length": 143, "alphanum_fraction": 0.6361817662, "num_tokens": 3869, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7185943925708561, "lm_q2_score": 0.43782349911420193, "lm_q1q2_score": 0.3146175113992167}}
{"text": "#include <Rcpp.h>\n\n//[[Rcpp::depends(RcppEigen)]]\n#include <RcppEigen.h>\n\n#include \"experimentalSetup.hpp\"\n#include \"individual.hpp\"\n#include \"encodingScheme.hpp\"\n#include \"logLikelihoods.hpp\"\n\n#include \"AuxiliaryFunctions.hpp\"\n\n#include <boost/random/mersenne_twister.hpp>\n#include <boost/random/uniform_int_distribution.hpp>\n#include <boost/random/uniform_real_distribution.hpp>\n\n//[[Rcpp::export(.oneStepApproximationCpp)]]\nRcpp::List oneStepApproximationCpp(const Eigen::VectorXd & encodedProfiles, const Eigen::VectorXd & sampleParameters,\n                                   const Eigen::VectorXd & noiseParameters, const Eigen::VectorXd & mixtureParameters,\n                                   const Eigen::VectorXd & coverage, const Eigen::VectorXd markerImbalances,\n                                   const std::vector< std::vector< Eigen::MatrixXd > > potentialParents,\n                                   const Eigen::MatrixXd & knownProfiles, const Eigen::MatrixXd & allKnownProfiles,\n                                   const Eigen::VectorXd & alleleFrequencies, const double & theta,\n                                   const std::size_t & numberOfContributors, const std::size_t & numberOfMarkers,\n                                   const Eigen::VectorXd & numberOfAlleles, const std::size_t & levelsOfStutterRecursion,\n                                   const bool & dualEstimation)\n{\n    const std::size_t numberOfKnownContributors = knownProfiles.cols();\n\n    const Eigen::VectorXd tolerance = Eigen::VectorXd::Zero(4);\n    const ExperimentalSetup ES(numberOfMarkers, numberOfAlleles, numberOfContributors, numberOfKnownContributors,\n                               knownProfiles, allKnownProfiles, coverage, potentialParents, markerImbalances, 0.8,\n                               noiseParameters, tolerance, theta, alleleFrequencies, levelsOfStutterRecursion, dualEstimation);\n\n    const std::size_t & N = numberOfAlleles[0] * (numberOfAlleles[0] + 1) / 2.0;\n    const std::size_t & numberOfUnknownContributors = ES.NumberOfContributors - ES.NumberOfKnownContributors;\n\n    std::vector<Eigen::MatrixXd> genotypeMatrices(N);\n    Eigen::VectorXd estimatedProbability = Eigen::VectorXd::Zero(N);\n    double estimatedProbabilitySum = 0.0;\n    double maxValue = -HUGE_VAL;\n\n    std::size_t n = 0;\n    for (std::size_t u = 0; u < numberOfUnknownContributors; u++)\n    {\n        const std::size_t & a = 2 * u;\n        Eigen::VectorXd encodedProfiles_um = encodedProfiles;\n        for (std::size_t i = 0; i < numberOfAlleles[0]; i++)\n        {\n            Eigen::VectorXd encodedProfiles_um = encodedProfiles;\n            double tt = encodedProfiles_um[a] + 1;\n            encodedProfiles_um[a] = i;\n\n            for (std::size_t j = i; j < numberOfAlleles[0]; j++)\n            {\n\n                encodedProfiles_um[a + 1] = j;\n                Individual I_umij(encodedProfiles_um, sampleParameters, noiseParameters, mixtureParameters, markerImbalances, ES);\n\n                genotypeMatrices[n] = decoding(I_umij.EncodedProfile, ES.NumberOfAlleles, 1, numberOfUnknownContributors);\n                estimatedProbability[n] = I_umij.Fitness;\n                estimatedProbabilitySum += std::exp(I_umij.Fitness);\n\n                if (I_umij.Fitness > maxValue)\n                    maxValue = I_umij.Fitness;\n\n                n++;\n            }\n        }\n    }\n\n    Eigen::VectorXd normalisedProbability = (estimatedProbability - maxValue * Eigen::VectorXd::Ones(N)).array().exp();\n    normalisedProbability = normalisedProbability / normalisedProbability.sum();\n\n    return Rcpp::List::create(Rcpp::Named(\"GenotypeMatrix\") = genotypeMatrices,\n                              Rcpp::Named(\"LogUnnormalisedProbabilitySum\") = std::log(estimatedProbabilitySum),\n                              Rcpp::Named(\"LogUnnormalisedProbability\") = estimatedProbability,\n                              Rcpp::Named(\"NormalisedProbabilities\") = normalisedProbability);\n}\n\n\n//[[Rcpp::export(.EAApproximationCpp)]]\nRcpp::List EAApproximationCpp(const std::vector<Eigen::VectorXd> & encodedProfiles, const Eigen::VectorXd & sampleParameters,\n                              const Eigen::VectorXd & noiseParameters, const Eigen::VectorXd & mixtureParameters,\n                              const Eigen::VectorXd & coverage, const Eigen::VectorXd markerImbalances,\n                              const std::vector< std::vector< Eigen::MatrixXd > > potentialParents,\n                              const Eigen::MatrixXd & knownProfiles, const Eigen::MatrixXd & allKnownProfiles,\n                              const Eigen::VectorXd & alleleFrequencies, const double & theta,\n                              const std::size_t & numberOfContributors, const std::size_t & numberOfMarkers,\n                              const Eigen::VectorXd & numberOfAlleles, const std::size_t & levelsOfStutterRecursion,\n                              const bool & type1, const bool & dualEstimation)\n{\n    const std::size_t numberOfKnownContributors = knownProfiles.cols();\n\n    const Eigen::VectorXd tolerance = Eigen::VectorXd::Zero(4);\n    const ExperimentalSetup ES(numberOfMarkers, numberOfAlleles, numberOfContributors, numberOfKnownContributors,\n                               knownProfiles, allKnownProfiles, coverage, potentialParents, markerImbalances, 0.8,\n                               noiseParameters, tolerance, theta, alleleFrequencies, levelsOfStutterRecursion, dualEstimation);\n\n    const std::size_t & numberOfUnknownContributors = ES.NumberOfContributors - ES.NumberOfKnownContributors;\n    const std::size_t & N = encodedProfiles.size();\n\n    std::vector<Eigen::MatrixXd> genotypeMatrices(N);\n    Eigen::VectorXd estimatedProbability = Eigen::VectorXd::Zero(N);\n    double estimatedProbabilitySum = 0.0;\n    double maxValue = -HUGE_VAL;\n    for (std::size_t n = 0; n < N; n++)\n    {\n        const Eigen::VectorXd & encodedProfiles_n = encodedProfiles[n];\n        Individual I(encodedProfiles_n, sampleParameters, noiseParameters, mixtureParameters, markerImbalances, ES);\n\n        genotypeMatrices[n] = decoding(I.EncodedProfile, ES.NumberOfAlleles, 1, numberOfUnknownContributors);\n\n        if (type1) {\n            estimatedProbability[n] = I.Fitness;\n            estimatedProbabilitySum += std::exp(I.Fitness - estimatedProbability[0]);\n        }\n        else {\n            estimatedProbability[n] = I.Fitness;\n            estimatedProbabilitySum += std::exp(I.Fitness);\n        }\n\n        if (I.Fitness > maxValue)\n            maxValue = I.Fitness;\n    }\n\n\n    Eigen::VectorXd normalisedProbability = (estimatedProbability - maxValue * Eigen::VectorXd::Ones(N)).array().exp();\n    normalisedProbability = normalisedProbability / normalisedProbability.sum();\n\n    double logEstimatedProbabilitySum = std::log(estimatedProbabilitySum);\n    if (type1) {\n        logEstimatedProbabilitySum += estimatedProbability[0];\n    }\n\n    return Rcpp::List::create(Rcpp::Named(\"GenotypeMatrix\") = genotypeMatrices,\n                              Rcpp::Named(\"LogUnnormalisedProbabilitySum\") = logEstimatedProbabilitySum,\n                              Rcpp::Named(\"LogUnnormalisedProbability\") = estimatedProbability,\n                              Rcpp::Named(\"NormalisedProbabilities\") = normalisedProbability);\n}\n\n\n////\nstruct sampledPriorGenotype {\n    Eigen::VectorXd encodedGenotype;\n    double priorProbability;\n\n    sampledPriorGenotype(Eigen::VectorXd encodedGenotype_, double priorProbability_) :\n        encodedGenotype(encodedGenotype_), priorProbability(priorProbability_) {};\n};\n\nEigen::MatrixXd expectedContributionMarker(const Eigen::MatrixXd & genotype, const std::vector<Eigen::MatrixXd> &potentialParents_m,\n                                           const double & levelsOfStutterRecursion)\n{\n    const std::size_t & N = genotype.rows();\n    const std::size_t & M = genotype.cols();\n\n    Eigen::MatrixXd expectedContributionProfile_m = Eigen::MatrixXd::Zero(N, M);\n    for (std::size_t u = 0; u < M; u++)\n    {\n        Eigen::VectorXd genotype_u = genotype.col(u);\n        Eigen::VectorXd stutterContribution = Eigen::VectorXd::Zero(N);\n        for (std::size_t n = 0; n < N; n++)\n        {\n            stutterContribution[n] = ParentStutterContribution(n, levelsOfStutterRecursion, 1, genotype_u, potentialParents_m, N);\n        }\n\n        expectedContributionProfile_m.col(u) = genotype_u + stutterContribution;\n    }\n\n    return expectedContributionProfile_m;\n}\n\n\nvoid adjustCoverage(Eigen::VectorXd & adjustedCoverage, const double & sampleParameter, const Eigen::VectorXd & mixtureParamters,\n                    const double & markerParameter, const Eigen::MatrixXd & genotype, const std::vector< Eigen::MatrixXd > & potentialParents_m,\n                    const double & levelsOfStutterRecursion)\n{\n    const std::size_t & N = adjustedCoverage.size();\n    const Eigen::VectorXd & E_c = expectedContributionMarker(genotype, potentialParents_m, levelsOfStutterRecursion);\n    const Eigen::VectorXd & mu_ma = sampleParameter * markerParameter * (E_c * mixtureParamters);\n\n    adjustedCoverage = adjustedCoverage - mu_ma;\n    for (std::size_t n = 0; n < N; n++)\n    {\n        if (adjustedCoverage[n] <= 0.0)\n        {\n            adjustedCoverage[n] = std::exp(adjustedCoverage[n]);\n        }\n\n    }\n}\n\ndouble calculatePriorProbabiliy(const Eigen::VectorXd & E, const Eigen::MatrixXd &knownProfiles, const Eigen::VectorXd &coverage,\n                                std::vector<Eigen::MatrixXd> potentialParents_m,\n                                const double &sampleParameter, const Eigen::VectorXd &mixtureParameters, const double &markerParameter,\n                                const std::size_t & numberOfContributors, const double & levelsOfStutterRecursion,\n                                const bool &suggestionBool)\n{\n    if (!suggestionBool)\n    {\n        return 0.0;\n    }\n\n    const std::size_t numberOfKnownContributors = knownProfiles.cols();\n    const std::size_t N = E.size();\n    const std::size_t M = coverage.size();\n\n    Eigen::MatrixXd genotype = Eigen::MatrixXd::Zero(M, numberOfContributors);\n    for (std::size_t k = 0; k < numberOfKnownContributors; k++)\n    {\n        genotype.col(k) = knownProfiles.col(k);\n    }\n\n    Eigen::VectorXd adjustedCoverage = coverage;\n    if (suggestionBool)\n    {\n        adjustCoverage(adjustedCoverage, sampleParameter, mixtureParameters, markerParameter, genotype, potentialParents_m, levelsOfStutterRecursion);\n    }\n    else\n    {\n        adjustedCoverage = Eigen::VectorXd::Ones(M);\n    }\n\n    double priorProbability = 0.0;\n    for (std::size_t n = 0; n < N; n++)\n    {\n        std::size_t u = std::floor(n / 2);\n        Eigen::VectorXd proportionalProbability = adjustedCoverage / adjustedCoverage.sum();\n\n        genotype(E[n], numberOfKnownContributors + u) += 1.0;\n\n        if (suggestionBool)\n        {\n            Eigen::VectorXd singleAllele = Eigen::VectorXd::Zero(M);\n            singleAllele[E[n]] = 1.0;\n\n            priorProbability += std::log(proportionalProbability[E[n]]);\n            adjustCoverage(adjustedCoverage, sampleParameter, mixtureParameters.row(u), markerParameter, singleAllele, potentialParents_m,\n                           levelsOfStutterRecursion);\n        }\n    }\n\n    return priorProbability;\n}\n\nsampledPriorGenotype samplePriorGenotypeMarker(const Eigen::MatrixXd &knownProfiles, const Eigen::VectorXd &coverage,\n                                               const std::vector<Eigen::MatrixXd> &potentialParents_m,\n                                               const double &sampleParameter, const Eigen::VectorXd &mixtureParameters,\n                                               const double &markerParameter, const std::size_t numberOfContributors,\n                                               const double &levelsOfStutterRecursion, const bool & suggestionBool,\n                                               const std::size_t &seed)\n{\n    boost::random::mt19937 rng(seed);\n    boost::random::uniform_real_distribution<> uniform(0, 1);\n\n    const std::size_t &N = coverage.size();\n    const std::size_t &numberOfKnownContributors = knownProfiles.cols();\n    const std::size_t &numberOfUnknownContributors = numberOfContributors - numberOfKnownContributors;\n\n    Eigen::MatrixXd sampledGenotype = Eigen::MatrixXd::Zero(N, numberOfContributors);\n    for (std::size_t k = 0; k < numberOfKnownContributors; k++)\n        sampledGenotype.col(k) = knownProfiles.col(k);\n\n    Eigen::VectorXd adjustedCoverage = Eigen::VectorXd::Ones(N);\n    if (suggestionBool)\n    {\n        adjustedCoverage = coverage;\n        adjustCoverage(adjustedCoverage, sampleParameter, mixtureParameters, markerParameter, sampledGenotype, potentialParents_m,\n                       levelsOfStutterRecursion);\n    }\n\n    Eigen::VectorXd sampledGenotypeEncoded = Eigen::VectorXd::Zero(2 * numberOfUnknownContributors);\n    double sampledPriorProbability = 0.0;\n    for (std::size_t u = 0; u < numberOfUnknownContributors; u++)\n    {\n        for (std::size_t i = 0; i < 2; i++)\n        {\n            Eigen::VectorXd proportionalProbability = adjustedCoverage / adjustedCoverage.sum();\n            Eigen::VectorXd partialSumProportionalProbability = partialSumEigen(proportionalProbability);\n            double randomVariate = uniform(rng);\n            std::size_t j = 0.0;\n            while (randomVariate > partialSumProportionalProbability[j + 1])\n                j++;\n\n            sampledGenotype(j, numberOfKnownContributors + u) += 1.0;\n\n            if (suggestionBool)\n            {\n                Eigen::VectorXd singleAllele = Eigen::VectorXd::Zero(N);\n                singleAllele[j] = 1.0;\n\n                sampledPriorProbability += std::log(proportionalProbability[j]);\n                adjustCoverage(adjustedCoverage, sampleParameter, mixtureParameters.row(u), markerParameter, singleAllele, potentialParents_m,\n                               levelsOfStutterRecursion);\n            }\n\n            if (i == 0)\n            {\n                sampledGenotypeEncoded[2 * u] = j;\n            }\n            else\n            {\n                if (j < sampledGenotypeEncoded[2 * u])\n                {\n                    sampledGenotypeEncoded[2 * u + i] = sampledGenotypeEncoded[2 * u];\n                    sampledGenotypeEncoded[2 * u] = j;\n                }\n                else\n                {\n                    sampledGenotypeEncoded[2 * u + i] = j;\n                }\n            }\n        }\n    }\n\n    sampledPriorGenotype spg(sampledGenotypeEncoded, sampledPriorProbability);\n    return spg;\n}\n\n//[[Rcpp::export(.samplePosteriorGenotypesGuidedCpp)]]\nRcpp::List samplePosteriorGenotypesGuidedCpp(const Eigen::VectorXd & encodedProfiles, const Eigen::VectorXd & sampleParameters,\n                                             const Eigen::VectorXd & noiseParameters, const Eigen::VectorXd & mixtureParameters,\n                                             const Eigen::VectorXd markerParameters, const Eigen::VectorXd & coverage,\n                                             const std::vector< std::vector< Eigen::MatrixXd > > potentialParents,\n                                             const Eigen::MatrixXd & knownProfiles, const Eigen::MatrixXd & allKnownProfiles,\n                                             const Eigen::VectorXd & alleleFrequencies, const double & theta,\n                                             const std::size_t & numberOfContributors,  const Eigen::VectorXd & numberOfAlleles,\n                                             const std::size_t & levelsOfStutterRecursion,\n                                             const std::size_t &numberOfSimulations, const bool & suggestionBool,\n                                             const std::size_t &seed, const bool & dualEstimation)\n{\n    boost::random::mt19937 rng(seed);\n    boost::random::uniform_int_distribution<> seedShift(0, seed);\n    boost::random::uniform_real_distribution<> uniform(0, 1);\n\n    const std::size_t &numberOfKnownContributors = knownProfiles.cols();\n    const std::size_t &numberOfMarkers = numberOfAlleles.size();\n\n    const Eigen::VectorXd tolerance = Eigen::VectorXd::Zero(4);\n    const ExperimentalSetup ES(1, numberOfAlleles, numberOfContributors, numberOfKnownContributors,\n                               knownProfiles, allKnownProfiles, coverage, potentialParents, markerParameters, 0.0,\n                               noiseParameters, tolerance, theta, alleleFrequencies, levelsOfStutterRecursion, dualEstimation);\n\n    Eigen::VectorXd currentEncodedGenotype = encodedProfiles;\n    double currentPriorProbability = calculatePriorProbabiliy(currentEncodedGenotype, knownProfiles, coverage,\n                                                              potentialParents[0], sampleParameters[0], mixtureParameters,\n                                                              markerParameters[0], numberOfContributors, levelsOfStutterRecursion,\n                                                              suggestionBool);\n\n    Individual currentI(currentEncodedGenotype, sampleParameters, noiseParameters, mixtureParameters, markerParameters, ES);\n    double currentLogLikelihood = currentI.Fitness;\n\n    std::vector<Eigen::MatrixXd> sampledGenotypeList(numberOfSimulations);\n    Eigen::VectorXd unnormalisedLogLikelihood = Eigen::VectorXd::Zero(numberOfSimulations);\n    double acceptedProposals = 0.0;\n    for (std::size_t n = 0; n < numberOfSimulations; n++)\n    {\n        int seedShift_n = seedShift(rng);\n        const sampledPriorGenotype & newGenotype = samplePriorGenotypeMarker(knownProfiles, coverage, potentialParents[0],\n                                                                             sampleParameters[0], mixtureParameters,\n                                                                             markerParameters[0], numberOfContributors, levelsOfStutterRecursion,\n                                                                             suggestionBool, seed + n + seedShift_n);\n\n        const Eigen::VectorXd & newEncodedGenotype = newGenotype.encodedGenotype;\n        const double & newPriorProbability = newGenotype.priorProbability;\n\n        const Individual newI(newEncodedGenotype, sampleParameters, noiseParameters, mixtureParameters, markerParameters, ES);\n        const double & newLogLikelihood = newI.Fitness;\n\n        const double & logHastingsRatio = newLogLikelihood - currentLogLikelihood + currentPriorProbability - newPriorProbability;\n        double acceptProbability = 1.0;\n        if (logHastingsRatio < 0)\n        {\n            acceptProbability = std::exp(logHastingsRatio);\n        }\n\n        double randomVariate = uniform(rng);\n        if (randomVariate < acceptProbability)\n        {\n            currentEncodedGenotype = newEncodedGenotype;\n            currentPriorProbability = newPriorProbability;\n            currentLogLikelihood = newLogLikelihood;\n            acceptedProposals += 1;\n        }\n\n        Eigen::MatrixXd currentDecodedGenotype = decoding(currentEncodedGenotype, numberOfAlleles, 1,\n                                                          numberOfContributors - numberOfKnownContributors);\n        sampledGenotypeList[n] = currentDecodedGenotype;\n        unnormalisedLogLikelihood[n] = currentLogLikelihood;\n    }\n\n    return Rcpp::List::create(Rcpp::Named(\"SampledGenotypes\") = sampledGenotypeList,\n                              Rcpp::Named(\"UnnormalisedLogLikelihood\") = unnormalisedLogLikelihood,\n                              Rcpp::Named(\"AcceptedProposals\") = acceptedProposals);\n}\n", "meta": {"hexsha": "8ae4bee042a71e597a786dc1cecdcea281370fa6", "size": 19544, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/unknownContributorSumApproximation.cpp", "max_stars_repo_name": "svilsen/MPSMixtures", "max_stars_repo_head_hexsha": "07b21c593bee795162f6282446ff370985ceec38", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/unknownContributorSumApproximation.cpp", "max_issues_repo_name": "svilsen/MPSMixtures", "max_issues_repo_head_hexsha": "07b21c593bee795162f6282446ff370985ceec38", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/unknownContributorSumApproximation.cpp", "max_forks_repo_name": "svilsen/MPSMixtures", "max_forks_repo_head_hexsha": "07b21c593bee795162f6282446ff370985ceec38", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 49.2292191436, "max_line_length": 150, "alphanum_fraction": 0.626023332, "num_tokens": 4032, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.7248702761768248, "lm_q2_score": 0.4339814648038985, "lm_q1q2_score": 0.3145802642480249}}
{"text": "// Copyright 2019 Yan Yan\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 <tensorview/tensorview.h>\n#include <boost/geometry.hpp>\n#include <torch/script.h>\n#include <vector>\n\nnamespace spconv {\nnamespace functor{\ntemplate <typename Device, typename T, typename Index>\nstruct NonMaxSupressionFunctor {\n  Index operator()(const Device &d, tv::TensorView<Index> keep,\n                   tv::TensorView<const T> boxes, T threshold, T eps);\n};\n\ntemplate <typename Device, typename T, typename Index>\nstruct rotateNonMaxSupressionFunctor {\n  Index operator()(const Device &d, tv::TensorView<Index> keep,\n                   tv::TensorView<const T> boxCorners,\n                   tv::TensorView<const T> standupIoU, T threshold);\n};\n\n}\n}\n\n\nnamespace spconv {\n\nnamespace functor {\ntemplate <typename T, typename Index>\nstruct NonMaxSupressionFunctor<tv::CPU, T, Index> {\n  Index operator()(const tv::CPU &d, tv::TensorView<Index> keep,\n                   tv::TensorView<const T> boxes, T threshold, T eps) {\n    auto ndets = boxes.dim(0);\n    auto suppressed = std::vector<Index>(ndets);\n    auto area = std::vector<T>(ndets);\n    for (int i = 0; i < ndets; ++i) {\n      area[i] =\n          (boxes(i, 2) - boxes(i, 0) + eps) * (boxes(i, 3) - boxes(i, 1) + eps);\n    }\n    int i, j;\n    T xx1, xx2, w, h, inter, ovr;\n    int keepNum = 0;\n    for (int _i = 0; _i < ndets; ++_i) {\n      i = _i;\n      if (suppressed[i] == 1)\n        continue;\n      keep[keepNum] = i;\n      keepNum += 1;\n      for (int _j = _i + 1; _j < ndets; ++_j) {\n        j = _j;\n        if (suppressed[j] == 1)\n          continue;\n        xx2 = std::min(boxes(i, 2), boxes(j, 2));\n        xx1 = std::max(boxes(i, 0), boxes(j, 0));\n        w = xx2 - xx1 + eps;\n        if (w > 0) {\n          xx2 = std::min(boxes(i, 3), boxes(j, 3));\n          xx1 = std::max(boxes(i, 1), boxes(j, 1));\n          h = xx2 - xx1 + eps;\n          if (h > 0) {\n            inter = w * h;\n            ovr = inter / (area[i] + area[j] - inter);\n            if (ovr >= threshold)\n              suppressed[j] = 1;\n          }\n        }\n      }\n    }\n    return keepNum;\n  }\n};\n\ntemplate <typename T, typename Index>\nstruct rotateNonMaxSupressionFunctor<tv::CPU, T, Index> {\n  Index operator()(const tv::CPU &d, tv::TensorView<Index> keep,\n                   tv::TensorView<const T> boxCorners,\n                   tv::TensorView<const T> standupIoU, T threshold) {\n    auto ndets = boxCorners.dim(0);\n    auto suppressed = std::vector<Index>(ndets);\n    int i, j;\n    namespace bg = boost::geometry;\n    typedef bg::model::point<T, 2, bg::cs::cartesian> point_t;\n    typedef bg::model::polygon<point_t> polygon_t;\n    polygon_t poly, qpoly;\n    std::vector<polygon_t> poly_inter, poly_union;\n    T inter_area, union_area, overlap;\n    int keepNum = 0;\n    for (int _i = 0; _i < ndets; ++_i) {\n      i = _i;\n      if (suppressed[i] == 1)\n        continue;\n      keep[keepNum] = i;\n      keepNum += 1;\n      for (int _j = _i + 1; _j < ndets; ++_j) {\n        j = _j;\n        if (suppressed[j] == 1)\n          continue;\n        if (standupIoU(i, j) <= 0.0)\n          continue;\n        bg::append(poly, point_t(boxCorners(i, 0, 0), boxCorners(i, 0, 1)));\n        bg::append(poly, point_t(boxCorners(i, 1, 0), boxCorners(i, 1, 1)));\n        bg::append(poly, point_t(boxCorners(i, 2, 0), boxCorners(i, 2, 1)));\n        bg::append(poly, point_t(boxCorners(i, 3, 0), boxCorners(i, 3, 1)));\n        bg::append(poly, point_t(boxCorners(i, 0, 0), boxCorners(i, 0, 1)));\n        bg::append(qpoly, point_t(boxCorners(j, 0, 0), boxCorners(j, 0, 1)));\n        bg::append(qpoly, point_t(boxCorners(j, 1, 0), boxCorners(j, 1, 1)));\n        bg::append(qpoly, point_t(boxCorners(j, 2, 0), boxCorners(j, 2, 1)));\n        bg::append(qpoly, point_t(boxCorners(j, 3, 0), boxCorners(j, 3, 1)));\n        bg::append(qpoly, point_t(boxCorners(j, 0, 0), boxCorners(j, 0, 1)));\n        bg::intersection(poly, qpoly, poly_inter);\n\n        if (!poly_inter.empty()) {\n          inter_area = bg::area(poly_inter.front());\n          bg::union_(poly, qpoly, poly_union);\n          if (!poly_union.empty()) { // ignore invalid box\n            union_area = bg::area(poly_union.front());\n            overlap = inter_area / union_area;\n            if (overlap >= threshold)\n              suppressed[j] = 1;\n            poly_union.clear();\n          }\n        }\n        poly.clear();\n        qpoly.clear();\n        poly_inter.clear();\n      }\n    }\n    return keepNum;\n  }\n};\n\n} // namespace functor\n\n#define DECLARE_CPU_T_INDEX(T, Index)                                          \\\n  template struct functor::NonMaxSupressionFunctor<tv::CPU, T, Index>;         \\\n  template struct functor::rotateNonMaxSupressionFunctor<tv::CPU, T, Index>;\n\n#define DECLARE_CPU_INDEX(Index)                                               \\\n  DECLARE_CPU_T_INDEX(float, Index);                                           \\\n  DECLARE_CPU_T_INDEX(double, Index);\n\nDECLARE_CPU_INDEX(int);\nDECLARE_CPU_INDEX(long);\n\n#undef DECLARE_CPU_INDEX\n#undef DECLARE_CPU_T_INDEX\n\n} // namespace spconv\n", "meta": {"hexsha": "11253cf16f313053dd3e0356d82f95e8f59de61e", "size": 5580, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/spconv/nms.cc", "max_stars_repo_name": "jasonperhaps/spconv", "max_stars_repo_head_hexsha": "c44bd5985fcfc63181fee47bc6b4ace9474fb952", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/spconv/nms.cc", "max_issues_repo_name": "jasonperhaps/spconv", "max_issues_repo_head_hexsha": "c44bd5985fcfc63181fee47bc6b4ace9474fb952", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/spconv/nms.cc", "max_forks_repo_name": "jasonperhaps/spconv", "max_forks_repo_head_hexsha": "c44bd5985fcfc63181fee47bc6b4ace9474fb952", "max_forks_repo_licenses": ["Apache-2.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.4444444444, "max_line_length": 80, "alphanum_fraction": 0.5756272401, "num_tokens": 1614, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7057850402140659, "lm_q2_score": 0.44552953503957277, "lm_q1q2_score": 0.3144480808044589}}
{"text": "\n///////////////////////////////////////////////////////////////////////////////\n//  Copyright 2018 John Maddock\n//  Distributed under the Boost\n//  Software License, Version 1.0. (See accompanying file\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n#ifndef BOOST_MATH_HYPERGEOMETRIC_PFQ_HPP\n#define BOOST_MATH_HYPERGEOMETRIC_PFQ_HPP\n\n#include <boost/math/special_functions/detail/hypergeometric_pFq_checked_series.hpp>\n#include <chrono>\n#include <initializer_list>\n\nnamespace boost {\n   namespace math {\n\n      namespace detail {\n\n         struct pFq_termination_exception : public std::runtime_error\n         {\n            pFq_termination_exception(const char* p) : std::runtime_error(p) {}\n         };\n\n         struct timed_iteration_terminator\n         {\n            timed_iteration_terminator(std::uintmax_t i, double t) : max_iter(i), max_time(t), start_time(std::chrono::system_clock::now()) {}\n\n            bool operator()(std::uintmax_t iter)const\n            {\n               if (iter > max_iter)\n                  boost::throw_exception(boost::math::detail::pFq_termination_exception(\"pFq exceeded maximum permitted iterations.\"));\n               if (std::chrono::duration<double>(std::chrono::system_clock::now() - start_time).count() > max_time)\n                  boost::throw_exception(boost::math::detail::pFq_termination_exception(\"pFq exceeded maximum permitted evaluation time.\"));\n               return false;\n            }\n\n            std::uintmax_t max_iter;\n            double max_time;\n            std::chrono::system_clock::time_point start_time;\n         };\n\n      }\n\n      template <class Seq, class Real, class Policy>\n      inline typename tools::promote_args<Real, typename Seq::value_type>::type hypergeometric_pFq(const Seq& aj, const Seq& bj, const Real& z, Real* p_abs_error, const Policy& pol)\n      {\n         typedef typename tools::promote_args<Real, typename Seq::value_type>::type result_type;\n         typedef typename policies::evaluation<result_type, Policy>::type value_type;\n         typedef typename policies::normalise<\n            Policy,\n            policies::promote_float<false>,\n            policies::promote_double<false>,\n            policies::discrete_quantile<>,\n            policies::assert_undefined<> >::type forwarding_policy;\n\n         BOOST_MATH_STD_USING\n\n         long long scale = 0;\n         std::pair<value_type, value_type> r = boost::math::detail::hypergeometric_pFq_checked_series_impl(aj, bj, value_type(z), pol, boost::math::detail::iteration_terminator(boost::math::policies::get_max_series_iterations<forwarding_policy>()), scale);\n         r.first *= exp(Real(scale));\n         r.second *= exp(Real(scale));\n         if (p_abs_error)\n            *p_abs_error = static_cast<Real>(r.second) * boost::math::tools::epsilon<Real>();\n         return policies::checked_narrowing_cast<result_type, Policy>(r.first, \"boost::math::hypergeometric_pFq<%1%>(%1%,%1%,%1%)\");\n      }\n\n      template <class Seq, class Real>\n      inline typename tools::promote_args<Real, typename Seq::value_type>::type hypergeometric_pFq(const Seq& aj, const Seq& bj, const Real& z, Real* p_abs_error = 0)\n      {\n         return hypergeometric_pFq(aj, bj, z, p_abs_error, boost::math::policies::policy<>());\n      }\n\n      template <class R, class Real, class Policy>\n      inline typename tools::promote_args<Real, R>::type hypergeometric_pFq(const std::initializer_list<R>& aj, const std::initializer_list<R>& bj, const Real& z, Real* p_abs_error, const Policy& pol)\n      {\n         return hypergeometric_pFq<std::initializer_list<R>, Real, Policy>(aj, bj, z, p_abs_error, pol);\n      }\n      \n      template <class R, class Real>\n      inline typename tools::promote_args<Real, R>::type  hypergeometric_pFq(const std::initializer_list<R>& aj, const std::initializer_list<R>& bj, const Real& z, Real* p_abs_error = 0)\n      {\n         return hypergeometric_pFq<std::initializer_list<R>, Real>(aj, bj, z, p_abs_error);\n      }\n\n      template <class T>\n      struct scoped_precision\n      {\n         scoped_precision(unsigned p)\n         {\n            old_p = T::default_precision();\n            T::default_precision(p);\n         }\n         ~scoped_precision()\n         {\n            T::default_precision(old_p);\n         }\n         unsigned old_p;\n      };\n\n      template <class Seq, class Real, class Policy>\n      Real hypergeometric_pFq_precision(const Seq& aj, const Seq& bj, Real z, unsigned digits10, double timeout, const Policy& pol)\n      {\n         unsigned current_precision = digits10 + 5;\n\n         for (auto ai = aj.begin(); ai != aj.end(); ++ai)\n         {\n            current_precision = (std::max)(current_precision, ai->precision());\n         }\n         for (auto bi = bj.begin(); bi != bj.end(); ++bi)\n         {\n            current_precision = (std::max)(current_precision, bi->precision());\n         }\n         current_precision = (std::max)(current_precision, z.precision());\n\n         Real r, norm;\n         std::vector<Real> aa(aj), bb(bj);\n         do\n         {\n            scoped_precision<Real> p(current_precision);\n            for (auto ai = aa.begin(); ai != aa.end(); ++ai)\n               ai->precision(current_precision);\n            for (auto bi = bb.begin(); bi != bb.end(); ++bi)\n               bi->precision(current_precision);\n            z.precision(current_precision);\n            try\n            {\n               long long scale = 0;\n               std::pair<Real, Real> rp = boost::math::detail::hypergeometric_pFq_checked_series_impl(aa, bb, z, pol, boost::math::detail::timed_iteration_terminator(boost::math::policies::get_max_series_iterations<Policy>(), timeout), scale);\n               rp.first *= exp(Real(scale));\n               rp.second *= exp(Real(scale));\n\n               r = rp.first;\n               norm = rp.second;\n\n               unsigned cancellation;\n               try {\n                  cancellation = itrunc(log10(abs(norm / r)));\n               }\n               catch (const boost::math::rounding_error&)\n               {\n                  // Happens when r is near enough zero:\n                  cancellation = UINT_MAX;\n               }\n               if (cancellation >= current_precision - 1)\n               {\n                  current_precision *= 2;\n                  continue;\n               }\n               unsigned precision_obtained = current_precision - 1 - cancellation;\n               if (precision_obtained < digits10)\n               {\n                  current_precision += digits10 - precision_obtained + 5;\n               }\n               else\n                  break;\n            }\n            catch (const boost::math::evaluation_error&)\n            {\n               current_precision *= 2;\n            }\n            catch (const detail::pFq_termination_exception& e)\n            {\n               //\n               // Either we have exhausted the number of series iterations, or the timeout.\n               // Either way we quit now.\n               throw boost::math::evaluation_error(e.what());\n            }\n         } while (true);\n\n         return r;\n      }\n      template <class Seq, class Real>\n      Real hypergeometric_pFq_precision(const Seq& aj, const Seq& bj, const Real& z, unsigned digits10, double timeout = 0.5)\n      {\n         return hypergeometric_pFq_precision(aj, bj, z, digits10, timeout, boost::math::policies::policy<>());\n      }\n\n      template <class Real, class Policy>\n      Real hypergeometric_pFq_precision(const std::initializer_list<Real>& aj, const std::initializer_list<Real>& bj, const Real& z, unsigned digits10, double timeout, const Policy& pol)\n      {\n         return hypergeometric_pFq_precision< std::initializer_list<Real>, Real>(aj, bj, z, digits10, timeout, pol);\n      }\n      template <class Real>\n      Real hypergeometric_pFq_precision(const std::initializer_list<Real>& aj, const std::initializer_list<Real>& bj, const Real& z, unsigned digits10, double timeout = 0.5)\n      {\n         return hypergeometric_pFq_precision< std::initializer_list<Real>, Real>(aj, bj, z, digits10, timeout, boost::math::policies::policy<>());\n      }\n\n   }\n} // namespaces\n\n#endif // BOOST_MATH_BESSEL_ITERATORS_HPP\n", "meta": {"hexsha": "338d2300b9db36f8cbd405cd0eb8f6b944e0518d", "size": 8208, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/math/special_functions/hypergeometric_pFq.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/special_functions/hypergeometric_pFq.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/special_functions/hypergeometric_pFq.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": 42.3092783505, "max_line_length": 256, "alphanum_fraction": 0.5966130604, "num_tokens": 1862, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7057850278370112, "lm_q2_score": 0.4455295350395727, "lm_q1q2_score": 0.3144480752901155}}
{"text": "/*\n * This is part of the fl library, a C++ Bayesian filtering library\n * (https://github.com/filtering-library)\n *\n * Copyright (c) 2015 Max Planck Society,\n * \t\t\t\t Autonomous Motion Department,\n * \t\t\t     Institute for Intelligent Systems\n *\n * This Source Code Form is subject to the terms of the MIT License (MIT).\n * A copy of the license can be found in the LICENSE file distributed with this\n * source code.\n */\n\n/**\n * \\file multi_sensor_sigma_point_update_policy.hpp\n * \\date August 2015\n * \\author Jan Issac (jan.issac@gmail.com)\n */\n\n#pragma once\n\n\n#include <Eigen/Dense>\n\n#include <fl/util/meta.hpp>\n#include <fl/util/types.hpp>\n#include <fl/util/traits.hpp>\n#include <fl/util/descriptor.hpp>\n#include <fl/model/sensor/joint_sensor_iid.hpp>\n#include <fl/filter/gaussian/transform/point_set.hpp>\n#include <fl/filter/gaussian/quadrature/sigma_point_quadrature.hpp>\n\nnamespace fl\n{\n\n// Forward declarations\ntemplate <typename...> class MultiSensorSigmaPointUpdatePolicy;\n\n/**\n * \\internal\n */\ntemplate <\n    typename SigmaPointQuadrature,\n    typename NonJoinSensor\n>\nclass MultiSensorSigmaPointUpdatePolicy<\n          SigmaPointQuadrature,\n          NonJoinSensor>\n{\n    static_assert(\n        std::is_base_of<\n            internal::JointSensorIidType, NonJoinSensor\n        >::value,\n        \"\\n\\n\\n\"\n        \"====================================================================\\n\"\n        \"= Static Assert: You are using the wrong observation model type    =\\n\"\n        \"====================================================================\\n\"\n        \"  Observation model type must be a JointSensor<...>.      \\n\"\n        \"  For single observation model, use the regular Gaussian filter     \\n\"\n        \"  or the regular SigmaPointUpdatePolicy if you are specifying       \\n\"\n        \"  the update policy explicitly fo the GaussianFilter.               \\n\"\n        \"====================================================================\\n\"\n    );\n};\n\n\n/**\n * \\brief Represents an update policy update for multiple sensors. This instance\n *        expects a \\a JointSensor<>. The model is forwarded  as\n *        NonAdditive<JointSensor> to the actual\n *        implementation. In case you want to use the model as Additive, you may\n *        specify this explicitly using Additive<JointSensor> or\n *        UseAsAdditive<JointSensor>::Type\n */\ntemplate <\n    typename SigmaPointQuadrature,\n    typename MultipleOfLocalSensor\n>\nclass MultiSensorSigmaPointUpdatePolicy<\n          SigmaPointQuadrature,\n          JointSensor<MultipleOfLocalSensor>>\n    : public MultiSensorSigmaPointUpdatePolicy<\n                SigmaPointQuadrature,\n                NonAdditive<JointSensor<MultipleOfLocalSensor>>>\n{ };\n\n\n/**\n * \\brief Represents an update policy update functor for multiple sensors.\n *        This instance expects a \\a NonAdditive<JointSensor<>>.\n *        The implementation exploits factorization in the joint observation.\n *        The update is performed for each sensor separately.\n */\ntemplate <\n    typename SigmaPointQuadrature,\n    typename MultipleOfLocalSensor\n>\nclass MultiSensorSigmaPointUpdatePolicy<\n          SigmaPointQuadrature,\n          NonAdditive<JointSensor<MultipleOfLocalSensor>>>\n    : public Descriptor\n{\npublic:\n    typedef JointSensor<MultipleOfLocalSensor> JointModel;\n\n    typedef typename JointModel::State State;\n    typedef typename JointModel::Obsrv Obsrv;\n    typedef typename JointModel::LocalObsrv LocalObsrv;\n    typedef typename JointModel::LocalNoise LocalObsrvNoise;\n\n    template <typename Belief>\n    void operator()(JointModel& obsrv_function,\n                    const SigmaPointQuadrature& quadrature,\n                    const Belief& prior_belief,\n                    const Obsrv& y,\n                    Belief& posterior_belief)\n    {\n        auto& sensor_model = obsrv_function.local_sensor();\n\n        /* ------------------------------------------ */\n        /* - Determine the number of quadrature     - */\n        /* - points needed for the given quadrature - */\n        /* - in conjunction with the joint Gaussian - */\n        /* - p(State, LocalObsrvNoise)              - */\n        /* ------------------------------------------ */\n        enum : signed int\n        {\n            NumberOfPoints = SigmaPointQuadrature::number_of_points(\n                                 JoinSizes<\n                                     SizeOf<State>::Value,\n                                     SizeOf<LocalObsrvNoise>::Value\n                                 >::Size)\n        };\n\n        /* ------------------------------------------ */\n        /* - PointSets                              - */\n        /* - [p_X, p_Q] ~ p(State, LocalObsrvNoise) - */\n        /* ------------------------------------------ */\n        PointSet<State, NumberOfPoints> p_X;\n        PointSet<LocalObsrvNoise, NumberOfPoints> p_Q;\n\n        /* ------------------------------------------ */\n        /* - PointSet [p_Y] = h(p_X, p_Q)           - */\n        /* ------------------------------------------ */\n        PointSet<LocalObsrv, NumberOfPoints> p_Y;\n\n        /* ------------------------------------------ */\n        /* - Transform p(State, LocalObsrvNoise) to - */\n        /* - point sets [p_X, p_Q]                  - */\n        /* ------------------------------------------ */\n        quadrature.transform_to_points(\n            prior_belief,\n            Gaussian<LocalObsrvNoise>(sensor_model.noise_dimension()),\n            p_X,\n            p_Q);\n\n        /* ------------------------------------------ */\n        /* - Compute expected moments of the state  - */\n        /* - E[X], Cov(X, X)                        - */\n        /* ------------------------------------------ */\n        auto W = p_X.covariance_weights_vector().asDiagonal();\n        auto mu_x = p_X.mean();\n        auto X = p_X.centered_points();\n        auto c_xx_inv = (X * W * X.transpose()).inverse().eval();\n\n        /* ------------------------------------------ */\n        /* - Temporary accumulators which will be   - */\n        /* - used to updated the belief             - */\n        /* ------------------------------------------ */\n        auto C = c_xx_inv;\n        auto D = State();\n        D.setZero(mu_x.size());\n\n        const int sensor_count = obsrv_function.count_local_models();\n        const int dim_y = y.size() / sensor_count;\n\n        /* ------------------------------------------ */\n        /* - lambda of the sensor observation       - */\n        /* - function                               - */\n        /* ------------------------------------------ */\n        auto&& h = [&](const State& x, const LocalObsrvNoise& w)\n        {\n            return sensor_model.observation(x, w);\n        };\n\n\n        for (int i = 0; i < sensor_count; ++i)\n        {\n            // validate sensor value, i.e. make sure it is finite\n            if (!is_valid(y, i * dim_y, i * dim_y + dim_y)) continue;\n\n            // select current sensor and propagate the points through h(x, w)\n            sensor_model.id(i);\n            quadrature.propagate_points(h, p_X, p_Q, p_Y);\n\n            // comute expected moments of the observation and validate\n            auto mu_y = p_Y.mean();\n            if (!is_valid(mu_y, 0, dim_y)) continue;\n\n            // update accumulatorsa according to the equations in PAPER REF\n            auto Y = p_Y.centered_points();\n            auto c_xy = (X * W * Y.transpose()).eval();\n            auto c_yx = c_xy.transpose().eval();\n            auto A_i = (c_yx * c_xx_inv).eval();\n            auto c_yy_given_x = (\n                     (Y * W * Y.transpose()) - c_yx * c_xx_inv * c_xy\n                 ).eval();\n\n            auto innovation = (y.middleRows(i * dim_y, dim_y) - mu_y).eval();\n            C += A_i.transpose() * solve(c_yy_given_x, A_i);\n            D += A_i.transpose() * solve(c_yy_given_x, innovation);\n        }\n\n        /* ------------------------------------------ */\n        /* - Update belief according to PAPER REF   - */\n        /* ------------------------------------------ */\n        // make sure the posterior has the correct dimension\n        posterior_belief.dimension(prior_belief.dimension());\n        posterior_belief.covariance(C.inverse());\n        posterior_belief.mean(mu_x + posterior_belief.covariance() * D);\n    }\n\n    virtual std::string name() const\n    {\n        return \"MultiSensorSigmaPointUpdatePolicy<\"\n                + this->list_arguments(\n                       \"SigmaPointQuadrature\",\n                       \"NonAdditive<SensorFunction>\")\n                + \">\";\n    }\n\n    virtual std::string description() const\n    {\n        return \"Multi-Sensor Sigma Point based filter update policy \"\n               \"for joint observation model of multiple local observation \"\n               \"models with non-additive noise.\";\n    }\n\nprivate:\n    /**\n     * \\brief Checks whether all vector components within the range (start, end)\n     *        are finiate, i.e. not NAN nor Inf.\n     */\n    template <typename Vector>\n    bool is_valid(Vector&& vector, int start, int end) const\n    {\n        for (int k = start; k < end; ++k)\n        {\n            if (!std::isfinite(vector(k))) return false;\n        }\n\n        return true;\n    }\n};\n\n}\n", "meta": {"hexsha": "1994a2a0d61bc0c34ccff380cb0844352e9eb80c", "size": 9212, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/fl/filter/gaussian/update_policy/multi_sensor_sigma_point_update_policy.hpp", "max_stars_repo_name": "aeolusbot-tommyliu/fl", "max_stars_repo_head_hexsha": "a50d0c9620a8f86e0cd14a5e22ee0f022d00bd02", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 17.0, "max_stars_repo_stars_event_min_datetime": "2015-07-03T06:53:05.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-15T20:55:12.000Z", "max_issues_repo_path": "include/fl/filter/gaussian/update_policy/multi_sensor_sigma_point_update_policy.hpp", "max_issues_repo_name": "aeolusbot-tommyliu/fl", "max_issues_repo_head_hexsha": "a50d0c9620a8f86e0cd14a5e22ee0f022d00bd02", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2015-02-20T12:48:17.000Z", "max_issues_repo_issues_event_max_datetime": "2019-12-18T08:45:13.000Z", "max_forks_repo_path": "include/fl/filter/gaussian/update_policy/multi_sensor_sigma_point_update_policy.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": 35.8443579767, "max_line_length": 80, "alphanum_fraction": 0.5185627442, "num_tokens": 1916, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6992544210587585, "lm_q2_score": 0.4493926344647597, "lm_q1q2_score": 0.3142397864407258}}
{"text": "/* +------------------------------------------------------------------------+\n   |                     Mobile Robot Programming Toolkit (MRPT)            |\n   |                          https://www.mrpt.org/                         |\n   |                                                                        |\n   | Copyright (c) 2005-2019, Individual contributors, see AUTHORS file     |\n   | See: https://www.mrpt.org/Authors - All rights reserved.               |\n   | Released under BSD License. See: https://www.mrpt.org/License          |\n   +------------------------------------------------------------------------+ */\n\n#include \"poses-precomp.h\"  // Precompiled headers\n\n#include <mrpt/config.h>  // for HAVE_SINCOS\n#include <mrpt/core/bits_math.h>  // for square\n#include <mrpt/math/CMatrixDynamic.h>  // for CMatrixD...\n#include <mrpt/math/CMatrixF.h>  // for CMatrixF\n#include <mrpt/math/CMatrixFixed.h>  // for CMatrixF...\n#include <mrpt/math/CQuaternion.h>  // for CQuatern...\n#include <mrpt/math/CVectorFixed.h>  // for CArrayDo...\n#include <mrpt/math/TPoint3D.h>\n#include <mrpt/math/geometry.h>  // for skew_sym...\n#include <mrpt/math/homog_matrices.h>  // for homogene...\n#include <mrpt/math/matrix_serialization.h>  // for operator>>\n#include <mrpt/math/ops_containers.h>  // for dotProduct\n#include <mrpt/math/utils_matlab.h>\n#include <mrpt/math/wrap2pi.h>  // for wrapToPi\n#include <mrpt/poses/CPoint2D.h>  // for CPoint2D\n#include <mrpt/poses/CPoint3D.h>  // for CPoint3D\n#include <mrpt/poses/CPose2D.h>  // for CPose2D\n#include <mrpt/poses/CPose3D.h>  // for CPose3D\n#include <mrpt/poses/CPose3DQuat.h>  // for CPose3DQuat\n#include <mrpt/poses/Lie/SO.h>\n#include <mrpt/serialization/CArchive.h>\n#include <mrpt/serialization/CSchemeArchiveBase.h>\n#include <mrpt/serialization/CSerializable.h>  // for CSeriali...\n#include <Eigen/Dense>\n#include <algorithm>  // for move\n#include <cmath>  // for fabs\n#include <iomanip>  // for operator<<\n#include <limits>  // for numeric_...\n#include <ostream>  // for operator<<\n#include <string>  // for allocator\n\nusing namespace mrpt;\nusing namespace mrpt::math;\nusing namespace mrpt::poses;\n\nIMPLEMENTS_SERIALIZABLE(CPose3D, CSerializable, mrpt::poses)\n\n/*---------------------------------------------------------------\n\tConstructors\n  ---------------------------------------------------------------*/\nCPose3D::CPose3D()\n{\n\tm_coords[0] = m_coords[1] = m_coords[2] = 0;\n\tm_ROT.setIdentity();\n}\n\nCPose3D::CPose3D(\n\tconst double x, const double y, const double z, const double yaw,\n\tconst double pitch, const double roll)\n\t: m_ROT(UNINITIALIZED_MATRIX), m_ypr_uptodate(false)\n{\n\tsetFromValues(x, y, z, yaw, pitch, roll);\n}\n\nCPose3D::CPose3D(const mrpt::math::TPose3D& o) : m_ypr_uptodate(false)\n{\n\tsetFromValues(o.x, o.y, o.z, o.yaw, o.pitch, o.roll);\n}\n\nCPose3D::CPose3D(const CPose2D& p) : m_ypr_uptodate(false)\n{\n\tsetFromValues(p.x(), p.y(), 0, p.phi(), 0, 0);\n}\n\nCPose3D::CPose3D(const CPoint3D& p)\n\t: m_ypr_uptodate(false), m_yaw(), m_pitch(), m_roll()\n{\n\tsetFromValues(p.x(), p.y(), p.z());\n}\n\nCPose3D::CPose3D(const math::CMatrixDouble& m)\n\t: m_ROT(UNINITIALIZED_MATRIX), m_ypr_uptodate(false)\n{\n\tASSERT_ABOVEEQ_(m.rows(), 3);\n\tASSERT_ABOVEEQ_(m.cols(), 4);\n\tfor (int r = 0; r < 3; r++)\n\t\tfor (int c = 0; c < 3; c++) m_ROT(r, c) = m(r, c);\n\tfor (int r = 0; r < 3; r++) m_coords[r] = m(r, 3);\n}\n\nCPose3D::CPose3D(const math::CMatrixDouble44& m)\n\t: m_ROT(UNINITIALIZED_MATRIX), m_ypr_uptodate(false)\n{\n\tfor (int r = 0; r < 3; r++)\n\t\tfor (int c = 0; c < 3; c++) m_ROT(r, c) = m(r, c);\n\tfor (int r = 0; r < 3; r++) m_coords[r] = m(r, 3);\n}\n\n/** Constructor from a quaternion (which only represents the 3D rotation part)\n * and a 3D displacement. */\nCPose3D::CPose3D(\n\tconst mrpt::math::CQuaternionDouble& q, const double _x, const double _y,\n\tconst double _z)\n\t: m_ROT(UNINITIALIZED_MATRIX), m_ypr_uptodate(false)\n{\n\tdouble yaw, pitch, roll;\n\tq.rpy(roll, pitch, yaw);\n\tthis->setFromValues(_x, _y, _z, yaw, pitch, roll);\n}\n\n/** Constructor from a quaternion-based full pose. */\nCPose3D::CPose3D(const CPose3DQuat& p)\n\t: m_ROT(UNINITIALIZED_MATRIX), m_ypr_uptodate(false)\n{\n\t// Extract XYZ + ROT from quaternion:\n\tm_coords[0] = p.x();\n\tm_coords[1] = p.y();\n\tm_coords[2] = p.z();\n\tp.quat().rotationMatrixNoResize(m_ROT);\n}\n\nuint8_t CPose3D::serializeGetVersion() const { return 3; }\nvoid CPose3D::serializeTo(mrpt::serialization::CArchive& out) const\n{\n\t// v2 serialized the equivalent CPose3DQuat representation.\n\t// But this led to (**really** tiny) numerical differences between the\n\t// original and reconstructed poses. To ensure bit-by-bit equivalence before\n\t// and after serialization, let's get back to serializing the actual SO(3)\n\t// matrix in serialization v3:\n\tfor (int i = 0; i < 3; i++) out << m_coords[i];\n\tfor (int r = 0; r < 3; r++)\n\t\tfor (int c = 0; c < 3; c++) out << m_ROT(r, c);\n}\nvoid CPose3D::serializeFrom(mrpt::serialization::CArchive& in, uint8_t version)\n{\n\tswitch (version)\n\t{\n\t\tcase 0:\n\t\t{\n\t\t\t// The coordinates:\n\t\t\tCMatrixF HM2;\n\t\t\tin >> HM2;\n\t\t\tASSERT_(HM2.rows() == 4 && HM2.isSquare());\n\n\t\t\tm_ROT = HM2.block<3, 3>(0, 0).cast<double>();\n\n\t\t\tm_coords[0] = HM2(0, 3);\n\t\t\tm_coords[1] = HM2(1, 3);\n\t\t\tm_coords[2] = HM2(2, 3);\n\t\t}\n\t\tbreak;\n\t\tcase 1:\n\t\t{\n\t\t\t// The coordinates:\n\t\t\tCMatrixDouble44 HM;\n\t\t\tin >> HM;\n\n\t\t\tm_ROT = HM.block<3, 3>(0, 0);\n\n\t\t\tm_coords[0] = HM(0, 3);\n\t\t\tm_coords[1] = HM(1, 3);\n\t\t\tm_coords[2] = HM(2, 3);\n\t\t}\n\t\tbreak;\n\t\tcase 2:\n\t\t{\n\t\t\t// An equivalent CPose3DQuat\n\t\t\tCPose3DQuat p(UNINITIALIZED_QUATERNION);\n\t\t\tin >> p[0] >> p[1] >> p[2] >> p[3] >> p[4] >> p[5] >> p[6];\n\n\t\t\t// Extract XYZ + ROT from quaternion:\n\t\t\tm_coords[0] = p.x();\n\t\t\tm_coords[1] = p.y();\n\t\t\tm_coords[2] = p.z();\n\t\t\tp.quat().rotationMatrixNoResize(m_ROT);\n\t\t}\n\t\tbreak;\n\t\tcase 3:\n\t\t{\n\t\t\tfor (int i = 0; i < 3; i++) in >> m_coords[i];\n\t\t\tfor (int r = 0; r < 3; r++)\n\t\t\t\tfor (int c = 0; c < 3; c++) in >> m_ROT(r, c);\n\t\t}\n\t\tbreak;\n\t\tdefault:\n\t\t\tMRPT_THROW_UNKNOWN_SERIALIZATION_VERSION(version);\n\t};\n\tm_ypr_uptodate = false;\n}\n\nvoid CPose3D::serializeTo(mrpt::serialization::CSchemeArchiveBase& out) const\n{\n\tSCHEMA_SERIALIZE_DATATYPE_VERSION(1);\n\tout[\"x\"] = m_coords[0];\n\tout[\"y\"] = m_coords[1];\n\tout[\"z\"] = m_coords[2];\n\tout[\"rot\"] = CMatrixD(m_ROT);\n}\nvoid CPose3D::serializeFrom(mrpt::serialization::CSchemeArchiveBase& in)\n{\n\tuint8_t version;\n\tSCHEMA_DESERIALIZE_DATATYPE_VERSION();\n\tswitch (version)\n\t{\n\t\tcase 1:\n\t\t{\n\t\t\tm_coords[0] = static_cast<double>(in[\"x\"]);\n\t\t\tm_coords[1] = static_cast<double>(in[\"y\"]);\n\t\t\tm_coords[2] = static_cast<double>(in[\"z\"]);\n\t\t\tCMatrixD m;\n\t\t\tin[\"rot\"].readTo(m);\n\t\t\tm_ROT = m;\n\t\t}\n\t\tbreak;\n\t\tdefault:\n\t\t\tMRPT_THROW_UNKNOWN_SERIALIZATION_VERSION(version);\n\t}\n}\n\n/**  Textual output stream function.\n */\nstd::ostream& mrpt::poses::operator<<(std::ostream& o, const CPose3D& p)\n{\n\tconst std::streamsize old_pre = o.precision();\n\tconst std::ios_base::fmtflags old_flags = o.flags();\n\to << \"(x,y,z,yaw,pitch,roll)=(\" << std::fixed << std::setprecision(4)\n\t  << p.m_coords[0] << \",\" << p.m_coords[1] << \",\" << p.m_coords[2] << \",\"\n\t  << std::setprecision(2) << RAD2DEG(p.yaw()) << \"deg,\"\n\t  << RAD2DEG(p.pitch()) << \"deg,\" << RAD2DEG(p.roll()) << \"deg)\";\n\to.flags(old_flags);\n\to.precision(old_pre);\n\treturn o;\n}\n\n/*---------------------------------------------------------------\n  Implements the writing to a mxArray for Matlab\n ---------------------------------------------------------------*/\n#if MRPT_HAS_MATLAB\n// Add to implement mexplus::from template specialization\nIMPLEMENTS_MEXPLUS_FROM(mrpt::poses::CPose3D)\n#endif\n\nmxArray* CPose3D::writeToMatlab() const\n{\n#if MRPT_HAS_MATLAB\n\tconst char* fields[] = {\"R\", \"t\"};\n\tmexplus::MxArray pose_struct(\n\t\tmexplus::MxArray::Struct(sizeof(fields) / sizeof(fields[0]), fields));\n\tpose_struct.set(\"R\", mrpt::math::convertToMatlab(this->m_ROT));\n\tpose_struct.set(\"t\", mrpt::math::convertToMatlab(this->m_coords));\n\treturn pose_struct.release();\n#else\n\tTHROW_EXCEPTION(\"MRPT was built without MEX (Matlab) support!\");\n#endif\n}\n\n/*---------------------------------------------------------------\n\t\t\t\tnormalizeAngles\n---------------------------------------------------------------*/\nvoid CPose3D::normalizeAngles() { updateYawPitchRoll(); }\n/*---------------------------------------------------------------\n Set the pose from 3D point and yaw/pitch/roll angles, in radians.\n---------------------------------------------------------------*/\nvoid CPose3D::setFromValues(\n\tconst double x0, const double y0, const double z0, const double yaw,\n\tconst double pitch, const double roll)\n{\n\tm_coords[0] = x0;\n\tm_coords[1] = y0;\n\tm_coords[2] = z0;\n\tthis->m_yaw = mrpt::math::wrapToPi(yaw);\n\tthis->m_pitch = mrpt::math::wrapToPi(pitch);\n\tthis->m_roll = mrpt::math::wrapToPi(roll);\n\n\tm_ypr_uptodate = true;\n\n\trebuildRotationMatrix();\n}\n\nvoid CPose3D::rebuildRotationMatrix()\n{\n\tm_ROT = Lie::SO<3>::fromYPR(m_yaw, m_pitch, m_roll);\n}\n\n/*---------------------------------------------------------------\n\t\tScalar multiplication.\n---------------------------------------------------------------*/\nvoid CPose3D::operator*=(const double s)\n{\n\tupdateYawPitchRoll();\n\tm_coords[0] *= s;\n\tm_coords[1] *= s;\n\tm_coords[2] *= s;\n\tm_yaw *= s;\n\tm_pitch *= s;\n\tm_roll *= s;\n\trebuildRotationMatrix();\n}\n\n/*---------------------------------------------------------------\n\t\tgetYawPitchRoll\n---------------------------------------------------------------*/\nvoid CPose3D::getYawPitchRoll(double& yaw, double& pitch, double& roll) const\n{\n\tTPose3D::SO3_to_yaw_pitch_roll(m_ROT, yaw, pitch, roll);\n}\n\n/*---------------------------------------------------------------\n\t\tsphericalCoordinates\n---------------------------------------------------------------*/\nvoid CPose3D::sphericalCoordinates(\n\tconst TPoint3D& point, double& out_range, double& out_yaw,\n\tdouble& out_pitch) const\n{\n\t// Pass to coordinates as seen from this 6D pose:\n\tTPoint3D local;\n\tthis->inverseComposePoint(\n\t\tpoint.x, point.y, point.z, local.x, local.y, local.z);\n\n\t// Range:\n\tout_range = local.norm();\n\n\t// Yaw:\n\tif (local.y != 0 || local.x != 0)\n\t\tout_yaw = atan2(local.y, local.x);\n\telse\n\t\tout_yaw = 0;\n\n\t// Pitch:\n\tif (out_range != 0)\n\t\tout_pitch = -asin(local.z / out_range);\n\telse\n\t\tout_pitch = 0;\n}\n\nCPose3D CPose3D::getOppositeScalar() const\n{\n\treturn CPose3D(\n\t\t-m_coords[0], -m_coords[1], -m_coords[2], -m_yaw, -m_pitch, -m_roll);\n}\n\n/*---------------------------------------------------------------\n\t\taddComponents\n---------------------------------------------------------------*/\nvoid CPose3D::addComponents(const CPose3D& p)\n{\n\tupdateYawPitchRoll();\n\tm_coords[0] += p.m_coords[0];\n\tm_coords[1] += p.m_coords[1];\n\tm_coords[2] += p.m_coords[2];\n\tm_yaw += p.m_yaw;\n\tm_pitch += p.m_pitch;\n\tm_roll += p.m_roll;\n\trebuildRotationMatrix();\n}\n\n/*---------------------------------------------------------------\n\t\tdistanceEuclidean6D\n---------------------------------------------------------------*/\ndouble CPose3D::distanceEuclidean6D(const CPose3D& o) const\n{\n\tupdateYawPitchRoll();\n\to.updateYawPitchRoll();\n\treturn sqrt(\n\t\tsquare(o.m_coords[0] - m_coords[0]) +\n\t\tsquare(o.m_coords[1] - m_coords[1]) +\n\t\tsquare(o.m_coords[2] - m_coords[2]) +\n\t\tsquare(wrapToPi(o.m_yaw - m_yaw)) +\n\t\tsquare(wrapToPi(o.m_pitch - m_pitch)) +\n\t\tsquare(wrapToPi(o.m_roll - m_roll)));\n}\n\n/*---------------------------------------------------------------\n\t\tcomposePoint\n---------------------------------------------------------------*/\nvoid CPose3D::composePoint(\n\tdouble lx, double ly, double lz, double& gx, double& gy, double& gz,\n\tmrpt::optional_ref<mrpt::math::CMatrixDouble33> out_jacobian_df_dpoint,\n\tmrpt::optional_ref<mrpt::math::CMatrixDouble36> out_jacobian_df_dpose,\n\tmrpt::optional_ref<mrpt::math::CMatrixDouble36> out_jacobian_df_dse3,\n\tbool use_small_rot_approx) const\n{\n\t// Jacob: df/dpoint\n\tif (out_jacobian_df_dpoint) out_jacobian_df_dpoint.value().get() = m_ROT;\n\n\t// Jacob: df/dpose\n\tif (out_jacobian_df_dpose)\n\t{\n\t\tif (use_small_rot_approx)\n\t\t{\n\t\t\t// Linearized Jacobians around (yaw,pitch,roll)=(0,0,0):\n\t\t\talignas(MRPT_MAX_STATIC_ALIGN_BYTES) const double nums[3 * 6] = {\n\t\t\t\t1, 0, 0, -ly, lz, 0, 0, 1, 0, lx, 0, -lz, 0, 0, 1, 0, -lx, ly};\n\t\t\tout_jacobian_df_dpose.value().get().loadFromArray(nums);\n\t\t}\n\t\telse\n\t\t{\n\t\t\t// Exact Jacobians:\n\t\t\tupdateYawPitchRoll();\n#ifdef HAVE_SINCOS\n\t\t\tdouble cy, sy;\n\t\t\t::sincos(m_yaw, &sy, &cy);\n\t\t\tdouble cp, sp;\n\t\t\t::sincos(m_pitch, &sp, &cp);\n\t\t\tdouble cr, sr;\n\t\t\t::sincos(m_roll, &sr, &cr);\n#else\n\t\t\tconst double cy = cos(m_yaw);\n\t\t\tconst double sy = sin(m_yaw);\n\t\t\tconst double cp = cos(m_pitch);\n\t\t\tconst double sp = sin(m_pitch);\n\t\t\tconst double cr = cos(m_roll);\n\t\t\tconst double sr = sin(m_roll);\n#endif\n\n\t\t\talignas(MRPT_MAX_STATIC_ALIGN_BYTES) const double nums[3 * 6] = {\n\t\t\t\t1,\n\t\t\t\t0,\n\t\t\t\t0,\n\t\t\t\t-lx * sy * cp + ly * (-sy * sp * sr - cy * cr) +\n\t\t\t\t\tlz * (-sy * sp * cr + cy * sr),  // d_x'/d_yaw\n\t\t\t\t-lx * cy * sp + ly * (cy * cp * sr) +\n\t\t\t\t\tlz * (cy * cp * cr),  // d_x'/d_pitch\n\t\t\t\tly * (cy * sp * cr + sy * sr) +\n\t\t\t\t\tlz * (-cy * sp * sr + sy * cr),  // d_x'/d_roll\n\t\t\t\t0,\n\t\t\t\t1,\n\t\t\t\t0,\n\t\t\t\tlx * cy * cp + ly * (cy * sp * sr - sy * cr) +\n\t\t\t\t\tlz * (cy * sp * cr + sy * sr),  // d_y'/d_yaw\n\t\t\t\t-lx * sy * sp + ly * (sy * cp * sr) +\n\t\t\t\t\tlz * (sy * cp * cr),  // d_y'/d_pitch\n\t\t\t\tly * (sy * sp * cr - cy * sr) +\n\t\t\t\t\tlz * (-sy * sp * sr - cy * cr),  // d_y'/d_roll\n\t\t\t\t0,\n\t\t\t\t0,\n\t\t\t\t1,\n\t\t\t\t0,  // d_z' / d_yaw\n\t\t\t\t-lx * cp - ly * sp * sr - lz * sp * cr,  // d_z' / d_pitch\n\t\t\t\tly * cp * cr - lz * cp * sr  // d_z' / d_roll\n\t\t\t};\n\t\t\tout_jacobian_df_dpose.value().get().loadFromArray(nums);\n\t\t}\n\t}\n\n\tgx = m_ROT(0, 0) * lx + m_ROT(0, 1) * ly + m_ROT(0, 2) * lz + m_coords[0];\n\tgy = m_ROT(1, 0) * lx + m_ROT(1, 1) * ly + m_ROT(1, 2) * lz + m_coords[1];\n\tgz = m_ROT(2, 0) * lx + m_ROT(2, 1) * ly + m_ROT(2, 2) * lz + m_coords[2];\n\n\t// Jacob: df/dse3\n\tif (out_jacobian_df_dse3)\n\t{\n\t\talignas(MRPT_MAX_STATIC_ALIGN_BYTES) const double nums[3 * 6] = {\n\t\t\t1, 0, 0, 0, gz, -gy, 0, 1, 0, -gz, 0, gx, 0, 0, 1, gy, -gx, 0};\n\t\tout_jacobian_df_dse3.value().get().loadFromArray(nums);\n\t}\n}\n\nmrpt::math::TVector3D CPose3D::rotateVector(\n\tconst mrpt::math::TVector3D& l) const\n{\n\tmrpt::math::TVector3D g;\n\tg.x = m_ROT(0, 0) * l.x + m_ROT(0, 1) * l.y + m_ROT(0, 2) * l.z;\n\tg.y = m_ROT(1, 0) * l.x + m_ROT(1, 1) * l.y + m_ROT(1, 2) * l.z;\n\tg.z = m_ROT(2, 0) * l.x + m_ROT(2, 1) * l.y + m_ROT(2, 2) * l.z;\n\treturn g;\n}\n\nmrpt::math::TVector3D CPose3D::inverseRotateVector(\n\tconst mrpt::math::TVector3D& g) const\n{\n\tmrpt::math::TVector3D l;\n\tl.x = m_ROT(0, 0) * g.x + m_ROT(1, 0) * g.y + m_ROT(2, 0) * g.z;\n\tl.y = m_ROT(0, 1) * g.x + m_ROT(1, 1) * g.y + m_ROT(2, 1) * g.z;\n\tl.z = m_ROT(0, 2) * g.x + m_ROT(1, 2) * g.y + m_ROT(2, 2) * g.z;\n\treturn l;\n}\n\n// TODO: Use SSE2? OTOH, this forces mem align...\n#if MRPT_HAS_SSE2 && defined(MRPT_USE_SSE2)\n/*static inline __m128 transformSSE(const __m128* matrix, const __m128& in)\n{\n\tASSERT_(((size_t)matrix & 15) == 0);\n\t__m128 a0 = _mm_mul_ps(_mm_load_ps((float*)(matrix+0)),\n_mm_shuffle_ps(in,in,_MM_SHUFFLE(0,0,0,0)));\n\t__m128 a1 = _mm_mul_ps(_mm_load_ps((float*)(matrix+1)),\n_mm_shuffle_ps(in,in,_MM_SHUFFLE(1,1,1,1)));\n\t__m128 a2 = _mm_mul_ps(_mm_load_ps((float*)(matrix+2)),\n_mm_shuffle_ps(in,in,_MM_SHUFFLE(2,2,2,2)));\n\n\treturn _mm_add_ps(_mm_add_ps(a0,a1),a2);\n}*/\n#endif  // SSE2\n\nvoid CPose3D::asVector(vector_t& r) const\n{\n\tupdateYawPitchRoll();\n\tr[0] = m_coords[0];\n\tr[1] = m_coords[1];\n\tr[2] = m_coords[2];\n\tr[3] = m_yaw;\n\tr[4] = m_pitch;\n\tr[5] = m_roll;\n}\n\n/*---------------------------------------------------------------\n\t\tunary -\n---------------------------------------------------------------*/\nCPose3D mrpt::poses::operator-(const CPose3D& b)\n{\n\tCMatrixDouble44 B_INV(UNINITIALIZED_MATRIX);\n\tb.getInverseHomogeneousMatrix(B_INV);\n\treturn CPose3D(B_INV);\n}\n\nvoid CPose3D::getAsQuaternion(\n\tmrpt::math::CQuaternionDouble& q,\n\tmrpt::optional_ref<mrpt::math::CMatrixDouble43> out_dq_dr) const\n{\n\tupdateYawPitchRoll();\n\tmrpt::math::TPose3D(0, 0, 0, m_yaw, m_pitch, m_roll)\n\t\t.getAsQuaternion(q, out_dq_dr);\n}\n\nbool mrpt::poses::operator==(const CPose3D& p1, const CPose3D& p2)\n{\n\treturn (p1.m_coords == p2.m_coords) &&\n\t\t   ((p1.getRotationMatrix() - p2.getRotationMatrix())\n\t\t\t\t.array()\n\t\t\t\t.abs()\n\t\t\t\t.maxCoeff() < 1e-6);\n}\n\nbool mrpt::poses::operator!=(const CPose3D& p1, const CPose3D& p2)\n{\n\treturn (p1.m_coords != p2.m_coords) ||\n\t\t   ((p1.getRotationMatrix() - p2.getRotationMatrix())\n\t\t\t\t.array()\n\t\t\t\t.abs()\n\t\t\t\t.maxCoeff() >= 1e-6);\n}\n\n/*---------------------------------------------------------------\n\t\t\t\tpoint3D = pose3D + point3D\n  ---------------------------------------------------------------*/\nCPoint3D CPose3D::operator+(const CPoint3D& b) const\n{\n\treturn CPoint3D(\n\t\tm_coords[0] + m_ROT(0, 0) * b.x() + m_ROT(0, 1) * b.y() +\n\t\t\tm_ROT(0, 2) * b.z(),\n\t\tm_coords[1] + m_ROT(1, 0) * b.x() + m_ROT(1, 1) * b.y() +\n\t\t\tm_ROT(1, 2) * b.z(),\n\t\tm_coords[2] + m_ROT(2, 0) * b.x() + m_ROT(2, 1) * b.y() +\n\t\t\tm_ROT(2, 2) * b.z());\n}\n\n/*---------------------------------------------------------------\n\t\t\t\tpoint3D = pose3D + point2D\n  ---------------------------------------------------------------*/\nCPoint3D CPose3D::operator+(const CPoint2D& b) const\n{\n\treturn CPoint3D(\n\t\tm_coords[0] + m_ROT(0, 0) * b.x() + m_ROT(0, 1) * b.y(),\n\t\tm_coords[1] + m_ROT(1, 0) * b.x() + m_ROT(1, 1) * b.y(),\n\t\tm_coords[2] + m_ROT(2, 0) * b.x() + m_ROT(2, 1) * b.y());\n}\n\n/*---------------------------------------------------------------\n\t\t\t\tthis = A + B\n  ---------------------------------------------------------------*/\nvoid CPose3D::composeFrom(const CPose3D& A, const CPose3D& B)\n{\n\t// The translation part HM(0:3,3)\n\tif (this == &B)\n\t{\n\t\t// we need to make a temporary copy of the vector:\n\t\tconst CVectorFixedDouble<3> B_coords = B.m_coords;\n\t\tfor (int r = 0; r < 3; r++)\n\t\t\tm_coords[r] = A.m_coords[r] + A.m_ROT(r, 0) * B_coords[0] +\n\t\t\t\t\t\t  A.m_ROT(r, 1) * B_coords[1] +\n\t\t\t\t\t\t  A.m_ROT(r, 2) * B_coords[2];\n\t}\n\telse\n\t{\n\t\tfor (int r = 0; r < 3; r++)\n\t\t\tm_coords[r] = A.m_coords[r] + A.m_ROT(r, 0) * B.m_coords[0] +\n\t\t\t\t\t\t  A.m_ROT(r, 1) * B.m_coords[1] +\n\t\t\t\t\t\t  A.m_ROT(r, 2) * B.m_coords[2];\n\t}\n\n\t// Important: Make this multiplication AFTER the translational part, to cope\n\t// with the case when A==this\n\tm_ROT = A.m_ROT * B.m_ROT;\n\n\tm_ypr_uptodate = false;\n}\n\n/** Convert this pose into its inverse, saving the result in itself. */\nvoid CPose3D::inverse()\n{\n\tCMatrixDouble33 inv_rot(UNINITIALIZED_MATRIX);\n\tCVectorFixedDouble<3> inv_xyz;\n\n\tmrpt::math::homogeneousMatrixInverse(m_ROT, m_coords, inv_rot, inv_xyz);\n\n\tm_ROT = inv_rot;\n\tm_coords = inv_xyz;\n\tm_ypr_uptodate = false;\n}\n\n/*---------------------------------------------------------------\n\t\t\t\t\t\tisHorizontal\n ---------------------------------------------------------------*/\nbool CPose3D::isHorizontal(const double tolerance) const\n{\n\tupdateYawPitchRoll();\n\treturn (fabs(m_pitch) <= tolerance || M_PI - fabs(m_pitch) <= tolerance) &&\n\t\t   (fabs(m_roll) <= tolerance ||\n\t\t\tfabs(mrpt::math::wrapToPi(m_roll - M_PI)) <= tolerance);\n}\n\n/**  Makes \\f$ this = A \\ominus B \\f$ this method is slightly more efficient\n * than \"this= A - B;\" since it avoids the temporary object.\n *  \\note A or B can be \"this\" without problems.\n * \\sa composeFrom, composePoint\n */\nvoid CPose3D::inverseComposeFrom(const CPose3D& A, const CPose3D& B)\n{\n\t// this    =    A  (-)  B\n\t// HM_this = inv(HM_B) * HM_A\n\t//\n\t// [  R_b  | t_b ] -1   [  R_a  | t_a ]    [ R_b^t * Ra |    ..    ]\n\t// [ ------+-----]    * [ ------+-----]  = [ ---------- +----------]\n\t// [ 0 0 0 |  1  ]      [ 0 0 0 |  1  ]    [  0  0   0  |      1   ]\n\t//\n\n\t// XYZ part:\n\tCMatrixDouble33 R_b_inv(UNINITIALIZED_MATRIX);\n\tCVectorFixedDouble<3> t_b_inv;\n\tmrpt::math::homogeneousMatrixInverse(B.m_ROT, B.m_coords, R_b_inv, t_b_inv);\n\n\tfor (int i = 0; i < 3; i++)\n\t\tm_coords[i] = t_b_inv[i] + R_b_inv(i, 0) * A.m_coords[0] +\n\t\t\t\t\t  R_b_inv(i, 1) * A.m_coords[1] +\n\t\t\t\t\t  R_b_inv(i, 2) * A.m_coords[2];\n\n\t// Rot part:\n\tm_ROT = R_b_inv * A.m_ROT;\n\tm_ypr_uptodate = false;\n}\n\n/**  Computes the 3D point L such as \\f$ L = G \\ominus this \\f$.\n * \\sa composePoint, composeFrom\n */\nvoid CPose3D::inverseComposePoint(\n\tconst double gx, const double gy, const double gz, double& lx, double& ly,\n\tdouble& lz,\n\tmrpt::optional_ref<mrpt::math::CMatrixDouble33> out_jacobian_df_dpoint,\n\tmrpt::optional_ref<mrpt::math::CMatrixDouble36> out_jacobian_df_dpose,\n\tmrpt::optional_ref<mrpt::math::CMatrixDouble36> out_jacobian_df_dse3) const\n{\n\tCMatrixDouble33 R_inv(UNINITIALIZED_MATRIX);\n\tCVectorFixedDouble<3> t_inv;\n\tmrpt::math::homogeneousMatrixInverse(m_ROT, m_coords, R_inv, t_inv);\n\n\t// Jacob: df/dpoint\n\tif (out_jacobian_df_dpoint) out_jacobian_df_dpoint.value().get() = R_inv;\n\n\t// Jacob: df/dpose\n\tif (out_jacobian_df_dpose)\n\t{\n\t\t// TODO: Perhaps this and the sin/cos's can be avoided if all needed\n\t\t// terms are already in m_ROT ???\n\t\tupdateYawPitchRoll();\n\n#ifdef HAVE_SINCOS\n\t\tdouble cy, sy;\n\t\t::sincos(m_yaw, &sy, &cy);\n\t\tdouble cp, sp;\n\t\t::sincos(m_pitch, &sp, &cp);\n\t\tdouble cr, sr;\n\t\t::sincos(m_roll, &sr, &cr);\n#else\n\t\tconst double cy = cos(m_yaw);\n\t\tconst double sy = sin(m_yaw);\n\t\tconst double cp = cos(m_pitch);\n\t\tconst double sp = sin(m_pitch);\n\t\tconst double cr = cos(m_roll);\n\t\tconst double sr = sin(m_roll);\n#endif\n\n\t\tconst double m11_dy = -sy * cp;\n\t\tconst double m12_dy = cy * cp;\n\t\tconst double m13_dy = 0;\n\t\tconst double m11_dp = -cy * sp;\n\t\tconst double m12_dp = -sy * sp;\n\t\tconst double m13_dp = -cp;\n\t\tconst double m11_dr = 0;\n\t\tconst double m12_dr = 0;\n\t\tconst double m13_dr = 0;\n\n\t\tconst double m21_dy = (-sy * sp * sr - cy * cr);\n\t\tconst double m22_dy = (cy * sp * sr - sy * cr);\n\t\tconst double m23_dy = 0;\n\t\tconst double m21_dp = (cy * cp * sr);\n\t\tconst double m22_dp = (sy * cp * sr);\n\t\tconst double m23_dp = -sp * sr;\n\t\tconst double m21_dr = (cy * sp * cr + sy * sr);\n\t\tconst double m22_dr = (sy * sp * cr - cy * sr);\n\t\tconst double m23_dr = cp * cr;\n\n\t\tconst double m31_dy = (-sy * sp * cr + cy * sr);\n\t\tconst double m32_dy = (cy * sp * cr + sy * sr);\n\t\tconst double m33_dy = 0;\n\t\tconst double m31_dp = (cy * cp * cr);\n\t\tconst double m32_dp = (sy * cp * cr);\n\t\tconst double m33_dp = -sp * cr;\n\t\tconst double m31_dr = (-cy * sp * sr + sy * cr);\n\t\tconst double m32_dr = (-sy * sp * sr - cy * cr);\n\t\tconst double m33_dr = -cp * sr;\n\n\t\tconst double Ax = gx - m_coords[0];\n\t\tconst double Ay = gy - m_coords[1];\n\t\tconst double Az = gz - m_coords[2];\n\n\t\talignas(MRPT_MAX_STATIC_ALIGN_BYTES) const double nums[3 * 6] = {\n\t\t\t-m_ROT(0, 0),\n\t\t\t-m_ROT(1, 0),\n\t\t\t-m_ROT(2, 0),\n\t\t\tAx * m11_dy + Ay * m12_dy + Az * m13_dy,  // d_x'/d_yaw\n\t\t\tAx * m11_dp + Ay * m12_dp + Az * m13_dp,  // d_x'/d_pitch\n\t\t\tAx * m11_dr + Ay * m12_dr + Az * m13_dr,  // d_x'/d_roll\n\n\t\t\t-m_ROT(0, 1),\n\t\t\t-m_ROT(1, 1),\n\t\t\t-m_ROT(2, 1),\n\t\t\tAx * m21_dy + Ay * m22_dy + Az * m23_dy,  // d_x'/d_yaw\n\t\t\tAx * m21_dp + Ay * m22_dp + Az * m23_dp,  // d_x'/d_pitch\n\t\t\tAx * m21_dr + Ay * m22_dr + Az * m23_dr,  // d_x'/d_roll\n\n\t\t\t-m_ROT(0, 2),\n\t\t\t-m_ROT(1, 2),\n\t\t\t-m_ROT(2, 2),\n\t\t\tAx * m31_dy + Ay * m32_dy + Az * m33_dy,  // d_x'/d_yaw\n\t\t\tAx * m31_dp + Ay * m32_dp + Az * m33_dp,  // d_x'/d_pitch\n\t\t\tAx * m31_dr + Ay * m32_dr + Az * m33_dr,  // d_x'/d_roll\n\t\t};\n\t\tout_jacobian_df_dpose.value().get().loadFromArray(nums);\n\t}\n\n\tlx = t_inv[0] + R_inv(0, 0) * gx + R_inv(0, 1) * gy + R_inv(0, 2) * gz;\n\tly = t_inv[1] + R_inv(1, 0) * gx + R_inv(1, 1) * gy + R_inv(1, 2) * gz;\n\tlz = t_inv[2] + R_inv(2, 0) * gx + R_inv(2, 1) * gy + R_inv(2, 2) * gz;\n\n\t// Jacob: df/dse3\n\tif (out_jacobian_df_dse3)\n\t{\n\t\talignas(MRPT_MAX_STATIC_ALIGN_BYTES) const double nums[3 * 6] = {\n\t\t\t-1, 0, 0, 0, -lz, ly, 0, -1, 0, lz, 0, -lx, 0, 0, -1, -ly, lx, 0};\n\t\tout_jacobian_df_dse3.value().get().loadFromArray(nums);\n\t}\n}\n\nvoid CPose3D::setToNaN()\n{\n\tfor (int i = 0; i < 3; i++)\n\t\tfor (int j = 0; j < 3; j++)\n\t\t\tm_ROT(i, j) = std::numeric_limits<double>::quiet_NaN();\n\n\tfor (int i = 0; i < 3; i++)\n\t\tm_coords[i] = std::numeric_limits<double>::quiet_NaN();\n}\n\nmrpt::math::TPose3D CPose3D::asTPose() const\n{\n\treturn mrpt::math::TPose3D(x(), y(), z(), yaw(), pitch(), roll());\n}\n\nvoid CPose3D::fromString(const std::string& s)\n{\n\tusing mrpt::DEG2RAD;\n\tmrpt::math::CMatrixDouble m;\n\tif (!m.fromMatlabStringFormat(s))\n\t\tTHROW_EXCEPTION(\"Malformed expression in ::fromString\");\n\tASSERTMSG_(m.rows() == 1 && m.cols() == 6, \"Expected vector length=6\");\n\tthis->setFromValues(\n\t\tm(0, 0), m(0, 1), m(0, 2), DEG2RAD(m(0, 3)), DEG2RAD(m(0, 4)),\n\t\tDEG2RAD(m(0, 5)));\n}\n\nvoid CPose3D::fromStringRaw(const std::string& s)\n{\n\tthis->fromString(\"[\" + s + \"]\");\n}\n\nvoid CPose3D::getHomogeneousMatrix(mrpt::math::CMatrixDouble44& out_HM) const\n{\n\tauto M = out_HM.asEigen();\n\tM.block<3, 3>(0, 0) = m_ROT.asEigen();\n\tfor (int i = 0; i < 3; i++) out_HM(i, 3) = m_coords[i];\n\tout_HM(3, 0) = out_HM(3, 1) = out_HM(3, 2) = 0.;\n\tout_HM(3, 3) = 1.;\n}\n", "meta": {"hexsha": "8d19f2683002cfbe78dbe92fb0828c02c15292f0", "size": 24736, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/poses/src/CPose3D.cpp", "max_stars_repo_name": "NewProggie/mrpt", "max_stars_repo_head_hexsha": "4929a1d066c5e9295e50150f38d7f1f64d8964ae", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-12-10T06:24:08.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-10T06:24:08.000Z", "max_issues_repo_path": "libs/poses/src/CPose3D.cpp", "max_issues_repo_name": "YangZhengShi/mrpt", "max_issues_repo_head_hexsha": "836b840ab63f4cf22c43989930ffb4d6b130a95f", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "libs/poses/src/CPose3D.cpp", "max_forks_repo_name": "YangZhengShi/mrpt", "max_forks_repo_head_hexsha": "836b840ab63f4cf22c43989930ffb4d6b130a95f", "max_forks_repo_licenses": ["BSD-3-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.7279503106, "max_line_length": 80, "alphanum_fraction": 0.5725663001, "num_tokens": 8401, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6334102636778401, "lm_q2_score": 0.4960938294709195, "lm_q1q2_score": 0.3142309233341246}}
{"text": "/*\n * DIPlib 3.0\n * This file contains definitions of functions for adaptive Gaussian filtering.\n *\n * (c)2018, Erik Schuitema.\n * Based on original DIPlib code: (c)1995-2014, Delft University 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\n#include \"diplib/nonlinear.h\"\n#include \"diplib/framework.h\"\n#include \"diplib/generation.h\"\n#include \"diplib/overload.h\"\n#include \"diplib/pixel_table.h\"\n#include \"diplib/private/constfor.h\"\n\n#if defined(__GNUG__) || defined(__clang__)\n// For this file, turn off -Wsign-conversion, Eigen is really bad at this!\n#pragma GCC diagnostic push\n#pragma GCC diagnostic ignored \"-Wsign-conversion\"\n#pragma GCC diagnostic ignored \"-Wconversion\"\n#if __GNUC__ >= 7 || __clang_major__ >= 12\n#pragma GCC diagnostic ignored \"-Wint-in-bool-context\"\n#endif\n#if __GNUC__ >= 9\n#pragma GCC diagnostic ignored \"-Wdeprecated-copy\"\n#endif\n#endif\n\n#include <Eigen/Geometry>\n\nnamespace dip {\n\nnamespace {\n\n// KernelTransform: transforms kernel pixel coordinates according to one or more parameter images\n// The base class performs no specific transformation,\n// other than simply adding kernel coordinates to the current image coordinates\nclass KernelTransform {\n   public:\n      // Virtual destructor\n      virtual ~KernelTransform() = default;\n\n      // Clone the kernel transform. This is done when creating a copy for each thread\n      // to avoid unwanted sharing between threads of the members altered inside SetImageCoords().\n      virtual KernelTransform* Clone() const { return new KernelTransform( *this ); }\n\n      virtual void SetImageCoords( UnsignedArray const& imgCoords ) {\n         // Cast-copy\n         imgCoords_.resize( imgCoords.size() );\n         for( UnsignedArray::size_type ii = 0; ii < imgCoords.size(); ++ii ) {\n            imgCoords_[ ii ] = static_cast< dfloat >( imgCoords[ ii ] );\n         }\n         // Note for writing derived classes: perform any parameter computation or other preparation here,\n         // so it is done only once per input pixel.\n      }\n\n      // Transforms kernel coordinates to input image coordinates\n      virtual void Transform( IntegerArray const& kernelCoords, dip::uint /*tensorIndex*/, FloatArray& transformedCoords ) const {\n         transformedCoords[ 0 ] = imgCoords_[ 0 ] + static_cast< dfloat >( kernelCoords[ 0 ] );\n         transformedCoords[ 1 ] = imgCoords_[ 1 ] + static_cast< dfloat >( kernelCoords[ 1 ] );\n      }\n\n   protected:\n      FloatArray imgCoords_;\n      // Makes a quick copy of a parameter image and expands its tensor if necessary\n      static void ParamImageQuickCopyAndExpandTensor( Image const& paramImage, Image& expandedParamImage, dip::uint inputTensorElements ) {\n         expandedParamImage = paramImage.QuickCopy();\n         if( expandedParamImage.TensorElements() != inputTensorElements ) {\n            expandedParamImage.ExpandSingletonTensor( inputTensorElements );\n         }\n      }\n};\n\n// Scaling helper class\ntemplate< dip::uint nDims >\nclass KernelTransformScale {\n   public:\n      // The `kernelScale` image tensor need not be expanded beforehand\n      KernelTransformScale( Image const& kernelScale, dip::uint inputTensorElements )\n            : scaleAtImgCoords_( inputTensorElements ), inputTensorElements_( inputTensorElements ) {\n         // The kernel scale image must be a COL_MAJOR_MATRIX tensor image with the following tensor size:\n         // Rows == input tensor size (the input image has a column vector tensor)\n         // Cols == input dimensionality == kernelScaleDimensionality\n         kernelScale_ = kernelScale.QuickCopy();\n         dip::uint tensorRows = inputTensorElements;\n         dip::uint tensorCols = kernelScale.Dimensionality();\n         // See if we need to reshape the tensor\n         if( kernelScale_.TensorElements() == 1 ) {\n            // Singleton expansion to COL_MAJOR_MATRIX tensor\n            kernelScale_.ExpandSingletonTensor( tensorRows * tensorCols );\n            kernelScale_.ReshapeTensor( tensorRows, tensorCols );\n            scaleTensorLUT_ = kernelScale_.Tensor().LookUpTable();\n         } else if( kernelScale_.TensorColumns() == tensorCols && kernelScale_.TensorRows() == tensorRows ) {\n            // Dimensions are ok, only create LUT\n            scaleTensorLUT_ = kernelScale_.Tensor().LookUpTable();\n         } else if( inputTensorElements == 1 && kernelScale_.TensorShape() == Tensor::Shape::COL_VECTOR && kernelScale_.TensorRows() == tensorCols ) {\n            // The scale tensor is a col vector but must be a row vector\n            kernelScale_.ReshapeTensor( tensorRows, tensorCols );\n            scaleTensorLUT_ = kernelScale_.Tensor().LookUpTable();\n         } else if( kernelScale_.TensorColumns() == 1 && kernelScale_.TensorRows() == tensorRows ) {\n            // Only the row size matches: tensor contains a scalar per input tensor element -> create special LUT but leave the tensor itself unchanged\n            // LUT is indexed as: [col * NUM_ROWS + row]\n            scaleTensorLUT_ = kernelScale_.Tensor().LookUpTable(); // LUT for column vector\n            //kernelScale_.ExpandSingletonTensor(tensorRows * tensorCols);\n            //kernelScale_.ReshapeTensor( tensorRows, tensorCols );\n            // Complete LUT by adding the same indices for each column\n            dip::sint LUTColSize = static_cast< dip::sint >( scaleTensorLUT_.size() );\n            for( dip::uint iDim = 1; iDim < nDims; ++iDim ) {\n               scaleTensorLUT_.insert( scaleTensorLUT_.end(), scaleTensorLUT_.begin(), scaleTensorLUT_.begin() + LUTColSize );\n            }\n         } else {\n            DIP_THROW( \"Scale parameter image tensor has wrong size, must have \" + std::to_string( inputTensorElements ) + \" rows and \" + std::to_string( nDims ) + \" columns\" );\n         }\n      }\n\n      // Computes scaleAtImgCoords_.\n      // Prerequisite: SetImageCoords() must have been called to populate the image coords\n      void SetScaleAtImgCoords( UnsignedArray const& imgCoords ) {\n         // Given a tensor with `M` rows and `N` columns, tensor element `(m,n)` has the linear\n         // index given by `scaleTensorLUT_[n*M+m] = Tensor::LookUpTable()[n*M+m]`.\n         Image::Pixel scalePixel = kernelScale_.At( imgCoords );\n         for( dip::uint iTE = 0; iTE < inputTensorElements_; ++iTE ) {\n            // scaleTensorRowIndex = iTE : The scale tensor has a row for each input tensor element.\n            for( dip::uint iDim = 0; iDim < nDims; ++iDim ) {\n               // scaleTensorColIndex = iDim : The scale tensor has a column for each kernel/input dimension ( 0 for X, 1 for Y ).\n               scaleAtImgCoords_[ iTE ][ iDim ] = scalePixel[ scaleTensorLUT_[ iDim * inputTensorElements_ + iTE ]].template As< dfloat >();\n            }\n         }\n      }\n\n   protected:\n      std::vector< std::array< dfloat, nDims >> scaleAtImgCoords_; // The vector is over the input tensor elements; the array is over the kernel dimensions\n      Image kernelScale_;\n      dip::uint inputTensorElements_;\n      std::vector< dip::sint > scaleTensorLUT_;\n};\n\n// Kernel transformation: 2D rotation\nclass KernelTransform2DRotation : public KernelTransform {\n   public:\n      // The `orientation` image tensor need not be expanded beforehand\n      KernelTransform2DRotation( Image const& orientation, dip::uint inputTensorElements ) {\n         ParamImageQuickCopyAndExpandTensor( orientation, orientation_, inputTensorElements );\n         csn_.resize( inputTensorElements );\n         sn_.resize( inputTensorElements );\n      }\n\n      virtual KernelTransform* Clone() const override { return new KernelTransform2DRotation( *this ); }\n\n      virtual void SetImageCoords( UnsignedArray const& imgCoords ) override {\n         KernelTransform::SetImageCoords( imgCoords );\n         Image::Pixel dirPixel = orientation_.At( imgCoords );\n         // Iterate over tensor elements\n         for( dip::uint iTE = 0; iTE < orientation_.TensorElements(); ++iTE ) {\n            csn_[ iTE ] = std::cos( dip::pi * 0.5 - dirPixel[ iTE ].As< dfloat >() );\n            sn_[ iTE ] = std::sin( dip::pi * 0.5 - dirPixel[ iTE ].As< dfloat >() );\n         }\n      }\n\n      virtual void Transform( IntegerArray const& kernelCoords, dip::uint tensorIndex, FloatArray& transformedCoords ) const override {\n         transformedCoords[ 0 ] = imgCoords_[ 0 ] + static_cast< dfloat >( kernelCoords[ 0 ] ) * csn_[ tensorIndex ]\n                                  + static_cast< dfloat >( kernelCoords[ 1 ] ) * sn_[ tensorIndex ];\n         transformedCoords[ 1 ] = imgCoords_[ 1 ] - static_cast< dfloat >( kernelCoords[ 0 ] ) * sn_[ tensorIndex ]\n                                  + static_cast< dfloat >( kernelCoords[ 1 ] ) * csn_[ tensorIndex ];\n      }\n\n   protected:\n      std::vector< dfloat > csn_, sn_;   // Length is equal to number of input tensor elements\n      Image orientation_;\n};\n\nclass KernelTransform2DScaledRotation : public KernelTransform2DRotation, public KernelTransformScale< 2 > {\n   public:\n      // The `orientation` and `kernelScale` image tensors need not be expanded beforehand\n      KernelTransform2DScaledRotation( Image const& orientation, Image const& kernelScale, dip::uint inputTensorElements )\n            : KernelTransform2DRotation( orientation, inputTensorElements ), KernelTransformScale< 2 >( kernelScale, inputTensorElements ) {}\n\n      virtual KernelTransform* Clone() const override { return new KernelTransform2DScaledRotation( *this ); }\n\n      virtual void SetImageCoords( UnsignedArray const& imgCoords ) override {\n         KernelTransform2DRotation::SetImageCoords( imgCoords );\n         SetScaleAtImgCoords( imgCoords );\n      }\n\n      virtual void Transform( IntegerArray const& kernelCoords, dip::uint tensorIndex, FloatArray& transformedCoords ) const override {\n         // First scale, then rotate\n         dfloat scaledKernelCoords[ 2 ] = {\n               scaleAtImgCoords_[ tensorIndex ][ 0 ] * static_cast< dfloat >( kernelCoords[ 0 ] ),\n               scaleAtImgCoords_[ tensorIndex ][ 1 ] * static_cast< dfloat >( kernelCoords[ 1 ] )\n         };\n         transformedCoords[ 0 ] = imgCoords_[ 0 ] + scaledKernelCoords[ 0 ] * csn_[ tensorIndex ]\n                                  + scaledKernelCoords[ 1 ] * sn_[ tensorIndex ];\n         transformedCoords[ 1 ] = imgCoords_[ 1 ] - scaledKernelCoords[ 0 ] * sn_[ tensorIndex ]\n                                  + scaledKernelCoords[ 1 ] * csn_[ tensorIndex ];\n      }\n};\n\n// Kernel transformation: 3D rotation using phi3 and theta3\nclass KernelTransform3DRotationZ : public KernelTransform {\n   public:\n      // The `phi3` and `theta3` image tensors need not be expanded beforehand\n      KernelTransform3DRotationZ( Image const& phi3, Image const& theta3, dip::uint inputTensorElements ) {\n         ParamImageQuickCopyAndExpandTensor( phi3, phi3_, inputTensorElements );\n         ParamImageQuickCopyAndExpandTensor( theta3, theta3_, inputTensorElements );\n         R_.resize( inputTensorElements );\n      }\n\n      virtual KernelTransform* Clone() const override { return new KernelTransform3DRotationZ( *this ); }\n\n      virtual void SetImageCoords( UnsignedArray const& imgCoords ) override {\n         KernelTransform::SetImageCoords( imgCoords );\n         Image::Pixel phiPixel = phi3_.At( imgCoords );\n         Image::Pixel thetaPixel = theta3_.At( imgCoords );\n         for( dip::uint iTE = 0; iTE < phi3_.TensorElements(); ++iTE ) {\n            dfloat phi = phiPixel[ iTE ].As< dfloat >();  // TODO: handle tensor elements\n            dfloat theta = thetaPixel[ iTE ].As< dfloat >();  // TODO: handle tensor elements\n            dfloat cs_p = std::cos( phi );\n            dfloat sn_p = std::sin( phi );\n            dfloat cs_t = std::cos( theta );\n            dfloat sn_t = std::sin( theta );\n\n            RotMatrix& R = R_[ iTE ];\n            R[ 0 ] = cs_p * cs_t;   R[ 1 ] = -sn_p;   R[ 2 ] = cs_p * sn_t;\n            R[ 3 ] = sn_p * cs_t;   R[ 4 ] = cs_p;    R[ 5 ] = sn_p * sn_t;\n            R[ 6 ] = -sn_t;         R[ 7 ] = 0;       R[ 8 ] = cs_t;\n         }\n      }\n\n      virtual void Transform( IntegerArray const& kernelCoords, dip::uint tensorIndex, FloatArray& transformedCoords ) const override {\n         RotMatrix const& R = R_[ tensorIndex ];\n         transformedCoords[ 0 ] = imgCoords_[ 0 ] + static_cast< dfloat >( kernelCoords[ 0 ] ) * R[ 0 ]\n                                  + static_cast< dfloat >( kernelCoords[ 1 ] ) * R[ 1 ]\n                                  + static_cast< dfloat >( kernelCoords[ 2 ] ) * R[ 2 ];\n         transformedCoords[ 1 ] = imgCoords_[ 1 ] + static_cast< dfloat >( kernelCoords[ 0 ] ) * R[ 3 ]\n                                  + static_cast< dfloat >( kernelCoords[ 1 ] ) * R[ 4 ]\n                                  + static_cast< dfloat >( kernelCoords[ 2 ] ) * R[ 5 ];\n         transformedCoords[ 2 ] = imgCoords_[ 2 ] + static_cast< dfloat >( kernelCoords[ 0 ] ) * R[ 6 ]\n                                  + static_cast< dfloat >( kernelCoords[ 2 ] ) * R[ 8 ];\n      }\n\n   protected:\n      Image phi3_;\n      Image theta3_;\n      using RotMatrix = std::array< dfloat, 9 >;\n      std::vector< RotMatrix > R_;  // Rotation matrix. The vector is over the input tensor elements. // TODO: use Matrix class?\n};\n\n// Kernel transformation: 3D rotation using phi2, theta2, phi3 and theta3\nclass KernelTransform3DRotationXY : public KernelTransform {\n   public:\n      // The `phi2`, `theta2`, `phi3` and `theta3` image tensors need not be expanded beforehand\n      KernelTransform3DRotationXY( Image const& phi2, Image const& theta2, Image const& phi3, Image const& theta3, dip::uint inputTensorElements ) {\n         // Expand parameter images if necessary\n         ParamImageQuickCopyAndExpandTensor( phi2, phi2_, inputTensorElements );\n         ParamImageQuickCopyAndExpandTensor( theta2, theta2_, inputTensorElements );\n         ParamImageQuickCopyAndExpandTensor( phi3, phi3_, inputTensorElements );\n         ParamImageQuickCopyAndExpandTensor( theta3, theta3_, inputTensorElements );\n         T_.resize( inputTensorElements );\n      }\n\n      virtual KernelTransform* Clone() const override { return new KernelTransform3DRotationXY( *this ); }\n\n      virtual void SetImageCoords( UnsignedArray const& imgCoords ) override {\n         Image::Pixel phi2Pixel = phi2_.At( imgCoords );\n         Image::Pixel theta2Pixel = theta2_.At( imgCoords );\n         Image::Pixel phi3Pixel = phi3_.At( imgCoords );\n         Image::Pixel theta3Pixel = theta3_.At( imgCoords );\n         for( dip::uint iTE = 0; iTE < phi2_.TensorElements(); ++iTE ) {\n            dfloat phi2 = phi2Pixel[ iTE ].As< dfloat >();  // TODO: handle tensor elements\n            dfloat theta2 = theta2Pixel[ iTE ].As< dfloat >();  // TODO: handle tensor elements\n            dfloat phi3 = phi3Pixel[ iTE ].As< dfloat >();  // TODO: handle tensor elements\n            dfloat theta3 = theta3Pixel[ iTE ].As< dfloat >();  // TODO: handle tensor elements\n\n            // Create transformation matrix from basis vectors\n            Eigen::Vector3d xAxis( GetAxis( phi2, theta2 ));\n            Eigen::Vector3d yAxis( GetAxis( phi3, theta3 ));\n            Eigen::Vector3d zAxis( xAxis.cross( yAxis ).normalized() ); // TODO: do we need to normalize? Only needed if xAxis and zAxis are not perpendicular..\n            // Set rotation part\n            T_[ iTE ].linear() << xAxis, yAxis, zAxis;\n            // Set translation part\n            T_[ iTE ].translation() << Eigen::Vector3d( imgCoords_[ 0 ], imgCoords_[ 1 ], imgCoords_[ 2 ] );\n         }\n      }\n\n      virtual void Transform( IntegerArray const& /*kernelCoords*/, dip::uint tensorIndex, FloatArray& transformedCoords ) const override {\n         Eigen::Map< Eigen::Vector3d > output( transformedCoords.data() );   // Create an Eigen map that directly accesses transformedCoords\n         output = T_[ tensorIndex ] * output;\n      }\n\n   protected:\n      Eigen::Vector3d GetAxis( dfloat phi, dfloat theta ) {\n         dfloat sin_phi = std::sin( phi );\n         dfloat cos_phi = std::cos( phi );\n         dfloat sin_theta = std::sin( theta );\n         dfloat cos_theta = std::cos( theta );\n         return Eigen::Vector3d( sin_phi * cos_theta, sin_phi * sin_theta, cos_phi );\n      }\n\n      Image phi2_;\n      Image theta2_;\n      Image phi3_;\n      Image theta3_;\n      using CompactTransform = Eigen::Transform< dfloat, 3, Eigen::AffineCompact >;\n      std::vector< CompactTransform, Eigen::aligned_allocator< CompactTransform >> T_;  // Transformation matrix. The vector is over the input tensor elements.\n};\n\n// Kernel transformation: 2D skew\nclass KernelTransform2DSkew : public KernelTransform {\n   public:\n      // The `skew` image tensor need not be expanded beforehand\n      KernelTransform2DSkew( Image const& skew, dip::uint inputTensorElements ) {\n         ParamImageQuickCopyAndExpandTensor( skew, skew_, inputTensorElements );\n         s_.resize( inputTensorElements );\n      }\n\n      virtual KernelTransform* Clone() const override { return new KernelTransform2DSkew( *this ); }\n\n      virtual void SetImageCoords( UnsignedArray const& imgCoords ) override {\n         KernelTransform::SetImageCoords( imgCoords );\n         Image::Pixel skewPixel = skew_.At( imgCoords );\n         for( dip::uint iTE = 0; iTE < skew_.TensorElements(); ++iTE ) {\n            s_[ iTE ] = skewPixel[ iTE ].As< dfloat >();\n         }\n      }\n\n      virtual void Transform( IntegerArray const& kernelCoords, dip::uint tensorIndex, FloatArray& transformedCoords ) const override {\n         dfloat kernelCoordX = static_cast< dfloat >( kernelCoords[ 0 ] );\n         transformedCoords[ 0 ] = imgCoords_[ 0 ] + kernelCoordX;\n         transformedCoords[ 1 ] = imgCoords_[ 1 ] + static_cast< dfloat >( kernelCoords[ 1 ] ) + s_[ tensorIndex ] * kernelCoordX;\n      }\n\n   protected:\n      Image skew_;\n      std::vector< dfloat > s_;  // The vector is over the input tensor elements\n};\n\n// Kernel transformation: 2D banana\nclass KernelTransform2DBanana : public KernelTransform2DRotation {\n   public:\n      // The `orientation` and `hcurvature` image tensors need not be expanded beforehand\n      KernelTransform2DBanana( Image const& orientation, Image const& hcurvature, dip::uint inputTensorElements )\n            : KernelTransform2DRotation( orientation, inputTensorElements ) {\n         ParamImageQuickCopyAndExpandTensor( hcurvature, hcurvature_, inputTensorElements );\n         hcurv_.resize( inputTensorElements );\n      }\n\n      virtual KernelTransform* Clone() const override { return new KernelTransform2DBanana( *this ); }\n\n      virtual void SetImageCoords( UnsignedArray const& imgCoords ) override {\n         KernelTransform2DRotation::SetImageCoords( imgCoords );\n         Image::Pixel cPixel = hcurvature_.At( imgCoords );\n         for( dip::uint iTE = 0; iTE < orientation_.TensorElements(); ++iTE ) {\n            hcurv_[ iTE ] = -0.5 * cPixel[ iTE ].As< dfloat >();\n         }\n      }\n\n      virtual void Transform( IntegerArray const& kernelCoords, dip::uint tensorIndex, FloatArray& transformedCoords ) const override {\n         dfloat kernelCoordX = static_cast< dfloat> ( kernelCoords[ 0 ] );\n         dfloat kernelCoordY = static_cast< dfloat >( kernelCoords[ 1 ] ) + ( hcurv_[ tensorIndex ] * kernelCoordX * kernelCoordX );\n         transformedCoords[ 0 ] = imgCoords_[ 0 ] + kernelCoordX * csn_[ tensorIndex ] + kernelCoordY * sn_[ tensorIndex ];\n         transformedCoords[ 1 ] = imgCoords_[ 1 ] - kernelCoordX * sn_[ tensorIndex ] + kernelCoordY * csn_[ tensorIndex ];\n      }\n\n   protected:\n      Image hcurvature_;\n      std::vector< dfloat > hcurv_; // The vector is over the input tensor elements\n};\n\nclass KernelTransform2DScaledBanana : public KernelTransform2DBanana, public KernelTransformScale< 2 > {\n   public:\n      // The `orientation`, `hcurvature` and `kernelScale` image tensors need not be expanded beforehand\n      KernelTransform2DScaledBanana( Image const& orientation, Image const& hcurvature, Image const& kernelScale, dip::uint inputTensorElements )\n            : KernelTransform2DBanana( orientation, hcurvature, inputTensorElements ), KernelTransformScale< 2 >( kernelScale, inputTensorElements ) {}\n\n      virtual KernelTransform* Clone() const override { return new KernelTransform2DScaledBanana( *this ); }\n\n      virtual void SetImageCoords( UnsignedArray const& imgCoords ) override {\n         KernelTransform2DBanana::SetImageCoords( imgCoords );\n         SetScaleAtImgCoords( imgCoords );\n      }\n\n      virtual void Transform( IntegerArray const& kernelCoords, dip::uint tensorIndex, FloatArray& transformedCoords ) const override {\n         // First scale, then curve, then rotate\n         dfloat kernelCoordX = scaleAtImgCoords_[ tensorIndex ][ 0 ] * static_cast< dfloat >( kernelCoords[ 0 ] );\n         dfloat kernelCoordY = scaleAtImgCoords_[ tensorIndex ][ 1 ] * static_cast< dfloat >( kernelCoords[ 1 ] ) + ( hcurv_[ tensorIndex ] * kernelCoordX * kernelCoordX );\n         transformedCoords[ 0 ] = imgCoords_[ 0 ] + kernelCoordX * csn_[ tensorIndex ] + kernelCoordY * sn_[ tensorIndex ];\n         transformedCoords[ 1 ] = imgCoords_[ 1 ] - kernelCoordX * sn_[ tensorIndex ] + kernelCoordY * csn_[ tensorIndex ];\n      }\n};\n\n// Input interpolation class\ntemplate< typename TPI, typename TPO >\nclass InputInterpolator {\n   public:\n      explicit InputInterpolator( Image const& in )\n            : in_( in ), inOrigin_( static_cast< TPI* >( in_.Origin() )), inTensorStride_( in_.TensorStride() ) {}\n\n      virtual ~InputInterpolator() = default;\n\n      virtual TPO GetInputValue( FloatArray& /*coords*/, dip::uint /*tensorIndex*/, bool /*mirrorAtImageBoundaries*/ ) const { return 0; }\n\n   protected:\n      // Maps coords to a location inside the image using mirroring at the image boundaries.\n      // Returns false if coordinates don't fall inside the image even after mirroring.\n      template< dip::uint nDims >\n      bool MapCoords_Mirror( dfloat* coords ) const {\n         // Make sure all coordinates are within the image. Mirror at the boundaries.\n         for( dip::uint iDim = 0; iDim < nDims; ++iDim ) {\n            const dfloat cMax = static_cast< dfloat >( in_.Size( iDim ) - 1 );\n            dfloat& c = coords[ iDim ];\n            if( c < 0 ) {\n               c = -c;\n               if( c > cMax ) {\n                  return false; // Mirroring exceeds border\n               }\n            } else if( c > cMax ) {\n               c = cMax - ( c - cMax );\n               if( c < 0 ) {\n                  return false; // Mirroring exceeds border\n               }\n            }\n         }\n         return true;\n      }\n\n      Image const& in_; // Input image\n      TPI* inOrigin_;   // Input image origin\n      dip::sint inTensorStride_;   // Input image tensor stride\n};\n\n// Input interpolation class, templated in the number of input dimensions\ntemplate< dip::uint nDims, typename TPI, typename TPO >\nclass InputInterpolatorFixedDims : public InputInterpolator< TPI, TPO > {\n   public:\n      explicit InputInterpolatorFixedDims( Image const& in ) : InputInterpolator< TPI, TPO >( in ) {\n         // Verify input dimensionality\n         DIP_THROW_IF( in_.Dimensionality() != nDims, \"Interpolation dimensionality incorrect\" );\n         // Cache strides and sizes\n         for( dip::uint iDim = 0; iDim < nDims; ++iDim ) {\n            inStrides_[ iDim ] = in_.Stride( iDim );\n            inSizes_[ iDim ] = in_.Size( iDim );\n         }\n      }\n\n   protected:\n      using InputInterpolator< TPI, TPO >::in_;\n      std::array< dip::sint, nDims > inStrides_;\n      std::array< dip::uint, nDims > inSizes_;\n};\n\n\n// Zero order hold input interpolator\ntemplate< dip::uint nDims, typename TPI, typename TPO >\nclass InputInterpolatorZOH : public InputInterpolatorFixedDims< nDims, TPI, TPO > {\n   public:\n      explicit InputInterpolatorZOH( Image const& in ) : InputInterpolatorFixedDims< nDims, TPI, TPO >( in ) {}\n\n      // Get zero-order-hold input value at floating point coordinates, arbitrary input dimensionality\n      TPO GetInputValue( FloatArray& coords, dip::uint tensorIndex, bool mirrorAtImageBoundaries ) const override {\n         // If not mirroring at the image boundaries, the input value is considered 0 outside the image\n         if( !mirrorAtImageBoundaries ) {\n            if( !in_.IsInside( coords )) {\n               return 0;\n            }\n         } else {\n            // Mirror input coordinates. May fail -> return 0.\n            if( !this->template MapCoords_Mirror< nDims >( &coords[ 0 ] )) {\n               return 0;\n            }\n         }\n\n         // Compute pixel offset\n         dip::sint pixelOffset = 0;\n         for( dip::uint iDim = 0; iDim < nDims; ++iDim ) {\n            dip::sint integerCoord = floor_cast( coords[ iDim ] );\n            pixelOffset += integerCoord * inStrides_[ iDim ];\n         }\n\n         // Add tensor offset\n         pixelOffset += static_cast< dip::sint >( tensorIndex ) * inTensorStride_;\n\n         // Output single input value\n         TPI inValue = *( inOrigin_ + pixelOffset );\n         return static_cast< TPO >(inValue);\n      }\n\n      using InputInterpolatorFixedDims< nDims, TPI, TPO >::inStrides_;\n      using InputInterpolator< TPI, TPO >::inTensorStride_;\n      using InputInterpolator< TPI, TPO >::inOrigin_;\n      using InputInterpolator< TPI, TPO >::in_;\n};\n\n// First order hold input interpolator\ntemplate< dip::uint nDims, typename TPI, typename TPO >\nclass InputInterpolatorFOH : public InputInterpolatorFixedDims< nDims, TPI, TPO > {\n   public:\n      explicit InputInterpolatorFOH( Image const& in ) : InputInterpolatorFixedDims< nDims, TPI, TPO >( in ) {}\n\n      // Get linearly interpolated input value at floating point coordinates, arbitrary input dimensionality\n      TPO GetInputValue( FloatArray& coords, dip::uint tensorIndex, bool mirrorAtImageBoundaries ) const override {\n         using InputAsFloat = FloatType< TPI >;\n\n         // If not mirroring at the image boundaries, the input value is considered 0 outside the image\n         if( !mirrorAtImageBoundaries ) {\n            if( !in_.IsInside( coords )) {\n               return 0;\n            }\n         } else {\n            // Mirror input coordinates. May fail -> return 0.\n            if( !this->template MapCoords_Mirror< nDims >( &coords[ 0 ] )) {\n               return 0;\n            }\n         }\n\n         // Start linear interpolation\n         // Compute lower bound index and interpolation factor for all coordinates\n         //  E.g.: if coords[i] == 1.1, then loBoundIndices[i] == 1.0 and factors[i] == 0.1\n         std::array< dip::sint, nDims > loBoundIndices;\n         std::array< InputAsFloat, nDims > factors; // Linear interpolation factors\n         for( dip::uint iDim = 0; iDim < nDims; ++iDim ) {\n            loBoundIndices[ iDim ] = floor_cast( coords[ iDim ] );   // Take lower bound using floor_cast\n            if( loBoundIndices[ iDim ] == static_cast< dip::sint >( inSizes_[ iDim ] - 1 )) { // Because we interpolate between loBound and loBound+1, make sure we don't go beyond the image borders\n               loBoundIndices[ iDim ]--;\n            }\n            factors[ iDim ] = static_cast< InputAsFloat >( coords[ iDim ] ) - static_cast< InputAsFloat >( loBoundIndices[ iDim ] );\n         }\n\n         // Compute pixel offset for first pixel of the interpolation input window, including tensor offset\n         dip::sint interpOriginOffset = 0;\n         for( dip::uint iDim = 0; iDim < nDims; ++iDim ) {\n            interpOriginOffset += loBoundIndices[ iDim ] * inStrides_[ iDim ];\n         }\n\n         // Compute pixel offsets and composite interpolation factors for a total of 2 ^ nDims pixels\n         // We can avoid an ND-loop by exploiting the fact that only 2 coordinates are processed per dimension.\n         constexpr dip::uint numInterpPixels = dip::uint( 1 ) << nDims;\n\n         TPO result = 0.0;\n         //for( dip::uint iOffset = 0; iOffset < numInterpPixels; ++iOffset ) {\n         const_for< numInterpPixels >(\n               [ & ]( dip::uint iOffset ) {\n                  dip::sint pixelOffset = interpOriginOffset;\n                  InputAsFloat pixelFactor = 1.0;\n                  //for( dip::uint iDim = 0; iDim < nDims; ++iDim ) {\n                  const_for< nDims >(\n                        [ & ]( dip::uint iDim ) {\n                           // To process all permutations of lowerbound and upperbound (= lowerbound + 1) in each dimension,\n                           // decide whether to process the upperbound in this dimension by testing the bits in iOffset\n                           bool useUpperBound = ( iOffset & ( dip::uint( 1 ) << iDim )) != 0;\n                           if( useUpperBound ) {\n                              pixelOffset += inStrides_[ iDim ];\n                              pixelFactor *= factors[ iDim ];\n                           } else {\n                              pixelFactor *= 1 - factors[ iDim ];\n                           }\n                        } );\n                  // Add tensor offset\n                  pixelOffset += static_cast< dip::sint >( tensorIndex ) * inTensorStride_;\n                  // Multiply pixel input values with composite interpolation factors\n                  TPI inValue = *( inOrigin_ + pixelOffset );\n                  result += static_cast< TPO >(inValue) * pixelFactor;\n               } );\n\n         return result;\n      }\n\n      /*\n      // GetInputValue_LinearInterpolation() 2D reference implementation for speed comparison\n      TPO GetInputValue_LinearInterpolation_2D( FloatArray& coords, bool mirrorAtImageBoundaries ) const {\n         using InputAsFloat = FloatType< TPI >;\n         assert( in_.Dimensionality() == nDims );\n\n         // Cache strides\n         std::array< dip::sint, 2 > strides = { in_.Stride( 0 ), in_.Stride( 1 ) };\n\n         // If not mirroring at the image boundaries, the input value is considered 0 outside the image\n         if( !mirrorAtImageBoundaries ) {\n            if( !in_.IsInside( coords ) )\n               return 0;\n         } else {\n            // Mirror input coordinates. May fail -> return 0.\n            if( !this->template MapCoords_Mirror< 2 >( &coords[ 0 ] ) )\n               return 0;\n         }\n\n         // Start linear interpolation\n         // Compute lower bound index and interpolation factor for all coordinates\n         //  E.g.: if coords[i] == 1.1, then loBoundIndices[i] == 1.0 and factors[i] == 0.1\n         std::array< dip::uint, 2> loBoundIndices;\n         for( dip::uint iDim = 0; iDim < 2; ++iDim ) {\n            loBoundIndices[ iDim ] = (floor_cast( coords[ iDim ] ));   // Take lower bound using floor_cast\n            if( coords[ iDim ] == in_.Size( iDim ) - 1 )  // Because we interpolate between loBound and loBound+1, make sure we don't go beyond the image borders\n               loBoundIndices[ iDim ]--;\n         }\n\n         // Compute pixel offset of p00\n         dip::sint offset = loBoundIndices[ 0 ] * strides[ 0 ] + loBoundIndices[ 1 ] * strides[ 1 ];\n\n         TPI* origin = static_cast<TPI*>(in_.Origin());\n         TPO p00 = static_cast<TPO>(*(origin + offset));\n         TPO p01 = static_cast<TPO>(*(origin + offset + strides[ 1 ]));\n         TPO p10 = static_cast<TPO>(*(origin + offset + strides[ 0 ]));\n         TPO p11 = static_cast<TPO>(*(origin + offset + strides[ 0 ] + strides[ 1 ]));\n         InputAsFloat xo = coords[ 0 ] - loBoundIndices[ 0 ];\n         InputAsFloat yo = coords[ 1 ] - loBoundIndices[ 1 ];\n         InputAsFloat xs = 1 - xo;\n         InputAsFloat ys = 1 - yo;\n\n         return (TPO)((p00 * xs * ys)\n            + (p10 * xo * ys)\n            + (p01 * xs * yo)\n            + (p11 * xo * yo));\n      }\n      */\n\n      using InputInterpolatorFixedDims< nDims, TPI, TPO >::inSizes_;\n      using InputInterpolatorFixedDims< nDims, TPI, TPO >::inStrides_;\n      using InputInterpolator< TPI, TPO >::inTensorStride_;\n      using InputInterpolator< TPI, TPO >::inOrigin_;\n      using InputInterpolator< TPI, TPO >::in_;\n};\n\n// The adaptive window convolution filter for adaptive gauss and its variants\ntemplate< typename TPI, typename TPO = FlexType< TPI >>\nclass AdaptiveWindowConvolutionLineFilter : public Framework::FullLineFilter {\n   public:\n      AdaptiveWindowConvolutionLineFilter( Image const& in, Kernel const& kernel, ImageArray const& params, String const& interpolation, BoundaryCondition bc, String const& transform )\n            : in_( in ), kernel_( kernel ) {\n         // Determine kernel transformation\n         if( in_.Dimensionality() == 2 ) {\n            // === 2D ===\n            // Construct input interpolator\n            ConstructInputInterpolator< 2 >( in, interpolation );\n\n            // Construct kernel transformation\n            ConstructKernelTransform2D( transform, params, in.TensorElements() );\n\n         } else if( in_.Dimensionality() == 3 ) {\n            // === 3D ===\n            // Construct input interpolator\n            ConstructInputInterpolator< 3 >( in, interpolation );\n\n            // Determine kernel transformation\n            ConstructKernelTransform3D( transform, params, in.TensorElements() );\n         } else {\n            DIP_THROW( \"No transform \\\"\" + transform + \"\\\" known for input dimensionality \" + std::to_string( in_.Dimensionality() ));\n         }\n\n         // Store boundary condition. We only support mirroring or zeros for now.\n         DIP_THROW_IF( bc != BoundaryCondition::SYMMETRIC_MIRROR && bc != BoundaryCondition::ADD_ZEROS, \"Unsupported boundary condition\" );\n         mirrorAtInputBoundaries_ = ( bc == BoundaryCondition::SYMMETRIC_MIRROR );\n      }\n\n      virtual void SetNumberOfThreads( dip::uint numThreads, PixelTableOffsets const& pixelTable ) override {\n         offsets_ = pixelTable.Offsets();\n         kernelTransforms_.resize( numThreads - 1 );  // kernelTransform_ is used for thread 0\n      }\n\n      virtual void Filter( Framework::FullLineFilterParameters const& params ) override {\n         TPI* in = static_cast< TPI* >( params.inBuffer.buffer );\n         dip::sint inStride = params.inBuffer.stride;\n         TPO* out = static_cast< TPO* >( params.outBuffer.buffer );\n         dip::sint outStride = params.outBuffer.stride;\n         dip::sint outTensorStride = params.outBuffer.tensorStride;\n         dip::uint length = params.bufferLength;\n         PixelTableOffsets const& pixelTableOffsets = params.pixelTable;\n         std::vector< dfloat > const& weights = pixelTableOffsets.Weights();\n         UnsignedArray inCoords( params.position );\n         PixelTable pixelTable = kernel_.PixelTable( in_.Dimensionality(), params.dimension );  // TODO: move to constructor\n         FloatArray transformedKernelCoords( in_.Dimensionality() );\n\n         // Obtain kernel transform for this thread\n         std::unique_ptr< KernelTransform >& kernelTransform = params.thread == 0 ? kernelTransform_ : kernelTransforms_[ params.thread - 1 ];\n         // Clone kernelTransform_ for this thread if not done already.\n         // Needed because the KernelTransform computes and stores values per input pixel and uses those repeatedly for each kernel element.\n         if( !kernelTransform ) {\n            kernelTransform.reset( kernelTransform_->Clone() );\n         }\n\n         for( dip::uint ii = 0; ii < length; ++ii ) {\n            for( dip::uint iTE = 0; iTE < in_.TensorElements(); ++iTE ) {\n               *( out + static_cast< dip::sint >( iTE ) * outTensorStride ) = 0;\n            }\n            auto itWeight = weights.begin();\n            // Prepare kernel transform for current input coordinates\n            kernelTransform->SetImageCoords( inCoords );\n            // Apply kernel\n            for( PixelTable::iterator itPT = pixelTable.begin(); itPT != pixelTable.end(); ++itPT ) {\n               for( dip::uint iTE = 0; iTE < in_.TensorElements(); ++iTE ) {\n                  // Apply kernel transformation\n                  kernelTransform->Transform( *itPT, iTE, transformedKernelCoords );\n                  // Obtain input value at the transformed kernel coords\n                  *( out + static_cast< dip::sint >( iTE ) * outTensorStride ) +=\n                        inputInterpolator_->GetInputValue( transformedKernelCoords, iTE, mirrorAtInputBoundaries_ ) * static_cast< FloatType< TPO >>( *itWeight );\n               }\n               ++itWeight;\n            }\n            // Prepare next buffer element\n            inCoords[ params.dimension ]++;\n            in += inStride;\n            out += outStride;\n         }\n      }\n\n   private:\n      template< dip::uint nDims >\n      void ConstructInputInterpolator( Image const& in, String const& interpolation ) {\n         // Determine input interpolator\n         if( interpolation == S::ZERO_ORDER ) {\n            inputInterpolator_ = std::make_unique< InputInterpolatorZOH< nDims, TPI, TPO >>( in );\n         } else if( interpolation == S::LINEAR ) {\n            inputInterpolator_ = std::make_unique< InputInterpolatorFOH< nDims, TPI, TPO >>( in );\n         } else {\n            DIP_THROW( \"Unknown interpolation \\\"\" + interpolation + \"\\\"\" );\n         }\n      }\n\n      void ConstructKernelTransform2D( String const& transform, ImageArray const& params, dip::uint inputTensorElements ) {\n         // Determine kernel transformation\n         if( transform == \"none\" ) {\n            kernelTransform_ = std::make_unique< KernelTransform >();\n         } else if( transform == \"ellipse\" ) {\n            if( params.size() == 1 ) {\n               kernelTransform_ = std::make_unique< KernelTransform2DRotation >( params[ 0 ], inputTensorElements );\n            } else if( params.size() == 2 ) {\n               kernelTransform_ = std::make_unique< KernelTransform2DScaledRotation >( params[ 0 ], params[ 1 ], inputTensorElements );\n            } else {\n               DIP_THROW( E::ARRAY_PARAMETER_WRONG_LENGTH );\n            }\n         } else if( transform == \"banana\" ) {\n            if( params.size() == 2 ) {\n               kernelTransform_ = std::make_unique< KernelTransform2DBanana >( params[ 0 ], params[ 1 ], inputTensorElements );\n            } else if( params.size() == 3 ) {\n               kernelTransform_ = std::make_unique< KernelTransform2DScaledBanana >( params[ 0 ], params[ 1 ], params[ 2 ], inputTensorElements );\n            } else {\n               DIP_THROW( E::ARRAY_PARAMETER_WRONG_LENGTH );\n            }\n         } else if( transform == \"skew\" ) {\n            DIP_THROW_IF( params.size() != 1, E::ARRAY_PARAMETER_WRONG_LENGTH );\n            kernelTransform_ = std::make_unique< KernelTransform2DSkew >( params[ 0 ], inputTensorElements );\n         } else {\n            DIP_THROW( \"Unknown 2D transform \\\"\" + transform + \"\\\"\" );\n         }\n      }\n\n      void ConstructKernelTransform3D( String const& transform, ImageArray const& params, dip::uint inputTensorElements ) {\n         if( transform == \"none\" ) {\n            kernelTransform_ = std::make_unique< KernelTransform >();\n         } else if( transform == \"ellipse\" ) {\n            if( params.size() == 2 ) {\n               kernelTransform_ = std::make_unique< KernelTransform3DRotationZ >( params[ 0 ], params[ 1 ], inputTensorElements );\n            } else if( params.size() == 4 ) {\n               kernelTransform_ = std::make_unique< KernelTransform3DRotationXY >( params[ 0 ], params[ 1 ], params[ 2 ], params[ 3 ], inputTensorElements );\n            }\n         } else {\n            DIP_THROW( \"Unknown 3D transform \\\"\" + transform + \"\\\"\" );\n         }\n      }\n\n      std::vector< dip::sint > offsets_;  // Pixel table offsets\n      Image const& in_; // Input image\n      Kernel const& kernel_;  // Kernel\n      std::unique_ptr< KernelTransform > kernelTransform_;  // Kernel transform for thread 0\n      std::vector< std::unique_ptr< KernelTransform >> kernelTransforms_; // Kernel transforms for remaining threads\n      std::unique_ptr< InputInterpolator< TPI, TPO >> inputInterpolator_; // Input interpolator\n      bool mirrorAtInputBoundaries_;   // Boundary condition: either mirror or zeros\n};\n\n} // namespace\n\n\nvoid AdaptiveFilter(\n      Image const& in,\n      ImageConstRefArray const& params,\n      Image& out,\n      FloatArray sigmas,\n      UnsignedArray const& orders,\n      dfloat truncation,\n      UnsignedArray const& exponents,\n      String const& interpolationMethod,\n      String const& boundaryCondition,\n      String const& transform\n) {\n   DIP_THROW_IF( !in.IsForged(), E::IMAGE_NOT_FORGED );\n\n   // Prepare parameter images: expand singleton dimensions, including the tensor\n   ImageArray paramImages( params.size() );\n   for( dip::uint iP = 0; iP < params.size(); ++iP ) {\n      paramImages[ iP ] = params[ iP ].get().QuickCopy();\n      paramImages[ iP ].ExpandSingletonDimensions( in.Sizes() );\n      // The param image's tensor is expanded while constructing the kernel transformation\n      // TODO: ExpandSingletonDimensions() could also be done while constructing the kernel transformation, so this loop is removed altogether\n   }\n   DIP_STACK_TRACE_THIS( ArrayUseParameter( sigmas, in.Dimensionality(), 1.0 ));\n\n   DIP_START_STACK_TRACE\n      // Create gaussian kernel\n      Kernel kernel{ CreateGauss( sigmas, orders, truncation, exponents ) };\n\n      BoundaryCondition bc = StringToBoundaryCondition( boundaryCondition );\n      DataType outputType = DataType::SuggestFlex( in.DataType() );\n      std::unique_ptr< Framework::FullLineFilter > lineFilter;\n      DIP_OVL_NEW_ALL( lineFilter, AdaptiveWindowConvolutionLineFilter, ( in, kernel, paramImages, interpolationMethod, bc, transform ), in.DataType() );\n      // We use the full framework to allow multi-threading. Its parameters prevent input or output buffering to minimize overhead. Border expansion is not used either.\n      Framework::Full( in, out, in.DataType(), outputType, outputType, in.TensorElements(), { bc }, kernel, *lineFilter, Framework::FullOption::BorderAlreadyExpanded );// for performance comparisons: +Framework::FullOption::NoMultiThreading );\n\n   DIP_END_STACK_TRACE\n}\n\nvoid AdaptiveGauss(\n      Image const& in,\n      ImageConstRefArray const& params,\n      Image& out,\n      FloatArray const& sigmas,\n      UnsignedArray const& orders,\n      dfloat truncation,\n      UnsignedArray const& exponents,\n      String const& interpolationMethod,\n      String const& boundaryCondition\n) {\n   AdaptiveFilter( in, params, out, sigmas, orders, truncation, exponents, interpolationMethod, boundaryCondition, \"ellipse\" );\n}\n\nvoid AdaptiveBanana(\n      Image const& in,\n      ImageConstRefArray const& params,\n      Image& out,\n      FloatArray const& sigmas,\n      UnsignedArray const& orders,\n      dfloat truncation,\n      UnsignedArray const& exponents,\n      String const& interpolationMethod,\n      String const& boundaryCondition\n) {\n   AdaptiveFilter( in, params, out, sigmas, orders, truncation, exponents, interpolationMethod, boundaryCondition, \"banana\" );\n}\n\n} // namespace dip\n\n#if defined(__GNUG__) || defined(__clang__)\n#pragma GCC diagnostic pop\n#endif\n", "meta": {"hexsha": "dc55dd0ae7ad3d097d82bee3a407cbf15bc130ba", "size": 43436, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/nonlinear/adaptivegauss.cpp", "max_stars_repo_name": "KDAB/diplib", "max_stars_repo_head_hexsha": "e55d56fab4982dfaeb0cc080d68e199973fec0e1", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-07-07T01:02:57.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-07T01:02:57.000Z", "max_issues_repo_path": "src/nonlinear/adaptivegauss.cpp", "max_issues_repo_name": "KDAB/diplib", "max_issues_repo_head_hexsha": "e55d56fab4982dfaeb0cc080d68e199973fec0e1", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/nonlinear/adaptivegauss.cpp", "max_forks_repo_name": "KDAB/diplib", "max_forks_repo_head_hexsha": "e55d56fab4982dfaeb0cc080d68e199973fec0e1", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 50.8023391813, "max_line_length": 243, "alphanum_fraction": 0.6342204623, "num_tokens": 10412, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6334102498375401, "lm_q2_score": 0.4960938294709195, "lm_q1q2_score": 0.31423091646803714}}
{"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 rk.hpp\n * @brief Integration of ODEs by Runge-Kutta\n * @author Ben Allanach, Alexander Voigt\n *\n * The implementation of the Runge-Kutta routines have been derived\n * from SOFTSUSY [hep-ph/0104145, Comp. Phys. Comm. 143 (2002) 305].\n */\n\n#ifndef RK_H\n#define RK_H\n\n#include <algorithm>\n#include <cmath>\n#include <functional>\n\n#include <Eigen/Core>\n\n#include \"logger.hpp\"\n#include \"error.hpp\"\n\nnamespace flexiblesusy {\n\nnamespace runge_kutta {\n\nnamespace {\n/// Returns |a| with sign of b in front\ninline double sign(double a, double b) noexcept {\n   return b >= 0 ? std::fabs(a) : -std::fabs(a);\n}\n} // anonymous namespace\n\n/// A single step of Runge Kutta (5th order), input:\n/// y and dydx (derivative of y), x is independent variable. yout is value\n/// after step. derivs is a user-supplied function\ntemplate <typename ArrayType, typename Derivs>\nvoid rungeKuttaStep(const ArrayType& y, const ArrayType& dydx, double x,\n\t\t    double h, ArrayType& yout, ArrayType& yerr, Derivs derivs)\n{\n   const double a2 = 0.2;\n   const double a3 = 0.3;\n   const double a4 = 0.6;\n   const double a5 = 1.0;\n   const double a6 = 0.875;\n   const double b21 = 0.2;\n   const double b31 = 3.0 / 40.0;\n   const double b32 = 9.0 / 40.0;\n   const double b41 = 0.3;\n   const double b42 = -0.9;\n   const double b43 = 1.2;\n   const double b51 = -11.0 / 54.0;\n   const double b52 = 2.5;\n   const double b53 = -70.0 / 27.0;\n   const double b54 = 35.0 / 27.0;\n   const double b61 = 1631.0 / 55296.0;\n   const double b62 = 175.0 / 512.0;\n   const double b63 = 575.0 / 13824.0;\n   const double b64 = 44275.0 / 110592.0;\n   const double b65 = 253.0 / 4096.0;\n   const double c1 = 37.0 / 378.0;\n   const double c3 = 250.0 / 621.0;\n   const double c4 = 125.0 / 594.0;\n   const double c6 = 512.0 / 1771.0;\n   const double dc5 = -277.00 / 14336.0;\n   const double dc1 = c1 - 2825.0 / 27648.0;\n   const double dc3 = c3 - 18575.0 / 48384.0;\n   const double dc4 = c4 - 13525.0 / 55296.0;\n   const double dc6 = c6 - 0.25;\n\n   ArrayType ytemp = b21 * h * dydx + y;\n   const ArrayType ak2 = derivs(x + a2 * h, ytemp);\n\n   // Allowing piece-wise calculating of ytemp for speed reasons\n   ytemp = y + h * (b31 * dydx + b32 * ak2);\n   const ArrayType ak3 = derivs(x + a3 * h, ytemp);\n\n   ytemp = y + h * (b41 * dydx + b42 * ak2 + b43 * ak3);\n   const ArrayType ak4 = derivs(x+a4*h,ytemp);\n\n   ytemp = y + h * (b51 * dydx + b52 * ak2 + b53 * ak3 + b54 * ak4);\n   const ArrayType ak5 = derivs(x + a5 * h, ytemp);\n\n   ytemp = y + h * (b61 * dydx + b62 * ak2 + b63 * ak3 + b64 * ak4 + b65 * ak5);\n   const ArrayType ak6 = derivs(x + a6 * h, ytemp);\n\n   yout = y + h * (c1 * dydx + c3 * ak3 + c4 * ak4 + c6 * ak6);\n   yerr = h * (dc1 * dydx + dc3 * ak3 + dc4 * ak4 + dc5 * ak5 + dc6 * ak6);\n}\n\n/// organises the variable step-size for Runge-Kutta evolution\ntemplate <typename ArrayType, typename Derivs>\ndouble odeStepper(ArrayType& y, const ArrayType& dydx, double& x, double htry,\n                  double eps, const ArrayType& yscal, Derivs derivs,\n                  int& max_step_dir)\n{\n   const double SAFETY = 0.9;\n   const double PGROW = -0.2;\n   const double PSHRNK = -0.25;\n   const double ERRCON = 1.89e-4;\n   const int n = y.size();\n   double errmax;\n   double h = htry;\n   ArrayType yerr(n);\n   ArrayType ytemp(n);\n\n   for (;;) {\n      rungeKuttaStep(y, dydx, x, h, ytemp, yerr, derivs);\n      errmax = (yerr / yscal).abs().maxCoeff(&max_step_dir);\n      errmax  /= eps;\n      if (!std::isfinite(errmax)) {\n#ifdef ENABLE_VERBOSE\n         ERROR(\"odeStepper: non-perturbative running at Q = \"\n               << std::exp(x) << \" GeV of parameter y(\" << max_step_dir\n               << \") = \" << y(max_step_dir) << \", dy(\" << max_step_dir\n               << \")/dx = \" << dydx(max_step_dir));\n#endif\n         throw NonPerturbativeRunningError(std::exp(x), max_step_dir, y(max_step_dir));\n      }\n      if (errmax <= 1.0) {\n         break;\n      }\n      const double htemp = SAFETY * h * std::pow(errmax, PSHRNK);\n      h = (h >= 0.0 ? std::max(htemp, 0.1 * h) : std::min(htemp, 0.1 * h));\n      if (x + h == x) {\n#ifdef ENABLE_VERBOSE\n         ERROR(\"At Q = \" << std::exp(x) << \" GeV \"\n               \"stepsize underflow in odeStepper in parameter y(\"\n               << max_step_dir << \") = \" << y(max_step_dir) << \", dy(\"\n               << max_step_dir << \")/dx = \" << dydx(max_step_dir));\n#endif\n         throw NonPerturbativeRunningError(std::exp(x), max_step_dir, y(max_step_dir));\n      }\n   }\n   x += h;\n   y = ytemp;\n\n   return errmax > ERRCON ? SAFETY * h * std::pow(errmax,PGROW) : 5.0 * h;\n}\n\n/// Organises integration of 1st order system of ODEs\ntemplate <typename ArrayType, typename Derivs,\n          typename Stepper = decltype(runge_kutta::odeStepper<ArrayType,Derivs>)>\nvoid integrateOdes(ArrayType& ystart, double from, double to, double eps,\n                   double h1, double hmin, Derivs derivs,\n                   Stepper rkqs = runge_kutta::odeStepper<ArrayType,Derivs>, int max_steps = 400)\n{\n   const int nvar = ystart.size();\n   const double TINY = 1.0e-16;\n   double x = from;\n   double h = sign(h1, to - from);\n   ArrayType yscal(nvar);\n   ArrayType y(ystart);\n   ArrayType dydx;\n   int max_step_dir;\n\n   for (int nstp = 0; nstp < max_steps; ++nstp) {\n      dydx = derivs(x, y);\n      yscal = y.abs() + (dydx * h).abs() + TINY;\n      if ((x + h - to) * (x + h - from) > 0.0) {\n         h = to - x;\n      }\n\n      const double hnext = rkqs(y, dydx, x, h, eps, yscal, derivs, max_step_dir);\n\n      if ((x - to) * (to - from) >= 0.0) {\n         ystart = y;\n         return;\n      }\n\n      h = hnext;\n\n      if (std::fabs(hnext) <= hmin) {\n         break;\n      }\n   }\n\n#ifdef ENABLE_VERBOSE\n   ERROR(\"Bailed out of rk.cpp:too many steps in integrateOdes\\n\"\n         \"********** Q = \" << std::exp(x) << \" *********\");\n   ERROR(\"max step in direction of \" << max_step_dir);\n   for (int i = 0; i < nvar; i++)\n      ERROR(\"y(\" << i << \") = \" << y(i) << \" dydx(\" << i <<\n            \") = \" << dydx(i));\n#endif\n\n   throw NonPerturbativeRunningError(std::exp(x), max_step_dir, y(max_step_dir));\n}\n\n} // namespace runge_kutta\n\n} // namespace flexiblesusy\n\n#endif // RK_H\n", "meta": {"hexsha": "0eec0997320378a13f8a2c38f59235c7503b9b80", "size": 6993, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "contrib/MassSpectra/flexiblesusy/src/rk.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/rk.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/rk.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": 32.9858490566, "max_line_length": 97, "alphanum_fraction": 0.5888745889, "num_tokens": 2255, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6757646010190476, "lm_q2_score": 0.4649015713733885, "lm_q1q2_score": 0.31416402489226614}}
{"text": "#include \"localization_graph.h\"\n#include \"debug_functions.h\"\n#include \"features.h\"\n#include <Eigen/src/Core/Matrix.h>\n\n#ifdef USE_OPEN3D\n    #include <Open3D/Geometry/Geometry.h>\n    #include <Open3D/Geometry/PointCloud.h>\n    #include <Open3D/Geometry/TriangleMesh.h>\n    #include <Open3D/Visualization/Utility/DrawGeometry.h>\n    #include <Open3D/IO/ClassIO/TriangleMeshIO.h>\n    #include <Open3D/IO/ClassIO/PointCloudIO.h>\n#endif\n\n#include <algorithm>\n#include <cstdint>\n// #include <fmt/format.h>\n#include <iostream>\n#include <memory>\n#include <opencv2/calib3d.hpp>\n#include <opencv2/core.hpp>\n#include <opencv2/core/base.hpp>\n#include <opencv2/core/mat.hpp>\n#include <opencv2/core/matx.hpp>\n#include <opencv2/core/types.hpp>\n#include <opencv2/highgui.hpp>\n#include <opencv2/imgcodecs.hpp>\n#include <opencv2/imgproc.hpp>\n#include <stdexcept>\n#include <utility>\n\nusing namespace k3d;\n\nLGraph::LGraph()\n#ifdef TRANSMIT_POSES\n    : stream_handle(networking::acquire_stream_handle(STREAM_IP, STREAM_PORT))\n#endif\n{\n    // double identity_vec[3*3] = { 1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0 };\n    // identity_mat = utilities::restrucure_mat<double>(identity_vec, 3, 3);\n}\n\nbool LGraph::localize_frame(std::shared_ptr<Frame> frame)\n{\n    current_frame_points.clear();\n    current_frame_point_colors.clear();\n\n\tframes.push_back(frame);\n\n    bool status = false;\n\n    // cannot localize if only 1 frame\n    if (frames.size() == 1)\n        status = true;\n\n    // localize using essential matrix decomposition\n    else if (frames.size() == 2)\n        status = localize_frame_essential(frames[0], frame);\n\n    // localize using PnP\n    else\n        status = localize_frame_pnp(frames[frames.size() - 2], frame);\n\n    // stream points and frame to the remote device\n    if (status)\n    {\n        #ifdef TRANSMIT_POSES\n        networking::stream_points_camera(current_frame_points, current_frame_point_colors, frames.back(), stream_handle);\n        #endif\n    }\n\n    return status;\n}\n\n\nbool LGraph::localize_frame_essential(const std::shared_ptr<Frame> ref_frame, std::shared_ptr<Frame> frame)\n{\n    std::vector<std::pair<uint32_t, uint32_t>> matches = \n#if defined USE_FLANN_ESSENTIAL\n        features::match_features_flann(ref_frame->descriptors, frame->descriptors);\n#else\n        features::match_features_bf_crosscheck(ref_frame->descriptors, frame->descriptors);\n#endif\n\n    matches = features::radius_distance_filter_matches(matches, ref_frame->keypoints, frame->keypoints, FEATURE_DIST_MAX_RADIUS);\n\n\n    if (matches.size() < MIN_MATCH_FEATURE_COUNT)\n        throw std::runtime_error(\"not enough feature matches: \" + std::to_string(matches.size()));\n\n    // DEBUG_visualize_matches(*ref_frame->rgb, *frame->rgb, matches, ref_frame->keypoints, frame->keypoints);\n\n    std::vector<cv::Point2f> x1, x2;\n    x1.reserve(matches.size());\n    x2.reserve(matches.size());\n\n    // populate the 2d feature position vectors\n    for (const auto& m : matches)\n    {\n        x1.push_back(ref_frame->keypoints[m.first].pt);\n        x2.push_back(frame->keypoints[m.second].pt);\n    }\n    cv::undistortPoints(x1, x1, frame->params.intr, frame->params.distortion, cv::noArray(), frame->params.intr);\n    cv::undistortPoints(x2, x2, frame->params.intr, frame->params.distortion, cv::noArray(), frame->params.intr);\n\n    cv::Mat mask;\n    const cv::Mat essential = cv::findEssentialMat(x1, x2, frame->params.intr, cv::RANSAC, 0.999, 0.11, mask);\n\n    std::cout << essential << \"\\n\";\n\n    cv::Mat local_R, local_t;\n    cv::recoverPose(essential, x1, x2, frame->params.intr, local_R, local_t, mask);\n\n    std::cout << local_R << \"\\n\\n\" << local_t << \"\\n\";\n\n    Eigen::Matrix3d dR;\n    Eigen::Vector3d dt;\n    cv::cv2eigen(local_R, dR);\n    cv::cv2eigen(local_t, dt);\n\n    frame->position = dt;\n    frame->rotation = dR;\n\n    const auto T_P = utilities::TP_from_Rt(dR.transpose(), -dR.transpose() * dt, frame->params.intr);\n    frame->transformation = T_P.first;\n    frame->projection = T_P.second;\n    cv::eigen2cv(T_P.second, frame->projection_cv);\n\n    #ifdef LOG\n    const  Eigen::AngleAxisd ax(dR);\n    std::cout << \"essential angle: \" << ax.angle() * (180. / 3.1415) << \"\\n\";\n    #endif\n\n    create_landmarks_from_matches(ref_frame, frame, matches);\n\n    // visualize_camera_tracks(true);\n\n    return true;\n}\n\nvoid LGraph::create_landmarks_from_matches(const std::shared_ptr<Frame> ref_frame, \n        const std::shared_ptr<Frame> frame, const std::vector<std::pair<uint32_t, uint32_t>>& matches)\n{\n    for (auto& m : matches)\n    {\n        Landmark lm;\n\n        lm.descriptors.push_back(features::get_individual_descriptor(ref_frame->descriptors, m.first));\n        lm.descriptors.push_back(features::get_individual_descriptor(frame->descriptors, m.second));\n\n        std::vector<cv::Point2f> x1 = { ref_frame->keypoints[m.first].pt };\n        std::vector<cv::Point2f> x2 = { frame->keypoints[m.second].pt };\n\n        cv::undistortPoints(x1, x1, frame->params.intr, ref_frame->params.distortion, cv::noArray(), ref_frame->params.intr);\n        cv::undistortPoints(x2, x2, frame->params.intr, frame->params.distortion, cv::noArray(), frame->params.intr);\n\n        lm.feature_2d_points.push_back(x1[0]);\n        lm.feature_2d_points.push_back(x2[0]);\n\n        lm.triangulate_2d_points.push_back(x1[0]);\n        lm.triangulate_2d_points.push_back(x2[0]);\n\n        lm.view_frames.push_back(ref_frame);\n        lm.view_frames.push_back(frame);\n\n        lm.triangulate_frames.push_back(ref_frame);\n        lm.triangulate_frames.push_back(frame);\n\n// use multiview triangulation. Considerably slower.\n#if false\n        const cv::Point3d new_p3d = features::triangulate_multiview_eigen(lm.triangulate_2d_points, [&lm] {\n            std::vector<Mat34> pmats;\n            for (const auto& f : lm.triangulate_frames)\n                pmats.push_back(f->projection);\n            return pmats;\n        }());\n// use 2view DLT. Fast.\n#else\n        cv::Mat p4d;\n        cv::triangulatePoints(ref_frame->projection_cv, frame->projection_cv, x1, x2, p4d);\n        const cv::Point3f new_p3d = cv::Point3f(\n                    p4d.at<float>(0, 0) / p4d.at<float>(3, 0),\n                    p4d.at<float>(1, 0) / p4d.at<float>(3, 0),\n                    p4d.at<float>(2, 0) / p4d.at<float>(3, 0));\n#endif\n\n        // if the triangulated point is behind the camera or too far away -> ignore \n        if (!utilities::point_in_front(frame->projection, Eigen::Vector3d(new_p3d.x, new_p3d.y, new_p3d.z)) ||\n            Eigen::Vector3d(new_p3d.x, new_p3d.y, new_p3d.z).norm() > TRIANGULATE_DISTANCE_OUTLIER)\n            continue;\n\n        lm.location = new_p3d;\n        const cv::Vec3b col = frame->rgb->at<cv::Vec3b>(x2[0].y, x2[0].x);\n        lm.color = Eigen::Vector3d((float)(col.val[2]) / 255.0, (float)(col.val[1]) / 255.0, (float)(col.val[0]) / 255.0);\n\n        lm.normal = frame->position - Eigen::Vector3d(new_p3d.x, new_p3d.y, new_p3d.z);\n\n        landmarks.push_back(lm);\n\n        // <feature index, landmark index>\n        frame->feature_landmark_lookup.push_back(std::make_pair(m.second, landmarks.size() - 1));\n\n        // these will be sent over the network to the remote device\n        current_frame_points.push_back(Eigen::Vector3d(new_p3d.x, new_p3d.y, new_p3d.z));\n        current_frame_point_colors.push_back(lm.color);\n    }\n}\n\nvoid LGraph::update_landmarks(const std::shared_ptr<Frame> frame, \n        std::vector<uint32_t>& feature_ids, std::vector<uint32_t>& landmark_ids)\n{\n    for (int ii = 0; ii < feature_ids.size(); ii++)\n    {\n        Landmark& lm = landmarks[landmark_ids[ii]];\n\n        // const std::vector<cv::Point2f> x1 = { lm.first_feature_point };\n        // const std::vector<cv::Point2f> x2 = { frame->keypoints[feature_ids[ii]].pt };\n\n        // cv::Mat p4d;\n        // cv::triangulatePoints(lm.first_frame->projection_cv, frame->projection_cv, x1, x2, p4d);\n        // const cv::Point3f p3d = cv::Point3f(\n        //             p4d.at<float>(0, 0) / p4d.at<float>(3, 0),\n        //             p4d.at<float>(1, 0) / p4d.at<float>(3, 0),\n        //             p4d.at<float>(2, 0) / p4d.at<float>(3, 0));\n\n        // // if the triangulated point is behind the camera -> ignore \n        // if (utilities::point_infront_of_camera(frame->projection, Eigen::Vector3d(p3d.x, p3d.y, p3d.z)) &&\n        //     Eigen::Vector3d(p3d.x, p3d.y, p3d.z).norm() < TRIANGULATE_DISTANCE_OUTLIER)\n        // {\n        //     lm.location += p3d;\n        //     lm.location /= 2.0;\n        // }\n\n        frame->feature_landmark_lookup.push_back(std::make_pair(feature_ids[ii], landmark_ids[ii]));\n        lm.descriptors.push_back(features::get_individual_descriptor(frame->descriptors, feature_ids[ii]));\n        lm.feature_2d_points.push_back(frame->keypoints[feature_ids[ii]].pt);\n        lm.view_frames.push_back(frame);\n\n        // for performance's sake skip the incremential 3d improvement\n        continue;\n\n        const Eigen::Vector3d test_p3d (lm.location.x, lm.location.y, lm.location.z);\n\n        // find a triangulatable frame\n        for (int jj = lm.triangulate_frames.size() - 1; jj >= 0; jj--)\n        {\n            const double frame_angle = utilities::calculate_triangulation_angle(lm.triangulate_frames[jj]->position, frame->position, test_p3d);\n\n            // std::cout << frame_angle << \", \" << RAD2DEG(frame_angle) << \"\\n\";\n\n            if (RAD2DEG(frame_angle) < MIN_TRIANGULATION_ANGLE)\n                continue;\n\n\n            lm.triangulate_2d_points.push_back(frame->keypoints[feature_ids[ii]].pt);\n\n            const cv::Point3d new_p3d = features::triangulate_multiview_eigen(lm.feature_2d_points, [&lm, &frame] {\n                std::vector<Mat34> pmats;\n                for (const auto& f : lm.view_frames)\n                    pmats.push_back(f->projection);\n                pmats.push_back(frame->projection);\n                return pmats;\n            }());\n\n            if (std::isnan(new_p3d.x) || std::isnan(new_p3d.y) || std::isnan(new_p3d.z) ||\n                std::isinf(new_p3d.x) || std::isinf(new_p3d.y) || std::isinf(new_p3d.z))\n            {\n                lm.triangulate_2d_points.pop_back();\n                continue;\n            }\n\n            // if the triangulated point is behind the camera or too far away -> ignore \n            if (!utilities::point_in_front(frame->projection, Eigen::Vector3d(new_p3d.x, new_p3d.y, new_p3d.z)) ||\n                Eigen::Vector3d(new_p3d.x, new_p3d.y, new_p3d.z).norm() > TRIANGULATE_DISTANCE_OUTLIER)\n            {\n                lm.triangulate_2d_points.pop_back();\n                continue;\n            }\n\n            lm.location = new_p3d;\n            lm.triangulate_frames.push_back(frame);\n\n            std::cout << ii << \" updated, \" << frame_angle << \", \" << RAD2DEG(frame_angle) << \"\\n\";\n\n            break;\n        }\n    }\n}\n\nbool LGraph::localize_frame_pnp(const std::shared_ptr<Frame> prev_frame, std::shared_ptr<Frame> frame)\n{\n    std::vector<std::pair<uint32_t, uint32_t>> matches = \n#if defined USE_FLANN\n        features::match_features_flann(prev_frame->descriptors, frame->descriptors);\n#else\n        features::match_features_bf_crosscheck(prev_frame->descriptors, frame->descriptors);\n#endif\n\n    // matches = features::radius_distance_filter_matches(matches, prev_frame->keypoints, frame->keypoints, FEATURE_DIST_MAX_RADIUS);\n    matches = homography_filter_matches(prev_frame, frame, matches);\n\n    // DEBUG_visualize_matches(*prev_frame->rgb, *frame->rgb, matches, prev_frame->keypoints, frame->keypoints);\n\n    // find landmark points for PnP\n    std::vector<cv::Point3f> lm_points;\n    std::vector<uint32_t> lm_ids;\n    std::vector<cv::Point2f> feature_points;\n    std::vector<uint32_t> feature_ids;\n\n    for (const auto& lfc : find_landmark_feature_matches(prev_frame, matches))\n    {\n        feature_points.push_back(frame->keypoints[lfc.first].pt);\n        feature_ids.push_back(lfc.first);\n\n        lm_points.push_back(landmarks[lfc.second].location);\n        lm_ids.push_back(lfc.second);\n    }\n\n    if (feature_points.size() < MIN_MATCH_FEATURE_COUNT)\n    {\n        std::cout << \"could not localize frame, not enough matches: \" << feature_points.size() << \"\\n\";\n        this->frames.pop_back();\n        return false;\n    }\n\n    cv::undistortPoints(feature_points, feature_points, frame->params.intr, frame->params.distortion, cv::noArray(), frame->params.intr);\n\n    cv::Mat rcv, tcv, rcv_mat;\n    cv::eigen2cv(prev_frame->position, tcv);\n    cv::eigen2cv(prev_frame->rotation, rcv);\n\n    std::vector<int> inliers;\n    cv::solvePnPRansac(lm_points, feature_points, frame->params.intr, frame->params.distortion, rcv, tcv, true, 1000, 8.0, 0.988, inliers);\n    cv::Rodrigues(rcv, rcv_mat);\n\n    Eigen::Matrix3d dR;\n    Eigen::Vector3d dt;\n    cv::cv2eigen(rcv_mat, dR);\n    cv::cv2eigen(tcv, dt);\n\n    frame->rotation = dR;\n    frame->position = dt;\n\n    const auto T_P = utilities::TP_from_Rt(dR.transpose(), -dR.transpose() * dt, frame->params.intr);\n    frame->transformation = T_P.first;\n    frame->projection = T_P.second;\n    cv::eigen2cv(T_P.second, frame->projection_cv);\n\n    // reject the frame if it has too high location magnitude\n    if (frame->position.norm() - prev_frame->position.norm() > FRAME_POSITION_DISTANCE_DEVIATION)\n    {\n        std::cout << \"frame rejected for having an outlier position of \" << frame->position.transpose() << \n            \" compared to the previous frame pose of \" << prev_frame->position.transpose() << \"\\n\";\n\n        frames.pop_back();\n        return false;\n    }\n\n    // update matched landmarks using lookup\n    update_landmarks(frame, feature_ids, lm_ids);\n\n    if (feature_points.size() < MIN_MATCH_TRIANGULATE_NEW_COUNT)\n    {\n        // std::cout << \"low number of active landmarks reached, creating new ones\\n\";\n        new_landmarks_standalone(frame, lm_points);\n    }\n\n    if (frames.size() % DENSE_POINTS_EVERY_NTH_FRAME == 0)\n    {\n        std::cout << \"project more points\\n\";\n        project_more_points(find_triangulatable_point_frame(frame, lm_points, MIN_TRIANGULATION_ANGLE_LIBERAL), frame);\n    }\n\n    return true;\n}\n\nvoid LGraph::project_more_points(const std::shared_ptr<Frame> ref_frame, const std::shared_ptr<Frame> frame)\n{\n    // compute dense features\n    const auto [ref_kps, ref_desc] = features::detect_features_orb(ref_frame->rgb, true);\n    const auto [frame_kps, frame_desc] = features::detect_features_orb(frame->rgb, true);\n\n    std::vector<std::pair<uint32_t, uint32_t>> matches = \n        features::match_features_flann(ref_desc, frame_desc, KNN_DISTANCE_RATIO_LIBERAL);\n\n    matches = features::radius_distance_filter_matches(matches, ref_kps, frame_kps, FEATURE_DIST_MAX_RADIUS);\n    // matches = homography_filter_matches(ref_frame, frame, matches);\n\n    // DEBUG_visualize_matches(*ref_frame->rgb, *frame->rgb, matches, ref_frame->keypoints, frame->keypoints);\n\n    std::vector<cv::Point2f> x1, x2;\n\n    for (const auto& m : matches)\n    {\n        x1.push_back(ref_kps[m.first].pt);\n        x2.push_back(frame_kps[m.second].pt);\n    }\n\n    cv::undistortPoints(x1, x1, frame->params.intr, frame->params.distortion, cv::noArray(), frame->params.intr);\n    cv::undistortPoints(x2, x2, frame->params.intr, frame->params.distortion, cv::noArray(), frame->params.intr);\n\n    cv::Mat p4ds;\n    cv::triangulatePoints(ref_frame->projection_cv, frame->projection_cv, x1, x2, p4ds);\n\n    // std::vector<Eigen::Vector3d> debug_points, debug_colors;\n\n    // loop over all triangulated points and convert from homography to cartecian\n    for (int ii = 0; ii < p4ds.cols; ii++)\n    {\n        const Eigen::Vector3d new_p3d (\n                    p4ds.at<float>(0, ii) / p4ds.at<float>(3, ii),\n                    p4ds.at<float>(1, ii) / p4ds.at<float>(3, ii),\n                    p4ds.at<float>(2, ii) / p4ds.at<float>(3, ii));\n\n        // if the triangulated point is behind the camera or too far away -> ignore \n        if (!utilities::point_in_front(frame->projection, new_p3d) || new_p3d.norm() > TRIANGULATE_DISTANCE_OUTLIER)\n            continue;\n\n        extra_3d_points.push_back(new_p3d);\n\n        const cv::Vec3b col = frame->rgb->at<cv::Vec3b>(x2[ii].y, x2[ii].x);\n        extra_3d_points_colors.push_back(Eigen::Vector3d((float)(col.val[2]) / 255.0, (float)(col.val[1]) / 255.0, (float)(col.val[0]) / 255.0));\n\n        extra_3d_points_normals.push_back(frame->position - new_p3d);\n\n        // add to streamable points\n        current_frame_points.push_back(new_p3d);\n        current_frame_point_colors.push_back(extra_3d_points_colors.back());\n\n        // debug_points.push_back(new_p3d);\n        // debug_colors.push_back(Eigen::Vector3d((float)(col.val[2]) / 255.0, (float)(col.val[1]) / 255.0, (float)(col.val[0]) / 255.0));\n    }\n\n    // auto extra_cloud = std::make_shared<open3d::geometry::PointCloud>(open3d::geometry::PointCloud(debug_points));\n    // extra_cloud->colors_ = debug_colors;\n\n    // std::shared_ptr<open3d::geometry::TriangleMesh> camera_mesh = std::make_shared<open3d::geometry::TriangleMesh>(open3d::geometry::TriangleMesh());\n    // open3d::io::ReadTriangleMeshFromOBJ(\"../assets/debug_camera_mesh.obj\", *camera_mesh, false);\n    // camera_mesh->Transform(frame->transformation);\n\n    // open3d::visualization::DrawGeometries({ extra_cloud, camera_mesh });\n}\n\nstd::vector<std::pair<uint32_t, uint32_t>> LGraph::find_landmark_feature_matches(const std::shared_ptr<Frame> ref_frame,\n        const std::vector<std::pair<uint32_t, uint32_t>>& matches)\n{\n    // <2d feature, 3d landmark>\n    std::vector<std::pair<uint32_t, uint32_t>> feature_lm_correspondences;\n    feature_lm_correspondences.reserve(std::min(matches.size(), ref_frame->feature_landmark_lookup.size()));\n\n\n    for (const auto& flm : ref_frame->feature_landmark_lookup)\n    {\n        for (const auto& match : matches)\n        {\n            // feature match was found in landmark lookup\n            if (match.first == flm.first)\n                feature_lm_correspondences.push_back(std::make_pair(match.second, flm.second));\n        }\n    }\n\n    feature_lm_correspondences.shrink_to_fit();\n    return feature_lm_correspondences;\n}\n\nstd::vector<std::pair<uint32_t, uint32_t>> LGraph::backpropagate_future_matches(const std::shared_ptr<Frame> ref_frame,\n        const std::shared_ptr<Frame> frame,\n        const std::vector<std::pair<uint32_t, uint32_t>>& matches)\n{\n    throw std::runtime_error(\"this does not work, to the surprise of absolutely no one \");\n\n    // <2d feature, 3d landmark>\n    std::vector<std::pair<uint32_t, uint32_t>> feature_lm_correspondences;\n    std::vector<uint32_t> ref_feature_ids;\n    feature_lm_correspondences.reserve(std::min(matches.size(), ref_frame->feature_landmark_lookup.size()));\n\n    // collect landmark point ids and current frame feature point ids\n    // find prev-current matched form prev-landmarks\n    for (const auto& flm : ref_frame->feature_landmark_lookup)\n    {\n        for (const auto& match : matches)\n        {\n            // feature match was found in landmark lookup\n            if (match.first == flm.first)\n            {\n                feature_lm_correspondences.push_back(std::make_pair(match.second, flm.second));\n                ref_feature_ids.push_back(match.first);\n            }\n        }\n    }\n\n    // not enough matches, backpropagate new ones\n    // if (feature_lm_correspondences.size() < MIN_MATCH_FEATURE_COUNT)\n    if (frames.size() > 5)\n    {\n        std::vector<std::pair<uint32_t, uint32_t>> new_matches;\n        std::shared_ptr<Frame> latest_frame;\n\n        // find a frame until STATISTICAL_FEATURE_COUNT condition not met\n        for (int ii = frames.size() - 4; ii >= 0; ii--)\n        {\n            latest_frame = frames[ii];\n\n            new_matches = features::match_features_flann(latest_frame->descriptors, ref_frame->descriptors);\n            new_matches = features::take_only_indexed_matches(new_matches, ref_feature_ids);\n\n            // new_matches = features::match_features_bf_crosscheck(latest_frame->descriptors, ref_desc);\n\n            // new_matches = homography_filter_matches(latest_frame, ref_frame, new_matches);\n            // new_matches = features::radius_distance_filter_matches(new_matches, ref_kps, latest_frame->keypoints, frame_kps;\n\n            // DEBUG_visualize_matches(*latest_frame->rgb, *ref_frame->rgb, new_matches, latest_frame->keypoints, ref_frame->keypoints);\n\n            // std::cout << ref_feature_ids.size() << \", \" << new_matches.size() << \", \" << matches.size() << \"\\n\";\n\n            // frame found, stop searching\n            if (new_matches.size() < 250)\n                break;\n        }\n\n        feature_lm_correspondences.shrink_to_fit();\n        create_landmarks_from_matches(latest_frame, frame, new_matches);\n\n        feature_lm_correspondences.clear();\n\n        for (const auto& flm : ref_frame->feature_landmark_lookup)\n        {\n            for (const auto& match : matches)\n            {\n                // feature match was found in landmark lookup\n                if (match.first == flm.first)\n                {\n                    feature_lm_correspondences.push_back(std::make_pair(match.second, flm.second));\n                    ref_feature_ids.push_back(match.first);\n                }\n            }\n        }\n    }\n\n    return feature_lm_correspondences;\n}\n\nvoid LGraph::new_landmarks_standalone(const std::shared_ptr<Frame> frame, const std::vector<cv::Point3f>& tr_angle_points)\n{\n    /**\n     *  - find a triangulatable frame\n     *  - match and filter features\n     *  - triangulate\n     *  - add to frame->feature_landmark_lookup\n     */\n\n    std::shared_ptr<Frame> ref_frame = find_triangulatable_point_frame(frame, tr_angle_points);\n\n    std::vector<std::pair<uint32_t, uint32_t>> matches = \n#if defined USE_FLANN\n        features::match_features_flann(ref_frame->descriptors, frame->descriptors);\n#else\n        features::match_features_bf_crosscheck(ref_frame->descriptors, frame->descriptors);\n#endif\n\n    // if (matches.size() > HOMOGRAPHY_MIN_FEATURE_COUNT)\n    //     matches = homography_filter_matches(ref_frame, frame, matches);\n    \n    matches = features::radius_distance_filter_matches(matches, ref_frame->keypoints, frame->keypoints, FEATURE_DIST_MAX_RADIUS);\n\n    // DEBUG_visualize_matches(*ref_frame->rgb, *frame->rgb, matches, ref_frame->keypoints, frame->keypoints);\n    // visualize_camera_tracks(true);\n\n    // std::cout << \"created new landmarks: \" << matches.size() << \"\\n\";\n\n    // create landmarks and add to feature_landmark_lookup\n    create_landmarks_from_matches(ref_frame, frame, matches);\n}\n\nvoid LGraph::backpropagate_new_landmarks_homography(const std::shared_ptr<Frame> frame,\n        const cv::Point3f tr_angle_point)\n{\n    // TODO: find the largest difference frame to match against\n\n    std::shared_ptr<Frame> ref_frame = nullptr;\n    const Eigen::Vector3d tr_point (tr_angle_point.x, tr_angle_point.y, tr_angle_point.z);\n\n    if (frames.size() < 4)\n        return;\n\n    for (int ii = frames.size() - 3; ii >= 0; ii--)\n    {\n        const double frame_angle = utilities::calculate_triangulation_angle(frames[ii]->position, frame->position, tr_point);\n\n        if (RAD2DEG(frame_angle) < MIN_TRIANGULATION_ANGLE)\n            continue;\n\n        ref_frame = frames[ii];\n        break;\n    }\n\n    if (!ref_frame)\n        return;\n\n    std::vector<std::pair<uint32_t, uint32_t>> matches = \n        features::match_features_bf_crosscheck(ref_frame->descriptors, frame->descriptors);\n    matches = homography_filter_matches(ref_frame, frame, matches);\n\n\n    // filter matches for already existing landmarks\n\n    std::vector<std::pair<uint32_t, uint32_t>> new_matches;\n    for (const auto& m : matches)\n    {\n        // find if the feature id already exists in teh landmark lookup\n        const auto it = std::find_if(ref_frame->feature_landmark_lookup.begin(), ref_frame->feature_landmark_lookup.end(),\n            [&m](const std::pair<uint32_t, uint32_t>& feature_landmark) {\n                return feature_landmark.first == m.first;\n            });\n\n        // the feature was not found --> create new landmarks\n        if (it == ref_frame->feature_landmark_lookup.end())\n            new_matches.push_back(m);\n    }\n\n    create_landmarks_from_matches(ref_frame, frame, new_matches);\n\n    std::cout << \"matches \" << matches.size() << \" out of \" << new_matches.size() << \"\\n\";\n\n    // DEBUG_visualize_matches(*ref_frame->rgb, *frame->rgb, matches, ref_frame->keypoints, frame->keypoints);\n    // visualize_camera_tracks(true);\n\n}\n\nstd::vector<std::pair<uint32_t, uint32_t>> LGraph::homography_filter_matches(\n        const std::shared_ptr<Frame> ref_frame, const std::shared_ptr<Frame> frame,\n        const std::vector<std::pair<uint32_t, uint32_t>>& matches)\n{\n    if (matches.size() < HOMOGRAPHY_MIN_FEATURE_COUNT)\n        throw std::runtime_error(\"not enough matches for computing homography\");\n\n    std::vector<cv::Point2f> fpoints1, fpoints2;\n    fpoints1.reserve(matches.size());\n    fpoints2.reserve(matches.size());\n\n    for (const auto& m : matches)\n    {\n        fpoints1.push_back(ref_frame->keypoints[m.first].pt);\n        fpoints2.push_back(frame->keypoints[m.second].pt);\n    }\n\n    cv::Mat homography;\n\n    homography = findHomography(fpoints1, fpoints2, cv::RANSAC, HOMOGRAPHY_RANSAC_THRESHOLD, cv::noArray());\n\n    std::vector<std::pair<uint32_t, uint32_t>> good_matches;\n    good_matches.reserve(matches.size());\n\n    for (size_t ii = 0; ii < matches.size(); ii++)\n    {\n        cv::Mat col = cv::Mat::ones(3, 1, CV_64F);\n        col.at<double>(0) = fpoints1[ii].x;\n        col.at<double>(1) = fpoints1[ii].y;\n        col = homography * col;\n        col /= col.at<double>(2);\n\n        const double dist = sqrt(pow(col.at<double>(0) - fpoints2[ii].x, 2) + pow(col.at<double>(1) - fpoints2[ii].y, 2));\n        if (dist < HOMOGRAPHY_FILTER_MAX_DIST)\n            good_matches.push_back(matches[ii]);\n    }\n\n    good_matches.shrink_to_fit();\n    return good_matches;\n}\n\n\nvoid LGraph::backpropagate_new_landmarks(const std::shared_ptr<Frame> frame,\n        const std::shared_ptr<Frame> ref_frame,\n        const std::vector<uint32_t>& ref_frame_fids_inv,\n        const std::vector<uint32_t>& current_frame_fids_inv,\n        const std::vector<std::pair<uint32_t, uint32_t>>& matches,\n        const cv::Point3f tr_angle_point)\n{\n    // traverse the frames backwards, matching the features, until\n    // a frame is found which has enough triangulatable movement\n\n    // Create a data structure for holding the to-be-triangulated (tbt) feature chains.\n    // Is also used as a lookup for pruning the triangulation list\n    std::unordered_map<uint32_t, std::vector<uint32_t>> feature_chain;\n    feature_chain.reserve(current_frame_fids_inv.size());\n\n    // used to map feature ids from frame -> last_frame\n    std::map<uint32_t, uint32_t> first_current_feature_lookup;\n\n    for (int ii = 0; ii < current_frame_fids_inv.size(); ii++)\n    {\n        feature_chain.insert(std::make_pair(current_frame_fids_inv[ii], std::vector<uint32_t> { ref_frame_fids_inv[ii] }));\n        first_current_feature_lookup.insert(std::make_pair(current_frame_fids_inv[ii], ref_frame_fids_inv[ii]));\n    }\n\n    std::vector<uint32_t> last_frame_fids = ref_frame_fids_inv;\n    cv::Mat last_frame_descriptor = features::descriptor_from_feature_ids(ref_frame->descriptors, last_frame_fids);\n    std::shared_ptr<Frame> last_frame = ref_frame;\n\n\n    // -3: -1 for size, -2 for frame, -3 for ref_frame\n    for (int ii = frames.size() - 3; ii >= 0; ii--)\n    {\n        const std::shared_ptr<Frame> current_frame = frames[ii];;\n\n        // match the current latest descriptors against a new frame\n        std::vector<std::pair<uint32_t, uint32_t>> matches = \n            features::match_features_bf_crosscheck(last_frame_descriptor, current_frame->descriptors);\n        matches = features::radius_distance_filter_matches(matches, last_frame->keypoints, current_frame->keypoints, FEATURE_DIST_MAX_RADIUS);\n\n        std::cout << \"matches size: \" << matches.size() << \"\\n\";\n\n        last_frame_fids.clear();\n\n        // populate tbt feature chain lookup\n        for (const auto& match : matches)\n        {\n            // find match.first in first_current_feature_lookup, acquire the \"key\", use the key to\n            // index into feature_chain, append match.second\n            const auto key_iter = std::find_if(\n                first_current_feature_lookup.begin(),\n                first_current_feature_lookup.end(),\n                [match](const auto& fcfl) { return fcfl.second == match.first; });\n\n            if (key_iter == first_current_feature_lookup.end())\n                continue;\n\n            const uint32_t key = key_iter->first;\n            feature_chain.at(key).push_back(match.second);\n\n            // append the current frame feature id, next iteration last frame id\n            last_frame_fids.push_back(match.second);\n        }\n\n        // check if enough triangulatable distance\n\n        // if enough movement, stop iterating and triangulate\n        throw std::runtime_error(\"todo\");\n\n        last_frame = current_frame;\n        last_frame_descriptor = features::descriptor_from_feature_ids(current_frame->descriptors, last_frame_fids);\n    }\n}\n\n\nstd::shared_ptr<Frame> LGraph::find_triangulatable_movement_frame(const std::shared_ptr<Frame> frame, const double angle_threshold)\n{\n    // use angle to find good frame\n\n    const Eigen::Vector3d current_pos = frame->position;\n\n    for (int ii = frames.size() - 2; ii >= 0; ii--)\n    {\n        const std::shared_ptr<Frame> ref_frame = frames[ii];\n\n        if ((ref_frame->position - current_pos).norm() > angle_threshold)\n            return ref_frame;\n    }\n\n    return nullptr;\n}\n\nstd::shared_ptr<Frame> LGraph::find_triangulatable_point_frame(const std::shared_ptr<Frame> frame,\n        const std::vector<cv::Point3f>& tr_angle_points, const double angle_threshold)\n{\n    const Eigen::Vector3d current_pos = frame->position;\n\n    // take the average of all of the triangulated points\n    const Eigen::Vector3d tr_point_eigen = [&tr_angle_points] {\n        cv::Point3f trp (0.0, 0.0, 0.0);\n        for (const auto& p : tr_angle_points)\n            trp += p;\n        return Eigen::Vector3d(trp.x, trp.y, trp.z) / (double)tr_angle_points.size();\n\n    }();\n\n    for (int ii = frames.size() - 2; ii >= 0; ii--)\n    {\n        const std::shared_ptr<Frame> ref_frame = frames[ii];\n\n        const double frame_angle = utilities::calculate_triangulation_angle(frames[ii]->position, frame->position, tr_point_eigen);\n\n        if (RAD2DEG(frame_angle) < angle_threshold)\n            continue;\n\n        std::cout << \"use frame id \" << ii << \" for triangulation, current frame is \" << frames.size() - 1 << \"\\n\";\n        return ref_frame;\n    }\n\n    std::cout << \"use frame id 0 for triangulation\\n\";\n    return frames[0];\n}\n\nvoid LGraph::new_landmarks_from_matched(const std::shared_ptr<Frame> ref_frame,\n        const std::shared_ptr<Frame> frame)\n{\n    std::vector<std::pair<uint32_t, uint32_t>> matches = \n        features::match_features_bf_crosscheck(ref_frame->descriptors, frame->descriptors);\n\n    matches = features::radius_distance_filter_matches(matches, ref_frame->keypoints, frame->keypoints, FEATURE_DIST_MAX_RADIUS);\n\n    std::vector<std::pair<uint32_t, uint32_t>> new_matches;\n\n    // filter matches for already existing landmarks\n    for (const auto& m : matches)\n    {\n        // find if the feature id already exists in teh landmark lookup\n        const auto it = std::find_if(ref_frame->feature_landmark_lookup.begin(), ref_frame->feature_landmark_lookup.end(),\n            [&m](const std::pair<uint32_t, uint32_t>& feature_landmark) {\n                return feature_landmark.first == m.first;\n            });\n\n        // the feature was not found --> create new landmarks\n        if (it == ref_frame->feature_landmark_lookup.end())\n            new_matches.push_back(m);\n    }\n\n    // std::cout << \"new landmarks: \" << new_matches.size() << \"\\n\";\n\n    // std::cout << ref_frame->position.transpose() << \", \" << frame->position.transpose() << \"\\n\";\n\n    create_landmarks_from_matches(ref_frame, frame, new_matches);\n}\n\n#ifdef USE_OPEN3D\nvoid LGraph::visualize_camera_tracks(const bool visualize_landmarks, bool generate_mesh) const\n{\n    std::vector<std::shared_ptr<const open3d::geometry::Geometry>> debug_cameras;\n\n    for (int ii = 0; ii < frames.size(); ii++)\n    {\n        std::cout << \"frame \" << ii << \": \" << frames[ii]->position.transpose() << \"\\n\";\n\n        std::shared_ptr<open3d::geometry::TriangleMesh> camera_mesh = std::make_shared<open3d::geometry::TriangleMesh>(open3d::geometry::TriangleMesh());\n        open3d::io::ReadTriangleMeshFromOBJ(\"../assets/debug_camera_mesh.obj\", *camera_mesh, false);\n\n        camera_mesh->Transform(frames[ii]->transformation);\n        debug_cameras.push_back(camera_mesh);\n    }\n\n    if (visualize_landmarks)\n    {\n        std::vector<Eigen::Vector3d> landmark_points;\n        std::vector<Eigen::Vector3d> landmark_colors;\n        std::vector<Eigen::Vector3d> landmark_normals;\n\n        for (const auto& lm : landmarks)\n        {\n            landmark_points.push_back(Eigen::Vector3d(lm.location.x, lm.location.y, lm.location.z));\n            landmark_colors.push_back(lm.color);\n            landmark_normals.push_back(lm.normal);\n        }\n\n        auto lms_cloud = std::make_shared<open3d::geometry::PointCloud>(open3d::geometry::PointCloud(landmark_points));\n        lms_cloud->colors_ = landmark_colors;\n        lms_cloud->normals_ = landmark_normals;\n\n        if (generate_mesh)\n        {\n            auto mesh_cloud = std::make_shared<open3d::geometry::PointCloud>(open3d::geometry::PointCloud(extra_3d_points));\n            mesh_cloud->colors_ = extra_3d_points_colors;\n            mesh_cloud->normals_ = extra_3d_points_normals;\n\n            *mesh_cloud += *lms_cloud;\n\n            // mesh_cloud->EstimateNormals(open3d::geometry::KDTreeSearchParamHybrid(0.5, 16));\n\n            auto [new_mesh, trash] = open3d::geometry::TriangleMesh::CreateFromPointCloudPoisson(*mesh_cloud, MESH_POISSON_DEPTH);\n            new_mesh = new_mesh->FilterSmoothLaplacian(LAPLACIAN_ITERATIONS, LAPLACIAN_LAMBDA);\n\n            // new_mesh->Translate(Eigen::Vector3d(0.0, 20.0, 0.0));\n\n            debug_cameras.push_back(new_mesh);\n            // debug_cameras.push_back(mesh_cloud);\n        }\n        else\n        {\n            debug_cameras.push_back(lms_cloud);\n\n            auto extra_cloud = std::make_shared<open3d::geometry::PointCloud>(open3d::geometry::PointCloud(extra_3d_points));\n            extra_cloud->colors_ = extra_3d_points_colors;\n            extra_cloud->normals_ = extra_3d_points_normals;\n            *extra_cloud += *lms_cloud;\n\n            // open3d::io::WritePointCloudToPLY(\"export_cloud.ply\", *extra_cloud);\n\n            // debug_cameras.push_back(extra_cloud);\n        }\n    }\n\n    open3d::visualization::DrawGeometries(debug_cameras, \"track visualization\", 1920, 1080);\n}\n#endif\n\n\nvoid LGraph::print_camera_tracks() const\n{\n    for (int ii = 0; ii < frames.size(); ii++)\n    {\n        std::cout << \"frame \" << ii << \": \" << frames[ii]->position.transpose() << \"\\n\";\n    }\n}\n", "meta": {"hexsha": "f465c9098b6ed2a92d8c17cbeb7dad708194f85e", "size": 35125, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/localization_graph.cpp", "max_stars_repo_name": "teo3n/BScEmbeddedLocalization", "max_stars_repo_head_hexsha": "1aa901a38decc85f152059b89a7f39e37716c521", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/localization_graph.cpp", "max_issues_repo_name": "teo3n/BScEmbeddedLocalization", "max_issues_repo_head_hexsha": "1aa901a38decc85f152059b89a7f39e37716c521", "max_issues_repo_licenses": ["MIT"], "max_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_graph.cpp", "max_forks_repo_name": "teo3n/BScEmbeddedLocalization", "max_forks_repo_head_hexsha": "1aa901a38decc85f152059b89a7f39e37716c521", "max_forks_repo_licenses": ["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.8981173865, "max_line_length": 153, "alphanum_fraction": 0.6576797153, "num_tokens": 9102, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6757646010190476, "lm_q2_score": 0.46490157137338844, "lm_q1q2_score": 0.3141640248922661}}
{"text": "/*\n * self_similarity.cpp\n *\n *  Created on: Jan 25, 2012\n *      Author: lbossard\n */\n\n#include \"self_similarity.hpp\"\n\n#include <boost/math/constants/constants.hpp>\n#include <boost/foreach.hpp>\n\nnamespace vision\n{\nnamespace features\n{\n\nSelfSimilarityExtractor::SelfSimilarityExtractor(\n        bool color_ssd,\n        unsigned int patch_size,\n        unsigned int window_radius,\n        unsigned int radius_bin_count,\n        unsigned int angle_bin_count,\n        float var_noise,\n        unsigned int auto_var_radius)\n{\n    color_ssd_ = color_ssd;\n    this->setSelfSimilarityParameters(\n            patch_size,\n            window_radius,\n            radius_bin_count,\n            angle_bin_count,\n            var_noise,\n            auto_var_radius);\n}\n\nvoid SelfSimilarityExtractor::setSelfSimilarityParameters(\n        unsigned int patch_size,\n        unsigned int window_radius,\n        unsigned int radius_bin_count,\n        unsigned int angle_bin_count,\n        float var_noise,\n        unsigned int auto_var_radius)\n{\n\n    self_similarity_.setParameters(patch_size,\n            window_radius,\n            radius_bin_count,\n            angle_bin_count,\n            var_noise,\n            auto_var_radius);\n\n}\n\n\n/*virtual*/ SelfSimilarityExtractor::~SelfSimilarityExtractor()\n{\n\n}\n\n/*virtual*/ cv::Mat_<float> SelfSimilarityExtractor::denseExtract(\n        const cv::Mat& input_image,\n        std::vector<cv::Point>& locations,\n        const cv::Mat_<uchar>& mask\n) const\n{\n    const unsigned int radius = 5;\n\n    // generate locations\n    locations.clear();\n    LowLevelFeatureExtractor::generateGridLocations(\n            input_image.size(),\n            cv::Size(radius, radius),\n            radius,\n            radius,\n            locations,\n            mask);\n    if (locations.size() == 0)\n    {\n        return cv::Mat_<float>();\n    }\n\n    // convert to gray if necessary\n    cv::Mat image = input_image;\n    if (!color_ssd_ && image.type() != CV_8U)\n    {\n        cv::cvtColor(image, image, CV_BGR2GRAY);\n    }\n\n    // allocate memroy\n    cv::Mat_<float> features(locations.size(), descriptorLength());\n\n    // loop over locations and compute descriptors\n    std::size_t point_idx = 0;\n    BOOST_FOREACH(const cv::Point& p, locations)\n    {\n        cv::Mat_<float> descriptor = features.row(point_idx);\n        if (self_similarity_.extract(image, p, descriptor))\n        {\n            ++point_idx;\n        }\n    }\n    if (point_idx == 0)\n    {\n        return cv::Mat_<float>();\n    }\n    features.resize(point_idx);\n    return features;\n}\n\n/*virtual*/ unsigned int SelfSimilarityExtractor::descriptorLength() const\n{\n    return self_similarity_.descriptorLength();\n}\n////////////////////////////////////////////////////////////////////////////////\n/**\n *\n * @param patch_size       odd\n * @param window_radius    even\n * @param radius_bin_count\n * @param angle_bin_count\n * @param var_noise\n * @param auto_var_radius\n */\nSelfSimilarity::SelfSimilarity(\n        unsigned int patch_size,\n        unsigned int window_radius,\n        unsigned int radius_bin_count,\n        unsigned int angle_bin_count,\n        float var_noise,\n        unsigned int auto_var_radius)\n{\n    setParameters(patch_size,\n            window_radius,\n            radius_bin_count,\n            angle_bin_count,\n            var_noise,\n            auto_var_radius);\n}\n/*virtual*/ SelfSimilarity::~SelfSimilarity()\n{\n\n}\n\nvoid SelfSimilarity::setParameters(unsigned int patch_size,\n        unsigned int window_radius,\n        unsigned int radius_bin_count,\n        unsigned int angle_bin_count,\n        float var_noise,\n        unsigned int auto_var_radius)\n{\n    // set parameters\n    patch_size_ = patch_size;\n    window_radius_ = window_radius;\n    radius_bin_count_ = radius_bin_count;\n    angle_bin_count_ = angle_bin_count;\n    var_noise_ = var_noise;\n\n    // precompute binning and autovar indices\n    const int window_size = 2 * window_radius_ + 1;\n    bin_map_= -cv::Mat_<int>::ones(window_size, window_size);  // init to -1\n    autovar_indices_.clear();\n    autovar_indices_.reserve((2*auto_var_radius + 1)*(2*auto_var_radius + 1)); // upper bound\n    double angle = 0.f;\n    double radius = 0.f;\n    int angle_bin = 0;\n    int radius_bin = 0;\n    int bin_id = 0;\n    for (int y = -window_radius_; y < window_size; ++y)\n    {\n        for (int x = -window_radius_; x < window_size; ++x)\n        {\n            /*\n             * scale log(y) to (bin_count - 1)...0\n             */\n            radius = std::sqrt(static_cast<float>(x * x + y * y));\n            if (radius > window_radius_ || radius == 0.)\n            {\n                continue;\n            }\n            radius_bin = static_cast<int>(\n                    ( std::log(radius)) / std::log(window_radius_+.5)\n                    * radius_bin_count_);\n\n            /*\n             * \\alpha \\in [ -\\pi ... +\\pi ]\n             * bin_id \\in [0 ... (bin_count - 1) ]\n             * bin_id = floor( (\\alpha + \\pi) / ( 2 \\pi) * bin_count )\n             *        = floor( \\alpha bin_count / ( 2 \\pi) + bin_count/2 )\n             */\n            angle = std::atan2(y, x); // [-pi ... pi]\n            angle_bin = static_cast<int>(\n                   ((angle * angle_bin_count_)\n                    / ( boost::math::constants::two_pi<double>()))\n                    + angle_bin_count_/2.) % angle_bin_count; // atan2 gives [-pi ... pi] and not (-pi ... pi] that's why we mod\n\n            bin_id = angle_bin * radius_bin_count + radius_bin;\n            bin_map_(y + window_radius_, x + window_radius_) = bin_id;\n\n            if (radius <= auto_var_radius && radius > 0)\n            {\n                autovar_indices_.push_back(cv::Point(y + window_radius_, x + window_radius_));\n            }\n\n        }\n    }\n}\n\n\nbool SelfSimilarity::extract(const cv::Mat& image, const cv::Point& location, cv::Mat_<float>& descriptor) const\n{\n    // compute the distance surface\n    cv::Mat_<float> distance_surface;\n    compute_distance_surface(image, location, distance_surface);\n\n    if (distance_surface.rows == 0 || distance_surface.cols == 0)\n    {\n        return false;\n    }\n\n    // put it into the logpolar descriptor\n    compute_descriptor(distance_surface, descriptor);\n    return true;\n}\n\n//void showmat(const std::string titile, const cv::Mat& mat, int size)\n//{\n//    cv::Mat scaled;\n//    cv::resize(mat, scaled, cv::Size(mat.rows * size, mat.cols * size), 0, 0, cv::INTER_AREA);\n//    cv::imshow(titile, scaled);\n//}\n\nvoid SelfSimilarity::compute_distance_surface(const cv::Mat& image, const cv::Point& loaction, cv::Mat_<float>& distance_surface) const\n{\n    const int patch_radius = patch_size_ / 2;\n    const int window_size  = window_radius_ * 2 + 1;\n\n    // check boundaries\n    if (\t   (loaction.x - (int)window_radius_ - patch_radius) < 0\n            || (loaction.y - (int)window_radius_ - patch_radius) < 0\n            || (loaction.x + (int)window_radius_ + patch_size_) >= image.cols\n            || (loaction.y + (int)window_radius_ + patch_size_) >= image.rows)\n    {\n        distance_surface = cv::Mat_<float>();\n        return;\n    }\n\n    // allocate memory and precompute some structures\n    distance_surface.create(window_size, window_size);\n\n    const cv::Mat inner_patch = image(\n            cv::Range(loaction.y - patch_radius, loaction.y + patch_radius + 1),\n            cv::Range(loaction.x - patch_radius, loaction.x + patch_radius + 1));\n\n//    assert(distance_surface.rows == window_size);\n//    assert(distance_surface.cols == window_size);\n    for (unsigned int r = 0; r < window_size; ++r)\n    {\n        const int y_window_patch_start = loaction.y - window_radius_ + r - patch_radius ;\n        const cv::Range y_window_range(\n                y_window_patch_start,\n                y_window_patch_start + patch_size_);\n        for (unsigned int c = 0; c < window_size; ++c)\n        {\n//            const int bin_idx = bin_map_(r,c);\n//            if (bin_idx < 0)\n//            {\n//                continue;\n//            }\n            const int x_window_patch_start = loaction.x - window_radius_  + c - patch_radius;\n            const cv::Range x_window_range(\n                    x_window_patch_start,\n                    x_window_patch_start + patch_size_);\n\n            const cv::Mat window_patch = image(y_window_range, x_window_range);\n            if (image.channels() == 3)\n            {\n                distance_surface(r, c) = ssd3(inner_patch, window_patch);\n            }\n            else\n            {\n                distance_surface(r, c) = ssd1(inner_patch, window_patch);\n            }\n\n//            showmat(\"inner\", inner_patch, 100);\n//            showmat(\"window_patch\", window_patch, 100);\n//            cv::Mat d = image.clone();\n//            // window_patch\n//            cv::rectangle(d,\n//                    cv::Point(x_window_range.start, y_window_range.start),\n//                    cv::Point(x_window_range.end-1,   y_window_range.end-1),\n//                    CV_RGB(0,255,255)\n//                    );\n//            // center_patch\n//            cv::rectangle(d,\n//                    cv::Point(loaction.x - patch_radius, loaction.y - patch_radius),\n//                    cv::Point(loaction.x + patch_radius, loaction.y + patch_radius),\n//                    CV_RGB(255,0,255)\n//                    );\n//            // whole window\n//            cv::rectangle(d,\n//                    cv::Point(\n//                            loaction.x - window_radius_,\n//                            loaction.y - window_radius_),\n//                    cv::Point(\n//                            loaction.x + window_radius_,\n//                            loaction.y + window_radius_),\n//                    CV_RGB(255,0,255)\n//                    );\n//            showmat(\"all\", d, 5);\n//            cv::waitKey();\n        }\n    }\n}\n\n\nvoid SelfSimilarity::compute_descriptor(const cv::Mat_<float>& distance_surface, cv::Mat_<float>& descriptor) const\n{\n    // allocate log-polar descriptor. we init it with -1 as the e^-x is\n    // always > 0 for x < \\inf\n    const int descriptor_length = radius_bin_count_*angle_bin_count_;\n    descriptor.create(1, descriptor_length);\n    descriptor = -1;\n\n    // compute auto noise (like original paper matlab implementation):\n    // find max ssd at the autovar_indices (<- places with within radius 1)\n    float variance = var_noise_;\n    for (unsigned int i = 0; i < autovar_indices_.size(); ++i)\n    {\n        const cv::Point& p = autovar_indices_[i];\n        variance = std::max(variance, distance_surface(p.y, p.x));\n    }\n\n    // compute finally the descriptor\n    float min_correlation = std::numeric_limits<float>::max();\n    float max_correlation = std::numeric_limits<float>::min();\n    for (int r = 0; r < distance_surface.rows; ++r)\n    {\n        for (int c = 0; c < distance_surface.cols; ++c)\n        {\n            const int bin_idx = bin_map_(r,c);\n            if (bin_idx < 0)\n            {\n                continue;\n            }\n            // compute S_q(x,y)\n            float correlation = std::exp(-distance_surface(r, c) / variance);\n            // we store only the max ssd\n            const float current_value = descriptor(bin_idx);\n            if (current_value < correlation)\n            {\n                descriptor(bin_idx) = correlation;\n                min_correlation = std::min(correlation, min_correlation);\n                max_correlation = std::max(correlation, max_correlation);\n            }\n\n        }\n    }\n    // finally: normalize to [0 ... 1]\n    //XXX: Note: in the original implementation, there would be only stretching to max without substracting min\n    // however, the paper states \"normalized by linearly streticht its values to the range [0...1]\"\n//    descriptor = (descriptor - min_correlation) / (max_correlation - min_correlation);\n    //XXX: strange enough: \"correct\" normalization gives a segfault while clustering\n    descriptor = descriptor / max_correlation;  // normalisation from the paper implementation\n\n}\n\n} /* namespace features */\n} /* namespace vision */\n", "meta": {"hexsha": "d203bf517b9b61576aa40c7c8c7f8827b60d7bb8", "size": 12034, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "MEX/src/cpp/vision/features/low_level/self_similarity.cpp", "max_stars_repo_name": "umariqb/3D_Pose_Estimation_CVPR2016", "max_stars_repo_head_hexsha": "83f6bf36aa68366ea8fa078eea6d91427e28503b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 47.0, "max_stars_repo_stars_event_min_datetime": "2016-07-25T00:48:59.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-17T09:19:03.000Z", "max_issues_repo_path": "MEX/src/cpp/vision/features/low_level/self_similarity.cpp", "max_issues_repo_name": "umariqb/3D_Pose_Estimation_CVPR2016", "max_issues_repo_head_hexsha": "83f6bf36aa68366ea8fa078eea6d91427e28503b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2016-09-17T19:40:46.000Z", "max_issues_repo_issues_event_max_datetime": "2018-11-07T06:49:02.000Z", "max_forks_repo_path": "MEX/src/cpp/vision/features/low_level/self_similarity.cpp", "max_forks_repo_name": "iqbalu/3D_Pose_Estimation_CVPR2016", "max_forks_repo_head_hexsha": "83f6bf36aa68366ea8fa078eea6d91427e28503b", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 35.0, "max_forks_repo_forks_event_min_datetime": "2016-07-21T09:13:15.000Z", "max_forks_repo_forks_event_max_datetime": "2019-05-13T14:11:37.000Z", "avg_line_length": 32.5243243243, "max_line_length": 135, "alphanum_fraction": 0.5754528835, "num_tokens": 2784, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6001883735630721, "lm_q2_score": 0.523420348936324, "lm_q1q2_score": 0.314150807917908}}
{"text": "/*********************************************************************\n *\n * Software License Agreement (BSD License)\n *\n *  Copyright (c) 2016,\n *  TU Dortmund - Institute of Control Theory and Systems Engineering.\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 institute 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: Christoph Rösmann, Otniel Rinaldo\n *********************************************************************/\n\n#include <costmap_converter/costmap_to_polygons.h>\n#include <costmap_converter/misc.h>\n#include <boost/thread.hpp>\n#include <boost/thread/mutex.hpp>\n#include <pluginlib/class_list_macros.h>\n\nPLUGINLIB_EXPORT_CLASS(costmap_converter::CostmapToPolygonsDBSMCCH, costmap_converter::BaseCostmapToPolygons)\n\nnamespace\n{\n\n/**\n * @brief Douglas-Peucker Algorithm for fitting lines into ordered set of points\n * \n * Douglas-Peucker Algorithm, see https://en.wikipedia.org/wiki/Ramer%E2%80%93Douglas%E2%80%93Peucker_algorithm\n * \n * @param begin iterator pointing to the begin of the range of points\n * @param end interator pointing to the end of the range of points\n * @param epsilon distance criteria for removing points if it is closer to the line segment than this\n * @param result the simplified polygon\n */\nstd::vector<geometry_msgs::Point32> douglasPeucker(std::vector<geometry_msgs::Point32>::iterator begin,\n  std::vector<geometry_msgs::Point32>::iterator end, double epsilon)\n{\n  if (std::distance(begin, end) <= 2)\n  {\n    return std::vector<geometry_msgs::Point32>(begin, end);\n  }\n\n  // Find the point with the maximum distance from the line [begin, end)\n  double dmax = std::numeric_limits<double>::lowest();\n  std::vector<geometry_msgs::Point32>::iterator max_dist_it;\n  std::vector<geometry_msgs::Point32>::iterator last = std::prev(end);\n  for (auto it = std::next(begin); it != last; ++it)\n  {\n    double d = costmap_converter::computeSquaredDistanceToLineSegment(*it, *begin, *last);\n    if (d > dmax)\n    {\n      max_dist_it = it;\n      dmax = d;\n    }\n  }\n\n  if (dmax < epsilon * epsilon)\n  { // termination criterion reached, line is good enough\n    std::vector<geometry_msgs::Point32> result;\n    result.push_back(*begin);\n    result.push_back(*last);\n    return result;\n  }\n\n  // Recursive calls for the two splitted parts\n  auto firstLineSimplified = douglasPeucker(begin, std::next(max_dist_it), epsilon);\n  auto secondLineSimplified = douglasPeucker(max_dist_it, end, epsilon);\n\n  // Combine the two lines into one line and return the merged line.\n  // Note that we have to skip the first point of the second line, as it is duplicated above.\n  firstLineSimplified.insert(firstLineSimplified.end(),\n    std::make_move_iterator(std::next(secondLineSimplified.begin())),\n    std::make_move_iterator(secondLineSimplified.end()));\n  return firstLineSimplified;\n}\n\n} // end namespace\n\nnamespace costmap_converter\n{\n    \nCostmapToPolygonsDBSMCCH::CostmapToPolygonsDBSMCCH() : BaseCostmapToPolygons()\n{\n  costmap_ = NULL;\n  dynamic_recfg_ = NULL;\n  neighbor_size_x_ = neighbor_size_y_ = -1;\n  offset_x_ = offset_y_ = 0.;\n}\n\nCostmapToPolygonsDBSMCCH::~CostmapToPolygonsDBSMCCH() \n{\n  if (dynamic_recfg_ != NULL)\n    delete dynamic_recfg_;\n}\n\nvoid CostmapToPolygonsDBSMCCH::initialize(ros::NodeHandle nh)\n{\n    costmap_ = NULL;\n   \n    nh.param(\"cluster_max_distance\", parameter_.max_distance_, 0.4);\n    nh.param(\"cluster_min_pts\", parameter_.min_pts_, 2);\n    nh.param(\"cluster_max_pts\", parameter_.max_pts_, 30);\n    nh.param(\"convex_hull_min_pt_separation\", parameter_.min_keypoint_separation_, 0.1);\n    \n    parameter_buffered_ = parameter_;\n    \n    // setup dynamic reconfigure\n    dynamic_recfg_ = new dynamic_reconfigure::Server<CostmapToPolygonsDBSMCCHConfig>(nh);\n    dynamic_reconfigure::Server<CostmapToPolygonsDBSMCCHConfig>::CallbackType cb = boost::bind(&CostmapToPolygonsDBSMCCH::reconfigureCB, this, _1, _2);\n    dynamic_recfg_->setCallback(cb);\n}\n\n\nvoid CostmapToPolygonsDBSMCCH::compute()\n{\n    std::vector< std::vector<KeyPoint> > clusters;\n    dbScan(clusters);\n    \n    // Create new polygon container\n    PolygonContainerPtr polygons(new std::vector<geometry_msgs::Polygon>());\n    \n    \n    // add convex hulls to polygon container\n    for (std::size_t i = 1; i <clusters.size(); ++i) // skip first cluster, since it is just noise\n    {\n      polygons->push_back( geometry_msgs::Polygon() );\n      convexHull2(clusters[i], polygons->back() );\n    }\n    \n    // add our non-cluster points to the polygon container (as single points)\n    if (!clusters.empty())\n    {\n      for (std::size_t i=0; i < clusters.front().size(); ++i)\n      {\n        polygons->push_back( geometry_msgs::Polygon() );\n        convertPointToPolygon(clusters.front()[i], polygons->back());\n      }\n    }\n    \n    // replace shared polygon container\n    updatePolygonContainer(polygons);\n}\n\nvoid CostmapToPolygonsDBSMCCH::setCostmap2D(costmap_2d::Costmap2D *costmap)\n{\n    if (!costmap)\n      return;\n\n    costmap_ = costmap;     \n    \n    updateCostmap2D();\n}\n\nvoid CostmapToPolygonsDBSMCCH::updateCostmap2D()\n{\n      occupied_cells_.clear();\n      \n      if (!costmap_->getMutex())\n      {\n        ROS_ERROR(\"Cannot update costmap since the mutex pointer is null\");\n        return;\n      }\n      \n      { // get a copy of our parameters from dynamic reconfigure\n        boost::mutex::scoped_lock lock(parameter_mutex_);\n        parameter_ = parameter_buffered_;\n      }\n      \n      costmap_2d::Costmap2D::mutex_t::scoped_lock lock(*costmap_->getMutex());\n\n      // allocate neighbor lookup\n      int cells_x = int(costmap_->getSizeInMetersX() / parameter_.max_distance_) + 1;\n      int cells_y = int(costmap_->getSizeInMetersY() / parameter_.max_distance_) + 1;\n\n      if (cells_x != neighbor_size_x_ || cells_y != neighbor_size_y_) {\n        neighbor_size_x_ = cells_x;\n        neighbor_size_y_ = cells_y;\n        neighbor_lookup_.resize(neighbor_size_x_ * neighbor_size_y_);\n      }\n      offset_x_ = costmap_->getOriginX();\n      offset_y_ = costmap_->getOriginY();\n      for (auto& n : neighbor_lookup_)\n        n.clear();\n\n      // get indices of obstacle cells\n      for(std::size_t i = 0; i < costmap_->getSizeInCellsX(); i++)\n      {\n        for(std::size_t j = 0; j < costmap_->getSizeInCellsY(); j++)\n        {\n          int value = costmap_->getCost(i,j);\n          if(value >= costmap_2d::LETHAL_OBSTACLE)\n          {\n            double x, y;\n            costmap_->mapToWorld((unsigned int)i, (unsigned int)j, x, y);\n            addPoint(x, y);\n          }\n        }\n      }\n}\n\n\nvoid CostmapToPolygonsDBSMCCH::dbScan(std::vector< std::vector<KeyPoint> >& clusters)\n{\n  std::vector<bool> visited(occupied_cells_.size(), false);\n\n  clusters.clear();  \n  \n  //DB Scan Algorithm\n  int cluster_id = 0; // current cluster_id\n  clusters.push_back(std::vector<KeyPoint>());\n  for(int i = 0; i< (int)occupied_cells_.size(); i++)\n  {\n    if(!visited[i]) //keypoint has not been visited before\n    {\n      visited[i] = true; // mark as visited\n      std::vector<int> neighbors;\n      regionQuery(i, neighbors); //Find neighbors around the keypoint\n      if((int)neighbors.size() < parameter_.min_pts_) //If not enough neighbors are found, mark as noise\n      {\t\t\n        clusters[0].push_back(occupied_cells_[i]);\n      }\n      else\n      {\n        ++cluster_id; // increment current cluster_id\n        clusters.push_back(std::vector<KeyPoint>());\n        \n        // Expand the cluster\n        clusters[cluster_id].push_back(occupied_cells_[i]);\n        for(int j = 0; j<(int)neighbors.size(); j++)\n        {\n          if ((int)clusters[cluster_id].size() == parameter_.max_pts_)\n            break;\n          \n          if(!visited[neighbors[j]]) //keypoint has not been visited before\n          {\n            visited[neighbors[j]] = true;  // mark as visited\n            std::vector<int> further_neighbors;\n            regionQuery(neighbors[j], further_neighbors); //Find more neighbors around the new keypoint\n//             if(further_neighbors.size() < min_pts_)\n//             {\t  \n//               clusters[0].push_back(occupied_cells[neighbors[j]]);\n//             }\n//             else\n            if ((int)further_neighbors.size() >= parameter_.min_pts_)\n            {\n              // neighbors found\n              neighbors.insert(neighbors.end(), further_neighbors.begin(), further_neighbors.end());  //Add these newfound P' neighbour to P neighbour vector \"nb_indeces\"\n              clusters[cluster_id].push_back(occupied_cells_[neighbors[j]]);\n            }\n          }\n        }\n      }\t      \n    }\n  } \n}\n  \nvoid CostmapToPolygonsDBSMCCH::regionQuery(int curr_index, std::vector<int>& neighbors)\n{\n    neighbors.clear();\n\n    double dist_sqr_threshold = parameter_.max_distance_ * parameter_.max_distance_;\n    const KeyPoint& kp = occupied_cells_[curr_index];\n    int cx, cy;\n    pointToNeighborCells(kp, cx,cy);\n    \n    // loop over the neighboring cells for looking up the points\n    const int offsets[9][2] = {{-1, -1}, {0, -1}, {1, -1},\n                               {-1,  0}, {0,  0}, {1,  0},\n                               {-1,  1}, {0,  1}, {1,  1}};\n    for (int i = 0; i < 9; ++i)\n    {\n      int idx = neighborCellsToIndex(cx + offsets[i][0], cy + offsets[i][1]);\n      if (idx < 0 || idx >= int(neighbor_lookup_.size()))\n        continue;\n      const std::vector<int>& pointIndicesToCheck = neighbor_lookup_[idx];\n      for (int point_idx : pointIndicesToCheck) {\n        if (point_idx == curr_index) // point is not a neighbor to itself\n          continue;\n        const KeyPoint& other = occupied_cells_[point_idx];\n        double dx = other.x - kp.x;\n        double dy = other.y - kp.y;\n        double dist_sqr = dx*dx + dy*dy;\n        if (dist_sqr <= dist_sqr_threshold)\n          neighbors.push_back(point_idx);\n      }\n    }\n}\n\nbool isXCoordinateSmaller(const CostmapToPolygonsDBSMCCH::KeyPoint& p1, const CostmapToPolygonsDBSMCCH::KeyPoint& p2)\n{\n  return p1.x < p2.x || (p1.x == p2.x && p1.y < p2.y);\n}\n\nvoid CostmapToPolygonsDBSMCCH::convexHull(std::vector<KeyPoint>& cluster, geometry_msgs::Polygon& polygon)\n{\n    //Monotone Chain ConvexHull Algorithm source from http://www.algorithmist.com/index.php/Monotone_Chain_Convex_Hull\n  \n    int k = 0;\n    int n = cluster.size();\n    \n    // sort points according to x coordinate (TODO. is it already sorted due to the map representation?)\n    std::sort(cluster.begin(), cluster.end(), isXCoordinateSmaller);\n    \n    polygon.points.resize(2*n);\n      \n    // lower hull\n    for (int i = 0; i < n; ++i)\n    {\n      while (k >= 2 && cross(polygon.points[k-2], polygon.points[k-1], cluster[i]) <= 0) \n      {\n        --k;\n      }\n      cluster[i].toPointMsg(polygon.points[k]);\n      ++k;\n    }\n      \n    // upper hull  \n    for (int i = n-2, t = k+1; i >= 0; --i) \n    {\n      while (k >= t && cross(polygon.points[k-2], polygon.points[k-1], cluster[i]) <= 0)\n      {\n        --k;\n      }\n      cluster[i].toPointMsg(polygon.points[k]);\n      ++k;\n    }\n    \n\n    polygon.points.resize(k); // original\n    // TEST we skip the last point, since in our definition the polygon vertices do not contain the start/end vertex twice.\n//     polygon.points.resize(k-1); // TODO remove last point from the algorithm above to reduce computational cost\n\n    simplifyPolygon(polygon);\n}\n\n\n\nvoid CostmapToPolygonsDBSMCCH::convexHull2(std::vector<KeyPoint>& cluster, geometry_msgs::Polygon& polygon)\n{\n    std::vector<KeyPoint>& P = cluster;\n    std::vector<geometry_msgs::Point32>& points = polygon.points;\n\n    // Sort P by x and y\n    std::sort(P.begin(), P.end(), isXCoordinateSmaller);\n\n    // the output array H[] will be used as the stack\n    int i;                 // array scan index\n\n    // Get the indices of points with min x-coord and min|max y-coord\n    int minmin = 0, minmax;\n    double xmin = P[0].x;\n    for (i = 1; i < (int)P.size(); i++)\n        if (P[i].x != xmin) break;\n    minmax = i - 1;\n    if (minmax == (int)P.size() - 1)\n    {   // degenerate case: all x-coords == xmin\n        points.push_back(geometry_msgs::Point32());\n        P[minmin].toPointMsg(points.back());\n        if (P[minmax].y != P[minmin].y) // a  nontrivial segment\n        {\n            points.push_back(geometry_msgs::Point32());\n            P[minmax].toPointMsg(points.back());\n        }\n        // add polygon endpoint\n        points.push_back(geometry_msgs::Point32());\n        P[minmin].toPointMsg(points.back());\n        return;\n    }\n\n    // Get the indices of points with max x-coord and min|max y-coord\n    int maxmin, maxmax = (int)P.size() - 1;\n    double xmax = P.back().x;\n    for (i = P.size() - 2; i >= 0; i--)\n        if (P[i].x != xmax) break;\n    maxmin = i+1;\n\n    // Compute the lower hull on the stack H\n    // push  minmin point onto stack\n    points.push_back(geometry_msgs::Point32());\n    P[minmin].toPointMsg(points.back());\n    i = minmax;\n    while (++i <= maxmin)\n    {\n        // the lower line joins P[minmin]  with P[maxmin]\n        if (cross(P[minmin], P[maxmin], P[i]) >= 0 && i < maxmin)\n            continue;           // ignore P[i] above or on the lower line\n\n        while (points.size() > 1)         // there are at least 2 points on the stack\n        {\n            // test if  P[i] is left of the line at the stack top\n            if (cross(points[points.size() - 2], points.back(), P[i]) > 0)\n                break;         // P[i] is a new hull  vertex\n            points.pop_back();         // pop top point off  stack\n        }\n        // push P[i] onto stack\n        points.push_back(geometry_msgs::Point32());\n        P[i].toPointMsg(points.back());\n    }\n\n    // Next, compute the upper hull on the stack H above  the bottom hull\n    if (maxmax != maxmin)      // if  distinct xmax points\n    {\n         // push maxmax point onto stack\n         points.push_back(geometry_msgs::Point32());\n         P[maxmax].toPointMsg(points.back());\n    }\n    int bot = (int)points.size();                  // the bottom point of the upper hull stack\n    i = maxmin;\n    while (--i >= minmax)\n    {\n        // the upper line joins P[maxmax]  with P[minmax]\n        if (cross( P[maxmax], P[minmax], P[i])  >= 0 && i > minmax)\n            continue;           // ignore P[i] below or on the upper line\n\n        while ((int)points.size() > bot)     // at least 2 points on the upper stack\n        {\n            // test if  P[i] is left of the line at the stack top\n            if (cross(points[points.size() - 2], points.back(), P[i]) > 0)\n                break;         // P[i] is a new hull  vertex\n            points.pop_back();         // pop top point off stack\n        }\n        // push P[i] onto stack\n        points.push_back(geometry_msgs::Point32());\n        P[i].toPointMsg(points.back());\n    }\n    if (minmax != minmin)\n    {\n        // push  joining endpoint onto stack\n        points.push_back(geometry_msgs::Point32());\n        P[minmin].toPointMsg(points.back());\n    }\n    \n    simplifyPolygon(polygon);\n}\n\nvoid CostmapToPolygonsDBSMCCH::simplifyPolygon(geometry_msgs::Polygon& polygon)\n{\n  size_t triangleThreshold = 3;\n  // check if first and last point are the same. If yes, a triangle has 4 points\n  if (polygon.points.size() > 1\n      && std::abs(polygon.points.front().x - polygon.points.back().x) < 1e-5\n      && std::abs(polygon.points.front().y - polygon.points.back().y) < 1e-5)\n  {\n    triangleThreshold = 4;\n  }\n  if (polygon.points.size() <= triangleThreshold) // nothing to do for triangles or lines\n    return;\n  // TODO Reason about better start conditions for splitting lines, e.g., by\n  // https://en.wikipedia.org/wiki/Rotating_calipers\n  polygon.points = douglasPeucker(polygon.points.begin(), polygon.points.end(), parameter_.min_keypoint_separation_);;\n}\n\nvoid CostmapToPolygonsDBSMCCH::updatePolygonContainer(PolygonContainerPtr polygons)\n{\n  boost::mutex::scoped_lock lock(mutex_);\n  polygons_ = polygons;\n}\n\n\nPolygonContainerConstPtr CostmapToPolygonsDBSMCCH::getPolygons()\n{\n  boost::mutex::scoped_lock lock(mutex_);\n  PolygonContainerConstPtr polygons = polygons_;\n  return polygons;\n}\n\nvoid CostmapToPolygonsDBSMCCH::reconfigureCB(CostmapToPolygonsDBSMCCHConfig& config, uint32_t level)\n{\n  boost::mutex::scoped_lock lock(parameter_mutex_);\n  parameter_buffered_.max_distance_ = config.cluster_max_distance;\n  parameter_buffered_.min_pts_ = config.cluster_min_pts;\n  parameter_buffered_.max_pts_ = config.cluster_max_pts;\n  parameter_buffered_.min_keypoint_separation_ = config.convex_hull_min_pt_separation;\n}\n\n}//end namespace costmap_converter\n\n\n", "meta": {"hexsha": "537dcb5affb9bc34ac61ecf4d68fe8b0c69a9960", "size": 18004, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "costmap_converter-master/src/costmap_to_polygons.cpp", "max_stars_repo_name": "RuidongDavidLin/CUMTB_gazebo", "max_stars_repo_head_hexsha": "a190c1dc17a587c789b5d856b3ee1b6de45e5503", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-01-10T10:52:03.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-10T10:52:03.000Z", "max_issues_repo_path": "costmap_converter-master/src/costmap_to_polygons.cpp", "max_issues_repo_name": "RuidongDavidLin/CUMTB_gazebo", "max_issues_repo_head_hexsha": "a190c1dc17a587c789b5d856b3ee1b6de45e5503", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-11-12T09:53:16.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-12T09:53:16.000Z", "max_forks_repo_path": "costmap_converter-master/src/costmap_to_polygons.cpp", "max_forks_repo_name": "RuidongDavidLin/CUMTB_gazebo", "max_forks_repo_head_hexsha": "a190c1dc17a587c789b5d856b3ee1b6de45e5503", "max_forks_repo_licenses": ["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.7222222222, "max_line_length": 170, "alphanum_fraction": 0.6405798711, "num_tokens": 4614, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.600188359260205, "lm_q2_score": 0.523420348936324, "lm_q1q2_score": 0.3141508004314963}}
{"text": "#ifndef STAN_MATH_REV_CORE_VAR_HPP\n#define STAN_MATH_REV_CORE_VAR_HPP\n\n#include <stan/math/rev/core/vari.hpp>\n#include <stan/math/rev/core/grad.hpp>\n#include <stan/math/rev/core/chainable_alloc.hpp>\n#include <boost/math/tools/config.hpp>\n#include <ostream>\n#include <vector>\n\nnamespace stan {\n  namespace math {\n\n    // forward declare\n    static void grad(vari* vi);\n\n    /**\n     * Independent (input) and dependent (output) variables for gradients.\n     *\n     * This class acts as a smart pointer, with resources managed by\n     * an agenda-based memory manager scoped to a single gradient\n     * calculation.\n     *\n     * An var is constructed with a double and used like any\n     * other scalar.  Arithmetical functions like negation, addition,\n     * and subtraction, as well as a range of mathematical functions\n     * like exponentiation and powers are overridden to operate on\n     * var values objects.\n     */\n    class var {\n    public:\n      // FIXME: doc what this is for\n      typedef double Scalar;\n\n      /**\n       * Pointer to the implementation of this variable.\n       *\n       * This value should not be modified, but may be accessed in\n       * <code>var</code> operators to construct <code>vari</code>\n       * instances.\n       */\n      vari * vi_;\n\n      /**\n       * Return <code>true</code> if this variable has been\n       * declared, but not been defined.  Any attempt to use an\n       * undefined variable's value or adjoint will result in a\n       * segmentation fault.\n       *\n       * @return <code>true</code> if this variable does not yet have\n       * a defined variable.\n       */\n      bool is_uninitialized() {\n        return (vi_ == static_cast<vari*>(0U));\n      }\n\n      /**\n       * Construct a variable for later assignment.\n       *\n       * This is implemented as a no-op, leaving the underlying implementation\n       * dangling.  Before an assignment, the behavior is thus undefined just\n       * as for a basic double.\n       */\n      var() : vi_(static_cast<vari*>(0U)) { }\n\n      /**\n       * Construct a variable from a pointer to a variable implementation.\n       *\n       * @param vi Variable implementation.\n       */\n      var(vari* vi) : vi_(vi) {  }  // NOLINT\n\n      /**\n       * Construct a variable from the specified arithmetic argument\n       * by constructing a new <code>vari</code> with the argument\n       * cast to <code>double</code>, and a zero adjoint.\n       *\n       * @param x Value of the variable.\n       */\n      var(float x) : vi_(new vari(static_cast<double>(x))) { }  // NOLINT\n\n      /**\n       * Construct a variable from the specified arithmetic argument\n       * by constructing a new <code>vari</code> with the argument as\n       * a value and a zero adjoint.\n       *\n       * @param x Value of the variable.\n       */\n      var(double x) : vi_(new vari(x)) { }  // NOLINT\n\n      /**\n       * Construct a variable from the specified arithmetic argument\n       * by constructing a new <code>vari</code> with the argument\n       * cast to <code>double</code>, and a zero adjoint.\n       *\n       * @param x Value of the variable.\n       */\n      var(long double x) : vi_(new vari(x)) { }  // NOLINT\n\n      /**\n       * Construct a variable from the specified arithmetic argument\n       * by constructing a new <code>vari</code> with the argument\n       * cast to <code>double</code>, and a zero adjoint.\n       *\n       * @param x Value of the variable.\n       */\n      var(bool x) : vi_(new vari(static_cast<double>(x))) { }  // NOLINT\n\n      /**\n       * Construct a variable from the specified arithmetic argument\n       * by constructing a new <code>vari</code> with the argument\n       * cast to <code>double</code>, and a zero adjoint.\n       *\n       * @param x Value of the variable.\n       */\n      var(char x) : vi_(new vari(static_cast<double>(x))) { }  // NOLINT\n\n      /**\n       * Construct a variable from the specified arithmetic argument\n       * by constructing a new <code>vari</code> with the argument\n       * cast to <code>double</code>, and a zero adjoint.\n       *\n       * @param x Value of the variable.\n       */\n      var(short x) : vi_(new vari(static_cast<double>(x))) { }  // NOLINT\n\n      /**\n       * Construct a variable from the specified arithmetic argument\n       * by constructing a new <code>vari</code> with the argument\n       * cast to <code>double</code>, and a zero adjoint.\n       *\n       * @param x Value of the variable.\n       */\n      var(int x) : vi_(new vari(static_cast<double>(x))) { }  // NOLINT\n\n      /**\n       * Construct a variable from the specified arithmetic argument\n       * by constructing a new <code>vari</code> with the argument\n       * cast to <code>double</code>, and a zero adjoint.\n       *\n       * @param x Value of the variable.\n       */\n      var(long x) : vi_(new vari(static_cast<double>(x))) { }  // NOLINT\n\n      /**\n       * Construct a variable from the specified arithmetic argument\n       * by constructing a new <code>vari</code> with the argument\n       * cast to <code>double</code>, and a zero adjoint.\n       *\n       * @param x Value of the variable.\n       */\n      var(unsigned char x)  // NOLINT(runtime/explicit)\n      : vi_(new vari(static_cast<double>(x))) { }\n\n      /**\n       * Construct a variable from the specified arithmetic argument\n       * by constructing a new <code>vari</code> with the argument\n       * cast to <code>double</code>, and a zero adjoint.\n       *\n       * @param x Value of the variable.\n       */\n      // NOLINTNEXTLINE\n      var(unsigned short x) : vi_(new vari(static_cast<double>(x))) { }\n\n      /**\n       * Construct a variable from the specified arithmetic argument\n       * by constructing a new <code>vari</code> with the argument\n       * cast to <code>double</code>, and a zero adjoint.\n       *\n       * @param x Value of the variable.\n       */\n      var(unsigned int x) : vi_(new vari(static_cast<double>(x))) { }  // NOLINT\n\n      /**\n       * Construct a variable from the specified arithmetic argument\n       * by constructing a new <code>vari</code> with the argument\n       * cast to <code>double</code>, and a zero adjoint.\n       *\n       * @param x Value of the variable.\n       */\n      // NOLINTNEXTLINE\n      var(unsigned long x) : vi_(new vari(static_cast<double>(x))) { }  // NOLINT\n\n#ifdef _WIN64\n\n      // these two ctors are for Win64 to enable 64-bit signed\n      // and unsigned integers, because long and unsigned long\n      // are still 32-bit\n\n      /**\n       * Construct a variable from the specified arithmetic argument\n       * by constructing a new <code>vari</code> with the argument\n       * cast to <code>double</code>, and a zero adjoint.\n       *\n       * @param x Value of the variable.\n       */\n      var(size_t x) : vi_(new vari(static_cast<double>(x))) { }  // NOLINT\n\n      /**\n       * Construct a variable from the specified arithmetic argument\n       * by constructing a new <code>vari</code> with the argument\n       * cast to <code>double</code>, and a zero adjoint.\n       *\n       * @param x Value of the variable.\n       */\n      var(ptrdiff_t x) : vi_(new vari(static_cast<double>(x))) { }  // NOLINT\n#endif\n\n#ifdef BOOST_MATH_USE_FLOAT128\n\n      // this ctor is for later GCCs that have the __float128\n      // type enabled, because it gets enabled by boost\n\n      /**\n       * Construct a variable from the specified arithmetic argument\n       * by constructing a new <code>vari</code> with the argument\n       * cast to <code>double</code>, and a zero adjoint.\n       *\n       * @param x Value of the variable.\n       */\n      var(__float128 x) : vi_(new vari(static_cast<double>(x))) { }  // NOLINT\n\n#endif\n\n      /**\n       * Return the value of this variable.\n       *\n       * @return The value of this variable.\n       */\n      inline double val() const {\n        return vi_->val_;\n      }\n\n      /**\n       * Return the derivative of the root expression with\n       * respect to this expression.  This method only works\n       * after one of the <code>grad()</code> methods has been\n       * called.\n       *\n       * @return Adjoint for this variable.\n       */\n      inline double adj() const {\n        return vi_->adj_;\n      }\n\n      /**\n       * Compute the gradient of this (dependent) variable with respect to\n       * the specified vector of (independent) variables, assigning the\n       * specified vector to the gradient.\n       *\n       * The grad() function does <i>not</i> recover memory.  In Stan\n       * 2.4 and earlier, this function did recover memory.\n       *\n       * @param x Vector of independent variables.\n       * @param g Gradient vector of partial derivatives of this\n       * variable with respect to x.\n       */\n      void grad(std::vector<var>& x,\n                std::vector<double>& g) {\n        stan::math::grad(vi_);\n        g.resize(x.size());\n        for (size_t i = 0; i < x.size(); ++i)\n          g[i] = x[i].vi_->adj_;\n      }\n\n      /**\n       * Compute the gradient of this (dependent) variable with respect\n       * to all (independent) variables.\n       * \n       * The grad() function does <i>not</i> recover memory.\n       */\n      void grad() {\n        stan::math::grad(vi_);\n      }\n\n      // POINTER OVERRIDES\n\n      /**\n       * Return a reference to underlying implementation of this variable.\n       *\n       * If <code>x</code> is of type <code>var</code>, then applying\n       * this operator, <code>*x</code>, has the same behavior as\n       * <code>*(x.vi_)</code>.\n       *\n       * <i>Warning</i>:  The returned reference does not track changes to\n       * this variable.\n       *\n       * @return variable\n       */\n      inline vari& operator*() {\n        return *vi_;\n      }\n\n      /**\n       * Return a pointer to the underlying implementation of this variable.\n       *\n       * If <code>x</code> is of type <code>var</code>, then applying\n       * this operator, <code>x-&gt;</code>, behaves the same way as\n       * <code>x.vi_-&gt;</code>.\n       *\n       * <i>Warning</i>: The returned result does not track changes to\n       * this variable.\n       */\n      inline vari* operator->() {\n        return vi_;\n      }\n\n      // COMPOUND ASSIGNMENT OPERATORS\n\n      /**\n       * The compound add/assignment operator for variables (C++).\n       *\n       * If this variable is a and the argument is the variable b,\n       * then (a += b) behaves exactly the same way as (a = a + b),\n       * creating an intermediate variable representing (a + b).\n       *\n       * @param b The variable to add to this variable.\n       * @return The result of adding the specified variable to this variable.\n       */\n      inline var& operator+=(const var& b);\n\n      /**\n       * The compound add/assignment operator for scalars (C++).\n       *\n       * If this variable is a and the argument is the scalar b, then\n       * (a += b) behaves exactly the same way as (a = a + b).  Note\n       * that the result is an assignable lvalue.\n       *\n       * @param b The scalar to add to this variable.\n       * @return The result of adding the specified variable to this variable.\n       */\n      inline var& operator+=(double b);\n\n      /**\n       * The compound subtract/assignment operator for variables (C++).\n       *\n       * If this variable is a and the argument is the variable b,\n       * then (a -= b) behaves exactly the same way as (a = a - b).\n       * Note that the result is an assignable lvalue.\n       *\n       * @param b The variable to subtract from this variable.\n       * @return The result of subtracting the specified variable from\n       * this variable.\n       */\n      inline var& operator-=(const var& b);\n\n      /**\n       * The compound subtract/assignment operator for scalars (C++).\n       *\n       * If this variable is a and the argument is the scalar b, then\n       * (a -= b) behaves exactly the same way as (a = a - b).  Note\n       * that the result is an assignable lvalue.\n       *\n       * @param b The scalar to subtract from this variable.\n       * @return The result of subtracting the specified variable from this\n       * variable.\n       */\n      inline var& operator-=(double b);\n\n      /**\n       * The compound multiply/assignment operator for variables (C++).\n       *\n       * If this variable is a and the argument is the variable b,\n       * then (a *= b) behaves exactly the same way as (a = a * b).\n       * Note that the result is an assignable lvalue.\n       *\n       * @param b The variable to multiply this variable by.\n       * @return The result of multiplying this variable by the\n       * specified variable.\n       */\n      inline var& operator*=(const var& b);\n\n      /**\n       * The compound multiply/assignment operator for scalars (C++).\n       *\n       * If this variable is a and the argument is the scalar b, then\n       * (a *= b) behaves exactly the same way as (a = a * b).  Note\n       * that the result is an assignable lvalue.\n       *\n       * @param b The scalar to multiply this variable by.\n       * @return The result of multplying this variable by the specified\n       * variable.\n       */\n      inline var& operator*=(double b);\n\n      /**\n       * The compound divide/assignment operator for variables (C++).  If this\n       * variable is a and the argument is the variable b, then (a /= b)\n       * behaves exactly the same way as (a = a / b).  Note that the\n       * result is an assignable lvalue.\n       *\n       * @param b The variable to divide this variable by.\n       * @return The result of dividing this variable by the\n       * specified variable.\n       */\n      inline var& operator/=(const var& b);\n\n      /**\n       * The compound divide/assignment operator for scalars (C++).\n       *\n       * If this variable is a and the argument is the scalar b, then\n       * (a /= b) behaves exactly the same way as (a = a / b).  Note\n       * that the result is an assignable lvalue.\n       *\n       * @param b The scalar to divide this variable by.\n       * @return The result of dividing this variable by the specified\n       * variable.\n       */\n      inline var& operator/=(double b);\n\n      /**\n       * Write the value of this auto-dif variable and its adjoint to\n       * the specified output stream.\n       *\n       * @param os Output stream to which to write.\n       * @param v Variable to write.\n       * @return Reference to the specified output stream.\n       */\n      friend std::ostream& operator<<(std::ostream& os, const var& v) {\n        if (v.vi_ == 0)\n          return os << \"uninitialized\";\n        return os << v.val();\n      }\n    };\n\n  }\n}\n#endif\n", "meta": {"hexsha": "f5be5a4f946f9ba1b9ba10c7d0dafdbca9272d8c", "size": 14593, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "cmdstan/stan/lib/stan_math/stan/math/rev/core/var.hpp", "max_stars_repo_name": "yizhang-cae/torsten", "max_stars_repo_head_hexsha": "dc82080ca032325040844cbabe81c9a2b5e046f9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cmdstan/stan/lib/stan_math/stan/math/rev/core/var.hpp", "max_issues_repo_name": "yizhang-cae/torsten", "max_issues_repo_head_hexsha": "dc82080ca032325040844cbabe81c9a2b5e046f9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cmdstan/stan/lib/stan_math/stan/math/rev/core/var.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": 34.0163170163, "max_line_length": 81, "alphanum_fraction": 0.5877475502, "num_tokens": 3513, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.600188359260205, "lm_q2_score": 0.523420348936324, "lm_q1q2_score": 0.3141508004314963}}
{"text": "/* Copyright (c) 2019 Kjetil Olsen Lye, ETH Zurich\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#pragma once\n#include <boost/python.hpp>\n#include <boost/python/numpy.hpp>\n#include <fbm/fbm.hpp>\nnamespace fbmpy {\n\n//! Adapter function for fbm::generate_fractional_brownian_bridge\ninline boost::python::numpy::ndarray fractional_brownian_bridge_3d(\n    double H, int nx, const boost::python::numpy::ndarray& X) {\n    Py_intptr_t shape[1] = {(nx + 1)* (nx + 1)* (nx + 1)};\n    auto bridge_data = boost::python::numpy::zeros(1, shape,\n            boost::python::numpy::dtype::get_builtin<double>());\n\n    fbm::fractional_brownian_bridge_3d(reinterpret_cast<double*>\n        (bridge_data.get_data()),\n        H,\n        nx,\n        reinterpret_cast<const double*>(X.get_data()));\n\n    return bridge_data;\n\n}\n\n\n//! Adapter function for fbm::generate_fractional_brownian_bridge\ninline boost::python::numpy::ndarray fractional_brownian_bridge_2d(\n    double H, int nx, const boost::python::numpy::ndarray& X) {\n    Py_intptr_t shape[1] = {(nx + 1)* (nx + 1)};\n    auto bridge_data = boost::python::numpy::zeros(1, shape,\n            boost::python::numpy::dtype::get_builtin<double>());\n\n    fbm::fractional_brownian_bridge_2d(reinterpret_cast<double*>\n        (bridge_data.get_data()),\n        H,\n        nx,\n        reinterpret_cast<const double*>(X.get_data()));\n\n    return bridge_data;\n\n}\n\n\n//! Adapter function for fbm::generate_fractional_brownian_bridge\ninline boost::python::numpy::ndarray fractional_brownian_bridge_1d(\n    double H, int nx, const boost::python::numpy::ndarray& X) {\n    Py_intptr_t shape[1] = {(nx + 1)};\n    auto bridge_data = boost::python::numpy::zeros(1, shape,\n            boost::python::numpy::dtype::get_builtin<double>());\n\n    fbm::fractional_brownian_bridge_1d(reinterpret_cast<double*>\n        (bridge_data.get_data()),\n        H,\n        nx,\n        reinterpret_cast<const double*>(X.get_data()));\n\n    return bridge_data;\n\n}\n\n//! Adapter function for fbm::generate_fractional_brownian_motion\ninline boost::python::numpy::ndarray fractional_brownian_motion_1d(\n    double H, int nx, const boost::python::numpy::ndarray& X) {\n    Py_intptr_t shape[1] = {(nx + 1)};\n    auto bridge_data = boost::python::numpy::zeros(1, shape,\n            boost::python::numpy::dtype::get_builtin<double>());\n\n    fbm::fractional_brownian_motion_1d(reinterpret_cast<double*>\n        (bridge_data.get_data()),\n        H,\n        nx,\n        reinterpret_cast<const double*>(X.get_data()));\n\n    return bridge_data;\n\n}\n\n\n//! Adapter function for fbm::generate_fractional_brownian_motion\ninline boost::python::numpy::ndarray fractional_brownian_motion_2d(\n    double H, int nx, const boost::python::numpy::ndarray& X) {\n    Py_intptr_t shape[1] = {(nx + 1)* (nx + 1)};\n    auto bridge_data = boost::python::numpy::zeros(1, shape,\n            boost::python::numpy::dtype::get_builtin<double>());\n\n    fbm::fractional_brownian_bridge_2d(reinterpret_cast<double*>\n        (bridge_data.get_data()),\n        H,\n        nx,\n        reinterpret_cast<const double*>(X.get_data()),\n        false);\n\n    return bridge_data;\n\n}\n\n\n//! Adapter function for fbm::generate_fractional_brownian_motion\ninline boost::python::numpy::ndarray fractional_brownian_motion_3d(\n    double H, int nx, const boost::python::numpy::ndarray& X) {\n    Py_intptr_t shape[1] = {(nx + 1)* (nx + 1)* (nx + 1)};\n    auto bridge_data = boost::python::numpy::zeros(1, shape,\n            boost::python::numpy::dtype::get_builtin<double>());\n\n    fbm::fractional_brownian_bridge_3d(reinterpret_cast<double*>\n        (bridge_data.get_data()),\n        H,\n        nx,\n        reinterpret_cast<const double*>(X.get_data()),\n        false);\n\n    return bridge_data;\n\n}\n}\n", "meta": {"hexsha": "e8a4e445fd435627ffe4ea6515de810e5b6cb9b7", "size": 4787, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "fbmpy/include/fbmpy/fbmpy.hpp", "max_stars_repo_name": "kjetil-lye/fractional_brownian_motion", "max_stars_repo_head_hexsha": "0dfd8ddd8568e72f8d1eaf1ad37280cc6733be8b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-06-24T12:37:03.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-24T12:37:03.000Z", "max_issues_repo_path": "fbmpy/include/fbmpy/fbmpy.hpp", "max_issues_repo_name": "kjetil-lye/fractional_brownian_motion", "max_issues_repo_head_hexsha": "0dfd8ddd8568e72f8d1eaf1ad37280cc6733be8b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "fbmpy/include/fbmpy/fbmpy.hpp", "max_forks_repo_name": "kjetil-lye/fractional_brownian_motion", "max_forks_repo_head_hexsha": "0dfd8ddd8568e72f8d1eaf1ad37280cc6733be8b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-06-14T15:48:05.000Z", "max_forks_repo_forks_event_max_datetime": "2019-06-14T15:48:05.000Z", "avg_line_length": 34.9416058394, "max_line_length": 81, "alphanum_fraction": 0.6876958429, "num_tokens": 1195, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6001883592602049, "lm_q2_score": 0.523420348936324, "lm_q1q2_score": 0.31415080043149624}}
{"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 <cstdlib>\n#include <boost/math/special_functions/fpclassify.hpp>\n#include <boost/numeric/ublas/banded.hpp>\n#include \"ublas_trace.hpp\"\n#include \"ublas_elementwise.hpp\"\n#include \"gauss_distribution.hpp\"\n#include \"gaussian_process_normal.hpp\"\n\nnamespace bayesopt\n{\n\n  namespace ublas = boost::numeric::ublas; \n  \n  GaussianProcessNormal::GaussianProcessNormal(size_t dim, \n\t\t\t\t\t       Parameters params, \n\t\t\t\t\t       const Dataset& data, \n\t\t\t\t\t       MeanModel& mean,\n\t\t\t\t\t       randEngine& eng):\n    HierarchicalGaussianProcess(dim,params,data,mean,eng),\n    mW0(params.mean.coef_mean.size()), mInvVarW(params.mean.coef_mean.size()), \n    mD(params.mean.coef_mean.size(),params.mean.coef_mean.size())\n  {  \n    mSigma = params.sigma_s;\n    mW0 = params.mean.coef_mean;\n    for (size_t ii = 0; ii < params.mean.coef_std.size(); ++ii)\n      {\n\tdouble varii = params.mean.coef_std[ii] * params.mean.coef_std[ii];\n\tmInvVarW(ii) = 1/varii;\n      }\n     d_ = new GaussianDistribution(eng);\n  }  // Constructor\n\n\n\n  GaussianProcessNormal::~GaussianProcessNormal()\n  {\n    delete d_;\n  } // Default destructor\n\n\n  ProbabilityDistribution* \n  GaussianProcessNormal::prediction(const vectord &query)\n  {\n    const double kq = computeSelfCorrelation(query);\n    const vectord phi = mMean.getFeatures(query);\n\n    vectord v = computeCrossCorrelation(query);\n\n    inplace_solve(mL,v,ublas::lower_tag());\n\n    vectord rq = phi - prod(v,mKF);\n\n    vectord rho(rq);\n    inplace_solve(mD,rho,ublas::lower_tag());\n    \n    double yPred = inner_prod(phi,mWMap) + inner_prod(v,mVf);\n    double sPred = sqrt( mSigma * (kq - inner_prod(v,v) \n\t\t\t        + inner_prod(rho,rho)));\n\n    if ((boost::math::isnan(yPred)) || (boost::math::isnan(sPred)))\n      {\n\tthrow std::runtime_error(\"Error in prediction. NaN found.\");\n      }\n\t\t\t\t\t\n\n    d_->setMeanAndStd(yPred,sPred);\n    return d_;\n  }\n\n\n  double GaussianProcessNormal::negativeLogLikelihood()\n  {\n    matrixd KK = computeCorrMatrix();\n    const size_t n = KK.size1();\n    const size_t p = mMean.nFeatures();\n  \n    vectord v0 = mData.mY - prod(trans(mMean.mFeatM),mW0);\n    matrixd WW = zmatrixd(p,p);  //TODO: diagonal matrix\n    utils::add_to_diagonal(WW,mInvVarW);\n    matrixd FW = prod(trans(mMean.mFeatM),WW);\n    KK += prod(FW,mMean.mFeatM);\n    matrixd BB(n,n);\n    utils::cholesky_decompose(KK,BB);\n    inplace_solve(BB,v0,ublas::lower_tag());\n    double zz = inner_prod(v0,v0);\n\n    double lik = 1/(2*mSigma) * zz;\n    lik += utils::log_trace(BB);\n    return lik;\n  }\n\n\n\n  void GaussianProcessNormal::precomputePrediction()\n  {\n    const size_t p = mMean.nFeatures();\n\n    mKF = trans(mMean.mFeatM);\n    inplace_solve(mL,mKF,ublas::lower_tag());\n    //TODO: make one line\n    matrixd DD(p,p);\n    DD = prod(trans(mKF),mKF);\n    utils::add_to_diagonal(DD,mInvVarW);\n    utils::cholesky_decompose(DD,mD);\n\n    vectord vn = mData.mY;\n    inplace_solve(mL,vn,ublas::lower_tag());\n    mWMap = prod(mMean.mFeatM,vn) + utils::ublas_elementwise_prod(mInvVarW,mW0);\n    utils::cholesky_solve(mD,mWMap,ublas::lower());\n\n    mVf = mData.mY - prod(trans(mMean.mFeatM),mWMap);\n    inplace_solve(mL,mVf,ublas::lower_tag());\n\n    if (boost::math::isnan(mWMap(0)))\n      {\n\tthrow std::runtime_error(\"Error in precomputed prediction. NaN found.\");\n      }\n  }\n\n} //namespace bayesopt\n", "meta": {"hexsha": "a7c609204f3b0155fa28f20138d24fc932651acf", "size": 4284, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "external/bayesopt/src/gaussian_process_normal.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/gaussian_process_normal.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/gaussian_process_normal.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": 29.958041958, "max_line_length": 80, "alphanum_fraction": 0.6554621849, "num_tokens": 1144, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6926419958239132, "lm_q2_score": 0.4532618480153861, "lm_q1q2_score": 0.3139481910402122}}
{"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_TENSOR_HPP\n#define AMA_TENSOR_TENSOR_HPP 1\n\n#include <ama/tensor/config.hpp>\n#include <ama/tensor/copy.hpp>\n#include <ama/tensor/detail/tensor_base.hpp>\n#include <ama/tensor/iexp/iexp.hpp>\n#include <ama/tensor/iexp/iexp_calculator.hpp>\n#include <ama/tensor/iexp/iexp_factory.hpp>\n#include <ama/tensor/iexp/indices.hpp>\n#include <ama/common/size_t.hpp>\n#include <ama/multi_array/multi_array.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#include <boost/mpl/size_t.hpp>\n\nnamespace ama\n{\n\n  template <typename S, /* scalar value used to represent scalar value */\n            size_t D,   /* the dimension of vector space               */\n            size_t CT,  /* the dimension of controvariant part         */\n            size_t CO>  /* the dimension of covariant part             */\n  class tensor;\n\n\n  /* tensor traits specialization */\n  namespace tensor_\n  {\n\n    template <typename S, size_t D, size_t CT, size_t CO>\n    struct tensor_traits< tensor<S,D,CT,CO> >\n    {\n      typedef S value_type;\n\n      typedef ::boost::mpl::size_t<D> dimension_type;\n\n      typedef ::boost::mpl::size_t<CT> controvariant_type;\n      typedef ::boost::mpl::size_t<CO> covariant_type;\n\n      typedef ::boost::mpl::true_ is_assignable;\n      typedef ::boost::mpl::false_ is_temporary;\n    };\n\n  }\n\n\n  /* class declaration */\n  template <typename S, size_t D, size_t CT, size_t CO>\n  class tensor:\n        public tensor_::tensor_base< tensor<S,D,CT,CO> >\n      , public multi_array<S,D,CT+CO>\n#ifdef AMA_MULTI_ARRAY_USE_LINEAR_ACCESS\n      , public tensor_::iexp< tensor<S,D,CT,CO>, CT+CO >\n#endif /* AMA_MULTI_ARRAY_USE_LINEAR_ACCESS */\n  {\n  public:\n    /* resolv the ambiguity */\n    typedef typename tensor_::tensor_base< tensor<S,D,CT,CO> >::value_type value_type;\n    typedef typename tensor_::tensor_base< tensor<S,D,CT,CO> >::dimension_type dimension_type;\n\n    /* needed */\n    typedef typename tensor_::tensor_base< tensor<S,D,CT,CO> >::controvariant_type controvariant_type;\n    typedef typename tensor_::tensor_base< tensor<S,D,CT,CO> >::covariant_type covariant_type;\n\n  public:\n    /* default constructor */\n    tensor():\n        tensor_::tensor_base< tensor<S,D,CT,CO> >(),\n        multi_array<S,D,CT+CO>() { }\n\n    /* copy constructor */\n    tensor(tensor const & t):\n        tensor_::tensor_base< tensor<S,D,CT,CO> >(),\n        multi_array<S,D,CT+CO>(t) { }\n\n    template <typename DERIVED>\n    explicit\n    tensor(tensor_::tensor_base<DERIVED> const & t):\n        tensor_::tensor_base< tensor<S,D,CT,CO> >(),\n        multi_array<S,D,CT+CO>()\n    {\n      ama::copy(t.derived(), *this);\n    }\n\n  public:\n    /* copy operator */\n    template <typename DERIVED>\n    tensor & operator=(tensor const & t)\n    {\n      ama::copy(t.derived(), *this);\n      return *this;\n    }\n\n    template <typename DERIVED>\n    tensor & operator=(tensor_::tensor_base<DERIVED> const & t)\n    {\n      ama::copy(t.derived(), *this);\n      return *this;\n    }\n\n\n#ifdef AMA_MULTI_ARRAY_USE_LINEAR_ACCESS\n  public:\n    using multi_array<S,D,CT+CO>::operator();\n    using tensor_::iexp< tensor<S,D,CT,CO> , CT+CO >::operator();\n#endif /* AMA_MULTI_ARRAY_USE_LINEAR_ACCESS */\n\n/* ============================ INDEX EXPRESSION ============================ */\n  public:\n    /* index expression contruction */\n    template <typename ILIST>\n    typename tensor_::iexp_calculator<tensor, ILIST, ::boost::mpl::false_>::type\n    idx()\n    {\n      namespace mpl = ::boost::mpl;\n\n      typedef mpl::equal_to<\n            mpl::size<typename tensor_::controvariant<tensor<S,D,CT,CO>, ILIST>::type>\n          , controvariant_type\n          > ct;\n      typedef mpl::equal_to<\n            mpl::size<typename tensor_::covariant<tensor<S,D,CT,CO>, ILIST>::type>\n          , covariant_type\n          > co;\n\n      BOOST_MPL_ASSERT_MSG(\n            (ct::value && co::value)\n          , THE_LENGTH_OF_LIST_OF_INDICES_MUST_BE_EQUAL_TO_THE_TENSOR_ORDER\n          , (ILIST));\n\n      typedef typename tensor_::iexp_calculator<tensor, ILIST, ::boost::mpl::false_>::type what;\n\n      return tensor_::iexp_factory<what>::template apply<ILIST>(*this);\n    }\n\n    template <typename ILIST>\n    typename tensor_::iexp_calculator<tensor, ILIST, ::boost::mpl::true_>::type\n    idx() const\n    {\n      namespace mpl = ::boost::mpl;\n\n      typedef mpl::equal_to<\n            mpl::size<typename tensor_::controvariant<tensor<S,D,CT,CO>, ILIST>::type>\n          , controvariant_type\n          > ct;\n      typedef mpl::equal_to<\n            mpl::size<typename tensor_::covariant<tensor<S,D,CT,CO>, ILIST>::type>\n          , covariant_type\n          > co;\n\n      BOOST_MPL_ASSERT_MSG(\n            (ct::value && co::value)\n          , THE_LENGTH_OF_LIST_OF_INDICES_MUST_BE_EQUAL_TO_THE_TENSOR_ORDER\n          , (ILIST));\n\n      typedef typename tensor_::iexp_calculator<tensor, ILIST, ::boost::mpl::true_>::type what;\n\n      return tensor_::iexp_factory<what>::template apply<ILIST>(*this);\n    }\n/* ============================ INDEX EXPRESSION ============================ */\n  };\n\n\n\n\n  /* partial specialization for 0-order tensor */\n  template <typename S, size_t D>\n  class tensor<S,D,0,0>:\n      public tensor_::tensor_base< tensor<S,D,0,0> >,\n      public multi_array<S,D,0>\n  {\n  public:\n    /* resolv the ambiguity */\n    typedef typename tensor_::tensor_base< tensor<S,D,0,0> >::value_type value_type;\n    typedef typename tensor_::tensor_base< tensor<S,D,0,0> >::dimension_type dimension_type;\n\n  public:\n    /* default constructor */\n    explicit\n    tensor(S const & value = S()):\n        tensor_::tensor_base< tensor<S,D,0,0> >(),\n        multi_array<S,D,0>(value) { }\n\n    /* copy constructor */\n    tensor(tensor const & t):\n        tensor_::tensor_base< tensor<S,D,0,0> >(),\n        multi_array<S,D,0>(t) { }\n\n    template <typename DERIVED>\n    explicit\n    tensor(tensor_::tensor_base<DERIVED> const & t):\n        tensor_::tensor_base< tensor<S,D,0,0> >(),\n        multi_array<S,D,0>()\n    {\n      ama::copy(t.derived(), *this);\n    }\n\n  public:\n    /* copy operator */\n    template <typename DERIVED>\n    tensor & operator=(tensor_::tensor_base<DERIVED> const & t)\n    {\n      ama::copy(t.derived(), *this);\n      return *this;\n    }\n\n  public:\n    /* cast operator */\n    operator value_type() { return this->template at<void>(); }\n    operator value_type() const { return this->template at<void>(); }\n  };\n\n\n\n\n  /* partial specialization for 0-dimension tensor */\n  template <typename S, size_t CT, size_t CO>\n  class tensor<S,0,CT,CO>:\n      public tensor_::tensor_base< tensor<S,0,CT,CO> >,\n      public multi_array<S,0,CT+CO>\n  {\n  public:\n    /* resolv the ambiguity */\n    typedef typename tensor_::tensor_base< tensor<S,0,CT,CO> >::value_type value_type;\n    typedef typename tensor_::tensor_base< tensor<S,0,CT,CO> >::dimension_type dimension_type;\n  };\n\n\n\n\n  /* partial specialization for 0-dimension tensor */\n  template <typename S>\n  class tensor<S,0,0,0>:\n      public tensor_::tensor_base< tensor<S,0,0,0> >,\n      public multi_array<S,0,0>\n  {\n  public:\n    /* resolv the ambiguity */\n    typedef typename tensor_::tensor_base< tensor<S,0,0,0> >::value_type value_type;\n    typedef typename tensor_::tensor_base< tensor<S,0,0,0> >::dimension_type dimension_type;\n  };\n\n}\n\n#endif /* AMA_TENSOR_TENSOR_HPP */\n", "meta": {"hexsha": "f91984c098b33b864306f4638336277c38289fb4", "size": 9011, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/ama/tensor/tensor.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/tensor.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/tensor.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": 32.5306859206, "max_line_length": 102, "alphanum_fraction": 0.6523138386, "num_tokens": 2276, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5621765008857982, "lm_q2_score": 0.5583269943353745, "lm_q1q2_score": 0.31387831602554567}}
{"text": "#include <cassert>\n#include <cmath>\n#include <string>\n#include <sstream>\n#include <iostream>\n#include <fstream>\n#include <algorithm>\n#include <random>\n#include <ctime>              // required for \"struct timezone\" and\n                              // \"gettimeofday()\" used to set the randomseed\nusing namespace std;\n\n#ifndef DISABLE_OPENMP\n#include <omp.h>       // (OpenMP-specific)\n#endif\n\n//#include <boost/math/special_functions/gamma.hpp>\n\n#include <mrc_simple.hpp>\n#include <visfd.hpp>\nusing namespace visfd;\n\n#include \"err.hpp\"\n#include \"settings.hpp\"\n\n\n\nint main(int argc, char **argv) {\n  try {\n\n    Settings settings; // parse the command-line argument list from the shell\n    settings.ParseArgs(argc, argv);\n\n\n    #ifndef DISABLE_OPENMP\n    #pragma omp parallel\n    {\n      int rank, nthr;\n      rank = omp_get_thread_num();\n      //cerr << \"rank=\" << rank << endl;\n      if (rank == 0) {\n        nthr = omp_get_num_threads();\n        cerr << \"   (Using \" << nthr << \" threads (cpu cores).  You can change this using the \\\"-np n\\\"\\n\"\n             << \"    argument, or by setting the OMP_NUM_THREADS environment variable.)\" << endl;\n      }\n    }\n    #else\n    cerr << \" (Serial version)\" << endl;\n    #endif //#ifndef DISABLE_OPENMP\n\n\n    // Read the input tomogram\n    MrcSimple tomo_in;\n\n    if (settings.in_file_name != \"\") {\n      cerr << \"Reading tomogram \\\"\"<<settings.in_file_name<<\"\\\"\" << endl;\n      tomo_in.Read(settings.in_file_name, false);\n      // (Note: You can also use \"tomo_in.Read(cin);\" or \"cin >> tomo;\")\n      tomo_in.PrintStats(cerr);      //Optional (display the tomogram size & format)\n      WarnMRCSignedBytes(tomo_in, settings.in_file_name, cerr);\n    }\n    else {\n      assert((settings.image_size[0] > 0) &&\n             (settings.image_size[1] > 0) &&\n             (settings.image_size[2] > 0));\n      tomo_in.Resize(settings.image_size);\n    }\n\n    // ---- mask ----\n\n    // Optional: if there is a \"mask\", read that too\n    MrcSimple mask;\n    if (settings.mask_file_name != \"\") {\n      cerr << \"Reading mask \\\"\"<<settings.mask_file_name<<\"\\\"\" << endl;\n      mask.Read(settings.mask_file_name, false);\n      if ((mask.header.nvoxels[0] != tomo_in.header.nvoxels[0]) ||\n          (mask.header.nvoxels[1] != tomo_in.header.nvoxels[1]) ||\n          (mask.header.nvoxels[2] != tomo_in.header.nvoxels[2]))\n        throw InputErr(\"Error: The size of the mask image does not match the size of the input image.\\n\");\n    }\n\n    // ---- Voxel size? ----\n\n\n    float voxel_width[3] = {1.0, 1.0, 1.0};\n    if (settings.voxel_width > 0.0) {\n      // Did the user manually specify the width of each voxel?\n      voxel_width[0] = settings.voxel_width;\n      voxel_width[1] = settings.voxel_width;\n      voxel_width[2] = settings.voxel_width;\n    }\n    else {\n      // Otherwise, infer it from the header of the MRC file\n      voxel_width[0] = tomo_in.header.cellA[0]/tomo_in.header.nvoxels[0];\n      voxel_width[1] = tomo_in.header.cellA[1]/tomo_in.header.nvoxels[1];\n      voxel_width[2] = tomo_in.header.cellA[2]/tomo_in.header.nvoxels[2];\n      if (settings.voxel_width_divide_by_10) {\n        voxel_width[0] *= 0.1;\n        voxel_width[1] *= 0.1;\n        voxel_width[2] *= 0.1;\n      }\n      cerr << \"voxel width in physical units = (\"\n           << voxel_width[0] << \", \"\n           << voxel_width[1] << \", \"\n           << voxel_width[2] << \")\\n\";\n    }\n\n    if ((voxel_width[0] <= 0.0) ||\n        (voxel_width[1] <= 0.0) ||\n        (voxel_width[2] <= 0.0))\n      throw InputErr(\"Error in tomogram header: Invalid voxel width(s).\\n\"\n                     \"Use the -w argument to specify the voxel width.\");\n\n    if ((voxel_width[0] != voxel_width[1]) ||\n        (voxel_width[1] != voxel_width[2]))\n      throw InputErr(\"Error in tomogram header: Unequal voxel widths in the x, y and directions.\\n\"\n                     \"Use the -w argument to specify the voxel width.\");\n\n\n    if (settings.in_coords_file_name != \"\") {\n      for (int iz = 0; iz < tomo_in.header.nvoxels[2]; iz++)\n        for (int iy = 0; iy < tomo_in.header.nvoxels[1]; iy++)\n          for (int ix = 0; ix < tomo_in.header.nvoxels[0]; ix++)\n            tomo_in.aaafI[iz][iy][ix] = 0.0;\n      fstream coords_file;\n      coords_file.open(settings.in_coords_file_name, ios::in);\n      if (! coords_file)\n        throw InputErr(\"Error: unable to open \\\"\"+\n                       settings.in_coords_file_name +\"\\\" for reading.\\n\");\n      while (coords_file) {\n        float x, y, z;\n        coords_file >> x;\n        coords_file >> y;\n        coords_file >> z;\n        int ix, iy, iz;\n        ix = static_cast<int>(x / voxel_width[0]);\n        iy = static_cast<int>(y / voxel_width[1]);\n        iz = static_cast<int>(z / voxel_width[2]);\n        if (((0 <= ix) && (ix < tomo_in.header.nvoxels[0])) &&\n            ((0 <= iy) && (iy < tomo_in.header.nvoxels[1])) &&\n            ((0 <= iz) && (iz < tomo_in.header.nvoxels[2])))\n          tomo_in.aaafI[iz][iy][ix] = 1.0;\n      }\n    } //if (settings.in_coords_file_name != \"\") {\n\n\n\n    double vol_total = settings.compartment_volume;\n    if (settings.compartment_volume < 0) {\n      if (mask.aaafI) {\n        for (int iz=0; iz<tomo_in.header.nvoxels[2]; iz++)\n          for (int iy=0; iy<tomo_in.header.nvoxels[1]; iy++)\n            for (int ix=0; ix<tomo_in.header.nvoxels[0]; ix++)\n              vol_total += mask.aaafI[iz][iy][ix];\n      }\n      else {\n        vol_total = (tomo_in.header.nvoxels[0] *\n                     tomo_in.header.nvoxels[1] *\n                     tomo_in.header.nvoxels[2]);\n      }\n      vol_total *= (voxel_width[0]*voxel_width[1]*voxel_width[2]);\n    }\n\n    if (settings.num_particles < 0) {\n      // If the user did not explicitly specify the number of particles\n      // (ie \"ribosomes\") present in the original image, we can attempt\n      // to infer it from the image itself.  To do this, I assume that\n      // the image is filled with voxels containing 0s everywhere except\n      // at the center of where each particle is located, where the voxel is 1.\n      // Consequently, the number of non-zero voxels (not excluded by the mask)\n      // should equal the sum of all of the voxel entries.\n      // (This should also equal the number of non-zero voxels.  However\n      //  sometimes these images are themselves slightly blurred to make it\n      //  easier to see each particle.  This blurring should not effect the sum)\n      double sum = 0.0;\n      for (int iz=0; iz<tomo_in.header.nvoxels[2]; iz++) {\n        for (int iy=0; iy<tomo_in.header.nvoxels[1]; iy++) {\n          for (int ix=0; ix<tomo_in.header.nvoxels[0]; ix++) {\n            if (mask.aaafI)\n              sum += tomo_in.aaafI[iz][iy][ix] * mask.aaafI[iz][iy][ix];\n            else\n              sum += tomo_in.aaafI[iz][iy][ix];\n          }\n        }\n      }\n      settings.num_particles = sum;\n    }\n\n\n    // DEBUG: The next if-then statement is for debugging only.\n    if (settings.randomize_input_image) {\n      size_t nparticles = floor(settings.num_particles);\n      size_t nvoxels;\n      if (mask.aaafI) {\n        for (int iz=0; iz<tomo_in.header.nvoxels[2]; iz++)\n          for (int iy=0; iy<tomo_in.header.nvoxels[1]; iy++)\n            for (int ix=0; ix<tomo_in.header.nvoxels[0]; ix++)\n              if (mask.aaafI[iz][iy][ix] != 0.0)\n                nvoxels += 1;\n      }\n      else {\n        nvoxels = (tomo_in.header.nvoxels[0] *\n                   tomo_in.header.nvoxels[1] *\n                   tomo_in.header.nvoxels[2]);\n      }\n      vector<bool> random_bit_list(nvoxels, false);\n      for (size_t i=0; i < nparticles; i++)\n        random_bit_list[i] = true;\n\n      long random_seed = settings.random_seed;\n      if (random_seed <= 0) {\n        random_seed = time(nullptr);\n        cerr << \"(random_seed = \" << random_seed << \")\" << endl;\n      }\n      shuffle(random_bit_list.begin(), random_bit_list.end(),\n              default_random_engine(random_seed));\n      size_t i=0;\n      for (int iz = 0; iz < tomo_in.header.nvoxels[2]; iz++) {\n        for (int iy = 0; iy < tomo_in.header.nvoxels[1]; iy++) {\n          for (int ix = 0; ix < tomo_in.header.nvoxels[0]; ix++) {\n            tomo_in.aaafI[iz][iy][ix] = 0.0;\n            if ((! mask.aaafI) || mask.aaafI[iz][iy][ix] != 0.0) {\n              tomo_in.aaafI[iz][iy][ix] = random_bit_list[i];\n              i++;\n            }\n          }\n        }\n      }\n    } //if (settings.randomize_input_image)\n\n\n\n    // First we must allocate a new array to store the filtered image.\n    MrcSimple tomo_out = tomo_in;\n\n\n    for (int i_sig = 0; i_sig < settings.vfSigma.size(); ++i_sig) {\n\n      // ---- main calculation: -----\n\n      //A Gaussian filter is a (weighted) average over a volume of nearby voxels\n      //Below we estimate the effective volume of those nearby voxels, by taking\n      //advantage of the fact that Gaussian is normalized (it's integral = 1).\n      //Normalization effectively reduces the height of the filter by the number\n      //of voxels which effectively belong to the filter.\n      // Example: a cube filter\n      // If we were averaging the brightness of the 27 voxels\n      // belonging to a 3*3*3 cube surrounding the voxel of interest\n      // then the effective volume of the filter is is 3*3*3=27, and\n      // weight of each voxel's contribution to the average is 1/27.  Similarly,\n      // for a more general filter, we can interpret the peak height of the\n      // filter as 1/volume. Below, we calculate the height of the 3D Gaussian's\n      // peak after normalization.  Normally the 3D Gaussian is:\n      //   (2*pi*sigma^2)^(-3/2) * exp(-0.5*(x^2+y^2+z^2)/sigma^2)\n      // and the peak height is (2*pi*sigma^2)^(-3/2),\n      // However this formula does not work for small sigma << 1.\n      // For small sigma, you have to normalize by computing a discrete sum\n      // (over a finite range).  We do this below (in a non-intuitive way).\n\n      float sigma = settings.vfSigma[i_sig];\n\n      sigma /= voxel_width[0]; //scale by voxel_width (if specified)\n\n\n      // How wide is the filter window (over what size window do we integrate)?\n      if (settings.filter_truncate_ratio <= 0) {\n        assert(settings.filter_truncate_threshold > 0.0);\n        settings.filter_truncate_ratio = sqrt(-2*log(settings.filter_truncate_threshold));\n      }\n      int filter_truncate_halfwidth = floor(sigma *\n                                            settings.filter_truncate_ratio);\n\n      float gauss_peak_height_3D;\n\n      {\n        // GenFilterGauss1D generates a 1D discrete normalized Gaussian (located\n        // in the afH[]) member. afH[0] is the height at the central peak. \n        // However, for now I just use them to estimate the height of the \n        // Gaussian peak.  (See below)\n        Filter1D<float, int> filter1D =\n          GenFilterGauss1D(sigma, filter_truncate_halfwidth);\n\n        // A 3D Gaussian blur can be performed by expoiting the fact that\n        // multidimensional Gaussians are \"seperable\" filters:  You can blur\n        // in the X direction, then in the Y direcion, then in the Z direction.\n        // The result is the same that you would get from a 3D filter Gaussian\n        // which is the product of Gaussians in the X,Y,Z directions.\n        // So the peak height is the product of the 3 1D Gaussian peak heights.\n        gauss_peak_height_3D =\n          (filter1D.afH[0] *\n           filter1D.afH[0] *\n           filter1D.afH[0]);\n      }\n    \n      // The Gaussian peak's height is 1/volume.\n\n      float volume_gaussian_bin = 1.0 / gauss_peak_height_3D;\n      volume_gaussian_bin *= (voxel_width[0]*voxel_width[1]*voxel_width[2]);\n\n      float num_bins = vol_total / volume_gaussian_bin;\n\n      // Now blur the original image (if the user did not do it already)\n      if ((! settings.precomputed_gaussian_blur) ||\n          (settings.vfSigma.size() > 1)) {\n\n        ApplyGauss(tomo_in.header.nvoxels,\n                   tomo_in.aaafI,\n                   tomo_out.aaafI, //<-store resulting image here\n                   mask.aaafI,\n                   sigma,\n                   filter_truncate_halfwidth,\n                   true,\n                   &cerr);\n\n        // Densities everywhere are assumed to be in physical units\n        // (ie. of 1/Angstroms^3),  NOT   1/voxels^3\n        // The Gaussian blur computes densities in 1/voxels^3\n        // To compensate for this, divide the densities by voxel_width^3\n        MultiplyScalarArr(static_cast<float>(\n                          1.0/(voxel_width[0]*voxel_width[1]*voxel_width[2])),\n                          tomo_out.header.nvoxels,\n                          tomo_out.aaafI);\n      }\n\n      // After bluring the image, find the lowest density:\n    \n      float extreme_density;\n      int afXextreme[3] = {-1, -1, -1};\n      float global_minima;\n      float global_maxima;\n\n      // Find the voxels with the minima and maxima intensities.\n      // Discard global minima or maxima which lie on the boundary\n      // The safe, careful way to do this is to only consider\n      // voxels which are surrounded by other voxels and are\n      // local minima or maxima.\n      for (int iz=0; iz < tomo_out.header.nvoxels[2]; iz++) {\n        for (int iy=0; iy < tomo_out.header.nvoxels[1]; iy++) {\n          for (int ix=0; ix < tomo_out.header.nvoxels[0]; ix++) {\n\n            bool is_local_minima = true;\n            bool is_local_maxima = true;\n\n            if (! settings.extrema_on_boundary) {\n              if ((ix == 0) || (ix ==  tomo_out.header.nvoxels[0]-1) ||\n                  (ix == 0) || (ix ==  tomo_out.header.nvoxels[0]-1) ||\n                  (ix == 0) || (ix ==  tomo_out.header.nvoxels[0]-1)) {\n                is_local_minima = false;\n                is_local_maxima = false;\n              }\n            }\n\n            float center_val = tomo_out.aaafI[iz][iy][ix];\n            for (int jz=-1; jz<=1; jz++) {\n              for (int jy=-1; jy<=1; jy++) {\n                for (int jx=-1; jx<=1; jx++) {\n                  if (! settings.extrema_on_boundary) {\n                    if (mask.aaafI && (mask.aaafI[iz+jz][iy+jy][ix+jx] == 0.0))\n                    {\n                      is_local_minima = false;\n                      is_local_maxima = false;\n                    }\n                  }\n                  if (tomo_out.aaafI[iz+jz][iy+jy][ix+jx] <= center_val)\n                    is_local_minima = false;\n                  if (tomo_out.aaafI[iz+jz][iy+jy][ix+jx] >= center_val)\n                    is_local_maxima = false;\n                }\n              }\n            }\n            if ((center_val < global_minima) || (afXextreme[0] == -1)) {\n              global_minima = center_val;\n              if (settings.use_min_density) {\n                extreme_density = global_minima;\n                afXextreme[0] = ix;\n                afXextreme[1] = iy;\n                afXextreme[2] = iz;\n              }\n            }\n            if ((center_val > global_maxima) || (afXextreme[0] == -1)) {\n              global_maxima = center_val;\n              if (! settings.use_min_density) {\n                extreme_density = global_maxima;\n                afXextreme[0] = ix;\n                afXextreme[1] = iy;\n                afXextreme[2] = iz;\n              }\n            }\n          } //for (int ix=1; ix < tomo_out.header.nvoxels[0]-1; ix++)\n        } //for (int iy=1; iy < tomo_out.header.nvoxels[1]-1; iy++)\n      } //for (int iz=1; iz < tomo_out.header.nvoxels[2]-1; iz++)\n\n\n      // Did we fail to find any local minima or maxima densities?\n      if (afXextreme[0] == -1) {\n        string extrema_type = \"minina\";\n        if (! settings.use_min_density)\n          extrema_type = \"maxima\";\n        stringstream msg_ss;\n        msg_ss << \"Error: There are no local density \" << extrema_type << \"\\n\"\n               << \"       in the image (at scale sigma = \" << sigma << \")\\n\"\n               << \"       Aborting...\\n\";\n        throw InputErr(msg_ss.str());\n      }\n\n      float ave_density = settings.num_particles / vol_total;\n\n\n      // Suppose you divide the volume of the region (ie. cell, compartment...)\n      // into equal size \"bins\" of equal size (\"volume_gaussian_bin\").\n      // A fixed number of particles lie within this volume.\n      // ...What is the probability that the number of particles in a bin\n      //    does not exceed \"extreme_density\"?\n      //  This is given by the (cumulative) Poisson distribution:\n      //     prob = lambda^k * exp(-lambda) / k!\n      //          = lambda^k * exp(-lambda) / Gamma(k+1)  <-continuous version\n      // \"k\" is the number of particles in this Gaussian-shaped \"bin\"\n      long double k = extreme_density * volume_gaussian_bin;\n      // \"lambda\" is the expected number of particles in this \"bin\"\n      long double lambda = ave_density * volume_gaussian_bin;\n\n\n      long double prob_cdf_obvious_way = 0.0;\n      if (settings.use_min_density) {\n        // Calculate the culmulative probability of seeing this many\n        // particles in the bin or less.  First try it the obvious way:\n\n        for (long i=0; i <= floor(k); i++)\n          prob_cdf_obvious_way += pow(lambda, i) * exp(-lambda) / tgamma(i+1.0);\n      }\n      else {\n      // Calculate the culmulative probability of seeing this many\n      // particles in the bin or more.  First try it the obvious way:\n        for (long i=0; i < floor(k); i++)\n          prob_cdf_obvious_way += pow(lambda, i) * exp(-lambda) / tgamma(i+1.0);\n        prob_cdf_obvious_way = 1.0 - prob_cdf_obvious_way;\n      }\n\n      cerr << \"####################################\" << endl;\n      cerr << \"## DEBUG MESSAGES (PLEASE IGNORE) ##\" << endl;\n      cerr << \"## location (in voxels) = (\"\n           << afXextreme[0] << \",\"\n           << afXextreme[1] << \",\"\n           << afXextreme[2] << \")\" << endl;\n      cerr << \"## num_in_bin = \" << k << endl;\n      cerr << \"## num_expected_in_bin = \" << lambda << endl;\n      cerr << \"## prob_cdf_obvious_way = \" << prob_cdf_obvious_way << endl;\n      cerr << \"####################################\" << endl;\n\n      long double prob_cdf;\n\n      // However, in our case the number of particles in this \"bin\" is not (k)\n      // necessarily an integer.  In that case use the continuous version of\n      // (the cumulative distribution) of the Poisson distributio.\n      // COMMENTING OUT: This requires the BOOST libraries\n      // COMMENTING OUT: if (use_min_density)\n      // COMMENTING OUT:   prob_cdf = gamma_q(k+1,lambda);\n      // COMMENTING OUT: else\n      // COMMENTING OUT:   prob_cdf = 1.0 - gamma_q(k,lambda);\n      //    (gamma_q() is defined in boost)\n\n      // The cumulative distribution of the Poisson distribution\n      // is also given by the upper incomplete Gamma function\n      // COMMENTING OUT: USE THE BOOST LIBRARY\n      //double prob_cdf = gamma_q(floor(k)+1, lambda);\n      // Unfortunately the  BOOST library can not be easily distributed with\n      // this code.  (Even if I throw away most ofthe BOOST code using the\n      // \"bcp\" utility, the remaining BOOST code exceeds the size of this\n      // the code for this project by a factor of 50.)\n      // Hence we will use the integer approximation (\"obvious_way\"):\n\n      prob_cdf = prob_cdf_obvious_way;\n\n      // ...Now what is the probability that the number of particles\n      //    in ANY OF THE BINS does not exceed \"extreme_density\"?\n\n      long double prob_total = 1.0 - pow((1.0 - prob_cdf), num_bins);\n\n      double effective_bin_size = (pow(volume_gaussian_bin, 1.0/3) *\n                                   voxel_width[0]);\n      cout << prob_total\n           << \" \" << extreme_density\n           << \" \" << afXextreme[0]\n           << \" \" << afXextreme[1]\n           << \" \" << afXextreme[2]\n           << \" \" << effective_bin_size\n           << endl;\n\n      // Discussion:\n      //      What do we expect this number to be?\n      // What is the expected value of \"prob_total\" for a randomly distributed\n      // particles in the same number of bins.\n      //\n      // Answer: 0.5\n      //\n      // The proof is not specific to the kind of distribution we are using.\n      // (a Poisson distribution)\n      //\n      // Proof:\n      //\n      // Let \"c\" be the cumulative probability distrubution for the entire\n      // system (in this \"prob_total\", but it could also be \"prob_cdf\")\n      //\n      // Let p(x) be the probability density of measuring x.\n      //\n      // Let C(x) be the cumulative distribution of measuring something <= x.\n      // (in this case the probability that none of the bins have\n      //  a density exceeding x)  This means that:\n      //\n      // C(X) = \\int_{-\\infty}^X  dx  p(x)\n      //\n      // Let C^{-1}(c)  denote the inverse of C(x)\n      // ==> C^{-1}(c) = x   if   C(x) = c\n      //\n      // What is the average value of c?\n      //\n      // <c> = \\int_{-infty}^{\\infty} * c(x) * p(x) * dx\n      //\n      //     = \\int_0^1         c *  p(x(c)) * dx(c)/dc * dc\n      //\n      //     = \\int_0^1 c * p( C^{-1}(c) ) * (d/dc) C^{-1}(c)  * dc\n      //\n      //     = \\int_0^1 c * p( C^{-1}(c) ) * ( 1 / (d/dx) C( C^{-1}(c) ) ) * dc\n      //\n      //     = \\int_0^1 c * p( C^{-1}(c) ) * ( 1 / p( C^{-1}(c) ) )  * dc\n      //\n      //     = \\int_0^1 c * dc\n      //\n      //     = 0.5\n      //\n      // However this number will be lower if you repeat this multiple times\n      // (using different bin-sizes (\"sigma\" values), for example)\n      // because by repeating, you give it more opportunities to find\n      // a more extreme value.  (Here we scan over a range of \"sigma\" values.)\n\n    } // for (int i_sig = 0; i_sig < settings.vfSigma.size(); i_sig++) {...\n\n\n    if ((settings.out_file_name != \"\") && (settings.vfSigma.size() == 1))\n    {\n      // Write the image file containing the filtered version for that sigma\n      cerr << \"writing a tomogram containing the most recently calculated density cloud\"\n           << endl;\n\n      tomo_out.Write(settings.out_file_name);\n      // (You can also use \"file_stream << tomo_out;\")\n    }\n\n  } //try {\n  catch (const std::exception& e) {\n    cerr << \"\\n\" << e.what() << endl;\n    exit(1);\n  }\n\n} // main()\n\n", "meta": {"hexsha": "637f58bd77a1104241345aec8dc77bb39a986bcf", "size": 22073, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "bin/pval_mrc/pval_mrc.cpp", "max_stars_repo_name": "jewettaij/visfd", "max_stars_repo_head_hexsha": "0c4fcdf9215b76e9cc9f3d2d9def5e50ebe86a93", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2019-06-26T04:32:53.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T07:12:40.000Z", "max_issues_repo_path": "bin/pval_mrc/pval_mrc.cpp", "max_issues_repo_name": "jewettaij/visfd", "max_issues_repo_head_hexsha": "0c4fcdf9215b76e9cc9f3d2d9def5e50ebe86a93", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 14.0, "max_issues_repo_issues_event_min_datetime": "2019-03-02T00:41:53.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-18T04:20:12.000Z", "max_forks_repo_path": "bin/pval_mrc/pval_mrc.cpp", "max_forks_repo_name": "jewettaij/visfd", "max_forks_repo_head_hexsha": "0c4fcdf9215b76e9cc9f3d2d9def5e50ebe86a93", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-02-16T13:50:42.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-16T13:50:42.000Z", "avg_line_length": 39.6283662478, "max_line_length": 106, "alphanum_fraction": 0.5633126444, "num_tokens": 5988, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5583269943353745, "lm_q2_score": 0.5621765008857982, "lm_q1q2_score": 0.31387831602554567}}
{"text": "// Copyright Nick Thompson 2017.\r\n// Use, modification and distribution are subject to the\r\n// Boost Software License, Version 1.0.\r\n// (See accompanying file LICENSE_1_0.txt\r\n// or copy at http://www.boost.org/LICENSE_1_0.txt)\r\n\r\n#ifndef BOOST_MATH_SPECIAL_LEGENDRE_STIELTJES_HPP\r\n#define BOOST_MATH_SPECIAL_LEGENDRE_STIELTJES_HPP\r\n\r\n/*\r\n * Constructs the Legendre-Stieltjes polynomial of degree m.\r\n * The Legendre-Stieltjes polynomials are used to create extensions for Gaussian quadratures,\r\n * commonly called \"Gauss-Konrod\" quadratures.\r\n *\r\n * References:\r\n * Patterson, TNL. \"The optimum addition of points to quadrature formulae.\" Mathematics of Computation 22.104 (1968): 847-856.\r\n */\r\n\r\n#include <iostream>\r\n#include <vector>\r\n#include <boost/math/tools/roots.hpp>\r\n#include <boost/math/special_functions/legendre.hpp>\r\n\r\nnamespace boost{\r\nnamespace math{\r\n\r\ntemplate<class Real>\r\nclass legendre_stieltjes\r\n{\r\npublic:\r\n    legendre_stieltjes(size_t m)\r\n    {\r\n        if (m == 0)\r\n        {\r\n           throw std::domain_error(\"The Legendre-Stieltjes polynomial is defined for order m > 0.\\n\");\r\n        }\r\n        m_m = static_cast<int>(m);\r\n        std::ptrdiff_t n = m - 1;\r\n        std::ptrdiff_t q;\r\n        std::ptrdiff_t r;\r\n        bool odd = n & 1;\r\n        if (odd)\r\n        {\r\n           q = 1;\r\n           r = (n-1)/2 + 2;\r\n        }\r\n        else\r\n        {\r\n           q = 0;\r\n           r = n/2 + 1;\r\n        }\r\n        m_a.resize(r + 1);\r\n        // We'll keep the ones-based indexing at the cost of storing a superfluous element\r\n        // so that we can follow Patterson's notation exactly.\r\n        m_a[r] = static_cast<Real>(1);\r\n        // Make sure using the zero index is a bug:\r\n        m_a[0] = std::numeric_limits<Real>::quiet_NaN();\r\n\r\n        for (std::ptrdiff_t k = 1; k < r; ++k)\r\n        {\r\n            Real ratio = 1;\r\n            m_a[r - k] = 0;\r\n            for (std::ptrdiff_t i = r + 1 - k; i <= r; ++i)\r\n            {\r\n                // See Patterson, equation 12\r\n                std::ptrdiff_t num = (n - q + 2*(i + k - 1))*(n + q + 2*(k - i + 1))*(n-1-q+2*(i-k))*(2*(k+i-1) -1 -q -n);\r\n                std::ptrdiff_t den = (n - q + 2*(i - k))*(2*(k + i - 1) - q - n)*(n + 1 + q + 2*(k - i))*(n - 1 - q + 2*(i + k));\r\n                ratio *= static_cast<Real>(num)/static_cast<Real>(den);\r\n                m_a[r - k] -= ratio*m_a[i];\r\n            }\r\n        }\r\n    }\r\n\r\n\r\n    Real norm_sq() const\r\n    {\r\n        Real t = 0;\r\n        bool odd = m_m & 1;\r\n        for (size_t i = 1; i < m_a.size(); ++i)\r\n        {\r\n            if(odd)\r\n            {\r\n                t += 2*m_a[i]*m_a[i]/static_cast<Real>(4*i-1);\r\n            }\r\n            else\r\n            {\r\n                t += 2*m_a[i]*m_a[i]/static_cast<Real>(4*i-3);\r\n            }\r\n        }\r\n        return t;\r\n    }\r\n\r\n\r\n    Real operator()(Real x) const\r\n    {\r\n        // Trivial implementation:\r\n        // Em += m_a[i]*legendre_p(2*i - 1, x);  m odd\r\n        // Em += m_a[i]*legendre_p(2*i - 2, x);  m even\r\n        size_t r = m_a.size() - 1;\r\n        Real p0 = 1;\r\n        Real p1 = x;\r\n\r\n        Real Em;\r\n        bool odd = m_m & 1;\r\n        if (odd)\r\n        {\r\n            Em = m_a[1]*p1;\r\n        }\r\n        else\r\n        {\r\n            Em = m_a[1]*p0;\r\n        }\r\n\r\n        unsigned n = 1;\r\n        for (size_t i = 2; i <= r; ++i)\r\n        {\r\n            std::swap(p0, p1);\r\n            p1 = boost::math::legendre_next(n, x, p0, p1);\r\n            ++n;\r\n            if (!odd)\r\n            {\r\n               Em += m_a[i]*p1;\r\n            }\r\n            std::swap(p0, p1);\r\n            p1 = boost::math::legendre_next(n, x, p0, p1);\r\n            ++n;\r\n            if(odd)\r\n            {\r\n                Em += m_a[i]*p1;\r\n            }\r\n        }\r\n        return Em;\r\n    }\r\n\r\n\r\n    Real prime(Real x) const\r\n    {\r\n        Real Em_prime = 0;\r\n\r\n        for (size_t i = 1; i < m_a.size(); ++i)\r\n        {\r\n            if(m_m & 1)\r\n            {\r\n                Em_prime += m_a[i]*detail::legendre_p_prime_imp(static_cast<unsigned>(2*i - 1), x, policies::policy<>());\r\n            }\r\n            else\r\n            {\r\n                Em_prime += m_a[i]*detail::legendre_p_prime_imp(static_cast<unsigned>(2*i - 2), x, policies::policy<>());\r\n            }\r\n        }\r\n        return Em_prime;\r\n    }\r\n\r\n    std::vector<Real> zeros() const\r\n    {\r\n        using boost::math::constants::half;\r\n\r\n        std::vector<Real> stieltjes_zeros;\r\n        std::vector<Real> legendre_zeros = legendre_p_zeros<Real>(m_m - 1);\r\n        int k;\r\n        if (m_m & 1)\r\n        {\r\n            stieltjes_zeros.resize(legendre_zeros.size() + 1, std::numeric_limits<Real>::quiet_NaN());\r\n            stieltjes_zeros[0] = 0;\r\n            k = 1;\r\n        }\r\n        else\r\n        {\r\n            stieltjes_zeros.resize(legendre_zeros.size(), std::numeric_limits<Real>::quiet_NaN());\r\n            k = 0;\r\n        }\r\n\r\n        while (k < (int)stieltjes_zeros.size())\r\n        {\r\n            Real lower_bound;\r\n            Real upper_bound;\r\n            if (m_m & 1)\r\n            {\r\n                lower_bound = legendre_zeros[k - 1];\r\n                if (k == (int)legendre_zeros.size())\r\n                {\r\n                    upper_bound = 1;\r\n                }\r\n                else\r\n                {\r\n                    upper_bound = legendre_zeros[k];\r\n                }\r\n            }\r\n            else\r\n            {\r\n                lower_bound = legendre_zeros[k];\r\n                if (k == (int)legendre_zeros.size() - 1)\r\n                {\r\n                    upper_bound = 1;\r\n                }\r\n                else\r\n                {\r\n                    upper_bound = legendre_zeros[k+1];\r\n                }\r\n            }\r\n\r\n            // The root bracketing is not very tight; to keep weird stuff from happening\r\n            // in the Newton's method, let's tighten up the tolerance using a few bisections.\r\n            boost::math::tools::eps_tolerance<Real> tol(6);\r\n            auto g = [&](Real t) { return this->operator()(t); };\r\n            auto p = boost::math::tools::bisect(g, lower_bound, upper_bound, tol);\r\n\r\n            Real x_nk_guess = p.first + (p.second - p.first)*half<Real>();\r\n            boost::uintmax_t number_of_iterations = 500;\r\n\r\n            auto f = [&] (Real x) { Real Pn = this->operator()(x);\r\n                                    Real Pn_prime = this->prime(x);\r\n                                    return std::pair<Real, Real>(Pn, Pn_prime); };\r\n\r\n            const Real x_nk = boost::math::tools::newton_raphson_iterate(f, x_nk_guess,\r\n                                                  p.first, p.second,\r\n                                                  2*std::numeric_limits<Real>::digits10,\r\n                                                  number_of_iterations);\r\n\r\n            BOOST_ASSERT(p.first < x_nk);\r\n            BOOST_ASSERT(x_nk < p.second);\r\n            stieltjes_zeros[k] = x_nk;\r\n            ++k;\r\n        }\r\n        return stieltjes_zeros;\r\n    }\r\n\r\nprivate:\r\n    // Coefficients of Legendre expansion\r\n    std::vector<Real> m_a;\r\n    int m_m;\r\n};\r\n\r\n}}\r\n#endif\r\n", "meta": {"hexsha": "788f1cc9eda3836a4ebbda9e3f509328d92ee218", "size": 7136, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "deps/boost/include/boost/math/special_functions/legendre_stieltjes.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/math/special_functions/legendre_stieltjes.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/math/special_functions/legendre_stieltjes.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": 30.2372881356, "max_line_length": 130, "alphanum_fraction": 0.4481502242, "num_tokens": 1830, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5544704796847396, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.31384056872063604}}
{"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 ERROREST_HH\n#define ERROREST_HH\n\n#include <vector>\n\n#include <boost/fusion/include/for_each.hpp>\n#include <boost/utility.hpp>\n#include <boost/multi_array.hpp>\n\nnamespace Kaskade \n{\n  /**\n   * \\ingroup refcrit\n   * \\brief Base class for refinement criteria.\n   */\n  class RefinementCriterion\n  {\n  public:\n    /**\n     * \\brief Computes the thresholds for refinement.\n     * \\param normalizedErrors a twodimensional array containing the normalized error contribution for each cell and\n     *                         each variable, i.e. normalizedErrors[i][j] contains the error contribution of cell i\n     *                         to the error in variable j, divided by the tolerance, such that the sum over i\n     *                         should not exceed one (for acceptance)\n     * \\returns an array containing a threshold value such that any cell i for which normalizedErrors[i][j] > return[j]\n     *          for any j is to be refined, or an empty array in case all variables are accurate enough\n     */\n    std::vector<double> threshold(boost::multi_array<double,2> const& normalizedErrors) const;\n    \n  private:\n    virtual double computeThreshold(std::vector<double>& normalizedErrors, double totalError, int j) const = 0;\n  };\n  \n  /**\n   * \\ingroup refcrit\n   * \\brief Refines the grid according to the normalized errors and the given thresholds.\n   */\n  template <class GridManager, class GridView>\n  void markAndRefine(GridManager& gridManager, GridView const& gridView, boost::multi_array<double,2> const& normalizedErrors, \n                     std::vector<double> const& threshold)\n  {\n    auto end = gridView.template end<0>();\n    for (auto ci=gridView.template begin<0>(); ci!=end; ++ci)\n    {\n      auto idx = gridView.indexSet().index(*ci);\n      for (int j=0; j<threshold.size(); ++j)\n        if (normalizedErrors[idx][j] >= threshold[j])\n        {\n          gridManager.mark(1,*ci);\n          break;\n        }\n    }\n    gridManager.adaptAtOnce();\n  }\n  \n  /**\n   * \\ingroup refcrit\n   * \\brief Fixed fraction refinement criterion.\n   * Determines the refinement thresholds such that at least the specified fraction of the cells are\n   * marked for refinement. This ensures that not too few cells are marked, which could lead to very many \n   * refinement iterations, but may lead to erratic refinement if there are indeed only very local refinements\n   * necessary.\n   * \n   * In very rare circumstances (namely when there are many cells with exactly the same local error estimate),\n   * much more cells than the required fraction can be marked for refinement.\n   */\n  class FixedFractionCriterion: public RefinementCriterion\n  {\n  public:\n    FixedFractionCriterion(double fraction = 0.2);\n    \n  private:\n    double fraction;\n    virtual double computeThreshold(std::vector<double>& normalizedErrors, double totalError, int j) const;\n  };\n  \n  /**\n   * \\ingroup refcrit\n   * \\brief Bulk refinement criterion.\n   * Determines the refinement thresholds such that approximately the specified fraction of the total error \n   * is removed by the refinement (under the unrealistically optimistic assumption that refinement eliminates\n   * the error completely in that cell - in reality, it's only reduced by a certain factor, so the total \n   * error is reduced somewhat less).\n   */\n  class BulkCriterion: public RefinementCriterion\n  {\n  public:\n    BulkCriterion(double fraction = 0.2);\n    \n  private:\n    double fraction;\n    virtual double computeThreshold(std::vector<double>& normalizedErrors, double totalError, int j) const;\n  };\n  \n  /**\n   * \\ingroup refcrit\n   * \\brief Max value refinement criterion.\n   * Determines the refinement thresholds such that all cells with an error contribution exceeding a certain \n   * fraction of the maximum error contribution are refined.\n   */\n  class MaxValueCriterion: public RefinementCriterion\n  {\n  public:\n    MaxValueCriterion(double fraction = 0.2);\n    \n  private:\n    double fraction;\n    virtual double computeThreshold(std::vector<double>& normalizedErrors, double totalError, int j) const;\n  };\n  \n  /**\n   * \\ingroup refcrit\n   * \\brief Babuska-Rheinboldt refinement criterion.\n   * Determines the refinement thresholds such that all cells with an error contribution exceeding the \n   * expected error contribution of the worst cell \\em after refinement will be marked. This tends to \n   * equilibrate the error contributions quite fast.\n   * \n   * Note that the local convergence order should be estimated (important in the vicinity of singularities)\n   * but is here assumed to be the fixed specified order.\n   */\n  class BabuskaRheinboldtCriterion: public MaxValueCriterion\n  {\n  public:\n    BabuskaRheinboldtCriterion(std::vector<int> const& order);\n    \n  private:\n    std::vector<int> order;\n    virtual double computeThreshold(std::vector<double>& normalizedErrors, double totalError, int j) const;\n  };\n  \n  //---------------------------------------------------------------------------------------------\n  \n  namespace ErrorestDetail\n  {\n    template <class GroupByCell>\n    struct GroupedSummationCollector\n    {\n      GroupedSummationCollector(GroupByCell const& group_):\n        group(group_)\n      {}\n      \n      template <class Cell>\n      int integrationOrder(Cell const& , int shapeFunctionOrder) const\n      {\n        return shapeFunctionOrder;\n      }\n      \n      // need to define this because boost::multi_array does not perform assignment if the arrays have\n      // different shape.\n      GroupedSummationCollector<GroupByCell>& operator=(GroupedSummationCollector<GroupByCell> const& c)\n      {\n        auto shape = c.sums.shape();\n\n        sums.resize(boost::extents[shape[0]][shape[1]]);\n        sums = c.sums;\n        group = c.group;\n\n        return *this;\n      }\n      \n      template <class CellPointer, class Index, class Sequence>\n      void operator()(CellPointer const& ci, Index idx, double weight, Sequence const& x)\n      {\n        if (sums.num_elements()==0)\n          sums.resize(boost::extents[group.nGroups][boost::fusion::size(x)]);\n        int i = 0; // for_each needs constant functor...\n        boost::fusion::for_each(x,Add(sums,group[idx],i,weight));\n      }\n      \n      void join(GroupedSummationCollector<GroupByCell> const& c)\n      {\n        auto shape = c.sums.shape();\n        auto myshape = sums.shape();\n        \n        if(c.sums.num_elements()==0) return;\n        if (sums.num_elements()==0 || myshape[0]!=shape[0] || myshape[1]!=shape[1]) // not yet initialized\n        {\n          sums.resize(boost::extents[shape[0]][shape[1]]);\n          sums = c.sums;                                  // -> do a simple copy\n        }\n        else\n          for (size_t i=0; i<shape[0]; ++i)               // otherwise add up\n            for (size_t j=0; j<shape[1]; ++j)\n              sums[i][j] += c.sums[i][j];\n      }\n\n      boost::multi_array<double,2> sums;\n\n    private:\n      GroupByCell group;\n\n      struct Add\n      {\n        Add(boost::multi_array<double,2>& sums_, int idx_, int& i_, double w_):\n          sums(sums_), idx(idx_), i(i_) , w(w_)\n        {}\n\n        template <class T>\n        void operator()(T const& t) const { sums[idx][i++] += w*t; }\n\n      private:\n        boost::multi_array<double,2>& sums;\n        int idx;\n        int& i;\n        double w;\n      };\n    };\n    \n  }\n}\n\n#endif\n", "meta": {"hexsha": "5e6a3bc05fe12d35beda603fa15212b5f1a4f4b1", "size": 8231, "ext": "hh", "lang": "C++", "max_stars_repo_path": "Kaskade/fem/errorest.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/errorest.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/errorest.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": 36.5822222222, "max_line_length": 127, "alphanum_fraction": 0.598226218, "num_tokens": 1867, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.554470450236115, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.31384055205216865}}
{"text": "\n#include \"distances.h\"\n#include <EMD_wrapper.h>\n\n#define EIGEN_NO_DEBUG\n#define EIGEN_DONT_PARALLELIZE\n#include <Eigen/Dense>\n\n#include <cmath> // for std::isnormal\n#include <limits>\n#include <vector>\n\n#if defined(WITH_ARRAYFIRE)\n#include <cuda_runtime.h>\n#if WITH_GPU_PROFILING\n#include <nvtx3/nvToolsExt.h>\n#endif\n#define AF_DEFINE_CUDA_TYPES\n#include <af/cuda.h>\n#include <arrayfire.h>\n\n#include \"lp_distance.cuh\"\n\nusing af::array;\n#endif\n\nusing MatrixXd = Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>;\n\nstd::vector<Metric> expand_metrics(const ManifoldGenerator& generator, int E, Distance distance,\n                                   const std::vector<Metric>& metrics)\n{\n  // Expand the 'metrics' vector now that we know the value of E.\n  std::vector<Metric> expandedMetrics;\n\n  // For the Wasserstein distance, it's more convenient to have one 'metric' for each variable (before taking lags).\n  // However, for the L^1 / L^2 distances, it's more convenient to have one 'metric' for each individual\n  // point of each observations, so metrics.size() == M.E_actual().\n  if (distance == Distance::Wasserstein) {\n    // Add a metric for the main variable and for the dt variable.\n    // These are always treated as a continuous values (though perhaps in the future this will change).\n    expandedMetrics.push_back(Metric::Diff);\n    if (generator.E_dt(E) > 0) {\n      expandedMetrics.push_back(Metric::Diff);\n    }\n\n    // Add in the metrics for the 'extra' variables as they were supplied to us.\n    for (int k = 0; k < generator.numExtras(); k++) {\n      expandedMetrics.push_back(metrics[k]);\n    }\n  } else {\n    // Add metrics for the main variable and the dt variable and their lags.\n    // These are always treated as a continuous values (though perhaps in the future this will change).\n    for (int lagNum = 0; lagNum < E + generator.E_dt(E); lagNum++) {\n      expandedMetrics.push_back(Metric::Diff);\n    }\n\n    // The user specified how to treat the extra variables.\n    for (int k = 0; k < generator.numExtras(); k++) {\n      int numLags = (k < generator.numExtrasLagged()) ? E : 1;\n      for (int lagNum = 0; lagNum < numLags; lagNum++) {\n        expandedMetrics.push_back(metrics[k]);\n      }\n    }\n  }\n\n  return expandedMetrics;\n}\n\nDistanceIndexPairs lazy_lp_distances(int Mp_i, const Options& opts, const Manifold& M, const Manifold& Mp)\n{\n  std::vector<int> inds;\n  std::vector<double> dists;\n\n  inds.reserve(M.numPoints());\n  dists.reserve(M.numPoints());\n\n  // We'll store the points we are comparing in the following two arrays.\n  auto x = std::unique_ptr<double[]>(new double[M.E_actual()], std::default_delete<double[]>());\n  auto y = std::unique_ptr<double[]>(new double[M.E_actual()], std::default_delete<double[]>());\n\n  Mp.lazy_fill_in_point(Mp_i, y.get());\n\n  const bool skipOtherPanels = opts.panelMode && (opts.idw < 0);\n\n  // Compare every observation in the M manifold to the\n  // Mp_i'th observation in the Mp manifold.\n  for (int i = 0; i < M.numPoints(); i++) {\n\n    if (skipOtherPanels && (M.panel(i) != Mp.panel(Mp_i))) {\n      continue;\n    }\n\n    // Calculate the distance between M[i] and Mp[Mp_i]\n    double dist_i = 0.0;\n\n    M.lazy_fill_in_point(i, x.get());\n\n    // If we have panel data and the M[i] / Mp[Mp_j] observations come from different panels\n    // then add the user-supplied penalty/distance for the mismatch.\n    if (opts.panelMode && opts.idw > 0) {\n      dist_i += opts.idw * (M.panel(i) != Mp.panel(Mp_i));\n    }\n\n    for (int j = 0; j < M.E_actual(); j++) {\n      // Get the sub-distance between M[i,j] and Mp[Mp_i, j]\n      double dist_ij;\n\n      // If either of these values is missing, the distance from\n      // M[i,j] to Mp[Mp_i, j] is opts.missingdistance.\n      // However, if the user doesn't specify this, then the entire\n      // M[i] to Mp[Mp_i] distance is set as missing.\n      if ((x[j] == MISSING_D) || (y[j] == MISSING_D)) {\n        if (opts.missingdistance == 0) {\n          dist_i = MISSING_D;\n          break;\n        } else {\n          dist_ij = opts.missingdistance;\n        }\n      } else { // Neither M[i,j] nor Mp[Mp_i, j] is missing.\n        // How do we compare them? Do we treat them like continuous values and subtract them,\n        // or treat them like unordered categorical variables and just check if they're the same?\n        if (opts.metrics[j] == Metric::Diff) {\n          dist_ij = x[j] - y[j];\n        } else { // Metric::CheckSame\n          dist_ij = (x[j] != y[j]);\n        }\n      }\n\n      if (opts.distance == Distance::MeanAbsoluteError) {\n        dist_i += abs(dist_ij) / M.E_actual();\n      } else { // Distance::Euclidean\n        dist_i += dist_ij * dist_ij;\n      }\n    }\n\n    if (dist_i != 0 && dist_i != MISSING_D) {\n      if (opts.distance == Distance::MeanAbsoluteError) {\n        dists.push_back(dist_i);\n      } else { // Distance::Euclidean\n        dists.push_back(sqrt(dist_i));\n      }\n      inds.push_back(i);\n    }\n  }\n\n  return { inds, dists };\n}\n\nDistanceIndexPairs eager_lp_distances(int Mp_i, const Options& opts, const Manifold& M, const Manifold& Mp)\n{\n  std::vector<int> inds;\n  std::vector<double> dists;\n\n  inds.reserve(M.numPoints());\n  dists.reserve(M.numPoints());\n\n  const bool skipOtherPanels = opts.panelMode && (opts.idw < 0);\n\n  // Compare every observation in the M manifold to the\n  // Mp_i'th observation in the Mp manifold.\n  for (int i = 0; i < M.numPoints(); i++) {\n\n    if (skipOtherPanels && (M.panel(i) != Mp.panel(Mp_i))) {\n      continue;\n    }\n\n    // Calculate the distance between M[i] and Mp[Mp_i]\n    double dist_i = 0.0;\n\n    // If we have panel data and the M[i] / Mp[Mp_j] observations come from different panels\n    // then add the user-supplied penalty/distance for the mismatch.\n    if (opts.panelMode && opts.idw > 0) {\n      dist_i += opts.idw * (M.panel(i) != Mp.panel(Mp_i));\n    }\n\n    for (int j = 0; j < M.E_actual(); j++) {\n      // Get the sub-distance between M[i,j] and Mp[Mp_i, j]\n      double dist_ij;\n\n      // If either of these values is missing, the distance from\n      // M[i,j] to Mp[Mp_i, j] is opts.missingdistance.\n      // However, if the user doesn't specify this, then the entire\n      // M[i] to Mp[Mp_i] distance is set as missing.\n      if ((M(i, j) == MISSING_D) || (Mp(Mp_i, j) == MISSING_D)) {\n        if (opts.missingdistance == 0) {\n          dist_i = MISSING_D;\n          break;\n        } else {\n          dist_ij = opts.missingdistance;\n        }\n      } else { // Neither M[i,j] nor Mp[Mp_i, j] is missing.\n        // How do we compare them? Do we treat them like continuous values and subtract them,\n        // or treat them like unordered categorical variables and just check if they're the same?\n        if (opts.metrics[j] == Metric::Diff) {\n          dist_ij = M(i, j) - Mp(Mp_i, j);\n        } else { // Metric::CheckSame\n          dist_ij = (M(i, j) != Mp(Mp_i, j));\n        }\n      }\n\n      if (opts.distance == Distance::MeanAbsoluteError) {\n        dist_i += abs(dist_ij) / M.E_actual();\n      } else { // Distance::Euclidean\n        dist_i += dist_ij * dist_ij;\n      }\n    }\n\n    if (dist_i != 0 && dist_i != MISSING_D) {\n      if (opts.distance == Distance::MeanAbsoluteError) {\n        dists.push_back(dist_i);\n      } else { // Distance::Euclidean\n        dists.push_back(sqrt(dist_i));\n      }\n      inds.push_back(i);\n    }\n  }\n\n  return { inds, dists };\n}\n\n// This function compares the M(i,.) multivariate time series to the Mp(j,.) multivariate time series.\n// The M(i,.) observation has data for E consecutive time points (e.g. time(i), time(i+1), ..., time(i+E-1)) and\n// the Mp(j,.) observation corresponds to E consecutive time points (e.g. time(j), time(j+1), ..., time(j+E-1)).\n// At each time instant we observe n >= 1 pieces of data.\n// These may either be continuous data or unordered categorical data.\n//\n// The Wasserstein distance (using the 'curve-matching' strategy) is equivalent to the (minimum) cost of turning\n// the first time series into the second time series. In a simple example, say E = 2 and n = 1, and\n//         M(i,.) = [ 1, 2 ] and Mp(j,.) = [ 2, 2 ].\n// To turn M(i,.) into Mp(j,.) the first element needs to be increased by 1, so the overall cost is\n//         Wasserstein( M(i,.), Mp(j,.) ) = 1.\n// The distance can also reorder the points, so for example say\n//         M(i,.) = [ 1, 100 ] and Mp(j,.) = [ 100, 1 ].\n// If we just change the 1 to 100 and the 100 to 1 then the cost of each is 99 + 99 = 198.\n// However, Wasserstein can instead reorder these points at a cost of\n//         Wasserstein( M(i,.), Mp(j,.) ) = 2 * gamma * (time(1)-time(2))\n// so if the observations occur on a regular grid so time(i) = i then the distance will just be 2 * gamma.\n//\n// The return value of this function is a matrix which shows the pairwise costs associated to each\n// potential Wasserstein solution. E.g. the (n,m) element of the returned matrix shows the cost\n// of turning the individual point M(i, n) into Mp(j, m).\n//\n// When there are missing values in one or other observation, we can either ignore this time period\n// and compute the Wasserstein for the mismatched regime where M(i,.) is of size len_i and Mp(j,.) is\n// of size len_j, where len_i != len_j is possible. Alternatively, we can fill in the affected elements\n// of the cost matrix with some user-supplied 'missingDistance' value and then len_i == len_j is upheld.\nstd::unique_ptr<double[]> wasserstein_cost_matrix(const Manifold& M, const Manifold& Mp, int i, int j,\n                                                  const Options& opts, int& len_i, int& len_j)\n{\n  // The M(i,.) observation will be stored as one flat vector of length M.E_actual():\n  // - the first M.E() observations will the lagged version of the main time series\n  // - the next M.E() observations will be the lagged 'dt' time series (if it is included, i.e., if M.E_dt() > 0)\n  // - the next n * M.E() observations will be the n lagged extra variables,\n  //   so in total that is M.E_lagged_extras() = n * M.E() observations\n  // - the remaining M.E_actual() - M.E() - M.E_dt() - M.E_lagged_extras() are the unlagged extras and the distance\n  //   between those two vectors forms a kind of minimum distance which is added to the time-series curve matching\n  //   Wasserstein distance.\n\n  bool skipMissing = (opts.missingdistance == 0);\n\n  // We'll store the points we are comparing in the following two arrays.\n  auto x = std::unique_ptr<double[]>(new double[M.E_actual()], std::default_delete<double[]>());\n  auto y = std::unique_ptr<double[]>(new double[M.E_actual()], std::default_delete<double[]>());\n\n  if (opts.lowMemoryMode) {\n    M.lazy_fill_in_point(i, x.get());\n    Mp.lazy_fill_in_point(j, y.get());\n  } else {\n    M.eager_fill_in_point(i, x.get());\n    Mp.eager_fill_in_point(j, y.get());\n  }\n\n  int numLaggedExtras = M.E_lagged_extras() / M.E();\n\n  auto M_i = Eigen::Map<MatrixXd>(x.get(), 1 + (M.E_dt() > 0) + numLaggedExtras, M.E());\n  auto Mp_j = Eigen::Map<MatrixXd>(y.get(), 1 + (M.E_dt() > 0) + numLaggedExtras, M.E());\n\n  auto M_i_missing = (M_i.array() == M.missing()).colwise().any();\n  auto Mp_j_missing = (Mp_j.array() == Mp.missing()).colwise().any();\n\n  if (skipMissing) {\n    // N.B. Can't .sum() a vector of bools to count them in Eigen.\n    len_i = M.E() - M_i_missing.count();\n    len_j = Mp.E() - Mp_j_missing.count();\n  } else {\n    len_i = M.E();\n    len_j = Mp.E();\n  }\n\n  double gamma = 1.0;\n  if (M.E_dt() > 0) {\n    // Imagine the M_i time series as a plot, and calculate the\n    // aspect ratio of this plot, so we can rescale the time variable\n    // to get the user-supplied aspect ratio.\n    double minData = std::numeric_limits<double>::max();\n    double maxData = std::numeric_limits<double>::min();\n    double maxTime = 0.0;\n    for (int t = 0; t < M_i.cols(); t++) {\n      if (M_i(0, t) != MISSING_D) {\n        if (M_i(0, t) < minData) {\n          minData = M_i(0, t);\n        }\n        if (M_i(0, t) > maxData) {\n          maxData = M_i(0, t);\n        }\n      }\n      if (M_i(1, t) != MISSING_D && M_i(1, t) > maxTime) {\n        maxTime = M_i(1, t);\n      }\n    }\n\n    double epsilon = 1e-6; // Some small number in case the following ratio gets wildly large/small\n    gamma = opts.aspectRatio * (maxData - minData + epsilon) / (maxTime + epsilon);\n  }\n\n  int timeSeriesDim = M_i.rows();\n\n  double unlaggedDist = 0.0;\n  int numUnlaggedExtras = M.E_extras() - M.E_lagged_extras();\n  for (int e = 0; e < numUnlaggedExtras; e++) {\n    double x_e = x[M_i.size() + e];\n    double y_e = y[Mp_j.size() + e];\n\n    bool eitherMissing = (x_e == M.missing()) || (y_e == M.missing());\n\n    if (eitherMissing) {\n      unlaggedDist += opts.missingdistance;\n    } else {\n      if (opts.metrics[timeSeriesDim + e] == Metric::Diff) {\n        unlaggedDist += abs(x_e - y_e);\n      } else {\n        unlaggedDist += (x_e != y_e);\n      }\n    }\n  }\n\n  // If we have panel data and the M[i] / Mp[j] observations come from different panels\n  // then add the user-supplied penalty/distance for the mismatch.\n  if (opts.panelMode && opts.idw > 0) {\n    unlaggedDist += opts.idw * (M.panel(i) != Mp.panel(j));\n  }\n\n  auto flatCostMatrix = std::make_unique<double[]>(len_i * len_j);\n  std::fill_n(flatCostMatrix.get(), len_i * len_j, unlaggedDist);\n  Eigen::Map<MatrixXd> costMatrix(flatCostMatrix.get(), len_i, len_j);\n\n  for (int k = 0; k < timeSeriesDim; k++) {\n    int n = 0;\n    for (int nn = 0; nn < M_i.cols(); nn++) {\n      if (skipMissing && M_i_missing[nn]) {\n        continue;\n      }\n\n      int m = 0;\n\n      for (int mm = 0; mm < Mp_j.cols(); mm++) {\n        if (skipMissing && Mp_j_missing[mm]) {\n          continue;\n        }\n        double dist;\n        bool eitherMissing = M_i_missing[nn] || Mp_j_missing[mm];\n\n        if (eitherMissing) {\n          dist = opts.missingdistance;\n        } else {\n          if (opts.metrics[k] == Metric::Diff) {\n            dist = abs(M_i(k, nn) - Mp_j(k, mm));\n          } else {\n            dist = M_i(k, nn) != Mp_j(k, mm);\n          }\n        }\n\n        // For the time data, we add in the 'gamma' scaling factor calculated earlier\n        if ((M.E_dt() > 0) && (k == 1)) {\n          dist *= gamma;\n        }\n\n        costMatrix(n, m) += dist;\n\n        m += 1;\n      }\n\n      n += 1;\n    }\n  }\n\n  return flatCostMatrix;\n}\n\n// TODO: Subtract the D(x,x) and D(y,y) parts from this.\ndouble approx_wasserstein(double* C, int len_i, int len_j, double eps, double stopErr)\n{\n  Eigen::Map<Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>> costMatrix(C, len_i, len_j);\n\n  double r = 1.0 / len_i;\n  double c = 1.0 / len_j;\n\n  Eigen::MatrixXd K = Eigen::exp(-costMatrix.array() / eps);\n  Eigen::MatrixXd Kp = len_i * K.array();\n\n  Eigen::VectorXd u = Eigen::VectorXd::Ones(len_i) / len_i;\n  Eigen::VectorXd v = Eigen::VectorXd::Ones(len_j) / len_j;\n\n  int maxIter = 10000;\n  for (int iter = 0; iter < maxIter; iter++) {\n\n    v = c / (K.transpose() * u).array();\n    u = 1.0 / (Kp * v).array();\n\n    if (iter % 10 == 0) {\n      // Compute right marginal (diag(u) K diag(v))^T1\n      Eigen::VectorXd tempColSums = (u.asDiagonal() * K * v.asDiagonal()).colwise().sum();\n      double LInfErr = (tempColSums.array() - c).abs().maxCoeff();\n      if (LInfErr < stopErr) {\n        break;\n      }\n    }\n  }\n\n  Eigen::MatrixXd transportPlan = u.asDiagonal() * K * v.asDiagonal();\n  double dist = (transportPlan.array() * costMatrix.array()).sum();\n  return dist;\n}\n\ndouble wasserstein(double* C, int len_i, int len_j)\n{\n  // Create vectors which are just 1/len_i and 1/len_j of length len_i and len_j.\n  auto w_1 = std::make_unique<double[]>(len_i);\n  std::fill_n(w_1.get(), len_i, 1.0 / len_i);\n  auto w_2 = std::make_unique<double[]>(len_j);\n  std::fill_n(w_2.get(), len_j, 1.0 / len_j);\n\n  int maxIter = 10000;\n  double cost;\n  EMD_wrap(len_i, len_j, w_1.get(), w_2.get(), C, &cost, maxIter);\n  return cost;\n}\n\nDistanceIndexPairs wasserstein_distances(int Mp_i, const Options& opts, const Manifold& M, const Manifold& Mp)\n{\n  std::vector<int> inds;\n  std::vector<double> dists;\n\n  inds.reserve(M.numPoints());\n  dists.reserve(M.numPoints());\n\n  const bool skipOtherPanels = opts.panelMode && (opts.idw < 0);\n\n  // Compare every observation in the M manifold to the\n  // Mp_i'th observation in the Mp manifold.\n  for (int i = 0; i < M.numPoints(); i++) {\n\n    if (skipOtherPanels && (M.panel(i) != Mp.panel(Mp_i))) {\n      continue;\n    }\n\n    int len_i, len_j;\n    auto C = wasserstein_cost_matrix(M, Mp, i, Mp_i, opts, len_i, len_j);\n\n    if (len_i > 0 && len_j > 0) {\n      double dist_i = wasserstein(C.get(), len_i, len_j);\n\n      // Alternatively, the approximate version based on Sinkhorn's algorithm can be called with something like:\n      // double dist_i = approx_wasserstein(C.get(), len_i, len_j, 0.1, 0.1)\n      // In that case, the \"std::isnormal\" is really needed on the next line, as some\n      // instability gives us some 'nan' distances using that method.\n\n      if (dist_i != 0 && std::isnormal(dist_i)) {\n        dists.push_back(dist_i);\n        inds.push_back(i);\n      }\n    }\n  }\n\n  return { inds, dists };\n}\n\n/////////////////////////////////////////////////////////////// ArrayFire PORTED versions BEGIN HERE\n\n#if defined(WITH_ARRAYFIRE)\nDistanceIndexPairsOnGPU afLPDistances(const int numPredictions, const Options& opts, const ManifoldOnGPU& M,\n                                      const ManifoldOnGPU& Mp, const af::array& metricOpts)\n{\n  constexpr bool useCustomKernel = true;\n\n#if WITH_GPU_PROFILING\n  auto range = nvtxRangeStartA(__FUNCTION__);\n#endif\n\n  const af_dtype cType = M.mdata.type();\n\n  if (useCustomKernel) {\n    af::array valids(M.numPoints, numPredictions, b8);\n    af::array dists(M.numPoints, numPredictions, cType);\n    if (cType == f64) {\n      cuLPDistances(valids.device<char>(), dists.device<double>(), numPredictions,\n                    opts.distance == Distance::MeanAbsoluteError, opts.panelMode, opts.idw, opts.missingdistance,\n                    M.E_actual, M.numPoints, M.mdata.device<double>(), M.panel.device<int>(), Mp.mdata.device<double>(),\n                    Mp.panel.device<int>(), metricOpts.device<char>(), afcu::getStream(0));\n    } else if (cType == f32) {\n      cuLPDistances(valids.device<char>(), dists.device<float>(), numPredictions,\n                    opts.distance == Distance::MeanAbsoluteError, opts.panelMode, opts.idw, opts.missingdistance,\n                    M.E_actual, M.numPoints, M.mdata.device<float>(), M.panel.device<int>(), Mp.mdata.device<float>(),\n                    Mp.panel.device<int>(), metricOpts.device<char>(), afcu::getStream(0));\n    }\n    valids.unlock();\n    dists.unlock();\n    M.mdata.unlock();\n    M.panel.unlock();\n    Mp.mdata.unlock();\n    Mp.panel.unlock();\n    metricOpts.unlock();\n\n#if WITH_GPU_PROFILING\n    nvtxRangeEnd(range);\n#endif\n    return { valids, dists };\n  } else {\n    using af::array;\n    using af::moddims;\n    using af::select;\n    using af::seq;\n    using af::span;\n    using af::sum;\n    using af::tile;\n\n    // Mp_i goes from 0 to numPredictions - 1\n    // All coloumns of Manifold M are considered valid for batch operation\n\n    const bool imdoZero = opts.missingdistance == 0;\n    const int numLibraryPoints = M.numPoints;\n    const int eacts = M.E_actual;\n\n    array anyMCols, distsMat;\n    {\n      array predsM = tile(M.mdata, 1, 1, numPredictions);\n      array predsMp = tile(moddims(Mp.mdata(span, seq(numPredictions)), eacts, 1, numPredictions), 1, numLibraryPoints);\n      array diffMMp = predsM - predsMp;\n      array compMMp = (predsM != predsMp).as(cType);\n      array distMMp = select(tile(metricOpts, 1, numLibraryPoints, numPredictions), diffMMp, compMMp);\n      array missing = predsM == MISSING_D || predsMp == MISSING_D;\n\n      distsMat = (imdoZero ? distMMp : select(missing, opts.missingdistance, distMMp));\n      anyMCols = anyTrue(missing, 0);\n\n      if (opts.distance == Distance::MeanAbsoluteError) {\n        distsMat = af::abs(distsMat) / double(eacts);\n      } else {\n        distsMat = distsMat * distsMat;\n      }\n    }\n    if (opts.panelMode && opts.idw > 0) {\n      array npPanelMp = tile(Mp.panel(seq(numPredictions)).T(), numLibraryPoints);\n      array npPanelM = tile(M.panel, 1, numPredictions);\n      array penalty = (opts.idw * (npPanelM != npPanelMp));\n      array penalties = tile(moddims(penalty, 1, numLibraryPoints, numPredictions), eacts);\n\n      distsMat += penalties;\n    }\n    array accDists = sum(distsMat, 0);\n    array distances = select(anyMCols * imdoZero, double(MISSING_D), accDists);\n    array valids = (distances != 0.0 && distances != double(MISSING_D));\n    array dists = (opts.distance == Distance::MeanAbsoluteError ? distances : af::sqrt(distances));\n\n    valids = moddims(valids, numLibraryPoints, numPredictions);\n    dists = moddims(dists, numLibraryPoints, numPredictions);\n\n#if WITH_GPU_PROFILING\n    nvtxRangeEnd(range);\n#endif\n    return { valids, dists };\n  }\n}\n\narray afWassersteinCostMatrix(const bool& skipMissing, const Options& opts, const array& metricOpts,\n                              const ManifoldOnGPU& M, const array& M_i, const array& M_i_missing, const array& x,\n                              const int& len_i, const array& Mp_j, const array& Mp_j_missing, const array& y,\n                              const int& len_j, const bool arePanelIdsSame)\n{\n  using af::array;\n  using af::constant;\n  using af::dim4;\n  using af::moddims;\n  using af::seq;\n  using af::span;\n  using af::sum;\n  using af::tile;\n  using af::where;\n\n  const af_dtype cType = M.mdata.type();\n\n  double gamma = 1.0;\n  if (M.E_dt > 0) {\n    array firstColumn = M_i(span, 0);\n    array nonMissings = firstColumn != MISSING_D;\n    array validIndexs = where(nonMissings);\n    array validValues = firstColumn(validIndexs);\n    double minData = af::min<double>(validValues);\n    double maxData = af::max<double>(validValues);\n    double maxTime = af::max<double>(M_i(span, 1));\n\n    // Some small number in case the following ratio gets wildly large/small\n    constexpr double epsilon = 1e-6;\n\n    gamma = opts.aspectRatio * (maxData - minData + epsilon) / (maxTime + epsilon);\n  }\n\n  const int timeSeriesDim = M_i.dims(1);\n  double unlaggedDist = 0.0;\n  {\n    const int numUnlaggedExtras = M.E_extras - M.E_lagged_extras;\n\n    array eitherMissing = (x == M.missing || y == M.missing);\n\n    array cond = metricOpts(seq(timeSeriesDim, numUnlaggedExtras + timeSeriesDim - 1));\n    array ulDists = (cond * af::abs(x - y) + (1 - cond) * (x != y).as(cType));\n    array dists = (eitherMissing * opts.missingdistance + (1 - eitherMissing) * ulDists);\n    unlaggedDist = sum<double>(dists);\n  }\n\n  if (opts.panelMode && opts.idw > 0) {\n    unlaggedDist += opts.idw * arePanelIdsSame;\n  }\n\n  const seq timeSeries(timeSeriesDim);\n  array costMatrix = af::constant(unlaggedDist, len_j, len_i, cType);\n\n  array cmIsMetricDiff = metricOpts(timeSeries);\n  cmIsMetricDiff = tile(moddims(cmIsMetricDiff, 1, 1, timeSeriesDim), len_j, len_i);\n\n  if (skipMissing) {\n    // In this case: Unless both entries are available, no need to process anything else\n    array idxM_i_missing = where(!M_i_missing);\n    array idxMp_j_missing = where(!Mp_j_missing);\n\n    array Mp_j_k = moddims(Mp_j(idxMp_j_missing, timeSeries), len_j, 1, timeSeriesDim);\n    array M_i_k = moddims(M_i(idxM_i_missing, timeSeries), 1, len_i, timeSeriesDim);\n    array cmMp_j = tile(Mp_j_k, 1, len_i);\n    array cmM_i = tile(M_i_k, len_j);\n    array cmDiff = select(cmIsMetricDiff, af::abs(cmMp_j - cmM_i), (cmM_i != cmMp_j).as(cType));\n\n    if (M.E_dt > 0) {\n      // For time series k = 1, scale by gamma\n      cmDiff(span, span, 1) *= gamma;\n    }\n    costMatrix += sum(cmDiff, 2); // Add results to unlaggedDist\n  } else {\n    array Mp_j_missingT = tile(Mp_j_missing, 1, M_i_missing.dims(0)); // cost matrix shape\n    array M_i_missingT = tile(M_i_missing.T(), Mp_j_missing.dims(0)); // cost matrix shape\n    array eitherMissing = (M_i_missingT || Mp_j_missingT);            // one of the entries missing\n    array eitherMissingT = tile(eitherMissing, 1, 1, timeSeriesDim);  // [len_j len_i timeSeriesDim 1]\n\n    array Mp_j_k = moddims(Mp_j(span, timeSeries), len_j, 1, timeSeriesDim);\n    array M_i_k = moddims(M_i(span, timeSeries), 1, len_i, timeSeriesDim);\n    array cmMp_j = tile(Mp_j_k, 1, len_i);\n    array cmM_i = tile(M_i_k, len_j);\n    array cmDiff = select(cmIsMetricDiff, af::abs(cmMp_j - cmM_i), (cmM_i != cmMp_j).as(cType));\n    array cmDist = select(eitherMissingT, opts.missingdistance, cmDiff);\n\n    if (M.E_dt > 0) {\n      // For time series k = 1, scale by gamma\n      cmDist(span, span, 1) *= gamma;\n    }\n    costMatrix += sum(cmDist, 2); // Add results to unlaggedDist\n  }\n\n  return costMatrix;\n}\n\nDistanceIndexPairs afWassersteinDistances(int Mp_i, const Options& opts, const Manifold& hostM, const Manifold& hostMp,\n                                          const ManifoldOnGPU& M, const ManifoldOnGPU& Mp,\n                                          const std::vector<int>& inpInds, const af::array& metricOpts)\n{\n  using af::anyTrue;\n  using af::seq;\n\n  const bool skipMissing = (opts.missingdistance == 0);\n\n  // Precompute values that are iteration invariant\n  const seq mpjRange0(Mp.E_x);\n  const seq mpjRange1(Mp_i, Mp_i + 1 + (Mp.E_dt > 0) + Mp.E_lagged_extras / Mp.E_x);\n\n  const array Mp_j = Mp.mdata(mpjRange0, mpjRange1);\n\n  const array Mp_j_missing = anyTrue(Mp_j == Mp.missing, 1);\n\n  const int numUnlaggedExtrasEnd = M.E_extras - M.E_lagged_extras;\n\n  const seq xseq(M.E_x + M.E_dt + M.E_lagged_extras, M.E_x + M.E_dt + M.E_lagged_extras + numUnlaggedExtrasEnd - 1);\n  const seq yseq(Mp.E_x + Mp.E_dt + Mp.E_lagged_extras,\n                 Mp.E_x + Mp.E_dt + Mp.E_lagged_extras + numUnlaggedExtrasEnd - 1);\n\n  const array y = Mp.mdata(yseq, Mp_i);\n  const int len_j = (skipMissing ? Mp.E_x - af::sum<int>(Mp_j_missing) : Mp.E_x);\n\n  // Since both len_i and len_j should be greater than zero\n  // to collect valid indices and respective distances, just return empty handed\n  if (len_j <= 0) {\n    return {};\n  }\n\n  // Return Items\n  std::vector<int> inds;\n  std::vector<double> dists;\n\n  // Compare every observation in the M manifold to the Mp_i'th observation in the Mp manifold.\n  for (int i : inpInds) {\n    const seq miRange0(M.E_x);\n    const seq miRange1(i, i + 1 + (M.E_dt > 0) + M.E_lagged_extras / M.E_x);\n\n    array M_i = M.mdata(miRange0, miRange1);\n\n    array M_i_missing = anyTrue(M_i == M.missing, 1);\n\n    array x = M.mdata(xseq, i);\n\n    const int len_i = (skipMissing ? M.E_x - af::sum<int>(M_i_missing) : M.E_x);\n\n    if (len_i > 0) { // Short-check for len_j already passed\n      // TODO I think afWassersteinCostMatrix can be further vectorized to run for all i's\n      array cm = afWassersteinCostMatrix(skipMissing, opts, metricOpts, M, M_i, M_i_missing, x, len_i, Mp_j,\n                                         Mp_j_missing, y, len_j, (hostM.panel(i) != hostMp.panel(Mp_i)));\n      std::vector<double> C(cm.elements());\n      cm.host(C.data());\n      double dist_i = wasserstein(C.data(), len_i, len_j);\n\n      // Alternative: approximate version based on Sinkhorn's algorithm\n      // double dist_i = approx_wasserstein(C.get(), len_i, len_j, 0.1, 0.1)\n      // In that case, the \"std::isnormal\" is really needed on the next line, as some\n      // instability gives us some 'nan' distances using that method.\n      if (dist_i != 0 && std::isnormal(dist_i)) {\n        dists.push_back(dist_i);\n        inds.push_back(i);\n      }\n    }\n  }\n\n  return { inds, dists };\n}\n#endif\n", "meta": {"hexsha": "f24fc393453c01de451c08d31a8388f179dad936", "size": 27554, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/distances.cpp", "max_stars_repo_name": "EDM-Developers/EDM", "max_stars_repo_head_hexsha": "f3e0ee6dc48809d635f0746ec910b8ac565aafce", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-04-27T00:21:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-23T03:46:04.000Z", "max_issues_repo_path": "src/distances.cpp", "max_issues_repo_name": "EDM-Developers/EDM", "max_issues_repo_head_hexsha": "f3e0ee6dc48809d635f0746ec910b8ac565aafce", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/distances.cpp", "max_forks_repo_name": "EDM-Developers/EDM", "max_forks_repo_head_hexsha": "f3e0ee6dc48809d635f0746ec910b8ac565aafce", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-09-17T17:14:07.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-17T17:14:07.000Z", "avg_line_length": 37.1848852901, "max_line_length": 120, "alphanum_fraction": 0.629200842, "num_tokens": 7843, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.658417500561683, "lm_q2_score": 0.47657965106367595, "lm_q1q2_score": 0.31378838267190456}}
{"text": "/**\n * ****************************************************************************\n * Copyright (c) 2015, Robert Lukierski.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n * \n * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * \n * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation\n * and/or other materials provided with the distribution.\n * \n * Neither the name of the copyright holder nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n * \n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\n * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n * \n * ****************************************************************************\n * Simple Kalman Filter.\n * ****************************************************************************\n */\n\n#ifndef VISIONCORE_MATH_KALMAN_HPP\n#define VISIONCORE_MATH_KALMAN_HPP\n\n#include <VisionCore/Platform.hpp>\n\n#include <Eigen/LU>\n\nnamespace vc\n{\n    \nnamespace math\n{\n    \n#if 0 // TODO FIXME\ntemplate<int dimension, class StateType>\nclass ConstantProcess {\npublic:\n    typedef Eigen::Matrix<double, StateType::DIM, 1> VecState;\n    typedef Eigen::Matrix<double, StateType::DIM, StateType::DIM> MatStateState;\n    \n    \n    /// Noise per second, per component\n    VecState sigma;\n    MatStateState noise;\n    MatStateState jacobian;\n    \n    inline ConstantProcess() :\n    sigma(VecState::Zero()),\n    noise(MatStateState::Zero()),\n    jacobian(MatStateState::Identity())\n    {}\n    \n    MatStateState const& getJacobian(StateType const& /*state*/, const double /*dt*/) {\n        /// No change over time due to process model\n        return jacobian;\n    }\n    \n    void updateState(StateType const& /*state*/, const double /*dt*/) {\n        /// no-op - no change due to process model\n    }\n    \n    MatStateState const& getNoiseCovariance(const double dt) {\n        noise = (dt * sigma).asDiagonal();\n        return noise;\n    }\n    \n    void updateFromMeasurement(StateType & state, VecState const & innovation) {\n        state.x += innovation;\n    }\n    \n};\n\ntemplate<class StateType>\nclass AbsoluteMeasurement {\npublic:\n    static const int DIM = StateType::DIM;\n    typedef Eigen::Matrix<double, DIM, 1> VecMeas;\n    typedef Eigen::Matrix<double, DIM, 1> VecState;\n    typedef Eigen::Matrix<double, DIM, DIM> MatMeasMeas;\n    typedef Eigen::Matrix<double, DIM, DIM> MatMeasState;\n    \n    VecMeas measurement;\n    \n    MatMeasState jacobian;\n    MatMeasMeas covariance;\n    \n    AbsoluteMeasurement() :\n    measurement(VecMeas::Zero()),\n    jacobian(MatMeasState::Identity()),\n    covariance(MatMeasMeas::Identity()) {}\n    \n    \n    MatMeasState const& getJacobian(StateType const& /*state*/) {\n        return jacobian;\n    }\n    \n    /// Measurement noise covariance, aka uncertainty\n    /// in measurement\n    MatMeasMeas const& getCovariance(StateType const& /*state*/) {\n        return covariance;\n    }\n    \n    VecState const getInnovation(StateType const& state) {\n        return measurement - state.x;\n    }\n    \n};\n\ntemplate<typename T, typename TimeT = T>\nclass KalmanFilter \n{\npublic:\n    typedef T Scalar;\n    typedef TimeT TimeType;\n    \n    template<unsigned int dim>\n    class StateT\n    {\n    public:\n        static const int Dimension = dim;\n        typedef Eigen::Matrix<Scalar, Dimension, 1> StateVectorT;\n        typedef Eigen::Matrix<Scalar, Dimension, Dimension> CovarianceMatrixT;\n        \n        StateVectorT StateVector;\n        CovarianceMatrixT Covariance;\n        \n        StateT() : StateVector(StateVectorT::Zero()), Covariance(CovarianceMatrixT::Identity()) \n        { \n            \n        }  \n    };\n    \n    template<unsigned int sdim, unsigned int mdim>\n    class MeasurementT\n    {\n    public:\n        typedef StateT<sdim> StateType;\n        static const int Dimension = mdim;\n        typedef Eigen::Matrix<Scalar, Dimension, 1> MeasurementVectorT;\n        typedef Eigen::Matrix<Scalar, StateType::Dimension, 1> StateVectorT;\n        typedef Eigen::Matrix<Scalar, Dimension, Dimension> JacobianMatrixT;\n        typedef Eigen::Matrix<Scalar, Dimension, StateType::Dimension> HMatrixT;\n\n        MeasurementT() \n        { \n            \n        }  \n    };\n    \n    template<unsigned int dim>\n    void predict(StateT<dim>& state, TimeType dt) \n    {\n        const StateT<dim>::CovarianceMatrixT A(processModel.getJacobian(state, dt));\n        state.Covariance = A * state.Covariance * A.transpose() + processModel.getNoiseCovariance(dt);\n        /// @todo symmetrize?\n        processModel.updateState(state, dt);\n    }\n    \n    template<class MeasurementType>\n    void correct(MeasurementType & m) \n    {\n        typedef Eigen::Matrix<Scalar, MeasurementType::DIM, StateType::DIM> MatMeasState;\n        typedef Eigen::Matrix<Scalar, MeasurementType::DIM, MeasurementType::DIM> MatMeasMeas;\n        typedef Eigen::Matrix<Scalar, MeasurementType::DIM, 1> VecMeas;\n        /// @todo implement\n        const MatMeasState & H = m.getJacobian(state);\n        const MatMeasMeas & R = m.getCovariance(state);\n        const VecState innovation = m.getInnovation(state);\n        const MatMeasMeas S = H * state.covariance * H.transpose() + R;\n\n        Eigen::eikfLUType<MatMeasMeas> luOfS = S.eikfLUFunc();\n        MatStateState K = state.covariance * H.transpose() * luOfS.inverse();\n        processModel.updateFromMeasurement(state, K * innovation);\n        state.covariance = (MatStateState::Identity() - K * H) * state.covariance;\n        \n    }\n    \n    \n};\n#endif\n\n}\n\n}\n\n#endif // VISIONCORE_MATH_KALMAN_HPP\n", "meta": {"hexsha": "94792c03388cb51a31c4c373605b2a3215384a03", "size": 6575, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/VisionCore/Math/Kalman.hpp", "max_stars_repo_name": "lukier/vision_core", "max_stars_repo_head_hexsha": "45cb1bf7b74e1e1d5aa1078494a328b317d5a368", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 29.0, "max_stars_repo_stars_event_min_datetime": "2016-10-30T23:59:11.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-30T12:27:40.000Z", "max_issues_repo_path": "include/VisionCore/Math/Kalman.hpp", "max_issues_repo_name": "jczarnowski/vision_core", "max_issues_repo_head_hexsha": "924c53339b1d99ebb3b1e358edfaa1a4e8d3703b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-05-19T04:45:41.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-07T01:32:22.000Z", "max_forks_repo_path": "include/VisionCore/Math/Kalman.hpp", "max_forks_repo_name": "lukier/vision_core", "max_forks_repo_head_hexsha": "45cb1bf7b74e1e1d5aa1078494a328b317d5a368", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2016-11-14T00:46:26.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-01T08:55:11.000Z", "avg_line_length": 32.5495049505, "max_line_length": 102, "alphanum_fraction": 0.6527756654, "num_tokens": 1470, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.658417500561683, "lm_q2_score": 0.47657965106367595, "lm_q1q2_score": 0.31378838267190456}}
{"text": "//=======================================================================\n// Copyright (c)\n//\n// Distributed under the Boost Software License, Version 1.0. (See\n// accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n//=======================================================================\n/**\n * @file scheduling_jobs.hpp\n * @brief\n * @author Robert Rosolek\n * @version 1.0\n * @date 2013-11-19\n */\n#ifndef PAAL_SCHEDULING_JOBS_HPP\n#define PAAL_SCHEDULING_JOBS_HPP\n\n#define BOOST_RESULT_OF_USE_DECLTYPE\n\n#include \"paal/data_structures/fraction.hpp\"\n#include \"paal/utils/functors.hpp\"\n#include \"paal/utils/type_functions.hpp\"\n#include \"paal/utils/irange.hpp\"\n#include \"paal/utils/assign_updates.hpp\"\n\n#include <boost/range/algorithm/copy.hpp>\n#include <boost/range/algorithm/sort.hpp>\n#include <boost/range/counting_range.hpp>\n#include <boost/range/iterator_range.hpp>\n#include <boost/range/numeric.hpp>\n\n#include <algorithm>\n#include <cassert>\n#include <iterator>\n#include <numeric>\n#include <random>\n#include <utility>\n#include <vector>\n\nnamespace paal {\nnamespace greedy {\n\nnamespace detail {\n\ntemplate <class MachineIterator, class JobIterator, class GetSpeed,\n          class GetLoad>\nstruct sched_traits {\n    typedef typename std::iterator_traits<MachineIterator>::reference\n        machine_reference;\n    typedef typename std::iterator_traits<JobIterator>::reference job_reference;\n    typedef pure_result_of_t<GetSpeed(machine_reference)> speed_t;\n    typedef pure_result_of_t<GetLoad(job_reference)> load_t;\n    typedef data_structures::fraction<load_t, speed_t> frac_t;\n};\n\ntemplate <class MachineIterator, class JobIterator, class GetSpeed,\n          class GetLoad, class Traits = sched_traits<\n                             MachineIterator, JobIterator, GetSpeed, GetLoad>>\ntypename Traits::frac_t calculate_bound(const MachineIterator mfirst,\n                                        const MachineIterator mlast,\n                                        const JobIterator jfirst,\n                                        const JobIterator jlast,\n                                        GetSpeed get_speed, GetLoad get_load) {\n    typedef typename Traits::speed_t Speed;\n    typedef typename Traits::load_t Load;\n    typedef typename Traits::frac_t Frac;\n\n    auto jobs_num = jlast - jfirst;\n    auto machines_num = mlast - mfirst;\n\n    std::vector<Speed> speed_sum(machines_num);\n    std::transform(mfirst, mlast, speed_sum.begin(), get_speed);\n    boost::partial_sum(speed_sum, speed_sum.begin());\n\n    std::vector<Load> load_sum(jobs_num);\n    std::transform(jfirst, jlast, load_sum.begin(), get_load);\n    boost::partial_sum(load_sum, load_sum.begin());\n\n    typedef decltype(machines_num) MachinesNumType;\n    assert(jobs_num > 0 && machines_num > 0);\n    Frac result(get_load(*jfirst), get_speed(*mfirst));\n    for (auto jobID : irange(jobs_num)) {\n        Load load = get_load(jfirst[jobID]);\n        auto get_single = [ = ](MachinesNumType i) {\n            return Frac(load, get_speed(mfirst[i]));\n        };\n        auto get_summed = [&](MachinesNumType i) {\n            return Frac(load_sum[jobID], speed_sum[i]);\n        };\n        auto condition = [ = ](MachinesNumType i) {\n            return get_summed(i) >= get_single(i);\n        };\n        auto machines_ids = boost::counting_range(\n            static_cast<MachinesNumType>(0), machines_num);\n        // current range based version in boost is broken\n        // should be replaced when released\n        // https://github.com/boostorg/algorithm/pull/4\n        auto it = std::partition_point(machines_ids.begin(), machines_ids.end(),\n                                       condition);\n        MachinesNumType machineID =\n            (it != machines_ids.end()) ? *it : machines_num - 1;\n        auto getMax = [ = ](MachinesNumType i) {\n            return std::max(get_single(i), get_summed(i));\n        };\n\n        Frac candidate = getMax(machineID);\n        if (machineID != 0) {\n            assign_min(candidate, getMax(machineID - 1));\n        }\n        assign_max(result, candidate);\n    }\n    return result;\n}\n\ntemplate <class MachineIterator, class JobIterator, class OutputIterator,\n          class GetSpeed, class GetLoad, class RoundFun>\nvoid schedule(MachineIterator mfirst, MachineIterator mlast, JobIterator jfirst,\n              JobIterator jlast, OutputIterator result, GetSpeed get_speed,\n              GetLoad get_load, RoundFun round) {\n    typedef sched_traits<MachineIterator, JobIterator, GetSpeed, GetLoad>\n        Traits;\n    typedef typename Traits::speed_t Speed;\n    typedef typename Traits::load_t Load;\n\n    if (mfirst == mlast || jfirst == jlast) {\n        return;\n    }\n\n    std::vector<MachineIterator> machines;\n    boost::copy(boost::counting_range(mfirst, mlast),\n                std::back_inserter(machines));\n    auto get_speed_from_iterator = utils::make_lift_iterator_functor(get_speed);\n    boost::sort(machines, utils::make_functor_to_comparator(\n                              get_speed_from_iterator, utils::greater{}));\n\n    std::vector<JobIterator> jobs;\n    boost::copy(boost::counting_range(jfirst, jlast), std::back_inserter(jobs));\n    auto get_load_from_iterator = utils::make_lift_iterator_functor(get_load);\n    boost::sort(jobs, utils::make_functor_to_comparator(get_load_from_iterator,\n                                                        utils::greater{}));\n\n    auto bound = detail::calculate_bound(\n        machines.begin(), machines.end(), jobs.begin(), jobs.end(),\n        get_speed_from_iterator, get_load_from_iterator);\n    Load bound_load = bound.num;\n    Speed bound_speed = bound.den;\n    Load current_load{};\n    auto emit = [&result](MachineIterator miter, JobIterator jiter) {\n        *result = std::make_pair(miter, jiter);\n        ++result;\n    };\n    auto job_iter = jobs.begin();\n    for (auto machine_iter = machines.begin(); machine_iter != machines.end();\n         ++machine_iter) {\n        auto &&machine = *(*machine_iter);\n        Speed speed = get_speed(machine);\n        while (job_iter != jobs.end()) {\n            auto &&job = *(*job_iter);\n            Load job_load = get_load(job) * bound_speed,\n                 new_load = current_load + job_load;\n            assert(new_load <= bound_load * (2 * speed));\n            if (bound_load * speed < new_load) {\n                Load frac_load = bound_load * speed - current_load;\n                if (round(frac_load, job_load)) {\n                    emit(*machine_iter, *job_iter);\n                } else {\n                    auto next_machine_iter = std::next(machine_iter);\n                    assert(next_machine_iter != machines.end());\n                    emit(*next_machine_iter, *job_iter);\n                }\n                ++job_iter;\n                current_load = job_load - frac_load;\n                break;\n            }\n            emit(*machine_iter, *job_iter);\n            ++job_iter;\n            current_load = new_load;\n        }\n    }\n    assert(job_iter == jobs.end());\n}\n} //!detail\n\n/*\n * @brief This is deterministic solve scheduling jobs on machines with different\n * speeds problem and return schedule\n *\n * Example:\n *  \\snippet scheduling_jobs_example.cpp Scheduling Jobs Example\n *\n * example file is scheduling_jobs_example.cpp\n *\n * @param mfirst\n * @param mlast\n * @param jfirst\n * @param jlast\n * @param result\n * @param get_speed\n * @param get_load\n * @tparam MachineIterator\n * @tparam JobIterator\n * @tparam OutputIterator\n * @tparam GetSpeed\n * @tparam GetLoad\n */\ntemplate <class MachineIterator, class JobIterator, class OutputIterator,\n          class GetSpeed, class GetLoad>\nvoid schedule_deterministic(const MachineIterator mfirst,\n                            const MachineIterator mlast,\n                            const JobIterator jfirst, const JobIterator jlast,\n                            OutputIterator result, GetSpeed get_speed,\n                            GetLoad get_load) {\n    detail::schedule(mfirst, mlast, jfirst, jlast, result, get_speed, get_load,\n                     utils::always_true{});\n}\n\n/*\n * @brief This is randomized solve scheduling jobs on machines with different\n * speeds problem and return schedule.\n *\n * Example:\n *  \\snippet scheduling_jobs_example.cpp Scheduling Jobs Example\n *\n * example file is scheduling_jobs_example.cpp\n *\n * @param mfirst\n * @param mlast\n * @param jfirst\n * @param jlast\n * @param result\n * @param get_speed\n * @param get_load\n * @param gen\n * @tparam MachineIterator\n * @tparam JobIterator\n * @tparam OutputIterator\n * @tparam GetSpeed\n * @tparam GetLoad\n * @tparam RandomNumberGenerator\n */\ntemplate <class MachineIterator, class JobIterator, class OutputIterator,\n          class GetSpeed, class GetLoad,\n          class RandomNumberGenerator = std::default_random_engine>\nvoid schedule_randomized(const MachineIterator mfirst,\n                         const MachineIterator mlast, const JobIterator jfirst,\n                         const JobIterator jlast, OutputIterator result,\n                         GetSpeed get_speed, GetLoad get_load,\n                         RandomNumberGenerator &&gen =\n                             std::default_random_engine(97345631u)) {\n    typedef typename detail::sched_traits<MachineIterator, JobIterator,\n                                          GetSpeed, GetLoad> Traits;\n    double alpha = std::uniform_real_distribution<double>()(gen);\n    auto round = [alpha](typename Traits::load_t fractional_load,\n                         typename Traits::load_t total_load) {\n        return total_load * alpha < fractional_load;\n    };\n    detail::schedule(mfirst, mlast, jfirst, jlast, result, get_speed, get_load,\n                     round);\n}\n\n} //!greedy\n} //!paal\n\n#endif // PAAL_SCHEDULING_JOBS_HPP\n", "meta": {"hexsha": "2c92f79ca049b577a759725690196537ff6e97b5", "size": 9778, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/paal/greedy/scheduling_jobs/scheduling_jobs.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/scheduling_jobs/scheduling_jobs.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/scheduling_jobs/scheduling_jobs.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.8981132075, "max_line_length": 80, "alphanum_fraction": 0.6295766005, "num_tokens": 2124, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6477982315512489, "lm_q2_score": 0.4843800842769843, "lm_q1q2_score": 0.31378056199327536}}
{"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, 2008 StatPro Italia srl\n Copyright (C) 2007, 2008, 2009, 2015 Ferdinando Ametrano\n Copyright (C) 2007, 2009 Roland Lichters\n Copyright (C) 2015 Maddalena Zanzi\n Copyright (C) 2015 Paolo Mazzocchi\n Copyright (C) 2018 Matthias Lungwitz\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 ratehelpers.hpp\n    \\brief deposit, FRA, futures, and various swap rate helpers\n*/\n\n#ifndef quantlib_ratehelpers_hpp\n#define quantlib_ratehelpers_hpp\n\n#include <ql/termstructures/bootstraphelper.hpp>\n#include <ql/instruments/vanillaswap.hpp>\n#include <ql/instruments/bmaswap.hpp>\n#include <ql/instruments/futures.hpp>\n#include <ql/time/calendar.hpp>\n#include <ql/time/daycounter.hpp>\n#include <ql/time/calendars/unitedstates.hpp>\n\n#include <boost/optional.hpp>\n\nnamespace QuantLib {\n\n    class SwapIndex;\n    class Quote;\n\n    typedef BootstrapHelper<YieldTermStructure> RateHelper;\n    typedef RelativeDateBootstrapHelper<YieldTermStructure>\n                                                        RelativeDateRateHelper;\n\n    //! Rate helper for bootstrapping over IborIndex futures prices\n    class FuturesRateHelper : public RateHelper {\n      public:\n        FuturesRateHelper(const Handle<Quote>& price,\n                          const Date& iborStartDate,\n                          Natural lengthInMonths,\n                          const Calendar& calendar,\n                          BusinessDayConvention convention,\n                          bool endOfMonth,\n                          const DayCounter& dayCounter,\n                          Handle<Quote> convexityAdjustment = Handle<Quote>(),\n                          Futures::Type type = Futures::IMM);\n        FuturesRateHelper(Real price,\n                          const Date& iborStartDate,\n                          Natural lengthInMonths,\n                          const Calendar& calendar,\n                          BusinessDayConvention convention,\n                          bool endOfMonth,\n                          const DayCounter& dayCounter,\n                          Rate convexityAdjustment = 0.0,\n                          Futures::Type type = Futures::IMM);\n        FuturesRateHelper(const Handle<Quote>& price,\n                          const Date& iborStartDate,\n                          const Date& iborEndDate,\n                          const DayCounter& dayCounter,\n                          Handle<Quote> convexityAdjustment = Handle<Quote>(),\n                          Futures::Type type = Futures::IMM);\n        FuturesRateHelper(Real price,\n                          const Date& iborStartDate,\n                          const Date& endDate,\n                          const DayCounter& dayCounter,\n                          Rate convexityAdjustment = 0.0,\n                          Futures::Type type = Futures::IMM);\n        FuturesRateHelper(const Handle<Quote>& price,\n                          const Date& iborStartDate,\n                          const ext::shared_ptr<IborIndex>& iborIndex,\n                          const Handle<Quote>& convexityAdjustment = Handle<Quote>(),\n                          Futures::Type type = Futures::IMM);\n        FuturesRateHelper(Real price,\n                          const Date& iborStartDate,\n                          const ext::shared_ptr<IborIndex>& iborIndex,\n                          Rate convexityAdjustment = 0.0,\n                          Futures::Type type = Futures::IMM);\n        //! \\name RateHelper interface\n        //@{\n        Real impliedQuote() const override;\n        //@}\n        //! \\name FuturesRateHelper inspectors\n        //@{\n        Real convexityAdjustment() const;\n        //@}\n\t\t//********************************************************************\n\t\t//Deriscope: Added inspectors\n\t\tTime const yearFraction() const { return yearFraction_; }\n\t\t//********************************************************************\n        //! \\name Visitability\n        //@{\n        void accept(AcyclicVisitor&) override;\n        //@}\n      private:\n        Time yearFraction_;\n        Handle<Quote> convAdj_;\n    };\n\n\n    //! Rate helper for bootstrapping over deposit rates\n    class DepositRateHelper : public RelativeDateRateHelper {\n      public:\n        DepositRateHelper(const Handle<Quote>& rate,\n                          const Period& tenor,\n                          Natural fixingDays,\n                          const Calendar& calendar,\n                          BusinessDayConvention convention,\n                          bool endOfMonth,\n                          const DayCounter& dayCounter);\n        DepositRateHelper(Rate rate,\n                          const Period& tenor,\n                          Natural fixingDays,\n                          const Calendar& calendar,\n                          BusinessDayConvention convention,\n                          bool endOfMonth,\n                          const DayCounter& dayCounter);\n        DepositRateHelper(const Handle<Quote>& rate,\n                          const ext::shared_ptr<IborIndex>& iborIndex);\n        DepositRateHelper(Rate rate,\n                          const ext::shared_ptr<IborIndex>& iborIndex);\n        //! \\name RateHelper interface\n        //@{\n        Real impliedQuote() const override;\n        void setTermStructure(YieldTermStructure*) override;\n\t\t//********************************************************************\n\t\t//Deriscope: Added inspectors\n\t\tDate const & fixingDate() const { return fixingDate_; }\n\t\text::shared_ptr<IborIndex> const & iborIndex() const { return iborIndex_; }\n\t\t//********************************************************************\n        //@}\n        //! \\name Visitability\n        //@{\n        void accept(AcyclicVisitor&) override;\n        //@}\n      private:\n        void initializeDates() override;\n        Date fixingDate_;\n        ext::shared_ptr<IborIndex> iborIndex_;\n        RelinkableHandle<YieldTermStructure> termStructureHandle_;\n    };\n\n\n    //! Rate helper for bootstrapping over %FRA rates\n    class FraRateHelper : public RelativeDateRateHelper {\n      public:\n        FraRateHelper(const Handle<Quote>& rate,\n                      Natural monthsToStart,\n                      Natural monthsToEnd,\n                      Natural fixingDays,\n                      const Calendar& calendar,\n                      BusinessDayConvention convention,\n                      bool endOfMonth,\n                      const DayCounter& dayCounter,\n                      Pillar::Choice pillar = Pillar::LastRelevantDate,\n                      Date customPillarDate = Date(),\n                      bool useIndexedCoupon = true);\n        FraRateHelper(Rate rate,\n                      Natural monthsToStart,\n                      Natural monthsToEnd,\n                      Natural fixingDays,\n                      const Calendar& calendar,\n                      BusinessDayConvention convention,\n                      bool endOfMonth,\n                      const DayCounter& dayCounter,\n                      Pillar::Choice pillar = Pillar::LastRelevantDate,\n                      Date customPillarDate = Date(),\n                      bool useIndexedCoupon = true);\n        FraRateHelper(const Handle<Quote>& rate,\n                      Natural monthsToStart,\n                      const ext::shared_ptr<IborIndex>& iborIndex,\n                      Pillar::Choice pillar = Pillar::LastRelevantDate,\n                      Date customPillarDate = Date(),\n                      bool useIndexedCoupon = true);\n        FraRateHelper(Rate rate,\n                      Natural monthsToStart,\n                      const ext::shared_ptr<IborIndex>& iborIndex,\n                      Pillar::Choice pillar = Pillar::LastRelevantDate,\n                      Date customPillarDate = Date(),\n                      bool useIndexedCoupon = true);\n        FraRateHelper(const Handle<Quote>& rate,\n                      Period periodToStart,\n                      Natural lengthInMonths,\n                      Natural fixingDays,\n                      const Calendar& calendar,\n                      BusinessDayConvention convention,\n                      bool endOfMonth,\n                      const DayCounter& dayCounter,\n                      Pillar::Choice pillar = Pillar::LastRelevantDate,\n                      Date customPillarDate = Date(),\n                      bool useIndexedCoupon = true);\n        FraRateHelper(Rate rate,\n                      Period periodToStart,\n                      Natural lengthInMonths,\n                      Natural fixingDays,\n                      const Calendar& calendar,\n                      BusinessDayConvention convention,\n                      bool endOfMonth,\n                      const DayCounter& dayCounter,\n                      Pillar::Choice pillar = Pillar::LastRelevantDate,\n                      Date customPillarDate = Date(),\n                      bool useIndexedCoupon = true);\n        FraRateHelper(const Handle<Quote>& rate,\n                      Period periodToStart,\n                      const ext::shared_ptr<IborIndex>& iborIndex,\n                      Pillar::Choice pillar = Pillar::LastRelevantDate,\n                      Date customPillarDate = Date(),\n                      bool useIndexedCoupon = true);\n        FraRateHelper(Rate rate,\n                      Period periodToStart,\n                      const ext::shared_ptr<IborIndex>& iborIndex,\n                      Pillar::Choice pillar = Pillar::LastRelevantDate,\n                      Date customPillarDate = Date(),\n                      bool useIndexedCoupon = true);\n        FraRateHelper(const Handle<Quote>& rate,\n                      Natural immOffsetStart,\n                      Natural immOffsetEnd,\n                      const ext::shared_ptr<IborIndex>& iborIndex,\n                      Pillar::Choice pillar = Pillar::LastRelevantDate,\n                      Date customPillarDate = Date(),\n                      bool useIndexedCoupon = true);\n        FraRateHelper(Rate rate,\n                      Natural immOffsetStart,\n                      Natural immOffsetEnd,\n                      const ext::shared_ptr<IborIndex>& iborIndex,\n                      Pillar::Choice pillar = Pillar::LastRelevantDate,\n                      Date customPillarDate = Date(),\n                      bool useIndexedCoupon = true);\n        //! \\name RateHelper interface\n        //@{\n        Real impliedQuote() const override;\n        void setTermStructure(YieldTermStructure*) override;\n        //@}\n\t\t//********************************************************************\n\t\t//Deriscope: Added inspectors\n\t\tDate const & fixingDate() const { return fixingDate_; }\n\t\tboost::optional<Period> const & periodToStart() const { return periodToStart_; }\n\t\text::shared_ptr<IborIndex> const & iborIndex() const { return iborIndex_; }\n\t\tboost::optional<Natural> const immOffsetStart() const { return immOffsetStart_; }\n\t\tboost::optional<Natural> const immOffsetEnd() const { return immOffsetEnd_; }\n\t\tPillar::Choice const pillarChoice() const { return pillarChoice_; }\n\t\tbool const useIndexedCoupon() const { return useIndexedCoupon_; }\n\t\tReal const spanningTime() const { return spanningTime_; }\n\t\t//********************************************************************\n        //! \\name Visitability\n        //@{\n        void accept(AcyclicVisitor&) override;\n        //@}\n      private:\n        void initializeDates() override;\n        Date fixingDate_;\n        boost::optional<Period> periodToStart_;\n        boost::optional<Natural> immOffsetStart_, immOffsetEnd_;\n        Pillar::Choice pillarChoice_;\n        ext::shared_ptr<IborIndex> iborIndex_;\n        RelinkableHandle<YieldTermStructure> termStructureHandle_;\n        bool useIndexedCoupon_;\n        Real spanningTime_;\n    };\n\n\n    //! Rate helper for bootstrapping over swap rates\n    /*! \\todo use input SwapIndex to create the swap */\n    class SwapRateHelper : public RelativeDateRateHelper {\n      public:\n        SwapRateHelper(const Handle<Quote>& rate,\n                       const ext::shared_ptr<SwapIndex>& swapIndex,\n                       Handle<Quote> spread = Handle<Quote>(),\n                       const Period& fwdStart = 0 * Days,\n                       // exogenous discounting curve\n                       Handle<YieldTermStructure> discountingCurve = Handle<YieldTermStructure>(),\n                       Pillar::Choice pillar = Pillar::LastRelevantDate,\n                       Date customPillarDate = Date(),\n                       bool endOfMonth = false);\n        SwapRateHelper(const Handle<Quote>& rate,\n                       const Period& tenor,\n                       Calendar calendar,\n                       // fixed leg\n                       Frequency fixedFrequency,\n                       BusinessDayConvention fixedConvention,\n                       DayCounter fixedDayCount,\n                       // floating leg\n                       const ext::shared_ptr<IborIndex>& iborIndex,\n                       Handle<Quote> spread = Handle<Quote>(),\n                       const Period& fwdStart = 0 * Days,\n                       // exogenous discounting curve\n                       Handle<YieldTermStructure> discountingCurve = Handle<YieldTermStructure>(),\n                       Natural settlementDays = Null<Natural>(),\n                       Pillar::Choice pillar = Pillar::LastRelevantDate,\n                       Date customPillarDate = Date(),\n                       bool endOfMonth = false);\n        SwapRateHelper(Rate rate,\n                       const ext::shared_ptr<SwapIndex>& swapIndex,\n                       Handle<Quote> spread = Handle<Quote>(),\n                       const Period& fwdStart = 0 * Days,\n                       // exogenous discounting curve\n                       Handle<YieldTermStructure> discountingCurve = Handle<YieldTermStructure>(),\n                       Pillar::Choice pillar = Pillar::LastRelevantDate,\n                       Date customPillarDate = Date(),\n                       bool endOfMonth = false);\n        SwapRateHelper(Rate rate,\n                       const Period& tenor,\n                       Calendar calendar,\n                       // fixed leg\n                       Frequency fixedFrequency,\n                       BusinessDayConvention fixedConvention,\n                       DayCounter fixedDayCount,\n                       // floating leg\n                       const ext::shared_ptr<IborIndex>& iborIndex,\n                       Handle<Quote> spread = Handle<Quote>(),\n                       const Period& fwdStart = 0 * Days,\n                       // exogenous discounting curve\n                       Handle<YieldTermStructure> discountingCurve = Handle<YieldTermStructure>(),\n                       Natural settlementDays = Null<Natural>(),\n                       Pillar::Choice pillar = Pillar::LastRelevantDate,\n                       Date customPillarDate = Date(),\n                       bool endOfMonth = false);\n        //! \\name RateHelper interface\n        //@{\n        Real impliedQuote() const override;\n        void setTermStructure(YieldTermStructure*) override;\n        //@}\n        //! \\name SwapRateHelper inspectors\n        //@{\n        Spread spread() const;\n        ext::shared_ptr<VanillaSwap> swap() const;\n        const Period& forwardStart() const;\n        //@}\n        //! \\name Visitability\n        //@{\n        void accept(AcyclicVisitor&) override;\n        //@}\n      protected:\n        void initializeDates() override;\n        Natural settlementDays_;\n        Period tenor_;\n        Pillar::Choice pillarChoice_;\n        Calendar calendar_;\n        BusinessDayConvention fixedConvention_;\n        Frequency fixedFrequency_;\n        DayCounter fixedDayCount_;\n        ext::shared_ptr<IborIndex> iborIndex_;\n        ext::shared_ptr<VanillaSwap> swap_;\n        RelinkableHandle<YieldTermStructure> termStructureHandle_;\n        Handle<Quote> spread_;\n        bool endOfMonth_;\n        Period fwdStart_;\n        Handle<YieldTermStructure> discountHandle_;\n        RelinkableHandle<YieldTermStructure> discountRelinkableHandle_;\n    };\n\n\n    //! Rate helper for bootstrapping over BMA swap rates\n    class BMASwapRateHelper : public RelativeDateRateHelper {\n      public:\n        BMASwapRateHelper(const Handle<Quote>& liborFraction,\n                          const Period& tenor, // swap maturity\n                          Natural settlementDays,\n                          Calendar calendar,\n                          // bma leg\n                          const Period& bmaPeriod,\n                          BusinessDayConvention bmaConvention,\n                          DayCounter bmaDayCount,\n                          ext::shared_ptr<BMAIndex> bmaIndex,\n                          // ibor leg\n                          ext::shared_ptr<IborIndex> index);\n        //! \\name RateHelper interface\n        //@{\n        Real impliedQuote() const override;\n        void setTermStructure(YieldTermStructure*) override;\n\t\t//********************************************************************\n\t\t//Deriscope: Added inspectors\n\t\tPeriod const & tenor() const { return tenor_; }\n\t\tNatural const settlementDays() const { return settlementDays_; }\n\t\tCalendar const & calendar() const { return calendar_; }\n\t\tPeriod const & bmaPeriod() const { return bmaPeriod_; }\n\t\tBusinessDayConvention const bmaConvention() const { return bmaConvention_; }\n\t\tDayCounter const & bmaDayCount() const { return bmaDayCount_; }\n\t\text::shared_ptr<BMAIndex> const & bmaIndex() const { return bmaIndex_; }\n\t\text::shared_ptr<IborIndex> const & iborIndex() const { return iborIndex_; }\n\t\text::shared_ptr<BMASwap> const & swap() const { return swap_; }\n\t\t//********************************************************************\n        //@}\n        //! \\name Visitability\n        //@{\n        void accept(AcyclicVisitor&) override;\n        //@}\n    protected:\n      void initializeDates() override;\n      Period tenor_;\n      Natural settlementDays_;\n      Calendar calendar_;\n      Period bmaPeriod_;\n      BusinessDayConvention bmaConvention_;\n      DayCounter bmaDayCount_;\n      ext::shared_ptr<BMAIndex> bmaIndex_;\n      ext::shared_ptr<IborIndex> iborIndex_;\n\n      ext::shared_ptr<BMASwap> swap_;\n      RelinkableHandle<YieldTermStructure> termStructureHandle_;\n    };\n\n\n    //! Rate helper for bootstrapping over Fx Swap rates\n    /*! The forward is given by `fwdFx = spotFx + fwdPoint`.\n\n        `isFxBaseCurrencyCollateralCurrency` indicates if the base\n        currency of the FX currency pair is the one used as collateral.\n\n        `calendar` is usually the joint calendar of the two currencies\n        in the pair.\n\n        `tradingCalendar` can be used when the cross pairs don't\n        include the currency of the business center (usually USD; the\n        corresponding calendar is `UnitedStates`).  If given, it will\n        be used for adjusting the earliest settlement date and for\n        setting the latest date. Due to FX spot market conventions, it\n        is not sufficient to pass a JointCalendar with UnitedStates\n        included as `calendar`; with regard the earliest date, this\n        calendar is only used in case the spot date of the two\n        currencies is not a US business day.\n\n        \\warning The ON fx swaps can be achieved by setting\n                 `fixingDays` to 0 and using a tenor of '1d'. The same\n                 tenor should be used for TN swaps, with `fixingDays`\n                 set to 1.  However, handling ON and TN swaps for\n                 cross rates without USD is not trivial and should be\n                 treated with caution. If today is a US holiday, ON\n                 trade is not possible. If tomorrow is a US Holiday,\n                 the ON trade will be at least two business days long\n                 in the other countries and the TN trade will not\n                 exist. In such cases, if this helper is used for\n                 curve construction, probably it is safer not to pass\n                 a trading calendar to the ON and TN helpers and\n                 provide fwdPoints that will yield proper level of\n                 discount factors.\n    */\n    class FxSwapRateHelper : public RelativeDateRateHelper {\n      public:\n        FxSwapRateHelper(const Handle<Quote>& fwdPoint,\n                         Handle<Quote> spotFx,\n                         const Period& tenor,\n                         Natural fixingDays,\n                         Calendar calendar,\n                         BusinessDayConvention convention,\n                         bool endOfMonth,\n                         bool isFxBaseCurrencyCollateralCurrency,\n                         Handle<YieldTermStructure> collateralCurve,\n                         Calendar tradingCalendar = Calendar());\n        //! \\name RateHelper interface\n        //@{\n        Real impliedQuote() const override;\n        void setTermStructure(YieldTermStructure*) override;\n        //@}\n        //! \\name FxSwapRateHelper inspectors\n        //@{\n        Real spot() const { return spot_->value(); }\n        Period tenor() const { return tenor_; }\n        Natural fixingDays() const { return fixingDays_; }\n        Calendar calendar() const { return cal_; }\n        BusinessDayConvention businessDayConvention() const { return conv_; }\n        bool endOfMonth() const { return eom_; }\n        bool isFxBaseCurrencyCollateralCurrency() const {\n                                return isFxBaseCurrencyCollateralCurrency_; }\n        Calendar tradingCalendar() const { return tradingCalendar_; }\n        Calendar adjustmentCalendar() const { return jointCalendar_; }\n        //@}\n        //! \\name Visitability\n        //@{\n        void accept(AcyclicVisitor&) override;\n        //@}\n    private:\n      void initializeDates() override;\n      Handle<Quote> spot_;\n      Period tenor_;\n      Natural fixingDays_;\n      Calendar cal_;\n      BusinessDayConvention conv_;\n      bool eom_;\n      bool isFxBaseCurrencyCollateralCurrency_;\n\n      RelinkableHandle<YieldTermStructure> termStructureHandle_;\n\n      Handle<YieldTermStructure> collHandle_;\n      RelinkableHandle<YieldTermStructure> collRelinkableHandle_;\n\n      Calendar tradingCalendar_;\n      Calendar jointCalendar_;\n    };\n\n    // inline\n\n    inline Spread SwapRateHelper::spread() const {\n        return spread_.empty() ? 0.0 : spread_->value();\n    }\n\n    inline ext::shared_ptr<VanillaSwap> SwapRateHelper::swap() const {\n        return swap_;\n    }\n\n    inline const Period& SwapRateHelper::forwardStart() const {\n        return fwdStart_;\n    }\n\n}\n\n#endif\n", "meta": {"hexsha": "608d761cf0841af81b62f48bfa79cbd63f236eab", "size": 23380, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ql/termstructures/yield/ratehelpers.hpp", "max_stars_repo_name": "irigopou/QuantLib", "max_stars_repo_head_hexsha": "6921d8ce181288e85c24886f3f9faa35183ef931", "max_stars_repo_licenses": ["BSD-3-Clause"], "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/termstructures/yield/ratehelpers.hpp", "max_issues_repo_name": "irigopou/QuantLib", "max_issues_repo_head_hexsha": "6921d8ce181288e85c24886f3f9faa35183ef931", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 8.0, "max_issues_repo_issues_event_min_datetime": "2020-06-25T10:14:45.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-19T22:20:44.000Z", "max_forks_repo_path": "ql/termstructures/yield/ratehelpers.hpp", "max_forks_repo_name": "irigopou/QuantLib", "max_forks_repo_head_hexsha": "6921d8ce181288e85c24886f3f9faa35183ef931", "max_forks_repo_licenses": ["BSD-3-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.6183206107, "max_line_length": 98, "alphanum_fraction": 0.5576133447, "num_tokens": 4491, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6477982179521105, "lm_q2_score": 0.48438008427698437, "lm_q1q2_score": 0.31378055540612354}}
{"text": "/*\n system.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 <iomanip>\n#include <fstream>\n#include \"system.h\"\n#include \"constants.h\"\n#include \"mathfunctions.h\"\n#include \"timer.h\"\n#include \"memory.h\"\n#include \"error.h\"\n#include \"constraint.h\"\n#include \"fcs.h\"\n#include \"symmetry.h\"\n#include \"fitting.h\"\n#include \"xml_parser.h\"\n#include <boost/property_tree/ptree.hpp>\n#include <boost/property_tree/xml_parser.hpp>\n#include <boost/foreach.hpp>\n#include <boost/optional.hpp>\n#include <boost/lexical_cast.hpp>\n\nusing namespace ALM_NS;\n\nSystem::System(ALM *alm): Pointers(alm) {}\n\nSystem::~System() \n{\n    memory->deallocate(x_cartesian);\n    memory->deallocate(atomlist_class);\n    memory->deallocate(magmom);\n}\n\nvoid System::init()\n{\n    using namespace std;\n\n    int i, j;\n\n    cout << \" SYSTEM\" << endl;\n    cout << \" ======\" << endl << endl;\n\n    recips(lavec, rlavec);\n\n    cout.setf(ios::scientific);\n\n    cout << \"  Lattice Vector\" << endl;\n    cout << setw(16) << lavec[0][0] << setw(15) << lavec[1][0] << setw(15) << lavec[2][0] << \" : a1\" << endl;\n    cout << setw(16) << lavec[0][1] << setw(15) << lavec[1][1] << setw(15) << lavec[2][1] << \" : a2\" << endl;\n    cout << setw(16) << lavec[0][2] << setw(15) << lavec[1][2] << setw(15) << lavec[2][2] << \" : a3\" << endl;\n    cout << endl;\n\n    double vec_tmp[3][3];\n    for (i = 0; i < 3; ++i) {\n        for (j = 0; j < 3; ++j) {\n            vec_tmp[i][j] = lavec[j][i];\n        }\n    }\n\n    cell_volume = volume(vec_tmp[0], vec_tmp[1], vec_tmp[2]);\n    cout << \"  Cell volume = \" << cell_volume << \" (a.u)^3\" << endl << endl;\n\n    cout << \"  Reciprocal Lattice Vector\" << std::endl;\n    cout << setw(16) << rlavec[0][0] << setw(15) << rlavec[0][1] << setw(15) << rlavec[0][2] << \" : b1\" << endl;\n    cout << setw(16) << rlavec[1][0] << setw(15) << rlavec[1][1] << setw(15) << rlavec[1][2] << \" : b2\" << endl;\n    cout << setw(16) << rlavec[2][0] << setw(15) << rlavec[2][1] << setw(15) << rlavec[2][2] << \" : b3\" << endl;\n    cout << endl;\n\n    cout << \"  Atomic species:\" << endl;\n    for (i = 0; i < nkd; ++i) {\n        cout << setw(6) << i + 1 << setw(5) << kdname[i] << endl;\n    }\n    cout << endl;\n\n    cout << \"  Atomic positions in fractional basis and atomic species\" << endl;\n    for (i = 0; i < nat; ++i) {\n        cout << setw(6) << i + 1;\n        cout << setw(15) << xcoord[i][0];\n        cout << setw(15) << xcoord[i][1];\n        cout << setw(15) << xcoord[i][2];\n        cout << setw(5) << kd[i] << endl;\n    }\n    cout << endl << endl;\n    cout.unsetf(ios::scientific);\n\n    // Generate Cartesian coordinate\n\n    memory->allocate(x_cartesian, nat, 3);\n\n    for (i = 0; i < nat; ++i) {\n        for (j = 0; j < 3; ++j) {\n            x_cartesian[i][j] = xcoord[i][j];\n        }\n    }\n    frac2cart(x_cartesian);\n    setup_atomic_class(kd);\n\n    if (lspin) {\n        cout << \"  MAGMOM is given. The magnetic moments of each atom are as follows:\" << endl;\n        for (i = 0; i < nat; ++i) {\n            cout << setw(6) << i + 1;\n            cout << setw(5) << magmom[i][0];\n            cout << setw(5) << magmom[i][1];\n            cout << setw(5) << magmom[i][2];\n            cout << endl;\n        }\n        cout << endl;\n        if (noncollinear == 0) {\n            cout << \"  NONCOLLINEAR = 0: magnetic moments are considered as scalar variables.\" << endl;\n        } else if (noncollinear == 1) {\n            cout << \"  NONCOLLINEAR = 1: magnetic moments are considered as vector variables.\" << endl;\n            if (symmetry->trev_sym_mag) {\n                cout << \"  TREVSYM = 1: Time-reversal symmetry will be considered for generating magnetic space group\" << endl;\n            } else {\n                cout << \"  TREVSYM = 0: Time-reversal symmetry will NOT be considered for generating magnetic space group\" << endl;\n            }\n        }\n        cout << endl << endl;\n    }\n\n    timer->print_elapsed();\n    cout << \" --------------------------------------------------------------\" << endl;\n    cout << endl;\n}\n\nvoid System::recips(double aa[3][3], double bb[3][3])\n{\n    /*\n    Calculate Reciprocal Lattice Vectors\n\n    Here, BB is just the inverse matrix of AA (multiplied by factor 2 Pi)\n\n    BB = 2 Pi AA^{-1},\n    = t(b1, b2, b3)\n\n    (b11 b12 b13)\n    = (b21 b22 b23)\n    (b31 b32 b33),\n\n    b1 = t(b11, b12, b13) etc.\n    */\n\n    double det;\n    det = aa[0][0] * aa[1][1] * aa[2][2] \n    + aa[1][0] * aa[2][1] * aa[0][2] \n    + aa[2][0] * aa[0][1] * aa[1][2]\n    - aa[0][0] * aa[2][1] * aa[1][2] \n    - aa[2][0] * aa[1][1] * aa[0][2]\n    - aa[1][0] * aa[0][1] * aa[2][2];\n\n    if (std::abs(det) < eps12) {\n        error->exit(\"recips\", \"Lattice Vector is singular\");\n    }\n\n    double factor = 2.0 * pi / det;\n\n    bb[0][0] = (aa[1][1] * aa[2][2] - aa[1][2] * aa[2][1]) * factor;\n    bb[0][1] = (aa[0][2] * aa[2][1] - aa[0][1] * aa[2][2]) * factor;\n    bb[0][2] = (aa[0][1] * aa[1][2] - aa[0][2] * aa[1][1]) * factor;\n\n    bb[1][0] = (aa[1][2] * aa[2][0] - aa[1][0] * aa[2][2]) * factor;\n    bb[1][1] = (aa[0][0] * aa[2][2] - aa[0][2] * aa[2][0]) * factor;\n    bb[1][2] = (aa[0][2] * aa[1][0] - aa[0][0] * aa[1][2]) * factor;\n\n    bb[2][0] = (aa[1][0] * aa[2][1] - aa[1][1] * aa[2][0]) * factor;\n    bb[2][1] = (aa[0][1] * aa[2][0] - aa[0][0] * aa[2][1]) * factor;\n    bb[2][2] = (aa[0][0] * aa[1][1] - aa[0][1] * aa[1][0]) * factor;\n}\n\nvoid System::frac2cart(double **xf)\n{\n    // x_cartesian = A x_fractional\n\n    int i, j;\n\n    double *x_tmp;\n    memory->allocate(x_tmp, 3);\n\n    for (i = 0; i < nat; ++i) {\n\n        rotvec(x_tmp, xf[i], lavec);\n\n        for (j = 0; j < 3; ++j) {\n            xf[i][j] = x_tmp[j];\n        }\n    }\n    memory->deallocate(x_tmp);\n}\n\nvoid System::load_reference_system_xml(std::string file_reference_fcs, const int order_fcs, double *const_out)\n{\n    using namespace boost::property_tree;\n    ptree pt;\n\n    int nat_ref, natmin_ref, ntran_ref;\n    int **intpair_ref;\n    std::string str_error;\n    double *fcs_ref;\n    int nfcs_ref;\n\n    try {\n        read_xml(file_reference_fcs, pt);\n    }\n    catch (std::exception &e) {\n        if (order_fcs == 0) {\n            str_error = \"Cannot open file FC2XML ( \" + file_reference_fcs + \" )\";\n        } else if (order_fcs == 1) {\n            str_error = \"Cannot open file FC3XML ( \" + file_reference_fcs + \" )\";\n        }\n        error->exit(\"load_reference_system_xml\", str_error.c_str());\n    }\n\n    nat_ref = boost::lexical_cast<int>(get_value_from_xml(pt, \"Data.Structure.NumberOfAtoms\"));\n    ntran_ref = boost::lexical_cast<int>(get_value_from_xml(pt, \"Data.Symmetry.NumberOfTranslations\"));\n    natmin_ref = nat_ref / ntran_ref;\n\n    if (natmin_ref != symmetry->natmin) {\n        error->exit(\"load_reference_system_xml\", \"The number of atoms in the primitive cell is not consistent.\");\n    }\n\n    if (order_fcs == 0) {\n        nfcs_ref = boost::lexical_cast<int>(get_value_from_xml(pt, \"Data.ForceConstants.HarmonicUnique.NFC2\"));\n\n        if (nfcs_ref != fcs->ndup[0].size()) {\n            error->exit(\"load_reference_system_xml\", \"The number of harmonic force constants is not the same.\");\n        }\n\n    } else if (order_fcs == 1) {\n        nfcs_ref = boost::lexical_cast<int>(get_value_from_xml(pt, \"Data.ForceConstants.CubicUnique.NFC3\"));\n\n        if (nfcs_ref != fcs->ndup[1].size()) {\n            error->exit(\"load_reference_system_xml\", \"The number of cubic force constants is not the same.\");\n        }\n    }\n    memory->allocate(fcs_ref, nfcs_ref);\n    memory->allocate(intpair_ref, nfcs_ref, 3);\n\n    int counter = 0;\n\n    if (order_fcs == 0) {\n        BOOST_FOREACH (const ptree::value_type& child_, pt.get_child(\"Data.ForceConstants.HarmonicUnique\")) {\n            if (child_.first == \"FC2\") {\n                const ptree& child = child_.second;\n                const std::string str_intpair = child.get<std::string>(\"<xmlattr>.pairs\");\n                const std::string str_multiplicity = child.get<std::string>(\"<xmlattr>.multiplicity\");\n\n                std::istringstream is(str_intpair);\n                is >> intpair_ref[counter][0] >> intpair_ref[counter][1];\n                fcs_ref[counter] = boost::lexical_cast<double>(child.data());\n                ++counter;\n            }\n        }\n    } else if (order_fcs == 1) {\n        BOOST_FOREACH (const ptree::value_type& child_, pt.get_child(\"Data.ForceConstants.CubicUnique\")) {\n            if (child_.first == \"FC3\") {\n                const ptree& child = child_.second;\n                const std::string str_intpair = child.get<std::string>(\"<xmlattr>.pairs\");\n                const std::string str_multiplicity = child.get<std::string>(\"<xmlattr>.multiplicity\");\n\n                std::istringstream is(str_intpair);\n                is >> intpair_ref[counter][0] >> intpair_ref[counter][1] >> intpair_ref[counter][2];\n                fcs_ref[counter] = boost::lexical_cast<double>(child.data());\n                ++counter;\n            }\n        }\n    }\n\n    int i;\n    std::set<FcProperty> list_found;\n    std::set<FcProperty>::iterator iter_found;\n    int *ind;\n    int nterms = order_fcs + 2;\n    memory->allocate(ind, nterms);\n\n    list_found.clear();\n\n    for (std::vector<FcProperty>::iterator p = fcs->fc_set[order_fcs].begin(); \n        p != fcs->fc_set[order_fcs].end(); ++p) {\n            FcProperty list_tmp = *p; // Using copy constructor\n            for (i = 0; i < nterms; ++i) {\n                ind[i] = list_tmp.elems[i];\n            }\n            list_found.insert(FcProperty(nterms, list_tmp.coef, ind, list_tmp.mother));\n    }\n    // \n    //     for (i = 0; i < nfcs_ref; ++i) {\n    //         constraint->const_mat[i][i] = 1.0;\n    //     }\n\n    for (i = 0; i < nfcs_ref; ++i) {\n        iter_found = list_found.find(FcProperty(nterms, 1.0, intpair_ref[i], 1));\n        if (iter_found == list_found.end()) {\n            error->exit(\"load_reference_system\", \"Cannot find equivalent force constant, number: \", i + 1);\n        }\n        FcProperty arrtmp = *iter_found;\n        const_out[arrtmp.mother] = fcs_ref[i];\n    }\n\n    memory->deallocate(intpair_ref);\n    memory->deallocate(fcs_ref);\n    memory->deallocate(ind);\n    list_found.clear();\n}\n\nvoid System::load_reference_system()\n{\n    int i;\n    int iat, jat;\n    int icrd;\n\n    unsigned int nat_s, nkd_s;\n    unsigned int natmin_ref, ntran_ref;\n    double lavec_s[3][3];\n    int *kd_s;\n    double **xcoord_s;\n    int *map_ref;\n    int **map_p2s_s;\n    Symmetry::Maps *map_s2p_s;\n    std::ifstream ifs_fc2;\n\n    ifs_fc2.open(constraint->fc2_file.c_str(), std::ios::in);\n    if(!ifs_fc2) error->exit(\"calc_constraint_matrix\", \"cannot open file fc2_file\");\n\n    bool is_found_system = false;\n\n    int nparam_harmonic_ref;\n    int nparam_harmonic = fcs->ndup[0].size();\n\n    std::string str_tmp;\n\n    while(!ifs_fc2.eof() && !is_found_system)\n    {\n        std::getline(ifs_fc2, str_tmp);\n        if (str_tmp == \"##SYSTEM INFO\") {\n\n            is_found_system = true;\n\n            std::getline(ifs_fc2, str_tmp);\n            for (i = 0; i < 3; ++i) {\n                ifs_fc2 >> lavec_s[0][i] >> lavec_s[1][i] >> lavec_s[2][i];\n            }\n            ifs_fc2.ignore();\n            std::getline(ifs_fc2, str_tmp);\n            ifs_fc2 >> nkd_s;\n            ifs_fc2.ignore();\n            std::getline(ifs_fc2, str_tmp);\n            std::getline(ifs_fc2, str_tmp);\n\n            ifs_fc2 >> nat_s >> natmin_ref >> ntran_ref;\n\n            if (natmin_ref != symmetry->natmin) {\n                error->exit(\"load_reference_system\", \"The number of atoms in the primitive cell is not consistent\");\n            }\n\n            if (nat_s != nat) {\n                std::cout << \"The number of atoms in the reference system differs from input.\" << std::endl;\n                std::cout << \"Trying to map the related force constants (^o^)\" << std::endl << std::endl;\n            }\n\n            memory->allocate(xcoord_s, nat_s, 3);\n            memory->allocate(kd_s, nat_s);\n            memory->allocate(map_p2s_s, natmin_ref, ntran_ref);\n            memory->allocate(map_s2p_s, nat_s);\n\n            unsigned int ikd, itran, icell;\n            std::getline(ifs_fc2, str_tmp);\n            std::getline(ifs_fc2, str_tmp);\n            for (i = 0; i < nat_s; ++i) {\n                ifs_fc2 >> str_tmp >> ikd >> xcoord_s[i][0] >> xcoord_s[i][1] >> xcoord_s[i][2] >> itran >> icell;\n                kd_s[i] = ikd;\n                map_p2s_s[icell - 1][itran - 1] = i;\n                map_s2p_s[i].atom_num = icell - 1;\n                map_s2p_s[i].tran_num = itran - 1;\n            }\n        }\n    }\n    if (!is_found_system) error->exit(\"load_reference_system\", \"SYSTEM INFO flag not found in the fc2_file\");\n\n    //\n    // Generate Mapping Information (big supercell -> small supercell)\n    //\n\n    double *xtmp;\n    double *xdiff;\n    int **intpair_tmp;\n\n    memory->allocate(xtmp, 3);\n    memory->allocate(xdiff, 3);\n    memory->allocate(map_ref, nat_s);\n\n    bool map_found;\n    double dist;\n\n    for (iat = 0; iat < nat_s; ++iat) {\n        map_found = false;\n\n        rotvec(xtmp, xcoord_s[iat], lavec_s);\n        rotvec(xtmp, xtmp, rlavec);\n\n        for (icrd = 0; icrd < 3; ++icrd) xtmp[icrd] /= 2.0 * pi;\n\n        for (jat = 0; jat < nat; ++jat) {\n            for (icrd = 0; icrd < 3; ++icrd) {\n                xdiff[icrd] = xtmp[icrd] - xcoord[jat][icrd];\n                xdiff[icrd] = std::fmod(xdiff[icrd], 1.0);\n            }\n            dist = xdiff[0] * xdiff[0] + xdiff[1] * xdiff[1] + xdiff[2] * xdiff[2];\n\n            if (dist < eps12 && kd_s[iat] == kd[jat]) {\n                map_ref[iat] = jat;\n                map_found = true;\n                break;\n            }\n        }\n        if (!map_found) error->exit(\"load_reference_system\", \"Could not find an equivalent atom for atom \", iat + 1);\n    }\n\n    memory->deallocate(xtmp);\n    memory->deallocate(xdiff);\n    memory->deallocate(xcoord_s);\n    memory->deallocate(kd_s);\n\n    ifs_fc2.clear();\n    ifs_fc2.seekg(0, std::ios_base::beg);\n\n    double *fc2_ref;\n\n    bool is_found_fc2 = false;\n\n    while(!ifs_fc2.eof() && !is_found_fc2)\n    {\n        std::getline(ifs_fc2, str_tmp);\n        if (str_tmp == \"##HARMONIC FORCE CONSTANTS\")\n        {\n            ifs_fc2 >> nparam_harmonic_ref;\n            if (nparam_harmonic_ref < nparam_harmonic) {\n                error->exit(\"load_reference_system\", \"Reference file doesn't contain necessary fc2. (too few)\");\n            } else if (nparam_harmonic_ref > nparam_harmonic){\n                error->exit(\"load_reference_system\",\"Reference file contains extra force constants.\" );\n            }\n\n            is_found_fc2 = true;\n\n            memory->allocate(fc2_ref, nparam_harmonic);\n            memory->allocate(intpair_tmp, nparam_harmonic, 2);\n\n            for (i = 0; i < nparam_harmonic; ++i) {\n                ifs_fc2 >> fc2_ref[i] >> intpair_tmp[i][0] >> intpair_tmp[i][1];\n            }\n\n            std::set<FcProperty> list_found;\n            std::set<FcProperty>::iterator iter_found;\n            int *ind;\n            memory->allocate(ind, 2);\n\n            list_found.clear();\n            for (std::vector<FcProperty>::iterator p = fcs->fc_set[0].begin(); p != fcs->fc_set[0].end(); ++p) {\n                FcProperty list_tmp = *p; // Using copy constructor\n                for (i = 0; i < 2; ++i){\n                    ind[i] = list_tmp.elems[i];\n                }\n                list_found.insert(FcProperty(2, list_tmp.coef, ind, list_tmp.mother));\n            }\n\n            for (i = 0; i < nparam_harmonic; ++i) {\n                constraint->const_mat[i][i] = 1.0;\n            }\n\n            for (i = 0; i < nparam_harmonic; ++i) {\n\n                iter_found = list_found.find(FcProperty(2, 1.0, intpair_tmp[i], 1));\n                if (iter_found == list_found.end()) {\n                    error->exit(\"load_reference_system\", \"Cannot find equivalent force constant, number: \", i + 1);\n                }\n                FcProperty arrtmp = *iter_found;\n                constraint->const_rhs[arrtmp.mother] = fc2_ref[i];\n            }\n\n            memory->deallocate(intpair_tmp);\n            memory->deallocate(ind);\n            memory->deallocate(fc2_ref);\n            list_found.clear();\n        }\n    }\n\n    if(!is_found_fc2) error->exit(\"load_reference_system\", \"HARMONIC FORCE CONSTANTS flag not found in the fc2_file\");\n    ifs_fc2.close();\n}\n\ndouble System::volume(double vec1[3], double vec2[3], double vec3[3])\n{\n    double vol;\n\n    vol = std::abs(vec1[0]*(vec2[1]*vec3[2] - vec2[2]*vec3[1]) \n        + vec1[1]*(vec2[2]*vec3[0] - vec2[0]*vec3[2]) \n        + vec1[2]*(vec2[0]*vec3[1] - vec2[1]*vec3[0]));\n\n    return vol;\n}\n\nvoid System::setup_atomic_class(int *kd) \n{\n    // In the case of collinear calculation, spin moments are considered as scalar\n    // variables. Therefore, the same elements with different magnetic moments are\n    // considered as different types. In noncollinear calculations, \n    // magnetic moments are not considered in this stage. They will be treated\n    // separately in symmetry.cpp where spin moments will be rotated and flipped \n    // using time-reversal symmetry.\n\n    unsigned int i;\n    AtomType type_tmp;\n    std::set<AtomType> set_type;\n    set_type.clear();\n\n    for (i = 0; i < nat; ++i) {\n        type_tmp.element = kd[i];\n\n        if (noncollinear == 0) {\n            type_tmp.magmom = magmom[i][2];\n        } else {\n            type_tmp.magmom = 0.0;\n        }\n        set_type.insert(type_tmp);\n    }\n\n    nclassatom = set_type.size();\n\n    memory->allocate(atomlist_class, nclassatom);\n\n    for (i = 0; i < nat; ++i) {\n        int count = 0;\n        for (std::set<AtomType>::iterator it = set_type.begin(); it != set_type.end(); ++it) {\n            if (noncollinear) {\n                if (kd[i] == (*it).element) {\n                    atomlist_class[count].push_back(i);\n                }\n            } else {\n                if (kd[i] == (*it).element && std::abs(magmom[i][2] - (*it).magmom) < eps6) {\n                    atomlist_class[count].push_back(i);\n                }\n            }\n            ++count;\n        }\n    }\n    set_type.clear();\n}\n", "meta": {"hexsha": "920d49db6996bfb0c92cde8bd715d2244c2089af", "size": 18262, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "alm/system.cpp", "max_stars_repo_name": "dlnguyen/alamode", "max_stars_repo_head_hexsha": "f99d333262489f28a3ef4838dfbe3147dc239261", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "alm/system.cpp", "max_issues_repo_name": "dlnguyen/alamode", "max_issues_repo_head_hexsha": "f99d333262489f28a3ef4838dfbe3147dc239261", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "alm/system.cpp", "max_forks_repo_name": "dlnguyen/alamode", "max_forks_repo_head_hexsha": "f99d333262489f28a3ef4838dfbe3147dc239261", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.9045045045, "max_line_length": 131, "alphanum_fraction": 0.5398094404, "num_tokens": 5470, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6477982179521103, "lm_q2_score": 0.48438008427698437, "lm_q1q2_score": 0.3137805554061235}}
{"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_SKY_POINT_HPP\n#define BOOST_ASTRONOMY_COORDINATE_SKY_POINT_HPP\n\n#include <string>\n#include <type_traits>\n#include <cmath>\n\n#include <boost/units/io.hpp>\n#include <boost/static_assert.hpp>\n\n#include <boost/astronomy/coordinate/frame.hpp>\n#include <boost/astronomy/detail/is_base_template_of.hpp>\n\nnamespace boost { namespace astronomy { namespace coordinate {\n\nnamespace bu = boost::units;\nnamespace bg = boost::geometry;\n\n/*!sky_point is used to represent a point(coordinate) in the sky*/\ntemplate <typename CoordinateSystem>\nstruct sky_point\n{\n    ///@cond INTERNAL\n    BOOST_STATIC_ASSERT_MSG((boost::astronomy::detail::is_base_frame_of\n            <boost::astronomy::coordinate::base_frame, CoordinateSystem>::value),\n            \"Template argument is expected to be a frame class\");\n    ///@endcond\n    \nprotected:\n    CoordinateSystem point;\n\npublic:\n    typedef CoordinateSystem system;\n    \n    //constructors  \n\n    //!default constructor\n    sky_point() {}\n\n    //!create point with the given coordinates\n    sky_point(CoordinateSystem const& object) : point(object) {}\n\n    //!create point with providing representation and differential class object\n    template <typename Representation, typename Differential>\n    sky_point\n    (\n        Representation const& representation_data,\n        Differential const& differential_data\n    )\n    {\n        BOOST_STATIC_ASSERT_MSG((boost::astronomy::detail::is_base_template_of\n            <boost::astronomy::coordinate::base_representation, Representation>::value),\n            \"argument type is expected to be a representation class\");\n\n        BOOST_STATIC_ASSERT_MSG((boost::astronomy::detail::is_base_template_of\n            <boost::astronomy::coordinate::base_differential, Differential>::value),\n            \"argument type is expected to be a differential class\");\n\n        point = CoordinateSystem(representation_data, differential_data);\n    }\n\n    //!create point with direct values of representation and differential\n    sky_point\n    (\n        typename CoordinateSystem::representation::quantity1 const& lat,\n        typename CoordinateSystem::representation::quantity2 const& lon,\n        typename CoordinateSystem::representation::quantity3 const& distance,\n        typename CoordinateSystem::differential::quantity1 const& pm_lat,\n        typename CoordinateSystem::differential::quantity2 const& pm_lon_coslat,\n        typename CoordinateSystem::differential::quantity3 const& radian_velocity\n    )\n    {\n        point = CoordinateSystem(lat, lon, distance, pm_lat, pm_lon_coslat,\n                    radian_velocity);\n    }\n\n    template<class OtherCoordinateSystem>\n    sky_point(sky_point<OtherCoordinateSystem> const& object);\n\n    //!constructing from direct value of representation\n    sky_point\n    (\n        typename CoordinateSystem::representation::quantity1 const& lat,\n        typename CoordinateSystem::representation::quantity2 const& lon,\n        typename CoordinateSystem::representation::quantity3 const& distance\n    )\n    {\n        point = CoordinateSystem(lat, lon, distance);\n    }\n\n    //constructing from name of object if available in the calatoge\n    sky_point(std::string const& name);\n\n    std::string get_constillation();\n\n    sky_point<CoordinateSystem> from_name(std::string const& name);\n\n    //!angular separation between two coordinates in radians\n    bu::quantity<bu::si::plane_angle> separation(sky_point<CoordinateSystem> const& \n        object) const\n    {\n        return this->point.get_angular_separation(object.get_point());\n    }\n\n    //!returns positional angle in the radian\n    bu::quantity<bu::si::plane_angle> positional_angle(sky_point<CoordinateSystem>\n        const& object) const\n    {\n        auto p1 = make_spherical_representation(this->point.get_data());\n        auto p2 = make_spherical_representation(object.get_point().get_data());\n\n        auto diff = p2.get_lon() - p1.get_lon();\n\n        double temp_p1 = static_cast<bu::quantity<bu::si::plane_angle,\n            typename CoordinateSystem::representation::type>>(p1.get_lat()).value();\n        double temp_p2 = static_cast<bu::quantity<bu::si::plane_angle,\n            typename CoordinateSystem::representation::type>>(p2.get_lat()).value();\n        double temp_diff = static_cast<bu::quantity<bu::si::plane_angle,\n            typename CoordinateSystem::representation::type>>(diff).value();\n\n        double coslat = std::cos(temp_p2);\n\n        double x = std::sin(temp_p2) * std::cos(temp_p1) - \n            coslat * std::sin(temp_p1) * std::cos(temp_diff);\n        double y = std::sin(temp_diff) * coslat;\n\n        return bu::quantity<bu::si::plane_angle>::from_value(std::atan2(x, y));\n    }\n\n    //!returns true if both coordinate systems are same else returns false\n    template<class OtherCoordinateSystem>\n    bool is_equivalent_system(sky_point<OtherCoordinateSystem> const& object)\n    {\n        return std::is_same<CoordinateSystem, OtherCoordinateSystem>::value;\n    }\n\n    template<class OtherCoordinateSystem>\n    sky_point<OtherCoordinateSystem> transform_to();\n\n    //!returns the point\n    CoordinateSystem get_point() const\n    {\n        return this->point;\n    }\n\n    //!sets the point with given object\n    void set_point(CoordinateSystem const& otherPoint)\n    {\n        this->point = otherPoint;\n    }\n\n}; //sky_point\n\n}}} //namespace boost::astronomy::coordinate\n\n#endif // !BOOST_ASTRONOMY_COORDINATE_SKY_POINT_HPP\n\n", "meta": {"hexsha": "c8e9bec968141fa82b9591c8a9978af9587d388d", "size": 5623, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/astronomy/coordinate/sky_point.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/sky_point.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/sky_point.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": 34.4969325153, "max_line_length": 88, "alphanum_fraction": 0.7031833541, "num_tokens": 1226, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6477982179521103, "lm_q2_score": 0.4843800842769843, "lm_q1q2_score": 0.3137805554061235}}
{"text": "#ifndef MATHEVAL_IMPLEMENTATION\n#error \"Do not include parser_def.hpp directly!\"\n#endif\n\n#pragma once\n\n#include \"ast.hpp\"\n#include \"ast_adapted.hpp\"\n#include \"math.hpp\"\n#include \"parser.hpp\"\n\n#include <boost/spirit/include/phoenix.hpp>\n#define BOOST_SPIRIT_NO_PREDEFINED_TERMINALS\n#include <boost/spirit/include/qi.hpp>\n\n#include <cmath>\n#include <iostream>\n#include <limits>\n#include <sstream>\n#include <string>\n\nnamespace matheval {\n\nnamespace qi = boost::spirit::qi;\n\nnamespace parser {\n\ntemplate <typename Iterator>\ngrammar<Iterator>::grammar() : grammar::base_type(expression) {\n    qi::_2_type _2;\n    qi::_3_type _3;\n    qi::_4_type _4;\n\n    qi::alnum_type alnum;\n    qi::alpha_type alpha;\n    qi::double_type double_;\n    qi::lexeme_type lexeme;\n    qi::raw_type raw;\n\n    // clang-format off\n\n    constant.add\n        (\"e\"      , boost::math::constants::e<double>())\n        (\"epsilon\", std::numeric_limits<double>::epsilon())\n        (\"phi\"    , boost::math::constants::phi<double>())\n        (\"pi\"     , boost::math::constants::pi<double>())\n        ;\n\n    ufunc.add\n        (\"abs\"  , static_cast<double (*)(double)>(&std::abs))\n        (\"acos\" , static_cast<double (*)(double)>(&std::acos))\n        (\"asin\" , static_cast<double (*)(double)>(&std::asin))\n        (\"atan\" , static_cast<double (*)(double)>(&std::atan))\n        (\"ceil\" , static_cast<double (*)(double)>(&std::ceil))\n        (\"cos\"  , static_cast<double (*)(double)>(&std::cos))\n        (\"cosh\" , static_cast<double (*)(double)>(&std::cosh))\n        (\"deg\"  , static_cast<double (*)(double)>(&math::deg))\n        (\"exp\"  , static_cast<double (*)(double)>(&std::exp))\n        (\"floor\", static_cast<double (*)(double)>(&std::floor))\n        (\"isinf\", static_cast<double (*)(double)>(&math::isinf))\n        (\"isnan\", static_cast<double (*)(double)>(&math::isnan))\n        (\"log\"  , static_cast<double (*)(double)>(&std::log))\n        (\"log10\", static_cast<double (*)(double)>(&std::log10))\n        (\"rad\"  , static_cast<double (*)(double)>(&math::rad))\n        (\"sgn\"  , static_cast<double (*)(double)>(&math::sgn))\n        (\"sin\"  , static_cast<double (*)(double)>(&std::sin))\n        (\"sinh\" , static_cast<double (*)(double)>(&std::sinh))\n        (\"sqrt\" , static_cast<double (*)(double)>(&std::sqrt))\n        (\"tan\"  , static_cast<double (*)(double)>(&std::tan))\n        (\"tanh\" , static_cast<double (*)(double)>(&std::tanh))\n        ;\n\n    bfunc.add\n        (\"atan2\", static_cast<double (*)(double, double)>(&std::atan2))\n        (\"pow\"  , static_cast<double (*)(double, double)>(&std::pow))\n        ;\n\n    unary_op.add\n        (\"+\", static_cast<double (*)(double)>(&math::plus))\n        (\"-\", static_cast<double (*)(double)>(&math::minus))\n        (\"!\", static_cast<double (*)(double)>(&math::unary_not))\n        ;\n\n    additive_op.add\n        (\"+\", static_cast<double (*)(double, double)>(&math::plus))\n        (\"-\", static_cast<double (*)(double, double)>(&math::minus))\n        ;\n\n    multiplicative_op.add\n        (\"*\", static_cast<double (*)(double, double)>(&math::multiplies))\n        (\"/\", static_cast<double (*)(double, double)>(&math::divides))\n        (\"%\", static_cast<double (*)(double, double)>(&std::fmod))\n        ;\n\n    logical_op.add\n        (\"&&\", static_cast<double (*)(double, double)>(&math::logical_and))\n        (\"||\", static_cast<double (*)(double, double)>(&math::logical_or))\n        ;\n\n    relational_op.add\n        (\"<\" , static_cast<double (*)(double, double)>(&math::less))\n        (\"<=\", static_cast<double (*)(double, double)>(&math::less_equals))\n        (\">\" , static_cast<double (*)(double, double)>(&math::greater))\n        (\">=\", static_cast<double (*)(double, double)>(&math::greater_equals))\n        ;\n\n    equality_op.add\n        (\"==\", static_cast<double (*)(double, double)>(&math::equals))\n        (\"!=\", static_cast<double (*)(double, double)>(&math::not_equals))\n        ;\n\n    power.add\n        (\"**\", static_cast<double (*)(double, double)>(&std::pow))\n        ;\n\n    expression =\n        logical.alias()\n        ;\n\n    logical =\n        equality >> *(logical_op > equality)\n        ;\n\n    equality =\n        relational >> *(equality_op > relational)\n        ;\n\n    relational =\n        additive >> *(relational_op > additive)\n        ;\n\n    additive =\n        multiplicative >> *(additive_op > multiplicative)\n        ;\n\n    multiplicative =\n        factor >> *(multiplicative_op > factor)\n        ;\n\n    factor =\n        primary >> *( power > factor )\n        ;\n\n    unary =\n        ufunc > '(' > expression > ')'\n        ;\n\n    binary =\n        bfunc > '(' > expression > ',' > expression > ')'\n        ;\n\n    variable =\n        raw[lexeme[alpha >> *(alnum | '_')]]\n        ;\n\n    primary =\n          double_\n        | ('(' > expression > ')')\n        | (unary_op > primary)\n        | binary\n        | unary\n        | constant\n        | variable\n        ;\n\n    // clang-format on\n\n    expression.name(\"expression\");\n    logical.name(\"logical\");\n    equality.name(\"equality\");\n    relational.name(\"relational\");\n    additive.name(\"additive\");\n    multiplicative.name(\"multiplicative\");\n    factor.name(\"factor\");\n    variable.name(\"variable\");\n    primary.name(\"primary\");\n    unary.name(\"unary\");\n    binary.name(\"binary\");\n\n    // typedef boost::phoenix::function<error_handler<Iterator> >\n    // error_handler_function; qi::on_error<qi::fail>(expression,\n    //        error_handler_function(error_handler<Iterator>())(\n    //            \"Error! Expecting \", qi::_4, qi::_3));\n    qi::on_error<qi::fail>(\n        expression,\n        boost::phoenix::bind(boost::phoenix::ref(err_handler), _3, _2, _4));\n}\n\n} // namespace parser\n\n} // namespace matheval\n", "meta": {"hexsha": "a179a096c0d9ccb81a21879e38beb9bd9cbe47f6", "size": 5682, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "libs/boost_matheval/src/qi/parser_def.hpp", "max_stars_repo_name": "0um/PrecisionCheck", "max_stars_repo_head_hexsha": "dc74ccd6e56e270ec360f0f7e8d5aff2432ee9d3", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 17.0, "max_stars_repo_stars_event_min_datetime": "2018-01-26T01:58:59.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T13:49:05.000Z", "max_issues_repo_path": "libs/boost_matheval/src/qi/parser_def.hpp", "max_issues_repo_name": "0um/PrecisionCheck", "max_issues_repo_head_hexsha": "dc74ccd6e56e270ec360f0f7e8d5aff2432ee9d3", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 10.0, "max_issues_repo_issues_event_min_datetime": "2017-11-07T04:32:37.000Z", "max_issues_repo_issues_event_max_datetime": "2019-10-31T06:53:42.000Z", "max_forks_repo_path": "libs/boost_matheval/src/qi/parser_def.hpp", "max_forks_repo_name": "0um/PrecisionCheck", "max_forks_repo_head_hexsha": "dc74ccd6e56e270ec360f0f7e8d5aff2432ee9d3", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2017-11-07T07:09:06.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-31T03:03:03.000Z", "avg_line_length": 29.59375, "max_line_length": 78, "alphanum_fraction": 0.5584301302, "num_tokens": 1385, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6477982043529715, "lm_q2_score": 0.48438008427698437, "lm_q1q2_score": 0.3137805488189715}}
{"text": "/** \n All of this code is written by Aman Agrawal \n (Indian Institute of Technology, Delhi)\n*/\n\n#include <bits/stdc++.h>\n#include <Eigen/Dense>\n#include <Eigen/Core>\n#include <Eigen/LU>\n#include <Eigen/SVD>\n#include <Eigen/QR>\n#include \"time.h\"\n#include <thread>\n#include <chrono>\n\n#include \"genotype.h\"\n#include \"mailman.h\"\n#include \"arguments.h\"\n#include \"helper.h\"\n#include \"storage.h\"\n\n#if SSE_SUPPORT==1\n\t#define fastmultiply fastmultiply_sse\n\t#define fastmultiply_pre fastmultiply_pre_sse\n#else\n\t#define fastmultiply fastmultiply_normal\n\t#define fastmultiply_pre fastmultiply_pre_normal\n#endif\n\nusing namespace Eigen;\nusing namespace std;\n\n// Storing in RowMajor Form\ntypedef Matrix<double, Dynamic, Dynamic, RowMajor> MatrixXdr;\n\n//Intermediate Variables\n//\n// How to batch columns: \nint blocksize;\ndouble **partialsums;\ndouble *sum_op;\t\t\n\n// Intermediate computations in E-step. \n// Size = 3^(log_3(n)) * k\ndouble **yint_e;\n//  n X k\ndouble ***y_e;\n\n// Intermediate computations in M-step. \n// Size = nthreads X 3^(log_3(n)) * k\ndouble **yint_m;\n//  nthreads X log_3(n) X k\ndouble ***y_m;\n\n\nstruct timespec t0;\n\nclock_t total_begin = clock();\n\ngenotype g;\nMatrixXdr geno_matrix; //(p,n)\n\nint MAX_ITER;\nint k,p,n;\nint k_orig;\n\nMatrixXdr c; //(p,k)\nMatrixXdr x; //(k,n)\nMatrixXdr v; //(p,k)\nMatrixXdr means; //(p,1)\nMatrixXdr stds; //(p,1)\n\noptions command_line_opts;\n\nbool debug = false;\nbool check_accuracy = false;\nbool var_normalize=false;\nint accelerated_em=0;\ndouble convergence_limit;\nbool memory_efficient = false;\nbool missing=false;\nbool fast_mode = true;\nbool text_version = false;\nint nthreads = 1;\n\n\n\n\nvoid multiply_y_pre_fast_thread (int begin, int end, MatrixXdr &op, int Ncol_op, double *yint_m, double **y_m, double *partialsums, MatrixXdr &res){\n\tfor(int seg_iter = begin; seg_iter < end; seg_iter++){\n\t\tmailman::fastmultiply ( g.segment_size_hori, g.Nindv, Ncol_op, g.p[seg_iter], op, yint_m, partialsums, y_m);\n\t\tint p_base = seg_iter * g.segment_size_hori; \n\t\tfor(int p_iter=p_base; (p_iter < p_base + g.segment_size_hori) && (p_iter < g.Nsnp) ; p_iter++ ){\n\t\t\tfor(int k_iter = 0; k_iter < Ncol_op; k_iter++) \n\t\t\t\tres(p_iter, k_iter) = y_m [p_iter - p_base][k_iter];\n\t\t}\n\t}\n}\n\nvoid multiply_y_post_fast_thread (int begin, int end, MatrixXdr &op, int Ncol_op, double *yint_e, double **y_e, double *partialsums){\n\tfor (int i = 0 ; i < g.Nindv ; i++) {\n\t\tmemset (y_e[i], 0, blocksize * sizeof(double));\n\t}\n\n\tfor(int seg_iter = begin; seg_iter < end; seg_iter++){\n\t\tmailman::fastmultiply_pre (g.segment_size_hori, g.Nindv, Ncol_op, seg_iter * g.segment_size_hori, g.p[seg_iter], op, yint_e, partialsums, y_e);\n\t}\n}\n\n\n/*\n * M-step: Compute C = Y E \n * Y : p X n genotype matrix\n * E : n K k matrix: X^{T} (XX^{T})^{-1}\n * C = p X k matrix\n *\n * op : E\n * Ncol_op : k\n * res : C\n * subtract_means :\n */\nvoid multiply_y_pre_fast(MatrixXdr &op, int Ncol_op ,MatrixXdr &res,bool subtract_means){\n\t\n\tfor(int k_iter = 0; k_iter < Ncol_op; k_iter++){\n\t\tsum_op[k_iter] = op.col(k_iter).sum();\t\t\n\t}\n\n\t#if DEBUG==1\n\t\tif(debug){\n\t\t\tprint_time (); \n\t\t\tcout <<\"Starting mailman on premultiply\"<<endl;\n\t\t\tcout << \"Nops = \" << Ncol_op << \"\\t\" <<g.Nsegments_hori << endl;\n\t\t\tcout << \"Segment size = \" << g.segment_size_hori << endl;\n\t\t\tcout << \"Matrix size = \" <<g.segment_size_hori<<\"\\t\" <<g.Nindv << endl;\n\t\t\tcout << \"op = \" <<  op.rows () << \"\\t\" << op.cols () << endl;\n\t\t}\n\t#endif\n\n\n\t//TODO: Memory Effecient SSE FastMultipy\n\n\tnthreads = (nthreads > g.Nsegments_hori) ? g.Nsegments_hori: nthreads;\n\n\tstd::thread th [nthreads];\n\tint perthread = g.Nsegments_hori/nthreads;\n//\tcout << g.Nsegments_hori << \"\\t\" << nthreads << \"\\t\" << perthread << endl;\n\tint t = 0;\n\tfor (; t < nthreads - 1; t++) {\n//\t\tcout << \"Launching thread \" << t << endl;\n\t\tth[t] = std::thread (multiply_y_pre_fast_thread, t * perthread , (t+1)*perthread, std::ref (op), Ncol_op, yint_m[t], y_m[t], partialsums[t], std::ref(res));\n\t}\n\t\n\tth[t] = std::thread (multiply_y_pre_fast_thread, t * perthread , g.Nsegments_hori  - 1, std::ref (op), Ncol_op, yint_m[t], y_m[t], partialsums[t], std::ref(res));\n\n\tfor (int t = 0 ; t < nthreads; t++) {\n\t\tth[t].join ();\n\t}\n\t\n/*\n\tfor(int seg_iter = 0; seg_iter < g.Nsegments_hori - 1; seg_iter++){\n\t\tmailman::fastmultiply ( g.segment_size_hori, g.Nindv, Ncol_op, g.p[seg_iter], op, yint_m, partialsums, y_m);\n\t\tint p_base = seg_iter * g.segment_size_hori; \n\t\tfor(int p_iter=p_base; (p_iter < p_base + g.segment_size_hori) && (p_iter < g.Nsnp) ; p_iter++ ){\n\t\t\tfor(int k_iter = 0; k_iter < Ncol_op; k_iter++) \n\t\t\t\tres(p_iter, k_iter) = y_m [p_iter - p_base][k_iter];\n\t\t}\n\t}\n*/\n\n\tint last_seg_size = (g.Nsnp % g.segment_size_hori !=0 ) ? g.Nsnp % g.segment_size_hori : g.segment_size_hori;\n\tmailman::fastmultiply(last_seg_size, g.Nindv, Ncol_op, g.p[g.Nsegments_hori-1], op, yint_m[0], partialsums[0], y_m[0]);\t\t\n\tint p_base = (g.Nsegments_hori - 1) * g.segment_size_hori;\n\tfor(int p_iter = p_base; (p_iter < p_base + g.segment_size_hori) && (p_iter < g.Nsnp) ; p_iter++){\n\t\tfor(int k_iter = 0; k_iter < Ncol_op; k_iter++) \n\t\t\tres(p_iter, k_iter) = y_m [0][p_iter - p_base][k_iter];\n\t}\n\n\t#if DEBUG==1\n\t\tif(debug){\n\t\t\tprint_time (); \n\t\t\tcout <<\"Ending mailman on premultiply\"<<endl;\n\t\t}\n\t#endif\n\n\n\tif(!subtract_means)\n\t\treturn;\n\n\tfor(int p_iter = 0; p_iter < p; p_iter++){\n \t\tfor(int k_iter = 0 ; k_iter < Ncol_op; k_iter++){\t\t \n\t\t\tres(p_iter, k_iter) = res(p_iter, k_iter) - (g.get_col_mean(p_iter)*sum_op[k_iter]);\n\t\t\tif(var_normalize)\n\t\t\t\tres(p_iter, k_iter) = res(p_iter, k_iter)/(g.get_col_std(p_iter));\t\t\n \t\t}\t\t\n \t}\t\n\n}\n\n/*\n * E-step: Compute X = D Y \n * Y : p X n genotype matrix\n * D : k X p matrix: (C^T C)^{-1} C^{T}\n * X : k X n matrix\n *\n * op_orig : D\n * Nrows_op : k\n * res : X\n * subtract_means :\n */\nvoid multiply_y_post_fast(MatrixXdr &op_orig, int Nrows_op, MatrixXdr &res,bool subtract_means){\n\n\tMatrixXdr op;\n\top = op_orig.transpose();\n\n\tif(var_normalize && subtract_means){\n\t\tfor(int p_iter = 0; p_iter < p ; p_iter++){\n\t\t\tfor(int k_iter = 0; k_iter < Nrows_op; k_iter++)\t\t\n\t\t\t\top(p_iter,k_iter) = op(p_iter,k_iter) / (g.get_col_std(p_iter));\t\t\n\t\t}\t\t\n\t}\n\n\t#if DEBUG==1\n\t\tif(debug){\n\t\t\tprint_time (); \n\t\t\tcout <<\"Starting mailman on postmultiply\"<<endl;\n\t\t}\n\t#endif\n\t\n\tint Ncol_op = Nrows_op;\n\n\tnthreads = (nthreads > g.Nsegments_hori) ? g.Nsegments_hori: nthreads;\n\n\tstd::thread th [nthreads];\n\tint perthread = g.Nsegments_hori/nthreads;\n//\tcout << \"post: \" << g.segment_size_hori << \"\\t\" << g.Nsegments_hori << \"\\t\" << nthreads << \"\\t\" << perthread << endl;\n\tint t = 0;\n\tfor (; t < nthreads - 1; t++) {\n//\t\tcout << \"Launching \" << t << endl;\n\t\tth[t] = std::thread ( multiply_y_post_fast_thread,t * perthread, (t+1)*perthread, std::ref(op), Ncol_op, yint_e[t], y_e[t], partialsums[t]);\n\n\t}\n//\tcout << \"Launching \" << t << endl;\n\tth[t] = std::thread ( multiply_y_post_fast_thread, t * perthread, g.Nsegments_hori - 1, std::ref(op), Ncol_op, yint_e[t], y_e[t], partialsums[t]);\n\tfor (int t = 0 ; t < nthreads; t++) {\n\t\tth[t].join ();\n\t}\n//\tcout << \"Joined \"<< endl;\n\n/*\n\tint seg_iter;\n\tfor(seg_iter = 0; seg_iter < g.Nsegments_hori-1; seg_iter++){\n\t\tmailman::fastmultiply_pre (g.segment_size_hori, g.Nindv, Ncol_op, seg_iter * g.segment_size_hori, g.p[seg_iter], op, yint_e, partialsums[0], y_e);\n\t}\n*/\n\n\tfor (int t = 1 ; t < nthreads; t++){\n\t\tfor(int n_iter = 0; n_iter < n; n_iter++) \n\t\t\tfor(int k_iter = 0; k_iter < Ncol_op; k_iter++)\n\t\t\t\ty_e [0][n_iter][k_iter] += y_e[t][n_iter][k_iter];\n\t}\n\n\tint last_seg_size = (g.Nsnp % g.segment_size_hori !=0 ) ? g.Nsnp % g.segment_size_hori : g.segment_size_hori;\n\tmailman::fastmultiply_pre(last_seg_size, g.Nindv, Ncol_op, (g.Nsegments_hori-1) * g.segment_size_hori, g.p[g.Nsegments_hori-1], op, yint_e[0], partialsums[0], y_e[0]);\n\n\tfor(int n_iter = 0; n_iter < n; n_iter++)  {\n\t\tfor(int k_iter = 0; k_iter < Ncol_op; k_iter++) {\n\t\t\tres(k_iter,n_iter) = y_e[0][n_iter][k_iter];\n\t\t\ty_e[0][n_iter][k_iter] = 0;\n\t\t}\n\t}\n\t\n\t#if DEBUG==1\n\t\tif(debug){\n\t\t\tprint_time (); \n\t\t\tcout <<\"Ending mailman on postmultiply\"<<endl;\n\t\t}\n\t#endif\n\n\n\tif(!subtract_means)\n\t\treturn;\n\n\tdouble *sums_elements = new double[Ncol_op];\n \tmemset (sums_elements, 0, Nrows_op * sizeof(int));\n\n \tfor(int k_iter=0;k_iter<Ncol_op;k_iter++){\t\t\n \t\tdouble sum_to_calc=0.0;\t\t\n \t\tfor(int p_iter=0;p_iter<p;p_iter++)\t\t\n \t\t\tsum_to_calc += g.get_col_mean(p_iter)*op(p_iter,k_iter);\t\t\n \t\tsums_elements[k_iter] = sum_to_calc;\t\t\n \t}\t\t\n \tfor(int k_iter=0;k_iter<Ncol_op;k_iter++){\t\t\n \t\tfor(int n_iter=0;n_iter<n;n_iter++)\t\t\n \t\t\tres(k_iter,n_iter) = res(k_iter,n_iter) - sums_elements[k_iter];\t\t\n \t}\n\n}\n\nvoid multiply_y_pre_naive_mem(MatrixXdr &op, int Ncol_op ,MatrixXdr &res){\n\tfor(int p_iter=0;p_iter<p;p_iter++){\n\t\tfor(int k_iter=0;k_iter<Ncol_op;k_iter++){\n\t\t\tdouble temp=0;\n\t\t\tfor(int n_iter=0;n_iter<n;n_iter++)\n\t\t\t\ttemp+= g.get_geno(p_iter,n_iter,var_normalize)*op(n_iter,k_iter);\n\t\t\tres(p_iter,k_iter)=temp;\n\t\t}\n\t}\n}\n\nvoid multiply_y_post_naive_mem(MatrixXdr &op, int Nrows_op ,MatrixXdr &res){\n\tfor(int n_iter=0;n_iter<n;n_iter++){\n\t\tfor(int k_iter=0;k_iter<Nrows_op;k_iter++){\n\t\t\tdouble temp=0;\n\t\t\tfor(int p_iter=0;p_iter<p;p_iter++)\n\t\t\t\ttemp+= op(k_iter,p_iter)*(g.get_geno(p_iter,n_iter,var_normalize));\n\t\t\tres(k_iter,n_iter)=temp;\n\t\t}\n\t}\n}\n\nvoid multiply_y_pre_naive(MatrixXdr &op, int Ncol_op ,MatrixXdr &res){\n\tres = geno_matrix * op;\n}\n\nvoid multiply_y_post_naive(MatrixXdr &op, int Nrows_op ,MatrixXdr &res){\n\tres = op * geno_matrix;\n}\n\nvoid multiply_y_post(MatrixXdr &op, int Nrows_op ,MatrixXdr &res,bool subtract_means){\n    if(fast_mode)\n        multiply_y_post_fast(op,Nrows_op,res,subtract_means);\n    else{\n\t\tif(memory_efficient)\n\t\t\tmultiply_y_post_naive_mem(op,Nrows_op,res);\n\t\telse\n\t\t\tmultiply_y_post_naive(op,Nrows_op,res);\n\t}\n}\n\nvoid multiply_y_pre(MatrixXdr &op, int Ncol_op ,MatrixXdr &res,bool subtract_means){\n    if(fast_mode)\n        multiply_y_pre_fast(op,Ncol_op,res,subtract_means);\n    else{\n\t\tif(memory_efficient)\n\t\t\tmultiply_y_pre_naive_mem(op,Ncol_op,res);\n\t\telse\n\t\t\tmultiply_y_pre_naive(op,Ncol_op,res);\n\t}\n}\n\npair<double,double> get_error_norm(MatrixXdr &c){\n\tHouseholderQR<MatrixXdr> qr(c);\n\tMatrixXdr Q;\n\tQ = qr.householderQ() * MatrixXdr::Identity(p,k);\n\tMatrixXdr q_t(k,p);\n\tq_t = Q.transpose();\n\tMatrixXdr b(k,n);\n\t// Need this for subtracting the correct mean in case of missing data\n\tif(missing){\n\t\tmultiply_y_post(q_t,k,b,false);\n\t\t// Just calculating b from seen data\n\t\tMatrixXdr M_temp(k,1);\n\t\tM_temp = q_t * means;\n\t\tfor(int j=0;j<n;j++){\n\t\t\tMatrixXdr M_to_remove(k,1);\n\t\t\tM_to_remove = MatrixXdr::Zero(k,1);\n\t\t\tfor(int i=0;i<g.not_O_j[j].size();i++){\n\t\t\t\tint idx = g.not_O_j[j][i];\n\t\t\t\tM_to_remove = M_to_remove + (Q.row(idx).transpose()*g.get_col_mean(idx));\n\t\t\t}\n\t\t\tb.col(j) -= (M_temp - M_to_remove);\n\t\t}\n\t}\n\telse{\n\t\tmultiply_y_post(q_t,k,b,true);\t\t\n\t}\n\n\tJacobiSVD<MatrixXdr> b_svd(b, ComputeThinU | ComputeThinV);\n\tMatrixXdr u_l,d_l,v_l; \n\tif(fast_mode)\n        u_l = b_svd.matrixU();\n    else\n        u_l = Q * b_svd.matrixU();\n\tv_l = b_svd.matrixV();\n\td_l = MatrixXdr::Zero(k,k);\n\tfor(int kk=0;kk<k; kk++)\n\t\td_l(kk,kk) = (b_svd.singularValues())(kk);\n\t\n\tMatrixXdr u_k,v_k,d_k;\n\tu_k = u_l.leftCols(k_orig);\n\tv_k = v_l.leftCols(k_orig);\n\td_k = MatrixXdr::Zero(k_orig,k_orig);\n\tfor(int kk =0 ; kk < k_orig ; kk++)\n\t\td_k(kk,kk)  =(b_svd.singularValues())(kk);\n\n\tMatrixXdr b_l,b_k;\n    b_l = u_l * d_l * (v_l.transpose());\n    b_k = u_k * d_k * (v_k.transpose());\n\n    if(fast_mode){\n        double temp_k = b_k.cwiseProduct(b).sum();\n        double temp_l = b_l.cwiseProduct(b).sum();\n        double b_knorm = b_k.norm();\n        double b_lnorm = b_l.norm();\n        double norm_k = (b_knorm*b_knorm) - (2*temp_k);\n        double norm_l = (b_lnorm*b_lnorm) - (2*temp_l);\t\n        return make_pair(norm_k,norm_l);\n    }\n    else{\n        MatrixXdr e_l(p,n);\n        MatrixXdr e_k(p,n);\n        for(int p_iter=0;p_iter<p;p_iter++){\n            for(int n_iter=0;n_iter<n;n_iter++){\n                e_l(p_iter,n_iter) = g.get_geno(p_iter,n_iter,var_normalize) - b_l(p_iter,n_iter);\n                e_k(p_iter,n_iter) = g.get_geno(p_iter,n_iter,var_normalize) - b_k(p_iter,n_iter);\n            }\n        }\n\n        double ek_norm = e_k.norm();\n        double el_norm = e_l.norm();\n        return make_pair(ek_norm,el_norm);\n    }\n}\n\n\n/* Run one iteration of EM when genotypes are not missing\n * c_orig : p X k matrix\n * Output: c_new : p X k matrix \n */\nMatrixXdr run_EM_not_missing(MatrixXdr &c_orig){\n\t\n\t#if DEBUG==1\n\t\tif(debug){\n\t\t\tprint_time ();\n\t\t\tcout << \"Enter: run_EM_not_missing\" << endl;\n\t\t}\n\t#endif\n\n \t// c_temp : k X p matrix: (C^T C)^{-1} C^{T}\n\tMatrixXdr c_temp(k,p);\n\tMatrixXdr c_new(p,k);\n\tc_temp = ( (c_orig.transpose()*c_orig).inverse() ) * (c_orig.transpose());\n\t\n\t#if DEBUG==1\n\t\tif(debug){\n\t\t\tprint_timenl ();\n\t\t}\n\t#endif\n\t\n \t/* E-step: Compute X = D Y \n \t* Y : p X n genotype matrix\n \t* D : k X p matrix: (C^T C)^{-1} C^{T}\n \t* X : k X n matrix\n \t*  x_fn: X\n \t*  c_temp: D \n \t*/\n\tMatrixXdr x_fn(k,n);\n\tmultiply_y_post(c_temp,k,x_fn,true);\n\t\n\t#if DEBUG==1\n\t\tif(debug){\n\t\t\tprint_timenl ();\n\t\t}\n\t#endif\n\t\n\t// x_temp : n X k matrix X^{T} (XX^{T})^{-1}\n\tMatrixXdr x_temp(n,k);\n\tx_temp = (x_fn.transpose()) * ((x_fn*(x_fn.transpose())).inverse());\n\n\t/* M-step: C = Y E\n \t* Y : p X n genotype matrix\n \t* E : n K k matrix: X^{T} (XX^{T})^{-1}\n \t* C = p X k matrix\n \t* c_new : C \n \t* x_temp : E \n \t*/\n\tmultiply_y_pre(x_temp,k,c_new,true);\n\t\n\t#if DEBUG==1\n\t\tif(debug){\n\t\t\tprint_time ();\n\t\t\tcout << \"Exiting: run_EM_not_missing\" << endl;\n\t\t}\n\t#endif\n\n\treturn c_new;\n}\n\nMatrixXdr run_EM_missing(MatrixXdr &c_orig){\n\t\n\tMatrixXdr c_new(p,k);\n\n\tMatrixXdr mu(k,n);\n\t\n\t// E step\n\tMatrixXdr c_temp(k,k);\n\tc_temp = c_orig.transpose() * c_orig;\n\n\tMatrixXdr T(k,n);\n\tMatrixXdr c_fn;\n\tc_fn = c_orig.transpose();\n\tmultiply_y_post(c_fn,k,T,false);\n\n\tMatrixXdr M_temp(k,1);\n\tM_temp = c_orig.transpose() *  means;\n\t\n\tfor(int j=0;j<n;j++){\n\t\tMatrixXdr D(k,k);\n\t\tMatrixXdr M_to_remove(k,1);\n\t\tD = MatrixXdr::Zero(k,k);\n\t\tM_to_remove = MatrixXdr::Zero(k,1);\n\t\tfor(int i=0;i<g.not_O_j[j].size();i++){\n\t\t\tint idx = g.not_O_j[j][i];\n\t\t\tD = D + (c_orig.row(idx).transpose() * c_orig.row(idx));\n\t\t\tM_to_remove = M_to_remove + (c_orig.row(idx).transpose()*g.get_col_mean(idx));\n\t\t}\n\t\tmu.col(j) = (c_temp-D).inverse() * ( T.col(j) - M_temp + M_to_remove);\n\t}\n\n\t#if DEBUG==1\n\t\tif(debug){\n\t\t\tofstream x_file;\n\t\t\tx_file.open((string(command_line_opts.OUTPUT_PATH)+string(\"x_in_fn_vals.txt\")).c_str());\n\t\t\tx_file<<std::setprecision(15)<<mu<<endl;\n\t\t\tx_file.close();\n\t\t}\n\t#endif\n\n\n\t// M step\n\n\tMatrixXdr mu_temp(k,k);\n\tmu_temp = mu * mu.transpose();\n\tMatrixXdr T1(p,k);\n\tMatrixXdr mu_fn;\n\tmu_fn = mu.transpose();\n\tmultiply_y_pre(mu_fn,k,T1,false);\n\tMatrixXdr mu_sum(k,1);\n\tmu_sum = MatrixXdr::Zero(k,1);\n\tmu_sum = mu.rowwise().sum();\n\n\tfor(int i=0;i<p;i++){\n\t\tMatrixXdr D(k,k);\n\t\tMatrixXdr mu_to_remove(k,1);\n\t\tD = MatrixXdr::Zero(k,k);\n\t\tmu_to_remove = MatrixXdr::Zero(k,1);\n\t\tfor(int j=0;j<g.not_O_i[i].size();j++){\n\t\t\tint idx = g.not_O_i[i][j];\n\t\t\tD = D + (mu.col(idx) * mu.col(idx).transpose());\n\t\t\tmu_to_remove = mu_to_remove + (mu.col(idx));\n\t\t}\n\t\tc_new.row(i) = (((mu_temp-D).inverse()) * (T1.row(i).transpose() -  ( g.get_col_mean(i) * (mu_sum-mu_to_remove)))).transpose();\n\t\tdouble mean;\n\t\tmean = g.get_col_sum(i);\n\t\tmean = mean -  (c_orig.row(i)*(mu_sum-mu_to_remove))(0,0);\n\t\tmean = mean * 1.0 / (n-g.not_O_i[i].size());\n\t\tg.update_col_mean(i,mean);\n\t}\n\n\t// IMPORTANT: Update the value of means variable present locally, so that for next iteration, updated value of means is used.\n\tfor(int i=0;i<p;i++){\n\t\tmeans(i,0) = g.get_col_mean(i);\n\t\t// Also updating std, just for consistency, though, it is not used presently.\n\t\tstds(i,0) = g.get_col_std(i);\n\t}\n\n\treturn c_new;\n}\n\nMatrixXdr run_EM(MatrixXdr &c_orig){\n\t\n\tif(missing)\n\t\treturn run_EM_missing(c_orig);\n\telse\n\t\treturn run_EM_not_missing(c_orig);\n}\n\nvoid print_vals(){\n\n\tHouseholderQR<MatrixXdr> qr(c);\n\tMatrixXdr Q;\n\tQ = qr.householderQ() * MatrixXdr::Identity(p,k);\n\tMatrixXdr q_t(k,p);\n\tq_t = Q.transpose();\n\tMatrixXdr b(k,n);\n\n\t// Need this for subtracting the correct mean in case of missing data\n\tif(missing){\n\t\tmultiply_y_post(q_t,k,b,false);\n\t\t// Just calculating b from seen data\n\t\tMatrixXdr M_temp(k,1);\n\t\tM_temp = q_t * means;\n\t\tfor(int j=0;j<n;j++){\n\t\t\tMatrixXdr M_to_remove(k,1);\n\t\t\tM_to_remove = MatrixXdr::Zero(k,1);\n\t\t\tfor(int i=0;i<g.not_O_j[j].size();i++){\n\t\t\t\tint idx = g.not_O_j[j][i];\n\t\t\t\tM_to_remove = M_to_remove + (Q.row(idx).transpose()*g.get_col_mean(idx));\n\t\t\t}\n\t\t\tb.col(j) -= (M_temp - M_to_remove);\n\t\t}\n\t}\n\telse{\n\t\tmultiply_y_post(q_t,k,b,true);\t\t\n\t}\n\t\n\tJacobiSVD<MatrixXdr> b_svd(b, ComputeThinU | ComputeThinV);\n\tMatrixXdr u_l; \n\tu_l = b_svd.matrixU();\n\tMatrixXdr v_l;\n\tv_l = b_svd.matrixV();\n\tMatrixXdr u_k;\n\tMatrixXdr v_k,d_k;\n\tu_k = u_l.leftCols(k_orig);\n\tv_k = v_l.leftCols(k_orig);\n\n\tofstream evec_file;\n\tevec_file.open((string(command_line_opts.OUTPUT_PATH)+string(\"evecs.txt\")).c_str());\n\tevec_file<< std::setprecision(15) << Q*u_k << endl;\n\tevec_file.close();\n\tofstream eval_file;\n\teval_file.open((string(command_line_opts.OUTPUT_PATH)+string(\"evals.txt\")).c_str());\n\tfor(int kk =0 ; kk < k_orig ; kk++)\n\t\teval_file << std::setprecision(15)<< (b_svd.singularValues())(kk)*(b_svd.singularValues())(kk)/g.Nsnp<<endl;\n\teval_file.close();\n\n\tofstream proj_file;\n\tproj_file.open((string(command_line_opts.OUTPUT_PATH) + string(\"projections.txt\")).c_str());\n\tproj_file << std::setprecision(15)<< v_k<<endl;\n\tproj_file.close();\n\tif(debug){\n\t\tofstream c_file;\n\t\tc_file.open((string(command_line_opts.OUTPUT_PATH)+string(\"cvals.txt\")).c_str());\n\t\tc_file<<std::setprecision(15)<<c<<endl;\n\t\tc_file.close();\n\n\t\tofstream means_file;\n\t\tmeans_file.open((string(command_line_opts.OUTPUT_PATH)+string(\"means.txt\")).c_str());\n\t\tmeans_file<<std::setprecision(15)<<means<<endl;\n\t\tmeans_file.close();\n\t\t\n\t\td_k = MatrixXdr::Zero(k_orig,k_orig);\n\t\tfor(int kk =0 ; kk < k_orig ; kk++)\n\t\t\td_k(kk,kk)  =(b_svd.singularValues())(kk);\n\t\tMatrixXdr x_k;\n\t\tx_k = d_k * (v_k.transpose());\n\t\tofstream x_file;\n\t\tx_file.open((string(command_line_opts.OUTPUT_PATH) + string(\"xvals.txt\")).c_str());\n\t\tx_file<<std::setprecision(15)<<x_k.transpose()<<endl;\n\t\tx_file.close();\n\t}\n}\n\nint main(int argc, char const *argv[]){\n\t\n\tauto start = std::chrono::system_clock::now();\n\n\tclock_t io_begin = clock();\n    clock_gettime (CLOCK_REALTIME, &t0);\n\n\tpair<double,double> prev_error = make_pair(0.0,0.0);\n\tdouble prevnll=0.0;\n\n\tparse_args(argc,argv);\n\n\t\n\t//TODO: Memory Effecient Version of Mailman\n\n\tmemory_efficient = command_line_opts.memory_efficient;\n\ttext_version = command_line_opts.text_version;\n    fast_mode = command_line_opts.fast_mode;\n\tmissing = command_line_opts.missing;\n    MAX_ITER =  command_line_opts.max_iterations ; \n\tk_orig = command_line_opts.num_of_evec ;\n\tdebug = command_line_opts.debugmode ;\n\tcheck_accuracy = command_line_opts.getaccuracy;\n\tvar_normalize = command_line_opts.var_normalize;\n\taccelerated_em = command_line_opts.accelerated_em;\n\tnthreads = command_line_opts.nthreads;\n\t\n\tif(text_version){\n\t\tif(fast_mode)\n\t\t\tg.read_txt_mailman(command_line_opts.GENOTYPE_FILE_PATH,missing);\n\t\telse\n\t\t\tg.read_txt_naive(command_line_opts.GENOTYPE_FILE_PATH,missing);\n\t}\n\telse{\n\t\tg.read_plink(command_line_opts.GENOTYPE_FILE_PATH,missing,fast_mode);\n\t}\n\n\t//TODO: Implement these codes.\n\tif(missing && !fast_mode){\n\t\tcout<<\"Missing version works only with mailman i.e. fast mode\\n EXITING...\"<<endl;\n\t\texit(-1);\n\t}\n\tif(fast_mode && memory_efficient){\n\t\tcout<<\"Memory effecient version for mailman EM not yet implemented\"<<endl;\n\t\tcout<<\"Ignoring Memory effecient Flag\"<<endl;\n\t}\n\tif(missing && var_normalize){\n\t\tcout<<\"Missing version works only without variance normalization\\n EXITING...\"<<endl;\n\t\texit(-1);\n\t}\n\n\tk = k_orig + command_line_opts.l;\n\tk = (int)ceil(k/10.0)*10;\n\tcommand_line_opts.l = k - k_orig;\n\tp = g.Nsnp;\n\tn = g.Nindv;\n\tconvergence_limit = command_line_opts.convergence_limit;\n\tbool toStop=false;\n\tif(convergence_limit!=-1)\n\t\ttoStop=true;\n\n\tif (command_line_opts.given_seed)\n\t\tsrand(command_line_opts.seed);\n\telse\t\t\n\t\tsrand((unsigned int) time(0));\n\n\tc.resize(p,k);\n\tx.resize(k,n);\n\tv.resize(p,k);\n\tmeans.resize(p,1);\n\tstds.resize(p,1);\n\n\tif(!fast_mode && !memory_efficient){\n\t\tgeno_matrix.resize(p,n);\n\t\tg.generate_eigen_geno(geno_matrix,var_normalize);\n\t}\n\t\n\tclock_t io_end = clock();\n\n\t//TODO: Initialization of c with gaussian distribution\n\tc = MatrixXdr::Random(p,k);\n\n\n\t// Initial intermediate data structures\n\t// Operate in blocks to improve caching\n\t//\n\tblocksize = k;\n\tint hsegsize = g.segment_size_hori; \t// = log_3(n)\n\tint hsize = pow(3,hsegsize);\t\t \n\tint vsegsize = g.segment_size_ver; \t\t// = log_3(p)\n\tint vsize = pow(3,vsegsize);\t\t \n\n\n\tpartialsums = new double* [nthreads];\n\tyint_m = new double* [nthreads];\n\tfor (int t = 0 ; t < nthreads ; t++) { \n\t\tpartialsums[t] = new double [blocksize];\n\t\tyint_m[t] = new double [hsize*blocksize];\n\t\tmemset (yint_m[t], 0, hsize*blocksize * sizeof(double));\n\t}\n\n\tsum_op = new double[blocksize];\n\n\tyint_e = new double* [nthreads];\n\tfor (int t = 0 ; t < nthreads ; t++) { \n\t\tyint_e[t] = new double [hsize*blocksize];\n\t\tmemset (yint_e[t], 0, hsize*blocksize * sizeof(double));\n\t}\n\n\ty_e  = new double**[nthreads];\n\tfor (int t = 0 ; t < nthreads ; t++) {\n\t\ty_e[t]  = new double*[g.Nindv];\n\t\tfor (int i = 0 ; i < g.Nindv ; i++) {\n\t\t\ty_e[t][i] = new double[blocksize];\n\t\t\tmemset (y_e[t][i], 0, blocksize * sizeof(double));\n\t\t}\n\t}\n\n\ty_m = new double**[nthreads];\n\tfor (int t = 0 ; t < nthreads; t++){\n\t\ty_m[t] = new double*[hsegsize];\n\t\tfor (int i = 0 ; i < hsegsize ; i++)\n\t\t\ty_m[t][i] = new double[blocksize];\n\n\t}\n\n\tfor(int i=0;i<p;i++){\n\t\tmeans(i,0) = g.get_col_mean(i);\n\t\tstds(i,0) = g.get_col_std(i);\n\t}\n\t\t\n\n\tofstream c_file;\n\tif(debug){\n\t\tc_file.open((string(command_line_opts.OUTPUT_PATH)+string(\"cvals_orig.txt\")).c_str());\n\t\tc_file<<std::setprecision(15)<<c<<endl;\n\t\tc_file.close();\n\t\tprintf(\"Read Matrix\\n\");\n\t}\n\n\tcout<<\"Running on Dataset of \"<<g.Nsnp<<\" SNPs and \"<<g.Nindv<<\" Individuals\"<<endl;\n\n\t#if SSE_SUPPORT==1\n\t\tif(fast_mode)\n\t\t\tcout<<\"Using Optimized SSE FastMultiply\"<<endl;\n\t#endif\n\n\t\n\t\n\tclock_t it_begin = clock();\n\tfor(int i=0;i<MAX_ITER;i++){\n\n\t\tMatrixXdr c1,c2,cint,r,v;\n\t\tdouble a,nll;\n\t\tif(debug){\n\t\t\tprint_time (); \n\t\t\tcout << \"*********** Begin epoch \" << i << \"***********\" << endl;\n\t\t}\n\t\tif(accelerated_em!=0){\n\t\t\t#if DEBUG==1\n\t\t\t\tif(debug){\n\t\t\t\t\tprint_time();\n\t\t\t\t\tcout << \"Before EM\" << endl;\n\t\t\t\t}\n\t\t\t#endif\n\t\t\tc1 = run_EM(c);\n\t\t\tc2 = run_EM(c1);\n\t\t\t#if DEBUG==1\n\t\t\t\tif(debug){\n\t\t\t\t\tprint_time(); \n\t\t\t\t\tcout << \"After EM but before acceleration\" << endl;\n\t\t\t\t}\n\t\t\t#endif\n\t\t\tr = c1-c;\n\t\t\tv = (c2-c1) - r;\n\t\t\ta = -1.0 * r.norm() / (v.norm()) ;\n\t\t\tif(accelerated_em==1){\n\t\t\t\tif(a>-1){\n\t\t\t\t\ta=-1;\n\t\t\t\t\tcint=c2;\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tcint = c - 2*a*r + a*a*v;\n\t\t\t\t\tnll = get_error_norm(cint).second;\n\t\t\t\t\tif(i>0){\n\t\t\t\t\t\twhile(nll>prevnll && a<-1){\n\t\t\t\t\t\t\ta = 0.5 * (a-1);\n\t\t\t\t\t\t\tcint = c - 2*a*r +(a*a*v);\n\t\t\t\t\t\t\tnll = get_error_norm(cint).second;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tc = cint;\n\t\t\t}\n\t\t\telse if(accelerated_em==2){\n\t\t\t\tcint = c - 2*a*r + a*a*v;\n\t\t\t\tc = cint;\n\t\t\t\t// c = run_EM(cint);\t\t\t\t\n\t\t\t}\n\t\t}\n\t\telse{\n\t\t\tc = run_EM(c);\n\t\t}\n\t\t\n\t\tif ( accelerated_em == 1 || check_accuracy || toStop) {\n\t\t\tpair<double,double> e = get_error_norm(c);\n\t\t\tprevnll = e.second;\n\t\t\tif(check_accuracy) \n\t\t\t\tcout<<\"Iteration \"<<i+1<<\"  \"<<std::setprecision(15)<<e.first<<\"  \"<<e.second<<endl;\n\t\t\tif(abs(e.first-prev_error.first)<=convergence_limit){\n\t\t\t\tcout<<\"Breaking after \"<<i+1<<\" iterations\"<<endl;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tprev_error = e;\n\t\t}\n\t\tif(debug){\n\t\t\tprint_time (); \n\t\t\tcout << \"*********** End epoch \" << i << \"***********\" << endl;\n\t\t}\n\n\t}\n\tclock_t it_end = clock();\n\n    print_vals();\n\t\t\n\tclock_t total_end = clock();\n\tdouble io_time = double(io_end - io_begin) / CLOCKS_PER_SEC;\n\tdouble avg_it_time = double(it_end - it_begin) / (MAX_ITER * 1.0 * CLOCKS_PER_SEC);\n\tdouble total_time = double(total_end - total_begin) / CLOCKS_PER_SEC;\n\tcout<<\"IO Time:  \"<< io_time << \"\\nAVG Iteration Time:  \"<<avg_it_time<<\"\\nTotal runtime:   \"<<total_time<<endl;\n\n\tstd::chrono::duration<double> wctduration = std::chrono::system_clock::now() - start;\n\tcout <<\"Wall clock time = \" <<  wctduration.count() << endl;\n\n\n\n\tdelete[] sum_op;\n\tfor (int t = 0 ; t < nthreads ; t++){\n\t\tdelete[] yint_e[t];\n\t}\t\n\tdelete[] yint_e;\n\n\tfor (int t = 0 ; t < nthreads ; t++){\n\t\tdelete[] yint_m[t];\n\t\tdelete[] partialsums[t];\n\t}\n\tdelete[] yint_m;\n\tdelete[] partialsums;\n\n\tfor (int t = 0 ; t < nthreads ; t++){\n\t\tfor (int i  = 0 ; i < hsegsize; i++)\n\t\t\tdelete[] y_m [t][i];\n\t\tdelete[] y_m[t];\n\t} \n\tdelete[] y_m;\n\n\tfor (int t = 0 ; t < nthreads ; t++){\n\t\tfor (int i  = 0 ; i < g.Nindv; i++)\n\t\t\tdelete[] y_e[t][i]; \n\t\tdelete[] y_e[t];\n\t}\n\tdelete[] y_e;\n\n\treturn 0;\n}\n", "meta": {"hexsha": "3afb9a2061e30541ceb4505439572c9bc3778594", "size": 24653, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/propca.cpp", "max_stars_repo_name": "tlangfor/ProPCA", "max_stars_repo_head_hexsha": "e94c9729f5ff9e1c4b70864fd9cb3dc85e4aebe1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2019-09-23T16:28:58.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-09T14:36:57.000Z", "max_issues_repo_path": "src/propca.cpp", "max_issues_repo_name": "tlangfor/ProPCA", "max_issues_repo_head_hexsha": "e94c9729f5ff9e1c4b70864fd9cb3dc85e4aebe1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2020-09-30T06:57:11.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-16T18:19:34.000Z", "max_forks_repo_path": "src/propca.cpp", "max_forks_repo_name": "tlangfor/ProPCA", "max_forks_repo_head_hexsha": "e94c9729f5ff9e1c4b70864fd9cb3dc85e4aebe1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2020-08-27T23:02:27.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-09T14:36:59.000Z", "avg_line_length": 26.8258977149, "max_line_length": 168, "alphanum_fraction": 0.6443840506, "num_tokens": 8038, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6039318337259583, "lm_q2_score": 0.519521321952093, "lm_q1q2_score": 0.31375546462626147}}
{"text": "/* pcmsolver_copyright_start */\n/*\n *     PCMSolver, an API for the Polarizable Continuum Model\n *     Copyright (C) 2013-2016 Roberto Di Remigio, Luca Frediani and contributors\n *     \n *     This file is part of PCMSolver.\n *     \n *     PCMSolver is free software: you can redistribute it and/or modify\n *     it under the terms of the GNU Lesser General Public License as published by\n *     the Free Software Foundation, either version 3 of the License, or\n *     (at your option) any later version.\n *     \n *     PCMSolver is distributed in the hope that it will be useful,\n *     but WITHOUT ANY WARRANTY; without even the implied warranty of\n *     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n *     GNU Lesser General Public License for more details.\n *     \n *     You should have received a copy of the GNU Lesser General Public License\n *     along with PCMSolver.  If not, see <http://www.gnu.org/licenses/>.\n *     \n *     For information on the complete list of contributors to the\n *     PCMSolver API, see: <http://pcmsolver.readthedocs.io/>\n */\n/* pcmsolver_copyright_end */\n\n#ifndef INTEGRATORHELPERFUNCTIONS_HPP\n#define INTEGRATORHELPERFUNCTIONS_HPP\n\n#include <cmath>\n#include <vector>\n\n#include \"Config.hpp\"\n\n#include <Eigen/Core>\n\n#include <boost/mpl/at.hpp>\n#include <boost/mpl/int.hpp>\n#include <boost/mpl/map.hpp>\n\n#include \"cavity/Element.hpp\"\n#include \"utils/QuadratureRules.hpp\"\n\nnamespace integrator {\n/*! \\typedef Diagonal\n *  \\brief functor handle to the calculation of the diagonal elements\n */\ntypedef pcm::function<double(const Element &)> Diagonal;\n\n/*! \\typedef KernelS\n *  \\brief functor handle to the kernelS method in IGreensFunction\n */\ntypedef pcm::function<double(const Eigen::Vector3d &, const Eigen::Vector3d &)> KernelS;\n\n/*! \\typedef KernelD\n *  \\brief functor handle to the kernelD method in IGreensFunction\n */\ntypedef pcm::function<double(const Eigen::Vector3d &, const Eigen::Vector3d &, const Eigen::Vector3d &)> KernelD;\n\n/*! Approximate collocation diagonal for S\n *  \\param[in] factor scaling factor for diagonal elements\n *  \\param[in] eps    permittivity\n *  \\param[in] el     finite element\n */\ninline double SI(double factor, double eps, const Element & el)\n{\n    return (factor * std::sqrt(4 * M_PI / el.area()) * 1.0 / eps);\n}\n\n/*! Approximate collocation diagonal for D\n *  \\param[in] factor scaling factor for diagonal elements\n *  \\param[in] el     finite element\n */\ninline double DI(double factor, const Element & el)\n{\n    return (-factor * std::sqrt(M_PI / el.area()) * 1.0 / el.sphere().radius);\n}\n\n/*! Returns matrix representation of the single layer operator by collocation\n *  \\param[in] elements list of finite elements\n *  \\param[in] diagS    functor for the evaluation of the diagonal of S\n *  \\param[in] kernS    function for the evaluation of the off-diagonal of S\n */\ninline Eigen::MatrixXd singleLayer(const std::vector<Element> & elements,\n                                   const Diagonal & diagS, const KernelS & kernS)\n{\n    PCMSolverIndex mat_size = elements.size();\n    Eigen::MatrixXd S = Eigen::MatrixXd::Zero(mat_size, mat_size);\n    for (PCMSolverIndex i = 0; i < mat_size; ++i) {\n        // Fill diagonal\n        S(i, i) = diagS(elements[i]);\n        Eigen::Vector3d source = elements[i].center();\n        for (PCMSolverIndex j = 0; j < mat_size; ++j) {\n            // Fill off-diagonal\n            Eigen::Vector3d probe = elements[j].center();\n            if (i != j) S(i, j) = kernS(source, probe);\n        }\n    }\n    return S;\n}\n\n/*! Returns matrix representation of the double layer operator by collocation\n *  \\param[in] elements list of finite elements\n *  \\param[in] diagD    functor for the evaluation of the diagonal of D\n *  \\param[in] kernD    function for the evaluation of the off-diagonal of D\n */\ninline Eigen::MatrixXd doubleLayer(const std::vector<Element> & elements,\n                                   const Diagonal & diagD, const KernelD & kernD)\n{\n    PCMSolverIndex mat_size = elements.size();\n    Eigen::MatrixXd D = Eigen::MatrixXd::Zero(mat_size, mat_size);\n    for (PCMSolverIndex i = 0; i < mat_size; ++i) {\n        // Fill diagonal\n        D(i, i) = diagD(elements[i]);\n        Eigen::Vector3d source = elements[i].center();\n        for (PCMSolverIndex j = 0; j < mat_size; ++j) {\n            // Fill off-diagonal\n            Eigen::Vector3d probe = elements[j].center();\n            Eigen::Vector3d probeNormal = elements[j].normal();\n            probeNormal.normalize();\n            if (i != j) D(i, j) = kernD(probeNormal, source, probe);\n        }\n    }\n    return D;\n}\n\n/*! \\brief Integrates a single layer type operator on a single spherical polygon\n *  \\date 2014\n *  \\tparam PhiPoints Gaussian rule to be used in the angular phi integration\n *  \\tparam ThetaPoints Gaussian rule to be used in the angular theta integration\n *\n *  This is needed for the numerical evaluation of the diagonal elements when using\n *  centroid collocation.\n */\ntemplate <int PhiPoints, int ThetaPoints>\ndouble integrateS(const KernelS & F, const Element & e)\n{\n    double result = 0.0;\n\n    // Get the quadrature rules for azimuthal and polar integrations\n    namespace mpl = boost::mpl;\n    typedef typename mpl::at<rules_map, mpl::int_<PhiPoints> >::type PhiPolicy;\n    typedef typename mpl::at<rules_map, mpl::int_<ThetaPoints> >::type ThetaPolicy;\n    QuadratureRule<PhiPolicy> phiRule;\n    QuadratureRule<ThetaPolicy> thetaRule;\n    int upper_phi = PhiPoints / 2; // Upper limit for loop on phi points\n    int upper_theta = ThetaPoints / 2; // Upper limit for loop on theta points\n\n    // Extract relevant data from Element\n    int nVertices = e.nVertices();\n    Eigen::Vector3d normal = e.normal();\n    Sphere sph = e.sphere();\n    Eigen::Matrix3Xd vertices = e.vertices();\n    Eigen::Matrix3Xd arcs = e.arcs();\n\n    // Calculation of the tangent and the bitangent (binormal) vectors\n    // Tangent, Bitangent and Normal form a local reference frame:\n    // T <-> x; B <-> y; N <-> z\n    Eigen::Vector3d tangent, bitangent;\n    tangent_and_bitangent(normal, tangent, bitangent);\n\n    std::vector<double> theta(nVertices), phi(nVertices), phinumb(nVertices+1);\n    std::vector<int> numb(nVertices+1);\n    // Clean-up heap crap\n    std::fill_n(theta.begin(),   nVertices,   0.0);\n    std::fill_n(phi.begin(),     nVertices,   0.0);\n    std::fill_n(numb.begin(),    nVertices+1, 0);\n    std::fill_n(phinumb.begin(), nVertices+1, 0.0);\n    // Populate arrays and redefine tangent and bitangent\n    e.spherical_polygon(tangent, bitangent, theta, phi, phinumb, numb);\n\n    // Actual integration occurs here\n    for (int i = 0; i < nVertices; ++i) { // Loop on edges\n        double phiLower = phinumb[i];\n        double phiUpper = phinumb[i+1];\n        double phiA= (phiUpper - phiLower) / 2.0;\n        double phiB = (phiUpper + phiLower) / 2.0;\n        double thetaLower = theta[numb[i]];\n        double thetaUpper = theta[numb[i+1]];\n        double thetaMax = 0.0;\n        Eigen::Vector3d oc = (arcs.col(i) - sph.center) / sph.radius;\n        double oc_norm = oc.norm();\n        double oc_norm2 = std::pow(oc_norm, 2);\n        for (int j = 0; j < upper_phi; ++j) { // Loop on Gaussian points: phi integration\n            for (int k = 0; k <= 1; ++k) {\n                double ph = (2*k - 1) * phiA * phiRule.abscissa(j) + phiB;\n                double cos_ph = std::cos(ph);\n                double sin_ph = std::sin(ph);\n                // We need to calculate the upper bound for the integration on theta, which depends on phi\n                if (oc_norm2 < 1.0e-07) { // This means that the edge is centered on the same sphere the tessera belongs to\n                    double cotg_thmax = (std::sin(ph-phiLower) / std::tan(thetaUpper) + std::sin(phiUpper-ph) / std::tan(\n                                thetaLower)) / std::sin(phiUpper - phiLower);\n                    thetaMax = std::atan(1.0 / cotg_thmax);\n                } else {\n                    Eigen::Vector3d scratch;\n                    scratch << tangent.dot(oc), bitangent.dot(oc), normal.dot(oc);\n                    double aa = std::pow(tangent.dot(oc)*cos_ph + bitangent.dot(oc)*sin_ph,\n                            2) + std::pow(normal.dot(oc), 2);\n                    double bb = -normal.dot(oc) * oc_norm2;\n                    double cc = std::pow(oc_norm2,\n                            2) - std::pow(tangent.dot(oc)*cos_ph + bitangent.dot(oc)*sin_ph, 2);\n                    double ds = std::pow(bb, 2) - aa*cc;\n                    if (ds < 0.0) ds = 0.0;\n                    double cs = (-bb + std::sqrt(ds)) / aa;\n                    if (cs > 1.0) cs = 1.0;\n                    if (cs < -1.0) cs = 1.0;\n                    thetaMax = std::acos(cs);\n                }\n                double scratch = 0.0;\n                if (!(thetaMax < 1.0e-08)) {\n                    double thetaA = thetaMax / 2.0;\n                    for (int l = 0; l < upper_theta; ++l) { // Loop on Gaussian points: theta integration\n                        for (int m = 0; m <= 1; ++m) {\n                            double th = (2*m - 1) * thetaA * thetaRule.abscissa(l) + thetaA;\n                            double cos_th = std::cos(th);\n                            double sin_th = std::sin(th);\n                            Eigen::Vector3d point;\n                            point(0) = tangent(0) * sin_th * cos_ph\n                                + bitangent(0) * sin_th * sin_ph\n                                + normal(0) * (cos_th - 1.0);\n                            point(1) = tangent(1) * sin_th * cos_ph\n                                + bitangent(1) * sin_th * sin_ph\n                                + normal(1) * (cos_th - 1.0);\n                            point(2) = tangent(2) * sin_th * cos_ph\n                                + bitangent(2) * sin_th * sin_ph\n                                + normal(2) * (cos_th - 1.0);\n                            double value = F(point,\n                                    Eigen::Vector3d::Zero()); // Evaluate integrand at Gaussian point\n                            scratch += std::pow(sph.radius, 2) * value * sin_th * thetaA * thetaRule.weight(l);\n                        }\n                    }\n                    result += scratch * phiA * phiRule.weight(j);\n                }\n            }\n        }\n    }\n    return result;\n}\n\n/*! \\brief Integrates a double layer type operator on a single spherical polygon\n *  \\date 2014\n *  \\tparam PhiPoints Gaussian rule to be used in the angular phi integration\n *  \\tparam ThetaPoints Gaussian rule to be used in the angular theta integration\n *\n *  This is needed for the numerical evaluation of the diagonal elements when using\n *  centroid collocation.\n */\ntemplate <int PhiPoints, int ThetaPoints>\ndouble integrateD(const KernelD & F, const Element & e)\n{\n    double result = 0.0;\n\n    // Get the quadrature rules for azimuthal and polar integrations\n    namespace mpl = boost::mpl;\n    typedef typename mpl::at<rules_map, mpl::int_<PhiPoints> >::type PhiPolicy;\n    typedef typename mpl::at<rules_map, mpl::int_<ThetaPoints> >::type ThetaPolicy;\n    QuadratureRule<PhiPolicy> phiRule;\n    QuadratureRule<ThetaPolicy> thetaRule;\n    int upper_phi = PhiPoints / 2; // Upper limit for loop on phi points\n    int upper_theta = ThetaPoints / 2; // Upper limit for loop on theta points\n\n    // Extract relevant data from Element\n    int nVertices = e.nVertices();\n    Eigen::Vector3d normal = e.normal();\n    Sphere sph = e.sphere();\n    Eigen::Matrix3Xd vertices = e.vertices();\n    Eigen::Matrix3Xd arcs = e.arcs();\n\n    // Calculation of the tangent and the bitangent (binormal) vectors\n    // Tangent, Bitangent and Normal form a local reference frame:\n    // T <-> x; B <-> y; N <-> z\n    Eigen::Vector3d tangent, bitangent;\n    tangent_and_bitangent(normal, tangent, bitangent);\n\n    std::vector<double> theta(nVertices), phi(nVertices), phinumb(nVertices+1);\n    std::vector<int> numb(nVertices+1);\n    // Clean-up heap crap\n    std::fill_n(theta.begin(),   nVertices,   0.0);\n    std::fill_n(phi.begin(),     nVertices,   0.0);\n    std::fill_n(numb.begin(),    nVertices+1, 0);\n    std::fill_n(phinumb.begin(), nVertices+1, 0.0);\n    // Populate arrays and redefine tangent and bitangent\n    e.spherical_polygon(tangent, bitangent, theta, phi, phinumb, numb);\n\n    // Actual integration occurs here\n    for (int i = 0; i < nVertices; ++i) { // Loop on edges\n        double phiLower = phinumb[i]; // Lower vertex of edge\n        double phiUpper = phinumb[i+1]; // Upper vertex of edge\n        double phiA = (phiUpper - phiLower) / 2.0;\n        double phiB = (phiUpper + phiLower) / 2.0;\n        double thetaLower = theta[numb[i]];\n        double thetaUpper = theta[numb[i+1]];\n        double thetaMax = 0.0;\n        Eigen::Vector3d oc = (arcs.col(i) - sph.center) / sph.radius;\n        double oc_norm = oc.norm();\n        double oc_norm2 = std::pow(oc_norm, 2);\n        for (int j = 0; j < upper_phi; ++j) { // Loop on Gaussian points: phi integration\n            for (int k = 0; k <= 1; ++k) {\n                double ph = (2*k - 1) * phiA * phiRule.abscissa(j) + phiB;\n                double cos_phi = std::cos(ph);\n                double sin_phi = std::sin(ph);\n                if (oc_norm2 < 1.0e-07) { // This should check if oc_norm2 is zero\n                    double cotg_thmax = (std::sin(ph-phiLower) / std::tan(thetaUpper) + std::sin(phiUpper-ph) / std::tan(\n                                thetaLower)) / std::sin(phiUpper - phiLower);\n                    thetaMax = std::atan(1.0 / cotg_thmax);\n                } else {\n                    Eigen::Vector3d scratch;\n                    scratch << tangent.dot(oc), bitangent.dot(oc), normal.dot(oc);\n                    double aa = std::pow(tangent.dot(oc)*cos_phi + bitangent.dot(oc)*sin_phi,\n                            2) + std::pow(normal.dot(oc), 2);\n                    double bb = -normal.dot(oc) * oc_norm2;\n                    double cc = std::pow(oc_norm2,\n                            2) - std::pow(tangent.dot(oc)*cos_phi + bitangent.dot(oc)*sin_phi, 2);\n                    double ds = std::pow(bb, 2) - aa*cc;\n                    if (ds < 0.0) ds = 0.0;\n                    double cs = (-bb + std::sqrt(ds)) / aa;\n                    if (cs > 1.0) cs = 1.0;\n                    if (cs < -1.0) cs = 1.0;\n                    thetaMax = std::acos(cs);\n                }\n                double thetaA = thetaMax / 2.0;\n                double scratch = 0.0;\n                if (!(thetaMax < 1.0e-08)) {\n                    for (int l = 0; l < upper_theta; ++l) { // Loop on Gaussian points: theta integration\n                        for (int m = 0; m <= 1; ++m) {\n                            double th = (2*m - 1) * thetaA  * thetaRule.abscissa(l) + thetaA;\n                            double cos_theta = std::cos(th);\n                            double sin_theta = std::sin(th);\n                            Eigen::Vector3d point;\n                            point(0) = tangent(0) * sin_theta * cos_phi\n                                + bitangent(0) * sin_theta * sin_phi\n                                + normal(0) * (cos_theta - 1.0);\n                            point(1) = tangent(1) * sin_theta * cos_phi\n                                + bitangent(1) * sin_theta * sin_phi\n                                + normal(1) * (cos_theta - 1.0);\n                            point(2) = tangent(2) * sin_theta * cos_phi\n                                + bitangent(2) * sin_theta * sin_phi\n                                + normal(2) * (cos_theta - 1.0);\n                            double value = F(e.normal(),\n                                    Eigen::Vector3d::Zero(),\n                                    point); // Evaluate integrand at Gaussian point\n                            scratch += std::pow(sph.radius, 2) * value * sin_theta * thetaA * thetaRule.weight(l);\n                        }\n                    }\n                    result += scratch * phiA * phiRule.weight(j);\n                }\n            }\n        }\n    }\n    return result;\n}\n} // namespace integrator\n\n#endif // INTEGRATORHELPERFUNCTIONS_HPP\n", "meta": {"hexsha": "4ee85213ee573ec4958eecf5c591f44c69b30741", "size": 16160, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "external/PCMSolver/PCMSolver-source/src/bi_operators/IntegratorHelperFunctions.hpp", "max_stars_repo_name": "robertodr/externalize", "max_stars_repo_head_hexsha": "c7b1dda2009dab329a6efb580c57ef8e1494cf3b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2017-02-15T22:16:34.000Z", "max_stars_repo_stars_event_max_datetime": "2017-02-15T22:16:34.000Z", "max_issues_repo_path": "external/PCMSolver/PCMSolver-source/src/bi_operators/IntegratorHelperFunctions.hpp", "max_issues_repo_name": "robertodr/externalize", "max_issues_repo_head_hexsha": "c7b1dda2009dab329a6efb580c57ef8e1494cf3b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "external/PCMSolver/PCMSolver-source/src/bi_operators/IntegratorHelperFunctions.hpp", "max_forks_repo_name": "robertodr/externalize", "max_forks_repo_head_hexsha": "c7b1dda2009dab329a6efb580c57ef8e1494cf3b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 45.6497175141, "max_line_length": 123, "alphanum_fraction": 0.5636138614, "num_tokens": 4118, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6224593312018546, "lm_q2_score": 0.5039061705290805, "lm_q1q2_score": 0.31366109789601915}}
{"text": "#include <cmath>\n#include <iostream>\n#include <vector>\n\n#include <boost/align/aligned_allocator.hpp>\n#include <boost/align/aligned_delete.hpp>\n\n#include <boost/simd/function/cos.hpp>\n#include <boost/simd/function/load.hpp>\n#include <boost/simd/function/sin.hpp>\n#include <boost/simd/function/sincos.hpp>\n#include <boost/simd/function/store.hpp>\n#include <boost/simd/pack.hpp>\n\nint main(int argc, char** argv)\n{\n  namespace bs = boost::simd;\n  namespace ba = boost::alignment;\n\n  using pack_t = bs::pack<float>;\n\n  std::size_t num_elements = 1024;\n  std::size_t alignment    = pack_t::alignment;\n  //! [transcendental-declare]\n  std::vector<float, ba::aligned_allocator<float, pack_t::alignment>> X(num_elements);\n  std::vector<float, ba::aligned_allocator<float, pack_t::alignment>> sinX(num_elements);\n  std::vector<float, ba::aligned_allocator<float, pack_t::alignment>> cosX(num_elements);\n  //! [transcendental-declare]\n\n  //! [transcendental-scalar]\n  for (int i = 0; i < num_elements; ++i) {\n    sinX[i] = std::sin(X[i]);\n    cosX[i] = std::cos(X[i]);\n  }\n  //! [transcendental-scalar]\n\n  //! [transcendental-calc-individ]\n  for (int i = 0; i < num_elements; i += pack_t::static_size) {\n    pack_t v0 = bs::load<pack_t>(&X[i]);\n    bs::store(bs::sin(v0), &sinX[i]);\n    bs::store(bs::cos(v0), &sinX[i]);\n  }\n  //! [transcendental-calc-individ]\n\n  //! [transcendental-calc-combine]\n  for (int i = 0; i < num_elements; i += pack_t::static_size) {\n    pack_t v0 = bs::load<pack_t>(&X[i]);\n    auto res  = bs::sincos(v0);\n    bs::store(res.first, &sinX[i]);\n    bs::store(res.second, &cosX[i]);\n  }\n  //! [transcendental-calc-combine]\n\n  //! [transcendental-calc-small]\n  for (int i = 0; i < num_elements; i += pack_t::static_size) {\n    pack_t v0 = bs::load<pack_t>(&X[i]);\n    bs::store(bs::sin(v0, bs::tag::small_), &sinX[i]);\n  }\n  //! [transcendental-calc-small]\n}\n", "meta": {"hexsha": "1622089ba3cf9688db9644c51d77def707c0d2af", "size": 1872, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "doc/examples/transcendental.cpp", "max_stars_repo_name": "TobiasLudwig/boost.simd", "max_stars_repo_head_hexsha": "c04d0cc56747188ddb9a128ccb5715dd3608dbc1", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2018-02-25T22:23:33.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-15T15:13:12.000Z", "max_issues_repo_path": "doc/examples/transcendental.cpp", "max_issues_repo_name": "dendisuhubdy/boost.simd", "max_issues_repo_head_hexsha": "7630b1c1ffbd0300c100885b89ff78c2d579a24c", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "doc/examples/transcendental.cpp", "max_forks_repo_name": "dendisuhubdy/boost.simd", "max_forks_repo_head_hexsha": "7630b1c1ffbd0300c100885b89ff78c2d579a24c", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2017-12-12T12:36:31.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-10T14:27:07.000Z", "avg_line_length": 30.6885245902, "max_line_length": 89, "alphanum_fraction": 0.6549145299, "num_tokens": 582, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6224593312018546, "lm_q2_score": 0.5039061705290805, "lm_q1q2_score": 0.31366109789601915}}
{"text": "//-*****************************************************************************\n// Copyright 2015 Christopher Jon Horvath\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//     http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//-*****************************************************************************\n\n//-*****************************************************************************\n// The basic architecture of these Waves is based on the TweakWaves application\n// written by Chris Horvath for Tweak Films in 2001.  This, in turn, was based\n// on the SIGGRAPH papers and courses by Jerry Tessendorf, and by the paper\n// \"A Simple Fluid Solver based on the FTT\" by Jos Stam.\n//\n// The TMA, JONSWAP, and Pierson Moskowitz Wave Spectra, as well as the\n// directional spreading functions are formulated based on the descriptions\n// given in \"Ocean Waves: The Stochastic Approach\",\n// by Michel K. Ochi, published by Cambridge Ocean Technology Series, 1998,2005.\n//\n// This library is written as a working implementation of the paper:\n// Christopher J. Horvath. 2015.\n// Empirical directional wave spectra for computer graphics.\n// In Proceedings of the 2015 Symposium on Digital Production (DigiPro '15),\n// Los Angeles, Aug. 8, 2015, pp. 29-39.\n//-*****************************************************************************\n\n#include <EncinoWaves/All.h>\n\n#include <boost/program_options.hpp>\n\n#include <iostream>\n#include <stdio.h>\n#include <stdlib.h>\n\nnamespace ewav = EncinoWaves;\nnamespace po   = boost::program_options;\n\n//-*****************************************************************************\nvoid doTest(const ewav::Parametersf& i_params) {\n  ewav::InitialStatef istate(i_params);\n  int w = istate.HSpectralPos.width();\n  int h = istate.HSpectralPos.height();\n  int N = h;\n  std::cout << \"A: Computed initial state.\" << std::endl\n            << \"Size: \" << w << \" by \" << h << std::endl\n            << \"HspecPos: \" << istate.HSpectralPos[N / 4][N / 4] << std::endl\n            << \"HspecNeg: \" << istate.HSpectralNeg[N / 4][N / 4] << std::endl\n            << \"Omega: \" << istate.Omega[N / 4][N / 4] << std::endl;\n}\n\n//-*****************************************************************************\nint main(int argc, char* argv[]) {\n  ewav::Parametersf params;\n\n  int threads              = -1;\n  int dispersion           = 2;\n  int spectrum             = 2;\n  int directionalSpreading = 0;\n  int filter               = 0;\n  int random               = 0;\n  int seed                 = 54321;\n\n  po::options_description desc(\"Tweak Waves 2013 : Initial State Test\");\n  desc.add_options()\n\n    // clang-format off\n\n    ( \"help,h\", \"prints this help message\" )\n\n\n    ( \"threads\",\n      po::value<int>( &threads )\n      ->default_value( threads ),\n      \"Threads to use. Default of -1 means use all.\" )\n\n    ( \"resolution\",\n      po::value<int>( &params.resolutionPowerOfTwo )\n      ->default_value( params.resolutionPowerOfTwo ),\n      \"Power of Two of the sim resolution\" )\n\n    ( \"domain\",\n      po::value<float>( &params.domain )\n      ->default_value( params.domain ),\n      \"Size, in meters, of largest wave\" )\n\n    ( \"gravity\",\n      po::value<float>( &params.gravity )\n      ->default_value( params.gravity ),\n      \"Gravitational constant, in meters per second squared\" )\n\n    ( \"surfaceTension\",\n      po::value<float>( &params.surfaceTension )\n      ->default_value( params.surfaceTension ),\n      \"Surface tension constant, in Newtons per meter\" )\n\n    ( \"density\",\n      po::value<float>( &params.density )\n      ->default_value( params.density ),\n      \"Water density, in kilograms per meter cubed\" )\n\n    ( \"depth\",\n      po::value<float>( &params.depth )\n      ->default_value( params.depth ),\n      \"Average depth of the ocean, in meters\" )\n\n    ( \"windSpeed\",\n      po::value<float>( &params.windSpeed )\n      ->default_value( params.windSpeed ),\n      \"Average wind speed, in meters per second\" )\n\n    ( \"fetch\",\n      po::value<float>( &params.fetch )\n      ->default_value( params.fetch ),\n      \"Wind fetch, in KILOMETERS\" )\n\n    ( \"pinch\",\n      po::value<float>( &params.pinch )\n      ->default_value( params.pinch ),\n      \"Lateral displacement, normalized\" )\n\n    ( \"amplitudeGain\",\n      po::value<float>( &params.amplitudeGain )\n      ->default_value( params.amplitudeGain ),\n      \"Gain on the wave height\" )\n\n    ( \"dispersion\",\n      po::value<int>( &dispersion )\n      ->default_value( dispersion ),\n      \"Dispersion: 0 for Deep, 1 for Finite Depth, 2 for Capillary\" )\n\n    ( \"spectrum\",\n      po::value<int>( &spectrum )\n      ->default_value( spectrum ),\n      \"Spectrum: 0 for Pierson-Moskowitz, 1 for JONSWAP, 2 for TMA\" )\n\n    ( \"directionalSpreading\",\n      po::value<int>( &directionalSpreading )\n      ->default_value( directionalSpreading ),\n      \"Directional Spreading: 0 for Balanced Cos2 Theta, \"\n      \"1 for Mitsuyasu, 2 for Hasselmann, 3 for Donelan-Banner\" )\n\n    ( \"swell\",\n      po::value<float>( &params.directionalSpreading.swell )\n      ->default_value( params.directionalSpreading.swell ),\n      \"The mix between a wind-driven local sea and a swell caused by a \"\n      \"distant storm.\" )\n\n    ( \"filter\",\n      po::value<int>( &filter )\n      ->default_value( filter ),\n      \"Filter: 0 for nullptr, 1 for Smoothed Invertible Band-Pass\" )\n\n    ( \"filterSoftWidth\",\n      po::value<float>( &params.filter.softWidth )\n      ->default_value( params.filter.softWidth ),\n      \"Size in meters of the softness of wavelength filter falloff.\" )\n\n    ( \"filterSmall\",\n      po::value<float>( &params.filter.smallWavelength )\n      ->default_value( params.filter.smallWavelength ),\n      \"Size in meters of the smallest kept wavelengths.\" )\n\n    ( \"filterBig\",\n      po::value<float>( &params.filter.bigWavelength )\n      ->default_value( params.filter.bigWavelength ),\n      \"Size in meters of the biggest kept wavelengths.\" )\n\n    ( \"filterMin\",\n      po::value<float>( &params.filter.min )\n      ->default_value( params.filter.min ),\n      \"Minimum value of filter.\" )\n\n    ( \"filterInvert\", \"Invert the filter\" )\n\n    ( \"random\",\n      po::value<int>( &random )\n      ->default_value( random ),\n      \"Random Distribution: 0 for Normal, 1 for Log-Normal\" )\n\n    ( \"seed\",\n      po::value<int>( &params.random.seed )\n      ->default_value( params.random.seed ),\n      \"Random Seed\" )\n\n    ;\n\n  // clang-format on\n\n  po::variables_map vm;\n  po::store(po::command_line_parser(argc, argv).options(desc).run(), vm);\n  po::notify(vm);\n\n  //-*************************************************************************\n  if (vm.count(\"help\")) {\n    std::cout << desc << std::endl;\n    return 0;\n  }\n\n  if (vm.count(\"filterInvert\")) {\n    params.filter.invert = true;\n  }\n\n  params.dispersion.type = (ewav::DispersionType)dispersion;\n  params.spectrum.type = (ewav::SpectrumType)spectrum;\n  params.directionalSpreading.type =\n    (ewav::DirectionalSpreadingType)directionalSpreading;\n  params.filter.type = (ewav::FilterType)filter;\n  params.random.type = (ewav::RandomType)random;\n  params.random.seed = seed;\n\n  doTest(params);\n\n  return 0;\n}", "meta": {"hexsha": "952f72a5f291d284689cc76cbb4fb3c695e63d66", "size": 7551, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/EncinoWaves/Tests/test_InitialState.cpp", "max_stars_repo_name": "NTForked/EncinoWaves", "max_stars_repo_head_hexsha": "b7db46962e8405e2c7fb91b3eb7fda03d78489d4", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 64.0, "max_stars_repo_stars_event_min_datetime": "2015-08-08T08:53:03.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-09T15:45:21.000Z", "max_issues_repo_path": "src/EncinoWaves/Tests/test_InitialState.cpp", "max_issues_repo_name": "NTForked/EncinoWaves", "max_issues_repo_head_hexsha": "b7db46962e8405e2c7fb91b3eb7fda03d78489d4", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-10-10T18:50:26.000Z", "max_issues_repo_issues_event_max_datetime": "2018-10-10T18:50:26.000Z", "max_forks_repo_path": "src/EncinoWaves/Tests/test_InitialState.cpp", "max_forks_repo_name": "NTForked/EncinoWaves", "max_forks_repo_head_hexsha": "b7db46962e8405e2c7fb91b3eb7fda03d78489d4", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 15.0, "max_forks_repo_forks_event_min_datetime": "2015-08-09T02:40:15.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-11T19:39:29.000Z", "avg_line_length": 34.0135135135, "max_line_length": 80, "alphanum_fraction": 0.5944907959, "num_tokens": 1842, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6688802603710086, "lm_q2_score": 0.46879062662624377, "lm_q1q2_score": 0.3135647963972502}}
{"text": "#include <chrono>\n#include <ctime>\n#include <iostream>\n#include <fstream>\n#include <vector>\n#include <Eigen/Geometry>\nusing namespace std;\n\n//default input values\nstring inputFile = \"trajBig.pdb\";\nstring outputFile = \"output.txt\";\nint spheresAllocationFrame = 0;\ndouble RMSDThreshPercent = 50;\n\n//additional parameters\ndouble sphereRadius = 8;\n\nint SPHERES;\nint ATOMS;\nint FRAMES;\ndouble highestSize;\n\n//Atoms[<frame>][<atom>][<coordinate>]\nvector<vector<vector<double>>> A;\n\n//RMSDValue[<frame>][<sphere>]\nvector<vector<double>> C;\n\n//Maps sphere to CA; CAAtomNumber[<sphere>]\nvector<int> sphereCA;\n\n//Numer of atoms in [<sphere>]\nvector<int> sphereSize;\n\nstruct sphere\n{\n    int frame;\n    int index;\n    double RMSD;\n};\n\nvector<vector<int>> sphereAtoms;\nvector<vector<int>> atomToSphere;\nvector<vector<double>> highestRMSD;\nvector<sphere> highestRMSDbase;\n\n\n\nbool operator <(const sphere& lhs, const sphere& rhs)\n{\n    return lhs.RMSD < rhs.RMSD;\n}\n\nvector<string> result;\n\n\n//--------------------------------------------------\n\n//reading data from input pdb file.\nvoid readFile(string filename)\n{\n    string line;\n    ifstream myfile(filename);\n    if (myfile.is_open())\n    {\n        int frame = 0;\n        int atom;\n        SPHERES = 0;\n        FRAMES = 0;\n        ATOMS = 0;\n        A = {};\n        sphereCA = {};\n        sphereSize = {};\n        while (getline(myfile, line))\n        {\n            if (line[0] == 'M')\n            {\n                frame = stoi(line.substr(9, 5));\n                frame--;\n                A.push_back({});\n                C.push_back({});\n                FRAMES++;\n            }\n            else if (line[0] == 'A')\n            {\n                atom = stoi(line.substr(6, 5));\n                atom--;\n                A[frame].push_back({});\n                A[frame][atom].push_back(stod(line.substr(30, 8)));\n                A[frame][atom].push_back(stod(line.substr(38, 8)));\n                A[frame][atom].push_back(stod(line.substr(46, 8)));\n                if (frame == 0)\n                {\n                    ATOMS++;\n                    if (line[14] == 'A' and line[13] == 'C')\n                    {\n                        sphereCA.push_back(atom);\n                        sphereSize.push_back(0);\n                        SPHERES++;\n                    }\n                }\n            }\n        }\n        myfile.close();\n    }\n    else \n    {\n        cout << \"Nie odnaleziono pliku!\" << endl;\n    }\n}\n\n//calculating distance between 2 atoms, used when allocating atoms to spheres.\ndouble atomsDistanceCalc(int atom1, int atom2)\n{\n    double result = sqrt(pow(A[spheresAllocationFrame][atom1][0] - A[spheresAllocationFrame][atom2][0], 2) +\n        pow(A[spheresAllocationFrame][atom1][1] - A[spheresAllocationFrame][atom2][1], 2) +\n        pow(A[spheresAllocationFrame][atom1][2] - A[spheresAllocationFrame][atom2][2], 2));\n    return result;\n}\n\n//allocating atoms into spheres, based on sphereRadius\nvoid atomsAllocation()\n{\n    auto timestamp = std::chrono::system_clock::now();\n    std::time_t timestamp_print = std::chrono::system_clock::to_time_t(timestamp);\n    int checkpoint = 0;\n    sphereAtoms = {};\n    atomToSphere = {};\n    for (int i = 0; i < SPHERES; i++)\n    {\n        sphereAtoms.push_back({});\n    }\n    for (int i = 0; i < ATOMS; i++)\n    {\n        atomToSphere.push_back({});\n        for (int j = 0; j < SPHERES; j++)\n        {\n            if (atomsDistanceCalc(i, sphereCA[j]) <= sphereRadius)\n            {\n                atomToSphere[i].push_back(j);\n                sphereAtoms[j].push_back(i);\n                sphereSize[j]++;\n            }\n        }\n        if ((i - checkpoint) >= 0.1 * ATOMS)\n        {\n            checkpoint = i;\n            timestamp = std::chrono::system_clock::now();\n            timestamp_print = std::chrono::system_clock::to_time_t(timestamp);\n            cout << \"[RMSD] Atom number \" << i + 1 << \" of \" << ATOMS << \" allocated to spheres at \" << std::ctime(&timestamp_print) << endl;\n        }\n    }\n}\n\n// Find3DAffineTransform is from oleg-alexandrov repository on github, available here https://github.com/oleg-alexandrov/projects/blob/master/eigen/Kabsch.cpp [as of 27.01.2022]\n// Given two sets of 3D points, find the rotation + translation + scale\n// which best maps the first set to the second.\n// Source: http://en.wikipedia.org/wiki/Kabsch_algorithm\n\n// The input 3D points are stored as columns.\nEigen::Affine3d Find3DAffineTransform(Eigen::Matrix3Xd in, Eigen::Matrix3Xd out) {\n\n    // Default output\n    Eigen::Affine3d A;\n    A.linear() = Eigen::Matrix3d::Identity(3, 3);\n    A.translation() = Eigen::Vector3d::Zero();\n\n    if (in.cols() != out.cols())\n        throw \"Find3DAffineTransform(): input data mis-match\";\n\n    // First find the scale, by finding the ratio of sums of some distances,\n    // then bring the datasets to the same scale.\n    double dist_in = 0, dist_out = 0;\n    for (int col = 0; col < in.cols() - 1; col++) {\n        dist_in += (in.col(col + 1) - in.col(col)).norm();\n        dist_out += (out.col(col + 1) - out.col(col)).norm();\n    }\n    if (dist_in <= 0 || dist_out <= 0)\n        return A;\n    double scale = dist_out / dist_in;\n    out /= scale;\n\n    // Find the centroids then shift to the origin\n    Eigen::Vector3d in_ctr = Eigen::Vector3d::Zero();\n    Eigen::Vector3d out_ctr = Eigen::Vector3d::Zero();\n    for (int col = 0; col < in.cols(); col++) {\n        in_ctr += in.col(col);\n        out_ctr += out.col(col);\n    }\n    in_ctr /= in.cols();\n    out_ctr /= out.cols();\n    for (int col = 0; col < in.cols(); col++) {\n        in.col(col) -= in_ctr;\n        out.col(col) -= out_ctr;\n    }\n\n    // SVD\n    Eigen::MatrixXd Cov = in * out.transpose();\n    Eigen::JacobiSVD<Eigen::MatrixXd> svd(Cov, Eigen::ComputeThinU | Eigen::ComputeThinV);\n\n    // Find the rotation\n    double d = (svd.matrixV() * svd.matrixU().transpose()).determinant();\n    if (d > 0)\n        d = 1.0;\n    else\n        d = -1.0;\n    Eigen::Matrix3d I = Eigen::Matrix3d::Identity(3, 3);\n    I(2, 2) = d;\n    Eigen::Matrix3d R = svd.matrixV() * I * svd.matrixU().transpose();\n\n    // The final transform\n    A.linear() = scale * R;\n    A.translation() = scale * (out_ctr - R * in_ctr);\n\n    return A;\n}\n\n//superpose changes vector of atoms frame 2 to map atoms from frame 1 in the way to minimise RMSD between both frames\nvoid superpose(const vector<vector<double>>& frame1, vector<vector<double>>& frame2)\n{\n    int atomsInSphere = frame1.size();\n    Eigen::Matrix3Xd S1(3, atomsInSphere);\n    Eigen::Matrix3Xd S2(3, atomsInSphere);\n    for (int j = 0; j < atomsInSphere; j++)\n    {\n        for (int k = 0; k < 3; k++)\n        {\n            S1(k, j) = frame1[j][k];\n            S2(k, j) = frame2[j][k];\n        }\n    }\n    Eigen::Affine3d RT = Find3DAffineTransform(S2, S1);\n    S2 = RT.linear() * S2;\n    for (int j = 0; j < atomsInSphere; j++)\n    {\n        S2.block<3, 1>(0, j) += RT.translation();\n    }\n    for (int j = 0; j < atomsInSphere; j++)\n    {\n        for (int k = 0; k < 3; k++)\n        {\n            frame2[j][k] = S2(k, j);\n        }\n    }\n}\n\n//initializing vector for RMSD values\nvoid initializeC()\n{\n    C = {};\n    for (int i = 0; i < FRAMES; i++)\n    {\n        C.push_back({});\n        for (int j = 0; j < SPHERES; j++)\n            C[i].push_back(0);\n    }\n}\n\n//calculating RMSD on spheres, on adjacent frames\nvoid calculateRMSDSuperpose()\n{\n    initializeC();\n    vector<vector<vector<double>>> sphereMatrix;\n    vector<vector<double>> tempMatrix;\n    double tempRMSD;\n    auto timestamp = std::chrono::system_clock::now();\n    std::time_t timestamp_print = std::chrono::system_clock::to_time_t(timestamp);\n    int checkpoint = 0;\n    for (int s = 0; s < SPHERES; s++)\n    {\n        int atomsInSphere = sphereAtoms[s].size();\n        sphereMatrix = {};\n        for (int i = 0; i < FRAMES; i++)\n        {\n            sphereMatrix.push_back({});\n            for (int j = 0; j < atomsInSphere; j++)\n            {\n                sphereMatrix[i].push_back(A[i][sphereAtoms[s][j]]);\n            }\n            if (i > 0)\n            {\n                tempMatrix = sphereMatrix[i];\n                superpose(sphereMatrix[i - 1], tempMatrix);\n                for (int j = 0; j < atomsInSphere; j++)\n                {\n                    for (int k = 0; k < 3; k++)\n                    {\n                        tempRMSD = pow(tempMatrix[j][k] - sphereMatrix[i - 1][j][k], 2);\n                        C[i - 1][s] += tempRMSD;\n                    }\n                }\n                C[i - 1][s] /= ((long)atomsInSphere * (long)3);\n                C[i - 1][s] = sqrt(C[i - 1][s]);\n            }\n        }\n        if ((s - checkpoint) >= 0.1 * SPHERES)\n        {\n            checkpoint = s;\n            timestamp = std::chrono::system_clock::now();\n            timestamp_print = std::chrono::system_clock::to_time_t(timestamp);\n            cout << \"[RMSD] RMSD calculated for \" << s + 1 << \" of \" << SPHERES << \" spheres at \" << std::ctime(&timestamp_print) << endl;\n        }\n    }\n}\n\n//initializing vector for storing information about spheres with highest RMSD\nvoid initializeHighestRMSD()\n{\n    highestRMSD = {};\n    highestSize = (double)SPHERES / 100;\n    highestSize *= (long)(FRAMES - 1);\n    highestSize *= RMSDThreshPercent;\n    for (int i = 0; i < highestSize; i++)\n    {\n        highestRMSD.push_back({});\n        for (int j = 0; j < 3; j++)\n            highestRMSD[i].push_back(-1);\n    }\n}\n\n//choosing frames and spheres with highest RMSD, they will be colored later\nvoid chooseHighestRMSD()\n{\n    initializeHighestRMSD();\n    for (int i = 0; i < FRAMES - 1; i++)\n    {\n        for (int j = 0; j < SPHERES; j++)\n        {\n            for (unsigned int k = 0; k < highestRMSD.size(); k++)\n            {\n                if (C[i][j] > highestRMSD[k][2])\n                {\n                    for (int l = highestRMSD.size() - 1; l > k; l--)\n                    {\n                        for (int m = 0; m < 3; m++)\n                        {\n                            highestRMSD[l][m] = highestRMSD[l - 1][m];\n                        }\n                    }\n                    highestRMSD[k][0] = i;\n                    highestRMSD[k][1] = j;\n                    highestRMSD[k][2] = C[i][j];\n                    break;\n                }\n            }\n        }\n    }\n}\n\n//choosing frames and spheres with highest RMSD, they will be colored later\nvoid chooseHighestRMSDquick()\n{\n    auto timestamp = std::chrono::system_clock::now();\n    std::time_t timestamp_print = std::chrono::system_clock::to_time_t(timestamp);\n    initializeHighestRMSD();\n    int counter = 0;\n    for (int i = 0; i < FRAMES - 1; i++)\n    {\n        for (int j = 0; j < SPHERES; j++)\n        {\n            highestRMSDbase.push_back(sphere());\n            highestRMSDbase[counter].frame = i;\n            highestRMSDbase[counter].index = j;\n            highestRMSDbase[counter].RMSD = C[i][j];\n            counter++;\n        }\n    }\n    timestamp = std::chrono::system_clock::now();\n    timestamp_print = std::chrono::system_clock::to_time_t(timestamp);\n    cout << \"[RMSD] RMSD started being sorted at \" << std::ctime(&timestamp_print) << endl;\n    sort(highestRMSDbase.begin(), highestRMSDbase.end());\n    timestamp = std::chrono::system_clock::now();\n    timestamp_print = std::chrono::system_clock::to_time_t(timestamp);\n    cout << \"[RMSD] RMSD sorted at \" << std::ctime(&timestamp_print) << endl;\n    for (unsigned int k = 0; k < highestRMSD.size(); k++)\n    {\n        highestRMSD[k][0] = highestRMSDbase[k].frame;\n        highestRMSD[k][1] = highestRMSDbase[k].index;\n        highestRMSD[k][2] = highestRMSDbase[k].RMSD;\n    }\n}\n\n//calculates result variable content, basen on highestRMSD\nvoid calculateResult()\n{\n    result = {};\n    int numberOfSpheresToColor = highestRMSD.size();\n    vector<vector<int>> resultSpheres;\n    for (int i = 0; i < FRAMES - 1; i++)\n    {\n        resultSpheres.push_back({});\n    }\n    for (int i = 0; i < numberOfSpheresToColor; i++)\n    {\n        resultSpheres[highestRMSD[i][0]].push_back(highestRMSD[i][1]);\n    }\n    string subResult;\n    for (int i = 0; i < FRAMES - 1; i++)\n    {\n        subResult = \"\";\n        for (int j = 0; j < numberOfSpheresToColor; j++)\n        {\n            if (highestRMSD[j][0] == i)\n            {\n                stringstream ss;\n                string s;\n                ss << sphereCA[highestRMSD[j][1]];\n                ss >> s;\n                subResult += s + \" \";\n            }\n        }\n        result.push_back(subResult);\n    }\n}\n\n//saving results to an output file\nvoid saveToFile(string filename)\n{\n    ofstream myfile(filename);\n    if (myfile.is_open())\n    {\n        for (int i = 0; i < FRAMES - 1; i++)\n        {\n            if (!result[i].empty())\n            {\n                myfile << i << ' ' << result[i] << endl;\n            }\n        }\n        myfile.close();\n    }\n}\n\n//debug function for checking superpose results\nvoid makePDB(string filename)\n{\n    vector<vector<vector<double>>> sphereMatrix;\n    int atomsInSphere = sphereAtoms[0].size();\n    sphereMatrix = {};\n    for (int i = 0; i < 2; i++)\n    {\n        sphereMatrix.push_back({});\n        for (int j = 0; j < atomsInSphere; j++)\n        {\n            sphereMatrix[i].push_back(A[i][sphereAtoms[0][j]]);\n        }\n        if (i > 0)\n        {\n            superpose(sphereMatrix[i - 1], sphereMatrix[i]);\n        }\n    }\n    string line;\n    ifstream myfilein(filename);\n    filename += \"out\";\n    ofstream myfileout(\"testBase.pdb\");\n    ofstream myfilesuper(\"testSuperpose.pdb\");\n    int counter = 0;\n    if (myfilein.is_open() && myfileout.is_open())\n    {\n        int frame = 0;\n        int atom;\n        while (getline(myfilein, line))\n        {\n            if (line[0] == 'M')\n            {\n                myfileout << line << endl;\n                myfilesuper << line << endl;\n            }\n            \n            if (line[0] == 'E')\n            {\n                myfileout << line << endl;\n                myfilesuper << line << endl;\n                frame++;\n                if (frame > 1)\n                {\n                    break;\n                }\n            }\n            if (line[0] == 'A')\n            {\n                atom = stoi(line.substr(6, 5));\n                atom--;\n                for (unsigned int i = 0; i < sphereAtoms[0].size(); i++)\n                {\n                    if (sphereAtoms[0][i] == atom)\n                    {\n                        myfileout << line << endl;\n                        if (frame == 1)\n                        {                            \n                            line.replace(32, 6, to_string(sphereMatrix[1][counter][0]), 0, 6);\n                            line.replace(40, 6, to_string(sphereMatrix[1][counter][1]), 0, 6);\n                            line.replace(48, 6, to_string(sphereMatrix[1][counter][2]), 0, 6);\n                            myfilesuper << line << endl;\n                            counter++;\n                        }\n                        else\n                        {\n                            myfilesuper << line << endl;\n                        }\n                    }\n                }\n            }\n        }\n        myfilein.close();\n        myfileout.close();\n        myfilesuper.close();\n    }\n}\n\nint main(int argc, char* argv[])\n{\n    auto start = chrono::high_resolution_clock::now();\n    if (argc == 5)\n    {\n        inputFile = string(argv[1]);\n        outputFile = string(argv[2]);\n        spheresAllocationFrame = stoi(argv[3]) - 1;\n        RMSDThreshPercent = stod(argv[4]);\n    }\n    readFile(inputFile);\n    if (spheresAllocationFrame < 0)\n    {\n        spheresAllocationFrame = 1;\n    }\n    else if (spheresAllocationFrame >= FRAMES)\n    {\n        spheresAllocationFrame = FRAMES - 1;\n    }\n    auto timestamp = std::chrono::system_clock::now();\n    std::time_t timestamp_print = std::chrono::system_clock::to_time_t(timestamp);\n    cout << \"[RMSD] Input file: \" << inputFile << \" loaded at \" << std::ctime(&timestamp_print) << endl;\n    atomsAllocation();\n    timestamp = std::chrono::system_clock::now();\n    timestamp_print = std::chrono::system_clock::to_time_t(timestamp);\n    cout << \"[RMSD] Atoms allocated to spheres at \" << std::ctime(&timestamp_print) << endl;\n    calculateRMSDSuperpose();\n    chooseHighestRMSDquick();\n    calculateResult();\n    saveToFile(outputFile);\n    timestamp = std::chrono::system_clock::now();\n    timestamp_print = std::chrono::system_clock::to_time_t(timestamp);\n    cout << \"[RMSD] Output file: \" << outputFile << \" saved at \" << std::ctime(&timestamp_print) << endl;\n    //makePDB(inputFile);\n    auto stop = chrono::high_resolution_clock::now();\n    chrono::duration<double> elapsed = stop - start;\n    timestamp = std::chrono::system_clock::now();\n    timestamp_print = std::chrono::system_clock::to_time_t(timestamp);\n    cout << \"[RMSD] Computation time: \" << elapsed.count() << \"s, ended at: \" << std::ctime(&timestamp_print) << endl;\n}\n", "meta": {"hexsha": "4d35ffcbe1339ca286299086cd48014dbf5af090", "size": 16970, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "gromacs_api/app/src/rmsd.cpp", "max_stars_repo_name": "KrzysztofMularski/ProProtein", "max_stars_repo_head_hexsha": "d86bbe68051b139f6f114c2505e4e6ee1462fce3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "gromacs_api/app/src/rmsd.cpp", "max_issues_repo_name": "KrzysztofMularski/ProProtein", "max_issues_repo_head_hexsha": "d86bbe68051b139f6f114c2505e4e6ee1462fce3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "gromacs_api/app/src/rmsd.cpp", "max_forks_repo_name": "KrzysztofMularski/ProProtein", "max_forks_repo_head_hexsha": "d86bbe68051b139f6f114c2505e4e6ee1462fce3", "max_forks_repo_licenses": ["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.8545454545, "max_line_length": 177, "alphanum_fraction": 0.5183264585, "num_tokens": 4469, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.668880247169804, "lm_q2_score": 0.4687906266262437, "lm_q1q2_score": 0.3135647902086492}}
{"text": "#include \"ocean_model_interfaces/fvcom/FVCOMStructure.h\"\n#include \"ocean_model_interfaces/fvcom/FVCOM.h\"\n\n#include <netcdf>\n#include <memory>\n#include <cmath>\n#include <limits>\n#include <algorithm>\n#include <iterator>\n\n#include <boost/filesystem.hpp>\nnamespace fs = boost::filesystem;\n\nusing namespace ocean_model_interfaces;\n\nFVCOMStructure::FVCOMStructure() {}\n\nFVCOMStructure::FVCOMStructure(const std::string filename, int xChunkSize, int yChunkSize, int siglayChunkSize, int timeChunkSize) :\n    xChunkSize(xChunkSize),\n    yChunkSize(yChunkSize),\n    siglayChunkSize(siglayChunkSize),\n    timeChunkSize(timeChunkSize),\n    lastContainingTriangle(0)\n{\n    loadStructureData(filename);\n\n    splitIntoChunks();\n}\n\nFVCOMStructure::Plane::Plane() {}\n\nFVCOMStructure::Plane::Plane(FVCOMStructure::Point& p0, FVCOMStructure::Point& p1, FVCOMStructure::Point& p2)\n{\n    double ab[3];\n    double ac[3];\n\n    ab[0] = p1.x - p0.x;\n    ab[1] = p1.y - p0.y;\n    ab[2] = p1.z - p0.z;\n\n    ac[0] = p2.x - p0.x;\n    ac[1] = p2.y - p0.y;\n    ac[2] = p2.z - p0.z;\n\n    a = (ab[1] * ac[2]) - (ab[2] * ac[1]);\n    b = (ab[2] * ac[0]) - (ab[0] * ac[2]);\n    c = (ab[0] * ac[1]) - (ab[1] * ac[0]);\n\n    double magnitude = sqrt(a * a +  b * b +  c * c);\n    a /= magnitude;\n    b /= magnitude;\n    c /= magnitude;\n\n    d = -(p0.x * a + p0.y * b + p0.z * c);\n}\n\ndouble FVCOMStructure::Plane::getHeight(Point& interpolatePoint)\n{\n    return (-d - a * interpolatePoint.x - b * interpolatePoint.y) / c;\n}\n\nstd::vector<std::string> FVCOMStructure::traverseDataFiles(const std::string filename)\n{\n    std::vector<std::string> filenames;\n    fs::path p1 = filename;\n    if(fs::is_directory(p1))\n    {\n        for(auto& p: fs::directory_iterator(p1))\n        {\n            if(!fs::is_directory(p))\n            {\n                filenames.push_back(p.path().string());\n            }\n        }\n    }\n    else\n    {\n        filenames.push_back(filename);\n    }\n    return filenames;\n}\n\nvoid FVCOMStructure::loadStructureData(const std::string directory)\n{\n    unsigned int timeDim = 0;\n    std::vector<std::string> filenames = traverseDataFiles(directory);\n\n    //Set start times and time dimensions from files\n    for(auto &filename : filenames)\n    {\n        netCDF::NcFile dataFile(filename, netCDF::NcFile::read);\n        timeDim += dataFile.getDim(\"time\").getSize();\n        \n        std::vector<float> tempTimes;\n        tempTimes.resize(dataFile.getDim(\"time\").getSize());\n        netCDF::NcVar timeVar = dataFile.getVar(\"time\");\n        timeVar.getVar(tempTimes.data());\n        ModelFile modelFile;\n        modelFile.filename = filename;\n        modelFile.startTime = tempTimes[0];\n        modelFile.timeDim = dataFile.getDim(\"time\").getSize();\n        modelFiles.push_back(modelFile);\n    }\n    \n    //sort filenames based on start ties\n    std::sort(modelFiles.begin(), modelFiles.end());\n\n    //load time variables into one vector\n    times.resize(timeDim);\n    unsigned int currentIndex = 0;\n    for(auto &modelFile : modelFiles)\n    {\n        netCDF::NcFile dataFile(modelFile.filename, netCDF::NcFile::read);\n        netCDF::NcVar timeVar = dataFile.getVar(\"time\");\n\n        //Set the start time index for this file\n        modelFile.startTimeIndex = currentIndex;\n\n        //Load times from this file\n        timeVar.getVar(times.data() + currentIndex);\n\n        //move current index for next files\n        currentIndex += dataFile.getDim(\"time\").getSize();\n    }\n    netCDF::NcFile dataFile(modelFiles[0].filename, netCDF::NcFile::read);\n\n    //Get dimensions of structure elements\n    unsigned int nodeDim = dataFile.getDim(\"node\").getSize();\n    unsigned int neleDim = dataFile.getDim(\"nele\").getSize();\n    siglayDim = dataFile.getDim(\"siglay\").getSize();\n\n    //Load all variables for the structure of the model\n    netCDF::NcVar xVar = dataFile.getVar(\"x\");\n    netCDF::NcVar yVar = dataFile.getVar(\"y\");\n    netCDF::NcVar xcVar = dataFile.getVar(\"xc\");\n    netCDF::NcVar ycVar = dataFile.getVar(\"yc\");\n    netCDF::NcVar nvVar = dataFile.getVar(\"nv\");\n    netCDF::NcVar hVar = dataFile.getVar(\"h\");\n    netCDF::NcVar siglayVar = dataFile.getVar(\"siglay\");\n    netCDF::NcVar centerSiglayVar = dataFile.getVar(\"siglay_center\");\n\n    //Load in as floats as that is what they are in the files\n    //but they will be converted to doubles to maintain precision during calculations\n    std::vector<float> nodeX;\n    std::vector<float> nodeY;\n    std::vector<float> nodeH;\n\n    std::vector<float> triangleX;\n    std::vector<float> triangleY;\n\n    nodeX.resize(nodeDim);\n    nodeY.resize(nodeDim);\n    triangleX.resize(neleDim);\n    triangleY.resize(neleDim);\n    nodeH.resize(nodeDim);\n\n    //Resize siglay 2d vectors\n    nodeSiglay.resize(nodeDim);\n\n    for(unsigned int i = 0; i < nodeSiglay.size(); i++)\n    {\n        nodeSiglay[i].resize(siglayDim);\n    }\n\n    //resize for multidimensional array\n    triangleToNodes.resize(neleDim);\n    \n    for(unsigned int i = 0; i < neleDim; i++)\n    {\n        triangleToNodes[i].resize(3);\n    }\n\n    //Assign all arrays for the structure variables\n    xVar.getVar(nodeX.data());\n    yVar.getVar(nodeY.data());\n    xcVar.getVar(triangleX.data());\n    ycVar.getVar(triangleY.data());\n    hVar.getVar(nodeH.data());\n\n    //load nvVar into a multidimensional vector\n    for(unsigned int i = 0; i < neleDim; i++)\n    {\n        std::vector<size_t> start = {0, i};\n        std::vector<size_t> count = {3, 1};\n        nvVar.getVar(start, count, triangleToNodes[i].data());\n    }\n\n    //load node siglay into a multidimensional vector\n    for(unsigned int i = 0; i < nodeSiglay.size(); i++)\n    {\n        std::vector<size_t> start = {0, i};\n        std::vector<size_t> count = {siglayDim, 1};\n        siglayVar.getVar(start, count, nodeSiglay[i].data());\n    }\n\n    //Convert to use point struct\n    nodes.resize(nodeDim);\n    triangles.resize(neleDim);\n    for(unsigned int i = 0; i < nodeDim; i++)\n    {\n        nodes[i].x = nodeX[i];\n        nodes[i].y = nodeY[i];\n        nodes[i].z = nodeH[i];\n    }\n\n    for(unsigned int i = 0; i < neleDim; i++)\n    {\n        triangles[i].x = triangleX[i];\n        triangles[i].y = triangleY[i];\n        triangles[i].z = std::numeric_limits<double>::quiet_NaN();\n        //Height data is not loaded for triangles so we set it to NaN.\n    }\n\n\n    //The nv variable from the netCDF indexes starting at 1\n    //Convert this to 0 by subtracting 1 from every value\n    for(unsigned int i = 0; i < neleDim; i++)\n    {\n        for(unsigned int j = 0; j < 3; j++)\n        {\n            triangleToNodes[i][j]--;\n        }\n    }\n\n    //Pre Processes model to get node to triangle conversion\n    nodeToTriangles.resize(nodeDim);\n\n    for(unsigned int i = 0; i < neleDim; i++)\n    {\n        for(unsigned int j = 0; j < 3; j++)\n        {\n            int triangle = i;\n            int node = triangleToNodes[i][j];\n\n            nodeToTriangles[node].push_back(triangle);\n        }\n    }\n\n}\n\nvoid FVCOMStructure::splitIntoChunks()\n{\n    getModelExtent();\n\n    siglayDimChunks = std::ceil(siglayDim / (double)siglayChunkSize);\n    timeDimChunks = std::ceil(times.size() / (double)timeChunkSize);\n    yDimChunks = std::ceil((maxY - minY) / (double)yChunkSize);\n    xDimChunks = std::ceil((maxX - minX) / (double)xChunkSize);\n\n    nodesInChunk.resize(xDimChunks * yDimChunks);\n    trianglesInChunk.resize(xDimChunks * yDimChunks);\n    for(unsigned int i = 0; i < nodes.size(); i++)\n    {\n        FVCOMStructure::ChunkInfo chunk = getChunkForNode(i, 0, 0);\n\n        //This does not contain the siglay or time dimensions as the\n        //node locations do not change with depth or time.\n        int chunkId = chunk.yChunk + (chunk.xChunk * yDimChunks);\n\n        nodesInChunk[chunkId].push_back(i);\n    }\n\n    for(unsigned int i = 0; i < triangles.size(); i++)\n    {\n        FVCOMStructure::ChunkInfo chunk = getChunkForTriangle(i, 0, 0);\n\n        //This does not contain the siglay or time dimensions as the\n        //node locations do not change with depth or time.\n        int chunkId = chunk.yChunk + (chunk.xChunk * yDimChunks);\n\n        trianglesInChunk[chunkId].push_back(i);\n    }\n}\n\nvoid FVCOMStructure::getModelExtent()\n{\n    for(unsigned int i = 0; i < nodes.size(); i++)\n    {\n        Point& node = nodes[i];\n        \n        if(node.x > maxX)\n        {\n            maxX = node.x;\n        }\n\n        if(node.x < minX)\n        {\n            minX = node.x;\n        }\n\n        if(node.y > maxY)\n        {\n            maxY = node.y;\n        }\n\n        if(node.y < minY)\n        {\n            minY = node.y;\n        }\n    }\n}\n\nbool FVCOMStructure::pointInTriangle(Point testPoint, int triangle) const\n{\n    int p0Index = triangleToNodes[triangle][0];\n    int p1Index = triangleToNodes[triangle][1];\n    int p2Index = triangleToNodes[triangle][2];\n\n    Point p0 = nodes[p0Index];\n    Point p1 = nodes[p1Index];\n    Point p2 = nodes[p2Index];\n\n    //Calculate barycentric coordinates\n    double alpha = ((p1.y - p2.y)*(testPoint.x - p2.x) + (p2.x - p1.x)*(testPoint.y - p2.y)) /\n        ((p1.y - p2.y)*(p0.x - p2.x) + (p2.x - p1.x)*(p0.y - p2.y));\n\n    double beta = ((p2.y - p0.y)*(testPoint.x - p2.x) + (p0.x - p2.x)*(testPoint.y - p2.y)) /\n           ((p1.y - p2.y)*(p0.x - p2.x) + (p2.x - p1.x)*(p0.y - p2.y));\n\n    double gamma = 1.0 - alpha - beta;\n\n    //if all coordinates are none negative then the point is in the triangle\n    return alpha >= 0 && beta >= 0 && gamma >= 0;\n}\n\nint FVCOMStructure::getContainingTriangle(Point testPoint, int closestNode)\n{\n    if(pointInTriangle(testPoint, lastContainingTriangle))\n    {\n        return lastContainingTriangle;\n    }\n\n    //Search all triangles that are connected to the closest node\n    for(unsigned int i = 0; i < nodeToTriangles[closestNode].size(); i++)\n    {\n        //return the triangle for which the point is inside\n        if(pointInTriangle(testPoint, nodeToTriangles[closestNode][i]))\n        {\n            lastContainingTriangle = nodeToTriangles[closestNode][i];\n            return nodeToTriangles[closestNode][i];\n        }\n    }\n\n    //if the point is not inside any of those triangles search all the triangles\n    for(unsigned int i = 0; i < triangles.size(); i++)\n    {\n        if(pointInTriangle(testPoint, i))\n        {\n            lastContainingTriangle = i;\n            return i;\n        }\n    }\n\n\n    throw std::out_of_range(\"FVCOM request outside of model extent\");\n}\n\nint FVCOMStructure::getContainingTriangle(Point testPoint)\n{\n    if(pointInTriangle(testPoint, lastContainingTriangle))\n    {\n        return lastContainingTriangle;\n    }\n\n    //Get the closest node to start the search for the containing triangle\n    int closestNode = getClosestNode(testPoint);\n\n    return getContainingTriangle(testPoint, closestNode);\n}\n\nconst std::vector<int>& FVCOMStructure::getNodesInTriangle(int triangle) const\n{\n    return triangleToNodes[triangle];\n}\n\nconst std::vector<FVCOMStructure::ModelFile> FVCOMStructure::getModelFiles() const\n{\n    return modelFiles;\n}\n\nint FVCOMStructure::getClosestNode(Point testPoint) const\n{\n    //Checks distance between testPoint and every node, this is slow and will probably need to be improved\n    double closestDistance = std::numeric_limits<double>::max();\n    int node = -1;\n    for(unsigned int i = 0; i < nodes.size(); i++)\n    {\n\n        if(distanceSquared(testPoint, nodes[i]) < closestDistance)\n        {\n            closestDistance = distanceSquared(testPoint, nodes[i]);\n            node = i;\n        }\n    }\n\n    return node;\n}\n\n\nint FVCOMStructure::getClosestTime(double time) const\n{\n    auto lower = std::lower_bound(times.begin(), times.end(), time);\n\n    int index1 = std::distance(times.begin(), lower);\n    int index2 = index1 - 1;\n\n\n    if(std::abs(times[index1] - time) > std::abs(times[index2] - time))\n    {\n        return index2;\n    }\n    else\n    {\n        return index1;\n    }\n\n}\n\nint FVCOMStructure::getPreviousTimeIndex(double time) const\n{\n    auto lower = std::lower_bound(times.begin(), times.end(), time);\n    int index = std::distance(times.begin(), lower);\n\n    if(times[index] == time)\n     {\n         return index;\n    }\n\n    return index - 1;\n}\n\nfloat FVCOMStructure::getTime(int timeIndex) const\n{\n    return times[timeIndex];\n}\n\nFVCOMStructure::Plane FVCOMStructure::getTrianglePlane(int triangle) const\n{\n    const std::vector<int>& surroundingNodes = triangleToNodes[triangle];\n\n    FVCOMStructure::Point p0 = getNodePointWithH(surroundingNodes[0]);\n    FVCOMStructure::Point p1 = getNodePointWithH(surroundingNodes[1]);\n    FVCOMStructure::Point p2 = getNodePointWithH(surroundingNodes[2]);\n    \n    FVCOMStructure::Plane plane(p0, p1, p2);\n\n    return plane;\n}\n\nFVCOMStructure::Plane FVCOMStructure::getTriangleSiglayPlane(int triangle, unsigned int siglay) const\n{\n    const std::vector<int>& surroundingNodes = triangleToNodes[triangle];\n\n    FVCOMStructure::Point p0 = getNodePointAtSiglay(surroundingNodes[0], siglay);\n    FVCOMStructure::Point p1 = getNodePointAtSiglay(surroundingNodes[1], siglay);\n    FVCOMStructure::Point p2 = getNodePointAtSiglay(surroundingNodes[2], siglay);\n    \n    FVCOMStructure::Plane plane(p0, p1, p2);\n\n    return plane;\n}\n\ndouble FVCOMStructure::distance(Point p0, Point p1) const\n{\n    return std::sqrt((p0.x - p1.x)*(p0.x - p1.x) + (p0.y - p1.y)*(p0.y - p1.y) );\n}\n\ndouble FVCOMStructure::distanceSquared(Point p0, Point p1) const\n{\n    return (p0.x - p1.x)*(p0.x - p1.x) + (p0.y - p1.y)*(p0.y - p1.y);\n}\n\nconst FVCOMStructure::Point FVCOMStructure::getNodePointWithH(int node) const\n{\n    return nodes[node];\n}\n\nconst FVCOMStructure::Point FVCOMStructure::getNodePointAtSiglay(int node, int siglay) const\n{\n    FVCOMStructure::Point returnPoint = nodes[node];\n    returnPoint.z = returnPoint.z * nodeSiglay[node][siglay];\n\n    return returnPoint;\n}\n\n\nFVCOMStructure::ChunkInfo FVCOMStructure::getChunkForNode(int node, int siglay, int time) const\n{\n    //Chunk ids based on this ordering (x,y,sigma,time)\n    FVCOMStructure::ChunkInfo chunk;\n\n    double nodeX = nodes[node].x;\n    double nodeY = nodes[node].y;\n\n    //calculate the chunks for each individual dimension\n    chunk.xChunk = (nodeX - minX) / xChunkSize;\n    chunk.yChunk = (nodeY - minY) / yChunkSize;\n    chunk.siglayChunk = siglay / siglayChunkSize;\n    chunk.timeChunk = time / timeChunkSize;\n\n    //Check to insure that the chunks are valid.  If not this node is in the last chunk dimension.\n    //NOTE: This should only occur if the x/y extent is divisible by x/y chunk dimension.\n    //In this case maxX and maxY will give a chunk# as 1 more than the last chunk index.\n    //It seems like a waste to have the a chunk only be these single nodes so they are included\n    //in the last chunk.\n    if(chunk.xChunk >= xDimChunks)\n    {\n        chunk.xChunk = xDimChunks - 1;\n    }\n\n    if(chunk.yChunk >= yDimChunks)\n    {\n        chunk.yChunk = yDimChunks - 1;\n    }\n\n    chunk.id = chunk.timeChunk +\n           (chunk.siglayChunk * timeDimChunks) +\n           (chunk.yChunk * timeDimChunks * siglayDimChunks) +\n           (chunk.xChunk * timeDimChunks * siglayDimChunks * yDimChunks);\n\n\n    chunk.xStart = chunk.xChunk * xChunkSize - minX;\n    chunk.yStart = chunk.yChunk * yChunkSize - minX;\n    chunk.siglayStart = chunk.siglayChunk * siglayChunkSize;\n    chunk.timeStart = chunk.timeChunk * timeChunkSize;\n\n    chunk.xSize = xChunkSize;\n    chunk.ySize = yChunkSize;\n\n    unsigned int timeSize = times.size();\n    chunk.siglaySize = std::min(siglayChunkSize, siglayDim - chunk.siglayStart);\n    chunk.timeSize = std::min(timeChunkSize, timeSize - chunk.timeStart);\n\n    return chunk;\n}\n\n\nFVCOMStructure::ChunkInfo FVCOMStructure::getChunkForTriangle(int triangle, int siglay, int time) const\n{\n    //Chunk ids based on this ordering (x,y,sigma,time)\n\n    FVCOMStructure::ChunkInfo chunk;\n\n    double triangleX = triangles[triangle].x;\n    double triangleY = triangles[triangle].y;\n\n    //calculate the chunks for each individual dimension\n\n\n    chunk.xChunk = (triangleX - minX) / xChunkSize;\n    chunk.yChunk = (triangleY - minY) / yChunkSize;\n    chunk.siglayChunk = siglay / siglayChunkSize;\n    chunk.timeChunk = time / timeChunkSize;\n\n    //Check to insure that the chunks are valid.  If not this node is in the last chunk dimension.\n    //NOTE: This should only occur if the x/y extent is divisible by x/y chunk dimension.\n    //In this case maxX and maxY will give a chunk# as 1 more than the last chunk index.\n    //It seems like a waste to have the a chunk only be these single nodes so they are included\n    //in the last chunk.\n\n    if(chunk.xChunk >= xDimChunks)\n    {\n        chunk.xChunk = xDimChunks - 1;\n    }\n\n    if(chunk.yChunk >= yDimChunks)\n    {\n        chunk.yChunk = yDimChunks - 1;\n    }\n\n    chunk.id = chunk.timeChunk +\n           (chunk.siglayChunk * timeDimChunks) +\n           (chunk.yChunk * timeDimChunks * siglayDimChunks) +\n           (chunk.xChunk * timeDimChunks * siglayDimChunks * yDimChunks);\n\n    chunk.xStart = chunk.xChunk * xChunkSize - minX;\n    chunk.yStart = chunk.yChunk * yChunkSize - minX;\n    chunk.siglayStart = chunk.siglayChunk * siglayChunkSize;\n    chunk.timeStart = chunk.timeChunk * timeChunkSize;\n\n    chunk.xSize = xChunkSize;\n    chunk.ySize = yChunkSize;\n\n    unsigned int timeSize = times.size();\n    chunk.siglaySize = std::min(siglayChunkSize, siglayDim - chunk.siglayStart);\n    chunk.timeSize = std::min(timeChunkSize, timeSize - chunk.timeStart);\n\n    return chunk;\n}\n\nvoid FVCOMStructure::timeInterpolation(double time, int& time1Index, int& time2Index, double& time1Percent) const\n{\n    time1Index = getPreviousTimeIndex(time);\n    double previousTime = getTime(time1Index);\n\n    //Time is exactly on a time division, no interpolation needed.\n    if(previousTime == time)\n    {\n        time2Index = time1Index;\n        time1Percent = 1;\n    }\n    else //time is spilt between divisions so it needs interpolation\n    {\n        time2Index = time1Index + 1;\n        double nextTime = getTime(time2Index);\n        time1Percent = (nextTime - time) / (nextTime - previousTime);\n    }\n}\n\n\nvoid FVCOMStructure::siglayInterpolation(FVCOMStructure::Point& interpolatePoint, int& siglay1Index, int& siglay2Index, double& siglay1Percent)\n{\n    int containingTriangle = getContainingTriangle(interpolatePoint);\n    siglayInterpolation(interpolatePoint, siglay1Index, siglay2Index, siglay1Percent, containingTriangle);\n}\n\nvoid FVCOMStructure::siglayInterpolation(FVCOMStructure::Point& interpolatePoint, int& siglay1Index, int& siglay2Index, double& siglay1Percent, int containingTriangle)\n{\n    siglay1Index = siglay2Index = -1;\n\n    double prevDot = 0;\n    for(uint i = 0; i < getNumSiglays(); i++)\n    {\n        FVCOMStructure::Plane plane = getTriangleSiglayPlane(containingTriangle, i);\n\n        //calculate the dot product with the plane and the point to determine which side of the plane it is on\n        double dot = plane.a * interpolatePoint.x + plane.b * interpolatePoint.y + plane.c * interpolatePoint.z + plane.d;\n\n        if(i != 0)\n        {\n            if(dot == 0) //point is in the plane, use current siglayIndex and no interpolation needed\n            {\n                siglay1Index = i;\n                siglay2Index = i;\n                break;\n            }\n            else if((dot > 0 && prevDot < 0) || //The sign of dot has changed so the siglay has been found\n                    (dot < 0 && prevDot > 0))\n            {\n                siglay1Index = i - 1;\n                siglay2Index = i;\n                break;\n            }\n            else if((prevDot > 0 && prevDot < dot) || //The distance from the plane to the point is increasing so we have passed it.\n                    (prevDot < 0 && prevDot > dot))   //If this occurs then it means the point is above the 0th siglay, use the 0th siglay\n            {\n                siglay1Index = 0;\n                siglay2Index = 0;\n                break;\n            }\n        }\n\n        prevDot = dot;\n    }\n\n\n    //The dot product was always decreasing however it never changed sign.\n    //Therefore the point is below the final siglay, so use the final siglay.\n    if(siglay1Index == siglay2Index && siglay2Index == -1)\n    {\n        siglay1Index = getNumSiglays() -1;\n        siglay2Index = getNumSiglays() -1;\n    }\n\n    if(siglay1Index == siglay2Index) //The point is above the 0th siglay so and there is no data there\n    {\n        siglay1Percent = 1.0;\n    }\n    else\n    {\n        FVCOMStructure::Plane upperPlane = getTriangleSiglayPlane(containingTriangle, siglay1Index);\n        FVCOMStructure::Plane lowerPlane = getTriangleSiglayPlane(containingTriangle, siglay2Index);\n\n        double upperH = (-upperPlane.d - upperPlane.a * interpolatePoint.x - upperPlane.b * interpolatePoint.y) / upperPlane.c;\n        double lowerH = (-lowerPlane.d - lowerPlane.a * interpolatePoint.x - lowerPlane.b * interpolatePoint.y) / lowerPlane.c;\n\n        siglay1Percent = (lowerH - interpolatePoint.z) / (lowerH - upperH);\n    }\n}\n\ndouble FVCOMStructure::getDepthAtPoint(FVCOMStructure::Point& interpolatePoint, int containingTriangle)\n{\n    const std::vector<int>& surroundingNodes = getNodesInTriangle(containingTriangle);\n\n    FVCOMStructure::Point p1 = getNodePointWithH(surroundingNodes[0]);\n    FVCOMStructure::Point p2 = getNodePointWithH(surroundingNodes[1]);\n    FVCOMStructure::Point p3 = getNodePointWithH(surroundingNodes[2]);\n\n    FVCOMStructure::Plane groundPlane(p1,p2,p3);\n\n    return groundPlane.getHeight(interpolatePoint);\n}\n\ndouble FVCOMStructure::getDepthAtPoint(FVCOMStructure::Point& interpolatePoint)\n{\n    int containingTriangle = getContainingTriangle(interpolatePoint);\n\n    const std::vector<int>& surroundingNodes = getNodesInTriangle(containingTriangle);\n\n    FVCOMStructure::Point p1 = getNodePointWithH(surroundingNodes[0]);\n    FVCOMStructure::Point p2 = getNodePointWithH(surroundingNodes[1]);\n    FVCOMStructure::Point p3 = getNodePointWithH(surroundingNodes[2]);\n\n    FVCOMStructure::Plane groundPlane(p1,p2,p3);\n\n    return groundPlane.getHeight(interpolatePoint);\n}\n\nconst bool FVCOMStructure::pointInModel(Point p, double time)\n{\n    int containingTriangle = 0;\n    try\n    {\n        containingTriangle = getContainingTriangle(p);\n    }\n    catch(const std::out_of_range& e)\n    {\n        return false;\n    }\n\n    Plane plane = getTrianglePlane(containingTriangle);\n    double depth = plane.getHeight(p);\n    return p.x >= minX && p.x <= maxX && \n           p.y >= minY && p.y <= maxY && \n           time >= times[0] && time <= times[times.size() - 1] &&\n           p.z <= 0 && p.z >= -depth;\n}\n\nconst bool FVCOMStructure::timeInModel(double time) const\n{\n    return time >= times[0] && time <= times[times.size() - 1];\n}\n\nconst bool FVCOMStructure::depthInModel(Point p)\n{\n    int containingTriangle = 0;\n    try\n    {\n        containingTriangle = getContainingTriangle(p);\n    }\n    catch(const std::out_of_range& e)\n    {\n        return false;\n    }\n\n    Plane plane = getTrianglePlane(containingTriangle);\n    double depth = plane.getHeight(p);\n\n    return p.z <= 0 && p.z >= -depth;\n}\n\nconst bool FVCOMStructure::xyInModel(Point p) const\n{\n    return p.x >= minX && p.x <= maxX && \n           p.y >= minY && p.y <= maxY;\n}\n\n\nconst std::vector<unsigned int>& FVCOMStructure::getNodesInChunk(FVCOMStructure::ChunkInfo chunk) const\n{\n    int chunkId = chunk.yChunk + (chunk.xChunk * yDimChunks);\n\n    return nodesInChunk[chunkId];\n}\n\nconst std::vector<unsigned int>& FVCOMStructure::getTrianglesInChunk(FVCOMStructure::ChunkInfo chunk) const\n{\n    int chunkId = chunk.yChunk + (chunk.xChunk * yDimChunks);\n\n    return trianglesInChunk[chunkId];\n}\n\nconst unsigned int FVCOMStructure::getNumSiglays() const\n{\n    return siglayDim;\n}\n", "meta": {"hexsha": "90f024326a0907d1645b04a99032e6284ea36d65", "size": 23707, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ocean_model_interfaces/src/fvcom/FVCOMStructure.cpp", "max_stars_repo_name": "nasa-jpl/ocean-model-interfaces", "max_stars_repo_head_hexsha": "54bd471a79870dc43ef457b30e18372c07666ba9", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-01-07T20:49:15.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-07T20:49:15.000Z", "max_issues_repo_path": "ocean_model_interfaces/src/fvcom/FVCOMStructure.cpp", "max_issues_repo_name": "nasa-jpl/ocean-model-interfaces", "max_issues_repo_head_hexsha": "54bd471a79870dc43ef457b30e18372c07666ba9", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ocean_model_interfaces/src/fvcom/FVCOMStructure.cpp", "max_forks_repo_name": "nasa-jpl/ocean-model-interfaces", "max_forks_repo_head_hexsha": "54bd471a79870dc43ef457b30e18372c07666ba9", "max_forks_repo_licenses": ["Apache-2.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.5109395109, "max_line_length": 167, "alphanum_fraction": 0.6463069979, "num_tokens": 6366, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6370307944803831, "lm_q2_score": 0.49218813572079556, "lm_q1q2_score": 0.31353899913203703}}
{"text": "////////////////////////////////////////////////////////////////////////////////\n// msh_processor.cc\n////////////////////////////////////////////////////////////////////////////////\n/*! @file\n//      Extracts and processes fields from a .msh file. The field processor is\n//      essentually an RPN evaluator that maintains a stack of values and\n//      applies the filters specified on the command line in order.\n//\n//      Component-wise Binary Operations:\n//          add, sub, mul, div\n//      Component-wise Unary Operations:\n//          abs, scale, set\n//      (Partial) reductions:\n//          min, max, minMag, maxMag, norm, index, sum, mean\n//      Reductions can be done in multiple wasy for multi-indexed objects\n//      (e.g. vector fields, vector interpolants, fields of vector interpolants).\n//      By default, reductions are done over the innermost index\n//      (\"pointwise\" for fields/interpolants)\n//          Field<NonScalar>       -> Field<Reduced>       (recursive)\n//          Interpolant<NonScalar> -> Interpolant<Reduced> (recursive)\n//          Field<Scalar>          -> Scalar\n//          Interpolant<Scalar>    -> Scalar\n//          PointValue             -> Scalar\n//      When \"outer reduction\" mode is requested, reductions are done over the\n//      outer index (per-component reduction for vector fields/interpolants).\n//      Note: this is probably the more natural action for sum, mean of vector\n//      fields.\n//          Field<NonScalar>     -> Scalar\n//          Field<Scalar>        -> Scalar\n//          Interpolant<Scalar>  -> Scalar\n//          Field<T>             -> T\n//          Interpolant<T>       -> T\n//          PointValue           -> Scalar\n//      Warning: operations treat interpolants as vectors of nodal values, so\n//      for interpolants with negative weights component-wise min/max won't\n//      necessarily be the min/max over the simplex.\n//\n//      TODO: store element *index* on interpolant: binary operations can only\n//      act on a pair of interpolants with matching element index.\n*/\n//  Author:  Julian Panetta (jpanetta), julian.panetta@gmail.com\n//  Company:  New York University\n//  Created:  08/16/2014 15:26:04\n////////////////////////////////////////////////////////////////////////////////\n#include \"argparse.hh\"\n#include \"Sampler.hh\"\n#include \"Values.hh\"\n#include \"MeshConnectivity.hh\"\n#include <MeshFEM/ExpressionVector.hh>\n#include <MeshFEM/filters/remove_dangling_vertices.hh>\n#include <MeshFEM/MSHFieldParser.hh>\n#include <MeshFEM/MSHFieldWriter.hh>\n#include <MeshFEM/SimplicialMesh.hh>\n#include <MeshFEM/Types.hh>\n#include <MeshFEM/VonMises.hh>\n#include <boost/algorithm/string.hpp>\n#include <iomanip>\n#include <regex>\n#include <vector>\n#include <map>\n#include <set>\n#include <stdexcept>\n#include <cmath>\n#include <cctype>\n#include <memory>\n#include <functional>\n#include <limits>\n#include <sstream>\n\n//using namespace MeshIO;\nusing namespace std;\n\n// Global parsers used for 2 and 3D cases.\nunique_ptr<MSHFieldParser<2>> g_parser2D;\nunique_ptr<MSHFieldParser<3>> g_parser3D;\n\ntemplate<size_t N, typename... Args>\nvoid parseMSH(Args&&... args) {\n    static_assert(N == 2 || N == 3, \"Invalid parser dimension\");\n    if (N == 2) g_parser2D = make_unique<MSHFieldParser<2>>(std::forward<Args>(args)...);\n    else        g_parser3D = make_unique<MSHFieldParser<3>>(std::forward<Args>(args)...);\n}\n\ntemplate<size_t N>\nconst MSHFieldParser<N> &getParser();\ntemplate<> const MSHFieldParser<2> &getParser<2>() { return *g_parser2D; }\ntemplate<> const MSHFieldParser<3> &getParser<3>() { return *g_parser3D; }\n\ntemplate<size_t N>\nMSHFieldParser<N> &getMutableParser();\ntemplate<>       MSHFieldParser<2> &getMutableParser<2>() { return *g_parser2D; }\ntemplate<>       MSHFieldParser<3> &getMutableParser<3>() { return *g_parser3D; }\n\n// Global lazily-constructed element samplers used for 2 and 3D cases.\nunique_ptr<ElementSampler::Sampler<2>> g_sampler2D;\nunique_ptr<ElementSampler::Sampler<3>> g_sampler3D;\n\ntemplate<size_t N>\nconst ElementSampler::Sampler<N> &getElementSampler();\ntemplate<> const ElementSampler::Sampler<2> &getElementSampler<2>() { if (g_sampler2D) return *g_sampler2D; g_sampler2D = make_unique<ElementSampler::Sampler<2>>(g_parser2D->vertices(), g_parser2D->elements()); return *g_sampler2D; }\ntemplate<> const ElementSampler::Sampler<3> &getElementSampler<3>() { if (g_sampler3D) return *g_sampler3D; g_sampler3D = make_unique<ElementSampler::Sampler<3>>(g_parser3D->vertices(), g_parser3D->elements()); return *g_sampler3D; }\n\n// Global lazily-constructed mesh data structures for 2 and 3D cases.\nunique_ptr<SimplicialMesh<2>> g_triMesh;\nunique_ptr<SimplicialMesh<3>> g_tetMesh;\n\ntemplate<size_t N>\nconst SimplicialMesh<N> &getMeshDS();\ntemplate<> const SimplicialMesh<2> &getMeshDS<2>() { if (g_triMesh) return *g_triMesh; else g_triMesh = make_unique<SimplicialMesh<2>>(g_parser2D->elements(), g_parser2D->vertices().size()); return *g_triMesh; }\ntemplate<> const SimplicialMesh<3> &getMeshDS<3>() { if (g_tetMesh) return *g_tetMesh; else g_tetMesh = make_unique<SimplicialMesh<3>>(g_parser3D->elements(), g_parser3D->vertices().size()); return *g_tetMesh; }\n\n////////////////////////////////////////////////////////////////////////////////\n// Stack operations\n////////////////////////////////////////////////////////////////////////////////\nusing Stack = vector<NamedValue>;\n\nstruct Modifiers {\n    bool outerReduction = false;\n    bool applyAll = false;\n};\n\nNamedValue &getValue(Stack &stack, size_t offset = 0) {\n    if (stack.size() <= offset) throw std::runtime_error(\"Accessed out of stack bounds.\");\n    size_t idx = stack.size() - 1 - offset;\n    return stack.at(idx);\n}\n\nNamedValue popValue(Stack &stack) {\n    if (stack.empty()) throw std::runtime_error(\"Tried to pop from empty stack.\");\n    NamedValue val = std::move(getValue(stack));\n    stack.pop_back();\n    return val;\n}\n\ntemplate<typename T>\nTypedNamedValue<T> &getTypedValue(Stack &stack, size_t offset = 0) {\n    return TypedNamedValue<T>(getValue(stack, offset));\n}\n\ntemplate<typename T>\nTypedNamedValue<T> popTypedValue(Stack &stack) {\n    if (stack.empty()) throw std::runtime_error(\"Tried to pop from empty stack.\");\n    NamedValue val = std::move(stack.back());\n    stack.pop_back();\n    return val;\n}\n\n////////////////////////////////////////////////////////////////////////////////\n// Filters - operate on the stack.\n// These are all template functions with the signature:\n// template<size_t N>\n// size_t f(const string &op, const string &arg, Stack &stack, const Modifiers &m)\n//\n// Filters return the number of results they pushed onto the stack. Filters are\n// considered to first pop all of their arguments then push \"results\" onto the\n// stack. For example, the print operation that acts on the stack top but\n// does not modify the stack is considered to have one result (it pops and\n// pushes back the argument). The reverse operation, which acts on the whole\n// stack, returns the stack size.\n//\n// Placed in their own namespace because their names overload those defined\n// elsewhere, causing problems with the lookup table definition\n////////////////////////////////////////////////////////////////////////////////\nnamespace Filter {\n// Data source filters\n// Extract field(s) matching the pattern in \"arg\", pushing them on the top of\n// the stack.\nsize_t pushScalarField(Stack &stack, const string &name, const ScalarField<Real> &sf, const DomainType &dtype) {\n    TypedNamedValue<FSValue> sfv(name, dtype, sf.domainSize());\n    for (size_t i = 0; i < sf.domainSize(); ++i)\n        sfv->value[i] = SValue(sf[i]);\n    stack.push_back(std::move(sfv));\n    return 1;\n}\n\ntemplate<size_t N>\nsize_t pushVectorField(Stack &stack, const string &name, const VectorField<Real, N> &vf, const DomainType &dtype) {\n    TypedNamedValue<FVValue> vfv(name, dtype, vf.domainSize());\n    for (size_t i = 0; i < vf.domainSize(); ++i)\n        vfv->value[i] = VValue(vf(i).eval());\n    stack.push_back(std::move(vfv));\n    return 1;\n}\n\ntemplate<size_t N>\nsize_t pushSymmetricMatrixField(Stack &stack, const string &name, const SymmetricMatrixField<Real, N> &smf, const DomainType &dtype) {\n    TypedNamedValue<FSMValue> smfv(name, dtype, smf.domainSize());\n    for (size_t i = 0; i < smf.domainSize(); ++i)\n        smfv->value[i] = SMValue(smf(i));\n    stack.push_back(std::move(smfv));\n    return 1;\n}\n\ntemplate<class IFType, class RawType>\nsize_t pushInterpolantField(Stack &stack, const string &name, const RawType &raw_if, const DomainType &dtype) {\n    TypedNamedValue<IFType> ifv(name, dtype, raw_if.size());\n    for (size_t i = 0; i < raw_if.size(); ++i)\n        ifv->value[i] = raw_if[i];\n    stack.push_back(std::move(ifv));\n    return 1;\n}\n\ntemplate<size_t N>\nsize_t extract(const string &/*op*/, const string &arg, Stack &stack, const Modifiers &) {\n    const auto &parser = getParser<N>();\n    std::regex pattern(arg);\n    size_t origSize = stack.size();\n    DomainType dtype;\n    for (const string &name : parser.scalarFieldNames()) {\n        if (regex_match(name, pattern))\n            pushScalarField(stack, name, parser.scalarField(name, DomainType::ANY, dtype), dtype);\n    }\n    for (const string &name : parser.vectorFieldNames()) {\n        if (regex_match(name, pattern))\n            pushVectorField(stack, name, parser.vectorField(name, DomainType::ANY, dtype), dtype);\n    }\n    for (const string &name : parser.symmetricMatrixFieldNames()) {\n        if (regex_match(name, pattern))\n            pushSymmetricMatrixField(stack, name, parser.symmetricMatrixField(name, DomainType::ANY, dtype), dtype);\n    }\n    for (const string &name : parser.scalarInterpolantFieldNames()) {\n        if (regex_match(name, pattern))\n            pushInterpolantField< FISValue>(stack, name, parser.         scalarInterpolantField(name, DomainType::ANY, dtype), dtype);\n    }\n    for (const string &name : parser.vectorInterpolantFieldNames()) {\n        if (regex_match(name, pattern))\n            pushInterpolantField< FIVValue>(stack, name, parser.         vectorInterpolantField(name, DomainType::ANY, dtype), dtype);\n    }\n    for (const string &name : parser.symmetricMatrixInterpolantFieldNames()) {\n        if (regex_match(name, pattern))\n            pushInterpolantField<FISMValue>(stack, name, parser.symmetricMatrixInterpolantField(name, DomainType::ANY, dtype), dtype);\n    }\n\n    assert(stack.size() >= origSize);\n    if (stack.size() == origSize) throw runtime_error(\"No fields matched '\" + arg + \"'\");\n    return stack.size() - origSize;\n}\n\ntemplate<size_t N>\nsize_t extractAll(const string &/*op*/, const string &/* arg */, Stack &stack, const Modifiers &) {\n    size_t origSize = stack.size();\n    const auto &parser = getParser<N>();\n    DomainType dtype;\n    for (const string &name : parser.scalarFieldNames())\n        pushScalarField(stack, name, parser.scalarField(name, DomainType::ANY, dtype), dtype);\n    for (const string &name : parser.vectorFieldNames())\n        pushVectorField(stack, name, parser.vectorField(name, DomainType::ANY, dtype), dtype);\n    for (const string &name : parser.symmetricMatrixFieldNames())\n        pushSymmetricMatrixField(stack, name, parser.symmetricMatrixField(name, DomainType::ANY, dtype), dtype);\n\n    assert(stack.size() >= origSize);\n    return stack.size() - origSize;\n}\n\ntemplate<size_t N>\nsize_t generate(const string &, const string &arg, Stack &stack, const Modifiers &) {\n    const auto &parser = getParser<N>();\n    const auto &vertices = parser.vertices();\n    const auto &elements = parser.elements();\n    if (arg == \"x\") {\n        VectorField<Real, N> x(vertices.size());\n        for (size_t i = 0; i < vertices.size(); ++i)\n            x(i) = truncateFrom3D<VectorND<N>>(vertices[i].point);\n        pushVectorField(stack, \"x\", x, DomainType::PER_NODE);\n    }\n    else if (arg == \"volume\") {\n        const auto &sampler = getElementSampler<N>();\n        ScalarField<Real> vol(elements.size());\n        for (size_t i = 0; i < elements.size(); ++i)\n            vol[i] = sampler.volume(i);\n        pushScalarField(stack, \"volume\", vol, DomainType::PER_ELEMENT);\n    }\n    else if (arg == \"barycenter\") {\n        VectorField<Real, N> c(elements.size());\n        c.clear();\n        for (size_t ei = 0; ei < elements.size(); ++ei) {\n            const auto &e = elements[ei];\n            for (size_t j : e)\n                c(ei) += truncateFrom3D<VectorND<N>>(vertices.at(j).point);\n            c(ei) *= 1.0 / e.size();\n        }\n        pushVectorField(stack, \"barycenter\", c, DomainType::PER_ELEMENT);\n    }\n    else throw std::runtime_error(\"Invalid mesh property name: \" + arg);\n\n    return 1;\n}\n\ntemplate<size_t N>\nsize_t expression(const string &, const string &arg, Stack &stack, const Modifiers &) {\n    const auto &parser = getParser<N>();\n    const auto &vertices = parser.vertices();\n\n    vector<string> components;\n    boost::split(components, arg, boost::is_any_of(\",\"));\n    string name = \"expr(\" + arg + \")\";\n\n    ExpressionEnvironment env;\n    BBox<VectorND<N>> bb(vertices);\n    env.setVectorValue(\"mesh_size_\", bb.dimensions());\n    env.setVectorValue(\"mesh_min_\",  bb.minCorner);\n    env.setVectorValue(\"mesh_max_\",  bb.maxCorner);\n\n    if (components.size() == 1) {\n        Expression expr(components[0]);\n        ScalarField<Real> sf(vertices.size());\n        for (size_t i = 0; i < vertices.size(); ++i) {\n            env.setXYZ(vertices[i].point);\n            sf[i] = expr.eval(env);\n        }\n        pushScalarField(stack, name, sf, DomainType::PER_NODE);\n    }\n    else if (components.size() == N) {\n        ExpressionVector expr(components);\n        VectorField<Real, N> vf(vertices.size());\n        for (size_t i = 0; i < vertices.size(); ++i) {\n            env.setXYZ(vertices[i].point);\n            vf(i) = expr.eval<N>(env);\n        }\n        pushVectorField(stack, name, vf, DomainType::PER_NODE);\n    }\n    else throw std::runtime_error(\"Invalid number of components in vector-valued expression \" + arg);\n\n    return 1;\n}\n\nsize_t     dup(const string &, const string &   , Stack &stack, const Modifiers &) { stack.emplace_back(getValue(stack)); return 2; } // Copies: NamedValue has value semantics\nsize_t     pop(const string &, const string &   , Stack &stack, const Modifiers &) { popValue(stack); return 0; }\nsize_t    push(const string &, const string &arg, Stack &stack, const Modifiers &) { double d = parseRealArg(arg); stack.push_back(TypedNamedValue<SValue>(to_string(d), d)); return 1; }\nsize_t reverse(const string &, const string &   , Stack &stack, const Modifiers &) { std::reverse(stack.begin(), stack.end()); return stack.size(); }\nsize_t pull(const string &, const string &arg, Stack &stack, const Modifiers &) {\n    for (auto it = stack.begin(); it != stack.end(); ++it) {\n        if ((*it).name == arg) {\n            NamedValue val(std::move(*it));\n            stack.erase(it);\n            stack.emplace_back(std::move(val));\n            return 1;\n        }\n    }\n    throw runtime_error(\"Couldn't find '\" + arg + \"' for pull.\");\n}\n\n////////////////////////////////////////////////////////////////////////////////\n// Symmetric matrix operations\n////////////////////////////////////////////////////////////////////////////////\nstruct Eigenvalues {\n    // Returns a vector of eigenvalues.\n    using value_type = VValue;\n    static constexpr const char *name = \"eigenvalues\";\n    static VValue apply(const SMValue &sm) { return VValue(sm.value.eigenvalues()); }\n};\n\nstruct VonMises {\n    // Returns a symmetric matrix\n    using value_type = SMValue;\n    static constexpr const char *name = \"vonMises\";\n    static SMValue apply(const SMValue &sm) { return vonMises(sm.value); }\n};\n\nstruct FrobeniusNorm {\n    // Returns a scalar\n    using value_type = SValue;\n    static constexpr const char *name = \"frobeniusNorm\";\n    static SValue apply(const SMValue &sm) { return sqrt(sm.value.frobeniusNormSq()); }\n};\n\ntemplate<class Op>\nsize_t SMatrixOperation(const string &, const string &/* arg */, Stack &stack, const Modifiers &) {\n    using VT = typename Op::value_type;\n    auto val = popValue(stack);\n    string name = std::string(Op::name) + \"(\" + val.name + \")\";\n    if (auto sm = dynamic_cast<SMValue *>(VPtr(val)))\n        stack.push_back(TypedNamedValue<VT>(name, Op::apply(sm->value)));\n    else if (auto ism = dynamic_cast<ISMValue *>(VPtr(val))) {\n        auto result = make_unique<InterpolantValue<VT>>(ism->simplexDimension());\n        for (size_t i = 0; i < result->dim(); ++i)\n            (*result)[i] = VT(Op::apply((*ism)[i].value));\n        stack.emplace_back(name, std::move(result));\n    }\n    else if (auto fsm = dynamic_cast<FSMValue *>(VPtr(val))) {\n        auto result = make_unique<FieldValue<VT>>(fsm->size());\n        result->domainType = fsm->domainType;\n        for (size_t i = 0; i < result->size(); ++i) {\n            (*result)[i] = VT(Op::apply((*fsm)[i].value));\n        }\n        stack.emplace_back(name, std::move(result));\n    }\n    else if (/*auto ifsm =*/ dynamic_cast<FISMValue *>(VPtr(val))) {\n        throw std::runtime_error(\"Not yet implemented.\");\n    }\n    else throw runtime_error(\"called on non-matrix type argument\");\n\n    return 1;\n}\n\n// // This matrix->vector operator unfortunately must be implemented manually in\n// // the current framework...\n// size_t eigenvaluesAndEigenvectors(const string &, const string &arg, Stack &stack, const Modifiers &) {\n//     auto val = popValue(stack);\n//     string name = \"eigenvalues(\" + val.name + \")\";\n//     if (auto sm = dynamic_cast<SMValue *>(VPtr(val)))\n//         stack.push_back(TypedNamedValue<VValue>(name, sm->value.eigenvalues()));\n//     else if (auto  ism = dynamic_cast<ISMValue *>(VPtr(val))) {\n//         auto result = make_unique<IVValue>(ism->simplexDimension());\n//         for (size_t i = 0; i < result->dim(); ++i) {\n//             auto &sm = (*ism)[i];\n//             (*result)[i] = VValue(sm.value.eigenvalues());\n//         }\n//         stack.emplace_back(name, std::move(result));\n//     }\n//     else if (auto  fsm = dynamic_cast<FSMValue *>(VPtr(val))) {\n//         auto result = make_unique<FVValue>(fsm->size());\n//         result->domainType = fsm->domainType;\n//         for (size_t i = 0; i < result->size(); ++i) {\n//             auto &sm = (*fsm)[i];\n//             (*result)[i] = VValue(sm.value.eigenvalues());\n//         }\n//         stack.emplace_back(name, std::move(result));\n//     }\n//     else if (/*auto ifsm =*/ dynamic_cast<FISMValue *>(VPtr(val))) {\n//         throw std::runtime_error(\"Not yet implemented.\");\n//     }\n//     else throw runtime_error(\"called on non-matrix type argument\");\n//\n//     return 1;\n// }\n\ntemplate<size_t N>\nsize_t elementBarycenterFieldTransfer(const string &, const string &arg, Stack &stack, const Modifiers &) {\n    auto &sampler = getElementSampler<N>();\n    sampler.accelerate();\n\n    MSHFieldParser<N> targetMesh(arg);\n\n    PointND<N> center;\n    std::vector<ElementSampler::Sample> samplePts; samplePts.reserve(targetMesh.elements().size());\n    for (const auto &e : targetMesh.elements()) {\n        center.setZero();\n        for (size_t vi : e) center += truncateFrom3D<VectorND<N>>(targetMesh.vertices().at(vi));\n        center *= 1.0 / e.size();\n        samplePts.emplace_back(sampler(center));\n    }\n\n    auto &currentMesh = getMutableParser<N>();\n    Stack xferStack;\n\n    for (const auto &val : stack) {\n        string name = \"transfer(\" + val.name + \")\";\n        xferStack.emplace_back(name, val->sample(samplePts,\n                    currentMesh.meshDegree(), currentMesh.meshDimension(),\n                    DomainType::PER_ELEMENT));\n    }\n\n    // Replace mesh/value stack with the new mesh, stack of transferred values.\n    // Sampler is also invalidated\n    stack = std::move(xferStack);\n    currentMesh = std::move(targetMesh);\n    g_sampler2D.reset();\n    g_sampler3D.reset();\n\n    return stack.size();\n}\n\ntemplate<size_t N>\nsize_t loadNewMSH(const string &, const string &arg, Stack &, const Modifiers &) {\n    auto &currentMesh = getMutableParser<N>();\n    currentMesh = MSHFieldParser<N>(arg);\n    g_sampler2D.reset();\n    g_sampler3D.reset();\n    return 0;\n}\n\n// Filter elements using an indicator scalar field.\n// (elements with value > 0 are kept).\ntemplate<size_t N>\nsize_t filterElements(const string &, const string &, Stack &stack, const Modifiers &) {\n    auto invalid = std::runtime_error(\"Invalid argument to filterElements. Argument must be a per-element scalar field.\");\n    try {\n        auto &currentMesh = getMutableParser<N>();\n        auto top = popTypedValue<FSValue>(stack);\n        if (top->domainType != DomainType::PER_ELEMENT)\n            throw invalid;\n        auto verts = currentMesh.vertices();\n        const auto &oldElems  = currentMesh.elements();\n        std::vector<::MeshIO::IOElement> elems;\n        for (size_t i = 0; i < oldElems.size(); ++i) {\n            if (top->value[i].value > 0) elems.emplace_back(oldElems[i]);\n        }\n        remove_dangling_vertices(verts, elems);\n        currentMesh.replaceMesh(elems, verts);\n        stack.clear();\n    }\n    catch (...) {\n        throw invalid;\n    }\n    return 0;\n}\n\n// Sample a field at the point(s) specified by vector list encoded in \"arg\".\n// Nodal fields are interpolated using the mesh's finite element basis functions.\n// Element fields are interpolated piecewise constant\n// Interpolant fields are sampled at barycentric coordinates.\n// Error is thrown for sample points outside the mesh (note: could happen on\n// element boundaries if inside/outside check is not robust)\ntemplate<size_t N>\nsize_t sample(const string &, const string &arg, Stack &stack, const Modifiers &) {\n    auto pts = parseVectorListArg<N>(arg);\n    auto val = popValue(stack);\n    // Determine element index, barycentric coordinates, and element node\n    // indices of the containing element.\n    const auto &sampler = getElementSampler<N>();\n    const auto &parser = getParser<N>();\n\n    for (const auto &p : pts) {\n        stringstream ss;\n        ss << p.format(Eigen::IOFormat(Eigen::FullPrecision, Eigen::DontAlignCols, \"\", \", \", \"\", \"\", \"[\", \"]\"));\n        string name = \"sample(\" + val.name + \", \" + ss.str() + \")\";\n        stack.emplace_back(name, val->sample(sampler(p), parser.meshDegree(),\n                           parser.meshDimension()));\n    }\n\n    return pts.size();\n}\n\n// Average a field over each element.\ntemplate<size_t N>\nsize_t elementAverage(const string &, const string &/* arg */, Stack &stack, const Modifiers &) {\n    auto val = popValue(stack);\n    const auto &parser = getParser<N>();\n    stack.emplace_back(\"elementAverage(\" + val.name + \")\",\n                        val->elementAverage(parser.elements(), parser.meshDegree(), parser.meshDimension()));\n    return 1;\n}\n\n// Create a per-element field by a volume-weighted averaging over each element's\n// neighbors.\ntemplate<size_t N>\nsize_t smoothedElementField(const string &, const string &/* arg */, Stack &stack, const Modifiers &) {\n    auto val = popValue(stack);\n    const auto &parser = getParser<N>();\n\n    // Compute element volumes\n    const auto &sampler = getElementSampler<N>();\n    size_t nelems = parser.elements().size();\n    std::vector<Real> volumes(nelems);\n    for (size_t i = 0; i < nelems; ++i)\n        volumes[i] = sampler.volume(i);\n\n    stack.emplace_back(\"smoothedElementField(\" + val.name + \")\",\n                        val->smoothedElementField(parser.elements(), parser.meshDegree(), parser.meshDimension(),\n                                                  volumes, MeshConnectivityImpl<SimplicialMesh<N>>(getMeshDS<N>())));\n    return 1;\n}\n\n// Report filters\n// List all fields parsed\ntemplate<size_t N>\nsize_t listNames(const string &, const string &/* arg */, Stack &, const Modifiers &) {\n    const auto &parser = getParser<N>();\n    for (const string &name : parser.         scalarFieldNames()) { cout << \"s\\t\"  << name << endl; }\n    for (const string &name : parser.         vectorFieldNames()) { cout << \"v\\t\"  << name << endl; }\n    for (const string &name : parser.symmetricMatrixFieldNames()) { cout << \"sm\\t\" << name << endl; }\n\n    for (const string &name : parser.         scalarInterpolantFieldNames()) { cout << \"si\\t\"  << name << endl; }\n    for (const string &name : parser.         vectorInterpolantFieldNames()) { cout << \"vi\\t\"  << name << endl; }\n    for (const string &name : parser.symmetricMatrixInterpolantFieldNames()) { cout << \"smi\\t\" << name << endl; }\n    return 0;\n}\n\n// Print the top of the stack.\nsize_t print    (const string &, const string &, Stack &stack, const Modifiers &) { getValue(stack)->print(); cout << endl; return 1; }\nsize_t printName(const string &, const string &, Stack &stack, const Modifiers &) { cout << getValue(stack).name << endl; return 1; }\nsize_t noprint  (const string &, const string &, Stack &     , const Modifiers &) { return 1; }\n\ntemplate<size_t N>\nsize_t importScalarField(const string &/* op */, const string &arg, Stack &stack, const Modifiers &) {\n    const auto &parser = getParser<N>();\n    const auto &vertices = parser.vertices();\n    const auto &elements = parser.elements();\n    ifstream inFile(arg);\n    if (!inFile.is_open()) throw std::runtime_error(\"Couldn't open scalar field import file: \" + arg);\n    Real val;\n    std::vector<Real> values;\n    while (inFile >> val)\n        values.push_back(val);\n    if (values.size() == vertices.size())\n        pushScalarField(stack, arg, values, DomainType::PER_NODE);\n    else if (values.size() == elements.size())\n        pushScalarField(stack, arg, values, DomainType::PER_ELEMENT);\n    else throw std::runtime_error(\"Didn't recognize imported field size.\");\n\n    return 1;\n}\n\n// Import a flattened vector field (x0 y0 z0 x1 ...)\ntemplate<size_t N>\nsize_t importVectorField(const string &/* op */, const string &arg, Stack &stack, const Modifiers &) {\n    const auto &parser = getParser<N>();\n    const auto &vertices = parser.vertices();\n    const auto &elements = parser.elements();\n    ifstream inFile(arg);\n    if (!inFile.is_open()) throw std::runtime_error(\"Couldn't open vector field import file: \" + arg);\n    Real val;\n    std::vector<Real> values;\n    while (inFile >> val)\n        values.push_back(val);\n    VectorField<Real, N> vfield(values);\n\n    if (vfield.domainSize() == vertices.size())\n        pushVectorField(stack, arg, vfield, DomainType::PER_NODE);\n    else if (vfield.domainSize() == elements.size())\n        pushVectorField(stack, arg, vfield, DomainType::PER_ELEMENT);\n    else throw std::runtime_error(\"Didn't recognize imported field size.\");\n\n    return 1;\n}\n\ntemplate<size_t N>\nsize_t outputMSH(const string &/* op */, const string &arg, Stack &stack, const Modifiers &) {\n    const auto &parser = getParser<N>();\n    // Note: there will be downsampling of interpolant fields if the output\n    // mesh elements are linear. But in these cases, the original extracted\n    // interpolant fields were linear as well.\n    // TODO: rewrite as template code.\n    MSHFieldWriter writer(arg, parser.vertices(), parser.elements(), parser.meshType());\n    for (const auto &val : stack) {\n        if (auto fs = dynamic_cast<const FSValue *>(CVPtr(val))) {\n            ScalarField<Real> sf(fs->value.size());\n            for (size_t i = 0; i < sf.domainSize(); ++i)\n                sf[i] = fs->value[i].value;\n            writer.addField(val.name, sf, fs->domainType);\n        }\n        else if (auto fv = dynamic_cast<const FVValue *>(CVPtr(val))) {\n            VectorField<Real, N> vf(fv->value.size());\n            for (size_t i = 0; i < vf.domainSize(); ++i)\n                vf(i) = fv->value[i].value;\n            writer.addField(val.name, vf, fv->domainType);\n        }\n        else if (auto fsm = dynamic_cast<const FSMValue *>(CVPtr(val))) {\n            SymmetricMatrixField<Real, N> smf(fsm->value.size());\n            for (size_t i = 0; i < smf.domainSize(); ++i)\n                smf(i) = fsm->value[i].value;\n            writer.addField(val.name, smf, fsm->domainType);\n        }\n        else if (auto fis = dynamic_cast<const FISValue *>(CVPtr(val))) {\n            std::vector<typename InterpolantGetter<SValue, N>::storage_backed_type> isf(fis->value.size());\n            for (size_t i = 0; i < fis->value.size(); ++i)\n                isf[i] = InterpolantGetter<SValue, N>::get(fis->value[i]);\n            writer.addField(val.name, isf, fis->domainType);\n        }\n        else if (auto fiv = dynamic_cast<const FIVValue *>(CVPtr(val))) {\n            std::vector<typename InterpolantGetter<VValue, N>::storage_backed_type> ivf(fiv->value.size());\n            for (size_t i = 0; i < fiv->value.size(); ++i)\n                ivf[i] = InterpolantGetter<VValue, N>::get(fiv->value[i]);\n            writer.addField(val.name, ivf, fiv->domainType);\n        }\n        else if (auto fism = dynamic_cast<const FISMValue *>(CVPtr(val))) {\n            std::vector<typename InterpolantGetter<SMValue, N>::storage_backed_type> ismf(fism->value.size());\n            for (size_t i = 0; i < fism->value.size(); ++i)\n                ismf[i] = InterpolantGetter<SMValue, N>::get(fism->value[i]);\n            writer.addField(val.name, ismf, fism->domainType);\n        }\n        else cout << \"WARNING: ignored non-field value on stack: \" << val.name << endl;\n    }\n    return stack.size();\n}\n\nsize_t rename(const string &/* op */, const string &arg, Stack &stack, const Modifiers &) {\n    vector<string> names;\n    boost::split(names, arg, boost::is_any_of(\",\"));\n    if (names.size() > stack.size()) {\n        throw runtime_error(\"Too many names provided to rename\");\n    }\n    size_t pos = stack.size();\n    for(auto &name : names)\n        stack[--pos].name = std::move(name);\n    return names.size();\n}\n\ntemplate<size_t N>\nsize_t setNodePositions(const string &, const string &/* arg */, Stack &stack, const Modifiers &) {\n    const auto &top = popTypedValue<FVValue>(stack);\n\n    size_t nVals = top->size();\n    std::vector<PointND<3>> newPositions(nVals);\n    for (size_t i = 0; i < nVals; ++i)\n        newPositions[i] = top->operator[](i).value;\n\n    getMutableParser<N>().setNodePositions(newPositions);\n    return 0;\n}\n\ntemplate<class R>\nsize_t applyReduction(const string &op, const string &arg, Stack &stack, const Modifiers &m) {\n    auto top = popValue(stack);\n    string name = op + arg + \"(\" + top.name + \")\";\n    if (m.outerReduction) name = \"outer_\" + name;\n    R r(arg);\n    if (m.outerReduction) stack.emplace_back(name, top->outerReduction(r));\n    else                  stack.emplace_back(name, top->innerReduction(r));\n    return 1;\n}\n\ntemplate<class UOp>\nsize_t applyUnaryOp(const string &op, const string &arg, Stack &stack, const Modifiers &) {\n    auto top = popValue(stack);\n    stack.emplace_back(op + arg + \"(\" + top.name + \")\",\n                       top->componentwiseUnaryOp(UOp(arg)));\n    return 1;\n}\n\ntemplate<class BOp>\nsize_t applyBinaryOp(const string &op, const string &arg, Stack &stack, const Modifiers &) {\n    // Top of stack is the second operand, next in stack is the first\n    auto b = popValue(stack);\n    auto a = popValue(stack);\n    if (arg.size() != 0) throw runtime_error(\"Did not expect binary op argument\");\n    stack.emplace_back(op + \"(\" + a.name + \", \" + b.name + \")\",\n                       a->componentwiseBinaryOp(BOp(), b));\n    return 1;\n}\n\n} // end namespace Filter\n\ntemplate<size_t N>\nvoid execute(vector<FilterInvocation> &filters) {\n    map<string, function<size_t(const string &, const string &, Stack &, const Modifiers &)>>\n    filterImplementations = {\n        // Reductions\n        {\"min\",    Filter::applyReduction<ReductionMin   >},\n        {\"max\",    Filter::applyReduction<ReductionMax   >},\n        {\"minMag\", Filter::applyReduction<ReductionMinMag>},\n        {\"maxMag\", Filter::applyReduction<ReductionMaxMag>},\n        {\"norm\",   Filter::applyReduction<ReductionNorm  >},\n        {\"sum\",    Filter::applyReduction<ReductionSum   >},\n        {\"mean\",   Filter::applyReduction<ReductionMean  >},\n        {\"index\",  Filter::applyReduction<ReductionIndex >},\n        // Unary operations\n        {\"abs\",    Filter::applyUnaryOp<AbsOp  >},\n        {\"scale\",  Filter::applyUnaryOp<ScaleOp>},\n        {\"set\",    Filter::applyUnaryOp<SetOp  >},\n        // Binary operations\n        {\"add\",    Filter::applyBinaryOp<AddOp>},\n        {\"sub\",    Filter::applyBinaryOp<SubOp>},\n        {\"mul\",    Filter::applyBinaryOp<MulOp>},\n        {\"div\",    Filter::applyBinaryOp<DivOp>},\n        // Custom value operations\n        {\"print\",          Filter::print},\n        {\"noprint\",        Filter::noprint},\n        {\"printName\",      Filter::printName},\n        {\"eigenvalues\",    Filter::SMatrixOperation<Filter::Eigenvalues>},\n        {\"vonMises\",       Filter::SMatrixOperation<Filter::VonMises>},\n        {\"frobeniusNorm\",  Filter::SMatrixOperation<Filter::FrobeniusNorm>},\n        // {\"eigs\",           Filter::eigenvaluesAndEigenvectors},\n        {\"sample\",         Filter::sample<N>},\n        {\"elementAverage\", Filter::elementAverage<N>},\n        {\"smoothedElementField\", Filter::smoothedElementField<N>},\n        // Stack operations\n        {\"list\",          Filter::listNames<N>},\n        {\"extract\",       Filter::extract<N>},\n        {\"extractAll\",    Filter::extractAll<N>},\n        {\"generate\",      Filter::generate<N>},\n        {\"expression\",    Filter::expression<N>},\n        {\"dup\",           Filter::dup},\n        {\"pop\",           Filter::pop},\n        {\"push\",          Filter::push},\n        {\"pull\",          Filter::pull},\n        {\"rename\",        Filter::rename},\n        {\"import_sfield\", Filter::importScalarField<N>},\n        {\"import_vfield\", Filter::importVectorField<N>},\n        {\"reverse\",       Filter::reverse},\n        {\"setNodePositions\", Filter::setNodePositions<N>},\n        {\"outMSH\",        Filter::outputMSH<N>},\n\n        {\"transferFieldsToPerElem\", Filter::elementBarycenterFieldTransfer<N>},\n        {\"loadNewMSH\", Filter::loadNewMSH<N>},\n        {\"filterElements\", Filter::filterElements<N>}\n    };\n\n    // Classify the operations.\n    set<string> reductions = { \"min\", \"max\", \"minMag\", \"maxMag\",\n                               \"norm\", \"sum\", \"mean\", \"index\" };\n    set<string> unaryOps  = { \"abs\", \"scale\", \"set\" };\n    set<string> binaryOps = { \"add\", \"sub\", \"mul\", \"div\" };\n\n    // The following commands suppress automatic output of stack at exit when performed last\n    set<string> suppressImplicitPrint = { \"noprint\", \"print\", \"outMSH\", \"list\" };\n\n    // Apply-all makes sense only for the following operations:\n    set<string> acceptsApplyAll = { \"print\", \"printName\", \"eigenvalues\",\n                                    \"vonMises\", \"frobeniusNorm\", \"sample\" };\n    acceptsApplyAll.insert(reductions.begin(), reductions.end());\n    acceptsApplyAll.insert(  unaryOps.begin(),   unaryOps.end());\n    acceptsApplyAll.insert( binaryOps.begin(),  binaryOps.end());\n\n    // Implicit list operation when filters are empty\n    if (filters.size() == 0) filters.push_back({\"list\", \"\"});\n\n    // Add an implicit print operation unless it is supressed\n    if (!suppressImplicitPrint.count(filters.back().first)) filters.push_back({\"print\", \"\"});\n\n    Stack stack;\n    for (size_t fi = 0; fi < filters.size(); ++fi) {\n        try {\n            Modifiers m; // fresh modifier flags\n            runtime_error missingOperation(\"Modifier specified without an operation.\");\n            // Note: applyAll should appear *first*\n            if (filters[fi].first == \"applyAll\")       { m.applyAll       = true; ++fi; }\n            if (fi >= filters.size()) throw missingOperation;\n            if (filters[fi].first == \"outerReduction\") { m.outerReduction = true; ++fi; }\n            if (fi >= filters.size()) throw missingOperation;\n            const auto &f = filters[fi];\n\n            // Validate modifiers.\n            if (m.outerReduction && (reductions.count(f.first) == 0))\n                throw runtime_error(\"--outerReduction must be followed by reduction\");\n            if (m.applyAll && (acceptsApplyAll.count(f.first) == 0))\n                throw runtime_error(\"operation does not support apply all\");\n\n            // Perform the filter either once or once per stack value.\n            if (m.applyAll) {\n                Stack newStack;\n                while (stack.size()) {\n                    size_t n = filterImplementations.at(f.first)(f.first, f.second, stack, m);\n                    // Move each result over to the new stack\n                    for (size_t r = 0; r < n; ++r)\n                        newStack.emplace_back(popValue(stack));\n                }\n                std::reverse(newStack.begin(), newStack.end());\n                stack = std::move(newStack);\n            }\n            else filterImplementations.at(f.first)(f.first, f.second, stack, m);\n        }\n        catch (const exception &e) {\n            if (fi < filters.size())\n                cout << \"Filter '\" << filters[fi].first << \"' failed: \" << e.what() << endl;\n            else\n                cout << \"Filter failed: \" << e.what() << endl;\n            exit(-1);\n        }\n    }\n}\n\nint main(int argc, char *argv[])\n{\n    cout << std::scientific << std::setprecision(16);\n    MeshIO::MeshIO_MSH io;\n    vector<MeshIO::IOVertex>  v;\n    vector<MeshIO::IOElement> e;\n\n    string mshFile;\n    vector<FilterInvocation> filters;\n    auto forcedDim = boost::make_optional(false, size_t()); // work around maybe-uninitialized GCC warning bug\n    std::tie(mshFile, filters, forcedDim) = parseCmdLine(argc, argv);\n\n    ifstream infile(mshFile);\n    if (!infile.is_open()) throw runtime_error(\"Couldn't open \" + mshFile);\n    MeshIO::MeshType type = io.load(infile, v, e, MeshIO::MESH_GUESS);\n    size_t meshDim = ::MeshIO::meshDimension(type);\n\n    size_t dim = forcedDim ? *forcedDim : meshDim;\n    if (dim < 2 || dim > 3) throw std::runtime_error(\"Unsupported dimension: \" + std::to_string(dim));\n\n    if (meshDim != dim)\n        cerr << \"Warning: some operations won't work properly on non-full-dimension meshes\" << endl;\n\n    if (dim == 3) parseMSH<3>(infile, type, std::move(e), std::move(v), io.binary(), meshDim != dim);\n    else          parseMSH<2>(infile, type, std::move(e), std::move(v), io.binary(), meshDim != dim);\n\n    if (dim == 3) execute<3>(filters);\n    else          execute<2>(filters);\n\n    return 0;\n}\n", "meta": {"hexsha": "e64cfba41e853539ff46871ebf4ceca6d09afe23", "size": 38285, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/bin/tools/msh_processor.cc", "max_stars_repo_name": "pbedenbaugh/MeshFEM", "max_stars_repo_head_hexsha": "742d609d4851582ffb9c5616774fc2ef489e2f88", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 19.0, "max_stars_repo_stars_event_min_datetime": "2020-10-21T10:05:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-20T13:41:50.000Z", "max_issues_repo_path": "src/bin/tools/msh_processor.cc", "max_issues_repo_name": "pbedenbaugh/MeshFEM", "max_issues_repo_head_hexsha": "742d609d4851582ffb9c5616774fc2ef489e2f88", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2021-01-01T15:58:15.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-19T03:31:09.000Z", "max_forks_repo_path": "src/bin/tools/msh_processor.cc", "max_forks_repo_name": "pbedenbaugh/MeshFEM", "max_forks_repo_head_hexsha": "742d609d4851582ffb9c5616774fc2ef489e2f88", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2020-10-05T09:01:50.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-11T03:02:39.000Z", "avg_line_length": 43.7542857143, "max_line_length": 233, "alphanum_fraction": 0.6179966044, "num_tokens": 9501, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5774953651858118, "lm_q2_score": 0.5428632831725052, "lm_q1q2_score": 0.31350102996167467}}
{"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_DETAIL_HPP\r\n#define BOOST_MATH_INTERPOLATORS_WHITAKKER_SHANNON_DETAIL_HPP\r\n#include <boost/assert.hpp>\r\n#include <boost/math/constants/constants.hpp>\r\n#include <boost/math/special_functions/sin_pi.hpp>\r\n#include <boost/math/special_functions/cos_pi.hpp>\r\n\r\nnamespace boost { namespace math { namespace interpolators { namespace detail {\r\n\r\ntemplate<class RandomAccessContainer>\r\nclass whittaker_shannon_detail {\r\npublic:\r\n\r\n    using Real = typename RandomAccessContainer::value_type;\r\n    whittaker_shannon_detail(RandomAccessContainer&& y, Real const & t0, Real const & h) : m_y{std::move(y)}, m_t0{t0}, m_h{h}\r\n    {\r\n        for (size_t i = 1; i < m_y.size(); i += 2)\r\n        {\r\n            m_y[i] = -m_y[i];\r\n        }\r\n    }\r\n\r\n    inline Real operator()(Real t) const {\r\n        using boost::math::constants::pi;\r\n        using std::isfinite;\r\n        using std::floor;\r\n        Real y = 0;\r\n        Real x = (t - m_t0)/m_h;\r\n        Real z = x;\r\n        auto it = m_y.begin();\r\n\r\n        // For some reason, neither clang nor g++ will cache the address of m_y.end() in a register.\r\n        // Hence make a copy of it:\r\n        auto end = m_y.end();\r\n        while(it != end)\r\n        {\r\n\r\n            y += *it++/z;\r\n            z -= 1;\r\n        }\r\n\r\n        if (!isfinite(y))\r\n        {\r\n            BOOST_ASSERT_MSG(floor(x) == ceil(x), \"Floor and ceiling should be equal.\\n\");\r\n            size_t i = static_cast<size_t>(floor(x));\r\n            if (i & 1)\r\n            {\r\n                return -m_y[i];\r\n            }\r\n            return m_y[i];\r\n        }\r\n        return y*boost::math::sin_pi(x)/pi<Real>();\r\n    }\r\n\r\n    Real prime(Real t) const {\r\n        using boost::math::constants::pi;\r\n        using std::isfinite;\r\n        using std::floor;\r\n\r\n        Real x = (t - m_t0)/m_h;\r\n        if (ceil(x) == x) {\r\n            Real s = 0;\r\n            long j = static_cast<long>(x);\r\n            long n = m_y.size();\r\n            for (long i = 0; i < n; ++i)\r\n            {\r\n                if (j - i != 0)\r\n                {\r\n                    s += m_y[i]/(j-i);\r\n                }\r\n                // else derivative of sinc at zero is zero.\r\n            }\r\n            if (j & 1) {\r\n                s /= -m_h;\r\n            } else {\r\n                s /= m_h;\r\n            }\r\n            return s;\r\n        }\r\n        Real z = x;\r\n        auto it = m_y.begin();\r\n        Real cospix = boost::math::cos_pi(x);\r\n        Real sinpix_div_pi = boost::math::sin_pi(x)/pi<Real>();\r\n\r\n        Real s = 0;\r\n        auto end = m_y.end();\r\n        while(it != end)\r\n        {\r\n            s += (*it++)*(z*cospix - sinpix_div_pi)/(z*z);\r\n            z -= 1;\r\n        }\r\n\r\n        return s/m_h;\r\n    }\r\n\r\n\r\n\r\n    Real operator[](size_t i) const {\r\n        if (i & 1)\r\n        {\r\n            return -m_y[i];\r\n        }\r\n        return m_y[i];\r\n    }\r\n\r\n    RandomAccessContainer&& return_data() {\r\n        for (size_t i = 1; i < m_y.size(); i += 2)\r\n        {\r\n            m_y[i] = -m_y[i];\r\n        }\r\n        return std::move(m_y);\r\n    }\r\n\r\n\r\nprivate:\r\n    RandomAccessContainer m_y;\r\n    Real m_t0;\r\n    Real m_h;\r\n};\r\n}}}}\r\n#endif\r\n", "meta": {"hexsha": "0fbd7febf925a837227ec1c7648689622e8556d2", "size": 3421, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "deps/boost/include/boost/math/interpolators/detail/whittaker_shannon_detail.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/detail/whittaker_shannon_detail.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/detail/whittaker_shannon_detail.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.937007874, "max_line_length": 127, "alphanum_fraction": 0.4826074247, "num_tokens": 869, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5774953651858118, "lm_q2_score": 0.5428632831725051, "lm_q1q2_score": 0.3135010299616746}}
{"text": "/*\n  Copyright 2011 Larry Gritz and the other authors and contributors.\n  All Rights Reserved.\n\n  Redistribution and use in source and binary forms, with or without\n  modification, are permitted provided that the following conditions are\n  met:\n  * Redistributions of source code must retain the above copyright\n    notice, this list of conditions and the following disclaimer.\n  * Redistributions in binary form must reproduce the above copyright\n    notice, this list of conditions and the following disclaimer in the\n    documentation and/or other materials provided with the distribution.\n  * Neither the name of the software's owners nor the names of its\n    contributors may be used to endorse or promote products derived from\n    this software without specific prior written permission.\n  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n  \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n  A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n  OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n  SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n  LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n  DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n  THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n  (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n  OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n  (This is the Modified BSD License)\n*/\n\n\n/// \\file\n/// Implementation of ImageBufAlgo algorithms.\n\n#include <iostream>\n#include <cmath>\n\n#include <boost/scoped_array.hpp>\n\n#include <OpenEXR/ImathFun.h>\n#include <OpenEXR/ImathColor.h>\nusing Imath::Color3f;\n\n#include \"fmath.h\"\n#include \"imagebuf.h\"\n#include \"imagebufalgo.h\"\n#include \"dassert.h\"\n\n\ntemplate<class T>\ninline Imath::Vec3<T>\npowf (const Imath::Vec3<T> &x, float y)\n{\n    return Imath::Vec3<T> (powf (x[0], y), powf (x[1], y), powf (x[2], y));\n}\n\n\n\n\nOIIO_NAMESPACE_ENTER\n{\n\nnamespace\n{\n\nstatic bool\nsame_size (const ImageBuf &A, const ImageBuf &B)\n{\n    const ImageSpec &a (A.spec()), &b (B.spec());\n    return (a.width == b.width && a.height == b.height &&\n            a.depth == b.depth && a.nchannels == b.nchannels);\n}\n\n\n#define LAPLACIAN_MAX_LEVELS 8\n\n\nclass LaplacianPyramid\n{\npublic:\n    LaplacianPyramid (float *image, int _width, int _height) \n        : w(_width), h(_height)\n    {\n        level[0].insert (level[0].begin(), image, image+w*h);\n        for (int i = 1;  i < LAPLACIAN_MAX_LEVELS;  ++i)\n            convolve (level[i], level[i-1]);\n    }\n\n    ~LaplacianPyramid () { }\n\n    float value (int x, int y, int lev) const {\n\treturn level[std::min (lev, LAPLACIAN_MAX_LEVELS-1)][y*w + x];\n    }\n\nprivate:\n    int w, h;\n    std::vector<float> level[LAPLACIAN_MAX_LEVELS];\n\n    // convolve image b with the kernel and store it in a\n    void convolve (std::vector<float> &a, const std::vector<float> &b) {\n        const float kernel[] = {0.05f, 0.25f, 0.4f, 0.25f, 0.05f};\n        a.resize (b.size());\n        for (int y = 0, index = 0;  y < h;  ++y) {\n            for (int x = 0;  x < w;  ++x, ++index) {\n                a[index] = 0.0f;\n                for (int i = -2;  i <= 2;  ++i) {\n                    for (int j = -2;  j<= 2;  ++j) {\n                        int nx = abs(x+i);\n                        int ny = abs(y+j);\n                        if (nx >= w)\n                            nx=2*w-nx-1;\n                        if (ny >= h)\n                            ny=2*h-ny-1;\n                        a[index] += kernel[i+2] * kernel[j+2] * b[ny * w + nx];\n                    } \n                }\n            }\n        }\n    }\n};\n\n\n\n\n// Adobe RGB (1998) with reference white D65 -> XYZ\n// matrix is from http://www.brucelindbloom.com/\ninline Color3f\nAdobeRGBToXYZ (const Color3f &rgb)\n{\n    return Color3f (rgb[0] * 0.576700f  + rgb[1] * 0.185556f  + rgb[2] * 0.188212f,\n                    rgb[0] * 0.297361f  + rgb[1] * 0.627355f  + rgb[2] * 0.0752847f,\n                    rgb[0] * 0.0270328f + rgb[1] * 0.0706879f + rgb[2] * 0.991248f);\n}\n\n\n\n/// Convert a color in XYZ space to LAB space.\n///\nstatic Color3f\nXYZToLAB (const Color3f xyz)\n{\n    // Reference white point\n    static const Color3f white (0.576700f + 0.185556f + 0.188212f,\n                                0.297361f + 0.627355f + 0.0752847f,\n                                0.0270328f + 0.0706879f + 0.991248f);\n    const float epsilon = 216.0f / 24389.0f;\n    const float kappa = 24389.0f / 27.0f;\n\n    Color3f r = xyz / white;\n    Color3f f;\n    for (int i = 0; i < 3; i++) {\n        if (r[i] > epsilon)\n            f[i] = powf (r[i], 1.0f / 3.0f);\n        else\n            f[i] = (kappa * r[i] + 16.0f) / 116.0f;\n    }\n    return Color3f (116.0f * f[1] - 16.0f,    // L\n                    500.0f * (f[0] - f[1]),   // A\n                    200.0f * (f[1] - f[2]));  // B\n}\n\n\n\n// Contrast sensitivity function (Barten SPIE 1989)\nstatic float\ncontrast_sensitivity (float cyclesperdegree, float luminance)\n{\n    float a = 440.0f * powf ((1.0f + 0.7f / luminance), -0.2f);\n    float b = 0.3f * powf ((1.0f + 100.0f / luminance), 0.15f);\n    return a * cyclesperdegree * expf(-b * cyclesperdegree) \n             * sqrtf(1.0f + 0.06f * expf(b * cyclesperdegree)); \n}\n\n\n\n// Visual Masking Function from Daly 1993\ninline float\nmask (float contrast)\n{\n    float a = powf (392.498f * contrast, 0.7f);\n    float b = powf (0.0153f * a, 4.0f);\n    return powf (1.0f + b, 0.25f); \n}\n\n\n\n// Given the adaptation luminance, this function returns the\n// threshold of visibility in cd per m^2\n// TVI means Threshold vs Intensity function\n// This version comes from Ward Larson Siggraph 1997\nstatic float\ntvi (float adaptation_luminance)\n{\n    // returns the threshold luminance given the adaptation luminance\n    // units are candelas per meter squared\n    float r;\n    float log_a = log10f(adaptation_luminance);\n    if (log_a < -3.94f)\n        r = -2.86f;\n    else if (log_a < -1.44f)\n        r = powf(0.405f * log_a + 1.6f , 2.18f) - 2.86f;\n    else if (log_a < -0.0184f)\n        r = log_a - 0.395f;\n    else if (log_a < 1.9f)\n        r = powf(0.249f * log_a + 0.65f, 2.7f) - 0.72f;\n    else\n        r = log_a - 1.255f;\n    return powf (10.0f, r); \n}\n\n\n}\n\n\n\nint\nImageBufAlgo::compare_Yee (const ImageBuf &img0, const ImageBuf &img1,\n                           float luminance, float fov)\n{\n    const ImageSpec &spec (img0.spec());\n    ASSERT (spec.format == TypeDesc::FLOAT);\n    ASSERT (same_size (img0, img1));\n    int nscanlines = spec.height * spec.depth;\n    int npels = nscanlines * spec.width;\n\n    bool luminanceOnly = false;\n\n    // assuming colorspaces are in Adobe RGB (1998), convert to LAB\n    boost::scoped_array<Color3f> aLAB (new Color3f[npels]);\n    boost::scoped_array<Color3f> bLAB (new Color3f[npels]);\n    boost::scoped_array<float> aLum (new float[npels]);\n    boost::scoped_array<float> bLum (new float[npels]);\n    ImageBuf::ConstIterator<float,float> pix0 (img0);\n    ImageBuf::ConstIterator<float,float> pix1 (img1);\n    for (int i = 0;  pix0.valid();  ++i, pix0++) {\n        pix1.pos (pix0.x(), pix0.y());  // ensure alignment\n        Color3f RGB, XYZ;\n        RGB.setValue (pix0[0], pix0[1], pix0[2]);\n        XYZ = AdobeRGBToXYZ (RGB);\n        aLAB[i] = XYZToLAB (XYZ);\n        aLum[i] = XYZ[1] * luminance;\n\n        RGB.setValue (pix1[0], pix1[1], pix1[2]);\n        XYZ = AdobeRGBToXYZ (RGB);\n        bLAB[i] = XYZToLAB (XYZ);\n        bLum[i] = XYZ[1] * luminance;\n    }\n\n    // Construct Laplacian pyramids\n    LaplacianPyramid la (&aLum[0], spec.width, nscanlines);\n    LaplacianPyramid lb (&bLum[0], spec.width, nscanlines);\n\n    float num_one_degree_pixels = (float) (2 * tan(fov * 0.5 * M_PI / 180) * 180 / M_PI);\n    float pixels_per_degree = spec.width / num_one_degree_pixels;\n\n    unsigned int adaptation_level = 0;\n    for (int i = 0, npixels = 1;\n             i < LAPLACIAN_MAX_LEVELS && npixels <= num_one_degree_pixels;\n             ++i, npixels *= 2) \n        adaptation_level = i;\n\n    float cpd[LAPLACIAN_MAX_LEVELS];\n    cpd[0] = 0.5f * pixels_per_degree;\n    for (int i = 1;  i < LAPLACIAN_MAX_LEVELS;  ++i)\n        cpd[i] = 0.5f * cpd[i - 1];\n    float csf_max = contrast_sensitivity (3.248f, 100.0f);\n\n    float F_freq[LAPLACIAN_MAX_LEVELS - 2];\n    for (int i = 0; i < LAPLACIAN_MAX_LEVELS - 2;  ++i)\n        F_freq[i] = csf_max / contrast_sensitivity (cpd[i], 100.0f);\n\n    unsigned int pixels_failed = 0;\n    for (int y = 0, index = 0; y < nscanlines;  ++y) {\n        for (int x = 0;  x < spec.width;  ++x, ++index) {\n            float contrast[LAPLACIAN_MAX_LEVELS - 2];\n            float sum_contrast = 0;\n            for (int i = 0; i < LAPLACIAN_MAX_LEVELS - 2; i++) {\n                float n1 = fabsf (la.value(x,y,i) - la.value(x,y,i+1));\n                float n2 = fabsf (lb.value(x,y,i) - lb.value(x,y,i+1));\n                float numerator = std::max (n1, n2);\n                float d1 = fabsf (la.value(x,y,i+2));\n                float d2 = fabsf (lb.value(x,y,i+2));\n                float denominator = std::max (std::max (d1, d2), 1.0e-5f);\n                contrast[i] = numerator / denominator;\n                sum_contrast += contrast[i];\n            }\n            if (sum_contrast < 1e-5)\n                sum_contrast = 1e-5f;\n            float F_mask[LAPLACIAN_MAX_LEVELS - 2];\n            float adapt = la.value(x,y,adaptation_level) + lb.value(x,y,adaptation_level);\n            adapt *= 0.5f;\n            if (adapt < 1e-5)\n                adapt = 1e-5f;\n            for (int i = 0; i < LAPLACIAN_MAX_LEVELS - 2; i++)\n                F_mask[i] = mask(contrast[i] * contrast_sensitivity(cpd[i], adapt)); \n            float factor = 0;\n            for (int i = 0; i < LAPLACIAN_MAX_LEVELS - 2; i++)\n                factor += contrast[i] * F_freq[i] * F_mask[i] / sum_contrast;\n            factor = Imath::clamp (factor, 1.0f, 10.0f);\n            float delta = fabsf (la.value(x,y,0) - lb.value(x,y,0));\n            bool pass = true;\n            // pure luminance test\n            if (delta > factor * tvi(adapt)) {\n                pass = false;\n            } else if (! luminanceOnly) {\n                // CIE delta E test with modifications\n                float color_scale = 1.0f;\n                // ramp down the color test in scotopic regions\n                if (adapt < 10.0f) {\n                    color_scale = 1.0f - (10.0f - color_scale) / 10.0f;\n                    color_scale = color_scale * color_scale;\n                }\n                float da = aLAB[index][1] - bLAB[index][1];  // diff in A\n                float db = aLAB[index][2] - bLAB[index][2];  // diff in B\n                da = da * da;\n                db = db * db;\n                float delta_e = (da + db) * color_scale;\n                if (delta_e > factor)\n                    pass = false;\n            }\n            if (!pass)\n                ++pixels_failed;\n        }\n    }\n//    std::cout << \"Perceptual diff shows \" << pixels_failed << \" failures\\n\";\n\n    return pixels_failed;\n}\n\n\n}\nOIIO_NAMESPACE_EXIT\n", "meta": {"hexsha": "b7be2f0add13361ac66ca3204982dfb7e13d7ee9", "size": 11167, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/libOpenImageIO/imagebufalgo_yee.cpp", "max_stars_repo_name": "fpsunflower/oiio", "max_stars_repo_head_hexsha": "2470ff03ec82cadf376cda4d652f1cb069afd6ef", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2015-02-25T21:54:04.000Z", "max_stars_repo_stars_event_max_datetime": "2015-07-30T17:59:13.000Z", "max_issues_repo_path": "src/libOpenImageIO/imagebufalgo_yee.cpp", "max_issues_repo_name": "Alexander-Murashko/oiio", "max_issues_repo_head_hexsha": "2cb95cf674e6cb085eb14614c428535ed2b8989b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/libOpenImageIO/imagebufalgo_yee.cpp", "max_forks_repo_name": "Alexander-Murashko/oiio", "max_forks_repo_head_hexsha": "2cb95cf674e6cb085eb14614c428535ed2b8989b", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2016-08-22T11:47:04.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-04T11:35:39.000Z", "avg_line_length": 33.5345345345, "max_line_length": 90, "alphanum_fraction": 0.5721321752, "num_tokens": 3413, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6076631698328916, "lm_q2_score": 0.5156199157230156, "lm_q1q2_score": 0.31332323241721605}}
{"text": "/*\r\n * Copyright (c) 2017, Adrian Michel\r\n * http://www.amichel.com\r\n *\r\n * This software is released under the 3-Clause BSD License\r\n *\r\n * The complete terms can be found in the attached LICENSE file\r\n * or at https://opensource.org/licenses/BSD-3-Clause\r\n */\r\n\r\n#pragma once\r\n\r\n#include <boost/algorithm/string.hpp>\r\n#include <boost/format.hpp>\r\n#include <boost/lexical_cast.hpp>\r\n#include <boost/make_shared.hpp>\r\n#include <boost/tokenizer.hpp>\r\n#include <set>\r\n\r\n#include \"de_types.hpp\"\r\n#include \"random_generator.hpp\"\r\n\r\n#if defined(max)\r\n#undef max\r\n#endif\r\n\r\n#if defined(min)\r\n#undef min\r\n#endif\r\n\r\n\r\nnamespace amichel {\r\nnamespace de {\r\n\r\n/**\r\n * Exception thrown in case of a constraint error\r\n */\r\nclass constraints_exception : public exception {\r\n public:\r\n  constraints_exception(const std::string& message)\r\n      : exception(message.c_str()) {}\r\n};\r\n\r\n/**\r\n * Abstract base class for concrete constraint classes\r\n *\r\n * A constraint class describes certain characteristics and\r\n * limits of the input variables fed to the objective function.\r\n */\r\nclass constraint {\r\n public:\r\n  virtual ~constraint() {}\r\n\r\n  /**\r\n   * returns a random value limited to the type and range of the\r\n   * constraint\r\n   *\r\n   * @return double\r\n   */\r\n  virtual double get_rand_value() = 0;\r\n\r\n  /**\r\n   * returns a random value limited to the type and range of the\r\n   * constraint based on a previous value and an origin (see\r\n   * specific implementation in derived classes)\r\n   *\r\n   * @param value\r\n   * @param origin\r\n   *\r\n   * @return double\r\n   */\r\n  virtual double get_rand_value(double value, double origin) = 0;\r\n\r\n  /**\r\n   * returns the min limit of the range\r\n   *\r\n   * @return double\r\n   */\r\n  virtual double min() const = 0;\r\n\r\n  /**\r\n   * returns the max limit of the range\r\n   *\r\n   * @return double\r\n   */\r\n  virtual double max() const = 0;\r\n\r\n  /**\r\n   * Gets a random value within the limits set for the constraint,\r\n   * but further limited to a range defined by its origin and the\r\n   * width of the zone around this origin in pct of the total\r\n   * width\r\n   *\r\n   * @param origin the origin (center) of the zone further\r\n   *  \t\t\t limiting the constraint\r\n   * @param zonePct the width of the zone in pct of the total\r\n   *  \t\t\t  width, around the origin\r\n   *\r\n   * @return double\r\n   */\r\n  virtual double get_rand_value_in_zone(double origin, double zonePct) const = 0;\r\n\r\n  /**\r\n   * Gets the point midway between min and max - will only work\r\n   * for range constraints\r\n   *\r\n   * @return double\r\n   */\r\n  virtual double get_middle_point() = 0;\r\n};\r\n\r\n/**\r\n * A smart pointer to a Constraint\r\n */\r\nusing constraint_ptr = std::shared_ptr<constraint>;\r\n\r\n/**\r\n * Base class for constraints that are range based. Each such\r\n * constraint has a min and a max value\r\n */\r\nclass range_constraint : public constraint {\r\n private:\r\n  double m_min;\r\n  double m_max;\r\n\r\n public:\r\n  /**\r\n   * constructor that takes the min and max limits of the range\r\n   *\r\n   * @param min\r\n   * @param max\r\n   */\r\n  range_constraint(double min, double max) : m_min(min), m_max(max) {\r\n    assert(min <= max);\r\n  }\r\n\r\n  /**\r\n   * returns the min limit of the range\r\n   *\r\n   * @return double\r\n   */\r\n  double min() const { return m_min; }\r\n\r\n  /**\r\n   * returns the max limit of the range\r\n   *\r\n   * @return double\r\n   */\r\n  double max() const { return m_max; }\r\n};\r\n\r\n/**\r\n * A real constraint. Specifies that variables can have any\r\n * double value, within the specified limits.\r\n */\r\nclass real_constraint : public range_constraint {\r\n public:\r\n  /**\r\n   * constructor that takes the min and max limit of the real\r\n   * constraint\r\n   *\r\n   * @param min\r\n   * @param max\r\n   */\r\n  real_constraint(double min, double max) : range_constraint(min, max) {\r\n    assert(min <= max);\r\n  }\r\n\r\n  /**\r\n   * returns a random value limited to the type and range of the\r\n   * constraint\r\n   *\r\n   * @return double\r\n   */\r\n  double get_rand_value() {\r\n    return genrand(range_constraint::min(), range_constraint::max());\r\n  }\r\n\r\n  /**\r\n   * returns a random value limited to the type and range of the\r\n   * constraint based on a previous value and an origin\r\n   *\r\n   * @param value\r\n   * @param origin\r\n   *\r\n   * @return double\r\n   */\r\n  double get_rand_value(double value, double origin) {\r\n    double ret = value;\r\n\r\n    while (ret < range_constraint::min()) {\r\n      ret = range_constraint::min() + genrand() * (origin - range_constraint::min());\r\n    }\r\n\r\n    while (ret > range_constraint::max()) {\r\n      ret = range_constraint::max() + genrand() * (origin - range_constraint::max());\r\n    }\r\n\r\n    return ret;\r\n  }\r\n\r\n  double get_rand_value_in_zone(double origin, double zonePct) const override {\r\n    if (origin > max()) {\r\n      throw constraints_exception(\"origin coordinate > max\");\r\n    }\r\n\r\n    if (origin < min()) {\r\n      throw constraints_exception(\"origin coordinate < min\");\r\n    }\r\n\r\n    if (zonePct > 100.0) {\r\n      throw constraints_exception(\"zonePct > 100%\");\r\n    }\r\n\r\n    if (zonePct < 0) {\r\n      throw constraints_exception(\"zonePct < 0%\");\r\n    }\r\n\r\n    if (zonePct == 0) {\r\n      throw constraints_exception(\"zonePct == 0%\");\r\n    }\r\n\r\n    double zoneSize = (max() - min()) * zonePct / 100.0;\r\n\r\n    double _min = std::max(min(), origin - zoneSize / 2.0);\r\n    double _max = std::min(max(), origin + zoneSize / 2.0);\r\n\r\n    return genrand(_min, _max);\r\n  }\r\n\r\n  double get_middle_point() override { return (max() + min()) / 2.0; }\r\n};\r\n\r\n/**\r\n * An integer constraint. Specifies that variables can have any\r\n * integer values within the specified limits.\r\n */\r\nclass int_constraint : public range_constraint {\r\n public:\r\n  /**\r\n   * constructor that takes the min and max limit of the integer\r\n   * constraint\r\n   *\r\n   * @param min\r\n   * @param max\r\n   */\r\n  int_constraint(double min, double max) : range_constraint(min, max) {\r\n    assert(min <= max);\r\n  }\r\n\r\n  /**\r\n   * returns a random value limited to the type and range of the\r\n   * constraint\r\n   *\r\n   * @return double\r\n   */\r\n  double get_rand_value() {\r\n    return genintrand(range_constraint::min(), range_constraint::max());\r\n  }\r\n\r\n  /**\r\n   * returns a random value limited to the type and range of the\r\n   * constraint based on a previous value and an origin\r\n   *\r\n   * @param value\r\n   * @param origin\r\n   *\r\n   * @return double\r\n   */\r\n  double get_rand_value(double value, double origin) {\r\n    double ret = boost::math::round(value);\r\n\r\n    while (ret < range_constraint::min()) {\r\n      ret = range_constraint::min() + genrand() * (origin - range_constraint::min());\r\n      ret = boost::math::round(ret);\r\n    }\r\n\r\n    while (ret > range_constraint::max()) {\r\n      ret = range_constraint::max() + genrand() * (origin - range_constraint::max());\r\n      ret = boost::math::round(ret);\r\n    }\r\n\r\n    return ret;\r\n  }\r\n\r\n  virtual double get_rand_value_in_zone(double origin, double zonePct) const {\r\n    if (origin > max()) {\r\n      throw constraints_exception(\"origin coordinate > max\");\r\n    }\r\n\r\n    if (origin < min()) {\r\n      throw constraints_exception(\"origin coordinate < min\");\r\n    }\r\n\r\n    if (zonePct > 100.0) {\r\n      throw constraints_exception(\"zonePct > 100%\");\r\n    }\r\n\r\n    if (zonePct < 0) {\r\n      throw constraints_exception(\"zonePct < 0%\");\r\n    }\r\n\r\n    if (zonePct == 0) {\r\n      throw constraints_exception(\"zonePct == 0%\");\r\n    }\r\n\r\n    double zoneSize = (max() - min()) * zonePct / 100.0;\r\n\r\n    double _min = std::max(min(), origin - zoneSize / 2.0);\r\n    double _max = std::min(max(), origin + zoneSize / 2.0);\r\n\r\n    double val = boost::math::round(genrand(_min, _max));\r\n\r\n    while (val < _min || val > _max) {\r\n      val = boost::math::round(genrand(_min, _max));\r\n    }\r\n\r\n    return val;\r\n  }\r\n\r\n  virtual double get_middle_point() {\r\n    return boost::math::round((max() - min()) / 2.0);\r\n  }\r\n};\r\n\r\n/**\r\n * A set constraint. Specifies that variables can take any\r\n * values from a predefined set. Doesn't require min or max.\r\n *\r\n * Note that duplicate values will be removed\r\n */\r\nclass set_constraint : public constraint {\r\n private:\r\n  class unique : public std::unary_function<double, bool> {\r\n   public:\r\n    bool operator()(double d) const { return m_unique.insert(d).second; }\r\n\r\n   public:\r\n    double min() const {\r\n      if (m_unique.size() > 0) {\r\n        return *m_unique.begin();\r\n      }\r\n      else {\r\n        throw constraints_exception(\"could not get the min value of an empty set constraint\");\r\n      }\r\n    }\r\n\r\n    double max() const {\r\n      if (m_unique.size() > 0) {\r\n        return *m_unique.rbegin();\r\n      }\r\n      else {\r\n        throw constraints_exception(\"could not get the max value of an empty set constraint\");\r\n      }\r\n    }\r\n\r\n   private:\r\n    mutable std::set<double> m_unique;\r\n  };\r\n\r\n private:\r\n  unique m_unique;\r\n  de::DVector m_values;\r\n\r\n public:\r\n  /**\r\n   * Constructs the set from a vector of Double values, and\r\n   * removes duplicates to ensure a uniform distribution for\r\n   * randomization\r\n   *\r\n   * @param values\r\n   */\r\n  set_constraint(const de::DVector& values) {\r\n    // making sure the values in the \"set\" are unique\r\n    std::remove_copy_if(values.begin(), values.end(), std::back_inserter(m_values), m_unique);\r\n  }\r\n\r\n  /**\r\n   * adds an individual value to the \"set\", won't create duplicate\r\n   * values.\r\n   *\r\n   * @param value\r\n   */\r\n  void add_value(double value) {\r\n    if (m_unique(value)) {\r\n      m_values.push_back(value);\r\n    }\r\n  }\r\n\r\n  /**\r\n   * returns a value randomly chosen from the set of available\r\n   * values\r\n   *\r\n   * @return double\r\n   */\r\n  virtual double get_rand_value() {\r\n    de::DVector::size_type index(genintrand(0, m_values.size() - 1));\r\n\r\n    return m_values[index];\r\n  }\r\n\r\n  /**\r\n   * returns a value randomly chosen from the set of available\r\n   * values\r\n   *\r\n   * @return double\r\n   */\r\n  virtual double get_rand_value(double value, double origin) {\r\n    return get_rand_value();\r\n  }\r\n\r\n  /**\r\n   * returns the min limit of the range\r\n   *\r\n   * @return double\r\n   */\r\n  double min() const { return m_unique.min(); }\r\n\r\n  /**\r\n   * returns the max limit of the range\r\n   *\r\n   * @return double\r\n   */\r\n  double max() const { return m_unique.max(); }\r\n\r\n  virtual double get_rand_value_in_zone(double origin, double zonePct) const {\r\n    throw constraints_exception(\"get_rand_value_in_zone only supported for range constraints\");\r\n  }\r\n\r\n  virtual double get_middle_point() {\r\n    throw constraints_exception(\"get_middle_point not supported by set constraint\");\r\n  }\r\n};\r\n\r\n/**\r\n * A boolean constraint. Specifies that variables can take a\r\n * boolean value - true or false.\r\n */\r\nclass boolean_constraint : public constraint {\r\n public:\r\n  /**\r\n   * returns a random boolean value\r\n   *\r\n   * @return double\r\n   */\r\n  virtual double get_rand_value() { return genrand() < 0.5; }\r\n\r\n  /**\r\n   * returns a random boolean value\r\n   *\r\n   * @return double\r\n   */\r\n  virtual double get_rand_value(double value, double origin) {\r\n    return get_rand_value();\r\n  }\r\n\r\n  /**\r\n   * returns the min limit of the range\r\n   *\r\n   * @return double\r\n   */\r\n  double min() const { return 0; }\r\n\r\n  /**\r\n   * returns the max limit of the range\r\n   *\r\n   * @return double\r\n   */\r\n  double max() const { return 1; }\r\n\r\n  virtual double get_rand_value_in_zone(double origin, double zonePct) const {\r\n    throw constraints_exception(\"get_rand_value_in_zone only supported for range constraints\");\r\n  }\r\n\r\n  virtual double get_middle_point() {\r\n    throw constraints_exception(\"get_middle_point not supported by bool constraint\");\r\n  }\r\n};\r\n\r\nusing constraints_base = std::vector<constraint_ptr>;\r\n\r\n/**\r\n * A collection of constraints, implemented as a vector.\r\n *\r\n * Is used to define the constraints for all variables used\r\n * during an optimization session.\r\n */\r\nclass constraints : public constraints_base {\r\n private:\r\n  using separator = boost::char_separator<char>;\r\n  using tokenizer = boost::tokenizer<separator>;\r\n\r\n public:\r\n  /**\r\n   * Initializes a collection of constraints with default values.\r\n   * All constraints are of type real and have the same default\r\n   * min and max.\r\n   *\r\n   * @param varCount number of constraints\r\n   * @param defMin default min limit\r\n   * @param defMax default max limit\r\n   */\r\n  constraints(size_t varCount, double defMin, double defMax)\r\n      : constraints_base(varCount, std::make_shared<real_constraint>(defMin, defMax)) {}\r\n\r\n  /**\r\n   * Initializes a collection of constraints from string\r\n   * descriptions. Currently used only for range based\r\n   * constraints.\r\n   *\r\n   * A constraint can be described as \"type;min;max\" where type\r\n   * can be real or integer and min and max are the range limits.\r\n   *\r\n   * @param str a collection (vector) of constraint description\r\n   *  \t\t  strings, each string describing constraints for\r\n   *  \t\t  one variable\r\n   * @param var_count the total number of variables (can be\r\n   *  \t\t\t   different than the number of strings). If\r\n   *  \t\t\t   there are more variables than strings, the\r\n   *  \t\t\t   extra constraints are set to be real and use\r\n   *  \t\t\t   the default min and max arguments for the\r\n   *  \t\t\t   range\r\n   * @param def_min default min value in case the number of\r\n   *  \t\t\t variables is higher than the number of\r\n   *  \t\t\t constraints specified as strings.\r\n   * @param def_max default max value in case the number of\r\n   *  \t\t\t variables is higher than the number of\r\n   *  \t\t\t constraints specified as strings.\r\n   */\r\n  constraints(const std::vector<std::string>& str, size_t var_count, double def_min, double def_max)\r\n      : constraints_base( var_count, std::make_shared<real_constraint>(def_min, def_max)) {\r\n    for (std::vector<std::string>::size_type i = 0; i < str.size(); ++i) {\r\n      tokenizer tokens(str[i], separator(\":;,\"));\r\n\r\n      std::string type;\r\n      double _min;\r\n      double _max;\r\n\r\n      size_t count(0);\r\n\r\n      for (tokenizer::const_iterator j = tokens.begin(); j != tokens.end(); ++j, ++count) {\r\n        const std::string token(boost::trim_copy(*j));\r\n\r\n        try {\r\n          switch (count) {\r\n            case 0:\r\n              type = token;\r\n              break;\r\n            case 1:\r\n              _min = boost::lexical_cast<double>(token.c_str());\r\n              break;\r\n            case 2:\r\n              _max = boost::lexical_cast<double>(token.c_str());\r\n              break;\r\n            default:\r\n              // too many fields\r\n              throw constraints_exception((boost::format(\"wrong variable format in \\\"%1%\\\" - too many fields\") % str[i]) .str());\r\n          }\r\n        }\r\n        catch (const boost::bad_lexical_cast&) {\r\n          throw constraints_exception((boost::format(\"wrong floating point number format: %1%\") % token).str());\r\n        }\r\n      }\r\n\r\n      // too few fields\r\n      if (count < 3) {\r\n        throw constraints_exception((boost::format(\"wrong variable format in \\\"%1%\\\" - too few fields\") % str[i]).str());\r\n      }\r\n\r\n      if (i < var_count) {\r\n        constraints_base::at(i) = str_to_constraint(type, _min, _max);\r\n      }\r\n      else {\r\n        constraints_base::push_back(str_to_constraint(type, _min, _max));\r\n      }\r\n    }\r\n  }\r\n\r\n  /**\r\n   * returns a random value limited to the type and range of the\r\n   * constraint\r\n   *\r\n   * @return double\r\n   */\r\n  double get_rand_value(size_t index) const {\r\n    if (index < constraints_base::size()) {\r\n      return (*this)[index]->get_rand_value();\r\n    }\r\n    else {\r\n      throw constraints_exception((boost::format(\"invalid constraint index: %1%, higher than max number of constraints: %2%\") %\r\n          index % constraints_base::size()).str());\r\n    }\r\n  }\r\n\r\n  /**\r\n   * returns a random value limited to the type and range of the\r\n   * constraint based on a previous value and an origin\r\n   *\r\n   * @param index the constraint index\r\n   * @param value previous value\r\n   * @param origin origin\r\n   *\r\n   * @return double\r\n   */\r\n  double get_rand_value(size_t index, double value, double origin) const {\r\n    if (index < constraints_base::size()) {\r\n      return (*this)[index]->get_rand_value(value, origin);\r\n    }\r\n    else {\r\n      throw constraints_exception((boost::format(\"invalid constraint index: %1%, higher than max number of constraints: %2%\") %\r\n        index % constraints_base::size()).str());\r\n    }\r\n  }\r\n\r\n  /**\r\n   * Generates a set of random values within a \"hypercube\" region\r\n   * defined by an origin and an area expressed as a percentage of\r\n   * the entire range\r\n   *\r\n   * @param origin the origin coordinates of the region\r\n   * @param sidePct the side of the hypercube in pct of the entire\r\n   *  \t\t\t  side\r\n   *\r\n   * @return DVectorPtr\r\n   */\r\n  DVectorPtr get_square_zone_rand_values(const DVectorPtr origin, double sidePct) const {\r\n    assert(origin);\r\n    assert(sidePct > 0 && sidePct <= 100);\r\n\r\n    if (origin->size() == constraints_base::size()) {\r\n      DVectorPtr square(std::make_shared<DVector>(origin->size()));\r\n\r\n      for (constraints_base::size_type n = 0; n < constraints_base::size(); ++n)\r\n        (*square)[n] = (*this)[n]->get_rand_value_in_zone((*origin)[n], sidePct);\r\n\r\n      return square;\r\n\r\n    }\r\n    else {\r\n      throw constraints_exception(\"The origin vector must have the same number of elements as there are constraints\");\r\n    }\r\n  }\r\n\r\n  DVectorPtr get_middle_point() {\r\n    DVectorPtr r(std::make_shared<DVector>(constraints_base::size()));\r\n\r\n    for (constraints_base::size_type n = 0; n < constraints_base::size(); ++n)\r\n      (*r)[n] = (*this)[n]->get_middle_point();\r\n\r\n    return r;\r\n  }\r\n\r\n  /**\r\n   * Get a set of random values within the limits set by the\r\n   * constraints\r\n   *\r\n   * @return DVectorPtr\r\n   */\r\n  DVectorPtr get_rand_values() const {\r\n    DVectorPtr r(std::make_shared<DVector>(constraints_base::size()));\r\n\r\n    for (constraints_base::size_type n = 0; n < constraints_base::size(); ++n)\r\n      (*r)[n] = (*this)[n]->get_rand_value();\r\n\r\n    return r;\r\n  }\r\n\r\n private:\r\n  constraint_ptr str_to_constraint(const std::string& type, double min, double max) {\r\n    if (boost::to_lower_copy(type) == \"real\") {\r\n      return std::make_shared<real_constraint>(min, max);\r\n    }\r\n    else if (boost::to_lower_copy(type) == \"int\" || boost::to_lower_copy(type) == \"integer\") {\r\n      return std::make_shared<int_constraint>(min, max);\r\n    }\r\n    else {\r\n      throw constraints_exception((boost::format(\"invalid constraint type \\\"%1%\\\"\") % type).str());\r\n    }\r\n  }\r\n};\r\n\r\nusing constraints_ptr = std::shared_ptr<constraints>;\r\n}  // namespace de\r\n}  // namespace amichel\r\n", "meta": {"hexsha": "523eae8d9a9953065d5b49b2d40c39a17a7615e3", "size": 18544, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "differentialevolution/de_constraints.hpp", "max_stars_repo_name": "adrianmichel/differential-evolution", "max_stars_repo_head_hexsha": "ec20399c542bfcb3637c05244e7e24abfd05d3c9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 17.0, "max_stars_repo_stars_event_min_datetime": "2019-03-14T03:14:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-18T06:59:21.000Z", "max_issues_repo_path": "differentialevolution/de_constraints.hpp", "max_issues_repo_name": "adrianmichel/differential-evolution", "max_issues_repo_head_hexsha": "ec20399c542bfcb3637c05244e7e24abfd05d3c9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-08-05T02:41:35.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-21T20:55:31.000Z", "max_forks_repo_path": "differentialevolution/de_constraints.hpp", "max_forks_repo_name": "adrianmichel/differential-evolution", "max_forks_repo_head_hexsha": "ec20399c542bfcb3637c05244e7e24abfd05d3c9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 14.0, "max_forks_repo_forks_event_min_datetime": "2017-11-18T15:47:18.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-07T00:41:29.000Z", "avg_line_length": 27.0715328467, "max_line_length": 130, "alphanum_fraction": 0.6150776531, "num_tokens": 4429, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.31331261199117677}}
{"text": "/*-------------HO.cpp---------------------------------------------------------//\n*\n*              HO.cpp -- Diffusion Monte Carlo for Schroedy\n*\n* Purpose: Implement the quantum Monte Carlo (diffusion) by Kosztin:\n*          http://www.thphys.uni-heidelberg.de/~wetzel/qmc2006/KOSZ96.pdf\n*\n*    Note: This algorithm may be improved by later work\n*          A \"psip\" is an imaginary configuration of electrons in space.\n*          Requires c++11 for random and Eigen for matrix\n*          Protons assume to be at origin\n*          A lot of this algorithm is more easily understood here:\n*              http://www.thphys.uni-heidelberg.de/~wetzel/qmc2006/KOSZ96.pdf\n*\n*-----------------------------------------------------------------------------*/\n\n#include <iostream>\n#include <random>\n#include <Eigen/Core>\n#include <fstream>\n\n#define DOF 1\n#define SIZE 2000\n#define DIMS (DOF + 2)\n#define binnum 40\n\ntypedef Eigen::Matrix<double, // typename Scalar\n   SIZE, // int RowsAtCompileTime,\n   DIMS, // int ColsAtCompileTime,\n   0> // int Options = 0,\n   MatrixPSIP;\n\nstruct H3plus { \n    MatrixPSIP pos;\n    double Vref, dt, Energy;\n    int psipnum, id;\n    std::vector<int> bins = std::vector<int>(binnum, 0);;\n};\n\n// Populate a distribution of particles for QMC\nvoid populate(H3plus& state);\n\n// Calculates energy of a configuration and stores it into the final element of \n// the MatrixPSIP\nvoid find_weights(H3plus& state);\n\n// Branching scheme\nvoid branch(H3plus& state);\n\n// Random walking of matrix of position created in populate\nvoid diffuse(H3plus& state, std::ostream& output);\n\n// Adding function to bin data into wavefunction\nvoid bin(H3plus& state, std::ostream& output);\n\n// output certain elements in array\nvoid arrayout(H3plus& state, int length);\n\n/*----------------------------------------------------------------------------//\n* MAIN\n*-----------------------------------------------------------------------------*/\n\nint main(){\n\n    std::ofstream output(\"out.dat\", std::ostream::out);\n    H3plus state;\n\n    state.Vref = 0;\n    state.dt = 0.1;\n    state.psipnum = 100;\n    state.Energy = 0;\n    state.id = 0;\n\n    populate(state);\n\n    std::cout << state.Vref << '\\t' << state.psipnum << '\\n';\n\n    /*\n    for (size_t i = 0; i < state.psipnum; i++){\n        std::cout << \" final element is: \" << state.pos(i,DIMS-2) << '\\n';\n    }\n    */\n\n    diffuse(state, output);\n\n    //output << state.pos << '\\n';\n\n}\n\n/*----------------------------------------------------------------------------//\n* SUBROUTINES\n*-----------------------------------------------------------------------------*/\n\n// Populate a distribution of particles for QMC\n// Unlike Anderson, we are initilizing each psip randomly from a distribution.\n// This might scre things up, because\nvoid populate(H3plus& state){\n\n    std::default_random_engine generator;\n    std::uniform_real_distribution<double> distribution(-1.0,1.0);\n\n    for (size_t i = 0; i < state.psipnum; i++){\n        state.pos(i,0) = 0;\n        state.pos(i,DIMS-1) = state.id;\n        state.id++;\n    }\n\n    find_weights(state);\n\n    /*\n    for (size_t i = 0; i < state.psipnum; i++){\n        std::cout << state.pos(i,DIMS-2) << '\\n';\n    }\n    */\n\n}\n\n// Calculates energy of a configuration and stores it into the final element of \n// the MatrixPSIP\n// Note: When calculating the potential, I am not sure whether we need to use\n//       absolute value of distance or the distance, itself.\n// Note: Inefficient. Can calculate energy on the fly with every generation of \n//       psip. Think about it.\n// Note: Vref will be a dummy variable for now.\nvoid find_weights(H3plus& state){\n\n    double dist, pot, pot_tot = 0;\n\n    std::default_random_engine gen;\n    std::uniform_real_distribution<double> distribution(0,1);\n\n\n    // Note that this is specific to the Anderson paper\n    // Finding the distance between electrons, then adding the distances\n    // from the protons to the electrons.\n    for (size_t i = 0; i < state.psipnum; i++){\n        pot = 0.5 * state.pos(i,0) * state.pos(i,0);\n        state.pos(i,DIMS-2) = pot;\n\n        pot_tot += pot;\n\n    }\n\n    // defining the new reference potential to psipnum down.\n    state.Energy = pot_tot / state.psipnum;\n    state.Vref = state.Energy\n                 - ((state.psipnum - 1000) / (1000 * state.dt));\n\n    for (size_t i = 0; i < state.psipnum; i++){\n        state.pos(i,DIMS-2) = (int)(1-(state.pos(i,DIMS-2) - state.Vref) \n                                    * state.dt\n                              + distribution(gen));\n        if (state.pos(i,DIMS-2) > 3){\n            state.pos(i,DIMS-2) = 3;\n        }\n\n    }\n}\n\n// Branching scheme\nvoid branch(H3plus& state){\n\n    find_weights(state);\n\n    /*\n    for (size_t i = 0; i < state.psipnum; i++){\n        std::cout << state.pos(i,DIMS-2) << '\\n';\n    }\n    */\n\n    int variable, offset = 0, psip_old = state.psipnum, births = 0, tmpi = 0;\n\n    for (size_t i = 0; i < psip_old + births; i++){\n\n        //std::cout << i << '\\n';\n\n        variable = state.pos(i, DIMS-2);\n\n        switch (variable){\n            // Destruction\n            case 0: state.psipnum--;\n                    break;\n\n            // Creation of 1\n            case 2: state.psipnum++;\n                    births++;\n                    for (size_t j = 0; j < state.pos.cols() - 2; j++){\n                        state.pos(psip_old+births-1,j) = state.pos(i,j);\n                    }\n                    //std::cout << \"writing: \" << i << \" to \" \n                    //          << psip_old+births-1 << '\\n';\n                    state.pos(psip_old+births-1,DIMS-2) = 1;\n                    state.pos(psip_old+births-1,DIMS-1) = state.id;\n                    state.id++;\n                    break;\n\n            // Creation of 2\n            case 3: state.psipnum += 2;\n                    births += 2;\n                    for (size_t k = 0; k < 2; k++){\n                        for (size_t j = 0; j < state.pos.cols() - 2; j++){\n                            state.pos(psip_old-k+births-1, j) = state.pos(i, j);\n                            //std::cout << state.pos(psip_old-k+births-1, j) \n                            //          << '\\n';\n                        }\n                        state.pos(psip_old-k+births-1,DIMS-2) = 1;\n                        state.pos(psip_old-k+births-1,DIMS-1) = state.id;\n                        state.id++;\n                        //std::cout << \"writing: \" << i << \" to \" \n                        //          << psip_old-k+births-1 << '\\n';\n                    }\n                    break;\n\n        }\n\n    }\n\n    //arrayout(state, state.psipnum);\n\n    // Adjustment for offset\n    // Note: Account for the situation where offset is greater than arraysize\n    for (size_t i = 0; i < SIZE; i++){\n        if (state.pos(i,DIMS-2) != 0){\n            for (size_t j = 0; j < state.pos.cols(); j++){\n                state.pos(tmpi,j) = state.pos(i,j);\n            }\n            tmpi++;\n        }\n        if (i > state.psipnum){\n            for (size_t j = 0; j < state.pos.cols(); j++){\n                state.pos(i,j) = 0;\n            }\n\n        }\n    }\n\n}\n\n// Random walking of matrix of position created in populate\n// Step 1: Move particles via 6D random walk\n// Step 2: Destroy and create particles as need based on Anderson\n// Step 3: check energy, end if needed.\nvoid diffuse(H3plus& state, std::ostream& output){\n\n    // Let's initialize the randomness\n    std::default_random_engine gen;\n    std::normal_distribution<double> gaussian(0,1);\n\n    double diff = 1, Vsave = 0, tmpbin, x;\n    int wavenum = 1000;\n\n    for (size_t k = 0; k < wavenum; k++){\n        // For now, I am going to set a definite number of timesteps\n        // This will be replaced by a while loop in the future.\n        for (size_t t = 0; t < 100; t++){\n        //while (diff > 0.01){\n            Vsave = state.Vref;\n            #pragma omp parallel for \n            for (size_t i = 0; i < state.psipnum; i++){\n                for (size_t j = 0; j < state.pos.cols() - 1; j++){\n                    state.pos(i, j) += sqrt(state.dt) * gaussian(gen);\n                }\n            }\n            branch(state);\n            diff = sqrt((Vsave - state.Vref)*(Vsave - state.Vref));\n            std::cout << state.Vref << '\\t' << state.psipnum << '\\n';\n        }\n\n        bin(state, output);\n    }\n\n    for (size_t i = 0; i < binnum; i++){\n        tmpbin = state.bins[i] * 0.0001;\n        output << tmpbin << '\\n';\n    }\n\n    output << '\\n' << '\\n';\n\n    for (size_t i = 0; i < binnum; i++){\n        x = ((double)i / (double)binnum)*8.0 - 4.0;\n        std::cout << x << '\\n';\n        tmpbin = exp(- x*x / 2);\n        output << tmpbin << '\\n';\n    }\n\n\n}\n\n// Adding function to bin data into wavefunction\nvoid bin(H3plus& state, std::ostream& output){\n\n    double bound = 4, max = bound, min = -bound;\n\n    for (size_t i = 0; i < state.psipnum; i++){\n        for (size_t j = 0; j < binnum; j++){\n            if (state.pos(i,0) >= ((max - min) / binnum) * j  - bound&&\n                state.pos(i,0) < ((max - min) / binnum) * (j+1) - bound){\n                state.bins[j] += 1;\n            }\n        }\n    }\n\n}\n\n// output certain elements in array\nvoid arrayout(H3plus& state, int length){\n\n    for (size_t i = 0; i < length; i++){\n        for (size_t j  = 0; j < 2; j++){\n            std::cout << state.pos(i,DIMS - 1 - j) << '\\t';\n        }\n        std::cout << '\\n';\n    } \n}\n", "meta": {"hexsha": "0cdbda5d9a032407bb082c9d9903a58f91131061", "size": 9396, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "QMC/HO.cpp", "max_stars_repo_name": "mika314/simuleios", "max_stars_repo_head_hexsha": "0b05660c7df0cd6e31eb5e70864cbedaec29b55a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 197.0, "max_stars_repo_stars_event_min_datetime": "2015-07-26T02:04:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-21T11:53:33.000Z", "max_issues_repo_path": "QMC/HO.cpp", "max_issues_repo_name": "shiffman/simuleios", "max_issues_repo_head_hexsha": "57239350d2cbed10893483bda65fa323e5e3a06d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 18.0, "max_issues_repo_issues_event_min_datetime": "2015-08-04T22:55:46.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-06T02:33:48.000Z", "max_forks_repo_path": "QMC/HO.cpp", "max_forks_repo_name": "shiffman/simuleios", "max_forks_repo_head_hexsha": "57239350d2cbed10893483bda65fa323e5e3a06d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 55.0, "max_forks_repo_forks_event_min_datetime": "2015-08-02T21:43:18.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-13T18:25:08.000Z", "avg_line_length": 29.8285714286, "max_line_length": 80, "alphanum_fraction": 0.5, "num_tokens": 2488, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7690802370707283, "lm_q2_score": 0.40733340004593027, "lm_q1q2_score": 0.31327206787414985}}
{"text": "#include <iostream>\n#include <string>\n\n#include <boost/program_options.hpp>\n#include <boost/property_tree/ptree.hpp>\n#include <boost/property_tree/json_parser.hpp>\n#include <boost/preprocessor/seq/for_each.hpp>\n\n#if defined(SOLVER_BACKEND_VEXCL)\n#  include <amgcl/backend/vexcl.hpp>\n   typedef amgcl::backend::vexcl<double> Backend;\n#elif defined(SOLVER_BACKEND_VIENNACL)\n#  include <amgcl/backend/viennacl.hpp>\n   typedef amgcl::backend::viennacl< viennacl::compressed_matrix<double> > Backend;\n#elif defined(SOLVER_BACKEND_CUDA)\n#  include <amgcl/backend/cuda.hpp>\n#  include <amgcl/relaxation/cusparse_ilu0.hpp>\n   typedef amgcl::backend::cuda<double> Backend;\n#else\n#  ifndef SOLVER_BACKEND_BUILTIN\n#    define SOLVER_BACKEND_BUILTIN\n#  endif\n#  include <amgcl/backend/builtin.hpp>\n#  include <amgcl/value_type/static_matrix.hpp>\n#  include <amgcl/adapter/block_matrix.hpp>\n#  include <amgcl/make_block_solver.hpp>\n   typedef amgcl::backend::builtin<double> Backend;\n#endif\n\n#include <amgcl/make_solver.hpp>\n#include <amgcl/amg.hpp>\n#include <amgcl/solver/runtime.hpp>\n#include <amgcl/coarsening/runtime.hpp>\n#include <amgcl/relaxation/runtime.hpp>\n#include <amgcl/preconditioner/schur_pressure_correction.hpp>\n#include <amgcl/preconditioner/runtime.hpp>\n#include <amgcl/adapter/crs_tuple.hpp>\n\n#include <amgcl/io/mm.hpp>\n#include <amgcl/io/binary.hpp>\n#include <amgcl/profiler.hpp>\n\n#ifndef AMGCL_BLOCK_SIZES\n#  define AMGCL_BLOCK_SIZES (3)(4)\n#endif\n\nnamespace amgcl { profiler<> prof; }\nusing amgcl::prof;\nusing amgcl::precondition;\n\ntemplate <class USolver, class PSolver, class Matrix>\ntypename std::enable_if<\n    (\n        amgcl::math::static_rows<\n            typename amgcl::preconditioner::detail::common_backend<\n                typename USolver::backend_type,\n                typename PSolver::backend_type\n            >::type::value_type\n        >::value > 1\n    ),\n    void\n    >::type\nsolve_schur(const Matrix&, const std::vector<double>&, boost::property_tree::ptree&)\n{}\n\n//---------------------------------------------------------------------------\ntemplate <class USolver, class PSolver, class Matrix>\ntypename std::enable_if<\n    (\n        amgcl::math::static_rows<\n            typename amgcl::preconditioner::detail::common_backend<\n                typename USolver::backend_type,\n                typename PSolver::backend_type\n            >::type::value_type\n        >::value == 1\n    ),\n    void>::type\nsolve_schur(const Matrix &K, const std::vector<double> &rhs, boost::property_tree::ptree &prm)\n{\n    Backend::params bprm;\n\n#if defined(SOLVER_BACKEND_VEXCL)\n    vex::Context ctx(vex::Filter::Env);\n    std::cout << ctx << std::endl;\n    bprm.q = ctx;\n#elif defined(SOLVER_BACKEND_VIENNACL)\n    std::cout\n        << viennacl::ocl::current_device().name()\n        << \" (\" << viennacl::ocl::current_device().vendor() << \")\\n\\n\";\n#elif defined(SOLVER_BACKEND_CUDA)\n    cusparseCreate(&bprm.cusparse_handle);\n    {\n        int dev;\n        cudaGetDevice(&dev);\n\n        cudaDeviceProp prop;\n        cudaGetDeviceProperties(&prop, dev);\n        std::cout << prop.name << std::endl << std::endl;\n    }\n#endif\n\n    auto t1 = prof.scoped_tic(\"schur_complement\");\n\n    prof.tic(\"setup\");\n    amgcl::make_solver<\n        amgcl::preconditioner::schur_pressure_correction<USolver, PSolver>,\n        amgcl::runtime::solver::wrapper<Backend>\n        > solve(K, prm, bprm);\n    prof.toc(\"setup\");\n\n    std::cout << solve.precond() << std::endl;\n\n    auto f = Backend::copy_vector(rhs, bprm);\n    auto x = Backend::create_vector(rhs.size(), bprm);\n    amgcl::backend::clear(*x);\n\n    size_t iters;\n    double error;\n\n    prof.tic(\"solve\");\n    std::tie(iters, error) = solve(*f, *x);\n    prof.toc(\"solve\");\n\n    std::cout << \"Iterations: \" << iters << std::endl\n              << \"Error:      \" << error << std::endl;\n}\n\n#define AMGCL_BLOCK_PSOLVER(z, data, B)                                        \\\n  case B: {                                                                    \\\n    typedef amgcl::backend::builtin<amgcl::static_matrix<double, B, B> >       \\\n        BBackend;                                                              \\\n    typedef amgcl::make_block_solver<                                          \\\n        amgcl::runtime::preconditioner<BBackend>,                              \\\n        amgcl::runtime::solver::wrapper<BBackend> >                            \\\n        PSolver;                                                               \\\n    solve_schur<USolver, PSolver>(K, rhs, prm);                                \\\n  } break;\n\n//---------------------------------------------------------------------------\ntemplate <class USolver, class Matrix>\nvoid solve_schur(int pb, const Matrix &K, const std::vector<double> &rhs, boost::property_tree::ptree &prm)\n{\n    switch (pb) {\n        case 1:\n            {\n                typedef\n                    amgcl::make_solver<\n                        amgcl::runtime::preconditioner<Backend>,\n                        amgcl::runtime::solver::wrapper<Backend>\n                        >\n                    PSolver;\n                solve_schur<USolver, PSolver>(K, rhs, prm);\n            }\n            break;\n#if defined(SOLVER_BACKEND_BUILTIN)\n        BOOST_PP_SEQ_FOR_EACH(AMGCL_BLOCK_PSOLVER, ~, AMGCL_BLOCK_SIZES)\n#endif\n        default:\n            precondition(false, \"Unsupported block size for pressure\");\n    }\n}\n\n#define AMGCL_BLOCK_USOLVER(z, data, B)                                        \\\n  case B: {                                                                    \\\n    typedef amgcl::backend::builtin<amgcl::static_matrix<double, B, B> >       \\\n        BBackend;                                                              \\\n    typedef amgcl::make_block_solver<                                          \\\n        amgcl::runtime::preconditioner<BBackend>,                              \\\n        amgcl::runtime::solver::wrapper<BBackend> >                            \\\n        USolver;                                                               \\\n    solve_schur<USolver>(pb, K, rhs, prm);                                     \\\n  } break;\n\n//---------------------------------------------------------------------------\ntemplate <class Matrix>\nvoid solve_schur(int ub, int pb, const Matrix &K, const std::vector<double> &rhs, boost::property_tree::ptree &prm)\n{\n    precondition(ub == 1 || pb == 1,\n            \"At least one of the flow/pressure subproblems has to be scalar\");\n\n    switch (ub) {\n        case 1:\n            {\n                typedef\n                    amgcl::make_solver<\n                        amgcl::runtime::preconditioner<Backend>,\n                        amgcl::runtime::solver::wrapper<Backend>\n                        >\n                    USolver;\n                solve_schur<USolver>(pb, K, rhs, prm);\n            }\n            break;\n#if defined(SOLVER_BACKEND_BUILTIN)\n        BOOST_PP_SEQ_FOR_EACH(AMGCL_BLOCK_USOLVER, ~, AMGCL_BLOCK_SIZES)\n#endif\n        default:\n            precondition(false, \"Unsupported block size for flow\");\n    }\n}\n\n//---------------------------------------------------------------------------\nint main(int argc, char *argv[]) {\n    using std::string;\n    using std::vector;\n\n    namespace po = boost::program_options;\n    namespace io = amgcl::io;\n\n    po::options_description desc(\"Options\");\n\n    desc.add_options()\n        (\"help,h\", \"show help\")\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         \"matrix,A\",\n         po::value<string>()->required(),\n         \"The system matrix in MatrixMarket format\"\n        )\n        (\n         \"rhs,f\",\n         po::value<string>(),\n         \"The right-hand side in MatrixMarket format\"\n        )\n        (\n         \"pmask,m\",\n         po::value<string>(),\n         \"The pressure mask in MatrixMarket format. Or, if the parameter has \"\n         \"the form '%n:m', then each (n+i*m)-th variable is treated as pressure.\"\n        )\n        (\n         \"ub\",\n         po::value<int>()->default_value(1),\n         \"Block-size of the 'flow'/'non-pressure' part of the matrix\"\n        )\n        (\n         \"pb\",\n         po::value<int>()->default_value(1),\n         \"Block-size of the 'pressure' part of the matrix\"\n        )\n        (\n         \"params,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\n    po::variables_map vm;\n    po::store(po::parse_command_line(argc, argv, desc), vm);\n\n    if (vm.count(\"help\")) {\n        std::cout << desc << std::endl;\n        return 0;\n    }\n\n    po::notify(vm);\n\n    boost::property_tree::ptree prm;\n    if (vm.count(\"params\")) read_json(vm[\"params\"].as<string>(), prm);\n\n    if (vm.count(\"prm\")) {\n        for(const string &v : vm[\"prm\"].as<vector<string> >()) {\n            amgcl::put(prm, v);\n        }\n    }\n\n    size_t rows;\n    vector<ptrdiff_t> ptr, col;\n    vector<double> val, rhs;\n    std::vector<char> pm;\n\n    {\n        auto t = prof.scoped_tic(\"reading\");\n\n        string Afile  = vm[\"matrix\"].as<string>();\n        bool   binary = vm[\"binary\"].as<bool>();\n\n        if (binary) {\n            io::read_crs(Afile, rows, ptr, col, val);\n        } else {\n            size_t cols;\n            std::tie(rows, cols) = io::mm_reader(Afile)(ptr, col, val);\n            precondition(rows == cols, \"Non-square system matrix\");\n        }\n\n        if (vm.count(\"rhs\")) {\n            string bfile = vm[\"rhs\"].as<string>();\n\n            size_t n, m;\n\n            if (binary) {\n                io::read_dense(bfile, n, m, rhs);\n            } else {\n                std::tie(n, m) = io::mm_reader(bfile)(rhs);\n            }\n\n            precondition(n == rows && m == 1, \"The RHS vector has wrong size\");\n        } else {\n            rhs.resize(rows, 1.0);\n        }\n\n        if(vm.count(\"pmask\")) {\n            std::string pmask = vm[\"pmask\"].as<string>();\n            prm.put(\"precond.pmask_size\", rows);\n\n            switch (pmask[0]) {\n                case '%':\n                case '<':\n                case '>':\n                    prm.put(\"precond.pmask_pattern\", pmask);\n                    break;\n                default:\n                    {\n                        size_t n, m;\n\n                        if (binary) {\n                            io::read_dense(pmask, n, m, pm);\n                        } else {\n                            std::tie(n, m) = amgcl::io::mm_reader(pmask)(pm);\n                        }\n\n                        precondition(n == rows && m == 1, \"Mask file has wrong size\");\n\n                        prm.put(\"precond.pmask\", static_cast<void*>(&pm[0]));\n                    }\n            }\n        }\n    }\n\n    solve_schur(vm[\"ub\"].as<int>(), vm[\"pb\"].as<int>(),\n            std::tie(rows, ptr, col, val), rhs, prm);\n\n    std::cout << prof << std::endl;\n}\n", "meta": {"hexsha": "380cc2ff25b13a01fa2e818ca34f85df3702344d", "size": 11285, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/schur_pressure_correction.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/schur_pressure_correction.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/schur_pressure_correction.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": 32.5216138329, "max_line_length": 115, "alphanum_fraction": 0.510677891, "num_tokens": 2662, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6261241772283034, "lm_q2_score": 0.5, "lm_q1q2_score": 0.3130620886141517}}
{"text": "/*\n    Copyright 2016 Emanuele Vespa, Imperial College London \n    Redistribution and use in source and binary forms, with or without\n    modification, are permitted provided that the following conditions are met:\n\n    1. Redistributions of source code must retain the above copyright notice, 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 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\" 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#ifndef OCTANT_OPS_HPP\n#define OCTANT_OPS_HPP\n#include \"utils/morton_utils.hpp\"\n#include \"utils/math_utils.h\"\n#include \"octree_defines.h\"\n#include <iostream>\n#include <bitset>\n#include <Eigen/Dense>\n\nnamespace se {\n  namespace keyops {\n\n    inline se::key_t code(const se::key_t key) {\n      return key & ~SCALE_MASK;\n    }\n\n    inline int level(const se::key_t key) {\n      return key & SCALE_MASK;\n}\n\n    inline se::key_t encode(const int x, const int y, const int z, \n        const int level, const int max_depth) {\n      const int offset = MAX_BITS - max_depth + level - 1;\n      return (compute_morton(x, y, z) & MASK[offset]) | level;\n    }\n\n    inline Eigen::Vector3i decode(const se::key_t key) {\n      return unpack_morton(key & ~SCALE_MASK);\n    }\n  }\n}\n\n/*\n * Algorithm 5 of p4est paper: https://epubs.siam.org/doi/abs/10.1137/100791634\n */\ninline Eigen::Vector3i face_neighbour(const se::key_t o, \n    const unsigned int face, const unsigned int l, \n    const unsigned int max_depth) {\n  Eigen::Vector3i coords = se::keyops::decode(o);\n  const unsigned int side = 1 << (max_depth - l); \n  coords(0) = coords(0) + ((face == 0) ? -side : (face == 1) ? side : 0);\n  coords(1) = coords(1) + ((face == 2) ? -side : (face == 3) ? side : 0);\n  coords(2) = coords(2) + ((face == 4) ? -side : (face == 5) ? side : 0);\n  return {coords(0), coords(1), coords(2)};\n}\n\n/*\n * \\brief Return true if octant is a descendant of ancestor\n * \\param octant \n * \\param ancestor \n * \\param max_depth max depth of the tree on which the octant lives\n */\ninline bool descendant(se::key_t octant, se::key_t ancestor, \n    const int max_depth) {\n  const int level = se::keyops::level(ancestor);\n  const int idx = MAX_BITS - max_depth + level - 1;\n  ancestor = se::keyops::code(ancestor);\n  octant = se::keyops::code(octant) & MASK[idx];\n  return (ancestor ^ octant) == 0;\n}\n\n/*\n * \\brief Computes the parent's morton code of a given octant\n * \\param octant\n * \\param max_depth max depth of the tree on which the octant lives\n */\ninline se::key_t parent(const se::key_t& octant, const int max_depth) {\n  const int level = se::keyops::level(octant) - 1;\n  const int idx = MAX_BITS - max_depth + level - 1;\n  return (octant & MASK[idx]) | level;\n}\n\n/*\n * \\brief Computes the octants's id in its local brotherhood\n * \\param octant\n * \\param level of octant \n * \\param max_depth max depth of the tree on which the octant lives\n */\ninline int child_id(se::key_t octant, const int level, \n    const int max_depth) {\n  int shift = max_depth - level;\n  octant = se::keyops::code(octant) >> shift*3;\n  int idx = (octant & 0x01) | (octant & 0x02) | (octant & 0x04);\n  return idx;\n}\n\n/*\n * \\brief Computes the octants's corner which is not shared with its siblings\n * \\param octant\n * \\param level of octant \n * \\param max_depth max depth of the tree on which the octant lives\n */\ninline Eigen::Vector3i far_corner(const se::key_t octant, const int level, \n    const int max_depth) {\n  const unsigned int side = 1 << (max_depth - level); \n  const int idx = child_id(octant, level, max_depth);\n  const Eigen::Vector3i coordinates = se::keyops::decode(octant);\n  return Eigen::Vector3i(coordinates(0) + (idx & 1) * side,\n                   coordinates(1) + ((idx & 2) >> 1) * side,\n                   coordinates(2) + ((idx & 4) >> 2) * side);\n}\n\n/*\n * \\brief Computes the non-sibling neighbourhood around an octants. In the\n * special case in which the octant lies on an edge, neighbour are duplicated \n * as movement outside the enclosing cube is forbidden.\n * \\param result 7-vector containing the neighbours\n * \\param octant\n * \\param level of octant \n * \\param max_depth max depth of the tree on which the octant lives\n */\ninline void exterior_neighbours(se::key_t result[7], \n    const se::key_t octant, const int level, const int max_depth) {\n\n  const int idx = child_id(octant, level, max_depth);\n  Eigen::Vector3i dir = Eigen::Vector3i((idx & 1) ? 1 : -1,\n                       (idx & 2) ? 1 : -1,\n                       (idx & 4) ? 1 : -1);\n  Eigen::Vector3i base = far_corner(octant, level, max_depth);\n  dir(0) = se::math::in(base(0) + dir(0) , 0, (1 << max_depth) - 1) ? dir(0) : 0;\n  dir(1) = se::math::in(base(1) + dir(1) , 0, (1 << max_depth) - 1) ? dir(1) : 0;\n  dir(2) = se::math::in(base(2) + dir(2) , 0, (1 << max_depth) - 1) ? dir(2) : 0;\n\n result[0] = se::keyops::encode(base(0) + dir(0), base(1) + 0, base(2) + 0, \n     level, max_depth);\n result[1] = se::keyops::encode(base(0) + 0, base(1) + dir(1), base(2) + 0, \n     level, max_depth); \n result[2] = se::keyops::encode(base(0) + dir(0), base(1) + dir(1), base(2) + 0, \n     level, max_depth); \n result[3] = se::keyops::encode(base(0) + 0, base(1) + 0, base(2) + dir(2), \n     level, max_depth); \n result[4] = se::keyops::encode(base(0) + dir(0), base(1) + 0, base(2) + dir(2), \n     level, max_depth); \n result[5] = se::keyops::encode(base(0) + 0, base(1) + dir(1), base(2) + dir(2), \n     level, max_depth); \n result[6] = se::keyops::encode(base(0) + dir(0), base(1) + dir(1), \n     base(2) + dir(2), level, max_depth); \n}\n\n/*\n * \\brief Computes the morton number of all siblings around an octant,\n * including itself.\n * \\param result 8-vector containing the neighbours\n * \\param octant\n * \\param max_depth max depth of the tree on which the octant lives\n */\ninline void siblings(se::key_t result[8], \n    const se::key_t octant, const int max_depth) {\n  const int level = (octant & SCALE_MASK);\n  const int shift = 3*(max_depth - level);\n  const se::key_t p = parent(octant, max_depth) + 1; // set-up next level\n  for(int i = 0; i < 8; ++i) {\n    result[i] = p | (i << shift);\n  }\n}\n#endif\n", "meta": {"hexsha": "b910bb4f94a0753aeed0325774f6f65ace8dcc6e", "size": 7217, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "se_core/include/se/octant_ops.hpp", "max_stars_repo_name": "ori-drs/supereight", "max_stars_repo_head_hexsha": "f3cfcbebe5b9eab37435172e0c7470c9f4a85b37", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 171.0, "max_stars_repo_stars_event_min_datetime": "2018-07-10T08:05:38.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T09:10:41.000Z", "max_issues_repo_path": "se_core/include/se/octant_ops.hpp", "max_issues_repo_name": "sotpapathe/supereight", "max_issues_repo_head_hexsha": "f3cfcbebe5b9eab37435172e0c7470c9f4a85b37", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 16.0, "max_issues_repo_issues_event_min_datetime": "2018-08-13T08:42:59.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-04T08:50:10.000Z", "max_forks_repo_path": "se_core/include/se/octant_ops.hpp", "max_forks_repo_name": "sotpapathe/supereight", "max_forks_repo_head_hexsha": "f3cfcbebe5b9eab37435172e0c7470c9f4a85b37", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 51.0, "max_forks_repo_forks_event_min_datetime": "2018-07-03T10:23:22.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-27T10:46:20.000Z", "avg_line_length": 39.0108108108, "max_line_length": 83, "alphanum_fraction": 0.6632949979, "num_tokens": 2126, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6261241632752915, "lm_q2_score": 0.5, "lm_q1q2_score": 0.31306208163764576}}
{"text": "/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */\n\n/*\n Copyright (C) 2010 Roland Lichters\n\n This file is part of QuantLib, a free-software/open-source library\n for financial quantitative analysts and developers - http://quantlib.org/\n\n QuantLib is free software: you can redistribute it and/or modify it\n under the terms of the QuantLib license.  You should have received a\n copy of the license along with this program; if not, please email\n <quantlib-dev@lists.sf.net>. The license is also available online at\n <http://quantlib.org/license.shtml>.\n\n This program is distributed in the hope that it will be useful, but WITHOUT\n ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n FOR A PARTICULAR PURPOSE.  See the license for more details.\n*/\n\n#include <qlo/qladdindefines.hpp>\n#include <qlo/credit.hpp>\n#include <qlo/enumerations/factories/termstructuresfactory.hpp>\n\n#include <ql/instruments/stock.hpp>\n#include <ql/quote.hpp>\n#include <ql/time/daycounter.hpp>\n#include <ql/termstructures/credit/interpolatedhazardratecurve.hpp>\n#include <ql/termstructures/yield/piecewiseyieldcurve.hpp>\n#include <ql/termstructures/credit/piecewisedefaultcurve.hpp>\n#include <ql/math/interpolations/backwardflatinterpolation.hpp>\n#include <ql/math/interpolations/loginterpolation.hpp>\n#include <ql/pricingengines/credit/midpointcdsengine.hpp>\n\n#include <boost/algorithm/string/case_conv.hpp>\n\n#include <ql/settings.hpp>\n\nusing boost::algorithm::to_upper_copy;\n\nnamespace QuantLibAddin {\n\n    CreditDefaultSwap::CreditDefaultSwap(\n              const boost::shared_ptr<ObjectHandler::ValueObject>& properties,\n              QuantLib::Protection::Side side,\n              QuantLib::Real notional,\n              QuantLib::Rate upfront,\n              QuantLib::Rate spread,\n              const boost::shared_ptr<QuantLib::Schedule>& schedule,\n              QuantLib::BusinessDayConvention paymentConvention,\n              const QuantLib::DayCounter& dayCounter,\n              bool settlesAccrual,\n              bool paysAtDefaultTime,\n              const QuantLib::Date& protectionStart,\n              const QuantLib::Date& upfrontDate,\n              bool permanent)\n        : Instrument(properties, permanent) {\n        libraryObject_ = boost::shared_ptr<QuantLib::CreditDefaultSwap>(\n                    new QuantLib::CreditDefaultSwap(side,\n                                                    notional,\n                                                    upfront,\n                                                    spread,\n                                                    *schedule,\n                                                    paymentConvention,\n                                                    dayCounter,\n                                                    settlesAccrual,\n                                                    paysAtDefaultTime,\n                                                    protectionStart,\n                                                    upfrontDate));\n    }\n    \n    MidPointCdsEngine::MidPointCdsEngine(\n            const boost::shared_ptr<ObjectHandler::ValueObject>& properties,\n            const QuantLib::Handle<QuantLib::DefaultProbabilityTermStructure>& defaultTS,\n            QuantLib::Real recoveryRate,\n            const QuantLib::Handle<QuantLib::YieldTermStructure>& yieldTS,\n            bool permanent) \n        : PricingEngine(properties, permanent) {\n        libraryObject_ = boost::shared_ptr<QuantLib::PricingEngine>(new\n              QuantLib::MidPointCdsEngine(defaultTS, recoveryRate, yieldTS));\n    }\n\n\n\n    SpreadCdsHelper::SpreadCdsHelper(\n            const boost::shared_ptr<ObjectHandler::ValueObject>& properties,\n            const QuantLib::Handle<QuantLib::Quote>& quote,\n            const QuantLib::Period& period,\n            QuantLib::Natural settlementDays,\n            const QuantLib::Calendar& calendar,\n            QuantLib::Frequency frequency,\n            QuantLib::BusinessDayConvention paymentConvention,\n            QuantLib::DateGeneration::Rule rule,\n            const QuantLib::DayCounter& dayCounter,\n            QuantLib::Real recoveryRate,\n            const QuantLib::Handle<QuantLib::YieldTermStructure>& yieldTS,\n            bool settlesAccrual,\n            bool paysAtDefaultTime,\n            bool permanent) : DefaultProbabilityHelper(properties, permanent) {\n\n        libraryObject_ = boost::shared_ptr<QuantLib::DefaultProbabilityHelper>(new\n\t\t       QuantLib::SpreadCdsHelper(quote,\n\t\t\t\t\t\t period,\n\t\t\t\t\t\t settlementDays,\n\t\t\t\t\t\t calendar,\n\t\t\t\t\t\t frequency,\n\t\t\t\t\t\t paymentConvention,\n\t\t\t\t\t\t rule,\n\t\t\t\t\t\t dayCounter,\n\t\t\t\t\t\t recoveryRate,\n\t\t\t\t\t\t yieldTS,\n\t\t\t\t\t\t settlesAccrual,\n\t\t\t\t\t\t paysAtDefaultTime));\n    }\n\n    UpfrontCdsHelper::UpfrontCdsHelper(\n            const boost::shared_ptr<ObjectHandler::ValueObject>& properties,\n            const QuantLib::Handle<QuantLib::Quote>& quote,\n            QuantLib::Rate runningSpread,\n            const QuantLib::Period& period,\n            QuantLib::Natural settlementDays,\n            const QuantLib::Calendar& calendar,\n            QuantLib::Frequency frequency,\n            QuantLib::BusinessDayConvention paymentConvention,\n            QuantLib::DateGeneration::Rule rule,\n            const QuantLib::DayCounter& dayCounter,\n            QuantLib::Real recoveryRate,\n            const QuantLib::Handle<QuantLib::YieldTermStructure>& yieldTS,\n            QuantLib::Natural upfrontSettlementDays,\n            bool settlesAccrual,\n            bool paysAtDefaultTime,\n            bool permanent) : DefaultProbabilityHelper(properties, permanent) {\n        libraryObject_ = boost::shared_ptr<QuantLib::DefaultProbabilityHelper>(new\n\t\t       QuantLib::UpfrontCdsHelper(quote,\n                                          runningSpread,\n                                          period,\n                                          settlementDays,\n                                          calendar,\n                                          frequency,\n                                          paymentConvention,\n                                          rule,\n                                          dayCounter,\n                                          recoveryRate,\n                                          yieldTS,\n                                          upfrontSettlementDays,\n                                          settlesAccrual,\n                                          paysAtDefaultTime));\n    }\n\n    HazardRateCurve::HazardRateCurve(\n            const boost::shared_ptr<ObjectHandler::ValueObject>& properties,\n            const std::vector<QuantLib::Date>& dates,\n            const std::vector<QuantLib::Rate>& hazardRates,\n            const QuantLib::DayCounter& dayCounter,\n            bool permanent) \n        : DefaultProbabilityTermStructure(properties, permanent) {\n        QL_REQUIRE(!dates.empty(), \"no input dates given\");\n        QL_REQUIRE(dates.size() == hazardRates.size(), \n                   \"vector sizes differ\");\n        libraryObject_ = boost::shared_ptr<QuantLib::Extrapolator>(\n        new QuantLib::InterpolatedHazardRateCurve<QuantLib::BackwardFlat>(\n \t\t\t\t dates, hazardRates, dayCounter));\n    }\n\n    PiecewiseFlatHazardRateCurve::PiecewiseFlatHazardRateCurve(\n            const boost::shared_ptr<ObjectHandler::ValueObject>& properties,\n            const QuantLib::Date& referenceDate,\n            const std::vector<boost::shared_ptr<QuantLib::DefaultProbabilityHelper> >& helpers,\n            const QuantLib::DayCounter& dayCounter,\n            QuantLib::Real accuracy,\n            bool permanent) \n        : DefaultProbabilityTermStructure(properties, permanent) {\n        libraryObject_ = boost::shared_ptr<QuantLib::Extrapolator>(new\n               QuantLib::PiecewiseDefaultCurve<QuantLib::HazardRate,QuantLib::BackwardFlat>(referenceDate, helpers, dayCounter));\n    }\n\n    PiecewiseFlatForwardCurve::PiecewiseFlatForwardCurve(\n            const boost::shared_ptr<ObjectHandler::ValueObject>& properties,\n            const QuantLib::Date& referenceDate,\n            const std::vector<boost::shared_ptr<QuantLib::RateHelper> >& helpers,\n            const QuantLib::DayCounter& dayCounter,\n            QuantLib::Real accuracy,\n            bool permanent)\n        : YieldTermStructure(properties, permanent) {\n        libraryObject_ = boost::shared_ptr<QuantLib::Extrapolator>(new\n               QuantLib::PiecewiseYieldCurve<QuantLib::Discount,QuantLib::LogLinear>(referenceDate, helpers, dayCounter));\n    }\n\n}\n", "meta": {"hexsha": "04bf567976e7b860a18b33035e86416d9887115c", "size": 8536, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "QuantLibAddin/qlo/credit.cpp", "max_stars_repo_name": "frannuca/quantlib", "max_stars_repo_head_hexsha": "63e66f5f767397e5b7c79fa78eaed4e3e0a6b7c6", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "QuantLibAddin/qlo/credit.cpp", "max_issues_repo_name": "frannuca/quantlib", "max_issues_repo_head_hexsha": "63e66f5f767397e5b7c79fa78eaed4e3e0a6b7c6", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "QuantLibAddin/qlo/credit.cpp", "max_forks_repo_name": "frannuca/quantlib", "max_forks_repo_head_hexsha": "63e66f5f767397e5b7c79fa78eaed4e3e0a6b7c6", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-02-24T04:54:18.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-24T04:54:18.000Z", "avg_line_length": 45.164021164, "max_line_length": 129, "alphanum_fraction": 0.6009840675, "num_tokens": 1640, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7025300573952054, "lm_q2_score": 0.4455295350395727, "lm_q1q2_score": 0.3129978898226102}}
{"text": "#include <stdio.h>\n\n#include <complex>\n#include <iostream>\n#include <iomanip>\n#include <cstdlib>\n#include <cmath>\n#include <utility>\n\n#include <boost/timer/timer.hpp>\n\n#include \"dune/grid/config.h\"\n\n#include \"dune/common/stdstreams.hh\"\n#include \"dune/grid/sgrid.hh\"\n#include \"dune/grid/uggrid.hh\"\n#include \"dune/grid/io/file/amirameshreader.hh\"\n#include \"dune/grid/io/file/amirameshwriter.hh\"\n#include \"dune/grid/common/gridinfo.hh\"\n#include \"dune/istl/solvers.hh\"\n\n#include \"utilities/enums.hh\"\n#include \"fem/assemble.hh\"\n#include \"fem/gridmanager.hh\"\n#include \"fem/lagrangespace.hh\"\n#include \"fem/functional_aux.hh\"\n#include \"fem/coarsening.hh\"\n#include \"fem/norms.hh\"\n\n#include \"linalg/umfpack_solve.hh\"\n\n#include \"timestepping/limexWithoutJens.hh\"\n#include \"timestepping/semieuler.hh\"\n#include \"timestepping/extrapolation.hh\"\n\n#include \"io/vtk.hh\"\n#include \"io/amira.hh\"\n\n#include \"utilities/kaskopt.hh\"\n#include \"amiramesh.hh\"\n\nusing namespace Kaskade;\n\n#include \"integrate.hh\"\n#include \"aliev.hh\"\n\n\nboost::timer::cpu_timer partTimer;\ndouble assTime, solveTime;\n\n\nstruct InitialValue \n{\n  typedef double Scalar;\n  static int const components = 1;\n  typedef Dune::FieldVector<Scalar,components> ValueType;\n\n  InitialValue(int c): component(c) {}\n  \n  template <class Cell> int order(Cell const&) const { return std::numeric_limits<int>::max(); }\n  template <class Cell>\n  ValueType value(Cell const& cell,\n                  Dune::FieldVector<typename Cell::ctype,Cell::dimension> const& localCoordinate) const \n  {\n\tDune::FieldVector<typename Cell::ctype,Cell::dimensionworld> x = cell.geometry().global(localCoordinate);\n\tdouble R=1.0;\t\t// slab: R=0.09\t\theart: R=1.0\n\tdouble beta=1000.0;\n\tdouble f=0.0;\n\tdouble r;\n\t\n\t//r = sqrt( (x[0]-(0.3))*(x[0]-(0.3)) + (x[1]-(-2.4))*(x[1]-(-2.4)) + (x[2]-182.5)*(x[2]-182.5) );\t// heart smooth\n\tr = sqrt( (x[0]-(-0.9))*(x[0]-(-0.9)) + (x[1]-1.7)*(x[1]-1.7) + (x[2]-1.1)*(x[2]-1.1) );\t\t\t// heart glenn\n\t//r = sqrt( (x[0]-1.5)*(x[0]-1.5) + (x[1]-1.5)*(x[1]-1.5) + (x[2]-1.1)*(x[2]-1.1) );\t\t\t\t// slab\n\tbeta = -1e4*log(0.001);\n\tif (r < R) f = 1;\n\telse f = exp(-beta*(R-r)*(R-r));\n\t\n    if (component==0) \n      return 0.0;\t\t// 0.95*f;\n    else if (component==1) \n      return 0.0;\n    else\n      assert(\"wrong index!\\n\"==0);\n    return 0;\n  }\n\nprivate:\n  int component;\n};\n\n\n\n\ntemplate <class Eq>\ntypename Eq::AnsatzVars::VariableSet transformBack(Eq const& eq, typename Eq::AnsatzVars::VariableSet const& vars) \n{\n  typename Eq::AnsatzVars::VariableSet  x(vars);\n  \n  for (int j=0; j<boost::fusion::at_c<0>(x.data).space().degreesOfFreedom(); ++j) {\n    (boost::fusion::at_c<0>(x.data)).coefficients()[j] = eq.theta((boost::fusion::at_c<0>(x.data)).coefficients()[j]);\n  }\n  \n  return x;\n}\n\ntemplate <class Eq>\ntypename Eq::AnsatzVars::VariableSet transformBackDeriv(Eq const& eq, typename Eq::AnsatzVars::VariableSet const& vars) \n{\n  typename Eq::AnsatzVars::VariableSet  x(vars);\n  \n  for (int j=0; j<boost::fusion::at_c<0>(x.data).space().degreesOfFreedom(); ++j) {\n    (*boost::fusion::at_c<0>(x.data))[j] = eq.dtheta((*boost::fusion::at_c<0>(x.data))[j]);\n  }\n  \n  return x;\n}\n\ntemplate <class Eq>\ntypename Eq::AnsatzVars::VariableSet transformBackDerivMul(Eq const& eq, typename Eq::AnsatzVars::VariableSet const& vars1, typename Eq::AnsatzVars::VariableSet const& vars2) \n{\n  typename Eq::AnsatzVars::VariableSet  x(vars1);\n  \n  for (int j=0; j<boost::fusion::at_c<0>(x.data).space().degreesOfFreedom(); ++j) {\n    (*boost::fusion::at_c<0>(x.data))[j] = eq.dtheta((*boost::fusion::at_c<0>(x.data))[j]) * (*boost::fusion::at_c<0>(vars2.data))[j];\n  }\n  \n  return x;\n}\n\ntemplate <class Eq>\ntypename Eq::AnsatzVars::VariableSet transformForward(Eq const& eq, typename Eq::AnsatzVars::VariableSet const& vars) \n{\n  typename Eq::AnsatzVars::VariableSet  x(vars);\n  \n  for (int j=0; j<boost::fusion::at_c<0>(x.data).space().degreesOfFreedom(); ++j) {\n    (*boost::fusion::at_c<0>(x.data))[j] = eq.zeta((*boost::fusion::at_c<0>(x.data))[j]);\n  }\n  \n  return x;\n}\n\ntemplate <class Eq>\ntypename Eq::AnsatzVars::VariableSet transformInitial(Eq const& eq, typename Eq::AnsatzVars::VariableSet const& vars) \n{\n  typename Eq::AnsatzVars::VariableSet  x(vars);\n  \n  for (int j=0; j<boost::fusion::at_c<0>(x.data).space().degreesOfFreedom(); ++j) {\n    (*boost::fusion::at_c<0>(x.data))[j] = eq.zetaInitial((*boost::fusion::at_c<0>(x.data))[j]);\n  }\n  \n  return x;\n}\n\n\n\nint main(int argc, char *argv[])\n{\n  using namespace boost::fusion;\n\n  int verbosityOpt = 1;\n  bool dump = true; \n  std::unique_ptr<boost::property_tree::ptree> pt = getKaskadeOptions(argc, argv, verbosityOpt, dump);\n\n  std::cout << \"Start cardiac simulation (Aliev-Panfilov)\" << std::endl;\n\n  fexcept_t flag;\n  fegetexceptflag(&flag,FE_DIVBYZERO|FE_INVALID|FE_OVERFLOW|FE_UNDERFLOW);\n  fesetexceptflag(&flag,FE_DIVBYZERO|FE_INVALID|FE_OVERFLOW|FE_UNDERFLOW);  \n  \n  boost::timer::cpu_timer totalTimer;\n\n  int const dim = 3;\n  int refinements;\n  int  order, extrapolOrder, maxSteps;\n  double dt, maxDT, T, rTolT, aTolT, rTolX, aTolX, writeInterval;\n  std::string logname = \"cardio.log\";\n  bool refineTimeStep;\n  std::string zetaFile, thetaFile;\n  double xi, a, gs, ga, mu1, mu2, eps1, kappa, v_rest, v_peak;\n  \t\n  std::string empty, geoFile(\"slab242.am\");\n  geoFile = getParameter(pt, \"file\", geoFile);\n\n\n  refinements = 0;   // slab: 3,  Herz: 0\n  order = 2;\n  extrapolOrder = 2;\n  T = 1.0;\n  dt = 0.01;\n  maxDT = 4.0;\n  writeInterval = 1.0;\n  refineTimeStep = true;\n  rTolT = 1e-3;\n  aTolT = 1e-3;\n  rTolX = 1e-3;\n  aTolX = 1e-3;\n  maxSteps = 10000;\n// \tthetaFile = \"zetaLinearInv.gnu\";\n// \tzetaFile  = \"zetaLinear.gnu\";\n// \tthetaFile = \"zetaInv.gnu\";     \t\t\t// original nonlinear scaling\n// \tzetaFile  = \"zeta.gnu\";        \t\t\t// original nonlinear scaling\n// \tthetaFile = \"theta-tanh5-100000.gnu\";   // tanh nonlinear scaling\n// \tzetaFile  = \"zeta-tanh5-100000.gnu\";    // tanh nonlinear scaling\n\tthetaFile = \"theta-tanh2-100000.gnu\";   // tanh nonlinear scaling\n\tzetaFile  = \"zeta-tanh2-100000.gnu\";    // tanh nonlinear scaling\n// \tthetaFile = \"zetaInv-MW.gnu\";     \t\t// MW nonlinear scaling\n// \tzetaFile  = \"zeta-MW.gnu\";        \t\t// MW nonlinear scaling\n// \tthetaFile = \"theta-2d-1e-5.gnu\";\t\t// MW nonlinear scaling\n// \tzetaFile  = \"zeta-2d-1e-5.gnu\";\t\t\t// MW nonlinear scaling\n//\tthetaFile = \"theta-2d-1e-7.gnu\";\t\t// MW nonlinear scaling\n//\tzetaFile  = \"zeta-2d-1e-7.gnu\";\t\t\t// MW nonlinear scaling\n// \tthetaFile = \"zetaInvQuadratic.gnu\";     // Quadratic nonlinear scaling\n// \tzetaFile  = \"zetaQuadratic.gnu\";        // Quadratic nonlinear scaling\n// \tthetaFile = \"zetaIdentityInv.gnu\";\n// \tzetaFile  = \"zetaIdentity.gnu\";\n// \tthetaFile = \"\";\n// \tzetaFile  = \"\";\n\t\n\t\n  xi   = 1.0;\n  kappa = 0.001;\n  a = 0.1;\n  gs = 8.0;\n  ga = 8.0;\n  mu1 = 0.07;\n  mu2 = 0.3;\n  eps1 = 0.01;\n\t\n  v_rest = 0.0;   //-85.0;\n  v_peak = 1.0;   //35.0;\n\t\n\n  int heapSize=16384;\n  typedef Dune::UGGrid<dim> Grid;\n  Grid::setDefaultHeapSize(heapSize);\n  Dune::GridFactory<Grid> factory;\n\n  DuneAmiraMesh<dim,dim,Grid> mesh(geoFile.c_str());\n  mesh.InsertUGGrid(factory);\n      \n  std::unique_ptr<Grid> grid( factory.createGrid() );\n  for (int k=0; k<refinements; k++)\n  {\n    grid->globalRefine(1);\n  }\n\n  // some information on the refined mesh\n  std::cout << std::endl << \"Grid: \" << grid->size(0) << \" tetrahedra, \" << std::endl;\n  std::cout << \"      \" << grid->size(1) << \" triangles, \" << std::endl;\n  std::cout << \"      \" << grid->size(dim-1) << \" edges, \" << std::endl;\n  std::cout << \"      \" << grid->size(dim) << \" points\" << std::endl;\n  // a gridmanager is constructed \n  // as connector between geometric and algebraic information\n  GridManager<Grid> gridManager(std::move(grid));\n  gridManager.enforceConcurrentReads(true);\n    \n  typedef Grid::LeafGridView LeafView;\n\t\t\n  \t// construct involved spaces.\n    //typedef ContinuousHierarchicMapper<double,Grid>  LMapper;\n  typedef ContinuousLagrangeMapper<double,LeafView> LMapper;  \n  typedef FEFunctionSpace<LMapper> H1Space;\n\t\n  H1Space h1Space(gridManager,gridManager.grid().leafView(),order);\n\t\n  \ttypedef boost::fusion::vector<H1Space const*> Spaces;\n  \tSpaces spaces(&h1Space);\n\t\n  \t// construct variable list.\n  \ttypedef boost::fusion::vector<VariableDescription<0,1,0>,\n    \t\t\t\t\t\t\t  VariableDescription<0,1,1> > VariableDescriptions;\n  \tstd::string varNames[2] = { \"u\", \"v\" };\n\n  \ttypedef VariableSetDescription<Spaces,VariableDescriptions> VariableSet;\n  \tVariableSet variableSet(spaces,varNames);\n\n  \ttypedef AlievPanfilovEquation<double,VariableSet> Equation;\n  \tEquation Eq(xi,kappa,a,gs,ga,mu1,mu2,eps1,v_rest,v_peak,zetaFile,thetaFile);\n  \t// Eq.check();\n  \n\n  std::vector<VariableSet::VariableSet> solutions;\n  std::cout << \"solutions.size = \" << solutions.size() << std::endl;\n  // std::vector<VariableSet::VariableSet> devnull;\n\n  Eq.time(0);\n  VariableSet::VariableSet x(variableSet);\n  Eq.scaleInitialValue<0>(InitialValue(0),x);\n  Eq.scaleInitialValue<1>(InitialValue(1),x);\n\n  T     = 1.0;      \t\n  dt    = 1e-3;\t\t\t//0.001;\n  maxDT = 1.0;\n  rTolT = 5e-3;\t\t// slab: 1e-2; herz(Glenn): 5e-3;\t\t//1e-5/8.0;\n  aTolT = 5e-3;\t\t// slab: 1e-2; herz(Glenn): 5e-3;\t\t//1e-5/8.0;\n  rTolX = 1e-2;\t\t// slab: 1e-2; herz(Glenn): 5e-3;\t\t//1e-5*2.0;\n  aTolX = 1e-2;\t\t// slab: 1e-2; herz(Glenn): 5e-3;\t\t//1e-5*2.0;\n  maxSteps = 10000;\n  x = integrate(gridManager,Eq,variableSet,spaces,gridManager.grid(),\n                dt,maxDT,T,maxSteps,rTolT,aTolT,rTolX,aTolX,extrapolOrder,\n                std::back_inserter(solutions),writeInterval,x,DirectType::MUMPS);\n\n  T     = 225.0;      \t\n  dt    = 5e-3;\t\t//0.001;\n  rTolT = 2e-3;\t\t//1e-5/8.0;\n  aTolT = 2e-3;\t\t//1e-5/8.0;\n  rTolX = 1.0e-2;   //1.5e-2;\t\t//1e-5*2.0;\n  aTolX = 1.0e-2;   //1.5e-2;\t\t//1e-5*2.0;\n  maxSteps = 10000;\n  x = integrate(gridManager,Eq,variableSet,spaces,gridManager.grid(),\n                dt,maxDT,T,maxSteps,rTolT,aTolT,rTolX,aTolX,extrapolOrder,\n                std::back_inserter(solutions),writeInterval,x,DirectType::MUMPS);\n\n  T     = 226.0;      \t\n  dt    = 1e-3;\t\t\t//0.001;\n  rTolT = 2e-3;\t\t//1e-5/8.0;\n  aTolT = 2e-3;\t\t//1e-5/8.0;\n  rTolX = 1.5e-2;\t\t//1e-5*2.0;\n  aTolX = 1.5e-2;\t\t//1e-5*2.0;\n  maxSteps = 10000;\n  x = integrate(gridManager,Eq,variableSet,spaces,gridManager.grid(),\n                dt,maxDT,T,maxSteps,rTolT,aTolT,rTolX,aTolX,extrapolOrder,\n                std::back_inserter(solutions),writeInterval,x,DirectType::MUMPS);\n\n  T     = 1000.0;      \t\n  dt    = 1e-3;\t\t//0.001;\n  rTolT = 2e-3;\t\t//1e-5/8.0;\n  aTolT = 2e-3;\t\t//1e-5/8.0;\n  rTolX = 1.5e-2;\t\t//1e-5*2.0;\n  aTolX = 1.5e-2;\t\t//1e-5*2.0;\n  maxSteps = 10000;\n  x = integrate(gridManager,Eq,variableSet,spaces,gridManager.grid(),\n                dt,maxDT,T,maxSteps,rTolT,aTolT,rTolX,aTolX,extrapolOrder,\n                std::back_inserter(solutions),writeInterval,x,DirectType::MUMPS);\n\n  std::cout << \" End of integrate\" << std::endl;\n\n//   if (order>1)\n//     gridManager.globalRefine(order);\n  \n//   for (int i=0; i<solutions.size(); ++i) {\n//     //VariableSet::VariableSet x(transformBack(Eq,solutions[i]));\n//     VariableSet::VariableSet xT(transformBack(Eq,x));\n//     \n//     std::ostringstream fn;\n//     fn << \"graph/out-rescaled\";\n//     fn.width(3);\n//     fn.fill('0');\n//     fn.setf(std::ios_base::right,std::ios_base::adjustfield);\n//     fn << i;\n//     fn.flush();\n//     writeVTKFile(variableSet,xT,fn.str());\n//   }\n  \n//   \n//   for (int i=0; i<solutions.size(); ++i) {\n//     std::ostringstream fn;\n//     fn << \"graph/outScaled\";\n//     fn.width(3);\n//     fn.fill('0');\n//     fn.setf(std::ios_base::right,std::ios_base::adjustfield);\n//     fn << i;\n//     fn.flush();\n//     writeVTKFile(variableSet,solutions[i],fn.str());\n//   }\n  \n  std::cout << \"End Aliev-Panfilov integration\" << std::endl;\n\n  return 0;\n}\n", "meta": {"hexsha": "a8e5b0ce9fe2c82fa63a90582e8d99a469eac919", "size": 11746, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Kaskade/tutorial/cardio/aliev.cpp", "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/tutorial/cardio/aliev.cpp", "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/tutorial/cardio/aliev.cpp", "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.6603773585, "max_line_length": 175, "alphanum_fraction": 0.6356206368, "num_tokens": 4175, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7025300573952052, "lm_q2_score": 0.4455295350395727, "lm_q1q2_score": 0.3129978898226101}}
{"text": "#include <fstream>\n#include <string>\n#include <cmath>\n\n// BOOST GRAPH LIBRARY (BGL)\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/graph_utility.hpp>\n#include <boost/graph/graphml.hpp>\n#include <boost/property_map/dynamic_property_map.hpp>\n#include <boost/property_map/property_map.hpp>\n#include <boost/graph/dijkstra_shortest_paths.hpp>\n\n// BOOST GEOMETRY\n#include <boost/geometry.hpp>\n\n// BOOST POLYGON\n#include <boost/polygon/polygon.hpp>\n\n// BOOST PROGRAM OPTIONS\n#include<boost/program_options.hpp>\n\n// FLAGS TO SET BEHAVIOUR\nbool is_log;\ndouble simplify_quantity;\nbool fill_inside;\ndouble travel_speed;\nstd::vector<double> radii;\ndouble buffer_distance;\ndouble additional_buffer_distance;\nconst double default_buffer_distance{ 0.0002 };\nint points_per_circle;\nbool subtract_smaller;\nstd::string in_file;\nstd::string out_file;\nstd::string centres;\nbool predecessor;\n\n\n// OTHER CONSTANTS\nconst double MULTIPLIER{ 100000000.0 };\n// radius of Earth in km\nconst double R{ 6371.0 };\n// factor to change degrees to radians\nconst double TO_RAD{ 3.1415926536 / 180.0 };\n\n\n/*\nATTRIBUTES AT EACH VERTEX\nWe could choose to include osmid and highway, but for the sake of\nsaving memory we do not include them as they are not needed in the\nscope of the project. We leave them in comment.\n*/\nstruct VertexProperty\n{\n    // longitude at the vertex\n    double x;\n    // latitude at the vertex\n    double y;\n    // std::string osmid;\n    // std::string highway;\n\n    // predecessor vertex id of the vertex after shortest distance calculation\n    int pred;\n    // distance from the closest source vertex\n    double dist;\n};\n\n/*\nATTRIBUTES OF EACH EDGE\nSimilarly we ignore osmid, name, highway, maxspeed, oneway.\n*/\nstruct EdgeProperty\n{\n    // std::string osmid;\n    // std::string name;\n    // std::string highway;\n    // std::string maxspeed;\n    // std::string oneway;\n\n    // length of the edge in meters\n    double length;\n    // Linestring that describes all points an edge composed of\n    std::string geometry;\n    // the weight in our calculations, the time it takes to travel the edge with a given speed\n    double time;\n    // true if a the edge is within <radius> distance from the closest cource\n    std::vector<bool> included;\n};\n\n\n// the graph type we use with directed edges\nusing Graph_t = boost::adjacency_list<boost::vecS,\n                                    boost::vecS,\n                                    boost::directedS,\n                                    VertexProperty,\n                                    EdgeProperty>;\n\nusing Vertex_t = Graph_t::vertex_descriptor;\nusing Edge_t = Graph_t::edge_descriptor;\n\nnamespace bg = boost::geometry;\nnamespace gtl = boost::polygon;\nnamespace po = boost::program_options;\n\n// types we define for the Boost Geometry Library\ntypedef bg::model::point<double, 2, bg::cs::cartesian> point_t;\ntypedef bg::model::polygon<point_t, false> polygon_t;\ntypedef bg::model::multi_polygon<polygon_t> mpolygon_t;\ntypedef bg::model::multi_point<point_t> mpoint_t;\ntypedef bg::model::linestring<point_t> linestring_t;\ntypedef bg::model::multi_linestring<linestring_t> mlinestring_t;\ntypedef bg::ring_type<polygon_t>::type ring_t;\n\n// types we define for the Boost Polygon Library\ntypedef gtl::polygon_with_holes_data<long int> Polygon_Holes;\ntypedef gtl::polygon_data<long int> Polygon_NoHoles;\ntypedef gtl::point_data<long int> Point;\ntypedef gtl::polygon_set_data<long int> PolygonSet;\ntemplate <typename T>\nstruct lookup_polygon_set_type { typedef PolygonSet type; };\ntypedef typename lookup_polygon_set_type<gtl::property_merge<long int, long int>>::type polygon_set_type;\ntypedef std::map<std::set<long int>, polygon_set_type> property_merge_result_type;\n\n\n// my_visitor ensures that we stop when up to radius we covered the graph,\n// and do not compute the distance and predicate to all vertices\nstruct my_visitor : boost::default_dijkstra_visitor\n{\n    using base = boost::default_dijkstra_visitor;\n    struct done{};\n\n    my_visitor(double dist) : distance(dist) {}\n\n    void finish_vertex(Vertex_t v, Graph_t const& g)\n    {\n        if (g[v].dist > distance)\n            throw done{};\n\n        base::finish_vertex(v, g);\n    }\n\n  private:\n    double distance;\n};\n\n\n// spherical distance between two vertices given their azimuth angle (longitude)\n// and zenith angle (latitude)\ndouble haversine_dist(double ph1, double th1, double ph2, double th2)\n{\n\tdouble dx, dy, dz;\n\tph1 -= ph2;\n\tph1 *= TO_RAD, th1 *= TO_RAD, th2 *= TO_RAD;\n\n\tdz = sin(th1) - sin(th2);\n\tdx = cos(ph1) * cos(th1) - cos(th2);\n\tdy = sin(ph1) * cos(th1);\n\treturn asin(sqrt(dx * dx + dy * dy + dz * dz) / 2) * 2 * R;\n}\n\n\n// the haversine formula computes the id of the closest node in the graph\nint closest_node(double x, double y, Graph_t g)\n{\n    double min_dist = 1000000000.0;\n    double dist = 0.0;\n    int min_id;\n    for (auto vd : boost::make_iterator_range(vertices(g))) {\n        dist = haversine_dist(x, y, g[vd].x, g[vd].y);\n        if (dist < min_dist){\n            min_dist = dist;\n            min_id = vd;\n        }\n    }\n    return min_id;\n}\n\n\n// converts BGL type polygon into GTL type polygon\n// the credit goes to\n// https://github.com/mmccoo/nerd_mmccoo/blob/master/boost_polygon_geometry/poly_utils.cpp\nvoid geom_poly2gtl_poly(const polygon_t& boost_poly, Polygon_Holes& gtlpoly)\n{\n    std::vector<Point> pts;\n    for (point_t pt : boost_poly.outer()) {\n        pts.push_back(gtl::construct<Point>((long int) (pt.get<0>()*MULTIPLIER),\n                                            (long int) (pt.get<1>()*MULTIPLIER)));\n    }\n    gtl::set_points(gtlpoly, pts.begin(), pts.end());\n\n    std::vector<Polygon_NoHoles> holes;\n    for (ring_t r: boost_poly.inners()) {\n        std::vector<Point> pts;\n        for (point_t pt : r) {\n            pts.push_back(gtl::construct<Point>((long int) (pt.get<0>()*MULTIPLIER),\n                                                (long int) (pt.get<1>()*MULTIPLIER)));\n        }\n        Polygon_NoHoles hole;\n        gtl::set_points(hole, pts.begin(), pts.end());\n        holes.push_back(hole);\n    }\n    gtl::set_holes(gtlpoly, holes.begin(), holes.end());\n}\n\n\n// converts GTL type polygon into BGL type polygon\n// the credit goes to\n// https://github.com/mmccoo/nerd_mmccoo/blob/master/boost_polygon_geometry/poly_utils.cpp\nvoid gtl_poly2geom_poly(const Polygon_Holes& gtlpoly, polygon_t& boost_poly)\n{\n    boost_poly.clear();\n    for(Point pt : gtlpoly) {\n        boost_poly.outer().push_back(\n            point_t((double)gtl::x(pt)/MULTIPLIER,(double)gtl::y(pt)/MULTIPLIER));\n    }\n\n    int num_holes{ 0 };\n    for(auto iter = gtlpoly.begin_holes(); iter != gtlpoly.end_holes(); ++iter) {\n        num_holes++;\n        const gtl::polygon_data<long int> h = *iter;\n\n        ring_t r;\n        for(Point pt : h) {\n            r.push_back(point_t((double)gtl::x(pt)/MULTIPLIER,(double)gtl::y(pt)/MULTIPLIER));\n        }\n        boost_poly.inners().push_back(r);\n    }\n\n    // if gtl goes in the wrong direction. clockwise vs counter-clockwise.\n    bg::correct(boost_poly);\n}\n\n\n// rescales Linestring\nvoid scale_geom(mlinestring_t mls, mlinestring_t &mls_scaled, double scale_x, double scale_y)\n{\n    mls_scaled.clear();\n\n    for (linestring_t ls : mls) {\n        std::vector<point_t> pts;\n        linestring_t ls_out;\n\n        for (point_t pt : ls){\n            pts.push_back(point_t(pt.get<0>()*scale_x, pt.get<1>()*scale_y));\n        }\n        bg::assign_points(ls_out, pts);\n        mls_scaled.push_back(ls_out);\n    }\n}\n\n// rescales Polygon\nvoid scale_geom(polygon_t  poly, polygon_t &poly_scaled, double scale_x, double scale_y)\n{\n    poly_scaled.clear();\n\n    for (point_t pt : poly.outer()) {\n        poly_scaled.outer().push_back(point_t(pt.get<0>()*scale_x, pt.get<1>()*scale_y));\n    }\n\n    std::vector<Polygon_NoHoles> holes;\n    for (ring_t r: poly.inners()) {\n        std::vector<point_t> pts;\n        for (point_t pt : r) {\n            pts.push_back(point_t(pt.get<0>()*scale_x, pt.get<1>()*scale_y));\n        }\n        ring_t ring;\n        bg::assign_points(ring, pts);\n        poly_scaled.inners().push_back(ring);\n    }\n}\n\n// rescales Multipolygon\nvoid scale_geom(mpolygon_t  mpoly, mpolygon_t &mpoly_scaled, double scale_x, double scale_y)\n{\n    mpoly_scaled.clear();\n\n    for (polygon_t poly : mpoly) {\n        polygon_t poly_scaled;\n        scale_geom(poly, poly_scaled, scale_x, scale_y);\n        mpoly_scaled.push_back(poly_scaled);\n    }\n}\n\n\n// reads graphml file into Graph_t\n// Again we omit certain OSM properties to save memory. These are left in comment.\nGraph_t ReadGraph(std::string fn)\n{\n    std::ifstream is(fn.c_str());\n    if (!is.is_open()) {\n        std::cout << \"loading file '\" << fn << \"'failed.\" << std::endl;\n        throw \"Could not load file.\";\n    }\n    Graph_t graph;\n    boost::dynamic_properties dp(boost::ignore_other_properties);\n    dp.property(\"x\", boost::get(&VertexProperty::x, graph));\n    dp.property(\"y\", boost::get(&VertexProperty::y, graph));\n    // dp.property(\"osmid\", boost::get(&VertexProperty::osmid, graph));\n    // dp.property(\"highway\", boost::get(&VertexProperty::highway, graph));\n\n    // dp.property(\"osmid\", boost::get(&EdgeProperty::osmid, graph));\n    // dp.property(\"name\", boost::get(&EdgeProperty::name, graph));\n    // dp.property(\"highwaye\", boost::get(&EdgeProperty::highway, graph));\n    // dp.property(\"maxspeed\", boost::get(&EdgeProperty::maxspeed, graph));\n    // dp.property(\"oneway\", boost::get(&EdgeProperty::oneway, graph));\n    dp.property(\"length\", boost::get(&EdgeProperty::length, graph));\n    dp.property(\"geometry\", boost::get(&EdgeProperty::geometry, graph));\n\n    boost::read_graphml(is, graph, dp);\n\n    return graph;\n};\n\n\n// read the source points from text file which contains a WKT Linestring\nlinestring_t read_src_points(std::string centres)\n{\n    std::ifstream input(centres);\n    std::string input_line;\n    for(std::string line; getline(input, line); ) {\n        input_line += line;\n    }\n    linestring_t src_points;\n    bg::read_wkt(input_line, src_points);\n    return src_points;\n}\n\n\n// writes radii and Multipolygons into files\nvoid write_isochrones(std::string out_file, std::vector<mpolygon_t> isochrone_polys)\n{\n    std::ofstream poly_file(out_file);\n    for (int r : radii) {\n        poly_file << r << \" \";\n    }\n    poly_file << std::endl;\n    for (int i=0; i<radii.size(); i++) {\n        poly_file << std::setprecision(12) << bg::wkt(isochrone_polys[i]) << std::endl;\n    }\n      poly_file.flush();\n      poly_file.close();\n}\n\n\n// only changes the \"included\" property if the edge\n// is reached within a certain radius with, this is done with Dijkstra's algorithm\nvoid get_isochrones(int source, std::vector<double> radii, Graph_t &g) {\n    double maxi = -1;\n    for (auto radius : radii) {\n        if (maxi < radius) maxi = radius;\n    }\n    my_visitor vis { maxi };\n\n    try {\n    boost::dijkstra_shortest_paths(g, source,\n                          boost::visitor(vis)\n                          .predecessor_map(get(&VertexProperty::pred, g))\n                          .distance_map(get(&VertexProperty::dist, g))\n                          .weight_map(get(&EdgeProperty::time, g)));\n    } catch(my_visitor::done const&) {\n    }\n\n\n    for (int i=0; i<radii.size(); i++) {\n        Vertex_t src, tar;\n        auto es = boost::edges(g);\n        for (auto eit = es.first; eit != es.second; ++eit) {\n            src = boost::source(*eit, g);\n            tar = boost::target(*eit, g);\n            if (g[tar].dist < radii[i] && g[src].dist < radii[i]) {\n                if(predecessor == true && g[tar].pred != src) {\n                    continue;\n                }\n                g[*eit].included[i] = true;\n            }\n        }\n    }\n}\n\n\n// unary union from a property_merge into mpolygon_t\nvoid polygon_merge(gtl::property_merge<long int, long int> pm, mpolygon_t &multipolygon)\n{\n    property_merge_result_type merge_result;\n    pm.merge(merge_result);\n    PolygonSet result = merge_result.begin()->second;\n    std::vector<Polygon_Holes> polys;\n    result.get(polys);\n    for (int k=0; k<polys.size(); k++) {\n        polygon_t poly;\n        gtl_poly2geom_poly(polys[k], poly);\n        multipolygon.push_back(poly);\n    }\n}\n\n\n// computes the Multilinestring within a given radius\nvoid get_multilinestring_within(int i, Graph_t g, mlinestring_t &mls)\n{\n    auto es = boost::edges(g);\n\n    // for a directed edge src is the source and tar is the target vertex\n    Vertex_t src, tar;\n\n    linestring_t ls;\n\n    // we loop through all the edges in the graph\n    for (auto eit = es.first; eit != es.second; ++eit) {\n        // if the i-th smallest radius is in reach\n        if (g[*eit].included[i] == true) {\n            // if i > 0 and we already processed the edge in the previous run\n            // of the outmost loop then we continue in the loop\n            if (i > 0 && g[*eit].included[i-1] == true) {\n                continue;\n            }\n\n            src = boost::source(*eit, g);\n            tar = boost::target(*eit, g);\n            std::string str(g[*eit].geometry);\n\n            // if the geometry of the edge is not empty then we read\n            // the geometry into Linestring\n            if (str.length() > 1) {\n                bg::read_wkt(str, ls);\n            }\n            // else we consider the endpoints of of the edge as Linestring\n            else {\n                std::vector<point_t> pts;\n                pts.push_back(point_t(g[src].x, g[src].y));\n                pts.push_back(point_t(g[tar].x, g[tar].y));\n                bg::assign_points(ls, pts);\n            }\n            mls.push_back(ls);\n        }\n    }\n}\n\n\n// applies transformations on the geometry\nvoid build_isochrone_geometry(std::vector<mpolygon_t> &isochrone_polys,\n                            std::vector<Polygon_Holes> polys, double lat_lon_ratio)\n{\n    bg::strategy::buffer::distance_symmetric<double> distance_strategy(buffer_distance);\n    bg::strategy::buffer::join_round join_strategy(points_per_circle);\n    bg::strategy::buffer::end_round end_strategy(points_per_circle);\n    bg::strategy::buffer::point_circle circle_strategy(points_per_circle);\n    bg::strategy::buffer::side_straight side_strategy;\n\n    // auxiliary variables for further computations with polygons\n    polygon_t    poly, poly_aux;\n    ring_t       ring;\n    mpolygon_t   mpoly, mpoly_scaled, mpoly_collect;\n\n    // we loop over radii starting with the smallest\n    for (int j=0; j<polys.size(); j++) {\n        gtl_poly2geom_poly(polys[j], poly);\n            if (fill_inside == true && predecessor == false) {\n                ring = poly.outer();\n                bg::convert(ring, poly_aux);\n                bg::simplify(poly_aux, poly, simplify_quantity);\n                bg::strategy::buffer::distance_symmetric<double>\n                    distance_strategy(additional_buffer_distance);\n                bg::buffer(poly, mpoly, distance_strategy, side_strategy,\n                           join_strategy, end_strategy, circle_strategy);\n                scale_geom(mpoly, mpoly_scaled, 1/lat_lon_ratio, 1);\n                ring.clear();\n                ring = mpoly_scaled[0].outer();\n                mpoly_scaled.clear();\n                mpoly.clear();\n                poly.clear();\n                bg::convert(ring, poly);\n            } else {\n                bg::simplify(poly, poly_aux, simplify_quantity);\n                scale_geom(poly_aux, poly, 1/lat_lon_ratio, 1);\n            }\n            mpoly_collect.push_back(poly);\n    }\n    isochrone_polys.push_back(mpoly_collect);\n}\n\n\nvoid union_of_fill_inside_true_predecessor_false(std::vector<mpolygon_t> &isochrone_polys)\n{\n    std::vector<mpolygon_t> isochrone_polys_union;\n    gtl::property_merge<long int, long int> pm;\n    for (mpolygon_t mpoly : isochrone_polys) {\n        for (polygon_t poly : mpoly){\n            Polygon_Holes pl;\n            geom_poly2gtl_poly(poly, pl);\n            pm.insert(pl, 0);\n        }\n        mpolygon_t multipolygon, multipolygon_outer;\n        polygon_merge(pm, multipolygon);\n        for (polygon_t poly: multipolygon) {\n            ring_t ring = poly.outer();\n            poly.clear();\n            bg::convert(ring, poly);\n            multipolygon_outer.push_back(poly);\n        }\n        isochrone_polys_union.push_back(multipolygon_outer);\n    }\n    isochrone_polys.clear();\n    isochrone_polys.insert(isochrone_polys.end(),\n                           isochrone_polys_union.begin(), isochrone_polys_union.end());\n}\n\n\nvoid subtract_smaller_polygon(std::vector<mpolygon_t> &isochrone_polys)\n{\n    std::vector<mpolygon_t> isochrone_polys_difference;\n    for (int j=0; j<isochrone_polys.size()-1; j++) {\n        if (j == 0) {\n            isochrone_polys_difference.push_back(isochrone_polys[0]);\n        }\n        gtl::property_merge<long int, long int> pm;\n        Polygon_Holes pl;\n        for (polygon_t poly : isochrone_polys[j+1]) {\n            geom_poly2gtl_poly(poly, pl);\n            pm.insert(pl, 0);\n        }\n        for (polygon_t poly : isochrone_polys[j]) {\n            geom_poly2gtl_poly(poly, pl);\n            pm.insert(pl, 1);\n        }\n        mpolygon_t multipolygon;\n        polygon_merge(pm, multipolygon);\n        isochrone_polys_difference.push_back(multipolygon);\n    }\n    isochrone_polys.clear();\n    isochrone_polys.insert(isochrone_polys.end(),\n                           isochrone_polys_difference.begin(), isochrone_polys_difference.end());\n}\n\n\n// obtaining command line options\nint cmd_input(int ac, char * av[],\n            bool &is_log,\n            double &simplify_quantity,\n            bool &fill_inside,\n            double &travel_speed,\n            std::vector<double> &radii,\n            double &buffer_distance,\n            double &additional_buffer_distance,\n            int &points_per_circle,\n            bool &subtract_smaller,\n            std::string &in_file,\n            std::string &out_file,\n            std::string &centres,\n            bool &predecessor)\n{\n    po::options_description desc(\"Allowed options\");\n    desc.add_options()\n        (\"help\", \"produce help message\")\n        (\"verbose\", po::bool_switch(&is_log)->default_value(false),\n        \"prints log details\")\n        (\"simplify\", po::value<double>(&simplify_quantity),\n        \"the epsilon in Ramer-Douglas-Peucker algorithm, the bigger the number is, the less points shall be present in the output\")\n        (\"fill\", po::bool_switch(&fill_inside)->default_value(false),\n        \"if the polygon contains holes it removes them\")\n        (\"travel-speed\", po::value<double>(&travel_speed)->default_value(20.0),\n        \"the travel speed in km/h\")\n        (\"radii\", po::value<std::vector<double>>(&radii)\n                ->multitoken()->default_value(std::vector<double>{10,20,30,40,50,60},\n        \"10,20,30,40,50,60\"), \"the radii of the isochrone curves in minutes\")\n        (\"circle-points\", po::value<int>(&points_per_circle)->default_value(1),\n        \"the radii of the isochrone curves in minutes\")\n        (\"subtract\", po::bool_switch(&subtract_smaller)->default_value(false),\n        \"subtracts the smaller radius polygon from the larger thus creating a hole in that\")\n        (\"input-file\", po::value<std::string>(&in_file)->required(),\n        \"the input .graphml file\")\n        (\"output-file,o\", po::value<std::string>(&out_file)->default_value(\"out.txt\"),\n        \"the output text file\")\n        (\"sources\", po::value<std::string>(&centres)->default_value(\"sources.txt\"),\n        \"a file containing a WKT Linestring whose vertices are the sources\")\n        (\"predecessor\", po::bool_switch(&predecessor)->default_value(false),\n        \"computes the isochrone curves with a shortest path tree, fill does not affect it, it is not adviced to have multiple sources in this case\")\n        (\"buffer-distance\", po::value<double>(&buffer_distance)->default_value(default_buffer_distance),\n        \"thickness added to the roads and polygons\")\n    ;\n\n    po::variables_map vm;\n    po::store(po::parse_command_line(ac, av, desc), vm);\n\n    if (vm.count(\"help\")) {\n        std::cout << desc << \"\\n\";\n        return 1;\n    }\n\n    po::notify(vm);\n\n    if (buffer_distance <= 0) {\n        std::cout << \"the buffer distance must be positive\\n\";\n        return 1;\n    }\n\n    if (fill_inside == true and predecessor == false) {\n        if (buffer_distance > default_buffer_distance*2) {\n            additional_buffer_distance = buffer_distance - default_buffer_distance;\n            buffer_distance = default_buffer_distance;\n        }\n        else {\n            buffer_distance /= 2;\n            additional_buffer_distance = buffer_distance;\n        }\n    }\n    else {\n        if (buffer_distance > default_buffer_distance*2) {\n            std::cout << \"WARNING: too large buffer distance may result in the program never complete.\\n\";\n        }\n    }\n    return 0;\n}\n\n\nint main(int ac, char * av[])\n{\n    // command line arguments\n    int error = cmd_input(\n            ac, av,\n            is_log,\n            simplify_quantity,\n            fill_inside,\n            travel_speed,\n            radii,\n            buffer_distance,\n            additional_buffer_distance,\n            points_per_circle,\n            subtract_smaller,\n            in_file,\n            out_file,\n            centres,\n            predecessor\n    );\n\n    if (error == 1){\n        return 1;\n    }\n\n    if (is_log == true) {\n        std::cout << \"File \\\"\" << in_file << \"\\\" starts being read.\\n\";\n    }\n\n    Graph_t g = ReadGraph(in_file);\n\n    if (is_log == true) {\n        std::cout << \"File \\\"\" << in_file << \"\\\" is read.\\n\";\n    }\n\n    double meters_per_minute{ travel_speed * 1000.0 / 60.0 };\n    auto es = boost::edges(g);\n\n    // we initialise \"included\" as a vector of falses\n    for (auto eit = es.first; eit != es.second; ++eit) {\n        g[*eit].time =  (g[*eit].length / meters_per_minute);\n        for (int i=0; i<radii.size(); i++) {\n            g[*eit].included.push_back(false);\n        }\n    }\n\n    // 40075==circumference of Earth in km;\n    // 111.32==1 degree of latitude in km\n    // lat_lon_ratio expresses the ratio of one meter of latitude and longitude\n    // at given latitude\n    double lat_lon_ratio{ 40075.0 * cos(g[0].y * TO_RAD) / 360.0 / 111.32 };\n\n    // loads the source points\n    linestring_t src_points = read_src_points(centres);\n\n    int idx = 0;\n    auto size = src_points.size();\n    for (point_t pt : src_points) {\n        idx++;\n        int source = closest_node(pt.get<0>(), pt.get<1>(), g);\n        if (is_log == true) {\n            std::cout << \"#\" <<  idx << \"/\" << size << \", \" << \"x=\"\n                      << pt.get<0>() << \", y=\" << pt.get<1>() << \"\\n\";\n        }\n        get_isochrones(source, radii, g);\n    }\n    if (is_log == true) {\n        std::cout << \"Dijkstra is done.\\n\";\n        std::cout << \"Geometry is being assembled.\\n\";\n    }\n\n    //buffer strategy, for reference visit the website of BGL\n    bg::strategy::buffer::distance_symmetric<double> distance_strategy(buffer_distance);\n    bg::strategy::buffer::join_round join_strategy(points_per_circle);\n    bg::strategy::buffer::end_round end_strategy(points_per_circle);\n    bg::strategy::buffer::point_circle circle_strategy(points_per_circle);\n    bg::strategy::buffer::side_straight side_strategy;\n\n\n    // we collect the computed isochronic polygons in \"isochrone_polys\"\n    std::vector<mpolygon_t> isochrone_polys;\n\n    // the result of GTL property merge (union in our case) is converted into\n    // std::vector<Polygon_Holes> which is stored in \"polys,\"\n    // futhermore the previous (smaller) isochronic curve is inserted into the\n    // next one thus speeding up computation, which is done with \"polys\"\n    std::vector<Polygon_Holes> polys;\n\n    // we loop over radii starting with the smallest\n    for (int i=0; i<radii.size(); i++) {\n        // auxiliary variables for polygon manipulations\n        mlinestring_t mls, mls_scaled;\n        mpolygon_t   mpoly_aux;\n        Polygon_Holes pl;\n\n        get_multilinestring_within(i, g, mls);\n\n        // at this point if collected in a vector, the isochronic Multilinestrings\n        // could be saved\n\n        // we collect the polygons to be unioned in \"pm\"\n        gtl::property_merge<long int, long int> pm;\n\n        // we insert the previous isochronic curve here thus gaining speed\n        for (Polygon_Holes polygon : polys) {\n            pm.insert(polygon, 0);\n        }\n        // polys emptied for further computations after insertion\n        polys.clear();\n\n        // in buffer we scale the geometries thus buffer affects x and y directions equally\n        scale_geom(mls, mls_scaled, lat_lon_ratio, 1);\n\n        // memory saving for the rest of the loop\n        mls.clear();\n\n        // buffer applied to the scaled Multilinestring\n        for (linestring_t ls : mls_scaled) {\n            bg::buffer(ls, mpoly_aux, distance_strategy, side_strategy,\n                       join_strategy, end_strategy, circle_strategy);\n            geom_poly2gtl_poly(mpoly_aux.at(0), pl);\n            pm.insert(pl, 0);\n        }\n\n        // \"merge_result\" holds the result for the unary union\n        property_merge_result_type merge_result;\n        pm.merge(merge_result);\n        PolygonSet result = merge_result.begin()->second;\n        result.get(polys);\n\n        build_isochrone_geometry(isochrone_polys, polys, lat_lon_ratio);\n\n    }\n\n    if (fill_inside == true && predecessor == false) {\n        union_of_fill_inside_true_predecessor_false(isochrone_polys);\n    }\n\n    if (subtract_smaller == true) {\n        subtract_smaller_polygon(isochrone_polys);\n    }\n\n    // writing result into file\n    write_isochrones(out_file, isochrone_polys);\n\n      if (is_log == true) {\n          std::cout << \"Polygons are written into \\\"\" << out_file << \"\\\"\\n\";\n      }\n      return 0;\n}\n", "meta": {"hexsha": "e09ad21f7471eab352abba19ee682f8de3e18441", "size": 25772, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "isochrones.cpp", "max_stars_repo_name": "csekri/isochrone-polygons", "max_stars_repo_head_hexsha": "cfc77b024df4ab521ac81ce476e0888c3e59da4d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "isochrones.cpp", "max_issues_repo_name": "csekri/isochrone-polygons", "max_issues_repo_head_hexsha": "cfc77b024df4ab521ac81ce476e0888c3e59da4d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "isochrones.cpp", "max_forks_repo_name": "csekri/isochrone-polygons", "max_forks_repo_head_hexsha": "cfc77b024df4ab521ac81ce476e0888c3e59da4d", "max_forks_repo_licenses": ["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.7329842932, "max_line_length": 148, "alphanum_fraction": 0.6249805991, "num_tokens": 6409, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6619228891883799, "lm_q2_score": 0.47268347662043286, "lm_q1q2_score": 0.31288001251620495}}
{"text": "/*\n * Copyright 2020 California  Institute  of Technology (“Caltech”)\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 <x/vio/msckf_slam_update.h>\n#include <x/vio/tools.h>\n#include <x/ekf/state.h>\n#include <boost/math/distributions.hpp>\n\nusing namespace x;\nusing namespace Eigen;\n\nMsckfSlamUpdate::MsckfSlamUpdate(const x::TrackList& trks,\n                                 const x::AttitudeList& quats,\n                                 const x::TranslationList& pos,\n                                 const Triangulation& triangulator,\n                                 const MatrixXd& cov_s,\n                                 const int n_poses_max,\n                                 const double sigma_img)\n{\n  // Number of features\n  const size_t n_trks = trks.size();\n\n  // Number of feature observations\n  size_t n_obs = 0;\n  for(size_t i=0; i < n_trks; i++)\n    n_obs += trks[i].size();\n\n  // Initialize MSCKF Kalman update matrices\n  const size_t rows0 = 2 * n_obs - n_trks * 3;\n  const size_t cols = cov_s.cols();\n  jac_ = MatrixXd::Zero(rows0, cols);\n  cov_m_diag_ = VectorXd::Ones(rows0);\n  res_ = MatrixXd::Zero(rows0, 1);\n\n  // Initialize MSCKF-SLAM feature initialization matrices\n  const size_t rows1 = n_trks * 3;\n  init_mats_.H1 = MatrixXd::Zero(rows1, cols);\n  init_mats_.H2 = MatrixXd::Zero(rows1, n_trks * 3);\n  init_mats_.r1 = MatrixXd::Zero(rows1, 1);\n  init_mats_.features = MatrixXd::Zero(rows1, 1);\t\n  \n  // For each track, compute residual, Jacobian and covariance block\n  const double var_img = sigma_img * sigma_img;\n  size_t row_h = 0, row1 = 0;\n  for (size_t i = 0; i < n_trks; ++i) {\n    processOneTrack(trks[i],\n                    quats,\n                    pos,\n                    triangulator,\n                    cov_s,\n                    n_poses_max,\n                    var_img,\n                    i,\n                    row_h,\n                    row1);\n  }\n}\n\nvoid MsckfSlamUpdate::processOneTrack(const x::Track& track,\n                                      const x::AttitudeList& C_q_G,\n                                      const x::TranslationList& G_p_C,\n                                      const Triangulation& triangulator,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t      const MatrixXd& P,\n                                      const int n_poses_max,\n                                      const double var_img,\n                                      const size_t& j,\n                                      size_t& row_h,\n                                      size_t& row1)\n{\n  const size_t track_size = track.size();\n  unsigned int rows_track_j = track_size * 2;\n  const size_t cols = P.cols();\n  MatrixXd h_j(MatrixXd::Zero(rows_track_j, cols));\n  MatrixXd Hf_j(MatrixXd::Zero(h_j.rows(), kJacCols));\n  MatrixXd res_j(MatrixXd::Zero(rows_track_j, 1));\n  \n  // Feature triangulation\n  Vector3d feature; // inverse-depth parameters in last observation frame\n  triangulator.triangulateGN(track, feature);\n  const double alpha = feature(0);\n  const double beta  = feature(1);\n  const double rho   = feature(2);\n\n  // Anchor pose\n  x::Quaternion Cn_q_G;\n  Cn_q_G.x() = C_q_G.back().ax;\n  Cn_q_G.y() = C_q_G.back().ay;\n  Cn_q_G.z() = C_q_G.back().az;\n  Cn_q_G.w() = C_q_G.back().aw;\n\n  Vector3d G_p_Cn(G_p_C.back().tx, G_p_C.back().ty, G_p_C.back().tz);\n\n  // Coordinate of feature in global frame\n  Vector3d G_p_fj = 1 / (rho)*Cn_q_G.normalized().toRotationMatrix() * Vector3d(alpha, beta, 1) + G_p_Cn;\n\n  x::Quatern attitude_to_quaternion;\n\n  // LOOP OVER ALL FEATURE OBSERVATIONS\n  for (size_t i = 0; i < track_size; ++i)\n  {\n    const unsigned int pos = C_q_G.size() - track_size + i;\n    \n    Quaterniond Ci_q_G_ = attitude_to_quaternion(C_q_G[pos]);\n    Vector3d G_p_Ci_(G_p_C[pos].tx, G_p_C[pos].ty, G_p_C[pos].tz);\n\n    // Feature position expressed in camera frame.\n    Vector3d Ci_p_fj;\n    Ci_p_fj << Ci_q_G_.normalized().toRotationMatrix().transpose() * (G_p_fj - G_p_Ci_);\n\n    // eq. 20(a)\n    Vector2d z;\n    z(0) = track[i].getX();\n    z(1) = track[i].getY();\n\n    Vector2d z_hat(z);\n    assert(Ci_p_fj(2));\n    z_hat(0) = Ci_p_fj(0) / Ci_p_fj(2);\n    z_hat(1) = Ci_p_fj(1) / Ci_p_fj(2);\n\n    // eq. 20(b)\n    res_j(i * 2, 0) = z(0) - z_hat(0);\n    res_j(i * 2 + 1, 0) = z(1) - z_hat(1);\n\n    //============================\n    // Measurement Jacobian matrix\n    //============================\n\n    if (i == track_size - 1)  // Handle special case\n    {\n      // Inverse-depth feature coordinates jacobian\n      MatrixXd mat(MatrixXd::Zero(2, 3));\n      mat(0, 0) = 1.0;\n      mat(1, 1) = 1.0;\n\n      // Update stacked Jacobian matrices associated to the current feature\n      unsigned int row = i * kVisJacRows;\n      Hf_j.block<kVisJacRows, kJacCols>(row, 0) = mat;\n    }\n    else\n    {\n      // Set Jacobian of pose for i'th measurement of feature j (eq.22, 23)\n      VisJacBlock J_i(VisJacBlock::Zero());\n      // first row\n      J_i(0, 0) = 1.0 / Ci_p_fj(2);\n      J_i(0, 1) = 0.0;\n      J_i(0, 2) = -Ci_p_fj(0) / std::pow((double)Ci_p_fj(2), 2);\n      // second row\n      J_i(1, 0) = 0.0;\n      J_i(1, 1) = 1.0 / Ci_p_fj(2);\n      J_i(1, 2) = -Ci_p_fj(1) / std::pow((double)Ci_p_fj(2), 2);\n\n      // Attitude\n      Vector3d skew_vector = Ci_q_G_.normalized().toRotationMatrix().transpose() * (G_p_fj - G_p_Ci_);\n      VisJacBlock J_attitude = J_i * x::Skew(skew_vector(0), skew_vector(1), skew_vector(2)).matrix;\n\n      // Position\n      VisJacBlock J_position = -J_i * Ci_q_G_.normalized().toRotationMatrix().transpose();\n\n      // Anchor attitude\n      VisJacBlock J_anchor_att = -1 / rho * J_i * Ci_q_G_.normalized().toRotationMatrix().transpose() *\n                                      Cn_q_G.normalized().toRotationMatrix() * x::Skew(alpha, beta, 1).matrix;\n\n      // Anchor position\n      VisJacBlock J_anchor_pos = -J_position;\n\n      // Inverse-depth feature coordinates\n      MatrixXd mat(MatrixXd::Identity(3, 3));\n      mat(0, 2) = -alpha / rho;\n      mat(1, 2) = -beta / rho;\n      mat(2, 2) = -1 / rho;\n      VisJacBlock Hf_j1 = 1 / rho * J_i * Ci_q_G_.normalized().toRotationMatrix().transpose() *\n                               Cn_q_G.normalized().toRotationMatrix() * mat;\n\n      // Update stacked Jacobian matrices associated to the current feature\n      unsigned int row = i * kVisJacRows;\n      Hf_j.block<kVisJacRows, kJacCols>(row, 0) = Hf_j1;\n      \n      unsigned int col = pos * kJacCols;\n      h_j.block<kVisJacRows, kJacCols>(row, kSizeCoreErr + col) = J_position;\n\n      col += n_poses_max * kJacCols;\n      h_j.block<kVisJacRows, kJacCols>(row, kSizeCoreErr + col) = J_attitude;\n\n      col = (C_q_G.size() - 1) * kJacCols;\n      h_j.block<kVisJacRows, kJacCols>(row, kSizeCoreErr + col) = J_anchor_pos;\n\n      col += n_poses_max * kJacCols;\n      h_j.block<kVisJacRows, kJacCols>(row, kSizeCoreErr + col) = J_anchor_att;\n    }\n  }  // LOOP OVER ALL FEATURE OBSERVATIONS\n\n  //========================================================================\n  // Left nullspace projection\n  //========================================================================\n  // Nullspace computation\n  MatrixXd q = Hf_j.householderQr().householderQ();\n  MatrixXd A = x::MatrixBlock(q, 0, 3);\n\n  // Projections\n  MatrixXd res0_j = A.transpose() * res_j;\n  MatrixXd h0_j = A.transpose() * h_j;\n\n  // New noise measurement matrix\n  VectorXd r0_j_diag = var_img * VectorXd::Ones(rows_track_j - 3);\n  MatrixXd r0_j = r0_j_diag.asDiagonal();\n\n  //========================================================================\n  // Column space projection\n  //========================================================================\n  // Only needed for persistent feature init (Li, 2012)\n\n\t// Column space\n\tconst MatrixXd U = x::MatrixBlock(q, 0, 0, q.rows(), 3);\n\n\t// Projections to be used in Core::CorrectAfterCoreCorrection\n\tMatrixXd H1j = U.transpose() * h_j;\n\tMatrixXd H2j = U.transpose() * Hf_j;\n\tMatrixXd r1j = U.transpose() * res_j;\n  \n  init_mats_.H1.block(row1, 0, 3, cols) = H1j;\n\tinit_mats_.H2.block(row1, row1, 3, 3) = H2j;\n\tinit_mats_.r1.block(row1, 0, 3, 1)\t= r1j;\n\tinit_mats_.features.block(row1, 0, 3, 1)= feature;\n\trow1 += 3;\n\n  //==========================================================================\n  // Outlier rejection\n  //==========================================================================\n  MatrixXd S_inv = (h0_j * P * h0_j.transpose() + r0_j).inverse();\n  MatrixXd gamma = res0_j.transpose() * S_inv * res0_j;\n  boost::math::chi_squared_distribution<> my_chisqr(2 * track_size - 3);  // 2*Mj-3 DoFs\n  double chi = quantile(my_chisqr, 0.95);                            // 95-th percentile\n\n  if (gamma(0, 0) < chi)  // Inlier\n  {\n#ifdef VERBOSE\n    inliers_.push_back(G_p_fj);\n#endif\n\n    jac_.block(row_h,            // startRow\n             0,                 // startCol\n             rows_track_j - 3,  // numRows\n             cols) = h0_j;    // numCols\n\n    // Residual vector [feature j]\n    res_.block(row_h, 0, rows_track_j - 3, 1) = res0_j;\n\n    // Measurement covariance matrix [feature j]\n    cov_m_diag_.segment(row_h, rows_track_j - 3) = r0_j_diag;\n\n    row_h += rows_track_j - 3;\n\t}\n  else  // outlier\n  {\n#ifdef VERBOSE\n    outliers_.push_back(G_p_fj);\n#endif\n  }\n}\n", "meta": {"hexsha": "007ebc1a92149b2fc5d001f540f3ce8528558836", "size": 9681, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/x/vio/msckf_slam_update.cpp", "max_stars_repo_name": "jpl-x/x_events", "max_stars_repo_head_hexsha": "e9d0b6e578f045eb7b57acadf75b77d8a323f51d", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 57.0, "max_stars_repo_stars_event_min_datetime": "2020-10-20T18:01:14.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T18:44:43.000Z", "max_issues_repo_path": "src/x/vio/msckf_slam_update.cpp", "max_issues_repo_name": "jpl-x/x_events", "max_issues_repo_head_hexsha": "e9d0b6e578f045eb7b57acadf75b77d8a323f51d", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2022-03-11T15:53:17.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-11T15:53:17.000Z", "max_forks_repo_path": "src/x/vio/msckf_slam_update.cpp", "max_forks_repo_name": "jpl-x/x_events", "max_forks_repo_head_hexsha": "e9d0b6e578f045eb7b57acadf75b77d8a323f51d", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 11.0, "max_forks_repo_forks_event_min_datetime": "2020-10-17T00:36:02.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T18:44:45.000Z", "avg_line_length": 35.4615384615, "max_line_length": 110, "alphanum_fraction": 0.5671934717, "num_tokens": 2785, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6619228758499942, "lm_q2_score": 0.47268347662043286, "lm_q1q2_score": 0.3128800062113704}}
{"text": "/*\nCopyright (c) 2020 Naomasa Matsubayashi\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n*/\n\n#include <cstdint>\n#include <cmath>\n#include <array>\n#include <iostream>\n#include <fstream>\n#include <algorithm>\n#include <iterator>\n#include <charconv>\n#include <random>\n#include <boost/container/flat_map.hpp>\n#include <boost/program_options.hpp>\n#include <omp.h>\n#include <nlohmann/json.hpp>\n#include \"ifm/exp_match.h\"\nint main( int argc, char *argv[] ) {\n  boost::program_options::options_description options(\"オプション\");\n  options.add_options()\n    (\"help,h\",    \"ヘルプを表示\")\n    (\"decay,d\", boost::program_options::value<bool>()->default_value( true ), \"decay\")\n    (\"alpha,a\", boost::program_options::value<float>()->default_value( 1 ), \"a\")\n    (\"beta,b\", boost::program_options::value<float>()->default_value( 1 ), \"b\")\n    (\"length,l\", boost::program_options::value<float>()->default_value( 1 ), \"l\");\n  boost::program_options::variables_map params;\n  boost::program_options::store( boost::program_options::parse_command_line( argc, argv, options ), params );\n  boost::program_options::notify( params );\n  if( params.count(\"help\") ) {\n    std::cout << options << std::endl;\n    return 0;\n  }\n  float x0, x1, x2, y0, y1, y2;\n  float a = params[\"alpha\"].as<float>();\n  float b = params[\"beta\"].as<float>();\n  if( params[\"decay\"].as<bool>() ) {\n    const auto [d1,d2] = ifm::approxymate_decay( a, b, params[\"length\"].as<float>() );\n    x0 = 0;\n    x1 = d1;\n    x2 = d2;\n    y0 = ifm::get_exp_envelope( a, b, x0 );\n    y1 = ifm::get_exp_envelope( a, b, x1 );\n    y2 = ifm::get_exp_envelope( a, b, x2 );\n    std::cout << d1 << \" \" << d2 << std::endl;\n  }\n  else {\n    x0 = 0;\n    x1 = ifm::approxymate_attack( a, b, params[\"length\"].as<float>() );\n    x2 = params[\"length\"].as<float>();\n    y0 = ifm::get_exp_envelope( a, b, x0 );\n    y1 = ifm::get_exp_envelope( a, b, x1 );\n    y2 = ifm::get_exp_envelope( a, b, x2 );\n    std::cout << a << std::endl;\n  }\n  const auto [tangent0,shift0] = ifm::get_linear_interpolation( x0, y0, x1, y1 );\n  const auto [tangent1,shift1] = ifm::get_linear_interpolation( x1, y1, x2, y2 );\n  float diff = 0;\n  for( size_t i = 0; i != 1000; ++i ) {\n    float x = i * params[\"length\"].as<float>() / 1000.f;\n    float approx_y;\n    if( x < x1 ) approx_y = x * tangent0 + shift0;\n    else if( x < x2 ) approx_y = x * tangent1 + shift1;\n    else approx_y = y2;\n    float y = ifm::get_exp_envelope( a, b, x );\n    diff += approx_y - y;\n  }\n  std::cout << \"max(\" << tangent0 << \"x+\" << shift0 << \",\" << tangent1 << \"x+\" << shift1 << \",\" << y2 << \")\" << std::endl;\n  std::cout << \"diff: \" << diff/1000.f << std::endl;\n}\n\n", "meta": {"hexsha": "95e85e796eea66cdb8f86757957ca9fd3520d54e", "size": 3612, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/approx_env.cpp", "max_stars_repo_name": "Fadis/ifm", "max_stars_repo_head_hexsha": "8e538c67e756cfc4056bf406e578809dc2b462f9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 20.0, "max_stars_repo_stars_event_min_datetime": "2020-02-08T08:51:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-28T04:44:24.000Z", "max_issues_repo_path": "src/approx_env.cpp", "max_issues_repo_name": "Fadis/ifm", "max_issues_repo_head_hexsha": "8e538c67e756cfc4056bf406e578809dc2b462f9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-04-01T18:31:50.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-01T18:31:50.000Z", "max_forks_repo_path": "src/approx_env.cpp", "max_forks_repo_name": "Fadis/ifm", "max_forks_repo_head_hexsha": "8e538c67e756cfc4056bf406e578809dc2b462f9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.1333333333, "max_line_length": 122, "alphanum_fraction": 0.6625138427, "num_tokens": 1055, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.661922862511608, "lm_q2_score": 0.47268347662043286, "lm_q1q2_score": 0.3128799999065357}}
{"text": "/*\n * word2vec.cpp\n *\n */\n#include <fstream>\n#include <random>\n#include <set>\n#include <string>\n#include <utility>\n\n#include <boost/assert.hpp>\n\n#include \"core/utils.h\"\n#include \"core/functions.h\"\n#include \"core/updaters.h\"\n#include \"layers/contlayer.h\"\n#include \"layers/fclayer.h\"\n#include \"layers/smaxlayer.h\"\n\n#include \"word2vec.h\"\n\nusing namespace std;\nusing namespace boost;\nusing namespace yann;\nusing namespace yann::word2vec;\n\nnamespace yann::word2vec {\n\nclass DataSource_SkipGram : public Trainer::DataSource\n{\n  typedef vector<pair<MatrixSize, MatrixSize>> TestsVector;\n\npublic:\n  DataSource_SkipGram(\n      const Text & text,\n      const MatrixSize & window_size,\n      const MatrixSize & batch_size\n  ) :\n    _text(text),\n    _window_size(window_size),\n    _batch_size(batch_size),\n    _cur_pos(0)\n  {\n    YANN_CHECK_GT(_batch_size, 0);\n    YANN_CHECK_GT(_text.get_dictionary_size(), 0);\n\n    _tests = get_tests(_text, _window_size);\n    resize_batch(_inputs_batch, _batch_size, _text.get_dictionary_size());\n    resize_batch(_outputs_batch, _batch_size, _text.get_dictionary_size());\n  }\n  virtual ~DataSource_SkipGram()\n  {\n  }\n\n  // Trainer::DataSource overwrites\n  virtual std::string get_info() const\n  {\n    ostringstream oss;\n    oss << \"yann::DataSource_SkipGram(\"\n        << \"dictionary_size=\" << _text.get_dictionary_size()\n        << \", batch_size=\" << _batch_size\n        << \", window_size=\" << _window_size\n        << \", tests_num=\" << _tests.size()\n        << \")\";\n    return oss.str();\n  }\n  virtual MatrixSize get_batch_size() const\n  {\n    return _batch_size;\n  }\n\n  virtual MatrixSize get_num_batches() const\n  {\n    YANN_CHECK(_batch_size > 0);\n    return _tests.size() / _batch_size;\n  }\n\n  virtual void start_epoch()\n  {\n    _cur_pos = 0;\n\n    // todo: support sequential mode w/o shuffling too\n    auto rng = default_random_engine { };\n    shuffle(begin(_tests), end(_tests), rng);\n  }\n\n  virtual optional<Batch> get_next_batch()\n  {\n    YANN_CHECK_GE(_cur_pos, 0);\n    auto res = create_batch(_cur_pos);\n    if(res <= 0) {\n      return boost::none;\n    }\n    _cur_pos += res;\n    return Batch(_inputs_batch, _outputs_batch, get_batch_size()); // each row in the batch is a test\n  }\n  virtual void end_epoch()\n  {\n    // do nothing\n  }\n\npublic:\n  double test_all(const Network & nn)\n  {\n    size_t success_count = 0, total_count = 0;\n\n    VectorBatch outputs;\n    outputs.resizeLike(_outputs_batch);\n    for(MatrixSize start_pos = 0; ; ) {\n      auto res = create_batch(start_pos);\n      if(res <= 0) {\n        break;\n      }\n      start_pos += res;\n\n      nn.calculate(_inputs_batch, outputs);\n      for(MatrixSize jj = 0; jj < yann::get_batch_size(outputs); ++jj) {\n        const auto & actual = get_batch(outputs, jj);\n        const auto & expected = get_batch(_outputs_batch, jj);\n        MatrixSize aa = 0, ee = 0;\n        actual.array().maxCoeff(&aa);\n        expected.array().maxCoeff(&ee);\n        if(aa == ee) {\n          ++success_count;\n        }\n        ++total_count;\n      }\n    }\n\n    return total_count > 0 ? success_count / (double)total_count : 0.0;\n  }\n\nprivate:\n  MatrixSize create_batch(const MatrixSize & start_pos)\n  {\n    YANN_CHECK_GE(start_pos, 0);\n\n    _inputs_batch.setZero();\n    _outputs_batch.setZero();\n    for(MatrixSize ii = 0, pos = start_pos; ii < _batch_size; ++ii, ++pos) {\n      if(pos >= (MatrixSize)_tests.size()) {\n        return 0;\n      }\n      const auto & cur =  _tests[pos];\n      _inputs_batch.insert(ii, cur.first) = 1.0; // RowMajor\n      _outputs_batch(ii, cur.second) = 1.0; // RowMajor\n    }\n    return _batch_size;\n  }\n\n  static TestsVector get_tests(const Text & text, const MatrixSize & window_size)\n  {\n    TestsVector tests;\n    for(MatrixSize ii = 0, size = text.sentences().size(); ii < size; ++ii) {\n      const auto & sentence = text.sentences()[ii];\n      // sentence[jj] is the \"input\" word\n      for(MatrixSize jj = 0, sentence_size = sentence.size(); jj < sentence_size; ++jj) {\n        // sentence[kk] is the \"output\" word\n        for(MatrixSize kk = jj - window_size; kk <= jj + window_size; ++kk) {\n          // check if we are in-range and that we are not pointing to the word itself\n          if(kk < 0 || kk >= sentence_size || sentence[jj] == sentence[kk]) {\n            continue;\n          }\n          tests.push_back(make_pair(sentence[jj], sentence[kk]));\n        }\n      }\n    }\n    return tests;\n  }\n\n\nprivate:\n  const Text & _text;\n  const MatrixSize _window_size;\n  const MatrixSize _batch_size;\n\n  TestsVector _tests;\n  size_t      _cur_pos;\n\n  SparseVectorBatch _inputs_batch;\n  VectorBatch _outputs_batch;\n}; // class DataSource_SkipGram\n\n\nclass DataSource_CBOW : public Trainer::DataSource\n{\n  typedef set<MatrixSize> BagOfWords;\n  typedef vector<pair<MatrixSize, BagOfWords>> TestsVector;\n\npublic:\n  DataSource_CBOW(\n      const Text & text,\n      const MatrixSize & window_size,\n      const MatrixSize & batch_size\n  ) :\n    _text(text),\n    _window_size(window_size),\n    _batch_size(batch_size),\n    _cur_pos(0)\n  {\n    YANN_CHECK_GT(_batch_size, 0);\n    YANN_CHECK_GT(_text.get_dictionary_size(), 0);\n\n    _tests = get_tests(_text, _window_size);\n    resize_batch(_inputs_batch, _batch_size, _text.get_dictionary_size());\n    resize_batch(_outputs_batch, _batch_size, _text.get_dictionary_size());\n  }\n  virtual ~DataSource_CBOW()\n  {\n  }\n\n  // Trainer::DataSource overwrites\n  virtual std::string get_info() const\n  {\n    ostringstream oss;\n    oss << \"yann::DataSource_CBOW(\"\n        << \"dictionary_size=\" << _text.get_dictionary_size()\n        << \", batch_size=\" << _batch_size\n        << \", window_size=\" << _window_size\n        << \", tests_num=\" << _tests.size()\n        << \")\";\n    return oss.str();\n  }\n  virtual MatrixSize get_batch_size() const\n  {\n    return _batch_size;\n  }\n\n  virtual MatrixSize get_num_batches() const\n  {\n    YANN_CHECK(_batch_size > 0);\n    return _tests.size() / _batch_size;\n  }\n  virtual void start_epoch()\n  {\n    _cur_pos = 0;\n\n    // todo: support sequential mode w/o shuffling too\n    auto rng = default_random_engine { };\n    shuffle(begin(_tests), end(_tests), rng);\n  }\n\n  virtual optional<Batch> get_next_batch()\n  {\n    YANN_CHECK_GE(_cur_pos, 0);\n    auto res = create_batch(_cur_pos);\n    if(res <= 0) {\n      return boost::none;\n    }\n    _cur_pos += res;\n    return Batch(_inputs_batch, _outputs_batch, get_batch_size()); // each row in the batch is a test\n  }\n\n  virtual void end_epoch()\n  {\n    // do nothing\n  }\n\npublic:\n  double test_all(const Network & nn)\n  {\n    size_t success_count = 0, total_count = 0;\n\n    VectorBatch outputs;\n    outputs.resizeLike(_outputs_batch);\n    for(MatrixSize start_pos = 0; ; ) {\n      auto res = create_batch(start_pos);\n      if(res <= 0) {\n        break;\n      }\n      start_pos += res;\n\n      nn.calculate(_inputs_batch, outputs);\n      for(MatrixSize jj = 0; jj < yann::get_batch_size(outputs); ++jj) {\n        const auto & actual = get_batch(outputs, jj);\n        const auto & expected = get_batch(_outputs_batch, jj);\n        MatrixSize aa = 0, ee = 0;\n        actual.array().maxCoeff(&aa);\n        expected.array().maxCoeff(&ee);\n        if(aa == ee) {\n          ++success_count;\n        }\n        ++total_count;\n      }\n    }\n\n    return total_count > 0 ? success_count / (double)total_count : 0.0;\n  }\n\nprivate:\n  MatrixSize create_batch(const MatrixSize & start_pos)\n  {\n    YANN_CHECK_GE(start_pos, 0);\n\n    _inputs_batch.setZero();\n    _outputs_batch.setZero();\n    for(MatrixSize ii = 0, pos = start_pos; ii < _batch_size; ++ii, ++pos) {\n      if(pos >= (MatrixSize)_tests.size()) {\n        return 0;\n      }\n      const auto & cur =  _tests[pos];\n      _inputs_batch.insert(ii, cur.first) = 1.0; // RowMajor\n      for(const auto & val : cur.second) {\n        _outputs_batch(ii, val) = 1.0; // RowMajor\n      }\n    }\n    return _batch_size;\n  }\n\n  static TestsVector get_tests(const Text & text, const MatrixSize & window_size)\n  {\n    TestsVector tests;\n    for(MatrixSize ii = 0, size = text.sentences().size(); ii < size; ++ii) {\n      const auto & sentence = text.sentences()[ii];\n      // sentence[jj] is the \"current\" word\n      for(MatrixSize jj = 0, sentence_size = sentence.size(); jj < sentence_size; ++jj) {\n        // sentence[kk] is the \"bag\" word\n        BagOfWords bow;\n        for(MatrixSize kk = jj - window_size; kk <= jj + window_size; ++kk) {\n          // check if we are in-range and that we are not pointing to the word itself\n          if(kk < 0 || kk >= sentence_size || sentence[jj] == sentence[kk]) {\n            continue;\n          }\n          bow.insert(sentence[kk]);\n        }\n        tests.push_back(make_pair(sentence[jj], bow));\n      }\n    }\n    return tests;\n  }\n\n\nprivate:\n  const Text & _text;\n  const MatrixSize _window_size;\n  const MatrixSize _batch_size;\n\n  TestsVector _tests;\n  size_t      _cur_pos;\n\n  SparseVectorBatch _inputs_batch;\n  VectorBatch _outputs_batch;\n}; // class DataSource_CBOW\n\n}; // namespace yann::word2vec\n\n////////////////////////////////////////////////////////////////////////////////////////////////\n//\n// Word2Vec::TrainingParams implementation\n//\nyann::word2vec::Word2Vec::TrainingParams::TrainingParams():\n    _window_size(5),\n    _dimensions(100),\n    _updater(make_unique<Updater_GradientDescent>(0.9)),\n    _training_sampling_rate(0.0),\n    _training_batch_size(100),\n    _epochs(10),\n    _epochs_callback(nullptr),\n    _batch_callback(nullptr)\n{\n}\n\n////////////////////////////////////////////////////////////////////////////////////////////////\n//\n// Word2Vec implementation\n//\n\n// the format is (d:<dictionary>,v:<vectors>)\nostream& std::operator<<(ostream & os, const Word2Vec & w2v)\n{\n  os << \"(d:\" << w2v._dictionary << \",v:\" << w2v._vectors << \")\";\n  return os;\n}\n\n// the format is (d:<dictionary>,v:<vectors>)\nistream& std::operator>>(istream & is, Word2Vec & w2v)\n{\n  char ch;\n  if(is >> ch && ch != '(') {\n    is.putback(ch);\n    is.setstate(std::ios_base::failbit);\n    return is;\n  }\n  if(is >> ch && ch != 'd') {\n    is.putback(ch);\n    is.setstate(std::ios_base::failbit);\n    return is;\n  }\n  if(is >> ch && ch != ':') {\n    is.putback(ch);\n    is.setstate(std::ios_base::failbit);\n    return is;\n  }\n  is >> w2v._dictionary;\n  if(is.fail()) {\n    return is;\n  }\n  if(is >> ch && ch != ',') {\n    is.putback(ch);\n    is.setstate(std::ios_base::failbit);\n    return is;\n  }\n  if(is >> ch && ch != 'v') {\n    is.putback(ch);\n    is.setstate(std::ios_base::failbit);\n    return is;\n  }\n  if(is >> ch && ch != ':') {\n    is.putback(ch);\n    is.setstate(std::ios_base::failbit);\n    return is;\n  }\n  is >> w2v._vectors;\n  if(is.fail()) {\n    return is;\n  }\n  if(is >> ch && ch != ')') {\n    is.putback(ch);\n    is.setstate(std::ios_base::failbit);\n    return is;\n  }\n\n  return is;\n}\n\n\n// cos alpha = A * B / (|A| * |B|)\nValue yann::word2vec::Word2Vec::cosine(const RefConstVector & v1, const RefConstVector & v2)\n{\n  return (v1.array() * v2.array()).sum() / (v1.norm() * v2.norm());\n}\n\nyann::word2vec::Word2Vec::Word2Vec()\n{\n}\n\nyann::word2vec::Word2Vec::~Word2Vec()\n{\n}\n\nbool yann::word2vec::Word2Vec::is_equal(const Word2Vec& other, double tolerance) const\n{\n  return _dictionary == other._dictionary && _vectors.isApprox(other._vectors, tolerance);\n}\n\noptional<MatrixSize> yann::word2vec::Word2Vec::find_word(const std::string & word) const\n{\n  return _dictionary.find_word(word);\n}\noptional<const std::string &> yann::word2vec::Word2Vec::find_word(const MatrixSize & word_num) const\n{\n  return _dictionary.find_word(word_num);\n}\n\noptional<RefConstVector> yann::word2vec::Word2Vec::find_vector(const MatrixSize & word_num) const\n{\n  YANN_CHECK_LT(word_num, get_vectors_size());\n  RefConstVector vv = _vectors.row(word_num);\n  return vv;\n}\n\noptional<RefConstVector> yann::word2vec::Word2Vec::find_vector(const std::string & word) const\n{\n  auto word_num = find_word(word);\n  if(!word_num) {\n    return boost::none;\n  }\n  return find_vector(*word_num);\n}\n\n\nValue yann::word2vec::Word2Vec::distance(const MatrixSize & word_num1, const MatrixSize & word_num2) const\n{\n  auto vv1 = find_vector(word_num1);\n  auto vv2 = find_vector(word_num2);\n  return (vv1 && vv2) ? cosine(*vv1, *vv2) : 0;\n}\n\nValue yann::word2vec::Word2Vec::distance(const std::string word1, const std::string & word2) const\n{\n  auto vv1 = find_vector(word1);\n  auto vv2 = find_vector(word2);\n  return (vv1 && vv2) ? cosine(*vv1, *vv2) : 0;\n}\n\nvector<pair<const string &, Value>> yann::word2vec::Word2Vec::find_closest(const string & word, const size_t & num) const\n{\n  YANN_CHECK_GT(num, 0);\n\n  auto word_num = find_word(word);\n  if(!word_num) {\n    return vector<pair<const string &, Value>>(); // not found\n  }\n  auto vv = find_vector(*word_num);\n  YANN_CHECK(vv);\n\n  // compare by the vector distance\n  auto cmp = [](const auto & aa, const auto & bb) { return aa.second < bb.second; };\n  set<pair<MatrixSize, Value>, decltype(cmp)> ordered(cmp);\n  for(MatrixSize ii = 0; ii < _vectors.rows(); ++ii) {\n    if(ii == *word_num) continue; // ignore itself\n\n    auto distance = cosine(*vv, _vectors.row(ii));\n    ordered.insert(make_pair(ii, distance));\n    if(ordered.size() > num) {\n      ordered.erase(ordered.begin());\n    }\n  }\n\n  vector<pair<const string &, Value>> res;\n  res.reserve(ordered.size());\n  for(auto it = ordered.rbegin(); it != ordered.rend(); ++it) {\n    // can't use make_pair() because of \"const string &\"\n    res.push_back(pair<const string &, Value>(_dictionary.get_word(it->first), it->second));\n  }\n  return res;\n}\n\nvector<pair<const string &, Value>> yann::word2vec::Word2Vec::find_farthest(const string & word, const size_t & num) const\n{\n  YANN_CHECK_GT(num, 0);\n\n  auto word_num = find_word(word);\n  if(!word_num) {\n    return vector<pair<const string &, Value>>(); // not found\n  }\n  auto vv = find_vector(*word_num);\n  YANN_CHECK(vv);\n\n  // compare by the vector distance\n  auto cmp = [](const auto & aa, const auto & bb) { return aa.second > bb.second; };\n  set<pair<MatrixSize, Value>, decltype(cmp)> ordered(cmp);\n  for(MatrixSize ii = 0; ii < _vectors.rows(); ++ii) {\n    if(ii == *word_num) continue; // ignore itself\n\n    auto distance = cosine(*vv, _vectors.row(ii));\n    ordered.insert(make_pair(ii, distance));\n    if(ordered.size() > num) {\n      ordered.erase(ordered.begin());\n    }\n  }\n\n  vector<pair<const string &, Value>> res;\n  res.reserve(ordered.size());\n  for(auto it = ordered.rbegin(); it != ordered.rend(); ++it) {\n    // can't use make_pair() because of \"const string &\"\n    res.push_back(pair<const string &, Value>(_dictionary.get_word(it->first), it->second));\n  }\n  return res;\n}\n\nvoid yann::word2vec::Word2Vec::save(const string & filename) const\n{\n  ofstream ofs(filename, ofstream::out | ofstream::trunc);\n  if(!ofs || ofs.fail()) {\n    throw runtime_error(\"can't open file \" + filename);\n  }\n  ofs << (*this);\n  if(!ofs || ofs.fail()) {\n    throw runtime_error(\"can't write to file \" + filename);\n  }\n  ofs.close();\n}\n\nvoid yann::word2vec::Word2Vec::load(const std::string & filename)\n{\n  ifstream ifs(filename, ifstream::in);\n  if(!ifs || ifs.fail()) {\n    throw runtime_error(\"can't open file \" + filename);\n  }\n  ifs >> (*this);\n  if(!ifs || ifs.fail()) {\n    throw runtime_error(\"can't read file \" + filename);\n  }\n  ifs.close();\n}\n\ntemplate<typename DataSourceType>\nstd::unique_ptr<Word2Vec> yann::word2vec::Word2Vec::train(\n    const Text & text,\n    const TrainingParams & params,\n    DataSourceType & data_source)\n{\n  auto w2v = make_unique<Word2Vec>();\n  YANN_CHECK(w2v);\n\n  // create network\n  auto nn = make_unique<Network>();\n  YANN_CHECK(nn);\n  nn->set_cost_function(make_unique<CrossEntropyCost>());\n\n  auto fc_layer1 = make_unique<FullyConnectedLayer>(\n      text.get_dictionary_size(), params._dimensions);\n  fc_layer1->set_fixed_bias(0.0);\n  fc_layer1->set_activation_function(make_unique<IdentityFunction>());\n  if(0 < params._training_sampling_rate && params._training_sampling_rate < 1.0) {\n    fc_layer1->set_sampling_rate(params._training_sampling_rate);\n  }\n  nn->append_layer(std::move(fc_layer1));\n\n  auto fc_layer2 = make_unique<FullyConnectedLayer>(\n      params._dimensions, text.get_dictionary_size());\n  fc_layer2->set_fixed_bias(0.0);\n  fc_layer2->set_activation_function(make_unique<FastSigmoidFunction>());\n  if(0 < params._training_sampling_rate && params._training_sampling_rate < 1.0) {\n    fc_layer2->set_sampling_rate(params._training_sampling_rate);\n  }\n  nn->append_layer(std::move(fc_layer2));\n  nn->init(Layer::InitMode_Random, params._training_init_context);\n\n  // train the network\n  Trainer trainer(params._updater);\n  trainer.set_batch_progress_callback(params._batch_callback);\n  trainer.set_epochs_progress_callback(params._epochs_callback);\n  trainer.train(*nn, data_source, params._training_batch_size,  params._epochs);\n\n  // extract the weights\n  auto fc_layer = dynamic_cast<const FullyConnectedLayer*>(nn->get_layer(0));\n  YANN_CHECK(fc_layer);\n  w2v->_vectors = fc_layer->get_weights();\n  w2v->_dictionary = text.dictionary();\n\n  // done\n  return w2v;\n}\n\nunique_ptr<Word2Vec> yann::word2vec::Word2Vec::train_skip_gram(const Text & text, const TrainingParams & params)\n{\n  DataSource_SkipGram data_source(\n        text,\n        params._window_size,\n        params._training_batch_size);\n  return train(text, params, data_source);\n}\n\nstd::unique_ptr<Word2Vec> yann::word2vec::Word2Vec::train_cbow(const Text & text, const TrainingParams & params)\n{\n  DataSource_CBOW data_source(\n        text,\n        params._window_size,\n        params._training_batch_size);\n  return train(text, params, data_source);\n}\n", "meta": {"hexsha": "3e3c313f51693e4bcfba6bc203a13cfd2e0e4d53", "size": 17595, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/word2vec/word2vec.cpp", "max_stars_repo_name": "lsh123/yann", "max_stars_repo_head_hexsha": "4a12b7c1ee2d89d34772d647586b3018df6997db", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-08-22T18:14:44.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-01T10:25:07.000Z", "max_issues_repo_path": "src/word2vec/word2vec.cpp", "max_issues_repo_name": "lsh123/yann", "max_issues_repo_head_hexsha": "4a12b7c1ee2d89d34772d647586b3018df6997db", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/word2vec/word2vec.cpp", "max_forks_repo_name": "lsh123/yann", "max_forks_repo_head_hexsha": "4a12b7c1ee2d89d34772d647586b3018df6997db", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.3214285714, "max_line_length": 122, "alphanum_fraction": 0.6423984086, "num_tokens": 4743, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6113819874558603, "lm_q2_score": 0.5117166047041654, "lm_q1q2_score": 0.3128543147981974}}
{"text": "﻿/*******************************************************************\r\nAuthor: David Ge (dge893@gmail.com, aka Wei Ge)\r\nLast modified: 11/21/2020\r\nAllrights reserved by David Ge\r\n\r\nbase class for time advancement estimation module\r\n********************************************************************/\r\n#include \"TimeTssBase.h\"\r\n#include \"../FileUtil/fileutil.h\"\r\n#include \"../ProcessMonitor/ProcessMonitor.h\"\r\n#include \"../ProcessMonitor/workProcess.h\"\r\n\r\n#include <thread>\r\n\r\n#include <boost/multiprecision/cpp_dec_float.hpp>\r\n\r\nbool voidReport(){ return false; }\r\nTimeTssBase::TimeTssBase()\r\n{\r\n\tGehP = GhhP = GeeP = GheP = NULL;\r\n\tspace = NULL;\r\n\tH = E = curlH = curlE = NULL; // workH = workE = NULL;\r\n\tcurrentTime = 0.0;\r\n\ttIndex = 0;\r\n\treporter = NULL;\r\n\toperationCanceled = voidReport;\r\n}\r\n\r\n\r\nTimeTssBase::~TimeTssBase()\r\n{\r\n\tcleanup();\r\n}\r\nvoid TimeTssBase::cleanup()\r\n{\r\n\t//\r\n\tif (GehP != NULL)\r\n\t{\r\n\t\tfree(GehP); GehP = NULL;\r\n\t}\r\n\tif (GhhP != NULL)\r\n\t{\r\n\t\tfree(GhhP); GhhP = NULL;\r\n\t}\r\n\tif (GeeP != NULL)\r\n\t{\r\n\t\tfree(GeeP); GeeP = NULL;\r\n\t}\r\n\tif (GheP != NULL)\r\n\t{\r\n\t\tfree(GheP); GheP = NULL;\r\n\t}\r\n\t//\r\n\tif (H != NULL)\r\n\t{\r\n\t\tFreeMemory(H); H = NULL;\r\n\t}\r\n\tif (E != NULL)\r\n\t{\r\n\t\tFreeMemory(E); E = NULL;\r\n\t}\r\n\tif (curlH != NULL)\r\n\t{\r\n\t\tFreeMemory(curlH); curlH = NULL;\r\n\t}\r\n\tif (curlE != NULL)\r\n\t{\r\n\t\tFreeMemory(curlE); curlE = NULL;\r\n\t}\r\n}\r\nvoid TimeTssBase::onSettingSimParams()\r\n{\r\n\tcellCount = (pams->nx + 1)*(pams->ny + 1)*(pams->nz + 1);\r\n}\r\nint TimeTssBase::initializeTimeModule(Space *s, SimStruct *pams0, FieldSourceTss *src)\r\n{\r\n\tusing namespace boost::multiprecision;\r\n\tint ret = ERR_OK;\r\n\tputs(\"\\r\\nCalculating update coefficients...\");\r\n\tpams = pams0;\r\n\tonSettingSimParams();\r\n\tfieldMemorySize = cellCount*sizeof(Point3Dstruct);\r\n\tif (src != NULL)\r\n\t{\r\n\t\tif (!src->Initialized())\r\n\t\t{\r\n\t\t\treturn ERR_SRC_NOT_INIT;\r\n\t\t}\r\n\t}\r\n\tspace = s;\r\n\tsource = src;\r\n\tcpp_dec_float_100 *G_ehP = (cpp_dec_float_100 *)malloc((pams->kmax + 1)*sizeof(cpp_dec_float_100));\r\n\tcpp_dec_float_100 *G_hhP = (cpp_dec_float_100 *)malloc((pams->kmax + 1)*sizeof(cpp_dec_float_100));\r\n\tcpp_dec_float_100 *G_eeP = (cpp_dec_float_100 *)malloc((pams->kmax + 1)*sizeof(cpp_dec_float_100));\r\n\tcpp_dec_float_100 *G_heP = (cpp_dec_float_100 *)malloc((pams->kmax + 1)*sizeof(cpp_dec_float_100));\r\n\t//\r\n\tGehP = (double*)malloc((pams->kmax + 1)*sizeof(double));\r\n\tGhhP = (double*)malloc((pams->kmax + 1)*sizeof(double));\r\n\tGeeP = (double*)malloc((pams->kmax + 1)*sizeof(double));\r\n\tGheP = (double*)malloc((pams->kmax + 1)*sizeof(double));\r\n\tif (G_ehP == NULL || G_hhP == NULL || G_eeP == NULL || G_heP == NULL || GehP == NULL || GhhP == NULL || GeeP == NULL || GheP == NULL)\r\n\t{\r\n\t\tret = ERR_OUTOFMEMORY;\r\n\t}\r\n\telse\r\n\t{\r\n\t\tprintf(\"\\r\\nUpdate coefficients allocated. Array size:%u \", pams->kmax + 1);\r\n\t\tfor (unsigned int k = 0; k <= pams->kmax; k++)\r\n\t\t{\r\n\t\t\tG_ehP[k] = G_hhP[k] = G_eeP[k] = G_heP[k] = 0.0;\r\n\t\t\tGehP[k]  = GhhP[k]  = GeeP[k]  = GheP[k]  = 0.0;\r\n\t\t}\r\n\t}\r\n\tif (ret == ERR_OK)\r\n\t{\r\n\t\t/*\r\n\t\tp[h=0..2k_max+2,i=0..2k_max+2]=p_i^{h} \r\n\t\tq[h=0..2k_max+2,i=0..2k_max+2]=q_i^{h} \r\n\t\t*/\r\n\t\tsize_t pMax = 2 * pams->kmax + 3; // 0 ... 2kmax+2\r\n\t\tsize_t pMax2 = pMax * pMax;\r\n\t\t//p_i^{h}\r\n#define Idx_ih(i, h) ((h)*pMax+(i))\r\n\t\tcpp_dec_float_100 *p = (cpp_dec_float_100 *)malloc(pMax2*sizeof(cpp_dec_float_100));\r\n\t\tcpp_dec_float_100 *q = (cpp_dec_float_100 *)malloc(pMax2*sizeof(cpp_dec_float_100));\r\n\t\tcpp_dec_float_100 *dtR = (cpp_dec_float_100 *)malloc(pMax*sizeof(cpp_dec_float_100));\r\n\t\tcpp_dec_float_100 *dsR = (cpp_dec_float_100 *)malloc(pMax*sizeof(cpp_dec_float_100));\r\n\t\tif (p == NULL || q == NULL || dtR == NULL || dsR == NULL)\r\n\t\t{\r\n\t\t\tret = ERR_OUTOFMEMORY;\r\n\t\t}\r\n\t\tif (ret == ERR_OK)\r\n\t\t{\r\n\t\t\tcpp_dec_float_100 gde = pams->sie;\r\n\t\t\tcpp_dec_float_100 geps = pams->eps;\r\n\t\t\tcpp_dec_float_100 gmu = pams->mu;\r\n\t\t\tcpp_dec_float_100 gdm = pams->sim;\r\n\t\t\tcpp_dec_float_100 g1 = 1.0;\r\n\t\t\tcpp_dec_float_100 f;\r\n\t\t\t//values for k=0\r\n\t\t\tcpp_dec_float_100 dt2 = 1.0;\r\n\t\t\tcpp_dec_float_100 XN = 0.0;\r\n\t\t\tcpp_dec_float_100 X = 1.0;\r\n\t\t\tcpp_dec_float_100 ds2 = 1.0;\r\n\t\t\tfor (unsigned int k = 0; k < pMax2; k++)\r\n\t\t\t{\r\n\t\t\t\tp[k] = 0.0; q[k] = 0.0;\r\n\t\t\t}\r\n\t\t\t//p_0^0=1, q_0^0 = 1\r\n\t\t\tp[0] = 1.0; q[0] = 1.0;\r\n\t\t\tfor (unsigned int k = 0; k < pMax; k++)\r\n\t\t\t{\r\n\t\t\t\tf = dt2 / X;\r\n\t\t\t\tdtR[k] = f; //dt^k/k!\r\n\t\t\t\tdsR[k] = ds2; //ds^k\r\n\t\t\t\t//prepare for k+1\r\n\t\t\t\tXN = XN + 1.0;\r\n\t\t\t\tX = X * XN;\r\n\t\t\t\tdt2 = dt2 * pams->dt;\r\n\t\t\t\tds2 = ds2 * pams->ds;\r\n\t\t\t}\r\n\t\t\t/*\r\n\t\t\tp_0^{1} =1/ε,p_1^{1} =-σ/ε\r\n\t\t\tq_0^{1} =-1/μ,q_1^{1} =-σ_m/μ\r\n\t\t\t*/\r\n\t\t\tp[Idx_ih(0, 1)] = g1 / geps; p[Idx_ih(1, 1)] = -gde / geps;\r\n\t\t\tq[Idx_ih(0, 1)] = -g1 / gmu; q[Idx_ih(1, 1)] = -gdm / gmu;\r\n\t\t\t/*\r\n\t\t\tp_0^{2k}  =q_0^{1}  p_0^{2k-1} \r\n\t\t\tp_2k^{2k} =p_(2k-1)^{2k-1}  p_1^{1}\r\n\t\t\tq_0^{2k}  =p_0^{1}  q_0^{2k-1} \r\n\t\t\tq_2k^{2k} =q_(2k-1)^{2k-1}  q_1^{1}\r\n\r\n\t\t\tp_0^{2k+1}      =p_0^{1}  p_0^{2k} \r\n\t\t\tp_(2k+1)^{2k+1} =p_2k^{2k}  p_1^{1} \r\n\t\t\tq_0^{2k+1}      =q_0^{1}  q_0^{2k} \r\n\t\t\tq_(2k+1)^{2k+1} =q_2k^{2k}  q_1^{1}\r\n\t\t\t*/\r\n\t\t\t//from (0,1), (1,1) get\r\n\t\t\t//(0,2)...(0,2kmax+2); (2,2) ... (2kmax+2,2kmax+2)\r\n\t\t\t//(0,3)...(0,2kmax+1); (3,3) ... (2kmax+1,2kmax+1)\r\n\t\t\tfor (unsigned int k = 1; k <= pams->kmax + 1; k++)\r\n\t\t\t{\r\n\t\t\t\tp[Idx_ih(0, 2 * k)] = q[Idx_ih(0, 1)] * p[Idx_ih(0, 2 * k - 1)];\r\n\t\t\t\tq[Idx_ih(0, 2 * k)] = p[Idx_ih(0, 1)] * q[Idx_ih(0, 2 * k - 1)];\r\n\t\t\t\tp[Idx_ih(2 * k, 2 * k)] = p[Idx_ih(2 * k - 1, 2 * k - 1)] * p[Idx_ih(1, 1)];\r\n\t\t\t\tq[Idx_ih(2 * k, 2 * k)] = q[Idx_ih(2 * k - 1, 2 * k - 1)] * q[Idx_ih(1, 1)];\r\n\t\t\t\tif (k <= pams->kmax)\r\n\t\t\t\t{\r\n\t\t\t\t\tp[Idx_ih(0, 2 * k + 1)] = p[Idx_ih(0, 1)] * p[Idx_ih(0, 2 * k)];\r\n\t\t\t\t\tq[Idx_ih(0, 2 * k + 1)] = q[Idx_ih(0, 1)] * q[Idx_ih(0, 2 * k)];\r\n\t\t\t\t\tp[Idx_ih(2 * k + 1, 2 * k + 1)] = p[Idx_ih(2 * k, 2 * k)] * p[Idx_ih(1, 1)];\r\n\t\t\t\t\tq[Idx_ih(2 * k + 1, 2 * k + 1)] = q[Idx_ih(2 * k, 2 * k)] * q[Idx_ih(1, 1)];\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\t/*\r\n\t\t\tp_(2i+1)^{2k} =q_1^{1}  p_2i^{2k-1} +p_0^{1}  p_(2i+1)^{2k-1} ;    i=0,1,…,k-1;k_max+1≥k>0\r\n\t\t\tq_(2i+1)^{2k} =p_1^{1}  q_2i^{2k-1} +q_0^{1}  q_(2i+1)^{2k-1} ;    i=0,1,…,k-1;k_max+1≥k>0\r\n\t\t\tp_(2i+2)^{2k} =p_1^{1}  p_(2i+1)^{2k-1} +q_0^{1}  p_(2i+2)^{2k-1} ;i=0,1,…,k-2;k_max+1≥k>1\r\n\t\t\tq_(2i+2)^{2k} =q_1^{1}  q_(2i+1)^{2k-1} +p_0^{1}  q_(2i+2)^{2k-1} ;i=0,1,…,k-2;k_max+1≥k>1\r\n\t\t\t*/\r\n\t\t\tfor (unsigned int k = 1; k <= pams->kmax + 1; k++)\r\n\t\t\t{\r\n\t\t\t\tfor (unsigned int i = 0; i < k; i++)\r\n\t\t\t\t{\r\n\t\t\t\t\tp[Idx_ih(2 * i + 1, 2 * k)] = q[Idx_ih(1, 1)] * p[Idx_ih(2 * i, 2 * k - 1)] + p[Idx_ih(0, 1)] * p[Idx_ih(2 * i + 1, 2 * k - 1)];\r\n\t\t\t\t\tq[Idx_ih(2 * i + 1, 2 * k)] = p[Idx_ih(1, 1)] * q[Idx_ih(2 * i, 2 * k - 1)] + q[Idx_ih(0, 1)] * q[Idx_ih(2 * i + 1, 2 * k - 1)];\r\n\t\t\t\t\tif (k>1 && i < k - 1)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tp[Idx_ih(2 * i + 2, 2 * k)] = p[Idx_ih(1, 1)] * p[Idx_ih(2 * i + 1, 2 * k - 1)] + q[Idx_ih(0, 1)] * p[Idx_ih(2 * i + 2, 2 * k - 1)];\r\n\t\t\t\t\t\tq[Idx_ih(2 * i + 2, 2 * k)] = q[Idx_ih(1, 1)] * q[Idx_ih(2 * i + 1, 2 * k - 1)] + p[Idx_ih(0, 1)] * q[Idx_ih(2 * i + 2, 2 * k - 1)];\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\tif (k <= pams->kmax)\r\n\t\t\t\t{\r\n\t\t\t\t\t/*\r\n\t\t\t\t\tp_(2i-1)^{2k+1} =p_1^{1}  p_(2i-2)^{2k} +q_0^{1}  p_(2i-1)^{2k}\r\n\t\t\t\t\tp_2i    ^{2k+1} =q_1^{1}  p_(2i-1)^{2k} +p_0^{1}  p_2i^{2k}\r\n\t\t\t\t\tq_(2i-1)^{2k+1} =q_1^{1}  q_(2i-2)^{2k} +p_0^{1}  q_(2i-1)^{2k}\r\n\t\t\t\t\tq_2i    ^{2k+1} =p_1^{1}  q_(2i-1)^{2k} +q_0^{1}  q_2i^{2k}\r\n\t\t\t\t\ti=1,2,…,k;k≥1\r\n\t\t\t\t\t*/\r\n\t\t\t\t\tfor (unsigned int i = 1; i <= k; i++)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tp[Idx_ih(2 * i - 1, 2 * k + 1)] = p[Idx_ih(1, 1)] * p[Idx_ih(2 * i - 2, 2 * k)] + q[Idx_ih(0, 1)] * p[Idx_ih(2 * i - 1, 2 * k)];\r\n\t\t\t\t\t\tq[Idx_ih(2 * i - 1, 2 * k + 1)] = q[Idx_ih(1, 1)] * q[Idx_ih(2 * i - 2, 2 * k)] + p[Idx_ih(0, 1)] * q[Idx_ih(2 * i - 1, 2 * k)];\r\n\t\t\t\t\t\tp[Idx_ih(2 * i, 2 * k + 1)] = q[Idx_ih(1, 1)] * p[Idx_ih(2 * i - 1, 2 * k)] + p[Idx_ih(0, 1)] * p[Idx_ih(2 * i, 2 * k)];\r\n\t\t\t\t\t\tq[Idx_ih(2 * i, 2 * k + 1)] = p[Idx_ih(1, 1)] * q[Idx_ih(2 * i - 1, 2 * k)] + q[Idx_ih(0, 1)] * q[Idx_ih(2 * i, 2 * k)];\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\t////calculate G_e^h, G_h^h, G_h^e, G_e^e///////////////////////////////\r\n\t\t\tcpp_dec_float_100 a, b, c;\r\n\t\t\t/*\r\n\t\t\ti=0,1,...,kmax\r\n\t\t\tG_e^h (i,∆_t)=∑_(k=i)^(k_max)〖C_e^h (k,i,∆_t ) 〗\r\n\t\t\tG_h^h (i,∆_t)=∑_(k=i)^(k_max)〖C_h^h (k,i,∆_t ) 〗\r\n\t\t\tG_h^e (i,∆_t)=∑_(k=i)^(k_max)〖C_h^e (k,i,∆_t ) 〗\r\n\t\t\tG_e^e (i,∆_t)=∑_(k=i)^(k_max)〖C_e^e (k,i,∆_t ) 〗\r\n\t\t\t//\r\n\t\t\tsum k=i,i+1,...,kmax\r\n\t\t\tstart from (∆_t^(2i+1))/(2i+1)! go up\r\n\t\t\t-------------------------------------\r\n\t\t\tC_e^h (k,i,∆_t )= ((∆_t^(2k+1))/(2k+1)! q_0^{2k+1}                                        ,i=k\r\n\t\t\t\t\t\t\t  (∆_t^2k)/(2k)! q_(2(k-i)-1)^{2k} + (∆_t^(2k+1))/(2k+1)! q_2(k-i)^{2k+1} ,0≤i<k\r\n\t\t\t//\r\n\t\t\tC_h^e (k,i,∆_t )= ((∆_t^(2k+1))/(2k+1)! p_0^{2k+1}                                        ,i=k\r\n\t\t\t\t\t\t\t  (∆_t^2k)/(2k)! p_(2(k-i)-1)^{2k} + (∆_t^(2k+1))/(2k+1)! p_2(k-i)^{2k+1} ,0≤i<k\r\n\t\t\t====================\r\n\t\t\tC_h^h (k,i,∆_t )=(∆_t^2k)/(2k)! q_2(k-i)^{2k} +(∆_t^(2k+1))/(2k+1)! q_(2(k-i)+1)^{2k+1} \r\n\t\t\tC_e^e (k,i,∆_t )=(∆_t^2k)/(2k)! p_2(k-i)^{2k} +(∆_t^(2k+1))/(2k+1)! p_(2(k-i)+1)^{2k+1}\r\n\t\t\t--------------------------------\r\n\t\t\t*/\r\n\t\t\tfor (unsigned int i = 0; i <= pams->kmax; i++)\r\n\t\t\t{\r\n\t\t\t\tG_ehP[i] = 0.0; G_hhP[i] = 0.0; G_eeP[i] = 0.0; G_heP[i] = 0.0;\r\n\t\t\t\tfor (unsigned int k = i; k <= pams->kmax; k++)\r\n\t\t\t\t{\r\n\t\t\t\t\ta = q[Idx_ih(2 * (k - i), 2 * k)];\r\n\t\t\t\t\tb = p[Idx_ih(2 * (k - i), 2 * k)];\r\n\t\t\t\t\tG_hhP[i] += dtR[2*k] * a;\r\n\t\t\t\t\tG_eeP[i] += dtR[2*k] * b;\r\n\t\t\t\t\t//\r\n\t\t\t\t\ta = q[Idx_ih(2 * (k - i)+1, 2 * k+1)];\r\n\t\t\t\t\tb = p[Idx_ih(2 * (k - i)+1, 2 * k+1)];\r\n\t\t\t\t\tG_hhP[i] += dtR[2 * k+1] * a;\r\n\t\t\t\t\tG_eeP[i] += dtR[2 * k+1] * b;\r\n\t\t\t\t\t//\r\n\t\t\t\t\tif (k == i)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\ta = q[Idx_ih(0, 2 * k + 1)];\r\n\t\t\t\t\t\tb = p[Idx_ih(0, 2 * k + 1)];\r\n\t\t\t\t\t\tG_ehP[i] += dtR[2 * k + 1] * a;\r\n\t\t\t\t\t\tG_heP[i] += dtR[2 * k + 1] * b;\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\ta = q[Idx_ih(2 * (k - i) - 1, 2 * k)];\r\n\t\t\t\t\t\tb = p[Idx_ih(2 * (k - i) - 1, 2 * k)];\r\n\t\t\t\t\t\tG_ehP[i] += dtR[2 * k] * a;\r\n\t\t\t\t\t\tG_heP[i] += dtR[2 * k] * b;\r\n\t\t\t\t\t\t//\r\n\t\t\t\t\t\ta = q[Idx_ih(2 * (k - i), 2 * k + 1)];\r\n\t\t\t\t\t\tb = p[Idx_ih(2 * (k - i), 2 * k + 1)];\r\n\t\t\t\t\t\tG_ehP[i] += dtR[2 * k+1] * a;\r\n\t\t\t\t\t\tG_heP[i] += dtR[2 * k+1] * b;\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\t/*\r\n\t\t\tG_h^h (i,∆_t ) ∇ ̅^{2i} ×H+G_e^h (i,∆_t ) ∇ ̅^{2i+1} ×E\r\n\t\t\tG_e^e (i,∆_t ) ∇ ̅^{2i} ×E+G_h^e (i,∆_t ) ∇ ̅^{2i+1} ×H\r\n\t\t\t*/\r\n\t\t\tfor (unsigned int i = 0; i <= pams->kmax; i++)\r\n\t\t\t{\r\n\t\t\t\tG_ehP[i] = G_ehP[i] / dsR[2 * i + 1];\r\n\t\t\t\tG_heP[i] = G_heP[i] / dsR[2 * i + 1];\r\n\t\t\t\tG_hhP[i] = G_hhP[i] / dsR[2 * i];\r\n\t\t\t\tG_eeP[i] = G_eeP[i] / dsR[2 * i];\r\n\t\t\t}\r\n\t\t\tfor (unsigned int i = 0; i <= pams->kmax; i++)\r\n\t\t\t{\r\n\t\t\t\tGehP[i] = G_ehP[i].convert_to<double>();\r\n\t\t\t\tGheP[i] = G_heP[i].convert_to<double>();\r\n\t\t\t\tGhhP[i] = G_hhP[i].convert_to<double>();\r\n\t\t\t\tGeeP[i] = G_eeP[i].convert_to<double>();\r\n\t\t\t}\r\n\t\t\tfree(G_ehP); free(G_heP); free(G_hhP); free(G_eeP);\r\n\t\t\tif (source != NULL)\r\n\t\t\t{\r\n\t\t\t\tif (ret == ERR_OK)\r\n\t\t\t\t{\r\n\t\t\t\t\tunsigned int emMax = source->GetemMax(); //2 * kmax + 3;\r\n\t\t\t\t\tsize_t emMax2 = emMax*emMax;\r\n\t\t\t\t\tcpp_dec_float_100 *e = (cpp_dec_float_100 *)malloc(emMax2*sizeof(cpp_dec_float_100));\r\n\t\t\t\t\tcpp_dec_float_100 *m = (cpp_dec_float_100 *)malloc(emMax2*sizeof(cpp_dec_float_100));\r\n\t\t\t\t\tsize_t t,t1;\r\n\t\t\t\t\tfor (t = 0; t < emMax2; t++)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\te[t] = 0.0; m[t] = 0.0;\r\n\t\t\t\t\t}\r\n\t\t\t\t\t/*\r\n\t\t\t\t\tEq. (16), (17)\r\n\t\t\t\t\te_0^{0} =-1/ε\r\n\t\t\t\t\tm_0^{0} =-1/μ\r\n\t\t\t\t\t*/\r\n\t\t\t\t\te[I_ih(0, 0)] = -1.0 / pams->eps;\r\n\t\t\t\t\tm[I_ih(0, 0)] = -1.0 / pams->mu;\r\n\t\t\t\t\t/*\r\n\t\t\t\t\tEq. (18)\r\n\t\t\t\t\te_2(k-i)^{2i} =p_(2(k-i))^{2k}  e_0^{0} ,\r\n\t\t\t\t\tm_2(k-i)^{2i} =q_(2(k-i))^{2k}  m_0^{0} ,\r\n\t\t\t\t\ti=0,1,2,…,k, k>0\t\t\t\t\t\r\n\t\t\t\t\t*/\r\n\t\t\t\t\tfor (unsigned int k = 1; k <= pams->kmax + 1; k++)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tfor (unsigned int i = 0; i <= k; i++)\r\n\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t//0...2kmax+2\r\n\t\t\t\t\t\t\tt = I_ih(2 * (k - i), 2 * i); //[2kmax+2, (2kmax), ..., 0], {0, 2, ..., 2kmax+2}\r\n\t\t\t\t\t\t\te[t] = p[Idx_ih(2 * (k - i), 2 * k)] * e[I_ih(0, 0)];\r\n\t\t\t\t\t\t\tm[t] = q[Idx_ih(2 * (k - i), 2 * k)] * m[I_ih(0, 0)];\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t\t/*\r\n\t\t\t\t\tEq. (19)\r\n\t\t\t\t\tm_(2(k-i)+1)^{2i-1} =p_(2(k-i)+1)^{2k}  m_0^{0} ,\r\n\t\t\t\t\te_(2(k-i)+1)^{2i-1} =q_(2(k-i)+1)^{2k}  e_0^{0} ,\r\n\t\t\t\t\ti=1,2,…,k,k>0\r\n\t\t\t\t\t*/\r\n\t\t\t\t\tfor (unsigned int k = 1; k <= pams->kmax + 1; k++)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tfor (unsigned int i = 1; i <= k; i++)\r\n\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\tt = I_ih(2 * (k - i) + 1, 2 * i - 1);//[2kmax+1,2kmax-1,...,1], {1,3,...,2kmax+1}\r\n\t\t\t\t\t\t\tm[t] = p[Idx_ih(2 * (k - i) + 1, 2 * k)] * m[I_ih(0, 0)];\r\n\t\t\t\t\t\t\te[t] = q[Idx_ih(2 * (k - i) + 1, 2 * k)] * e[I_ih(0, 0)];\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t\t/*\r\n\t\t\t\t\tEq. (26)\r\n\t\t\t\t\te_(2(k-i)-1)^{2i} =p_(2(k-i)-1)^{2k-1}  e_0^{0} ,\r\n\t\t\t\t\tm_(2(k-i)-1)^{2i} =q_(2(k-i)-1)^{2k-1}  m_0^{0} ,\r\n\t\t\t\t\ti=0,1,2,…,k-1, k>0\r\n\t\t\t\t\tEq. (27)\r\n\t\t\t\t\tm_(2(k-i-1))^{2i+1} =p_(2(k-i-1))^{2k-1}  m_0^{0} ,\r\n\t\t\t\t\te_(2(k-i-1))^{2i+1} =q_(2(k-i-1))^{2k-1}  e_0^{0} ,\r\n\t\t\t\t\ti=0,1,2,…,k-1, k>0\r\n\t\t\t\t\t*/\r\n\t\t\t\t\tfor (unsigned int k = 1; k <= pams->kmax + 1; k++)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tfor (unsigned int i = 0; i < k; i++)\r\n\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\tt = I_ih(2 * (k - i) - 1, 2 * i);//[2kmax+1,2kmax-1,...,1],{0,2,...,2kmax+2}\r\n\t\t\t\t\t\t\tt1 = Idx_ih(2 * (k - i) - 1, 2 * k - 1);\r\n\t\t\t\t\t\t\te[t] = p[t1] * e[I_ih(0, 0)];\r\n\t\t\t\t\t\t\tm[t] = q[t1] * m[I_ih(0, 0)];\r\n\t\t\t\t\t\t\tt = I_ih(2 * (k - i - 1), 2 * i + 1);//[2kmax,2kmax-2,...,0],{1,2,...,2kmax+1}\r\n\t\t\t\t\t\t\tt1 = Idx_ih(2 * (k - i - 1), 2 * k - 1);\r\n\t\t\t\t\t\t\tm[t] = p[t1] * m[I_ih(0, 0)];\r\n\t\t\t\t\t\t\te[t] = q[t1] * e[I_ih(0, 0)];\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t\tret = source->onInitialized(e, m);\r\n\t\t\t\t\tfree(e); free(m);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\tif (p != NULL) { free(p); p = NULL; }\r\n\t\tif (q != NULL) { free(q); q = NULL; }\r\n\t}\r\n\tif (ret == ERR_OK)\r\n\t{\r\n\t\tstartThreads();\r\n\t\tret = pml.initialize(pams);\r\n\t}\r\n\tif (ret == ERR_OK)\r\n\t{\r\n\t\tputs(\"\\r\\nFinished calculating update coefficients.\");\r\n\t}\r\n\treturn ret;\r\n}\r\nint TimeTssBase::initFields(FieldsSetter* f0)\r\n{\r\n\tint ret = ERR_OK;\r\n\tputs(\"\\r\\nAllocating field memories...\");\r\n\t//\r\n\t//all field memories used\r\n\tif (H != NULL) \r\n\t{\r\n\t\tFreeMemory(H); H = NULL;\r\n\t}\r\n\tif (E != NULL)\r\n\t{\r\n\t\tFreeMemory(E); E = NULL;\r\n\t}\r\n\tif (curlH != NULL)\r\n\t{\r\n\t\tFreeMemory(curlH); curlH = NULL;\r\n\t}\r\n\tif (curlE != NULL)\r\n\t{\r\n\t\tFreeMemory(curlE); curlE = NULL;\r\n\t}\r\n\tH = (Point3Dstruct *)AllocateMemory(fieldMemorySize);\r\n\tif (H == NULL)\r\n\t{\r\n\t\tret = MEMRETLAST;\r\n\t\tif (ret == ERR_OK)\r\n\t\t{\r\n\t\t\tret = ERR_OUTOFMEMORY;\r\n\t\t}\r\n\t}\r\n\tif (ret == ERR_OK)\r\n\t{\r\n\t\tE = (Point3Dstruct *)AllocateMemory(fieldMemorySize);\r\n\t\tif (E == NULL)\r\n\t\t{\r\n\t\t\tret = MEMRETLAST;\r\n\t\t\tif (ret == ERR_OK)\r\n\t\t\t{\r\n\t\t\t\tret = ERR_OUTOFMEMORY;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\tif (ret == ERR_OK)\r\n\t{\r\n\t\tcurlH = (Point3Dstruct *)AllocateMemory(fieldMemorySize);\r\n\t\tif (curlH == NULL)\r\n\t\t{\r\n\t\t\tret = MEMRETLAST;\r\n\t\t\tif (ret == ERR_OK)\r\n\t\t\t{\r\n\t\t\t\tret = ERR_OUTOFMEMORY;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\tif (ret == ERR_OK)\r\n\t{\r\n\t\tcurlE = (Point3Dstruct *)AllocateMemory(fieldMemorySize);\r\n\t\tif (curlE == NULL)\r\n\t\t{\r\n\t\t\tret = MEMRETLAST;\r\n\t\t\tif (ret == ERR_OK)\r\n\t\t\t{\r\n\t\t\t\tret = ERR_OUTOFMEMORY;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\tif (ret == ERR_OK)\r\n\t{\r\n\t\tsize_t w = 0;\r\n\t\tdouble x = pams->xmin, y, z;\r\n\t\tputs(\"\\r\\nInitializing fields...\");\r\n\t\tfor (unsigned int i = 0; i <= pams->nx; i++)\r\n\t\t{\r\n\t\t\ty = pams->ymin;\r\n\t\t\tfor (unsigned int j = 0; j <= pams->ny; j++)\r\n\t\t\t{\r\n\t\t\t\tz = pams->zmin;\r\n\t\t\t\tfor (unsigned int k = 0; k <= pams->nz; k++)\r\n\t\t\t\t{\r\n\t\t\t\t\tif (f0 != NULL)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tf0->SetFields(x, y, z, &(E[w]), &(H[w]));\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\tE[w].x = 0.0;\r\n\t\t\t\t\t\tE[w].y = 0.0;\r\n\t\t\t\t\t\tE[w].z = 0.0;\r\n\t\t\t\t\t\tH[w].x = 0.0;\r\n\t\t\t\t\t\tH[w].y = 0.0;\r\n\t\t\t\t\t\tH[w].z = 0.0;\r\n\t\t\t\t\t}\r\n\t\t\t\t\tz += pams->ds;\r\n\t\t\t\t\tw++;\r\n\t\t\t\t}\r\n\t\t\t\ty += pams->ds;\r\n\t\t\t}\r\n\t\t\tx += pams->ds;\r\n\t\t}\r\n\t}\r\n\treturn ret;\r\n}\r\n\r\nint TimeTssBase::writeCoefficientsToFile(char *file, unsigned int maxTimeSteps, double courantFactor, unsigned int dataFileSteps)\r\n{\r\n\tint ret = ERR_OK;\r\n\tFILE *retFileHandle = 0;\r\n\tif (file != NULL)\r\n\t{\r\n\t\tret = deleteFile(file);\r\n\t\tif (ret == ERR_OK)\r\n\t\t{\r\n\t\t\tret = openTextfileWrite(file, &retFileHandle);\r\n\t\t}\r\n\t}\r\n\telse\r\n\t{\r\n\t\tret = ERR_FILENAME_MISSING;\r\n\t}\r\n\tif (retFileHandle != 0)\r\n\t{\r\n\t\tunsigned int size = 1024;\r\n\t\tchar buff[1024];\r\n\t\tsprintf_1(buff, size, \"kmax=%u, time estimation order = 2(kmax+1)=%u \\nds=%g, dt=%g, courant factor=%g, total time=%g, data file interval=%g\\n\", pams->kmax, 2 * (pams->kmax + 1), pams->ds, pams->dt, courantFactor, pams->dt*maxTimeSteps, pams->dt*dataFileSteps);\r\n\t\twritefile(retFileHandle, buff, (unsigned int)strnlen_0(buff, size));\r\n\t\tsprintf_1(buff, size, \"material parameters: eps=%g, mu=%g, sigma_e=%g, sigma_h=%g\\r\\n\", pams->eps, pams->mu, pams->sie, pams->sim);\r\n\t\twritefile(retFileHandle, buff, (unsigned int)strnlen_0(buff, size));\r\n\t\t////////////H/////////////////////////////////////////////\r\n\t\tsprintf_1(buff, size, \"H=C.F.dJm+C.G.dJe+\");\r\n\t\twritefile(retFileHandle, buff, (unsigned int)strnlen_0(buff, size));\r\n\t\t//Curl X H -> H\r\n\t\tfor (unsigned int k = 0; k <= pams->kmax; k++)\r\n\t\t{\r\n\t\t\tif (k == 0)\r\n\t\t\t{\r\n\t\t\t\tif (k == pams->kmax)\r\n\t\t\t\t{\r\n\t\t\t\t\tsprintf_1(buff, size, \"[%g]C2xH+\", GhhP[k]);\r\n\t\t\t\t}\r\n\t\t\t\telse\r\n\t\t\t\t{\r\n\t\t\t\t\tsprintf_1(buff, size, \"[%g,\", GhhP[k]);\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\tif (k == pams->kmax)\r\n\t\t\t\t{\r\n\t\t\t\t\tsprintf_1(buff, size, \" %g]C2xH+\", GhhP[k]);\r\n\t\t\t\t}\r\n\t\t\t\telse\r\n\t\t\t\t{\r\n\t\t\t\t\tsprintf_1(buff, size, \" %g,\", GhhP[k]);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\twritefile(retFileHandle, buff, (unsigned int)strnlen_0(buff, size));\r\n\t\t}\r\n\t\t//CE->H\r\n\t\tfor (unsigned int k = 0; k <= pams->kmax; k++)\r\n\t\t{\r\n\t\t\tif (k == 0)\r\n\t\t\t{\r\n\t\t\t\tif (k == pams->kmax)\r\n\t\t\t\t{\r\n\t\t\t\t\tsprintf_1(buff, size, \"[%g]C1xE\\r\\n\", GehP[k]);\r\n\t\t\t\t}\r\n\t\t\t\telse\r\n\t\t\t\t{\r\n\t\t\t\t\tsprintf_1(buff, size, \"[%g,\", GehP[k]);\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\tif (k == pams->kmax)\r\n\t\t\t\t{\r\n\t\t\t\t\tsprintf_1(buff, size, \" %g]C1xE\\n\", GehP[k]);\r\n\t\t\t\t}\r\n\t\t\t\telse\r\n\t\t\t\t{\r\n\t\t\t\t\tsprintf_1(buff, size, \" %g,\", GehP[k]);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\twritefile(retFileHandle, buff, (unsigned int)strnlen_0(buff, size));\r\n\t\t}\r\n\t\t///////////////E///////////\r\n\t\tsprintf_1(buff, size, \"\\nE=C.U.dJe+C.W.dJm+\");\r\n\t\twritefile(retFileHandle, buff, (unsigned int)strnlen_0(buff, size));\r\n\t\t//Curl X E -> E\r\n\t\tfor (unsigned int k = 0; k <= pams->kmax; k++)\r\n\t\t{\r\n\t\t\tif (k == 0)\r\n\t\t\t{\r\n\t\t\t\tif (k == pams->kmax)\r\n\t\t\t\t{\r\n\t\t\t\t\tsprintf_1(buff, size, \"[%g]C2xE+\", GeeP[k]);\r\n\t\t\t\t}\r\n\t\t\t\telse\r\n\t\t\t\t{\r\n\t\t\t\t\tsprintf_1(buff, size, \"[%g,\", GeeP[k]);\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\tif (k == pams->kmax)\r\n\t\t\t\t{\r\n\t\t\t\t\tsprintf_1(buff, size, \" %g]C2xE+\", GeeP[k]);\r\n\t\t\t\t}\r\n\t\t\t\telse\r\n\t\t\t\t{\r\n\t\t\t\t\tsprintf_1(buff, size, \" %g,\", GeeP[k]);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\twritefile(retFileHandle, buff, (unsigned int)strnlen_0(buff, size));\r\n\t\t}\r\n\t\t//CH->E\r\n\t\tfor (unsigned int k = 0; k <= pams->kmax; k++)\r\n\t\t{\r\n\t\t\tif (k == 0)\r\n\t\t\t{\r\n\t\t\t\tif (k == pams->kmax)\r\n\t\t\t\t{\r\n\t\t\t\t\tsprintf_1(buff, size, \"[%g]C1xH\\n\", GheP[k]);\r\n\t\t\t\t}\r\n\t\t\t\telse\r\n\t\t\t\t{\r\n\t\t\t\t\tsprintf_1(buff, size, \"[%g,\", GheP[k]);\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\tif (k == pams->kmax)\r\n\t\t\t\t{\r\n\t\t\t\t\tsprintf_1(buff, size, \" %g]C1xH\\n\", GheP[k]);\r\n\t\t\t\t}\r\n\t\t\t\telse\r\n\t\t\t\t{\r\n\t\t\t\t\tsprintf_1(buff, size, \" %g,\", GheP[k]);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\twritefile(retFileHandle, buff, (unsigned int)strnlen_0(buff, size));\r\n\t\t}\r\n\t\tif (source != NULL)\r\n\t\t{\r\n\t\t\tdouble *f = source->GetJmH();\r\n\t\t\tdouble *g = source->GetJeH();\r\n\t\t\tdouble *u = source->GetJeE();\r\n\t\t\tdouble *w = source->GetJmE();\r\n\t\t\tunsigned int srcDim = source->GetsrcDim();\r\n\t\t\tunsigned int t = 0;\r\n\t\t\t//SH=============================================\r\n\t\t\tsprintf_1(buff, size, \"\\nF[ %u x %u ]=\\n\", srcDim, srcDim);\r\n\t\t\twritefile(retFileHandle, buff, (unsigned int)strnlen_0(buff, size));\r\n\t\t\tt = 0;\r\n\t\t\tfor (unsigned int i = 0; i < srcDim; i++)\r\n\t\t\t{\r\n\t\t\t\tfor (unsigned int j = 0; j < srcDim; j++)\r\n\t\t\t\t{\r\n\t\t\t\t\tif (j == srcDim - 1)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tsprintf_1(buff, size, \" %g\\n\", f[t]);\r\n\t\t\t\t\t}\r\n\t\t\t\t\telse\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tsprintf_1(buff, size, \" %g,\\t\", f[t]);\r\n\t\t\t\t\t}\r\n\t\t\t\t\twritefile(retFileHandle, buff, (unsigned int)strnlen_0(buff, size));\r\n\t\t\t\t\tt++;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tsprintf_1(buff, size, \" \\nG[ %u x %u ]=\\n\", srcDim, srcDim);\r\n\t\t\twritefile(retFileHandle, buff, (unsigned int)strnlen_0(buff, size));\r\n\t\t\tt = 0;\r\n\t\t\tfor (unsigned int i = 0; i < srcDim; i++)\r\n\t\t\t{\r\n\t\t\t\tfor (unsigned int j = 0; j < srcDim; j++)\r\n\t\t\t\t{\r\n\t\t\t\t\tif (j == srcDim - 1)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tsprintf_1(buff, size, \" %g\\n\", g[t]);\r\n\t\t\t\t\t}\r\n\t\t\t\t\telse\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tsprintf_1(buff, size, \" %g,\\t\", g[t]);\r\n\t\t\t\t\t}\r\n\t\t\t\t\twritefile(retFileHandle, buff, (unsigned int)strnlen_0(buff, size));\r\n\t\t\t\t\tt++;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\t//SE=============================================\r\n\t\t\tsprintf_1(buff, size, \"\\nU[ %u x %u ]=\\n\", srcDim, srcDim);\r\n\t\t\twritefile(retFileHandle, buff, (unsigned int)strnlen_0(buff, size));\r\n\t\t\tt = 0;\r\n\t\t\tfor (unsigned int i = 0; i < srcDim; i++)\r\n\t\t\t{\r\n\t\t\t\tfor (unsigned int j = 0; j < srcDim; j++)\r\n\t\t\t\t{\r\n\t\t\t\t\tif (j == srcDim - 1)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tsprintf_1(buff, size, \" %g\\n\", u[t]);\r\n\t\t\t\t\t}\r\n\t\t\t\t\telse\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tsprintf_1(buff, size, \" %g,\\t\", u[t]);\r\n\t\t\t\t\t}\r\n\t\t\t\t\twritefile(retFileHandle, buff, (unsigned int)strnlen_0(buff, size));\r\n\t\t\t\t\tt++;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tsprintf_1(buff, size, \"\\nW[ %u x %u ]=\\n\", srcDim, srcDim);\r\n\t\t\twritefile(retFileHandle, buff, (unsigned int)strnlen_0(buff, size));\r\n\t\t\tt = 0;\r\n\t\t\tfor (unsigned int i = 0; i < srcDim; i++)\r\n\t\t\t{\r\n\t\t\t\tfor (unsigned int j = 0; j < srcDim; j++)\r\n\t\t\t\t{\r\n\t\t\t\t\tif (j == srcDim - 1)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tsprintf_1(buff, size, \" %g\\n\", w[t]);\r\n\t\t\t\t\t}\r\n\t\t\t\t\telse\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tsprintf_1(buff, size, \" %g,\\t\", w[t]);\r\n\t\t\t\t\t}\r\n\t\t\t\t\twritefile(retFileHandle, buff, (unsigned int)strnlen_0(buff, size));\r\n\t\t\t\t\tt++;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}//source\r\n\t\tif (pml.usePML())\r\n\t\t{\r\n\t\t\tpml.writeCoefficientsToFile(retFileHandle);\r\n\t\t}\r\n\t}\r\n\tif (retFileHandle != 0)\r\n\t{\r\n\t\tclosefile(retFileHandle);\r\n\t}\r\n\treturn ret;\r\n}\r\n\r\nint TimeTssBase::saveFieldToFile(char *filename, FIELD_EMTYPE fieldToSave)\r\n{\r\n\tint ret = ERR_OK;\r\n\tFILE *fp = NULL;\r\n\tret = openfileWrite(filename, &fp);\r\n\tif (ret != ERR_OK || fp == NULL)\r\n\t{\r\n\t\tif (ret == ERR_OK)\r\n\t\tret = ERR_FILE_OPEN_WRIT_EACCES;\r\n\t}\r\n\telse\r\n\t{\r\n\t\tsize_t sizew; \r\n\t\tif (fieldToSave == Field_E)\r\n\t\t{\r\n\t\t\tsizew = fwrite(getRawMemoryE(), sizeof(Point3Dstruct), cellCount, fp);\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\tsizew = fwrite(getRawMemoryH(), sizeof(Point3Dstruct), cellCount, fp);\r\n\t\t}\r\n\t\tfclose(fp);\r\n\t\tif (sizew != cellCount)\r\n\t\t{\r\n\t\t\tret = ERR_FILE_WRITE_LESS;\r\n\t\t}\r\n\t}\r\n\treturn ret;\r\n}\r\n\r\nint TimeTssBase::loadFieldFromFile(char *filename, FIELD_EMTYPE fieldToLoad)\r\n{\r\n\tint ret = ERR_OK;\r\n\tsize_t fSize = 0;\r\n\tPoint3Dstruct *f = (Point3Dstruct *)ReadFileIntoMemory(filename, &fSize, &ret);\r\n\tif (ret == ERR_OK)\r\n\t{\r\n\t\tif (fieldMemorySize != fSize)\r\n\t\t{\r\n\t\t\tret = ERR_FILESIZE_MISMATCH;\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\tPoint3Dstruct *field;\r\n\t\t\tif (fieldToLoad == Field_E)\r\n\t\t\t{\r\n\t\t\t\tfield = getRawMemoryE();\r\n\t\t\t}\r\n\t\t\telse\r\n\t\t\t{\r\n\t\t\t\tfield = getRawMemoryH();\r\n\t\t\t}\r\n\t\t\tfor (size_t w = 0; w < cellCount; w++)\r\n\t\t\t{\r\n\t\t\t\tfield[w].x = f[w].x;\r\n\t\t\t\tfield[w].y = f[w].y;\r\n\t\t\t\tfield[w].z = f[w].z;\r\n\t\t\t}\r\n\t\t}\r\n\t\tFreeMemory(f);\r\n\t}\r\n\treturn ret;\r\n}\r\n\r\n\r\n", "meta": {"hexsha": "f771a80fe589103ed0a6366beeb337f771a5721b", "size": 22665, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Source Code V2/Tss/TimeTssBase.cpp", "max_stars_repo_name": "DavidGeUSA/TSS", "max_stars_repo_head_hexsha": "e364e324948c68efc6362a0db3aa51696227fa60", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 11.0, "max_stars_repo_stars_event_min_datetime": "2020-09-27T07:35:22.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-09T11:01:31.000Z", "max_issues_repo_path": "Source Code V2/Tss/TimeTssBase.cpp", "max_issues_repo_name": "DavidGeUSA/TSS", "max_issues_repo_head_hexsha": "e364e324948c68efc6362a0db3aa51696227fa60", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-10-28T13:14:58.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-28T21:04:44.000Z", "max_forks_repo_path": "Source Code V2/Tss/TimeTssBase.cpp", "max_forks_repo_name": "DavidGeUSA/TSS", "max_forks_repo_head_hexsha": "e364e324948c68efc6362a0db3aa51696227fa60", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2020-09-27T07:35:24.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-02T13:53:21.000Z", "avg_line_length": 28.0160692213, "max_line_length": 264, "alphanum_fraction": 0.4717846901, "num_tokens": 9912, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6113819732941511, "lm_q2_score": 0.5117166047041654, "lm_q1q2_score": 0.3128543075514157}}
{"text": "//\n// $Id: filter.hpp 5313 2013-12-17 18:06:54Z chambm $\n//\n//\n// Original author: Witold Wolski <wewolski@gmail.com>\n//\n// Copyright : ETH Zurich\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\"); \n// you may not use this file except in compliance with the License. \n// You may obtain a copy of the License at \n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software \n// distributed under the License is distributed on an \"AS IS\" BASIS, \n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. \n// See the License for the specific language governing permissions and \n// limitations under the License.\n//\n\n#ifndef FILTERUTILS_H\n#define FILTERUTILS_H\n#include <math.h>\n#include <algorithm>\n#include <vector>\n#include <functional>\n#include <numeric>\n#include <limits>\n\n#include <boost/iterator/reverse_iterator.hpp>\n#include <boost/bind.hpp>\n#include <boost/math/distributions/normal.hpp>\n#include <boost/cstdint.hpp>\n\n\n#include \"pwiz/utility/findmf/base/filter/utilities/preparedata.hpp\"\n\n\nnamespace ralab\n{\n  namespace base\n  {\n    namespace filter\n    {\n\n      typedef boost::uint32_t uint32_t;\n      template <typename TIterator, typename TFilterIterator, typename TOutputIterator>\n      void filter_sequence(\n          TIterator  dataBeg,   //!<[in] a univariate time series.\n          TIterator  dataEnd,\n          TFilterIterator filterBeg, //!<[in] a vector of filter coefficients in reverse time order (as for AR or MA coefficients). Lenght of filter must be odd.\n          size_t fsize,\n          TOutputIterator resBeg, //!<[out] result\n          bool circular = false, //!<[in]  If TRUE, wrap the filter around the ends of the series, otherwise assume external values are missing (NA).\n          uint32_t sides = 2  //!<[in] currently only sides 2 supported....\n          )\n      {\n        typedef typename std::iterator_traits<TOutputIterator>::value_type TReal;\n        if((fsize-1) % 2)\n          {\n            throw std::logic_error(\"filter size must be odd\");\n          }\n        if(!circular)\n          {\n            //result.assign(data.size(), std::numeric_limits<TReal>::quiet_NaN() );\n\n            size_t offset = static_cast<size_t>(fsize/2);\n            for(std::size_t i = 0 ; i< offset; ++i, ++resBeg)\n              {\n                *resBeg = std::numeric_limits<TReal>::quiet_NaN();\n              }\n\n            for( ; dataBeg != dataEnd - (fsize -1) ; ++dataBeg, ++resBeg )\n              {\n                *resBeg = (std::inner_product(dataBeg , dataBeg + fsize, filterBeg ,0. ));\n              }\n          }\n        else\n          {\n\n            std::vector<typename std::iterator_traits<TIterator>::value_type> tmp;\n            typename std::vector<typename std::iterator_traits<TIterator>::value_type>::iterator it;\n            it = utilities::prepareData( dataBeg, dataEnd, fsize , tmp );\n\n            TIterator tbegin = tmp.begin();\n            TIterator tend = it;\n\n            for( ; tbegin != tend - (fsize-1 ) ; ++tbegin, ++resBeg )\n              {\n                *resBeg = std::inner_product(tbegin , tbegin + fsize, filterBeg ,0. );\n              }\n          }\n      }// filter end\n\n\n\n      /*! \\brief Applies linear convolution (filtering) to a univariate time series\n\n            The convolution filter is  \\f$ y[i] = f[1]*x[i+o] + ... + f[p]*x[i+o-(p-1)] \\f$\n            where o is the offset: see sides for how it is determined.\n\n            \\param sides for convolution filters only.\n                        If sides=1 the filter coefficients are for past values only;\n                        if sides=2 they are centred around lag 0.\n                        In this case the length of the filter should be odd,\n                        but if it is even, more of the filter is forward in time than backward\n\n\n            */\n      template <typename TContainer>\n      void filter(\n          const TContainer & data,   //!<[in] a univariate time series.\n          const TContainer & filter, //!<[in] a vector of filter coefficients in reverse time order (as for AR or MA coefficients). Lenght of filter must be odd.\n          TContainer & result, //!<[out] result\n          bool circular = false, //!<[in]  If TRUE, wrap the filter around the ends of the series, otherwise assume external values are missing (NA).\n          uint32_t sides = 2  //!<[in] currently only sides 2 supported....\n          )\n      {\n        result.resize(data.size());\n        filter_sequence\n            (\n              data.begin(),\n              data.end(),\n              filter.begin(),\n              filter.size(),\n              result.begin(),\n              circular,\n              sides\n              );\n      }// filter end\n    }//filter\n  }//base\n}//ralab\n\n\n\n\n\n#endif\n\n\n", "meta": {"hexsha": "1dffa3e08d6354aefdad39a50623c92250a6265e", "size": 4804, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "pwiz/utility/findmf/base/filter/filter.hpp", "max_stars_repo_name": "edyp-lab/pwiz-mzdb", "max_stars_repo_head_hexsha": "d13ce17f4061596c7e3daf9cf5671167b5996831", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 11.0, "max_stars_repo_stars_event_min_datetime": "2015-01-08T08:33:44.000Z", "max_stars_repo_stars_event_max_datetime": "2019-07-12T06:14:54.000Z", "max_issues_repo_path": "pwiz/utility/findmf/base/filter/filter.hpp", "max_issues_repo_name": "shze/pwizard-deb", "max_issues_repo_head_hexsha": "4822829196e915525029a808470f02d24b8b8043", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 61.0, "max_issues_repo_issues_event_min_datetime": "2015-05-27T11:20:11.000Z", "max_issues_repo_issues_event_max_datetime": "2019-12-20T15:06:21.000Z", "max_forks_repo_path": "pwiz/utility/findmf/base/filter/filter.hpp", "max_forks_repo_name": "shze/pwizard-deb", "max_forks_repo_head_hexsha": "4822829196e915525029a808470f02d24b8b8043", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2016-02-03T09:41:16.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-01T18:42:36.000Z", "avg_line_length": 33.5944055944, "max_line_length": 161, "alphanum_fraction": 0.590549542, "num_tokens": 1124, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6113819732941511, "lm_q2_score": 0.5117166047041654, "lm_q1q2_score": 0.3128543075514157}}
{"text": "/*!@file\n * @copyright This code is licensed under the 3-clause BSD license.\n *   Copyright ETH Zurich, Laboratory of Physical Chemistry, Reiher Group.\n *   See LICENSE.txt for details.\n */\n\n#include \"Molassembler/DistanceGeometry/TetrangleSmoothing.h\"\n#include \"Molassembler/DistanceGeometry/ValueBounds.h\"\n#include \"Molassembler/Temple/constexpr/Array.h\"\n#include \"Molassembler/Temple/constexpr/Numeric.h\"\n#include \"Molassembler/Temple/Invoke.h\"\n\n#include <Eigen/Dense>\n#include <cfenv>\n\nnamespace Scine {\nnamespace Molassembler {\nnamespace DistanceGeometry {\n\nstruct LU {\n  Eigen::Matrix4d L = Eigen::Matrix4d::Zero();\n  Eigen::Matrix4d U = Eigen::Matrix4d::Zero();\n\n  LU(\n    const Eigen::MatrixXd& bounds,\n    const std::array<unsigned, 4>& indices\n  ) {\n    for(unsigned i = 0; i < 4; ++i) {\n      for(unsigned j = i + 1; j < 4; ++j) {\n        unsigned a = indices[i];\n        unsigned b = indices[j];\n        if(a > b) {\n          std::swap(a, b);\n        }\n\n        U(i, j) = bounds(a, b);\n        U(j, i) = bounds(a, b);\n        L(i, j) = bounds(b, a);\n        L(j, i) = bounds(b, a);\n      }\n    }\n  }\n\n  EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n};\n\n// Named parameters to indicate when indices passed to lower and upper are ordered\nstruct OrderedIndicesTag {};\nconstexpr OrderedIndicesTag orderedIndicesTag;\n\nconstexpr unsigned pickMissingInZeroToThree(unsigned a, unsigned b, unsigned c) {\n  if(\n    !(a < 4 && b < 4 && c < 4)\n    || a == b\n    || a == c\n    || b == c\n  ) {\n    throw std::logic_error(\"Unsafe arguments!\");\n  }\n\n  unsigned x = 0;\n\n  for(unsigned i = 0; i < 4; ++i) {\n    if(a != i && b != i && c != i) {\n      x = i;\n      break;\n    }\n  }\n\n  return x;\n}\n\nstruct TriCheckResult {\n  /* Lower and upper bounds on the 3-4/k-l distance as per triangle\n   * inequalities\n   */\n  double klLowerBound; // l3_lim\n  double klUpperBound; // u3_lim\n\n  /* Whether or not the various triangle limits can be attained without\n   * violating any of the passed bounds.\n   */\n  bool l_col = false;\n  bool u_col = false;\n};\n\ntemplate<typename MatrixType, typename ... AssumeISmallerJPack>\nstd::conditional_t<\n  std::is_const<std::remove_reference_t<MatrixType>>::value,\n  double,\n  double&\n> upper(MatrixType&& matrix, const unsigned i, const unsigned j, AssumeISmallerJPack ... pack) {\n  if(sizeof...(pack) > 0) {\n    return matrix(i, j);\n  }\n\n  if(i < j) {\n    return matrix(i, j);\n  }\n\n  return matrix(j, i);\n}\n\ntemplate<typename MatrixType, typename ... AssumeISmallerJPack>\nstd::conditional_t<\n  std::is_const<std::remove_reference_t<MatrixType>>::value,\n  double,\n  double&\n> lower(MatrixType&& matrix, const unsigned i, const unsigned j, AssumeISmallerJPack ... pack) {\n  if(sizeof...(pack) > 0) {\n    return matrix(j, i);\n  }\n\n  if(i < j) {\n    return matrix(j, i);\n  }\n\n  return matrix(i, j);\n}\n\ndouble T(\n  const double d_pr,\n  const double d_qr,\n  const double d_ps,\n  const double d_qs\n) {\n  if(d_pr + d_qr > d_ps + d_qs || d_pr + d_qr < std::fabs(d_ps - d_qs)) {\n    throw std::logic_error(\"T preconditions violated!\");\n  }\n\n  return (\n    d_pr * (std::pow(d_qs, 2) - std::pow(d_qr, 2))\n    + d_qr * (std::pow(d_ps, 2) - std::pow(d_pr, 2))\n  ) / (d_pr + d_qr);\n}\n\nbool collinear(\n  const double d_pr,\n  const double d_qr,\n  const double l_ps,\n  const double l_qs,\n  const double l_rs,\n  const double u_ps,\n  const double u_qs,\n  const double u_rs\n) {\n  auto U = [&]() -> double {\n    if(d_pr + d_qr < u_ps - u_qs) {\n      return std::pow(d_qr + u_qs, 2);\n    }\n\n    if(d_pr + d_qr < u_qs - u_ps) {\n      return std::pow(d_pr + u_ps, 2);\n    }\n\n    return T(d_pr, d_qr, u_ps, u_qs);\n  };\n\n  auto L = [&]() -> double {\n    if(d_pr + d_qr > l_ps + l_qs) {\n      return std::pow(\n        std::max({\n          0.0,\n          d_qr - u_qs,\n          d_pr - u_ps,\n          l_qs - d_qr,\n          l_ps - d_pr\n        }),\n        2\n      );\n    }\n\n    if(d_pr + d_qr < l_ps - l_qs) {\n      return std::pow(l_ps - d_pr, 2);\n    }\n\n    if(d_pr + d_qr < l_qs - l_ps) {\n      return std::pow(l_qs - d_qr, 2);\n    }\n\n    return T(d_pr, d_qr, l_ps, l_qs);\n  };\n\n  return (\n    d_pr + d_qr <= u_ps + u_qs\n    && u_rs >= L()\n    && l_rs <= U()\n  );\n}\n\n[[gnu::pure]] constexpr unsigned decrement(unsigned i) {\n  if(i == 0) {\n    throw std::logic_error(\"Underflow\");\n  }\n\n  return i - 1;\n}\n\n/* limitTest overload set definitions section */\n\ntemplate<bool isUpper, unsigned i, unsigned j, unsigned k>\nstd::enable_if_t<isUpper, bool> limitTest(\n  const Eigen::Matrix4d& lower,\n  const Eigen::Matrix4d& upper,\n  const double minimalUpperLimit,\n  const double tripletLimit\n) {\n  // Triangle upper limit test\n  static_assert(i == 2 && k == 3, \"Unexpected instantiation!\");\n  constexpr unsigned l = pickMissingInZeroToThree(i, j, k);\n  static_assert(j < 4 && l < 4, \"Zero-based indices\");\n\n  return (\n    tripletLimit == minimalUpperLimit\n    && collinear(\n      upper(i, decrement(3)),\n      upper(i, decrement(4)),\n      lower(j, decrement(3)),\n      lower(j, decrement(4)),\n      lower(i, j),\n      upper(j, decrement(3)),\n      upper(j, decrement(4)),\n      upper(i, j)\n    )\n  );\n}\n\ntemplate<bool isUpper, unsigned i, unsigned k, unsigned l>\nstd::enable_if_t<!isUpper, bool> limitTest(\n  const Eigen::Matrix4d& lower,\n  const Eigen::Matrix4d& upper,\n  const double maximalLowerLimit,\n  const double tripletLimit\n) {\n  // Triangle lower limit test\n  constexpr unsigned j = pickMissingInZeroToThree(i, k, l);\n  return(\n    tripletLimit == maximalLowerLimit\n    && collinear(\n      upper(i, k),\n      /* Paper has l_3(b_k, b_l) below, assuming that's a typo, as it would\n       * mean the lower triangle inequality bound between k and l instead\n       * of the current lower bound on that quantity. There is no such\n       * subscripted quantity in the place of the paper where triangle upper\n       * limit tests are performed.\n       */\n      lower(k, l),\n      lower(i, j),\n      lower(j, l),\n      lower(j, k),\n      upper(i, j),\n      upper(j, l),\n      upper(j, k)\n    )\n  );\n}\n\ntemplate<bool isUpper, unsigned k, unsigned i, unsigned j, unsigned l>\nstd::enable_if_t<isUpper, bool> limitTest(\n  const Eigen::Matrix4d& lower,\n  const Eigen::Matrix4d& upper,\n  const double minimalUpperLimit,\n  const double quadrupletLimit\n) {\n  // Tetrangle upper limit test\n  if(quadrupletLimit == minimalUpperLimit) {\n    const double firstConditionA = upper(j, k);\n    const double firstConditionB = (\n      upper(i, k) + upper(i, j)\n    );\n    const double firstConditionC = lower(j, k);\n\n    // ujk >= uik + uij >= ljk\n    if(firstConditionA >= firstConditionB && firstConditionB >= firstConditionC) {\n      const double secondConditionA = upper(i, l);\n      const double secondConditionB = (\n        upper(j, l) + upper(i, l)\n      );\n      const double secondConditionC = lower(i, l);\n\n      // uil >= ujl + uil >= lil\n      return (secondConditionA >= secondConditionB && secondConditionB >= secondConditionC);\n    }\n\n    return false;\n  }\n\n  return false;\n}\n\n// First set of 4-atom lower limits with L[i, k, l, j] with {k, l} = {3, 4}\ntemplate<bool isUpper, unsigned i, unsigned k, unsigned l, unsigned j>\nstd::enable_if_t<\n  !isUpper && (\n    (k == 2 && l == 3) || (k == 3 && l == 2)\n  ),\n  bool\n> limitTest(\n  const Eigen::Matrix4d& lower,\n  const Eigen::Matrix4d& upper,\n  const double maximalLowerLimit,\n  const double quadrupletLimit\n) {\n  if(quadrupletLimit == maximalLowerLimit) {\n    const double firstConditionA = upper(i, k);\n    const double firstConditionB = lower(i, j) - upper(i, k);\n    const double firstConditionC = lower(j, k);\n\n    // uik >= lij - uik >= ljk\n    if(firstConditionA >= firstConditionB && firstConditionB >= firstConditionC) {\n      const double secondConditionA = upper(i, l);\n      const double secondConditionB = lower(i, j) - upper(j, l);\n      const double secondConditionC = lower(i, l);\n\n      // uil >= lij - ujl >= lil\n      return (secondConditionA >= secondConditionB && secondConditionB >= secondConditionC);\n    }\n\n    return false;\n  }\n\n  return false;\n}\n\n/* Second set of 4-atom lower limits with L[i, j, k, l] with {k, l} = {3, 4}\n * Here, k and l are the last two indices instead of in the middle.\n */\ntemplate<bool isUpper, unsigned i, unsigned j, unsigned k, unsigned l>\nstd::enable_if_t<\n  !isUpper && (\n    (k == 2 && l == 3) || (k == 3 && l == 2)\n  ),\n  bool\n> limitTest(\n  const Eigen::Matrix4d& lower,\n  const Eigen::Matrix4d& upper,\n  const double maximalLowerLimit,\n  const double quadrupletLimit\n) {\n  if(quadrupletLimit == maximalLowerLimit) {\n    const double firstConditionA = upper(j, l);\n    const double firstConditionB = lower(i, l) - upper(i, j);\n    const double firstConditionC = lower(j, l);\n\n    // ujl >= lil - uij >= ljl\n    if(firstConditionA >= firstConditionB && firstConditionB >= firstConditionC) {\n      const double secondConditionA = upper(i, k);\n      const double secondConditionB = upper(i, j) + upper(j, k);\n      const double secondConditionC = lower(i, k);\n\n      // uik >= uij + ujk >= lik\n      return (secondConditionA >= secondConditionB && secondConditionB >= secondConditionC);\n    }\n\n    return false;\n  }\n\n  return false;\n}\n\nbool triangleInequalitiesHold(const Eigen::Matrix3d& matrix) {\n  // Ensure triangle inequalities are satisified in this matrix\n  for(unsigned k = 0; k < 3; ++k) {\n    for(unsigned i = 0; i < 3; ++i) {\n      for(unsigned j = i + 1; j < 3; ++j) {\n        if(upper(matrix, i, j, orderedIndicesTag) > upper(matrix, i, k) + upper(matrix, k, j)) {\n          return false;\n        }\n\n        if(lower(matrix, i, j, orderedIndicesTag) < lower(matrix, i, k) - upper(matrix, k, j)) {\n          return false;\n        }\n      }\n    }\n  }\n\n  return true;\n}\n\nbool zeroBoundTest(\n  const Eigen::Matrix4d& lower,\n  const Eigen::Matrix4d& upper,\n  const double maximalLowerLimit\n) {\n  auto l = [&lower](unsigned i, unsigned j) {\n    return lower(decrement(i), decrement(j));\n  };\n  auto u = [&upper](unsigned i, unsigned j) {\n    return upper(decrement(i), decrement(j));\n  };\n\n  if(maximalLowerLimit == 0.0) {\n    Eigen::Matrix3d c;\n\n    // if i < j, then i,j an upper bound, i > j, a lower bound\n    c(1, 0) = l(1, 2);\n    c(0, 1) = u(1, 2);\n    c(2, 0) = std::max(l(1, 3), l(1, 4));\n    c(0, 2) = std::min(u(1, 3), u(1, 4));\n    c(2, 1) = std::max(l(2, 3), l(2, 4));\n    c(1, 2) = std::min(u(2, 3), u(2, 4));\n\n    return triangleInequalitiesHold(c);\n  }\n\n  return false;\n}\n\n/* This function is a catch-all for the various bounds calculated in the\n * beginning of triCheck based on an index_sequence type argument.\n *\n * Although it may seem ridiculous to instantiate this for each index sequence\n * if the matrix element access is resolved at runtime anyway, using\n * index_sequence to store the various sequences allows for code reuse in the\n * checking stage of triCheck. It also allows us to group the expressions\n * for the various bounds nicely.\n *\n * Note that this takes zero-based indices! Make sure to use decrement() for\n * the index_sequence with which this is instantiated.\n */\nconstexpr unsigned NAngleBoundNoneValue = 100;\ntemplate<bool isUpper, bool firstPattern, unsigned i, unsigned j, unsigned k, unsigned l = NAngleBoundNoneValue>\ndouble NAngleBound(const Eigen::Matrix4d& lower, const Eigen::Matrix4d& upper) {\n  static_assert(i < 4 && j < 4 && k < 4, \"Zero-based indices!\");\n  static_assert(l == NAngleBoundNoneValue || l < 4, \"Optional d argument is not zero-based!\");\n\n  // NOTE all ifs here could be if constexpr in C++17\n  if(l == NAngleBoundNoneValue) {\n    // Triangle algorithms\n    if(isUpper) {\n      // Upper triangle bound\n      return upper(i, j) + upper(j, k);\n    }\n\n    // Lower triangle bound\n    return lower(i, k) - upper(i, j);\n  }\n\n  // Tetrangle algorithms: l != NAngleBoundNoneValue\n  if(isUpper) {\n    // Upper tetrangle bound\n    return upper(i, j) + upper(j, k) + upper(k, l);\n  }\n\n  // Lower tetrangle bound (THESE ARE IRREGULAR!)\n  if(firstPattern) {\n    return lower(i, l) - upper(i, j) - upper(k, l); // for the first two\n  }\n\n  return lower(i, l) - upper(i, j) - upper(j, k); // for the last four\n}\n\ntemplate<bool isUpper, bool firstPattern, std::size_t ... Inds>\ndouble NAngleBoundsMap(const Eigen::Matrix4d& lower, const Eigen::Matrix4d& upper, std::index_sequence<Inds ...> /* inds */) {\n  // Raise the index sequence from function argument to template argument\n  return NAngleBound<isUpper, firstPattern, decrement(Inds)...>(lower, upper);\n}\n\ntemplate<typename TupleType, bool isUpper, bool firstPattern, std::size_t ... TupleInds>\nauto mapIndexSetsHelper(const Eigen::Matrix4d& lower, const Eigen::Matrix4d& upper, std::index_sequence<TupleInds ...> /* inds */) {\n  // Create an array with the results of bounds evaluations\n  return std::array<double, sizeof...(TupleInds)> {\n    NAngleBoundsMap<isUpper, firstPattern>(\n      lower,\n      upper,\n      std::tuple_element_t<TupleInds, TupleType> {}\n    )...\n  };\n}\n\n/* isUpper denotes whether we are calculating an upper or lower bound\n * firstPattern is only for the tetrangle lower limits, where there are two\n * index patterns.\n */\ntemplate<typename TupleType, bool isUpper, bool firstPattern>\nauto mapIndexSets(const Eigen::Matrix4d& lower, const Eigen::Matrix4d& upper) {\n  // Enumerate the index sequences in TupleType\n  return mapIndexSetsHelper<TupleType, isUpper, firstPattern>(\n    lower,\n    upper,\n    std::make_index_sequence<std::tuple_size<TupleType>::value> {}\n  );\n}\n\ntemplate<typename ArgsTuple, typename CallableArgPair>\nbool foldCallableArgsPairLogicalOr(\n  const ArgsTuple& args,\n  CallableArgPair&& a\n) {\n  /* Piece together the arguments in order to call LimitTester::operator(),\n   * which forwards its arguments to the limitTest overload set\n   *\n   * The CallableArgPair is created in limitAnyOfHelper and consists of a\n   * LimitTester and a part of the arguments needed to call it.\n   */\n  return Temple::invoke(a.first, std::tuple_cat(args, std::tie(a.second)));\n}\n\n// C++17 fold\ntemplate<typename ArgsTuple, typename CallableArgPair, typename OtherCallableArgPair, typename ... Conditionals>\nbool foldCallableArgsPairLogicalOr(\n  const ArgsTuple& args,\n  CallableArgPair&& a,\n  OtherCallableArgPair&& b,\n  Conditionals ... conditionals\n) {\n  // Fold the results of calls hopefully with short-circuiting\n  return (\n    foldCallableArgsPairLogicalOr(args, a)\n    || foldCallableArgsPairLogicalOr(args, b, conditionals...)\n  );\n}\n\ntemplate<bool isUpper, std::size_t ... Inds>\nstruct LimitTester {\n  template<typename ... Args>\n  bool operator() (Args&& ... args) {\n    return limitTest<isUpper, decrement(Inds)...>(std::forward<Args>(args)...);\n  }\n};\n\ntemplate<bool isUpper, std::size_t ... Inds>\nauto makeLimitTester(std::index_sequence<Inds ...> /* inds */) {\n  // Raise index sequence from function argument to template argument\n  return LimitTester<isUpper, Inds ...> {};\n}\n\ntemplate<typename TupleType, bool isUpper, typename ArgsTuple, std::size_t ... Inds>\nauto limitAnyOfHelper(\n  const ArgsTuple& args,\n  const std::array<double, std::tuple_size<TupleType>::value>& values,\n  std::index_sequence<Inds ...> /* inds */\n) {\n  /* Create a long list of pairs of test functors corresponding to index\n   * sequences in TupleType that we can fold with logical or\n   */\n  return foldCallableArgsPairLogicalOr(\n    args,\n    std::make_pair(\n      makeLimitTester<isUpper>(std::tuple_element_t<Inds, TupleType> {}),\n      values.at(Inds)\n    )...\n  );\n}\n\ntemplate<typename TupleType, bool isUpper, typename ArgsTuple>\nauto limitAnyOf(\n  const ArgsTuple& args,\n  const std::array<double, std::tuple_size<TupleType>::value>& values\n) {\n  // Enumerate the indices into TupleType\n  return limitAnyOfHelper<TupleType, isUpper>(\n    args,\n    values,\n    std::make_index_sequence<std::tuple_size<TupleType>::value> {}\n  );\n}\n\nTriCheckResult triCheck(\n  const Eigen::Matrix4d& lower,\n  const Eigen::Matrix4d& upper\n) {\n  TriCheckResult result;\n  /* The comments here sometimes refer to the parts of TRI_CHECK that they\n   * implement from the original algorithm.\n   *\n   * Here we first define all the index sequences we will need as types so we\n   * can freely mess with them. Note that these are one-based purely to match\n   * the definitions from the original algorithm description.\n   */\n  // Definitions of upper triangle index sets that `U` is called with\n  using UpperTriangleIndexSets = std::tuple<\n    std::index_sequence<3, 1, 4>,\n    std::index_sequence<3, 2, 4>\n  >;\n\n  // Definitions of upper tetrangle index sets that `U` is called with\n  using UpperTetrangleIndexSets = std::tuple<\n    std::index_sequence<3, 1, 2, 4>,\n    std::index_sequence<4, 1, 2, 3>\n  >;\n\n  // Definitions of lower triangle index sets that `L` is called with\n  using LowerTriangleIndexSets = std::tuple<\n    std::index_sequence<1, 3, 4>,\n    std::index_sequence<2, 3, 4>,\n    std::index_sequence<1, 4, 3>,\n    std::index_sequence<2, 4, 3>\n  >;\n\n  // Lower tetrangle index sets following the pattern l_ik - u_ij - u_kl\n  using FirstLowerTetrangleIndexSets = std::tuple<\n    std::index_sequence<1, 3, 4, 2>,\n    std::index_sequence<1, 4, 3, 2>\n  >;\n\n  // Lower tetrangle index sets following the pattern l_ik - u_ij - u_jk\n  using SecondLowerTetrangleIndexSets = std::tuple<\n    std::index_sequence<1, 2, 3, 4>,\n    std::index_sequence<2, 1, 3, 4>,\n    std::index_sequence<1, 2, 4, 3>,\n    std::index_sequence<2, 1, 4, 3>\n  >;\n\n  /* Now we actually calculate all of those values by calling `U` and `L` with\n   * them. mapIndexSets takes care of forwarding the index sequences to the\n   * right functions and grouping the results into arrays. The first boolean\n   * template argument denotes whether we are calculating an upper bound, which\n   * we are.\n   *\n   * The second is relevant only to the lower tetrangle bounds, and its value\n   * is just set false here.\n   *\n   * The three- and four-argument `L` and `U` functions are represented by\n   * the function NAngleBound.\n   */\n  const auto upperTriangleBounds = mapIndexSets<UpperTriangleIndexSets, true, false>(lower, upper);\n  const auto upperTetrangleBounds = mapIndexSets<UpperTetrangleIndexSets, true, false>(lower, upper);\n\n  /* Now for the lower bounds. Regarding the tetrangle bounds, you saw in the\n   * index sequence definition that there are two sets, each following a\n   * different pattern. If the second boolean template argument to mapIndexSets\n   * is true, that means the current set follows the first pattern.\n   */\n  const auto lowerTriangleBounds = mapIndexSets<LowerTriangleIndexSets, false, false>(lower, upper);\n  const auto firstLowerTetrangleBounds = mapIndexSets<FirstLowerTetrangleIndexSets, false, true>(lower, upper);\n  const auto secondLowerTetrangleBounds = mapIndexSets<SecondLowerTetrangleIndexSets, false, false>(lower, upper);\n\n  /* We set u3 and l3 from the minimum and maximum of the calculated bounds */\n  result.klUpperBound = std::min(\n    Temple::min(upperTriangleBounds), // min(U[i, j, k])\n    Temple::min(upperTetrangleBounds) // min(U[i, j, k, l])\n  );\n\n  result.klLowerBound = std::max({\n    0.0, // L[0] := 0\n    Temple::max(lowerTriangleBounds), // min(L[i, j, k])\n    Temple::max(firstLowerTetrangleBounds), // min(L[i, j, k, l]) of first pattern\n    Temple::max(secondLowerTetrangleBounds) // min(L[i, j, k, l]) of second pattern\n  });\n\n  /* Now we determine u_col and l_col. These are \"true whenever the triangle\n   * inequality limits on the (3, 4)-distance are attainable without violating\n   * the given bounds or the tetrangle inequality.\n   *\n   * The algorithm itself has multiple \"For each 3-atom upper limit\", \"For each\n   * 4-atom upper limit\" parts that we abstract over here. If any of those\n   * trigger, then the rest need not be evaluated, so we short-circuit with\n   * logical ors.\n   */\n\n  const auto upperArgs = std::tie(lower, upper, result.klUpperBound);\n  result.u_col = (\n    limitAnyOf<UpperTriangleIndexSets, true>(upperArgs, upperTriangleBounds)\n    || limitAnyOf<UpperTetrangleIndexSets, true>(upperArgs, upperTetrangleBounds)\n  );\n\n  const auto lowerArgs = std::tie(lower, upper, result.klLowerBound);\n  result.l_col = (\n    Temple::invoke(zeroBoundTest, lowerArgs)\n    || limitAnyOf<LowerTriangleIndexSets, false>(lowerArgs, lowerTriangleBounds)\n    || limitAnyOf<FirstLowerTetrangleIndexSets, false>(lowerArgs, firstLowerTetrangleBounds)\n    || limitAnyOf<SecondLowerTetrangleIndexSets, false>(lowerArgs, secondLowerTetrangleBounds)\n  );\n\n  return result;\n}\n\ndouble CMUpper(\n  const double d12,\n  const double d13,\n  const double d14,\n  const double d23,\n  const double d24\n) {\n  const double a = std::pow(d12, 2);\n  const double b = std::pow(d13, 2);\n  const double c = std::pow(d14, 2);\n  const double d = std::pow(d23, 2);\n  const double e = std::pow(d24, 2);\n\n  const double A = -a / 4;\n  const double B = (\n    a * (-a + b + c + d + e)\n    - b * c + b * e + c * d - d * e\n  ) / 4;\n  const double C = (\n    d * (- a * b + a * c + b * c - c * c - c * d)\n    + e * (a * b - b * b - a * c + b * c + b * d + c * d - b * e)\n  ) / 4;\n\n  const double discriminant = B * B + a * C; // A = -a / 4 -> -4 A = a\n\n  if(discriminant >= 0) {\n    return (-B - std::sqrt(discriminant)) / (2.0 * A);\n  }\n\n  return std::numeric_limits<double>::lowest();\n}\n\ndouble CMLower(\n  const double d12,\n  const double d13,\n  const double d14,\n  const double d23,\n  const double d24\n) {\n  // NOTE: Nearly identical to CMUpper\n  const double a = std::pow(d12, 2);\n  const double b = std::pow(d13, 2);\n  const double c = std::pow(d14, 2);\n  const double d = std::pow(d23, 2);\n  const double e = std::pow(d24, 2);\n\n  const double A = -a / 4;\n  const double B = (\n    a * (-a + b + c + d + e)\n    - b * c + b * e + c * d - d * e\n  ) / 4;\n  const double C = (\n    d * (- a * b + a * c + b * c - c * c - c * d)\n    + e * (a * b - b * b - a * c + b * c + b * d + c * d - b * e)\n  ) / 4;\n\n  const double discriminant = B * B + a * C; // A = -a / 4 -> -4 A = a\n\n  if(discriminant >= 0) {\n    return (-B + std::sqrt(discriminant)) / (2.0 * A);\n  }\n\n  return std::numeric_limits<double>::max();\n}\n\n/* Namespace with non-templated lower and upper functions so they can be\n * template parameters for other functions\n */\nnamespace m {\n\ntemplate<typename FnTuple, std::size_t ... Inds>\nauto makeTetrangleCallTupleHelper(\n  const Eigen::MatrixXd& bounds,\n  const std::array<unsigned, 4>& b,\n  FnTuple fnTuple,\n  std::index_sequence<Inds...> /* inds */\n) {\n  constexpr auto indexTuple = std::make_tuple(\n    std::pair<unsigned, unsigned> {0, 1},\n    std::pair<unsigned, unsigned> {0, 2},\n    std::pair<unsigned, unsigned> {0, 3},\n    std::pair<unsigned, unsigned> {1, 2},\n    std::pair<unsigned, unsigned> {1, 3}\n  );\n\n  return std::make_tuple(\n    std::get<Inds>(fnTuple)(\n      bounds,\n      b[std::get<Inds>(indexTuple).first],\n      b[std::get<Inds>(indexTuple).second]\n    )...\n  );\n}\n\ntemplate<typename ... Fns>\nauto fetchAppropriateBounds(\n  const Eigen::MatrixXd& bounds,\n  const std::array<unsigned, 4>& b,\n  Fns ... fns\n) {\n  return makeTetrangleCallTupleHelper(\n    bounds,\n    b,\n    std::forward_as_tuple(fns...),\n    std::make_index_sequence<sizeof...(fns)>()\n  );\n}\n\n\ndouble l(const Eigen::MatrixXd& bounds, const unsigned i, const unsigned j) {\n  if(i < j) {\n    return bounds(j, i);\n  }\n\n  return bounds(i, j);\n}\n\ndouble u(const Eigen::MatrixXd& bounds, const unsigned i, const unsigned j) {\n  if(i < j) {\n    return bounds(i, j);\n  }\n\n  return bounds(j, i);\n}\n\n} // namespace m\n\ndouble upperTetrangleLimit(\n  const Eigen::MatrixXd& bounds,\n  const std::array<unsigned, 4>& b\n) {\n  /* Indices are always the following sequence: 12, 13, 14, 23, 24.\n   * The only thing different among the tetrangle limits is whether we pass\n   * the lower or upper bound. To make this readable, we pass merely functions\n   * fetching the lower or upper bound from bounds and let\n   * fetchAppropriateBounds take care of subindexing the indices stored in b\n   * appropriately for each passed function.\n   *\n   * m::l is lower\n   * m::u is upper\n   *\n   * These functions had to be duplicated from the original lower and upper\n   * functions and fully qualified since we cannot pass templated functions as\n   * an overload set.\n   */\n  return std::max({\n    Temple::invoke(CMUpper, m::fetchAppropriateBounds(bounds, b, m::l, m::u, m::u, m::u, m::u)),\n    Temple::invoke(CMUpper, m::fetchAppropriateBounds(bounds, b, m::u, m::l, m::l, m::u, m::u)),\n    Temple::invoke(CMUpper, m::fetchAppropriateBounds(bounds, b, m::u, m::u, m::u, m::l, m::l))\n  });\n}\n\ndouble lowerTetrangleLimit(\n  const Eigen::MatrixXd& bounds,\n  const std::array<unsigned, 4>& b\n) {\n  // See upperTetrangleLimit to explain the matrix below\n  return std::min({\n    Temple::invoke(CMLower, m::fetchAppropriateBounds(bounds, b, m::u, m::u, m::l, m::l, m::u)),\n    Temple::invoke(CMLower, m::fetchAppropriateBounds(bounds, b, m::u, m::l, m::u, m::u, m::l)),\n    Temple::invoke(CMLower, m::fetchAppropriateBounds(bounds, b, m::l, m::l, m::u, m::l, m::u)),\n    Temple::invoke(CMLower, m::fetchAppropriateBounds(bounds, b, m::l, m::u, m::l, m::u, m::l))\n  });\n}\n\nstruct TetrangleLimits {\n  DistanceGeometry::ValueBounds klLimits;\n  bool boundViolation;\n\n  TetrangleLimits(\n    const Eigen::MatrixXd& bounds,\n    const std::array<unsigned, 4>& b\n  ) {\n    LU matrixPair {bounds, b};\n    // Can try the original triCheck here too\n    TriCheckResult check = triCheck(matrixPair.L, matrixPair.U);\n\n    /* NOTE: upperTetrangleLimit and lowerTetrangleLimit could use the LU\n     * matrices for better data locality if this ever needs optimization\n     */\n    if(check.u_col) {\n      klLimits.upper = check.klUpperBound;\n    } else {\n      const double limit = upperTetrangleLimit(bounds, b);\n      klLimits.upper = std::sqrt(limit);\n    }\n\n    if(check.l_col) {\n      klLimits.lower = check.klLowerBound;\n    } else {\n      const double limit = lowerTetrangleLimit(bounds, b);\n      klLimits.lower = std::sqrt(limit);\n    }\n\n    boundViolation = klLimits.upper < klLimits.lower;\n  }\n};\n\nunsigned tetrangleSmooth(Eigen::Ref<Eigen::MatrixXd> bounds) {\n  feenableexcept(FE_DIVBYZERO | FE_INVALID | FE_OVERFLOW);\n\n  const unsigned N = bounds.cols();\n\n  // Minimal change in the bounds required to consider something has changed\n  constexpr double epsilon = 0.01;\n\n  bool changedSomething;\n  unsigned iterations = 0;\n  do {\n    changedSomething = false;\n\n    for(unsigned i = 0; i < N - 1; ++i) {\n      for(unsigned j = i + 1; j < N; ++j) {\n        // NOTE (i,j) and (k,l) are not mutually disjoint\n        for(unsigned k = 0; k < N - 1; ++k) {\n          for(unsigned l = k + 1; l < N; ++l) {\n            // Equal index pairs are trouble\n            if(i == k && j == l) {\n              continue;\n            }\n\n            const TetrangleLimits limits {bounds, {i, j, k, l}};\n\n            if(limits.boundViolation) {\n              throw std::runtime_error(\"Bound violation found!\");\n            }\n\n            // k < l, so bounds(k, l) is the upper bound, bounds(l, k) the lower\n            double& klLowerBound = bounds(l, k);\n            double& klUpperBound = bounds(k, l);\n\n            assert(klLowerBound <= klUpperBound);\n\n            if(\n              limits.klLimits.lower > klLowerBound\n              && std::fabs(limits.klLimits.lower - klLowerBound) / klLowerBound > epsilon\n            ) {\n              if(limits.klLimits.lower > klUpperBound) {\n                throw std::runtime_error(\"Bound violation found!\");\n              }\n\n              klLowerBound = limits.klLimits.lower;\n              changedSomething = true;\n            }\n\n            if(\n              limits.klLimits.upper < klUpperBound\n              && std::fabs(klUpperBound - limits.klLimits.upper) / klUpperBound > epsilon\n            ) {\n              if(limits.klLimits.upper < klLowerBound) {\n                throw std::runtime_error(\"Bound violation found!\");\n              }\n              klUpperBound = limits.klLimits.upper;\n              changedSomething = true;\n            }\n          }\n        }\n      }\n    }\n\n    ++iterations;\n  } while(changedSomething);\n\n  fedisableexcept(FE_DIVBYZERO | FE_INVALID | FE_OVERFLOW);\n  return iterations;\n}\n\n} // namespace DistanceGeometry\n} // namespace Molassembler\n} // namespace Scine\n", "meta": {"hexsha": "83cb413daf34cb45d17cd2b012f83e2c86008925", "size": 28168, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Molassembler/DistanceGeometry/TetrangleSmoothing.cpp", "max_stars_repo_name": "Dom1L/molassembler", "max_stars_repo_head_hexsha": "dafc656b1aa846b65b1fd1e06f3740ceedcf22db", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 17.0, "max_stars_repo_stars_event_min_datetime": "2020-11-27T14:59:34.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T10:31:25.000Z", "max_issues_repo_path": "src/Molassembler/DistanceGeometry/TetrangleSmoothing.cpp", "max_issues_repo_name": "Dom1L/molassembler", "max_issues_repo_head_hexsha": "dafc656b1aa846b65b1fd1e06f3740ceedcf22db", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Molassembler/DistanceGeometry/TetrangleSmoothing.cpp", "max_forks_repo_name": "Dom1L/molassembler", "max_forks_repo_head_hexsha": "dafc656b1aa846b65b1fd1e06f3740ceedcf22db", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2020-12-09T09:21:53.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-22T15:42:21.000Z", "avg_line_length": 29.9978700745, "max_line_length": 132, "alphanum_fraction": 0.642999148, "num_tokens": 8074, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6959583376458152, "lm_q2_score": 0.4493926344647597, "lm_q1q2_score": 0.3127585508323676}}
{"text": "/* \n *            Copyright 2009-2017 The VOTCA Development Team\n *                       (http://www.votca.org)\n *\n *      Licensed under the Apache License, Version 2.0 (the \"License\")\n *\n * You may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *              http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"A_ol I_ol\" BA_olI_ol,\n * WITHOUT WARRANTIE_ol OR CONDITION_ol OF ANY KIND, either express or implied.\n * _olee the License for the specific language governing permissions and\n * limitations under the License.\n *\n */\n// Overload of uBLAS prod function with MKL/GSL implementations\n\n#include <votca/xtp/aomatrix.h>\n\n#include <votca/xtp/aobasis.h>\n\n\n#include <votca/tools/linalg.h>\n#include <votca/xtp/elements.h>\n#include <votca/tools/constants.h>\n//#include <boost/timer/timer.hpp>\n\n\nusing namespace votca::tools;\n\n\n\nnamespace votca { namespace xtp {\n    namespace ub = boost::numeric::ublas;\n    namespace CTP = votca::ctp;\n    \n\n    \n    void AODipole_Potential::FillBlock( ub::matrix_range< ub::matrix<double> >& _matrix,const AOShell* _shell_row,const AOShell* _shell_col , AOBasis* ecp) {\n\n        const double pi = boost::math::constants::pi<double>();\n\n        // Get components of dipole vector somehow\n        \n        vec dipole=-(apolarsite->getU1()+apolarsite->getQ1())*tools::conv::nm2bohr;\n       \n        double d_0 = dipole.getX();\n        double d_1 = dipole.getY();\n        double d_2 = dipole.getZ();\n\n        // cout << _gridpoint << endl;\n        // shell info, only lmax tells how far to go\n        int _lmax_row = _shell_row->getLmax();\n        int _lmax_col = _shell_col->getLmax();\n        int _lsum = _lmax_row + _lmax_col;\n        // set size of internal block for recursion\n        int _nrows = this->getBlockSize( _lmax_row ); \n        int _ncols = this->getBlockSize( _lmax_col ); \n    \n        // initialize local matrix block for unnormalized cartesians\n/////////        ub::matrix<double> nuc   = ub::zero_matrix<double>(_nrows,_ncols);\n        ub::matrix<double> dip = ub::zero_matrix<double>(_nrows,_ncols);\n        \n\n        //cout << nuc.size1() << \":\" << nuc.size2() << endl;\n        \n        /* FOR CONTRACTED FUNCTIONS, ADD LOOP OVER ALL DECAYS IN CONTRACTION\n         * MULTIPLY THE TRANSFORMATION MATRICES BY APPROPRIATE CONTRACTION \n         * COEFFICIENTS, AND ADD TO matrix(i,j)\n         */\n        \n int n_orbitals[] = { 1, 4, 10, 20, 35, 56, 84 };\n\n int nx[] = { 0,\n              1, 0, 0,\n              2, 1, 1, 0, 0, 0,\n              3, 2, 2, 1, 1, 1, 0, 0, 0, 0,\n              4, 3, 3, 2, 2, 2, 1, 1, 1, 1, 0, 0, 0, 0, 0 };\n\n int ny[] = { 0,\n              0, 1, 0,\n              0, 1, 0, 2, 1, 0,\n              0, 1, 0, 2, 1, 0, 3, 2, 1, 0,\n              0, 1, 0, 2, 1, 0, 3, 2, 1, 0, 4, 3, 2, 1, 0 };\n\n int nz[] = { 0,\n              0, 0, 1,\n              0, 0, 1, 0, 1, 2,\n              0, 0, 1, 0, 1, 2, 0, 1, 2, 3,\n              0, 0, 1, 0, 1, 2, 0, 1, 2, 3, 0, 1, 2, 3, 4 };\n\n\n int i_less_x[] = {  0,\n                     0,  0,  0,\n                     1,  2,  3,  0,  0,  0,\n                     4,  5,  6,  7,  8,  9,  0,  0,  0,  0,\n                    10, 11, 12, 13, 14, 15, 16, 17, 18, 19,  0,  0,  0,  0,  0 };\n\n int i_less_y[] = {  0,\n                     0,  0,  0,\n                     0,  1,  0,  2,  3,  0,\n                     0,  4,  0,  5,  6,  0,  7,  8,  9,  0,\n                     0, 10,  0, 11, 12,  0, 13, 14, 15,  0, 16, 17, 18, 19,  0 };\n\n int i_less_z[] = {  0,\n                     0,  0,  0,\n                     0,  0,  1,  0,  2,  3,\n                     0,  0,  4,  0,  5,  6,  0,  7,  8,  9,\n                     0,  0, 10,  0, 11, 12,  0, 13, 14, 15,  0, 16, 17, 18, 19 };\n      \n        \n        // get shell positions\n        const vec& _pos_row = _shell_row->getPos();\n        const vec& _pos_col = _shell_col->getPos();\n        const vec  _diff    = _pos_row - _pos_col;\n        // initialize some helper\n      \n        double _distsq = _diff*_diff; \n        \n        \n        // iterate over Gaussians in this _shell_row\n        for (AOShell::GaussianIterator itr = _shell_row->firstGaussian(); itr != _shell_row->lastGaussian(); ++itr) {\n            // iterate over Gaussians in this _shell_col\n            // get decay constant\n            const double _decay_row = itr->getDecay();\n            \n            for ( AOShell::GaussianIterator itc = _shell_col->firstGaussian(); itc != _shell_col->lastGaussian(); ++itc) {\n                //get decay constant\n                const double _decay_col = itc->getDecay();\n\n                const double zeta = _decay_row + _decay_col;\n                const double _fak  = 0.5/zeta;\n                const double _fak2 = 2.0 * _fak;\n                const double xi = _decay_row * _decay_col * _fak2;\n\n                double _exparg = xi *_distsq;\n                // check if distance between postions is big, then skip step   \n                if ( _exparg > 30.0 ) { continue; }\n\n        // some helpers\n        double PmA0 = _fak2*( _decay_row * _pos_row.getX() + _decay_col * _pos_col.getX() ) - _pos_row.getX();\n        double PmA1 = _fak2*( _decay_row * _pos_row.getY() + _decay_col * _pos_col.getY() ) - _pos_row.getY();\n        double PmA2 = _fak2*( _decay_row * _pos_row.getZ() + _decay_col * _pos_col.getZ() ) - _pos_row.getZ();\n\n        double PmB0 = _fak2*( _decay_row * _pos_row.getX() + _decay_col * _pos_col.getX() ) - _pos_col.getX();\n        double PmB1 = _fak2*( _decay_row * _pos_row.getY() + _decay_col * _pos_col.getY() ) - _pos_col.getY();\n        double PmB2 = _fak2*( _decay_row * _pos_row.getZ() + _decay_col * _pos_col.getZ() ) - _pos_col.getZ();\n\n        double PmC0 = _fak2*( _decay_row * _pos_row.getX() + _decay_col * _pos_col.getX() ) - _gridpoint.getX();\n        double PmC1 = _fak2*( _decay_row * _pos_row.getY() + _decay_col * _pos_col.getY() ) - _gridpoint.getY();\n        double PmC2 = _fak2*( _decay_row * _pos_row.getZ() + _decay_col * _pos_col.getZ() ) - _gridpoint.getZ();\n\n        const double _U = zeta*(PmC0*PmC0+PmC1*PmC1+PmC2*PmC2);\n\n        const std::vector<double> _FmU=XIntegrate(_lsum+2, _U );\n\n        typedef boost::multi_array<double, 3> ma_type;\n        typedef boost::multi_array<double, 4> ma4_type; //////////////////\n        ma_type nuc3(boost::extents[_nrows][_ncols][_lsum+1]);\n        ma4_type dip4(boost::extents[_nrows][_ncols][3][_lsum+1]);\n        typedef ma_type::index index;\n\n        for (index i = 0; i < _nrows; ++i) {\n          for (index j = 0; j < _ncols; ++j) {\n            for (index m = 0; m < _lsum+1; ++m) {\n              nuc3[i][j][m] = 0.;\n            }\n          }\n        }\n\n        for (index i = 0; i < _nrows; ++i) {\n          for (index j = 0; j < _ncols; ++j) {\n            for (index k = 0; k < 3 ; ++k) { ///////////////////////////////// error corrected\n              for (index m = 0; m < _lsum+1; ++m) {\n                dip4[i][j][k][m] = 0.;\n              }\n            }\n          }\n        }\n\n\n\n\n\n// (s-s element normiert )\ndouble _prefactor = 4. * sqrt(2./pi) * pow(_decay_row*_decay_col,.75) * _fak2 * exp(-_exparg);\nfor (int m = 0; m < _lsum+1; m++) {\n  nuc3[0][0][m] = _prefactor*_FmU[m];\n}\n//------------------------------------------------------\n\n//Integrals     p - s\nif (_lmax_row > 0) {\n  for (int m = 0; m < _lsum; m++) {\n    nuc3[Cart::x][0][m] = PmA0*nuc3[0][0][m] - PmC0*nuc3[0][0][m+1];\n    nuc3[Cart::y][0][m] = PmA1*nuc3[0][0][m] - PmC1*nuc3[0][0][m+1];\n    nuc3[Cart::z][0][m] = PmA2*nuc3[0][0][m] - PmC2*nuc3[0][0][m+1];\n  }\n}\n//------------------------------------------------------\n\n//Integrals     d - s\nif (_lmax_row > 1) {\n  for (int m = 0; m < _lsum-1; m++) {\n    double term = _fak*(nuc3[0][0][m]-nuc3[0][0][m+1]);\n    nuc3[Cart::xx][0][m] = PmA0*nuc3[Cart::x][0][m] - PmC0*nuc3[Cart::x][0][m+1] + term;\n    nuc3[Cart::xy][0][m] = PmA0*nuc3[Cart::y][0][m] - PmC0*nuc3[Cart::y][0][m+1];\n    nuc3[Cart::xz][0][m] = PmA0*nuc3[Cart::z][0][m] - PmC0*nuc3[Cart::z][0][m+1];\n    nuc3[Cart::yy][0][m] = PmA1*nuc3[Cart::y][0][m] - PmC1*nuc3[Cart::y][0][m+1] + term;\n    nuc3[Cart::yz][0][m] = PmA1*nuc3[Cart::z][0][m] - PmC1*nuc3[Cart::z][0][m+1];\n    nuc3[Cart::zz][0][m] = PmA2*nuc3[Cart::z][0][m] - PmC2*nuc3[Cart::z][0][m+1] + term;\n  }\n}\n//------------------------------------------------------\n\n//Integrals     f - s\nif (_lmax_row > 2) {\n  for (int m = 0; m < _lsum-2; m++) {\n    nuc3[Cart::xxx][0][m] = PmA0*nuc3[Cart::xx][0][m] - PmC0*nuc3[Cart::xx][0][m+1] + 2*_fak*(nuc3[Cart::x][0][m]-nuc3[Cart::x][0][m+1]);\n    nuc3[Cart::xxy][0][m] = PmA1*nuc3[Cart::xx][0][m] - PmC1*nuc3[Cart::xx][0][m+1];\n    nuc3[Cart::xxz][0][m] = PmA2*nuc3[Cart::xx][0][m] - PmC2*nuc3[Cart::xx][0][m+1];\n    nuc3[Cart::xyy][0][m] = PmA0*nuc3[Cart::yy][0][m] - PmC0*nuc3[Cart::yy][0][m+1];\n    nuc3[Cart::xyz][0][m] = PmA0*nuc3[Cart::yz][0][m] - PmC0*nuc3[Cart::yz][0][m+1];\n    nuc3[Cart::xzz][0][m] = PmA0*nuc3[Cart::zz][0][m] - PmC0*nuc3[Cart::zz][0][m+1];\n    nuc3[Cart::yyy][0][m] = PmA1*nuc3[Cart::yy][0][m] - PmC1*nuc3[Cart::yy][0][m+1] + 2*_fak*(nuc3[Cart::y][0][m]-nuc3[Cart::y][0][m+1]);\n    nuc3[Cart::yyz][0][m] = PmA2*nuc3[Cart::yy][0][m] - PmC2*nuc3[Cart::yy][0][m+1];\n    nuc3[Cart::yzz][0][m] = PmA1*nuc3[Cart::zz][0][m] - PmC1*nuc3[Cart::zz][0][m+1];\n    nuc3[Cart::zzz][0][m] = PmA2*nuc3[Cart::zz][0][m] - PmC2*nuc3[Cart::zz][0][m+1] + 2*_fak*(nuc3[Cart::z][0][m]-nuc3[Cart::z][0][m+1]);\n  }\n}\n//------------------------------------------------------\n\n//Integrals     g - s\nif (_lmax_row > 3) {\n  for (int m = 0; m < _lsum-3; m++) {\n    double term_xx = _fak*(nuc3[Cart::xx][0][m]-nuc3[Cart::xx][0][m+1]);\n    double term_yy = _fak*(nuc3[Cart::yy][0][m]-nuc3[Cart::yy][0][m+1]);\n    double term_zz = _fak*(nuc3[Cart::zz][0][m]-nuc3[Cart::zz][0][m+1]);\n    nuc3[Cart::xxxx][0][m] = PmA0*nuc3[Cart::xxx][0][m] - PmC0*nuc3[Cart::xxx][0][m+1] + 3*term_xx;\n    nuc3[Cart::xxxy][0][m] = PmA1*nuc3[Cart::xxx][0][m] - PmC1*nuc3[Cart::xxx][0][m+1];\n    nuc3[Cart::xxxz][0][m] = PmA2*nuc3[Cart::xxx][0][m] - PmC2*nuc3[Cart::xxx][0][m+1];\n    nuc3[Cart::xxyy][0][m] = PmA0*nuc3[Cart::xyy][0][m] - PmC0*nuc3[Cart::xyy][0][m+1] + term_yy;\n    nuc3[Cart::xxyz][0][m] = PmA1*nuc3[Cart::xxz][0][m] - PmC1*nuc3[Cart::xxz][0][m+1];\n    nuc3[Cart::xxzz][0][m] = PmA0*nuc3[Cart::xzz][0][m] - PmC0*nuc3[Cart::xzz][0][m+1] + term_zz;\n    nuc3[Cart::xyyy][0][m] = PmA0*nuc3[Cart::yyy][0][m] - PmC0*nuc3[Cart::yyy][0][m+1];\n    nuc3[Cart::xyyz][0][m] = PmA0*nuc3[Cart::yyz][0][m] - PmC0*nuc3[Cart::yyz][0][m+1];\n    nuc3[Cart::xyzz][0][m] = PmA0*nuc3[Cart::yzz][0][m] - PmC0*nuc3[Cart::yzz][0][m+1];\n    nuc3[Cart::xzzz][0][m] = PmA0*nuc3[Cart::zzz][0][m] - PmC0*nuc3[Cart::zzz][0][m+1];\n    nuc3[Cart::yyyy][0][m] = PmA1*nuc3[Cart::yyy][0][m] - PmC1*nuc3[Cart::yyy][0][m+1] + 3*term_yy;\n    nuc3[Cart::yyyz][0][m] = PmA2*nuc3[Cart::yyy][0][m] - PmC2*nuc3[Cart::yyy][0][m+1];\n    nuc3[Cart::yyzz][0][m] = PmA1*nuc3[Cart::yzz][0][m] - PmC1*nuc3[Cart::yzz][0][m+1] + term_zz;\n    nuc3[Cart::yzzz][0][m] = PmA1*nuc3[Cart::zzz][0][m] - PmC1*nuc3[Cart::zzz][0][m+1];\n    nuc3[Cart::zzzz][0][m] = PmA2*nuc3[Cart::zzz][0][m] - PmC2*nuc3[Cart::zzz][0][m+1] + 3*term_zz;\n  }\n}\n//------------------------------------------------------\n\n\n\nif (_lmax_col > 0) {\n\n  //Integrals     s - p\n  for (int m = 0; m < _lmax_col; m++) {\n    nuc3[0][Cart::x][m] = PmB0*nuc3[0][0][m] - PmC0*nuc3[0][0][m+1];\n    nuc3[0][Cart::y][m] = PmB1*nuc3[0][0][m] - PmC1*nuc3[0][0][m+1];\n    nuc3[0][Cart::z][m] = PmB2*nuc3[0][0][m] - PmC2*nuc3[0][0][m+1];\n  }\n  //------------------------------------------------------\n\n  //Integrals     p - p\n  if (_lmax_row > 0) {\n    for (int m = 0; m < _lmax_col; m++) {\n      double term = _fak*(nuc3[0][0][m]-nuc3[0][0][m+1]);\n      for (int _i =  1; _i < 4; _i++) {\n        nuc3[_i][Cart::x][m] = PmB0*nuc3[_i][0][m] - PmC0*nuc3[_i][0][m+1] + nx[_i]*term;\n        nuc3[_i][Cart::y][m] = PmB1*nuc3[_i][0][m] - PmC1*nuc3[_i][0][m+1] + ny[_i]*term;\n        nuc3[_i][Cart::z][m] = PmB2*nuc3[_i][0][m] - PmC2*nuc3[_i][0][m+1] + nz[_i]*term;\n      }\n    }\n  }\n  //------------------------------------------------------\n\n  //Integrals     d - p     f - p     g - p\n  for (int m = 0; m < _lmax_col; m++) {\n    for (int _i = 4; _i < n_orbitals[_lmax_row]; _i++) {\n      int nx_i = nx[_i];\n      int ny_i = ny[_i];\n      int nz_i = nz[_i];\n      int ilx_i = i_less_x[_i];\n      int ily_i = i_less_y[_i];\n      int ilz_i = i_less_z[_i];\n      nuc3[_i][Cart::x][m] = PmB0*nuc3[_i][0][m] - PmC0*nuc3[_i][0][m+1] + nx_i*_fak*(nuc3[ilx_i][0][m] - nuc3[ilx_i][0][m+1]);\n      nuc3[_i][Cart::y][m] = PmB1*nuc3[_i][0][m] - PmC1*nuc3[_i][0][m+1] + ny_i*_fak*(nuc3[ily_i][0][m] - nuc3[ily_i][0][m+1]);\n      nuc3[_i][Cart::z][m] = PmB2*nuc3[_i][0][m] - PmC2*nuc3[_i][0][m+1] + nz_i*_fak*(nuc3[ilz_i][0][m] - nuc3[ilz_i][0][m+1]);\n    }\n  }\n  //------------------------------------------------------\n\n} // end if (_lmax_col > 0)\n\n\nif (_lmax_col > 1) {\n\n  //Integrals     s - d\n  for (int m = 0; m < _lmax_col-1; m++) {\n    double term = _fak*(nuc3[0][0][m]-nuc3[0][0][m+1]);\n    nuc3[0][Cart::xx][m] = PmB0*nuc3[0][Cart::x][m] - PmC0*nuc3[0][Cart::x][m+1] + term;\n    nuc3[0][Cart::xy][m] = PmB0*nuc3[0][Cart::y][m] - PmC0*nuc3[0][Cart::y][m+1];\n    nuc3[0][Cart::xz][m] = PmB0*nuc3[0][Cart::z][m] - PmC0*nuc3[0][Cart::z][m+1];\n    nuc3[0][Cart::yy][m] = PmB1*nuc3[0][Cart::y][m] - PmC1*nuc3[0][Cart::y][m+1] + term;\n    nuc3[0][Cart::yz][m] = PmB1*nuc3[0][Cart::z][m] - PmC1*nuc3[0][Cart::z][m+1];\n    nuc3[0][Cart::zz][m] = PmB2*nuc3[0][Cart::z][m] - PmC2*nuc3[0][Cart::z][m+1] + term;\n  }\n  //------------------------------------------------------\n\n  //Integrals     p - d     d - d     f - d     g - d\n  for (int m = 0; m < _lmax_col-1; m++) {\n    for (int _i = 1; _i < n_orbitals[_lmax_row]; _i++) {\n      int nx_i = nx[_i];\n      int ny_i = ny[_i];\n      int nz_i = nz[_i];\n      int ilx_i = i_less_x[_i];\n      int ily_i = i_less_y[_i];\n      int ilz_i = i_less_z[_i];\n      double term = _fak*(nuc3[_i][0][m]-nuc3[_i][0][m+1]);\n      nuc3[_i][Cart::xx][m] = PmB0*nuc3[_i][Cart::x][m] - PmC0*nuc3[_i][Cart::x][m+1] + nx_i*_fak*(nuc3[ilx_i][Cart::x][m] - nuc3[ilx_i][Cart::x][m+1]) + term;\n      nuc3[_i][Cart::xy][m] = PmB0*nuc3[_i][Cart::y][m] - PmC0*nuc3[_i][Cart::y][m+1] + nx_i*_fak*(nuc3[ilx_i][Cart::y][m] - nuc3[ilx_i][Cart::y][m+1]);\n      nuc3[_i][Cart::xz][m] = PmB0*nuc3[_i][Cart::z][m] - PmC0*nuc3[_i][Cart::z][m+1] + nx_i*_fak*(nuc3[ilx_i][Cart::z][m] - nuc3[ilx_i][Cart::z][m+1]);\n      nuc3[_i][Cart::yy][m] = PmB1*nuc3[_i][Cart::y][m] - PmC1*nuc3[_i][Cart::y][m+1] + ny_i*_fak*(nuc3[ily_i][Cart::y][m] - nuc3[ily_i][Cart::y][m+1]) + term;\n      nuc3[_i][Cart::yz][m] = PmB1*nuc3[_i][Cart::z][m] - PmC1*nuc3[_i][Cart::z][m+1] + ny_i*_fak*(nuc3[ily_i][Cart::z][m] - nuc3[ily_i][Cart::z][m+1]);\n      nuc3[_i][Cart::zz][m] = PmB2*nuc3[_i][Cart::z][m] - PmC2*nuc3[_i][Cart::z][m+1] + nz_i*_fak*(nuc3[ilz_i][Cart::z][m] - nuc3[ilz_i][Cart::z][m+1]) + term;\n    }\n  }\n  //------------------------------------------------------\n\n} // end if (_lmax_col > 1)\n\n\nif (_lmax_col > 2) {\n\n  //Integrals     s - f\n  for (int m = 0; m < _lmax_col-2; m++) {\n    nuc3[0][Cart::xxx][m] = PmB0*nuc3[0][Cart::xx][m] - PmC0*nuc3[0][Cart::xx][m+1] + 2*_fak*(nuc3[0][Cart::x][m]-nuc3[0][Cart::x][m+1]);\n    nuc3[0][Cart::xxy][m] = PmB1*nuc3[0][Cart::xx][m] - PmC1*nuc3[0][Cart::xx][m+1];\n    nuc3[0][Cart::xxz][m] = PmB2*nuc3[0][Cart::xx][m] - PmC2*nuc3[0][Cart::xx][m+1];\n    nuc3[0][Cart::xyy][m] = PmB0*nuc3[0][Cart::yy][m] - PmC0*nuc3[0][Cart::yy][m+1];\n    nuc3[0][Cart::xyz][m] = PmB0*nuc3[0][Cart::yz][m] - PmC0*nuc3[0][Cart::yz][m+1];\n    nuc3[0][Cart::xzz][m] = PmB0*nuc3[0][Cart::zz][m] - PmC0*nuc3[0][Cart::zz][m+1];\n    nuc3[0][Cart::yyy][m] = PmB1*nuc3[0][Cart::yy][m] - PmC1*nuc3[0][Cart::yy][m+1] + 2*_fak*(nuc3[0][Cart::y][m]-nuc3[0][Cart::y][m+1]);\n    nuc3[0][Cart::yyz][m] = PmB2*nuc3[0][Cart::yy][m] - PmC2*nuc3[0][Cart::yy][m+1];\n    nuc3[0][Cart::yzz][m] = PmB1*nuc3[0][Cart::zz][m] - PmC1*nuc3[0][Cart::zz][m+1];\n    nuc3[0][Cart::zzz][m] = PmB2*nuc3[0][Cart::zz][m] - PmC2*nuc3[0][Cart::zz][m+1] + 2*_fak*(nuc3[0][Cart::z][m]-nuc3[0][Cart::z][m+1]);\n  }\n  //------------------------------------------------------\n\n  //Integrals     p - f     d - f     f - f     g - f\n  for (int m = 0; m < _lmax_col-2; m++) {\n    for (int _i = 1; _i < n_orbitals[_lmax_row]; _i++) {\n      int nx_i = nx[_i];\n      int ny_i = ny[_i];\n      int nz_i = nz[_i];\n      int ilx_i = i_less_x[_i];\n      int ily_i = i_less_y[_i];\n      int ilz_i = i_less_z[_i];\n      double term_x = 2*_fak*(nuc3[_i][Cart::x][m]-nuc3[_i][Cart::x][m+1]);\n      double term_y = 2*_fak*(nuc3[_i][Cart::y][m]-nuc3[_i][Cart::y][m+1]);\n      double term_z = 2*_fak*(nuc3[_i][Cart::z][m]-nuc3[_i][Cart::z][m+1]);\n      nuc3[_i][Cart::xxx][m] = PmB0*nuc3[_i][Cart::xx][m] - PmC0*nuc3[_i][Cart::xx][m+1] + nx_i*_fak*(nuc3[ilx_i][Cart::xx][m] - nuc3[ilx_i][Cart::xx][m+1]) + term_x;\n      nuc3[_i][Cart::xxy][m] = PmB1*nuc3[_i][Cart::xx][m] - PmC1*nuc3[_i][Cart::xx][m+1] + ny_i*_fak*(nuc3[ily_i][Cart::xx][m] - nuc3[ily_i][Cart::xx][m+1]);\n      nuc3[_i][Cart::xxz][m] = PmB2*nuc3[_i][Cart::xx][m] - PmC2*nuc3[_i][Cart::xx][m+1] + nz_i*_fak*(nuc3[ilz_i][Cart::xx][m] - nuc3[ilz_i][Cart::xx][m+1]);\n      nuc3[_i][Cart::xyy][m] = PmB0*nuc3[_i][Cart::yy][m] - PmC0*nuc3[_i][Cart::yy][m+1] + nx_i*_fak*(nuc3[ilx_i][Cart::yy][m] - nuc3[ilx_i][Cart::yy][m+1]);\n      nuc3[_i][Cart::xyz][m] = PmB0*nuc3[_i][Cart::yz][m] - PmC0*nuc3[_i][Cart::yz][m+1] + nx_i*_fak*(nuc3[ilx_i][Cart::yz][m] - nuc3[ilx_i][Cart::yz][m+1]);\n      nuc3[_i][Cart::xzz][m] = PmB0*nuc3[_i][Cart::zz][m] - PmC0*nuc3[_i][Cart::zz][m+1] + nx_i*_fak*(nuc3[ilx_i][Cart::zz][m] - nuc3[ilx_i][Cart::zz][m+1]);\n      nuc3[_i][Cart::yyy][m] = PmB1*nuc3[_i][Cart::yy][m] - PmC1*nuc3[_i][Cart::yy][m+1] + ny_i*_fak*(nuc3[ily_i][Cart::yy][m] - nuc3[ily_i][Cart::yy][m+1]) + term_y;\n      nuc3[_i][Cart::yyz][m] = PmB2*nuc3[_i][Cart::yy][m] - PmC2*nuc3[_i][Cart::yy][m+1] + nz_i*_fak*(nuc3[ilz_i][Cart::yy][m] - nuc3[ilz_i][Cart::yy][m+1]);\n      nuc3[_i][Cart::yzz][m] = PmB1*nuc3[_i][Cart::zz][m] - PmC1*nuc3[_i][Cart::zz][m+1] + ny_i*_fak*(nuc3[ily_i][Cart::zz][m] - nuc3[ily_i][Cart::zz][m+1]);\n      nuc3[_i][Cart::zzz][m] = PmB2*nuc3[_i][Cart::zz][m] - PmC2*nuc3[_i][Cart::zz][m+1] + nz_i*_fak*(nuc3[ilz_i][Cart::zz][m] - nuc3[ilz_i][Cart::zz][m+1]) + term_z;\n    }\n  }\n  //------------------------------------------------------\n\n} // end if (_lmax_col > 2)\n\n\nif (_lmax_col > 3) {\n\n  //Integrals     s - g\n  for (int m = 0; m < _lmax_col-3; m++) {\n    double term_xx = _fak*(nuc3[0][Cart::xx][m]-nuc3[0][Cart::xx][m+1]);\n    double term_yy = _fak*(nuc3[0][Cart::yy][m]-nuc3[0][Cart::yy][m+1]);\n    double term_zz = _fak*(nuc3[0][Cart::zz][m]-nuc3[0][Cart::zz][m+1]);\n    nuc3[0][Cart::xxxx][m] = PmB0*nuc3[0][Cart::xxx][m] - PmC0*nuc3[0][Cart::xxx][m+1] + 3*term_xx;\n    nuc3[0][Cart::xxxy][m] = PmB1*nuc3[0][Cart::xxx][m] - PmC1*nuc3[0][Cart::xxx][m+1];\n    nuc3[0][Cart::xxxz][m] = PmB2*nuc3[0][Cart::xxx][m] - PmC2*nuc3[0][Cart::xxx][m+1];\n    nuc3[0][Cart::xxyy][m] = PmB0*nuc3[0][Cart::xyy][m] - PmC0*nuc3[0][Cart::xyy][m+1] + term_yy;\n    nuc3[0][Cart::xxyz][m] = PmB1*nuc3[0][Cart::xxz][m] - PmC1*nuc3[0][Cart::xxz][m+1];\n    nuc3[0][Cart::xxzz][m] = PmB0*nuc3[0][Cart::xzz][m] - PmC0*nuc3[0][Cart::xzz][m+1] + term_zz;\n    nuc3[0][Cart::xyyy][m] = PmB0*nuc3[0][Cart::yyy][m] - PmC0*nuc3[0][Cart::yyy][m+1];\n    nuc3[0][Cart::xyyz][m] = PmB0*nuc3[0][Cart::yyz][m] - PmC0*nuc3[0][Cart::yyz][m+1];\n    nuc3[0][Cart::xyzz][m] = PmB0*nuc3[0][Cart::yzz][m] - PmC0*nuc3[0][Cart::yzz][m+1];\n    nuc3[0][Cart::xzzz][m] = PmB0*nuc3[0][Cart::zzz][m] - PmC0*nuc3[0][Cart::zzz][m+1];\n    nuc3[0][Cart::yyyy][m] = PmB1*nuc3[0][Cart::yyy][m] - PmC1*nuc3[0][Cart::yyy][m+1] + 3*term_yy;\n    nuc3[0][Cart::yyyz][m] = PmB2*nuc3[0][Cart::yyy][m] - PmC2*nuc3[0][Cart::yyy][m+1];\n    nuc3[0][Cart::yyzz][m] = PmB1*nuc3[0][Cart::yzz][m] - PmC1*nuc3[0][Cart::yzz][m+1] + term_zz;\n    nuc3[0][Cart::yzzz][m] = PmB1*nuc3[0][Cart::zzz][m] - PmC1*nuc3[0][Cart::zzz][m+1];\n    nuc3[0][Cart::zzzz][m] = PmB2*nuc3[0][Cart::zzz][m] - PmC2*nuc3[0][Cart::zzz][m+1] + 3*term_zz;\n  }\n  //------------------------------------------------------\n\n  //Integrals     p - g     d - g     f - g     g - g\n  for (int m = 0; m < _lmax_col-3; m++) {\n    for (int _i = 1; _i < n_orbitals[_lmax_row]; _i++) {\n      int nx_i = nx[_i];\n      int ny_i = ny[_i];\n      int nz_i = nz[_i];\n      int ilx_i = i_less_x[_i];\n      int ily_i = i_less_y[_i];\n      int ilz_i = i_less_z[_i];\n      double term_xx = _fak*(nuc3[_i][Cart::xx][m]-nuc3[_i][Cart::xx][m+1]);\n      double term_yy = _fak*(nuc3[_i][Cart::yy][m]-nuc3[_i][Cart::yy][m+1]);\n      double term_zz = _fak*(nuc3[_i][Cart::zz][m]-nuc3[_i][Cart::zz][m+1]);\n      nuc3[_i][Cart::xxxx][m] = PmB0*nuc3[_i][Cart::xxx][m] - PmC0*nuc3[_i][Cart::xxx][m+1] + nx_i*_fak*(nuc3[ilx_i][Cart::xxx][m] - nuc3[ilx_i][Cart::xxx][m+1]) + 3*term_xx;\n      nuc3[_i][Cart::xxxy][m] = PmB1*nuc3[_i][Cart::xxx][m] - PmC1*nuc3[_i][Cart::xxx][m+1] + ny_i*_fak*(nuc3[ily_i][Cart::xxx][m] - nuc3[ily_i][Cart::xxx][m+1]);\n      nuc3[_i][Cart::xxxz][m] = PmB2*nuc3[_i][Cart::xxx][m] - PmC2*nuc3[_i][Cart::xxx][m+1] + nz_i*_fak*(nuc3[ilz_i][Cart::xxx][m] - nuc3[ilz_i][Cart::xxx][m+1]);\n      nuc3[_i][Cart::xxyy][m] = PmB0*nuc3[_i][Cart::xyy][m] - PmC0*nuc3[_i][Cart::xyy][m+1] + nx_i*_fak*(nuc3[ilx_i][Cart::xyy][m] - nuc3[ilx_i][Cart::xyy][m+1]) + term_yy;\n      nuc3[_i][Cart::xxyz][m] = PmB1*nuc3[_i][Cart::xxz][m] - PmC1*nuc3[_i][Cart::xxz][m+1] + ny_i*_fak*(nuc3[ily_i][Cart::xxz][m] - nuc3[ily_i][Cart::xxz][m+1]);\n      nuc3[_i][Cart::xxzz][m] = PmB0*nuc3[_i][Cart::xzz][m] - PmC0*nuc3[_i][Cart::xzz][m+1] + nx_i*_fak*(nuc3[ilx_i][Cart::xzz][m] - nuc3[ilx_i][Cart::xzz][m+1]) + term_zz;\n      nuc3[_i][Cart::xyyy][m] = PmB0*nuc3[_i][Cart::yyy][m] - PmC0*nuc3[_i][Cart::yyy][m+1] + nx_i*_fak*(nuc3[ilx_i][Cart::yyy][m] - nuc3[ilx_i][Cart::yyy][m+1]);\n      nuc3[_i][Cart::xyyz][m] = PmB0*nuc3[_i][Cart::yyz][m] - PmC0*nuc3[_i][Cart::yyz][m+1] + nx_i*_fak*(nuc3[ilx_i][Cart::yyz][m] - nuc3[ilx_i][Cart::yyz][m+1]);\n      nuc3[_i][Cart::xyzz][m] = PmB0*nuc3[_i][Cart::yzz][m] - PmC0*nuc3[_i][Cart::yzz][m+1] + nx_i*_fak*(nuc3[ilx_i][Cart::yzz][m] - nuc3[ilx_i][Cart::yzz][m+1]);\n      nuc3[_i][Cart::xzzz][m] = PmB0*nuc3[_i][Cart::zzz][m] - PmC0*nuc3[_i][Cart::zzz][m+1] + nx_i*_fak*(nuc3[ilx_i][Cart::zzz][m] - nuc3[ilx_i][Cart::zzz][m+1]);\n      nuc3[_i][Cart::yyyy][m] = PmB1*nuc3[_i][Cart::yyy][m] - PmC1*nuc3[_i][Cart::yyy][m+1] + ny_i*_fak*(nuc3[ily_i][Cart::yyy][m] - nuc3[ily_i][Cart::yyy][m+1]) + 3*term_yy;\n      nuc3[_i][Cart::yyyz][m] = PmB2*nuc3[_i][Cart::yyy][m] - PmC2*nuc3[_i][Cart::yyy][m+1] + nz_i*_fak*(nuc3[ilz_i][Cart::yyy][m] - nuc3[ilz_i][Cart::yyy][m+1]);\n      nuc3[_i][Cart::yyzz][m] = PmB1*nuc3[_i][Cart::yzz][m] - PmC1*nuc3[_i][Cart::yzz][m+1] + ny_i*_fak*(nuc3[ily_i][Cart::yzz][m] - nuc3[ily_i][Cart::yzz][m+1]) + term_zz;\n      nuc3[_i][Cart::yzzz][m] = PmB1*nuc3[_i][Cart::zzz][m] - PmC1*nuc3[_i][Cart::zzz][m+1] + ny_i*_fak*(nuc3[ily_i][Cart::zzz][m] - nuc3[ily_i][Cart::zzz][m+1]);\n      nuc3[_i][Cart::zzzz][m] = PmB2*nuc3[_i][Cart::zzz][m] - PmC2*nuc3[_i][Cart::zzz][m+1] + nz_i*_fak*(nuc3[ilz_i][Cart::zzz][m] - nuc3[ilz_i][Cart::zzz][m+1]) + 3*term_zz;\n    }\n  }\n  //------------------------------------------------------\n\n} // end if (_lmax_col > 3)\n\n\n\n\n\n// (s-s element normiert )\ndouble _prefactor_dip = 2. * zeta * _prefactor;\nfor (int m = 0; m < _lsum+1; m++) {\n  dip4[0][0][0][m] = PmC0*_prefactor_dip*_FmU[m+1];\n  dip4[0][0][1][m] = PmC1*_prefactor_dip*_FmU[m+1];\n  dip4[0][0][2][m] = PmC2*_prefactor_dip*_FmU[m+1];\n}\n//------------------------------------------------------\n\n//Integrals     p - s\nif (_lmax_row > 0) {\n  for (int m = 0; m < _lsum; m++) {\n    for (int _k = 0; _k < 3; _k++) {\n      dip4[Cart::x][0][_k][m] = PmA0*dip4[0][0][_k][m] - PmC0*dip4[0][0][_k][m+1] + (_k==0)*nuc3[0][0][m+1];\n      dip4[Cart::y][0][_k][m] = PmA1*dip4[0][0][_k][m] - PmC1*dip4[0][0][_k][m+1] + (_k==1)*nuc3[0][0][m+1];\n      dip4[Cart::z][0][_k][m] = PmA2*dip4[0][0][_k][m] - PmC2*dip4[0][0][_k][m+1] + (_k==2)*nuc3[0][0][m+1];\n    }\n  }\n}\n//------------------------------------------------------\n\n//Integrals     d - s\nif (_lmax_row > 1) {\n  for (int m = 0; m < _lsum-1; m++) {\n    for (int _k = 0; _k < 3; _k++) {\n    double term = _fak*(dip4[0][0][_k][m]-dip4[0][0][_k][m+1]);\n      dip4[Cart::xx][0][_k][m] = PmA0*dip4[Cart::x][0][_k][m] - PmC0*dip4[Cart::x][0][_k][m+1] + (_k==0)*nuc3[Cart::x][0][m+1] + term;\n      dip4[Cart::xy][0][_k][m] = PmA0*dip4[Cart::y][0][_k][m] - PmC0*dip4[Cart::y][0][_k][m+1] + (_k==0)*nuc3[Cart::y][0][m+1];\n      dip4[Cart::xz][0][_k][m] = PmA0*dip4[Cart::z][0][_k][m] - PmC0*dip4[Cart::z][0][_k][m+1] + (_k==0)*nuc3[Cart::z][0][m+1];\n      dip4[Cart::yy][0][_k][m] = PmA1*dip4[Cart::y][0][_k][m] - PmC1*dip4[Cart::y][0][_k][m+1] + (_k==1)*nuc3[Cart::y][0][m+1] + term;\n      dip4[Cart::yz][0][_k][m] = PmA1*dip4[Cart::z][0][_k][m] - PmC1*dip4[Cart::z][0][_k][m+1] + (_k==1)*nuc3[Cart::z][0][m+1];\n      dip4[Cart::zz][0][_k][m] = PmA2*dip4[Cart::z][0][_k][m] - PmC2*dip4[Cart::z][0][_k][m+1] + (_k==2)*nuc3[Cart::z][0][m+1] + term;\n    }\n  }\n}\n//------------------------------------------------------\n\n//Integrals     f - s\nif (_lmax_row > 2) {\n  for (int m = 0; m < _lsum-2; m++) {\n    for (int _k = 0; _k < 3; _k++) {\n      dip4[Cart::xxx][0][_k][m] = PmA0*dip4[Cart::xx][0][_k][m] - PmC0*dip4[Cart::xx][0][_k][m+1] + (_k==0)*nuc3[Cart::xx][0][m+1] + 2*_fak*(dip4[Cart::x][0][_k][m]-dip4[Cart::x][0][_k][m+1]);\n      dip4[Cart::xxy][0][_k][m] = PmA1*dip4[Cart::xx][0][_k][m] - PmC1*dip4[Cart::xx][0][_k][m+1] + (_k==1)*nuc3[Cart::xx][0][m+1];\n      dip4[Cart::xxz][0][_k][m] = PmA2*dip4[Cart::xx][0][_k][m] - PmC2*dip4[Cart::xx][0][_k][m+1] + (_k==2)*nuc3[Cart::xx][0][m+1];\n      dip4[Cart::xyy][0][_k][m] = PmA0*dip4[Cart::yy][0][_k][m] - PmC0*dip4[Cart::yy][0][_k][m+1] + (_k==0)*nuc3[Cart::yy][0][m+1];\n      dip4[Cart::xyz][0][_k][m] = PmA0*dip4[Cart::yz][0][_k][m] - PmC0*dip4[Cart::yz][0][_k][m+1] + (_k==0)*nuc3[Cart::yz][0][m+1];\n      dip4[Cart::xzz][0][_k][m] = PmA0*dip4[Cart::zz][0][_k][m] - PmC0*dip4[Cart::zz][0][_k][m+1] + (_k==0)*nuc3[Cart::zz][0][m+1];\n      dip4[Cart::yyy][0][_k][m] = PmA1*dip4[Cart::yy][0][_k][m] - PmC1*dip4[Cart::yy][0][_k][m+1] + (_k==1)*nuc3[Cart::yy][0][m+1] + 2*_fak*(dip4[Cart::y][0][_k][m]-dip4[Cart::y][0][_k][m+1]);\n      dip4[Cart::yyz][0][_k][m] = PmA2*dip4[Cart::yy][0][_k][m] - PmC2*dip4[Cart::yy][0][_k][m+1] + (_k==2)*nuc3[Cart::yy][0][m+1];\n      dip4[Cart::yzz][0][_k][m] = PmA1*dip4[Cart::zz][0][_k][m] - PmC1*dip4[Cart::zz][0][_k][m+1] + (_k==1)*nuc3[Cart::zz][0][m+1];\n      dip4[Cart::zzz][0][_k][m] = PmA2*dip4[Cart::zz][0][_k][m] - PmC2*dip4[Cart::zz][0][_k][m+1] + (_k==2)*nuc3[Cart::zz][0][m+1] + 2*_fak*(dip4[Cart::z][0][_k][m]-dip4[Cart::z][0][_k][m+1]);\n    }\n  }\n}\n//------------------------------------------------------\n\n//Integrals     g - s\nif (_lmax_row > 3) {\n  for (int m = 0; m < _lsum-3; m++) {\n    for (int _k = 0; _k < 3; _k++) {\n    double term_xx = _fak*(dip4[Cart::xx][0][_k][m]-dip4[Cart::xx][0][_k][m+1]);\n    double term_yy = _fak*(dip4[Cart::yy][0][_k][m]-dip4[Cart::yy][0][_k][m+1]);\n    double term_zz = _fak*(dip4[Cart::zz][0][_k][m]-dip4[Cart::zz][0][_k][m+1]);\n    dip4[Cart::xxxx][0][_k][m] = PmA0*dip4[Cart::xxx][0][_k][m] - PmC0*dip4[Cart::xxx][0][_k][m+1] + (_k==0)*nuc3[Cart::xxx][0][m+1] + 3*term_xx;\n    dip4[Cart::xxxy][0][_k][m] = PmA1*dip4[Cart::xxx][0][_k][m] - PmC1*dip4[Cart::xxx][0][_k][m+1] + (_k==1)*nuc3[Cart::xxx][0][m+1];\n    dip4[Cart::xxxz][0][_k][m] = PmA2*dip4[Cart::xxx][0][_k][m] - PmC2*dip4[Cart::xxx][0][_k][m+1] + (_k==2)*nuc3[Cart::xxx][0][m+1];\n    dip4[Cart::xxyy][0][_k][m] = PmA0*dip4[Cart::xyy][0][_k][m] - PmC0*dip4[Cart::xyy][0][_k][m+1] + (_k==0)*nuc3[Cart::xyy][0][m+1] + term_yy;\n    dip4[Cart::xxyz][0][_k][m] = PmA1*dip4[Cart::xxz][0][_k][m] - PmC1*dip4[Cart::xxz][0][_k][m+1] + (_k==1)*nuc3[Cart::xxz][0][m+1];\n    dip4[Cart::xxzz][0][_k][m] = PmA0*dip4[Cart::xzz][0][_k][m] - PmC0*dip4[Cart::xzz][0][_k][m+1] + (_k==0)*nuc3[Cart::xzz][0][m+1] + term_zz;\n    dip4[Cart::xyyy][0][_k][m] = PmA0*dip4[Cart::yyy][0][_k][m] - PmC0*dip4[Cart::yyy][0][_k][m+1] + (_k==0)*nuc3[Cart::yyy][0][m+1];\n    dip4[Cart::xyyz][0][_k][m] = PmA0*dip4[Cart::yyz][0][_k][m] - PmC0*dip4[Cart::yyz][0][_k][m+1] + (_k==0)*nuc3[Cart::yyz][0][m+1];\n    dip4[Cart::xyzz][0][_k][m] = PmA0*dip4[Cart::yzz][0][_k][m] - PmC0*dip4[Cart::yzz][0][_k][m+1] + (_k==0)*nuc3[Cart::yzz][0][m+1];\n    dip4[Cart::xzzz][0][_k][m] = PmA0*dip4[Cart::zzz][0][_k][m] - PmC0*dip4[Cart::zzz][0][_k][m+1] + (_k==0)*nuc3[Cart::zzz][0][m+1];\n    dip4[Cart::yyyy][0][_k][m] = PmA1*dip4[Cart::yyy][0][_k][m] - PmC1*dip4[Cart::yyy][0][_k][m+1] + (_k==1)*nuc3[Cart::yyy][0][m+1] + 3*term_yy;\n    dip4[Cart::yyyz][0][_k][m] = PmA2*dip4[Cart::yyy][0][_k][m] - PmC2*dip4[Cart::yyy][0][_k][m+1] + (_k==2)*nuc3[Cart::yyy][0][m+1];\n    dip4[Cart::yyzz][0][_k][m] = PmA1*dip4[Cart::yzz][0][_k][m] - PmC1*dip4[Cart::yzz][0][_k][m+1] + (_k==1)*nuc3[Cart::yzz][0][m+1] + term_zz;\n    dip4[Cart::yzzz][0][_k][m] = PmA1*dip4[Cart::zzz][0][_k][m] - PmC1*dip4[Cart::zzz][0][_k][m+1] + (_k==1)*nuc3[Cart::zzz][0][m+1];\n    dip4[Cart::zzzz][0][_k][m] = PmA2*dip4[Cart::zzz][0][_k][m] - PmC2*dip4[Cart::zzz][0][_k][m+1] + (_k==2)*nuc3[Cart::zzz][0][m+1] + 3*term_zz;\n    }\n  }\n}\n//------------------------------------------------------\n\n\n\nif (_lmax_col > 0) {\n\n  //Integrals     s - p\n  for (int m = 0; m < _lmax_col; m++) {\n    for (int _k = 0; _k < 3; _k++) {\n      dip4[0][Cart::x][_k][m] = PmB0*dip4[0][0][_k][m] - PmC0*dip4[0][0][_k][m+1] + (_k==0)*nuc3[0][0][m+1];\n      dip4[0][Cart::y][_k][m] = PmB1*dip4[0][0][_k][m] - PmC1*dip4[0][0][_k][m+1] + (_k==1)*nuc3[0][0][m+1];\n      dip4[0][Cart::z][_k][m] = PmB2*dip4[0][0][_k][m] - PmC2*dip4[0][0][_k][m+1] + (_k==2)*nuc3[0][0][m+1];\n    }\n  }\n  //------------------------------------------------------\n\n  //Integrals     p - p\n  if (_lmax_row > 0) {\n    for (int m = 0; m < _lmax_col; m++) {\n      for (int _i =  1; _i < 4; _i++) {\n        for (int _k = 0; _k < 3; _k++) {\n          double term = _fak*(dip4[0][0][_k][m]-dip4[0][0][_k][m+1]);\n          dip4[_i][Cart::x][_k][m] = PmB0*dip4[_i][0][_k][m] - PmC0*dip4[_i][0][_k][m+1] + (_k==0)*nuc3[_i][0][m+1] + nx[_i]*term;\n          dip4[_i][Cart::y][_k][m] = PmB1*dip4[_i][0][_k][m] - PmC1*dip4[_i][0][_k][m+1] + (_k==1)*nuc3[_i][0][m+1] + ny[_i]*term;\n          dip4[_i][Cart::z][_k][m] = PmB2*dip4[_i][0][_k][m] - PmC2*dip4[_i][0][_k][m+1] + (_k==2)*nuc3[_i][0][m+1] + nz[_i]*term;\n        }\n      }\n    }\n  }\n  //------------------------------------------------------\n\n  //Integrals     d - p     f - p     g - p\n  for (int m = 0; m < _lmax_col; m++) {\n    for (int _i = 4; _i < n_orbitals[_lmax_row]; _i++) {\n      int nx_i = nx[_i];\n      int ny_i = ny[_i];\n      int nz_i = nz[_i];\n      int ilx_i = i_less_x[_i];\n      int ily_i = i_less_y[_i];\n      int ilz_i = i_less_z[_i];\n      for (int _k = 0; _k < 3; _k++) {\n        dip4[_i][Cart::x][_k][m] = PmB0*dip4[_i][0][_k][m] - PmC0*dip4[_i][0][_k][m+1] + (_k==0)*nuc3[_i][0][m+1] + nx_i*_fak*(dip4[ilx_i][0][_k][m] - dip4[ilx_i][0][_k][m+1]);\n        dip4[_i][Cart::y][_k][m] = PmB1*dip4[_i][0][_k][m] - PmC1*dip4[_i][0][_k][m+1] + (_k==1)*nuc3[_i][0][m+1] + ny_i*_fak*(dip4[ily_i][0][_k][m] - dip4[ily_i][0][_k][m+1]);\n        dip4[_i][Cart::z][_k][m] = PmB2*dip4[_i][0][_k][m] - PmC2*dip4[_i][0][_k][m+1] + (_k==2)*nuc3[_i][0][m+1] + nz_i*_fak*(dip4[ilz_i][0][_k][m] - dip4[ilz_i][0][_k][m+1]);\n      }\n    }\n  }\n  //------------------------------------------------------\n\n} // end if (_lmax_col > 0)\n\n\nif (_lmax_col > 1) {\n\n  //Integrals     s - d\n  for (int m = 0; m < _lmax_col-1; m++) {\n    for (int _k = 0; _k < 3; _k++) {\n      double term = _fak*(dip4[0][0][_k][m]-dip4[0][0][_k][m+1]);\n      dip4[0][Cart::xx][_k][m] = PmB0*dip4[0][Cart::x][_k][m] - PmC0*dip4[0][Cart::x][_k][m+1] + (_k==0)*nuc3[0][Cart::x][m+1] + term;\n      dip4[0][Cart::xy][_k][m] = PmB0*dip4[0][Cart::y][_k][m] - PmC0*dip4[0][Cart::y][_k][m+1] + (_k==0)*nuc3[0][Cart::y][m+1];\n      dip4[0][Cart::xz][_k][m] = PmB0*dip4[0][Cart::z][_k][m] - PmC0*dip4[0][Cart::z][_k][m+1] + (_k==0)*nuc3[0][Cart::z][m+1];\n      dip4[0][Cart::yy][_k][m] = PmB1*dip4[0][Cart::y][_k][m] - PmC1*dip4[0][Cart::y][_k][m+1] + (_k==1)*nuc3[0][Cart::y][m+1] + term;\n      dip4[0][Cart::yz][_k][m] = PmB1*dip4[0][Cart::z][_k][m] - PmC1*dip4[0][Cart::z][_k][m+1] + (_k==1)*nuc3[0][Cart::z][m+1];\n      dip4[0][Cart::zz][_k][m] = PmB2*dip4[0][Cart::z][_k][m] - PmC2*dip4[0][Cart::z][_k][m+1] + (_k==2)*nuc3[0][Cart::z][m+1] + term;\n    }\n  }\n  //------------------------------------------------------\n\n  //Integrals     p - d     d - d     f - d     g - d\n  for (int m = 0; m < _lmax_col-1; m++) {\n    for (int _i = 1; _i < n_orbitals[_lmax_row]; _i++) {\n      int nx_i = nx[_i];\n      int ny_i = ny[_i];\n      int nz_i = nz[_i];\n      int ilx_i = i_less_x[_i];\n      int ily_i = i_less_y[_i];\n      int ilz_i = i_less_z[_i];\n      for (int _k = 0; _k < 3; _k++) {\n        double term = _fak*(dip4[_i][0][_k][m]-dip4[_i][0][_k][m+1]);\n        dip4[_i][Cart::xx][_k][m] = PmB0*dip4[_i][Cart::x][_k][m] - PmC0*dip4[_i][Cart::x][_k][m+1] + (_k==0)*nuc3[_i][Cart::x][m+1]\n                                    + nx_i*_fak*(dip4[ilx_i][Cart::x][_k][m] - dip4[ilx_i][Cart::x][_k][m+1]) + term;\n        dip4[_i][Cart::xy][_k][m] = PmB0*dip4[_i][Cart::y][_k][m] - PmC0*dip4[_i][Cart::y][_k][m+1] + (_k==0)*nuc3[_i][Cart::y][m+1]\n                                    + nx_i*_fak*(dip4[ilx_i][Cart::y][_k][m] - dip4[ilx_i][Cart::y][_k][m+1]);\n        dip4[_i][Cart::xz][_k][m] = PmB0*dip4[_i][Cart::z][_k][m] - PmC0*dip4[_i][Cart::z][_k][m+1] + (_k==0)*nuc3[_i][Cart::z][m+1]\n                                    + nx_i*_fak*(dip4[ilx_i][Cart::z][_k][m] - dip4[ilx_i][Cart::z][_k][m+1]);\n        dip4[_i][Cart::yy][_k][m] = PmB1*dip4[_i][Cart::y][_k][m] - PmC1*dip4[_i][Cart::y][_k][m+1] + (_k==1)*nuc3[_i][Cart::y][m+1]\n                                    + ny_i*_fak*(dip4[ily_i][Cart::y][_k][m] - dip4[ily_i][Cart::y][_k][m+1]) + term;\n        dip4[_i][Cart::yz][_k][m] = PmB1*dip4[_i][Cart::z][_k][m] - PmC1*dip4[_i][Cart::z][_k][m+1] + (_k==1)*nuc3[_i][Cart::z][m+1]\n                                    + ny_i*_fak*(dip4[ily_i][Cart::z][_k][m] - dip4[ily_i][Cart::z][_k][m+1]);\n        dip4[_i][Cart::zz][_k][m] = PmB2*dip4[_i][Cart::z][_k][m] - PmC2*dip4[_i][Cart::z][_k][m+1] + (_k==2)*nuc3[_i][Cart::z][m+1]\n                                    + nz_i*_fak*(dip4[ilz_i][Cart::z][_k][m] - dip4[ilz_i][Cart::z][_k][m+1]) + term;\n      }\n    }\n  }\n  //------------------------------------------------------\n\n} // end if (_lmax_col > 1)\n\n\nif (_lmax_col > 2) {\n\n  //Integrals     s - f\n  for (int m = 0; m < _lmax_col-2; m++) {\n    for (int _k = 0; _k < 3; _k++) {\n      dip4[0][Cart::xxx][_k][m] = PmB0*dip4[0][Cart::xx][_k][m] - PmC0*dip4[0][Cart::xx][_k][m+1] + (_k==0)*nuc3[0][Cart::xx][m+1] + 2*_fak*(dip4[0][Cart::x][_k][m]-dip4[0][Cart::x][_k][m+1]);\n      dip4[0][Cart::xxy][_k][m] = PmB1*dip4[0][Cart::xx][_k][m] - PmC1*dip4[0][Cart::xx][_k][m+1] + (_k==1)*nuc3[0][Cart::xx][m+1];\n      dip4[0][Cart::xxz][_k][m] = PmB2*dip4[0][Cart::xx][_k][m] - PmC2*dip4[0][Cart::xx][_k][m+1] + (_k==2)*nuc3[0][Cart::xx][m+1];\n      dip4[0][Cart::xyy][_k][m] = PmB0*dip4[0][Cart::yy][_k][m] - PmC0*dip4[0][Cart::yy][_k][m+1] + (_k==0)*nuc3[0][Cart::yy][m+1];\n      dip4[0][Cart::xyz][_k][m] = PmB0*dip4[0][Cart::yz][_k][m] - PmC0*dip4[0][Cart::yz][_k][m+1] + (_k==0)*nuc3[0][Cart::yz][m+1];\n      dip4[0][Cart::xzz][_k][m] = PmB0*dip4[0][Cart::zz][_k][m] - PmC0*dip4[0][Cart::zz][_k][m+1] + (_k==0)*nuc3[0][Cart::zz][m+1];\n      dip4[0][Cart::yyy][_k][m] = PmB1*dip4[0][Cart::yy][_k][m] - PmC1*dip4[0][Cart::yy][_k][m+1] + (_k==1)*nuc3[0][Cart::yy][m+1] + 2*_fak*(dip4[0][Cart::y][_k][m]-dip4[0][Cart::y][_k][m+1]);\n      dip4[0][Cart::yyz][_k][m] = PmB2*dip4[0][Cart::yy][_k][m] - PmC2*dip4[0][Cart::yy][_k][m+1] + (_k==2)*nuc3[0][Cart::yy][m+1];\n      dip4[0][Cart::yzz][_k][m] = PmB1*dip4[0][Cart::zz][_k][m] - PmC1*dip4[0][Cart::zz][_k][m+1] + (_k==1)*nuc3[0][Cart::zz][m+1];\n      dip4[0][Cart::zzz][_k][m] = PmB2*dip4[0][Cart::zz][_k][m] - PmC2*dip4[0][Cart::zz][_k][m+1] + (_k==2)*nuc3[0][Cart::zz][m+1] + 2*_fak*(dip4[0][Cart::z][_k][m]-dip4[0][Cart::z][_k][m+1]);\n    }\n  }\n  //------------------------------------------------------\n\n  //Integrals     p - f     d - f     f - f     g - f\n  for (int m = 0; m < _lmax_col-2; m++) {\n    for (int _i = 1; _i < n_orbitals[_lmax_row]; _i++) {\n      int nx_i = nx[_i];\n      int ny_i = ny[_i];\n      int nz_i = nz[_i];\n      int ilx_i = i_less_x[_i];\n      int ily_i = i_less_y[_i];\n      int ilz_i = i_less_z[_i];\n      for (int _k = 0; _k < 3; _k++) {\n        double term_x = 2*_fak*(dip4[_i][Cart::x][_k][m]-dip4[_i][Cart::x][_k][m+1]);\n        double term_y = 2*_fak*(dip4[_i][Cart::y][_k][m]-dip4[_i][Cart::y][_k][m+1]);\n        double term_z = 2*_fak*(dip4[_i][Cart::z][_k][m]-dip4[_i][Cart::z][_k][m+1]);\n        dip4[_i][Cart::xxx][_k][m] = PmB0*dip4[_i][Cart::xx][_k][m] - PmC0*dip4[_i][Cart::xx][_k][m+1] + (_k==0)*nuc3[_i][Cart::xx][m+1]\n                                     + nx_i*_fak*(dip4[ilx_i][Cart::xx][_k][m] - dip4[ilx_i][Cart::xx][_k][m+1]) + term_x;\n        dip4[_i][Cart::xxy][_k][m] = PmB1*dip4[_i][Cart::xx][_k][m] - PmC1*dip4[_i][Cart::xx][_k][m+1] + (_k==1)*nuc3[_i][Cart::xx][m+1]\n                                     + ny_i*_fak*(dip4[ily_i][Cart::xx][_k][m] - dip4[ily_i][Cart::xx][_k][m+1]);\n        dip4[_i][Cart::xxz][_k][m] = PmB2*dip4[_i][Cart::xx][_k][m] - PmC2*dip4[_i][Cart::xx][_k][m+1] + (_k==2)*nuc3[_i][Cart::xx][m+1]\n                                     + nz_i*_fak*(dip4[ilz_i][Cart::xx][_k][m] - dip4[ilz_i][Cart::xx][_k][m+1]);\n        dip4[_i][Cart::xyy][_k][m] = PmB0*dip4[_i][Cart::yy][_k][m] - PmC0*dip4[_i][Cart::yy][_k][m+1] + (_k==0)*nuc3[_i][Cart::yy][m+1]\n                                     + nx_i*_fak*(dip4[ilx_i][Cart::yy][_k][m] - dip4[ilx_i][Cart::yy][_k][m+1]);\n        dip4[_i][Cart::xyz][_k][m] = PmB0*dip4[_i][Cart::yz][_k][m] - PmC0*dip4[_i][Cart::yz][_k][m+1] + (_k==0)*nuc3[_i][Cart::yz][m+1]\n                                     + nx_i*_fak*(dip4[ilx_i][Cart::yz][_k][m] - dip4[ilx_i][Cart::yz][_k][m+1]);\n        dip4[_i][Cart::xzz][_k][m] = PmB0*dip4[_i][Cart::zz][_k][m] - PmC0*dip4[_i][Cart::zz][_k][m+1] + (_k==0)*nuc3[_i][Cart::zz][m+1]\n                                     + nx_i*_fak*(dip4[ilx_i][Cart::zz][_k][m] - dip4[ilx_i][Cart::zz][_k][m+1]);\n        dip4[_i][Cart::yyy][_k][m] = PmB1*dip4[_i][Cart::yy][_k][m] - PmC1*dip4[_i][Cart::yy][_k][m+1] + (_k==1)*nuc3[_i][Cart::yy][m+1]\n                                     + ny_i*_fak*(dip4[ily_i][Cart::yy][_k][m] - dip4[ily_i][Cart::yy][_k][m+1]) + term_y;\n        dip4[_i][Cart::yyz][_k][m] = PmB2*dip4[_i][Cart::yy][_k][m] - PmC2*dip4[_i][Cart::yy][_k][m+1] + (_k==2)*nuc3[_i][Cart::yy][m+1]\n                                     + nz_i*_fak*(dip4[ilz_i][Cart::yy][_k][m] - dip4[ilz_i][Cart::yy][_k][m+1]);\n        dip4[_i][Cart::yzz][_k][m] = PmB1*dip4[_i][Cart::zz][_k][m] - PmC1*dip4[_i][Cart::zz][_k][m+1] + (_k==1)*nuc3[_i][Cart::zz][m+1]\n                                     + ny_i*_fak*(dip4[ily_i][Cart::zz][_k][m] - dip4[ily_i][Cart::zz][_k][m+1]);\n        dip4[_i][Cart::zzz][_k][m] = PmB2*dip4[_i][Cart::zz][_k][m] - PmC2*dip4[_i][Cart::zz][_k][m+1] + (_k==2)*nuc3[_i][Cart::zz][m+1]\n                                     + nz_i*_fak*(dip4[ilz_i][Cart::zz][_k][m] - dip4[ilz_i][Cart::zz][_k][m+1]) + term_z;\n      }\n    }\n  }\n  //------------------------------------------------------\n\n} // end if (_lmax_col > 2)\n\n\nif (_lmax_col > 3) {\n\n  //Integrals     s - g\n  for (int m = 0; m < _lmax_col-3; m++) {\n    for (int _k = 0; _k < 3; _k++) {\n      double term_xx = _fak*(dip4[0][Cart::xx][_k][m]-dip4[0][Cart::xx][_k][m+1]);\n      double term_yy = _fak*(dip4[0][Cart::yy][_k][m]-dip4[0][Cart::yy][_k][m+1]);\n      double term_zz = _fak*(dip4[0][Cart::zz][_k][m]-dip4[0][Cart::zz][_k][m+1]);\n      dip4[0][Cart::xxxx][_k][m] = PmB0*dip4[0][Cart::xxx][_k][m] - PmC0*dip4[0][Cart::xxx][_k][m+1] + (_k==0)*nuc3[0][Cart::xxx][m+1] + 3*term_xx;\n      dip4[0][Cart::xxxy][_k][m] = PmB1*dip4[0][Cart::xxx][_k][m] - PmC1*dip4[0][Cart::xxx][_k][m+1] + (_k==1)*nuc3[0][Cart::xxx][m+1];\n      dip4[0][Cart::xxxz][_k][m] = PmB2*dip4[0][Cart::xxx][_k][m] - PmC2*dip4[0][Cart::xxx][_k][m+1] + (_k==2)*nuc3[0][Cart::xxx][m+1];\n      dip4[0][Cart::xxyy][_k][m] = PmB0*dip4[0][Cart::xyy][_k][m] - PmC0*dip4[0][Cart::xyy][_k][m+1] + (_k==0)*nuc3[0][Cart::xyy][m+1] + term_yy;\n      dip4[0][Cart::xxyz][_k][m] = PmB1*dip4[0][Cart::xxz][_k][m] - PmC1*dip4[0][Cart::xxz][_k][m+1] + (_k==1)*nuc3[0][Cart::xxz][m+1];\n      dip4[0][Cart::xxzz][_k][m] = PmB0*dip4[0][Cart::xzz][_k][m] - PmC0*dip4[0][Cart::xzz][_k][m+1] + (_k==0)*nuc3[0][Cart::xzz][m+1] + term_zz;\n      dip4[0][Cart::xyyy][_k][m] = PmB0*dip4[0][Cart::yyy][_k][m] - PmC0*dip4[0][Cart::yyy][_k][m+1] + (_k==0)*nuc3[0][Cart::yyy][m+1];\n      dip4[0][Cart::xyyz][_k][m] = PmB0*dip4[0][Cart::yyz][_k][m] - PmC0*dip4[0][Cart::yyz][_k][m+1] + (_k==0)*nuc3[0][Cart::yyz][m+1];\n      dip4[0][Cart::xyzz][_k][m] = PmB0*dip4[0][Cart::yzz][_k][m] - PmC0*dip4[0][Cart::yzz][_k][m+1] + (_k==0)*nuc3[0][Cart::yzz][m+1];\n      dip4[0][Cart::xzzz][_k][m] = PmB0*dip4[0][Cart::zzz][_k][m] - PmC0*dip4[0][Cart::zzz][_k][m+1] + (_k==0)*nuc3[0][Cart::zzz][m+1];\n      dip4[0][Cart::yyyy][_k][m] = PmB1*dip4[0][Cart::yyy][_k][m] - PmC1*dip4[0][Cart::yyy][_k][m+1] + (_k==1)*nuc3[0][Cart::yyy][m+1] + 3*term_yy;\n      dip4[0][Cart::yyyz][_k][m] = PmB2*dip4[0][Cart::yyy][_k][m] - PmC2*dip4[0][Cart::yyy][_k][m+1] + (_k==2)*nuc3[0][Cart::yyy][m+1];\n      dip4[0][Cart::yyzz][_k][m] = PmB1*dip4[0][Cart::yzz][_k][m] - PmC1*dip4[0][Cart::yzz][_k][m+1] + (_k==1)*nuc3[0][Cart::yzz][m+1] + term_zz;\n      dip4[0][Cart::yzzz][_k][m] = PmB1*dip4[0][Cart::zzz][_k][m] - PmC1*dip4[0][Cart::zzz][_k][m+1] + (_k==1)*nuc3[0][Cart::zzz][m+1];\n      dip4[0][Cart::zzzz][_k][m] = PmB2*dip4[0][Cart::zzz][_k][m] - PmC2*dip4[0][Cart::zzz][_k][m+1] + (_k==2)*nuc3[0][Cart::zzz][m+1] + 3*term_zz;\n    }\n  }\n  //------------------------------------------------------\n\n  //Integrals     p - g     d - g     f - g     g - g\n  for (int m = 0; m < _lmax_col-3; m++) {\n    for (int _i = 1; _i < n_orbitals[_lmax_row]; _i++) {\n      int nx_i = nx[_i];\n      int ny_i = ny[_i];\n      int nz_i = nz[_i];\n      int ilx_i = i_less_x[_i];\n      int ily_i = i_less_y[_i];\n      int ilz_i = i_less_z[_i];\n      for (int _k = 0; _k < 3; _k++) {\n        double term_xx = _fak*(dip4[_i][Cart::xx][_k][m]-dip4[_i][Cart::xx][_k][m+1]);\n        double term_yy = _fak*(dip4[_i][Cart::yy][_k][m]-dip4[_i][Cart::yy][_k][m+1]);\n        double term_zz = _fak*(dip4[_i][Cart::zz][_k][m]-dip4[_i][Cart::zz][_k][m+1]);\n        dip4[_i][Cart::xxxx][_k][m] = PmB0*dip4[_i][Cart::xxx][_k][m] - PmC0*dip4[_i][Cart::xxx][_k][m+1] + (_k==0)*nuc3[_i][Cart::xxx][m+1]\n                                      + nx_i*_fak*(dip4[ilx_i][Cart::xxx][_k][m] - dip4[ilx_i][Cart::xxx][_k][m+1]) + 3*term_xx;\n        dip4[_i][Cart::xxxy][_k][m] = PmB1*dip4[_i][Cart::xxx][_k][m] - PmC1*dip4[_i][Cart::xxx][_k][m+1] + (_k==1)*nuc3[_i][Cart::xxx][m+1]\n                                      + ny_i*_fak*(dip4[ily_i][Cart::xxx][_k][m] - dip4[ily_i][Cart::xxx][_k][m+1]);\n        dip4[_i][Cart::xxxz][_k][m] = PmB2*dip4[_i][Cart::xxx][_k][m] - PmC2*dip4[_i][Cart::xxx][_k][m+1] + (_k==2)*nuc3[_i][Cart::xxx][m+1]\n                                      + nz_i*_fak*(dip4[ilz_i][Cart::xxx][_k][m] - dip4[ilz_i][Cart::xxx][_k][m+1]);\n        dip4[_i][Cart::xxyy][_k][m] = PmB0*dip4[_i][Cart::xyy][_k][m] - PmC0*dip4[_i][Cart::xyy][_k][m+1] + (_k==0)*nuc3[_i][Cart::xyy][m+1]\n                                      + nx_i*_fak*(dip4[ilx_i][Cart::xyy][_k][m] - dip4[ilx_i][Cart::xyy][_k][m+1]) + term_yy;\n        dip4[_i][Cart::xxyz][_k][m] = PmB1*dip4[_i][Cart::xxz][_k][m] - PmC1*dip4[_i][Cart::xxz][_k][m+1] + (_k==1)*nuc3[_i][Cart::xxz][m+1]\n                                      + ny_i*_fak*(dip4[ily_i][Cart::xxz][_k][m] - dip4[ily_i][Cart::xxz][_k][m+1]);\n        dip4[_i][Cart::xxzz][_k][m] = PmB0*dip4[_i][Cart::xzz][_k][m] - PmC0*dip4[_i][Cart::xzz][_k][m+1] + (_k==0)*nuc3[_i][Cart::xzz][m+1]\n                                      + nx_i*_fak*(dip4[ilx_i][Cart::xzz][_k][m] - dip4[ilx_i][Cart::xzz][_k][m+1]) + term_zz;\n        dip4[_i][Cart::xyyy][_k][m] = PmB0*dip4[_i][Cart::yyy][_k][m] - PmC0*dip4[_i][Cart::yyy][_k][m+1] + (_k==0)*nuc3[_i][Cart::yyy][m+1]\n                                      + nx_i*_fak*(dip4[ilx_i][Cart::yyy][_k][m] - dip4[ilx_i][Cart::yyy][_k][m+1]);\n        dip4[_i][Cart::xyyz][_k][m] = PmB0*dip4[_i][Cart::yyz][_k][m] - PmC0*dip4[_i][Cart::yyz][_k][m+1] + (_k==0)*nuc3[_i][Cart::yyz][m+1]\n                                      + nx_i*_fak*(dip4[ilx_i][Cart::yyz][_k][m] - dip4[ilx_i][Cart::yyz][_k][m+1]);\n        dip4[_i][Cart::xyzz][_k][m] = PmB0*dip4[_i][Cart::yzz][_k][m] - PmC0*dip4[_i][Cart::yzz][_k][m+1] + (_k==0)*nuc3[_i][Cart::yzz][m+1]\n                                      + nx_i*_fak*(dip4[ilx_i][Cart::yzz][_k][m] - dip4[ilx_i][Cart::yzz][_k][m+1]);\n        dip4[_i][Cart::xzzz][_k][m] = PmB0*dip4[_i][Cart::zzz][_k][m] - PmC0*dip4[_i][Cart::zzz][_k][m+1] + (_k==0)*nuc3[_i][Cart::zzz][m+1]\n                                      + nx_i*_fak*(dip4[ilx_i][Cart::zzz][_k][m] - dip4[ilx_i][Cart::zzz][_k][m+1]);\n        dip4[_i][Cart::yyyy][_k][m] = PmB1*dip4[_i][Cart::yyy][_k][m] - PmC1*dip4[_i][Cart::yyy][_k][m+1] + (_k==1)*nuc3[_i][Cart::yyy][m+1]\n                                      + ny_i*_fak*(dip4[ily_i][Cart::yyy][_k][m] - dip4[ily_i][Cart::yyy][_k][m+1]) + 3*term_yy;\n        dip4[_i][Cart::yyyz][_k][m] = PmB2*dip4[_i][Cart::yyy][_k][m] - PmC2*dip4[_i][Cart::yyy][_k][m+1] + (_k==2)*nuc3[_i][Cart::yyy][m+1]\n                                      + nz_i*_fak*(dip4[ilz_i][Cart::yyy][_k][m] - dip4[ilz_i][Cart::yyy][_k][m+1]);\n        dip4[_i][Cart::yyzz][_k][m] = PmB1*dip4[_i][Cart::yzz][_k][m] - PmC1*dip4[_i][Cart::yzz][_k][m+1] + (_k==1)*nuc3[_i][Cart::yzz][m+1]\n                                      + ny_i*_fak*(dip4[ily_i][Cart::yzz][_k][m] - dip4[ily_i][Cart::yzz][_k][m+1]) + term_zz;\n        dip4[_i][Cart::yzzz][_k][m] = PmB1*dip4[_i][Cart::zzz][_k][m] - PmC1*dip4[_i][Cart::zzz][_k][m+1] + (_k==1)*nuc3[_i][Cart::zzz][m+1]\n                                      + ny_i*_fak*(dip4[ily_i][Cart::zzz][_k][m] - dip4[ily_i][Cart::zzz][_k][m+1]);\n        dip4[_i][Cart::zzzz][_k][m] = PmB2*dip4[_i][Cart::zzz][_k][m] - PmC2*dip4[_i][Cart::zzz][_k][m+1] + (_k==2)*nuc3[_i][Cart::zzz][m+1]\n                                      + nz_i*_fak*(dip4[ilz_i][Cart::zzz][_k][m] - dip4[ilz_i][Cart::zzz][_k][m+1]) + 3*term_zz;\n      }\n    }\n  }\n  //------------------------------------------------------\n\n} // end if (_lmax_col > 3)\n\n\nfor (int _i = 0; _i < _nrows; _i++) {\n  for (int _j = 0; _j < _ncols; _j++) {\n    dip(_i,_j) = d_0 * dip4[_i][_j][0][0] + d_1 * dip4[_i][_j][1][0] + d_2 * dip4[_i][_j][2][0];\n  }\n}                         \n\n        \n        ub::matrix<double> _trafo_row = getTrafo(*itr);\n        ub::matrix<double> _trafo_col_tposed = ub::trans(getTrafo(*itc));      \n             \n        ub::matrix<double> _dip_tmp = ub::prod( _trafo_row, dip );\n        ub::matrix<double> _dip_sph = ub::prod( _dip_tmp, _trafo_col_tposed );\n        // save to _matrix\n        \n        for ( unsigned i = 0; i< _matrix.size1(); i++ ) {\n            for (unsigned j = 0; j < _matrix.size2(); j++) {\n                _matrix(i,j) += _dip_sph(i+_shell_row->getOffset(),j+_shell_col->getOffset());\n            }\n        }\n        \n            }// _shell_col Gaussians\n        }// _shell_row Gaussians\n        }\n\n        void AODipole_Potential::Fillextpotential(const AOBasis& aobasis, const std::vector<ctp::PolarSeg*> & _sites) {\n\n            _externalpotential = ub::zero_matrix<double>(aobasis.AOBasisSize(), aobasis.AOBasisSize());\n            for (unsigned int i = 0; i < _sites.size(); i++) {\n                for (ctp::PolarSeg::const_iterator it = _sites[i]->begin(); it < _sites[i]->end(); ++it) {\n\n                    if ((*it)->getRank() > 0 || (*it)->IsPolarizable()) {\n                        vec positionofsite = (*it)->getPos() * tools::conv::nm2bohr;\n                        _aomatrix = ub::zero_matrix<double>(aobasis.AOBasisSize(), aobasis.AOBasisSize());\n                        setAPolarSite((*it));\n                        Fill(aobasis, positionofsite);\n                        _externalpotential += _aomatrix;\n                    }\n                }\n            }\n            return;\n        }\n\n\n\n\n    \n}}\n\n", "meta": {"hexsha": "138ac5e11ef459a12126e15cb5d5d1ab747897a3", "size": 48881, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/libxtp/aomatrices/aodipole_potential.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/aomatrices/aodipole_potential.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/aomatrices/aodipole_potential.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": 59.9031862745, "max_line_length": 192, "alphanum_fraction": 0.4960618645, "num_tokens": 23145, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7401743505760728, "lm_q2_score": 0.42250463481418826, "lm_q1q2_score": 0.3127270936889726}}
{"text": "/*\n Copyright (C) 2019 Quaternion Risk Management Ltd\n All rights reserved.\n\n This file is part of ORE, a free-software/open-source library\n for transparent pricing and risk analysis - http://opensourcerisk.org\n\n ORE is free software: you can redistribute it and/or modify it\n under the terms of the Modified BSD License.  You should have received a\n copy of the license along with this program.\n The license is also available online at <http://opensourcerisk.org>\n\n This program is distributed on the basis that it will form a useful\n contribution to risk analytics and model standardisation, but WITHOUT\n ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n FITNESS FOR A PARTICULAR PURPOSE. See the license for more details.\n*/\n\n#include <boost/make_shared.hpp>\n#include <ql/instruments/impliedvolatility.hpp>\n#include <ql/instruments/vanillaoption.hpp>\n#include <ql/math/solvers1d/brent.hpp>\n#include <ql/pricingengines/vanilla/analyticeuropeanengine.hpp>\n#include <ql/processes/blackscholesprocess.hpp>\n#include <ql/termstructures/volatility/equityfx/blackconstantvol.hpp>\n#include <qle/pricingengines/baroneadesiwhaleyengine.hpp>\n#include <qle/termstructures/blackvariancesurfacesparse.hpp>\n#include <qle/termstructures/equityoptionsurfacestripper.hpp>\n\nusing std::pair;\nusing std::vector;\nusing namespace QuantLib;\n\nnamespace {\n\nclass PriceError {\npublic:\n    PriceError(const VanillaOption& option, SimpleQuote& vol, Real targetValue)\n        : option_(option), vol_(vol), targetValue_(targetValue){};\n    Real operator()(Volatility x) const;\n\nprivate:\n    const VanillaOption& option_;\n    SimpleQuote& vol_;\n    Real targetValue_;\n};\n\nReal PriceError::operator()(Volatility x) const {\n    vol_.setValue(x);\n    Real npv;\n    // Barone Adesi Whaley fails for very small variance, so wrap in a try/catch\n    try {\n        npv = option_.NPV();\n    } catch (...) {\n        npv = 0.0;\n    }\n    return npv - targetValue_;\n}\n\n} // namespace\n\nnamespace QuantExt {\n\nEquityOptionSurfaceStripper::EquityOptionSurfaceStripper(const boost::shared_ptr<OptionInterpolatorBase>& callSurface,\n                                                         const boost::shared_ptr<OptionInterpolatorBase>& putSurface,\n                                                         const Handle<EquityIndex>& eqIndex, const Calendar& calendar,\n                                                         const DayCounter& dayCounter, Exercise::Type type,\n                                                         bool lowerStrikeConstExtrap, bool upperStrikeConstExtrap,\n                                                         bool timeFlatExtrapolation)\n    : callSurface_(callSurface), putSurface_(putSurface), eqIndex_(eqIndex), calendar_(calendar),\n      dayCounter_(dayCounter), type_(type), lowerStrikeConstExtrap_(lowerStrikeConstExtrap),\n      upperStrikeConstExtrap_(upperStrikeConstExtrap), timeFlatExtrapolation_(timeFlatExtrapolation) {\n\n    // the call and put surfaces should have the same expiries/strikes/reference date/day counters, some checks to\n    // ensure this\n    QL_REQUIRE(callSurface_->referenceDate() == putSurface_->referenceDate(),\n               \"Mismatch between Call and Put reference dates in EquityOptionPremiumCurveStripper\");\n\n    // register with all market data\n    registerWith(eqIndex);\n    registerWith(Settings::instance().evaluationDate());\n}\n\nvoid EquityOptionSurfaceStripper::performCalculations() const {\n    // create a set of all dates\n    std::set<Date> allExpiries;\n    std::vector<Date> callExpiries = callSurface_->expiries();\n    std::vector<Date> putExpiries = putSurface_->expiries();\n    for (auto expiry : callExpiries)\n        allExpiries.insert(expiry);\n    for (auto expiry : putExpiries)\n        allExpiries.insert(expiry);\n\n    boost::shared_ptr<SimpleQuote> volQuote;\n    boost::shared_ptr<PricingEngine> engine;\n\n    boost::shared_ptr<BlackVarianceSurfaceSparse> callVolSurface, putVolSurface;\n\n    // if the surface is a price surface then we have premiums\n    bool premiumSurfaces = boost::dynamic_pointer_cast<OptionPriceSurface>(callSurface_) != NULL;\n    if (premiumSurfaces) {\n        // first also check the put surface\n        QL_REQUIRE(boost::dynamic_pointer_cast<OptionPriceSurface>(putSurface_) != NULL,\n                   \"Call price surface provided, but no put price surface\");\n\n        // Set up the engine for implying the vols\n        // term structures needed to get implied vol\n        volQuote = boost::make_shared<SimpleQuote>(0.1);\n        Handle<BlackVolTermStructure> volTs(boost::make_shared<BlackConstantVol>(\n            callSurface_->referenceDate(), calendar_, Handle<Quote>(volQuote), dayCounter_));\n\n        // a black scholes process\n        boost::shared_ptr<GeneralizedBlackScholesProcess> gbsp = boost::make_shared<BlackScholesMertonProcess>(\n            eqIndex_->equitySpot(), eqIndex_->equityDividendCurve(), eqIndex_->equityForecastCurve(), volTs);\n\n        // hard code the engines here\n        // BaroneAdesiWhaley for American options - much faster than alternatives\n        // Black for European\n        if (type_ == Exercise::American) {\n            engine = boost::make_shared<QuantExt::BaroneAdesiWhaleyApproximationEngine>(gbsp);\n        } else if (type_ == Exercise::European) {\n            engine = boost::make_shared<QuantExt::AnalyticEuropeanEngine>(gbsp);\n        } else {\n            QL_FAIL(\"Unsupported exercise type for option stripping\");\n        }\n    } else {\n        // we have variance surfaces, explicitly cast so we can look up vol later\n        callVolSurface = boost::dynamic_pointer_cast<BlackVarianceSurfaceSparse>(callSurface_);\n        putVolSurface = boost::dynamic_pointer_cast<BlackVarianceSurfaceSparse>(putSurface_);\n    }\n\n    vector<Real> volStrikes;\n    vector<Real> volData;\n    vector<Date> volExpiries;\n\n    // loop over each expiry\n    for (auto exp : allExpiries) {\n        // get the forward price at time\n        Real forward = eqIndex_->fixing(exp);\n\n        vector<Real> callStrikes, putStrikes;\n        auto itc = std::find(callExpiries.begin(), callExpiries.end(), exp);\n        if (itc != callExpiries.end()) {\n            auto pos = std::distance(callExpiries.begin(), itc);\n            callStrikes = callSurface_->strikes().at(pos);\n        }\n        auto itp = std::find(putExpiries.begin(), putExpiries.end(), exp);\n        if (itp != putExpiries.end()) {\n            auto pos = std::distance(putExpiries.begin(), itp);\n            putStrikes = putSurface_->strikes().at(pos);\n        }\n\n        // We want a set of prices both sides of ATM forward\n        // We take calls where strike < atm, and puts where strike > atm\n\n        bool haveCalls = false, havePuts = false;\n        // check if calls in the correct range\n        if (callStrikes.size() > 0 && callStrikes.front() < forward)\n            haveCalls = true;\n\n        // check if puts in the correct range\n        if (putStrikes.size() > 0 && putStrikes.back() > forward)\n            havePuts = true;\n\n        for (auto cs : callStrikes) {\n            if (!havePuts || cs < forward) {\n                volStrikes.push_back(cs);\n                volExpiries.push_back(exp);\n                if (premiumSurfaces) {\n                    volData.push_back(implyVol(exp, cs, Option::Call, engine, volQuote));\n                } else {\n                    volData.push_back(callVolSurface->blackVol(exp, cs));\n                }\n            }\n        }\n        for (auto ps : putStrikes) {\n            if (!haveCalls || ps > forward) {\n                volStrikes.push_back(ps);\n                volExpiries.push_back(exp);\n                if (premiumSurfaces) {\n                    volData.push_back(implyVol(exp, ps, Option::Put, engine, volQuote));\n                } else {\n                    volData.push_back(putVolSurface->blackVol(exp, ps));\n                }\n            }\n        }\n    }\n    volSurface_ = boost::make_shared<BlackVarianceSurfaceSparse>(\n        callSurface_->referenceDate(), calendar_, volExpiries, volStrikes, volData, dayCounter_,\n        lowerStrikeConstExtrap_, upperStrikeConstExtrap_, timeFlatExtrapolation_);\n}\n\nReal EquityOptionSurfaceStripper::implyVol(Date expiry, Real strike, Option::Type type,\n                                           boost::shared_ptr<PricingEngine> engine,\n                                           boost::shared_ptr<SimpleQuote> volQuote) const {\n\n    // create an american option for current strike/expiry and type\n    boost::shared_ptr<StrikedTypePayoff> payoff(new PlainVanillaPayoff(type, strike));\n    boost::shared_ptr<Exercise> exercise;\n    if (type_ == Exercise::American) {\n        exercise = boost::make_shared<AmericanExercise>(expiry);\n    } else if (type_ == Exercise::European) {\n        exercise = boost::make_shared<EuropeanExercise>(expiry);\n    } else {\n        QL_FAIL(\"Unsupported exercise type for option stripping\");\n    }\n    VanillaOption option(payoff, exercise);\n    option.setPricingEngine(engine);\n\n    // option.setPricingEngine(engine);\n    Real targetPrice =\n        type == Option::Call ? callSurface_->getValue(expiry, strike) : putSurface_->getValue(expiry, strike);\n\n    // calculate the implied volatility using a solver\n    Real vol;\n    try {\n        PriceError f(option, *volQuote, targetPrice);\n        Brent solver;\n        solver.setMaxEvaluations(100);\n        solver.setLowerBound(0.0001);\n        vol = solver.solve(f, 0.0001, 0.2, 0.01);\n    } catch (...) {\n        vol = 0.0;\n    }\n    return vol;\n}\n\nboost::shared_ptr<QuantLib::BlackVolTermStructure> EquityOptionSurfaceStripper::volSurface() {\n    calculate();\n    return volSurface_;\n}\n\n} // namespace QuantExt", "meta": {"hexsha": "27c4c932533a5fc7331aa261e261948390e4445b", "size": 9675, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "QuantExt/qle/termstructures/equityoptionsurfacestripper.cpp", "max_stars_repo_name": "mrslezak/Engine", "max_stars_repo_head_hexsha": "c46ff278a2c5f4162db91a7ab500a0bb8cef7657", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 335.0, "max_stars_repo_stars_event_min_datetime": "2016-10-07T16:31:10.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-02T07:12:03.000Z", "max_issues_repo_path": "QuantExt/qle/termstructures/equityoptionsurfacestripper.cpp", "max_issues_repo_name": "mrslezak/Engine", "max_issues_repo_head_hexsha": "c46ff278a2c5f4162db91a7ab500a0bb8cef7657", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 59.0, "max_issues_repo_issues_event_min_datetime": "2016-10-31T04:20:24.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-03T16:39:57.000Z", "max_forks_repo_path": "QuantExt/qle/termstructures/equityoptionsurfacestripper.cpp", "max_forks_repo_name": "mrslezak/Engine", "max_forks_repo_head_hexsha": "c46ff278a2c5f4162db91a7ab500a0bb8cef7657", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 180.0, "max_forks_repo_forks_event_min_datetime": "2016-10-08T14:23:50.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T10:43:05.000Z", "avg_line_length": 41.5236051502, "max_line_length": 118, "alphanum_fraction": 0.6564341085, "num_tokens": 2218, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6723316860482762, "lm_q2_score": 0.46490157137338844, "lm_q1q2_score": 0.3125680573279633}}
{"text": "/*\n * Author: Benoit Sklenard benoit.sklenard@cea.fr \n * \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 <cmath>\n#include <vector>\n\n#include \"io/Diagnostic.h\"\n#include \"io/ParameterManager.h\"\n\n#include \"okmc/Defect.h\"\n#include \"kernel/ParticleType.h\"\n#include \"okmc/MobileParticleParam.h\"\n\n#include <boost/numeric/ublas/io.hpp>\n\n#include \"kernel/Mesh.h\"\n\n#include \"ParticleToNodeHandler.h\"\n\n#include <ctime>\n\nusing namespace Electrostatics;\nusing namespace Kernel;\nusing namespace boost::numeric;\n\nParticleToNodeHandler::ParticleToNodeHandler(Kernel::Domain *pDomain, Kernel::Mesh *pMesh) {\n\tLOWMSG(\"Loading Particle To Node handler\");\n\t_pMesh   = pMesh;\n\t_pDomain = pDomain;\n}\n\nParticleToNodeHandler::~ParticleToNodeHandler() {\n\n}\n\ninline double ParticleToNodeHandler::getOverlap(double u1, double u2) {\n\treturn 15./16. * ((u2 - u1) - 2./3. * (u2*u2*u2 - u1*u1*u1) + 1./5. * (u2*u2*u2*u2*u2 - u1*u1*u1*u1*u1));\n}\n\nvoid ParticleToNodeHandler::remove(OKMC::Particle *pPart) {\n\tstd::map<OKMC::Particle *, std::set<MeshNode *> >::iterator mit;\n\n\tmit = _syncOKMC.find(pPart);\n\tif (mit != _syncOKMC.end()) {\n\t\tfor (std::set<MeshNode *>::iterator sit = mit->second.begin(); sit != mit->second.end(); ++sit)\n\t\t\t(*sit)->remove(pPart);\n\t\t_syncOKMC.erase(mit);\n\t}\n}\n\nvoid ParticleToNodeHandler::remove(LKMC::LatticeAtom *pLA) {\n\tstd::map<LKMC::LatticeAtom *, std::set<MeshNode *> >::iterator mit;\n\n\tmit = _syncLKMC.find(pLA);\n\tif (mit != _syncLKMC.end()) {\n\t\tfor (std::set<MeshNode *>::iterator sit = mit->second.begin(); sit != mit->second.end(); ++sit)\n\t\t\t(*sit)->remove(pLA);\n\t\t_syncLKMC.erase(mit);\n\t}\n}\n\ndouble ParticleToNodeHandler::addWeightNode(MeshNode *pNode, LKMC::LatticeAtom *pLA) {\n\tM_TYPE mt = pLA->getElement()->getMaterial();\n\tdouble dr = _pDomain->_pLaPar[mt]->_orbitalRadius;\n\n\tublas::vector<double> n  = ublas::zero_vector<double>(3);\n\tublas::vector<double> c1 = ublas::zero_vector<double>(3);\n\tublas::vector<double> c2 = ublas::zero_vector<double>(3);\n\tMeshNode ***pNodes = _pMesh->getNodes();\n\n\tn(0)  = pLA->getCoordinates()._x;\n\tn(1)  = pLA->getCoordinates()._y;\n\tn(2)  = pLA->getCoordinates()._z;\n\n\tc1(0) = pNode->_xm;\n\tc1(1) = pNode->_ym;\n\tc1(2) = pNode->_zm;\n\tc2(0) = pNode->_xp;\n\tc2(1) = pNode->_yp;\n\tc2(2) = pNode->_zp;\n\n\t_pMesh->setPeriodicRelative(n, c1); // c1 = c1 - n\n\t_pMesh->setPeriodicRelative(n, c2); // c2 = c2 - n\n\n\tc1 /= dr;\n\tc2 /= dr;\n\n\tif (c1(0) <= -1) c1(0) = -1.;\n\tif (c2(0) <= -1) c2(0) = -1.;\n\tif (c1(0) >= 1)  c1(0) = 1.;\n\tif (c2(0) >= 1)  c2(0) = 1.;\n\n\tif (c1(1) <= -1) c1(1) = -1.;\n\tif (c2(1) <= -1) c2(1) = -1.;\n\tif (c1(1) >= 1)  c1(1) = 1.;\n\tif (c2(1) >= 1)  c2(1) = 1.;\n\n\tif (c1(2) <= -1) c1(2) = -1.;\n\tif (c2(2) <= -1) c2(2) = -1.;\n\tif (c1(2) >= 1)  c1(2) = 1.;\n\tif (c2(2) >= 1)  c2(2) = 1.;\n\n\tconst double wx  = getOverlap(c1(0), c2(0));\n\tconst double wy  = getOverlap(c1(1), c2(1));\n\tconst double wz  = getOverlap(c1(2), c2(2));\n\n\tconst double w   = wx * wy * wz;\n\n\tif (w > 0) {\n\t\tunsigned i = pNode->_ix;\n\t\tunsigned j = pNode->_iy;\n\t\tunsigned k = pNode->_iz;\n\n\t\tif (_pMesh->getPeriodicX() && pNode->_ix == (_pMesh->getnx() - 1))\n\t\t\ti = 0;\n\t\tif (_pMesh->getPeriodicY() && pNode->_iy == (_pMesh->getny() - 1))\n\t\t\tj = 0;\n\t\tif (_pMesh->getPeriodicZ() && pNode->_iz == (_pMesh->getnz() - 1))\n\t\t\tk = 0;\n\n\t\tpNodes[i][j][k].insert(pLA, w);\n\n\t    std::pair<std::map<LKMC::LatticeAtom *, std::set<MeshNode *> >::iterator, bool > r;\n\t    r = _syncLKMC.insert(std::pair<LKMC::LatticeAtom *, std::set<MeshNode *> >(pLA, std::set<MeshNode *>()));\n\t    r.first->second.insert(&pNodes[i][j][k]);\n\t}\n\n\treturn w;\n}\n\ndouble ParticleToNodeHandler::addWeightNode(MeshNode *pNode, OKMC::Particle *pPart) {\n\tM_TYPE mt = pPart->getElement()->getMaterial();\n\tP_TYPE pt = pPart->getPType();\n\n\tdouble dr = _pDomain->_pMPPar->_orbitalRadius[mt][pt];\n\t// double dr = 1.; // _pDomain->_pLaPar[mt]->_orbitalRadius;\n\n\tublas::vector<double> n  = ublas::zero_vector<double>(3);\n\tublas::vector<double> c1 = ublas::zero_vector<double>(3);\n\tublas::vector<double> c2 = ublas::zero_vector<double>(3);\n\tMeshNode ***pNodes = _pMesh->getNodes();\n\n\tn(0)  = pPart->getCoordinates()._x;\n\tn(1)  = pPart->getCoordinates()._y;\n\tn(2)  = pPart->getCoordinates()._z;\n\n\tc1(0) = pNode->_xm;\n\tc1(1) = pNode->_ym;\n\tc1(2) = pNode->_zm;\n\tc2(0) = pNode->_xp;\n\tc2(1) = pNode->_yp;\n\tc2(2) = pNode->_zp;\n\n\t_pMesh->setPeriodicRelative(n, c1); // c1 = c1 - n\n\t_pMesh->setPeriodicRelative(n, c2); // c2 = c2 - n\n\n\tc1 /= dr;\n\tc2 /= dr;\n\n\tif (c1(0) <= -1) c1(0) = -1.;\n\tif (c2(0) <= -1) c2(0) = -1.;\n\tif (c1(0) >= 1)  c1(0) = 1.;\n\tif (c2(0) >= 1)  c2(0) = 1.;\n\n\tif (c1(1) <= -1) c1(1) = -1.;\n\tif (c2(1) <= -1) c2(1) = -1.;\n\tif (c1(1) >= 1)  c1(1) = 1.;\n\tif (c2(1) >= 1)  c2(1) = 1.;\n\n\tif (c1(2) <= -1) c1(2) = -1.;\n\tif (c2(2) <= -1) c2(2) = -1.;\n\tif (c1(2) >= 1)  c1(2) = 1.;\n\tif (c2(2) >= 1)  c2(2) = 1.;\n\n\tconst double wx  = getOverlap(c1(0), c2(0));\n\tconst double wy  = getOverlap(c1(1), c2(1));\n\tconst double wz  = getOverlap(c1(2), c2(2));\n\n\tconst double w   = wx * wy * wz;\n\n\tif (w > 0) {\n\t\tunsigned i = pNode->_ix;\n\t\tunsigned j = pNode->_iy;\n\t\tunsigned k = pNode->_iz;\n\n\t\tif (_pMesh->getPeriodicX() && pNode->_ix == (_pMesh->getnx() - 1))\n\t\t\ti = 0;\n\t\tif (_pMesh->getPeriodicY() && pNode->_iy == (_pMesh->getny() - 1))\n\t\t\tj = 0;\n\t\tif (_pMesh->getPeriodicZ() && pNode->_iz == (_pMesh->getnz() - 1))\n\t\t\tk = 0;\n\n\t\tpNodes[i][j][k].insert(pPart, w);\n\n\t    std::pair<std::map<OKMC::Particle *, std::set<MeshNode *> >::iterator, bool > r;\n\t    r = _syncOKMC.insert(std::pair<OKMC::Particle *, std::set<MeshNode *> >(pPart, std::set<MeshNode *>()));\n\t    r.first->second.insert(&pNodes[i][j][k]);\n\t}\n\n\treturn w;\n}\n\nvoid ParticleToNodeHandler::insert(LKMC::LatticeAtom *pLA) {\n\tstd::set<MeshNode*> MN;\n\tMeshNode* pMN = NULL;\n\n\tM_TYPE mt = pLA->getElement()->getMaterial();\n\n\tdouble dr = _pDomain->_pLaPar[mt]->_orbitalRadius;\n\n\tremove(pLA);\n\tMeshNode ***pNodes  = _pMesh->getNodes();\n\tpMN = _pMesh->getFirstNodeFromElement(pLA->getElement());\n\n\n\tconst size_t dx = ceil(dr / fabs(pNodes[0][0][0]._xm - pNodes[0][0][0]._xp)) + 1;\n\tconst size_t dy = ceil(dr / fabs(pNodes[0][0][0]._ym - pNodes[0][0][0]._yp)) + 1;\n\tconst size_t dz = ceil(dr / fabs(pNodes[0][0][0]._zm - pNodes[0][0][0]._zp)) + 1;\n\n\tconst size_t startx = (dx <= pMN->_ix ? pMN->_ix - dx : _pMesh->getnx() - 1 - dx + pMN->_ix);\n\tconst size_t endx   = (pMN->_ix + dx) % _pMesh->getnx();\n\tconst size_t starty = (dy <= pMN->_iy ? pMN->_iy - dy : _pMesh->getny() - 1 - dy + pMN->_iy);\n\tconst size_t endy   = (pMN->_iy + dy) % _pMesh->getny();\n\tconst size_t startz = (dz <= pMN->_iz ? pMN->_iz - dz : _pMesh->getnz() - 1 - dz + pMN->_iz);\n\tconst size_t endz   = (pMN->_iz + dz) % _pMesh->getnz();\n\n\tdouble w = 0.;\n\tfor (size_t ix = startx; ix != endx; ix = (ix + 1) % _pMesh->getnx()) {\n\t\tfor (size_t iy = starty; iy != endy; iy = (iy + 1) % _pMesh->getny()) {\n\t\t\tfor (size_t iz = startz; iz != endz; iz = (iz + 1) % _pMesh->getnz()) {\n\t\t\t\tw += addWeightNode(&pNodes[ix][iy][iz], pLA);\n\t\t\t}\n\t\t}\n\t}\n\n\tif (_syncLKMC.find(pLA) ==_syncLKMC.end())\n\t\tERRORMSG(\"LatticeAtom has not been inserted!\");\n}\n\n\nvoid ParticleToNodeHandler::insert(OKMC::Particle *pPart) {\n\tstd::set<MeshNode*> MN;\n\tMeshNode* pMN = NULL;\n\n\tM_TYPE mt = pPart->getElement()->getMaterial();\n\tP_TYPE pt = pPart->getPType();\n\n\tif (!_pDomain->_pMPPar->_mapToGrid[mt][pt]) {\n\t//\tWARNINGMSG(\"Not inserted (OKMC) \" << Domains::global()->PM()->getMaterialName(mt) << \" \" << Domains::global()->PM()->getParticleName(mt, pt));\n\t\treturn ;\n\t}\n\n\tdouble dr = _pDomain->_pMPPar->_orbitalRadius[mt][pt];\n\n\tremove(pPart);\n\tMeshNode ***pNodes  = _pMesh->getNodes();\n\tpMN = _pMesh->getFirstNodeFromElement(pPart->getElement());\n\n\tconst size_t dx = ceil(dr / fabs(pNodes[0][0][0]._xm - pNodes[0][0][0]._xp)) + 1;\n\tconst size_t dy = ceil(dr / fabs(pNodes[0][0][0]._ym - pNodes[0][0][0]._yp)) + 1;\n\tconst size_t dz = ceil(dr / fabs(pNodes[0][0][0]._zm - pNodes[0][0][0]._zp)) + 1;\n\n\tconst size_t startx = (dx <= pMN->_ix ? pMN->_ix - dx : _pMesh->getnx() - 1 - dx + pMN->_ix);\n\tconst size_t endx   = (pMN->_ix + dx) % _pMesh->getnx();\n\tconst size_t starty = (dy <= pMN->_iy ? pMN->_iy - dy : _pMesh->getny() - 1 - dy + pMN->_iy);\n\tconst size_t endy   = (pMN->_iy + dy) % _pMesh->getny();\n\tconst size_t startz = (dz <= pMN->_iz ? pMN->_iz - dz : _pMesh->getnz() - 1 - dz + pMN->_iz);\n\tconst size_t endz   = (pMN->_iz + dz) % _pMesh->getnz();\n\n\tdouble w = 0.;\n\tfor (size_t ix = startx; ix != endx; ix = (ix + 1) % _pMesh->getnx()) {\n\t\tfor (size_t iy = starty; iy != endy; iy = (iy + 1) % _pMesh->getny()) {\n\t\t\tfor (size_t iz = startz; iz != endz; iz = (iz + 1) % _pMesh->getnz()) {\n\t\t\t\tw += addWeightNode(&pNodes[ix][iy][iz], pPart);\n\t\t\t}\n\t\t}\n\t}\n\n\tif (_syncOKMC.find(pPart) ==_syncOKMC.end())\n\t\tERRORMSG(\"Particle has not been inserted!\");\n}\n\nvoid ParticleToNodeHandler::getParticleNodes(OKMC::Particle *pPart, std::set<MeshNode *> &nodes) {\n\tstd::map<OKMC::Particle *, std::set<MeshNode *> >::iterator mit = _syncOKMC.find(pPart);\n\n\tif (mit != _syncOKMC.end())\n\t\tfor (std::set<MeshNode *>::iterator sit = mit->second.begin(); sit != mit->second.end(); ++sit)\n\t\t\tnodes.insert(*sit);\n}\n\nvoid ParticleToNodeHandler::getParticleNodes(LKMC::LatticeAtom *pLA, std::set<MeshNode *> &nodes) {\n\tstd::map<LKMC::LatticeAtom *, std::set<MeshNode *> >::iterator mit = _syncLKMC.find(pLA);\n\n\tif (mit != _syncLKMC.end())\n\t\tfor (std::set<MeshNode *>::iterator sit = mit->second.begin(); sit != mit->second.end(); ++sit)\n\t\t\tnodes.insert(*sit);\n}\n\nvoid ParticleToNodeHandler::print() {\n\tLOWMSG(_syncOKMC.size() << \" particles in ParticleToNodeHandler:\");\n\n\tif (!_syncOKMC.empty()) {\n\t\tunsigned i = 0;\n\n\t\tfor (std::map<OKMC::Particle *, std::set<MeshNode *> >::iterator mit = _syncOKMC.begin(); mit != _syncOKMC.end(); ++mit) {\n\t\t\tdouble w = 0.;\n\t\t\tfor (std::set<MeshNode *>::iterator sit = mit->second.begin(); sit != mit->second.end(); ++sit) {\n\t\t\t\tstd::map<OKMC::Particle *, double>::iterator mit2 = (*sit)->_mPart.find(mit->first);\n\t\t\t\tif (mit2 != (*sit)->_mPart.end())\n\t\t\t\t\tw += mit2->second;\n\t\t\t\telse\n\t\t\t\t\tLOWMSG(\"Got a null value!\");\n\t\t\t}\n\t\t\tLOWMSG(\"Particle \" << i++ << \" \" <<  mit->first->getCoordinates() << \" is affected to \" << mit->second.size() << \" nodes\" << \" weight= \" << w);\n\t\t}\n\t}\n}\n\nvoid ParticleToNodeHandler::printLKMC() {\n\tLOWMSG(_syncLKMC.size() << \" LKMC::LatticeAtom in ParticleToNodeHandler:\");\n\n\tif (!_syncLKMC.empty()) {\n\t\tunsigned i = 0;\n\n\t\tfor (std::map<LKMC::LatticeAtom *, std::set<MeshNode *> >::iterator mit = _syncLKMC.begin(); mit != _syncLKMC.end(); ++mit) {\n\t\t\tdouble w = 0.;\n\t\t\tfor (std::set<MeshNode *>::iterator sit = mit->second.begin(); sit != mit->second.end(); ++sit) {\n\t\t\t\tstd::map<LKMC::LatticeAtom *, double>::iterator mit2 = (*sit)->_mLA.find(mit->first);\n\t\t\t\tif (mit2 != (*sit)->_mLA.end())\n\t\t\t\t\tw += mit2->second;\n\t\t\t\telse\n\t\t\t\t\tLOWMSG(\"Got a null value!\");\n\t\t\t}\n\t\t\t\tLOWMSG(\"LKMC::LaticeAtom \" << ++i << \" \" <<  mit->first->getCoordinates() << \" is affected to \" << mit->second.size() << \" nodes\" << \" weight= \" << w);\n\t\t}\n\t}\n}\n", "meta": {"hexsha": "d728ea7304db882c47a782d164646923d80c4a39", "size": 11531, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/electrostatics/ParticleToNodeHandler.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/electrostatics/ParticleToNodeHandler.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/electrostatics/ParticleToNodeHandler.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": 32.5734463277, "max_line_length": 155, "alphanum_fraction": 0.6068857861, "num_tokens": 4174, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6893056040203135, "lm_q2_score": 0.45326184801538616, "lm_q1q2_score": 0.3124359319256093}}
{"text": "#include \"neal8_algorithm.h\"\n\n#include <Eigen/Dense>\n#include <memory>\n#include <stan/math/prim/fun.hpp>\n\n#include \"algorithm_id.pb.h\"\n#include \"algorithm_state.pb.h\"\n#include \"hierarchy_id.pb.h\"\n#include \"mixing_id.pb.h\"\n#include \"neal2_algorithm.h\"\n#include \"src/algorithms/marginal_algorithm.h\"\n#include \"src/hierarchies/base_hierarchy.h\"\n#include \"src/utils/distributions.h\"\n\nvoid Neal8Algorithm::read_params_from_proto(\n    const bayesmix::AlgorithmParams &params) {\n  // Set number of auxiliary blocks in addition to regular parameters\n  BaseAlgorithm::read_params_from_proto(params);\n  n_aux = params.neal8_n_aux();\n}\n\nvoid Neal8Algorithm::initialize() {\n  MarginalAlgorithm::initialize();\n  // Create correct amount of auxiliary blocks\n  aux_unique_values.clear();\n  for (size_t i = 0; i < n_aux; i++) {\n    aux_unique_values.push_back(unique_values[0]->clone());\n  }\n}\n\nvoid Neal8Algorithm::print_startup_message() const {\n  std::string msg = \"Running Neal8 algorithm (m=\" + std::to_string(n_aux) +\n                    \" aux. blocks) with \" +\n                    bayesmix::HierarchyId_Name(unique_values[0]->get_id()) +\n                    \" hierarchies, \" +\n                    bayesmix::MixingId_Name(mixing->get_id()) + \" mixing...\";\n  std::cout << msg << std::endl;\n}\n\nvoid Neal8Algorithm::sample_allocations() {\n  // Initialize relevant values\n  unsigned int n_data = data.rows();\n  auto &rng = bayesmix::Rng::Instance().get();\n\n  // Loop over data points\n  for (size_t i = 0; i < n_data; i++) {\n    bool singleton = (unique_values[allocations[i]]->get_card() <= 1);\n    unsigned int c_old = allocations[i];\n\n    if (singleton) {\n      // Save unique value in the first auxiliary block\n      bayesmix::AlgorithmState::ClusterState curr_val;\n      unique_values[allocations[i]]->write_state_to_proto(&curr_val);\n      aux_unique_values[0]->set_state_from_proto(curr_val);\n      // Remove datum from cluster\n      remove_singleton(c_old);\n    } else {\n      unique_values[c_old]->remove_datum(\n          i, data.row(i), update_hierarchy_params(), hier_covariates.row(i));\n    }\n\n    unsigned int n_clust = unique_values.size();\n    // Draw the unique values in the auxiliary blocks from their prior\n    for (size_t j = singleton; j < n_aux; j++) {\n      aux_unique_values[j]->sample_prior();\n    }\n    // Compute probabilities of clusters in log-space\n    Eigen::VectorXd logprobas =\n        get_cluster_prior_mass(i) + get_cluster_lpdf(i);\n    // Draw a NEW value for datum allocation\n    unsigned int c_new =\n        bayesmix::categorical_rng(stan::math::softmax(logprobas), rng, 0);\n\n    if (c_new >= n_clust) {\n      // datum moves to a new cluster\n      // Copy one of the auxiliary block as the new cluster\n      std::shared_ptr<AbstractHierarchy> hier_new =\n          aux_unique_values[c_new - n_clust]->clone();\n      unique_values.push_back(hier_new);\n      allocations[i] = n_clust;\n      unique_values[n_clust]->add_datum(\n          i, data.row(i), update_hierarchy_params(), hier_covariates.row(i));\n    } else {\n      allocations[i] = c_new;\n      unique_values[c_new]->add_datum(\n          i, data.row(i), update_hierarchy_params(), hier_covariates.row(i));\n    }\n  }\n}\n\nEigen::VectorXd Neal8Algorithm::lpdf_marginal_component(\n    std::shared_ptr<AbstractHierarchy> hier, const Eigen::MatrixXd &grid,\n    const Eigen::RowVectorXd &covariate) const {\n  unsigned int n_grid = grid.rows();\n  Eigen::VectorXd lpdf_(n_grid);\n  Eigen::MatrixXd lpdf_temp(n_grid, n_aux);\n  for (size_t i = 0; i < n_aux; i++) {\n    hier->sample_prior();\n    lpdf_temp.col(i) = hier->like_lpdf_grid(grid, covariate);\n  }\n  for (size_t i = 0; i < n_grid; i++) {\n    lpdf_(i) = stan::math::log_sum_exp(lpdf_temp.row(i));\n  }\n  return lpdf_.array() - log(n_aux);\n}\n\nEigen::VectorXd Neal8Algorithm::get_cluster_prior_mass(\n    const unsigned int data_idx) const {\n  unsigned int n_data = data.rows();\n  unsigned int n_clust = unique_values.size();\n  Eigen::VectorXd logprior(n_clust + n_aux);\n  for (size_t j = 0; j < n_clust; j++) {\n    // Probability of being assigned to an already existing cluster\n    logprior(j) = mixing->get_mass_existing_cluster(\n        n_data - 1, n_clust, true, true, unique_values[j],\n        mix_covariates.row(data_idx));\n  }\n  // Further update with marginal components\n  for (size_t j = 0; j < n_aux; j++) {\n    logprior(n_clust + j) = mixing->get_mass_new_cluster(\n        n_data - 1, n_clust, true, true, mix_covariates.row(data_idx));\n  }\n  return logprior;\n}\n\nEigen::VectorXd Neal8Algorithm::get_cluster_lpdf(\n    const unsigned int data_idx) const {\n  unsigned int n_data = data.rows();\n  unsigned int n_clust = unique_values.size();\n  Eigen::VectorXd loglpdf(n_clust + n_aux);\n  for (size_t j = 0; j < n_clust; j++) {\n    // Probability of being assigned to an already existing cluster\n    loglpdf(j) = unique_values[j]->get_like_lpdf(\n        data.row(data_idx), hier_covariates.row(data_idx));\n  }\n  for (size_t j = 0; j < n_aux; j++) {\n    // Probability of being assigned to a newly created cluster\n    loglpdf(n_clust + j) =\n        aux_unique_values[j]->get_like_lpdf(data.row(data_idx),\n                                            hier_covariates.row(data_idx)) -\n        log(n_aux);\n  }\n  return loglpdf;\n}\n", "meta": {"hexsha": "0fca14a8e86df6c072daf20ad41fa8172a78991d", "size": 5251, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/algorithms/neal8_algorithm.cc", "max_stars_repo_name": "vnardi/bayesmix", "max_stars_repo_head_hexsha": "6b87912f52983bdfb18acc743f2b2e0a54cb7016", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_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/neal8_algorithm.cc", "max_issues_repo_name": "vnardi/bayesmix", "max_issues_repo_head_hexsha": "6b87912f52983bdfb18acc743f2b2e0a54cb7016", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/algorithms/neal8_algorithm.cc", "max_forks_repo_name": "vnardi/bayesmix", "max_forks_repo_head_hexsha": "6b87912f52983bdfb18acc743f2b2e0a54cb7016", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-02-11T09:03:46.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-11T09:03:46.000Z", "avg_line_length": 35.9657534247, "max_line_length": 77, "alphanum_fraction": 0.6693963055, "num_tokens": 1368, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6297746213017459, "lm_q2_score": 0.49609382947091946, "lm_q1q2_score": 0.3124273035851812}}
{"text": "#include <ThermalAnalysis/LinearCombination.hpp>\n#include <boost/program_options.hpp>\n#include <boost/lexical_cast.hpp>\n#include <boost/filesystem.hpp>\n#include <boost/algorithm/string.hpp>\n#include <libField/HDF5.hpp>\n#include <gputils/io.hpp>\n#include <libArrhenius/Arrhenius.hpp>\n\n#include <iostream>\n#include <fstream>\n#include <vector>\n#include <algorithm>\n\nnamespace po = boost::program_options;\n\nField<double,1> read_profile(const std::string& filename)\n{\n  Field<double, 1> F;\n  GP2DData data;\n  ReadGPASCII2DDataFile(filename, data);\n\n  F.reset(data.x.size());\n  for(int i = 0; i < F.size(); ++i)\n  {\n    F.getAxis(0)[i] = data.x[i];\n    F(i) = data.f[i];\n  }\n\n  return F;\n}\n\nint main(int argc, const char** argv)\n{\n  // define command line options\n  po::options_description po_opts(\"Options\");\n  po_opts.add_options()(\"help,h\", \"print help message.\")(\n      \"verbose,v\", po::value<int>()->implicit_value(0), \"verbose level.\")\n    (\"Ea\", po::value<double>()->default_value(6.28e5), \"Activation energy [J/mol].\")\n    (\"A\",  po::value<double>()->default_value(3.1e99), \"Frequency factor [1/s].\")\n    (\"temperature-bias\",  po::value<double>()->default_value(0.0), \"A temperature offset that will be added to the temperature history to convert it to absolute temperature.\")\n    (\"exposure\",  po::value<double>()->default_value(1.0), \"The exposure that gave the temperature history. I.e., if the temperature history corresponds to a 2.5 W exposure, then computed damage threshold scaling factors will be multiplied by 2.5 and the threshold values will correspond to power.\")\n    (\"taus\",  po::value<string>(), \"Directly specify the exposure durations to run (as a comma separated list) instead of computing them [s].\")\n    (\"tau-min\",  po::value<double>()->default_value(10e-6), \"The minimum exposure duration to compute the damage threshold for [s].\")\n    (\"tau-max\",  po::value<double>(), \"The maximum exposure duration to compute the damage threshold for. The default is to use the entire exposure, but this may not be accurate if the cool down period is important [s].\")\n    (\"tau-reduction-factor\",  po::value<double>()->default_value(2), \"The reduction factor between consecutive exposure duration. I.e., a reduction factor of 2 would cut the exposure duration in half each time.\")\n    (\"dt\",  po::value<double>()->default_value(10e-6), \"Time resolution to use for generated temperature histories.\")\n    (\"write-profiles\", \"Write damage threshold profiles.\")\n    ;\n\n  // now define our arguments.\n  po::options_description po_args(\"Arguments\");\n  po_args.add_options()\n    (\"thermal-profiles\"  , po::value<std::vector<std::string>>()->composing(), \"Text files containing thermal profiles. Temperature should be expressed in Kelvin.\")\n    ;\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  // po_opts\n  po::options_description all_options(\"Options and Arguments\");\n  all_options.add(po_opts).add(po_args);\n\n  // tell boost how to translate positional options to named options\n  po::positional_options_description args;\n  args.add(\"thermal-profiles\", -1);\n\n  po::variables_map vm;\n  po::store(po::command_line_parser(argc, argv)\n      .options(all_options)\n      .positional(args)\n      .run(),\n      vm);\n  po::notify(vm);\n\n  if (argc == 1 || vm.count(\"help\")) {\n    std::cout << R\"EOL(\n    A small utility to quickly compute the damage threshold vs. exposure duration from a single temperature history computed from a long exposure.\n\n    For the linear heat equation, the temperature rise resulting from a short exposure can be computed from the temperature rise resulting from a long exposure by\n    linear combination. Even for the Penne's bioheat equation, the non-linear blood perfusion term has a small effect on the temeprature rise during an exposure, and\n    linearity can be assumed.\n\n    To run the tool, simply pass a file containing the temperature history (plain text file with time in the first column and temperature in the second column).\n    By default, the Welch-Polhamus Arrhenius coefficients will be used, but these can be set wit the --Ea and --A options. For example, so use the Henruques\n    coefficients (used fo skin), run\n\n    > ./thermal-damage-trender --A 3.1e98 --Ea 6.27e5 ./Tvst.txt\n\n    This will start printing out the damage threshold scaling factor as a function of exposure duration.\n\n\n)EOL\";\n\n    std::cout << po_opts << std::endl;\n    return 0;\n  }\n\n  if(vm[\"tau-reduction-factor\"].as<double>() <= 1)\n  {\n    std::cerr << \"Error: The tau reduction factor must be greater than 1.\" << std::endl;\n    return 1;\n  }\n\n\n  for( auto file : vm[\"thermal-profiles\"].as<std::vector<std::string>>() )\n  {\n    if( !boost::filesystem::exists(file) )\n    {\n      std::cerr << file << \" does not appear to exists. Skipping\" << std::endl;\n      continue;\n    }\n\n    Field<double,1> Tvst = read_profile(file);\n    if(Tvst.size() < 10)\n    {\n      std::cerr << \"Thermal profile has less than 10 data points. Cannot make any reasonable predictions about threshold trends... Skipping.\" << std::endl;\n      continue;\n    }\n\n\n    Tvst += vm[\"temperature-bias\"].as<double>();\n    auto T0 = Tvst[0];\n    auto tmin = Tvst.getCoord(0);\n    auto tmax = Tvst.getCoord(Tvst.size()-1);\n\n    Tvst -= T0;\n\n    // calculate how many\n    std::vector<double> taus;\n\n    if( vm.count(\"taus\") > 0 )\n    {\n      std::vector<std::string> toks;\n      boost::split(toks, vm[\"taus\"].as<std::string>(),boost::is_any_of(\",\"),boost::token_compress_on);\n      for( auto& tok : toks )\n      {\n        taus.push_back( boost::lexical_cast<double>(tok));\n      }\n\n    }\n    else\n    {\n      taus.push_back(tmax-tmin);\n      if( vm.count(\"tau-max\") > 0 )\n      {\n        taus[0] = vm[\"tau-max\"].as<double>();\n      }\n      while( taus[taus.size()-1] > vm[\"tau-min\"].as<double>() )\n      {\n        taus.push_back(taus[taus.size()-1]/vm[\"tau-reduction-factor\"].as<double>());\n      }\n    }\n\n    double dt = 10e-6;\n    int N = tmax/dt;\n    libArrhenius::ThresholdCalculator< libArrhenius::ArrheniusIntegral<double> > calc(vm[\"A\"].as<double>(),vm[\"Ea\"].as<double>());\n    for( auto tau : taus)\n    {\n      Field<double,1> Tvst2(N);\n      Tvst2.setCoordinateSystem( Uniform(tmin,tmax) );\n      LinearCombination<_1D::MonotonicInterpolator<double>> tempBuilder;\n\n      tempBuilder.add(Tvst, 0, 1.);\n      tempBuilder.add(Tvst, tau, -1.);\n      tempBuilder.build(Tvst2);\n\n      Tvst2 += T0;\n\n      double threshold = calc(Tvst2.size(), Tvst2.getAxis(0).data(),Tvst2.data() );\n      std::cout << tau << \" \" << threshold * vm[\"exposure\"].as<double>() << std::endl;\n\n      if(vm.count(\"write-profiles\"))\n      {\n        std::string ofile = file+\"-\"+boost::lexical_cast<std::string>(tau)+\"-threshold\";\n        std::ofstream out(ofile.c_str());\n        Tvst2 -= T0;\n        Tvst2 *= threshold;\n        Tvst2 += T0;\n        out << Tvst2;\n      }\n\n\n    }\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n  }\n\n\n  return 0;\n}\n", "meta": {"hexsha": "427f04024864a16d50e8d273b7dab12aa8e3f5aa", "size": 7021, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "applications/thermal-damage-trender.cpp", "max_stars_repo_name": "CD3/ThermalAnalysis", "max_stars_repo_head_hexsha": "4e268d697a8b7140a2e01d48d49b995c7b58a248", "max_stars_repo_licenses": ["MIT"], "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/thermal-damage-trender.cpp", "max_issues_repo_name": "CD3/ThermalAnalysis", "max_issues_repo_head_hexsha": "4e268d697a8b7140a2e01d48d49b995c7b58a248", "max_issues_repo_licenses": ["MIT"], "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/thermal-damage-trender.cpp", "max_forks_repo_name": "CD3/ThermalAnalysis", "max_forks_repo_head_hexsha": "4e268d697a8b7140a2e01d48d49b995c7b58a248", "max_forks_repo_licenses": ["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.4333333333, "max_line_length": 299, "alphanum_fraction": 0.6593077909, "num_tokens": 1836, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6297746213017459, "lm_q2_score": 0.49609382947091946, "lm_q1q2_score": 0.3124273035851812}}
{"text": "/*\n  Copyright 2010 Larry Gritz and the other authors and contributors.\n  All Rights Reserved.\n\n  Redistribution and use in source and binary forms, with or without\n  modification, are permitted provided that the following conditions are\n  met:\n  * Redistributions of source code must retain the above copyright\n    notice, this list of conditions and the following disclaimer.\n  * Redistributions in binary form must reproduce the above copyright\n    notice, this list of conditions and the following disclaimer in the\n    documentation and/or other materials provided with the distribution.\n  * Neither the name of the software's owners nor the names of its\n    contributors may be used to endorse or promote products derived from\n    this software without specific prior written permission.\n  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n  \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n  A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n  OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n  SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n  LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n  DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n  THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n  (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n  OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n  (This is the Modified BSD License)\n*/\n\n#include <cmath>\n#include <vector>\n#include <string>\n\n#include <boost/algorithm/string.hpp>\nusing boost::algorithm::iequals;\n\n#include \"colortransfer.h\"\n\nOIIO_NAMESPACE_ENTER\n{\n\nbool\nColorTransfer::set (std::string name_, float param)\n{\n    return false;\n}\n\nbool\nColorTransfer::get (std::string name_, float &param)\n{\n    return false;\n}\n\n\nnamespace {  // anonymous\n\n\n/// Null (pass-thru) transfer function\n///\nclass ColorTransfer_null : public ColorTransfer {\npublic:\n    ColorTransfer_null () : ColorTransfer(\"null\") { };\n    ~ColorTransfer_null (void) { };\n    float operator() (float x) { return x; }\n};\n\n\n\n/// Gamma transfer function\n///\nclass ColorTransfer_gamma : public ColorTransfer {\npublic:\n    ColorTransfer_gamma (float gamma=2.2f, float gain=1.0f) \n        : ColorTransfer(\"gamma\"), m_gamma(gamma), m_gain(gain)\n    {\n        add_paramater (\"gamma\");\n        add_paramater (\"gain\");\n    };\n    \n    ~ColorTransfer_gamma (void) { };\n    \n    bool set (std::string name, float param) {\n        if (iequals (name, \"gamma\"))\n            m_gamma = param;\n        else if (iequals (name, \"gain\"))\n            m_gain = param;\n        else return false;\n        return true;\n    };\n    \n    bool get (std::string name, float &param) {\n        if (iequals (name, \"gamma\"))\n            param = m_gamma;\n        else if (iequals (name, \"gain\"))\n            param = m_gain;\n        else return false;\n        return true;\n    };\n    \n    float operator() (float x) {\n        if (x < 0.0f)\n            return m_gain * x;\n        return std::pow (m_gain * x, m_gamma);\n    };\n    \nprivate:\n    float m_gamma;\n    float m_gain;\n};\n\n\n\n/// sRGB transfer function which is a widely used computer monitor standard\n///    http://en.wikipedia.org/wiki/SRGB\nclass ColorTransfer_linear_to_sRGB : public ColorTransfer {\npublic:\n    ColorTransfer_linear_to_sRGB () : ColorTransfer(\"linear_to_sRGB\") { };\n    ~ColorTransfer_linear_to_sRGB (void) { };\n    \n    float operator() (float x) {\n        if (x < 0.0f)\n            return 0.0f;\n        return (x <= 0.0031308f) ? (12.92f * x)\n                                 : (1.055f * std::pow (x, 1.f/2.4f) - 0.055f);\n    }\n};\n\n\n\n/// sRGB transfer function which is a widely used computer monitor standard\n///    http://en.wikipedia.org/wiki/SRGB\nclass ColorTransfer_sRGB_to_linear : public ColorTransfer {\npublic:\n    ColorTransfer_sRGB_to_linear () : ColorTransfer(\"sRGB_to_linear\") { };\n    ~ColorTransfer_sRGB_to_linear (void) { };\n    \n    float operator() (float x) {\n        return (x <= 0.04045f) ? (x / 12.92f)\n                               : std::pow ((x + 0.055f) / 1.055f, 2.4f);\n    }\n};\n\n\n\n/// AdobeRGB transfer function\n///    http://en.wikipedia.org/wiki/Adobe_RGB\n///    http://www.adobe.com/digitalimag/pdfs/AdobeRGB1998.pdf\nclass ColorTransfer_AdobeRGB_to_linear : public ColorTransfer {\n    \npublic:\n    ColorTransfer_AdobeRGB_to_linear () : ColorTransfer(\"AdobeRGB_to_linear\") {}\n    ~ColorTransfer_AdobeRGB_to_linear (void) { };\n    \n    float operator() (float x) {\n        if (x < 0.f)\n            return 0.f;\n        return std::pow (x, 2.f + (51.f / 256.f));\n    }\n};\n\n\n\nclass ColorTransfer_linear_to_AdobeRGB : public ColorTransfer {\n    \npublic:\n    ColorTransfer_linear_to_AdobeRGB () : ColorTransfer(\"linear_to_AdobeRGB\") {}\n    ~ColorTransfer_linear_to_AdobeRGB (void) { }\n    \n    float operator() (float x) {\n        if (x < 0.f)\n            return 0.f;\n        return std::pow (x, 1.f / (2.f + (51.f / 256.f)));\n    }\n};\n\n\n\n/// Rec709 transfer function which is a HDTV standard\n///    http://en.wikipedia.org/wiki/Rec._709\nclass ColorTransfer_Rec709_to_linear : public ColorTransfer {\npublic:\n    ColorTransfer_Rec709_to_linear () : ColorTransfer (\"Rec709_to_linear\") { };\n    ~ColorTransfer_Rec709_to_linear (void) { };\n    \n    float operator() (float x) {\n        if (x < 0.f)\n            return 0.f;\n        return (x <= 0.081f ? x / 4.5f : std::pow ((x + 0.099f) / 1.099f, 1.0f / 0.45f));\n    };\n};\n\n\n\nclass ColorTransfer_linear_to_Rec709 : public ColorTransfer {\npublic:\n    ColorTransfer_linear_to_Rec709 () : ColorTransfer (\"linear_to_Rec709\") { };\n    ~ColorTransfer_linear_to_Rec709 (void) { };\n    \n    float operator() (float x) {\n        if (x < 0.f)\n            return 0.f;\n        return (x <= 0.018f) ? x * 4.5f : (std::pow (x, 0.45f) * 1.099f) - 0.099f;\n    }\n};\n\n\n\n\nstatic void\ncompute_kodak_coeff (float refBlack, float refWhite,\n                     float dispGamma, float negGamma,\n                     float &black, float &white, float &gamma, float &gain,\n                     float &offset)\n{\n    // reference black code values below 0 are not allowed\n    black = refBlack;\n    if (black < 0.f) black = 0.f;\n        \n    // reference white code values above 1023 are not allowed, and must be\n    // equal or above reference black\n    white = refWhite;\n    if (white > 1023.f)\n        white = 1023.f;\n    else if (white < black)\n        white = black;\n        \n    // compute coefficients\n    gamma = 0.002f / negGamma * dispGamma / 1.7f;\n    gain = 1.f / (1.f - std::pow(10.f, (black - white) * gamma));\n    offset = gain - 1.f;\n    \n    // convert 10bit code values to float\n    black /= 1023.f;\n    white /= 1023.f;\n    gamma *= 1023.f;\n}\n\n\n\n/// Kodak Log transfer function which is used on Kodak 10bit log data\n///\n/// @todo cache results into a look up table with enough detail for\n/// 10bits as this function will be slightly slow at the moment.\n///\n/// @note the soft clip is not implemented as it makes the transfer\n/// function non-reversible. This parameter was designed to help display\n/// high code values on a CRT monitor. Having a non-reversible transfer\n/// function isn't so good for an image processing pipeline.\nclass ColorTransfer_KodakLog_to_linear : public ColorTransfer {\npublic:\n    ColorTransfer_KodakLog_to_linear ()\n        : ColorTransfer(\"_KodakLog_to_linear\"), m_refBlack(95.f),\n          m_refWhite(685.f), m_dispGamma(1.7f), m_negGamma(0.6f)\n    {\n        add_paramater (\"refBlack\");\n        add_paramater (\"refWhite\");\n        add_paramater (\"dispGamma\");\n        add_paramater (\"negGamma\");\n        compute_kodak_coeff (m_refBlack, m_refWhite, m_dispGamma, m_negGamma,\n                                     m_black, m_white, m_gamma, m_gain, m_offset);\n    };\n    \n    ~ColorTransfer_KodakLog_to_linear (void) { };\n    \n    bool set (std::string name, float param) {\n        if (iequals (name, \"refBlack\"))  m_refBlack = param;\n        else if (iequals (name, \"refWhite\"))  m_refWhite = param;\n        else if (iequals (name, \"dispGamma\")) m_dispGamma = param;\n        else if (iequals (name, \"negGamma\"))  m_negGamma = param;\n        else return false;\n        // recompute coefficients\n        compute_kodak_coeff (m_refBlack, m_refWhite, m_dispGamma, m_negGamma,\n                             m_black, m_white, m_gamma, m_gain, m_offset);\n        return true;\n    }\n    \n    bool get (std::string name, float &param) {\n        if (iequals (name, \"refBlack\"))  param = m_refBlack;\n        else if (iequals (name, \"refWhite\"))  param = m_refWhite;\n        else if (iequals (name, \"dispGamma\")) param = m_dispGamma;\n        else if (iequals (name, \"negGamma\"))  param = m_negGamma;\n        else return false;\n        return true;\n    }\n    \n    float operator() (float x) {\n        return (x < (m_black + 1e-06)) ? 0.f :\n            std::pow (10.f, ((x - m_white) * m_gamma)) * m_gain - m_offset;\n    }\n    \nprivate:\n    // transfer paramaters\n    float m_refBlack;\n    float m_refWhite;\n    float m_dispGamma;\n    float m_negGamma;\n    \n    // coefficents\n    float m_black;\n    float m_white;\n    float m_gamma;\n    float m_gain;\n    float m_offset;\n};\n\n\n\nclass ColorTransfer_linear_to_KodakLog : public ColorTransfer {\npublic:\n    ColorTransfer_linear_to_KodakLog () \n        : ColorTransfer(\"linear_to_KodakLog\"), m_refBlack(95.f),\n          m_refWhite(685.f), m_dispGamma(1.7f), m_negGamma(0.6f)\n    {\n        add_paramater (\"refBlack\");\n        add_paramater (\"refWhite\");\n        add_paramater (\"dispGamma\");\n        add_paramater (\"negGamma\");\n        compute_kodak_coeff (m_refBlack, m_refWhite, m_dispGamma, m_negGamma,\n                                     m_black, m_white, m_gamma, m_gain, m_offset);\n    }\n    \n    ~ColorTransfer_linear_to_KodakLog (void) { };\n    \n    bool set (std::string name, float param) {\n        if (iequals (name, \"refBlack\"))  m_refBlack = param;\n        else if (iequals (name, \"refWhite\"))  m_refWhite = param;\n        else if (iequals (name, \"dispGamma\")) m_dispGamma = param;\n        else if (iequals (name, \"negGamma\"))  m_negGamma = param;\n        else return false;\n        // recompute coefficients\n        compute_kodak_coeff (m_refBlack, m_refWhite, m_dispGamma, m_negGamma,\n                             m_black, m_white, m_gamma, m_gain, m_offset);\n        return true;\n    }\n    \n    bool get (std::string name, float &param) {\n        if (iequals (name, \"refBlack\"))  param = m_refBlack;\n        else if (iequals (name, \"refWhite\"))  param = m_refWhite;\n        else if (iequals (name, \"dispGamma\")) param = m_dispGamma;\n        else if (iequals (name, \"negGamma\"))  param = m_negGamma;\n        else return false;\n        return true;\n    }\n    \n    float operator() (float x) {\n        if (x < 1e-10)\n            x = 1e-10;\n        x = std::log10 ((x + m_offset) / m_gain) / m_gamma + m_white;\n        return (x < m_black) ? 0.f : x;\n    }\n    \nprivate:\n    // transfer paramaters\n    float m_refBlack;\n    float m_refWhite;\n    float m_dispGamma;\n    float m_negGamma;\n    \n    // coefficents\n    float m_black;\n    float m_white;\n    float m_gamma;\n    float m_gain;\n    float m_offset;\n};\n\n\n};  // anonymous namespace\n\n\n\n// ColorTransfer::create is a static method that, given a transfer function\n// name, returns an allocated and instantiated transfer function of the correct\n// implementation.\n// If the name is not recongnoized, return NULL.\nColorTransfer *\nColorTransfer::create (const std::string &name)\n{\n    if (iequals (name, \"linear_to_linear\") || iequals (name, \"null\"))\n        return new ColorTransfer_null ();\n    if (iequals (name, \"Gamma\"))\n        return new ColorTransfer_gamma ();\n    if (iequals (name, \"linear_to_sRGB\"))\n        return new ColorTransfer_linear_to_sRGB ();\n    if (iequals (name, \"sRGB_to_linear\"))\n        return new ColorTransfer_sRGB_to_linear ();\n    if (iequals (name, \"linear_to_AdobeRGB\"))\n        return new ColorTransfer_linear_to_AdobeRGB ();\n    if (iequals (name, \"AdobeRGB_to_linear\"))\n        return new ColorTransfer_AdobeRGB_to_linear ();\n    if (iequals (name, \"linear_to_Rec709\"))\n        return new ColorTransfer_linear_to_Rec709 ();\n    if (iequals (name, \"Rec709_to_linear\"))\n        return new ColorTransfer_Rec709_to_linear ();\n    if (iequals (name, \"linear_to_KodakLog\"))\n        return new ColorTransfer_linear_to_KodakLog ();\n    if (iequals (name, \"KodakLog_to_linear\"))\n        return new ColorTransfer_KodakLog_to_linear ();\n    return NULL;\n}\n\n\n}\nOIIO_NAMESPACE_EXIT\n", "meta": {"hexsha": "299a7cd6bae76407465e38af3d3fda5ef212e237", "size": 12626, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/libutil/colortransfer.cpp", "max_stars_repo_name": "ndubey/oiio", "max_stars_repo_head_hexsha": "fb00e178be048c31f478076977d17434c310472c", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2016-09-05T01:16:09.000Z", "max_stars_repo_stars_event_max_datetime": "2016-09-05T01:16:09.000Z", "max_issues_repo_path": "src/libutil/colortransfer.cpp", "max_issues_repo_name": "Alexander-Murashko/oiio", "max_issues_repo_head_hexsha": "2cb95cf674e6cb085eb14614c428535ed2b8989b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/libutil/colortransfer.cpp", "max_forks_repo_name": "Alexander-Murashko/oiio", "max_forks_repo_head_hexsha": "2cb95cf674e6cb085eb14614c428535ed2b8989b", "max_forks_repo_licenses": ["BSD-3-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.0985221675, "max_line_length": 89, "alphanum_fraction": 0.6363060352, "num_tokens": 3312, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6297746074044134, "lm_q2_score": 0.4960938294709195, "lm_q1q2_score": 0.3124272966908003}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\r\n\r\n// Copyright (c) 2007-2012 Barend Gehrels, Amsterdam, the Netherlands.\r\n// Copyright (c) 2008-2012 Bruno Lalande, Paris, France.\r\n// Copyright (c) 2009-2012 Mateusz Loskot, London, UK.\r\n\r\n// Parts of Boost.Geometry are redesigned from Geodan's Geographic Library\r\n// (geolib/GGL), copyright (c) 1995-2010 Geodan, Amsterdam, the Netherlands.\r\n\r\n// Use, modification and distribution is subject to the Boost Software License,\r\n// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\r\n// http://www.boost.org/LICENSE_1_0.txt)\r\n\r\n#ifndef BOOST_GEOMETRY_ALGORITHMS_CONVEX_HULL_HPP\r\n#define BOOST_GEOMETRY_ALGORITHMS_CONVEX_HULL_HPP\r\n\r\n#include <boost/array.hpp>\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/num_points.hpp>\r\n#include <boost/geometry/algorithms/detail/as_range.hpp>\r\n#include <boost/geometry/algorithms/detail/assign_box_corners.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 convex_hull\r\n{\r\n\r\ntemplate <order_selector Order>\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 Geometry, typename OutputIterator, typename Strategy>\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\nstruct hull_to_geometry\r\n{\r\n    template <typename Geometry, typename OutputGeometry, typename Strategy>\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::point_order<OutputGeometry>::value\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// Helper metafunction for default strategy retrieval\r\ntemplate <typename Geometry>\r\nstruct default_strategy\r\n    : strategy_convex_hull\r\n          <\r\n              Geometry,\r\n              typename point_type<Geometry>::type\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 Geometry,\r\n    typename Tag = typename tag<Geometry>::type\r\n>\r\nstruct convex_hull\r\n    : detail::convex_hull::hull_to_geometry\r\n{};\r\n\r\ntemplate <typename Box>\r\nstruct convex_hull<Box, box_tag>\r\n{\r\n    template <typename OutputGeometry, typename Strategy>\r\n    static inline void apply(Box const& box, OutputGeometry& out,\r\n            Strategy const& )\r\n    {\r\n        static bool const Close\r\n            = geometry::closure<OutputGeometry>::value == closed;\r\n        static bool const Reverse\r\n            = geometry::point_order<OutputGeometry>::value == counterclockwise;\r\n\r\n        // A hull for boxes is trivial. Any strategy is (currently) skipped.\r\n        boost::array<typename point_type<Box>::type, 4> range;\r\n        geometry::detail::assign_box_corners_oriented<Reverse>(box, range);\r\n        geometry::append(out, range);\r\n        if (Close)\r\n        {\r\n            geometry::append(out, *boost::begin(range));\r\n        }\r\n    }\r\n};\r\n\r\n\r\n\r\ntemplate <order_selector Order>\r\nstruct convex_hull_insert\r\n    : detail::convex_hull::hull_insert<Order>\r\n{};\r\n\r\n\r\n} // namespace dispatch\r\n#endif // DOXYGEN_NO_DISPATCH\r\n\r\n\r\ntemplate<typename Geometry, typename OutputGeometry, typename Strategy>\r\ninline void convex_hull(Geometry const& geometry,\r\n            OutputGeometry& out, Strategy const& strategy)\r\n{\r\n    concept::check_concepts_and_equal_dimensions\r\n        <\r\n            const Geometry,\r\n            OutputGeometry\r\n        >();\r\n\r\n    BOOST_CONCEPT_ASSERT( (geometry::concept::ConvexHullStrategy<Strategy>) );\r\n\r\n    if (geometry::num_points(geometry) == 0)\r\n    {\r\n        // Leave output empty\r\n        return;\r\n    }\r\n\r\n    dispatch::convex_hull<Geometry>::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 Geometry, typename OutputGeometry>\r\ninline void convex_hull(Geometry const& geometry,\r\n            OutputGeometry& hull)\r\n{\r\n    concept::check_concepts_and_equal_dimensions\r\n        <\r\n            const Geometry,\r\n            OutputGeometry\r\n        >();\r\n\r\n    typedef typename detail::convex_hull::default_strategy<Geometry>::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            geometry::point_order<Geometry>::value\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 detail::convex_hull::default_strategy<Geometry>::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": "29eef9fd664af85734d5b9d0d72bc0ab07fa01e9", "size": 7400, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "_thirdPartyLibs/include/boost/geometry/algorithms/convex_hull.hpp", "max_stars_repo_name": "kamarianakis/glGA-edu", "max_stars_repo_head_hexsha": "17f0b33c3ea8efcfa8be01d41343862ea4e6fae0", "max_stars_repo_licenses": ["BSD-4-Clause-UC"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2018-08-22T03:43:30.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-11T18:20:27.000Z", "max_issues_repo_path": "_thirdPartyLibs/include/boost/geometry/algorithms/convex_hull.hpp", "max_issues_repo_name": "kamarianakis/glGA-edu", "max_issues_repo_head_hexsha": "17f0b33c3ea8efcfa8be01d41343862ea4e6fae0", "max_issues_repo_licenses": ["BSD-4-Clause-UC"], "max_issues_count": 7.0, "max_issues_repo_issues_event_min_datetime": "2020-10-06T16:34:12.000Z", "max_issues_repo_issues_event_max_datetime": "2020-12-06T17:29:22.000Z", "max_forks_repo_path": "_thirdPartyLibs/include/boost/geometry/algorithms/convex_hull.hpp", "max_forks_repo_name": "kamarianakis/glGA-edu", "max_forks_repo_head_hexsha": "17f0b33c3ea8efcfa8be01d41343862ea4e6fae0", "max_forks_repo_licenses": ["BSD-4-Clause-UC"], "max_forks_count": 71.0, "max_forks_repo_forks_event_min_datetime": "2015-03-26T10:28:04.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-07T10:09:12.000Z", "avg_line_length": 29.6, "max_line_length": 90, "alphanum_fraction": 0.6854054054, "num_tokens": 1573, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5964331462646255, "lm_q2_score": 0.523420348936324, "lm_q1q2_score": 0.31218524553501986}}
{"text": "/**\n * Copyright Soramitsu Co., Ltd. All Rights Reserved.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n#include \"consensus/babe/impl/threshold_util.hpp\"\n\n#include <boost/range/adaptors.hpp>\n#include <boost/range/numeric.hpp>\n\nnamespace kagome::consensus {\n\n  Threshold calculateThreshold(const std::pair<uint64_t, uint64_t> &c_pair,\n                               const primitives::AuthorityList &authorities,\n                               primitives::AuthorityIndex authority_index) {\n    double c = double(c_pair.first) / c_pair.second;\n\n    using boost::adaptors::transformed;\n    double theta =\n        double(authorities[authority_index].weight)\n        / boost::accumulate(authorities | transformed([](auto &authority) {\n                              return authority.weight;\n                            }),\n                            0.);\n\n    using namespace boost::multiprecision;  // NOLINT\n    cpp_rational p_rat(1. - pow(1. - c, theta));\n    static const auto a = (uint256_t{1} << 128);\n    return Threshold{a * numerator(p_rat) / denominator(p_rat)};\n  }\n\n}  // namespace kagome::consensus\n", "meta": {"hexsha": "937b27c9c20ab0a57ab9ee63234fc72eac0d3166", "size": 1104, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "core/consensus/babe/impl/threshold_util.cpp", "max_stars_repo_name": "FlorianFranzen/kagome", "max_stars_repo_head_hexsha": "27ee11c78767e72f0ecd2c515c77bebc2ff5758d", "max_stars_repo_licenses": ["Apache-2.0"], "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/consensus/babe/impl/threshold_util.cpp", "max_issues_repo_name": "FlorianFranzen/kagome", "max_issues_repo_head_hexsha": "27ee11c78767e72f0ecd2c515c77bebc2ff5758d", "max_issues_repo_licenses": ["Apache-2.0"], "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/consensus/babe/impl/threshold_util.cpp", "max_forks_repo_name": "FlorianFranzen/kagome", "max_forks_repo_head_hexsha": "27ee11c78767e72f0ecd2c515c77bebc2ff5758d", "max_forks_repo_licenses": ["Apache-2.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.4545454545, "max_line_length": 76, "alphanum_fraction": 0.615942029, "num_tokens": 248, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6548947290421276, "lm_q2_score": 0.47657965106367595, "lm_q1q2_score": 0.3121095014503378}}
{"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 <cmath>\n#include <cstddef>\n#include <limits>\n#include <ostream>\n#include <pup.h>  // IWYU pragma: keep\n#include <type_traits>\n#include <unordered_map>\n#include <utility>  // for pair\n\n#include \"DataStructures/DataVector.hpp\"  // IWYU pragma: keep\n#include \"DataStructures/Index.hpp\"\n#include \"DataStructures/ModalVector.hpp\"  // IWYU pragma: keep\n#include \"DataStructures/Tags.hpp\"\n#include \"DataStructures/Tensor/Metafunctions.hpp\"  // IWYU pragma: keep\n#include \"DataStructures/Tensor/Tensor.hpp\"         // IWYU pragma: keep\n#include \"DataStructures/Variables.hpp\"             // IWYU pragma: keep\n#include \"Domain/Structure/Direction.hpp\"\n#include \"Domain/Structure/Element.hpp\"         // IWYU pragma: keep\n#include \"Domain/Structure/ElementId.hpp\"       // IWYU pragma: keep\n#include \"Domain/Structure/OrientationMap.hpp\"  // IWYU pragma: keep\n#include \"Domain/Structure/OrientationMapHelpers.hpp\"\n#include \"Domain/Tags.hpp\"  // IWYU pragma: keep\n#include \"NumericalAlgorithms/LinearOperators/CoefficientTransforms.hpp\"\n#include \"NumericalAlgorithms/Spectral/Mesh.hpp\"\n#include \"NumericalAlgorithms/Spectral/Spectral.hpp\"\n#include \"Options/Options.hpp\"\n#include \"Utilities/Algorithm.hpp\"\n#include \"Utilities/ErrorHandling/Error.hpp\"\n#include \"Utilities/Gsl.hpp\"\n#include \"Utilities/MakeArray.hpp\"\n#include \"Utilities/Math.hpp\"\n#include \"Utilities/TMPL.hpp\"\n\n// IWYU pragma: no_include <algorithm>\n// IWYU pragma: no_forward_declare Variables\n\n/// \\cond\nnamespace Limiters {\ntemplate <size_t VolumeDim, typename TagsToLimit>\nclass Krivodonova;\n}  // namespace Limiters\n/// \\endcond\n\nnamespace Limiters {\n/*!\n * \\ingroup LimitersGroup\n * \\brief An implementation of the Krivodonova limiter.\n *\n * The limiter is described in \\cite Krivodonova2007. The Krivodonova limiter\n * works by limiting the highest derivatives/modal coefficients using an\n * aggressive minmod approach, decreasing in derivative/modal coefficient order\n * until no more limiting is necessary. In 3d, the function being limited is\n * expanded as:\n *\n * \\f{align}{\n * u^{l,m,n}=\\sum_{i,j,k=0,0,0}^{N_i,N_j,N_k}c^{l,m,n}_{i,j,k}\n *  P_{i}(\\xi)P_{j}(\\eta)P_{k}(\\zeta)\n * \\f}\n *\n * where \\f$\\left\\{\\xi, \\eta, \\zeta\\right\\}\\f$ are the logical coordinates,\n * \\f$P_{i}\\f$ are the Legendre polynomials, the superscript \\f$\\{l,m,n\\}\\f$\n * represents the element indexed by \\f$l,m,n\\f$, and \\f$N_i,N_j\\f$ and\n * \\f$N_k\\f$ are the number of collocation points minus one in the\n * \\f$\\xi,\\eta,\\f$ and \\f$\\zeta\\f$ direction, respectively. The coefficients are\n * limited according to:\n *\n * \\f{align}{\n * \\tilde{c}^{l,m,n}_{i,j,k}=\\mathrm{minmod}\n *   &\\left(c_{i,j,k}^{l,m,n},\n *          \\alpha_i\\left(c^{l+1,m,n}_{i-1,j,k}-c^{l,m,n}_{i-1,j,k}\\right),\n *          \\alpha_i\\left(c^{l,m,n}_{i-1,j,k}-c^{l-1,m,n}_{i-1,j,k}\\right),\n *     \\right.\\notag \\\\\n *   &\\;\\;\\;\\;\n *          \\alpha_j\\left(c^{l,m+1,n}_{i,j-1,k}-c^{l,m,n}_{i,j-1,k}\\right),\n *          \\alpha_j\\left(c^{l,m,n}_{i,j-1,k}-c^{l,m-1,n}_{i,j-1,k}\\right),\n *     \\notag \\\\\n *   &\\;\\;\\;\\;\\left.\n *          \\alpha_k\\left(c^{l,m,n+1}_{i,j,k-1}-c^{l,m,n}_{i,j,k-1}\\right),\n *          \\alpha_k\\left(c^{l,m,n}_{i,j,k-1}-c^{l,m,n-1}_{i,j,k-1}\\right)\n *     \\right),\n * \\label{eq:krivodonova 3d minmod}\n * \\f}\n *\n * where \\f$\\mathrm{minmod}\\f$ is the minmod function defined as\n *\n * \\f{align}{\n *  \\mathrm{minmod}(a,b,c,\\ldots)=\n *  \\left\\{\n *  \\begin{array}{ll}\n *    \\mathrm{sgn}(a)\\min(\\lvert a\\rvert, \\lvert b\\rvert,\n *    \\lvert c\\rvert, \\ldots) & \\mathrm{if} \\;\n *    \\mathrm{sgn}(a)=\\mathrm{sgn}(b)=\\mathrm{sgn}(c)=\\mathrm{sgn}(\\ldots) \\\\\n *    0 & \\mathrm{otherwise}\n *  \\end{array}\\right.\n * \\f}\n *\n * Krivodonova \\cite Krivodonova2007 requires \\f$\\alpha_i\\f$ to be in the range\n *\n * \\f{align*}{\n * \\frac{1}{2(2i-1)}\\le \\alpha_i \\le 1\n * \\f}\n *\n * where the lower bound comes from finite differencing the coefficients between\n * neighbor elements when using Legendre polynomials (see \\cite Krivodonova2007\n * for details). Note that we normalize our Legendre polynomials by \\f$P_i(1) =\n * 1\\f$; this is the normalization \\cite Krivodonova2007 uses in 1D, (but not in\n * 2D), which is why our bounds on \\f$\\alpha_i\\f$ match Eq. 14 of\n * \\cite Krivodonova2007 (but not Eq. 23). We relax the lower bound:\n *\n * \\f{align*}{\n * 0 \\le \\alpha_i \\le 1\n * \\f}\n *\n * to allow different basis functions (e.g. Chebyshev polynomials) and to allow\n * the limiter to be more dissipative if necessary. The same \\f$\\alpha_i\\f$s are\n * used in all dimensions.\n *\n * \\note The only place where the specific choice of 1d basis\n * comes in is the lower bound for the \\f$\\alpha_i\\f$s, and so in general the\n * limiter can be applied to any 1d or tensor product of 1d basis functions.\n *\n * The limiting procedure must be applied from the highest derivatives to the\n * lowest, i.e. the highest coefficients to the lowest. Let us consider a 3d\n * element with \\f$N+1\\f$ coefficients in each dimension and denote the\n * coefficients as \\f$c_{i,j,k}\\f$. Then the limiting procedure starts at\n * \\f$c_{N,N,N}\\f$, followed by \\f$c_{N,N,N-1}\\f$, \\f$c_{N,N-1,N}\\f$, and\n * \\f$c_{N-1,N,N}\\f$. A detailed example is given below. Limiting is stopped if\n * all symmetric pairs of coefficients are left unchanged, i.e.\n * \\f$c_{i,j,k}=\\tilde{c}_{i,j,k}\\f$. By all symmetric coefficients we mean\n * that, for example, \\f$c_{N-i,N-j,N-k}\\f$, \\f$c_{N-j,N-i,N-k}\\f$,\n * \\f$c_{N-k,N-j,N-i}\\f$, \\f$c_{N-j,N-k,N-i}\\f$, \\f$c_{N-i,N-k,N-j}\\f$, and\n * \\f$c_{N-k,N-i,N-j}\\f$ are not limited. As a concrete example, consider a 3d\n * element with 3 collocation points per dimension. Each limited coefficient is\n * defined as (though only computed if needed):\n *\n * \\f{align*}{\n * \\tilde{c}^{l,m,n}_{2,2,2}=\\mathrm{minmod}\n *   &\\left(c_{2,2,2}^{l,m,n},\n *          \\alpha_2\\left(c^{l+1,m,n}_{1,2,2}-c^{l,m,n}_{1,2,2}\\right),\n *          \\alpha_2\\left(c^{l,m,n}_{1,2,2}-c^{l-1,m,n}_{1,2,2}\\right),\n *     \\right.\\\\\n *   &\\;\\;\\;\\;\n *          \\alpha_2\\left(c^{l,m+1,n}_{2,1,2}-c^{l,m,n}_{2,1,2}\\right),\n *          \\alpha_2\\left(c^{l,m,n}_{2,1,2}-c^{l,m-1,n}_{2,1,2}\\right),\\\\\n *   &\\;\\;\\;\\;\\left.\n *          \\alpha_2\\left(c^{l,m,n+1}_{2,2,1}-c^{l,m,n}_{2,2,1}\\right),\n *          \\alpha_2\\left(c^{l,m,n}_{2,2,1}-c^{l,m,n-1}_{2,2,1}\\right)\n *     \\right),\\\\\n * \\tilde{c}^{l,m,n}_{2,2,1}=\\mathrm{minmod}\n *   &\\left(c_{2,2,1}^{l,m,n},\n *          \\alpha_2\\left(c^{l+1,m,n}_{1,2,1}-c^{l,m,n}_{1,2,1}\\right),\n *          \\alpha_2\\left(c^{l,m,n}_{1,2,1}-c^{l-1,m,n}_{1,2,1}\\right),\n *     \\right.\\\\\n *   &\\;\\;\\;\\;\n *          \\alpha_2\\left(c^{l,m+1,n}_{2,1,1}-c^{l,m,n}_{2,1,1}\\right),\n *          \\alpha_2\\left(c^{l,m,n}_{2,1,1}-c^{l,m-1,n}_{2,1,1}\\right),\\\\\n *   &\\;\\;\\;\\;\\left.\n *          \\alpha_1\\left(c^{l,m,n+1}_{2,2,0}-c^{l,m,n}_{2,2,0}\\right),\n *          \\alpha_1\\left(c^{l,m,n}_{2,2,0}-c^{l,m,n-1}_{2,2,0}\\right)\n *     \\right),\\\\\n * \\tilde{c}^{l,m,n}_{2,1,2}=\\mathrm{minmod}\n *   &\\left(c_{2,1,2}^{l,m,n},\n *          \\alpha_2\\left(c^{l+1,m,n}_{1,1,2}-c^{l,m,n}_{1,1,2}\\right),\n *          \\alpha_2\\left(c^{l,m,n}_{1,1,2}-c^{l-1,m,n}_{1,1,2}\\right),\n *     \\right.\\\\\n *   &\\;\\;\\;\\;\n *          \\alpha_1\\left(c^{l,m+1,n}_{2,0,2}-c^{l,m,n}_{2,0,2}\\right),\n *          \\alpha_1\\left(c^{l,m,n}_{2,0,2}-c^{l,m-1,n}_{2,0,2}\\right),\\\\\n *   &\\;\\;\\;\\;\\left.\n *          \\alpha_2\\left(c^{l,m,n+1}_{2,1,1}-c^{l,m,n}_{2,1,1}\\right),\n *          \\alpha_2\\left(c^{l,m,n}_{2,1,1}-c^{l,m,n-1}_{2,1,1}\\right)\n *     \\right),\\\\\n * \\tilde{c}^{l,m,n}_{1,2,2}=\\mathrm{minmod}\n *   &\\left(c_{1,2,2}^{l,m,n},\n *          \\alpha_1\\left(c^{l+1,m,n}_{0,2,2}-c^{l,m,n}_{0,2,2}\\right),\n *          \\alpha_1\\left(c^{l,m,n}_{0,2,2}-c^{l-1,m,n}_{0,2,2}\\right),\n *     \\right.\\\\\n *   &\\;\\;\\;\\;\n *          \\alpha_2\\left(c^{l,m+1,n}_{1,1,2}-c^{l,m,n}_{1,1,2}\\right),\n *          \\alpha_2\\left(c^{l,m,n}_{1,1,2}-c^{l,m-1,n}_{1,1,2}\\right),\\\\\n *   &\\;\\;\\;\\;\\left.\n *          \\alpha_2\\left(c^{l,m,n+1}_{1,2,1}-c^{l,m,n}_{1,2,1}\\right),\n *          \\alpha_2\\left(c^{l,m,n}_{1,2,1}-c^{l,m,n-1}_{1,2,1}\\right)\n *     \\right),\\\\\n * \\tilde{c}^{l,m,n}_{2,2,0}=\\mathrm{minmod}\n *   &\\left(c_{2,2,0}^{l,m,n},\n *          \\alpha_2\\left(c^{l+1,m,n}_{1,2,0}-c^{l,m,n}_{1,2,0}\\right),\n *          \\alpha_2\\left(c^{l,m,n}_{1,2,0}-c^{l-1,m,n}_{1,2,0}\\right),\n *     \\right.\\\\\n *   &\\;\\;\\;\\;\\left.\n *          \\alpha_2\\left(c^{l,m+1,n}_{2,1,0}-c^{l,m,n}_{2,1,0}\\right),\n *          \\alpha_2\\left(c^{l,m,n}_{2,1,0}-c^{l,m-1,n}_{2,1,0}\\right)\n *     \\right),\\\\\n * \\tilde{c}^{l,m,n}_{2,0,2}=\\mathrm{minmod}\n *   &\\left(c_{2,0,2}^{l,m,n},\n *          \\alpha_2\\left(c^{l+1,m,n}_{1,0,2}-c^{l,m,n}_{1,0,2}\\right),\n *          \\alpha_2\\left(c^{l,m,n}_{1,0,2}-c^{l-1,m,n}_{1,0,2}\\right),\n *     \\right.\\\\\n *   &\\;\\;\\;\\;\\left.\n *          \\alpha_2\\left(c^{l,m,n+1}_{2,0,1}-c^{l,m,n}_{2,0,1}\\right),\n *          \\alpha_2\\left(c^{l,m,n}_{2,0,1}-c^{l,m,n-1}_{2,0,1}\\right)\n *     \\right),\\\\\n * \\tilde{c}^{l,m,n}_{0,2,2}=\\mathrm{minmod}\n *   &\\left(c_{0,2,2}^{l,m,n},\n *          \\alpha_2\\left(c^{l,m+1,n}_{0,1,2}-c^{l,m,n}_{0,1,2}\\right),\n *          \\alpha_2\\left(c^{l,m,n}_{0,1,2}-c^{l,m-1,n}_{0,1,2}\\right),\n *     \\right.\\\\\n *   &\\;\\;\\;\\;\\left.\n *          \\alpha_2\\left(c^{l,m,n+1}_{0,2,1}-c^{l,m,n}_{0,2,1}\\right),\n *          \\alpha_2\\left(c^{l,m,n}_{0,2,1}-c^{l,m,n-1}_{0,2,1}\\right)\n *     \\right),\\\\\n * \\tilde{c}^{l,m,n}_{2,1,1}=\\mathrm{minmod}\n *   &\\left(c_{2,1,1}^{l,m,n},\n *          \\alpha_2\\left(c^{l+1,m,n}_{1,1,1}-c^{l,m,n}_{1,1,1}\\right),\n *          \\alpha_2\\left(c^{l,m,n}_{1,1,1}-c^{l-1,m,n}_{1,1,1}\\right),\n *     \\right.\\\\\n *   &\\;\\;\\;\\;\n *          \\alpha_1\\left(c^{l,m+1,n}_{2,0,1}-c^{l,m,n}_{2,0,1}\\right),\n *          \\alpha_1\\left(c^{l,m,n}_{2,0,1}-c^{l,m-1,n}_{2,0,1}\\right),\\\\\n *   &\\;\\;\\;\\;\\left.\n *          \\alpha_1\\left(c^{l,m,n+1}_{2,1,0}-c^{l,m,n}_{2,1,0}\\right),\n *          \\alpha_1\\left(c^{l,m,n}_{2,1,0}-c^{l,m,n-1}_{2,1,0}\\right)\n *     \\right),\\\\\n * \\tilde{c}^{l,m,n}_{1,2,1}=\\mathrm{minmod}\n *   &\\left(c_{1,2,1}^{l,m,n},\n *          \\alpha_1\\left(c^{l+1,m,n}_{0,2,1}-c^{l,m,n}_{0,2,1}\\right),\n *          \\alpha_1\\left(c^{l,m,n}_{0,2,1}-c^{l-1,m,n}_{0,2,1}\\right),\n *     \\right.\\\\\n *   &\\;\\;\\;\\;\n *          \\alpha_2\\left(c^{l,m+1,n}_{1,1,1}-c^{l,m,n}_{1,1,1}\\right),\n *          \\alpha_2\\left(c^{l,m,n}_{1,1,1}-c^{l,m-1,n}_{1,1,1}\\right),\\\\\n *   &\\;\\;\\;\\;\\left.\n *          \\alpha_1\\left(c^{l,m,n+1}_{1,2,0}-c^{l,m,n}_{1,2,0}\\right),\n *          \\alpha_1\\left(c^{l,m,n}_{1,2,0}-c^{l,m,n-1}_{1,2,0}\\right)\n *     \\right),\\\\\n * \\tilde{c}^{l,m,n}_{1,1,2}=\\mathrm{minmod}\n *   &\\left(c_{1,1,2}^{l,m,n},\n *          \\alpha_1\\left(c^{l+1,m,n}_{0,1,2}-c^{l,m,n}_{0,1,2}\\right),\n *          \\alpha_1\\left(c^{l,m,n}_{0,1,2}-c^{l-1,m,n}_{0,1,2}\\right),\n *     \\right.\\\\\n *   &\\;\\;\\;\\;\n *          \\alpha_1\\left(c^{l,m+1,n}_{1,0,2}-c^{l,m,n}_{1,0,2}\\right),\n *          \\alpha_1\\left(c^{l,m,n}_{1,0,2}-c^{l,m-1,n}_{1,0,2}\\right),\\\\\n *   &\\;\\;\\;\\;\\left.\n *          \\alpha_2\\left(c^{l,m,n+1}_{1,1,1}-c^{l,m,n}_{1,1,1}\\right),\n *          \\alpha_2\\left(c^{l,m,n}_{1,1,1}-c^{l,m,n-1}_{1,1,1}\\right)\n *     \\right),\n * \\f}\n * \\f{align*}{\n * \\tilde{c}^{l,m,n}_{2,1,0}=\\mathrm{minmod}\n *   &\\left(c_{2,1,0}^{l,m,n},\n *          \\alpha_2\\left(c^{l+1,m,n}_{1,1,0}-c^{l,m,n}_{1,1,0}\\right),\n *          \\alpha_2\\left(c^{l,m,n}_{1,1,0}-c^{l-1,m,n}_{1,1,0}\\right),\n *     \\right.\\\\\n *   &\\;\\;\\;\\;\\left.\n *          \\alpha_1\\left(c^{l,m+1,n}_{2,0,0}-c^{l,m,n}_{2,0,0}\\right),\n *          \\alpha_1\\left(c^{l,m,n}_{2,0,0}-c^{l,m-1,n}_{2,0,0}\\right)\n *     \\right),\\\\\n * \\tilde{c}^{l,m,n}_{2,0,1}=\\mathrm{minmod}\n *   &\\left(c_{2,0,1}^{l,m,n},\n *          \\alpha_2\\left(c^{l+1,m,n}_{1,0,1}-c^{l,m,n}_{1,0,1}\\right),\n *          \\alpha_2\\left(c^{l,m,n}_{1,0,1}-c^{l-1,m,n}_{1,0,1}\\right),\n *     \\right.\\\\\n *   &\\;\\;\\;\\;\\left.\n *          \\alpha_1\\left(c^{l,m,n+1}_{2,0,0}-c^{l,m,n}_{2,0,0}\\right),\n *          \\alpha_1\\left(c^{l,m,n}_{2,0,0}-c^{l,m,n-1}_{2,0,0}\\right)\n *     \\right),\\\\\n * \\tilde{c}^{l,m,n}_{1,2,0}=\\mathrm{minmod}\n *   &\\left(c_{1,2,0}^{l,m,n},\n *          \\alpha_1\\left(c^{l+1,m,n}_{0,2,0}-c^{l,m,n}_{0,2,0}\\right),\n *          \\alpha_1\\left(c^{l,m,n}_{0,2,0}-c^{l-1,m,n}_{0,2,0}\\right),\n *     \\right.\\\\\n *   &\\;\\;\\;\\;\\left.\n *          \\alpha_2\\left(c^{l,m+1,n}_{1,1,0}-c^{l,m,n}_{1,1,0}\\right),\n *          \\alpha_2\\left(c^{l,m,n}_{1,1,0}-c^{l,m-1,n}_{1,1,0}\\right)\n *     \\right),\\\\\n * \\tilde{c}^{l,m,n}_{1,0,2}=\\mathrm{minmod}\n *   &\\left(c_{1,0,2}^{l,m,n},\n *          \\alpha_1\\left(c^{l+1,m,n}_{0,0,2}-c^{l,m,n}_{0,0,2}\\right),\n *          \\alpha_1\\left(c^{l,m,n}_{0,0,2}-c^{l-1,m,n}_{0,0,2}\\right),\n *     \\right.\\\\\n *   &\\;\\;\\;\\;\\left.\n *          \\alpha_2\\left(c^{l,m,n+1}_{1,0,1}-c^{l,m,n}_{1,0,1}\\right),\n *          \\alpha_2\\left(c^{l,m,n}_{1,0,1}-c^{l,m,n-1}_{1,0,1}\\right)\n *     \\right),\\\\\n * \\tilde{c}^{l,m,n}_{0,1,2}=\\mathrm{minmod}\n *   &\\left(c_{0,1,2}^{l,m,n},\n *          \\alpha_1\\left(c^{l,m+1,n}_{0,0,2}-c^{l,m,n}_{0,0,2}\\right),\n *          \\alpha_1\\left(c^{l,m,n}_{0,0,2}-c^{l,m-1,n}_{0,0,2}\\right),\n *   \\right. \\\\\n *   &\\;\\;\\;\\;\\left.\n *          \\alpha_2\\left(c^{l,m,n+1}_{0,1,1}-c^{l,m,n}_{0,1,1}\\right),\n *          \\alpha_2\\left(c^{l,m,n}_{0,1,1}-c^{l,m,n-1}_{0,1,1}\\right)\n *     \\right),\\\\\n * \\tilde{c}^{l,m,n}_{0,2,1}=\\mathrm{minmod}\n *   &\\left(c_{0,2,1}^{l,m,n},\n *          \\alpha_2\\left(c^{l,m+1,n}_{0,1,1}-c^{l,m,n}_{0,1,1}\\right),\n *          \\alpha_2\\left(c^{l,m,n}_{0,1,1}-c^{l,m-1,n}_{0,1,1}\\right),\n *   \\right.\\\\\n *   &\\;\\;\\;\\;\\left.\n *          \\alpha_1\\left(c^{l,m,n+1}_{0,2,0}-c^{l,m,n}_{0,2,0}\\right),\n *          \\alpha_1\\left(c^{l,m,n}_{0,2,0}-c^{l,m,n-1}_{0,2,0}\\right)\n *     \\right),\n * \\f}\n * \\f{align*}{\n * \\tilde{c}^{l,m,n}_{2,0,0}=\\mathrm{minmod}\n *   &\\left(c_{2,0,0}^{l,m,n},\n *          \\alpha_2\\left(c^{l+1,m,n}_{1,0,0}-c^{l,m,n}_{1,0,0}\\right),\n *          \\alpha_2\\left(c^{l,m,n}_{1,0,0}-c^{l-1,m,n}_{1,0,0}\\right)\n *     \\right),\\\\\n * \\tilde{c}^{l,m,n}_{0,2,0}=\\mathrm{minmod}\n *   &\\left(c_{0,2,0}^{l,m,n},\n *          \\alpha_2\\left(c^{l,m+1,n}_{0,1,0}-c^{l,m,n}_{0,1,0}\\right),\n *          \\alpha_2\\left(c^{l,m,n}_{0,1,0}-c^{l,m-1,n}_{0,1,0}\\right)\n *     \\right),\\\\\n * \\tilde{c}^{l,m,n}_{0,0,2}=\\mathrm{minmod}\n *   &\\left(c_{0,0,2}^{l,m,n},\n *          \\alpha_2\\left(c^{l,m,n+1}_{0,0,1}-c^{l,m,n}_{0,0,1}\\right),\n *          \\alpha_2\\left(c^{l,m,n}_{0,0,1}-c^{l,m,n-1}_{0,0,1}\\right)\n *     \\right),\\\\\n * \\tilde{c}^{l,m,n}_{1,1,1}=\\mathrm{minmod}\n *   &\\left(c_{1,1,1}^{l,m,n},\n *          \\alpha_1\\left(c^{l+1,m,n}_{0,1,1}-c^{l,m,n}_{0,1,1}\\right),\n *          \\alpha_1\\left(c^{l,m,n}_{0,1,1}-c^{l-1,m,n}_{0,1,1}\\right),\n *     \\right.\\\\\n *   &\\;\\;\\;\\;\n *          \\alpha_1\\left(c^{l,m+1,n}_{1,0,1}-c^{l,m,n}_{1,0,1}\\right),\n *          \\alpha_1\\left(c^{l,m,n}_{1,0,1}-c^{l,m-1,n}_{1,0,1}\\right),\\\\\n *   &\\;\\;\\;\\;\\left.\n *          \\alpha_1\\left(c^{l,m,n+1}_{1,1,0}-c^{l,m,n}_{1,1,0}\\right),\n *          \\alpha_1\\left(c^{l,m,n}_{1,1,0}-c^{l,m,n-1}_{1,1,0}\\right)\n *     \\right),\\\\\n * \\tilde{c}^{l,m,n}_{1,1,0}=\\mathrm{minmod}\n *   &\\left(c_{1,1,0}^{l,m,n},\n *          \\alpha_1\\left(c^{l+1,m,n}_{0,1,0}-c^{l,m,n}_{0,1,0}\\right),\n *          \\alpha_1\\left(c^{l,m,n}_{0,1,0}-c^{l-1,m,n}_{0,1,0}\\right),\n *     \\right.\\\\\n *   &\\;\\;\\;\\;\\left.\n *          \\alpha_1\\left(c^{l,m+1,n}_{1,0,0}-c^{l,m,n}_{1,0,0}\\right),\n *          \\alpha_1\\left(c^{l,m,n}_{1,0,0}-c^{l,m-1,n}_{1,0,0}\\right),\n *     \\right),\\\\\n * \\tilde{c}^{l,m,n}_{1,0,1}=\\mathrm{minmod}\n *   &\\left(c_{1,0,1}^{l,m,n},\n *          \\alpha_1\\left(c^{l+1,m,n}_{0,0,1}-c^{l,m,n}_{0,0,1}\\right),\n *          \\alpha_1\\left(c^{l,m,n}_{0,0,1}-c^{l-1,m,n}_{0,0,1}\\right),\n *     \\right.\\\\\n *   &\\;\\;\\;\\;\\left.\n *          \\alpha_1\\left(c^{l,m,n+1}_{1,0,0}-c^{l,m,n}_{1,0,0}\\right),\n *          \\alpha_1\\left(c^{l,m,n}_{1,0,0}-c^{l,m,n-1}_{1,0,0}\\right)\n *     \\right),\\\\\n * \\tilde{c}^{l,m,n}_{0,1,1}=\\mathrm{minmod}\n *   &\\left(c_{0,1,1}^{l,m,n},\n *          \\alpha_1\\left(c^{l,m+1,n}_{0,0,1}-c^{l,m,n}_{0,0,1}\\right),\n *          \\alpha_1\\left(c^{l,m,n}_{0,0,1}-c^{l,m-1,n}_{0,0,1}\\right),\n *   \\right.\\\\\n *   &\\;\\;\\;\\;\\left.\n *          \\alpha_1\\left(c^{l,m,n+1}_{0,1,0}-c^{l,m,n}_{0,1,0}\\right),\n *          \\alpha_1\\left(c^{l,m,n}_{0,1,0}-c^{l,m,n-1}_{0,1,0}\\right)\n *     \\right),\\\\\n * \\tilde{c}^{l,m,n}_{1,0,0}=\\mathrm{minmod}\n *   &\\left(c_{1,0,0}^{l,m,n},\n *          \\alpha_1\\left(c^{l+1,m,n}_{0,0,0}-c^{l,m,n}_{0,0,0}\\right),\n *          \\alpha_1\\left(c^{l,m,n}_{0,0,0}-c^{l-1,m,n}_{0,0,0}\\right)\n *     \\right),\\\\\n * \\tilde{c}^{l,m,n}_{0,1,0}=\\mathrm{minmod}\n *   &\\left(c_{0,1,0}^{l,m,n},\n *          \\alpha_1\\left(c^{l,m+1,n}_{0,0,0}-c^{l,m,n}_{0,0,0}\\right),\n *          \\alpha_1\\left(c^{l,m,n}_{0,0,0}-c^{l,m-1,n}_{0,0,0}\\right)\n *     \\right),\\\\\n * \\tilde{c}^{l,m,n}_{0,0,1}=\\mathrm{minmod}\n *   &\\left(c_{0,0,1}^{l,m,n},\n *          \\alpha_1\\left(c^{l,m,n+1}_{0,0,0}-c^{l,m,n}_{0,0,0}\\right),\n *          \\alpha_1\\left(c^{l,m,n}_{0,0,0}-c^{l,m,n-1}_{0,0,0}\\right)\n *     \\right),\n * \\f}\n *\n *\n * The algorithm to perform the limiting is as follows:\n *\n * - limit \\f$c_{2,2,2}\\f$ (i.e. \\f$c_{2,2,2}\\leftarrow\\tilde{c}_{2,2,2}\\f$), if\n *   not changed, stop\n * - limit \\f$c_{2,2,1}\\f$, \\f$c_{2,1,2}\\f$, and \\f$c_{1,2,2}\\f$, if all not\n * changed, stop\n * - limit \\f$c_{2,2,0}\\f$, \\f$c_{2,0,2}\\f$, and \\f$c_{0,2,2}\\f$, if all not\n * changed, stop\n * - limit \\f$c_{2,1,1}\\f$, \\f$c_{1,2,1}\\f$, and \\f$c_{1,1,2}\\f$, if all not\n * changed, stop\n * - limit \\f$c_{2,1,0}\\f$, \\f$c_{2,0,1}\\f$, \\f$c_{1,2,0}\\f$, \\f$c_{1,0,2}\\f$,\n * \\f$c_{0,1,2}\\f$, and \\f$c_{0,2,1}\\f$, if all not changed, stop\n * - limit \\f$c_{2,0,0}\\f$, \\f$c_{0,2,0}\\f$, and \\f$c_{0,0,2}\\f$, if all not\n * changed, stop\n * - limit \\f$c_{1,1,1}\\f$, if not changed, stop\n * - limit \\f$c_{1,1,0}\\f$, \\f$c_{1,0,1}\\f$, and \\f$c_{0,1,1}\\f$, if all not\n * changed, stop\n * - limit \\f$c_{1,0,0}\\f$, \\f$c_{0,1,0}\\f$, and \\f$c_{0,0,1}\\f$, if all not\n * changed, stop\n *\n * The 1d and 2d implementations are straightforward restrictions of the\n * described algorithm.\n *\n * #### Limitations:\n *\n * - We currently recompute the spectral coefficients for local use, after\n *   having computed these same coefficients for sending to the neighbors. We\n *   should be able to avoid this either by storing the coefficients in the\n *   DataBox or by allowing the limiters' `packaged_data` function to return an\n *   object to be passed as an additional argument to the `operator()` (still\n *   would need to be stored in the DataBox).\n * - We cannot handle the case where neighbors have more/fewer\n *   coefficients. In the case that the neighbor has more coefficients we could\n *   just ignore the higher coefficients. In the case that the neighbor has\n *   fewer coefficients we have a few choices.\n * - Having a different number of collocation points in different directions is\n *   not supported. However, it is straightforward to handle this case. The\n *   outermost loop should be in the direction with the most collocation points,\n *   while the inner most loop should be over the direction with the fewest\n *   collocation points. The highest to lowest coefficients can then be limited\n *   appropriately again.\n * - h-refinement is not supported, but there is one reasonably straightforward\n *   implementation that may work. In this case we would ignore refinement that\n *   is not in the direction of the neighbor, treating the element as\n *   simply having multiple neighbors in that direction. The only change would\n *   be accounting for different refinement in the direction of the neighor,\n *   which should be easy to add since the differences in coefficients in\n *   Eq.\\f$\\ref{eq:krivodonova 3d minmod}\\f$ will just be multiplied by\n *   non-unity factors.\n */\ntemplate <size_t VolumeDim, typename... Tags>\nclass Krivodonova<VolumeDim, tmpl::list<Tags...>> {\n public:\n  /*!\n   * \\brief The \\f$\\alpha_i\\f$ values in the Krivodonova algorithm.\n   */\n  struct Alphas {\n    using type = std::array<\n        double, Spectral::maximum_number_of_points<Spectral::Basis::Legendre>>;\n    static constexpr Options::String help = {\n        \"The alpha parameters of the Krivodonova limiter\"};\n  };\n  /*!\n   * \\brief Turn the limiter off\n   *\n   * This option exists to temporarily disable the limiter for debugging\n   * purposes. For problems where limiting is not needed, the preferred\n   * approach is to not compile the limiter into the executable.\n   */\n  struct DisableForDebugging {\n    using type = bool;\n    static type suggested_value() noexcept { return false; }\n    static constexpr Options::String help = {\"Disable the limiter\"};\n  };\n\n  using options = tmpl::list<Alphas, DisableForDebugging>;\n  static constexpr Options::String help = {\n      \"The hierarchical limiter of Krivodonova.\\n\\n\"\n      \"This limiter works by limiting the highest modal \"\n      \"coefficients/derivatives using an aggressive minmod approach, \"\n      \"decreasing in modal coefficient order until no more limiting is \"\n      \"necessary.\"};\n\n  explicit Krivodonova(\n      std::array<double,\n                 Spectral::maximum_number_of_points<Spectral::Basis::Legendre>>\n          alphas,\n      bool disable_for_debugging = false, const Options::Context& context = {});\n\n  Krivodonova() = default;\n  Krivodonova(const Krivodonova&) = delete;\n  Krivodonova& operator=(const Krivodonova&) = delete;\n  Krivodonova(Krivodonova&&) = default;\n  Krivodonova& operator=(Krivodonova&&) = default;\n  ~Krivodonova() = default;\n\n  // NOLINTNEXTLINE(google-runtime-references)\n  void pup(PUP::er& p) noexcept;\n\n  bool operator==(const Krivodonova& rhs) const noexcept;\n\n  struct PackagedData {\n    Variables<tmpl::list<::Tags::Modal<Tags>...>> modal_volume_data;\n    Mesh<VolumeDim> mesh;\n\n    // clang-tidy: google-runtime-references\n    void pup(PUP::er& p) noexcept {  // NOLINT\n      p | modal_volume_data;\n      p | mesh;\n    }\n  };\n\n  using package_argument_tags =\n      tmpl::list<Tags..., domain::Tags::Mesh<VolumeDim>>;\n\n  /// \\brief Package data for sending to neighbor elements.\n  void package_data(gsl::not_null<PackagedData*> packaged_data,\n                    const typename Tags::type&... tensors,\n                    const Mesh<VolumeDim>& mesh,\n                    const OrientationMap<VolumeDim>& orientation_map) const\n      noexcept;\n\n  using limit_tags = tmpl::list<Tags...>;\n  using limit_argument_tags = tmpl::list<domain::Tags::Element<VolumeDim>,\n                                         domain::Tags::Mesh<VolumeDim>>;\n\n  bool operator()(\n      const gsl::not_null<std::add_pointer_t<typename Tags::type>>... tensors,\n      const Element<VolumeDim>& element, const Mesh<VolumeDim>& mesh,\n      const std::unordered_map<\n          std::pair<Direction<VolumeDim>, ElementId<VolumeDim>>, PackagedData,\n          boost::hash<std::pair<Direction<VolumeDim>, ElementId<VolumeDim>>>>&\n          neighbor_data) const noexcept;\n\n private:\n  template <typename Tag>\n  char limit_one_tensor(\n      gsl::not_null<Variables<tmpl::list<::Tags::Modal<Tags>...>>*> coeffs_self,\n      gsl::not_null<bool*> limited_any_component, const Mesh<1>& mesh,\n      const std::unordered_map<\n          std::pair<Direction<1>, ElementId<1>>, PackagedData,\n          boost::hash<std::pair<Direction<1>, ElementId<1>>>>& neighbor_data)\n      const noexcept;\n  template <typename Tag>\n  char limit_one_tensor(\n      gsl::not_null<Variables<tmpl::list<::Tags::Modal<Tags>...>>*> coeffs_self,\n      gsl::not_null<bool*> limited_any_component, const Mesh<2>& mesh,\n      const std::unordered_map<\n          std::pair<Direction<2>, ElementId<2>>, PackagedData,\n          boost::hash<std::pair<Direction<2>, ElementId<2>>>>& neighbor_data)\n      const noexcept;\n  template <typename Tag>\n  char limit_one_tensor(\n      gsl::not_null<Variables<tmpl::list<::Tags::Modal<Tags>...>>*> coeffs_self,\n      gsl::not_null<bool*> limited_any_component, const Mesh<3>& mesh,\n      const std::unordered_map<\n          std::pair<Direction<3>, ElementId<3>>, PackagedData,\n          boost::hash<std::pair<Direction<3>, ElementId<3>>>>& neighbor_data)\n      const noexcept;\n\n  template <typename Tag, size_t Dim>\n  char fill_variables_tag_with_spectral_coeffs(\n      gsl::not_null<Variables<tmpl::list<::Tags::Modal<Tags>...>>*>\n          modal_coeffs,\n      const typename Tag::type& nodal_tensor, const Mesh<Dim>& mesh) const\n      noexcept;\n\n  std::array<double,\n             Spectral::maximum_number_of_points<Spectral::Basis::Legendre>>\n      alphas_ = make_array<\n          Spectral::maximum_number_of_points<Spectral::Basis::Legendre>>(\n          std::numeric_limits<double>::signaling_NaN());\n  bool disable_for_debugging_{false};\n};\n\ntemplate <size_t VolumeDim, typename... Tags>\nKrivodonova<VolumeDim, tmpl::list<Tags...>>::Krivodonova(\n    std::array<double,\n               Spectral::maximum_number_of_points<Spectral::Basis::Legendre>>\n        alphas,\n    bool disable_for_debugging, const Options::Context& context)\n    : alphas_(alphas), disable_for_debugging_(disable_for_debugging) {\n  // See the main documentation for an explanation of why these bounds are\n  // different from those of Krivodonova 2007\n  if (alg::any_of(alphas_, [](const double t) noexcept {\n        return t > 1.0 or t <= 0.0;\n      })) {\n    PARSE_ERROR(context,\n                \"The alphas in the Krivodonova limiter must be in the range \"\n                \"(0,1].\");\n  }\n}\n\ntemplate <size_t VolumeDim, typename... Tags>\nvoid Krivodonova<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 OrientationMap<VolumeDim>& orientation_map) const noexcept {\n  if (UNLIKELY(disable_for_debugging_)) {\n    // Do not initialize packaged_data\n    return;\n  }\n\n  packaged_data->modal_volume_data.initialize(mesh.number_of_grid_points());\n  // perform nodal coefficients to modal coefficients transformation on each\n  // tensor component\n  expand_pack(fill_variables_tag_with_spectral_coeffs<Tags>(\n      &(packaged_data->modal_volume_data), tensors, mesh)...);\n\n  packaged_data->modal_volume_data = orient_variables(\n      packaged_data->modal_volume_data, mesh.extents(), orientation_map);\n\n  packaged_data->mesh = orientation_map(mesh);\n}\n\ntemplate <size_t VolumeDim, typename... Tags>\nbool Krivodonova<VolumeDim, tmpl::list<Tags...>>::operator()(\n    const gsl::not_null<std::add_pointer_t<typename Tags::type>>... tensors,\n    const Element<VolumeDim>& element, const Mesh<VolumeDim>& mesh,\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  if (UNLIKELY(mesh != Mesh<VolumeDim>(mesh.extents()[0], mesh.basis()[0],\n                                       mesh.quadrature()[0]))) {\n    ERROR(\n        \"The Krivodonova limiter does not yet support non-uniform number of \"\n        \"collocation points, bases, and quadrature in each direction. The \"\n        \"mesh is: \"\n        << mesh);\n  }\n  if (UNLIKELY(alg::any_of(element.neighbors(),\n                           [](const auto& direction_neighbors) noexcept {\n                             return direction_neighbors.second.size() != 1;\n                           }))) {\n    ERROR(\"The Krivodonova limiter does not yet support h-refinement\");\n  }\n  alg::for_each(neighbor_data, [&mesh](const auto& id_packaged_data) noexcept {\n    if (UNLIKELY(id_packaged_data.second.mesh != mesh)) {\n      ERROR(\n          \"The Krivodonova limiter does not yet support differing meshes \"\n          \"between neighbors. Self mesh is: \"\n          << mesh << \" neighbor mesh is: \" << id_packaged_data.second.mesh);\n    }\n  });\n\n  // Compute local modal coefficients\n  Variables<tmpl::list<::Tags::Modal<Tags>...>> coeffs_self(\n      mesh.number_of_grid_points(), 0.0);\n  expand_pack(fill_variables_tag_with_spectral_coeffs<Tags>(&coeffs_self,\n                                                            *tensors, mesh)...);\n\n  // Perform the limiting on the modal coefficients\n  bool limited_any_component = false;\n  expand_pack(limit_one_tensor<::Tags::Modal<Tags>>(\n      make_not_null(&coeffs_self), make_not_null(&limited_any_component), mesh,\n      neighbor_data)...);\n\n  // transform back to nodal coefficients\n  const auto wrap_copy_nodal_coeffs =\n      [&mesh, &coeffs_self](auto tag, const auto tensor) noexcept {\n        auto& coeffs_tensor = get<decltype(tag)>(coeffs_self);\n        auto tensor_it = tensor->begin();\n        for (auto coeffs_it = coeffs_tensor.begin();\n             coeffs_it != coeffs_tensor.end();\n             (void)++coeffs_it, (void)++tensor_it) {\n          to_nodal_coefficients(make_not_null(&*tensor_it), *coeffs_it, mesh);\n        }\n        return '0';\n      };\n  expand_pack(wrap_copy_nodal_coeffs(::Tags::Modal<Tags>{}, tensors)...);\n\n  return limited_any_component;\n}\n\ntemplate <size_t VolumeDim, typename... Tags>\ntemplate <typename Tag>\nchar Krivodonova<VolumeDim, tmpl::list<Tags...>>::limit_one_tensor(\n    const gsl::not_null<Variables<tmpl::list<::Tags::Modal<Tags>...>>*>\n        coeffs_self,\n    const gsl::not_null<bool*> limited_any_component, const Mesh<1>& mesh,\n    const std::unordered_map<\n        std::pair<Direction<1>, ElementId<1>>, PackagedData,\n        boost::hash<std::pair<Direction<1>, ElementId<1>>>>& neighbor_data)\n    const noexcept {\n  using tensor_type = typename Tag::type;\n  for (size_t storage_index = 0; storage_index < tensor_type::size();\n       ++storage_index) {\n    // for each coefficient...\n    for (size_t i = mesh.extents()[0] - 1; i > 0; --i) {\n      auto& self_coeffs = get<Tag>(*coeffs_self)[storage_index];\n      double min_abs_coeff = std::abs(self_coeffs[i]);\n      const double sgn_of_coeff = sgn(self_coeffs[i]);\n      bool sgns_all_equal = true;\n      for (const auto& kv : neighbor_data) {\n        const auto& neighbor_coeffs =\n            get<Tag>(kv.second.modal_volume_data)[storage_index];\n        const double tmp = kv.first.first.sign() * gsl::at(alphas_, i) *\n                           (neighbor_coeffs[i - 1] - self_coeffs[i - 1]);\n\n        min_abs_coeff = std::min(min_abs_coeff, std::abs(tmp));\n        sgns_all_equal &= sgn(tmp) == sgn_of_coeff;\n        if (not sgns_all_equal) {\n          self_coeffs[i] = 0.0;\n          break;\n        }\n      }\n      if (sgns_all_equal) {\n        const double tmp = sgn_of_coeff * min_abs_coeff;\n        if (tmp == self_coeffs[i]) {\n          break;\n        }\n        *limited_any_component |= true;\n        self_coeffs[i] = tmp;\n      }\n    }\n  }\n  return '0';\n}\n\ntemplate <size_t VolumeDim, typename... Tags>\ntemplate <typename Tag>\nchar Krivodonova<VolumeDim, tmpl::list<Tags...>>::limit_one_tensor(\n    const gsl::not_null<Variables<tmpl::list<::Tags::Modal<Tags>...>>*>\n        coeffs_self,\n    const gsl::not_null<bool*> limited_any_component, const Mesh<2>& mesh,\n    const std::unordered_map<\n        std::pair<Direction<2>, ElementId<2>>, PackagedData,\n        boost::hash<std::pair<Direction<2>, ElementId<2>>>>& neighbor_data)\n    const noexcept {\n  using tensor_type = typename Tag::type;\n  const auto minmod = [&coeffs_self, &mesh, &neighbor_data, this](\n                          const size_t local_i, const size_t local_j,\n                          const size_t local_tensor_storage_index) noexcept {\n    const auto& self_coeffs =\n        get<Tag>(*coeffs_self)[local_tensor_storage_index];\n    double min_abs_coeff = std::abs(\n        self_coeffs[mesh.storage_index(Index<VolumeDim>{local_i, local_j})]);\n    const double sgn_of_coeff = sgn(\n        self_coeffs[mesh.storage_index(Index<VolumeDim>{local_i, local_j})]);\n    for (const auto& kv : neighbor_data) {\n      const Direction<2>& dir = kv.first.first;\n      const auto& neighbor_coeffs =\n          get<Tag>(kv.second.modal_volume_data)[local_tensor_storage_index];\n      const size_t index_i =\n          dir.axis() == Direction<VolumeDim>::Axis::Xi ? local_i - 1 : local_i;\n      const size_t index_j =\n          dir.axis() == Direction<VolumeDim>::Axis::Eta ? local_j - 1 : local_j;\n      // skip neighbors where we cannot compute a finite difference in that\n      // direction because we are already at the lowest coefficient.\n      if (index_i == std::numeric_limits<size_t>::max() or\n          index_j == std::numeric_limits<size_t>::max()) {\n        continue;\n      }\n      const size_t alpha_index =\n          dir.axis() == Direction<VolumeDim>::Axis::Xi ? local_i : local_j;\n      const double tmp =\n          dir.sign() * gsl::at(alphas_, alpha_index) *\n          (neighbor_coeffs[mesh.storage_index(\n               Index<VolumeDim>{index_i, index_j})] -\n           self_coeffs[mesh.storage_index(Index<VolumeDim>{index_i, index_j})]);\n\n      min_abs_coeff = std::min(min_abs_coeff, std::abs(tmp));\n      if (sgn(tmp) != sgn_of_coeff) {\n        return 0.0;\n      }\n    }\n    return sgn_of_coeff * min_abs_coeff;\n  };\n\n  for (size_t tensor_storage_index = 0;\n       tensor_storage_index < tensor_type::size(); ++tensor_storage_index) {\n    // for each coefficient...\n    for (size_t i = mesh.extents()[0] - 1; i > 0; --i) {\n      for (size_t j = i; j < mesh.extents()[1]; --j) {\n        // Check if we are done limiting, and if so we move on to the next\n        // tensor component.\n        auto& self_coeffs = get<Tag>(*coeffs_self)[tensor_storage_index];\n        // We treat the different cases separately to reduce the number of\n        // times we call minmod, not because it is required for correctness.\n        if (UNLIKELY(i == j)) {\n          const double tmp = minmod(i, j, tensor_storage_index);\n          if (tmp == self_coeffs[mesh.storage_index(Index<VolumeDim>{i, j})]) {\n            goto next_tensor_index;\n          }\n          *limited_any_component |= true;\n          self_coeffs[mesh.storage_index(Index<VolumeDim>{i, j})] = tmp;\n        } else {\n          const double tmp_ij = minmod(i, j, tensor_storage_index);\n          const double tmp_ji = minmod(j, i, tensor_storage_index);\n          if (tmp_ij ==\n                  self_coeffs[mesh.storage_index(Index<VolumeDim>{i, j})] and\n              tmp_ji ==\n                  self_coeffs[mesh.storage_index(Index<VolumeDim>{j, i})]) {\n            goto next_tensor_index;\n          }\n          *limited_any_component |= true;\n          self_coeffs[mesh.storage_index(Index<VolumeDim>{i, j})] = tmp_ij;\n          self_coeffs[mesh.storage_index(Index<VolumeDim>{j, i})] = tmp_ji;\n        }\n      }\n    }\n  next_tensor_index:\n    continue;\n  }\n  return '0';\n}\n\ntemplate <size_t VolumeDim, typename... Tags>\ntemplate <typename Tag>\nchar Krivodonova<VolumeDim, tmpl::list<Tags...>>::limit_one_tensor(\n    const gsl::not_null<Variables<tmpl::list<::Tags::Modal<Tags>...>>*>\n        coeffs_self,\n    const gsl::not_null<bool*> limited_any_component, const Mesh<3>& mesh,\n    const std::unordered_map<\n        std::pair<Direction<3>, ElementId<3>>, PackagedData,\n        boost::hash<std::pair<Direction<3>, ElementId<3>>>>& neighbor_data)\n    const noexcept {\n  using tensor_type = typename Tag::type;\n  const auto minmod = [&coeffs_self, &mesh, &neighbor_data, this](\n                          const size_t local_i, const size_t local_j,\n                          const size_t local_k,\n                          const size_t local_tensor_storage_index) noexcept {\n    const auto& self_coeffs =\n        get<Tag>(*coeffs_self)[local_tensor_storage_index];\n    double min_abs_coeff = std::abs(self_coeffs[mesh.storage_index(\n        Index<VolumeDim>{local_i, local_j, local_k})]);\n    const double sgn_of_coeff = sgn(self_coeffs[mesh.storage_index(\n        Index<VolumeDim>{local_i, local_j, local_k})]);\n    for (const auto& kv : neighbor_data) {\n      const Direction<3>& dir = kv.first.first;\n      const auto& neighbor_coeffs =\n          get<Tag>(kv.second.modal_volume_data)[local_tensor_storage_index];\n      const size_t index_i =\n          dir.axis() == Direction<VolumeDim>::Axis::Xi ? local_i - 1 : local_i;\n      const size_t index_j =\n          dir.axis() == Direction<VolumeDim>::Axis::Eta ? local_j - 1 : local_j;\n      const size_t index_k = dir.axis() == Direction<VolumeDim>::Axis::Zeta\n                                 ? local_k - 1\n                                 : local_k;\n      // skip neighbors where we cannot compute a finite difference in that\n      // direction because we are already at the lowest coefficient.\n      if (index_i == std::numeric_limits<size_t>::max() or\n          index_j == std::numeric_limits<size_t>::max() or\n          index_k == std::numeric_limits<size_t>::max()) {\n        continue;\n      }\n      const size_t alpha_index =\n          dir.axis() == Direction<VolumeDim>::Axis::Xi\n              ? local_i\n              : dir.axis() == Direction<VolumeDim>::Axis::Eta ? local_j\n                                                              : local_k;\n      const double tmp = dir.sign() * gsl::at(alphas_, alpha_index) *\n                         (neighbor_coeffs[mesh.storage_index(\n                              Index<VolumeDim>{index_i, index_j, index_k})] -\n                          self_coeffs[mesh.storage_index(\n                              Index<VolumeDim>{index_i, index_j, index_k})]);\n\n      min_abs_coeff = std::min(min_abs_coeff, std::abs(tmp));\n      if (sgn(tmp) != sgn_of_coeff) {\n        return 0.0;\n      }\n    }\n    return sgn_of_coeff * min_abs_coeff;\n  };\n\n  for (size_t tensor_storage_index = 0;\n       tensor_storage_index < tensor_type::size(); ++tensor_storage_index) {\n    // for each coefficient...\n    for (size_t i = mesh.extents()[0] - 1; i > 0; --i) {\n      for (size_t j = i; j < mesh.extents()[1]; --j) {\n        for (size_t k = j; k < mesh.extents()[2]; --k) {\n          // Check if we are done limiting, and if so we move on to the next\n          // tensor component.\n          auto& self_coeffs = get<Tag>(*coeffs_self)[tensor_storage_index];\n          // We treat the different cases separately to reduce the number of\n          // times we call minmod, not because it is required for correctness.\n          //\n          // Note that the case `i == k and i != j` cannot be encountered since\n          // the loop bounds are `i >= j >= k`.\n          if (UNLIKELY(i == j and i == k)) {\n            const double tmp = minmod(i, j, k, tensor_storage_index);\n            if (tmp ==\n                self_coeffs[mesh.storage_index(Index<VolumeDim>{i, j, k})]) {\n              goto next_tensor_index;\n            }\n            *limited_any_component |= true;\n            self_coeffs[mesh.storage_index(Index<VolumeDim>{i, j, k})] = tmp;\n          } else if (i == j and i != k) {\n            const double tmp_ijk = minmod(i, j, k, tensor_storage_index);\n            const double tmp_ikj = minmod(i, k, j, tensor_storage_index);\n            const double tmp_kij = minmod(k, i, j, tensor_storage_index);\n            if (tmp_ijk == self_coeffs[mesh.storage_index(\n                               Index<VolumeDim>{i, j, k})] and\n                tmp_ikj == self_coeffs[mesh.storage_index(\n                               Index<VolumeDim>{i, k, j})] and\n                tmp_kij == self_coeffs[mesh.storage_index(\n                               Index<VolumeDim>{k, i, j})]) {\n              goto next_tensor_index;\n            }\n            *limited_any_component |= true;\n            self_coeffs[mesh.storage_index(Index<VolumeDim>{i, j, k})] =\n                tmp_ijk;\n            self_coeffs[mesh.storage_index(Index<VolumeDim>{i, k, j})] =\n                tmp_ikj;\n            self_coeffs[mesh.storage_index(Index<VolumeDim>{k, i, j})] =\n                tmp_kij;\n          } else if (i != j and j == k) {\n            const double tmp_ijk = minmod(i, j, k, tensor_storage_index);\n            const double tmp_kij = minmod(k, i, j, tensor_storage_index);\n            const double tmp_kji = minmod(k, j, i, tensor_storage_index);\n            if (tmp_ijk == self_coeffs[mesh.storage_index(\n                               Index<VolumeDim>{i, j, k})] and\n                tmp_kij == self_coeffs[mesh.storage_index(\n                               Index<VolumeDim>{k, i, j})] and\n                tmp_kji == self_coeffs[mesh.storage_index(\n                               Index<VolumeDim>{k, j, i})]) {\n              goto next_tensor_index;\n            }\n            *limited_any_component |= true;\n            self_coeffs[mesh.storage_index(Index<VolumeDim>{i, j, k})] =\n                tmp_ijk;\n            self_coeffs[mesh.storage_index(Index<VolumeDim>{k, i, j})] =\n                tmp_kij;\n            self_coeffs[mesh.storage_index(Index<VolumeDim>{k, j, i})] =\n                tmp_kji;\n          } else {\n            const double tmp_ijk = minmod(i, j, k, tensor_storage_index);\n            const double tmp_jik = minmod(j, i, k, tensor_storage_index);\n            const double tmp_ikj = minmod(i, k, j, tensor_storage_index);\n            const double tmp_jki = minmod(j, k, i, tensor_storage_index);\n            const double tmp_kij = minmod(k, i, j, tensor_storage_index);\n            const double tmp_kji = minmod(k, j, i, tensor_storage_index);\n            if (tmp_ijk == self_coeffs[mesh.storage_index(\n                               Index<VolumeDim>{i, j, k})] and\n                tmp_jik == self_coeffs[mesh.storage_index(\n                               Index<VolumeDim>{j, i, k})] and\n                tmp_ikj == self_coeffs[mesh.storage_index(\n                               Index<VolumeDim>{i, k, j})] and\n                tmp_jki == self_coeffs[mesh.storage_index(\n                               Index<VolumeDim>{j, k, i})] and\n                tmp_kij == self_coeffs[mesh.storage_index(\n                               Index<VolumeDim>{k, i, j})] and\n                tmp_kji == self_coeffs[mesh.storage_index(\n                               Index<VolumeDim>{k, j, i})]) {\n              goto next_tensor_index;\n            }\n            *limited_any_component |= true;\n            self_coeffs[mesh.storage_index(Index<VolumeDim>{i, j, k})] =\n                tmp_ijk;\n            self_coeffs[mesh.storage_index(Index<VolumeDim>{j, i, k})] =\n                tmp_jik;\n            self_coeffs[mesh.storage_index(Index<VolumeDim>{i, k, j})] =\n                tmp_ikj;\n            self_coeffs[mesh.storage_index(Index<VolumeDim>{j, k, i})] =\n                tmp_jki;\n            self_coeffs[mesh.storage_index(Index<VolumeDim>{k, i, j})] =\n                tmp_kij;\n            self_coeffs[mesh.storage_index(Index<VolumeDim>{k, j, i})] =\n                tmp_kji;\n          }\n        }\n      }\n    }\n  next_tensor_index:\n    continue;\n  }\n  return '0';\n}\n\ntemplate <size_t VolumeDim, typename... Tags>\ntemplate <typename Tag, size_t Dim>\nchar Krivodonova<VolumeDim, tmpl::list<Tags...>>::\n    fill_variables_tag_with_spectral_coeffs(\n        const gsl::not_null<Variables<tmpl::list<::Tags::Modal<Tags>...>>*>\n            modal_coeffs,\n        const typename Tag::type& nodal_tensor, const Mesh<Dim>& mesh) const\n    noexcept {\n  auto& coeffs_tensor = get<::Tags::Modal<Tag>>(*modal_coeffs);\n  auto tensor_it = nodal_tensor.begin();\n  for (auto coeffs_it = coeffs_tensor.begin(); coeffs_it != coeffs_tensor.end();\n       (void)++coeffs_it, (void)++tensor_it) {\n    to_modal_coefficients(make_not_null(&*coeffs_it), *tensor_it, mesh);\n  }\n  return '0';\n}\n\ntemplate <size_t VolumeDim, typename... Tags>\nvoid Krivodonova<VolumeDim, tmpl::list<Tags...>>::pup(PUP::er& p) noexcept {\n  p | alphas_;\n  p | disable_for_debugging_;\n}\n\ntemplate <size_t VolumeDim, typename... Tags>\nbool Krivodonova<VolumeDim, tmpl::list<Tags...>>::operator==(\n    const Krivodonova<VolumeDim, tmpl::list<Tags...>>& rhs) const noexcept {\n  return alphas_ == rhs.alphas_ and\n         disable_for_debugging_ == rhs.disable_for_debugging_;\n}\n\ntemplate <size_t VolumeDim, typename... Tags>\nbool operator!=(\n    const Krivodonova<VolumeDim, tmpl::list<Tags...>>& lhs,\n    const Krivodonova<VolumeDim, tmpl::list<Tags...>>& rhs) noexcept {\n  return not(lhs == rhs);\n}\n}  // namespace Limiters\n", "meta": {"hexsha": "a33b86ee8bbb6377306e6758c363a381b2254cb1", "size": 44095, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/Evolution/DiscontinuousGalerkin/Limiters/Krivodonova.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/Krivodonova.hpp", "max_issues_repo_name": "trami18/spectre", "max_issues_repo_head_hexsha": "6b1f6497bf2e26d1474bfadf143b3321942c40b4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2022-03-25T18:26:16.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-25T19:30:39.000Z", "max_forks_repo_path": "src/Evolution/DiscontinuousGalerkin/Limiters/Krivodonova.hpp", "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": 44.2720883534, "max_line_length": 80, "alphanum_fraction": 0.5812903957, "num_tokens": 14361, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6548947290421275, "lm_q2_score": 0.47657965106367595, "lm_q1q2_score": 0.3121095014503377}}
{"text": "#pragma once\n\n#include <fstream>\n#include <sstream>\n#include <map>\n#include <vector>\n#include <algorithm>\n#include <assert.h>\n#include <iostream>\n#include <cmath>\n#include <stdexcept>\n#include <list>\n#include <float.h>\n#include <random>\n#include <chrono>\n#include <unordered_map>\n#include <unordered_set>\n#include <stdexcept>\n#include <time.h>\n#include <stdio.h>\n#include <boost/math/distributions/binomial.hpp>\n#include <boost/math/distributions/poisson.hpp>\n#include <boost/random.hpp>\n#include <boost/math/special_functions/gamma.hpp>\n\n//#define REUSE\n#define STACK\n//#define SAMPLE\n\n#define MISS_BAR 1024 * 2\n\nnamespace sdd {\n\n/* to calculate C(a, k) / C(b, k) */\ninline double combinationRatio(int b, int a, int k)\n{\n\tif (b < a || !a || !b || !k)\n\t\tthrow std::exception();\n\t\n\t/* This is for the condition that wouldn't occur. */\n\tif (k > a) return 0.0;\n\n\n\tint loops = b - a;\n\tdouble result = 1.0;\n\twhile (loops--)\n\t\tresult *= (double)(b - k) / (b--);\n\n\tif (result <= DBL_MIN)\n\t\tthrow std::exception();\n\n\treturn result;\n}\n\n/* calculate log2(s) + 1 */\ntemplate<class T>\ninline T log2p1(T s)\n{\n\tT result = 0;\n\twhile (s) {\n\t\ts >>= 1;\n\t\t++result;\n\t}\n\n\treturn result;\n}\n\n/* for recording distribution into a Histogram, \n   Accur is the accuracy of transforming calculation */\ntemplate <class B = int64_t>\nclass Histogram\n{\n\tB * bins;\n\tB samples;\n\tint size;\n\npublic:\n\tHistogram() : bins(nullptr), samples(0), size(0) {};\n\n\t~Histogram()\n\t{\n    \tdelete [] bins;\n\t}\n\n\tvoid allocateBins(int _size)\n\t{\n    \tsize = _size;\n    \tbins = new B[size];\n    \t/* init bins to 0 */\n    \tfor (int i = 0; i < size; ++i)\n        \tbins[i] = 0;\n\t\n    \tstd::cout << \"size of bins \" << size << std::endl;\n\t}\n\n\tvoid clear()\n\t{\n    \tdelete [] bins;\n    \tsamples = 0;\n    \t/* when clear bins, the size keeps unchanged */\n    \tallocateBins(size);\n\t}\n\n\tvoid sample(B x);\n\n\tvoid print(std::ofstream & file)\n\t{\n    \t//file.write((char *)bins, sizeof(B) * size);\n    \tfor (int i = 0; i < size; ++i) {\n    \t\tfile << bins[i] << \" \";\n    \t}\n    \tfile << \"\\n\";\n\t}\n};\n\ntemplate <class Accur>\nclass AvlNode\n{\n\t//int holes;\n\tfriend class AvlTreeStack;\n\t/* this is the num of holes of this tree,\n\tincluding the holes of subtrees and the self interval. */\n\tint holes;\n\t/* this is the num of holes of entire right subtree. */\n\tint rHoles;\n\tstd::pair<Accur, Accur> interval;\n\tint height;\n\tAvlNode<Accur> * left;\n\tAvlNode<Accur> * right;\n\npublic:\n\tAvlNode(Accur & a);\n\n\tAvlNode(AvlNode<Accur> & n);\n\n\t~AvlNode();\n\n\tstatic int getHeight(AvlNode<Accur> * & node)\n\t{\n\t\treturn node ? node->height : -1;\n\t}\n\n\tvoid updateHeight();\n\n\tvoid updateHoles();\n};\n\n/* for calculating stack distance distribution via AVL Tree, with no sampling*/\nclass AvlTreeStack\n{\n\tstd::map <uint64_t, long> addrMap;\n\tAvlNode<long> * root;\n\t/* the index of refs in memory trace */\n\tlong index;\n\t/* holes between current ref and last ref with same address */\n\tint curHoles;\n\npublic:\n\tAvlTreeStack(long & v);\n\n\tAvlTreeStack();\n\n\t~AvlTreeStack() { destroy(root); }\n\n\tvoid destroy(AvlNode<long> * & tree);\n\n\tvoid clear();\n\n\tvoid insert(AvlNode<long> * & tree, long & v);\n\n\tvoid insert(long & a);\n\n\t/*AvlNode<long> * & find(AvlNode<long> * & tree, int & v)\n\t{\n\tif (!tree)\n\treturn nullptr;\n\n\tif (v < tree->holes)\n\tfind(tree->left, v);\n\telse if (v > tree->holes)\n\tfind(tree->right, v);\n\telse\n\treturn tree;\n\t}*/\n\n\t/* find the minimal interval node */\n\tAvlNode<long> * & findMin(AvlNode<long> * & tree);\n\t\n\t/* find the maximal interval node */\n\tAvlNode<long> * & findMax(AvlNode<long> * & tree);\n\n\tvoid remove(AvlNode<long> * & tree, std::pair<long, long> & inter);\n\n\tvoid rotate(AvlNode<long> * & tree);\n\n\tvoid doubleRotate(AvlNode<long> * & tree);\n\n\tvoid balance(AvlNode<long> * & tree);\n\n\tvoid calStackDist(uint64_t addr, Histogram<> & hist);\n};\n\n/* do reuse distance statistics */\nclass ReuseDist\n{\n\tstd::map<uint64_t, long> addrMap;\n\tlong index;\n\npublic:\n\tReuseDist() {};\n\t~ReuseDist() {};\n\n\tvoid calReuseDist(uint64_t addr, Histogram<> & hist);\n};\n\n/* stack distance staticstics with sampling */\nclass SampleStack\n{\n\tlong index;\n\n\ttypedef std::unordered_set<uint64_t> AddrSet;\n\t/* each watchpoint has a set to keep the unique mem refs */\n\tstd::unordered_map<uint64_t, AddrSet> addrTable;\n\tint randNum;\n\tint sampleCounter;\n\tint expectSamples;\n\tint hibernInter;\n\tint sampleInter;\n\tlong statusCounter;\n\tbool isSampling;\n\npublic:\n\tSampleStack();\n\n\t/* to generate a random number */\n\tint genRandom();\n\n\tvoid calStackDist(uint64_t addr, Histogram<> & hist);\n};\n\n}; // namespace sdd", "meta": {"hexsha": "67daace9818a66fdde81ee1834ae74d7c79c7c77", "size": 4499, "ext": "hh", "lang": "C++", "max_stars_repo_path": "src/base/StackDistance.hh", "max_stars_repo_name": "ShenShan123/gem5-branch-model", "max_stars_repo_head_hexsha": "a672cef669df9c750e0711bde8d1fe16e5f143e6", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_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/StackDistance.hh", "max_issues_repo_name": "ShenShan123/gem5-branch-model", "max_issues_repo_head_hexsha": "a672cef669df9c750e0711bde8d1fe16e5f143e6", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_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/StackDistance.hh", "max_forks_repo_name": "ShenShan123/gem5-branch-model", "max_forks_repo_head_hexsha": "a672cef669df9c750e0711bde8d1fe16e5f143e6", "max_forks_repo_licenses": ["BSD-3-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.6680497925, "max_line_length": 79, "alphanum_fraction": 0.6479217604, "num_tokens": 1273, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6548947155710233, "lm_q2_score": 0.47657965106367595, "lm_q1q2_score": 0.31210949503028357}}
{"text": "#include <fstream> \r\n#include <iostream>\r\n#include <string>\r\n#include <cmath>\r\n#include <vector>\r\n#include <cfloat>\r\n#include <boost/filesystem.hpp>\r\n#include \"canvas.h\"\r\n#include \"vector.h\"\r\n#include \"matrix.h\"\r\n#include \"shapes.h\"\r\n#include \"model.h\"\r\n#include \"light.h\"\r\n\r\n// Local function prototypes\r\nvoid swap(vec3&, vec3&);\r\nvoid sort_desc(std::vector<vec3>&);\r\n\r\n////////////\r\n\r\n// Constructor\r\nCanvas::Canvas(int w, int h) : width(w), height(h)\r\n{\r\n    canvas.resize(w, std::vector<color>(h));\r\n    depth_buffer.resize(w, std::vector<float>(h));\r\n    for (int i = 0; i < w; ++i)\r\n    {\r\n        std::fill(depth_buffer[i].begin(), \r\n                  depth_buffer[i].end(), \r\n                  -std::numeric_limits<float>::max()\r\n        );         \r\n    }\r\n}\r\n\r\nvec3 Canvas::convert_ndc_to_canvas(const vec3 &p)\r\n{\r\n    vec3 canvas_coords(\r\n        (int)(0.5f * (width * p.x() + width)),\r\n        (int)(0.5f * (height * p.y() + height)),\r\n              0\r\n    );\r\n\r\n    return canvas_coords;\r\n}\r\n\r\nvec3 Canvas::convert_canvas_to_ndc(const vec3 &p)\r\n{\r\n    vec3 ndc_coords(\r\n        (2 * p.x() - width) / width,\r\n        (2 * p.y() - height) / height,\r\n         0\r\n    );\r\n\r\n    return ndc_coords;\r\n}\r\n\r\n\r\nvoid Canvas::draw_shapes()\r\n{\r\n    // Draw all the shapes that are stored in the shapes_list\r\n    for (std::vector<shape*>::const_iterator it = shapes_list.begin();\r\n           it != shapes_list.end(); ++it)\r\n    {\r\n        // TODO refactor this to be just one function\r\n        //(*it)->draw(canvas);\r\n    }\r\n}\r\n\r\nvoid Canvas::apply_transform(const mat4& m_transform)\r\n{\r\n    // Apply transformation matrix on all shapes\r\n    // and their corresponding vertices\r\n    for (std::vector<shape *>::const_iterator it = shapes_list.begin();\r\n           it != shapes_list.end(); ++it)\r\n    {\r\n        (*it)->apply_transform(m_transform);\r\n    }\r\n}\r\n\r\nvoid Canvas::reset_canvas(const color& _color)\r\n{\r\n    for (int h = 0; h < height; ++h)\r\n    {\r\n        for (int w = 0; w < width; ++w)\r\n        {\r\n            canvas[w][h] = _color;\r\n\r\n            // Set depth_buffer values to -FLT_MAX\r\n            // which serves as the furthest point from the camera\r\n            depth_buffer[w][h] = -FLT_MAX;\r\n        }\r\n    }\r\n}\r\n\r\nvoid Canvas::print_canvas()\r\n{\r\n    // Output canvas into ppm file\r\n    std::cout << \"P3\\n\" << width << \" \" << height << \"\\n255\\n\";\r\n    for (int y = height-1; y >= 0; --y)\r\n    {\r\n        for (int x = 0; x < width; ++x)\r\n        {\r\n            int r = (int)(canvas[x][y].r() * 255.99f);\r\n            int g = (int)(canvas[x][y].g() * 255.99f);\r\n            int b = (int)(canvas[x][y].b() * 255.99f);\r\n\r\n            std::cout << r << \" \"\r\n                      << g << \" \"\r\n                      << b << std::endl;\r\n        }\r\n    }\r\n}\r\n\r\nvoid Canvas::print_canvas(std::string _title)\r\n{\r\n    // Create an output directory to store renders\r\n    // using the boost filesystem lib\r\n    std::string output_dir = \"../renders/\";\r\n    if (!boost::filesystem::exists(output_dir))\r\n    {\r\n        std::cout << \"Creating output directory for renders at: \" << output_dir << std::endl;\r\n        boost::filesystem::create_directory(output_dir);\r\n    }\r\n\r\n    // Output canvas into ppm file\r\n    std::ofstream image_file; \r\n    image_file.open (output_dir + _title.c_str()); \r\n    image_file << \"P3\\n\" << width << \" \" << height << \"\\n255\\n\";\r\n    for (int y = height-1; y >= 0; --y)\r\n    {\r\n        for (int x = 0; x < width; ++x)\r\n        {\r\n            int r = (int)(canvas[x][y].r() * 255.99f);\r\n            int g = (int)(canvas[x][y].g() * 255.99f);\r\n            int b = (int)(canvas[x][y].b() * 255.99f);\r\n\r\n            image_file << r << \" \" \r\n                       << g << \" \" \r\n                       << b << \"\\n\";\r\n        }\r\n    }\r\n    image_file.close();\r\n\r\n    std::cout << \"Printing \" << _title << \" to \" << output_dir << std::endl;\r\n}\r\n\r\n\r\nvoid Canvas::put_pixel(int x, int y, const color& _color)\r\n{\r\n    // Only color the pixel if it is within the bounds of the canvas\r\n    if (x > canvas.size() ||\r\n        y > canvas[0].size() ||\r\n        x < 0 || y < 0)\r\n    {\r\n        return;\r\n    }\r\n\r\n    // TODO\r\n    // This is done due to the issues with convert_ndc_to_canvas\r\n    // the 0.5f multiplication factor causes a 1.0 ndc value to be out of range\r\n    // using 0.49999f can work but can be inaccurate based on the resolution\r\n    if (x == canvas.size())\r\n    {\r\n        x--;\r\n    }\r\n    if (y == canvas[0].size())\r\n    {\r\n        y--;\r\n    }\r\n\r\n    canvas[x][y] = _color;\r\n}\r\n\r\nvoid swap(vec3 &p0, vec3 &p1)\r\n{\r\n    vec3 temp(p0);\r\n    p0 = p1;\r\n    p1 = temp;\r\n}\r\n\r\n// ==========================================\r\n// This function orders the list of vertices\r\n// by descending Y. \r\n// So that v[0].y >= v[1].y >= .. >= v[n-1].y\r\n// ==========================================\r\nvoid sort_desc(std::vector<vec3> &verts)\r\n{\r\n    for (int i = 0; i < verts.size(); ++i) \r\n    {\r\n        for (int j = i + 1; j < verts.size(); ++j) \r\n        {\r\n            if (verts[i].y() < verts[j].y())\r\n            {\r\n                swap(verts[i], verts[j]);\r\n            }\r\n        }\r\n    }\r\n}\r\n\r\n// ==========================================\r\n// Draws a model from a *.obj format\r\n// This is done by processing three vertices\r\n// within the face\r\n// ==========================================\r\nvoid Canvas::draw_model(Model model, const color& _color, bool is_wire)\r\n{\r\n    vec3 new_color = _color;\r\n    int nfaces = model.num_faces();\r\n    for (int i = 0; i < nfaces; ++i)\r\n    {\r\n        bool is_back_face = false;\r\n        // Check backface by using normal with scene camera\r\n\r\n        // Get the index of the vertices that comprise the face\r\n        std::vector<int> vert_indices = model.face(i);\r\n\r\n        vec3 p0 = model.vert(vert_indices[0]);\r\n        vec3 p1 = model.vert(vert_indices[1]);\r\n        vec3 p2 = model.vert(vert_indices[2]);\r\n\r\n        // TODO rethink how to handle drawing to NDC\r\n        // Need to rethink how to tie with camera functions\r\n        // Compute the direction of the normal and compare it with the light\r\n        vec3 normal = cross((p1-p0), (p2-p0));\r\n        normal.make_unit_vector();\r\n\r\n        // TODO check backface based on camera position?\r\n        vec3 cameraDir = camera.look_from - camera.look_at;\r\n        cameraDir.make_unit_vector();\r\n        is_back_face = dot(cameraDir, normal) < 0.0f;\r\n\r\n        if (!is_wire && !lights.empty() && !is_back_face)\r\n        {\r\n            // TODO calculate direction off each fragment instead of a single vertex for more accurate results\r\n            // TODO base light dir off of the center of the triangle\r\n            vec3 midPoint = (p2 - ((p0 - p1)*0.5f)) * 0.5f;\r\n\r\n            vec3 diffuse(0.0f);\r\n            for (auto light : lights)\r\n            {\r\n                vec3 light_dir = (light->pos) - midPoint;\r\n                light_dir.make_unit_vector();\r\n\r\n                diffuse += std::max(0.0f, dot(normal, light_dir)) * light->color;\r\n            }\r\n\r\n            float ambient = 0.2f;\r\n            new_color = (ambient + diffuse) * _color;\r\n        }\r\n\r\n        // TODO add depth buffer\r\n         \r\n\r\n        // Back-face culling - don't draw if it's a back-face\r\n        if (!is_back_face)\r\n        {\r\n            // Draw the triangles based on the position of the three vertices\r\n            draw_triangle(convert_ndc_to_canvas(p0),\r\n                    convert_ndc_to_canvas(p1),\r\n                    convert_ndc_to_canvas(p2),\r\n                    new_color,\r\n                    is_wire);\r\n        }\r\n    }\r\n}\r\n\r\nvoid Canvas::draw_line(vec3 p0, vec3 p1, const color& _color)\r\n{\r\n    int dx = p1.x() - p0.x();\r\n    int dy = p1.y() - p0.y();\r\n\r\n    // Check if p0 == p1, then just paint just that point\r\n    if (dx == 0 && dy == 0)\r\n    {\r\n        put_pixel(p0.x(), p0.y(), _color);\r\n        return;\r\n    }\r\n\r\n    // Draw line using y = f(x)\r\n    if (abs(dx) > abs(dy))\r\n    {\r\n        if (p0.x() > p1.x())\r\n        {\r\n            swap(p0, p1);\r\n        }\r\n\r\n        int x_end = p1.x();\r\n        float y = p0.y();\r\n        float m = (p1.y() - p0.y())/(p1.x() - p0.x());  // slope of line\r\n\r\n        for (int x = p0.x(); x < x_end; ++x) \r\n        {\r\n            put_pixel(x, (int)y, _color);\r\n            y += m; \r\n        } \r\n    }\r\n    // Draw line using x = f(y)\r\n    else \r\n    {\r\n        if (p0.y() > p1.y())\r\n        {\r\n            swap(p0, p1); \r\n        }\r\n\r\n        int y_end = p1.y(); \r\n        float x = p0.x(); \r\n        float m = (p1.x() - p0.x())/(p1.y() - p0.y());  // slope of line\r\n\r\n        for (int y = p0.y(); y < y_end; ++y)\r\n        {\r\n            put_pixel((int)x, y, _color);\r\n            x += m;\r\n        }\r\n    }\r\n}\r\n\r\n// ==========================================\r\n// Fills triangle by drawing lines from \r\n// bottom-most point p1/p2 to the top-most \r\n// point p0.\r\n//\r\n//     p0 \r\n//    /  \\ \r\n//   p1--p2\r\n//\r\n// precondition: p0.y > p1.y == p2.y\r\n// ==========================================\r\nvoid Canvas::fill_flat_bottom_triangle(vec3 p0, vec3 p1, vec3 p2, const color &_color)\r\n{\r\n    int dy = p0.y() - p1.y(); \r\n    float slope_p1_p0 = (p0.x() - p1.x())/(p0.y() - p1.y());\r\n    float slope_p2_p0 = (p0.x() - p2.x())/(p0.y() - p2.y());\r\n\r\n    for (int i = 0; i < dy; ++i) \r\n    {\r\n        p1.e[0] += slope_p1_p0; \r\n        p1.e[1] ++;\r\n        p2.e[0] += slope_p2_p0; \r\n        p2.e[1] ++;\r\n\r\n        draw_line(p1, p2, _color);\r\n    }\r\n}\r\n\r\n// =====================================\r\n// Fills triangle by drawing lines from \r\n// bottom most point p2 to the \r\n// top-most points p0 and p1.\r\n//\r\n//   p0--p1\r\n//    \\  /\r\n//     p2\r\n//\r\n// precondition: p0.y == p1.y > p2.y\r\n// =====================================\r\nvoid Canvas::fill_flat_top_triangle(vec3 p0, vec3 p1, vec3 p2, const color &_color)\r\n{\r\n    int dy = p0.y() - p2.y();\r\n    float slope_p2_p0 = (p0.x() - p2.x())/(p0.y() - p2.y());\r\n    float slope_p2_p1 = (p1.x() - p2.x())/(p1.y() - p2.y());\r\n\r\n    vec3 pa = p2;\r\n    vec3 pb = p2;\r\n\r\n    for (int i = 0; i < dy; ++i) \r\n    {\r\n        pa.e[0] += slope_p2_p0; \r\n        pa.e[1] ++;\r\n        pb.e[0] += slope_p2_p1; \r\n        pb.e[1] ++;\r\n\r\n        draw_line(pa, pb, _color);\r\n    }\r\n}\r\n\r\n//==========================================\r\n// Calculates the triangles barycentric coordinate\r\n//=========================================\r\nvec3 barycentric(vec3 p0, vec3 p1, vec3 p2)\r\n{\r\n    vec3 bp;\r\n}\r\n\r\n//==========================================\r\n// Draws a filled triangle, by splitting \r\n// a triangle into a flat bottom part and \r\n// flat top part. Then fills each line \r\n// horizontally.\r\n// =========================================\r\nvoid Canvas::draw_triangle_filled(vec3 p0, vec3 p1, vec3 p2, const color &_color)\r\n{\r\n    // sort vertices on descending y \r\n    std::vector<vec3> verts = {p0, p1, p2};\r\n    sort_desc(verts);  \r\n\r\n    p0 = verts[0]; \r\n    p1 = verts[1];\r\n    p2 = verts[2];\r\n\r\n    if ((int)p1.y() == (int)p2.y())\r\n    {\r\n        fill_flat_bottom_triangle(p0, p1, p2, _color);\r\n    }\r\n    else if ((int)p0.y() == (int)p1.y())\r\n    {\r\n        fill_flat_top_triangle(p0, p1, p2, _color);\r\n    }\r\n    else \r\n    {\r\n        // Split the triangle into 2 triangles \r\n        // one with a flat top and one with a flat bottom part\r\n        // \r\n        // precondition: p0.y > p1.y > p2.y\r\n        //\r\n\r\n        // slope from p0 to p2\r\n        float mx = (p2.x() - p0.x())/(p2.y() - p0.y());\r\n        // Get pa using pa = p0 + t(p2 - p0)\r\n        vec3 pa(p0.x() + (p1.y() - p0.y())*mx, p1.y(), 0.0f);\r\n\r\n        // Current use requires that p0.y > p1.y == pa.y\r\n        //                           p1.y == pa.y > p2.y\r\n        // due to the fill triangle method signature\r\n        fill_flat_bottom_triangle(p0, p1, pa, _color);\r\n        fill_flat_top_triangle(p1, pa, p2, _color);\r\n    }\r\n}\r\n\r\nvoid Canvas::draw_triangle_wireframe(vec3 p0, vec3 p1, vec3 p2, const color &_color)\r\n{\r\n    draw_line(p0, p1, _color);\r\n    draw_line(p1, p2, _color);\r\n    draw_line(p2, p0, _color);\r\n}\r\n\r\nvoid Canvas::draw_triangle(vec3 p0, vec3 p1, vec3 p2, const color &_color, bool is_wire)\r\n{\r\n    if (is_wire)\r\n    {\r\n        draw_triangle_wireframe(p0, p1, p2, _color);\r\n    }\r\n    else \r\n    {\r\n        draw_triangle_filled(p0, p1, p2, _color);\r\n    }\r\n}\r\n", "meta": {"hexsha": "20cc6750d6e204a1af1bd152308b1fe041a6f4f9", "size": 12225, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/canvas.cpp", "max_stars_repo_name": "danhuynh0803/Graphica", "max_stars_repo_head_hexsha": "06af9e49b2977498a0d6f7d2a01c1521290f4b7b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-07-02T04:18:38.000Z", "max_stars_repo_stars_event_max_datetime": "2020-07-02T04:18:38.000Z", "max_issues_repo_path": "src/canvas.cpp", "max_issues_repo_name": "danhuynh0803/Graffitica", "max_issues_repo_head_hexsha": "06af9e49b2977498a0d6f7d2a01c1521290f4b7b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/canvas.cpp", "max_forks_repo_name": "danhuynh0803/Graffitica", "max_forks_repo_head_hexsha": "06af9e49b2977498a0d6f7d2a01c1521290f4b7b", "max_forks_repo_licenses": ["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.3489932886, "max_line_length": 111, "alphanum_fraction": 0.4754192229, "num_tokens": 3410, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6001883735630721, "lm_q2_score": 0.519521321952093, "lm_q1q2_score": 0.31181065725376383}}
{"text": "// Copyright 2016-2019 Doug Moen\n// Licensed under the Apache License, version 2.0\n// See accompanying file LICENSE or https://www.apache.org/licenses/LICENSE-2.0\n\n#include <libcurv/builtin.h>\n\n#include <libcurv/analyser.h>\n#include <libcurv/array_op.h>\n#include <libcurv/die.h>\n#include <libcurv/dir_record.h>\n#include <libcurv/exception.h>\n#include <libcurv/function.h>\n#include <libcurv/sc_compiler.h>\n#include <libcurv/sc_context.h>\n#include <libcurv/import.h>\n#include <libcurv/math.h>\n#include <libcurv/pattern.h>\n#include <libcurv/picker.h>\n#include <libcurv/program.h>\n#include <libcurv/source.h>\n#include <libcurv/system.h>\n\n#include <boost/math/constants/constants.hpp>\n#include <boost/filesystem.hpp>\n\n#include <cassert>\n#include <climits>\n#include <cmath>\n#include <cstdlib>\n#include <string>\n\nusing namespace std;\nusing namespace boost::math::double_constants;\n\nnamespace curv {\n\nShared<Meaning>\nBuiltin_Value::to_meaning(const Identifier& id) const\n{\n    return make<Constant>(share(id), value_);\n}\n\nstruct Is_Null_Function : public Legacy_Function\n{\n    static const char* name() { return \"is_null\"; }\n    Is_Null_Function() : Legacy_Function(1,name()) {}\n    Value call(Frame& args) override\n    {\n        return {args[0].is_null()};\n    }\n};\nstruct Is_Bool_Function : public Legacy_Function\n{\n    static const char* name() { return \"is_bool\"; }\n    Is_Bool_Function() : Legacy_Function(1,name()) {}\n    Value call(Frame& args) override\n    {\n        return {isbool(args[0])};\n    }\n};\nstruct Is_Num_Function : public Legacy_Function\n{\n    static const char* name() { return \"is_num\"; }\n    Is_Num_Function() : Legacy_Function(1,name()) {}\n    Value call(Frame& args) override\n    {\n        return {isnum(args[0])};\n    }\n};\nstruct Is_String_Function : public Legacy_Function\n{\n    static const char* name() { return \"is_string\"; }\n    Is_String_Function() : Legacy_Function(1,name()) {}\n    Value call(Frame& args) override\n    {\n        return {args[0].dycast<String>() != nullptr};\n    }\n};\nstruct Is_List_Function : public Legacy_Function\n{\n    static const char* name() { return \"is_list\"; }\n    Is_List_Function() : Legacy_Function(1,name()) {}\n    Value call(Frame& args) override\n    {\n        return {islist(args[0])};\n    }\n};\nstruct Is_Record_Function : public Legacy_Function\n{\n    static const char* name() { return \"is_record\"; }\n    Is_Record_Function() : Legacy_Function(1,name()) {}\n    Value call(Frame& args) override\n    {\n        return {args[0].dycast<Record>() != nullptr};\n    }\n};\nstruct Is_Fun_Function : public Legacy_Function\n{\n    static const char* name() { return \"is_fun\"; }\n    Is_Fun_Function() : Legacy_Function(1,name()) {}\n    Value call(Frame& args) override\n    {\n        return {args[0].dycast<Function>() != nullptr};\n    }\n};\n\nstruct Bit_Function : public Legacy_Function\n{\n    static const char* name() { return \"bit\"; }\n    Bit_Function() : Legacy_Function(1,name()) {}\n    Value call(Frame& args) override\n    {\n        return {double(args[0].to_bool(At_Arg(*this, args)))};\n    }\n    SC_Value sc_call(SC_Frame& f) const override\n    {\n        auto arg = f[0];\n        if (arg.type != SC_Type::Bool())\n            throw Exception(At_SC_Arg(0, f),\n                stringify(name(),\": argument is not a bool\"));\n        auto result = f.sc_.newvalue(SC_Type::Num());\n        f.sc_.out() << \"  float \"<<result<<\" = float(\"<<arg<<\");\\n\";\n        return result;\n    }\n};\n\n#define UNARY_NUMERIC_FUNCTION(Class_Name,curv_name,c_name,glsl_name) \\\nstruct Class_Name : public Legacy_Function \\\n{ \\\n    static const char* name() { return #curv_name; } \\\n    Class_Name() : Legacy_Function(1,name()) {} \\\n    struct Scalar_Op { \\\n        static double call(double x) { return c_name(x); } \\\n        Shared<Operation> make_expr(Shared<Operation> x) const \\\n        { \\\n            return make<Call_Expr>( \\\n                cx.call_frame_.call_phrase_, \\\n                make<Constant>( \\\n                    func_part(cx.call_frame_.call_phrase_), \\\n                    Value{share(cx.fun_)}), \\\n                x); \\\n        } \\\n        static Shared<const String> callstr(Value x) { \\\n            return stringify(x); \\\n        } \\\n        At_Arg cx; \\\n        Scalar_Op(Function& fun, Frame& args) : cx(fun,args) {} \\\n    }; \\\n    static Unary_Numeric_Array_Op<Scalar_Op> array_op; \\\n    Value call(Frame& args) override \\\n    { \\\n        return array_op.op(Scalar_Op(*this, args), args[0]); \\\n    } \\\n    SC_Value sc_call(SC_Frame& f) const override \\\n    { \\\n        return sc_call_unary_numeric(f, #glsl_name); \\\n    } \\\n}; \\\n\nUNARY_NUMERIC_FUNCTION(Sqrt_Function, sqrt, sqrt, sqrt)\nUNARY_NUMERIC_FUNCTION(Log_Function, log, log, log)\nUNARY_NUMERIC_FUNCTION(Abs_Function, abs, abs, abs)\nUNARY_NUMERIC_FUNCTION(Floor_Function, floor, floor, floor)\nUNARY_NUMERIC_FUNCTION(Ceil_Function, ceil, ceil, ceil)\nUNARY_NUMERIC_FUNCTION(Trunc_Function, trunc, trunc, trunc)\nUNARY_NUMERIC_FUNCTION(Round_Function, round, rint, roundEven)\n\ninline double frac(double n) { return n - floor(n); }\nUNARY_NUMERIC_FUNCTION(Frac_Function, frac, frac, fract)\n\nUNARY_NUMERIC_FUNCTION(Sin_Function, sin, sin, sin)\nUNARY_NUMERIC_FUNCTION(Cos_Function, cos, cos, cos)\nUNARY_NUMERIC_FUNCTION(Tan_Function, tan, tan, tan)\nUNARY_NUMERIC_FUNCTION(Acos_Function, acos, acos, acos)\nUNARY_NUMERIC_FUNCTION(Asin_Function, asin, asin, asin)\nUNARY_NUMERIC_FUNCTION(Atan_Function, atan, atan, atan)\n\nUNARY_NUMERIC_FUNCTION(Sinh_Function, sinh, sinh, sinh)\nUNARY_NUMERIC_FUNCTION(Cosh_Function, cosh, cosh, cosh)\nUNARY_NUMERIC_FUNCTION(Tanh_Function, tanh, tanh, tanh)\nUNARY_NUMERIC_FUNCTION(Acosh_Function, acosh, acosh, acosh)\nUNARY_NUMERIC_FUNCTION(Asinh_Function, asinh, asinh, asinh)\nUNARY_NUMERIC_FUNCTION(Atanh_Function, atanh, atanh, atanh)\n\ndouble fhash(double f)\n{\n    union {\n        double f;\n        uint64_t u;\n    } data;\n    data.f = f;\n    data.u =\n        ((data.u & 0x000F'FFFF'FFFF'FFFF) // strip sign bit and exponent\n        | 0x3FF0'0000'0000'0000) // set sign to 0 and exponent to 0\n        ^ (data.u >> 12) // xor exponent and sign on top of mantissa\n        ;\n    // If f is normalized, then 1 <= data.f < 2.\n    // If f is denormalized, then 0 <= data.f < 1. This includes f==0.\n    return data.f - floor(data.f);\n}\nUNARY_NUMERIC_FUNCTION(Fhash_Function, fhash, fhash, fhash)\n\nstruct Atan2_Function : public Legacy_Function\n{\n    static const char* name() { return \"atan2\"; }\n    Atan2_Function() : Legacy_Function(2,name()) {}\n\n    struct Scalar_Op {\n        static double call(double x, double y) { return atan2(x, y); }\n        Shared<Operation> make_expr(\n            Shared<Operation> x, Shared<Operation> y) const\n        {\n            throw Exception(cx,\n                \"Internal error: atan2 applied to a reactive value\");\n            //return make<Divide_Expr>(share(syntax), std::move(x), std::move(y));\n        }\n        static const char* name() { return \"atan2\"; }\n        static Shared<const String> callstr(Value x, Value y) {\n            return stringify(\"[\",x,\",\",y,\"]\");\n        }\n        At_Arg cx;\n        Scalar_Op(Function& fun, Frame& args) : cx(fun, args) {}\n    };\n    static Binary_Numeric_Array_Op<Scalar_Op> array_op;\n    Value call(Frame& args) override\n    {\n        return array_op.op(Scalar_Op(*this, args), args[0], args[1]);\n    }\n    SC_Value sc_call(SC_Frame& f) const override\n    {\n        auto x = f[0];\n        auto y = f[1];\n\n        SC_Type rtype = SC_Type::Bool();\n        if (x.type == y.type)\n            rtype = x.type;\n        else if (x.type == SC_Type::Num())\n            rtype = y.type;\n        else if (y.type == SC_Type::Num())\n            rtype = x.type;\n        if (rtype == SC_Type::Bool())\n            throw Exception(At_SC_Phrase(f.call_phrase_, f),\n                \"domain error\");\n\n        SC_Value result = f.sc_.newvalue(rtype);\n        f.sc_.out() <<\"  \"<<rtype<<\" \"<<result<<\" = atan(\";\n        sc_put_as(f, x, At_SC_Arg(0, f), rtype);\n        f.sc_.out() << \",\";\n        sc_put_as(f, y, At_SC_Arg(1, f), rtype);\n        f.sc_.out() << \");\\n\";\n        return result;\n    }\n};\n\nSC_Value sc_minmax(const char* name, Operation& argx, SC_Frame& f)\n{\n    auto list = dynamic_cast<List_Expr*>(&argx);\n    if (list) {\n        std::list<SC_Value> args;\n        SC_Type type = SC_Type::Num();\n        for (auto op : *list) {\n            auto val = sc_eval_op(f, *op);\n            args.push_back(val);\n            if (val.type == SC_Type::Num())\n                ;\n            else if (val.type.is_vec()) {\n                if (type == SC_Type::Num())\n                    type = val.type;\n                else if (type != val.type)\n                    throw Exception(At_SC_Phrase(op->syntax_, f), stringify(\n                        name, \": vector arguments of different lengths\"));\n            } else {\n                throw Exception(At_SC_Phrase(op->syntax_, f), stringify(\n                    name,\": argument has bad type\"));\n            }\n        }\n        auto result = f.sc_.newvalue(type);\n        if (args.size() == 0)\n            f.sc_.out() << \"  \" << type << \" \" << result << \" = -0.0/0.0;\\n\";\n        else if (args.size() == 1)\n            return args.front();\n        else {\n            f.sc_.out() << \"  \" << type << \" \" << result << \" = \";\n            int rparens = 0;\n            while (args.size() > 2) {\n                f.sc_.out() << name << \"(\" << args.front() << \",\";\n                args.pop_front();\n                ++rparens;\n            }\n            f.sc_.out() << name << \"(\" << args.front() << \",\" << args.back() << \")\";\n            while (rparens > 0) {\n                f.sc_.out() << \")\";\n                --rparens;\n            }\n            f.sc_.out() << \";\\n\";\n        }\n        return result;\n    } else {\n        auto arg = sc_eval_op(f, argx);\n        auto result = f.sc_.newvalue(SC_Type::Num());\n        f.sc_.out() << \"  float \"<<result<<\" = \";\n        if (arg.type == SC_Type::Vec(2))\n            f.sc_.out() << name <<\"(\"<<arg<<\".x,\"<<arg<<\".y);\\n\";\n        else if (arg.type == SC_Type::Vec(3))\n            f.sc_.out() << name<<\"(\"<<name<<\"(\"<<arg<<\".x,\"<<arg<<\".y),\"\n                <<arg<<\".z);\\n\";\n        else if (arg.type == SC_Type::Vec(4))\n            f.sc_.out() << name<<\"(\"<<name<<\"(\"<<name<<\"(\"<<arg<<\".x,\"<<arg<<\".y),\"\n                <<arg<<\".z),\"<<arg<<\".w);\\n\";\n        else\n            throw Exception(At_SC_Phrase(argx.syntax_, f), stringify(\n                name,\": argument is not a vector\"));\n        return result;\n    }\n}\n\nstruct Max_Function : public Legacy_Function\n{\n    static const char* name() { return \"max\"; }\n    Max_Function() : Legacy_Function(1,name()) {}\n\n    struct Scalar_Op {\n        static double call(double x, double y) {\n            // return NaN if either argument is NaN.\n            if (x >= y) return x;\n            if (x < y) return y;\n            return 0.0/0.0;\n        }\n        Shared<Operation> make_expr(\n            Shared<Operation> x, Shared<Operation> y) const\n        {\n            Shared<List_Expr> args =\n                List_Expr::make({x, y}, arg_part(cx.call_frame_.call_phrase_));\n            args->init();\n            return make<Call_Expr>(\n                cx.call_frame_.call_phrase_,\n                make<Constant>(\n                    func_part(cx.call_frame_.call_phrase_),\n                    Value{share(cx.fun_)}),\n                args);\n        }\n        static const char* name() { return \"max\"; }\n        static Shared<const String> callstr(Value x, Value y) {\n            return stringify(\"[\",x,\",\",y,\"]\");\n        }\n        At_Arg cx;\n        Scalar_Op(Function& fun, Frame& args) : cx(fun,args) {}\n    };\n    static Binary_Numeric_Array_Op<Scalar_Op> array_op;\n    Value call(Frame& args) override\n    {\n        return array_op.reduce(Scalar_Op(*this, args), -INFINITY, args[0]);\n    }\n    SC_Value sc_call_expr(Operation& argx, Shared<const Phrase>, SC_Frame& f)\n    const override\n    {\n        return sc_minmax(name(),argx,f);\n    }\n};\n\nstruct Min_Function : public Legacy_Function\n{\n    static const char* name() { return \"min\"; }\n    Min_Function() : Legacy_Function(1,name()) {}\n\n    struct Scalar_Op {\n        static double call(double x, double y) {\n            // return NaN if either argument is NaN\n            if (x <= y) return x;\n            if (x > y) return y;\n            return 0.0/0.0;\n        }\n        Shared<Operation> make_expr(\n            Shared<Operation> x, Shared<Operation> y) const\n        {\n            Shared<List_Expr> args =\n                List_Expr::make({x, y}, arg_part(cx.call_frame_.call_phrase_));\n            args->init();\n            return make<Call_Expr>(\n                cx.call_frame_.call_phrase_,\n                make<Constant>(\n                    func_part(cx.call_frame_.call_phrase_),\n                    Value{share(cx.fun_)}),\n                args);\n        }\n        static const char* name() { return \"min\"; }\n        static Shared<const String> callstr(Value x, Value y) {\n            return stringify(\"[\",x,\",\",y,\"]\");\n        }\n        At_Arg cx;\n        Scalar_Op(Function& fun, Frame& args) : cx(fun, args) {}\n    };\n    static Binary_Numeric_Array_Op<Scalar_Op> array_op;\n    Value call(Frame& args) override\n    {\n        return array_op.reduce(Scalar_Op(*this, args), INFINITY, args[0]);\n    }\n    SC_Value sc_call_expr(Operation& argx, Shared<const Phrase>, SC_Frame& f)\n    const override\n    {\n        return sc_minmax(\"min\",argx,f);\n    }\n};\n\n// Generalized dot product that includes vector dot product and matrix product.\n// Same as Mathematica Dot[A,B]. Like APL A+.×B, Python numpy.dot(A,B)\nstruct Dot_Function : public Legacy_Function\n{\n    static const char* name() { return \"dot\"; }\n    Dot_Function() : Legacy_Function(2,name()) {}\n    Value call(Frame& args) override\n    {\n        return dot(args[0], args[1], At_Arg(*this, args));\n    }\n    SC_Value sc_call(SC_Frame& f) const override\n    {\n        auto a = f[0];\n        auto b = f[1];\n        if (!a.type.is_vec())\n            throw Exception(At_SC_Arg(0, f), \"dot: argument is not a vector\");\n        if (a.type != b.type)\n            throw Exception(At_SC_Arg(1, f), \"dot: arguments have different types\");\n        auto result = f.sc_.newvalue(SC_Type::Num());\n        f.sc_.out() << \"  float \"<<result<<\" = dot(\"<<a<<\",\"<<b<<\");\\n\";\n        return result;\n    }\n};\n\nstruct Mag_Function : public Legacy_Function\n{\n    static const char* name() { return \"mag\"; }\n    Mag_Function() : Legacy_Function(1,name()) {}\n    Value call(Frame& args) override\n    {\n        // TODO: use hypot() or BLAS DNRM2 or Eigen stableNorm/blueNorm?\n        // Avoids overflow/underflow due to squaring of large/small values.\n        // Slower.  https://forum.kde.org/viewtopic.php?f=74&t=62402\n        auto list = args[0].to<List>(At_Arg(*this, args));\n        // Fast path: assume we have a list of number, compute a result.\n        double sum = 0.0;\n        for (auto val : *list) {\n            double x = val.get_num_or_nan();\n            sum += x * x;\n        }\n        if (sum == sum)\n            return {sqrt(sum)};\n        // The computation failed. Second fastest path: assume a mix of numbers\n        // and reactive numbers, try to return a reactive result.\n        Shared<List_Expr> rlist =\n            List_Expr::make(list->size(),arg_part(args.call_phrase_));\n        for (unsigned i = 0; i < list->size(); ++i) {\n            Value val = list->at(i);\n            if (val.is_num()) {\n                rlist->at(i) = make<Constant>(arg_part(args.call_phrase_), val);\n                continue;\n            }\n            auto r = val.dycast<Reactive_Value>();\n            if (r && r->sctype_ == SC_Type::Num()) {\n                rlist->at(i) = r->expr(*arg_part(args.call_phrase_));\n                continue;\n            }\n            rlist = nullptr;\n            break;\n        }\n        if (rlist) {\n            rlist->init();\n            return {make<Reactive_Expression>(\n                SC_Type::Num(),\n                make<Call_Expr>(\n                    args.call_phrase_,\n                    make<Constant>(\n                        func_part(args.call_phrase_),\n                        Value{share(*this)}),\n                    rlist),\n                At_Arg(*this, args))};\n        }\n        throw Exception(At_Arg(*this, args),\n            stringify(args[0],\": domain error\"));\n    }\n    SC_Value sc_call(SC_Frame& f) const override\n    {\n        auto arg = f[0];\n        if (!arg.type.is_vec())\n            throw Exception(At_SC_Arg(0, f), \"mag: argument is not a vector\");\n        auto result = f.sc_.newvalue(SC_Type::Num());\n        f.sc_.out() << \"  float \"<<result<<\" = length(\"<<arg<<\");\\n\";\n        return result;\n    }\n};\n\nstruct Count_Function : public Legacy_Function\n{\n    static const char* name() { return \"count\"; }\n    Count_Function() : Legacy_Function(1,name()) {}\n    Value call(Frame& args) override\n    {\n        if (auto list = args[0].dycast<const List>())\n            return {double(list->size())};\n        if (auto string = args[0].dycast<const String>())\n            return {double(string->size())};\n        if (auto re = args[0].dycast<const Reactive_Value>()) {\n            if (re->sctype_.is_list())\n                return {double(re->sctype_.count())};\n            //TODO:\n            //if (re->sctype_ == SC_Type::Any())\n        }\n        throw Exception(At_Arg(*this, args), \"not a list or string\");\n    }\n    SC_Value sc_call(SC_Frame& f) const override\n    {\n        auto arg = f[0];\n        if (!arg.type.is_list())\n            throw Exception(At_SC_Arg(0, f), \"count: argument is not a list\");\n        auto result = f.sc_.newvalue(SC_Type::Num());\n        f.sc_.out() << \"  float \"<<result<<\" = \"<<arg.type.count()<<\";\\n\";\n        return result;\n    }\n};\nstruct Fields_Function : public Legacy_Function\n{\n    static const char* name() { return \"fields\"; }\n    Fields_Function() : Legacy_Function(1,name()) {}\n    Value call(Frame& args) override\n    {\n        if (auto record = args[0].dycast<const Record>())\n            return {record->fields()};\n        throw Exception(At_Arg(*this, args), \"not a record\");\n    }\n};\n\nstruct Strcat_Function : public Legacy_Function\n{\n    static const char* name() { return \"strcat\"; }\n    Strcat_Function() : Legacy_Function(1,name()) {}\n    Value call(Frame& args) override\n    {\n        if (auto list = args[0].dycast<const List>()) {\n            String_Builder sb;\n            for (auto val : *list) {\n                if (auto str = val.dycast<const String>())\n                    sb << str;\n                else\n                    sb << val;\n            }\n            return {sb.get_string()};\n        }\n        throw Exception(At_Arg(*this, args), \"not a list\");\n    }\n};\nstruct Repr_Function : public Legacy_Function\n{\n    static const char* name() { return \"repr\"; }\n    Repr_Function() : Legacy_Function(1,name()) {}\n    Value call(Frame& args) override\n    {\n        String_Builder sb;\n        sb << args[0];\n        return {sb.get_string()};\n    }\n};\nstruct Decode_Function : public Legacy_Function\n{\n    static const char* name() { return \"decode\"; }\n    Decode_Function() : Legacy_Function(1,name()) {}\n    Value call(Frame& f) override\n    {\n        String_Builder sb;\n        At_Arg cx(*this, f);\n        auto list = f[0].to<List>(cx);\n        for (size_t i = 0; i < list->size(); ++i)\n            sb << (char)(*list)[i].to_int(1, 127, At_Index(i,cx));\n        return {sb.get_string()};\n    }\n};\nstruct Encode_Function : public Legacy_Function\n{\n    static const char* name() { return \"encode\"; }\n    Encode_Function() : Legacy_Function(1,name()) {}\n    Value call(Frame& f) override\n    {\n        List_Builder lb;\n        At_Arg cx(*this, f);\n        auto str = f[0].to<String>(cx);\n        for (size_t i = 0; i < str->size(); ++i)\n            lb.push_back({(double)(int)str->at(i)});\n        return {lb.get_list()};\n    }\n};\n\nstruct Match_Function : public Legacy_Function\n{\n    static const char* name() { return \"match\"; }\n    Match_Function() : Legacy_Function(1,name()) {}\n    Value call(Frame& f) override\n    {\n        At_Arg ctx0(*this, f);\n        auto list = f[0].to<List>(ctx0);\n        std::vector<Shared<Function>> cases;\n        for (size_t i = 0; i < list->size(); ++i)\n            cases.push_back(list->at(i).to<Function>(At_Index(i,ctx0)));\n        auto mf = make<Piecewise_Function>(cases);\n        mf->name_ = name_;\n        mf->argpos_ = 1;\n        return {mf};\n    }\n};\n\n// The filename argument to \"file\", if it is a relative filename,\n// is interpreted relative to the parent directory of the source file from\n// which \"file\" is called.\n//\n// Because \"file\" has this hidden parameter (the name of the source file from\n// which it is called), it is not a pure function. For this reason, it isn't\n// a function value at all, it's a metafunction.\nstruct File_Expr : public Just_Expression\n{\n    Shared<Operation> arg_;\n    File_Expr(Shared<const Call_Phrase> src, Shared<Operation> arg)\n    :\n        Just_Expression(std::move(src)),\n        arg_(std::move(arg))\n    {}\n    virtual Value eval(Frame& f) const override\n    {\n        // Metafunction calls do not automatically get a new stack frame\n        // allocated. But I want the call to `file pathname` to appear\n        // in stack traces, so I need a Frame.\n        auto& callphrase = dynamic_cast<const Call_Phrase&>(*syntax_);\n        std::unique_ptr<Frame> f2 =\n            Frame::make(0, f.system_, &f, &callphrase, nullptr);\n        At_Metacall_With_Call_Frame cx(\"file\", 0, *f2);\n\n        // construct file pathname from argument\n        Value arg = arg_->eval(f);\n        auto argstr = arg.to<String>(cx);\n        namespace fs = boost::filesystem;\n        fs::path filepath;\n        auto caller_filename = syntax_->location().source().name_;\n        if (caller_filename->empty()) {\n            filepath = fs::path(argstr->c_str());\n        } else {\n            filepath = fs::path(caller_filename->c_str()).parent_path()\n                / fs::path(argstr->c_str());\n        }\n\n        return import(filepath, cx);\n    }\n};\nstruct File_Metafunction : public Metafunction\n{\n    using Metafunction::Metafunction;\n    virtual Shared<Meaning> call(const Call_Phrase& ph, Environ& env) override\n    {\n        return make<File_Expr>(share(ph), analyse_op(*ph.arg_, env));\n    }\n};\n\n/// The meaning of a call to `print`, such as `print \"foo\"`.\nstruct Print_Action : public Operation\n{\n    Shared<Operation> arg_;\n    Print_Action(\n        Shared<const Phrase> syntax,\n        Shared<Operation> arg)\n    :\n        Operation(std::move(syntax)),\n        arg_(std::move(arg))\n    {}\n    virtual void exec(Frame& f, Executor&) const override\n    {\n        Value arg = arg_->eval(f);\n        auto str = arg.dycast<String>();\n        if (str == nullptr)\n            str = stringify(arg);\n        f.system_.print(str->c_str());\n    }\n};\n/// The meaning of the phrase `print` in isolation.\nstruct Print_Metafunction : public Metafunction\n{\n    using Metafunction::Metafunction;\n    virtual Shared<Meaning> call(const Call_Phrase& ph, Environ& env) override\n    {\n        return make<Print_Action>(share(ph), analyse_op(*ph.arg_, env));\n    }\n};\n\nstruct Warning_Action : public Operation\n{\n    Shared<Operation> arg_;\n    Warning_Action(\n        Shared<const Phrase> syntax,\n        Shared<Operation> arg)\n    :\n        Operation(std::move(syntax)),\n        arg_(std::move(arg))\n    {}\n    virtual void exec(Frame& f, Executor&) const override\n    {\n        Value arg = arg_->eval(f);\n        Shared<String> msg;\n        if (auto str = arg.dycast<String>())\n            msg = str;\n        else\n            msg = stringify(arg);\n        Exception exc{At_Phrase(*syntax_, f), msg};\n        f.system_.warning(exc);\n    }\n};\n/// The meaning of the phrase `warning` in isolation.\nstruct Warning_Metafunction : public Metafunction\n{\n    using Metafunction::Metafunction;\n    virtual Shared<Meaning> call(const Call_Phrase& ph, Environ& env) override\n    {\n        return make<Warning_Action>(share(ph), analyse_op(*ph.arg_, env));\n    }\n};\n\n/// The meaning of a call to `error`, such as `error(\"foo\")`.\nstruct Error_Operation : public Operation\n{\n    Shared<Operation> arg_;\n    Error_Operation(\n        Shared<const Phrase> syntax,\n        Shared<Operation> arg)\n    :\n        Operation(std::move(syntax)),\n        arg_(std::move(arg))\n    {}\n    [[noreturn]] void run(Frame& f) const\n    {\n        Value val = arg_->eval(f);\n        Shared<const String> msg;\n        if (auto s = val.dycast<String>())\n            msg = s;\n        else\n            msg = stringify(val);\n        throw Exception{At_Phrase(*syntax_, f), msg};\n    }\n    virtual void exec(Frame& f, Executor&) const override\n    {\n        run(f);\n    }\n    virtual Value eval(Frame& f) const override\n    {\n        run(f);\n    }\n};\n/// The meaning of the phrase `error` in isolation.\nstruct Error_Metafunction : public Metafunction\n{\n    using Metafunction::Metafunction;\n    virtual Shared<Meaning> call(const Call_Phrase& ph, Environ& env) override\n    {\n        return make<Error_Operation>(share(ph), analyse_op(*ph.arg_, env));\n    }\n};\n\n// exec(expr) -- a debug action that evaluates expr, then discards the result.\n// It is used to call functions or source files for their side effects.\nstruct Exec_Action : public Operation\n{\n    Shared<Operation> arg_;\n    Exec_Action(\n        Shared<const Phrase> syntax,\n        Shared<Operation> arg)\n    :\n        Operation(std::move(syntax)),\n        arg_(std::move(arg))\n    {}\n    virtual void exec(Frame& f, Executor&) const override\n    {\n        arg_->eval(f);\n    }\n};\nstruct Exec_Metafunction : public Metafunction\n{\n    using Metafunction::Metafunction;\n    virtual Shared<Meaning> call(const Call_Phrase& ph, Environ& env) override\n    {\n        return make<Exec_Action>(share(ph), analyse_op(*ph.arg_, env));\n    }\n};\n\nstruct Assert_Action : public Operation\n{\n    Shared<Operation> arg_;\n    Assert_Action(\n        Shared<const Phrase> syntax,\n        Shared<Operation> arg)\n    :\n        Operation(std::move(syntax)),\n        arg_(std::move(arg))\n    {}\n    virtual void exec(Frame& f, Executor&) const override\n    {\n        At_Metacall cx{\"assert\", 0, *arg_->syntax_, f};\n        bool b = arg_->eval(f).to_bool(cx);\n        if (!b)\n            throw Exception(At_Phrase(*syntax_, f), \"assertion failed\");\n    }\n};\nstruct Assert_Metafunction : public Metafunction\n{\n    using Metafunction::Metafunction;\n    virtual Shared<Meaning> call(const Call_Phrase& ph, Environ& env) override\n    {\n        auto arg = analyse_op(*ph.arg_, env);\n        return make<Assert_Action>(share(ph), arg);\n    }\n};\n\nstruct Assert_Error_Action : public Operation\n{\n    Shared<Operation> expected_message_;\n    Shared<const String> actual_message_;\n    Shared<Operation> expr_;\n\n    Assert_Error_Action(\n        Shared<const Phrase> syntax,\n        Shared<Operation> expected_message,\n        Shared<const String> actual_message,\n        Shared<Operation> expr)\n    :\n        Operation(std::move(syntax)),\n        expected_message_(std::move(expected_message)),\n        actual_message_(std::move(actual_message)),\n        expr_(std::move(expr))\n    {}\n\n    virtual void exec(Frame& f, Executor&) const override\n    {\n        Value expected_msg_val = expected_message_->eval(f);\n        auto expected_msg_str = expected_msg_val.to<const String>(\n            At_Phrase(*expected_message_->syntax_, f));\n\n        if (actual_message_ != nullptr) {\n            if (*actual_message_ != *expected_msg_str)\n                throw Exception(At_Phrase(*syntax_, f),\n                    stringify(\"assertion failed: expected error \\\"\",\n                        expected_msg_str,\n                        \"\\\", actual error \\\"\",\n                        actual_message_,\n                        \"\\\"\"));\n            return;\n        }\n\n        Value result;\n        try {\n            result = expr_->eval(f);\n        } catch (Exception& e) {\n            if (*e.shared_what() != *expected_msg_str) {\n                throw Exception(At_Phrase(*syntax_, f),\n                    stringify(\"assertion failed: expected error \\\"\",\n                        expected_msg_str,\n                        \"\\\", actual error \\\"\",\n                        e.shared_what(),\n                        \"\\\"\"));\n            }\n            return;\n        }\n        throw Exception(At_Phrase(*syntax_, f),\n            stringify(\"assertion failed: expected error \\\"\",\n                expected_msg_str,\n                \"\\\", got value \", result));\n    }\n};\nstruct Assert_Error_Metafunction : public Metafunction\n{\n    using Metafunction::Metafunction;\n    virtual Shared<Meaning> call(const Call_Phrase& ph, Environ& env) override\n    {\n        auto parens = cast<Paren_Phrase>(ph.arg_);\n        Shared<Comma_Phrase> commas = nullptr;\n        if (parens) commas = cast<Comma_Phrase>(parens->body_);\n        if (parens && commas && commas->args_.size() == 2) {\n            auto msg = analyse_op(*commas->args_[0].expr_, env);\n            Shared<Operation> expr = nullptr;\n            Shared<const String> actual_msg = nullptr;\n            try {\n                expr = analyse_op(*commas->args_[1].expr_, env);\n            } catch (Exception& e) {\n                actual_msg = e.shared_what();\n            }\n            return make<Assert_Error_Action>(share(ph), msg, actual_msg, expr);\n        } else {\n            throw Exception(At_Phrase(ph, env),\n                \"assert_error: expecting 2 arguments\");\n        }\n    }\n};\n\nstruct Defined_Expression : public Just_Expression\n{\n    Shared<const Operation> expr_;\n    Symbol_Expr selector_;\n\n    Defined_Expression(\n        Shared<const Phrase> syntax,\n        Shared<const Operation> expr,\n        Symbol_Expr selector)\n    :\n        Just_Expression(std::move(syntax)),\n        expr_(std::move(expr)),\n        selector_(std::move(selector))\n    {\n    }\n\n    virtual Value eval(Frame& f) const override\n    {\n        auto val = expr_->eval(f);\n        auto s = val.dycast<Record>();\n        if (s) {\n            auto id = selector_.eval(f);\n            return {s->hasfield(id)};\n        } else {\n            return {false};\n        }\n    }\n};\nstruct Defined_Metafunction : public Metafunction\n{\n    using Metafunction::Metafunction;\n    virtual Shared<Meaning> call(const Call_Phrase& ph, Environ& env) override\n    {\n        auto arg = analyse_op(*ph.arg_, env);\n        auto dot = cast<Dot_Expr>(arg);\n        if (dot != nullptr)\n            return make<Defined_Expression>(\n                share(ph), dot->base_, dot->selector_);\n        throw Exception(At_Phrase(*ph.arg_, env),\n            \"defined: argument must be `expression.identifier`\");\n    }\n};\n\nconst Namespace&\nbuiltin_namespace()\n{\n    #define FUNCTION(f) {f::name(), make<Builtin_Value>(Value{make<f>()})}\n\n    static const Namespace names = {\n    {\"pi\", make<Builtin_Value>(pi)},\n    {\"tau\", make<Builtin_Value>(two_pi)},\n    {\"inf\", make<Builtin_Value>(INFINITY)},\n    {\"null\", make<Builtin_Value>(Value())},\n    {\"false\", make<Builtin_Value>(Value(false))},\n    {\"true\", make<Builtin_Value>(Value(true))},\n\n    FUNCTION(Is_Null_Function),\n    FUNCTION(Is_Bool_Function),\n    FUNCTION(Is_Num_Function),\n    FUNCTION(Is_String_Function),\n    FUNCTION(Is_List_Function),\n    FUNCTION(Is_Record_Function),\n    FUNCTION(Is_Fun_Function),\n    FUNCTION(Bit_Function),\n    FUNCTION(Sqrt_Function),\n    FUNCTION(Log_Function),\n    FUNCTION(Abs_Function),\n    FUNCTION(Floor_Function),\n    FUNCTION(Ceil_Function),\n    FUNCTION(Trunc_Function),\n    FUNCTION(Round_Function),\n    FUNCTION(Frac_Function),\n    FUNCTION(Fhash_Function),\n    FUNCTION(Sin_Function),\n    FUNCTION(Cos_Function),\n    FUNCTION(Tan_Function),\n    FUNCTION(Asin_Function),\n    FUNCTION(Acos_Function),\n    FUNCTION(Atan_Function),\n    FUNCTION(Atan2_Function),\n    FUNCTION(Sinh_Function),\n    FUNCTION(Cosh_Function),\n    FUNCTION(Tanh_Function),\n    FUNCTION(Asinh_Function),\n    FUNCTION(Acosh_Function),\n    FUNCTION(Atanh_Function),\n    FUNCTION(Max_Function),\n    FUNCTION(Min_Function),\n    FUNCTION(Dot_Function),\n    FUNCTION(Mag_Function),\n    FUNCTION(Count_Function),\n    FUNCTION(Fields_Function),\n    FUNCTION(Strcat_Function),\n    FUNCTION(Repr_Function),\n    FUNCTION(Decode_Function),\n    FUNCTION(Encode_Function),\n    FUNCTION(Match_Function),\n\n    {\"file\", make<Builtin_Meaning<File_Metafunction>>()},\n    {\"print\", make<Builtin_Meaning<Print_Metafunction>>()},\n    {\"warning\", make<Builtin_Meaning<Warning_Metafunction>>()},\n    {\"error\", make<Builtin_Meaning<Error_Metafunction>>()},\n    {\"assert\", make<Builtin_Meaning<Assert_Metafunction>>()},\n    {\"assert_error\", make<Builtin_Meaning<Assert_Error_Metafunction>>()},\n    {\"exec\", make<Builtin_Meaning<Exec_Metafunction>>()},\n    {\"defined\", make<Builtin_Meaning<Defined_Metafunction>>()},\n    };\n    return names;\n}\n\n} // namespace curv\n", "meta": {"hexsha": "37d4a9e997c042f48bdc588205bba7921a843658", "size": 32851, "ext": "cc", "lang": "C++", "max_stars_repo_path": "libcurv/builtin.cc", "max_stars_repo_name": "p-e-w/curv", "max_stars_repo_head_hexsha": "a5e3231e7cc96b24df73c0e5cc43e7de00b74727", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "libcurv/builtin.cc", "max_issues_repo_name": "p-e-w/curv", "max_issues_repo_head_hexsha": "a5e3231e7cc96b24df73c0e5cc43e7de00b74727", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "libcurv/builtin.cc", "max_forks_repo_name": "p-e-w/curv", "max_forks_repo_head_hexsha": "a5e3231e7cc96b24df73c0e5cc43e7de00b74727", "max_forks_repo_licenses": ["Apache-2.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.6875621891, "max_line_length": 84, "alphanum_fraction": 0.5819609753, "num_tokens": 8138, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.600188359260205, "lm_q2_score": 0.519521321952093, "lm_q1q2_score": 0.3118106498231194}}
{"text": "/*\n * This file is part of the statismo library.\n *\n * Author: Marcel Luethi (marcel.luethi@unibas.ch)\n *\n * Copyright (c) 2011 University of Basel\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * Redistributions of source code must retain the above copyright notice,\n * this list of conditions and the following disclaimer.\n *\n * Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and/or other materials provided with the distribution.\n *\n * Neither the name of the project's author nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED\n * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n */\n\n\n#include \"LowRankGPModelBuilder.h\"\n#include \"StatisticalModel.h\"\n#include \"vtkPolyDataReader.h\"\n#include \"vtkStandardMeshRepresenter.h\"\n\n#include \"Kernels.h\"\n#include \"KernelCombinators.h\"\n\n#include <iostream>\n#include <boost/scoped_ptr.hpp>\n\nusing namespace statismo;\n\n\n/**\n * A scalar valued gaussian kernel.\n */\nclass GaussianKernel: public ScalarValuedKernel<vtkPoint> {\n  public:\n\n    GaussianKernel(double sigma) : m_sigma(sigma), m_sigma2(sigma * sigma) {\n    }\n\n    inline double operator()(const vtkPoint& x, const vtkPoint& y) const {\n        VectorType r(3);\n        r << x[0] - y[0], x[1] - y[1], x[2] - y[2];\n        return exp(-r.dot(r) / m_sigma2);\n    }\n\n    std::string GetKernelInfo() const {\n        std::ostringstream os;\n        os << \"GaussianKernel(\" << m_sigma << \")\";\n        return os.str();\n    }\n\n  private:\n\n    double m_sigma;\n    double m_sigma2;\n};\n\n\nvtkPolyData* loadVTKPolyData(const std::string& filename) {\n    vtkPolyDataReader* reader = vtkPolyDataReader::New();\n    reader->SetFileName(filename.c_str());\n    reader->Update();\n    vtkPolyData* pd = vtkPolyData::New();\n    pd->ShallowCopy(reader->GetOutput());\n    return pd;\n}\n\n\n\n//\n// This example illustrates, how the flexibility of a statistical (shape) model can be extended by combining its covariance function\n// with a Gaussian Kernel function.\n//\nint main(int argc, char** argv) {\n\n    if (argc < 5) {\n        std::cout << \"Usage \" << argv[0] << \" model gaussianKernelWidth numberOfComponents, outputmodelName\" << std::endl;\n        exit(-1);\n    }\n    std::string modelFilename(argv[1]);\n    double gaussianKernelSigma = std::atof(argv[2]);\n    int numberOfComponents = std::atoi(argv[3]);\n    std::string outputModelFilename(argv[4]);\n\n\n    // All the statismo classes have to be parameterized with the RepresenterType.\n\n    typedef vtkStandardMeshRepresenter RepresenterType;\n    typedef LowRankGPModelBuilder<vtkPolyData> ModelBuilderType;\n    typedef StatisticalModel<vtkPolyData> StatisticalModelType;\n    typedef GaussianKernel GaussianKernelType;\n    typedef MatrixValuedKernel<vtkPoint> MatrixValuedKernelType;\n\n    try {\n\n        // we load an existing statistical model and create a StatisticalModelKernel from it. The statisticlModelKernel\n        // takes the covariance (matrix) of the model and defines a kernel function from it.\n        vtkStandardMeshRepresenter* representer = vtkStandardMeshRepresenter::Create();\n        boost::scoped_ptr<StatisticalModelType> model(StatisticalModelType::Load(representer, modelFilename));\n        const MatrixValuedKernelType& statModelKernel = StatisticalModelKernel<vtkPolyData>(model.get());\n\n        // Create a (scalar valued) gaussian kernel. This kernel is then made matrix-valued. We use a UncorrelatedMatrixValuedKernel,\n        // which assumes that each output component is independent.\n\n        const GaussianKernel gk = GaussianKernel(gaussianKernelSigma);\n        const MatrixValuedKernelType& mvGk = UncorrelatedMatrixValuedKernel<vtkPoint>(&gk, model->GetRepresenter()->GetDimensions());\n\n        // We scale the kernel (and hence the resulting deformations) of the Gaussian kernel by  a factor of 100, in order\n        // to achieve a visible effect.\n        const MatrixValuedKernelType& scaledGk = ScaledKernel<vtkPoint>(&mvGk, 100.0);\n\n        // The model kernel and the Gaussian kernel are combined to a new kernel.\n        const MatrixValuedKernelType& combinedModelAndGaussKernel = SumKernel<vtkPoint>(&statModelKernel, &scaledGk);\n\n        // We create a new model using the combined kernel. The new model will be more flexible than the original statistical model.\n        boost::scoped_ptr<ModelBuilderType> modelBuilder(ModelBuilderType::Create(model->GetRepresenter()));\n        boost::scoped_ptr<StatisticalModelType> combinedModel(modelBuilder->BuildNewModel(model->DrawMean(), combinedModelAndGaussKernel, numberOfComponents));\n\n        // Once we have built the model, we can save it to disk.\n        combinedModel->Save(outputModelFilename);\n        std::cout << \"Successfully saved shape model as \" << outputModelFilename << std::endl;\n\n    } catch (StatisticalModelException& e) {\n        std::cout << \"Exception occured while building the shape model\" << std::endl;\n        std::cout << e.what() << std::endl;\n    }\n}\n", "meta": {"hexsha": "29aa4d4eba81070634bf7fc9c617c7bfa13e06f6", "size": 5984, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "modules/VTK/examples/vtkBuildGaussianProcessShapeModelExample.cxx", "max_stars_repo_name": "tom-albrecht/statismo", "max_stars_repo_head_hexsha": "e7825afadb1accc4902d911d5f00a8c4bd383a31", "max_stars_repo_licenses": ["BSD-3-Clause"], "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/VTK/examples/vtkBuildGaussianProcessShapeModelExample.cxx", "max_issues_repo_name": "tom-albrecht/statismo", "max_issues_repo_head_hexsha": "e7825afadb1accc4902d911d5f00a8c4bd383a31", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/VTK/examples/vtkBuildGaussianProcessShapeModelExample.cxx", "max_forks_repo_name": "tom-albrecht/statismo", "max_forks_repo_head_hexsha": "e7825afadb1accc4902d911d5f00a8c4bd383a31", "max_forks_repo_licenses": ["BSD-3-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.8933333333, "max_line_length": 159, "alphanum_fraction": 0.7242647059, "num_tokens": 1354, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.600188359260205, "lm_q2_score": 0.5195213219520929, "lm_q1q2_score": 0.31181064982311935}}
{"text": "#ifndef HEADER_SHAPEMODEL\n#define HEADER_SHAPEMODEL\n\n#include <string>\n#include <iostream>\n#include <armadillo>\n#include <set>\n#include <map>\n#include <limits>\n\n#include <ShapeUQLib/FrameGraph.hpp>\n\n\n\n\nclass Element;\n\n/**\nDeclaration of the ShapeModel class. Base class for \nthe implementation of shape model\n*/\ntemplate <class PointType>\nclass ShapeModel {\n\npublic:\n\n\t/**\n\tConstructor\n\t*/\n\tShapeModel();\n\n\n\t/**\n\tConstructor\n\t@param frame_graph Pointer to the graph storing\n\treference frame relationships\n\t@param frame_graph Pointer to the reference frame graph\n\t*/\n\tShapeModel(std::string ref_frame_name,\n\t\tFrameGraph * frame_graph);\n\n\n\t/**\n\tReturns the dimensions of the bounding box\n\t@param Bounding box dimension to be computed (xmin,ymin,zmin,xmax,ymax,zmax)\n\t*/\n\tvoid get_bounding_box(double * bounding_box,arma::mat M = arma::eye<arma::mat>(3,3)) const;\n\n\n\t/**\n\tTranslates the shape model by x\n\t@param x translation vector applied to the coordinates of each control point\n\t*/\n\tvoid translate(const arma::vec::fixed<3> &);\n\n\t/**\n\tRotates the shape model by \n\t@param M rotation matrix\n\t*/\n\tvoid rotate(const arma::mat::fixed<3,3> & M);\n\n\t\n\t\n\t/**\n\tShifts the coordinates of the shape model\n\tso as to have (0,0,0) aligned with its barycenter\n\tThe resulting barycenter coordinates are (0,0,0)\n\t*/\n\tvoid shift_to_barycenter();\n\n\t/**\n\tApplies a rotation that aligns the body\n\twith its principal axes.\n\tThis assumes that the body has been shifted so\n\tthat (0,0,0) lies at its barycenter\n\tThe resulting inertia tensor is diagonal\n\tUndefined behavior if\n\tthe inertia tensor has not been computed beforehand\n\t*/\n\tvoid align_with_principal_axes();\n\n\t\n\n\n\t/**\n\tReturns the volume of the provided shape model\n\t@return volume (U^2 where U is the unit of the shape coordinates)\n\t*/\n\tdouble get_volume() const;\n\n\n\t/**\n\tReturns the principal axes and principal moments of the shape model\n\t@param axes M as in X = MX' where X' is a position expressed in the principal frame\n\t@param moments dimensionless inertia moments in ascending order\n\t*/\t\n\tvoid get_principal_inertias(arma::mat & axes,arma::vec & moments) const;\n\n\n\n\t/**\n\tDefines the reference frame attached to the shape model\n\t@param ref_frame Pointer to the reference frame attached\n\tto the shape model\n\t*/\n\tvoid set_ref_frame_name(std::string ref_frame_name);\n\n\t/**\n\tReturns the name of the reference frame attached to this\n\tref frame\n\t@return name of reference frame\n\t*/\n\tstd::string get_ref_frame_name() const;\n\n\n\tPointType & get_point(unsigned int i) ;\n\tconst arma::vec::fixed<3> & get_point_coordinates(unsigned int i) const;\n\n\tvirtual arma::vec::fixed<3> get_point_normal_coordinates(unsigned int i) const = 0;\n\n\t/**\n\tPointer to the shape model's control points\n\t@return vertices pointer to the control points\n\t*/\n\tconst std::vector<PointType> & get_points() const;\n\n\tunsigned int get_point_index(std::shared_ptr<PointType> point) const;\n\n\t\n\n\t/**\n\tReturns the geometrical center of the shape\n\t@return geometrical center\n\t*/\n\tarma::vec::fixed<3> get_center() const;\n\t\n\t\n\t/**\n\tAugment the internal container storing vertices with a new (and not already inserted)\n\tone\n\t@param control_point pointer to the new control point to be inserted\n\t*/\n\tvoid add_control_point(PointType & control_point);\n\n\tvirtual void clear() = 0;\n\n\t/**\n\tReturns number of elements\n\t@return number of elements\n\t*/\n\tvirtual unsigned int get_NElements() const  = 0;\n\n\t/**\n\tReturns number of control points\n\t@return number of control points\n\t*/\n\tunsigned int get_NControlPoints() const ;\n\n\t/**\n\tComputes the surface area of the shape model\n\t*/\n\tvirtual void compute_surface_area() = 0;\n\t/**\n\tComputes the volume of the shape model\n\t*/\n\tvirtual void compute_volume() = 0;\n\n\t/**\n\tComputes the center of mass of the shape model\n\t*/\n\tvirtual void compute_center_of_mass() = 0;\n\t/**\n\tComputes the inertia tensor of the shape model\n\t*/\n\tvirtual void compute_inertia() = 0;\n\n\t\n\n\n\t/**\n\tConstructs a connectivity table associated a control point pointer to its index\n\tin this shape model control points vector\n\t*/\n\tvoid initialize_index_table();\n\n\t/**\n\tReturns the non-dimensional inertia tensor of the body in the body-fixed\n\tprincipal axes. (rho == 1, l = (volume)^(1/3))\n\t@return principal inertia tensor\n\t*/\n\tconst arma::mat::fixed<3,3> & get_inertia() const;\n\n\t/**\n\tUpdates shape geometric and mass properties\n\t*/\n\tvirtual void update_mass_properties() = 0;\n\n\t/**\n\tReturns the surface area of the shape model\n\t@return surface area (U^2 where U is the unit of the shape coordinates)\n\t*/\n\tdouble get_surface_area() const;\n\n\t\n\t/**\n\tReturns the location of the center of mass\n\t@return pointer to center of mass\n\t*/\n\tconst arma::vec::fixed<3> & get_center_of_mass() const;\n\n\t/**\n\tBuilds the covariance of the provided control points\n\t@param P covariance to set\n\t@param Ci pointer to first point\n\t@param Cj pointer to second point\n\t@param Ck pointer to third point\n\t@param Cl pointer to fourth point\n\t@param Cm pointer to fifth point\n\t@param Cp pointer to sixth point\n\t*/\n\tstatic void assemble_covariance(arma::mat & P,\n\t\tconst PointType & Ci,\n\t\tconst PointType & Cj,\n\t\tconst PointType & Ck,\n\t\tconst PointType & Cl,\n\t\tconst PointType & Cm,\n\t\tconst PointType & Cp);\n\n\t/**\n\tBuilds the covariance of the provided control points\n\t@param P covariance to set\n\t@param Ci pointer to first point\n\t@param Cj pointer to second point\n\t@param Ck pointer to third point\n\t@param Cl pointer to fourth point\n\t@param Cm pointer to fifth point\n\t@param Cp pointer to sixth point\n\t@param Cq pointer to seventh point\n\t*/\n\tstatic void assemble_covariance(arma::mat & P,\n\t\tconst PointType & Ci,\n\t\tconst PointType & Cj,\n\t\tconst PointType & Ck,\n\t\tconst PointType & Cl,\n\t\tconst PointType & Cm,\n\t\tconst PointType & Cp,\n\t\tconst PointType & Cq);\n\n\n\t/**\n\tBuilds the covariance of the provided control points\n\t@param P covariance to set\n\t@param Ci pointer to first point\n\t@param Cj pointer to second point\n\t@param Ck pointer to third point\n\t@param Cl pointer to fourth point\n\t@param Cm pointer to fifth point\n\t@param Cp pointer to sixth point\n\t@param Cq pointer to seventh point\n\t@param Cq pointer to eigth point\n\t*/\n\tstatic void assemble_covariance(arma::mat & P,\n\t\tconst PointType & Ci,\n\t\tconst PointType & Cj,\n\t\tconst PointType & Ck,\n\t\tconst PointType & Cl,\n\t\tconst PointType & Cm,\n\t\tconst PointType & Cp,\n\t\tconst PointType & Cq,\n\t\tconst PointType & Cr);\n\n\n\t/**\n\tReturns radius of circumscribing sphere, measured from the shape's center of mass\n\t@return radius of circumscribing sphere\n\t*/\n\tdouble get_circumscribing_radius() const;\n\n\n\n\tarma::vec get_inertia_param() const;\n\n\tvirtual const std::vector<int> & get_element_control_points(int e) const = 0;\n\nprotected:\n\n\tstd::vector<std::set<int> > edges;\n\tstd::vector<PointType> control_points;\n\n\tstd::map<std::shared_ptr<PointType> ,unsigned int> pointer_to_global_index;\n\n\tFrameGraph * frame_graph;\n\tstd::string ref_frame_name;\n\n\tarma::mat::fixed<3,3> inertia;\n\tarma::vec::fixed<3> cm;\n\tdouble volume;\n\tdouble surface_area;\n\n\n\t/**\n\tRadius of sphere of equivalent volume\n\t*/\n\tdouble r_avg;\n\n\n\n\n\n};\n\n#endif", "meta": {"hexsha": "3451b9a6987d9fdf371d00ccf6a9eecefb5c1d2a", "size": 7035, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/ShapeUQLib/ShapeModel.hpp", "max_stars_repo_name": "bbercovici/ShapeUQLib", "max_stars_repo_head_hexsha": "4906704270ab306f799c88336b4b35484e89eb1b", "max_stars_repo_licenses": ["MIT"], "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/ShapeUQLib/ShapeModel.hpp", "max_issues_repo_name": "bbercovici/ShapeUQLib", "max_issues_repo_head_hexsha": "4906704270ab306f799c88336b4b35484e89eb1b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/ShapeUQLib/ShapeModel.hpp", "max_forks_repo_name": "bbercovici/ShapeUQLib", "max_forks_repo_head_hexsha": "4906704270ab306f799c88336b4b35484e89eb1b", "max_forks_repo_licenses": ["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.5480769231, "max_line_length": 92, "alphanum_fraction": 0.7312011372, "num_tokens": 1753, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6187804478040617, "lm_q2_score": 0.5039061705290805, "lm_q1q2_score": 0.3118072858512143}}
{"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#ifndef GRAPHLAB_RANDOM_HPP\n#define GRAPHLAB_RANDOM_HPP\n\n#include <cstdlib>\n#include <stdint.h>\n\n\n#include <vector>\n#include <limits>\n#include <algorithm>\n\n#include <boost/random.hpp>\n#include <graphlab/util/timer.hpp>\n#include <graphlab/parallel/pthread_tools.hpp>\n\nnamespace graphlab {\n\n  /**\n   * \\ingroup random\n   * A collection of thread safe random number routines.  Each thread\n   * is assigned its own generator however assigning a seed affects\n   * all current and future generators.\n   */\n  namespace random {        \n\n\n    ///////////////////////////////////////////////////////////////////////\n    //// Underlying generator definition\n\n\n\n    namespace distributions {\n      /**\n       * The uniform distribution struct is used for partial function\n       * specialization. Generating uniform random real numbers is\n       * accomplished slightly differently than for integers.\n       * Therefore the base case is for integers and we then\n       * specialize the two real number types (floats and doubles).\n       */\n      template<typename IntType>\n      struct uniform {\n        typedef boost::uniform_int<IntType> distribution_type;\n        template<typename RealRNG, typename DiscreteRNG>\n        static inline IntType sample(RealRNG& real_rng, \n                                     DiscreteRNG& discrete_rng, \n                                     const IntType& min, const IntType& max) {\n          return distribution_type(min, max)(discrete_rng);\n        }\n      };\n      template<>\n      struct uniform<double> {\n        typedef boost::uniform_real<double> distribution_type;\n        template<typename RealRNG, typename DiscreteRNG>\n        static inline double sample(RealRNG& real_rng, \n                                    DiscreteRNG& discrete_rng, \n                                    const double& min, const double& max) {\n          return distribution_type(min, max)(real_rng);\n        }\n      };\n      template<>\n      struct uniform<float> {\n        typedef boost::uniform_real<float> distribution_type;\n        template<typename RealRNG, typename DiscreteRNG>\n        static inline float sample(RealRNG& real_rng, \n                                  DiscreteRNG& discrete_rng, \n                                  const float& min, const float& max) {\n          return distribution_type(min, max)(real_rng);\n        }\n      };\n    }; // end of namespace distributions\n\n    /**\n     * The generator class is the base underlying type used to\n     * generate random numbers.  User threads should use the functions\n     * provided in the random namespace.\n     */\n    class generator {\n    public:\n      // base Generator types\n      typedef boost::lagged_fibonacci607 real_rng_type;\n      typedef boost::mt11213b            discrete_rng_type;  \n      typedef boost::rand48              fast_discrete_rng_type;       \n    \n      generator() {\n        time_seed();\n      }\n    \n      //! Seed the generator using the default seed\n      inline void seed() {\n        mut.lock();\n        real_rng.seed();\n        discrete_rng.seed();\n        fast_discrete_rng.seed();\n        mut.unlock();\n      }\n\n      //! Seed the generator nondeterministically\n      void nondet_seed();\n\n\n      //! Seed the generator using the current time in microseconds\n      inline void time_seed() {\n        seed( graphlab::timer::usec_of_day() );\n      }\n\n      //! Seed the random number generator based on a number\n      void seed(size_t number) {\n        mut.lock();\n        fast_discrete_rng.seed(number);\n        real_rng.seed(fast_discrete_rng);\n        discrete_rng.seed(fast_discrete_rng);\n        mut.unlock();\n      }\n      \n      //! Seed the generator using another generator\n      void seed(generator& other){\n        mut.lock();\n        real_rng.seed(other.real_rng);\n        discrete_rng.seed(other.discrete_rng);\n        fast_discrete_rng.seed(other.fast_discrete_rng());\n        mut.unlock();\n      } \n   \n      /**\n       * Generate a random number in the uniform real with range [min,\n       * max) or [min, max] if the number type is discrete.\n       */\n      template<typename NumType>\n      inline NumType uniform(const NumType min, const NumType max) { \n        mut.lock();\n        const NumType result = distributions::uniform<NumType>::\n          sample(real_rng, discrete_rng, min, max);\n        mut.unlock();\n        return result;\n      } // end of uniform\n\n      /**\n       * Generate a random number in the uniform real with range [min,\n       * max) or [min, max] if the number type is discrete.\n       */\n      template<typename NumType>\n      inline NumType fast_uniform(const NumType min, const NumType max) { \n        mut.lock();\n        const NumType result = distributions::uniform<NumType>::\n          sample(real_rng, fast_discrete_rng, min, max);\n        mut.unlock();\n        return result;\n      } // end of fast_uniform\n\n\n      /**\n       * Generate a random number in the uniform real with range [min,\n       * max);\n       */\n      inline double gamma(const double alpha = double(1)) {\n        boost::gamma_distribution<double> gamma_dist(alpha);\n        mut.lock();\n        const double result = gamma_dist(real_rng);\n        mut.unlock();\n        return result;\n      } // end of gamma\n\n\n      /**\n       * Generate a gaussian random variable with zero mean and unit\n       * variance.\n       */\n      inline double gaussian(const double mean = double(0), \n                             const double stdev = double(1)) {\n        boost::normal_distribution<double> normal_dist(mean,stdev);\n        mut.lock();\n        const double result = normal_dist(real_rng);\n        mut.unlock();\n        return result;\n      } // end of gaussian\n\n      /**\n       * Generate a gaussian random variable with zero mean and unit\n       * variance.\n       */\n      inline double normal(const double mean = double(0), \n                           const double stdev = double(1)) {\n        return gaussian(mean, stdev);\n      } // end of normal\n\n\n      inline bool bernoulli(const double p = double(0.5)) {\n        boost::bernoulli_distribution<double> dist(p);\n        mut.lock();\n        const double result(dist(discrete_rng));\n        mut.unlock();\n        return result;\n      } // end of bernoulli\n\n      inline bool fast_bernoulli(const double p = double(0.5)) {\n        boost::bernoulli_distribution<double> dist(p);\n        mut.lock();\n        const double result(dist(fast_discrete_rng));\n        mut.unlock();\n        return result;\n      } // end of bernoulli\n\n\n      /**\n       * Draw a random number from a multinomial\n       */\n      template<typename Double>\n      size_t multinomial(const std::vector<Double>& prb) {\n        ASSERT_GT(prb.size(),0);\n        if (prb.size() == 1) { return 0; }\n        Double sum(0);\n        for(size_t i = 0; i < prb.size(); ++i) {\n          ASSERT_GE(prb[i], 0); // Each entry must be P[i] >= 0\n          sum += prb[i];\n        }\n        ASSERT_GT(sum, 0); // Normalizer must be positive\n        // actually draw the random number\n        const Double rnd(uniform<Double>(0,1));\n        size_t ind = 0;\n        for(Double cumsum(prb[ind]/sum); \n            rnd > cumsum && (ind+1) < prb.size(); \n            cumsum += (prb[++ind]/sum));\n        return ind;\n      } // end of multinomial\n\n\n      /**\n       * Generate a draw from a multinomial using a CDF.  This is\n       * slightly more efficient since normalization is not required\n       * and a binary search can be used.\n       */\n      template<typename Double>\n      inline size_t multinomial_cdf(const std::vector<Double>& cdf) {\n        return std::upper_bound(cdf.begin(), cdf.end(),\n                                uniform<Double>(0,1)) - cdf.begin();\n        \n      } // end of multinomial_cdf\n\n\n      /** \n       * Construct a random permutation\n       */ \n      template<typename T>\n      inline std::vector<T> permutation(const size_t nelems) { \n        std::vector<T> perm(nelems);\n        for(T i = 0; i < nelems; ++i) perm[i] = i;\n        shuffle(perm);\n        return perm;\n      } // end of construct a permutation\n      \n      /** \n       * Shuffle a standard vector\n       */ \n      template<typename T>\n      void shuffle(std::vector<T>& vec) { shuffle(vec.begin(), vec.end()); }\n\n      /** \n       * Shuffle a range using the begin and end iterators\n       */ \n      template<typename Iterator>\n      void shuffle(Iterator begin, Iterator end) {\n        mut.lock();\n        shuffle_functor functor(*this);\n        std::random_shuffle(begin, end, functor);\n        mut.unlock();\n      } // end of shuffle\n\n    private:\n      //////////////////////////////////////////////////////\n      /// Data members\n      struct shuffle_functor {\n        generator& gen;\n        inline shuffle_functor(generator& gen) : gen(gen) { }\n        inline std::ptrdiff_t operator()(std::ptrdiff_t end) {\n          return distributions::uniform<ptrdiff_t>::\n            sample(gen.real_rng, gen.fast_discrete_rng, 0, end-1);\n        }\n      };\n\n      \n      //! The real random number generator\n      real_rng_type real_rng;\n      //! The discrete random number generator\n      discrete_rng_type discrete_rng;\n      //! The fast discrete random number generator\n      fast_discrete_rng_type fast_discrete_rng;\n      //! lock used to access local members\n      mutex mut;      \n    }; // end of class generator\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n    /**\n     * \\ingroup random\n     * Seed all generators using the default seed\n     */\n    void seed();\n\n    /**\n     * \\ingroup random\n     * Seed all generators using an integer\n     */\n    void seed(size_t seed_value);\n\n    /**\n     * \\ingroup random\n     * Seed all generators using a nondeterministic source\n     */\n    void nondet_seed();\n\n    /**\n     * \\ingroup random\n     * Seed all generators using the current time in microseconds\n     */\n    void time_seed();\n    \n\n    /**\n     * \\ingroup random\n     * Get the local generator\n     */\n    generator& get_source();\n\n    /**\n     * \\ingroup random\n     * Generate a random number in the uniform real with range [min,\n     * max) or [min, max] if the number type is discrete.\n     */\n    template<typename NumType>\n    inline NumType uniform(const NumType min, const NumType max) { \n      if (min == max) return min;\n      return get_source().uniform<NumType>(min, max);\n    } // end of uniform\n    \n    /**\n     * \\ingroup random\n     * Generate a random number in the uniform real with range [min,\n     * max) or [min, max] if the number type is discrete.\n     */\n    template<typename NumType>\n    inline NumType fast_uniform(const NumType min, const NumType max) { \n      if (min == max) return min;\n      return get_source().fast_uniform<NumType>(min, max);\n    } // end of fast_uniform\n    \n    /**\n     * \\ingroup random\n     * Generate a random number between 0 and 1\n     */\n    inline double rand01() { return uniform<double>(0, 1); }\n\n    /**\n     * \\ingroup random\n     * Simulates the standard rand function as defined in cstdlib\n     */\n    inline int rand() { return fast_uniform(0, RAND_MAX); }\n\n\n    /**\n     * \\ingroup random\n     * Generate a random number from a gamma distribution.\n     */\n    inline double gamma(const double alpha = double(1)) {\n      return get_source().gamma(alpha);\n    }\n\n\n\n    /**\n     * \\ingroup random\n     * Generate a gaussian random variable with zero mean and unit\n     * standard deviation.\n     */\n    inline double gaussian(const double mean = double(0), \n                           const double stdev = double(1)) {\n      return get_source().gaussian(mean, stdev);\n    }\n\n    /**\n     * \\ingroup random\n     * Generate a gaussian random variable with zero mean and unit\n     * standard deviation.\n     */\n    inline double normal(const double mean = double(0), \n                         const double stdev = double(1)) {\n      return get_source().normal(mean, stdev);\n    }\n\n    /**\n     * \\ingroup random\n     * Draw a sample from a bernoulli distribution\n     */\n    inline bool bernoulli(const double p = double(0.5)) {\n      return get_source().bernoulli(p);\n    }\n\n    /**\n     * \\ingroup random\n     * Draw a sample form a bernoulli distribution using the faster generator\n     */\n    inline bool fast_bernoulli(const double p = double(0.5)) {\n      return get_source().fast_bernoulli(p);\n    }\n\n    /**\n     * \\ingroup random\n     * Generate a draw from a multinomial.  This function\n     * automatically normalizes as well.\n     */\n    template<typename Double>\n    inline size_t multinomial(const std::vector<Double>& prb) {\n      return get_source().multinomial(prb);\n    }\n\n\n    /**\n     * \\ingroup random\n     * Generate a draw from a cdf;\n     */\n    template<typename Double>\n    inline size_t multinomial_cdf(const std::vector<Double>& cdf) {\n      return get_source().multinomial_cdf(cdf);\n    }\n\n\n\n    /** \n     * \\ingroup random\n     * Construct a random permutation\n     */ \n    template<typename T>\n    inline std::vector<T> permutation(const size_t nelems) { \n      return get_source().permutation<T>(nelems); \n    }\n\n\n    /** \n     * \\ingroup random\n     * Shuffle a standard vector\n     */ \n    template<typename T>\n    inline void shuffle(std::vector<T>& vec) { \n      get_source().shuffle(vec); \n    }\n   \n    /** \n     * \\ingroup random\n     * Shuffle a range using the begin and end iterators\n     */ \n    template<typename Iterator>\n    inline void shuffle(Iterator begin, Iterator end) {\n      get_source().shuffle(begin, end);\n    }\n\n    /**\n     * Converts a discrete PDF into a CDF\n     */\n    void pdf2cdf(std::vector<double>& pdf);\n\n\n    \n  }; // end of random \n}; // end of graphlab\n\n\n#endif\n\n", "meta": {"hexsha": "9c49e502d7139441f3a319935392d4785d939d5d", "size": 14343, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/graphlab/util/random.hpp", "max_stars_repo_name": "coreyp1/graphlab", "max_stars_repo_head_hexsha": "637be90021c5f83ab7833ca15c48e76039057969", "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": "src/graphlab/util/random.hpp", "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": "src/graphlab/util/random.hpp", "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": 28.5149105368, "max_line_length": 78, "alphanum_fraction": 0.5884403542, "num_tokens": 3187, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7057850402140659, "lm_q2_score": 0.44167300566462553, "lm_q1q2_score": 0.31172620006447505}}
{"text": "/*\n\ncreateDiffusionTensorImage.cxx\nBishesh Khanal\nAsclepios, INRIA Sophia Antipolis\n\nA test program to create diffusion tensor images of desired size.\n\n*/\n\n#include <iostream>\n#include <string>\n#include <sstream>\n#include <boost/program_options.hpp>\n\n#include <itkImage.h>\n#include <itkImageFileReader.h>\n#include <itkImageFileWriter.h>\n#include <itkDiffusionTensor3D.h>\n\n#undef __FUNCT__\n#define __FUNCT__ \"main\"\nint main(int argc, char **argv)\n{\n    std::string inRefFileName, outFileName;         //input reference file for origin and spacings; name of the output file to be created.\n    std::string elements;       //elements of the tensor separted by comma, without spaces in lower triangular order.\n    double D[6];            //six diffusion tensor elements, in LT order.\n\n    //-------------- Set up the command line options-------------------------\n    boost::program_options::options_description optionsDescription(\"Possible options\");\n    optionsDescription.add_options()\n            (\"help,h\", \"displays help message\")\n            (\"reference,r\", boost::program_options::value< std::string >(&inRefFileName), \"input reference file\")\n            (\"output,o\", boost::program_options::value< std::string >(&outFileName), \"output filename\")\n            (\"elements,e\",boost::program_options::value< std::string >(&elements), \"elements separted by comma without any spaces in lower traingular order\")\n            ;\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        std::cout<<optionsDescription<<std::endl;\n        return EXIT_SUCCESS;\n    }\n\n    //Confirm all the options required are given.\n    if(!options.count(\"reference\") || !options.count(\"output\") || !options.count(\"elements\")) {\n        std::cerr<<\"invalid options! run with --help or -h to see the proper options.\"<<std::endl;\n        return EXIT_FAILURE;\n    }\n\n    //Parse the elements into number from the string:\n    {\n        std::stringstream ss(elements);\n        std::cout<<\"what is in elements: \"<<ss.str()<<std::endl;\n        unsigned int i = 0;\n        while(ss>>D[i++]) { //get the string until comma to first element of D and then increase i.\n            if(ss.peek() == ',') //Still don't know why ss>> gives output upto comma, did not see\n                ss.ignore();        //it in the documentation!\n        }\n    }\n\n    //Check if the elements are properly parsed into D array.\n    //for (int i=0;i<6;++i)\n    //    std::cout<<std::endl<<D[i];\n\n    //---------------------  Read the reference image type ----------------------//\n    typedef itk::Image<double, 3>                       ScalarImageType;\n    typedef itk::ImageFileReader<ScalarImageType>       ScalarImageReaderType;\n\n    ScalarImageReaderType::Pointer reader = ScalarImageReaderType::New();\n    reader->SetFileName(inRefFileName);\n    reader->Update();\n    ScalarImageType::Pointer refImg = reader->GetOutput();\n\n    //-------------------- Tensor Image -------------------------------------//\n    typedef itk::Image<itk::DiffusionTensor3D<double>, 3>       TensorImageType;\n    TensorImageType::Pointer tensorImage = TensorImageType::New();\n\n    //------------ Get important details from the reference image ------------//\n    tensorImage->SetRegions(refImg->GetLargestPossibleRegion());\n    tensorImage->SetOrigin(refImg->GetOrigin());\n    tensorImage->SetSpacing(refImg->GetSpacing());\n    tensorImage->SetDirection(refImg->GetDirection());\n\n    // ----------- Allocate memory ---------------------------//\n    tensorImage->Allocate();\n\n    // Fill the voxels with the input tensor value\n    tensorImage->FillBuffer(D);\n\n    // Test how the values are stored:\n    std::cout<<\"origin: \"<<tensorImage->GetOrigin()<<std::endl;\n    std::cout<<\"direction: \"<<tensorImage->GetDirection()<<std::endl;\n    TensorImageType::IndexType posTensor;\n    for (unsigned int i = 0; i<3; ++i) posTensor.SetElement(i,10);\n    std::cout<<\"Tensor value: \"<<tensorImage->GetPixel(posTensor)<<std::endl;\n    std::cout<<\"Tensor values again:\\n\"<<tensorImage->GetPixel(posTensor)(0,0)<<\"\\t\"<<tensorImage->GetPixel(posTensor)(0,1)<<\"\\t\"<<tensorImage->GetPixel(posTensor)(0,2)<<std::endl;\n    std::cout<<tensorImage->GetPixel(posTensor)(1,0)<<\"\\t\"<<tensorImage->GetPixel(posTensor)(1,1)<<\"\\t\"<<tensorImage->GetPixel(posTensor)(1,2)<<std::endl;\n    std::cout<<tensorImage->GetPixel(posTensor)(2,0)<<\"\\t\"<<tensorImage->GetPixel(posTensor)(2,1)<<\"\\t\"<<tensorImage->GetPixel(posTensor)(2,2)<<std::endl;\n\n    //------------ Write output image -------------------------//\n    typedef itk::ImageFileWriter<TensorImageType>       TensorImageWriterType;\n    TensorImageWriterType::Pointer writer = TensorImageWriterType::New();\n    writer->SetFileName(outFileName);\n    writer->SetInput(tensorImage);\n    writer->Update();\n\n    return EXIT_SUCCESS;\n}\n\n", "meta": {"hexsha": "8721e5dcd415d8cc2c043377582a7f4aa6d71634", "size": 4997, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "src/createDiffusionTensorImage.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/createDiffusionTensorImage.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/createDiffusionTensorImage.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": 43.8333333333, "max_line_length": 180, "alphanum_fraction": 0.6429857915, "num_tokens": 1176, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5660185205547239, "lm_q2_score": 0.5506073655352405, "lm_q1q2_score": 0.3116539664467909}}
{"text": "////////////////////////////////////////////////////////////////////////////////////\n//  Geometric utilities for multicamera calibration\n//\n//  Copyright (C) 2016  David Alejo, Fernando Caballero, Luis Merino \n//  Universidad Pablo de Olavide\n//  Seville, Spain.\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////////////////////////////////////////////////////////////////////////////////////\n\n#ifndef GEOMETRIC_UTILS__\n#define GEOMETRIC_UTILS__\n\n#include <boost/random/normal_distribution.hpp>\n#include <boost/random/mersenne_twister.hpp>\n#include <boost/random/variate_generator.hpp>\n#include <boost/concept_check.hpp>\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n\n#ifndef  CALI_VEC_SIZE \n#define CALI_VEC_SIZE 7\n#endif\n\ntypedef boost::variate_generator<boost::mt19937, boost::normal_distribution<> > NormalDist;\nstatic NormalDist norm_dist(boost::mt19937(time(0)), boost::normal_distribution<>(0, 1.0));\n\n\n// --------------------------- General utilities ----------------------------------\ndouble f_rand(double fMin = 0.0, double fMax = 1.0)\n{\n  static bool init = false;\n  if (!init) {\n    init = true;\n    srand(time(NULL));\n  }\n  double f = (double)rand() / RAND_MAX;\n  return fMin + f * (fMax - fMin);\n}\n\nstd::vector<double> eigen2stdvec(const Eigen::Vector3d &v) {\n  std::vector<double> ret;\n  ret.resize(3);\n  for (int i = 0; i < 3; i++) {\n    ret[i] = v[i];\n  }\n  return ret;\n}\n\n\n// ----------------- Geometric utilities ------------------------------\n\n\n//! Gets a transformation from a parameter\nEigen::Affine3d getTransform(const double *p) \n{\n  // Get the transformation matrix T from p vector\n  Eigen::Affine3d T = Eigen::Affine3d::Identity();\n  Eigen::Quaterniond R(p[0], p[1], p[2], p[3]);\n  T.rotate(R);\n  T.pretranslate(Eigen::Vector3d(p[4], p[5], p[6]));\n    \n  return T;\n}\n\nvoid decomposeTransform(const Eigen::Affine3d &T, Eigen::Quaterniond &q, Eigen::Vector3d &v) {\n  Eigen::Quaterniond d(T.rotation( ));\n  q = d;\n  v[0] = T(0,3);\n  v[1] = T(1,3);\n  v[2] = T(2,3);\n}\n\nbool quat2rotvec(const Eigen::Quaterniond &q, Eigen::Vector3d &v) {\n  double norm = sqrt(1 - q.w());\n  if (norm < 1e-4) { \n    // Too small rotation\n    v[0] = v[1] = v[2] = 0.0;\n    return false;\n  }\n  norm = 1 / norm;\n  v[0] = q.x() * norm;\n  v[1] = q.y() * norm;\n  v[2] = q.z() * norm;\n  \n  return true;\n}\n\nEigen::Quaterniond euler2quat(double roll, double pitch, double yaw) {\n  Eigen::AngleAxisd yawAngle(yaw, Eigen::Vector3d(0.0, 0.0, 1.0));\n  Eigen::AngleAxisd rollAngle(roll, Eigen::Vector3d(1.0, 0.0, 0.0));\n  Eigen::AngleAxisd pitchAngle(pitch, Eigen::Vector3d(0.0, 1.0, 0.0));\n  Eigen::Quaterniond q =  yawAngle * pitchAngle * rollAngle; // 3-2-1\n \n  return q;\n}\n\n// Returns the 3-2-1 body angles in [roll, pitch, yaw]\nEigen::Vector3d quat2euler(const Eigen::Quaterniond &q) {\n  Eigen::Vector3d ret;\n  double w = q.w(), x = q.x(), y = q.y(), z = q.z();\n  \n  ret[0] = atan2(2*(w*x + y*z), 1 - 2*(x*x + y*y));\n  ret[1] = asin(0.9999999* (2*(w*y - z*x)));\n//   cout << \"x = \" << asin(1.0) << endl;\n  ret[2] = atan2(2*(w*z + x*y), 1 - 2*(y*y + z*z));\n  \n  return ret;\n}\n\n#endif", "meta": {"hexsha": "8798951e4c06bc55a0e845516501dc01d23b0221", "size": 3548, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/plane_detector/geometric_utilities.hpp", "max_stars_repo_name": "robotics-upo/plane_detector", "max_stars_repo_head_hexsha": "c3ca7d25b5be9c7d7063489523bed9388d4a5ee0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 42.0, "max_stars_repo_stars_event_min_datetime": "2018-08-02T01:08:15.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-18T05:11:27.000Z", "max_issues_repo_path": "include/plane_detector/geometric_utilities.hpp", "max_issues_repo_name": "robotics-upo/plane_detector", "max_issues_repo_head_hexsha": "c3ca7d25b5be9c7d7063489523bed9388d4a5ee0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2019-07-17T04:03:03.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-27T11:02:45.000Z", "max_forks_repo_path": "include/plane_detector/geometric_utilities.hpp", "max_forks_repo_name": "robotics-upo/plane_detector", "max_forks_repo_head_hexsha": "c3ca7d25b5be9c7d7063489523bed9388d4a5ee0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2018-08-03T07:15:20.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-03T06:33:38.000Z", "avg_line_length": 29.5666666667, "max_line_length": 94, "alphanum_fraction": 0.6000563698, "num_tokens": 1085, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5660185205547239, "lm_q2_score": 0.5506073655352404, "lm_q1q2_score": 0.31165396644679083}}
{"text": "#pragma once\n\n// system includes ------------------------------------------------------------\n#include <Eigen/Sparse>\n#include <boost/iterator/filter_iterator.hpp>\n#include <boost/mpl/identity.hpp>\n#include <functional>\n#include <type_traits>\n#include <iterator>\n#include <tuple>\n\n// own includes ------------------------------------------------------------\n#include \"spectral/basis/spectral_basis.hpp\"\n#include \"spectral/basis/spectral_elem_accessor.hpp\"\n#include \"spectral/basis/spectral_basis_factory_hermite.hpp\"\n#include \"spectral/basis/spectral_basis_factory_ks.hpp\"\n\n\nnamespace boltzmann {\n\nnamespace spectral {\n\n// ----------------------------------------------------------------------\ntemplate <typename BASIS>\nunsigned int\nget_max_l(const BASIS& basis)\n{\n  typedef typename std::tuple_element<0, typename BASIS::elem_t::container_t>::type elem_t;\n  // radial basis\n  typename BASIS::elem_t::Acc::template get<elem_t> get_xir;\n  unsigned int maxL = 0;\n  for (auto it = basis.begin(); it != basis.end(); ++it) {\n    unsigned int l = get_xir(*it).get_id().l;\n    if (l > maxL) maxL = l;\n  }\n\n  return maxL;\n}\n\n// ----------------------------------------------------------------------\n/**\n * @Brief Return the max polynomial degree for the Polar-Laguerre basis\n *\n * @param basis\n *\n * @return\n */\ntemplate <typename BASIS>\ntypename std::enable_if<std::is_same<typename BASIS::elem_t::container_t,\n                                     typename ::boltzmann::SpectralBasisFactoryKS::elem_t::container_t\n                                     >::value,\n                        unsigned int>::type\nget_max_k(const BASIS& basis)\n{\n  typedef typename std::tuple_element<1, typename BASIS::elem_t::container_t>::type elem_t;\n  typename BASIS::elem_t::Acc::template get<elem_t> get_phi;\n  unsigned int maxK = 0;\n  for (auto it = basis.begin(); it != basis.end(); ++it) {\n    unsigned int k = get_phi(*it).get_id().k;\n    if (k > maxK) maxK = k;\n  }\n  return maxK;\n}\n\n\n// ----------------------------------------------------------------------\n/**\n * @Brief Return the max polynomial degree for the Polar-Laguerre basis\n *\n * @param basis\n *\n * @return\n */\ntemplate <typename BASIS>\ntypename std::enable_if<std::is_same<typename BASIS::elem_t::container_t,\n                                     typename ::boltzmann::SpectralBasisFactoryKS::elem_t::container_t\n                                     >::value,\n                        unsigned int>::type\nget_K(const BASIS& basis)\n{\n  typedef typename std::tuple_element<1, typename BASIS::elem_t::container_t>::type elem_t;\n  typename BASIS::elem_t::Acc::template get<elem_t> get_phi;\n  unsigned int maxK = 0;\n  for (auto it = basis.begin(); it != basis.end(); ++it) {\n    unsigned int k = get_phi(*it).get_id().k;\n    if (k > maxK) maxK = k;\n  }\n  return maxK+1;\n}\n\n\n// ----------------------------------------------------------------------\n/**\n * @Brief Return the max polynomial degree for the Hermite basis\n *\n * @param basis\n *\n * @return\n */\ntemplate <typename BASIS>\ntypename std::enable_if<std::is_same<typename BASIS::elem_t::container_t,\n                                     typename ::boltzmann::SpectralBasisFactoryHN::elem_t::container_t\n                                     >::value,\n                        unsigned int>::type\nget_K(const BASIS& basis)\n{\n  typedef typename std::tuple_element<0, typename BASIS::elem_t::container_t>::type hx_t;\n  typedef typename std::tuple_element<1, typename BASIS::elem_t::container_t>::type hy_t;\n  typename BASIS::elem_t::Acc::template get<hx_t> get_hx;\n  unsigned int maxKx = 0;\n  for (auto it = basis.begin(); it != basis.end(); ++it) {\n    unsigned int k = get_hx(*it).get_id().k;\n    if (k > maxKx) maxKx = k;\n  }\n\n  typename BASIS::elem_t::Acc::template get<hy_t> get_hy;\n  unsigned int maxKy = 0;\n  for (auto it = basis.begin(); it != basis.end(); ++it) {\n    unsigned int k = get_hx(*it).get_id().k;\n    if (k > maxKy) maxKy = k;\n  }\n\n  return std::max(maxKx, maxKy)+1;\n}\n\n\n#ifdef USE_CXX14\n/**\n * @brief return boost::filter_iterator with basis functions that have angular frequency \\f$ l \\f$.\n *\n * @param begin\n * @param end\n * @param l    angular frequency\n *\n * @return\n */\ntemplate <typename ITERATOR>\nauto\nfilter_freq(const ITERATOR& begin,\n            const typename boost::mpl::identity<ITERATOR>::type& end,\n            unsigned int l)\n{\n  typedef typename std::iterator_traits<ITERATOR>::value_type elem_t;\n\n  typedef typename std::tuple_element<0, typename elem_t::container_t>::type aelem_t;\n\n  auto f = [l](const elem_t& elem) {\n    typename elem_t::Acc::template get<aelem_t> get_xir;\n    return get_xir(elem).get_id().l == l;\n  };\n\n  return std::make_tuple(boost::make_filter_iterator(f, begin, end),\n                         boost::make_filter_iterator(f, end, end));\n}\n\n/**\n * @brief return boost::filter_iterator with basis functions that total polynomial degree \\f$ k \\f$.\n *\n * @param begin\n * @param end\n * @param k    polynomial degree\n *\n * @return\n */\ntemplate <typename ITERATOR>\nauto\nfilter_deg(const ITERATOR& begin,\n           const typename boost::mpl::identity<ITERATOR>::type& end,\n           unsigned int k)\n{\n  typedef typename std::iterator_traits<ITERATOR>::value_type elem_t;\n\n  typedef typename std::tuple_element<1, typename elem_t::container_t>::type aelem_t;\n\n  auto f = [k](const elem_t& elem) {\n    typename elem_t::Acc::template get<aelem_t> get_lag;\n    return get_lag(elem).get_id().k == k;\n  };\n\n  return std::make_tuple(boost::make_filter_iterator(f, begin, end),\n                         boost::make_filter_iterator(f, end, end));\n}\n#endif  // USE_CXX14\n\n}  // end namespace spectral_basis\n}  // end namespace boltzmann\n", "meta": {"hexsha": "2f57ce12bd530e63e893ff2268ae30c7960f1dfd", "size": 5671, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/spectral/basis/toolbox/spectral_basis.hpp", "max_stars_repo_name": "simonpintarelli/2dBoltzmann", "max_stars_repo_head_hexsha": "bc6b7bbeffa242ce80937947444383b416ba3fc9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/spectral/basis/toolbox/spectral_basis.hpp", "max_issues_repo_name": "simonpintarelli/2dBoltzmann", "max_issues_repo_head_hexsha": "bc6b7bbeffa242ce80937947444383b416ba3fc9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/spectral/basis/toolbox/spectral_basis.hpp", "max_forks_repo_name": "simonpintarelli/2dBoltzmann", "max_forks_repo_head_hexsha": "bc6b7bbeffa242ce80937947444383b416ba3fc9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.3262032086, "max_line_length": 102, "alphanum_fraction": 0.6041262564, "num_tokens": 1386, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5698526514141571, "lm_q2_score": 0.546738151984614, "lm_q1q2_score": 0.31156018553770864}}
{"text": "#include <vector>\n#include <string>\n#include <iostream>\n#include <sstream>\n#include <memory>\n\n#include <boost/lexical_cast.hpp>\n\nstruct Token\n{\n    enum Type { integer, plus, minus, lparen, rparen } type;\n\n    std::string text;\n\n    friend std::ostream& operator<<(std::ostream& oss, const Token& token)\n    {\n        return oss << \"'\" << token.text << \"'\";\n    }\n};\n\nstd::vector<Token> lex(const std::string& input)\n{\n    std::vector<Token> result;\n\n    for(size_t i = 0; i < input.size(); i++)\n    {\n        switch(input[i])\n        {\n            case '+':\n                result.push_back( { Token::plus, \"+\" } );\n                break;\n            case '-':\n                result.push_back( { Token::minus, \"-\" } );\n                break;\n            case '(':\n                result.push_back( { Token::lparen, \"(\" } );\n                break;\n            case ')':\n                result.push_back( { Token::rparen, \")\" } );\n                break;\n            default:\n                std::ostringstream buffer;\n                buffer << input[i];\n                for(size_t j = i + 1; j < input.size(); j++)\n                {\n                    if(std::isdigit(input[j]))\n                    {\n                        buffer << input[j];\n                        ++i;\n                    }\n                    else\n                    {\n                        break;\n                    }\n                }\n\n                result.push_back( { Token::integer, buffer.str() } );\n        }\n    }\n\n    return result;\n}\n\nstruct Element\n{\n    using Ptr = std::shared_ptr<Element>;\n\n    virtual int eval() const = 0;\n};\n\nstruct Integer : Element\n{\n    int value;\n\n    Integer(int value) : value (value) {};\n\n    int eval() const override\n    {\n        return value;\n    }\n};\n\nstruct BinaryOp : Element\n{\n    enum Type { addition, substraction } type;\n\n    Element::Ptr lhs;\n    Element::Ptr rhs;\n\n    int eval() const override\n    {\n        if(type == addition)\n        {\n            return lhs->eval() + rhs->eval();\n        }\n        else\n        {\n            return lhs->eval() - rhs->eval();\n        }\n    }\n};\n\nElement::Ptr parse(const std::vector<Token>& tokens)\n{\n    auto result = std::make_shared<BinaryOp>();\n\n    bool have_lhs { false };\n\n    for(size_t i = 0; i < tokens.size(); i++)\n    {\n        auto token = tokens[i];\n        \n        switch(token.type)\n        {\n            case Token::integer:\n            {\n                int value = boost::lexical_cast<int>(token.text);\n                if(!have_lhs)\n                {\n                    result->lhs = std::make_shared<Integer>(value);\n                    have_lhs = true;\n                }\n                else\n                {\n                    result->rhs = std::make_shared<Integer>(value);\n                }\n\n            }\n                break;\n            case Token::plus:\n                result->type = BinaryOp::addition;\n                break;\n            case Token::minus:\n                result->type = BinaryOp::substraction;\n                break;\n            case Token::lparen:\n            {\n                size_t j = i;\n                for(; j < tokens.size(); ++j)\n                {\n                    if(tokens[j].type == Token::rparen)\n                    {\n                        break;\n                    }\n                }\n\n                std::vector<Token> subexpression(&tokens[i + 1], &tokens[j]);\n                auto element = parse(subexpression);\n\n                if(!have_lhs)\n                {\n                    result->lhs = element;\n                    have_lhs = true;\n                }\n                else\n                {\n                    result->rhs = element;\n                }\n\n                i = j;\n            }\n                break;\n            case Token::rparen:\n                break;\n        }\n    }\n\n    return result;\n}\n\nint main()\n{\n    std::string input { \"(13-4)-(12+1)\" };\n\n    auto tokens = lex(input);\n\n    for(auto& token : tokens)\n    {\n        std::cout << token << \" \";\n    }\n    std::cout << \"\\n\";\n\n    try\n    {\n        auto parsed = parse(tokens);\n        std::cout << input << \" = \" << parsed->eval() << std::endl;\n    }\n    catch(const std::exception& ex)\n    {\n        std::cout << ex.what() << std::endl;\n    }\n\n    return 0;\n}\n", "meta": {"hexsha": "c026193d5a5b29a82d7c53a1589f37ba9ffb890b", "size": 4290, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "interpreter_handmade_parsing/src/main.cpp", "max_stars_repo_name": "Thordreck/design_patterns_cpp", "max_stars_repo_head_hexsha": "b7b8ccc76ba26b2f63b80a2022616f266001d85d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-02-27T09:39:13.000Z", "max_stars_repo_stars_event_max_datetime": "2020-02-27T09:39:13.000Z", "max_issues_repo_path": "interpreter_handmade_parsing/src/main.cpp", "max_issues_repo_name": "Thordreck/design_patterns_cpp", "max_issues_repo_head_hexsha": "b7b8ccc76ba26b2f63b80a2022616f266001d85d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "interpreter_handmade_parsing/src/main.cpp", "max_forks_repo_name": "Thordreck/design_patterns_cpp", "max_forks_repo_head_hexsha": "b7b8ccc76ba26b2f63b80a2022616f266001d85d", "max_forks_repo_licenses": ["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.0, "max_line_length": 77, "alphanum_fraction": 0.4013986014, "num_tokens": 900, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.546738151984614, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.31156018553770864}}
{"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 \"GlobalOptimization.h\"\n\n#include <vector>\n#include <tuple>\n#include <Eigen/Dense>\n#include <Eigen/Sparse>\n#include <Core/Utility/Console.h>\n#include <Core/Utility/Timer.h>\n#include <Core/Registration/PoseGraph.h>\n#include <Core/Registration/GlobalOptimizationMethod.h>\n#include <Core/Registration/GlobalOptimizationConvergenceCriteria.h>\n\nnamespace three{\n\nnamespace {\n\n/// Definition of linear operators used for computing Jacobian matrix.\n/// If the relative transform of the two geometry is reasonably small,\n/// they can be approximated as below linearized form\n/// SE(3) \\approx = |     1 -gamma   beta     a |\n///                 | gamma      1 -alpha     b |\n///                 | -beta  alpha      1     c |\n///                 |     0      0      0     1 |\n/// It is from sin(x) \\approx x and cos(x) \\approx 1 when x is almost zero.\n/// See [Choi et al 2015] for more detail. Reference list in GlobalOptimization.h\nconst std::vector<Eigen::Matrix4d> jacobian_operator = {\n    (Eigen::Matrix4d() << /* for alpha */\n    0, 0, 0, 0, 0, 0, -1, 0, 0, 1, 0, 0, 0, 0, 0, 0).finished(),\n    (Eigen::Matrix4d() << /* for beta */\n    0, 0, 1, 0, 0, 0, 0, 0, -1, 0, 0, 0, 0, 0, 0, 0).finished(),\n    (Eigen::Matrix4d() << /* for gamma */\n    0, -1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0).finished(),\n    (Eigen::Matrix4d() << /* for a */\n    0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0).finished(),\n    (Eigen::Matrix4d() << /* for b */\n    0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0).finished(),\n    (Eigen::Matrix4d() << /* for c */\n    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0).finished() };\n\n/// This function is intended for linearized form of SE(3).\n/// It is an approximate form. See [Choi et al 2015] for derivation.\n/// Alternatively, explicit representation that uses quaternion can be used\n/// here to replace this function. Refer to linearizeOplus() in\n/// https://github.com/RainerKuemmerle/g2o/blob/master/g2o/types/slam3d/edge_se3.cpp\ninline Eigen::Vector6d GetLinearized6DVector(const Eigen::Matrix4d input)\n{\n    Eigen::Vector6d output;\n    output(0) = (-input(1, 2) + input(2, 1)) / 2.0;\n    output(1) = (-input(2, 0) + input(0, 2)) / 2.0;\n    output(2) = (-input(0, 1) + input(1, 0)) / 2.0;\n    output.block<3, 1>(3, 0) = input.block<3, 1>(0, 3);\n    return std::move(output);\n}\n\ninline Eigen::Vector6d GetMisalignmentVector(const Eigen::Matrix4d &X_inv,\n        const Eigen::Matrix4d &Ts, const Eigen::Matrix4d &Tt_inv)\n{\n    Eigen::Matrix4d temp;\n    temp.noalias() = X_inv * Tt_inv * Ts;\n    return GetLinearized6DVector(temp);\n}\n\ninline std::tuple<Eigen::Matrix4d, Eigen::Matrix4d, Eigen::Matrix4d>\n        GetRelativePoses(const PoseGraph &pose_graph, int edge_id)\n{\n    const PoseGraphEdge &te = pose_graph.edges_[edge_id];\n    const PoseGraphNode &ts = pose_graph.nodes_[te.source_node_id_];\n    const PoseGraphNode &tt = pose_graph.nodes_[te.target_node_id_];\n    Eigen::Matrix4d X_inv = te.transformation_.inverse();\n    Eigen::Matrix4d Ts = ts.pose_;\n    Eigen::Matrix4d Tt_inv = tt.pose_.inverse();\n    return std::make_tuple(std::move(X_inv), std::move(Ts), std::move(Tt_inv));\n}\n\nstd::tuple<Eigen::Matrix6d, Eigen::Matrix6d> GetJacobian(\n        const Eigen::Matrix4d &X_inv, const Eigen::Matrix4d &Ts,\n        const Eigen::Matrix4d &Tt_inv)\n{\n    Eigen::Matrix6d Js = Eigen::Matrix6d::Zero();\n    for (int i = 0; i < 6; i++) {\n        Eigen::Matrix4d temp = X_inv * Tt_inv *\n                jacobian_operator[i] * Ts;\n        Js.block<6, 1>(0, i) = GetLinearized6DVector(temp);\n    }\n    Eigen::Matrix6d Jt = Eigen::Matrix6d::Zero();\n    for (int i = 0; i < 6; i++) {\n        Eigen::Matrix4d temp = X_inv * Tt_inv *\n                -jacobian_operator[i] * Ts;\n        Jt.block<6, 1>(0, i) = GetLinearized6DVector(temp);\n    }\n    return std::make_tuple(std::move(Js), std::move(Jt));\n}\n\n/// Function to update line_process value defined in [Choi et al 2015]\n/// See Eq (2). temp2 value in this function is derived from dE/dl = 0\nint UpdateConfidence(\n        PoseGraph &pose_graph, const Eigen::VectorXd &zeta,\n        const double line_process_weight,\n        const GlobalOptimizationOption &option)\n{\n    int n_edges = (int)pose_graph.edges_.size();\n    int valid_edges_num = 0;\n    for (int iter_edge = 0; iter_edge < n_edges; iter_edge++) {\n        PoseGraphEdge &t = pose_graph.edges_[iter_edge];\n        Eigen::Vector6d e = zeta.block<6, 1>(iter_edge * 6, 0);\n        double residual_square = e.transpose() * t.information_ * e;\n        double temp = line_process_weight /\n                (line_process_weight + residual_square);\n        double temp2 = temp * temp;\n        t.confidence_ = temp2;\n        if (temp2 > option.edge_prune_threshold_)\n            valid_edges_num++;\n    }\n    return valid_edges_num;\n}\n\n/// Function to compute residual defined in [Choi et al 2015] See Eq (9).\ndouble ComputeResidual(const PoseGraph &pose_graph, const Eigen::VectorXd &zeta,\n        const double line_process_weight,\n        const GlobalOptimizationOption &option)\n{\n    int n_edges = (int)pose_graph.edges_.size();\n    double residual = 0.0;\n    for (int iter_edge = 0; iter_edge < n_edges; iter_edge++) {\n        const PoseGraphEdge &te = pose_graph.edges_[iter_edge];\n        double line_process_iter = te.confidence_;\n        Eigen::Vector6d e = zeta.block<6, 1>(iter_edge * 6, 0);\n        residual += line_process_iter * e.transpose() * te.information_ * e +\n                line_process_weight * pow(sqrt(line_process_iter) - 1, 2.0);\n    }\n    return residual;\n}\n\n/// Function to compute residual defined in [Choi et al 2015] See Eq (6).\nEigen::VectorXd ComputeZeta(const PoseGraph &pose_graph)\n{\n    int n_edges = (int)pose_graph.edges_.size();\n    Eigen::VectorXd output(n_edges * 6);\n    for (int iter_edge = 0; iter_edge < n_edges; iter_edge++) {\n        Eigen::Matrix4d X_inv, Ts, Tt_inv;\n        std::tie(X_inv, Ts, Tt_inv) = GetRelativePoses(pose_graph, iter_edge);\n        Eigen::Vector6d e = GetMisalignmentVector(X_inv, Ts, Tt_inv);\n        output.block<6, 1>(iter_edge * 6, 0) = e;\n    }\n    return std::move(output);\n}\n\n/// The information matrix used here is consistent with [Choi et al 2015].\n/// It is [p_x | I]^T[p_x | I]. \\zeta is [\\alpha \\beta \\gamma a b c]\n/// Another definition of information matrix used for [Kümmerle et al 2011] is\n/// [I | p_x] ^ T[I | p_x]  so \\zeta is [a b c \\alpha \\beta \\gamma].\n///\n/// To see how H can be derived see [Kümmerle et al 2011].\n/// Eq (9) for definition of H and b for k-th constraint.\n/// To see how the covariance matrix forms H, check g2o technical note:\n/// https ://github.com/RainerKuemmerle/g2o/blob/master/doc/g2o.pdf\n/// Eq (20) and Eq (21). (There is a typo in the equation though. B should be J)\n///\n/// This function focuses the case that every edge has two nodes (not hyper graph)\n/// so we have two Jacobian matrices from one constraint.\nstd::tuple<Eigen::MatrixXd, Eigen::VectorXd> ComputeLinearSystem(\n        const PoseGraph &pose_graph, const Eigen::VectorXd &zeta)\n{\n    int n_nodes = (int)pose_graph.nodes_.size();\n    int n_edges = (int)pose_graph.edges_.size();\n    Eigen::MatrixXd H(n_nodes * 6, n_nodes * 6);\n    Eigen::VectorXd b(n_nodes * 6);\n    H.setZero();\n    b.setZero();\n\n    for (int iter_edge = 0; iter_edge < n_edges; iter_edge++) {\n        const PoseGraphEdge &t = pose_graph.edges_[iter_edge];\n        Eigen::Vector6d e = zeta.block<6, 1>(iter_edge * 6, 0);\n\n        Eigen::Matrix4d X_inv, Ts, Tt_inv;\n        std::tie(X_inv, Ts, Tt_inv) = GetRelativePoses(pose_graph, iter_edge);\n\n        Eigen::Matrix6d Js, Jt;\n        std::tie(Js, Jt) = GetJacobian(X_inv, Ts, Tt_inv);\n        Eigen::Matrix6d JsT_Info =\n                Js.transpose() * t.information_;\n        Eigen::Matrix6d JtT_Info =\n                Jt.transpose() * t.information_;\n        Eigen::Vector6d eT_Info = e.transpose() * t.information_;\n        double line_process_iter = t.confidence_;\n\n        int id_i = t.source_node_id_ * 6;\n        int id_j = t.target_node_id_ * 6;\n        H.block<6, 6>(id_i, id_i).noalias() +=\n                line_process_iter * JsT_Info * Js;\n        H.block<6, 6>(id_i, id_j).noalias() +=\n                line_process_iter * JsT_Info * Jt;\n        H.block<6, 6>(id_j, id_i).noalias() +=\n                line_process_iter * JtT_Info * Js;\n        H.block<6, 6>(id_j, id_j).noalias() +=\n                line_process_iter * JtT_Info * Jt;\n        b.block<6, 1>(id_i, 0).noalias() -=\n                line_process_iter * eT_Info.transpose() * Js;\n        b.block<6, 1>(id_j, 0).noalias() -=\n                line_process_iter * eT_Info.transpose() * Jt;\n    }\n    return std::make_tuple(std::move(H), std::move(b));\n}\n\nEigen::VectorXd UpdatePoseVector(const PoseGraph &pose_graph)\n{\n    int n_nodes = (int)pose_graph.nodes_.size();\n    Eigen::VectorXd output(n_nodes * 6);\n    for (int iter_node = 0; iter_node < n_nodes; iter_node++) {\n        Eigen::Vector6d output_iter = TransformMatrix4dToVector6d(\n                pose_graph.nodes_[iter_node].pose_);\n        output.block<6, 1>(iter_node * 6, 0) = output_iter;\n    }\n    return std::move(output);\n}\n\nstd::shared_ptr<PoseGraph> UpdatePoseGraph(const PoseGraph &pose_graph,\n        const Eigen::VectorXd delta)\n{\n    std::shared_ptr<PoseGraph> pose_graph_updated =\n        std::make_shared<PoseGraph>();\n    *pose_graph_updated = pose_graph;\n    int n_nodes = (int)pose_graph.nodes_.size();\n    for (int iter_node = 0; iter_node < n_nodes; iter_node++) {\n        Eigen::Vector6d delta_iter = delta.block<6, 1>(iter_node * 6, 0);\n        pose_graph_updated->nodes_[iter_node].pose_ =\n                TransformVector6dToMatrix4d(delta_iter) *\n                pose_graph_updated->nodes_[iter_node].pose_;\n    }\n    return pose_graph_updated;\n}\n\nbool CheckRightTerm(const Eigen::VectorXd &right_term,\n        const GlobalOptimizationConvergenceCriteria &criteria)\n{\n    if (right_term.maxCoeff() < criteria.min_right_term_) {\n        PrintDebug(\"Maximum coefficient of right term < %e\\n\",\n                criteria.min_right_term_);\n        return true;\n    }\n    return false;\n}\n\nbool CheckRelativeIncrement(\n        const Eigen::VectorXd &delta, const Eigen::VectorXd &x,\n        const GlobalOptimizationConvergenceCriteria &criteria)\n{\n    if (delta.norm() < criteria.min_relative_increment_ *\n            (x.norm() + criteria.min_relative_increment_)) {\n        PrintDebug(\"Delta.norm() < %e * (x.norm() + %e)\\n\",\n                criteria.min_relative_increment_,\n                criteria.min_relative_increment_);\n        return true;\n    }\n    return false;\n}\n\nbool CheckRelativeResidualIncrement(\n        double current_residual, double new_residual,\n        const GlobalOptimizationConvergenceCriteria &criteria)\n{\n    if (current_residual - new_residual <\n        criteria.min_relative_residual_increment_ * current_residual) {\n        PrintDebug(\"Current_residual - new_residual < %e * current_residual\\n\",\n                criteria.min_relative_residual_increment_);\n        return true;\n    }\n    return false;\n}\n\nbool CheckResidual(double residual,\n        const GlobalOptimizationConvergenceCriteria &criteria)\n{\n    if (residual < criteria.min_residual_) {\n        PrintDebug(\"Current_residual < %e\\n\", criteria.min_residual_);\n        return true;\n    }\n    return false;\n}\n\nbool CheckMaxIteration(int iteration,\n        const GlobalOptimizationConvergenceCriteria &criteria)\n{\n    if (iteration >= criteria.max_iteration_) {\n        PrintDebug(\"Reached maximum number of iterations (%d)\\n\",\n                criteria.max_iteration_);\n        return true;\n    }\n    return false;\n}\n\nbool CheckMaxIterationLM(int iteration,\n        const GlobalOptimizationConvergenceCriteria &criteria)\n{\n    if (iteration >= criteria.max_iteration_lm_) {\n        PrintDebug(\"Reached maximum number of iterations (%d)\\n\",\n                criteria.max_iteration_lm_);\n        return true;\n    }\n    return false;\n}\n\ndouble ComputeLineProcessWeight(const PoseGraph &pose_graph,\n        const GlobalOptimizationOption &option)\n{\n    int n_edges = (int)pose_graph.edges_.size();\n    double average_number_of_correspondences = 0.0;\n    for (int iter_edge = 0; iter_edge < n_edges; iter_edge++) {\n        double number_of_correspondences =\n                pose_graph.edges_[iter_edge].information_(5,5);\n        average_number_of_correspondences += number_of_correspondences;\n    }\n    if (n_edges > 0) {\n        // see Section 5 in [Choi et al 2015]\n        average_number_of_correspondences /= (double)n_edges;\n        double line_process_weight = option.preference_loop_closure_ *\n                pow(option.max_correspondence_distance_, 2) *\n                average_number_of_correspondences;\n        return line_process_weight;\n    }\n    else {\n        return 0.0;\n    }\n}\n\nvoid CompensateReferencePoseGraphNode(PoseGraph &pose_graph_new,\n        const PoseGraph &pose_graph_orig, int reference_node)\n{\n    PrintDebug(\"CompensateReferencePoseGraphNode : reference : %d\\n\",\n            reference_node);\n    int n_nodes = (int)pose_graph_new.nodes_.size();\n    if (reference_node < 0 || reference_node >= n_nodes) {\n        return;\n    } else {\n        Eigen::Matrix4d compensation =\n                pose_graph_orig.nodes_[reference_node].pose_ *\n                pose_graph_new.nodes_[reference_node].pose_.inverse();\n        for (int i = 0; i < n_nodes; i++)\n        {\n            pose_graph_new.nodes_[i].pose_ = compensation *\n                    pose_graph_new.nodes_[i].pose_;\n        }\n    }\n}\n\n}    // unnamed namespace\n\nstd::shared_ptr<PoseGraph> CreatePoseGraphWithoutInvalidEdges(\n        const PoseGraph &pose_graph,\n        const GlobalOptimizationOption &option)\n{\n    std::shared_ptr<PoseGraph> pose_graph_pruned =\n            std::make_shared<PoseGraph>();\n\n    int n_nodes = (int)pose_graph.nodes_.size();\n    for (int iter_node = 0; iter_node < n_nodes; iter_node++) {\n        const PoseGraphNode &t = pose_graph.nodes_[iter_node];\n        pose_graph_pruned->nodes_.push_back(t);\n    }\n    int n_edges = (int)pose_graph.edges_.size();\n    for (int iter_edge = 0; iter_edge < n_edges; iter_edge++) {\n        const PoseGraphEdge &t = pose_graph.edges_[iter_edge];\n        if (t.uncertain_) {\n            if (t.confidence_ > option.edge_prune_threshold_) {\n                pose_graph_pruned->edges_.push_back(t);\n            }\n        } else {\n            pose_graph_pruned->edges_.push_back(t);\n        }\n    }\n    return pose_graph_pruned;\n}\n\nvoid GlobalOptimizationGaussNewton::\n        OptimizePoseGraph(PoseGraph &pose_graph,\n        const GlobalOptimizationConvergenceCriteria &criteria,\n        const GlobalOptimizationOption &option) const\n{\n    int n_nodes = (int)pose_graph.nodes_.size();\n    int n_edges = (int)pose_graph.edges_.size();\n    double line_process_weight = ComputeLineProcessWeight(pose_graph, option);\n\n    PrintDebug(\"[GlobalOptimizationGaussNewton] Optimizing PoseGraph having %d nodes and %d edges. \\n\",\n            n_nodes, n_edges);\n    PrintDebug(\"Line process weight : %f\\n\", line_process_weight);\n\n    Eigen::VectorXd zeta = ComputeZeta(pose_graph);\n    double current_residual, new_residual;\n    new_residual = ComputeResidual(pose_graph, zeta,\n            line_process_weight, option);\n    current_residual = new_residual;\n\n    int valid_edges_num;\n    valid_edges_num = UpdateConfidence(pose_graph, zeta,\n            line_process_weight, option);\n\n    Eigen::MatrixXd H;\n    Eigen::VectorXd b;\n    Eigen::VectorXd x = UpdatePoseVector(pose_graph);\n\n    std::tie(H, b) = ComputeLinearSystem(pose_graph, zeta);\n\n    PrintDebug(\"[Initial     ] residual : %e\\n\", current_residual);\n\n    bool stop = false;\n    if (stop || CheckRightTerm(b, criteria))\n        return;\n\n    Timer timer_overall;\n    timer_overall.Start();\n    int iter;\n    for (iter = 0; !stop; iter++) {\n        Timer timer_iter;\n        timer_iter.Start();\n\n        Eigen::VectorXd delta = H.ldlt().solve(b);\n\n        stop = stop || CheckRelativeIncrement(delta, x, criteria);\n        if (stop) {\n            break;\n        } else {\n            std::shared_ptr<PoseGraph> pose_graph_new =\n                UpdatePoseGraph(pose_graph, delta);\n\n            Eigen::VectorXd zeta_new;\n            zeta_new = ComputeZeta(*pose_graph_new);\n            new_residual = ComputeResidual(pose_graph, zeta_new,\n                    line_process_weight, option);\n            stop = stop || CheckRelativeResidualIncrement(\n                    current_residual, new_residual, criteria);\n            if (stop)\n                break;\n            current_residual = new_residual;\n\n            zeta = zeta_new;\n            pose_graph = *pose_graph_new;\n            x = UpdatePoseVector(pose_graph);\n            valid_edges_num = UpdateConfidence(pose_graph, zeta,\n                    line_process_weight, option);\n            std::tie(H, b) = ComputeLinearSystem(pose_graph, zeta);\n\n            stop = stop || CheckRightTerm(b, criteria);\n            if (stop)\n                break;\n        }\n        timer_iter.Stop();\n        PrintDebug(\"[Iteration %02d] residual : %e, valid edges : %d, time : %.3f sec.\\n\",\n                iter, current_residual, valid_edges_num,\n                timer_iter.GetDuration() / 1000.0);\n        stop = stop || CheckResidual(current_residual, criteria)\n                || CheckMaxIteration(iter, criteria);\n    }    // end for\n    timer_overall.Stop();\n    PrintDebug(\"[GlobalOptimizationGaussNewton] total time : %.3f sec.\\n\",\n            timer_overall.GetDuration() / 1000.0);\n}\n\nvoid GlobalOptimizationLevenbergMarquardt::\n        OptimizePoseGraph(PoseGraph &pose_graph,\n        const GlobalOptimizationConvergenceCriteria &criteria,\n        const GlobalOptimizationOption &option) const\n{\n    int n_nodes = (int)pose_graph.nodes_.size();\n    int n_edges = (int)pose_graph.edges_.size();\n    double line_process_weight = ComputeLineProcessWeight(pose_graph, option);\n\n    PrintDebug(\"[GlobalOptimizationLM] Optimizing PoseGraph having %d nodes and %d edges. \\n\",\n            n_nodes, n_edges);\n    PrintDebug(\"Line process weight : %f\\n\", line_process_weight);\n\n    Eigen::VectorXd zeta = ComputeZeta(pose_graph);\n    double current_residual, new_residual;\n    new_residual = ComputeResidual(pose_graph, zeta,\n            line_process_weight, option);\n    current_residual = new_residual;\n\n    int valid_edges_num = UpdateConfidence(pose_graph, zeta,\n            line_process_weight, option);\n\n    Eigen::MatrixXd H_I = Eigen::MatrixXd::Identity(n_nodes * 6, n_nodes * 6);\n    Eigen::MatrixXd H;\n    Eigen::VectorXd b;\n    Eigen::VectorXd x = UpdatePoseVector(pose_graph);\n\n    std::tie(H, b) = ComputeLinearSystem(pose_graph, zeta);\n\n    Eigen::VectorXd H_diag = H.diagonal();\n    double tau = 1e-5;\n    double current_lambda = tau * H_diag.maxCoeff();\n    double ni = 2.0;\n    double rho = 0.0;\n\n    PrintDebug(\"[Initial     ] residual : %e, lambda : %e\\n\",\n            current_residual, current_lambda);\n\n    bool stop = false;\n    stop = stop || CheckRightTerm(b, criteria);\n    if (stop)\n        return;\n\n    Timer timer_overall;\n    timer_overall.Start();\n    for (int iter = 0; !stop; iter++) {\n        Timer timer_iter;\n        timer_iter.Start();\n        int lm_count = 0;\n        do {\n            Eigen::MatrixXd H_LM = H + current_lambda * H_I;\n            Eigen::VectorXd delta(H_LM.cols());\n\n            //Using a sparse solver\n            Eigen::SparseMatrix<double> H_LM_sparse = H_LM.sparseView();\n            Eigen::SimplicialCholesky<Eigen::SparseMatrix<double>> chol;\n            chol.compute(H_LM_sparse);\n\n            if (chol.info() == Eigen::Success) {\n                delta = chol.solve(b);\n                if (chol.info() != Eigen::Success) {\n                    PrintInfo(\"[GlobalOptimizationLM] sparse solver couldn't solve !! switching to dense solver\");\n                    delta = H_LM.ldlt().solve(b);\n                    }\n            } else {\n                PrintInfo(\"[GlobalOptimizationLM] Cholesky Decomposition Failed !! switching to dense solver\");\n                delta = H_LM.ldlt().solve(b);\n            }\n\n            stop = stop || CheckRelativeIncrement(delta, x, criteria);\n            if (!stop) {\n                std::shared_ptr<PoseGraph> pose_graph_new =\n                        UpdatePoseGraph(pose_graph, delta);\n\n                Eigen::VectorXd zeta_new;\n                zeta_new = ComputeZeta(*pose_graph_new);\n                new_residual = ComputeResidual(pose_graph, zeta_new,\n                        line_process_weight, option);\n                rho = (current_residual - new_residual) /\n                        (delta.dot(current_lambda * delta + b) + 1e-3);\n                if (rho > 0) {\n                    stop = stop || CheckRelativeResidualIncrement(\n                            current_residual, new_residual, criteria);\n                    if (stop)\n                        break;\n                    double alpha = 1. - pow((2 * rho - 1), 3);\n                    alpha = (std::min)(alpha, criteria.upper_scale_factor_);\n                    double scaleFactor = (std::max)\n                            (criteria.lower_scale_factor_, alpha);\n                    current_lambda *= scaleFactor;\n                    ni = 2;\n                    current_residual = new_residual;\n\n                    zeta = zeta_new;\n                    pose_graph = *pose_graph_new;\n                    x = UpdatePoseVector(pose_graph);\n                    valid_edges_num = UpdateConfidence(pose_graph, zeta,\n                            line_process_weight, option);\n                    std::tie(H, b) = ComputeLinearSystem(pose_graph, zeta);\n\n                    stop = stop || CheckRightTerm(b, criteria);\n                    if (stop)\n                        break;\n                } else {\n                    current_lambda *= ni;\n                    ni *= 2;\n                }\n            }\n            lm_count++;\n            stop = stop || CheckMaxIterationLM(lm_count, criteria);\n        } while (!((rho > 0) || stop));\n        timer_iter.Stop();\n        if (!stop) {\n            PrintDebug(\"[Iteration %02d] residual : %e, valid edges : %d, time : %.3f sec.\\n\",\n                    iter, current_residual, valid_edges_num,\n                    timer_iter.GetDuration() / 1000.0);\n        }\n        stop = stop || CheckResidual(current_residual, criteria)\n                || CheckMaxIteration(iter, criteria);\n    }    // end for\n    timer_overall.Stop();\n    PrintDebug(\"[GlobalOptimizationLM] total time : %.3f sec.\\n\",\n            timer_overall.GetDuration() / 1000.0);\n}\n\nvoid GlobalOptimization(\n        PoseGraph &pose_graph,\n        const GlobalOptimizationMethod &method\n        /* = GlobalOptimizationLevenbergMarquardt() */,\n        const GlobalOptimizationConvergenceCriteria &criteria\n        /* = GlobalOptimizationConvergenceCriteria() */,\n        const GlobalOptimizationOption &option\n        /* = GlobalOptimizationOption() */)\n{\n    std::shared_ptr<PoseGraph> pose_graph_pre =\n            std::make_shared<PoseGraph>();\n    *pose_graph_pre = pose_graph;\n    method.OptimizePoseGraph(*pose_graph_pre, criteria, option);\n    auto pose_graph_pruned = CreatePoseGraphWithoutInvalidEdges(\n            *pose_graph_pre, option);\n    method.OptimizePoseGraph(*pose_graph_pruned, criteria, option);\n    CompensateReferencePoseGraphNode(*pose_graph_pruned,\n            pose_graph, option.reference_node_);\n    pose_graph = *pose_graph_pruned;\n}\n\n}    // namespace three\n", "meta": {"hexsha": "4b189694fe7980a2d18fec4b19a851962e5c8361", "size": 24916, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Core/Registration/GlobalOptimization.cpp", "max_stars_repo_name": "cnheider/Open3D", "max_stars_repo_head_hexsha": "eb0267dee7c50a824d4f94e9bd0f18dccbd3eb5d", "max_stars_repo_licenses": ["MIT"], "max_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/Registration/GlobalOptimization.cpp", "max_issues_repo_name": "cnheider/Open3D", "max_issues_repo_head_hexsha": "eb0267dee7c50a824d4f94e9bd0f18dccbd3eb5d", "max_issues_repo_licenses": ["MIT"], "max_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/Registration/GlobalOptimization.cpp", "max_forks_repo_name": "cnheider/Open3D", "max_forks_repo_head_hexsha": "eb0267dee7c50a824d4f94e9bd0f18dccbd3eb5d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-08-25T16:27:13.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-25T16:27:13.000Z", "avg_line_length": 39.4865293185, "max_line_length": 114, "alphanum_fraction": 0.6192005137, "num_tokens": 6313, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6757646010190476, "lm_q2_score": 0.46101677931231594, "lm_q1q2_score": 0.3115388199350735}}
{"text": "#include <boost/python.hpp>\n#include \"integrand.h\"\n\nusing namespace Eigen;\n\n\nvoid GetBandHamiltonian(const VectorXd &x, ComplexMatrix &mat, const std::vector<ComplexMatrix> &HR, \n    const MatrixXi &R, const double &H, const double &delta) \n{\n  static Complex I(0,1);\n  mat.fill(0);\n  for (int i = 0; i < R.rows(); ++i) {\n    mat += HR[i]*exp(I*(x(0)*R(i,0) + x(1)*R(i,1) + x(2)*R(i,2)));\n  }\n  for (int i = 0; i < mat.rows(); ++i)\n    mat(i,i) -= H;\n  for (int i = 0; i < kNCor*kNLayers; ++i)\n    mat(i,i) -= delta;\n}\n\n\nGreenIntegrand::GreenIntegrand(const Eigen::VectorXcd &omega, const double &chemical_potential,   \n    const std::vector<ComplexMatrix> &hamiltonian_r, const Eigen::MatrixXi &r_vectors,   \n    const Eigen::MatrixXcd &all_self_energy, const double &magnetic_field, const double &double_counting) \n    : md_int::GeneralIntegrand<Complex>(), delta_(double_counting), chemical_potential_(chemical_potential),\n    ham_r_(hamiltonian_r), r_vectors_(r_vectors), h_field_(magnetic_field), all_omega_(omega), \n    all_self_energy_(all_self_energy), self_energy_(ComplexMatrix::Zero()) {\n  set_dim_in(kDim);\n  set_dim_out(kMSize*kMSize);\n}\n\n// set omega and self energy:\n// e.g. tilted 5d band case: 4 blocks for 4 cell, each block is a 5x5 matrix \nvoid GreenIntegrand::set_data(const int &r) {\n    w_ = all_omega_(r);\n\n    for (int c = 0; c < kNLayers; ++c) \n        for (int i = 0; i < kNCor; ++i)\n            for (int j = 0; j < kNCor; ++j)\n                self_energy_(kNCor*c+i,kNCor*c+j) = all_self_energy_(r, kNCor*kNCor*c+kNCor*i+j);\n}\n\nvoid GreenIntegrand::CalculateOriginalIntegrand(const VectorXd &x, VectorXcd &y) const\n{\n    y.resize(dim_out());\n    ComplexMatrix tmp, negative_green;\n    GetBandHamiltonian(x, tmp, ham_r_, r_vectors_, h_field_, delta_);\n\n    for (int n = 0; n < kMSize; ++n) tmp(n, n) -= w_ + chemical_potential_;\n    tmp += self_energy_;\n\n    inv::inverse(tmp, negative_green);\n    for (int i = 0; i < kMSize; ++i)\n        for (int j = 0; j < kMSize; ++j)\n            y(kMSize*i+j) = -negative_green(i, j);\n}\n\n\nHamiltonianIntegrand::HamiltonianIntegrand(const int &num_order, const std::vector<ComplexMatrix> &hamiltonian_r, \n    const Eigen::MatrixXi &r_vectors, const double &magnetic_field, const double &double_counting)\n    : md_int::GeneralIntegrand<Complex>(), num_order_(num_order), ham_r_(hamiltonian_r), \n    r_vectors_(r_vectors), h_field_(magnetic_field), delta_(double_counting) {\n  set_dim_in(kDim);\n  set_dim_out(num_order_*kMSize*kMSize);\n}\n\nvoid HamiltonianIntegrand::CalculateOriginalIntegrand(const VectorXd &x, VectorXcd &y) const\n{\n    ComplexMatrix ham, ham_pow(ComplexMatrix::Identity());\n    y.resize(dim_out());\n    GetBandHamiltonian(x, ham, ham_r_, r_vectors_, h_field_, delta_);\n    for (int n = 0; n < num_order_; ++n) {\n        ham_pow *= ham;\n        for (int i = 0; i < kMSize; ++i)\n            for (int j = 0; j < kMSize; ++j)\n                y(kMSize*kMSize*n+kMSize*i+j) = ham_pow(i, j);\n    }\n}\n\n", "meta": {"hexsha": "c6a07c69909743612079a1d002899211dc93d75e", "size": 2975, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "integrate_dft_mlwf/integrand.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_dft_mlwf/integrand.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_dft_mlwf/integrand.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": 37.1875, "max_line_length": 114, "alphanum_fraction": 0.6611764706, "num_tokens": 949, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7577943712746406, "lm_q2_score": 0.411110869232168, "lm_q1q2_score": 0.31153750267396174}}
{"text": "// fixed_point.hpp\r\n//\r\n// Copyright (c) 2016 Piotr K. Semenov (piotr.k.semenov at gmail dot com)\r\n// Distributed under the New BSD License. (See accompanying file LICENSE)\r\n\r\n/*!\r\n \\file fixed_point.hpp\r\n\r\n \\brief Provides the fixed-point numbers of any format and CORDIC-based\r\n overloading of STD math as well.\r\n*/\r\n\r\n#ifndef INC_LIBQ_FIXED_POINT_HPP_\r\n#define INC_LIBQ_FIXED_POINT_HPP_\r\n\r\n#include <boost/integer.hpp>\r\n#include <boost/integer/integer_mask.hpp>\r\n\r\n#include <cstdint>\r\n#include <cmath>\r\n#include <limits>\r\n#include <exception>\r\n#include <type_traits>\r\n\r\n#include \"arithmetics_safety.hpp\"\r\n#include \"type_promotion.hpp\"\r\n\r\n\r\n#ifndef IMPLICIT_COPY_CTR\r\n#define COPY_CTR_EXPLICIT_SPECIFIER explicit\r\n#else\r\n#define COPY_CTR_EXPLICIT_SPECIFIER\r\n#endif\r\n\r\n\r\nnamespace libq {\r\nnamespace details {\r\n    double exp2(double _val) {\r\n#if defined(_MSC_VER)\r\n        return std::exp2(_val);\r\n#elif defined(__GNUC__)\r\n        return std::pow(2.0, _val);\r\n#endif\r\n    }\r\n}  // details\r\n\r\n/*!\r\n \\brief Gets the reference to the stored integer behind the fixed-point number\r\n \\param[in] _x the fixed-point number\r\n*/\r\ntemplate<typename T, std::size_t n, std::size_t f, int e, class ... Ps>\r\nT& lift(fixed_point<T, n, f, e, Ps...>& _x) {  // NOLINT\r\n    return _x.m_value;\r\n}\r\n\r\n/*!\r\n \\brief Gets the value of the stored integer behind the fixed-point number\r\n \\param[in] _x the fixed-point number\r\n*/\r\ntemplate<typename T, std::size_t n, std::size_t f, int e, class ... Ps>\r\nT const lift(fixed_point<T, n, f, e, Ps...> const& _x) {\r\n    return _x.m_value;\r\n}\r\n\r\n/*!\r\n \\brief Implements the fixed-point number arithmetics. Note, this extends the\r\n Q-formats like UQn.f, Qn.f with fixed pre-scaling factor \\f$2^e\\f$.\r\n \\tparam value_type Built-in integral type to represent a fixed-point number.\r\n \\tparam n Number of integral bits.\r\n \\tparam f Number of fractional bits.\r\n \\remark Note, \\f$n\\f$ and \\f$f\\f$ exclude the sign bit. So if storage_type is\r\n signed then total number of bits is \\f$(n + f + 1)\\f$.\r\n \\remark Note, the supremum of \\f$(n + f)\\f$ is\r\n std::numeric_limits<std::uintmax_t>::digits in case of the unsigned numbers\r\n and std::numeric_limits<std::intmax_t>::digits in case of the signed numbers.\r\n \\tparam e Exponent of the pre-scaling factor \\f$2^e\\f$.\r\n \\tparam op Policy class specifying the actions to do if overflow occurred.\r\n \\tparam up Policy class specifying the actions to do if underflow occurred.\r\n\r\n <B>Usage</B>\r\n\r\n <I>Example 1</I>: Flexible switch between the floating-point calculations and\r\n fixed precision calculations while algorithm staying the same.\r\n \\code{.cpp}\r\n    #include \"fixed_point.hpp\"\r\n    #include <iostream>\r\n    #include <cstdlib>\r\n\r\n    namespace floating_point {\r\n        using value_type = double;\r\n    };  // namespace floating_point\r\n    namespace fixed_precision {\r\n        using value_type = libq::Q<30, 20>;\r\n    };  // namespace fixed_precision\r\n    using value_type = fixed_precision::value_type;\r\n\r\n    int main(int, char**) {\r\n        value_type input{ 0.0 };\r\n        std::cin >> input;\r\n\r\n        value_type const result = your_algorithm_here(input);\r\n        std::cout << result << std::endl;\r\n\r\n        return EXIT_SUCCESS;\r\n    }\r\n \\endcode\r\n\r\n \\note Please, see http://en.wikipedia.org/wiki/Q_(number_format) for details.\r\n*/\r\ntemplate<typename value_type,\r\n         std::size_t n,\r\n         std::size_t f,\r\n         int e,\r\n         class op,\r\n         class up>\r\nclass fixed_point {\r\n    static_assert(std::is_integral<value_type>::value,\r\n                  \"value_type must be of the built-in integral type\");\r\n\r\n    using this_class = fixed_point<value_type, n, f, e, op, up>;\r\n    using largest_type = typename std::conditional<\r\n                                    std::numeric_limits<value_type>::is_signed,\r\n                                    std::intmax_t, std::uintmax_t>::type;\r\n\r\n public:\r\n    using type = this_class;\r\n    using overflow_policy = op;\r\n    using underflow_policy = up;\r\n\r\n    /*!\r\n     \\brief Used type for the stored integer.\r\n    */\r\n    using storage_type = value_type;\r\n\r\n    enum: int {\r\n        scaling_factor_exponent = e\r\n    };\r\n    enum: std::size_t {\r\n        /*!\r\n         \\brief Total number of significant bits.\r\n        */\r\n        number_of_significant_bits = n + f,\r\n\r\n        /*!\r\n         \\brief Queried number of bits to represent the fractional part of\r\n         fixed-point number.\r\n        */\r\n        bits_for_fractional = f,\r\n\r\n        /*!\r\n         \\brief Number of bits to represent the integral part.\r\n        */\r\n        bits_for_integral = n,\r\n\r\n        /*!\r\n         \\brief This checks if this fixed-point number is signed.\r\n        */\r\n        is_signed = std::numeric_limits<storage_type>::is_signed\r\n    };\r\n\r\n    /*!\r\n     \\brief Gets the scaling factor for this fixed-point number.\r\n    */\r\n    inline static double scaling_factor() {\r\n        static double const factor = details::exp2(\r\n                    -static_cast<double>(this_class::scaling_factor_exponent));\r\n\r\n        return factor;\r\n    }\r\n\r\n\r\n    static_assert(this_class::number_of_significant_bits <=\r\n                    std::numeric_limits<largest_type>::digits,\r\n                  \"too big word size is required\");\r\n#define EXP2N(N) (std::uintmax_t(1u) << (N))\r\n    enum : std::uintmax_t {\r\n        /*!\r\n         \\brief Scale factor for this fixed-point number.\r\n        */\r\n        scale = EXP2N(this_class::bits_for_fractional),\r\n\r\n        /*!\r\n         \\brief Binary mask to extract the integral bits only from the stored\r\n         integer.\r\n        */\r\n        // This is tricky to process if n + f = max. possible word size.\r\n        integer_bits_mask = (this_class::bits_for_integral > 0u) ?\r\n            2u * ( EXP2N(this_class::bits_for_fractional + this_class::bits_for_integral - 1u) -  // NOLINT\r\n                   ( (this_class::bits_for_fractional > 0u) ? EXP2N(this_class::bits_for_fractional - 1u) : 0u)) : 0u,  // NOLINT\r\n\r\n        /*!\r\n         \\brief Binary mask to extract the fractional bits from the stored\r\n         integer.\r\n        */\r\n        fractional_bits_mask = (this_class::bits_for_fractional > 0u) ?\r\n            2u * (EXP2N(this_class::bits_for_fractional - 1u) - 1u) + 1u : 0u\r\n    };\r\n#undef EXP2N\r\n\r\n    /*!\r\n     \\brief The maximum value of stored integer for this fixed-point format.\r\n    */\r\n    static typename this_class::largest_type const largest_stored_integer =\r\n        boost::low_bits_mask_t<this_class::number_of_significant_bits>::sig_bits;  // NOLINT\r\n    /*!\r\n     \\brief Gets the maximum available fixed-point number.\r\n    */\r\n    static this_class largest() {\r\n        return\r\n            this_class::wrap<typename this_class::largest_type>(\r\n                                           this_class::largest_stored_integer);\r\n    }\r\n\r\n\r\n    /*\r\n     \\brief The minimum value of stored integer for this fixed-point format.\r\n    */\r\n    static std::intmax_t const least_stored_integer =\r\n        this_class::is_signed * (-static_cast<std::intmax_t>(this_class::largest_stored_integer) - 1);  // NOLINT\r\n    /*!\r\n     \\brief Gets the minimum available fixed-point number.\r\n    */\r\n    static this_class least() {\r\n        return\r\n            this_class::wrap(this_class::least_stored_integer);\r\n    }\r\n\r\n\r\n    /*!\r\n     \\brief Gets the dynamic range (dB) for this fixed-point format\r\n    */\r\n    static double dynamic_range_db() {\r\n        double const max_stored_integer =\r\n            static_cast<double>(this_class::largest_stored_integer);\r\n\r\n        return\r\n            20.0 * std::log10(max_stored_integer);\r\n    }\r\n\r\n\r\n    /*!\r\n     \\brief Gets the precision of this fixed-point number.\r\n    */\r\n    static double precision() {\r\n        return\r\n            1.0 / this_class::scale;\r\n    }\r\n\r\n\r\n    /*!\r\n     \\brief Signed version of this fixed-point number type.\r\n    */\r\n    using to_signed_type = fixed_point<\r\n                                 typename std::make_signed<storage_type>::type,\r\n                                 this_class::bits_for_integral,\r\n                                 this_class::bits_for_fractional,\r\n                                 this_class::scaling_factor_exponent,\r\n                                 overflow_policy,\r\n                                 underflow_policy>;\r\n\r\n\r\n    /*!\r\n     \\brief Unsigned version of this fixed-point number type.\r\n    */\r\n    using to_unsigned_type = fixed_point<\r\n                               typename std::make_unsigned<storage_type>::type,\r\n                               this_class::bits_for_integral,\r\n                               this_class::bits_for_fractional,\r\n                               this_class::scaling_factor_exponent,\r\n                               overflow_policy,\r\n                               underflow_policy>;\r\n\r\n\r\n    /*!\r\n     \\brief Wraps the input integer _val as a fixed-point number.\r\n\r\n     <B>Usage</B>\r\n\r\n     <I>Example 1</I>:\r\n     \\code{.cpp}\r\n         #include \"fixed_point.hpp\"\r\n         #include <cstdint>\r\n     \r\n         int main(int, char**) {\r\n             using Q = libq::Q<30, 20>;\r\n     \r\n             std::uint8_t input{ 23u };\r\n             Q const fp = Q::wrap(input);\r\n     \r\n             return EXIT_SUCCESS;\r\n         }\r\n     \\endcode\r\n    */\r\n    template<typename T>\r\n    static this_class wrap(T const& _val) {\r\n        static_assert(std::is_integral<T>::value,\r\n                      \"input param must be of the built-in integral type\");\r\n\r\n        if ((_val < 0 && _val < this_class::least_stored_integer) ||\r\n            (_val > 0 && _val > this_class::largest_stored_integer)) {\r\n            overflow_policy::raise_event();\r\n        }\r\n\r\n        this_class x;\r\n        x.m_value = storage_type(_val);\r\n\r\n        return x;\r\n    }\r\n    static this_class wrap(float const&) = delete;\r\n    static this_class wrap(double const&) = delete;\r\n\r\n\r\n    fixed_point() = default;\r\n    COPY_CTR_EXPLICIT_SPECIFIER fixed_point(this_class const& _x) = default;  // NOLINT\r\n\r\n\r\n    /*!\r\n     \\brief Normalizes the input fixed-point number to be accepted by current\r\n     format.\r\n    */\r\n    template<typename T1,\r\n             std::size_t n1,\r\n             std::size_t f1,\r\n             int e1,\r\n             typename op1,\r\n             typename up1>\r\n    COPY_CTR_EXPLICIT_SPECIFIER\r\n        fixed_point(fixed_point<T1, n1, f1, e1, op1, up1> const& _x)\r\n        : m_value(\r\n            this_class::normalize(_x,\r\n                std::integral_constant<bool, (int(f1) + e1 - int(this_class::bits_for_fractional) - this_class::scaling_factor_exponent > 0)>())) { // NOLINT\r\n    }\r\n\r\n\r\n    /*!\r\n     \\brief Creates the fixed-point number from any arithmetic object.\r\n    */\r\n    template<typename T>\r\n    COPY_CTR_EXPLICIT_SPECIFIER fixed_point(T const& _value)\r\n        : m_value(\r\n            this_class::calc_stored_integer_from(_value,\r\n                                                 std::integral_constant<bool, std::is_floating_point<T>::value>())) {  // NOLINT\r\n    }\r\n\r\n\r\n    /*!\r\n     \\brief Assigns the fixed-point number being of different format.\r\n    */\r\n    template<typename T1,\r\n            std::size_t n1,\r\n            std::size_t f1,\r\n            int e1,\r\n            typename op1,\r\n            typename up1>\r\n    this_class& operator =(fixed_point<T1, n1, f1, e1, op1, up1> const& _x) {\r\n        using status_type =\r\n            std::integral_constant<bool,\r\n                            (static_cast<int>(f1) + e1 -\r\n                            static_cast<int>(this_class::bits_for_fractional) -\r\n                            this_class::scaling_factor_exponent > 0)>;  // NOLINT\r\n        return\r\n            this->set_value_to(this_class::normalize(_x, status_type()));\r\n    }\r\n    this_class& operator =(this_class const& _x) = default;\r\n\r\n\r\n    /*!\r\n     \\brief Assigns any arithmetic type.\r\n    */\r\n    template<typename T>\r\n    void operator =(T const& _x) {\r\n        static_assert(std::is_arithmetic<T>::value,\r\n                      \"T must be of the arithmetic type\");\r\n        using status_type = std::integral_constant<bool,\r\n                                             std::is_floating_point<T>::value>;\r\n\r\n        this->m_value =\r\n            this_class::calc_stored_integer_from(_x, status_type());\r\n    }\r\n\r\n\r\n    /*!\r\n     \\brief Converts this fixed-point number to the single-precision\r\n     floating-point number.\r\n    */\r\n    operator float() const {\r\n        return static_cast<float>(to_floating_point());\r\n    }\r\n\r\n\r\n    /*!\r\n     \\brief Converts this fixed-point number to the double-precision\r\n     floating-point number.\r\n    */\r\n    operator double() const {\r\n        return to_floating_point();\r\n    }\r\n\r\n\r\n    /*!\r\n     \\brief Gets the stored integer behind this fixed-point number.\r\n    */\r\n    storage_type value() const {\r\n        return this->m_value;\r\n    }\r\n\r\n\r\n    // Unfortunately, nobody can use BOOST.Operators here because it cannot\r\n    // handle the template operators\r\n#define COMPARISON_OPERATOR(op)\\\r\n    template<typename T>\\\r\n    bool operator op(T const& _x) const {\\\r\n        return this->value() op this_class(_x).value();\\\r\n     }\r\n\r\n    COMPARISON_OPERATOR(<);  // NOLINT\r\n    COMPARISON_OPERATOR(<=);  // NOLINT\r\n    COMPARISON_OPERATOR(>);  // NOLINT\r\n    COMPARISON_OPERATOR(>=);  // NOLINT\r\n    COMPARISON_OPERATOR(==);  // NOLINT\r\n    COMPARISON_OPERATOR(!=);  // NOLINT\r\n#undef COMPARISON_OPERATOR\r\n\r\n    bool operator !() const {\r\n        return this->value() == 0;\r\n    }\r\n\r\n    /*!\r\n     \\brief Fixed-point approximation of the widely-used constants.\r\n     \\note This uses the following naming convention:\r\n     - CONST_2PI is for \\f$2 * \\pi\\f$.\r\n     - CONST_2_PI is for \\f$\\frac{2}{\\pi}\\f$.\r\n     - CONST_PI_2 is for \\f$\\frac{\\pi}{2}\\f$.\r\n     \\note Weirdly, g++ 5.3.0 needs the full specification of type here.\r\n     Otherwise, it will not interpret lines 705-707 as declaration instead of\r\n     definition.\r\n    */\r\n    static fixed_point<value_type, n, f, e, op, up> const\r\n        CONST_E, CONST_LOG2E, CONST_1_LOG2E, CONST_LOG10E, CONST_LOG102,\r\n        CONST_LN2, CONST_LN10, CONST_2PI, CONST_PI, CONST_PI_2, CONST_PI_4,\r\n        CONST_1_PI, CONST_2_PI, CONST_2_SQRTPI, CONST_SQRT2, CONST_SQRT1_2,\r\n        CONST_2SQRT2;\r\n\r\n\r\n    /*!\r\n     \\brief Calculates the sum of the current fixed-point number and some\r\n     numeric object.\r\n     \\note If no extra significant bits is available for the promoted type then\r\n     the result type is equal to std::common_type<L, R>::type = L.\r\n    */\r\n    template<typename T>\r\n    typename libq::details::sum_traits<this_class>::promoted_type\r\n        operator +(T const& _x) const {\r\n        using sum_type = typename libq::details::sum_traits<this_class>::promoted_type;  // NOLINT\r\n        using word_type = typename sum_type::storage_type;\r\n\r\n        this_class const converted(_x);\r\n        if (details::does_add_overflow(*this, converted)) {\r\n            overflow_policy::raise_event();\r\n        }\r\n\r\n        word_type const stored_integer = word_type(this->value()) +\r\n            word_type(converted.value());\r\n        return sum_type::wrap(stored_integer);\r\n    }\r\n    template<typename T>\r\n    inline this_class& operator +=(T const& _x) {\r\n        this_class const result(*this + _x);\r\n\r\n        return this->set_value_to(result.value());\r\n    }\r\n\r\n\r\n    /*!\r\n     \\brief Subtracts some numeric object from the current fixed-point number.\r\n     \\note If no extra significant bits is available for the promoted type then\r\n     the result type is equal to std::common_type<L, R>::type = L.\r\n    */\r\n    template<typename T>\r\n    typename libq::details::sum_traits<this_class>::promoted_type\r\n        operator -(T const& _x) const {\r\n        using diff_type = typename libq::details::sum_traits<this_class>::promoted_type;  // NOLINT\r\n        using word_type = typename diff_type::storage_type;\r\n\r\n        this_class const converted(_x);\r\n        if (details::does_sub_overflow(*this, converted)) {\r\n            overflow_policy::raise_event();\r\n        }\r\n\r\n        word_type const stored_integer = word_type(this->value()) -\r\n            word_type(converted.value());\r\n        return diff_type::wrap(stored_integer);\r\n    }\r\n    template<typename T>\r\n    this_class operator -=(T const& _x) {\r\n        this_class const result(*this - _x);\r\n\r\n        return this->set_value_to(result.value());\r\n    }\r\n\r\n\r\n    /*!\r\n     \\brief Multiplies the current fixed-point number with some numeric object.\r\n     \\note If no extra significant bits is available for the promoted type then\r\n     the result type is equal to std::common_type<L, R>::type = L.\r\n    */\r\n    template<typename T1,\r\n             std::size_t n1,\r\n             std::size_t f1,\r\n             int e1,\r\n             class op1,\r\n             class up1>\r\n    typename libq::details::mult_of<this_class,\r\n                                    libq::fixed_point<T1, n1, f1, e1, op1, up1> >::promoted_type  // NOLINT\r\n        operator *(libq::fixed_point<T1, n1, f1, e1, op1, up1> const& _x)\r\n                                                                        const {\r\n        using operand_type =\r\n            typename libq::fixed_point<T1, n1, f1, e1, op1, up1>;\r\n        using promotion_traits = libq::details::mult_of<this_class,\r\n                                                        operand_type>;\r\n        using result_type = typename promotion_traits::promoted_type;\r\n        using word_type = typename promotion_traits::promoted_storage_type;\r\n\r\n        if (details::does_mul_overflow(*this, _x)) {\r\n            overflow_policy::raise_event();\r\n        }\r\n\r\n        // do the exact/approximate multiplication of fixed-point numbers\r\n        return result_type::wrap(\r\n            (static_cast<word_type>(this->value()) * static_cast<word_type>(_x.value()))  // NOLINT\r\n                >> (promotion_traits::is_expandable ? 0 : operand_type::bits_for_fractional));  // NOLINT\r\n    }\r\n    template<typename T1, std::size_t n1, std::size_t f1, int e1, class op1, class up1>  // NOLINT\r\n    this_class\r\n        operator *=(libq::fixed_point<T1, n1, f1, e1, op1, up1> const& _x) {\r\n        this_class const result(*this * _x);\r\n\r\n        return this->set_value_to(result.value());\r\n    }\r\n\r\n\r\n    /*!\r\n     \\brief Divides the current fixed-point number with some numeric object.\r\n     \\note If no extra significant bits is available for the promoted type then\r\n     the result type is equal to std::common_type<L, R>::type = L.\r\n    */\r\n    template<typename T1, std::size_t n1, std::size_t f1, int e1, class... Ps>\r\n    typename libq::details::div_of<this_class, libq::fixed_point<T1, n1, f1, e1, Ps...> >::promoted_type  // NOLINT\r\n        operator /(libq::fixed_point<T1, n1, f1, e1, Ps...> const& _x) const {\r\n        using operand_type = typename libq::fixed_point<T1, n1, f1, e1, Ps...>;\r\n        using promotion_traits =\r\n            libq::details::div_of<this_class, operand_type>;\r\n        using result_type = typename promotion_traits::promoted_type;\r\n        using word_type = typename promotion_traits::promoted_storage_type;\r\n\r\n        if (details::does_div_overflow(*this, _x)) {\r\n            overflow_policy::raise_event();\r\n        }\r\n\r\n        word_type const shifted = static_cast<word_type>(this->value()) << operand_type::number_of_significant_bits;  // NOLINT\r\n        if (!promotion_traits::is_expandable && _x.value() !=\r\n                (shifted >> operand_type::number_of_significant_bits)) {\r\n            overflow_policy::raise_event();\r\n        }\r\n\r\n        return\r\n            result_type::wrap(shifted / static_cast<word_type>(_x.value()));\r\n    }\r\n    template<typename T1, std::size_t n1, std::size_t f1, int e1, class... Ps>\r\n    this_class\r\n        operator /=(libq::fixed_point<T1, n1, f1, e1, Ps...> const& _x) {\r\n        this_class const result(*this / _x);\r\n\r\n        return this->set_value_to(result.value());\r\n    }\r\n\r\n\r\n    /*!\r\n     \\brief Gets the negative value of the current fixed-point number.\r\n    */\r\n    this_class operator -() const {\r\n        if (details::does_unary_neg_overflow(*this)) {\r\n            overflow_policy::raise_event();\r\n        }\r\n\r\n        return this_class::wrap(-this->value());\r\n    }\r\n\r\n private:\r\n    /*!\r\n     \\brief Represents some floating-point number as a fixed-point number.\r\n     \\note It uses the rounding-to-nearest logics in case of floating-point\r\n     types.\r\n    */\r\n    template<typename T>\r\n    static storage_type\r\n        calc_stored_integer_from(T const& _x, std::true_type) {\r\n        double const scale = static_cast<double>(\r\n                                          this_class::scaling_factor_exponent);\r\n        double const value = static_cast<double>(_x) / details::exp2(scale);\r\n        if (_x > T(0)) {\r\n            storage_type const converted = static_cast<storage_type>(\r\n                                  std::floor(value * this_class::scale + 0.5));\r\n            if (converted < 0) {\r\n                overflow_policy::raise_event();\r\n            }\r\n\r\n            return converted;\r\n        }\r\n\r\n        return\r\n            static_cast<storage_type>(\r\n                                   std::ceil(value * this_class::scale - 0.5));\r\n    }\r\n\r\n\r\n    /*!\r\n     \\brief Represents some integral number as a fixed-point number.\r\n    */\r\n    template<typename T>\r\n    static storage_type\r\n        calc_stored_integer_from(T const& _x, std::false_type) {\r\n        double const scale = static_cast<double>(\r\n                                          this_class::scaling_factor_exponent);\r\n        double const value = static_cast<double>(_x) / details::exp2(scale);\r\n        return storage_type(value) << this_class::bits_for_fractional;\r\n    }\r\n\r\n\r\n    /*!\r\n     \\brief Normalizes the input fixed-point number to one of the current\r\n     format in case \\f$f + e - f1 - e1 > 0\\f$.\r\n    */\r\n    template<typename T1, std::size_t n1, std::size_t f1, int e1, class... Ps>\r\n    static storage_type normalize(fixed_point<T1, n1, f1, e1, Ps...> const& _x,\r\n                                  std::false_type) {\r\n        static std::size_t const shifts =\r\n            (static_cast<int>(this_class::bits_for_fractional) + this_class::scaling_factor_exponent) -  // NOLINT\r\n            (static_cast<int>(e1) + f1);\r\n        storage_type const normalized = storage_type(_x.value()) << shifts;\r\n\r\n        if (_x.value() != (normalized >> shifts)) {\r\n            overflow_policy::raise_event();\r\n        }\r\n        return normalized;\r\n    }\r\n\r\n\r\n    /*!\r\n     \\brief Normalizes the input fixed-point number to one of the current\r\n     format in case \\f$f + e - f1 - e1 < 0\\f$.\r\n    */\r\n    template<typename T1, std::size_t n1, std::size_t f1, int e1, class... Ps>\r\n    static storage_type normalize(fixed_point<T1, n1, f1, e1, Ps...> const& _x,\r\n                                  std::true_type) {\r\n        static std::size_t const shifts =\r\n            (static_cast<int>(e1) + f1) -\r\n            (static_cast<int>(this_class::bits_for_fractional) + this_class::scaling_factor_exponent);  // NOLINT\r\n        storage_type const normalized =\r\n            static_cast<storage_type>(_x.value() >> shifts);\r\n\r\n        if (_x.value() && !normalized) {\r\n            underflow_policy::raise_event();\r\n        }\r\n        return normalized;\r\n    }\r\n\r\n\r\n    /*!\r\n     \\brief Converts the fixed-point number to the floating-point number.\r\n    */\r\n    double to_floating_point() const {\r\n        return\r\n            this->scaling_factor() * static_cast<double>(value()) / this_class::scale;  // NOLINT\r\n    }\r\n\r\n\r\n    storage_type m_value;\r\n    /*!\r\n     \\brief This also checks if the stored integer is within the range of\r\n     current fixed-point number.\r\n    */\r\n    this_class& set_value_to(storage_type const _x) {\r\n        if (_x < this_class::least_stored_integer ||\r\n            _x > this_class::largest_stored_integer) {\r\n            overflow_policy::raise_event();\r\n        }\r\n\r\n        this->m_value = _x;\r\n        return *this;\r\n    }\r\n\r\n    friend storage_type& lift<value_type, n, f, e, overflow_policy, underflow_policy>(this_class&);  // NOLINT\r\n};\r\n\r\n/*!\r\n \\brief Short-cut for the signed fixed-point with just 2 template parameters\r\n n and f.\r\n*/\r\ntemplate<std::size_t n, std::size_t f, int e = 0, class op = libq::ignorance_policy, class up = libq::ignorance_policy>  // NOLINT\r\nusing Q = libq::fixed_point<typename boost::int_t<n+1>::least, n-f, f, e, op, up>;  // NOLINT\r\n\r\n/*!\r\n \\brief Short-cut for the unsigned fixed-point with just 2 template parameters\r\n n and f.\r\n*/\r\ntemplate<std::size_t n, std::size_t f, int e = 0, class op = libq::ignorance_policy, class up = libq::ignorance_policy>  // NOLINT\r\nusing UQ = libq::fixed_point<typename boost::uint_t<n>::least, n-f, f, e, op, up>;  // NOLINT\r\n\r\n\r\n#define CONSTANT(name, value)\\\r\n    template<class T, std::size_t n, std::size_t f, int e, class op, class up>\\\r\n    fixed_point<T, n, f, e, op, up> const fixed_point<T, n, f, e, op, up>::name(value);  // NOLINT\r\n\r\n\r\nCONSTANT(CONST_E, 2.71828182845904523536)\r\nCONSTANT(CONST_1_LOG2E, 0.6931471805599453)\r\nCONSTANT(CONST_LOG2E, 1.44269504088896340736)\r\nCONSTANT(CONST_LOG10E, 0.434294481903251827651)\r\nCONSTANT(CONST_LOG102, 0.301029995663981195214)\r\nCONSTANT(CONST_LN2, 0.693147180559945309417)\r\nCONSTANT(CONST_LN10, 2.30258509299404568402)\r\nCONSTANT(CONST_2PI, 6.283185307179586)\r\nCONSTANT(CONST_PI, 3.14159265358979323846)\r\nCONSTANT(CONST_PI_2, 1.57079632679489661923)\r\nCONSTANT(CONST_PI_4, 0.785398163397448309616)\r\nCONSTANT(CONST_1_PI, 0.318309886183790671538)\r\nCONSTANT(CONST_2_PI, 0.636619772367581343076)\r\nCONSTANT(CONST_2_SQRTPI, 1.12837916709551257390)\r\nCONSTANT(CONST_SQRT2, 1.41421356237309504880)\r\nCONSTANT(CONST_SQRT1_2, 0.707106781186547524401)\r\nCONSTANT(CONST_2SQRT2, 2.82842712474619009760)\r\n\r\n#undef CONSTANT\r\n}  // namespace libq\r\n\r\n\r\n#include \"details/sum_traits.inl\"\r\n#include \"details/mult_of.inl\"\r\n#include \"details/div_of.inl\"\r\n\r\n#include \"details/sign.inl\"\r\n\r\n#include \"details/ceil.inl\"\r\n#include \"details/fabs.inl\"\r\n#include \"details/floor.inl\"\r\n#include \"details/round.inl\"\r\n#include \"details/remainder.inl\"\r\n#include \"details/fmod.inl\"\r\n#include \"details/numeric_limits.inl\"\r\n#include \"details/type_traits.inl\"\r\n\r\n#include \"loop_unroller.hpp\"\r\n\r\n\r\n#include \"CORDIC/lut/lut.hpp\"\r\n\r\n#include \"CORDIC/log.inl\"\r\n#include \"CORDIC/sqrt.inl\"\r\n\r\n#include \"CORDIC/sin.inl\"\r\n#include \"CORDIC/cos.inl\"\r\n#include \"CORDIC/tan.inl\"\r\n\r\n#include \"CORDIC/exp.inl\"\r\n\r\n#include \"CORDIC/sinh.inl\"\r\n#include \"CORDIC/cosh.inl\"\r\n#include \"CORDIC/tanh.inl\"\r\n\r\n#include \"CORDIC/acos.inl\"\r\n#include \"CORDIC/asin.inl\"\r\n#include \"CORDIC/atan.inl\"\r\n\r\n#include \"CORDIC/asinh.inl\"\r\n#include \"CORDIC/acosh.inl\"\r\n#include \"CORDIC/atanh.inl\"\r\n\r\n#endif  // INC_LIBQ_FIXED_POINT_HPP_\r\n", "meta": {"hexsha": "ccf9f140e2006da0c5a93ada74a3dc89f311b0bb", "size": 26653, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "libq/fixed_point.hpp", "max_stars_repo_name": "piotr-semenov/libq", "max_stars_repo_head_hexsha": "facfca4610da1ca366637dd030eae5ee06f0c792", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2016-06-15T09:08:40.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-21T11:57:09.000Z", "max_issues_repo_path": "libq/fixed_point.hpp", "max_issues_repo_name": "aka-sps/libq", "max_issues_repo_head_hexsha": "facfca4610da1ca366637dd030eae5ee06f0c792", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2018-04-05T18:11:09.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-30T12:11:09.000Z", "max_forks_repo_path": "libq/fixed_point.hpp", "max_forks_repo_name": "aka-sps/libq", "max_forks_repo_head_hexsha": "facfca4610da1ca366637dd030eae5ee06f0c792", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2018-07-31T23:18:22.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-19T07:45:43.000Z", "avg_line_length": 34.1705128205, "max_line_length": 158, "alphanum_fraction": 0.6032341575, "num_tokens": 6521, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5736784220301065, "lm_q2_score": 0.5428632831725052, "lm_q1q2_score": 0.31142895166848567}}
{"text": "//==============================================================================\n//         Copyright 2003 - 2011   LASMEA UMR 6602 CNRS/Univ. Clermont II\n//         Copyright 2009 - 2011   LRI    UMR 8623 CNRS/Univ Paris Sud XI\n//\n//          Distributed under the Boost Software License, Version 1.0.\n//                 See accompanying file LICENSE.txt or copy at\n//                     http://www.boost.org/LICENSE_1_0.txt\n//==============================================================================\n#ifndef NT2_TRIGONOMETRIC_CONSTANTS_PIX2_1_HPP_INCLUDED\n#define NT2_TRIGONOMETRIC_CONSTANTS_PIX2_1_HPP_INCLUDED\n\n#include <nt2/include/functor.hpp>\n#include <boost/simd/constant/hierarchy.hpp>\n#include <boost/simd/constant/register.hpp>\nnamespace nt2\n{\n  namespace tag\n  {\n   /*!\n     @brief Pix2_1 generic tag\n\n     Represents the Pix2_1 constant in generic contexts.\n\n     @par Models:\n        Hierarchy\n   **/\n    // 12.56637061\n    BOOST_SIMD_CONSTANT_REGISTER( Pix2_1, double\n                                , 1, 0x40c90f00\n                                , 0x401921fb54400000LL\n                                )\n  }\n  namespace ext\n  {\n   template<class Site>\n   BOOST_FORCEINLINE generic_dispatcher<tag::Pix2_1, Site> dispatching_Pix2_1(adl_helper, boost::dispatch::meta::unknown_<Site>, ...)\n   {\n     return generic_dispatcher<tag::Pix2_1, Site>();\n   }\n   template<class... Args>\n   struct impl_Pix2_1;\n  }\n  /*!\n    Constant used in modular computation involving \\f$\\pi\\f$\n\n    @par Semantic:\n\n    For type T0:\n\n    @code\n    T0 r = Pix2_1<T0>();\n    @endcode\n\n    @return a value of type T0\n  **/\n  BOOST_SIMD_CONSTANT_IMPLEMENTATION(tag::Pix2_1, Pix2_1);\n}\n\n#endif\n\n", "meta": {"hexsha": "b74adf6030b3feb494759e98750020d10c9e8b3c", "size": 1687, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/core/trigonometric/include/nt2/trigonometric/constants/pix2_1.hpp", "max_stars_repo_name": "feelpp/nt2", "max_stars_repo_head_hexsha": "4d121e2c7450f24b735d6cff03720f07b4b2146c", "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/trigonometric/include/nt2/trigonometric/constants/pix2_1.hpp", "max_issues_repo_name": "feelpp/nt2", "max_issues_repo_head_hexsha": "4d121e2c7450f24b735d6cff03720f07b4b2146c", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "modules/core/trigonometric/include/nt2/trigonometric/constants/pix2_1.hpp", "max_forks_repo_name": "feelpp/nt2", "max_forks_repo_head_hexsha": "4d121e2c7450f24b735d6cff03720f07b4b2146c", "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": 27.6557377049, "max_line_length": 133, "alphanum_fraction": 0.5720213397, "num_tokens": 428, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.603931819468636, "lm_q2_score": 0.5156199157230157, "lm_q1q2_score": 0.31139927385686567}}
{"text": "// Boost.Geometry\n\n// Copyright (c) 2018-2019 Barend Gehrels, Amsterdam, the Netherlands.\n\n// This file was modified by Oracle on 2020.\n// Modifications copyright (c) 2020 Oracle and/or its affiliates.\n// Contributed and/or modified by Adam Wulkiewicz, on behalf of Oracle\n\n// Use, modification and distribution is subject to the Boost Software License,\n// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n\n#ifndef BOOST_GEOMETRY_STRATEGIES_GEOGRAPHIC_BUFFER_POINT_CIRCLE_HPP\n#define BOOST_GEOMETRY_STRATEGIES_GEOGRAPHIC_BUFFER_POINT_CIRCLE_HPP\n\n#include <cstddef>\n\n#include <boost/range/value_type.hpp>\n\n#include <boost/geometry/util/math.hpp>\n#include <boost/geometry/util/select_calculation_type.hpp>\n\n#include <boost/geometry/strategies/buffer.hpp>\n\n\nnamespace boost { namespace geometry\n{\n\nnamespace strategy { namespace buffer\n{\n\n/*!\n\\brief Create a circular buffer around a point, on the Earth\n\\ingroup strategies\n\\details This strategy can be used as PointStrategy for the buffer algorithm.\n    It creates a circular buffer around a point, on the Earth. It can be applied\n    for points and multi_points.\n\n\\qbk{\n[heading Example]\n[buffer_geographic_point_circle]\n[buffer_geographic_point_circle_output]\n[heading See also]\n\\* [link geometry.reference.algorithms.buffer.buffer_7_with_strategies buffer (with strategies)]\n\\* [link geometry.reference.strategies.strategy_buffer_point_circle point_circle]\n\\* [link geometry.reference.strategies.strategy_buffer_point_square point_square]\n}\n */\ntemplate\n<\n    typename FormulaPolicy = strategy::andoyer,\n    typename Spheroid = srs::spheroid<double>,\n    typename CalculationType = void\n>\nclass geographic_point_circle\n{\npublic :\n    //! \\brief Constructs the strategy\n    //! \\param count number of points for the created circle (if count\n    //! is smaller than 3, count is internally set to 3)\n    explicit geographic_point_circle(std::size_t count = 90)\n        : m_count((count < 3u) ? 3u : count)\n    {}\n\n#ifndef DOXYGEN_SHOULD_SKIP_THIS\n    //! Fills output_range with a circle around point using distance_strategy\n    template\n    <\n        typename Point,\n        typename OutputRange,\n        typename DistanceStrategy\n    >\n    inline void apply(Point const& point,\n                DistanceStrategy const& distance_strategy,\n                OutputRange& output_range) const\n    {\n        typedef typename boost::range_value<OutputRange>::type output_point_type;\n\n        typedef typename select_calculation_type\n            <\n                Point, output_point_type,\n                CalculationType\n                //double\n            >::type calculation_type;\n\n        calculation_type const buffer_distance = distance_strategy.apply(point, point,\n                        strategy::buffer::buffer_side_left);\n\n        typedef typename FormulaPolicy::template direct\n            <\n                calculation_type, true, false, false, false\n            > direct_t;\n\n        calculation_type const two_pi = geometry::math::two_pi<calculation_type>();\n        calculation_type const pi = geometry::math::pi<calculation_type>();\n\n        calculation_type const diff = two_pi / calculation_type(m_count);\n        // TODO: after calculation of some angles is corrected,\n        // we can start at 0.0\n        calculation_type angle = 0.001;\n\n        for (std::size_t i = 0; i < m_count; i++, angle += diff)\n        {\n            if (angle > pi)\n            {\n                angle -= two_pi;\n            }\n\n            typename direct_t::result_type\n                dir_r = direct_t::apply(get_as_radian<0>(point), get_as_radian<1>(point),\n                                        buffer_distance, angle,\n                                        m_spheroid);\n            output_point_type p;\n            set_from_radian<0>(p, dir_r.lon2);\n            set_from_radian<1>(p, dir_r.lat2);\n            output_range.push_back(p);\n        }\n\n        {\n            // Close the range\n            const output_point_type p = output_range.front();\n            output_range.push_back(p);\n        }\n    }\n#endif // DOXYGEN_SHOULD_SKIP_THIS\n\nprivate :\n    std::size_t m_count;\n    Spheroid m_spheroid;\n};\n\n\n}} // namespace strategy::buffer\n\n}} // namespace boost::geometry\n\n#endif // BOOST_GEOMETRY_STRATEGIES_GEOGRAPHIC_BUFFER_POINT_CIRCLE_HPP\n", "meta": {"hexsha": "8d6643d73d6844bde40435bc0f31ac3468240c7e", "size": 4346, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ReactNativeFrontend/ios/Pods/boost/boost/geometry/strategies/geographic/buffer_point_circle.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/geometry/strategies/geographic/buffer_point_circle.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": 130.0, "max_issues_repo_issues_event_min_datetime": "2016-06-22T22:11:25.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-29T20:24:09.000Z", "max_forks_repo_path": "ReactNativeFrontend/ios/Pods/boost/boost/geometry/strategies/geographic/buffer_point_circle.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.4927536232, "max_line_length": 96, "alphanum_fraction": 0.6723423838, "num_tokens": 946, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6926419831347361, "lm_q2_score": 0.44939263446475963, "lm_q1q2_score": 0.31126820554181467}}
{"text": "/** \\file   pr_kmeans.cpp\n    \\brief  Implement kmeans method with different initialization scheme\n    \\author Hui Xue\n*/\n\n#include \"pr_kmeans.h\"\n#include \"log.h\"\n\n#include \"hoNDArray_reductions.h\"\n#include \"hoNDArray_elemwise.h\"\n#include \"hoNDArray_math.h\"\n#include \"hoNDArray_linalg.h\"\n\n#include <boost/math/special_functions/sign.hpp>\n\n#include <random>\n\nnamespace Gadgetron { \n\ntemplate <typename T> \nkmeans<T>::kmeans()\n{\n    max_iter_ = 100;\n    replicates_ = 10;\n    perform_online_update_ = true;\n\n    verbose_ = false;\n    perform_timing_ = false;\n\n    gt_timer_local_.set_timing_in_destruction(false);\n    gt_timer_.set_timing_in_destruction(false);\n}\n\ntemplate <typename T>\nkmeans<T>::~kmeans()\n{\n}\n\ntemplate <typename T>\nvoid kmeans<T>::get_initial_guess_sample(const ArrayType& X, size_t K, ArrayType& C_for_initial)\n{\n    try\n    {\n        if (this->perform_timing_) gt_timer_local_.start(\"get_initial_guess_sample\");\n\n        size_t P = X.get_size(0);\n        size_t N = X.get_size(1);\n\n        GADGET_CHECK_THROW(N>K);\n\n        std::random_device rd;\n        std::mt19937 gen(rd());\n        std::uniform_real_distribution<> dis(0, 1);\n\n        C_for_initial.create(P, K, this->replicates_);\n        Gadgetron::clear(C_for_initial);\n\n        size_t n, k;\n        for (n = 0; n < this->replicates_; n++)\n        {\n            for (k = 0; k < K; k++)\n            {\n                size_t ind = (size_t)(dis(gen)*N);\n                if (ind >= N) ind = N - 1;\n                memcpy(&C_for_initial(0, k, n), &X(0, ind), sizeof(T)*P);\n            }\n        }\n\n        if (this->perform_timing_) gt_timer_local_.stop();\n    }\n    catch(...)\n    {\n        GERROR_STREAM(\"Exceptions happened in kmeans<T>::get_initial_guess_sample(...) ... \");\n    }\n}\n\ntemplate <typename T>\nvoid kmeans<T>::get_initial_guess_uniform(const ArrayType& X, size_t K, ArrayType& C_for_initial)\n{\n    try\n    {\n        if (this->perform_timing_) gt_timer_local_.start(\"get_initial_guess_uniform\");\n\n        size_t P = X.get_size(0);\n        size_t N = X.get_size(1);\n\n        GADGET_CHECK_THROW(N>K);\n\n        std::random_device rd;\n        std::mt19937 gen(rd());\n        std::uniform_real_distribution<> dis(0, 1);\n\n        C_for_initial.create(P, K, this->replicates_);\n        Gadgetron::clear(C_for_initial);\n\n        // find the range of X\n        std::vector<T> xmin(P, 0);\n        std::vector<T> xmax(P, 0);\n\n        size_t p, n, k;\n\n        for (p = 0; p<P; p++)\n        {\n            xmin[p] = X(p, 0);\n            xmax[p] = xmin[p];\n            for (n = 1; n < N; n++)\n            {\n                T v = X(p, n);\n                if (v < xmin[p]) xmin[p] = v;\n                if (v > xmax[p]) xmax[p] = v;\n            }\n        }\n\n        for (n = 0; n < this->replicates_; n++)\n        {\n            for (k = 0; k < K; k++)\n            {\n                for (p = 0; p < P; p++)\n                {\n                    T v = xmin[p] + dis(gen) * (xmax[p] - xmin[p]);\n                    C_for_initial(p, k, n) = v;\n                }\n            }\n        }\n\n        if (this->perform_timing_) gt_timer_local_.stop();\n    }\n    catch (...)\n    {\n        GERROR_STREAM(\"Exceptions happened in kmeans<T>::get_initial_guess_uniform(...) ... \");\n    }\n}\n\ntemplate <typename T>\nvoid kmeans<T>::get_initial_guess_cluster(const ArrayType& X, size_t K, ArrayType& C_for_initial)\n{\n    try\n    {\n        if (this->perform_timing_) gt_timer_.start(\"get_initial_guess_cluster\");\n\n        size_t P = X.get_size(0);\n        size_t N = X.get_size(1);\n\n        GADGET_CHECK_THROW(N>K);\n\n        std::random_device rd;\n        std::mt19937 gen(rd());\n        std::uniform_real_distribution<> dis(0, 1);\n\n        C_for_initial.create(P, K, this->replicates_);\n        Gadgetron::clear(C_for_initial);\n\n        // randomly pick 20% of data\n        double ratio = 0.2;\n        size_t M = (size_t)(ratio*N);\n        while(M<K && ratio<=1.0)\n        {\n            ratio = ratio + 0.1;\n            M = (size_t)(ratio*N);\n        }\n\n        if(M>=N)\n        {\n            GWARN_STREAM(\"Too few samples in the data array X ... \");\n            this->get_initial_guess_sample(X, K, C_for_initial);\n            return;\n        }\n\n        ArrayType X_subset;\n        X_subset.create(P, M);\n\n        ArrayType C_for_initial_subset;\n        ClusterType IDX;\n        ArrayType C;\n        T sumD;\n\n        size_t n, m;\n        for (n = 0; n < this->replicates_; n++)\n        {\n            for (m = 0; m < M; m++)\n            {\n                size_t ind = (size_t)(dis(gen)*N);\n                if (ind >= N) ind = N - 1;\n                memcpy(&X_subset(0, m), &X(0, ind), sizeof(T)*P);\n            }\n\n            this->get_initial_guess_sample(X_subset, K, C_for_initial_subset);\n\n            // call kmeans\n            this->run(X_subset, K, C_for_initial_subset, IDX, C, sumD);\n\n            memcpy(&C_for_initial(0, 0, n), C.begin(), sizeof(T)*K*P);\n        }\n\n        if (this->perform_timing_) gt_timer_.stop();\n    }\n    catch (...)\n    {\n        GERROR_STREAM(\"Exceptions happened in kmeans<T>::get_initial_guess_cluster(...) ... \");\n    }\n}\n\ntemplate <typename T>\nvoid kmeans<T>::get_initial_guess_kmeansplusplus(const ArrayType& X, size_t K, ArrayType& C_for_initial)\n{\n    try\n    {\n        if (this->perform_timing_) gt_timer_.start(\"get_initial_guess_kmeansplusplus\");\n\n        size_t P = X.get_size(0);\n        size_t N = X.get_size(1);\n\n        GADGET_CHECK_THROW(N>K);\n\n        std::random_device rd;\n        std::mt19937 gen(rd());\n        std::uniform_real_distribution<> dis(0, 1);\n\n        C_for_initial.create(P, K, this->replicates_);\n        Gadgetron::clear(C_for_initial);\n\n        ClusterType IDX;\n        IDX.resize(N, 0);\n\n        // find the first center\n        ArrayType C;\n        C.create(P, K);\n        Gadgetron::clear(C);\n\n        VectorType norm_C(K, 0);\n\n        ArrayType D;\n        D.create(P, N);\n\n        ArrayType D_norm;\n        D_norm.create(N);\n\n        ArrayType cumsum_D_norm;\n        cumsum_D_norm.create(N);\n\n        ArrayType CX;\n\n        size_t n, i, t, s;\n\n        for (n = 0; n < this->replicates_; n++)\n        {\n            size_t ind = (size_t)(dis(gen)*N);\n            if (ind >= N) ind = N - 1;\n            memcpy(&C(0, 0), &X(0, ind), sizeof(T)*P);\n\n            ArrayType aC;\n            aC.create(P, C.begin());\n            norm_C[0] = Gadgetron::dot(aC, aC,false);\n\n            for (i = 1; i < K; i++)\n            {\n                // compute distance to the nearest centroid for all data points\n                this->compute_dist(X, IDX, C, D);\n\n                // compute norm of distance vector\n                this->compute_norm_dist(D, D_norm);\n\n                // compute accumulated distrance\n                cumsum_D_norm(0) = D_norm(0);\n                for (t = 1; t < N; t++)\n                {\n                    cumsum_D_norm(t) = cumsum_D_norm(t - 1) + D_norm(t);\n                }\n\n                if (std::abs(cumsum_D_norm(N - 1)) < FLT_EPSILON)\n                {\n                    GERROR_STREAM(\"std::abs(cumsum_D_norm(N-1))<FLT_EPSILON ... \");\n                    // set centroid from i to K\n\n                    for (s = i; s < K; s++)\n                    {\n                        size_t ind = (size_t)(dis(gen)*N);\n                        if (ind >= N) ind = N - 1;\n                        memcpy(&C(0, s), &X(0, ind), sizeof(T)*P);\n                    }\n                    break;\n                }\n\n                // convert to probability\n                for (t = 0; t < N; t++)\n                {\n                    cumsum_D_norm(t) /= cumsum_D_norm(N - 1);\n                }\n\n                T v = dis(gen);\n                for (t = 0; t < N; t++)\n                {\n                    if (cumsum_D_norm(t)>=v) break;\n                }\n\n                memcpy(&C(0, i), &X(0, t), sizeof(T)*P);\n\n                aC.create(P, &C(0, i));\n                norm_C[i] = Gadgetron::dot(aC, aC,false);\n\n                // update the IDX\n                ArrayType curr_C;\n                curr_C.create(P, i+1, C.begin());\n\n                this->update_IDX(X, curr_C, norm_C, IDX);\n            }\n\n            memcpy(&C_for_initial(0, 0, n), C.begin(), sizeof(T)*P*K);\n        }\n\n        if (this->perform_timing_) gt_timer_.stop();\n    }\n    catch (...)\n    {\n        GERROR_STREAM(\"Exceptions happened in kmeans<T>::get_initial_guess_kmeansplusplus(...) ... \");\n    }\n}\n\ntemplate <typename T>\nvoid kmeans<T>::run_replicates(const ArrayType& X, size_t K, const ArrayType& C_for_initial, ClusterType& IDX, ArrayType& C, VectorType& sumD_rep, T& sumD)\n{\n    try\n    {\n        Gadgetron::GadgetronTimer timer;\n        timer.set_timing_in_destruction(false);\n\n        if (this->perform_timing_) gt_timer_.start(\"run_replicates\");\n\n        size_t P = X.get_size(0);\n        size_t N = X.get_size(1);\n\n        GADGET_CHECK_THROW(N>K);\n        GADGET_CHECK_THROW(C_for_initial.get_size(0) == P);\n        GADGET_CHECK_THROW(C_for_initial.get_size(1) == K);\n\n        size_t R = C_for_initial.get_size(2);\n\n        std::vector<ArrayType> C_rep(R);\n        std::vector<ClusterType> IDX_rep(R);\n\n        sumD_rep.resize(R, 0);\n\n        size_t r;\n        for (r=0; r<R; r++)\n        {\n            std::stringstream outs;\n            outs << \"-----> Kmeans, replicate \" << r << \" out of \" << R;\n\n            if (this->verbose_)\n            {\n                GDEBUG_STREAM(outs.str());\n            }\n\n            ArrayType curr_C_initial;\n            curr_C_initial.create(P, K, const_cast<T*>(&C_for_initial(0, 0, r)) );\n\n            if (this->perform_timing_) timer.start(outs.str().c_str());\n            this->run(X, K, curr_C_initial, IDX_rep[r], C_rep[r], sumD_rep[r]);\n            if (this->perform_timing_) timer.stop();\n\n            if(this->verbose_)\n            {\n                GDEBUG_STREAM(\"Kmeans, replicate \" << r << \" out of \" << R << \" - \" << sumD_rep[r]);\n            }\n        }\n\n        size_t best_r = 0;\n        sumD = sumD_rep[0];\n        for (r = 1; r < R; r++)\n        {\n            if(sumD>sumD_rep[r])\n            {\n                sumD = sumD_rep[r];\n                best_r = r;\n            }\n        }\n\n        IDX = IDX_rep[best_r];\n        C = C_rep[best_r];\n\n        if (this->perform_timing_) gt_timer_.stop();\n    }\n    catch(...)\n    {\n        GERROR_STREAM(\"Exceptions happened in kmeans<T>::run_replicates(...) ... \");\n    }\n}\n\ntemplate <typename T>\nvoid kmeans<T>::run(const ArrayType& X, size_t K, const ArrayType& C_for_initial, ClusterType& IDX, ArrayType& C, T& sumD)\n{\n    try\n    {\n        size_t P = X.get_size(0);\n        size_t N = X.get_size(1);\n\n        GADGET_CHECK_THROW(N>K);\n        GADGET_CHECK_THROW(C_for_initial.get_size(0) == P);\n        GADGET_CHECK_THROW(C_for_initial.get_size(1) == K);\n\n        this->replicates_ = C_for_initial.get_size(2);\n\n        IDX.resize(N, 0);\n        C.create(P, K);\n        Gadgetron::clear(C);\n        sumD  = 0;\n\n        C = C_for_initial;\n\n        VectorType norm_C(K, 0);\n\n        size_t k, p;\n        for (k=0; k<K; k++)\n        {\n            T v = 0;\n            for (p=0; p<P; p++)\n            {\n                v += C(p, k)*C(p, k);\n            }\n\n            norm_C[k] = v;\n        }\n\n        // first round of clustering\n        this->update_IDX(X, C, norm_C, IDX);\n\n        ClusterType prev_IDX;\n        ArrayType D, D_norm;\n\n        size_t num_iter = 0;\n        T prev_sumD = std::numeric_limits<T>::max();\n\n        std::vector<size_t> cluster_size;\n\n        while (num_iter<=this->max_iter_ &&  this->is_clustering_changed(prev_IDX, IDX))\n        {\n            prev_IDX = IDX;\n\n            // update the centroid\n            this->update_centroid(X, IDX, C, norm_C);\n            // update clustering\n            this->update_IDX(X, C, norm_C, IDX);\n\n            this->compute_dist(X, IDX, C, D);\n            this->compute_norm_dist(D, D_norm);\n\n            // if there are clusters having no member, find a point furthest away from its own cluster centroid\n            // replace the empty cluster centroid with this point\n            std::vector<size_t> empty_clusters;\n            this->has_empty_cluster(C, IDX, cluster_size, empty_clusters);\n\n            if (!empty_clusters.empty())\n            {\n                if (this->verbose_)\n                {\n                    GDEBUG_STREAM(\"Kmeas iteration, found empty cluster : iter - \" << num_iter);\n                }\n\n                size_t e;\n                for (e = 0; e < empty_clusters.size(); e++)\n                {\n                    // find the most \"lonely\" point\n                    size_t lonely(0);\n                    this->find_lonely_point(IDX, D_norm, cluster_size, lonely);\n\n                    // replace this empty centroid with the lonely point, update IDX\n                    IDX[lonely] = empty_clusters[e];\n\n                    // updates centroid\n                    this->update_centroid(X, IDX, C, norm_C);\n\n                    // update distances\n                    this->compute_dist(X, IDX, C, D);\n                    this->compute_norm_dist(D, D_norm);\n                }\n            }\n\n            sumD = 0;\n            for (p = 0; p<N; p++)\n            {\n                sumD += D_norm(p)*D_norm(p);\n            }\n\n            if (sumD>prev_sumD)\n            {\n                if (this->verbose_)\n                {\n                    GDEBUG_STREAM(\"Kmeas iteration terminated due to increasted total distance : iter \" << num_iter << \" - \" << sumD << \" > \" << prev_sumD);\n                }\n\n                IDX = prev_IDX;\n\n                break;\n            }\n            else\n            {\n                prev_sumD = sumD;\n            }\n\n            num_iter++;\n        }\n\n        if (this->verbose_)\n        {\n            GDEBUG_STREAM(\"Kmeas iteration stopped : iter \" << num_iter << \" - \" << sumD);\n        }\n\n        if(this->perform_online_update_)\n        {\n            this->perform_online_update(X, IDX, C, sumD);\n            if (this->verbose_)\n            {\n                GDEBUG_STREAM(\"Kmeas online update : \" << sumD);\n            }\n        }\n    }\n    catch (...)\n    {\n        GERROR_STREAM(\"Exceptions happened in kmeans<T>::run(...) ... \");\n    }\n}\n\ntemplate <typename T>\nvoid kmeans<T>::compute_dist(const ArrayType& X, const ClusterType& IDX, const ArrayType& C, ArrayType& D)\n{\n    try\n    {\n        size_t P = X.get_size(0);\n        size_t N = X.get_size(1);\n\n        size_t K = C.get_size(1);\n\n        GADGET_CHECK_THROW(N== IDX.size());\n\n        D.create(P, N);\n        Gadgetron::clear(D);\n\n        const T* pX = X.begin();\n        const T* pC = C.begin();\n        T* pD = D.begin();\n\n        long long p, n;\n\n#pragma omp parallel for default(none) private(n, p) shared(N, IDX, K, P, pD, pX, pC)\n        for (n=0; n<N; n++)\n        {\n            size_t nC = IDX[n];\n\n            if (nC >= K)\n            {\n                // GWARN_STREAM(\"nC >= K :\" << nC << \" - \" << K << \" for \" << n);\n                continue;\n            }\n\n            for (p=0; p<P; p++)\n            {\n                pD[p + n*P] = pX[p + n*P] - pC[p + nC*P];\n            }\n        }\n    }\n    catch (...)\n    {\n        GERROR_STREAM(\"Exceptions happened in kmeans<T>::compute_dist(...) ... \");\n    }\n}\n\ntemplate <typename T>\nvoid kmeans<T>::compute_norm_dist(const ArrayType& D, ArrayType& D_norm)\n{\n    try\n    {\n        size_t P = D.get_size(0);\n        size_t N = D.get_size(1);\n\n        D_norm.create(N);\n        Gadgetron::clear(D_norm);\n\n        const T* pD = D.begin();\n\n        long long n, p;\n\n#pragma omp parallel for default(none) private(n, p) shared(N, P, pD, D_norm)\n        for(n=0; n<N; n++)\n        {\n            T v = 0;\n            for (p = 0; p<P; p++)\n            {\n                v += pD[p + n*P] * pD[p + n*P];\n            }\n\n            D_norm(n) = std::sqrt(v);\n        }\n    }\n    catch (...)\n    {\n        GERROR_STREAM(\"Exceptions happened in kmeans<T>::compute_norm_dist(...) ... \");\n    }\n}\n\ntemplate <typename T>\nvoid kmeans<T>::update_IDX(const ArrayType& X, const ArrayType& C, const VectorType& norm_C, ClusterType& IDX)\n{\n    try\n    {\n        size_t P = X.get_size(0);\n        size_t N = X.get_size(1);\n\n        size_t K = C.get_size(1);\n\n        IDX.resize(N);\n\n        ArrayType CX;\n        Gadgetron::gemm(CX, C, true, X, false);\n\n        size_t t, s;\n\n        for (t = 0; t < N; t++)\n        {\n            for (s = 0; s < K; s++)\n            {\n                CX(s, t) = 2* CX(s, t) - norm_C[s];\n            }\n\n            T maxCX = CX(0, t);\n            IDX[t] = 0;\n            for (s = 1; s < K; s++)\n            {\n                if (CX(s, t) > maxCX)\n                {\n                    maxCX = CX(s, t);\n                    IDX[t] = s;\n                }\n            }\n        }\n    }\n    catch (...)\n    {\n        GERROR_STREAM(\"Exceptions happened in kmeans<T>::update_IDX(...) ... \");\n    }\n}\n\ntemplate <typename T>\nvoid kmeans<T>::update_centroid(const ArrayType& X, const ClusterType& IDX, ArrayType& C, VectorType& norm_C)\n{\n    try\n    {\n        size_t P = X.get_size(0);\n        size_t N = X.get_size(1);\n        const T* pX = X.begin();\n\n        size_t K = C.get_size(1);\n\n        norm_C.resize(K);\n\n        std::vector<size_t> num_in_C(K, 0);\n\n        Gadgetron::clear(C);\n        T* pC = C.begin();\n\n        size_t n, p;\n        for (n=0; n<N; n++)\n        {\n            size_t currK = IDX[n];\n\n            if(currK<K)\n            {\n                for (p=0; p<P; p++)\n                {\n                    pC[p+currK*P] += pX[p+n*P];\n                }\n\n                num_in_C[currK]++;\n            }\n            else\n            {\n                GERROR_STREAM(\"kmeans, currC>=K, in update_centroid : \" << n);\n            }\n        }\n\n        for (n = 0; n < K; n++)\n        {\n            T v = 0;\n            for (p = 0; p<P; p++)\n            {\n                if (num_in_C[n] > 0)\n                {\n                    pC[p + n*P] /= num_in_C[n];\n                    v += pC[p + n*P] * pC[p + n*P];\n                }\n            }\n\n            norm_C[n] = v;\n        }\n    }\n    catch (...)\n    {\n        GERROR_STREAM(\"Exceptions happened in kmeans<T>::update_centroid(...) ... \");\n    }\n}\n\ntemplate <typename T>\nvoid kmeans<T>::has_empty_cluster(const ArrayType& C, const ClusterType& IDX, std::vector<size_t>& cluster_size, std::vector<size_t>& empty_clusters)\n{\n    try\n    {\n        size_t K = C.get_size(1);\n        size_t N = IDX.size();\n\n        cluster_size.resize(K, 0);\n\n        size_t n;\n        for (n=0; n<N; n++)\n        {\n            if (IDX[n] < K)\n            {\n                cluster_size[IDX[n]]++;\n            }\n        }\n\n        empty_clusters.clear();\n        for (n = 0; n < K; n++)\n        {\n            if(cluster_size[n]==0)\n            {\n                empty_clusters.push_back(n);\n            }\n        }\n    }\n    catch (...)\n    {\n        GERROR_STREAM(\"Exceptions happened in kmeans<T>::has_empty_cluster(...) ... \");\n    }\n}\n\ntemplate <typename T>\nvoid kmeans<T>::find_lonely_point(const ClusterType& IDX, const ArrayType& D_norm, const std::vector<size_t>& cluster_size, size_t& lonely)\n{\n    try\n    {\n        size_t N = IDX.size();\n\n        T maxD (0);\n        Gadgetron::maxAbsolute(D_norm, maxD, lonely);\n\n        size_t cluster = IDX[lonely];\n\n        size_t n, c;\n\n        if(cluster_size[cluster]<2)\n        {\n            // if the picked cluster has only one member ...\n            std::vector<size_t> big_clusters;\n            for (c=0; c<cluster_size.size(); c++)\n            {\n                if(cluster_size[c]>2)\n                {\n                    big_clusters.push_back(c);\n                }\n            }\n\n            if(big_clusters.empty())\n            {\n                GADGET_THROW(\"All clusters have only one member ... \");\n            }\n            else\n            {\n                size_t cluster_picked = big_clusters[big_clusters.size() / 2]; // pick one cluster\n\n                // find the furthest point in the picked cluster\n                lonely = 0;\n                maxD = 0;\n                for (n=0; n<N; n++)\n                {\n                    if(IDX[n]==cluster_picked)\n                    {\n                        if(D_norm(n)>maxD)\n                        {\n                            maxD = D_norm(n);\n                            lonely = n;\n                        }\n                    }\n                }\n            }\n        }\n    }\n    catch (...)\n    {\n        GERROR_STREAM(\"Exceptions happened in kmeans<T>::find_lonely_point(...) ... \");\n    }\n}\n\ntemplate <typename T>\nbool kmeans<T>::is_clustering_changed(const ClusterType&prev_IDX, const ClusterType& IDX)\n{\n    try\n    {\n        if (prev_IDX.size() != IDX.size()) return true;\n\n        size_t N = IDX.size();\n\n        size_t n;\n        for (n=0; n<N; n++)\n        {\n            if (prev_IDX[n] != IDX[n])\n            {\n                return true;\n            }\n        }\n\n        return false;\n    }\n    catch (...)\n    {\n        GERROR_STREAM(\"Exceptions happened in kmeans<T>::is_clustering_changed(...) ... \");\n        return false;\n    }\n}\n\ntemplate <typename T>\nvoid kmeans<T>::perform_online_update(const ArrayType& X, ClusterType& IDX, ArrayType& C, T& sumD)\n{\n    try\n    {\n        size_t P = X.get_size(0);\n        size_t N = X.get_size(1);\n        const T* pX = X.begin();\n\n        size_t K = C.get_size(1);\n\n        ArrayType del_cost; // store the delat change of sum cost if reassign a point\n        del_cost.create(N, K);\n\n        // count the number of points in each cluster\n        std::vector<size_t> num_pt_clusters(K, 0);\n\n        size_t n, p, k;\n\n        num_pt_clusters.resize(K, 0);\n        for (n = 0; n < N; n++)\n        {\n            num_pt_clusters[IDX[n]]++;\n        }\n\n        size_t iter(0);\n\n        size_t lastmoved = 0;\n        size_t nummoved = 0;\n        ClusterType prevIDX, newIDX(IDX);\n\n        while (iter < this->max_iter_)\n        {\n            // for every cluster K and every point N\n            // compute change of delta sum cost\n            for (k = 0; k < K; k++)\n            {\n                for (n = 0; n < N; n++)\n                {\n                    T v;\n                    if (IDX[n] == k)\n                    {\n                        if (num_pt_clusters[k] > 1)\n                            v = (T)num_pt_clusters[k] / (T)(num_pt_clusters[k] - 1);\n                        else\n                            v = 1;\n                    }\n                    else\n                        v = (T)num_pt_clusters[k] / (T)(num_pt_clusters[k] + 1);\n\n                    T t(0), d = 0;\n                    for (p = 0; p < P; p++)\n                    {\n                        t = X(p, n) - C(p, k);\n                        d += t*t;\n                    }\n\n                    del_cost(n, k) = v * d;\n                }\n            }\n\n            prevIDX = IDX;\n\n            // get the new IDX\n            for (n = 0; n < N; n++)\n            {\n                newIDX[n] = 0;\n                T min_del_cost = del_cost(n, 0);\n                for (k = 1; k < K; k++)\n                {\n                    if(del_cost(n, k) < min_del_cost)\n                    {\n                        newIDX[n] = k;\n                        min_del_cost = del_cost(n, k);\n                    }\n                }\n            }\n\n            // marked the moving points\n            std::vector<size_t> moved;\n            for (n = 0; n < N; n++)\n            {\n                if(prevIDX[n] != newIDX[n])\n                {\n                    moved.push_back(n);\n                }\n            }\n\n            // if no candidates to move, stop\n            if(moved.empty())\n            {\n                iter++;\n                break;\n            }\n\n            // pick a point to move\n            int moved_ind = N+1;\n            int tt(0);\n            for (size_t ii = 0; ii < moved.size(); ii++)\n            {\n                tt = (int)moved[ii] - (int)lastmoved - 1;\n                if (tt < 0) tt += N;\n                if (tt >= N) tt -= N;\n\n                tt += lastmoved;\n\n                if (tt < moved_ind) moved_ind = tt;\n            }\n\n            if (tt < 0) tt += N;\n            if (tt >= N) tt -= N;\n            moved_ind = (size_t)(tt);\n\n            if(moved_ind<=lastmoved)\n            {\n                iter++;\n                if (iter >= this->max_iter_) break;\n                nummoved = 0;\n            }\n\n            nummoved++;\n            lastmoved = moved_ind;\n\n            size_t oidx = IDX[moved_ind];\n            size_t nidx = newIDX[moved_ind];\n\n            sumD = sumD + del_cost(moved_ind, nidx) - del_cost(moved_ind, oidx);\n\n            IDX[moved_ind] = nidx;\n\n            num_pt_clusters[oidx]--;\n            num_pt_clusters[nidx]++;\n\n            for (p=0; p<P; p++)\n            {\n                C(p, nidx) = C(p, nidx) + (X(p, moved_ind) - C(p, nidx)) / num_pt_clusters[nidx];\n                C(p, oidx) = C(p, oidx) - (X(p, moved_ind) - C(p, oidx)) / num_pt_clusters[oidx];\n            }\n        }\n    }\n    catch (...)\n    {\n        GERROR_STREAM(\"Exceptions happened in kmeans<T>::perform_online_update(...) ... \");\n    }\n}\n\n// ------------------------------------------------------------\n// Instantiation\n// ------------------------------------------------------------\n\ntemplate class EXPORTPR kmeans< float >;\ntemplate class EXPORTPR kmeans< double >;\n\n}\n", "meta": {"hexsha": "e769e0fb39a7d7a7c9dc2b6c335b17da0faf2c93", "size": 25341, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "toolboxes/pattern_recognition/pr_kmeans.cpp", "max_stars_repo_name": "roopchansinghv/gadgetron", "max_stars_repo_head_hexsha": "fb6c56b643911152c27834a754a7b6ee2dd912da", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-02-22T21:06:36.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-22T21:06:36.000Z", "max_issues_repo_path": "toolboxes/pattern_recognition/pr_kmeans.cpp", "max_issues_repo_name": "apd47/gadgetron", "max_issues_repo_head_hexsha": "073e84dabe77d2dae3b3dd9aa4bf9edbf1f890f2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "toolboxes/pattern_recognition/pr_kmeans.cpp", "max_forks_repo_name": "apd47/gadgetron", "max_forks_repo_head_hexsha": "073e84dabe77d2dae3b3dd9aa4bf9edbf1f890f2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.0441932169, "max_line_length": 156, "alphanum_fraction": 0.4506925536, "num_tokens": 6475, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5774953651858118, "lm_q2_score": 0.5389832206876841, "lm_q1q2_score": 0.31126031186005915}}
{"text": "//\n//  Copyright (c) 2012, Institue of Cancer Research.\n//  All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are\n// met:\n//\n//     * Redistributions of source code must retain the above copyright\n//       notice, this list of conditions and the following disclaimer.\n//     * 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 Institue of Cancer Research.\n//       nor the names of its contributors may be used to endorse or promote\n//       products 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 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// For more information on the Plane of Best Fit please see\n// http://pubs.acs.org/doi/abs/10.1021/ci300293f\n//\n//  If this code has been useful to you, please include the reference\n//  in any work which has made use of it:\n\n//  Plane of Best Fit: A Novel Method to Characterize the Three-Dimensionality\n//  of Molecules, Nicholas C. Firth, Nathan Brown, and Julian Blagg, Journal of\n//  Chemical Information and Modeling 2012 52 (10), 2516-2525\n\n//\n//\n// Created by Nicholas Firth, November 2011\n// Modified by Greg Landrum for inclusion in the RDKit distribution November\n// 2012\n// Further modified by Greg Landrum for inclusion in the RDKit core September\n// 2016\n//\n\n#include <GraphMol/RDKitBase.h>\n#include <GraphMol/MolTransforms/MolTransforms.h>\n\n#include \"PBF.h\"\n#include <Numerics/Matrix.h>\n#include <Numerics/SquareMatrix.h>\n#include <Numerics/SymmMatrix.h>\n#include <boost/foreach.hpp>\n\n#include <Eigen/Dense>\n\nnamespace RDKit {\nnamespace Descriptors {\nnamespace {\n\ndouble distanceFromAPlane(const RDGeom::Point3D &pt,\n                          const std::vector<double> &plane, double denom) {\n  double numer = 0.0;\n  numer =\n      std::abs(pt.x * plane[0] + pt.y * plane[1] + pt.z * plane[2] + plane[3]);\n\n  return numer / denom;\n}\n\nbool getBestFitPlane(const Conformer &conf,\n                     const std::vector<RDGeom::Point3D> &points,\n                     std::vector<double> &plane,\n                     const std::vector<double> *weights) {\n  PRECONDITION((!weights || weights->size() >= points.size()),\n               \"bad weights vector\");\n  PRECONDITION(plane.size() >= 4, \"bad plane\");\n  RDGeom::Point3D origin(0, 0, 0);\n  double wSum = 0.0;\n\n  for (unsigned int i = 0; i < points.size(); ++i) {\n    if (weights) {\n      double w = (*weights)[i];\n      wSum += w;\n      origin += points[i] * w;\n    } else {\n      wSum += 1;\n      origin += points[i];\n    }\n  }\n  origin /= wSum;\n\n  Eigen::Matrix3d evects;\n  Eigen::Vector3d evals;\n  MolTransforms::computePrincipalAxesAndMomentsFromGyrationMatrix(\n      conf, evects, evals, false, weights);\n  RDGeom::Point3D normal;\n  normal.x = evects(0, 0);\n  normal.y = evects(1, 0);\n  normal.z = evects(2, 0);\n\n  plane[0] = normal.x;\n  plane[1] = normal.y;\n  plane[2] = normal.z;\n  plane[3] = -1 * normal.dotProduct(origin);\n  return true;\n}\n\n}  // end of anonymous namespace\n\ndouble PBF(const ROMol &mol, int confId) {\n  PRECONDITION(mol.getNumConformers() >= 1, \"molecule has no conformers\")\n  unsigned int numAtoms = mol.getNumAtoms();\n  if (numAtoms < 4) return 0;\n\n  const Conformer &conf = mol.getConformer(confId);\n  if (!conf.is3D()) return 0;\n\n  std::vector<RDGeom::Point3D> points;\n  points.reserve(numAtoms);\n  for (unsigned int i = 0; i < numAtoms; ++i) {\n    points.push_back(conf.getAtomPos(i));\n  }\n\n  std::vector<double> plane(4);\n  if (!getBestFitPlane(conf, points, plane, NULL)) {\n    // the eigenvalue calculation failed, return 0\n    // FIX: throw an exception here?\n    return 0.0;\n  }\n\n  double denom = 0.0;\n  for (unsigned int i = 0; i < 3; ++i) {\n    denom += plane[i] * plane[i];\n  }\n  denom = sqrt(denom);\n\n  double res = 0.0;\n  for (unsigned int i = 0; i < numAtoms; ++i) {\n    res += distanceFromAPlane(points[i], plane, denom);\n  }\n  res /= numAtoms;\n\n  return res;\n}\n\n}  // end of Descriptors namespace\n}  // end of RDKit namespace\n", "meta": {"hexsha": "4f9fc7f1d661583ee15526a2e38d69b5f70a53a1", "size": 4977, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Code/GraphMol/Descriptors/PBF.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/Descriptors/PBF.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/Descriptors/PBF.cpp", "max_forks_repo_name": "docking-org/rdk", "max_forks_repo_head_hexsha": "6eb710254f027b348a8e3089e6a92c3d40de0949", "max_forks_repo_licenses": ["PostgreSQL"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-03-30T03:22:10.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-30T03:22:10.000Z", "avg_line_length": 32.5294117647, "max_line_length": 79, "alphanum_fraction": 0.6767128792, "num_tokens": 1326, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6477982179521103, "lm_q2_score": 0.48047867804790706, "lm_q1q2_score": 0.3112532314034199}}
{"text": "#include \"hoCuNDArray_utils.h\"\n#include \"radial_utilities.h\"\n#include \"cuNDArray_fileio.h\"\n#include \"cuNDArray.h\"\n#include \"imageOperator.h\"\n#include \"identityOperator.h\"\n#include \"hoPartialDerivativeOperator.h\"\n#include \"hoCuConebeamProjectionOperator.h\"\n#include \"cuConvolutionOperator.h\"\n#include \"hoCuNDArray_blas.h\"\n#include \"hoCuNDArray_elemwise.h\"\n#include \"hoCuNDArray_blas.h\"\n#include \"cgSolver.h\"\n#include \"CBCT_acquisition.h\"\n#include \"complext.h\"\n#include \"encodingOperatorContainer.h\"\n#include \"vector_td_io.h\"\n#include \"hoPartialDerivativeOperator.h\"\n#include \"hoCuGPBBSolver.h\"\n#include \"hoCuTvOperator.h\"\n#include \"hoCuTvPicsOperator.h\"\n#include \"hoCuNCGSolver.h\"\n#include \"hoCuCgDescentSolver.h\"\n#include \"hoNDArray_utils.h\"\n#include \"hoCuPartialDerivativeOperator.h\"\n#include \"cuTvOperator.h\"\n#include \"cuTv1dOperator.h\"\n#include \"cuTvPicsOperator.h\"\n#include \"CBSubsetOperator.h\"\n#include \"osSPSSolver.h\"\n#include \"osMOMSolver.h\"\n#include <iostream>\n#include <algorithm>\n#include <sstream>\n#include <math_constants.h>\n#include <boost/program_options.hpp>\n#include <boost/make_shared.hpp>\n#include \"cuSolverUtils.h\"\nusing namespace std;\nusing namespace Gadgetron;\n\nnamespace po = boost::program_options;\n\n\nboost::shared_ptr<hoCuNDArray<float> > calculate_prior(boost::shared_ptr<CBCT_binning>  binning,boost::shared_ptr<CBCT_acquisition> ps, hoCuNDArray<float>& projections, std::vector<size_t> is_dims, floatd3 imageDimensions){\n  std::cout << \"Calculating FDK prior\" << std::endl;\n\tboost::shared_ptr<CBCT_binning> binning_pics= binning->get_3d_binning();\n\t    std::vector<size_t> is_dims3d = is_dims;\n\t    is_dims3d.pop_back();\n\t    boost::shared_ptr< hoCuConebeamProjectionOperator >\n\t      Ep( new hoCuConebeamProjectionOperator() );\n\t    Ep->setup(ps,binning_pics,imageDimensions);\n\t    Ep->set_codomain_dimensions(ps->get_projections()->get_dimensions().get());\n\t    Ep->set_domain_dimensions(&is_dims3d);\n\t      Ep->set_use_filtered_backprojection(true);\n\t    boost::shared_ptr<hoCuNDArray<float> > prior3d(new hoCuNDArray<float>(&is_dims3d));\n\t    Ep->mult_MH(&projections,prior3d.get());\n\n\t    hoCuNDArray<float> tmp_proj(*ps->get_projections());\n\t    Ep->mult_M(prior3d.get(),&tmp_proj);\n\t    float s = dot(ps->get_projections().get(),&tmp_proj)/dot(&tmp_proj,&tmp_proj);\n\t    *prior3d *= s;\n\t    boost::shared_ptr<hoCuNDArray<float> > prior(new hoCuNDArray<float>(*expand( prior3d.get(), is_dims.back() )));\n\t    std::cout << \"Prior complete\" << std::endl;\n\t    return prior;\n}\n\nint main(int argc, char** argv)\n{\n  string acquisition_filename;\n  string outputFile;\n  uintd3 imageSize;\n  floatd3 voxelSize;\n  int device;\n  unsigned int downsamples;\n  unsigned int iterations;\n  unsigned int subsets;\n  float rho;\n  float tv_weight,pics_weight;\n\n  po::options_description desc(\"Allowed options\");\n\n  desc.add_options()\n    (\"help\", \"produce help message\")\n    (\"acquisition,a\", po::value<string>(&acquisition_filename)->default_value(\"acquisition.hdf5\"), \"Acquisition data\")\n    (\"samples,n\",po::value<unsigned int>(),\"Number of samples per ray\")\n    (\"output,f\", po::value<string>(&outputFile)->default_value(\"reconstruction.real\"), \"Output filename\")\n    (\"size,s\",po::value<uintd3>(&imageSize)->default_value(uintd3(512,512,1)),\"Image size in pixels\")\n    (\"binning,b\",po::value<string>(),\"Binning file for 4d reconstruction\")\n    (\"SAG\",\"Use exact SAG correction if present\")\n    (\"voxelSize,v\",po::value<floatd3>(&voxelSize)->default_value(floatd3(0.488f,0.488f,1.0f)),\"Voxel size in mm\")\n    (\"dimensions,d\",po::value<floatd3>(),\"Image dimensions in mm. Overwrites voxelSize.\")\n    (\"iterations,i\",po::value<unsigned int>(&iterations)->default_value(10),\"Number of iterations\")\n    (\"device\",po::value<int>(&device)->default_value(0),\"Number of the device to use (0 indexed)\")\n    (\"downsample,D\",po::value<unsigned int>(&downsamples)->default_value(0),\"Downsample projections this factor\")\n    (\"subsets,u\",po::value<unsigned int>(&subsets)->default_value(10),\"Number of subsets to use\")\n    (\"TV\",po::value<float>(&tv_weight)->default_value(0),\"Total variation weight\")\n    (\"PICS\",po::value<float>(&pics_weight)->default_value(0),\"PICS weight\")\n    (\"use_prior\",\"Use an FDK prior\")\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    cout << desc << \"\\n\";\n    return 1;\n  }\n\n  std::cout << \"Command line options:\" << std::endl;\n  for (po::variables_map::iterator it = vm.begin(); it != vm.end(); ++it){\n    boost::any a = it->second.value();\n    std::cout << it->first << \": \";\n    if (a.type() == typeid(std::string)) std::cout << it->second.as<std::string>();\n    else if (a.type() == typeid(int)) std::cout << it->second.as<int>();\n    else if (a.type() == typeid(unsigned int)) std::cout << it->second.as<unsigned int>();\n    else if (a.type() == typeid(float)) std::cout << it->second.as<float>();\n    else if (a.type() == typeid(vector_td<float,3>)) std::cout << it->second.as<vector_td<float,3> >();\n    else if (a.type() == typeid(vector_td<int,3>)) std::cout << it->second.as<vector_td<int,3> >();\n    else if (a.type() == typeid(vector_td<unsigned int,3>)) std::cout << it->second.as<vector_td<unsigned int,3> >();\n    else std::cout << \"Unknown type\" << std::endl;\n    std::cout << std::endl;\n  }\n\n  cudaSetDevice(device);\n  cudaDeviceReset();\n\n  //Really weird stuff. Needed to initialize the device?? Should find real bug.\n  cudaDeviceManager::Instance()->lockHandle();\n  cudaDeviceManager::Instance()->unlockHandle();\n\n  boost::shared_ptr<CBCT_acquisition> ps(new CBCT_acquisition());\n  ps->load(acquisition_filename);\n  ps->get_geometry()->print(std::cout);\n\tps->downsample(downsamples);\n\n  float SDD = ps->get_geometry()->get_SDD();\n  float SAD = ps->get_geometry()->get_SAD();\n\n  boost::shared_ptr<CBCT_binning> binning(new CBCT_binning());\n  if (vm.count(\"binning\")){\n    std::cout << \"Loading binning data\" << std::endl;\n    binning->load(vm[\"binning\"].as<string>());\n  } else binning->set_as_default_3d_bin(ps->get_projections()->get_size(2));\n  binning->print(std::cout);\n\n  floatd3 imageDimensions;\n  if (vm.count(\"dimensions\")){\n    imageDimensions = vm[\"dimensions\"].as<floatd3>();\n    voxelSize = imageDimensions/imageSize;\n  }\n  else imageDimensions = voxelSize*imageSize;\n\n  float lengthOfRay_in_mm = norm(imageDimensions);\n  unsigned int numSamplesPerPixel = 3;\n  float minSpacing = min(voxelSize)/numSamplesPerPixel;\n\n  unsigned int numSamplesPerRay;\n  if (vm.count(\"samples\")) numSamplesPerRay = vm[\"samples\"].as<unsigned int>();\n  else numSamplesPerRay = ceil( lengthOfRay_in_mm / minSpacing );\n\n  float step_size_in_mm = lengthOfRay_in_mm / numSamplesPerRay;\n  size_t numProjs = ps->get_projections()->get_size(2);\n  size_t needed_bytes = 2 * prod(imageSize) * sizeof(float);\n  std::vector<size_t> is_dims = to_std_vector((uint64d3)imageSize);\n\n  std::cout << \"IS dimensions \" << is_dims[0] << \" \" << is_dims[1] << \" \" << is_dims[2] << std::endl;\n  std::cout << \"Image size \" << imageDimensions << std::endl;\n\n  is_dims.push_back(binning->get_number_of_bins());\n  osMOMSolver<cuNDArray<float>> solver;\n\n  if (pics_weight > 0){\n  \tstd::cout << \"Calculating PICS prior\" << std::endl;\n  \thoCuConebeamProjectionOperator op;\n  \tauto bin3D = binning->get_3d_binning();\n  \top.setup(ps,bin3D,imageDimensions);\n  \thoCuNDArray<float> proj(*ps->get_projections());\n  \top.offset_correct(&proj);\n  \top.set_use_filtered_backprojection(true);\n\n  \tstd::vector<size_t> is_dims3D = to_std_vector((uint64d3)imageSize);\n\n  \thoCuNDArray<float> image(is_dims3D);\n\n  \top.mult_MH(&proj,&image,false);\n  \tauto prior = boost::make_shared<cuNDArray<float>>(image);\n  \tauto PICS = boost::make_shared<cuTvPicsOperator<float,3>>();\n  \tPICS->set_prior(prior);\n  \tPICS->set_weight(pics_weight);\n  \tsolver.add_nonlinear_operator(PICS);\n\n  \t//write_nd_array(prior.get(),\"fdk_prior.real\");\n  }\n\n  // Define encoding matrix\n  auto E = boost::make_shared<CBSubsetOperator<cuNDArray> >(subsets);\n\n\n  //E->setup(ps,binning,imageDimensions);\n  E->setup(ps,binning,imageDimensions);\n  E->set_domain_dimensions(&is_dims);\n  E->set_codomain_dimensions(ps->get_projections()->get_dimensions().get());\n\n  /*auto weight_array = boost::make_shared<cuNDArray<float>>(is_dims);\n  {\n  \tboost::shared_ptr<linearOperator<cuNDArray<float>>> E2(E);\n  \tcuNDArray<float> tmp_proj(*ps->get_projections()->get_dimensions());\n  \tfill(&tmp_proj,1.0f);\n  \tE2->mult_MH(&tmp_proj,weight_array.get(),false);\n  \tclamp_min(weight_array.get(),1.0f);\n  \treciprocal_inplace(weight_array.get());\n  \t//*weight_array *= *weight_array;\n  }\n  write_nd_array(weight_array.get(),\"weights.real\");\n*/\n  //hoCuCgDescentSolver<float> solver;\n\n  //osSPSSolver<hoNDArray<float>> solver;\n  //hoCuNCGSolver<float> solver;\n  solver.set_encoding_operator(E);\n  //solver.set_domain_dimensions(&is_dims);\n  solver.set_max_iterations(iterations);\n  solver.set_output_mode(osSPSSolver<cuNDArray<float>>::OUTPUT_VERBOSE);\n  //solver.set_non_negativity_constraint(true);\n  //solver.set_rho(rho);\n\n  if (tv_weight > 0){\n\n\n\n\n  \tauto total_variation = boost::make_shared<cuTvOperator<float,4>>();\n  \ttotal_variation->set_weight(tv_weight);\n  \t//total_variation->set_weight_array(weight_array);\n  \tsolver.add_nonlinear_operator(total_variation);\n  \tsolver.set_kappa(tv_weight);\n  \t/*\n  \tauto total_variation_t = boost::make_shared<cuTv1DOperator<float,4>>();\n  \ttotal_variation_t->set_weight(tv_weight);\n  \tsolver.add_nonlinear_operator(total_variation_t);\n  \t*/\n/*\n  \tauto total_variation2 = boost::make_shared<cuWTvOperator<float,4>>();\n  \ttotal_variation2->set_step(2);\n  \ttotal_variation2->set_weight(tv_weight);\n  \ttotal_variation2->set_weight_array(weight_array);\n  \tsolver.add_nonlinear_operator(total_variation2);\n  \tauto total_variation3 = boost::make_shared<cuWTvOperator<float,4>>();\n  \ttotal_variation3->set_step(3);\n  \ttotal_variation3->set_weight(tv_weight);\n  \ttotal_variation3->set_weight_array(weight_array);\n  \tsolver.add_nonlinear_operator(total_variation3);\n*/\n  }\n\n\n\n  cuNDArray<float> projections(*ps->get_projections());\n  std::cout << \"Projection norm:\" << nrm2(&projections) << std::endl;\n  //E->set_use_offset_correction(false);\n  E->offset_correct(&projections);\n  std::cout << \"Projection norm:\" << nrm2(&projections) << std::endl;\n\n  {\n  \tE->set_use_offset_correction(false);\n  \tlinearOperator<cuNDArray<float>>* E_all = E.get();\n  \tauto precon_image = boost::make_shared<cuNDArray<float>>(is_dims);\n  \tfill(precon_image.get(),1.0f);\n  \tcuNDArray<float> tmp_proj(projections.get_dimensions());\n\n  \tE_all->mult_M(precon_image.get(),&tmp_proj);\n  \tE_all->mult_MH(&tmp_proj,precon_image.get());\n\n   \tclamp_min(precon_image.get(),1e-6f);\n  \treciprocal_inplace(precon_image.get());\n  \tsolver.set_preconditioning_image(precon_image);\n\n  \tstd::cout << \"Precon mean: \" << mean(precon_image.get()) << std::endl;\n  \tE->set_use_offset_correction(true);\n\n  }\n\n\n/*\n    boost::shared_ptr<hoCuNDArray<float> > prior;\n\n  if (vm.count(\"use_prior\")) {\n  \tprior = calculate_prior(binning,ps,projections,is_dims,imageDimensions);\n  \tsolver.set_x0(prior);\n  }\n*/\n\n  auto result = solver.solve(&projections);\n\n  write_nd_array<float>( result.get(), outputFile.c_str());\n}\n", "meta": {"hexsha": "4f423ded093a1f2f2fe2cba77db7a209af4054ea", "size": 11238, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "xray/cuCBOSMOM.cpp", "max_stars_repo_name": "ahsanjav/gt-tomography", "max_stars_repo_head_hexsha": "1f53d72672ccda417bc8966d8497af6d786e8935", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2017-06-26T13:41:55.000Z", "max_stars_repo_stars_event_max_datetime": "2019-06-10T11:06:27.000Z", "max_issues_repo_path": "xray/cuCBOSMOM.cpp", "max_issues_repo_name": "ahsanjav/gt-tomography", "max_issues_repo_head_hexsha": "1f53d72672ccda417bc8966d8497af6d786e8935", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "xray/cuCBOSMOM.cpp", "max_forks_repo_name": "ahsanjav/gt-tomography", "max_forks_repo_head_hexsha": "1f53d72672ccda417bc8966d8497af6d786e8935", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-09-27T14:37:29.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-27T14:37:29.000Z", "avg_line_length": 37.5852842809, "max_line_length": 223, "alphanum_fraction": 0.7116034882, "num_tokens": 3073, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.743168019989179, "lm_q2_score": 0.41869690935568665, "lm_q1q2_score": 0.3111621531014544}}
{"text": "// Copyright (C) 2016 The Regents of the University of California (Regents).\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are\n// met:\n//\n//     * Redistributions of source code must retain the above copyright\n//       notice, this list of conditions and the following disclaimer.\n//\n//     * Redistributions in binary form must reproduce the above\n//       copyright notice, this list of conditions and the following\n//       disclaimer in the documentation and/or other materials provided\n//       with the distribution.\n//\n//     * Neither the name of The Regents or University of California nor the\n//       names of its contributors may be used to endorse or promote products\n//       derived from this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE\n// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n// POSSIBILITY OF SUCH DAMAGE.\n//\n// Please contact the author of this library if you have any questions.\n// Author: Chris Sweeney (cmsweeney@cs.ucsb.edu)\n\n#include \"theia/sfm/undistort_image.h\"\n\n#include <Eigen/Core>\n#include <algorithm>\n#include <limits>\n\n#include \"theia/image/image.h\"\n#include \"theia/sfm/camera/camera.h\"\n#include \"theia/sfm/camera/camera_intrinsics_model.h\"\n#include \"theia/sfm/camera/fisheye_camera_model.h\"\n#include \"theia/sfm/camera/pinhole_camera_model.h\"\n#include \"theia/sfm/camera/pinhole_radial_tangential_camera_model.h\"\n#include \"theia/sfm/reconstruction.h\"\n#include \"theia/sfm/track.h\"\n#include \"theia/sfm/types.h\"\n#include \"theia/sfm/view.h\"\n\nnamespace theia {\nnamespace {\n\n// Set all radial distortion parameters to zero. This requires adjusting\n// different parameters for each camera intrinsics model type.\nvoid SetLensDistortionToZero(Camera* camera) {\n  double* intrinsics = camera->mutable_intrinsics();\n  switch (camera->GetCameraIntrinsicsModelType()) {\n    case CameraIntrinsicsModelType::PINHOLE:\n      intrinsics[PinholeCameraModel::RADIAL_DISTORTION_1] = 0.0;\n      intrinsics[PinholeCameraModel::RADIAL_DISTORTION_2] = 0.0;\n      break;\n    case CameraIntrinsicsModelType::PINHOLE_RADIAL_TANGENTIAL:\n      intrinsics[PinholeRadialTangentialCameraModel::RADIAL_DISTORTION_1] = 0.0;\n      intrinsics[PinholeRadialTangentialCameraModel::RADIAL_DISTORTION_2] = 0.0;\n      intrinsics[PinholeRadialTangentialCameraModel::RADIAL_DISTORTION_3] = 0.0;\n      intrinsics[PinholeRadialTangentialCameraModel::TANGENTIAL_DISTORTION_1] =\n          0.0;\n      intrinsics[PinholeRadialTangentialCameraModel::TANGENTIAL_DISTORTION_2] =\n          0.0;\n      break;\n    case CameraIntrinsicsModelType::FISHEYE:\n      intrinsics[FisheyeCameraModel::RADIAL_DISTORTION_1] = 0.0;\n      intrinsics[FisheyeCameraModel::RADIAL_DISTORTION_2] = 0.0;\n      intrinsics[FisheyeCameraModel::RADIAL_DISTORTION_3] = 0.0;\n      intrinsics[FisheyeCameraModel::RADIAL_DISTORTION_4] = 0.0;\n      break;\n    case CameraIntrinsicsModelType::FOV:\n      intrinsics[FisheyeCameraModel::RADIAL_DISTORTION_1] = 0.0;\n      break;\n    default:\n      LOG(FATAL) << \"Invalid camera intrinsics type.\";\n      break;\n  }\n}\n\n// We seek a mapping from undistorted pixels to distorted pixels such that a\n// valid mapping exists for all undistorted pixels. This is effectively\n// undistorting the image then cropping it so that no unmapped (black) pixels\n// are in the undistorted image. To do this, we need to find the min and max x/y\n// values of unmapped pixels so that we can determine the size and location of\n// the crop.\nvoid FindUndistortedImageBoundary(const Camera& distorted_camera,\n                                  const Camera& undistorted_camera,\n                                  Eigen::Vector4d* bounds) {\n  const CameraIntrinsicsModel& distorted_intrinsics =\n      *distorted_camera.CameraIntrinsics();\n  const CameraIntrinsicsModel& undistorted_intrinsics =\n      *undistorted_camera.CameraIntrinsics();\n\n  // Find the max and min locations of the undistorted pixels.\n  double left_max_x = std::numeric_limits<double>::lowest();\n  double right_min_x = std::numeric_limits<double>::max();\n  for (size_t y = 0; y < distorted_camera.ImageHeight(); ++y) {\n    // Left border.\n    const Eigen::Vector3d distorted_point1 =\n        distorted_intrinsics.ImageToCameraCoordinates(\n            Eigen::Vector2d(0.5, y + 0.0));\n    const Eigen::Vector2d undistorted_point1 =\n        undistorted_intrinsics.CameraToImageCoordinates(distorted_point1);\n    left_max_x = std::max(left_max_x, undistorted_point1(0));\n\n    // Right border.\n    const Eigen::Vector3d distorted_point2 =\n        distorted_intrinsics.ImageToCameraCoordinates(\n            Eigen::Vector2d(distorted_camera.ImageWidth() - 0.5, y + 0.5));\n    const Eigen::Vector2d undistorted_point2 =\n        undistorted_intrinsics.CameraToImageCoordinates(distorted_point2);\n    right_min_x = std::min(right_min_x, undistorted_point2(0));\n  }\n\n  // Determine min, max coordinates along left / right image border.\n  double top_max_y = std::numeric_limits<double>::lowest();\n  double bottom_min_y = std::numeric_limits<double>::max();\n  for (size_t x = 0; x < distorted_camera.ImageWidth(); ++x) {\n    // Top border.\n    const Eigen::Vector3d distorted_point1 =\n        distorted_intrinsics.ImageToCameraCoordinates(\n            Eigen::Vector2d(x + 0.5, 0.5));\n    const Eigen::Vector2d undistorted_point1 =\n        undistorted_intrinsics.CameraToImageCoordinates(distorted_point1);\n    top_max_y = std::max(top_max_y, undistorted_point1(1));\n\n    // Bottom border.\n    const Eigen::Vector3d distorted_point2 =\n        distorted_intrinsics.ImageToCameraCoordinates(\n            Eigen::Vector2d(x + 0.5, distorted_camera.ImageHeight() - 0.5));\n    const Eigen::Vector2d undistorted_point2 =\n        undistorted_intrinsics.CameraToImageCoordinates(distorted_point2);\n    bottom_min_y = std::min(bottom_min_y, undistorted_point2(1));\n  }\n\n  *bounds = Eigen::Vector4d(left_max_x, right_min_x, top_max_y, bottom_min_y);\n}\n\n// Create an undistorted image from the distorted image given the distorted and\n// undistorted camera parameters. This function only maps the pixels to create\n// the undistorted image and assumes the camera parameters and image sizes have\n// already been solved for.\nvoid RemoveImageLensDistortion(const Camera& distorted_camera,\n                               const FloatImage& distorted_image,\n                               const Camera& undistorted_camera,\n                               FloatImage* undistorted_image) {\n  const CameraIntrinsicsModel& distorted_intrinsics =\n      *distorted_camera.CameraIntrinsics();\n  const CameraIntrinsicsModel& undistorted_intrinsics =\n      *undistorted_camera.CameraIntrinsics();\n\n  // For each pixel in the undistorted image, find the coordinate in the\n  // distorted image and set the pixel color accordingly.\n  const int num_channels = distorted_image.Channels();\n  OpenImageIO::ImageBuf& undistorted_img =\n      undistorted_image->GetOpenImageIOImageBuf();\n  OpenImageIO::ImageBuf::Iterator<float> undistorted_it(undistorted_img);\n  for (; !undistorted_it.done(); ++undistorted_it) {\n    Eigen::Vector2d image_point(undistorted_it.x() + 0.5,\n                                undistorted_it.y() + 0.5);\n\n    // Camera models assume that the upper left pixel center is (0.5, 0.5).\n    const Eigen::Vector3d distorted_point =\n        undistorted_intrinsics.ImageToCameraCoordinates(image_point);\n    const Eigen::Vector2d distorted_pixel =\n        distorted_intrinsics.CameraToImageCoordinates(distorted_point);\n    const Eigen::Vector2d pixel(std::round<int>(distorted_pixel.x() - 0.5),\n                                std::round<int>(distorted_pixel.y() - 0.5));\n    // Set all color channels appropriately. Note that we do not need to check\n    // if the distorted pixel is within the image bounds since the\n    // FindUndistortedImageBoundary function has guaranteed that all pixels will\n    // be within the image borders.\n    for (int c = 0; c < num_channels; c++) {\n      undistorted_it[c] = distorted_image.BilinearInterpolate(\n          distorted_pixel.x(), distorted_pixel.y(), c);\n    }\n  }\n}\n\n}  // namespace\n\nbool UndistortImage(const Camera& distorted_camera,\n                    const FloatImage& distorted_image,\n                    const Camera& undistorted_camera,\n                    FloatImage* undistorted_image) {\n  // Undistort the image.\n  if (distorted_image.Channels() == 1) {\n    undistorted_image->ConvertToGrayscaleImage();\n  } else {\n    undistorted_image->ConvertToRGBImage();\n  }\n  undistorted_image->Resize(undistorted_camera.ImageWidth(),\n                            undistorted_camera.ImageHeight());\n\n  // Remap the distorted pixels into the undistorted image.\n  RemoveImageLensDistortion(distorted_camera,\n                            distorted_image,\n                            undistorted_camera,\n                            undistorted_image);\n\n  return true;\n}\n\n// Create the undistorted camera by removing radial distortion parameters.\nbool UndistortCamera(const Camera& distorted_camera,\n                     Camera* undistorted_camera) {\n  *undistorted_camera = distorted_camera;\n  SetLensDistortionToZero(undistorted_camera);\n\n  Eigen::Vector4d undistorted_image_boundaries;\n  FindUndistortedImageBoundary(distorted_camera,\n                               *undistorted_camera,\n                               &undistorted_image_boundaries);\n\n  // Given the locations of the min/max undistorted pixels, compute the scale\n  // factor to resize the undistorted image.\n  const double cx = undistorted_camera->PrincipalPointX();\n  const double cy = undistorted_camera->PrincipalPointY();\n  const double left_max_x = undistorted_image_boundaries(0);\n  const double right_min_x = undistorted_image_boundaries(1);\n  const double top_max_y = undistorted_image_boundaries(2);\n  const double bottom_min_y = undistorted_image_boundaries(3);\n\n  // Scale undistorted camera dimensions.\n  const double scale_x =\n      1.0 /\n      std::max(cx / (cx - left_max_x),\n               (distorted_camera.ImageWidth() - 0.5 - cx) / (right_min_x - cx));\n  const double scale_y =\n      1.0 / std::max(cy / (cy - top_max_y),\n                     (distorted_camera.ImageHeight() - 0.5 - cy) /\n                         (bottom_min_y - cy));\n\n  undistorted_camera->SetImageSize(\n      static_cast<int>(\n          std::max(1.0, scale_x * undistorted_camera->ImageWidth())),\n      static_cast<int>(\n          std::max(1.0, scale_y * undistorted_camera->ImageHeight())));\n\n  // Scale the principal point according to the new dimensions of the image.\n  undistorted_camera->SetPrincipalPoint(\n      undistorted_camera->PrincipalPointX() *\n          static_cast<double>(undistorted_camera->ImageWidth()) /\n          distorted_camera.ImageWidth(),\n      undistorted_camera->PrincipalPointY() *\n          static_cast<double>(undistorted_camera->ImageHeight()) /\n          distorted_camera.ImageHeight());\n\n  return true;\n}\n\nbool UndistortReconstruction(Reconstruction* reconstruction) {\n  const auto view_ids = reconstruction->ViewIds();\n  for (const ViewId view_id : view_ids) {\n    View* view = reconstruction->MutableView(view_id);\n    if (view == nullptr || !view->IsEstimated()) {\n      continue;\n    }\n\n    // Undistort the image to obtain the undistorted camera.\n    const Camera distorted_camera = view->Camera();\n    Camera* undistorted_camera = view->MutableCamera();\n    if (!UndistortCamera(distorted_camera, undistorted_camera)) {\n      return false;\n    }\n\n    // The camera intrinsics models describe how to distort and undistort the\n    // pixels.\n    const CameraIntrinsicsModel& distorted_intrinsics =\n        *distorted_camera.CameraIntrinsics();\n    const CameraIntrinsicsModel& undistorted_intrinsics =\n        *undistorted_camera->CameraIntrinsics();\n\n    // Undisort all features seen by the view.\n    const auto track_ids = view->TrackIds();\n    for (const TrackId track_id : track_ids) {\n      Track* track = reconstruction->MutableTrack(track_id);\n      if (track == nullptr || !track->IsEstimated()) {\n        continue;\n      }\n\n      // Get the undistorted feature.\n      const Feature* distorted_feature = view->GetFeature(track_id);\n      const Eigen::Vector3d distorted_point =\n          distorted_intrinsics.ImageToCameraCoordinates(*distorted_feature);\n      const Eigen::Vector2d undistorted_feature =\n          undistorted_intrinsics.CameraToImageCoordinates(distorted_point);\n\n      // Add the new undistorted feature to the undistorted view. First, remove\n      // the feature since it is not mutable.\n      CHECK(view->RemoveFeature(track_id));\n\n      // Only add the feature back if it is within the new image\n      // boundaries. Otherwise, remove the feature from the view and the track.\n      if (undistorted_feature.x() < 0 ||\n          undistorted_feature.x() > undistorted_camera->ImageWidth() - 1 ||\n          undistorted_feature.y() < 0 ||\n          undistorted_feature.y() > undistorted_camera->ImageHeight() - 1) {\n        track->RemoveView(view_id);\n        // Remove the track if there are no more observations.\n        if (track->NumViews() == 0) {\n          reconstruction->RemoveTrack(track_id);\n        }\n      } else {\n        view->AddFeature(track_id, undistorted_feature);\n      }\n    }\n  }\n\n  return true;\n}\n\n}  // namespace theia\n", "meta": {"hexsha": "cda0a9f98f7a14a6559bbcdff093b1ff07bb32f5", "size": 14053, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/theia/sfm/undistort_image.cc", "max_stars_repo_name": "CGAnderson/TheiaSfM", "max_stars_repo_head_hexsha": "8a11923eb55be75b8b51f4afcaaaf0683905f539", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-03-05T20:10:09.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-05T20:10:09.000Z", "max_issues_repo_path": "src/theia/sfm/undistort_image.cc", "max_issues_repo_name": "CGAnderson/TheiaSfM", "max_issues_repo_head_hexsha": "8a11923eb55be75b8b51f4afcaaaf0683905f539", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/theia/sfm/undistort_image.cc", "max_forks_repo_name": "CGAnderson/TheiaSfM", "max_forks_repo_head_hexsha": "8a11923eb55be75b8b51f4afcaaaf0683905f539", "max_forks_repo_licenses": ["BSD-3-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.6428571429, "max_line_length": 80, "alphanum_fraction": 0.7058990963, "num_tokens": 3368, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5350984434543458, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.3110543789789725}}
{"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 <algorithm>\n#include <functional>\n#include <memory>\n\n#include <boost/make_shared.hpp>\n#include <boost/bind.hpp>\n#include \"Tudat/Astrodynamics/Aerodynamics/flightConditions.h\"\n#include \"Tudat/Astrodynamics/Ephemerides/frameManager.h\"\n#include \"Tudat/Astrodynamics/Gravitation/sphericalHarmonicsGravityField.h\"\n#include \"Tudat/Astrodynamics/Propulsion/thrustMagnitudeWrapper.h\"\n#include \"Tudat/Astrodynamics/ReferenceFrames/aerodynamicAngleCalculator.h\"\n#include \"Tudat/Astrodynamics/ReferenceFrames/referenceFrameTransformations.h\"\n#include \"Tudat/Astrodynamics/Relativity/relativisticAccelerationCorrection.h\"\n#include \"Tudat/Astrodynamics/Relativity/metric.h\"\n#include \"Tudat/Basics/utilities.h\"\n#include \"Tudat/SimulationSetup/PropagationSetup/accelerationSettings.h\"\n#include \"Tudat/SimulationSetup/PropagationSetup/createAccelerationModels.h\"\n#include \"Tudat/SimulationSetup/EnvironmentSetup/createFlightConditions.h\"\n\nnamespace tudat\n{\n\nnamespace simulation_setup\n{\n\nusing namespace aerodynamics;\nusing namespace gravitation;\nusing namespace basic_astrodynamics;\nusing namespace electro_magnetism;\nusing namespace ephemerides;\n\n\n//! Function to create a direct (i.e. not third-body) gravitational acceleration (of any type)\nstd::shared_ptr< basic_astrodynamics::AccelerationModel< Eigen::Vector3d > > createDirectGravitationalAcceleration(\n        const std::shared_ptr< Body > bodyUndergoingAcceleration,\n        const std::shared_ptr< Body > bodyExertingAcceleration,\n        const std::string& nameOfBodyUndergoingAcceleration,\n        const std::string& nameOfBodyExertingAcceleration,\n        const std::shared_ptr< AccelerationSettings > accelerationSettings,\n        const std::string& nameOfCentralBody,\n        const bool isCentralBody )\n{\n    // Check if sum of gravitational parameters (i.e. inertial force w.r.t. central body) should be used.\n    bool sumGravitationalParameters = 0;\n    if( ( nameOfCentralBody == nameOfBodyExertingAcceleration ) && bodyUndergoingAcceleration != nullptr )\n    {\n        sumGravitationalParameters = 1;\n    }\n\n\n    // Check type of acceleration model and create.\n    std::shared_ptr< basic_astrodynamics::AccelerationModel< Eigen::Vector3d > > accelerationModel;\n    switch( accelerationSettings->accelerationType_ )\n    {\n    case central_gravity:\n        accelerationModel = createCentralGravityAcceleratioModel(\n                    bodyUndergoingAcceleration,\n                    bodyExertingAcceleration,\n                    nameOfBodyUndergoingAcceleration,\n                    nameOfBodyExertingAcceleration,\n                    sumGravitationalParameters );\n        break;\n    case spherical_harmonic_gravity:\n        accelerationModel = createSphericalHarmonicsGravityAcceleration(\n                    bodyUndergoingAcceleration,\n                    bodyExertingAcceleration,\n                    nameOfBodyUndergoingAcceleration,\n                    nameOfBodyExertingAcceleration,\n                    accelerationSettings,\n                    sumGravitationalParameters );\n        break;\n    case mutual_spherical_harmonic_gravity:\n        accelerationModel = createMutualSphericalHarmonicsGravityAcceleration(\n                    bodyUndergoingAcceleration,\n                    bodyExertingAcceleration,\n                    nameOfBodyUndergoingAcceleration,\n                    nameOfBodyExertingAcceleration,\n                    accelerationSettings,\n                    sumGravitationalParameters,\n                    isCentralBody );\n        break;\n    default:\n\n        std::string errorMessage = \"Error when making gravitional acceleration model, cannot parse type \" +\n                std::to_string( accelerationSettings->accelerationType_ );\n        throw std::runtime_error( errorMessage );\n    }\n    return accelerationModel;\n}\n\n//! Function to create a third-body gravitational acceleration (of any type)\nstd::shared_ptr< basic_astrodynamics::AccelerationModel< Eigen::Vector3d > > createThirdBodyGravitationalAcceleration(\n        const std::shared_ptr< Body > bodyUndergoingAcceleration,\n        const std::shared_ptr< Body > bodyExertingAcceleration,\n        const std::shared_ptr< Body > centralBody,\n        const std::string& nameOfBodyUndergoingAcceleration,\n        const std::string& nameOfBodyExertingAcceleration,\n        const std::string& nameOfCentralBody,\n        const std::shared_ptr< AccelerationSettings > accelerationSettings )\n{\n    // Check type of acceleration model and create.\n    std::shared_ptr< basic_astrodynamics::AccelerationModel< Eigen::Vector3d > > accelerationModel;\n    switch( accelerationSettings->accelerationType_ )\n    {\n    case central_gravity:\n        accelerationModel = std::make_shared< ThirdBodyCentralGravityAcceleration >(\n                    std::dynamic_pointer_cast< CentralGravitationalAccelerationModel3d >(\n                        createDirectGravitationalAcceleration(\n                            bodyUndergoingAcceleration, bodyExertingAcceleration,\n                            nameOfBodyUndergoingAcceleration, nameOfBodyExertingAcceleration,\n                            accelerationSettings, \"\", 0 ) ),\n                    std::dynamic_pointer_cast< CentralGravitationalAccelerationModel3d >(\n                        createDirectGravitationalAcceleration(\n                            centralBody, bodyExertingAcceleration,\n                            nameOfCentralBody, nameOfBodyExertingAcceleration,\n                            accelerationSettings, \"\", 1 ) ), nameOfCentralBody );\n        break;\n    case spherical_harmonic_gravity:\n        accelerationModel = std::make_shared< ThirdBodySphericalHarmonicsGravitationalAccelerationModel >(\n                    std::dynamic_pointer_cast< SphericalHarmonicsGravitationalAccelerationModel >(\n                        createDirectGravitationalAcceleration(\n                            bodyUndergoingAcceleration, bodyExertingAcceleration,\n                            nameOfBodyUndergoingAcceleration, nameOfBodyExertingAcceleration,\n                            accelerationSettings, \"\", 0 ) ),\n                    std::dynamic_pointer_cast< SphericalHarmonicsGravitationalAccelerationModel >(\n                        createDirectGravitationalAcceleration(\n                            centralBody, bodyExertingAcceleration, nameOfCentralBody, nameOfBodyExertingAcceleration,\n                            accelerationSettings, \"\", 1 ) ), nameOfCentralBody );\n        break;\n    case mutual_spherical_harmonic_gravity:\n        accelerationModel = std::make_shared< ThirdBodyMutualSphericalHarmonicsGravitationalAccelerationModel >(\n                    std::dynamic_pointer_cast< MutualSphericalHarmonicsGravitationalAccelerationModel >(\n                        createDirectGravitationalAcceleration(\n                            bodyUndergoingAcceleration, bodyExertingAcceleration,\n                            nameOfBodyUndergoingAcceleration, nameOfBodyExertingAcceleration,\n                            accelerationSettings, \"\", 0 ) ),\n                    std::dynamic_pointer_cast< MutualSphericalHarmonicsGravitationalAccelerationModel >(\n                        createDirectGravitationalAcceleration(\n                            centralBody, bodyExertingAcceleration, nameOfCentralBody, nameOfBodyExertingAcceleration,\n                            accelerationSettings, \"\", 1 ) ), nameOfCentralBody );\n        break;\n    default:\n\n        std::string errorMessage = \"Error when making third-body gravitional acceleration model, cannot parse type \" +\n                std::to_string( accelerationSettings->accelerationType_ );\n        throw std::runtime_error( errorMessage );\n    }\n    return accelerationModel;\n}\n\n//! Function to create gravitational acceleration (of any type)\nstd::shared_ptr< AccelerationModel< Eigen::Vector3d > > createGravitationalAccelerationModel(\n        const std::shared_ptr< Body > bodyUndergoingAcceleration,\n        const std::shared_ptr< Body > bodyExertingAcceleration,\n        const std::shared_ptr< AccelerationSettings > accelerationSettings,\n        const std::string& nameOfBodyUndergoingAcceleration,\n        const std::string& nameOfBodyExertingAcceleration,\n        const std::shared_ptr< Body > centralBody,\n        const std::string& nameOfCentralBody )\n{\n\n    std::shared_ptr< AccelerationModel< Eigen::Vector3d > > accelerationModelPointer;\n    if( accelerationSettings->accelerationType_ != central_gravity &&\n            accelerationSettings->accelerationType_ != spherical_harmonic_gravity &&\n            accelerationSettings->accelerationType_ != mutual_spherical_harmonic_gravity )\n    {\n        throw std::runtime_error( \"Error when making gravitational acceleration, type is inconsistent\" );\n    }\n\n    if( nameOfCentralBody == nameOfBodyExertingAcceleration || ephemerides::isFrameInertial( nameOfCentralBody ) )\n    {\n        accelerationModelPointer = createDirectGravitationalAcceleration( bodyUndergoingAcceleration,\n                                                                          bodyExertingAcceleration,\n                                                                          nameOfBodyUndergoingAcceleration,\n                                                                          nameOfBodyExertingAcceleration,\n                                                                          accelerationSettings,\n                                                                          nameOfCentralBody, false );\n    }\n    else\n    {\n        accelerationModelPointer = createThirdBodyGravitationalAcceleration( bodyUndergoingAcceleration,\n                                                                             bodyExertingAcceleration,\n                                                                             centralBody,\n                                                                             nameOfBodyUndergoingAcceleration,\n                                                                             nameOfBodyExertingAcceleration,\n                                                                             nameOfCentralBody, accelerationSettings );\n    }\n\n    return accelerationModelPointer;\n}\n\n\n//! Function to create central gravity acceleration model.\nstd::shared_ptr< CentralGravitationalAccelerationModel3d > createCentralGravityAcceleratioModel(\n        const std::shared_ptr< Body > bodyUndergoingAcceleration,\n        const std::shared_ptr< Body > bodyExertingAcceleration,\n        const std::string& nameOfBodyUndergoingAcceleration,\n        const std::string& nameOfBodyExertingAcceleration,\n        const bool useCentralBodyFixedFrame )\n{\n    // Declare pointer to return object.\n    std::shared_ptr< CentralGravitationalAccelerationModel3d > accelerationModelPointer;\n\n    // Check if body is endowed with a gravity field model (i.e. is capable of exerting\n    // gravitation acceleration).\n    if( bodyExertingAcceleration->getGravityFieldModel( ) == nullptr )\n    {\n        throw std::runtime_error(\n                    std::string( \"Error, gravity field model not set when making central \") +\n                    \" gravitational acceleration of \" + nameOfBodyExertingAcceleration + \" on \" +\n                    nameOfBodyUndergoingAcceleration );\n    }\n    else\n    {\n        std::function< double( ) > gravitationalParameterFunction;\n\n        // Set correct value for gravitational parameter.\n        if( useCentralBodyFixedFrame == 0  ||\n                bodyUndergoingAcceleration->getGravityFieldModel( ) == nullptr )\n        {\n            gravitationalParameterFunction =\n                    std::bind( &gravitation::GravityFieldModel::getGravitationalParameter,\n                               bodyExertingAcceleration->getGravityFieldModel( ) );\n        }\n        else\n        {\n            std::function< double( ) > gravitationalParameterOfBodyExertingAcceleration =\n                    std::bind( &gravitation::GravityFieldModel::getGravitationalParameter,\n                               bodyExertingAcceleration->getGravityFieldModel( ) );\n            std::function< double( ) > gravitationalParameterOfBodyUndergoingAcceleration =\n                    std::bind( &gravitation::GravityFieldModel::getGravitationalParameter,\n                               bodyUndergoingAcceleration->getGravityFieldModel( ) );\n            gravitationalParameterFunction =\n                    std::bind( &utilities::sumFunctionReturn< double >,\n                               gravitationalParameterOfBodyExertingAcceleration,\n                               gravitationalParameterOfBodyUndergoingAcceleration );\n        }\n\n        // Create acceleration object.\n        accelerationModelPointer =\n                std::make_shared< CentralGravitationalAccelerationModel3d >(\n                    std::bind( &Body::getPosition, bodyUndergoingAcceleration ),\n                    gravitationalParameterFunction,\n                    std::bind( &Body::getPosition, bodyExertingAcceleration ),\n                    useCentralBodyFixedFrame );\n    }\n\n\n    return accelerationModelPointer;\n}\n\n//! Function to create spherical harmonic gravity acceleration model.\nstd::shared_ptr< gravitation::SphericalHarmonicsGravitationalAccelerationModel >\ncreateSphericalHarmonicsGravityAcceleration(\n        const std::shared_ptr< Body > bodyUndergoingAcceleration,\n        const std::shared_ptr< Body > bodyExertingAcceleration,\n        const std::string& nameOfBodyUndergoingAcceleration,\n        const std::string& nameOfBodyExertingAcceleration,\n        const std::shared_ptr< AccelerationSettings > accelerationSettings,\n        const bool useCentralBodyFixedFrame,\n        const bool useDegreeZeroTerm )\n{\n    // Declare pointer to return object\n    std::shared_ptr< SphericalHarmonicsGravitationalAccelerationModel > accelerationModel;\n\n    // Dynamic cast acceleration settings to required type and check consistency.\n    std::shared_ptr< SphericalHarmonicAccelerationSettings > sphericalHarmonicsSettings =\n            std::dynamic_pointer_cast< SphericalHarmonicAccelerationSettings >(\n                accelerationSettings );\n    if( sphericalHarmonicsSettings == nullptr )\n    {\n        throw std::runtime_error(\n                    std::string( \"Error, acceleration settings inconsistent \") +\n                    \" making sh gravitational acceleration of \" + nameOfBodyExertingAcceleration +\n                    \" on \" + nameOfBodyUndergoingAcceleration );\n    }\n    else\n    {\n        // Get pointer to gravity field of central body and cast to required type.\n        std::shared_ptr< SphericalHarmonicsGravityField > sphericalHarmonicsGravityField =\n                std::dynamic_pointer_cast< SphericalHarmonicsGravityField >(\n                    bodyExertingAcceleration->getGravityFieldModel( ) );\n\n        std::shared_ptr< RotationalEphemeris> rotationalEphemeris =\n                bodyExertingAcceleration->getRotationalEphemeris( );\n        if( sphericalHarmonicsGravityField == nullptr )\n        {\n            throw std::runtime_error(\n                        std::string( \"Error, spherical harmonic gravity field model not set when \")\n                        + \" making sh gravitational acceleration of \" +\n                        nameOfBodyExertingAcceleration +\n                        \" on \" + nameOfBodyUndergoingAcceleration );\n        }\n        else\n        {\n            if( rotationalEphemeris == nullptr )\n            {\n                throw std::runtime_error( \"Warning when making spherical harmonic acceleration on body \" +\n                                          nameOfBodyUndergoingAcceleration + \", no rotation model found for \" +\n                                          nameOfBodyExertingAcceleration );\n            }\n\n            if( rotationalEphemeris->getTargetFrameOrientation( ) !=\n                    sphericalHarmonicsGravityField->getFixedReferenceFrame( ) )\n            {\n                throw std::runtime_error( \"Warning when making spherical harmonic acceleration on body \" +\n                                          nameOfBodyUndergoingAcceleration + \", rotation model found for \" +\n                                          nameOfBodyExertingAcceleration + \" is incompatible, frames are: \" +\n                                          rotationalEphemeris->getTargetFrameOrientation( ) + \" and \" +\n                                          sphericalHarmonicsGravityField->getFixedReferenceFrame( ) );\n            }\n\n            std::function< double( ) > gravitationalParameterFunction;\n\n            // Check if mutual acceleration is to be used.\n            if( useCentralBodyFixedFrame == false ||\n                    bodyUndergoingAcceleration->getGravityFieldModel( ) == nullptr )\n            {\n                gravitationalParameterFunction =\n                        std::bind( &SphericalHarmonicsGravityField::getGravitationalParameter,\n                                   sphericalHarmonicsGravityField );\n            }\n            else\n            {\n                // Create function returning summed gravitational parameter of the two bodies.\n                std::function< double( ) > gravitationalParameterOfBodyExertingAcceleration =\n                        std::bind( &gravitation::GravityFieldModel::getGravitationalParameter,\n                                   sphericalHarmonicsGravityField );\n                std::function< double( ) > gravitationalParameterOfBodyUndergoingAcceleration =\n                        std::bind( &gravitation::GravityFieldModel::getGravitationalParameter,\n                                   bodyUndergoingAcceleration->getGravityFieldModel( ) );\n                gravitationalParameterFunction =\n                        std::bind( &utilities::sumFunctionReturn< double >,\n                                   gravitationalParameterOfBodyExertingAcceleration,\n                                   gravitationalParameterOfBodyUndergoingAcceleration );\n            }\n\n            std::function< Eigen::MatrixXd( ) > originalCosineCoefficientFunction =\n                    std::bind( &SphericalHarmonicsGravityField::getCosineCoefficientsBlock,\n                               sphericalHarmonicsGravityField,\n                               sphericalHarmonicsSettings->maximumDegree_,\n                               sphericalHarmonicsSettings->maximumOrder_ );\n\n            std::function< Eigen::MatrixXd( ) > cosineCoefficientFunction;\n            if( !useDegreeZeroTerm )\n            {\n                cosineCoefficientFunction =\n                        std::bind( &setDegreeAndOrderCoefficientToZero, originalCosineCoefficientFunction );\n            }\n            else\n            {\n                cosineCoefficientFunction = originalCosineCoefficientFunction;\n            }\n\n            // Create acceleration object.\n            accelerationModel =\n                    std::make_shared< SphericalHarmonicsGravitationalAccelerationModel >\n                    ( std::bind( &Body::getPosition, bodyUndergoingAcceleration ),\n                      gravitationalParameterFunction,\n                      sphericalHarmonicsGravityField->getReferenceRadius( ),\n                      cosineCoefficientFunction,\n                      std::bind( &SphericalHarmonicsGravityField::getSineCoefficientsBlock,\n                                 sphericalHarmonicsGravityField,\n                                 sphericalHarmonicsSettings->maximumDegree_,\n                                 sphericalHarmonicsSettings->maximumOrder_ ),\n                      std::bind( &Body::getPosition, bodyExertingAcceleration ),\n                      std::bind( &Body::getCurrentRotationToGlobalFrame,\n                                 bodyExertingAcceleration ), useCentralBodyFixedFrame );\n        }\n    }\n    return accelerationModel;\n}\n\n//! Function to create mutual spherical harmonic gravity acceleration model.\nstd::shared_ptr< gravitation::MutualSphericalHarmonicsGravitationalAccelerationModel >\ncreateMutualSphericalHarmonicsGravityAcceleration(\n        const std::shared_ptr< Body > bodyUndergoingAcceleration,\n        const std::shared_ptr< Body > bodyExertingAcceleration,\n        const std::string& nameOfBodyUndergoingAcceleration,\n        const std::string& nameOfBodyExertingAcceleration,\n        const std::shared_ptr< AccelerationSettings > accelerationSettings,\n        const bool useCentralBodyFixedFrame,\n        const bool acceleratedBodyIsCentralBody )\n{\n    using namespace basic_astrodynamics;\n\n    // Declare pointer to return object\n    std::shared_ptr< MutualSphericalHarmonicsGravitationalAccelerationModel > accelerationModel;\n\n    // Dynamic cast acceleration settings to required type and check consistency.\n    std::shared_ptr< MutualSphericalHarmonicAccelerationSettings > mutualSphericalHarmonicsSettings =\n            std::dynamic_pointer_cast< MutualSphericalHarmonicAccelerationSettings >( accelerationSettings );\n    if( mutualSphericalHarmonicsSettings == nullptr )\n    {\n        std::string errorMessage = \"Error, expected mutual spherical harmonics acceleration settings when making acceleration model on \" +\n                nameOfBodyUndergoingAcceleration + \"due to \" + nameOfBodyExertingAcceleration;\n        throw std::runtime_error( errorMessage );\n    }\n    else\n    {\n        // Get pointer to gravity field of central body and cast to required type.\n        std::shared_ptr< SphericalHarmonicsGravityField > sphericalHarmonicsGravityFieldOfBodyExertingAcceleration =\n                std::dynamic_pointer_cast< SphericalHarmonicsGravityField >(\n                    bodyExertingAcceleration->getGravityFieldModel( ) );\n        std::shared_ptr< SphericalHarmonicsGravityField > sphericalHarmonicsGravityFieldOfBodyUndergoingAcceleration =\n                std::dynamic_pointer_cast< SphericalHarmonicsGravityField >(\n                    bodyUndergoingAcceleration->getGravityFieldModel( ) );\n\n        if( sphericalHarmonicsGravityFieldOfBodyExertingAcceleration == nullptr )\n        {\n\n            std::string errorMessage = \"Error \" + nameOfBodyExertingAcceleration + \" does not have a spherical harmonics gravity field \" +\n                    \"when making mutual spherical harmonics gravity acceleration on \" +\n                    nameOfBodyUndergoingAcceleration;\n            throw std::runtime_error( errorMessage );\n\n        }\n        else if( sphericalHarmonicsGravityFieldOfBodyUndergoingAcceleration == nullptr )\n        {\n\n            std::string errorMessage = \"Error \" + nameOfBodyUndergoingAcceleration + \" does not have a spherical harmonics gravity field \" +\n                    \"when making mutual spherical harmonics gravity acceleration on \" +\n                    nameOfBodyUndergoingAcceleration;\n            throw std::runtime_error( errorMessage );\n        }\n        else\n        {\n            std::function< double( ) > gravitationalParameterFunction;\n\n            // Create function returning summed gravitational parameter of the two bodies.\n            if( useCentralBodyFixedFrame == false )\n            {\n                gravitationalParameterFunction =\n                        std::bind( &SphericalHarmonicsGravityField::getGravitationalParameter,\n                                   sphericalHarmonicsGravityFieldOfBodyExertingAcceleration );\n            }\n            else\n            {\n                // Create function returning summed gravitational parameter of the two bodies.\n                std::function< double( ) > gravitationalParameterOfBodyExertingAcceleration =\n                        std::bind( &gravitation::GravityFieldModel::getGravitationalParameter,\n                                   sphericalHarmonicsGravityFieldOfBodyExertingAcceleration );\n                std::function< double( ) > gravitationalParameterOfBodyUndergoingAcceleration =\n                        std::bind( &gravitation::GravityFieldModel::getGravitationalParameter,\n                                   sphericalHarmonicsGravityFieldOfBodyUndergoingAcceleration );\n                gravitationalParameterFunction =\n                        std::bind( &utilities::sumFunctionReturn< double >,\n                                   gravitationalParameterOfBodyExertingAcceleration,\n                                   gravitationalParameterOfBodyUndergoingAcceleration );\n            }\n\n            // Create acceleration object.\n\n            int maximumDegreeOfUndergoingBody, maximumOrderOfUndergoingBody;\n            if( !acceleratedBodyIsCentralBody )\n            {\n                maximumDegreeOfUndergoingBody = mutualSphericalHarmonicsSettings->maximumDegreeOfBodyUndergoingAcceleration_;\n                maximumOrderOfUndergoingBody = mutualSphericalHarmonicsSettings->maximumOrderOfBodyUndergoingAcceleration_;\n            }\n            else\n            {\n                maximumDegreeOfUndergoingBody = mutualSphericalHarmonicsSettings->maximumDegreeOfCentralBody_;\n                maximumOrderOfUndergoingBody = mutualSphericalHarmonicsSettings->maximumOrderOfCentralBody_;\n            }\n\n            accelerationModel = std::make_shared< MutualSphericalHarmonicsGravitationalAccelerationModel >(\n                        std::bind( &Body::getPosition, bodyUndergoingAcceleration ),\n                        std::bind( &Body::getPosition, bodyExertingAcceleration ),\n                        gravitationalParameterFunction,\n                        sphericalHarmonicsGravityFieldOfBodyExertingAcceleration->getReferenceRadius( ),\n                        sphericalHarmonicsGravityFieldOfBodyUndergoingAcceleration->getReferenceRadius( ),\n                        std::bind( &SphericalHarmonicsGravityField::getCosineCoefficientsBlock,\n                                   sphericalHarmonicsGravityFieldOfBodyExertingAcceleration,\n                                   mutualSphericalHarmonicsSettings->maximumDegreeOfBodyExertingAcceleration_,\n                                   mutualSphericalHarmonicsSettings->maximumOrderOfBodyExertingAcceleration_ ),\n                        std::bind( &SphericalHarmonicsGravityField::getSineCoefficientsBlock,\n                                   sphericalHarmonicsGravityFieldOfBodyExertingAcceleration,\n                                   mutualSphericalHarmonicsSettings->maximumDegreeOfBodyExertingAcceleration_,\n                                   mutualSphericalHarmonicsSettings->maximumOrderOfBodyExertingAcceleration_ ),\n                        std::bind( &SphericalHarmonicsGravityField::getCosineCoefficientsBlock,\n                                   sphericalHarmonicsGravityFieldOfBodyUndergoingAcceleration,\n                                   maximumDegreeOfUndergoingBody,\n                                   maximumOrderOfUndergoingBody ),\n                        std::bind( &SphericalHarmonicsGravityField::getSineCoefficientsBlock,\n                                   sphericalHarmonicsGravityFieldOfBodyUndergoingAcceleration,\n                                   maximumDegreeOfUndergoingBody,\n                                   maximumOrderOfUndergoingBody ),\n                        std::bind( &Body::getCurrentRotationToGlobalFrame,\n                                   bodyExertingAcceleration ),\n                        std::bind( &Body::getCurrentRotationToGlobalFrame,\n                                   bodyUndergoingAcceleration ),\n                        useCentralBodyFixedFrame );\n        }\n    }\n    return accelerationModel;\n}\n\n\n//! Function to create a third body central gravity acceleration model.\nstd::shared_ptr< gravitation::ThirdBodyCentralGravityAcceleration >\ncreateThirdBodyCentralGravityAccelerationModel(\n        const std::shared_ptr< Body > bodyUndergoingAcceleration,\n        const std::shared_ptr< Body > bodyExertingAcceleration,\n        const std::shared_ptr< Body > centralBody,\n        const std::string& nameOfBodyUndergoingAcceleration,\n        const std::string& nameOfBodyExertingAcceleration,\n        const std::string& nameOfCentralBody )\n{\n    // Declare pointer to return object.\n    std::shared_ptr< ThirdBodyCentralGravityAcceleration > accelerationModelPointer;\n\n    // Create acceleration object.\n    accelerationModelPointer =  std::make_shared< ThirdBodyCentralGravityAcceleration >(\n                std::dynamic_pointer_cast< CentralGravitationalAccelerationModel3d >(\n                    createCentralGravityAcceleratioModel( bodyUndergoingAcceleration,\n                                                          bodyExertingAcceleration,\n                                                          nameOfBodyUndergoingAcceleration,\n                                                          nameOfBodyExertingAcceleration, 0 ) ),\n                std::dynamic_pointer_cast< CentralGravitationalAccelerationModel3d >(\n                    createCentralGravityAcceleratioModel( centralBody, bodyExertingAcceleration,\n                                                          nameOfCentralBody,\n                                                          nameOfBodyExertingAcceleration, 0 ) ), nameOfCentralBody );\n\n    return accelerationModelPointer;\n}\n\n//! Function to create a third body spheric harmonic gravity acceleration model.\nstd::shared_ptr< gravitation::ThirdBodySphericalHarmonicsGravitationalAccelerationModel >\ncreateThirdBodySphericalHarmonicGravityAccelerationModel(\n        const std::shared_ptr< Body > bodyUndergoingAcceleration,\n        const std::shared_ptr< Body > bodyExertingAcceleration,\n        const std::shared_ptr< Body > centralBody,\n        const std::string& nameOfBodyUndergoingAcceleration,\n        const std::string& nameOfBodyExertingAcceleration,\n        const std::string& nameOfCentralBody,\n        const std::shared_ptr< AccelerationSettings > accelerationSettings )\n{\n    using namespace basic_astrodynamics;\n\n    // Declare pointer to return object\n    std::shared_ptr< ThirdBodySphericalHarmonicsGravitationalAccelerationModel > accelerationModel;\n\n    // Dynamic cast acceleration settings to required type and check consistency.\n    std::shared_ptr< SphericalHarmonicAccelerationSettings > sphericalHarmonicsSettings =\n            std::dynamic_pointer_cast< SphericalHarmonicAccelerationSettings >( accelerationSettings );\n    if( sphericalHarmonicsSettings == nullptr )\n    {\n        std::string errorMessage = \"Error, expected spherical harmonics acceleration settings when making acceleration model on \" +\n                nameOfBodyUndergoingAcceleration + \" due to \" + nameOfBodyExertingAcceleration;\n        throw std::runtime_error( errorMessage );\n    }\n    else\n    {\n        // Get pointer to gravity field of central body and cast to required type.\n        std::shared_ptr< SphericalHarmonicsGravityField > sphericalHarmonicsGravityField =\n                std::dynamic_pointer_cast< SphericalHarmonicsGravityField >(\n                    bodyExertingAcceleration->getGravityFieldModel( ) );\n        if( sphericalHarmonicsGravityField == nullptr )\n        {\n            std::string errorMessage = \"Error \" + nameOfBodyExertingAcceleration + \" does not have a spherical harmonics gravity field \" +\n                    \"when making third body spherical harmonics gravity acceleration on \" +\n                    nameOfBodyUndergoingAcceleration;\n            throw std::runtime_error( errorMessage );\n        }\n        else\n        {\n\n            accelerationModel =  std::make_shared< ThirdBodySphericalHarmonicsGravitationalAccelerationModel >(\n                        std::dynamic_pointer_cast< SphericalHarmonicsGravitationalAccelerationModel >(\n                            createSphericalHarmonicsGravityAcceleration(\n                                bodyUndergoingAcceleration, bodyExertingAcceleration, nameOfBodyUndergoingAcceleration,\n                                nameOfBodyExertingAcceleration, sphericalHarmonicsSettings, 0 ) ),\n                        std::dynamic_pointer_cast< SphericalHarmonicsGravitationalAccelerationModel >(\n                            createSphericalHarmonicsGravityAcceleration(\n                                centralBody, bodyExertingAcceleration, nameOfCentralBody,\n                                nameOfBodyExertingAcceleration, sphericalHarmonicsSettings, 0 ) ), nameOfCentralBody );\n        }\n    }\n    return accelerationModel;\n}\n\n//! Function to create a third body mutual spheric harmonic gravity acceleration model.\nstd::shared_ptr< gravitation::ThirdBodyMutualSphericalHarmonicsGravitationalAccelerationModel >\ncreateThirdBodyMutualSphericalHarmonicGravityAccelerationModel(\n        const std::shared_ptr< Body > bodyUndergoingAcceleration,\n        const std::shared_ptr< Body > bodyExertingAcceleration,\n        const std::shared_ptr< Body > centralBody,\n        const std::string& nameOfBodyUndergoingAcceleration,\n        const std::string& nameOfBodyExertingAcceleration,\n        const std::string& nameOfCentralBody,\n        const std::shared_ptr< AccelerationSettings > accelerationSettings )\n{\n    // Declare pointer to return object\n    std::shared_ptr< ThirdBodyMutualSphericalHarmonicsGravitationalAccelerationModel > accelerationModel;\n\n    // Dynamic cast acceleration settings to required type and check consistency.\n    std::shared_ptr< MutualSphericalHarmonicAccelerationSettings > mutualSphericalHarmonicsSettings =\n            std::dynamic_pointer_cast< MutualSphericalHarmonicAccelerationSettings >( accelerationSettings );\n    if( mutualSphericalHarmonicsSettings == nullptr )\n    {\n\n        std::string errorMessage = \"Error, expected mutual spherical harmonics acceleration settings when making acceleration model on \" +\n                nameOfBodyUndergoingAcceleration +\n                \" due to \" + nameOfBodyExertingAcceleration;\n        throw std::runtime_error( errorMessage );\n    }\n    else\n    {\n        // Get pointer to gravity field of central body and cast to required type.\n        std::shared_ptr< SphericalHarmonicsGravityField > sphericalHarmonicsGravityFieldOfBodyExertingAcceleration =\n                std::dynamic_pointer_cast< SphericalHarmonicsGravityField >(\n                    bodyExertingAcceleration->getGravityFieldModel( ) );\n        std::shared_ptr< SphericalHarmonicsGravityField > sphericalHarmonicsGravityFieldOfBodyUndergoingAcceleration =\n                std::dynamic_pointer_cast< SphericalHarmonicsGravityField >(\n                    bodyUndergoingAcceleration->getGravityFieldModel( ) );\n        std::shared_ptr< SphericalHarmonicsGravityField > sphericalHarmonicsGravityFieldOfCentralBody =\n                std::dynamic_pointer_cast< SphericalHarmonicsGravityField >(\n                    centralBody->getGravityFieldModel( ) );\n\n        if( sphericalHarmonicsGravityFieldOfBodyExertingAcceleration == nullptr )\n        {\n            std::string errorMessage = \"Error \" + nameOfBodyExertingAcceleration + \" does not have a spherical harmonics gravity field \" +\n                    \"when making mutual spherical harmonics gravity acceleration on \" +\n                    nameOfBodyUndergoingAcceleration;\n            throw std::runtime_error( errorMessage );\n        }\n        else if( sphericalHarmonicsGravityFieldOfBodyUndergoingAcceleration == nullptr )\n        {\n            std::string errorMessage = \"Error \" + nameOfBodyUndergoingAcceleration + \" does not have a spherical harmonics gravity field \" +\n                    \"when making mutual spherical harmonics gravity acceleration on \" +\n                    nameOfBodyUndergoingAcceleration;\n            throw std::runtime_error( errorMessage );\n        }\n        else if( sphericalHarmonicsGravityFieldOfCentralBody == nullptr )\n        {\n            std::string errorMessage = \"Error \" + nameOfCentralBody + \" does not have a spherical harmonics gravity field \" +\n                    \"when making mutual spherical harmonics gravity acceleration on \" +\n                    nameOfBodyUndergoingAcceleration;\n            throw std::runtime_error( errorMessage );\n        }\n        else\n        {\n            std::shared_ptr< MutualSphericalHarmonicAccelerationSettings > accelerationSettingsForCentralBodyAcceleration =\n                    std::make_shared< MutualSphericalHarmonicAccelerationSettings >(\n                        mutualSphericalHarmonicsSettings->maximumDegreeOfBodyExertingAcceleration_,\n                        mutualSphericalHarmonicsSettings->maximumOrderOfBodyExertingAcceleration_,\n                        mutualSphericalHarmonicsSettings->maximumDegreeOfCentralBody_,\n                        mutualSphericalHarmonicsSettings->maximumOrderOfCentralBody_ );\n            accelerationModel =  std::make_shared< ThirdBodyMutualSphericalHarmonicsGravitationalAccelerationModel >(\n                        std::dynamic_pointer_cast< MutualSphericalHarmonicsGravitationalAccelerationModel >(\n                            createMutualSphericalHarmonicsGravityAcceleration(\n                                bodyUndergoingAcceleration, bodyExertingAcceleration, nameOfBodyUndergoingAcceleration,\n                                nameOfBodyExertingAcceleration, mutualSphericalHarmonicsSettings, 0, 0 ) ),\n                        std::dynamic_pointer_cast< MutualSphericalHarmonicsGravitationalAccelerationModel >(\n                            createMutualSphericalHarmonicsGravityAcceleration(\n                                centralBody, bodyExertingAcceleration, nameOfCentralBody,\n                                nameOfBodyExertingAcceleration, accelerationSettingsForCentralBodyAcceleration, 0, 1 ) ),\n                        nameOfCentralBody );\n        }\n    }\n    return accelerationModel;\n}\n\n//! Function to create an aerodynamic acceleration model.\nstd::shared_ptr< aerodynamics::AerodynamicAcceleration > createAerodynamicAcceleratioModel(\n        const std::shared_ptr< Body > bodyUndergoingAcceleration,\n        const std::shared_ptr< Body > bodyExertingAcceleration,\n        const std::string& nameOfBodyUndergoingAcceleration,\n        const std::string& nameOfBodyExertingAcceleration )\n{\n    // Check existence of required environment models\n    if( bodyUndergoingAcceleration->getAerodynamicCoefficientInterface( ) == nullptr )\n    {\n        throw std::runtime_error( \"Error when making aerodynamic acceleration, body \" +\n                                  nameOfBodyUndergoingAcceleration +\n                                  \"has no aerodynamic coefficients.\" );\n    }\n\n    if( bodyExertingAcceleration->getAtmosphereModel( ) == nullptr )\n    {\n        throw std::runtime_error( \"Error when making aerodynamic acceleration, central body \" +\n                                  nameOfBodyExertingAcceleration + \" has no atmosphere model.\");\n    }\n\n    if( bodyExertingAcceleration->getShapeModel( ) == nullptr )\n    {\n        throw std::runtime_error( \"Error when making aerodynamic acceleration, central body \" +\n                                  nameOfBodyExertingAcceleration + \" has no shape model.\" );\n    }\n\n    // Retrieve flight conditions; create object if not yet extant.\n    std::shared_ptr< AtmosphericFlightConditions > bodyFlightConditions =\n            std::dynamic_pointer_cast< AtmosphericFlightConditions >( bodyUndergoingAcceleration->getFlightConditions( ) );\n\n    if( bodyFlightConditions == nullptr && bodyUndergoingAcceleration->getFlightConditions( ) == nullptr )\n    {\n        bodyFlightConditions = createAtmosphericFlightConditions( bodyUndergoingAcceleration,\n                                                                  bodyExertingAcceleration,\n                                                                  nameOfBodyUndergoingAcceleration,\n                                                                  nameOfBodyExertingAcceleration );\n        bodyUndergoingAcceleration->setFlightConditions( bodyFlightConditions );\n    }\n    else if( bodyFlightConditions == nullptr && bodyUndergoingAcceleration->getFlightConditions( ) != nullptr )\n    {\n        throw std::runtime_error( \"Error when making aerodynamic acceleration, found flight conditions that are not atmospheric.\" );\n    }\n\n    // Retrieve frame in which aerodynamic coefficients are defined.\n    std::shared_ptr< aerodynamics::AerodynamicCoefficientInterface > aerodynamicCoefficients =\n            bodyUndergoingAcceleration->getAerodynamicCoefficientInterface( );\n    reference_frames::AerodynamicsReferenceFrames accelerationFrame;\n    if( aerodynamicCoefficients->getAreCoefficientsInAerodynamicFrame( ) )\n    {\n        accelerationFrame = reference_frames::aerodynamic_frame;\n    }\n    else\n    {\n        accelerationFrame = reference_frames::body_frame;\n    }\n\n    // Create function to transform from frame of aerodynamic coefficienrs to that of propagation.\n    std::function< Eigen::Vector3d( const Eigen::Vector3d& ) > toPropagationFrameTransformation;\n    toPropagationFrameTransformation =\n            reference_frames::getAerodynamicForceTransformationFunction(\n                bodyFlightConditions->getAerodynamicAngleCalculator( ),\n                accelerationFrame,\n                std::bind( &Body::getCurrentRotationToGlobalFrame, bodyExertingAcceleration ),\n                reference_frames::inertial_frame );\n\n    std::function< Eigen::Vector3d( ) > coefficientFunction =\n            std::bind( &AerodynamicCoefficientInterface::getCurrentForceCoefficients,\n                       aerodynamicCoefficients );\n    std::function< Eigen::Vector3d( ) > coefficientInPropagationFrameFunction =\n            std::bind( &reference_frames::transformVectorFunctionFromVectorFunctions,\n                       coefficientFunction, toPropagationFrameTransformation );\n\n    // Create acceleration model.\n    return std::make_shared< AerodynamicAcceleration >(\n                coefficientInPropagationFrameFunction,\n                std::bind( &AtmosphericFlightConditions::getCurrentDensity, bodyFlightConditions ),\n                std::bind( &AtmosphericFlightConditions::getCurrentAirspeed, bodyFlightConditions ),\n                std::bind( &Body::getBodyMass, bodyUndergoingAcceleration ),\n                std::bind( &AerodynamicCoefficientInterface::getReferenceArea,\n                           aerodynamicCoefficients ),\n                aerodynamicCoefficients->getAreCoefficientsInNegativeAxisDirection( ) );\n}\n\n//! Function to create a cannonball radiation pressure acceleration model.\nstd::shared_ptr< CannonBallRadiationPressureAcceleration >\ncreateCannonballRadiationPressureAcceleratioModel(\n        const std::shared_ptr< Body > bodyUndergoingAcceleration,\n        const std::shared_ptr< Body > bodyExertingAcceleration,\n        const std::string& nameOfBodyUndergoingAcceleration,\n        const std::string& nameOfBodyExertingAcceleration )\n{\n    // Retrieve radiation pressure interface\n    if( bodyUndergoingAcceleration->getRadiationPressureInterfaces( ).count(\n                nameOfBodyExertingAcceleration ) == 0 )\n    {\n        throw std::runtime_error(\n                    \"Error when making radiation pressure, no radiation pressure interface found  in \" +\n                    nameOfBodyUndergoingAcceleration +\n                    \" for body \" + nameOfBodyExertingAcceleration );\n    }\n    std::shared_ptr< RadiationPressureInterface > radiationPressureInterface =\n            bodyUndergoingAcceleration->getRadiationPressureInterfaces( ).at(\n                nameOfBodyExertingAcceleration );\n\n    // Create acceleration model.\n    return std::make_shared< CannonBallRadiationPressureAcceleration >(\n                std::bind( &Body::getPosition, bodyExertingAcceleration ),\n                std::bind( &Body::getPosition, bodyUndergoingAcceleration ),\n                std::bind( &RadiationPressureInterface::getCurrentRadiationPressure, radiationPressureInterface ),\n                std::bind( &RadiationPressureInterface::getRadiationPressureCoefficient, radiationPressureInterface ),\n                std::bind( &RadiationPressureInterface::getArea, radiationPressureInterface ),\n                std::bind( &Body::getBodyMass, bodyUndergoingAcceleration ) );\n\n}\n\n//! Function to create a panelled radiation pressure acceleration model.\nstd::shared_ptr< electro_magnetism::PanelledRadiationPressureAcceleration > createPanelledRadiationPressureAcceleration(\n        const std::shared_ptr< Body > bodyUndergoingAcceleration,\n        const std::shared_ptr< Body > bodyExertingAcceleration,\n        const std::string& nameOfBodyUndergoingAcceleration,\n        const std::string& nameOfBodyExertingAcceleration )\n{\n    using namespace tudat::electro_magnetism;\n\n    // Declare pointer to return object.\n    std::shared_ptr< PanelledRadiationPressureAcceleration > accelerationModel;\n\n    // Get radiation pressure interface from body undergoing acceleration, containing data on how body responds to radiation pressure.\n    std::shared_ptr< PanelledRadiationPressureInterface > radiationPressureInterface =\n            std::dynamic_pointer_cast< PanelledRadiationPressureInterface >(\n                bodyUndergoingAcceleration->getRadiationPressureInterfaces( ).at( nameOfBodyExertingAcceleration ) );\n\n    if( radiationPressureInterface == NULL )\n    {\n        throw std::runtime_error(\n                    \"Error, body undergoing acceleration, \" + nameOfBodyUndergoingAcceleration +\n                    \" possesses no radiation pressure coefficient interface when making panelled radiation pressure acceleration due to \" +\n                    nameOfBodyExertingAcceleration );\n    }\n    else\n    {\n        // Create acceleration model.\n        accelerationModel = std::make_shared< PanelledRadiationPressureAcceleration >(\n                    radiationPressureInterface, std::bind( &Body::getBodyMass, bodyUndergoingAcceleration ) );\n    }\n    return accelerationModel;\n}\n\n//! Function to create a solar sail radiation pressure acceleration model.\nstd::shared_ptr< SolarSailAcceleration > createSolarSailAccelerationModel(\n    const std::shared_ptr< Body > bodyUndergoingAcceleration,\n    const std::shared_ptr< Body > bodyExertingAcceleration,\n    const std::shared_ptr< Body > centralBody,\n    const std::string& nameOfBodyUndergoingAcceleration,\n    const std::string& nameOfBodyExertingAcceleration )\n{\n    // Retrieve radiation pressure interface.\n    if( bodyUndergoingAcceleration->getRadiationPressureInterfaces( ).count(\n            nameOfBodyExertingAcceleration ) == 0 )\n    {\n        throw std::runtime_error(\n            \"Error when making radiation pressure, no radiation pressure interface found  in \" +\n            nameOfBodyUndergoingAcceleration +\n            \" for body \" + nameOfBodyExertingAcceleration );\n    }\n\n    // Get radiation pressure interface from body undergoing acceleration, containing data on how body responds to radiation pressure.\n    std::shared_ptr< SolarSailingRadiationPressureInterface > radiationPressureInterface =\n            std::dynamic_pointer_cast< SolarSailingRadiationPressureInterface >(\n                bodyUndergoingAcceleration->getRadiationPressureInterfaces( ).at( nameOfBodyExertingAcceleration ) );\n\n    // Create and return solar sailing acceleration model.\n    return std::make_shared< SolarSailAcceleration >(\n                std::bind( &Body::getPosition, bodyExertingAcceleration ),\n                std::bind( &Body::getPosition, bodyUndergoingAcceleration ),\n                std::bind( &Body::getVelocity, bodyUndergoingAcceleration ),\n                std::bind( &Body::getVelocity, centralBody ),\n                std::bind( &SolarSailingRadiationPressureInterface::getCurrentRadiationPressure, radiationPressureInterface ),\n                std::bind( &SolarSailingRadiationPressureInterface::getCurrentConeAngle, radiationPressureInterface ),\n                std::bind( &SolarSailingRadiationPressureInterface::getCurrentClockAngle, radiationPressureInterface ),\n                std::bind( &SolarSailingRadiationPressureInterface::getFrontEmissivityCoefficient, radiationPressureInterface ),\n                std::bind( &SolarSailingRadiationPressureInterface::getBackEmissivityCoefficient, radiationPressureInterface ),\n                std::bind( &SolarSailingRadiationPressureInterface::getFrontLambertianCoefficient, radiationPressureInterface ),\n                std::bind( &SolarSailingRadiationPressureInterface::getBackLambertianCoefficient, radiationPressureInterface ),\n                std::bind( &SolarSailingRadiationPressureInterface::getReflectivityCoefficient, radiationPressureInterface ),\n                std::bind( &SolarSailingRadiationPressureInterface::getSpecularReflectionCoefficient, radiationPressureInterface ),\n                std::bind( &RadiationPressureInterface::getArea, radiationPressureInterface ),\n                std::bind( &Body::getBodyMass, bodyUndergoingAcceleration ) );\n\n}\n\n\n//! Function to create an orbiter relativistic correction acceleration model\nstd::shared_ptr< relativity::RelativisticAccelerationCorrection > createRelativisticCorrectionAcceleration(\n        const std::shared_ptr< Body > bodyUndergoingAcceleration,\n        const std::shared_ptr< Body > bodyExertingAcceleration,\n        const std::string& nameOfBodyUndergoingAcceleration,\n        const std::string& nameOfBodyExertingAcceleration,\n        const std::shared_ptr< AccelerationSettings > accelerationSettings,\n        const NamedBodyMap& bodyMap )\n{\n    using namespace relativity;\n\n    // Declare pointer to return object\n    std::shared_ptr< RelativisticAccelerationCorrection > accelerationModel;\n\n    // Dynamic cast acceleration settings to required type and check consistency.\n    std::shared_ptr< RelativisticAccelerationCorrectionSettings > relativisticAccelerationSettings =\n            std::dynamic_pointer_cast< RelativisticAccelerationCorrectionSettings >(\n                accelerationSettings );\n    if( relativisticAccelerationSettings == nullptr )\n    {\n        throw std::runtime_error( \"Error, expected relativistic acceleration settings when making acceleration model on \" +\n                                  nameOfBodyUndergoingAcceleration + \" due to \" + nameOfBodyExertingAcceleration );\n    }\n    else\n    {\n\n        // Retrieve function pointers for properties of bodies exerting/undergoing acceleration.\n        std::function< Eigen::Vector6d( ) > stateFunctionOfBodyExertingAcceleration =\n                std::bind( &Body::getState, bodyExertingAcceleration );\n        std::function< Eigen::Vector6d( ) > stateFunctionOfBodyUndergoingAcceleration =\n                std::bind( &Body::getState, bodyUndergoingAcceleration );\n\n        std::function< double( ) > centralBodyGravitationalParameterFunction;\n        std::shared_ptr< GravityFieldModel > gravityField = bodyExertingAcceleration->getGravityFieldModel( );\n        if( gravityField == nullptr )\n        {\n            throw std::runtime_error( \"Error \" + nameOfBodyExertingAcceleration + \" does not have a gravity field \" +\n                                      \"when making relativistic acceleration on\" + nameOfBodyUndergoingAcceleration );\n        }\n        else\n        {\n            centralBodyGravitationalParameterFunction =\n                    std::bind( &GravityFieldModel::getGravitationalParameter, bodyExertingAcceleration->getGravityFieldModel( ) );\n        }\n\n        // Create acceleration model if only schwarzschild term is to be used.\n        if( relativisticAccelerationSettings->calculateLenseThirringCorrection_ == false &&\n                relativisticAccelerationSettings->calculateDeSitterCorrection_ == false )\n        {\n            std::function< double( ) > ppnGammaFunction = std::bind( &PPNParameterSet::getParameterGamma, ppnParameterSet );\n            std::function< double( ) > ppnBetaFunction = std::bind( &PPNParameterSet::getParameterBeta, ppnParameterSet );\n\n            // Create acceleration model.\n            accelerationModel = std::make_shared< RelativisticAccelerationCorrection >\n                    ( stateFunctionOfBodyUndergoingAcceleration,\n                      stateFunctionOfBodyExertingAcceleration,\n                      centralBodyGravitationalParameterFunction,\n                      ppnGammaFunction, ppnBetaFunction );\n\n        }\n        else\n        {\n\n            // Retrieve parameters of primary body if de Sitter term is to be used.\n            std::function< Eigen::Vector6d( ) > stateFunctionOfPrimaryBody;\n            std::function< double( ) > primaryBodyGravitationalParameterFunction;\n            if( relativisticAccelerationSettings->calculateDeSitterCorrection_ == true )\n            {\n                if(  bodyMap.count( relativisticAccelerationSettings->primaryBody_ ) == 0 )\n                {\n                    throw std::runtime_error( \"Error, no primary body \" + relativisticAccelerationSettings->primaryBody_ +\n                                              \" found when making de Sitter acceleration correction\" );\n                }\n                stateFunctionOfPrimaryBody =\n                        std::bind( &Body::getState, bodyMap.at( relativisticAccelerationSettings->primaryBody_ ) );\n\n                if(  bodyMap.at( relativisticAccelerationSettings->primaryBody_ )->getGravityFieldModel( ) == nullptr )\n                {\n                    throw std::runtime_error( \"Error, primary body \" + relativisticAccelerationSettings->primaryBody_ +\n                                              \" has no gravity field when making de Sitter acceleration correction\" );\n                }\n\n                primaryBodyGravitationalParameterFunction =\n                        std::bind( &GravityFieldModel::getGravitationalParameter,\n                                   bodyMap.at( relativisticAccelerationSettings->primaryBody_ )->getGravityFieldModel( ) );\n\n\n            }\n\n            // Retrieve angular momentum vector if Lense-Thirring\n            std::function< Eigen::Vector3d( ) > angularMomentumFunction;\n            if( relativisticAccelerationSettings->calculateLenseThirringCorrection_ == true  )\n            {\n                angularMomentumFunction = [ = ]( ){ return\n                            relativisticAccelerationSettings->centralBodyAngularMomentum_; };\n            }\n\n            if( relativisticAccelerationSettings->calculateDeSitterCorrection_ == true )\n            {\n                // Create acceleration model with Lense-Thirring and de Sitter terms.\n                accelerationModel = std::make_shared< RelativisticAccelerationCorrection >\n                        ( stateFunctionOfBodyUndergoingAcceleration,\n                          stateFunctionOfBodyExertingAcceleration,\n                          stateFunctionOfPrimaryBody,\n                          centralBodyGravitationalParameterFunction,\n                          primaryBodyGravitationalParameterFunction,\n                          relativisticAccelerationSettings->primaryBody_,\n                          angularMomentumFunction,\n                          std::bind( &PPNParameterSet::getParameterGamma, ppnParameterSet ),\n                          std::bind( &PPNParameterSet::getParameterBeta, ppnParameterSet ),\n                          relativisticAccelerationSettings->calculateSchwarzschildCorrection_ );\n            }\n            else\n            {\n                // Create acceleration model with Lense-Thirring and term.\n                accelerationModel = std::make_shared< RelativisticAccelerationCorrection >\n                        ( stateFunctionOfBodyUndergoingAcceleration,\n                          stateFunctionOfBodyExertingAcceleration,\n                          centralBodyGravitationalParameterFunction,\n                          angularMomentumFunction,\n                          std::bind( &PPNParameterSet::getParameterGamma, ppnParameterSet ),\n                          std::bind( &PPNParameterSet::getParameterBeta, ppnParameterSet ),\n                          relativisticAccelerationSettings->calculateSchwarzschildCorrection_ );\n            }\n        }\n    }\n    return accelerationModel;\n}\n\n\n//! Function to create empirical acceleration model.\nstd::shared_ptr< EmpiricalAcceleration > createEmpiricalAcceleration(\n        const std::shared_ptr< Body > bodyUndergoingAcceleration,\n        const std::shared_ptr< Body > bodyExertingAcceleration,\n        const std::string& nameOfBodyUndergoingAcceleration,\n        const std::string& nameOfBodyExertingAcceleration,\n        const  std::shared_ptr< AccelerationSettings > accelerationSettings )\n{\n    // Declare pointer to return object\n    std::shared_ptr< EmpiricalAcceleration > accelerationModel;\n\n    // Dynamic cast acceleration settings to required type and check consistency.\n    std::shared_ptr< EmpiricalAccelerationSettings > empiricalSettings =\n            std::dynamic_pointer_cast< EmpiricalAccelerationSettings >(\n                accelerationSettings );\n    if( empiricalSettings == nullptr )\n    {\n        throw std::runtime_error( \"Error, expected empirical acceleration settings when making acceleration model on \" +\n                                  nameOfBodyUndergoingAcceleration + \" due to \" + nameOfBodyExertingAcceleration );\n    }\n    else\n    {\n        // Get pointer to gravity field of central body (for determining keplerian elememts)\n        std::shared_ptr< GravityFieldModel > gravityField = bodyExertingAcceleration->getGravityFieldModel( );\n\n        if( gravityField == nullptr )\n        {\n            throw std::runtime_error( \"Error \" + nameOfBodyExertingAcceleration + \" does not have a gravity field \" +\n                                      \"when making empirical acceleration on\" + nameOfBodyUndergoingAcceleration );\n        }\n        else\n        {\n            // Create acceleration model.\n            accelerationModel = std::make_shared< EmpiricalAcceleration >(\n                        empiricalSettings->constantAcceleration_,\n                        empiricalSettings->sineAcceleration_,\n                        empiricalSettings->cosineAcceleration_,\n                        std::bind( &Body::getState, bodyUndergoingAcceleration ),\n                        std::bind( &GravityFieldModel::getGravitationalParameter, gravityField ),\n                        std::bind( &Body::getState, bodyExertingAcceleration ) );\n        }\n    }\n\n    return accelerationModel;\n}\n\n//! Function to create a thrust acceleration model.\nstd::shared_ptr< propulsion::ThrustAcceleration >\ncreateThrustAcceleratioModel(\n        const std::shared_ptr< AccelerationSettings > accelerationSettings,\n        const NamedBodyMap& bodyMap,\n        const std::string& nameOfBodyUndergoingThrust )\n{\n    // Check input consistency\n    std::shared_ptr< ThrustAccelerationSettings > thrustAccelerationSettings =\n            std::dynamic_pointer_cast< ThrustAccelerationSettings >( accelerationSettings );\n    if( thrustAccelerationSettings == nullptr )\n    {\n        throw std::runtime_error( \"Error when creating thrust acceleration, input is inconsistent\" );\n    }\n\n    std::map< propagators::EnvironmentModelsToUpdate, std::vector< std::string > > magnitudeUpdateSettings;\n    std::map< propagators::EnvironmentModelsToUpdate, std::vector< std::string > > directionUpdateSettings;\n\n\n\n    // Check if user-supplied interpolator for full thrust ius present.\n    if( thrustAccelerationSettings->interpolatorInterface_ != nullptr )\n    {\n        // Check input consisten\n        if( thrustAccelerationSettings->thrustFrame_ == unspecified_thurst_frame )\n        {\n            throw std::runtime_error( \"Error when creating thrust acceleration, input frame is inconsistent with interface\" );\n        }\n        else if( thrustAccelerationSettings->thrustFrame_ != inertial_thurst_frame )\n        {\n            // Create rotation function from thrust-frame to propagation frame.\n            if( thrustAccelerationSettings->thrustFrame_ == lvlh_thrust_frame )\n            {\n                std::function< Eigen::Vector6d( ) > vehicleStateFunction =\n                        std::bind( &Body::getState, bodyMap.at( nameOfBodyUndergoingThrust ) );\n                std::function< Eigen::Vector6d( ) > centralBodyStateFunction;\n\n                if( ephemerides::isFrameInertial( thrustAccelerationSettings->centralBody_ ) )\n                {\n                    centralBodyStateFunction =  [ ]( ){ return Eigen::Vector6d::Zero( ); };\n                }\n                else\n                {\n                    if( bodyMap.count( thrustAccelerationSettings->centralBody_ ) == 0 )\n                    {\n                        throw std::runtime_error( \"Error when creating thrust acceleration, input central body not found\" );\n                    }\n                    centralBodyStateFunction =\n                            std::bind( &Body::getState, bodyMap.at( thrustAccelerationSettings->centralBody_ ) );\n                }\n                thrustAccelerationSettings->interpolatorInterface_->resetRotationFunction(\n                            std::bind( &reference_frames::getVelocityBasedLvlhToInertialRotationFromFunctions,\n                                       vehicleStateFunction, centralBodyStateFunction, true ) );\n            }\n            else\n            {\n                throw std::runtime_error( \"Error when creating thrust acceleration, input frame not recognized\" );\n            }\n        }\n    }\n\n    // Create thrust direction model.\n    std::shared_ptr< propulsion::BodyFixedForceDirectionGuidance  > thrustDirectionGuidance = createThrustGuidanceModel(\n                thrustAccelerationSettings->thrustDirectionGuidanceSettings_, bodyMap, nameOfBodyUndergoingThrust,\n                getBodyFixedThrustDirection( thrustAccelerationSettings->thrustMagnitudeSettings_, bodyMap,\n                                             nameOfBodyUndergoingThrust ), magnitudeUpdateSettings );\n\n    // Create thrust magnitude model\n    std::shared_ptr< propulsion::ThrustMagnitudeWrapper > thrustMagnitude = createThrustMagnitudeWrapper(\n                thrustAccelerationSettings->thrustMagnitudeSettings_, bodyMap, nameOfBodyUndergoingThrust,\n                directionUpdateSettings );\n\n    // Add required updates of environemt models.\n    std::map< propagators::EnvironmentModelsToUpdate, std::vector< std::string > > totalUpdateSettings;\n    propagators::addEnvironmentUpdates( totalUpdateSettings, magnitudeUpdateSettings );\n    propagators::addEnvironmentUpdates( totalUpdateSettings, directionUpdateSettings );\n\n    // Set DependentOrientationCalculator for body if required.\n    if( !( thrustAccelerationSettings->thrustDirectionGuidanceSettings_->thrustDirectionType_ ==\n           thrust_direction_from_existing_body_orientation ) )\n    {\n        bodyMap.at( nameOfBodyUndergoingThrust )->setDependentOrientationCalculator( thrustDirectionGuidance );\n    }\n\n    // Create and return thrust acceleration object.\n    std::function< void( const double ) > updateFunction =\n            std::bind( &updateThrustMagnitudeAndDirection, thrustMagnitude, thrustDirectionGuidance, std::placeholders::_1 );\n    std::function< void( const double ) > timeResetFunction =\n            std::bind( &resetThrustMagnitudeAndDirectionTime, thrustMagnitude, thrustDirectionGuidance, std::placeholders::_1 );\n    return std::make_shared< propulsion::ThrustAcceleration >(\n                std::bind( &propulsion::ThrustMagnitudeWrapper::getCurrentThrustMagnitude, thrustMagnitude ),\n                std::bind( &propulsion::BodyFixedForceDirectionGuidance ::getCurrentForceDirectionInPropagationFrame, thrustDirectionGuidance ),\n                std::bind( &Body::getBodyMass, bodyMap.at( nameOfBodyUndergoingThrust ) ),\n                std::bind( &propulsion::ThrustMagnitudeWrapper::getCurrentMassRate, thrustMagnitude ),\n                thrustAccelerationSettings->thrustMagnitudeSettings_->thrustOriginId_,\n                updateFunction, timeResetFunction, totalUpdateSettings );\n}\n\n//! Function to create a direct tical acceleration model, according to approach of Lainey et al. (2007, 2009, ...)\nstd::shared_ptr< gravitation::DirectTidalDissipationAcceleration > createDirectTidalDissipationAcceleration(\n        const std::shared_ptr< Body > bodyUndergoingAcceleration,\n        const std::shared_ptr< Body > bodyExertingAcceleration,\n        const std::string& nameOfBodyUndergoingAcceleration,\n        const std::string& nameOfBodyExertingAcceleration,\n        const  std::shared_ptr< AccelerationSettings > accelerationSettings )\n{\n    // Check input consistency\n    std::shared_ptr< DirectTidalDissipationAccelerationSettings > tidalAccelerationSettings =\n            std::dynamic_pointer_cast< DirectTidalDissipationAccelerationSettings >( accelerationSettings );\n    if( tidalAccelerationSettings == nullptr )\n    {\n        throw std::runtime_error( \"Error when creating direct tidal dissipation acceleration, input is inconsistent\" );\n    }\n\n    std::function< double( ) > gravitationalParaterFunctionOfBodyExertingTide;\n    std::function< double( ) > gravitationalParaterFunctionOfBodyUndergoingTide;\n\n    if( tidalAccelerationSettings->useTideRaisedOnPlanet_ )\n    {\n        if( bodyUndergoingAcceleration->getGravityFieldModel( ) == nullptr )\n        {\n            throw std::runtime_error( \"Error when creating direct tidal dissipation acceleration, satellite \" +\n                                      nameOfBodyUndergoingAcceleration + \" has no gravity field\" );\n        }\n        else\n        {\n            gravitationalParaterFunctionOfBodyUndergoingTide = std::bind(\n                        &GravityFieldModel::getGravitationalParameter, bodyUndergoingAcceleration->getGravityFieldModel( ) );\n        }\n    }\n    else\n    {\n        if( bodyExertingAcceleration->getGravityFieldModel( ) == nullptr )\n        {\n            throw std::runtime_error( \"Error when creating direct tidal dissipation acceleration, satellite \" +\n                                      nameOfBodyExertingAcceleration + \" has no gravity field\" );\n        }\n        else\n        {\n            gravitationalParaterFunctionOfBodyExertingTide = std::bind(\n                        &GravityFieldModel::getGravitationalParameter, bodyExertingAcceleration->getGravityFieldModel( ) );\n        }\n\n\n        if( bodyUndergoingAcceleration->getGravityFieldModel( ) == nullptr )\n        {\n            throw std::runtime_error( \"Error when creating direct tidal dissipation acceleration, satellite \" +\n                                      nameOfBodyUndergoingAcceleration + \" has no gravity field\" );\n        }\n        else\n        {\n            gravitationalParaterFunctionOfBodyUndergoingTide = std::bind(\n                        &GravityFieldModel::getGravitationalParameter, bodyUndergoingAcceleration->getGravityFieldModel( ) );\n        }\n    }\n\n    double referenceRadius = TUDAT_NAN;\n    if( tidalAccelerationSettings->useTideRaisedOnPlanet_ )\n    {\n        if( std::dynamic_pointer_cast< gravitation::SphericalHarmonicsGravityField >(\n                    bodyExertingAcceleration->getGravityFieldModel( ) ) == nullptr )\n        {\n            throw std::runtime_error( \"Error when creating direct tidal dissipation acceleration, planet \" +\n                                      nameOfBodyExertingAcceleration + \" has no s.h. gravity field\" );\n        }\n        else\n        {\n            referenceRadius = std::dynamic_pointer_cast< gravitation::SphericalHarmonicsGravityField >(\n                        bodyExertingAcceleration->getGravityFieldModel( ) )->getReferenceRadius( );\n        }\n    }\n    else\n    {\n        if( std::dynamic_pointer_cast< gravitation::SphericalHarmonicsGravityField >(\n                    bodyUndergoingAcceleration->getGravityFieldModel( ) ) == nullptr )\n        {\n            throw std::runtime_error( \"Error when creating direct tidal dissipation acceleration, planet \" +\n                                      nameOfBodyUndergoingAcceleration + \" has no s.h. gravity field\" );\n        }\n        else\n        {\n            referenceRadius = std::dynamic_pointer_cast< gravitation::SphericalHarmonicsGravityField >(\n                        bodyUndergoingAcceleration->getGravityFieldModel( ) )->getReferenceRadius( );\n        }\n    }\n    \n\n    if( tidalAccelerationSettings->useTideRaisedOnPlanet_ )\n    {\n        std::function< Eigen::Vector3d( ) > planetAngularVelocityVectorFunction =\n                std::bind( &Body::getCurrentAngularVelocityVectorInGlobalFrame, bodyExertingAcceleration );\n\n\n        return std::make_shared< DirectTidalDissipationAcceleration >(\n                    std::bind( &Body::getState, bodyUndergoingAcceleration ),\n                    std::bind( &Body::getState, bodyExertingAcceleration ),\n                    gravitationalParaterFunctionOfBodyUndergoingTide,\n                    planetAngularVelocityVectorFunction,\n                    tidalAccelerationSettings->k2LoveNumber_,\n                    tidalAccelerationSettings->timeLag_,\n                    referenceRadius,\n                    tidalAccelerationSettings->includeDirectRadialComponent_);\n    }\n    else\n    {\n        return std::make_shared< DirectTidalDissipationAcceleration >(\n                    std::bind( &Body::getState, bodyUndergoingAcceleration ),\n                    std::bind( &Body::getState, bodyExertingAcceleration ),\n                    gravitationalParaterFunctionOfBodyExertingTide,\n                    gravitationalParaterFunctionOfBodyUndergoingTide,\n                    tidalAccelerationSettings->k2LoveNumber_,\n                    tidalAccelerationSettings->timeLag_,\n                    referenceRadius,\n                    tidalAccelerationSettings->includeDirectRadialComponent_);\n    }\n}\n\n//! Function to create a momentum wheel desaturation acceleration model.\nstd::shared_ptr< propulsion::MomentumWheelDesaturationThrustAcceleration > createMomentumWheelDesaturationAcceleration(\n        const std::shared_ptr< Body > bodyUndergoingAcceleration,\n        const std::shared_ptr< Body > bodyExertingAcceleration,\n        const std::string& nameOfBodyUndergoingAcceleration,\n        const std::string& nameOfBodyExertingAcceleration,\n        const  std::shared_ptr< AccelerationSettings > accelerationSettings )\n{\n    // Check input consistency\n    std::shared_ptr< MomentumWheelDesaturationAccelerationSettings > desaturationAccelerationSettings =\n            std::dynamic_pointer_cast< MomentumWheelDesaturationAccelerationSettings >( accelerationSettings );\n    if( desaturationAccelerationSettings == nullptr )\n    {\n        throw std::runtime_error( \"Error when creating momentum wheel desaturation acceleration, input is inconsistent\" );\n    }\n\n    if( nameOfBodyUndergoingAcceleration != nameOfBodyExertingAcceleration )\n    {\n        throw std::runtime_error( \"Error when creating momentum wheel desaturation acceleration, exerting and undergoing bodies are not the same\" );\n    }\n\n    // Return desaturation acceleration model.\n    return std::make_shared< propulsion::MomentumWheelDesaturationThrustAcceleration >(\n                desaturationAccelerationSettings->thrustMidTimes_,\n                desaturationAccelerationSettings->deltaVValues_,\n                desaturationAccelerationSettings->totalManeuverTime_,\n                desaturationAccelerationSettings->maneuverRiseTime_ );\n}\n\n//! Function to create acceleration model object.\nstd::shared_ptr< AccelerationModel< Eigen::Vector3d > > createAccelerationModel(\n        const std::shared_ptr< Body > bodyUndergoingAcceleration,\n        const std::shared_ptr< Body > bodyExertingAcceleration,\n        const std::shared_ptr< AccelerationSettings > accelerationSettings,\n        const std::string& nameOfBodyUndergoingAcceleration,\n        const std::string& nameOfBodyExertingAcceleration,\n        const std::shared_ptr< Body > centralBody,\n        const std::string& nameOfCentralBody,\n        const NamedBodyMap& bodyMap )\n{\n    // Declare pointer to return object.\n    std::shared_ptr< AccelerationModel< Eigen::Vector3d > > accelerationModelPointer;\n\n    // Switch to call correct acceleration model type factory function.\n    switch( accelerationSettings->accelerationType_ )\n    {\n    case central_gravity:\n        accelerationModelPointer = createGravitationalAccelerationModel(\n                    bodyUndergoingAcceleration, bodyExertingAcceleration, accelerationSettings,\n                    nameOfBodyUndergoingAcceleration, nameOfBodyExertingAcceleration,\n                    centralBody, nameOfCentralBody );\n        break;\n    case spherical_harmonic_gravity:\n        accelerationModelPointer = createGravitationalAccelerationModel(\n                    bodyUndergoingAcceleration, bodyExertingAcceleration, accelerationSettings,\n                    nameOfBodyUndergoingAcceleration, nameOfBodyExertingAcceleration,\n                    centralBody, nameOfCentralBody );\n        break;\n    case mutual_spherical_harmonic_gravity:\n        accelerationModelPointer = createGravitationalAccelerationModel(\n                    bodyUndergoingAcceleration, bodyExertingAcceleration, accelerationSettings,\n                    nameOfBodyUndergoingAcceleration, nameOfBodyExertingAcceleration,\n                    centralBody, nameOfCentralBody );\n        break;\n    case aerodynamic:\n        accelerationModelPointer = createAerodynamicAcceleratioModel(\n                    bodyUndergoingAcceleration,\n                    bodyExertingAcceleration,\n                    nameOfBodyUndergoingAcceleration,\n                    nameOfBodyExertingAcceleration );\n        break;\n    case cannon_ball_radiation_pressure:\n        accelerationModelPointer = createCannonballRadiationPressureAcceleratioModel(\n                    bodyUndergoingAcceleration,\n                    bodyExertingAcceleration,\n                    nameOfBodyUndergoingAcceleration,\n                    nameOfBodyExertingAcceleration );\n        break;\n    case panelled_radiation_pressure_acceleration:\n        accelerationModelPointer = createPanelledRadiationPressureAcceleration(\n                    bodyUndergoingAcceleration,\n                    bodyExertingAcceleration,\n                    nameOfBodyUndergoingAcceleration,\n                    nameOfBodyExertingAcceleration );\n        break;\n    case thrust_acceleration:\n        accelerationModelPointer = createThrustAcceleratioModel(\n                    accelerationSettings, bodyMap,\n                    nameOfBodyUndergoingAcceleration );\n        break;\n    case relativistic_correction_acceleration:\n        accelerationModelPointer = createRelativisticCorrectionAcceleration(\n                    bodyUndergoingAcceleration,\n                    bodyExertingAcceleration,\n                    nameOfBodyUndergoingAcceleration,\n                    nameOfBodyExertingAcceleration,\n                    accelerationSettings, bodyMap );\n        break;\n    case empirical_acceleration:\n        accelerationModelPointer = createEmpiricalAcceleration(\n                    bodyUndergoingAcceleration,\n                    bodyExertingAcceleration,\n                    nameOfBodyUndergoingAcceleration,\n                    nameOfBodyExertingAcceleration,\n                    accelerationSettings );\n        break;\n    case direct_tidal_dissipation_in_central_body_acceleration:\n        accelerationModelPointer = createDirectTidalDissipationAcceleration(\n                    bodyUndergoingAcceleration,\n                    bodyExertingAcceleration,\n                    nameOfBodyUndergoingAcceleration,\n                    nameOfBodyExertingAcceleration,\n                    accelerationSettings );\n        break;\n    case direct_tidal_dissipation_in_orbiting_body_acceleration:\n        accelerationModelPointer = createDirectTidalDissipationAcceleration(\n                    bodyUndergoingAcceleration,\n                    bodyExertingAcceleration,\n                    nameOfBodyUndergoingAcceleration,\n                    nameOfBodyExertingAcceleration,\n                    accelerationSettings );\n        break;\n    case momentum_wheel_desaturation_acceleration:\n        accelerationModelPointer = createMomentumWheelDesaturationAcceleration(\n                    bodyUndergoingAcceleration,\n                    bodyExertingAcceleration,\n                    nameOfBodyUndergoingAcceleration,\n                    nameOfBodyExertingAcceleration,\n                    accelerationSettings );\n        break;\n    case solar_sail_acceleration:\n        accelerationModelPointer = createSolarSailAccelerationModel(\n                    bodyUndergoingAcceleration,\n                    bodyExertingAcceleration,\n                    centralBody,\n                    nameOfBodyUndergoingAcceleration,\n                    nameOfBodyExertingAcceleration );\n        break;\n    default:\n        throw std::runtime_error(\n                    std::string( \"Error, acceleration model \") +\n                    std::to_string( accelerationSettings->accelerationType_ ) +\n                    \" not recognized when making acceleration model of\" +\n                    nameOfBodyExertingAcceleration + \" on \" +\n                    nameOfBodyUndergoingAcceleration );\n        break;\n    }\n    return accelerationModelPointer;\n}\n\n//! Function to put SelectedAccelerationMap in correct order, to ensure correct model creation\nSelectedAccelerationList orderSelectedAccelerationMap( const SelectedAccelerationMap& selectedAccelerationsPerBody )\n{\n    // Declare map of acceleration models acting on current body.\n    SelectedAccelerationList orderedAccelerationsPerBody;\n\n    // Iterate over all bodies which are undergoing acceleration\n    for( SelectedAccelerationMap::const_iterator bodyIterator =\n         selectedAccelerationsPerBody.begin( ); bodyIterator != selectedAccelerationsPerBody.end( );\n         bodyIterator++ )\n    {\n        // Retrieve name of body undergoing acceleration.\n        std::string bodyUndergoingAcceleration = bodyIterator->first;\n\n        // Retrieve list of required acceleration model types and bodies exerting accelerationd on\n        // current body.\n        std::map< std::string, std::vector< std::shared_ptr< AccelerationSettings > > >\n                accelerationsForBody = bodyIterator->second;\n\n        // Retrieve indices of all acceleration anf thrust models.\n        std::vector< int > aerodynamicAccelerationIndices;\n        std::vector< int > thrustAccelerationIndices;\n\n        std::vector< std::pair< std::string, std::shared_ptr< AccelerationSettings > > >\n                currentBodyAccelerations;\n        int counter = 0;\n        // Iterate over all bodies exerting an acceleration\n        for( std::map< std::string, std::vector< std::shared_ptr< AccelerationSettings > > >::\n             iterator body2Iterator = accelerationsForBody.begin( );\n             body2Iterator != accelerationsForBody.end( ); body2Iterator++ )\n        {\n            // Retrieve name of body exerting acceleration.\n            std::string bodyExertingAcceleration = body2Iterator->first;\n            std::vector< std::shared_ptr< AccelerationSettings > > accelerationList = body2Iterator->second;\n            for( unsigned int i = 0; i < accelerationList.size( ); i++ )\n            {\n                if( accelerationList.at( i )->accelerationType_ == basic_astrodynamics::thrust_acceleration )\n                {\n                    thrustAccelerationIndices.push_back( counter );\n                }\n                else if( accelerationList.at( i )->accelerationType_ == basic_astrodynamics::aerodynamic )\n                {\n                    aerodynamicAccelerationIndices.push_back( counter );\n                }\n                std::pair< std::string, std::shared_ptr< AccelerationSettings > >  currentAccelerationPair =\n                        std::make_pair( bodyExertingAcceleration, accelerationList.at( i ) );\n                currentBodyAccelerations.push_back( currentAccelerationPair );\n                counter++;\n            }\n        }\n\n        if( thrustAccelerationIndices.size( ) > 0 && aerodynamicAccelerationIndices.size( ) > 0 )\n        {\n            std::vector< int > indexList;\n            for( unsigned int i = 0; i < aerodynamicAccelerationIndices.size( ); i++ )\n            {\n                indexList.push_back( aerodynamicAccelerationIndices.at( i ) );\n            }\n            for( unsigned int i = 0; i < thrustAccelerationIndices.size( ); i++ )\n            {\n                indexList.push_back( thrustAccelerationIndices.at( i ) );\n            }\n\n            std::vector< int > unorderedIndexList = indexList;\n            std::sort( indexList.begin( ), indexList.end( ) );\n            if( !( indexList == unorderedIndexList ) )\n            {\n                std::vector< std::pair< std::string, std::shared_ptr< AccelerationSettings > > >\n                        orderedAccelerationSettings = currentBodyAccelerations;\n\n                int indexCounter = 0;\n                for( unsigned int i = 0; i < aerodynamicAccelerationIndices.size( ); i++ )\n                {\n                    orderedAccelerationSettings[ indexList.at( indexCounter ) ]\n                            = currentBodyAccelerations[ aerodynamicAccelerationIndices.at( i ) ];\n                    indexCounter++;\n                }\n\n                for( unsigned int i = 0; i < thrustAccelerationIndices.size( ); i++ )\n                {\n                    orderedAccelerationSettings[ indexList.at( indexCounter ) ]\n                            = currentBodyAccelerations[ thrustAccelerationIndices.at( i ) ];\n                    indexCounter++;\n                }\n\n                currentBodyAccelerations = orderedAccelerationSettings;\n            }\n        }\n\n        orderedAccelerationsPerBody[ bodyUndergoingAcceleration ] = currentBodyAccelerations;\n    }\n\n    return orderedAccelerationsPerBody;\n}\n\n\n//! Function to create a set of acceleration models from a map of bodies and acceleration model types.\nbasic_astrodynamics::AccelerationMap createAccelerationModelsMap(\n        const NamedBodyMap& bodyMap,\n        const SelectedAccelerationMap& selectedAccelerationPerBody,\n        const std::map< std::string, std::string >& centralBodies )\n{\n    // Declare return map.\n    basic_astrodynamics::AccelerationMap accelerationModelMap;\n\n    // Put selectedAccelerationPerBody in correct order\n    SelectedAccelerationList orderedAccelerationPerBody =\n            orderSelectedAccelerationMap( selectedAccelerationPerBody );\n\n    // Iterate over all bodies which are undergoing acceleration\n    for( SelectedAccelerationList::const_iterator bodyIterator =\n         orderedAccelerationPerBody.begin( ); bodyIterator != orderedAccelerationPerBody.end( );\n         bodyIterator++ )\n    {\n        std::shared_ptr< Body > currentCentralBody;\n\n        // Retrieve name of body undergoing acceleration.\n        std::string bodyUndergoingAcceleration = bodyIterator->first;\n\n        // Retrieve name of current central body.\n        std::string currentCentralBodyName = centralBodies.at( bodyUndergoingAcceleration );\n\n        if( !ephemerides::isFrameInertial( currentCentralBodyName ) )\n        {\n            if( bodyMap.count( currentCentralBodyName ) == 0 )\n            {\n                throw std::runtime_error(\n                            std::string( \"Error, could not find non-inertial central body \") +\n                            currentCentralBodyName + \" of \" + bodyUndergoingAcceleration +\n                            \" when making acceleration model.\" );\n            }\n            else\n            {\n                currentCentralBody = bodyMap.at( currentCentralBodyName );\n            }\n        }\n\n        // Check if body undergoing acceleration is included in bodyMap\n        if( bodyMap.count( bodyUndergoingAcceleration ) ==  0 )\n        {\n            throw std::runtime_error(\n                        std::string( \"Error when making acceleration models, requested forces\" ) +\n                        \"acting on body \" + bodyUndergoingAcceleration  +\n                        \", but no such body found in map of bodies\" );\n        }\n\n        // Declare map of acceleration models acting on current body.\n        basic_astrodynamics::SingleBodyAccelerationMap mapOfAccelerationsForBody;\n\n        // Retrieve list of required acceleration model types and bodies exerting accelerationd on\n        // current body.\n        std::vector< std::pair< std::string, std::shared_ptr< AccelerationSettings > > >\n                accelerationsForBody = bodyIterator->second;\n\n        std::vector< std::pair< std::string, std::shared_ptr< AccelerationSettings > > > thrustAccelerationSettings;\n\n        std::shared_ptr< basic_astrodynamics::AccelerationModel< Eigen::Vector3d > > currentAcceleration;\n        // Iterate over all bodies exerting an acceleration\n        for( unsigned int i = 0; i < accelerationsForBody.size( ); i++ )\n        {\n            // Retrieve name of body exerting acceleration.\n            std::string bodyExertingAcceleration = accelerationsForBody.at( i ).first;\n\n            // Check if body exerting acceleration is included in bodyMap\n            if( bodyMap.count( bodyExertingAcceleration ) ==  0 )\n            {\n                throw std::runtime_error(\n                            std::string( \"Error when making acceleration models, requested forces \")\n                            + \"acting on body \" + bodyUndergoingAcceleration  + \" due to body \" +\n                            bodyExertingAcceleration +\n                            \", but no such body found in map of bodies\" );\n            }\n\n            if( !( accelerationsForBody.at( i ).second->accelerationType_ == basic_astrodynamics::thrust_acceleration ) )\n            {\n                currentAcceleration = createAccelerationModel( bodyMap.at( bodyUndergoingAcceleration ),\n                                                               bodyMap.at( bodyExertingAcceleration ),\n                                                               accelerationsForBody.at( i ).second,\n                                                               bodyUndergoingAcceleration,\n                                                               bodyExertingAcceleration,\n                                                               currentCentralBody,\n                                                               currentCentralBodyName,\n                                                               bodyMap );\n\n\n                // Create acceleration model.\n                mapOfAccelerationsForBody[ bodyExertingAcceleration ].push_back(\n                            currentAcceleration );\n            }\n            else\n            {\n                thrustAccelerationSettings.push_back( accelerationsForBody.at( i ) );\n            }\n\n        }\n\n        for( unsigned int i = 0; i < thrustAccelerationSettings.size( ); i++ )\n        {\n            currentAcceleration = createAccelerationModel( bodyMap.at( bodyUndergoingAcceleration ),\n                                                           bodyMap.at( thrustAccelerationSettings.at( i ).first ),\n                                                           thrustAccelerationSettings.at( i ).second,\n                                                           bodyUndergoingAcceleration,\n                                                           thrustAccelerationSettings.at( i ).first,\n                                                           currentCentralBody,\n                                                           currentCentralBodyName,\n                                                           bodyMap );\n\n\n            // Create acceleration model.\n            mapOfAccelerationsForBody[ thrustAccelerationSettings.at( i ).first  ].push_back(\n                        currentAcceleration );\n        }\n\n\n        // Put acceleration models on current body in return map.\n        accelerationModelMap[ bodyUndergoingAcceleration ] = mapOfAccelerationsForBody;\n    }\n\n    return accelerationModelMap;\n}\n\n//! Function to create acceleration models from a map of bodies and acceleration model types.\nbasic_astrodynamics::AccelerationMap createAccelerationModelsMap(\n        const NamedBodyMap& bodyMap,\n        const SelectedAccelerationMap& selectedAccelerationPerBody,\n        const std::vector< std::string >& propagatedBodies,\n        const std::vector< std::string >& centralBodies )\n{\n    if( centralBodies.size( ) != propagatedBodies.size( ) )\n    {\n        throw std::runtime_error( \"Error, number of propagated bodies must equal number of central bodies\" );\n    }\n\n    std::map< std::string, std::string > centralBodyMap;\n    for( unsigned int i = 0; i < propagatedBodies.size( ); i++ )\n    {\n        centralBodyMap[ propagatedBodies.at( i ) ] = centralBodies.at( i );\n    }\n\n    return createAccelerationModelsMap( bodyMap, selectedAccelerationPerBody, centralBodyMap );\n}\n\n} // namespace simulation_setup\n\n} // namespace tudat\n", "meta": {"hexsha": "0bde75a8f260edf02034a86656d5b660b63cd28d", "size": 88985, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Tudat/SimulationSetup/PropagationSetup/createAccelerationModels.cpp", "max_stars_repo_name": "sebranchett/tudat", "max_stars_repo_head_hexsha": "24e5f3cc85c250fcbed0aac37f026c1dd7fd6c44", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Tudat/SimulationSetup/PropagationSetup/createAccelerationModels.cpp", "max_issues_repo_name": "sebranchett/tudat", "max_issues_repo_head_hexsha": "24e5f3cc85c250fcbed0aac37f026c1dd7fd6c44", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Tudat/SimulationSetup/PropagationSetup/createAccelerationModels.cpp", "max_forks_repo_name": "sebranchett/tudat", "max_forks_repo_head_hexsha": "24e5f3cc85c250fcbed0aac37f026c1dd7fd6c44", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 53.7673716012, "max_line_length": 148, "alphanum_fraction": 0.6522447604, "num_tokens": 16691, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.785308580887758, "lm_q2_score": 0.39606816627404173, "lm_q1q2_score": 0.3110357295914843}}
{"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_HASH_KECCAK_HPP\n#define CRYPTO3_HASH_KECCAK_HPP\n\n#include <nil/crypto3/hash/detail/sponge_construction.hpp>\n#include <nil/crypto3/hash/detail/block_stream_processor.hpp>\n\n#include <nil/crypto3/hash/detail/keccak/keccak_functions.hpp>\n#include <nil/crypto3/hash/detail/keccak/keccak_policy.hpp>\n#include <nil/crypto3/hash/detail/keccak/keccak_finalizer.hpp>\n#include <nil/crypto3/hash/detail/keccak/keccak_padding.hpp>\n\n#include <boost/endian/conversion.hpp>\n\nnamespace nil {\n    namespace crypto3 {\n        namespace hashes {\n            template<std::size_t DigestBits = 512>\n            class keccak_1600_compressor {\n            protected:\n                typedef detail::keccak_1600_functions<DigestBits> policy_type;\n\n            public:\n                constexpr static const std::size_t word_bits = policy_type::word_bits;\n                typedef typename policy_type::word_type word_type;\n\n                constexpr static const std::size_t state_bits = policy_type::state_bits;\n                constexpr static const std::size_t state_words = policy_type::state_words;\n                typedef typename policy_type::state_type state_type;\n\n                constexpr static const std::size_t block_bits = policy_type::block_bits;\n                constexpr static const std::size_t block_words = policy_type::block_words;\n                typedef typename policy_type::block_type block_type;\n\n                static void process_block(state_type &state, const block_type &block) {\n                    for (std::size_t i = 0; i != block_words; ++i)\n                        state[i] ^= block[i];\n\n                    for (std::size_t i = 0; i != state_words; ++i)\n                        boost::endian::endian_reverse_inplace(state[i]);\n\n                    policy_type::permute(state);\n\n                    for (std::size_t i = 0; i != state_words; ++i)\n                        boost::endian::endian_reverse_inplace(state[i]);\n                }\n            };\n\n            /*!\n             * @brief\n             * @tparam DigestBits\n             * @ingroup hashes\n             */\n            template<std::size_t DigestBits = 512>\n            class keccak_1600 {\n                typedef detail::keccak_1600_policy<DigestBits> policy_type;\n\n            public:\n                constexpr static const std::size_t word_bits = policy_type::word_bits;\n                typedef typename policy_type::word_type word_type;\n\n                constexpr static const std::size_t block_bits = policy_type::block_bits;\n                constexpr static const std::size_t block_words = policy_type::block_words;\n                typedef typename policy_type::block_type block_type;\n\n                constexpr static const std::size_t digest_bits = policy_type::digest_bits;\n                typedef typename policy_type::digest_type digest_type;\n\n                struct construction {\n                    struct params_type {\n                        typedef typename policy_type::digest_endian digest_endian;\n\n                        constexpr static const std::size_t length_bits = policy_type::length_bits;\n                        constexpr static const std::size_t digest_bits = policy_type::digest_bits;\n                    };\n\n                    typedef sponge_construction<\n                        params_type, typename policy_type::iv_generator, keccak_1600_compressor<DigestBits>,\n                        detail::keccak_1600_padding<policy_type>, detail::keccak_1600_finalizer<policy_type>>\n                        type;\n                };\n\n                template<typename StateAccumulator, std::size_t ValueBits>\n                struct stream_processor {\n                    struct params_type {\n                        typedef typename policy_type::digest_endian digest_endian;\n\n                        constexpr static const std::size_t value_bits = ValueBits;\n                    };\n\n                    typedef block_stream_processor<construction, StateAccumulator, params_type> type;\n                };\n            };\n        }    // namespace hashes\n    }        // namespace crypto3\n}    // namespace nil\n\n#endif\n", "meta": {"hexsha": "a9408758e84c8bebdec55418b8b69ef638a8aeb1", "size": 5518, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/nil/crypto3/hash/keccak.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/keccak.hpp", "max_issues_repo_name": "JasonCoombs/crypto3-hash", "max_issues_repo_head_hexsha": "a4f330d14029b0b0330a5697ef24e825137ffded", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 18.0, "max_issues_repo_issues_event_min_datetime": "2020-09-24T01:09:15.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-14T14:43:47.000Z", "max_forks_repo_path": "include/nil/crypto3/hash/keccak.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": 44.8617886179, "max_line_length": 109, "alphanum_fraction": 0.6170714027, "num_tokens": 1069, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6688802603710085, "lm_q2_score": 0.4649015713733885, "lm_q1q2_score": 0.31096348410712304}}
{"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 \"modified_helmholtz_3d_calderon_projector.hpp\"\n#include \"../common/shared_ptr.hpp\"\n\n#include \"modified_helmholtz_3d_single_layer_boundary_operator.hpp\"\n#include \"modified_helmholtz_3d_double_layer_boundary_operator.hpp\"\n#include \"modified_helmholtz_3d_hypersingular_boundary_operator.hpp\"\n#include \"identity_operator.hpp\"\n#include \"blocked_operator_structure.hpp\"\n#include \"../fiber/explicit_instantiation.hpp\"\n\n#include <boost/make_shared.hpp>\n\nnamespace Bempp {\n\ntemplate <typename BasisFunctionType, typename KernelType, typename ResultType>\nBlockedBoundaryOperator<BasisFunctionType, ResultType>\nmodifiedHelmholtz3dExteriorCalderonProjector(\n    const shared_ptr<const Context<BasisFunctionType, ResultType>> &context,\n    const shared_ptr<const Space<BasisFunctionType>> &hminusSpace,\n    const shared_ptr<const Space<BasisFunctionType>> &hplusSpace,\n    KernelType waveNumber, const std::string &label, bool useInterpolation,\n    int interpPtsPerWavelength) {\n\n  typedef BoundaryOperator<BasisFunctionType, ResultType> BdOp;\n\n  shared_ptr<const Space<BasisFunctionType>> internalHplusSpace =\n      hplusSpace->discontinuousSpace(hplusSpace);\n\n  BdOp internalSlp = modifiedHelmholtz3dSingleLayerBoundaryOperator(\n      context, internalHplusSpace, internalHplusSpace, internalHplusSpace,\n      waveNumber, label + \"_slp\", SYMMETRIC, useInterpolation,\n      interpPtsPerWavelength);\n\n  BdOp dlp = modifiedHelmholtz3dDoubleLayerBoundaryOperator(\n      context, hplusSpace, hplusSpace, hminusSpace, waveNumber, label + \"_dlp\",\n      NO_SYMMETRY, useInterpolation, interpPtsPerWavelength);\n\n  BdOp adjDlp = adjoint(dlp);\n\n  BdOp hyp = modifiedHelmholtz3dHypersingularBoundaryOperator(\n      context, hplusSpace, hminusSpace, hplusSpace, waveNumber, label + \"_hyp\",\n      SYMMETRIC, useInterpolation, interpPtsPerWavelength, internalSlp);\n\n  BdOp idSpaceTransformation1 = identityOperator(\n      context, hminusSpace, internalHplusSpace, internalHplusSpace);\n  BdOp idSpaceTransformation2 =\n      identityOperator(context, internalHplusSpace, hplusSpace, hminusSpace);\n  BdOp idDouble =\n      identityOperator(context, hplusSpace, hplusSpace, hminusSpace);\n  BdOp idAdjDouble =\n      identityOperator(context, hminusSpace, hminusSpace, hplusSpace);\n\n  // Now Assemble the entries of the Calderon Projector\n\n  BlockedOperatorStructure<BasisFunctionType, ResultType> structure;\n\n  structure.setBlock(0, 0, .5 * idDouble + dlp);\n  structure.setBlock(0, 1, -1. * idSpaceTransformation2 * internalSlp *\n                               idSpaceTransformation1);\n  structure.setBlock(1, 0, -1. * hyp);\n  structure.setBlock(1, 1, .5 * idAdjDouble - adjDlp);\n\n  return BlockedBoundaryOperator<BasisFunctionType, ResultType>(structure);\n}\n\ntemplate <typename BasisFunctionType, typename KernelType, typename ResultType>\nBlockedBoundaryOperator<BasisFunctionType, ResultType>\nmodifiedHelmholtz3dInteriorCalderonProjector(\n    const shared_ptr<const Context<BasisFunctionType, ResultType>> &context,\n    const shared_ptr<const Space<BasisFunctionType>> &hminusSpace,\n    const shared_ptr<const Space<BasisFunctionType>> &hplusSpace,\n    KernelType waveNumber, const std::string &label, bool useInterpolation,\n    int interpPtsPerWavelength) {\n\n  typedef BoundaryOperator<BasisFunctionType, ResultType> BdOp;\n\n  shared_ptr<const Space<BasisFunctionType>> internalHplusSpace =\n      hplusSpace->discontinuousSpace(hplusSpace);\n\n  BdOp internalSlp = modifiedHelmholtz3dSingleLayerBoundaryOperator(\n      context, internalHplusSpace, internalHplusSpace, internalHplusSpace,\n      waveNumber, label + \"_slp\", SYMMETRIC, useInterpolation,\n      interpPtsPerWavelength);\n\n  BdOp dlp = modifiedHelmholtz3dDoubleLayerBoundaryOperator(\n      context, hplusSpace, hplusSpace, hminusSpace, waveNumber, label + \"_dlp\",\n      NO_SYMMETRY, useInterpolation, interpPtsPerWavelength);\n\n  BdOp adjDlp = adjoint(dlp);\n\n  BdOp hyp = modifiedHelmholtz3dHypersingularBoundaryOperator(\n      context, hplusSpace, hminusSpace, hplusSpace, waveNumber, label + \"_hyp\",\n      SYMMETRIC, useInterpolation, interpPtsPerWavelength, internalSlp);\n\n  BdOp idSpaceTransformation1 = identityOperator(\n      context, hminusSpace, internalHplusSpace, internalHplusSpace);\n  BdOp idSpaceTransformation2 =\n      identityOperator(context, internalHplusSpace, hplusSpace, hminusSpace);\n  BdOp idDouble =\n      identityOperator(context, hplusSpace, hplusSpace, hminusSpace);\n  BdOp idAdjDouble =\n      identityOperator(context, hminusSpace, hminusSpace, hplusSpace);\n\n  // Now Assemble the entries of the Calderon Projector\n\n  BlockedOperatorStructure<BasisFunctionType, ResultType> structure;\n\n  structure.setBlock(0, 0, .5 * idDouble - dlp);\n  structure.setBlock(0, 1, idSpaceTransformation2 * internalSlp *\n                               idSpaceTransformation1);\n  structure.setBlock(1, 0, hyp);\n  structure.setBlock(1, 1, .5 * idAdjDouble + adjDlp);\n\n  return BlockedBoundaryOperator<BasisFunctionType, ResultType>(structure);\n}\n\n#define INSTANTIATE_NONMEMBER_CONSTRUCTOR(BASIS, KERNEL, RESULT)               \\\n  template BlockedBoundaryOperator<BASIS, RESULT>                              \\\n  modifiedHelmholtz3dExteriorCalderonProjector(                                \\\n      const shared_ptr<const Context<BASIS, RESULT>> &,                        \\\n      const shared_ptr<const Space<BASIS>> &,                                  \\\n      const shared_ptr<const Space<BASIS>> &, KERNEL, const std::string &,     \\\n      bool, int);                                                              \\\n  template BlockedBoundaryOperator<BASIS, RESULT>                              \\\n  modifiedHelmholtz3dInteriorCalderonProjector(                                \\\n      const shared_ptr<const Context<BASIS, RESULT>> &,                        \\\n      const shared_ptr<const Space<BASIS>> &,                                  \\\n      const shared_ptr<const Space<BASIS>> &, KERNEL, const std::string &,     \\\n      bool, int)\n\nFIBER_ITERATE_OVER_BASIS_KERNEL_AND_RESULT_TYPES(\n    INSTANTIATE_NONMEMBER_CONSTRUCTOR);\n\n} // Bempp\n", "meta": {"hexsha": "fe6ee49bd915445e2e3c68554583d65c5cbf9419", "size": 7204, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lib/assembly/modified_helmholtz_3d_calderon_projector.cpp", "max_stars_repo_name": "mdavezac/bempp", "max_stars_repo_head_hexsha": "bc573062405bda107d1514e40b6153a8350d5ab5", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "lib/assembly/modified_helmholtz_3d_calderon_projector.cpp", "max_issues_repo_name": "mdavezac/bempp", "max_issues_repo_head_hexsha": "bc573062405bda107d1514e40b6153a8350d5ab5", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lib/assembly/modified_helmholtz_3d_calderon_projector.cpp", "max_forks_repo_name": "mdavezac/bempp", "max_forks_repo_head_hexsha": "bc573062405bda107d1514e40b6153a8350d5ab5", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 46.4774193548, "max_line_length": 80, "alphanum_fraction": 0.7393114936, "num_tokens": 1741, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.685949467848392, "lm_q2_score": 0.45326184801538616, "lm_q1q2_score": 0.31091472344213283}}
{"text": "/*==========================================================\n * tCGGPsumrnd.cpp\n *\n * The calling syntax is:\n *\n *\t\tS_w = tCGGPsumrnd(p, logalpha, sigma, tau, a, b, gamma, T)\n *\t\tS_w = tCGGPsumrnd(p, logalpha, sigma, tau, a, b, gamma, T, seed)\n *\n * Compilation command (from MATLAB console)\n * -----------------------------------------\n * Using gcc (Linux, Mac):\n * - using a C++11 compiler (gcc>=4.3):\n *\n *      mex tCGGPsumrnd.cpp CXXFLAGS='$CXXFLAGS -std=c++0x -fopenmp' LDFLAGS='$LDFLAGS -fopenmp'\n *\n * - using Boost installed in a standard path:\n *\n *      mex tCGGPsumrnd.cpp CXXFLAGS='$CXXFLAGS -fopenmp' LDFLAGS='$LDFLAGS -fopenmp'\n *\n * - using custom Boost path:\n *\n *      mex tCGGPsumrnd.cpp -Ipath/to/boost CXXFLAGS='$CXXFLAGS -fopenmp' LDFLAGS='$LDFLAGS -fopenmp'\n *\n * Using Microsoft Visual C++ (Windows) and Boost:\n * \n *      mex tCGGPsumrnd.cpp -Ipath/to/boost COMPFLAGS=\"$COMPFLAGS /openmp\" LINKFLAGS=\"$LINKFLAGS /openmp\"\n *\n * e.g: mex tCGGPsumrnd.cpp -I\"C:/Program Files/boost/boost_1_58_0\" COMPFLAGS=\"$COMPFLAGS /openmp\" LINKFLAGS=\"$LINKFLAGS /openmp\"\n *\n *========================================================*/\n\n#include \"mex.h\"\n#include <cmath>\n#include <ctime>\n#include <limits>\n#include <omp.h>\n\ntypedef double double_;\n\n#if __cplusplus != 199711L /* C++11 std */\n        \n#include <random> \ntypedef std::default_random_engine generator; \ntypedef std::uniform_real_distribution<double_> uniform_dist; \ntypedef std::gamma_distribution<double_> gamma_dist; \n\n#else /* Boost */\n\n#include <boost/math/special_functions/gamma.hpp>\nusing boost::math::lgamma;\n\n#include <boost/random/mersenne_twister.hpp>\n#include <boost/random/uniform_real_distribution.hpp>\n#include <boost/random/gamma_distribution.hpp>\ntypedef boost::random::mt19937 generator;\ntypedef boost::random::uniform_real_distribution<double_> uniform_dist;\ntypedef boost::random::gamma_distribution<double_> gamma_dist;\n\n#endif\n\nvoid tCGGPsumrnd( const unsigned p,  const double logalpha, const double sigma,\n        const double tau, const double * a, const double * b, const double * gamma, \n        double_ T, const double_ Tmax, const unsigned seed,\n        double_ * S_w );\n\nvoid tCGGPsumrnd_tau0( const unsigned p,  const double logalpha, const double sigma,\n        const double * a, const double * b, const double * gamma, \n        double_ T, const double_ Tmax, const unsigned seed,\n        double_ * S_w );\n\n/* The gateway function */\nvoid mexFunction( int nlhs, mxArray *plhs[],\n                  int nrhs, const mxArray *prhs[] )\n{\n    /* check for proper number of arguments */\n    if(nrhs<8) {\n        mexErrMsgTxt(\"At least 8 inputs required.\");\n    }\n    if(nlhs!=1) {\n        mexErrMsgTxt(\"One output required.\");\n    }\n    \n    /* get the value of the input  */\n    const unsigned p = mxGetScalar( prhs[0] );\n    const double logalpha = mxGetScalar( prhs[1] );\n    const double sigma = mxGetScalar( prhs[2] );\n    const double tau = mxGetScalar( prhs[3] );\n    double * a = mxGetPr( prhs[4] );\n    const unsigned na = mxGetNumberOfElements( prhs[4] );\n    double * b = mxGetPr( prhs[5] );\n    const unsigned nb = mxGetNumberOfElements( prhs[5] );\n    double * gamma = mxGetPr( prhs[6] );\n    const unsigned ng = mxGetNumberOfElements( prhs[6] );\n    const double T = mxGetScalar( prhs[7] );\n    double seed = time(NULL);\n    if ( nrhs >= 9 )\n        seed = mxGetScalar( prhs[8] );\n    // number of concurent jobs\n    unsigned nthreads = omp_get_max_threads();\n    if ( nrhs >= 10 )\n        nthreads = unsigned(mxGetScalar( prhs[9] ));\n    \n    if ( na < p && na==1 ) {\n        // duplicate value of a\n        double a_val = *a;\n        a = new double[p];\n        for ( unsigned k = 0; k < p; ++k )\n            a[k] = a_val;\n    }\n    if ( nb < p && nb==1 ) {\n        // duplicate value of b\n        double b_val = *a;\n        b = new double[p];\n        for ( unsigned k = 0; k < p; ++k )\n            b[k] = b_val;\n    }\n    if ( ng < p && ng==1 ) {\n        // duplicate value of gamma\n        double g_val = *a;\n        gamma = new double[p];\n        for ( unsigned k = 0; k < p; ++k )\n            gamma[k] = g_val;\n    }\n    \n    // expected log number of jumps\n    const double_ cst = logalpha - lgamma( 1.0 - sigma ) - log(sigma);\n    const double_ log_njumps = cst - sigma * log(T);\n    \n    /* cut into nthreads intervals [Tcut(i), Tcut(i+1)] such that the expected\n     * number of jumps is njumps/nthreads in each interval */\n    double_ * Tcut = new double_[nthreads+1];\n    Tcut[0] = T;\n    for (unsigned i = 1; i < nthreads; ++i) {\n        // TODO: find a better bound of the expected number of jumps\n        Tcut[i] = pow( pow(Tcut[i-1], -sigma) - exp( log_njumps - log(double(nthreads)) - cst ), -1.0 / sigma);\n    }\n    Tcut[nthreads] = std::numeric_limits<double_>::infinity();\n            \n    double_ ** S_w = new double_*[nthreads];\n    for (unsigned i = 0; i < nthreads; ++i)\n        S_w[i] = new double_[p];\n    \n    /* call the computational routine */\n    if ( tau < 1e-8 ) {\n        // case tau==0\n        #pragma omp parallel for\n        for (int i = 0; i < nthreads; ++i) {\n            tCGGPsumrnd_tau0( p, logalpha, sigma, a, b, gamma, Tcut[i], Tcut[i+1], unsigned(seed)+i,\n                S_w[i] );\n        }\n    } else {\n        // case tau>0\n        #pragma omp parallel for\n        for (int i = 0; i < nthreads; ++i) {\n            tCGGPsumrnd( p, logalpha, sigma, tau, a, b, gamma, Tcut[i], Tcut[i+1], unsigned(seed)+i,\n                S_w[i] );\n        }\n    }\n    \n    /* reduction */\n    for (unsigned i = 1; i < nthreads; ++i) {\n        for (unsigned k = 0; k < p; ++k)\n            S_w[0][k] += S_w[i][k];\n    }\n    \n    /* create the output */\n    plhs[0] = mxCreateDoubleMatrix( 1, p, mxREAL );\n    for (unsigned k = 0; k < p; ++k)\n        mxGetPr( plhs[0] )[k] = S_w[0][k];\n    \n    /* deallocate memory */\n    delete[] Tcut;\n    for (unsigned i = 0; i < nthreads; ++i)\n        delete[] S_w[i];\n    delete[] S_w;\n    if ( na < p && na==1 )\n        delete[] a;\n    if ( nb < p && nb==1 )\n        delete[] b;\n    if ( ng < p && ng==1 )\n        delete[] gamma;\n}\n\n/* The computational routine */\n\nvoid tCGGPsumrnd( const unsigned p,  const double logalpha, const double sigma,\n        const double tau, const double * a, const double * b, const double * gamma, \n        double_ T, const double_ Tmax, const unsigned seed,\n        double_ * S_w )\n{\n    const double_ sigmap1 = sigma + 1.0;\n    const double_ tauinv = 1.0 / tau;\n    const double_ log_cst = logalpha - lgamma( 1.0 - sigma ) - log(tau);\n    double_ * gamma_b = new double_[p];\n    for ( unsigned k = 0; k < p; ++k )\n        gamma_b[k] = gamma[k]/b[k];\n    double_ log_r;    \n    double_ log_mgf;       \n    double_ t_new;    \n    double_ log_mgf_new; \n    double_ log_G;\n    generator gen(seed);\n    uniform_dist unif( 0.0, 1.0 );\n    gamma_dist gam;\n\n    for ( unsigned k = 0; k < p; ++k )\n        S_w[k] = 0.0;\n       \n    while (true) {\n        log_r = log( -log( unif(gen) ) );\n        log_mgf = 0.0;\n        for ( unsigned k = 0; k < p; ++k )\n            log_mgf -= a[k] * log1p( T * gamma_b[k] );\n        log_G = log_mgf + log_cst - sigmap1 * log(T) - tau * T;\n        if ( log_r > log_G )\n            break;\n        t_new = T - tauinv * log1p( -exp( log_r - log_G ) );\n        if ( t_new > Tmax )\n            break;\n        log_mgf_new = 0.0;\n        for ( unsigned k = 0; k < p; ++k )\n            log_mgf_new -= a[k] * log1p( t_new * gamma_b[k] );\n        if ( log( unif(gen) ) < sigmap1 * ( log(T) - log(t_new) ) + log_mgf_new - log_mgf ) {\n            for ( unsigned k = 0; k < p; ++k ) {\n                gam = gamma_dist( a[k], 1 / ( b[k] + t_new * gamma[k] ) );\n                S_w[k] += exp( log(t_new) + log( gam(gen) ) );\n                //gam = gamma_dist( a[k], 1 / ( b[k] / t_new + gamma[k] ) );\n                //S_w[k] += gam(gen);\n            }\n        }\n        T = t_new;\n    }\n    \n    delete[] gamma_b;\n}\n\n\nvoid tCGGPsumrnd_tau0( const unsigned p,  const double logalpha, const double sigma,\n        const double * a, const double * b, const double * gamma, \n        double_ T, const double_ Tmax, const unsigned seed,\n        double_ * S_w )\n{\n    const double_ log_cst = logalpha - lgamma( 1.0 - sigma ) - log(sigma);\n    const double_ msigma = -sigma;\n    const double_ msigmainv = 1.0 / msigma;\n    double_ * gamma_b = new double_[p];\n    for ( unsigned k = 0; k < p; ++k )\n        gamma_b[k] = gamma[k]/b[k];\n    double_ log_r;    \n    double_ log_mgf;       \n    double_ t_new;    \n    double_ log_mgf_new; \n    double_ log_temp; \n    double_ log_tmsigma;\n    generator gen(seed);\n    uniform_dist unif( 0.0, 1.0 );\n    gamma_dist gam;\n\n    for ( unsigned k = 0; k < p; ++k )\n        S_w[k] = 0.0;\n       \n    while (true) {\n        log_r = log( -log( unif(gen) ) );\n        log_mgf = 0.0;\n        for ( unsigned k = 0; k < p; ++k )\n            log_mgf -= a[k] * log1p( T * gamma_b[k] );\n        log_temp = log_r - log_mgf - log_cst;\n        log_tmsigma = msigma * log(T);\n        if ( log_temp > log_tmsigma )\n            break;\n        t_new = pow( exp(log_tmsigma) - exp(log_temp) , msigmainv );\n        if ( t_new > Tmax )\n            break;\n        log_mgf_new = 0.0;\n        for ( unsigned k = 0; k < p; ++k )\n            log_mgf_new -= a[k] * log1p( t_new * gamma_b[k] );\n        if ( log( unif(gen) ) < log_mgf_new - log_mgf ) {\n            for ( unsigned k = 0; k < p; ++k ) {\n                gam = gamma_dist( a[k], 1 / ( b[k] / t_new + gamma[k] ) );\n                S_w[k] += gam(gen);\n            }\n        }\n        T = t_new;\n    }\n    \n    delete[] gamma_b;\n}\n", "meta": {"hexsha": "484fbd6bd907243c03d991dc368f51a8d1dfa2ec", "size": 9611, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "CGGP/private/tCGGPsumrnd.cpp", "max_stars_repo_name": "jdtuck/SNetOC", "max_stars_repo_head_hexsha": "3e1c8800155bf998dfa150691e25afcd4de86f30", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2019-03-27T10:03:40.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-31T14:27:57.000Z", "max_issues_repo_path": "CGGP/private/tCGGPsumrnd.cpp", "max_issues_repo_name": "jdtuck/SNetOC", "max_issues_repo_head_hexsha": "3e1c8800155bf998dfa150691e25afcd4de86f30", "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": "CGGP/private/tCGGPsumrnd.cpp", "max_forks_repo_name": "jdtuck/SNetOC", "max_forks_repo_head_hexsha": "3e1c8800155bf998dfa150691e25afcd4de86f30", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2018-01-07T17:12:48.000Z", "max_forks_repo_forks_event_max_datetime": "2019-11-01T18:47:34.000Z", "avg_line_length": 33.3715277778, "max_line_length": 129, "alphanum_fraction": 0.543543856, "num_tokens": 2924, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6859494550081925, "lm_q2_score": 0.45326184801538616, "lm_q1q2_score": 0.31091471762216033}}
{"text": "/* Copyright (C) 2017 IBM Corp.\n *  Licensed under the Apache License, Version 2.0 (the \"License\"); \n * you may not use this file except in compliance with the License. \n * You may obtain a copy of the License at\n *     http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, \n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,\n * either express or implied. See the License for the specific\n * language governing permissions and limitations under the License. \n */\n/////////////////////////////\n// sampleG - Sampling pre-image z such that G*z = v, G is the \"easy\" matrix\n//////////////////////////////////////////\n\n//#include <mpfr.h>\n#include <NTL/mat_lzz_p.h>\n#include \"utils/timing.h\"\n\nNTL_CLIENT\n\n#include \"mat_l.h\"\n#include \"stash.h\"\n#include \"TDMatrix.h\"\n\nstatic zz_p\nupdateSyndromValue(vec_l &xOut, const Vec<vec_zz_p>& syndrom,\n\t\t   TDMatrixParams* params, long lFactor, long row,long offset);\n\n//#define DEBUG\n\n// Sample from a discrete Gaussian until you get a sample point equal\n// to u modulo f. Uses a stack to put points that are not equal to u.\nstatic long sampleMod(long u, long f,\n                      Gaussian1Dsampler& sampler, SampleStash& stash)\n{\n  FHE_TIMER_START;\n\n  long umodf = u%f;\n  if (umodf<0) umodf += f;\n\n  long val = (long)stash.getPoint(umodf);\n  if (val != umodf+1) // found in stash\n    return val;\n\n  // If not found in stash, sample until you get it\n  while (true) {\n    NTL::Pair<bool,long> extra(false,0);\n    val = sampler.getSample(/*mu=*/0.0, extra);\n    long valmodf = val%f;\n    if (valmodf<0) valmodf += f;\n\n    if ( valmodf == umodf ) // found\n      return val;\n    else                    // not found, keep point for later\n      stash.setPoint(valmodf, (int)val);\n  }\n}\n\n\n// SampleG: Sample vector xOut such that G * xOut = syndrom. syndrom is given\n// in CRT representation but x is a vector of longs.\n\n// Generate a vector of size params>n*kFactors*e\n// For each row in G, choose kFactors*e elements of xOut\n\n// The function updates the syndrom vector, based on all previously\n// chosen values in xOut. We update syndrom[lFactor][row]\n// only just before we need to use it (as opposed to updating\n// it for every new value of xOut as it is chosen)\n\n// based on the updated syndrome, we sample a new entry in xOut,\n// equal to uVal mod factor and append it to xOut\n\nint sampleG(vec_l &xOut,\n            const Vec<vec_zz_p>& syndrom, TDMatrixParams* params)\n{\n  FHE_TIMER_START;\n  xOut.SetLength(0);\n  xOut.SetMaxLength(params->m); // allocate space\n\n  long sigma = params->r * params->maxFactor;\n  Gaussian1Dsampler sampler(sigma);\n\n  zz_pPush push; // backup the NTL current modulus\n\n  // For each row in G, choose kFactors*e elements of xOut\n  for (long row = 0; row < params->n; row++)\n    {\n      long offset = row * (params->kFactors) * (params->e);\n\n      for (long lFactor = 0; lFactor < params->kFactors; lFactor++)\n        {\n\t  long factor = params->factors[lFactor];\n\t  params->zzp_context[lFactor].restore(); // NTL-modulus := factor\n\n\t  // lazy update of the syndrom vector, based on all previously\n\t  // chosen values in xOut. We update syndrom[lFactor][row]\n\t  // only just before we need to use it (as opposed to updating\n\t  // it for every new value of xOut as it is chosen).\n\n\t  zz_p zzNewVal = updateSyndromValue(xOut, syndrom,params, lFactor, row, offset);\n\n\t  long uVal = conv<long>(zzNewVal);\n\n\t  // Done updating the uSyndrom, now choose next e elements in xOut\n\n\t  for (long lPower = 0; lPower < params->e; lPower++)\n            {\n\t      // sample a new entry in xOut, equal to uVal mod factor\n\t      long samp = sampleMod(uVal, factor, sampler, params->stash[lFactor]);\n\t      assert( 0 == ((uVal-samp)%factor) ); // sanity check\n\n\t      xOut.append(samp);\n\n\t      // update uVal := (uVal-samp)/factor (over the integers)\n\t      uVal -= samp;\n\t      uVal /= factor;\n            }\n        }\n    }\n  return 0;\n}\n\n\n// lazy update of the syndrom vector, based on all previously chosen values\n// in xOut. We update syndrom[lFactor][row] just before we need to use it\n// (as opposed to updating it for every new value of xOut as it is chosen).\n\nstatic zz_p\nupdateSyndromValue(vec_l &xOut, const Vec<vec_zz_p>& syndrom,\n\t\t   TDMatrixParams* params, long lFactor, long row, long offset)\n{\n    zz_p zzNewVal = syndrom[lFactor][row];\n#ifdef DEBUG\n    cout << zzNewVal << endl;\n#endif\n    long xIndex=offset;\n    for (long vFactor = 0; vFactor < lFactor; vFactor++)\n        for (long ie=0; ie < params->e; ie++) // repeat e times\n        {\n            long xVal = xOut[xIndex++];     // xIndex = offset+ie\n            zzNewVal -= xVal;\n            zzNewVal *= params->fInv[vFactor][lFactor];\n            // update via u := (u - xval)/pi (mod pj)\n#ifdef DEBUG\n            cout << zzNewVal << endl;\n#endif\n        }\n    return zzNewVal;\n}\n", "meta": {"hexsha": "d7a58041b2cbc392c0b229b7df1def53472a44cb", "size": 4926, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "sampleG.cpp", "max_stars_repo_name": "shaih/BPobfus", "max_stars_repo_head_hexsha": "9c116312a8c9c0bc47a1c4b20e771c60c2510c6e", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2017-09-25T14:37:20.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-11T03:19:43.000Z", "max_issues_repo_path": "sampleG.cpp", "max_issues_repo_name": "shaih/BPobfus", "max_issues_repo_head_hexsha": "9c116312a8c9c0bc47a1c4b20e771c60c2510c6e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "sampleG.cpp", "max_forks_repo_name": "shaih/BPobfus", "max_forks_repo_head_hexsha": "9c116312a8c9c0bc47a1c4b20e771c60c2510c6e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2017-12-23T04:03:34.000Z", "max_forks_repo_forks_event_max_datetime": "2019-09-12T07:42:29.000Z", "avg_line_length": 32.4078947368, "max_line_length": 82, "alphanum_fraction": 0.6485992692, "num_tokens": 1352, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5851011542032312, "lm_q2_score": 0.5312093733737563, "lm_q1q2_score": 0.31081121748456}}
{"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\n#ifndef HAVOQGT_MPI_PAGE_RANK_HPP_INCLUDED\n#define HAVOQGT_MPI_PAGE_RANK_HPP_INCLUDED\n\n\n\n#include <havoqgt/visitor_queue.hpp>\n#include <boost/container/deque.hpp>\n#include <vector>\n\nnamespace havoqgt {\n\ntemplate <typename Visitor>\nclass pr_queue\n{\n\nprotected:\n  std::vector< Visitor > m_data;\npublic:\n  pr_queue() { }\n\n  bool push(Visitor const & task)\n  {\n    m_data.push_back(task);\n    return true;\n  }\n\n  void pop()\n  {\n    m_data.pop_back();\n  }\n\n  Visitor const & top() //const\n  {\n    return m_data.back();\n  }\n\n  size_t size() const\n  {\n    return m_data.size();;\n  }\n\n  bool empty() const\n  {\n    return m_data.empty();\n  }\n\n  void clear()\n  {\n    m_data.clear();\n  }\n};\n\n\n\ntemplate<typename Graph>\nclass pr_visitor {\npublic:\n  typedef typename Graph::vertex_locator                 vertex_locator;\n  pr_visitor(): rank(std::numeric_limits<double>::min())  { }\n\n  pr_visitor(vertex_locator _vertex, double _rank)\n    : vertex(_vertex)\n    , rank(_rank) { }\n\n  pr_visitor(vertex_locator _vertex)\n    : vertex(_vertex)\n    , rank(std::numeric_limits<double>::min()) { }      \n\n  template<typename AlgData> \n  bool pre_visit(AlgData& alg_data) const {\n    if(rank == std::numeric_limits<double>::min()) {\n      HAVOQGT_ERROR_MSG(\"This is a damn logic error!\");\n      return true;\n    }\n    std::get<1>(alg_data)[vertex] += rank; //change to next_rank \n    return false;\n  }\n  \n  template<typename VisitorQueueHandle, typename AlgData>\n  bool init_visit(Graph& g, VisitorQueueHandle vis_queue, AlgData& alg_data) const {\n    return visit(g, vis_queue, alg_data);\n  }\n\n  template<typename VisitorQueueHandle, typename AlgData>\n  bool visit(Graph& g, VisitorQueueHandle vis_queue, AlgData& alg_data) const {\n    //change to cur_rank\n    double old_rank = std::get<0>(alg_data)[vertex];    \n    uint64_t degree = g.degree(vertex);\n    double send_rank = old_rank / double(degree);\n\n\n    typedef typename Graph::edge_iterator eitr_type;\n    for(eitr_type eitr = g.edges_begin(vertex); eitr != g.edges_end(vertex); ++eitr) {\n      vertex_locator neighbor = eitr.target();\n      pr_visitor new_visitor( neighbor, send_rank);\n      vis_queue->queue_visitor(new_visitor);\n    }\n    return true;\n  }\n\n\n  friend inline bool operator>(const pr_visitor& v1, const pr_visitor& v2) {\n    return false;\n  }\n\n  friend inline bool operator<(const pr_visitor& v1, const pr_visitor& v2) {\n    return false;\n  }\n\n  vertex_locator   vertex;\n  double           rank;\n};\n\ntemplate <typename TGraph, typename PRData>\nvoid page_rank(TGraph& g, PRData& cur_rank, PRData& next_rank, bool initial) {\n  typedef  pr_visitor<TGraph>    visitor_type;\n  auto alg_data = std::forward_as_tuple(cur_rank, next_rank);\n   \n  if(initial) {\n    cur_rank.reset(double(1)/double(g.max_global_vertex_id()));\n  }\n   \n  auto vq = create_visitor_queue<visitor_type, detail::visitor_priority_queue>(&g, alg_data);\n  vq.init_visitor_traversal();\n  next_rank.all_reduce();\n}\n\n\n\n} //end namespace havoqgt\n\n\n\n\n#endif //HAVOQGT_MPI_PAGE_RANK_HPP_INCLUDED\n", "meta": {"hexsha": "437ff2e0209fd52184ea5c86fc118f1d17d80e36", "size": 3196, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/havoqgt/page_rank.hpp", "max_stars_repo_name": "LLNL/HavoqGT", "max_stars_repo_head_hexsha": "2e8b2a8a0ed764188079f32b1b01b8b24c81e20b", "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/page_rank.hpp", "max_issues_repo_name": "LLNL/HavoqGT", "max_issues_repo_head_hexsha": "2e8b2a8a0ed764188079f32b1b01b8b24c81e20b", "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/page_rank.hpp", "max_forks_repo_name": "LLNL/HavoqGT", "max_forks_repo_head_hexsha": "2e8b2a8a0ed764188079f32b1b01b8b24c81e20b", "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": 22.5070422535, "max_line_length": 93, "alphanum_fraction": 0.6892991239, "num_tokens": 815, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5888891451980403, "lm_q2_score": 0.5273165233795671, "lm_q1q2_score": 0.3105309767017957}}
{"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 <algorithm>\n\n#include <graphlab/ui/mongoose/mongoose.h>\n#include <boost/math/special_functions/gamma.hpp>\n#include <vector>\n#include <algorithm>\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 <graphlab/parallel/atomic.hpp>\n\n\n\n// Global Types\n// ============================================================================\ntypedef long 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< graphlab::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// We include the rest of GraphLab after we define the operator+= for\n// vector.\n#include <graphlab.hpp>\n#include <graphlab/macros_def.hpp>\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\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 std::vector< topic_id_type > assignment_type;\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 */\nsize_t NTOPICS = 50;\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/**\n * \\brief The interval to compute & display the likelihood\n */\nsize_t LIK_INTERVAL = 5;\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 * \\brief The json top word struct contains the current set of top\n * words for each topic encoded in the form of a json string.\n */\nstruct top_words_type {\n  graphlab::mutex lock;\n  std::string json_string;\n  top_words_type() : \n    json_string(\"{\\n\" + json_header_string() + \"\\tvalues: [] \\n }\") { }\n  inline std::string json_header_string() const {\n    return\n      \"\\t\\\"ntopics\\\": \" + graphlab::tostr(NTOPICS) + \",\\n\" +\n      \"\\t\\\"nwords\\\":  \" + graphlab::tostr(NWORDS) + \",\\n\" +\n      \"\\t\\\"ndocs\\\":   \" + graphlab::tostr(NDOCS) + \",\\n\" +\n      \"\\t\\\"ntokens\\\": \" + graphlab::tostr(NTOKENS) + \",\\n\" +\n      \"\\t\\\"alpha\\\":   \" + graphlab::tostr(ALPHA) + \",\\n\" +\n      \"\\t\\\"beta\\\":    \" + graphlab::tostr(BETA) + \",\\n\";\n  } // end of json header string\n} TOP_WORDS;\n\n\n\n/**\n * \\brief This method is called by the web interface to construct and\n * return the word clouds.\n */\nstd::pair<std::string, std::string>\nword_cloud_callback(std::map<std::string, std::string>& varmap) {\n  TOP_WORDS.lock.lock();\n  const std::pair<std::string, std::string>\n    pair(\"text/html\",TOP_WORDS.json_string);\n  TOP_WORDS.lock.unlock();\n  return pair;\n}\n\n\n\n\n/**\n * \\brief Create a token changes event tracker which is reported in\n * the GraphLab metrics dashboard.\n */\nDECLARE_EVENT(TOKEN_CHANGES);\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  void save(graphlab::oarchive& arc) const {\n    arc << nupdates << nchanges << factor;\n  }\n  void load(graphlab::iarchive& arc) {\n    arc >> nupdates >> nchanges >> factor;\n  }\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), assignment(ntokens, NULL_TOPIC) { }\n  void save(graphlab::oarchive& arc) const { arc << nchanges << assignment; }\n  void load(graphlab::iarchive& arc) { arc >> nchanges >> assignment; }\n}; // end of edge_data\n\n\n/**\n * \\brief The LDA graph is a bipartite graph with docs connected to\n * terms if the term occurs in the document.\n *\n * The edges store the number of occurrences of the term in the\n * document as a vector of the assignments of that term in that\n * document to topics.\n *\n * The vertices store the total topic counts.\n */\ntypedef graphlab::distributed_graph<vertex_data, edge_data> graph_type;\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 * \\brief The graph loader is used by graph.load to parse lines of the\n * text data file.\n *\n * The global variable MAX_COUNT limits the number of tokens that can\n * be constructed on a particular edge.\n *\n * We use the relativley fast boost::spirit parser to parse each line.\n */\nbool graph_loader(graph_type& graph, const std::string& fname,\n                  const std::string& line) {\n  ASSERT_FALSE(line.empty());\n  namespace qi = boost::spirit::qi;\n  namespace ascii = boost::spirit::ascii;\n  namespace phoenix = boost::phoenix;\n\n  graphlab::vertex_id_type doc_id(-1), word_id(-1);\n  size_t count = 0;\n  const bool success = qi::phrase_parse\n    (line.begin(), line.end(),       \n     //  Begin grammar\n     (\n      qi::ulong_[phoenix::ref(doc_id) = qi::_1] >> -qi::char_(',') >>\n      qi::ulong_[phoenix::ref(word_id) = qi::_1] >> -qi::char_(',') >>\n      qi::ulong_[phoenix::ref(count) = qi::_1]\n      )\n     ,\n     //  End grammar\n     ascii::space); \n  if(!success) return false;  \n  // Threshold the count\n  count = std::min(count, MAX_COUNT);\n  // since this is a bipartite graph I need a method to number the\n  // left and right vertices differently.  To accomplish I make sure\n  // all vertices have non-zero ids and then negate the right vertex.\n  // Unfortunatley graphlab reserves -1 and so we add 2 and negate.\n  doc_id += 2;\n  ASSERT_GT(doc_id, 1);\n  doc_id = -doc_id;\n  ASSERT_NE(doc_id, word_id);\n  // Create an edge and add it to the graph\n  graph.add_edge(doc_id, word_id, edge_data(count));\n  return true; // successful load\n}; // end of graph loader\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  void save(graphlab::oarchive& arc) const { arc << factor << nchanges; }\n  void load(graphlab::iarchive& arc) { arc >> factor >> 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>,\n  public graphlab::IS_POD_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        INCREMENT_EVENT(TOKEN_CHANGES,1);\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  void save(graphlab::oarchive& arc) const { arc << top_words << nchanges; }\n  void load(graphlab::iarchive& arc) { arc >> top_words >> nchanges; }\n\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    std::string json = \"{\\n\"+ TOP_WORDS.json_header_string() +\n      \"\\t\\\"values\\\": [\\n\";\n    for(size_t i = 0; i < total.top_words.size(); ++i) {\n      std::cout << \"Topic \" << i << \": \";\n      json += \"\\t[\\n\";\n      size_t counter = 0;\n      rev_foreach(cw_pair_type pair, total.top_words[i])  {\n      ASSERT_LT(pair.second, DICTIONARY.size());\n        json += \"\\t\\t[\\\"\" + DICTIONARY[pair.second] + \"\\\", \" +\n          graphlab::tostr(pair.first) + \"]\";\n        if(++counter < total.top_words[i].size()) json += \", \";\n        json += '\\n';\n        std::cout << DICTIONARY[pair.second]\n                  << \"(\" << pair.first << \")\" << \", \";\n        // std::cout << DICTIONARY[pair.second] << \",  \";\n      }\n      json += \"\\t]\";\n      if(i+1 < total.top_words.size()) json += \", \";\n      json += '\\n';\n      std::cout << std::endl;\n    }\n    json += \"]}\";\n    // Post the change to the global variable\n    TOP_WORDS.lock.lock();\n    TOP_WORDS.json_string.swap(json);\n    TOP_WORDS.lock.unlock();\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 * Computing log_gamma can be a bit slow so this class precomptues \n * log gamma for a subset of values.\n */\nclass log_gamma {\n  double offset;\n  std::vector<double> values;\npublic:\n  log_gamma(): offset(1.0) {}\n\n  void init(const double& new_offset, const size_t& buckets) {\n    using boost::math::lgamma;\n    ASSERT_GT(offset, 0.0);\n    values.resize(buckets);\n    offset = new_offset;\n    for(size_t i = 0; i < values.size(); ++i) {\n      values[i] = lgamma(i + offset);\n    }\n  }\n\n  double operator()(const count_type& index) const {\n    using boost::math::lgamma;\n    if(index < values.size() && index >= 0) { return values[index]; }\n    else { return lgamma(index + offset); }\n  }\n\n};\n\nlog_gamma ALPHA_LGAMMA;\nlog_gamma BETA_LGAMMA;\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 *\n * Latex formulation:\n *\n    \\mathcal{L}( w | z) & = T * \\left( \\log\\Gamma(W * \\beta) - W * \\log\\Gamma(\\beta) \\right) + \\\\\n    & \\sum_{t} \\left( \\left(\\sum_{w} \\log\\Gamma(N_{wt} + \\beta)\\right) - \n           \\log\\Gamma\\left( W * \\beta + \\sum_{w} N_{wt}  \\right) \\right) \\\\\n    & = T * \\left( \\log\\Gamma(W * \\beta) - W * \\log\\Gamma(\\beta) \\right) - \n        \\sum_{t} \\log\\Gamma\\left( W * \\beta + N_{t}  \\right) + \\\\\n    & \\sum_{w} \\sum_{t} \\log\\Gamma(N_{wt} + \\beta)   \\\\\n    \\\\\n    \\mathcal{L}(z) & = D * \\left(\\log\\Gamma(T * \\alpha) - T * \\log\\Gamma(\\alpha) \\right) + \\\\\n    & \\sum_{d} \\left( \\left(\\sum_{t}\\log\\Gamma(N_{td} + \\alpha)\\right) -  \n        \\log\\Gamma\\left( T * \\alpha + \\sum_{t} N_{td} \\right) \\right) \\\\\n    \\\\\n    \\mathcal{L}(w,z) & = \\mathcal{L}(w | z) + \\mathcal{L}(z)\n *\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 count_type value = std::max(count_type(factor[t]), count_type(0));\n        //ret.lik_words_given_topics += lgamma(value + BETA);\n        ret.lik_words_given_topics += BETA_LGAMMA(value);\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 count_type value = std::max(count_type(factor[t]), count_type(0));\n        //ret.lik_topics += lgamma(value + ALPHA);\n        ret.lik_topics += ALPHA_LGAMMA(value);\n        ntokens_in_doc += value;\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      const count_type value = \n        std::max(count_type(GLOBAL_TOPIC_COUNT[t]), count_type(0));\n      denominator += lgamma(value + 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 * \\brief This function is used to load and then initialize the data\n * graph (corpus) from a folder or file.\n * \n * The graph can be in either json form constructed using the graph\n * builder tools or in raw text form.  The raw text format contains a\n * token on each line of each file in the format:\n *\n \\verbatim\n <docid> <wordid> <count>\n          ...\n \\endverbatim\n *\n * for example:\n \\verbatim\n    0    0     2\n    0    4     1\n    0    2     3\n \\endverbatim\n * \n * implies that document zero contains word zero twice, word 4 once,\n * and word two three times.\n *\n * If a dictionary is used it is important that each word id\n * correspond to the index in the dictionary file (starting at zero).\n *\n * Once loaded the total number of words, documents, and tokens is\n * counted and saved to global variables which are read during the\n * execution of the sampler.\n *\n * \\param [in] dc The distributed control object used to coordinate\n * between machines.\n *\n * \\param [in,out] graph The graph object that is initialized.\n * \n * \\param [in] corpus_dir The directory or file containing the graph\n * data.  The corpus directory can reside on hdfs in which case the\n * path should begin with \"hdfs://namenode\".  In addition the file(s)\n * may be gzipped and therefore must end in \".gz\".\n *\n * \\param [in] load_json Whether the graph data is in text format or\n * preprocessed json format using the graph builder tools.\n */\nbool load_and_initialize_graph(graphlab::distributed_control& dc,\n                               graph_type& graph,\n                               const std::string& corpus_dir,\n                               const std::string& format\t\t\t       \n\t\t\t       ) {\n  dc.cout() << \"Loading graph.\" << std::endl;\n  graphlab::timer timer; timer.start();\n\n  if(format==\"matrix\"){\n      dc.cout() << \"matrix format\" << std::endl;\n      graph.load(corpus_dir, graph_loader);\n  // } else if(format==\"json\"){\n  //     dc.cout() << \"json format\" << std::endl;\n  //     graph.load_json(corpus_dir, false, eparser, vparser);\n  // } else if(format==\"json-gzip\"){\n  //     dc.cout() <<\"json gzip format\" << std::endl;\n  //     graph.load_json(corpus_dir, true, eparser, vparser);\n  }else{\n      dc.cout() << \"Non supported format. See --help\" << std::endl;\n      return false;\n  }\n\n  dc.cout() << \"Finalizing graph.\" << std::endl;\n  timer.start();\n  graph.finalize();\n  dc.cout() << \"Finalizing graph. Finished in \"\n            << timer.current_time() << \" seconds.\" << std::endl;\n\n  dc.cout() << \"Computing number of words and documents.\" << std::endl;\n  NWORDS = graph.map_reduce_vertices<size_t>(is_word);\n  NDOCS = graph.map_reduce_vertices<size_t>(is_doc);\n  NTOKENS = graph.map_reduce_edges<size_t>(count_tokens);\n\n\n  dc.cout() << \"Number of words:     \" << NWORDS  << std::endl;\n  dc.cout() << \"Number of docs:      \" << NDOCS   << std::endl;\n  dc.cout() << \"Number of tokens:    \" << NTOKENS << std::endl;\n\n  ASSERT_GT(NWORDS, 0);\n  ASSERT_GT(NDOCS, 0);\n  ASSERT_GT(NTOKENS, 0);\n\n\n  // Prepare the json struct with the word counts\n  TOP_WORDS.lock.lock();\n  TOP_WORDS.json_string = \"{\\n\" + TOP_WORDS.json_header_string() +\n    \"\\t\\\"values\\\": [] \\n }\";\n  TOP_WORDS.lock.unlock();\n  return true;\n} // end of load and initialize graph\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  if(boost::starts_with(fname, \"hdfs://\")) {\n    graphlab::hdfs hdfs;\n    graphlab::hdfs::fstream in_file(hdfs, fname);\n    boost::iostreams::filtering_stream<boost::iostreams::input> fin;\n    fin.set_auto_close(false);\n    if(gzip) fin.push(boost::iostreams::gzip_decompressor());\n    fin.push(in_file);\n    if(!fin.good()) {\n      logstream(LOG_ERROR) << \"Error loading dictionary: \"\n                           << fname << std::endl;\n      return false;\n    }\n    std::string term;\n    while(std::getline(fin,term).good()) DICTIONARY.push_back(term);\n    if (gzip) fin.pop();\n    fin.pop();\n    in_file.close();\n  } else {\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    if (gzip) fin.push(boost::iostreams::gzip_decompressor());\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    if (gzip) fin.pop();\n    fin.pop();\n    in_file.close();\n  } // end of else\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 * \\brief The omni engine type is used to allow switching between\n * synchronous and asynchronous computation. \n */\ntypedef graphlab::omni_engine<cgs_lda_vertex_program> engine_type;\n\n\n\n\n\n\n\n\n\nint main(int argc, char** argv) {\n  global_logger().set_log_level(LOG_INFO);\n  global_logger().set_log_to_console(true);\n  ///! Initialize control plain using mpi\n  graphlab::mpi_tools::init(argc, argv);\n  graphlab::distributed_control dc;\n  //  INITIALIZE_EVENT_LOG(dc);\n  ADD_CUMULATIVE_EVENT(TOKEN_CHANGES, \"Token Changes\", \"Changes\");\n\n  // Parse command line options -----------------------------------------------\n  const std::string description =\n    \"\\n=========================================================================\\n\"\n    \"The Collapsed Gibbs Sampler for the LDA model implements\\n\"\n    \"a highly asynchronous version of parallel LDA in which document\\n\"\n    \"and word counts are maintained in an eventually consistent\\n\"\n    \"manner.\\n\"\n    \"\\n\"\n    \"The standard usage is: \\n\"\n    \"\\t./cgs_lda --dictionary dictionary.txt --corpus doc_word_count.tsv\\n\"\n    \"where dictionary.txt contains: \\n\"\n    \"\\taaa \\n\\taaai \\n\\tabalone \\n\\t   ... \\n\"\n    \"each line number corresponds to wordid (i.e aaa has wordid=0)\\n\\n\"\n    \"and doc_word_count.tsv is formatted <docid> <wordid> <count>:\\n\"\n    \"(where wordid is indexed starting from zero and docid are positive integers)\\n\"\n    \"\\t0\\t0\\t3\\n\"\n    \"\\t0\\t5\\t1\\n\"\n    \"\\t ...\\n\\n\"\n    \"For JSON format, make sure docid are negative integers index starting from -2 \\n\\n\"\n    \"To learn more about the NLP package and its applications visit\\n\\n\"\n    \"\\t\\t http://graphlab.org \\n\\n\"\n    \"Additional Options\";\n  graphlab::command_line_options clopts(description);\n  std::string corpus_dir;\n  std::string dictionary_fname;\n  std::string doc_dir;\n  std::string word_dir;\n  std::string exec_type = \"asynchronous\";\n  std::string format = \"matrix\";\n  \n  clopts.attach_option(\"dictionary\", dictionary_fname,\n                       \"The file containing the list of unique words\");\n  clopts.attach_option(\"engine\", exec_type, \n                       \"The engine type synchronous or asynchronous\");\n  clopts.attach_option(\"corpus\", corpus_dir,\n                       \"The directory or file containing the corpus data.\");\n  clopts.add_positional(\"corpus\");\n  clopts.attach_option(\"ntopics\", NTOPICS,\n                       \"Number of topics to use.\");\n  clopts.attach_option(\"alpha\", ALPHA,\n                       \"The document hyper-prior\");\n  clopts.attach_option(\"beta\", BETA,\n                       \"The word hyper-prior\");\n  clopts.attach_option(\"topk\", TOPK,\n                       \"The number of words to report\");\n  clopts.attach_option(\"interval\", INTERVAL,\n                       \"statistics reporting interval (in seconds)\");\n  clopts.attach_option(\"lik_interval\", LIK_INTERVAL,\n                       \"likelihood reporting interval (in seconds)\");\n  clopts.attach_option(\"max_count\", MAX_COUNT,\n                       \"The maximum number of occurences of a word in a document.\");\n  clopts.attach_option(\"format\", format,\n                       \"Formats: matrix,json,json-gzip\");\n  clopts.attach_option(\"burnin\", BURNIN, \n                       \"The time in second to run until a sample is collected. \"\n                       \"If less than zero the sampler runs indefinitely.\");\n  clopts.attach_option(\"doc_dir\", doc_dir,\n                       \"The output directory to save the final document counts.\");\n  clopts.attach_option(\"word_dir\", word_dir,\n                       \"The output directory to save the final words counts.\");\n\n\n  if(!clopts.parse(argc, argv)) {\n    graphlab::mpi_tools::finalize();\n    return clopts.is_set(\"help\")? EXIT_SUCCESS : EXIT_FAILURE;\n  }\n\n  if(dictionary_fname.empty()) {\n    logstream(LOG_WARNING) << \"No dictionary file was provided.\" << std::endl\n                           << \"Top k words will not be estimated.\" << std::endl;\n  }\n\n  if(corpus_dir.empty()) {\n    logstream(LOG_ERROR) << \"No corpus file was provided.\" << std::endl;\n    return EXIT_FAILURE;\n  }\n\n  // Start the webserver\n  graphlab::launch_metric_server();\n  graphlab::add_metric_server_callback(\"wordclouds\", word_cloud_callback);\n\n\n  ///! Initialize global variables\n  GLOBAL_TOPIC_COUNT.resize(NTOPICS);\n  if(!dictionary_fname.empty()) {\n    const bool success = load_dictionary(dictionary_fname);\n    if(!success) {\n      logstream(LOG_ERROR) << \"Error loading dictionary.\" << std::endl;\n      return EXIT_FAILURE;\n    }\n  }\n\n  if(ALPHA <= 0) {\n    logstream(LOG_ERROR) \n      << \"Alpha must be positive (alpha=\" << ALPHA << \")!\"  << std::endl;\n    return EXIT_FAILURE;\n  }\n\n  if(BETA <= 0) {\n    logstream(LOG_ERROR) \n      << \"Beta must be positive (beta=\" << BETA << \")!\"  << std::endl;\n    return EXIT_FAILURE;\n  }\n   \n  /// Initialize the log_gamma precached calculations.\n  ALPHA_LGAMMA.init(ALPHA, 100000);\n  BETA_LGAMMA.init(BETA, 1000000);\n\n\n  ///! load the graph\n  graph_type graph(dc, clopts);\n  {\n    const bool success = \n      load_and_initialize_graph(dc, graph, corpus_dir, format);\n    if(!success) {\n      logstream(LOG_ERROR) << \"Error loading graph.\" << std::endl;\n      return EXIT_FAILURE;\n    }\n  }\n\n\n  const size_t ntokens = graph.map_reduce_edges<size_t>(count_tokens);\n  dc.cout() << \"Total tokens: \" << ntokens << std::endl;\n\n\n\n  engine_type engine(dc, graph, exec_type, clopts);\n  ///! Add an aggregator\n  if(!DICTIONARY.empty()) {\n    const bool success =\n      engine.add_vertex_aggregator<topk_aggregator>\n      (\"topk\", topk_aggregator::map, topk_aggregator::finalize) &&\n      engine.aggregate_periodic(\"topk\", INTERVAL);\n    ASSERT_TRUE(success);\n  }\n\n  { // Add the Global counts aggregator\n    const bool success =\n      engine.add_vertex_aggregator<factor_type>\n      (\"global_counts\", \n       global_counts_aggregator::map, \n       global_counts_aggregator::finalize) &&\n      engine.aggregate_periodic(\"global_counts\", 5);\n    ASSERT_TRUE(success);\n  }\n  \n  { // Add the likelihood aggregator\n    const bool success =\n      engine.add_vertex_aggregator<likelihood_aggregator>\n      (\"likelihood\", \n       likelihood_aggregator::map, \n       likelihood_aggregator::finalize) &&\n      engine.aggregate_periodic(\"likelihood\", LIK_INTERVAL);\n    ASSERT_TRUE(success);\n  }\n\n  ///! schedule only documents\n  dc.cout() << \"Running The Collapsed Gibbs Sampler\" << std::endl;\n  engine.map_reduce_vertices<graphlab::empty>(signal_only::docs);\n  graphlab::timer timer;\n  // Enable sampling\n  cgs_lda_vertex_program::DISABLE_SAMPLING = false;\n  // Run the engine\n  engine.start();\n  // Finalize the counts\n  cgs_lda_vertex_program::DISABLE_SAMPLING = true;\n  engine.signal_all();\n  engine.start();\n  \n  const double runtime = timer.current_time();\n  dc.cout()\n    << \"----------------------------------------------------------\" << std::endl\n    << \"Final Runtime (seconds):   \" << runtime\n    << std::endl\n    << \"Updates executed: \" << engine.num_updates() << std::endl\n    << \"Update Rate (updates/second): \"\n    << engine.num_updates() / runtime << std::endl;\n  \n  \n  \n  if(!word_dir.empty()) {\n    // save word topic counts\n    const bool gzip_output = false;\n    const bool save_vertices = true;\n    const bool save_edges = false;\n    const size_t threads_per_machine = 2;\n    const bool save_words = true;\n    graph.save(word_dir, count_saver(save_words),\n               gzip_output, save_vertices, \n               save_edges, threads_per_machine);\n  }\n\n  \n  if(!doc_dir.empty()) {\n    // save doc topic counts\n    const bool gzip_output = false;\n    const bool save_vertices = true;\n    const bool save_edges = false;\n    const size_t threads_per_machine = 2;\n    const bool save_words = false;\n    graph.save(doc_dir, count_saver(save_words),\n               gzip_output, save_vertices, \n               save_edges, threads_per_machine);\n\n  }\n\n\n  graphlab::stop_metric_server_on_eof();\n  graphlab::mpi_tools::finalize();\n  return EXIT_SUCCESS;\n\n\n} // end of main\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n", "meta": {"hexsha": "0ff28f76b2f0c58660064509a181539cff17e1aa", "size": 40748, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "toolkits/topic_modeling/cgs_lda.cpp", "max_stars_repo_name": "coreyp1/graphlab", "max_stars_repo_head_hexsha": "637be90021c5f83ab7833ca15c48e76039057969", "max_stars_repo_licenses": ["ECL-2.0", "Apache-2.0"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2017-11-19T11:46:55.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-08T22:45:55.000Z", "max_issues_repo_path": "toolkits/topic_modeling/cgs_lda.cpp", "max_issues_repo_name": "coreyp1/graphlab", "max_issues_repo_head_hexsha": "637be90021c5f83ab7833ca15c48e76039057969", "max_issues_repo_licenses": ["ECL-2.0", "Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "toolkits/topic_modeling/cgs_lda.cpp", "max_forks_repo_name": "coreyp1/graphlab", "max_forks_repo_head_hexsha": "637be90021c5f83ab7833ca15c48e76039057969", "max_forks_repo_licenses": ["ECL-2.0", "Apache-2.0"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2015-12-15T12:12:23.000Z", "max_forks_repo_forks_event_max_datetime": "2019-10-16T16:48:40.000Z", "avg_line_length": 31.1529051988, "max_line_length": 97, "alphanum_fraction": 0.6442524786, "num_tokens": 10358, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5888891451980403, "lm_q2_score": 0.5273165233795671, "lm_q1q2_score": 0.3105309767017957}}
{"text": "#include <algorithm>\n#include <boost/optional.hpp>\n#include <climits>\n#include <cmath>\n#include <cstdio>\n#include <cstring>\n#include <functional>\n#include <iostream>\n#include <limits>\n#include <list>\n#include <numeric>\n#include <queue>\n#include <sstream>\n#include <string>\n#include <tuple>\n#include <type_traits>\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) (a).begin(), (a).end()\n#define AALL(a, n) (a), ((a) + (n))\n#define FILL(a, n) memset((a), n, sizeof(a))\n#define FILLZ(a) FILL(a, 0)\n\nusing namespace std;\n\nusing ll = long long;\nusing VI = vector<int>;\nusing VI2D = vector<vector<int>>;\n\nconst int INF = 2e9;\nconst double EPS = 1e-10;\nconst double PI = acos(-1.0);\n\nconst int dx[] = {-1, 0, 1, 0};\nconst int dy[] = {0, -1, 0, 1};\n\ntemplate <typename T>\nint sign(T x) {\n\treturn x < 0 ? -1 : x > 0 ? 1 : 0;\n}\n\ntemplate <>\nint sign(double x) {\n\treturn x < -EPS ? -1 : x > EPS ? 1 : 0;\n}\n\ntemplate <typename T>\nvoid chmax(T& m, T x) {\n\tm = max(m, x);\n}\n\ntemplate <typename T>\nvoid chmin(T& m, T x) {\n\tm = min(m, x);\n}\n\ntemplate <typename T>\nT square(T x) {\n\treturn x * x;\n}\n\ninline int toInt(string s) {\n\tint v;\n\tistringstream sin(s);\n\tsin >> v;\n\treturn v;\n}\n\ntemplate <long long MOD = 1000000007>\nclass ModInt {\n\tpublic:\n\tlong long n;\n\n\tModInt() : n(0) {}\n\tModInt(long long n) : n(n) {\n\t\twhile(this->n < 0) {\n\t\t\tthis->n += MOD;\n\t\t}\n\t\tthis->n %= MOD;\n\t}\n\n\tlong long get() const { return this->n; }\n\tlong long get_mod() const { return MOD; }\n\n\tModInt inv() const { return pow<ModInt<>>(*this, MOD - 2); }\n\n\tModInt& operator=(const long long rhs) { return *this = ModInt(rhs); }\n\tModInt& operator+=(const ModInt rhs) {\n\t\treturn *this = ModInt(this->n + rhs.n);\n\t}\n\tModInt& operator-=(const ModInt rhs) {\n\t\treturn *this = ModInt(this->n - rhs.n);\n\t}\n\tModInt& operator*=(const ModInt rhs) {\n\t\treturn *this = ModInt(this->n * rhs.n);\n\t}\n\tModInt& operator/=(const ModInt rhs) { return *this *= rhs.inv(); }\n\tbool operator==(const ModInt rhs) const { return this->n == rhs.n; }\n};\n\ntemplate <long long MOD>\nModInt<MOD> operator+(const ModInt<MOD>& lhs, const ModInt<MOD>& rhs) {\n\treturn ModInt<MOD>(lhs) += rhs;\n}\ntemplate <long long MOD>\nModInt<MOD> operator+(const ModInt<MOD>& lhs, const long long& rhs) {\n\treturn ModInt<MOD>(lhs) += rhs;\n}\ntemplate <long long MOD>\nModInt<MOD> operator+(const long long& lhs, const ModInt<MOD>& rhs) {\n\treturn ModInt<MOD>(lhs) += rhs;\n}\n\ntemplate <long long MOD>\nModInt<MOD> operator-(const ModInt<MOD>& lhs, const ModInt<MOD>& rhs) {\n\treturn ModInt<MOD>(lhs) -= rhs;\n}\ntemplate <long long MOD>\nModInt<MOD> operator-(const ModInt<MOD>& lhs, const long long& rhs) {\n\treturn ModInt<MOD>(lhs) -= rhs;\n}\ntemplate <long long MOD>\nModInt<MOD> operator-(const long long& lhs, const ModInt<MOD>& rhs) {\n\treturn ModInt<MOD>(lhs) -= rhs;\n}\n\ntemplate <long long MOD>\nModInt<MOD> operator*(const ModInt<MOD>& lhs, const ModInt<MOD>& rhs) {\n\treturn ModInt<MOD>(lhs) *= rhs;\n}\ntemplate <long long MOD>\nModInt<MOD> operator*(const ModInt<MOD>& lhs, const long long& rhs) {\n\treturn ModInt<MOD>(lhs) *= rhs;\n}\ntemplate <long long MOD>\nModInt<MOD> operator*(const long long& lhs, const ModInt<MOD>& rhs) {\n\treturn ModInt<MOD>(lhs) *= rhs;\n}\n\ntemplate <long long MOD>\nModInt<MOD> operator/(const ModInt<MOD>& lhs, const ModInt<MOD>& rhs) {\n\treturn ModInt<MOD>(lhs) /= rhs;\n}\ntemplate <long long MOD>\nModInt<MOD> operator/(const ModInt<MOD>& lhs, const long long& rhs) {\n\treturn ModInt<MOD>(lhs) /= rhs;\n}\ntemplate <long long MOD>\nModInt<MOD> operator/(const long long& lhs, const ModInt<MOD>& rhs) {\n\treturn ModInt<MOD>(lhs) /= rhs;\n}\n\ntemplate <long long MOD>\nstd::ostream& operator<<(std::ostream& os, const ModInt<MOD>& x) {\n\treturn os << x.n;\n}\n\ntemplate <long long MOD>\nstd::istream& operator>>(std::istream& is, const ModInt<MOD>& x) {\n\treturn is >> x.n;\n}\n\n// 繰り返し2乗法\n// 計算量 O(logn)\ntemplate <typename T>\nT pow(T a, int n) {\n\tT ret = 1;\n\twhile(n != 0) {\n\t\tif(n % 2) {\n\t\t\tret *= a;\n\t\t}\n\t\ta *= a;\n\t\tn /= 2;\n\t}\n\treturn ret;\n}\n\n// 二項係数\n// 計算量 O(r)\ntemplate <typename T>\nT comb(long long n, long long r) {\n\tif(n < r || n < 0 || r < 0) {\n\t\treturn T(0);\n\t}\n\tT ret = 1;\n\tr = std::min(r, n - r);\n\tfor(int i = 0; i < r; i++) {\n\t\tret *= (n - i);\n\t\tret /= i + 1;\n\t}\n\treturn ret;\n}\n\nint main() {\n\tint n, a, b;\n\tcin >> n >> a >> b;\n\tauto all = pow<ModInt<>>(2, n) - 1;\n\tcout << all - comb<ModInt<>>(n, a) - comb<ModInt<>>(n, b) << endl;\n\treturn 0;\n}", "meta": {"hexsha": "b1d51c4a317c5ffd18a938ab9e035495609288f9", "size": 4547, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "AtCoder/ABC156/D2.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/ABC156/D2.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/ABC156/D2.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": 22.2892156863, "max_line_length": 76, "alphanum_fraction": 0.61952936, "num_tokens": 1535, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5273165085228825, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.31053096034356836}}
{"text": "#include \"truncated-svd-solver/linear-algebra-helpers.h\"\n\n#include <algorithm>\n#include <cmath>\n\n#include <cholmod.h>\n#include <Eigen/Dense>\n#include <glog/logging.h>\n#include <spqr.hpp>\n#include <SuiteSparseQR.hpp>\n\nnamespace truncated_svd_solver {\n\ncholmod_sparse* columnSubmatrix(cholmod_sparse* A, std::ptrdiff_t\n    col_start_idx, std::ptrdiff_t col_end_idx, cholmod_common* cholmod) {\n  CHECK_NOTNULL(A);\n  CHECK_NOTNULL(cholmod);\n\n  CHECK_GE(col_end_idx, col_start_idx);\n  CHECK_LT(col_end_idx, static_cast<std::ptrdiff_t>(A->ncol));\n  CHECK_GE(col_start_idx, 0);\n\n  const std::ptrdiff_t num_indices = col_end_idx - col_start_idx + 1;\n  std::ptrdiff_t* col_indices = new std::ptrdiff_t[num_indices];\n  for (std::ptrdiff_t j = col_start_idx; j <= col_end_idx; ++j) {\n    col_indices[j - col_start_idx] = j;\n  }\n\n  cholmod_sparse* A_sub = cholmod_l_submatrix(A, nullptr, -1, col_indices,\n    num_indices, 1, 1, cholmod);\n  delete [] col_indices;\n  CHECK(A_sub != nullptr) << \"cholmod_l_submatrix failed.\";\n\n  return A_sub;\n}\n\ncholmod_sparse* rowSubmatrix(cholmod_sparse* A, std::ptrdiff_t row_start_idx,\n    std::ptrdiff_t row_end_idx, cholmod_common* cholmod) {\n  CHECK_NOTNULL(A);\n  CHECK_NOTNULL(cholmod);\n\n  CHECK_GE(row_end_idx, row_start_idx);\n  CHECK_LT(row_end_idx, static_cast<std::ptrdiff_t>(A->nrow));\n  CHECK_GE(row_start_idx, 0);\n\n  const std::ptrdiff_t num_indices = row_end_idx - row_start_idx + 1;\n  std::ptrdiff_t* row_indices = new std::ptrdiff_t[num_indices];\n  for (std::ptrdiff_t i = row_start_idx; i <= row_end_idx; ++i){\n    row_indices[i - row_start_idx] = i;\n  }\n\n  cholmod_sparse* A_sub = cholmod_l_submatrix(A, row_indices, num_indices,\n    nullptr, -1, 1, 1, cholmod);\n  delete [] row_indices;\n  CHECK(A_sub != nullptr) << \"cholmod_l_submatrix failed.\";\n\n  return A_sub;\n}\n\ndouble colNorm(const cholmod_sparse* A, std::ptrdiff_t col_idx) {\n  CHECK_NOTNULL(A);\n  CHECK_GE(col_idx, 0);\n  CHECK_LT(col_idx, static_cast<std::ptrdiff_t>(A->ncol));\n\n  const std::ptrdiff_t* col_ptr =\n    reinterpret_cast<const std::ptrdiff_t*>(A->p);\n  const double* values = reinterpret_cast<const double*>(A->x);\n  const std::ptrdiff_t p = col_ptr[col_idx];\n  const std::ptrdiff_t num_elements = col_ptr[col_idx + 1] - p;\n\n  double norm = 0.0;\n  for (std::ptrdiff_t i = 0; i < num_elements; ++i) {\n    norm += values[p + i] * values[p + i];\n  }\n  return std::sqrt(norm);\n}\n\ncholmod_dense* columnScalingMatrix(cholmod_sparse* A, cholmod_common*\n    cholmod, double eps) {\n  CHECK_NOTNULL(A);\n  CHECK_NOTNULL(cholmod);\n  CHECK_GT(eps, 0.0);\n\n  cholmod_dense* G = cholmod_l_allocate_dense(A->ncol, 1, A->ncol,\n    CHOLMOD_REAL, cholmod);\n  CHECK(G != nullptr) << \"cholmod_l_allocate_dense failed.\";\n\n  const double norm_tolerance = std::sqrt(A->nrow * eps);\n  double* values = reinterpret_cast<double*>(G->x);\n  for (std::ptrdiff_t col_idx = 0;\n      col_idx < static_cast<std::ptrdiff_t>(A->ncol);\n      ++col_idx) {\n    const double norm = colNorm(A, col_idx);\n    if (norm < norm_tolerance) {\n      values[col_idx] = 0.0;\n    } else {\n      values[col_idx] = 1.0 / norm;\n    }\n  }\n  return G;\n}\n\nvoid cholmodSparseToEigenDenseCopy(const cholmod_sparse* in,\n    Eigen::MatrixXd& out) {\n  CHECK_NOTNULL(in);\n  out.setZero(in->nrow, in->ncol);\n\n  const std::ptrdiff_t* row_ind =\n    reinterpret_cast<const std::ptrdiff_t*>(in->i);\n  const std::ptrdiff_t* col_ptr =\n    reinterpret_cast<const std::ptrdiff_t*>(in->p);\n  const double* values = reinterpret_cast<const double*>(in->x);\n  for (std::ptrdiff_t col_idx = 0;\n       col_idx < static_cast<std::ptrdiff_t>(in->ncol); ++col_idx)\n    for (std::ptrdiff_t val_idx = col_ptr[col_idx];\n         val_idx < col_ptr[col_idx + 1]; ++val_idx) {\n      out(row_ind[val_idx], col_idx) = values[val_idx];\n      if (in->stype && col_idx != row_ind[val_idx]) {\n        out(col_idx, row_ind[val_idx]) = values[val_idx];\n      }\n    }\n}\n\nvoid eigenDenseToCholmodDenseView(const Eigen::VectorXd& in, cholmod_dense*\n    out) {\n  CHECK_NOTNULL(out);\n\n  out->nrow = in.size();\n  out->ncol = 1;\n  out->nzmax = in.size();\n  out->d = in.size();\n  out->x = reinterpret_cast<void*>(const_cast<double*>(in.data()));\n  out->z = nullptr;\n  out->xtype = CHOLMOD_REAL;\n  out->dtype = CHOLMOD_DOUBLE;\n}\n\ncholmod_dense* eigenDenseToCholmodDenseCopy(const Eigen::VectorXd& in,\n    cholmod_common* cholmod) {\n  CHECK_NOTNULL(cholmod);\n  cholmod_dense* out = cholmod_l_allocate_dense(in.size(), 1, in.size(),\n    CHOLMOD_REAL, cholmod);\n  CHECK(out != nullptr) << \"cholmod_l_allocate_dense failed.\";\n\n  double* out_val = reinterpret_cast<double*>(out->x);\n  const double* in_val = in.data();\n  std::copy(in_val, in_val + in.size(), out_val);\n  return out;\n}\n\nvoid cholmodDenseToEigenDenseCopy(const cholmod_dense* in, Eigen::VectorXd&\n    out) {\n  CHECK_NOTNULL(in);\n  out.resize(in->nrow);\n  const double* in_val = reinterpret_cast<const double*>(in->x);\n  std::copy(in_val, in_val + in->nrow, out.data());\n}\n\ncholmod_sparse* eigenDenseToCholmodSparseCopy(const Eigen::MatrixXd& A,\n    cholmod_common* cholmod, double eps) {\n  CHECK_NOTNULL(cholmod);\n  CHECK_GT(eps, 0.0);\n\n  size_t nzmax = 0;\n  for (std::ptrdiff_t i = 0; i < A.rows(); ++i) {\n    for (std::ptrdiff_t j = 0; j < A.cols(); ++j) {\n      if (std::fabs(A(i, j)) > eps) {\n        nzmax++;\n      }\n    }\n  }\n\n  cholmod_sparse* A_cholmod = cholmod_l_allocate_sparse(A.rows(), A.cols(),\n    nzmax, 1, 1, 0, CHOLMOD_REAL, cholmod);\n  CHECK(A_cholmod != nullptr) << \"cholmod_l_allocate_sparse failed.\";\n\n  std::ptrdiff_t* row_ind = reinterpret_cast<std::ptrdiff_t*>(A_cholmod->i);\n  std::ptrdiff_t* col_ptr = reinterpret_cast<std::ptrdiff_t*>(A_cholmod->p);\n  double* values = reinterpret_cast<double*>(A_cholmod->x);\n  std::ptrdiff_t row_it = 0;\n  std::ptrdiff_t col_it = 1;\n  for (std::ptrdiff_t c = 0; c < A.cols(); ++c) {\n    for (std::ptrdiff_t r = 0; r < A.rows(); ++r)\n      if (std::fabs(A(r, c)) > eps) {\n        values[row_it] = A(r, c);\n        row_ind[row_it] = r;\n        row_it++;\n      }\n    col_ptr[col_it] = row_it;\n    col_it++;\n  }\n  return A_cholmod;\n}\n\nstd::ptrdiff_t estimateNumericalRank(const Eigen::VectorXd& singular_values,\n                                     double tolerance) {\n  CHECK_GE(tolerance, 0.0);\n\n  std::ptrdiff_t numerical_rank = singular_values.size();\n  for (std::ptrdiff_t i = singular_values.size() - 1; i >= 0; --i) {\n    if (singular_values(i) > tolerance) {\n      // Assumes that the singular values are ordered.\n      break;\n    } else {\n      --numerical_rank;\n    }\n  }\n  return numerical_rank;\n}\n\ndouble rankTol(const Eigen::VectorXd& singular_values, double eps) {\n  CHECK_GT(singular_values.rows(), 0) << \"Empty singular values vector.\";\n  CHECK_GT(eps, 0.0);\n  return singular_values(0) * eps * singular_values.size();\n}\n\ndouble qrTol(cholmod_sparse* A, cholmod_common* cholmod, double eps) {\n  CHECK_NOTNULL(A);\n  CHECK_NOTNULL(cholmod);\n  CHECK_GT(eps, 0.0);\n  return 20.0 * static_cast<double>(A->nrow + A->ncol) * eps *\n    spqr_maxcolnorm<double>(A, cholmod);\n}\n\ndouble svGap(const Eigen::VectorXd& singular_values, std::ptrdiff_t rank) {\n  CHECK_LE(rank, singular_values.rows());\n  CHECK_GE(rank, 0);\n\n  if (rank == 0) {\n    return 0.0;\n  } else if (rank < singular_values.size()) {\n    return singular_values(rank - 1) / singular_values(rank);\n  }\n  return std::numeric_limits<double>::infinity();\n}\n\nvoid reduceLeftHandSide(SuiteSparseQR_factorization<double>* factor,\n    cholmod_sparse* A_rt, cholmod_sparse** Omega, cholmod_sparse** A_rtQ,\n    cholmod_common* cholmod) {\n  CHECK_NOTNULL(A_rt);\n  CHECK_NOTNULL(cholmod);\n  CHECK_NOTNULL(Omega);\n\n  // Handle the special case where the QR part is empty.\n  if (factor == nullptr) {\n    // NO QR part!\n    *Omega = cholmod_l_aat(A_rt, nullptr, 0, 1, cholmod);\n    return;\n  } else {\n    CHECK(factor->QRsym != nullptr) << \"Run symbolic factorization first.\";\n    CHECK(factor->QRnum != nullptr) << \"Run QR decomposition first.\";\n  }\n  CHECK_NOTNULL(factor);\n  CHECK_NOTNULL(A_rtQ);\n\n  cholmod_sparse* A_rtQFull = SuiteSparseQR_qmult<double>(SPQR_XQ, factor,\n    A_rt, cholmod);\n  CHECK(A_rtQFull != nullptr) << \"SuiteSparseQR_qmult failed.\";\n\n\n  *A_rtQ = columnSubmatrix(A_rtQFull, 0, factor->QRsym->n - 1, cholmod);\n  cholmod_l_free_sparse(&A_rtQFull, cholmod);\n\n  cholmod_sparse* A_rtQ2 = cholmod_l_aat(*A_rtQ, nullptr, 0, 1, cholmod);\n  CHECK(A_rtQ2 != nullptr) << \"cholmod_l_aat failed.\";\n  A_rtQ2->stype = 1;\n\n  cholmod_sparse* A_rt2 = cholmod_l_aat(A_rt, nullptr, 0, 1, cholmod);\n  CHECK(A_rt2 != nullptr) << \"cholmod_l_aat failed.\";\n  A_rt2->stype = 1;\n\n  double alpha[2];\n  alpha[0] = 1.0;\n  double beta[2];\n  beta[0] = -1.0;\n\n  *Omega = cholmod_l_add(A_rt2, A_rtQ2, alpha, beta, 1, 1, cholmod);\n  CHECK(*Omega != nullptr) << \"cholmod_l_add failed.\";\n\n  cholmod_l_free_sparse(&A_rt2, cholmod);\n  cholmod_l_free_sparse(&A_rtQ2, cholmod);\n}\n\ncholmod_dense* reduceRightHandSide(SuiteSparseQR_factorization<double>*\n    factor, cholmod_sparse* A_rt, cholmod_sparse* A_rtQ, cholmod_dense* b,\n    cholmod_common* cholmod) {\n  CHECK_NOTNULL(A_rt);\n  CHECK_NOTNULL(b);\n  CHECK_NOTNULL(cholmod);\n\n  // Handle the special case where the QR part is empty.\n  if (factor == nullptr) {\n    // NO QR part!\n    double one = 1, zero = 0;\n    cholmod_dense* b_reduced = cholmod_l_allocate_dense(\n        A_rt->nrow, 1, A_rt->nrow, CHOLMOD_REAL, cholmod);\n    CHECK(b_reduced != nullptr) << \"cholmod_l_allocate_dense failed.\";\n\n    const int status = cholmod_l_sdmult(A_rt, 0, &one, &zero, b, b_reduced,\n                                        cholmod);\n    CHECK(status) << \"cholmod_l_sdmult failed\";\n    return b_reduced;\n  } else {\n    CHECK(factor->QRsym != nullptr) << \"Run symbolic factorization first.\";\n    CHECK(factor->QRnum != nullptr) << \"Run QR decomposition first.\";\n  }\n  CHECK_NOTNULL(factor);\n  CHECK_NOTNULL(A_rtQ);\n\n  cholmod_sparse* b_sparse = cholmod_l_dense_to_sparse(b, 1, cholmod);\n  CHECK(b_sparse != nullptr) << \"cholmod_l_dense_to_sparse failed.\";\n\n  cholmod_sparse* A_rtb = cholmod_l_ssmult(A_rt, b_sparse, 0, 1, 1, cholmod);\n  CHECK(A_rtb != nullptr) << \"cholmod_l_ssmult failed.\";\n\n  cholmod_sparse* QtbFull = SuiteSparseQR_qmult<double>(SPQR_QTX, factor,\n    b_sparse, cholmod);\n  CHECK(QtbFull != nullptr) << \"SuiteSparseQR_qmult failed.\";\n  cholmod_l_free_sparse(&b_sparse, cholmod);\n\n  cholmod_sparse* Qtb;\n  Qtb = rowSubmatrix(QtbFull, 0, factor->QRsym->n - 1, cholmod);\n  cholmod_l_free_sparse(&QtbFull, cholmod);\n\n  cholmod_sparse* A_rtQQtb = cholmod_l_ssmult(A_rtQ, Qtb, 0, 1, 1, cholmod);\n  CHECK(A_rtQQtb != nullptr) << \"cholmod_l_ssmult failed.\";\n  cholmod_l_free_sparse(&Qtb, cholmod);\n\n  double alpha[2];\n  alpha[0] = 1.0;\n  double beta[2];\n  beta[0] = -1.0;\n\n  cholmod_sparse* b_reduced_sparse = cholmod_l_add(A_rtb, A_rtQQtb, alpha,\n    beta, 1, 1, cholmod);\n  CHECK(b_reduced_sparse != nullptr) << \"cholmod_l_add failed.\";\n  cholmod_l_free_sparse(&A_rtb, cholmod);\n  cholmod_l_free_sparse(&A_rtQQtb, cholmod);\n\n  cholmod_dense* b_reduced = cholmod_l_sparse_to_dense(b_reduced_sparse,\n    cholmod);\n  CHECK(b_reduced != nullptr) << \"cholmod_l_sparse_to_dense failed.\";\n  cholmod_l_free_sparse(&b_reduced_sparse, cholmod);\n  return b_reduced;\n}\n\nvoid analyzeSVD(const cholmod_sparse* Omega, Eigen::VectorXd& sv,\n    Eigen::MatrixXd& U, Eigen::MatrixXd& V) {\n  CHECK_NOTNULL(Omega);\n\n  Eigen::MatrixXd OmegaDense;\n  cholmodSparseToEigenDenseCopy(Omega, OmegaDense);\n  const Eigen::JacobiSVD<Eigen::MatrixXd> svd(OmegaDense,\n    Eigen::ComputeThinU | Eigen::ComputeThinV);\n  U = svd.matrixU();\n  V = svd.matrixV();\n  sv = svd.singularValues();\n}\n\nvoid solveSVD(const cholmod_dense* b, const Eigen::VectorXd& sv, const\n    Eigen::MatrixXd& U, const Eigen::MatrixXd& V, std::ptrdiff_t rank,\n    Eigen::VectorXd& x) {\n  CHECK_NOTNULL(b);\n  CHECK_LE(rank, V.cols());\n  CHECK_EQ(V.cols(), sv.rows());\n  CHECK_EQ(U.rows(), static_cast<std::ptrdiff_t>(b->nrow));\n\n  Eigen::Map<const Eigen::VectorXd> b_eigen(\n    reinterpret_cast<const double*>(b->x), b->nrow);\n  x = V.leftCols(rank) * sv.head(rank).asDiagonal().inverse() *\n    U.leftCols(rank).adjoint() * b_eigen;\n}\n\ncholmod_dense* solveQR(SuiteSparseQR_factorization<double>* factor,\n    cholmod_dense* b, cholmod_sparse* A_r, const Eigen::VectorXd& x_r,\n    cholmod_common* cholmod) {\n  CHECK_NOTNULL(factor);\n  CHECK(factor->QRsym != nullptr) << \"Run symbolic factorization first.\";\n  CHECK(factor->QRnum != nullptr) << \"Run QR decomposition first.\";\n  CHECK_NOTNULL(b);\n  CHECK_NOTNULL(cholmod);\n\n  cholmod_dense* QtbmA_rx_r = nullptr;\n  if (A_r != nullptr) {\n    CHECK_EQ(x_r.size(), static_cast<int>(A_r->ncol))\n      << \"Dimension mismatch between x_r and A_r.\";\n\n    cholmod_dense x_r_cholmod;\n    eigenDenseToCholmodDenseView(x_r, &x_r_cholmod);\n    cholmod_dense* A_rx_r = cholmod_l_allocate_dense(A_r->nrow, 1, A_r->nrow,\n      CHOLMOD_REAL, cholmod);\n    CHECK(A_rx_r != nullptr) << \"cholmod_l_allocate_dense failed.\";\n\n    double alpha[2];\n    alpha[0] = 1.0;\n    double beta[2];\n    beta[0] = 0.0;\n    const bool success = cholmod_l_sdmult(A_r, 0, alpha, beta, &x_r_cholmod,\n                                          A_rx_r, cholmod);\n    CHECK(success) << \"cholmod_l_sdmult failed.\";\n\n    Eigen::Map<const Eigen::VectorXd> bEigen(\n      reinterpret_cast<const double*>(b->x), b->nrow);\n    Eigen::Map<const Eigen::VectorXd> A_rx_rEigen(\n      reinterpret_cast<const double*>(A_rx_r->x), A_rx_r->nrow);\n    const Eigen::VectorXd bmA_rx_rEigen = bEigen - A_rx_rEigen;\n    cholmod_l_free_dense(&A_rx_r, cholmod);\n    cholmod_dense bmA_rx_r;\n    eigenDenseToCholmodDenseView(bmA_rx_rEigen, &bmA_rx_r);\n    QtbmA_rx_r = SuiteSparseQR_qmult<double>(SPQR_QTX, factor, &bmA_rx_r,\n                                             cholmod);\n  } else {\n    QtbmA_rx_r = SuiteSparseQR_qmult<double>(SPQR_QTX, factor, b, cholmod);\n  }\n  CHECK(QtbmA_rx_r != nullptr) << \"SuiteSparseQR_qmult failed.\";\n\n  cholmod_dense* x_l = SuiteSparseQR_solve<double>(SPQR_RETX_EQUALS_B,\n    factor, QtbmA_rx_r, cholmod);\n  CHECK(x_l != nullptr) << \"SuiteSparseQR_solve failed.\";\n  cholmod_l_free_dense(&QtbmA_rx_r, cholmod);\n  return x_l;\n}\n\n}  // namespace truncated_svd_solver\n", "meta": {"hexsha": "3d7263142eaf2ae8b3c4d054f4e6d7b584d25d73", "size": 14138, "ext": "cc", "lang": "C++", "max_stars_repo_path": "truncated_svd_solver/src/linear-algebra-helpers.cc", "max_stars_repo_name": "ethz-asl/truncated_svd_solver", "max_stars_repo_head_hexsha": "12772b2e3a0282e77022f12f67497401ca020f57", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 13.0, "max_stars_repo_stars_event_min_datetime": "2017-02-06T18:05:24.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-30T01:56:49.000Z", "max_issues_repo_path": "truncated_svd_solver/src/linear-algebra-helpers.cc", "max_issues_repo_name": "ethz-asl/truncated_svd_solver", "max_issues_repo_head_hexsha": "12772b2e3a0282e77022f12f67497401ca020f57", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2017-02-14T16:46:52.000Z", "max_issues_repo_issues_event_max_datetime": "2017-02-14T16:46:52.000Z", "max_forks_repo_path": "truncated_svd_solver/src/linear-algebra-helpers.cc", "max_forks_repo_name": "ethz-asl/truncated_svd_solver", "max_forks_repo_head_hexsha": "12772b2e3a0282e77022f12f67497401ca020f57", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2018-12-27T09:15:14.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-11T23:22:28.000Z", "avg_line_length": 33.2658823529, "max_line_length": 77, "alphanum_fraction": 0.6825576461, "num_tokens": 4300, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6113819732941511, "lm_q2_score": 0.5078118642792044, "lm_q1q2_score": 0.3104670196452017}}
{"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_MAC_SIPHASH_FUNCTIONS_HPP\n#define CRYPTO3_MAC_SIPHASH_FUNCTIONS_HPP\n\n#include <boost/integer.hpp>\n#include <boost/container/static_vector.hpp>\n\n#include <nil/crypto3/mac/detail/siphash/siphash_policy.hpp>\n\nnamespace nil {\n    namespace crypto3 {\n        namespace mac {\n            namespace detail {\n                template<std::size_t Rounds, std::size_t FinalRounds>\n                struct siphash_functions : public siphash_policy<Rounds, FinalRounds> {\n                    typedef siphash_policy<Rounds, FinalRounds> policy_type;\n\n                    constexpr static const std::size_t rounds = policy_type::rounds;\n                    constexpr static const std::size_t final_rounds = policy_type::final_rounds;\n\n                    constexpr static const std::size_t word_bits = policy_type::word_bits;\n                    typedef typename policy_type::word_type word_type;\n\n                    constexpr static const std::size_t key_bits = policy_type::key_bits;\n                    constexpr static const std::size_t key_words = policy_type::key_words;\n                    typedef typename policy_type::key_type key_type;\n\n                    constexpr static const std::size_t 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                    template<std::size_t InternalRounds>\n                    void sip_rounds(key_schedule_type& V, word_type M) {\n                        word_type V0 = V[0], V1 = V[1], V2 = V[2], V3 = V[3];\n\n                        V3 ^= M;\n\n                        for (size_t i = 0; i != InternalRounds; ++i) {\n                            V0 += V1;\n                            V2 += V3;\n                            V1 = policy_type::template rotl<13>(V1);\n                            V3 = policy_type::template rotl<16>(V3);\n                            V1 ^= V0;\n                            V3 ^= V2;\n                            V0 = policy_type::template rotl<32>(V0);\n\n                            V2 += V1;\n                            V0 += V3;\n                            V1 = policy_type::template rotl<17>(V1);\n                            V3 = policy_type::template rotl<21>(V3);\n                            V1 ^= V2;\n                            V3 ^= V0;\n                            V2 = policy_type::template rotl<32>(V2);\n                        }\n                        V0 ^= M;\n\n                        V[0] = V0;\n                        V[1] = V1;\n                        V[2] = V2;\n                        V[3] = V3;\n                    }\n                };\n            }    // namespace detail\n        }        // namespace mac\n    }            // namespace crypto3\n}    // namespace nil\n\n#endif    // CRYPTO3_SIPHASH_POLICY_HPP\n", "meta": {"hexsha": "9e7c82b393ffce9d7f0899590fbbf795d4ff2e3d", "size": 4213, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "snark-logic/libs-source/mac/include/nil/crypto3/mac/detail/siphash/siphash_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": "snark-logic/libs-source/mac/include/nil/crypto3/mac/detail/siphash/siphash_functions.hpp", "max_issues_repo_name": "podlodkin/podlodkin-freeton-year-control", "max_issues_repo_head_hexsha": "e394c11f2414804d2fbde93a092ae589d4359739", "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": "snark-logic/libs-source/mac/include/nil/crypto3/mac/detail/siphash/siphash_functions.hpp", "max_forks_repo_name": "podlodkin/podlodkin-freeton-year-control", "max_forks_repo_head_hexsha": "e394c11f2414804d2fbde93a092ae589d4359739", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-08-31T06:27:19.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-31T06:27:19.000Z", "avg_line_length": 45.7934782609, "max_line_length": 108, "alphanum_fraction": 0.5454545455, "num_tokens": 849, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7090191214879992, "lm_q2_score": 0.4378234991142019, "lm_q1q2_score": 0.3104252327087532}}
{"text": "//Machine-generated by miind.py. Edit at your own risk.\n\n#include <boost/timer/timer.hpp>\n#include <GeomLib.hpp>\n#include <MPILib/include/MPINetworkCode.hpp>\n#include <MPILib/include/RateAlgorithmCode.hpp>\n#include <MPILib/include/SimulationRunParameter.hpp>\n#include <MPILib/include/report/handler/RootReportHandler.hpp>\n#include <MPILib/include/WilsonCowanAlgorithm.hpp>\n#include <MPILib/include/PersistantAlgorithm.hpp>\n#include <MPILib/include/DelayAlgorithmCode.hpp>\n#include <MPILib/include/RateFunctorCode.hpp>\n\ntypedef MPILib::MPINetwork<double, MPILib::utilities::CircularDistribution> Network;\n\nint main(int argc, char *argv[]) {\n    Network network;\n    boost::timer::auto_cpu_timer t;\n\n#ifdef ENABLE_MPI\n    // initialise the mpi environment this cannot be forwarded to a class\n    boost::mpi::environment env(argc, argv);\n#endif\n\n    try {\t// generating algorithms\n        const MPILib::Time t_mem_0 = 50e-3;\n        const double f_noise_0 = 1.0;\n        MPILib::Rate f_max_0 = 10.0;\n        MPILib::Rate I_ext_0 = 0;\n        MPILib::WilsonCowanParameter  par_wil_0(t_mem_0,f_max_0,f_noise_0,I_ext_0);\n        MPILib::WilsonCowanAlgorithm alg_wc_0(par_wil_0);\n        MPILib::RateAlgorithm<double> rate_alg_1(100.0);\n        // generating nodes\n        MPILib::NodeId id_0 = network.addNode(alg_wc_0,MPILib::EXCITATORY_GAUSSIAN);\n        MPILib::NodeId id_1 = network.addNode(rate_alg_1,MPILib::EXCITATORY_GAUSSIAN);\n        // generating connections\n        double con_1_0(0.1);\n        network.makeFirstInputOfSecond(id_1,id_0,con_1_0);\n        // generation simulation parameter\n        const MPILib::Time tmin = 0;\n        const MPILib::Time tmax = 0.3;\n        const MPILib::Rate fmin = 0;\n        const MPILib::Rate fmax = 10;\n        const MPILib::Potential statemin = 0;\n        const MPILib::Potential statemax = 0.02;\n        const MPILib::Potential densemin = 0;\n        const MPILib::Potential densemax = 250;\n        MPILib::CanvasParameter par_canvas(tmin,tmax,fmin,fmax,statemin,statemax,densemin,densemax);\n\n        MPILib::report::handler::RootReportHandler handler(\"wilsoncowan\",true,true, par_canvas);\n        handler.addNodeToCanvas(id_0);\n        SimulationRunParameter par_run( handler,1000000,0,0.3,1e-03,1e-03,\"wilson.log\",1e-03);\n        network.configureSimulation(par_run);\n        network.evolve();\n    } catch(std::exception exc) {\n        std::cout << exc.what() << std::endl;\n#ifdef ENABLE_MPI\n        //Abort the MPI environment in the correct way :\n        env.abort(1);\n#endif\n    }\n\n    MPILib::utilities::MPIProxy().barrier();\n    t.stop();\n    if (MPILib::utilities::MPIProxy().getRank() == 0) {\n\n        std::cout << \"Overall time spend\\n\";\n        t.report();\n    }\n    return 0;\n}\n", "meta": {"hexsha": "9d219ff081d5775b8d98df85feb8a4e002ecc6e0", "size": 2734, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "apps/BasicDemos/wilsoncowan.cpp", "max_stars_repo_name": "dekamps/miind", "max_stars_repo_head_hexsha": "4b321c62c2bd27eb0d5d8336a16a9e840ba63856", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 13.0, "max_stars_repo_stars_event_min_datetime": "2015-09-15T17:28:25.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T20:26:47.000Z", "max_issues_repo_path": "apps/BasicDemos/wilsoncowan.cpp", "max_issues_repo_name": "dekamps/miind", "max_issues_repo_head_hexsha": "4b321c62c2bd27eb0d5d8336a16a9e840ba63856", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 41.0, "max_issues_repo_issues_event_min_datetime": "2015-08-25T07:50:55.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-21T16:20:37.000Z", "max_forks_repo_path": "apps/BasicDemos/wilsoncowan.cpp", "max_forks_repo_name": "dekamps/miind", "max_forks_repo_head_hexsha": "4b321c62c2bd27eb0d5d8336a16a9e840ba63856", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2015-09-14T20:52:07.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-08T12:18:18.000Z", "avg_line_length": 37.9722222222, "max_line_length": 100, "alphanum_fraction": 0.685442575, "num_tokens": 784, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6513548782017745, "lm_q2_score": 0.476579651063676, "lm_q1q2_score": 0.3104224805720249}}
{"text": "/*ckwg +29\n * Copyright 2017 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#include <vital/types/homography.h>\n\n#include <Eigen/Core>\n\n#include <pybind11/pybind11.h>\n#include <pybind11/eigen.h>\n\nnamespace py=pybind11;\nnamespace kwiver {\nnamespace vital  {\nnamespace python {\n\nclass PyHomographyBase\n{\n\n  public:\n\n    virtual ~PyHomographyBase() = default;\n\n    virtual char get_type() {return '0';};\n    virtual py::object get_matrix() {return py::none();};\n\n    virtual py::object inverse() {return py::none();};\n    virtual py::object map(py::object) {return py::none();};\n    virtual py::object normalize() {return py::none();};\n\n    bool operator==(std::shared_ptr<PyHomographyBase> &);\n    bool operator!=(std::shared_ptr<PyHomographyBase> &other) {return !(*this == other);};\n    virtual std::shared_ptr<PyHomographyBase> operator*(std::shared_ptr<PyHomographyBase> &) {return std::shared_ptr<PyHomographyBase>();};\n};\n\nclass PyHomographyD\n: public PyHomographyBase\n{\n  kwiver::vital::homography_<double> homog;\n\n  public:\n\n    PyHomographyD() {};\n    PyHomographyD(Eigen::Matrix<double, 3, 3> mat) : homog(kwiver::vital::homography_<double>(mat)) {};\n    PyHomographyD(kwiver::vital::homography_<double> mat) : homog(mat) {};\n\n    char get_type() {return 'd';};\n    py::object get_matrix() { return py::cast<Eigen::Matrix<double, 3, 3>>(homog.get_matrix()); };\n\n    py::object inverse();\n    py::object map(py::object);\n    py::object normalize();\n\n    std::shared_ptr<PyHomographyBase> operator*(std::shared_ptr<PyHomographyBase> &);\n};\n\nclass PyHomographyF\n: public PyHomographyBase\n{\n  kwiver::vital::homography_<float> homog;\n\n  public:\n\n    PyHomographyF() {};\n    PyHomographyF(Eigen::Matrix<float, 3, 3> mat) : homog(kwiver::vital::homography_<float>(mat)) {};\n    PyHomographyF(kwiver::vital::homography_<float> mat) : homog(mat) {};\n\n    char get_type() {return 'f';};\n    py::object get_matrix() { return py::cast<Eigen::Matrix<float, 3, 3>>(homog.get_matrix()); };\n\n    py::object inverse();\n    py::object map(py::object);\n    py::object normalize();\n\n    std::shared_ptr<PyHomographyBase> operator*(std::shared_ptr<PyHomographyBase> &);\n};\n\npy::object\nPyHomographyD\n::inverse()\n{\n  auto new_homog = this->homog.inverse();\n  auto new_matrix = new_homog->matrix();\n  return py::cast<Eigen::Matrix<double, 3, 3>>(new_matrix);\n}\n\npy::object\nPyHomographyD\n::map(py::object p_obj)\n{\n  auto p = p_obj.cast<Eigen::Matrix<double,2,1>>();\n  auto new_matrix = this->homog.map_point(p);\n  return py::cast<Eigen::Matrix<double, 2, 1>>(new_matrix);\n}\n\npy::object\nPyHomographyD\n::normalize()\n{\n  auto new_homog = this->homog.normalize();\n  auto new_matrix = new_homog->matrix();\n  return py::cast<Eigen::Matrix<double, 3, 3>>(new_matrix);\n}\n\nstd::shared_ptr<PyHomographyBase>\nPyHomographyD::\noperator*(std::shared_ptr<PyHomographyBase> &other)\n{\n  auto mat = other->get_matrix().cast<Eigen::Matrix<double,3,3>>(); //this part is a bit silly, could be done better\n  auto other_homog = kwiver::vital::homography_<double>(mat);\n  return std::shared_ptr<PyHomographyBase>(new PyHomographyD(this->homog*other_homog));\n}\n\npy::object\nPyHomographyF\n::inverse()\n{\n  auto new_homog = this->homog.inverse();\n  auto new_matrix = new_homog->matrix();\n  return py::cast<Eigen::Matrix<double, 3, 3>>(new_matrix);\n}\n\npy::object\nPyHomographyF\n::map(py::object p_obj)\n{\n  auto p = p_obj.cast<Eigen::Matrix<float,2,1>>();\n  auto new_matrix = this->homog.map_point(p);\n  return py::cast<Eigen::Matrix<float, 2, 1>>(new_matrix);\n}\n\npy::object\nPyHomographyF\n::normalize()\n{\n  auto new_homog = this->homog.normalize();\n  auto new_matrix = new_homog->matrix();\n  return py::cast<Eigen::Matrix<double, 3, 3>>(new_matrix);\n}\n\nstd::shared_ptr<PyHomographyBase>\nPyHomographyF::\noperator*(std::shared_ptr<PyHomographyBase> &other)\n{\n  auto mat = other->get_matrix().cast<Eigen::Matrix<float,3,3>>(); //this part is a bit silly, could be done better\n  auto other_homog = kwiver::vital::homography_<float>(mat);\n  return std::shared_ptr<PyHomographyBase>(new PyHomographyF(this->homog*other_homog));\n}\n\nbool\nPyHomographyBase::\noperator==(std::shared_ptr<PyHomographyBase> &other)\n{\n  if(this->get_type() == 'd')\n  {\n    auto this_mat = this->get_matrix().cast<Eigen::Matrix<double, 3, 3>>();\n    auto other_mat = other->get_matrix().cast<Eigen::Matrix<double, 3, 3>>();\n    return this_mat.isApprox(other_mat);\n  }\n  else if(this->get_type() == 'f')\n  {\n    auto this_mat = this->get_matrix().cast<Eigen::Matrix<float, 3, 3>>();\n    auto other_mat = other->get_matrix().cast<Eigen::Matrix<float, 3, 3>>();\n    return this_mat.isApprox(other_mat, 0.001);\n  }\n\n  return false;\n}\n\nstd::shared_ptr<PyHomographyBase>\nnew_homography(char ctype)\n{\n  std::shared_ptr<PyHomographyBase> retVal;\n  if(ctype == 'd')\n  {\n    retVal = std::shared_ptr<PyHomographyBase>(new PyHomographyD());\n  }\n  else if(ctype == 'f')\n  {\n    retVal = std::shared_ptr<PyHomographyBase>(new PyHomographyF());\n  }\n  return retVal;\n}\n\nstd::shared_ptr<PyHomographyBase>\nnew_homography_from_matrix(py::object data_obj, char ctype)\n{\n  std::shared_ptr<PyHomographyBase> retVal;\n  if(ctype == 'd')\n  {\n    auto data = data_obj.cast<Eigen::Matrix<double, 3,3>>();\n    retVal = std::shared_ptr<PyHomographyBase>(new PyHomographyD(data));\n  }\n  else if(ctype == 'f')\n  {\n    auto data = data_obj.cast<Eigen::Matrix<float, 3,3>>();\n    retVal = std::shared_ptr<PyHomographyBase>(new PyHomographyF(data));\n  }\n  return retVal;\n}\n\nstd::shared_ptr<PyHomographyBase>\nnew_random_homography(char ctype)\n{\n  py::object data_obj;\n  if(ctype == 'd')\n  {\n    data_obj = py::cast<Eigen::Matrix<double, 3, 3>>(Eigen::MatrixXd::Random(3,3));\n  }\n  else if(ctype == 'f')\n  {\n    data_obj = py::cast<Eigen::Matrix<float, 3, 3>>(Eigen::MatrixXf::Random(3,3));\n  }\n  return new_homography_from_matrix(data_obj, ctype);\n}\n\n}\n}\n}\n\nusing namespace kwiver::vital::python;\nPYBIND11_MODULE(homography, m)\n{\n  py::class_<PyHomographyBase, std::shared_ptr<PyHomographyBase>>(m, \"Homography\")\n  .def(py::init(&new_homography),\n    py::arg(\"type\")='d')\n  .def_static(\"from_matrix\", &new_homography_from_matrix,\n    py::arg(\"data\"), py::arg(\"type\")='d')\n  .def_static(\"random\", &new_random_homography,\n    py::arg(\"type\")='d')\n  .def_property_readonly(\"type_name\", &PyHomographyBase::get_type)\n  .def(\"as_matrix\", &PyHomographyBase::get_matrix)\n  .def(\"inverse\", &PyHomographyBase::inverse)\n  .def(\"map\", &PyHomographyBase::map,\n    py::arg(\"point\"))\n  .def(\"normalize\", &PyHomographyBase::normalize)\n  .def(\"__eq__\", &PyHomographyBase::operator==)\n  .def(\"__ne__\", &PyHomographyBase::operator!=)\n  .def(\"__mul__\", &PyHomographyBase::operator*)\n  ;\n}\n", "meta": {"hexsha": "4434ec682531d49a1dc942bf2c92601c407b8a12", "size": 8152, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "python/kwiver/vital/types/homography.cxx", "max_stars_repo_name": "VIAME/kwiver", "max_stars_repo_head_hexsha": "b746303025a834f6799b69dfb90d0c8061df64c4", "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": "python/kwiver/vital/types/homography.cxx", "max_issues_repo_name": "VIAME/kwiver", "max_issues_repo_head_hexsha": "b746303025a834f6799b69dfb90d0c8061df64c4", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/kwiver/vital/types/homography.cxx", "max_forks_repo_name": "VIAME/kwiver", "max_forks_repo_head_hexsha": "b746303025a834f6799b69dfb90d0c8061df64c4", "max_forks_repo_licenses": ["BSD-3-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.4179104478, "max_line_length": 139, "alphanum_fraction": 0.700686948, "num_tokens": 2305, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6513548782017745, "lm_q2_score": 0.47657965106367595, "lm_q1q2_score": 0.3104224805720248}}
{"text": "/*****************************************************************************\n *\n * This file is part of Mapnik (c++ mapping toolkit)\n *\n * Copyright (C) 2017 Artem Pavlenko\n *\n * This library is free software; you can redistribute it and/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA\n *\n *****************************************************************************/\n\n#include <mapnik/geometry/interior.hpp>\n#include <mapnik/geometry_envelope.hpp>\n#include <mapnik/box2d.hpp>\n#include <mapnik/geometry_centroid.hpp>\n\n#include <algorithm>\n#include <cmath>\n#include <iostream>\n#include <queue>\n\n#pragma GCC diagnostic push\n#include <mapnik/warning_ignore.hpp>\n#include <boost/optional.hpp>\n#pragma GCC diagnostic pop\n\nnamespace mapnik { namespace geometry {\n\n// Interior algorithm is realized as a modification of Polylabel algorithm\n// from https://github.com/mapbox/polylabel.\n// The modification aims to improve visual output by prefering\n// placements closer to centroid.\n\nnamespace detail {\n\n// get squared distance from a point to a segment\ntemplate <class T>\nT segment_dist_sq(const point<T>& p,\n                  const point<T>& a,\n                  const point<T>& b)\n{\n    auto x = a.x;\n    auto y = a.y;\n    auto dx = b.x - x;\n    auto dy = b.y - y;\n\n    if (dx != 0 || dy != 0) {\n\n        auto t = ((p.x - x) * dx + (p.y - y) * dy) / (dx * dx + dy * dy);\n\n        if (t > 1) {\n            x = b.x;\n            y = b.y;\n\n        } else if (t > 0) {\n            x += dx * t;\n            y += dy * t;\n        }\n    }\n\n    dx = p.x - x;\n    dy = p.y - y;\n\n    return dx * dx + dy * dy;\n}\n\ntemplate <class T>\nvoid point_to_ring_dist(point<T> const& point, linear_ring<T> const& ring,\n                        bool & inside, double & min_dist_sq)\n{\n    for (std::size_t i = 0, len = ring.size(), j = len - 1; i < len; j = i++)\n    {\n        const auto& a = ring[i];\n        const auto& b = ring[j];\n\n        if ((a.y > point.y) != (b.y > point.y) &&\n            (point.x < (b.x - a.x) * (point.y - a.y) / (b.y - a.y) + a.x)) inside = !inside;\n\n        min_dist_sq = std::min(min_dist_sq, segment_dist_sq(point, a, b));\n    }\n}\n\n// signed distance from point to polygon outline (negative if point is outside)\ntemplate <class T>\ndouble point_to_polygon_dist(const point<T>& point, const polygon<T>& polygon)\n{\n    bool inside = false;\n    double min_dist_sq = std::numeric_limits<double>::infinity();\n\n    point_to_ring_dist(point, polygon.exterior_ring, inside, min_dist_sq);\n\n    for (const auto& ring : polygon.interior_rings)\n    {\n        point_to_ring_dist(point, ring, inside, min_dist_sq);\n    }\n\n    return (inside ? 1 : -1) * std::sqrt(min_dist_sq);\n}\n\ntemplate <class T>\nstruct fitness_functor\n{\n    fitness_functor(point<T> const& centroid, point<T> const& polygon_size)\n        : centroid(centroid),\n          max_size(std::max(polygon_size.x, polygon_size.y))\n        {}\n\n    T operator()(point<T> const& cell_center, T distance_polygon) const\n    {\n        if (distance_polygon <= 0)\n        {\n            return distance_polygon;\n        }\n        point<T> d(cell_center.x - centroid.x, cell_center.y - centroid.y);\n        double distance_centroid = std::sqrt(d.x * d.x + d.y * d.y);\n        return distance_polygon * (1 - distance_centroid / max_size);\n    }\n\n    point<T> centroid;\n    T max_size;\n};\n\ntemplate <class T>\nstruct cell\n{\n    template <class FitnessFunc>\n    cell(const point<T>& c_, T h_,\n         const polygon<T>& polygon,\n         const FitnessFunc& ff)\n        : c(c_),\n          h(h_),\n          d(point_to_polygon_dist(c, polygon)),\n          fitness(ff(c, d)),\n          max_fitness(ff(c, d + h * std::sqrt(2)))\n        {}\n\n    point<T> c; // cell center\n    T h; // half the cell size\n    T d; // distance from cell center to polygon\n    T fitness; // fitness of the cell center\n    T max_fitness; // a \"potential\" of the cell calculated from max distance to polygon within the cell\n};\n\ntemplate <class T>\npoint<T> polylabel(polygon<T> const& polygon, box2d<T> const& bbox , T precision = 1)\n{\n    const point<T> size { bbox.width(), bbox.height() };\n\n    const T cell_size = std::min(size.x, size.y);\n    T h = cell_size / 2;\n\n    // a priority queue of cells in order of their \"potential\" (max distance to polygon)\n    auto compare_func = [] (const cell<T>& a, const cell<T>& b)\n    {\n        return a.max_fitness < b.max_fitness;\n    };\n    using Queue = std::priority_queue<cell<T>, std::vector<cell<T>>, decltype(compare_func)>;\n    Queue queue(compare_func);\n\n    if (cell_size == 0)\n    {\n        return { bbox.minx(), bbox.miny() };\n    }\n\n    point<T> centroid;\n    if (!mapnik::geometry::centroid(polygon, centroid))\n    {\n        auto center = bbox.center();\n        return { center.x, center.y };\n    }\n\n    fitness_functor<T> fitness_func(centroid, size);\n\n    // cover polygon with initial cells\n    for (T x = bbox.minx(); x < bbox.maxx(); x += cell_size)\n    {\n        for (T y = bbox.miny(); y < bbox.maxy(); y += cell_size)\n        {\n            queue.push(cell<T>({x + h, y + h}, h, polygon, fitness_func));\n        }\n    }\n\n    // take centroid as the first best guess\n    auto best_cell = cell<T>(centroid, 0, polygon, fitness_func);\n\n    while (!queue.empty())\n    {\n        // pick the most promising cell from the queue\n        auto current_cell = queue.top();\n        queue.pop();\n\n        // update the best cell if we found a better one\n        if (current_cell.fitness > best_cell.fitness)\n        {\n            best_cell = current_cell;\n        }\n\n        // do not drill down further if there's no chance of a better solution\n        if (current_cell.max_fitness - best_cell.fitness <= precision) continue;\n\n        // split the cell into four cells\n        h = current_cell.h / 2;\n        queue.push(cell<T>({current_cell.c.x - h, current_cell.c.y - h}, h, polygon, fitness_func));\n        queue.push(cell<T>({current_cell.c.x + h, current_cell.c.y - h}, h, polygon, fitness_func));\n        queue.push(cell<T>({current_cell.c.x - h, current_cell.c.y + h}, h, polygon, fitness_func));\n        queue.push(cell<T>({current_cell.c.x + h, current_cell.c.y + h}, h, polygon, fitness_func));\n    }\n\n    return best_cell.c;\n}\n\n} // namespace detail\n\ntemplate <class T>\nbool interior(polygon<T> const& polygon, double scale_factor, point<T> & pt)\n{\n    if (polygon.exterior_ring.empty())\n    {\n        return false;\n    }\n\n    const box2d<T> bbox = envelope(polygon.exterior_ring);\n\n    // Let the precision be 1% of the polygon size to be independent to map scale.\n    double precision = (std::max(bbox.width(), bbox.height()) / 100.0) * scale_factor;\n\n    pt = detail::polylabel(polygon, bbox, precision);\n    return true;\n}\n\ntemplate\nbool interior(polygon<double> const& polygon, double scale_factor, point<double> & pt);\n\n} }\n\n", "meta": {"hexsha": "683f3ad8661519d3eba535ddff8f723df172091e", "size": 7426, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "external/mapnik/src/geometry/interior.cpp", "max_stars_repo_name": "baiyicanggou/mapnik_mvt", "max_stars_repo_head_hexsha": "9bde52fa9958d81361c015c816858534ec0931bb", "max_stars_repo_licenses": ["Apache-2.0"], "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/mapnik/src/geometry/interior.cpp", "max_issues_repo_name": "baiyicanggou/mapnik_mvt", "max_issues_repo_head_hexsha": "9bde52fa9958d81361c015c816858534ec0931bb", "max_issues_repo_licenses": ["Apache-2.0"], "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/mapnik/src/geometry/interior.cpp", "max_forks_repo_name": "baiyicanggou/mapnik_mvt", "max_forks_repo_head_hexsha": "9bde52fa9958d81361c015c816858534ec0931bb", "max_forks_repo_licenses": ["Apache-2.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.0647773279, "max_line_length": 103, "alphanum_fraction": 0.6034204148, "num_tokens": 1874, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6513548646660542, "lm_q2_score": 0.476579651063676, "lm_q1q2_score": 0.310422474121176}}
{"text": "#include \"RBGL.hpp\"\n#include \"mincut.hpp\"\n#include <boost/graph/edmonds_karp_max_flow.hpp>\n#include <boost/graph/push_relabel_max_flow.hpp>\n#include <boost/graph/kolmogorov_max_flow.hpp>\n\ntypedef enum { E_MF_Push_Relabel, E_MF_Edmonds_Karp, E_MF_Kolmogorov } E_MF_METHOD;\n\nstatic SEXP BGL_max_flow_internal(SEXP num_verts_in, SEXP num_edges_in,\n                                  SEXP R_edges_in, SEXP R_capacity_in,\n                                  SEXP src, SEXP sink, E_MF_METHOD method )\n{\n    using namespace boost;\n\n    typedef adjacency_list_traits<vecS, vecS, directedS> Tr;\n    typedef Tr::edge_descriptor Tr_edge_desc;\n\n    typedef adjacency_list<vecS, vecS, directedS, no_property,\n    \t\tproperty<edge_capacity_t, double,\n    \t\tproperty<edge_residual_capacity_t, double,\n    \t\tproperty<edge_reverse_t, Tr_edge_desc> > > >\n\t\tFlowGraph;\n\n    typedef graph_traits<FlowGraph>::edge_iterator   edge_iterator;\n    typedef graph_traits<FlowGraph>::vertex_descriptor vertex_descriptor;\n\n    FlowGraph flow_g;\n\n    property_map < FlowGraph, edge_capacity_t >::type\n    cap = get(edge_capacity, flow_g);\n    property_map < FlowGraph, edge_residual_capacity_t >::type\n    res_cap = get(edge_residual_capacity, flow_g);\n    property_map < FlowGraph, edge_reverse_t >::type\n    rev_edge = get(edge_reverse, flow_g);\n\n    Tr::edge_descriptor e1, e2;\n    bool in1, in2;\n\n    if (!isInteger(R_edges_in)) error(\"R_edges_in should be integer\");\n\n    int NV = INTEGER(num_verts_in)[0];\n    int NE = asInteger(num_edges_in);\n    int* edges_in = INTEGER(R_edges_in);\n    int*    capacity_i = (isReal(R_capacity_in)) ? 0 : INTEGER(R_capacity_in);\n    double* capacity_d = (isReal(R_capacity_in)) ? REAL(R_capacity_in) : 0;\n\n    for (int i = 0; i < NE ; i++, edges_in += 2)\n    {\n        tie(e1, in1) = boost::add_edge(*edges_in, *(edges_in+1), flow_g);\n        tie(e2, in2) = boost::add_edge(*(edges_in+1), *edges_in, flow_g);\n        if ( !in1 || !in2 )\n            error(\"unable to add edge: (%d, %d)\", *edges_in, *(edges_in+1));\n\n        // fill in capacity_map\n        cap[e1] = capacity_i ? (*capacity_i++) : (*capacity_d++);\n        cap[e2] = 0;\n\n        // fill in reverse_edge_map\n        rev_edge[e1] = e2;\n        rev_edge[e2] = e1;\n    }\n\n    double maxflow = 0;\n\n    int vsrc = INTEGER(src)[0];\n    int vsink = INTEGER(sink)[0];\n\n    if ( 0 <= vsrc && vsrc < NV && 0 <= vsink && vsink < NV )\n    {\n    \tvertex_descriptor s = vertex(vsrc, flow_g);\n    \tvertex_descriptor t = vertex(vsink, flow_g);\n\n    \tif ( method == E_MF_Push_Relabel ) \n\t     maxflow = push_relabel_max_flow(flow_g, s, t);\n\telse if ( method == E_MF_Edmonds_Karp )\n             maxflow = edmonds_karp_max_flow(flow_g, s, t);\n\telse if ( method == E_MF_Kolmogorov )\n\t{\n\t     error(\"kolmogorov_max_flow from BGL doesn't work\");\n\t     //maxflow = kolmogorov_max_flow(flow_g, s, t);\n\t}\n\telse\n\t     error(\"unknown method for max_flow\");\n    }\n\n    SEXP ansList, conn, eList, fList;\n    PROTECT(ansList = allocVector(VECSXP,3));\n    PROTECT(conn = NEW_NUMERIC(1));\n    PROTECT(eList = allocMatrix(INTSXP, 2, asInteger(num_edges_in)));\n    PROTECT(fList = allocMatrix(REALSXP, 1, asInteger(num_edges_in)));\n\n    REAL(conn)[0] = maxflow;\n\n    edge_iterator ei, e_end;\n    int i = 0, j = 0;\n    for (tie(ei, e_end) = edges(flow_g); ei != e_end; ++ei)\n        if (cap[*ei] > 0) {\n            INTEGER(eList)[i++] = source(*ei, flow_g);\n            INTEGER(eList)[i++] = target(*ei, flow_g);\n            REAL(fList)[j++] = cap[*ei] - res_cap[*ei];\n        }\n\n    SET_VECTOR_ELT(ansList,0,conn);\n    SET_VECTOR_ELT(ansList,1,eList);\n    SET_VECTOR_ELT(ansList,2,fList);\n    UNPROTECT(4);\n\n    return(ansList);\n}\n\nextern \"C\"\n{\n    SEXP BGL_min_cut_U (SEXP num_verts_in, SEXP num_edges_in,\n                        SEXP R_edges_in,   SEXP R_weights_in )\n    {\n        using namespace boost;\n\n        Graph_ud g(num_verts_in, num_edges_in, R_edges_in, R_weights_in);\n\n        typedef graph_traits < Graph_ud >::vertex_descriptor Vertex;\n        typedef graph_traits < Graph_ud >::edges_size_type dst;\n        std::vector<Vertex> s_set, vs_set;\n        dst cut_capacity = min_cut(g, std::back_inserter(s_set), std::back_inserter(vs_set) );\n\n        SEXP ansList, conn;\n        SEXP sList, vsList;  // for subsets of nodes in mincut: S, V - S\n\n        PROTECT(ansList = allocVector(VECSXP,3));\n        PROTECT(conn = NEW_NUMERIC(1));\n        PROTECT(sList = allocVector(INTSXP, s_set.size()));\n        PROTECT(vsList = allocVector(INTSXP,vs_set.size()));\n\n        REAL(conn)[0] = (double)cut_capacity;\n\n        std::vector<Vertex>::iterator vi;\n        int i = 0;\n        for ( i = 0, vi = s_set.begin(); vi != s_set.end(); i++, ++vi)\n            INTEGER(sList)[i] = *vi;\n\n        for ( i = 0, vi = vs_set.begin(); vi != vs_set.end(); i++, ++vi)\n            INTEGER(vsList)[i] = *vi;\n\n        SET_VECTOR_ELT(ansList,0,conn);\n        SET_VECTOR_ELT(ansList,1,sList);\n        SET_VECTOR_ELT(ansList,2,vsList);\n        UNPROTECT(4);\n\n        return(ansList);\n    }\n\n\n    SEXP BGL_edmonds_karp_max_flow(SEXP num_verts_in, SEXP num_edges_in,\n                                   SEXP R_edges_in, SEXP R_capacity_in, \n\t\t\t\t   SEXP src, SEXP sink )\n    {\n        SEXP ansList = BGL_max_flow_internal(num_verts_in, num_edges_in,\n                                             R_edges_in, R_capacity_in, \n\t\t\t\t\t     src, sink, E_MF_Edmonds_Karp);\n        return(ansList);\n    }\n\n    SEXP BGL_push_relabel_max_flow(SEXP num_verts_in, SEXP num_edges_in,\n                                   SEXP R_edges_in, SEXP R_capacity_in, \n\t\t\t\t   SEXP src, SEXP sink )\n    {\n        SEXP ansList = BGL_max_flow_internal(num_verts_in, num_edges_in,\n                                             R_edges_in, R_capacity_in, \n\t\t\t\t\t     src, sink, E_MF_Push_Relabel);\n        return(ansList);\n    }\n\n    SEXP BGL_kolmogorov_max_flow(SEXP num_verts_in, SEXP num_edges_in,\n                                   SEXP R_edges_in, SEXP R_capacity_in, \n\t\t\t\t   SEXP src, SEXP sink )\n    {\n        SEXP ansList = BGL_max_flow_internal(num_verts_in, num_edges_in,\n                                             R_edges_in, R_capacity_in, \n\t\t\t\t\t     src, sink, E_MF_Kolmogorov);\n        return(ansList);\n    }\n\n}\n\n", "meta": {"hexsha": "0be67778cbd8bc9b0165b1438c197ee1b4f56bfe", "size": 6212, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/mincut.cpp", "max_stars_repo_name": "cran/RBGL", "max_stars_repo_head_hexsha": "e5d1a5109bf1dfbd6882bf50b6650ddc9da5ffb8", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-10-29T11:20:31.000Z", "max_stars_repo_stars_event_max_datetime": "2018-10-29T11:20:31.000Z", "max_issues_repo_path": "src/mincut.cpp", "max_issues_repo_name": "cran/RBGL", "max_issues_repo_head_hexsha": "e5d1a5109bf1dfbd6882bf50b6650ddc9da5ffb8", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/mincut.cpp", "max_forks_repo_name": "cran/RBGL", "max_forks_repo_head_hexsha": "e5d1a5109bf1dfbd6882bf50b6650ddc9da5ffb8", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.7608695652, "max_line_length": 94, "alphanum_fraction": 0.6118802318, "num_tokens": 1706, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6513548646660542, "lm_q2_score": 0.47657965106367595, "lm_q1q2_score": 0.31042247412117596}}
{"text": "/* ------------Includes---------------------- */\n#include <cmath>\n#include <iostream>\n#include <utility>\n#include <unistd.h>\n#include \"../include/CAN_utils.h\"\n#include \"../include/CO_message.h\"\n#include \"../include/vehicle.h\"\n#include \"../include/motor.h\"\n#include \"../include/caster.h\"\n#include <Eigen/Core>\n#include <Eigen/QR>\n#include <Eigen/Geometry>\n#include <Eigen/Dense>\n#include <Eigen/LU>\n#include <omniveyor_common/definitions.h>\n\n// #define VELOCITY_SATURATION \n// #define SEND_ZERO_TORQUES\n#define CLAMP_TORQUES\n\nusing std::cout;\nusing std::endl; \n\n/* --------------------------- STATIC FUNCTION PROTOTYPES ------------------------------- */\nstatic double casterPosXSign(int casterNum);\nstatic double casterPosYSign(int casterNum);\nstatic Eigen::Vector3d clampVelocity(Eigen::Vector3d xd_com_in);\nstatic Eigen::Vector3d clampAcceleration(Eigen::Vector3d xdd_com_in);\nstatic float saturate(float x); \n\n/* --------------------------- PUBLIC MEMBER FUNCTIONS ------------------------------- */\n\n/* Constructor. Caster number starts at 1 */\nVehicle::Vehicle() \n{\n\t_initialized = false;\n\t_enabled = false;\n\t_stopped = false;\n\t_control = VELOCITY;\n\n\t_x_local.setZero(); \n\t_xd_local.setZero();\n\t_gx.setZero(); \n\t_gxd.setZero();\n\t_gxd_com.setZero();\n\t_gxd_des.setZero();\n\t_gxdd.setZero();\n\n\t_g_cf.setZero();\n\t_cf_des_local.setZero();\n\n\t_q_steer.setZero(); \n\t_qd.setZero(); \n\t_qd_des.setZero(); \n\t_tq.setZero(); \n\t_tq_des.setZero(); \n\t_lambda.setZero(); \n\t_mu.setZero(); \n\t_C.setZero(); \n\t_Cp.setZero(); \n\t_Jq.setZero(); \n\t_C_pinv.setZero(); \n\n\t_heading = 0; \n\n\t_Kp.setZero(); // zero gains for torque control initially\n\t_Kv.setZero(); // zero gains for torque control initially\n\n\t// create casters\n\tfor(int i = 0; i < NUM_CASTERS; i++)\n\t{\n\t\tcasters[i] = new Caster(i+1);\t\t\n\t} \n\n\t/* create a socket for the control thread */\n\ts = create_can_socket (UNUSED_NODE_ID, 0xF);\n\tif (s < 0)\n\t{\n\t\tperror (\"Unable to open control socket\\n\");\n\t\texit (-1);\n\t}\n\t//CO_Set_bitrate(s, 500000);\n}\n\n\n/* Destructor */\nVehicle::~Vehicle()\n{\n\t_initialized = false;\n\t/* quick stop to motors - wait (x amount of time)*/\n\n\t/* destroy caster objects */\n\tfor(int i = 0; i < NUM_CASTERS; i++)\n\t{\n\t\tdelete casters[i];\n\t}\n\t/* reset comm */\t\n\tstruct CO_message msg;\n\tmsg.type = NMT;\n\tmsg.m.NMT.data = 0x81;\n\tCO_send_message (s, 0, &msg);\n\tshutdown(s,1);\n\t//close(s);\n}\n\n\n/* Intializes all casters */\nint Vehicle::init() \n{\n\tfor(int i = 0; i < NUM_CASTERS; i++)\n\t{\n\t\tif(casters[i]->init())\n\t\t{\n\t\t\treturn -1;\n\t\t}\n\t}\n\t_initialized = true;\n\treturn 0;\n}  \n\n\n/* Enable all casters*/\nint Vehicle::enable() \n{\n\tif(!_initialized)\n\t{\n\t\treturn -1;\n\t}\n\n\tfor(int i = 0; i < NUM_CASTERS; i++)\n\t{\n\t\tif(casters[i]->enable())\n\t\t{\n\t\t\treturn -1;\n\t\t}\n\t}\n\n\t_enabled = true;\n\t_stopped = false;\n\treturn 0;\n}\n\n\n/* Disable all casters */\nint Vehicle::disable()\n{\n\tif(!_initialized)\n\t{\n\t\treturn -1;\n\t}\n\n\tfor(int i = 0; i < NUM_CASTERS; i++)\n\t{\n\t\tif(casters[i]->disable())\n\t\t{\n\t\t\treturn -1;\n\t\t}\n\t}\n\n\t_enabled = false;\n\treturn 0;\n}\n\n\n/* Stop all motors */\n// HAVEN'T GOTTEN THIS TO WORK YET - CAN USE WHATEVER METHOD YOU WANT\nint Vehicle::stop() \n{\n\tif (!_enabled)\n\t{\n\t\treturn -1;\n\t}\n\n\tfor(int i = 0; i < NUM_CASTERS; i++)\n\t{\n\t\tif(casters[i]->stop() == 0)\n\t\t{\n\t\t\tcout << \"stopping caster \" << i << endl;\n\t\t\t// return -1;\n\t\t}\n\t}\n\n\t_stopped = true; // wait for stop?\n\treturn 0;\n}\n\nint Vehicle::start() \n{\n\tif (!_enabled)\n\t{\n\t\treturn -1;\n\t}\n\n\tfor(int i = 0; i < NUM_CASTERS; i++)\n\t{\n\t\tif(casters[i]->start() == 0)\n\t\t{\n\t\t\tcout << \"starting caster \" << i << endl;\n\t\t\t// return -1;\n\t\t}\n\t}\n\n\t_stopped = false; // wait for stop?\n\treturn 0;\n}\n\n\n/* Set control mode to velocity or torque control.\n * This can only be set when the motors are disabled.\n */\nint Vehicle::setCtrlMode(enum ctrl_mode cm)\n{\n\tif(_enabled && !_stopped)\n\t{\n\t\treturn -1; // only set mode if disabled\n\t}\n\n\t// Set mode\n\t_control = cm;\n\tcout << \"Setting vehicle control mode to : \" << cm << endl;\n\tfor(int i = 0; i < NUM_CASTERS; i++)\n\t{\n\t\tif(casters[i]->setCtrlMode(cm))\n\t\t{\n\t\t\treturn -1;\n\t\t}\n\t}\n\n\treturn 0;\n}\n\n/* Update the local and global coordinates of the \n * operational point of the mobile base\n */\nvoid Vehicle::updateOdometry(){\n\tupdateJointData();\n\t// Eigen::Matrix<double, NUM_MOTORS, 1> deltaQ = getDeltaQ();\n\t\n\t// Calculate C_p^+\n\tupdateConstraintPinvMatrix();\n\n\t// Find velocity and position of the base in the frame of the base with respect to the world origin\n\t// _xd_local = _C_pinv * deltaQ / CONTROL_PERIOD_s;\n\t_xd_local = _C_pinv * _qd;\n\t_x_local += _xd_local * CONTROL_PERIOD_s;\n\n\t_heading = _gx(2)+ 0.5*_xd_local(2)*CONTROL_PERIOD_s;\n\n\t// Rotation matrix to convert vectors from local frame to global frame \n\tEigen::Matrix3d R = Eigen::Matrix3d::Zero();\n\tR(0, 0) =  cos(_heading);\n    R(0, 1) = -sin(_heading);\n    R(1, 0) =  sin(_heading);\n    R(1, 1) =  cos(_heading);\n    R(2, 2) =  1.0;\n    \n    _gxd = R * _xd_local;\n    _gx += _gxd * CONTROL_PERIOD_s;\n}\n\n\n/* Returns the change in steer and roll angle */ \nEigen::Matrix<double, NUM_MOTORS, 1> Vehicle::getDeltaQ(){\n\tEigen::Matrix<double, NUM_MOTORS, 1> deltaQ;\n\tfor(int i = 0; i < NUM_CASTERS; i++)\n\t{\n\t\tdeltaQ(2*i) = casters[i]->getSteerDeltaQ();\n\t\tdeltaQ(2*i + 1) = casters[i]->getRollDeltaQ();\n\t}\n\treturn deltaQ;\n}\n\n\n/* Set vehicle velocities in x, y, and theta. vx,vy in m/s and vth in rad/s */\n// (6.1)\nint Vehicle::setGlobalVelocity(Eigen::Vector3d xd_com_in)\n{\n\t// Retrieve latest joint data\n\tupdateJointData();\n\n\t// Calculate C\n\tupdateConstraintMatrix();\n\n\t// Store velocity command and determine current xd_des (limit acceleration)\n\t_gxd_com = clampVelocity(xd_com_in);\n\t_gxd_des = _gxd_des + clampAcceleration(_gxd_com - _gxd_des);\n\n\t// Calculate joint velocities to command\n\t_qd_des = _C * _gxd_des;\n\n\t// Set velocities for each caster\n\tfor(int i = 0; i < NUM_CASTERS; i++) \n\t{\n\t\tif(casters[i]->setVelocities(_qd_des(2*i),_qd_des(2*i+1))) \n\t\t{\n\t\t\treturn -1;\n\t\t}\n\t}\t\n\n\treturn 0;\n} \n\n\n/* Set desired vehicle position, velocity, and acceleration for torque controller */\n// (6.4)\nvoid Vehicle::setTargets(Eigen::Array3d gx_des_in, Eigen::Array3d gxd_des_in, Eigen::Array3d gxdd_des_in) \n{\n\t// update _lambda and mu\n\tupdateDynamics();\n\n\t_gx_des   = gx_des_in; \n\t_gxd_des  = gxd_des_in; \n\t_gxdd_des = gxdd_des_in; \n\n\t// Calculate and set control forces/torques\n#ifdef VELOCITY_SATURATION\n\tEigen::Array3d dxd; \n\tdxd = _Kp / _Kv * (gx_des_in - _gx.array()); \n\tEigen::Array3d nu; \n\tnu(0) = saturate(MAX_VEL_X/abs(dxd(0))); \n\tnu(1) = saturate(MAX_VEL_Y/abs(dxd(1))); \n\tnu(2) = saturate(MAX_VEL_TH/abs(dxd(2))); \n\tEigen::Vector3d g_cf_unit = -_Kv * (_gxd.array() - nu * dxd); \n#else \n\tEigen::Vector3d g_cf_unit = -_Kp * (_gx.array() - gx_des_in) - _Kv * (_gxd.array() - gxd_des_in) + gxdd_des_in;\n\n#endif\n\n\t// Rotation matrix to convert vector from global frame to local frame\n\tEigen::Matrix3d R = Eigen::Matrix3d::Zero();\n\tR(0, 0) = cos(_heading);\n    R(0, 1) = sin(_heading);\n    R(1, 0) = -sin(_heading);\n    R(1, 1) = cos(_heading);\n    R(2, 2) = 1.0;\n\n\t// Map global command to local coordinates \n\tEigen::Array3d cf_unit_local = R * g_cf_unit; \n\n\t_cf_des_local = _lambda * cf_unit_local.matrix();\n\t// cf_des = _lambda * cf_unit.matrix() + mu;\n\t\n\tsetTorque(_cf_des_local);\n}\t\n\n\n/* set _Kp gains */\nvoid Vehicle::setKp(Eigen::Array3d Kp_des){\n\t_Kp = Kp_des;\n}\n\n/* set Kv gains */\nvoid Vehicle::setKv(Eigen::Array3d Kv_des){\n\t_Kv = Kv_des;\n}\n\n/* Get control mode (velocity/torque) */\nenum ctrl_mode Vehicle::getCtrlMode() const \n{\n\treturn _control;\n}\n\n/* Get position in m for x and y and rad for theta */\nEigen::Vector3d Vehicle::getGlobalPosition() const\n{\n\treturn _gx;\n}\n\nEigen::Vector3d Vehicle::getLocalPosition() const \n{\n\treturn  _x_local; \n}\n\n/* Get vehicle velocity in m/s for x and y and rad/s for theta */\nEigen::Vector3d Vehicle::getGlobalVelocity() const \n{\n\treturn _gxd;\n}\n\nEigen::Vector3d Vehicle::getLocalVelocity() const \n{\n\treturn _xd_local; \n}\n\n/* Get joint steering angles in rad */\nEigen::Matrix<double, NUM_CASTERS, 1> Vehicle::getJointSteeringAngles() const\n{\n\t// updateJointData();\n\treturn _q_steer;\n}\n\n/* Get desired joint velocities in rad/s */\nEigen::Matrix<double, NUM_MOTORS, 1> Vehicle::getDesJointVelocities() const\n{\n\treturn _qd_des;\n}\n\n/* Get joint velocities in rad/s */\nEigen::Matrix<double, NUM_MOTORS, 1> Vehicle::getJointVelocities() const\n{\n\treturn _qd;\n}\n\n/* Get vehicle (operational space) forces in x and y in N and torque in theta in Nm */\nEigen::Vector3d Vehicle::getLocalCommandForces() const\n{\n\treturn _cf_des_local;\n}\n\n\n/* Get joint torques in Nm */\nEigen::Matrix<double, NUM_MOTORS, 1> Vehicle::getDesJointTorques() const \n{\n\treturn _tq_des;\n}\n\n/* Get initialization status of vehicle */\nbool Vehicle::isInitialized() const\n{\n\treturn _initialized;\n}\n\n/* Get enable status of vehicle */\nbool Vehicle::isEnabled() const\n{\n\treturn _enabled;\n}\n\n/* Get status of vehicle */\nbool Vehicle::isStopped() const\n{\n\treturn _stopped;\n}\n\nEigen::Matrix3d Vehicle::getLambda() const \n{\n\treturn _lambda; \n}\n\nEigen::MatrixXd Vehicle::getCPinv() const \n{\n\treturn _C_pinv; \n}\n\n\n/* Returns true if at least one bumper is hit */\nbool Vehicle::isBumperHit() const\n{\n\tbool retVal = false; \n\tfor(int i = 0; i < NUM_CASTERS; i++)\n\t{\n\t\tif (casters[i]->getBumperState()){\n\t\t\tretVal = true; \n\t\t} \n\t}\n\treturn retVal; \n}\n\n/* Returns a 4D vector containing the bumper state of each bumper */\nEigen::Vector4d Vehicle::getBumperState() const\n{\n\tEigen::Vector4d bumper_state; \n\tfor(int i = 0; i < NUM_CASTERS; i++)\n\t{\n\t\tbumper_state[i] = casters[i]->getBumperState(); \n\t}\n\treturn bumper_state; \n}\n\ndouble Vehicle::getHeading() const \n{\n\treturn _heading; \n}\n\nvoid Vehicle::getElectricalStatus (robotElectrical_T *status)\n{\n\tfor (int i=0; i<NUM_CASTERS; i++){\n\t\tcasters[i]->getAmps(&(status->steerMotorCurrent[i]), &(status->rollMotorCurrent[i]));\n\t\tcasters[i]->getVolts(&(status->steerMotorVoltage[i]), &(status->rollMotorVoltage[i]));\n\t}\n}\n\nbool Vehicle::reachedTarget(Eigen::Vector3d curr_pos, Eigen::Vector3d curr_target, double max_linear_dist, double max_rot_dist) const\n{\n\treturn ((fabs(curr_pos[0]-curr_target[0]) < max_linear_dist) && (fabs(curr_pos[1]-curr_target[1]) < max_linear_dist) && (fabs(curr_pos[2]-curr_target[2]) < max_rot_dist));\n}\n\n/* --------------------------- PRIVATE MEMBER FUNCTIONS ------------------------------- */\n\n/* Input: operational space forces fx,fy (N) and torque tz (Nm), all in local frame */\n/* Outputs torques to casters */\nint Vehicle::setTorque(const Eigen::Vector3d& cf_command)\n{\n\t// Retrieve latest joint data\n\tupdateJointData();\n\n\t// Calculate C#\n\t//updateConstraintMatrix();\n\n\t// Calculate C_p^+\n\tupdateConstraintPinvMatrix();\n\n\t// Calculate joint torques\n\t// (6.11)\n\t_tq_des = _C_pinv.transpose() * cf_command; \n\n#ifdef CLAMP_TORQUES\n\tclampTorque(); \n#endif\n\n#ifdef SEND_ZERO_TORQUES\n\t_tq_des.setZero(); \n#endif\n\n\tfor(int i = 0; i < NUM_CASTERS; i++)\n\t{\n\t\tif(casters[i]->setTorques(_tq_des(2*i),_tq_des(2*i+1)))\n\t\t{\n\t\t\treturn -1;\n\t\t}\n\t}\t\n\treturn 0;\n}\n\n\n/* Update joint data */\nvoid Vehicle::updateJointData() \n{\n\tstd::pair<double,double> jointVel;\n\tfor(int i = 0; i < NUM_CASTERS; i++)\n\t{\n\t\t_q_steer(i) = casters[i]->getSteerPosition();\n\t\tjointVel = casters[i]->getVelocities();\n\t\t_qd(2*i) = jointVel.first;\n\t\t_qd(2*i + 1) = jointVel.second;\n\t}\n}\n\n\n/* Mass Matrix taken from pg 20 of PCV Dyanmics.pdf*/\nvoid Vehicle::updateDynamics()\n{\n\t_lambda = Eigen::Matrix3d::Zero();\n\t_mu = Eigen::Vector3d::Zero();\n\tfor(int i = 0; i < NUM_CASTERS; i++)\n\t{\n\t\t// Calculate relevant matrices and vectors\n\t\tEigen::Matrix3d C_th = calcC_thMatrix(i);\n\t\tEigen::Matrix3d A = calcAMatrix();\n\t\tEigen::Vector3d p = calcpVector(i);\n\t\tEigen::Matrix3d J_dot = calcJ_dotMatrix(i);\n\t\tEigen::Vector3d Q_dot = calcQ_dotVector(i);\n\n\t\t//Calculate lambda_pumpkin and mu_pumpkin\t\n\t\tEigen::Matrix3d lambda_pumpkin = calcLambdaPumpkinMatrix(i);\n\t\tEigen::Vector3d mu_pumpkin = calcMuPumpkinVector(i);\n\n\t\tEigen::Matrix3d lambda_i = C_th.transpose() * A * C_th + lambda_pumpkin;\n\t\t_lambda += lambda_i;\n\n\t\tEigen::Vector3d mu_i = C_th.transpose()*(p - A*C_th*J_dot*Q_dot) + mu_pumpkin; \n \t\t_mu += mu_i;\n\t}\n\t_lambda += calcLambdaVehicleMatrix();\n}\n\n\n/* Update kinematic constraint matrix, C#. Assumes joint data is up to date.\n   Converts from operational space (xdot) to joint space (qdot). See pg 27 PCV_Dyanmics.pdf*/\nvoid Vehicle::updateConstraintMatrix() \n{\n\tfor(int i = 0; i < NUM_CASTERS; i++)\n\t{\n\t\tint steerRow = 2*i;\n\t\tint rollRow = 2*i + 1;\n\n\t\t// Caster position values\n\t\tdouble hx = casterPosXSign(i+1) * DIST_TO_CASTER_X;\n\t\tdouble hy = casterPosYSign(i+1) * DIST_TO_CASTER_Y;\n\n\t\t// Take sin/cos of steeering angle\n\t\tdouble steerSin = sin(_q_steer(i));\n\t\tdouble steerCos = cos(_q_steer(i));\n\n\t\t// Compute steer row\n\t\t/**************** Alternative sign convention *******************/\n\t\t// C(steerRow,0) = -steerSin / PC_b;\n\t\t// C(steerRow,1) = steerCos / PC_b;\n\t\t// C(steerRow,2) = (hx * steerCos + hy * steerSin) / PC_b - 1.0;\n\t\t/****************************************************************/\n\t\t_C(steerRow,0) = steerSin / PC_b;\n\t\t_C(steerRow,1) = -steerCos / PC_b;\n\t\t_C(steerRow,2) = -(hx * steerCos + hy * steerSin) / PC_b - 1.0;\n\n\t\t// Compute roll row\n\t\t_C(rollRow,0) = steerCos / PC_r;\n\t\t_C(rollRow,1) = steerSin / PC_r;\n\t\t_C(rollRow,2) = (hx * steerSin - hy * steerCos) / PC_r;\n\t}\n}\n\n\n/* Update Moore-Penrose pseudoinverse of the constraint matrix C_p. Assumes constraint matrix, C#, is up to date */\nvoid Vehicle::updateConstraintPinvMatrix() \n{\n\t// Update Cp matrix with current data\n\tupdateCpMatrix(); \n\n\tEigen::MatrixXd CptCli = Eigen::MatrixXd::Zero(3, NUM_MOTORS);\n\n\tfor(int i = 0; i < NUM_CASTERS; i++)\n\t{\n\t\t// Cli IS 2x2 BLOCK DIAGONAL, SO MULTIPLY\n\t    // IN PIECES TO AVOID SLOW NxN MATRIX OPERATIONS\n\n\t\t// Take sin/cos of steering angle\n\t\tdouble steerSin = sin(_q_steer(i));\n\t\tdouble steerCos = cos(_q_steer(i));\n\n\t\t// Caster position values\n\t\tdouble hx = casterPosXSign(i+1) * DIST_TO_CASTER_X;\n\t\tdouble hy = casterPosYSign(i+1) * DIST_TO_CASTER_Y;\n\n\t    int j = 2*i;\n\n\t    // Note: sign of p-dot is: wheel as viewed from ground\n\t    CptCli(0, j ) =  PC_b * steerSin;\n\t    CptCli(0,j+1) =  PC_r * steerCos;\n\t    CptCli(1, j ) = -PC_b * steerCos;\n\t    CptCli(1,j+1) =  PC_r * steerSin;\n\t    CptCli(2, j ) = -PC_b * ((hx * steerCos + hy * steerSin) + PC_b);\n\t    CptCli(2,j+1) =  PC_r * (hx * steerSin - hy * steerCos);\n\t}\n\n\t_C_pinv = (_Cp.transpose()*_Cp).llt().solve(CptCli);\n}\n\n\nEigen::Matrix3d Vehicle::calcAMatrix(){\n\tEigen::Matrix3d A;\n\tA(0, 0) = PC_Mf*pow(PC_e, 2) + PC_If + PC_Ii + PC_Ih + PC_Is*pow(Ns, 2) + PC_It*Nr;\n\tA(0, 1) = PC_Ii*Nw - PC_Ih*Nw - PC_It*pow(Nr, 2)*Nw;\n\tA(0, 2) = PC_Mf*pow(PC_e, 2) + PC_If + PC_Ii + PC_Ih - PC_Is*Ns - PC_It*Nr;\n\n\tA(1, 0) = A(0, 1); \n\tA(1, 1) = PC_Mf*pow(PC_r, 2) + PC_Ii*pow(Nw, 2) + PC_Ih*pow(Nw, 2) + PC_It*pow(Nr, 2)*pow(Nw, 2) + PC_Ij;\n\tA(1, 2) = PC_Ii*Nw - PC_Ih*Nw + PC_It*Nr*Nw;\n\n\tA(2, 0) = A(0, 2);\n\tA(2, 1) = A(1, 2);\n\tA(2, 2) = PC_Mf*pow(PC_e, 2) + PC_If + PC_Ii + PC_Ih + PC_Is + PC_It;\n\treturn A;\n}\n\n\n// PCV Dynamics page 21\nEigen::Vector3d Vehicle::calcpVector(int caster_no){\n\tdouble steer_d = _qd(2*caster_no);\n\tdouble roll_d  = _qd(2*caster_no+1);\n\tdouble gth_d   = _gxd(2);\n\n\tEigen::Vector3d p;\n\tp(0) = PC_Mf*PC_r*PC_e*roll_d*(steer_d+gth_d);\n\tp(1) = -PC_Mf*PC_r*PC_e*pow((steer_d+gth_d), 2);\n\tp(2) = PC_Mf*PC_r*PC_e*roll_d*(steer_d+gth_d);\n\treturn p; \n}\n\n\n// From PCV Dynamics page 29\nEigen::Matrix3d Vehicle::calcC_thMatrix(int caster_no) \n{\n\t// Caster position values\n\tdouble hx = casterPosXSign(caster_no+1) * DIST_TO_CASTER_X;\n\tdouble hy = casterPosYSign(caster_no+1) * DIST_TO_CASTER_Y;\n\n\t// Take sin/cos of steering angle\n\tdouble steerSin = sin(_q_steer(caster_no));\n\tdouble steerCos = cos(_q_steer(caster_no));\n\n\tEigen::Matrix3d C_th;\n\t/***  Alternate sign convention ***/\n\t// C_th(0, 0) = -steerSin / PC_b;\n\t// C_th(0, 1) = steerCos / PC_b;\n\t// C_th(0, 2) = (hx * steerCos + hy * steerSin) / PC_b - 1.0;\n\t/**********************************/\n\tC_th(0, 0) = steerSin / PC_b;\n\tC_th(0, 1) = -steerCos / PC_b;\n\tC_th(0, 2) = -(hx * steerCos + hy * steerSin) / PC_b - 1.0;\n\n\tC_th(1, 0) = steerCos / PC_r;\n\tC_th(1, 1) = steerSin / PC_r;\n\tC_th(1, 2) = (hx * steerSin - hy * steerCos) / PC_r;\n\t\t\t\n\tC_th(2, 0) = 0.0;\n\tC_th(2, 1) = 0.0;\n\tC_th(2, 2) = 1.0;\n \n\treturn C_th;\n}\n\n\n// From PCV Dynamics page 25\nEigen::Matrix3d Vehicle::calcJ_dotMatrix(int caster_no)\n{\n\tEigen::Matrix3d J_dot;\n\tdouble steer_d = _qd(2*caster_no);\n\tdouble gth_d = _gxd(2);\n\n\t// Caster position values\n\tdouble hx = casterPosXSign(caster_no+1) * DIST_TO_CASTER_X;\n\tdouble hy = casterPosYSign(caster_no+1) * DIST_TO_CASTER_Y;\n\n\t// Take sin/cos of steeering angle\n\tdouble steerSin = sin(_q_steer(caster_no));\n\tdouble steerCos = cos(_q_steer(caster_no));\n\n\t// Take sin/cos of steer angle velocity plus PCV angle velocity\n\tdouble Sum = steer_d + gth_d;\n\n\tJ_dot(0, 0) = PC_b * steerCos * Sum;\n\tJ_dot(0, 1) = -PC_r * steerSin * Sum;\n\tJ_dot(0, 2) = hx * gth_d + PC_b * steerCos * Sum;\n\n\tJ_dot(1, 0) = PC_b * steerSin * Sum;\n\tJ_dot(1, 1) = PC_r * steerCos * Sum;\n\tJ_dot(1, 2) = hy * gth_d + PC_b * steerSin * Sum;\n\t\t\t\n\tJ_dot(2, 0) = 0.0;\n\tJ_dot(2, 1) = 0.0;\n\tJ_dot(2, 2) = 0.0;\n\n\treturn J_dot;\n}\n\n\nEigen::Matrix3d Vehicle::calcLambdaPumpkinMatrix(int caster_no) \n{\n\tEigen::Matrix3d lambda_pumpkin = Eigen::Matrix3d::Zero();\n\n\t// Caster position values\n\tdouble hx = casterPosXSign(caster_no+1) * DIST_TO_CASTER_X;\n\tdouble hy = casterPosYSign(caster_no+1) * DIST_TO_CASTER_Y;\n\n\tlambda_pumpkin(0, 0) = PC_Mp;\n\tlambda_pumpkin(0, 2) = -PC_Mp*hy;\n\n\tlambda_pumpkin(1, 1) = PC_Mp;\n\tlambda_pumpkin(1, 2) = PC_Mp*hx;\n\n\tlambda_pumpkin(2, 0) = lambda_pumpkin(0, 2);\n\tlambda_pumpkin(2, 1) = lambda_pumpkin(1, 2);\n\tlambda_pumpkin(2, 2) = PC_Ip + PC_Mp*pow(DIST_TO_CASTER ,2);\n\treturn lambda_pumpkin;\n}\n\n\nEigen::Matrix3d Vehicle::calcLambdaVehicleMatrix() \n{\n\tEigen::Matrix3d lambda_vehicle = Eigen::Matrix3d::Zero();\n\n\tlambda_vehicle(0, 0) = PC_Mv; // Effective mass along the x direction is the mass of the vehicle \n\tlambda_vehicle(1, 1) = PC_Mv; // Effective mass along the y direction is the mass of the vehicle \n\tlambda_vehicle(2, 2) = PC_Iv; // Inertia of the vehicle about the z axis \n\n\treturn lambda_vehicle;\n}\n\n\nEigen::Vector3d Vehicle::calcQ_dotVector(int caster_no)\n{\n\tEigen::Vector3d Q_dot;\n\n\tdouble steer_d = _qd(2*caster_no);\n\tdouble roll_d = _qd(2*caster_no+1);\n\tdouble gth_d = _gxd(2);\n\tQ_dot << steer_d, roll_d, gth_d;\n\n\treturn Q_dot;\n}\n\n\nEigen::Vector3d Vehicle::calcMuPumpkinVector(int caster_no)\n{\n\tEigen::Vector3d mu_pumpkin;\n\tdouble gth_d = _gxd(2);\n\n\t// Caster position values\n\tdouble hx = casterPosXSign(caster_no+1) * DIST_TO_CASTER_X;\n\tdouble hy = casterPosYSign(caster_no+1) * DIST_TO_CASTER_Y;\n\n\tmu_pumpkin << -PC_Mp * hx * pow(gth_d, 2), -PC_Mp * hy * pow(gth_d, 2), 0.0;\n\n\treturn mu_pumpkin;\n}\n\n\n/* Update Jq matrix. Transforms q_d's into p_d's (p_d = Jq*q_d). In documentation, Jq = C_q^{-1} */\nvoid Vehicle::updateJqMatrix() \n{\n\t_Jq = Eigen::MatrixXd::Zero(NUM_MOTORS, NUM_MOTORS);\n\tfor(int i = 0; i < NUM_CASTERS; i++)\n\t{\n\t\t// Which rows to calculate\n\t\tint steerRow = 2*i;\n\t\tint rollRow = 2*i + 1;\n\n\t\t// Take sin/cos of steering angle\n\t\tdouble steerSin = sin(_q_steer(i));\n\t\tdouble steerCos = cos(_q_steer(i));\n\n\t\t// Compute steer row\n\t\t_Jq(steerRow,steerRow) = steerSin * PC_b;\n\t\t_Jq(steerRow,rollRow) = steerCos * PC_r;\n\n\t\t// Compute roll row\n\t\t_Jq(rollRow,steerRow) = -steerCos * PC_b;\n\t\t_Jq(rollRow,rollRow) = steerSin * PC_r;\n\t}\n}\n\n\n/* Update Cp matrix. Transforms x_d's into p_d's (p_d = C_p*x_d) */\nvoid Vehicle::updateCpMatrix() \n{\n\tfor(int i = 0; i < NUM_CASTERS; i++)\n\t{\n\t\t// Which rows to calculate\n\t\tint steerRow = 2*i;\n\t\tint rollRow = 2*i + 1;\n\n\t\t// Take sin/cos of steering angle\n\t\tdouble steerSin = sin(_q_steer(i));\n\t\tdouble steerCos = cos(_q_steer(i));\n\n\t\t// Caster position values\n\t\tdouble hx = casterPosXSign(i+1) * DIST_TO_CASTER_X;\n\t\tdouble hy = casterPosYSign(i+1) * DIST_TO_CASTER_Y;\n\n\t\t// Cp = Jq*C, could calculate it this way instead\n\t\t// Compute steer row\n\t\t_Cp(steerRow,0) = 1.0;\n\t\t_Cp(steerRow,1) = 0.0;\n\t\t_Cp(steerRow,2) = -PC_b * steerSin - hy;\n\n\t\t// Compute roll row\n\t\t_Cp(rollRow,0) = 0.0;\n\t\t_Cp(rollRow,1) = 1.0;\n\t\t_Cp(rollRow,2) = PC_b * steerCos + hx;\n\t}\n}\n\n\n// Clamp the torque command to max values\nvoid Vehicle::clampTorque(){\n\t// Clamp torque values to maximum allowed\n\tfor(int i = 0; i < NUM_CASTERS; i++)\n\t{\n\t\t_tq_des(2*i)   = abs(_tq_des(2*i))   < MAX_STEER_TORQUE  ? _tq_des(2*i)   : copysign(MAX_STEER_TORQUE, _tq_des(2*i));\n\t\t_tq_des(2*i+1) = abs(_tq_des(2*i+1)) < MAX_ROLL_TORQUE   ? _tq_des(2*i+1) : copysign(MAX_ROLL_TORQUE,  _tq_des(2*i+1));\n\t}\n}\n\n\n\n/* ------------ Static functions-------------- */\n// Determine sign of x position of caster based on number\nstatic double casterPosXSign(int casterNum)\n{\n\tswitch(casterNum)\n\t{\n\t\tcase 1:\n\t\tcase 2:\n\t\t\treturn 1.0;\n\t\tcase 3:\n\t\tcase 4:\n\t\t\treturn -1.0;\n\t\tdefault:\n\t\t\treturn 0;\n\t}\n}\n\n\n// Determine sign of y position of caster based on number\nstatic double casterPosYSign(int casterNum)\n{\n\tswitch(casterNum)\n\t{\n\t\tcase 2:\n\t\tcase 3:\n\t\t\treturn 1.0;\n\t\tcase 1:\t\t\n\t\tcase 4:\n\t\t\treturn -1.0;\n\t\tdefault:\n\t\t\treturn 0;\n\t}\n}\n\n\n/*  Saturation function \n\tReturns the input float value if its absolute value is less than or equal to 1. \n\tOtherwise, it returns 1.0 or -1.0 (depending on the sign of float x) */\nstatic float saturate(float x) {\n\tx = abs(x) <= 1.0 ? x : copysign(1.0, x); \n\treturn x; \n}\n\n\n// Function to clamp velocity command to max values\nstatic Eigen::Vector3d clampVelocity(Eigen::Vector3d xd_com_in){\n\t// Clamp velocity values to maximum allowed\n\txd_com_in(0) = abs(xd_com_in(0)) < MAX_VEL_TRANS ? xd_com_in(0) : copysign(MAX_VEL_TRANS, xd_com_in(0));\n\txd_com_in(1) = abs(xd_com_in(1)) < MAX_VEL_TRANS ? xd_com_in(1) : copysign(MAX_VEL_TRANS, xd_com_in(1));\n\txd_com_in(2) = abs(xd_com_in(2)) < MAX_VEL_ROT ? xd_com_in(2) : copysign(MAX_VEL_ROT, xd_com_in(2));\n\n\treturn xd_com_in;\n}\n\n\n// Function to clamp acceleration command to max values (accel is change in xd_des for one control loop here)\nstatic Eigen::Vector3d clampAcceleration(Eigen::Vector3d xdd_com_in){\n\n\t// Clamp acceleration values to maximum allowed\n\n\t// Check accel/decel for x\n\tif(xdd_com_in(0) >= 0){\n\t\t// Clamp trans accel\n\t\txdd_com_in(0) = xdd_com_in(0) < MAX_VEL_TRANS_INC ? xdd_com_in(0) : MAX_VEL_TRANS_INC;\n\t}\n\telse{\n\t\t// Clamp trans decel\n\t\txdd_com_in(0) = xdd_com_in(0) > -MAX_VEL_TRANS_DEC ? xdd_com_in(0) : -MAX_VEL_TRANS_DEC;\n\t}\n\n\t// Check accel/decel for y\n\tif(xdd_com_in(1) >= 0){\n\t\t// Clamp trans accel\n\t\txdd_com_in(1) = xdd_com_in(1) < MAX_VEL_TRANS_INC ? xdd_com_in(1) : MAX_VEL_TRANS_INC;\n\t}\n\telse{\n\t\t// Clamp trans decel\n\t\txdd_com_in(1) = xdd_com_in(1) > -MAX_VEL_TRANS_DEC ? xdd_com_in(1) : -MAX_VEL_TRANS_DEC;\n\t}\n\t\n\t// Check accel/decel for theta\n\tif(xdd_com_in(2) >= 0){\n\t\t// Clamp trans accel\n\t\txdd_com_in(2) = xdd_com_in(2) < MAX_VEL_ROT_INC ? xdd_com_in(2) : MAX_VEL_ROT_INC;\n\t}\n\telse{\n\t\t// Clamp trans decel\n\t\txdd_com_in(2) = xdd_com_in(2) > -MAX_VEL_ROT_DEC ? xdd_com_in(2) : -MAX_VEL_ROT_DEC;\n\t}\n\n\treturn xdd_com_in;\n}\n\n/*********************** TEST HARNESS *****************************************/\n\n#ifdef TEST_VEHICLE\n\n// Different types of tests to run\nenum test_type \n{\n\tTEST_INIT,\n\tTEST_CONSTRAINT_MATRIX,\n\tTEST_DYNAMICS\n};\n\nint main (void)\n{\n\tcout << \"Begin vehicle test harness\" << endl;\n\n\t/* instantiate vehicle */\n\tVehicle *vehicle = new Vehicle ();\n\n\t// Which test to run\n\tenum test_type thisTest = TEST_DYNAMICS;\t\n\t\n\tint s = create_can_socket (0xF, 0xF);\n\n\t// Switch on type\n\tswitch(thisTest){\n\n\t\tcase TEST_DYNAMICS:\n\t\t{\n\t\t\tcout << \"Testing Vehicle Dynamics\" << endl;\n\n\t\t}\n\t\t\n\t\tcase TEST_INIT:\n\t\t\tcout << \"Testing Vehicle Initialization\" << endl;\n\n\t\t\tif (vehicle->init())\n\t\t\t\tcout << \"Vehicle initialization failed\" << endl;\n\t\t\telse\n\t\t\t\tcout << \"Vehicle initialization success\" << endl;\n\n\t\t\tgetchar ();\n\t\t\tbreak;\n\n\t\tcase TEST_CONSTRAINT_MATRIX:\n\t\t\t{\n\t\t\t\tcout << \"Testing Vehicle constraint matrix\" << endl;\n\n\t\t\t\tEigen::Matrix<double, NUM_MOTORS, 3> C; \t\t \t\t// constraint matrix\n\t\t\t\tEigen::Matrix<double, NUM_CASTERS, 5> _q_steer;\n\t\t\t\tEigen::Vector3d xd1;\n\t\t\t\tEigen::Vector3d xd2;\n\t\t\t\txd1 << 1,0,0;\n\t\t\t\txd2 << 0,1,0;\n\n\t\t\t\t_q_steer << 0,0,0,0,\n\t\t\t\t\t\t\t\t   M_PI/2, M_PI/2, M_PI/2, M_PI/2,\n\t\t\t\t\t\t\t\t\t M_PI,M_PI,M_PI,M_PI,\n\t\t\t\t\t\t\t\t\t 3*M_PI/2,3*M_PI/2,3*M_PI/2,3*M_PI/2,\n\t\t\t\t\t\t\t\t\t -M_PI/2, -M_PI/2, -M_PI/2, -M_PI/2;\n\n\t\t\t\t// Re-compute constraint matrix C\n\t\t\t\tfor(int j = 0; j < 5; j++){\n\t\t\t\t\tcout << \"q_steer = [\";\n\t\t\t\t\tfor(int i = 0; i < NUM_CASTERS; i++)\n\t\t\t\t\t{\n\t\t\t\t\t\t// Which rows to calculate\n\t\t\t\t\t\tint steerRow = 2*i;\n\t\t\t\t\t\tint rollRow = 2*i + 1;\n\n\t\t\t\t\t\t// Caster position values\n\t\t\t\t\t\tdouble hx = casterPosXSign(i+1) * DIST_TO_CASTER_X;\n\t\t\t\t\t\tdouble hy = casterPosYSign(i+1) * DIST_TO_CASTER_Y;\n\n\t\t\t\t\t\t// Take sin/cos of steeering angle\n\t\t\t\t\t\tdouble steerSin = sin(_q_steer(i,j));\n\t\t\t\t\t\tdouble steerCos = cos(_q_steer(i,j));\n\n\t\t\t\t\t\t// Compute steer row\n\t\t\t\t\t\tC(steerRow,0) = -steerSin / PC_b;\n\t\t\t\t\t\tC(steerRow,1) =  steerCos / PC_b;\n\t\t\t\t\t\tC(steerRow,2) = (hx * steerCos + hy * steerSin) / PC_b - 1.0;\n\n\t\t\t\t\t\t\t\t// Compute roll row\n\t\t\t\t\t\tC(rollRow,0) = steerCos / PC_r;\n\t\t\t\t\t\tC(rollRow,1) = steerSin / PC_r;\n\t\t\t\t\t\tC(rollRow,2) = (hx * steerSin - hy * steerCos) / PC_r;\n\n\t\t\t\t\t\tcout << _q_steer(i,j) << \", \";\n\t\t\t\t\t}\n\n\t\t\t\t\tcout << \"]\" << endl;\n\t\t\t\t\tcout << endl << \"C = \" << endl;\n\t\t\t\t\tcout << C << endl;\n\t\t\t\t\tcout << \"xd1 = \" << xd1.transpose() << endl;\n\t\t\t\t\tcout << \"qd1 = \" << (C*xd1).transpose() << endl;\n\t\t\t\t\tcout << \"xd2 = \" << xd2.transpose() << endl;\n\t\t\t\t\tcout << \"qd2 = \" << (C*xd2).transpose() << endl;\n\n\t\t\t\t\tgetchar();\n\t\t\t\t}\n\t\t\t}\n\t\t\tbreak;\n\n\t\tdefault:\n\t\t\tbreak;\n\t}\n\n\t// Delete caster\n\tdelete vehicle;\n\n\n\tgetchar ();\n\tcout << \"End vehicle test harness\" << endl;\n\treturn 0;\n}\n\n\n#endif\n", "meta": {"hexsha": "ba45248764ed4c49fed2525389a9910d97e3c0aa", "size": 25574, "ext": "cc", "lang": "C++", "max_stars_repo_path": "pcv_base/src/vehicle.cc", "max_stars_repo_name": "HaoguangYang/omniveyor_hardware", "max_stars_repo_head_hexsha": "68f5d824ea838e24cad14f8eaae1cb4ad9f51c83", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "pcv_base/src/vehicle.cc", "max_issues_repo_name": "HaoguangYang/omniveyor_hardware", "max_issues_repo_head_hexsha": "68f5d824ea838e24cad14f8eaae1cb4ad9f51c83", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pcv_base/src/vehicle.cc", "max_forks_repo_name": "HaoguangYang/omniveyor_hardware", "max_forks_repo_head_hexsha": "68f5d824ea838e24cad14f8eaae1cb4ad9f51c83", "max_forks_repo_licenses": ["BSD-3-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.7015755329, "max_line_length": 172, "alphanum_fraction": 0.6470634238, "num_tokens": 8610, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7279754489059775, "lm_q2_score": 0.4263215925474903, "lm_q1q2_score": 0.3103516527130705}}
{"text": "//\n// Created by philipp on 1/16/20.\n//\n\n#ifndef FUNNELS_CPP_EX1_FIXED_HH\n#define FUNNELS_CPP_EX1_FIXED_HH\n\n#include <Eigen/Core>\n#include <cmath>\n#include <sstream>\n#include <algorithm>\n#include <array>\n\n\n#include <funnels/utils.hh>\n\n#ifndef M_PI\n#define M_PI 3.1415926535897932384626433832795d\n#endif\n\n// Attention, in example 1, velocity coincides with the control\n// signal\n// Attention, assumes constant velocity/input\n\nconst double max_r_step = 0.5; // different funnel sizes in a family\nconst double min_r = 0.001; // Minimal radius\nconst double max_r = 0.5+5.*min_r; // Minimal radius\nconst double max_alpha_step = max_r_step*max_r_step; // Minimal step for alpha\nconst double min_alpha = min_r*min_r; // Minimal alpha for ellipsoids\nconst double max_alpha = max_r*max_r; // Minimal alpha for ellipsoids\nconst double max_vel = 1.; // Norm of velocity\nconst double min_vel_diff = 0.1; // Norm difference in velocity\nconst double min_ang_diff = 20.*M_PI/180.;\nconst double gamma_conv = 10.; // exponential convergence rate\nconst double max_traj_length = 3; // Length of the new segment\nconst double dt_step = 0.05; //time step between two verification points\nconst size_t n_max = 100;\nconst double max_time = 100.;\nconst double min_englobe_fac = 1.1;\n\nconst double plane_dist = 0.3;\nconst double inter_dist = 0.3;\n\nEigen::Matrix2d getR(double alpha);\n\n\ntemplate <class FUN_PTR_T>\nstd::pair<FUN_PTR_T, FUN_PTR_T> get_this_funnel(const FUN_PTR_T &src, double radius,\n                          const Eigen::Vector4d &x0_O, const Eigen::Vector2d u){\n  \n  using fun_t = typename FUN_PTR_T::element_type;\n  \n  // Get maximal time before the maximal length is attained\n  // or the playground is left\n  Eigen::Vector4d x0 = x0_O;\n  double n_u, t_max;\n  if (u.norm() > 1e-3){\n    n_u = u.norm()+1e-200;\n    t_max = std::min(max_time, max_traj_length/n_u);\n    // distance to x/y-border\n    for (size_t i=0; i<2; i++){\n      if(u(i)>=0.){\n        t_max = std::min(t_max, (1.2-x0(i))/(u(i)+1e-200));\n      }else{\n        t_max = std::min(t_max, (-1.2-x0(i))/(u(i)+1e-200));\n      }\n    }\n    if (t_max < 3.*dt_step){\n      // trajectory is too short\n      // initial is on the boundary and we are pointing outwards\n      return std::pair(nullptr, nullptr);\n    }\n  }else{\n    t_max = 3.*dt_step;\n  }\n  \n  \n  // Convert to number of points\n  size_t this_n_verif = std::max((size_t)3, std::min((size_t) (t_max/dt_step), n_max));\n  \n  // todo check if this funnel already exists in the\n  // funnel system\n  // get the new name\n  // Update the initial pos\n  x0 = x0_O;\n  \n  std::stringstream sstream;\n  sstream.setf(std::ios::fixed);\n  sstream.precision(2);\n  \n  sstream << \"fun_\";\n  for(size_t i=0; i<4; i++){\n    sstream << (double) x0(i) << \"_\";\n  }\n  sstream << radius;\n  std::string name = sstream.str();\n  std::replace( name.begin(), name.end(), '.', 'p');\n  std::replace( name.begin(), name.end(), '-', 'm');\n  \n  // If exactly this funnel exists, the name will exist\n  if (utils_ext::loc_map.find(name)){\n    return std::pair(nullptr, nullptr);\n  }\n  \n  FUN_PTR_T new_fun1 = src->make_copy(name, 2.*this_n_verif);\n  FUN_PTR_T new_fun2 = src->make_copy(name+\"_twin\", 2.*this_n_verif);\n  \n  // set the new radius\n  new_fun1->set_P(src->get_P()*(src->get_alpha()/(radius*radius)));\n  new_fun2->set_P(src->get_P()*(src->get_alpha()/(radius*radius)));\n  // and convergence\n  new_fun1->set_gamma(gamma_conv);\n  new_fun2->set_gamma(gamma_conv);\n  \n  // Update pos and compute traj\n  x0.block(2,0,2,1) -= -t_max*u;\n  new_fun1->compute(x0, 0., 2.*t_max, u);\n  // Mirror\n  x0 = -x0_O;\n  x0.block(2,0,2,1) -= -t_max*u;\n  new_fun2->compute(x0, 0., 2.*t_max, u);\n  \n  \n  // He starts a family\n  new_fun1->start_family(new_fun1);\n  new_fun2->start_family(new_fun2);\n  \n  return std::pair(new_fun1, new_fun2);\n}\n\ntemplate <class FUN_PTR_T>\nFUN_PTR_T get_this_funnel_1(const FUN_PTR_T &src, double radius,\n    const Eigen::Vector4d &x0_O, const Eigen::Vector2d u){\n  \n  using fun_t = typename FUN_PTR_T::element_type;\n  \n  // Get maximal time before the maximal length is attained\n  // or the playground is left\n  Eigen::Vector4d x0 = x0_O;\n  double n_u, t_max;\n  if (u.norm() > 1e-3){\n    n_u = u.norm()+1e-200;\n    t_max = std::min(max_time, max_traj_length/n_u);\n    // distance to x/y-border\n    for (size_t i=0; i<2; i++){\n      if(u(i)>=0.){\n        t_max = std::min(t_max, (1.2-x0(i))/(u(i)+1e-200));\n      }else{\n        t_max = std::min(t_max, (-1.2-x0(i))/(u(i)+1e-200));\n      }\n    }\n    if (t_max < 3.*dt_step){\n      // trajectory is too short\n      // initial is on the boundary and we are pointing outwards\n      return nullptr;\n    }\n  }else{\n    t_max = 3.*dt_step;\n  }\n  \n  \n  // Convert to number of points\n  size_t this_n_verif = std::max((size_t)3, std::min((size_t) (t_max/dt_step), n_max));\n  \n  // todo check if this funnel already exists in the\n  // funnel system\n  // get the new name\n  // Update the initial pos\n  x0 = x0_O;\n  \n  std::stringstream sstream;\n  sstream.setf(std::ios::fixed);\n  sstream.precision(2);\n  \n  sstream << \"fun_\";\n  for(size_t i=0; i<4; i++){\n    sstream << (double) x0(i) << \"_\";\n  }\n  sstream << radius;\n  std::string name = sstream.str();\n  std::replace( name.begin(), name.end(), '.', 'p');\n  std::replace( name.begin(), name.end(), '-', 'm');\n  \n  // If exactly this funnel exists, the name will exist\n  if (utils_ext::loc_map.find(name)){\n    return nullptr;\n  }\n  \n  FUN_PTR_T new_fun = src->make_copy(name, this_n_verif);\n  \n  // set the new radius\n  new_fun->set_P(src->get_P() * (src->get_alpha() / (radius * radius)));\n  // and convergence\n  new_fun->set_gamma(gamma_conv);\n  \n  // Update pos and compute traj\n  x0.block(2,0,2,1) -= -t_max*u;\n  new_fun->compute(x0, 0., 2. * t_max, u);\n  // Mirror\n  x0 = -x0_O;\n  x0.block(2,0,2,1) -= -t_max*u;\n  \n  \n  // He starts a family\n  new_fun->start_family(new_fun);\n  \n  return new_fun;\n}\n\ntemplate <class FUN_PTR_T>\nstd::vector<FUN_PTR_T> get_children(FUN_PTR_T &parent){\n  \n  using fun_t = typename FUN_PTR_T::element_type;\n  using matrix_t = typename fun_t::matrix_t;\n  \n  FUN_PTR_T this_child_fun;\n  FUN_PTR_T this_parent_fun = parent;\n  \n  \n  std::stringstream sstream;\n  std::string name;\n  \n  // Original unscaled matrix\n  matrix_t P_p = parent->get_P()*parent->get_alpha();\n  \n  sstream.setf(std::ios::fixed);\n  sstream.precision(2);\n  \n  std::vector<FUN_PTR_T> fun_vec_child;\n  \n  const double alpha_step = max_alpha_step;\n  const double r_step = max_r_step;\n  \n  // Radius of parent\n  double alpha = parent->get_alpha();\n  \n  if(std::sqrt(alpha) < min_r + r_step){\n    return fun_vec_child;\n  }\n  \n  alpha = std::max(min_alpha, (std::sqrt(alpha)-r_step)*(std::sqrt(alpha)-r_step));\n  \n  while(alpha>=min_alpha){\n    // Get the name\n    sstream.str(std::string());\n    sstream << \"fun_\";\n    auto x00 = parent->x0();\n    for(size_t i=0; i<4; i++){\n      sstream << (double) x00(i) << \"_\";\n    }\n    sstream << std::sqrt(alpha);\n    name = sstream.str();\n    std::replace( name.begin(), name.end(), '.', 'p');\n    std::replace( name.begin(), name.end(), '-', 'm');\n    if (utils_ext::loc_map.find(name)){\n      // Already exists\n      return fun_vec_child;\n    }\n    \n    this_child_fun = this_parent_fun->make_copy(name, this_parent_fun->size());\n    // set the new radius\n    this_child_fun->set_P(P_p/alpha);\n    this_child_fun->set_cyclic(this_parent_fun->is_cyclic());\n    // And convergence\n    this_child_fun->set_gamma(gamma_conv);\n    \n    fun_t::set_parent(this_parent_fun, this_child_fun);\n    fun_vec_child.emplace_back(this_child_fun);\n    this_parent_fun = this_child_fun;\n    this_child_fun = nullptr;\n    // Update alpha\n    alpha = (std::sqrt(alpha)-r_step); // New alpha as r\n    if (alpha <= min_r){\n      break; // Necessary as negative radii become positive in next step\n    }\n    alpha *= alpha; // Convert to alpha\n  }\n  return fun_vec_child;\n}\n\n\ntemplate<class FUN_PTR_T, class FUN_SYS>\nvoid add_new_funnels(const FUN_PTR_T& src,\n                     double t_src, FUN_SYS &fun_sys){\n  \n  // Src is dummy, only to keep the same signature\n  \n  using fun_t = typename FUN_PTR_T::element_type;\n  \n  // Return val\n  FUN_PTR_T fun_parent1, fun_parent2;\n  std::vector<FUN_PTR_T> fun_vec_child;\n  \n  Eigen::Vector2d pos_0;\n  \n  Eigen::Vector2d orth_p, vel_p, vel_1 = Eigen::Vector2d::Zero();\n  vel_1(0) = 1.;\n  \n  Eigen::Vector4d x0;\n  \n  // The problem is purely symmetric\n  \n  // Grid of static funnels\n  std::array<int, 2> signs = {-1,1};\n  x0.setZero();\n  vel_p.setZero();\n  for (double x_s = plane_dist/2.; x_s <= 1.; x_s+=plane_dist){\n    for (double y_s = plane_dist/2.; y_s <= 1.; y_s+=plane_dist) {\n      for (auto s_x : signs){\n        for (auto s_y : signs){\n          x0(0) = s_x*x_s;\n          x0(1) = s_y*y_s;\n          fun_parent1 = get_this_funnel_1(src, max_r, x0, vel_p);\n          if (fun_parent1 != nullptr) {\n            // add\n            fun_sys.add_funnel(fun_parent1, true);\n            // all_children\n            fun_vec_child = get_children(fun_parent1);\n            for (auto a_f : fun_vec_child) {\n              fun_sys.add_funnel(a_f);\n            }\n          }\n        }\n      }\n    }\n  }\n  \n  // \"Dynamic\" funnels\n  // Loop over all velocities <-> planes\n  for (double n_vel=inter_dist; n_vel<=1.0; n_vel+=inter_dist) {\n      // Loop over all angles\n    for (double d_alpha = 0.; d_alpha <= 2 * M_PI - d_alpha / 2;\n         d_alpha += min_ang_diff) {\n      // New velocity\n      vel_p = n_vel * (getR(d_alpha) * vel_1);\n      // New orthogonal\n      orth_p = getR(M_PI / 2.) * getR(d_alpha) * vel_1;\n      // Loop over all funnel origins\n      pos_0 = orth_p * (plane_dist / 2.);\n      while (true) {\n        if ((pos_0.array().abs() >= 1.).any()) {\n          // Out of the box\n          break;\n        }\n    \n        // Now we have a new parent funnel candidate\n        x0.block(0, 0, 2, 1) = pos_0;\n        // todo refactor norm vs normalized\n        x0.block(2, 0, 2, 1) = vel_p;\n        // Parent\n        std::tie(fun_parent1, fun_parent2) = get_this_funnel(src, max_r, x0,\n                                                             vel_p);\n    \n        if (fun_parent1 != nullptr) {\n          // add\n          fun_sys.add_funnel(fun_parent1, true);\n          // all_children\n          fun_vec_child = get_children(fun_parent1);\n          for (auto a_f : fun_vec_child) {\n            fun_sys.add_funnel(a_f);\n          }\n        }\n        if (fun_parent2 != nullptr) {\n          // add\n          fun_sys.add_funnel(fun_parent2, true);\n          // all_children\n          fun_vec_child = get_children(fun_parent2);\n          for (auto a_f : fun_vec_child) {\n            fun_sys.add_funnel(a_f);\n          }\n        }\n        // Update\n        pos_0 += orth_p * plane_dist;\n      } // origin pos\n    } // angle\n  } // plane\n  return;\n}\n\n#endif //FUNNELS_CPP_EX1_FIXED_HH\n", "meta": {"hexsha": "de13d038058814bbceae3d354817de0408f979d8", "size": 10822, "ext": "hh", "lang": "C++", "max_stars_repo_path": "include/heuristics/ex1_fixed.hh", "max_stars_repo_name": "schlepil/funnels_cpp_2", "max_stars_repo_head_hexsha": "1ed746a90019f7f6aff7a54fd4b63bfbd58fa2ac", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/heuristics/ex1_fixed.hh", "max_issues_repo_name": "schlepil/funnels_cpp_2", "max_issues_repo_head_hexsha": "1ed746a90019f7f6aff7a54fd4b63bfbd58fa2ac", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/heuristics/ex1_fixed.hh", "max_forks_repo_name": "schlepil/funnels_cpp_2", "max_forks_repo_head_hexsha": "1ed746a90019f7f6aff7a54fd4b63bfbd58fa2ac", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.4041994751, "max_line_length": 87, "alphanum_fraction": 0.6171687304, "num_tokens": 3261, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.640635854839898, "lm_q2_score": 0.48438008427698437, "lm_q1q2_score": 0.31031124935820775}}
{"text": "#include <iostream>\n#include <vector>\n\n#include <boost/lexical_cast.hpp>\n#include <boost/tuple/tuple.hpp>\n#include <boost/random/mersenne_twister.hpp>\n#include <boost/random/uniform_int_distribution.hpp>\n\n#include \"util.hpp\"\n\n#include \"elias_fano.hpp\"\n#include \"mapper.hpp\"\n\n#include \"perftest_common.hpp\"\n\nstruct monotone_generator\n{\n    monotone_generator(uint64_t m, uint8_t bits, unsigned int seed)\n\t: m_gen(seed)\n        , m_bits(bits)\n    {\n\tm_stack.push_back(state_t(0, m, 0));\n    }\n    \n    uint64_t next()\n    {\n\tuint64_t cur_word, cur_m;\n\tuint8_t cur_depth;\n\t\n\tassert(m_stack.size());\n\tboost::tie(cur_word, cur_m, cur_depth) = m_stack.back();\n\tm_stack.pop_back();\n\t\n\twhile (cur_depth < m_bits) {\n\t    boost::random::uniform_int_distribution<uint64_t> dist(0, cur_m);\n\t    uint64_t left_m = dist(m_gen);\n\t    uint64_t right_m = cur_m - left_m;\n\t    \n\t    // push left and right children, if present\n\t    if (right_m > 0) {\n\t\tm_stack.push_back(state_t(cur_word | (uint64_t(1) << (m_bits - cur_depth - 1)),\n\t\t\t\t\t  right_m, cur_depth + 1));\n\t    }\n\t    if (left_m > 0) {\n\t\tm_stack.push_back(state_t(cur_word, left_m, cur_depth + 1));\n\t\t\n\t    }\n\n\t    // pop next child in visit\n\t    boost::tie(cur_word, cur_m, cur_depth) = m_stack.back();\n\t    m_stack.pop_back();\n\t}\n\n\tif (cur_m > 1) {\n\t    // push back the current leaf, with cur_m decreased by one\n\t    m_stack.push_back(state_t(cur_word, cur_m - 1, cur_depth));\n\t}\n\n\treturn cur_word;\n    }\n\n    bool done() const \n    {\n\treturn m_stack.empty();\n    }\n    \nprivate:\n    typedef boost::tuple<uint64_t /* cur_word */, \n\t\t\t uint64_t /* cur_m */,\n\t\t\t uint64_t /* cur_depth */> state_t;\n    std::vector<state_t> m_stack;\n    boost::random::mt19937 m_gen;\n    uint8_t m_bits;\n};\n\nvoid ef_enumeration_benchmark(uint64_t m, uint8_t bits)\n{\n    succinct::elias_fano::elias_fano_builder bvb(uint64_t(1) << bits, m);\n    monotone_generator mgen(m, bits, 37);\n    for (size_t i = 0; i < m; ++i) { \n\tbvb.push_back(mgen.next());\n    }\n    assert(mgen.done());\n\n    succinct::elias_fano ef(&bvb);\n    succinct::mapper::size_tree_of(ef)->dump();\n    \n    \n    double elapsed;\n    uint64_t foo = 0;\n    SUCCINCT_TIMEIT(elapsed) {\n\tsuccinct::elias_fano::select_enumerator it(ef, 0);\n\tfor (size_t i = 0; i < m; ++i) {\n\t    foo ^= it.next();\n\t}\n    }\n    volatile uint64_t vfoo = foo;\n    (void)vfoo; // silence warning\n\n    std::cerr << \"Elapsed: \" << elapsed / 1000 << \" msec\\n\"\n\t      << double(m) / elapsed << \" Mcodes/s\" << std::endl;\n}\n\nint main(int argc, char** argv)\n{\n    if (argc != 3) {\n        std::cerr << \"Invalid arguments\" << std::endl;\n        std::terminate();\n    }\n    size_t m = boost::lexical_cast<uint64_t>(argv[1]);\n    uint8_t bits = uint8_t(boost::lexical_cast<int>(argv[2]));\n        \n    ef_enumeration_benchmark(m, bits);\n}\n", "meta": {"hexsha": "dcf4d77308e824e7ddba75d36cb03c49c00c650d", "size": 2792, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "external/succinct/perftest/perftest_elias_fano.cpp", "max_stars_repo_name": "ZabalaMariano/PISA", "max_stars_repo_head_hexsha": "344063799847e89f2f4bd7d75d606ccb95620d30", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 138.0, "max_stars_repo_stars_event_min_datetime": "2015-01-03T23:21:53.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-26T16:51:03.000Z", "max_issues_repo_path": "external/succinct/perftest/perftest_elias_fano.cpp", "max_issues_repo_name": "ZabalaMariano/PISA", "max_issues_repo_head_hexsha": "344063799847e89f2f4bd7d75d606ccb95620d30", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2015-03-04T11:14:32.000Z", "max_issues_repo_issues_event_max_datetime": "2017-06-13T21:25:50.000Z", "max_forks_repo_path": "perftest/perftest_elias_fano.cpp", "max_forks_repo_name": "ot/succinct", "max_forks_repo_head_hexsha": "669eebbdcaa0562028a22cb7c877e512e4f1210b", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 23.0, "max_forks_repo_forks_event_min_datetime": "2015-02-04T01:58:41.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-04T14:43:23.000Z", "avg_line_length": 24.2782608696, "max_line_length": 81, "alphanum_fraction": 0.6289398281, "num_tokens": 826, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6619228758499941, "lm_q2_score": 0.46879062662624377, "lm_q1q2_score": 0.3103032397479641}}
{"text": "/***********************************************************************************************************************\n *\n * Copyright (c) \n * 2015, ABB Schweiz AG\n * 2021, JOiiNT LAB, Fondazione Istituto Italiano di Tecnologia, Intellimech Consorzio per la Meccatronica.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with\n * or without modification, are permitted provided that\n * the following conditions are met:\n *\n *    * Redistributions of source code must retain the\n *      above copyright notice, this list of conditions\n *      and the following disclaimer.\n *    * Redistributions in binary form must reproduce the\n *      above copyright notice, this list of conditions\n *      and the following disclaimer in the documentation\n *      and/or other materials provided with the\n *      distribution.\n *    * Neither the name of ABB nor the names of its\n *      contributors may be used to endorse or promote\n *      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 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 OF\n * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n ***********************************************************************************************************************\n * \n * Authors: Gianluca Lentini, Ugo Alberto Simioni\n * Date:18/01/2022\n * Version 1.0\n * Description: this package provides a ROS node that communicates with the controller using Robot Web Services 2.0, original code can be retrieved at https://github.com/ros-industrial/abb_libegm\n * \n ***********************************************************************************************************************\n */\n\n#define _USE_MATH_DEFINES\n\n#include <cmath>\n\n#include <boost/math/quaternion.hpp>\n\n#include \"abb_libegm/egm_common_auxiliary.h\"\n\nnamespace abb\n{\nnamespace egm\n{\n/***********************************************************************************************************************\n * Math functions\n */\n\ndouble saturate(const double value, const double lower, const double upper)\n{\n  return (value < lower ? lower : (value > upper ? upper : value));\n}\n\nvoid multiply(wrapper::Joints* p_j, const double factor)\n{\n  if (p_j)\n  {\n    for (int i = 0; i < p_j->values_size(); ++i)\n    {\n      p_j->set_values(i, p_j->values(i)*factor);\n    }\n  }\n}\n\nvoid multiply(wrapper::Cartesian* p_c, const double factor)\n{\n  if (p_c)\n  {\n    p_c->set_x(p_c->x()*factor);\n    p_c->set_y(p_c->y()*factor);\n    p_c->set_z(p_c->z()*factor);\n  }\n}\n\nvoid multiply(wrapper::Euler* p_e, const double factor)\n{\n  if (p_e)\n  {\n    p_e->set_x(p_e->x()*factor);\n    p_e->set_y(p_e->y()*factor);\n    p_e->set_z(p_e->z()*factor);\n  }\n}\n\nvoid multiply(wrapper::Quaternion* p_q, const double factor)\n{\n  if (p_q)\n  {\n    p_q->set_u0(p_q->u0()*factor);\n    p_q->set_u1(p_q->u1()*factor);\n    p_q->set_u2(p_q->u2()*factor);\n    p_q->set_u3(p_q->u3()*factor);\n  }\n}\n\nwrapper::Quaternion multiply(const wrapper::Quaternion& q1, const wrapper::Quaternion& q2)\n{\n  wrapper::Quaternion result;\n\n  result.set_u0(q1.u0()*q2.u0() - q1.u1()*q2.u1() - q1.u2()*q2.u2() - q1.u3()*q2.u3());\n  result.set_u1(q1.u0()*q2.u1() + q1.u1()*q2.u0() + q1.u2()*q2.u3() - q1.u3()*q2.u2());\n  result.set_u2(q1.u0()*q2.u2() + q1.u2()*q2.u0() + q1.u3()*q2.u1() - q1.u1()*q2.u3());\n  result.set_u3(q1.u0()*q2.u3() + q1.u3()*q2.u0() + q1.u1()*q2.u2() - q1.u2()*q2.u1());\n  \n  return result;\n}\n\ndouble dotProduct(const wrapper::Quaternion& q1, const wrapper::Quaternion& q2)\n{\n  return q1.u0()*q2.u0() + q1.u1()*q2.u1() + q1.u2()*q2.u2() + q1.u3()*q2.u3();\n}\n\ndouble euclideanNorm(const wrapper::Quaternion& q)\n{\n  return std::sqrt(dotProduct(q, q));\n}\n\nvoid normalize(wrapper::Quaternion* p_q)\n{\n  if (p_q)\n  {\n    double norm = euclideanNorm(*p_q);\n    if (norm != 0.0)\n    {\n      p_q->set_u0(p_q->u0() / norm);\n      p_q->set_u1(p_q->u1() / norm);\n      p_q->set_u2(p_q->u2() / norm);\n      p_q->set_u3(p_q->u3() / norm);\n    }\n  }\n}\n\nvoid convert(wrapper::Quaternion* p_q, const wrapper::Euler& e)\n{\n  if (p_q)\n  {\n    double z = e.z() * Constants::Conversion::DEG_TO_RAD;\n    double y = e.y() * Constants::Conversion::DEG_TO_RAD;\n    double x = e.x() * Constants::Conversion::DEG_TO_RAD;\n\n    // Convert ZYX Euler angles to a rotation matrix.\n    // See for example https://en.wikipedia.org/wiki/Conversion_between_quaternions_and_Euler_angles for the equations.\n\n    double cx = std::cos(0.5*x);\n    double sx = std::sin(0.5*x);\n    double cy = std::cos(0.5*y);\n    double sy = std::sin(0.5*y);\n    double cz = std::cos(0.5*z);\n    double sz = std::sin(0.5*z);\n\n    p_q->set_u0(sx*sy*sz + cx*cy*cz);\n    p_q->set_u1(-cx*sy*sz + sx*cy*cz);\n    p_q->set_u2(sx*cy*sz + cx*sy*cz);\n    p_q->set_u3(cx*cy*sz - sx*sy*cz);\n\n    normalize(p_q);\n  }\n}\n\nvoid convert(wrapper::Euler* p_e, const wrapper::Quaternion& q)\n{\n  if(p_e && euclideanNorm(q) != 0.0)\n  {\n    // Convert a quaternion to ZYX Euler angles.\n    // See for example https://en.wikipedia.org/wiki/Conversion_between_quaternions_and_Euler_angles for the equations.\n    //\n    // Handle singularities.\n    // See for example http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToEuler/index.htm\n    // for indications of how to derive the equations.\n\n    double y = 0.0;\n    double z = 0.0;\n    double x = 0.0;\n\n    double u0 = q.u0();\n    double u1 = q.u1();\n    double u2 = q.u2();\n    double u3 = q.u3();\n\n    const double SINGULARITY_THRESHOLD = 0.000001;\n    double singularity_check = u0*u2 - u1*u3;\n\n    // Check for singularity (i.e. when y is close to +- 90 degrees).\n    // This occur when the argument of y = sin(2*(u0*u2 - u1*u3)) is close to 1.0 -> u0*u2 - u1*u3 = 0.5.\n    if (std::abs(singularity_check - 0.5) <= SINGULARITY_THRESHOLD)\n    {\n      // Y is close to 90 degrees.\n      x = 2.0*std::atan2(u1, u0);\n      y = M_PI_2;\n    }\n    else if (std::abs(singularity_check + 0.5) <= SINGULARITY_THRESHOLD)\n    {\n      // Y is close to -90 degrees.\n      x = 2.0*std::atan2(u1, u0);\n      y = -M_PI_2;\n    }\n    else\n    {\n      x = std::atan2(2.0*(u0*u1 + u2*u3), 1.0 - 2.0*(u1*u1 + u2*u2));\n      y = std::asin(2.0*(u0*u2 - u1*u3));\n      z = std::atan2(2.0*(u0*u3 + u1*u2), 1.0 - 2.0*(u2*u2 + u3*u3));\n    }\n\n    p_e->set_x(x*Constants::Conversion::RAD_TO_DEG);\n    p_e->set_y(y*Constants::Conversion::RAD_TO_DEG);\n    p_e->set_z(z*Constants::Conversion::RAD_TO_DEG);\n  }\n}\n\nvoid convert(wrapper::Quaternion* p_dq, const wrapper::Quaternion& previous_q, const wrapper::Euler& av)\n{\n  if (p_dq)\n  {\n    wrapper::Quaternion temp;\n    temp.set_u0(0.0);\n    temp.set_u1(av.x()*Constants::Conversion::DEG_TO_RAD);\n    temp.set_u2(av.y()*Constants::Conversion::DEG_TO_RAD);\n    temp.set_u3(av.z()*Constants::Conversion::DEG_TO_RAD);\n\n    p_dq->CopyFrom(multiply(temp, previous_q));\n    multiply(p_dq, 0.5);\n  }\n}\n\n\n\n\n/***********************************************************************************************************************\n * Estimation functions\n */\n \nbool estimateVelocities(wrapper::Joints* p_estimate,\n                        const wrapper::Joints& current,\n                        const wrapper::Joints& previous,\n                        const double sample_time)\n{\n  bool success = false;\n  double delta_speed = 0.0;\n\n  if (p_estimate && sample_time > 0.0)\n  {\n    p_estimate->Clear();\n    \n    for (int i = 0; i < current.values_size() && i < previous.values_size(); ++i)\n    {\n      delta_speed = current.values(i) - previous.values(i);\n      p_estimate->add_values(delta_speed / sample_time);\n    }\n    success = true;\n  }\n\n  return success;\n}\n\nbool estimateVelocities(wrapper::Euler* p_estimate,\n                        const wrapper::Quaternion& current,\n                        const wrapper::Quaternion& previous,\n                        const double sample_time)\n{\n  bool success = false;\n\n  if (p_estimate && sample_time > 0.0)\n  {\n    // Estimate the angular velocity.\n    // See for example https://en.wikipedia.org/wiki/Rotation_formalisms_in_three_dimensions for equations.\n    // Note: Only valid for orientations, for the same object, at two points close in time.\n    // Also assumes constant angular velocity between the points.\n    boost::math::quaternion<double> q1(previous.u0(), previous.u1(),\n                                       previous.u2(), previous.u3());\n    \n    boost::math::quaternion<double> q2(current.u0(), current.u1(),\n                                       current.u2(), current.u3());\n\n    boost::math::quaternion<double> estimation = ((2.0*(q2 - q1) / sample_time)*boost::math::conj(q1));\n\n    p_estimate->set_x(estimation.R_component_2()*Constants::Conversion::RAD_TO_DEG);\n    p_estimate->set_y(estimation.R_component_3()*Constants::Conversion::RAD_TO_DEG);\n    p_estimate->set_z(estimation.R_component_4()*Constants::Conversion::RAD_TO_DEG);\n\n    success = true;\n  }\n\n  return success;\n}\n\nbool estimateVelocities(wrapper::CartesianVelocity* p_estimate,\n                        const wrapper::CartesianPose& current,\n                        const wrapper::CartesianPose& previous,\n                        const double sample_time)\n{\n  bool success = false;\n\n  if (p_estimate && sample_time > 0.0)\n  {\n    // Estimate the linear velocity.\n    p_estimate->mutable_linear()->set_x((current.position().x() - previous.position().x()) / sample_time);\n    p_estimate->mutable_linear()->set_y((current.position().y() - previous.position().y()) / sample_time);\n    p_estimate->mutable_linear()->set_z((current.position().z() - previous.position().z()) / sample_time);\n\n    // Estimate the angular velocity.\n    success = estimateVelocities(p_estimate->mutable_angular(),\n                                 current.quaternion(),\n                                 previous.quaternion(),\n                                 sample_time);\n  }\n\n  return success;\n}\n\n\n\n\n/***********************************************************************************************************************\n * Find functions\n */\n\ndouble findMaxDifference(const wrapper::Joints& j1, const wrapper::Joints& j2)\n{\n  double max_difference = 0.0;\n\n  for (int i = 0; i < j1.values_size() && i < j2.values_size(); ++i)\n  {\n    max_difference = std::max(max_difference, std::abs(j1.values(i) - j2.values(i)));\n  }\n\n  return max_difference;\n}\n\ndouble findMaxDifference(const wrapper::Cartesian& c1, const wrapper::Cartesian& c2)\n{\n  double max_difference = std::abs(c1.x() - c2.x());\n  max_difference = std::max(max_difference, std::abs(c1.y() - c2.y()));\n  max_difference = std::max(max_difference, std::abs(c1.z() - c2.z()));\n\n  return max_difference;\n}\n\ndouble findMaxDifference(const wrapper::Euler& e1, const wrapper::Euler& e2)\n{\n  double max_difference = std::abs(e1.x() - e2.x());\n  max_difference = std::max(max_difference, std::abs(e1.y() - e2.y()));\n  max_difference = std::max(max_difference, std::abs(e1.z() - e2.z()));\n\n  return max_difference;\n}\n\n\n\n\n/***********************************************************************************************************************\n * Copy functions\n */\n\nvoid copyPresent(wrapper::Joints* p_target, const wrapper::Joints& source)\n{\n  if (p_target)\n  {\n    for (int i = 0; i < source.values_size() && i < p_target->values_size(); ++i)\n    {\n      p_target->set_values(i, source.values(i));\n    }\n  }\n}\n\nvoid copyPresent(wrapper::JointSpace* p_target, const wrapper::JointSpace& source)\n{\n  if (p_target)\n  {\n    if (source.has_position())\n    {\n      copyPresent(p_target->mutable_position(), source.position());\n    }\n\n    if (source.has_velocity())\n    {\n      copyPresent(p_target->mutable_velocity(), source.velocity());\n    }\n  }\n}\n\nvoid copyPresent(wrapper::Cartesian* p_target, const wrapper::Cartesian& source)\n{\n  if (p_target)\n  {\n    if (source.has_x())\n    {\n      p_target->set_x(source.x());\n    }\n\n    if (source.has_y())\n    {\n      p_target->set_y(source.y());\n    }\n\n    if (source.has_z())\n    {\n      p_target->set_z(source.z());\n    }\n  }\n}\n\nvoid copyPresent(wrapper::Euler* p_target, const wrapper::Euler& source)\n{\n  if (p_target)\n  {\n    if (source.has_x())\n    {\n      p_target->set_x(source.x());\n    }\n\n    if (source.has_y())\n    {\n      p_target->set_y(source.y());\n    }\n\n    if (source.has_z())\n    {\n      p_target->set_z(source.z());\n    }\n  }\n}\n\nvoid copyPresent(wrapper::Quaternion* p_target, const wrapper::Quaternion& source)\n{\n  if (p_target)\n  {\n    if (source.has_u0())\n    {\n      p_target->set_u0(source.u0());\n    }\n\n    if (source.has_u1())\n    {\n      p_target->set_u1(source.u1());\n    }\n\n    if (source.has_u2())\n    {\n      p_target->set_u2(source.u2());\n    }\n\n    if (source.has_u3())\n    {\n      p_target->set_u3(source.u3());\n    }\n\n    normalize(p_target);\n  }\n}\n\nvoid copyPresent(wrapper::CartesianPose* p_target, const wrapper::CartesianPose& source)\n{\n  if (p_target)\n  {\n    if (source.has_position())\n    {\n      copyPresent(p_target->mutable_position(), source.position());\n    }\n\n    if (source.has_euler())\n    {\n      copyPresent(p_target->mutable_euler(), source.euler());\n      convert(p_target->mutable_quaternion(), p_target->euler());\n    }\n    else if (source.has_quaternion())\n    {\n      copyPresent(p_target->mutable_quaternion(), source.quaternion());\n      normalize(p_target->mutable_quaternion());\n      convert(p_target->mutable_euler(), p_target->quaternion());\n    }\n  }\n}\n\nvoid copyPresent(wrapper::CartesianVelocity* p_target, const wrapper::CartesianVelocity& source)\n{\n  if (p_target)\n  {\n    if (source.has_linear())\n    {\n      copyPresent(p_target->mutable_linear(), source.linear());\n    }\n\n    if (source.has_angular())\n    {\n      copyPresent(p_target->mutable_angular(), source.angular());\n    }\n  }\n}\n\nvoid copyPresent(wrapper::CartesianSpace* p_target, const wrapper::CartesianSpace& source)\n{\n  if (p_target)\n  {\n    if (source.has_pose())\n    {\n      copyPresent(p_target->mutable_pose(), source.pose());\n    }\n\n    if (source.has_velocity())\n    {\n      copyPresent(p_target->mutable_velocity(), source.velocity());\n    }\n  }\n}\n\nvoid copyPresent(wrapper::Robot* p_target, const wrapper::Robot& source)\n{\n  if (p_target)\n  {\n    if (source.has_joints())\n    {\n      copyPresent(p_target->mutable_joints(), source.joints());\n    }\n\n    if (source.has_cartesian())\n    {\n      copyPresent(p_target->mutable_cartesian(), source.cartesian());\n    }\n  }\n}\n\nvoid copyPresent(wrapper::External* p_target, const wrapper::External& source)\n{\n  if (p_target)\n  {\n    if (source.has_joints())\n    {\n      copyPresent(p_target->mutable_joints(), source.joints());\n    }\n  }\n}\n\nvoid copyPresent(wrapper::Output* p_target, const wrapper::Output& source)\n{\n  if (p_target)\n  {\n    if (source.has_robot())\n    {\n      copyPresent(p_target->mutable_robot(), source.robot());\n    }\n\n    if (source.has_external())\n    {\n      copyPresent(p_target->mutable_external(), source.external());\n    }\n  }\n}\n\n\n\n\n/***********************************************************************************************************************\n * Parse functions\n */\n\nbool parse(wrapper::Header* p_target, const EgmHeader& source)\n{\n  bool success = false;\n\n  if (p_target && source.has_seqno() && source.has_tm() && source.has_mtype())\n  {\n    p_target->set_sequence_number(source.seqno());\n    p_target->set_time_stamp(source.tm());\n\n    switch (source.mtype())\n    {\n      case EgmHeader_MessageType_MSGTYPE_DATA:\n      {\n        p_target->set_message_type(wrapper::Header_MessageType_DATA);\n        success = true;\n      }\n      break;\n\n      case EgmHeader_MessageType_MSGTYPE_UNDEFINED:\n      case EgmHeader_MessageType_MSGTYPE_COMMAND:\n      case EgmHeader_MessageType_MSGTYPE_CORRECTION:\n      case EgmHeader_MessageType_MSGTYPE_PATH_CORRECTION:\n      default:\n      {\n        p_target->set_message_type(wrapper::Header_MessageType_UNDEFINED);\n      }\n    }\n  }\n\n  return success;\n}\n\nbool parse(wrapper::Status* p_target, const EgmRobot& source)\n{\n  bool success = false;\n\n  if (p_target &&\n      source.has_motorstate() && source.motorstate().has_state() &&\n      source.has_mcistate() && source.mcistate().has_state() &&\n      source.has_rapidexecstate() && source.rapidexecstate().has_state() &&\n      source.has_mciconvergencemet())\n  {\n    switch (source.motorstate().state())\n    {\n      case EgmMotorState_MotorStateType_MOTORS_UNDEFINED:\n      {\n        p_target->set_motor_state(wrapper::Status_MotorState_MOTORS_UNDEFINED);\n      }\n      break;\n\n      case EgmMotorState_MotorStateType_MOTORS_ON:\n      {\n        p_target->set_motor_state(wrapper::Status_MotorState_MOTORS_ON);\n      }\n      break;\n\n      case EgmMotorState_MotorStateType_MOTORS_OFF:\n      {\n        p_target->set_motor_state(wrapper::Status_MotorState_MOTORS_OFF);\n      }\n      break;\n\n      default:\n      {\n        p_target->set_motor_state(wrapper::Status_MotorState_MOTORS_UNDEFINED);\n      }\n    }\n    \n    switch (source.mcistate().state())\n    {\n      case EgmMCIState_MCIStateType_MCI_UNDEFINED:\n      {\n        p_target->set_egm_state(wrapper::Status_EGMState_EGM_UNDEFINED);\n      }\n      break;\n\n      case EgmMCIState_MCIStateType_MCI_ERROR:\n      {\n        p_target->set_egm_state(wrapper::Status_EGMState_EGM_ERROR);\n      }\n      break;\n\n      case EgmMCIState_MCIStateType_MCI_STOPPED:\n      {\n        p_target->set_egm_state(wrapper::Status_EGMState_EGM_STOPPED);\n      }\n      break;\n\n      case EgmMCIState_MCIStateType_MCI_RUNNING:\n      {\n        p_target->set_egm_state(wrapper::Status_EGMState_EGM_RUNNING);\n      }\n      break;\n\n      default:\n      {\n        p_target->set_egm_state(wrapper::Status_EGMState_EGM_UNDEFINED);\n      }\n    }\n\n    switch (source.rapidexecstate().state())\n    {\n      case EgmRapidCtrlExecState_RapidCtrlExecStateType_RAPID_UNDEFINED:\n      {\n        p_target->set_rapid_execution_state(wrapper::Status_RAPIDExecutionState_RAPID_UNDEFINED);\n      }\n      break;\n\n      case EgmRapidCtrlExecState_RapidCtrlExecStateType_RAPID_STOPPED:\n      {\n        p_target->set_rapid_execution_state(wrapper::Status_RAPIDExecutionState_RAPID_STOPPED);\n      }\n      break;\n\n      case EgmRapidCtrlExecState_RapidCtrlExecStateType_RAPID_RUNNING:\n      {\n        p_target->set_rapid_execution_state(wrapper::Status_RAPIDExecutionState_RAPID_RUNNING);\n      }\n      break;\n      \n      default:\n      {\n        p_target->set_rapid_execution_state(wrapper::Status_RAPIDExecutionState_RAPID_UNDEFINED);\n      }\n    }\n  \n    p_target->set_egm_convergence_met(source.mciconvergencemet());\n\n    success = true;\n  }\n\n  return success;\n}\n\nbool parse(wrapper::Clock* p_target, const EgmClock& source)\n{\n  bool success = true;\n\n  if (p_target && source.has_sec() && source.has_usec())\n  {\n    p_target->set_sec(source.sec());\n    p_target->set_usec(source.usec());\n  }\n  else\n  {\n    success = false;\n  }\n\n  return success;\n}\n\nbool parse(wrapper::Joints* p_target_robot,\n           wrapper::Joints* p_target_external,\n           const EgmJoints& source_robot,\n           const EgmJoints& source_external,\n           const RobotAxes axes)\n{\n  bool success = false;\n\n  if (p_target_robot && p_target_external)\n  {\n    p_target_robot->Clear();\n    p_target_external->Clear();\n\n    switch (axes)\n    {\n      case Six:\n      {\n        if (source_robot.joints_size() == Constants::RobotController::DEFAULT_NUMBER_OF_ROBOT_JOINTS)\n        {\n          for (int i = 0; i < source_robot.joints_size(); ++i)\n          {\n            p_target_robot->add_values(source_robot.joints(i));\n          }\n\n          for (int i = 0; i < source_external.joints_size(); ++i)\n          {\n            p_target_external->add_values(source_external.joints(i));\n          }\n\n          success = true;\n        }\n      }\n      break;\n\n      case Seven:\n      {\n        // If using a seven axes robot (e.g. IRB14000): Map to special case.\n        if (source_robot.joints_size() == Constants::RobotController::DEFAULT_NUMBER_OF_ROBOT_JOINTS &&\n            source_external.joints_size() >= 1)\n        {\n          p_target_robot->add_values(source_robot.joints(0));\n          p_target_robot->add_values(source_robot.joints(1));\n          p_target_robot->add_values(source_external.joints(0));\n          p_target_robot->add_values(source_robot.joints(2));\n          p_target_robot->add_values(source_robot.joints(3));\n          p_target_robot->add_values(source_robot.joints(4));\n          p_target_robot->add_values(source_robot.joints(5));\n\n          for (int i = 1; i < source_external.joints_size(); ++i)\n          {\n            p_target_external->add_values(source_external.joints(i));\n          }\n\n          success = true;\n        }\n      }\n      break;\n    }\n  }\n\n  return success;\n}\n\nbool parse(wrapper::CartesianPose* p_target, const EgmPose& source)\n{\n  bool success = true;\n\n  if (p_target)\n  {\n    p_target->Clear();\n    \n    if (source.has_pos() && source.pos().has_x() && source.pos().has_y() && source.pos().has_z())\n    {\n      p_target->mutable_position()->set_x(source.pos().x());\n      p_target->mutable_position()->set_y(source.pos().y());\n      p_target->mutable_position()->set_z(source.pos().z());\n    }\n    else\n    {\n      success = false;\n    }\n\n    if (success &&\n        source.has_orient() &&\n        source.orient().has_u0() &&\n        source.orient().has_u1() &&\n        source.orient().has_u2() &&\n        source.orient().has_u3())\n    {\n      p_target->mutable_quaternion()->set_u0(source.orient().u0());\n      p_target->mutable_quaternion()->set_u1(source.orient().u1());\n      p_target->mutable_quaternion()->set_u2(source.orient().u2());\n      p_target->mutable_quaternion()->set_u3(source.orient().u3());\n    }\n    else\n    {\n      success = false;\n    }\n\n    if (success)\n    {\n      if (source.has_euler() && source.euler().has_x() && source.euler().has_y() && source.euler().has_z())\n      {\n        p_target->mutable_euler()->set_x(source.euler().x());\n        p_target->mutable_euler()->set_y(source.euler().y());\n        p_target->mutable_euler()->set_z(source.euler().z());\n      }\n      else\n      {\n        convert(p_target->mutable_euler(), p_target->quaternion());\n      }\n    }\n  }\n\n  return success;\n}\n\nbool parse(wrapper::Feedback* p_target, const EgmFeedBack& source, const RobotAxes axes)\n{\n  bool success = false;\n\n  if (p_target)\n  {\n    success = parse(p_target->mutable_robot()->mutable_joints()->mutable_position(),\n                    p_target->mutable_external()->mutable_joints()->mutable_position(),\n                    source.joints(), source.externaljoints(), axes);\n\n    if (success)\n    {\n      success = parse(p_target->mutable_robot()->mutable_cartesian()->mutable_pose(), source.cartesian());\n\n      if (success)\n      {\n        success = parse(p_target->mutable_time(), source.time());\n      }\n    }\n  }\n\n  return success;\n}\n\nbool parse(wrapper::Planned* p_target, const EgmPlanned& source, const RobotAxes axes)\n{ \n  bool success = false;\n\n  if (p_target)\n  {\n    success = parse(p_target->mutable_robot()->mutable_joints()->mutable_position(),\n                    p_target->mutable_external()->mutable_joints()->mutable_position(),\n                    source.joints(), source.externaljoints(), axes);\n\n    if (success)\n    {\n      success = parse(p_target->mutable_robot()->mutable_cartesian()->mutable_pose(), source.cartesian());\n\n      if (success)\n      {\n        success = parse(p_target->mutable_time(), source.time());\n      }\n    }\n  }\n\n  return success;\n}\n\n\n\n\n/***********************************************************************************************************************\n * Reset functions\n */\n\nvoid reset(wrapper::Joints* p_joints, const unsigned int number_of_joints)\n{\n  if (p_joints)\n  {\n    p_joints->Clear();\n\n    for (unsigned int i = 0; i < number_of_joints; ++i)\n    {\n      p_joints->add_values(0.0);\n    }\n  }\n}\n\nvoid reset(wrapper::Cartesian* p_cartesian)\n{\n  if (p_cartesian)\n  {\n    p_cartesian->set_x(0.0);\n    p_cartesian->set_y(0.0);\n    p_cartesian->set_z(0.0);\n  }\n}\n\nvoid reset(wrapper::Euler* p_euler)\n{\n  if (p_euler)\n  {\n    p_euler->set_x(0.0);\n    p_euler->set_y(0.0);\n    p_euler->set_z(0.0);\n  }\n}\n\n} // end namespace egm\n} // end namespace abb", "meta": {"hexsha": "6086e49c23ef09060399d7e58e21631510f2640e", "size": 24781, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "abb_libegm/src/egm_common_auxiliary.cpp", "max_stars_repo_name": "JOiiNT-LAB/abb_wrapper", "max_stars_repo_head_hexsha": "68bfcded52a30a803d284f613cd1f2544c7ecc62", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2022-01-28T09:43:05.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-29T04:10:08.000Z", "max_issues_repo_path": "abb_libegm/src/egm_common_auxiliary.cpp", "max_issues_repo_name": "JOiiNT-LAB/abb_wrapper", "max_issues_repo_head_hexsha": "68bfcded52a30a803d284f613cd1f2544c7ecc62", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "abb_libegm/src/egm_common_auxiliary.cpp", "max_forks_repo_name": "JOiiNT-LAB/abb_wrapper", "max_forks_repo_head_hexsha": "68bfcded52a30a803d284f613cd1f2544c7ecc62", "max_forks_repo_licenses": ["BSD-3-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.7613390929, "max_line_length": 195, "alphanum_fraction": 0.6025584117, "num_tokens": 6392, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.734119526900183, "lm_q2_score": 0.42250463481418826, "lm_q1q2_score": 0.31016890262292646}}
{"text": "/** \\file\n* ppp.c : precise point positioning\n*\n* references :\n*    [1] D.D.McCarthy, IERS Technical Note 21, IERS Conventions 1996, July 1996\n*    [2] D.D.McCarthy and G.Petit, IERS Technical Note 32, IERS Conventions\n*        2003, November 2003\n*    [3] D.A.Vallado, Fundamentals of Astrodynamics and Applications 2nd ed,\n*        Space Technology Library, 2004\n*    [4] J.Kouba, A Guide to using International GNSS Service (IGS) products,\n*        May 2009\n*    [5] RTCM Paper, April 12, 2010, Proposed SSR Messages for SV Orbit Clock,\n*        Code Biases, URA\n*    [6] MacMillan et al., Atmospheric gradients and the VLBI terrestrial and\n*        celestial reference frames, Geophys. Res. Let., 1997\n*    [7] G.Petit and B.Luzum (eds), IERS Technical Note No. 36, IERS\n*         Conventions (2010), 2010\n*    [8] J.Kouba, A simplified yaw-attitude model for eclipsing GPS satellites,\n*        GPS Solutions, 13:1-12, 2009\n*    [9] F.Dilssner, GPS IIF-1 satellite antenna phase center and attitude\n*        modeling, InsideGNSS, September, 2010\n*    [10] F.Dilssner, The GLONASS-M satellite yaw-attitude model, Advances in\n*        Space Research, 2010\n*    [11] IGS MGEX (http://igs.org/mgex)\n*/\n\n\n#include <boost/log/trivial.hpp>\n\n#include <vector>\n\nusing std::vector;\n\n#include \"observations.hpp\"\n#include \"streamTrace.hpp\"\n#include \"linearCombo.hpp\"\n#include \"corrections.hpp\"\n#include \"navigation.hpp\"\n#include \"testUtils.hpp\"\n#include \"acsConfig.hpp\"\n#include \"biasSINEX.hpp\"\n#include \"constants.hpp\"\n#include \"satStat.hpp\"\n#include \"preceph.hpp\"\n#include \"station.hpp\"\n#include \"algebra.hpp\"\n#include \"antenna.hpp\"\n#include \"common.hpp\"\n#include \"wancorr.h\"\n#include \"mongo.hpp\"\n#include \"tides.hpp\"\n#include \"enums.h\"\n#include \"ppp.hpp\"\n#include \"vmf3.h\"\n#include \"trop.h\"\n\n#include \"eigenIncluder.hpp\"\n\n#define VAR_IONO    \tSQR(60.0)       // init variance iono-delay\n#define VAR_IONEX   \tSQR(0.0)\n#define ERR_BRDCI   \t0.5             // broadcast iono model error factor\n\n\n/** exclude meas of eclipsing satellite (block IIA)\n*/\nvoid testeclipse(\n\tObsList&\tobsList)\n{\n\tdouble erpv[5] = {0};\n\n\t/* unit vector of sun direction (ecef) */\n\tVector3d rsun;\n\tsunmoonpos(gpst2utc(obsList.front().time), erpv, &rsun);\n\tVector3d esun = rsun.normalized();\n\n\tfor (auto& obs : obsList)\n\t{\n\t\tif (obs.exclude)\n\t\t{\n\t\t\tcontinue;\n\t\t}\n\n\t\tdouble r = obs.rSat.norm();\n\t\tif (r <= 0)\n\t\t\tcontinue;\n\n\t\t/* only block IIA */\n// \t\tif (obs.satNav_ptr->pcv.type == \"BLOCK IIA\")\t\t//todo take from the satSys object\n// \t\t\tcontinue;\n\n\t\t/* sun-earth-satellite angle */\n\t\tdouble cosa = obs.rSat.dot(esun) / r;\n\t\t\n\t\tif (cosa < -1)\t\tcosa = -1;\n\t\tif (cosa > +1)\t\tcosa = +1;\n\t\t\n\t\tdouble ang = acos(cosa);\n\n\t\t/* test eclipse */\n\t\tif\t( ang < PI / 2\n\t\t\t|| r * sin(ang) > RE_WGS84)\n\t\t\tcontinue;\n\n// \t\ttrace(3, \"eclipsing sat excluded %s sat=%s\\n\", obs.time.to_string(0).c_str(), obs.Sat.id().c_str());\n\n\t\tobs.excludeEclipse = true;\n\t}\n}\n\n/** Calculate nominal yaw-angle\n*/\ndouble yaw_nominal(\n\tdouble\tbeta,\n\tdouble\tmu)\n{\n\tif\t( fabs(beta)\t< 1E-12\n\t\t&&fabs(mu)\t\t< 1E-12)\n\t\treturn PI;\n\n\treturn atan2(-tan(beta), sin(mu)) + PI;\n}\n\n/** Satellite attitude model\n*/\nint sat_yaw(\n\tGTime\t\ttime,\t\t///< Time of calculated yaw\n\tVector3d&\trSat,\t\t///< Satellite position (ECEF)\n\tVector3d&\tvSat,\t\t///< Satellite velocity (ECEF)\n\tVector3d&\texs,\t\t///< Output unit vector XS\n\tVector3d&\teys)\t\t///< Output unit vector YS\n{\n\tVector3d\trSun;\n\tdouble\t\terpv[5] = {};\n\tsunmoonpos(gpst2utc(time), erpv, &rSun);\n\n\tVector3d vSatPrime = vSat;\n\n\t/* beta and orbit angle */\n\tvSatPrime[0] -= OMGE * rSat[1];\n\tvSatPrime[1] += OMGE * rSat[0];\n\n\tVector3d n = rSat.\tcross(vSatPrime);\n\tVector3d p = rSun.\tcross(n);\n\n\tVector3d es\t\t= rSat.\tnormalized();\n\tVector3d eSun\t= rSun.\tnormalized();\n\tVector3d en\t\t= n.\tnormalized();\n\tVector3d ep\t\t= p.\tnormalized();\n\n\tdouble beta\t= PI / 2 - acos(eSun.dot(en));\n\tdouble E\t= acos(es.dot(ep));\n\tdouble mu\t= PI / 2 + (es.dot(eSun) <= 0 ? -E : E);\n\tif      (mu < -PI / 2)\t\tmu += 2 * PI;\n\telse if (mu >= PI / 2)\t\tmu -= 2 * PI;\n\n\t/* yaw-angle of satellite */\n\tdouble yaw = yaw_nominal(beta, mu);\n\n\t/* satellite fixed x,y-vector */\n\tVector3d ex = en.cross(es);\n\n\tdouble cosy = cos(yaw);\n\tdouble siny = sin(yaw);\n\n\teys = -cosy * en - siny * ex;\n\texs = -siny * en + cosy * ex;\n\n\treturn 1;\n}\n\n/** phase windup model\n*/\nint model_phw(\n\tGTime\t\ttime,\t///< Time\n\tObs&\t\tobs,\t///< Observation detailing the satellite to apply model to\n\tVector3d&\trRec,\t///< Position of receiver (ECEF)\n\tdouble&\t\tphw)\t///< Output of phase windup result\n{\n\t/* satellite yaw attitude model */\n\tVector3d exs;\n\tVector3d eys;\n\tif (!sat_yaw(time, obs.rSat, obs.satVel, exs, eys))\n\t\treturn 0;\n\n\t/* non block IIR satellites, to be refined for other constellations */\n\t/* if ((!strstr(type,\"BLOCK IIR\"))&&(sys!=SYS_GAL)) { */\n\n\t/* all the satellite orientation follow block II-A, 21/03/2019*/\n\tif (1)\n\t{\n\t\texs *= -1;\n\t\teys *= -1;\n\t}\n\n\t/* unit vector satellite to receiver */\n\tVector3d r = rRec - obs.rSat;\n\tVector3d ek = r.normalized();\n\n\t/* unit vectors of receiver antenna */\n\tdouble E[9];\n\tdouble pos[3];\n\tecef2pos(rRec.data(), pos);\n\txyz2enu(pos, E);\n\tVector3d exr;\n\tVector3d eyr;\n\texr(0) =  E[1];\n\texr(1) =  E[4];\n\texr(2) =  E[7]; /* x = north */\n\n\teyr(0) = -E[0];\n\teyr(1) = -E[3];\n\teyr(2) = -E[6]; /* y = west  */\n\n\t/* phase windup effect */\n\tVector3d eks = ek.cross(eys);\n\tVector3d ekr = ek.cross(eyr);\n\n\tVector3d ds = exs - ek * ek.dot(exs) - eks;\n\tVector3d dr = exr - ek * ek.dot(exr) + ekr;\n\tdouble cosp = ds.dot(dr) / ds.norm() / dr.norm();\n\tif      (cosp < -1) cosp = -1;\n\telse if (cosp > +1) cosp = +1;\n\tdouble ph = acos(cosp) / 2 / PI;\n\tVector3d drs = ds.cross(dr);\n\n\tif (ek.dot(drs) < 0)\n\t\tph *= -1;\n\n\tphw = ph + floor(phw - ph + 0.5); /* in cycle */\n\n\treturn 1;\n}\n\n/** get meterological parameters\n*/\nvoid getmet(\n\tdouble\tlat,\n\tdouble*\tmet)\n{\n\tconst double metprm[][10] = /* lat=15,30,45,60,75 */\n\t{\n\t\t{1013.25, 299.65, 26.31, 6.30E-3, 2.77,  0.00, 0.00, 0.00, 0.00E-3, 0.00},\n\t\t{1017.25, 294.15, 21.79, 6.05E-3, 3.15, -3.75, 7.00, 8.85, 0.25E-3, 0.33},\n\t\t{1015.75, 283.15, 11.66, 5.58E-3, 2.57, -2.25, 11.00, 7.24, 0.32E-3, 0.46},\n\t\t{1011.75, 272.15, 6.78, 5.39E-3, 1.81, -1.75, 15.00, 5.36, 0.81E-3, 0.74},\n\t\t{1013.00, 263.65, 4.11, 4.53E-3, 1.55, -0.50, 14.50, 3.39, 0.62E-3, 0.30}\n\t};\n\n\tlat = fabs(lat);\n\n\tif      (lat <= 15) for (int i = 0; i < 10; i++) met[i] = metprm[0][i];\n\telse if (lat >= 75) for (int i = 0; i < 10; i++) met[i] = metprm[4][i];\n\telse\n\t{\n\t\tint j = (int)(lat / 15);\n\t\tdouble a = (lat - j * 15) / 15.0;\n\n\t\tfor (int i = 0; i < 10; i++)\n\t\t{\n\t\t\tmet[i] = (1 - a) * metprm[j - 1][i] + a * metprm[j][i];\n\t\t}\n\t}\n}\n\n/* tropospheric delay correction -----------------------------------------------\n* compute sbas tropospheric delay correction (mops model)\n* args   : gtime_t time     I   time\n*          double   *pos    I   receiver position {lat,lon,height} (rad/m)\n*          double   *azel   I   satellite azimuth/elavation (rad)\n*          double   *var    O   variance of troposphric error (m^2)\n* return : slant tropospheric delay (m)\n*-----------------------------------------------------------------------------*/\ndouble sbstropcorr(\n\tGTime\t\t\ttime,\t\t\t///< Time\n\tVector3d&\t\trRec,\t\t\t///< Receiver position (ECEF)\n\tdouble\t\t\tel,\t\t\t\t///< Satellite elevation\n\tdouble*\t\t\tvar)\t\t\t///< Optional variance output\n{\n\tdouble pos[3];\n\tecef2pos(rRec.data(), pos);\n\tconst double k1\t= 77.604;\n\tconst double k2\t= 382000;\n\tconst double rd\t= 287.054;\n\tconst double gm\t= 9.784;\n\tconst double g\t= 9.80665;\n\n// \ttrace(4, \"sbstropcorr: pos=%.3f %.3f azel=%.3f\\n\",\n// \t\t\tpos[0]*R2D,\n// \t\t\tpos[1]*R2D,\n// \t\t\tel*R2D);\n\n\tif\t( pos[2]\t< -100\n\t\t||pos[2]\t> +10000\n\t\t||el\t\t<= 0)\n\t{\n\t\tif (var)\n\t\t\t*var = 0;\n\n\t\treturn 0;\n\t}\n\n\tdouble met[10];\n\tgetmet(pos[0] * R2D, met);\n\n\tdouble c = cos(2 * PI * (time2doy(time) - (pos[0] >= 0 ? 28 : 211)) / 365.25);\n\tfor (int i = 0; i < 5; i++)\n\t{\n\t\tmet[i] -= met[i + 5] * c;\n\t}\n\tdouble zh = 1E-6 * k1 * rd * met[0] / gm;\n\tdouble zw = 1E-6 * k2 * rd / (gm * (met[4] + 1.0) - met[3] * rd) * met[2] / met[1];\n\n\tdouble h = pos[2];\n\tzh *= pow(1 - met[3] * h / met[1], g / (rd * met[3]));\n\tzw *= pow(1 - met[3] * h / met[1], (met[4] + 1) * g / (rd * met[3]) - 1);\n\n\tdouble sinel = sin(el);\n\tdouble m = 1.001 / sqrt(0.002001 + sinel * sinel);\n\tif (var)\n\t\t*var = SQR(0.12 * m);\n\treturn (zh + zw) * m;\n}\n\n/** Antenna corrected measurement\n*/\nvoid corr_meas(\n\tTrace&\t\ttrace,\t\t///< Trace file to output to\n\tObs&\t\tobs,\t\t///< Observation to correct measurements of\n\tE_FType\t\tft,\t\t\t///< Frequency type to correct\n\tdouble\t\tel,\t\t\t///< Satellite elevation\n\tdouble\t\tdAntRec,\t///< Delta for antenna offset of receiver\n\tdouble\t\tdAntSat,\t///< Delta for antenna offset of satellite\n\tdouble\t\tphw,\t\t///< Phase wind up\n\tClockJump&\tcj,\t\t\t///< Clock jump\n\tStation&\trec)\t\t///< Receiver\n{\n\tTestStack ts(__FUNCTION__);\n\n\tSig& sig = obs.Sigs[ft];\n\n\tdouble lam = obs.satNav_ptr->lamMap[ft];\n\t\n\tif\t(  lam\t\t== 0 \n\t\t|| sig.L\t== 0 \n\t\t|| sig.P\t== 0)\n\t{\n\t\treturn;\n\t}\n\t\n\tdouble bias[2] = {};\n\tdouble bvar[2] = {};\n\t\n\tbias_io_opt biaopt;\n\tbiaopt.OSB_biases = acsConfig.ambrOpts.readOSB;\n\tbiaopt.DSB_biases = acsConfig.ambrOpts.readDSB;\n\tbiaopt.SSR_biases = acsConfig.ambrOpts.readSSRbias;\n\tbiaopt.SAT_biases = acsConfig.ambrOpts.readSATbias;\n\tbiaopt.REC_biases = acsConfig.ambrOpts.readRecBias;\n\tbiaopt.HYB_biases = acsConfig.ambrOpts.readHYBbias;\n\tbiaopt.COD_biases = true;\n\tbiaopt.PHS_biases = true;\t\n\t\n\tinpt_hard_bias(trace, obs, sig.code, bias, bvar, biaopt);\n\n\tif (acsConfig.ssrOpts.calculate_ssr)\n\t{\n\t\tdouble dummyVal = 0; // Set dummy code biases L1C & L2W to zero (not currently used)\n\t\tdouble dummyVar = 0; // Set dummy code biases L1C & L2W to zero (not currently used)\n\t\tif\t( (ft == F1 && sig.code == +E_ObsCode::L1C) \n\t\t\t||(ft == F2 && sig.code == +E_ObsCode::L2W))\n\t\t{\n\t\t\tobs.satNav_ptr->ssrOut.ssrCodeBias.canExport\t\t\t\t\t= false;\n\t\t\tobs.satNav_ptr->ssrOut.ssrCodeBias.codeBias_map[sig.code].bias\t= dummyVal;\n\t\t\tobs.satNav_ptr->ssrOut.ssrCodeBias.codeBias_map[sig.code].var\t= dummyVar;\n\t\t\tobs.satNav_ptr->ssrOut.ssrCodeBias.isSet\t\t\t\t\t\t= true;\n\t\t}\n\t}\n\t\n\t\n#if 0 /* this should not be done. Once all bias messages follow the SINEX format properly, could be activated temporaly in case Galileo L5 biases are absent */ \t\n\tif(bias[1]==0.0){\n\t\tif(obs.Sat.sys == +E_Sys::GPS) {\n\t\t\tif(ft == F1 && sig.code != +E_ObsCode::L1C) inpt_hard_bias(trace,obs,  1, bs, bsv, station, biaopt);\n\t\t\tif(ft == F1 && sig.code != +E_ObsCode::L2W) inpt_hard_bias(trace,obs, 20, bs, bsv, station, biaopt);\n\t\t}\n\t\t\n\t\tif( obs.Sat.sys == +E_Sys::GAL ){\n\t\t\tif(ft == F1 && sig.code != +E_ObsCode::L1X) inpt_hard_bias(trace,obs, 12, bs, bsv, station, biaopt);\n\t\t\tif(ft == F5 && sig.code != +E_ObsCode::L5X) inpt_hard_bias(trace,obs, 26, bs, bsv, station, biaopt);\n\t\t\tif(ft == F5 && sig.code != +E_ObsCode::L5Q) inpt_hard_bias(trace,obs, 25, bs, bsv, station, biaopt);\n\t\t\tif(ft == F5 && bs[1]    ==        0.0     )\tinpt_hard_bias(trace,obs, 24, bs, bsv, station, biaopt);\n\t\t}\n\t\tbias[1]=bs[1];\n\t\tbvar[1]=bsv[1];\n\t}\n#endif\n\t\n\ttracepdeex(3, trace, \"\\n %s  Biases for code %3d:   %9.4f %9.4f, vari: %10.4e %10.4e\", obs.Sat.id().c_str(), sig.code, bias[0], bias[1], bvar[0], bvar[1]);\n\t\n\tsig.P_corr_m = sig.P       \t- dAntSat - dAntRec - bias[0];\n\tsig.L_corr_m = sig.L * lam\t- dAntSat - dAntRec - bias[1] - phw * lam;\n\n#if 0\n\tdouble jump = cj.msJump * CLIGHT * 1e-3;\n\tsig.P_corr_m+=jump;\n\tsig.L_corr_m+=jump;\n#endif\n\t\n}\n\n\n/* satellite antenna phase center variation ----------------------------------*/\nvoid satantpcv(\n\tVector3d&\t\t\trs,\n\tVector3d&\t\t\trr,\n\tPhaseCenterData&\t\t\tpcv,\n\tmap<int, double>&\tdAntSat,\n\tdouble*\t\t\t\tnad)\n{\n\tVector3d ru = rr - rs;\n\tVector3d rz = -rs;\n\tVector3d eu = ru.normalized();\n\tVector3d ez = rz.normalized();\n\n\tdouble cosa = eu.dot(ez);\n\tif (cosa < -1)\tcosa = -1;\n\tif (cosa > +1)\tcosa = +1;\n\n\tdouble nadir = acos(cosa);\n\tif (nad)\n\t\t*nad = nadir * R2D;\n\n\tinterp_satantmodel(pcv, nadir, dAntSat);\n\t//antmodel_s(pcv,nadir,dAntSat);\n}\n\n/* precise tropospheric model ------------------------------------------------*/\ndouble trop_model_prec(\n\tGTime\t\ttime,\n\tdouble*\t\tpos,\n\tdouble*\t\tazel,\n\tdouble*\t\ttropStates,\n\tdouble*\t\tdTropDx,\n\tdouble&\t\tvar)\n{\n\tdouble map[2] = {};\n\n\t/* zenith hydrostatic delay */\n\tdouble zhd = tropacs(pos, azel, map);\n\n\tdouble zwd = tropStates[0] - zhd;\n\t\n\tif\t( acsConfig.process_user\n\t\t||acsConfig.process_ppp)\n\t{\n\t\t/* mapping function */\n\t\tdouble m_w;\n\t\tdouble m_h = tropmapf(time, pos, azel, &m_w);\n\n\t\tdouble& az = azel[0];\n\t\tdouble& el = azel[1];\n\t\t\n\t\tdouble m_az = 0;\n\t\t\n\t\tif (el > 0)\n\t\tif (el < 0.9999 * PI/2)\n\t\t{\n\t\t\tdouble c = 0.0031;\n\t\t\tm_az = 1 / (sin(el) * tan(el) + c);\n\t\t}\n\t\t\n\t\tdouble grad_n = m_az * cos(az);\n\t\tdouble grad_e = m_az * sin(az);\n\n\t\tvar\t\t\t= SQR(0.01);\t\t//todo aaron, move this somewhere else, should use trop state variance?\n\t\t\n\t\tdouble value\t= m_h\t\t* zhd\n\t\t\t\t\t\t+ m_w\t\t* zwd\n\t\t\t\t\t\t+ grad_n\t* tropStates[1]\n\t\t\t\t\t\t+ grad_e\t* tropStates[2];\n\t\t\t\t\t\t\n\t\tdTropDx[0] = m_w;\n\t\tdTropDx[1] = grad_n;\n\t\tdTropDx[2] = grad_e;\n\t\t\n\t\treturn value;\n\t}\n\telse\n\t{\n\t\t/* wet mapping function */\n\t\tdTropDx[0]\t= map[1];\n\t\tvar\t\t\t= SQR(0.01);\n\n\t\treturn map[0] * zhd;\n\t}\n}\n\n/* ionospheric model ---------------------------------------------------------*/\nint model_iono(\n\tGTime\t\ttime,\n\tdouble*\t\tpos,\n\tdouble*\t\tazel,\n\tdouble\t\tionoState,\n\tdouble&\t\tdion,\n\tdouble&\t\tvar)\n{\n\tswitch (acsConfig.ionoOpts.corr_mode)\n\t{\n\t\tcase E_IonoMode::TOTAL_ELECTRON_CONTENT:\n\t\t{\n\t\t\tint res = iontec(time, &nav, pos, azel, 1, dion, var);\n\t\t\tif (res)\tvar +=\tVAR_IONEX;\t\t\t// adding some extra errors to reflect modelling errors\n\t\t\telse\t\tvar =\tVAR_IONO;\n\n\t\t\treturn res;\n\t\t}\n\t\tcase E_IonoMode::BROADCAST:\n\t\t{\n\t\t\tdion\t= ionmodel(time, nav.ion_gps, pos, azel);\n\t\t\tvar\t\t= SQR(dion * ERR_BRDCI);\n\n\t\t\treturn 1;\n\t\t}\n\t\tcase E_IonoMode::ESTIMATE:\n\t\t{\n\t\t\tdion\t= ionoState;\n\t\t\tvar\t\t= 0;\n\n\t\t\treturn 1;\n\t\t}\n\t\tcase E_IonoMode::IONO_FREE_LINEAR_COMBO:\n\t\t{\n\t\t\tdion\t= 0;\n\t\t\tvar\t\t= 0;\n\n\t\t\treturn 1;\n\t\t}\n\t\tcase E_IonoMode::OFF:\n\t\t{\n\t\t\treturn 0;\n\t\t}\n\t}\n\n\treturn 0;\n}\n\nvoid pppCorrections(\n\tTrace&\t\ttrace,\n\tObsList&\tobsList,\n\tVector3d&\trRec,\n\trtk_t&\t\trtk,\n\tStation&\trec)\n{\n\tTestStack ts(__FUNCTION__);\n\n\tint lv = 3;\n\n\tdouble ep[6];\n\ttime2epoch(obsList.front().time, ep);\n\tdouble jd\t= ymdhms2jd(ep);\n\tdouble mjd\t= jd - JD2MJD;\n\n\n\tdouble pos[3];\n\tecef2pos(rRec.data(), pos);\n\n\ttracepde(3,trace, \"pppCorrections  : n=%d\\n\", obsList.size());\n\n\tfor (auto& obs : obsList)\n\t{\n\t\tif (obs.exclude)\n\t\t{\n\t\t\tcontinue;\n\t\t}\n\n\t\tTestStack ts(obs.Sat);\n\t\tSatStat&\tsatStat\t= *(obs.satStat_ptr);\n\t\tauto&\t\tlam\t\t= obs.satNav_ptr->lamMap;\n\n\t\tdouble r = geodist(obs.rSat, rRec, satStat.e);\t\t\t\t\t\tTestStack::testMat(\"r\",\t\tr);\n\t\tif \t( r <= 0\n\t\t\t||satStat.el < acsConfig.elevation_mask)\n\t\t{\n\t\t\tobs.excludeElevation = true;\n\t\t\tcontinue;\n\t\t}\n\n\t\tif\t(satexclude(obs.Sat, obs.svh))\n\t\t{\n\t\t\tobs.exclude = true;\n\t\t\tcontinue;\n\t\t}\n\n// \t\tif (acsConfig.antexacs == 0)\n// \t\t{\n// \t\t\tstd::cout << \" Using antmodel() \" << std::endl;\t\t\t//todo aaron, broke this.\n// \t\t\tantmodel(opt->pcvr, opt->antdel, obs.azel, opt->posopt[1], dAntRec);\n// \t\t}\n\n\t\t//satellite and receiver antenna model\n\t\tmap<int, double> dAntSat;\n\t\tif\t(acsConfig.sat_pcv)\n\t\t{\n\t\t\tPhaseCenterData* pcvsat = findAntenna(obs.Sat.id(), obs.time, nav);\n\t\t\tif (pcvsat)\n\t\t\t{\n\t\t\t\tsatantpcv(obs.rSat, rRec, *pcvsat, dAntSat);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\ttracepde(1, trace,\t\"Warning: no satellite (%s) pcv information\\n\",\tobs.Sat.id().c_str());\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t}\n\n\t\t// phase windup model\n\t\tif (acsConfig.phase_windup)\n\t\t{\n\t\t\tbool pass = model_phw(rtk.sol.time, obs, rRec, satStat.phw);\n\t\t\tif (pass == false)\n\t\t\t{\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t}\n\n\t\tmap<int, double> dAntRec;\n\n\t\tfor (auto& [ft, sig] : obs.Sigs)\n\t\t{\n\t\t\tTestStack ts(\"F\" + std::to_string(ft));\n\n\t\t\tsig.Range = r;\n\n\t\t\tdouble rpcv = 0;\n\n\t\t\t/* receiver pco correction to the coordinates */\n\t\t\tif (rtk.pcvrec)\n\t\t\t{\n\t\t\t\tVector3d pco_r;\n\t\t\t\tVector3d dr2;\n\n\t\t\t\trecpco(rtk.pcvrec, ft, pco_r);\n\t\t\t\tenu2ecef(pos, pco_r.data(), dr2.data());    /* convert enu to xyz */\n\n\t\t\t\t/* get rec position and geometric distance for each frequency */\n\t\t\t\tVector3d rRecFreq = rRec + dr2;\n\n\t\t\t\tsig.Range = geodist(obs.rSat, rRecFreq, satStat.e);\n\n\t\t\t\t/* calculate pcv */\n\t\t\t\tdouble azDeg = satStat.az * R2D;\n\t\t\t\tdouble elDeg = satStat.el * R2D;\n\t\t\t\trecpcv(rtk.pcvrec, ft, elDeg, azDeg, rpcv);\n\t\t\t\tdAntRec[ft] = rpcv;\n\n\t\t\t\t\t\t\t\t\t\t\t\tTestStack::testMat(\"obs.rSat\",\tobs.rSat);\n\t\t\t\t\t\t\t\t\t\t\t\tTestStack::testMat(\"rRecFreq\",\trRecFreq);\n\t\t\t\t\t\t\t\t\t\t\t\tTestStack::testMat(\"rRec\",\t    rRec);\n\t\t\t\t\t\t\t\t\t\t\t\tTestStack::testMat(\"dr2\",\t     dr2);\n\t\t\t\t\t\t\t\t\t\t\t\tTestStack::testMat(\"sig.Range\",\tsig.Range);\n\t\t\t}\n\t\t\t// corrected phase and code measurements\n\t\t\tClockJump cj = {};\n\t\t\tcorr_meas(trace, obs, ft, satStat.el, dAntRec[ft], dAntSat[ft], satStat.phw, cj, rec);\n\n\t\t\ttracepde(lv, trace, \"*---------------------------------------------------*\\n\");\n\t\t\ttracepde(lv, trace, \" %.6f %sL%d satpcv              = %14.4f\\n\",                       mjd, obs.Sat.id().c_str(), ft, dAntSat[ft]);\n\t\t\ttracepde(lv, trace, \" %.6f %sL%d recpcv              = %14.4f\\n\",                       mjd, obs.Sat.id().c_str(), ft, dAntRec[ft]);\n\t\t\ttracepde(lv, trace, \" %.6f %sL%d az, el              = %14.4f %14.4f\\n\",                mjd, obs.Sat.id().c_str(), ft, satStat.az*R2D, satStat.el*R2D);\n\t\t\ttracepde(lv, trace, \" %.6f %sL%d phw(cycle)          = %14.4f \\n\",                      mjd, obs.Sat.id().c_str(), ft, satStat.phw);\n\t\t\ttracepde(lv, trace, \" %.6f %sL%d satpos+pco          = %14.4f %14.4f %14.4f\\n\",         mjd, obs.Sat.id().c_str(), ft, obs.rSat[0], obs.rSat[1], obs.rSat[2]);\n\t\t\ttracepde(lv, trace, \" %.6f %sL%d dist                = %14.4f\\n\",                       mjd, obs.Sat.id().c_str(), ft, r);\n\n\n\t\t\t\t\t\t\t\tTestStack::testMat(\"dAntRec\",\tdAntRec[ft]);\n\t\t\t\t\t\t\t\tTestStack::testMat(\"dAntSat\",\tdAntSat[ft]);\n\t\t}\n\n\t\tif (acsConfig.ionoOpts.corr_mode == +E_IonoMode::IONO_FREE_LINEAR_COMBO)\n\t\tfor (E_FType ft : {F2, F5})\n\t\t{\n\t\t\t/* iono-free LC */\n\t\t\tSig sig1 = obs.Sigs[F1];\n\t\t\tSig sig2 = obs.Sigs[ft];\n\n\t\t\tif\t( lam[F1] == 0\n\t\t\t\t||lam[ft] == 0)\n\t\t\t\tcontinue;\n\n\t\t\tif\t( (sig1.L_corr_m == 0)\n\t\t\t\t||(sig1.P_corr_m == 0)\n\t\t\t\t||(sig2.L_corr_m == 0)\n\t\t\t\t||(sig2.P_corr_m == 0))\n\t\t\t{\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tdouble c1;\n\t\t\tdouble c2;\n\t\t\tS_LC lc = getLC(sig1.L_corr_m,\tsig2.L_corr_m,\n\t\t\t\t\t\t\tsig1.P_corr_m,\tsig2.P_corr_m,\n\t\t\t\t\t\t\tlam[F1],\t\tlam[ft],\n\t\t\t\t\t\t\t&c1, \t\t\t&c2);\n\n\t\t\tif (lc.valid == false)\n\t\t\t{\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tSig lcSig = {};\n\t\t\tlcSig.L_corr_m = lc.IF_Phas_m;\n\t\t\tlcSig.P_corr_m = lc.IF_Code_m;\n\n\t\t\tE_FType newType;\n\t\t\tswitch (ft)\n\t\t\t{\n\t\t\t\tcase F2: newType = FTYPE_IF12;\tbreak;\n\t\t\t\tcase F5: newType = FTYPE_IF15;\tbreak;\n\t\t\t\tdefault: continue;\n\t\t\t}\n\n\t\t\t//update distance measurement for iflc\n\t\t\tlcSig.Range\t= sig1.Range * c1\n\t\t\t\t\t\t- sig2.Range * c2;\n\n\t\t\tdouble AA = POW4(CLIGHT/lam[F1]) / POW2(POW2(CLIGHT/lam[F1]) - POW2(CLIGHT/lam[ft]));\n\t\t\tdouble BB = POW4(CLIGHT/lam[ft]) / POW2(POW2(CLIGHT/lam[F1]) - POW2(CLIGHT/lam[ft]));\n\n\t\t\tdouble A = POW4(lam[F1]) / POW2(POW2(lam[F1]) - POW2(lam[ft]));\n\t\t\tdouble B = POW4(lam[ft]) / POW2(POW2(lam[F1]) - POW2(lam[ft]));\n// \t\t\tprintf(\"\\n%f %f\\n\", A, B);\n// \t\t\tprintf(\"\\n%f %f\\n\", AA, BB);\n\t\t\tlcSig.codeVar\t= POW4(lam[F1]) * sig1.codeVar / POW2(POW2(lam[F1]) - POW2(lam[ft]))\n\t\t\t\t\t\t\t+ POW4(lam[ft]) * sig2.codeVar / POW2(POW2(lam[F1]) - POW2(lam[ft]));\n\n\t\t\tlcSig.phasVar \t= POW4(lam[F1]) * sig1.phasVar / POW2(POW2(lam[F1]) - POW2(lam[ft]))\n\t\t\t\t\t\t\t+ POW4(lam[ft]) * sig2.phasVar / POW2(POW2(lam[F1]) - POW2(lam[ft]));\n\n\t\t\tobs.Sigs[newType] = lcSig;\n\n\t\t\tobs.satStat_ptr->sigStatMap[newType].slip.any\t= obs.satStat_ptr->sigStatMap[F1].slip.any\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t| obs.satStat_ptr->sigStatMap[ft].slip.any;\n\t\t}\n\t}\n}\n\nvoid outputApriori(\n\tStationMap& stationMap)\n{\n\tKFState aprioriState;\n\tfor (auto& [id, rec] : stationMap)\n\t{\n\t\tKFKey kfKey;\n\t\tkfKey.str\t= id + \"_0\";\n\t\tkfKey.type\t= KF::REC_POS;\n\t\t\n\t\tfor (int i = 0; i < 3; i++)\n\t\t{\n\t\t\tkfKey.num = i;\n\t\t\t\n\t\t\taprioriState.addKFState(kfKey, {.x = rec.aprioriPos[i]});\n\t\t}\n\t}\n\tfor (auto& [id, rec] : stationMap)\n\t{\n\t\tKFKey kfKey;\n\t\tkfKey.str\t= id + \"_0\";\n\t\tkfKey.type\t= KF::REC_CLOCK;\n\t\t\t\n\t\tdouble precDtRec\t= 0;\n\t\tpephclk(tsync, id, nav, precDtRec);\n\n\t\taprioriState.addKFState(kfKey, {.x = CLIGHT * precDtRec});\n\t}\n\taprioriState.stateTransition(nullStream, tsync);\n\t\n#ifdef ENABLE_MONGODB\n\tmongoStates(aprioriState);\n#endif\n}\n\n/** Compare estimated station position with benchmark in SINEX file\n */\nvoid outputPPPSolution(\n\tStation& rec)\n{\n\tVector3d snxPos = rec.snx.pos;\n\tVector3d estPos = rec.rtk.sol.pppRRec;\n\tVector3d diffEcef = snxPos - estPos;\n\t\n\tdouble latLonHt[3];\n\tecef2pos(snxPos, latLonHt); // rad,rad,m\n\t\n\tdouble diffEcefArr[3];\n\tVector3d::Map(diffEcefArr, diffEcef.rows())\t= diffEcef; // equiv. to diffEcef = diff\n\t\n\tdouble diffEnuArr[3];\n\tecef2enu(latLonHt, diffEcefArr, diffEnuArr);\n\t\n\tVector3d diffEnu;\n\tdiffEnu = Vector3d::Map(diffEnuArr, diffEnu.rows());\n\n\tstd::ofstream fout(acsConfig.ppp_sol_filename, std::ios::out | std::ios::app);\n\tif (!fout)\n\t{\n\t\tBOOST_LOG_TRIVIAL(error)\n\t\t<< \"Could not open trace file for PPP solution at \" << acsConfig.ppp_sol_filename;\n\t}\n\telse\n\t{\n\t\tfout << epoch << \" \";\n\t\tfout << rec.id << \" \";\n\t\tfout << snxPos.transpose() << \" \";\n\t\tfout << estPos.transpose() << \" \";\n\t\tfout << diffEcef.transpose() << \" \";\n\t\tfout << diffEnu.transpose() << \" \";\n\t\tfout << std::endl;\n\t}\n}\n\n\nvoid selectAprioriSource(\n\tStation&\trec,\n\tbool&\t\tsppUsed)\n{\n\tsppUsed = false;\n\t\n\tif (rec.aprioriPos(2) != 0)\n\t{\n\t\t//already has apriori\n\t\treturn;\n\t}\n\t\n\tif (rec.snx.pos(2) != 0)\n\t{\n\t\trec.aprioriPos\t\t= rec.snx.pos;\n\t\trec.primaryApriori\t= rec.snx.primary;\n\t\t\n\t\tVector3d delta = rec.snx.pos - rec.rtk.sol.sppRRec;\n\t\t\n\t\tdouble distance = delta.norm();\n\t\t\n\t\tif\t( distance > 20\n\t\t\t&&rec.rtk.sol.sppRRec.norm() > 0)\n\t\t{\n\t\t\tBOOST_LOG_TRIVIAL(error)\n\t\t\t<< \"SINEX apriori for \" << rec.id << \" is \" << distance << \"m from SPP estimate\";\n\t\t}\n\t\t\n\t\treturn;\n\t}\n\telse\n\t{\n\t\trec.aprioriPos\t\t= rec.rtk.sol.sppRRec;\n\t\tsppUsed\t\t\t\t= true;\n\t}\n}\n\n/** Deweight worst measurement\n */\nbool deweightMeas(\n\tTrace&\t\ttrace,\n\tKFState&\tkfState,\n\tKFMeas&\t\tkfMeas,\n\tint\t\t\tindex)\n{\n\ttrace << std::endl << \"Deweighting \" << kfMeas.obsKeys[index] << std::endl;\n\n\tkfMeas.R.row(index) *= acsConfig.deweight_factor;\n\tkfMeas.R.col(index) *= acsConfig.deweight_factor;\n\t\n\treturn true;\n}\n\n/** Count worst measurement\n */\nbool incrementPhaseSignalError(\n\tTrace&\t\ttrace,\n\tKFState&\tkfState,\n\tKFMeas&\t\tkfMeas,\n\tint\t\t\tindex)\n{\n\tmap<string, void*>& metaDataMap = kfMeas.metaDataMaps[index];\n\n\tunsigned int* phaseRejectCount_ptr = (unsigned int*) metaDataMap[\"phaseRejectCount_ptr\"];\n\n\tif (phaseRejectCount_ptr == nullptr)\n\t{\n\t\treturn true;\n\t}\n\n\tunsigned int&\tphaseRejectCount\t= *phaseRejectCount_ptr;\n\n\t//increment counter, and clear the pointer so it cant be reset to zero in subsequent operations (because this is a failure)\n\tphaseRejectCount++;\n\tmetaDataMap[\"phaseRejectCount_ptr\"] = nullptr;\n\n\t\n\treturn true;\n}\n\nbool countSignalErrors(\n\tTrace&\t\ttrace,\n\tKFState&\tkfState,\n\tKFMeas&\t\tkfMeas,\n\tint\t\t\tindex)\n{\n\tmap<string, void*>& metaDataMap = kfMeas.metaDataMaps[index];\n\n\tObs* obs_ptr = (Obs*) metaDataMap[\"obs_ptr\"];\n\n\tif (obs_ptr == nullptr)\n\t{\n\t\treturn true;\n\t}\n\n\tObsKey&\t\tobsKey\t= kfMeas.obsKeys[index];\n\tObs&\t\tobs\t\t= *obs_ptr;\n\n\tif (obsKey.type == \"L\")\n\t{\n\t\t//this is a phase observation\n\t\tobs.Sigs[(E_FType)obsKey.num].phaseError = true;\n\t}\n\n\treturn true;\n}\n\nbool resetPhaseSignalError(\n\tKFMeas&\t\tkfMeas,\n\tint\t\t\tindex)\n{\n\tmap<string, void*>& metaDataMap = kfMeas.metaDataMaps[index];\n\n\t//this will have been set to null if there was an error after adding the measurement to the list\n\tunsigned int* phaseRejectCount_ptr = (unsigned int*) metaDataMap[\"phaseRejectCount_ptr\"];\n\n\tif (phaseRejectCount_ptr == nullptr)\n\t{\n\t\treturn true;\n\t}\n\n\tunsigned int&\tphaseRejectCount\t= *phaseRejectCount_ptr;\n\n\tphaseRejectCount = 0;\n\n\treturn true;\n}\n\nbool resetPhaseSignalOutage(\n\tKFMeas&\t\tkfMeas,\n\tint\t\t\tindex)\n{\n\tmap<string, void*>& metaDataMap = kfMeas.metaDataMaps[index];\n\n\tunsigned int* phaseOutageCount_ptr = (unsigned int*) metaDataMap[\"phaseOutageCount_ptr\"];\n\n\tif (phaseOutageCount_ptr == nullptr)\n\t{\n\t\treturn true;\n\t}\n\n\tunsigned int&\tphaseOutageCount\t= *phaseOutageCount_ptr;\n\n\tphaseOutageCount = 0;\n\n\treturn true;\n}\n\n\n", "meta": {"hexsha": "4bf3fe47628ceb4b3bc47a0f57befb61291075ae", "size": 23974, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/cpp/pea/ppp.cpp", "max_stars_repo_name": "umma-zannat/ginan", "max_stars_repo_head_hexsha": "a4d1a3bb8696267f23d26e8c6a2f6080b87bb494", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-01-12T15:14:55.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-12T15:14:55.000Z", "max_issues_repo_path": "src/cpp/pea/ppp.cpp", "max_issues_repo_name": "umma-zannat/ginan", "max_issues_repo_head_hexsha": "a4d1a3bb8696267f23d26e8c6a2f6080b87bb494", "max_issues_repo_licenses": ["Apache-2.0"], "max_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/pea/ppp.cpp", "max_forks_repo_name": "umma-zannat/ginan", "max_forks_repo_head_hexsha": "a4d1a3bb8696267f23d26e8c6a2f6080b87bb494", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-01-12T15:15:12.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-12T15:15:12.000Z", "avg_line_length": 24.6900102987, "max_line_length": 161, "alphanum_fraction": 0.6066989238, "num_tokens": 8657, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.734119526900183, "lm_q2_score": 0.42250463481418826, "lm_q1q2_score": 0.31016890262292646}}
{"text": "/**\n * gcodetimer\n *\n * Copyright © 2016 Juan Jose Gonzalez\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,\n * including without limitation the rights to use, copy, modify, merge, publish, distribute,\n * sublicense, and/or 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 all copies or\n * substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT\n * NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n */\n\n#include \"GCodeProcessorBase.h\"\n\n#include \"Utils.h\"\n#include \"Config.h\"\n\n#include <cstdio>\n#include <cstring>\n#include <string>\n#include <boost/tokenizer.hpp>\n\nusing namespace std;\nusing namespace boost;\n\nGCodeProcessorBase::GCodeProcessorBase(ifstream *input) : input(input) {}\n\nvoid GCodeProcessorBase::process_file() {\n    static const float max_jerk_magnitude = Utils::get_euclidean_length(Config::get()->max_jerk);\n    string line;\n    COORDS pos = {0.0, 0.0, 0.0, 0.0};       // mm\n    float rate = 0.0;\n    while(!(*input).eof()) {\n        float line_duration = 0.0;\n\n        getline(*input, line);\n        char_separator<char> sep(\" \");\n        tokenizer< char_separator<char> > tokens(line, sep);\n        tokenizer< char_separator<char> >::iterator token_iter = tokens.begin();\n        if (token_iter != tokens.end()) {\n            if ((*token_iter).compare(\"G1\") == 0) {     // Linear move\n                COORDS target_pos;\n\n                memcpy((void*)&target_pos, (void*)&pos, sizeof(COORDS));\n                for(++token_iter; token_iter != tokens.end(); ++token_iter) {\n                    char op;\n                    float value;\n\n                    sscanf((*token_iter).c_str(), \"%c%f\", &op, &value);\n                    switch(op) {\n                        case 'X': target_pos.x = value; break;\n                        case 'Y': target_pos.y = value; break;\n                        case 'Z': target_pos.z = value; break;\n                        case 'E': target_pos.e = value; break;\n                        case 'F': rate = value / 60; break;\n                    }\n                }\n\n                COORDS movement = Utils::get_diff(target_pos, pos);\n                float length = Utils::get_euclidean_length(movement);\n                if (length > 0) {\n                    float rate_speed_factor = Config::get()->speed_multiplier * rate / length;\n                    COORDS target_speed_components = Utils::map(movement, [=](float c) { return c * rate_speed_factor; });\n\n                    // Calculate the individual jerk components\n                    float jerk_speed_factor = max_jerk_magnitude / length;\n                    COORDS jerk_speed = Utils::map(movement, [=](float c) { return abs(c) * jerk_speed_factor; });\n\n                    // Check if the components exceed the max jerk per component. If so, reduce all\n                    // components by the required factor to comply with the max jerk settings\n                    COORDS jerk_reduce_factor = Utils::map(jerk_speed, Config::get()->max_jerk, [](float jc, float mc) { return jc > mc ? mc / jc : 1.0; });\n                    float jerk_multiplier = Utils::reduce(jerk_reduce_factor, [](float c, float factor) { return min (factor, c); }, 1.0);\n                    jerk_speed = Utils::map(jerk_speed, [=](float c) { return c * jerk_multiplier * Config::get()->jerk_efficiency; });\n\n                    // Calculate the magnitude of the final jerk vector\n                    float jerk_magnitude = Utils::get_euclidean_length(jerk_speed);\n\n                    // Calculate the speed delta for the acceleration and deceleration phase\n                    COORDS speed_delta_components = Utils::map(target_speed_components, jerk_speed, [](float sc, float jc) { return Utils::pos(abs(sc) - jc); });\n\n                    // Calculate the time required to complete the acceleration\n                    const COORDS &max_accel = movement.e != 0.0 ? Config::get()->max_print_accel : Config::get()->max_move_accel;\n                    COORDS accel_time_components = Utils::map(speed_delta_components, max_accel, [] (float sc, float ac) { return sc / ac; });\n                    float accel_time = Utils::reduce(accel_time_components, [] (float c, float t) { return max(c, t); }, accel_time_components.x);\n\n                    float accel_magnitude = 0.0;\n                    if (accel_time > EPSILON) {\n                        // Calculate the actual acceleration per component based on accel_time and speed_delta_components\n                        COORDS accel = Utils::map(speed_delta_components, [=] (float c) { return c / accel_time; });\n\n                        // Calculate the magnitude of the acceleration vector\n                        accel_magnitude = Utils::get_euclidean_length(accel) * Config::get()->accel_efficiency;\n                    } else {\n                        accel_time = 0.0;\n                    }\n\n                    float speed_magnitude = Utils::get_euclidean_length(target_speed_components);\n\n                    // Full acceleration (a*t^2 / 2) and deceleration (a*t^2 / 2) possible\n                    if (length > (2 * jerk_magnitude + accel_magnitude * accel_time) * accel_time) {\n                        line_duration = accel_time * 2 + (length - (2 * jerk_magnitude + accel_magnitude * accel_time) * accel_time) / speed_magnitude;\n\n                    } else {\n                        // l = 2 * (((t / 2) * a / 2 + js) * (t / 2)) = ((t / 4) * a + js) * t = t^2 * a / 4 + t * js\n                        // t^2 * a / 4 + t * js - l = 0 => t = (-js + sqrt(js^2 + a*l)) / 2*(a / 4)\n                        line_duration = (sqrt(jerk_magnitude * jerk_magnitude + accel_magnitude * length) - jerk_magnitude) / (accel_magnitude / 2);\n                    }\n\n                    memcpy((void*)&pos, (void*)&target_pos, sizeof(COORDS));\n                }\n            } else if ((*token_iter).compare(\"G28\") == 0) {     // Home\n                // We don't know how long this will take. Just set the position to 0 without adding any time\n                if (++token_iter == tokens.end()) {\n                    pos.x = 0;\n                    pos.y = 0;\n                    pos.z = 0;\n                }\n                for(token_iter; token_iter != tokens.end(); ++token_iter) {\n                    char op;\n                    float value;\n                    sscanf((*token_iter).c_str(), \"%c%f\", &op, &value);\n                    switch(op) {\n                        case 'X': pos.x = value; break;\n                        case 'Y': pos.y = value; break;\n                        case 'Z': pos.z = value; break;\n                    }\n                }\n            } else if ((*token_iter).compare(\"G92\") == 0) {     // Reset coords\n                if (++token_iter == tokens.end()) {\n                    memset((void*)&pos, 0, sizeof(pos));\n                }\n                for(token_iter; token_iter != tokens.end(); ++token_iter) {\n                    char op;\n                    float value;\n                    sscanf((*token_iter).c_str(), \"%c%f\", &op, &value);\n                    switch(op) {\n                        case 'X': pos.x = value; break;\n                        case 'Y': pos.y = value; break;\n                        case 'Z': pos.z = value; break;\n                        case 'E': pos.e = value; break;\n                    }\n                }\n            }\n        }\n        process_line(line, line_duration);\n    }\n}\n", "meta": {"hexsha": "305ad2e685399dfdeaeacd3a28f66b1646c634e0", "size": 8089, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/GCodeProcessorBase.cc", "max_stars_repo_name": "gonzalezjj/gcodetimer", "max_stars_repo_head_hexsha": "c53073f1d84363e5be290f0ccc312e6dc31898fa", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2016-07-24T11:15:45.000Z", "max_stars_repo_stars_event_max_datetime": "2016-07-24T11:15:45.000Z", "max_issues_repo_path": "src/GCodeProcessorBase.cc", "max_issues_repo_name": "gonzalezjj/gcodetimer", "max_issues_repo_head_hexsha": "c53073f1d84363e5be290f0ccc312e6dc31898fa", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/GCodeProcessorBase.cc", "max_forks_repo_name": "gonzalezjj/gcodetimer", "max_forks_repo_head_hexsha": "c53073f1d84363e5be290f0ccc312e6dc31898fa", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 51.5222929936, "max_line_length": 161, "alphanum_fraction": 0.5415997033, "num_tokens": 1792, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6959583250334526, "lm_q2_score": 0.4455295350395727, "lm_q1q2_score": 0.31006998895907395}}
{"text": "/*======================================================================\nCopyright 2019 Google LLC\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    https://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n======================================================================*/\n\n\n#include <iostream>\n#include <cmath>\n#include <assert.h>\n\n#include <Eigen/Dense>\n#include \"PCV_Types.h\"\n\n#include \"Traj3.h\"\n\nusing namespace std;\nusing namespace Eigen;\n\n#define DECEL_WINDOW  0.003\n#define POS_WINDOW    0.0002\n\nTraj3::Traj3(double freq)\n{\n  assert( freq > 0.1 );\n  period_=1.0/freq;\n  curPos_  = new Vector3d;\n  curVel_  = new Vector3d;\n  destPos_ = new Vector3d;\n  destVel_ = new Vector3d;\n  acc_     = new Vector3d;\n  maxVel_  = new Vector3d;\n};\n\nTraj3::~Traj3()\n{\n  delete curPos_;\n  delete curVel_;\n  delete destPos_;\n  delete destVel_;\n  delete acc_;\n  delete maxVel_;\n};\n\nvoid\nTraj3::curPos(Vector3d &_curPos)\n{\n  *curPos_ = _curPos;\n}\n\nvoid\nTraj3::curVel(Vector3d &_curVel)\n{\n  *curVel_ = _curVel;\n}\n\nvoid\nTraj3::maxVel(double v_lim, double w_lim)\n{\n v_lim_ = fabs(v_lim);\n w_lim_ = fabs(w_lim);\n\n (*maxVel_)[0] = v_lim_;\n (*maxVel_)[1] = v_lim_;\n (*maxVel_)[2] = w_lim_;\n}\n\nvoid\nTraj3::maxVel(Vector3d &_maxVel)\n{\n  for(int i ; i<_maxVel.size() ; ++i)\n  { (*maxVel_)[i] = fabs(_maxVel[i]);\n  }\n}\n\n\nvoid\nTraj3::accel(double lin_acc, double rot_acc)\n{\n  lin_acc_ = lin_acc;\n  rot_acc_ = rot_acc;\n\n  (*acc_)[0] = fabs(lin_acc_);\n  (*acc_)[1] = fabs(lin_acc_);\n  (*acc_)[2] = fabs(rot_acc_);\n}\n\n\nvoid\nTraj3::accel(Vector3d &acc)\n{\n  for(int i ; i<acc.size() ; ++i)\n  { (*acc_)[i] = fabs(acc[i]);\n  }\n}\n\n\nvoid\nTraj3::dest2(Vector3d &destPos)\n{\n  Vector3d errPos;\n  double   errLi;\n\n  *destPos_=destPos;\n\n  errPos = *destPos_ - *curPos_;\n  errLi  = hypot(errPos[0],errPos[1]);\n  if(1.0/errLi < POS_WINDOW )\n    errLi = 1;        // SHOULD BE 1/POS_WINDOW ???\n  errLi = 1.0/errLi;  // AT 1, IT GIVES A DEADBAND\n\n\n  (*acc_)[0] = fabs(lin_acc_ * errPos[0]*errLi);\n  (*acc_)[1] = fabs(lin_acc_ * errPos[1]*errLi);\n\n  (*acc_)[2] = rot_acc_;\n\n\n   (*maxVel_)[0] = fabs(v_lim_ * errPos[0]*errLi);\n   (*maxVel_)[1] = fabs(v_lim_ * errPos[1]*errLi);\n\n   (*maxVel_)[2] = w_lim_;\n}\n\n\nvoid\nTraj3::get_uV(Vector3d &destUvel, Vector3d &trajPos,\n              Vector3d &trajVel,  Vector3d &trajAcc)\n{\n  Vector3d errVel;\n  double   velL;          // LENGTH\n\n  // LIMIT LIN COMMAND SPEEDS TO UNIT MAG LIN\n  velL = hypot(destUvel[0],destUvel[1]);  // 'L' IS ALWAYS POSITIVE\n  if( velL > 1.0 )  // WON'T DIVIDE BY zero BECAUSE THIS CHECK\n  { destUvel[0] = destUvel[0]/velL;\n    destUvel[1] = destUvel[1]/velL;\n  }\n  // LIMIT ROT COMMAND SPEED TO UNIT MAG ROT\n  if( destUvel[2] >  1.0 ) destUvel[2] =  1.0;\n  if( destUvel[2] < -1.0 ) destUvel[2] = -1.0;\n\n  // SCALE UNIT INPUT TO V_LIMIT AND W_LIMIT\n  errVel[0] = destUvel[0]*v_lim_ - (*curVel_)[0];\n  errVel[1] = destUvel[1]*v_lim_ - (*curVel_)[1];\n  errVel[2] = destUvel[2]*w_lim_ - (*curVel_)[2];\n\n  double   accel;         // ACCELERATION TMP VAR\n  double   errL,errLi;    // LENGTHS\n  double   v_win =  lin_acc_ * period_; // MAX delta_V MAG.\n  double   w_win =  rot_acc_ * period_; // MAX delta_W MAG.\n\n  //LIN ACCEL AT MAX UNLESS ONE STEP TO ZERO ERROR\n  errL  = hypot(errVel[0],errVel[1]); // 'L' IS ALWAYS POSITIVE\n  if( errL < v_win*0.002 )\n    errL = v_win*0.002;\n  if( errL < v_win )\n    accel = lin_acc_ * errL/v_win;\n  else\n    accel = lin_acc_;\n  errLi = 1.0/errL;\n  trajAcc[0] = accel * errVel[0]*errLi;  // x component\n  trajAcc[1] = accel * errVel[1]*errLi;  // y component\n\n  //ROT ACCEL AT MAX UNLESS ONE STEP TO ZERO ERROR\n  if     ( errVel[2] >  w_win ) trajAcc[2] =  rot_acc_;\n  else if( errVel[2] < -w_win ) trajAcc[2] = -rot_acc_;\n  else    trajAcc[2] =  rot_acc_ * errVel[2]/w_win;\n\n  // COMPUTE NEW VELOCITIES\n  trajVel = *curVel_ + trajAcc*period_;\n\n  // COMPUTE NEW POSITIONS\n  trajPos = *curPos_ + trajVel*period_ +\n             trajAcc*(0.5*period_*period_);\n\n  // AGE THE VALUES\n  *curVel_ = trajVel;\n  *curPos_ = trajPos;\n}\n\n\nvoid\nTraj3::get_V_lin(Vector3d &destVel, Vector3d &trajPos,\n                 Vector3d &trajVel, Vector3d &trajAcc)\n{\n  Vector3d errVel;\n  double   velL;             // LENGTH\n  double   velR;             // RATIO\n\n  // LIMIT COMMAND SPEEDS DUE TO LIN (SCALE ENTIRE VECTOR)\n  velL = hypot(destVel[0],destVel[1]);  // 'L' IS ALWAYS POSITIVE\n  velR = velL/v_lim_;\n  if( velR > 1.0 )  // WON'T DIVIDE BY zero BECAUSE THIS CHECK\n    destVel *= (1.0/velR);\n  // LIMIT COMMAND SPEEDS DUE TO ROT (SCALE ENTIRE VECTOR)\n  velL = fabs( destVel[2] );\n  velR = velL/w_lim_;\n  if( velR > 1.0 )  // WON'T DIVIDE BY zero BECAUSE THIS CHECK\n     destVel *= (1.0/velR);\n\n  errVel = destVel - *curVel_;\n\n  double   accel;      // ACCELERATION TMP VAR\n  double   errL;       // LENGTHS\n  double   v_win =  lin_acc_ * period_; // MAX delta_V MAG.\n\n  // LIN ACCEL AT MAX UNLESS ONE STEP TO ZERO ERROR\n  // ROT ACCEL IS PROPORTIONAL TO LIN ACCEL...\n  // ROT ACCEL IS TO ROT V_ERR, AS LIN ACCEL IS TO LIN V_ERR\n  // ASSUMES USE OF INPUT WITH LIMITED ROT SPEED\n  errL  = hypot(errVel[0],errVel[1]); // 'L' IS ALWAYS POSITIVE\n  if( errL < v_win*0.002 )  // AVOID DIV. BY ZERO\n    errL = v_win*0.002;\n  if( errL < v_win )        // ONE STEP TO ZERO ERROR\n    accel = lin_acc_ * errL/v_win;\n  else\n    accel = lin_acc_;\n\n  trajAcc = errVel * (accel/errL); // RATIO ALWAYS POSITIVE\n\n // COMPUTE NEW VELOCITIES\n  trajVel = *curVel_ + trajAcc*period_;\n\n  // COMPUTE NEW POSITIONS\n  trajPos = *curPos_ + trajVel*period_ + trajAcc*(0.5*period_*period_);\n\n  // AGE THE VALUES\n  *curVel_ = trajVel;\n  *curPos_ = trajPos;\n}\n\n\nint\nTraj3::get(Vector3d &trajPos, Vector3d &trajVel, Vector3d &trajAcc)\n{\n  int i;\n  int goalcount = (*destPos_).size();\n  double decelDist, decelError, decel, error;\n  Vector3d errPos;\n\n\n  for (i=0; i < (*destPos_).size() ; ++i)\n    {\n      error = (*destPos_)[i] - (*curPos_)[i];\n      if ( ((*acc_)[i] != 0) && (fabs(error) > POS_WINDOW) )\n  {\n    /* check to see if we can decelerate to *destPos_ */\n    decelDist=(*curVel_)[i]*fabs((*curVel_)[i])/(*acc_)[i]/2.0;\n    decelError=decelDist - error;\n    if ( ((error>0) && (decelError>0) && (decelError <  DECEL_WINDOW)) ||\n         ((error<0) && (decelError<0) && (decelError > -DECEL_WINDOW)) )\n      {\n        /* calculate deceleration and apply it */\n        decel = -(*curVel_)[i] * (*curVel_)[i]/error/2.0;\n        (*curVel_)[i] += period_ * decel;\n        trajAcc[i] = (decel>0 ? (*acc_)[i] : -(*acc_)[i]);\n        if ( fabs(error) < POS_WINDOW) // NOT USED CURRENTLY ???\n        { (*curVel_)[i] = 0.0;\n          (*curPos_)[i] = (*destPos_)[i];\n        }\n      }\n    else\n      {\n        /* check to see if we need to accelerate, because we don't\n     need to decelerate */\n        /* positive acceration: */\n        if ( (( decelError < 0.0) && ((*curVel_)[i] < (*maxVel_)[i])) ||\n             ((*curVel_)[i] < -(*maxVel_)[i]) )\n    {\n      (*curVel_)[i] += period_ * (*acc_)[i];\n      trajAcc[i] =  (*acc_)[i];\n      if ((*curVel_)[i] > (*maxVel_)[i])\n      { (*curVel_)[i] = (*maxVel_)[i];\n      }\n    }\n        if ( (( decelError > 0.0) && ((*curVel_)[i] > -(*maxVel_)[i])) ||\n             ((*curVel_)[i] > (*maxVel_)[i]) )\n    {\n      (*curVel_)[i] -= period_ * (*acc_)[i];\n      trajAcc[i] = -(*acc_)[i];\n      if ((*curVel_)[i] < -(*maxVel_)[i])\n      { (*curVel_)[i] = -(*maxVel_)[i];\n      }\n    }\n        /* else we don't need to do anything */\n        // ie. stay at +/- maxVel\n      }\n    (*curPos_)[i] += period_ * (*curVel_)[i];\n  }\n      else\n        {\n          (*curVel_)[i] = 0.0;\n          trajAcc[i] = 0.0;\n//    (*curPos_)[i] = (*destPos_)[i];\n          --goalcount;\n        }\n\n      trajVel[i] = (*curVel_)[i];\n      trajPos[i] = (*curPos_)[i];\n\n    }\n\n  return goalcount;\n}\n", "meta": {"hexsha": "804078bb2395f7101fedc48846418373dce90f9a", "size": 8153, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Traj3.cpp", "max_stars_repo_name": "google/powered-caster-vehicle", "max_stars_repo_head_hexsha": "ad231909e8cbe6785dbf682aac6bbe33797f92c8", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2019-05-30T17:39:55.000Z", "max_stars_repo_stars_event_max_datetime": "2020-03-14T08:34:10.000Z", "max_issues_repo_path": "Traj3.cpp", "max_issues_repo_name": "google/powered-caster-vehicle", "max_issues_repo_head_hexsha": "ad231909e8cbe6785dbf682aac6bbe33797f92c8", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Traj3.cpp", "max_forks_repo_name": "google/powered-caster-vehicle", "max_forks_repo_head_hexsha": "ad231909e8cbe6785dbf682aac6bbe33797f92c8", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-05-30T18:23:50.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-16T23:17:59.000Z", "avg_line_length": 25.8006329114, "max_line_length": 73, "alphanum_fraction": 0.5839568257, "num_tokens": 2868, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6959583250334526, "lm_q2_score": 0.4455295350395727, "lm_q1q2_score": 0.31006998895907395}}
{"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 NQS_METROPOLISEXCHANGEPT_HPP\n#define NQS_METROPOLISEXCHANGEPT_HPP\n\n#include <mpi.h>\n#include <Eigen/Dense>\n#include <iostream>\n#include \"Utils/parallel_utils.hpp\"\n#include \"Utils/random_utils.hpp\"\n#include \"abstract_sampler.hpp\"\n\nnamespace nqs {\n\n// Metropolis sampling generating local exchanges\n// Parallel tempering is also used\nclass MetropolisExchangePt : public AbstractSampler {\n  // number of visible units\n  const int nv_;\n\n  const int nrep_;\n  std::vector<double> beta_;\n\n  // states of visible units\n  // for each sampled temperature\n  std::vector<Eigen::VectorXd> v_;\n\n  Eigen::VectorXd accept_;\n  Eigen::VectorXd moves_;\n\n  int mynode_;\n  int totalnodes_;\n\n  // clusters to do updates\n  std::vector<std::vector<int>> clusters_;\n\n  // Look-up tables\n  std::vector<typename AbstractMachine::LookupType> lt_;\n\n  int sweep_size_;\n\n public:\n  MetropolisExchangePt(const AbstractGraph &graph, AbstractMachine &psi,\n                       int dmax = 1, int nreplicas = 1)\n      : AbstractSampler(psi), nv_(GetHilbert().Size()), nrep_(nreplicas) {\n    Init(graph, dmax);\n  }\n\n  void Init(const AbstractGraph &graph, int dmax) {\n    MPI_Comm_size(MPI_COMM_WORLD, &totalnodes_);\n    MPI_Comm_rank(MPI_COMM_WORLD, &mynode_);\n\n    v_.resize(nrep_);\n    for (int i = 0; i < nrep_; i++) {\n      v_[i].resize(nv_);\n    }\n\n    for (int i = 0; i < nrep_; i++) {\n      beta_.push_back(1. - double(i) / double(nrep_));\n    }\n\n    lt_.resize(nrep_);\n\n    accept_.resize(2 * nrep_);\n    moves_.resize(2 * nrep_);\n\n    GenerateClusters(graph, dmax);\n\n    Reset(true);\n\n    // Always use odd sweep size to avoid possible ergodicity problems\n    if (nv_ % 2 == 0) {\n      sweep_size_ = nv_ + 1;\n    } else {\n      sweep_size_ = nv_;\n    }\n\n    InfoMessage() << \"Metropolis sampler with parallel tempering is ready \"\n                  << std::endl;\n    InfoMessage() << nrep_ << \" replicas are being used\" << std::endl;\n    InfoMessage() << dmax << \" is the maximum distance for exchanges\"\n                  << std::endl;\n  }\n\n  template <class Graph>\n  void GenerateClusters(Graph &graph, int dmax) {\n    auto dist = graph.AllDistances();\n\n    assert(int(dist.size()) == nv_);\n\n    for (int i = 0; i < nv_; i++) {\n      for (int j = 0; j < nv_; j++) {\n        if (dist[i][j] <= dmax && i != j) {\n          clusters_.push_back({i, j});\n        }\n      }\n    }\n  }\n\n  void Reset(bool initrandom = false) override {\n    if (initrandom) {\n      for (int i = 0; i < nrep_; i++) {\n        GetHilbert().RandomVals(v_[i], this->GetRandomEngine());\n      }\n    }\n\n    for (int i = 0; i < nrep_; i++) {\n      GetMachine().InitLookup(v_[i], lt_[i]);\n    }\n\n    accept_ = Eigen::VectorXd::Zero(2 * nrep_);\n    moves_ = Eigen::VectorXd::Zero(2 * nrep_);\n  }\n\n  // Exchange sweep at given temperature\n  void LocalExchangeSweep(int rep) {\n    std::vector<int> tochange(2);\n    std::uniform_real_distribution<double> distu;\n    std::uniform_int_distribution<int> distcl(0, clusters_.size() - 1);\n\n    std::vector<double> newconf(2);\n\n    for (int i = 0; i < sweep_size_; i++) {\n      int rcl = distcl(this->GetRandomEngine());\n      assert(rcl < int(clusters_.size()));\n      int si = clusters_[rcl][0];\n      int sj = clusters_[rcl][1];\n\n      assert(si < nv_ && sj < nv_);\n\n      if (std::abs(v_[rep](si) - v_[rep](sj)) >\n          std::numeric_limits<double>::epsilon()) {\n        tochange = clusters_[rcl];\n        newconf[0] = v_[rep](sj);\n        newconf[1] = v_[rep](si);\n\n        auto explo =\n            std::exp(beta_[rep] * GetMachine().LogValDiff(v_[rep], tochange,\n                                                          newconf, lt_[rep]));\n        double ratio = this->GetMachineFunc()(explo);\n\n        if (ratio > distu(this->GetRandomEngine())) {\n          accept_(rep) += 1;\n          GetMachine().UpdateLookup(v_[rep], tochange, newconf, lt_[rep]);\n          GetHilbert().UpdateConf(v_[rep], tochange, newconf);\n        }\n      }\n\n      moves_(rep) += 1;\n    }\n  }\n\n  void Sweep() override {\n    // First we do local exchange sweeps\n    for (int i = 0; i < nrep_; i++) {\n      LocalExchangeSweep(i);\n    }\n\n    // Tempearture exchanges\n    std::uniform_real_distribution<double> distribution(0, 1);\n\n    for (int r = 1; r < nrep_; r += 2) {\n      if (ExchangeProb(r, r - 1) > distribution(this->GetRandomEngine())) {\n        Exchange(r, r - 1);\n        accept_(nrep_ + r) += 1.;\n        accept_(nrep_ + r - 1) += 1;\n      }\n      moves_(nrep_ + r) += 1.;\n      moves_(nrep_ + r - 1) += 1;\n    }\n\n    for (int r = 2; r < nrep_; r += 2) {\n      if (ExchangeProb(r, r - 1) > distribution(this->GetRandomEngine())) {\n        Exchange(r, r - 1);\n        accept_(nrep_ + r) += 1.;\n        accept_(nrep_ + r - 1) += 1;\n      }\n      moves_(nrep_ + r) += 1.;\n      moves_(nrep_ + r - 1) += 1;\n    }\n  }\n\n  // computes the probability to exchange two replicas\n  double ExchangeProb(int r1, int r2) {\n    const double lf1 = 2 * std::real(GetMachine().LogVal(v_[r1], lt_[r1]));\n    const double lf2 = 2 * std::real(GetMachine().LogVal(v_[r2], lt_[r2]));\n\n    return std::exp((beta_[r1] - beta_[r2]) * (lf2 - lf1));\n  }\n\n  void Exchange(int r1, int r2) {\n    std::swap(v_[r1], v_[r2]);\n    std::swap(lt_[r1], lt_[r2]);\n  }\n\n  const Eigen::VectorXd &Visible() const noexcept override { return v_[0]; }\n\n  void SetVisible(const Eigen::VectorXd &v) override { v_[0] = v; }\n\n  AbstractMachine::VectorType DerLogVisible() override {\n    return GetMachine().DerLog(v_[0], lt_[0]);\n  }\n\n  Eigen::VectorXd Acceptance() const override {\n    Eigen::VectorXd acc = accept_;\n    for (int i = 0; i < acc.size(); i++) {\n      acc(i) /= moves_(i);\n    }\n    return acc;\n  }\n};\n\n}  // namespace nqs\n\n#endif\n", "meta": {"hexsha": "33acf3fee77b6b861a0085b7fa826be8b3b4ba47", "size": 6308, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Sources/Sampler/metropolis_exchange_pt.hpp", "max_stars_repo_name": "stubbi/netket", "max_stars_repo_head_hexsha": "7391466077a4694e8f12c649730a81bf634f695e", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-11-28T10:26:04.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-28T10:26:04.000Z", "max_issues_repo_path": "Sources/Sampler/metropolis_exchange_pt.hpp", "max_issues_repo_name": "stubbi/nqs", "max_issues_repo_head_hexsha": "7391466077a4694e8f12c649730a81bf634f695e", "max_issues_repo_licenses": ["Apache-2.0"], "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/Sampler/metropolis_exchange_pt.hpp", "max_forks_repo_name": "stubbi/nqs", "max_forks_repo_head_hexsha": "7391466077a4694e8f12c649730a81bf634f695e", "max_forks_repo_licenses": ["Apache-2.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.6666666667, "max_line_length": 78, "alphanum_fraction": 0.5979708307, "num_tokens": 1804, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6297745935070806, "lm_q2_score": 0.49218813572079556, "lm_q1q2_score": 0.3099675831025719}}
{"text": "#pragma once\n#include <vector>\n#include <queue>\n#include <Eigen/Geometry>\n#include <boost/optional.hpp>\n#include <OpenMesh/Core/Mesh/TriMesh_ArrayKernelT.hh>\n#include <OpenMesh/Core/Mesh/PolyConnectivity.hh>\n#include \"../vector_convert.hh\"\n#include \"../FaceBaryCoordT.hh\"\n#include \"../../eigen_util.hh\"\n#include \"../../util.hh\"\n#include \"../DerivedPtrHolder.hh\"\n\nnamespace kt84 {\n\n/*\n    Implementation of a surface mesh parameterization algorithm descibed in the following articles:\n        Ryan Schmidt, Cindy Grimm, and Brian Wyvill.\n        Interactive decal compositing with discrete exponential maps.\n        ACM SIGGRAPH 2006.\n        \n        Ryan Schmidt and Karan Singh.\n        Drag, Drop, and Clone: An Interactive Interface for Surface Composition.\n        Technical Report CSRG-611, Department of Computer Science, University of Toronto, 2010.\n    \n    NOTE: The algorithm is implemented in a slightly different way; the uv coordiante of currently processed vertex q is estimated by rotating \n    its local frame to that of its adjacent vertex p that has been processed already, which is in contrast to what is claimed in the original \n    SIGGRAPH paper (see sentences below equation (3)). This modification seems to provide better robustness especially when parameterizing highly \n    curved surface regions (probably because normals at distant locations are very different from the seed's normal).\n\n    parameters:\n        seed(s)                 seed vertex id\n        seed(s)_basis_u         3D vector in object space corresponding to unit basis vector of u-coordinate.\n                                (its length determines the overall scaling of the parameterization)\n        seed(s)_uv              seed uv coordinate\n        dist_max                termination criteria based on object-space distance\n        uv_min, uv_max          termination criteria based on parameter-space bounding box\n*/\n\nstruct ExpMap_VertexTraits {\n    struct Data {\n        bool            paramed;\n        double          dist;\n        double          weight;\n        Eigen::Vector2d uv;\n        Eigen::Vector2d basis_u;              // represents u-coordiante basis vector in object space.\n                                            // (i.e., its length determines scaling of parameterization.)\n                                            // living on the tangent plane defined by intrinsic bases\n        \n        Data()\n            : paramed()\n            , dist   (util::dbl_max())\n            , weight ()\n            , uv     (Eigen::Vector2d::Zero())\n            , basis_u(Eigen::Vector2d::Zero())\n        {}\n    } expmap;\n};\n\nstruct ExpMap_FaceTraits {\n    bool expmap_paramed;\n    \n    ExpMap_FaceTraits()\n        : expmap_paramed()\n    {}\n};\n\nnamespace internal {\n    template <class TMeshBase>\n    void expmap_compute_common(TMeshBase* mesh,\n                               const std::vector<OpenMesh::PolyConnectivity::VHandle>& seeds,\n                               const std::vector<Eigen::Vector3d                    >& seeds_basis_u,\n                               const std::vector<Eigen::Vector2d                    >& seeds_uv,\n                               double dist_max,\n                               const Eigen::Vector2d& uv_min,\n                               const Eigen::Vector2d& uv_max,\n                               std::vector<OpenMesh::PolyConnectivity::FHandle>& expmap_paramed_faces)\n    {\n        // helper functions ==============================================================================================\n        auto get_intr_basis = [] (const Eigen::Vector3d& normal) -> Eigen::Vector3d {\n            // get unit basis vector orthogonal to input vector in intrinsical manner\n            double nx = std::abs(normal.x());\n            double ny = std::abs(normal.y());\n            double nz = std::abs(normal.z());\n            Eigen::Vector3d basis =\n                nx < ny && ny < nz ? Eigen::Vector3d::UnitX() :\n                ny < nz            ? Eigen::Vector3d::UnitY() :\n                                     Eigen::Vector3d::UnitZ();\n            eigen_util::orthonormalize(normal, basis);\n            return basis;\n        };\n        \n        auto compute_rotation = [get_intr_basis] (const Eigen::Vector3d& p_normal,\n                                                  const Eigen::Vector3d& q_normal) -> Eigen::Rotation2Dd\n            // compute 2D rotation which will be used to rotate basis_u of p to estimate that of q\n        {\n            // get intrinsic basis vectors of p, q\n            auto p_intr_basis = get_intr_basis(p_normal);\n            auto q_intr_basis = get_intr_basis(q_normal);\n            \n            // step 1: compute 3D rotation that aligns q_normal with p_normal. apply it to q_basis.\n            auto rot1_axis = q_normal.cross(p_normal);\n            if (!rot1_axis.isZero()) {\n                rot1_axis.normalize();\n                double rot1_angle = util::acos_clamped(q_normal.dot(p_normal));\n                q_intr_basis = Eigen::AngleAxisd(rot1_angle, rot1_axis) * q_intr_basis;\n            }\n            \n            // step 2: compute 2D rotation that makes (rotated) q_basis aligned with p_basis.\n            double rot2_angle = util::acos_clamped(q_intr_basis.dot(p_intr_basis));\n            if (q_intr_basis.cross(p_intr_basis).dot(p_normal) < 0)     // negative rotation\n                rot2_angle *= -1.0f;\n            \n            return Eigen::Rotation2Dd(rot2_angle);\n        };\n        \n        auto compute_uv = [get_intr_basis] (const Eigen::Vector3d& p_point ,\n                                            const Eigen::Vector3d& p_normal,\n                                            const Eigen::Vector2d& p_uv,\n                                            const Eigen::Vector2d& p_basis_u,\n                                            const Eigen::Vector3d& q_point ) -> Eigen::Vector2d\n            // computes uv for point q using p's point, normal, uv, basis_u\n        {\n            auto p_intr_basis_x = get_intr_basis(p_normal);\n            auto p_intr_basis_y = p_normal.cross(p_intr_basis_x);\n            \n            // project (rotate) pq into tangent plane\n            Eigen::Vector3d pq = q_point - p_point;\n            Eigen::Vector2d local_uv(pq.dot(p_intr_basis_x), pq.dot(p_intr_basis_y));\n            local_uv *= pq.norm() / local_uv.norm();\n            \n            // encode 2D local_uv using propagated (non-unit) basis vectors\n            auto p_basis_v = eigen_util::rotate90(p_basis_u);\n            local_uv = Eigen::Vector2d(p_basis_u.dot(local_uv), p_basis_v.dot(local_uv));\n            \n            // account for scale difference\n            local_uv /= p_basis_u.squaredNorm();\n            \n            Eigen::Vector2d q_uv = p_uv + local_uv;\n            \n            return q_uv;\n        };\n        // ============================================================================================== helper functions\n        \n        // clear all vertex data\n        for (auto v : mesh->vertices())\n            mesh->data(v).expmap = ExpMap_VertexTraits::Data();\n        \n        // priority queue for propagation front\n        struct QueueElement {\n            OpenMesh::PolyConnectivity::VHandle vhandle;\n            double dist;\n            \n            QueueElement() : dist(){}\n            QueueElement(OpenMesh::PolyConnectivity::VHandle vhandle_, double dist_) : vhandle(vhandle_) , dist(dist_) {}\n            bool operator<(const QueueElement& rhs) const { return dist > rhs.dist; }       // note: smaller distance gets higher priority\n        };\n        std::priority_queue<QueueElement> candidates;\n        \n        // init\n        for (size_t i = 0; i < seeds.size(); ++i) {\n            auto seed = seeds[i];\n            auto& seed_data = mesh->data(seed).expmap;\n            \n            Eigen::Vector3d seed_normal       = o2e(mesh->normal(seed));\n            Eigen::Vector3d seed_intr_basis_x = get_intr_basis(seed_normal);\n            Eigen::Vector3d seed_intr_basis_y = seed_normal.cross(seed_intr_basis_x);\n            Eigen::Vector3d seed_basis_u      = seeds_basis_u[i];\n            \n            seed_data.weight  += 1;\n            seed_data.dist     = 0;\n            seed_data.uv      += seeds_uv[i];\n            seed_data.basis_u += Eigen::Vector2d(seed_intr_basis_x.dot(seed_basis_u), seed_intr_basis_y.dot(seed_basis_u));\n            \n            candidates.push(QueueElement(seed, 0));\n        }\n        \n        while (!candidates.empty()) {\n            auto p = candidates.top().vhandle;\n            candidates.pop();\n            \n            auto& p_data   = mesh->data(p).expmap;\n            auto  p_point  = o2e(mesh->point (p));\n            auto  p_normal = o2e(mesh->normal(p));\n            \n            if (p_data.paramed) continue;\n            p_data.paramed = true;\n            \n            p_data.uv      /= p_data.weight;\n            p_data.basis_u /= p_data.weight;\n            \n            if (dist_max < p_data.dist) continue;\n            \n            if (!Eigen::AlignedBox2d(uv_min, uv_max).contains(p_data.uv)) continue;\n            \n            for (auto q = mesh->vv_iter(p); q.is_valid(); ++q) {\n                auto& q_data   = mesh->data(*q).expmap;\n                auto  q_point  = o2e(mesh->point (*q));\n                auto  q_normal = o2e(mesh->normal(*q));\n                \n                if (q_data.paramed) continue;\n                \n                // distance update\n                double dist_pq = (p_point - q_point).norm();\n                if (p_data.dist + dist_pq < q_data.dist)\n                    q_data.dist = p_data.dist + dist_pq;\n                \n                // weight based on distance between p and q\n                double weight = 1.0f / std::pow(dist_pq, 0.25);\n                q_data.weight += weight;\n                \n                // estimate of data by weighted averaging\n                q_data.uv      += weight * compute_uv(p_point, p_normal, p_data.uv, p_data.basis_u, q_point);\n                q_data.basis_u += weight * (compute_rotation(p_normal, q_normal) * p_data.basis_u);            // be sure to use parentheses! otherwise Eigen will happily go funny:)\n                \n                candidates.push(QueueElement(*q, q_data.dist));\n            }\n        }\n        \n        // collect faces with its vertices all paramed\n        expmap_paramed_faces.clear();\n        expmap_paramed_faces.reserve(mesh->n_faces());\n        for (auto f : mesh->faces()) {\n            mesh->data(f).expmap_paramed = true;\n            for (auto v = mesh->fv_iter(f); v.is_valid(); ++v) {\n                if (!mesh->data(*v).expmap.paramed) {\n                    mesh->data(f).expmap_paramed = false;\n                    break;\n                }\n            }\n            if (mesh->data(f).expmap_paramed)\n                expmap_paramed_faces.push_back(f);\n        }\n    }\n}\n\ntemplate <class TMeshBase, class TMesh>\nstruct ExpMap : public DerivedPtrHolder<TMesh, ExpMap<TMeshBase, TMesh>> {\n    std::vector<typename TMeshBase::FHandle> expmap_paramed_faces;\n    \n    void expmap_compute(\n        const std::vector<typename TMeshBase::VHandle>& seeds,\n        const std::vector<Eigen::Vector3d            >& seeds_basis_u,\n        const std::vector<Eigen::Vector2d            >& seeds_uv,\n        double dist_max,\n        const Eigen::Vector2d& uv_min = Eigen::Vector2d::Constant(-std::numeric_limits<double>::max()),\n        const Eigen::Vector2d& uv_max = Eigen::Vector2d::Constant( std::numeric_limits<double>::max()))\n    {\n        TMesh* mesh = DerivedPtrHolder<TMesh, ExpMap<TMeshBase, TMesh>>::derived_ptr;\n        internal::expmap_compute_common(mesh, seeds, seeds_basis_u, seeds_uv, dist_max, uv_min, uv_max, expmap_paramed_faces);\n    }\n    void expmap_compute(\n        typename TMeshBase::VHandle seed,\n        Eigen::Vector3d             seed_basis_u,\n        Eigen::Vector2d             seed_uv,\n        double dist_max,\n        const Eigen::Vector2d& uv_min = Eigen::Vector2d::Constant(-std::numeric_limits<double>::max()),\n        const Eigen::Vector2d& uv_max = Eigen::Vector2d::Constant( std::numeric_limits<double>::max()))\n    {\n        expmap_compute(\n            std::vector<typename TMeshBase::VHandle>(1, seed        ),\n            std::vector<Eigen::Vector3d            >(1, seed_basis_u),\n            std::vector<Eigen::Vector2d            >(1, seed_uv     ),\n            dist_max,\n            uv_min,\n            uv_max);\n    }\n};\n\n// specialization for triangle meshes, with functionality to convert on-surface position (face id + barycentric coord) into uv coordinates.\ntemplate <class TTrait, class TMesh>\nstruct ExpMap<OpenMesh::TriMesh_ArrayKernelT<TTrait>, TMesh> : public DerivedPtrHolder<TMesh, ExpMap<OpenMesh::TriMesh_ArrayKernelT<TTrait>, TMesh>> {\n    typedef OpenMesh::TriMesh_ArrayKernelT<TTrait> MeshBase;\n    \n    std::vector<typename MeshBase::FHandle> expmap_paramed_faces;\n    \n    void expmap_compute(\n        const std::vector<typename MeshBase::VHandle>& seeds,\n        const std::vector<Eigen::Vector3d           >& seeds_basis_u,\n        const std::vector<Eigen::Vector2d           >& seeds_uv,\n        double dist_max,\n        const Eigen::Vector2d& uv_min = Eigen::Vector2d::Constant(-std::numeric_limits<double>::max()),\n        const Eigen::Vector2d& uv_max = Eigen::Vector2d::Constant( std::numeric_limits<double>::max()))\n    {\n        TMesh* mesh = get_mesh();\n        internal::expmap_compute_common(mesh, seeds, seeds_basis_u, seeds_uv, dist_max, uv_min, uv_max, expmap_paramed_faces);\n    }\n    void expmap_compute(\n        typename MeshBase::VHandle seed,\n        Eigen::Vector3d            seed_basis_u,\n        Eigen::Vector2d            seed_uv,\n        double dist_max,\n        const Eigen::Vector2d& uv_min = Eigen::Vector2d::Constant(-std::numeric_limits<double>::max()),\n        const Eigen::Vector2d& uv_max = Eigen::Vector2d::Constant( std::numeric_limits<double>::max()))\n    {\n        expmap_compute(\n            std::vector<typename MeshBase::VHandle>(1, seed        ),\n            std::vector<Eigen::Vector3d           >(1, seed_basis_u),\n            std::vector<Eigen::Vector2d           >(1, seed_uv     ),\n            dist_max,\n            uv_min,\n            uv_max);\n    }\n    void expmap_compute(\n        const std::vector<FaceBaryCoord  >& seeds,\n        const std::vector<Eigen::Vector3d>& seeds_basis_u,\n        const std::vector<Eigen::Vector2d>& seeds_uv,\n        double dist_max,\n        const Eigen::Vector2d& uv_min = Eigen::Vector2d::Constant(-std::numeric_limits<double>::max()),\n        const Eigen::Vector2d& uv_max = Eigen::Vector2d::Constant( std::numeric_limits<double>::max()))\n    {\n        TMesh* mesh = get_mesh();\n        \n        std::vector<typename MeshBase::VHandle> seeds2;\n        std::vector<Eigen::Vector3d           > seeds2_basis_u;\n        std::vector<Eigen::Vector2d           > seeds2_uv;\n        \n        for (size_t i = 0; i < seeds.size(); ++i) {\n            auto& seed         = seeds        [i];\n            auto& seed_basis_u = seeds_basis_u[i];\n            auto& seed_uv      = seeds_uv     [i];\n            \n            Eigen::Vector3d p = o2e(seed.blend_point (*mesh));\n            Eigen::Vector3d n = o2e(seed.blend_normal(*mesh));\n            \n            Eigen::Vector3d seed_basis_v = n.cross(seed_basis_u);\n            \n            double offset_scaling = 1 / seed_basis_u.squaredNorm();\n            \n            for (auto v = mesh->fv_iter(seed.f); v; ++v) {\n                Eigen::Vector3d pq = o2e(mesh->point(v)) - p;\n                Eigen::Vector2d uv_offset(pq.dot(seed_basis_u), pq.dot(seed_basis_v));\n                uv_offset *= offset_scaling;\n                \n                seeds2        .push_back(v);\n                seeds2_basis_u.push_back(seed_basis_u);\n                seeds2_uv     .push_back(seed_uv + uv_offset);\n            }\n        }\n        \n        expmap_compute(seeds2, seeds2_basis_u, seeds2_uv, dist_max, uv_min, uv_max);\n    }\n    void expmap_compute(\n        FaceBaryCoord   seed,\n        Eigen::Vector3d seed_basis_u,\n        Eigen::Vector2d seed_uv,\n        double dist_max,\n        const Eigen::Vector2d& uv_min = Eigen::Vector2d::Constant(-std::numeric_limits<double>::max()),\n        const Eigen::Vector2d& uv_max = Eigen::Vector2d::Constant( std::numeric_limits<double>::max()))\n    {\n        expmap_compute(\n            std::vector<FaceBaryCoord  >(1, seed        ),\n            std::vector<Eigen::Vector3d>(1, seed_basis_u),\n            std::vector<Eigen::Vector2d>(1, seed_uv     ),\n            dist_max,\n            uv_min,\n            uv_max);\n    }\n    // conversion from on-surface position to uv coordinates\n    boost::optional<Eigen::Vector2d> fbc_to_uv(const FaceBaryCoord& fbc) const {\n        TMesh* mesh = get_mesh();\n        \n        if (!mesh->data(fbc.f).expmap_paramed)\n            return boost::none;\n        \n        return fbc.blend_value<MeshBase, Eigen::Vector2d>(\n            *mesh,\n            [](const MeshBase& mesh, typename MeshBase::VHandle v) { return mesh.data(v).expmap.uv; }\n        );\n    }\n    boost::optional<Eigen::Vector2d> fbc_to_uv(typename MeshBase::FHandle f, const BaryCoord& bc) const {\n        return fbc_to_uv(FaceBaryCoord(f, bc));\n    }\n    FaceBaryCoord uv_to_fbc(Eigen::Vector2d uv) const {\n        TMesh* mesh = get_mesh();\n        \n        for (auto f : expmap_paramed_faces) {\n            // compute bounding box of this face\n            Eigen::AlignedBox2d box;\n            std::vector<Eigen::Vector2d> face_uv;\n            for (auto v = mesh->cfv_iter(f); v.is_valid(); ++v) {\n                auto expmap_uv = mesh->data(*v).expmap.uv;\n                face_uv.push_back(expmap_uv);\n                box.extend(expmap_uv);\n            }\n            \n            // skip if uv is outside the bounding box\n            if (!box.contains(uv)) continue;\n            \n            // compute barycentric coordinate\n            // (1 - hit.u - hit.v) * face_uv[0] + hit.u * face_uv[1] + hit.v * face_uv[2] = uv\n            // | face_uv[1] - face_uv[0], face_uv[2] - face_uv[0] | * |hit.u| = | uv - face_uv[0] |\n            // |                                                  |   |hit.v|   |                 |\n            Eigen::Matrix2d A;\n            A << face_uv[1] - face_uv[0], face_uv[2] - face_uv[0];\n            Eigen::Vector2d hit_uv = A.inverse() * (uv - face_uv[0]);\n            \n            // skip if barycentric coordinate is negative\n            BaryCoord bc(1 - hit_uv[0] - hit_uv[1], hit_uv[0], hit_uv[1]);\n            if (!bc.is_all_positive()) continue;\n            \n            // return result\n            return FaceBaryCoord(f, bc);\n        }\n        \n        return FaceBaryCoord();\n    }\nprivate:\n    TMesh* get_mesh() const { return DerivedPtrHolder<TMesh, ExpMap<OpenMesh::TriMesh_ArrayKernelT<TTrait>, TMesh>>::derived_ptr; }\n};\n\n}\n", "meta": {"hexsha": "a0e6f5cf212f17cad60cbd4b49c81e4f3c87476a", "size": 18868, "ext": "hh", "lang": "C++", "max_stars_repo_path": "src/kt84/openmesh/base/ExpMap.hh", "max_stars_repo_name": "honoriocassiano/skbar", "max_stars_repo_head_hexsha": "e2a8fca752f5a2f9d9a32f19cbe1f9032a0e1ac4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/kt84/openmesh/base/ExpMap.hh", "max_issues_repo_name": "honoriocassiano/skbar", "max_issues_repo_head_hexsha": "e2a8fca752f5a2f9d9a32f19cbe1f9032a0e1ac4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2020-09-01T12:16:28.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-01T12:21:41.000Z", "max_forks_repo_path": "src/kt84/openmesh/base/ExpMap.hh", "max_forks_repo_name": "honoriocassiano/skbar", "max_forks_repo_head_hexsha": "e2a8fca752f5a2f9d9a32f19cbe1f9032a0e1ac4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 45.6852300242, "max_line_length": 181, "alphanum_fraction": 0.5541657833, "num_tokens": 4326, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.672331699179286, "lm_q2_score": 0.46101677931231594, "lm_q1q2_score": 0.3099561945852113}}
{"text": "/* Siconos is a program dedicated to modeling, simulation and control\n * of non smooth dynamical systems.\n *\n * Copyright 2016 INRIA.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n*/\n\n\n#include <boost/numeric/ublas/matrix_proxy.hpp>\n\n\n#include \"determinant.hpp\"\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//       get norm\n//=======================\n\ndouble SimpleMatrix::normInf() const\n{\n  if (_num == 1)\n    return norm_inf(*mat.Dense);\n  else if (_num == 2)\n    return norm_inf(*mat.Triang);\n  else if (_num == 3)\n    return norm_inf(*mat.Sym);\n  else if (_num == 4)\n    return norm_inf(*mat.Sparse);\n  else if (_num == 5)\n    return norm_inf(*mat.Banded);\n  else if (_num == 6)\n    return 0;\n  else // if(_num==7)\n    return 1;\n}\n\nvoid SimpleMatrix::normInfByColumn(SP::SiconosVector vIn) const\n{\n  if (_num == 1)\n  {\n    if (vIn->size() != size(1))\n      RuntimeException::selfThrow(\"SimpleMatrix::normInfByColumn: the given vector does not have the right length\");\n    DenseVect tmpV = DenseVect(size(0));\n    for (unsigned int i = 0; i < size(1); i++)\n    {\n       ublas::noalias(tmpV) = ublas::column(*mat.Dense, i);\n       (*vIn)(i) = norm_inf(tmpV);\n    }\n  }\n  else\n    RuntimeException::selfThrow(\"SimpleMatrix::normInfByColumn: not implemented for data other than DenseMat\");\n}\n//=======================\n//       determinant\n//=======================\n\ndouble SimpleMatrix::det() const\n{\n  if (_num == 1)\n    return determinant(*mat.Dense);\n  else if (_num == 2)\n    return determinant(*mat.Triang);\n  else if (_num == 3)\n    return determinant(*mat.Sym);\n  else if (_num == 4)\n    return determinant(*mat.Sparse);\n  else if (_num == 5)\n    return determinant(*mat.Banded);\n  else if (_num == 6)\n    return 0;\n  else // if(_num==7)\n    return 1;\n}\n\n\nvoid SimpleMatrix::trans()\n{\n  switch (_num)\n  {\n  case 1:\n    *mat.Dense = ublas::trans(*mat.Dense);\n    break;\n  case 2:\n    SiconosMatrixException::selfThrow(\"SimpleMatrix::trans() failed, the matrix is triangular matrix and can not be transposed in place.\");\n    break;\n  case 3:\n    break;\n  case 4:\n    *mat.Sparse = ublas::trans(*mat.Sparse);\n    break;\n  case 5:\n    *mat.Banded = ublas::trans(*mat.Banded);\n    break;\n  case 6:\n    break;\n  case 7:\n    break;\n  }\n  resetLU();\n}\n\nvoid SimpleMatrix::trans(const SiconosMatrix &m)\n{\n  if (m.isBlock())\n    SiconosMatrixException::selfThrow(\"SimpleMatrix::trans(m) failed, not yet implemented for m being a BlockMatrix.\");\n\n\n  if (&m == this)\n    trans();//SiconosMatrixException::selfThrow(\"SimpleMatrix::trans(m) failed, m = this, use this->trans().\");\n  else\n  {\n    unsigned int numM = m.num();\n    switch (numM)\n    {\n    case 1:\n      if (_num != 1)\n        SiconosMatrixException::selfThrow(\"SimpleMatrix::trans(m) failed, try to transpose a dense matrix into another type.\");\n      noalias(*mat.Dense) = ublas::trans(*m.dense());\n      break;\n    case 2:\n      if (_num != 1)\n        SiconosMatrixException::selfThrow(\"SimpleMatrix::trans(m) failed, try to transpose a triangular matrix into a non-dense one.\");\n      noalias(*mat.Dense) = ublas::trans(*m.triang());\n      break;\n    case 3:\n      *this = m;\n      break;\n    case 4:\n      if (_num == 1)\n        noalias(*mat.Dense) = ublas::trans(*m.sparse());\n      else if (_num == 4)\n        noalias(*mat.Sparse) = ublas::trans(*m.sparse());\n      else\n        SiconosMatrixException::selfThrow(\"SimpleMatrix::trans(m) failed, try to transpose a sparse matrix into a forbidden type (not dense nor sparse).\");\n      break;\n    case 5:\n      if (_num == 1)\n        noalias(*mat.Dense) = ublas::trans(*m.banded());\n      else if (_num == 5)\n        noalias(*mat.Banded) = ublas::trans(*m.banded());\n      else\n        SiconosMatrixException::selfThrow(\"SimpleMatrix::trans(m) failed, try to transpose a banded matrix into a forbidden type (not dense nor banded).\");\n      break;\n    case 6:\n      *this = m;\n      break;\n    case 7:\n      *this = m;\n    }\n    // unsigned int tmp = _dimRow;\n    // _dimRow = _dimCol;\n    // _dimCol = tmp;\n    resetLU();\n  }\n}\n\n\n\n\n\n\n\nconst SimpleMatrix matrix_pow(const SimpleMatrix& m, unsigned int power)\n{\n  if (m.isBlock())\n    SiconosMatrixException::selfThrow(\"Matrix, pow function: not yet implemented for BlockMatrix.\");\n  if ( m.size(0) != m.size(1))\n    SiconosMatrixException::selfThrow(\"matrix_pow(SimpleMatrix), matrix is not square.\");\n\n  if (power > 0)\n  {\n    unsigned int num = m.num();\n    if (num == 1)\n    {\n      DenseMat p = *m.dense();\n      for (unsigned int i = 1; i < power; i++)\n        p = prod(p, *m.dense());\n      return p;\n    }\n    else if (num == 2)\n    {\n      TriangMat t = *m.triang();\n      for (unsigned int i = 1; i < power; i++)\n        t = prod(t, *m.triang());\n      return t;\n    }\n    else if (num == 3)\n    {\n      SymMat s = *m.sym();\n      for (unsigned int i = 1; i < power; i++)\n        s = prod(s, *m.sym());\n      return s;\n    }\n    else if (num == 4)\n    {\n      SparseMat sp = *m.sparse();\n      for (unsigned int i = 1; i < power; i++)\n        sp = prod(sp, *m.sparse());\n      return sp;\n    }\n    else if (num == 5)\n    {\n      DenseMat b = *m.banded();\n      for (unsigned int i = 1; i < power; i++)\n        b = prod(b, *m.banded());\n      return b;\n    }\n    else if (num == 6)\n    {\n      ZeroMat z(m.size(0), m.size(1));\n      return z;\n    }\n    else // if (num==7)\n    {\n      IdentityMat I(m.size(0), m.size(1));;\n      return I;\n    }\n  }\n  else// if(power == 0)\n  {\n    IdentityMat I = ublas::identity_matrix<double>(m.size(0), m.size(1));\n    return I;\n  }\n}\n\n\n\n/*\nThe following code inverts the matrix input using LU-decomposition with backsubstitution of unit vectors. Reference: Numerical Recipies in C, 2nd ed., by Press, Teukolsky, Vetterling & Flannery.\n\nyou can solve Ax=b using three lines of ublas code:\n\npermutation_matrix<> piv;\nlu_factorize(A, piv);\nlu_substitute(A, piv, x);\n\n*/\n#ifndef INVERT_MATRIX_HPP\n#define INVERT_MATRIX_HPP\n\n// REMEMBER to update \"lu.hpp\" header includes from boost-CVS\n#include <boost/numeric/ublas/vector.hpp>\n#include <boost/numeric/ublas/vector_proxy.hpp>\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/triangular.hpp>\n#include <boost/numeric/ublas/lu.hpp>\n#include <boost/numeric/ublas/io.hpp>\n\n/* Matrix inversion routine.\nUses lu_factorize and lu_substitute in uBLAS to invert a matrix */\ntemplate<class T, class U, class V>\nbool InvertMatrix(const ublas::matrix<T, U, V>& input, ublas::matrix<T, U, V>& inverse)\n{\n  using namespace boost::numeric::ublas;\n  typedef permutation_matrix<std::size_t> pmatrix;\n// create a working copy of the input\n  matrix<T, U, V> A(input);\n// create a permutation matrix for the LU-factorization\n  pmatrix pm(A.size1());\n\n// perform LU-factorization\n  int res = lu_factorize(A,pm);\n  if (res != 0) return false;\n\n// create identity matrix of \"inverse\"\n  inverse.assign(ublas::identity_matrix<T>(A.size1()));\n\n// backsubstitute to get the inverse\n  lu_substitute(A, pm, inverse);\n\n  return true;\n}\n\n#endif //INVERT_MATRIX_HPP\n\nvoid invertMatrix(const SimpleMatrix& input, SimpleMatrix& output)\n{\n  InvertMatrix(*input.dense(), *output.dense());\n}\n\n\n/* XXX Find out if we can use an elementwise ublas operation */\nSP::SiconosVector compareMatrices(const SimpleMatrix& data, const SimpleMatrix& ref)\n{\n  SimpleMatrix diff(data.size(0), data.size(1));\n  SP::SiconosVector res(new SiconosVector(data.size(1)));\n  diff = data - ref;\n  for (unsigned int i = 0; i < data.size(0); ++i)\n  {\n    for (unsigned int j = 0; j < data.size(1); ++j)\n      diff(i, j) /= 1 + fabs(ref(i, j));\n  }\n  diff.normInfByColumn(res);\n  return res;\n\n}\n\n", "meta": {"hexsha": "482388ab7dff91b8bf908c17c0a24e7b60b74824", "size": 8274, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "kernel/src/utils/SiconosAlgebra/SimpleMatrixMisc.cpp", "max_stars_repo_name": "siconos/siconos-deb", "max_stars_repo_head_hexsha": "2739a23f23d797dbfecec79d409e914e13c45c67", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "kernel/src/utils/SiconosAlgebra/SimpleMatrixMisc.cpp", "max_issues_repo_name": "siconos/siconos-deb", "max_issues_repo_head_hexsha": "2739a23f23d797dbfecec79d409e914e13c45c67", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "kernel/src/utils/SiconosAlgebra/SimpleMatrixMisc.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.1835443038, "max_line_length": 194, "alphanum_fraction": 0.6255740875, "num_tokens": 2344, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.672331699179286, "lm_q2_score": 0.4610167793123159, "lm_q1q2_score": 0.3099561945852113}}
{"text": "#include <iostream>\n#include <memory>\n#include <tuple>\n#include <stdlib.h>\n\n#include <boost/optional.hpp>\n\n// lvr2 includes\n#include \"lvr2/registration/TransformUtils.hpp\"\n#include \"lvr2/types/MatrixTypes.hpp\"\n\nint main(int argc, char** argv)\n{\n    std::cout << \"Coordinate Example\" << std::endl;\n    // Overview Coordinate Systems\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\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\n\n    // x: 2.0, y: 0.5, z: 1.0\n    // front: 1.0, right: 2.0, down: 0.5\n    lvr2::Vector3d cv_point = {2.0, 0.5, 1.0};\n    std::cout << \"cv point: \" << cv_point.transpose() << std::endl;\n\n    // convert to lvr\n    // should be x(front): 1.0, y(left): -2.0, z(up): -0.5 \n    lvr2::Vector3d lvr_point = lvr2::openCvToLvr(cv_point);\n    std::cout << \"lvr point: \" << lvr_point.transpose() << std::endl;\n\n    if(lvr2::lvrToOpenCv(lvr_point) == cv_point)\n    {\n        std::cout << \"LVR <-> OpenCV - Point: Success\" << std::endl;\n    }\n\n    // check opencv transformation\n\n    lvr2::Rotationd cv_rot, lvr_rot;\n\n    double roll = -0.25*M_PI; // cv: z, lvr: x\n    double pitch = 1.6*M_PI; // cv: -x, lvr: y\n    double yaw = -0.06*M_PI; // cv: -y, lvr: z\n\n    // cv rotate x: pitch\n    cv_rot = Eigen::AngleAxisd(roll, Eigen::Vector3d::UnitZ())\n        * Eigen::AngleAxisd(-pitch, Eigen::Vector3d::UnitX())\n        * Eigen::AngleAxisd(-yaw, Eigen::Vector3d::UnitY());\n    \n    // cv -> lvr\n    lvr_rot = lvr2::openCvToLvr(cv_rot);\n\n\n    // cv_rot \n\n    lvr2::Vector3d cv_point_rotated = cv_rot * cv_point;\n    lvr2::Vector3d lvr_point_rotated = lvr_rot * lvr_point;\n\n    // lvr2::openCvToLvr(cv_point_rotated) - lvr_point_rotated\n    if((lvr2::openCvToLvr(cv_point_rotated) - lvr_point_rotated).norm() < 0.000001)\n    {\n        std::cout << \"LVR <-> OpenCV - Rotation Matrix: Success\" << std::endl;\n    } else {\n        std::cout << \"LVR <-> OpenCV - Rotation Matrix: Wrong\" << std::endl;\n    }\n\n    // transformation\n    lvr2::Transformd cv_transform, lvr_transform;\n\n    cv_transform = lvr2::Transformd::Identity();\n    cv_transform.block<3,3>(0,0) = cv_rot;\n    cv_transform(0,2) = 2.0;\n    cv_transform(1,2) = 5.0;\n    cv_transform(2,2) = -1.0;\n\n    lvr_transform = lvr2::openCvToLvr(cv_transform);\n\n    lvr2::Vector3d cv_point_transformed = cv_transform * cv_point;\n    lvr2::Vector3d lvr_point_transformed = lvr_transform * lvr_point;\n\n    if((lvr2::openCvToLvr(cv_point_transformed)-lvr_point_transformed).norm() < 0.000001)\n    {\n        std::cout << \"LVR <-> OpenCV - Transformation Matrix: Success\" << std::endl;\n    } else {\n        std::cout << \"LVR <-> OpenCV - Transformation Matrix: Wrong\" << std::endl;\n    }\n\n    return 0;\n}", "meta": {"hexsha": "f31e49ac83cbacddbc9b7a0f952ee9e25b026622", "size": 2927, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/coordinates/Main.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": "examples/coordinates/Main.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": "examples/coordinates/Main.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": 26.3693693694, "max_line_length": 89, "alphanum_fraction": 0.5654253502, "num_tokens": 1011, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6150878555160665, "lm_q2_score": 0.5039061705290805, "lm_q1q2_score": 0.30994656581204544}}
{"text": "// Copyright Yamaha 2021\n// MIT License\n// https://github.com/yamaha-bps/cbr_control/blob/master/LICENSE\n\n#ifndef CBR_CONTROL__MPC__MPC_TRACKING_HPP_\n#define CBR_CONTROL__MPC__MPC_TRACKING_HPP_\n\n#include <Eigen/Dense>\n#include <cbr_utils/thread_pool.hpp>\n#include <cbr_utils/utils.hpp>\n#include <cbr_math/interp.hpp>\n\n#include <utility>\n#include <future>\n#include <mutex>\n#include <thread>\n\n#include \"cltv_ocp.hpp\"\n#include \"cltv_ocp_lie.hpp\"\n#include \"dltv_ocp.hpp\"\n#include \"dltv_ocp_solver.hpp\"\n#include \"ocp_common.hpp\"\n\nusing std::chrono::duration_cast, std::chrono::duration, std::chrono::nanoseconds;\n\nnamespace cbr\n{\n\n/**\n * @brief Helper type for MPC trajectory tracking\n *\n * CltvOcp requires an interface with get_xxx(tau) methods where tau is\n * the time elapsed from the initial condition of the problem.\n *\n * This class takes functions of absolute time t and implements the required\n * interfaces as functions of relative time.\n */\ntemplate<typename _problem_t>\nstruct MPCTrackingProblem : public _problem_t\n{\npublic:\n  using typename _problem_t::state_t;\n  using typename _problem_t::deriv_t;\n  using typename _problem_t::input_t;\n\n  explicit MPCTrackingProblem(double T, const _problem_t & p)\n  : _problem_t(p), T_(T) {}\n\n  explicit MPCTrackingProblem(double T, _problem_t && p)\n  : _problem_t(std::move(p)), T_(T) {}\n\n  /**\n   * @brief Return the time horizon of the problem\n   * @param[out] T result\n   */\n  double get_T() const {return T_;}\n\n  /**\n   * @brief Return the problem initial condition\n   * @param[out] x0 result\n   */\n  const state_t & get_x0() const {return x0;}\n\n  /**\n   * @brief Get the desired state\n   * @param tau relative problem time tau = t - t0\n   * @return xd(t0 + tau)\n   */\n  state_t get_xd(double tau) const\n  {\n    return xd(t0 + duration_cast<nanoseconds>(duration<double>(tau)));\n  }\n  /**\n   * @brief Get the desired input\n   * @param tau relative problem time tau = t - t0\n   * @return ud(t0 + tau)\n   */\n  input_t get_ud(double tau) const\n  {\n    return ud(t0 + duration_cast<nanoseconds>(duration<double>(tau)));\n  }\n\n  /**\n   * @brief Get the state linearization\n   * @param tau relative problem time tau = t - t0\n   * @return xl(t0 + tau)\n   */\n  state_t get_xl(double tau) const\n  {\n    return xl(t0 + duration_cast<nanoseconds>(duration<double>(tau)));\n  }\n  /**\n   * @brief Get the state derivative linearization\n   * @param tau relative problem time tau = t - t0\n   * @return xldot(t0 + tau)\n   */\n  deriv_t get_xldot(double tau) const\n  {\n    return xldot(t0 + duration_cast<nanoseconds>(duration<double>(tau)));\n  }\n  /**\n   * @brief Get the input linearization\n   * @param tau relative problem time tau = t - t0\n   * @return ul(t0 + tau)\n   */\n  input_t get_ul(double tau) const\n  {\n    return ul(t0 + duration_cast<nanoseconds>(duration<double>(tau)));\n  }\n\nprivate:\n  // These functions return are defined in absolute time\n  std::function<state_t(nanoseconds)> xd = [](nanoseconds) {return state_t{};};\n  std::function<input_t(nanoseconds)> ud = [](nanoseconds) {return input_t{};};\n  std::function<state_t(nanoseconds)> xl = [](nanoseconds) {return state_t{};};\n  std::function<deriv_t(nanoseconds)> xldot = [](nanoseconds) {return deriv_t{};};\n  std::function<input_t(nanoseconds)> ul = [](nanoseconds) {return input_t{};};\n\n  nanoseconds t0 = nanoseconds(0);\n  state_t x0{};\n  double T_{0};\n\n  // MPCTracking modifies the private variables from outside (except T_)\n  template<typename problem_t__, std::size_t nPts__>\n  friend class MPCTracking;\n};\n\n\nstruct MPCTrackingParams\n{\n  double T{10};  // MPC horizon\n  DltvOcpSolverParams solver_params{};\n};\n\n// Trait to detect whether a problem is defined on a lie group\ntemplate<typename, typename = void>\nstruct has_tangent : std::false_type {};\n\ntemplate<typename T>\nstruct has_tangent<T, std::void_t<typename T::Tangent>>: std::true_type {};\n\n\n/**\n * @brief Trajectory tracking with nonlinear MPC\n *\n * @tparam problem_t stationary problem definition with dynamics, weights, and state bounds\n * @tparam nPts_ number of time discretization points\n *\n * NOTE: all set_xxx methods must be called before solving for the first time\n */\ntemplate<typename _problem_t, std::size_t nPts_>\nclass MPCTracking\n{\npublic:\n  // Linearization order used for system linearization\n  static constexpr std::size_t LinOrder = 4;\n\n  static constexpr bool is_lie = has_tangent<typename _problem_t::state_t>::value;\n\n  using problem_t = _problem_t;\n  using state_t = typename problem_t::state_t;\n  using deriv_t = typename problem_t::deriv_t;\n  using input_t = typename problem_t::input_t;  // must be eigen type\n\n  // Use CltvOcpLie or CltvOcp depending on the type of problem we have\n  using cltv_t = typename std::conditional<is_lie,\n      CltvOcpLie<MPCTrackingProblem<_problem_t>>,\n      CltvOcp<MPCTrackingProblem<_problem_t>>\n    >::type;\n\n  using dltv_t = DltvOcp<cltv_t, nPts_, LinOrder>;\n  using solver_t = DltvOcpSolver<dltv_t>;\n\n  using state_traj_t = typename std::conditional<is_lie,\n      std::array<state_t, nPts_>,\n      Eigen::Matrix<double, problem_t::nx, nPts_>\n    >::type;\n\n  struct Solution\n  {\n    DltvOcpSolverCode rc;\n    Eigen::Matrix<double, 1, nPts_> t;\n    state_traj_t x;\n    Eigen::Matrix<double, input_t::SizeAtCompileTime, nPts_> u;\n  };\n\n  MPCTracking() = delete;\n  MPCTracking(const MPCTracking &) = default;\n  MPCTracking(MPCTracking &&) = default;\n  MPCTracking & operator=(const MPCTracking &) = default;\n  MPCTracking & operator=(MPCTracking &&) = default;\n\n  explicit MPCTracking(const _problem_t & problem, MPCTrackingParams param = MPCTrackingParams{})\n  : solver_(\n      DltvOcp<cltv_t, nPts_, LinOrder>(cltv_t(MPCTrackingProblem<_problem_t>(param.T, problem))),\n      param.solver_params\n  ),\n    uspline_(\n      (Eigen::Matrix<double, 1, 2>() << 0., 1.).finished(),\n      input_t::Zero()\n    ),\n    tp_(1)\n  {\n    mpcSol_.rc = DltvOcpSolverCode::no_run;\n\n    lock_problem();\n\n    if constexpr (is_lie) {\n      // lie types default-initialize to identity\n      set_xd([](std::chrono::nanoseconds) {return state_t{};});\n      set_xl([](std::chrono::nanoseconds) {return state_t{};});\n      set_xldot([](std::chrono::nanoseconds) {return deriv_t{};});\n    } else {\n      // Eigen types must be explicitly zero-initialized\n      set_xd([](std::chrono::nanoseconds) {return state_t::Zero();});\n      set_xl([](std::chrono::nanoseconds) {return state_t::Zero();});\n      set_xldot([](std::chrono::nanoseconds) {return deriv_t::Zero();});\n    }\n\n    // zero-initialize linearization and desired inputs\n    set_ud([](std::chrono::nanoseconds) {return input_t::Zero();});\n    set_ul([](std::chrono::nanoseconds) {return input_t::Zero();});\n\n    unlock_problem();\n  }\n\n\n  /**\n   * @brief Block solving to safely update xd/ud/xl/xldot/ul\n   *\n   * Use before calling the set_xxx functions, then call unlock_problem()\n   */\n  void lock_problem() {problemsMtx_.lock();}\n\n\n  /**\n   * @brief Unblock solving\n   *\n   * Use after calling lock_problem()\n   */\n  void unlock_problem() {problemsMtx_.unlock();}\n\n\n  /**\n   * @brief Specify desired state trajectory as a function t -> xd(t) [absolute time]\n   *\n   * Only use after calling lock_problem()\n   *\n   * @param f xd as a function of t\n   */\n  template<typename T>\n  void set_xd(T && f) {solver_.problem().problem().problem().xd = std::forward<T>(f);}\n\n\n  /**\n   * @brief Specify desired input trajectory as a function t -> ud(t) [absolute time]\n   *\n   * Only use after calling lock_problem()\n   *\n   * @param f ud as a function of t\n   */\n\n  template<typename T>\n  void set_ud(T && f) {solver_.problem().problem().problem().ud = std::forward<T>(f);}\n\n\n  /**\n   * @brief Specify state linearization trajectory as a function t -> xd(t) [absolute time]\n   *\n   * Only use after calling lock_problem()\n   *\n   * May be required if xd/ud is changed to be far from current linearization\n   */\n  template<typename T>\n  void set_xl(T && f) {solver_.problem().problem().problem().xl = std::forward<T>(f);}\n\n\n  /**\n   * @brief Specify state linearization trajectory as a function t -> \\dot xd(t) [absolute time]\n   *\n   * Only use after calling lock_problem()\n   *\n   * May be required if xd/ud is changed to be far from current linearization\n   */\n  template<typename T>\n  void set_xldot(T && f) {solver_.problem().problem().problem().xldot = std::forward<T>(f);}\n\n\n  /**\n   * @brief Specify state linearization trajectory as a function t -> xd(t) [absolute time]\n   *\n   * Only use after calling lock_problem()\n   *\n   * May be required if xd/ud is changed to be far from current linearization\n   */\n  template<typename T>\n  void set_ul(T && f) {solver_.problem().problem().problem().ul = std::forward<T>(f);}\n\n\n  /**\n   * @brief Asynchronous update of MPC\n   *\n   * @param t current absolute time\n   * @param xt state at time t\n   * @return future to solver status\n   *\n   * If optimization is already running this function returns without without effect.\n   */\n  std::shared_future<DltvOcpSolverCode>\n  update(const nanoseconds t, const state_t & xt)\n  {\n    std::lock_guard lock(futMtx_);\n    if (fut_.valid()) {\n      if (fut_.wait_for(nanoseconds(0)) != std::future_status::ready) {\n        return {};\n      }\n    }\n\n    fut_ = tp_.enqueue(&MPCTracking::update_, this, t, xt, 1);\n    return fut_.share();\n  }\n\n\n  /**\n   * @brief Blocking update of MPC\n   *\n   * @param t current absolute time\n   * @param xt state at time t\n   * @param iter number of solve/linearaze iterations to run\n   * @return solver status\n   */\n  DltvOcpSolverCode update_sync(const nanoseconds t, const state_t & xt, std::size_t iter = 1)\n  {\n    std::lock_guard lock(futMtx_);\n    if (fut_.valid()) {\n      fut_.wait();\n    }\n    return update_(t, xt, iter);\n  }\n\n\n  /**\n   * @brief Obtain input at given time for most recent solution\n   */\n  input_t get_u(nanoseconds t)\n  {\n    std::lock_guard lock(solutionMtx_);\n    return uspline_.val(duration_cast<duration<double>>(t - uspline_t0_).count());\n  }\n\n\n  /**\n   * @brief Obtain most recent solution\n   *\n   * NOTE: solution times are defined on [0, T]\n   */\n  Solution solution()\n  {\n    std::lock_guard lock(solutionMtx_);\n    return mpcSol_;\n  }\n\nprivate:\n  /**\n   * @brief Internal helper function to update mpc solution\n   */\n  DltvOcpSolverCode update_(std::chrono::nanoseconds t0, const state_t & x0, std::size_t iter)\n  {\n    std::lock_guard lock(problemsMtx_);  // lock for the duration to ensure consistency\n    DltvOcpSolverCode rc = DltvOcpSolverCode::no_run;\n\n    solver_.problem().problem().problem().t0 = t0;\n    solver_.problem().problem().problem().x0 = x0;\n\n    for (std::size_t i = 0; i != iter; ++i) {\n      solver_.init();\n\n      auto sol = solver_.solve();\n      rc = sol.rc;\n\n      if (sol.rc != DltvOcpSolverCode::success) {\n        break;\n      } else {\n        Solution abs_sol;\n        abs_sol.rc = sol.rc;\n\n        for (auto i = 0u; i < nPts_; i++) {\n          // solution is a trajectory around the linearization, we add back\n          // the linearization to get a trajectory in global coordinates\n          const double tt = solver_.problem().indexToTime(i);\n          abs_sol.t[i] = tt;\n          if constexpr (is_lie) {\n            abs_sol.x[i] =\n              solver_.problem().problem().problem().get_xl(tt) * state_t::exp(sol.x.col(i));\n          } else {\n            abs_sol.x.col(i) = solver_.problem().problem().problem().get_xl(tt) + sol.x.col(i);\n          }\n          abs_sol.u.col(i) = solver_.problem().problem().problem().get_ul(tt) + sol.u.col(i);\n        }\n\n        auto ulin = cbr::PiecewiseLinear::fitND(abs_sol.t, abs_sol.u);\n\n        {\n          // store solution so that get_u() can be called\n          std::lock_guard lock(solutionMtx_);\n          mpcSol_ = abs_sol;\n\n          uspline_t0_ = t0;\n          uspline_ = ulin;\n        }\n\n        // Set desired input for future solving to current input\n        solver_.problem().problem().problem().ud =\n          [u0 = abs_sol.u.col(0).eval()](nanoseconds) -> input_t {\n            return u0;\n          };\n\n        // Update linearization points (functions defined in absolute time)\n        solver_.problem().problem().problem().ul =\n          [t0 = t0, ulin = std::move(ulin)](nanoseconds t) -> input_t {\n            return ulin.val(duration_cast<duration<double>>(t - t0).count());\n          };\n\n        if constexpr (is_lie) {\n          // fit splines: first need to copy to a vector\n          vector_aligned<state_t> sol_vec(abs_sol.x.begin(), abs_sol.x.end());\n          auto xlin = cbr::Spline::fitLie(abs_sol.t, std::move(sol_vec));\n          xlin.set_extrap(PiecewisePoly::EXTRAP::CLAMP);\n\n          solver_.problem().problem().problem().xl =\n            [t0 = t0, xlin = xlin](nanoseconds t) -> state_t {\n              const auto t_spline = duration_cast<duration<double>>(t - t0).count();\n              return xlin.val(t_spline);\n            };\n          solver_.problem().problem().problem().xldot =\n            [t0 = t0, xlin = std::move(xlin)](nanoseconds t) -> deriv_t {\n              const auto t_spline = duration_cast<duration<double>>(t - t0).count();\n              return xlin.der(t_spline);\n            };\n        } else {\n          // fit splines\n          auto xlin = cbr::PiecewiseLinear::fitND(abs_sol.t, abs_sol.x);\n\n          solver_.problem().problem().problem().xl =\n            [t0 = t0, xlin = xlin](nanoseconds t) -> state_t {\n              return xlin.val(duration_cast<duration<double>>(t - t0).count());\n            };\n          solver_.problem().problem().problem().xldot =\n            [t0 = t0, xlin = xlin](nanoseconds t) -> deriv_t {\n              return xlin.der(duration_cast<duration<double>>(t - t0).count());\n            };\n        }\n\n        // reset warm-start solution to zeros\n        solver_.set_ic(decltype(sol.x)::Zero(), decltype(sol.u)::Zero());\n      }\n    }\n\n    return rc;\n  }\n\nprivate:\n  solver_t solver_{};\n\n  Solution mpcSol_;\n  std::mutex solutionMtx_, problemsMtx_, futMtx_;\n  std::future<DltvOcpSolverCode> fut_;\n\n  nanoseconds uspline_t0_;\n  cbr::PiecewisePolyND uspline_;\n\n  ThreadPool tp_;\n};\n\n}  // namespace cbr\n\n#endif  // CBR_CONTROL__MPC__MPC_TRACKING_HPP_\n", "meta": {"hexsha": "5ace5e0c53e0eca504aa7ded955587f586b24fba", "size": 14128, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/cbr_control/mpc/mpc_tracking.hpp", "max_stars_repo_name": "yamaha-bps/cbr_control", "max_stars_repo_head_hexsha": "c2faf79673d46c950dd7590f1072fc7decafad06", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/cbr_control/mpc/mpc_tracking.hpp", "max_issues_repo_name": "yamaha-bps/cbr_control", "max_issues_repo_head_hexsha": "c2faf79673d46c950dd7590f1072fc7decafad06", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/cbr_control/mpc/mpc_tracking.hpp", "max_forks_repo_name": "yamaha-bps/cbr_control", "max_forks_repo_head_hexsha": "c2faf79673d46c950dd7590f1072fc7decafad06", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.5564853556, "max_line_length": 97, "alphanum_fraction": 0.6465175538, "num_tokens": 3884, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6150878555160664, "lm_q2_score": 0.5039061705290805, "lm_q1q2_score": 0.3099465658120454}}
{"text": "#pragma once\n#include <tuple>\n#include <fastad_bits/reverse/core/expr_base.hpp>\n#include <fastad_bits/reverse/core/value_adj_view.hpp>\n#include <fastad_bits/reverse/core/constant.hpp>\n#include <fastad_bits/util/type_traits.hpp>\n#include <fastad_bits/util/numeric.hpp>\n#include <Eigen/Dense>\n\nnamespace ad {\nnamespace stat {\nnamespace details {\n\ntemplate <class XExprType\n        , class MeanExprType\n        , class SigmaExprType>\nstruct NormalBase:\n    core::ValueAdjView<util::common_value_t<\n                        XExprType, \n                        MeanExprType, \n                        SigmaExprType>, ad::scl>\n{\n    using x_t = XExprType;\n    using mean_t = MeanExprType;\n    using sigma_t = SigmaExprType;\n    using common_value_t = util::common_value_t<\n        x_t, mean_t, sigma_t>;\n    using value_adj_view_t = core::ValueAdjView<common_value_t, ad::scl>;\n    using typename value_adj_view_t::value_t;\n    using typename value_adj_view_t::shape_t;\n    using typename value_adj_view_t::var_t;\n    using typename value_adj_view_t::ptr_pack_t;\n\n    NormalBase(const x_t& x,\n               const mean_t& mean,\n               const sigma_t& sigma)\n        : value_adj_view_t(nullptr, nullptr, 1, 1)\n        , x_{x}\n        , mean_{mean}\n        , sigma_{sigma}\n    {}\n\n    ptr_pack_t bind_cache(ptr_pack_t begin)\n    {\n        begin = x_.bind_cache(begin);\n        begin = mean_.bind_cache(begin);\n        begin = sigma_.bind_cache(begin);\n        auto adj = begin.adj;\n        begin.adj = nullptr;\n        begin = value_adj_view_t::bind(begin);\n        begin.adj = adj;\n        return begin;\n    }\n\n    util::SizePack bind_cache_size() const \n    { \n        return single_bind_cache_size() + \n                x_.bind_cache_size() +\n                mean_.bind_cache_size() +\n                sigma_.bind_cache_size();\n    }\n\n    util::SizePack single_bind_cache_size() const\n    {\n        return {this->size(), 0}; \n    }\n\nprotected:\n    x_t x_;\n    mean_t mean_;\n    sigma_t sigma_;\n};\n\n} // namespace details\n\n/**\n * NormalAdjLogPDFNode represents the normal log pdf \n * adjusted to omit all fixed constants, i.e. omits -n/2*log(2*pi).\n *\n * It assumes the value type that is common to all three expressions.\n * Since it represents a log-pdf, it is always a scalar expression.\n *\n * The only possible shape combinations are as follows:\n * x -> scalar, mean -> scalar, sigma -> scalar\n * x -> vec, mean -> scalar | vector, sigma -> scalar | vector | self adjoint matrix\n *\n * No other shapes are permitted for this node.\n *\n * At construction, the actual sizes of the three expressions are checked -\n * specifically if x is a vector, and mean and sigma are not scalar,\n * then size of x must be the same as that of mean rows and sigma rows.\n * Additionally, we check that sigma is square if it is a matrix.\n *\n * @tparam  XExprType           type of x expression at which to evaluate log-pdf\n * @tparam  MeanExprType        type of mean expression\n * @tparam  SigmaExprType       type of sigma expression\n */\ntemplate <class XExprType\n        , class MeanExprType\n        , class SigmaExprType\n        , class = std::tuple<\n            typename util::shape_traits<XExprType>::shape_t,\n            typename util::shape_traits<MeanExprType>::shape_t,\n            typename util::shape_traits<SigmaExprType>::shape_t> >\nstruct NormalAdjLogPDFNode;\n\n// Case 1: sss\ntemplate <class XExprType\n        , class MeanExprType\n        , class SigmaExprType>\nstruct NormalAdjLogPDFNode<XExprType, MeanExprType, SigmaExprType,\n                           std::tuple<scl, scl, scl> >:\n    details::NormalBase<XExprType, MeanExprType, SigmaExprType>,\n    core::ExprBase<NormalAdjLogPDFNode<XExprType, MeanExprType, SigmaExprType>>\n{\nprivate:\n    using base_t = details::NormalBase<\n        XExprType, MeanExprType, SigmaExprType>;\n    \npublic:\n    using typename base_t::x_t;\n    using typename base_t::mean_t;\n    using typename base_t::sigma_t;\n    using typename base_t::value_t;\n    using typename base_t::var_t;\n    using base_t::x_;\n    using base_t::mean_;\n    using base_t::sigma_;\n\n    NormalAdjLogPDFNode(const x_t& x,\n                        const mean_t& mean,\n                        const sigma_t& sigma)\n        : base_t(x, mean, sigma)\n        , log_sigma_{0}\n    {\n        if constexpr (util::is_constant_v<sigma_t>) {\n            this->update_cache();\n        }\n    }\n\n    const var_t& feval()\n    {\n        auto&& x = x_.feval();\n        auto&& m = mean_.feval();\n        auto&& s = sigma_.feval();\n\n        if (s <= 0) return this->get() = util::neg_inf<value_t>;\n\n        if constexpr (!util::is_constant_v<sigma_t>) {\n            this->update_cache();\n        }\n\n        auto z = (x - m) / s;\n        \n        return this->get() = -0.5 * z * z - log_sigma_; \n    }\n\n    void beval(value_t seed)\n    {\n        if (seed == 0 || sigma_.get() <= 0) return;\n\n        value_t inv_s = 1./sigma_.get();\n        value_t z = (x_.get() - mean_.get()) * inv_s;\n\n        if constexpr (!util::is_constant_v<sigma_t>) {\n            sigma_.beval(seed * (z*z - 1) * inv_s);\n        }\n        value_t adj = seed * z * inv_s;\n        mean_.beval(adj);\n        x_.beval(-adj);\n    }\n\nprivate:\n    void update_cache() {\n        log_sigma_ = std::log(sigma_.get());\n    }\n\n    value_t log_sigma_;\n};\n\n// Case 2: vss\ntemplate <class XExprType\n        , class MeanExprType\n        , class SigmaExprType>\nstruct NormalAdjLogPDFNode<XExprType, MeanExprType, SigmaExprType,\n                           std::tuple<vec, scl, scl> >:\n    details::NormalBase<XExprType, MeanExprType, SigmaExprType>,\n    core::ExprBase<NormalAdjLogPDFNode<XExprType, MeanExprType, SigmaExprType>>\n{\nprivate:\n    using base_t = details::NormalBase<\n        XExprType, MeanExprType, SigmaExprType>;\n    \npublic:\n    using typename base_t::x_t;\n    using typename base_t::mean_t;\n    using typename base_t::sigma_t;\n    using typename base_t::value_t;\n    using typename base_t::var_t;\n    using base_t::x_;\n    using base_t::mean_;\n    using base_t::sigma_;\n\n    NormalAdjLogPDFNode(const x_t& x,\n                        const mean_t& mean,\n                        const sigma_t& sigma)\n        : base_t(x, mean, sigma)\n        , log_sigma_{0}\n        , z_sq{0}\n        , x_mean_{0}\n        , x_var_{0}\n    {\n        if constexpr (util::is_constant_v<sigma_t>) {\n            this->update_cache();\n        }\n\n        // optimization when x_ is constant\n        // reduced exponential form\n        if constexpr (util::is_constant_v<x_t>) {\n            x_mean_ = x_.get().mean();\n            x_var_ = (x_.get().array() - x_mean_).matrix().squaredNorm();\n        }\n    }\n\n    const var_t& feval()\n    {\n        auto&& x = x_.feval().array();\n        auto&& m = mean_.feval();\n        auto&& s = sigma_.feval();\n\n        if (s <= 0) return this->get() = util::neg_inf<value_t>;\n\n        if constexpr (!util::is_constant_v<sigma_t>) {\n            this->update_cache();\n        }\n\n        if constexpr (util::is_constant_v<x_t>) {\n            value_t centered = (m - x_mean_);\n            value_t inv_s_sq = 1./(s * s);\n            return this->get() = \n                -0.5 * inv_s_sq * (x_var_ + x_.rows() * centered * centered) \n                        - x_.rows() * log_sigma_;\n        } else {\n            auto z = (x - m).matrix();\n            z_sq = z.squaredNorm() / (s * s);\n            return this->get() = -0.5 * z_sq - x_.rows() * log_sigma_; \n        }\n    }\n\n    void beval(value_t seed)\n    {\n        if (seed == 0 || sigma_.get() <= 0) return;\n\n        value_t inv_s = 1./sigma_.get();\n        value_t inv_s_sq = inv_s * inv_s;\n\n        auto&& x = x_.get().array();\n        auto&& m = mean_.get();\n\n        // if x is constant, more optimized beval\n        if constexpr (util::is_constant_v<x_t>) {\n\n            if constexpr (!util::is_constant_v<sigma_t>) {\n                value_t c = (m - x_mean_);\n                value_t sigma_adj = ((x_var_ + x_.rows() * c * c) * inv_s_sq - x_.rows()) * inv_s;\n                sigma_.beval(seed * sigma_adj);\n            }\n\n            value_t mean_adj = x_.rows() * (x_mean_ - m) * inv_s_sq;\n            mean_.beval(seed * mean_adj);\n\n        } else {\n\n            if constexpr (!util::is_constant_v<sigma_t>) {\n                sigma_.beval(seed * (z_sq - x_.rows()) * inv_s);\n            }\n\n            value_t mean_adj = (x.array() - m).sum() * inv_s_sq;\n            mean_.beval(seed * mean_adj);\n\n            if constexpr (!util::is_constant_v<x_t>) {\n                x_.beval((seed * inv_s_sq) * (m - x));\n            }\n\n        }\n    }\n\nprivate:\n    void update_cache() {\n        log_sigma_ = std::log(sigma_.get());\n    }\n\n    value_t log_sigma_;\n\n    // only used when x is not constant\n    value_t z_sq;\n\n    // only used when x is constant\n    value_t x_mean_;    \n    value_t x_var_;\n};\n\n// Case 3: vvs\ntemplate <class XExprType\n        , class MeanExprType\n        , class SigmaExprType>\nstruct NormalAdjLogPDFNode<XExprType, MeanExprType, SigmaExprType,\n                           std::tuple<vec, vec, scl> >:\n    details::NormalBase<XExprType, MeanExprType, SigmaExprType>,\n    core::ExprBase<NormalAdjLogPDFNode<XExprType, MeanExprType, SigmaExprType>>\n{\nprivate:\n    using base_t = details::NormalBase<\n        XExprType, MeanExprType, SigmaExprType>;\n    \npublic:\n    using typename base_t::x_t;\n    using typename base_t::mean_t;\n    using typename base_t::sigma_t;\n    using typename base_t::value_t;\n    using typename base_t::var_t;\n    using base_t::x_;\n    using base_t::mean_;\n    using base_t::sigma_;\n\n    NormalAdjLogPDFNode(const x_t& x,\n                        const mean_t& mean,\n                        const sigma_t& sigma)\n        : base_t(x, mean, sigma)\n        , log_sigma_{0}\n        , z_sq{0}\n    {\n        if constexpr (util::is_constant_v<sigma_t>) {\n            this->update_cache();\n        }\n    }\n\n    const var_t& feval()\n    {\n        auto&& x = x_.feval().array();\n        auto&& m = mean_.feval().array();\n        auto&& s = sigma_.feval();\n\n        if (s <= 0) return this->get() = util::neg_inf<value_t>;\n\n        if constexpr (!util::is_constant_v<sigma_t>) {\n            this->update_cache();\n        }\n\n        auto z = (x - m).matrix();\n        z_sq = z.squaredNorm() / (s * s);\n        \n        return this->get() = -0.5 * z_sq - x_.rows() * log_sigma_; \n    }\n\n    void beval(value_t seed)\n    {\n        if (seed == 0 || sigma_.get() <= 0) return;\n\n        value_t inv_s = 1./sigma_.get();\n        value_t inv_s_sq = inv_s * inv_s;\n\n        auto&& x = x_.get().array();\n        auto&& m = mean_.get().array();\n\n        if constexpr (!util::is_constant_v<sigma_t>) {\n            sigma_.beval(seed * (z_sq - x_.rows()) * inv_s);\n        }\n\n        mean_.beval((seed * inv_s_sq) * (x - m));\n        x_.beval((seed * inv_s_sq) * (m - x));\n    }\n\nprivate:\n    void update_cache() {\n        log_sigma_ = std::log(sigma_.get());\n    }\n\n    value_t log_sigma_;\n    value_t z_sq;\n};\n\n// Case 4: vsv\ntemplate <class XExprType\n        , class MeanExprType\n        , class SigmaExprType>\nstruct NormalAdjLogPDFNode<XExprType, MeanExprType, SigmaExprType,\n                           std::tuple<vec, scl, vec> >:\n    details::NormalBase<XExprType, MeanExprType, SigmaExprType>,\n    core::ExprBase<NormalAdjLogPDFNode<XExprType, MeanExprType, SigmaExprType>>\n{\nprivate:\n    using base_t = details::NormalBase<\n        XExprType, MeanExprType, SigmaExprType>;\n    \npublic:\n    using typename base_t::x_t;\n    using typename base_t::mean_t;\n    using typename base_t::sigma_t;\n    using typename base_t::value_t;\n    using typename base_t::var_t;\n    using base_t::x_;\n    using base_t::mean_;\n    using base_t::sigma_;\n\n    NormalAdjLogPDFNode(const x_t& x,\n                        const mean_t& mean,\n                        const sigma_t& sigma)\n        : base_t(x, mean, sigma)\n        , log_sigma_{0}\n        , is_pos_def_{false}\n        , sq_term_{0}\n        , lin_term_{0}\n        , const_term_{0}\n    {\n        if constexpr (util::is_constant_v<sigma_t>) {\n            this->update_cache();\n\n            // if additionally x is constant, more optimized form\n            if constexpr (util::is_constant_v<x_t>) {\n                auto&& x = x_.get().array();\n                auto&& s = sigma_.get().array();\n                sq_term_ = (x/s).matrix().squaredNorm(); \n                lin_term_ = (x/(s * s)).sum();\n                const_term_ = (1./s).matrix().squaredNorm();\n            }\n        }\n    }\n\n    const var_t& feval()\n    {\n        auto&& x = x_.feval().array();\n        auto&& m = mean_.feval();\n        auto&& s = sigma_.feval().array();\n\n        if constexpr (!util::is_constant_v<sigma_t>) {\n            this->update_cache();\n        }\n\n        if (!is_pos_def_) {\n            return this->get() = util::neg_inf<value_t>;\n        }\n\n        if constexpr (util::is_constant_v<x_t> &&\n                      util::is_constant_v<sigma_t>) {\n            return this->get() = \n                -0.5 * (sq_term_ - 2 * m * lin_term_ + m * m * const_term_)\n                    - log_sigma_;\n        } else {\n            auto z = ((x - m) / s).matrix();\n            return this->get() = -0.5 * z.squaredNorm() - log_sigma_; \n        }\n    }\n\n    void beval(value_t seed)\n    {\n        if (seed == 0 || !is_pos_def_) return;\n\n        auto&& x = x_.get().array();\n        auto&& m = mean_.get();\n        auto&& s = sigma_.get().array();\n\n        if constexpr (util::is_constant_v<x_t> &&\n                      util::is_constant_v<sigma_t>) {\n            value_t mean_adj = lin_term_ - m * const_term_;\n            mean_.beval(seed * mean_adj);\n        } else {\n\n            if constexpr (!util::is_constant_v<sigma_t>) {\n                sigma_.beval((seed / s) * ( ((x - m)/s).square() - 1. ));\n            }\n\n            value_t mean_adj = ((x - m) / s.square()).sum();\n            mean_.beval(seed * mean_adj);\n            x_.beval((seed / s.square()) * (m - x));\n\n        }\n    }\n\nprivate:\n    void update_cache() {\n        is_pos_def_ = (sigma_.get().array() > 0).all();\n        if (is_pos_def_) {\n            log_sigma_ = sigma_.get().array().log().sum();\n        }\n    }\n\n    value_t log_sigma_;\n    size_t is_pos_def_;\n\n    // only used when x and sigma are both constant\n    value_t sq_term_;\n    value_t lin_term_;\n    value_t const_term_;\n};\n\n// Case 5: vvv\ntemplate <class XExprType\n        , class MeanExprType\n        , class SigmaExprType>\nstruct NormalAdjLogPDFNode<XExprType, MeanExprType, SigmaExprType,\n                           std::tuple<vec, vec, vec> >:\n    details::NormalBase<XExprType, MeanExprType, SigmaExprType>,\n    core::ExprBase<NormalAdjLogPDFNode<XExprType, MeanExprType, SigmaExprType>>\n{\nprivate:\n    using base_t = details::NormalBase<\n        XExprType, MeanExprType, SigmaExprType>;\n    \npublic:\n    using typename base_t::x_t;\n    using typename base_t::mean_t;\n    using typename base_t::sigma_t;\n    using typename base_t::value_t;\n    using typename base_t::var_t;\n    using base_t::x_;\n    using base_t::mean_;\n    using base_t::sigma_;\n\n    NormalAdjLogPDFNode(const x_t& x,\n                        const mean_t& mean,\n                        const sigma_t& sigma)\n        : base_t(x, mean, sigma)\n        , log_sigma_{0}\n        , is_pos_def_{false}\n    {\n        if constexpr (util::is_constant_v<sigma_t>) {\n            this->update_cache();\n        }\n    }\n\n    const var_t& feval()\n    {\n        auto&& x = x_.feval().array();\n        auto&& m = mean_.feval().array();\n        auto&& s = sigma_.feval().array();\n\n        if constexpr (!util::is_constant_v<sigma_t>) {\n            this->update_cache();\n        }\n\n        if (!is_pos_def_) {\n            return this->get() = util::neg_inf<value_t>;\n        }\n\n        auto z = ((x - m) / s).matrix();\n        \n        return this->get() = -0.5 * z.squaredNorm() - log_sigma_; \n    }\n\n    void beval(value_t seed)\n    {\n        if (seed == 0 || !is_pos_def_) return;\n\n        auto&& x = x_.get().array();\n        auto&& m = mean_.get().array();\n        auto&& s = sigma_.get().array();\n\n        if constexpr (!util::is_constant_v<sigma_t>) {\n            sigma_.beval((seed / s) * ( ((x - m)/s).square() - 1. ));\n        }\n\n        mean_.beval(seed * (x - m) / s.square());\n        x_.beval(seed * (m - x) / s.square());\n    }\n\nprivate:\n    void update_cache()\n    {\n        is_pos_def_ = (sigma_.get().array() > 0).all();\n        if (is_pos_def_) {\n            log_sigma_ = sigma_.get().array().log().sum();\n        }\n    }\n\n    value_t log_sigma_;\n    size_t is_pos_def_;\n};\n\n// Case 6: vsm\ntemplate <class XExprType\n        , class MeanExprType\n        , class SigmaExprType>\nstruct NormalAdjLogPDFNode<XExprType, MeanExprType, SigmaExprType,\n                           std::tuple<vec, scl, \n                                std::enable_if_t<util::is_mat_v<SigmaExprType>,\n                                    typename util::shape_traits<SigmaExprType>::shape_t>> >:\n    details::NormalBase<XExprType, MeanExprType, SigmaExprType>,\n    core::ExprBase<NormalAdjLogPDFNode<XExprType, MeanExprType, SigmaExprType>>\n{\nprivate:\n    using base_t = details::NormalBase<\n        XExprType, MeanExprType, SigmaExprType>;\n    \npublic:\n    using typename base_t::x_t;\n    using typename base_t::mean_t;\n    using typename base_t::sigma_t;\n    using typename base_t::value_t;\n    using typename base_t::var_t;\n    using base_t::x_;\n    using base_t::mean_;\n    using base_t::sigma_;\n\n    NormalAdjLogPDFNode(const x_t& x,\n                        const mean_t& mean,\n                        const sigma_t& sigma)\n        : base_t(x, mean, sigma)\n        , llt_(sigma.rows())\n        , log_det_{0}\n        , is_pos_def_{false}\n        , inv_(sigma.rows(), sigma.cols())\n        , z_(mean.cols())\n    {\n        // must be square matrix\n        assert(sigma_.rows() == sigma_.cols());\n        assert(x_.rows() == sigma_.rows());\n\n        if constexpr (util::is_constant_v<sigma_t>) {\n            this->update_cache();\n        }\n    }\n\n    const var_t& feval()\n    {\n        auto&& x = x_.feval().array();\n        auto&& m = mean_.feval();\n        sigma_.feval();\n\n        if constexpr (!util::is_constant_v<sigma_t>) {\n            this->update_cache();\n        }\n\n        if (!is_pos_def_) {\n            return this->get() = util::neg_inf<value_t>;\n        }\n        \n        z_ = inv_ * (x - m).matrix();\n        value_t sq_term = (x - m).matrix().transpose() * z_;\n        \n        return this->get() = -0.5 * sq_term - log_det_; \n    }\n\n    void beval(value_t seed)\n    {\n        if (seed == 0 || !is_pos_def_) return;\n\n        if constexpr (!util::is_constant_v<sigma_t>) {\n            auto adj = (-0.5 * seed) * (inv_ - z_ * z_.transpose());\n            sigma_.beval(adj.array());\n        }\n\n        mean_.beval(seed * z_.sum());\n        x_.beval((-seed) * z_.array());\n    }\n\nprivate:\n    void update_cache() {\n        llt_.compute(sigma_.get());\n        is_pos_def_ = (llt_.info() == Eigen::Success);\n        if (is_pos_def_) {\n            log_det_ = std::log(llt_.matrixL().determinant());\n            inv_ = llt_.solve(mat_t::Identity(sigma_.rows(), sigma_.cols()));\n        }\n    }\n\n    using mat_t = Eigen::Matrix<value_t, Eigen::Dynamic, Eigen::Dynamic>;\n    using vec_t = Eigen::Matrix<value_t, Eigen::Dynamic, 1>;\n\n    Eigen::LLT<mat_t, Eigen::Lower> llt_;\n    value_t log_det_;\n    bool is_pos_def_;\n    mat_t inv_;\n    vec_t z_;\n};\n\n// Case 7: vvm\ntemplate <class XExprType\n        , class MeanExprType\n        , class SigmaExprType>\nstruct NormalAdjLogPDFNode<XExprType, MeanExprType, SigmaExprType,\n                           std::tuple<vec, vec, \n                                std::enable_if_t<util::is_mat_v<SigmaExprType>,\n                                    typename util::shape_traits<SigmaExprType>::shape_t>> >:\n    details::NormalBase<XExprType, MeanExprType, SigmaExprType>,\n    core::ExprBase<NormalAdjLogPDFNode<XExprType, MeanExprType, SigmaExprType>>\n{\nprivate:\n    using base_t = details::NormalBase<\n        XExprType, MeanExprType, SigmaExprType>;\n    \npublic:\n    using typename base_t::x_t;\n    using typename base_t::mean_t;\n    using typename base_t::sigma_t;\n    using typename base_t::value_t;\n    using typename base_t::var_t;\n    using base_t::x_;\n    using base_t::mean_;\n    using base_t::sigma_;\n\n    NormalAdjLogPDFNode(const x_t& x,\n                        const mean_t& mean,\n                        const sigma_t& sigma)\n        : base_t(x, mean, sigma)\n        , llt_(sigma.rows())\n        , log_det_{0}\n        , is_pos_def_{false}\n        , inv_(sigma.rows(), sigma.cols())\n        , z_(mean.cols())\n    {\n        // must be square matrix\n        assert(sigma_.rows() == sigma_.cols());\n        assert(x_.rows() == mean_.rows());\n        assert(x_.rows() == sigma_.rows());\n\n        if constexpr (util::is_constant_v<sigma_t>) {\n            this->update_cache();\n        }\n    }\n\n    const var_t& feval()\n    {\n        auto&& x = x_.feval();\n        auto&& m = mean_.feval();\n        sigma_.feval();\n\n        if constexpr (!util::is_constant_v<sigma_t>) {\n            this->update_cache();\n        }\n\n        if (!is_pos_def_) {\n            return this->get() = util::neg_inf<value_t>;\n        }\n        \n        z_ = inv_ * (x - m);\n        value_t sq_term = (x - m).transpose() * z_;\n        \n        return this->get() = -0.5 * sq_term - log_det_; \n    }\n\n    void beval(value_t seed)\n    {\n        if (seed == 0 || !is_pos_def_) return;\n\n        if constexpr (!util::is_constant_v<sigma_t>) {\n            auto adj = (-0.5 * seed) * (inv_ - z_ * z_.transpose());\n            sigma_.beval(adj.array());\n        }\n\n        mean_.beval(seed * z_.array());\n        x_.beval((-seed) * z_.array());\n    }\n\nprivate:\n    void update_cache() {\n        llt_.compute(sigma_.get());\n        is_pos_def_ = (llt_.info() == Eigen::Success);\n        if (is_pos_def_) {\n            log_det_ = std::log(llt_.matrixL().determinant());\n            inv_ = llt_.solve(mat_t::Identity(sigma_.rows(), sigma_.cols()));\n        }\n    }\n\n    using mat_t = Eigen::Matrix<value_t, Eigen::Dynamic, Eigen::Dynamic>;\n    using vec_t = Eigen::Matrix<value_t, Eigen::Dynamic, 1>;\n\n    Eigen::LLT<mat_t, Eigen::Lower> llt_;\n    value_t log_det_;\n    bool is_pos_def_;\n    mat_t inv_;\n    vec_t z_;\n};\n\n} // namespace stat\n\ntemplate <class XType\n        , class MeanType\n        , class SigmaType\n        , class = std::enable_if_t<\n            util::is_convertible_to_ad_v<XType> &&\n            util::is_convertible_to_ad_v<MeanType> &&\n            util::is_convertible_to_ad_v<SigmaType> &&\n            util::any_ad_v<XType, MeanType, SigmaType> > >\ninline auto normal_adj_log_pdf(const XType& x,\n                               const MeanType& mean,\n                               const SigmaType& sigma)\n{\n    using x_expr_t = util::convert_to_ad_t<XType>;\n    using mean_expr_t = util::convert_to_ad_t<MeanType>;\n    using sigma_expr_t = util::convert_to_ad_t<SigmaType>;\n    x_expr_t x_expr = x;\n    mean_expr_t mean_expr = mean;\n    sigma_expr_t sigma_expr = sigma;\n    return stat::NormalAdjLogPDFNode<\n        x_expr_t, mean_expr_t, sigma_expr_t>(x_expr, mean_expr, sigma_expr);\n}\n\n} // namespace ad\n", "meta": {"hexsha": "6ddc49dfdc8cf73b58fe7a19ead6def963435bc8", "size": 23171, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/fastad_bits/reverse/stat/normal.hpp", "max_stars_repo_name": "kilasuelika/FastAD", "max_stars_repo_head_hexsha": "dd070c608c18f5391f2ac68dca4f9db223a33eca", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 50.0, "max_stars_repo_stars_event_min_datetime": "2019-11-28T22:25:01.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-20T03:55:19.000Z", "max_issues_repo_path": "include/fastad_bits/reverse/stat/normal.hpp", "max_issues_repo_name": "kilasuelika/FastAD", "max_issues_repo_head_hexsha": "dd070c608c18f5391f2ac68dca4f9db223a33eca", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 25.0, "max_issues_repo_issues_event_min_datetime": "2019-11-28T20:44:12.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-30T00:14:39.000Z", "max_forks_repo_path": "include/fastad_bits/reverse/stat/normal.hpp", "max_forks_repo_name": "kilasuelika/FastAD", "max_forks_repo_head_hexsha": "dd070c608c18f5391f2ac68dca4f9db223a33eca", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-02-26T11:14:56.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-07T06:40:18.000Z", "avg_line_length": 28.96375, "max_line_length": 98, "alphanum_fraction": 0.5590608951, "num_tokens": 6119, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5964331319177488, "lm_q2_score": 0.5195213219520929, "lm_q1q2_score": 0.30985972914993587}}
{"text": "#include <string>\n#include <stdexcept>\n\n#include <cstdlib>\n\n#include <armadillo>\n\n#include \"Conv2D/Mesh.hpp\"\n#include \"Conv2D/EulerDefaultBase.hpp\"\n\nclass Euler : public EulerDefaultBase\n{\npublic:\n    Euler() : EulerDefaultBase()\n    {\n    }\n\n    ~Euler() = default;\n\n    void computeBottomFlux(const arma::vec &UInt, const arma::rowvec &n,\n                           arma::vec &U, arma::vec &F, double &s) const;\n\n    void computeRightFlux(const arma::vec &UInt, const arma::rowvec &n,\n                          arma::vec &U, arma::vec &F, double &s) const;\n\n    void computeTopFlux(const arma::vec &UInt, const arma::rowvec &n,\n                        arma::vec &U, arma::vec &F, double &s) const;\n\n    void computeLeftFlux(const arma::vec &UInt, const arma::rowvec &n,\n                         arma::vec &U, arma::vec &F, double &s) const;\n};\n\nvoid Euler::computeTopFlux(const arma::vec &UInt, const arma::rowvec &n,\n                           arma::vec &U, arma::vec &F, double &s) const\n{\n    applyInvisidWallBC(UInt, n, U, F, s);\n}\n\nvoid Euler::computeBottomFlux(const arma::vec &UInt, const arma::rowvec &n,\n                              arma::vec &U, arma::vec &F, double &s) const\n{\n    applyInvisidWallBC(UInt, n, U, F, s);\n}\n\nvoid Euler::computeLeftFlux(const arma::vec &UInt, const arma::rowvec &n,\n                            arma::vec &U, arma::vec &F, double &s) const\n{\n    applyInflowBC(UInt, n, U, F, s);\n}\n\nvoid Euler::computeRightFlux(const arma::vec &UInt, const arma::rowvec &n,\n                             arma::vec &U, arma::vec &F, double &s) const\n{\n    applyOutflowBC(UInt, n, U, F, s);\n}\n\nint main(int argc, char **argv)\n{\n    if (argc != 2)\n    {\n        throw std::runtime_error(\"No choice of input mesh given\");\n    }\n\n    int choice = std::atoi(argv[1]);\n\n    if (choice < 0 || choice > 4)\n    {\n        throw std::runtime_error(\"Invalid choice of input mesh\");\n    }\n\n    const std::string choiceString = std::to_string(choice);\n\n    const std::string meshFile       = \"bump\" + choiceString + \".gri\";\n    const std::string residualFile   = \"FirstOrderSolverResidual\" + choiceString + \".dat\";\n    const std::string validationFile = \"FirstOrderSolverValidation\" + choiceString + \".dat\";\n    const std::string pressureFile   = \"FirstOrderSolverPressureCoefficients\" + choiceString + \".dat\";\n    const std::string machFile       = \"FirstOrderSolverMachNumbers\" + choiceString + \".vtk\";\n    const std::string solutionFile   = \"FirstOrderSolverSolution\" + choiceString + \".dat\";\n\n    Mesh mesh;\n    mesh.readFromFile(meshFile);\n    mesh.computeMatrices();\n\n    Euler problem;\n    problem.setMesh(mesh);\n    problem.setGasConstant(1.0);\n    problem.setSpecificHeatRatio(1.4);\n    problem.setFreeFlowMachNumber(0.5);\n    problem.setFreeFlowStaticPressure(1.0);\n    problem.setCFLNumber(0.5);\n\n    problem.setInitialState();\n\n    const double tolerance = 1.0e-07;\n    problem.runFirstOrderSolver(tolerance, residualFile);\n\n    problem.writeValidationValuesTofile(validationFile);\n    problem.writePressureCoefficientsToFile(pressureFile);\n    problem.writeMachNumbersToFile(machFile);\n\n    problem.writeStateToFile(solutionFile);\n\n    return 0;\n}\n", "meta": {"hexsha": "021f969e65e8c27d6b3305bcda20c2d1427aa34b", "size": 3172, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "app/FirstOrderSolver.cpp", "max_stars_repo_name": "saibalde/Aerosp623Project2", "max_stars_repo_head_hexsha": "cfa1c725f370404b2a2cee463d51826b9592d066", "max_stars_repo_licenses": ["MIT"], "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/FirstOrderSolver.cpp", "max_issues_repo_name": "saibalde/Aerosp623Project2", "max_issues_repo_head_hexsha": "cfa1c725f370404b2a2cee463d51826b9592d066", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "app/FirstOrderSolver.cpp", "max_forks_repo_name": "saibalde/Aerosp623Project2", "max_forks_repo_head_hexsha": "cfa1c725f370404b2a2cee463d51826b9592d066", "max_forks_repo_licenses": ["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.2095238095, "max_line_length": 102, "alphanum_fraction": 0.6314627995, "num_tokens": 853, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.5583269943353745, "lm_q1q2_score": 0.30957582814909296}}
{"text": "/*\n * fusion_runge_kutta.hpp\n *\n * Copyright 2010-2011 Mario Mulansky\n * Copyright 2010-2012 Karsten Ahnert\n *\n * Distributed under the Boost Software License, Version 1.0.\n * (See accompanying file LICENSE_1_0.txt or\n * copy at http://www.boost.org/LICENSE_1_0.txt)\n */\n\n\n#ifndef FUSION_EXPLICIT_RK_HPP_\n#define FUSION_EXPLICIT_RK_HPP_\n\n#include <boost/mpl/vector.hpp>\n#include <boost/mpl/push_back.hpp>\n#include <boost/mpl/for_each.hpp>\n#include <boost/mpl/range_c.hpp>\n#include <boost/mpl/copy.hpp>\n#include <boost/mpl/size_t.hpp>\n\n#include <boost/fusion/container.hpp>\n#include <boost/fusion/algorithm/iteration.hpp>\n\n#include <boost/array.hpp>\n\n#include \"fusion_algebra.hpp\"\n//#include \"fusion_foreach_performance.hpp\"\n\nnamespace mpl = boost::mpl;\nnamespace fusion = boost::fusion;\n\nusing namespace std;\n\nstruct intermediate_stage {};\nstruct last_stage {};\n\n\n\ntemplate< class T , class Constant >\nstruct array_wrapper\n{\n    typedef const typename boost::array< T , Constant::value > type;\n};\n\ntemplate< class T , size_t i , class StageCategory >\nstruct stage\n{\n    T c;\n    boost::array< T , i > a;\n    typedef StageCategory category;\n};\n\ntemplate< class T , size_t i>\nstruct stage< T , i , last_stage >\n{\n    T c;\n    boost::array< T , i > b;\n    typedef last_stage category;\n};\n\n\n\ntemplate< class T , class Constant , class StageCategory >\nstruct stage_wrapper\n{\n    typedef stage< T , Constant::value , StageCategory > type;\n};\n\n\ntemplate< class StateType , size_t stage_count >\nclass explicit_rk\n{\n\npublic:\n\n    typedef StateType state_type;\n\n    typedef mpl::range_c< size_t , 1 , stage_count > stage_indices;\n\n    typedef typename fusion::result_of::as_vector\n    <\n        typename mpl::copy\n        <\n            stage_indices ,\n            mpl::inserter\n            <\n                mpl::vector0< > ,\n                mpl::push_back< mpl::_1 , array_wrapper< double , mpl::_2 > >\n            >\n        >::type\n    >::type coef_a_type;\n\n    typedef boost::array< double , stage_count > coef_b_type;\n    typedef boost::array< double , stage_count > coef_c_type;\n\n    typedef typename fusion::result_of::as_vector\n    <\n        typename mpl::push_back\n        <\n            typename mpl::copy\n            <\n                stage_indices,\n                mpl::inserter\n                <\n                    mpl::vector0<> ,\n                    mpl::push_back< mpl::_1 , stage_wrapper< double , mpl::_2 , intermediate_stage > >\n                >\n            >::type ,\n            stage< double , stage_count , last_stage >\n        >::type\n    >::type stage_vector_base;\n\n\n    struct stage_vector : public stage_vector_base\n    {\n        struct do_insertion\n        {\n            stage_vector_base &m_base;\n            const coef_a_type &m_a;\n            const coef_c_type &m_c;\n\n            do_insertion( stage_vector_base &base , const coef_a_type &a , const coef_c_type &c )\n            : m_base( base ) , m_a( a ) , m_c( c ) { }\n\n            template< class Index >\n            void operator()( Index ) const\n            {\n                //fusion::at< Index >( m_base ) = stage< double , Index::value+1 , intermediate_stage >( m_c[ Index::value ] , fusion::at< Index >( m_a ) );\n                fusion::at< Index >( m_base ).c  = m_c[ Index::value ];\n                fusion::at< Index >( m_base ).a = fusion::at< Index >( m_a );\n            }\n        };\n\n        stage_vector( const coef_a_type &a , const coef_b_type &b , const coef_c_type &c )\n        {\n            typedef mpl::range_c< size_t , 0 , stage_count - 1 > indices;\n            mpl::for_each< indices >( do_insertion( *this , a , c ) );\n            //fusion::at_c< 0 >( fusion::at_c< stage_count - 1 >( *this ) ) = stage_count - 1 ;\n            fusion::at_c< stage_count - 1 >( *this ).c = c[ stage_count - 1 ];\n            fusion::at_c< stage_count - 1 >( *this ).b = b;\n        }\n    };\n\n\n\n    template< class System >\n    struct calculate_stage\n    {\n        System &system;\n        state_type &x , &x_tmp;\n        state_type *F;\n        const double t;\n        const double dt;\n\n        calculate_stage( System &_system , state_type &_x , state_type &_x_tmp , state_type *_F ,\n                            const double _t , const double _dt )\n        : system( _system ) , x( _x ) , x_tmp( _x_tmp ) , F( _F ) , t( _t ) , dt( _dt )\n        {}\n\n\n        template< typename T , size_t stage_number >\n        void inline operator()( stage< T , stage_number , intermediate_stage > const &stage ) const\n        //typename stage_fusion_wrapper< T , mpl::size_t< stage_number > , intermediate_stage >::type const &stage ) const\n        {\n            if( stage_number == 1 )\n                system( x , F[stage_number-1] , t + stage.c * dt );\n            else\n                system( x_tmp , F[stage_number-1] , t + stage.c * dt );\n\n            fusion_algebra<stage_number>::foreach( x_tmp , x , stage.a , F , dt);\n        }\n\n\n        template< typename T , size_t stage_number >\n        void inline operator()( stage< T , stage_number , last_stage > const &stage ) const\n        //void operator()( typename stage_fusion_wrapper< T , mpl::size_t< stage_number > , last_stage >::type const &stage ) const\n        {\n            if( stage_number == 1 )\n                system( x , F[stage_number-1] , t + stage.c * dt );\n            else\n                system( x_tmp , F[stage_number-1] , t + stage.c * dt );\n\n            fusion_algebra<stage_number>::foreach( x , x , stage.b , F , dt);\n        }\n\n\n    };\n\npublic:\n\n    explicit_rk( const coef_a_type &a ,\n                  const coef_b_type &b ,\n                  const coef_c_type &c )\n    : m_stages( a , b , c )\n\n    { }\n\n\n    template< class System >\n    void inline do_step( System system , state_type &x , const double t , const double dt )\n    {\n        fusion::for_each( m_stages , calculate_stage< System >( system , x , m_x_tmp , m_F , t , dt ) );\n    }\n\nprivate:\n\n    stage_vector m_stages;\n    state_type m_x_tmp;\n\nprotected:\n    state_type m_F[stage_count];\n\n};\n\n#endif /* FUSION_EXPLICIT_RK_HPP_ */\n", "meta": {"hexsha": "d16a67b5eb4338021404bcf2d30e60cd9b02aa38", "size": 6034, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/boost_1_56_0/libs/numeric/odeint/performance/fusion_explicit_rk_new.hpp", "max_stars_repo_name": "cooparation/caffe-android", "max_stars_repo_head_hexsha": "cd91078d1f298c74fca4c242531989d64a32ba03", "max_stars_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_stars_count": 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": "boost/boost_1_56_0/libs/numeric/odeint/performance/fusion_explicit_rk_new.hpp", "max_issues_repo_name": "cooparation/caffe-android", "max_issues_repo_head_hexsha": "cd91078d1f298c74fca4c242531989d64a32ba03", "max_issues_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_issues_count": 61.0, "max_issues_repo_issues_event_min_datetime": "2015-05-27T11:20:11.000Z", "max_issues_repo_issues_event_max_datetime": "2019-12-20T15:06:21.000Z", "max_forks_repo_path": "boost/boost_1_56_0/libs/numeric/odeint/performance/fusion_explicit_rk_new.hpp", "max_forks_repo_name": "cooparation/caffe-android", "max_forks_repo_head_hexsha": "cd91078d1f298c74fca4c242531989d64a32ba03", "max_forks_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_forks_count": 27.0, "max_forks_repo_forks_event_min_datetime": "2015-01-28T16:33:30.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-12T05:04:39.000Z", "avg_line_length": 27.6788990826, "max_line_length": 156, "alphanum_fraction": 0.5802121313, "num_tokens": 1516, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5583269943353745, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.30957582814909296}}
{"text": "#ifndef STAN_MATH_PRIM_PROB_VON_MISES_RNG_HPP\n#define STAN_MATH_PRIM_PROB_VON_MISES_RNG_HPP\n\n#include <stan/math/prim/meta.hpp>\n#include <stan/math/prim/err.hpp>\n#include <stan/math/prim/fun/constants.hpp>\n#include <stan/math/prim/fun/max_size.hpp>\n#include <boost/random/uniform_real_distribution.hpp>\n#include <boost/random/variate_generator.hpp>\n#include <cmath>\n\nnamespace stan {\nnamespace math {\n\n/** \\ingroup prob_dists\n * Return a von Mises random variate for the given location and concentration\n * using the specified random number generator.\n *\n * mu and kappa can each be a scalar or a vector. Any non-scalar\n * inputs must be the same length.\n *\n * The algorithm used in von_mises_rng is a modified version of the\n * algorithm in:\n *\n * Efficient Simulation of the von Mises Distribution\n * D. J. Best and N. I. Fisher\n * Journal of the Royal Statistical Society. Series C (Applied Statistics),\n * Vol. 28, No. 2 (1979), pp. 152-157\n *\n * For kappa < 1.4e-8, this reduces to a uniform distribution.\n *\n * @tparam T_loc type of location parameter\n * @tparam T_conc type of scale (concentration) parameter\n * @tparam RNG type of random number generator\n *\n * @param mu (Sequence of) location parameter(s)\n * @param kappa (Sequence of) non-negative scale (concentration) parameter(s)\n * @param rng random number generator\n * @return (Sequence of) von Mises random variate(s)\n * @throw std::domain_error if mu is infinite or kappa is negative\n * @throw std::invalid_argument if non-scalar arguments are of different\n * sizes\n */\ntemplate <typename T_loc, typename T_conc, class RNG>\ninline typename VectorBuilder<true, double, T_loc, T_conc>::type von_mises_rng(\n    const T_loc& mu, const T_conc& kappa, RNG& rng) {\n  using boost::random::uniform_real_distribution;\n  using boost::variate_generator;\n  static const char* function = \"von_mises_rng\";\n\n  check_finite(function, \"Location parameter\", mu);\n  check_nonnegative(function, \"Scale parameter\", kappa);\n  check_finite(function, \"Scale parameter\", kappa);\n  check_consistent_sizes(function, \"Location parameter\", mu, \"Scale parameter\",\n                         kappa);\n\n  scalar_seq_view<T_loc> mu_vec(mu);\n  scalar_seq_view<T_conc> kappa_vec(kappa);\n  size_t N = max_size(mu, kappa);\n  VectorBuilder<true, double, T_loc, T_conc> output(N);\n\n  variate_generator<RNG&, uniform_real_distribution<> > uniform_rng(\n      rng, uniform_real_distribution<>(0.0, 1.0));\n\n  for (size_t n = 0; n < N; ++n) {\n    // for kappa sufficiently close to zero, it reduces to a\n    // circular uniform distribution centered at mu\n    if (kappa_vec[n] < 1.4e-8) {\n      output[n] = (uniform_rng() - 0.5) * TWO_PI\n                  + std::fmod(std::fmod(mu_vec[n], TWO_PI) + TWO_PI, TWO_PI);\n      continue;\n    }\n\n    double r = 1 + std::pow((1 + 4 * kappa_vec[n] * kappa_vec[n]), 0.5);\n    double rho = 0.5 * (r - std::pow(2 * r, 0.5)) / kappa_vec[n];\n    double s = 0.5 * (1 + rho * rho) / rho;\n\n    bool done = false;\n    double W;\n    while (!done) {\n      double Z = std::cos(pi() * uniform_rng());\n      W = (1 + s * Z) / (s + Z);\n      double Y = kappa_vec[n] * (s - W);\n      double U2 = uniform_rng();\n      done = Y * (2 - Y) - U2 > 0;\n\n      if (!done) {\n        done = std::log(Y / U2) + 1 - Y >= 0;\n      }\n    }\n\n    double U3 = uniform_rng() - 0.5;\n    double sign = ((U3 >= 0) - (U3 <= 0));\n\n    //  it's really an fmod() with a positivity constraint\n    output[n] = sign * std::acos(W)\n                + std::fmod(std::fmod(mu_vec[n], TWO_PI) + TWO_PI, TWO_PI);\n  }\n\n  return output.data();\n}\n\n}  // namespace math\n}  // namespace stan\n#endif\n", "meta": {"hexsha": "337acd8cc86e5c828bb1f37869dfc5eaf9f4f4aa", "size": 3604, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "stan/math/prim/prob/von_mises_rng.hpp", "max_stars_repo_name": "kedartal/math", "max_stars_repo_head_hexsha": "77248cf73c1110660006c9700f78d9bb7c02be1d", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "stan/math/prim/prob/von_mises_rng.hpp", "max_issues_repo_name": "kedartal/math", "max_issues_repo_head_hexsha": "77248cf73c1110660006c9700f78d9bb7c02be1d", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "stan/math/prim/prob/von_mises_rng.hpp", "max_forks_repo_name": "kedartal/math", "max_forks_repo_head_hexsha": "77248cf73c1110660006c9700f78d9bb7c02be1d", "max_forks_repo_licenses": ["BSD-3-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.0, "max_line_length": 79, "alphanum_fraction": 0.6639844617, "num_tokens": 1021, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5621765008857982, "lm_q2_score": 0.5506073655352404, "lm_q1q2_score": 0.30953852211854904}}
{"text": "// Copyright 2018 The Simons Foundation, Inc. - All Rights Reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//    http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\n#include <Eigen/Dense>\n#include <algorithm>\n#include <cmath>\n#include <iostream>\n#include \"Utils/random_utils.hpp\"\n#include <vector>\n#include \"Utils/json_utils.hpp\"\n#include \"abstract_hilbert.hpp\"\n\n#ifndef NETKET_BOSONS_HPP\n#define NETKET_BOSONS_HPP\n\nnamespace netket {\n\n/**\n  Hilbert space for integer or bosons.\n  The hilbert space is truncated to some maximum occupation number.\n*/\n\nclass Boson : public AbstractHilbert {\n  int nsites_;\n\n  std::vector<double> local_;\n\n  // total number of bosons\n  // if constraint is activated\n  int nbosons_;\n\n  bool constraintN_;\n\n  // maximum local occupation number\n  int nmax_;\n\n  int nstates_;\n\n public:\n  explicit Boson(const json &pars) {\n    if (!FieldExists(pars[\"Hilbert\"], \"Nsites\")) {\n      std::cerr << \"Nsites is not defined\" << std::endl;\n    }\n\n    nsites_ = pars[\"Hilbert\"][\"Nsites\"];\n\n    if (!FieldExists(pars[\"Hilbert\"], \"Nmax\")) {\n      std::cerr << \"Nmax is not defined\" << std::endl;\n    }\n\n    nmax_ = pars[\"Hilbert\"][\"Nmax\"];\n\n    Init();\n\n    if (FieldExists(pars[\"Hilbert\"], \"Nbosons\")) {\n      SetNbosons(pars[\"Hilbert\"][\"Nbosons\"]);\n    } else {\n      constraintN_ = false;\n    }\n  }\n\n  void Init() {\n    if (nsites_ <= 0) {\n      std::cerr << \"Invalid number of sites\" << std::endl;\n      std::abort();\n    }\n\n    if (nmax_ <= 0) {\n      std::cerr << \"Invalid maximum occupation number\" << std::endl;\n      std::abort();\n    }\n\n    nstates_ = nmax_ + 1;\n\n    local_.resize(nstates_);\n\n    for (int i = 0; i < nstates_; i++) {\n      local_[i] = i;\n    }\n  }\n\n  void SetNbosons(int nbosons) {\n    constraintN_ = true;\n    nbosons_ = nbosons;\n\n    if (nbosons_ > nsites_ * nmax_) {\n      std::cerr << \"Cannot set the desired number of bosons\" << std::endl;\n      std::abort();\n    }\n  }\n\n  bool IsDiscrete() const override { return true; }\n\n  int LocalSize() const override { return nstates_; }\n\n  int Size() const override { return nsites_; }\n\n  std::vector<double> LocalStates() const override { return local_; }\n\n  void RandomVals(Eigen::VectorXd &state,\n                  netket::default_random_engine &rgen) const override {\n    assert(state.size() == nsites_);\n\n    if (!constraintN_) {\n      std::uniform_int_distribution<int> distribution(0, nstates_ - 1);\n      // unconstrained random\n      for (int i = 0; i < state.size(); i++) {\n        state(i) = distribution(rgen);\n      }\n    } else {\n      state.setZero();\n\n      std::uniform_int_distribution<int> distribution(0, nsites_ - 1);\n      for (int i = 0; i < nbosons_; i++) {\n        int rsite = distribution(rgen);\n\n        while (state(rsite) >= nmax_) {\n          rsite = distribution(rgen);\n        }\n\n        state(rsite) += 1;\n      }\n    }\n  }\n\n  bool CheckConstraint(Eigen::VectorXd &v) const {\n    int tot = 0;\n    for (int i = 0; i < v.size(); i++) {\n      tot += int(v(i));\n    }\n\n    return tot == nbosons_;\n  }\n\n  void UpdateConf(Eigen::VectorXd &v, const std::vector<int> &tochange,\n                  const std::vector<double> &newconf) const override {\n    assert(v.size() == nsites_);\n\n    int i = 0;\n    for (auto sf : tochange) {\n      v(sf) = newconf[i];\n      i++;\n      assert(v(sf) <= nmax_);\n    }\n\n    if (constraintN_) {\n      assert(CheckConstraint(v));\n    }\n  }\n};\n\n}  // namespace netket\n#endif\n", "meta": {"hexsha": "04811c22e9b2ba1638aad3c0ec78d17fb763c9f8", "size": 3881, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "NetKet/Hilbert/bosons.hpp", "max_stars_repo_name": "artemborin/netket", "max_stars_repo_head_hexsha": "c7f26d52fdb66d2a8f9f94f2e2cfdc8b4ab41334", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "NetKet/Hilbert/bosons.hpp", "max_issues_repo_name": "artemborin/netket", "max_issues_repo_head_hexsha": "c7f26d52fdb66d2a8f9f94f2e2cfdc8b4ab41334", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "NetKet/Hilbert/bosons.hpp", "max_forks_repo_name": "artemborin/netket", "max_forks_repo_head_hexsha": "c7f26d52fdb66d2a8f9f94f2e2cfdc8b4ab41334", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.5212121212, "max_line_length": 75, "alphanum_fraction": 0.6132440093, "num_tokens": 1064, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.600188359260205, "lm_q2_score": 0.5156199157230157, "lm_q1q2_score": 0.3094690712196819}}
{"text": "#include \"transport.hpp\"\n\n#include <assert.h>\n#include <limits>\n#include <vector>\n\n#include <boost/intrusive/list.hpp>\n#include <boost/intrusive/slist.hpp>\n\n#include \"union-find.hpp\"\n\ntemplate <typename T>\nclass TransportGraph {\n    public:\n        TransportGraph(int sizeSupply, int sizeDemand)\n            : _sizeSupply(sizeSupply)\n            , _sizeDemand(sizeDemand)\n            , _nodes(sizeSupply+sizeDemand)\n            , _treeEdges(2*(sizeSupply+sizeDemand - 1))\n        { \n            for (int i = 0; i < _sizeSupply+_sizeDemand; ++i)\n                _nodes[i].id = i;\n        }\n        \n        typedef boost::intrusive::list_base_hook<\n            boost::intrusive::link_mode<boost::intrusive::normal_link>\n            > ListHook;\n        struct Edge : public ListHook { \n            int target;\n            int edgeIdx;\n            Edge* reverse;\n        };\n\n        typedef boost::intrusive::list<Edge, \n                boost::intrusive::base_hook<ListHook>> EdgeList;\n\n        typedef boost::intrusive::slist_member_hook<\n            boost::intrusive::link_mode<boost::intrusive::normal_link>\n            > StackHook;\n\n        struct Node {\n            int id = 0;\n            T potential = 0;\n            EdgeList outEdges;\n            typename EdgeList::iterator dfsOutEdge;\n            StackHook stackHook;\n            bool inDfsStack = false;\n        };\n        typedef boost::intrusive::slist<Node,\n                boost::intrusive::member_hook<Node, \n                                              StackHook, \n                                              &Node::stackHook>\n                > NodeStack;\n\n\n        void addTreeEdge(int supply, int demand) {\n            assert(_numTreeEdges+2 <= static_cast<int>(_treeEdges.size()));\n            Edge& e1 = _treeEdges[_numTreeEdges];\n            Edge& e2 = _treeEdges[_numTreeEdges+1];\n            _numTreeEdges += 2;\n\n            int edgeIdx = supply*_sizeDemand+demand;\n            e1.target = demand+_sizeSupply;\n            e1.edgeIdx = edgeIdx;\n            e1.reverse = &e2;\n            e2.target = supply;\n            e2.edgeIdx = edgeIdx;\n            e2.reverse = &e1;\n\n            _nodes[supply].outEdges.push_back(e1);\n            _nodes[demand+_sizeSupply].outEdges.push_back(e2);\n        }\n\n        void augment(int supply, int demand, T* flows) {\n            int edgeIdx = supply*_sizeDemand+demand;\n\n            for (auto& n : _nodes)\n                n.inDfsStack = false;\n\n            NodeStack stack;\n            {\n                Node& startNode = _nodes.at(supply);\n                stack.push_front(startNode);\n                startNode.dfsOutEdge = startNode.outEdges.begin();\n                startNode.inDfsStack = true;\n            }\n            while (!stack.empty() && stack.front().id != demand+_sizeSupply) {\n                auto& n = stack.front();\n                if (n.dfsOutEdge == n.outEdges.end()) {\n                    stack.pop_front();\n                    assert(!stack.empty());\n                    auto& nextN = stack.front();\n                    assert(nextN.dfsOutEdge != nextN.outEdges.end());\n                    assert(nextN.dfsOutEdge->target == n.id);\n                    nextN.dfsOutEdge++;\n                    continue;\n                } else {\n                    int target = n.dfsOutEdge->target;\n                    auto& nextN = _nodes.at(target);\n                    if (nextN.inDfsStack) {\n                        n.dfsOutEdge++;\n                        continue;\n                    } else {\n                        stack.push_front(nextN);\n                        nextN.dfsOutEdge = nextN.outEdges.begin();\n                        nextN.inDfsStack = true;\n                        continue;\n                    }\n                }\n            }\n            assert(!stack.empty());\n            assert(stack.front().id == demand+_sizeSupply);\n            assert((stack.size() % 2) == 0);\n            stack.pop_front();\n\n            T bottleneckFlow = std::numeric_limits<T>::max();\n            Edge* bottleneckEdge = nullptr;\n            bool parity = true;\n            for (auto& n : stack) {\n                if (parity) {\n                    auto& e = *n.dfsOutEdge;\n                    auto f = flows[e.edgeIdx];\n                    if (f < bottleneckFlow) {\n                        bottleneckFlow = f;\n                        bottleneckEdge = &e;\n                    }\n                }\n                parity = !parity;\n            }\n            assert(bottleneckFlow < std::numeric_limits<T>::max());\n            assert(bottleneckEdge != nullptr);\n\n            parity = true;\n            for (auto& n : stack) {\n                auto& e = *n.dfsOutEdge;\n                if (parity)\n                    flows[e.edgeIdx] -= bottleneckFlow;\n                else\n                    flows[e.edgeIdx] += bottleneckFlow;\n                parity = !parity;\n            }\n            flows[edgeIdx] += bottleneckFlow;\n\n            Edge& e1 = *bottleneckEdge;\n            Edge& e2 = *e1.reverse;\n            {\n                Node& n1 = _nodes[e2.target];\n                Node& n2 = _nodes[e1.target];\n                n1.outEdges.erase(n1.outEdges.iterator_to(e1));\n                n2.outEdges.erase(n2.outEdges.iterator_to(e2));\n            }\n            {\n                Node& n1 = _nodes[supply];\n                Node& n2 = _nodes[demand+_sizeSupply];\n                e1.target = demand+_sizeSupply;\n                e1.edgeIdx = edgeIdx;\n                e1.reverse = &e2;\n                e2.target = supply;\n                e2.edgeIdx = edgeIdx;\n                e2.reverse = &e1;\n                n1.outEdges.push_back(e1);\n                n2.outEdges.push_back(e2);\n            }\n        }\n\n        void updatePotentials(const T* costs) {\n            for (auto& n : _nodes) {\n                n.potential = 0;\n                n.inDfsStack = false;\n            }\n\n            NodeStack stack;\n            {\n                Node& startNode = _nodes.at(0);\n                stack.push_front(startNode);\n                startNode.dfsOutEdge = startNode.outEdges.begin();\n                startNode.inDfsStack = true;\n            }\n            while (!stack.empty()) {\n                auto& n = stack.front();\n                if (n.dfsOutEdge == n.outEdges.end()) {\n                    stack.pop_front();\n                    if(!stack.empty()) {\n                        auto& nextN = stack.front();\n                        assert(nextN.dfsOutEdge != nextN.outEdges.end());\n                        assert(nextN.dfsOutEdge->target == n.id);\n                        nextN.dfsOutEdge++;\n                    }\n                    continue;\n                } else {\n                    int target = n.dfsOutEdge->target;\n                    auto& nextN = _nodes.at(target);\n                    if (nextN.inDfsStack) {\n                        n.dfsOutEdge++;\n                        continue;\n                    } else {\n                        int edgeIdx = n.dfsOutEdge->edgeIdx;\n                        T c = costs[edgeIdx];\n                        nextN.potential = c - n.potential;\n\n                        stack.push_front(nextN);\n                        nextN.dfsOutEdge = nextN.outEdges.begin();\n                        nextN.inDfsStack = true;\n                        continue;\n                    }\n                }\n            }\n        }\n\n        std::tuple<int, int, T> findPivot(const T* costs) {\n            std::tuple<int, int, T> minEdge \n                = {0, 0, std::numeric_limits<T>::max()};\n            for (int i = 0; i < _sizeSupply; ++i) {\n                for (int j = 0; j < _sizeDemand; ++j) {\n                    int edgeIdx = i*_sizeDemand+j;\n                    T resCost = costs[edgeIdx] \n                        - _nodes[i].potential \n                        - _nodes[j+_sizeSupply].potential;\n                    if (resCost < std::get<2>(minEdge))\n                        minEdge = {i, j, resCost};\n                }\n            }\n            return minEdge;\n        }\n\n\n        int _sizeSupply;\n        int _sizeDemand;\n        int _numTreeEdges = 0;\n        std::vector<Node> _nodes;\n        std::vector<Edge> _treeEdges;\n};\n\ntemplate <typename T>\ndouble solveTransport(int sizeSupply, int sizeDemand, const T* costs, \n        const T* supply, const T* demand, T* flow) {\n    T sumSupply = 0;\n    for (int i = 0; i < sizeSupply; ++i) \n        sumSupply += supply[i];\n    T sumDemand = 0;\n    for (int j = 0; j < sizeDemand; ++j)\n        sumDemand += demand[j];\n    assert(fabs(sumSupply - sumDemand) < 1e-5);\n\n    for (int k = 0; k < sizeSupply*sizeDemand; ++k)\n        flow[k] = 0;\n\n    std::vector<T> resSupply(supply, supply+sizeSupply);\n    std::vector<T> resDemand(demand, demand+sizeDemand);\n\n    TransportGraph<T> graph{sizeSupply, sizeDemand};\n\n\n    int numNodes = sizeSupply+sizeDemand;\n    auto uf = UnionFind{numNodes};\n    for (int k = 0; k < numNodes-1; ++k) {\n        T minCost = std::numeric_limits<T>::max();\n        int minI = 0;\n        int minJ = 0;\n        for (int i = 0; i < sizeSupply; ++i) {\n            if (resSupply.at(i) <= 0)\n                continue;\n            auto comp_i = uf.Find(i);\n            for (int j = 0; j < sizeDemand; ++j) {\n                if (resDemand.at(j) <= 0)\n                    continue;\n                auto comp_j = uf.Find(j+sizeSupply);\n                if (comp_i == comp_j)\n                    continue;\n                if (costs[i*sizeDemand+j] < minCost) {\n                    minCost = costs[i*sizeDemand+j];\n                    minI = i;\n                    minJ = j;\n                }\n            }\n        }\n        if (minCost == std::numeric_limits<T>::max())\n            break;\n        assert(uf.Find(minI) != uf.Find(minJ+sizeSupply));\n        T f = std::min(resSupply.at(minI), resDemand.at(minJ));\n        resSupply.at(minI) -= f;\n        resDemand.at(minJ) -= f;\n        flow[minI*sizeDemand+minJ] += f;\n        graph.addTreeEdge(minI, minJ);\n        uf.Merge(minI, minJ+sizeSupply);\n    }\n    // Add any unconnected components to connect to 0 \n    for (int i = 0; i < sizeSupply; ++i) {\n        if (uf.Find(i) != uf.Find(0+sizeSupply)) {\n            graph.addTreeEdge(i, 0);\n            uf.Merge(i, 0+sizeSupply);\n        }\n    }\n    for (int j = 0; j < sizeDemand; ++j) {\n        if (uf.Find(0) != uf.Find(j+sizeSupply)) {\n            graph.addTreeEdge(0, j);\n            uf.Merge(0, j+sizeSupply);\n        }\n    }\n\n#ifndef NDEBUG\n    for (auto s : resSupply) {\n        assert(fabs(s) < 1e-5);\n    }\n    for (auto d : resDemand)\n        assert(fabs(d) < 1e-5);\n#endif\n\n    while (true) {\n        graph.updatePotentials(costs);\n        std::tuple<int, int, T> minEdge = graph.findPivot(costs);\n        if (std::get<2>(minEdge) < 0)\n            graph.augment(std::get<0>(minEdge), std::get<1>(minEdge), flow);\n        else\n            break;\n    }\n\n    double cost = 0;\n    for (int i = 0; i < sizeSupply; ++i) {\n        for (int j = 0; j < sizeDemand; ++j) {\n            int idx = i*sizeDemand + j;\n            cost += flow[idx] * costs[idx];\n        }\n    }\n    return cost;\n}\n\n\n#define INSTANTIATE_TRANSPORT(T) \\\n    template double solveTransport<T>(int sizeSupply, int sizeDemand, \\\n            const T* costs, const T* supply, const T* demand, T* flow);\nINSTANTIATE_TRANSPORT(double)\nINSTANTIATE_TRANSPORT(int32_t)\nINSTANTIATE_TRANSPORT(int64_t)\n#undef INSTANTIATE_TRANSPORT\n", "meta": {"hexsha": "f70aff76cc0988ca9b24e629f819d41755656555", "size": 11392, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/transport.cpp", "max_stars_repo_name": "letterx/deconvolution", "max_stars_repo_head_hexsha": "5d4df9e842c121bd65537b7f8f4fb0a628b31242", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2016-11-27T05:38:10.000Z", "max_stars_repo_stars_event_max_datetime": "2016-11-27T05:38:10.000Z", "max_issues_repo_path": "src/transport.cpp", "max_issues_repo_name": "letterx/deconvolution", "max_issues_repo_head_hexsha": "5d4df9e842c121bd65537b7f8f4fb0a628b31242", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/transport.cpp", "max_forks_repo_name": "letterx/deconvolution", "max_forks_repo_head_hexsha": "5d4df9e842c121bd65537b7f8f4fb0a628b31242", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-09-30T01:58:51.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-30T01:58:51.000Z", "avg_line_length": 33.9047619048, "max_line_length": 78, "alphanum_fraction": 0.4673455056, "num_tokens": 2672, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5660185351961015, "lm_q2_score": 0.5467381519846138, "lm_q1q2_score": 0.3094639279221546}}
{"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: Stephan Aiche $\n// $Authors: Andreas Bertsch $\n// --------------------------------------------------------------------------\n//\n\n#include <sstream>\n#include <iostream>\n#include <cmath>\n#include <boost/math/special_functions/gamma.hpp>\n#include <boost/math/special_functions/digamma.hpp>\n\n#include <unsupported/Eigen/NonLinearOptimization>\n\n#include <OpenMS/MATH/STATISTICS/GammaDistributionFitter.h>\n\n// #define GAMMA_DISTRIBUTION_FITTER_VERBOSE\n// #undef  GAMMA_DISTRIBUTION_FITTER_VERBOSE\n\nnamespace OpenMS\n{\n  namespace Math\n  {\n    GammaDistributionFitter::GammaDistributionFitter() :\n      init_param_(1.0, 5.0)\n    {\n    }\n\n    GammaDistributionFitter::~GammaDistributionFitter()\n    {\n    }\n\n    void GammaDistributionFitter::setInitialParameters(const GammaDistributionFitResult& param)\n    {\n      init_param_ = param;\n    }\n\n    struct GammaFunctor\n    {\n      int inputs() const { return m_inputs; }\n      int values() const { return m_values; }\n\n      GammaFunctor(unsigned dimensions, const std::vector<DPosition<2> >* data) :\n        m_inputs(dimensions), m_values(data->size()), m_data(data) {}\n\n      int operator()(const Eigen::VectorXd& x, Eigen::VectorXd& fvec)\n      {\n\n        double b = x(0);\n        double p = x(1);\n\n        UInt i = 0;\n\n        // gamma distribution is only defined for positive parameter values\n        if (b > 0.0 && p > 0.0)\n        {\n          for (std::vector<DPosition<2> >::const_iterator it = m_data->begin(); it != m_data->end(); ++it, ++i)\n          {\n            double the_x = it->getX();\n            fvec(i) =  std::pow(b, p) / boost::math::tgamma(p) * std::pow(the_x, p - 1) * std::exp(-b * the_x) - it->getY();\n          }\n        }\n        else\n        {\n          for (std::vector<DPosition<2> >::const_iterator it = m_data->begin(); it != m_data->end(); ++it, ++i)\n          {\n            fvec(i) = -it->getY();\n          }\n        }\n\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\n        double b = x(0);\n        double p = x(1);\n\n        UInt i = 0;\n        // gamma distribution is only defined for positive parameter values\n        if (b > 0.0 && p > 0.0)\n        {\n          for (std::vector<DPosition<2> >::const_iterator it = m_data->begin(); it != m_data->end(); ++it, ++i)\n          {\n            double the_x = it->getX();\n\n            // partial deviation regarding b\n            double part_dev_b = std::pow(the_x, p - 1) * std::exp(-the_x * b) / boost::math::tgamma(p) * (p * std::pow(b, p - 1) - the_x * std::pow(b, p));\n            J(i, 0) = part_dev_b;\n\n            // partial deviation regarding p\n            double factor = std::exp(-b * the_x) * std::pow(the_x, p - 1) * std::pow(b, p) / std::pow(boost::math::tgamma(p), 2);\n            double argument = (std::log(b) + std::log(the_x)) * boost::math::tgamma(p) - boost::math::tgamma(p) * boost::math::digamma(p);\n            double part_dev_p = factor * argument;\n            J(i, 1) = part_dev_p;\n          }\n        }\n        else\n        {\n          for (std::vector<DPosition<2> >::const_iterator it = m_data->begin(); it != m_data->end(); ++it, ++i)\n          {\n            J(i, 0) = 0.0;\n            J(i, 1) = 0.0;\n          }\n        }\n        return 0;\n      }\n\n      const int m_inputs, m_values;\n      const std::vector<DPosition<2> >* m_data;\n    };\n\n    GammaDistributionFitter::GammaDistributionFitResult GammaDistributionFitter::fit(const std::vector<DPosition<2> >& input)\n    {\n      Eigen::VectorXd x_init(2);\n      x_init << init_param_.b, init_param_.p;\n      GammaFunctor functor(2, &input);\n      Eigen::LevenbergMarquardt<GammaFunctor> lmSolver(functor);\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__, __PRETTY_FUNCTION__, \"UnableToFit-GammaDistributionFitter\", \"Could not fit the gamma distribution to the data\");\n      }\n\n#ifdef GAMMA_DISTRIBUTION_FITTER_VERBOSE\n      std::stringstream formula;\n      formula << \"f(x)=\" << \"(\" << x_init(0) << \" ** \" << x_init(1) << \") / gamma(\" << x_init(1) << \") * x ** (\" << x_init(1) << \" - 1) * exp(- \" << x_init(0) << \" * x)\";\n      std::cout << formula.str() << std::endl;\n#endif\n\n      return GammaDistributionFitResult(x_init(0), x_init(1));\n    }\n\n  } //namespace Math\n} // namespace OpenMS\n", "meta": {"hexsha": "3ecc43555b9b8b31d99749329e414086ff18a78a", "size": 6673, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/openms/source/MATH/STATISTICS/GammaDistributionFitter.cpp", "max_stars_repo_name": "mrurik/OpenMS", "max_stars_repo_head_hexsha": "3bf48247423dc28a7df7b12b72fbc7751965c321", "max_stars_repo_licenses": ["Zlib", "Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/openms/source/MATH/STATISTICS/GammaDistributionFitter.cpp", "max_issues_repo_name": "mrurik/OpenMS", "max_issues_repo_head_hexsha": "3bf48247423dc28a7df7b12b72fbc7751965c321", "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/MATH/STATISTICS/GammaDistributionFitter.cpp", "max_forks_repo_name": "mrurik/OpenMS", "max_forks_repo_head_hexsha": "3bf48247423dc28a7df7b12b72fbc7751965c321", "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": 38.7965116279, "max_line_length": 170, "alphanum_fraction": 0.592836805, "num_tokens": 1622, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6187804196836383, "lm_q2_score": 0.5, "lm_q1q2_score": 0.30939020984181914}}
{"text": "#ifndef STAN_MATH_PRIM_SCAL_PROB_NEG_BINOMIAL_LPMF_HPP\n#define STAN_MATH_PRIM_SCAL_PROB_NEG_BINOMIAL_LPMF_HPP\n\n#include <stan/math/prim/scal/meta/is_constant_struct.hpp>\n#include <stan/math/prim/scal/meta/operands_and_partials.hpp>\n#include <stan/math/prim/scal/err/check_consistent_sizes.hpp>\n#include <stan/math/prim/scal/err/check_nonnegative.hpp>\n#include <stan/math/prim/scal/err/check_positive_finite.hpp>\n#include <stan/math/prim/scal/fun/size_zero.hpp>\n#include <stan/math/prim/scal/fun/constants.hpp>\n#include <stan/math/prim/scal/fun/value_of.hpp>\n#include <stan/math/prim/scal/fun/binomial_coefficient_log.hpp>\n#include <stan/math/prim/scal/fun/multiply_log.hpp>\n#include <stan/math/prim/scal/fun/digamma.hpp>\n#include <stan/math/prim/scal/fun/lgamma.hpp>\n#include <stan/math/prim/scal/fun/lbeta.hpp>\n#include <stan/math/prim/scal/meta/length.hpp>\n#include <stan/math/prim/scal/meta/scalar_seq_view.hpp>\n#include <stan/math/prim/scal/meta/VectorBuilder.hpp>\n#include <stan/math/prim/scal/meta/partials_return_type.hpp>\n#include <stan/math/prim/scal/meta/return_type.hpp>\n#include <stan/math/prim/scal/meta/include_summand.hpp>\n#include <stan/math/prim/scal/fun/grad_reg_inc_beta.hpp>\n#include <stan/math/prim/scal/fun/inc_beta.hpp>\n#include <stan/math/prim/scal/meta/max_size.hpp>\n#include <boost/math/special_functions/digamma.hpp>\n#include <boost/random/negative_binomial_distribution.hpp>\n#include <boost/random/variate_generator.hpp>\n#include <cmath>\n\nnamespace stan {\nnamespace math {\n\n// NegBinomial(n|alpha, beta)  [alpha > 0;  beta > 0;  n >= 0]\ntemplate <bool propto, typename T_n, typename T_shape, typename T_inv_scale>\ntypename return_type<T_shape, T_inv_scale>::type neg_binomial_lpmf(\n    const T_n& n, const T_shape& alpha, const T_inv_scale& beta) {\n  typedef typename stan::partials_return_type<T_n, T_shape, T_inv_scale>::type\n      T_partials_return;\n\n  static const char* function = \"neg_binomial_lpmf\";\n\n  if (size_zero(n, alpha, beta))\n    return 0.0;\n\n  T_partials_return logp(0.0);\n  check_nonnegative(function, \"Failures variable\", n);\n  check_positive_finite(function, \"Shape parameter\", alpha);\n  check_positive_finite(function, \"Inverse scale parameter\", beta);\n  check_consistent_sizes(function, \"Failures variable\", n, \"Shape parameter\",\n                         alpha, \"Inverse scale parameter\", beta);\n\n  if (!include_summand<propto, T_shape, T_inv_scale>::value)\n    return 0.0;\n\n  using std::log;\n  using std::log;\n\n  scalar_seq_view<T_n> n_vec(n);\n  scalar_seq_view<T_shape> alpha_vec(alpha);\n  scalar_seq_view<T_inv_scale> beta_vec(beta);\n  size_t size = max_size(n, alpha, beta);\n\n  operands_and_partials<T_shape, T_inv_scale> ops_partials(alpha, beta);\n\n  size_t len_ab = max_size(alpha, beta);\n  VectorBuilder<true, T_partials_return, T_shape, T_inv_scale> lambda(len_ab);\n  for (size_t i = 0; i < len_ab; ++i)\n    lambda[i] = value_of(alpha_vec[i]) / value_of(beta_vec[i]);\n\n  VectorBuilder<true, T_partials_return, T_inv_scale> log1p_beta(length(beta));\n  for (size_t i = 0; i < length(beta); ++i)\n    log1p_beta[i] = log1p(value_of(beta_vec[i]));\n\n  VectorBuilder<true, T_partials_return, T_inv_scale> log_beta_m_log1p_beta(\n      length(beta));\n  for (size_t i = 0; i < length(beta); ++i)\n    log_beta_m_log1p_beta[i] = log(value_of(beta_vec[i])) - log1p_beta[i];\n\n  VectorBuilder<true, T_partials_return, T_inv_scale, T_shape>\n      alpha_times_log_beta_over_1p_beta(len_ab);\n  for (size_t i = 0; i < len_ab; ++i)\n    alpha_times_log_beta_over_1p_beta[i]\n        = value_of(alpha_vec[i])\n          * log(value_of(beta_vec[i]) / (1.0 + value_of(beta_vec[i])));\n\n  VectorBuilder<!is_constant_struct<T_shape>::value, T_partials_return, T_shape>\n      digamma_alpha(length(alpha));\n  if (!is_constant_struct<T_shape>::value) {\n    for (size_t i = 0; i < length(alpha); ++i)\n      digamma_alpha[i] = digamma(value_of(alpha_vec[i]));\n  }\n\n  VectorBuilder<!is_constant_struct<T_shape>::value, T_partials_return,\n                T_inv_scale>\n      log_beta(length(beta));\n  if (!is_constant_struct<T_shape>::value) {\n    for (size_t i = 0; i < length(beta); ++i)\n      log_beta[i] = log(value_of(beta_vec[i]));\n  }\n\n  VectorBuilder<!is_constant_struct<T_inv_scale>::value, T_partials_return,\n                T_shape, T_inv_scale>\n      lambda_m_alpha_over_1p_beta(len_ab);\n  if (!is_constant_struct<T_inv_scale>::value) {\n    for (size_t i = 0; i < len_ab; ++i)\n      lambda_m_alpha_over_1p_beta[i]\n          = lambda[i]\n            - (value_of(alpha_vec[i]) / (1.0 + value_of(beta_vec[i])));\n  }\n\n  for (size_t i = 0; i < size; i++) {\n    if (alpha_vec[i] > 1e10) {  // reduces numerically to Poisson\n      if (include_summand<propto>::value)\n        logp -= lgamma(n_vec[i] + 1.0);\n      if (include_summand<propto, T_shape, T_inv_scale>::value)\n        logp += multiply_log(n_vec[i], lambda[i]) - lambda[i];\n\n      if (!is_constant_struct<T_shape>::value)\n        ops_partials.edge1_.partials_[i]\n            += n_vec[i] / value_of(alpha_vec[i]) - 1.0 / value_of(beta_vec[i]);\n      if (!is_constant_struct<T_inv_scale>::value)\n        ops_partials.edge2_.partials_[i]\n            += (lambda[i] - n_vec[i]) / value_of(beta_vec[i]);\n    } else {  // standard density definition\n      if (include_summand<propto, T_shape>::value)\n        if (n_vec[i] != 0)\n          logp += binomial_coefficient_log(\n              n_vec[i] + value_of(alpha_vec[i]) - 1.0, n_vec[i]);\n      if (include_summand<propto, T_shape, T_inv_scale>::value)\n        logp += alpha_times_log_beta_over_1p_beta[i] - n_vec[i] * log1p_beta[i];\n\n      if (!is_constant_struct<T_shape>::value)\n        ops_partials.edge1_.partials_[i]\n            += digamma(value_of(alpha_vec[i]) + n_vec[i]) - digamma_alpha[i]\n               + log_beta_m_log1p_beta[i];\n      if (!is_constant_struct<T_inv_scale>::value)\n        ops_partials.edge2_.partials_[i]\n            += lambda_m_alpha_over_1p_beta[i]\n               - n_vec[i] / (value_of(beta_vec[i]) + 1.0);\n    }\n  }\n  return ops_partials.build(logp);\n}\n\ntemplate <typename T_n, typename T_shape, typename T_inv_scale>\ninline typename return_type<T_shape, T_inv_scale>::type neg_binomial_lpmf(\n    const T_n& n, const T_shape& alpha, const T_inv_scale& beta) {\n  return neg_binomial_lpmf<false>(n, alpha, beta);\n}\n\n}  // namespace math\n}  // namespace stan\n#endif\n", "meta": {"hexsha": "0f486094e4ab03b08a039f31ac0c68349e7e4a86", "size": 6323, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "stan/math/prim/scal/prob/neg_binomial_lpmf.hpp", "max_stars_repo_name": "jrmie/math", "max_stars_repo_head_hexsha": "2850ec262181075a5843968e805dc9ad1654e069", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "stan/math/prim/scal/prob/neg_binomial_lpmf.hpp", "max_issues_repo_name": "jrmie/math", "max_issues_repo_head_hexsha": "2850ec262181075a5843968e805dc9ad1654e069", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "stan/math/prim/scal/prob/neg_binomial_lpmf.hpp", "max_forks_repo_name": "jrmie/math", "max_forks_repo_head_hexsha": "2850ec262181075a5843968e805dc9ad1654e069", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.7935483871, "max_line_length": 80, "alphanum_fraction": 0.7014075597, "num_tokens": 1792, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6825737344123242, "lm_q2_score": 0.4532618480153861, "lm_q1q2_score": 0.3093846322664934}}
{"text": "#include <iostream>\n#include \"specex_linalg.h\"\n#include <boost/archive/xml_oarchive.hpp>\n#include <boost/archive/text_oarchive.hpp>\n#include <boost/archive/basic_text_oarchive.hpp>\n#include <time.h>\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/triangular.hpp> \n#include <boost/random.hpp>\n\n\n\nusing namespace std;\n\nint main() {\n  \n  harp::vector_double x(4);\n  x(1)=1;\n  x[2]=2;\n\n  if(0) {\n  boost::archive::xml_oarchive xml_oa ( cout );\n  xml_oa << BOOST_SERIALIZATION_NVP(x);\n  \n  boost::archive::text_oarchive text_oa ( cout );\n  text_oa << BOOST_SERIALIZATION_NVP(x);\n  \n  boost::archive::text_oarchive basic_text_oa ( cout );\n  basic_text_oa << BOOST_SERIALIZATION_NVP(x);\n  }\n\n\n  {\n\n\n    //ublas::mapped_vector<double> sv (4000);\n    //ublas::compressed_vector<double> sv (4000);\n     cout << \"==================\" << endl;\n  cout << \" SPARSE VECTORS   \" << endl;\n  cout << \"==================\" << endl;\n  \n  int n = 8000;\n  //ublas::coordinate_vector<double> sv (n);\n  //ublas::mapped_vector<double> sv (n);\n  ublas::compressed_vector<double> sv (n);\n  //ublas::vector<double> sv (n);\n  harp::vector_double v (n);\n  harp::vector_double v2 (n);\n  double w = 0.2;\n  v.clear();\n  v2.clear();\n  sv.clear();\n  \n  for (unsigned i = 0; i < sv.size (); i ++) {\n    v2(i)=i;\n  }\n  for (unsigned i = 0; i < sv.size (); i += 10) {\n    sv(i) = i;\n    v(i)=i;\n  }\n  \n  {\n    harp::matrix_double a(10,10);\n    a.clear();\n    harp::vector_double h = ublas::project(v2,ublas::range(0,10));\n    cout << h << endl;\n    specex::syr(1,ublas::project(h,ublas::range(0,5)),a);\n    cout << a << endl;\n    a.clear();\n    specex::syr(1,ublas::project(h,ublas::range(5,10)),a);\n    cout << a << endl;\n    \n    exit(12);\n  }\t  \n\n\n    // see http://www.boost.org/doc/libs/1_38_0/libs/numeric/ublas/doc/blas.htm\n  \n  harp::matrix_double m(n,n);\n  \n  int N=500;\n  {\n    m.clear();\n    clock_t tstart = clock();\n    for(int i=0;i<N;i++)\n      specex::syr(w,v,m);\n    clock_t tstop = clock();\n    cout << \"#1 n clocks = \" << tstop-tstart << \" \" << float(tstop-tstart)/float(CLOCKS_PER_SEC) << endl;\n  }\n  \n  //ublas::coordinate_matrix<double> sm (n,n);\n  ublas::compressed_matrix<double> sm (n,n);\n  //ublas::triangular_matrix<double,  ublas::lower> sm (n,n); // crashed\n  //ublas::mapped_matrix<double> sm (n,n);\n  //ublas::matrix<double> sm (n,n);\n  {\n    \n    clock_t  tstart = clock();\n    //ublas::outer_prod(sv,sv);\n    clock_t tstop = clock();\n    cout << \"#1 n clocks = \" << tstop-tstart << \" \" << float(tstop-tstart)/float(CLOCKS_PER_SEC) << endl;\n  }\n  {\n    \n    clock_t  tstart = clock();\n    //ublas::outer_prod(sv,sv);\n    \n    //ublas::triangular_adaptor<ublas::compressed_matrix<double>,ublas::lower> tsm(sm);\n    for(int i=0;i<N;i++)\n      ublas::noalias(sm) += w*ublas::outer_prod(sv,sv);\n    //ublas::noalias(m) += ublas::sparse_prod(sv,sv);\n      \n    //ublas::blas_3::srk(m,1,1,v);\n    \n    clock_t tstop = clock();\n    cout << \"#2 n clocks = \" << tstop-tstart << \" \" << float(tstop-tstart)/float(CLOCKS_PER_SEC) << endl;\n  }\n  harp::matrix_double dm = m - sm;\n  for(unsigned i = 0; i < 100;i++) {\n    cout << \"m dm (\"<< i << \") =\" << m(i,i) << \" \" << dm(i,i) << endl;\n  }\n  \n\n  if(0) {\n    harp::matrix_double m(n,n); m.clear();\n    clock_t tstart = clock();\n    for(int i=0;i<N;i++)\n      specex::syr(w,v2,m);\n    clock_t tstop = clock();\n    cout << \"#3 n clocks = \" << tstop-tstart << \" \" << float(tstop-tstart)/float(CLOCKS_PER_SEC) << endl;\n  }\n  \n    return 0;\n\n}\n  cout << \"==================\" << endl;\n  cout << \" LINEAR SYSTEMS   \" << endl;\n  cout << \"==================\" << endl;\n  \n  typedef boost::ecuyer1988 base_generator_type;\n  base_generator_type generator(42u);\n  boost::uniform_real < double > dist ( 0.0, 1.0 );\n  boost::variate_generator < base_generator_type&, boost::uniform_real < double > > uni ( generator, dist );\n\n  int ndata = 12;\n  int nparams = 10;\n  vector<harp::vector_double> h;\n  for( int i=0; i<ndata; i++) {\n    harp::vector_double hi(nparams);\n    for(int p=0; p<nparams ;p++) {\n      hi(p)=uni(); // stupid number\n    }\n    //cout << \"data \" << i << \" h=\" << hi << endl;\n    h.push_back(hi);\n  }\n  \n  harp::vector_double true_params(nparams);\n  for(int p=0; p<nparams ;p++) {\n    true_params(p)=p;\n  }\n  \n  harp::matrix_double A(nparams,nparams);\n  harp::vector_double B(nparams);\n  A.clear();\n  B.clear();\n  \n  harp::vector_double data(ndata);\n  for( int i=0; i<ndata; i++) {\n    data[i]=specex::dot(true_params,h[i]);\n    double w=uni()+1; // stupid number\n    specex::syr(w,h[i],A);\n    specex::axpy(w*data(i),h[i],B);\n  }\n  \n  //cout << \"A=\" << A << endl;\n  //cout << \"B=\" << B << endl;\n  \n\n  int status = specex::cholesky_solve(A,B);\n  cout << \"cholesky_solve status = \" << status << endl;\n  harp::vector_double diff = B-true_params;\n  cout << \"parameter residuals = \" << diff << endl;\n  harp::vector_double res(ndata);\n  for( int i=0; i<ndata; i++) {\n    res(i) = data(i)-specex::dot(B,h[i]);\n  }\n  cout << \"data residuals = \" << res << endl;\n  \n  \n\n  cout << \"==================\" << endl;\n  cout << \" PROJECTIONS   \" << endl;\n  cout << \"==================\" << endl;\n  \n  harp::vector_double one(16);\n  harp::vector_double zero(16);\n  zero.clear();\n  \n  for(size_t i=0;i<one.size();i++) one[i]=i+1;\n  for(int j=0;j<4;j++)\n    ublas::project(zero,ublas::range(4*j,4*(j+1))) += pow(10,j)* ublas::project(one,ublas::range(4*j,4*(j+1)));\n  cout << zero << endl;\n\n  return 0;\n  harp::vector_double y(12);\n  for(int i=7;i<7+4;i++) y[i]=1;\n\n  try {\n    //cout << specex::dot(x,y) << endl; // this throws an exception\n    \n    \n    ublas::range r(0,1);\n    cout << specex::dot(x,ublas::project(y,ublas::range(0,x.size()))) << endl;\n    cout << specex::dot(x,ublas::project(y,ublas::range(7,7+x.size()))) << endl;\n\n\n    y.clear();\n    size_t x_size = x.size();\n    for(size_t k=0;(k+1)*x_size<=y.size();k++) {\n      ublas::project(y,ublas::range(k*x_size,(k+1)*x_size)) = (k+1)*x;\n    }\n\n    cout << y << endl;\n    cout << ublas::inner_prod (y,y) << endl;\n    cout << specex::dot(y,y) << endl;\n    cout << ublas::outer_prod (y,y) << endl;\n\n\n\n    cout << \"==================\" << endl;\n    cout << \" SPARSE VECTORS   \" << endl;\n    cout << \"==================\" << endl;\n\n    //ublas::mapped_vector<double> sv (8000);\n    ublas::compressed_vector<double> sv (8000);\n    //ublas::coordinate_vector<double> sv (8000);\n    harp::vector_double v (8000);\n    \n   \n\n    if(0) {\n      \n      cout << sv << endl;\n      // for coordinate vector\n      //for(ublas::coordinate_vector<double>::iterator it=sv.begin();it!=sv.end();++it) {\n      //cout << *it << \" \";\n      //}\n      //cout << endl;\n    }\n    \n    double res1=0;\n    {\n      clock_t tstart = clock();\n      ublas::vector<double> v2(v.size());\n      ublas::matrix<double> m = ublas::outer_prod(v,v); boost::numeric::bindings::blas::gemv(1,m,v,0,v2);\n      //boost::numeric::bindings::blas::gemv(1,(ublas::matrix<double>&)ublas::outer_prod(v,v),v,0,v2);\n      //cout << v2 << endl;\n      clock_t tstop = clock();\n      res1=ublas::inner_prod(v,v2);\n      cout << res1 << endl;\n      cout << \"n clocks = \" << tstop-tstart << \" \" << float(tstop-tstart)/float(CLOCKS_PER_SEC) << endl;\n    }\n    if(1){ // ok \n      clock_t tstart = clock();\n      ublas::vector<double> v2(sv.size());\n      ublas::matrix<double> m = ublas::outer_prod(sv,sv); boost::numeric::bindings::blas::gemv(1,m,v,0,v2);\n      double res2 = ublas::inner_prod(sv,v2);\n      clock_t tstop = clock();\n      cout << res2 << \" \" << res2/res1-1 << endl;\n      cout << \"n clocks = \" << tstop-tstart << \" \" << float(tstop-tstart)/float(CLOCKS_PER_SEC) << endl;\n    }\n    if(1){ // ok \n      clock_t tstart = clock();\n      double res2 = ublas::inner_prod(sv,ublas::prod(ublas::outer_prod(sv,sv),sv));\n      clock_t tstop = clock();\n      cout << res2 << \" \" << res2/res1-1 << endl;\n      cout << \"n clocks = \" << tstop-tstart << \" \" << float(tstop-tstart)/float(CLOCKS_PER_SEC) << endl;\n    }\n    \n    // same with \"pre-existing\" matrix\n    { \n      ublas::matrix<double, ublas::column_major> m(v.size(),v.size());\n      clock_t tstart = clock();\n      //m += ublas::outer_prod(sv,sv); // terribly slow\n      // ublas::add(m,ublas::outer_prod(sv,sv)); // doesn't compile \n      boost::numeric::bindings::blas::syr(1.,v,boost::numeric::bindings::lower(m)); // compiles, and fast, but fills only part of the matrix !!\n      //boost::numeric::bindings::blas::syr(1.,sv,boost::numeric::bindings::lower(m)); // doesn't compile\n      \n      //specex::syr(1.,v,m);\n      double res2 = ublas::inner_prod(sv,ublas::prod(m,sv));\n      clock_t tstop = clock();\n      cout << res2 << \" \" << res2/res1-1 << endl;\n      cout << \"n clocks = \" << tstop-tstart << \" \" << float(tstop-tstart)/float(CLOCKS_PER_SEC) << endl;\n    }\n\n\n  }catch(harp::exception e) {\n    cout << \"ohoh \" << e.what() << endl;\n    return EXIT_FAILURE;\n  }\n  return EXIT_SUCCESS;\n}\n", "meta": {"hexsha": "f4f80523490ea253fe561c3a80652562982914fe", "size": 8904, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/tests/specex_test_boost.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/tests/specex_test_boost.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/tests/specex_test_boost.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": 29.3861386139, "max_line_length": 143, "alphanum_fraction": 0.5604222821, "num_tokens": 2865, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5698526660244837, "lm_q2_score": 0.5428632831725052, "lm_q1q2_score": 0.30935208920265633}}
{"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 <bitset>\n#include <cmath>\n#include <algorithm>\n#include <numeric>\n#include <cassert>\n\n#include <boost/mpl/arithmetic.hpp>\n#include <boost/static_assert.hpp>\n#include <boost/mpl/plus.hpp>\n#include <boost/limits.hpp>\n\n#define MAX_XY_ORDER 64\n\nnamespace mpl = boost::mpl;\nnamespace boost { namespace mpl {\n  template <std::size_t N, std::size_t Power>\n  struct pow\n  {\n    static const std::size_t value = N * pow<N, Power - 1>::value;\n  };\n\n  template <std::size_t N>\n  struct pow<N, 0>\n  {\n    static const std::size_t value = 1;\n  };\n\n} }\n\n// Computes the higher-order transfer entropy matrix for all pairs.\n// x and y orders must be known at compile time.\ntemplate <typename TimeSeriesCollection, typename ResultMatrix,\n         std::size_t x_order, std::size_t y_order>\nvoid transent_ho\n(const TimeSeriesCollection& all_series,\n const typename TimeSeriesCollection::value_type::value_type y_delay,\n const typename TimeSeriesCollection::value_type::value_type duration,\n ResultMatrix& te_result,\n std::size_t row_start = 0, std::size_t rows = 0,\n std::size_t col_start = 0, std::size_t cols = 0) {\n\n  // Typedefs\n  typedef typename TimeSeriesCollection::value_type TimeSeries;\n  typedef typename TimeSeries::value_type TimeType;\n  typedef typename TimeSeries::const_iterator TimeSeriesIter;\n\n  typedef std::pair<TimeSeriesIter, TimeType> IterShiftPair;\n  typedef std::pair<TimeType, std::size_t> TimeIndexPair;\n\n  // Constants\n  const std::size_t num_series = 1 + y_order + x_order,\n                    num_counts = mpl::pow<2, num_series>::value,\n                    num_x = mpl::pow<2, mpl::plus<mpl::int_<x_order>, mpl::int_<1> >::value>::value,\n                    num_y = mpl::pow<2, y_order>::value;\n\n  BOOST_STATIC_ASSERT(x_order > 0);\n  BOOST_STATIC_ASSERT(y_order > 0);\n  assert(y_delay > 0);\n  BOOST_STATIC_ASSERT(num_series <= MAX_XY_ORDER);\n\n  if (rows == 0) {\n    rows = all_series.size();\n  }\n\n  if (cols == 0) {\n    cols = all_series.size();\n  }\n\n  // Locals\n  std::vector<TimeType> counts(num_counts);\n  std::bitset<MAX_XY_ORDER> code;\n  std::size_t idx = 0;\n  double te_final, prob_2, prob_3;\n\n  IterShiftPair ord_iter[num_series];\n  TimeType ord_times[num_series];\n  TimeSeriesIter ord_end[num_series];\n\n  const std::size_t window = std::max(y_order + y_delay, x_order + 1);\n  TimeType cur_time, next_time, end_time = duration - window + 1, shift;\n\n  // Calculate TE\n  for (std::size_t i = row_start; i < (rows + row_start); ++i) {\n    for (std::size_t j = col_start; j < (cols + col_start); ++j) {\n\n      // NOTE: Time series are assumed to be 1-based, so everything is shifted by 1 too.\n      // Order is x^(k+1), y^(l)\n      idx = 0;\n\n      // x^(k+1)\n      for (std::size_t k = 0; k < (x_order + 1); ++k) {\n        shift = (window - 1) - k;\n        ord_end[idx] = all_series[i].end();\n        ord_iter[idx] = std::make_pair(std::lower_bound(all_series[i].begin(), ord_end[idx], shift + 1), shift);\n        ord_times[idx] = *(ord_iter[idx].first) - ord_iter[idx].second;\n        ++idx;\n      }\n\n      // y^(l)\n      for (std::size_t k = 0; k < y_order; ++k) {\n        shift = (window - 1) - y_delay - k;\n        ord_end[idx] = all_series[j].end();\n        ord_iter[idx] = std::make_pair(std::lower_bound(all_series[j].begin(), ord_end[idx], shift + 1), shift);\n        ord_times[idx] = *(ord_iter[idx].first) - ord_iter[idx].second;\n        ++idx;\n      }\n\n      // Count spikes\n      std::fill(counts.begin(), counts.end(), 0);\n      cur_time = *(std::min_element(ord_times, ord_times + num_series));\n\n      while (cur_time <= end_time) {\n\n        code.reset();\n        next_time = std::numeric_limits<TimeType>::max();\n\n        // Calculate hash code for this time\n        for (std::size_t k = 0; k < num_series; ++k) {\n          if (ord_times[k] == cur_time) {        \n            code[k] = 1;\n\n            // Next spike\n            ++(ord_iter[k].first);\n\n            if (ord_iter[k].first == ord_end[k]) {\n              ord_times[k] = std::numeric_limits<TimeType>::max();\n            }\n            else {\n              ord_times[k] = *(ord_iter[k].first) - ord_iter[k].second;\n            }\n          }\n\n          if (ord_times[k] < next_time) {\n            next_time = ord_times[k];\n          }\n        }\n\n        ++(counts[code.to_ulong()]);\n        cur_time = next_time;\n\n      } // while spikes left\n\n      // Fill in zero count\n      counts[0] = end_time - std::accumulate(counts.begin() + 1, counts.end(), 0);\n\n      // =====================================================================\n\n      // Use counts to calculate TE\n      te_final = 0;\n\n      // Order is x^(k), y^(l), x(n+1)\n      for (std::size_t k = 0; k < num_counts; ++k) {\n        if (counts[k] == 0) {\n          continue;\n        }\n\n        prob_2 = (double)counts[k] / (double)(counts[k] + counts[k ^ 1]);\n\n        std::size_t c1 = 0, c2 = 0;\n        for (std::size_t l = 0; l < num_y; ++l) {\n          idx = (k & (num_x - 1)) + (l << (x_order + 1));\n          c1 += counts[idx];\n          c2 += (counts[idx] + counts[idx ^ 1]);\n        }\n\n        prob_3 = (double)c1 / (double)c2;\n\n        te_final += ((double)counts[k] * (log2(prob_2) - log2(prob_3)));\n      }\n\n      te_result[i - row_start][j - col_start] = te_final / (double)end_time;\n\n    } // for j\n\n  } // for i\n\n} //transent_ho\n\n// Computes the 1st order transfer entropy matrix for all pairs.\ntemplate <typename TimeSeriesCollection, typename ResultMatrix>\nvoid transent_1\n(const TimeSeriesCollection& all_series,\n const typename TimeSeriesCollection::value_type::value_type y_delay,\n const typename TimeSeriesCollection::value_type::value_type duration,\n ResultMatrix& te_result,\n std::size_t row_start = 0, std::size_t rows = 0,\n std::size_t col_start = 0, std::size_t cols = 0) {\n\n  return (transent_ho<TimeSeriesCollection, ResultMatrix, 1, 1>\n          (all_series, y_delay, duration, te_result,\n           row_start, rows, col_start, cols));\n\n} // transent_1\n\n\n// Computes the higher-order transfer entropy matrix for all pairs.\ntemplate <typename TimeSeriesCollection, typename ResultMatrix>\nvoid transent_ho\n(const TimeSeriesCollection& all_series,\n const typename std::size_t x_order, std::size_t y_order,\n const typename TimeSeriesCollection::value_type::value_type y_delay,\n const typename TimeSeriesCollection::value_type::value_type duration,\n ResultMatrix& te_result,\n std::size_t row_start = 0, std::size_t rows = 0,\n std::size_t col_start = 0, std::size_t cols = 0) {\n\n  // Typedefs\n  typedef typename TimeSeriesCollection::value_type TimeSeries;\n  typedef typename TimeSeries::value_type TimeType;\n  typedef typename TimeSeries::const_iterator TimeSeriesIter;\n\n  typedef std::pair<TimeSeriesIter, TimeType> IterShiftPair;\n  typedef std::pair<TimeType, std::size_t> TimeIndexPair;\n\n  // Constants\n  const std::size_t num_series = 1 + y_order + x_order,\n                    num_counts = (std::size_t)pow(2, num_series),\n                    num_x = (std::size_t)pow(2, x_order + 1),\n                    num_y = (std::size_t)pow(2, y_order);\n\n  assert(x_order > 0);\n  assert(y_order > 0);\n  assert(y_delay > 0);\n  assert(num_series <= MAX_XY_ORDER);\n\n  if (rows == 0) {\n    rows = all_series.size();\n  }\n\n  if (cols == 0) {\n    cols = all_series.size();\n  }\n\n  // Locals\n  std::vector<TimeType> counts(num_counts);\n  std::bitset<MAX_XY_ORDER> code;\n  std::size_t idx = 0;\n  double te_final, prob_2, prob_3;\n\n  IterShiftPair ord_iter[num_series];\n  TimeType ord_times[num_series];\n  TimeSeriesIter ord_end[num_series];\n\n  const std::size_t window = std::max(y_order + y_delay, x_order + 1);\n  TimeType cur_time, next_time, end_time = duration - window + 1, shift;\n\n  // Calculate TE\n  for (std::size_t i = row_start; i < (rows + row_start); ++i) {\n    for (std::size_t j = col_start; j < (cols + col_start); ++j) {\n\n      // NOTE: Time series are assumed to be 1-based, so everything is shifted by 1 too.\n      // Order is x^(k+1), y^(l)\n      idx = 0;\n\n      // x^(k+1)\n      for (std::size_t k = 0; k < (x_order + 1); ++k) {\n        shift = (window - 1) - k;\n        ord_end[idx] = all_series[i].end();\n        ord_iter[idx] = std::make_pair(std::lower_bound(all_series[i].begin(), ord_end[idx], shift + 1), shift);\n        ord_times[idx] = *(ord_iter[idx].first) - ord_iter[idx].second;\n        ++idx;\n      }\n\n      // y^(l)\n      for (std::size_t k = 0; k < y_order; ++k) {\n        ord_end[idx] = all_series[j].end();\n        ord_iter[idx] = std::make_pair(all_series[j].begin(), -k);\n        ord_times[idx] = *(ord_iter[idx].first) - ord_iter[idx].second;\n        ++idx;\n      }\n\n      // Count spikes\n      std::fill(counts.begin(), counts.end(), 0);\n      cur_time = *(std::min_element(ord_times, ord_times + num_series));\n\n      while (cur_time <= end_time) {\n\n        code.reset();\n        next_time = std::numeric_limits<TimeType>::max();\n\n        // Calculate hash code for this time\n        for (std::size_t k = 0; k < num_series; ++k) {\n          if (ord_times[k] == cur_time) {        \n            code[k] = 1;\n\n            // Next spike\n            ++(ord_iter[k].first);\n\n            if (ord_iter[k].first == ord_end[k]) {\n              ord_times[k] = std::numeric_limits<TimeType>::max();\n            }\n            else {\n              ord_times[k] = *(ord_iter[k].first) - ord_iter[k].second;\n            }\n          }\n\n          if (ord_times[k] < next_time) {\n            next_time = ord_times[k];\n          }\n        }\n\n        ++(counts[code.to_ulong()]);\n        cur_time = next_time;\n\n      } // while spikes left\n\n      // Fill in zero count\n      counts[0] = end_time - std::accumulate(counts.begin() + 1, counts.end(), 0);\n\n      // =====================================================================\n\n      // Use counts to calculate TE\n      te_final = 0;\n\n      // Order is x^(k), y^(l), x(n+1)\n      for (std::size_t k = 0; k < num_counts; ++k) {\n        if (counts[k] == 0) {\n          continue;\n        }\n\n        prob_2 = (double)counts[k] / (double)(counts[k] + counts[k ^ 1]);\n\n        std::size_t c1 = 0, c2 = 0;\n        for (std::size_t l = 0; l < num_y; ++l) {\n          idx = (k & (num_x - 1)) + (l << (x_order + 1));\n          c1 += counts[idx];\n          c2 += (counts[idx] + counts[idx ^ 1]);\n        }\n\n        prob_3 = (double)c1 / (double)c2;\n\n        te_final += ((double)counts[k] * (log2(prob_2) - log2(prob_3)));\n      }\n\n      te_result[i - row_start][j - col_start] = te_final / (double)end_time;\n\n    } // for j\n\n  } // for i\n\n} // transent_ho\n\n", "meta": {"hexsha": "147f948303a34cca01aa3c605fd349703f54c5b5", "size": 12242, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "cpp/transent.hpp", "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/transent.hpp", "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/transent.hpp", "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": 32.6453333333, "max_line_length": 112, "alphanum_fraction": 0.6042313347, "num_tokens": 3293, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6334102775181399, "lm_q2_score": 0.48828339529583464, "lm_q1q2_score": 0.30928372092183426}}
{"text": "\n\n#include \"distance_measures.h\"\n#include \"ProteinMatrix.h\"\n#include <cmath>\n#include <string>\n\n// #include <xmmintrin.h>\n// #include <emmintrin.h>\n// #include <pmmintrin.h>\n\n#include <boost/assign/std/vector.hpp>\n#include <boost/assign/list_of.hpp> // for 'list_of()'\n\nusing namespace boost::assign; // bring 'list_of()' into scope\n//using namespace boost::assign; // bring 'operator+()' into scope\n\nusing namespace std;\nusing namespace uqam_doc;\n\n//static function pointer calculators\n//using uqam_doc::DistSeqFuncStatic;\n\n//abstract class - interface\n//dist_2seq(string seq_a, string seq_b)\nusing uqam_doc::DistSeqInterface;\n// virtual functions implementations\nusing uqam_doc::Hamming;\nusing uqam_doc::Hamming2;\n\nusing uqam_doc::JukesKantorNucl;\nusing uqam_doc::JukesKantorProt;\nusing uqam_doc::KimProt;\nusing uqam_doc::ScoreDist;\nusing uqam_doc::Blosum80;\nusing uqam_doc::Blosum62;\n\n\n\n/*\nfloat DistSeqFuncStatic::hamming_2seq(string seq_a, string seq_b) {\n\n    float d = 0.0;\n\n    for (int i = 0; i < seq_a.length(); i++) {\n        d += (seq_a.at(i) == seq_b.at(i)) ? 0.0 : 1.0;\n\n    }\n    d /= seq_a.length();\n\n    return d;\n\n}\n */\n\n/*************************************************************************************\n/*\tNom\t\t\t:\tp_Kimura2Parameter\n/*\tParametres\t:\tpmatSites       (in) : Matrice de sites\n/*\t\t\t\t\tpmatDistances   (in) : Matrice de distances\n/*\t\t\t\t\tpintNbreEspeces (in) : Nombre d'esp�ces\n/*\t\t\t\t\tpintNbreSites   (in) : Nombre de sites\n/*\tRetour\t\t:\t-\n/*\tObjectif\t:\tComparer les s�quences deux par deux, en utilisant la m�thode\n/*\t\t\t\t\tKimura 2-Parameter, et stoker les distances entre elles dans la\n/*\t\t\t\t\tmatrice des distances.\n **************************************************************************************/\n\n/*\nfloat DistSeqFuncStatic::kimprot_2seq(string seq_a, string seq_b) {\n\n    //cout << \"------------------k2p_2seq\" << endl;\n    int nb_sites = seq_a.length();\n    float dist;\n\n    int k; // Compteur\n    float dblCorrespandance; // Nombre de correspondances entre les sites\n    int intPosComparable; // Nombre de positions comparables, l� o� il n'y a pas de gaps\n    int intGaps; // Les lacunes contenues dans les s�quences\n    float dblD; // Uncorrected distance\n\n\n    dblCorrespandance = 0;\n    intPosComparable = 0;\n    intGaps = 0;\n\n    for (k = 1; k <= nb_sites; k++) {\n        if ((seq_a[k] == seq_b[k]) && (seq_a[k] != '-') && (seq_a[k] != '?'))\n            dblCorrespandance++;\n        else if ((seq_a[k] == '-') || (seq_a[k] == '?') ||\n                (seq_b[k] == '-') || (seq_b[k] == '?'))\n            intGaps++;\n    }\n    intPosComparable = nb_sites - intGaps;\n\n    if (intPosComparable != 0) {\n        dblD = 1 - dblCorrespandance / intPosComparable;\n        dblD = 1 - dblD - 0.2 * dblD * dblD;\n        if (dblD <= 0) {\n            //non comparable\n            dist = INFINITY;\n        } else {\n            dist = -log(dblD);\n        }\n    } else {\n        //non comparable\n        dist = INFINITY;\n    }\n\n    return dist;\n\n}\n */\n\nDistAtom Hamming::dist_2seq(string seq_a, string seq_b) {\n\n    float intDist = 0.0;\n    float realDist = 0.0;\n\n    for (int i = 0; i < seq_a.length(); i++) {\n\n        intDist += (seq_a[i] == seq_b[i] ? 0 : 1);\n\n    }\n\n    realDist = intDist / seq_a.length();\n\n    return DistAtom(intDist, seq_a.length(), 0, realDist);\n}\n\nvoid Hamming::testIntrin() {\n    /**\n    int i;\n\n    __m128d a, b, c;\n    float x0[2] __attribute__((aligned(16))) = {1.2, 3.5};\n    float x1[2] __attribute__((aligned(16))) = {0.7, 2.6};\n    a = _mm_load_pd(x0);\n    b = _mm_load_pd(x1);\n    c = _mm_add_pd(a, b);\n    _mm_store_pd(x0, c);\n    for (i = 0; i < 2; i++) {\n       cout << x0[i] << endl;\n    }\n     **/\n\n}\n\nDistAtom Hamming2::dist_2seq(string seq_a, string seq_b) {\n\n    float pos_comparable = 0;\n    float prop_gaps = 0;\n\n    float two_gap = 0;\n    float one_gap = 0;\n    float ident = 0;\n    float subst = 0;\n\n    float intDist = 0.0;\n    float realDist = 0.0;\n\n    for (int i = 0; i < seq_a.length(); i++) {\n\n        //if no gaps\n        if (seq_a[i] != '-' && seq_b[i] != '-') {\n\n            if (seq_a[i] == seq_b[i]) { // identities\n                ident++;\n\n            } else { //substitutions\n                subst++;\n\n            }\n\n\n        } else if (seq_a[i] == '-' && seq_b[i] == '-') {\n            two_gap++;\n\n        } else {\n            one_gap++;\n        }\n\n        if (seq_a[i] != seq_b[i]) {\n            intDist++;\n        }\n\n\n        /*\n        //identities\n        if ((seq_a[i] == seq_b[i]) && (seq_a[i] != '-') && (seq_a[i] != '?')) {\n            intCorrespandance++;\n        //gaps\n        } else if ((seq_a[i] == '-') || (seq_a[i] == '?') ||\n                (seq_b[i] == '-') || (seq_b[i] == '?')) {\n            intGaps++;\n        //substitutions\n        } else {\n            intDist++;\n        }\n         */\n\n    }\n\n    intDist = subst + one_gap;\n    pos_comparable = ident + subst + one_gap;\n\n    prop_gaps = (one_gap + two_gap) / float(seq_a.length());\n\n    if (prop_gaps <= 0.5) {\n        realDist = intDist /= pos_comparable;\n        //realDist = intDist /= seq_a.length();\n    } else {\n        intDist = numeric_limits<float>::max();\n        realDist = numeric_limits<float>::max();\n    }\n\n\n    /*\n\n   intPosComparable = seq_a.length() - intGaps;\n   //si trop de gaps, incomparables\n   if (intGaps >= seq_a.length() * 0.9) {\n       intDist = numeric_limits<float>::max();\n       realDist = numeric_limits<float>::max();\n   } else {\n       realDist = intDist /= seq_a.length();\n   }\n     */\n    return DistAtom(intDist, seq_a.length(), 0, realDist);\n    //debug\n    //return DistAtom(prop_gaps, seq_a.length(), 0, prop_gaps);\n}\n\nvoid JukesKantorNucl::set_penality(float penality) {\n    penalty_ = penality;\n}\n\nJukesKantorNucl::JukesKantorNucl(float penality) {\n    cout << \"================JUKES CANTOR NUCL\" << endl;\n    penalty_ = penality;\n}\n\nJukesKantorNucl::~JukesKantorNucl() {\n\n}\n\n/*************************************************************************************\n/*\tNom\t\t\t:\tp_JukesCantorNucleo\n/*\tParam�tres\t:\tpmatSites       (in) : Matrice de sites\n/*\t\t\t\t\tpmatDistances   (in) : Matrice de distances\n/*\t\t\t\t\tpintNbreEspeces (in) : Nombre d'esp�ces\n/*\t\t\t\t\tpintNbreSites   (in) : Nombre de sites\n/*\t\t\t\t\tpdblPenalite    (in) : P�nalit� donn�e par l'utilisateur\n/*\tRetour\t\t:\t-\n/*\tObjectif\t:\tComparer les s�quences deux par deux, en utilisant la m�thode\n/*\t\t\t\t\tJukes-Cantor pour nucl�otides, et stoker les distances entre elles\n/*\t\t\t\t\tdans la matrice des distances.\n **************************************************************************************/\nDistAtom JukesKantorNucl::dist_2seq(string seq_a, string seq_b) {\n\n    int nb_sites = seq_a.length();\n    float dist;\n    int k; // Compteurs\n    int intCorrespandance; // Nombre de correspondances entre les sites\n    int intPosComparable; // Nombre de positions comparables, la o� il n'y a pas de gaps\n    int intGaps; // Les lacunes contenues dans les sequences\n    float dblD; // Uncorrected distance\n    float dblb; // Param�tre b\n\n    dblb = 3. / 4;\n\n    intCorrespandance = 0;\n    intGaps = 0;\n\n    for (k = 1; k <= nb_sites; k++) {\n        if ((seq_a[k] == seq_b[k]) && (seq_a[k] != '-') && (seq_a[k] != '?'))\n            intCorrespandance++;\n        else if ((seq_a[k] == '-') || (seq_a[k] == '?') ||\n                (seq_b[k] == '-') || (seq_b[k] == '?'))\n            intGaps++;\n    }\n    intPosComparable = nb_sites - intGaps;\n\n    if (intPosComparable != 0) {\n        dblD = 1 - intCorrespandance / (intPosComparable + penalty_ * intGaps);\n        dblD = dblD / dblb;\n        if (1 - dblD <= 0) dist = numeric_limits<float>::max();\n        else dist = -dblb * log(1 - dblD);\n    } else {\n        dist = numeric_limits<float>::max();\n    }\n    return DistAtom(numeric_limits<float>::max(), intPosComparable, intGaps, dist);\n\n}\n\nvoid JukesKantorProt::set_penality(float penality) {\n    penality_ = penality;\n}\n\nJukesKantorProt::JukesKantorProt(float penality) {\n    penality_ = penality;\n}\n\nJukesKantorProt::~JukesKantorProt() {\n\n}\n\n/*************************************************************************************\n/*\tNom\t\t\t:\tp_JukesCantorProt\n/*\tParam�tres\t:\tpmatSites       (in) : Matrice de sites\n/*\t\t\t\t\tpmatDistances   (in) : Matrice de distances\n/*\t\t\t\t\tpintNbreEspeces (in) : Nombre d'esp�ces\n/*\t\t\t\t\tpintNbreSites   (in) : Nombre de sites\n/*\t\t\t\t\tpdblPenalite    (in) : P�nalit� donn�e par l'utilisateur\n/*\tRetour\t\t:\t-\n/*\tObjectif\t:\tComparer les s�quences deux par deux, en utilisant la m�thode\n/*\t\t\t\t\tJukes-Cantor pour prot�ines, et stoker les distances entre elles\n/*\t\t\t\t\tdans la matrice des distances.\n **************************************************************************************/\nDistAtom JukesKantorProt::dist_2seq(string seq_a, string seq_b) {\n\n    int nb_sites = seq_a.length();\n    float dist;\n\n    int k; // Compteurs\n    int intCorrespandance; // Nombre de correspondances entre les sites\n    int intPosComparable; // Nombre de positions comparables, l� o� il n'y a pas de gaps\n    int intGaps; // Les lacunes contenues dans les s�quences\n    float dblD; // Uncorrected distance\n    float dblb; // Param�tre b\n\n    dblb = 19. / 20;\n\n\n    intCorrespandance = 0;\n    intGaps = 0;\n\n    for (k = 1; k <= nb_sites; k++) {\n        if ((seq_a[k] == seq_b[k]) && (seq_a[k] != '-') && (seq_a[k] != '?'))\n            intCorrespandance++;\n        else if ((seq_a[k] == '-') || (seq_a[k] == '?') ||\n                (seq_b[k] == '-') || (seq_b[k] == '?'))\n            intGaps++;\n    }\n    intPosComparable = nb_sites - intGaps;\n\n    if (intPosComparable != 0) {\n        dblD = 1.0 - intCorrespandance / (intPosComparable + penality_ * intGaps);\n        dblD = dblD / dblb;\n        if (1 - dblD <= 0)\n            dist = numeric_limits<float>::max();\n        else\n            dist = -dblb * log(1 - dblD);\n    } else\n        dist = numeric_limits<float>::max();\n\n    return DistAtom(numeric_limits<float>::max(), intPosComparable, intGaps, dist);\n    //if(pmatDistances[j][i] < 0 || pmatDistances[j][i] > 10)\n    //\t\t\tprintf(\"\\n%d %d %lf\",i,j,dist);\n\n\n}\n\n/*************************************************************************************\n/*\tNom\t\t\t:\tp_KimuraProtein\n/*\tParam�tres\t:\tpmatSites       (in) : Matrice de sites\n/*\t\t\t\t\tpmatDistances   (in) : Matrice de distances\n/*\t\t\t\t\tpintNbreEspeces (in) : Nombre d'esp�ces\n/*\t\t\t\t\tpintNbreSites   (in) : Nombre de sites\n/*\tRetour\t\t:\t-\n/*\tObjectif\t:\tComparer les s�quences deux par deux, en utilisant la m�thode\n/*\t\t\t\t\tKimura Protein, et stoker les distances entre elles dans la matrice\n/*\t\t\t\t\tdes distances.\n **************************************************************************************/\nDistAtom KimProt::dist_2seq(string seq_a, string seq_b) {\n    //cout << \"------------------k2p_2seq\" << endl;\n    int nb_sites = seq_a.length();\n    float dist;\n\n    int k; // Compteur\n    float dblCorrespandance; // Nombre de correspondances entre les sites\n    int intPosComparable; // Nombre de positions comparables, l� o� il n'y a pas de gaps\n    int intGaps; // Les lacunes contenues dans les s�quences\n    float dblD; // Uncorrected distance\n\n\n    dblCorrespandance = 0;\n    intPosComparable = 0;\n    intGaps = 0;\n\n    for (k = 1; k <= nb_sites; k++) {\n        if ((seq_a[k] == seq_b[k]) && (seq_a[k] != '-') && (seq_a[k] != '?'))\n            dblCorrespandance++;\n        else if ((seq_a[k] == '-') || (seq_a[k] == '?') ||\n                (seq_b[k] == '-') || (seq_b[k] == '?'))\n            intGaps++;\n    }\n    intPosComparable = nb_sites - intGaps;\n\n    if (intPosComparable != 0) {\n        dblD = 1 - dblCorrespandance / intPosComparable;\n        dblD = 1 - dblD - 0.2 * dblD * dblD;\n        if (dblD <= 0) {\n            //non comparable\n            dist = numeric_limits<float>::max();\n        } else {\n            dist = -log(dblD);\n        }\n    } else {\n        //non comparable\n        dist = numeric_limits<float>::max();\n    }\n\n    return DistAtom(numeric_limits<float>::max(), intPosComparable, intGaps, dist);\n\n}\n\n\n//load inherited fields\n\nBlosum80::Blosum80() {\n    //ftp://ftp.ncbi.nih.gov/blast/matrices/BLOSUM80\n    //matrices\n    //mat_prot_ident_ += \"A\", \"R\", \"N\", \"D\", \"C\", \"Q\", \"E\", \"G\", \"H\", \"I\", \"L\", \"K\", \"M\", \"F\", \"P\", \"S\", \"T\", \"W\", \"Y\", \"V\", \"B\", \"Z\", \"X\", \"_\";\n    mat_prot_ident_ = list_of(\"A\") (\"R\") (\"N\") (\"D\") (\"C\") (\"Q\") (\"E\") (\"G\") (\"H\") (\"I\") (\"L\") (\"K\") (\"M\") (\"F\") (\"P\") (\"S\") (\"T\") (\"W\") (\"Y\") (\"V\") (\"B\") (\"Z\") (\"X\") (\"*\");\n\n    mat_prot_ += list_of(7)(-3)(-3)(-3)(-1)(-2)(-2)(0)(-3)(-3)(-3)(-1)(-2)(-4)(-1)(2)(0)(-5)(-4)(-1)(-3)(-2)(-1)(-8);\n    mat_prot_ += list_of(-3)(9)(-1)(-3)(-6)(1)(-1)(-4)(0)(-5)(-4)(3)(-3)(-5)(-3)(-2)(-2)(-5)(-4)(-4)(-2)(0)(-2)(-8);\n    mat_prot_ += list_of(-3)(-1)(9)(2)(-5)(0)(-1)(-1)(1)(-6)(-6)(0)(-4)(-6)(-4)(1)(0)(-7)(-4)(-5)(5)(-1)(-2)(-8);\n    mat_prot_ += list_of(-3)(-3)(2)(10)(-7)(-1)(2)(-3)(-2)(-7)(-7)(-2)(-6)(-6)(-3)(-1)(-2)(-8)(-6)(-6)(6)(1)(-3)(-8);\n    mat_prot_ += list_of(-1)(-6)(-5)(-7)(13)(-5)(-7)(-6)(-7)(-2)(-3)(-6)(-3)(-4)(-6)(-2)(-2)(-5)(-5)(-2)(-6)(-7)(-4)(-8);\n    mat_prot_ += list_of(-2)(1)(0)(-1)(-5)(9)(3)(-4)(1)(-5)(-4)(2)(-1)(-5)(-3)(-1)(-1)(-4)(-3)(-4)(-1)(5)(-2)(-8);\n    mat_prot_ += list_of(-2)(-1)(-1)(2)(-7)(3)(8)(-4)(0)(-6)(-6)(1)(-4)(-6)(-2)(-1)(-2)(-6)(-5)(-4)(1)(6)(-2)(-8);\n    mat_prot_ += list_of(0)(-4)(-1)(-3)(-6)(-4)(-4)(9)(-4)(-7)(-7)(-3)(-5)(-6)(-5)(-1)(-3)(-6)(-6)(-6)(-2)(-4)(-3)(-8);\n    mat_prot_ += list_of(-3)(0)(1)(-2)(-7)(1)(0)(-4)(12)(-6)(-5)(-1)(-4)(-2)(-4)(-2)(-3)(-4)(3)(-5)(-1)(0)(-2)(-8);\n    mat_prot_ += list_of(-3)(-5)(-6)(-7)(-2)(-5)(-6)(-7)(-6)(7)(2)(-5)(2)(-1)(-5)(-4)(-2)(-5)(-3)(4)(-6)(-6)(-2)(-8);\n    mat_prot_ += list_of(-3)(-4)(-6)(-7)(-3)(-4)(-6)(-7)(-5)(2)(6)(-4)(3)(0)(-5)(-4)(-3)(-4)(-2)(1)(-7)(-5)(-2)(-8);\n    mat_prot_ += list_of(-1)(3)(0)(-2)(-6)(2)(1)(-3)(-1)(-5)(-4)(8)(-3)(-5)(-2)(-1)(-1)(-6)(-4)(-4)(-1)(1)(-2)(-8);\n    mat_prot_ += list_of(-2)(-3)(-4)(-6)(-3)(-1)(-4)(-5)(-4)(2)(3)(-3)(9)(0)(-4)(-3)(-1)(-3)(-3)(1)(-5)(-3)(-2)(-8);\n    mat_prot_ += list_of(-4)(-5)(-6)(-6)(-4)(-5)(-6)(-6)(-2)(-1)(0)(-5)(0)(10)(-6)(-4)(-4)(0)(4)(-2)(-6)(-6)(-3)(-8);\n    mat_prot_ += list_of(-1)(-3)(-4)(-3)(-6)(-3)(-2)(-5)(-4)(-5)(-5)(-2)(-4)(-6)(12)(-2)(-3)(-7)(-6)(-4)(-4)(-2)(-3)(-8);\n    mat_prot_ += list_of(2)(-2)(1)(-1)(-2)(-1)(-1)(-1)(-2)(-4)(-4)(-1)(-3)(-4)(-2)(7)(2)(-6)(-3)(-3)(0)(-1)(-1)(-8);\n    mat_prot_ += list_of(0)(-2)(0)(-2)(-2)(-1)(-2)(-3)(-3)(-2)(-3)(-1)(-1)(-4)(-3)(2)(8)(-5)(-3)(0)(-1)(-2)(-1)(-8);\n    mat_prot_ += list_of(-5)(-5)(-7)(-8)(-5)(-4)(-6)(-6)(-4)(-5)(-4)(-6)(-3)(0)(-7)(-6)(-5)(16)(3)(-5)(-8)(-5)(-5)(-8);\n    mat_prot_ += list_of(-4)(-4)(-4)(-6)(-5)(-3)(-5)(-6)(3)(-3)(-2)(-4)(-3)(4)(-6)(-3)(-3)(3)(11)(-3)(-5)(-4)(-3)(-8);\n    mat_prot_ += list_of(-1)(-4)(-5)(-6)(-2)(-4)(-4)(-6)(-5)(4)(1)(-4)(1)(-2)(-4)(-3)(0)(-5)(-3)(7)(-6)(-4)(-2)(-8);\n    mat_prot_ += list_of(-3)(-2)(5)(6)(-6)(-1)(1)(-2)(-1)(-6)(-7)(-1)(-5)(-6)(-4)(0)(-1)(-8)(-5)(-6)(6)(0)(-3)(-8);\n    mat_prot_ += list_of(-2)(0)(-1)(1)(-7)(5)(6)(-4)(0)(-6)(-5)(1)(-3)(-6)(-2)(-1)(-2)(-5)(-4)(-4)(0)(6)(-1)(-8);\n    mat_prot_ += list_of(-1)(-2)(-2)(-3)(-4)(-2)(-2)(-3)(-2)(-2)(-2)(-2)(-2)(-3)(-3)(-1)(-1)(-5)(-3)(-2)(-3)(-1)(-2)(-8);\n    mat_prot_ += list_of(-8)(-8)(-8)(-8)(-8)(-8)(-8)(-8)(-8)(-8)(-8)(-8)(-8)(-8)(-8)(-8)(-8)(-8)(-8)(-8)(-8)(-8)(-8)(1);\n\n\n    //cout << mat_prot_ident_.at(22) << endl;\n    //cout << mat_prot_ident_.at(17) << endl;\n\n    //ftp://ftp.ncbi.nih.gov/blast/matrices/BLOSUM80\n\n\n    //cout << mat_prot_.at(22).at(17) << endl;\n\n    mat_prot_expect_ = -0.7442;\n\n\n}\n\n//load inherited fields\n\nBlosum62::Blosum62() {\n    //ftp://ftp.ncbi.nih.gov/blast/matrices/BLOSUM80\n    //matrices\n    //mat_prot_ident_ += \"A\", \"R\", \"N\", \"D\", \"C\", \"Q\", \"E\", \"G\", \"H\", \"I\", \"L\", \"K\", \"M\", \"F\", \"P\", \"S\", \"T\", \"W\", \"Y\", \"V\", \"B\", \"Z\", \"X\", \"_\";\n    mat_prot_ident_ = list_of(\"A\") (\"R\") (\"N\") (\"D\") (\"C\") (\"Q\") (\"E\") (\"G\") (\"H\") (\"I\") (\"L\") (\"K\") (\"M\") (\"F\") (\"P\") (\"S\") (\"T\") (\"W\") (\"Y\") (\"V\") (\"B\") (\"Z\") (\"X\") (\"*\");\n\n    mat_prot_ += list_of (4)(-1)(-2)(-2)(0)(-1)(-1)(0)(-2)(-1)(-1)(-1)(-1)(-2)(-1)(1)(0)(-3)(-2)(0)(-2)(-1)(0)(-4);\n    mat_prot_ += list_of (-1)(5)(0)(-2)(-3)(1)(0)(-2)(0)(-3)(-2)(2)(-1)(-3)(-2)(-1)(-1)(-3)(-2)(-3)(-1)(0)(-1)(-4);\n    mat_prot_ += list_of (-2)(0)(6)(1)(-3)(0)(0)(0)(1)(-3)(-3)(0)(-2)(-3)(-2)(1)(0)(-4)(-2)(-3)(3)(0)(-1)(-4);\n    mat_prot_ += list_of (-2)(-2)(1)(6)(-3)(0)(2)(-1)(-1)(-3)(-4)(-1)(-3)(-3)(-1)(0)(-1)(-4)(-3)(-3)(4)(1)(-1)(-4);\n    mat_prot_ += list_of (0)(-3)(-3)(-3)(9)(-3)(-4)(-3)(-3)(-1)(-1)(-3)(-1)(-2)(-3)(-1)(-1)(-2)(-2)(-1)(-3)(-3)(-2)(-4);\n    mat_prot_ += list_of (-1)(1)(0)(0)(-3)(5)(2)(-2)(0)(-3)(-2)(1)(0)(-3)(-1)(0)(-1)(-2)(-1)(-2)(0)(3)(-1)(-4);\n    mat_prot_ += list_of (-1)(0)(0)(2)(-4)(2)(5)(-2)(0)(-3)(-3)(1)(-2)(-3)(-1)(0)(-1)(-3)(-2)(-2)(1)(4)(-1)(-4);\n    mat_prot_ += list_of (0)(-2)(0)(-1)(-3)(-2)(-2)(6)(-2)(-4)(-4)(-2)(-3)(-3)(-2)(0)(-2)(-2)(-3)(-3)(-1)(-2)(-1)(-4);\n    mat_prot_  += list_of (-2)(0)(1)(-1)(-3)(0)(0)(-2)(8)(-3)(-3)(-1)(-2)(-1)(-2)(-1)(-2)(-2)(2)(-3)(0)(0)(-1)(-4);\n    mat_prot_ += list_of (-1)(-3)(-3)(-3)(-1)(-3)(-3)(-4)(-3)(4)(2)(-3)(1)(0)(-3)(-2)(-1)(-3)(-1)(3)(-3)(-3)(-1)(-4);\n    mat_prot_ += list_of (-1)(-2)(-3)(-4)(-1)(-2)(-3)(-4)(-3)(2)(4)(-2)(2)(0)(-3)(-2)(-1)(-2)(-1)(1)(-4)(-3)(-1)(-4);\n    mat_prot_ += list_of (-1)(2)(0)(-1)(-3)(1)(1)(-2)(-1)(-3)(-2)(5)(-1)(-3)(-1)(0)(-1)(-3)(-2)(-2)(0)(1)(-1)(-4);\n    mat_prot_ += list_of (-1)(-1)(-2)(-3)(-1)(0)(-2)(-3)(-2)(1)(2)(-1)(5)(0)(-2)(-1)(-1)(-1)(-1)(1)(-3)(-1)(-1)(-4);\n    mat_prot_ += list_of (-2)(-3)(-3)(-3)(-2)(-3)(-3)(-3)(-1)(0)(0)(-3)(0)(6)(-4)(-2)(-2)(1)(3)(-1)(-3)(-3)(-1)(-4);\n    mat_prot_ += list_of (-1)(-2)(-2)(-1)(-3)(-1)(-1)(-2)(-2)(-3)(-3)(-1)(-2)(-4)(7)(-1)(-1)(-4)(-3)(-2)(-2)(-1)(-2)(-4);\n    mat_prot_ += list_of (1)(-1)(1)(0)(-1)(0)(0)(0)(-1)(-2)(-2)(0)(-1)(-2)(-1)(4)(1)(-3)(-2)(-2)(0)(0)(0)(-4);\n    mat_prot_ += list_of (0)(-1)(0)(-1)(-1)(-1)(-1)(-2)(-2)(-1)(-1)(-1)(-1)(-2)(-1)(1)(5)(-2)(-2)(0)(-1)(-1)(0)(-4);\n    mat_prot_ += list_of (-3)(-3)(-4)(-4)(-2)(-2)(-3)(-2)(-2)(-3)(-2)(-3)(-1)(1)(-4)(-3)(-2)(11)(2)(-3)(-4)(-3)(-2)(-4);\n    mat_prot_ += list_of (-2)(-2)(-2)(-3)(-2)(-1)(-2)(-3)(2)(-1)(-1)(-2)(-1)(3)(-3)(-2)(-2)(2)(7)(-1)(-3)(-2)(-1)(-4);\n    mat_prot_ += list_of (0)(-3)(-3)(-3)(-1)(-2)(-2)(-3)(-3)(3)(1)(-2)(1)(-1)(-2)(-2)(0)(-3)(-1)(4)(-3)(-2)(-1)(-4);\n    mat_prot_ += list_of (-2)(-1)(3)(4)(-3)(0)(1)(-1)(0)(-3)(-4)(0)(-3)(-3)(-2)(0)(-1)(-4)(-3)(-3)(4)(1)(-1)(-4);\n    mat_prot_ += list_of (-1)(0)(0)(1)(-3)(3)(4)(-2)(0)(-3)(-3)(1)(-1)(-3)(-1)(0)(-1)(-3)(-2)(-2)(1)(4)(-1)(-4);\n    mat_prot_ += list_of (0)(-1)(-1)(-1)(-2)(-1)(-1)(-1)(-1)(-1)(-1)(-1)(-1)(-1)(-2)(0)(0)(-2)(-1)(-1)(-1)(-1)(-1)(-4);\n    mat_prot_ += list_of (-4)(-4)(-4)(-4)(-4)(-4)(-4)(-4)(-4)(-4)(-4)(-4)(-4)(-4)(-4)(-4)(-4)(-4)(-4)(-4)(-4)(-4)(-4)(1);\n\n\n    //cout << mat_prot_ident_.at(22) << endl;\n    //cout << mat_prot_ident_.at(17) << endl;\n\n    //ftp://ftp.ncbi.nih.gov/blast/matrices/BLOSUM62\n\n\n    //cout << mat_prot_.at(22).at(17) << endl;\n\n    mat_prot_expect_ = -0.5209;\n\n\n}\n\n//constructor\n\nScoreDist::ScoreDist(ApplicationData* appl_data) {\n\n    // mat_prot_ = BLOSUM80_E;\n\n    if (appl_data->protmatrix_ == eBLOSUM80) {\n        matrix_ = new Blosum80();\n    } else if (appl_data->protmatrix_ == eBLOSUM62) {\n        matrix_ = new Blosum62();\n\n    //cout << \" mat_prot_ident_[1]: \" << matrix_->getMatProtIdent().at(1) << endl;\n    //cout << \" mat_prot_[1][5]: \" << matrix_->getMatProt().at(22).at(17) << endl;\n    }\n\n}\n\n\n\n\nDistAtom ScoreDist::dist_2seq(string seq_a, string seq_b) {\n    //cout << \"------------------k2p_2seq\" << endl;\n    //cout << \"seq_a: \" << seq_a << endl;\n    //cout << \"seq_b: \" << seq_b << endl;\n\n\n    int len = seq_a.length();\n\n    float sigma_s1_s2 = simple_dist_2seq(seq_a, seq_b);\n    float sigma_s1_s1 = simple_dist_2seq(seq_a, seq_a);\n    float sigma_s2_s2 = simple_dist_2seq(seq_b, seq_b);\n    float sigma_r_l = matrix_->getMatProtExpect() * len;\n\n    //correct lower_bound\n    if (sigma_s1_s2 < sigma_r_l) {\n        sigma_s1_s2 = sigma_r_l;\n    }\n\n\n    float sigma_n = sigma_s1_s2 - sigma_r_l;\n    float sigma_u_s1_s2 = (sigma_s1_s1 + sigma_s2_s2) / 2;\n    float sigma_un = sigma_u_s1_s2 - sigma_r_l;\n    float dist_01 = sigma_n /sigma_un;\n\n    //poisson process correction\n    float d_r = - log (dist_01) * 100 ;\n    //calibration constant\n    float c = 1.3370;\n\n    float d_s = c * d_r;\n\n    /*Evolutionary distances of 250–300 PAM units are commonly considered as the maximum\n     * for reasonable distance estimation and, therefore,\n     * the Scoredist estimate ds is restricted to the interval [0, 300] PAM.\n     */\n    float dist = 0;\n\n    float MAX_PAM = 1000;\n\n\n    //dist = c * dist_01;\n\n    if (d_s > MAX_PAM) {\n       dist  = MAX_PAM;\n    }\n\n\n\n    // cout << \"dist: \" << dist << endl;\n    //wrap d_s\n    return DistAtom(floor(dist*seq_a.length()), seq_a.length(), 0, dist);\n\n}\n\nfloat ScoreDist::simple_dist_2seq(string seq_a, string seq_b) {\n    //cout << \"------------------k2p_2seq\" << endl;\n    int nb_sites = seq_a.length();\n    float s = 0.0;\n\n\n    //sum\n    for (int k = 0; k < nb_sites; k++) {\n        s += dist_2car(seq_a.substr(k, 1), seq_b.substr(k, 1));\n\n    }\n\n    return s;\n\n}\n\nfloat ScoreDist::dist_2car(string car_a, string car_b) {\n\n    float one_dist = 0.0;\n\n\n    //cout << \"car_a: \" << car_a << endl;\n    //cout << \"car_b: \" << car_b << endl;\n\n    int idx_a = std::find(matrix_->getMatProtIdent().begin(), matrix_->getMatProtIdent().end(), car_a) - matrix_->getMatProtIdent().begin();\n    int idx_b = std::find(matrix_->getMatProtIdent().begin(), matrix_->getMatProtIdent().end(), car_b) - matrix_->getMatProtIdent().begin();\n\n\n    //underscore or other defaults to *\n    if (idx_a == matrix_->getMatProtIdent().size()) {\n        car_a = \"*\";\n        //and refind\n        idx_a = std::find(matrix_->getMatProtIdent().begin(), matrix_->getMatProtIdent().end(), car_a) - matrix_->getMatProtIdent().begin();\n    }\n\n    if (idx_b == matrix_->getMatProtIdent().size()) {\n        car_b = \"*\";\n        //and refind\n        idx_b = std::find(matrix_->getMatProtIdent().begin(), matrix_->getMatProtIdent().end(), car_b) - matrix_->getMatProtIdent().begin();\n    }\n\n    one_dist = matrix_->getMatProt().at(idx_a).at(idx_b);\n\n    //cout << \"one_dist: \" << one_dist << endl;\n\n    return one_dist;\n\n\n}\n\n", "meta": {"hexsha": "0ab1e2ffde167511651fe89eb568d503768fef12", "size": 22205, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Chapter5/Main/hgt-qfunc.v.0.5.2/src/distance_measures.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": "Chapter5/Main/hgt-qfunc.v.0.5.2/src/distance_measures.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": "Chapter5/Main/hgt-qfunc.v.0.5.2/src/distance_measures.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": 34.9135220126, "max_line_length": 173, "alphanum_fraction": 0.4915559559, "num_tokens": 8610, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5389832354982647, "lm_q2_score": 0.5736784074525096, "lm_q1q2_score": 0.30920304418424543}}
{"text": "/**\n * $Id$\n * \n * Software License Agreement (GNU General Public License)\n *\n *  Copyright (C) 2015:\n *\n *    Johann Prankl, prankl@acin.tuwien.ac.at\n *    Aitor Aldoma, aldoma@acin.tuwien.ac.at\n *\n *      Automation and Control Institute\n *      Vienna University of Technology\n *      Gusshausstraße 25-29\n *      1170 Vienn, Austria\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 * @author Johann Prankl, Aitor Aldoma\n *\n */\n\n#ifndef KP_BA_COST_FUNCTIONS_HPP\n#define KP_BA_COST_FUNCTIONS_HPP\n\n#include <Eigen/Dense>\n#include <ceres/rotation.h>\n#include <v4r/common/impl/Vector.hpp>\n#include <v4r/keypoints/impl/invPose.hpp>\n\nnamespace v4r\n{\n\ntemplate<class T>\ninline void print_values(const std::string &txt, const T &val1, const T &val2, const T &val3, const T &val4)\n{\n    //Do nothing\n}\n\ntemplate<>\ninline void print_values<double>(const std::string &txt, const double &val1, const double &val2, const double &val3, const double &val4)\n{\n  std::cout<<txt<<\" \"<<val1<<\" \"<<val2<<\" \"<<val3<<\" \"<<val4<<std::endl;\n}\n\n/**\n * Apply camera intrinsics to the normalized point to get image coordinates.\n * This applies the radial lens distortion to a point which is in normalized\n * camera coordinates (i.e. the principal point is at (0, 0)) to get image\n * coordinates in pixels. Templated for use with autodifferentiation.\n */\ntemplate <typename T>\ninline void applyRadialDistortionCameraIntrinsics(const T &focal_length_x,\n                                                  const T &focal_length_y,\n                                                  const T &principal_point_x,\n                                                  const T &principal_point_y,\n                                                  const T &k1,\n                                                  const T &k2,\n                                                  const T &k3,\n                                                  const T &p1,\n                                                  const T &p2,\n                                                  const T &normalized_x,\n                                                  const T &normalized_y,\n                                                  T *image_x,\n                                                  T *image_y) {\n  T x = normalized_x;\n  T y = normalized_y;\n\n  // Apply distortion to the normalized points to get (xd, yd).\n  T r2 = x*x + y*y;\n  T r4 = r2 * r2;\n  T r6 = r4 * r2;\n  T r_coeff = (T(1) + k1*r2 + k2*r4 + k3*r6);\n  T xd = x * r_coeff + T(2)*p1*x*y + p2*(r2 + T(2)*x*x);\n  T yd = y * r_coeff + T(2)*p2*x*y + p1*(r2 + T(2)*y*y);\n\n  // Apply focal length and principal point to get the final image coordinates.\n  *image_x = focal_length_x * xd + principal_point_x;\n  *image_y = focal_length_y * yd + principal_point_y;\n}\n\n/**\n * Apply camera intrinsics to the normalized point to get image coordinates.\n * Templated for use with autodifferentiation.\n */\ntemplate <typename T>\ninline void applyCameraIntrinsics(const T &focal_length_x,\n                                  const T &focal_length_y,\n                                  const T &principal_point_x,\n                                  const T &principal_point_y,\n                                  const T &normalized_x,\n                                  const T &normalized_y,\n                                  T *image_x,\n                                  T *image_y) {\n  // Apply focal length and principal point to get the final image coordinates.\n  *image_x = focal_length_x * normalized_x + principal_point_x;\n  *image_y = focal_length_y * normalized_y + principal_point_y;\n}\n\n\n/**\n * Cost functor which computes reprojection error of 3D point X\n * on camera defined by angle-axis rotation and it's translation\n * (which are in the same block due to optimization reasons).\n * This functor uses a radial distortion model.\n */\nstruct RadialDistortionReprojectionError {\n  RadialDistortionReprojectionError(const double &_observed_x, const double &_observed_y)\n      : observed_x(_observed_x), observed_y(_observed_y) {}\n\n  template <typename T>\n  bool operator()(const T* const intrinsics,\n                  const T* const R_t,  // Rotation denoted by angle axis\n                                       // followed with translation\n                  const T* const X,    // Point coordinates 3x1.\n                  T* residuals) const {\n    // Unpack the intrinsics.\n    const T& focal_length_x    = intrinsics[0];\n    const T& focal_length_y    = intrinsics[1];\n    const T& principal_point_x = intrinsics[2];\n    const T& principal_point_y = intrinsics[3];\n    const T& k1                = intrinsics[4];\n    const T& k2                = intrinsics[5];\n    const T& k3                = intrinsics[6];\n    const T& p1                = intrinsics[7];\n    const T& p2                = intrinsics[8];\n\n    // Compute projective coordinates: x = RX + t.\n    T x[3];\n\n    ceres::AngleAxisRotatePoint(R_t, X, x);\n    x[0] += R_t[3];\n    x[1] += R_t[4];\n    x[2] += R_t[5];\n\n    // Compute normalized coordinates: x /= x[2].\n    T xn = x[0] / x[2];\n    T yn = x[1] / x[2];\n\n    T predicted_x, predicted_y;\n\n    // Apply distortion to the normalized points to get (xd, yd).\n    applyRadialDistortionCameraIntrinsics(focal_length_x,\n                                          focal_length_y,\n                                          principal_point_x,\n                                          principal_point_y,\n                                          k1, k2, k3,\n                                          p1, p2,\n                                          xn, yn,\n                                          &predicted_x,\n                                          &predicted_y);\n\n    // The error is the difference between the predicted and observed position.\n    residuals[0] = predicted_x - T(observed_x);\n    residuals[1] = predicted_y - T(observed_y);\n\n    return true;\n  }\n\n  const double observed_x;\n  const double observed_y;\n};\n\n/**\n * Cost functor which computes reprojection error of 3D point X\n * on camera defined by angle-axis rotation and it's translation\n * (which are in the same block due to optimization reasons).\n */\nstruct ReprojectionError {\n  ReprojectionError(const double &_observed_x, const double &_observed_y)\n      : observed_x(_observed_x), observed_y(_observed_y) {}\n\n  template <typename T>\n  bool operator()(const T* const intrinsics,\n                  const T* const R_t,  // Rotation denoted by angle axis\n                                       // followed with translation\n                  const T* const X,    // Point coordinates 3x1.\n                  T* residuals) const {\n    // Unpack the intrinsics.\n    const T& focal_length_x    = intrinsics[0];\n    const T& focal_length_y    = intrinsics[1];\n    const T& principal_point_x = intrinsics[2];\n    const T& principal_point_y = intrinsics[3];\n\n    // Compute projective coordinates: x = RX + t.\n    T x[3];\n\n    ceres::AngleAxisRotatePoint(R_t, X, x);\n    x[0] += R_t[3];\n    x[1] += R_t[4];\n    x[2] += R_t[5];\n\n    // Compute normalized coordinates: x /= x[2].\n    T xn = x[0] / x[2];\n    T yn = x[1] / x[2];\n\n    T predicted_x, predicted_y;\n\n    // Apply distortion to the normalized points to get (xd, yd).\n    applyCameraIntrinsics(focal_length_x, focal_length_y, principal_point_x, principal_point_y,\n                          xn, yn, &predicted_x, &predicted_y);\n\n    // The error is the difference between the predicted and observed position.\n    residuals[0] = predicted_x - T(observed_x);\n    residuals[1] = predicted_y - T(observed_y);\n\n    return true;\n  }\n\n  const double observed_x;\n  const double observed_y;\n};\n\n\n/**\n * This functor uses a radial distortion model.\n */\nstruct RadialDistortionReprojectionAndDepthError {\n  RadialDistortionReprojectionAndDepthError(const double &_observed_x, const double &_observed_y, const double &_inv_depth, const double &_depth_err_weight)\n      : observed_x(_observed_x), observed_y(_observed_y), inv_depth(_inv_depth),\n        depth_err_weight(_depth_err_weight) {}\n\n  template <typename T>\n  bool operator()(const T* const intrinsics,\n                  const T* const R_t,  // Rotation denoted by angle axis\n                                       // followed with translation\n                  const T* const X,    // Point coordinates 3x1.\n                  T* residuals) const {\n    // Unpack the intrinsics.\n    const T& focal_length_x    = intrinsics[0];\n    const T& focal_length_y    = intrinsics[1];\n    const T& principal_point_x = intrinsics[2];\n    const T& principal_point_y = intrinsics[3];\n    const T& k1                = intrinsics[4];\n    const T& k2                = intrinsics[5];\n    const T& k3                = intrinsics[6];\n    const T& p1                = intrinsics[7];\n    const T& p2                = intrinsics[8];\n\n    // Compute projective coordinates: x = RX + t.\n    T x[3];\n\n    ceres::AngleAxisRotatePoint(R_t, X, x);\n    x[0] += R_t[3];\n    x[1] += R_t[4];\n    x[2] += R_t[5];\n\n    // Compute normalized coordinates: x /= x[2].\n    T xn = x[0] / x[2];\n    T yn = x[1] / x[2];\n\n    T predicted_x, predicted_y;\n\n    // Apply distortion to the normalized points to get (xd, yd).\n    applyRadialDistortionCameraIntrinsics(focal_length_x,\n                                          focal_length_y,\n                                          principal_point_x,\n                                          principal_point_y,\n                                          k1, k2, k3,\n                                          p1, p2,\n                                          xn, yn,\n                                          &predicted_x,\n                                          &predicted_y);\n\n    // The error is the difference between the predicted and observed position.\n    residuals[0] = predicted_x - T(observed_x);\n    residuals[1] = predicted_y - T(observed_y);\n    residuals[2] = T(depth_err_weight)*(T(1.)/x[2] - T(inv_depth));\n\n    return true;\n  }\n\n  const double observed_x;\n  const double observed_y;\n  const double inv_depth;\n  const double depth_err_weight;\n};\n\n\n/**\n * Cost functor which computes reprojection and a RGBD-depth error of 3D point X\n * on camera defined by angle-axis rotation and it's translation\n * (which are in the same block due to optimization reasons).\n */\nstruct ReprojectionAndDepthError {\n  ReprojectionAndDepthError(const double &_observed_x, const double &_observed_y, const double &_inv_depth,\n        const double &_depth_err_weight)\n      : observed_x(_observed_x), observed_y(_observed_y), inv_depth(_inv_depth),\n        depth_err_weight(_depth_err_weight) {}\n\n  template <typename T>\n  bool operator()(const T* const intrinsics,\n                  const T* const R_t,  // Rotation denoted by angle axis\n                                       // followed with translation\n                  const T* const X,    // Point coordinates 3x1.\n                  T* residuals) const {\n    // Unpack the intrinsics.\n    const T& focal_length_x    = intrinsics[0];\n    const T& focal_length_y    = intrinsics[1];\n    const T& principal_point_x = intrinsics[2];\n    const T& principal_point_y = intrinsics[3];\n\n    // Compute projective coordinates: x = RX + t.\n    T x[3];\n\n    ceres::AngleAxisRotatePoint(R_t, X, x);\n    x[0] += R_t[3];\n    x[1] += R_t[4];\n    x[2] += R_t[5];\n\n    // Compute normalized coordinates: x /= x[2].\n    T xn = x[0] / x[2];\n    T yn = x[1] / x[2];\n\n    T predicted_x, predicted_y;\n\n    // Apply distortion to the normalized points to get (xd, yd).\n    applyCameraIntrinsics(focal_length_x, focal_length_y, principal_point_x, principal_point_y,\n                          xn, yn, &predicted_x, &predicted_y);\n\n    // The error is the difference between the predicted and observed position.\n    residuals[0] = predicted_x - T(observed_x);\n    residuals[1] = predicted_y - T(observed_y);\n    residuals[2] = T(depth_err_weight)*(T(1.)/x[2] - T(inv_depth));\n\n//    print_values(\"dx,dy,dd: \",residuals[0],residuals[1],residuals[2],T(0));\n\n    return true;\n  }\n\n  const double observed_x;\n  const double observed_y;\n  const double inv_depth;\n  const double depth_err_weight;\n};\n\n\n\n/**\n * Cost functor which computes reprojection and a RGBD-depth error of 3D point X\n * on camera defined by angle-axis rotation and it's translation\n * (which are in the same block due to optimization reasons).\n */\nstruct ReprojectionErrorGlobalPoseCamViewData {\n  ReprojectionErrorGlobalPoseCamViewData(const double &_observed_x, const double &_observed_y)\n      : observed_x(_observed_x), observed_y(_observed_y) {}\n\n  template <typename T>\n  bool operator()(const T* const intrinsics,\n                  const T* const Rt0,   // Rotation denoted by angle axis followed with translation (...to keyframe)\n                  const T* const Rt1,   // ..to proj. frame\n                  const T* const X0,    // Point coordinates 3x1. (in keyframe coordinates)\n                  T* residuals) const {\n    // Unpack the intrinsics.\n    const T& focal_length_x    = intrinsics[0];\n    const T& focal_length_y    = intrinsics[1];\n    const T& principal_point_x = intrinsics[2];\n    const T& principal_point_y = intrinsics[3];\n\n    // transform point to global coordinates\n    T xg[3];\n    T invRt0[6];\n    v4r::invPose6(Rt0, &Rt0[3], invRt0, &invRt0[3]);\n    ceres::AngleAxisRotatePoint(invRt0, X0, xg);\n    xg[0] += invRt0[3];\n    xg[1] += invRt0[4];\n    xg[2] += invRt0[5];\n\n    // Compute projective coordinates: x = RX + t.\n    T x[3];\n\n    ceres::AngleAxisRotatePoint(Rt1, xg, x);\n    x[0] += Rt1[3];\n    x[1] += Rt1[4];\n    x[2] += Rt1[5];\n\n    // Compute normalized coordinates: x /= x[2].\n    T xn = x[0] / x[2];\n    T yn = x[1] / x[2];\n\n    T predicted_x, predicted_y;\n\n    // Apply distortion to the normalized points to get (xd, yd).\n    applyCameraIntrinsics(focal_length_x, focal_length_y, principal_point_x, principal_point_y, xn, yn, &predicted_x, &predicted_y);\n\n    // The error is the difference between the predicted and observed position.\n    residuals[0] = predicted_x - T(observed_x);\n    residuals[1] = predicted_y - T(observed_y);\n\n    //print_values(\"dx,dy,dd: \",residuals[0],residuals[1],residuals[2],T(0));\n\n    return true;\n  }\n\n  const double observed_x;\n  const double observed_y;\n};\n\n/**\n * Cost functor which computes reprojection and a RGBD-depth error of 3D point X\n * on camera defined by angle-axis rotation and it's translation\n * (which are in the same block due to optimization reasons).\n */\nstruct ReprojectionErrorGlobalPoseDeltaPoseCamViewData {\n  ReprojectionErrorGlobalPoseDeltaPoseCamViewData(const double &_observed_x, const double &_observed_y)\n      : observed_x(_observed_x), observed_y(_observed_y) {}\n\n  template <typename T>\n  bool operator()(const T* const intrinsics,\n                  const T* const Rt0,   // Rotation denoted by angle axis followed with translation (...to keyframe)\n                  const T* const Rt1,   // ..to proj. frame\n                  const T* const Rtd,   // ..to proj. frame\n                  const T* const X0,    // Point coordinates 3x1. (in keyframe coordinates)\n                  T* residuals) const {\n\n    // Unpack the intrinsics.\n    const T& focal_length_x    = intrinsics[0];\n    const T& focal_length_y    = intrinsics[1];\n    const T& principal_point_x = intrinsics[2];\n    const T& principal_point_y = intrinsics[3];\n\n    // transform point to cloud pose\n    T xd[3];\n    T invRtd[6];\n    v4r::invPose6(Rtd, &Rtd[3], invRtd, &invRtd[3]);\n    ceres::AngleAxisRotatePoint(invRtd, X0, xd);\n    xd[0] += invRtd[3];\n    xd[1] += invRtd[4];\n    xd[2] += invRtd[5];\n\n    // transform point to global coordinates\n    T xg[3];\n    T invRt0[6];\n    v4r::invPose6(Rt0, &Rt0[3], invRt0, &invRt0[3]);\n    ceres::AngleAxisRotatePoint(invRt0, xd, xg);\n    xd[0] += invRt0[3];\n    xd[1] += invRt0[4];\n    xd[2] += invRt0[5];\n\n    // Compute projective coordinates: x = RX + t.\n    T x[3];\n    ceres::AngleAxisRotatePoint(Rt1, xg, x);\n    x[0] += Rt1[3];\n    x[1] += Rt1[4];\n    x[2] += Rt1[5];\n\n    // Compute projective coordinates: x = RX + t.\n    T xrgb[3];\n    ceres::AngleAxisRotatePoint(Rtd, xg, xrgb);\n    xrgb[0] += Rtd[3];\n    xrgb[1] += Rtd[4];\n    xrgb[2] += Rtd[5];\n\n    // Compute normalized coordinates: x /= x[2].\n    T xn = xrgb[0] / xrgb[2];\n    T yn = xrgb[1] / xrgb[2];\n\n\n    T predicted_x, predicted_y;\n\n    // Apply distortion to the normalized points to get (xd, yd).\n    applyCameraIntrinsics(focal_length_x, focal_length_y, principal_point_x, principal_point_y, xn, yn, &predicted_x, &predicted_y);\n\n    // The error is the difference between the predicted and observed position.\n    residuals[0] = predicted_x - T(observed_x);\n    residuals[1] = predicted_y - T(observed_y);\n\n    //print_values(\"dx,dy,dd: \",residuals[0],residuals[1],residuals[2],T(0));\n\n    return true;\n  }\n\n  const double observed_x;\n  const double observed_y;\n};\n\n\n/**\n * This functor uses a radial distortion model.\n */\nstruct RadialDistortionReprojectionErrorGlobalPoseCamViewData {\n  RadialDistortionReprojectionErrorGlobalPoseCamViewData(const double &_observed_x, const double &_observed_y)\n      : observed_x(_observed_x), observed_y(_observed_y) {}\n\n  template <typename T>\n  bool operator()(const T* const intrinsics,\n                  const T* const Rt0,   // Rotation denoted by angle axis followed with translation (...to keyframe)\n                  const T* const Rt1,   // ..to proj. frame\n                  const T* const X0,    // Point coordinates 3x1.\n                  T* residuals) const {\n    // Unpack the intrinsics.\n    const T& focal_length_x    = intrinsics[0];\n    const T& focal_length_y    = intrinsics[1];\n    const T& principal_point_x = intrinsics[2];\n    const T& principal_point_y = intrinsics[3];\n    const T& k1                = intrinsics[4];\n    const T& k2                = intrinsics[5];\n    const T& k3                = intrinsics[6];\n    const T& p1                = intrinsics[7];\n    const T& p2                = intrinsics[8];\n\n    // transform point to global coordinates\n    T xg[3];\n    T invRt0[6];\n    v4r::invPose6(Rt0, &Rt0[3], invRt0, &invRt0[3]);\n    ceres::AngleAxisRotatePoint(invRt0, X0, xg);\n    xg[0] += invRt0[3];\n    xg[1] += invRt0[4];\n    xg[2] += invRt0[5];\n\n    // Compute projective coordinates: x = RX + t.\n    T x[3];\n\n    ceres::AngleAxisRotatePoint(Rt1, xg, x);\n    x[0] += Rt1[3];\n    x[1] += Rt1[4];\n    x[2] += Rt1[5];\n\n    // Compute normalized coordinates: x /= x[2].\n    T xn = x[0] / x[2];\n    T yn = x[1] / x[2];\n\n    T predicted_x, predicted_y;\n\n    // Apply distortion to the normalized points to get (xd, yd).\n    applyRadialDistortionCameraIntrinsics(focal_length_x, focal_length_y, principal_point_x, principal_point_y, k1, k2, k3, p1, p2, xn, yn, &predicted_x, &predicted_y);\n\n    // The error is the difference between the predicted and observed position.\n    residuals[0] = predicted_x - T(observed_x);\n    residuals[1] = predicted_y - T(observed_y);\n\n    return true;\n  }\n\n  const double observed_x;\n  const double observed_y;\n};\n\n/**\n * This functor uses a radial distortion model.\n */\nstruct RadialDistortionReprojectionErrorGlobalPoseDeltaPoseCamViewData {\n  RadialDistortionReprojectionErrorGlobalPoseDeltaPoseCamViewData(const double &_observed_x, const double &_observed_y)\n      : observed_x(_observed_x), observed_y(_observed_y) {}\n\n  template <typename T>\n  bool operator()(const T* const intrinsics,\n                  const T* const Rt0,   // Rotation denoted by angle axis followed with translation (...to keyframe)\n                  const T* const Rt1,   // ..to proj. frame\n                  const T* const Rtd,   // ..cloud->RGB delta pose\n                  const T* const X0,    // Point coordinates 3x1.\n                  T* residuals) const {\n    // Unpack the intrinsics.\n    const T& focal_length_x    = intrinsics[0];\n    const T& focal_length_y    = intrinsics[1];\n    const T& principal_point_x = intrinsics[2];\n    const T& principal_point_y = intrinsics[3];\n    const T& k1                = intrinsics[4];\n    const T& k2                = intrinsics[5];\n    const T& k3                = intrinsics[6];\n    const T& p1                = intrinsics[7];\n    const T& p2                = intrinsics[8];\n\n    // transform point to cloud pose\n    T xd[3];\n    T invRtd[6];\n    v4r::invPose6(Rtd, &Rtd[3], invRtd, &invRtd[3]);\n    ceres::AngleAxisRotatePoint(invRtd, X0, xd);\n    xd[0] += invRtd[3];\n    xd[1] += invRtd[4];\n    xd[2] += invRtd[5];\n\n    // transform point to global coordinates\n    T xg[3];\n    T invRt0[6];\n    v4r::invPose6(Rt0, &Rt0[3], invRt0, &invRt0[3]);\n    ceres::AngleAxisRotatePoint(invRt0, xd, xg);\n    xg[0] += invRt0[3];\n    xg[1] += invRt0[4];\n    xg[2] += invRt0[5];\n\n    // Compute projective coordinates: x = RX + t.\n    T x[3];\n    ceres::AngleAxisRotatePoint(Rt1, xg, x);\n    x[0] += Rt1[3];\n    x[1] += Rt1[4];\n    x[2] += Rt1[5];\n\n    // Compute projective coordinates: x = RX + t.\n    T xrgb[3];\n    ceres::AngleAxisRotatePoint(Rtd, x, xrgb);\n    xrgb[0] += Rtd[3];\n    xrgb[1] += Rtd[4];\n    xrgb[2] += Rtd[5];\n\n    // Compute normalized coordinates: x /= x[2].\n    T xn = xrgb[0] / xrgb[2];\n    T yn = xrgb[1] / xrgb[2];\n\n    T predicted_x, predicted_y;\n\n    // Apply distortion to the normalized points to get (xd, yd).\n    applyRadialDistortionCameraIntrinsics(focal_length_x, focal_length_y, principal_point_x, principal_point_y, k1, k2, k3, p1, p2, xn, yn, &predicted_x, &predicted_y);\n\n    // The error is the difference between the predicted and observed position.\n    residuals[0] = predicted_x - T(observed_x);\n    residuals[1] = predicted_y - T(observed_y);\n\n    return true;\n  }\n\n  const double observed_x;\n  const double observed_y;\n};\n\n\n/**\n * This functor uses a point to plane error model\n */\nstruct PointToPlaneErrorGlobalPoseCamViewData {\n  PointToPlaneErrorGlobalPoseCamViewData(const Eigen::Vector3d &_pt0, const Eigen::Vector3d &_n0, const  Eigen::Vector3d &_pt1, const double &_w)\n      : pt0(_pt0), n0(_n0), pt1(_pt1), error_weight(_w) {}\n\n  template <typename T>\n  bool operator()(const T* const Rt0,   // Rotation denoted by angle axis followed with translation (...to keyframe)\n                  const T* const Rt1,   // ..to proj. frame\n                  T* residuals) const {\n\n    Eigen::Matrix<T,3,1> pt0e, n0e, pt0g, n0g, pt1t, n1t, pt1e;\n\n    pt0e[0] = T(pt0[0]);\n    pt0e[1] = T(pt0[1]);\n    pt0e[2] = T(pt0[2]);\n    n0e[0] = T(n0[0]);\n    n0e[1] = T(n0[1]);\n    n0e[2] = T(n0[2]);\n    pt1e[0] = T(pt1[0]);\n    pt1e[1] = T(pt1[1]);\n    pt1e[2] = T(pt1[2]);\n\n    // transform point to global coordinates\n    T invRt0[6];\n    v4r::invPose6(Rt0, &Rt0[3], invRt0, &invRt0[3]);\n    ceres::AngleAxisRotatePoint(invRt0, &n0e[0], &n0g[0]);\n    ceres::AngleAxisRotatePoint(invRt0, &pt0e[0], &pt0g[0]);\n    pt0g[0] += invRt0[3];\n    pt0g[1] += invRt0[4];\n    pt0g[2] += invRt0[5];\n\n    // transform to view 1: x = RX + t.\n    ceres::AngleAxisRotatePoint(Rt1, &n0g[0], &n1t[0]);\n    ceres::AngleAxisRotatePoint(Rt1, &pt0g[0], &pt1t[0]);\n    pt1t[0] += Rt1[3];\n    pt1t[1] += Rt1[4];\n    pt1t[2] += Rt1[5];\n\n    // compute the point to plane distance\n    //residuals[0] = T(error_weight) * /*(T(2.)/(pt1e[2]+pt1t[2])) **/ (pt1e-pt1t).dot(n1t);\n    T weight = T(error_weight) * (T(2.)/(v4r::sqr(pt1e[2])+v4r::sqr(pt1t[2])));\n    Eigen::Matrix<T,3,1> diff;\n    diff = pt1e-pt1t;\n    residuals[0] = weight * diff[0]*n1t[0];\n    residuals[1] = weight * diff[1]*n1t[1];\n    residuals[2] = weight * diff[2]*n1t[2];\n\n    return true;\n  }\n\n  const Eigen::Vector3d pt0;\n  const Eigen::Vector3d n0;\n  const Eigen::Vector3d pt1;\n  const double error_weight;\n};\n\n/**\n * This functor uses a point to plane error model\n */\nstruct PointToPlaneErrorGlobalPoseCamViewDataOptiPt1 {\n  PointToPlaneErrorGlobalPoseCamViewDataOptiPt1(const Eigen::Vector3d &_pt0, const Eigen::Vector3d &_n0, const double &_w)\n      : pt0(_pt0), n0(_n0), error_weight(_w) {}\n\n  template <typename T>\n  bool operator()(const T* const Rt0,   // Rotation denoted by angle axis followed with translation (...to keyframe)\n                  const T* const Rt1,   // ..to proj. frame\n                  const T* const X1,\n                  T* residuals) const {\n\n    Eigen::Matrix<T,3,1> pt0e, n0e, pt0g, n0g, pt1t, n1t, pt1e;\n\n    pt0e[0] = T(pt0[0]);\n    pt0e[1] = T(pt0[1]);\n    pt0e[2] = T(pt0[2]);\n    n0e[0] = T(n0[0]);\n    n0e[1] = T(n0[1]);\n    n0e[2] = T(n0[2]);\n    pt1e[0] = X1[0];\n    pt1e[1] = X1[1];\n    pt1e[2] = X1[2];\n\n    // transform point to global coordinates\n    T invRt0[6];\n    v4r::invPose6(Rt0, &Rt0[3], invRt0, &invRt0[3]);\n    ceres::AngleAxisRotatePoint(invRt0, &n0e[0], &n0g[0]);\n    ceres::AngleAxisRotatePoint(invRt0, &pt0e[0], &pt0g[0]);\n    pt0g[0] += invRt0[3];\n    pt0g[1] += invRt0[4];\n    pt0g[2] += invRt0[5];\n\n    // transform to view 1: x = RX + t.\n    ceres::AngleAxisRotatePoint(Rt1, &n0g[0], &n1t[0]);\n    ceres::AngleAxisRotatePoint(Rt1, &pt0g[0], &pt1t[0]);\n    pt1t[0] += Rt1[3];\n    pt1t[1] += Rt1[4];\n    pt1t[2] += Rt1[5];\n\n    // compute the point to plane distance\n    //residuals[0] = T(error_weight) * /*(T(2.)/(pt1e[2]+pt1t[2])) **/ (pt1e-pt1t).dot(n1t);\n    T weight = T(error_weight) * (T(2.)/(v4r::sqr(pt1e[2])+v4r::sqr(pt1t[2])));\n    Eigen::Matrix<T,3,1> diff;\n    diff = pt1e-pt1t;\n    residuals[0] = weight * diff[0]*n1t[0];\n    residuals[1] = weight * diff[1]*n1t[1];\n    residuals[2] = weight * diff[2]*n1t[2];\n\n\n    return true;\n  }\n\n  const Eigen::Vector3d pt0;\n  const Eigen::Vector3d n0;\n  const double error_weight;\n};\n\n/**\n * This functor uses a point to plane error model\n */\nstruct PointToPlaneErrorGlobalPoseDeltaPoseCamViewDataOptiPt1 {\n  PointToPlaneErrorGlobalPoseDeltaPoseCamViewDataOptiPt1(const Eigen::Vector3d &_pt0, const Eigen::Vector3d &_n0, const double &_w)\n      : pt0(_pt0), n0(_n0), error_weight(_w) {}\n\n  template <typename T>\n  bool operator()(const T* const Rtd,   // ..to rgb. frame\n                  const T* const X1,\n                  T* residuals) const {\n\n    Eigen::Matrix<T,3,1> pt0e, n0e, pt1t, n1t, pt1e;\n\n    pt0e[0] = T(pt0[0]);\n    pt0e[1] = T(pt0[1]);\n    pt0e[2] = T(pt0[2]);\n    n0e[0] = T(n0[0]);\n    n0e[1] = T(n0[1]);\n    n0e[2] = T(n0[2]);\n    pt1e[0] = X1[0];\n    pt1e[1] = X1[1];\n    pt1e[2] = X1[2];\n\n    // transform to view 1: x = RX + t.\n    ceres::AngleAxisRotatePoint(Rtd, &n0e[0], &n1t[0]);\n    ceres::AngleAxisRotatePoint(Rtd, &pt0e[0], &pt1t[0]);\n    pt1t[0] += Rtd[3];\n    pt1t[1] += Rtd[4];\n    pt1t[2] += Rtd[5];\n\n    // compute the point to plane distance\n    //residuals[0] = T(error_weight) * /*(T(2.)/(pt1e[2]+pt1t[2])) **/ (pt1e-pt1t).dot(n1t);\n    T weight = T(error_weight) * (T(2.)/(v4r::sqr(pt1e[2])+v4r::sqr(pt1t[2])));\n    Eigen::Matrix<T,3,1> diff;\n    diff = pt1e-pt1t;\n    residuals[0] = weight * diff[0]*n1t[0];\n    residuals[1] = weight * diff[1]*n1t[1];\n    residuals[2] = weight * diff[2]*n1t[2];\n\n\n    return true;\n  }\n\n  const Eigen::Vector3d pt0;\n  const Eigen::Vector3d n0;\n  const double error_weight;\n};\n\n\n}\n\n\n#endif\n\n\n\n\n\n\n\n\n\n\n", "meta": {"hexsha": "e1fed9f5cb5f6f825d5f8e7b724a284f57888c51", "size": 27572, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/camera_tracking_and_mapping/include/v4r/camera_tracking_and_mapping/BACostFunctions.hpp", "max_stars_repo_name": "ToMadoRe/v4r", "max_stars_repo_head_hexsha": "7cb817e05cb9d99cb2f68db009c27d7144d07f09", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 17.0, "max_stars_repo_stars_event_min_datetime": "2015-11-16T14:21:10.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-09T02:57:33.000Z", "max_issues_repo_path": "modules/camera_tracking_and_mapping/include/v4r/camera_tracking_and_mapping/BACostFunctions.hpp", "max_issues_repo_name": "ToMadoRe/v4r", "max_issues_repo_head_hexsha": "7cb817e05cb9d99cb2f68db009c27d7144d07f09", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 35.0, "max_issues_repo_issues_event_min_datetime": "2015-07-27T15:04:43.000Z", "max_issues_repo_issues_event_max_datetime": "2019-08-22T10:52:35.000Z", "max_forks_repo_path": "modules/camera_tracking_and_mapping/include/v4r/camera_tracking_and_mapping/BACostFunctions.hpp", "max_forks_repo_name": "ToMadoRe/v4r", "max_forks_repo_head_hexsha": "7cb817e05cb9d99cb2f68db009c27d7144d07f09", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 18.0, "max_forks_repo_forks_event_min_datetime": "2015-08-06T09:26:27.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-03T01:31:00.000Z", "avg_line_length": 34.1237623762, "max_line_length": 168, "alphanum_fraction": 0.5944436385, "num_tokens": 8142, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.5774953651858117, "lm_q1q2_score": 0.309016862450079}}
{"text": "/*\n This program is free software; you can redistribute it and/or modify it under\n the terms of the European Union Public Licence - EUPL v.1.1 as published by\n the European Commission.\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 European Union Public Licence - EUPL v.1.1\n for more details.\n\n You should have received a copy of the European Union Public Licence - EUPL v.1.1\n along with this program.\n\n Further information about the European Union Public Licence - EUPL v.1.1 can\n also be found on the world wide web at http://ec.europa.eu/idabc/eupl\n\n*/\n\n/*\n ------ Copyright (C) 2010 STA Steering Board (space.trajectory.analysis AT gmail.com) ----\n*/\n\n\n/*\n ------------------ Author: Chris Laurel  -------------------------------------------------\n ------------------ E-mail: (claurel@gmail.com) ----------------------------\n\n Based on code by Chris Laurel from Celestia (http://www.shatters.net/celestia)\n */\n\n#include <Eigen/Core>\n//#include \"Eigen/src/Core/Map.h\"\n#include <QtCore>\n#include <QDataStream>\n#include <QIODevice>\n#include \"date.h\"\n#include \"jplephemeris.h\"\n\n\n\nusing namespace Eigen;\nusing namespace std;\n\ntypedef Eigen::Matrix< double, 3, 3 > \tMyMatrix3d;\ntypedef Eigen::Matrix< double, 3, 1 > \tMyVector3d;\n\nstatic const unsigned int DE200RecordSize    =  826;\nstatic const unsigned int DE405RecordSize    = 1018;\nstatic const unsigned int DE406RecordSize    =  728;\n\nstatic const unsigned int NConstants         =  400;\nstatic const unsigned int ConstantNameLength =  6;\n\nstatic const unsigned int MaxChebyshevCoeffs = 32;\n\nstatic const int LabelSize = 84;\n\n\nsta::JPLEphemeris::JPLEphemeris()\n{\n}\n\n\nsta::JPLEphemeris::~JPLEphemeris()\n{\n}\n\n\nunsigned int\nsta::JPLEphemeris::getDENumber() const\n{\n    return DENum;\n}\n\ndouble\nsta::JPLEphemeris::getStartDate() const\n{\n    return startDate;\n}\n\ndouble\nsta::JPLEphemeris::getEndDate() const\n{\n    return endDate;\n}\n\nsta::Ephemeris::TimeInterval\nsta::JPLEphemeris::validTimeInterval(const StaBody* /* body */) const\n{\n    return TimeInterval(sta::JdToMjd(startDate), sta::JdToMjd(endDate));\n}\n\n// Internal method to map an STA body id to a JPL ephemeris item\nsta::JPLEphemItem\nsta::JPLEphemeris::mapStaId(StaBodyId id) const\n{\n    switch (id)\n    {\n    case STA_SOLAR_SYSTEM_BARYCENTER:\n        return JPLEph_SSB;\n    case STA_EARTH_BARYCENTER:\n        return JPLEph_EarthMoonBary;\n    case STA_MERCURY:\n        return JPLEph_Mercury;\n    case STA_VENUS:\n        return JPLEph_Venus;\n    case STA_EARTH:\n        return JPLEph_Earth;\n    case STA_MARS:\n        return JPLEph_Mars;\n    case STA_JUPITER:\n        return JPLEph_Jupiter;\n    case STA_SATURN:\n        return JPLEph_Saturn;\n    case STA_URANUS:\n        return JPLEph_Uranus;\n    case STA_NEPTUNE:\n        return JPLEph_Neptune;\n    case STA_PLUTO:\n        return JPLEph_Pluto;\n    case STA_SUN:\n        return JPLEph_Sun;\n    case STA_MOON:\n        return JPLEph_Moon;\n    default:\n        return JPLEph_Invalid;\n    }\n}\n\n\nconst QList<StaBodyId>&\nsta::JPLEphemeris::bodyList() const\n{\n    return m_bodies;\n}\n\n\nconst StaBody*\nsta::JPLEphemeris::parentBody(const StaBody* body) const\n{\n    JPLEphemItem id = mapStaId(body->id());\n    if (id == JPLEph_Invalid)\n    {\n        return NULL;\n    }\n    else\n    {\n        if (id == JPLEph_SSB)\n            return NULL;\n        else if (id == JPLEph_Moon || id == JPLEph_Earth)\n            return STA_SOLAR_SYSTEM->lookup(STA_EARTH_BARYCENTER);\n        else\n            return STA_SOLAR_SYSTEM->lookup(STA_SOLAR_SYSTEM_BARYCENTER);\n    }\n}\n\n\nconst sta::CoordinateSystemType\nsta::JPLEphemeris::coordinateSystem(const StaBody* /* body */) const\n{\n    return sta::COORDSYS_EME_J2000;\n}\n\n\nsta::StateVector\nsta::JPLEphemeris::stateVector(const StaBody* body,\n                               double mjd,\n                               const StaBody* center,\n                               sta::CoordinateSystemType coordSys) const\n{\n    JPLEphemItem id = mapStaId(body->id());\n    if (id == JPLEph_Invalid || body == center)\n    {\n        return StateVector::zero();\n    }\n\n    StateVector state = getPlanetStateVector(id, MjdToJd(mjd));\n    const StaBody* parent = parentBody(body);\n\n    // If the parent object in the ephemeris is the same as the center, then no\n    // extra work is necessary. Otherwise, we also need compute the position of\n    // the parent with respect to the center.\n    if (parent == center)\n    {\n        return state;\n    }\n    else\n    {\n        const StaBody* ssb = STA_SOLAR_SYSTEM->lookup(STA_SOLAR_SYSTEM_BARYCENTER);\n        StateVector parentState = parent->stateVector(mjd, ssb, coordSys);\n        StateVector centerState = center->stateVector(mjd, ssb, coordSys);\n\n        return StateVector(parentState.position - centerState.position + state.position,\n                           parentState.velocity - centerState.velocity + state.velocity);\n    }\n}\n\n// Return the position of an object relative to the solar system barycenter\n// or the Earth (in the case of the Moon) at a specified TDB Julian date tjd.\n// If tjd is outside the span covered by the ephemeris it is clamped to a\n// valid time.\nsta::StateVector\nsta::JPLEphemeris::getPlanetStateVector(JPLEphemItem planet, double tjd) const\n{\n    // Solar system barycenter is the origin\n    if (planet == JPLEph_SSB)\n    {\n        return StateVector(MyVector3d(0.0, 0.0, 0.0), MyVector3d(0.0, 0.0, 0.0));\n    }\n\n    // The position of the Earth must be computed from the positions of the\n    // Earth-Moon barycenter and Moon. This is handled automatically because\n    // Earth's 'parent' in the ephemeris is the Earth-Moon barycenter.\n    if (planet == JPLEph_Earth)\n    {\n        // Get the geocentric position of the Moon\n        sta::StateVector moonState = getPlanetStateVector(JPLEph_Moon, tjd);\n\n        double f = 1.0 / (earthMoonMassRatio + 1.0);\n        return StateVector(-moonState.position * f, -moonState.velocity * f);\n    }\n\n    // Clamp time to [ startDate, endDate ]\n    if (tjd < startDate)\n    {\n        tjd = startDate;\n    }\n    else if (tjd > endDate)\n    {\n        tjd = endDate;\n    }\n\n    // recordIndex is always >= 0:\n    unsigned int recordIndex = (unsigned int) ((tjd - startDate) / daysPerInterval);\n    // Make sure we don't go past the end of the array if t == endDate\n    if (recordIndex >= records.size())\n    {\n        recordIndex = records.size() - 1;\n    }\n    const JPLEphRecord& record = records[recordIndex];\n\n    Q_ASSERT(coeffInfo[planet].nGranules >= 1);\n    Q_ASSERT(coeffInfo[planet].nGranules <= 32);\n    Q_ASSERT(coeffInfo[planet].nCoeffs <= MaxChebyshevCoeffs);\n\n    // u is the normalized time (in [-1, 1]) for interpolating\n    // coeffs is a pointer to the Chebyshev coefficients\n    double u = 0.0;\n    const double* coeffs = NULL;\n    unsigned int nCoeffs = coeffInfo[planet].nCoeffs;\n    double velocityScale = 1.0;\n\n    if (coeffInfo[planet].nGranules == 0xffffffff)\n    {\n        coeffs = record.coeffs + coeffInfo[planet].offset;\n        u = 2.0 * (tjd - record.t0) / daysPerInterval - 1.0;\n        velocityScale = 2.0 / daysPerInterval;\n    }\n    else\n    {\n        // This interval is subdivided into shorter subintervals (called granules)\n        // Adjust the coefficient pointer accordingly.\n        double daysPerGranule = daysPerInterval / coeffInfo[planet].nGranules;\n        int granule = (int) ((tjd - record.t0) / daysPerGranule);\n        double granuleStartDate = record.t0 + daysPerGranule * (double) granule;\n        coeffs = record.coeffs + coeffInfo[planet].offset +\n                 granule * coeffInfo[planet].nCoeffs * 3;\n        u = 2.0 * (tjd - granuleStartDate) / daysPerGranule - 1.0;\n        velocityScale = 2.0 / daysPerGranule;\n    }\n\n    // Calculate the Chebyshev polynomial terms and their derivatives\n    //Matrix<double, MaxChebyshevCoeffs, 1> positionTerms;\n    double positionTerms[MaxChebyshevCoeffs];\n    positionTerms[0] = 1.0;\n    positionTerms[1] = u;\n\n    //Matrix<double, MaxChebyshevCoeffs, 1> velocityTerms;\n    double velocityTerms[MaxChebyshevCoeffs];\n    velocityTerms[0] = 0.0;\n    velocityTerms[1] = 1.0;\n    for (unsigned int i = 2; i < nCoeffs; i++)\n    {\n        positionTerms[i] = 2.0 * u * positionTerms[i - 1] - positionTerms[i - 2];\n        velocityTerms[i] = 2.0 * u * velocityTerms[i - 1] - velocityTerms[i - 2] + 2.0 * positionTerms[i - 1];\n    }\n\n    // Note that Eigen uses column-major storage, so we need to transpose the coefficient\n    // matrix.\n    MyVector3d position = Map<MatrixXd>(coeffs, nCoeffs, 3).transpose() * Map<MatrixXd>(positionTerms, nCoeffs, 1);\n    MyVector3d velocity = Map<MatrixXd>(coeffs, nCoeffs, 3).transpose() * Map<MatrixXd>(velocityTerms, nCoeffs, 1);\n\n    return StateVector(position, velocity * (velocityScale / 86400.0));\n}\n\n\nsta::JPLEphemeris*\nsta::JPLEphemeris::load(QIODevice* device)\n{\n    QDataStream in(device);\n    in.setByteOrder(QDataStream::BigEndian);\n\n    JPLEphemeris* eph = NULL;\n\n    // Skip past three header labels\n    in.skipRawData(LabelSize * 3);\n    if (in.status() != QDataStream::Ok)\n        return NULL;\n\n    // Skip past the constant names\n    in.skipRawData(NConstants * ConstantNameLength);\n    if (in.status() != QDataStream::Ok)\n        return NULL;\n\n    eph = new JPLEphemeris();\n    if (eph == NULL)\n        return NULL;\n\n    // Read the start time, end time, and time interval\n    in >> eph->startDate;\n    in >> eph->endDate;\n    in >> eph->daysPerInterval;\n    if (in.status() != QDataStream::Ok)\n    {\n        delete eph;\n        return NULL;\n    }\n\n    // Number of constants with valid values; not useful for us\n    quint32 nConstants;\n    in >> nConstants;\n\n    in >> eph->au;     // kilometers per astronomical unit\n    in >> eph->earthMoonMassRatio;\n\n    // Read the coefficient information for each item in the ephemeris\n    for (unsigned int i = 0; i < JPLEph_NItems; i++)\n    {\n        in >> eph->coeffInfo[i].offset;\n        in >> eph->coeffInfo[i].nCoeffs;\n        in >> eph->coeffInfo[i].nGranules;\n\n        eph->coeffInfo[i].offset -= 3;\n    }\n\n    if (in.status() != QDataStream::Ok)\n    {\n        delete eph;\n        return NULL;\n    }\n\n    in >> eph->DENum;\n\n    switch (eph->DENum)\n    {\n    case 200:\n        eph->recordSize = DE200RecordSize;\n        break;\n    case 405:\n        eph->recordSize = DE405RecordSize;\n        break;\n    case 406:\n        eph->recordSize = DE406RecordSize;\n        break;\n    default:\n        delete eph;\n        return NULL;\n    }\n\n    in >> eph->librationCoeffInfo.offset;\n    in >> eph->librationCoeffInfo.nCoeffs;\n    in >> eph->librationCoeffInfo.nGranules;\n    if (in.status() != QDataStream::Ok)\n    {\n        delete eph;\n        return NULL;\n    }\n\n    // Skip past the rest of the record\n    in.skipRawData(eph->recordSize * 8 - 2856);\n    // The next record contains constant values (which we don't need)\n    in.skipRawData(eph->recordSize * 8);\n    if (in.status() != QDataStream::Ok)\n    {\n        delete eph;\n        return NULL;\n    }\n\n    unsigned int nRecords = (unsigned int) ((eph->endDate - eph->startDate) / eph->daysPerInterval);\n    eph->records.resize(nRecords);\n\n    for (unsigned int i = 0; i < nRecords; i++)\n    {\n        in >> eph->records[i].t0;\n        in >> eph->records[i].t1;\n\n    \t// Allocate coefficient array for this record; the first two\n    \t// 'coefficients' are actually the start and end time (t0 and t1)\n        eph->records[i].coeffs = new double[eph->recordSize - 2];\n        for (unsigned int j = 0; j < eph->recordSize - 2; j++)\n        {\n            in >> eph->records[i].coeffs[j];\n        }\n\n    \t// Make sure that we read this record successfully\n        if (in.status() != QDataStream::Ok)\n    \t{\n    \t    delete eph;\n    \t    return NULL;\n    \t}\n    }\n\n    eph->m_bodies << STA_SUN << STA_MERCURY << STA_VENUS << STA_EARTH << STA_MARS\n                  << STA_JUPITER << STA_SATURN << STA_URANUS << STA_NEPTUNE << STA_PLUTO\n                  << STA_EARTH_BARYCENTER << STA_MOON;\n\n    return eph;\n}\n", "meta": {"hexsha": "73801c9f60ca38b0cf55d5d3e5e84b671d1e72a5", "size": 12077, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "sta-src/Astro-Core/jplephemeris.cpp", "max_stars_repo_name": "hoehnp/SpaceDesignTool", "max_stars_repo_head_hexsha": "9abd34048274b2ce9dbbb685124177b02d6a34ca", "max_stars_repo_licenses": ["IJG"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2018-09-05T12:41:59.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-01T05:34:23.000Z", "max_issues_repo_path": "sta-src/Astro-Core/jplephemeris.cpp", "max_issues_repo_name": "hoehnp/SpaceDesignTool", "max_issues_repo_head_hexsha": "9abd34048274b2ce9dbbb685124177b02d6a34ca", "max_issues_repo_licenses": ["IJG"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2015-02-07T19:09:21.000Z", "max_issues_repo_issues_event_max_datetime": "2015-08-14T03:15:42.000Z", "max_forks_repo_path": "sta-src/Astro-Core/jplephemeris.cpp", "max_forks_repo_name": "hoehnp/SpaceDesignTool", "max_forks_repo_head_hexsha": "9abd34048274b2ce9dbbb685124177b02d6a34ca", "max_forks_repo_licenses": ["IJG"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2015-03-25T15:50:31.000Z", "max_forks_repo_forks_event_max_datetime": "2017-12-06T12:16:47.000Z", "avg_line_length": 28.8233890215, "max_line_length": 115, "alphanum_fraction": 0.6377411609, "num_tokens": 3363, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6757645879592642, "lm_q2_score": 0.4571367168274948, "lm_q1q2_score": 0.30891680508798286}}
{"text": "#include <ciphey/freq.hpp>\n\n#include <boost/math/special_functions/gamma.hpp>\n\n#include <future>\n#include <optional>\n#include <random>\n#include <set>\n#include <thread>\n\nnamespace ciphey {\n  static void merge_last(assoc_table& assoc) {\n    // Take the last two elements\n    auto to_merge = std::move(assoc.back());\n    assoc.pop_back();\n    auto target = assoc.back();\n    assoc.pop_back();\n\n    // Combine them\n    target.expected += to_merge.expected;\n    target.observed += to_merge.observed;\n\n    // Insert them into the correct position\n    auto new_pos = std::partition_point(assoc.begin(), assoc.end(),\n                                        [&](auto& a) { return a.expected > target.expected; });\n    assoc.insert(new_pos, std::move(target));\n\n  }\n\n  void prepare_chisq(assoc_table& assoc, freq_t count) {\n    // IIRC copying is much, MUCH faster than mallocing, so a list would be slower in this case\n    //\n    // Benchmarks seem to confirm this\n\n    // If there's nothing we can do, give up\n    if (count < 10)\n      return;\n\n    std::sort(assoc.begin(), assoc.end(), [](auto& a, auto& b) { return a.expected > b.expected; });\n\n    // We now perform a *really* simple bin packing to make sure that no expected frequency is lower that 1\n    auto exp_1_target = 1. / count;\n\n    while (assoc.size() >= 2 && assoc.back().expected < exp_1_target)\n      merge_last(assoc);\n\n\n    auto exp_5_target = 5. / count;\n    if (exp_5_target > 0.2)\n      return;\n    while (assoc.size() >= 2) {\n      auto upper_bound = std::partition_point(assoc.begin(), assoc.end(),\n                                              [&](auto& a) { return a.expected > exp_5_target; });\n      auto n_less_than_fifth = assoc.end() - upper_bound;\n      if (n_less_than_fifth <= assoc.size() / 5.)\n        break;\n      merge_last(assoc);\n    }\n  }\n\n  float_t run_chisq(const assoc_table& assoc, freq_t count) {\n    float_t chisq = 0;\n\n    for (auto const& elem : assoc) {\n      if (elem.expected == 0 && elem.observed != 0)\n        return std::numeric_limits<float_t>::infinity();\n\n      float_t contrib = elem.expected - elem.observed;\n      contrib *= contrib;\n      contrib /= elem.expected;\n\n      chisq += contrib;\n    }\n\n    // (f_e/n - f_o/n)^2/(f_e/n) = (1/n) (f_e - f_o)/(f_e)\n    //\n    // We need to normalise this for our stat to be interpretable\n    chisq *= count;\n    return chisq;\n  }\n\n  float_t run_g(const assoc_table& assoc, freq_t count) {\n    float_t g = 0;\n\n    for (auto const& elem : assoc) {\n      if (elem.observed == 0)\n        continue;\n\n      if (elem.expected == 0)\n        return std::numeric_limits<float_t>::infinity();\n\n      float_t contrib = ::log(elem.observed / elem.expected); // `count` cancels out here\n      contrib *= elem.observed;\n\n      g += contrib;\n    }\n\n    // (f_e/n - f_o/n)^2/(f_e/n) = (1/n) (f_e - f_o)/(f_e)\n    //\n    // We need to normalise this for our stat to be interpretable\n    g *= 2 * count;\n    return g;\n  }\n\n  prob_t chisq_cdf(freq_t dof, float_t up_to) {\n    // Handle the asymptopic value first, to save time\n    if (up_to == std::numeric_limits<float_t>::infinity())\n      return 1;\n    else if (up_to == 0)\n      return 0;\n    else if (dof == 0) // https://en.wikipedia.org/wiki/Zero_degrees_of_freedom\n      return 0;\n    return boost::math::gamma_p(static_cast<float>(dof) / 2, up_to / 2);\n  }\n\n  prob_t gof_test(assoc_table assoc, freq_t count) {\n//    prepare_chisq(assoc, count);\n    auto stat = run_g(assoc, count);\n    // We want the upper tail\n    auto p_value = 1 - chisq_cdf(assoc.size() - 1, stat);\n\n    return p_value;\n//    return std::max(p_value, orig_p_value);\n  }\n\n  assoc_table create_assoc_table(prob_table const& observed, prob_table const& expected) {\n    // TODO: optimise\n    //\n    // First, let's get all the keys\n    struct key_elem {\n      std::optional<float_t> obs_val, exp_val;\n    };\n\n    std::map<char_t, key_elem> keys;\n    // We can use index notation for this, as that gets default constructed\n    for (auto& i : expected)\n      keys[i.first].exp_val = i.second;\n    for (auto& i : observed) {\n      if (i.second == 0.)\n        continue;\n      keys[i.first].obs_val = i.second;\n    }\n\n    // We can now fill in all the values, with non-existent expected values being defined as zero\n    assoc_table ret;\n//    ret.reserve(keys.size());\n\n    for (auto& i : keys)\n      ret.emplace_back(assoc_table_elem{\n        .observed = i.second.obs_val.value_or(0),\n        .expected = i.second.exp_val.value_or(0)});\n\n    return ret;\n  }\n\n  prob_table freq_conv(freq_table const& freqs, freq_t total_len) {\n    prob_table ret;\n    for (auto& i : freqs)\n      ret[i.first] = static_cast<prob_t>(i.second) / total_len;\n    return ret;\n  }\n  prob_table freq_conv(freq_table const& freqs) {\n    freq_t total_len = 0;\n    for (auto& i : freqs)\n      total_len += i.second;\n    return freq_conv(freqs, total_len);\n  }\n  windowed_prob_table freq_conv(windowed_freq_table& freqs, freq_t total_len) {\n    windowed_prob_table ret;\n    ret.reserve(total_len);\n    for (auto& i : freqs)\n      // TODO: work the length out here, rather than do slow counting\n      ret.emplace_back(freq_conv(i));\n    return ret;\n  }\n  windowed_prob_table freq_conv(windowed_freq_table& freqs) {\n    freq_t total_len = 0;\n    for (auto& i : freqs)\n      for (auto& entry: i)\n        total_len += entry.second;\n    return freq_conv(freqs, total_len);\n  }\n\n  size_t filter_missing(freq_table& target, prob_table const& lookup) {\n    std::vector<char_t> to_remove;\n    size_t ret = 0;\n    for (auto& i : target) {\n      if (auto iter = lookup.find(i.first); iter == lookup.end() || iter->second == 0) {\n        to_remove.push_back(i.first);\n        ret += i.second;\n      }\n    }\n\n    for (auto i : to_remove)\n      target.erase(i);\n\n    return ret;\n  }\n\n  size_t filter_missing(freq_table& target, domain_t const& tab) {\n    std::vector<char_t> to_remove;\n    size_t ret = 0;\n    for (auto& i : target) {\n      if (!tab.count(i.first)) {\n        to_remove.push_back(i.first);\n        ret += i.second;\n      }\n    }\n\n    for (auto i : to_remove)\n      target.erase(i);\n\n    return ret;\n  }\n\n//  size_t filter_missing(windowed_freq_table& target, prob_table const& lookup) {\n//    size_t acc = 0;\n//    for (auto& i : target)\n//      acc += filter_missing(i, lookup);\n//    return acc;\n//  }\n\n  void freq_analysis(freq_table& tab, string_const_ref_t const& str) {\n    for (auto& i : str)\n      ++tab[i];\n  }\n  size_t freq_analysis(freq_table& tab, string_const_ref_t const& str, domain_t const& domain) {\n    size_t n = 0;\n    for (auto& i : str) {\n      if (domain.count(i)) {\n        ++tab[i];\n        ++n;\n      }\n    }\n    return n;\n  }\n  void freq_analysis(windowed_freq_table& tabs, string_const_ref_t const& str, size_t offset) {\n    for (size_t i = 0; i < str.size(); ++i)\n      ++tabs[(offset + i) % tabs.size()][str[i]];\n  }\n\n  size_t freq_analysis(windowed_freq_table& tabs, string_const_ref_t const& str, domain_t const& domain, size_t offset) {\n    for (auto& c : str) {\n      if (domain.count(c)) {\n        ++tabs[offset % tabs.size()][c];\n        ++offset;\n      }\n    }\n    return offset;\n  }\n\n  string_t generate_fuzz(prob_table const& tab, size_t len) {\n    string_t ret;\n    ret.resize(len);\n    std::mt19937 rng;\n\n    {\n      thread_local std::random_device seed_rng;\n      thread_local std::uniform_int_distribution<decltype(rng)::result_type> seed_dist;\n      rng.seed(seed_dist(seed_rng));\n    }\n\n    thread_local std::uniform_real_distribution<float_t> dist{0, 1};\n\n    for (auto& rand_char : ret) {\n    restat_char:\n      float_t stat = dist(rng);\n      // Iterate through the table, removing the probabilities until we are within a bracket\n      for (auto const& i : tab) {\n        if ((stat -= i.second) <= 0) {\n          rand_char = i.first;\n          goto next_char;\n        }\n      }\n      // This should not happen in normal usage!\n      //\n      // However, floats do weird things with rounding, so we will be leniant\n      goto restat_char;\n      next_char: {}\n    }\n\n    return ret;\n  }\n\n  assoc_table closeness_assoc(prob_table const& observed, prob_table const& expected) {\n    // What can we possibly do with this?\n    if (observed.size() == 0)\n      return {{.observed = 0, .expected = 1}};\n\n    assoc_table assoc;\n\n    // Sort the expected values\n    std::vector<prob_t> expected_sorted;\n    expected_sorted.reserve(expected_sorted.size());\n    for (auto& i : expected)\n      expected_sorted.emplace_back(i.second);\n    std::sort(expected_sorted.rbegin(), expected_sorted.rend());\n\n    // Sort the observed values\n    std::vector<prob_t> observed_sorted;\n    observed_sorted.reserve(observed.size());\n    for (auto& i : observed)\n      observed_sorted.emplace_back(i.second);\n    std::sort(observed_sorted.rbegin(), observed_sorted.rend());\n\n    // Fill table with observed values, or zeroes where appropriate\n    size_t i;\n    if (observed.size() > expected.size()) {\n      for (i = 0; i < expected.size(); ++i)\n        assoc.emplace_back(assoc_table_elem{.observed = observed_sorted[i], .expected = expected_sorted[i]});\n      for (; i < observed.size(); ++i)\n        assoc.emplace_back(assoc_table_elem{.observed = observed_sorted[i], .expected = 0.});\n    }\n    else {\n      for (i = 0; i < observed.size(); ++i)\n        assoc.emplace_back(assoc_table_elem{.observed = observed_sorted[i], .expected = expected_sorted[i]});\n      for (; i < expected.size(); ++i)\n        assoc.emplace_back(assoc_table_elem{.observed = 0, .expected = expected_sorted[i]});\n    }\n\n    return assoc;\n  }\n\n  prob_t closeness_test(prob_table const& observed, prob_table const& expected, freq_t count) {\n    // Quick bypass to avoid more filling than we have to\n    if (observed.size() > expected.size())\n      return 0;\n\n    auto assoc = closeness_assoc(observed, expected);\n    prepare_chisq(assoc, count);\n    auto stat = run_chisq(assoc, count);\n\n    return 1 - chisq_cdf(assoc.size() - 1, stat);\n  }\n\n  prob_t closeness_test(windowed_prob_table const& observed, prob_table const& expected, freq_t count) {\n    struct imdt_res_t {\n      size_t tab_size;\n      float_t chi_sq;\n    };\n\n    std::vector<std::future<imdt_res_t>> asyncs(observed.size());\n\n    for (size_t i = 0; i < observed.size(); ++i) {\n      asyncs[i] = std::async(std::launch::async, [&, i]() -> imdt_res_t {\n        auto assoc = closeness_assoc(observed[i], expected);\n        prepare_chisq(assoc, count);\n\n        // We can normalise at the end for efficiency\n        return {.tab_size = assoc.size(), .chi_sq = run_chisq(assoc)};\n      });\n    }\n\n    float_t stat = 0;\n    size_t total_tab_len = 0;\n    for (auto& i : asyncs) {\n      auto res = i.get();\n      total_tab_len += res.tab_size;\n      stat += res.chi_sq;\n    }\n\n    // Finally, we can normalise\n    stat *= count;\n\n    return 1 - chisq_cdf(total_tab_len - 1, stat);\n  }\n\n  float_t calculate_entropy(std::map<uint8_t, freq_t> const& freqs, size_t len) {\n    float_t ret = 0;\n    for (auto& i : freqs)  {\n      float_t observed_prob = static_cast<float_t>(i.second) / len;\n      ret -= observed_prob * ::log2(observed_prob);\n      // Some nice printing, kept for future debug\n//      std::cout << \"  \" << std::hex << (int)i.first << \": \" << i.second << std::endl;\n    }\n\n//    std::cout << ret << std::endl;\n    return ret;\n  }\n\n  float_t information_content(bytes_const_ref_t b) {\n    // TODO:\n    // I would prefer something more empirical,\n    // rather than just brute forcing the token size\n\n    std::map<uint8_t, freq_t> byte_freqs;\n    std::map<uint8_t, freq_t> nybble_freqs;\n    std::map<uint8_t, freq_t> pair_freqs;\n    std::map<uint8_t, freq_t> bit_freqs;\n    for (auto i : b) {\n      ++byte_freqs[i];\n      ++nybble_freqs[i>>4];\n      ++nybble_freqs[i&0xf];\n      ++pair_freqs[i&0x3];\n      ++pair_freqs[(i>>2)&0x3];\n      ++pair_freqs[(i>>4)&0x3];\n      ++pair_freqs[(i>>6)&0x3];\n      for (int bit = 0; bit < 8; ++bit)\n        ++bit_freqs[(i >> bit) & 1];\n    }\n\n    return std::min({\n                      calculate_entropy(byte_freqs,   b.size()    ) / 8,\n                      calculate_entropy(nybble_freqs, b.size() * 2) / 4,\n                      calculate_entropy(pair_freqs,   b.size() * 4) / 2,\n                      calculate_entropy(bit_freqs,    b.size() * 8)\n                    }) * b.size();\n  }\n\n  freq_t hamming_weight(uint8_t byte) {\n    /// Precomputed hamming weight table for each byte\n    static std::array<freq_t, 256> weights {\n      0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4,\n      1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5,\n      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,\n      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,\n      2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6,\n      3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7,\n      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,\n      2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6,\n      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,\n      3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7,\n      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    };\n\n    return weights[byte];\n  }\n\n  freq_t hamming_weight(bytes_const_ref_t b) {\n    freq_t ret = 0;\n    for (auto i : b)\n      ret += hamming_weight(i);\n    return ret;\n  }\n\n  freq_t hamming_distance(bytes_const_ref_t x, bytes_const_ref_t y) {\n    if (x.size() != y.size())\n      throw std::invalid_argument(\"Lengths must be the same for hamming distance\");\n    freq_t ret = 0;\n    for (size_t i = 0; i < x.size(); ++i)\n      ret += hamming_weight(x[i] ^ y[i]);\n    return ret;\n  }\n}\n\n", "meta": {"hexsha": "f454861c5e11f59daaeef2b95888faccf42fcca7", "size": 13807, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/freq.cpp", "max_stars_repo_name": "Cyclic3/CipheyCore", "max_stars_repo_head_hexsha": "63cc5fa79b68602e92fd1e16abdbd16b53fcbc53", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 35.0, "max_stars_repo_stars_event_min_datetime": "2020-05-30T10:25:14.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-09T05:46:28.000Z", "max_issues_repo_path": "src/freq.cpp", "max_issues_repo_name": "Cyclic3/CipheyCore", "max_issues_repo_head_hexsha": "63cc5fa79b68602e92fd1e16abdbd16b53fcbc53", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 12.0, "max_issues_repo_issues_event_min_datetime": "2020-08-01T16:52:49.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-25T22:04:42.000Z", "max_forks_repo_path": "src/freq.cpp", "max_forks_repo_name": "Cyclic3/CipheyCore", "max_forks_repo_head_hexsha": "63cc5fa79b68602e92fd1e16abdbd16b53fcbc53", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 14.0, "max_forks_repo_forks_event_min_datetime": "2020-08-06T01:36:08.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-02T09:53:18.000Z", "avg_line_length": 30.6141906874, "max_line_length": 121, "alphanum_fraction": 0.591149417, "num_tokens": 4331, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6224593312018546, "lm_q2_score": 0.49609382947091946, "lm_q1q2_score": 0.30879823330583545}}
{"text": "#include <polyfem/RhsAssembler.hpp>\n\n#include <polyfem/BoundarySampler.hpp>\n#include <polyfem/LinearSolver.hpp>\n// #include <polyfem/UIState.hpp>\n\n#include <polyfem/Logger.hpp>\n\n#include <Eigen/Sparse>\n\n\n\n\n#ifdef USE_TBB\n#include <tbb/parallel_for.h>\n#include <tbb/task_scheduler_init.h>\n#include <tbb/enumerable_thread_specific.h>\n#endif\n\n\n#include <iostream>\n#include <map>\n#include <memory>\n\nnamespace polyfem\n{\n\tnamespace\n\t{\n\t\tclass LocalThreadScalarStorage\n\t\t{\n\t\tpublic:\n\t\t\tdouble val;\n            ElementAssemblyValues vals;\n\n\t\t\tLocalThreadScalarStorage()\n\t\t\t{\n\t\t\t\tval = 0;\n\t\t\t}\n\t\t};\n\t}\n\n\tRhsAssembler::RhsAssembler(const Mesh &mesh, const int n_basis, const int size, const std::vector< ElementBases > &bases, const std::vector< ElementBases > &gbases, const std::string &formulation, const Problem &problem)\n\t: mesh_(mesh), n_basis_(n_basis), size_(size), bases_(bases), gbases_(gbases), formulation_(formulation), problem_(problem)\n\t{ }\n\n\tvoid RhsAssembler::assemble(Eigen::MatrixXd &rhs, const double t) const\n\t{\n\t\trhs = Eigen::MatrixXd::Zero(n_basis_ * size_, 1);\n\t\tif(!problem_.is_rhs_zero())\n\t\t{\n\t\t\tEigen::MatrixXd rhs_fun;\n\n\t\t\tconst int n_elements = int(bases_.size());\n\t\t\tElementAssemblyValues vals;\n\t\t\tfor(int e = 0; e < n_elements; ++e)\n\t\t\t{\n\t\t\t\tvals.compute(e, mesh_.is_volume(), bases_[e], gbases_[e]);\n\n\t\t\t\tconst Quadrature &quadrature = vals.quadrature;\n\n\n\t\t\t\tproblem_.rhs(formulation_, vals.val, t, rhs_fun);\n\n\t\t\t\tfor(int d = 0; d < size_; ++d)\n\t\t\t\t\trhs_fun.col(d) = rhs_fun.col(d).array() * vals.det.array() * quadrature.weights.array();\n\n\t\t\t\tconst int n_loc_bases_ = int(vals.basis_values.size());\n\t\t\t\tfor(int i = 0; i < n_loc_bases_; ++i)\n\t\t\t\t{\n\t\t\t\t\tconst AssemblyValues &v = vals.basis_values[i];\n\n\t\t\t\t\tfor(int d = 0; d < size_; ++d)\n\t\t\t\t\t{\n\t\t\t\t\t\tconst double rhs_value = (rhs_fun.col(d).array() * v.val.array()).sum();\n\t\t\t\t\t\tfor(std::size_t ii = 0; ii < v.global.size(); ++ii)\n\t\t\t\t\t\t\trhs(v.global[ii].index*size_+d) +=  rhs_value * v.global[ii].val;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tvoid RhsAssembler::initial_solution(Eigen::MatrixXd &sol) const\n\t{\n\t\ttime_bc([&](const Eigen::MatrixXd&pts, Eigen::MatrixXd&val){ problem_.initial_solution(pts, val);}, sol);\n\t}\n\n\tvoid RhsAssembler::initial_velocity(Eigen::MatrixXd &sol) const\n\t{\n\t\ttime_bc([&](const Eigen::MatrixXd&pts, Eigen::MatrixXd&val){ problem_.initial_velocity(pts, val);}, sol);\n\t}\n\n\tvoid RhsAssembler::initial_acceleration(Eigen::MatrixXd &sol) const\n\t{\n\t\ttime_bc([&](const Eigen::MatrixXd&pts, Eigen::MatrixXd&val){ problem_.initial_acceleration(pts, val);}, sol);\n\t}\n\n\tvoid RhsAssembler::time_bc(const std::function<void(const Eigen::MatrixXd&, Eigen::MatrixXd&)> &fun,Eigen::MatrixXd &sol) const\n\t{\n\t\tsol = Eigen::MatrixXd::Zero(n_basis_ * size_, 1);\n\t\tEigen::MatrixXd loc_sol;\n\n\t\tconst int n_elements = int(bases_.size());\n        ElementAssemblyValues vals;\n\t\tfor(int e = 0; e < n_elements; ++e)\n\t\t{\n\t\t\tvals.compute(e, mesh_.is_volume(), bases_[e], gbases_[e]);\n\n\t\t\tconst Quadrature &quadrature = vals.quadrature;\n\t\t\t//problem_.initial_solution(vals.val, loc_sol);\n\t\t\tfun(vals.val, loc_sol);\n\n\t\t\tfor(int d = 0; d < size_; ++d)\n\t\t\t\tloc_sol.col(d) = loc_sol.col(d).array() * vals.det.array() * quadrature.weights.array();\n\n\t\t\tconst int n_loc_bases_ = int(vals.basis_values.size());\n\t\t\tfor(int i = 0; i < n_loc_bases_; ++i)\n\t\t\t{\n\t\t\t\tconst AssemblyValues &v = vals.basis_values[i];\n\n\t\t\t\tfor(int d = 0; d < size_; ++d)\n\t\t\t\t{\n\t\t\t\t\tconst double sol_value = (loc_sol.col(d).array() * v.val.array()).sum();\n\t\t\t\t\tfor(std::size_t ii = 0; ii < v.global.size(); ++ii)\n\t\t\t\t\t\tsol(v.global[ii].index*size_+d) +=  sol_value * v.global[ii].val;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tvoid RhsAssembler::set_bc(\n\t\t\tconst std::function<void(const Eigen::MatrixXi&, const Eigen::MatrixXd&, const Eigen::MatrixXd&, Eigen::MatrixXd &)> &df,\n\t\t\tconst std::function<void(const Eigen::MatrixXi&, const Eigen::MatrixXd&, const Eigen::MatrixXd&, Eigen::MatrixXd &)> &nf,\n\t\t\tconst std::vector< LocalBoundary > &local_boundary, const std::vector<int> &bounday_nodes, const int resolution, const std::vector< LocalBoundary > &local_neumann_boundary, Eigen::MatrixXd &rhs) const\n\t{\n\t\tconst int n_el=int(bases_.size());\n\n\t\tEigen::MatrixXd uv, samples, gtmp, rhs_fun;\n\t\tEigen::VectorXi global_primitive_ids;\n\n\t\tint index = 0;\n\t\tstd::vector<int> indices; indices.reserve(n_el*10);\n\t\t// std::map<int, int> global_index_to_col;\n\n\t\tlong total_size = 0;\n\n\t\tEigen::Matrix<bool, Eigen::Dynamic, 1> is_boundary(n_basis_); is_boundary.setConstant(false);\n\t\tEigen::VectorXi global_index_to_col(n_basis_); global_index_to_col.setConstant(-1);\n\n\n\t\tconst int actual_dim = problem_.is_scalar() ? 1 : mesh_.dimension();\n\n\t\t// assert((bounday_nodes.size()/actual_dim)*actual_dim == bounday_nodes.size());\n\n\t\tfor(int b : bounday_nodes)\n\t\t\tis_boundary[b/actual_dim] = true;\n\n\t\tfor(const auto &lb : local_boundary)\n\t\t{\n\t\t\tconst int e = lb.element_id();\n\t\t\tbool has_samples = sample_boundary(lb, resolution, true, uv, samples, global_primitive_ids);\n\n\t\t\tif(!has_samples)\n\t\t\t\tcontinue;\n\n\t\t\tconst ElementBases &bs = bases_[e];\n\t\t\tconst int n_local_bases = int(bs.bases.size());\n\n\t\t\ttotal_size += samples.rows();\n\n\t\t\tfor(int j = 0; j < n_local_bases; ++j)\n\t\t\t{\n\t\t\t\tconst Basis &b=bs.bases[j];\n\n\t\t\t\tfor(std::size_t ii = 0; ii < b.global().size(); ++ii)\n\t\t\t\t{\n\t\t\t\t\t//pt found\n\t\t\t\t\t// if(std::find(bounday_nodes.begin(), bounday_nodes.end(), size_ * b.global()[ii].index) != bounday_nodes.end())\n\t\t\t\t\tif(is_boundary[b.global()[ii].index])\n\t\t\t\t\t{\n\t\t\t\t\t\t//if(global_index_to_col.find( b.global()[ii].index ) == global_index_to_col.end())\n\t\t\t\t\t\tif(global_index_to_col(b.global()[ii].index) == -1)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t// global_index_to_col[b.global()[ii].index] = index++;\n\t\t\t\t\t\t\tglobal_index_to_col(b.global()[ii].index) = index++;\n\t\t\t\t\t\t\tindices.push_back(b.global()[ii].index);\n\t\t\t\t\t\t\tassert(indices.size() == size_t(index));\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// Eigen::MatrixXd global_mat = Eigen::MatrixXd::Zero(total_size, indices.size());\n\t\tEigen::MatrixXd global_rhs = Eigen::MatrixXd::Zero(total_size, size_);\n\n\t\tconst long buffer_size = total_size * long(indices.size());\n\t\tstd::vector< Eigen::Triplet<double> > entries, entries_t;\n\t\t// entries.reserve(buffer_size);\n\t\t// entries_t.reserve(buffer_size);\n\n\t\tindex = 0;\n\n\t\tint global_counter = 0;\n\t\tEigen::MatrixXd mapped;\n\n\t\tstd::vector<AssemblyValues> tmp_val;\n\n\t\tfor(const auto &lb : local_boundary)\n\t\t{\n\t\t\tconst int e = lb.element_id();\n\t\t\tbool has_samples = sample_boundary(lb, resolution, false, uv, samples, global_primitive_ids);\n\n\t\t\tif(!has_samples)\n\t\t\t\tcontinue;\n\n\t\t\tconst ElementBases &bs = bases_[e];\n\t\t\tconst ElementBases &gbs = gbases_[e];\n\t\t\tconst int n_local_bases = int(bs.bases.size());\n\n\t\t\tgbs.eval_geom_mapping(samples, mapped);\n\n\t\t\tbs.evaluate_bases(samples, tmp_val);\n\t\t\tfor(int j = 0; j < n_local_bases; ++j)\n\t\t\t{\n\t\t\t\tconst Basis &b=bs.bases[j];\n\t\t\t\tconst auto &tmp = tmp_val[j].val;\n\n\t\t\t\tfor(std::size_t ii = 0; ii < b.global().size(); ++ii)\n\t\t\t\t{\n\t\t\t\t\t// auto item = global_index_to_col.find(b.global()[ii].index);\n\t\t\t\t\t// if(item != global_index_to_col.end()){\n\t\t\t\t\tauto item = global_index_to_col(b.global()[ii].index);\n\t\t\t\t\tif(item != -1){\n\t\t\t\t\t\tfor(int k = 0; k < int(tmp.size()); ++k)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t// entries.push_back(Eigen::Triplet<double>(global_counter+k, item->second, tmp(k, j) * b.global()[ii].val));\n\t\t\t\t\t\t\t// entries_t.push_back(Eigen::Triplet<double>(item->second, global_counter+k, tmp(k, j) * b.global()[ii].val));\n\t\t\t\t\t\t\tentries.push_back(Eigen::Triplet<double>(global_counter+k, item, tmp(k) * b.global()[ii].val));\n\t\t\t\t\t\t\tentries_t.push_back(Eigen::Triplet<double>(item, global_counter+k, tmp(k) * b.global()[ii].val));\n\t\t\t\t\t\t}\n\t\t\t\t\t\t// global_mat.block(global_counter, item->second, tmp.size(), 1) = tmp;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// problem_.bc(mesh_, global_primitive_ids, mapped, t, rhs_fun);\n\t\t\tdf(global_primitive_ids, uv, mapped, rhs_fun);\n\t\t\tglobal_rhs.block(global_counter, 0, rhs_fun.rows(), rhs_fun.cols()) = rhs_fun;\n\t\t\tglobal_counter += rhs_fun.rows();\n\n\t\t\t//UIState::ui_state().debug_data().add_points(mapped, Eigen::MatrixXd::Constant(1, 3, 0));\n\n\t\t\t//Eigen::MatrixXd asd(mapped.rows(), 3);\n\t\t\t//asd.col(0)=mapped.col(0);\n\t\t\t//asd.col(1)=mapped.col(1);\n\t\t\t//asd.col(2)=rhs_fun;\n\t\t\t//UIState::ui_state().debug_data().add_points(asd, Eigen::MatrixXd::Constant(1, 3, 0));\n\t\t}\n\n\t\tassert(global_counter == total_size);\n\n\t\tif(total_size > 0)\n\t\t{\n\t\t\tconst double mmin = global_rhs.minCoeff();\n\t\t\tconst double mmax = global_rhs.maxCoeff();\n\n\t\t\tif(fabs(mmin) < 1e-8 && fabs(mmax) < 1e-8)\n\t\t\t{\n\t\t\t\t// std::cout<<\"is all zero, skipping\"<<std::endl;\n\t\t\t\tfor(size_t i = 0; i < indices.size(); ++i){\n\t\t\t\t\tfor(int d = 0; d < size_; ++d){\n\t\t\t\t\t\tif(problem_.all_dimentions_dirichelt() || std::find(bounday_nodes.begin(), bounday_nodes.end(), indices[i]*size_+d) != bounday_nodes.end())\n\t\t\t\t\t\t\trhs(indices[i]*size_+d) = 0;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tStiffnessMatrix mat(int(total_size), int(indices.size()));\n\t\t\t\tmat.setFromTriplets(entries.begin(), entries.end());\n\n\t\t\t\tStiffnessMatrix mat_t(int(indices.size()), int(total_size));\n\t\t\t\tmat_t.setFromTriplets(entries_t.begin(), entries_t.end());\n\n\t\t\t\tStiffnessMatrix A = mat_t * mat;\n\t\t\t\tEigen::MatrixXd b = mat_t * global_rhs;\n\n\n\t\t\t\tEigen::MatrixXd coeffs(b.rows(), b.cols());\n\n\t\t\t\tjson params = {\n\t\t\t\t{\"mtype\", -2}, // matrix type for Pardiso (2 = SPD)\n\t\t\t\t// {\"max_iter\", 0}, // for iterative solvers\n\t\t\t\t// {\"tolerance\", 1e-9}, // for iterative solvers\n\t\t\t\t};\n\n\t\t\t\t// auto solver = LinearSolver::create(\"\", \"\");\n\t\t\t\tauto solver = LinearSolver::create(LinearSolver::defaultSolver(), LinearSolver::defaultPrecond());\n\t\t\t\tsolver->setParameters(params);\n\t\t\t\tsolver->analyzePattern(A);\n\t\t\t\tsolver->factorize(A);\n\t\t\t\tfor(long i = 0; i < b.cols(); ++i){\n\t\t\t\t\tsolver->solve(b.col(i), coeffs.col(i));\n\t\t\t\t}\n\t\t\t\tlogger().trace(\"RHS solve error {}\", (A*coeffs-b).norm());\n\n\t\t\t\tfor(long i = 0; i < coeffs.rows(); ++i){\n\t\t\t\t\tfor(int d = 0; d < size_; ++d){\n\t\t\t\t\t\tif(problem_.all_dimentions_dirichelt() || std::find(bounday_nodes.begin(), bounday_nodes.end(), indices[i]*size_+d) != bounday_nodes.end())\n\t\t\t\t\t\t\trhs(indices[i]*size_+d) = coeffs(i, d);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\n\n\t\t//Neumann\n\t\tEigen::MatrixXd points;\n\t\tEigen::VectorXd weights;\n\n        ElementAssemblyValues vals;\n\t\tfor(const auto &lb : local_neumann_boundary)\n\t\t{\n\t\t\tconst int e = lb.element_id();\n\t\t\tbool has_samples = boundary_quadrature(lb, resolution, false, uv, points, weights, global_primitive_ids);\n\n\t\t\tif(!has_samples)\n\t\t\t\tcontinue;\n\n\t\t\tconst ElementBases &gbs = gbases_[e];\n\t\t\tconst ElementBases &bs = bases_[e];\n\n\t\t\tvals.compute(e, mesh_.is_volume(), points, bs, gbs);\n\t\t\t// problem_.neumann_bc(mesh_, global_primitive_ids, vals.val, t, rhs_fun);\n\t\t\tnf(global_primitive_ids, uv, vals.val, rhs_fun);\n\n\t\t\t// UIState::ui_state().debug_data().add_points(vals.val, Eigen::RowVector3d(0,1,0));\n\n\t\t\tfor(int d = 0; d < size_; ++d)\n\t\t\t\trhs_fun.col(d) = rhs_fun.col(d).array() * weights.array();\n\n\t\t\tfor(int i = 0; i < lb.size(); ++i)\n\t\t\t{\n\t\t\t\tconst int primitive_global_id = lb.global_primitive_id(i);\n\t\t\t\tconst auto nodes = bs.local_nodes_for_primitive(primitive_global_id, mesh_);\n\n\t\t\t\tfor(long n = 0; n < nodes.size(); ++n)\n\t\t\t\t{\n\t\t\t\t\t// const auto &b = bs.bases[nodes(n)];\n\t\t\t\t\tconst AssemblyValues &v = vals.basis_values[nodes(n)];\n\t\t\t\t\tfor(int d = 0; d < size_; ++d)\n\t\t\t\t\t{\n\t\t\t\t\t\tconst double rhs_value = (rhs_fun.col(d).array() * v.val.array()).sum();\n\n\t\t\t\t\t\tfor(size_t g = 0; g < v.global.size(); ++g)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tconst int g_index = v.global[g].index*size_+d;\n\t\t\t\t\t\t\tconst bool is_neumann = std::find(bounday_nodes.begin(), bounday_nodes.end(), g_index ) == bounday_nodes.end();\n\n\t\t\t\t\t\t\tif(is_neumann){\n\t\t\t\t\t\t\t\trhs(g_index) += rhs_value * v.global[g].val;\n\t\t\t\t\t\t\t\t// UIState::ui_state().debug_data().add_points(v.global[g].node, Eigen::RowVector3d(1,0,0));\n\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// std::cout<<\"skipping \"<<g_index<<\" \"<<rhs_value * v.global[g].val<<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\t\t}\n\t}\n\n\tvoid RhsAssembler::set_bc(const std::vector< LocalBoundary > &local_boundary, const std::vector<int> &bounday_nodes, const int resolution, const std::vector< LocalBoundary > &local_neumann_boundary, Eigen::MatrixXd &rhs, const double t) const\n\t{\n\t\tset_bc(\n\t\t\t[&](const Eigen::MatrixXi &global_ids, const Eigen::MatrixXd &uv, const Eigen::MatrixXd &pts, Eigen::MatrixXd &val){ problem_.bc(mesh_, global_ids, uv, pts, t, val);},\n\t\t\t[&](const Eigen::MatrixXi &global_ids, const Eigen::MatrixXd &uv, const Eigen::MatrixXd &pts, Eigen::MatrixXd &val){ problem_.neumann_bc(mesh_, global_ids, uv, pts, t, val);},\n\t\t\tlocal_boundary, bounday_nodes, resolution, local_neumann_boundary, rhs);\n\t}\n\n\tvoid RhsAssembler::set_velocity_bc(const std::vector< LocalBoundary > &local_boundary, const std::vector<int> &bounday_nodes, const int resolution, const std::vector< LocalBoundary > &local_neumann_boundary, Eigen::MatrixXd &rhs, const double t) const\n\t{\n\t\tset_bc(\n\t\t\t[&](const Eigen::MatrixXi &global_ids, const Eigen::MatrixXd &uv, const Eigen::MatrixXd &pts, Eigen::MatrixXd &val){ problem_.velocity_bc(mesh_, global_ids, uv, pts, t, val);},\n\t\t\t[&](const Eigen::MatrixXi &global_ids, const Eigen::MatrixXd &uv, const Eigen::MatrixXd &pts, Eigen::MatrixXd &val){ problem_.neumann_velocity_bc(mesh_, global_ids, uv, pts, t, val);},\n\t\t\tlocal_boundary, bounday_nodes, resolution, local_neumann_boundary, rhs);\n\t}\n\n\tvoid RhsAssembler::set_acceleration_bc(const std::vector< LocalBoundary > &local_boundary, const std::vector<int> &bounday_nodes, const int resolution, const std::vector< LocalBoundary > &local_neumann_boundary, Eigen::MatrixXd &rhs, const double t) const\n\t{\n\t\tset_bc(\n\t\t\t[&](const Eigen::MatrixXi &global_ids, const Eigen::MatrixXd &uv, const Eigen::MatrixXd &pts, Eigen::MatrixXd &val){ problem_.acceleration_bc(mesh_, global_ids, uv, pts, t, val);},\n\t\t\t[&](const Eigen::MatrixXi &global_ids, const Eigen::MatrixXd &uv, const Eigen::MatrixXd &pts, Eigen::MatrixXd &val){ problem_.neumann_acceleration_bc(mesh_, global_ids, uv, pts, t, val);},\n\t\t\tlocal_boundary, bounday_nodes, resolution, local_neumann_boundary, rhs);\n\t}\n\n\tvoid RhsAssembler::compute_energy_grad(const std::vector< LocalBoundary > &local_boundary, const std::vector<int> &bounday_nodes, const int resolution, const std::vector< LocalBoundary > &local_neumann_boundary, const Eigen::MatrixXd &final_rhs, const double t, Eigen::MatrixXd &rhs) const\n\t{\n\t\tif(problem_.is_linear_in_time()){\n\t\t\tif(problem_.is_time_dependent())\n\t\t\t\trhs = final_rhs;\n\t\t\telse\n\t\t\t\trhs = final_rhs * t;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tassemble(rhs, t);\n\t\t\trhs *= -1;\n\t\t\tset_bc(local_boundary, bounday_nodes, resolution, local_neumann_boundary, rhs, t);\n\t\t}\n\t}\n\n\tdouble RhsAssembler::compute_energy(const Eigen::MatrixXd &displacement, const std::vector< LocalBoundary > &local_neumann_boundary, const int resolution, const double t) const\n\t{\n\t\tEigen::Matrix<double, Eigen::Dynamic, 1, 0, 3, 1> local_displacement(size_);\n\n\t\tdouble res = 0;\n\t\tEigen::MatrixXd forces;\n\n\t\tif(!problem_.is_rhs_zero())\n\t\t{\n#ifdef USE_TBB\n\t\ttypedef tbb::enumerable_thread_specific< LocalThreadScalarStorage > LocalStorage;\n\t\tLocalStorage storages((LocalThreadScalarStorage()));\n#else\n\t\tLocalThreadScalarStorage loc_storage;\n#endif\n\n\t\tconst int n_bases = int(bases_.size());\n\n#ifdef USE_TBB\n\t\ttbb::parallel_for( tbb::blocked_range<int>(0, n_bases), [&](const tbb::blocked_range<int> &r) {\n\t\tLocalStorage::reference loc_storage = storages.local();\n\t\tfor (int e = r.begin(); e != r.end(); ++e) {\n#else\n\t\tfor(int e=0; e < n_bases; ++e) {\n#endif\n\t\t\tElementAssemblyValues &vals = loc_storage.vals;\n\t\t\tvals.compute(e, mesh_.is_volume(), bases_[e], gbases_[e]);\n\n\t\t\tconst Quadrature &quadrature = vals.quadrature;\n\t\t\tconst Eigen::VectorXd da = vals.det.array() * quadrature.weights.array();\n\n\n\t\t\tproblem_.rhs(formulation_, vals.val, t, forces);\n\t\t\tassert(forces.rows() == da.size());\n\t\t\tassert(forces.cols() == size_);\n\n\t\t\tfor(long p = 0; p < da.size(); ++p)\n\t\t\t{\n\t\t\t\tlocal_displacement.setZero();\n\n\t\t\t\tfor(size_t i = 0; i < vals.basis_values.size(); ++i)\n\t\t\t\t{\n\t\t\t\t\tconst auto &bs = vals.basis_values[i];\n\t\t\t\t\tassert(bs.val.size() == da.size());\n\t\t\t\t\tconst double b_val = bs.val(p);\n\n\t\t\t\t\tfor(int d = 0; d < size_; ++d)\n\t\t\t\t\t{\n\t\t\t\t\t\tfor(std::size_t ii = 0; ii < bs.global.size(); ++ii)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tlocal_displacement(d) += (bs.global[ii].val * b_val) * displacement(bs.global[ii].index*size_ + d);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tfor(int d = 0; d < size_; ++d)\n\t\t\t\t\tloc_storage.val += forces(p, d) * local_displacement(d) * da(p);\n\t\t\t\t\t// res += forces(p, d) * local_displacement(d) * da(p);\n\t\t\t}\n#ifdef USE_TBB\n\t\t}});\n#else\n\t\t}\n#endif\n\n#ifdef USE_TBB\n\t\tfor (LocalStorage::iterator i = storages.begin(); i != storages.end();  ++i)\n\t\t{\n\t\t\tres += i->val;\n\t\t}\n#else\n\t\tres = loc_storage.val;\n#endif\n\t\t}\n\n\t\tElementAssemblyValues vals;\n\t\t//Neumann\n\t\tEigen::MatrixXd points, uv;\n\t\tEigen::VectorXd weights;\n\t\tEigen::VectorXi global_primitive_ids;\n\t\tfor(const auto &lb : local_neumann_boundary)\n\t\t{\n\t\t\tconst int e = lb.element_id();\n\t\t\tbool has_samples = boundary_quadrature(lb, resolution, false, uv, points, weights, global_primitive_ids);\n\n\t\t\tif(!has_samples)\n\t\t\t\tcontinue;\n\n\t\t\tconst ElementBases &gbs = gbases_[e];\n\t\t\tconst ElementBases &bs = bases_[e];\n\n\t\t\tvals.compute(e, mesh_.is_volume(), points, bs, gbs);\n\t\t\tproblem_.neumann_bc(mesh_, global_primitive_ids, uv, vals.val, t, forces);\n\n\t\t\t// UIState::ui_state().debug_data().add_points(vals.val, Eigen::RowVector3d(1,0,0));\n\n\t\t\tfor(long p = 0; p < weights.size(); ++p)\n\t\t\t{\n\t\t\t\tlocal_displacement.setZero();\n\n\t\t\t\tfor(size_t i = 0; i < vals.basis_values.size(); ++i)\n\t\t\t\t{\n\t\t\t\t\tconst auto &vv = vals.basis_values[i];\n\t\t\t\t\tassert(vv.val.size() == weights.size());\n\t\t\t\t\tconst double b_val = vv.val(p);\n\n\t\t\t\t\tfor(int d = 0; d < size_; ++d)\n\t\t\t\t\t{\n\t\t\t\t\t\tfor(std::size_t ii = 0; ii < vv.global.size(); ++ii)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tlocal_displacement(d) += (vv.global[ii].val * b_val) * displacement(vv.global[ii].index*size_ + d);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tfor(int d = 0; d < size_; ++d)\n\t\t\t\t\tres -= forces(p, d) * local_displacement(d) * weights(p);\n\t\t\t}\n\t\t}\n\n\t\treturn res;\n\t}\n\n\tbool RhsAssembler::boundary_quadrature(const LocalBoundary &local_boundary, const int order, const bool skip_computation, Eigen::MatrixXd &uv, Eigen::MatrixXd &points, Eigen::VectorXd &weights, Eigen::VectorXi &global_primitive_ids) const\n\t{\n\t\tuv.resize(0, 0);\n\t\tpoints.resize(0, 0);\n\t\tweights.resize(0);\n\t\tglobal_primitive_ids.resize(0);\n\n\t\tfor(int i = 0; i < local_boundary.size(); ++i)\n\t\t{\n\t\t\tconst int gid = local_boundary.global_primitive_id(i);\n\t\t\tEigen::MatrixXd tmp_p, tmp_uv;\n\t\t\tEigen::VectorXd tmp_w;\n\t\t\tswitch(local_boundary.type())\n\t\t\t{\n\t\t\t\tcase BoundaryType::TriLine:\t BoundarySampler::quadrature_for_tri_edge(local_boundary[i], order, gid, mesh_, tmp_uv, tmp_p, tmp_w); break;\n\t\t\t\tcase BoundaryType::QuadLine: BoundarySampler::quadrature_for_quad_edge(local_boundary[i], order, gid, mesh_, tmp_uv, tmp_p, tmp_w); break;\n\t\t\t\tcase BoundaryType::Quad: \t BoundarySampler::quadrature_for_quad_face(local_boundary[i], order, gid, mesh_, tmp_uv, tmp_p, tmp_w); break;\n\t\t\t\tcase BoundaryType::Tri: \t BoundarySampler::quadrature_for_tri_face(local_boundary[i], order, gid, mesh_, tmp_uv, tmp_p, tmp_w); break;\n\t\t\t\tcase BoundaryType::Invalid:  assert(false); break;\n\t\t\t\tdefault: assert(false);\n\t\t\t}\n\n\t\t\tuv.conservativeResize(uv.rows() + tmp_uv.rows(), tmp_uv.cols());\n\t\t\tuv.bottomRows(tmp_uv.rows()) = tmp_uv;\n\n\t\t\tpoints.conservativeResize(points.rows() + tmp_p.rows(), tmp_p.cols());\n\t\t\tpoints.bottomRows(tmp_p.rows()) = tmp_p;\n\n\t\t\tweights.conservativeResize(weights.rows() + tmp_w.rows(), tmp_w.cols());\n\t\t\tweights.bottomRows(tmp_w.rows()) = tmp_w;\n\n\t\t\tglobal_primitive_ids.conservativeResize(global_primitive_ids.rows() + tmp_p.rows());\n\t\t\tglobal_primitive_ids.bottomRows(tmp_p.rows()).setConstant(gid);\n\t\t}\n\n\t\tassert(uv.rows() == global_primitive_ids.size());\n\t\tassert(points.rows() == global_primitive_ids.size());\n\t\tassert(weights.size() == global_primitive_ids.size());\n\n\t\treturn true;\n\t}\n\n\n\tbool RhsAssembler::sample_boundary(const LocalBoundary &local_boundary, const int n_samples, const bool skip_computation, Eigen::MatrixXd &uv, Eigen::MatrixXd &samples, Eigen::VectorXi &global_primitive_ids) const\n\t{\n\t\tuv.resize(0, 0);\n\t\tsamples.resize(0, 0);\n\t\tglobal_primitive_ids.resize(0);\n\n\t\tfor(int i = 0; i < local_boundary.size(); ++i)\n\t\t{\n\t\t\tEigen::MatrixXd tmp, tmp_uv;\n\t\t\tswitch(local_boundary.type())\n\t\t\t{\n\t\t\t\tcase BoundaryType::TriLine:\t BoundarySampler::sample_parametric_tri_edge(local_boundary[i], n_samples, tmp_uv, tmp); break;\n\t\t\t\tcase BoundaryType::QuadLine: BoundarySampler::sample_parametric_quad_edge(local_boundary[i], n_samples, tmp_uv, tmp); break;\n\t\t\t\tcase BoundaryType::Quad: \t BoundarySampler::sample_parametric_quad_face(local_boundary[i], n_samples, tmp_uv, tmp); break;\n\t\t\t\tcase BoundaryType::Tri: \t BoundarySampler::sample_parametric_tri_face(local_boundary[i], n_samples, tmp_uv, tmp); break;\n\t\t\t\tcase BoundaryType::Invalid:  assert(false); break;\n\t\t\t\tdefault: assert(false);\n\t\t\t}\n\n\t\t\tuv.conservativeResize(uv.rows() + tmp_uv.rows(), tmp_uv.cols());\n\t\t\tuv.bottomRows(tmp_uv.rows()) = tmp_uv;\n\n\t\t\tsamples.conservativeResize(samples.rows() + tmp.rows(), tmp.cols());\n\t\t\tsamples.bottomRows(tmp.rows()) = tmp;\n\n\t\t\tglobal_primitive_ids.conservativeResize(global_primitive_ids.rows() + tmp.rows());\n\t\t\tglobal_primitive_ids.bottomRows(tmp.rows()).setConstant(local_boundary.global_primitive_id(i));\n\t\t}\n\n\t\tassert(uv.rows() == global_primitive_ids.size());\n\t\tassert(samples.rows() == global_primitive_ids.size());\n\n\n\t\treturn true;\n\t}\n\n}\n", "meta": {"hexsha": "2323218e955ff7679ccea944280d0866e90fd87d", "size": 21503, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/assembler/RhsAssembler.cpp", "max_stars_repo_name": "ldXiao/polyfem", "max_stars_repo_head_hexsha": "d4103af16979ff67d461a9ebe46a14bbc4dc8c7c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/assembler/RhsAssembler.cpp", "max_issues_repo_name": "ldXiao/polyfem", "max_issues_repo_head_hexsha": "d4103af16979ff67d461a9ebe46a14bbc4dc8c7c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/assembler/RhsAssembler.cpp", "max_forks_repo_name": "ldXiao/polyfem", "max_forks_repo_head_hexsha": "d4103af16979ff67d461a9ebe46a14bbc4dc8c7c", "max_forks_repo_licenses": ["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.7944983819, "max_line_length": 290, "alphanum_fraction": 0.6688369065, "num_tokens": 6133, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6224593312018546, "lm_q2_score": 0.4960938294709195, "lm_q1q2_score": 0.30879823330583545}}
{"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 \"include/Helly.hh\"\n#include \"../model/include/Hypergraphe.hh\"\n#include \"../model/include/HyperVertex.hh\"\n#include \"../model/include/HyperEdge.hh\"\n#include <boost/foreach.hpp>\n\nHelly::Helly(const boost::shared_ptr<HypergrapheAbstrait>& ptrHypergrapheAbstrait) :\n\t\t\t\t_ptrHypergrapheAbstrait( ptrHypergrapheAbstrait ) {\n\n}\n\nvoid\nHelly::runAlgorithme() {\n\n\t_result.setBooleanResult(true);\n\n\tBOOST_FOREACH(auto& x, _ptrHypergrapheAbstrait->getHyperVertexList()) {\n\t\tBOOST_FOREACH(auto& y, _ptrHypergrapheAbstrait->getHyperVertexList()) {\n\n\t\t\tLibType::ListHyperEdge X_xy( allContainXY(x, y) );\n\t\t\tBOOST_FOREACH(auto& v, _ptrHypergrapheAbstrait->getHyperVertexList()) {\n\n\t\t\t\tif( voisin(x, v) && voisin(y, v) ) {\n\t\t\t\t\tLibType::ListHyperEdge X_xv( allContainXY(x, v) );\n\t\t\t\t\tLibType::ListHyperEdge X_yv( allContainXY(y, v) );\n\n\t\t\t\t\tLibType::ListHyperEdge X;\n\t\t\t\t\tconcatenate(X, X_xy);\n\t\t\t\t\tconcatenate(X, X_xv);\n\t\t\t\t\tconcatenate(X, X_yv);\n\n\t\t\t\t\tif( !nonEmptyIntersection(X) ) {\n\t\t\t\t\t\t_result.setBooleanResult(false);\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t}\n\t}\n}\n\nbool\nHelly::voisin(boost::shared_ptr<HyperVertex>& v1, boost::shared_ptr<HyperVertex>& v2) {\n\tBOOST_FOREACH(auto& element1, v1->getHyperEdgeList() ) {\n\t\tBOOST_FOREACH(auto& element2, v2->getHyperEdgeList() ) {\n\t\t\tif( element1==element2 ) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t}\n\treturn false;\n}\n\nvoid\nHelly::concatenate(LibType::ListHyperEdge& dest, LibType::ListHyperEdge& src) {\n\tBOOST_FOREACH(auto& e, src) {\n\t\tdest.push_back(e);\n\t}\n}\n\nbool\nHelly::nonEmptyIntersection(LibType::ListHyperEdge& ensemble) {\n\tfor(unsigned int i=0; i<ensemble.size(); i++) {\n\t\tfor(unsigned int j=i+1; j<ensemble.size(); j++) {\n\t\t\tif( !nonEmptyBetween(ensemble.at(i), ensemble.at(j)) )\n\t\t\t\treturn false;\n\t\t}\n\t}\n\treturn true;\n}\n\nbool\nHelly::nonEmptyBetween(boost::shared_ptr<HyperEdge>& e1, boost::shared_ptr<HyperEdge>& e2) {\n\tBOOST_FOREACH(auto& a, e1->getHyperVertexList()) {\n\t\tBOOST_FOREACH(auto& b, e2->getHyperVertexList()) {\n\t\t\tif(a==b)return true;\n\t\t}\n\t}\n\treturn false;\n}\n\nLibType::ListHyperEdge&\nHelly::allContainXY(boost::shared_ptr<HyperVertex>& v1, boost::shared_ptr<HyperVertex>& v2) {\n\tLibType::ListHyperEdge * elist = new LibType::ListHyperEdge();\n\tBOOST_FOREACH(auto& e, _ptrHypergrapheAbstrait->getHyperEdgeList()) {\n\t\tif( e->containVertex(v1) && e->containVertex(v2) ) {\n\t\t\telist->push_back(e);\n\t\t}\n\t}\n\treturn *elist;\n}\n\nRStructure\nHelly::getResult() const {\n\treturn _result;\n}\n\nHelly::~Helly() {\n\n}\n", "meta": {"hexsha": "4836ff052df011dbb922fcf2f9059bc748e63b7c", "size": 3597, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/algorithm/Helly.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": "src/algorithm/Helly.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": "src/algorithm/Helly.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": 28.1015625, "max_line_length": 93, "alphanum_fraction": 0.7128162358, "num_tokens": 1013, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5813030906443133, "lm_q2_score": 0.5312093733737563, "lm_q1q2_score": 0.3087936505213935}}
{"text": "\n#include <iostream>\n#include <armadillo>\n#include \"RkFehl.h\"\n#include \"DuffingOscil.h\"\n/*\n * To change this license header, choose License Headers in Project Properties.\n * To change this template file, choose Tools | Templates\n * and open the template in the editor.\n */\nusing namespace std;\nusing namespace arma;\n\n/**\n * Pars has 5 fields:\n * \n * gamma - index 0.\n * h - index 1.\n * tf - index 2.\n * x0 - index 3.\n * y0 - index 4.\n * \n * \n * @param pars\n * @return \n */\nJNIEXPORT jdoubleArray JNICALL Java_net_tedkwan_javafem_jni_DuffingOscil_rk4(JNIEnv *env, jobject jobj, jdoubleArray jarray) {\n    unsigned int i;\n    jboolean isCopy1;\n\n    jdouble* srcArrayElems =\n            env -> GetDoubleArrayElements(jarray, &isCopy1);\n    jint n = env -> GetArrayLength(jarray);\n    vector<double> pars(4);\n    pars[2]= srcArrayElems[1];\n    pars[3]= srcArrayElems[4];\n    double h = srcArrayElems[0];\n    pars[0]= srcArrayElems[2];\n    pars[1]= srcArrayElems[3];\n    double tf = srcArrayElems[5];\n    vec x = zeros<vec>(2);\n    x(0) = srcArrayElems[6];\n    x(1) = srcArrayElems[7];\n    //x(2) = 0.75;\n    //Rkfun testrk(gamma,h,tf,x);\n    RkFehl testrk(pars,\"vanderpol\",tf,h,x);\n    vector<vec> y=testrk.y;\n    vector<double> t=testrk.t;\n    \n    \n    vector<double> res;\n    //jboolean isCopy2;\n    unsigned int k=t.size();\n    \n    for(int j=0;j<3;j++){\n        for (i = 0; i < k; i++) {\n        if(j<2){\n            res.push_back(y[i](j));\n        }\n        else{\n            res.push_back(t[i]);\n        }\n    }\n//        for(int j=0;j<4;j++){\n//        for (i = 0; i < k; i++) {\n//        if(j<3){\n//            res.push_back(y[i](j));\n//        }\n//        else{\n//            res.push_back(t[i]);\n//        }\n//    }\n        \n    }\n\n    cout << n << endl;\n\n    if (isCopy1 == JNI_TRUE) {\n        env -> ReleaseDoubleArrayElements(jarray, srcArrayElems, JNI_ABORT);\n    }\n    int lenres=res.size();\n    jdoubleArray result = env -> NewDoubleArray(lenres);\n    env->SetDoubleArrayRegion(result, 0, lenres, &res[0]);\n//    if (isCopy2 == JNI_TRUE) {\n//        env -> ReleaseDoubleArrayElements(jarray, destArrayElems, 0);\n//    }\n\n    return result;\n}\n", "meta": {"hexsha": "c9ebb35d11fb4ba6f767f18fc6dff5311dbcdcc7", "size": 2155, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/DuffingOscil.cpp", "max_stars_repo_name": "tmkwan/Cpp-Runge-Kutta-Fehlberg", "max_stars_repo_head_hexsha": "4e1aeb1d0231acbb12c94617fb79a33b3f542726", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/DuffingOscil.cpp", "max_issues_repo_name": "tmkwan/Cpp-Runge-Kutta-Fehlberg", "max_issues_repo_head_hexsha": "4e1aeb1d0231acbb12c94617fb79a33b3f542726", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/DuffingOscil.cpp", "max_forks_repo_name": "tmkwan/Cpp-Runge-Kutta-Fehlberg", "max_forks_repo_head_hexsha": "4e1aeb1d0231acbb12c94617fb79a33b3f542726", "max_forks_repo_licenses": ["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.9444444444, "max_line_length": 126, "alphanum_fraction": 0.5670533643, "num_tokens": 670, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.3087936505213935}}
{"text": "//  Copyright John Maddock 2007.\r\n//  Use, modification and distribution are subject to the\r\n//  Boost Software License, Version 1.0. (See accompanying file\r\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\r\n\r\n#include \"required_defines.hpp\"\r\n\r\n#include \"performance_measure.hpp\"\r\n\r\n#include <boost/math/distributions.hpp>\r\n\r\ndouble probabilities[] = {\r\n   1e-5,\r\n   1e-4,\r\n   1e-3,\r\n   1e-2,\r\n   0.05,\r\n   0.1,\r\n   0.2,\r\n   0.3,\r\n   0.4,\r\n   0.5,\r\n   0.6,\r\n   0.7,\r\n   0.8,\r\n   0.9,\r\n   0.95,\r\n   1-1e-5,\r\n   1-1e-4,\r\n   1-1e-3,\r\n   1-1e-2\r\n};\r\n\r\nint int_values[] = {\r\n   1,\r\n   2,\r\n   3,\r\n   5,\r\n   10,\r\n   20,\r\n   50,\r\n   100,\r\n   1000,\r\n   10000,\r\n   100000\r\n};\r\n\r\nint small_int_values[] = {\r\n   1,\r\n   2,\r\n   3,\r\n   5,\r\n   10,\r\n   15,\r\n   20,\r\n   30,\r\n   50,\r\n   100,\r\n   150\r\n};\r\n\r\ndouble real_values[] = {\r\n   1e-5,\r\n   1e-4,\r\n   1e-2,\r\n   1e-1,\r\n   1,\r\n   10,\r\n   100,\r\n   1000,\r\n   10000,\r\n   100000\r\n};\r\n\r\n#define BOOST_MATH_DISTRIBUTION3_TEST(name, param1_table, param2_table, param3_table, random_variable_table, probability_table) \\\r\n   BOOST_MATH_PERFORMANCE_TEST(BOOST_JOIN(dist, name), \"dist-\" BOOST_STRINGIZE(name) \"-cdf\")\\\r\n   {\\\r\n   double result = 0;\\\r\n   unsigned a_size = sizeof(param1_table)/sizeof(param1_table[0]);\\\r\n   unsigned b_size = sizeof(param2_table)/sizeof(param2_table[0]);\\\r\n   unsigned c_size = sizeof(param3_table)/sizeof(param3_table[0]);\\\r\n   unsigned d_size = sizeof(random_variable_table)/sizeof(random_variable_table[0]);\\\r\n   \\\r\n   for(unsigned i = 0; i < a_size; ++i)\\\r\n   {\\\r\n      for(unsigned j = 0; j < b_size; ++j)\\\r\n      {\\\r\n         for(unsigned k = 0; k < c_size; ++k)\\\r\n         {\\\r\n            for(unsigned l = 0; l < d_size; ++l)\\\r\n            {\\\r\n               result += cdf(boost::math:: BOOST_JOIN(name, _distribution) <>(param1_table[i], param2_table[j], param3_table[k]), random_variable_table[l]);\\\r\n            }\\\r\n         }\\\r\n      }\\\r\n   }\\\r\n   \\\r\n   consume_result(result);\\\r\n   set_call_count(a_size * b_size * c_size * d_size);\\\r\n   }\\\r\n   BOOST_MATH_PERFORMANCE_TEST(BOOST_JOIN(dist_pdf_, name), \"dist-\" BOOST_STRINGIZE(name) \"-pdf\")\\\r\n   {\\\r\n   double result = 0;\\\r\n   unsigned a_size = sizeof(param1_table)/sizeof(param1_table[0]);\\\r\n   unsigned b_size = sizeof(param2_table)/sizeof(param2_table[0]);\\\r\n   unsigned c_size = sizeof(param3_table)/sizeof(param3_table[0]);\\\r\n   unsigned d_size = sizeof(random_variable_table)/sizeof(random_variable_table[0]);\\\r\n   \\\r\n   for(unsigned i = 0; i < a_size; ++i)\\\r\n   {\\\r\n      for(unsigned j = 0; j < b_size; ++j)\\\r\n      {\\\r\n         for(unsigned k = 0; k < c_size; ++k)\\\r\n         {\\\r\n            for(unsigned l = 0; l < d_size; ++l)\\\r\n            {\\\r\n               result += pdf(boost::math:: BOOST_JOIN(name, _distribution) <>(param1_table[i], param2_table[j], param3_table[k]), random_variable_table[l]);\\\r\n            }\\\r\n         }\\\r\n      }\\\r\n   }\\\r\n   \\\r\n   consume_result(result);\\\r\n   set_call_count(a_size * b_size * c_size * d_size);\\\r\n   }\\\r\n   BOOST_MATH_PERFORMANCE_TEST(BOOST_JOIN(dist_quant, name), \"dist-\" BOOST_STRINGIZE(name) \"-quantile\")\\\r\n   {\\\r\n      double result = 0;\\\r\n      unsigned a_size = sizeof(param1_table)/sizeof(param1_table[0]);\\\r\n      unsigned b_size = sizeof(param2_table)/sizeof(param2_table[0]);\\\r\n      unsigned c_size = sizeof(param3_table)/sizeof(param3_table[0]);\\\r\n      unsigned d_size = sizeof(probability_table)/sizeof(probability_table[0]);\\\r\n      \\\r\n      for(unsigned i = 0; i < a_size; ++i)\\\r\n      {\\\r\n         for(unsigned j = 0; j < b_size; ++j)\\\r\n         {\\\r\n            for(unsigned k = 0; k < c_size; ++k)\\\r\n            {\\\r\n               for(unsigned l = 0; l < d_size; ++l)\\\r\n               {\\\r\n                  result += quantile(boost::math:: BOOST_JOIN(name, _distribution) <>(param1_table[i], param2_table[j], param3_table[k]), probability_table[l]);\\\r\n               }\\\r\n            }\\\r\n         }\\\r\n      }\\\r\n      \\\r\n      consume_result(result);\\\r\n      set_call_count(a_size * b_size * c_size * d_size);\\\r\n   }\r\n\r\n#define BOOST_MATH_DISTRIBUTION2_TEST(name, param1_table, param2_table, random_variable_table, probability_table) \\\r\n   BOOST_MATH_PERFORMANCE_TEST(BOOST_JOIN(dist, name), \"dist-\" BOOST_STRINGIZE(name) \"-cdf\")\\\r\n   {\\\r\n   double result = 0;\\\r\n   unsigned a_size = sizeof(param1_table)/sizeof(param1_table[0]);\\\r\n   unsigned b_size = sizeof(param2_table)/sizeof(param2_table[0]);\\\r\n   unsigned c_size = sizeof(random_variable_table)/sizeof(random_variable_table[0]);\\\r\n   \\\r\n   for(unsigned i = 0; i < a_size; ++i)\\\r\n   {\\\r\n      for(unsigned j = 0; j < b_size; ++j)\\\r\n      {\\\r\n         for(unsigned k = 0; k < c_size; ++k)\\\r\n         {\\\r\n            result += cdf(boost::math:: BOOST_JOIN(name, _distribution) <>(param1_table[i], param2_table[j]), random_variable_table[k]);\\\r\n         }\\\r\n      }\\\r\n   }\\\r\n   \\\r\n   consume_result(result);\\\r\n   set_call_count(a_size * b_size * c_size);\\\r\n   }\\\r\n   BOOST_MATH_PERFORMANCE_TEST(BOOST_JOIN(dist_pdf_, name), \"dist-\" BOOST_STRINGIZE(name) \"-pdf\")\\\r\n   {\\\r\n   double result = 0;\\\r\n   unsigned a_size = sizeof(param1_table)/sizeof(param1_table[0]);\\\r\n   unsigned b_size = sizeof(param2_table)/sizeof(param2_table[0]);\\\r\n   unsigned c_size = sizeof(random_variable_table)/sizeof(random_variable_table[0]);\\\r\n   \\\r\n   for(unsigned i = 0; i < a_size; ++i)\\\r\n   {\\\r\n      for(unsigned j = 0; j < b_size; ++j)\\\r\n      {\\\r\n         for(unsigned k = 0; k < c_size; ++k)\\\r\n         {\\\r\n            result += pdf(boost::math:: BOOST_JOIN(name, _distribution) <>(param1_table[i], param2_table[j]), random_variable_table[k]);\\\r\n         }\\\r\n      }\\\r\n   }\\\r\n   \\\r\n   consume_result(result);\\\r\n   set_call_count(a_size * b_size * c_size);\\\r\n   }\\\r\n   BOOST_MATH_PERFORMANCE_TEST(BOOST_JOIN(dist_quant, name), \"dist-\" BOOST_STRINGIZE(name) \"-quantile\")\\\r\n   {\\\r\n      double result = 0;\\\r\n      unsigned a_size = sizeof(param1_table)/sizeof(param1_table[0]);\\\r\n      unsigned b_size = sizeof(param2_table)/sizeof(param2_table[0]);\\\r\n      unsigned c_size = sizeof(probability_table)/sizeof(probability_table[0]);\\\r\n      \\\r\n      for(unsigned i = 0; i < a_size; ++i)\\\r\n      {\\\r\n         for(unsigned j = 0; j < b_size; ++j)\\\r\n         {\\\r\n            for(unsigned k = 0; k < c_size; ++k)\\\r\n            {\\\r\n               result += quantile(boost::math:: BOOST_JOIN(name, _distribution) <>(param1_table[i], param2_table[j]), probability_table[k]);\\\r\n            }\\\r\n         }\\\r\n      }\\\r\n      \\\r\n      consume_result(result);\\\r\n      set_call_count(a_size * b_size * c_size);\\\r\n   }\r\n\r\n#define BOOST_MATH_DISTRIBUTION1_TEST(name, param1_table, random_variable_table, probability_table) \\\r\n   BOOST_MATH_PERFORMANCE_TEST(BOOST_JOIN(dist, name), \"dist-\" BOOST_STRINGIZE(name) \"-cdf\")\\\r\n   {\\\r\n   double result = 0;\\\r\n   unsigned a_size = sizeof(param1_table)/sizeof(param1_table[0]);\\\r\n   unsigned c_size = sizeof(random_variable_table)/sizeof(random_variable_table[0]);\\\r\n   \\\r\n   for(unsigned i = 0; i < a_size; ++i)\\\r\n   {\\\r\n         for(unsigned k = 0; k < c_size; ++k)\\\r\n         {\\\r\n            result += cdf(boost::math:: BOOST_JOIN(name, _distribution) <>(param1_table[i]), random_variable_table[k]);\\\r\n         }\\\r\n   }\\\r\n   \\\r\n   consume_result(result);\\\r\n   set_call_count(a_size * c_size);\\\r\n   }\\\r\n   BOOST_MATH_PERFORMANCE_TEST(BOOST_JOIN(dist_pdf_, name), \"dist-\" BOOST_STRINGIZE(name) \"-pdf\")\\\r\n   {\\\r\n   double result = 0;\\\r\n   unsigned a_size = sizeof(param1_table)/sizeof(param1_table[0]);\\\r\n   unsigned c_size = sizeof(random_variable_table)/sizeof(random_variable_table[0]);\\\r\n   \\\r\n   for(unsigned i = 0; i < a_size; ++i)\\\r\n   {\\\r\n         for(unsigned k = 0; k < c_size; ++k)\\\r\n         {\\\r\n            result += pdf(boost::math:: BOOST_JOIN(name, _distribution) <>(param1_table[i]), random_variable_table[k]);\\\r\n         }\\\r\n   }\\\r\n   \\\r\n   consume_result(result);\\\r\n   set_call_count(a_size * c_size);\\\r\n   }\\\r\n   BOOST_MATH_PERFORMANCE_TEST(BOOST_JOIN(dist_quant, name), \"dist-\" BOOST_STRINGIZE(name) \"-quantile\")\\\r\n   {\\\r\n      double result = 0;\\\r\n      unsigned a_size = sizeof(param1_table)/sizeof(param1_table[0]);\\\r\n      unsigned c_size = sizeof(probability_table)/sizeof(probability_table[0]);\\\r\n      \\\r\n      for(unsigned i = 0; i < a_size; ++i)\\\r\n      {\\\r\n            for(unsigned k = 0; k < c_size; ++k)\\\r\n            {\\\r\n               result += quantile(boost::math:: BOOST_JOIN(name, _distribution) <>(param1_table[i]), probability_table[k]);\\\r\n            }\\\r\n      }\\\r\n      \\\r\n      consume_result(result);\\\r\n      set_call_count(a_size * c_size);\\\r\n   }\r\n\r\nBOOST_MATH_DISTRIBUTION2_TEST(beta, probabilities, probabilities, probabilities, probabilities)\r\nBOOST_MATH_DISTRIBUTION2_TEST(binomial, int_values, probabilities, int_values, probabilities)\r\nBOOST_MATH_DISTRIBUTION2_TEST(cauchy, int_values, real_values, int_values, probabilities)\r\nBOOST_MATH_DISTRIBUTION1_TEST(chi_squared, int_values, real_values, probabilities)\r\nBOOST_MATH_DISTRIBUTION1_TEST(exponential, real_values, real_values, probabilities)\r\nBOOST_MATH_DISTRIBUTION2_TEST(fisher_f, int_values, int_values, real_values, probabilities)\r\nBOOST_MATH_DISTRIBUTION2_TEST(gamma, real_values, real_values, real_values, probabilities)\r\nBOOST_MATH_DISTRIBUTION3_TEST(hypergeometric, small_int_values, small_int_values, small_int_values, small_int_values, probabilities)\r\nBOOST_MATH_DISTRIBUTION2_TEST(logistic, real_values, real_values, real_values, probabilities)\r\nBOOST_MATH_DISTRIBUTION2_TEST(lognormal, real_values, real_values, real_values, probabilities)\r\nBOOST_MATH_DISTRIBUTION2_TEST(negative_binomial, int_values, probabilities, int_values, probabilities)\r\nBOOST_MATH_DISTRIBUTION2_TEST(normal, real_values, real_values, real_values, probabilities)\r\nBOOST_MATH_DISTRIBUTION1_TEST(poisson, real_values, int_values, probabilities)\r\nBOOST_MATH_DISTRIBUTION1_TEST(students_t, int_values, real_values, probabilities)\r\nBOOST_MATH_DISTRIBUTION2_TEST(weibull, real_values, real_values, real_values, probabilities)\r\nBOOST_MATH_DISTRIBUTION2_TEST(non_central_chi_squared, int_values, int_values, real_values, probabilities)\r\nBOOST_MATH_DISTRIBUTION3_TEST(non_central_beta, int_values, int_values, real_values, real_values, probabilities)\r\nBOOST_MATH_DISTRIBUTION3_TEST(non_central_f, int_values, int_values, real_values, real_values, probabilities)\r\nBOOST_MATH_DISTRIBUTION2_TEST(non_central_t, int_values, small_int_values, real_values, probabilities)\r\n\r\n#ifdef TEST_R\r\n\r\n#define MATHLIB_STANDALONE 1\r\n\r\nextern \"C\" {\r\n#include \"Rmath.h\"\r\n}\r\n\r\n#define BOOST_MATH_R_DISTRIBUTION3_TEST(name, param1_table, param2_table, param3_table, random_variable_table, probability_table) \\\r\n   BOOST_MATH_PERFORMANCE_TEST(BOOST_JOIN(dist, name), \"dist-\" #name \"-R-cdf\")\\\r\n   {\\\r\n   double result = 0;\\\r\n   unsigned a_size = sizeof(param1_table)/sizeof(param1_table[0]);\\\r\n   unsigned b_size = sizeof(param2_table)/sizeof(param2_table[0]);\\\r\n   unsigned c_size = sizeof(param3_table)/sizeof(param3_table[0]);\\\r\n   unsigned d_size = sizeof(random_variable_table)/sizeof(random_variable_table[0]);\\\r\n   \\\r\n   for(unsigned i = 0; i < a_size; ++i)\\\r\n   {\\\r\n      for(unsigned j = 0; j < b_size; ++j)\\\r\n      {\\\r\n         for(unsigned k = 0; k < c_size; ++k)\\\r\n         {\\\r\n            for(unsigned l = 0; l < d_size; ++l)\\\r\n            {\\\r\n               result += p##name (random_variable_table[l], param1_table[i], param2_table[j], param3_table[k], 1, 0);\\\r\n            }\\\r\n         }\\\r\n      }\\\r\n   }\\\r\n   \\\r\n   consume_result(result);\\\r\n   set_call_count(a_size * b_size * c_size * d_size);\\\r\n   }\\\r\n   BOOST_MATH_PERFORMANCE_TEST(BOOST_JOIN(dist_pdf_, name), \"dist-\" #name \"-R-pdf\")\\\r\n   {\\\r\n   double result = 0;\\\r\n   unsigned a_size = sizeof(param1_table)/sizeof(param1_table[0]);\\\r\n   unsigned b_size = sizeof(param2_table)/sizeof(param2_table[0]);\\\r\n   unsigned c_size = sizeof(param3_table)/sizeof(param3_table[0]);\\\r\n   unsigned d_size = sizeof(random_variable_table)/sizeof(random_variable_table[0]);\\\r\n   \\\r\n   for(unsigned i = 0; i < a_size; ++i)\\\r\n   {\\\r\n      for(unsigned j = 0; j < b_size; ++j)\\\r\n      {\\\r\n         for(unsigned k = 0; k < c_size; ++k)\\\r\n         {\\\r\n            for(unsigned l = 0; l < d_size; ++l)\\\r\n            {\\\r\n               result += d##name (random_variable_table[l], param1_table[i], param2_table[j], param3_table[k], 0);\\\r\n            }\\\r\n         }\\\r\n      }\\\r\n   }\\\r\n   \\\r\n   consume_result(result);\\\r\n   set_call_count(a_size * b_size * c_size * d_size);\\\r\n   }\\\r\n   BOOST_MATH_PERFORMANCE_TEST(BOOST_JOIN(dist_quant, name), \"dist-\" #name \"-R-quantile\")\\\r\n   {\\\r\n      double result = 0;\\\r\n      unsigned a_size = sizeof(param1_table)/sizeof(param1_table[0]);\\\r\n      unsigned b_size = sizeof(param2_table)/sizeof(param2_table[0]);\\\r\n      unsigned c_size = sizeof(param3_table)/sizeof(param3_table[0]);\\\r\n      unsigned d_size = sizeof(probability_table)/sizeof(probability_table[0]);\\\r\n      \\\r\n      for(unsigned i = 0; i < a_size; ++i)\\\r\n      {\\\r\n         for(unsigned j = 0; j < b_size; ++j)\\\r\n         {\\\r\n            for(unsigned k = 0; k < c_size; ++k)\\\r\n            {\\\r\n               for(unsigned l = 0; l < d_size; ++l)\\\r\n               {\\\r\n                  result += q##name (probability_table[l], param1_table[i], param2_table[j], param3_table[k], 1, 0);\\\r\n               }\\\r\n            }\\\r\n         }\\\r\n      }\\\r\n      \\\r\n      consume_result(result);\\\r\n      set_call_count(a_size * b_size * c_size * d_size);\\\r\n   }\r\n\r\n#define BOOST_MATH_R_DISTRIBUTION2_TEST(name, param1_table, param2_table, random_variable_table, probability_table) \\\r\n   BOOST_MATH_PERFORMANCE_TEST(BOOST_JOIN(dist, name), \"dist-\" #name \"-R-cdf\")\\\r\n   {\\\r\n   double result = 0;\\\r\n   unsigned a_size = sizeof(param1_table)/sizeof(param1_table[0]);\\\r\n   unsigned b_size = sizeof(param2_table)/sizeof(param2_table[0]);\\\r\n   unsigned c_size = sizeof(random_variable_table)/sizeof(random_variable_table[0]);\\\r\n   \\\r\n   for(unsigned i = 0; i < a_size; ++i)\\\r\n   {\\\r\n      for(unsigned j = 0; j < b_size; ++j)\\\r\n      {\\\r\n         for(unsigned k = 0; k < c_size; ++k)\\\r\n         {\\\r\n            result += p##name (random_variable_table[k], param1_table[i], param2_table[j], 1, 0);\\\r\n         }\\\r\n      }\\\r\n   }\\\r\n   \\\r\n   consume_result(result);\\\r\n   set_call_count(a_size * b_size * c_size);\\\r\n   }\\\r\n   BOOST_MATH_PERFORMANCE_TEST(BOOST_JOIN(dist_pdf_, name), \"dist-\" #name \"-R-pdf\")\\\r\n   {\\\r\n   double result = 0;\\\r\n   unsigned a_size = sizeof(param1_table)/sizeof(param1_table[0]);\\\r\n   unsigned b_size = sizeof(param2_table)/sizeof(param2_table[0]);\\\r\n   unsigned c_size = sizeof(random_variable_table)/sizeof(random_variable_table[0]);\\\r\n   \\\r\n   for(unsigned i = 0; i < a_size; ++i)\\\r\n   {\\\r\n      for(unsigned j = 0; j < b_size; ++j)\\\r\n      {\\\r\n         for(unsigned k = 0; k < c_size; ++k)\\\r\n         {\\\r\n            result += d##name (random_variable_table[k], param1_table[i], param2_table[j], 0);\\\r\n         }\\\r\n      }\\\r\n   }\\\r\n   \\\r\n   consume_result(result);\\\r\n   set_call_count(a_size * b_size * c_size);\\\r\n   }\\\r\n   BOOST_MATH_PERFORMANCE_TEST(BOOST_JOIN(dist_quant, name), \"dist-\" #name \"-R-quantile\")\\\r\n   {\\\r\n      double result = 0;\\\r\n      unsigned a_size = sizeof(param1_table)/sizeof(param1_table[0]);\\\r\n      unsigned b_size = sizeof(param2_table)/sizeof(param2_table[0]);\\\r\n      unsigned c_size = sizeof(probability_table)/sizeof(probability_table[0]);\\\r\n      \\\r\n      for(unsigned i = 0; i < a_size; ++i)\\\r\n      {\\\r\n         for(unsigned j = 0; j < b_size; ++j)\\\r\n         {\\\r\n            for(unsigned k = 0; k < c_size; ++k)\\\r\n            {\\\r\n               result += q##name (probability_table[k], param1_table[i], param2_table[j], 1, 0);\\\r\n            }\\\r\n         }\\\r\n      }\\\r\n      \\\r\n      consume_result(result);\\\r\n      set_call_count(a_size * b_size * c_size);\\\r\n   }\r\n\r\n#define BOOST_MATH_R_DISTRIBUTION1_TEST(name, param1_table, random_variable_table, probability_table) \\\r\n   BOOST_MATH_PERFORMANCE_TEST(BOOST_JOIN(dist, name), \"dist-\" #name \"-R-cdf\")\\\r\n   {\\\r\n   double result = 0;\\\r\n   unsigned a_size = sizeof(param1_table)/sizeof(param1_table[0]);\\\r\n   unsigned c_size = sizeof(random_variable_table)/sizeof(random_variable_table[0]);\\\r\n   \\\r\n   for(unsigned i = 0; i < a_size; ++i)\\\r\n   {\\\r\n         for(unsigned k = 0; k < c_size; ++k)\\\r\n         {\\\r\n            result += p##name (random_variable_table[k], param1_table[i], 1, 0);\\\r\n         }\\\r\n   }\\\r\n   \\\r\n   consume_result(result);\\\r\n   set_call_count(a_size * c_size);\\\r\n   }\\\r\n   BOOST_MATH_PERFORMANCE_TEST(BOOST_JOIN(dist_pdf_, name), \"dist-\" #name \"-R-pdf\")\\\r\n   {\\\r\n   double result = 0;\\\r\n   unsigned a_size = sizeof(param1_table)/sizeof(param1_table[0]);\\\r\n   unsigned c_size = sizeof(random_variable_table)/sizeof(random_variable_table[0]);\\\r\n   \\\r\n   for(unsigned i = 0; i < a_size; ++i)\\\r\n   {\\\r\n         for(unsigned k = 0; k < c_size; ++k)\\\r\n         {\\\r\n            result += d##name (random_variable_table[k], param1_table[i], 0);\\\r\n         }\\\r\n   }\\\r\n   \\\r\n   consume_result(result);\\\r\n   set_call_count(a_size * c_size);\\\r\n   }\\\r\n   BOOST_MATH_PERFORMANCE_TEST(BOOST_JOIN(dist_quant, name), \"dist-\" #name \"-R-quantile\")\\\r\n   {\\\r\n      double result = 0;\\\r\n      unsigned a_size = sizeof(param1_table)/sizeof(param1_table[0]);\\\r\n      unsigned c_size = sizeof(probability_table)/sizeof(probability_table[0]);\\\r\n      \\\r\n      for(unsigned i = 0; i < a_size; ++i)\\\r\n      {\\\r\n            for(unsigned k = 0; k < c_size; ++k)\\\r\n            {\\\r\n               result += q##name (probability_table[k], param1_table[i], 1, 0);\\\r\n            }\\\r\n      }\\\r\n      \\\r\n      consume_result(result);\\\r\n      set_call_count(a_size * c_size);\\\r\n   }\r\n\r\ndouble qhypergeo(double r, double n, double N, double p, int i, int j)\r\n{\r\n   if(r > N)\r\n      return std::numeric_limits<double>::quiet_NaN();\r\n   double nr = r;\r\n   double nb = N - r;\r\n   return qhyper(nr, nb, n, p, i, j);\r\n}\r\n\r\ndouble phypergeo(double r, double n, double N, double k, int i, int j)\r\n{\r\n   if((r > N) || (k > n) || (k > r))\r\n      return std::numeric_limits<double>::quiet_NaN();\r\n   double nr = r;\r\n   double nb = N - r;\r\n   return phyper(nr, nb, n, k, i, j);\r\n}\r\n\r\ndouble dhypergeo(double r, double n, double N, double k, int i)\r\n{\r\n   if((r > N) || (k > n) || (k > r))\r\n      return std::numeric_limits<double>::quiet_NaN();\r\n   double nr = r;\r\n   double nb = N - r;\r\n   return dhyper(nr, nb, n, k, i);\r\n}\r\n\r\nBOOST_MATH_R_DISTRIBUTION2_TEST(beta, probabilities, probabilities, probabilities, probabilities)\r\nBOOST_MATH_R_DISTRIBUTION2_TEST(binom, int_values, probabilities, int_values, probabilities)\r\nBOOST_MATH_R_DISTRIBUTION2_TEST(cauchy, int_values, real_values, int_values, probabilities)\r\nBOOST_MATH_R_DISTRIBUTION1_TEST(chisq, int_values, real_values, probabilities)\r\nBOOST_MATH_R_DISTRIBUTION1_TEST(exp, real_values, real_values, probabilities)\r\nBOOST_MATH_R_DISTRIBUTION2_TEST(f, int_values, int_values, real_values, probabilities)\r\nBOOST_MATH_R_DISTRIBUTION2_TEST(gamma, real_values, real_values, real_values, probabilities)\r\nBOOST_MATH_R_DISTRIBUTION3_TEST(hypergeo, small_int_values, small_int_values, small_int_values, small_int_values, probabilities)\r\nBOOST_MATH_R_DISTRIBUTION2_TEST(logis, real_values, real_values, real_values, probabilities)\r\nBOOST_MATH_R_DISTRIBUTION2_TEST(lnorm, real_values, real_values, real_values, probabilities)\r\nBOOST_MATH_R_DISTRIBUTION2_TEST(nbinom, int_values, probabilities, int_values, probabilities)\r\nBOOST_MATH_R_DISTRIBUTION2_TEST(norm, real_values, real_values, real_values, probabilities)\r\nBOOST_MATH_R_DISTRIBUTION1_TEST(pois, real_values, int_values, probabilities)\r\nBOOST_MATH_R_DISTRIBUTION1_TEST(t, int_values, real_values, probabilities)\r\nBOOST_MATH_R_DISTRIBUTION2_TEST(weibull, real_values, real_values, real_values, probabilities)\r\nBOOST_MATH_R_DISTRIBUTION2_TEST(nchisq, int_values, int_values, real_values, probabilities)\r\nBOOST_MATH_R_DISTRIBUTION3_TEST(nf, int_values, int_values, real_values, real_values, probabilities)\r\nBOOST_MATH_R_DISTRIBUTION3_TEST(nbeta, int_values, int_values, real_values, real_values, probabilities)\r\nBOOST_MATH_R_DISTRIBUTION2_TEST(nt, int_values, small_int_values, real_values, probabilities)\r\n\r\n#endif\r\n\r\n#ifdef TEST_CEPHES\r\n\r\nextern \"C\"{\r\n\r\ndouble bdtr(int k, int n, double p);\r\ndouble bdtri(int k, int n, double p);\r\n\r\ndouble chdtr(double df, double x);\r\ndouble chdtri(double df, double p);\r\n\r\ndouble fdtr(int k, int n, double p);\r\ndouble fdtri(int k, int n, double p);\r\n\r\ndouble nbdtr(int k, int n, double p);\r\ndouble nbdtri(int k, int n, double p);\r\n\r\n}\r\n\r\n#define BOOST_MATH_CEPHES_DISTRIBUTION2_TEST(name, param1_table, param2_table, random_variable_table, probability_table) \\\r\n   BOOST_MATH_PERFORMANCE_TEST(BOOST_JOIN(dist, name), \"dist-\" #name \"-cephes-cdf\")\\\r\n   {\\\r\n   double result = 0;\\\r\n   unsigned a_size = sizeof(param1_table)/sizeof(param1_table[0]);\\\r\n   unsigned b_size = sizeof(param2_table)/sizeof(param2_table[0]);\\\r\n   unsigned c_size = sizeof(random_variable_table)/sizeof(random_variable_table[0]);\\\r\n   \\\r\n   for(unsigned i = 0; i < a_size; ++i)\\\r\n   {\\\r\n      for(unsigned j = 0; j < b_size; ++j)\\\r\n      {\\\r\n         for(unsigned k = 0; k < c_size; ++k)\\\r\n         {\\\r\n            result += name##dtr (param1_table[i], param2_table[j], random_variable_table[k]);\\\r\n         }\\\r\n      }\\\r\n   }\\\r\n   \\\r\n   consume_result(result);\\\r\n   set_call_count(a_size * b_size * c_size);\\\r\n   }\\\r\n   BOOST_MATH_PERFORMANCE_TEST(BOOST_JOIN(dist_quant, name), \"dist-\" #name \"-cephes-quantile\")\\\r\n   {\\\r\n      double result = 0;\\\r\n      unsigned a_size = sizeof(param1_table)/sizeof(param1_table[0]);\\\r\n      unsigned b_size = sizeof(param2_table)/sizeof(param2_table[0]);\\\r\n      unsigned c_size = sizeof(probability_table)/sizeof(probability_table[0]);\\\r\n      \\\r\n      for(unsigned i = 0; i < a_size; ++i)\\\r\n      {\\\r\n         for(unsigned j = 0; j < b_size; ++j)\\\r\n         {\\\r\n            for(unsigned k = 0; k < c_size; ++k)\\\r\n            {\\\r\n               result += name##dtri (param1_table[i], param2_table[j], probability_table[k]);\\\r\n            }\\\r\n         }\\\r\n      }\\\r\n      \\\r\n      consume_result(result);\\\r\n      set_call_count(a_size * b_size * c_size);\\\r\n   }\r\n\r\n#define BOOST_MATH_CEPHES_DISTRIBUTION1_TEST(name, param1_table, random_variable_table, probability_table) \\\r\n   BOOST_MATH_PERFORMANCE_TEST(BOOST_JOIN(dist, name), \"dist-\" #name \"-cephes-cdf\")\\\r\n   {\\\r\n   double result = 0;\\\r\n   unsigned a_size = sizeof(param1_table)/sizeof(param1_table[0]);\\\r\n   unsigned c_size = sizeof(random_variable_table)/sizeof(random_variable_table[0]);\\\r\n   \\\r\n   for(unsigned i = 0; i < a_size; ++i)\\\r\n   {\\\r\n         for(unsigned k = 0; k < c_size; ++k)\\\r\n         {\\\r\n            result += name##dtr (param1_table[i], random_variable_table[k]);\\\r\n         }\\\r\n   }\\\r\n   \\\r\n   consume_result(result);\\\r\n   set_call_count(a_size * c_size);\\\r\n   }\\\r\n   BOOST_MATH_PERFORMANCE_TEST(BOOST_JOIN(dist_quant, name), \"dist-\" #name \"-cephes-quantile\")\\\r\n   {\\\r\n      double result = 0;\\\r\n      unsigned a_size = sizeof(param1_table)/sizeof(param1_table[0]);\\\r\n      unsigned c_size = sizeof(probability_table)/sizeof(probability_table[0]);\\\r\n      \\\r\n      for(unsigned i = 0; i < a_size; ++i)\\\r\n      {\\\r\n            for(unsigned k = 0; k < c_size; ++k)\\\r\n            {\\\r\n               result += name##dtri (param1_table[i], probability_table[k]);\\\r\n            }\\\r\n      }\\\r\n      \\\r\n      consume_result(result);\\\r\n      set_call_count(a_size * c_size);\\\r\n   }\r\n// Cephes inverse doesn't actually calculate the quantile!!!\r\n// BOOST_MATH_CEPHES_DISTRIBUTION2_TEST(b, int_values, int_values, probabilities, probabilities)\r\nBOOST_MATH_CEPHES_DISTRIBUTION1_TEST(ch, int_values, real_values, probabilities)\r\nBOOST_MATH_CEPHES_DISTRIBUTION2_TEST(f, int_values, int_values, real_values, probabilities)\r\n// Cephes inverse doesn't calculate the quantile!!!\r\n// BOOST_MATH_CEPHES_DISTRIBUTION2_TEST(nb, int_values, int_values, probabilities, probabilities)\r\n\r\n#endif\r\n\r\n#ifdef TEST_DCDFLIB\r\n#include <dcdflib.h>\r\n\r\nvoid cdfbeta( int *which, double *p, double *q, double *x, double *a, double *b, int *status, double *bound)\r\n{\r\n   double y = 1 - *x;\r\n   cdfbet(which, p, q, x, &y, a, b, status, bound);\r\n}\r\n\r\nvoid cdfbinomial( int *which, double *p, double *q, double *x, double *a, double *b, int *status, double *bound)\r\n{\r\n   double y = 1 - *x;\r\n   double cb = 1 - *b;\r\n   cdfbet(which, p, q, x, a, b, &cb, status, bound);\r\n}\r\n\r\nvoid cdfnegative_binomial( int *which, double *p, double *q, double *x, double *a, double *b, int *status, double *bound)\r\n{\r\n   double y = 1 - *x;\r\n   double cb = 1 - *b;\r\n   cdfnbn(which, p, q, x, a, b, &cb, status, bound);\r\n}\r\n\r\nvoid cdfchi_squared( int *which, double *p, double *q, double *x, double *a, int *status, double *bound)\r\n{\r\n   cdfchi(which, p, q, x, a, status, bound);\r\n}\r\n\r\nvoid cdfnon_central_chi_squared( int *which, double *p, double *q, double *x, double *a, double *b, int *status, double *bound)\r\n{\r\n   cdfchn(which, p, q, x, a, b, status, bound);\r\n}\r\n\r\nnamespace boost{ namespace math{\r\n\r\n   template <class T = double> struct f_distribution : public fisher_f_distribution<T> \r\n   { f_distribution(T a, T b) : fisher_f_distribution<T>(a, b) {} };\r\n   template <class T = double> \r\n   struct fnc_distribution : public non_central_f_distribution<T> \r\n   { fnc_distribution(T a, T b, T c) : non_central_f_distribution<T>(a, b, c) {} };\r\n   template <class T = double> struct gam_distribution : public gamma_distribution<T> \r\n   { gam_distribution(T a, T b) : gamma_distribution<T>(a, b) {} };\r\n   template <class T = double> struct nor_distribution : public normal_distribution<T> \r\n   { nor_distribution(T a, T b) : normal_distribution<T>(a, b) {} };\r\n   template <class T = double> struct poi_distribution : public poisson_distribution<T> \r\n   { poi_distribution(T a) : poisson_distribution<T>(a) {} };\r\n   template <class T = double> struct t_distribution : public students_t_distribution<T> \r\n   { t_distribution(T a) : students_t_distribution<T>(a) {} };\r\n\r\n   template <class T>\r\n   T cdf(const f_distribution<T>& d, const T& r){  return cdf(static_cast<fisher_f_distribution<T> >(d), r);  }\r\n   template <class T>\r\n   T quantile(const f_distribution<T>& d, const T& r){  return quantile(static_cast<fisher_f_distribution<T> >(d), r);  }\r\n   template <class T>\r\n   T cdf(const fnc_distribution<T>& d, const T& r){  return cdf(static_cast<non_central_f_distribution<T> >(d), r);  }\r\n   template <class T>\r\n   T quantile(const fnc_distribution<T>& d, const T& r){  return quantile(static_cast<non_central_f_distribution<T> >(d), r);  }\r\n   template <class T>\r\n   T cdf(const gam_distribution<T>& d, const T& r){  return cdf(static_cast<gamma_distribution<T> >(d), r);  }\r\n   template <class T>\r\n   T quantile(const gam_distribution<T>& d, const T& r){  return quantile(static_cast<gamma_distribution<T> >(d), r);  }\r\n   template <class T>\r\n   T cdf(const nor_distribution<T>& d, const T& r){  return cdf(static_cast<normal_distribution<T> >(d), r);  }\r\n   template <class T>\r\n   T quantile(const nor_distribution<T>& d, const T& r){  return quantile(static_cast<normal_distribution<T> >(d), r);  }\r\n   template <class T>\r\n   T cdf(const poi_distribution<T>& d, const T& r){  return cdf(static_cast<poisson_distribution<T> >(d), r);  }\r\n   template <class T>\r\n   T quantile(const poi_distribution<T>& d, const T& r){  return quantile(static_cast<poisson_distribution<T> >(d), r);  }\r\n   template <class T>\r\n   T cdf(const t_distribution<T>& d, const T& r){  return cdf(static_cast<students_t_distribution<T> >(d), r);  }\r\n   template <class T>\r\n   T quantile(const t_distribution<T>& d, const T& r){  return quantile(static_cast<students_t_distribution<T> >(d), r);  }\r\n\r\n}}\r\n\r\nbool check_near(double a, double b)\r\n{\r\n   bool r = ((fabs(a) <= 1e-7) || (fabs(b) <= 1e-7)) ? (fabs(a-b) < 1e-7) : fabs((a - b) / a) < 1e-5;\r\n   return r;\r\n}\r\n\r\n#define BOOST_MATH_DCD_DISTRIBUTION3_TEST(name, param1_table, param2_table, param3_table, random_variable_table, probability_table) \\\r\n   BOOST_MATH_PERFORMANCE_TEST(BOOST_JOIN(dcd_dist, name), \"dist-\" BOOST_STRINGIZE(name) \"-dcd-cdf\")\\\r\n   {\\\r\n   double result = 0;\\\r\n   unsigned a_size = sizeof(param1_table)/sizeof(param1_table[0]);\\\r\n   unsigned b_size = sizeof(param2_table)/sizeof(param2_table[0]);\\\r\n   unsigned c_size = sizeof(param3_table)/sizeof(param3_table[0]);\\\r\n   unsigned d_size = sizeof(random_variable_table)/sizeof(random_variable_table[0]);\\\r\n   \\\r\n   for(unsigned i = 0; i < a_size; ++i)\\\r\n   {\\\r\n      for(unsigned j = 0; j < b_size; ++j)\\\r\n      {\\\r\n         for(unsigned k = 0; k < c_size; ++k)\\\r\n         {\\\r\n            for(unsigned l = 0; l < d_size; ++l)\\\r\n            {\\\r\n               int which = 1;\\\r\n               double p; double q; \\\r\n               double rv = random_variable_table[l];\\\r\n               double a = param1_table[i];\\\r\n               double b = param2_table[j];\\\r\n               double c = param3_table[k];\\\r\n               int status = 0;\\\r\n               double bound = 0;\\\r\n               BOOST_JOIN(cdf, name)(&which, &p, &q, &rv, &a, &b, &c, &status, &bound);\\\r\n               result += p;\\\r\n               BOOST_ASSERT(\\\r\n                  (status != 0) || check_near(p, \\\r\n                             cdf(boost::math:: BOOST_JOIN(name, _distribution) <>(param1_table[i], param2_table[j], param3_table[k]), random_variable_table[l])\\\r\n               ));\\\r\n            }\\\r\n         }\\\r\n      }\\\r\n   }\\\r\n   \\\r\n   consume_result(result);\\\r\n   set_call_count(a_size * b_size * c_size * d_size);\\\r\n   }\\\r\n   BOOST_MATH_PERFORMANCE_TEST(BOOST_JOIN(dcd_dist_quant, name), \"dist-\" BOOST_STRINGIZE(name) \"-dcd-quantile\")\\\r\n   {\\\r\n      double result = 0;\\\r\n      unsigned a_size = sizeof(param1_table)/sizeof(param1_table[0]);\\\r\n      unsigned b_size = sizeof(param2_table)/sizeof(param2_table[0]);\\\r\n      unsigned c_size = sizeof(param3_table)/sizeof(param3_table[0]);\\\r\n      unsigned d_size = sizeof(probability_table)/sizeof(probability_table[0]);\\\r\n      \\\r\n      for(unsigned i = 0; i < a_size; ++i)\\\r\n      {\\\r\n         for(unsigned j = 0; j < b_size; ++j)\\\r\n         {\\\r\n            for(unsigned k = 0; k < c_size; ++k)\\\r\n            {\\\r\n               for(unsigned l = 0; l < d_size; ++l)\\\r\n               {\\\r\n                  int which = 2;\\\r\n                  double p = probability_table[l];\\\r\n                  double q = 1 - p; \\\r\n                  double rv;\\\r\n                  double a = param1_table[i];\\\r\n                  double b = param2_table[j];\\\r\n                  double c = param3_table[k];\\\r\n                  int status = 0;\\\r\n                  double bound = 0;\\\r\n                  BOOST_JOIN(cdf, name)(&which, &p, &q, &rv, &a, &b, &c, &status, &bound);\\\r\n                  result += rv;\\\r\n                  BOOST_ASSERT((status != 0) || (p > 0.99) || check_near(rv, quantile(boost::math:: BOOST_JOIN(name, _distribution) <>(param1_table[i], param2_table[j], param3_table[k]), probability_table[l])));\\\r\n               }\\\r\n            }\\\r\n         }\\\r\n      }\\\r\n      \\\r\n      consume_result(result);\\\r\n      set_call_count(a_size * b_size * c_size * d_size);\\\r\n   }\r\n\r\n#define BOOST_MATH_DCD_DISTRIBUTION2_TEST(name, param1_table, param2_table, random_variable_table, probability_table) \\\r\n   BOOST_MATH_PERFORMANCE_TEST(BOOST_JOIN(dcd_dist, name), \"dist-\" BOOST_STRINGIZE(name) \"-dcd-cdf\")\\\r\n   {\\\r\n   double result = 0;\\\r\n   unsigned a_size = sizeof(param1_table)/sizeof(param1_table[0]);\\\r\n   unsigned b_size = sizeof(param2_table)/sizeof(param2_table[0]);\\\r\n   unsigned c_size = sizeof(random_variable_table)/sizeof(random_variable_table[0]);\\\r\n   \\\r\n   for(unsigned i = 0; i < a_size; ++i)\\\r\n   {\\\r\n      for(unsigned j = 0; j < b_size; ++j)\\\r\n      {\\\r\n         for(unsigned k = 0; k < c_size; ++k)\\\r\n         {\\\r\n            int which = 1;\\\r\n            double p; double q; \\\r\n            double rv = random_variable_table[k];\\\r\n            double a = param1_table[i];\\\r\n            double b = param2_table[j];\\\r\n            int status = 0;\\\r\n            double bound = 0;\\\r\n            BOOST_JOIN(cdf, name)(&which, &p, &q, &rv, &a, &b, &status, &bound);\\\r\n            result += p;\\\r\n            BOOST_ASSERT((status != 0) || check_near(p, cdf(boost::math:: BOOST_JOIN(name, _distribution) <>(param1_table[i], param2_table[j]), random_variable_table[k])));\\\r\n         }\\\r\n      }\\\r\n   }\\\r\n   \\\r\n   consume_result(result);\\\r\n   set_call_count(a_size * b_size * c_size);\\\r\n   }\\\r\n   BOOST_MATH_PERFORMANCE_TEST(BOOST_JOIN(dcd_dist_quant, name), \"dist-\" BOOST_STRINGIZE(name) \"-dcd-quantile\")\\\r\n   {\\\r\n      double result = 0;\\\r\n      unsigned a_size = sizeof(param1_table)/sizeof(param1_table[0]);\\\r\n      unsigned b_size = sizeof(param2_table)/sizeof(param2_table[0]);\\\r\n      unsigned c_size = sizeof(probability_table)/sizeof(probability_table[0]);\\\r\n      \\\r\n      for(unsigned i = 0; i < a_size; ++i)\\\r\n      {\\\r\n         for(unsigned j = 0; j < b_size; ++j)\\\r\n         {\\\r\n            for(unsigned k = 0; k < c_size; ++k)\\\r\n            {\\\r\n               int which = 2;\\\r\n               double p = probability_table[k];\\\r\n               double q = 1 - p; \\\r\n               double rv;\\\r\n               double a = param1_table[i];\\\r\n               double b = param2_table[j];\\\r\n               int status = 0;\\\r\n               double bound = 0;\\\r\n               BOOST_JOIN(cdf, name)(&which, &p, &q, &rv, &a, &b, &status, &bound);\\\r\n               result += rv;\\\r\n               BOOST_ASSERT((status != 0) || (p > 0.99) || check_near(rv, quantile(boost::math:: BOOST_JOIN(name, _distribution) <>(param1_table[i], param2_table[j]), probability_table[k])));\\\r\n            }\\\r\n         }\\\r\n      }\\\r\n      \\\r\n      consume_result(result);\\\r\n      set_call_count(a_size * b_size * c_size);\\\r\n   }\r\n\r\n#define BOOST_MATH_DCD_DISTRIBUTION1_TEST(name, param1_table, random_variable_table, probability_table) \\\r\n   BOOST_MATH_PERFORMANCE_TEST(BOOST_JOIN(dcd_dist, name), \"dist-\" BOOST_STRINGIZE(name) \"-dcd-cdf\")\\\r\n   {\\\r\n   double result = 0;\\\r\n   unsigned a_size = sizeof(param1_table)/sizeof(param1_table[0]);\\\r\n   unsigned c_size = sizeof(random_variable_table)/sizeof(random_variable_table[0]);\\\r\n   \\\r\n   for(unsigned i = 0; i < a_size; ++i)\\\r\n   {\\\r\n         for(unsigned k = 0; k < c_size; ++k)\\\r\n         {\\\r\n            int which = 1;\\\r\n            double p; double q; \\\r\n            double rv = random_variable_table[k];\\\r\n            double a = param1_table[i];\\\r\n            int status = 0;\\\r\n            double bound = 0;\\\r\n            BOOST_JOIN(cdf, name)(&which, &p, &q, &rv, &a, &status, &bound);\\\r\n            result += p;\\\r\n            BOOST_ASSERT((status != 0) || check_near(p, cdf(boost::math:: BOOST_JOIN(name, _distribution) <>(param1_table[i]), random_variable_table[k])));\\\r\n         }\\\r\n   }\\\r\n   \\\r\n   consume_result(result);\\\r\n   set_call_count(a_size * c_size);\\\r\n   }\\\r\n   BOOST_MATH_PERFORMANCE_TEST(BOOST_JOIN(dcd_dist_quant, name), \"dist-\" BOOST_STRINGIZE(name) \"-dcd-quantile\")\\\r\n   {\\\r\n      double result = 0;\\\r\n      unsigned a_size = sizeof(param1_table)/sizeof(param1_table[0]);\\\r\n      unsigned c_size = sizeof(probability_table)/sizeof(probability_table[0]);\\\r\n      \\\r\n      for(unsigned i = 0; i < a_size; ++i)\\\r\n      {\\\r\n            for(unsigned k = 0; k < c_size; ++k)\\\r\n            {\\\r\n               int which = 2;\\\r\n               double p = probability_table[k];\\\r\n               double q = 1 - p; \\\r\n               double rv;\\\r\n               double a = param1_table[i];\\\r\n               int status = 0;\\\r\n               double bound = 0;\\\r\n               BOOST_JOIN(cdf, name)(&which, &p, &q, &rv, &a, &status, &bound);\\\r\n               result += rv;\\\r\n               BOOST_ASSERT((status != 0) || (p > 0.99) || check_near(rv, quantile(boost::math:: BOOST_JOIN(name, _distribution) <>(param1_table[i]), probability_table[k])));\\\r\n            }\\\r\n      }\\\r\n      \\\r\n      consume_result(result);\\\r\n      set_call_count(a_size * c_size);\\\r\n   }\r\n\r\nBOOST_MATH_DCD_DISTRIBUTION2_TEST(beta, probabilities, probabilities, probabilities, probabilities) // ??\r\nBOOST_MATH_DCD_DISTRIBUTION2_TEST(binomial, int_values, probabilities, int_values, probabilities) // OK ish\r\nBOOST_MATH_DCD_DISTRIBUTION1_TEST(chi_squared, int_values, real_values, probabilities) // OK\r\nBOOST_MATH_DCD_DISTRIBUTION2_TEST(non_central_chi_squared, int_values, int_values, real_values, probabilities) // Error rates quite high for DCD version?\r\nBOOST_MATH_DCD_DISTRIBUTION2_TEST(f, int_values, int_values, real_values, probabilities) // OK\r\nBOOST_MATH_DCD_DISTRIBUTION3_TEST(fnc, int_values, int_values, real_values, real_values, probabilities) // Error rates quite high for DCD version?\r\nBOOST_MATH_DCD_DISTRIBUTION2_TEST(gam, real_values, real_values, real_values, probabilities) // ??\r\nBOOST_MATH_DCD_DISTRIBUTION2_TEST(negative_binomial, int_values, probabilities, int_values, probabilities) // OK\r\nBOOST_MATH_DCD_DISTRIBUTION2_TEST(nor, real_values, real_values, real_values, probabilities) // OK\r\nBOOST_MATH_DCD_DISTRIBUTION1_TEST(poi, real_values, int_values, probabilities) // OK\r\nBOOST_MATH_DCD_DISTRIBUTION1_TEST(t, int_values, real_values, probabilities) // OK\r\n\r\n#endif\r\n", "meta": {"hexsha": "2d900832383df6eaf009d5f558cfb3f61b436b9a", "size": 37149, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/math/performance/distributions.cpp", "max_stars_repo_name": "jmuskaan72/Boost", "max_stars_repo_head_hexsha": "047e36c01841a8cd6a5c74d4e3034da46e327bc1", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 198.0, "max_stars_repo_stars_event_min_datetime": "2015-01-13T05:47:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-09T04:46:46.000Z", "max_issues_repo_path": "libs/boost/libs/math/performance/distributions.cpp", "max_issues_repo_name": "flingone/frameworks_base_cmds_remoted", "max_issues_repo_head_hexsha": "4509d9f0468137ed7fd8d100179160d167e7d943", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 9.0, "max_issues_repo_issues_event_min_datetime": "2015-01-28T16:33:19.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-12T23:03:28.000Z", "max_forks_repo_path": "libs/boost/libs/math/performance/distributions.cpp", "max_forks_repo_name": "flingone/frameworks_base_cmds_remoted", "max_forks_repo_head_hexsha": "4509d9f0468137ed7fd8d100179160d167e7d943", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 139.0, "max_forks_repo_forks_event_min_datetime": "2015-01-15T20:09:31.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-31T15:21:16.000Z", "avg_line_length": 39.7315508021, "max_line_length": 213, "alphanum_fraction": 0.6151174998, "num_tokens": 10221, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5813030761371503, "lm_q2_score": 0.5312093733737563, "lm_q1q2_score": 0.30879364281505256}}
{"text": "// This file is part of libigl, a simple c++ geometry processing library.\n//\n// Copyright (C) 2014 Daniele Panozzo <daniele.panozzo@gmail.com>\n//\n// This Source Code Form is subject to the terms of the Mozilla Public License\n// v. 2.0. If a copy of the MPL was not distributed with this file, You can\n// obtain one at http://mozilla.org/MPL/2.0/.\n#include \"frame_field_deformer.h\"\n\n#include <Eigen/Dense>\n#include <Eigen/Sparse>\n#include <vector>\n\n#include <igl/cotmatrix_entries.h>\n#include <igl/cotmatrix.h>\n#include <igl/vertex_triangle_adjacency.h>\n\nnamespace igl\n{\n\nclass Frame_field_deformer\n{\npublic:\n\n  IGL_INLINE Frame_field_deformer();\n  IGL_INLINE ~Frame_field_deformer();\n\n  // Initialize the optimizer\n  IGL_INLINE void init(const Eigen::MatrixXd& _V, const Eigen::MatrixXi& _F, const Eigen::MatrixXd& _D1, const Eigen::MatrixXd& _D2, double _Lambda, double _perturb_rotations, int _fixed = 1);\n\n  // Run N optimization steps\n  IGL_INLINE void optimize(int N, bool reset = false);\n\n  // Reset optimization\n  IGL_INLINE void reset_opt();\n\n  // Precomputation of all components\n  IGL_INLINE void precompute_opt();\n\n  // Precomputation for deformation energy\n  IGL_INLINE void precompute_ARAP(Eigen::SparseMatrix<double> & Lff, Eigen::MatrixXd & LfcVc);\n\n  // Precomputation for regularization\n  IGL_INLINE void precompute_SMOOTH(Eigen::SparseMatrix<double> & MS, Eigen::MatrixXd & bS);\n\n  // extracts a r x c block from sparse matrix mat into sparse matrix m1\n  // (r0,c0) is upper left entry of block\n  IGL_INLINE void extractBlock(Eigen::SparseMatrix<double> & mat, int r0, int c0, int r, int c, Eigen::SparseMatrix<double> & m1);\n\n  // computes optimal rotations for faces of m wrt current coords in mw.V\n  // returns a 3x3 matrix\n  IGL_INLINE void compute_optimal_rotations();\n\n  // global optimization step - linear system\n  IGL_INLINE void compute_optimal_positions();\n\n  // compute the output XField from deformation gradient\n  IGL_INLINE void computeXField(std::vector< Eigen::Matrix<double,3,2> > & XF);\n\n  // computes in WW the ideal warp at each tri to make the frame field a cross\n  IGL_INLINE void compute_idealWarp(std::vector< Eigen::Matrix<double,3,3> > & WW);\n\n  // -------------------------------- Variables ----------------------------------------------------\n\n  // Mesh I/O:\n\n  Eigen::MatrixXd V;                         // Original mesh - vertices\n  Eigen::MatrixXi F;                         // Original mesh - faces\n\n  std::vector<std::vector<int> > VT;                   // Vertex to triangle topology\n  std::vector<std::vector<int> > VTi;                  // Vertex to triangle topology\n\n  Eigen::MatrixXd V_w;                       // Warped mesh - vertices\n\n  std::vector< Eigen::Matrix<double,3,2> > FF;  \t// frame field FF in 3D (parallel to m.F)\n  std::vector< Eigen::Matrix<double,3,3> > WW;    // warping matrices to make a cross field (parallel to m.F)\n  std::vector< Eigen::Matrix<double,3,2> > XF;  \t// pseudo-cross field from solution (parallel to m.F)\n\n  int fixed;\n\n  double perturb_rotations; // perturbation to rotation matrices\n\n  // Numerics\n  int nfree,nconst;\t\t\t\t\t          // number of free/constrained vertices in the mesh - default all-but-1/1\n  Eigen::MatrixXd C;\t\t\t\t\t\t\t            // cotangent matrix of m\n  Eigen::SparseMatrix<double> L;\t\t\t\t\t          // Laplacian matrix of m\n\n  Eigen::SparseMatrix<double> M;\t\t\t\t\t          // matrix for global optimization - pre-conditioned\n  Eigen::MatrixXd RHS;\t\t\t\t\t\t            // pre-computed part of known term in global optimization\n  std::vector< Eigen::Matrix<double,3,3> > RW;    // optimal rotation-warping matrices (parallel to m.F) -- INCORPORATES WW\n  Eigen::SimplicialCholesky<Eigen::SparseMatrix<double> > solver;   // solver for linear system in global opt.\n\n  // Parameters\nprivate:\n  double Lambda = 0.1;\t\t\t\t        // weight of energy regularization\n\n};\n\n  IGL_INLINE Frame_field_deformer::Frame_field_deformer() {}\n\n  IGL_INLINE Frame_field_deformer::~Frame_field_deformer() {}\n\n  IGL_INLINE void Frame_field_deformer::init(const Eigen::MatrixXd& _V,\n                          const Eigen::MatrixXi& _F,\n                          const Eigen::MatrixXd& _D1,\n                          const Eigen::MatrixXd& _D2,\n                          double _Lambda,\n                          double _perturb_rotations,\n                          int _fixed)\n{\n  V = _V;\n  F = _F;\n\n  assert(_D1.rows() == _D2.rows());\n\n  FF.clear();\n  for (unsigned i=0; i < _D1.rows(); ++i)\n  {\n    Eigen::Matrix<double,3,2> ff;\n    ff.col(0) = _D1.row(i);\n    ff.col(1) = _D2.row(i);\n    FF.push_back(ff);\n  }\n\n  fixed = _fixed;\n  Lambda = _Lambda;\n  perturb_rotations = _perturb_rotations;\n\n  reset_opt();\n  precompute_opt();\n}\n\n\nIGL_INLINE void Frame_field_deformer::optimize(int N, bool reset)\n{\n  //Reset optimization\n\tif (reset)\n    reset_opt();\n\n\t// Iterative Local/Global optimization\n  for (int i=0; i<N;i++)\n  {\n    compute_optimal_rotations();\n    compute_optimal_positions();\n\t\tcomputeXField(XF);\n  }\n}\n\nIGL_INLINE void Frame_field_deformer::reset_opt()\n{\n  V_w = V;\n\n  for (unsigned i=0; i<V_w.rows(); ++i)\n    for (unsigned j=0; j<V_w.cols(); ++j)\n      V_w(i,j) += (double(rand())/double(RAND_MAX))*10e-4*perturb_rotations;\n\n}\n\n// precomputation of all components\nIGL_INLINE void Frame_field_deformer::precompute_opt()\n{\n  using namespace Eigen;\n\tnfree = V.rows() - fixed;\t\t\t\t\t\t    // free vertices (at the beginning ov m.V) - global\n  nconst = V.rows()-nfree;\t\t\t\t\t\t// #constrained vertices\n  igl::vertex_triangle_adjacency(V,F,VT,VTi);                // compute vertex to face relationship\n\n  igl::cotmatrix_entries(V,F,C);\t\t\t\t\t\t\t     // cotangent matrix for opt. rotations - global\n\n  igl::cotmatrix(V,F,L);\n\n\tSparseMatrix<double> MA;\t\t\t\t\t\t// internal matrix for ARAP-warping energy\n\tMatrixXd LfcVc;\t\t\t\t\t\t\t\t\t\t  // RHS (partial) for ARAP-warping energy\n\tSparseMatrix<double> MS;\t\t\t\t\t\t// internal matrix for smoothing energy\n\tMatrixXd bS;\t\t\t\t\t\t\t\t\t\t    // RHS (full) for smoothing energy\n\n\tprecompute_ARAP(MA,LfcVc);\t\t\t\t\t// precompute terms for the ARAP-warp part\n\tprecompute_SMOOTH(MS,bS);\t\t\t\t\t\t// precompute terms for the smoothing part\n\tcompute_idealWarp(WW);              // computes the ideal warps\n  RW.resize(F.rows());\t\t\t\t\t\t\t\t// init rotation matrices - global\n\n  M =\t  (1-Lambda)*MA + Lambda*MS;\t\t// matrix for linear system - global\n\n\tRHS = (1-Lambda)*LfcVc + Lambda*bS;\t// RHS (partial) for linear system - global\n  solver.compute(M);\t\t\t\t\t\t\t\t\t// system pre-conditioning\n  if (solver.info()!=Eigen::Success) {fprintf(stderr,\"Decomposition failed in pre-conditioning!\\n\"); exit(-1);}\n\n\tfprintf(stdout,\"Preconditioning done.\\n\");\n\n}\n\nIGL_INLINE void Frame_field_deformer::precompute_ARAP(Eigen::SparseMatrix<double> & Lff, Eigen::MatrixXd & LfcVc)\n{\n  using namespace Eigen;\n\tfprintf(stdout,\"Precomputing ARAP terms\\n\");\n\tSparseMatrix<double> LL = -4*L;\n\tLff = SparseMatrix<double>(nfree,nfree);\n  extractBlock(LL,0,0,nfree,nfree,Lff);\n\tSparseMatrix<double> Lfc = SparseMatrix<double>(nfree,nconst);\n  extractBlock(LL,0,nfree,nfree,nconst,Lfc);\n\tLfcVc = - Lfc * V_w.block(nfree,0,nconst,3);\n}\n\nIGL_INLINE void Frame_field_deformer::precompute_SMOOTH(Eigen::SparseMatrix<double> & MS, Eigen::MatrixXd & bS)\n{\n  using namespace Eigen;\n\tfprintf(stdout,\"Precomputing SMOOTH terms\\n\");\n\n\tSparseMatrix<double> LL = 4*L*L;\n\n  // top-left\n\tMS = SparseMatrix<double>(nfree,nfree);\n  extractBlock(LL,0,0,nfree,nfree,MS);\n\n  // top-right\n\tSparseMatrix<double> Mfc = SparseMatrix<double>(nfree,nconst);\n  extractBlock(LL,0,nfree,nfree,nconst,Mfc);\n\n\tMatrixXd MfcVc = Mfc * V_w.block(nfree,0,nconst,3);\n\tbS = (LL*V).block(0,0,nfree,3)-MfcVc;\n\n}\n\n  IGL_INLINE void Frame_field_deformer::extractBlock(Eigen::SparseMatrix<double> & mat, int r0, int c0, int r, int c, Eigen::SparseMatrix<double> & m1)\n{\n  std::vector<Eigen::Triplet<double> > tripletList;\n  for (int k=c0; k<c0+c; ++k)\n    for (Eigen::SparseMatrix<double>::InnerIterator it(mat,k); it; ++it)\n    {\n      if (it.row()>=r0 && it.row()<r0+r)\n        tripletList.push_back(Eigen::Triplet<double>(it.row()-r0,it.col()-c0,it.value()));\n    }\n  m1.setFromTriplets(tripletList.begin(), tripletList.end());\n}\n\nIGL_INLINE void Frame_field_deformer::compute_optimal_rotations()\n{\n  using namespace Eigen;\n  Matrix<double,3,3> r,S,P,PP,D;\n\n  for (int i=0;i<F.rows();i++)\n\t{\n\t\t// input tri --- could be done once and saved in a matrix\n\t\tP.col(0) = (V.row(F(i,1))-V.row(F(i,0))).transpose();\n\t\tP.col(1) = (V.row(F(i,2))-V.row(F(i,1))).transpose();\n\t\tP.col(2) = (V.row(F(i,0))-V.row(F(i,2))).transpose();\n\n\t\tP = WW[i] * P;\t\t// apply ideal warp\n\n\t\t// current tri\n\t\tPP.col(0) = (V_w.row(F(i,1))-V_w.row(F(i,0))).transpose();\n\t\tPP.col(1) = (V_w.row(F(i,2))-V_w.row(F(i,1))).transpose();\n\t\tPP.col(2) = (V_w.row(F(i,0))-V_w.row(F(i,2))).transpose();\n\n\t\t// cotangents\n\t\tD <<    C(i,2), 0,      0,\n    0,      C(i,0), 0,\n    0,      0,      C(i,1);\n\n\t\tS = PP*D*P.transpose();\n\t\tEigen::JacobiSVD<Matrix<double,3,3> > svd(S, Eigen::ComputeFullU | Eigen::ComputeFullV );\n\t\tMatrix<double,3,3>  su = svd.matrixU();\n\t\tMatrix<double,3,3>  sv = svd.matrixV();\n\t\tr = su*sv.transpose();\n\n\t\tif (r.determinant()<0)  // correct reflections\n\t\t{\n\t\t\tsu(0,2)=-su(0,2); su(1,2)=-su(1,2); su(2,2)=-su(2,2);\n\t\t\tr = su*sv.transpose();\n\t\t}\n\t\tRW[i] = r*WW[i];\t\t// RW INCORPORATES IDEAL WARP WW!!!\n\t}\n}\n\nIGL_INLINE void Frame_field_deformer::compute_optimal_positions()\n{\n  using namespace Eigen;\n\t// compute variable RHS of ARAP-warp part of the system\n  MatrixXd b(nfree,3);          // fx3 known term of the system\n\tMatrixXd X;\t\t\t\t\t\t\t\t\t\t// result\n  int t;\t\t  \t\t\t\t\t\t\t\t\t// triangles incident to edge (i,j)\n\tint vi,i1,i2;\t\t\t\t\t\t\t\t\t// index of vertex i wrt tri t0\n\n  for (int i=0;i<nfree;i++)\n  {\n    b.row(i) << 0.0, 0.0, 0.0;\n    for (int k=0;k<(int)VT[i].size();k++)\t\t\t\t\t// for all incident triangles\n    {\n      t = VT[i][k];\t\t\t\t\t\t\t\t\t\t\t\t// incident tri\n\t\t\tvi = (i==F(t,0))?0:(i==F(t,1))?1:(i==F(t,2))?2:3;\t// index of i in t\n\t\t\tassert(vi!=3);\n\t\t\ti1 = F(t,(vi+1)%3);\n\t\t\ti2 = F(t,(vi+2)%3);\n\t\t\tb.row(i)+=(C(t,(vi+2)%3)*RW[t]*(V.row(i1)-V.row(i)).transpose()).transpose();\n\t\t\tb.row(i)+=(C(t,(vi+1)%3)*RW[t]*(V.row(i2)-V.row(i)).transpose()).transpose();\n    }\n  }\n  b/=2.0;\n\tb=-4*b;\n\n\tb*=(1-Lambda);\t\t// blend\n\n  b+=RHS;\t\t\t\t// complete known term\n\n\tX = solver.solve(b);\n\tif (solver.info()!=Eigen::Success) {printf(\"Solving linear system failed!\\n\"); return;}\n\n\t// copy result to mw.V\n  for (int i=0;i<nfree;i++)\n    V_w.row(i)=X.row(i);\n\n}\n\n  IGL_INLINE void Frame_field_deformer::computeXField(std::vector< Eigen::Matrix<double,3,2> > & XF)\n{\n  using namespace Eigen;\n  Matrix<double,3,3> P,PP,DG;\n\tXF.resize(F.rows());\n\n  for (int i=0;i<F.rows();i++)\n\t{\n\t\tint i0,i1,i2;\n\t\t// indexes of vertices of face i\n\t\ti0 = F(i,0); i1 = F(i,1); i2 = F(i,2);\n\n\t\t// input frame\n\t\tP.col(0) = (V.row(i1)-V.row(i0)).transpose();\n\t\tP.col(1) = (V.row(i2)-V.row(i0)).transpose();\n\t\tP.col(2) = P.col(0).cross(P.col(1));\n\n\t\t// output triangle brought to origin\n\t\tPP.col(0) = (V_w.row(i1)-V_w.row(i0)).transpose();\n\t\tPP.col(1) = (V_w.row(i2)-V_w.row(i0)).transpose();\n\t\tPP.col(2) = PP.col(0).cross(PP.col(1));\n\n\t\t// deformation gradient\n\t\tDG = PP * P.inverse();\n\t\tXF[i] = DG * FF[i];\n\t}\n}\n\n// computes in WW the ideal warp at each tri to make the frame field a cross\n  IGL_INLINE void Frame_field_deformer::compute_idealWarp(std::vector< Eigen::Matrix<double,3,3> > & WW)\n{\n  using namespace Eigen;\n\n  WW.resize(F.rows());\n\tfor (int i=0;i<(int)FF.size();i++)\n\t{\n\t\tVector3d v0,v1,v2;\n\t\tv0 = FF[i].col(0);\n\t\tv1 = FF[i].col(1);\n\t\tv2=v0.cross(v1); v2.normalize();\t\t\t// normal\n\n\t\tMatrix3d A,AI;\t\t\t\t\t\t\t\t// compute affine map A that brings:\n\t\tA <<    v0[0], v1[0], v2[0],\t\t\t\t//\tfirst vector of FF to x unary vector\n    v0[1], v1[1], v2[1],\t\t\t\t//\tsecond vector of FF to xy plane\n    v0[2], v1[2], v2[2];\t\t\t\t//\ttriangle normal to z unary vector\n\t\tAI = A.inverse();\n\n\t\t// polar decomposition to discard rotational component (unnecessary but makes it easier)\n\t\tEigen::JacobiSVD<Matrix<double,3,3> > svd(AI, Eigen::ComputeFullU | Eigen::ComputeFullV );\n\t\t//Matrix<double,3,3>  au = svd.matrixU();\n\t\tMatrix<double,3,3>  av = svd.matrixV();\n\t\tDiagonalMatrix<double,3>\tas(svd.singularValues());\n\t\tWW[i] = av*as*av.transpose();\n\t}\n}\n\n}\n\n\nIGL_INLINE void igl::frame_field_deformer(\n  const Eigen::MatrixXd& V,\n  const Eigen::MatrixXi& F,\n  const Eigen::MatrixXd& FF1,\n  const Eigen::MatrixXd& FF2,\n  Eigen::MatrixXd&       V_d,\n  Eigen::MatrixXd&       FF1_d,\n  Eigen::MatrixXd&       FF2_d,\n  const int              iterations,\n  const double           lambda,\n  const bool             perturb_initial_guess)\n{\n  using namespace Eigen;\n  // Solvers\n  Frame_field_deformer deformer;\n\n  // Init optimizer\n  deformer.init(V, F, FF1, FF2, lambda, perturb_initial_guess ? 0.1 : 0);\n\n  // Optimize\n  deformer.optimize(iterations,true);\n\n  // Copy positions\n  V_d = deformer.V_w;\n\n  // Allocate\n  FF1_d.resize(F.rows(),3);\n  FF2_d.resize(F.rows(),3);\n\n  // Copy frame field\n  for(unsigned i=0; i<deformer.XF.size(); ++i)\n  {\n    FF1_d.row(i) = deformer.XF[i].col(0);\n    FF2_d.row(i) = deformer.XF[i].col(1);\n  }\n}\n\n#ifdef IGL_STATIC_LIBRARY\n// Explicit template specialization\n#endif\n", "meta": {"hexsha": "f3c70ce764ce18b8bac2c27fe9da314128b426cb", "size": 13153, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Code/include/igl/frame_field_deformer.cpp", "max_stars_repo_name": "FabianRepository/SinusProject", "max_stars_repo_head_hexsha": "48d68902ccd83f08c4d208ba8e0739a8a1252338", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 35.0, "max_stars_repo_stars_event_min_datetime": "2017-04-07T22:49:41.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-03T13:59:20.000Z", "max_issues_repo_path": "Code/include/igl/frame_field_deformer.cpp", "max_issues_repo_name": "FabianRepository/SinusProject", "max_issues_repo_head_hexsha": "48d68902ccd83f08c4d208ba8e0739a8a1252338", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-08-04T22:39:02.000Z", "max_issues_repo_issues_event_max_datetime": "2020-08-05T21:02:47.000Z", "max_forks_repo_path": "Code/include/igl/frame_field_deformer.cpp", "max_forks_repo_name": "FabianRepository/SinusProject", "max_forks_repo_head_hexsha": "48d68902ccd83f08c4d208ba8e0739a8a1252338", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2019-03-11T19:26:53.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-04T07:17:10.000Z", "avg_line_length": 31.9247572816, "max_line_length": 192, "alphanum_fraction": 0.6360526116, "num_tokens": 4043, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6477982179521105, "lm_q2_score": 0.47657965106367595, "lm_q1q2_score": 0.3087274486712879}}
{"text": "#ifndef GRID_H_\n#define GRID_H_\n\n//#include <Python.h>\n#include <random>\n#include <vector>\n#include <unordered_map>\n#include <unordered_set>\n#include <boost/functional/hash.hpp>\n\n#include \"config.h\"\n#include \"Game.h\"\n#include \"pole.h\"\n#include \"drive.h\"\n#include \"net/network.hpp\"\n#include \"computation_graph.hpp\"\n\nusing namespace net;\n\ntypedef std::unordered_map<int, std::pair<double,double>> partial_states; // conjunction of ranges\ntypedef std::vector<partial_states> unsafes;  // disjunction of conjunctions of ranges\ntypedef std::vector<std::pair<double,double>> whole_states;\n\ntemplate < typename SEQUENCE > struct seq_hash\n{\n    std::size_t operator() ( const SEQUENCE& seq ) const\n    {\n        std::size_t hash = 0 ;\n        boost::hash_range( hash, seq.begin(), seq.end() ) ;\n        return hash ;\n    }\n};\n\ntemplate < typename SEQUENCE, typename T >\nusing sequence_to_data_map = std::unordered_map< SEQUENCE, T, seq_hash<SEQUENCE> > ;\n\nint binary_search(std::vector<double> v, double data) {\n    auto it = std::upper_bound(v.begin(), v.end(), data);\n    if (it == v.begin()) {\n    \treturn 0;\n    } else if (it == v.end()) {\n    \treturn v.size()-2;\n    } else {\n    \tstd::size_t index = std::distance(v.begin(), it);\n        return index-1;\n    }   \n}\n\nclass Grid {// abstract a world into grids\nprivate:\n\tvoid enumerateStateConfiguration (int i, std::vector<std::vector<int>>& stateconfigs) {\n\t\tstd::cout << \"enumerateStateConfiguration i = \" << i << \"\\n\";\n\t\tif (i == dimensions.size() - 1) {\n\t\t\tfor (int k = 0; k < dimensions[i].size() - 1; k++) {\n\t\t\t\tstd::vector<int> nv;\n\t\t\t\tnv.push_back(k);\n\t\t\t\tstateconfigs.push_back(nv);\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\n\t\tenumerateStateConfiguration (i+1, stateconfigs);\n\n\t\tint n = stateconfigs.size();\n\t\tfor (int j = 0; j < n; j++) {\n\t\t\tstateconfigs[j].insert (stateconfigs[j].begin(), 0);\n\t\t}\n\t\tfor (int k = 1; k < dimensions[i].size() - 1; k++) {\n\t\t\tfor (int j = 0; j < n; j++) {\n\t\t\t\tstd::vector<int> nv;\n\t\t\t\tnv.insert(nv.begin(), stateconfigs[j].begin(), stateconfigs[j].end());\n\t\t\t\tnv[0] = k;\n\t\t\t\tstateconfigs.push_back(nv);\n\t\t\t}\n\t\t}\n\t}\n\n\tbool empty_range (std::pair<double,double> arg1, std::pair<double,double> arg2) {\n\t\tstd::pair<double,double> intersection = { std::max(arg1.first, arg2.first), std::min(arg1.second, arg2.second) };\n\t\treturn (intersection.second <= intersection.first);\n\t}\n\n\tbool check_range (whole_states st, whole_states pst) {\n\t\tfor (int i = 0; i < st.size(); i++) {\n\t\t\tif (empty_range (st[i], pst[i])) \n\t\t\t\treturn false;\n\t\t}\n\t\treturn true;\n\t}\n\n\tbool check_range (whole_states st, partial_states pst) {\n\t\tfor (int i = 0; i < st.size(); i++) {\n\t\t\tif (pst.find(i) != pst.end() && empty_range (st[i], pst[i])) \n\t\t\t\treturn false;\n\t\t}\n\t\treturn true;\n\t}\n\n\tbool check_range (whole_states st, unsafes usfs) {\n\t\tfor (int i = 0; i < usfs.size(); i++) {\n\t\t\tif (check_range (st, usfs[i]))\n\t\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}\n\n\tstd::vector<double> stepGame (std::vector<double> gamestate) {\n\t\tgame->setGameState (gamestate);\n\t\t\n\t\t/*Vector vec;\n        vec.resize (game->inputs());\n        for (int i = 0; i < game->inputs(); i++) {\n        \tvec[i] = gamestate[i];\n        }\n        const auto& result = graph->forward(vec);\n        // greedy algorithm that generates the next action.\n        int row, col;\n        result.maxCoeff(&row,&col);\n        game->step (row);*/\n\n\t\tdouble x = gamestate[0];\n\t\tdouble gamma = gamestate[1];\n\t\tint row;\n  \t\tif (x <= -1.21205854416)\n    \t\trow = 0;\n  \t\telse\n    \t\tif (gamma <= 0.137111499906)\n      \t\t\trow = 2;\n    \t\telse\n      \t\t\tif (x <= 0.387143492699)\n        \t\t\trow = 0;\n      \t\t\telse\n        \t\t\trow = 1;\n        game->step(row);\n        return game->getGameState();\n\t}\n\npublic:\n\t// e.g. x  : -0.1, 0, 0.1 yields (-0.1, 0), (0, 0.1) \n\t// e.g. dx : -0.1, 0, 0.1 yields (-0.1, 0), (0, 0.1)\n\t// e.g. t  : -0.1, 0, 0.1 yields (-0.1, 0), (0, 0.1)\n\tstd::vector<std::vector<double>> dimensions;\n\n\tstd::unordered_map<int, std::vector<int>> index_to_coords;\n\tsequence_to_data_map<std::vector<int>, int> coords_to_index;\n\n\tstd::vector<int> error_states;\n\tstd::unordered_set<int> error_set;\n\tstd::vector<int> init_states;\n\n\t// Number of states\n\tint S;\n\t// Number of actions\n\tint A;\n\t// Pointer to a game instance\n\tGame* game;\n\t// Pointer to a neurual network\n\tComputationGraph* graph;\n\n\tGrid (Game& game, ComputationGraph& graph, \n\t\t\tstd::vector<std::vector<double>>& dimensions, whole_states& init_zones, unsafes& error_zones) {\n\t\t(this->dimensions).insert((this->dimensions).end(), dimensions.begin(), dimensions.end());\n\t\tthis->game = &game;\n\t\tthis->graph = &graph;\n\t\tthis->A = game.actions();\n\n\t\tstd::vector<std::vector<int>> stateconfigs;\n\t\tstd::cout << \"Discretizing state space ...\\n\";\n\t\tenumerateStateConfiguration (0, stateconfigs);\n\t\tstd::cout << \"State space discretized\\n\";\n\t\tS = 0;\n\t\tfor (int i = 0; i < stateconfigs.size(); i++) {\n\t\t\tstd::cout << \"(\";\n\t\t\tfor (int ind : stateconfigs[i])\n\t\t\t\tstd::cout << ind << \" \";\n\t\t\tstd::cout << \") is mapped to \" << i << \"\\n\";\n\t\t\tindex_to_coords.insert (std::make_pair (S, stateconfigs[i]));\n\t\t\tcoords_to_index.insert (std::make_pair (stateconfigs[i], S));\n\t\t\tS ++;\n\n\t\t\twhole_states state;\n\t\t\tfor (int j = 0; j < stateconfigs[i].size(); j++) {\n\t\t\t\tdouble start = dimensions[j][stateconfigs[i][j]];\n\t\t\t\tdouble end = dimensions[j][stateconfigs[i][j]+1];\n\t\t\t\tstate.push_back(std::make_pair(start,end));\n\t\t\t}\n\t\t\tif (check_range(state, error_zones)) {\n\t\t\t\terror_states.push_back(i);\n\t\t\t\terror_set.insert(i);\n\t\t\t}\n\t\t\tif (check_range(state, init_zones)) {\n\t\t\t\tinit_states.push_back(i);\n\t\t\t}\n\t\t}\n\t}\n\n\t// An observation is converted to the state of our world.\n\t// e.g. (x:-002, dx:0.05, t : 0.1)\n\tint observation_to_index (std::vector<double> observation) {\n\t\t//std::cout << \"Transitioning to (\";\n\t\t//for (int j = 0; j < observation.size(); j++) {\n\t\t//\tstd::cout << observation[j];\n\t\t//}\n\t\t//std::cout << \")\\n\";\n\n\t\tstd::vector<int> coord;\n\t\tfor (int i = 0; i < observation.size(); i++) {\n\t\t\tdouble v = observation[i];\n\t\t\tint ind = binary_search (dimensions[i], v);\n\t\t\tcoord.push_back(ind);\n\t\t}\n\n\t\t//std::cout << \"Transitioning to in coords (\";\n\t\t//for (int j = 0; j < coord.size(); j++) {\n\t\t//\tstd::cout << coord[j];\n\t\t//}\n\t\t//std::cout << \")\\n\";\n\n\t\tint index = coords_to_index[coord];\n\t\treturn index;\n\t}\n\n\t// A state of our world is mapped back to a range of possible observations.\n\tstd::vector<int> index_to_observation_range (int state) {\n\t\treturn index_to_coords[state];\n\t} \n\n\t// Build the tranision relations of states in our world.\n\tvoid build_transitions (int n_samples, std::unordered_map<int, std::unordered_map<int, double>>& transitionCounts) {\n\t\tstd::cout << \"Building probablisitic transitions about all states\\n\";\n\t\tfor (int i = 0; i < S; i++) {\n\t\t\tif (error_set.find(i) != error_set.end()) // No tranisition exploration for unsafe states.\n\t\t\t\tcontinue;\n\t\t\tstd::vector<int> ranges = index_to_observation_range(i);\n\t\t\t//std::cout << \"Transitioning from (\";\n\t\t\t//for (int j = 0; j < ranges.size(); j++) {\n\t\t\t//\tstd::cout << ranges[j];\n\t\t\t//}\n\t\t\t//std::cout << \")\\n\";\n\t\t\tint iteri = 0;\n\t\t\tunsigned seed = std::chrono::system_clock::now().time_since_epoch().count();\n    \t\tstd::mt19937 generator (seed);\n    \t\tstd::uniform_real_distribution<double> uniform01(0.0, 1.0);\n    \t\tstd::vector<std::vector<double>> points;\n\t\t\twhile (iteri < n_samples) {\n\t\t\t\t// Sample a point within the range of intersted.\n\t\t\t\tstd::vector<double> point;\n\t\t\t\tfor (int j = 0; j < ranges.size(); j++) {\n\t\t\t\t\tdouble start = dimensions[j][ranges[j]];\n\t\t\t\t\tdouble end = dimensions[j][ranges[j]+1];\n\n\t\t\t\t\tdouble sv =  (end - start) * uniform01(generator) + start;\n\t\t\t\t\tpoint.push_back(sv);\n\t\t\t\t}\n\t\t\t\t//std::cout << \"Samping a value in range (\";\n\t\t\t\t//\tfor (int j = 0; j < point.size(); j++) {\n\t\t\t\t//\tstd::cout << point[j];\n\t\t\t\t//}\n\t\t\t\t//std::cout << \")\\n\";\n\t\t\t\tpoints.push_back(point);\n\t\t\t\titeri++;\n\t\t\t}\n\t\t\tstd::unordered_map<int, double> currTransitionCount;\n\t\t\tfor (int j = 0; j < n_samples; j++) {\n\t\t\t\tint s = observation_to_index(stepGame(points[j]));\n\t\t\t\t//std::cout << \"sampled a tranision from \" << i << \" to \" << s << \"\\n\";\n\t\t\t\tcurrTransitionCount[s]++;\n\t\t\t}\n\t\t\tfor( auto& n : currTransitionCount ) {\n        \t\tn.second /= n_samples;\n    \t\t}\n    \t\ttransitionCounts[i] = currTransitionCount;\n\t\t}\n\t}\n\n\tvoid outputTraisitionCounts (std::unordered_map<int, std::unordered_map<int, double>>& transitionCounts) {\n\t\tstd::string datafile = \"./data/optimal_policy\";\n\t\tstd::fstream evl(datafile, std::fstream::out);\n\t\tfor (int i = 0; i < S; i++) {\n\t\t\tfor (int j = 0; j < S; j++) {\n\t\t\t\tif (transitionCounts[i].find(j) != transitionCounts[i].end())\n\t\t\t\t\tevl << i << \" \" << j << \" \" << transitionCounts[i][j] << \"\\n\";\t\n\t\t\t\telse \n\t\t\t\t\tevl << i << \" \" << j << \" 0\\n\";\t\n\t\t\t}\n\t\t}\n\t\tevl.close();\n\t}\n\n\tvoid outputInitial () {\n\t\tstd::string datafile = \"./data/start\";\n\t\tstd::fstream evl(datafile, std::fstream::out);\n\t\tfor (int i = 0; i < init_states.size(); i++)\n\t\t\tevl << init_states[i] << \"\\n\";\n\t\tevl.close();\n\t}\n\n\tvoid outputUnsafe () {\n\t\tstd::string datafile = \"./data/unsafe\";\n\t\tstd::fstream evl(datafile, std::fstream::out);\n\t\tfor (int i = 0; i < error_states.size(); i++)\n\t\t\tevl << error_states[i] << \"\\n\";\n\t\tevl.close();\n\t}\n\n\tvoid createSingleInitial (std::unordered_map<int, std::unordered_map<int, double>>& transitionCounts) {\n\t\tstd::unordered_map<int, double> currTransitionCount;\n\t\tfor (int i = 0; i < init_states.size(); i++) {\n\t\t\tcurrTransitionCount[init_states[i]] = ((double)1.0 / (init_states.size()));\n\t\t}\n\t\ttransitionCounts[S] = currTransitionCount;\n\t\tS++;\n\t}\t\n\n\tvoid createSingleFinal (std::unordered_map<int, std::unordered_map<int, double>>& transitionCounts) {\n\t\tfor (int i = 0; i < error_states.size(); i++) {\n\t\t\tstd::unordered_map<int, double> currTransitionCount;\n\t\t\tcurrTransitionCount[S] = 1.0;\n\t\t\ttransitionCounts[error_states[i]] = currTransitionCount;\n\t\t}\n\t\tstd::unordered_map<int, double> currTransitionCount;\n\t\tcurrTransitionCount[S] = 1.0;\n\t\ttransitionCounts[S] = currTransitionCount;\n\t\tS++;\n\t}\n\n\tvoid outputStateSpace () {\n\t\tstd::string datafile = \"./data/state_space\";\n\t\tstd::fstream evl(datafile, std::fstream::out);\n\t\tevl << \"states\\n\";\n\t\tevl << S << \"\\n\";\n\t\tevl << \"actions\\n\";\n\t\tevl << A;\n\t\tevl.close();\n\t} \n\n\t// Verify the safety of our world.\n\tdouble verify (int n_samples, int steps) {\n\t\tstd::cout << \"Verify generated probablisitic system\\n\";\n\t\toutputInitial ();\n\t\toutputUnsafe ();\n\n\t\tstd::unordered_map<int, std::unordered_map<int, double>> transitionCounts;\n\t\tbuild_transitions (n_samples, transitionCounts);\n\t\t// Create a single intial state and final state\n\t\tcreateSingleInitial(transitionCounts);\n\t\tcreateSingleFinal(transitionCounts);\n\t\t// export policy from transitionCounts\n\t\toutputTraisitionCounts (transitionCounts);\n\n\t\t// Output the state space.\n\t\toutputStateSpace();\n\n\t\tdouble verification_result = 0.0;\n\t\t\n\t\t// call prism to construct a probablisitic tranision system.\n\t\t/*setenv(\"PYTHONPATH\", \".\", 1);\n\t\tPy_Initialize();\n\n\t\tPyObject *pName = PyString_FromString(\"prism\");\n    \tPyObject *pModule = PyImport_Import(pName);\n    \tPy_DECREF(pName);\n\n    \tif (pModule != NULL) {\n        \tPyObject *pFunc = PyObject_GetAttrString(pModule, \"model_check\");\n        \tif (pFunc && PyCallable_Check(pFunc)) {\n        \t\tPyObject *pArgs = PyTuple_New(2);\n        \t\tPyObject *pValue1 = PyInt_FromLong(steps);\n        \t\tPyObject *pValue2 = PyInt_FromLong(S);\n        \t\tPyTuple_SetItem(pArgs, 0, pValue1);\n        \t\tPyTuple_SetItem(pArgs, 1, pValue2);\n\n            \tPyObject *pValue = PyObject_CallObject(pFunc, pArgs);\n            \tPy_DECREF(pArgs);\n            \tif (pValue != NULL) {\n            \t\tverification_result = PyFloat_AsDouble(pValue);\n                \tprintf(\"Result of call: %lf\\n\", verification_result);\n                \tPy_DECREF(pValue);\n            \t}\n            \telse {\n                \tPy_DECREF(pFunc);\n                \tPy_DECREF(pModule);\n                \tPyErr_Print();\n                \tfprintf(stderr,\"Call Prism model_check failed\\n\");\n                \treturn 0;\n            \t}\n        \t} else {\n            \tif (PyErr_Occurred())\n                \tPyErr_Print();\n            \tfprintf(stderr, \"Cannot find model_check function\\n\");\n            \treturn 0;\n        \t}\n        \tPy_XDECREF(pFunc);\n        \tPy_DECREF(pModule);\n        } else {\n        \tPyErr_Print();\n        \tfprintf(stderr, \"Failed to load prism\\n\");\n        \treturn 0;\n        }\n        Py_Finalize();*/\n\n        return verification_result;\n\t}\n\n};\n\nint main_verify(int argc, char** argv)\n{\n\tstd::string model(argv[1]);\n\tNetwork agent;\n\tagent.load (model);\n\tComputationGraph graph(agent);\n\t//Pole pole; \n\tDrive pole;\n\tstd::vector<std::vector<double>> dimensions;\n\t//double xd[] = {-1.2, -1.0, 0, 1.0, 1.2};\n\t//double xd[] = {-1.2,-1.0,-0.5,-0.4,-0.2,-0.000001,0.000001,0.2,0.4,0.5,1.0,1.2};\n\t// -- _that_is_within_safe_angle_ -- double xd[] = {-1.2,-1.0,-0.5,-0.4,-0.3,-0.2,-0.1,-0.000001,0.000001,1.2};\n\t// -- nice-abstraction - double xd[] = {-1.2,-1.0,-0.9,-0.7,-0.5,-0.3,-0.1,-0.000001,0.000001,1.2};\n\t//double xd[] = {-1.2,-1.0,-0.9,-0.7,-0.5,-0.3,-0.1,-0.000001,0.000001,1.2};\n\tdouble xd[] = {-2.2,-2.0,-1.9,-1.8,-1.7,-1.6,-1.5,-1.4,-1.3,-1.21205854416,-1.1,-1.0,-0.9,-0.8,-0.7,-0.6,-0.5,-0.4,-0.3,-0.2,-0.1,-0.008,-0.006,-0.004,-0.002,0,0.002,0.004,0.006,0.008,0.1,0.2,0.387143492699,0.4,0.5,0.6,0.7,0.8,0.9,1.0,1.1,1.2,1.3,1.4,1.5,1.6,1.7,1.8,1.9,2.0,2.2};\n  \tstd::vector<double> dx (xd, xd + sizeof(xd) / sizeof(double));\n  \t//double dxd[] = {-1.0, -0.2, 0, 0.2, 1.0};\n  \t//double dxd[] = {-1.0,-0.09,-0.003,-0.002,-0.000001,0.000001,0.002,0.003,0.09,1.0};\n  \t// -- _that_is_within_safe_angle_ -- double dxd[] = {-1.0,-0.09,-0.005,-0.003,-0.002,-0.000001,0.000001,1.0};\n  \t// -- nice-abstraction - double dxd[] = {-0.1,-0.09,-0.009,-0.005,-0.003,-0.002,-0.000001,0.000001,0.1};\n  \t//double dxd[] = {-0.2,-0.1,-0.009,-0.005,-0.003,-0.002,-0.000001,0.000001,0.2};\n  \tdouble dxd[] = {-1.3,-1.2,-1.1,-1,-0.9,-0.8,-0.78539815,-0.6,-0.5,-0.4,-0.3,-0.2,-0.1,-0.008,-0.006,-0.004,-0.002,0,0.002,0.004,0.006,0.008,0.137111499906,0.2,0.3,0.4,0.5,0.6,0.78539815,0.8,0.9,1,1.1,1.2,1.3};\n  \tstd::vector<double> ddx (dxd, dxd + sizeof(dxd) / sizeof(double));\n  \t//double thetad[] = {-1.0, -0.026179938765, 0, 0.026179938765, 1.0};\n  \t//double thetad[] = {-1.0,-0.026179938765,-0.005,-0.003,-0.002,-0.000001,0.000001,0.002,0.003,0.005,0.026179938765,1.0};\n  \t// -- _that_is_within_safe_angle_ -- double thetad[] = {-1.0,-0.026179938765,-0.01,-0.003,-0.002,-0.000001,0.000001,1.0};\n  \t// -- nice-abstraction - double thetad[] = {-0.1,-0.026179938765,-0.01,-0.003,-0.002,-0.000001,0.000001,0.1};\n  \t//*** double thetad[] = {-0.1,-0.026179938765,-0.01,-0.003,-0.002,-0.000001,0.000001,0.1};\n  \t//*** std::vector<double> dtheta (thetad, thetad + sizeof(thetad) / sizeof(double));\n  \t//double dthetad[] = {-1.0, -0.02, 0, 0.02, 1.0};\n  \t//double dthetad[] = {-1.0,-0.1,-0.05,-0.02,-0.01745329251,0.01745329251,0.02,0.05,0.1,1.0};\n  \t// -- _that_is_within_safe_angle_ -- double dthetad[] = {-1.0,-0.1,-0.05,-0.02,-0.01745329251,0.01745329251,1.0};\n  \t// -- nice-abstraction - double dthetad[] = {-0.1,-0.05,-0.02,-0.01745329251,0.01745329251,0.1};\n  \t// *** double dthetad[] = {-0.1,-0.05,-0.02,-0.01745329251,0.01745329251,0.1};\n  \t// *** std::vector<double> ddtheta (dthetad, dthetad + sizeof(dthetad) / sizeof(double));\n\tdimensions.push_back(dx);\n\tdimensions.push_back(ddx);\n\t//dimensions.push_back(dtheta);\n\t//dimensions.push_back(ddtheta);\n\n\tunsafes error_zones;\n\t//partial_states e1;\n\t//e1[0] = std::make_pair(-2.2, -2.0);\n\t//error_zones.push_back(e1);\n\tpartial_states e2;\n\te2[0] = std::make_pair(2.0, 2.2);\n\terror_zones.push_back(e2);\t\n\t//partial_states e1;\n\t//e1[2] = std::make_pair(-1.0, -0.026179938765);\n\t//error_zones.push_back(e1);\n\t//partial_states e2;\n\t//e2[2] = std::make_pair(0.026179938765, 1.0);\n\t//error_zones.push_back(e2);\n\t//partial_states e3;\n\t//e3[0] = std::make_pair(-1.2, -1.0);\n\t//error_zones.push_back(e3);\n\t//partial_states e4;\n\t//e4[0] = std::make_pair(1.0, 1.2);\n\t//error_zones.push_back(e4);\n\n\twhole_states init_zones;\n\tinit_zones.push_back (std::make_pair(-1,1));\n\tinit_zones.push_back (std::make_pair(-0.78539815,0.78539815));\n\t//init_zones.push_back (std::make_pair(-0.000001,0.000001));\n\t//init_zones.push_back (std::make_pair(-0.000001,0.000001));\n\t//init_zones.push_back (std::make_pair(-0.000001,0.000001));\n\t//init_zones.push_back (std::make_pair(-0.01745329251,0.01745329251));\n\n\tGrid g(pole, graph, dimensions, init_zones, error_zones);\n\tg.verify (1000, 200);\n\treturn 0;\n}\n\n#endif /* GRID_H_ */", "meta": {"hexsha": "4b7fa9ab13492adc06a1407e47cf33ea38341788", "size": 16458, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/discritize.cpp", "max_stars_repo_name": "rowangithub/FastRL", "max_stars_repo_head_hexsha": "d0a554d7549948ba69336eae15ea181f28589465", "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/discritize.cpp", "max_issues_repo_name": "rowangithub/FastRL", "max_issues_repo_head_hexsha": "d0a554d7549948ba69336eae15ea181f28589465", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-07-24T18:19:52.000Z", "max_issues_repo_issues_event_max_datetime": "2019-07-24T18:19:52.000Z", "max_forks_repo_path": "src/discritize.cpp", "max_forks_repo_name": "rowangithub/FastRL", "max_forks_repo_head_hexsha": "d0a554d7549948ba69336eae15ea181f28589465", "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.2875, "max_line_length": 281, "alphanum_fraction": 0.6116782112, "num_tokens": 5471, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6584175005616829, "lm_q2_score": 0.4687906266262437, "lm_q1q2_score": 0.3086599526699965}}
{"text": "// Copyright András Vukics 2006–2020. Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE.txt)\n#include \"Qbit_.h\"\n\n#include \"ParsQbit.h\"\n\n#include <boost/bind.hpp>\n\n\nusing namespace mathutils; using std::make_shared;\n\n\nnamespace qbit {\n\n\n///////////\n//\n// Averaged\n//\n///////////\n\n\nAveraged::Averaged() \n  : Base(keyTitle,{\"rho00\",\"rho11\",\"real(rho10=<sigma>)\",\"imag(\\\")\"})\n{\n}\n\nconst Averaged::Averages Averaged::average_v(NoTime, const LazyDensityOperator& matrix) const\n{\n  auto averages(initializedAverages());\n  averages=matrix(0),matrix(1),real(matrix(1)(0)),imag(matrix(1)(0));\n  return averages;\n}\n\n\nnamespace {\n\n\nvoid sigmaJump(qbit::StateVectorLow& psi, double gamma_perpendicular)\n{\n  psi(0)=sqrt(2.*gamma_perpendicular)*psi(1);\n  psi(1)=0;\n}\n\n\nvoid sigma_zJump(qbit::StateVectorLow& psi, double gamma_parallel)\n{\n  double fact=sqrt(2.*gamma_parallel);\n  psi(0)*= fact; psi(1)*=-fact;\n}\n\n\ndouble dummyProba(const qbit::LazyDensityOperator&)\n{\n  return -1;\n}\n\n\n}\n\n\nLiouvilleanPhaseNoise::LiouvilleanPhaseNoise(double gamma_perpendicular, double gamma_parallel) \n  : structure::ElementLiouvilleanStrategies<1,2>(JumpStrategies(bind(sigmaJump  ,_1,gamma_perpendicular),\n                                                                bind(sigma_zJump,_1,gamma_parallel)),\n                                                 JumpRateStrategies(dummyProba),\n                                                 \"LossyQbitWithPhaseNoise\",{\"excitation loss\",\"phase noise\"})\n{}\n\n} // qbit\n\n////////////////\n//\n// Highest level\n//\n////////////////\n\n\nQbitBase::QbitBase(const RealFreqs& realFreqs, const ComplexFreqs& complexFreqs)\n  : ModeBase(2,realFreqs,complexFreqs,qbit::keyTitle), Averaged()\n{}\n\n#define TUPLE_delta(ISIP) RF{\"delta\",-imag(BOOST_PP_IF(ISIP,get_zI,get_zSch)()),1}\n#define TUPLE_eta CF{\"eta\",get_eta(),1}\n#define TUPLE_gammadelta(ISIP) CF{\"(gamma,delta)\",conj(BOOST_PP_IF(ISIP,get_zI,get_zSch)()),1}\n#define TUPLE_gamma RF{\"gamma\",real(get_zSch()),1}\n\nQbit::Qbit(const qbit::Pars& p)\n  : Exact(dcomp(0,-p.delta)),\n    QbitBase{TUPLE_delta(1)}\n{}\n\n\nQbitSch::QbitSch(const qbit::Pars& p)\n  : qbit::Hamiltonian<false>(dcomp(0,-p.delta),0),\n    QbitBase{TUPLE_delta(0)}\n{\n  getParsStream()<<\"Schroedinger picture.\\n\";\n}\n\n   \nPumpedQbit::PumpedQbit(const qbit::ParsPumped& p)\n  : qbit::Hamiltonian<true>(0,dcomp(0,-p.delta),p.eta),\n    QbitBase(TUPLE_delta(1),TUPLE_eta)\n{\n  getParsStream()<<\"Pumped.\\n\";\n}\n\n\nPumpedQbitSch::PumpedQbitSch(const qbit::ParsPumped& p)\n  : qbit::Hamiltonian<false>(dcomp(0,-p.delta),p.eta),\n    QbitBase(TUPLE_delta(0),TUPLE_eta)\n{\n  getParsStream()<<\"Pumped, Schroedinger picture.\\n\";\n}\n\n\nLossyQbit::LossyQbit(double delta, double gamma)\n  : qbit::Liouvillean(gamma),\n    Exact(dcomp(gamma,-delta)),\n    QbitBase{TUPLE_gammadelta(1)}\n{\n  getParsStream()<<\"Lossy.\\n\";\n}\n\n\nLossyQbitSch::LossyQbitSch(double delta, double gamma)\n  : qbit::Liouvillean(gamma),\n    qbit::Hamiltonian<false>(dcomp(gamma,-delta),0),\n    QbitBase{TUPLE_gamma,TUPLE_delta(0)}\n{\n  getParsStream()<<\"Lossy, Schroedinger picture.\\n\";\n}\n\n\nLossyQbitUIP::LossyQbitUIP(double delta, double gamma)\n  : qbit::Liouvillean(gamma),\n    qbit::Hamiltonian<true>(dcomp(gamma,0),dcomp(0,-delta),0),\n    QbitBase{TUPLE_gamma,TUPLE_delta(1)}\n{\n  getParsStream()<<\"Lossy, Unitary interaction picture.\\n\";\n}\n\n\nPumpedLossyQbit::PumpedLossyQbit(const qbit::ParsPumpedLossy& p)\n  : qbit::Liouvillean(p.gamma),\n    qbit::Hamiltonian<true>(0,dcomp(p.gamma,-p.delta),p.eta),\n    QbitBase{TUPLE_gammadelta(1),TUPLE_eta}\n{\n  getParsStream()<<\"PumpedLossy.\\n\";\n}\n\n\nPumpedLossyQbitUIP::PumpedLossyQbitUIP(const qbit::ParsPumpedLossy& p)\n  : qbit::Liouvillean(p.gamma),\n    qbit::Hamiltonian<true>(dcomp(p.gamma,0),dcomp(0,-p.delta),p.eta),\n    QbitBase({TUPLE_gamma,TUPLE_delta(1)},TUPLE_eta)\n{\n  getParsStream()<<\"PumpedLossy, Unitary interaction picture.\\n\";\n}\n\n\nPumpedLossyQbitSch::PumpedLossyQbitSch(const qbit::ParsPumpedLossy& p)\n  : qbit::Liouvillean(p.gamma),\n    qbit::Hamiltonian<false>(dcomp(p.gamma,-p.delta),p.eta),\n    QbitBase{TUPLE_gammadelta(0),TUPLE_eta}\n{\n  getParsStream()<<\"PumpedLossy, Schroedinger picture.\\n\";\n}\n\n\nLossyQbitWithPhaseNoise::LossyQbitWithPhaseNoise(double delta, double gamma, double gamma_parallel)\n  : Exact(dcomp(gamma,-delta)), // gamma_parallel does not contribute to the Hamiltonian\n    qbit::LiouvilleanPhaseNoise(gamma,gamma_parallel),\n    QbitBase(RF{\"gamma_parallel\",gamma_parallel,1},TUPLE_gammadelta(1))\n{\n  getParsStream()<<\"LossyWithPhaseNoise.\\n\";\n}\n\n\nLossyQbitWithPhaseNoiseUIP::LossyQbitWithPhaseNoiseUIP(double delta, double gamma, double gamma_parallel)\n  : qbit::Hamiltonian<true>(dcomp(gamma,0),dcomp(0,-delta),0),\n    qbit::LiouvilleanPhaseNoise(gamma,gamma_parallel),\n    QbitBase{RF{\"gamma_parallel\",gamma_parallel,1},TUPLE_gamma,TUPLE_delta(1)}\n{\n  getParsStream()<<\"LossyWithPhaseNoise, Unitary interaction picture.\\n\";\n}\n\nPumpedLossyQbitWithPhaseNoise::PumpedLossyQbitWithPhaseNoise(const qbit::ParsPumpedLossyPhaseNoise& p)\n  : qbit::Hamiltonian<true>(0,dcomp(p.gamma,-p.delta),p.eta),\n    qbit::LiouvilleanPhaseNoise(p.gamma,p.gamma_parallel),\n    QbitBase{RF{\"gamma_parallel\",p.gamma_parallel,1},TUPLE_gammadelta(1),TUPLE_eta}\n{\n  getParsStream()<<\"PumpedLossyWithPhaseNoise.\\n\";\n}\n\nPumpedLossyQbitWithPhaseNoiseUIP::PumpedLossyQbitWithPhaseNoiseUIP(const qbit::ParsPumpedLossyPhaseNoise& p)\n  : qbit::Hamiltonian<true>(dcomp(p.gamma,0),dcomp(0,-p.delta),p.eta),\n    qbit::LiouvilleanPhaseNoise(p.gamma,p.gamma_parallel),\n    QbitBase{RF{\"gamma_parallel\",p.gamma_parallel,1},TUPLE_gamma,TUPLE_delta(1)}\n{\n  getParsStream()<<\"PumpedLossyWithPhaseNoise, Unitary interaction picture.\\n\";\n}\n\n#undef  TUPLE_gamma\n#undef  TUPLE_gammadelta\n#undef  TUPLE_eta\n#undef  TUPLE_delta\n\n//////////\n//\n// Helpers\n//\n//////////\n\nnamespace qbit {\n\n\nPtr make(const ParsPumpedLossy& p, QM_Picture qmp)\n{\n  switch (qmp) {\n  case QMP_IP  :\n    if (p.gamma==0 && std::abs(p.eta)==0)\n      return std::make_shared<Qbit            >(p);\n    if (p.gamma==0)\n      return std::make_shared<PumpedQbit      >(p);\n    if (std::abs(p.eta)==0)\n      return std::make_shared<LossyQbit       >(p);\n    return std::make_shared<PumpedLossyQbit   >(p);\n  case QMP_UIP :\n    if (p.gamma==0 && std::abs(p.eta)==0)\n      return std::make_shared<QbitUIP         >(p);\n    if (p.gamma==0)\n      return std::make_shared<PumpedQbitUIP   >(p);\n    if (std::abs(p.eta)==0)\n      return std::make_shared<LossyQbitUIP    >(p);\n    return std::make_shared<PumpedLossyQbitUIP>(p);\n  case QMP_SCH :\n    ;\n  }\n  if (p.gamma==0 && std::abs(p.eta)==0)\n    return std::make_shared<QbitSch         >(p);\n  if (p.gamma==0)\n    return std::make_shared<PumpedQbitSch   >(p);\n  if (std::abs(p.eta)==0)\n    return std::make_shared<LossyQbitSch    >(p);\n  return std::make_shared<PumpedLossyQbitSch>(p);\n}\n\n\nPtr make(const ParsPumpedLossyPhaseNoise& p, QM_Picture qmp)\n{\n  if (p.gamma_parallel) {\n    if (qmp==QMP_UIP) {\n      if (std::abs(p.eta))\n        return std::make_shared<PumpedLossyQbitWithPhaseNoiseUIP>(p);\n      else\n        return std::make_shared<      LossyQbitWithPhaseNoiseUIP>(p);\n    }\n    else {\n      if (std::abs(p.eta))\n        return std::make_shared<PumpedLossyQbitWithPhaseNoise>(p);\n      else\n        return std::make_shared<      LossyQbitWithPhaseNoise>(p);\n    }\n  }\n  return make(static_cast<const ParsPumpedLossy&>(p),qmp);\n}\n\n\nconst Tridiagonal sigmadagsigmaop()\n{\n  return mode::nop(make_shared<QbitBase>());\n}\n\n\nStateVector init(dcomp psi1)\n{\n  StateVector res(2);\n  res(0)=sqrt(1-sqrAbs(psi1)); res(1)=psi1;\n  return res;\n}\n\n\n} // qbit\n", "meta": {"hexsha": "630f7b639dbfcb0e4a2a1cca1c996162f00d3b36", "size": 7600, "ext": "cc", "lang": "C++", "max_stars_repo_path": "CPPQEDelements/frees/Qbit.cc", "max_stars_repo_name": "bartoszek/cppqed", "max_stars_repo_head_hexsha": "712b601e377642885f40cbf8a65eb1525360f654", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "CPPQEDelements/frees/Qbit.cc", "max_issues_repo_name": "bartoszek/cppqed", "max_issues_repo_head_hexsha": "712b601e377642885f40cbf8a65eb1525360f654", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "CPPQEDelements/frees/Qbit.cc", "max_forks_repo_name": "bartoszek/cppqed", "max_forks_repo_head_hexsha": "712b601e377642885f40cbf8a65eb1525360f654", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.7605633803, "max_line_length": 132, "alphanum_fraction": 0.6853947368, "num_tokens": 2386, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6076631698328916, "lm_q2_score": 0.5078118642792044, "lm_q1q2_score": 0.3085785671266515}}
{"text": "#include <scomplex/simplicial_complex.hpp>\n#include <scomplex/types.hpp>\n\n#include <iterator>  // for debuging purposes\n\n#include <gudhi/Hasse_complex.h>\n#include <gudhi/Simplex_tree.h>\n#include <Eigen/Dense>\n#include <Eigen/Sparse>\n\n#include <cmath>\n#include <functional>\n#include <memory>  // smart pointers\n#include <tuple>\n\n#include <iostream>\nnamespace gsimp {\n\n// hasse diagram structures\nstruct hasse_node {\n    std::pair< int, size_t > handle;\n    std::vector< std::shared_ptr< hasse_node > > cofaces;\n\n    hasse_node(std::pair< int, size_t > _handle) { handle = _handle; }\n\n    void add_coface(std::shared_ptr< hasse_node >& node) {\n        cofaces.push_back(node);\n    }\n};\n\nstruct hasse_diag {\n    std::vector< std::vector< std::shared_ptr< hasse_node > > > cells;\n    std::vector< std::vector< bool > > cells_c;\n\n    hasse_diag(){};\n\n    hasse_diag(simplicial_complex& s_comp) {\n        // vector of dimension d\n        for (int d = 0; d <= s_comp.dimension(); d++) {\n            size_t lv_s = s_comp.get_level_size(d);\n            std::vector< std::shared_ptr< hasse_node > > lv(lv_s);\n            cells.push_back(lv);\n\n            std::vector< bool > c(lv_s, false);\n            cells_c.push_back(c);\n        }\n\n        for (int d = s_comp.dimension(); d > 0; d--) {\n            for (size_t face_i = 0; face_i < s_comp.get_level_size(d);\n                 face_i++) {\n                std::shared_ptr< hasse_node > face_ptr =\n                    get_face(d, face_i, true);\n\n                std::vector< std::pair< int, size_t > > faces =\n                    s_comp.get_bdry_and_ind_index(d, face_i);\n                for (auto b_face_i : faces) {\n                    size_t b_face = std::get< 1 >(b_face_i);\n                    std::shared_ptr< hasse_node > b_face_ptr =\n                        get_face(d - 1, b_face, true);\n                    b_face_ptr->add_coface(face_ptr);\n                }\n            }\n        }\n        // no further need, free up the space\n        cells_c.clear();\n    }\n\n    std::shared_ptr< hasse_node > get_face(int d, size_t face_i,\n                                           bool building = false) {\n        std::shared_ptr< hasse_node > face;\n        if (building && cells_c[d][face_i])\n            face = cells[d][face_i];\n        else {\n            if (building) cells_c[d][face_i] = true;\n\n            cells[d][face_i] = std::make_shared< hasse_node >(\n                std::pair< int, size_t >(d, face_i));\n            face = cells[d][face_i];\n        }\n        return face;\n    }\n\n    std::vector< size_t > get_coface_i(int d, size_t face_i) {\n        auto node = cells[d][face_i];\n        std::vector< size_t > cofaces;\n        for (auto v : node->cofaces)\n            cofaces.push_back(std::get< 1 >(v->handle));\n        return cofaces;\n    }\n};\n\nstruct simplicial_complex::impl {\n    // auxiliary types\n    struct SimpleOptions : Gudhi::Simplex_tree_options_full_featured {\n        typedef size_t Vertex_handle;\n    };\n\n    typedef Gudhi::Simplex_tree< SimpleOptions > simp_tree;\n    typedef Gudhi::Simplex_tree< SimpleOptions >::Simplex_handle simp_handle;\n    typedef std::vector< simp_handle* > level_t;\n    typedef std::vector< std::unique_ptr< level_t > > levels_t;\n\n    // member variables\n    std::vector< point_t > points;\n    simp_tree simplices;\n    std::vector< matrix_t > boundary_matrices;\n    levels_t levels;\n\n    bool has_hasse;\n    hasse_diag incidence;\n\n    impl(std::vector< point_t >& arg_points, std::vector< cell_t >& arg_tris)\n        : points(arg_points) {\n        // create the simplex tree\n        for (auto tri : arg_tris) {\n            // removed deduping to try to make this a bit faster\n            // ... it did cut time down about 10%, so ...\n            simplices.insert_simplex_and_subfaces(tri);\n            int d = tri.size() - 1;\n            if (simplices.dimension() < d) simplices.set_dimension(d);\n        }\n\n        // assign a key to each simplex in each level\n        std::vector< size_t > count(simplices.dimension() + 1, 0);\n        for (int i = 0; i < simplices.dimension() + 1; ++i) {\n            level_t* level = new level_t();\n            levels.push_back(std::unique_ptr< level_t >(level));\n        }\n\n        auto simplex_range = simplices.complex_simplex_range();\n        for (auto s : simplex_range) {\n            int d = simplices.dimension(s);\n            simplices.assign_key(s, count[d]++);\n            levels[d]->push_back(new simp_handle(s));\n        }\n    }\n\n    ~impl() {\n        // get rid of the levels so they won't dangle\n        for (int i = levels.size(); i <= 0; --i) levels[i].reset();\n    };\n\n    size_t get_level_size(int level) { return levels[level]->size(); }\n\n    // calculate the index of s_1 in the boundary of s_2\n    int boundary_index(simp_handle s_1, simp_handle s_2) {\n        auto it_1 = simplices.simplex_vertex_range(s_1).begin();\n        auto end_1 = simplices.simplex_vertex_range(s_1).end();\n        //\n        auto it_2 = simplices.simplex_vertex_range(s_2).begin();\n        //\n        int orient = 0;\n        int unmatch = 0;\n        //\n        for (int p = 0; p <= simplices.dimension(s_2); p++) {\n            if (*it_1 != *it_2) {\n                orient = p++;\n                unmatch++;\n            } else {\n                if (it_1 != end_1) it_1++;\n                it_2++;\n            }\n        }\n        return pow(-1, orient);\n    }\n\n    std::vector< size_t > dedupe_vec(std::vector< size_t >& vec) {\n        std::set< size_t > no_reps;\n        std::vector< size_t > no_reps_list;\n        for (size_t el : vec) {\n            no_reps.insert(el);\n        }\n        for (size_t el : no_reps) {\n            no_reps_list.push_back(el);\n        }\n        return no_reps_list;\n    }\n\n    void calculate_matrices() {\n        boundary_matrices = std::vector< matrix_t >();\n        for (int k = 0; k < simplices.dimension(); k++) {\n            boundary_matrices.push_back(\n                matrix_t(get_level_size(k), get_level_size(k + 1)));\n        }\n        for (auto s : simplices.complex_simplex_range()) {\n            int j = simplices.key(s);\n            for (auto bs : simplices.boundary_simplex_range(s)) {\n                int i = simplices.key(bs);\n                int k = simplices.dimension(bs);\n                boundary_matrices[k].coeffRef(i, j) = boundary_index(bs, s);\n            }\n        }\n    }\n\n    std::vector< cell_t > get_level(int level) {\n        std::vector< cell_t > level_cells;\n        for (auto simp : *levels[level]) {\n            cell_t v_simp;\n            for (auto v : simplices.simplex_vertex_range(*simp)) {\n                v_simp.push_back(v);\n            }\n            level_cells.push_back(v_simp);\n        }\n        return level_cells;\n    }\n\n    simp_handle index_to_handle(int d, size_t tau) {\n        return *(*(levels[d]))[tau];\n    }\n\n    size_t handle_to_index(simp_handle tau) { return simplices.key(tau); }\n\n    simp_handle cell_to_handle(cell_t tau) {\n        auto sh = simplices.find(tau);\n        return sh;\n    }\n\n    cell_t handle_to_cell(simp_handle tau) {\n        cell_t cell;\n        for (auto v : simplices.simplex_vertex_range(tau)) cell.push_back(v);\n        return cell;\n    }\n\n};  // struct impl\n\nstd::vector< std::pair< int, cell_t > > simplicial_complex::get_bdry_and_ind(\n    cell_t cell) {\n    impl::simp_handle simp = p_impl->cell_to_handle(cell);\n    auto c_boundary = p_impl->simplices.boundary_simplex_range(simp);\n    std::vector< std::pair< int, cell_t > > boundary_and_indices;\n    for (auto face : c_boundary)\n        boundary_and_indices.push_back(              //\n            std::make_pair< int, cell_t >(           //\n                p_impl->boundary_index(face, simp),  //\n                p_impl->handle_to_cell(face)));      //\n    return boundary_and_indices;\n};\n\nstd::vector< std::pair< int, size_t > >\nsimplicial_complex::get_bdry_and_ind_index(int d, size_t cell) {\n    impl::simp_handle simp = p_impl->index_to_handle(d, cell);\n    auto c_boundary = p_impl->simplices.boundary_simplex_range(simp);\n    std::vector< std::pair< int, size_t > > boundary_and_indices;\n    for (auto face : c_boundary)\n        boundary_and_indices.push_back(              //\n            std::make_pair< int, size_t >(           //\n                p_impl->boundary_index(face, simp),  //\n                p_impl->handle_to_index(face)));     //\n    return boundary_and_indices;\n};\n\nstd::vector< size_t > simplicial_complex::cell_boundary_index(int d,\n                                                              size_t cell) {\n    impl::simp_handle simp = p_impl->index_to_handle(d, cell);\n    auto c_boundary = p_impl->simplices.boundary_simplex_range(simp);\n    std::vector< size_t > s_boundary;\n    for (auto c : c_boundary) s_boundary.push_back(p_impl->handle_to_index(c));\n    return s_boundary;\n}\n\nstd::vector< cell_t > simplicial_complex::cell_boundary(cell_t cell) {\n    impl::simp_handle simp = p_impl->cell_to_handle(cell);\n    auto c_boundary = p_impl->simplices.boundary_simplex_range(simp);\n    std::vector< cell_t > s_boundary;\n    for (auto c : c_boundary) s_boundary.push_back(p_impl->handle_to_cell(c));\n    return s_boundary;\n}\n\nint simplicial_complex::boundary_inclusion_index(cell_t c1, cell_t c2) {\n    return p_impl->boundary_index(p_impl->cell_to_handle(c1),   //\n                                  p_impl->cell_to_handle(c2));  //\n};\nint simplicial_complex::boundary_inclusion_index(int d1, size_t s1,    //\n                                                 int d2, size_t s2) {  //\n    cell_t c1 = index_to_cell(d1, s1);\n    cell_t c2 = index_to_cell(d2, s2);\n    return p_impl->boundary_index(p_impl->cell_to_handle(c1),\n                                  p_impl->cell_to_handle(c2));\n};\n\nstd::vector< std::pair< int, cell_t > > simplicial_complex::get_cof_and_ind(\n    cell_t cell) {\n    std::vector< std::pair< int, cell_t > > c_cofaces;\n    for (auto face : get_cofaces(cell))\n        c_cofaces.push_back(                                   //\n            std::make_pair(                                    //\n                boundary_inclusion_index(cell, face), face));  //\n    return c_cofaces;\n}\n\nstd::vector< std::pair< int, size_t > >\nsimplicial_complex::get_cof_and_ind_index(int d, size_t c) {\n    std::vector< std::pair< int, size_t > > c_cofaces;\n    for (auto face : get_cofaces_index(d, c))\n        c_cofaces.push_back(                                          //\n            std::make_pair(                                           //\n                boundary_inclusion_index(d, c, d + 1, face), face));  //\n    return c_cofaces;\n}\n\nint simplicial_complex::get_level_size(int level) {\n    return p_impl->get_level_size(level);\n}\n\nsimplicial_complex::simplicial_complex(std::vector< cell_t >& arg_tris) {\n    std::vector< point_t > points = {};\n    p_impl = std::make_shared< impl >(points, arg_tris);\n}\n\nsimplicial_complex::simplicial_complex(std::vector< point_t >& arg_points,\n                                       std::vector< cell_t >& arg_tris) {\n    p_impl = std::make_shared< impl >(arg_points, arg_tris);\n}\n\nsimplicial_complex::simplicial_complex(const simplicial_complex& other) {\n    p_impl = other.p_impl;\n}\n\nsimplicial_complex& simplicial_complex::operator=(\n    const simplicial_complex& other) {\n    p_impl = other.p_impl;\n    return *this;\n}\n\nsimplicial_complex::~simplicial_complex() {}\n\nstd::vector< point_t > simplicial_complex::get_points() {\n    return p_impl->points;\n}\n\npoint_t simplicial_complex::get_point(size_t index) {\n    return p_impl->points[index];\n}\n\nstd::vector< cell_t > simplicial_complex::get_level(int level) {\n    return p_impl->get_level(level);\n}\n\nmatrix_t simplicial_complex::get_boundary_matrix(int d) {\n    // uninstantiated boundary matrices\n    if (p_impl->boundary_matrices.size() == 0) p_impl->calculate_matrices();\n\n    // now they have to be instantiated, get them\n    if (0 <= d && d < p_impl->boundary_matrices.size())\n        return p_impl->boundary_matrices[d];\n    else\n        throw No_Boundary();\n}\n\nint simplicial_complex::dimension() { return p_impl->simplices.dimension(); }\n\ncell_t simplicial_complex::index_to_cell(int d, size_t ind) {\n    auto sh = (*(p_impl->levels[d]))[ind];\n    return p_impl->handle_to_cell(*sh);\n}\n\nsize_t simplicial_complex::cell_to_index(cell_t simp) {\n    auto sh = p_impl->simplices.find(simp);\n    return p_impl->simplices.key(sh);\n}\n\nstd::vector< size_t > simplicial_complex::get_cofaces_index(int d,\n                                                            size_t face) {\n    // codimension 1 faces\n    if (!p_impl->has_hasse) {\n        calculate_hasse();\n        p_impl->has_hasse = true;\n    }\n    auto s_cofaces = p_impl->incidence.get_coface_i(d, face);\n    return s_cofaces;\n}\n\nstd::vector< cell_t > simplicial_complex::get_cofaces(cell_t face) {\n    if (!p_impl->has_hasse) {\n        calculate_hasse();\n        p_impl->has_hasse = true;\n    }\n    std::vector< cell_t > s_cofaces;\n    auto face_i = cell_to_index(face);\n    int d = face.size() - 1;\n    // codimension 1 faces\n    auto coface_i_v = p_impl->incidence.get_coface_i(d, face_i);\n    for (auto v : coface_i_v) {\n        auto face_h = (*(p_impl->levels[d + 1]))[v];\n        s_cofaces.push_back(p_impl->handle_to_cell(*face_h));\n    }\n    return s_cofaces;\n}\n\nchain_v simplicial_complex::new_v_chain(int d) {\n    std::vector< double > v(get_level_size(d), 0);\n    return chain_v(d, v);\n}\nchain_t simplicial_complex::new_chain(int d) {\n    vector_t v(get_level_size(d));\n    return chain_t(d, v);\n}\n\nvoid simplicial_complex::calculate_hasse() {\n    p_impl->has_hasse = true;\n    p_impl->incidence = hasse_diag(*this);\n}\n};  // namespace gsimp\n", "meta": {"hexsha": "ef181544f1ba986d23aad86a2c7f3b19f80a89b7", "size": 13640, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lib/scomplex/simplicial_complex.cpp", "max_stars_repo_name": "crvs/coeff-flow", "max_stars_repo_head_hexsha": "24a2bbae4f2d11d29332cb00c453e4d9a8ed6f57", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2017-10-03T12:32:42.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-25T19:24:27.000Z", "max_issues_repo_path": "lib/scomplex/simplicial_complex.cpp", "max_issues_repo_name": "crvs/coeff-flow", "max_issues_repo_head_hexsha": "24a2bbae4f2d11d29332cb00c453e4d9a8ed6f57", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2018-06-23T22:50:35.000Z", "max_issues_repo_issues_event_max_datetime": "2018-06-28T14:05:52.000Z", "max_forks_repo_path": "lib/scomplex/simplicial_complex.cpp", "max_forks_repo_name": "crvs/coeff-flow", "max_forks_repo_head_hexsha": "24a2bbae4f2d11d29332cb00c453e4d9a8ed6f57", "max_forks_repo_licenses": ["BSD-3-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.7623762376, "max_line_length": 79, "alphanum_fraction": 0.5906891496, "num_tokens": 3504, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6370308082623216, "lm_q2_score": 0.4843800842769844, "lm_q1q2_score": 0.30856503659313883}}
{"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#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/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  // Compute the alpha and beta constants\n  compute_constants();\n}\n\ntemplate <int dim>\ntemplate <typename NumberType>\ndouble MaterialProperty<dim>::get(\n    typename dealii::Triangulation<dim>::active_cell_iterator const &cell,\n    Property prop, dealii::LA::distributed::Vector<NumberType> const &) const\n{\n  // TODO: For now, ignore field_state since we have a linear problem.\n  double value = 0.;\n  dealii::types::material_id material_id = cell->material_id();\n  unsigned int property = static_cast<unsigned int>(prop);\n\n  double const mp_dof_index = get_dof_index(cell);\n\n  for (unsigned int i = 0; i < _n_material_states; ++i)\n  {\n    // We cannot use operator[] because the function is constant.\n    auto const tmp = _properties.find(material_id);\n    ASSERT(tmp != _properties.end(), \"Material not found.\");\n    if ((tmp->second)[i][property] != nullptr)\n      value += _state[i][mp_dof_index] *\n               (tmp->second)[i][property]->value(dealii::Point<1>());\n  }\n\n  return value;\n}\n\ntemplate <int dim>\ntemplate <typename NumberType>\ndealii::LA::distributed::Vector<NumberType>\nMaterialProperty<dim>::enthalpy_to_temperature(\n    dealii::DoFHandler<dim> const &enthalpy_dof_handler,\n    dealii::LA::distributed::Vector<NumberType> const &enthalpy)\n{\n  dealii::LA::distributed::Vector<NumberType> temperature(\n      enthalpy.get_partitioner());\n  dealii::LA::distributed::Vector<NumberType> dummy;\n\n  update_state(enthalpy_dof_handler, enthalpy);\n\n  unsigned int const dofs_per_cell =\n      enthalpy_dof_handler.get_fe().dofs_per_cell;\n  std::vector<dealii::types::global_dof_index> local_dof_indices(dofs_per_cell);\n  for (auto cell :\n       dealii::filter_iterators(enthalpy_dof_handler.active_cell_iterators(),\n                                dealii::IteratorFilters::LocallyOwnedCell()))\n  {\n    cell->get_dof_indices(local_dof_indices);\n\n    double const liquid_ratio = get_state_ratio(cell, MaterialState::liquid);\n    double const density = get(cell, Property::density, dummy);\n    double const specific_heat = get(cell, Property::specific_heat, dummy);\n    double const liquidus = get(cell, Property::liquidus, dummy);\n    double const solidus = get(cell, Property::solidus, dummy);\n    double const solidus_enthalpy = solidus * density * specific_heat;\n    double const latent_heat = get(cell, Property::latent_heat, dummy);\n    double const liquidus_enthalpy = solidus_enthalpy + latent_heat;\n\n    NumberType enth_to_temp = [liquid_ratio, liquidus, solidus,\n                               liquidus_enthalpy, solidus_enthalpy, density,\n                               specific_heat](double const enthalpy) {\n      if (liquid_ratio > 0.)\n      {\n        if (liquid_ratio == 1.)\n        {\n          return liquidus +\n                 (enthalpy - liquidus_enthalpy) / (density * specific_heat);\n        }\n        else\n        {\n          return solidus + (liquidus - solidus) *\n                               (enthalpy - solidus_enthalpy) /\n                               (liquidus_enthalpy - solidus_enthalpy);\n        }\n      }\n      else\n      {\n        return enthalpy / (density * specific_heat);\n      }\n    };\n\n    for (unsigned int i = 0; i < dofs_per_cell; ++i)\n      temperature[local_dof_indices[i]] =\n          enth_to_temp(enthalpy[local_dof_indices[i]]);\n  }\n\n  return temperature;\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>\ntemplate <typename NumberType>\nvoid MaterialProperty<dim>::update_state(\n    dealii::DoFHandler<dim> const &enthalpy_dof_handler,\n    dealii::LA::distributed::Vector<NumberType, dealii::MemorySpace::CUDA> const &enthalpy)\n{\n  auto enthalpy_average =\n      compute_average_enthalpy(enthalpy_dof_handler, enthalpy);\n  dealii::LA::distributed::Vector<NumberType> enthalpy_average_host(enthalpy_average.get_partitioner());\n  enthalpy_average_host.import(enthalpy_average, dealii::VectorOperation::insert);\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    // TODO check that assumption enthalpy of solidus powder = enthalpy of\n    // solidus solid\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_latent_heat =\n        static_cast<unsigned int>(Property::latent_heat);\n    unsigned int constexpr prop_solidus =\n        static_cast<unsigned int>(Property::solidus);\n    unsigned int constexpr prop_density =\n        static_cast<unsigned int>(Property::density);\n    unsigned int constexpr prop_specific_heat =\n        static_cast<unsigned int>(Property::specific_heat);\n\n    dealii::Point<1> const empty_pt;\n\n    double const latent_heat =\n        ((tmp->second)[solid][prop_latent_heat] == nullptr)\n            ? std::numeric_limits<double>::max()\n            : (tmp->second)[solid][prop_latent_heat]->value(empty_pt);\n    double const solidus =\n        ((tmp->second)[solid][prop_solidus] == nullptr)\n            ? std::numeric_limits<double>::max()\n            : (tmp->second)[solid][prop_solidus]->value(empty_pt);\n    double const solidus_enthalpy =\n        solidus * (tmp->second)[solid][prop_density]->value(empty_pt) *\n        (tmp->second)[solid][prop_specific_heat]->value(empty_pt);\n    double const liquidus_enthalpy = solidus_enthalpy + latent_heat;\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 (enthalpy_average_host[dof] < solidus_enthalpy)\n      liquid_ratio = 0.;\n    else if (enthalpy_average_host[dof] > liquidus_enthalpy)\n      liquid_ratio = 1.;\n    else\n      liquid_ratio = (enthalpy_average_host[dof] - solidus_enthalpy) / latent_heat;\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}\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      {\"density\", \"latent_heat\", \"liquidus\", \"solidus\", \"specific_heat\",\n       \"thermal_conductivity\"}};\n\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    std::string variable = \"T\";\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_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>(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            _properties[material_id][state][p] =\n                std::make_unique<dealii::FunctionParser<1>>(1);\n            _properties[material_id][state][p]->initialize(\n                variable, property.get(), std::map<std::string, double>());\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<std::string> const property =\n          material_database.get_optional<std::string>(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        for (unsigned int state = 0; state < _n_material_states; ++state)\n        {\n          _properties[material_id][state][p] =\n              std::make_unique<dealii::FunctionParser<1>>(1);\n          _properties[material_id][state][p]->initialize(\n              variable, property.get(), std::map<std::string, double>());\n        }\n      }\n    }\n  }\n}\n\ntemplate <int dim>\nvoid MaterialProperty<dim>::compute_constants()\n{\n  unsigned int constexpr liquid =\n      static_cast<unsigned int>(MaterialState::liquid);\n  unsigned int constexpr solid =\n      static_cast<unsigned int>(MaterialState::solid);\n  unsigned int constexpr prop_latent_heat =\n      static_cast<unsigned int>(Property::latent_heat);\n  unsigned int constexpr solidus = static_cast<unsigned int>(Property::solidus);\n  unsigned int constexpr liquidus =\n      static_cast<unsigned int>(Property::liquidus);\n  unsigned int constexpr density = static_cast<unsigned int>(Property::density);\n  unsigned int constexpr specific_heat =\n      static_cast<unsigned int>(Property::specific_heat);\n\n  dealii::Point<1> const empty_pt;\n\n  for (auto prop = _properties.begin(); prop != _properties.end(); ++prop)\n  {\n    dealii::types::material_id const material_id = prop->first;\n    bool const liquidus_exist =\n        (prop->second[solid][liquidus] == nullptr) ? false : true;\n    bool const solidus_exist =\n        (prop->second[solid][solidus] == nullptr) ? false : true;\n    bool const latent_heat_exist =\n        (prop->second[solid][prop_latent_heat] == nullptr) ? false : true;\n    bool const density_exist =\n        (prop->second[solid][density] == nullptr) ? false : true;\n    bool const specific_heat_exist =\n        (prop->second[solid][specific_heat] == nullptr) ? false : true;\n\n    if (liquidus_exist && solidus_exist && latent_heat_exist)\n      _mushy_alpha[material_id] =\n          (prop->second[solid][liquidus]->value(empty_pt) -\n           prop->second[solid][solidus]->value(empty_pt)) /\n          prop->second[solid][prop_latent_heat]->value(empty_pt);\n\n    if (liquidus_exist && solidus_exist && density_exist && specific_heat_exist)\n    {\n      double const solidus_enthalpy =\n          prop->second[solid][solidus]->value(empty_pt) *\n          prop->second[solid][density]->value(empty_pt) *\n          prop->second[solid][specific_heat]->value(empty_pt);\n      _mushy_beta[material_id] =\n          -solidus_enthalpy /\n              prop->second[solid][prop_latent_heat]->value(empty_pt) *\n              (prop->second[solid][liquidus]->value(empty_pt) -\n               prop->second[solid][solidus]->value(empty_pt)) +\n          prop->second[solid][solidus]->value(empty_pt);\n      // TODO this is true only if density and heat capacity are independent of\n      // the temperature\n      _liquid_beta[material_id] =\n          -(solidus_enthalpy +\n            prop->second[liquid][prop_latent_heat]->value(empty_pt)) /\n              (prop->second[liquid][density]->value(empty_pt) *\n               prop->second[liquid][specific_heat]->value(empty_pt)) +\n          prop->second[liquid][liquidus]->value(empty_pt);\n    }\n  }\n}\n\ntemplate <int dim>\ntemplate <typename NumberType>\ndealii::LA::distributed::Vector<NumberType, dealii::MemorySpace::CUDA>\nMaterialProperty<dim>::compute_average_enthalpy(\n    dealii::DoFHandler<dim> const &enthalpy_dof_handler,\n    dealii::LA::distributed::Vector<NumberType, dealii::MemorySpace::CUDA> const &enthalpy) 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<NumberType> enthalpy_average(\n      _mp_dof_handler.locally_owned_dofs(), enthalpy.get_mpi_communicator());\n  dealii::LA::distributed::Vector<NumberType> enthalpy_host(enthalpy.get_partitioner());\n  enthalpy_host.import(enthalpy, dealii::VectorOperation::insert);\n  enthalpy_average = 0.;\n  auto mp_cell = _mp_dof_handler.begin_active();\n  auto mp_end_cell = _mp_dof_handler.end();\n  auto enth_cell = enthalpy_dof_handler.begin_active();\n  dealii::FiniteElement<dim> const &fe = enthalpy_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 area = 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          Assert(enth_dof_indices[i] < enthalpy_dof_handler.n_dofs(), dealii::ExcInternalError());\n          Assert(enth_dof_indices[i] < enthalpy_host.size(), dealii::ExcInternalError());\n          area += fe_values.shape_value(i, q) * fe_values.JxW(q);\n          enthalpy_average[mp_dof_index] += fe_values.shape_value(i, q) *\n                                            enthalpy_host[enth_dof_indices[i]] *\n                                            fe_values.JxW(q);\n        }\n      enthalpy_average[mp_dof_index] /= area;\n    }\n\n  dealii::LA::distributed::Vector<NumberType, dealii::MemorySpace::CUDA> enthalpy_average_device(\n      _mp_dof_handler.locally_owned_dofs(), enthalpy.get_mpi_communicator());\n  enthalpy_average_device.import(enthalpy_average, dealii::VectorOperation::insert);\n\n  return enthalpy_average_device;\n}\n} // namespace adamantine\n\nINSTANTIATE_DIM(MaterialProperty)\n\nnamespace adamantine\n{\n// Instantiate templated function: get\ntemplate double MaterialProperty<2>::get(\n    dealii::Triangulation<2>::active_cell_iterator const &, Property prop,\n    dealii::LA::distributed::Vector<float> const &) const;\ntemplate double MaterialProperty<2>::get(\n    dealii::Triangulation<2>::active_cell_iterator const &, Property prop,\n    dealii::LA::distributed::Vector<double> const &) const;\ntemplate double MaterialProperty<3>::get(\n    dealii::Triangulation<3>::active_cell_iterator const &, Property prop,\n    dealii::LA::distributed::Vector<float> const &) const;\ntemplate double MaterialProperty<3>::get(\n    dealii::Triangulation<3>::active_cell_iterator const &, Property prop,\n    dealii::LA::distributed::Vector<double> const &) const;\n\n// Instantiate templated function: update_state\ntemplate void MaterialProperty<2>::update_state(\n    dealii::DoFHandler<2> const &,\n    dealii::LA::distributed::Vector<float, dealii::MemorySpace::CUDA> const &);\ntemplate void MaterialProperty<2>::update_state(\n    dealii::DoFHandler<2> const &,\n    dealii::LA::distributed::Vector<double, dealii::MemorySpace::CUDA> const &);\ntemplate void MaterialProperty<3>::update_state(\n    dealii::DoFHandler<3> const &,\n    dealii::LA::distributed::Vector<float, dealii::MemorySpace::CUDA> const &);\ntemplate void MaterialProperty<3>::update_state(\n    dealii::DoFHandler<3> const &,\n    dealii::LA::distributed::Vector<double, dealii::MemorySpace::CUDA> const &);\n} // namespace adamantine\n", "meta": {"hexsha": "597ded16e062797351025a2caabf976fe26860e3", "size": 19435, "ext": "cc", "lang": "C++", "max_stars_repo_path": "source/MaterialProperty.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/MaterialProperty.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/MaterialProperty.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": 40.9157894737, "max_line_length": 104, "alphanum_fraction": 0.6820684332, "num_tokens": 4768, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6370307806984444, "lm_q2_score": 0.48438008427698437, "lm_q1q2_score": 0.3085650232417457}}
{"text": "// -------------------------------------------\n//  @description: 产生骨架的三维点云\n//  @author: hts\n//  @data: 2020-04-11\n//  @version: wpdwp\n// -------------------------------------------\n#include <stdlib.h>\n#include <stdio.h>\n#include <iostream>\n#include <sstream>\n#include <string>\n#include <vector>\n#include <cmath>\n#include <mutex>\n#include <thread>\n#include <chrono>\n\n#include <pcl/point_cloud.h>\n#include <pcl/point_types.h>\n#include <pcl/io/pcd_io.h>\n#include <pcl/visualization/cloud_viewer.h>\n\n#include <opencv2/opencv.hpp>\n\n#include <ros/ros.h>\n#include <ros/spinner.h>\n#include <sensor_msgs/CameraInfo.h>\n#include <sensor_msgs/Image.h>\n\n#include <cv_bridge/cv_bridge.h>\n\n#include <image_transport/image_transport.h>\n#include <image_transport/subscriber_filter.h>\n\n#include <message_filters/subscriber.h>\n#include <message_filters/synchronizer.h>\n#include <message_filters/sync_policies/exact_time.h>\n#include <message_filters/sync_policies/approximate_time.h>\n\n#include <kinect2_bridge/kinect2_definitions.h>\n#include <Eigen/Dense>\n#include <Eigen/Geometry>\nusing namespace Eigen;\n\n#define pi 3.14159265359\n\nclass Posepoint\n{\nprivate:\n  std::mutex lock;\n  cv::Mat color, depth;\n  cv::Mat cameraMatrixColor, cameraMatrixDepth;\n  cv::Mat lookupX, lookupY;\n  pcl::PointCloud<pcl::PointXYZRGBA>::Ptr cloud;\n  pcl::PCDWriter writer;\n  bool visualize_stop;\n  double pick_points[6];\n  Vector3f Lshoulder, Rshoulder, Pelv;  \npublic:\n  Posepoint():visualize_stop(false)\n  {\n    cameraMatrixColor = cv::Mat::zeros(3, 3, CV_64F);\n    static double my_points[6] = {255.67636108398438,292.16888427734375,320.4430236816406,266.26220703125,330.15802001953125,298.64556884765625};\n    for(int i=0; i<6; i++)\n    {\n      pick_points[i] = my_points[i];\n    }\n  }\n  ~Posepoint()\n  {\n  }\npublic:\n    void start(std::string color_path, std::string depth_path)\n  {\n    color = cv::imread(color_path);\n    depth = cv::imread(depth_path,2);\n    cloud = pcl::PointCloud<pcl::PointXYZRGBA>::Ptr(new pcl::PointCloud<pcl::PointXYZRGBA>());\n    cloud->height = color.rows;\n    cloud->width = color.cols;\n    cloud->is_dense = false;\n    cloud->points.resize(cloud->height * cloud->width);\n    readCameraInfo();\n    createLookup(this->color.cols, this->color.rows); //像极坐标系中的值保存在lookupX　lookupY里面\n    cloudViewer();\n  }\n  // 3x3内参矩阵\n//   367.933   0         254.169\n//     0     367.933     204.267\n//     0       0            1\n    void readCameraInfo()\n  {\n    double cameraInfoK[9]={367.933 , 0 , 254.169,\n                           0 , 367.933 , 204.267,\n                          0 , 0 , 1             }; \n    double *itC = cameraMatrixColor.ptr<double>(0, 0);\n    for(size_t i = 0; i < 9; ++i, ++itC)\n    {\n      *itC = cameraInfoK[i];\n    }\n  }\n    // 求在相机坐标系中的坐标\n    void createLookup(size_t width, size_t height)\n  {\n    // width是列->x　height是行->y\n    // 得到相机的内参数\n    //  成像模型\n// [u       [ fx　0 cx   [x\n//  v  = 1/z  0  fy cy    y\n//  1]        0   0  1]   z]\n// 求逆矩阵　得到像极坐标系中的坐标　\n    const float fx = 1.0f / cameraMatrixColor.at<double>(0, 0);\n    const float fy = 1.0f / cameraMatrixColor.at<double>(1, 1);\n    const float cx = cameraMatrixColor.at<double>(0, 2);\n    const float cy = cameraMatrixColor.at<double>(1, 2);\n    float *it;\n    // cout<<fx<<\" \"<<fy<<\" \"<<cx<<\" \"<<cy<<\" \"<<endl;\n    lookupY = cv::Mat(1, height, CV_32F);\n    it = lookupY.ptr<float>();\n    for(size_t r = 0; r < height; ++r, ++it)\n    {\n      *it = (r - cy) * fy;\n    }\n\n    lookupX = cv::Mat(1, width, CV_32F);\n    it = lookupX.ptr<float>();\n    for(size_t c = 0; c < width; ++c, ++it)\n    {\n      *it = (c - cx) * fx;\n    }\n  }\n    void cloudViewer()\n  {\n    cv::Mat color, depth;\n    pcl::visualization::PCLVisualizer::Ptr visualizer(new pcl::visualization::PCLVisualizer(\"Cloud Viewer\"));\n    const std::string cloudName = \"rendered\";\n\n    lock.lock();\n    color = this->color;\n    depth = this->depth;\n    lock.unlock();\n\n    createCloud(depth, color, cloud);\n    // 将点云数据添加到视窗中，并为其定义一个唯一的字符串作为ID号，利用此ID号保证其他成员方法也能表示该点云。\n    // 多次调用addPointCloud()可以实现多个点云的叠加，每调用一次就创建一个新的ID号。如果想要更新一个已经\n    // 显示的点云，用户必须先调用removePointCloud()，并提供新的ID号。（在PCL1.1版本之后直接调用updatePointCloud()\n    //  就可以了，不必手动调用removePointCloud()就可实现点云更新）\n    visualizer->addPointCloud(cloud, cloudName);\n    // 修改现实点云的尺寸。用户可通过该方法控制点云在视窗中的显示方式\n    visualizer->setPointCloudRenderingProperties(pcl::visualization::PCL_VISUALIZER_POINT_SIZE, 1, cloudName);\n    // 设置XYZ三个坐标轴的大小和长度，该值也可以缺省\n    // 查看复杂的点云图像会让用户没有方向感，为了让用户保持正确的方向判断，需要显示坐标轴。三个坐标轴X（R，红色）\n    // Y（G，绿色）Z（B，蓝色）分别用三种不同颜色的圆柱体代替\n    // visualizer->addCoordinateSystem(1.0);\n    // 通过设置相机参数是用户从默认的角度和方向观察点\n    visualizer->initCameraParameters();\n    // 设置窗口viewer的背景颜色\n    visualizer->setBackgroundColor(0, 0, 0);\n    visualizer->setPosition(0, 0);\n    visualizer->setSize(color.cols, color.rows);\n    visualizer->setShowFPS(true);\n    visualizer->setCameraPosition(0, 0, 0, 0, -1, 0);\n    visualizer->registerKeyboardCallback(&Posepoint::keyboardEvent, *this);\n    saveCloud(cloud);\n    // visualizer->spinOnce(300);\n    while (!visualize_stop) {\n        visualizer->spinOnce(100);\n    }\n\n    visualizer->close();\n  }\n    void createCloud(const cv::Mat &depth, const cv::Mat &color, pcl::PointCloud<pcl::PointXYZRGBA>::Ptr &cloud)\n  {\n    int body_part;\n    const float badPoint = std::numeric_limits<float>::quiet_NaN();\n    // FILE *fp = NULL;\n    // fp = fopen(\"/home/hts/catkin_ws/test.txt\", \"a\");\n    #pragma omp parallel for\n    for(int r = 0; r < depth.rows; ++r)\n    {\n      // 创建点云row行，每一行有col列\n      pcl::PointXYZRGBA *itP = &cloud->points[r * depth.cols];\n      // ptr函数访问任意一行像素的首地址　\n      const uint16_t *itD = depth.ptr<uint16_t>(r);\n      const cv::Vec3b *itC = color.ptr<cv::Vec3b>(r);\n      const float y = lookupY.at<float>(0, r);\n      const float *itX = lookupX.ptr<float>();\n\n      for(size_t c = 0; c < (size_t)depth.cols; ++c, ++itP, ++itD, ++itC, ++itX)\n      {\n        bool picked = false;\n          if(int(pick_points[0]) == r && size_t(pick_points[1]) == c)\n        {\n            // cout<<r<<\"   \"<<c<<\"Pelv_succ\"<<endl;\n            // cout<<\"Pelv\"<<endl;\n            picked = true;\n            body_part = 0;        \n        }\n          if(int(pick_points[2]) == r && size_t(pick_points[3]) == c)\n        {\n            // cout<<r<<\"   \"<<c<<\"Rshoulder_succ\"<<endl;\n            // cout<<\"Rshoulder\"<<endl;\n            picked = true;\n            body_part = 1;        \n        }\n          if(int(pick_points[4]) == r && size_t(pick_points[5]) == c)\n        {\n            // cout<<r<<\"   \"<<c<<\"LShoulder_succ\"<<endl;\n            // cout<<\"Lshoulder\"<<endl;\n            picked = true;\n            body_part = 2;        \n        }\n        if (picked)\n        {\n          // cout<<\"picked\"<<endl;\n          // cout<<body_part<<endl;\n          register const float depthValue = *itD / 1000.0f;\n          // Check for invalid measurements\n          if(*itD == 0)\n          {\n            // not valid\n            itP->x = itP->y = itP->z = badPoint;\n            itP->rgba = 0;\n            continue;\n          }\n          itP->z = depthValue;\n          itP->x = *itX * depthValue;\n          itP->y = y * depthValue;\n          itP->b = itC->val[0];\n          itP->g = itC->val[1];\n          itP->r = itC->val[2];\n          itP->a = 255;\n          // fprintf(fp, \"%f,%f,%f,%d,%d,%d,%d\\n\", itP->z,itP->x,itP->y,itP->b,itP->g,itP->r,itP->a);\n          switch(body_part)\n          {\n          case 0:;\n                Lshoulder(0) = itP->x; Lshoulder(1) = itP->y; Lshoulder(2) = itP->z;\n                // cout<<\"Pelv\"<<endl;\n                // cout<<\"Pelv\"<<\"  \"<<Lshoulder(0)<<\" \"<<Lshoulder(1)<<\" \"<<Lshoulder(2)<<endl;\n                break;\n          case 1:\n                Rshoulder(0) = itP->x; Rshoulder(1) = itP->y; Rshoulder(2) = itP->z;\n                // cout<<\"Rshoulder\"<<endl;\n                // cout<<\"Rshoulder\"<<\"  \"<<Rshoulder(0)<<\" \"<<Rshoulder(1)<<\" \"<<Rshoulder(2)<<endl;\n                break;\n          case 2:\n                Pelv(0) = itP->x; Pelv(1) = itP->y; Pelv(2) = itP->z;\n                // cout<<\"Lshoulder\"<<endl;\n                // cout<<\"Lshoulder\"<<\"  \"<<Pelv(0)<<\" \"<<Pelv(1)<<\" \"<<Pelv(2)<<endl;\n                break; \n          }\n        }\n        else\n        {\n            itP->x = itP->y = itP->z = badPoint;\n            itP->rgba = 0;\n            continue;\n        }\n        \n      }\n    }\n    // fclose(fp);\n  }\n    void saveCloud(const pcl::PointCloud<pcl::PointXYZRGBA>::ConstPtr cloud)\n  {\n    std::ostringstream oss;\n    oss.str(\"\");\n    oss << \"/home/hts/kinect_pic/\" << std::setfill('0') << std::setw(4);\n    const std::string baseName = oss.str();\n    const std::string cloudName = baseName + \"_cloud.pcd\";\n    OUT_INFO(\"saving cloud: \" << cloudName);\n     // writer是该类的pcl::PCDWriter类型的成员变量\n    writer.writeBinary(cloudName, *cloud);\n  }\n    void keyboardEvent(const pcl::visualization::KeyboardEvent &event, void *)\n  {\n    if(event.keyUp())\n    {\n      switch(event.getKeyCode())\n      {\n      case 27:\n      case 'q':\n        visualize_stop = true;\n        break;\n      }\n    }\n  }\n  //叉积\n  Vector3f ThreeCross()\n  {\n    Vector3f a, b,result;\n    a=Lshoulder-Pelv;\n    b=Rshoulder-Pelv;\n    cout<<a<<\"  \"<<b<<endl;\n    result = a.cross(b);\n    cout<<result<<endl;\n    // Eigen::Vector3d v3(0, 0, 0);\n\t  // v3.x() = 1;\n\t  // v3[2] = 1;\n\t  AngleAxisd angle_axis3(pi *25/ 18, Eigen::Vector3d(1, 0, 0));//1系绕x轴逆时针旋转250得到2系\n    // angle_axis3.matrix().cast<float>()\n\t  Vector3f rotated_result = angle_axis3.matrix().cast<float>()*result;\n\t  cout << \"绕x轴顺时针旋转250°(R12):\" << endl << angle_axis3.matrix() << endl;\n\t  cout << \"旋转后:\" << endl << rotated_result.transpose() << endl;\n    return result;\n  }\n};\nint main(int argc, char**argv)\n{\n  std::string color_path = argv[1];\n  std::string depth_path = argv[2];\n  Posepoint posepoint; \n  posepoint.start(color_path, depth_path);\n  posepoint.ThreeCross();\n\n  // Vector3f Lshoulder;\n  // Lshoulder<<0,0,0;\n  // Lshoulder(0)=1;\n}", "meta": {"hexsha": "4ea420b68d677efafb038caf9999a85c34a85e51", "size": 9923, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "kinect2_viewer/src/pointcloud_1.cpp", "max_stars_repo_name": "hutslib/iai_kinect2", "max_stars_repo_head_hexsha": "3f225ea61f4114f55ab458ea570ffdacaa38d7be", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "kinect2_viewer/src/pointcloud_1.cpp", "max_issues_repo_name": "hutslib/iai_kinect2", "max_issues_repo_head_hexsha": "3f225ea61f4114f55ab458ea570ffdacaa38d7be", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "kinect2_viewer/src/pointcloud_1.cpp", "max_forks_repo_name": "hutslib/iai_kinect2", "max_forks_repo_head_hexsha": "3f225ea61f4114f55ab458ea570ffdacaa38d7be", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.2044025157, "max_line_length": 145, "alphanum_fraction": 0.5663609795, "num_tokens": 3341, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5851011542032312, "lm_q2_score": 0.5273165233795671, "lm_q1q2_score": 0.30853350645981986}}
{"text": "/*\nBrian Staber (brian.staber@gmail.com)\n*/\n\n#include \"Epetra_ConfigDefs.h\"\n#ifdef HAVE_MPI\n#include \"mpi.h\"\n#include \"Epetra_MpiComm.h\"\n#else\n#include \"Epetra_SerialComm.h\"\n#endif\n\n#include \"Teuchos_CommandLineProcessor.hpp\"\n#include \"Teuchos_StandardCatchMacros.hpp\"\n#include \"Teuchos_ParameterList.hpp\"\n#include \"Teuchos_XMLParameterListCoreHelpers.hpp\"\n\n#include \"neumannInnerSurface_StochasticPolyconvexHGO.hpp\"\n#include <boost/math/special_functions/gamma.hpp>\n\n#include \"shinozukapp.hpp\"\n\nint main(int argc, char *argv[]){\n\n    std::string    xmlInFileName = \"\";\n    std::string    extraXmlFile = \"\";\n    std::string    xmlOutFileName = \"paramList.out\";\n\n    Teuchos::CommandLineProcessor  clp(false);\n    clp.setOption(\"xml-in-file\",&xmlInFileName,\"The XML file to read into a parameter list\");\n    clp.setDocString(\"TO DO.\");\n\n    Teuchos::CommandLineProcessor::EParseCommandLineReturn\n    parse_return = clp.parse(argc,argv);\n    if( parse_return != Teuchos::CommandLineProcessor::PARSE_SUCCESSFUL ) {\n        std::cout << \"\\nEnd Result: TEST FAILED\" << std::endl;\n        return parse_return;\n    }\n\n#ifdef HAVE_MPI\n    MPI_Init(&argc, &argv);\n    Epetra_MpiComm Comm(MPI_COMM_WORLD);\n#else\n    Epetra_SerialComm Comm;\n#endif\n\n    Teuchos::RCP<Teuchos::ParameterList> paramList = Teuchos::rcp(new Teuchos::ParameterList);\n    if(xmlInFileName.length()) {\n        Teuchos::updateParametersFromXmlFile(xmlInFileName, inoutArg(*paramList));\n    }\n\n    if (Comm.MyPID()==0){\n        paramList->print(std::cout,2,true,true);\n    }\n\n    Teuchos::RCP<neumannInnerSurface_StochasticPolyconvexHGO> my_interface\n    = Teuchos::rcp(new neumannInnerSurface_StochasticPolyconvexHGO(Comm,*paramList));\n\n    std::ifstream parameters_file_1, parameters_file_2, parameters_file_3, parameters_file_4;\n\n    std::string path1 = \"/Users/Brian/Documents/Thesis/Trilinos_results/arteries/gmrf_neumann/a100_gamma3_delta010/\";\n    parameters_file_1.open(path1+\"w1.txt\");\n    parameters_file_2.open(path1+\"w2.txt\");\n    parameters_file_3.open(path1+\"w3.txt\");\n    parameters_file_4.open(path1+\"w4.txt\");\n\n    unsigned int n_cells_p1_med = 297828;\n    unsigned int n_nodes_p1_med = 58464;\n\n    Epetra_Map StandardMap(int(n_nodes_p1_med),0,Comm);\n\n    Epetra_Vector c1(StandardMap);\n    Epetra_Vector c2(StandardMap);\n    Epetra_Vector u1(StandardMap);\n    Epetra_Vector mu4(StandardMap);\n\n    std::string path = \"/Users/Brian/Documents/Thesis/Trilinos/arteries/mesh/connectivity_p1_media.txt\";\n    my_interface->get_media(n_cells_p1_med,n_nodes_p1_med,path);\n\n    if (parameters_file_1.is_open() && parameters_file_2.is_open() && parameters_file_3.is_open() && parameters_file_4.is_open()){\n\n        for (unsigned nmc=0; nmc<1; ++nmc){\n            for (int i=0; i<n_nodes_p1_med; ++i){\n                parameters_file_1 >> my_interface->w1_gmrf(i);\n                parameters_file_2 >> my_interface->w2_gmrf(i);\n                parameters_file_3 >> my_interface->w3_gmrf(i);\n                parameters_file_4 >> my_interface->w4_gmrf(i);\n            }\n            for (int j=0; j<n_nodes_p1_med; ++j){\n                if (StandardMap.MyGID(j)){\n                    c1[StandardMap.LID(j)]  = my_interface->icdf_gamma(my_interface->w1_gmrf[j],my_interface->alpha1,my_interface->alpha2);\n                    c2[StandardMap.LID(j)]  = my_interface->icdf_gamma(my_interface->w2_gmrf[j],my_interface->alpha3,my_interface->alpha4);\n                    u1[StandardMap.LID(j)]  = my_interface->icdf_beta(my_interface->w3_gmrf[j],my_interface->tau1,my_interface->tau2);\n                    mu4[StandardMap.LID(j)] = my_interface->icdf_gamma(my_interface->w4_gmrf[j],my_interface->alpha5,my_interface->alpha6);\n                }\n            }\n        }\n        Comm.Barrier();\n        parameters_file_1.close();\n        parameters_file_2.close();\n        parameters_file_3.close();\n        parameters_file_4.close();\n    }\n    else{\n        std::cout << \"Couldn't open one of the parameters_file.\\n\";\n    }\n\n    int error;\n    int NumTargetElements = 0;\n    if (Comm.MyPID()==0){\n        NumTargetElements = n_nodes_p1_med;\n    }\n    Epetra_Map MapOnRoot(-1,NumTargetElements,0,Comm);\n    Epetra_Export ExportOnRoot(StandardMap,MapOnRoot);\n    Epetra_MultiVector lhs_root(MapOnRoot,true);\n    lhs_root.Export(c1,ExportOnRoot,Insert);\n    std::string filename = \"/Users/Brian/Documents/Thesis/Trilinos_results/arteries/boost_gmrf/gmrf_nodes/c1_test.mtx\";\n    error = EpetraExt::MultiVectorToMatrixMarketFile(filename.c_str(),lhs_root,0,0,false);\n\n    lhs_root.PutScalar(0.0);\n    lhs_root.Export(c2,ExportOnRoot,Insert);\n    filename = \"/Users/Brian/Documents/Thesis/Trilinos_results/arteries/boost_gmrf/gmrf_nodes/c2_test.mtx\";\n    error = EpetraExt::MultiVectorToMatrixMarketFile(filename.c_str(),lhs_root,0,0,false);\n\n    lhs_root.PutScalar(0.0);\n    lhs_root.Export(u1,ExportOnRoot,Insert);\n    filename = \"/Users/Brian/Documents/Thesis/Trilinos_results/arteries/boost_gmrf/gmrf_nodes/u1_test.mtx\";\n    error = EpetraExt::MultiVectorToMatrixMarketFile(filename.c_str(),lhs_root,0,0,false);\n\n    lhs_root.PutScalar(0.0);\n    lhs_root.Export(mu4,ExportOnRoot,Insert);\n    filename = \"/Users/Brian/Documents/Thesis/Trilinos_results/arteries/boost_gmrf/gmrf_nodes/mu4_test.mtx\";\n    error = EpetraExt::MultiVectorToMatrixMarketFile(filename.c_str(),lhs_root,0,0,false);\n\n\n#ifdef HAVE_MPI\n    MPI_Finalize();\n#endif\nreturn 0;\n\n}\n", "meta": {"hexsha": "73b21528f5f465d526f0f5c3429039846c4164b4", "size": 5400, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "arteries/boost_gmrf/gmrf_nodes/main.cpp", "max_stars_repo_name": "bstaber/Trilinos", "max_stars_repo_head_hexsha": "12ada5a678338a1da962113a4fad708f93b19e03", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "arteries/boost_gmrf/gmrf_nodes/main.cpp", "max_issues_repo_name": "bstaber/Trilinos", "max_issues_repo_head_hexsha": "12ada5a678338a1da962113a4fad708f93b19e03", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "arteries/boost_gmrf/gmrf_nodes/main.cpp", "max_forks_repo_name": "bstaber/Trilinos", "max_forks_repo_head_hexsha": "12ada5a678338a1da962113a4fad708f93b19e03", "max_forks_repo_licenses": ["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.0281690141, "max_line_length": 139, "alphanum_fraction": 0.7042592593, "num_tokens": 1501, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6688802603710086, "lm_q2_score": 0.46101677931231594, "lm_q1q2_score": 0.3083650233818257}}
{"text": "#include \"CollisionDetection.h\"\n#include \"RigidBodyInstance.h\"\n#include \"RigidBodyTemplate.h\"\n#include <Eigen/Core>\n#include \"VectorMath.h\"\n#include <Eigen/Geometry>\n#include <iostream>\n\nusing namespace std;\n\nstruct BBox\n{\n    double mins[3];\n    double maxs[3];\n};\n\nbool intersects(const BBox &b1, const BBox &b2)\n{\n    for(int i=0; i<3; i++)\n    {\n        if( (b1.maxs[i] < b2.mins[i]) || (b2.maxs[i] < b1.mins[i]))\n            return false;\n    }\n    return true;\n}\n\nstruct AABBNode\n{\n    AABBNode() : left(NULL), right(NULL), childtet(-1) {}\n    ~AABBNode() {delete left; delete right;}\n\n    AABBNode *left;\n    AABBNode *right;\n    BBox box;\n    int childtet;\n};\n\nclass NodeComparator\n{\npublic:\n    NodeComparator(int axis) : axis(axis) {}\n\n    int axis;\n\n    bool operator()(const AABBNode *left, const AABBNode *right) const\n    {\n        return left->box.mins[axis] < right->box.mins[axis];\n    }\n};\n\nAABBNode *buildAABB(vector<AABBNode *> nodes)\n{\n    if(nodes.size() == 0)\n        return NULL;\n    else if(nodes.size() == 1)\n        return nodes[0];\n\n    double axismins[3];\n    double axismaxs[3];\n    for(int i=0; i<3; i++)\n    {\n        axismins[i] = numeric_limits<double>::infinity();\n        axismaxs[i] = -numeric_limits<double>::infinity();\n    }\n    int nnodes = (int)nodes.size();\n    for(int i=0; i<nnodes; i++)\n    {\n        for(int j=0; j<3; j++)\n        {\n            axismins[j] = min(axismins[j], nodes[i]->box.mins[j]);\n            axismaxs[j] = max(axismaxs[j], nodes[i]->box.maxs[j]);\n        }\n    }\n    double widths[3];\n    for(int i=0; i<3; i++)\n        widths[i] = axismaxs[i] - axismins[i];\n    int splitaxis = -1;\n    if(widths[0] >= widths[1] && widths[0] >= widths[2])\n        splitaxis = 0;\n    else if(widths[1] >= widths[0] && widths[1] >= widths[2])\n        splitaxis = 1;\n    else\n        splitaxis = 2;\n    std::sort(nodes.begin(), nodes.end(), NodeComparator(splitaxis));\n    vector<AABBNode *> left(nnodes/2);\n    vector<AABBNode *> right(nnodes - nnodes/2);\n    for(int i=0; i<nnodes/2; i++)\n    {\n        left[i] = nodes[i];\n    }\n    for(int i=nnodes/2; i<nnodes; i++)\n    {\n        right[i-nnodes/2] = nodes[i];\n    }\n    AABBNode *node = new AABBNode;\n    node->left = buildAABB(left);\n    node->right = buildAABB(right);\n    for(int i=0; i<3; i++)\n    {\n        node->box.mins[i] = min(node->left->box.mins[i], node->right->box.mins[i]);\n        node->box.maxs[i] = max(node->left->box.maxs[i], node->right->box.maxs[i]);\n    }\n    return node;\n}\n\nvoid refitAABB(const RigidBodyInstance * instance, AABBNode *node)\n{\n    if(node->childtet != -1)\n    {\n        Eigen::Vector4i tet = instance->getTemplate().getTets().row(node->childtet);\n        for(int k=0; k<3; k++)\n        {\n            node->box.mins[k] = numeric_limits<double>::infinity();\n            node->box.maxs[k] = -numeric_limits<double>::infinity();\n        }\n        for(int k=0; k<4; k++)\n        {\n            Eigen::Vector3d point = instance->c + VectorMath::rotationMatrix(instance->theta)*instance->getTemplate().getVerts().row(tet[k]).transpose();\n            for(int l=0; l<3; l++)\n            {\n                node->box.mins[l] = min(node->box.mins[l], point[l]);\n                node->box.maxs[l] = max(node->box.maxs[l], point[l]);\n            }\n        }\n    }\n    else if(node->left && node->right)\n    {\n        refitAABB(instance, node->left);\n        refitAABB(instance, node->right);\n        for(int i=0; i<3; i++)\n        {\n            node->box.mins[i] = min(node->left->box.mins[i], node->right->box.mins[i]);\n            node->box.maxs[i] = max(node->left->box.maxs[i], node->right->box.maxs[i]);\n        }\n    }\n}\n\nAABBNode *buildAABB(const RigidBodyInstance * instance)\n{    \n    int ntets = (int)instance->getTemplate().getTets().rows();\n    vector<AABBNode *> leaves(ntets);\n    for(int j=0; j<ntets; j++)\n    {\n        AABBNode *leaf = new AABBNode;\n        leaf->childtet = j;\n        Eigen::Vector4i tet = instance->getTemplate().getTets().row(j);\n        BBox box;\n        for(int k=0; k<3; k++)\n        {\n            box.mins[k] = numeric_limits<double>::infinity();\n            box.maxs[k] = -numeric_limits<double>::infinity();\n        }\n        for(int k=0; k<4; k++)\n        {\n            Eigen::Vector3d point = instance->c + VectorMath::rotationMatrix(instance->theta)*instance->getTemplate().getVerts().row(tet[k]).transpose();\n            for(int l=0; l<3; l++)\n            {\n                box.mins[l] = min(box.mins[l], point[l]);\n                box.maxs[l] = max(box.maxs[l], point[l]);\n            }\n        }\n        leaf->box = box;\n        leaves[j] = leaf;\n    }\n    return buildAABB(leaves);\n}\n\nbool vertInTet(const Eigen::Vector3d &p, const Eigen::Vector3d &q1, const Eigen::Vector3d &q2, const Eigen::Vector3d &q3, const Eigen::Vector3d &q4)\n{\n    if( (q2-p).cross(q3-p).dot(q4-p) < 0)\n        return false;\n    if( (p-q1).cross(q3-q1).dot(q4-q1) < 0)\n        return false;\n    if( (q2-q1).cross(p-q1).dot(q4-q1) < 0)\n        return false;\n    if( (q2-q1).cross(q3-q1).dot(p-q1) < 0)\n        return false;\n    return true;\n}\n\nvoid tetTetIntersect(const AABBNode *node1, const AABBNode *node2, int body1, int body2, const std::vector<RigidBodyInstance *> instances, std::set<Collision> &collisions)\n{\n    if(body1==body2)\n        return;\n\n    Eigen::Vector4i tet1 = instances[body1]->getTemplate().getTets().row(node1->childtet);\n    Eigen::Vector4i tet2 = instances[body2]->getTemplate().getTets().row(node2->childtet);\n    Eigen::Vector3d verts1[4];\n    Eigen::Vector3d verts2[4];\n    for(int i=0; i<4; i++)\n    {\n        verts1[i] = instances[body1]->c + VectorMath::rotationMatrix(instances[body1]->theta)*instances[body1]->getTemplate().getVerts().row(tet1[i]).transpose();\n        verts2[i] = instances[body2]->c + VectorMath::rotationMatrix(instances[body2]->theta)*instances[body2]->getTemplate().getVerts().row(tet2[i]).transpose();\n    }\n    for(int i=0; i<4; i++)\n    {\n        if(vertInTet(verts1[i], verts2[0], verts2[1], verts2[2], verts2[3]))\n        {\n            Collision c;\n            c.body1 = body1;\n            c.body2 = body2;\n            c.collidingVertex = tet1[i];\n            c.collidingTet = node2->childtet;\n            collisions.insert(c);\n        }\n        if(vertInTet(verts2[i], verts1[0], verts1[1], verts1[2], verts1[3]))\n        {\n            Collision c;\n            c.body1 = body2;\n            c.body2 = body1;\n            c.collidingVertex = tet2[i];\n            c.collidingTet = node1->childtet;\n            collisions.insert(c);\n        }\n    }\n}\n\nvoid intersect(const AABBNode *node1, const AABBNode *node2, int body1, int body2, const std::vector<RigidBodyInstance *> instances, std::set<Collision> &collisions)\n{\n    if(!node1 || !node2)\n        return;\n\n    if(!intersects(node1->box, node2->box))\n        return;\n\n    if(node1->childtet != -1)\n    {\n        if(node2->childtet != -1)\n        {\n            tetTetIntersect(node1, node2, body1, body2, instances, collisions);\n        }\n        else\n        {\n            intersect(node1, node2->left, body1, body2, instances, collisions);\n            intersect(node1, node2->right, body1, body2, instances, collisions);\n        }\n    }\n    else\n    {\n        if(node2->childtet != -1)\n        {\n            intersect(node1->left, node2, body1, body2, instances, collisions);\n            intersect(node1->right, node2, body1, body2, instances, collisions);\n        }\n        else\n        {\n            intersect(node1->left, node2->left, body1, body2, instances, collisions);\n            intersect(node1->left, node2->right, body1, body2, instances, collisions);\n            intersect(node1->right, node2->left, body1, body2, instances, collisions);\n            intersect(node1->right, node2->right, body1, body2, instances, collisions);\n        }\n    }\n}\n\nvoid collisionDetection(const std::vector<RigidBodyInstance *> instances, std::set<Collision> &collisions)\n{\n    collisions.clear();\n    int nbodies = (int)instances.size();\n\n    for(int i=0; i<nbodies; i++)\n    {\n        refitAABB(instances[i], instances[i]->AABB);\n    }\n\n    for(int i=0; i<nbodies; i++)\n    {\n        for(int j=i+1; j<nbodies; j++)\n        {\n            intersect(instances[i]->AABB, instances[j]->AABB, i, j, instances, collisions);\n        }\n    }\n\n    // floor\n\n    for (int i=0; i<nbodies; i++)\n    {\n        int nverts = instances[i]->getTemplate().getVerts().rows();\n        for (int j = 0; j < nverts; j++)\n        {\n            Eigen::Vector3d point = VectorMath::rotationMatrix(instances[i]->theta) * instances[i]->getTemplate().getVerts().row(j).transpose() + instances[i]->c;\n            if (point[1] <= -1.0)\n            {\n                Collision c;\n                c.body1 = i;\n                c.body2 = -1;\n                c.collidingTet = -1;\n                c.collidingVertex = j;\n                collisions.insert(c);\n            }\n        }\n    }\n}\n", "meta": {"hexsha": "61738ddc52365f7fe2d7da17881e9e05ff5269a3", "size": 8910, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "CollisionDetection.cpp", "max_stars_repo_name": "Reimilia/DiscreteElasticRods", "max_stars_repo_head_hexsha": "1651b29ec41d03e2fa9898148f1a70a5e2845537", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2020-01-02T12:28:28.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T00:03:30.000Z", "max_issues_repo_path": "CollisionDetection.cpp", "max_issues_repo_name": "Reimilia/DiscreteElasticRods", "max_issues_repo_head_hexsha": "1651b29ec41d03e2fa9898148f1a70a5e2845537", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-01-17T07:14:52.000Z", "max_issues_repo_issues_event_max_datetime": "2020-01-17T07:14:52.000Z", "max_forks_repo_path": "CollisionDetection.cpp", "max_forks_repo_name": "Reimilia/DiscreteElasticRods", "max_forks_repo_head_hexsha": "1651b29ec41d03e2fa9898148f1a70a5e2845537", "max_forks_repo_licenses": ["Apache-2.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.409556314, "max_line_length": 171, "alphanum_fraction": 0.5502805836, "num_tokens": 2598, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6261241911813151, "lm_q2_score": 0.49218813572079556, "lm_q1q2_score": 0.3081708983872225}}
{"text": "#include \"shortest_path.h\"\n#include <iostream>\n#include <fstream>\n#include <math.h>\n\n#include <boost/algorithm/string.hpp>\n\nnamespace ShortestPath\n{\n    double eps = 1e-7;\n\n    struct dwell\n    {\n        int xlabel;\n        int ylabel;\n        int xnode;\n        int ynode;\n        double overlap;\n        double dist;\n        \n        dwell(int _xlabel, int _ylabel, int _xnode, int _ynode, double _overlap, double _dist)\n        {\n            xlabel = _xlabel;\n            ylabel = _ylabel;\n            xnode = _xnode;\n            ynode = _ynode;\n            overlap = _overlap;\n            dist = _dist;\n        }\n\n        bool operator< (const dwell& that) const\n        {\n            return this->overlap > that.overlap || (fabs(this->overlap - that.overlap) < eps && this->dist < that.dist);\n        }\n\n        friend std::ostream& operator<< (std::ostream& out, const dwell& that)\n        {\n            out << \"overlap \" << that.xlabel << \"[\" << that.xnode << \"] \" << that.ylabel << \"[\" << that.ynode << \"] = \" << that.overlap;\n            out << \" distance = \" << that.dist;\n            return out;\n        }\n    };\n\n    double euclidDistance(const Eigen::Vector3d& x, const Eigen::Vector3d& y)\n    {\n        Eigen::Vector3d z;\n        z = x - y;\n        return z.norm();\n    }\n\n    double arcDistance(const Eigen::Vector3d& x, const Eigen::Vector3d& y)\n    {\n        assert(fabs(x.norm() - 1.0) < 1e-7);\n        assert(fabs(y.norm() - 1.0) < 1e-7);\n\n        double costheta = x.dot(y);\n        if (costheta < -1.0) costheta = -1.0;\n        if (costheta > 1.0) costheta = 1.0;\n        return acos(costheta);\n    }\n\n    std::vector<std::set<int>> init(const std::string& fileName)\n    {\n        std::ifstream poseKeypointResult(\"pose_keypoint_200_\" + fileName + \".txt\");\n        std::vector<std::set<int>> visibleResult;\n        std::string s;\n        while (getline(poseKeypointResult, s))\n        {\n            std::set<int> set;\n            getline(poseKeypointResult, s);\n            std::vector<std::string> indices;\n            boost::split(indices, s, boost::is_any_of(\" \"));\n            for (const std::string& id: indices)\n            {\n                if (id.size() > 0)\n                {\n                    set.insert(std::stoi(id));\n                }\n            }\n            visibleResult.push_back(set);\n        }\n        poseKeypointResult.close();\n        return visibleResult;\n    }\n\n    double calcOverlap(const std::set<int>& A, const std::set<int>& B)\n    {\n        std::vector<int> i, u;\n        std::set_intersection(A.begin(), A.end(), B.begin(), B.end(), std::back_inserter(i));\n        std::set_union(A.begin(), A.end(), B.begin(), B.end(), std::back_inserter(u));\n        return (double)i.size() / (double)u.size();\n    }\n\n    std::vector<Eigen::Vector3d> getView(const Eigen::Vector3d& camera_normal, int horizontal_count, int vertical_count)\n    {\n        std::vector<Eigen::Vector3d> views;\n\n        double horizontal_angle = 2 * M_PI / horizontal_count;\n        double vertical_angle = M_PI / (vertical_count - 1);\n\n        for (int i = 0; i < vertical_count; ++i)\n        {\n            for (int j = 0; j < horizontal_count; ++j)\n            {\n                if ((i == 0 || i == vertical_count - 1) && j)\n                {\n                    continue;\n                }\n\n                double horizontal_spin = horizontal_angle * j;\n                double vertical_spin = vertical_angle * i;\n\n                Eigen::Matrix3d rotation, rotation_inv;\n                rotation = Eigen::AngleAxisd(vertical_spin, Eigen::Vector3d::UnitY()) * Eigen::AngleAxisd(horizontal_spin, camera_normal);\n                rotation_inv = rotation.inverse();\n                views.push_back(rotation_inv * camera_normal);\n            }\n        }\n        return views;\n    }\n\n    void execute(const std::string& fileName)\n    {\n        std::cout << \"name = \" << fileName << std::endl;\n        std::vector<std::set<int>> group = init(fileName);\n        std::vector<Eigen::Vector3d> views = getView(Eigen::Vector3d(0, 0, -1), 18, 13);\n        \n        std::vector<int> selected_views = {31, 23, 84, 57, 94, 148, 179, 171, 50, 35, 26};\n\n\n        int ecnt = 0;\n        std::vector<dwell> dummy;\n        \n        int n = selected_views.size();\n        double** g = new double*[n];\n        for (int i = 0; i < n; ++i)\n        {\n            g[i] = new double[n];\n        }\n        double** f = new double*[1 << n];\n        for (int i = 0; i < (1 << n); ++i)\n        {\n            f[i] = new double[n];\n            for (int j = 0; j < n; ++j)\n            {\n                f[i][j] = 1e10;\n            }\n        }\n        int** fa = new int*[1 << n];\n        for (int i = 0; i < (1 << n); ++i)\n        {\n            fa[i] = new int[n];\n            for (int j = 0; j < n; ++j)\n            {\n                fa[i][j] = -1;\n            }\n        }\n\n        for (int i = 0; i < selected_views.size(); ++i)\n        {\n            g[i][i] = 0.0;\n            for (int j = i + 1; j < selected_views.size(); ++j)\n            {\n                int x = selected_views[i];\n                int y = selected_views[j];\n                double overlap = calcOverlap(group[x], group[y]);\n                double dist = arcDistance(views[x], views[y]);\n                g[i][j] = g[j][i] = dist;\n                /* if (overlap + eps >= 0.5 || dist <= 2.0 + eps)\n                {\n                    ++ecnt;\n                    std::cout << \"overlap \" << i << \"[\" << x << \"] \" << j << \"[\" << y << \"] = \";\n                    std::cout << calcOverlap(group[x], group[y]) << \"(\" << group[x].size() << \", \" << group[y].size() << \")\";\n                    std::cout << \" distance = \" << arcDistance(views[x], views[y]);\n                    std::cout << std::endl;\n                } */\n                dummy.push_back(dwell(i, j, x, y, overlap, dist));\n            }\n        }\n        std::sort(dummy.begin(), dummy.end());\n        for (const dwell& dd: dummy)\n        {\n            std::cout << dd << std::endl;\n        }\n\n        // std::cout << \"edge count = \" << ecnt << std::endl;\n        \n        /*for (int selected_view: selected_views)\n        {\n            Eigen::Vector3d vv = views[selected_view];\n            std::cout << \"view \" << selected_view << \": [\" << vv[0] << \", \" << vv[1] << \", \" << vv[2] << \"]\" << std::endl;\n        }*/\n\n        // TSP\n\n        for (int i = 0; i < n; ++i)\n        {\n            f[0][i] = 0.0;\n        }\n        for (int i = 1; i < (1 << n); ++i)\n        {\n            for (int v = 0; v < n; ++v)\n            {\n                if (i & (1 << v))\n                {\n                    // f[i][v] = ...\n                    for (int u = 0; u < n; ++u)\n                    {\n                        double dist = f[i - (1 << v)][u] + g[u][v];\n                        if (dist < f[i][v])\n                        {\n                            f[i][v] = dist;\n                            fa[i][v] = u;\n                        }\n                    }\n                }\n            }\n        }\n\n        std::vector<int> answer;\n        double mindist = 1e10;\n        int where = -1;\n        for (int i = 0; i < n; ++i)\n        {\n            if (f[(1 << n) - 1][i] < mindist)\n            {\n                mindist = f[(1 << n) - 1][i];\n                where = i;\n            }\n        }\n\n        int curbin = (1 << n) - 1;\n        int where0 = where;\n        while (curbin)\n        {\n            answer.push_back(where0);\n            int nxt = fa[curbin][where0];\n            curbin -= (1 << where0);\n            where0 = nxt;\n        }\n\n        std::cout << \"minimum distance = \" << f[(1 << n) - 1][where] << std::endl;\n        for (int i = 0; i < answer.size() - 1; ++i)\n        {\n            int x = selected_views[answer[i]];\n            int y = selected_views[answer[i + 1]];\n            std::cout << answer[i] << \"(\" << x << \") \" << answer[i + 1] << \"(\" << y << \")\";\n            std::cout << \" dis = \" << g[answer[i]][answer[i + 1]] << \" overlap = \" << calcOverlap(group[x], group[y]);\n            std::cout << std::endl;\n        }\n\n    }\n}", "meta": {"hexsha": "3435376c33638016ae9075190d3e9490edfa5a81", "size": 8060, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "RenderKinect/shortest_path.cpp", "max_stars_repo_name": "MrJia1997/RenderKinect", "max_stars_repo_head_hexsha": "6cc6d6a56ce6a925920e155db5aa6f5239c563e8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "RenderKinect/shortest_path.cpp", "max_issues_repo_name": "MrJia1997/RenderKinect", "max_issues_repo_head_hexsha": "6cc6d6a56ce6a925920e155db5aa6f5239c563e8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "RenderKinect/shortest_path.cpp", "max_forks_repo_name": "MrJia1997/RenderKinect", "max_forks_repo_head_hexsha": "6cc6d6a56ce6a925920e155db5aa6f5239c563e8", "max_forks_repo_licenses": ["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.8577075099, "max_line_length": 138, "alphanum_fraction": 0.4251861042, "num_tokens": 2138, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6261241911813151, "lm_q2_score": 0.49218813572079556, "lm_q1q2_score": 0.3081708983872225}}
{"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_translation_hpp__\n#define __pinocchio_joint_translation_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/skew.hpp\"\n\nnamespace pinocchio\n{\n\n  template<typename Scalar, int Options=0> struct MotionTranslationTpl;\n  typedef MotionTranslationTpl<double> MotionTranslation;\n  \n  template<typename Scalar, int Options>\n  struct SE3GroupAction< MotionTranslationTpl<Scalar,Options> >\n  {\n    typedef MotionTpl<Scalar,Options> ReturnType;\n  };\n  \n  template<typename Scalar, int Options, typename MotionDerived>\n  struct MotionAlgebraAction< MotionTranslationTpl<Scalar,Options>, MotionDerived>\n  {\n    typedef MotionTpl<Scalar,Options> ReturnType;\n  };\n\n  template<typename _Scalar, int _Options>\n  struct traits< MotionTranslationTpl<_Scalar,_Options> >\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  }; // traits MotionTranslationTpl\n\n  template<typename _Scalar, int _Options>\n  struct MotionTranslationTpl\n  : MotionBase< MotionTranslationTpl<_Scalar,_Options> >\n  {\n    EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n    \n    MOTION_TYPEDEF_TPL(MotionTranslationTpl);\n\n    MotionTranslationTpl() {}\n    \n    template<typename Vector3Like>\n    MotionTranslationTpl(const Eigen::MatrixBase<Vector3Like> & v)\n    : m_v(v)\n    {}\n    \n    MotionTranslationTpl(const MotionTranslationTpl & other)\n    : m_v(other.m_v)\n    {}\n \n    Vector3 & operator()() { return m_v; }\n    const Vector3 & operator()() const { return m_v; }\n    \n    inline PlainReturnType plain() const\n    {\n      return PlainReturnType(m_v,PlainReturnType::Vector3::Zero());\n    }\n    \n    bool isEqual_impl(const MotionTranslationTpl & other) const\n    {\n      return m_v == other.m_v;\n    }\n    \n    MotionTranslationTpl & operator=(const MotionTranslationTpl & other)\n    {\n      m_v = other.m_v;\n      return *this;\n    }\n    \n    template<typename Derived>\n    void addTo(MotionDense<Derived> & other) const\n    {\n      other.linear() += m_v;\n    }\n    \n    template<typename Derived>\n    void setTo(MotionDense<Derived> & other) const\n    {\n      other.linear() = m_v;\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.rotation() * m_v; // TODO: check efficiency\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.rotation().transpose() * m_v;\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      mout.linear().noalias() = v.angular().cross(m_v);\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    const Vector3 & linear() const { return m_v; }\n    Vector3 & linear() { return m_v; }\n    \n  protected:\n    \n    Vector3 m_v;\n    \n  }; // struct MotionTranslationTpl\n  \n  template<typename S1, int O1, typename MotionDerived>\n  inline typename MotionDerived::MotionPlain\n  operator+(const MotionTranslationTpl<S1,O1> & m1,\n            const MotionDense<MotionDerived> & m2)\n  {\n    return typename MotionDerived::MotionPlain(m2.linear() + m1.linear(), m2.angular());\n  }\n  \n  template<typename Scalar, int Options> struct TransformTranslationTpl;\n  \n  template<typename _Scalar, int _Options>\n  struct traits< TransformTranslationTpl<_Scalar,_Options> >\n  {\n    enum {\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 LinearType & LinearRef;\n    typedef const LinearType & ConstLinearRef;\n    typedef typename traits<PlainType>::ActionMatrixType ActionMatrixType;\n    typedef typename traits<PlainType>::HomogeneousMatrixType HomogeneousMatrixType;\n  }; // traits TransformTranslationTpl\n  \n  template<typename Scalar, int Options>\n  struct SE3GroupAction< TransformTranslationTpl<Scalar,Options> >\n  { typedef typename traits <TransformTranslationTpl<Scalar,Options> >::PlainType ReturnType; };\n\n  template<typename _Scalar, int _Options>\n  struct TransformTranslationTpl\n  : SE3Base< TransformTranslationTpl<_Scalar,_Options> >\n  {\n    EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n    PINOCCHIO_SE3_TYPEDEF_TPL(TransformTranslationTpl);\n    typedef typename traits<TransformTranslationTpl>::Vector3 Vector3;\n    \n    TransformTranslationTpl() {}\n    \n    template<typename Vector3Like>\n    TransformTranslationTpl(const Eigen::MatrixBase<Vector3Like> & translation)\n    : m_translation(translation)\n    {}\n    \n    PlainType plain() const\n    {\n      PlainType res(PlainType::Identity());\n      res.rotation().setIdentity();\n      res.translation() = translation();\n      \n      return res;\n    }\n    \n    operator PlainType() const { return plain(); }\n    \n    template<typename S2, int O2>\n    typename SE3GroupAction<TransformTranslationTpl>::ReturnType\n    se3action(const SE3Tpl<S2,O2> & m) const\n    {\n      typedef typename SE3GroupAction<TransformTranslationTpl>::ReturnType ReturnType;\n      ReturnType res(m);\n      res.translation() += translation();\n      \n      return res;\n    }\n    \n    ConstLinearRef translation() const { return m_translation; }\n    LinearRef translation() { return m_translation; }\n    \n    AngularType rotation() const { return AngularType(3,3); }\n    \n    bool isEqual(const TransformTranslationTpl & other) const\n    {\n      return m_translation == other.m_translation;\n    }\n    \n  protected:\n    \n    LinearType m_translation;\n  };\n  \n  template<typename Scalar, int Options> struct ConstraintTranslationTpl;\n  \n  template<typename _Scalar, int _Options>\n  struct traits< ConstraintTranslationTpl<_Scalar,_Options> >\n  {\n    typedef _Scalar Scalar;\n    \n    enum { Options = _Options };\n    enum { LINEAR = 0, ANGULAR = 3 };\n    \n    typedef MotionTranslationTpl<Scalar,Options> JointMotion;\n    typedef Eigen::Matrix<Scalar,3,1,Options> JointForce;\n    typedef Eigen::Matrix<Scalar,6,3,Options> DenseBase;\n    \n    typedef DenseBase MatrixReturnType;\n    typedef const DenseBase ConstMatrixReturnType;\n  }; // traits ConstraintTranslationTpl\n  \n  template<typename _Scalar, int _Options>\n  struct ConstraintTranslationTpl\n  : ConstraintBase< ConstraintTranslationTpl<_Scalar,_Options> >\n  {\n    EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n    \n    PINOCCHIO_CONSTRAINT_TYPEDEF_TPL(ConstraintTranslationTpl)\n    \n    enum { NV = 3 };\n    \n    ConstraintTranslationTpl() {}\n    \n//    template<typename S1, int O1>\n//    Motion operator*(const MotionTranslationTpl<S1,O1> & vj) const\n//    { return Motion(vj(), Motion::Vector3::Zero()); }\n    \n    template<typename Vector3Like>\n    JointMotion __mult__(const Eigen::MatrixBase<Vector3Like> & v) const\n    {\n      EIGEN_STATIC_ASSERT_VECTOR_SPECIFIC_SIZE(Vector3Like,3);\n      return JointMotion(v);\n    }\n    \n    int nv_impl() const { return NV; }\n    \n    struct ConstraintTranspose\n    {\n      const ConstraintTranslationTpl & ref;\n      ConstraintTranspose(const ConstraintTranslationTpl & ref) : ref(ref) {}\n      \n      template<typename Derived>\n      typename ForceDense<Derived>::ConstLinearType\n      operator* (const ForceDense<Derived> & phi)\n      {\n        return phi.linear();\n      }\n      \n      /* [CRBA]  MatrixBase operator* (Constraint::Transpose S, ForceSet::Block) */\n      template<typename MatrixDerived>\n      const typename SizeDepType<3>::RowsReturn<MatrixDerived>::ConstType\n      operator*(const Eigen::MatrixBase<MatrixDerived> & F) const\n      {\n        assert(F.rows()==6);\n        return F.derived().template middleRows<3>(LINEAR);\n      }\n      \n    }; // struct ConstraintTranspose\n    \n    ConstraintTranspose transpose () const { return ConstraintTranspose(*this); }\n    \n    DenseBase matrix_impl() const\n    {\n      DenseBase S;\n      S.template middleRows<3>(LINEAR).setIdentity();\n      S.template middleRows<3>(ANGULAR).setZero();\n      return S;\n    }\n    \n    template<typename S1, int O1>\n    Eigen::Matrix<S1,6,3,O1> se3Action(const SE3Tpl<S1,O1> & m) const\n    {\n      Eigen::Matrix<S1,6,3,O1> M;\n      M.template middleRows<3>(LINEAR) = m.rotation();\n      M.template middleRows<3>(ANGULAR).setZero();\n      \n      return M;\n    }\n    \n    template<typename S1, int O1>\n    Eigen::Matrix<S1,6,3,O1> se3ActionInverse(const SE3Tpl<S1,O1> & m) const\n    {\n      Eigen::Matrix<S1,6,3,O1> M;\n      M.template middleRows<3>(LINEAR) = m.rotation().transpose();\n      M.template middleRows<3>(ANGULAR).setZero();\n      \n      return M;\n    }\n    \n    template<typename MotionDerived>\n    DenseBase motionAction(const MotionDense<MotionDerived> & m) const\n    {\n      const typename MotionDerived::ConstAngularType w = m.angular();\n      \n      DenseBase res;\n      skew(w,res.template middleRows<3>(LINEAR));\n      res.template middleRows<3>(ANGULAR).setZero();\n      \n      return res;\n    }\n    \n    bool isEqual(const ConstraintTranslationTpl &) const { return true; }\n    \n  }; // struct ConstraintTranslationTpl\n  \n  template<typename MotionDerived, typename S2, int O2>\n  inline typename MotionDerived::MotionPlain\n  operator^(const MotionDense<MotionDerived> & m1,\n            const MotionTranslationTpl<S2,O2> & m2)\n  {\n    return m2.motionAction(m1);\n  }\n  \n  /* [CRBA] ForceSet operator* (Inertia Y,Constraint S) */\n  template<typename S1, int O1, typename S2, int O2>\n  inline Eigen::Matrix<S2,6,3,O2>\n  operator*(const InertiaTpl<S1,O1> & Y,\n            const ConstraintTranslationTpl<S2,O2> &)\n  {\n    typedef ConstraintTranslationTpl<S2,O2> Constraint;\n    Eigen::Matrix<S2,6,3,O2> M;\n    alphaSkew(Y.mass(),Y.lever(),M.template middleRows<3>(Constraint::ANGULAR));\n    M.template middleRows<3>(Constraint::LINEAR).setZero();\n    M.template middleRows<3>(Constraint::LINEAR).diagonal().fill(Y.mass ());\n    \n    return M;\n  }\n  \n  /* [ABA] Y*S operator*/\n  template<typename M6Like, typename S2, int O2>\n  inline const typename SizeDepType<3>::ColsReturn<M6Like>::ConstType\n  operator*(const Eigen::MatrixBase<M6Like> & Y,\n            const ConstraintTranslationTpl<S2,O2> &)\n  {\n    typedef ConstraintTranslationTpl<S2,O2> Constraint;\n    return Y.derived().template middleCols<3>(Constraint::LINEAR);\n  }\n  \n  template<typename S1, int O1>\n  struct SE3GroupAction< ConstraintTranslationTpl<S1,O1> >\n  { typedef Eigen::Matrix<S1,6,3,O1> ReturnType; };\n  \n  template<typename S1, int O1, typename MotionDerived>\n  struct MotionAlgebraAction< ConstraintTranslationTpl<S1,O1>,MotionDerived >\n  { typedef Eigen::Matrix<S1,6,3,O1> ReturnType; };\n\n  template<typename Scalar, int Options> struct JointTranslationTpl;\n  \n  template<typename _Scalar, int _Options>\n  struct traits< JointTranslationTpl<_Scalar,_Options> >\n  {\n    enum {\n      NQ = 3,\n      NV = 3\n    };\n    typedef _Scalar Scalar;\n    enum { Options = _Options };\n    typedef JointDataTranslationTpl<Scalar,Options> JointDataDerived;\n    typedef JointModelTranslationTpl<Scalar,Options> JointModelDerived;\n    typedef ConstraintTranslationTpl<Scalar,Options> Constraint_t;\n    typedef TransformTranslationTpl<Scalar,Options> Transformation_t;\n    typedef MotionTranslationTpl<Scalar,Options> 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  }; // traits JointTranslationTpl\n  \n  template<typename Scalar, int Options>\n  struct traits< JointDataTranslationTpl<Scalar,Options> >\n  { typedef JointTranslationTpl<Scalar,Options> JointDerived; };\n  \n  template<typename Scalar, int Options>\n  struct traits< JointModelTranslationTpl<Scalar,Options> >\n  { typedef JointTranslationTpl<Scalar,Options> JointDerived; };\n  \n  template<typename _Scalar, int _Options>\n  struct JointDataTranslationTpl\n  : public JointDataBase< JointDataTranslationTpl<_Scalar,_Options> >\n  {\n    EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n    \n    typedef JointTranslationTpl<_Scalar,_Options> 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    JointDataTranslationTpl()\n    : M(Transformation_t::Vector3::Zero())\n    , v(Motion_t::Vector3::Zero())\n    , U(U_t::Zero())\n    , Dinv(D_t::Zero())\n    , UDinv(UD_t::Zero())\n    {}\n\n    static std::string classname() { return std::string(\"JointDataTranslation\"); }\n    std::string shortname() const { return classname(); }\n  }; // struct JointDataTranslationTpl\n\n  PINOCCHIO_JOINT_CAST_TYPE_SPECIALIZATION(JointModelTranslationTpl);\n  template<typename _Scalar, int _Options>\n  struct JointModelTranslationTpl\n  : public JointModelBase< JointModelTranslationTpl<_Scalar,_Options> >\n  {\n    EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n    \n    typedef JointTranslationTpl<_Scalar,_Options> JointDerived;\n    PINOCCHIO_JOINT_TYPEDEF_TEMPLATE(JointDerived);\n    \n    typedef JointModelBase<JointModelTranslationTpl> 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      data.M.translation() = this->jointConfigSelector(qs);\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      data.v.linear() = this->jointVelocitySelector(vs);\n    }\n    \n    template<typename Matrix6Like>\n    void calc_aba(JointDataDerived & data,\n                  const Eigen::MatrixBase<Matrix6Like> & I,\n                  const bool update_I) const\n    {\n      data.U = I.template middleCols<3>(Inertia::LINEAR);\n      \n      // compute inverse\n//      data.Dinv.setIdentity();\n//      data.U.template middleRows<3>(Inertia::LINEAR).llt().solveInPlace(data.Dinv);\n      internal::PerformStYSInversion<Scalar>::run(data.U.template middleRows<3>(Inertia::LINEAR),data.Dinv);\n      \n      data.UDinv.template middleRows<3>(Inertia::LINEAR).setIdentity(); // can be put in data constructor\n      data.UDinv.template middleRows<3>(Inertia::ANGULAR).noalias() = data.U.template middleRows<3>(Inertia::ANGULAR) * data.Dinv;\n      \n      if (update_I)\n      {\n        Matrix6Like & I_ = PINOCCHIO_EIGEN_CONST_CAST(Matrix6Like,I);\n        I_.template block<3,3>(Inertia::ANGULAR,Inertia::ANGULAR)\n        -= data.UDinv.template middleRows<3>(Inertia::ANGULAR) * I_.template block<3,3>(Inertia::LINEAR, Inertia::ANGULAR);\n        I_.template middleCols<3>(Inertia::LINEAR).setZero();\n        I_.template block<3,3>(Inertia::LINEAR,Inertia::ANGULAR).setZero();\n      }\n    }\n    \n    static std::string classname() { return std::string(\"JointModelTranslation\"); }\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    JointModelTranslationTpl<NewScalar,Options> cast() const\n    {\n      typedef JointModelTranslationTpl<NewScalar,Options> ReturnType;\n      ReturnType res;\n      res.setIndexes(id(),idx_q(),idx_v());\n      return res;\n    }\n\n  }; // struct JointModelTranslationTpl\n  \n} // namespace pinocchio\n\n#include <boost/type_traits.hpp>\n\nnamespace boost\n{\n  template<typename Scalar, int Options>\n  struct has_nothrow_constructor< ::pinocchio::JointModelTranslationTpl<Scalar,Options> >\n  : public integral_constant<bool,true> {};\n  \n  template<typename Scalar, int Options>\n  struct has_nothrow_copy< ::pinocchio::JointModelTranslationTpl<Scalar,Options> >\n  : public integral_constant<bool,true> {};\n  \n  template<typename Scalar, int Options>\n  struct has_nothrow_constructor< ::pinocchio::JointDataTranslationTpl<Scalar,Options> >\n  : public integral_constant<bool,true> {};\n  \n  template<typename Scalar, int Options>\n  struct has_nothrow_copy< ::pinocchio::JointDataTranslationTpl<Scalar,Options> >\n  : public integral_constant<bool,true> {};\n}\n\n#endif // ifndef __pinocchio_joint_translation_hpp__\n", "meta": {"hexsha": "a65869f20cf579e3efdd35a85c9929e2499027f0", "size": 18480, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/multibody/joint/joint-translation.hpp", "max_stars_repo_name": "thanhndv212/pinocchio", "max_stars_repo_head_hexsha": "3b4d272bf4e8a231954b71201ee7e0963c944aef", "max_stars_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_stars_count": 716.0, "max_stars_repo_stars_event_min_datetime": "2015-03-30T16:26:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T12:26:58.000Z", "max_issues_repo_path": "src/multibody/joint/joint-translation.hpp", "max_issues_repo_name": "thanhndv212/pinocchio", "max_issues_repo_head_hexsha": "3b4d272bf4e8a231954b71201ee7e0963c944aef", "max_issues_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_issues_count": 1130.0, "max_issues_repo_issues_event_min_datetime": "2015-02-21T17:30:44.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T09:06:22.000Z", "max_forks_repo_path": "src/multibody/joint/joint-translation.hpp", "max_forks_repo_name": "thanhndv212/pinocchio", "max_forks_repo_head_hexsha": "3b4d272bf4e8a231954b71201ee7e0963c944aef", "max_forks_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_forks_count": 239.0, "max_forks_repo_forks_event_min_datetime": "2015-02-05T14:15:14.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-14T23:51:47.000Z", "avg_line_length": 32.0833333333, "max_line_length": 130, "alphanum_fraction": 0.6912337662, "num_tokens": 4605, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6261241772283033, "lm_q2_score": 0.49218813572079556, "lm_q1q2_score": 0.3081708915197156}}
{"text": "/*\n\tCopyright (C) 2003-2013 by David White <davewx7@gmail.com>\n\t\n    This program is free software: you can redistribute it and/or modify\n    it under the terms of the GNU General Public License as published by\n    the Free Software Foundation, either version 2 of the License, or\n    (at your option) any later version.\n\n    This program is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n    GNU General Public License for more details.\n\n    You should have received a copy of the GNU General Public License\n    along with this program.  If not, see <http://www.gnu.org/licenses/>.\n*/\n#ifndef DECIMAL_HPP_INCLUDED\n#define DECIMAL_HPP_INCLUDED\n\n#include <string>\n\n#include <iosfwd>\n#include <boost/cstdint.hpp>\n#if defined(TARGET_BLACKBERRY)\n#include <math.h>\n#endif\n\nstatic const int64_t DECIMAL_PRECISION = 1000000;\nstatic const int64_t DECIMAL_PLACES = 6;\n\nclass decimal\n{\npublic:\n\tstatic decimal from_string(const std::string& s);\n\tstatic decimal from_int(int v) { return decimal(v); }\n\tstatic decimal from_raw_value(int64_t v) { decimal d; d.value_ = v; return d; }\n\tstatic decimal epsilon() { return decimal::from_raw_value(static_cast<int64_t>(1)); }\n\tdecimal() : value_(0) {}\n\texplicit decimal(int value) : value_(int64_t(value)*DECIMAL_PRECISION) {}\n#if defined(TARGET_BLACKBERRY)\n\texplicit decimal(double value) : value_(llround(value*DECIMAL_PRECISION)) {}\n#else\n\texplicit decimal(double value) : value_(int64_t(value*DECIMAL_PRECISION)) {}\n#endif\n\n\tint64_t value() const { return value_; }\n\tint as_int() const { return int( value_/DECIMAL_PRECISION ); }\n\tdouble as_float() const { return value_/double(DECIMAL_PRECISION); }\n\tint64_t fractional() const { return value_%DECIMAL_PRECISION; }\n\n\tdecimal operator-() const {\n\t\treturn decimal(from_raw_value(-value_));\n\t}\n\n\tfriend decimal operator+(const decimal& a, const decimal& b);\n\tfriend decimal operator-(const decimal& a, const decimal& b);\n\tfriend decimal operator*(const decimal& a, const decimal& b);\n\tfriend decimal operator/(const decimal& a, const decimal& b);\n\n\tvoid operator+=(decimal a) { *this = *this + a; } \n\tvoid operator-=(decimal a) { *this = *this - a; } \n\tvoid operator*=(decimal a) { *this = *this * a; } \n\tvoid operator/=(decimal a) { *this = *this / a; }\n\n\tvoid operator+=(int a) { operator+=(decimal::from_int(a)); } \n\tvoid operator-=(int a) { operator-=(decimal::from_int(a)); } \n\tvoid operator*=(int a) { operator*=(decimal::from_int(a)); } \n\tvoid operator/=(int a) { operator/=(decimal::from_int(a)); }\n\nprivate:\n\tint64_t value_;\n};\n\ninline decimal operator+(const decimal& a, const decimal& b) {\n\treturn decimal::from_raw_value(a.value() + b.value());\n}\n\ninline decimal operator-(const decimal& a, const decimal& b) {\n\treturn decimal::from_raw_value(a.value() - b.value());\n}\n\ndecimal operator*(const decimal& a, const decimal& b);\ndecimal operator/(const decimal& a, const decimal& b);\n\ninline bool operator==(const decimal& a, const decimal& b) {\n\treturn a.value() == b.value();\n}\n\ninline bool operator!=(const decimal& a, const decimal& b) {\n\treturn !operator==(a, b);\n}\n\ninline bool operator<=(const decimal& a, const decimal& b) {\n\treturn a.value() <= b.value();\n}\n\ninline bool operator>=(const decimal& a, const decimal& b) {\n\treturn b <= a;\n}\n\ninline bool operator<(const decimal& a, const decimal& b) {\n\treturn !(b <= a);\n}\n\ninline bool operator>(const decimal& a, const decimal& b) {\n\treturn !(a <= b);\n}\n\ninline decimal operator+(decimal a, int b) { return operator+(a, decimal::from_int(b)); }\ninline decimal operator-(decimal a, int b) { return operator-(a, decimal::from_int(b)); }\ninline decimal operator*(decimal a, int b) { return operator*(a, decimal::from_int(b)); }\ninline decimal operator/(decimal a, int b) { return operator/(a, decimal::from_int(b)); }\ninline bool operator<(decimal a, int b) { return operator<(a, decimal::from_int(b)); }\ninline bool operator>(decimal a, int b) { return operator>(a, decimal::from_int(b)); }\ninline bool operator<=(decimal a, int b) { return operator<=(a, decimal::from_int(b)); }\ninline bool operator>=(decimal a, int b) { return operator>=(a, decimal::from_int(b)); }\n\ninline decimal operator+(int a, decimal b) { return operator+(decimal::from_int(a), b); }\ninline decimal operator-(int a, decimal b) { return operator-(decimal::from_int(a), b); }\ninline decimal operator*(int a, decimal b) { return operator*(decimal::from_int(a), b); }\ninline decimal operator/(int a, decimal b) { return operator/(decimal::from_int(a), b); }\ninline bool operator<(int a, decimal b) { return operator<(decimal::from_int(a), b); }\ninline bool operator>(int a, decimal b) { return operator>(decimal::from_int(a), b); }\ninline bool operator<=(int a, decimal b) { return operator<=(decimal::from_int(a), b); }\ninline bool operator>=(int a, decimal b) { return operator>=(decimal::from_int(a), b); }\n\nstd::ostream& operator<<(std::ostream& s, decimal d);\n\n#endif\n", "meta": {"hexsha": "bd4c5ecb69e843a8e1e876626b41ddd58543d39f", "size": 5025, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/decimal.hpp", "max_stars_repo_name": "sweetkristas/anura", "max_stars_repo_head_hexsha": "5e8cbcfc7b761c5c01e5c5509a0fb159b8fb60cd", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/decimal.hpp", "max_issues_repo_name": "sweetkristas/anura", "max_issues_repo_head_hexsha": "5e8cbcfc7b761c5c01e5c5509a0fb159b8fb60cd", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/decimal.hpp", "max_forks_repo_name": "sweetkristas/anura", "max_forks_repo_head_hexsha": "5e8cbcfc7b761c5c01e5c5509a0fb159b8fb60cd", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.6538461538, "max_line_length": 89, "alphanum_fraction": 0.7066666667, "num_tokens": 1283, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6113819732941511, "lm_q2_score": 0.5039061705290805, "lm_q1q2_score": 0.30807914889316823}}
{"text": "#include <iostream>\n#include <iterator>\n#include <iomanip>\n#include <fstream>\n#include <vector>\n#include <algorithm>\n#include <numeric>\n#include <cmath>\n#ifdef _OPENMP\n#include <omp.h>\n#endif\n\n#include <boost/scope_exit.hpp>\n\n#include <boost/program_options.hpp>\n#include <boost/property_tree/ptree.hpp>\n#include <boost/property_tree/json_parser.hpp>\n\n#include <amgcl/amg.hpp>\n#include <amgcl/coarsening/runtime.hpp>\n#include <amgcl/relaxation/runtime.hpp>\n#include <amgcl/mpi/subdomain_deflation.hpp>\n#include <amgcl/mpi/solver/runtime.hpp>\n#include <amgcl/mpi/direct_solver/runtime.hpp>\n#include <amgcl/profiler.hpp>\n\nnamespace amgcl {\n    profiler<> prof;\n}\n\nusing amgcl::precondition;\n\n//---------------------------------------------------------------------------\nstd::vector<ptrdiff_t> read_problem(\n        const amgcl::mpi::communicator &world,\n        const std::string &A_file,\n        const std::string &rhs_file,\n        const std::string &part_file,\n        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{\n    // Read partition\n    std::vector<int> part;\n    std::vector<ptrdiff_t> domain(world.size + 1, 0);\n    ptrdiff_t n = 0;\n    std::string line;\n\n    {\n        std::ifstream f(part_file.c_str());\n        precondition(f, \"Failed to open part file (\" + part_file + \")\");\n\n        while (std::getline(f, line)) {\n            if (line[0] == '%') continue;\n            std::istringstream is(line);\n            ptrdiff_t cols;\n            precondition(is >> n >> cols, \"Unsupported format in matrix file\");\n            break;\n        }\n\n        precondition(n, \"Zero sized partition vector\");\n        precondition(n % block_size == 0, \"Matrix size is not divisible by block_size\");\n\n        part.reserve(n);\n\n        while (std::getline(f, line)) {\n            if (line[0] == '%') continue;\n            std::istringstream is(line);\n            int p;\n            precondition(is >> p, \"Unsupported format in part file\");\n            precondition(p < world.size, \"MPI world does not correspond to partition\");\n\n            part.push_back(p);\n            ++domain[p+1];\n        }\n\n        std::partial_sum(domain.begin(), domain.end(), domain.begin());\n    }\n\n    ptrdiff_t chunk_beg = domain[world.rank];\n    ptrdiff_t chunk_end = domain[world.rank + 1];\n    ptrdiff_t chunk     = chunk_end - chunk_beg;\n\n    // Reorder unknowns\n    std::vector<ptrdiff_t> order(n);\n    {\n        for(ptrdiff_t i = 0; i < n; ++i) {\n            int p = part[i];\n            int j = domain[p]++;\n\n            order[i] = j;\n        }\n\n        std::rotate(domain.begin(), domain.end()-1, domain.end());\n        domain[0] = 0;\n    }\n\n    // Read matrix chunk\n    {\n        std::ifstream A(A_file.c_str());\n        precondition(A, \"Failed to open matrix file (\" + A_file + \")\");\n\n        ptrdiff_t nnz = 0;\n        while ( std::getline(A, line) ) {\n            if (line[0] == '%') continue;\n            std::istringstream is(line);\n            ptrdiff_t rows, m;\n            precondition(is >> rows >> m >> nnz, \"Unsupported format in matrix file\");\n            precondition(rows == n, \"Matrix and partition have incompatible sizes\");\n            precondition(n == m, \"Non-square matrix in matrix file\");\n            break;\n        }\n\n        {\n            std::vector<ptrdiff_t> I, J;\n            std::vector<double>    V;\n\n            ptr.clear();\n            ptr.resize(chunk + 1, 0);\n\n            while (std::getline(A, line)) {\n                if (line[0] == '%') continue;\n                std::istringstream is(line);\n                ptrdiff_t i, j;\n                double v;\n                precondition(is >> i >> j >> v, \"Unsupported format in matrix file\");\n                --i;\n                --j;\n\n                if (part[i] != world.rank) continue;\n\n                ++ptr[order[i] + 1 - chunk_beg];\n\n                I.push_back(order[i] - chunk_beg);\n                J.push_back(order[j]);\n                V.push_back(v);\n            }\n\n            std::partial_sum(ptr.begin(), ptr.end(), ptr.begin());\n\n            ptrdiff_t loc_nnz = ptr.back();\n\n            col.clear(); col.resize(loc_nnz);\n            val.clear(); val.resize(loc_nnz);\n\n            for(ptrdiff_t i = 0; i < loc_nnz; ++i) {\n                ptrdiff_t row = I[i];\n                col[ptr[row]] = J[i];\n                val[ptr[row]] = V[i];\n                ++ptr[row];\n            }\n            std::rotate(ptr.begin(), ptr.end()-1, ptr.end());\n            ptr[0] = 0;\n        }\n    }\n\n    // Read RHS chunk.\n    {\n        std::ifstream f(rhs_file.c_str());\n        precondition(f, \"Failed to open rhs file (\" + rhs_file + \")\");\n\n        while (std::getline(f, line)) {\n            if (line[0] == '%') continue;\n            std::istringstream is(line);\n            ptrdiff_t rows, cols;\n            precondition(is >> rows >> cols, \"Unsupported format in matrix file\");\n            precondition(rows == n, \"RHS size should coincide with matrix size\");\n            break;\n        }\n\n        rhs.clear();\n        rhs.reserve(chunk);\n\n        ptrdiff_t pos = 0;\n        while (std::getline(f, line)) {\n            if (line[0] == '%') continue;\n            std::istringstream is(line);\n            double v;\n            precondition(is >> v, \"Unsupported format in RHS file\");\n\n            if (part[pos++] != world.rank) continue;\n\n            rhs.push_back(v);\n        }\n\n        assert(rhs.size() + 1 == ptr.size());\n    }\n\n    return domain;\n}\n\n//---------------------------------------------------------------------------\nint main(int argc, char *argv[]) {\n    int provided;\n    MPI_Init_thread(&argc, &argv, MPI_THREAD_MULTIPLE, &provided);\n    BOOST_SCOPE_EXIT(void) {\n        MPI_Finalize();\n    } BOOST_SCOPE_EXIT_END\n\n    amgcl::mpi::communicator world(MPI_COMM_WORLD);\n\n    if (world.rank == 0)\n        std::cout << \"World size: \" << world.size << std::endl;\n\n    // Read configuration from command line\n    amgcl::runtime::coarsening::type    coarsening       = amgcl::runtime::coarsening::smoothed_aggregation;\n    amgcl::runtime::relaxation::type    relaxation       = amgcl::runtime::relaxation::spai0;\n    amgcl::runtime::solver::type        iterative_solver = amgcl::runtime::solver::bicgstabl;\n    amgcl::runtime::mpi::direct::type   direct_solver    = amgcl::runtime::mpi::direct::skyline_lu;\n    std::string parameter_file;\n    std::string A_file    = \"A.mtx\";\n    std::string rhs_file  = \"b.mtx\";\n    std::string part_file = \"partition.mtx\";\n    std::string out_file;\n\n    namespace po = boost::program_options;\n    po::options_description desc(\"Options\");\n\n    desc.add_options()\n        (\"help,h\", \"show help\")\n        (\n         \"coarsening,c\",\n         po::value<amgcl::runtime::coarsening::type>(&coarsening)->default_value(coarsening),\n         \"ruge_stuben, aggregation, smoothed_aggregation, smoothed_aggr_emin\"\n        )\n        (\n         \"relaxation,r\",\n         po::value<amgcl::runtime::relaxation::type>(&relaxation)->default_value(relaxation),\n         \"gauss_seidel, ilu0, damped_jacobi, spai0, chebyshev\"\n        )\n        (\n         \"iter_solver,i\",\n         po::value<amgcl::runtime::solver::type>(&iterative_solver)->default_value(iterative_solver),\n         \"cg, bicgstab, bicgstabl, gmres\"\n        )\n        (\n         \"dir_solver,d\",\n         po::value<amgcl::runtime::mpi::direct::type>(&direct_solver)->default_value(direct_solver),\n         \"skyline_lu\"\n#ifdef AMGCL_HAVE_PASTIX\n         \", pastix\"\n#endif\n        )\n        (\n         \"params,p\",\n         po::value<std::string>(&parameter_file),\n         \"parameter file in json format\"\n        )\n        (\n         \"matrix,A\",\n         po::value<std::string>(&A_file)->default_value(A_file),\n         \"The system matrix in MatrixMarket format\"\n        )\n        (\n         \"rhs,b\",\n         po::value<std::string>(&rhs_file)->default_value(rhs_file),\n         \"The right-hand side in MatrixMarket format\"\n        )\n        (\n         \"part,s\",\n         po::value<std::string>(&part_file)->default_value(part_file),\n         \"Partitioning of the problem in MatrixMarket format\"\n        )\n        (\n         \"output,o\",\n         po::value<std::string>(&out_file),\n         \"The output file (saved in MatrixMarket format)\"\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 (world.rank == 0)\n            std::cout << desc << std::endl;\n        return 0;\n    }\n\n    boost::property_tree::ptree prm;\n    if (vm.count(\"params\")) read_json(parameter_file, prm);\n\n    prm.put(\"local.coarsening.type\", coarsening);\n    prm.put(\"local.relax.type\",      relaxation);\n    prm.put(\"isolver.type\",          iterative_solver);\n    prm.put(\"dsolver.type\",          direct_solver);\n\n    using amgcl::prof;\n\n    int block_size = prm.get(\"precond.coarsening.aggr.block_size\", 1);\n\n    prof.tic(\"read problem\");\n    std::vector<ptrdiff_t> ptr;\n    std::vector<ptrdiff_t> col;\n    std::vector<double>    val;\n    std::vector<double>    rhs;\n\n    std::vector<ptrdiff_t> domain = read_problem(\n            world, A_file, rhs_file, part_file, block_size, ptr, col, val, rhs\n            );\n\n    ptrdiff_t chunk = domain[world.rank + 1] - domain[world.rank];\n    prof.toc(\"read problem\");\n\n    prof.tic(\"setup\");\n    typedef\n        amgcl::mpi::subdomain_deflation<\n            amgcl::amg<\n                amgcl::backend::builtin<double>,\n                amgcl::runtime::coarsening::wrapper,\n                amgcl::runtime::relaxation::wrapper\n                >,\n            amgcl::runtime::mpi::solver::wrapper<amgcl::backend::builtin<double>>,\n            amgcl::runtime::mpi::direct::solver<double>\n        > SDD;\n\n    std::function<double(ptrdiff_t,unsigned)> dv = amgcl::mpi::constant_deflation(block_size);\n    prm.put(\"num_def_vec\", block_size);\n    prm.put(\"def_vec\", &dv);\n\n    SDD solve(world, std::tie(chunk, ptr, col, val), prm);\n    double tm_setup = prof.toc(\"setup\");\n\n    std::vector<double> x(chunk, 0);\n\n    prof.tic(\"solve\");\n    size_t iters;\n    double resid;\n    std::tie(iters, resid) = solve(rhs, x);\n    double tm_solve = prof.toc(\"solve\");\n\n    if (vm.count(\"output\")) {\n        prof.tic(\"save\");\n        for(int r = 0; r < world.size; ++r) {\n            if (r == world.rank) {\n                std::ofstream f(out_file.c_str(), r == 0 ? std::ios::trunc : std::ios::app);\n\n                if (r == 0) {\n                    f << \"%%MatrixMarket matrix array real general\\n\"\n                      << domain.back() << \" 1\\n\";\n                }\n\n                std::ostream_iterator<double> oi(f, \"\\n\");\n                std::copy(x.begin(), x.end(), oi);\n            }\n            MPI_Barrier(world);\n        }\n        prof.toc(\"save\");\n    }\n\n    if (world.rank == 0) {\n        std::cout\n            << \"Iterations: \" << iters << std::endl\n            << \"Error:      \" << resid << std::endl\n            << std::endl\n            << prof << std::endl;\n\n#ifdef _OPENMP\n        int nt = omp_get_max_threads();\n#else\n        int nt = 1;\n#endif\n        std::ostringstream log_name;\n        log_name << \"log_\" << domain.back() << \"_\" << nt << \"_\" << world.size << \".txt\";\n        std::ofstream log(log_name.str().c_str(), std::ios::app);\n        log << domain.back() << \"\\t\" << nt << \"\\t\" << world.size\n            << \"\\t\" << tm_setup << \"\\t\" << tm_solve\n            << \"\\t\" << iters << \"\\t\" << std::endl;\n    }\n\n}\n", "meta": {"hexsha": "ca90aa93ea5ad3997aba2a43ba3c7537305f16d6", "size": 11517, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/mpi/solve_mm_mpi.cpp", "max_stars_repo_name": "DABH/amgcl", "max_stars_repo_head_hexsha": "7135d9ae158b23008c0d377e74087e88f637b148", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2020-11-07T08:31:21.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-25T20:35:28.000Z", "max_issues_repo_path": "examples/mpi/solve_mm_mpi.cpp", "max_issues_repo_name": "SoftwareImpacts/SIMPAC-2020-51", "max_issues_repo_head_hexsha": "affc72ec009393134688e17110a8d38661d2a99a", "max_issues_repo_licenses": ["MIT"], "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/solve_mm_mpi.cpp", "max_forks_repo_name": "SoftwareImpacts/SIMPAC-2020-51", "max_forks_repo_head_hexsha": "affc72ec009393134688e17110a8d38661d2a99a", "max_forks_repo_licenses": ["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.6303191489, "max_line_length": 108, "alphanum_fraction": 0.5316488669, "num_tokens": 2866, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6113819732941511, "lm_q2_score": 0.5039061705290805, "lm_q1q2_score": 0.30807914889316823}}
{"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 \"A_ol I_ol\" BA_olI_ol,\n * WITHOUT WARRANTIE_ol OR CONDITION_ol OF ANY KIND, either express or implied.\n * _olee the License for the specific language governing permissions and\n * limitations under the License.\n *\n */\n\n\n#include <boost/math/constants/constants.hpp>\n#include \"votca/xtp/radial_euler_maclaurin_rule.h\"\n#include \"votca/xtp/aobasis.h\"\n#include \"votca/xtp/qmatom.h\"\n#include <votca/xtp/aomatrix.h>\n\n\nnamespace votca { namespace xtp { \n    \n    \n    std::vector<double> EulerMaclaurinGrid::CalculatePruningIntervals(const std::string & element){\n        std::vector<double> r;\n        // get Bragg-Slater Radius for this element\n        double BSradius = _BraggSlaterRadii.at(element);\n        // row type of element\n        int RowType = _pruning_set.at(element);\n        \n        if ( RowType == 1 ){\n            r.push_back( 0.25 * BSradius );\n            r.push_back( 0.5 * BSradius );\n            r.push_back( 1.0 * BSradius );\n            r.push_back( 4.5 * BSradius );\n        } else if ( RowType == 2 ){  \n            r.push_back( 0.1667 * BSradius );\n            r.push_back( 0.5 * BSradius );\n            r.push_back( 0.9 * BSradius );\n            r.push_back( 3.5 * BSradius );             \n        } else if ( RowType == 3 ) {\n            r.push_back( 0.1 * BSradius );\n            r.push_back( 0.4 * BSradius );\n            r.push_back( 0.8 * BSradius );\n            r.push_back( 2.5 * BSradius );\n        } else {\n          throw std::runtime_error(\"EulerMaclaurinGrid::CalculatePruningIntervals:Pruning unsupported for RowType\");\n        }\n        return r;\n     }\n    \n    void EulerMaclaurinGrid::FillElementRangeMap(const AOBasis& aobasis, std::vector<QMAtom*>& atoms, double eps){\n      std::map<std::string, min_exp>::iterator it;\n      for (QMAtom* atom:atoms) {\n        std::string name = atom->getType();\n        // is this element already in map?\n        it = _element_ranges.find(name);\n        // only proceed, if element data does not exist yet\n        if (it == _element_ranges.end()) {\n          min_exp this_atom;\n          double range_max = std::numeric_limits<double>::min();\n          double decaymin = std::numeric_limits<double>::max();\n          int    lvalue = std::numeric_limits<int>::min();\n          const std::vector<const AOShell*>  shells=aobasis.getShellsofAtom(atom->getAtomID());\n          // and loop over all shells to figure out minimum decay constant and angular momentum of this function\n          for (const AOShell* shell:shells) {\n            int lmax = shell->getLmax();\n            if (shell->getMinDecay() < decaymin) {\n              decaymin =shell->getMinDecay();\n              lvalue = lmax;\n            }\n            double range = DetermineCutoff(2 * decaymin, 2 * lvalue + 2, eps);\n            if (range > range_max) {\n              this_atom.alpha = decaymin;\n              this_atom.l = lvalue;\n              this_atom.range = range;\n              range_max = range;\n            }\n          } // shells\n          _element_ranges[name] = this_atom;\n        } // new element\n      } // atoms\n    }\n\n    void EulerMaclaurinGrid::RefineElementRangeMap(const AOBasis& aobasis, std::vector<QMAtom*>& atoms, double eps){\n      AOOverlap overlap;\n      overlap.Fill(aobasis);\n      \n      // get collapsed index list\n      std::vector<int> idxstart;\n      const std::vector<int>& idxsize = aobasis.getFuncPerAtom();\n      int start = 0;\n      for (int size : idxsize) {\n        idxstart.push_back(start);\n        start += size;\n      }\n      // refining by going through all atom combinations\n      for (unsigned i = 0; i < atoms.size(); ++i) {\n        QMAtom* atom_a = atoms[i];\n        int a_start = idxstart[i];\n        int a_size = idxsize[i];\n        double range_max = std::numeric_limits<double>::min();\n        // get preset values for this atom type\n        double alpha_a = _element_ranges.at(atom_a->getType()).alpha;\n        int l_a = _element_ranges.at(atom_a->getType()).l;\n        const tools::vec& pos_a = atom_a->getPos();\n        // Cannot iterate only over j<i because it is not symmetric due to shift_2g\n        for (unsigned j = 0; j < atoms.size(); ++j) {\n          if (i == j) {\n            continue;\n          }\n          QMAtom* atom_b = atoms[j];\n          int b_start = idxstart[j];\n          int b_size = idxsize[j];\n          const tools::vec& pos_b = atom_b->getPos();\n          // find overlap block of these two atoms\n          Eigen::MatrixXd overlapblock = overlap.Matrix().block(a_start, b_start, a_size, b_size);\n          // determine abs max of this block\n          double s_max = overlapblock.cwiseAbs().maxCoeff();\n          \n          if (s_max > 1e-5) {\n            double range = DetermineCutoff(alpha_a + _element_ranges.at(atom_b->getType()).alpha, l_a + _element_ranges.at(atom_b->getType()).l + 2, eps);\n            // now do some update trickery from Gaussian product formula\n            double dist = tools::abs(pos_b - pos_a);\n            double shift_2g = dist * alpha_a / (alpha_a + _element_ranges.at(atom_b->getType()).alpha);\n            range += (shift_2g + dist);\n            if (range > range_max) {\n              range_max = range;\n            }\n          }\n        }\n        if (std::round(range_max) > _element_ranges.at(atom_a->getType()).range) {\n          _element_ranges.at(atom_a->getType()).range = std::round(range_max);\n        }\n      }\n    }\n\n    void EulerMaclaurinGrid::CalculateRadialCutoffs(const AOBasis& aobasis, std::vector<QMAtom* > atoms, const std::string& gridtype) {\n\n      double eps = Accuracy[gridtype];\n      FillElementRangeMap(aobasis, atoms, eps);\n      RefineElementRangeMap(aobasis, atoms, eps);\n      return;\n    } \n    \n    std::map<std::string, GridContainers::radial_grid> EulerMaclaurinGrid::CalculateAtomicRadialGrids(const AOBasis& aobasis , std::vector<QMAtom* > atoms,const std::string& type) {\n     \n    CalculateRadialCutoffs(aobasis,atoms,type);\n    std::map<std::string,GridContainers::radial_grid>result;\n    for (const auto& element:_element_ranges){\n      result[element.first]=CalculateRadialGridforAtom( type,element );\n    }      \n     return result;\n    }\n    \n    GridContainers::radial_grid EulerMaclaurinGrid::CalculateRadialGridforAtom(const std::string& type, const std::pair<std::string, min_exp>& element) {\n      GridContainers::radial_grid result;\n      int np = getGridParameters(element.first, type);\n      double cutoff = element.second.range;\n      result.radius=Eigen::VectorXd::Zero(np);\n      result.weight=Eigen::VectorXd::Zero(np);\n      double alpha = -cutoff / (log(1.0 - std::pow((1.0 + double(np)) / (2.0 + double(np)), 3)));\n      double factor = 3.0 / (1.0 + double(np));\n\n      for (int i = 0; i < np; i++) {\n        double q = double(i + 1) / (double(np) + 1.0);\n        double r = -alpha * std::log(1.0 - std::pow(q, 3));\n        double w = factor * alpha * r * r / (1.0 - std::pow(q, 3)) * std::pow(q, 2);\n        result.radius[i]=r;\n        result.weight[i]=w;\n      }\n      return result;\n    }\n\n    double EulerMaclaurinGrid::DetermineCutoff(double alpha, int l, double eps){      \n      // determine norm of function                                                                                                                                                                                                         \n     /* For a function f(r) = r^k*exp(-alpha*r^2) determine                                                                                                                                                          \n        the radial distance r such that the fraction of the                                                                                                                                                          \n        function norm that is neglected if the 3D volume                                                                                                                                                             \n        integration is terminated at a distance r is less                                                                                                                                                            \n        than or equal to eps. */                                                                                                                                                                                       \n        \n        double cutoff    = 1.0; // initial value\n        double increment = 0.5; // increment\n\n            while (increment > 0.01) {\n                double residual = CalcResidual(alpha,l ,  cutoff);\n                if (residual > eps) {\n                    cutoff += increment;\n                } else {\n                    cutoff -= increment;\n                    if (cutoff < 0.0) cutoff = 0.0;\n                    increment = 0.5 * increment;\n                    cutoff += increment;\n                }\n            }\n        return cutoff;     \n    }\n    \n    double EulerMaclaurinGrid::CalcResidual(double alpha, int l, double cutoff){\n        return RadialIntegral(alpha,l+2,cutoff) / RadialIntegral(alpha,l+2, 0.0); \n    }\n\n    double EulerMaclaurinGrid::RadialIntegral(double alpha, int l, double cutoff){\n        const double pi = boost::math::constants::pi<double>();\n        int ilo = l % 2;\n        double value = 0.0;\n        double valexp;\n        if ( ilo == 0 ){\n            double expo = sqrt(alpha)*cutoff;\n            if ( expo > 40.0 ) {\n                value = 0.0;\n            } else {\n                value = 0.5 * sqrt(  pi /alpha  ) * std::erfc(expo);\n            }\n        }\n        double exponent = alpha*cutoff*cutoff;\n        if ( exponent > 500.0 ) {\n            valexp = 0.0;\n            value = 0.0;\n        } else {\n            valexp = exp(-exponent);\n            value = valexp/2.0/alpha;\n        } \n        for (int i = ilo+2; i <= l; i+=2){\n            value = ((i-1)*value + std::pow(cutoff,i-1)*valexp)/2.0/alpha;\n        }\n        return value;\n    }\n\n    int EulerMaclaurinGrid::getGridParameters(const std::string& element, const std::string& type){\n        if ( type == \"medium\"){           \n            return MediumGrid.at(element);                 \n        }\n        else if ( type == \"coarse\"){  \n            return CoarseGrid.at(element);              \n        }\n        else if ( type == \"xcoarse\"){ \n            return XcoarseGrid.at(element);            \n        }\n        else if ( type == \"fine\"){\n            return FineGrid.at(element);            \n        }\n        else if ( type == \"xfine\"){  \n            return XfineGrid.at(element);            \n        }\n        throw std::runtime_error(\"Grid type \"+type+\" is not implemented\");\n        return -1;\n    }\n    \n}\n}\n", "meta": {"hexsha": "57565984dcc520b3d2825af81dc7e17bf84d3e92", "size": 11228, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/libxtp/numerical_integration/radial_euler_maclaurin_rule.cc", "max_stars_repo_name": "mbarbry/xtp", "max_stars_repo_head_hexsha": "e79828209d11ec25bf1750ab75499ecf50f584ef", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/libxtp/numerical_integration/radial_euler_maclaurin_rule.cc", "max_issues_repo_name": "mbarbry/xtp", "max_issues_repo_head_hexsha": "e79828209d11ec25bf1750ab75499ecf50f584ef", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/libxtp/numerical_integration/radial_euler_maclaurin_rule.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": 43.1846153846, "max_line_length": 236, "alphanum_fraction": 0.5139828999, "num_tokens": 2636, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5926665999540698, "lm_q2_score": 0.519521321952093, "lm_q1q2_score": 0.3079029354849906}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\n\n// Copyright (c) 2016-2018 Oracle and/or its affiliates.\n// Contributed and/or modified by Vissarion Fisikopoulos, on behalf of Oracle\n// Contributed and/or modified by Adam Wulkiewicz, on behalf of Oracle\n\n// Use, modification and distribution is subject to the Boost Software License,\n// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n\n#ifndef BOOST_GEOMETRY_STRATEGIES_SPHERICAL_DISTANCE_CROSS_TRACK_BOX_BOX_HPP\n#define BOOST_GEOMETRY_STRATEGIES_SPHERICAL_DISTANCE_CROSS_TRACK_BOX_BOX_HPP\n\n#include <boost/config.hpp>\n#include <boost/concept_check.hpp>\n#include <boost/mpl/if.hpp>\n#include <boost/type_traits/is_void.hpp>\n\n#include <boost/geometry/core/access.hpp>\n#include <boost/geometry/core/assert.hpp>\n#include <boost/geometry/core/point_type.hpp>\n#include <boost/geometry/core/radian_access.hpp>\n#include <boost/geometry/core/tags.hpp>\n\n#include <boost/geometry/strategies/distance.hpp>\n#include <boost/geometry/strategies/concepts/distance_concept.hpp>\n#include <boost/geometry/strategies/spherical/distance_cross_track.hpp>\n\n#include <boost/geometry/util/math.hpp>\n#include <boost/geometry/algorithms/detail/assign_box_corners.hpp>\n\n\nnamespace boost { namespace geometry\n{\n\nnamespace strategy { namespace distance\n{\n\nnamespace details\n{\n\ntemplate <typename ReturnType>\nclass cross_track_box_box_generic\n{\npublic :\n\n    template\n    <\n            typename Box1,\n            typename Box2,\n            typename Strategy\n    >\n    ReturnType static inline apply (Box1 const& box1,\n                                    Box2 const& box2,\n                                    Strategy ps_strategy)\n    {\n\n        // this method assumes that the coordinates of the point and\n        // the box are normalized\n\n        typedef typename point_type<Box1>::type box_point_type1;\n        typedef typename point_type<Box2>::type box_point_type2;\n\n        box_point_type1 bottom_left1, bottom_right1, top_left1, top_right1;\n        geometry::detail::assign_box_corners(box1,\n                                             bottom_left1, bottom_right1,\n                                             top_left1, top_right1);\n\n        box_point_type2 bottom_left2, bottom_right2, top_left2, top_right2;\n        geometry::detail::assign_box_corners(box2,\n                                             bottom_left2, bottom_right2,\n                                             top_left2, top_right2);\n\n        ReturnType lon_min1 = geometry::get_as_radian<0>(bottom_left1);\n        ReturnType const lat_min1 = geometry::get_as_radian<1>(bottom_left1);\n        ReturnType lon_max1 = geometry::get_as_radian<0>(top_right1);\n        ReturnType const lat_max1 = geometry::get_as_radian<1>(top_right1);\n\n        ReturnType lon_min2 = geometry::get_as_radian<0>(bottom_left2);\n        ReturnType const lat_min2 = geometry::get_as_radian<1>(bottom_left2);\n        ReturnType lon_max2 = geometry::get_as_radian<0>(top_right2);\n        ReturnType const lat_max2 = geometry::get_as_radian<1>(top_right2);\n\n        ReturnType const two_pi = math::two_pi<ReturnType>();\n\n        // Test which sides of the boxes are closer and if boxes cross\n        // antimeridian\n        bool right_wrap;\n\n        if (lon_min2 > 0 && lon_max2 < 0) // box2 crosses antimeridian\n        {\n#ifdef BOOST_GEOMETRY_DEBUG_CROSS_TRACK_BOX_BOX\n            std::cout << \"(box2 crosses antimeridian)\";\n#endif\n            right_wrap = lon_min2 - lon_max1 < lon_min1 - lon_max2;\n            lon_max2 += two_pi;\n            if (lon_min1 > 0 && lon_max1 < 0) // both boxes crosses antimeridian\n            {\n                lon_max1 += two_pi;\n            }\n        }\n        else if (lon_min1 > 0 && lon_max1 < 0) // only box1 crosses antimeridian\n        {\n#ifdef BOOST_GEOMETRY_DEBUG_CROSS_TRACK_BOX_BOX\n            std::cout << \"(box1 crosses antimeridian)\";\n#endif\n            return apply(box2, box1, ps_strategy);\n        }\n        else\n        {\n            right_wrap = lon_max1 <= lon_min2\n                         ? lon_min2 - lon_max1 < two_pi - (lon_max2 - lon_min1)\n                         : lon_min1 - lon_max2 > two_pi - (lon_max1 - lon_min2);\n\n        }\n\n        // Check1: if box2 crosses the band defined by the\n        // minimum and maximum longitude of box1; if yes, determine\n        // if the box2 is above, below or intersects/is inside box1 and compute\n        // the distance (easy in this case)\n\n        bool lon_min12 = lon_min1 <= lon_min2;\n        bool right = lon_max1 <= lon_min2;\n        bool left = lon_min1 >= lon_max2;\n        bool lon_max12 = lon_max1 <= lon_max2;\n\n        if ((lon_min12 && !right)\n                || (!left && !lon_max12)\n                || (!lon_min12 && lon_max12))\n        {\n#ifdef BOOST_GEOMETRY_DEBUG_CROSS_TRACK_BOX_BOX\n            std::cout << \"(up-down)\\n\";\n#endif\n            if (lat_min1 > lat_max2)\n            {\n                return geometry::strategy::distance::services::result_from_distance\n                    <\n                        Strategy, box_point_type1, box_point_type2\n                    >::apply(ps_strategy, ps_strategy.get_distance_strategy()\n                               .meridian(lat_min1, lat_max2));\n            }\n            else if (lat_max1 < lat_min2)\n            {\n                return geometry::strategy::distance::services::result_from_distance\n                    <\n                        Strategy, box_point_type1, box_point_type2\n                    >::apply(ps_strategy, ps_strategy.get_distance_strategy().\n                             meridian(lat_min2, lat_max1));\n            }\n            else\n            {\n                //BOOST_GEOMETRY_ASSERT(plat >= lat_min && plat <= lat_max);\n                return ReturnType(0);\n            }\n        }\n\n        // Check2: if box2 is right/left of box1\n        // the max lat of box2 should be less than the max lat of box1\n        bool bottom_max;\n\n        ReturnType top_common = (std::min)(lat_max1, lat_max2);\n        ReturnType bottom_common = (std::max)(lat_min1, lat_min2);\n\n        // true if the closest points are on northern hemisphere\n        bool north_shortest = math::abs(top_common) > math::abs(bottom_common)\n                || lat_max1 <= lat_min2\n                || lat_min1 >= lat_max2;\n\n        if (north_shortest)\n        {\n            bottom_max = lat_max1 >= lat_max2;\n        }\n        else\n        {\n            bottom_max = lat_min1 <= lat_min2;\n        }\n\n#ifdef BOOST_GEOMETRY_DEBUG_CROSS_TRACK_BOX_BOX\n        std::cout << \"(diagonal)\";\n#endif\n        if (bottom_max && !right_wrap)\n        {\n#ifdef BOOST_GEOMETRY_DEBUG_CROSS_TRACK_BOX_BOX\n            std::cout << \"(bottom left)\";\n#endif\n            if (north_shortest)\n            {\n                return ps_strategy.apply(top_right2, top_left1, bottom_left1);\n            }\n            return ps_strategy.apply(bottom_right2, top_left1, bottom_left1);\n        }\n        if (bottom_max && right_wrap)\n        {\n#ifdef BOOST_GEOMETRY_DEBUG_CROSS_TRACK_BOX_BOX\n            std::cout << \"(bottom right)\";\n#endif\n            if (north_shortest)\n            {\n                return ps_strategy.apply(top_left2, top_right1, bottom_right1);\n            }\n            return ps_strategy.apply(bottom_left2, top_right1, bottom_right1);\n        }\n        if (!bottom_max && !right_wrap)\n        {\n#ifdef BOOST_GEOMETRY_DEBUG_CROSS_TRACK_BOX_BOX\n            std::cout << \"(top left)\";\n#endif\n            if (north_shortest)\n            {\n                return ps_strategy.apply(top_left1, top_right2, bottom_right2);\n            }\n            return ps_strategy.apply(bottom_left1, top_right2, bottom_right2);\n        }\n        if (!bottom_max && right_wrap)\n        {\n#ifdef BOOST_GEOMETRY_DEBUG_CROSS_TRACK_BOX_BOX\n            std::cout << \"(top right)\";\n#endif\n            if (north_shortest)\n            {\n                return ps_strategy.apply(top_right1, top_left2, bottom_left2);\n            }\n            return ps_strategy.apply(bottom_right1, top_left2, bottom_left2);\n        }\n        return ReturnType(0);\n    }\n};\n\n} //namespace details\n\n/*!\n\\brief Strategy functor for distance box to box calculation\n\\ingroup strategies\n\\details Class which calculates the distance of a box to a box, for\nboxes on a sphere or globe\n\\tparam CalculationType \\tparam_calculation\n\\tparam Strategy underlying point-segment distance strategy, defaults\nto cross track\n\\qbk{\n[heading See also]\n[link geometry.reference.algorithms.distance.distance_3_with_strategy distance (with strategy)]\n}\n*/\ntemplate\n<\n    typename CalculationType = void,\n    typename Strategy = cross_track<CalculationType>\n>\nclass cross_track_box_box\n{\npublic:\n    template <typename Box1, typename Box2>\n    struct return_type\n        : services::return_type<Strategy,\n                                typename point_type<Box1>::type,\n                                typename point_type<Box2>::type>\n    {};\n\n    typedef typename Strategy::radius_type radius_type;\n\n    inline cross_track_box_box()\n    {}\n\n    explicit inline cross_track_box_box(typename Strategy::radius_type const& r)\n        : m_ps_strategy(r)\n    {}\n\n    inline cross_track_box_box(Strategy const& s)\n        : m_ps_strategy(s)\n    {}\n\n\n    // It might be useful in the future\n    // to overload constructor with strategy info.\n    // crosstrack(...) {}\n\n    template <typename Box1, typename Box2>\n    inline typename return_type<Box1, Box2>::type\n    apply(Box1 const& box1, Box2 const& box2) const\n    {\n#if !defined(BOOST_MSVC)\n        BOOST_CONCEPT_ASSERT\n            (\n                (concepts::PointSegmentDistanceStrategy\n                    <\n                        Strategy,\n                        typename point_type<Box1>::type,\n                        typename point_type<Box2>::type\n                    >)\n            );\n#endif\n        typedef typename return_type<Box1, Box2>::type return_type;\n        return details::cross_track_box_box_generic\n                                <return_type>::apply(box1, box2, m_ps_strategy);\n    }\n\n    inline typename Strategy::radius_type radius() const\n    {\n        return m_ps_strategy.radius();\n    }\n\nprivate:\n    Strategy m_ps_strategy;\n};\n\n\n\n#ifndef DOXYGEN_NO_STRATEGY_SPECIALIZATIONS\nnamespace services\n{\n\ntemplate <typename CalculationType, typename Strategy>\nstruct tag<cross_track_box_box<CalculationType, Strategy> >\n{\n    typedef strategy_tag_distance_box_box type;\n};\n\n\ntemplate <typename CalculationType, typename Strategy, typename Box1, typename Box2>\nstruct return_type<cross_track_box_box<CalculationType, Strategy>, Box1, Box2>\n    : cross_track_box_box\n        <\n            CalculationType, Strategy\n        >::template return_type<Box1, Box2>\n{};\n\n\ntemplate <typename CalculationType, typename Strategy>\nstruct comparable_type<cross_track_box_box<CalculationType, Strategy> >\n{\n    typedef cross_track_box_box\n        <\n            CalculationType, typename comparable_type<Strategy>::type\n        > type;\n};\n\n\ntemplate <typename CalculationType, typename Strategy>\nstruct get_comparable<cross_track_box_box<CalculationType, Strategy> >\n{\n    typedef cross_track_box_box<CalculationType, Strategy> this_strategy;\n    typedef typename comparable_type<this_strategy>::type comparable_type;\n\npublic:\n    static inline comparable_type apply(this_strategy const& strategy)\n    {\n        return comparable_type(strategy.radius());\n    }\n};\n\n\ntemplate <typename CalculationType, typename Strategy, typename Box1, typename Box2>\nstruct result_from_distance\n    <\n        cross_track_box_box<CalculationType, Strategy>, Box1, Box2\n    >\n{\nprivate:\n    typedef cross_track_box_box<CalculationType, Strategy> this_strategy;\n\n    typedef typename this_strategy::template return_type\n        <\n            Box1, Box2\n        >::type return_type;\n\npublic:\n    template <typename T>\n    static inline return_type apply(this_strategy const& strategy,\n                                    T const& distance)\n    {\n        Strategy s(strategy.radius());\n\n        return result_from_distance\n            <\n                Strategy,\n                typename point_type<Box1>::type,\n                typename point_type<Box2>::type\n            >::apply(s, distance);\n    }\n};\n\n\n// define cross_track_box_box<default_point_segment_strategy> as\n// default box-box strategy for the spherical equatorial coordinate system\ntemplate <typename Box1, typename Box2, typename Strategy>\nstruct default_strategy\n    <\n        box_tag, box_tag, Box1, Box2,\n        spherical_equatorial_tag, spherical_equatorial_tag,\n        Strategy\n    >\n{\n    typedef cross_track_box_box\n        <\n            void,\n            typename boost::mpl::if_\n                <\n                    boost::is_void<Strategy>,\n                    typename default_strategy\n                        <\n                            point_tag, segment_tag,\n                            typename point_type<Box1>::type, typename point_type<Box2>::type,\n                            spherical_equatorial_tag, spherical_equatorial_tag\n                        >::type,\n                    Strategy\n                >::type\n        > type;\n};\n\n} // namespace services\n#endif // DOXYGEN_NO_STRATEGY_SPECIALIZATIONS\n\n\n}} // namespace strategy::distance\n\n\n}} // namespace boost::geometry\n\n#endif // BOOST_GEOMETRY_STRATEGIES_SPHERICAL_DISTANCE_CROSS_TRACK_BOX_BOX_HPP\n", "meta": {"hexsha": "4a315c653de27ac986f4f91a95cb09bdda779c49", "size": 13398, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/geometry/strategies/spherical/distance_cross_track_box_box.hpp", "max_stars_repo_name": "taken20090/ext-boost", "max_stars_repo_head_hexsha": "0518d698a8a0fd86a88e5e1d0f67f30e9bbc4181", "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/geometry/strategies/spherical/distance_cross_track_box_box.hpp", "max_issues_repo_name": "taken20090/ext-boost", "max_issues_repo_head_hexsha": "0518d698a8a0fd86a88e5e1d0f67f30e9bbc4181", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "boost/geometry/strategies/spherical/distance_cross_track_box_box.hpp", "max_forks_repo_name": "taken20090/ext-boost", "max_forks_repo_head_hexsha": "0518d698a8a0fd86a88e5e1d0f67f30e9bbc4181", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.9, "max_line_length": 95, "alphanum_fraction": 0.6241976414, "num_tokens": 2896, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6513548782017745, "lm_q2_score": 0.4726834766204329, "lm_q1q2_score": 0.3078846883420934}}
{"text": "/**\n\n\\file\n\\author Datta Ramadasan\n//==============================================================================\n//         Copyright 2015 INSTITUT PASCAL UMR 6602 CNRS/Univ. Clermont II\n//\n//          Distributed under the Boost Software License, Version 1.0.\n//                 See accompanying file LICENSE.txt or copy at\n//                     http://www.boost.org/LICENSE_1_0.txt\n//==============================================================================\n\n*/\n\n#ifndef __OPTIMISATION2_BA_PCG_HPP__\n#define __OPTIMISATION2_BA_PCG_HPP__\n\n#include <libv/lma/time/tictoc.hpp>\n#include <libv/lma/ttt/traits/wrap.hpp>\n#include <libv/lma/ttt/traits/naming.hpp>\n#include <libv/lma/lm/omp/omp.hpp>\n#include <boost/fusion/include/as_map.hpp>\n#include <boost/fusion/include/fold.hpp>\n#include <boost/fusion/include/for_each.hpp>\n#include <boost/mpl/for_each.hpp>\n#include <boost/mpl/transform.hpp>\n\n#include <iomanip>\n#include <exception>\n\n#include \"make_type.hpp\"\n#include \"utils.hpp\"\n\nnamespace lma\n{\n  template<class T> bool is_zero_or_infinite(T x) { return ((x == 0.0) || (std::isinf(x))); }\n\n\n\n  template<class S> struct AssignSameDiagInv\n  {\n    const S& s;\n    AssignSameDiagInv(const S& s_):s(s_){}\n    template<class Key, class Cont, template<class,class> class Pair> void operator()(Pair<Pair<Key,Key>,Cont>& obj) const\n    {\n      obj.second.set_diag_inv(boost::fusion::at_key<Pair<Key,Key>>(s));\n    }\n\n    template<class T> void operator()(T&) const {}\n  };\n\n  template<class D, class S> void assign_same_diag_inv(D& d, const S& s)\n  {\n    boost::fusion::for_each(d,AssignSameDiagInv<S>(s));\n  }\n\n  struct Minus\n  {\n    template<class Key, class Cont, template<class,class> class Pair> void operator()(Pair<Key,Cont>& obj) const\n    { this->operator()(obj.second); }\n\n    template<class T> void operator()(T& obj) const { obj.minus(); }\n  };\n\n  template<class A> struct Dot\n  {\n    typedef double result_type;\n    const A& a;\n\n    Dot(const A& a_):a(a_){}\n\n    template<class Key,class Cont, template<class,class> class Pair> result_type operator()(const result_type& prev, const Pair<Key,Cont>& pair) const\n    { return this->operator()<Cont>(prev,pair.second,boost::fusion::at_key<Key>(a)); }\n\n    template<class Cont1, class Cont2> result_type operator()(const result_type& result, const Cont1& cont, const Cont2& b) const\n    {\n      return result + cont.compute_dot(b);\n    }\n  };\n\n  template<class A> Dot<A> make_dot(const A& a) { return Dot<A>(a); }\n\n  template<class P, class A, class B> struct ProdDiag21\n  {\n    P& p;\n    const A& a;\n    const B& b;\n    ProdDiag21(P& p_, const A& a_, const B& b_):p(p_),a(a_),b(b_){}\n\n    template<class Key> void operator()(ttt::wrap<Key>)\n    {\n\n      auto& residu = bf::at_key<Key>(p);\n      const auto& refa = bf::at_key<bf::pair<Key,Key>>(a);\n//       clement(a);\n//       std::cout << ttt::name<Key>() << std::endl;\n//       std::cout << ttt::name<A>() << std::endl;\n      const auto& refb = bf::at_key<Key>(b);\n      residu.resize(refb.size());\n//       #pragma omp parallel for if(use_omp())\n      for(auto i = residu.first() ; i < residu.size() ; ++i)\n        residu(i) = refa(i,0) * refb(i);\n//       prod_trig_sup(residu,refa,refb);\n    }\n  };\n\n  template<class Scalar, class V> struct DecScalarProdV\n  {\n    const Scalar scalar;\n    const V& v;\n\n    DecScalarProdV(const Scalar& scalar_, const V& v_):scalar(scalar_),v(v_){}\n\n    template<class Key, class Cont, template<class,class> class Pair> void operator()(Pair<Key,Cont>& pair) const\n    {\n      auto& result = pair.second;\n      const auto& ref = boost::fusion::at_key<Key>(v);\n      result.resize(ref.size());\n//       #pragma omp parallel for if(use_omp())\n      for(auto i = result.first() ; i < result.size() ; ++i)\n        result(i) -= scalar * ref(i);\n    }\n  };\n  \n  template<class Scalar, class V> struct IncScalarProdV\n  {\n    const Scalar scalar;\n    const V& v;\n\n    IncScalarProdV(const Scalar& scalar_, const V& v_):scalar(scalar_),v(v_){}\n\n    template<class Key, class Cont, template<class,class> class Pair> void operator()(Pair<Key,Cont>& pair) const\n    {\n      auto& result = pair.second;\n      const auto& ref = boost::fusion::at_key<Key>(v);\n      result.resize(ref.size());\n//       #pragma omp parallel for if(use_omp())\n      for(auto i = result.first() ; i < result.size() ; ++i)\n        result(i) += scalar * ref(i);\n    }\n  };\n\n  //     p = -y + beta * p;\n  template<class A, class B, class C> struct MinusPlusScalarProdV\n  {\n    const A& a;\n    const B b;\n    const C& c;\n    MinusPlusScalarProdV(const A& a_, const B& b_, const C& c_):a(a_),b(b_),c(c_){}\n\n    template<class Key, class Cont, template<class,class> class Pair> void operator()(Pair<Key,Cont>& pair) const\n    {\n      auto& result = pair.second;\n      const auto& ref1 = boost::fusion::at_key<Key>(a);\n      const auto& ref2 = boost::fusion::at_key<Key>(c);\n\n//       #pragma omp parallel for if(use_omp())\n      for(auto i = result.first() ; i < result.size() ; ++i)\n        result(i) =  - ref1(i) + b * ref2(i);\n    }\n  };\n\n  template<class A, class B, class C> struct PlusScalarProdV\n  {\n    const A& a;\n    const B b;\n    const C& c;\n    PlusScalarProdV(const A& a_, const B& b_, const C& c_):a(a_),b(b_),c(c_){}\n\n    template<class Key, class Cont, template<class,class> class Pair> void operator()(Pair<Key,Cont>& pair) const\n    {\n      auto& result = pair.second;\n      const auto& ref1 = boost::fusion::at_key<Key>(a);\n      const auto& ref2 = boost::fusion::at_key<Key>(c);\n\n//       #pragma omp parallel for if(use_omp())\n      for(auto i = result.first() ; i < result.size() ; ++i)\n        result(i) =  ref1(i) + b * ref2(i);\n    }\n  };\n  \n  template<class A, class B> struct AssignSame2\n  {\n    A& a;\n    const B& b;\n    AssignSame2(A& a_, const B& b_):a(a_),b(b_){}\n\n    template<class Key> void operator()(ttt::wrap<Key>)\n    {\n      auto& refa = boost::fusion::at_key<Key>(a);\n      const auto& refb = boost::fusion::at_key<Key>(b);\n\n      if (refa.size() != refb.size())\n      {\n        std::cout << \" DIFF ! \" << ttt::name<Key>() << std::endl;\n        std::cout << refa.name() << std::endl;\n        std::cout << refb.name() << std::endl;\n        std::cout << refa.size() << \" , \" << refb.size() << std::endl;\n        getchar();\n      }\n      refa = refb;\n      \n      assert(!refa.is_invalid());\n      \n    }\n  };\n\n  template<class B, class Z> struct BMINUSZ\n  {\n    const B& b;\n    const Z& z;\n    BMINUSZ(const B& b_, const Z& z_):b(b_),z(z_){}\n\n    template<class Key, class Cont, template<class,class> class Pair> void operator()(Pair<Key,Cont>& pair) const\n    {\n      auto& result = pair.second;\n      const auto& ref1 = boost::fusion::at_key<Key>(b);\n      const auto& ref2 = boost::fusion::at_key<Key>(z);\n\n//       #pragma omp parallel for if(use_omp())\n      for(auto i = result.first() ; i < result.size() ; ++i)\n        result(i) =  ref1(i) - ref2(i);\n    }\n  };\n\n  template<class Scalar, class V> IncScalarProdV<Scalar,V> incscalarprodv(const Scalar& a, const V& v) { return IncScalarProdV<Scalar,V>(a,v); }\n  \n  template<class Scalar, class V> DecScalarProdV<Scalar,V> decscalarprodv(const Scalar& a, const V& v) { return DecScalarProdV<Scalar,V>(a,v); }\n  \n  template<class A, class B, class C> MinusPlusScalarProdV<A,B,C> minus_plus_scalar_prod_v(const A& a, const B& b, const C& c){ return MinusPlusScalarProdV<A,B,C>(a,b,c); }\n  \n  template<class A, class B, class C> PlusScalarProdV<A,B,C> plus_scalar_prod_v(const A& a, const B& b, const C& c){ return PlusScalarProdV<A,B,C>(a,b,c); }\n  \n  template<class A, class B> AssignSame2<A,B> assign_same2(A& a, const B& b){ return AssignSame2<A,B>(a,b); }\n\n  template<class B, class Z> BMINUSZ<B,Z> b_minus_z(const B& b, const Z& z) { return BMINUSZ<B,Z>(b,z); }\n  struct SquaredNorm\n  {\n    typedef double result_type;\n    template<class Key, class Cont, template<class,class> class Pair> result_type operator()(const result_type& prev, const Pair<Key,Cont>& obj) const\n    {\n//       std::cout << \" Norm : \" << prev << \" \" << obj.second.squaredNorm() << std::endl;\n      return prev + obj.second.squaredNorm();\n    }\n  };\n\n  template<class Tuple> double norm(const Tuple& t)\n  {\n    return std::sqrt(bf::fold(t,0.0,SquaredNorm()));\n  }\n\n  template<class Tuple> double dot(const Tuple& t)\n  {\n    return bf::fold(t,0.0,make_dot(t));\n  }\n\n\n\n  struct PcgConfig\n  {\n    double seuil;\n    size_t max_iteration;\n    size_t frequence;\n    PcgConfig(double s = 0.9999, size_t m = 100, size_t f = -1):seuil(s),max_iteration(m),frequence(f){}\n  };\n  \n  struct PCG : PcgConfig\n  {\n    PCG(PcgConfig config):PcgConfig(config) {}\n    \n    template<class Tag, class Container, class Delta>\n    void operator()(const Container& cont, Delta& delta, const Tag&)\n    {\n      //Pour la notation et la méthode cf Méthode numérique appliquées, A. Gourdin, M. Boumahrat : page 258,259\n      static const bool disp = false;\n\n      typedef typename Tag::second_type Float;\n      typedef typename Container::OptimizeKeys ListeParametre;\n      typedef typename mpl::transform< \n\t\t\t\t      ListeParametre, \n\t\t\t\t      MakeTupleTable<mpl::_1,mpl::_1,Tag>\n\t\t\t\t     >::type ListeDiag;\n      typedef typename mpl::transform<ListeParametre, VectorToPairStruct<mpl::_1,Tag> >::type ListeVector;\n      typedef typename br::as_map<ListeVector>::type TupleResidu;\n      typedef typename br::as_map<ListeDiag>::type TupleDiag;\n\n      TupleDiag C;\n      TupleResidu r,S,p,x;\n\n      Float r0y0 = 0,r1y1 = 0;\n      Float residualNorm2=std::numeric_limits<Float>::max(),residualNorm2Initial = 0;\n\n      //r0 = b\n      r = cont.B();// - mat * x;\n  \n      residualNorm2Initial = norm(r);//bf::fold(residual,0.0,dot(residual));\n//       std::cout << \" Initial norm : \" << residualNorm2Initial << std::endl;\n      \n      if (residualNorm2Initial==0) return;\n\n//       cont.get_preconditionner(C);\n      \n      assign_same_diag_inv(C,cont.A());// return le preconditionner inversé\n\n      \n      //p = C * r\n//       bf::for_each(p,prod_diag_21(C,r));\n      mpl::for_each<ListeParametre,ttt::wrap<mpl::_1>>(ProdDiag21<TupleResidu,TupleDiag,TupleResidu>(p,C,r));\n\n      // S = p\n      S = p;\n\n      size_t max_element = nb_element(r);\n      max_iteration = std::min(max_iteration,max_element);\n\n      //if (cpt > max_element) std::cerr << __FILE__ << \" : \" << __LINE__ <<  \" cpt > max_element : \" << cpt << \" > \" << max_element << std::endl;\n\n//       std::cout << \" S \\n \" << to_vect(S).transpose() << std::endl;\n      // r0y0 = r * S\n      r0y0 = bf::fold(r,0.0,make_dot(S));\n//       std::cout << \" r0y0 \" << r0y0 << std::endl;\n      \n      \n//       std::cout << \" Diff r0y0\" << std::abs(to_vect(r).dot(to_vect(S)) - r0y0) <<  std::endl;\n//       r0y0 = to_vect(r).dot(to_vect(S));\n//       assert(  to_vect(r).dot(to_vect(S)) == r0y0 );\n      if (r0y0==0) {std::cerr << \" r0y0 = \" << r0y0 << std::endl;return;}\n        \n      std::size_t it = 0;\n// /*\n      for( ; it < max_iteration ; ++it)\n      {\n        TupleResidu Ap;\n        // AP = s * p\n        // on fait le calcul ailleurs pour gérer les deux cas : S implicite ou explicite\n        cont.prodAP(Ap,p);\n// \tmpl::for_each<typename Container::TypesA,ttt::wrap<mpl::_1>>(prod_ap_p(Ap,cont.A(),p));\n\n        // denom = p * Ap\n        Float denom = bf::fold(p,0.0,make_dot(Ap));\n\n//         std::cout << \" Diff denom \" << std::abs(to_vect(p).dot(to_vect(Ap)) - denom) <<  std::endl;\n//         denom = to_vect(p).dot(to_vect(Ap));\n        \n        if (std::isinf(denom)) throw INF_ERROR(\"PCG denom\");\n  \n        if (std::isnan(denom)) { std::cerr << color.bold() << color.red() <<  \" PCG : p.dot(Ap) == NAN \" << color.reset() << std::endl; throw NAN_ERROR(\"PCG: isnan(p*Ap)\"); }\n        if (denom==0) { std::cerr << color.bold() << color.red() <<  \" PCG : p.dot(Ap) == 0 \" << color.reset() << std::endl; throw NAN_ERROR(\"PCG: p*Ap==0\"); }\n\n//         std::cout << \" numerateur   \" << r0y0 << std::endl;\n//         std::cout << \" denominateur \" << denom << std::endl;\n    \n        const Float alpha = r0y0 / denom;\n  \n        if (std::isinf(denom)) throw INF_ERROR(\"PCG alpha\");\n        \n\n\n        if (it !=0 && it%frequence==0)\n        {\n//         si r dérive, on peut utiliser (mais c'est plus lent!) :\n//         r = b - Ax\n          TupleResidu Ax;\n          cont.prodAP(Ax,x);\n          bf::for_each(r,b_minus_z(cont.B(),Ax));\n        }\n        else\n        {\n        // r -= alpha * Ap\n          bf::for_each(r,decscalarprodv(alpha,Ap));\n        }\n\n        residualNorm2 = norm(r);\n//         std::cout << alpha << \" \";\n        // x += alpha * p\n//         std::cout << to_vect(x) << std::endl << std::endl;\n//         std::cout << to_vect(p) << std::endl;\n//         auto x2 = (to_vect(x)  + alpha * to_vect(p)).eval();\n        bf::for_each(x,incscalarprodv(alpha,p));\n        \n//         std::cout << (to_vect(x) - x2).transpose() << std::endl;\n//         std::cout << \" residu : \" << residualNorm2 << std::endl;\n        \n        \n        if (std::abs(residualNorm2-residualNorm2Initial)/residualNorm2Initial > seuil && residualNorm2<residualNorm2Initial)\n        {\n//           std::cout << \" break condition \" << std::endl;\n          break;\n        }\n        \n        // S = invM * r\n// //         bf::for_each(S,prod_diag_21(C,r));\n\t  mpl::for_each<ListeParametre,ttt::wrap<mpl::_1>>(ProdDiag21<TupleResidu,TupleDiag,TupleResidu>(S,C,r));\n\n        // r1y1 = r.dot(S);\n        r1y1 = bf::fold(r,0.0,make_dot(S));\n        \n//         std::cout << \" Diff r1y1 \" << std::abs(to_vect(r).dot(to_vect(S)) - r1y1) <<  std::endl;\n//         r1y1 = to_vect(r).dot(to_vect(S));\n        //if (r1y1>r0y0) break;\n        if(is_zero_or_infinite(r1y1)) {std::cout << \" r1y1 is shitted ...\" << std::endl;break;}//throw ZeroOrInfiniteError(\"PCG r1y1\");\n  \n//         if(disp) std::cout << color.magenta() << \" r1y1 = \" << r1y1 << color.reset() << std::endl;\n        \n        const Float beta = r1y1 / r0y0;\n        \n        if(disp) std::cout << color.magenta() << \" beta = \" << beta << color.reset() << std::endl;\n\n        if (is_zero_or_infinite(beta)) ZeroOrInfiniteError(\"PCG beta\");\n        // p = S + beta * p;\n        bf::for_each(p,plus_scalar_prod_v(S,beta,p));\n\n        r0y0 = r1y1;\n\n//         std::cout << \" critère : \" << residualNorm2 << \" / \" << residualNorm2Initial << \" = \" << residualNorm2 / residualNorm2Initial << std::endl;\n//         if (residualNorm2 / residualNorm2Initial < 0.1) break;\n//         std::cout << \" residual[\" << it << \"]: \" << r1y1 << std::endl;\n      }\n\n//      std::cout << \" nb iteration = \" << it << \" / \" << max_iteration << std::endl;\n//       std::cout <<  \"final residual : \" << residualNorm2 << std::endl;\n//     std::cout << \" FINAL [\" << it << \"]: \" << r1y1 << std::endl;\n      mpl::for_each<ListeParametre,ttt::wrap<mpl::_1>>(assign_same2(delta,x));\n//       std::cout << \" my pcg     :  \" << to_matv(x).transpose() << std::endl;\n\n    }\n  };\n}// eon\n\nnamespace ttt\n{\n  template<> struct Name<lma::PCG> { static std::string name(){ return \"SSparsePCG\"; } };\n}\n\n/*\nvoid solve(const MatD& S, VecD& delta, const VecD& E, const std::size_t& nb_camera)\n{\n  const std::size_t size = nb_camera * C;\n\n  double seuil = 1e-16;   //à choisir entre 1e-8 et 1e-16 (influe sur le nombre d'itérations du PCG et sa précision)\n\n  double residual, residual_first;\n\n  VecD r = -E;\n  VecD x = VecD::Zero(size);\n  residual_first = r.dot(r);\n\n  VectorCC invMv(nb_camera);\n  for(std::size_t i = 0 ; i < nb_camera ; ++i)\n    invMv[i] = S.inverse();\n\n  VecD y = VecD::Zero(size);\n\n  for(std::size_t i = 0 ; i < nb_camera ; ++i)\n    BlockC1::view(y,i*C,0) = invMv[i] * BlockC1::view(r,i*C,0);\n\n  VecD p = - y;\n  double r0y0 = r.dot(y), r1y1;\n\n  for(std::size_t it = 0 ; it < size ; ++it)\n  {\n    VecD Ap = S * p;\n\n    double temp = p.dot(Ap) ;\n\n    if (std::isnan(temp)) { V_TXT(\" PCG : p.dot(Ap) == NAN \"); break; }\n\n    const double alpha = r0y0 / temp;\n\n    x += alpha * p;\n    r += alpha * Ap;\n    residual = r.dot(r);\n\n    if ( residual < seuil * residual_first ) {break;}\n\n    for(std::size_t i = 0 ; i < nb_camera ; ++i)\n      BlockC1::view(y,i*C,0) = invMv[i] * BlockC1::view(r,i*C,0);\n\n    r1y1 = r.dot(y);\n\n    const double beta = r1y1 / r0y0;\n    p = -y + beta * p;\n\n    r0y0 = r1y1;\n  }\n  delta = x;\n}\n*/\n\n\n#endif\n", "meta": {"hexsha": "262c4a72e27787faea80a4ea8772c867b132d84d", "size": 16256, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/libv/lma/lm/ba/pcg.hpp", "max_stars_repo_name": "bezout/LMA", "max_stars_repo_head_hexsha": "9555e41eed5f44690c5f6e3ea2d22d520ff1a9d2", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 29.0, "max_stars_repo_stars_event_min_datetime": "2015-12-08T12:07:30.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-08T21:23:01.000Z", "max_issues_repo_path": "src/libv/lma/lm/ba/pcg.hpp", "max_issues_repo_name": "ayumizll/LMA", "max_issues_repo_head_hexsha": "e945452e12a8b05bd17400b46a20a5322aeda01d", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2016-07-11T16:23:48.000Z", "max_issues_repo_issues_event_max_datetime": "2017-04-05T13:33:00.000Z", "max_forks_repo_path": "src/libv/lma/lm/ba/pcg.hpp", "max_forks_repo_name": "bezout/LMA", "max_forks_repo_head_hexsha": "9555e41eed5f44690c5f6e3ea2d22d520ff1a9d2", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2015-12-21T01:52:27.000Z", "max_forks_repo_forks_event_max_datetime": "2017-12-26T02:26:55.000Z", "avg_line_length": 33.0406504065, "max_line_length": 174, "alphanum_fraction": 0.5754798228, "num_tokens": 4961, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6513548646660543, "lm_q2_score": 0.47268347662043286, "lm_q1q2_score": 0.3078846819439821}}
{"text": "// This file is part of snark, a generic and flexible library for robotics research\n// Copyright (c) 2011 The University of Sydney\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are met:\n// 1. Redistributions of source code must retain the above copyright\n//    notice, this list of conditions and the following disclaimer.\n// 2. Redistributions in binary form must reproduce the above copyright\n//    notice, this list of conditions and the following disclaimer in the\n//    documentation and/or other materials provided with the distribution.\n// 3. Neither the name of the University of Sydney nor the\n//    names of its contributors may be used to endorse or promote products\n//    derived from this software without specific prior written permission.\n//\n// NO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE\n// GRANTED BY THIS LICENSE.  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT\n// HOLDERS AND CONTRIBUTORS \\\"AS IS\\\" AND ANY EXPRESS OR IMPLIED\n// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\n// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\n// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR\n// BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE\n// OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN\n// IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n#include <cmath>\n#include <Eigen/Geometry>\n#include <comma/math/compare.h>\n#include \"range_bearing_elevation.h\"\n\nnamespace snark {\n\nEigen::Vector2d bearing::to_cartesian( const double radians, const double radius )\n{\n    return Eigen::Vector2d( radius * std::sin( radians ), radius * std::cos( radians ) );\n}\n\ndouble bearing::from_cartesian( const double x, const double y )\n{\n    double radians = ( M_PI / 2 ) - std::atan2( y, x );\n    return radians < 0 ? radians + 2 * M_PI : radians;\n}\n\nbearing_elevation::bearing_elevation() : bearing_( 0 ), elevation_( 0 ) {}\n\nbearing_elevation::bearing_elevation( double b, double e ) : bearing_( bearing( b ) ), elevation_( elevation( e ) ) {}\n\ndouble bearing_elevation::bearing() const { return bearing_; }\n\ndouble bearing_elevation::elevation() const { return elevation_; }\n\ndouble bearing_elevation::b() const { return bearing(); }\n\ndouble bearing_elevation::e() const { return elevation(); }\n\ndouble bearing_elevation::b( double b ) { return bearing( b ); }\n\ndouble bearing_elevation::e( double e ) { return elevation( e ); }\n\nstatic double mod_( double t, double m ) // quick and dirty, because std::fmod is ridiculously slow\n{\n    int r = std::abs( t / m );\n    return comma::math::less( t, 0 ) ? ( t + m * r ) : ( t - m * r );\n}\n\ndouble bearing_elevation::bearing( double t )\n{\n    double b( mod_( t, ( double )( M_PI * 2 ) ) ); //double b( std::fmod( t, ( double )( M_PI * 2 ) ) );\n    if( !comma::math::less( b, M_PI ) ) { b -= ( M_PI * 2 ); }\n    else if( comma::math::less( b, -M_PI ) ) { b += ( M_PI * 2 ); }\n    bearing_ = b;\n    return bearing_;\n}\n\ndouble bearing_elevation::elevation( double t )\n{\n    double e( mod_( t, ( double )( M_PI * 2 ) ) ); //double e( std::fmod( t, ( double )( M_PI * 2 ) ) );\n    if( comma::math::less( e, 0 ) ) { e += M_PI * 2; }\n    if( !comma::math::less( e, M_PI / 2 ) )\n    {\n        if( !comma::math::less( e, M_PI ) )\n        {\n            if( !comma::math::less( e, M_PI * 3 / 2 ) )\n            {\n                e = e - M_PI * 2;\n            }\n            else\n            {\n                e = M_PI - e;\n                bearing( bearing() + M_PI );\n            }\n        }\n        else\n        {\n            e = M_PI - e;\n            bearing( bearing() + M_PI );\n        }\n    }\n    elevation_ = e;\n    return elevation_;\n}\n\nrange_bearing_elevation::range_bearing_elevation() { range( 0 ); }\n\nrange_bearing_elevation::range_bearing_elevation( double r, double b, double e )\n{\n    bearing_elevation_.bearing( b );\n    bearing_elevation_.elevation( e );\n    range( r );\n}\n\ndouble range_bearing_elevation::range( double t )\n{\n    if( !comma::math::less( t, 0 ) )\n    {\n        range_ = t;\n    }\n    else\n    {\n        range_ = -t;\n        bearing_elevation_.bearing( -bearing_elevation_.bearing() );\n        bearing_elevation_.elevation( -bearing_elevation_.elevation() );\n    }\n    return range_;\n}\n\nEigen::Vector3d range_bearing_elevation::to_cartesian() const\n{\n    double xy_projection( range() * std::cos( elevation() ) );\n    return ::Eigen::Matrix< double, 3, 1 >( xy_projection * std::cos( bearing() )\n                                    , xy_projection * std::sin( bearing() )\n                                    , range() * std::sin( elevation() ) );\n}\n\nconst range_bearing_elevation& range_bearing_elevation::from_cartesian( double x, double y, double z )\n{\n    return from_cartesian( Eigen::Vector3d( x, y, z ) );\n}\n\nconst range_bearing_elevation& range_bearing_elevation::from_cartesian( const Eigen::Vector3d& v )\n{\n    range_ = v.norm();\n    if( comma::math::equal( range_, 0 ) ) { bearing_elevation_ = snark::bearing_elevation( 0, 0 ); return *this; }\n    const Eigen::AngleAxis< double >& a =  Eigen::AngleAxis< double >( Eigen::Quaternion< double >::FromTwoVectors( v, Eigen::Vector3d( 0, 0, 1 ) ) );\n    double e = M_PI / 2 - a.angle();\n    Eigen::AngleAxis< double > c( -e, a.axis() );\n    const Eigen::Matrix3d& r = c.toRotationMatrix();\n    Eigen::AngleAxis< double > d( Eigen::Quaternion< double >::FromTwoVectors( Eigen::Vector3d( 1, 0, 0 ), r * v ) );\n    bearing_elevation_.bearing( d.angle() * ( d.axis().z() < 0 ? -1 : 1 ) );\n    bearing_elevation_.elevation( e );\n    return *this;\n}\n\n// const range_bearing_elevation& range_bearing_elevation::from_cartesian( const Eigen::Vector3d& xyz )\n// {\n//     return from_cartesian( xyz[0], xyz[1], xyz[2] );\n// }\n//\n// const range_bearing_elevation& range_bearing_elevation::from_cartesian( double x, double y, double z )\n// { // todo: use rotation matrices instead!\n//     long double projection_square ( x * x +  y * y );\n//     if ( comma::math::equal( projection_square, 0 ) )\n//     {\n//         if ( comma::math::equal( z, 0 ) )\n//         {\n//             range_ = 0;\n//             bearing_elevation_.bearing( 0 );\n//             bearing_elevation_.elevation( 0 );\n//             return *this;\n//         }\n//         range_ = std::abs( z );\n//         bearing_elevation_.bearing( 0 );\n//         elevation( comma::math::less( z, 0 ) ? -M_PI / 2 : M_PI / 2 );\n//         return *this;\n//     }\n//     long double range_square( projection_square + z * z );\n//     long double lr( std::sqrt( range_square ) );\n//     long double elevation_ = 0;\n//     if ( !comma::math::equal( z, 0 ) )\n//     {\n//         long double r = z / lr;\n//         if ( comma::math::less( ( long double )( 1.0 ), r ) ) { r = 1; }\n//         else if ( comma::math::less( r, ( long double ) ( -1.0 ) ) ) { r = -1; }\n//         elevation_ = std::asin( r );\n//     }\n//     long double r = x / std::sqrt( projection_square );\n//     if ( comma::math::less( ( long double )( 1.0 ), r ) ) { r = 1; }\n//     else if ( comma::math::less( r, ( long double ) ( -1.0 ) ) ) { r = -1; }\n//     long double bearing_ = std::acos( r );\n//     if ( comma::math::less( y, 0 ) ) { bearing_ = M_PI * 2 - bearing_; }\n//     range_ = lr;\n//     bearing( bearing_ );\n//     elevation( elevation_ );\n//     return *this;\n// }\n\nEigen::AngleAxis< double > great_circle_angle_axis( const bearing_elevation& lhs, const bearing_elevation& rhs )\n{\n    Eigen::Vector3d a = rbe( 1, lhs.bearing(), lhs.elevation() ).to_cartesian();\n    Eigen::Vector3d b = rbe( 1, rhs.bearing(), rhs.elevation() ).to_cartesian();\n    return Eigen::AngleAxis< double >( Eigen::Quaternion< double >::FromTwoVectors( a, b ) );\n}\n\n} // namespace snark {\n", "meta": {"hexsha": "ba29ec0970a8c41ba6647001a2fa8d61643f0207", "size": 8110, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "math/range_bearing_elevation.cpp", "max_stars_repo_name": "mission-systems-pty-ltd/snark", "max_stars_repo_head_hexsha": "2bc8a20292ee3684d3a9897ba6fee43fed8d89ae", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 63.0, "max_stars_repo_stars_event_min_datetime": "2015-01-14T14:38:02.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-01T09:56:03.000Z", "max_issues_repo_path": "math/range_bearing_elevation.cpp", "max_issues_repo_name": "NEU-LC/snark", "max_issues_repo_head_hexsha": "db890f73f4c4bbe679405f3a607fd9ea373deb2c", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 39.0, "max_issues_repo_issues_event_min_datetime": "2015-01-21T00:57:38.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-22T04:22:35.000Z", "max_forks_repo_path": "math/range_bearing_elevation.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": 38.8038277512, "max_line_length": 150, "alphanum_fraction": 0.6178791615, "num_tokens": 2217, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6513548511303338, "lm_q2_score": 0.47268347662043286, "lm_q1q2_score": 0.3078846755458706}}
{"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/// Code for dealing with Green's functions for 1 dimension in real\n/// space.\n\n#include <iostream>\n#include <fstream>\n#include <string>\n#include <vector>\n#include <boost/filesystem.hpp>\n#include <dynamical_matrix.hpp>\n#include <qpoint_grid.hpp>\n#include <vasp_io.hpp>\n\nnamespace alma {\n/// Objects of this class enable the calling code to compute 1d\n/// Green's functions along particular directions in a bulk\n/// material.\nclass Green1d_factory {\npublic:\n    /// Number of q points in the grid.\n    const std::size_t nqpoints;\n    /// Number of degrees of freedom in the unit cell.\n    const std::size_t ndof;\n    /// Basic constructor.\n    ///\n    /// @param[in] structure - description of the crystal lattice\n    /// @param[in] q0 - starting point in reciprocal space, in\n    /// Cartesian coordinates\n    /// @param[in] normal - direction of the path in reciprocal\n    /// space, expressed in direct coordinates (only integers are\n    /// allowed)\n    /// @param[in] nqpoints_ - number of divisions of the segment\n    /// @param[in] builder - factory of dynamical matrices\n    Green1d_factory(const Crystal_structure& structure,\n                    const Eigen::Ref<const Eigen::VectorXd>& q0,\n                    const Eigen::Ref<const Eigen::VectorXi>& normal,\n                    const std::size_t nqpoints_,\n                    const Dynamical_matrix_builder& builder);\n    /// Obtain the Green's function for a particular angular frequency.\n    ///\n    /// @param[in] omega - angular frequency [rad / ps]\n    /// @param[in] ncells - number of unit cells to include in the\n    /// supercell\n    /// @return the Green's function matrix\n    Eigen::MatrixXcd build(double omega, std::size_t ncells) const;\n\n    /// Obtain the scattering rate caused by a diagonal perturbation\n    /// proportional to the frequency squared\n    ///\n    /// @param[in] q - wave number of the incident phonon, as a number\n    /// between 0 and 2 * pi\n    /// @param[in] omega - frequency of the incident phonon [rad / ps]\n    /// @param[in] wfin - wave function of the incident phonon over a\n    /// single unit cell\n    /// @param[in] factors - coefficient of omega ** 2 for each atom\n    /// @return a scattering rate in ps^{-1}\n    double calc_w0_dmass(\n        double q,\n        double omega,\n        const Eigen::Ref<const Eigen::VectorXcd>& wfin,\n        const Eigen::Ref<const Eigen::VectorXd>& factors) const;\n\nprivate:\n    /// Projection of the origin over the direction of interest,\n    /// in the interval [0, 2 * pi).\n    const double offset;\n    /// Wave numbers at which the spectrum is sampled, from 0 to 2 *\n    /// pi.\n    Eigen::ArrayXd qgrid;\n    /// Angular frequencies squared for all modes [rad ** 2 / ps ** 2].\n    ///\n    /// The first index runs over branches, the second over q points.\n    Eigen::ArrayXXd Egrid;\n    /// Directional derivative of omega ** 2 along the direction of\n    /// interest.\n    ///\n    /// The first index runs over branches, the second over q points.\n    Eigen::ArrayXXd dEgrid;\n    /// Wave functions (over a single unit cell) for all modes.\n    ///\n    /// The main vector index runs over q points.\n    std::vector<Eigen::MatrixXcd> wfgrid;\n    /// Extend all wave functions at a particular q point from a single\n    /// unit\n    /// cell to a supercell.\n    ///\n    /// @param[in] iq - index of the q point\n    /// @param[in] ncells - supercell size\n    inline Eigen::MatrixXcd get_superwfs(std::size_t iq,\n                                         std::size_t ncells) const;\n\n    /// Compute the integration weights of all q points and all\n    /// branches for a given energy.\n    ///\n    /// @param[in] omega - angular frequency squared [rad ** 2 / ps ** 2]\n    /// @return the weights as a complex vector\n    Eigen::MatrixXcd compute_weights(double omega2) const;\n};\n} // namespace alma\n", "meta": {"hexsha": "00d9070b3f1cfdc337b5942e34414332c511936b", "size": 4461, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/green1d.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/green1d.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/green1d.hpp", "max_forks_repo_name": "sousaw/BTE-Barna", "max_forks_repo_head_hexsha": "029ca43ef096c4b725d3aeb2955bc0df9ca544a9", "max_forks_repo_licenses": ["MIT", "BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.4568965517, "max_line_length": 73, "alphanum_fraction": 0.6572517373, "num_tokens": 1058, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6619228758499942, "lm_q2_score": 0.4649015713733885, "lm_q1q2_score": 0.30772898511065466}}
{"text": "#include <sstream>\n#include <Eigen/Geometry>\n#include \"Geometry.h\"\n\n#include <iostream>\n\nusing namespace Eigen;\n\nfloatOptional Geometry::intersect(const Ray &r) {\n    if (transformed) {\n        Vector4f newOrigin;\n        newOrigin << r.origin(), 1;\n        Vector4f newDir;\n        newDir << r.direction(), 0;\n\n        newOrigin = inverseModelMatrix * newOrigin;\n        newDir = inverseModelMatrix * newDir;\n        const Ray transformedR = Ray(newOrigin.head(3), newDir.head(3));\n        return objectIntersect(transformedR);\n    }\n    else {\n        return objectIntersect(r);\n    }\n}\n\nEigen::Vector3f Geometry::normalAtPoint(const Eigen::Vector3f &p) {\n    if (transformed) {\n        Vector4f localP, n;\n        localP << p, 1;\n        localP = inverseModelMatrix * localP;\n        n << objectNormal(localP.head(3)), 0;\n        n = inverseModelMatrix.transpose() * n;\n        return n.head(3).normalized();\n    }\n    else {\n        return objectNormal(p);\n    }\n}\n\nEigen::Vector3f Geometry::minVector(const Eigen::Vector3f &a, const Eigen::Vector3f &b) {\n    Vector3f minVec;\n    minVec.x() = std::min(a.x(), b.x());\n    minVec.y() = std::min(a.y(), b.y());\n    minVec.z() = std::min(a.z(), b.z());\n    return minVec;\n}\n\nEigen::Vector3f Geometry::maxVector(const Eigen::Vector3f &a, const Eigen::Vector3f &b) {\n    Vector3f maxVec;\n    maxVec.x() = std::max(a.x(), b.x());\n    maxVec.y() = std::max(a.y(), b.y());\n    maxVec.z() = std::max(a.z(), b.z());\n    return maxVec;\n}\n\nvoid Geometry::worldSpaceBoundingBox(Eigen::Vector3f &min, Eigen::Vector3f &max) {\n    // clockwise on bottom, then top\n    Vector4f v[8];\n    // bottom vertices\n    v[0] << min, 1;\n    v[1] << max.x(), min.y(), min.z(), 1;\n    v[2] << max.x(), min.y(), max.z(), 1;\n    v[3] << min.x(), min.y(), max.z(), 1;\n    // top vertices\n    v[4] << min.x(), max.y(), min.z(), 1;\n    v[5] << max.x(), max.y(), min.z(), 1;\n    v[6] << max, 1;\n    v[7] << min.x(), max.y(), max.z(), 1;\n\n    min << INFINITY, INFINITY, INFINITY;\n    max << -INFINITY, -INFINITY, -INFINITY;\n    for (int i = 0; i < 8; i++) {\n        v[i] = modelMatrix * v[i];\n        min = minVector(min, v[i].head(3));\n        max = maxVector(max, v[i].head(3));\n    }\n}\n\nvoid Geometry::boundingBox(Eigen::Vector3f &min, Eigen::Vector3f &max) {\n    objectBoundingBox(min, max);\n    if (transformed) {\n        worldSpaceBoundingBox(min, max);\n    }\n}\n\nEigen::Vector3f Geometry::getCenter() {\n    Vector4f localCenter;\n    localCenter << objectCenter(), 1;\n    if (transformed) {\n        localCenter = modelMatrix * localCenter;\n    }\n    return localCenter.head(3);\n}\n\nstd::string Geometry::to_string() {\n    std::stringstream str;\n    str << \"- Color: \" << formatVector(pigment) << \"\\n\";\n    str << \"- Material:\\n\";\n    str << \"  - Ambient: \" << finish.ambient << \"\\n\";\n    str << \"  - Diffuse: \" << finish.diffuse << \"\\n\";\n    str << \"  - Specular: \" << finish.specular << \"\\n\";\n    str << \"  - Roughness: \" << finish.roughness << \"\\n\";\n    str << \"  - Metallic: \" << finish.metallic << \"\\n\";\n    str << \"  - IOR: \" << finish.ior << \"\\n\";\n    str << \"  - Reflection: \" << finish.reflection << \"\\n\";\n    str << \"  - Refraction: \" << finish.filter << \"\\n\";\n\n    return str.str();\n}\n\nvoid Geometry::scale(const Eigen::Vector3f s) {\n    Transform<float, 3, Projective> sc;\n    sc = Scaling(s);\n    modelMatrix = sc.matrix() * modelMatrix;\n    transformed = true;\n}\n\nvoid Geometry::rotate(const Eigen::Vector3f r) {\n    Transform<float, 3, Projective> rot;\n    rot = AngleAxisf(r.z() * M_PI / 180, Vector3f::UnitZ())\n        * AngleAxisf(r.y() * M_PI / 180, Vector3f::UnitY())\n        * AngleAxisf(r.x() * M_PI / 180, Vector3f::UnitX());\n    modelMatrix = rot.matrix() * modelMatrix;\n    transformed = true;\n}\n\nvoid Geometry::translate(const Eigen::Vector3f t) {\n    Matrix4f tr = Matrix4f::Identity();\n    tr.col(3).head(3) = t;\n    modelMatrix = tr * modelMatrix;\n    transformed = true;\n}\n\nvoid Geometry::finalizeTransform() {\n    if (transformed) {\n        inverseModelMatrix = modelMatrix.inverse();\n    }\n}\n\nRay Geometry::getTransformedRay(const Ray &r) {\n    if (transformed) {\n        Vector4f newOrigin;\n        newOrigin << r.origin(), 1;\n        Vector4f newDir;\n        newDir << r.direction(), 0;\n\n        newOrigin = modelMatrix * newOrigin;\n        newDir = modelMatrix * newDir;\n        return Ray(newOrigin.head(3), newDir.head(3));\n    }\n    else {\n        return r;\n    }\n}\n", "meta": {"hexsha": "edca3cc43f35360f38692a117d5fcdb992daef6f", "size": 4425, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Geometry/Geometry.cpp", "max_stars_repo_name": "moneil113/RayTrace", "max_stars_repo_head_hexsha": "0fd1264b6da395c038b1235485b210c0d8d4655f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Geometry/Geometry.cpp", "max_issues_repo_name": "moneil113/RayTrace", "max_issues_repo_head_hexsha": "0fd1264b6da395c038b1235485b210c0d8d4655f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Geometry/Geometry.cpp", "max_forks_repo_name": "moneil113/RayTrace", "max_forks_repo_head_hexsha": "0fd1264b6da395c038b1235485b210c0d8d4655f", "max_forks_repo_licenses": ["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.5483870968, "max_line_length": 89, "alphanum_fraction": 0.5699435028, "num_tokens": 1313, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7025300449389326, "lm_q2_score": 0.43782349911420193, "lm_q1q2_score": 0.307584162508021}}
{"text": "/* \n * Copyright 2009-2011 The VOTCA Development Team (http://www.votca.org)\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n */\n\n#include <votca/csg/map.h>\n#include <votca/csg/topology.h>\n#include <iostream>\n#include <votca/tools/matrix.h>\n#include <votca/tools/tokenizer.h>\n#include <numeric>\n#include <boost/lexical_cast.hpp>\n\nnamespace votca { namespace csg {\n\nusing namespace std;\n\nMap::~Map()\n{\n    vector<BeadMap *>::iterator iter;\n    for(iter=_maps.begin();iter!=_maps.end();++iter)\n        delete (*iter);    \n    _maps.clear();\n}\n\nvoid Map::Apply()\n{\n    vector<BeadMap *>::iterator iter;\n    for(iter=_maps.begin();iter!=_maps.end();++iter)\n        (*iter)->Apply();\n}\n\nvoid Map_Sphere::Initialize(Molecule *in, Bead *out, Property *opts_bead, Property *opts_map) {\n    BeadMap::Initialize(in, out, opts_bead, opts_map);\n    \n    vector<string> beads;\n    vector<double> weights;\n    vector<double> fweights;\n\n    // get the beads\n    string s(_opts_bead->get(\"beads\").value());\n    Tokenizer tok_beads(s, \" \\n\\t\");\n    tok_beads.ToVector(beads);\n\n    // get vector of weights\n    Tokenizer tok_weights(_opts_map->get(\"weights\").value(), \" \\n\\t\");\n    tok_weights.ConvertToVector<double>(weights);\n\n    // check weather weights and # beads matches\n    if (beads.size() != weights.size())\n        throw runtime_error(string(\"number of subbeads in \" +\n                opts_bead->get(\"name\").as<string>()\n                + \" and number of weights in map \"\n                + opts_map->get(\"name\").as<string>() + \" do not match\"));\n\n    // normalize the weights\n    double norm = 1./ std::accumulate(weights.begin(), weights.end(), 0.);\n    \n    transform(weights.begin(), weights.end(), weights.begin(), bind2nd(multiplies<double>(), norm));\n    // get the d vector if exists or initialize same as weights\n    vector<double> d;\n    if(_opts_map->exists(\"d\")) {\n        Tokenizer tok_weights(_opts_map->get(\"d\").value(), \" \\n\\t\");\n        tok_weights.ConvertToVector(d);\n        // normalize d coefficients\n        norm = 1./std::accumulate(d.begin(), d.end(), 0.);\n        transform(d.begin(), d.end(), d.begin(), bind2nd(multiplies<double>(), norm));\n    } else {\n        // initialize force-weights with weights\n        d.resize(weights.size());\n        copy(weights.begin(), weights.end(), d.begin());\n    }\n\n    // check weather number of d coeffs is correct\n    if (beads.size() != d.size()) {\n        throw runtime_error(string(\"number of subbeads in \" +\n            opts_bead->get(\"name\").as<string>()\n            + \" and number of d-coefficients in map \"\n            + opts_map->get(\"name\").as<string>() + \" do not match\"));\n    }\n\n    fweights.resize(weights.size());\n    // calculate force weights by d_i/w_i\n    for(size_t i=0; i<weights.size(); ++i) {\n        if(weights[i] == 0 && d[i]!=0) {\n            throw runtime_error(\n                \"A d coefficient is nonzero while weights is zero in mapping \"\n                + opts_map->get(\"name\").as<string>());\n        }\n        if(weights[i] != 0)\n            fweights[i] = d[i] / weights[i];\n        else\n            fweights[i] = 0;        \n    }\n\n    for (size_t i = 0; i < beads.size(); ++i) {\n        int iin = in->getBeadByName(beads[i]);\n        if (iin < 0)\n            throw std::runtime_error(string(\"mapping error: molecule \" + beads[i] + \" does not exist\"));\n        AddElem(in->getBead(iin), weights[i], fweights[i]);\n    }\n}\n\nvoid Map_Sphere::Apply()\n{\n    vector<element_t>::iterator iter;\n    vec cg(0., 0., 0.), f(0.,0.,0.), vel(0.,0.,0.);\n    bool bPos, bVel, bF;\n    bPos=bVel=bF=false;\n    _out->ParentBeads().clear();\n\n    // the following is needed for pbc treatment\n    Topology *top = _out->getParent();\n    double max_dist = 0.5*top->ShortestBoxSize();\n    vec r0 = vec(0,0,0);\n    string name0;\n    int id0;\n    if(_matrix.size() > 0) {\n        if(_matrix.front()._in->HasPos()) {\n            r0=_matrix.front()._in->getPos();\n            name0 = _matrix.front()._in->getName();\n            id0 = _matrix.front()._in->getId();\n        }\n    }\n\n    double M = 0;\n\n    for(iter = _matrix.begin(); iter != _matrix.end(); ++iter) {\n        Bead *bead = iter->_in;\n        _out->ParentBeads().push_back(bead->getId());\n        M+=bead->getM();\n        if(bead->HasPos()) {\n            vec r = top->BCShortestConnection(r0, bead->getPos());\n            if(abs(r) > max_dist) {\n                cout << r0 << \" \" << bead->getPos() << endl;\n                throw std::runtime_error(\"coarse-grained bead is bigger than half the box \\n (atoms \"\n                        + name0 + \" (id \" + boost::lexical_cast<string>(id0+1) + \")\" + \", \" + bead->getName() + \" (id \" + boost::lexical_cast<string>(bead->getId()+1) + \")\" +  +\" , molecule \"\n                        + boost::lexical_cast<string>(bead->getMolecule()->getId()+1) + \")\" );\n            }\n            cg += (*iter)._weight * (r+r0);\n            bPos=true;\n        }\n        if(bead->HasVel()) {\n            vel += (*iter)._weight * bead->getVel();\n            bVel = true;\n        }\n        if(bead->HasF()) {\n            f += (*iter)._force_weight * bead->getF();\n            bF = true;\n        }\n    }\n    _out->setM(M);\n    if(bPos)\n        _out->setPos(cg);\n    if(bVel)\n        _out->setVel(vel);\n    if(bF)\n        _out->setF(f);\n}\n\n/// \\todo implement this function\nvoid Map_Ellipsoid::Apply()\n{\n    vector<element_t>::iterator iter;\n    vec cg(0., 0., 0.), c(0., 0., 0.), f(0.,0.,0.), vel(0.,0.,0.);\n    matrix m(0.);\n     bool bPos, bVel, bF;\n    bPos=bVel=bF=false;\n\n    // the following is needed for pbc treatment\n    Topology *top = _out->getParent();\n    double max_dist = 0.5*top->ShortestBoxSize();\n    vec r0 = vec(0,0,0);\n    if(_matrix.size() > 0) {\n        if(_matrix.front()._in->HasPos()) {            \n            r0=_matrix.front()._in->getPos();\n        }\n    }\n\n    int n;\n    n = 0;\n    _out->ParentBeads().clear();\n    for(iter = _matrix.begin(); iter != _matrix.end(); ++iter) {\n       Bead *bead = iter->_in;\n       _out->ParentBeads().push_back(bead->getId());\n       if(bead->HasPos()) {\n            vec r = top->BCShortestConnection(r0, bead->getPos());\n            if(abs(r) > max_dist)\n                throw std::runtime_error(\"coarse-grained bead is bigger than half the box\");\n            cg += (*iter)._weight * (r+r0);\n            bPos=true;\n        }\n        if(bead->HasVel() == true) {\n            vel += (*iter)._weight * bead->getVel();\n            bVel = true;\n        }\n        if(bead->HasF()) {\n            /// \\todo fix me, right calculation should be F_i = m_cg / sum(w_i) * sum(w_i/m_i*F_i)\n            //f += (*iter)._weight * _in->getBeadF((*iter)._in);\n            f += (*iter)._force_weight * bead->getF();\n            bF = true;\n        }\n        \n        if((*iter)._weight>0 && bead->HasPos()) {\n            c += bead->getPos();\n            n++;\n        }\n    }\n    \n    if(bPos)\n        _out->setPos(cg);\n    if(bVel)\n        _out->setVel(vel);\n    if(bF)\n        _out->setF(f);\n\n    if(!_matrix[0]._in->HasPos()) {\n        _out->setU(vec(1.0,0,0));\n        _out->setV(vec(.0,1,0));\n        _out->setW(vec(.0,0,1));\n        return;\n    }\n    \n    // calculate the tensor of gyration\n    c=c/(double)n;    \n    for(iter = _matrix.begin(); iter != _matrix.end(); ++iter) {\n        if((*iter)._weight == 0) continue;\n        Bead *bead = iter->_in;\n            vec v = bead->getPos() - c;\n            //v = vec(1, 0.5, 0) * 0.*(drand48()-0.5)\n            //    + vec(0.5, -1, 0) * (drand48()-0.5)\n            //    + vec(0, 0, 1) * (drand48()-0.5);\n        \n            //Normalize the tensor with 1/number_of_atoms_per_bead\n            m[0][0] += v.getX()*v.getX()/(double)_matrix.size();\n            m[0][1] += v.getX()*v.getY()/(double)_matrix.size();\n            m[0][2] += v.getX()*v.getZ()/(double)_matrix.size();\n            m[1][1] += v.getY()*v.getY()/(double)_matrix.size();\n            m[1][2] += v.getY()*v.getZ()/(double)_matrix.size();\n            m[2][2] += v.getZ()*v.getZ()/(double)_matrix.size();\n        \n    }\n    m[1][0] = m[0][1];\n    m[2][0] = m[0][2];\n    m[2][1] = m[1][2];\n    \n    // calculate the eigenvectors\n    matrix::eigensystem_t es;\n    m.SolveEigensystem(es);\n    \n    //vec eigenv1=es.eigenvecs[0];\n    //vec eigenv2=es.eigenvecs[1];\n    //vec eigenv3=es.eigenvecs[2];\n    \n/*    _out->seteigenvec1(eigenv1);\n    _out->seteigenvec2(eigenv2);\n    _out->seteigenvec3(eigenv3);\n  */  \n    \n    vec u = es.eigenvecs[0];\n    vec v = _matrix[1]._in->getPos() - _matrix[0]._in->getPos();\n    v.normalize();\n    \n    _out->setV(v);\n    \n    vec w = _matrix[2]._in->getPos() - _matrix[0]._in->getPos();\n    w.normalize();\n    \n    if((v^w)*u < 0) u=vec(0.,0.,0.)-u;\n    _out->setU(u);\n    \n    //write out w\n    w=u^v;\n    w.normalize();\n    _out->setW(w);\n    \n    //out.BeadV(_out) = v;\n    \n    //out.BeadW(_out) = es.eigenvecs[2];\n}\n\n}}\n", "meta": {"hexsha": "5113c4452b591aa1802443afe8c7c5eb616eb557", "size": 9380, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/libcsg/map.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/libcsg/map.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/libcsg/map.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": 31.7966101695, "max_line_length": 191, "alphanum_fraction": 0.5342217484, "num_tokens": 2738, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6150878696277512, "lm_q2_score": 0.5, "lm_q1q2_score": 0.3075439348138756}}
{"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   A nonlinear optimizer that uses the Levenberg-Marquardt trust-region scheme\n * @author  Richard Roberts\n * @author  Frank Dellaert\n * @author  Luca Carlone\n * @date    Feb 26, 2012\n */\n\n#include <gtsam/nonlinear/LevenbergMarquardtOptimizer.h>\n#include <gtsam/nonlinear/internal/LevenbergMarquardtState.h>\n#include <gtsam/nonlinear/NonlinearFactorGraph.h>\n#include <gtsam/nonlinear/Values.h>\n#include <gtsam/linear/GaussianFactorGraph.h>\n#include <gtsam/linear/linearExceptions.h>\n#include <gtsam/inference/Ordering.h>\n#include <gtsam/base/Vector.h>\n#include <gtsam/base/timing.h>\n\n#include <boost/format.hpp>\n#include <boost/optional.hpp>\n#include <boost/range/adaptor/map.hpp>\n\n#include <cmath>\n#include <fstream>\n#include <iostream>\n#include <limits>\n#include <string>\n\nusing namespace std;\n\nnamespace gtsam {\n\nusing boost::adaptors::map_values;\ntypedef internal::LevenbergMarquardtState State;\n\n/* ************************************************************************* */\nLevenbergMarquardtOptimizer::LevenbergMarquardtOptimizer(const NonlinearFactorGraph& graph,\n                                                         const Values& initialValues,\n                                                         const LevenbergMarquardtParams& params)\n    : NonlinearOptimizer(\n          graph, std::unique_ptr<State>(new State(initialValues, graph.error(initialValues),\n                                                  params.lambdaInitial, params.lambdaFactor))),\n      params_(LevenbergMarquardtParams::EnsureHasOrdering(params, graph)) {}\n\nLevenbergMarquardtOptimizer::LevenbergMarquardtOptimizer(const NonlinearFactorGraph& graph,\n                                                         const Values& initialValues,\n                                                         const Ordering& ordering,\n                                                         const LevenbergMarquardtParams& params)\n    : NonlinearOptimizer(\n          graph, std::unique_ptr<State>(new State(initialValues, graph.error(initialValues),\n                                                  params.lambdaInitial, params.lambdaFactor))),\n      params_(LevenbergMarquardtParams::ReplaceOrdering(params, ordering)) {}\n\n/* ************************************************************************* */\nvoid LevenbergMarquardtOptimizer::initTime() {\n  startTime_ = boost::posix_time::microsec_clock::universal_time();\n}\n\n/* ************************************************************************* */\ndouble LevenbergMarquardtOptimizer::lambda() const {\n  auto currentState = static_cast<const State*>(state_.get());\n  return currentState->lambda;\n}\n\n/* ************************************************************************* */\nint LevenbergMarquardtOptimizer::getInnerIterations() const {\n  auto currentState = static_cast<const State*>(state_.get());\n  return currentState->totalNumberInnerIterations;\n}\n\n/* ************************************************************************* */\nGaussianFactorGraph::shared_ptr LevenbergMarquardtOptimizer::linearize() const {\n  return graph_.linearize(state_->values);\n}\n\n/* ************************************************************************* */\nGaussianFactorGraph LevenbergMarquardtOptimizer::buildDampedSystem(\n    const GaussianFactorGraph& linear, const VectorValues& sqrtHessianDiagonal) const {\n  gttic(damp);\n  auto currentState = static_cast<const State*>(state_.get());\n\n  if (params_.verbosityLM >= LevenbergMarquardtParams::DAMPED)\n    std::cout << \"building damped system with lambda \" << currentState->lambda << std::endl;\n\n  if (params_.diagonalDamping)\n    return currentState->buildDampedSystem(linear, sqrtHessianDiagonal);\n  else\n    return currentState->buildDampedSystem(linear);\n}\n\n/* ************************************************************************* */\n// Log current error/lambda to file\ninline void LevenbergMarquardtOptimizer::writeLogFile(double currentError){\n  auto currentState = static_cast<const State*>(state_.get());\n\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*/ currentState->totalNumberInnerIterations << \",\"\n        << 1e-6 * (currentTime - startTime_).total_microseconds() << \",\"\n        << /*current error*/ currentError << \",\" << currentState->lambda << \",\"\n        << /*outer iterations*/ currentState->iterations << endl;\n  }\n}\n\n/* ************************************************************************* */\nbool LevenbergMarquardtOptimizer::tryLambda(const GaussianFactorGraph& linear,\n                                            const VectorValues& sqrtHessianDiagonal) {\n  auto currentState = static_cast<const State*>(state_.get());\n  bool verbose = (params_.verbosityLM >= LevenbergMarquardtParams::TRYLAMBDA);\n\n#ifdef GTSAM_USING_NEW_BOOST_TIMERS\n  boost::timer::cpu_timer lamda_iteration_timer;\n  lamda_iteration_timer.start();\n#else\n  boost::timer lamda_iteration_timer;\n  lamda_iteration_timer.restart();\n#endif\n\n  if (verbose)\n    cout << \"trying lambda = \" << currentState->lambda << endl;\n\n  // Build damped system for this lambda (adds prior factors that make it like gradient descent)\n  auto dampedSystem = buildDampedSystem(linear, sqrtHessianDiagonal);\n\n  // Try solving\n  double modelFidelity = 0.0;\n  bool step_is_successful = false;\n  bool stopSearchingLambda = false;\n  double newError = numeric_limits<double>::infinity(), costChange;\n  Values newValues;\n  VectorValues delta;\n\n  bool systemSolvedSuccessfully;\n  try {\n    // ============ Solve is where most computation happens !! =================\n    delta = solve(dampedSystem, params_);\n    systemSolvedSuccessfully = true;\n  } catch (const IndeterminantLinearSystemException&) {\n    systemSolvedSuccessfully = false;\n  }\n\n  if (systemSolvedSuccessfully) {\n    if (verbose)\n      cout << \"linear delta norm = \" << delta.norm() << endl;\n    if (params_.verbosityLM >= 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 = currentState->error - newlinearizedError;\n    if (verbose)\n      cout << \"newlinearizedError = \" << newlinearizedError\n           << \"  linearizedCostChange = \" << linearizedCostChange << endl;\n\n    if (linearizedCostChange >= 0) {  // step is valid\n      // update values\n      gttic(retract);\n      // ============ This is where the solution is updated ====================\n      newValues = currentState->values.retract(delta);\n      // =======================================================================\n      gttoc(retract);\n\n      // compute new error\n      gttic(compute_error);\n      if (verbose)\n        cout << \"calculating error:\" << endl;\n      newError = graph_.error(newValues);\n      gttoc(compute_error);\n\n      if (verbose)\n        cout << \"old error (\" << currentState->error << \") new (tentative) error (\" << newError\n             << \")\" << endl;\n\n      // cost change in the original, nonlinear system (old - new)\n      costChange = currentState->error - newError;\n\n      if (linearizedCostChange >\n          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 (verbose)\n          cout << \"modelFidelity: \" << modelFidelity << endl;\n      }  // else we consider the step non successful and we either increase lambda or stop if error\n         // change is small\n\n      double minAbsoluteTolerance = params_.relativeErrorTol * currentState->error;\n      // if the change is small we terminate\n      if (std::abs(costChange) < minAbsoluteTolerance) {\n        if (verbose)\n          cout << \"abs(costChange)=\" << std::abs(costChange)\n               << \"  minAbsoluteTolerance=\" << minAbsoluteTolerance\n               << \" (relativeErrorTol=\" << params_.relativeErrorTol << \")\" << endl;\n        stopSearchingLambda = true;\n      }\n    }\n  } // if (systemSolvedSuccessfully)\n\n  if (params_.verbosityLM == LevenbergMarquardtParams::SUMMARY) {\n// do timing\n#ifdef GTSAM_USING_NEW_BOOST_TIMERS\n    double iterationTime = 1e-9 * lamda_iteration_timer.elapsed().wall;\n#else\n    double iterationTime = lamda_iteration_timer.elapsed();\n#endif\n    if (currentState->iterations == 0)\n      cout << \"iter      cost      cost_change    lambda  success iter_time\" << endl;\n\n    cout << boost::format(\"% 4d % 8e   % 3.2e   % 3.2e  % 4d   % 3.2e\") % currentState->iterations %\n                newError % costChange % currentState->lambda % systemSolvedSuccessfully %\n                iterationTime << endl;\n  }\n\n  if (step_is_successful) {\n    // we have successfully decreased the cost and we have good modelFidelity\n    // NOTE(frank): As we return immediately after this, we move the newValues\n    // TODO(frank): make Values actually support move. Does not seem to happen now.\n    state_ = currentState->decreaseLambda(params_, modelFidelity, std::move(newValues), newError);\n    return true;\n  } else if (!stopSearchingLambda) {  // we failed to solved the system or had no decrease in cost\n    if (verbose)\n      cout << \"increasing lambda\" << endl;\n    State* modifiedState = static_cast<State*>(state_.get());\n    modifiedState->increaseLambda(params_); // TODO(frank): make this functional with Values move\n\n    // check if lambda is too big\n    if (modifiedState->lambda >= params_.lambdaUpperBound) {\n      if (params_.verbosity >= NonlinearOptimizerParams::TERMINATION ||\n          params_.verbosityLM == LevenbergMarquardtParams::SUMMARY)\n        cout << \"Warning:  Levenberg-Marquardt giving up because \"\n                \"cannot decrease error with maximum lambda\" << endl;\n      return true;\n    } else {\n      return false;  // only case where we will keep trying\n    }\n  } else {  // the change in the cost is very small and it is not worth trying bigger lambdas\n    if (verbose)\n      cout << \"Levenberg-Marquardt: stopping as relative cost reduction is small\" << endl;\n    return true;\n  }\n}\n\n/* ************************************************************************* */\nGaussianFactorGraph::shared_ptr LevenbergMarquardtOptimizer::iterate() {\n  auto currentState = static_cast<const State*>(state_.get());\n\n  gttic(LM_iterate);\n\n  // Linearize graph\n  if (params_.verbosityLM >= LevenbergMarquardtParams::DAMPED)\n    cout << \"linearizing = \" << endl;\n  GaussianFactorGraph::shared_ptr linear = linearize();\n\n  if(currentState->totalNumberInnerIterations==0) { // write initial error\n    writeLogFile(currentState->error);\n\n    if (params_.verbosityLM == LevenbergMarquardtParams::SUMMARY) {\n      cout << \"Initial error: \" << currentState->error\n           << \", values: \" << currentState->values.size() << std::endl;\n    }\n  }\n\n  // Only calculate diagonal of Hessian (expensive) once per outer iteration, if we need it\n  VectorValues sqrtHessianDiagonal;\n  if (params_.diagonalDamping) {\n    sqrtHessianDiagonal = linear->hessianDiagonal();\n    for (Vector& v : sqrtHessianDiagonal | map_values) {\n      v = v.cwiseMax(params_.minDiagonal).cwiseMin(params_.maxDiagonal).cwiseSqrt();\n    }\n  }\n\n  // Keep increasing lambda until we make make progress\n  while (!tryLambda(*linear, sqrtHessianDiagonal)) {\n    auto newState = static_cast<const State*>(state_.get());\n    writeLogFile(newState->error);\n  }\n\n  return linear;\n}\n\n} /* namespace gtsam */\n\n", "meta": {"hexsha": "c85891af2d4106887adbf7859177cf40c10a7349", "size": 12155, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "gtsam/nonlinear/LevenbergMarquardtOptimizer.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/nonlinear/LevenbergMarquardtOptimizer.cpp", "max_issues_repo_name": "DEVESHTARASIA/gtsam", "max_issues_repo_head_hexsha": "e90e1f1dd2105b47df1d731ac82da28a6a9be454", "max_issues_repo_licenses": ["BSD-3-Clause"], "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": "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": 40.788590604, "max_line_length": 100, "alphanum_fraction": 0.6247634718, "num_tokens": 2713, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5964331462646255, "lm_q2_score": 0.5156199157230157, "lm_q1q2_score": 0.30753280861137927}}
{"text": "/*\n * kaskadeBridge.hh\n *\n *  Created on: 06.12.2013\n *      Author: Lars Lubkoll, Anton Schiela\n */\n\n#ifndef KASKADE_BRIDGE_HH_\n#define KASKADE_BRIDGE_HH_\n\n#include <boost/signals2.hpp>\n#include <boost/bind.hpp>\n\n#include \"algorithm/abstract_interface.hh\"\n#include \"algorithm/dune_bridge.hh\"\n#include \"algorithm/newton_bridge.hh\"\n\nnamespace Kaskade\n{\n  template <class Value>\n  void assignIfNegative(Value& val, Value newVal)\n  {\n    if(val < 0) val = newVal;\n  }\n\n  namespace Bridge\n  {\n    template <class Linearization>\n    class ConnectedLinearization : public Linearization, public AbstractFlushConnection\n    {\n    public:\n      template <typename... Args>\n      ConnectedLinearization(const Args&... args) : Linearization(args...)\n      {}\n\n      virtual ~ConnectedLinearization() { changed(); flushconn.disconnect(); }\n\n      virtual void flush() { changed(); Linearization::flush(); }\n\n      virtual void connectToSignalForFlush(boost::signals2::signal<void ()>& sig)\n      {\n        if(flushconn.connected()) flushconn.disconnect();\n        flushconn=sig.connect(boost::bind(&ConnectedLinearization<Linearization>::flush, this));\n      }\n\n      boost::signals2::signal<void ()> changed;\n      boost::signals2::connection flushconn;\n    };\n\n\n\n    /// Bridge::Linearization class that uses a VariationalFunctionalAssembler to create linear systems\n    /** Implements AbstractLinearization */\n    template<class Functional>\n    class KaskadeLinearization : public AbstractLinearization, public SparseLinearSystem\n    {\n    public:\n\n      static const int nThreads = 32;\n\n      typedef typename Functional::AnsatzVars::VariableSet DomainElement;\n      typedef typename Functional::TestVars::VariableSet ImageElement;\n      typedef typename Functional::Scalar Scalar;\n      typedef LinearizationAt<Functional> Implementation;\n      typedef VariationalFunctionalAssembler<Implementation> Assembler;\n      typedef typename DomainElement::Descriptions::template CoefficientVectorRepresentation<>::type CoefficientVector;\n      typedef Dune::LinearOperator<CoefficientVector, CoefficientVector> OperatorType;\n      typedef OperatorType Operator;\n\n      /*      KaskadeLinearization()\n      : x(0), fu(nullptr), lin(*fu,x), ass(nullptr), xptr(nullptr)\n      {\n        flush();\n      }\n\n      /// Creation of a linearization for a functional fu at x_\n      KaskadeLinearization(Functional const& fu_)\n      : x(0), fu(&fu_), lin(*fu,x), ass(nullptr), xptr(nullptr)\n      {\n        flush();\n      }*/\n\n      /// Creation of a linearization for a functional fu at x_\n      KaskadeLinearization(Functional const& fu_, DomainElement const& x_)\n        : x(x_), fu(&fu_), lin(*fu,x), ass(new Assembler(x.descriptions.spaces)), xptr(new Vector<DomainElement>(x))\n      {\n        flush();\n      }\n\n      /// Creation of a linearization for a functional fu at x_\n      KaskadeLinearization(Functional const& fu_, DomainElement const& x_, std::shared_ptr<Assembler> const& ass_)\n        : x(x_), fu(&fu_), lin(*fu,x), ass(ass_), xptr(new Vector<DomainElement>(x))\n      {\n        flush();\n      }\n\n      KaskadeLinearization(KaskadeLinearization const& other)\n        : x(other.x), fu(other.fu), lin(*fu,x), ass(other.ass), xptr(new Vector<DomainElement>(x))\n      {\n      }\n\n      virtual ~KaskadeLinearization() {}\n\n      /// Number of columns of components [cbegin, cend)\n      int cols(int cbegin=0, int cend=-1) const\n      {\n        assignIfNegative(cend,nColBlocks());\n        assert(cbegin<cend);\n        return x.descriptions.degreesOfFreedom(cbegin,cend);\n      }\n\n      /// Number of rows of components [rbegin, rend)\n      int rows(int rbegin=0, int rend=-1) const\n      {\n        assignIfNegative(rend,nRowBlocks());\n        assert(rbegin < rend);\n        return x.descriptions.degreesOfFreedom(rbegin,rend);\n      }\n\n      void precompute() {\n        doAssemble(Assembler::VALUE | Assembler::RHS | Assembler::MATRIX);\n      }\n\n      /// write blocks of the hessian matrix into mat\n      void getMatrixBlocks(MatrixAsTriplet<Scalar>& mat, int rbegin, int rend, int cbegin, int cend) const\n      {\n        doAssemble(Assembler::VALUE | Assembler::RHS | Assembler::MATRIX);\n        mat = ass->template get<MatrixAsTriplet<Scalar> >(false,rbegin,rend,cbegin,cend);\n\n        if(DiscreteBlockTraits<Functional>::anyPresent)\n        {\n          MatrixAsTriplet<Scalar> matD;\n          getDiscreteMatrixBlocks(matD,rbegin,rend,cbegin,cend);\n          mat+=matD;\n        }\n      }\n\n      /// write components of the gradient into rhs\n      void getRHSBlocks(std::vector<Scalar>& rhs, int rbegin, int rend) const\n      {\n        doAssemble(Assembler::VALUE | Assembler::RHS);\n        rhs.resize(rows(rbegin,rend),0.0);\n        ass->toSequence(rbegin,rend,rhs.begin());\n        if(DiscreteBlockTraits<Functional>::anyPresent)\n        {\n          addDiscreteRHSBlocks(rhs,rbegin,rend);\n        }\n      }\n\n\n      /// return number of columns\n      int nColBlocks() const { return Functional::AnsatzVars::noOfVariables; }\n\n      /// return number of rows\n      int nRowBlocks() const { return Functional::TestVars::noOfVariables; }\n\n      /// return point of linearization\n      AbstractFunctionSpaceElement const& getOrigin() const\n      {\n        return *xptr;\n      }\n\n      void setOrigin(AbstractFunctionSpaceElement const& x_)\n      {\n        x = Bridge::getImpl<DomainElement>(x_);\n        xptr.reset(new Vector<DomainElement>(x));\n\n        if(ass == nullptr)\n        {\n          ass.reset(new Assembler(x.descriptions.spaces));\n        }\n      }\n\n      /// return the implementation\n      Implementation const& getLinImpl() const {return lin; }\n\n      /// flush all data, gathered so far\n      void flush() { ass->flush( Assembler::VALUE | Assembler::RHS | Assembler::MATRIX ); }\n\n      /// return whether x is in the domain of definition\n      bool inDomain(DomainElement const& x) { return InDomainTraits<Functional,DomainElement>::inDomain(x); }\n\n      /// return the current value Functional(Origin)\n      double eval() const\n      {\n        doAssemble(Assembler::VALUE);\n        Scalar value =ass->functional();\n        if(DiscreteBlockTraits<Functional>::anyPresent)\n          value += DiscreteBlockTraits<Functional>::getValue(*fu,x);\n        return value;\n      }\n\n      double getValue() const { return eval(); }\n\n      void evald(AbstractFunctionSpaceElement& v, int rbegin, int rend) const\n      {\n        assignIfNegative(rend,nRowBlocks());\n        assert(rbegin<=rend);\n        std::vector<Scalar> rhs(rows(rbegin,rend),0.0);\n        getRHSBlocks(rhs,rbegin,rend);\n        dynamic_cast<Vector<ImageElement>& >(v).read(rhs,rbegin,rend);\n      }\n\n      void ddxpy(AbstractFunctionSpaceElement& y, AbstractFunctionSpaceElement const& x, int rbegin=0, int rend=-1, int cbegin=0, int cend=-1) const\n      {\n        assignIfNegative(rend,nRowBlocks());\n        assignIfNegative(cend,nColBlocks());\n        d2axpy(1.0,y,x,rbegin,rend,cbegin,cend);\n      }\n\n      void d2axpy(double a, AbstractFunctionSpaceElement& y, AbstractFunctionSpaceElement const& x, int rbegin=0, int rend=-1, int cbegin=0, int cend=-1) const\n      {\n        assignIfNegative(rend,nRowBlocks());\n        assignIfNegative(cend,nColBlocks());\n        assert( cbegin <= cend );\n        assert( rbegin <= rend );\n        std::vector<Scalar> result, argument;\n        dynamic_cast<Vector<ImageElement> const&>(x).write(argument,cbegin,cend);\n        dynamic_cast<Vector<ImageElement> const&>(y).write(result,rbegin,rend);\n        MatrixAsTriplet<Scalar> mat;\n        getMatrixBlocks(mat,rbegin,rend,cbegin,cend);\n        mat.axpy(result, argument, a);\n        dynamic_cast<Vector<ImageElement>&>(y).read(result,rbegin,rend);\n      }\n\n      void ddtxpy(AbstractFunctionSpaceElement& y, AbstractFunctionSpaceElement const& x, int rbegin=0, int rend=-1, int cbegin=0, int cend=-1) const\n      {\n        assignIfNegative(rend,nRowBlocks());\n        assignIfNegative(cend,nColBlocks());\n        d2taxpy(1.0,y,x,rbegin,rend,cbegin,cend);\n      }\n\n      void d2taxpy(double a, AbstractFunctionSpaceElement& y, AbstractFunctionSpaceElement const& x, int rbegin=0, int rend=-1, int cbegin=0, int cend=-1) const\n      {\n        assignIfNegative(rend,nRowBlocks());\n        assignIfNegative(cend,nColBlocks());\n\n        assert( cbegin <= cend );\n        assert( rbegin <= rend );\n        std::vector<Scalar> result, argument;\n        dynamic_cast<Vector<ImageElement> const&>(x).write(argument,rbegin,rend);\n        dynamic_cast<Vector<ImageElement> const&>(y).write(result,cbegin,cend);\n        MatrixAsTriplet<Scalar> mat;\n        getMatrixBlocks(mat,rbegin,rend,cbegin,cend);\n        mat.transpose().axpy(result, argument, a);\n        dynamic_cast<Vector<ImageElement>&>(y).read(result,cbegin,cend);\n      }\n\n      double evalL1norm() const\n      {\n        doAssemble(Assembler::VALUE);\n        Scalar value =0;//ass.fL1norm();\n        if(DiscreteBlockTraits<Functional>::anyPresent)\n          value += std::fabs(DiscreteBlockTraits<Functional>::getValue(*fu,x));\n        return value;\n      }\n\n      Assembler const& getValidAssembler() const\n      {\n        doAssemble((Assembler::VALUE | Assembler::RHS | Assembler::MATRIX));\n        return *ass;\n      }\n\n      Functional const& getFunctional() const\n      {\n        return *fu;\n      }\n\n    protected:\n      void addDiscreteRHSBlocks(std::vector<Scalar>& rhs, int rbegin, int rend) const\n      {\n        for(int i=rbegin; i<rend; ++i)\n        {\n          std::vector<Scalar> rhsD;\n          DiscreteBlockTraits<Functional>::getRHSBlock(rhsD,*fu,x,i);\n          if(rhsD.size() > 0)\n          {\n            assert(rhsD.size() == rows(i,i+1));\n            for(int k=rows(rbegin,i), l=0;k<rows(rbegin,i+1);++k, ++l)\n              rhs[k]+=rhsD[l];\n          }\n        }\n      }\n\n      void getDiscreteMatrixBlocks(MatrixAsTriplet<Scalar>& mat, int rbegin, int rend, int cbegin, int cend) const\n      {\n        for(int i=rbegin; i<rend; ++i)\n          for(int j=cbegin; j<cend; ++j)\n          {\n            MatrixAsTriplet<Scalar> matD;\n            DiscreteBlockTraits<Functional>::getMatrixBlock(matD, *fu,x,i,j);\n            matD.shiftIndices(rows(rbegin,i),cols(cbegin,j));\n            mat+=matD;\n          }\n      }\n\n      void doAssemble(int flags) const\n      {\n        int toDoFlag= ((~ass->valid()) & flags);\n        if(toDoFlag!=0) ass->assemble(lin,toDoFlag,nThreads);\n      }\n\n\n      DomainElement x;\n      Functional const* fu;\n      Implementation lin;\n      mutable std::shared_ptr<Assembler> ass;\n      std::unique_ptr<Vector<DomainElement> > xptr;\n    };\n\n    template <class Functional> using ConnectedKaskadeLinearization = ConnectedLinearization<KaskadeLinearization<Functional> >;\n\n    template<class Functional, int stateId=1, int adjointId=2>\n    class NormalStepLinearization : public ConnectedKaskadeLinearization<Functional>\n    {\n      typedef ConnectedKaskadeLinearization<Functional> Base;\n      typedef typename Base::Scalar Scalar;\n      typedef typename Base::Assembler Assembler;\n      typedef typename Base::DomainElement DomainElement;\n      typedef typename Base::ImageElement ImageElement;\n      using Base::nRowBlocks;\n      using Base::nColBlocks;\n    public:\n      NormalStepLinearization() : Base() {}\n\n      /// Creation of a linearization for a functional fu at x_\n      NormalStepLinearization(Functional const& fu, DomainElement const& x) : Base(fu,x) {}\n\n      /// Creation of a linearization for a functional fu at x_\n      NormalStepLinearization(Functional const& fu, DomainElement const& x, std::shared_ptr<Assembler> const& assembler) : Base(fu,x,assembler) {}\n\n      NormalStepLinearization(Base const& other) : Base(other) {}\n\n      /// write blocks of the hessian matrix into mat\n      void getMatrixBlocks(MatrixAsTriplet<Scalar>& mat, int rbegin=0, int rend=-1, int cbegin=0, int cend=-1) const\n      {\n        assignIfNegative(rend,nRowBlocks());\n        assignIfNegative(cend,nColBlocks());\n        if(rbegin==adjointId && rend==adjointId+1 && cbegin==adjointId && cend==adjointId+1) return;\n        this->doAssemble(Assembler::VALUE | Assembler::RHS | Assembler::MATRIX);\n        if(rbegin==stateId && rend==stateId+1 && cbegin==stateId && cend==stateId+1)\n        {\n          mat = this->ass->template get<MatrixAsTriplet<Scalar> >(false,adjointId,adjointId+1,adjointId,adjointId+1);\n          return;\n        }\n\n        if(rbegin<=stateId && rend>stateId && cbegin<=stateId && cend > stateId)\n        {\n          size_t rows0 = 0, cols0 = 0, rows1 = 0, cols1 = 0;\n          MatrixAsTriplet<Scalar> tmp;\n          if(rbegin < stateId)\n          {\n            tmp = this->ass->template get<MatrixAsTriplet<Scalar> >(false,rbegin,stateId,cbegin,cend);\n            rows0 = tmp.nrows();\n            mat += tmp;\n          }\n          if(cbegin < stateId)\n          {\n            tmp = this->ass->template get<MatrixAsTriplet<Scalar> >(false,stateId,stateId+1,cbegin,stateId);\n            cols0 = tmp.ncols();\n            tmp.shiftIndices(rows0,0);\n            mat += tmp;\n          }\n          tmp = this->ass->template get<MatrixAsTriplet<Scalar> >(false,adjointId,adjointId+1,adjointId,adjointId+1);\n          rows1 = tmp.nrows(), cols1 = tmp.ncols();\n          tmp.shiftIndices(rows0,cols0);\n          mat += tmp;\n          if(cend > stateId+1)\n          {\n            tmp = this->ass->template get<MatrixAsTriplet<Scalar> >(false,stateId,stateId+1,stateId+1,cend);\n            tmp.shiftIndices(rows0,cols0+cols1);\n            mat += tmp;\n          }\n          if(rend > stateId+1)\n          {\n            tmp = this->ass->template get<MatrixAsTriplet<Scalar> >(false,stateId+1,rend,cbegin,cend);\n            tmp.shiftIndices(rows0+rows1,0);\n            mat += tmp;\n          }\n\n        }\n        else\n          mat = this->ass->template get<MatrixAsTriplet<Scalar> >(false,rbegin,rend,cbegin,cend);\n\n\n        if(DiscreteBlockTraits<Functional>::anyPresent)\n        {\n          MatrixAsTriplet<Scalar> matD;\n          this->getDiscreteMatrixBlocks(matD,rbegin,rend,cbegin,cend);\n          mat+=matD;\n        }\n      }\n\n      void ddxpy(AbstractFunctionSpaceElement& y, AbstractFunctionSpaceElement const& x, int rbegin=0, int rend=-1, int cbegin=0, int cend=-1) const\n      {\n        assignIfNegative(rend,nRowBlocks());\n        assignIfNegative(cend,nColBlocks());\n        if(rbegin==adjointId && rend==adjointId+1 && cbegin==adjointId && cend==adjointId+1) return;\n        assert(cbegin<=cend);\n        assert(rbegin<=rend);\n        std::vector<Scalar> result, argument;\n        dynamic_cast<Vector<ImageElement> const& >(x).write(argument,cbegin,cend);\n        dynamic_cast<Vector<ImageElement>& >(y).write(result,rbegin,rend);\n        MatrixAsTriplet<Scalar> mat;\n        getMatrixBlocks(mat,rbegin,rend,cbegin,cend);\n        mat.axpy(result, argument);\n        dynamic_cast<Vector<ImageElement>& >(y).read(result,rbegin,rend);\n      }\n\n      void d2axpy(double a, AbstractFunctionSpaceElement& y, AbstractFunctionSpaceElement const& x, int rbegin=0, int rend=-1, int cbegin=0, int cend=-1) const\n      {\n        assignIfNegative(rend,nRowBlocks());\n        assignIfNegative(cend,nColBlocks());\n        if( rbegin == adjointId && rend == adjointId+1 && cbegin == adjointId && cend == adjointId+1 ) return;\n        assert( cbegin <= cend );\n        assert( rbegin <= rend );\n        std::vector<Scalar> result, argument;\n        dynamic_cast<Vector<ImageElement> const&>(x).write(argument,cbegin,cend);\n        dynamic_cast<Vector<ImageElement> const&>(y).write(result,rbegin,rend);\n        MatrixAsTriplet<Scalar> mat;\n        getMatrixBlocks(mat,rbegin,rend,cbegin,cend);\n        mat.axpy(result, argument, a);\n        dynamic_cast<Vector<ImageElement>&>(y).read(result, rbegin, rend);\n      }\n    };\n\n    template<class Functional, int stateId=1, int adjointId=2>\n    class TangentialStepLinearization : public ConnectedKaskadeLinearization<Functional>\n    {\n      typedef ConnectedKaskadeLinearization<Functional> Base;\n      typedef typename Base::Scalar Scalar;\n      typedef typename Base::Assembler Assembler;\n      typedef typename Base::DomainElement DomainElement;\n      typedef typename Base::ImageElement ImageElement;\n      using Base::nRowBlocks;\n      using Base::nColBlocks;\n    public:\n      TangentialStepLinearization() : Base() {}\n\n      /// Creation of a linearization for a functional fu at x_\n      TangentialStepLinearization(Functional const& fu, DomainElement const& x) : Base(fu,x) {}\n\n      /// Creation of a linearization for a functional fu at x_\n      TangentialStepLinearization(Functional const& fu, DomainElement const& x, std::shared_ptr<Assembler> const& assembler) : Base(fu,x,assembler) {}\n\n\n      TangentialStepLinearization(Base const& other) : Base(other) {}\n\n      /// write blocks of the hessian matrix into mat\n      void getMatrixBlocks(MatrixAsTriplet<Scalar>& mat, int rbegin=0, int rend=-1, int cbegin=0, int cend=-1) const\n      {\n        assignIfNegative(rend,nRowBlocks());\n        assignIfNegative(cend,nColBlocks());\n        if(rbegin==adjointId && rend==adjointId+1 && cbegin==adjointId && cend==adjointId+1) return;\n        this->doAssemble(Assembler::VALUE | Assembler::RHS | Assembler::MATRIX);\n\n        if(rend > adjointId && cend > adjointId)\n        {\n          mat = this->ass->template get<MatrixAsTriplet<Scalar> >(false,rbegin,rend-1,cbegin,cend-1);\n          size_t rows = mat.nrows(), cols = mat.ncols();\n          auto tmp = this->ass->template get<MatrixAsTriplet<Scalar> >(false,rend-1,rend,cbegin,cend-1);\n          tmp.shiftIndices(rows,0);\n          mat += tmp;\n          tmp = this->ass->template get<MatrixAsTriplet<Scalar> >(false,rbegin,rend-1,cend-1,cend);\n          tmp.shiftIndices(0,cols);\n          mat += tmp;\n        }\n        else\n          mat = this->ass->template get<MatrixAsTriplet<Scalar> >(false,rbegin,rend,cbegin,cend);\n\n        if(DiscreteBlockTraits<Functional>::anyPresent)\n        {\n          MatrixAsTriplet<Scalar> matD;\n          this->getDiscreteMatrixBlocks(matD,rbegin,rend,cbegin,cend);\n          mat+=matD;\n        }\n      }\n\n      void ddxpy(AbstractFunctionSpaceElement& y, AbstractFunctionSpaceElement const& x, int rbegin=0, int rend=-1, int cbegin=0, int cend=-1) const\n      {\n        assignIfNegative(rend,nRowBlocks());\n        assignIfNegative(cend,nColBlocks());\n        if(rbegin==adjointId && rend==adjointId+1 && cbegin==adjointId && cend==adjointId+1) return;\n        assert(cbegin<=cend);\n        assert(rbegin<=rend);\n        std::vector<Scalar> result, argument;\n        dynamic_cast<Vector<ImageElement> const& >(x).write(argument,cbegin,cend);\n        dynamic_cast<Vector<ImageElement>& >(y).write(result,rbegin,rend);\n        MatrixAsTriplet<Scalar> mat;\n        getMatrixBlocks(mat,rbegin,rend,cbegin,cend);\n        mat.axpy(result, argument);\n        dynamic_cast<Vector<ImageElement>& >(y).read(result,rbegin,rend);\n      }\n\n      void d2axpy(double a, AbstractFunctionSpaceElement& y, AbstractFunctionSpaceElement const& x, int rbegin=0, int rend=-1, int cbegin=0, int cend=-1) const\n      {\n        assignIfNegative(rend,nRowBlocks());\n        assignIfNegative(cend,nColBlocks());\n        if( rbegin == adjointId && rend == adjointId+1 && cbegin == adjointId && cend == adjointId+1 ) return;\n        assert( cbegin <= cend );\n        assert( rbegin <= rend );\n        std::vector<Scalar> result, argument;\n        dynamic_cast<Vector<ImageElement> const&>(x).write(argument,cbegin,cend);\n        dynamic_cast<Vector<ImageElement> const&>(y).write(result,rbegin,rend);\n        MatrixAsTriplet<Scalar> mat;\n        getMatrixBlocks(mat,rbegin,rend,cbegin,cend);\n        mat.axpy(result, argument, a);\n        dynamic_cast<Vector<ImageElement>&>(y).read(result,rbegin,rend);\n      }\n    };\n\n    //template <class Functional, int stateId=1, int adjointId=2> using NormalStepLinearization = ConnectedLinearization<NormalStepKaskadeLinearization<Functional,stateId,adjointId> >;\n    //template <class Functional, int stateId=1, int adjointId=2> using TangentialStepLinearization = ConnectedLinearization<TangentialStepKaskadeLinearization<Functional,stateId,adjointId> >;\n\n  }\n}\n\n#endif /* BRIDGE_HH_ */\n", "meta": {"hexsha": "8c18f7814dbdcb1464a002e6e448ff1c873077c9", "size": 20204, "ext": "hh", "lang": "C++", "max_stars_repo_path": "Kaskade/algorithm/kaskadeBridge.hh", "max_stars_repo_name": "chenzongxiong/streambox", "max_stars_repo_head_hexsha": "76f95780d1bf6c02731e39d8ac73937cea352b95", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2019-07-03T14:03:31.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-19T10:18:49.000Z", "max_issues_repo_path": "Kaskade/algorithm/kaskadeBridge.hh", "max_issues_repo_name": "chenzongxiong/streambox", "max_issues_repo_head_hexsha": "76f95780d1bf6c02731e39d8ac73937cea352b95", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2020-02-17T12:01:31.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-09T22:02:36.000Z", "max_forks_repo_path": "Kaskade/algorithm/kaskadeBridge.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.9287090559, "max_line_length": 192, "alphanum_fraction": 0.6428924965, "num_tokens": 5131, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5964331462646255, "lm_q2_score": 0.5156199157230157, "lm_q1q2_score": 0.30753280861137927}}
{"text": "/**\n * Dumps out a csv file with information on ring hypergraphs\n */\n\n#include <ostream>\n#include <istream>\n#include <iostream>\n#include <chrono>\n#include <sstream>\n#include <vector>\n\n#include <boost/hana.hpp>\n#include <hypergraph/approx.hpp>\n#include <generators/generators.hpp>\n#include <hypergraph/certificate.hpp>\n\nnamespace hana = boost::hana;\n\nstruct InputInfo {\n  BOOST_HANA_DEFINE_STRUCT(\n      InputInfo,\n      (size_t, num_vertices),\n      (size_t, num_edges),\n      (double, radius),\n      (uint64_t, seed),\n      (double, epsilon),\n\n      (size_t, min_cut_value),\n      (size_t, eps_cut_value),\n      (size_t, size_before),\n      (size_t, size_after),\n      (size_t, p1),\n      (size_t, p2)\n  );\n  /*\n  size_t num_vertices;\n  size_t num_edges;\n  double radius;\n  double epsilon;\n  // Suboptimality factor of cut found by running the approximate algorithm\n  double suboptimality_factor;\n  size_t size_before;\n  // Size after sparsifying with the cut value found by the approximate algorithm\n  size_t size_after;\n  // Size of partition 1\n  size_t p1;\n  // Size of partition 2\n  size_t p2;\n   */\n\n  static std::string header() {\n    std::stringstream s;\n    hana::for_each(InputInfo{}, hana::fuse([&s](const auto &name, const auto &member) {\n      s << name.c_str() << \",\";\n    }));\n    std::string str = s.str();\n    return str.substr(0, str.size() - 1);\n  }\n};\n\n// Comma delimit\ntemplate<typename T>\nstd::string comma_delimit(const T &data) {\n  std::stringstream s;\n  hana::for_each(data, hana::fuse([&s](const auto &name, const auto &member) {\n    s << member << \",\";\n  }));\n  std::string str = s.str();\n  return str.substr(0, str.size() - 1);\n}\n\nstd::ostream &operator<<(std::ostream &out, const InputInfo &info) {\n  out << comma_delimit(info) << std::endl;\n  return out;\n}\n\n/*\nstd::istream &operator>>(std::istream &in, InputInfo &info) {\n  std::string line;\n  std::getline(in, line);\n  std::stringstream line_stream(line);\n  auto map = hana::to<hana::map_tag>(info);\n  hana::for_each(info, hana::fuse([&line_stream, &map](auto name, auto member) {\n    std::string field;\n    std::getline(line_stream, field, ',');\n    std::stringstream field_stream(field);\n    decltype(member) m;\n    field_stream >> m;\n    map[name] = m;\n  }));\n\n  info.num_vertices = map[BOOST_HANA_STRING(\"num_vertices\")];\n  info.num_edges = map[BOOST_HANA_STRING(\"num_edges\")];\n\n  return in;\n}\n */\n\nstruct Timer {\n  using TimePoint = decltype(std::chrono::high_resolution_clock::now());\n\n  Timer() {\n    start = std::chrono::high_resolution_clock::now();\n  }\n\n  auto stop() {\n    return std::chrono::duration_cast<std::chrono::milliseconds>(\n        std::chrono::high_resolution_clock::now() - start).count();\n  }\nprivate:\n  TimePoint start;\n};\n\n// Compare just the input parts of InputInfo\nstruct CompareInput {\n  static auto to_tuple(const InputInfo &a) {\n    return std::make_tuple(a.num_vertices, a.num_edges, a.radius);\n  }\n\n  bool operator()(const InputInfo &a, const InputInfo &b) const {\n    return to_tuple(a) < to_tuple(b);\n  }\n};\n\nhypergraphlib::HypergraphCut<size_t> memoized_cut(const InputInfo &info, const hypergraphlib::Hypergraph &hypergraph) {\n  static std::map<InputInfo, hypergraphlib::HypergraphCut<size_t>, CompareInput> cuts;\n\n  auto it = cuts.find(info);\n  if (it == cuts.end()) {\n    hypergraphlib::Hypergraph h(hypergraph);\n    const auto cut = hypergraphlib::MW_min_cut(h);\n    cuts.insert({info, cut});\n    return cut;\n  }\n  return it->second;\n}\n\nint main() {\n  std::vector<InputInfo> infos;\n\n  for (size_t num_vertices = 100; num_vertices <= 500; num_vertices += 25) {\n    for (size_t num_edges = 100; num_edges <= num_vertices * 30; num_edges += 250) {\n      for (double radius = 5; radius <= 90; radius += 5) {\n        for (double epsilon: {0.1, 0.2, 0.4, 0.8, 1., 2., 4., 8., 16., 32., 64., 128.}) {\n          for (int i = 0; i < 10; ++i) {\n            std::mt19937_64 rd;\n            std::uniform_int_distribution<uint64_t> dis;\n            uint64_t seed;\n            InputInfo info = {\n                .num_vertices = num_vertices,\n                .num_edges = num_edges,\n                .radius = radius,\n                .seed = dis(rd),\n                .epsilon = epsilon\n            };\n            infos.emplace_back(std::move(info));\n          }\n        }\n      }\n    }\n  }\n\n  std::cout << InputInfo::header() << std::endl;\n\n  for (auto &info : infos) {\n    RandomRingConstantEdgeHypergraph gen(info.num_vertices, info.num_edges, info.radius, 777);\n    auto[h, _] = gen.generate();\n    // TODO do this before in generate or something\n    h.remove_singleton_and_empty_hyperedges();\n    const hypergraphlib::Hypergraph hypergraph(h);\n\n    const auto cut = memoized_cut(info, hypergraph);\n    hypergraphlib::Hypergraph temp2(hypergraph);\n    const auto eps_cut = hypergraphlib::approximate_minimizer(temp2, info.epsilon);\n    hypergraphlib::KTrimmedCertificate k(hypergraph);\n    auto hypergraph_after = k.certificate(eps_cut.value);\n\n    info.eps_cut_value = eps_cut.value;\n    info.min_cut_value = cut.value;\n    info.size_before = hypergraph.size();\n    info.size_after = hypergraph_after.size();\n    info.p1 = cut.partitions.at(0).size();\n    info.p2 = cut.partitions.at(1).size();\n\n    std::cout << info;\n  }\n}\n", "meta": {"hexsha": "1e363bad5c366844217485ee1f82ab1523945701", "size": 5237, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "scripts/eps.cpp", "max_stars_repo_name": "vsui/hypergraph-k-cut", "max_stars_repo_head_hexsha": "1134ca254fb709bce62a4506c931362d84a06894", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-01-17T07:31:36.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-14T08:36:50.000Z", "max_issues_repo_path": "scripts/eps.cpp", "max_issues_repo_name": "vsui/hypergraph-k-cut", "max_issues_repo_head_hexsha": "1134ca254fb709bce62a4506c931362d84a06894", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "scripts/eps.cpp", "max_forks_repo_name": "vsui/hypergraph-k-cut", "max_forks_repo_head_hexsha": "1134ca254fb709bce62a4506c931362d84a06894", "max_forks_repo_licenses": ["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.8563829787, "max_line_length": 119, "alphanum_fraction": 0.6419705939, "num_tokens": 1415, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5964331462646254, "lm_q2_score": 0.5156199157230156, "lm_q1q2_score": 0.30753280861137916}}
{"text": "/**\n * @file penalty_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_PENALTY_BASED_ALTERNATIVE_ROUTING_IMPL_HPP\n#define BOOST_PENALTY_BASED_ALTERNATIVE_ROUTING_IMPL_HPP\n\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/properties.hpp>\n#include <boost/graph/reverse_graph.hpp>\n#include <boost/property_map/function_property_map.hpp>\n#include <boost/property_map/property_map.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 <functional>\n#include <iostream>\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//                      Penalty algorithm types\n//===----------------------------------------------------------------------===//\n/**\n * A map from edges to the number of time they have been penalized so\n * far.\n *\n * @tparam Edge An edge_descriptor\n */\ntemplate <typename Edge>\nusing PenBoundsMap = std::unordered_map<Edge, int, boost::hash<Edge>>;\n\n/**\n * A map from edges to their weights\n *\n * @tparam Edge An edge_descriptor\n * @tparam Length The edge weight type\n */\ntemplate <typename Edge, typename Length>\nusing WeightMap = std::unordered_map<Edge, Length, boost::hash<Edge>>;\n\n/**\n * A vector for tracking distance of a vertex from the source.\n *\n * The vector must be indexable by the vertex_descriptor, thus its size should\n * be equal to the number of vertices in the graph.\n *\n * @tparam Length The edge weight type.\n */\ntemplate <typename Length> using DistanceMap = std::vector<Length>;\n\n//===----------------------------------------------------------------------===//\n//                      Penalty algorithm classes\n//===----------------------------------------------------------------------===//\n\n/**\n * A functor to return the penalized weight of an edge, to avoid changing\n * the original graph weights.\n *\n * @tparam PMap A Weight Property Map.\n */\ntemplate <typename PMap> class penalty_functor {\npublic:\n  using Edge = typename boost::property_traits<PMap>::key_type;\n  using Length = double;\n\n  /**\n   * Construct a new penalty functor object.\n   *\n   * @tparam EdgeIterator An iterator of the graph edges.\n   * @param weight The weight property map.\n   */\n  penalty_functor(PMap weight)\n      : weight{weight}, penalties{std::make_shared<WeightMap<Edge, Length>>()} {\n  }\n\n  /**\n   * Copy constructor.\n   *\n   * @param other The penalty functor to copy from\n   */\n  penalty_functor(const penalty_functor<PMap> &other)\n      : weight{other.weight}, penalties{other.penalties} {}\n\n  /**\n   * Returns the penalized weight of an edge.\n   *\n   * @param e The query edge.\n   * @return The penalized weight for @p e.\n   */\n  const Length &operator()(const Edge &e) const { return get_or_insert(e); }\n\n  /**\n   * Returns the penalized weight of an edge.\n   *\n   * @param e The query edge.\n   * @return The penalized weight for @p e.\n   */\n  Length &operator[](const Edge &e) { return get_or_insert(e); }\n\n  /**\n   * Returns the penalized weight of an edge.\n   *\n   * @param e The query edge.\n   * @return The penalized weight for @p e.\n   */\n  const Length &operator[](const Edge &e) const { return get_or_insert(e); }\n\n  penalty_functor clone() const {\n    auto pf = *this;\n    pf.penalties = std::make_shared<WeightMap<Edge, Length>>(*penalties);\n    return pf;\n  }\n\nprivate:\n  PMap weight;\n  mutable std::shared_ptr<WeightMap<Edge, Length>> penalties;\n\n  Length &get_or_insert(const Edge &e) const {\n    if (auto search = penalties->find(e); search != penalties->end()) {\n      return search->second;\n    } else {\n      auto [it, ok] = penalties->insert({e, weight[e]});\n      assert(ok && \"[kspwlo::penalty_functor] Could not insert edge weight\");\n      return it->second;\n    }\n  }\n};\n\ntemplate <typename PMap, typename Graph> class reverse_penalty_functor {\npublic:\n  using Edge = typename boost::graph_traits<\n      boost::reverse_graph<Graph>>::edge_descriptor;\n  using Length = double;\n\n  reverse_penalty_functor(penalty_functor<PMap> &penalty, const Graph &G,\n                          const boost::reverse_graph<Graph> &rev_G)\n      : inner_pf{penalty}, G{G}, rev_G{rev_G} {}\n\n  reverse_penalty_functor(reverse_penalty_functor const &other)\n      : inner_pf{other.inner_pf}, 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_pf(forward_edge);\n  }\n\n  Length &operator[](const Edge &e) {\n    auto forward_edge = get_forward_edge(e);\n\n    return inner_pf[forward_edge];\n  }\n\n  const Length &operator[](const Edge &e) const {\n    auto forward_edge = get_forward_edge(e);\n\n    return inner_pf[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  penalty_functor<PMap> &inner_pf;\n  const Graph &G;\n  const boost::reverse_graph<Graph> &rev_G;\n};\n\n//===----------------------------------------------------------------------===//\n//                     Penalty algorithm support routines\n//===----------------------------------------------------------------------===//\n/**\n * Computes the shortest path between two vertices s and t, first\n * from s to t and then from t to s. The distances of each node in the\n * shortest paths are stored in distance_s and distance_t.\n *\n * @tparam Graph A Boost::PropertyGraph having at least one edge\n *               property with tag boost::edge_weight_t.\n * @tparam Vertex A vertex_descriptor\n * @tparam Length The edge weight type.\n * @param G The graph.\n * @param s The source vertex.\n * @param t The target vertex.\n * @param distance_s A map from Vertex to its distance from @p s\n * @param distance_t A map from Vertex to its distance from @p t\n * @return A vector of the edges of the shortest path from s to t.\n *         An empty optional if t is not reachable from s.\n */\ntemplate <typename Graph, 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>>\ndijkstra_shortest_path_two_ways(const Graph &G, Vertex s, Vertex t,\n                                DistanceMap<Length> &distance_s,\n                                DistanceMap<Length> &distance_t) {\n  using namespace boost;\n\n  auto predecessor = std::vector<Vertex>(num_vertices(G), s);\n  auto vertex_id = get(vertex_index, G);\n\n  // Forward step\n  dijkstra_shortest_paths(G, s,\n                          distance_map(&distance_s[0])\n                              .predecessor_map(make_iterator_property_map(\n                                  std::begin(predecessor), vertex_id, s)));\n  auto edge_list = build_edge_list_from_dijkstra(G, s, t, predecessor);\n\n  // Backward step\n  auto rev_G = make_reverse_graph(G);\n  dijkstra_shortest_paths(rev_G, t, distance_map(&distance_t[0]));\n\n  if (exists_path_to<Length>(t, distance_s)) {\n    return std::make_optional(edge_list);\n  } else {\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} // namespace kspwlo_impl\n\n/**\n * Computes the Dijkstra shortest path from s to t using a\n *        penalty_functor to gather edges weight instead of the Graph's weight\n *        property map\n *\n * @tparam Graph A Boost::PropertyGraph having at least one edge\n *               property with tag boost::edge_weight_t.\n * @tparam PMap The graph's weight property map.\n * @tparam Vertex A vertex_descriptor.\n * @tparam Edge An edge_descriptor.\n * @tparam Length The edge weight type.\n * @param G The graph\n * @param s The source vertex\n * @param t The target vertex\n * @param penalty A penalty_functor\n * @return A vector of the edges of the shortest path from s to t.\n *         An empty optional if t is not reachable from s.\n */\ntemplate <typename Graph, typename PMap, 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>>\ndijkstra_shortest_path(const Graph &G, Vertex s, Vertex t,\n                       penalty_functor<PMap> &penalty) {\n  using namespace boost;\n\n  auto predecessor = std::vector<Vertex>(num_vertices(G), s);\n  auto vertex_id = get(vertex_index, G);\n\n  auto weight = make_function_property_map<Edge>(penalty);\n  try {\n    dijkstra_shortest_paths(\n        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 tf) {\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\ntemplate <typename Graph, typename PMap, typename AStarHeuristic,\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>>\nastar_shortest_path(const Graph &G, Vertex s, Vertex t,\n                    penalty_functor<PMap> &penalty,\n                    const AStarHeuristic &heuristic) {\n  using namespace boost;\n  auto predecessor = std::vector<Vertex>(num_vertices(G), s);\n  auto vertex_id = get(vertex_index, G);\n\n  auto weight = make_function_property_map<Edge>(penalty);\n  try {\n    astar_search(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 &tf) {\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 PMap, 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                                     penalty_functor<PMap> &penalty) {\n  using namespace boost;\n\n  auto index = get(vertex_index, 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  auto weight = make_function_property_map<Edge>(penalty);\n\n  auto rev_G = make_reverse_graph(G);\n  auto rev_weight_ = reverse_penalty_functor(penalty, G, rev_G);\n  using RevEdge = typename boost::graph_traits<\n      boost::reverse_graph<Graph>>::edge_descriptor;\n  auto rev_weight = make_function_property_map<RevEdge>(rev_weight_);\n  auto rev_index = get(vertex_index, rev_G);\n\n  try {\n    bidirectional_dijkstra(G, s, t, predecessor, distance, weight, rev_G,\n                           rev_weight, rev_index);\n  } catch (details::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 PMap, 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, penalty_functor<PMap> &)>\nbuild_shortest_path_fn(routing_kernels algorithm, const Graph &, const PMap &) {\n  switch (algorithm) {\n  case routing_kernels::dijkstra:\n    return [](const auto &G, auto s, auto t, auto &penalty) {\n      return dijkstra_shortest_path(G, s, t, penalty);\n    };\n  case routing_kernels::bidirectional_dijkstra:\n    return [](const auto &G, auto s, auto t, auto &penalty) {\n      return bidirectional_dijkstra_shortest_path(G, s, t, penalty);\n    };\n  default:\n    throw std::invalid_argument{\n        \"Invalid algorithm. Only [dijkstra|bidirectional_dijkstra] allowed.\"};\n  }\n}\n\ntemplate <typename Graph, typename PMap, typename AStarHeuristic,\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, penalty_functor<PMap> &)>\nbuild_shortest_path_fn(routing_kernels algorithm, const Graph &, const PMap &,\n                       const AStarHeuristic &heuristic) {\n  switch (algorithm) {\n  case routing_kernels::astar:\n    return [&heuristic](const auto &G, auto s, auto t, auto &penalty) {\n      return astar_shortest_path(G, s, t, penalty, heuristic);\n    };\n  default:\n    throw std::invalid_argument{\"Invalid algorithm. Only [astar] allowed.\"};\n  }\n}\n\n/**\n * Apply penalization step to the candidate path.\n *\n * @pre For each vertex @c v in @p candidate @p distance_s contains the shortest\n *      path distance of @c v from @p s\n * @pre For each vertex @c v in @p candidate @p distance_t contains the shortest\n *      path distance of @c v from @p t\n * @post For each edge @c e in @p candidate, if <tt>penalty_bounds[e] <\n *       bound_limit</tt>, @c e is penalized in @p penalty according to the\n *       following formula: <tt>w(e)_new = w(e) + @p p * w(e)</tt>\n * @post For each edge @c e incoming to a vertex @c u in @p candidate, if\n *       <tt>penalty_bounds[e] < bound_limit</tt>, @c e is penalized in @p\n *       penalty according to the following formula:\n *       <tt>w(e)_new = w(e) + w(e) * (0.1 + @p r * @p distance_t[u] / @p\n *       distance_t[s])</tt>\n * @post For each edge @c e outgoing from a vertex @c v in @p candidate, if\n *       <tt>penalty_bounds[e] < bound_limit</tt>, @c e is penalized in @p\n *       penalty according to the following formula:\n *       <tt>w(e)_new = w(e) + w(e) * (0.1 + @p r * @p distance_s[v] / @p\n *       distance_s[t])</tt>\n *\n * @tparam Graph A Boost::PropertyGraph having at least one edge\n *               property with tag boost::edge_weight_t.\n * @tparam DistanceMap A DistanceMap.\n * @tparam PMap The graph's weight property map.\n * @tparam Vertex A vertex_descriptor.\n * @tparam Edge An edge_descriptor.\n * @tparam Length The edge weight type.\n * @param candidate The candidate path.\n * @param G The graph.\n * @param s The source vertex.\n * @param t The target vertex.\n * @param p The penalty factor for edges in the candidate path.\n * @param r The penalty factor for edges incoming and outgoing to/from vertices\n *          of the candidate path.\n * @param penalty A penalty_functor.\n * @param distance_s A DistanceMap from s.\n * @param distance_t A DistanceMap from t.\n * @param penalty_bounds A PenBoundsMap.\n * @param bound_limit The maximum number of times an edge can be penalized.\n */\ntemplate <typename Graph, typename DistanceMap, typename PMap,\n          typename Vertex = vertex_of_t<Graph>,\n          typename Edge = edge_of_t<Graph>,\n          typename Length = length_of_t<Graph>>\nvoid penalize_candidate_path(const std::vector<Edge> &candidate, const Graph &G,\n                             Vertex s, Vertex t, double p, double r,\n                             penalty_functor<PMap> &penalty,\n                             const DistanceMap &distance_s,\n                             const DistanceMap &distance_t,\n                             PenBoundsMap<Edge> &penalty_bounds,\n                             int bound_limit) {\n  using namespace boost;\n\n  // Keep track of candidate vertices to exclude them from incoming/outgoing\n  // edges update\n  auto candidate_vertices = std::unordered_set<Vertex, boost::hash<Vertex>>{};\n  auto candidate_edges = std::unordered_set<Edge, boost::hash<Edge>>{};\n\n  for (const auto &e : candidate) {\n    candidate_edges.insert(e);\n\n    auto u = source(e, G);\n    auto v = target(e, G);\n    candidate_vertices.insert(u);\n    candidate_vertices.insert(v);\n  }\n\n  for (auto &e : candidate_edges) {\n    auto u = source(e, G);\n    auto v = target(e, G);\n\n    // Check if 'e' is already part of the alternative graph\n    if (auto search = penalty_bounds.find(e);\n        search != std::end(penalty_bounds)) {\n      // If so, penalize only if limit isnt reached\n      auto n_updates = search->second;\n      if (n_updates < bound_limit) {\n        penalty[e] += p * penalty[e];\n        ++penalty_bounds[e];\n      }\n    } else { // Penalize and create a nb_updates counter for e\n      penalty[e] += p * penalty[e];\n      penalty_bounds.insert({e, 1});\n    }\n\n    // Update incoming edges\n    for (auto [it, end] = in_edges(u, G); it != end; ++it) {\n      auto a = source(*it, G);\n\n      // Incoming edge (a, u) is updated only if 'a' is not part of candidate\n      // path\n      if (candidate_vertices.find(a) == std::end(candidate_vertices)) {\n        // Check if '*it' is already part of the alternative graph\n        if (auto search = penalty_bounds.find(*it);\n            search != std::end(penalty_bounds)) {\n          auto n_updates = search->second;\n          // penalize only if limit isnt reached\n          if (n_updates < bound_limit) {\n            auto closeness = distance_t[u] / distance_t[s];\n            auto pen_factor = 0.1 + r * closeness;\n            penalty[*it] += pen_factor * penalty[*it];\n            ++penalty_bounds[*it];\n          }\n        } else {\n          // Else, just update it\n          auto closeness = distance_t[u] / distance_t[s];\n          auto pen_factor = 0.1 + r * closeness;\n          penalty[*it] += pen_factor * penalty[*it];\n        }\n      }\n    }\n\n    // Update outgoing edges\n    for (auto [it, end] = out_edges(v, G); it != end; ++it) {\n      auto b = target(*it, G);\n\n      // Outgoing edge (v, b) is updated only if 'b' is not part of candidate\n      // path\n      if (candidate_vertices.find(b) == std::end(candidate_vertices)) {\n        // Check if '*it' is already part of the alternative graph\n        if (auto search = penalty_bounds.find(*it);\n            search != std::end(penalty_bounds)) {\n          auto n_updates = search->second;\n          // penalize only if limit isnt reached\n          if (n_updates < bound_limit) {\n            auto closeness = distance_s[v] / distance_s[t];\n            auto pen_factor = 0.1 + r * closeness;\n            penalty[*it] += pen_factor * penalty[*it];\n            ++penalty_bounds[*it];\n          }\n        } else {\n          // Else, just update it\n          auto closeness = distance_s[v] / distance_s[t];\n          auto pen_factor = 0.1 + r * closeness;\n          penalty[*it] += pen_factor * penalty[*it];\n        }\n      }\n    }\n  }\n}\n\ntemplate <typename Graph, typename WeightMap, typename MultiPredecessorMap,\n          typename RoutingKernel, typename Terminator,\n          typename Vertex = vertex_of_t<Graph>>\nvoid penalty(const Graph &G, WeightMap const &original_weight,\n             MultiPredecessorMap &predecessors, Vertex s, Vertex t, int k,\n             double theta, double p, double r, int max_nb_updates,\n             int max_nb_steps, RoutingKernel &routing_kernel,\n             Terminator &&terminator) {\n  using namespace boost;\n  using Edge = typename graph_traits<Graph>::edge_descriptor;\n  using Length = typename boost::property_traits<typename boost::property_map<\n      Graph, boost::edge_weight_t>::type>::value_type;\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  // P_LO set of k paths\n  auto resPaths = std::vector<Path<Graph>>{};\n  // Make a local weight map to avoid modifying existing graph.\n  auto pen_fctor = details::penalty_functor{original_weight};\n\n  // Compute shortest path from s to t\n  auto distance_s = std::vector<Length>(num_vertices(G));\n  auto distance_t = std::vector<Length>(num_vertices(G));\n  auto sp = dijkstra_shortest_path_two_ways(G, s, t, distance_s, distance_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  // Initialize map for penalty bounds\n  auto penalty_bounds = std::unordered_map<Edge, int, boost::hash<Edge>>{};\n\n  // Penalize sp edges\n  penalize_candidate_path(*sp, G, s, t, p, r, pen_fctor, distance_s, distance_t,\n                          penalty_bounds, max_nb_updates);\n\n  int step = 0;\n  using Index = std::size_t;\n  while (resPathsEdges.size() < static_cast<Index>(k) && step < max_nb_steps) {\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          \"Penalty terminated before completing due to a Terminator. Please \"\n          \"discard partial output.\"};\n    }\n\n    auto p_tmp = routing_kernel(G, s, t, pen_fctor);\n\n    // Penalize p_tmp edges\n    penalize_candidate_path(*p_tmp, G, s, t, p, r, pen_fctor, distance_s,\n                            distance_t, penalty_bounds, max_nb_updates);\n    ++step;\n\n    // If p_tmp is sufficiently dissimilar to other alternative paths, accept it\n    bool is_valid_path = true;\n    for (const auto &alt_path : resEdges) {\n      if (compute_similarity(*p_tmp, alt_path, original_weight) > theta) {\n        is_valid_path = false;\n        break;\n      }\n    }\n\n    if (is_valid_path) {\n      resPathsEdges.push_back(*p_tmp);\n      resEdges.emplace_back(p_tmp->begin(), p_tmp->end());\n    }\n  }\n\n  // Beforer returning, populate predecessors map\n  fill_multi_predecessor(resPathsEdges.begin(), resPathsEdges.end(), G,\n                         predecessors);\n}\n} // namespace details\n} // namespace arlib\n\n#endif", "meta": {"hexsha": "d070047b688b81939153a281fc19ed064ccd5cbf", "size": 24172, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/arlib/details/penalty_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/penalty_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/penalty_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": 37.1305683564, "max_line_length": 80, "alphanum_fraction": 0.6493877213, "num_tokens": 5771, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5583269943353745, "lm_q2_score": 0.5506073655352404, "lm_q1q2_score": 0.30741895545820963}}
{"text": "#include <iostream>\r\n#include <thread>\r\n#include <chrono>\r\n#include <iostream>\r\n#include <string>\r\n#include <boost/program_options.hpp>\r\n#include \"mqtt/async_client.h\"\r\n\r\nusing namespace std;\r\n\r\nconst string SERVER_ADDRESS { \"tcp://localhost:1883\" };\r\nconst string CLIENT_ID      { \"async_consume\" };\r\nconst string TOPIC          { \"adc/1\" };\r\n\r\nconst int  QOS = 1;\r\n\r\nclass pid_controller {\r\n    public:\r\n    double kp,ki,kd,intcap,outcap_pos,outcap_neg,setpoint;\r\n    double iterm, pterm, dterm;\r\n    double last_error;\r\n    \r\n    pid_controller(){\r\n        kp = 1;\r\n        ki = 0;\r\n        kd = 0;\r\n        intcap = 0;\r\n        outcap_pos = 1.0;\r\n        outcap_neg = 0;\r\n        setpoint = 1;\r\n        iterm = 0;\r\n        last_error = 0;\r\n    }\r\n    \r\n    double operator()(double input){\r\n        double rval;\r\n        double error = input - setpoint;\r\n        pterm = -error * kp;\r\n        iterm += error * ki;\r\n        dterm = kd * (last_error - error);\r\n        last_error = error;\r\n        if(iterm > intcap)\r\n            iterm = intcap;\r\n        if(-iterm > intcap)\r\n            iterm = -intcap;\r\n        rval = pterm + iterm + dterm;\r\n        if(rval > outcap_pos)\r\n            rval = outcap_pos;\r\n        if(rval < outcap_neg)\r\n            rval = outcap_neg;\r\n        return rval;\r\n    }\r\n};\r\n\r\n\r\n/////////////////////////////////////////////////////////////////////////////\r\nint main(int ac, char **av)\r\n{\r\n    namespace po = boost::program_options;\r\n    po::options_description desc(\"Allowed options\");\r\n    desc.add_options()\r\n        (\"help\", \"produce help message\")\r\n        (\"server\",  po::value<std::string>()->default_value(\"localhost\"), \"mqtt server\")\r\n        (\"port\",    po::value<int>()->default_value(1883),\"mqtt port\")\r\n\r\n        (\"pwmtopic\",   po::value<std::string>()->default_value(\"pwm1\"), \"mqtt publish topic for pwm output\")\r\n        (\"pwmtopictopic\",   po::value<std::string>()->default_value(\"pid/pwmtopic\"), \"mqtt subscribe topic to dynamically change pwm output topic\")\r\n        \r\n        (\"sensor\", po::value<std::string>()->default_value(\"adc/1\"), \"mqtt default subscribe topic for temperature sensor\")\r\n        (\"sensortopic\", po::value<std::string>()->default_value(\"sensortopic\"), \"mqtt (sensor topic) (subscribe topic) for temperature sensor e.g. dynamic control of temperature source data\")\r\n        (\"setpointtopic\", po::value<std::string>()->default_value(\"pid/set\"), \"mqtt setpoint topic\")\r\n        \r\n        (\"topic_kp\", po::value<std::string>()->default_value(\"pid/kp\"), \"mqtt subscribe topic for online kp updates\")\r\n        (\"topic_ki\", po::value<std::string>()->default_value(\"pid/ki\"), \"mqtt subscribe topic for online ki updates\")\r\n        (\"topic_kd\", po::value<std::string>()->default_value(\"pid/kd\"), \"mqtt subscribe topic for online kd updates\")\r\n        \r\n        (\"td\",  po::value<int>()->default_value(500), \"time between iterations (integer milliseconds)\")\r\n        (\"kp\",   po::value<double>()->default_value(0.01) , \"kp\")\r\n        (\"ki\",   po::value<double>()->default_value(-.0001), \"ki\")\r\n        (\"kd\",   po::value<double>()->default_value(0.1) , \"kd\")\r\n        (\"intcap\",   po::value<double>()->default_value(0.1) , \"integral term cap (+-)\")\r\n\r\n        (\"verbose\", \"report to stdout\")\r\n        (\"mqtt_log\", \"send debug log to mqtt\")\r\n        (\"csv\", \"csv readout to stdout\")\r\n\r\n    ;\r\n\r\n    po::variables_map vm;\r\n    po::store(po::parse_command_line(ac, av, desc), vm);\r\n    po::notify(vm);    \r\n\r\n    if (vm.count(\"help\")) {\r\n        std::cout << desc << \"\\n\";\r\n        return 1;\r\n    }\r\n\r\n    bool verbose=false;\r\n    if (vm.count(\"verbose\")){\r\n        std::cout << \"verbose set\\n\";\r\n        verbose = true;\r\n    }\r\n    \r\n    bool mqtt_log=false;\r\n    if (vm.count(\"mqtt_log\")){\r\n        std::cout << \"mqtt_log set\\n\";\r\n        mqtt_log = true;\r\n    }\r\n    \r\n    bool csv=false;\r\n    if (vm.count(\"verbose\")){\r\n        std::cout << \"verbose set\\n\";\r\n        verbose = true;\r\n    }\r\n   \r\n    int port = vm[\"port\"].as<int>();\r\n    std::string server = vm[\"server\"].as<std::string>();\r\n    \r\n    int td = vm[\"td\"].as<int>();\r\n    double kp = vm[\"kp\"].as<double>();\r\n    double ki = vm[\"ki\"].as<double>();\r\n    double kd = vm[\"kd\"].as<double>();\r\n    double intcap = vm[\"intcap\"].as<double>();\r\n    \r\n    std::string pwmtopic = vm[\"pwmtopic\"].as<std::string>();\r\n\r\n    std::string sensortopic = vm[\"sensor\"].as<std::string>();\r\n    std::string sensortopictopic = vm[\"sensortopic\"].as<std::string>();\r\n    std::string pwmtopictopic = vm[\"pwmtopictopic\"].as<std::string>();\r\n    std::string setpointtopic = vm[\"setpointtopic\"].as<std::string>();\r\n    std::string topic_kp = vm[\"topic_kp\"].as<std::string>();\r\n    std::string topic_ki = vm[\"topic_ki\"].as<std::string>();\r\n    std::string topic_kd = vm[\"topic_kd\"].as<std::string>();\r\n       \r\n    std::cout << \"done parsing command line\\n\" << std::flush;\r\n    std::cout << \"\\ntp= \" << kp;\r\n    std::cout << \"\\nti= \" << ki;\r\n    std::cout << \"\\ntd= \" << kd;\r\n    std::cout << \"\\nintcap= \" << intcap;\r\n    std::cout << \"\\npwmtopic= \" << pwmtopic;\r\n    std::cout << \"\\nsetpointtopic= \" << setpointtopic;\r\n    std::cout << \"\\nsensortopic= \" << sensortopic;\r\n    std::cout << \"\\nsensortopictopic= \" << sensortopictopic;\r\n    std::cout << \"\\npwmtopictopic= \" << pwmtopictopic;\r\n    std::cout << \"\\ntopic_kp= \" << topic_kp;\r\n    std::cout << \"\\ntopic_ki= \" << topic_ki;\r\n    std::cout << \"\\ntopic_kd= \" << topic_kd;\r\n    \r\n    pid_controller pid{};\r\n    pid.kp = kp;\r\n    pid.ki = ki;\r\n    pid.kd = kd;\r\n    pid.intcap = intcap;\r\n    pid.outcap_neg = 0;\r\n    pid.outcap_pos = 1.0;\r\n    \r\n    \r\n    // mqtt\r\n    const int    QOS = 1;\r\n    const auto PERIOD = std::chrono::seconds(5);\r\n    const int MAX_BUFFERED_MSGS = 120;  // 120 * 5sec => 10min off-line buffering\r\n    const std::string PERSIST_DIR { \"data-persist\" };\r\n\r\n    std::string address = std::string(\"tcp://\") + server + std::string(\":\") + std::to_string(port);\r\n    mqtt::async_client cli(address, \"\", MAX_BUFFERED_MSGS, PERSIST_DIR);\r\n    \r\n    mqtt::connect_options connOpts;\r\n    connOpts.set_keep_alive_interval(MAX_BUFFERED_MSGS * PERIOD);\r\n    connOpts.set_clean_session(true);\r\n    connOpts.set_automatic_reconnect(true);\r\n\r\n    try {\r\n        std::cout << \"Connecting to server '\" << address << \"'...\" << std::flush;\r\n        cli.connect(connOpts)->wait();\r\n        cli.start_consuming();\r\n        std::cout << \"OK\\n\" << std::endl;\r\n    }\r\n    catch (const mqtt::exception& exc) {\r\n        cerr << exc.what() << endl;\r\n        return 1;\r\n    }\r\n\r\n    // mqtt publish topics\r\n    shared_ptr<mqtt::topic> pwm;\r\n    pwm = make_shared<mqtt::topic>(cli, pwmtopic, QOS, true);\r\n    \r\n    // mqtt_log\r\n    shared_ptr<mqtt::topic> mqtt_log_sender;\r\n    mqtt_log_sender = make_shared<mqtt::topic>(cli, \"log/pwm\", QOS, true);\r\n    \r\n    \r\n    // mqtt consume topics\r\n    cli.start_consuming();\r\n    std::cout << \"Subscribing to topic[s]\\n\";\r\n    cli.subscribe(sensortopic, QOS)->wait();\r\n    cli.subscribe(setpointtopic, QOS)->wait();\r\n    cli.subscribe(sensortopictopic, QOS)->wait();\r\n    cli.subscribe(pwmtopictopic, QOS)->wait();\r\n    cli.subscribe(topic_kp, QOS)->wait();\r\n    cli.subscribe(topic_ki, QOS)->wait();\r\n    cli.subscribe(topic_kd, QOS)->wait();\r\n\r\n    mqtt::const_message_ptr mqtt_msg;\r\n    \r\n\r\n    \r\n    \r\n    \r\n    // Consume messages\r\n    \r\n    \r\n    while (true) {\r\n        double input_val = 0;\r\n        double outval = 0;\r\n        while(cli.try_consume_message(&mqtt_msg)){\r\n            std::string topic = mqtt_msg->get_topic();\r\n            std::string payload = mqtt_msg->to_string();\r\n            //std::cout << \"\\n\" << topic << \": \" << payload;\r\n            if(topic == sensortopic){\r\n                input_val = std::stod(payload);\r\n                continue;\r\n            }\r\n            if(topic == sensortopictopic){\r\n                std::cout << \"\\nSwitching to sensor topic: \" << payload;\r\n                cli.unsubscribe(sensortopic);\r\n                sensortopic = payload;\r\n                cli.subscribe(sensortopic, QOS)->wait();\r\n                continue;\r\n            }            \r\n            if(topic == pwmtopictopic){\r\n                std::cout << \"\\nSwitching to PWM output topic: \" << payload;\r\n                pwm = make_shared<mqtt::topic>(cli, payload, QOS, true);\r\n                continue;\r\n            }\r\n            if(topic == topic_kp){\r\n                std::cout << \"\\nReceived kp update: \" << payload;\r\n                pid.kp = std::stod(payload);\r\n                continue;\r\n            }           \r\n            if(topic == setpointtopic){\r\n                std::cout << \"\\nReceived setpointtopic update: \" << payload;\r\n                pid.setpoint = std::stod(payload);\r\n                continue;\r\n            }\r\n            if(topic == topic_ki){\r\n                std::cout << \"\\nReceived ki update: \" << payload;\r\n                pid.ki = std::stod(payload);\r\n                pid.iterm = 0;\r\n                continue;\r\n            }\r\n            if(topic == topic_kd){\r\n                std::cout << \"\\nReceived kd update: \" << payload;\r\n                pid.kd = std::stod(payload);\r\n                continue;\r\n            }\r\n        }\r\n        outval = pid(input_val);\r\n        pwm->publish(std::to_string(outval));\r\n        mqtt_log_sender->publish(std::string(\"pid.pterm \") + std::to_string(pid.pterm));\r\n        mqtt_log_sender->publish(std::string(\"pid.iterm \") + std::to_string(pid.iterm));\r\n        mqtt_log_sender->publish(std::string(\"pid.dterm \") + std::to_string(pid.dterm));\r\n        //\r\n        this_thread::sleep_for(chrono::milliseconds(td));\r\n    }\r\n\r\n    // Disconnect\r\n\r\n    cout << \"\\nShutting down and disconnecting from the MQTT server...\" << flush;\r\n    cli.unsubscribe(TOPIC)->wait();\r\n    cli.stop_consuming();\r\n    cli.disconnect()->wait();\r\n    cout << \"OK\" << endl;\r\n\r\n\r\n    return 0;\r\n}\r\n", "meta": {"hexsha": "c2762b62b387c56b4897cce73f6510646026279e", "size": 9844, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "mqtt_pid_pwm.cpp", "max_stars_repo_name": "martinsah/mqtt_pid", "max_stars_repo_head_hexsha": "fc06f73e34383a51f38889118914a6170b1392f4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "mqtt_pid_pwm.cpp", "max_issues_repo_name": "martinsah/mqtt_pid", "max_issues_repo_head_hexsha": "fc06f73e34383a51f38889118914a6170b1392f4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "mqtt_pid_pwm.cpp", "max_forks_repo_name": "martinsah/mqtt_pid", "max_forks_repo_head_hexsha": "fc06f73e34383a51f38889118914a6170b1392f4", "max_forks_repo_licenses": ["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.5379061372, "max_line_length": 192, "alphanum_fraction": 0.5364689151, "num_tokens": 2489, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.5583269943353744, "lm_q1q2_score": 0.3074189554582096}}
{"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 \"ompl/util/RandomNumbers.h\"\n#include \"ompl/util/Exception.h\"\n#include \"ompl/util/Console.h\"\n#include <boost/random/lagged_fibonacci.hpp>\n#include <boost/random/uniform_int.hpp>\n#include <boost/thread/mutex.hpp>\n#include <boost/thread/once.hpp>\n#include <boost/scoped_ptr.hpp>\n#include <boost/date_time/posix_time/posix_time.hpp>\n#include <boost/math/constants/constants.hpp>\n\n/// @cond IGNORE\nnamespace\n{\n    /// We use a different random number generator for the seeds of the\n    /// other random generators. The root seed is from the number of\n    /// nano-seconds in the current time, or given by the user.\n    class RNGSeedGenerator\n    {\n    public:\n        RNGSeedGenerator() :\n            someSeedsGenerated_(false),\n            firstSeed_((boost::uint32_t)(boost::posix_time::microsec_clock::universal_time() -\n                boost::posix_time::ptime(boost::date_time::min_date_time)).total_microseconds()),\n            sGen_(firstSeed_),\n            sDist_(1, 1000000000),\n            s_(sGen_, sDist_)\n        {\n        }\n\n        boost::uint32_t firstSeed()\n        {\n            boost::mutex::scoped_lock slock(rngMutex_);\n            return firstSeed_;\n        }\n\n        void setSeed(boost::uint32_t seed)\n        {\n            boost::mutex::scoped_lock slock(rngMutex_);\n            if (seed > 0)\n            {\n                if (someSeedsGenerated_)\n                {\n                    OMPL_ERROR(\"Random number generation already started. Changing seed now will not lead to deterministic sampling.\");\n                }\n                else\n                {\n                    // In this case, since no seeds have been generated yet, so we remember this seed as the first one.\n                    firstSeed_ = seed;\n                }\n            }\n            else\n            {\n                if (someSeedsGenerated_)\n                {\n                    OMPL_WARN(\"Random generator seed cannot be 0. Ignoring seed.\");\n                    return;\n                }\n                else\n                {\n                    OMPL_WARN(\"Random generator seed cannot be 0. Using 1 instead.\");\n                    seed = 1;\n                }\n            }\n            sGen_.seed(seed);\n        }\n\n        boost::uint32_t nextSeed()\n        {\n            boost::mutex::scoped_lock slock(rngMutex_);\n            someSeedsGenerated_ = true;\n            return s_();\n        }\n\n    private:\n        bool                       someSeedsGenerated_;\n        boost::uint32_t            firstSeed_;\n        boost::mutex               rngMutex_;\n        boost::lagged_fibonacci607 sGen_;\n        boost::uniform_int<>       sDist_;\n        boost::variate_generator<boost::lagged_fibonacci607&, boost::uniform_int<> > s_;\n    };\n\n    static boost::once_flag g_once = BOOST_ONCE_INIT;\n    static boost::scoped_ptr<RNGSeedGenerator> g_RNGSeedGenerator;\n\n    void initRNGSeedGenerator()\n    {\n        g_RNGSeedGenerator.reset(new RNGSeedGenerator());\n    }\n\n    RNGSeedGenerator& getRNGSeedGenerator()\n    {\n        boost::call_once(&initRNGSeedGenerator, g_once);\n        return *g_RNGSeedGenerator;\n    }\n}  // namespace\n/// @endcond\n\nboost::uint32_t ompl::RNG::getSeed()\n{\n    return getRNGSeedGenerator().firstSeed();\n}\n\nvoid ompl::RNG::setSeed(boost::uint32_t seed)\n{\n    getRNGSeedGenerator().setSeed(seed);\n}\n\nompl::RNG::RNG() :\n    generator_(getRNGSeedGenerator().nextSeed()),\n    uniDist_(0, 1),\n    normalDist_(0, 1),\n    uni_(generator_, uniDist_),\n    normal_(generator_, normalDist_)\n{\n}\n\ndouble ompl::RNG::halfNormalReal(double r_min, double r_max, double focus)\n{\n    assert(r_min <= r_max);\n\n    const double mean = r_max - r_min;\n    double       v    = gaussian(mean, mean/focus);\n\n    if (v > mean) v = 2.0 * mean - v;\n    double r = v >= 0.0 ? v + r_min : r_min;\n    return r > r_max ? r_max : r;\n}\n\nint ompl::RNG::halfNormalInt(int r_min, int r_max, double focus)\n{\n    int r = (int)floor(halfNormalReal((double)r_min, (double)(r_max) + 1.0, focus));\n    return (r > r_max) ? r_max : r;\n}\n\n// From: \"Uniform Random Rotations\", Ken Shoemake, Graphics Gems III,\n//       pg. 124-132\nvoid ompl::RNG::quaternion(double value[4])\n{\n    double x0 = uni_();\n    double r1 = sqrt(1.0 - x0), r2 = sqrt(x0);\n    double t1 = 2.0 * boost::math::constants::pi<double>() * uni_(), t2 = 2.0 * boost::math::constants::pi<double>() * uni_();\n    double c1 = cos(t1), s1 = sin(t1);\n    double c2 = cos(t2), s2 = sin(t2);\n    value[0] = s1 * r1;\n    value[1] = c1 * r1;\n    value[2] = s2 * r2;\n    value[3] = c2 * r2;\n}\n\n// From Effective Sampling and Distance Metrics for 3D Rigid Body Path Planning, by James Kuffner, ICRA 2004\nvoid ompl::RNG::eulerRPY(double value[3])\n{\n    value[0] = boost::math::constants::pi<double>() * (-2.0 * uni_() + 1.0);\n    value[1] = acos(1.0 - 2.0 * uni_()) - boost::math::constants::pi<double>() / 2.0;\n    value[2] = boost::math::constants::pi<double>() * (-2.0 * uni_() + 1.0);\n}\n", "meta": {"hexsha": "8306a3eb02d044be5bd40cdf3e5f4feb142f8d64", "size": 6731, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/ompl/util/src/RandomNumbers.cpp", "max_stars_repo_name": "jmainpri/ompl", "max_stars_repo_head_hexsha": "6f7445180aa787806055ded249c96e1266ee9a99", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2018-08-10T18:11:35.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-06T00:33:13.000Z", "max_issues_repo_path": "src/ompl/util/src/RandomNumbers.cpp", "max_issues_repo_name": "jmainpri/ompl", "max_issues_repo_head_hexsha": "6f7445180aa787806055ded249c96e1266ee9a99", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_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/util/src/RandomNumbers.cpp", "max_forks_repo_name": "jmainpri/ompl", "max_forks_repo_head_hexsha": "6f7445180aa787806055ded249c96e1266ee9a99", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-08-10T18:11:36.000Z", "max_forks_repo_forks_event_max_datetime": "2018-08-10T18:11:36.000Z", "avg_line_length": 34.5179487179, "max_line_length": 135, "alphanum_fraction": 0.6092705393, "num_tokens": 1668, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5583269943353744, "lm_q2_score": 0.5506073655352404, "lm_q1q2_score": 0.3074189554582096}}
{"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 lexicographic.hpp\n *\n * @brief Find lexicographically smallest and largest solutions\n *\n * Based on Knuth TAOCP Exercise 7.2.2.2-109.\n *\n * @author Mathias Soeken\n * @since  2.3\n */\n\n#ifndef LEXICOGRAPHIC_SAT_HPP\n#define LEXICOGRAPHIC_SAT_HPP\n\n#include <exception>\n#include <iostream>\n#include <vector>\n\n#include <boost/dynamic_bitset.hpp>\n\n#include <core/utils/range_utils.hpp>\n#include <classical/sat/sat_solver.hpp>\n#include <classical/sat/utils/visit_solutions.hpp>\n\nnamespace cirkit\n{\n\nclass unsat_exception : public std::exception\n{\n  virtual const char * what() const throw()\n  {\n    return \"Solution is UNSAT\";\n  }\n};\n\ntemplate <typename Solver>\nboost::dynamic_bitset<>\nlexicographic_solution( Solver& solver, const std::vector<int>& vars,\n                        const std::vector<int>& assumptions, bool smallest,\n                        const properties::ptr& settings,\n                        const properties::ptr& statistics )\n{\n  auto runtime   = 0.0;\n  auto sat_calls = 0u;\n  auto clauses   = 0u;\n\n  /* F1. [Initialize.] */\n  solver_execution_statistics stats;\n  auto result = solve( solver, stats, assumptions );\n  runtime += stats.runtime;\n  clauses = stats.num_clauses;\n  ++sat_calls;\n\n  if ( result == boost::none )\n  {\n    throw unsat_exception();\n  }\n\n  auto ys = extract_solution( result, vars );\n\n  auto d_iter = std::string::npos;\n\n  while ( true )\n  {\n    /* F2. [Advance d.] */\n    std::string s;\n    to_string( ys, s );\n    if ( smallest )\n    {\n      d_iter = s.find( \"1\", d_iter + 1 );\n    }\n    else\n    {\n      d_iter = s.find( \"0\", d_iter + 1 );\n    }\n\n    /* F3. [Done?] */\n    if ( d_iter == std::string::npos )\n    {\n      set( statistics, \"runtime\", runtime );\n      set( statistics, \"sat_calls\", sat_calls );\n      set( statistics, \"num_clauses\", clauses );\n      return ys;\n    }\n\n    unsigned d = s.size() - d_iter - 1;\n\n    /* F4. [Try for smaller/larger.] */\n    auto local_assumptions = assumptions;\n    for ( auto j = vars.size() - 1; j > d; --j )\n    {\n      local_assumptions.push_back( ys[j] ? vars[j] : -vars[j] );\n    }\n    local_assumptions.push_back( smallest ? -vars[d] : vars[d] );\n\n    result = solve( solver, stats, local_assumptions );\n    runtime += stats.runtime;\n    ++sat_calls;\n    if ( result != boost::none )\n    {\n      ys = extract_solution( result, vars );\n    }\n  }\n}\n\ntemplate<typename Solver>\nboost::dynamic_bitset<> lexicographic_smallest_solution( Solver& solver, const std::vector<int>& vars,\n                                                         const std::vector<int>& assumptions = std::vector<int>(),\n                                                         const properties::ptr& settings = properties::ptr(),\n                                                         const properties::ptr& statistics = properties::ptr() )\n{\n  return lexicographic_solution( solver, vars, assumptions, true, settings, statistics );\n}\n\ntemplate<typename Solver>\nboost::dynamic_bitset<> lexicographic_largest_solution( Solver& solver, const std::vector<int>& vars,\n                                                        const std::vector<int>& assumptions = std::vector<int>(),\n                                                        const properties::ptr& settings = properties::ptr(),\n                                                        const properties::ptr& statistics = properties::ptr() )\n{\n  return lexicographic_solution( solver, vars, assumptions, false, settings, statistics );\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": "af92bc4a43721ddecc4823f31e5062f67d7328b9", "size": 4814, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/classical/sat/utils/lexicographic.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/sat/utils/lexicographic.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/sat/utils/lexicographic.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": 30.2767295597, "max_line_length": 114, "alphanum_fraction": 0.6265060241, "num_tokens": 1129, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5583269796369905, "lm_q2_score": 0.5506073655352404, "lm_q1q2_score": 0.30741894736517117}}
{"text": "/*\n Copyright (C) 2017 Sascha Meiers\n Distributed under the MIT software license, see the accompanying\n file LICENSE.md or http://www.opensource.org/licenses/mit-license.php.\n */\n\n#ifndef simulate_hpp\n#define simulate_hpp\n\n\n#include <iostream>\n#include <vector>\n#include <random>\n#include <utility>\n#include <chrono>\n#include <unordered_map>\n\n//#include <boost/math/distributions/negative_binomial.hpp>\n#include <boost/multiprecision/random.hpp>\n#include <boost/program_options/cmdline.hpp>\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/filesystem.hpp>\n\n#include \"version.hpp\"\n#include \"program_options.hpp\"\n#include \"intervals.hpp\"\n#include \"counter.hpp\"\n#include \"iocounts.hpp\"\n\n/**\n * @file\n * @defgroup simulation Simulation of Strand-seq data\n *\n * Summary of how Strand-seq data simulation works\n *\n * ## Strand-seq simulation\n *\n * The simulation of a single cell contains of three steps:\n *\n *   1. Sample basic counts for both haplotypes from a negative binomial distribution\n *   2. Insert SV according to the user specificaitons onto one of the haplotypes.\n *   3. Render cell as WW,WC or CC, potentially including SCEs\n *\n * ### 1: Basic counts for a cell\n * First, we randomly select a mean coverage (\\f$c\\f$) between `minCoverage` and\n * `maxCoverage` (user-specified) from a uniform distribution.\n *\n * Internally, a simulated cell is represented by two haplotypes (`h1`, `h2`), \n * which both have reads on the main strand (I call it *plus*), and a few \n * abnormal reads that are flipped in orientation (i.e. on the *minus* strand). \n *\n *   * *plus* reads are sampled from a negative binomial with parameters \\f$p\\f$\n *     (user-specified) and \\f$n = c/2 * p/(1-p)\\f$\n *   * *minus* reads are sampled from a zero-inflated geometric distribution:\n *     with probability \\f$1-\\alpha\\f$ the bin gets 0 reads, otherwise the read\n *     number is sampled from a geometric distribution\n *\n * ### 2: Insertion of SVs\n * SVs are specified in a config file and their start and end positions do **not\n * need to align with bins**.\n *\n * SVs are introduced by changing the *plus* and *minus* counts according to \n * what you would expect from an SV. This can be either done for a single\n * haplotype (heterozygous) or both haplotypes (homozygous). Below the changes\n * to the strands are listed in detail\n *\n * SV type         | Haplotype *plus* counts | Haplotype *minus* counts\n * ---             | ---                     | ---\n * deletion  *HET* / *HOM*)     | set to 0                | no change\n * duplication (*HET* / *HOM*)  | multiply by 2           | no change\n * inversion (*HET* / *HOM*)    | switch with *minus*     | switch with *plus*\n * inverted duplication (*HET*) | no change               | set to *plus*\n * false_del (*HOM*)            | divide by 2             | no change\n *\n * > For now, heterozygous SV are **always introduced on haplotype 1**. In *HET*\n * > SVs the aforementioned changes are applied only to haplotype 1, in *HOM*\n * > SVs to both haplotypes.\n *\n * The changes are applied to all bins involved in the SV. However, if a bin is\n * only involved partially, the rule is applied only to a fraction of the\n * counts.\n *\n *\n * ### 3: Render cells\n *\n * At the last step, haplotypes are \"inherited\" as either Watson or Crick\n * strands. This is randomly chosen for each chromosome so that on average we\n * will obtain a 25:50:25 ratio of WW:WC:CC chromosomes.\n */\n\n\n\nnamespace simulator {\n\n\nusing interval::Interval;\nusing count::TGenomeCounts;\nusing count::Counter;\n\n\n/**\n * Save read counts of a single bin for 2 haplotypes, separated by correct\n * strand (*plus*) and flipped strand (*minus*).\n *\n * @ingroup simulation\n */\nstruct HaploCount {\n    unsigned h1_plus, h1_minus, h2_plus, h2_minus;\n    HaploCount() : h1_plus(0), h1_minus(0), h2_plus(0), h2_minus(0)\n    {}\n};\n\n/**\n * @ingroup simulation\n */\nenum SV_type {\n    het_inv,\n    hom_inv,\n    het_del,\n    hom_del,\n    het_dup,\n    hom_dup,\n    inv_dup,\n    false_del\n};\n    std::string SV_type_to_string(SV_type x) {\n        switch(x) {\n            case het_inv: return (\"het_inv\");\n            case hom_inv: return (\"hom_inv\");\n            case het_del: return (\"het_del\");\n            case hom_del: return (\"hom_del\");\n            case het_dup: return (\"het_dup\");\n            case hom_dup: return (\"hom_dup\");\n            case inv_dup: return (\"inv_dup\");\n            case false_del: return (\"false_del\");\n        }\n        return (\"?\");\n    }\n\n/**\n * @ingroup simulation\n */\nstruct SV {\n    Interval where;\n    SV_type type;\n    float vaf;\n    SV(Interval const & intvl, SV_type const & type) :\n        where(intvl), type(type), vaf(1)\n    {}\n    SV(Interval const & intvl, SV_type const & type, float vaf) :\n        where(intvl), type(type), vaf(vaf)\n    {}\n};\n\n\ntypedef std::vector<HaploCount> THapCount;\ntypedef std::vector<std::string> THapType;\n\nstruct phased_counts {\n    uint8_t h1_w;\n    uint8_t h1_c;\n    uint8_t h2_w;\n    uint8_t h2_c;\n};\n\n/**\n * Turn the list of HaploCount information into Strand-seq data.\n * @ingroup simulation\n *\n * Initially we decide for each haplotype on which strand (W or C) it is going\n * to be inherited. Then, while traversing along the chromosome, there is a \n * small chance in every bin that these states change --> this is an SCE.\n *\n * **Update**: Now this function also simulates phased reads for both\n * haplotypes, which are drawn from a binomial distribution using `phased_frac`\n * as a probability.\n *\n * @param hapls Vector of haplotypes (THapl) for each cell, which shall be written as W/C counts.\n * @param chrom_map Chromosome boarders\n * @param sce_prob Probabiliy per bin to change strands\n * @param strand_states Vector of inherited strand states. Note that `Interval`s\n *        get mis-used by inputting bin numbers instead of chromosomal positions\n * @param phases Empty vector of `phased_counts` which will be filled to the\n *        same size as the returned `TGenomeCounts` with counts of haplotypes\n *        H1 and H2 on Watson and Crick strands. This simulates phase data.\n * @param phased_frac Fraction of reads that can be phased (used in binomial\n *        distribution).\n * @return Final Watson/Crick counts that can be plotted.\n */\ntemplate <typename TRandomDev>\nTGenomeCounts render_cell(THapCount const & hapls,\n                          std::vector<int32_t> const & chrom_map,\n                          float sce_prob,\n                          std::vector<std::pair<Interval, std::string>> & strand_states,\n                          std::vector<phased_counts> & phases,\n                          TRandomDev & rd_gen,\n                          float phased_frac = 0.1)\n{\n    std::uniform_real_distribution<> rd_unif(0,1);\n\n    // Final counts to be written\n    TGenomeCounts counts(chrom_map.back());\n    phases.resize(chrom_map.back());\n\n    // Go through all chromosomes\n    for (int32_t chrom = 0; chrom<chrom_map.size()-1; ++chrom)\n    {\n        if (chrom_map[chrom+1] - chrom_map[chrom] < 1) continue;\n\n        // strand states for both haplotypes: true = Watson, false = Crick\n        // Initially, choose states with equal prob.\n        bool W_h1 = rd_unif(rd_gen) < 0.5;\n        bool W_h2 = rd_unif(rd_gen) < 0.5;\n        std::string state = std::string(W_h1?\"W\":\"C\") + std::string(W_h2?\"W\":\"C\");\n\n        // Iterate over bins\n        unsigned start_bin = chrom_map[chrom];\n        for(unsigned bin = chrom_map[chrom]; bin < chrom_map[chrom+1]; ++bin)\n        {\n            // Small chance of an SCE:\n            if(bin > chrom_map[chrom] && rd_unif(rd_gen) < sce_prob)\n            {\n                // Write down interval\n                strand_states.push_back(std::make_pair(Interval(chrom, start_bin, bin-1), state));\n                start_bin = bin;\n\n                // change the state of one haplotype\n                if (rd_unif(rd_gen) < 0.5) W_h1 = !W_h1;\n                else                       W_h2 = !W_h2;\n                state = std::string(W_h1?\"W\":\"C\") + std::string(W_h2?\"W\":\"C\");\n            }\n\n            // Fill counts\n            counts[bin].watson_count = (W_h1  ? hapls[bin].h1_plus : hapls[bin].h1_minus) +\n                                       (W_h2  ? hapls[bin].h2_plus : hapls[bin].h2_minus);\n            counts[bin].crick_count  = (!W_h1 ? hapls[bin].h1_plus : hapls[bin].h1_minus) +\n                                       (!W_h2 ? hapls[bin].h2_plus : hapls[bin].h2_minus);\n\n            // Simulate phased reads (for each read there is a small chance to be phased)\n            if (W_h1) {\n                phases[bin].h1_w = std::binomial_distribution<>(hapls[bin].h1_plus, phased_frac)(rd_gen);\n                phases[bin].h1_c = std::binomial_distribution<>(hapls[bin].h1_minus, phased_frac)(rd_gen);\n            } else {\n                phases[bin].h1_c = std::binomial_distribution<>(hapls[bin].h1_plus, phased_frac)(rd_gen);\n                phases[bin].h1_w = std::binomial_distribution<>(hapls[bin].h1_minus, phased_frac)(rd_gen);\n            }\n            if (W_h2) {\n                phases[bin].h2_w = std::binomial_distribution<>(hapls[bin].h2_plus, phased_frac)(rd_gen);\n                phases[bin].h2_c = std::binomial_distribution<>(hapls[bin].h2_minus, phased_frac)(rd_gen);\n            } else {\n                phases[bin].h2_c = std::binomial_distribution<>(hapls[bin].h2_plus, phased_frac)(rd_gen);\n                phases[bin].h2_w = std::binomial_distribution<>(hapls[bin].h2_minus, phased_frac)(rd_gen);\n            }\n        }\n\n        // write down interval\n        strand_states.push_back(std::make_pair(Interval(chrom, start_bin, chrom_map[chrom+1]-1), state));\n    }\n    return counts;\n}\n\n\n\n\n/** (Partially) flip haplotype counts according to a certail SV type\n *\n * For a het inversion for example, plus and minus on h1 are exchanged.\n * If a breakpoint of the SV does not perfectly align with bin boundaries,\n * you can specify an additional fraction f [0,1] to say that the flip should\n * only occur in f% of the bin.\n *\n * @param h Haplotype of a single bin (containing 4 counts).\n * @param sv_type Type of SV, only a few are possible.\n * @param f Apply the flip only to a portion of this bin.\n */\ninline void flip_strand(HaploCount & h, SV_type sv_type, float f = 1)\n{\n    HaploCount x = h;\n    switch(sv_type) {\n        case het_inv:\n            h.h1_plus  = (1-f) * h.h1_plus  + f * x.h1_minus;\n            h.h1_minus = (1-f) * h.h1_minus + f * x.h1_plus;\n            break;\n        case hom_inv:\n            h.h1_plus  = (1-f) * h.h1_plus  + f * x.h1_minus;\n            h.h1_minus = (1-f) * h.h1_minus + f * x.h1_plus;\n            h.h2_plus  = (1-f) * h.h2_plus  + f * x.h2_minus;\n            h.h2_minus = (1-f) * h.h2_minus + f * x.h2_plus;\n            break;\n        case het_del:\n            h.h1_plus  = (1-f) * h.h1_plus  + f * 0;\n            h.h1_minus = (1-f) * h.h1_minus + f * 0;\n            break;\n        case hom_del:\n            h.h1_plus  = (1-f) * h.h1_plus  + f * 0;\n            h.h1_minus = (1-f) * h.h1_minus + f * 0;\n            h.h2_plus  = (1-f) * h.h2_plus  + f * 0;\n            h.h2_minus = (1-f) * h.h2_minus + f * 0;\n            break;\n        case het_dup:\n            h.h1_plus  = (1-f) * h.h1_plus  + f * 2 * h.h1_plus;\n            h.h1_minus = (1-f) * h.h1_minus + f * 2 * h.h1_minus; // should be 0\n            break;\n        case hom_dup:\n            h.h1_plus  = (1-f) * h.h1_plus  + f * 2 * h.h1_plus;\n            h.h1_minus = (1-f) * h.h1_minus + f * 2 * h.h1_minus; // should be 0\n            h.h2_plus  = (1-f) * h.h2_plus  + f * 2 * h.h2_plus;\n            h.h2_minus = (1-f) * h.h2_minus + f * 2 * h.h2_minus; // should be 0\n            break;\n        case inv_dup:\n            h.h1_plus  = (1-f) * h.h1_plus  + f * (x.h1_minus + x.h1_plus);\n            h.h1_minus = (1-f) * h.h1_minus + f * (x.h1_minus + x.h1_plus);\n            break;\n        case false_del:\n            h.h1_plus  = (1-f) * h.h1_plus  + f * x.h1_plus/2;\n            h.h1_minus = (1-f) * h.h1_minus + f * x.h1_minus/2;\n            h.h2_plus  = (1-f) * h.h2_plus  + f * x.h2_plus/2;\n            h.h2_minus = (1-f) * h.h2_minus + f * x.h2_minus/2;\n    }\n}\n\n\n\n\n\n\n\n\n\n/** Read the SV config file (5 columns)\n *\n * this function also checks that the SV definition is valid and within the\n * chromosome boarders. Note that this is important because this check will not\n * be done during `locate_partial_bins`.\n *\n * @param filename file name.\n * @param chrom_names vector of names of the chromosomes.\n * @param chrom_size  vector of chromosome sizes. Must match `chrom_names` in size.\n * @param sv_list List of SVs to be written (push_back is used)\n */\nbool read_SV_config_file(std::string const & filename,\n                         std::vector<std::string> const & chrom_names,\n                         std::vector<int32_t> const & chrom_size,\n                         std::vector<SV> & sv_list)\n{\n    std::ifstream interval_file(filename.c_str(), std::ifstream::in);\n    if (interval_file.is_open()) {\n        while (interval_file.good()) {\n            std::string line;\n            getline(interval_file, line);\n            typedef boost::tokenizer< boost::char_separator<char> > Tokenizer;\n            boost::char_separator<char> sep(\" \\t,;\");\n            Tokenizer tokens(line, sep);\n            Tokenizer::iterator tokIter = tokens.begin();\n            if (tokIter!=tokens.end())\n            {\n                std::string chrName = *tokIter++;\n\n                // get chromosome id\n                //int32_t tid = bam_name2id(hdr, chrName.c_str());\n                int32_t tid = -1;\n                for (int32_t i = 0; i < chrom_names.size(); ++i) {\n                    if (chrom_names[i] == chrName) {\n                        tid = i;\n                        break;\n                    }\n                }\n                if (tid >= 0 && tid < chrom_names.size())\n                {\n                    Interval ivl;\n                    ivl.chr = tid;\n\n                    if (tokIter == tokens.end()) {\n                        std::cerr << \"Warning: Invalid line: \" << line << std::endl;\n                        continue;\n                    }\n                    ivl.start = boost::lexical_cast<int32_t>(*tokIter++);\n                    if (tokIter == tokens.end()) {\n                        std::cerr << \"Warning: Invalid line: \" << line << std::endl;\n                        continue;\n                    }\n                    ivl.end   = boost::lexical_cast<int32_t>(*tokIter++);\n\n                    // check whether interval makes sens\n                    if (ivl.start < 0 || ivl.start > ivl.end || ivl.end > chrom_size[tid]) {\n                        std::cerr << \"[Warning] Interval out of bounds \" << line << std::endl;\n                        continue;\n                    }\n\n                    // Get SV type and VAF\n                    if (tokIter == tokens.end()) {\n                        std::cerr << \"Warning: Invalid line: \" << line << std::endl;\n                        continue;\n                    }\n                    std::string type_in = *tokIter++;\n                    SV_type type_out;\n                    if      (type_in == \"het_inv\")\n                        type_out = het_inv;\n                    else if (type_in == \"hom_inv\")\n                        type_out = hom_inv;\n                    else if (type_in == \"het_del\")\n                        type_out = het_del;\n                    else if (type_in == \"hom_del\")\n                        type_out = hom_del;\n                    else if (type_in == \"het_dup\")\n                        type_out = het_dup;\n                    else if (type_in == \"hom_dup\")\n                        type_out = hom_dup;\n                    else if (type_in == \"inv_dup\")\n                        type_out = inv_dup;\n                    else if (type_in == \"false_del\")\n                        type_out = false_del;\n                    else {\n                        std::cerr << \"[Warning] Unknown SV type. Ignored: \" << line << std::endl;\n                    }\n\n\n                    // Variant allele frequency\n                    if (tokIter == tokens.end()) {\n                        std::cerr << \"Warning: Invalid line: \" << line << std::endl;\n                        continue;\n                    }\n                    float sv_vaf = boost::lexical_cast<float>(*tokIter++);\n                    assert(tokIter == tokens.end());\n\n                    sv_list.push_back(SV(ivl, type_out, sv_vaf));\n                } else {\n                    std::cerr << \"Warning: Chromosome not found: \" << chrName << \" in \\\"\" << line << \"\\\"\" << std::endl;\n                }\n            }\n        }\n        interval_file.close();\n    } else {\n        std::cerr << \"[Error] SV config file cannot be read: \" << filename << std::endl;\n        return false;\n    }\n    return true;\n}\n\n\n\n\n/**\n * Insert SVs onto haplotype counts.\n * @ingroup simulator\n *\n * This function does a couple of steps at the same time **for each SV**:\n *    * smaple which cells are supposed to carry the SV with a probability\n *      of *vaf* for each cell (this is probabilistic, so the actual number can\n *      differ from the expected vaf).\n *    * Insert SV onto haplotypes (currently just on h1), including\n *      *fractional bins* at the ends.\n *    * Note down ids of cell carrying the SV into `inserted_SVs` (refers to \n *      `cells`).\n *    * Calculate `optimal_breakpoints`, which are **always the right end of the\n *      bins**. The bin adapts to the left or right if the real SV breakpoint\n *      is < or > 50% of the bin.\n *\n * @param haplotypes Haplotype Counts that will be edited according to `flip_strands`.\n * @param inserted_SVs List of SVs and carriers that are inserted into haplotypes (initially empty).\n * @param cells List of `CellInfo`, which include cell and sample names etc.\n * @param optimal_breakpoints Set of optimal bin positions (e.g. optimal segmentation).\n * @param sv_list List of SVs to be inserted.\n * @param bins List of Intervals (bins) across the genome.\n * @param rd_gen Just pass the random generator here to flip a coin for each carrier.\n */\ntemplate <typename TRandomGenerator>\nvoid simulate_SVs(std::vector<THapCount> & haplotypes,\n                  std::vector<std::vector<unsigned>> & inserted_SVs,\n                  std::set<unsigned> & optimal_breakpoints,\n                  std::vector<SV> const & sv_list,\n                  std::vector<Interval> const & bins,\n                  std::vector<int32_t> const & chrom_map,\n                  TRandomGenerator & rd_gen)\n{\n    // Need a uniform dist. to sample carriers of the SV.\n    std::uniform_real_distribution<> rd_unif(0,1);\n\n    // Prepare entries in inserted_SVs for each SV\n    inserted_SVs.resize(sv_list.size());\n\n    for (unsigned j = 0; j < sv_list.size(); ++j)\n    {\n        // SV position in bin coordinates\n        SV const & sv = sv_list[j];\n        auto   sv_bins = interval::locate_partial_bins(sv.where, bins, chrom_map);\n        int32_t   binl = sv_bins.first.first;\n        int32_t   binr = sv_bins.first.second;\n        float       fl = sv_bins.second.first;\n        float       fr = sv_bins.second.second;\n\n        // Try for each cell\n        for (unsigned i = 0; i < haplotypes.size(); ++i)\n        {\n            if (rd_unif(rd_gen) < sv.vaf)\n            {\n                // List which cells got which SV.\n                inserted_SVs[j].push_back(i);\n\n                // There is only one bin --> fraction is fl - (1-fr)\n                if (binl == binr)\n                {\n                    flip_strand(haplotypes[i][binl], sv.type, fl - (1-fr));\n                    optimal_breakpoints.insert(binl); // right\n                    if (binl > chrom_map[sv.where.chr])\n                        optimal_breakpoints.insert(binl-1); // left\n\n                } else {\n\n                    // Partially flip first bin\n                    flip_strand(haplotypes[i][binl], sv.type, fl);\n                    if (fl > 0.5 && binl > chrom_map[sv.where.chr]) // left\n                        optimal_breakpoints.insert(binl-1);\n                    else\n                        optimal_breakpoints.insert(binl);\n\n                    // Partially flip last bin\n                    flip_strand(haplotypes[i][binr], sv.type, fr);\n                    if (fr < 0.5 && binr > chrom_map[sv.where.chr]) // right\n                        optimal_breakpoints.insert(binr-1);\n                    else\n                        optimal_breakpoints.insert(binr);\n\n                    // Completely flip all bins in between\n                    for (unsigned bin = binl+1; bin < binr; ++bin) {\n                        flip_strand(haplotypes[i][bin], sv.type);\n                    }\n                }\n            }\n        }\n    }\n}\n\n\n\n\n\n} /* namespace */\n\nstruct Conf_simul {\n    bool verbose;\n    unsigned n_cells;\n    unsigned window;\n    boost::filesystem::path f_sv;\n    boost::filesystem::path f_out;\n    boost::filesystem::path f_phases;\n    boost::filesystem::path f_sce;\n    boost::filesystem::path f_fai;\n    boost::filesystem::path f_svs;\n    boost::filesystem::path f_segment;\n    boost::filesystem::path f_info;\n    unsigned seed;\n    double p, min_cov, max_cov, alpha, phased_frac;\n    unsigned sce_num;\n    std::string sample_name;\n};\n\n\nint main_simulate(int argc, char **argv)\n{\n\n    using interval::Interval;\n    using count::TGenomeCounts;\n    using count::Counter;\n    using simulator::SV;\n    using simulator::HaploCount;\n    using simulator::SV_type;\n    using simulator::THapCount;\n    using simulator::THapType;\n\n\n    // Command line options\n    Conf_simul conf;\n    boost::program_options::options_description po_generic(\"Generic options\");\n    po_generic.add_options()\n    (\"help,?\", \"show help message\")\n    (\"verbose,v\", \"tell me more\")\n    (\"seed\", boost::program_options::value<unsigned>(&conf.seed), \"Random generator seed\")\n    (\"window,w\", boost::program_options::value<unsigned>(&conf.window)->default_value(100000)->notifier(in_range(1000,10000000,\"window\")), \"window size of fixed windows\")\n    (\"numcells,n\", boost::program_options::value<unsigned>(&conf.n_cells)->default_value(10)->notifier(in_range(0,500,\"numcells\")), \"number of cells to simulate\")\n    (\"genome,g\", boost::program_options::value<boost::filesystem::path>(&conf.f_fai), \"Chrom names & length file. Default: GRch38\")\n    ;\n\n    boost::program_options::options_description po_out(\"Output options\");\n    po_out.add_options()\n    (\"out,o\",         boost::program_options::value<boost::filesystem::path>(&conf.f_out)->default_value(\"out.txt.gz\"), \"output count file\")\n    (\"phases,P\",      boost::program_options::value<boost::filesystem::path>(&conf.f_phases), \"output phased reads into a file\")\n    (\"sceFile,S\",     boost::program_options::value<boost::filesystem::path>(&conf.f_sce), \"output the positions of SCEs\")\n    (\"variantFile,V\", boost::program_options::value<boost::filesystem::path>(&conf.f_svs), \"output SVs and which cells they were simulated in\")\n    (\"segmentFile,U\", boost::program_options::value<boost::filesystem::path>(&conf.f_segment), \"output optimal segmentation according to SVs and SCEs.\")\n    (\"info,i\",        boost::program_options::value<boost::filesystem::path>(&conf.f_info), \"Write info about samples\")\n    (\"sample-name\",   boost::program_options::value<std::string>(&conf.sample_name)->default_value(\"simulated\"), \"Use this sample name in the output\")\n    ;\n\n    boost::program_options::options_description po_rand(\"Radnomization parameters\");\n    po_rand.add_options()\n    (\"nbinom_p,p\",    boost::program_options::value<double>(&conf.p)->default_value(0.8,\"0.8\")->notifier(in_range(0.01,0.99,\"nbinom\")), \"p parameter of the NB distirbution\")\n    (\"minCoverage,c\", boost::program_options::value<double>(&conf.min_cov)->default_value(10)->notifier(in_range(1,500,\"minCoverage\")), \"min. read coverage per bin\")\n    (\"maxCoverage,C\", boost::program_options::value<double>(&conf.max_cov)->default_value(60)->notifier(in_range(1,500,\"maxCoverage\")), \"max. read coverage per bin\")\n    (\"alpha,a\",       boost::program_options::value<double>(&conf.alpha)->default_value(0.1,\"0.1\")->notifier(in_range(0,1,\"alpha\")), \"noise added to all bins: mostly 0, but for a fraction alpha drawn from geometrix distribution\")\n    (\"scesPerCell,s\", boost::program_options::value<unsigned>(&conf.sce_num)->default_value(4)->notifier(in_range(0,200,\"scesPerCell\")), \"Average number of SCEs per cell\")\n    (\"phasedFraction,z\", boost::program_options::value<double>(&conf.phased_frac)->default_value(0.1)->notifier(in_range(0,1,\"scesPerCell\")), \"Average number of SCEs per cell\")\n    ;\n\n    boost::program_options::options_description po_hidden(\"Hidden options\");\n    po_hidden.add_options()\n    (\"sv_config_file\", boost::program_options::value<boost::filesystem::path>(&conf.f_sv), \"Config file for SVs (see details)\")\n    ;\n\n    boost::program_options::positional_options_description po_positional;\n    po_positional.add(\"sv_config_file\", -1);\n\n    boost::program_options::options_description po_cmdline_options;\n    po_cmdline_options.add(po_generic).add(po_out).add(po_rand).add(po_hidden);\n    boost::program_options::options_description po_visible_options;\n    po_visible_options.add(po_generic).add(po_out).add(po_rand);\n    boost::program_options::variables_map vm;\n    boost::program_options::store(boost::program_options::command_line_parser(argc, argv).options(po_cmdline_options).positional(po_positional).run(), vm);\n    boost::program_options::notify(vm);\n\n    conf.verbose = vm.count(\"verbose\");\n\n    if (vm.count(\"help\") || !vm.count(\"sv_config_file\") || !file_exists(conf.f_sv.string()))\n    {\n        std::cout << std::endl;\n        std::cout << \"Mosaicatcher \" << STRINGIFYMACRO(MOSAIC_VERSION_MAJOR);\n        std::cout << \".\" << STRINGIFYMACRO(MOSAIC_VERSION_MINOR) << std::endl;\n        std::cout << \"> Simulate binned Strand-seq data.\" << std::endl;\n        std::cout << std::endl;\n        std::cout << \"Usage:   \" << argv[0] << \" [OPTIONS] SV-conf-file\" << std::endl << std::endl;\n        std::cout << po_visible_options << std::endl;\n\n        if (vm.count(\"help\")) {\n            std::cout << \"Simulate binned Strand-seq cells including structural variants (SVs)\" << std::endl;\n            std::cout << \"and sister chromatid exchange events (SCEs). Type, size, position and\" << std::endl;\n            std::cout << \"frequency of SVs are specified by a config file. To not include SVs\" << std::endl;\n            std::cout << \"specify an empty file. The SV config file is a tab-separated file with\" << std::endl;\n            std::cout << \"5 columns (chrom, start, end, SV type, avg. freuqency).\" << std::endl;\n            std::cout << \"The allowed SV types are\" << std::endl;\n            std::cout << \"  - het_del, hom_del\" << std::endl;\n            std::cout << \"  - het_dup, hom_dup\" << std::endl;\n            std::cout << \"  - het_inv, hom_inv\" << std::endl;\n            std::cout << \"  - inv_dup\" << std::endl;\n            std::cout << \"  - false_del (to simulate lower mappability region)\" << std::endl;\n            std::cout << \"SV breakpoints do not need to align with bin boundaries.\" << std::endl;\n            std::cout << std::endl;\n            std::cout << \"Note: The frequency (5-th colum) is interpreted as an expected\" << std::endl;\n            std::cout << \"      fraction of cells carrying the SV - the exact number of cells\" << std::endl;\n            std::cout << \"      can eventually differ form that expectation.\" << std::endl;\n        }\n        return vm.count(\"help\") ? 0 : 1;\n    }\n\n    // Error when coverage & p are not applicable to boost negative_binomial\n    double nb_n_param = conf.min_cov/2 * conf.p / (1-conf.p);\n    if (nb_n_param < 1) {\n        std::cerr << \"[Error] The specified values for p and minCov will cause a problem\" << std::endl;\n        std::cerr << \"        for the negative binomial distribution. This is currently\" << std::endl;\n        std::cerr << \"        a limitation of boost::random::negative_binomial_distribution,\" << std::endl;\n        std::cerr << \"        which only allows integer values > 0 as a value for n\" << std::endl;\n        std::cerr << \"        This behaviour is different in boost::math::negative_binomial\" << std::endl;\n        std::cerr << \"        and again different in the implementation used in R.\" << std::endl;\n        std::cerr << \"        std::negative_binomial is not giving an error but produces\" << std::endl;\n        std::cerr << \"        wrong numbers!\" << std::endl;\n        std::cerr << \"        This limitation is also the reason why background reads cannot be\" << std::endl;\n        std::cerr << \"        modelled by an NB for now.\" << std::endl;\n        std::cerr << \"Please choose a higher p or minCov!\" << std::endl;\n        return 0;\n    }\n\n\n    std::chrono::steady_clock::time_point t1, t2;\n\n    // global vars\n    std::vector<Interval>       bins;\n    std::vector<int32_t>        chrom_map;\n    std::vector<int32_t>        chrom_sizes;\n    std::vector<std::string>    chrom_names;\n    std::vector<THapCount>      haplotypes;\n    std::vector<THapType>       chrom_states;\n    std::vector<CellInfo>       cells;\n\n    // Read genome or use GRch38 by default\n    if (vm.count(\"genome\")) {\n        std::cerr << \"[Error]: reading a genome file is not implemented. Leave out this flag to use GRch38\" << std::endl;\n        return 2;\n    } else {\n        chrom_sizes = { \\\n            248956422, 242193529, 198295559, 190214555,\n            181538259, 170805979, 159345973, 145138636,\n            138394717, 133797422, 135086622, 133275309,\n            114364328, 107043718, 101991189,  90338345,\n            83257441,  80373285,  58617616,  64444167,\n            46709983,  50818468, 156040895,  57227415 };     // GRCh38\n        chrom_names = { \\\n            \"chr1\",  \"chr2\",  \"chr3\",   \"chr4\",  \"chr5\",  \"chr6\",\n            \"chr7\",  \"chr8\",  \"chr9\",  \"chr10\", \"chr11\", \"chr12\",\n            \"chr13\", \"chr14\", \"chr15\", \"chr16\", \"chr17\", \"chr18\",\n            \"chr19\", \"chr20\", \"chr21\", \"chr22\",  \"chrX\",  \"chrY\" };\n    }\n\n    // Generage bins & chrom_map\n    chrom_map.resize(chrom_sizes.size());\n    create_fixed_bins(bins, chrom_map, conf.window, std::vector<Interval>(), (int32_t)chrom_sizes.size(), chrom_sizes);\n    chrom_map.push_back((int32_t)bins.size());\n\n    // Random generator\n    std::random_device rd;\n    std::mt19937 rd_gen(rd());\n    boost::random::mt19937 rd_gen_boost;\n    if (vm.count(\"seed\")) {\n        rd_gen_boost.seed(conf.seed);\n        rd_gen      .seed(conf.seed);\n        std::cout << \"[Info] Using random seed \" << conf.seed << std::endl;\n    }\n\n\n    // Generate basic haplotype counts of each cells, including random noise\n    t1 = std::chrono::steady_clock::now();\n    std::uniform_real_distribution<> rd_cov(conf.min_cov, conf.max_cov);\n    std::uniform_real_distribution<> rd_unif(0,1);\n    double p = conf.p;\n\n    if (conf.verbose) std::cout << \"Simulating  \" << conf.n_cells << \" cells\" << std::endl;\n    for (unsigned i = 0; i < conf.n_cells; ++i)\n    {\n        double cov_per_bin = rd_cov(rd_gen);\n        std::geometric_distribution<>         rd_geom(5/(5+log2(cov_per_bin)));\n        //std::negative_binomial_distribution<> rd_nb(cov_per_bin/2 * p/(1-p), p); // gives wrong results for small r !!\n        boost::random::negative_binomial_distribution<> rd_nb_boost(cov_per_bin/2 * p/(1-p), p);\n        boost::random::variate_generator<boost::mt19937&, boost::random::negative_binomial_distribution<> > rd_nb(rd_gen_boost, rd_nb_boost);\n\n\n        CellInfo cell;\n        cell.median_bin_count = static_cast<unsigned>(cov_per_bin);\n        cell.sample_name = conf.sample_name;\n        cell.cell_name   = std::string(\"cell_\") + std::to_string(i);\n        cell.bam_file    = \"no_file\";\n        cell.nb_p        = p;\n        cell.nb_a        = 0;\n        cell.nb_r        = cov_per_bin * p / (1-p);\n\n        THapCount count(bins.size());\n        for (unsigned bin = 0; bin < bins.size(); ++bin)\n        {\n            count[bin].h1_plus = rd_nb();\n            count[bin].h2_plus = rd_nb();\n            count[bin].h1_minus = (rd_unif(rd_gen)<conf.alpha) ? rd_geom(rd_gen) : 0;\n            count[bin].h2_minus = (rd_unif(rd_gen)<conf.alpha) ? rd_geom(rd_gen) : 0;\n        }\n        haplotypes.push_back(std::move(count));\n        cells.push_back(std::move(cell));\n    }\n\n\n    // SV part\n    std::vector<SV> sv_list;\n    read_SV_config_file(conf.f_sv.string(), chrom_names, chrom_sizes, sv_list);\n\n    // Insert SVs\n    std::vector<std::vector<unsigned>> inserted_SVs;\n    std::set<unsigned> optimal_breakpoints;\n    simulate_SVs(haplotypes,\n                 inserted_SVs,\n                 optimal_breakpoints,\n                 sv_list,\n                 bins,\n                 chrom_map,\n                 rd_gen);\n\n\n    t2 = std::chrono::steady_clock::now();\n    auto time = std::chrono::duration_cast<std::chrono::duration<double>>(t2 - t1);\n    if (conf.verbose) std::cout << \"[Info] Simulation took \" << time.count() << \" sec.\" << std::endl;\n\n\n    // Write SV information (especially which cells contain the SVs)\n    if (vm.count(\"variantFile\"))\n    {\n        std::cout << \"[Write] Variant summary: \" << conf.f_svs.string() << std::endl;\n        std::ofstream out(conf.f_svs.string());\n        if (out.is_open())\n        {\n            out << \"chrom\\tstart\\tend\\tSV_type\\tsample\\tcell\" << std::endl;\n            for (unsigned j = 0; j < sv_list.size(); ++j)\n            {\n                SV const & sv = sv_list[j];\n                for (unsigned carrier_id : inserted_SVs[j])\n                {\n                    out << chrom_names[sv.where.chr] << \"\\t\";\n                    out << sv.where.start << \"\\t\" << sv.where.end << \"\\t\";\n                    out << SV_type_to_string(sv.type) << \"\\t\";\n                    out << cells[carrier_id].sample_name << \"\\t\";\n                    out << cells[carrier_id].cell_name << std::endl;\n                }\n            }\n        } else {\n            std::cerr << \"[Warning] Cannot write to \" << conf.f_svs.string() << std::endl;\n        }\n    }\n\n    // Update optimal_breakpoints by one breakpoint at the end of each chrom.\n    for (int32_t chrom = 1; chrom < chrom_map.size(); ++chrom)\n        optimal_breakpoints.insert(chrom_map[chrom]-1);\n\n    // Write optimal segmentation file, which includes SV breakpoints and SCE breakpoints.\n    if (vm.count(\"segmentFile\"))\n    {\n        std::cout << \"[Write] Segmentation file: \" << conf.f_segment.string() << std::endl;\n        std::ofstream out(conf.f_segment.string());\n        if (out.is_open())\n        {\n            out << \"k\\tchrom\\tbps\" << std::endl;\n            for (auto const & bin : optimal_breakpoints)\n            {\n                int32_t chrom = std::upper_bound(chrom_map.begin(), chrom_map.end(), bin) - chrom_map.begin() -1;\n                out << 0 << \"\\t\" << chrom_names[chrom] << \"\\t\";\n                out << bin - chrom_map[chrom] << std::endl;\n            }\n        } else {\n            std::cerr << \"[Warning] Cannot write to \" << conf.f_segment.string() << std::endl;\n        }\n    }\n    \n\n    // Turn haplotypes into TGenomeCounts and simulate SCEs\n    t1 = std::chrono::steady_clock::now();\n    std::vector<TGenomeCounts> final_counts;\n    std::vector<std::pair<Interval,std::string>> strand_states;\n    std::vector<unsigned> str_states_cells;\n    std::vector<std::vector<simulator::phased_counts>> phases;\n\n    for (unsigned i = 0; i < conf.n_cells; ++i)\n    {\n        unsigned cell_pos = strand_states.size();\n        std::vector<simulator::phased_counts> phase;\n        final_counts.push_back(render_cell(haplotypes[i],   // simulated counts\n                                           chrom_map,       // chromosome boundaries\n                                           (float)conf.sce_num / bins.size(), // sce_probability\n                                           strand_states, // Intervals with inherited strand states\n                                           phase,\n                                           rd_gen,\n                                           conf.phased_frac));\n\n        // note down which cells belong to these intervals\n        for (; cell_pos < strand_states.size(); ++cell_pos)\n            str_states_cells.push_back(i);\n\n        // save phased reads as additional output\n        phases.push_back(phase);\n    }\n    t2 = std::chrono::steady_clock::now();\n    time = std::chrono::duration_cast<std::chrono::duration<double>>(t2 - t1);\n    if (conf.verbose) std::cout << \"[Info] Rendering cells took \" << time.count() << \" sec.\" << std::endl;\n\n\n\n    // write down SCEs\n    if (vm.count(\"sceFile\"))\n    {\n        std::cout << \"[Write] Inherited strand states (SCEs) to file \" << conf.f_sce.string() << std::endl;\n        std::ofstream out(conf.f_sce.string());\n        if (out.is_open()) {\n            out << \"sample\\tcell\\tchrom\\tstart\\tend\\tclass\" << std::endl;\n            for (unsigned i = 0; i < strand_states.size(); ++i) {\n                out << conf.sample_name << \"\\t\";\n                out << \"cell_\" << std::to_string(str_states_cells[i]) << \"\\t\";\n                out << chrom_names[strand_states[i].first.chr] << \"\\t\";\n                out << bins[(strand_states[i].first).start].start << \"\\t\";\n                out << bins[(strand_states[i].first).end].end << \"\\t\";\n                out << strand_states[i].second << std::endl;\n            }\n        } else {\n            std::cerr << \"[Warning] Cannot write to \" << conf.f_sce.string() << std::endl;\n        }\n    }\n\n\n    // Get total number of reads per cell and print cell information:\n    for (unsigned i = 0; i < final_counts.size(); ++i) {\n        for (unsigned bin = 0; bin < bins.size(); ++bin) {\n            cells[i].n_mapped += final_counts[i][bin].watson_count + final_counts[i][bin].crick_count;\n        }\n    }\n\n    //\n    // Chapter: Filter cells and bins and run HMM\n\n    t1 = std::chrono::steady_clock::now();\n\n    // median per cell\n    count::set_median_per_cell(final_counts, cells);\n\n    // filter cells with low counts and set pass_qc = false for bad cells;\n    std::vector<unsigned> good_cells;\n    good_cells = count::get_good_cells(final_counts, cells);\n    for (auto c : cells) c.pass_qc = false;\n    for (unsigned cid : good_cells) cells[cid].pass_qc = true;\n    if (cells.size() > good_cells.size())\n        std::cout << \"[Info] \" << cells.size() - good_cells.size() << \"/\" << cells.size()\n                  << \" cells were deemed QC fail by HMM (which is purely based on coverage for now)\" << std::endl;\n\n    // filter bins with abnormal counts (not happening here)\n    std::vector<unsigned> good_bins(bins.size());\n    std::iota(good_bins.begin(), good_bins.end(), 0); // fill with 0,1,2,...\n\n    // calculate cell means and cell variances, grouped by sample (not cell)\n    std::unordered_map<std::string, SampleInfo> samples;\n    calculate_new_cell_mean(samples, cells, final_counts, good_cells, good_bins);\n\n    // Estimation of parameter p per sample\n    for (auto it = samples.begin(); it != samples.end(); ++it) {\n        SampleInfo & s = it->second;\n        s.p = std::inner_product(s.means.begin(), s.means.end(), s.means.begin(), 0.0f) \\\n        / std::inner_product(s.means.begin(), s.means.end(), s.vars.begin(), 0.0f);\n    }\n\n    // Chapter: Run HMM\n    run_standard_HMM(final_counts,\n                     good_cells,\n                     cells,\n                     good_bins,\n                     chrom_map,\n                     samples,\n                     10.0f / bins.size());\n\n    t2 = std::chrono::steady_clock::now();\n    time = std::chrono::duration_cast<std::chrono::duration<double>>(t2 - t1);\n    if (conf.verbose) std::cout << \"[Info] Running HMM took \" << time.count() << \" sec.\" << std::endl;\n\n\n    // Write info files\n    if (vm.count(\"info\")) {\n        std::cout << \"[Write] Cell info to \" << conf.f_info.string() << \". Note that NB parameters are estimated before SVs are introduced.\" << std::endl;\n        write_cell_info(conf.f_info.string(), cells);\n    }\n\n\n\n\n    // write down phases\n    if (vm.count(\"phases\"))\n    {\n        std::cout << \"[Write] Phases to \" << conf.f_phases.string() << std::endl;\n        std::ofstream out(conf.f_phases.string());\n        if (out.is_open())\n        {\n            out << \"chrom\\tstart\\tend\\tsample\\tcell\\th1_w\\th1_c\\th2_w\\th2_c\" << std::endl;\n            for (unsigned i = 0; i < phases.size(); ++i)\n            {\n                for (unsigned j = 0; j < phases[i].size(); ++j)\n                {\n                    out << chrom_names[bins[j].chr] << \"\\t\";\n                    out << bins[j].start << \"\\t\";\n                    out << bins[j].end << \"\\t\";\n                    out << cells[i].sample_name << \"\\t\";\n                    out << cells[i].cell_name << \"\\t\";\n                    out << static_cast<int>(phases[i][j].h1_w) << \"\\t\";\n                    out << static_cast<int>(phases[i][j].h1_c) << \"\\t\";\n                    out << static_cast<int>(phases[i][j].h2_w) << \"\\t\";\n                    out << static_cast<int>(phases[i][j].h2_c) << std::endl;\n                }\n            }\n        } else {\n            std::cerr << \"[Warning] Cannot write to \" << conf.f_phases.string() << std::endl;\n        }\n    }\n\n    \n\n\n    // write down counts\n    std::cout << \"[Write] Count table \" << conf.f_out.string() << std::endl;\n    std::vector<std::pair<std::string, std::string>> sample_cell_names;\n    for (unsigned i=0; i<conf.n_cells; ++i) {\n        sample_cell_names.push_back(std::make_pair(conf.sample_name, \"cell_\" + std::to_string(i)));\n    }\n    io::write_counts_gzip(conf.f_out.string(), final_counts, bins, chrom_names, sample_cell_names);\n\n    return 0;\n}\n\n\n\n\n\n#endif /* simulate_hpp */\n", "meta": {"hexsha": "c1f14b39ade4d19f07d6cce893e6d03cf4f3b761", "size": 41751, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/simulate.hpp", "max_stars_repo_name": "tobiasmarschall/mosaicatcher", "max_stars_repo_head_hexsha": "42b078ec0964f3711f0f4871065be5157e63eb37", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2019-12-26T01:36:59.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-30T00:28:01.000Z", "max_issues_repo_path": "src/simulate.hpp", "max_issues_repo_name": "tobiasmarschall/mosaicatcher", "max_issues_repo_head_hexsha": "42b078ec0964f3711f0f4871065be5157e63eb37", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2018-01-12T11:56:43.000Z", "max_issues_repo_issues_event_max_datetime": "2019-01-29T16:09:34.000Z", "max_forks_repo_path": "src/simulate.hpp", "max_forks_repo_name": "tobiasmarschall/mosaicatcher", "max_forks_repo_head_hexsha": "42b078ec0964f3711f0f4871065be5157e63eb37", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2018-05-24T09:12:56.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-02T11:33:28.000Z", "avg_line_length": 42.1727272727, "max_line_length": 229, "alphanum_fraction": 0.576584992, "num_tokens": 10617, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6959583376458152, "lm_q2_score": 0.4416730056646256, "lm_q1q2_score": 0.3073860108053835}}
{"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 point_set.hpp\n * \\date October 2014\n * \\author Jan Issac (jan.issac@gmail.com)\n */\n\n#pragma once\n\n\n#include <map>\n#include <cmath>\n#include <type_traits>\n\n#include <Eigen/Dense>\n\n#include <fl/util/meta.hpp>\n#include <fl/util/traits.hpp>\n\n#include <fl/distribution/gaussian.hpp>\n#include <fl/exception/exception.hpp>\n#include <fl/filter/filter_interface.hpp>\n\n/** \\cond internal */\n/**\n * Checks dimensions\n */\n#define INLINE_CHECK_POINT_SET_DIMENSIONS() \\\n    assert(points_.cols() == int(weights_.size())); \\\n    if (points_.rows() == 0) \\\n    { \\\n        fl_throw(ZeroDimensionException(\"PointSet\")); \\\n    } \\\n    if (points_.cols() == 0)  \\\n    { \\\n        fl_throw(Exception(\"PointSet contains no points.\")); \\\n    }\n\n/**\n * Checks for index out of bounds and valid dimensions\n */\n#define INLINE_CHECK_POINT_SET_BOUNDS(i) \\\n    if (i >= int(weights_.size())) \\\n    { \\\n        fl_throw(OutOfBoundsException(i, weights_.size())); \\\n    } \\\n    INLINE_CHECK_POINT_SET_DIMENSIONS();\n/** \\endcond */\n\nnamespace fl\n{\n\n// Forward declaration\ntemplate <typename Point, int Points_> class PointSet;\n\n/**\n * Trait struct of a PointSet\n */\ntemplate <typename Point_, int Points_>\nstruct Traits<PointSet<Point_, Points_>>\n{\n    /**\n     * \\brief Point type\n     */\n    typedef Point_ Point;\n\n    /**\n     * \\brief Number of points for fixed-size set\n     */\n    enum\n    {\n        /**\n         * \\brief Number of points which provided by the PointSet.\n         *\n         * If the number of points is unknown and there for dynamic, then\n         * NumberOfPoints is set to Eigen::Dynamic\n         */\n        NumberOfPoints = IsFixed<Points_>() ? Points_ : Eigen::Dynamic\n    };\n\n    /**\n     * \\brief Weight harbors the weights of a point. For each of the first two\n     * moments there is a separate weight.\n     *\n     *\n     * Generally a single weight suffices. However, some transforms utilize\n     * different weights for each moment to select a set of points representing\n     * the underlying moments.\n     */\n    struct Weight\n    {\n        /**\n         * First moment (mean) point weight\n         */\n        double w_mean;\n\n        /**\n         * Second centered moment (covariance) point weight\n         */\n        double w_cov;\n    };\n\n    /**\n     * \\brief Point container type\n     *\n     * \\details\n     * The point container type has a fixed-size dimension of a point\n     * and the number of the points is statically known.\n     */\n    typedef Eigen::Matrix<\n                typename Point::Scalar,\n                Point::RowsAtCompileTime,\n                Points_\n            > PointMatrix;\n\n    /**\n     * \\brief WeightVector\n     */\n    typedef Eigen::Matrix<\n                typename Point::Scalar,\n                Points_,\n                1\n            > WeightVector;\n\n    /**\n     * \\brief Weight list of all points\n     */\n    typedef Eigen::Array<Weight, Points_, 1> Weights;\n};\n\n/**\n * \\ingroup nonlinear_gaussian_filter\n *\n * \\brief PointSet represents a container of fixed-size or dynamic-size points each\n *        paired with a set of weights.\n *\n * PointSet has two degree-of-freedoms. The first\n * is the dimension of the points. The second is the number of points within the\n * set. Each of the parameter can either be fixed at compile time or left\n * unspecified. That is, the parameter is set to Eigen::Dynamic.\n *\n * \\tparam Point    Gaussian variable type\n * \\tparam Points_  Number of points representing the gaussian\n */\ntemplate <typename Point_, int Points_ = -1>\nclass PointSet\n{\nprivate:\n    /** \\brief Typdef of \\c This for #from_traits(TypeName) helper */\n    typedef PointSet<Point_, Points_> This;\n\npublic:\n    typedef from_traits(Point);\n    typedef from_traits(PointMatrix);\n    typedef from_traits(Weight);\n    typedef from_traits(Weights);\n    typedef from_traits(WeightVector);\n\n    static_assert(Points_ != 0, \"Invalid point count\");\n\npublic:\n    /**\n     * \\brief Creates a PointSet\n     *\n     * \\param points_count   Number of points representing the Gaussian\n     * \\param dimension      Sample space dimension\n     */\n    PointSet(int dimension,\n             int points_count = ToDimension<Points_>())\n        : points_(dimension, points_count),\n          weights_(points_count, 1)\n    {\n        assert(points_count >= 0);\n        static_assert(Points_ >= Eigen::Dynamic, \"Invalid point count\");\n\n        points_.setZero();\n\n        double weight = (points_count > 0) ? 1./double(points_count) : 0;\n        weights_.fill(Weight{weight, weight});\n    }\n\n    /**\n     * \\brief Creates a PointSet\n     */\n    PointSet()\n    {\n        points_.setZero();\n\n        double weight = (weights_.size() > 0) ? 1./double(weights_.size()) : 0;\n        weights_.fill(Weight{weight, weight});\n    }\n\n    /**\n     * \\brief Overridable default destructor\n     */\n    virtual ~PointSet() noexcept { }\n\n    /**\n     * \\brief Resizes a dynamic-size PointSet\n     *\n     * \\param Points_   Number of points\n     *\n     * \\throws ResizingFixedSizeEntityException\n     */\n    void resize(int points_count)\n    {\n        if (int(weights_.size()) == points_count &&\n            int(points_.cols()) == points_count) return;\n\n        if (IsFixed<Points_>())\n        {\n            fl_throw(\n                fl::ResizingFixedSizeEntityException(weights_.size(),\n                                                     points_count,\n                                                     \"poit set Gaussian\"));\n        }\n\n        points_.setZero(points_.rows(), points_count);\n\n        weights_.resize(points_count, 1);\n        const double weight = (points_count > 0)? 1. / double(points_count) : 0;\n        for (int i = 0; i < points_count; ++i)\n        {\n            weights_(i).w_mean = weight;\n            weights_(i).w_cov = weight;\n        }\n\n        // std::fill(weights_.begin(), weights_.end(), Weight{weight, weight});\n    }\n\n    /**\n     * \\brief Resizes a dynamic-size PointSet\n     *\n     * \\param Points_   Number of points\n     *\n     * \\throws ResizingFixedSizeEntityException\n     */\n    void resize(int dim, int points_count)\n    {\n        if (dim == dimension() && points_count == count_points()) return;\n\n        points_.setZero(dim, points_count);\n\n        weights_.resize(points_count, 1);\n        const double weight = (points_count > 0)? 1. / double(points_count) : 0;\n        for (int i = 0; i < points_count; ++i)\n        {\n            weights_(i).w_mean = weight;\n            weights_(i).w_cov = weight;\n        }\n    }\n\n    /**\n     * \\brief Sets the new dimension for dynamic-size points (not to confuse\n     * with the number of points)\n     *\n     * \\param dim  Dimension of each point\n     */\n    void dimension(int dim)\n    {\n        points_.resize(dim, count_points());\n    }\n\n    /**\n     * \\return Dimension of containing points\n     */\n    int dimension() const\n    {\n        return points_.rows();\n    }\n\n    /**\n     * \\brief  The number of points\n     */\n    int count_points() const\n    {\n        return points_.cols();\n    }\n\n    /**\n     * \\brief  Read only access on i-th point\n     *\n     * \\param i Index of requested point\n     *\n     * \\throws OutOfBoundsException\n     * \\throws ZeroDimensionException\n     */\n    Point point(int i) const\n    {\n        INLINE_CHECK_POINT_SET_BOUNDS(i);\n\n        return points_.col(i);\n    }\n\n    auto operator[](int i) -> decltype(PointMatrix().col(i))\n    {\n        return points_.col(i);\n    }\n\n    /**\n     * \\brief  weight of i-th point assuming both weights are the same\n     *\n     * \\param i Index of requested point\n     *\n     * \\throws OutOfBoundsException\n     * \\throws ZeroDimensionException\n     */\n    double weight(int i)\n    {\n        INLINE_CHECK_POINT_SET_BOUNDS(i);\n\n        return weights_(i).w_mean;\n    }\n\n    /**\n     * \\brief  weights of i-th point\n     *\n     * \\param i Index of requested point\n     *\n     * \\throws OutOfBoundsException\n     * \\throws ZeroDimensionException\n     */\n    const Weight& weights(int i) const\n    {\n        INLINE_CHECK_POINT_SET_BOUNDS(i);\n\n        return weights_(i);\n    }\n\n    /**\n     * \\brief  Point matrix (read only)\n     */\n    const PointMatrix& points() const noexcept\n    {\n        return points_;\n    }\n\n    /**\n     * \\brief  Point matrix\n     */\n    PointMatrix& points()\n    {\n        return points_;\n    }\n\n    /**\n     * \\brief  point weights vector\n     */\n    const Weights& weights() const noexcept\n    {\n        return weights_;\n    }\n\n    /**\n     * \\brief  Returns the weights for the mean of the points as a vector\n     */\n    WeightVector mean_weights_vector() const noexcept\n    {\n        const int point_count = count_points();\n\n        WeightVector weight_vec(point_count);\n\n        for (int i = 0; i < point_count; ++i)\n        {\n            weight_vec(i) = weights_(i).w_mean;\n        }\n\n        return weight_vec;\n    }\n\n    /**\n     * \\brief  Returns the weights for the covariance of the points as a vector\n     */\n    WeightVector covariance_weights_vector() const noexcept\n    {\n        const int point_count = count_points();\n\n        WeightVector weight_vec(point_count);\n\n        for (int i = 0; i < point_count; ++i)\n        {\n            weight_vec(i) = weights_(i).w_cov;\n        }\n\n        return weight_vec;\n    }\n\n    /**\n     * \\brief Sets the given point matrix\n     */\n    void points(const PointMatrix& point_matrix)\n    {\n        points_ = point_matrix;\n    }\n\n    /**\n     * \\brief Sets a given point at position i\n     *\n     * \\param i         Index of point\n     * \\param p         The new point\n     *\n     * \\throws OutOfBoundsException\n     * \\throws ZeroDimensionException\n     */\n    void point(int i, Point p)\n    {\n        INLINE_CHECK_POINT_SET_BOUNDS(i);\n\n        points_.col(i) = p;\n    }\n\n    /**\n     * \\brief Sets a given point at position i along with its weights\n     *\n     * \\param i         Index of point\n     * \\param p         The new point\n     * \\param w         Point weights. The weights determinaing the first two\n     *                  moments are the same\n     *\n     * \\throws OutOfBoundsException\n     * \\throws ZeroDimensionException\n     */\n    void point(int i, Point p, double w)\n    {\n        point(i, p, Weight{w, w});\n    }\n\n    /**\n     * \\brief Sets a given point at position i along with its weights\n     *\n     * \\param i         Index of point\n     * \\param p         The new point\n     * \\param w_mean    point weight used to compute the first moment\n     * \\param w_cov     point weight used to compute the second centered moment\n     *\n     * \\throws OutOfBoundsException\n     * \\throws ZeroDimensionException\n     */\n    void point(int i, Point p, double w_mean , double w_cov)\n    {\n        point(i, p, Weight{w_mean, w_cov});\n    }\n\n    /**\n     * \\brief Sets a given point at given position i along with its weights\n     *\n     * \\param i         Index of point\n     * \\param p         The new point\n     * \\param weights   point weights\n     *\n     * \\throws OutOfBoundsException\n     * \\throws ZeroDimensionException\n     */\n    void point(int i, Point p, Weight weights)\n    {\n        INLINE_CHECK_POINT_SET_BOUNDS(i);\n\n        points_.col(i) = p;\n        weights_(i) = weights;\n    }\n\n    /**\n     * \\brief Sets a given weight of a point at position i\n     *\n     * \\param i         Index of point\n     * \\param w         Point weights. The weights determinaing the first two\n     *                  moments are the same\n     *\n     * \\throws OutOfBoundsException\n     * \\throws ZeroDimensionException\n     */\n    void weight(int i, double w)\n    {\n        weight(i, Weight{w, w});\n    }\n\n    /**\n     * \\brief Sets given weights of a point at position i\n     *\n     * \\param i         Index of point\n     * \\param w_mean    point weight used to compute the first moment\n     * \\param w_cov     point weight used to compute the second centered moment\n     *\n     * \\throws OutOfBoundsException\n     * \\throws ZeroDimensionException\n     */\n    void weight(int i, double w_mean , double w_cov)\n    {\n        weight(i, Weight{w_mean, w_cov});\n    }\n\n    /**\n     * Sets given weights of a point at position i\n     *\n     * \\param i         Index of point\n     * \\param weights   point weights\n     *\n     * \\throws OutOfBoundsException\n     * \\throws ZeroDimensionException\n     */\n    void weight(int i, Weight weights)\n    {\n        INLINE_CHECK_POINT_SET_BOUNDS(i);\n\n        weights_(i) = weights;\n    }\n\n    /**\n     * \\brief Creates a PointMatrix populated with zero mean points\n     *\n     * \\return Centered points matrix.\n     *\n     * \\throws ZeroDimensionException\n     * \\throws Exception\n     */\n    PointMatrix centered_points() const\n    {\n        INLINE_CHECK_POINT_SET_DIMENSIONS();\n\n        PointMatrix centered(points_.rows(), points_.cols());\n\n        const Point weighted_mean = mean();\n        const int point_count = points_.cols();\n        for (int i = 0; i < point_count; ++i)\n        {\n            centered.col(i) = points_.col(i) - weighted_mean;\n        }\n\n        return centered;\n    }\n\n    /**\n     * \\brief Centers all points and returns the mean over all points.\n     *\n     * Computes the weighted mean of all points and subtracts the mean from all\n     * points. Finally returns the weighted mean\n     *\n     * \\return Weighted mean\n     */\n    Point center()\n    {\n        Point weighted_mean = mean();\n        const int point_count = points_.cols();\n        for (int i = 0; i < point_count; ++i)\n        {\n            points_.col(i) -= weighted_mean;\n        }\n\n        return weighted_mean;\n    }\n\n    /**\n     * \\brief Returns the weighted mean of all points\n     *\n     * \\throws ZeroDimensionException\n     * \\throws Exception\n     */\n    Point mean() const\n    {\n        INLINE_CHECK_POINT_SET_DIMENSIONS();\n\n        Point weighted_mean;\n        weighted_mean.setZero(points_.rows());\n\n        const int point_count = points_.cols();\n        for (int i = 0; i < point_count; ++i)\n        {\n            weighted_mean += weights_(i).w_mean * points_.col(i);\n        }\n\n        return weighted_mean;\n    }\n\nprotected:\n    /**\n     * \\brief point container\n     */\n    PointMatrix points_;\n\n    /**\n     * \\brief weight container\n     */\n    Weights weights_;\n};\n\n}\n", "meta": {"hexsha": "849fb93d7b9ff226ae33e121b902fbc9cfff7935", "size": 14601, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/fl/filter/gaussian/transform/point_set.hpp", "max_stars_repo_name": "aeolusbot-tommyliu/fl", "max_stars_repo_head_hexsha": "a50d0c9620a8f86e0cd14a5e22ee0f022d00bd02", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 17.0, "max_stars_repo_stars_event_min_datetime": "2015-07-03T06:53:05.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-15T20:55:12.000Z", "max_issues_repo_path": "include/fl/filter/gaussian/transform/point_set.hpp", "max_issues_repo_name": "aeolusbot-tommyliu/fl", "max_issues_repo_head_hexsha": "a50d0c9620a8f86e0cd14a5e22ee0f022d00bd02", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2015-02-20T12:48:17.000Z", "max_issues_repo_issues_event_max_datetime": "2019-12-18T08:45:13.000Z", "max_forks_repo_path": "include/fl/filter/gaussian/transform/point_set.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": 24.3756260434, "max_line_length": 83, "alphanum_fraction": 0.577768646, "num_tokens": 3425, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5467381667555714, "lm_q2_score": 0.5621765008857981, "lm_q1q2_score": 0.3073633494873631}}
{"text": "/*\n * BSD 3-Clause License\n *\n * Full text: https://opensource.org/licenses/BSD-3-Clause\n *\n * Copyright (c) 2018, Viktor Seib\n * All rights reserved.\n *\n */\n\n#include \"utils.h\"\n#include <Eigen/Eigenvalues>\n\n#include \"../third_party/libgdiam-1.3/gdiam.hpp\"\n\n#include <boost/math/constants/constants.hpp>\n\nnamespace ism3d\n{\n    Json::Value Utils::vector3fToJson(const Eigen::Vector3f& vector)\n    {\n        Json::Value json(Json::arrayValue);\n\n        json.append(vector[0]);\n        json.append(vector[1]);\n        json.append(vector[2]);\n\n        return json;\n    }\n\n    bool Utils::jsonToVector3f(Json::Value json, Eigen::Vector3f& vector)\n    {\n        if (json.isNull() || !json.isArray() || json.size() != 3)\n            return false;\n\n        vector[0] = json[0].asFloat();\n        vector[1] = json[1].asFloat();\n        vector[2] = json[2].asFloat();\n\n        return true;\n    }\n\n    Json::Value Utils::quatToJson(const boost::math::quaternion<float>& quat)\n    {\n        Json::Value json(Json::arrayValue);\n\n        json.append(quat.R_component_1());\n        json.append(quat.R_component_2());\n        json.append(quat.R_component_3());\n        json.append(quat.R_component_4());\n\n        return json;\n    }\n\n    bool Utils::jsonToQuat(Json::Value json, boost::math::quaternion<float>& quat)\n    {\n        if (json.isNull() || !json.isArray() || json.size() != 4)\n            return false;\n\n        quat = boost::math::quaternion<float>(json[0].asFloat(),\n                json[1].asFloat(), json[2].asFloat(), json[3].asFloat());\n\n        return true;\n    }\n\n    float Utils::ln(float x)\n    {\n        return log(x) / log(10);\n    }\n\n    boost::math::quaternion<float> Utils::ln(const boost::math::quaternion<float>& quat)\n    {\n        float w = quat.R_component_1();\n        float x = quat.R_component_2();\n        float y = quat.R_component_3();\n        float z = quat.R_component_4();\n\n        if (fabs(w) < 1.0f) {\n            float angle = acosf(w);\n            float sinAngle = sinf(angle);\n            if (sinAngle >= 0.00001) {\n                float coeff = angle / sinAngle;\n                x *= coeff;\n                y *= coeff;\n                z *= coeff;\n            }\n        }\n\n        boost::math::quaternion<float> result(w, x, y, z);\n        return result;\n\n        /*float qNorm = boost::math::norm(quat);\n        float vNorm = sqrtf(quat.R_component_2() * quat.R_component_2() +\n                            quat.R_component_3() * quat.R_component_3() +\n                            quat.R_component_4() * quat.R_component_4());\n\n        float w = ln(qNorm);\n        float x = (quat.R_component_2() / vNorm) * acosf(quat.R_component_1() / qNorm);\n        float y = (quat.R_component_3() / vNorm) * acosf(quat.R_component_1() / qNorm);\n        float z = (quat.R_component_4() / vNorm) * acosf(quat.R_component_1() / qNorm);*/\n    }\n\n    boost::math::quaternion<float> Utils::exp(const boost::math::quaternion<float>& quat)\n    {\n        float w = quat.R_component_1();\n        float x = quat.R_component_2();\n        float y = quat.R_component_3();\n        float z = quat.R_component_4();\n\n        float angle = sqrtf(x * x + y * y + z * z);\n        float sinAngle = sinf(angle);\n\n        w = cosf(angle);\n\n        if (fabs(sinAngle) >= 0.00001f) {\n            float coeff = sinAngle / angle;\n            x *= coeff;\n            y *= coeff;\n            z *= coeff;\n        }\n\n        boost::math::quaternion<float> result(w, x, y, z);\n        return result;\n    }\n\n    float Utils::deg2rad(float deg)\n    {\n        return deg * (M_PI / 180.0f);\n    }\n\n    float Utils::rad2deg(float rad)\n    {\n        return (rad * 180.0f) / M_PI;\n    }\n\n    void Utils::getRotQuaternion(const pcl::ReferenceFrame& refFrame, boost::math::quaternion<float>& quaternion)\n    {\n        // transform the point from the world into the keypoint coordinate system\n        Eigen::Matrix3f keypointCoord = Eigen::Matrix3f::Identity();\n        keypointCoord(0, 0) = refFrame.x_axis[0];\n        keypointCoord(1, 0) = refFrame.x_axis[1];\n        keypointCoord(2, 0) = refFrame.x_axis[2];\n        keypointCoord(0, 1) = refFrame.y_axis[0];\n        keypointCoord(1, 1) = refFrame.y_axis[1];\n        keypointCoord(2, 1) = refFrame.y_axis[2];\n        keypointCoord(0, 2) = refFrame.z_axis[0];\n        keypointCoord(1, 2) = refFrame.z_axis[1];\n        keypointCoord(2, 2) = refFrame.z_axis[2];\n\n        // create rotation quaternion\n        matrix2Quat(keypointCoord, quaternion);\n    }\n\n    Eigen::Vector3f Utils::rotateInto(const Eigen::Vector3f& point, const pcl::ReferenceFrame& refFrame)\n    {\n        // create rotation quaternion\n        boost::math::quaternion<float> rotQuat;\n        getRotQuaternion(refFrame, rotQuat);\n\n        // rotate point into coordinate system\n        Eigen::Vector3f result(point);\n        quatRotateInv(rotQuat, result);\n\n        return result;\n    }\n\n    Eigen::Vector3f Utils::rotateBack(const Eigen::Vector3f& point, const pcl::ReferenceFrame& refFrame)\n    {\n        // create rotation quaternion\n        boost::math::quaternion<float> rotQuat;\n        getRotQuaternion(refFrame, rotQuat);\n\n        // rotate point from coordinate system back into world\n        Eigen::Vector3f result(point);\n        quatRotate(rotQuat, result);\n\n        return result;\n    }\n\n    std::vector<pcl::ReferenceFrame> Utils::generateFrames(const pcl::ReferenceFrame& refFrame)\n    {\n        // This function 4 different coordinates system by rotating the reference frame with the\n        // right hand rule (see http://www.pointclouds.org/assets/uploads/cglibs13_features.pdf).\n\n        std::vector<pcl::ReferenceFrame> frames(4, refFrame);\n\n        // frames[0] = refFrame\n\n        pcl::ReferenceFrame& frame1 = frames[1];\n        frame1.x_axis[0] *= -1;\n        frame1.x_axis[1] *= -1;\n        frame1.x_axis[2] *= -1;\n        frame1.y_axis[0] *= -1;\n        frame1.y_axis[1] *= -1;\n        frame1.y_axis[2] *= -1;\n\n        pcl::ReferenceFrame& frame2 = frames[2];\n        frame2.x_axis[0] *= -1;\n        frame2.x_axis[1] *= -1;\n        frame2.x_axis[2] *= -1;\n        frame2.z_axis[0] *= -1;\n        frame2.z_axis[1] *= -1;\n        frame2.z_axis[2] *= -1;\n\n        pcl::ReferenceFrame& frame3 = frames[3];\n        frame3.y_axis[0] *= -1;\n        frame3.y_axis[1] *= -1;\n        frame3.y_axis[2] *= -1;\n        frame3.z_axis[0] *= -1;\n        frame3.z_axis[1] *= -1;\n        frame3.z_axis[2] *= -1;\n\n        return frames;\n    }\n\n    template\n    Utils::BoundingBox Utils::computeAABB<PointT>(const pcl::PointCloud<PointT>::ConstPtr &model);\n    template\n    Utils::BoundingBox Utils::computeAABB<PointNormalT>(const pcl::PointCloud<PointNormalT>::ConstPtr &model);\n\n    template<typename T>\n    Utils::BoundingBox Utils::computeAABB(const typename pcl::PointCloud<T>::ConstPtr &model)\n    {\n        T minP, maxP;\n        pcl::getMinMax3D(*model, minP, maxP);\n\n        Utils::BoundingBox box;\n        box.rotQuat = boost::math::quaternion<float>(1, 0, 0, 0);\n        box.size = Eigen::Vector3f(maxP.x - minP.x, maxP.y - minP.y, maxP.z - minP.z);\n        box.position = Eigen::Vector3f(minP.x + (box.size[0] / 2),\n                minP.y + (box.size[1] / 2), minP.z + (box.size[2] / 2));\n        return box;\n    }\n\n    template\n    Utils::BoundingBox Utils::computeMVBB<PointT>(const pcl::PointCloud<PointT>::ConstPtr&);\n\n    template\n    Utils::BoundingBox Utils::computeMVBB<PointNormalT>(const pcl::PointCloud<PointNormalT>::ConstPtr&);\n\n    template<typename T>\n    Utils::BoundingBox Utils::computeMVBB(const typename pcl::PointCloud<T>::ConstPtr &model)\n    {\n        // remove nan points to avoid infinite loops\n        typename pcl::PointCloud<T>::Ptr cloud(new pcl::PointCloud<T>());\n        std::vector<int> indices;\n        pcl::removeNaNFromPointCloud(*model,*cloud, indices);\n\n        gdiam_real* points = (gdiam_point)malloc(sizeof(gdiam_point_t) * cloud->points.size());\n        assert(points != NULL);\n\n        for (int i = 0; i < (int)cloud->size(); i++) {\n            const T& point = cloud->at(i);\n            points[i * 3 + 0] = point.x;\n            points[i * 3 + 1] = point.y;\n            points[i * 3 + 2] = point.z;\n        }\n\n        // compute minimum volume bounding box\n        gdiam_point* pnt_arr = gdiam_convert((gdiam_real*)points, cloud->points.size());\n        gdiam_bbox bb = gdiam_approx_mvbb(pnt_arr, cloud->points.size(), 0.0);\n        free(points);\n\n        Eigen::Vector3d minP, maxP;\n        bb.get_min(&minP[0], &minP[1], &minP[2]);\n        bb.get_max(&maxP[0], &maxP[1], &maxP[2]);\n\n        Eigen::Vector3f dirX = Eigen::Vector3f(bb.get_dir(0)[0], bb.get_dir(0)[1], bb.get_dir(0)[2]);\n        Eigen::Vector3f dirY = Eigen::Vector3f(bb.get_dir(1)[0], bb.get_dir(1)[1], bb.get_dir(1)[2]);\n        Eigen::Vector3f dirZ = Eigen::Vector3f(bb.get_dir(2)[0], bb.get_dir(2)[1], bb.get_dir(2)[2]);\n        Eigen::Vector3f size = Eigen::Vector3f(maxP[0] - minP[0], maxP[1] - minP[1], maxP[2] - minP[2]);\n        Eigen::Vector3f pos = Eigen::Vector3f(minP[0] + (size[0] / 2.0f),\n                minP[1] + (size[1] / 2.0f), minP[2] + (size[2] / 2.0f));\n\n        Eigen::Matrix3f rot = Eigen::Matrix3f::Identity();\n        rot(0, 0) = dirX[0];\n        rot(1, 0) = dirX[1];\n        rot(2, 0) = dirX[2];\n        rot(0, 1) = dirY[0];\n        rot(1, 1) = dirY[1];\n        rot(2, 1) = dirY[2];\n        rot(0, 2) = dirZ[0];\n        rot(1, 2) = dirZ[1];\n        rot(2, 2) = dirZ[2];\n\n        Utils::BoundingBox box;\n        Utils::matrix2Quat(rot, box.rotQuat);\n        box.size = size;\n        box.position = pos;\n        Utils::quatRotate(box.rotQuat, box.position);\n\n        return box;\n    }\n\n    template\n    float Utils::computeCloudRadius<PointT>(const pcl::PointCloud<PointT>::Ptr &cloud);\n\n    template\n    float Utils::computeCloudRadius<PointNormalT>(const pcl::PointCloud<PointNormalT>::Ptr &cloud);\n\n    template<typename T>\n    float Utils::computeCloudRadius(const typename pcl::PointCloud<T>::Ptr &cloud)\n    {\n        // compute the object centroid\n        Eigen::Vector4f centroid4f;\n        pcl::compute3DCentroid(*cloud, centroid4f);\n        Eigen::Vector3f centroid(centroid4f[0], centroid4f[1], centroid4f[2]);\n\n        // compute radius (maximum distance of a point to centroid)\n        float radius = 0.0f;\n        for(const T &point : cloud->points)\n        {\n            Eigen::Vector3f eigpoint = point.getArray3fMap();\n            float temp_radius = (eigpoint-centroid).norm();\n            if(temp_radius > radius)\n            {\n                radius = temp_radius;\n            }\n        }\n        return radius;\n    }\n\n\n    // TODO VS check if this is ever used\n    float Utils::computeHingeLoss(const std::vector<float> &class_distances, const unsigned class_id)\n    {\n        float sum = 0;\n        float true_class_dist = fabs(class_distances.at(class_id));\n\n        for(int i = 0; i < class_distances.size(); i++)\n        {\n            if(class_id == i) continue;\n\n            float class_dist = fabs(class_distances.at(i));\n            sum += std::max(0.0f, class_dist - true_class_dist + 1);\n        }\n\n        return sum;\n    }\n\n\n    void Utils::matrix2Quat(const float* rot, float* quat)\n    {\n        // convert rotation matrix to quaternion (adapted from OgreQuaternion.cpp)\n\n        float matrix[3][3] = {\n            {rot[0], rot[1], rot[2]},\n            {rot[3], rot[4], rot[5]},\n            {rot[6], rot[7], rot[8]}\n        };\n\n        float trace = matrix[0][0] + matrix[1][1] + matrix[2][2];\n        float root;\n\n        if (trace > 0.0f) {\n            root = sqrtf(trace + 1.0f);\n            quat[3] = 0.5f * root;\n            root = 0.5f / root;\n\n            quat[0] = (matrix[2][1] - matrix[1][2]) * root;\n            quat[1] = (matrix[0][2] - matrix[2][0]) * root;\n            quat[2] = (matrix[1][0] - matrix[0][1]) * root;\n        }\n        else {\n            static size_t next[3] = {1, 2, 0};\n            size_t i = 0;\n            if (matrix[1][1] > matrix[0][0])\n                i = 1;\n            if (matrix[2][2] > matrix[i][i])\n                i = 2;\n            size_t j = next[i];\n            size_t k = next[j];\n\n            root = sqrtf(matrix[i][i] - matrix[j][j] - matrix[k][k] + 1.0);\n            float* apkQuat[3] = {&quat[0], &quat[1], &quat[2]};\n            *apkQuat[i] = 0.5f * root;\n            root = 0.5f / root;\n            quat[3] = (matrix[k][j] - matrix[j][k]) * root;\n            *apkQuat[j] = (matrix[j][i] + matrix[i][j]) * root;\n            *apkQuat[k] = (matrix[k][i] + matrix[i][k]) * root;\n        }\n    }\n\n    void Utils::matrix2Quat(const Eigen::Matrix3f& rot, boost::math::quaternion<float>& quat)\n    {\n        float q[4] = { quat.R_component_2(),\n            quat.R_component_3(),\n            quat.R_component_4(),\n            quat.R_component_1() };\n\n        matrix2Quat((float*)&rot(0, 0), q);\n\n        quat = boost::math::quaternion<float>(q[3], q[0], q[1], q[2]);\n    }\n\n    void Utils::quat2Matrix(const float* quat, float* rot)\n    {\n        // convert quaternion to rotation matrix (adapted from OgreQuaternion.cpp)\n\n        float tx = quat[0] + quat[0];\n        float ty = quat[1] + quat[1];\n        float tz = quat[2] + quat[2];\n        float twx = tx * quat[3];\n        float twy = ty * quat[3];\n        float twz = tz * quat[3];\n        float txx = tx * quat[0];\n        float txy = ty * quat[0];\n        float txz = tz * quat[0];\n        float tyy = ty * quat[1];\n        float tyz = tz * quat[1];\n        float tzz = tz * quat[2];\n\n        float matrix[3][3];\n\n        matrix[0][0] = 1.0 - (tyy + tzz);\n        matrix[0][1] = txy - twz;\n        matrix[0][2] = txz + twy;\n        matrix[1][0] = txy + twz;\n        matrix[1][1] = 1.0 - (txx + tzz);\n        matrix[1][2] = tyz - twx;\n        matrix[2][0] = txz - twy;\n        matrix[2][1] = tyz + twx;\n        matrix[2][2] = 1.0 - (txx + tyy);\n\n        rot[0] = matrix[0][0];\n        rot[1] = matrix[0][1];\n        rot[2] = matrix[0][2];\n        rot[3] = matrix[1][0];\n        rot[4] = matrix[1][1];\n        rot[5] = matrix[1][2];\n        rot[6] = matrix[2][0];\n        rot[7] = matrix[2][1];\n        rot[8] = matrix[2][2];\n    }\n\n    void Utils::quat2Matrix(const boost::math::quaternion<float>& quat, Eigen::Matrix3f& rot)\n    {\n        float q[4] = { quat.R_component_2(),\n            quat.R_component_3(),\n            quat.R_component_4(),\n            quat.R_component_1() };\n\n        quat2Matrix(q, (float*)&rot(0, 0));\n    }\n\n    void Utils::euler2Quat(boost::math::quaternion<float>& quat, float angleX, float angleY, float angleZ)\n    {\n        float r = deg2rad(angleX / 2.0f);\n        float p = deg2rad(angleY / 2.0f);\n        float y = deg2rad(angleZ / 2.0f);\n\n        float sinp = sinf(p);\n        float siny = sinf(y);\n        float sinr = sinf(r);\n        float cosp = cosf(p);\n        float cosy = cosf(y);\n        float cosr = cosf(r);\n\n        quat = boost::math::quaternion<float>(\n            cosr * cosp * cosy + sinr * sinp * siny,\n            sinr * cosp * cosy - cosr * sinp * siny,\n            cosr * sinp * cosy + sinr * cosp * siny,\n            cosr * cosp * siny - sinr * sinp * cosy);\n\n        // normalize\n        quat /= boost::math::norm(quat);\n    }\n\n    void Utils::quat2Euler(const boost::math::quaternion<float>& quat, float& angleX, float& angleY, float& angleZ)\n    {\n        boost::math::quaternion<float> myQuat = quat;\n        myQuat /= boost::math::norm(myQuat);\n\n        Eigen::Vector3f euler(0, 0, 0);\n\n        float qW = myQuat.R_component_1();\n        float qX = myQuat.R_component_2();\n        float qY = myQuat.R_component_3();\n        float qZ = myQuat.R_component_4();\n\n        float test = (qW * qY - qZ * qX);\n        float unit = qX * qX + qY * qY + qZ * qZ + qW * qW;\n\n        // handle singularities\n        if (test > 0.4999999f * unit) {\n            euler[0] = 2.0f * atan2(qX, qW);\n            euler[1] = M_PI / 2.0f;\n            euler[2] = 0;\n        }\n        else if (test < -0.4999999f * unit) {\n            euler[0] = 2.0f * atan2(qX, qW);\n            euler[1] = -M_PI / 2.0f;\n            euler[2] = 0;\n        }\n        else {\n            euler[0] = atan2(2.0f * (qW * qX + qY * qZ), 1.0f - 2.0f * (qX * qX + qY * qY));\n            euler[1] = asin(2.0f * test);\n            euler[2] = atan2(2.0f * (qW * qZ + qX * qY), 1.0f - 2.0f * (qY * qY + qZ * qZ));\n        }\n\n        angleX = rad2deg(euler[0]);\n        angleY = rad2deg(euler[1]);\n        angleZ = rad2deg(euler[2]);\n    }\n\n    void Utils::axis2Quat(boost::math::quaternion<float>& quat, const Eigen::Vector3f& axis, float angle)\n    {\n        Eigen::Vector3f myAxis = axis;\n        myAxis.normalize();\n\n        float halfAngle = deg2rad(angle / 2.0f);\n        float sinAngle = sinf(halfAngle);\n\n        quat = boost::math::quaternion<float>(cosf(halfAngle), myAxis[0] * sinAngle,\n                myAxis[1] * sinAngle, myAxis[2] * sinAngle);\n    }\n\n    void Utils::quat2Axis(const boost::math::quaternion<float>& quat, Eigen::Vector3f& axis, float& angle)\n    {\n        boost::math::quaternion<float> myQuat = quat;\n        float qw = myQuat.R_component_1();\n\n        // normalize\n        if (qw > 1.0f)\n            myQuat /= boost::math::norm(myQuat);\n\n        angle = rad2deg(2.0f * acos(qw));\n        float s = sqrtf(1.0f - qw * qw);\n\n        if (s < 0.0001f) {\n            // avoid divbyzero, any arbitrary axis is valid\n            axis[0] = 0;\n            axis[1] = 1;\n            axis[2] = 0;\n        }\n        else {\n            axis[0] = myQuat.R_component_2() / s;\n            axis[1] = myQuat.R_component_3() / s;\n            axis[2] = myQuat.R_component_4() / s;\n        }\n    }\n\n    void Utils::quatRotate(const boost::math::quaternion<float>& quat, Eigen::Vector3f& point)\n    {\n        boost::math::quaternion<float> pointTemp(0, point[0], point[1], point[2]);\n        pointTemp = boost::math::conj(quat) * pointTemp * quat;\n        point = Eigen::Vector3f(pointTemp.R_component_2(), pointTemp.R_component_3(),\n            pointTemp.R_component_4());\n    }\n\n    void Utils::quatRotateInv(const boost::math::quaternion<float>& quat, Eigen::Vector3f& point)\n    {\n        boost::math::quaternion<float> pointTemp(0, point[0], point[1], point[2]);\n        pointTemp = quat * pointTemp * boost::math::conj(quat);\n        point = Eigen::Vector3f(pointTemp.R_component_2(), pointTemp.R_component_3(),\n            pointTemp.R_component_4());\n    }\n\n    void Utils::quatGetRotationTo(boost::math::quaternion<float>& quat,\n                                  const Eigen::Vector3f& src, const Eigen::Vector3f& dest)\n    {\n        // Based on Stan Melax's article in Game Programming Gems\n\n        // Copy, since cannot modify local\n        Eigen::Vector3f v0 = src;\n        Eigen::Vector3f v1 = dest;\n        v0.normalize();\n        v1.normalize();\n\n        float d = v0.dot(v1);\n        // If dot == 1, vectors are the same\n        if (d >= 1.0f) {\n            // identity quaternion\n            quat = boost::math::quaternion<float>(1, 0, 0, 0);\n        }\n        else if (d < (1e-6f - 1.0f)) {\n            // Generate an axis\n            Eigen::Vector3f axis = Eigen::Vector3f(1, 0, 0).cross(src);\n            if (axis.norm() < (1e-06 * 1e-06)) // pick another if colinear\n                axis = Eigen::Vector3f(0, 1, 0).cross(src);\n            axis.normalize();\n            axis2Quat(quat, axis, M_PI);\n        }\n        else {\n            float s = sqrtf((1 + d) * 2);\n            float invS = 1 / s;\n\n            Eigen::Vector3f c = v0.cross(v1);\n\n            float x = c[0] * invS;\n            float y = c[1] * invS;\n            float z = c[2] * invS;\n            float w = s * 0.5f;\n\n            quat = boost::math::quaternion<float>(w, x, y, z);\n            quat /= boost::math::norm(quat);\n        }\n    }\n\n    void Utils::quatWeightedAverage(const std::vector<boost::math::quaternion<float> >& quaternions,\n                                    const std::vector<float>& weights,\n                                    boost::math::quaternion<float>& result)\n    {\n        Eigen::Matrix4f scatterMatrix;\n        scatterMatrix.setZero();\n\n        for (int i = 0; i < 4; i++) {\n            for (int j = 0; j < 4; j++) {\n                float value = 0;\n\n                #pragma omp parallel for\n                for (int k = 0; k < (int)quaternions.size(); k++)\n                {\n                    const boost::math::quaternion<float>& quat1 = quaternions[k];\n                    Eigen::Vector4f quatVec1(quat1.R_component_1(), quat1.R_component_2(), quat1.R_component_3(), quat1.R_component_4());\n                    float weight = weights[k];\n                    float factor = weight * quatVec1[i] * quatVec1[j];\n                    #pragma omp critical\n                    {\n                        value += factor;\n                    }\n                }\n                scatterMatrix(i, j) = value;\n            }\n        }\n\n        Eigen::EigenSolver<Eigen::Matrix4f> solver(scatterMatrix);\n        Eigen::EigenSolver<Eigen::Matrix4f>::EigenvalueType eigenvalues = solver.eigenvalues();\n        Eigen::EigenSolver<Eigen::Matrix4f>::EigenvectorsType eigenvectors = solver.eigenvectors();\n\n        int maxEigenvalueIndex = 0;\n        float maxEigenvalue = 0;\n        for (int i = 0; i < eigenvalues.cols(); i++) {\n            const std::complex<float> eigenvalue = eigenvalues[i];\n            if (eigenvalue.real() > maxEigenvalue) {\n                maxEigenvalue = eigenvalue.real();\n                maxEigenvalueIndex = i;\n            }\n        }\n\n        Eigen::Vector4cf maxEigenvector(eigenvectors(0, maxEigenvalueIndex),\n                                       eigenvectors(1, maxEigenvalueIndex),\n                                       eigenvectors(2, maxEigenvalueIndex),\n                                       eigenvectors(3, maxEigenvalueIndex));\n\n        result = boost::math::quaternion<float>(maxEigenvector[0].real(), maxEigenvector[1].real(),\n                maxEigenvector[2].real(), maxEigenvector[3].real());\n    }\n}\n", "meta": {"hexsha": "e0914d033873a61ef58a11eab5a5c3edc2299425", "size": 21949, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/implicit_shape_model/utils/utils.cpp", "max_stars_repo_name": "vseib/PointCloudNNOR", "max_stars_repo_head_hexsha": "1ba93fd06c530dad5221177b4c50d1bc679bda96", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/implicit_shape_model/utils/utils.cpp", "max_issues_repo_name": "vseib/PointCloudNNOR", "max_issues_repo_head_hexsha": "1ba93fd06c530dad5221177b4c50d1bc679bda96", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/implicit_shape_model/utils/utils.cpp", "max_forks_repo_name": "vseib/PointCloudNNOR", "max_forks_repo_head_hexsha": "1ba93fd06c530dad5221177b4c50d1bc679bda96", "max_forks_repo_licenses": ["BSD-3-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.7676923077, "max_line_length": 137, "alphanum_fraction": 0.5356963871, "num_tokens": 6386, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5621765008857981, "lm_q2_score": 0.546738151984614, "lm_q1q2_score": 0.3073633411834779}}
{"text": "/*******************************************************************************\n* nemesis. an experimental finite element code.                                *\n* Copyright (C) 2004-2011 F.E.Karaoulanis [http://www.nemesis-project.org]     *\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 3, as           *\n* published by the Free Software Foundation.                                   *\n*                                                                              *\n* This program is distributed in the hope that it will be useful,              *\n* but WITHOUT ANY WARRANTY; without even the implied warranty of               *\n* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the                *\n* GNU 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// $LastChangedDate$\n// $LastChangedRevision$\n// $LastChangedBy$\n// $HeadURL$\n// Author(s): F.E. Karaoulanis (fkar@nemesis-project.org)\n// *****************************************************************************\n\n#include \"reorderer/reverse_sloan.h\"\n#include <boost/graph/sloan_ordering.hpp>\n#include <stdio.h>\n#include \"analysis/analysis.h\"\n#include \"model/model.h\"\n\nReverseSloan::ReverseSloan(double w1, double w2)\n    : weight1(w1),\n      weight2(w2) {\n  myTag = TAG_REORDERER_REVERSE_SLOAN;\n}\n\nReverseSloan::~ReverseSloan() {\n}\n\nint ReverseSloan::get_perm(std::vector<int>& perm) {\n  // Create the Graph and additional vectors\n  UndirectedGraph G(pA->get_model()->get_num_eqns());\n  pA->get_model()->get_undirected_graph(&G);\n  property_map<UndirectedGraph, vertex_index_t>::type\n    index_map = get(vertex_index, G);\n  std::vector<int> inv_perm(num_vertices(G));\n  perm.resize(num_vertices(G));\n\n  // Find old bandwidth, profile and wavefronts\n  int oldBandwidth = bandwidth(G);\n  int oldProfile = profile(G);\n  /// @todo check for warnings in wavefront()\n  // double oldMaxWavefront = max_wavefront(G);\n  // double oldAverWavefront = aver_wavefront(G);\n  // double oldRmsWavefront = rms_wavefront(G);\n\n  // Call Sloan algorithm\n  sloan_ordering(G, inv_perm.rbegin(), get(vertex_color, G),\n    make_degree_map(G), get(vertex_priority, G), weight1, weight2);\n  for (unsigned k = 0; k != inv_perm.size(); k++)\n    perm[index_map[inv_perm[k]]]=k;\n\n  // Find new bandwidth and profile\n  int newBandwidth = bandwidth(G, make_iterator_property_map(&perm[0],\n                               index_map, perm[0]));\n  int newProfile = profile(G, make_iterator_property_map(&perm[0], index_map));\n  // double newMaxWavefront = max_wavefront(G,\n  //                          make_iterator_property_map(&perm[0], index_map));\n  // double newAverWavefront = aver_wavefront(G,\n  //                          make_iterator_property_map(&perm[0], index_map));\n  // double newRmsWavefront = rms_wavefront(G,\n  //                          make_iterator_property_map(&perm[0], index_map));\n\n  // Print optimized sizes\n  printf(\"reo: Optimized (original) bandwidth : %d (%d)\\n\",\n         newBandwidth, oldBandwidth);\n  printf(\"reo: Optimized (original) profile   : %d (%d)\\n\",\n         newProfile, oldProfile);\n  // cout   << \"rSloan: Optimized (original) maximum wavefront   : \"\n  //        <<newMaxWavefront   << \" (\" << oldMaxWavefront   << \")\" << endl;\n  // cout   << \"rSloan: Optimized (original) average wavefront   : \"\n  //        <<newAverWavefront  << \" (\" << oldAverWavefront  << \")\" << endl;\n  // cout   << \"rSloan: Optimized (original) rms wavefront       : \"\n  //        << newRmsWavefront  << \" (\" << oldRmsWavefront   << \")\" << endl;\n\n  // Check if optimization is needed\n  if (newBandwidth > oldBandwidth) return -1;\n  return 1;\n}\n", "meta": {"hexsha": "486a966e7eb4e99d1f3b9df060b5a3ec8f7c0b43", "size": 4212, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/reorderer/reverse_sloan.cc", "max_stars_repo_name": "karaoulanis/nemesis-code", "max_stars_repo_head_hexsha": "1ed488b389a552802ea910c9d8045f4cb0e57200", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-07-02T11:59:42.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-17T11:51:55.000Z", "max_issues_repo_path": "src/reorderer/reverse_sloan.cc", "max_issues_repo_name": "karaoulanis/nemesis-code", "max_issues_repo_head_hexsha": "1ed488b389a552802ea910c9d8045f4cb0e57200", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/reorderer/reverse_sloan.cc", "max_forks_repo_name": "karaoulanis/nemesis-code", "max_forks_repo_head_hexsha": "1ed488b389a552802ea910c9d8045f4cb0e57200", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 46.2857142857, "max_line_length": 80, "alphanum_fraction": 0.5529439696, "num_tokens": 948, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5621765008857982, "lm_q2_score": 0.5467381519846138, "lm_q1q2_score": 0.3073633411834779}}
{"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/Bag.h\"\n#include \"galois/Timer.h\"\n#include \"galois/Timer.h\"\n#include \"galois/graphs/Graph.h\"\n#include \"galois/graphs/LCGraph.h\"\n#include \"galois/Reduction.h\"\n#include \"galois/ParallelSTL.h\"\n#include \"galois/substrate/PaddedLock.h\"\n#include \"Lonestar/BoilerPlate.h\"\n#include <boost/iterator/transform_iterator.hpp>\n#include <boost/iterator/counting_iterator.hpp>\n\n#ifdef HAS_EIGEN\n#include <Eigen/Sparse>\n#endif\n\n#include <iostream>\n#include <cassert>\n#include <algorithm>\n#include <fstream>\n#include <vector>\n\n/**           CONFIG           **/\n\nstatic const char* const name =\n    \"Stochastic Gradient Descent for Linear Support Vector Machines\";\nstatic const char* const desc = \"Implements a linear support vector machine \"\n                                \"using stochastic gradient descent\";\nstatic const char* const url = \"sgdsvm\";\n\nenum class UpdateType {\n  Wild,\n  WildOrig,\n  ReplicateByThread,\n  ReplicateBySocket,\n  CycleBySocket,\n  Staleness\n};\n\nenum class AlgoType {\n  SGDL1,\n  SGDL2,\n  SGDLR,\n  DCDL1,\n  DCDL2,\n  DCDLR,\n  CDLasso,\n  LeastSquares,\n  GLMNETL1RLR,\n};\n\nnamespace cll = llvm::cl;\nstatic cll::opt<std::string> inputTrainGraphFilename(\n    cll::Positional, cll::desc(\"<training graph input file>\"), cll::Required);\nstatic cll::opt<std::string> inputTrainLabelFilename(\n    cll::Positional, cll::desc(\"<training label input file>\"), cll::Required);\nstatic cll::opt<std::string> inputTestGraphFilename(\n    cll::Positional, cll::desc(\"<testing graph input file>\"), cll::Required);\nstatic cll::opt<std::string> inputTestLabelFilename(\n    cll::Positional, cll::desc(\"<testing label input file>\"), cll::Required);\nstatic cll::opt<double>\n    creg(\"creg\", cll::desc(\"the regularization parameter C\"), cll::init(1.0));\nstatic cll::opt<bool>\n    shuffleSamples(\"shuffle\", cll::desc(\"shuffle samples between iterations\"),\n                   cll::init(true));\nstatic cll::opt<unsigned> SEED(\"seed\", cll::desc(\"random seed\"),\n                               cll::init(~0U));\nstatic cll::opt<bool> printObjective(\"printObjective\",\n                                     cll::desc(\"print objective value\"),\n                                     cll::init(true));\nstatic cll::opt<bool> printAccuracy(\"printAccuracy\",\n                                    cll::desc(\"print accuracy value\"),\n                                    cll::init(true));\nstatic cll::opt<double> tol(\"tol\", cll::desc(\"convergence tolerance\"),\n                            cll::init(0.1));\nstatic cll::opt<unsigned>\n    maxIterations(\"maxIterations\", cll::desc(\"maximum number of iterations\"),\n                  cll::init(1000));\nstatic cll::opt<bool>\n    useshrink(\"useshrink\",\n              cll::desc(\"use rhinking strategy for coordinate descent\"),\n              cll::init(true));\nstatic cll::opt<unsigned> fixedIterations(\n    \"fixedIterations\",\n    cll::desc(\"run specific number of iterations, ignoring convergence\"),\n    cll::init(0));\nstatic cll::opt<UpdateType> updateType(\n    \"update\", cll::desc(\"Update type:\"),\n    cll::values(clEnumValN(UpdateType::Wild, \"wild\",\n                           \"unsynchronized (default)\"),\n                clEnumValN(UpdateType::WildOrig, \"wildorig\", \"unsynchronized\"),\n                clEnumValN(UpdateType::ReplicateByThread, \"replicateByThread\",\n                           \"thread replication\"),\n                clEnumValN(UpdateType::ReplicateBySocket, \"replicateBySocket\",\n                           \"socket replication\"),\n                clEnumValN(UpdateType::CycleBySocket, \"cycleBySocket\",\n                           \"socket replication\"),\n                clEnumValN(UpdateType::Staleness, \"staleness\", \"stale reads\"),\n                clEnumValEnd),\n    cll::init(UpdateType::Wild));\nstatic cll::opt<AlgoType> algoType(\n    \"algo\", cll::desc(\"Algorithm:\"),\n    cll::values(\n        clEnumValN(AlgoType::SGDL1, \"sgdl1\",\n                   \"primal stochastic gradient descent hinge loss (default)\"),\n        clEnumValN(AlgoType::SGDL2, \"sgdl2\",\n                   \"primal stochastic gradient descent square-hinge loss\"),\n        clEnumValN(AlgoType::SGDLR, \"sgdlr\",\n                   \"primal stochastic gradient descent logistic regression\"),\n        clEnumValN(AlgoType::DCDL1, \"dcdl1\",\n                   \"Dual coordinate descent hinge loss\"),\n        clEnumValN(AlgoType::DCDL2, \"dcdl2\",\n                   \"Dual coordinate descent square-hinge loss\"),\n        clEnumValN(AlgoType::DCDLR, \"dcdlr\",\n                   \"Dual coordinate descent logistic regression\"),\n        clEnumValN(AlgoType::CDLasso, \"cdlasso\", \"Coordinate descent Lasso\"),\n        clEnumValN(AlgoType::GLMNETL1RLR, \"l1rlr\",\n                   \"new GLMENT for L1-regularized Logistic Regression\"),\n#ifdef HAS_EIGEN\n        clEnumValN(AlgoType::LeastSquares, \"ls\",\n                   \"minimize l2 norm of residual as least squares problem\"),\n#endif\n        clEnumValEnd),\n    cll::init(AlgoType::SGDL1));\n\n/**          DATA TYPES        **/\n\ntypedef struct Node {\n  // double w; //weight - relevant for variable nodes\n  union {\n    int field; // variable nodes - (1/variable count), sample nodes - label\n    int y;     // sample node label\n  };\n\n  union {\n    double alpha;   // sample node\n    double w;       // variable node\n    double exp_wTx; // sample node: newGLMNET;\n  };\n\n  union {\n    double QD;\n    double xTx;\n    double xTd;   // sample node: newGLMNET\n    double Hdiag; // variable node: newGLMNET\n  };\n\n  union {\n    double alpha2;\n    double b;\n    double exp_wTx_new; // sample node: newGLMNET;\n    double Grad;        // variable node: newGLMNET\n  };\n\n  union {\n    double D;   // sample node: newGLMNET\n    double wpd; // variable node: newGLMNET\n  };\n\n  union {\n    double tau;       // sample node: used for newGLMNET\n    double xjneg_sum; // variable node: newGLMNET\n  };\n\n  Node() : w(0.0), field(0), QD(0.0), alpha2(0.0), D(0.0), tau(0.0) {}\n} Node;\n\nusing Graph =\n    galois::graphs::LC_CSR_Graph<Node, double>::with_out_of_line_lockable<\n        true>::type ::with_numa_alloc<true>::type;\nusing GNode = Graph::GraphNode;\ntypedef galois::InsertBag<GNode> Bag;\n\n/**         CONSTANTS AND PARAMETERS       **/\nunsigned NUM_SAMPLES        = 0;\nunsigned NUM_VARIABLES      = 0;\nunsigned NUM_TEST_SAMPLES   = 0;\nunsigned NUM_TEST_VARIABLES = 0;\n\nunsigned variableNodeToId(GNode variable_node) {\n  return ((unsigned)variable_node) - NUM_SAMPLES;\n}\n\ngalois::substrate::PerThreadStorage<double*> thread_weights;\ngalois::substrate::PerSocketStorage<double*> socket_weights;\ngalois::LargeArray<double> old_weights;\n\n// undef to test specialization for dense feature space\n//#define DENSE\n//#define DENSE_NUM_FEATURES 500\n\ntemplate <typename T, UpdateType UT>\nclass DiffractedCollection {\n  galois::substrate::PerThreadStorage<unsigned> counts;\n  galois::substrate::PerThreadStorage<T*> thread;\n  galois::substrate::PerSocketStorage<T*> socket;\n  galois::LargeArray<T> old;\n  size_t size;\n  unsigned num_threads;\n  unsigned num_sockets;\n  unsigned block_size;\n\n  template <typename GetFn>\n  void doMerge(const GetFn& getFn) {\n    bool byThread =\n        UT == UpdateType::ReplicateByThread || UT == UpdateType::Staleness;\n    double* local = byThread ? *thread.getLocal() : *socket.getLocal();\n    unsigned n    = byThread ? num_threads : num_sockets;\n\n    if (true || UT == UpdateType::CycleBySocket ||\n        UT == UpdateType::ReplicateBySocket) {\n      galois::do_all(boost::counting_iterator<unsigned>(0),\n                     boost::counting_iterator<unsigned>(size), [&](unsigned i) {\n                       if (byThread) {\n                         int index = i % num_threads;\n                         local[i]  = (*thread.getRemote(index))[i];\n                       } else {\n                         int index = i % num_sockets;\n                         local[i]  = (*socket.getRemoteByPkg(index))[i];\n                       }\n                       auto& v = getFn(i);\n                       if (UT == UpdateType::Staleness)\n                         v = (old[i] = local[i]);\n                       else\n                         v = local[i];\n                     });\n    } else {\n      galois::do_all(boost::counting_iterator<unsigned>(0),\n                     boost::counting_iterator<unsigned>(size), [&](unsigned i) {\n                       for (unsigned j = 1; j < n; j++) {\n                         double o = byThread ? (*thread.getRemote(j))[i]\n                                             : (*socket.getRemoteByPkg(j))[i];\n                         local[i] += o;\n                       }\n                       local[i] /= n;\n                       auto& v = getFn(i);\n                       if (UT == UpdateType::Staleness)\n                         v = (old[i] = local[i]);\n                       else\n                         v = local[i];\n                     });\n    }\n\n    galois::on_each([&](unsigned tid, unsigned total) {\n      switch (UT) {\n      case UpdateType::Staleness:\n      case UpdateType::ReplicateByThread:\n        if (tid)\n          std::copy(local, local + size, *thread.getLocal());\n        break;\n      case UpdateType::CycleBySocket:\n      case UpdateType::ReplicateBySocket:\n        if (tid && galois::substrate::getThreadPool().isLeader(tid))\n          std::copy(local, local + size, *socket.getLocal());\n        break;\n      default:\n        abort();\n      }\n    });\n  }\n\npublic:\n  DiffractedCollection(size_t n) : size(n), block_size(0) {\n    num_threads = galois::getActiveThreads();\n    num_sockets = galois::substrate::getThreadPool().getCumulativeMaxSocket(\n                      num_threads - 1) +\n                  1;\n\n    if (UT == UpdateType::Staleness)\n      old.create(n);\n\n    if (UT == UpdateType::Staleness || UT == UpdateType::ReplicateByThread) {\n      galois::on_each([n, this](unsigned tid, unsigned total) {\n        T* p               = new T[n];\n        *thread.getLocal() = p;\n        std::fill(p, p + n, 0);\n      });\n    } else if (UT == UpdateType::ReplicateBySocket ||\n               UT == UpdateType::CycleBySocket) {\n      galois::on_each([n, this](unsigned tid, unsigned total) {\n        if (galois::substrate::getThreadPool().isLeader(tid)) {\n          T* p               = new T[n];\n          *socket.getLocal() = p;\n          std::fill(p, p + n, 0);\n        }\n      });\n    }\n\n    if (UT == UpdateType::CycleBySocket) {\n      block_size = size / (num_threads * num_sockets);\n    }\n  }\n\n  struct Accessor {\n    T* rptr;\n    T* wptr;\n    T* bptr;\n\n    Accessor(T* p) : rptr(p), wptr(p), bptr(nullptr) {}\n    Accessor(T* p1, T* p2) : rptr(p1), wptr(p2), bptr(nullptr) {}\n    Accessor(T* p1, T* p2, T* p3) : rptr(p1), wptr(p2), bptr(p3) {}\n\n    T& read(T& addr, ptrdiff_t x) {\n      switch (UT) {\n      case UpdateType::WildOrig:\n      case UpdateType::Wild:\n        return addr;\n      default:\n        return rptr[x];\n      }\n    }\n    T& write(T& addr, ptrdiff_t x) {\n      switch (UT) {\n      case UpdateType::WildOrig:\n      case UpdateType::Wild:\n        return addr;\n      default:\n        return wptr[x];\n      }\n    }\n    void writeBig(T& addr, const T& value) {\n      if (!bptr)\n        return;\n      assert(rptr == wptr);\n      bptr[std::distance(wptr, &addr)] = value;\n    }\n  };\n\n  Accessor get() {\n    // XXX\n    if ((UT == UpdateType::ReplicateBySocket ||\n         UT == UpdateType::CycleBySocket) &&\n        num_sockets > 1) {\n      unsigned tid       = galois::substrate::ThreadPool::getTID();\n      unsigned my_socket = galois::substrate::ThreadPool::getSocket();\n      if (UT == UpdateType::ReplicateBySocket || block_size == 0) {\n        unsigned next = (my_socket + 1) % num_sockets;\n        return Accessor{*socket.getLocal(), *socket.getLocal(),\n                        *socket.getRemoteByPkg(next)};\n      } else if (UT == UpdateType::CycleBySocket) {\n        unsigned v     = (*counts.getLocal())++;\n        unsigned index = v / block_size;\n        unsigned cur   = (my_socket + index) % num_sockets;\n        unsigned next  = (my_socket + index + 1) % num_sockets;\n        return Accessor{*socket.getRemoteByPkg(cur),\n                        *socket.getRemoteByPkg(cur),\n                        *socket.getRemoteByPkg(next)};\n      } else {\n        abort();\n      }\n    }\n\n    switch (UT) {\n    case UpdateType::Wild:\n    case UpdateType::WildOrig:\n    case UpdateType::Staleness:\n      return Accessor{&old[0], *thread.getLocal()};\n    case UpdateType::CycleBySocket:\n    case UpdateType::ReplicateBySocket:\n      return Accessor{*socket.getLocal()};\n    case UpdateType::ReplicateByThread:\n      return Accessor{*thread.getLocal()};\n    default:\n      abort();\n    }\n  }\n\n  template <typename GetFn>\n  void merge(const GetFn& getFn) {\n    switch (UT) {\n    case UpdateType::Wild:\n    case UpdateType::WildOrig:\n      return;\n    case UpdateType::CycleBySocket:\n    case UpdateType::Staleness:\n    case UpdateType::ReplicateBySocket:\n    case UpdateType::ReplicateByThread:\n      return doMerge(getFn);\n    default:\n      abort();\n    }\n  }\n};\n\ntemplate <UpdateType UT>\nstruct LogisticRegression {\n  typedef int tt_needs_per_iter_alloc;\n  typedef int tt_does_not_need_aborts;\n\n  Graph& g;\n  double learningRate;\n  galois::GAccumulator<size_t>& bigUpdates;\n  bool has_other;\n\n  AlgoType alg_type;\n  double* QD;\n  double* xTx;\n  double* alpha;\n  double innereps;\n  size_t* newton_iter;\n\n  double diag;\n  double C;\n\n#ifdef DENSE\n  Node* baseNodeData;\n  ptrdiff_t edgeOffset;\n  double* baseEdgeData;\n#endif\n  LogisticRegression(Graph& _g, double _lr, galois::GAccumulator<size_t>& b)\n      : g(_g), learningRate(_lr), bigUpdates(b) {\n    has_other = galois::substrate::getThreadPool().getCumulativeMaxSocket(\n                    galois::getActiveThreads() - 1) > 1;\n    alg_type = AlgoType::SGDL1;\n#ifdef DENSE\n    baseNodeData = &g.getData(g.getEdgeDst(g.edge_begin(0)));\n    edgeOffset   = std::distance(&g.getData(NUM_SAMPLES), baseNodeData);\n    baseEdgeData = &g.getEdgeData(g.edge_begin(0));\n#endif\n  }\n\n  LogisticRegression(Graph& _g, galois::GAccumulator<size_t>& b, double* _alpha,\n                     double* _qd, bool useL1Loss)\n      : g(_g), bigUpdates(b), alpha(_alpha), QD(_qd) {\n    has_other = galois::substrate::getThreadPool().getCumulativeMaxSocket(\n                    galois::getActiveThreads() - 1) > 1;\n\n    diag = 0.5 / creg;\n    C    = std::numeric_limits<double>::max();\n    if (useL1Loss) {\n      diag = 0;\n      C    = creg;\n    }\n\n    if (useL1Loss)\n      alg_type = AlgoType::DCDL1;\n    else\n      alg_type = AlgoType::DCDL2;\n#ifdef DENSE\n    baseNodeData = &g.getData(g.getEdgeDst(g.edge_begin(0)));\n    edgeOffset   = std::distance(&g.getData(NUM_SAMPLES), baseNodeData);\n    baseEdgeData = &g.getEdgeData(g.edge_begin(0));\n#endif\n  }\n\n  LogisticRegression(Graph& _g, galois::GAccumulator<size_t>& b, double* _alpha,\n                     double* _xTx, double _innereps, size_t* _newton_iter)\n      : g(_g), bigUpdates(b), alpha(_alpha), xTx(_xTx), innereps(_innereps),\n        newton_iter(_newton_iter) {\n    has_other = galois::substrate::getThreadPool().getCumulativeMaxSocket(\n                    galois::getActiveThreads() - 1) > 1;\n\n    C        = creg;\n    alg_type = AlgoType::DCDLR;\n\n#ifdef DENSE\n    baseNodeData = &g.getData(g.getEdgeDst(g.edge_begin(0)));\n    edgeOffset   = std::distance(&g.getData(NUM_SAMPLES), baseNodeData);\n    baseEdgeData = &g.getEdgeData(g.edge_begin(0));\n#endif\n  }\n\n  void operator()(GNode n, galois::UserContext<GNode>& ctx) {\n    Node& sample_data = g.getData(n);\n\n    // Gather\n    double dot = 0.0;\n    for (auto edge_it : g.out_edges(n, galois::MethodFlag::UNPROTECTED)) {\n      GNode variable_node = g.getEdgeDst(edge_it);\n      Node& var_data =\n          g.getData(variable_node, galois::MethodFlag::UNPROTECTED);\n      double weight = var_data.w;\n      dot += weight * g.getEdgeData(edge_it, galois::MethodFlag::UNPROTECTED);\n    }\n\n    int label = sample_data.field;\n    double d  = 0.0;\n\n    // For Coordinate Descent\n    if (alg_type == AlgoType::DCDLR) { // Added by Rofu\n      int yi      = label > 0 ? 1 : -1;\n      double ywTx = dot * yi, xisq = sample_data.xTx;\n      double alpha[2] = {sample_data.alpha, sample_data.alpha2};\n      // double &alpha = sample_data.alpha, &alpha2 = sample_data.alpha2;\n      double a = xisq, b = ywTx;\n\n      // Decide to minimize g_1(z) or g_2(z)\n      int ind1 = 0, ind2 = 1, sign = 1;\n      if (0.5 * a * (alpha[ind2] - alpha[ind1]) + b < 0) {\n        ind1 = 1;\n        ind2 = 0;\n        sign = -1;\n      }\n\n      //  g_t(z) = z*log(z) + (C-z)*log(C-z) + 0.5a(z-alpha_old)^2 +\n      //  sign*b(z-alpha_old)\n      double alpha_old = alpha[ind1];\n      double z         = alpha_old;\n      if (C - z < 0.5 * C)\n        z = 0.1 * z;\n      double gp = a * (z - alpha_old) + sign * b + log(z / (C - z));\n\n      // Newton method on the sub-problem\n      const double eta         = 0.1; // xi in the paper\n      const int max_inner_iter = 100;\n      int inner_iter           = 0;\n      while (inner_iter <= max_inner_iter) {\n        if (fabs(gp) < innereps)\n          break;\n        double gpp  = a + C / (C - z) / z;\n        double tmpz = z - gp / gpp;\n        if (tmpz <= 0)\n          z *= eta;\n        else // tmpz in (0, C)\n          z = tmpz;\n        gp = a * (z - alpha_old) + sign * b + log(z / (C - z));\n        inner_iter++;\n      }\n      *newton_iter += inner_iter;\n      alpha[ind1]        = z;\n      alpha[ind2]        = C - z;\n      sample_data.alpha  = alpha[0];\n      sample_data.alpha2 = alpha[1];\n      d                  = sign * (z - alpha_old) * yi;\n      if (d == 0)\n        return;\n    }\n\n    for (auto edge_it : g.out_edges(n, galois::MethodFlag::UNPROTECTED)) {\n      GNode variable_node = g.getEdgeDst(edge_it);\n      Node& var_data =\n          g.getData(variable_node, galois::MethodFlag::UNPROTECTED);\n\n      double delta = -d * g.getEdgeData(edge_it);\n      var_data.w -= delta;\n    }\n  }\n};\n\ntypedef struct {\n  std::vector<double> QD;\n  std::vector<double> alpha;\n  double diag;\n  double C;\n\n  double PG;\n  double PGmax_old;\n  double PGmin_old;\n  // double PGmax_new;\n  // double PGmin_new;\n  size_t active_size;\n  galois::GReduceMax<double> PGmax_new;\n  galois::GReduceMin<double> PGmin_new;\n\n  std::vector<bool> isactive;\n} DCD_parameters;\n\ntemplate <UpdateType UT>\nstruct linearSVM_DCD {\n  typedef int tt_needs_per_iter_alloc;\n  typedef int tt_does_not_need_aborts;\n\n  Graph& g;\n  galois::GAccumulator<size_t>& bigUpdates;\n  Bag* next_bag;\n  bool has_other;\n\n  double diag;\n  double C;\n  DCD_parameters* params;\n\n#ifdef DENSE\n  Node* baseNodeData;\n  ptrdiff_t edgeOffset;\n  double* baseEdgeData;\n#endif\n\n  linearSVM_DCD(Graph& _g, galois::GAccumulator<size_t>& b,\n                DCD_parameters* _params, Bag* _next_bag = NULL)\n      : g(_g), bigUpdates(b), diag(_params->diag), C(_params->C),\n        params(_params), next_bag(_next_bag) {\n    has_other = galois::substrate::getThreadPool().getCumulativeMaxSocket(\n                    galois::getActiveThreads() - 1) > 1;\n\n#ifdef DENSE\n    baseNodeData = &g.getData(g.getEdgeDst(g.edge_begin(0)));\n    edgeOffset   = std::distance(&g.getData(NUM_SAMPLES), baseNodeData);\n    baseEdgeData = &g.getEdgeData(g.edge_begin(0));\n#endif\n  }\n\n  void operator()(GNode n, galois::UserContext<GNode>& ctx) {\n\n    // if (!params->isactive[n]) return;\n    Node& sample_data = g.getData(n);\n\n    // Gather\n    double dot = 0.0;\n    for (auto edge_it : g.out_edges(n, galois::MethodFlag::UNPROTECTED)) {\n      GNode variable_node = g.getEdgeDst(edge_it);\n      Node& var_data =\n          g.getData(variable_node, galois::MethodFlag::UNPROTECTED);\n      double weight = var_data.w;\n      dot += weight * g.getEdgeData(edge_it, galois::MethodFlag::UNPROTECTED);\n    }\n\n    int label = sample_data.field;\n    double d  = 0.0;\n\n    double& nowalpha = sample_data.alpha;\n    double a         = nowalpha;\n    double G         = dot * label - 1 + nowalpha * diag;\n    double PG        = 0;\n\n    if (useshrink == true) {\n      if (a == 0) {\n        if (G > params->PGmax_old) {\n          //(params->isactive)[n] = false;\n          // params->active_size--;\n          return;\n        } else if (G < 0) {\n          PG = G;\n        }\n      } else if (a == C) {\n        if (G < params->PGmin_old) {\n          //(params->isactive)[n] = false;\n          // params->active_size--;\n          return;\n        } else if (G > 0) {\n          PG = G;\n        }\n      } else {\n        PG = G;\n      }\n      next_bag->push(n);\n\n      params->PGmax_new.update(PG);\n      params->PGmin_new.update(PG);\n      // params->PGmax_new = std::max(params->PGmax_new, PG);\n      // params->PGmin_new = std::min(params->PGmin_new, PG);\n    }\n\n    nowalpha = std::min(std::max(a - G / sample_data.QD, 0.0), C);\n    d        = (nowalpha - a) * label;\n    if (d == 0.0)\n      return;\n\n    for (auto edge_it : g.out_edges(n, galois::MethodFlag::UNPROTECTED)) {\n      GNode variable_node = g.getEdgeDst(edge_it);\n      Node& var_data =\n          g.getData(variable_node, galois::MethodFlag::UNPROTECTED);\n\n      double delta = -d * g.getEdgeData(edge_it);\n      var_data.w -= delta;\n    }\n  }\n};\n\n// SGD for linearSVM and logistic regression -- only for wild update\nstruct LinearSGDWild {\n  Graph& g;\n  double learningRate;\n  bool has_other;\n\n  LinearSGDWild(Graph& _g, double _lr) : g(_g), learningRate(_lr) {}\n\n  void operator()(GNode n, galois::UserContext<GNode>& ctx) {\n    Node& sample_data = g.getData(n);\n    double invcreg    = 1.0 / creg;\n    // Gather\n    double dot = 0.0;\n    for (auto edge_it : g.out_edges(n, galois::MethodFlag::UNPROTECTED)) {\n      GNode variable_node = g.getEdgeDst(edge_it);\n      Node& var_data =\n          g.getData(variable_node, galois::MethodFlag::UNPROTECTED);\n      double weight = var_data.w;\n      dot += weight * g.getEdgeData(edge_it, galois::MethodFlag::UNPROTECTED);\n    }\n\n    int label = sample_data.field;\n\n    bool bigUpdate = true;\n    if ((algoType == AlgoType::SGDL1) || (algoType == AlgoType::SGDL2))\n      bigUpdate = label * dot < 1;\n\n    double d = 0.0;\n    if (algoType == AlgoType::SGDL1)\n      d = 1.0;\n    else if (algoType == AlgoType::SGDL2)\n      d = 2 * (1 - label * dot);\n    else if (algoType == AlgoType::SGDLR)\n      d = 1 / (1 + exp(dot * label));\n\n    for (auto edge_it : g.out_edges(n, galois::MethodFlag::UNPROTECTED)) {\n      GNode variable_node = g.getEdgeDst(edge_it);\n      Node& var_data =\n          g.getData(variable_node, galois::MethodFlag::UNPROTECTED);\n      int varCount   = var_data.field;\n      double rfactor = var_data.QD;\n      double delta   = 0;\n      if (bigUpdate == true)\n        delta = learningRate *\n                (var_data.w * rfactor -\n                 d * label *\n                     g.getEdgeData(edge_it, galois::MethodFlag::UNPROTECTED));\n      else\n        delta = learningRate * (var_data.w * rfactor);\n      var_data.w -= delta;\n    }\n  }\n};\n\n// SGD for linearSVM and logistic regression\ntemplate <UpdateType UT>\nstruct LinearSGD {\n  typedef int tt_needs_per_iter_alloc;\n  typedef int tt_does_not_need_aborts;\n\n  Graph& g;\n  DiffractedCollection<double, UT>& dstate;\n  double learningRate;\n\n#ifdef DENSE\n  Node* baseNodeData;\n  ptrdiff_t edgeOffset;\n  double* baseEdgeData;\n#endif\n\n  LinearSGD(Graph& _g, DiffractedCollection<double, UT>& d, double _lr)\n      : g(_g), dstate(d), learningRate(_lr) {\n#ifdef DENSE\n    baseNodeData = &g.getData(g.getEdgeDst(g.edge_begin(0)));\n    edgeOffset   = std::distance(&g.getData(NUM_SAMPLES), baseNodeData);\n    baseEdgeData = &g.getEdgeData(g.edge_begin(0));\n#endif\n  }\n\n  void operator()(GNode n, galois::UserContext<GNode>& ctx) {\n    galois::PerIterAllocTy& alloc = ctx.getPerIterAlloc();\n\n    // Store edge data in iteration-local temporary to reduce cache misses\n#ifdef DENSE\n    const ptrdiff_t size = DENSE_NUM_FEATURES;\n#else\n    ptrdiff_t size = std::distance(g.edge_begin(n), g.edge_end(n));\n#endif\n    // regularized factors\n    double* rfactors = (double*)alloc.allocate(sizeof(double) * size);\n    // document weights\n    double* dweights = (double*)alloc.allocate(sizeof(double) * size);\n    // model weights\n    double* mweights = (double*)alloc.allocate(sizeof(double) * size);\n    // write destinations\n    double** wptrs = (double**)alloc.allocate(sizeof(double*) * size);\n\n    // Gather\n    size_t cur = 0;\n    double dot = 0.0;\n    auto d     = dstate.get();\n#ifdef DENSE\n    double* myEdgeData = &baseEdgeData[size * n];\n    for (cur = 0; cur < size;) {\n      int varCount = baseNodeData[cur].field;\n#else\n    for (auto edge_it : g.out_edges(n, galois::MethodFlag::UNPROTECTED)) {\n      GNode variable_node = g.getEdgeDst(edge_it);\n      Node& var_data =\n          g.getData(variable_node, galois::MethodFlag::UNPROTECTED);\n      int varCount  = var_data.field;\n#endif\n\n      double weight;\n#ifdef DENSE\n      weight = d.read(baseNodeData[cur].w, cur + edgeOffset);\n#else\n      wptrs[cur]    = &d.write(var_data.w, variableNodeToId(variable_node));\n      weight        = d.read(var_data.w, variableNodeToId(variable_node));\n#endif\n      mweights[cur] = weight;\n#ifdef DENSE\n      dweights[cur] = myEdgeData[cur];\n#else\n      dweights[cur] = g.getEdgeData(edge_it);\n#endif\n      if (UT == UpdateType::WildOrig) {\n        rfactors[cur] = (creg * varCount);\n      } else {\n        rfactors[cur] = mweights[cur] / (creg * varCount);\n      }\n      dot += mweights[cur] * dweights[cur];\n      cur += 1;\n    }\n\n    Node& sample_data = g.getData(n);\n    int label         = sample_data.field;\n\n    bool bigUpdate = algoType == AlgoType::SGDLR || label * dot < 1;\n    double dd      = 0.0;\n    // TODO account for these ops\n    if (algoType == AlgoType::SGDL1)\n      dd = 1.0;\n    else if (algoType == AlgoType::SGDL2)\n      dd = 2 * (1 - label * dot);\n    else if (algoType == AlgoType::SGDLR)\n      dd = 1 / (1 + exp(dot * label));\n\n    for (cur = 0; cur < size; ++cur) {\n      double delta;\n      if (UT == UpdateType::WildOrig) {\n        if (bigUpdate)\n          delta = learningRate *\n                  (*wptrs[cur] / rfactors[cur] - dd * label * dweights[cur]);\n        else\n          delta = *wptrs[cur] / rfactors[cur];\n      } else {\n        if (bigUpdate)\n          delta = learningRate * (rfactors[cur] - dd * label * dweights[cur]);\n        else\n          delta = rfactors[cur];\n      }\n#ifdef DENSE\n      d.write(baseNodeData[cur].w, cur + edgeOffset) = mweights[cur] - delta;\n#else\n      if (UT == UpdateType::WildOrig) {\n        double v    = *wptrs[cur] - delta;\n        *wptrs[cur] = v;\n        if (bigUpdate)\n          d.writeBig(*wptrs[cur], v);\n      } else {\n        double v    = mweights[cur] - delta;\n        *wptrs[cur] = v;\n        if (bigUpdate)\n          d.writeBig(*wptrs[cur], v);\n      }\n#endif\n    }\n  }\n};\n\ntypedef struct {\n  double Gmax_old;\n  double Gnorm1_init;\n  galois::GReduceMax<double> Gmax_new;\n  galois::GAccumulator<double> Gnorm1_new;\n} CD_parameters;\n\n// Primal CD for Lasso\ntemplate <UpdateType UT>\nstruct Lasso_CD {\n  Graph& g;\n  double lambda;\n  CD_parameters* params;\n  Bag* next_bag;\n\n  enum { COMP, UPDATE };\n  struct Task {\n    int type;\n    GNode target;\n    // int target;\n    double arg;\n  };\n\n  struct Initializer : public std::unary_function<GNode, Task> {\n    Task operator()(GNode arg) const { return {COMP, arg, 0.0}; }\n  };\n\n  Lasso_CD(Graph& _g, CD_parameters* _params, Bag* _next_bag = NULL)\n      : g(_g), params(_params), next_bag(_next_bag) {\n    lambda = 0.5 / creg;\n  }\n\n  //  void operator()(GNode n, galois::UserContext<GNode>& ctx) {\n  void operator()(const Task& t, galois::UserContext<Task>& ctx) {\n    if (t.type == COMP) {\n      do_comp(t, ctx);\n    } else if (t.type == UPDATE) {\n      do_update(t, ctx);\n    }\n  }\n\n  void do_update(const Task& t, galois::UserContext<Task>& ctx) {\n    Node& var_data = g.getData(t.target);\n    var_data.alpha += t.arg;\n  }\n\n  void do_comp(const Task& t, galois::UserContext<Task>& ctx) {\n    GNode n        = t.target;\n    Node& var_data = g.getData(n);\n    double& w      = var_data.w;\n\n    if (var_data.xTx == 0.0)\n      return;\n    double wold = w;\n    double ainv = var_data.xTx;\n\n    double dot = 0.0;\n    for (auto edge_it : g.out_edges(n, galois::MethodFlag::UNPROTECTED)) {\n      GNode sample_node = g.getEdgeDst(edge_it);\n      Node& sample_data =\n          g.getData(sample_node, galois::MethodFlag::UNPROTECTED);\n      double r = sample_data.alpha;\n      dot += r * g.getEdgeData(edge_it, galois::MethodFlag::UNPROTECTED);\n    }\n\n    double violation = 0;\n    if (useshrink) {\n      double G  = dot * 2 * creg;\n      double Gp = G + 1;\n      double Gn = G - 1;\n      if (wold == 0) {\n        if (Gp < 0)\n          violation = -Gp;\n        else if (Gn > 0)\n          violation = Gn;\n        else if (Gp > (params->Gmax_old / NUM_SAMPLES) &&\n                 Gn < -(params->Gmax_old / NUM_SAMPLES))\n          return;\n      } else if (wold > 0) {\n        violation = std::fabs(Gp);\n      } else {\n        violation = std::fabs(Gn);\n      }\n\n      params->Gmax_new.update(violation);\n      params->Gnorm1_new += violation;\n      next_bag->push(n);\n    }\n    double z       = wold - dot * ainv;\n    double lambda1 = lambda * ainv;\n\n    double wnew = std::max(std::fabs(z) - lambda1, 0.0);\n    if (z < 0)\n      wnew = -wnew;\n    double delta = wnew - wold;\n    if (std::fabs(delta) > 1e-12) {\n      w = wnew;\n      for (auto edge_it : g.out_edges(n, galois::MethodFlag::UNPROTECTED)) {\n        GNode sample_node = g.getEdgeDst(edge_it);\n        //\t\t\tNode& sample_data = g.getData(sample_node,\n        //galois::MethodFlag::UNPROTECTED);\n\n        double update_val =\n            delta * g.getEdgeData(edge_it, galois::MethodFlag::UNPROTECTED);\n        ctx.push(Task{UPDATE, sample_node, update_val});\n\n        //\t\t\tsample_data.alpha += delta*g.getEdgeData(edge_it,\n        //galois::MethodFlag::UNPROTECTED);\n      }\n    }\n  }\n};\n\ndouble getDualObjective(Graph& g, const std::vector<GNode>& trainingSamples,\n                        double* diag, const std::vector<double>& alpha) {\n  // 0.5 * w^Tw + C * sum_i [max(0, 1 - y_i * w^T * x_i)]^2\n  galois::GAccumulator<double> objective;\n\n  galois::do_all(trainingSamples.begin(), trainingSamples.end(), [&](GNode n) {\n    Node& data = g.getData(n);\n    int label  = g.getData(n).field;\n    objective += alpha[n] * (alpha[n] * diag[label + 1] - 2);\n  });\n\n  galois::do_all(boost::counting_iterator<size_t>(0),\n                 boost::counting_iterator<size_t>(NUM_VARIABLES),\n                 [&](size_t i) {\n                   double v = g.getData(i + NUM_SAMPLES).w;\n                   objective += v * v;\n                 });\n  return objective.reduce();\n}\n\nvoid printParameters(const std::vector<GNode>& trainingSamples,\n                     const std::vector<GNode>& testingSamples) {\n  std::cout << \"Input Train graph file: \" << inputTrainGraphFilename << \"\\n\";\n  std::cout << \"Input Train label file: \" << inputTrainLabelFilename << \"\\n\";\n  std::cout << \"Input Test graph file: \" << inputTestGraphFilename << \"\\n\";\n  std::cout << \"Input Test label file: \" << inputTestLabelFilename << \"\\n\";\n  std::cout << \"Threads: \" << galois::getActiveThreads() << \"\\n\";\n  std::cout << \"Train Samples: \" << NUM_SAMPLES << \"\\n\";\n  std::cout << \"Test Samples: \" << NUM_TEST_SAMPLES << \"\\n\";\n  std::cout << \"Variables: \" << NUM_VARIABLES << \"\\n\";\n  std::cout << \"Test Variables: \" << NUM_TEST_VARIABLES << \"\\n\";\n  std::cout << \"Training samples: \" << trainingSamples.size() << \"\\n\";\n  std::cout << \"Testing samples: \" << testingSamples.size() << \"\\n\";\n  std::cout << \"Algo type: \";\n  switch (algoType) {\n  case AlgoType::SGDL1:\n    std::cout << \"primal stocahstic gradient descent for hinge Loss\";\n    break;\n  case AlgoType::SGDL2:\n    std::cout << \"primal stocahstic gradient descent for square-hinge Loss\";\n    break;\n  case AlgoType::SGDLR:\n    std::cout << \"primal stocahstic gradient descent for logistic Loss\";\n    break;\n  case AlgoType::DCDL1:\n    std::cout << \"dual coordinate descent hinge loss parallel\";\n    break;\n  case AlgoType::DCDL2:\n    std::cout << \"dual coordinate descent square-hinge loss parallel\";\n    break;\n  case AlgoType::DCDLR:\n    std::cout << \"dual coordinate descent logsitic regression\";\n    break;\n  case AlgoType::CDLasso:\n    std::cout << \"coordinate descent lasso\";\n    break;\n  case AlgoType::GLMNETL1RLR:\n    std::cout << \"new GLMNET l1r-lr\";\n    break;\n  case AlgoType::LeastSquares:\n    std::cout << \"least squares\";\n    break;\n  default:\n    abort();\n  }\n  std::cout << \"\\n\";\n\n  std::cout << \"Update type: \";\n  switch (updateType) {\n  case UpdateType::Wild:\n    std::cout << \"wild\";\n    break;\n  case UpdateType::WildOrig:\n    std::cout << \"wild orig\";\n    break;\n  case UpdateType::ReplicateByThread:\n    std::cout << \"replicate by thread\";\n    break;\n  case UpdateType::ReplicateBySocket:\n    std::cout << \"replicate by socket\";\n    break;\n  case UpdateType::CycleBySocket:\n    std::cout << \"cycle by socket\";\n    break;\n  case UpdateType::Staleness:\n    std::cout << \"stale reads\";\n    break;\n  default:\n    abort();\n  }\n  std::cout << \"\\n\";\n}\n\nvoid initializeVariableCounts(Graph& g) {\n  for (auto n : g) {\n    for (auto edge_it : g.out_edges(n)) {\n      GNode variable_node = g.getEdgeDst(edge_it);\n      Node& data          = g.getData(variable_node);\n      data.field++; // increase count of variable occurrences\n    }\n  }\n  for (auto n : g) {\n    if (n >= NUM_SAMPLES) {\n      Node& data = g.getData(n);\n      if (data.field != 0)\n        data.QD = 1.0 / (creg * data.field);\n    }\n  }\n}\n\nunsigned loadb(Graph& g, std::string filename) {\n  std::ifstream infile(filename);\n\n  unsigned sample_id;\n  double bi;\n  int num_labels = 0;\n  while (infile >> sample_id >> bi) {\n    g.getData(sample_id).b = bi;\n    ++num_labels;\n  }\n\n  return num_labels;\n}\n\nunsigned loadLabels(Graph& g, std::string filename) {\n  std::ifstream infile(filename);\n\n  unsigned sample_id;\n  int label;\n  int num_labels = 0;\n  while (infile >> sample_id >> label) {\n    if (label > 0)\n      g.getData(sample_id).field = 1;\n    else\n      g.getData(sample_id).field = -1;\n    ++num_labels;\n  }\n\n  return num_labels;\n}\n\nsize_t getNumCorrect(Graph& g_test, std::vector<GNode>& testing_samples,\n                     Graph& g_train) {\n  galois::GAccumulator<size_t> correct;\n\n  std::vector<double> w_vec(NUM_VARIABLES);\n  galois::do_all(g_train.begin() + NUM_SAMPLES, g_train.end(), [&](GNode n) {\n    Node& data             = g_train.getData(n);\n    w_vec[n - NUM_SAMPLES] = data.w;\n  });\n\n  galois::do_all(testing_samples.begin(), testing_samples.end(), [&](GNode n) {\n    double sum = 0.0;\n    Node& data = g_test.getData(n);\n    int label  = data.field;\n    for (auto edge_it : g_test.out_edges(n)) {\n      GNode variable_node = g_test.getEdgeDst(edge_it);\n      if ((variable_node - NUM_TEST_SAMPLES) < NUM_VARIABLES) {\n        double weight = g_test.getEdgeData(edge_it);\n        sum += w_vec[variable_node - NUM_TEST_SAMPLES] * weight;\n      }\n    }\n\n    if (sum <= 0.0 && label == -1) {\n      correct += 1;\n    } else if (sum > 0.0 && label == 1) {\n      correct += 1;\n    }\n  });\n\n  return correct.reduce();\n}\n\ndouble getTestRMSE(Graph& g_test, std::vector<GNode>& testing_samples,\n                   Graph& g_train) {\n  galois::GAccumulator<double> square_err;\n\n  std::vector<double> w_vec(NUM_VARIABLES);\n  galois::do_all(g_train.begin() + NUM_SAMPLES, g_train.end(), [&](GNode n) {\n    Node& data             = g_train.getData(n);\n    w_vec[n - NUM_SAMPLES] = data.w;\n  });\n\n  double wnorm = 0;\n  for (auto i : w_vec)\n    wnorm += i * i;\n  //  printf(\"wnorm: %lf, umvariables: %d\\n\", wnorm, NUM_VARIABLES);\n\n  galois::do_all(testing_samples.begin(), testing_samples.end(), [&](GNode n) {\n    double sum = 0.0;\n    Node& data = g_test.getData(n);\n    double b   = data.b;\n    for (auto edge_it : g_test.out_edges(n)) {\n      GNode variable_node = g_test.getEdgeDst(edge_it);\n      if ((variable_node - NUM_TEST_SAMPLES) < NUM_VARIABLES) {\n        double weight = g_test.getEdgeData(edge_it);\n        sum += w_vec[variable_node - NUM_TEST_SAMPLES] * weight;\n      }\n    }\n    square_err += (sum - b) * (sum - b);\n  });\n\n  double err = square_err.reduce();\n  //  printf(\"err: %lf\\n\", err);\n  return sqrt(err / NUM_TEST_SAMPLES);\n  //  return correct.reduce();\n}\n\ndouble getPrimalObjective(Graph& g, const std::vector<GNode>& trainingSamples) {\n  // 0.5 * w^Tw + C * sum_i loss(w^T * x_i, y_i)\n  //// 0.5 * w^Tw + C * sum_i [max(0, 1 - y_i * w^T * x_i)]^2\n  galois::GAccumulator<double> objective;\n\n  galois::do_all(trainingSamples.begin(), trainingSamples.end(), [&](GNode n) {\n    double sum = 0.0;\n    Node& data = g.getData(n);\n    int label  = data.field;\n    double b;\n    if (algoType == AlgoType::CDLasso)\n      b = data.b;\n    for (auto edge_it : g.out_edges(n)) {\n      GNode variable_node = g.getEdgeDst(edge_it);\n      Node& data          = g.getData(variable_node);\n      double weight       = g.getEdgeData(edge_it);\n      sum += data.w * weight;\n    }\n\n    double o;\n    if ((algoType == AlgoType::DCDL2) || (algoType == AlgoType::SGDL2)) {\n      o = std::max(0.0, 1 - label * sum);\n      o = o * o;\n    } else if ((algoType == AlgoType::DCDLR) || (algoType == AlgoType::SGDLR) ||\n               (algoType == AlgoType::GLMNETL1RLR))\n      o = log(1 + exp(-label * sum));\n    else if ((algoType == AlgoType::DCDL1) || (algoType == AlgoType::SGDL1))\n      o = std::max(0.0, 1 - label * sum);\n    else if (algoType == AlgoType::CDLasso)\n      o = (sum - b) * (sum - b);\n    objective += o;\n  });\n\n  galois::GAccumulator<double> norm;\n  galois::do_all(\n      boost::counting_iterator<size_t>(0),\n      boost::counting_iterator<size_t>(NUM_VARIABLES), [&](size_t i) {\n        double v = g.getData(i + NUM_SAMPLES).w;\n        if (algoType == AlgoType::CDLasso || algoType == AlgoType::GLMNETL1RLR)\n          norm += std::fabs(v);\n        else\n          norm += 0.5 * v * v;\n      });\n  return objective.reduce() * creg + norm.reduce();\n}\n\nvoid runDCD(Graph& g_train, Graph& g_test, std::mt19937& gen,\n            std::vector<GNode>& trainingSamples,\n            std::vector<GNode>& testingSamples) {\n  galois::TimeAccumulator accumTimer;\n  accumTimer.start();\n\n  // allocate storage for weights from previous iteration\n  old_weights.create(NUM_VARIABLES);\n  if (updateType == UpdateType::ReplicateByThread ||\n      updateType == UpdateType::Staleness) {\n    galois::on_each([](unsigned tid, unsigned total) {\n      double* p                  = new double[NUM_VARIABLES];\n      *thread_weights.getLocal() = p;\n      std::fill(p, p + NUM_VARIABLES, 0);\n    });\n  }\n  if (updateType == UpdateType::ReplicateBySocket) {\n    galois::on_each([](unsigned tid, unsigned total) {\n      if (galois::substrate::getThreadPool().isLeader(tid)) {\n        double* p                  = new double[NUM_VARIABLES];\n        *socket_weights.getLocal() = p;\n        std::fill(p, p + NUM_VARIABLES, 0);\n      }\n    });\n  }\n\n  galois::StatTimer DcdTime(\"DcdTime\");\n\n  // Initialization for DCD\n  double diag[] = {0.5 / creg, 0, 0.5 / creg};\n  double ub[]   = {std::numeric_limits<double>::max(), 0,\n                 std::numeric_limits<double>::max()};\n  if (algoType == AlgoType::DCDL1 or algoType == AlgoType::DCDLR) {\n    diag[0] = 0;\n    diag[2] = 0;\n    ub[0]   = creg;\n    ub[2]   = creg;\n  }\n\n  DCD_parameters params;\n  params.C                   = ub[0];\n  params.diag                = diag[0];\n  params.QD                  = std::vector<double>(NUM_SAMPLES, 0);\n  params.alpha               = std::vector<double>(NUM_SAMPLES, 0);\n  std::vector<double>& QD    = params.QD;\n  std::vector<double>& alpha = params.alpha;\n  params.PGmax_old           = std::numeric_limits<double>::max();\n  params.PGmin_old           = std::numeric_limits<double>::lowest();\n  params.isactive            = std::vector<bool>(NUM_SAMPLES, true);\n  params.active_size         = NUM_SAMPLES;\n\n  Bag bags[2];\n  Bag *cur_bag = &bags[0], *next_bag = &bags[1];\n\n  // For LR\n  double innereps     = 1e-2;\n  double innereps_min = 1e-8; // min(1e-8, eps);\n\n  if (algoType == AlgoType::DCDLR)\n    alpha.resize(2 * NUM_SAMPLES, 0);\n\n  printf(\"asdfasdfasdf\\n\");\n  // initialize model w to zero\n  //\tgalois::do_all(boost::counting_iterator<size_t>(0),\n  //boost::counting_iterator<size_t>(NUM_VARIABLES), [&](size_t i) {\n  //\t\t\tg_train.getData(i+NUM_VARIABLES).w = 0;\n  //\t\t});\n\n  printf(\"asdfasdfasdf\\n\");\n  galois::StatTimer QDTime(\"QdTime\");\n  QDTime.start();\n  std::vector<double> xTx(NUM_SAMPLES);\n  // for (auto ii = g.begin(), ei = g.begin() + NUM_SAMPLES; ii != ei; ++ii) {\n  auto ts_begin = trainingSamples.begin();\n  auto ts_end   = trainingSamples.end();\n\n  printf(\"asdfasdfasdf\\n\");\n\n  for (auto ii = ts_begin, ei = ts_end; ii != ei; ++ii) {\n    int& label     = g_train.getData(*ii).field;\n    auto& nodedata = g_train.getData(*ii);\n    cur_bag->push(*ii);\n\n    if (label != 1 && label != -1) {\n      label = label <= 0 ? -1 : 1;\n    }\n    if (algoType == AlgoType::DCDLR) {\n      alpha[2 * (*ii)]     = std::min(0.001 * ub[label + 1], 1e-8);\n      alpha[2 * (*ii) + 1] = ub[label + 1] - alpha[2 * (*ii)];\n      nodedata.alpha       = std::min(0.001 * ub[label + 1], 1e-8);\n      nodedata.alpha2      = ub[label + 1] - nodedata.alpha2;\n    } else {\n      alpha[*ii]     = 0;\n      nodedata.alpha = 0;\n    }\n\n    for (auto edge : g_train.out_edges(*ii)) {\n      double val = g_train.getEdgeData(edge);\n      // xTx[*ii] += val*val;\n      nodedata.xTx += val * val;\n      auto variable_node = g_train.getEdgeDst(edge);\n      Node& data         = g_train.getData(variable_node);\n      data.w += label * nodedata.alpha * val;\n      /*\n      if(algoType == AlgoType::DCDLR) {\n          data.w += label*alpha[2*(*ii)]*val;\n      } else {\n          data.w += label*alpha[*ii]*val;\n      }\n      */\n    }\n\n    if (algoType == AlgoType::DCDLR)\n      nodedata.QD = nodedata.xTx + diag[label + 1];\n    // QD[*ii] = diag[label+1] + xTx[*ii];\n    // g_train.getData(*ii).QD=QD[*ii];\n  }\n  QDTime.stop();\n  printf(\"QDTIME~!!!!!!!!!! %lf\\n\", QDTime.get() / 1e3);\n\n  unsigned iterations = maxIterations;\n  double minObj       = std::numeric_limits<double>::max();\n  if (fixedIterations)\n    iterations = fixedIterations;\n\n  bool is_terminate = false;\n  std::vector<GNode> active_set;\n\n  for (unsigned iter = 1; iter <= iterations && is_terminate == false; ++iter) {\n    DcdTime.start();\n\n    // params.PGmax_new = std::numeric_limits<double>::lowest();\n    // params.PGmin_new = std::numeric_limits<double>::max();\n    params.PGmax_new.reset();\n    params.PGmin_new.reset();\n\n    // include shuffling time in the time taken per iteration\n    // also: not parallel\n\n    if (useshrink) {\n      active_set.clear();\n      for (auto& gg : *cur_bag)\n        active_set.push_back(gg);\n    }\n    if (shuffleSamples) {\n      if (useshrink) {\n        std::shuffle(active_set.begin(), active_set.end(), gen);\n      } else {\n        std::shuffle(trainingSamples.begin(), trainingSamples.end(), gen);\n      }\n    }\n\n    size_t newton_iter = 0;\n    auto ts_begin      = trainingSamples.begin();\n    auto ts_end        = trainingSamples.end();\n    auto ln            = galois::loopname(\"LinearSVM\");\n    if (algoType == AlgoType::DCDLR)\n      ln = galois::loopname(\"LogisticRegression\");\n\n    auto wl = galois::wl<galois::worklists::PerSocketChunkFIFO<32>>();\n    //\t\tauto wl = galois::wl<galois::worklists::StableIterator<true> >();\n    galois::GAccumulator<size_t> bigUpdates;\n\n    printf(\"pgmax_old: %lf, pgmin_old: %lf\\n\", params.PGmax_old,\n           params.PGmin_old);\n\n    UpdateType type = updateType;\n    switch (type) {\n    case UpdateType::Wild:\n    case UpdateType::WildOrig:\n      if (algoType == AlgoType::DCDLR) {\n        galois::for_each(ts_begin, ts_end,\n                         LogisticRegression<UpdateType::Wild>(\n                             g_train, bigUpdates, &alpha[0], &xTx[0], innereps,\n                             &newton_iter),\n                         ln, wl);\n      } else if (useshrink) {\n        cur_bag->clear();\n        printf(\"active set size: %zu\\n\", active_set.size());\n        galois::for_each(active_set.begin(), active_set.end(),\n                         linearSVM_DCD<UpdateType::Wild>(g_train, bigUpdates,\n                                                         &params, cur_bag),\n                         ln, wl);\n      } else {\n        galois::for_each(\n            ts_begin, ts_end,\n            linearSVM_DCD<UpdateType::Wild>(g_train, bigUpdates, &params), ln,\n            wl);\n      }\n      break;\n    case UpdateType::ReplicateBySocket:\n      //        galois::for_each(ts_begin, ts_end,\n      //        linearSVM<UpdateType::ReplicateBySocket>(g, learning_rate,\n      //        bigUpdates), ln, wl); break;\n    case UpdateType::ReplicateByThread:\n      //        galois::for_each(ts_begin, ts_end,\n      //        linearSVM<UpdateType::ReplicateByThread>(g, learning_rate,\n      //        bigUpdates), ln, wl); break;\n    case UpdateType::Staleness:\n      //        galois::for_each(ts_begin, ts_end,\n      //        linearSVM<UpdateType::Staleness>(g, learning_rate, bigUpdates),\n      //        ln, wl);\n      printf(\"ERROR: only support Wild updates\\n\");\n      return;\n      break;\n    default:\n      abort();\n    }\n\n    if (useshrink == true) {\n      size_t active_size = std::distance(cur_bag->begin(), cur_bag->end());\n      double PGmax_local = params.PGmax_new.reduce();\n      double PGmin_local = params.PGmin_new.reduce();\n      printf(\"now dual gap: %lf, active_size: %zu\\n\", PGmax_local - PGmin_local,\n             active_size);\n      // if ( params.PGmax_new - params.PGmin_new <= tol )\n      if (PGmax_local - PGmin_local <= tol) {\n        if (active_size == NUM_SAMPLES)\n          is_terminate = true;\n        else {\n          /*\n          params.active_size = NUM_SAMPLES;\n          for ( int i=0 ; i<NUM_SAMPLES ; i++ )\n              params.isactive[i] = true;\n              */\n\n          cur_bag->clear();\n          for (auto ii = ts_begin; ii != ts_end; ii++)\n            cur_bag->push(*ii);\n          params.PGmax_old = std::numeric_limits<double>::max();\n          params.PGmin_old = std::numeric_limits<double>::lowest();\n        }\n      } else {\n        params.PGmax_old = PGmax_local;\n        params.PGmin_old = PGmin_local;\n        printf(\"Pgmaxlocal: %.17g, pgmin_local: %.17g\\n\", PGmax_local,\n               PGmin_local);\n        if (params.PGmax_old <= 1e-300) {\n          printf(\"hihi\\n\");\n          params.PGmax_old = std::numeric_limits<double>::max();\n        }\n        if (params.PGmin_old >= 0)\n          params.PGmin_old = std::numeric_limits<double>::lowest();\n      }\n    }\n\n    DcdTime.stop();\n\n    if (algoType == AlgoType::DCDLR)\n      if (newton_iter <= trainingSamples.size() / 10)\n        innereps = std::max(1e-8, 0.1 * innereps);\n    size_t numBigUpdates = bigUpdates.reduce();\n\n    /*\n    //swap weights from past iteration and this iteration\n    if (type != UpdateType::Wild && type != UpdateType::WildOrig) {\n        bool byThread = type == UpdateType::ReplicateByThread || type ==\n    UpdateType::Staleness; double *localw = byThread ?\n    *thread_weights.getLocal() : *socket_weights.getLocal(); unsigned\n    num_threads = galois::getActiveThreads(); unsigned num_sockets =\n    galois::runtime::LL::getMaxSocketForThread(num_threads-1) + 1;\n        galois::do_all(boost::counting_iterator<unsigned>(0),\n    boost::counting_iterator<unsigned>(NUM_VARIABLES), [&](unsigned i) {\n                unsigned n = byThread ? num_threads : num_sockets;\n                for (unsigned j = 1; j < n; j++) {\n                double o = byThread ?\n                (*thread_weights.getRemote(j))[i] :\n                (*socket_weights.getRemoteByPkg(j))[i];\n                localw[i] += o;\n                }\n                localw[i] /=  n;\n                GNode variable_node = (GNode) (i + NUM_SAMPLES);\n                Node& var_data = g.getData(variable_node,\n    galois::MethodFlag::UNPROTECTED); var_data.w = localw[i]; old_weights[i] =\n    var_data.w;\n                });\n        galois::on_each([&](unsigned tid, unsigned total) {\n                switch (type) {\n                case UpdateType::Staleness:\n                case UpdateType::ReplicateByThread:\n                if (tid)\n                std::copy(localw, localw + NUM_VARIABLES,\n    *thread_weights.getLocal()); break; case UpdateType::ReplicateBySocket: if\n    (tid && galois::runtime::LL::isSocketLeader(tid)) std::copy(localw, localw +\n    NUM_VARIABLES, *socket_weights.getLocal()); break; default: abort();\n                }\n                });\n    }\n*/\n    accumTimer.stop();\n\n    std::cout << \"iter \" << iter << \" walltime \" << DcdTime.get() / 1e3;\n\n    if (printObjective)\n      std::cout << \" f \" << getPrimalObjective(g_train, trainingSamples);\n    if (printAccuracy)\n      std::cout << \" accuracy \"\n                << getNumCorrect(g_test, testingSamples, g_train) /\n                       (double)testingSamples.size();\n\n    std::cout << \"\\n\";\n\n    if (algoType != AlgoType::DCDLR) {\n      // Verify whether w = \\sum_i alpha_i x_i\n      std::vector<double> realw(NUM_SAMPLES);\n      for (auto ii = g_train.begin(), ei = g_train.begin() + NUM_SAMPLES;\n           ii != ei; ++ii) {\n        double alphai = alpha[*ii];\n        int& label    = g_train.getData(*ii).field;\n        if (label != 1 && label != -1) {\n          label = label <= 0 ? -1 : 1;\n        }\n        for (auto edge : g_train.out_edges(*ii)) {\n          double val          = g_train.getEdgeData(edge);\n          GNode variable_node = g_train.getEdgeDst(edge);\n          realw[variableNodeToId(variable_node)] += val * label * alphai;\n        }\n      }\n\n      double diff = 0;\n      for (auto ii = 0; ii < NUM_VARIABLES; ii++) {\n        Node& var_data = g_train.getData(ii + NUM_SAMPLES);\n        double w       = var_data.w;\n        diff += (realw[ii] - w) * (realw[ii] - w);\n      }\n      printf(\"diff: %lf\\n\", diff);\n    }\n  }\n\n  if (!fixedIterations)\n    std::cout << \"Failed to converge\\n\";\n}\n\ntemplate <UpdateType UT>\nvoid runPrimalSgd_(Graph& g_train, Graph& g_test, std::mt19937& gen,\n                   std::vector<GNode>& trainingSamples,\n                   std::vector<GNode>& testingSamples) {\n  galois::TimeAccumulator accumTimer;\n  accumTimer.start();\n\n  DiffractedCollection<double, UT> dstate(NUM_VARIABLES);\n\n  galois::StatTimer sgdTime(\"SgdTime\");\n\n  unsigned iterations = maxIterations;\n  double minObj       = std::numeric_limits<double>::max();\n  if (fixedIterations)\n    iterations = fixedIterations;\n\n  for (unsigned iter = 1; iter <= iterations; ++iter) {\n    sgdTime.start();\n\n    // include shuffling time in the time taken per iteration\n    // also: not parallel\n    if (shuffleSamples)\n      std::shuffle(trainingSamples.begin(), trainingSamples.end(), gen);\n\n    double learning_rate = 30 / (100.0 + iter);\n    auto ts_begin        = trainingSamples.begin();\n    auto ts_end          = trainingSamples.end();\n    auto ln              = galois::loopname(\"LinearSVM\");\n    auto wl = galois::wl<galois::worklists::PerSocketChunkFIFO<32>>();\n\n    if (UT == UpdateType::Wild)\n      galois::for_each(ts_begin, ts_end, LinearSGDWild(g_train, learning_rate),\n                       ln, wl);\n    else\n      galois::for_each(ts_begin, ts_end,\n                       LinearSGD<UT>(g_train, dstate, learning_rate), ln, wl);\n\n    sgdTime.stop();\n\n    dstate.merge([&g_train](ptrdiff_t x) -> double& {\n      return g_train.getData(x + NUM_SAMPLES).w;\n    });\n\n    accumTimer.stop();\n\n    std::cout << \"iter \" << iter << \" walltime \" << sgdTime.get() / 1e3;\n\n    double obj = getPrimalObjective(g_train, trainingSamples);\n    if (printObjective)\n      std::cout << \" f \" << obj;\n    if (printAccuracy)\n      std::cout << \" accuracy \"\n                << getNumCorrect(g_test, testingSamples, g_train) /\n                       (double)testingSamples.size();\n\n    std::cout << \"\\n\";\n\n    if (!fixedIterations) {\n      if (std::fabs((obj - minObj) / minObj) < tol) {\n        std::cout << \"Converged in \" << iter << \" iterations.\\n\";\n        return;\n      }\n      minObj = std::min(obj, minObj);\n    }\n  }\n\n  if (!fixedIterations)\n    std::cout << \"Failed to converge\\n\";\n}\n\nvoid runPrimalSgd(Graph& g_train, Graph& g_test, std::mt19937& gen,\n                  std::vector<GNode>& trainingSamples,\n                  std::vector<GNode>& testingSamples) {\n  switch (updateType) {\n  case UpdateType::Wild:\n    return runPrimalSgd_<UpdateType::Wild>(g_train, g_test, gen,\n                                           trainingSamples, testingSamples);\n  case UpdateType::WildOrig:\n    return runPrimalSgd_<UpdateType::WildOrig>(g_train, g_test, gen,\n                                               trainingSamples, testingSamples);\n  case UpdateType::ReplicateBySocket:\n    return runPrimalSgd_<UpdateType::ReplicateBySocket>(\n        g_train, g_test, gen, trainingSamples, testingSamples);\n  case UpdateType::CycleBySocket:\n    return runPrimalSgd_<UpdateType::CycleBySocket>(\n        g_train, g_test, gen, trainingSamples, testingSamples);\n  case UpdateType::ReplicateByThread:\n    return runPrimalSgd_<UpdateType::ReplicateByThread>(\n        g_train, g_test, gen, trainingSamples, testingSamples);\n  case UpdateType::Staleness:\n    return runPrimalSgd_<UpdateType::Staleness>(\n        g_train, g_test, gen, trainingSamples, testingSamples);\n  default:\n    abort();\n  }\n}\n\nvoid runCD(Graph& g_train, Graph& g_test, std::mt19937& gen,\n           std::vector<GNode>& trainingSamples,\n           std::vector<GNode>& testingSamples) {\n  galois::TimeAccumulator accumTimer;\n  accumTimer.start();\n  galois::StatTimer CdTime(\"CdTime\");\n\n  unsigned iterations = maxIterations;\n  if (fixedIterations)\n    iterations = fixedIterations;\n\n  bool is_terminate = false;\n\n  std::vector<GNode> variables(g_train.begin() + NUM_SAMPLES, g_train.end());\n\n  for (auto ii = variables.begin(), ei = variables.end(); ii != ei; ii++) {\n    auto& nodedata = g_train.getData(*ii);\n    nodedata.w     = 0;\n    nodedata.xTx   = 0;\n\n    for (auto edge : g_train.out_edges(*ii)) {\n      double val = g_train.getEdgeData(edge);\n      nodedata.xTx += val * val;\n    }\n    nodedata.xTx = 1.0 / nodedata.xTx;\n  }\n\n  for (auto ii = trainingSamples.begin(), ei = trainingSamples.end(); ii != ei;\n       ii++) {\n    auto& nodedata = g_train.getData(*ii);\n    auto& label    = g_train.getData(*ii).b;\n    nodedata.alpha = label * (-1);\n  }\n\n  CD_parameters params;\n  params.Gmax_old = std::numeric_limits<double>::max();\n\n  Bag cur_bag;\n  std::vector<GNode> active_set;\n  for (auto ii = variables.begin(), ei = variables.end(); ii != ei; ii++) {\n    cur_bag.push(*ii);\n  }\n\n  for (unsigned iter = 1; iter <= iterations && is_terminate == false; ++iter) {\n    CdTime.start();\n\n    params.Gmax_new.reset();\n    params.Gnorm1_new.reset();\n\n    if (useshrink) {\n      active_set.clear();\n      for (auto& gg : cur_bag) {\n        active_set.push_back(gg);\n      }\n    }\n    if (shuffleSamples) {\n      if (useshrink) {\n        std::shuffle(active_set.begin(), active_set.end(), gen);\n      } else {\n        std::shuffle(variables.begin(), variables.end(), gen);\n      }\n    }\n\n    auto ln = galois::loopname(\"PrimalCD\");\n    auto wl = galois::wl<galois::worklists::PerSocketChunkLIFO<32>>();\n    //\t\tauto wl = galois::wl<galois::worklists::StableIterator<true> >();\n\n    UpdateType type = updateType;\n    switch (type) {\n    case UpdateType::Wild:\n    case UpdateType::WildOrig:\n      if (useshrink) {\n        cur_bag.clear();\n        printf(\"active set size: %zu\\n\", active_set.size());\n      } else {\n        galois::for_each(\n            boost::transform_iterator<Lasso_CD<UpdateType::Wild>::Initializer,\n                                      boost::counting_iterator<int>>(\n                NUM_SAMPLES),\n            boost::transform_iterator<Lasso_CD<UpdateType::Wild>::Initializer,\n                                      boost::counting_iterator<int>>(\n                NUM_SAMPLES + NUM_VARIABLES),\n            Lasso_CD<UpdateType::Wild>(g_train, &params), ln, wl);\n        //                  \tgalois::for_each(variables.begin(),\n        //                  variables.end(), Lasso_CD<UpdateType::Wild>(g_train,\n        //                  &params), ln, wl);\n      }\n      break;\n    case UpdateType::ReplicateBySocket:\n      //        galois::for_each(ts_begin, ts_end,\n      //        linearSVM<UpdateType::ReplicateBySocket>(g, learning_rate,\n      //        bigUpdates), ln, wl); break;\n    case UpdateType::ReplicateByThread:\n      //        galois::for_each(ts_begin, ts_end,\n      //        linearSVM<UpdateType::ReplicateByThread>(g, learning_rate,\n      //        bigUpdates), ln, wl); break;\n    case UpdateType::Staleness:\n      //        galois::for_each(ts_begin, ts_end,\n      //        linearSVM<UpdateType::Staleness>(g, learning_rate, bigUpdates),\n      //        ln, wl);\n      printf(\"ERROR: only support Wild updates\\n\");\n      return;\n      break;\n    default:\n      abort();\n    }\n\n    if (useshrink == true) {\n      size_t active_size  = std::distance(cur_bag.begin(), cur_bag.end());\n      double Gmax_local   = params.Gmax_new.reduce();\n      double Gnorm1_local = params.Gnorm1_new.reduce();\n      if (iter == 1)\n        params.Gnorm1_init = Gnorm1_local;\n      printf(\"gnorm1: %lf, Gmax_new: %lf\\n\", Gnorm1_local, Gmax_local);\n      if (Gnorm1_local <= tol * (params.Gnorm1_init)) {\n        cur_bag.clear();\n        for (auto ii = variables.begin(), ei = variables.end(); ii != ei; ii++)\n          cur_bag.push(*ii);\n\n        params.Gmax_old = std::numeric_limits<double>::max();\n        tol             = tol * 0.1;\n      } else\n        params.Gmax_old = Gmax_local;\n    }\n\n    CdTime.stop();\n    accumTimer.stop();\n\n    std::cout << \"iter \" << iter << \" walltime \" << CdTime.get() / 1e3;\n\n    std::cout.precision(10);\n    if (printObjective)\n      std::cout << \" f \" << getPrimalObjective(g_train, trainingSamples);\n    if (printAccuracy)\n      std::cout << \" rmse \" << getTestRMSE(g_test, testingSamples, g_train);\n\n    std::cout << \"\\n\";\n  }\n\n  if (!fixedIterations)\n    std::cout << \"Failed to converge\\n\";\n}\n\n// new GLMNET for L1R Logistic Regression\ntypedef struct {\n  double Gmax_old;\n  double Gnorm1_init;\n  double QP_Gmax_old;\n  galois::GReduceMax<double> Gmax_new, QP_Gmax_new;\n  galois::GAccumulator<double> Gnorm1_new, QP_Gnorm1_new;\n} GLMNET_parameters;\n\n// cd for the subproblem of glmenet for L1R-LR\ntemplate <UpdateType UT>\nstruct glmnet_cd { // {{{\n  typedef int tt_does_not_need_aborts;\n  typedef GLMNET_parameters param_t;\n  Graph& g_train;\n  DiffractedCollection<double, UT>& dstate;\n  GLMNET_parameters& params;\n  Bag& cd_bag;\n  size_t nr_samples;\n  double nu;\n\n  glmnet_cd(Graph& _g, DiffractedCollection<double, UT>& d, param_t& _p,\n            Bag& bag, size_t _nr_samples)\n      : g_train(_g), dstate(d), params(_p), cd_bag(bag),\n        nr_samples(_nr_samples), nu(1e-12) {}\n\n  void operator()(GNode feat_j, galois::UserContext<GNode>& ctx) {\n    auto& j_data = g_train.getData(feat_j, galois::MethodFlag::UNPROTECTED);\n    auto& H      = j_data.Hdiag;\n    auto& Grad_j = j_data.Grad;\n    auto& wpd_j  = j_data.wpd;\n    auto& w_j    = j_data.w;\n    double G     = Grad_j + (wpd_j - w_j) * nu;\n    auto d       = dstate.get();\n\n    for (auto& edge :\n         g_train.out_edges(feat_j, galois::MethodFlag::UNPROTECTED)) {\n      auto& x_ij  = g_train.getEdgeData(edge);\n      auto dst    = g_train.getEdgeDst(edge);\n      auto& ddata = g_train.getData(dst, galois::MethodFlag::UNPROTECTED);\n      G += x_ij * ddata.D * d.read(ddata.xTd, dst);\n    }\n    double Gp        = G + 1;\n    double Gn        = G - 1;\n    double violation = 0;\n    if (wpd_j == 0) {\n      if (Gp < 0)\n        violation = -Gp;\n      else if (Gn > 0)\n        violation = Gn;\n      else if (Gp > params.QP_Gmax_old / nr_samples &&\n               Gn < -params.QP_Gmax_old / nr_samples) {\n        return;\n      }\n    } else if (wpd_j > 0)\n      violation = fabs(Gp);\n    else\n      violation = fabs(Gn);\n    cd_bag.push(feat_j);\n    params.QP_Gmax_new.update(violation);\n    params.QP_Gnorm1_new.update(violation);\n    double z = 0;\n    if (Gp < H * wpd_j)\n      z = -Gp / H;\n    else if (Gn > H * wpd_j)\n      z = -Gn / H;\n    else\n      z = -wpd_j;\n    if (fabs(z) < 1.0e-12)\n      return;\n    z = std::min(std::max(z, -10.0), 10.0);\n    wpd_j += z;\n    for (auto& edge :\n         g_train.out_edges(feat_j, galois::MethodFlag::UNPROTECTED)) {\n      auto& x_ij  = g_train.getEdgeData(edge);\n      auto dst    = g_train.getEdgeDst(edge);\n      auto& ddata = g_train.getData(dst, galois::MethodFlag::UNPROTECTED);\n      double& l   = d.read(ddata.xTd, dst);\n      double v    = l + x_ij * z;\n      d.write(ddata.xTd, dst) = v;\n      // d.writeBig(l, v);\n      // d.write(ddata.xTd, dst) += x_ij*z;\n    }\n  }\n}; // }}}\n\nstruct glmnet_qp_construct { // {{{\n  typedef GLMNET_parameters param_t;\n  Graph& g_train;\n  GLMNET_parameters& params;\n  Bag& cd_bag;\n  size_t nr_samples;\n  double nu;\n  glmnet_qp_construct(Graph& _g, param_t& _p, Bag& bag, size_t _nr_samples)\n      : g_train(_g), params(_p), cd_bag(bag), nr_samples(_nr_samples),\n        nu(1e-12) {}\n  void operator()(GNode feat_j, galois::UserContext<GNode>& ctx) {\n    auto& j_data  = g_train.getData(feat_j, galois::MethodFlag::UNPROTECTED);\n    auto& w_j     = j_data.w;\n    auto& Hdiag_j = j_data.Hdiag;\n    auto& Grad_j  = j_data.Grad;\n    auto& xjneg_sum_j = j_data.xjneg_sum;\n    Hdiag_j           = nu;\n    Grad_j            = 0;\n    double tmp        = 0;\n    for (auto& edge :\n         g_train.out_edges(feat_j, galois::MethodFlag::UNPROTECTED)) {\n      auto x_ij  = g_train.getEdgeData(edge, galois::MethodFlag::UNPROTECTED);\n      auto& self = g_train.getData(g_train.getEdgeDst(edge),\n                                   galois::MethodFlag::UNPROTECTED);\n      Hdiag_j += x_ij * x_ij * self.D;\n      tmp += x_ij * self.tau;\n    }\n    Grad_j = -tmp + xjneg_sum_j;\n\n    double Gp        = Grad_j + 1;\n    double Gn        = Grad_j - 1;\n    double violation = 0;\n    if (w_j == 0) {\n      if (Gp < 0)\n        violation = -Gp;\n      else if (Gn > 0)\n        violation = Gn;\n      // outer-level shrinking\n      else if (Gp > params.Gmax_old / nr_samples &&\n               Gn < -params.Gmax_old / nr_samples) {\n        return;\n      }\n\n    } else if (w_j > 0)\n      violation = fabs(Gp);\n    else\n      violation = fabs(Gn);\n    cd_bag.push(feat_j);\n    params.Gmax_new.update(violation);\n    params.Gnorm1_new.update(violation);\n  }\n}; // }}}\n\ntemplate <UpdateType UT>\nvoid runGLMNET_(Graph& g_train, Graph& g_test, std::mt19937& gen,\n                std::vector<GNode>& trainingSamples,\n                std::vector<GNode>& testingSamples) { // {{{\n  galois::TimeAccumulator accumTimer;\n  accumTimer.start();\n  // galois::runtime::getThreadPool().burnPower(numThreads);\n\n  DiffractedCollection<double, UT> dstate(NUM_SAMPLES);\n\n  galois::StatTimer glmnetTime(\"GLMNET_Time\");\n  galois::StatTimer cdTime(\"CD_Time\");\n  galois::StatTimer FirstTime(\"First_Time\");\n  galois::StatTimer SecondTime(\"Second_Time\");\n  galois::StatTimer ThirdTime(\"Third_Time\");\n  galois::StatTimer ActiveSetTime(\"ActiveSet_Time\");\n\n  unsigned max_newton_iter = fixedIterations ? fixedIterations : maxIterations;\n  unsigned max_cd_iter     = 50;\n  unsigned max_num_linesearch = 20;\n  double nu                   = 1e-12;\n  double inner_eps            = 0.01;\n  double sigma                = 0.01;\n\n  double C[3] = {creg, 0, creg};\n\n  std::vector<GNode> variables(g_train.begin() + NUM_SAMPLES, g_train.end());\n\n  // initialization {{{\n  galois::do_all(trainingSamples.begin(), trainingSamples.end(),\n                 [&](GNode inst_node) {\n                   auto& self   = g_train.getData(inst_node);\n                   self.y       = self.y > 0 ? 1 : -1;\n                   self.exp_wTx = 0.0;\n                 });\n  double w_norm = 0;\n  galois::do_all(variables.begin(), variables.end(), [&](GNode feat_j) {\n    auto& j_data        = g_train.getData(feat_j);\n    double& w_j         = j_data.w;\n    double& wpd_j       = j_data.wpd;\n    double& xjneg_sum_j = j_data.xjneg_sum;\n    w_norm += fabs(w_j);\n    wpd_j       = w_j;\n    xjneg_sum_j = 0;\n    for (auto edge :\n         g_train.out_edges(feat_j, galois::MethodFlag::UNPROTECTED)) {\n      auto x_ij  = g_train.getEdgeData(edge, galois::MethodFlag::UNPROTECTED);\n      auto& self = g_train.getData(g_train.getEdgeDst(edge),\n                                   galois::MethodFlag::UNPROTECTED);\n      self.exp_wTx += w_j * x_ij;\n      if (self.y == -1)\n        xjneg_sum_j += creg * x_ij;\n    }\n  });\n  galois::GAccumulator<double> xx;\n  galois::do_all(variables.begin(), variables.end(), [&](GNode feat_j) {\n    xx += g_train.getData(feat_j).xjneg_sum;\n  });\n  double cc = creg;\n  printf(\"creg %lf init xx %lf\\n\", cc, xx.reduce());\n\n  galois::do_all(\n      trainingSamples.begin(), trainingSamples.end(), [&](GNode inst_node) {\n        auto& self =\n            g_train.getData(inst_node, galois::MethodFlag::UNPROTECTED);\n        self.exp_wTx   = exp(self.exp_wTx);\n        double tau_tmp = 1.0 / (1.0 + self.exp_wTx);\n        self.tau       = creg * tau_tmp;\n        self.D         = creg * self.exp_wTx * tau_tmp * tau_tmp;\n      }); //}}}\n\n  int newton_iter = 0;\n  Bag cur_bag; // used for outerlevel active set\n  std::vector<GNode> active_set;\n  GLMNET_parameters params;\n  params.Gmax_old   = std::numeric_limits<double>::max();\n  size_t nr_samples = trainingSamples.size();\n\n  while (newton_iter < max_newton_iter) {\n    glmnetTime.start();\n\n    cur_bag.clear();\n    active_set.clear();\n    for (auto& feat_j : variables)\n      active_set.push_back(feat_j);\n    params.Gmax_new.reset();\n    params.Gnorm1_new.reset();\n\n    // if(shuffleSamples) std::shuffle(active_set.begin(), active_set.end(),\n    // gen);\n\n    FirstTime.start();\n\n    // Compute Newton direction -- Hessian and Gradient\n    auto ln = galois::loopname(\"GLMENT-QPconstruction\");\n    auto wl = galois::wl<galois::worklists::PerSocketChunkFIFO<32>>();\n    galois::for_each(active_set.begin(), active_set.end(),\n                     glmnet_qp_construct(g_train, params, cur_bag, nr_samples),\n                     ln, wl);\n\n    double tmp_Gnorm1_new = params.Gnorm1_new.reduce();\n    if (newton_iter == 0)\n      params.Gnorm1_init = tmp_Gnorm1_new;\n    params.Gmax_old = params.Gmax_new.reduce();\n    FirstTime.stop();\n\n    ActiveSetTime.start();\n\n    // Compute Newton direction -- Coordinate Descet for QP\n    cdTime.start();\n    params.QP_Gmax_old = std::numeric_limits<double>::max();\n    galois::do_all(\n        trainingSamples.begin(), trainingSamples.end(), [&](GNode& inst_node) {\n          g_train.getData(inst_node, galois::MethodFlag::UNPROTECTED).xTd = 0.0;\n        });\n    auto init_original_active_set = [&] {\n      active_set.clear();\n      for (auto& feat_j : cur_bag)\n        active_set.push_back(feat_j);\n    };\n    init_original_active_set();\n\n    ActiveSetTime.stop();\n\n    int original_active_size = active_set.size();\n    int cd_iter              = 0;\n    Bag cd_bag;\n\n    double grad_norm = 0, H_norm = 0, xx = 0;\n    SecondTime.start();\n    while (cd_iter < max_cd_iter) { //{{{\n      params.QP_Gmax_new.reset();\n      params.QP_Gnorm1_new.reset();\n\n      if (shuffleSamples)\n        std::shuffle(active_set.begin(), active_set.end(), gen);\n      auto ln = galois::loopname(\"GLMENT-CDiteration\");\n#if 1\n      auto wl = galois::wl<galois::worklists::PerSocketChunkFIFO<32>>();\n      galois::for_each(\n          active_set.begin(), active_set.end(),\n          glmnet_cd<UT>(g_train, dstate, params, cd_bag, nr_samples), ln, wl);\n      dstate.merge([&g_train](ptrdiff_t x) -> double& {\n        return g_train.getData(x).xTd;\n      });\n#else\n      {\n        auto wl = galois::wl<galois::worklists::StableIterator<>>();\n        galois::GAccumulator<double> Gaccum;\n        double nu = 1e-12;\n        for (auto feat_j : active_set) {\n          auto& j_data =\n              g_train.getData(feat_j, galois::MethodFlag::UNPROTECTED);\n          auto& H      = j_data.Hdiag;\n          auto& Grad_j = j_data.Grad;\n          auto& wpd_j  = j_data.wpd;\n          auto& w_j    = j_data.w;\n          double G     = Grad_j + (wpd_j - w_j) * nu;\n          galois::for_each(\n              g_train.out_edges(feat_j, galois::MethodFlag::UNPROTECTED)\n                  .begin(),\n              g_train.out_edges(feat_j, galois::MethodFlag::UNPROTECTED).end(),\n              [&](typename Graph::edge_iterator edge,\n                  galois::UserContext<typename Graph::edge_iterator>&) {\n                auto& x_ij = g_train.getEdgeData(edge);\n                auto dst   = g_train.getEdgeDst(edge);\n                auto& ddata =\n                    g_train.getData(dst, galois::MethodFlag::UNPROTECTED);\n                Gaccum += x_ij * ddata.D * ddata.xTd;\n              },\n              ln, wl);\n          G += Gaccum.reduce();\n          Gaccum.reset();\n          double Gp        = G + 1;\n          double Gn        = G - 1;\n          double violation = 0;\n          if (wpd_j == 0) {\n            if (Gp < 0)\n              violation = -Gp;\n            else if (Gn > 0)\n              violation = Gn;\n            else if (Gp > params.QP_Gmax_old / nr_samples &&\n                     Gn < -params.QP_Gmax_old / nr_samples) {\n              continue;\n            }\n          } else if (wpd_j > 0)\n            violation = fabs(Gp);\n          else\n            violation = fabs(Gn);\n          cd_bag.push(feat_j);\n          params.QP_Gmax_new.update(violation);\n          params.QP_Gnorm1_new.update(violation);\n          double z = 0;\n          if (Gp < H * wpd_j)\n            z = -Gp / H;\n          else if (Gn > H * wpd_j)\n            z = -Gn / H;\n          else\n            z = -wpd_j;\n          if (fabs(z) < 1.0e-12)\n            continue;\n          z = std::min(std::max(z, -10.0), 10.0);\n          wpd_j += z;\n          galois::for_each(\n              g_train.out_edges(feat_j, galois::MethodFlag::UNPROTECTED)\n                  .begin(),\n              g_train.out_edges(feat_j, galois::MethodFlag::UNPROTECTED).end(),\n              [&](typename Graph::edge_iterator edge,\n                  galois::UserContext<typename Graph::edge_iterator>&) {\n                auto& x_ij = g_train.getEdgeData(edge);\n                auto dst   = g_train.getEdgeDst(edge);\n                auto& ddata =\n                    g_train.getData(dst, galois::MethodFlag::UNPROTECTED);\n                ddata.xTd += x_ij * z;\n              },\n              ln, wl);\n        }\n      }\n#endif\n      cd_iter++;\n      double tmp_QP_Gmax_new   = params.QP_Gmax_new.reduce();\n      double tmp_QP_Gnorm1_new = params.QP_Gnorm1_new.reduce();\n      active_set.clear();\n      for (auto& feat_j : cd_bag)\n        active_set.push_back(feat_j);\n      cd_bag.clear();\n      if (tmp_QP_Gmax_new <= inner_eps * params.Gnorm1_init) {\n        // inner stopping\n        if (active_set.size() == original_active_size)\n          break;\n        // active set reactivation\n        else {\n          init_original_active_set();\n          params.QP_Gmax_old = std::numeric_limits<double>::max();\n        }\n      } else {\n        params.QP_Gmax_old = tmp_QP_Gmax_new;\n      }\n    } //}}}\n    cdTime.stop();\n    SecondTime.stop();\n\n    ThirdTime.start();\n    // Perform Line Search\n    // {{{\n    galois::GAccumulator<double> delta_acc, w_norm_acc;\n    galois::do_all(variables.begin(), variables.end(), //{{{\n                   [&](GNode& feat_j) {\n                     auto& self = g_train.getData(\n                         feat_j, galois::MethodFlag::UNPROTECTED);\n                     delta_acc.update(self.Grad * (self.wpd - self.w));\n                     if (self.wpd != 0)\n                       w_norm_acc.update(fabs(self.wpd));\n                   }); //}}}\n    double w_norm_new = w_norm_acc.reduce();\n    double delta      = delta_acc.reduce() + (w_norm_new - w_norm);\n\n    galois::GAccumulator<double> tmp_acc;\n    galois::do_all(\n        trainingSamples.begin(), trainingSamples.end(), [&](GNode& inst_node) {\n          auto& self =\n              g_train.getData(inst_node, galois::MethodFlag::UNPROTECTED);\n          if (self.y == -1)\n            tmp_acc.update(creg * self.xTd);\n        });\n    double negsum_xTd = tmp_acc.reduce();\n\n    int num_linesearch = 0;\n    for (num_linesearch = 0; num_linesearch < max_num_linesearch;\n         num_linesearch++) {\n      double cond = w_norm_new - w_norm + negsum_xTd - sigma * delta;\n      tmp_acc.reset();\n      galois::do_all(trainingSamples.begin(), trainingSamples.end(),\n                     [&](GNode& inst_node) {\n                       auto& self = g_train.getData(\n                           inst_node, galois::MethodFlag::UNPROTECTED);\n                       double exp_xTd   = exp(self.xTd);\n                       self.exp_wTx_new = self.exp_wTx * exp_xTd;\n                       tmp_acc.update(creg * log((1 + self.exp_wTx_new) /\n                                                 (exp_xTd + self.exp_wTx_new)));\n                     });\n      cond += tmp_acc.reduce();\n      if (cond <= 0.0) {\n        w_norm = w_norm_new;\n        galois::do_all(variables.begin(), variables.end(), [&](GNode& feat_j) {\n          auto& self = g_train.getData(feat_j, galois::MethodFlag::UNPROTECTED);\n          self.w     = self.wpd;\n        });\n        galois::do_all(\n            trainingSamples.begin(), trainingSamples.end(), [&](GNode& inst_i) {\n              auto& self =\n                  g_train.getData(inst_i, galois::MethodFlag::UNPROTECTED);\n              self.exp_wTx   = self.exp_wTx_new;\n              double tau_tmp = 1 / (1 + self.exp_wTx);\n              self.tau       = creg * tau_tmp;\n              self.D         = creg * self.exp_wTx * tau_tmp * tau_tmp;\n            });\n        break;\n      } else {\n        w_norm_new = 0;\n        tmp_acc.reset();\n        galois::do_all(variables.begin(), variables.end(), [&](GNode& feat_j) {\n          auto& self = g_train.getData(feat_j, galois::MethodFlag::UNPROTECTED);\n          self.wpd   = (self.w + self.wpd) * 0.5;\n          if (self.wpd != 0)\n            tmp_acc.update(fabs(self.wpd));\n        });\n        w_norm_new = tmp_acc.reduce();\n        delta *= 0.5;\n        negsum_xTd *= 0.5;\n        galois::do_all(\n            trainingSamples.begin(), trainingSamples.end(), [&](GNode& inst_i) {\n              g_train.getData(inst_i, galois::MethodFlag::UNPROTECTED).xTd *=\n                  0.5;\n            });\n      }\n    }\n    if (num_linesearch >= max_num_linesearch) {\n      galois::do_all(\n          trainingSamples.begin(), trainingSamples.end(), [&](GNode& inst_i) {\n            g_train.getData(inst_i, galois::MethodFlag::UNPROTECTED).exp_wTx =\n                0;\n          });\n\n      galois::do_all(variables.begin(), variables.end(), [&](GNode& feat_j) {\n        auto& self = g_train.getData(feat_j, galois::MethodFlag::UNPROTECTED);\n        if (self.w != 0) {\n          for (auto& edge : g_train.out_edges(feat_j)) {\n            auto& x_ij =\n                g_train.getEdgeData(edge, galois::MethodFlag::UNPROTECTED);\n            g_train\n                .getData(g_train.getEdgeDst(edge),\n                         galois::MethodFlag::UNPROTECTED)\n                .exp_wTx += self.w * x_ij;\n          }\n        }\n      });\n      galois::do_all(\n          trainingSamples.begin(), trainingSamples.end(), [&](GNode& inst_i) {\n            auto& exp_wTx =\n                g_train.getData(inst_i, galois::MethodFlag::UNPROTECTED)\n                    .exp_wTx;\n            exp_wTx = exp(exp_wTx);\n          });\n    }\n    //}}} // end of line search\n\n    ThirdTime.stop();\n    if (cd_iter == 1)\n      inner_eps *= 0.25;\n\n    newton_iter++;\n    glmnetTime.stop();\n    accumTimer.stop();\n\n    printf(\"iter %d walltime %.1f ittime %.1f cdtime %.2f cd-iters %d \"\n           \"firsttime %.2f secondtime %.2f thirdtime %.2f\",\n           newton_iter, accumTimer.get() / 1e3, glmnetTime.get() / 1e3,\n           cdTime.get() / 1e3, cd_iter, FirstTime.get() / 1e3,\n           SecondTime.get() / 1e3, ThirdTime.get() / 1e3);\n    if (printObjective) {\n      printf(\" f %.6f\", getPrimalObjective(g_train, trainingSamples));\n    }\n    if (printAccuracy) {\n      printf(\" accuracy %.6f\", getNumCorrect(g_test, testingSamples, g_train) /\n                                   (double)testingSamples.size());\n    }\n    printf(\"\\n\");\n    accumTimer.start();\n  }\n  // galois::runtime::getThreadPool().beKind();\n} // }}}\n\nvoid runGLMNET(Graph& g_train, Graph& g_test, std::mt19937& gen,\n               std::vector<GNode>& trainingSamples,\n               std::vector<GNode>& testingSamples) {\n  switch (updateType) {\n  case UpdateType::Wild:\n    return runGLMNET_<UpdateType::Wild>(g_train, g_test, gen, trainingSamples,\n                                        testingSamples);\n  case UpdateType::ReplicateBySocket:\n    return runGLMNET_<UpdateType::ReplicateBySocket>(\n        g_train, g_test, gen, trainingSamples, testingSamples);\n  case UpdateType::CycleBySocket:\n    return runGLMNET_<UpdateType::CycleBySocket>(\n        g_train, g_test, gen, trainingSamples, testingSamples);\n  case UpdateType::ReplicateByThread:\n    return runGLMNET_<UpdateType::ReplicateByThread>(\n        g_train, g_test, gen, trainingSamples, testingSamples);\n  case UpdateType::Staleness:\n    return runGLMNET_<UpdateType::Staleness>(g_train, g_test, gen,\n                                             trainingSamples, testingSamples);\n  default:\n    abort();\n  }\n}\n\n#ifdef HAS_EIGEN\nvoid runLeastSquares(Graph& g, std::mt19937& gen,\n                     std::vector<GNode>& trainingSamples,\n                     std::vector<GNode>& testingSamples) {\n  Eigen::SparseMatrix<double> A(NUM_SAMPLES, NUM_VARIABLES);\n  {\n    typedef Eigen::Triplet<double> Triplet;\n    std::vector<Triplet> triplets{g.sizeEdges()};\n    {\n      auto it = triplets.begin();\n      for (auto n : g) {\n        for (auto edge : g.out_edges(n)) {\n          *it++ =\n              Triplet(n, g.getEdgeDst(edge) - NUM_SAMPLES, g.getEdgeData(edge));\n        }\n      }\n    }\n    A.setFromTriplets(triplets.begin(), triplets.end());\n  }\n\n  Eigen::VectorXd b(NUM_SAMPLES);\n  size_t cur = 0;\n  for (auto ii = g.begin(), ei = g.begin() + NUM_SAMPLES; ii != ei; ++ii) {\n    b(cur++) = g.getData(*ii).field;\n  }\n\n  // Least-squares problem: minimize ||Ax - b||_2\n  // normal equation: A^T A x = A^T b\n  Eigen::VectorXd x;\n  // Cholesky is almost always faster but QR is more numerically stable\n  if (g.sizeEdges() > 10000) {\n    // Solve normal equation directly with Cholesky\n    Eigen::SparseMatrix<double> AT  = A.transpose();\n    Eigen::SparseMatrix<double> ATA = AT * A;\n    for (int i = 0; i < ATA.rows(); ++i)\n      ATA.coeffRef(i, i) += creg;\n    Eigen::VectorXd ATb = AT * b;\n    Eigen::ConjugateGradient<Eigen::SparseMatrix<double>> solver;\n    solver.compute(ATA);\n    x = solver.solve(ATb);\n    std::cout << \"cg iterations: \" << solver.iterations() << \"\\n\";\n    std::cout << \"cg est error: \" << solver.error() << \"\\n\";\n  } else {\n    // TODO add L2 regularizer\n    // Decompose normal equation\n    // A = QR\n    // A^T A x = A^T b\n    // R^T Q^T Q R x = R^T Q^T b => ... => R x = Q^T b\n    Eigen::SparseQR<Eigen::SparseMatrix<double>, Eigen::COLAMDOrdering<int>>\n        solver;\n    solver.compute(A);\n    if (solver.info() != Eigen::Success) {\n      GALOIS_DIE(\"factorization failed\");\n    }\n    Eigen::VectorXd QTb = solver.matrixQ().transpose() * b;\n    int r               = solver.rank();\n    Eigen::VectorXd out;\n    out.resize(A.cols());\n    out.topRows(r) = solver.matrixR()\n                         .topLeftCorner(r, r)\n                         .triangularView<Eigen::Upper>()\n                         .solve(QTb.topRows(r));\n    out.bottomRows(out.rows() - r).setZero();\n    x = solver.colsPermutation() * out;\n  }\n\n  // Verify\n  {\n    for (size_t i = 0; i < NUM_VARIABLES; ++i) {\n      g.getData(i + NUM_SAMPLES).w = x(i);\n    }\n    std::vector<GNode> allSamples(g.begin(), g.begin() + NUM_SAMPLES);\n    //    size_t n = getNumCorrect(g, allSamples);\n    //    std::cout << \"All: \" << n / (double) NUM_SAMPLES << \" (\" << n << \"/\"\n    //    << NUM_SAMPLES << \")\\n\"; n = getNumCorrect(g, testingSamples);\n    //    std::cout << \"Testing: \" << n / (double) testingSamples.size() << \" (\"\n    //    << n << \"/\" << testingSamples.size() << \")\\n\";\n  }\n}\n#endif\n\nint main(int argc, char** argv) {\n  LonestarStart(argc, argv, name, desc, url);\n  galois::StatManager statManager;\n\n  Graph g_train, g_test;\n  // Load Training Data\n  galois::graphs::readGraph(g_train, inputTrainGraphFilename);\n  if (algoType == AlgoType::CDLasso)\n    NUM_SAMPLES = loadb(g_train, inputTrainLabelFilename);\n  else {\n    NUM_SAMPLES = loadLabels(g_train, inputTrainLabelFilename);\n  }\n  if (algoType != AlgoType::CDLasso and algoType != AlgoType::GLMNETL1RLR)\n    initializeVariableCounts(g_train);\n  NUM_VARIABLES = g_train.size() - NUM_SAMPLES;\n  assert(NUM_SAMPLES > 0 && NUM_VARIABLES > 0);\n\n  // Load Testing Data\n  galois::graphs::readGraph(g_test, inputTestGraphFilename);\n  if (algoType == AlgoType::CDLasso)\n    NUM_TEST_SAMPLES = loadb(g_test, inputTestLabelFilename);\n  else\n    NUM_TEST_SAMPLES = loadLabels(g_test, inputTestLabelFilename);\n  //  NUM_TEST_SAMPLES = loadLabels(g_test, inputTestLabelFilename);\n  if (algoType != AlgoType::CDLasso and algoType != AlgoType::GLMNETL1RLR)\n    initializeVariableCounts(g_test);\n  NUM_TEST_VARIABLES = g_test.size() - NUM_TEST_SAMPLES;\n  assert(NUM_TEST_SAMPLES > 0);\n\n  // put samples in a list and shuffle them\n  std::random_device rd;\n  std::mt19937 gen(SEED == ~0U ? rd() : SEED);\n\n  std::vector<GNode> trainingSamples(g_train.begin(),\n                                     g_train.begin() + NUM_SAMPLES);\n  std::vector<GNode> testingSamples(g_test.begin(),\n                                    g_test.begin() + NUM_TEST_SAMPLES);\n\n  printParameters(trainingSamples, testingSamples);\n  if (printAccuracy) {\n    std::cout << \"Initial\";\n    if (printAccuracy) {\n      std::cout << \" Accuracy: \"\n                << getNumCorrect(g_test, testingSamples, g_train) /\n                       (double)testingSamples.size();\n    }\n    std::cout << \"\\n\";\n  }\n\n  galois::StatTimer timer;\n  timer.start();\n  switch (algoType) {\n  case AlgoType::SGDL1:\n  case AlgoType::SGDL2:\n  case AlgoType::SGDLR:\n    runPrimalSgd(g_train, g_test, gen, trainingSamples, testingSamples);\n    break;\n  case AlgoType::DCDL1:\n  case AlgoType::DCDL2:\n  case AlgoType::DCDLR:\n  case AlgoType::CDLasso:\n    runCD(g_train, g_test, gen, trainingSamples, testingSamples);\n    break;\n  case AlgoType::GLMNETL1RLR:\n    runGLMNET(g_train, g_test, gen, trainingSamples, testingSamples);\n    break;\n#ifdef HAS_EIGEN\n//    case AlgoType::LeastSquares: runLeastSquares(g, gen, trainingSamples,\n//    testingSamples); break;\n#endif\n  default:\n    abort();\n  }\n  timer.stop();\n\n  return 0;\n}\n\n// vim: set noexpandtab:\n", "meta": {"hexsha": "ffb4b6e9230e56a59ffdd8221c94e307b377d12a", "size": 83893, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lonestar/experimental/svm/svm-new.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/svm/svm-new.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/svm/svm-new.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.6109775641, "max_line_length": 85, "alphanum_fraction": 0.5860560476, "num_tokens": 23307, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.5621765008857981, "lm_q1q2_score": 0.30736334118347786}}
{"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:        SurfpackApproximation\n//- Description:  Class implementation of Surfpack response surface \n//-               \n//- Owner:        Brian Adams\n\n#include <stdexcept>\n#include <typeinfo>\n\n#include \"SurfpackApproximation.hpp\"\n#include \"SharedSurfpackApproxData.hpp\"\n#include \"ProblemDescDB.hpp\"\n#include \"DakotaVariables.hpp\"\n#include \"dakota_data_io.hpp\"\n\n// Headers from Surfpack\n#include \"SurfData.h\"\n// for Hessian data\n#include \"SurfpackMatrix.h\"\n#include \"ModelFactory.h\"\n#include \"ModelFitness.h\"\n#include \"surfaces/SurfpackModel.h\"\n#include \"SurfpackInterface.h\"\n \n#include <algorithm>\n#include <boost/math/special_functions/round.hpp>\n\n\nnamespace Dakota {\n\nusing surfpack::toString;\nusing surfpack::fromVec;\n\n/** Initialize the embedded Surfpack surface object and configure it\n    using the specifications from the input file.  Data for the\n    surface is created later. */\nSurfpackApproximation::\nSurfpackApproximation(const ProblemDescDB& problem_db,\n\t\t      const SharedApproxData& shared_data,\n                      const String& approx_label):\n  Approximation(BaseConstructor(), problem_db, shared_data, approx_label), //surface(NULL),\n  surfData(NULL), model(NULL), factory(NULL)\n  //sharedDataRep((SharedSurfpackApproxData*)shared_data.data_rep())\n{\n  SharedSurfpackApproxData* shared_surf_data_rep\n    = (SharedSurfpackApproxData*)sharedDataRep;\n\n  ParamMap args;\n\n  args[\"verbosity\"] = toString<short>(sharedDataRep->outputLevel);\n  args[\"ndims\"] = toString<size_t>(sharedDataRep->numVars);\n\n  // For now, not exposing Surfpack random seed in the DAKOTA UI;\n  // instead fixing at an arbitrary value (treated as int in Surfpack)\n  args[\"seed\"] = \"8147\";\n\n  // For Polynomial surface fits\n  if (sharedDataRep->approxType == \"global_polynomial\") {\n    args[\"type\"] = \"polynomial\";\n    args[\"order\"] = toString<unsigned short>(shared_surf_data_rep->approxOrder);\n    // TO DO: activate derivative-based regression\n  }\n\n  // For Kriging surface fits\n  else if (sharedDataRep->approxType == \"global_kriging\") {\n\n    args[\"type\"]  = \"kriging\";\n    args[\"order\"] = toString<unsigned short>(shared_surf_data_rep->approxOrder);\n    args[\"reduced_polynomial\"] =\n      (problem_db.get_string(\"model.surrogate.trend_order\") == \"quadratic\") ?\n      toString<bool>(false) : toString<bool>(true);\n\n    // activate derivative information if available\n    unsigned short surfpack_derivative_order = 0;\n    short bdo = sharedDataRep->buildDataOrder;\n    if (bdo & 2)\n      surfpack_derivative_order = 1;\n    if (bdo & 4) {\n      if (bdo & 2)\n\tsurfpack_derivative_order = 2;\n      else {\n\tCerr << \"\\nError (global_kriging): Hessian information only used \"\n\t     << \"if gradients present.\\nbuildDataOrder = \" << bdo << std::endl;\n\tabort_handler(-1);\n      }\n    }\n    args[\"derivative_order\"] = \n      toString<unsigned short>(surfpack_derivative_order);\n\n    // optimization options are none | sample | local | global (default)\n    args[\"optimization_method\"] = \"global\";\n    const String& optimization_method = \n      problem_db.get_string(\"model.surrogate.kriging_opt_method\");\n    if (!optimization_method.empty()) {\n      if (optimization_method == \"none\" || optimization_method == \"sampling\" \n\t  || optimization_method == \"local\" \n\t  || optimization_method == \"global\")\n\targs[\"optimization_method\"] = optimization_method;\n      else {\n\tCerr << \"Error (global_kriging): invalid optimization method \"\n\t     << optimization_method << \"; valid options are \" \n\t     << \"none, sampling, local, or global\" << std::endl;\n\tabort_handler(-1);\n      }\n    }\n\n    short max_trials\n      = problem_db.get_short(\"model.surrogate.kriging_max_trials\");\n    if (max_trials > 0)\n      args[\"max_trials\"] = toString<short>(max_trials);\n\n    // NIDR support for RealArray (aka std::vector) would eliminate xtra copy!\n    // old parameters\n    Real nugget = problem_db.get_real(\"model.surrogate.nugget\");\n    short find_nugget = problem_db.get_short(\"model.surrogate.find_nugget\");\n    if (nugget > 0) {\n      args[\"nugget\"] = toString<Real>(nugget);\n    } \n    else { \n      if (find_nugget > 0) {\n\tif (find_nugget == 1)  \n\t  args[\"find_nugget\"] = toString<bool>(false);\n\telse if (find_nugget == 2)  \n\t  args[\"find_nugget\"] = toString<bool>(true);\n\telse {\n\t  Cerr << \" find_nugget must be 1 or 2\" << '\\n'; \n\t  abort_handler(-1);\n\t}\n      }\n    }\n\n    const RealVector& correlation_rv\n      = problem_db.get_rv(\"model.surrogate.kriging_correlations\");\n    if (!correlation_rv.empty()) {\n      RealArray correlation_ra; //std::vector<double>\n      copy_data(correlation_rv, correlation_ra);\n      args[\"correlation_lengths\"] = fromVec<Real>(correlation_ra);\n      args[\"optimization_method\"] = \"none\";\n    }\n\n    /*\n    const RealVector& max_correlations_rv \n      = problem_db.get_rv(\"model.surrogate.kriging_max_correlations\");\n    if (!max_correlations_rv.empty()) {\n      RealArray max_correlation_ra; //std::vector<double>\n      copy_data(max_correlations_rv, max_correlation_ra);\n      args[\"max_correlations\"] = fromVec<Real>(max_correlation_ra);\n    }\n\n    const RealVector& min_correlations_rv \n      = problem_db.get_rv(\"model.surrogate.kriging_min_correlations\");\n    if (!min_correlations_rv.empty()) {\n      RealArray min_correlation_ra; //std::vector<double>\n      copy_data(min_correlations_rv, min_correlation_ra);\n      args[\"min_correlations\"] = fromVec<Real>(min_correlation_ra);\n    }\n\n    // bounds set at run time within build()\n    if (!sharedDataRep->approxCLowerBnds.empty()) {\n      RealArray alb_ra;\n      copy_data(sharedDataRep->approxCLowerBnds, alb_ra);\n      args[\"lower_bounds\"] = fromVec<Real>(alb_ra);\n    }\n    if (!sharedDataRep->approxCUpperBnds.empty()) {\n      RealArray aub_ra;\n      copy_data(sharedDataRep->approxCUpperBnds, aub_ra);\n      args[\"upper_bounds\"] = fromVec<Real>(aub_ra);\n    }\n    */\n\n    // unused for now\n    IntVector dimension_groups_iv;\n    if (!dimension_groups_iv.empty()) {\n      IntArray dg_ra;\n      copy_data(dimension_groups_iv, dg_ra);\n      args[\"dimension_groups\"] = fromVec<int>(dg_ra);\n    }\n\n  }\n\n  // For ANN surface fits\n  else if (sharedDataRep->approxType == \"global_neural_network\") {\n    args[\"type\"] = \"ann\";\n    short random_weight\n      = problem_db.get_short(\"model.surrogate.neural_network_random_weight\");\n    if (random_weight > 0) {\n      args[\"random_weight\"] = toString<short>(random_weight);\n    }\n    short nodes\n      = problem_db.get_short(\"model.surrogate.neural_network_nodes\");\n    if (nodes > 0) {\n      args[\"nodes\"] = toString<short>(nodes);\n    }\n    const Real& range\n      = problem_db.get_real(\"model.surrogate.neural_network_range\");\n    if (range > 0) {\n      args[\"range\"] = toString<Real>(range);\n    }\n  }\n\n  //// For moving least squares\n  else if (sharedDataRep->approxType == \"global_moving_least_squares\") {\n    args[\"type\"] = \"mls\";\n    short weight\n      = problem_db.get_short(\"model.surrogate.mls_weight_function\");\n    if (weight > 0) {\n      args[\"weight\"] = toString<short>(weight);\n    }\n    short order = problem_db.get_short(\"model.surrogate.polynomial_order\");\n    if (order > 0) {\n      args[\"order\"] = toString<short>(order);\n    }\n  }\n\n  //// For radial basis function networks\n  else if (sharedDataRep->approxType == \"global_radial_basis\") {\n    args[\"type\"] = \"rbf\";\n    // mapping number bases to number of centers\n    short bases = problem_db.get_short(\"model.surrogate.rbf_bases\");\n    if (bases > 0) {\n      args[\"centers\"] = toString<short>(bases);\n    }\n    short min_partition\n      = problem_db.get_short(\"model.surrogate.rbf_min_partition\");\n    if (min_partition > 0) {\n      args[\"min_partition\"] = toString<short>(min_partition);\n    }\n    short max_subsets\n      = problem_db.get_short(\"model.surrogate.rbf_max_subsets\");\n    if (max_subsets > 0) {\n      args[\"max_iter\"] = toString<short>(max_subsets);\n    }\n    // mapping max_pts to cvt_pts\n    short max_pts = problem_db.get_short(\"model.surrogate.rbf_max_pts\");\n    if (max_pts > 0) {\n      args[\"cvt_pts\"] = toString<short>(max_pts);\n    }\n  }\n\n  //// For Mars surface fits\n  else if (sharedDataRep->approxType == \"global_mars\") {\n    args[\"type\"] = \"mars\";\n    short max_bases = problem_db.get_short(\"model.surrogate.mars_max_bases\");\n    if (max_bases > 0) {\n      args[\"max_bases\"] = toString<short>(max_bases);\n    }\n    const String& interpolation\n      = problem_db.get_string(\"model.surrogate.mars_interpolation\");\n    if (interpolation != \"\") {\n      args[\"interpolation\"] = interpolation; \n    }\n  }\n  //Cout << \"PARAMETERS: \" << std::endl;\n  //for (ParamMap::iterator itr = args.begin(); itr != args.end(); itr++)\n  //   Cout << \"     \" << itr->first << \": \" << itr->second << std::endl;\n\n  factory = ModelFactory::createModelFactory(args);\n\n  //catch(...) {\n  //  Cout << \"Exception caught in attempt to create Surface object\"\n  //       << std::endl;\n  //  abort_handler(-1);\n  //}\n\n  // validate diagnostic settings (preliminary); TODO: do more at\n  // run time and move to both ctors\n  bool err_found = false;\n  const StringArray& diag_set = shared_surf_data_rep->diagnosticSet;\n  if (!diag_set.empty()) {\n    std::set<std::string> valid_metrics;\n    valid_metrics.insert(\"sum_squared\");\n    valid_metrics.insert(\"mean_squared\");\n    valid_metrics.insert(\"root_mean_squared\");\n    valid_metrics.insert(\"sum_abs\");\n    valid_metrics.insert(\"mean_abs\");\n    valid_metrics.insert(\"max_abs\");\n    valid_metrics.insert(\"rsquared\");\n\n    int num_diag = diag_set.size();\n    for (int j = 0; j < num_diag; ++j)\n      if (valid_metrics.find(diag_set[j]) == valid_metrics.end()) {\n\tCerr << \"Error: surrogate metric '\" << diag_set[j] \n\t     << \"' is not available in Dakota.\\n\";\n\terr_found = true;\n      }\t\n    if (err_found) {\n      Cerr << \"Valid surrogate metrics include:\\n  \";\n      std::copy(valid_metrics.begin(), valid_metrics.end(), \n\t\tstd::ostream_iterator<std::string>(Cerr, \" \"));\n      Cerr << std::endl;\n    }\n  }\n  if (shared_surf_data_rep->crossValidateFlag) {\n    if (shared_surf_data_rep->numFolds > 0 &&\n\tshared_surf_data_rep->numFolds < 2) {\n      Cerr << \"Error: cross_validation folds must be 2 or greater.\"\n\t   << std::endl;\n      err_found = true;\n    }\n    if (shared_surf_data_rep->percentFold < 0.0 ||\n\tshared_surf_data_rep->percentFold > 0.5) {\n      Cerr << \"Error: cross_validation percent must be between 0.0 and 0.5\"\n\t   << std::endl;\n      err_found = true;\n    }\n  }\n  if (err_found)\n    abort_handler(-1);\n}\n\n\n/// On-the-fly constructor which uses mostly Surfpack model defaults\nSurfpackApproximation::\nSurfpackApproximation(const SharedApproxData& shared_data):\n  Approximation(NoDBBaseConstructor(), shared_data),\n  surfData(NULL), model(NULL), factory(NULL)\n  //sharedDataRep((SharedSurfpackApproxData*)shared_data.data_rep())\n{\n  SharedSurfpackApproxData* shared_surf_data_rep\n    = (SharedSurfpackApproxData*)sharedDataRep;\n\n  ParamMap args;\n  args[\"verbosity\"] = toString<short>(sharedDataRep->outputLevel);\n  args[\"ndims\"]     = toString<size_t>(sharedDataRep->numVars);\n  args[\"seed\"]      = \"8147\";\n\n  if (sharedDataRep->approxType == \"global_polynomial\") {\n    args[\"type\"] = \"polynomial\";\n    args[\"order\"] = toString<unsigned short>(shared_surf_data_rep->approxOrder);\n  }\n  else if (sharedDataRep->approxType == \"global_kriging\") {\n\n    args[\"type\"] = \"kriging\";\n    args[\"order\"] = toString<unsigned short>(shared_surf_data_rep->approxOrder);\n    args[\"reduced_polynomial\"] = toString<bool>(true);\n    /*\n    // bounds set at run time within build():\n    if (!sharedDataRep->approxCLowerBnds.empty()) {\n      RealArray alb_ra;\n      copy_data(sharedDataRep->approxCLowerBnds, alb_ra);\n      args[\"lower_bounds\"] = fromVec<Real>(alb_ra);\n    }\n    if (!sharedDataRep->approxCUpperBnds.empty()) {\n      RealArray aub_ra;\n      copy_data(sharedDataRep->approxCUpperBnds, aub_ra);\n      args[\"upper_bounds\"] = fromVec<Real>(aub_ra);\n    }\n    */\n    //size_t krig_max_trials=(2*num_vars+1)*(num_vars+1)*10;\n    //size_t krig_max_trials=20*(2*num_vars+1)*\n      //(1+num_vars+((num_vars+1)*num_vars)/2); //#der0 + #der1 + #der2\n    //if(krig_max_trials>10000)\n      //krig_max_trials=10000;\n    //size_t krig_max_trials=1000;\n    //args[\"max_trials\"] = toString<size_t>(krig_max_trials);\n    args[\"max_trials\"] = toString<size_t>(5000);\n    \n    // activate derivative information if available\n    unsigned short surfpack_derivative_order = 0;\n    short bdo = sharedDataRep->buildDataOrder;\n    if (bdo == 1)      surfpack_derivative_order = 0;\n    else if (bdo == 3) surfpack_derivative_order = 1;\n    else if (bdo == 7) surfpack_derivative_order = 2;\n    else {\n      Cerr << \"\\nError (global_kriging): Unsupported buildDataOrder = \" << bdo\n\t   << std::endl;\n      abort_handler(-1);\n    }\n    args[\"derivative_order\"] = \n      toString<unsigned short>(surfpack_derivative_order);\n\n  }\n  else if (sharedDataRep->approxType == \"global_neural_network\")\n    args[\"type\"] = \"ann\";\n  else if (sharedDataRep->approxType == \"global_moving_least_squares\") {\n    args[\"type\"] = \"mls\";\n    args[\"order\"] = toString<unsigned short>(shared_surf_data_rep->approxOrder);\n  }\n  else if (sharedDataRep->approxType == \"global_radial_basis\")\n    args[\"type\"] = \"rbf\";\n  else if (sharedDataRep->approxType == \"global_mars\")\n    args[\"type\"] = \"mars\";\n  \n  factory = ModelFactory::createModelFactory(args);\n}\n\n\n\n// Embedded Surfpack objects will need to be deleted\nSurfpackApproximation::~SurfpackApproximation()\n{\n  delete surfData;\n  delete model;\n  delete factory;\n}\n\n\nint SurfpackApproximation::min_coefficients() const\n{\n  assert(factory);\n  return factory->minPointsRequired();\n}\n\n\nint SurfpackApproximation::recommended_coefficients() const\n{\n  assert(factory);\n  return factory->recommendedNumPoints();\n}\n\n\nvoid SurfpackApproximation::build(size_t index)\n{\n  // base class implementation checks data set against min required\n  Approximation::build(index);\n\n  // Surface object should have been created in constructor\n  if (!factory) { \n    Cerr << \"Error: surface is null in SurfpackApproximation::build().\"\n\t << std::endl;  \n    abort_handler(-1);\n  }\n\n  SharedSurfpackApproxData* shared_surf_data_rep\n    = (SharedSurfpackApproxData*)sharedDataRep;\n\n  /// surfData will be deleted in dtor\n  /// \\todo Right now, we're completely deleting the old data and then\n  /// recopying the current data into a SurfData object.  This was just\n  /// the easiest way to arrive at a solution that would build and run.\n  /// This function is frequently called from addPoint rebuild, however,\n  /// and it's not good to go through this whole process every time one\n  /// more data point is added.\n  try {\n    if (surfData) {\n      delete surfData;\n      surfData = NULL;\n    }\n    surfData = surrogates_to_surf_data();\n \n    // set bounds at run time since they are updated by some methods (e.g., SBO)\n    if (!sharedDataRep->approxCLowerBnds.empty() ||\n\t!sharedDataRep->approxDILowerBnds.empty() ||\n\t!sharedDataRep->approxDRLowerBnds.empty()) {\n      RealArray lb;\n      shared_surf_data_rep->merge_variable_arrays(\n\tsharedDataRep->approxCLowerBnds, sharedDataRep->approxDILowerBnds,\n\tsharedDataRep->approxDRLowerBnds, lb);\n      factory->add(\"lower_bounds\", fromVec<Real>(lb));\n    }\n    if (!sharedDataRep->approxCUpperBnds.empty() ||\n\t!sharedDataRep->approxDIUpperBnds.empty() ||\n\t!sharedDataRep->approxDRUpperBnds.empty()) {\n      RealArray ub;\n      shared_surf_data_rep->merge_variable_arrays(\n\tsharedDataRep->approxCUpperBnds, sharedDataRep->approxDIUpperBnds,\n\tsharedDataRep->approxDRUpperBnds, ub);\n      factory->add(\"upper_bounds\", fromVec<Real>(ub));\n    }\n\n    if (model) {\n      delete model;\n      model = NULL;\n    }\n    model = factory->Build(*surfData); \n    // TO DO: extract coefficients array\n  }\n  catch (std::runtime_error& e) {\n    Cerr << e.what() << std::endl;\n    Cerr << typeid(e).name() << std::endl;\n    abort_handler(-1);\n  }\n  catch (std::string& e) {\n    Cerr << \"Error: exception with no recourse caught trying to build model:\\n\"\n\t << e << std::endl;\n    abort_handler(-1);\n  }\n  catch (...) {\n    Cerr << \"Error: exception caught trying to build model\" << std::endl;\n    abort_handler(-1);\n  }\n\n/*  if (!shared_surf_data_rep->exportModelName.empty() &&\n      SurfpackInterface::HasFeature(\"model_save\")) {\n    if (sharedDataRep->outputLevel >= VERBOSE_OUTPUT)\n      Cout << \"\\nSaving surrogate model to file \"\n\t   << shared_surf_data_rep->exportModelName << std::endl;\n    SurfpackInterface::Save(model, shared_surf_data_rep->exportModelName);\n  }*/\n}\n\n\nvoid SurfpackApproximation::export_model(const String& fn_label,\n \t\t\t\t\t const String& export_prefix, \n                                         const unsigned short export_format)\n{\n  String without_extension;\n  unsigned short formats;\n  if(export_format) {\n    without_extension = export_prefix + \".\" + fn_label;\n    formats = export_format;\n  } else {\n    without_extension = sharedDataRep->modelExportPrefix + \".\" + approxLabel;\n    formats = sharedDataRep->modelExportFormat;\n  }\n  //unsigned short formats = export_format; \n  const bool &can_save = SurfpackInterface::HasFeature(\"model_save\");\n  // Saving to text archive\n  if(formats & TEXT_ARCHIVE) {\n    if(can_save) {\n      String filename = without_extension + \".sps\";\n      SurfpackInterface::Save(model,filename);\n    } else\n        Cerr << \"\\nRequested surrogate export to text archive failed: \"\n\t\t<< \"Surfpack lacks support for model saving.\\n\";\n  }\n  // Saving to binary archive\n  if(formats & BINARY_ARCHIVE) {\n    if(can_save) {\n      String filename = without_extension + \".bsps\";\n      SurfpackInterface::Save(model,filename);\n    } else\n        Cerr << \"\\nRequested surrogate export to binary archive failed: \"\n\t        << \"Surfpack lacks support for model saving.\\n\";\n  }\n  // Saving to algebraic file\n  if(formats & ALGEBRAIC_FILE) {\n    String filename = without_extension + \".alg\";\n    std::ofstream af(filename.c_str(),std::ofstream::out);\n    af << \"Model for response \" << fn_label << \":\\n\" << model->asString();\n    af.close();\n    Cout << \"Model saved in algebraic format to file '\" << filename << \"'.\\n\";\n  }\n  // Writing in algebraic format to screen\n  if(formats & ALGEBRAIC_CONSOLE) {\n    Cout << \"\\nModel for response \" << fn_label << \":\\n\";\n    Cout << model->asString();\n  }    \n}\n\nReal SurfpackApproximation::value(const Variables& vars)\n{ \n  //static int times_called = 0;\n  if (!model) { \n    Cerr << \"Error: surface is null in SurfpackApproximation::value()\"\n\t << std::endl;  \n    abort_handler(-1);\n  }\n\n  RealArray x_array;\n  ((SharedSurfpackApproxData*)sharedDataRep)->vars_to_realarray(vars, x_array);\n  return (*model)(x_array);\n}\n\n\nconst RealVector& SurfpackApproximation::gradient(const Variables& vars)\n{\n  approxGradient.sizeUninitialized(vars.cv());\n  try {\n    RealArray x_array;\n    ((SharedSurfpackApproxData*)sharedDataRep)\n      ->vars_to_realarray(vars, x_array);\n    VecDbl local_grad = model->gradient(x_array);\n    for (unsigned i = 0; i < surfData->xSize(); i++)\n      approxGradient[i] = local_grad[i];\n  }\n  catch (...) {\n    Cerr << \"Error: gradient() not available for this approximation type.\"\n\t << std::endl;\n    abort_handler(-1);\n  }\n  return approxGradient;\n}\n\n\nconst RealSymMatrix& SurfpackApproximation::hessian(const Variables& vars)\n{\n  size_t num_cv = vars.cv();\n  approxHessian.reshape(num_cv);\n  try {\n    if (sharedDataRep->approxType == \"global_moving_least_squares\") {\n      Cerr << \"Have not implemented analytical hessians in this surfpack class\"\n\t   << std::endl;\n      abort_handler(-1);\n    }\n    RealArray x_array;\n    ((SharedSurfpackApproxData*)sharedDataRep)\n      ->vars_to_realarray(vars, x_array);\n    MtxDbl sm = model->hessian(x_array);\n    ///\\todo Make this acceptably efficient\n    for (size_t i = 0; i < num_cv; i++)\n      for(size_t j = 0; j < num_cv; j++)\n        approxHessian(i,j) = sm(i,j);\n  }\n  catch (...) {\n    Cerr << \"Error: hessian() not available for this approximation type.\"\n\t << std::endl;\n    abort_handler(-1);\n  }\n  return approxHessian;\n}\n\n\nReal SurfpackApproximation::prediction_variance(const Variables& vars)\n{\n  try {\n    RealArray x_array;\n    ((SharedSurfpackApproxData*)sharedDataRep)\n      ->vars_to_realarray(vars, x_array);\n    return model->variance(x_array);\n  }\n  catch (...) {\n    Cerr << \"Error: prediction_variance() not available for this \"\n\t << \"approximation type.\" << std::endl;\n    abort_handler(-1);\n  }\n}\n\nReal SurfpackApproximation::value(const RealVector& c_vars)\n{\n    //static int times_called = 0;\n    if (!model) {\n        Cerr << \"Error: surface is null in SurfpackApproximation::value()\"\n        << std::endl;\n        abort_handler(-1);\n    }\n        \n    RealArray x_array;\n    size_t num_vars = c_vars.length();\n    for (size_t i = 0; i < num_vars; i++) x_array.push_back(c_vars[i]);\n    return (*model)(x_array);\n}\n    \n    \nconst RealVector& SurfpackApproximation::gradient(const RealVector& c_vars)\n{\n    approxGradient.sizeUninitialized(c_vars.length());\n    try {\n        RealArray x_array;\n        size_t num_vars = c_vars.length();\n        for (size_t i = 0; i < num_vars; i++) x_array.push_back(c_vars[i]);\n        \n        VecDbl local_grad = model->gradient(x_array);\n        for (unsigned i = 0; i < surfData->xSize(); i++)\n            approxGradient[i] = local_grad[i];\n    }\n    catch (...) {\n        Cerr << \"Error: gradient() not available for this approximation type.\"\n        << std::endl;\n        abort_handler(-1);\n    }\n    return approxGradient;\n}\n    \n    \nconst RealSymMatrix& SurfpackApproximation::hessian(const RealVector& c_vars)\n{\n    size_t num_cv = c_vars.length();\n    approxHessian.reshape(num_cv);\n    try {\n        if (sharedDataRep->approxType == \"global_moving_least_squares\") {\n            Cerr << \"Have not implemented analytical hessians in this surfpack class\"\n            << std::endl;\n            abort_handler(-1);\n        }\n        RealArray x_array;\n        for (size_t i = 0; i < num_cv; i++) x_array.push_back(c_vars[i]);\n        \n        MtxDbl sm = model->hessian(x_array);\n        ///\\todo Make this acceptably efficient\n        for (size_t i = 0; i < num_cv; i++)\n            for(size_t j = 0; j < num_cv; j++)\n                approxHessian(i,j) = sm(i,j);\n    }\n    catch (...) {\n        Cerr << \"Error: hessian() not available for this approximation type.\"\n        << std::endl;\n        abort_handler(-1);\n    }\n    return approxHessian;\n}\n    \n    \nReal SurfpackApproximation::prediction_variance(const RealVector& c_vars)\n{\n    try {\n        RealArray x_array;\n        size_t num_vars = c_vars.length();\n        for (size_t i = 0; i < num_vars; i++) x_array.push_back(c_vars[i]);\n        return model->variance(x_array);\n    }\n    catch (...) {\n        Cerr << \"Error: prediction_variance() not available for this \"\n        << \"approximation type.\" << std::endl;\n        abort_handler(-1);\n    }\n}\n\n\nReal SurfpackApproximation::diagnostic(const String& metric_type)\n{ \n  if (!model) { \n    Cerr << \"Error: surface is null in SurfpackApproximation::diagnostic()\"\n         << std::endl;  \n    abort_handler(-1);\n  }\n\n  return diagnostic(metric_type, *model, *surfData);\n}\n\n\nReal SurfpackApproximation::diagnostic(const String& metric_type,\n\t\t\t\t       const SurfpackModel& sp_model,\n\t\t\t\t       const SurfData& s_data)\n{ \n  Real approx_diag;\n  try {\n    ModelFitness* SS_fitness = ModelFitness::Create(metric_type);\n    approx_diag = (*SS_fitness)(sp_model, s_data);\n    delete SS_fitness;\n  }\n  catch (const std::string& msg) {\n    Cerr << \"Error evaluating surrogate metric: \" << msg << std::endl;\n    abort_handler(-1);\n  }\n\n  Cout << std::setw(20) << metric_type << std::setw(20) << approx_diag << '\\n';\n  return approx_diag;\n}\n\n\nvoid SurfpackApproximation::primary_diagnostics(int fn_index)\n{\n  String func_description = approxLabel.empty() ? \n    \"function \" + boost::lexical_cast<std::string>(fn_index+1) : approxLabel;  \n  SharedSurfpackApproxData* shared_surf_data_rep\n    = (SharedSurfpackApproxData*)sharedDataRep;\n  const StringArray& diag_set = shared_surf_data_rep->diagnosticSet;\n  if (diag_set.empty()) {\n    // conditionally print default diagnostics\n    if (sharedDataRep->outputLevel > NORMAL_OUTPUT) {\n      Cout << \"\\nSurrogate quality metrics for \" << func_description << \":\\n\";\n      diagnostic(\"root_mean_squared\");\t\n      diagnostic(\"mean_abs\");\n      diagnostic(\"rsquared\");\n    }\n  }\n  else {\n    Cout << \"\\nSurrogate quality metrics for \" << func_description << \":\\n\";\n    int num_diag = diag_set.size();\n    for (int j = 0; j < num_diag; ++j)\n      diagnostic(diag_set[j]);\n   \n    // BMA TODO: at runtime verify (though Surfpack will too) \n    //  * 1/N <= percentFold <= 0.5\n    //  * 2 <= numFolds <= N\n    if (shared_surf_data_rep->crossValidateFlag) {\n      int num_folds = shared_surf_data_rep->numFolds;\n      // if no folds, try percent, otherwise set default = 10\n      if (num_folds == 0) {\n        if (shared_surf_data_rep->percentFold > 0.0) {\n          num_folds = boost::math::iround(1./shared_surf_data_rep->percentFold);\n          if (sharedDataRep->outputLevel >= DEBUG_OUTPUT)\n            Cout << \"Info: cross_validate num_folds = \" << num_folds \n                 << \" calculated from specified percent = \"\n                 << shared_surf_data_rep->percentFold << \".\" << std::endl;\n        }\n        else {\n          num_folds = 10;\n          if (sharedDataRep->outputLevel >= DEBUG_OUTPUT)\n            Cout << \"Info: default num_folds = \" << num_folds << \" used.\"\n                 << std::endl;\n        }\n      }\n\n      Cout << \"\\nSurrogate quality metrics (\" << num_folds << \"-fold CV) for \" \n           << func_description << \":\\n\";\n      RealArray cv_metrics = cv_diagnostic(diag_set, num_folds);\n      //CrossValidationFitness CV_fitness(num_folds);\n      //VecDbl cv_metrics;\n      //CV_fitness.eval_metrics(cv_metrics, *model, *surfData, diag_set);\n      \n      for (int j = 0; j < num_diag; ++j) {\n        const String& metric_type = diag_set[j];\n        if (metric_type == \"rsquared\")\n          Cout << std::setw(20) << metric_type\n               << std::setw(20) << std::numeric_limits<Real>::quiet_NaN()\n               << \"  (n/a for cross-validation)\" \n               << std::endl;\n        else\n          Cout << std::setw(20) << metric_type << std::setw(20) << cv_metrics[j] \n               << std::endl;\n      }\n\n    }\n    if (shared_surf_data_rep->pressFlag) {\n      Cout << \"\\nSurrogate quality metrics (PRESS/leave-one-out) for \" \n           << func_description << \":\\n\";\n     \n      // perform press as CV with N folds\n      RealArray cv_metrics = cv_diagnostic(diag_set, surfData->size());\n      //CrossValidationFitness CV_fitness(surfData->size());\n      //VecDbl cv_metrics;\n      //CV_fitness.eval_metrics(cv_metrics, *model, *surfData, diag_set);\n     \n      for (int j = 0; j < num_diag; ++j) {\n        const String& metric_type = diag_set[j];\n        if (metric_type == \"rsquared\")\n          Cout << std::setw(20) << metric_type \n               << std::setw(20) << std::numeric_limits<Real>::quiet_NaN()\n               << \"  (n/a for PRESS)\" << std::endl;\n        else\n          Cout << std::setw(20) << metric_type << std::setw(20) << cv_metrics[j] \n               << std::endl;\n      }\n\n    }\n  }\n}\n\n\nvoid SurfpackApproximation::\nchallenge_diagnostics(int fn_index, const RealMatrix& challenge_points,\n                      const RealVector& challenge_responses)\n{\n  if (!model) { \n    Cerr << \"Error: surface is null in SurfpackApproximation::diagnostic()\"\n\t << std::endl;  \n    abort_handler(-1);\n  }\n  \n  String func_description = approxLabel.empty() ? \n    \"function \" + boost::lexical_cast<std::string>(fn_index+1) : approxLabel;  \n\n  // copy\n  StringArray diag_set = \n    ((SharedSurfpackApproxData*)sharedDataRep)->diagnosticSet;\n  if (diag_set.empty()) {\n    // conditionally print default diagnostics\n    if (sharedDataRep->outputLevel > NORMAL_OUTPUT) {\n      Cout << \"\\nSurrogate quality metrics (challenge data) for \" \n\t   << func_description << \":\\n\";\n      diag_set.push_back(\"root_mean_squared\");\t\n      diag_set.push_back(\"mean_abs\");\n      diag_set.push_back(\"rsquared\");\n      challenge_diagnostic(diag_set, challenge_points, challenge_responses);\n    }\n  }\n  else {\n    Cout << \"\\nSurrogate quality metrics (challenge data) for \" \n\t << func_description << \":\\n\";\n    challenge_diagnostic(diag_set, challenge_points, challenge_responses);\n  }\n\n}\n\nRealArray SurfpackApproximation::cv_diagnostic(const StringArray& metric_types, \n                                               unsigned num_folds) {\n  CrossValidationFitness CV_fitness(num_folds);\n  VecDbl cv_metrics;\n  try {\n    CV_fitness.eval_metrics(cv_metrics, *model, *surfData, metric_types);\n  } catch(String cv_error) {\n    Cerr << \"Error: Exception caught while computing CV score:\\n\" << cv_error << std::endl;\n    cv_metrics.resize(metric_types.size());\n    std::fill(cv_metrics.begin(), cv_metrics.end(), std::numeric_limits<Real>::quiet_NaN());\n  }\n  return cv_metrics;\n}\n\nRealArray SurfpackApproximation::challenge_diagnostic(const StringArray& metric_types,\n\t\t\t    const RealMatrix& challenge_points,\n                            const RealVector& challenge_responses) {\n  // JAS: painful but probably unavoidable data copy on every call.\n  SurfData chal_data;\n  RealArray chal_metrics;\n  size_t num_v = sharedDataRep->numVars;\n  for (size_t row=0; row<challenge_points.numRows(); ++row) {\n    RealArray x(num_v);\n    for (size_t col=0; col<num_v; ++col)\n      x[col] = challenge_points[col][row];\n    Real f = challenge_responses[row];\n    chal_data.addPoint(SurfPoint(x, f));\n  }\n  for (int j = 0; j < metric_types.size(); ++j)\n    chal_metrics.push_back(diagnostic(metric_types[j], *model, chal_data));\n  return chal_metrics;\n}\n\n/** Copy the data stored in Dakota-style SurrogateData into\n    Surfpack-style SurfPoint and SurfData objects. */\nSurfData* SurfpackApproximation::surrogates_to_surf_data()\n{\n  SurfData* surf_data = new SurfData();\n\n  // screen approximation data for failures\n  approxData.data_checks();\n\n  // some surrogates, e.g., global_polynomials and kriging, treat the anchor\n  // point specially as a constraint; other treat as a regular data point\n  SharedSurfpackApproxData* shared_surf_data_rep\n    = (SharedSurfpackApproxData*)sharedDataRep;\n  if (approxData.anchor()) {\n    if (factory->supports_constraints())\n      add_anchor_to_surfdata(*surf_data);\n    else\n      shared_surf_data_rep->\n\tadd_sd_to_surfdata(approxData.anchor_variables(),\n\t\t\t   approxData.anchor_response(),\n\t\t\t   approxData.failed_anchor_data(), *surf_data);\n  }\n  // add the remaining surrogate data points\n  if (sharedDataRep->outputLevel >= DEBUG_OUTPUT)\n    Cout << \"Requested build data order is \" << sharedDataRep->buildDataOrder\n\t << '\\n';\n  size_t i, num_data_pts = approxData.points();\n  const Pecos::SDVArray& sdv_array = approxData.variables_data();\n  const Pecos::SDRArray& sdr_array = approxData.response_data();\n  const Pecos::SizetShortMap& failed_resp = approxData.failed_response_data();\n  Pecos::SizetShortMap::const_iterator fit = failed_resp.begin();\n  for (i=0; i<num_data_pts; ++i) {\n    short fail_code = 0;\n    if (fit != failed_resp.end() && fit->first == i)\n      { fail_code = fit->second; ++fit; }\n    shared_surf_data_rep->add_sd_to_surfdata(sdv_array[i], sdr_array[i],\n\t\t\t\t\t     fail_code, *surf_data);\n  }\n\n  return surf_data;\n}\n\n\n/** If there is an anchor point, add an equality constraint for its response\n    value.  Also add constraints for gradient and hessian, if applicable. */\nvoid SurfpackApproximation::add_anchor_to_surfdata(SurfData& surf_data)\n{\n  // coarse-grained fault tolerance for now: any failure qualifies for omission\n  if (approxData.failed_anchor_data())\n    return;\n\n  // Surfpack's RealArray is std::vector<double>\n  RealArray x; \n  Real f;\n  RealArray gradient;\n  SurfpackMatrix<Real> hessian;\n\n  // Print out the anchor continuous variables\n  SharedSurfpackApproxData* shared_surf_data_rep\n    = (SharedSurfpackApproxData*)sharedDataRep;\n  shared_surf_data_rep->sdv_to_realarray(approxData.anchor_variables(), x);\n  if (sharedDataRep->outputLevel > NORMAL_OUTPUT)\n    Cout << \"Anchor point vars\\n\" << x;\n\n  // At a minimum, there should be a response value\n  unsigned short anchor_data_order = 1;\n  f = approxData.anchor_function();\n  if (sharedDataRep->outputLevel > NORMAL_OUTPUT)\n    Cout << \"Anchor response: \" << f << '\\n';\n\n  // Check for gradient in anchor point\n  const RealVector& anchor_grad = approxData.anchor_gradient();\n  if (!anchor_grad.empty()) {\n    anchor_data_order |= 2;\n    copy_data(anchor_grad, gradient);\n    if (sharedDataRep->outputLevel > NORMAL_OUTPUT) {\n      Cout << \"Anchor gradient:\\n\";\n      write_data(Cout, anchor_grad);\n    }\n  }\n\n  // Check for hessian in anchor point\n  const RealSymMatrix& anchor_hess = approxData.anchor_hessian();\n  if (!anchor_hess.empty()) {\n    anchor_data_order |= 4;\n    shared_surf_data_rep->copy_matrix(anchor_hess, hessian);\n    if (sharedDataRep->outputLevel > NORMAL_OUTPUT) {\n      Cout << \"Anchor hessian:\\n\";\n      write_data(Cout, anchor_hess, false, true, true);\n    }\n  }\n\n  if (sharedDataRep->outputLevel > NORMAL_OUTPUT)\n    Cout << \"Requested constraint data order is \" << anchor_data_order\n\t << '\\n';\n\n  // for now only allow builds from exactly 1, 3=1+2, or 7=1+2+4; use\n  // different set functions so the SurfPoint data remains empty if\n  // not present\n  switch (anchor_data_order) {\n\n  case 1:\n    surf_data.setConstraintPoint(SurfPoint(x, f));\n    break;\n\n  case 3:\n    surf_data.setConstraintPoint(SurfPoint(x, f, gradient));\n    break;\n\n  case 7:\n    surf_data.setConstraintPoint(SurfPoint(x, f, gradient, hessian));\n    break;\n\n  default:\n    Cerr << \"\\nError (SurfpackApproximation): derivative data may only be used\"\n\t << \"if all\\nlower-order information is also present. Specified \"\n\t << \"anchor_data_order is \" << anchor_data_order << \".\"  << std::endl; \n    abort_handler(-1);\n    break;\n\n  }\n\n}\n\n} // namespace Dakota\n", "meta": {"hexsha": "4f39f8bdc194a9c76c301fdb7ac5f8e669283b9d", "size": 34407, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/SurfpackApproximation.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/SurfpackApproximation.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/SurfpackApproximation.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": 33.6663405088, "max_line_length": 92, "alphanum_fraction": 0.6636149621, "num_tokens": 8911, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6723316991792861, "lm_q2_score": 0.4571367168274948, "lm_q1q2_score": 0.30734750558186974}}
{"text": "// File: finite_grad_check.cc\n// Author: Karl Moritz Hermann (mail@karlmoritz.com)\n// Created: 01-01-2013\n// Last Update: Thu 03 Oct 2013 11:44:36 AM BST\n\n// STL\n#include <iostream>\n#include <cmath>\n\n// Boost\n#include <boost/program_options/variables_map.hpp>\n#include <boost/program_options/parsers.hpp>\n\n#include \"shared_defs.h\"\n\n// L-BFGS\n#include <lbfgs.h>\n\n// Local\n#include \"finite_grad_check.h\"\n#include \"train_update.h\"\n#include \"recursive_autoencoder.h\"\n\nusing namespace std;\nnamespace bpo = boost::program_options;\n\n\nint finite_grad_check(Model &model)\n{\n  Real* vars = nullptr;\n  int number_vars = 0;\n\n  modvars<int> counts;\n  model.rae.setIncrementalCounts(counts,vars,number_vars);\n\n  WeightVectorType theta(vars,number_vars);\n\n  Real* data1 = new Real[number_vars]();\n  Real* data2 = new Real[number_vars]();\n  WeightVectorType grad(data1,number_vars);\n  WeightVectorType grad2(data2,number_vars);\n\n  Real error1 = computeCostAndGrad(model,nullptr,data1,number_vars);\n\n  modvars<Real> dists;\n  Real dist = 0.0;\n\n  Real delta = 1.0e-7;\n\n  for (int i=0;i<number_vars;++i)\n  {\n    theta[i] += delta;\n    Real error2 = computeCostAndGrad(model,nullptr,data2,number_vars);\n    Real xdev = (error2 - error1) / delta;\n    theta[i] -= delta;\n    if (i < counts.D)   { dists.D += abs(grad2[i] - xdev);   cout << \"D   \"; }\n    else if (i < counts.U)  { dists.U += abs(grad2[i] - xdev);  cout << \"U  \"; }\n    else if (i < counts.V)  { dists.V += abs(grad2[i] - xdev);  cout << \"V  \"; }\n    else if (i < counts.W)  { dists.W += abs(grad2[i] - xdev);  cout << \"W  \"; }\n    else if (i < counts.A)  { dists.A += abs(grad2[i] - xdev);  cout << \"A  \"; }\n    else if (i < counts.Wd)  { dists.Wd += abs(grad2[i] - xdev);  cout << \"Wd  \"; }\n    else if (i < counts.Wdr) { dists.Wdr += abs(grad2[i] - xdev); cout << \"Wdr \"; }\n    else if (i < counts.Bd)  { dists.Bd += abs(grad2[i] - xdev);  cout << \"Bd  \"; }\n    else if (i < counts.Bdr) { dists.Bdr += abs(grad2[i] - xdev); cout << \"Bdr \"; }\n    else if (i < counts.Wf)  { dists.Wf += abs(grad2[i] - xdev);  cout << \"Wf  \"; }\n    else if (i < counts.Wl)  { dists.Wl += abs(grad2[i] - xdev);  cout << \"Wl  \"; }\n    else if (i < counts.Bl)  { dists.Bl += abs(grad2[i] - xdev);  cout << \"Bl  \"; }\n\n    //template<> void modvars<int>::init() { D = 0; U = 0; V = 0; W = 0; A = 0; Wd = 0; Wdr = 0; Bd = 0; Bdr = 0; Wf = 0; Wl = 0; Bl = 0; alpha_rae = 0; alpha_lbl = 0; }\n    cout << i << \": \" << grad2[i] << \" vs \" << (xdev) << \"   \" << error2 << \" - \" << error1 << \"[\" << theta[i] << \"]\" << endl;\n\n    dist += abs(grad2[i] - xdev);\n  }\n\n  cout << \"total: \" << dist << \" D/U/V/W/A/Wd/Wdr/Bd/Bdr/Wf/Wl/Bl \" << endl;\n  cout << dists.D << \" \";\n  cout << dists.U << \" \";\n  cout << dists.V << \" \";\n  cout << dists.W << \" \";\n  cout << dists.A << \" \";\n  cout << dists.Wd << \" \" << dists.Wdr << \" \" << dists.Bd << \" \" << dists.Bdr << \" \";\n  cout << dists.Wf << \" \";\n  cout << dists.Wl << \" \" << dists.Bl << endl;\n  // Don't care about what's next\n  assert(false);\n\n  return 0;\n}\n", "meta": {"hexsha": "d8b9197754a338cc23787ba11842004db67101a7", "size": 3010, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/common/finite_grad_check.cc", "max_stars_repo_name": "karlmoritz/oxcvsm", "max_stars_repo_head_hexsha": "02fd78231a8b3c4d48e9e759a3a075d04bcd0529", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2015-02-06T01:41:41.000Z", "max_stars_repo_stars_event_max_datetime": "2017-10-06T15:50:32.000Z", "max_issues_repo_path": "src/common/finite_grad_check.cc", "max_issues_repo_name": "karlmoritz/oxcvsm", "max_issues_repo_head_hexsha": "02fd78231a8b3c4d48e9e759a3a075d04bcd0529", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/common/finite_grad_check.cc", "max_forks_repo_name": "karlmoritz/oxcvsm", "max_forks_repo_head_hexsha": "02fd78231a8b3c4d48e9e759a3a075d04bcd0529", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2015-01-02T10:49:15.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-30T17:59:22.000Z", "avg_line_length": 33.8202247191, "max_line_length": 169, "alphanum_fraction": 0.5671096346, "num_tokens": 1059, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.672331699179286, "lm_q2_score": 0.4571367168274948, "lm_q1q2_score": 0.3073475055818697}}
{"text": "\n//  Copyright (c) 2011-2013 Thomas Heller\n//\n//  SPDX-License-Identifier: BSL-1.0\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#if !defined(JACOBI_SMP_NO_pika)\n#include <pika/init.hpp>\n#endif\n\n#include <pika/modules/program_options.hpp>\n\n#include <boost/spirit/include/phoenix.hpp>\n#include <boost/spirit/include/qi_action.hpp>\n#include <boost/spirit/include/qi_auxiliary.hpp>\n#include <boost/spirit/include/qi_char.hpp>\n#include <boost/spirit/include/qi_numeric.hpp>\n#include <boost/spirit/include/qi_operator.hpp>\n#include <boost/spirit/include/qi_parse.hpp>\n#include <boost/spirit/include/qi_string.hpp>\n#include <boost/spirit/include/support_istream_iterator.hpp>\n\n#include <cstddef>\n#include <fstream>\n#include <iostream>\n#include <string>\n#include <vector>\n\nusing pika::program_options::options_description;\nusing pika::program_options::parse_command_line;\nusing pika::program_options::store;\nusing pika::program_options::value;\nusing pika::program_options::variables_map;\n\n#include \"jacobi_nonuniform.hpp\"\n\nnamespace jacobi_smp {\n\n    void jacobi_kernel_nonuniform(crs_matrix<double> const& A,\n        std::vector<double>& dst, std::vector<double> const& src,\n        std::vector<double> const& b, std::size_t row)\n    {\n        double result = b[row];\n        double div = 1.0;\n        const std::size_t begin = A.row_begin(row);\n        const std::size_t end = A.row_end(row);\n\n        for (std::size_t j = begin; j < end; ++j)\n        {\n            if (row == j)\n                div = div / A.values[j];\n            else\n                result -= A.values[j] * src[A.indices[j]];\n        }\n        dst[row] = result * div;\n    }\n}    // namespace jacobi_smp\n\nnamespace qi = boost::spirit::qi;\nnamespace phx = boost::phoenix;\n\nvoid init(\n    jacobi_smp::crs_matrix<double>& M, std::size_t dim, std::size_t non_zeros)\n{\n    M.values.reserve(non_zeros);\n    M.indices.reserve(non_zeros);\n    M.rows.reserve(dim + 1);\n    M.rows.push_back(0);\n}\n\nvoid add_entry(jacobi_smp::crs_matrix<double>& M, std::size_t& row,\n    std::size_t& n, std::size_t j, std::size_t i, double v)\n{\n    M.values.push_back(v);\n    M.indices.push_back(j);\n    ++n;\n    if (i != row)\n    {\n        row = i;\n        M.rows.push_back(M.rows.back() + n);\n        n = 0;\n    }\n}\n\nint pika_main(variables_map& vm)\n{\n#if !defined(JACOBI_SMP_NO_pika)\n    pika::scoped_finalize f;\n#endif\n\n    {\n        std::size_t iterations = vm[\"iterations\"].as<std::size_t>();\n        std::size_t block_size = vm[\"block-size\"].as<std::size_t>();\n        std::string matrix = vm[\"matrix\"].as<std::string>();\n        std::string mode = vm[\"mode\"].as<std::string>();\n\n        jacobi_smp::crs_matrix<double> A;\n        std::vector<double> x;\n        std::vector<double> b;\n\n        {\n            std::ifstream file(matrix.c_str());\n            file.unsetf(std::ios_base::skipws);\n            using iterator = boost::spirit::istream_iterator;\n            iterator begin(file);\n            iterator end;\n\n            std::size_t current_row = 0;\n            std::size_t non_zero_row = 0;\n            std::size_t dim = 0;\n            std::size_t non_zero_entries = 0;\n\n            qi::phrase_parse(begin, end,\n                (qi::int_[phx::ref(dim) = qi::_1] >> qi::int_ >>\n                    qi::int_[phx::ref(non_zero_entries) = qi::_1])[phx::bind(\n                    init, phx::ref(A), dim, non_zero_entries)] >>\n                    *(    // entry\n                        (qi::int_ >> qi::int_ >> qi::double_)[phx::bind(\n                            add_entry, phx::ref(A), phx::ref(current_row),\n                            phx::ref(non_zero_row), qi::_1, qi::_2, qi::_3)]),\n                qi::space |\n                    (qi::lit(\"%\") >> *(!qi::eol >> qi::char_) >> qi::eol));\n\n            if (dim == 0)\n            {\n                std::cerr << \"Parsed zero non zero values in matrix file \"\n                          << matrix << \"\\n\";\n                return 1;\n            }\n\n            std::cout << \"A: \" << dim << \"x\" << dim\n                      << \" number of non zeros: \" << non_zero_entries << \"\\n\";\n        }\n        if (vm.count(\"vector\"))\n        {\n            std::string vector = vm[\"vector\"].as<std::string>();\n            std::ifstream file(vector.c_str());\n            file.unsetf(std::ios_base::skipws);\n            using iterator = boost::spirit::istream_iterator;\n            iterator begin(file);\n            iterator end;\n            qi::phrase_parse(begin, end, *qi::double_, qi::ascii::space, b);\n        }\n        else\n        {\n            b = std::vector<double>(A.rows.size() - 1, 1.0);\n        }\n        std::cout << \"b: \" << b.size() << \"\\n\";\n\n        if (mode == \"solve\")\n        {\n            jacobi_smp::jacobi(A, b, iterations, block_size);\n        }\n        else if (mode == \"statistics\")\n        {\n            std::size_t min_per_row = (std::numeric_limits<std::size_t>::max)();\n            std::size_t max_per_row = 0;\n            double mean_per_row = 0.0;\n            for (std::size_t r = 0; r < b.size(); ++r)\n            {\n                const std::size_t begin = A.row_begin(r);\n                const std::size_t end = A.row_end(r);\n                std::size_t n_row = end - begin;\n                mean_per_row += double(n_row);\n                if (n_row > max_per_row)\n                {\n                    max_per_row = n_row;\n                }\n                if (n_row < min_per_row)\n                {\n                    min_per_row = n_row;\n                }\n            }\n            std::cout << \"Matrix has \" << A.values.size()\n                      << \" non zero entries\\n\";\n            std::cout << \"order: \" << b.size() << \"x\" << b.size() << \"\\n\";\n            std::cout << \"Entries per row:\\n\";\n            std::cout << \"\\tmax \" << max_per_row << \"\\n\";\n            std::cout << \"\\tmin \" << min_per_row << \"\\n\";\n            std::cout << \"\\tmean \" << mean_per_row / double(b.size()) << \"\\n\";\n            std::cout << \"Density is: \"\n                      << double(A.values.size()) / double(b.size() * b.size())\n                      << \"\\n\";\n        }\n        else\n        {\n            std::cout << \"Unknown mode \" << mode << \"\\n\";\n            return 1;\n        }\n    }\n\n    return 0;\n}\n\nint main(int argc, char** argv)\n{\n    options_description desc_cmd(\n        \"usage: \" PIKA_APPLICATION_STRING \" [options]\");\n\n    // clang-format off\n    desc_cmd.add_options()\n        (\"iterations\", value<std::size_t>()->default_value(1000),\n         \"Number of iterations\")\n        (\"block-size\", value<std::size_t>()->default_value(256),\n         \"Block size of the different chunks to calculate in parallel\")\n        (\"matrix\", value<std::string>(),\n         \"Filename of the input matrix (Matrix Market format)\")\n        (\"vector\", value<std::string>(), \"Filename of the right hand side vector\")\n        (\"mode\", value<std::string>()->default_value(\"solve\"),\n        \"Mode of the program, can be solve or statistics (default: solve)\");\n    // clang-format on\n\n#if defined(JACOBI_SMP_NO_pika)\n    variables_map vm;\n    desc_cmd.add_options()(\"help\", \"This help message\");\n    store(parse_command_line(argc, argv, desc_cmd), vm);\n    if (vm.count(\"help\"))\n    {\n        std::cout << desc_cmd;\n        return 1;\n    }\n    return pika_main(vm);\n#else\n    pika::init_params init_args;\n    init_args.desc_cmdline = desc_cmd;\n\n    return pika::init(pika_main, argc, argv, init_args);\n#endif\n}\n", "meta": {"hexsha": "a31e7101556cec3efbf693e71ce71c4c2cfca10c", "size": 7506, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/jacobi_smp/jacobi_nonuniform.cpp", "max_stars_repo_name": "pika-org/pika", "max_stars_repo_head_hexsha": "c80f542b2432a7f108fcfba31a5fe5073ad2b3e1", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 13.0, "max_stars_repo_stars_event_min_datetime": "2022-01-17T12:01:48.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-16T10:03:14.000Z", "max_issues_repo_path": "examples/jacobi_smp/jacobi_nonuniform.cpp", "max_issues_repo_name": "pika-org/pika", "max_issues_repo_head_hexsha": "c80f542b2432a7f108fcfba31a5fe5073ad2b3e1", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 163.0, "max_issues_repo_issues_event_min_datetime": "2022-01-17T17:36:45.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T17:42:57.000Z", "max_forks_repo_path": "examples/jacobi_smp/jacobi_nonuniform.cpp", "max_forks_repo_name": "pika-org/pika", "max_forks_repo_head_hexsha": "c80f542b2432a7f108fcfba31a5fe5073ad2b3e1", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2022-01-19T08:44:22.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-31T23:16:21.000Z", "avg_line_length": 32.4935064935, "max_line_length": 82, "alphanum_fraction": 0.537569944, "num_tokens": 1907, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5428632979641571, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.307270688725397}}
{"text": "// Copyright (C) 2011-2013 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_modified_aca_hpp\n#define bempp_modified_aca_hpp\n\n#include \"../common/common.hpp\"\n#include \"bempp/common/config_ahmed.hpp\"\n\n#ifdef WITH_AHMED\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 <boost/scoped_array.hpp>\n#include <limits>\n\nnamespace Bempp\n{\n\n// returns true if a pivot could be found (there were any nonapproximated\n// rows or columns), false otherwise\ntemplate <class abs_T>\nbool select_pivot_with_min_norm2(unsigned n, const abs_T* norm2,\n                                 const int* apprx_times /* S or Z */,\n                                 unsigned& pivot)\n{\n    pivot = n; // invalid value\n    abs_T min_norm2 = std::numeric_limits<abs_T>::max();\n    for (unsigned i = 0; i < n; ++i)\n        if (apprx_times[i] >= 0 && norm2[i] < min_norm2) {\n            min_norm2 = norm2[i];\n            pivot = i;\n        }\n    return (pivot != n);\n}\n\ntemplate<class T, class MATGEN_T>\nbool ACAs(MATGEN_T& MatGen, unsigned b1, unsigned n1, unsigned b2, unsigned n2,\n          double eps, unsigned kmax, unsigned i0, unsigned& k, T* &U, T* &V,\n          const cluster* c1, const cluster* c2)\n{\n    typedef typename num_traits<T>::abs_type abs_T;\n    unsigned no = 0; // number of crosses calculated so far\n    unsigned klast;  // unused\n    const unsigned maxit = std::min(n1, n2);\n\n    abs_T scale = MatGen.scale(b1, n1, b2, n2, c1, c2); // set initial scale\n\n    U = new T[(kmax+1)*n1]; // these arrays are expected to be\n    V = new T[(kmax+1)*n2]; // deallocated by the caller\n    assert(U != NULL && V != NULL);\n\n    // arrays storing number of successful approximations of rows and columns\n    boost::scoped_array<int> Z(new int[n1]), S(new int[n2]);\n    for (unsigned l=0; l<n1; ++l)\n        Z[l] = 0;\n    for (unsigned l=0; l<n2; ++l)\n        S[l] = 0;\n\n    boost::scoped_array<T> orig_row(new T[n2]);\n    boost::scoped_array<T> orig_col(new T[n1]);\n\n    boost::scoped_array<abs_T> orig_row_norm2(new abs_T[n2]);\n    boost::scoped_array<abs_T> orig_col_norm2(new abs_T[n1]);\n\n    abs_T nrms2 = 0.; // squared Frobenius norm of U V^H\n\n    const unsigned ROW = 0, COL = 1;\n    const unsigned NORMAL = 0, FIRST_SHOT = 1, SECOND_SHOT = 2;\n    unsigned mode = ROW;\n    unsigned stage = NORMAL;\n\n    k = 0;\n    unsigned next_pivot = i0;\n\n    // The relativeScale() function is expected to return an estimate of the\n    // magnitude of the largest element in the block, relative to the magnitude\n    // of the largest element in the whole matrix.\n    // If the result is deemed small enough relative to eps, the block is taken to\n    // be zero and its elements are not evaluate.\n    // This can be useful in the approximation of strongly decaying kernels.\n    // abs_T relscale = MatGen.relativeScale(b1, n1, b2, n2, c1, c2);\n    // if (relscale < 1e-2 * eps)\n    //     return true;\n\n    do {\n        ACA_status status;\n        abs_T nrmlsk2; // product of squared norms of new columns of U and V\n        bool retry_if_zero = (stage == NORMAL); // don't retry if shooting\n        // compute a cross\n        if (mode == ROW)\n            status = ACA_row_step(\n                        MatGen, b1, n1, b2, n2, klast, next_pivot, k, no,\n                        Z.get(), S.get(), U, V, nrmlsk2, scale, c1, c2,\n                        retry_if_zero, orig_row.get(), orig_col.get());\n        else\n            status = ACA_col_step(\n                        MatGen, b1, n1, b2, n2, next_pivot, k, no,\n                        Z.get(), S.get(), U, V, nrmlsk2, scale, c1, c2,\n                        retry_if_zero, orig_row.get(), orig_col.get());\n        // std::cout << \"status = \" << status << std::endl;\n\n        bool stpcrit = false;\n        if (status == ACA_STATUS_SUCCESS) {\n            // check stopping criterion\n            T sum = 0.;                            // update nrms2\n            for (unsigned l=0; l<k; ++l)\n                sum += blas::scpr(n1, U+l*n1, U+k*n1) * blas::scpr(n2, V+k*n2, V+l*n2);\n            nrms2 += 2. * Re(sum) + nrmlsk2;\n\n            stpcrit = (nrmlsk2 < eps * eps * nrms2);\n            // adjust scale (estimated entry size of the next remainder)\n            scale = sqrt(nrmlsk2/(n1*n2));\n            // std::cout << \"nrmlsk2: \" << nrmlsk2 << \", nrms2: \" << nrms2 << \", scale = \" << scale\n            //           << std::endl;\n\n            ++k;\n        } else if (status == ACA_STATUS_EARLY_EXIT)\n            stpcrit = true;\n        else {\n            // in the last step no non-zero row/column could be found\n            assert(status == ACA_STATUS_REMAINDER_IS_ZERO);\n            return true;\n        }\n\n        if (stpcrit) {\n            if (stage == SECOND_SHOT)\n                return true;\n            else if (stage == FIRST_SHOT) {\n                if (mode == ROW) {\n                    // select column pivot\n                    bool found = select_pivot_with_min_norm2(\n                                n2, orig_row_norm2.get(), S.get(), next_pivot);\n                    if (!found) // no nonapproximated column could be found\n                        return true;\n                    mode = COL;\n                } else {\n                    // select row pivot\n                    bool found = select_pivot_with_min_norm2(\n                                n1, orig_col_norm2.get(), Z.get(), next_pivot);\n                    if (!found) // no nonapproximated row could be found\n                        return true;\n                    mode = ROW;\n                }\n                stage = SECOND_SHOT;\n            } else {\n                assert(stage == NORMAL);\n                for (unsigned i = 0; i < n2; ++i)\n                    orig_row_norm2[i] = abs2(orig_row[i]);\n                for (unsigned i = 0; i < n1; ++i)\n                    orig_col_norm2[i] = abs2(orig_col[i]);\n                if (mode == ROW) {\n                    // select row pivot\n                    bool found = select_pivot_with_min_norm2(\n                                n1, orig_col_norm2.get(), Z.get(), next_pivot);\n                    if (!found) // no nonapproximated row could be found\n                        return true;\n                }\n                else {\n                    // select column pivot\n                    bool found = select_pivot_with_min_norm2(\n                                n2, orig_row_norm2.get(), S.get(), next_pivot);\n                    if (!found) // no nonapproximated column could be found\n                        return true;\n                }\n                stage = FIRST_SHOT;\n                // mode stays the same\n            }\n        } else\n            stage = NORMAL;\n            // mode stays the same\n\n        // std::cout << \"Stage: \" << stage << \", mode: \" << mode << \"\\n\";\n    } while (no < maxit && k < kmax);\n\n    // std::cout << \"Giving up\" << std::endl;\n    return false;\n}\n\ntemplate<class T,class T1,class T2, class MATGEN_T>\nvoid apprx_unsym_shooting(\n        MATGEN_T& MatGen, mblock<T>* &mbl, bemblcluster<T1,T2>* bl,\n        double eps, unsigned rankmax)\n{\n    apprx_unsym_generic(&ACAs<T, MATGEN_T>, MatGen, mbl, bl, eps, rankmax);\n}\n\n} // namespace Bempp\n\n#endif // WITH_AHMED\n\n#endif\n", "meta": {"hexsha": "703f2940a3d466b7fb57a3e1cf93922e8117fc0b", "size": 8317, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "lib/assembly/modified_aca.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/modified_aca.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/modified_aca.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": 38.1513761468, "max_line_length": 99, "alphanum_fraction": 0.5616207767, "num_tokens": 2103, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5698526660244837, "lm_q2_score": 0.5389832206876841, "lm_q1q2_score": 0.30714102525133946}}
{"text": "#include \"eigen_numpy.h\"\n\n#include <Eigen/Eigen>\n#if EIGEN_VERSION_AT_LEAST(3, 3, 0)\n#include <unsupported/Eigen/CXX11/Tensor>\n#endif // EIGEN_VERSION_AT_LEAST(3, 3, 0)\n#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION\n#include <numpy/arrayobject.h>\n\n// These macros were renamed in NumPy 1.7.1.\n#if !defined(NPY_ARRAY_C_CONTIGUOUS) && defined(NPY_C_CONTIGUOUS)\n#define NPY_ARRAY_C_CONTIGUOUS NPY_C_CONTIGUOUS\n#endif\n\n#if !defined(NPY_ARRAY_ALIGNED) && defined(NPY_ALIGNED)\n#define NPY_ARRAY_ALIGNED NPY_ALIGNED\n#endif\n\nnamespace bp = boost::python;\n\nusing namespace Eigen;\n\ntemplate <typename SCALAR>\nstruct NumpyEquivalentType {};\n\ntemplate <> struct NumpyEquivalentType<double> {enum {type_code = NPY_DOUBLE};};\ntemplate <> struct NumpyEquivalentType<float> {enum {type_code = NPY_FLOAT};};\ntemplate <> struct NumpyEquivalentType<int> {enum {type_code = NPY_INT};};\ntemplate <> struct NumpyEquivalentType<unsigned short>{enum {type_code = NPY_USHORT};};\ntemplate <> struct NumpyEquivalentType<unsigned char>{enum {type_code = NPY_UBYTE};};\ntemplate <> struct NumpyEquivalentType<std::complex<double> > {enum {type_code = NPY_CDOUBLE};};\n\ntemplate <typename SourceType, typename DestType >\nstatic void copy_array(const SourceType* source, DestType* dest,\n                       const npy_int &nb_rows, const npy_int &nb_cols,\n    const bool &isSourceTypeNumpy = false, const bool &isDestRowMajor = true,\n    const bool& isSourceRowMajor = true,\n    const npy_int &numpy_row_stride = 1, const npy_int &numpy_col_stride = 1)\n{\n  // determine source strides\n  int row_stride = 1, col_stride = 1;\n  if (isSourceTypeNumpy) {\n    row_stride = numpy_row_stride;\n    col_stride = numpy_col_stride;\n  } else {\n    if (isSourceRowMajor) {\n      row_stride = nb_cols;\n    } else {\n      col_stride = nb_rows;\n    }\n  }\n\n  if (isDestRowMajor) {\n    for (int r=0; r<nb_rows; r++) {\n      for (int c=0; c<nb_cols; c++) {\n        *dest = source[r*row_stride + c*col_stride];\n        dest++;\n      }\n    }\n  } else {\n    for (int c=0; c<nb_cols; c++) {\n      for (int r=0; r<nb_rows; r++) {\n        *dest = source[r*row_stride + c*col_stride];\n        dest++;\n      }\n    }\n  }\n}\n\ntemplate<class MatType> // MatrixXf or MatrixXd\nstruct EigenMatrixToPython {\n  static PyObject* convert(const MatType& mat) {\n    npy_intp shape[2] = { mat.rows(), mat.cols() };\n    PyArrayObject* python_array = (PyArrayObject*)PyArray_SimpleNew(\n        2, shape, NumpyEquivalentType<typename MatType::Scalar>::type_code);\n\n    copy_array(mat.data(),\n               (typename MatType::Scalar*)PyArray_DATA(python_array),\n               mat.rows(),\n               mat.cols(),\n               false,\n               true,\n               MatType::Flags & Eigen::RowMajorBit);\n    return (PyObject*)python_array;\n  }\n};\n\ntemplate<typename MatType>\nstruct EigenMatrixFromPython {\n  typedef typename MatType::Scalar T;\n\n  EigenMatrixFromPython() {\n    bp::converter::registry::push_back(&convertible,\n                                       &construct,\n                                       bp::type_id<MatType>());\n  }\n\n  static void* convertible(PyObject* obj_ptr) {\n    PyArrayObject *array = reinterpret_cast<PyArrayObject*>(obj_ptr);\n    if (!PyArray_Check(array)) {\n      //LOG(ERROR) << \"PyArray_Check failed\";\n      return 0;\n    }\n    if (PyArray_NDIM(array) > 2) {\n      //LOG(ERROR) << \"dim > 2\";\n      return 0;\n    }\n    if (PyArray_ObjectType(obj_ptr, 0) != NumpyEquivalentType<typename MatType::Scalar>::type_code) {\n      //LOG(ERROR) << \"types not compatible\";\n      return 0;\n    }\n    int flags = PyArray_FLAGS(array);\n    if (!(flags & NPY_ARRAY_C_CONTIGUOUS)) {\n      //LOG(ERROR) << \"Contiguous C array required\";\n      return 0;\n    }\n    if (!(flags & NPY_ARRAY_ALIGNED)) {\n      //LOG(ERROR) << \"Aligned array required\";\n      return 0;\n    }\n    return obj_ptr;\n  }\n\n  static void construct(PyObject* obj_ptr,\n                        bp::converter::rvalue_from_python_stage1_data* data) {\n    const int R = MatType::RowsAtCompileTime;\n    const int C = MatType::ColsAtCompileTime;\n\n    using bp::extract;\n\n    PyArrayObject *array = reinterpret_cast<PyArrayObject*>(obj_ptr);\n    int ndims = PyArray_NDIM(array);\n    npy_intp* dimensions = PyArray_DIMS(array);\n\n    int dtype_size = (PyArray_DESCR(array))->elsize;\n    int s1 = PyArray_STRIDE(array, 0);\n    //CHECK_EQ(0, s1 % dtype_size);\n    int s2 = 0;\n    if (ndims > 1) {\n      s2 = PyArray_STRIDE(array, 1);\n      //CHECK_EQ(0, s2 % dtype_size);\n    }\n\n    int nrows = R;\n    int ncols = C;\n    if (ndims == 2) {\n      if (R != Eigen::Dynamic) {\n        //CHECK_EQ(R, array->dimensions[0]);\n      } else {\n        nrows = dimensions[0];\n      }\n\n      if (C != Eigen::Dynamic) {\n        //CHECK_EQ(C, array->dimensions[1]);\n      } else {\n        ncols = dimensions[1];\n      }\n    } else {\n      //CHECK_EQ(1, ndims);\n      // Vector are a somehow special case because for Eigen, everything is\n      // a 2D array with a dimension set to 1, but to numpy, vectors are 1D\n      // arrays\n      // So we could get a 1x4 array for a Vector4\n\n      // For a vector, at least one of R, C must be 1\n      //CHECK(R == 1 || C == 1);\n\n      if (R == 1) {\n        if (C != Eigen::Dynamic) {\n          //CHECK_EQ(C, array->dimensions[0]);\n        } else {\n          ncols = dimensions[0];\n        }\n        // We have received a 1xC array and want to transform to VectorCd,\n        // so we need to transpose\n        // TODO: An alternative is to add wrappers for RowVector, but maybe\n        // implicit transposition is more natural\n        std::swap(s1, s2);\n      } else {\n        if (R != Eigen::Dynamic) {\n          //CHECK_EQ(R, array->dimensions[0]);\n        } else {\n          nrows = dimensions[0];\n        }\n      }\n    }\n\n    T* raw_data = reinterpret_cast<T*>(PyArray_DATA(array));\n\n    typedef Map<Matrix<T, Dynamic, Dynamic, RowMajor>, Aligned, Stride<Dynamic, Dynamic> > MapType;\n\n    void* storage=((bp::converter::rvalue_from_python_storage<MatType>*)\n                   (data))->storage.bytes;\n\n    new (storage) MatType;\n    MatType* emat = (MatType*)storage;\n    // TODO: This is a (potentially) expensive copy operation. There should\n    // be a better way\n    *emat = MapType(raw_data, nrows, ncols,\n                Stride<Dynamic, Dynamic>(s1/dtype_size, s2/dtype_size));\n    data->convertible = storage;\n  }\n};\n\ntemplate<class TransformType> // MatrixXf or MatrixXd\nstruct EigenTransformToPython {\n  static PyObject* convert(const TransformType& transform) {\n      return EigenMatrixToPython<typename TransformType::MatrixType>::convert(transform.matrix());\n  }\n};\n\ntemplate<typename TransformType>\nstruct EigenTransformFromPython {\n  EigenTransformFromPython() {\n    bp::converter::registry::push_back(&convertible,\n                                       &construct,\n                                       bp::type_id<TransformType>());\n  }\n\n  static void* convertible(PyObject* obj_ptr) {\n    return EigenMatrixFromPython<typename TransformType::MatrixType>::convertible(obj_ptr);\n  }\n\n  static void construct(PyObject* obj_ptr,\n                        bp::converter::rvalue_from_python_stage1_data* data) {\n    return EigenMatrixFromPython<typename TransformType::MatrixType>::construct(obj_ptr, data);\n  }\n};\n\n#if EIGEN_VERSION_AT_LEAST(3, 3, 0)\n\n//Assumes row-major destination\ntemplate<typename SourceType, typename DestType>\nstatic void copy_tensor(\n    const SourceType* source, DestType* dest,\n    const int& num_dimensions,\n    const npy_intp* shape,\n    const int& size,\n    const bool& is_source_row_major = false) {\n  if (is_source_row_major) {\n    for(int i_element = 0; i_element < size; i_element++,dest++){\n      *dest = source[i_element];\n    }\n    return;\n  }\n\n  int col_stride = shape[0];\n  std::vector<int> strides;\n  std::vector<int> remaining_dims;\n  int cumulative_stride = shape[0] * shape[1];\n  int chunk_size = 1;\n\n  for (int ix_dimension = 2; ix_dimension < num_dimensions; ix_dimension++) {\n    int dim = shape[ix_dimension];\n    strides.push_back(cumulative_stride);\n    remaining_dims.push_back(dim);\n    cumulative_stride *= dim;\n    chunk_size *= dim;\n  }\n\n  std::reverse(remaining_dims.begin(), remaining_dims.end());\n  std::reverse(strides.begin(), strides.end());\n\n  for (int r = 0; r < shape[0]; r++) {\n    for (int c = 0; c < shape[1]; c++) {\n      int row_and_col_offset = r + c * col_stride;\n      for (int ix_element = 0; ix_element < chunk_size; ix_element++) {\n        int ix_subelement = ix_element;\n        int remaining_offset = 0;\n        for (size_t ix_dim = 0; ix_dim < remaining_dims.size(); ix_dim++) {\n          div_t division_result = div(ix_subelement, remaining_dims[ix_dim]);\n          ix_subelement = division_result.quot;\n          int coord = division_result.rem;\n          remaining_offset += coord * strides[ix_dim];\n        }\n        *dest = source[row_and_col_offset + remaining_offset];\n        dest++;\n      }\n    }\n  }\n}\n\ntemplate<class TensorType>\nstruct EigenTensorToPython {\n  static PyObject* convert(const TensorType& tensor) {\n\n    const int num_dimensions = TensorType::NumDimensions;\n    npy_intp* shape = static_cast<npy_intp*>(malloc(sizeof(npy_intp) * num_dimensions));\n    //npy_int shape2[num_dimensions]; //will error, check\n    for (int i_dimension = 0; i_dimension < num_dimensions; i_dimension++) {\n      shape[i_dimension] = static_cast<npy_intp>(tensor.dimension(i_dimension));\n    }\n\n    PyArrayObject* python_array = (PyArrayObject*) PyArray_SimpleNew(\n        num_dimensions, shape, NumpyEquivalentType<typename TensorType::Scalar>::type_code);\n\n    copy_tensor(tensor.data(),\n        (typename TensorType::Scalar*) PyArray_DATA(python_array),\n        num_dimensions,\n        shape,\n        tensor.size(),\n        static_cast<Eigen::StorageOptions>(TensorType::Layout) == Eigen::RowMajor);\n    free(shape);\n    return (PyObject*) python_array;\n\n  }\n};\n\ntemplate<typename TensorType>\nstruct EigenTensorFromPython {\n  typedef typename TensorType::Scalar T;\n  EigenTensorFromPython() {\n    bp::converter::registry::push_back(&convertible,\n        &construct,\n        bp::type_id<TensorType>());\n  }\n\n  static void* convertible(PyObject* obj_ptr) {\n    PyArrayObject* array = reinterpret_cast<PyArrayObject*>(obj_ptr);\n    if (!PyArray_Check(array)) {\n      //LOG(ERROR) << \"PyArray_Check failed\";\n      return 0;\n    }\n\n    int dimension_count = PyArray_NDIM(array);\n    if (dimension_count <= 2) {\n      //This should be a Matrix or Vector, not Eigen::Tensor (default behavior)\n      //LOG(ERROR) << \"PyArray_Check failed\";\n      return 0;\n    } else if (dimension_count != TensorType::NumDimensions) {\n      //LOG(ERROR) << \"PyArray_Check failed\";\n      return 0;\n    }\n    if (PyArray_ObjectType(obj_ptr, 0) != NumpyEquivalentType<T>::type_code) {\n      //LOG(ERROR) << \"types not compatible\";\n      return 0;\n    }\n    int flags = PyArray_FLAGS(array);\n    if (!(flags & NPY_ARRAY_C_CONTIGUOUS)) {\n      //LOG(ERROR) << \"Contiguous C array required\";\n      return 0;\n    }\n    if (!(flags & NPY_ARRAY_ALIGNED)) {\n      //LOG(ERROR) << \"Aligned array required\";\n      return 0;\n    }\n    return obj_ptr;\n  }\n\n  static void construct(PyObject* obj_ptr,\n      bp::converter::rvalue_from_python_stage1_data* data) {\n\n    using bp::extract;\n\n    PyArrayObject* array = reinterpret_cast<PyArrayObject*>(obj_ptr);\n    npy_intp* numpy_array_dimensions = PyArray_DIMS(array);\n\n    T* raw_data = reinterpret_cast<T*>(PyArray_DATA(array));\n\n    typedef TensorMap<Tensor<T, TensorType::NumDimensions, RowMajor>, Aligned> TensorMapType;\n    typedef TensorLayoutSwapOp<Tensor<T, TensorType::NumDimensions, RowMajor>> TensorSwapLayoutType;\n\n    void* storage = ((bp::converter::rvalue_from_python_storage<TensorType>*)\n        (data))->storage.bytes;\n\n    std::array<Index, TensorType::NumDimensions> tensor_dimensions;\n    std::array<int, TensorType::NumDimensions> inverse_dimensions;\n    for (size_t i_dim = 0, inv_dim = TensorType::NumDimensions - 1; i_dim < tensor_dimensions.size();\n        i_dim++, inv_dim--) {\n      tensor_dimensions[i_dim] = static_cast<Index>(numpy_array_dimensions[i_dim]);\n      inverse_dimensions[i_dim] = inv_dim;\n    }\n\n    new (storage) TensorType;\n    TensorType* etensor = (TensorType*) storage;\n\n    // TODO: This is a (potentially) expensive copy operation. There should be a better way\n    auto mapped_t = TensorMapType(raw_data, tensor_dimensions);\n    *etensor = TensorSwapLayoutType(mapped_t).shuffle(inverse_dimensions);\n    data->convertible = storage;\n  }\n};\n\n#endif // EIGEN_VERSION_AT_LEAST(3, 3, 0)\n\n#define EIGEN_MATRIX_CONVERTER(Type) \\\n  EigenMatrixFromPython<Type>();  \\\n  bp::to_python_converter<Type, EigenMatrixToPython<Type> >();\n\n#define EIGEN_TRANSFORM_CONVERTER(Type) \\\n  EigenTransformFromPython<Type>();  \\\n  bp::to_python_converter<Type, EigenTransformToPython<Type> >();\n\n#define MAT_CONV(R, C, T) \\\n  typedef Matrix<T, R, C> Matrix ## R ## C ## T; \\\n  EIGEN_MATRIX_CONVERTER(Matrix ## R ## C ## T);\n\n// This require a MAT_CONV for that Matrix type to be registered first\n#define MAP_CONV(R, C, T) \\\n  typedef Map<Matrix ## R ## C ## T> Map ## R ## C ## T; \\\n  EIGEN_MATRIX_CONVERTER(Map ## R ## C ## T);\n\n#define T_CONV(R, C, T) \\\n  typedef Transpose<Matrix ## R ## C ## T> Transpose ## R ## C ## T; \\\n  EIGEN_MATRIX_CONVERTER(Transpose ## R ## C ## T);\n\n#define BLOCK_CONV(R, C, BR, BC, T) \\\n  typedef Block<Matrix ## R ## C ## T, BR, BC> Block ## R ## C ## BR ## BC ## T; \\\n  EIGEN_MATRIX_CONVERTER(Block ## R ## C ## BR ## BC ## T);\n\n#if EIGEN_VERSION_AT_LEAST(3, 3, 0)\n\n//For two-way Eigen <--> numpy Tensor converters\n#define EIGEN_TENSOR_CONVERTER(Type) \\\n  EigenTensorFromPython<Type>(); \\\n  bp::to_python_converter<Type, EigenTensorToPython<Type> >();\n\n//For one-way Eigen --> numpy converters (for row-major Eigen stuff)\n#define TENSOR_ROW_MAJOR_CONV(T, D)\\\n  typedef Tensor<T, D, RowMajor> TensorRm ## T ## D; \\\n  bp::to_python_converter<TensorRm ## T ## D, EigenTensorToPython<TensorRm ## T ## D> >();\n\n#define TENSOR_CONV(T, D) \\\n  typedef Tensor<T, D> Tensor ## T ## D; \\\n  EIGEN_TENSOR_CONVERTER(Tensor ## T ## D);\n\n#endif // EIGEN_VERSION_AT_LEAST(3, 3, 0)\n\nstatic const int X = Eigen::Dynamic;\n\n#if PY_VERSION_HEX >= 0x03000000\nvoid*\n#else\nvoid\n#endif\nSetupEigenConverters() {\n  static bool is_setup = false;\n  if (is_setup) return NUMPY_IMPORT_ARRAY_RETVAL;\n  is_setup = true;\n\n  import_array();\n\n  EIGEN_MATRIX_CONVERTER(Matrix2f);\n  EIGEN_MATRIX_CONVERTER(Matrix2d);\n  EIGEN_MATRIX_CONVERTER(Matrix3f);\n  EIGEN_MATRIX_CONVERTER(Matrix3d);\n  EIGEN_MATRIX_CONVERTER(Matrix4f);\n  EIGEN_MATRIX_CONVERTER(Matrix4d);\n\n  EIGEN_MATRIX_CONVERTER(Vector2f);\n  EIGEN_MATRIX_CONVERTER(Vector3f);\n  EIGEN_MATRIX_CONVERTER(Vector4f);\n  EIGEN_MATRIX_CONVERTER(Vector2d);\n  EIGEN_MATRIX_CONVERTER(Vector3d);\n  EIGEN_MATRIX_CONVERTER(Vector4d);\n\n  EIGEN_TRANSFORM_CONVERTER(Affine2f);\n  EIGEN_TRANSFORM_CONVERTER(Affine3f);\n  EIGEN_TRANSFORM_CONVERTER(Affine2d);\n  EIGEN_TRANSFORM_CONVERTER(Affine3d);\n\n  EIGEN_TRANSFORM_CONVERTER(Isometry2f);\n  EIGEN_TRANSFORM_CONVERTER(Isometry3f);\n  EIGEN_TRANSFORM_CONVERTER(Isometry2d);\n  EIGEN_TRANSFORM_CONVERTER(Isometry3d);\n\n  EIGEN_TRANSFORM_CONVERTER(Projective2f);\n  EIGEN_TRANSFORM_CONVERTER(Projective3f);\n  EIGEN_TRANSFORM_CONVERTER(Projective2d);\n  EIGEN_TRANSFORM_CONVERTER(Projective3d);\n\n  MAT_CONV(2, 3, double);\n  MAT_CONV(X, 3, double);\n  MAT_CONV(X, X, double);\n  MAT_CONV(X, 1, double);\n  MAT_CONV(1, 4, double);\n  MAT_CONV(1, X, double);\n  MAT_CONV(3, 4, double);\n  MAT_CONV(2, X, double);\n\n#if EIGEN_VERSION_AT_LEAST(3, 3, 0)\n\n  TENSOR_ROW_MAJOR_CONV(float, 3);\n  TENSOR_ROW_MAJOR_CONV(float, 4);\n  TENSOR_ROW_MAJOR_CONV(double, 3);\n  TENSOR_ROW_MAJOR_CONV(double, 4);\n\n  TENSOR_CONV(int, 3);\n  TENSOR_CONV(int, 4);\n  TENSOR_CONV(float, 3);\n  TENSOR_CONV(float, 4);\n  TENSOR_CONV(double, 3);\n  TENSOR_CONV(double, 4);\n\n#endif // EIGEN_VERSION_AT_LEAST(3, 3, 0)\n\n#if PY_VERSION_HEX >= 0x03000000\n  return 0;\n#endif\n}\n", "meta": {"hexsha": "21fc8bd72e4c6e047ca2e0afb3ff5450b123e432", "size": 15973, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/eigen_numpy.cc", "max_stars_repo_name": "ColinTogashi/boost_numpy_eigen", "max_stars_repo_head_hexsha": "210fa9216bb3c4010e16839ab673e343cb363d17", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 9.0, "max_stars_repo_stars_event_min_datetime": "2018-08-16T18:27:45.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-19T20:47:39.000Z", "max_issues_repo_path": "src/eigen_numpy.cc", "max_issues_repo_name": "Algomorph/boost_numpy_eigen", "max_issues_repo_head_hexsha": "f46dc261272aed8dc8672c4937b33381b5fa451c", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2018-08-16T18:42:03.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-17T16:46:58.000Z", "max_forks_repo_path": "src/eigen_numpy.cc", "max_forks_repo_name": "Algomorph/boost_numpy_eigen", "max_forks_repo_head_hexsha": "f46dc261272aed8dc8672c4937b33381b5fa451c", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2019-02-06T21:41:59.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-21T21:44:02.000Z", "avg_line_length": 31.8822355289, "max_line_length": 101, "alphanum_fraction": 0.6628059851, "num_tokens": 4304, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5698526514141572, "lm_q2_score": 0.5389832206876841, "lm_q1q2_score": 0.30714101737661864}}
{"text": "/*\n * F.cc\n *\n *  Created on: Apr 13, 2014\n *      Author: wilfeli\n */\n#include <list>\n\n#include <boost/random.hpp>\n#include <boost/random/normal_distribution.hpp>\n#include <boost/random/uniform_int_distribution.hpp>\n#include <math.h>\n#include <string>\n\n#include \"Tools.h\"\n#include \"F.h\"\n#include \"W.h\"\n#include \"Contract.h\"\n#include \"Market.h\"\n#include \"H.h\"\n\n\n//using std::shared_ptr;\n//using std::unique_ptr;\nusing Eigen::MatrixXd;\nusing namespace boost;\n//using Tools::mgrid;\n\n//will pass w as itself, it will be converted to reference\nF::F(W &w_, int id_):w(w_),\n\t\t\t\t\tl_bid(0.0, 0.0),\n\t\t\t\t\tc_ask(0.0, 0.0),\n\t\t\t\t\tid(id_),\n\t\t\t\t\ts0(1,19),\n\t\t\t\t\ttheta_x(1,4){\n\tw.AddF(this);\n\n\t//create storage for goods\n\tass_asGC.push_back(new GoodC(this, 0.0));\n\n\ttype = \"FGC\";\n\n\tl_bid.issuer = this;\n\tc_ask.issuer = this;\n\n\t//create wm\n\tExpectationBackward* exp = new ExpectationBackward(1.0, 10, 0.5);\n\twm[\"MasCHK\"] = exp;\n\n\t//create wm\n\texp = new ExpectationBackward(1.0, 10, 0.5);\n\twm[\"MasGC\"] = exp;\n\n\n\t//parameters\n\tparam = new Parameters();\n\tparam->init();\n\n\n\t//accounting\n\taccount = new AccountF();\n                        \n    \n\n};\n\nvoid\nF::init(){\n    //ADP setup\n    theta_V = Eigen::MatrixXd::Constant(1, 1, param->ADP_BF_N);\n    B_n_1_RLS = Eigen::MatrixXd::Zero(param->ADP_BF_N, param->ADP_BF_N);\n    \n    //QL setup\n    _set_QL();\n    \n    \n    //mRe setup\n    _set_mRE();\n\n};\n\ndouble\nF::get_status(){\n\treturn status;\n};\n\nvoid\nF::ac_W_begin_step(){\n\t//begin step - pay off obligations\n\t//check that has enough money to pay all\n\tdouble q_all = 0.0;\n\tdouble pq = 0.0;\n\tMessagePSSendPayment* inf;\n\tbool PAY_DIV = false;\n\n\tfor (auto c:ass_asCHK){\n\t\tif(c->t_end == w.t - 1){\n\t\t\tq_all += c->q * c->p;\n\t\t};\n\t};\n\n\tbool PAY_ALL = false;\n\n\tif (q_all <= ass_asCBDt0.front()->q){\n\t\tPAY_ALL = true;\n\t};\n\n\tfor (auto c:ass_asCHK){\n\n\t\tif(c->t_end == w.t - 1){\n\n\t\t\tpq = PAY_ALL?c->q * c->p:(c->q * c->p) * ass_asCBDt0.front()->q /q_all;\n\n\n\t\t\t//make payment\n\t\t\tinf = new MessagePSSendPayment(c->issuer, pq ,\"asCHK_b\");\n\t\t\tinf->sender = this;\n\n\t\t\tass_asCBDt0.front()->issuer->_PS_accept_PO(inf);\n\n\t\t\tdelete inf;\n\n\t\t};\n\t};\n\n\n\tif (w.t > 0.0){\n\n\t\t//check last period profit\n\t\tq_all = (account->profit.back() > 0.0)? account->profit.back() * param->DIV_SHARE: 0.0;\n\n\t\tif (q_all > 0.0) {\n\t\t\tPAY_DIV = true;\n\t\t\tif (q_all <= ass_asCBDt0.front()->q){\n\t\t\t\tPAY_ALL = PAY_ALL && true;\n\t\t\t} else{\n\t\t\t\tPAY_ALL = false;\n\t\t\t};\n\t\t};\n\n\t\t//pay off dividends\n\t\tif (PAY_ALL  && PAY_DIV){\n\t\t\tpq = q_all/w.NH;\n\t\t\tfor (auto a:w.Hs){\n\t\t\t\t//make payment\n\t\t\t\tinf = new MessagePSSendPayment(pq ,static_cast<std::string>(\"FI_div\"));\n\t\t\t\tinf->getter = a; //dynamic_cast<IPSAgent*>(a);\n\t\t\t\tinf->sender = this;\n\n\t\t\t\tass_asCBDt0.front()->issuer->_PS_accept_PO(inf);\n\n\t\t\t\tdelete inf;\n\t\t\t};\n\n\t\t};\n\t};\n\n\n\n\t//checks for bankruptcy\n\tif ((ass_asCBDt0.front()->q < 0.0) || !PAY_ALL){\n\t\t//calls bankruptcy\n\t\tMessageBankruptcy* mes = new MessageBankruptcy(this);\n\t\tw.ac_LS_bankruptcy(mes);\n\n\t\tdelete mes;\n\n\t};\n\n\n\t//clear contracts\n\tass_asCHK.erase(std::remove_if(ass_asCHK.begin(), ass_asCHK.end(),\n\t                       [&](ContractHK* x) -> bool { return (x->t_end <= w.t); }),\n\t\t\tass_asCHK.end());\n\n//\tfor (auto c:ass_asCHK){\n//\t\tstd::cout << true << std::endl;\n//\t};\n\n\taccount->ac_W_initialize_step();\n\n};\n\nvoid\nF::ac_W_begin_step(MessageStatus* mes){\n\tif (mes->status <= 0.0){\n\t\taccount->ac_W_initialize_step(mes);\n\t};\n};\n\n\nvoid\nF::ac_W_end_step(){\n\t// calls accounting to calculate profit\n\t_s0();\n\taccount->ac_W_end_step(&s0);\n\n};\n\n\ndouble\nF::_mas_q_sell(MessageMarketCCheckAsk* inf){\n\t//checks how much to sell\n\t//return q from ask\n\n\tdouble q_sell = 0.0;\n\n\tif (inf->p_eq >= c_ask.p){\n\t\tq_sell = c_ask.q;\n\t};\n\n\treturn q_sell;\n};\n\ndouble\nF::_mas_q_buy(MessageMarketLCheckBid* inf){\n\t//checks how much to sell\n\t//return q from ask\n\n\tdouble q_buy = 0.0;\n\n\tif (inf->p_eq <= l_bid.p){\n\t\tq_buy = l_bid.q;\n\t};\n\n\treturn q_buy;\n};\n\n\nvoid\nF::_buy_asCHK(ContractHK* c){\n\t//add to contract\n\tass_asCHK.push_back(c);\n\n\n\t//update ask\n\tl_bid.q -= c->q;\n\n\t//message for accounting\n\tMessage* mes = new Message(\"buy_asCHK\");\n\n\t//call accounting\n\taccount->ac_get_inf(mes, c);\n\n\n\tdelete mes;\n\n};\n\nvoid\nF::wm_update_k_s(){\n\n\tif (w.t > 0.0){\n\n\t\tMatrixXd w0 = wm_w0_tbeg();\n\t\tExpectationBackward* exp_i;\n\t\tstd::vector<double> s_t_i;\n\n\t\t//update k_s if conditions are met\n//\t\tif ((w0(0,1) > 0.0) || ((w0(0,1) == 0.0) && (w0(0,0) != 0.0)) || ((w0(0,4) > 0.0) && (w0(0,0) == 0.0))){\n\t\t\ts_t_i.push_back(w0(0,0));\n\t\t\ts_t_i.push_back(w0(0,1));\n\n\t\t\texp_i = wm[\"MasCHK\"];\n\n\t\t\texp_i->s_t.push_back(s_t_i);\n\n\t\t\twm_update_expectation_backward(exp_i, 1);\n//\t\t};\n\n\t\ts_t_i.clear();\n\n\t\ts_t_i.push_back(w0(0,2));\n\t\ts_t_i.push_back((w0(0,2) > 0.0)? w0(0,3)/w0(0,2):w0(0,5));\n\n\n\t\texp_i = wm[\"MasGC\"];\n\n\t\texp_i->s_t.push_back(s_t_i);\n\n\t\twm_update_expectation_backward(exp_i, 1);\n\n\t\ts_t_i.clear();\n        \n        \n        if (param->opt_TYPE == \"QL\"){\n            wm_update_Q();\n            \n        };\n        \n        if (param->opt_TYPE == \"mRE\"){\n            wm_update_mRE();\n            \n        };\n        \n\t};\n\n};\n\n\nEigen::MatrixXd\nF::wm_w0_tbeg(){\n\tMatrixXd w0(1,8);\n\n\tlong life_length = account->asCHK_q.size();\n\n\tw0(0,0) = account->asCHK_q.at(life_length - 2);\n\tw0(0,1) = w.ml->market_price.at(w.t - 1)->p;\n\tw0(0,2) = account->sales_q.at(life_length - 2);\n\tw0(0,3) = account->sales_pq.at(life_length - 2);\n\n\tw0(0,4) = l_bid.q_t_0;\n\tw0(0,5) = w.mc->market_price.at(w.t - 1)->p;\n\tw0(0,6) = c_ask.q_t_0;\n\tw0(0,7) = account->profit.at(life_length - 2);\n\n//\tstd::cout << w0 << std::endl;\n\n\treturn w0;\n};\n\nvoid\nF::wm_update_expectation_backward(ExpectationBackward* exp_i, int p_position){\n\n\n\tstd::vector<double> p;\n\n\tint i_s_t_1_max = 0;\n\tlong i_s_t_max = 0;\n\n\t//depending on the length of the wm and accumulated number of prices\n\tif (std::isinf(param->WM_LENGTH)){\n\t\ti_s_t_1_max = exp_i->s_t_1[\"n\"];\n\t\ti_s_t_max = exp_i->s_t.size();\n\t}else{\n\t\ti_s_t_1_max = std::min(std::max(param->WM_LENGTH - exp_i->s_t.size(), 0.0), exp_i->s_t_1[\"n\"]);\n\t\ti_s_t_max = std::min(param->WM_LENGTH, static_cast<double>(exp_i->s_t.size()));\n\t};\n\n\tfor (int i = 0; i < i_s_t_1_max; i++){\n\t\tp.push_back(exp_i->s_t_1[\"mu\"]);\n\t};\n\n\t//push other prices\n\tfor (std::size_t i = (exp_i->s_t.size() - i_s_t_max);i < exp_i->s_t.size();i++){\n\t\tp.push_back(exp_i->s_t[i][p_position]);\n\t};\n\n//\tTools::print_vector(p);\n\n\tEigen::MatrixXd mean_variance = wm_mean_variance(p);\n\n\texp_i->mu = mean_variance(0,0);\n\texp_i->n += 1.0;\n\texp_i->v = mean_variance(1,0);\n    \n    if (exp_i->v <= 0.0){\n        exp_i->v = exp_i->mu * 0.01;\n    };\n\n\n};\n\n\n\nEigen::MatrixXd\nF::wm_mean_variance(std::vector<double> &x){\n\tMatrixXd mean_variance(2,1);\n\n\t//gets mean and variance\n\tdouble sum = std::accumulate(x.begin(), x.end(), 0.0);\n\tdouble mean = sum / x.size();\n\tstd::vector<double> diff(x.size());\n\tstd::transform(x.begin(), x.end(), diff.begin(),\n\t               std::bind2nd(std::minus<double>(), mean));\n\tdouble sq_sum = std::inner_product(diff.begin(), diff.end(), diff.begin(), 0.0);\n//\tdouble stdev = std::sqrt(sq_sum / x.size());\n\tdouble variance = sq_sum/x.size();\n\n\tmean_variance(0,0) = mean;\n\tmean_variance(1,0) = variance;\n\n\treturn mean_variance;\n};\n\n\nEigen::MatrixXd\nF::_s0(){\n\t//money holdings\n\ts0(0,0) = ass_asCBDt0.front()->q;\n\n\ts0(0,1) = 0.0;\n\t//human capital for production\n\tfor (auto c:ass_asCHK){\n\t\ts0(0,1) += c->q;\n\t};\n\n\t//amount of good c\n\ts0(0,2) = ass_asGC.front()->q;\n\n\t//expected price on labor market\n\ts0(0,3) = wm[\"MasCHK\"]->mu;\n\n\t//number of observations\n\ts0(0,4) = wm[\"MasCHK\"]->n;\n\n\t//expected price on goods market\n\ts0(0,5) = wm[\"MasGC\"]->mu;\n\n\t//number of observations\n\ts0(0,6) = wm[\"MasGC\"]->n;\n\n\t//p*q - total costs\n\ts0(0,7) = account->cost_p * account->cost_q;\n\n\t//cost - q\n\ts0(0,8) = account->cost_q;\n\n\t//current period labor contracts\n\ts0(0,9) = 0.0;\n\n\t//current period labor price\n\ts0(0,10) = 0.0;\n\n\t//current period sales q\n\ts0(0,11) = 0.0;\n\n\t//current period sales p\n\ts0(0,12) = 0.0;\n\n\t//current period production\n\ts0(0,13) = 0.0;\n\n\t//current profit\n\ts0(0,14) = 0.0;\n\n\t//state dead/alive\n\ts0(0,15) = status;\n\n\t//share of dividends\n\ts0(0,16) = param->DIV_SHARE;\n\n\t//variance of labor market\n\ts0(0,17) = wm[\"MasCHK\"]->v;\n\n\t//variance of goods market\n\ts0(0,18) = wm[\"MasGC\"]->v;\n\n\n\treturn s0;\n};\n\n\nBid*\nF::ac_L(){\n\t//update numbers in bid\n\tl_bid.demand_curve = Eigen::MatrixXd::Zero(1,2);\n\tl_bid.demand_curve << l_bid.p , l_bid.q;\n\n\tl_bid.p_t_0 = l_bid.p;\n\tl_bid.q_t_0 = l_bid.q;\n\n\n\n\t//return reference to the bid\n\treturn &l_bid;\n};\n\nAsk*\nF::ac_C(){\n\t//update numbers in ask\n\tc_ask.q = _s0()(0,2) * c_ask.q_share;\n\n\tc_ask.p_t_0 = c_ask.p;\n\tc_ask.q_t_0 = c_ask.q;\n\tc_ask.q_share_t_0 = c_ask.q_share;\n\n\t//update numbers in ask\n\tc_ask.supply_curve = Eigen::MatrixXd::Zero(1,2);\n\tc_ask.supply_curve << c_ask.p , c_ask.q;\n\n\n//\tstd::cout << ass_asCHK.size() << \"\\n\";\n//\n//\tstd::cout << c_ask.supply_curve << \"\\n\";\n\n\t//return reference to the bid\n\treturn &c_ask;\n};\n\n\nbool\nF::_sell_asGC(MessageMarketCSellGoodC* mes){\n\t//decrease offer\n\tc_ask.q -= mes->q;\n\n\t//sell actual good\n\tass_asGC.back()->q -= mes->q;\n\n\n\tMessageGoodC* mgc = new MessageGoodC(mes->q, mes->p);\n\n\n\t//send goods to the buyer\n\tmes->buyer->_buy_asGC(mgc);\n    \n    //delete message\n    delete mgc;\n\n\n\t//account sale\n\taccount->ac_get_inf(mes);\n\n\treturn true;\n\n\n};\n\n\n\nvoid\nF::ac_W(MessageMakeDec* mes){\n\n    _s0();\n\t//calls opt choice\n    if (param->opt_TYPE == \"EO_CS\"){\n        opt_CS(&s0,&theta_x, param->opt_CS_N);\n    };\n    \n    if (param->opt_TYPE == \"EO_ADP\"){\n        theta_V = _API_LM(&s0, param->ADP_API_LM_N, param->ADP_API_LM_M);\n        Eigen::Block<Eigen::MatrixXd> s = s0.block(0,0,s0.rows(),s0.cols());\n        _opt_CS_s_V(s,theta_x, theta_V, param->opt_CS_N);\n    };\n    \n    if (param->opt_TYPE == \"QL\"){\n        opt_QL();\n    };\n    \n    if (param->opt_TYPE == \"mRE\"){\n        opt_mRE();\n        \n    };\n    \n\n\t//transforms it into ask and bid\n\tl_bid.q = floor(theta_x(0,0));\n\tl_bid.p = theta_x(0,1) * s0(0,3);\n\n\tc_ask.q_share = theta_x(0,2);\n\tc_ask.p = theta_x(0,3) * s0(0,5);\n\n\n\n};\n\n\nvoid\nF::ac_W(MessageF_F* mes){\n\t//calls production function\n\t_s0();\n\tmes->q = _F_F(&s0);\n\tass_asGC.back()->q += mes->q;\n\taccount->ac_get_inf(mes);\n\n};\n\ndouble\nF::_F_F(Eigen::MatrixXd* s){\n\tdouble l;\n\n\tl = (*s)(0,1);\n\n\treturn param->F_F_theta(0,0) * pow(l, param->F_F_theta(0,1));\n};\n\n\n\nvoid\nF::opt_CS(MatrixXd* s0,  MatrixXd* theta_x, int N){\n\n//\tN = 1;\n\n\t//gets matrix of thetas\n\t//prepare initial matrix\n\tMatrixXd m_s0 = MatrixXd::Zero(N, s0->cols());\n\n\tm_s0.rowwise() += s0->row(0);\n\n\n\t//allocate space to the matrix\n\tMatrixXd n_w;\n\tMatrixXd n_x;\n\tMatrixXd n_s = MatrixXd::Zero(N, s0->cols());\n\tMatrixXd n_c;\n\n\n\t//create matrix for the grid - small size here\n\tMatrixXd grid(4,3);\n\n    create_decision_grid(grid,0);\n\n    if (w.param->SIMULATION_MODE == \"test\"){\n        Tools::mgrid_test(grid, &theta_x_all);\n\n    } else{\n\n        Tools::mgrid(grid, &theta_x_all);\n    };\n\n\t//create random number generators for the implementation\n\n\tboost::normal_distribution<> nd_w1((*s0)(0,3), pow((*s0)(0,17),0.5));\n\tboost::normal_distribution<> nd_w2((*s0)(0,5), pow((*s0)(0,18),0.5));\n\n\tboost::variate_generator<boost::mt19937&,\n\t                           boost::normal_distribution<>> rng_w1(w.rng, nd_w1);\n\n\tboost::variate_generator<boost::mt19937&,\n\t                           boost::normal_distribution<>> rng_w2(w.rng, nd_w2);\n\n\n    if (w.param->SIMULATION_MODE != \"test\"){\n\n        //draw random variables\n        n_w = MatrixXd::Zero(N, 2 * param->T_MAX);\n        for (int i = 0; i < N; i++){\n            for(int j=0; j< n_w.cols(); j++){\n                if (j%2 == 0){\n                    n_w(i,j) = rng_w1();\n                } else {\n                    n_w(i,j) = rng_w2();\n                };\n                n_w(i,j) = std::max(0.0, (double)n_w(i,j));\n            };\n        };\n    };\n    \n\n\t//matrix of all\n\tMatrixXd c_all(theta_x_all.cols(),1);\n\n\tfor (int i = 0 ; i < theta_x_all.cols(); i++){\n        //redraw random in comparative with Python mode\n        if (w.param->SIMULATION_MODE == \"test\"){\n            n_w = MatrixXd::Zero(N, 2 * param->T_MAX);\n            for (int k = 0; k < N; k++){\n                for(int j=0; j< n_w.cols(); j++){\n                    if (j%2 == 0){\n                        n_w(k,j) = Tools::get_normal((*s0)(0,3), pow((*s0)(0,17),0.5), w.myrng);\n                    } else {\n                        n_w(k,j) = Tools::get_normal((*s0)(0,5), pow((*s0)(0,18),0.5), w.myrng);\n                    };\n                    n_w(k,j) = std::max(0.0, (double)n_w(k,j));\n                };\n            };\n        };\n        \n        \n\t\t//call estimator of results of steps, given theta_x\n\t\ttheta_x->row(0) = theta_x_all.col(i).transpose();\n\t\tn_x = MatrixXd::Zero(N, 4);\n\t\tn_s = m_s0;\n\t\tn_c = MatrixXd::Zero(N, param->T_MAX);\n\t\t_step_opt_CS(theta_x, &n_w, &n_x, &n_s, &n_c, param->T_MAX);\n\n//        std::cout << n_c << std::endl;\n//        std::cout << theta_x->row(0) << std::endl;\n        \n\t\t//after n_c\n\t\t//average over n runs\n\t\tc_all(i,0) = (n_c * param->BETA_T).mean();\n\n\t};\n\n//\tstd::cout << n_c << \"\\n\";\n\n//\tstd::cout << c_all.transpose() << \"\\n\";\n\n\t//find all max elements\n\tdouble max = c_all(0,0);\n\tstd::list<int> i_max;\n\tfor (int i=0; i<c_all.rows(); i++){\n\t\tif (c_all(i,0) == max){\n\t\t\ti_max.push_back(i);\n\t\t}else{\n\t\t\tif (c_all(i,0) > max){\n\t\t\t\tmax = c_all(i,0);\n\t\t\t\ti_max.clear();\n\t\t\t\ti_max.push_back(i);\n\t\t\t};\n\t\t}\n\t};\n\n\t//if more than 1 max - randomly pick\n\tlong theta_max_i;\n\tif (i_max.size()>1){\n\t\tboost::random::uniform_int_distribution<> i_max_dist(0, i_max.size()-1);\n\t\ttheta_max_i = i_max_dist(w.rng);\n\t}else{\n\t\ttheta_max_i = i_max.front();\n\t};\n\n\n\ttheta_x->row(0) = theta_x_all.col(theta_max_i).transpose();\n};\n\n\nvoid\nF::_step_opt_CS(MatrixXd *theta_x,\n\t\tMatrixXd *w,\n\t\tMatrixXd *x,\n\t\tMatrixXd *s,\n\t\tMatrixXd *c,\n                int T){\n\n\t//sets decisions for labor market\n\t//zero vector\n\tauto s_zero = MatrixXd::Zero(s->rows(),1);\n\n\n\n\tfor (int i=0; i< T; i++){\n\n\n\t\tx->col(0) = Eigen::MatrixXd::Constant(x->rows(), 1, (*theta_x)(0,0));\n\t\tx->col(1) = (*theta_x)(0,1) * s->col(3).array();\n        \n//        std::cout << *x << std::endl;\n\n\t\t//labor market results\n\t\t//if wage is less than realized wage - zero, otherwise hire all desired number\n\n\t\t(*s).col(9) = ((*w).col(i*2).array() <= x->col(1).array()).cast<double>().array() *x->col(0).array();\n\t\t(*s).col(10) = (*w).col(i*2);\n        \n        //cast to whole numbers\n        for (int j=0; j < s->rows(); j++){\n            (*s)(j,9) = floor((*s)(j,9));\n        };\n        \n//        std::cout << *s << std::endl;\n\n\n\n\t\t//current production\n\t\ts->col(13) = s->col(9).array().pow(param->F_F_theta(0,1))*param->F_F_theta(0,0);\n\t\ts->col(2) += s->col(13);\n\n//        std::cout << *s << std::endl;\n        \n\t\t//update for cost structure\n\t\ts->col(7) = s->col(7).array() + ((*s).col(9).array() * (*s).col(10).array());\n\t\ts->col(8) += s->col(13);\n\n//        std::cout << *s << std::endl;\n\n\t\t//sets decision for goods market\n\t\tx->col(2) = (*theta_x)(0,2) * s->col(2).array();\n\t\tx->col(3) = Eigen::MatrixXd::Constant(x->rows(), 1, (*theta_x)(0,3) * (*s)(0,5));\n\n//        std::cout << *x << std::endl;\n        \n\t\t//sales\n\t\t(*s).col(11) = ((*w).col(i*2 + 1).array() >= x->col(3).array()).cast<double>().array() *x->col(2).array();\n\t\t(*s).col(12) = (*w).col(i*2 + 1);\n\n//        std::cout << *s << std::endl;\n\n\t\t//money\n\t\ts->col(0) = s->col(0).array() + (s->col(11).array() * s->col(12).array());\n        \n//        std::cout << *s << std::endl;\n\n\t\t//inventory\n\t\ts->col(2) -= s->col(11);\n        \n//        std::cout << *s << std::endl;\n\n\t\tdouble atc = 0.0;\n\n\t\t//updates current profit\n\t\tfor (int j=0; j < s->rows(); j++){\n\n\t\t\tif ((*s)(j,8)>0.0){\n\t\t\t\tatc = (*s)(j,7) / (*s)(j,8);\n                \n                \n                if (param->ACCOUNTING_TYPE==\"modern\"){\n                    //update profit to cost of production\n                    (*s)(j,14) -= atc * (*s)(j,11);\n                };\n                if (param->ACCOUNTING_TYPE==\"classic\"){\n                    //update profit to cost of production\n                    (*s)(j,14) -= (*s)(j,9) * (*s)(j,10);\n                };\n               \n                \n\t\t\t\t//update cost of production\n\t\t\t\t(*s)(j,7) -= atc * (*s)(j,11);\n\t\t\t\t(*s)(j,8) -= (*s)(j,11);\n\t\t\t};\n\n\t\t\t//update profit to sales\n\t\t\t(*s)(j,14) += (*s)(j,11) * (*s)(j,12);\n\n\t\t\tatc = 0.0;\n\t\t};\n\n//        std::cout << *s << std::endl;\n\n\t\t//labor payment\n\t\ts->col(0) = s->col(0).array() -  (s->col(9).array() * s->col(10).array());\n        \n//        std::cout << *s << std::endl;\n\n\t\t//dividends\n\t\ts->col(0) = s->col(0).array() - (s->col(14).array() > s_zero.array()).cast<double>().array() * s->col(14).array() * s->col(16).array();\n\n//        std::cout << *s << std::endl;\n\n\t\t//zero out labor contract\n\t\ts->col(9) = s_zero;\n\t\ts->col(10) = s_zero;\n\n\n        //dead or alive\n\t\ts->col(15) = (s->col(0).array() >= s_zero.array()).cast<double>().array() * s->col(15).array();\n\n//        std::cout << *s << std::endl;\n        \n\t\t//stores realized goal\n\t\tc->col(i) = (s->col(15).array() > s_zero.array()).cast<double>().array() * s->col(14).array();\n\n//        std::cout << *c << std::endl;\n\n\t\t//zero out current profit\n\t\ts->col(14) = s_zero;\n\n\n\t};\n\n\n};\n\n\n\nvoid\nF::_bf(Eigen::MatrixXd* s, Eigen::MatrixXd* ret){\n    (*ret)(0,0) = (*s)(0,0);\n};\n\nvoid\nF::_bf(Eigen::Block<Eigen::MatrixXd>& s, Eigen::MatrixXd* ret){\n    (*ret)(0,0) = s(0,0);\n};\n\n\ndouble\nF::_V(Eigen::MatrixXd* s, Eigen::MatrixXd* phi_f, Eigen::MatrixXd& theta_V){\n    _bf(s, phi_f);\n\n    return (theta_V*(*phi_f).transpose()).sum();\n\n};\n\n\ndouble\nF::_V(Eigen::Block<Eigen::MatrixXd>& s, Eigen::MatrixXd* phi_f, Eigen::MatrixXd& theta_V){\n    _bf(s, phi_f);\n    \n    return (theta_V*(*phi_f).transpose()).sum();\n    \n};\n\n\nEigen::MatrixXd\nF::_API_LM(Eigen::MatrixXd* s0, int N, int M){\n//Approximate policy iteration using linear models.\n//\n//p.407 ADP\n//\n\n    //fix basis functions\n    long n_theta_t = param->ADP_BF_N;\n\n    //inner theta\n    //theta for now and future\n    Eigen::MatrixXd theta_V_n = Eigen::MatrixXd::Constant(1, n_theta_t, 1);\n\n    //policy theta\n    Eigen::MatrixXd theta_V_pi = theta_V;\n\n    \n    Eigen::MatrixXd s_n_m;\n    Eigen::MatrixXd v_n_m;\n    Eigen::MatrixXd x_n_m(1,4);\n    Eigen::MatrixXd phi(1, param->ADP_BF_N);\n    Eigen::MatrixXd phi1(1, param->ADP_BF_N);\n    \n    \n\n    for (int n=0; n<N; n++){\n        theta_V_n = theta_V_pi;\n        \n        s_n_m = MatrixXd::Zero(M+1, s0->cols());\n        s_n_m.row(0) += s0->row(0);\n        //v_n_m_T1 = 0\n        v_n_m = Eigen::MatrixXd::Constant(M, n_theta_t, 0.0);\n\n\n        for (int m=0; m<M; m++){\n\n            Eigen::Block<Eigen::MatrixXd> s = s_n_m.block(m,0,1,(*s0).cols());\n\n\n            //choose action, takes reference to s\n            _opt_CS_s_V(s, x_n_m, theta_V_pi, param->opt_CS_N);\n            \n            s_n_m.block(m+1,0,1,(*s0).cols()) = s;\n            \n            Eigen::Block<Eigen::MatrixXd> s1 = s_n_m.block(m+1,0,1,(*s0).cols());\n            s = s_n_m.block(m,0,1,(*s0).cols());\n            \n            \n            //make step given action, to update state and return value function\n            double _c = _c_theta_x(x_n_m, s1, theta_V_pi);\n            \n            double c_n_m = _c - _V(s1,&phi,theta_V_pi);\n            \n            _bf(s,&phi);\n            _bf(s1,&phi1);\n            Eigen::MatrixXd v_n_m = phi - param->BETA*phi1;\n            \n//            std::cout << s_n_m.row(m) << std::endl;\n//            std::cout << s << std::endl;\n//            \n//            std::cout << s_n_m.row(m+1) << std::endl;\n//            std::cout << theta_V_pi << std::endl;\n//            std::cout << theta_V_n << std::endl;\n            \n\n            //update theta_V_n\n            theta_V_n = _RLS(theta_V_n,\n                            v_n_m,\n                            s,\n                            m,\n                            c_n_m);\n            //assume that only 1 element in v and restrict it\n            if (theta_V_n(0,0) > 1000){\n                theta_V_n(0,0) = 1000;\n            };\n            if (theta_V_n(0,0) < 0.0){\n                theta_V_n(0,0) = 0.01;\n            };\n\n        };\n\n        theta_V_pi = theta_V_n;\n    };\n\n    //std::cout << theta_V_pi << std::endl;\n    return theta_V_pi;\n};\n\nEigen::MatrixXd\nF::_RLS(Eigen::MatrixXd& theta, Eigen::MatrixXd& v, Eigen::Block<Eigen::MatrixXd>& s, int i, double c){\n\n    //i - iteration if i = 0 - initialize B\n    //for each theta_t:\n    Eigen::MatrixXd B_n_1;\n    \n    if (i == 0){\n        //identity matrix\n        double e_B_0 = 0.0005;\n        \n        //B(n-1)\n        B_n_1 = e_B_0 * Eigen::MatrixXd::Identity(param->ADP_BF_N, param->ADP_BF_N);\n        \n    }else{\n        B_n_1 = B_n_1_RLS;\n    };\n    \n    //container for basis functions\n    Eigen::MatrixXd phi(1, param->ADP_BF_N);\n    _bf(s,&phi);\n    \n    double e_n = c - (v.transpose()*theta)(0,0);\n    \n    double gamma_n = 1 + ((v.transpose()*B_n_1)*phi)(0,0);\n    \n\n    Eigen::MatrixXd B_n = B_n_1 - 1/gamma_n *((B_n_1*(phi*v.transpose()))*B_n_1);\n    \n    Eigen::MatrixXd theta_n = theta + 1/gamma_n * ((e_n*B_n_1)*phi);\n    \n//    std::cout << 1/gamma_n * ((e_n*B_n_1)*phi) << std::endl;\n    \n//    std::cout << theta_n << std::endl;\n    \n    B_n_1_RLS = B_n;\n\n    \n                \n    return theta_n;\n    \n    \n};\n\n\n\n\ndouble\nF::_c_theta_x(Eigen::MatrixXd& theta_x, Eigen::Block<Eigen::MatrixXd>& s0, Eigen::MatrixXd& theta_V){\n    \n    int N = 1;\n    double _c = 0.0;\n    \n//    std::cout << s0 << std::endl;\n    \n\t//gets matrix of thetas\n\t//prepare initial matrix\n\tMatrixXd m_s0 = MatrixXd::Zero(N, s0.cols());\n    \n\tm_s0.rowwise() += s0.row(0);\n    \n    \n\t//allocate space to the matrix\n\tMatrixXd n_w;\n\tMatrixXd n_x = MatrixXd::Zero(N, 4);\n\tMatrixXd n_s = MatrixXd::Zero(N, s0.cols());\n    MatrixXd v_bf_ret = MatrixXd::Zero(1, param->ADP_BF_N);\n\tMatrixXd n_c = MatrixXd::Zero(N, 1);;\n    MatrixXd n_v = MatrixXd::Zero(N, 1);;\n\n    \n    //create random number generators for the implementation\n    \n\tboost::normal_distribution<> nd_w1(s0(0,3), pow(s0(0,17),0.5));\n\tboost::normal_distribution<> nd_w2(s0(0,5), pow(s0(0,18),0.5));\n    \n\tboost::variate_generator<boost::mt19937&,\n    boost::normal_distribution<>> rng_w1(w.rng, nd_w1);\n    \n\tboost::variate_generator<boost::mt19937&,\n    boost::normal_distribution<>> rng_w2(w.rng, nd_w2);\n    \n    \n    if (w.param->SIMULATION_MODE != \"test\"){\n        \n        //draw random variables\n        n_w = MatrixXd::Zero(N, 2 * 1);\n        for (int i = 0; i < N; i++){\n            for(int j=0; j< n_w.cols(); j++){\n                if (j%2 == 0){\n                    n_w(i,j) = rng_w1();\n                } else {\n                    n_w(i,j) = rng_w2();\n                };\n                n_w(i,j) = std::max(0.0, (double)n_w(i,j));\n            };\n        };\n    };\n\n\n    \n\n    //redraw random in comparative with Python mode\n    if (w.param->SIMULATION_MODE == \"test\"){\n        n_w = MatrixXd::Zero(N, 2 * param->T_MAX);\n        for (int k = 0; k < N; k++){\n            for(int j=0; j< n_w.cols(); j++){\n                if (j%2 == 0){\n                    n_w(k,j) = Tools::get_normal(s0(0,3), pow(s0(0,17),0.5), w.myrng);\n                } else {\n                    n_w(k,j) = Tools::get_normal(s0(0,5), pow(s0(0,18),0.5), w.myrng);\n                };\n                n_w(k,j) = std::max(0.0, (double)n_w(k,j));\n            };\n        };\n    };\n    \n    \n    //call estimator of results of steps, given theta_x\n    n_s = m_s0;\n    _step_opt_CS(theta_x, &n_w, &n_x, &n_s, &n_c, &n_v, theta_V, &v_bf_ret, 1);\n    _c = (n_c + param->BETA*n_v).mean();\n    \n    s0.row(0) = n_s.row(0);\n    \n    \n//    std::cout << s0 << std::endl;\n    \n    return _c;\n    \n};\n\n\n\nvoid\nF::_opt_CS_s_V(Eigen::Block<Eigen::MatrixXd>& s0,  Eigen::MatrixXd& theta_x, Eigen::MatrixXd& theta_V, int N){\n    \n    //\tN = 1;\n    \n\t//gets matrix of thetas\n\t//prepare initial matrix\n\tMatrixXd m_s0 = MatrixXd::Zero(N, s0.cols());\n    \n\tm_s0.rowwise() += s0.row(0);\n    \n    \n\t//allocate space to the matrix\n\tMatrixXd n_w;\n\tMatrixXd n_x;\n\tMatrixXd n_s = MatrixXd::Zero(N, s0.cols());\n\tMatrixXd n_c;\n    MatrixXd v_bf_ret = MatrixXd::Zero(1, param->ADP_BF_N);\n    MatrixXd n_v;\n    \n    \n\t//create matrix for the grid - small size here\n\tMatrixXd grid(4,3);\n    \n    create_decision_grid(grid,0);\n    \n    if (w.param->SIMULATION_MODE == \"test\"){\n        Tools::mgrid_test(grid, &theta_x_all);\n        \n    } else{\n        \n        Tools::mgrid(grid, &theta_x_all);\n    };\n    \n\t//create random number generators for the implementation\n    \n\tboost::normal_distribution<> nd_w1(s0(0,3), pow(s0(0,17),0.5));\n\tboost::normal_distribution<> nd_w2(s0(0,5), pow(s0(0,18),0.5));\n    \n\tboost::variate_generator<boost::mt19937&,\n    boost::normal_distribution<>> rng_w1(w.rng, nd_w1);\n    \n\tboost::variate_generator<boost::mt19937&,\n    boost::normal_distribution<>> rng_w2(w.rng, nd_w2);\n    \n    \n    if (w.param->SIMULATION_MODE != \"test\"){\n        \n        //draw random variables\n        n_w = MatrixXd::Zero(N, 2 * 1);\n        for (int i = 0; i < N; i++){\n            for(int j=0; j< n_w.cols(); j++){\n                if (j%2 == 0){\n                    n_w(i,j) = rng_w1();\n                } else {\n                    n_w(i,j) = rng_w2();\n                };\n                n_w(i,j) = std::max(0.0, (double)n_w(i,j));\n            };\n        };\n    };\n    \n    \n\t//matrix of all\n\tMatrixXd c_all(theta_x_all.cols(),1);\n    \n\tfor (int i = 0 ; i < theta_x_all.cols(); i++){\n        //redraw random in comparative with Python mode\n        if (w.param->SIMULATION_MODE == \"test\"){\n            n_w = MatrixXd::Zero(N, 2 * 1);\n            for (int k = 0; k < N; k++){\n                for(int j=0; j< n_w.cols(); j++){\n                    if (j%2 == 0){\n                        n_w(k,j) = Tools::get_normal(s0(0,3), pow(s0(0,17),0.5), w.myrng);\n                    } else {\n                        n_w(k,j) = Tools::get_normal(s0(0,5), pow(s0(0,18),0.5), w.myrng);\n                    };\n                    n_w(k,j) = std::max(0.0, (double)n_w(k,j));\n                };\n            };\n        };\n        \n        \n\t\t//call estimator of results of steps, given theta_x\n\t\ttheta_x.row(0) = theta_x_all.col(i).transpose();\n\t\tn_x = MatrixXd::Zero(N, 4);\n\t\tn_s = m_s0;\n\t\tn_c = MatrixXd::Zero(N, 1);\n        n_v = MatrixXd::Zero(N, 1);\n\t\t_step_opt_CS(theta_x, &n_w, &n_x, &n_s, &n_c, &n_v, theta_V, &v_bf_ret, 1);\n        \n\t\t//after n_c\n\t\t//average over n runs\n        c_all(i,0) = (n_c + param->BETA*n_v).mean();\n        \n\t};\n    \n//    std::cout << (n_c + param->BETA*n_v).mean() << std::endl;\n    \n    \n\t//find all max elements\n\tdouble max = c_all(0,0);\n\tstd::list<int> i_max;\n\tfor (int i=0; i<c_all.rows(); i++){\n\t\tif (c_all(i,0) == max){\n\t\t\ti_max.push_back(i);\n\t\t}else{\n\t\t\tif (c_all(i,0) > max){\n\t\t\t\tmax = c_all(i,0);\n\t\t\t\ti_max.clear();\n\t\t\t\ti_max.push_back(i);\n\t\t\t};\n\t\t}\n\t};\n    \n\t//if more than 1 max - randomly pick\n\tlong theta_max_i;\n\tif (i_max.size()>1){\n\t\tboost::random::uniform_int_distribution<> i_max_dist(0, i_max.size()-1);\n\t\ttheta_max_i = i_max_dist(w.rng);\n\t}else{\n\t\ttheta_max_i = i_max.front();\n\t};\n    \n    \n\ttheta_x.row(0) = theta_x_all.col(theta_max_i).transpose();\n    \n//    std::cout << theta_x << std::endl;\n};\n\n\nvoid\nF::create_decision_grid(Eigen::MatrixXd& grid, int begin_index){\n    int i = begin_index;\n    \n    if (param->GRID == \"small\"){\n\t\tgrid(i,0) = 0.0;\n\t\tgrid(i,1) = w.NH;\n\t\tgrid(i,2) = ((grid(i,1) - grid(i,0))/4);\n\t\tgrid(i+1,0) = 0.8;\n\t\tgrid(i+1,1) = 1.25;\n\t\tgrid(i+1,2) = 0.2;\n\t\tgrid(i+2,0) = 0.0;\n\t\tgrid(i+2,1) = 1.0;\n\t\tgrid(i+2,2) = 0.5;\n\t\tgrid(i+3,0) = 0.8;\n\t\tgrid(i+3,1) = 1.25;\n\t\tgrid(i+3,2) = 0.2;\n\t};\n    \n    if (param->GRID == \"big\"){\n\t\tgrid(i,0) = 0.0;\n\t\tgrid(i,1) = w.NH;\n\t\tgrid(i,2) = (grid(i,1) - grid(i,0))/4;\n\t\tgrid(i+1,0) = 0.1;\n\t\tgrid(i+1,1) = 2.1;\n\t\tgrid(i+1,2) = 0.45;\n\t\tgrid(i+2,0) = 0.0;\n\t\tgrid(i+2,1) = 1.0;\n\t\tgrid(i+2,2) = 0.5;\n\t\tgrid(i+3,0) = 0.1;\n\t\tgrid(i+3,1) = 2.1;\n\t\tgrid(i+3,2) = 0.45;\n        \n\t};\n    if (param->GRID == \"test\"){\n        \n        //        grid(0,0) = w.NH;\n        //        grid(0,1) = w.NH + 0.5;\n        //        grid(0,2) = 1.0;\n        //        grid(1,0) = 1.0;\n        //        grid(1,1) = 1.1;\n        //        grid(1,2) = 1.0;\n        //        grid(2,0) = 1.0;\n        //        grid(2,1) = 1.1;\n        //        grid(2,2) = 1.0;\n        //        grid(3,0) = 1.0;\n        //        grid(3,1) = 1.1;\n        //        grid(3,2) = 1.0;\n        \n        grid(i,0) = 2.5;\n        grid(i,1) = 2.5 + 1.5;\n        grid(i,2) = 1.0;\n        \n        grid(i+1,0) = 1.0;\n        grid(i+1,1) = 1.1;\n        grid(i+1,2) = 1.0;\n        \n        grid(i+2,0) = 0.5;\n        grid(i+2,1) = 1.1;\n        grid(i+2,2) = 1.0;\n        \n        grid(i+3,0) = 1.2;\n        grid(i+3,1) = 1.3;\n        grid(i+3,2) = 1.0;\n        \n        \n        \n    };\n\n    \n};\n\nvoid\nF::_step_opt_CS(MatrixXd& theta_x,\n                MatrixXd *w,\n                MatrixXd *x,\n                MatrixXd *s,\n                MatrixXd *c,\n                MatrixXd* v,\n                MatrixXd& theta_v,\n                MatrixXd* ret,\n                int T){\n    \n\t//sets decisions for labor market\n\t//zero vector\n\tauto s_zero = MatrixXd::Zero(s->rows(),1);\n    Eigen::Block<Eigen::MatrixXd> s_block = s->block(0,0,1,s->cols());;\n    \n    \n    \n\tfor (int i=0; i< T; i++){\n        \n        \n\t\tx->col(0) = Eigen::MatrixXd::Constant(x->rows(), 1, theta_x(0,0));\n\t\tx->col(1) = theta_x(0,1) * s->col(3).array();\n        \n        //        std::cout << *x << std::endl;\n        \n\t\t//labor market results\n\t\t//if wage is less than realized wage - zero, otherwise hire all desired number\n        \n\t\t(*s).col(9) = ((*w).col(i*2).array() <= x->col(1).array()).cast<double>().array() *x->col(0).array();\n\t\t(*s).col(10) = (*w).col(i*2);\n        \n        //cast to whole numbers\n        for (int j=0; j < s->rows(); j++){\n            (*s)(j,9) = floor((*s)(j,9));\n        };\n        \n        //        std::cout << *s << std::endl;\n        \n        \n        \n\t\t//current production\n\t\ts->col(13) = s->col(9).array().pow(param->F_F_theta(0,1))*param->F_F_theta(0,0);\n\t\ts->col(2) += s->col(13);\n        \n        //        std::cout << *s << std::endl;\n        \n\t\t//update for cost structure\n\t\ts->col(7) = s->col(7).array() + ((*s).col(9).array() * (*s).col(10).array());\n\t\ts->col(8) += s->col(13);\n        \n        //        std::cout << *s << std::endl;\n        \n\t\t//sets decision for goods market\n\t\tx->col(2) = theta_x(0,2) * s->col(2).array();\n\t\tx->col(3) = Eigen::MatrixXd::Constant(x->rows(), 1, theta_x(0,3) * (*s)(0,5));\n        \n        //        std::cout << *x << std::endl;\n        \n\t\t//sales\n\t\t(*s).col(11) = ((*w).col(i*2 + 1).array() >= x->col(3).array()).cast<double>().array() *x->col(2).array();\n\t\t(*s).col(12) = (*w).col(i*2 + 1);\n        \n        //        std::cout << *s << std::endl;\n        \n\t\t//money\n\t\ts->col(0) = s->col(0).array() + (s->col(11).array() * s->col(12).array());\n        \n        //        std::cout << *s << std::endl;\n        \n\t\t//inventory\n\t\ts->col(2) -= s->col(11);\n        \n        //        std::cout << *s << std::endl;\n        \n\t\tdouble atc = 0.0;\n        \n\t\t//updates current profit\n\t\tfor (int j=0; j < s->rows(); j++){\n            \n\t\t\tif ((*s)(j,8)>0.0){\n\t\t\t\tatc = (*s)(j,7) / (*s)(j,8);\n\n                \n                if (param->ACCOUNTING_TYPE==\"modern\"){\n                    //update profit to cost of production\n                    (*s)(j,14) -= atc * (*s)(j,11);\n                };\n                if (param->ACCOUNTING_TYPE==\"classic\"){\n                    //update profit to cost of production\n                    (*s)(j,14) -= (*s)(j,9) * (*s)(j,10);\n                };\n                \n\t\t\t\t//update cost of production\n\t\t\t\t(*s)(j,7) -= atc * (*s)(j,11);\n\t\t\t\t(*s)(j,8) -= (*s)(j,11);\n\t\t\t};\n            \n\t\t\t//update profit to sales\n\t\t\t(*s)(j,14) += (*s)(j,11) * (*s)(j,12);\n            \n\t\t\tatc = 0.0;\n\t\t};\n        \n        //        std::cout << *s << std::endl;\n        \n\t\t//labor payment\n\t\ts->col(0) = s->col(0).array() -  (s->col(9).array() * s->col(10).array());\n        \n        //        std::cout << *s << std::endl;\n        \n\t\t//dividends\n\t\ts->col(0) = s->col(0).array() - (s->col(14).array() > s_zero.array()).cast<double>().array() * s->col(14).array() * s->col(16).array();\n        \n//        std::cout << *s << std::endl;\n        \n\n\t\t\n        //zero out labor contract\n\t\ts->col(9) = s_zero;\n\t\ts->col(10) = s_zero;\n        \n        \n        //dead or alive\n\t\ts->col(15) = (s->col(0).array() >= s_zero.array()).cast<double>().array() * s->col(15).array();\n        \n        //        std::cout << *s << std::endl;\n        \n\t\t//stores realized goal\n\t\tc->col(i) = (s->col(15).array() > s_zero.array()).cast<double>().array() * s->col(14).array();\n\n        \n        //add value function estimation\n        for (int j=0; j < s->rows(); j++){\n            s_block  = s->block(j,0,1,s->cols());\n            \n            (*v)(j,i) = _V(s_block,ret, theta_V);\n        };\n        \n//        std::cout << *c << std::endl;\n        \n//        std::cout << *v << std::endl;\n        \n\t\t//zero out current profit\n\t\ts->col(14) = s_zero;\n        \n        \n\t};\n    \n    \n};\n\n\n\n\n\nvoid\nF::opt_QL(){\n    //find best action for the state\n    \n    //find current bin for the state\n    _s0();\n    std::vector<double> s_bin = _place_state_QL(s0);\n    s_t_bin = s_bin;\n    std::vector<int> Q_s;\n    \n    \n    //create list of all indexes that correspond to current state\n    for (int i = 0; i < s_bin.size(); i++){\n        for (int j = 0; j< Q.cols(); j++){\n            if (_is_bin(j, i, s_bin)){\n                Q_s.push_back(j);\n            };\n            \n        };\n    };\n    \n    //find index with max Q\n    std::vector<int> Q_max;\n    double max = Q(6,Q_s.at(0));\n    \n    for (auto j:Q_s){\n        if (Q(6,j) > max){\n            max = Q(6,j);\n            Q_max.clear();\n            Q_max.push_back(j);\n            \n        }else{\n            if (Q(6,j) == max){\n                Q_max.push_back(j);\n            };\n        };\n        \n    };\n    \n    \n    \n    \n    boost::random::uniform_01<> _exp_dist;\n    double exp_rate = _exp_dist(w.rng);\n    \n    boost::random::uniform_int_distribution<> Q_dist(0, Q.cols()-1);\n    long theta_max_i;\n\n    \n    if (exp_rate < param->QL_experimental_rate){\n        theta_max_i = Q_dist(w.rng);\n    }else{\n        //pick randomly best action\n        if (Q_max.size()>1){\n            boost::random::uniform_int_distribution<> Q_max_dist(0, Q_max.size()-1);\n            theta_max_i = Q_max.at(Q_max_dist(w.rng));\n            \n        }else{\n            theta_max_i = Q_max.front();\n        };\n    };\n    \n    theta_x_t_bin.push_back(theta_max_i);\n\n    //transform from index to decision\n    theta_x.row(0) = Q.block(s_bin.size(),theta_max_i,4,1).transpose();\n    \n};\n\nbool\nF::_is_bin(int j, int i, std::vector<double>& s_bin){\n    bool is_bin = false;\n    \n    if (i < s_bin.size()){\n        is_bin = (Q(i,j) == Q_bin.at(i).at(s_bin.at(i))) && _is_bin(j, i+1, s_bin);\n//        std::cout << (Q(i,j) == s_bin.at(i)) << std::endl;\n//        std::cout << _is_bin(j, i+1, s_bin) << std::endl;\n    }else{\n        is_bin = true;\n    };\n    \n    return is_bin;\n};\n\n\n\nvoid\nF::wm_update_Q(){\n    //updates Q matrix\n    //reward\n    double R_t1 = account->profit.at(account->profit.size()-2);\n    \n    //new state\n    _s0();\n    std::vector<double> s_bin = _place_state_QL(s0);\n    std::vector<int> Q_s;\n    \n    \n    //create list of all indexes that correspond to current state\n    for (int i = 0; i < s_bin.size(); i++){\n        for (int j = 0; j< Q.cols(); j++){\n            if (_is_bin(j, i+1, s_bin)){\n                Q_s.push_back(j);\n            };\n            \n        };\n    };\n    \n    //find index with max Q\n    std::vector<int> Q_max;\n    double max = Q(6,Q_s.at(0));\n    \n    for (auto j:Q_s){\n        if (Q(6,j) > max){\n            max = Q(6,j);\n            Q_max.clear();\n            Q_max.push_back(j);\n            \n        }else{\n            if (Q(6,j) == max){\n                Q_max.push_back(j);\n            };\n        };\n        \n    };\n\n    //pick best action\n    long theta_max_i;\n    long max_i;\n    if (Q_max.size()>1){\n        boost::random::uniform_int_distribution<> Q_max_dist(0, Q_max.size()-1);\n        max_i = Q_max_dist(w.rng);\n        theta_max_i = Q_max.at(max_i);\n    }else{\n        theta_max_i = Q_max.front();\n    };\n\n    \n    //update Q value\n    Q(6,theta_x_t_bin.back()) = Q(6,theta_x_t_bin.back())\n                                + Q(7,theta_x_t_bin.back())\n                                * (R_t1 + param->BETA*Q(6,theta_max_i) - Q(6,theta_x_t_bin.back()));\n//    std::cout << Q << std::endl;\n    \n};\n\n\n\nvoid\nF::_set_QL(){\n    //setup QL matrix\n    //create matrix for the grid - small size here\n\tQ_grid = Eigen::MatrixXd::Zero(8,3);\n\n    //money and stock of goods on hand\n    Q_grid(0,0) = 0.0;\n    Q_grid(0,1) = 100.0;\n    Q_grid(0,2) = ((Q_grid(0,1) - Q_grid(0,0))/2);\n    Q_grid(1,0) = 0.0;\n    Q_grid(1,1) = w.NH;\n    Q_grid(1,2) = ((Q_grid(1,1) - Q_grid(1,0))/2);\n    \n    create_decision_grid(Q_grid, 2);\n    \n    Q_grid(6,0) = 0.0;\n    Q_grid(6,1) = 0.1;\n    Q_grid(6,2) = 1.0;\n\n    Q_grid(7,0) = param->QL_L; //speed of learning\n    Q_grid(7,1) = Q_grid(7,0) + 0.1;\n    Q_grid(7,2) = Q_grid(7,0) + 1.0;\n    \n    if (w.param->SIMULATION_MODE == \"test\"){\n        Tools::mgrid_test(Q_grid, &Q);\n        \n    } else{\n        \n        Tools::mgrid(Q_grid, &Q);\n    };\n    \n    create_bin_values(Q_grid, Q_bin);\n\n    //update Q to push to hiring all of them\n    for (int j = 0; j < Q.cols(); j++){\n        if (Q(2,j) == Q_bin.at(2).back()){\n            Q(6,j) = 0.05;\n        };\n    };\n    \n    \n//    std::cout << Q << std::endl;\n    \n//    Tools::print_vector(Q_bin);\n    \n};\n\n\nvoid\nF::create_bin_values(Eigen::MatrixXd& _grid, std::vector<std::vector<double>>& _bin){\n    long N_rows = _grid.rows();\n\tint n_steps_i;\n\tdouble n_steps_i_int;\n    \n\tdouble val;\n    std::vector<double> values_temp;\n    \n    //create matrix of bin values\n    //create list of values\n\tfor (int i=0; i < N_rows; i++){\n\t\t//n_steps\n\t\tn_steps_i_int = (_grid(i,1) - _grid(i,0))/_grid(i,2);\n        \n\t\tn_steps_i = static_cast<int>(floor(n_steps_i_int)) + 1;\n\n        \n\t\tfor (int j=0; j<n_steps_i; j++){\n\t\t\tval = _grid(i,0) + _grid(i,2)*j;\n\t\t\tvalues_temp.push_back(val);\n\t\t};\n        \n\t\t_bin.push_back(values_temp);\n\t\tvalues_temp.clear();\n\t};\n\n};\n\n\nstd::vector<double>\nF::_place_state_QL(Eigen::MatrixXd& s){\n    std::vector<double> s_bin;\n    \n    //pick first and compare\n    //push values for bins ina  vector\n    \n    bool FLAG_PLACED = false;\n    \n    int j = Q_bin.at(0).size()-1;\n    while ((j>=0) && !FLAG_PLACED){\n    \n           if (s(0,0) >= Q_bin.at(0).at(j)){\n               s_bin.push_back(j);\n               FLAG_PLACED = true;\n           };\n        j -= 1;\n    };\n    \n    j = Q_bin.at(1).size()-1;\n    FLAG_PLACED = false;\n    while ((j>=0) && !FLAG_PLACED){\n        \n        if (s(0,2) >= Q_bin.at(1).at(j)){\n            s_bin.push_back(j);\n            FLAG_PLACED = true;\n        };\n        j -= 1;\n    };\n    \n    return s_bin;\n};\n\n\n\nvoid\nF::_set_mRE(){\n    //\n    mRE_grid = Eigen::MatrixXd::Zero(5,3);\n    create_decision_grid(mRE_grid, 0);\n    mRE_grid(4,0) = 1.0;\n    mRE_grid(4,1) = 1.1;\n    mRE_grid(4,2) = 1.0;\n    \n    if (w.param->SIMULATION_MODE == \"test\"){\n        Tools::mgrid_test(mRE_grid, &mRE);\n        \n    } else{\n        \n        Tools::mgrid(mRE_grid, &mRE);\n    };\n    \n    \n    \n    create_bin_values(mRE_grid, mRE_bin);\n    \n    //update mRE to push to hiring all of them\n    for (int j = 0; j < mRE.cols(); j++){\n        if (mRE(0,j) == mRE_bin.at(0).back()){\n            mRE(4,j) = 1.05;\n        };\n    };\n    \n    \n//    //storage for actual probabilities\n//    mRE_grid(5,0) = 0.0;\n//    mRE_grid(5,1) = 0.1;\n//    mRE_grid(5,2) = 1.0;\n    \n};\n\n\n\nvoid\nF::opt_mRE(){\n    //form matrix of probabilities\n    double sum_prob = 0.0;\n    \n    for (int j=0; j<mRE.cols();j++){\n        sum_prob += exp(mRE(4,j)/param->mRE_T);\n    };\n    \n    std::vector<double> probs;\n    \n    for (int j=0; j<mRE.cols();j++){\n        probs.push_back(exp(mRE(4,j)/param->mRE_T)/sum_prob);\n    };\n\n    \n    //roll weighted dice\n    boost::random::discrete_distribution<> dist(probs.begin(), probs.end());\n    \n    \n    int theta_i = dist(w.rng);\n    \n    theta_x_t_bin.push_back(theta_i);\n    \n    //transform from index to decision\n    theta_x.row(0) = mRE.block(0,theta_i,4,1).transpose();\n    \n};\n\n\n\nvoid\nF::wm_update_mRE(){\n    //adjustment matrix\n    Eigen::MatrixXd _E_re  = Eigen::MatrixXd::Zero(1, mRE.cols());\n    \n    //reward\n    double R_t1 = account->profit.at(account->profit.size()-2);\n    \n    //adjustment\n    _E_re = mRE.row(4) * (param->mRE_EPSILON/(mRE.cols()-1));\n    \n    //include reward\n    _E_re(0,theta_x_t_bin.back()) = R_t1 * (1 - param->mRE_EPSILON);\n    \n    //update whole matrix\n    mRE.row(4) = mRE.row(4) * (1 - param->mRE_PHI) + _E_re;\n    \n//    std::cout << mRE << std::endl;\n};\n\n\n\nvoid\nF::_PS_receive_payment(MessagePSSendPayment* mes){};\n\nbool\nF::_PS_accept_PO(MessagePSSendPayment* mes){\n\treturn true;\n};\n\n\nContractBDt0*\nF::_PS_contract(){\n\treturn ass_asCBDt0.front();\n};\n", "meta": {"hexsha": "670ca58ed85a2289fe832a49a6e3c5b99b547e28", "size": 41015, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/F.cpp", "max_stars_repo_name": "wilfeli/DMGameBasic", "max_stars_repo_head_hexsha": "ccc5e7ba08ee4e1959c60421692540cafb1faeed", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2017-08-11T23:12:44.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-04T08:54:19.000Z", "max_issues_repo_path": "src/F.cpp", "max_issues_repo_name": "wilfeli/DMGameBasic", "max_issues_repo_head_hexsha": "ccc5e7ba08ee4e1959c60421692540cafb1faeed", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/F.cpp", "max_forks_repo_name": "wilfeli/DMGameBasic", "max_forks_repo_head_hexsha": "ccc5e7ba08ee4e1959c60421692540cafb1faeed", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-08-02T20:23:21.000Z", "max_forks_repo_forks_event_max_datetime": "2020-08-02T20:23:21.000Z", "avg_line_length": 22.4739726027, "max_line_length": 137, "alphanum_fraction": 0.5125685725, "num_tokens": 13689, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6001883735630721, "lm_q2_score": 0.5117166047041654, "lm_q1q2_score": 0.3071263567026105}}
{"text": "//---------------------------------------------------------------------------//\n//!\n//! \\file   DataGen_ElasticElectronMomentsEvaluator.cpp\n//! \\author Luke Kersting\n//! \\brief  Elastic electron cross section moments evaluator definition\n//!\n//---------------------------------------------------------------------------//\n\n// Std Lib Includes\n#include <limits>\n\n// Boost Includes\n#include <boost/function.hpp>\n#include <boost/bind.hpp>\n\n// FRENSIE Includes\n#include \"DataGen_ElasticElectronMomentsEvaluator.hpp\"\n#include \"Utility_GaussKronrodIntegrator.hpp\"\n#include \"Utility_LegendrePolynomial.hpp\"\n#include \"Utility_PhysicalConstants.hpp\"\n#include \"Utility_ContractException.hpp\"\n#include \"MonteCarlo_TwoDDistributionHelpers.hpp\"\n#include \"MonteCarlo_ElasticElectronScatteringDistributionNativeFactory.hpp\"\n#include \"MonteCarlo_ElectroatomicReactionNativeFactory.hpp\"\n#include \"Utility_StandardHashBasedGridSearcher.hpp\"\n\nnamespace DataGen{\n\n// Initialize static member data\n\n// cutoff angle for analytical peak\ndouble ElasticElectronMomentsEvaluator::s_rutherford_cutoff_angle = 1.0e-6;\n\n// cutoff angle cosine for analytical peak\ndouble ElasticElectronMomentsEvaluator::s_rutherford_cutoff_angle_cosine = 0.999999;\n\n// Constructor\nElasticElectronMomentsEvaluator::ElasticElectronMomentsEvaluator(\n    const Data::EvaluatedElectronDataContainer& native_eedl_data,\n    const double& cutoff_angle )\n  : d_native_eedl_data ( native_eedl_data ),\n    d_cutoff_angle( cutoff_angle )\n{\n  // Make sure the data is valid\n  testPrecondition( cutoff_angle >= s_rutherford_cutoff_angle );\n  testPrecondition( cutoff_angle <= 2.0 );\n\n  // Extract the common energy grid used for this atom\n  Teuchos::ArrayRCP<double> energy_grid;\n  energy_grid.assign( native_eedl_data.getElectronEnergyGrid().begin(),\n                      native_eedl_data.getElectronEnergyGrid().end() );\n\n  // Create the hard elastic distributions ( both Analog and Screened Rutherford ) \n  MonteCarlo::ElasticElectronScatteringDistributionNativeFactory::createHardElasticDistributions(\n    d_analog_distribution,\n    d_rutherford_distribution,\n    native_eedl_data,\n    cutoff_angle );\n\n  // Construct the hash-based grid searcher for this atom\n  Teuchos::RCP<Utility::HashBasedGridSearcher> grid_searcher(\n     new Utility::StandardHashBasedGridSearcher<Teuchos::ArrayRCP<const double>, false>(\n\t\t\t\t\t\t     energy_grid,\n\t\t\t\t\t\t     100u ) );\n\n  MonteCarlo::ElectroatomicReactionNativeFactory::createScreenedRutherfordElasticReaction(\n\t\t\t\t\t   native_eedl_data,\n\t\t\t\t\t   energy_grid,\n                       grid_searcher,\n\t\t\t\t\t   d_rutherford_reaction );\n\n  MonteCarlo::ElectroatomicReactionNativeFactory::createAnalogElasticReaction(\n\t\t\t\t\t   native_eedl_data,\n\t\t\t\t\t   energy_grid,\n                       grid_searcher,\n\t\t\t\t\t   d_analog_reaction );\n}\n\n// Evaluate the Legnendre Polynomial expansion of the screened rutherford pdf\ndouble ElasticElectronMomentsEvaluator::evaluateLegendreExpandedRutherford(\n                                    const double scattering_angle,\n                                    const double incoming_energy, \n                                    const int polynomial_order ) const\n{\n  // Make sure the energy and angle are valid\n  testPrecondition( incoming_energy > 0.0 );\n  testPrecondition( scattering_angle >= 0.0 );\n  testPrecondition( scattering_angle <= s_rutherford_cutoff_angle );\n\n  // Evaluate the elastic pdf value at a given energy and scattering angle cosine\n  double pdf_value = \n            d_rutherford_distribution->evaluatePDF( incoming_energy,\n                                                    scattering_angle );\n\n  // Evaluate the Legendre Polynomial at the given angle and order\n  double legendre_value =  \n    Utility::getLegendrePolynomial( 1.0-scattering_angle, polynomial_order );\n                   \n  return pdf_value*legendre_value;\n}\n\n// Evaluate the Legnendre Polynomial expansion of the elastic scttering PDF\ndouble ElasticElectronMomentsEvaluator::evaluateLegendreExpandedPDF(\n                                    const double scattering_angle,\n                                    const double incoming_energy, \n                                    const int polynomial_order ) const\n{\n  // Make sure the energy and angle are valid\n  testPrecondition( incoming_energy > 0.0 );\n  testPrecondition( scattering_angle >= s_rutherford_cutoff_angle );\n  testPrecondition( scattering_angle <= 2.0 );\n\n  // Evaluate the elastic pdf value at a given energy and scattering angle cosine\n  double pdf_value = \n            d_analog_distribution->evaluatePDF( incoming_energy,\n                                                scattering_angle );\n\n  // Evaluate the Legendre Polynomial at the given angle and order\n  double legendre_value =  \n    Utility::getLegendrePolynomial( 1.0 - scattering_angle, polynomial_order );\n                   \n  return pdf_value*legendre_value;\n}\n\n// Evaluate the Legnendre Polynomial expansion of the elastic scttering PDF\ndouble ElasticElectronMomentsEvaluator::evaluateLegendreExpandedPDFAtEnergyBin(\n                                    const double scattering_angle,\n                                    const unsigned incoming_energy_bin, \n                                    const int polynomial_order ) const\n{\n  // Make sure the energy and angle are valid\n  testPrecondition( incoming_energy_bin >= 0 );\n  testPrecondition( scattering_angle >= s_rutherford_cutoff_angle );\n  testPrecondition( scattering_angle <= 2.0 );\n\n  // Evaluate the elastic pdf value at a given energy and scattering angle cosine\n  double pdf_value = \n            d_analog_distribution->evaluatePDF( incoming_energy_bin,\n                                                scattering_angle );\n\n  // Evaluate the Legendre Polynomial at the given angle and order\n  double legendre_value =  \n    Utility::getLegendrePolynomial( 1.0 - scattering_angle, polynomial_order );\n      \n  return pdf_value*legendre_value;\n}\n\n// Evaluate the first n moments of the elastic scattering distribution at a given energy\nvoid ElasticElectronMomentsEvaluator::evaluateElasticMoment( \n            Teuchos::Array<Utility::long_float>& legendre_moments,\n            const double energy, \n            const int n,\n            const double precision ) const\n{\n  // Make sure the energy and order is valid\n  testPrecondition( energy > 0.0 );\n  testPrecondition( n >= 0 );\n\n  // Get common angular grid\n  Teuchos::Array<double> angular_grid;\n\n  angular_grid =\n    MonteCarlo::ElasticElectronScatteringDistributionNativeFactory::getAngularGrid(\n        d_native_eedl_data,\n        energy,\n        d_cutoff_angle );\n\n  // resize array to the number of legendre moments wanted\n  legendre_moments.resize(n+1);\n\n  Utility::GaussKronrodIntegrator integrator( precision );\n\n  // Calucuate the tabular and Rutherford component of the Legendre moment\n  Utility::long_float tabular_moment,rutherford_moment;\n\n  for ( int i = 0; i <= n; i++ )\n  {\n    double abs_error, moment_k;\n\n    // Get the analog cross section\n    double analog_cross_section = \n        d_analog_reaction->getCrossSection( energy ); \n\n    // Calucuate the component of the moment from screened Rutherford peak\n    evaluateScreenedRutherfordMoment( rutherford_moment, energy, i );\n\n    // Create boost rapper function for the hard elastic differential cross section\n    boost::function<double (double x)> distribution_wrapper = \n      boost::bind<double>( &ElasticElectronMomentsEvaluator::evaluateLegendreExpandedPDF,\n                         boost::cref( *this ),\n                         _1,\n                         energy,\n                         i );\n\n    Teuchos::Array<double>::iterator grid_point, grid_point_minus_one;\n    grid_point_minus_one = angular_grid.begin();\n    grid_point = ++angular_grid.begin();\n\n    tabular_moment = Utility::long_float(0);\n    for ( grid_point; grid_point != angular_grid.end(); grid_point++ )\n    {\n      moment_k = 0.0;\n      abs_error = 0.0;\n      integrator.integrateAdaptively<61>(\n\t\t\t\t\tdistribution_wrapper,\n\t\t\t\t\t*grid_point_minus_one,\n\t\t\t\t\t*grid_point,\n\t\t\t\t\tmoment_k,\n\t\t\t\t\tabs_error );\n\n      grid_point_minus_one = grid_point;\n\n      tabular_moment += moment_k;\n    }\n    legendre_moments[i] =\n        rutherford_moment + tabular_moment*analog_cross_section;\n  }\n}\n\n// Evaluate the first n moments of the elastic scattering distribution at a given energy\nvoid ElasticElectronMomentsEvaluator::evaluateElasticMoment( \n            Teuchos::Array<Utility::long_float>& legendre_moments,\n            const unsigned energy_bin, \n            const int n,\n            const double precision ) const\n{\n  // Make sure the energy and order is valid\n  testPrecondition( energy_bin >= 0 );\n  testPrecondition( n >= 0 );\n\n  // Get the energy at the given angular energy bin\n  double energy = d_analog_distribution->getEnergy( energy_bin );\n\n  // Get angular grid\n  Teuchos::Array<double> angular_grid;\n\n  angular_grid =\n    MonteCarlo::ElasticElectronScatteringDistributionNativeFactory::getAngularGrid(\n        d_native_eedl_data,\n        energy,\n        d_cutoff_angle );\n\n  // resize array to the number of legendre moments wanted\n  legendre_moments.resize(n+1);\n\n  Utility::GaussKronrodIntegrator integrator( precision );\n\n  // Calucuate the tabular and Rutherford component of the Legendre moment\n  Utility::long_float tabular_moment,rutherford_moment;\n\n  for ( int i = 0; i <= n; i++ )\n  {\n    double abs_error, moment_k;\n\n    // Get the analog cross section\n    double analog_cross_section = \n        d_analog_reaction->getCrossSection( energy ); \n\n    // Calucuate the component of the moment from screened Rutherford peak\n    evaluateScreenedRutherfordMoment( rutherford_moment, energy, i );\n\n    // Create boost rapper function for the hard elastic differential cross section\n    boost::function<double (double x)> distribution_wrapper = \n      boost::bind<double>( &ElasticElectronMomentsEvaluator::evaluateLegendreExpandedPDFAtEnergyBin,\n                         boost::cref( *this ),\n                         _1,\n                         energy_bin,\n                         i );\n\n    Teuchos::Array<double>::iterator grid_point, grid_point_minus_one;\n    grid_point_minus_one = angular_grid.begin();\n    grid_point = ++angular_grid.begin();\n\n    tabular_moment = Utility::long_float(0);\n    for ( grid_point; grid_point != angular_grid.end(); grid_point++ )\n    {\n      moment_k = 0.0;\n      abs_error = 0.0;\n      integrator.integrateAdaptively<61>(\n\t\t\t\t\tdistribution_wrapper,\n\t\t\t\t\t*grid_point_minus_one,\n\t\t\t\t\t*grid_point,\n\t\t\t\t\tmoment_k,\n\t\t\t\t\tabs_error );\n\n      grid_point_minus_one = grid_point;\n\n      tabular_moment += moment_k;\n    }\n    legendre_moments[i] = \n        rutherford_moment + tabular_moment*analog_cross_section;\n  }\n}\n\n// Evaluate the nth cross section moment of the screened Rutherford peak distribution \nvoid ElasticElectronMomentsEvaluator::evaluateScreenedRutherfordMoment( \n            Utility::long_float& rutherford_moment,\n            const double energy,\n            const int n ) const\n{\n  // Make sure the energy and angle are valid\n  testPrecondition( energy > 0.0 );\n\n  double angle;\n\n  angle = s_rutherford_cutoff_angle;\n\n  // Calcuate Moliere's modified screening constant (eta) \n  double eta = \n    d_rutherford_distribution->evaluateMoliereScreeningConstant( energy );\n\n  /*!  \\details If eta is small ( << 1 ) a recursion relationship can be used to \n   *! calculate the moments of the screened Rutherford peak. For larger eta the \n   *! moments will be calculated by numerical integration.\n   */\n  if ( eta <= 1.0e-2 )\n  {\n    rutherford_moment = d_rutherford_reaction->getCrossSection( energy );\n\n    if ( n > 0 )\n    {\n      Teuchos::Array<Utility::long_float> coef_one( n+1 ), coef_two( n+1 );\n\n      coef_one[0] = Utility::long_float(0);\n      coef_one[1] = ( log( ( eta + angle )/( eta ) ) ) -\n                     angle/( angle + eta );\n\n      coef_two[0] = angle;\n      coef_two[1] = ( Utility::long_float(2) - angle )*angle/\n                      Utility::long_float(2);\n\n      for ( int i = 1; i < n; i++ )\n      {\n        coef_one[i+1] = \n          ( Utility::long_float(2) + Utility::long_float(1)/i )*\n          ( Utility::long_float(1) + eta )*coef_one[i] - \n          ( Utility::long_float(1) + Utility::long_float(1)/i )*coef_one[i-1] -\n          ( ( Utility::long_float(2) + Utility::long_float(1)/i )/\n          ( angle + eta ) )*( angle - coef_two[i] );\n\n        coef_two[i+1] = \n          ( Utility::long_float(2)*i + Utility::long_float(1) )/\n          ( i + Utility::long_float(2) )*( Utility::long_float(1) - angle )*\n          coef_two[i] - \n          ( i - Utility::long_float(1) )/( i + Utility::long_float(2) )*\n          coef_two[i-1];\n      } \n      Utility::long_float frac_disc = \n          angle*( Utility::long_float(1) + eta/Utility::long_float(2) )/\n        ( angle + eta );\n\n      rutherford_moment *= (1.0 - eta*coef_one[n]/frac_disc );\n    }\n  }\n  else // Numerically integrate the moment\n  {\n    Utility::GaussKronrodIntegrator integrator( 1e-13 );\n\n    double abs_error, moment_n;\n\n    double rutherford_cross_section = \n        d_rutherford_reaction->getCrossSection( energy ); \n\n    double moment_zero = \n        d_rutherford_distribution->evaluateIntegratedPDF( energy );\n \n    if ( n == 0 )\n    {\n      moment_n = moment_zero;\n    }\n    else\n    {\n      // Create boost rapper function for the screened Rutherford peak\n      boost::function<double (double x)> wrapper = \n        boost::bind<double>( &ElasticElectronMomentsEvaluator::evaluateLegendreExpandedRutherford,\n                         boost::cref( *this ),\n                         _1,\n                         energy,\n                         n );\n\n      integrator.integrateAdaptively<61>(\n\t\t\t\t\twrapper,\n                    0.0,\n\t\t\t\t\ts_rutherford_cutoff_angle,\n\t\t\t\t\tmoment_n,\n\t\t\t\t\tabs_error );\n    }\n    rutherford_moment = moment_n/moment_zero*rutherford_cross_section;\n  }\n}\n\n} // end DataGen namespace\n\n//---------------------------------------------------------------------------//\n// end DataGen_ElasticElectronMomentsEvaluator.cpp\n//---------------------------------------------------------------------------//\n", "meta": {"hexsha": "539bd4a32207b455e0135e0bcf0a02d63d9b9995", "size": 14161, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "packages/data_gen/electron_photon/src/DataGen_ElasticElectronMomentsEvaluator.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_ElasticElectronMomentsEvaluator.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_ElasticElectronMomentsEvaluator.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": 35.6700251889, "max_line_length": 100, "alphanum_fraction": 0.6573688299, "num_tokens": 3194, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6893056295505784, "lm_q2_score": 0.4455295350395727, "lm_q1q2_score": 0.30710601663382914}}
{"text": "/*\n * Author(s):  Salvadore Gerace <sgerace@dotdecimal.com>\n *             Thomas Madden <tmadden@mgh.harvard.edu>\n * Date:       03/27/2013\n *\n * Copyright:\n * This work was developed as a joint effort between .decimal, Inc. and\n * Partners HealthCare under research agreement A213686; as such, it is\n * jointly copyrighted by the participating organizations.\n * (c) 2013 .decimal, Inc. All rights reserved.\n * (c) 2013 Partners HealthCare. All rights reserved.\n */\n#include <boost/algorithm/string/classification.hpp>\n#include <boost/algorithm/string/split.hpp>\n#include <boost/algorithm/string/trim.hpp>\n#include <cradle/geometry/meshing.hpp>\n\n#include <cradle/geometry/common.hpp>\n#include <cradle/geometry/distance.hpp>\n#include <cradle/geometry/grid_points.hpp>\n#include <cradle/geometry/intersection.hpp>\n#include <cradle/geometry/polygonal.hpp>\n\n#include <cradle/imaging/geometry.hpp>\n#include <cradle/imaging/image.hpp>\n\n#include <boost/compressed_pair.hpp>\n\n#include <fstream>\n\n//#include <cradle/io/stereolithography_io.hpp>\n\nnamespace cradle {\n\n// amount to scale our geometry by to make it sized correctly for clipper\nstatic const double geometry_scale_factor\n    = 1.0 / cradle::clipper_integer_precision;\n\ntriangle_mesh\nmake_cube(vertex3 const& origin, vertex3 const& extent)\n{\n    triangle_mesh mesh;\n\n    auto vertices = allocate(&mesh.vertices, 8);\n    vertices[0] = make_vector(origin[0], origin[1], origin[2]);\n    vertices[1] = make_vector(extent[0], origin[1], origin[2]);\n    vertices[2] = make_vector(origin[0], extent[1], origin[2]);\n    vertices[3] = make_vector(extent[0], extent[1], origin[2]);\n    vertices[4] = make_vector(origin[0], origin[1], extent[2]);\n    vertices[5] = make_vector(extent[0], origin[1], extent[2]);\n    vertices[6] = make_vector(origin[0], extent[1], extent[2]);\n    vertices[7] = make_vector(extent[0], extent[1], extent[2]);\n\n    auto faces = allocate(&mesh.faces, 12);\n    faces[0] = make_vector(0, 3, 1);\n    faces[1] = make_vector(0, 2, 3);\n    faces[2] = make_vector(0, 1, 5);\n    faces[3] = make_vector(0, 5, 4);\n    faces[4] = make_vector(0, 4, 2);\n    faces[5] = make_vector(2, 4, 6);\n    faces[6] = make_vector(4, 5, 6);\n    faces[7] = make_vector(5, 7, 6);\n    faces[8] = make_vector(2, 6, 3);\n    faces[9] = make_vector(3, 6, 7);\n    faces[10] = make_vector(1, 3, 5);\n    faces[11] = make_vector(3, 7, 5);\n\n    return mesh;\n}\n\ntriangle_mesh\nmake_cylinder(\n    vector3d const& base,\n    double radius,\n    double height,\n    int resolution,\n    unsigned axis_direction)\n{\n    triangle_mesh mesh;\n\n    unsigned direction = 2;\n    if (axis_direction < 3)\n    {\n        direction = axis_direction;\n    }\n    vector3i ordinates;\n    if (direction == 0)\n    {\n        ordinates = make_vector(1, 2, 0);\n    }\n    if (direction == 1)\n    {\n        ordinates = make_vector(2, 0, 1);\n    }\n    if (direction == 2)\n    {\n        ordinates = make_vector(0, 1, 2);\n    }\n\n    int k = 8;\n    if (resolution > k)\n    {\n        k = resolution;\n    }\n    vector3d axis = make_vector(0.0, 0.0, 0.0);\n    axis[direction] = height;\n    double delta = (2.0 * pi) / k;\n    auto vertices = allocate(&mesh.vertices, 2 * k + 2);\n    for (int i = 0; i < k; ++i)\n    {\n        vector3d v = make_vector(0., 0., 0.);\n        v[ordinates[0]] = radius * std::cos(i * delta);\n        v[ordinates[1]] = radius * std::sin(i * delta);\n        vertices[i] = base + v;\n        v[ordinates[2]] = height;\n        vertices[i + k + 1] = base + v;\n    }\n    vertices[k] = base;\n    vertices[2 * k + 1] = base + axis;\n\n    auto faces = allocate(&mesh.faces, 4 * k);\n    for (int i = 0; i < k; ++i)\n    {\n        faces[i] = make_vector(i, k, i + 1);\n        faces[i + k] = make_vector(i + k + 2, 2 * k + 1, i + k + 1);\n    }\n    faces[k - 1] = make_vector(k - 1, k, 0);\n    faces[2 * k - 1] = make_vector(k + 1, 2 * k + 1, 2 * k);\n    for (int i = 0; i < k; ++i)\n    {\n        faces[2 * i + 2 * k] = make_vector(i, i + 1, i + k + 1);\n        faces[2 * i + 2 * k + 1] = make_vector(i + 1, i + k + 2, i + k + 1);\n    }\n    faces[4 * k - 2] = make_vector(k - 1, 0, 2 * k);\n    faces[4 * k - 1] = make_vector(0, k + 1, 2 * k);\n\n    return mesh;\n};\n\ntriangle_mesh\nmake_sphere(\n    vector3d const& center, double radius, int theta_count, int phi_count)\n{\n    triangle_mesh mesh;\n\n    int kt = 8;\n    if (theta_count > kt)\n    {\n        kt = theta_count;\n    }\n\n    int kp = 8;\n    if (phi_count > kp)\n    {\n        kp = phi_count;\n    }\n\n    double deltat = (2.0 * pi) / kt;\n    double deltap = pi / (double(kp) - 1.0);\n    auto vertices = allocate(&mesh.vertices, kt * (kp - 2) + 2);\n    auto faces = allocate(&mesh.faces, (kp - 2) * 2 * kt);\n\n    int k = 1;\n    int f = 0;\n    vertices[0] = center - make_vector(0., 0., radius);\n    int kL = 0;\n    for (int j = 1; j < kp - 1; ++j)\n    {\n        double z = center[2] - radius * std::cos(j * deltap);\n        vector3d v = make_vector(0., 0., z);\n        double rL = radius * std::sin(j * deltap);\n        for (int i = 0; i < kt; ++i)\n        {\n            // Make next batch of vertices\n            v[0] = center[0] + rL * std::cos(i * deltat);\n            v[1] = center[1] + rL * std::sin(i * deltat);\n            vertices[k + i] = v;\n        }\n\n        if (j == 1)\n        {\n            // First level\n            for (int i = 0; i < kt - 1; ++i)\n            {\n                faces[f++] = make_vector(k + i, k + i + 1, 0);\n            }\n            faces[f++] = make_vector(k + kt - 1, k, 0);\n        }\n        else\n        {\n            // All other levels\n            kL = k - kt;\n            for (int i = 0; i < kt - 1; ++i)\n            {\n                faces[f++] = make_vector(kL + i + 1, kL + i, k + i);\n                faces[f++] = make_vector(k + i, k + i + 1, kL + i + 1);\n            }\n            faces[f++] = make_vector(kL, kL + kt - 1, k + kt - 1);\n            faces[f++] = make_vector(k + kt - 1, k, kL);\n        }\n        k += kt;\n    }\n    // Last Level\n    vertices[k] = center + make_vector(0., 0., radius);\n    kL = k - kt;\n    for (int i = 0; i < kt - 1; ++i)\n    {\n        faces[f++] = make_vector(kL + i + 1, kL + i, k);\n    }\n    faces[f++] = make_vector(kL + kt - 1, kL, k);\n    // std::cout << \"Faces: \" << f << \" Edges: \" << k+1 << std::endl;\n    return mesh;\n}\n\ntriangle_mesh\nmake_pyramid(\n    vector3d const& base,\n    double width,\n    double length,\n    double height,\n    unsigned axis_direction)\n{\n    triangle_mesh mesh;\n\n    unsigned direction = 2;\n    if (axis_direction < 3)\n    {\n        direction = axis_direction;\n    }\n    vector3i ordinates;\n    if (direction == 0)\n    {\n        ordinates = make_vector(1, 2, 0);\n    }\n    if (direction == 1)\n    {\n        ordinates = make_vector(2, 0, 1);\n    }\n    if (direction == 2)\n    {\n        ordinates = make_vector(0, 1, 2);\n    }\n\n    vector3d axis = make_vector(0.0, 0.0, 0.0);\n    axis[direction] = height;\n\n    auto vertices = allocate(&mesh.vertices, 5);\n\n    vector3d v = base;\n    v[ordinates[0]] -= 0.5 * width;\n    v[ordinates[1]] -= 0.5 * length;\n    vertices[0] = v;\n    v[ordinates[0]] += width;\n    vertices[1] = v;\n    v[ordinates[1]] += length;\n    vertices[2] = v;\n    v[ordinates[0]] -= width;\n    vertices[3] = v;\n    v = base;\n    v[ordinates[2]] += height;\n    vertices[4] = v;\n\n    auto faces = allocate(&mesh.faces, 6);\n    faces[0] = make_vector(0, 1, 2);\n    faces[1] = make_vector(0, 2, 3);\n    faces[2] = make_vector(0, 4, 1);\n    faces[3] = make_vector(1, 4, 2);\n    faces[4] = make_vector(2, 4, 3);\n    faces[5] = make_vector(3, 4, 0);\n\n    return mesh;\n}\n\ntriangle_mesh\nmake_parallelepiped(\n    vector3d const& corner,\n    vector3d const& a,\n    vector3d const& b,\n    vector3d const& c)\n{\n    triangle_mesh mesh;\n\n    auto vertices = allocate(&mesh.vertices, 8);\n    vertices[0] = corner;\n    vertices[1] = corner + a;\n    vertices[2] = corner + b;\n    vertices[3] = corner + a + b;\n    vertices[4] = corner + c;\n    vertices[5] = corner + a + c;\n    vertices[6] = corner + b + c;\n    vertices[7] = corner + a + b + c;\n\n    auto faces = allocate(&mesh.faces, 12);\n    faces[0] = make_vector(0, 3, 1);\n    faces[1] = make_vector(0, 2, 3);\n    faces[2] = make_vector(0, 1, 5);\n    faces[3] = make_vector(0, 5, 4);\n    faces[4] = make_vector(0, 4, 2);\n    faces[5] = make_vector(2, 4, 6);\n    faces[6] = make_vector(4, 5, 6);\n    faces[7] = make_vector(5, 7, 6);\n    faces[8] = make_vector(2, 6, 3);\n    faces[9] = make_vector(3, 6, 7);\n    faces[10] = make_vector(1, 3, 5);\n    faces[11] = make_vector(3, 7, 5);\n\n    return mesh;\n};\n\ntypedef boost::compressed_pair<unsigned char, unsigned char> cpair;\n\ntypedef line_segment<2, double> line_segment2;\n\ndouble\ninterpolate_value(double ss, double tol, double ptb, double a, double b)\n{\n    double dsq = (b * b + ss);\n    if (dsq < a * a)\n    {\n        return ((a < 0) ? 1.0 : -1.0) * std::sqrt(dsq);\n        // return -std::sqrt(dsq);\n    }\n    else\n    {\n        return std::fabs(a) > tol ? -a : -a + ptb;\n    }\n}\n\nvertex3\ninterpolate_position(\n    vector3d const& origin,\n    vector3d const& extent,\n    int c,\n    int r,\n    double a,\n    double b)\n{\n    double u = origin[c] - a * (extent[c] - origin[c]) / (b - a);\n    switch (c)\n    {\n        case 0: {\n            switch (r)\n            {\n                case 0: {\n                    return make_vector(u, origin[1], origin[2]);\n                }\n                case 1: {\n                    return make_vector(u, extent[1], origin[2]);\n                }\n                case 2: {\n                    return make_vector(u, origin[1], extent[2]);\n                }\n                case 3: {\n                    return make_vector(u, extent[1], extent[2]);\n                }\n                default: {\n                    return vertex3();\n                }\n            }\n            break;\n        }\n        case 1: {\n            switch (r)\n            {\n                case 0: {\n                    return make_vector(origin[0], u, origin[2]);\n                }\n                case 1: {\n                    return make_vector(extent[0], u, origin[2]);\n                }\n                case 2: {\n                    return make_vector(origin[0], u, extent[2]);\n                }\n                case 3: {\n                    return make_vector(extent[0], u, extent[2]);\n                }\n                default: {\n                    return vertex3();\n                }\n            }\n            break;\n        }\n        case 2: {\n            switch (r)\n            {\n                case 0: {\n                    return make_vector(origin[0], origin[1], u);\n                }\n                case 1: {\n                    return make_vector(extent[0], origin[1], u);\n                }\n                case 2: {\n                    return make_vector(origin[0], extent[1], u);\n                }\n                case 3: {\n                    return make_vector(extent[0], extent[1], u);\n                }\n                default: {\n                    return vertex3();\n                }\n            }\n            break;\n        }\n        default: {\n            return vertex3();\n        }\n    }\n}\n\ntypedef std::vector<vertex3> growable_vertex3_array;\n\ntypedef std::vector<face3> growable_face3_array;\n\napi(struct)\nstruct growable_triangle_mesh\n{\n    growable_vertex3_array vertices;\n    growable_face3_array faces;\n};\n\ntemplate<class T>\nvoid\nvector_to_array(array<T>* array, std::vector<T> const& vector)\n{\n    size_t size = vector.size();\n    if (size != 0)\n    {\n        auto p = allocate(array, size);\n        memcpy(p, &vector[0], sizeof(T) * size);\n    }\n    else\n    {\n        clear(array);\n    }\n}\n\nstatic triangle_mesh\ncollapse_mesh(growable_triangle_mesh const& growable)\n{\n    triangle_mesh mesh;\n    vector_to_array(&mesh.vertices, growable.vertices);\n    vector_to_array(&mesh.faces, growable.faces);\n    return mesh;\n}\n\ntypedef std::vector<vertex3> growable_vertex3_array;\n\ntypedef std::vector<face3> growable_face3_array;\n\napi(struct)\nstruct growable_triangle_mesh_with_normals\n{\n    growable_vertex3_array vertex_positions;\n    growable_vertex3_array vertex_normals;\n    growable_face3_array face_position_indices;\n    growable_face3_array face_normal_indices;\n};\n\nstatic triangle_mesh_with_normals\ncollapse_mesh(growable_triangle_mesh_with_normals const& growable)\n{\n    triangle_mesh_with_normals mesh;\n    vector_to_array(&mesh.vertex_positions, growable.vertex_positions);\n    vector_to_array(&mesh.vertex_normals, growable.vertex_normals);\n    vector_to_array(\n        &mesh.face_position_indices, growable.face_position_indices);\n    vector_to_array(&mesh.face_normal_indices, growable.face_normal_indices);\n    return mesh;\n}\n\nimage<3, float, shared>\nset_data_for_structure(\n    image<3, float, shared> const& img,\n    structure_geometry const& structure,\n    float threshold,\n    bool setDataInside)\n{\n    image<3, float, unique> tmp;\n    create_image(tmp, img.size);\n    set_spatial_mapping(\n        tmp,\n        img.origin,\n        make_vector(img.axes[0][0], img.axes[1][1], img.axes[2][2]));\n    set_value_mapping(\n        tmp, img.value_mapping.intercept, img.value_mapping.slope, img.units);\n\n    auto image_const_view = as_const_view(img);\n    unsigned kk = 0;\n    for (unsigned int k = 0; k < img.size[2]; ++k)\n    {\n        double z = img.origin[2] + img.axes[2][2] * k;\n        for (unsigned int j = 0; j < img.size[1]; ++j)\n        {\n            double y = img.origin[1] + img.axes[1][1] * j;\n            for (unsigned int i = 0; i < img.size[0]; ++i)\n            {\n                double x = img.origin[0] + img.axes[0][0] * i;\n                if (is_inside(structure, make_vector(x, y, z))\n                    == setDataInside)\n                {\n                    tmp.pixels.ptr[kk]\n                        = (image_const_view.pixels[kk] > threshold) ? 0.0f\n                                                                    : 1.0f;\n                }\n                else\n                {\n                    tmp.pixels.ptr[kk] = 0.0f;\n                }\n                ++kk;\n            }\n        }\n    }\n    return share(tmp);\n}\n\nimage<3, double, shared>\nset_data_for_structure(\n    image<3, double, shared> const& img,\n    structure_geometry const& structure,\n    double threshold,\n    bool setDataInside)\n{\n    image<3, double, unique> tmp;\n    create_image(tmp, img.size);\n    set_spatial_mapping(\n        tmp,\n        img.origin,\n        make_vector(img.axes[0][0], img.axes[1][1], img.axes[2][2]));\n    set_value_mapping(\n        tmp, img.value_mapping.intercept, img.value_mapping.slope, img.units);\n\n    auto image_const_view = as_const_view(img);\n    unsigned kk = 0;\n    for (unsigned int k = 0; k < img.size[2]; ++k)\n    {\n        double z = img.origin[2] + img.axes[2][2] * k;\n        for (unsigned int j = 0; j < img.size[1]; ++j)\n        {\n            double y = img.origin[1] + img.axes[1][1] * j;\n            for (unsigned int i = 0; i < img.size[0]; ++i)\n            {\n                double x = img.origin[0] + img.axes[0][0] * i;\n                if (is_inside(structure, make_vector(x, y, z))\n                    == setDataInside)\n                {\n                    tmp.pixels.ptr[kk]\n                        = (image_const_view.pixels[kk] > threshold) ? 0.0\n                                                                    : 1.0;\n                }\n                else\n                {\n                    tmp.pixels.ptr[kk] = 0.0;\n                }\n                ++kk;\n            }\n        }\n    }\n    return share(tmp);\n}\n\n// loading .OBJ files\ntriangle_mesh_with_normals\nload_mesh_from_obj(cradle::file_path const& path)\n{\n    triangle_mesh_with_normals mesh;\n    std::ifstream f;\n    f.open(path.string(), std::ios::in);\n    if (!f)\n    {\n        throw new cradle::file_error(path, \"unable to open OBJ file\");\n        return mesh;\n    }\n    mesh = load_mesh_from_obj(f);\n    f.close();\n    return mesh;\n}\n\n// loading .OBJ files\ntriangle_mesh_with_normals\nload_mesh_from_obj(std::istream& obj)\n{\n    growable_triangle_mesh_with_normals mesh;\n\n    std::string line;\n    while (std::getline(obj, line))\n    {\n        boost::trim_right(line);\n        if (line.c_str()[0] == '#')\n        {\n            // skip comments\n            continue;\n        }\n\n        std::vector<string> tokens;\n        boost::split(\n            tokens, line, boost::is_space(), boost::token_compress_on);\n\n        if (tokens.size())\n        {\n            if (\"v\" == tokens[0])\n            {\n                if (tokens.size() != 4)\n                {\n                    throw cradle::exception(\"Error in OBJ format\");\n                }\n                mesh.vertex_positions.push_back(make_vector(\n                    atof(tokens[1].c_str()),\n                    atof(tokens[2].c_str()),\n                    atof(tokens[3].c_str())));\n            }\n            else if (\"vn\" == tokens[0])\n            {\n                if (tokens.size() != 4)\n                {\n                    throw cradle::exception(\"Error in OBJ format\");\n                }\n                mesh.vertex_normals.push_back(make_vector(\n                    atof(tokens[1].c_str()),\n                    atof(tokens[2].c_str()),\n                    atof(tokens[3].c_str())));\n            }\n            else if (\"f\" == tokens[0])\n            {\n                if (tokens.size() != 4)\n                {\n                    throw new cradle::exception(\"Error in OBJ format\");\n                }\n\n                face3 face_p;\n                face3 face_n = make_vector<int>(-1, -1, -1);\n                for (int i = 1; i < 4; ++i)\n                {\n                    if (tokens[i].find('/'))\n                    {\n                        std::vector<string> vertex_triplet;\n                        boost::split(\n                            vertex_triplet, tokens[i], boost::is_any_of(\"/\"));\n                        if (vertex_triplet.size() != 3)\n                        {\n                            throw new cradle::exception(\"Error in OBJ format\");\n                        }\n                        face_p[i - 1] = atoi(vertex_triplet[0].c_str()) - 1;\n                        face_n[i - 1] = atoi(vertex_triplet[2].c_str()) - 1;\n                    }\n                    else\n                    {\n                        face_p[i - 1] = atoi(tokens[i].c_str()) - 1;\n                    }\n                }\n                mesh.face_position_indices.push_back(face_p);\n                mesh.face_normal_indices.push_back(face_n);\n            }\n            // ignore other kinds of lines\n        }\n    }\n\n    return collapse_mesh(mesh);\n}\n\n// convert triangle_mesh_with_normals to a plain old triangle_mesh\ntriangle_mesh\nremove_normals(triangle_mesh_with_normals const& orig)\n{\n    triangle_mesh mesh;\n    mesh.vertices = orig.vertex_positions;\n    mesh.faces = orig.face_position_indices;\n    return mesh;\n}\n\ntriangle3d\nget_triangle(triangle_mesh const& mesh, face3_array::size_type index)\n{\n    face3 face = mesh.faces[index];\n    return triangle3d(\n        mesh.vertices[face[0]],\n        mesh.vertices[face[1]],\n        mesh.vertices[face[2]]);\n}\n\nvector3d\nget_normal(triangle_mesh const& mesh, face3_array::size_type index)\n{\n    face3 face = mesh.faces[index];\n    vertex3 v0 = mesh.vertices[face[0]];\n    return unit(\n        cross(mesh.vertices[face[1]] - v0, mesh.vertices[face[2]] - v0));\n}\n// calculate the bounds of a triangle mesh\nbox3d\nbounding_box(triangle_mesh const& mesh)\n{\n    if (mesh.vertices.size() < 1)\n    {\n        return cradle::box<3, double>();\n    }\n\n    vertex3_array::const_iterator iter = mesh.vertices.begin();\n    vector3d mins = (*iter);\n    vector3d maxs = (*iter);\n    ++iter;\n    vertex3_array::const_iterator vertices_end = mesh.vertices.end();\n    for (; iter != vertices_end; ++iter)\n    {\n        for (int i = 0; i < 3; ++i)\n        {\n            if ((*iter)[i] < mins[i])\n                mins[i] = (*iter)[i];\n            if ((*iter)[i] > maxs[i])\n                maxs[i] = (*iter)[i];\n        }\n    }\n    return cradle::box<3, double>(mins, maxs - mins);\n}\n\n// calculate the bounds for a face of a triangle mesh\nbox3d\nbounding_box(triangle_mesh const& mesh, face3_array::size_type index)\n{\n    return bounding_box(get_triangle(mesh, index));\n}\n\nstruct sum\n{\n    triangle_mesh const& mesh;\n    line_segment<3, double> const& segment;\n\n    sum(triangle_mesh const& m, line_segment<3, double> const& s)\n        : mesh(m), segment(s)\n    {\n    }\n\n    bool\n    operator()(unsigned const& index, int* value)\n    {\n        segment_triangle_intersection_type type\n            = is_intersecting(segment, get_triangle(mesh, index));\n        if (type == segment_triangle_intersection_type::NONE)\n        {\n            *value = 0;\n            return true;\n        }\n        else if (type == segment_triangle_intersection_type::FACE)\n        {\n            *value = 1;\n            return true;\n        }\n        else\n        {\n            return false;\n        }\n    }\n};\n\ntypedef std::pair<int, int> edge;\n\nedge\nmake_edge(int a, int b)\n{\n    if (a > b)\n    {\n        std::swap(a, b);\n    }\n    return edge(a, b);\n}\n\nstruct edge_state\n{\n    unsigned char state;\n\n    edge_state() : state(0)\n    {\n    }\n\n    void\n    update(bool visible)\n    {\n        if (visible)\n        {\n            ++state;\n        }\n        else\n        {\n            --state;\n        }\n    }\n};\n\nbool\nis_coincident(clipper_point const& p1, clipper_point const& p2)\n{\n    return p1.X == p2.X && p1.Y == p2.Y;\n}\n\ntypedef std::map<edge, edge_state> edge_map;\n\nvoid\nerase_connectivity(\n    unsigned short* connectivity_counts, int** connectivity, int i1, int i2)\n{\n    // Erase connectivity for first index\n    int count1 = connectivity_counts[i1];\n    int* c1 = connectivity[i1];\n    for (int i = 0; i < count1; ++i)\n    {\n        if (*c1 == i2)\n        {\n            *c1 = -1;\n            break;\n        }\n        ++c1;\n    }\n\n    // Erase connectivity for second index\n    int count2 = connectivity_counts[i2];\n    int* c2 = connectivity[i2];\n    for (int i = 0; i < count2; ++i)\n    {\n        if (*c2 == i1)\n        {\n            *c2 = -1;\n            break;\n        }\n        ++c2;\n    }\n}\n\nvector2d\npoint_to_plane(plane<double> const& pl, vector3d const& pt)\n{\n    // Compute reference vector (shortcut)\n    vector3d reference = cross(pl.normal, make_vector(0.0, 0.0, 1.0));\n    if (length2(reference) < 1.0e-20)\n    {\n        reference = cross(pl.normal, make_vector(1.0, 0.0, 0.0));\n    }\n    reference = reference / length(reference);\n    vector3d plU = reference - (dot(reference, pl.normal) * pl.normal);\n    vector3d plV = cross(pl.normal, plU);\n    vector3d v = pt - pl.point;\n    return make_vector<double>(dot(v, plU), dot(v, plV));\n}\n\nbool\ntriangle_segment_intersection(\n    vector3d const& s1,\n    vector3d const& s2,\n    triangle<3, double> const& t,\n    double& u)\n{\n    vector3d normal = cross(t[1] - t[0], t[2] - t[0]);\n\n    plane<double> pl(t[1], normal);\n\n    double dist1 = dot(s1 - pl.point, pl.normal);\n    double dist2 = dot(s2 - pl.point, pl.normal);\n    bool intersects = (dist1 * dist2 < 0);\n    if (!intersects)\n        return false;\n\n    vector2d vp1 = point_to_plane(pl, t[0]);\n    vector2d vp2 = point_to_plane(pl, t[1]);\n    vector2d vp3 = point_to_plane(pl, t[2]);\n\n    u = std::fabs(dist1) / (std::fabs(dist1) + std::fabs(dist2) + 1.0e-20);\n    vector2d vp = point_to_plane(pl, point_along(s1, s2, u));\n\n    vector2d d1 = vp2 - vp1;\n    vector2d d2 = vp3 - vp1;\n\n    double denom = cross(d1, d2);\n    if (denom == 0.0)\n    {\n        return false;\n    }\n\n    double numer1 = cross(vp, d2) - cross(vp1, d2);\n    double a = numer1 / denom;\n    if (a < -1.0e-12)\n        return false;\n\n    double numer2 = cross(vp1, d1) - cross(vp, d1);\n    double b = numer2 / denom;\n    if (b < -1.0e-12)\n        return false; // I believe there may be a problem in this computation\n                      // somewhere - Sal (02.09.2009)\n\n    double sum = a + b;\n    if (sum > (1.0 + 1.0e-12))\n        return false;\n\n    return true;\n}\n\nbool\nget_first_last_intersection(\n    vector3d const& s1,\n    vector3d const& s2,\n    std::vector<triangle_mesh> const& targets,\n    vector3d& pt1,\n    vector3d& pt2,\n    double& uu1,\n    double& uu2)\n{\n    double u1 = 1.0e100;\n    double u2 = -1.0e100;\n    for (size_t i = 0; i < targets.size(); ++i)\n    {\n        for (size_t j = 0; j < targets[i].faces.size(); ++j)\n        {\n            double temp_u = 0.0;\n            bool isIntersected = triangle_segment_intersection(\n                s1, s2, get_triangle(targets[i], j), temp_u);\n            if (isIntersected)\n            {\n                if (temp_u < u1)\n                {\n                    u1 = temp_u;\n                }\n                if (temp_u > u2)\n                {\n                    u2 = temp_u;\n                }\n            }\n            // if (isIntersected) std::cout << \"Intersect: \" << temp_u << \" \"\n            // << u << std::endl;\n        }\n    }\n    if (u2 > 0.0)\n    {\n        pt1 = point_along(s1, s2, u1);\n        pt2 = point_along(s1, s2, u2);\n        uu1 = u1;\n        uu2 = u2;\n        return true;\n    }\n    return false;\n}\n\nbool\nget_first_last_intersection(\n    vector3d const& s1,\n    vector3d const& s2,\n    triangle_mesh const& mesh,\n    vector3d& pt1,\n    vector3d& pt2,\n    double& uu1,\n    double& uu2)\n{\n    double u1 = 1.0e100;\n    double u2 = -1.0e100;\n    for (size_t j = 0; j < mesh.faces.size(); ++j)\n    {\n        double temp_u = 0.0;\n        bool isIntersected = triangle_segment_intersection(\n            s1, s2, get_triangle(mesh, j), temp_u);\n        if (isIntersected)\n        {\n            if (temp_u < u1)\n            {\n                u1 = temp_u;\n            }\n            if (temp_u > u2)\n            {\n                u2 = temp_u;\n            }\n        }\n    }\n    if (u2 > 0.0)\n    {\n        pt1 = point_along(s1, s2, u1);\n        pt2 = point_along(s1, s2, u2);\n        uu1 = u1;\n        uu2 = u2;\n        return true;\n    }\n    return false;\n}\n\nbool\nget_deepest_intersection(\n    vector3d const& s1,\n    vector3d const& s2,\n    std::vector<triangle_mesh> const& targets,\n    vector3d& pt,\n    double& uu)\n{\n    double u = 0.0;\n    for (size_t i = 0; i < targets.size(); ++i)\n    {\n        for (size_t j = 0; j < targets[i].faces.size(); ++j)\n        {\n            double temp_u = 0.0;\n            bool isIntersected = triangle_segment_intersection(\n                s1, s2, get_triangle(targets[i], j), temp_u);\n            if (isIntersected && (temp_u > u))\n            {\n                u = temp_u;\n            }\n            // if (isIntersected) std::cout << \"Intersect: \" << temp_u << \" \"\n            // << u << std::endl;\n        }\n    }\n    if (u > 0.0)\n    {\n        pt = point_along(s1, s2, u);\n        uu = u;\n        return true;\n    }\n    return false;\n}\n\ndouble\ncompute_solid_angle(triangle_mesh const& mesh, vector3d const& p)\n{\n    double ang = 0.0;\n    face3_array::const_iterator end = mesh.faces.end();\n    for (face3_array::const_iterator iter = mesh.faces.begin(); iter != end;\n         ++iter)\n    {\n        // Get triangle\n        vector3d a = mesh.vertices[(*iter)[0]] - p;\n        vector3d b = mesh.vertices[(*iter)[1]] - p;\n        vector3d c = mesh.vertices[(*iter)[2]] - p;\n\n        double alength = length(a);\n        double blength = length(b);\n        double clength = length(c);\n\n        double numer = dot(a, cross(b, c));\n        double denom = (alength * blength * clength) + clength * dot(a, b)\n                       + blength * dot(a, c) + alength * dot(b, c);\n\n        ang += std::atan2(numer, denom);\n    }\n    return 2.0 * ang;\n}\n\n// transforms the vertices in a triangle mesh\n// (leaves the original alone and creates a transformed COPY)\ntriangle_mesh\ntransform_triangle_mesh(\n    const triangle_mesh& original, const matrix<4, 4, double>& matrix)\n{\n    triangle_mesh output_mesh;\n    output_mesh.faces = original.faces;\n    auto n_vertices = original.vertices.size();\n    auto output_vertices = allocate(&output_mesh.vertices, n_vertices);\n    for (size_t i = 0; i != n_vertices; ++i)\n        output_vertices[i] = transform_point(matrix, original.vertices[i]);\n    return output_mesh;\n}\n\ntriangle_mesh_with_normals\ntransform_triangle_mesh(\n    triangle_mesh_with_normals const& original,\n    matrix<4, 4, double> const& matrix)\n{\n    triangle_mesh_with_normals output_mesh;\n\n    {\n        output_mesh.face_position_indices = original.face_position_indices;\n        auto n_vertices = original.vertex_positions.size();\n        auto output_vertices\n            = allocate(&output_mesh.vertex_positions, n_vertices);\n        for (size_t i = 0; i != n_vertices; ++i)\n        {\n            output_vertices[i]\n                = transform_point(matrix, original.vertex_positions[i]);\n        }\n    }\n\n    {\n        output_mesh.face_normal_indices = original.face_normal_indices;\n        auto n_normals = original.vertex_normals.size();\n        auto output_normals = allocate(&output_mesh.vertex_normals, n_normals);\n        for (size_t i = 0; i != n_normals; ++i)\n        {\n            output_normals[i]\n                = transform_vector(matrix, original.vertex_normals[i]);\n        }\n    }\n\n    return output_mesh;\n}\n\n} // namespace cradle\n", "meta": {"hexsha": "163fcffb5b2d97c026432ae3589da5eba6a393ff", "size": 29151, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/cradle/geometry/meshing.cpp", "max_stars_repo_name": "mghro/astroid-core", "max_stars_repo_head_hexsha": "72736f64bed19ec3bb0e92ebee4d7cf09fc0399f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/cradle/geometry/meshing.cpp", "max_issues_repo_name": "mghro/astroid-core", "max_issues_repo_head_hexsha": "72736f64bed19ec3bb0e92ebee4d7cf09fc0399f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2020-10-26T18:45:47.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-26T18:46:06.000Z", "max_forks_repo_path": "src/cradle/geometry/meshing.cpp", "max_forks_repo_name": "mghro/astroid-core", "max_forks_repo_head_hexsha": "72736f64bed19ec3bb0e92ebee4d7cf09fc0399f", "max_forks_repo_licenses": ["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.8178472861, "max_line_length": 79, "alphanum_fraction": 0.5230009262, "num_tokens": 8134, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6442251064863697, "lm_q2_score": 0.47657965106367595, "lm_q1q2_score": 0.30702457645573356}}
{"text": "//  (C) Copyright Jeremy William Murphy 2016.\n\n//  Use, modification and distribution are subject to the\n//  Boost Software License, Version 1.0. (See accompanying file\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n#ifndef BOOST_MATH_COMMON_FACTOR_RT_HPP\n#define BOOST_MATH_COMMON_FACTOR_RT_HPP\n\n#include <boost/assert.hpp>\n#include <boost/core/enable_if.hpp>\n#include <boost/mpl/and.hpp>\n#include <boost/type_traits.hpp>\n\n#include <boost/config.hpp>  // for BOOST_NESTED_TEMPLATE, etc.\n#include <boost/limits.hpp>  // for std::numeric_limits\n#include <climits>           // for CHAR_MIN\n#include <boost/detail/workaround.hpp>\n#include <iterator>\n#include <algorithm>\n#include <limits>\n\n#if (defined(BOOST_MSVC) || (defined(__clang__) && defined(__c2__)) || (defined(BOOST_INTEL) && defined(_MSC_VER))) && (defined(_M_IX86) || defined(_M_X64))\n#include <intrin.h>\n#endif\n\n#ifdef BOOST_MSVC\n#pragma warning(push)\n#pragma warning(disable:4127 4244)  // Conditional expression is constant\n#endif\n\nnamespace boost {\n   namespace math {\n\n      template <class T, bool a = is_unsigned<T>::value || (std::numeric_limits<T>::is_specialized && !std::numeric_limits<T>::is_signed)>\n      struct gcd_traits_abs_defaults\n      {\n         inline static const T& abs(const T& val) { return val; }\n      };\n      template <class T>\n      struct gcd_traits_abs_defaults<T, false>\n      {\n         inline static T abs(const T& val)\n         {\n            using std::abs;\n            return abs(val);\n         }\n      };\n\n      template <class T>\n      struct gcd_traits_defaults : public gcd_traits_abs_defaults<T>\n      {\n         BOOST_FORCEINLINE static unsigned make_odd(T& val)\n         {\n            unsigned r = 0;\n            while(!(val & 1u))\n            {\n               val >>= 1;\n               ++r;\n            }\n            return r;\n         }\n         inline static bool less(const T& a, const T& b)\n         {\n            return a < b;\n         }\n\n         enum method_type\n         {\n            method_euclid = 0,\n            method_binary = 1,\n            method_mixed = 2,\n         };\n\n         static const method_type method =\n            boost::has_right_shift_assign<T>::value && boost::has_left_shift_assign<T>::value && boost::has_less<T>::value && boost::has_modulus<T>::value\n            ? method_mixed :\n            boost::has_right_shift_assign<T>::value && boost::has_left_shift_assign<T>::value && boost::has_less<T>::value\n            ? method_binary : method_euclid;\n      };\n      //\n      // Default gcd_traits just inherits from defaults:\n      //\n      template <class T>\n      struct gcd_traits : public gcd_traits_defaults<T> {};\n      //\n      // Special handling for polynomials:\n      //\n      namespace tools {\n         template <class T>\n         class polynomial;\n      }\n\n      template <class T>\n      struct gcd_traits<boost::math::tools::polynomial<T> > : public gcd_traits_defaults<T>\n      {\n         static const boost::math::tools::polynomial<T>& abs(const boost::math::tools::polynomial<T>& val) { return val; }\n      };\n      //\n      // Some platforms have fast bitscan operations, that allow us to implement\n      // make_odd much more efficiently:\n      //\n#if (defined(BOOST_MSVC) || (defined(__clang__) && defined(__c2__)) || (defined(BOOST_INTEL) && defined(_MSC_VER))) && (defined(_M_IX86) || defined(_M_X64))\n#pragma intrinsic(_BitScanForward,)\n      template <>\n      struct gcd_traits<unsigned long> : public gcd_traits_defaults<unsigned long>\n      {\n         BOOST_FORCEINLINE static unsigned find_lsb(unsigned long val)\n         {\n            unsigned long result;\n            _BitScanForward(&result, val);\n            return result;\n         }\n         BOOST_FORCEINLINE static unsigned make_odd(unsigned long& val)\n         {\n            unsigned result = find_lsb(val);\n            val >>= result;\n            return result;\n         }\n      };\n\n#ifdef _M_X64\n#pragma intrinsic(_BitScanForward64)\n      template <>\n      struct gcd_traits<unsigned __int64> : public gcd_traits_defaults<unsigned __int64>\n      {\n         BOOST_FORCEINLINE static unsigned find_lsb(unsigned __int64 mask)\n         {\n            unsigned long result;\n            _BitScanForward64(&result, mask);\n            return result;\n         }\n         BOOST_FORCEINLINE static unsigned make_odd(unsigned __int64& val)\n         {\n            unsigned result = find_lsb(val);\n            val >>= result;\n            return result;\n         }\n      };\n#endif\n      //\n      // Other integer type are trivial adaptations of the above,\n      // this works for signed types too, as by the time these functions\n      // are called, all values are > 0.\n      //\n      template <> struct gcd_traits<long> : public gcd_traits_defaults<long> \n      { BOOST_FORCEINLINE static unsigned make_odd(long& val){ unsigned result = gcd_traits<unsigned long>::find_lsb(val); val >>= result; return result; } };\n      template <> struct gcd_traits<unsigned int> : public gcd_traits_defaults<unsigned int> \n      { BOOST_FORCEINLINE static unsigned make_odd(unsigned int& val){ unsigned result = gcd_traits<unsigned long>::find_lsb(val); val >>= result; return result; } };\n      template <> struct gcd_traits<int> : public gcd_traits_defaults<int> \n      { BOOST_FORCEINLINE static unsigned make_odd(int& val){ unsigned result = gcd_traits<unsigned long>::find_lsb(val); val >>= result; return result; } };\n      template <> struct gcd_traits<unsigned short> : public gcd_traits_defaults<unsigned short> \n      { BOOST_FORCEINLINE static unsigned make_odd(unsigned short& val){ unsigned result = gcd_traits<unsigned long>::find_lsb(val); val >>= result; return result; } };\n      template <> struct gcd_traits<short> : public gcd_traits_defaults<short> \n      { BOOST_FORCEINLINE static unsigned make_odd(short& val){ unsigned result = gcd_traits<unsigned long>::find_lsb(val); val >>= result; return result; } };\n      template <> struct gcd_traits<unsigned char> : public gcd_traits_defaults<unsigned char> \n      { BOOST_FORCEINLINE static unsigned make_odd(unsigned char& val){ unsigned result = gcd_traits<unsigned long>::find_lsb(val); val >>= result; return result; } };\n      template <> struct gcd_traits<signed char> : public gcd_traits_defaults<signed char> \n      { BOOST_FORCEINLINE static signed make_odd(signed char& val){ signed result = gcd_traits<unsigned long>::find_lsb(val); val >>= result; return result; } };\n      template <> struct gcd_traits<char> : public gcd_traits_defaults<char> \n      { BOOST_FORCEINLINE static unsigned make_odd(char& val){ unsigned result = gcd_traits<unsigned long>::find_lsb(val); val >>= result; return result; } };\n      template <> struct gcd_traits<wchar_t> : public gcd_traits_defaults<wchar_t> \n      { BOOST_FORCEINLINE static unsigned make_odd(wchar_t& val){ unsigned result = gcd_traits<unsigned long>::find_lsb(val); val >>= result; return result; } };\n#ifdef _M_X64\n      template <> struct gcd_traits<__int64> : public gcd_traits_defaults<__int64> \n      { BOOST_FORCEINLINE static unsigned make_odd(__int64& val){ unsigned result = gcd_traits<unsigned __int64>::find_lsb(val); val >>= result; return result; } };\n#endif\n\n#elif defined(BOOST_GCC) || defined(__clang__) || (defined(BOOST_INTEL) && defined(__GNUC__))\n\n      template <>\n      struct gcd_traits<unsigned> : public gcd_traits_defaults<unsigned>\n      {\n         BOOST_FORCEINLINE static unsigned find_lsb(unsigned mask)\n         {\n            return __builtin_ctz(mask);\n         }\n         BOOST_FORCEINLINE static unsigned make_odd(unsigned& val)\n         {\n            unsigned result = find_lsb(val);\n            val >>= result;\n            return result;\n         }\n      };\n      template <>\n      struct gcd_traits<unsigned long> : public gcd_traits_defaults<unsigned long>\n      {\n         BOOST_FORCEINLINE static unsigned find_lsb(unsigned long mask)\n         {\n            return __builtin_ctzl(mask);\n         }\n         BOOST_FORCEINLINE static unsigned make_odd(unsigned long& val)\n         {\n            unsigned result = find_lsb(val);\n            val >>= result;\n            return result;\n         }\n      };\n      template <>\n      struct gcd_traits<boost::ulong_long_type> : public gcd_traits_defaults<boost::ulong_long_type>\n      {\n         BOOST_FORCEINLINE static unsigned find_lsb(boost::ulong_long_type mask)\n         {\n            return __builtin_ctzll(mask);\n         }\n         BOOST_FORCEINLINE static unsigned make_odd(boost::ulong_long_type& val)\n         {\n            unsigned result = find_lsb(val);\n            val >>= result;\n            return result;\n         }\n      };\n      //\n      // Other integer type are trivial adaptations of the above,\n      // this works for signed types too, as by the time these functions\n      // are called, all values are > 0.\n      //\n      template <> struct gcd_traits<boost::long_long_type> : public gcd_traits_defaults<boost::long_long_type>\n      {\n         BOOST_FORCEINLINE static unsigned make_odd(boost::long_long_type& val) { unsigned result = gcd_traits<boost::ulong_long_type>::find_lsb(val); val >>= result; return result; }\n      };\n      template <> struct gcd_traits<long> : public gcd_traits_defaults<long>\n      {\n         BOOST_FORCEINLINE static unsigned make_odd(long& val) { unsigned result = gcd_traits<unsigned long>::find_lsb(val); val >>= result; return result; }\n      };\n      template <> struct gcd_traits<int> : public gcd_traits_defaults<int>\n      {\n         BOOST_FORCEINLINE static unsigned make_odd(int& val) { unsigned result = gcd_traits<unsigned long>::find_lsb(val); val >>= result; return result; }\n      };\n      template <> struct gcd_traits<unsigned short> : public gcd_traits_defaults<unsigned short>\n      {\n         BOOST_FORCEINLINE static unsigned make_odd(unsigned short& val) { unsigned result = gcd_traits<unsigned>::find_lsb(val); val >>= result; return result; }\n      };\n      template <> struct gcd_traits<short> : public gcd_traits_defaults<short>\n      {\n         BOOST_FORCEINLINE static unsigned make_odd(short& val) { unsigned result = gcd_traits<unsigned>::find_lsb(val); val >>= result; return result; }\n      };\n      template <> struct gcd_traits<unsigned char> : public gcd_traits_defaults<unsigned char>\n      {\n         BOOST_FORCEINLINE static unsigned make_odd(unsigned char& val) { unsigned result = gcd_traits<unsigned>::find_lsb(val); val >>= result; return result; }\n      };\n      template <> struct gcd_traits<signed char> : public gcd_traits_defaults<signed char>\n      {\n         BOOST_FORCEINLINE static signed make_odd(signed char& val) { signed result = gcd_traits<unsigned>::find_lsb(val); val >>= result; return result; }\n      };\n      template <> struct gcd_traits<char> : public gcd_traits_defaults<char>\n      {\n         BOOST_FORCEINLINE static unsigned make_odd(char& val) { unsigned result = gcd_traits<unsigned>::find_lsb(val); val >>= result; return result; }\n      };\n      template <> struct gcd_traits<wchar_t> : public gcd_traits_defaults<wchar_t>\n      {\n         BOOST_FORCEINLINE static unsigned make_odd(wchar_t& val) { unsigned result = gcd_traits<unsigned>::find_lsb(val); val >>= result; return result; }\n      };\n#endif\n\nnamespace detail\n{\n    \n   //\n   // The Mixed Binary Euclid Algorithm\n   // Sidi Mohamed Sedjelmaci\n   // Electronic Notes in Discrete Mathematics 35 (2009) 169-176\n   //\n   template <class T>\n   T mixed_binary_gcd(T u, T v)\n   {\n      using std::swap;\n      if(gcd_traits<T>::less(u, v))\n         swap(u, v);\n\n      unsigned shifts = 0;\n\n      if(!u)\n         return v;\n      if(!v)\n         return u;\n\n      shifts = (std::min)(gcd_traits<T>::make_odd(u), gcd_traits<T>::make_odd(v));\n\n      while(gcd_traits<T>::less(1, v))\n      {\n         u %= v;\n         v -= u;\n         if(!u)\n            return v << shifts;\n         if(!v)\n            return u << shifts;\n         gcd_traits<T>::make_odd(u);\n         gcd_traits<T>::make_odd(v);\n         if(gcd_traits<T>::less(u, v))\n            swap(u, v);\n      }\n      return (v == 1 ? v : u) << shifts;\n   }\n\n    /** Stein gcd (aka 'binary gcd')\n     * \n     * From Mathematics to Generic Programming, Alexander Stepanov, Daniel Rose\n     */\n    template <typename SteinDomain>\n    SteinDomain Stein_gcd(SteinDomain m, SteinDomain n)\n    {\n        using std::swap;\n        BOOST_ASSERT(m >= 0);\n        BOOST_ASSERT(n >= 0);\n        if (m == SteinDomain(0))\n            return n;\n        if (n == SteinDomain(0))\n            return m;\n        // m > 0 && n > 0\n        int d_m = gcd_traits<SteinDomain>::make_odd(m);\n        int d_n = gcd_traits<SteinDomain>::make_odd(n);\n        // odd(m) && odd(n)\n        while (m != n)\n        {\n            if (n > m)\n                swap(n, m);\n            m -= n;\n            gcd_traits<SteinDomain>::make_odd(m);\n        }\n        // m == n\n        m <<= (std::min)(d_m, d_n);\n        return m;\n    }\n\n    \n    /** Euclidean algorithm\n     * \n     * From Mathematics to Generic Programming, Alexander Stepanov, Daniel Rose\n     * \n     */\n    template <typename EuclideanDomain>\n    inline EuclideanDomain Euclid_gcd(EuclideanDomain a, EuclideanDomain b)\n    {\n        using std::swap;\n        while (b != EuclideanDomain(0))\n        {\n            a %= b;\n            swap(a, b);\n        }\n        return a;\n    }\n\n\n    template <typename T>\n    inline BOOST_DEDUCED_TYPENAME enable_if_c<gcd_traits<T>::method == gcd_traits<T>::method_mixed, T>::type\n       optimal_gcd_select(T const &a, T const &b)\n    {\n       return detail::mixed_binary_gcd(a, b);\n    }\n\n    template <typename T>\n    inline BOOST_DEDUCED_TYPENAME enable_if_c<gcd_traits<T>::method == gcd_traits<T>::method_binary, T>::type\n       optimal_gcd_select(T const &a, T const &b)\n    {\n       return detail::Stein_gcd(a, b);\n    }\n\n    template <typename T>\n    inline BOOST_DEDUCED_TYPENAME enable_if_c<gcd_traits<T>::method == gcd_traits<T>::method_euclid, T>::type\n       optimal_gcd_select(T const &a, T const &b)\n    {\n       return detail::Euclid_gcd(a, b);\n    }\n\n    template <class T>\n    inline T lcm_imp(const T& a, const T& b)\n    {\n       T temp = boost::math::detail::optimal_gcd_select(a, b);\n#if BOOST_WORKAROUND(BOOST_GCC_VERSION, < 40500)\n       return (temp != T(0)) ? T(a / temp * b) : T(0);\n#else\n       return temp ? T(a / temp * b) : T(0);\n#endif\n    }\n\n} // namespace detail\n\n\ntemplate <typename Integer>\ninline Integer gcd(Integer const &a, Integer const &b)\n{\n    return detail::optimal_gcd_select(static_cast<Integer>(gcd_traits<Integer>::abs(a)), static_cast<Integer>(gcd_traits<Integer>::abs(b)));\n}\n\ntemplate <typename Integer>\ninline Integer lcm(Integer const &a, Integer const &b)\n{\n   return detail::lcm_imp(static_cast<Integer>(gcd_traits<Integer>::abs(a)), static_cast<Integer>(gcd_traits<Integer>::abs(b)));\n}\n\n/**\n * Knuth, The Art of Computer Programming: Volume 2, Third edition, 1998\n * Chapter 4.5.2, Algorithm C: Greatest common divisor of n integers.\n *\n * Knuth counts down from n to zero but we naturally go from first to last.\n * We also return the termination position because it might be useful to know.\n * \n * Partly by quirk, partly by design, this algorithm is defined for n = 1, \n * because the gcd of {x} is x. It is not defined for n = 0.\n * \n * @tparam  I   Input iterator.\n * @return  The gcd of the range and the iterator position at termination.\n */\ntemplate <typename I>\nstd::pair<typename std::iterator_traits<I>::value_type, I>\ngcd_range(I first, I last)\n{\n    BOOST_ASSERT(first != last);\n    typedef typename std::iterator_traits<I>::value_type T;\n    \n    T d = *first++;\n    while (d != T(1) && first != last)\n    {\n        d = gcd(d, *first);\n        first++;\n    }\n    return std::make_pair(d, first);\n}\n\n}  // namespace math\n}  // namespace boost\n\n#ifdef BOOST_MSVC\n#pragma warning(pop)\n#endif\n\n#endif  // BOOST_MATH_COMMON_FACTOR_RT_HPP\n", "meta": {"hexsha": "acde21d2c845c8b750495a2b70e43744f6789174", "size": 15921, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/math/common_factor_rt.hpp", "max_stars_repo_name": "ZCube/boost-cmake", "max_stars_repo_head_hexsha": "f1eca5534ab6c9bc89cf7ee4670f056503b7ba86", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 156.0, "max_stars_repo_stars_event_min_datetime": "2016-12-14T07:54:55.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-06T10:16:27.000Z", "max_issues_repo_path": "ios/Pods/boost-for-react-native/boost/math/common_factor_rt.hpp", "max_issues_repo_name": "c7yrus/alyson-v3", "max_issues_repo_head_hexsha": "5ad95a8f782f5f5d2fd543d44ca6a8b093395965", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 28.0, "max_issues_repo_issues_event_min_datetime": "2016-10-16T19:42:37.000Z", "max_issues_repo_issues_event_max_datetime": "2018-09-14T21:29:48.000Z", "max_forks_repo_path": "ios/Pods/boost-for-react-native/boost/math/common_factor_rt.hpp", "max_forks_repo_name": "c7yrus/alyson-v3", "max_forks_repo_head_hexsha": "5ad95a8f782f5f5d2fd543d44ca6a8b093395965", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 35.0, "max_forks_repo_forks_event_min_datetime": "2016-11-25T14:39:33.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-15T11:06:57.000Z", "avg_line_length": 37.1118881119, "max_line_length": 183, "alphanum_fraction": 0.629169022, "num_tokens": 3705, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6442251064863697, "lm_q2_score": 0.47657965106367595, "lm_q1q2_score": 0.30702457645573356}}
{"text": "/* -*- c++ -*- */\n/*\n * Copyright 2010-2012,2014 Free Software Foundation, Inc.\n *\n * This file is part of GNU Radio\n *\n * GNU Radio is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 3, or (at your option)\n * any later version.\n *\n * GNU Radio is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with GNU Radio; see the file COPYING.  If not, write to\n * the Free Software Foundation, Inc., 51 Franklin Street,\n * Boston, MA 02110-1301, USA.\n */\n\n#ifdef HAVE_CONFIG_H\n#include \"config.h\"\n#endif\n\n#include <gnuradio/io_signature.h>\n#include <gnuradio/digital/constellation.h>\n#include <gnuradio/math.h>\n#include <gnuradio/gr_complex.h>\n#include <cstdlib>\n#include <cfloat>\n#include <stdexcept>\n#include <boost/format.hpp>\n#include <iostream>\n\nnamespace gr {\n  namespace digital {\n\n#define M_TWOPI (2*M_PI)\n#define SQRT_TWO 0.707107\n\n    // Base Constellation Class\n    constellation::constellation(std::vector<gr_complex> constell,\n                                 std::vector<int> pre_diff_code,\n                                 unsigned int rotational_symmetry,\n                                 unsigned int dimensionality\n    ) :\n      d_constellation(constell),\n      d_pre_diff_code(pre_diff_code),\n      d_rotational_symmetry(rotational_symmetry),\n      d_dimensionality(dimensionality),\n      d_re_min(1e20),\n      d_re_max(1e20),\n      d_im_min(1e20),\n      d_im_max(1e20),\n      d_lut_precision(0),\n      d_lut_scale(0)\n    {\n      // Scale constellation points so that average magnitude is 1.\n      float summed_mag = 0;\n      unsigned int constsize = d_constellation.size();\n      for (unsigned int i=0; i<constsize; i++) {\n        gr_complex c = d_constellation[i];\n        summed_mag += sqrt(c.real()*c.real() + c.imag()*c.imag());\n      }\n      d_scalefactor = constsize/summed_mag;\n      for (unsigned int i=0; i<constsize; i++) {\n        d_constellation[i] = d_constellation[i]*d_scalefactor;\n      }\n      if(pre_diff_code.size() == 0)\n        d_apply_pre_diff_code = false;\n      else if(pre_diff_code.size() != constsize)\n        throw std::runtime_error(\n          \"The constellation and pre-diff code must be of the same length.\");\n      else\n        d_apply_pre_diff_code = true;\n      calc_arity();\n    }\n\n    constellation::constellation() :\n      d_apply_pre_diff_code(false),\n      d_rotational_symmetry(0),\n      d_dimensionality(1),\n      d_scalefactor(1.0),\n      d_re_min(1e20),\n      d_re_max(1e20),\n      d_im_min(1e20),\n      d_im_max(1e20),\n      d_lut_precision(0.0),\n      d_lut_scale(0.0)\n    {\n      calc_arity();\n    }\n\n    constellation::~constellation()\n    {\n    }\n\n    //! Returns the constellation points for a symbol value\n    void\n    constellation::map_to_points(unsigned int value, gr_complex *points)\n    {\n      for(unsigned int i=0; i<d_dimensionality; i++)\n        points[i] = d_constellation[value*d_dimensionality + i];\n    }\n\n    std::vector<gr_complex>\n    constellation::map_to_points_v(unsigned int value)\n    {\n      std::vector<gr_complex> points_v;\n      points_v.resize(d_dimensionality);\n      map_to_points(value, &(points_v[0]));\n      return points_v;\n    }\n\n    float\n    constellation::get_distance(unsigned int index, const gr_complex *sample)\n    {\n      float dist = 0;\n      for(unsigned int i=0; i<d_dimensionality; i++) {\n        dist += norm(sample[i] - d_constellation[index*d_dimensionality + i]);\n      }\n      return dist;\n    }\n\n    unsigned int\n    constellation::get_closest_point(const gr_complex *sample)\n    {\n      unsigned int min_index = 0;\n      float min_euclid_dist;\n      float euclid_dist;\n\n      min_euclid_dist = get_distance(0, sample);\n      min_index = 0;\n      for(unsigned int j = 1; j < d_arity; j++){\n        euclid_dist = get_distance(j, sample);\n        if(euclid_dist < min_euclid_dist){\n          min_euclid_dist = euclid_dist;\n          min_index = j;\n        }\n      }\n      return min_index;\n    }\n\n    unsigned int\n    constellation::decision_maker_pe(const gr_complex *sample,\n                                     float *phase_error)\n    {\n      unsigned int index = decision_maker(sample);\n      *phase_error = 0;\n      for(unsigned int d=0; d<d_dimensionality; d++)\n        *phase_error += -arg(sample[d]*conj(d_constellation[index+d]));\n      return index;\n    }\n\n    std::vector<gr_complex> constellation::s_points()\n    {\n      if(d_dimensionality != 1)\n        throw std::runtime_error(\n          \"s_points only works for dimensionality 1 constellations.\");\n      else\n        return d_constellation;\n    }\n\n    std::vector<std::vector<gr_complex> >\n    constellation::v_points()\n    {\n      std::vector<std::vector<gr_complex> > vv_const;\n      vv_const.resize(d_arity);\n      for(unsigned int p=0; p<d_arity; p++) {\n        std::vector<gr_complex> v_const;\n        v_const.resize(d_dimensionality);\n        for(unsigned int d=0; d<d_dimensionality; d++) {\n          v_const[d] = d_constellation[p*d_dimensionality+d];\n        }\n        vv_const[p] = v_const;\n      }\n      return vv_const;\n    }\n\n    void\n    constellation::calc_metric(const gr_complex *sample, float *metric,\n                               trellis_metric_type_t type)\n    {\n      switch(type){\n      case TRELLIS_EUCLIDEAN:\n        calc_euclidean_metric(sample, metric);\n        break;\n      case TRELLIS_HARD_SYMBOL:\n        calc_hard_symbol_metric(sample, metric);\n        break;\n      case TRELLIS_HARD_BIT:\n        throw std::runtime_error(\"Invalid metric type (not yet implemented).\");\n        break;\n      default:\n        throw std::runtime_error(\"Invalid metric type.\");\n      }\n    }\n\n    void\n    constellation::calc_euclidean_metric(const gr_complex *sample,\n                                         float *metric)\n    {\n      for(unsigned int o=0; o<d_arity; o++) {\n        metric[o] = get_distance(o, sample);\n      }\n    }\n\n    void\n    constellation::calc_hard_symbol_metric(const gr_complex *sample,\n                                           float *metric)\n    {\n      float minm = FLT_MAX;\n      unsigned int minmi = 0;\n      for(unsigned int o=0; o<d_arity; o++) {\n        float dist = get_distance(o, sample);\n        if(dist < minm) {\n          minm = dist;\n          minmi = o;\n        }\n      }\n      for(unsigned int o=0; o<d_arity; o++) {\n        metric[o] = (o==minmi?0.0:1.0);\n      }\n    }\n\n    void\n    constellation::calc_arity()\n    {\n      if(d_constellation.size() % d_dimensionality != 0)\n        throw std::runtime_error(\n          \"Constellation vector size must be a multiple of the dimensionality.\");\n      d_arity = d_constellation.size()/d_dimensionality;\n    }\n\n    unsigned int\n    constellation::decision_maker_v(std::vector<gr_complex> sample)\n    {\n      assert(sample.size() == d_dimensionality);\n      return decision_maker(&(sample[0]));\n    }\n\n\n    void\n    constellation::gen_soft_dec_lut(int precision, float npwr)\n    {\n      d_soft_dec_lut.clear();\n      d_lut_scale = powf(2.0f, static_cast<float>(precision));\n\n      // We know we've normalized the constellation, so the min/max\n      // dimensions in either direction are scaled to +/-1.\n      float maxd = 1.0f;\n      float step = (2.0f*maxd) / (d_lut_scale-1);\n      float y = -maxd;\n      while(y < maxd+step) {\n        float x = -maxd;\n        while(x < maxd+step) {\n          gr_complex pt = gr_complex(x, y);\n          d_soft_dec_lut.push_back(calc_soft_dec(pt, npwr));\n          x += step;\n        }\n        y += step;\n      }\n\n      d_lut_precision = precision;\n    }\n\n    std::vector<float>\n    constellation::calc_soft_dec(gr_complex sample, float npwr)\n    {\n      int v;\n      int M = static_cast<int>(d_constellation.size());\n      int k = static_cast<int>(log(static_cast<double>(M))/log(2.0));\n      std::vector<float> tmp(2*k, 0);\n      std::vector<float> s(k, 0);\n\n      for(int i = 0; i < M; i++) {\n        // Calculate the distance between the sample and the current\n        // constellation point.\n        float dist = std::abs(sample - d_constellation[i]);\n        // Calculate the probability factor from the distance and\n        // the scaled noise power.\n        float d = expf(-dist/npwr);\n\n        if(d_apply_pre_diff_code)\n          v = d_pre_diff_code[i];\n        else\n          v = i;\n\n        for(int j = 0; j < k; j++) {\n          // Get the bit at the jth index\n          int mask = 1 << j;\n          int bit = (v & mask) >> j;\n\n          // If the bit is a 0, add to the probability of a zero\n          if(bit == 0)\n            tmp[2*j+0] += d;\n          // else, add to the probability of a one\n          else\n            tmp[2*j+1] += d;\n        }\n      }\n\n      // Calculate the log-likelihood ratio for all bits based on the\n      // probability of ones (tmp[2*i+1]) over the probability of a zero\n      // (tmp[2*i+0]).\n      for(int i = 0; i < k; i++) {\n        s[k-1-i] = (logf(tmp[2*i+1]) - logf(tmp[2*i+0]));\n      }\n\n      return s;\n    }\n\n    void\n    constellation::set_soft_dec_lut(const std::vector< std::vector<float> > &soft_dec_lut,\n                                    int precision)\n    {\n      max_min_axes();\n\n      d_soft_dec_lut = soft_dec_lut;\n      d_lut_precision = precision;\n      d_lut_scale = powf(2.0, static_cast<float>(precision));\n    }\n\n    bool\n    constellation::has_soft_dec_lut()\n    {\n      return d_soft_dec_lut.size() > 0;\n    }\n\n    std::vector< std::vector<float> >\n    constellation::soft_dec_lut()\n    {\n      return d_soft_dec_lut;\n    }\n\n    std::vector<float>\n    constellation::soft_decision_maker(gr_complex sample)\n    {\n      if(has_soft_dec_lut()) {\n        // Clip to just below 1 --> at 1, we can overflow the index\n        // that will put us in the next row of the 2D LUT.\n        float xre = branchless_clip(sample.real(), 0.99);\n        float xim = branchless_clip(sample.imag(), 0.99);\n\n        // We normalize the constellation in the ctor, so we know that\n        // the maximum dimensions go from -1 to +1. We can infer the x\n        // and y scale directly.\n        float scale = d_lut_scale / (2.0f);\n\n        // Convert the clipped x and y samples to nearest index offset\n        xre = floorf((1.0f + xre) * scale);\n        xim = floorf((1.0f + xim) * scale);\n        int index = static_cast<int>(d_lut_scale*xim + xre);\n\n        int max_index = d_lut_scale*d_lut_scale;\n\n        // Make sure we are in bounds of the index\n        while(index >= max_index) {\n          index -= d_lut_scale;\n        }\n        while(index < 0) {\n          index += d_lut_scale;\n        }\n\n        return d_soft_dec_lut[index];\n      }\n      else {\n        return calc_soft_dec(sample);\n      }\n    }\n\n    void\n    constellation::max_min_axes()\n    {\n      // Find min/max of constellation for both real and imag axes.\n      d_re_min = 1e20;\n      d_im_min = 1e20;\n      d_re_max = -1e20;\n      d_im_max = -1e20;\n      for(size_t i = 0; i < d_constellation.size(); i++) {\n        if(d_constellation[i].real() > d_re_max)\n          d_re_max = d_constellation[i].real();\n        if(d_constellation[i].imag() > d_im_max)\n          d_im_max = d_constellation[i].imag();\n\n        if(d_constellation[i].real() < d_re_min)\n          d_re_min = d_constellation[i].real();\n        if(d_constellation[i].imag() < d_im_min)\n          d_im_min = d_constellation[i].imag();\n      }\n      if(d_im_min == 0)\n        d_im_min = d_re_min;\n      if(d_im_max == 0)\n        d_im_max = d_re_max;\n      if(d_re_min == 0)\n        d_re_min = d_im_min;\n      if(d_re_max == 0)\n        d_re_max = d_im_max;\n    }\n\n    /********************************************************************/\n\n\n    constellation_calcdist::sptr\n    constellation_calcdist::make(std::vector<gr_complex> constell,\n                                 std::vector<int> pre_diff_code,\n                                 unsigned int rotational_symmetry,\n                                 unsigned int dimensionality)\n    {\n      return constellation_calcdist::sptr(\n        new constellation_calcdist(constell, pre_diff_code,\n                                   rotational_symmetry, dimensionality));\n    }\n\n    constellation_calcdist::constellation_calcdist(\n      std::vector<gr_complex> constell,\n      std::vector<int> pre_diff_code,\n      unsigned int rotational_symmetry,\n      unsigned int dimensionality)\n      : constellation(constell, pre_diff_code, rotational_symmetry, dimensionality)\n    {}\n\n    // Chooses points base on shortest distance.\n    // Inefficient.\n    unsigned int\n    constellation_calcdist::decision_maker(const gr_complex *sample)\n    {\n      return get_closest_point(sample);\n    }\n\n\n    /********************************************************************/\n\n\n    constellation_sector::constellation_sector(std::vector<gr_complex> constell,\n                                               std::vector<int> pre_diff_code,\n                                               unsigned int rotational_symmetry,\n                                               unsigned int dimensionality,\n                                               unsigned int n_sectors) :\n      constellation(constell, pre_diff_code, rotational_symmetry,\n                    dimensionality),\n      n_sectors(n_sectors)\n    {\n    }\n\n    constellation_sector::~constellation_sector()\n    {\n    }\n\n    unsigned int\n    constellation_sector::decision_maker(const gr_complex *sample)\n    {\n      unsigned int sector;\n      sector = get_sector(sample);\n      return sector_values[sector];\n    }\n\n    void\n    constellation_sector::find_sector_values()\n    {\n      unsigned int i;\n      sector_values.clear();\n      for(i=0; i<n_sectors; i++) {\n        sector_values.push_back(calc_sector_value(i));\n      }\n    }\n\n\n    /********************************************************************/\n\n\n    constellation_rect::sptr\n    constellation_rect::make(std::vector<gr_complex> constell,\n                             std::vector<int> pre_diff_code,\n                             unsigned int rotational_symmetry,\n                             unsigned int real_sectors,\n                             unsigned int imag_sectors,\n                             float width_real_sectors,\n                             float width_imag_sectors)\n    {\n      return constellation_rect::sptr(new constellation_rect\n                                      (constell, pre_diff_code,\n                                       rotational_symmetry,\n                                       real_sectors, imag_sectors,\n                                       width_real_sectors,\n                                       width_imag_sectors));\n    }\n\n    constellation_rect::constellation_rect(\n      std::vector<gr_complex> constell,\n      std::vector<int> pre_diff_code,\n      unsigned int rotational_symmetry,\n      unsigned int real_sectors, unsigned int imag_sectors,\n      float width_real_sectors, float width_imag_sectors) :\n      constellation_sector(constell, pre_diff_code, rotational_symmetry,\n                           1, real_sectors * imag_sectors),\n      n_real_sectors(real_sectors), n_imag_sectors(imag_sectors),\n      d_width_real_sectors(width_real_sectors),\n      d_width_imag_sectors(width_imag_sectors)\n    {\n      d_width_real_sectors *= d_scalefactor;\n      d_width_imag_sectors *= d_scalefactor;\n      find_sector_values();\n    }\n\n    constellation_rect::~constellation_rect()\n    {\n    }\n\n    unsigned int\n    constellation_rect::get_sector(const gr_complex *sample)\n    {\n      int real_sector, imag_sector;\n      unsigned int sector;\n\n      real_sector = int(real(*sample)/d_width_real_sectors\n                        + n_real_sectors/2.0);\n      if(real_sector < 0)\n        real_sector = 0;\n      if(real_sector >= (int)n_real_sectors)\n        real_sector = n_real_sectors-1;\n\n      imag_sector = int(imag(*sample)/d_width_imag_sectors\n                        + n_imag_sectors/2.0);\n      if(imag_sector < 0)\n        imag_sector = 0;\n      if(imag_sector >= (int)n_imag_sectors)\n        imag_sector = n_imag_sectors-1;\n\n      sector = real_sector * n_imag_sectors + imag_sector;\n      return sector;\n    }\n\n    gr_complex\n    constellation_rect::calc_sector_center(unsigned int sector)\n    {\n      unsigned int real_sector, imag_sector;\n      gr_complex sector_center;\n      real_sector = float(sector)/n_imag_sectors;\n      imag_sector = sector - real_sector * n_imag_sectors;\n      sector_center = gr_complex(\n        (real_sector + 0.5 - n_real_sectors/2.0) * d_width_real_sectors,\n        (imag_sector + 0.5 - n_imag_sectors/2.0) * d_width_imag_sectors);\n      return sector_center;\n    }\n\n    unsigned int\n    constellation_rect::calc_sector_value(unsigned int sector)\n    {\n      gr_complex sector_center = calc_sector_center(sector);\n      unsigned int closest_point;\n      closest_point = get_closest_point(&sector_center);\n      return closest_point;\n    }\n\n    /********************************************************************/\n\n    constellation_expl_rect::sptr\n    constellation_expl_rect::make(std::vector<gr_complex> constellation,\n                                  std::vector<int> pre_diff_code,\n                                  unsigned int rotational_symmetry,\n                                  unsigned int real_sectors,\n                                  unsigned int imag_sectors,\n                                  float width_real_sectors,\n                                  float width_imag_sectors,\n                                  std::vector<unsigned int> sector_values)\n    {\n      return constellation_expl_rect::sptr\n        (new constellation_expl_rect(constellation, pre_diff_code,\n                                     rotational_symmetry,\n                                     real_sectors, imag_sectors,\n                                     width_real_sectors, width_imag_sectors,\n                                     sector_values));\n    }\n\n    constellation_expl_rect::constellation_expl_rect(\n      std::vector<gr_complex> constellation,\n      std::vector<int> pre_diff_code,\n      unsigned int rotational_symmetry,\n      unsigned int real_sectors,\n      unsigned int imag_sectors,\n      float width_real_sectors,\n      float width_imag_sectors,\n      std::vector<unsigned int> sector_values)\n      : constellation_rect(constellation, pre_diff_code, rotational_symmetry,\n                           real_sectors, imag_sectors, width_real_sectors, width_imag_sectors),\n        d_sector_values(sector_values)\n    {\n    }\n\n    constellation_expl_rect::~constellation_expl_rect()\n    {\n    }\n\n    /********************************************************************/\n\n\n    constellation_psk::sptr\n    constellation_psk::make(std::vector<gr_complex> constell,\n                            std::vector<int> pre_diff_code,\n                            unsigned int n_sectors)\n    {\n      return constellation_psk::sptr(new constellation_psk\n                                     (constell, pre_diff_code,\n                                      n_sectors));\n    }\n\n    constellation_psk::constellation_psk(std::vector<gr_complex> constell,\n                                         std::vector<int> pre_diff_code,\n                                         unsigned int n_sectors) :\n      constellation_sector(constell, pre_diff_code, constell.size(),\n                           1, n_sectors)\n    {\n      find_sector_values();\n    }\n\n    constellation_psk::~constellation_psk()\n    {\n    }\n\n    unsigned int\n    constellation_psk::get_sector(const gr_complex *sample)\n    {\n      float phase = arg(*sample);\n      float width = M_TWOPI / n_sectors;\n      int sector = floor(phase/width + 0.5);\n      if(sector < 0)\n        sector += n_sectors;\n      return sector;\n    }\n\n    unsigned int\n    constellation_psk::calc_sector_value(unsigned int sector)\n    {\n      float phase = sector * M_TWOPI / n_sectors;\n      gr_complex sector_center = gr_complex(cos(phase), sin(phase));\n      unsigned int closest_point = get_closest_point(&sector_center);\n      return closest_point;\n    }\n\n\n    /********************************************************************/\n\n\n    constellation_bpsk::sptr\n    constellation_bpsk::make()\n    {\n      return constellation_bpsk::sptr(new constellation_bpsk());\n    }\n\n    constellation_bpsk::constellation_bpsk()\n    {\n      d_constellation.resize(2);\n      d_constellation[0] = gr_complex(-1, 0);\n      d_constellation[1] = gr_complex(1, 0);\n      d_rotational_symmetry = 2;\n      d_dimensionality = 1;\n      calc_arity();\n    }\n\n    constellation_bpsk::~constellation_bpsk()\n    {\n    }\n\n    unsigned int\n    constellation_bpsk::decision_maker(const gr_complex *sample)\n    {\n      return (real(*sample) > 0);\n    }\n\n\n    /********************************************************************/\n\n\n    constellation_qpsk::sptr\n    constellation_qpsk::make()\n    {\n      return constellation_qpsk::sptr(new constellation_qpsk());\n    }\n\n    constellation_qpsk::constellation_qpsk()\n    {\n      d_constellation.resize(4);\n      // Gray-coded\n      d_constellation[0] = gr_complex(-SQRT_TWO, -SQRT_TWO);\n      d_constellation[1] = gr_complex(SQRT_TWO, -SQRT_TWO);\n      d_constellation[2] = gr_complex(-SQRT_TWO, SQRT_TWO);\n      d_constellation[3] = gr_complex(SQRT_TWO, SQRT_TWO);\n\n      /*\n        d_constellation[0] = gr_complex(SQRT_TWO, SQRT_TWO);\n        d_constellation[1] = gr_complex(-SQRT_TWO, SQRT_TWO);\n        d_constellation[2] = gr_complex(SQRT_TWO, -SQRT_TWO);\n        d_constellation[3] = gr_complex(SQRT_TWO, -SQRT_TWO);\n      */\n\n      d_pre_diff_code.resize(4);\n      d_pre_diff_code[0] = 0x0;\n      d_pre_diff_code[1] = 0x2;\n      d_pre_diff_code[2] = 0x3;\n      d_pre_diff_code[3] = 0x1;\n\n      d_rotational_symmetry = 4;\n      d_dimensionality = 1;\n      calc_arity();\n    }\n\n    constellation_qpsk::~constellation_qpsk()\n    {\n    }\n\n    unsigned int\n    constellation_qpsk::decision_maker(const gr_complex *sample)\n    {\n      // Real component determines small bit.\n      // Imag component determines big bit.\n      return 2*(imag(*sample)>0) + (real(*sample)>0);\n\n      /*\n        bool a = real(*sample) > 0;\n        bool b = imag(*sample) > 0;\n        if(a) {\n        if(b)\n        return 0x0;\n        else\n        return 0x1;\n        }\n        else {\n        if(b)\n        return 0x2;\n        else\n        return 0x3;\n        }\n      */\n    }\n\n\n    /********************************************************************/\n\n\n    constellation_dqpsk::sptr\n    constellation_dqpsk::make()\n    {\n      return constellation_dqpsk::sptr(new constellation_dqpsk());\n    }\n\n    constellation_dqpsk::constellation_dqpsk()\n    {\n      // This constellation is not gray coded, which allows\n      // us to use differential encodings (through diff_encode and\n      // diff_decode) on the symbols.\n      d_constellation.resize(4);\n      d_constellation[0] = gr_complex(+SQRT_TWO, +SQRT_TWO);\n      d_constellation[1] = gr_complex(-SQRT_TWO, +SQRT_TWO);\n      d_constellation[2] = gr_complex(-SQRT_TWO, -SQRT_TWO);\n      d_constellation[3] = gr_complex(+SQRT_TWO, -SQRT_TWO);\n\n      // Use this mapping to convert to gray code before diff enc.\n      d_pre_diff_code.resize(4);\n      d_pre_diff_code[0] = 0x0;\n      d_pre_diff_code[1] = 0x1;\n      d_pre_diff_code[2] = 0x3;\n      d_pre_diff_code[3] = 0x2;\n      d_apply_pre_diff_code = true;\n\n      d_rotational_symmetry = 4;\n      d_dimensionality = 1;\n      calc_arity();\n    }\n\n    constellation_dqpsk::~constellation_dqpsk()\n    {\n    }\n\n    unsigned int\n    constellation_dqpsk::decision_maker(const gr_complex *sample)\n    {\n      // Slower deicison maker as we can't slice along one axis.\n      // Maybe there's a better way to do this, still.\n\n      bool a = real(*sample) > 0;\n      bool b = imag(*sample) > 0;\n      if(a) {\n        if(b)\n          return 0x0;\n        else\n          return 0x3;\n      }\n      else {\n        if(b)\n          return 0x1;\n        else\n          return 0x2;\n      }\n    }\n\n\n    /********************************************************************/\n\n\n    constellation_8psk::sptr\n    constellation_8psk::make()\n    {\n      return constellation_8psk::sptr(new constellation_8psk());\n    }\n\n    constellation_8psk::constellation_8psk()\n    {\n      float angle = M_PI/8.0;\n      d_constellation.resize(8);\n      // Gray-coded\n      d_constellation[0] = gr_complex(cos( 1*angle), sin( 1*angle));\n      d_constellation[1] = gr_complex(cos( 7*angle), sin( 7*angle));\n      d_constellation[2] = gr_complex(cos(15*angle), sin(15*angle));\n      d_constellation[3] = gr_complex(cos( 9*angle), sin( 9*angle));\n      d_constellation[4] = gr_complex(cos( 3*angle), sin( 3*angle));\n      d_constellation[5] = gr_complex(cos( 5*angle), sin( 5*angle));\n      d_constellation[6] = gr_complex(cos(13*angle), sin(13*angle));\n      d_constellation[7] = gr_complex(cos(11*angle), sin(11*angle));\n      d_rotational_symmetry = 8;\n      d_dimensionality = 1;\n      calc_arity();\n    }\n\n    constellation_8psk::~constellation_8psk()\n    {\n    }\n\n    unsigned int\n    constellation_8psk::decision_maker(const gr_complex *sample)\n    {\n      unsigned int ret = 0;\n\n      float re = sample->real();\n      float im = sample->imag();\n\n      if(fabsf(re) <= fabsf(im))\n        ret  = 4;\n      if(re <= 0)\n        ret |= 1;\n      if(im <= 0)\n        ret |= 2;\n\n      return ret;\n    }\n\n\n    /********************************************************************/\n\n\n    constellation_8psk_natural::sptr \n    constellation_8psk_natural::make()\n    {\n      return constellation_8psk_natural::sptr(new constellation_8psk_natural());\n    }\n\n    constellation_8psk_natural::constellation_8psk_natural()\n    {\n      float angle = M_PI/8.0;\n      d_constellation.resize(8);\n      // Natural-mapping\n      d_constellation[0] = gr_complex(cos( 15*angle), sin( 15*angle));\n      d_constellation[1] = gr_complex(cos( 1*angle), sin( 1*angle));\n      d_constellation[2] = gr_complex(cos(3*angle), sin(3*angle));\n      d_constellation[3] = gr_complex(cos( 5*angle), sin( 5*angle));\n      d_constellation[4] = gr_complex(cos( 7*angle), sin( 7*angle));\n      d_constellation[5] = gr_complex(cos( 9*angle), sin( 9*angle));\n      d_constellation[6] = gr_complex(cos(11*angle), sin(11*angle));\n      d_constellation[7] = gr_complex(cos(13*angle), sin(13*angle));\n      d_rotational_symmetry = 8;\n      d_dimensionality = 1;\n      calc_arity();\n    }\n\n    constellation_8psk_natural::~constellation_8psk_natural()\n    {\n    }\n\n    unsigned int\n    constellation_8psk_natural::decision_maker(const gr_complex *sample)\n    {\n      unsigned int ret = 0;\n\n      float re = sample->real();\n      float im = sample->imag();\n\n      if((re+im) < 0)\n        ret  = 4;\n      if(fabsf(im) > fabsf(re)){\n        ret |= 2;\n\tif(re*im < 0)\n          ret |= 1;\n\t}\n      if(fabsf(im) < fabsf(re) && re*im > 0)\n        ret |= 1;\n\n      return ret;\n    }\n\n\n    /********************************************************************/\n\n\n    constellation_16qam::sptr \n    constellation_16qam::make()\n    {\n      return constellation_16qam::sptr(new constellation_16qam());\n    }\n\n    constellation_16qam::constellation_16qam()\n    {\n      const float level = sqrt(float(0.1));\n      d_constellation.resize(16);\n      // The mapping used in 16qam set partition\n      d_constellation[0] = gr_complex(1*level,-1*level);\n      d_constellation[1] = gr_complex(-1*level,-1*level);\n      d_constellation[2] = gr_complex(3*level,-3*level);\n      d_constellation[3] = gr_complex(-3*level,-3*level);\n      d_constellation[4] = gr_complex(-3*level,-1*level);\n      d_constellation[5] = gr_complex(3*level,-1*level);\n      d_constellation[6] = gr_complex(-1*level,-3*level);\n      d_constellation[7] = gr_complex(1*level,-3*level);\n      d_constellation[8] = gr_complex(-3*level,3*level);\n      d_constellation[9] = gr_complex(3*level,3*level);\n      d_constellation[10] = gr_complex(-1*level,1*level);\n      d_constellation[11] = gr_complex(1*level,1*level);\n      d_constellation[12] = gr_complex(1*level,3*level);\n      d_constellation[13] = gr_complex(-1*level,3*level);\n      d_constellation[14] = gr_complex(3*level,1*level);\n      d_constellation[15] = gr_complex(-3*level,1*level);\n      d_rotational_symmetry = 4;\n      d_dimensionality = 1;\n      calc_arity();\n    }\n\n    constellation_16qam::~constellation_16qam()\n    {\n    }\n\n    unsigned int\n    constellation_16qam::decision_maker(const gr_complex *sample)\n    {\n      unsigned int ret = 0;\n      const float level = sqrt(float(0.1));\n      float re = sample->real();\n      float im = sample->imag();\n\n      if(im <= 0 && im >= -2*level && re >= 0 && re <= 2*level)\n\tret = 0;\n      else if(im <= 0 && im >= -2*level && re <= 0 && re >= -2*level)\n\tret = 1;\n      else if(im <= -2*level && re >= 2*level)\n\tret = 2;\n      else if(im <= -2*level && re <= -2*level)\n\tret = 3;\n      else if(im <= 0 && im >= -2*level && re <= -2*level)\n\tret = 4;\n      else if(im <= 0 && im >= -2*level && re >= 2*level)\n\tret = 5;\n      else if(im <= -2*level && re <= 0 && re >= -2*level)\n\tret = 6;\n      else if(im <= -2*level && re >= 0 && re <= 2*level)\n\tret = 7;\n      else if(im >= 2*level && re <= -2*level)\n\tret = 8;\n      else if(im >= 2*level && re >= 2*level)\n\tret = 9;\n      else if(im >= 0 && im <= 2*level && re <= 0 && re >= -2*level)\n\tret = 10;\n      else if(im >= 0 && im <= 2*level && re >= 0 && re <= 2*level)\n\tret = 11;\n      else if(im >= 2*level && re >= 0 && re <= 2*level)\n\tret = 12;\n      else if(im >= 2*level && re <= 0 && re >= -2*level)\n\tret = 13;\n      else if(im >= 0 && im <= 2*level && re >= 2*level)\n\tret = 14;\n      else if(im >= 0 && im <= 2*level && re <= -2*level)\n\tret = 15;\n\n      return ret;\n    }\n\n\n  } /* namespace digital */\n} /* namespace gr */\n", "meta": {"hexsha": "a09a9e5fb975fd8d57b5fde17ce1d4a5f87e9a43", "size": 29975, "ext": "cc", "lang": "C++", "max_stars_repo_path": "gnuradio-3.7.13.4/gr-digital/lib/constellation.cc", "max_stars_repo_name": "v1259397/cosmic-gnuradio", "max_stars_repo_head_hexsha": "64c149520ac6a7d44179c3f4a38f38add45dd5dc", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-03-09T07:32:37.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-09T07:32:37.000Z", "max_issues_repo_path": "gnuradio-3.7.13.4/gr-digital/lib/constellation.cc", "max_issues_repo_name": "v1259397/cosmic-gnuradio", "max_issues_repo_head_hexsha": "64c149520ac6a7d44179c3f4a38f38add45dd5dc", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "gnuradio-3.7.13.4/gr-digital/lib/constellation.cc", "max_forks_repo_name": "v1259397/cosmic-gnuradio", "max_forks_repo_head_hexsha": "64c149520ac6a7d44179c3f4a38f38add45dd5dc", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.3083923155, "max_line_length": 95, "alphanum_fraction": 0.5743452877, "num_tokens": 7562, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6548947155710233, "lm_q2_score": 0.46879062662624377, "lm_q1q2_score": 0.3070085040867557}}
{"text": "///\n\n#include <iostream>\n#include <algorithm>\n#include <vector>\n#include <unordered_map>\n#include <map>\n#include <iterator>\n// BGL includes\n// #include <boost/graph/adjacency_list.hpp>\n\n// // BGL graph definitions\n// // =====================\n// // Graph Type with nested interior edge properties for Flow Algorithms\n// // =====================\n// // Graph Type, OutEdgeList Type, VertexList Type, (un)directedS\n// typedef boost::adjacency_list<boost::vecS, boost::vecS, boost::directedS     // Use vecS for the VertexList! Choosing setS for the OutEdgeList disallows parallel edges.\n//     >          graph;\n// typedef boost::graph_traits<graph>::vertex_descriptor    vertex_desc;    // Vertex Descriptor: with vecS vertex list, this is really just an int in the range [0, num_vertices(G)).  \n// typedef boost::graph_traits<graph>::edge_iterator    edge_it;    // to iterate over all edges\n// typedef  boost::graph_traits<graph>::out_edge_iterator      out_edge_it;\n// // Custom Edge Adder Class, that holds the references\n// // to the graph, capacity map and reverse edge map\n// // ===================================================\n\nstd::vector<int> age;\nstd::vector<int> solution;\nstd::vector<std::pair<int,int>> curr_path;\n\nstruct second_greater {\n  bool operator() (const std::pair<int, int>& t0, const std::pair<int,int>& t1) {\n    return t0.second > t1.second;\n  }\n};\n\n\nvoid solve_for(int idx, std::vector<std::vector<int>> &children,\n  std::vector<std::vector<std::pair<int,int>>> &queries) {\n        \n  curr_path.push_back({idx, age[idx]});\n  std::vector<std::pair<int,int>> queries_for_idx = queries[idx];\n  for(auto p : queries_for_idx) {\n    int sol_idx = p.first;\n    int b = p.second;\n    auto j = std::lower_bound(curr_path.begin(), curr_path.end(), std::make_pair(0, b), second_greater());\n    solution[sol_idx] = j->first;\n  }\n  for(const int i : children[idx]) {\n    solve_for(i, children, queries);\n  }\n  \n  curr_path.pop_back();\n  \n}\n\n// Main\nvoid testcase() {\n  // build graph\n  int n, q;\n  std::cin >> n >> q;\n  \n  std::unordered_map<std::string, int> name_to_ind;\n  name_to_ind.clear();\n  \n  std::vector<std::vector<int>> children(n);\n  \n  age.clear();\n  age.reserve(n);\n  \n  solution.clear();\n  solution = std::vector<int>(q);\n  \n  curr_path.clear();\n  \n  std::vector<std::string> ind_to_name;\n  ind_to_name.reserve(n);\n  \n  \n  int root = -1;\n  int max_age =  std::numeric_limits<int>::min();\n  \n  for(int i = 0; i < n; i++) {\n    std::string s; int a;\n    std::cin >> s; std::cin >> a;\n    name_to_ind.insert({s, i});\n    ind_to_name.push_back(s);\n    age.push_back(a);\n    if(a > max_age) {\n      root = i; max_age = a;\n    }\n  }\n  \n  for(int i = 0; i < n - 1; i++) {\n    std::string s, p;\n    std::cin >> s; std::cin >> p;\n    children[name_to_ind.at(p)].push_back(name_to_ind.at(s));\n  }\n  \n  std::vector<std::vector<std::pair<int,int>>> queries(n);\n  \n  for(int k = 0; k < q; k++) {\n    std::string s; int b;\n    std::cin >> s; std::cin >> b;\n    int idx = name_to_ind.at(s);\n    queries[idx].push_back({k, b});\n  }\n  \n  \n  solve_for(root, children, queries);\n  \n  for(int k = 0; k < q; k++) {\n    std::cout << ind_to_name[solution[k]] << \" \";\n  }\n  std::cout << std::endl;\n}\n\nint main() {\n  std::ios_base::sync_with_stdio(false);\n  std::size_t t;\n  for (std::cin >> t; t > 0; --t) testcase();\n  return 0;\n}\n", "meta": {"hexsha": "3e93674034b0503376265c52c10ad0ff9a00b0c2", "size": 3338, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "problems/week10-evolution/src/algorithm.cpp", "max_stars_repo_name": "haeggee/algolab", "max_stars_repo_head_hexsha": "176a7d4efbbfb2842f46e93250be00d3b59e0ec3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "problems/week10-evolution/src/algorithm.cpp", "max_issues_repo_name": "haeggee/algolab", "max_issues_repo_head_hexsha": "176a7d4efbbfb2842f46e93250be00d3b59e0ec3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "problems/week10-evolution/src/algorithm.cpp", "max_forks_repo_name": "haeggee/algolab", "max_forks_repo_head_hexsha": "176a7d4efbbfb2842f46e93250be00d3b59e0ec3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.1382113821, "max_line_length": 184, "alphanum_fraction": 0.6054523667, "num_tokens": 942, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.5736784074525096, "lm_q1q2_score": 0.3069744143648549}}
{"text": "// Boost.Maral library (Molecular Archiving, Retrieval & Algorithm Library)\n//\n// Copyright (C) 2014 Armin Madadkar Sobhani\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// $Id$\n\n#ifndef MARAL_UNITS_HPP\n#define MARAL_UNITS_HPP\n\n#include <boost/units/systems/si/plane_angle.hpp>\n#include <boost/units/systems/angle/degrees.hpp>\n#include <boost/units/systems/angle/gradians.hpp>\n#include <boost/units/systems/si/length.hpp>\n#include <boost/units/base_units/metric/angstrom.hpp> \n#include <boost/units/systems/si/io.hpp>\n\nnamespace boost { namespace units \n{ \n    typedef metric::angstrom_base_unit::unit_type angstrom_unit; \n    BOOST_UNITS_STATIC_CONSTANT(angstrom, angstrom_unit); \n    BOOST_UNITS_STATIC_CONSTANT(angstroms, angstrom_unit); \n\n    typedef scaled_base_unit<si::meter_base_unit, \n            scale<10, static_rational<-9> > > nanometer_base_unit; \n    typedef nanometer_base_unit::unit_type nanometer_unit; \n    BOOST_UNITS_STATIC_CONSTANT(nanometer, nanometer_unit); \n    BOOST_UNITS_STATIC_CONSTANT(nanometers, nanometer_unit); \n\n}}  // namespace boost::units \n\nnamespace maral {\n\n////////////////////////////////////////////////////////////////////////////////\n/// \\brief Namespace for units, quantities and unit system support.\n///\n/// Namespace for supporting units, quantities, unit system and dimensional\n/// analysis. It is based on Boost.Units. Some terminology from Boost.Units:\n///\n/// \\li \\b Unit: A set of base units raised to rational exponents, e.g. m^1,\n/// kg^1, m^1/s^2.\n/// \\li \\b Quantity: A quantity represents a concrete amount of a unit. Thus,\n/// while the meter is the base unit of length in the SI system, 5.5 meters is a\n/// quantity of length in that system.\n/// \\li \\b System: A unit system is a collection of base units representing all\n/// the measurable entities of interest for a specific problem.\n///\n/// Maral uses SI unit system by default.\n\nnamespace units {\n\n////////////////////////////////////////////////////////////////////////////////\n// Units for Angle\n\n////////////////////////////////////////////////////////////////////////////////\n/// \\brief Specialization of boost::units::quantity for storing angles in\n/// radians.\n///\n/// \\param Type Value type of the angle (e.g. int, float, double, ...).\n/// \\remarks\n/// \\par\n/// A partial specialization of boost::units::quantity for storing angle values\n/// in radians.\n/// \\see radians, to_radians\n\ntemplate <typename Type>\nusing angle_in_radians =\n    boost::units::quantity<boost::units::si::plane_angle, Type>;\n\n////////////////////////////////////////////////////////////////////////////////\n/// \\brief Specialization of boost::units::quantity for storing angles in\n/// degrees.\n///\n/// \\param Type Value type of the angle (e.g. int, float, double, ...).\n/// \\remarks\n/// \\par\n/// A partial specialization of boost::units::quantity for storing angle values\n/// in degrees.\n/// \\see degrees, to_degrees\n\ntemplate <typename Type>\nusing angle_in_degrees =\n    boost::units::quantity<boost::units::degree::plane_angle, Type>;\n\n////////////////////////////////////////////////////////////////////////////////\n/// \\brief Specialization of boost::units::quantity for storing angles in\n/// gradians.\n///\n/// \\param Type Value type of the angle (e.g. int, float, double, ...).\n/// \\remarks\n/// \\par\n/// A partial specialization of boost::units::quantity for storing angle values\n/// in gradians.\n/// \\see degrees, to_degrees\n\ntemplate <typename Type>\nusing angle_in_gradians =\n    boost::units::quantity<boost::units::gradian::plane_angle, Type>;\n\n////////////////////////////////////////////////////////////////////////////////\n/// \\return Created angle in raidans as a boost::units::quantity object.\n/// \\param rad Angle value in radians.\n/// \\remarks\n/// Type-safe factory method for creating an angle in radians from a value\n/// specified.\n/// \\see to_radians\n\ntemplate <typename Type>\ninline\nangle_in_radians<Type> radians(Type rad)\n{\n    return angle_in_radians<Type>(rad * boost::units::si::radians);\n}\n\n////////////////////////////////////////////////////////////////////////////////\n/// \\return Created angle in degrees as a boost::units::quantity object.\n/// \\param deg Angle value in degrees.\n/// \\remarks\n/// Type-safe factory method for creating an angle in degrees from a value\n/// specified.\n/// \\see to_degrees\n\ntemplate <typename Type>\ninline\nangle_in_degrees<Type> degrees(Type deg)\n{\n    return angle_in_degrees<Type>(deg * boost::units::degree::degrees);\n}\n\n////////////////////////////////////////////////////////////////////////////////\n/// \\return Created angle in gradians as a boost::units::quantity object.\n/// \\param grd Angle value in gradians.\n/// \\remarks\n/// Type-safe factory method for creating an angle in gradians from a value\n/// specified.\n/// \\see to_gradians\n\ntemplate <typename Type>\ninline\nangle_in_gradians<Type> gradians(Type grd)\n{\n    return angle_in_degrees<Type>(grd * boost::units::gradian::gradians);\n}\n\n////////////////////////////////////////////////////////////////////////////////\n/// \\return Angle in radians.\n/// \\param ang Reference to an angle quantity object.\n/// \\remarks\n/// Conversion method for getting angle quantity in radians.\n/// \\see radians\n\ntemplate <typename Unit, typename Type>\ninline\nangle_in_radians<Type> to_radians(\n    const boost::units::quantity<Unit, Type>& ang)\n{\n    return static_cast< angle_in_radians<Type> > (ang);\n}\n\n////////////////////////////////////////////////////////////////////////////////\n/// \\return Angle in degrees.\n/// \\param ang Reference to an angle quantity object.\n/// \\remarks\n/// Conversion method for getting angle quantity in degrees.\n/// \\see degrees\n\ntemplate <typename Unit, typename Type>\ninline\nangle_in_degrees<Type> to_degrees(\n    const boost::units::quantity<Unit, Type>& ang)\n{\n    return static_cast< angle_in_degrees<Type> > (ang);\n}\n\n////////////////////////////////////////////////////////////////////////////////\n/// \\return Angle in gradians.\n/// \\param ang Reference to an angle quantity object.\n/// \\remarks\n/// Conversion method for getting angle quantity in gradians.\n/// \\see gradians\n\ntemplate <typename Unit, typename Type>\ninline\nangle_in_gradians<Type> to_gradians(\n    const boost::units::quantity<Unit, Type>& ang)\n{\n    return static_cast< angle_in_gradians<Type> > (ang);\n}\n\n////////////////////////////////////////////////////////////////////////////////\n// Units for Length\n\n////////////////////////////////////////////////////////////////////////////////\n/// \\brief Specialization of boost::units::quantity for storing length in\n/// Angstroms.\n///\n/// \\param Type Value type of the length (e.g. int, float, double, ...).\n/// \\remarks\n/// \\par\n/// An alias of boost::units::quantity for storing length values in Angstroms.\n/// \\see angstroms, to_angstroms\n\ntemplate <typename Type>\nusing length_in_angstroms =\n    boost::units::quantity<boost::units::angstrom_unit, Type>;\n\n////////////////////////////////////////////////////////////////////////////////\n/// \\brief Specialization of boost::units::quantity for storing length in\n/// nanometers.\n///\n/// \\param Type Value type of the length (e.g. int, float, double, ...).\n/// \\remarks\n/// \\par\n/// An alias of boost::units::quantity for storing length values in nanometers.\n/// \\see nanometers, to_nanometers\n\ntemplate <typename Type>\nusing length_in_nanometers =\n    boost::units::quantity<boost::units::nanometer_unit, Type>;\n\n////////////////////////////////////////////////////////////////////////////////\n/// \\brief Specialization of boost::units::quantity for storing angles in\n/// gradians.\n///\n/// \\param Type Value type of the angle (e.g. int, float, double, ...).\n/// \\remarks\n/// \\par\n/// A partial specialization of boost::units::quantity for storing angle values\n/// in gradians.\n/// \\see degrees, to_degrees\n\n//template <typename Type>\n//using angle_in_gradians =\n//    boost::units::quantity<boost::units::gradian::plane_angle, Type>;\n\n////////////////////////////////////////////////////////////////////////////////\n/// \\return Created length in Angstroms as a boost::units::quantity object.\n/// \\param ang Length value in Angstroms.\n/// \\remarks\n/// Type-safe factory method for creating a length in Angstroms from a value\n/// specified.\n/// \\see to_angstroms\n\ntemplate <typename Type>\ninline\nlength_in_angstroms<Type> angstroms(Type ang)\n{\n    return length_in_angstroms<Type>(ang * boost::units::angstroms);\n}\n\n////////////////////////////////////////////////////////////////////////////////\n/// \\return Created length in nanometers as a boost::units::quantity object.\n/// \\param len Length value in nanometers.\n/// \\remarks\n/// Type-safe factory method for creating a length in nanometers from a value\n/// specified.\n/// \\see to_nanometers\n\ntemplate <typename Type>\ninline\nlength_in_nanometers<Type> nanometers(Type len)\n{\n    return length_in_nanometers<Type>(len * boost::units::nanometers);\n}\n\n////////////////////////////////////////////////////////////////////////////////\n/// \\return Created angle in gradians as a boost::units::quantity object.\n/// \\param grd Angle value in gradians.\n/// \\remarks\n/// Type-safe factory method for creating an angle in gradians from a value\n/// specified.\n/// \\see to_gradians\n\n//template <typename Type>\n//inline\n//angle_in_gradians<Type> gradians(Type grd)\n//{\n//    return angle_in_degrees<Type>(grd * boost::units::gradian::gradians);\n//}\n\n////////////////////////////////////////////////////////////////////////////////\n/// \\return Length in Angstroms.\n/// \\param len Reference to a length quantity object.\n/// \\remarks\n/// Conversion method for getting length quantity in Angstroms.\n/// \\see angstroms\n\ntemplate <typename Unit, typename Type>\ninline\nlength_in_angstroms<Type> to_angstroms(\n    const boost::units::quantity<Unit, Type>& len)\n{\n    return static_cast< length_in_angstroms<Type> > (len);\n}\n\n////////////////////////////////////////////////////////////////////////////////\n/// \\return Length in nanometers.\n/// \\param len Reference to a length value.\n/// \\remarks\n/// Conversion method for getting a length quantity in nanometers.\n/// \\see nanometers\n\ntemplate <typename Unit, typename Type>\ninline\nlength_in_nanometers<Type> to_nanometers(\n    const boost::units::quantity<Unit, Type>& len)\n{\n    return static_cast< length_in_nanometers<Type> > (len);\n}\n\n////////////////////////////////////////////////////////////////////////////////\n/// \\return Angle in gradians.\n/// \\param ang Reference to an angle quantity object.\n/// \\remarks\n/// Conversion method for getting angle quantity in gradians.\n/// \\see gradians\n\n//template <typename Unit, typename Type>\n//inline\n//angle_in_gradians<Type> to_gradians(\n//    const boost::units::quantity<Unit, Type>& ang)\n//{\n//    return static_cast< angle_in_gradians<Type> > (ang);\n//}\n\n}}    // namespace maral::units\n\n#endif    // MARAL_UNITS_HPP\n", "meta": {"hexsha": "9945b588bad423ccd7fef2c60b7233304c14dabd", "size": 10973, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/maral/units.hpp", "max_stars_repo_name": "arminms/maral", "max_stars_repo_head_hexsha": "72ac000aa5e37702beec3b3423db7ab2e43da01e", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-03-01T19:00:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-01T19:00:17.000Z", "max_issues_repo_path": "src/maral/units.hpp", "max_issues_repo_name": "arminms/maral", "max_issues_repo_head_hexsha": "72ac000aa5e37702beec3b3423db7ab2e43da01e", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2016-04-28T18:51:08.000Z", "max_issues_repo_issues_event_max_datetime": "2016-05-25T19:43:19.000Z", "max_forks_repo_path": "src/maral/units.hpp", "max_forks_repo_name": "arminms/maral", "max_forks_repo_head_hexsha": "72ac000aa5e37702beec3b3423db7ab2e43da01e", "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.0512048193, "max_line_length": 80, "alphanum_fraction": 0.6094960357, "num_tokens": 2298, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6187804478040617, "lm_q2_score": 0.49609382947091946, "lm_q1q2_score": 0.30697316195284735}}
{"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 \"reed_muller_synthesis.hpp\"\n\n#include <math.h>\n\n#include <boost/assign/std/vector.hpp>\n#include <boost/dynamic_bitset.hpp>\n#include <boost/range/adaptor/reversed.hpp>\n#include <boost/range/adaptor/transformed.hpp>\n#include <boost/range/algorithm/find_if.hpp>\n#include <boost/range/algorithm/for_each.hpp>\n#include <boost/range/irange.hpp>\n#include <boost/range/iterator_range.hpp>\n#include <boost/variant.hpp>\n\n#include <core/functor.hpp>\n#include <core/utils/timer.hpp>\n\n#include <reversible/functions/add_gates.hpp>\n#include <reversible/functions/clear_circuit.hpp>\n#include <reversible/functions/copy_metadata.hpp>\n#include <reversible/functions/fully_specified.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  using spectra_t = std::vector<boost::dynamic_bitset<>>;\n\n  struct to_value\n  {\n    using result_type = bool;\n\n    bool operator()( const boost::optional<bool>& b ) const\n    {\n      return *b;\n    }\n  };\n\n  template<typename CubeIterator>\n  unsigned long cube_to_value( CubeIterator first, CubeIterator second )\n  {\n    boost::dynamic_bitset<> input;\n\n    using boost::adaptors::transformed;\n    boost::for_each( boost::make_iterator_range( first, second ) | transformed( to_value() ), [&input]( bool b ) { input.push_back( b ); } );\n    return input.to_ulong();\n  }\n\n  void apply_cnot( spectra_t& f, unsigned c, unsigned t )\n  {\n    for ( auto& row : f )\n    {\n      row[t] = row[t] ^ row[c];\n    }\n  }\n\n  boost::dynamic_bitset<> multiply_columns( const spectra_t& f, const std::vector<unsigned>& columns )\n  {\n    boost::dynamic_bitset<> m( f.size() );\n\n    // Initial\n    for ( unsigned r = 0u; r < f.size(); ++r )\n    {\n      m.set( r, f[r].test( columns.at( 0u ) ) );\n    }\n\n    for ( unsigned i = 1u; i < columns.size(); ++i )\n    {\n      boost::dynamic_bitset<> mnew( f.size(), 0 );\n\n      for ( unsigned r = 0u; r < f.size(); ++r )\n      {\n        if ( m.test( r ) )\n        {\n          for ( unsigned r2 = 0u; r2 < f.size(); ++r2 )\n          {\n            if ( f[r2].test( columns.at( i ) ) )\n            {\n              mnew.flip( r | r2 );\n            }\n          }\n        }\n      }\n\n      m = mnew;\n    }\n\n    return m;\n  }\n\n  void apply_toffoli( spectra_t& f, const std::vector<unsigned>& controls, unsigned t )\n  {\n    boost::dynamic_bitset<> c = multiply_columns( f, controls );\n\n    for ( unsigned r = 0u; r < f.size(); ++r )\n    {\n      f[r][t] = f[r][t] ^ c[r];\n    }\n  }\n\n  void apply_toffoli_front( spectra_t& f, const std::vector<unsigned>& controls, unsigned t )\n  {\n    if ( f.empty() ) return;\n\n    // Control Mask\n    unsigned cmask = 0u;\n    for ( unsigned c : controls )\n    {\n      cmask |= 1u << c;\n    }\n\n    // Target Mask\n    unsigned tmask = 1u << t;\n\n    // for each column\n    for ( unsigned j : boost::irange( 0u, (unsigned)f[0u].size() ) )\n    {\n      // for each row\n      for ( unsigned r : boost::irange( 0u, (unsigned)f.size() ) )\n      {\n        // match?\n        if ( ( r & tmask ) && f[r].test( j ) )\n        {\n          // Clear the bit\n          unsigned mask = r & ~tmask;\n          f[mask | cmask].flip( j );\n        }\n      }\n    }\n  }\n\n  void apply_gate( circuit& circ, const std::vector<spectra_t*>& funcs, unsigned offset, unsigned& insert_at, const boost::variant<std::vector<unsigned>, unsigned>& controls, unsigned t )\n  {\n    std::vector<unsigned> _controls;\n\n    if ( const std::vector<unsigned>* op = boost::get<std::vector<unsigned> >( &controls ) )\n    {\n      _controls.assign( op->begin(), op->end() );\n    }\n    else if ( const unsigned* op = boost::get<unsigned>( &controls ) )\n    {\n      _controls += *op;\n    }\n\n    switch ( _controls.size() )\n    {\n    case 0u:\n      insert_not( circ, insert_at, t );\n      insert_at += offset;\n      funcs[offset]->at( 0u ).reset( t );\n      apply_toffoli_front( *funcs[1u - offset], _controls, t );\n      break;\n\n    case 1u:\n      insert_cnot( circ, insert_at, _controls.at( 0u ), t );\n      insert_at += offset;\n      apply_cnot( *funcs[offset], _controls.at( 0u ), t );\n      apply_toffoli_front( *funcs[1u - offset], _controls, t );\n      break;\n\n    default:\n      insert_toffoli( circ, insert_at, _controls, t );\n      insert_at += offset;\n      apply_toffoli( *funcs[offset], _controls, t );\n      apply_toffoli_front( *funcs[1u - offset], _controls, t );\n      break;\n    }\n  }\n\n  void print_spectra( const spectra_t& f )\n  {\n    for ( unsigned i = 0u; i < f.size(); ++i )\n    {\n      std::cout << f[i] << std::endl;\n    }\n  }\n\n  bool reed_muller_synthesis( circuit& circ, const binary_truth_table& spec, properties::ptr settings, properties::ptr statistics )\n  {\n\n    // Settings parsing\n    const auto bidirectional = get( settings, \"bidirectional\", true );\n\n    // Run-time measuring\n    properties_timer t( statistics );\n\n    // circuit has to be empty\n    clear_circuit( circ );\n\n    // truth table has to be fully specified\n    if ( !fully_specified( spec ) )\n    {\n      set_error_message( statistics, \"truth table `spec` is not fully specified.\" );\n      return false;\n    }\n\n    // Determine Function Vectors from Specification\n    unsigned n = spec.num_outputs();\n    spectra_t func( 1u << n, boost::dynamic_bitset<>( n ) );\n    spectra_t ifunc( 1u << n, boost::dynamic_bitset<>( n ) );\n\n    for ( binary_truth_table::const_iterator it = spec.begin(); it != spec.end(); ++it )\n    {\n      unsigned long ipos = cube_to_value( it->first.first, it->first.second );\n      binary_truth_table::cube_type output( it->second.first, it->second.second );\n\n      for ( unsigned i = 0u; i < n; ++i )\n      {\n        func[ipos].set( i, *output.at( i ) );\n      }\n\n      if ( bidirectional )\n      {\n        unsigned long opos = cube_to_value( it->second.first, it->second.second );\n        binary_truth_table::cube_type input( it->first.first, it->first.second );\n        for ( unsigned i = 0u; i < n; ++i )\n        {\n          ifunc[opos].set( i, *input.at( i ) );\n        }\n      }\n    }\n\n    // Determine Reed Muller Spectra fom Function Vectors\n    {\n      unsigned i, j, k, m, p;\n      for ( m = 1u; m < ( 1u << n ); m = 2 * m )\n      {\n        for ( i = 0u; i < ( 1u << n ); i = i + 2 * m )\n        {\n          for ( j = i, p = k = i + m; j < p; j = j + 1, k = k + 1 )\n          {\n            func[k] = func[k] ^ func[j];\n            if ( bidirectional )\n            {\n              ifunc[k] = ifunc[k] ^ ifunc[j];\n            }\n          }\n        }\n      }\n    }\n\n    // Synthesis\n    // copy metadata\n    circ.set_lines( n );\n    copy_metadata( spec, circ );\n\n    std::vector<spectra_t*> funcs;\n    funcs += &func,&ifunc;\n    unsigned insert_at = 0u;\n\n    // Step A (i = 0)\n    for ( unsigned j = 0u; j < n; ++j )\n    {\n      unsigned offset = bidirectional && ( ifunc[0u].count() < func[0u].count() ) ? 1u : 0u;\n\n      if ( funcs[offset]->at( 0u ).test( j ) )\n      {\n        apply_gate( circ, funcs, offset, insert_at, std::vector<unsigned>(), j );\n      }\n    }\n\n    for ( unsigned i = 1u; i < ( 1u << n ) - 1; ++i )\n    {\n      // Step B (i = 2^(k-1), variable rows)\n      if ( ( log( i ) / log( 2.0 ) ) == ceil( ( log( i ) / log( 2.0 ) ) ) )\n      {\n        unsigned k = (unsigned)ceil( ( log( i ) / log( 2.0 ) ) );\n        unsigned offset = bidirectional && ( hamming_distance( i, ifunc[0u].to_ulong() ) < hamming_distance( i, func[0u].to_ulong() ) ) ? 1u : 0u;\n        const boost::dynamic_bitset<>& func_offset = funcs[offset]->at( i );\n        if ( !func_offset.test( k ) )\n        {\n          using boost::adaptors::reversed;\n\n          unsigned s = *boost::find_if( boost::irange( 0u, n ) | reversed, [&func_offset]( unsigned j ) { return func_offset.test( j ); } );\n          apply_gate( circ, funcs, offset, insert_at, s, k );\n        }\n\n        for ( unsigned j = 0u; j < n; ++j )\n        {\n          if ( j != k && func_offset.test( j ) )\n          {\n            apply_gate( circ, funcs, offset, insert_at, k, j );\n          }\n        }\n      }\n      // Step C (i != 2^(k-1), non-variable rows)\n      else\n      {\n        unsigned offset = bidirectional && ( hamming_distance( i, ifunc[0u].to_ulong() ) < hamming_distance( i, func[0u].to_ulong() ) ) ? 1u : 0u;\n\n        // already empty?\n        if ( funcs[offset]->at( i ).none() ) continue;\n\n        // Find s?\n        using boost::adaptors::reversed;\n        unsigned s = n;\n        for ( unsigned j : boost::irange( 0u, n ) | reversed )\n        {\n          if ( funcs[offset]->at( i ).test( j ) && ( i & ( 1u << j ) ) == 0u )\n          {\n            s = j;\n            break;\n          }\n        }\n\n        assert( s != n );\n\n        // Before CNOTs\n        std::vector<unsigned> targets;\n        for ( unsigned j = 0u; j < n; ++j )\n        {\n          if ( j != s && funcs[offset]->at( i ).test( j ) )\n          {\n            apply_gate( circ, funcs, offset, insert_at, s, j );\n            targets += j;\n          }\n        }\n\n        // Toffoli Gate\n        std::vector<unsigned> controls;\n        for ( unsigned j = 0u; j < n; ++j )\n        {\n          if ( i & ( 1u << j ) )\n          {\n            controls += j;\n          }\n        }\n        apply_gate( circ, funcs, offset, insert_at, controls, s );\n\n        // After CNOTs\n        for ( unsigned j : targets )\n        {\n          apply_gate( circ, funcs, offset, insert_at, s, j );\n        }\n      }\n    }\n\n    return true;\n  }\n\n  truth_table_synthesis_func reed_muller_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 reed_muller_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": "c10f074ab1b3eb9cdc0885f7dec50a4eddf17dfe", "size": 11083, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "addons/cirkit-addon-reversible/src/reversible/synthesis/reed_muller_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/reed_muller_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/reed_muller_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": 28.6382428941, "max_line_length": 187, "alphanum_fraction": 0.5653703871, "num_tokens": 3091, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6187804337438501, "lm_q2_score": 0.4960938294709195, "lm_q1q2_score": 0.30697315497766314}}
{"text": "//\n// Copyright (c) 2002--2010\n// Toon Knapen, Karl Meerbergen, Kresimir Fresl,\n// Thomas Klimpel and Rutger ter Borg\n//\n// Distributed under the Boost Software License, Version 1.0.\n// (See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n//\n// THIS FILE IS AUTOMATICALLY GENERATED\n// PLEASE DO NOT EDIT!\n//\n\n#ifndef BOOST_NUMERIC_BINDINGS_LAPACK_DRIVER_GESDD_HPP\n#define BOOST_NUMERIC_BINDINGS_LAPACK_DRIVER_GESDD_HPP\n\n#include <boost/assert.hpp>\n#include <boost/numeric/bindings/begin.hpp>\n#include <boost/numeric/bindings/detail/array.hpp>\n#include <boost/numeric/bindings/is_column_major.hpp>\n#include <boost/numeric/bindings/is_complex.hpp>\n#include <boost/numeric/bindings/is_mutable.hpp>\n#include <boost/numeric/bindings/is_real.hpp>\n#include <boost/numeric/bindings/lapack/workspace.hpp>\n#include <boost/numeric/bindings/remove_imaginary.hpp>\n#include <boost/numeric/bindings/size.hpp>\n#include <boost/numeric/bindings/stride.hpp>\n#include <boost/numeric/bindings/traits/detail/utils.hpp>\n#include <boost/numeric/bindings/value_type.hpp>\n#include <boost/static_assert.hpp>\n#include <boost/type_traits/is_same.hpp>\n#include <boost/type_traits/remove_const.hpp>\n#include <boost/utility/enable_if.hpp>\n\n//\n// The LAPACK-backend for gesdd is the netlib-compatible backend.\n//\n#include <boost/numeric/bindings/lapack/detail/lapack.h>\n#include <boost/numeric/bindings/lapack/detail/lapack_option.hpp>\n\nnamespace boost {\nnamespace numeric {\nnamespace bindings {\nnamespace lapack {\n\n//\n// The detail namespace contains value-type-overloaded functions that\n// dispatch to the appropriate back-end LAPACK-routine.\n//\nnamespace detail {\n\n//\n// Overloaded function for dispatching to\n// * netlib-compatible LAPACK backend (the default), and\n// * float value-type.\n//\ninline std::ptrdiff_t gesdd( const char jobz, const fortran_int_t m,\n        const fortran_int_t n, float* a, const fortran_int_t lda, float* s,\n        float* u, const fortran_int_t ldu, float* vt,\n        const fortran_int_t ldvt, float* work, const fortran_int_t lwork,\n        fortran_int_t* iwork ) {\n    fortran_int_t info(0);\n    LAPACK_SGESDD( &jobz, &m, &n, a, &lda, s, u, &ldu, vt, &ldvt, work,\n            &lwork, iwork, &info );\n    return info;\n}\n\n//\n// Overloaded function for dispatching to\n// * netlib-compatible LAPACK backend (the default), and\n// * double value-type.\n//\ninline std::ptrdiff_t gesdd( const char jobz, const fortran_int_t m,\n        const fortran_int_t n, double* a, const fortran_int_t lda, double* s,\n        double* u, const fortran_int_t ldu, double* vt,\n        const fortran_int_t ldvt, double* work, const fortran_int_t lwork,\n        fortran_int_t* iwork ) {\n    fortran_int_t info(0);\n    LAPACK_DGESDD( &jobz, &m, &n, a, &lda, s, u, &ldu, vt, &ldvt, work,\n            &lwork, iwork, &info );\n    return info;\n}\n\n//\n// Overloaded function for dispatching to\n// * netlib-compatible LAPACK backend (the default), and\n// * complex<float> value-type.\n//\ninline std::ptrdiff_t gesdd( const char jobz, const fortran_int_t m,\n        const fortran_int_t n, std::complex<float>* a,\n        const fortran_int_t lda, float* s, std::complex<float>* u,\n        const fortran_int_t ldu, std::complex<float>* vt,\n        const fortran_int_t ldvt, std::complex<float>* work,\n        const fortran_int_t lwork, float* rwork, fortran_int_t* iwork ) {\n    fortran_int_t info(0);\n    LAPACK_CGESDD( &jobz, &m, &n, a, &lda, s, u, &ldu, vt, &ldvt, work,\n            &lwork, rwork, iwork, &info );\n    return info;\n}\n\n//\n// Overloaded function for dispatching to\n// * netlib-compatible LAPACK backend (the default), and\n// * complex<double> value-type.\n//\ninline std::ptrdiff_t gesdd( const char jobz, const fortran_int_t m,\n        const fortran_int_t n, std::complex<double>* a,\n        const fortran_int_t lda, double* s, std::complex<double>* u,\n        const fortran_int_t ldu, std::complex<double>* vt,\n        const fortran_int_t ldvt, std::complex<double>* work,\n        const fortran_int_t lwork, double* rwork, fortran_int_t* iwork ) {\n    fortran_int_t info(0);\n    LAPACK_ZGESDD( &jobz, &m, &n, a, &lda, s, u, &ldu, vt, &ldvt, work,\n            &lwork, rwork, iwork, &info );\n    return info;\n}\n\n} // namespace detail\n\n//\n// Value-type based template class. Use this class if you need a type\n// for dispatching to gesdd.\n//\ntemplate< typename Value, typename Enable = void >\nstruct gesdd_impl {};\n\n//\n// This implementation is enabled if Value is a real type.\n//\ntemplate< typename Value >\nstruct gesdd_impl< Value, typename boost::enable_if< is_real< Value > >::type > {\n\n    typedef Value value_type;\n    typedef typename remove_imaginary< Value >::type real_type;\n\n    //\n    // Static member function for user-defined workspaces, that\n    // * Deduces the required arguments for dispatching to LAPACK, and\n    // * Asserts that most arguments make sense.\n    //\n    template< typename MatrixA, typename VectorS, typename MatrixU,\n            typename MatrixVT, typename WORK, typename IWORK >\n    static std::ptrdiff_t invoke( const char jobz, MatrixA& a, VectorS& s,\n            MatrixU& u, MatrixVT& vt, detail::workspace2< WORK,\n            IWORK > work ) {\n        namespace bindings = ::boost::numeric::bindings;\n        BOOST_STATIC_ASSERT( (bindings::is_column_major< MatrixA >::value) );\n        BOOST_STATIC_ASSERT( (bindings::is_column_major< MatrixU >::value) );\n        BOOST_STATIC_ASSERT( (bindings::is_column_major< MatrixVT >::value) );\n        BOOST_STATIC_ASSERT( (boost::is_same< typename remove_const<\n                typename bindings::value_type< MatrixA >::type >::type,\n                typename remove_const< typename bindings::value_type<\n                VectorS >::type >::type >::value) );\n        BOOST_STATIC_ASSERT( (boost::is_same< typename remove_const<\n                typename bindings::value_type< MatrixA >::type >::type,\n                typename remove_const< typename bindings::value_type<\n                MatrixU >::type >::type >::value) );\n        BOOST_STATIC_ASSERT( (boost::is_same< typename remove_const<\n                typename bindings::value_type< MatrixA >::type >::type,\n                typename remove_const< typename bindings::value_type<\n                MatrixVT >::type >::type >::value) );\n        BOOST_STATIC_ASSERT( (bindings::is_mutable< MatrixA >::value) );\n        BOOST_STATIC_ASSERT( (bindings::is_mutable< VectorS >::value) );\n        BOOST_STATIC_ASSERT( (bindings::is_mutable< MatrixU >::value) );\n        BOOST_STATIC_ASSERT( (bindings::is_mutable< MatrixVT >::value) );\n        std::ptrdiff_t minmn = std::min< std::ptrdiff_t >( size_row(a),\n                size_column(a) );\n        BOOST_ASSERT( bindings::size(s) >= std::min<\n                std::ptrdiff_t >(bindings::size_row(a),\n                bindings::size_column(a)) );\n        BOOST_ASSERT( bindings::size(work.select(fortran_int_t())) >=\n                min_size_iwork( minmn ));\n        BOOST_ASSERT( bindings::size(work.select(real_type())) >=\n                min_size_work( bindings::size_row(a),\n                bindings::size_column(a), jobz, minmn ));\n        BOOST_ASSERT( bindings::size_column(a) >= 0 );\n        BOOST_ASSERT( bindings::size_minor(a) == 1 ||\n                bindings::stride_minor(a) == 1 );\n        BOOST_ASSERT( bindings::size_minor(u) == 1 ||\n                bindings::stride_minor(u) == 1 );\n        BOOST_ASSERT( bindings::size_minor(vt) == 1 ||\n                bindings::stride_minor(vt) == 1 );\n        BOOST_ASSERT( bindings::size_row(a) >= 0 );\n        BOOST_ASSERT( bindings::stride_major(a) >= std::max< std::ptrdiff_t >(1,\n                bindings::size_row(a)) );\n        BOOST_ASSERT( jobz == 'A' || jobz == 'S' || jobz == 'O' ||\n                jobz == 'N' );\n        return detail::gesdd( jobz, bindings::size_row(a),\n                bindings::size_column(a), bindings::begin_value(a),\n                bindings::stride_major(a), bindings::begin_value(s),\n                bindings::begin_value(u), bindings::stride_major(u),\n                bindings::begin_value(vt), bindings::stride_major(vt),\n                bindings::begin_value(work.select(real_type())),\n                bindings::size(work.select(real_type())),\n                bindings::begin_value(work.select(fortran_int_t())) );\n    }\n\n    //\n    // Static member function that\n    // * Figures out the minimal workspace requirements, and passes\n    //   the results to the user-defined workspace overload of the \n    //   invoke static member function\n    // * Enables the unblocked algorithm (BLAS level 2)\n    //\n    template< typename MatrixA, typename VectorS, typename MatrixU,\n            typename MatrixVT >\n    static std::ptrdiff_t invoke( const char jobz, MatrixA& a, VectorS& s,\n            MatrixU& u, MatrixVT& vt, minimal_workspace ) {\n        namespace bindings = ::boost::numeric::bindings;\n        std::ptrdiff_t minmn = std::min< std::ptrdiff_t >( size_row(a),\n                size_column(a) );\n        bindings::detail::array< real_type > tmp_work( min_size_work(\n                bindings::size_row(a), bindings::size_column(a), jobz,\n                minmn ) );\n        bindings::detail::array< fortran_int_t > tmp_iwork(\n                min_size_iwork( minmn ) );\n        return invoke( jobz, a, s, u, vt, workspace( tmp_work, tmp_iwork ) );\n    }\n\n    //\n    // Static member function that\n    // * Figures out the optimal workspace requirements, and passes\n    //   the results to the user-defined workspace overload of the \n    //   invoke static member\n    // * Enables the blocked algorithm (BLAS level 3)\n    //\n    template< typename MatrixA, typename VectorS, typename MatrixU,\n            typename MatrixVT >\n    static std::ptrdiff_t invoke( const char jobz, MatrixA& a, VectorS& s,\n            MatrixU& u, MatrixVT& vt, optimal_workspace ) {\n        namespace bindings = ::boost::numeric::bindings;\n        return invoke( jobz, a, s, u, vt, minimal_workspace() );\n    }\n\n    //\n    // Static member function that returns the minimum size of\n    // workspace-array work.\n    //\n    static std::ptrdiff_t min_size_work( const std::ptrdiff_t m,\n            const std::ptrdiff_t n, const char jobz,\n            const std::ptrdiff_t minmn ) {\n        if ( n == 0 ) return 1;\n        if ( jobz == 'N' ) return 3*minmn + std::max<\n                std::ptrdiff_t >( std::max< std::ptrdiff_t >(m,n), 7*minmn );\n        if ( jobz == 'O' ) return 3*minmn*minmn + std::max<\n                std::ptrdiff_t >( std::max< std::ptrdiff_t >( m,n ),\n                5*minmn*minmn + 4*minmn );\n        return 3*minmn*minmn + std::max< std::ptrdiff_t >( std::max<\n                std::ptrdiff_t >( m,n ), 4*minmn*minmn + 4*minmn );\n    }\n\n    //\n    // Static member function that returns the minimum size of\n    // workspace-array iwork.\n    //\n    static std::ptrdiff_t min_size_iwork( const std::ptrdiff_t minmn ) {\n            return 8*minmn;\n    }\n};\n\n//\n// This implementation is enabled if Value is a complex type.\n//\ntemplate< typename Value >\nstruct gesdd_impl< Value, typename boost::enable_if< is_complex< Value > >::type > {\n\n    typedef Value value_type;\n    typedef typename remove_imaginary< Value >::type real_type;\n\n    //\n    // Static member function for user-defined workspaces, that\n    // * Deduces the required arguments for dispatching to LAPACK, and\n    // * Asserts that most arguments make sense.\n    //\n    template< typename MatrixA, typename VectorS, typename MatrixU,\n            typename MatrixVT, typename WORK, typename RWORK, typename IWORK >\n    static std::ptrdiff_t invoke( const char jobz, MatrixA& a, VectorS& s,\n            MatrixU& u, MatrixVT& vt, detail::workspace3< WORK, RWORK,\n            IWORK > work ) {\n        namespace bindings = ::boost::numeric::bindings;\n        BOOST_STATIC_ASSERT( (bindings::is_column_major< MatrixA >::value) );\n        BOOST_STATIC_ASSERT( (bindings::is_column_major< MatrixU >::value) );\n        BOOST_STATIC_ASSERT( (bindings::is_column_major< MatrixVT >::value) );\n        BOOST_STATIC_ASSERT( (boost::is_same< typename remove_const<\n                typename bindings::value_type< MatrixA >::type >::type,\n                typename remove_const< typename bindings::value_type<\n                MatrixU >::type >::type >::value) );\n        BOOST_STATIC_ASSERT( (boost::is_same< typename remove_const<\n                typename bindings::value_type< MatrixA >::type >::type,\n                typename remove_const< typename bindings::value_type<\n                MatrixVT >::type >::type >::value) );\n        BOOST_STATIC_ASSERT( (bindings::is_mutable< MatrixA >::value) );\n        BOOST_STATIC_ASSERT( (bindings::is_mutable< VectorS >::value) );\n        BOOST_STATIC_ASSERT( (bindings::is_mutable< MatrixU >::value) );\n        BOOST_STATIC_ASSERT( (bindings::is_mutable< MatrixVT >::value) );\n        std::ptrdiff_t minmn = std::min< std::ptrdiff_t >( size_row(a),\n                size_column(a) );\n        BOOST_ASSERT( bindings::size(s) >= std::min<\n                std::ptrdiff_t >(bindings::size_row(a),\n                bindings::size_column(a)) );\n        BOOST_ASSERT( bindings::size(work.select(fortran_int_t())) >=\n                min_size_iwork( minmn ));\n        BOOST_ASSERT( bindings::size(work.select(real_type())) >=\n                min_size_rwork( minmn, jobz ));\n        BOOST_ASSERT( bindings::size(work.select(value_type())) >=\n                min_size_work( bindings::size_row(a),\n                bindings::size_column(a), jobz, minmn ));\n        BOOST_ASSERT( bindings::size_column(a) >= 0 );\n        BOOST_ASSERT( bindings::size_minor(a) == 1 ||\n                bindings::stride_minor(a) == 1 );\n        BOOST_ASSERT( bindings::size_minor(u) == 1 ||\n                bindings::stride_minor(u) == 1 );\n        BOOST_ASSERT( bindings::size_minor(vt) == 1 ||\n                bindings::stride_minor(vt) == 1 );\n        BOOST_ASSERT( bindings::size_row(a) >= 0 );\n        BOOST_ASSERT( bindings::stride_major(a) >= std::max< std::ptrdiff_t >(1,\n                bindings::size_row(a)) );\n        BOOST_ASSERT( jobz == 'A' || jobz == 'S' || jobz == 'O' ||\n                jobz == 'N' );\n        return detail::gesdd( jobz, bindings::size_row(a),\n                bindings::size_column(a), bindings::begin_value(a),\n                bindings::stride_major(a), bindings::begin_value(s),\n                bindings::begin_value(u), bindings::stride_major(u),\n                bindings::begin_value(vt), bindings::stride_major(vt),\n                bindings::begin_value(work.select(value_type())),\n                bindings::size(work.select(value_type())),\n                bindings::begin_value(work.select(real_type())),\n                bindings::begin_value(work.select(fortran_int_t())) );\n    }\n\n    //\n    // Static member function that\n    // * Figures out the minimal workspace requirements, and passes\n    //   the results to the user-defined workspace overload of the \n    //   invoke static member function\n    // * Enables the unblocked algorithm (BLAS level 2)\n    //\n    template< typename MatrixA, typename VectorS, typename MatrixU,\n            typename MatrixVT >\n    static std::ptrdiff_t invoke( const char jobz, MatrixA& a, VectorS& s,\n            MatrixU& u, MatrixVT& vt, minimal_workspace ) {\n        namespace bindings = ::boost::numeric::bindings;\n        std::ptrdiff_t minmn = std::min< std::ptrdiff_t >( size_row(a),\n                size_column(a) );\n        bindings::detail::array< value_type > tmp_work( min_size_work(\n                bindings::size_row(a), bindings::size_column(a), jobz,\n                minmn ) );\n        bindings::detail::array< real_type > tmp_rwork( min_size_rwork( minmn,\n                jobz ) );\n        bindings::detail::array< fortran_int_t > tmp_iwork(\n                min_size_iwork( minmn ) );\n        return invoke( jobz, a, s, u, vt, workspace( tmp_work, tmp_rwork,\n                tmp_iwork ) );\n    }\n\n    //\n    // Static member function that\n    // * Figures out the optimal workspace requirements, and passes\n    //   the results to the user-defined workspace overload of the \n    //   invoke static member\n    // * Enables the blocked algorithm (BLAS level 3)\n    //\n    template< typename MatrixA, typename VectorS, typename MatrixU,\n            typename MatrixVT >\n    static std::ptrdiff_t invoke( const char jobz, MatrixA& a, VectorS& s,\n            MatrixU& u, MatrixVT& vt, optimal_workspace ) {\n        namespace bindings = ::boost::numeric::bindings;\n        std::ptrdiff_t minmn = std::min< std::ptrdiff_t >( size_row(a),\n                size_column(a) );\n        value_type opt_size_work;\n        bindings::detail::array< real_type > tmp_rwork( min_size_rwork( minmn,\n                jobz ) );\n        bindings::detail::array< fortran_int_t > tmp_iwork(\n                min_size_iwork( minmn ) );\n        detail::gesdd( jobz, bindings::size_row(a),\n                bindings::size_column(a), bindings::begin_value(a),\n                bindings::stride_major(a), bindings::begin_value(s),\n                bindings::begin_value(u), bindings::stride_major(u),\n                bindings::begin_value(vt), bindings::stride_major(vt),\n                &opt_size_work, -1, bindings::begin_value(tmp_rwork),\n                bindings::begin_value(tmp_iwork) );\n        bindings::detail::array< value_type > tmp_work(\n                traits::detail::to_int( opt_size_work ) );\n        return invoke( jobz, a, s, u, vt, workspace( tmp_work, tmp_rwork,\n                tmp_iwork ) );\n    }\n\n    //\n    // Static member function that returns the minimum size of\n    // workspace-array work.\n    //\n    static std::ptrdiff_t min_size_work( const std::ptrdiff_t m,\n            const std::ptrdiff_t n, const char jobz,\n            const std::ptrdiff_t minmn ) {\n        if ( n == 0 ) return 1;\n        if ( jobz == 'N' ) return 2*minmn + std::max< std::ptrdiff_t >( m,n );\n        if ( jobz == 'O' ) return 2*(minmn*minmn + minmn) + std::max<\n                std::ptrdiff_t >( m, n );\n        return minmn*minmn + 2*minmn + std::max< std::ptrdiff_t >( m, n );\n    }\n\n    //\n    // Static member function that returns the minimum size of\n    // workspace-array rwork.\n    //\n    static std::ptrdiff_t min_size_rwork( const std::ptrdiff_t minmn,\n            const char jobz ) {\n        if ( jobz == 'N' ) return 5*minmn;\n        return 5*minmn*minmn + 7*minmn;\n    }\n\n    //\n    // Static member function that returns the minimum size of\n    // workspace-array iwork.\n    //\n    static std::ptrdiff_t min_size_iwork( const std::ptrdiff_t minmn ) {\n            return 8*minmn;\n    }\n};\n\n\n//\n// Functions for direct use. These functions are overloaded for temporaries,\n// so that wrapped types can still be passed and used for write-access. In\n// addition, if applicable, they are overloaded for user-defined workspaces.\n// Calls to these functions are passed to the gesdd_impl classes. In the \n// documentation, most overloads are collapsed to avoid a large number of\n// prototypes which are very similar.\n//\n\n//\n// Overloaded function for gesdd. Its overload differs for\n// * User-defined workspace\n//\ntemplate< typename MatrixA, typename VectorS, typename MatrixU,\n        typename MatrixVT, typename Workspace >\ninline typename boost::enable_if< detail::is_workspace< Workspace >,\n        std::ptrdiff_t >::type\ngesdd( const char jobz, MatrixA& a, VectorS& s, MatrixU& u, MatrixVT& vt,\n        Workspace work ) {\n    return gesdd_impl< typename bindings::value_type<\n            MatrixA >::type >::invoke( jobz, a, s, u, vt, work );\n}\n\n//\n// Overloaded function for gesdd. Its overload differs for\n// * Default workspace-type (optimal)\n//\ntemplate< typename MatrixA, typename VectorS, typename MatrixU,\n        typename MatrixVT >\ninline typename boost::disable_if< detail::is_workspace< MatrixVT >,\n        std::ptrdiff_t >::type\ngesdd( const char jobz, MatrixA& a, VectorS& s, MatrixU& u,\n        MatrixVT& vt ) {\n    return gesdd_impl< typename bindings::value_type<\n            MatrixA >::type >::invoke( jobz, a, s, u, vt,\n            optimal_workspace() );\n}\n\n} // namespace lapack\n} // namespace bindings\n} // namespace numeric\n} // namespace boost\n\n#endif\n", "meta": {"hexsha": "fa6b54a46f886598210c208e3770edb1f90f94bc", "size": 20182, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "externals/numeric_bindings/boost/numeric/bindings/lapack/driver/gesdd.hpp", "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/boost/numeric/bindings/lapack/driver/gesdd.hpp", "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/boost/numeric/bindings/lapack/driver/gesdd.hpp", "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": 43.3090128755, "max_line_length": 84, "alphanum_fraction": 0.631602418, "num_tokens": 4974, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6334102636778401, "lm_q2_score": 0.48438008427698437, "lm_q1q2_score": 0.3068113169021791}}
{"text": "/*******************************************************************************\n *\n * Standard domain of intervals.\n *\n * Author: Arnaud J. Venet (arnaud.j.venet@nasa.gov)\n *\n * Contributors: Alexandre C. D. Wimmers (alexandre.c.wimmers@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 <boost/optional.hpp>\n#include <crab/common/types.hpp>\n#include <crab/common/stats.hpp>\n#include <crab/common/bignums.hpp>\n#include <crab/domains/linear_constraints.hpp>\n#include <crab/domains/linear_interval_solver.hpp>\n#include <crab/domains/separate_domains.hpp>\n#include <crab/domains/operators_api.hpp>\n#include <crab/domains/backward_assign_operations.hpp>\n\nnamespace ikos {\n\n  template< typename Number >\n  class bound;\n\n  template< typename Number >\n  class bound: public writeable {\n    \n    template < typename Any > friend class bound;\n\n  public:\n    typedef bound< Number > bound_t;\n    \n  private:\n    bool _is_infinite;\n    Number _n;\n\n  private:\n    bound();\n    \n    bound(bool is_infinite, Number n): _is_infinite(is_infinite), _n(n) {\n      if (is_infinite){\n        if (n > 0)\n          this->_n = 1;\n        else \n          this->_n = -1;\n      }\n    }\n    \n  public:\n    static bound_t min(bound_t x, bound_t y) {\n      return (x.operator<=(y) ? x : y);\n    }\n\n    static bound_t min(bound_t x, bound_t y, bound_t z) {\n      return min(x, min(y, z));\n    }\n\n    static bound_t min(bound_t x, bound_t y, bound_t z, bound_t t) {\n      return min(x, min(y, z, t));\n    }\n\n    static bound_t max(bound_t x, bound_t y) {\n      return (x.operator<=(y) ? y : x);\n    }\n\n    static bound_t max(bound_t x, bound_t y, bound_t z) {\n      return max(x, max(y, z));\n    }\n\n    static bound_t max(bound_t x, bound_t y, bound_t z, bound_t t) {\n      return max(x, max(y, z, t));\n    }\n\n    static bound_t plus_infinity() {\n      return bound_t(true, 1);\n    }\n    \n    static bound_t minus_infinity() {\n      return bound_t(true, -1);\n    }\n    \n  public:\n    bound(int n): _is_infinite(false), _n(n) { }\n\n    bound(std::string s): _n(1) {\n      if (s == \"+oo\") {\n        this->_is_infinite = true;\n      } else if (s == \"-oo\") {\n        this->_is_infinite = true;\n        this->_n = -1;\n      } else {\n        this->_is_infinite = false;\n        this->_n = Number(s);\n      }\n    }\n\n    bound(Number n): _is_infinite(false), _n(n) { }\n    \n    bound(const bound_t& o): writeable(), _is_infinite(o._is_infinite), _n(o._n) { }\n    \n    bound_t& operator=(const bound_t &o){\n      if (this != &o) {\n        this->_is_infinite = o._is_infinite;\n        this->_n = o._n;\n      }\n      return *this;\n    }\n    \n    bool is_infinite() const {\n      return this->_is_infinite;\n    }\n    \n    bool is_finite() const {\n      return !this->_is_infinite;\n    }\n\n    bool is_plus_infinity() const {\n      return (this->is_infinite() && this->_n > 0);\n    }\n    \n    bool is_minus_infinity() const {\n      return (this->is_infinite() && this->_n < 0);\n    }\n    \n    bound_t operator-() const {\n      return bound_t(this->_is_infinite, -this->_n);\n    }\n    \n    bound_t operator+(bound_t x) const {\n      if (this->is_finite() && x.is_finite()) {\n        return bound_t(this->_n + x._n);\n      } else if (this->is_finite() && x.is_infinite()) {\n        return x;\n      } else if (this->is_infinite() && x.is_finite()) {\n        return *this;\n      } else if (this->_n == x._n) {\n        return *this;\n      } else {\n        CRAB_ERROR(\"Bound: undefined operation -oo + +oo\");\n      }\n    }\n\n    bound_t& operator+=(bound_t x)  {\n      return this->operator=(this->operator+(x));\n    }\n\t\t\n    bound_t operator-(bound_t x) const {\n      return this->operator+(x.operator-());\n    }\n\t\t\n    bound_t& operator-=(bound_t x)  {\n      return this->operator=(this->operator-(x));\n    }\n    \n    bound_t operator*(bound_t x) const {\n      if (x._n == 0) \n        return x;\n      else if (this->_n == 0)\n        return *this;\n      else \n        return bound_t(this->_is_infinite || x._is_infinite, this->_n * x._n);\n    }\n\t\t\n    bound_t& operator*=(bound_t x)  {\n      return this->operator=(this->operator*(x));\n    }\n    \n    bound_t operator/(bound_t x) const {\n      if (x._n == 0) {\n        CRAB_ERROR(\"Bound: division by zero\");\n      } else if (this->is_finite() && x.is_finite()) {\n        return bound_t(false, _n / x._n);\n      } else if (this->is_finite() && x.is_infinite()) {\n        if (this->_n > 0) {\n          return x;\n        } else if (this->_n == 0) {\n          return *this;\n        } else {\n          return x.operator-();\n        }\n      } else if (this->is_infinite() && x.is_finite()) {\n        if (x._n > 0) {\n          return *this;\n        } else {\n          return this->operator-();\n        }\n      } else {\n        return bound_t(true, this->_n * x._n);\n      }\n    }\n    \n    bound_t& operator/=(bound_t x) {\n      return this->operator=(this->operator/(x));\n    }\n    \n    bool operator<(bound_t x) const {\n      return !this->operator>=(x);\n    }\n\n    bool operator>(bound_t x) const {\n      return !this->operator<=(x);\n    }\n\n    bool operator==(bound_t x) const {\n      return (this->_is_infinite == x._is_infinite && this->_n == x._n);\n    }\n    \n    bool operator!=(bound_t x) const {\n      return !this->operator==(x);\n    }\n    \n    /*\toperator<= and operator>= use a somewhat optimized implementation.\n     *\tresults include up to 20% improvements in performance in the octagon domain\n     *\tover a more naive implementation.\n     */\n    bool operator<=(bound_t x) const {\n      if(this->_is_infinite xor x._is_infinite){\n        if(this->_is_infinite){\n          return this->_n < 0;\n        }\n        return x._n > 0;\n      }\n      return this->_n <= x._n;\n    }\n    \n    bool operator>=(bound_t x) const {\n      if(this->_is_infinite xor x._is_infinite){\n        if(this->_is_infinite){\n          return this->_n > 0;\n        }\n        return x._n < 0;\n      }\n      return this->_n >= x._n;\n    }\n    \n    bound_t abs() const {\n      if (this->operator>=(0)) {\n        return *this;\n      } else {\n        return this->operator-();\n      }\n    }\n    \n    boost::optional< Number > number() const {\n      if (this->is_infinite()) {\n        return boost::optional< Number >();\n      } else {\n        return boost::optional< Number >(this->_n);\n      }\n    }\n    \n    void write(crab::crab_os& o) {\n      if (this->is_plus_infinity()) {\n        o << \"+oo\";\n      } else if (this->is_minus_infinity()) {\n        o << \"-oo\";\n      } else {\n        o << this->_n;\n      }\n    }\n    \n  }; // class bound\n\n  typedef bound< z_number > z_bound;\n  typedef bound< q_number > q_bound;\n\n\n  namespace bounds_impl {\n    // Conversion between z_bound and q_bound\n    // template<class B1, class B2>\n    // inline void convert_bounds(B1 b1, B2& b2);\n    \n    inline void convert_bounds(z_bound b1, z_bound &b2)\n    { std::swap (b1,b2); }\n    inline void convert_bounds(q_bound b1, q_bound &b2)\n    { std::swap (b1,b2); }\n    inline void convert_bounds(z_bound b1, q_bound &b2)\n    {\n      if (b1.is_plus_infinity())\n\tb2 = q_bound::plus_infinity();\n      else if (b1.is_minus_infinity())\n\tb2 = q_bound::minus_infinity();\n      else\n\tb2 = q_bound (q_number(*b1.number()));\n    }\n    inline void convert_bounds(q_bound b1, z_bound &b2)\n    {\n      if (b1.is_plus_infinity())\n\tb2 = z_bound::plus_infinity();\n      else if (b1.is_minus_infinity())\n\tb2 = z_bound::minus_infinity();\n      else\n\tb2 = z_bound ((*(b1.number())).round_to_lower ());\n    }\n  }\n\n  \n  template< typename Number >\n  class interval;\n\n  template< typename Number >\n  class interval: public writeable {\n    \n  public:\n    typedef bound< Number > bound_t;\n    typedef interval< Number > interval_t;\n    \n  private:\n    bound_t _lb;\n    bound_t _ub;\n\n  public:\n    static interval_t top() {\n      return interval_t(bound_t::minus_infinity(), bound_t::plus_infinity());\n    }\n\n    static interval_t bottom() {\n      return interval_t();\n    }\n\n  private:\n    interval(): _lb(0), _ub(-1) { }\n\n    static Number abs(Number x) { return x < 0 ? -x : x; }\n    \n    static Number max(Number x, Number y) { return x.operator<=(y) ? y : x; }\n    \n    static Number min(Number x, Number y) { return x.operator<(y) ? x : y; }\n    \n  public:\n    interval(bound_t lb, bound_t ub): _lb(lb), _ub(ub) { \n      if (lb > ub) {\n        this->_lb = 0;\n        this->_ub = -1;\n      }\n    }\n    \n    interval(bound_t b): _lb(b), _ub(b) { \n      if (b.is_infinite()) {\n        this->_lb = 0;\n        this->_ub = -1;\t\n      }\n    }\n\n    interval(Number n): _lb(n), _ub(n) { }\n\n    interval(std::string b): _lb(b), _ub(b) { \n      if (this->_lb.is_infinite()) {\n        this->_lb = 0;\n        this->_ub = -1;\t\n      }\n    }\n\n    interval(const interval_t& i): writeable(), _lb(i._lb), _ub(i._ub) { }\n    \n    interval_t& operator=(interval_t i){\n      this->_lb = i._lb;\n      this->_ub = i._ub;\n      return *this;\n    }\n\n    bound_t lb() const {\n      return this->_lb;\n    }\n\n    bound_t ub() const {\n      return this->_ub;\n    }\n\n    bool is_bottom() const {\n      return (this->_lb > this->_ub);\n    }\n    \n    bool is_top() const {\n      return (this->_lb.is_infinite() && this->_ub.is_infinite());\n    }\n    \n    interval_t lower_half_line() const {\n      return interval_t(bound_t::minus_infinity(), this->_ub);\n    }\n    \n    interval_t upper_half_line() const {\n      return interval_t(this->_lb, bound_t::plus_infinity());\n    }\n\n    bool operator==(interval_t x) const {\n      if (is_bottom()) {\n        return x.is_bottom();\n      } else {\n        return (this->_lb == x._lb) && (this->_ub == x._ub);\n      }\n    }\n    \n    bool operator!=(interval_t x) const {\n      return !this->operator==(x);\n    }\n\n    bool operator<=(interval_t x) const {\n      if (this->is_bottom()) {\n        return true;\n      } else if (x.is_bottom()) {\n        return false;\n      } else {\n        return (x._lb <= this->_lb) && (this->_ub <= x._ub);\n      }\n    }\n\n    interval_t operator|(interval_t x) const {\n      if (this->is_bottom()) {\n        return x;\n      } else if (x.is_bottom()) {\n        return *this;\n      } else {\n\treturn interval_t(bound_t::min(this->_lb, x._lb), \n                            bound_t::max(this->_ub, x._ub));\n      }\n    }\n\n    interval_t operator&(interval_t x) const {\n      if (this->is_bottom() || x.is_bottom()) {\n        return this->bottom();\n      } else {\n        return interval_t(bound_t::max(this->_lb, x._lb), \n                          bound_t::min(this->_ub, x._ub));\n      }\n    }\n    \n    interval_t operator||(interval_t x) const {\n      if (this->is_bottom()) {\n\treturn x;\n      } else if (x.is_bottom()) {\n\treturn *this;\n      } else {\n        return interval_t(x._lb < this->_lb ? \n                          bound_t::minus_infinity() : \n                          this->_lb, \n                          this->_ub < x._ub ?\n                          bound_t::plus_infinity() : \n                          this->_ub);\n      }\n    }\n\n    template<typename Thresholds>\n    interval_t widening_thresholds (interval_t x, const Thresholds &ts) {\n      if (this->is_bottom()) {\n\treturn x;\n      } else if (x.is_bottom()) {\n\treturn *this;\n      } else {\n        bound_t lb = (x._lb < this->_lb ? ts.get_prev (x._lb) : this->_lb);\n        bound_t ub = (this->_ub < x._ub ? ts.get_next (x._ub) :  this->_ub);            \n        return interval_t(lb, ub);\n      }\n    }\n\n    interval_t operator&&(interval_t x) const {\n      if (this->is_bottom() || x.is_bottom()) {\n        return this->bottom();\n      } else {\n        return interval_t(this->_lb.is_infinite() && x._lb.is_finite() ? \n                          x._lb : this->_lb, \n                          this->_ub.is_infinite() && x._ub.is_finite() ?\n                          x._ub : this->_ub);\n      }\n    }\n\n    interval_t operator+(interval_t x) const {\n      if (this->is_bottom() || x.is_bottom()) {\n        return this->bottom();\n      } else {\n\treturn interval_t(this->_lb + x._lb, this->_ub + x._ub);\n      }\n    }\n    \n    interval_t& operator+=(interval_t x) {\n      return this->operator=(this->operator+(x));\n    }\n    \n    interval_t operator-() const {\n      if (this->is_bottom()) {\n        return this->bottom();\n      } else {\n        return interval_t(-this->_ub, -this->_lb);\n      }\n    }\n    \n    interval_t operator-(interval_t x) const {\n      if (this->is_bottom() || x.is_bottom()) {\n        return this->bottom();\n      } else {\n        return interval_t(this->_lb - x._ub, this->_ub - x._lb);\n      }\n    }\n    \n    interval_t& operator-=(interval_t x) {\n      return this->operator=(this->operator-(x));\n    }\n    \n    interval_t operator*(interval_t x) const {\n      if (this->is_bottom() || x.is_bottom()) {\n        return this->bottom();\n      } else {\n        bound_t ll = this->_lb * x._lb;\n        bound_t lu = this->_lb * x._ub;\n        bound_t ul = this->_ub * x._lb;\n        bound_t uu = this->_ub * x._ub;\n        return interval_t(bound_t::min(ll, lu, ul, uu), \n                          bound_t::max(ll, lu, ul, uu));\n      }\n    }\n    \n    interval_t& operator*=(interval_t x) {\n      return this->operator=(this->operator*(x));\n    }\n    \n    interval_t operator/(interval_t x) const;\n\n    interval_t& operator/=(interval_t x) {\n      return this->operator=(this->operator/(x));\n    }   \n    \n    boost::optional< Number > singleton() const {\n      if (!this->is_bottom() && this->_lb == this->_ub) {\n        return this->_lb.number();\n      } else {\n        return boost::optional< Number >();\n      }\n    }\n    \n    bool operator[](Number n) const {\n      if (this->is_bottom()) {\n        return false;\n      } else {\n        bound_t b(n);\n        return (this->_lb <= b) && (b <= this->_ub);\n      }\n    }\n    \n    void write(crab::crab_os& o) {\n      if (is_bottom()) {\n        o << \"_|_\";\n      } else {\n        o << \"[\" << _lb << \", \" << _ub << \"]\";\n      }\n    }    \n    \n    // division and remainder operations\n\n    interval_t UDiv(interval_t x ) const {\n      if (this->is_bottom() || x.is_bottom()) {\n        return this->bottom();\n      } else {\n        return this->top();\n      }\n    }\n\n    interval_t SRem(interval_t x)  const {\n      if (this->is_bottom() || x.is_bottom()) {\n        return this->bottom();\n      } else {\n        return this->top();\n      }\n    }\n\n    interval_t URem(interval_t x)  const {\n      if (this->is_bottom() || x.is_bottom()) {\n        return this->bottom();\n      } else {\n        return this->top();\n      }\n    }\n\n    // bitwise operations\n    interval_t And(interval_t x) const {\n      if (this->is_bottom() || x.is_bottom()) {\n        return this->bottom();\n      } else {\n        return this->top();\n      }\n    }\n    \n    interval_t Or(interval_t x)  const {\n      if (this->is_bottom() || x.is_bottom()) {\n        return this->bottom();\n      } else {\n        return this->top();\n      }\n    }\n    \n    interval_t Xor(interval_t x) const { return this->Or(x); }\n    \n    interval_t Shl(interval_t x) const {\n      if (this->is_bottom() || x.is_bottom()) {\n        return this->bottom();\n      } else {\n        return this->top();\n      }\n    }\n\n    interval_t LShr(interval_t  x) const {\n      if (this->is_bottom() || x.is_bottom()) {\n        return this->bottom();\n      } else {\n        return this->top();\n      }\n    }\n\n    interval_t AShr(interval_t  x) const {\n      if (this->is_bottom() || x.is_bottom()) {\n        return this->bottom();\n      } else {\n        return this->top();\n      }\n    }\n    \n  };//  class interval\n\n  template<>\n  inline interval< q_number > interval< q_number >::\n  operator/(interval< q_number > x) const {\n    if (this->is_bottom() || x.is_bottom()) {\n      return this->bottom();\n    } else {\n      boost::optional< q_number > d = x.singleton();\n      if (d && *d == 0) {\n        // [_, _] / 0 = _|_\n        return this->bottom();\n      } else if (x[0]) {\n        boost::optional< q_number > n = this->singleton();\n        if (n && *n == 0) {\n          // 0 / [_, _] = 0\n          return interval_t(q_number(0));\n        } else {\n          return this->top();\n        }\n      } else {\n        bound_t ll = this->_lb / x._lb;\n        bound_t lu = this->_lb / x._ub;\n        bound_t ul = this->_ub / x._lb;\n        bound_t uu = this->_ub / x._ub;\n        return interval_t(bound_t::min(ll, lu, ul, uu), \n                          bound_t::max(ll, lu, ul, uu));\n      }\n    }\n  }\n\n  template<>\n  inline interval< z_number > interval< z_number >::\n  operator/(interval< z_number > x) const {\n    if (this->is_bottom() || x.is_bottom()) {\n      return this->bottom();\n    } else {\n      // Divisor is a singleton:\n      //   the linear interval solver can perform many divisions where\n      //   the divisor is a singleton interval. We optimize for this case.\n      if (boost::optional<z_number> n = x.singleton()) {\n\tz_number c = *n;\n\tif (c == 1) {\n\t  return *this;\n\t} else if (c > 0) {\n\t  return interval_t(_lb / c, _ub / c);\n\t} else if (c < 0) {\n\t  return interval_t(_ub / c, _lb / c);\n\t} else {}\n      }\n      // Divisor is not a singleton\n      typedef interval< z_number > z_interval;\n      if (x[0]) {\n        z_interval l(x._lb, z_bound(-1));\n        z_interval u(z_bound(1), x._ub);\n        return (this->operator/(l) | this->operator/(u));\n      } else if (this->operator[](0)) {\n        z_interval l(this->_lb, z_bound(-1));\n        z_interval u(z_bound(1), this->_ub);\n        return ((l / x) | (u / x) | z_interval(z_number(0)));\n      } else {\n        // Neither the dividend nor the divisor contains 0\n        z_interval a = (this->_ub < 0) ? \n            (*this + ((x._ub < 0) ? \n                      (x + z_interval(z_number(1))) : \n                      (z_interval(z_number(1)) - x))) : *this;\n\tbound_t ll = a._lb / x._lb;\n\tbound_t lu = a._lb / x._ub;\n\tbound_t ul = a._ub / x._lb;\n\tbound_t uu = a._ub / x._ub;\n\treturn interval_t(bound_t::min(ll, lu, ul, uu), \n\t\t\t  bound_t::max(ll, lu, ul, uu));\t\n      }\n    }\n  }\n\n\n  template <>\n  inline interval< z_number > interval< z_number >::\n  SRem(interval< z_number > x) const {\n    // note that the sign of the divisor does not matter\n    \n    if (this->is_bottom() || x.is_bottom()) {\n      return this->bottom();\n    } else if (this->singleton() && x.singleton()) {\n      z_number dividend = *this->singleton();\n      z_number divisor = *x.singleton();\n      \n      if (divisor == 0) {\n        return this->bottom();\n      }\n      \n      return interval_t(dividend % divisor);\n    } else if (x.ub().is_finite() && x.lb().is_finite()) {\n      z_number max_divisor = max(abs(*x.lb().number()), \n                                 abs(*x.ub().number()));\n      \n      if (max_divisor == 0) {\n        return this->bottom();\n      }\n      \n      if (this->lb() < 0) {\n        if (this->ub() > 0) {\n          return interval_t(-(max_divisor - 1), max_divisor - 1);\n        } else {\n          return interval_t(-(max_divisor - 1), 0);\n        }\n      } else {\n        return interval_t(0, max_divisor - 1);\n      }\n    } else {\n      return this->top();\n    }\n  }\n\n  template <>\n  inline interval< z_number > interval< z_number >::\n  URem(interval< z_number > x) const {\n    \n    if (this->is_bottom() || x.is_bottom()) {\n      return this->bottom();\n    } else if (this->singleton() && x.singleton()) {\n      z_number dividend = *this->singleton();\n      z_number divisor = *x.singleton();\n      \n      if (divisor < 0) {\n        return this->top();\n      } else if (divisor == 0) {\n        return this->bottom();\n      } else if (dividend < 0) {\n        // dividend is treated as an unsigned integer.\n        // we would need the size to be more precise\n        return interval_t(0, divisor - 1);\n      } else {\n        return interval_t(dividend % divisor);\n      }\n    } else if (x.ub().is_finite() && x.lb().is_finite()) {\n      z_number max_divisor = *x.ub().number();\n      \n      if (x.lb() < 0 || x.ub() < 0) {\n        return this->top();\n      } else if (max_divisor == 0) {\n        return this->bottom();\n      }\n      \n      return interval_t(0, max_divisor - 1);\n    } else {\n      return this->top();\n    }\n  }\n\n  template <>\n  inline interval< z_number > interval< z_number >::\n  And(interval< z_number > x) const {\n    if (this->is_bottom() || x.is_bottom()) {\n      return this->bottom();\n    } else {\n      boost::optional< z_number > left_op = this->singleton();\n      boost::optional< z_number > right_op = x.singleton();\n      \n      if (left_op && right_op) {\n        return interval_t((*left_op) & (*right_op));\n      } else if (this->lb() >= 0 && x.lb() >= 0) {\n        return interval_t(0, bound_t::min(this->ub(), x.ub()));\n      } else {\n        return this->top();\n      }\n    }\n  }\n\n  template <>\n  inline interval< z_number > interval< z_number >::\n  Or(interval< z_number > x) const {\n    if (this->is_bottom() || x.is_bottom()) {\n      return this->bottom();\n    } else {\n      boost::optional< z_number > left_op = this->singleton();\n      boost::optional< z_number > right_op = x.singleton();\n      \n      if (left_op && right_op) {\n        return interval_t((*left_op) | (*right_op));\n      } else if (this->lb() >= 0 && x.lb() >= 0) {\n        boost::optional< z_number > left_ub = this->ub().number();\n        boost::optional< z_number > right_ub = x.ub().number();\n        \n        if (left_ub && right_ub) {\n          z_number m = (*left_ub > *right_ub ? *left_ub : *right_ub); \n          return interval_t(0, m.fill_ones());\n        } else {\n          return interval_t(0, bound_t::plus_infinity());\n        }\n      } else {\n        return this->top();\n      }\n    }\n  }\n\n  template <>\n  inline interval< z_number > interval< z_number >::\n  Xor(interval< z_number > x)  const {\n    if (this->is_bottom() || x.is_bottom()) {\n      return this->bottom();\n    } else {\n      boost::optional< z_number > left_op = this->singleton();\n      boost::optional< z_number > right_op = x.singleton();\n      \n      if (left_op && right_op) {\n        return interval_t((*left_op) ^ (*right_op));\n      } else {\n        return this->Or(x);\n      }\n    }\n  }\n\n  template <>\n  inline interval< z_number > interval< z_number >::\n  Shl(interval< z_number > x) const {\n    if (this->is_bottom() || x.is_bottom()) {\n      return this->bottom();\n    } else {\n      if (boost::optional<z_number> shift = x.singleton()) {\n\tz_number k = *shift;\n\tif (k < 0) {\n\t  //CRAB_ERROR(\"lshr shift operand cannot be negative\");\n\t  return this->top();\n\t}\n\t// Some crazy linux drivers generate shl instructions with\n\t// huge shifts.  We limit the number of times the loop is run\n\t// to avoid wasting too much time on it.\n\tif (k <= 128) {\n\t  z_number factor = 1;\n\t  for (int i = 0; k > i ; i++) {\n\t    factor *= 2;\n\t  }\n\t  return (*this) * factor;\n\t}\n      } \n      return this->top();\n    }\n  }\n\n  template <>\n  inline interval< z_number > interval< z_number >::\n  AShr(interval< z_number > x) const {\n    if (this->is_bottom() || x.is_bottom()) {\n      return this->bottom();\n    } else {\n      if (boost::optional<z_number> shift = x.singleton()) {\n\tz_number k = *shift;\n\tif (k < 0) {\n\t  //CRAB_ERROR(\"ashr shift operand cannot be negative\");\n\t  return this->top();\n\t}\t  \n\t// Some crazy linux drivers generate ashr instructions with\n\t// huge shifts.  We limit the number of times the loop is run\n\t// to avoid wasting too much time on it.\n\tif (k <= 128) {\n\t  z_number factor = 1;\n\t  for (int i = 0; k > i; i++) {\n\t    factor *= 2;\n\t  }\n\t  return (*this) / factor;\n\t}\n      }\n      return this->top();\n    }\n  }\n  \n  template <>\n  inline interval< z_number > interval< z_number >::\n  LShr(interval< z_number > x) const {\n    if (this->is_bottom() || x.is_bottom()) {\n      return this->bottom();\n    } else {\n      if (boost::optional< z_number > shift = x.singleton()) {\n\tz_number k = *shift;\n\tif (k < 0) {\n\t  //CRAB_ERROR(\"lshr shift operand cannot be negative\");\n\t  return this->top();\n\t}\n\t// Some crazy linux drivers generate lshr instructions with\n\t// huge shifts.  We limit the number of times the loop is run\n\t// to avoid wasting too much time on it.\n\tif (k <= 128) {\n\t  if (this->lb() >= 0 && this->ub().is_finite() && shift) {\n\t    z_number lb = *this->lb().number();\n\t    z_number ub = *this->ub().number();\n\t    return interval< z_number >(lb >> k, ub >> k);\n\t  }\n\t}\n      }\n      return this->top();\n    }\n  }\n\n  template< typename Number >\n  inline interval< Number > operator+(Number c, interval< Number > x) {\n    return interval< Number >(c) + x;\n  }\n  \n  template< typename Number >\n  inline interval< Number > operator+(interval< Number > x, Number c) {\n    return x + interval< Number >(c);\n  }\n\n  template< typename Number >\n  inline interval< Number > operator*(Number c, interval< Number > x) {\n    return interval< Number >(c) * x;\n  }\n\n  template< typename Number >\n  inline interval< Number > operator*(interval< Number > x, Number c) {\n    return x * interval< Number >(c);\n  }\n\n  template< typename Number >\n  inline interval< Number > operator/(Number c, interval< Number > x) {\n    return interval< Number >(c) / x;\n  }\n\n  template< typename Number >\n  inline interval< Number > operator/(interval< Number > x, Number c) {\n    return x / interval< Number >(c);\n  }\n\n  template< typename Number >\n  inline interval< Number > operator-(Number c, interval< Number > x) {\n    return interval< Number >(c) - x;\n  }\n\n  template< typename Number >\n  inline interval< Number > operator-(interval< Number > x, Number c) {\n    return x - interval< Number >(c);\n  }\n\n  template < typename Number >\n  inline crab::crab_os& operator<<(crab::crab_os& o, interval< Number > i) {\n    i.write(o);\n    return o;\n  }\n\n  typedef interval< z_number > z_interval;\n  typedef interval< q_number > q_interval;  \n  \n  namespace linear_interval_solver_impl {\n\n    template<>\n    inline z_interval trim_interval(z_interval i, z_interval j) {\n      if (boost::optional<z_number> c = j.singleton()) {\n\tif (i.lb() == *c) {\n\t  return z_interval(*c + 1, i.ub());\n\t} else if (i.ub() == *c) {\n\t  return z_interval(i.lb(), *c - 1);\n\t} else {\n\t}\t\n      }\n      return i;\n    }\n    \n    template<>\n    inline q_interval trim_interval(q_interval i, q_interval /* j */) { \n      // No refinement possible for disequations over rational numbers\n      return i;\n    }\n\n    template<>\n    inline z_interval lower_half_line(z_interval i, bool /*is_signed*/) {\n      return i.lower_half_line();\n    }\n\n    template<>\n    inline q_interval lower_half_line(q_interval i, bool /*is_signed*/) {\n      return i.lower_half_line();\n    }\n\n    template<>\n    inline z_interval upper_half_line(z_interval i, bool /*is_signed*/) {\n      return i.upper_half_line();\n    }\n\n    template<>\n    inline q_interval upper_half_line(q_interval i, bool /*is_signed*/) {\n      return i.upper_half_line();\n    }\n  } // namespace linear_interval_solver_impl\n\n  template<typename Number, typename VariableName, std::size_t max_reduction_cycles = 10>\n  class interval_domain:\n    public crab::domains::\n    abstract_domain<Number, VariableName,\n\t\t    interval_domain<Number,VariableName,max_reduction_cycles> >  {\n  public:\n    typedef interval_domain<Number, VariableName, max_reduction_cycles> interval_domain_t;\n    typedef crab::domains::\n    abstract_domain<Number,VariableName,interval_domain_t> abstract_domain_t;\n    using typename abstract_domain_t::linear_expression_t;\n    using typename abstract_domain_t::linear_constraint_t;\n    using typename abstract_domain_t::linear_constraint_system_t;\n    using typename abstract_domain_t::variable_t;\n    using typename abstract_domain_t::number_t;\n    using typename abstract_domain_t::varname_t;\n    typedef interval<Number> interval_t;\n    \n  private:\n    typedef separate_domain<variable_t, interval_t> separate_domain_t;\n    typedef linear_interval_solver<Number, VariableName, separate_domain_t> solver_t;\n    \n  public:\n    typedef typename separate_domain_t::iterator iterator;\n    \n  private:\n    separate_domain_t _env;\n\n\n    interval_domain(separate_domain_t env): _env(env) { }\n\n  public:\n    static interval_domain_t top() {\n      return interval_domain(separate_domain_t::top());\n    }\n    \n    static interval_domain_t bottom() {\n      return interval_domain(separate_domain_t::bottom());\n    }\n\n  public:\n    interval_domain(): _env(separate_domain_t::top()) { }\n\n    interval_domain(const interval_domain_t& e): \n      _env(e._env) { \n      crab::CrabStats::count (getDomainName() + \".count.copy\");\n      crab::ScopedCrabStats __st__(getDomainName() + \".copy\");\n    }\n\n    interval_domain_t& operator=(const interval_domain_t& o) {\n      crab::CrabStats::count (getDomainName() + \".count.copy\");\n      crab::ScopedCrabStats __st__(getDomainName() + \".copy\");\n      if (this != &o)\n        this->_env = o._env;\n      return *this;\n    }\n\n    iterator begin() {\n      return this->_env.begin();\n    }\n\n    iterator end() {\n      return this->_env.end();\n    }\n\n    bool is_bottom() {\n      return this->_env.is_bottom();\n    }\n\n    bool is_top() {\n      return this->_env.is_top();\n    }\n\n    bool operator<=(interval_domain_t e) {\n      crab::CrabStats::count (getDomainName() + \".count.leq\");\n      crab::ScopedCrabStats __st__(getDomainName() + \".leq\");\n      return (this->_env <= e._env);\n    }\n\n    void operator|=(interval_domain_t e) {\n      crab::CrabStats::count (getDomainName() + \".count.join\");\n      crab::ScopedCrabStats __st__(getDomainName() + \".join\");\n      this->_env = this->_env | e._env;\n    }\n\n    interval_domain_t operator|(interval_domain_t e) {\n      crab::CrabStats::count (getDomainName() + \".count.join\");\n      crab::ScopedCrabStats __st__(getDomainName() + \".join\");\n      return (this->_env | e._env);\n    }\n\n    interval_domain_t operator&(interval_domain_t e) {\n      crab::CrabStats::count (getDomainName() + \".count.meet\");\n      crab::ScopedCrabStats __st__(getDomainName() + \".meet\");\n      return (this->_env & e._env);\n    }\n\n    interval_domain_t operator||(interval_domain_t e) {\n      crab::CrabStats::count (getDomainName() + \".count.widening\");\n      crab::ScopedCrabStats __st__(getDomainName() + \".widening\");\n      return (this->_env || e._env);\n    }\n\n    template<typename Thresholds>\n    interval_domain_t widening_thresholds (interval_domain_t e, const Thresholds &ts) {\n      crab::CrabStats::count (getDomainName() + \".count.widening\");\n      crab::ScopedCrabStats __st__(getDomainName() + \".widening\");\n      return this->_env.widening_thresholds (e._env, ts);\n    }\n\n    interval_domain_t operator&&(interval_domain_t e) {\n      crab::CrabStats::count (getDomainName() + \".count.narrowing\");\n      crab::ScopedCrabStats __st__(getDomainName() + \".narrowing\");\n      return (this->_env && e._env);\n    }\n\n    void set(variable_t v, interval_t i) {\n      crab::CrabStats::count (getDomainName() + \".count.assign\");\n      crab::ScopedCrabStats __st__(getDomainName() + \".assign\");\n      this->_env.set(v, i);\n    }\n\n    void set(variable_t v, Number n) {\n      crab::CrabStats::count (getDomainName() + \".count.assign\");\n      crab::ScopedCrabStats __st__(getDomainName() + \".assign\");\n      this->_env.set(v, interval_t(n));\n    }\n\n    void operator-=(variable_t v) {\n      crab::CrabStats::count (getDomainName() + \".count.forget\");\n      crab::ScopedCrabStats __st__(getDomainName() + \".forget\");\n      this->_env -= v;\n    }\n    \n    interval_t operator[](variable_t v) {\n      return this->_env[v];\n    }\n\n    interval_t operator[](linear_expression_t expr) {\n      interval_t r(expr.constant());\n      for (typename linear_expression_t::iterator it = expr.begin(); \n           it != expr.end(); ++it) {\n\tinterval_t c(it->first);\n\tr += c * this->_env[it->second];\n      }\n      return r;\n    }\n    \n    void operator+=(linear_constraint_system_t csts) {\n      crab::CrabStats::count (getDomainName() + \".count.add_constraints\");\n      crab::ScopedCrabStats __st__(getDomainName() + \".add_constraints\");\n      this->add(csts);\n    }\n\n    void add(linear_constraint_system_t csts, \n             std::size_t threshold = max_reduction_cycles) {\n      if (!this->is_bottom()) {\n\t// XXX: filter out unsigned linear inequalities\n\tlinear_constraint_system_t signed_csts;\n\tfor (auto const& c: csts) {\n\t  if (c.is_inequality() && c.is_unsigned()) {\n\t    CRAB_WARN(\"unsigned inequality skipped\");\n\t    continue;\n\t  }\n\t  signed_csts += c;\n\t}\n\tsolver_t solver(signed_csts, threshold);\n\tsolver.run(this->_env);\n      }\n    }\n\n    interval_domain_t operator+(linear_constraint_system_t csts) {\n      interval_domain_t e(this->_env);\n      e += csts;\n      return e;\n    }\n    \n    void assign(variable_t x, linear_expression_t e) {\n      crab::CrabStats::count (getDomainName() + \".count.assign\");\n      crab::ScopedCrabStats __st__(getDomainName() + \".assign\");\n\n      if (boost::optional<variable_t> v = e.get_variable ()) {\n        this->_env.set(x, this->_env [(*v)]);\n      }\n      else {\n        interval_t r = e.constant();\n        for (typename linear_expression_t::iterator it = e.begin(); \n             it != e.end(); ++it) {\n\tr += it->first * this->_env[it->second];\n        }\n        this->_env.set(x, r);\n      }\n    }\n\n    void apply(operation_t op, variable_t x, variable_t y, variable_t z) {\n      crab::CrabStats::count (getDomainName() + \".count.apply\");\n      crab::ScopedCrabStats __st__(getDomainName() + \".apply\");\n\n      interval_t yi = this->_env[y];\n      interval_t zi = this->_env[z];\n      interval_t xi = interval_t::bottom();\n      \n      switch (op) {\n      case OP_ADDITION: {\n\txi = yi + zi;\n\tbreak;\n      }\n      case OP_SUBTRACTION: {\n\txi = yi - zi;\n\tbreak;\n      }\n      case OP_MULTIPLICATION: {\n\txi = yi * zi;\n\tbreak;\n      }\n      case OP_DIVISION: {\n\txi = yi / zi;\n\tbreak;\n      }\n      }\n      this->_env.set(x, xi);\n    }\n\n    void apply(operation_t op, variable_t x, variable_t y, Number k) {\n      crab::CrabStats::count (getDomainName() + \".count.apply\");\n      crab::ScopedCrabStats __st__(getDomainName() + \".apply\");\n\n      interval_t yi = this->_env[y];\n      interval_t zi(k);\n      interval_t xi = interval_t::bottom();\n      \n      switch (op) {\n      case OP_ADDITION: {\n\txi = yi + zi;\n\tbreak;\n      }\n      case OP_SUBTRACTION: {\n\txi = yi - zi;\n\tbreak;\n      }\n      case OP_MULTIPLICATION: {\n\txi = yi * zi;\n\tbreak;\n      }\n      case OP_DIVISION: {\n\txi = yi / zi;\n\tbreak;\n      }\n      }\n      this->_env.set(x, xi);\n    }\n\n    void backward_assign (variable_t x, linear_expression_t e,\n\t\t\t  interval_domain_t inv) {\n      crab::domains::BackwardAssignOps<interval_domain_t>::\n\tassign (*this, x, e, inv);\n    }      \n    \n    void backward_apply (operation_t op,\n\t\t\t variable_t x, variable_t y, Number z,\n\t\t\t interval_domain_t inv) {\n      crab::domains::BackwardAssignOps<interval_domain_t>::\n\tapply(*this, op, x, y, z, inv);\n    }      \n    \n    void backward_apply(operation_t op,\n\t\t\tvariable_t x, variable_t y, variable_t z,\n\t\t\tinterval_domain_t inv) {\n      crab::domains::BackwardAssignOps<interval_domain_t>::\n\tapply(*this, op, x, y, z, inv);\n    }\n    \n    // cast_operators_api\n    \n    void apply(crab::domains::int_conv_operation_t /*op*/,\n\t       variable_t dst, variable_t src){\n      // ignore the widths \n      assign(dst, src);\n    }\n\n    // bitwise_operators_api\n    \n    void apply(bitwise_operation_t op, variable_t x, variable_t y, variable_t z){\n      crab::CrabStats::count (getDomainName() + \".count.apply\");\n      crab::ScopedCrabStats __st__(getDomainName() + \".apply\");\n\n      interval_t yi = this->_env[y];\n      interval_t zi = this->_env[z];\n      interval_t xi = interval_t::bottom();\n      \n      switch (op) {\n        case OP_AND: {\n\txi = yi.And(zi);\n\tbreak;\n        }\n        case OP_OR: {\n\txi = yi.Or(zi);\n\tbreak;\n        }\n        case OP_XOR: {\n\txi = yi.Xor(zi);\n\tbreak;\n        }\n        case OP_SHL: {\n\txi = yi.Shl(zi);\n\tbreak;\n        }\n        case OP_LSHR: {\n          xi = yi.LShr(zi);\n          break;\n        }\n        case OP_ASHR: {\n\txi = yi.AShr(zi);\n\tbreak;\n        }\n        default: \n          CRAB_ERROR(\"unreachable\");\n      }\n      this->_env.set(x, xi);\n    }\n    \n    void apply(bitwise_operation_t op, variable_t x, variable_t y, Number k){\n      crab::CrabStats::count (getDomainName() + \".count.apply\");\n      crab::ScopedCrabStats __st__(getDomainName() + \".apply\");\n\n      interval_t yi = this->_env[y];\n      interval_t zi(k);\n      interval_t xi = interval_t::bottom();\n      switch (op) {\n        case OP_AND: {\n\txi = yi.And(zi);\n\tbreak;\n        }\n        case OP_OR: {\n\txi = yi.Or(zi);\n\tbreak;\n        }\n        case OP_XOR: {\n\txi = yi.Xor(zi);\n\tbreak;\n        }\n        case OP_SHL: {\n\txi = yi.Shl(zi);\n\tbreak;\n        }\n        case OP_LSHR: {\n          xi = yi.LShr(zi);\n          break;\n        }\n        case OP_ASHR: {\n\txi = yi.AShr(zi);\n\tbreak;\n        }\n        default: \n          CRAB_ERROR(\"unreachable\");\n      }\n      this->_env.set(x, xi);\n    }\n    \n    // division_operators_api\n    \n    void apply(div_operation_t op, variable_t x, variable_t y, variable_t z){\n      crab::CrabStats::count (getDomainName() + \".count.apply\");\n      crab::ScopedCrabStats __st__(getDomainName() + \".apply\");\n\n      interval_t yi = this->_env[y];\n      interval_t zi = this->_env[z];\n      interval_t xi = interval_t::bottom();\n      \n      switch (op) {\n        case OP_SDIV: {\n\txi = yi / zi;\n\tbreak;\n        }\n        case OP_UDIV: {\n\txi = yi.UDiv(zi);\n\tbreak;\n        }\n        case OP_SREM: {\n\txi = yi.SRem(zi);\n\tbreak;\n        }\n        case OP_UREM: {\n\txi = yi.URem(zi);\n\tbreak;\n        }\n        default: \n          CRAB_ERROR(\"unreachable\");\n      }\n      this->_env.set(x, xi);\n\n    }\n\n    void apply(div_operation_t op, variable_t x, variable_t y, Number k){\n      crab::CrabStats::count (getDomainName() + \".count.apply\");\n      crab::ScopedCrabStats __st__(getDomainName() + \".apply\");\n\n      interval_t yi = this->_env[y];\n      interval_t zi(k);\n      interval_t xi = interval_t::bottom();\n      switch (op) {\n        case OP_SDIV: {\n\txi = yi / zi;\n\tbreak;\n        }\n        case OP_UDIV: {\n\txi = yi.UDiv(zi);\n\tbreak;\n        }\n        case OP_SREM: {\n\txi = yi.SRem(zi);\n\tbreak;\n        }\n        case OP_UREM: {\n\txi = yi.URem(zi);\n\tbreak;\n        }\n        default: \n          CRAB_ERROR(\"unreachable\");\n      }\n      this->_env.set(x, xi);\n    }\n\n    void write(crab::crab_os& o) {\n      this->_env.write(o);\n    }\n\n    linear_constraint_system_t to_linear_constraint_system ()\n    {\n      linear_constraint_system_t csts;\n      \n      if (this->is_bottom()) {\n        csts += linear_constraint_t::get_false();\n        return csts;\n      }\n\n      for (iterator it = this->_env.begin(); it != this->_env.end(); ++it)\n      {\n        variable_t v = it->first;\n        interval_t   i = it->second;\n        boost::optional<Number> lb = i.lb().number();\n        boost::optional<Number> ub = i.ub().number();\n        if (lb) csts += linear_constraint_t(v >= *lb);\n        if (ub) csts += linear_constraint_t(v <= *ub);\n      }\n      return csts;\n    }\n    \n    static std::string getDomainName () {\n      return \"Intervals\";\n    }\n\n  }; // class interval_domain\n  \n} // namespace ikos\n\n", "meta": {"hexsha": "02055450020f3c9cd1056617b0576bdd2c55c38a", "size": 40936, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/crab/domains/intervals.hpp", "max_stars_repo_name": "aziem/crab", "max_stars_repo_head_hexsha": "e150afd53d6fe49cefaade389542b3f3cfe9dbe5", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/crab/domains/intervals.hpp", "max_issues_repo_name": "aziem/crab", "max_issues_repo_head_hexsha": "e150afd53d6fe49cefaade389542b3f3cfe9dbe5", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/crab/domains/intervals.hpp", "max_forks_repo_name": "aziem/crab", "max_forks_repo_head_hexsha": "e150afd53d6fe49cefaade389542b3f3cfe9dbe5", "max_forks_repo_licenses": ["Apache-2.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.436997319, "max_line_length": 90, "alphanum_fraction": 0.5656634747, "num_tokens": 11080, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6334102636778401, "lm_q2_score": 0.4843800842769844, "lm_q1q2_score": 0.3068113169021791}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\n\n// Copyright (c) 2019 Tinko Bartels, Berlin, Germany.\n\n// Use, modification and distribution is subject to the Boost Software License,\n// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n\n#ifndef BOOST_GEOMETRY_EXTENSIONS_TRIANGULATION_STRATEGIES_CARTESIAN_ACCELERATED_SHULL_HPP\n#define BOOST_GEOMETRY_EXTENSIONS_TRIANGULATION_STRATEGIES_CARTESIAN_ACCELERATED_SHULL_HPP\n\n#include <boost/geometry/extensions/triangulation/strategies/delaunay_triangulation.hpp>\n#include <boost/geometry/extensions/triangulation/strategies/cartesian/detail/accelerated_shull.hpp>\n#include <boost/geometry/extensions/triangulation/strategies/delaunay_triangulation.hpp>\n#include <boost/geometry/extensions/triangulation/strategies/cartesian/in_circle_robust.hpp>\n#include <boost/geometry/strategies/cartesian/side_by_triangle.hpp>\n\n#include <boost/geometry/core/coordinate_system.hpp>\n#include <boost/geometry/core/tag.hpp>\n#include <boost/geometry/core/tags.hpp>\n\nnamespace boost { namespace geometry { namespace strategy\n{ \n\nnamespace delaunay_triangulation\n{\n\nstruct accelerated_shull\n{\n    template\n    <\n        typename PointContainer,\n        typename Triangulation,\n        typename SideStrategy = strategy::side::side_by_triangle<>,\n        typename InCircleStrategy = strategy::in_circle::in_circle_robust<>\n    >\n    static inline void apply(PointContainer const & in,\n                             Triangulation& out,\n                             bool legalize = true)\n    {\n        detail::accelerated_shull::apply<\n            PointContainer,\n            Triangulation,\n            SideStrategy,\n            InCircleStrategy>(in, out, legalize);\n    }\n};\n\nnamespace services\n{\ntemplate <>\nstruct default_strategy<point_tag, cartesian_tag, 2>\n{\n    typedef accelerated_shull type;\n};\n}\n\n}}}} // namespace boost::geometry::strategy::delaunay:triangulation\n\n#endif // BOOST_GEOMETRY_EXTENSIONS_TRIANGULATION_STRATEGIES_CARTESIAN_ACCELERATED_SHULL_HPP\n", "meta": {"hexsha": "9550075282ce362bd44a277f6b59ad5d4acb1a4e", "size": 2051, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/geometry/extensions/triangulation/strategies/cartesian/accelerated_shull.hpp", "max_stars_repo_name": "BoostGSoC19/geometry", "max_stars_repo_head_hexsha": "bad1b9c5a2f4f458284a912a848a25e73c28014b", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-01-31T19:33:37.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-31T19:33:37.000Z", "max_issues_repo_path": "include/boost/geometry/extensions/triangulation/strategies/cartesian/accelerated_shull.hpp", "max_issues_repo_name": "BoostGSoC19/geometry", "max_issues_repo_head_hexsha": "bad1b9c5a2f4f458284a912a848a25e73c28014b", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/boost/geometry/extensions/triangulation/strategies/cartesian/accelerated_shull.hpp", "max_forks_repo_name": "BoostGSoC19/geometry", "max_forks_repo_head_hexsha": "bad1b9c5a2f4f458284a912a848a25e73c28014b", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2019-11-20T12:45:45.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-29T04:54:35.000Z", "avg_line_length": 33.6229508197, "max_line_length": 100, "alphanum_fraction": 0.7562164798, "num_tokens": 460, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6334102636778401, "lm_q2_score": 0.48438008427698437, "lm_q1q2_score": 0.3068113169021791}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\n\n// Copyright (c) 2008-2012 Bruno Lalande, Paris, France.\n// Copyright (c) 2008-2012 Barend Gehrels, Amsterdam, the Netherlands.\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_ARITHMETIC_ARITHMETIC_HPP\n#define BOOST_GEOMETRY_ARITHMETIC_ARITHMETIC_HPP\n\n#include <functional>\n\n#include <boost/call_traits.hpp>\n#include <boost/concept/requires.hpp>\n\n#include <boost/geometry/core/coordinate_type.hpp>\n#include <boost/geometry/geometries/concepts/point_concept.hpp>\n#include <boost/geometry/util/for_each_coordinate.hpp>\n#include <boost/geometry/util/select_most_precise.hpp>\n\n\nnamespace geofeatures_boost {} namespace boost = geofeatures_boost; namespace geofeatures_boost { namespace geometry\n{\n\n#ifndef DOXYGEN_NO_DETAIL\nnamespace detail\n{\n\n\ntemplate <typename Point>\nstruct param\n{\n    typedef typename geofeatures_boost::call_traits\n        <\n            typename coordinate_type<Point>::type\n        >::param_type type;\n};\n\n\ntemplate <typename Value, template <typename> class Function>\nstruct value_operation\n{\n    Value m_value;\n\n    inline value_operation(Value const &value)\n        : m_value(value)\n    {}\n\n    template <typename PointDst, std::size_t Index>\n    inline void apply(PointDst& point_dst) const\n    {\n        set<Index>(point_dst,\n               Function\n                <\n                    typename geometry::select_most_precise\n                        <\n                            Value,\n                            typename geometry::coordinate_type<PointDst>::type\n                        >::type\n                >()(get<Index>(point_dst), m_value));\n    }\n};\n\ntemplate <typename PointSrc, template <typename> class Function>\nstruct point_operation\n{\n    PointSrc const& m_point_src;\n\n    inline point_operation(PointSrc const& point)\n        : m_point_src(point)\n    {}\n\n    template <typename PointDst, std::size_t Index>\n    inline void apply(PointDst& point_dst) const\n    {\n        set<Index>(point_dst,\n               Function\n                <\n                    typename geometry::select_most_precise\n                        <\n                            typename geometry::coordinate_type<PointSrc>::type,\n                            typename geometry::coordinate_type<PointDst>::type\n                        >::type\n                >()(get<Index>(point_dst), get<Index>(m_point_src)));\n    }\n};\n\n\ntemplate <typename Value>\nstruct value_assignment\n{\n    Value m_value;\n\n    inline value_assignment(Value const &value)\n        : m_value(value)\n    {}\n\n    template <typename PointDst, std::size_t Index>\n    inline void apply(PointDst& point_dst) const\n    {\n        set<Index>(point_dst, m_value);\n    }\n};\n\ntemplate <typename PointSrc>\nstruct point_assignment\n{\n    PointSrc const& m_point_src;\n\n    inline point_assignment(PointSrc const& point)\n        : m_point_src(point)\n    {}\n\n    template <typename PointDst, std::size_t Index>\n    inline void apply(PointDst& point_dst) const\n    {\n        set<Index>(point_dst, get<Index>(m_point_src));\n    }\n};\n\n\n} // namespace detail\n#endif // DOXYGEN_NO_DETAIL\n\n/*!\n    \\brief Adds the same value to each coordinate of a point\n    \\ingroup arithmetic\n    \\details\n    \\tparam Point \\tparam_point\n    \\param p point\n    \\param value value to add\n */\ntemplate <typename Point>\ninline void add_value(Point& p, typename detail::param<Point>::type value)\n{\n    BOOST_CONCEPT_ASSERT( (concept::Point<Point>) );\n\n    for_each_coordinate(p,\n                        detail::value_operation\n                            <\n                                typename coordinate_type<Point>::type,\n                                std::plus\n                            >(value));\n}\n\n/*!\n    \\brief Adds a point to another\n    \\ingroup arithmetic\n    \\details The coordinates of the second point will be added to those of the first point.\n             The second point is not modified.\n    \\tparam Point1 \\tparam_point\n    \\tparam Point2 \\tparam_point\n    \\param p1 first point\n    \\param p2 second point\n */\ntemplate <typename Point1, typename Point2>\ninline void add_point(Point1& p1, Point2 const& p2)\n{\n    BOOST_CONCEPT_ASSERT( (concept::Point<Point1>) );\n    BOOST_CONCEPT_ASSERT( (concept::ConstPoint<Point2>) );\n\n    for_each_coordinate(p1, detail::point_operation<Point2, std::plus>(p2));\n}\n\n/*!\n    \\brief Subtracts the same value to each coordinate of a point\n    \\ingroup arithmetic\n    \\details\n    \\tparam Point \\tparam_point\n    \\param p point\n    \\param value value to subtract\n */\ntemplate <typename Point>\ninline void subtract_value(Point& p, typename detail::param<Point>::type value)\n{\n    BOOST_CONCEPT_ASSERT( (concept::Point<Point>) );\n\n    for_each_coordinate(p,\n                        detail::value_operation\n                            <\n                                typename coordinate_type<Point>::type,\n                                std::minus\n                            >(value));\n}\n\n/*!\n    \\brief Subtracts a point to another\n    \\ingroup arithmetic\n    \\details The coordinates of the second point will be subtracted to those of the first point.\n             The second point is not modified.\n    \\tparam Point1 \\tparam_point\n    \\tparam Point2 \\tparam_point\n    \\param p1 first point\n    \\param p2 second point\n */\ntemplate <typename Point1, typename Point2>\ninline void subtract_point(Point1& p1, Point2 const& p2)\n{\n    BOOST_CONCEPT_ASSERT( (concept::Point<Point1>) );\n    BOOST_CONCEPT_ASSERT( (concept::ConstPoint<Point2>) );\n\n    for_each_coordinate(p1, detail::point_operation<Point2, std::minus>(p2));\n}\n\n/*!\n    \\brief Multiplies each coordinate of a point by the same value\n    \\ingroup arithmetic\n    \\details\n    \\tparam Point \\tparam_point\n    \\param p point\n    \\param value value to multiply by\n */\ntemplate <typename Point>\ninline void multiply_value(Point& p, typename detail::param<Point>::type value)\n{\n    BOOST_CONCEPT_ASSERT( (concept::Point<Point>) );\n\n    for_each_coordinate(p,\n                        detail::value_operation\n                            <\n                                typename coordinate_type<Point>::type,\n                                std::multiplies\n                            >(value));\n}\n\n/*!\n    \\brief Multiplies a point by another\n    \\ingroup arithmetic\n    \\details The coordinates of the first point will be multiplied by those of the second point.\n             The second point is not modified.\n    \\tparam Point1 \\tparam_point\n    \\tparam Point2 \\tparam_point\n    \\param p1 first point\n    \\param p2 second point\n    \\note This is *not* a dot, cross or wedge product. It is a mere field-by-field multiplication.\n */\ntemplate <typename Point1, typename Point2>\ninline void multiply_point(Point1& p1, Point2 const& p2)\n{\n    BOOST_CONCEPT_ASSERT( (concept::Point<Point1>) );\n    BOOST_CONCEPT_ASSERT( (concept::ConstPoint<Point2>) );\n\n    for_each_coordinate(p1, detail::point_operation<Point2, std::multiplies>(p2));\n}\n\n/*!\n    \\brief Divides each coordinate of the same point by a value\n    \\ingroup arithmetic\n    \\details\n    \\tparam Point \\tparam_point\n    \\param p point\n    \\param value value to divide by\n */\ntemplate <typename Point>\ninline void divide_value(Point& p, typename detail::param<Point>::type value)\n{\n    BOOST_CONCEPT_ASSERT( (concept::Point<Point>) );\n\n    for_each_coordinate(p,\n                        detail::value_operation\n                            <\n                                typename coordinate_type<Point>::type,\n                                std::divides\n                            >(value));\n}\n\n/*!\n    \\brief Divides a point by another\n    \\ingroup arithmetic\n    \\details The coordinates of the first point will be divided by those of the second point.\n             The second point is not modified.\n    \\tparam Point1 \\tparam_point\n    \\tparam Point2 \\tparam_point\n    \\param p1 first point\n    \\param p2 second point\n */\ntemplate <typename Point1, typename Point2>\ninline void divide_point(Point1& p1, Point2 const& p2)\n{\n    BOOST_CONCEPT_ASSERT( (concept::Point<Point1>) );\n    BOOST_CONCEPT_ASSERT( (concept::ConstPoint<Point2>) );\n\n    for_each_coordinate(p1, detail::point_operation<Point2, std::divides>(p2));\n}\n\n/*!\n    \\brief Assign each coordinate of a point the same value\n    \\ingroup arithmetic\n    \\details\n    \\tparam Point \\tparam_point\n    \\param p point\n    \\param value value to assign\n */\ntemplate <typename Point>\ninline void assign_value(Point& p, typename detail::param<Point>::type value)\n{\n    BOOST_CONCEPT_ASSERT( (concept::Point<Point>) );\n\n    for_each_coordinate(p,\n                        detail::value_assignment\n                            <\n                                typename coordinate_type<Point>::type\n                            >(value));\n}\n\n/*!\n    \\brief Assign a point with another\n    \\ingroup arithmetic\n    \\details The coordinates of the first point will be assigned those of the second point.\n             The second point is not modified.\n    \\tparam Point1 \\tparam_point\n    \\tparam Point2 \\tparam_point\n    \\param p1 first point\n    \\param p2 second point\n */\ntemplate <typename Point1, typename Point2>\ninline void assign_point(Point1& p1, Point2 const& p2)\n{\n    BOOST_CONCEPT_ASSERT( (concept::Point<Point1>) );\n    BOOST_CONCEPT_ASSERT( (concept::ConstPoint<Point2>) );\n\n    for_each_coordinate(p1, detail::point_assignment<Point2>(p2));\n}\n\n\n}} // namespace geofeatures_boost::geometry\n\n\n#endif // BOOST_GEOMETRY_ARITHMETIC_ARITHMETIC_HPP\n", "meta": {"hexsha": "8d5a105fef5226fd46c26ce342f8a68c13a64913", "size": 9841, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Pods/Headers/Private/GeoFeatures/boost/geometry/arithmetic/arithmetic.hpp", "max_stars_repo_name": "xarvey/Yuuuuuge", "max_stars_repo_head_hexsha": "9f4ec32f81cf813ea630ba2c44eb03970c56dad3", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Pods/Headers/Private/GeoFeatures/boost/geometry/arithmetic/arithmetic.hpp", "max_issues_repo_name": "xarvey/Yuuuuuge", "max_issues_repo_head_hexsha": "9f4ec32f81cf813ea630ba2c44eb03970c56dad3", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Pods/Headers/Private/GeoFeatures/boost/geometry/arithmetic/arithmetic.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": 29.2886904762, "max_line_length": 116, "alphanum_fraction": 0.6432273143, "num_tokens": 2181, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.665410558746814, "lm_q2_score": 0.4610167793123159, "lm_q1q2_score": 0.30676543271386475}}
{"text": "/*\n * multi_expo.cpp\n *\n *  Created on: 02.07.2012\n *      Author: stephaniebayer\n */\n\n#include \"multi_expo.h\"\n#include \"G_q.h\"\n#include \"ElGammal.h\";\n#include \"Pedersen.h\"\n#include \"Cipher_elg.h\"\n#include <NTL/ZZ.h>\nNTL_CLIENT\n#include<vector>\nusing namespace std;\n#include <iostream>\n#include <time.h>\n#include <fstream>\n\nextern G_q G;\nextern G_q H;\nextern ElGammal El;\nextern Pedersen Ped;\n\nmulti_expo::multi_expo() {\n\t// TODO Auto-generated constructor stub\n\n}\n\nmulti_expo::~multi_expo() {\n\t// TODO Auto-generated destructor stub\n}\n\n\nvector<vector<int>*>* multi_expo::to_binary(int win){\n\n\tvector<vector<int>* >* ret;\n\tvector<int>* temp;\n\tlong e,i,j;\n\tdouble two= 2;\n\n\te = pow(two, win);\n\tret = new vector<vector<int>* >(e);\n\tfor (i = 0; i<e; i++){\n\t\ttemp = new vector<int>(win);\n\t\tfor (j=0; j<win; j++){\n\t\t\ttemp->at(j) =bit(i,j);\n\t\t}\n\t\tret->at(i)=temp;\n\t}\n\treturn ret;\n\n}\n\nlong multi_expo::to_long(vector<int>* bit_r){\n\n\tlong  t, length;\n\tdouble two,i;\n\ttwo = 2;\n\n\tlength =bit_r->size();\n\tt=0;\n\tfor(i = 0; i<length; i++ ){\n\t\tt = t+bit_r->at(i)*pow(two,i);\n\t}\n\treturn t;\n}\n\nvoid multi_expo::to_long(long& t,vector<int>* bit_r){\n\n\tlong  length;\n\tdouble two,i;\n\ttwo = 2;\n\n\tlength =bit_r->size();\n\tt=0;\n\tfor(i = 0; i<length; i++ ){\n\t\tt = t+bit_r->at(i)*pow(two,i);\n\t}\n}\n\nvector<long>* multi_expo::to_basis(ZZ e, long num_b, int omega){\n\tlong i, j, l, t;\n\tvector<int>* bit_r;\n\tvector<long>* basis;\n\tbit_r = new vector<int>(omega);\n\tt= num_b/omega +1;\n\tbasis = new vector<long>(t);\n\n\tj=0;\n\tl=0;\n\n\tfor(i=0; i<num_b; i++){\n\t\tbit_r->at(j)=bit(e,i);\n\t\tj++;\n\t\tif(j==omega){\n\t\t\tto_long(basis->at(l),bit_r);\n\t\t\tj=0;\n\t\t\tl++;\n\t\t}\n\t\telse if(i == num_b-1){\n\t\t\tfor(j = j; j<omega; j++){\n\t\t\t\tbit_r->at(j)= 0;\n\t\t\t\tto_long(basis->at(l),bit_r);\n\t\t\t}\n\t\t}\n\t}\n\tdelete bit_r;\n\treturn basis;\n\n}\n\n\nvector<vector<vector<long>* >* >* multi_expo::to_basis_vec(vector<vector<ZZ>* >* a, long num_b, int omega){\n\tvector<vector<vector<long>* >* >* basis_vec=0;\n\tvector<vector<long>* >* basis_row=0;\n\tvector<long>* basis = 0;\n\tlong i, j, m,n;\n\tm=a->size();\n\tn=a->at(0)->size();\n\tbasis_vec = new vector<vector<vector<long>* >* >(m+1);\n\n\tfor (i = 0; i<m; i++){\n\n\t\tbasis_row = new vector<vector<long>* >(n);\n\t\tfor (j = 0; j<n; j++){\n\t\t\tbasis = to_basis(a->at(i)->at(j), num_b, omega);\n\t\t\tbasis_row->at(j)= basis;\n\t\t}\n\t\tbasis_vec->at(i+1) = basis_row;\n\t}\n\tdelete basis;\n\treturn basis_vec;\n}\n\nZZ multi_expo::expo_mult(const vector<ZZ>* e, ZZ ran, int omega_expo, vector<Mod_p>* gen){\n\tlong i, j, k, l,t;\n\tvector<vector<long>* >* basis_vec;\n\tlong length;// num_b;\n\tZZ prod, p, temp_1, temp_2, mod;\n\tdouble two;\n\tlong num_b;\n\tlength = e->size();\n\tmod = G.get_mod();\n\tnum_b = NumBits(G.get_ord());\n\tl = num_b/omega_expo +1;\n\tbasis_vec = new vector<vector<long>* >(length+1);\n\tbasis_vec->at(0) = to_basis(ran, num_b, omega_expo);\n\tfor(i = 0; i<length; i++){\n\t\tbasis_vec->at(i+1) = to_basis(e->at(i), num_b, omega_expo);\n\t}\n\tprod = 1;\n\ttwo = 2;\n\tp=1;\n\tt = pow(two, omega_expo)-1;\n\tfor(i=l-1; i>0; i--){\n\n\t\tp=1;\n\t\tfor(j = 0; j<length+1; j++){\n\t\t\tif(basis_vec->at(j)->at(i)==t){\n\t\t\t\tMulMod(p,p,gen->at(j).get_val(),mod);\n\t\t\t}\n\t\t}\n\t\ttemp_1 = p;\n\t\ttemp_2 = p;\n\t\tfor(k = t-1; k>0; k--){\n\t\t\tp=1;\n\t\t\tfor(j = 0; j<length+1; j++){\n\t\t\t\tif(basis_vec->at(j)->at(i)==k){\n\t\t\t\t\tMulMod(p,p,gen->at(j).get_val(),mod);\n\t\t\t\t}\n\t\t\t}\n\t\t\tMulMod(temp_1,temp_1,p,mod);\n\t\t\tMulMod(temp_2,temp_1,temp_2,mod);\n\n\t\t}\n\t\tMulMod(prod , prod,temp_2,mod);\n\t\tfor(k =0; k<omega_expo; k++){\n\t\t\tSqrMod(prod,prod,mod);\n\t\t}\n\t}\n\tp=1;\n\tfor(j = 0; j<length+1; j++){\n\t\tif(basis_vec->at(j)->at(0)==t){\n\t\t\tMulMod(p,p,gen->at(j).get_val(),mod);\n\t\t}\n\t}\n\ttemp_1 = p;\n\ttemp_2 = p;\n\tfor(k = t-1; k>0; k--){\n\t\tp=1;\n\t\tfor(j = 0; j<length+1; j++){\n\t\t\tif(basis_vec->at(j)->at(0)==k){\n\t\t\t\tMulMod(p,p,gen->at(j).get_val(),mod);\n\t\t\t}\n\t\t}\n\t\tMulMod(temp_1,temp_1,p,mod);\n\t\tMulMod(temp_2,temp_1,temp_2,mod);\n\t}\n\tMulMod(prod,prod,temp_2,mod);\n\tj = basis_vec->size();\n\tfor(i=0; i<j; i++){\n\t\tdelete basis_vec->at(i);\n\t\tbasis_vec->at(i)=0;\n\t}\n\tdelete basis_vec;\n\treturn prod;\n}\n\n\nvoid multi_expo::expo_mult(ZZ& prod, const vector<ZZ>* e, ZZ ran, int omega_expo, vector<Mod_p>* gen){\n\tlong i, j, k, l,t;\n\tvector<vector<long>* >* basis_vec;\n\tlong length;// num_b;\n\tZZ p, temp_1, temp_2, mod;\n\tdouble two;\n\tlong num_b;\n\tlength = e->size();\n\tmod = G.get_mod();\n\tnum_b = NumBits(G.get_ord());\n\tl = num_b/omega_expo +1;\n\tbasis_vec = new vector<vector<long>* >(length+1);\n\tbasis_vec->at(0) = to_basis(ran, num_b, omega_expo);\n\tfor(i = 0; i<length; i++){\n\t\tbasis_vec->at(i+1) = to_basis(e->at(i), num_b, omega_expo);\n\t}\n\tprod = 1;\n\ttwo = 2;\n\tp=1;\n\tt = pow(two, omega_expo)-1;\n\tlength = length +1;\n\tfor(i=l-1; i>0; i--){\n\n\t\tp=1;\n\t\tfor(j = 0; j<length; j++){\n\t\t\tif(basis_vec->at(j)->at(i)==t){\n\t\t\t\tMulMod(p,p,gen->at(j).get_val(),mod);\n\t\t\t}\n\t\t}\n\t\ttemp_1 = p;\n\t\ttemp_2 = p;\n\t\tfor(k = t-1; k>0; k--){\n\t\t\tp=1;\n\t\t\tfor(j = 0; j<length; j++){\n\t\t\t\tif(basis_vec->at(j)->at(i)==k){\n\t\t\t\t\tMulMod(p,p,gen->at(j).get_val(),mod);\n\t\t\t\t}\n\t\t\t}\n\t\t\tMulMod(temp_1,temp_1,p,mod);\n\t\t\tMulMod(temp_2,temp_1,temp_2,mod);\n\n\t\t}\n\t\tMulMod(prod , prod,temp_2,mod);\n\t\tfor(k =0; k<omega_expo; k++){\n\t\t\tSqrMod(prod,prod,mod);\n\t\t}\n\t}\n\tp=1;\n\tfor(j = 0; j<length; j++){\n\t\tif(basis_vec->at(j)->at(0)==t){\n\t\t\tMulMod(p,p,gen->at(j).get_val(),mod);\n\t\t}\n\t}\n\ttemp_1 = p;\n\ttemp_2 = p;\n\tfor(k = t-1; k>0; k--){\n\t\tp=1;\n\t\tfor(j = 0; j<length; j++){\n\t\t\tif(basis_vec->at(j)->at(0)==k){\n\t\t\t\tMulMod(p,p,gen->at(j).get_val(),mod);\n\t\t\t}\n\t\t}\n\t\tMulMod(temp_1,temp_1,p,mod);\n\t\tMulMod(temp_2,temp_1,temp_2,mod);\n\t}\n\tMulMod(prod,prod,temp_2,mod);\n\tj = basis_vec->size();\n\tfor(i=0; i<j; i++){\n\t\tdelete basis_vec->at(i);\n\t\tbasis_vec->at(i)=0;\n\t}\n\tdelete basis_vec;\n}\n\n\n\nCipher_elg multi_expo::expo_mult(const vector<Cipher_elg>* a, vector<ZZ>* e, int omega ){\n\tlong i, j, k, l,t;\n\tvector<vector<long>* >* basis_vec;\n\tlong length;\n\tZZ prod_u, p_u, temp_1_u, temp_2_u,prod_v, p_v, temp_1_v, temp_2_v, mod;\n\tCipher_elg prod;\n\tdouble two;\n\tlong num_b;\n\n\tlength = e->size();\n\tmod = H.get_mod();\n\tnum_b = NumBits(H.get_ord());\n\tl = num_b/omega +1;\n\n\tvector<ZZ> a_u(length);\n\tvector<ZZ> a_v(length);\n\tbasis_vec = new vector<vector<long>* >(length);\n\tfor(i = 0; i<length; i++){\n\t\tbasis_vec->at(i) = to_basis(e->at(i), num_b,omega);\n\t\ta_u.at(i)=a->at(i).get_u();\n\t\ta_v.at(i)=a->at(i).get_v();\n\t}\n\tprod_u = 1;\n\tprod_v= 1;\n\ttwo = 2;\n\tt = pow(two, omega)-1;\n\tfor(i=l-1; i>0; i--){\n\t\tp_u= 1;\n\t\tp_v= 1;\n\t\tfor(j = 0; j<length; j++){\n\t\t\tif(basis_vec->at(j)->at(i)==t){\n\t\t\t\tMulMod(p_u,p_u,a_u.at(j),mod);\n\t\t\t\tMulMod(p_v,p_v,a_v.at(j), mod);\n\t\t\t}\n\t\t}\n\t\ttemp_1_u = p_u;\n\t\ttemp_2_u = p_u;\n\t\ttemp_1_v = p_v;\n\t\ttemp_2_v = p_v;\n\t\tfor(k = t-1; k>0; k--){\n\t\t\tp_u= 1;\n\t\t\tp_v = 1;\n\t\t\tfor(j = 0; j<length; j++){\n\t\t\t\tif(basis_vec->at(j)->at(i)==k){\n\t\t\t\t\tMulMod(p_u,p_u,a_u.at(j),mod);\n\t\t\t\t\tMulMod(p_v,p_v,a_v.at(j),mod);\n\t\t\t\t}\n\t\t\t}\n\t\t\tMulMod(temp_1_u,temp_1_u,p_u,mod);\n\t\t\tMulMod(temp_2_u,temp_1_u,temp_2_u,mod);\n\t\t\tMulMod(temp_1_v, temp_1_v,p_v,mod);\n\t\t\tMulMod(temp_2_v,temp_1_v,temp_2_v,mod);\n\n\t\t}\n\t\tMulMod(prod_u,prod_u,temp_2_u,mod);\n\t\tMulMod(prod_v,prod_v,temp_2_v,mod);\n\t\tfor(k =0; k<omega; k++){\n\t\t\tSqrMod(prod_u,prod_u,mod);\n\t\t\tSqrMod(prod_v,prod_v,mod);\n\t\t}\n\t}\n\tp_u= 1;\n\tp_v= 1;\n\tfor(j = 0; j<length; j++){\n\t\tif(basis_vec->at(j)->at(0)==t){\n\t\t\tMulMod(p_u,p_u,a_u.at(j),mod);\n\t\t\tMulMod(p_v,p_v,a_v.at(j),mod);\n\t\t}\n\t}\n\ttemp_1_u = p_u;\n\ttemp_2_u = p_u;\n\ttemp_1_v = p_v;\n\ttemp_2_v = p_v;\n\tfor(k = t-1; k>0; k--){\n\t\tp_u= 1;\n\t\tp_v = 1;\n\t\tfor(j = 0; j<length; j++){\n\t\t\tif(basis_vec->at(j)->at(0)==k){\n\t\t\t\tMulMod(p_u,p_u,a_u.at(j),mod);\n\t\t\t\tMulMod(p_v,p_v,a_v.at(j),mod);\n\t\t\t}\n\t\t}\n\t\tMulMod(temp_1_u,temp_1_u,p_u,mod);\n\t\tMulMod(temp_2_u,temp_1_u,temp_2_u,mod);\n\t\tMulMod(temp_1_v,temp_1_v,p_v,mod);\n\t\tMulMod(temp_2_v,temp_1_v,temp_2_v,mod);\n\t}\n\tMulMod(prod_u,prod_u,temp_2_u,mod);\n\tMulMod(prod_v,prod_v,temp_2_v,mod);\n\tprod = Cipher_elg(prod_u, prod_v, mod);\n\n\tj = basis_vec->size();\n\tfor(i=0; i<j; i++){\n\t\tdelete basis_vec->at(i);\n\t\tbasis_vec->at(i)=0;\n\t}\n\tdelete basis_vec;\n\treturn prod;\n}\n\nvoid multi_expo::expo_mult(Cipher_elg& prod, const vector<Cipher_elg>* a, vector<ZZ>* e, int omega ){\n\tlong i, j, k, l,t;\n\tvector<vector<long>* >* basis_vec;\n\tZZ ord = H.get_ord();\n\tlong length;\n\tZZ prod_u, p_u, temp_1_u, temp_2_u,prod_v, p_v, temp_1_v, temp_2_v, mod,temp;\n\tdouble two;\n\tlong num_b;\n\n\tlength = a->size();\n\tmod = H.get_mod();\n\tnum_b = NumBits(ord);\n\tl = num_b/omega +1;\n\n\tvector<ZZ> a_u(length);\n\tvector<ZZ> a_v(length);\n\tbasis_vec = new vector<vector<long>* >(length);\n\tfor(i = 0; i<length; i++){\n\t\tbasis_vec->at(i) = to_basis(e->at(i), num_b,omega);\n\t\ta_u.at(i)=a->at(i).get_u();\n\t\ta_v.at(i)=a->at(i).get_v();\n\t}\n\tprod_u = 1;\n\tprod_v= 1;\n\ttwo = 2;\n\tt = pow(two, omega)-1;\n\tfor(i=l-1; i>0; i--){\n\t\tp_u= 1;\n\t\tp_v= 1;\n\t\tfor(j = 0; j<length; j++){\n\t\t\tif(basis_vec->at(j)->at(i)==t){\n\t\t\t\tMulMod(p_u,p_u,a_u.at(j),mod);\n\t\t\t\tMulMod(p_v,p_v,a_v.at(j), mod);\n\t\t\t}\n\t\t}\n\t\ttemp_1_u = p_u;\n\t\ttemp_2_u = p_u;\n\t\ttemp_1_v = p_v;\n\t\ttemp_2_v = p_v;\n\t\tfor(k = t-1; k>0; k--){\n\t\t\tp_u= 1;\n\t\t\tp_v = 1;\n\t\t\tfor(j = 0; j<length; j++){\n\t\t\t\tif(basis_vec->at(j)->at(i)==k){\n\t\t\t\t\tMulMod(p_u,p_u,a_u.at(j),mod);\n\t\t\t\t\tMulMod(p_v,p_v,a_v.at(j),mod);\n\t\t\t\t}\n\t\t\t}\n\t\t\tMulMod(temp_1_u ,temp_1_u,p_u,mod);\n\t\t\tMulMod(temp_2_u ,temp_1_u,temp_2_u,mod);\n\t\t\tMulMod(temp_1_v ,temp_1_v,p_v,mod);\n\t\t\tMulMod(temp_2_v ,temp_1_v,temp_2_v,mod);\n\n\t\t}\n\t\tprod_u = MulMod(prod_u,temp_2_u,mod);\n\t\tprod_v = MulMod(prod_v,temp_2_v,mod);\n\t\tfor(k =0; k<omega; k++){\n\t\t\tSqrMod(prod_u,prod_u,mod);\n\t\t\tSqrMod(prod_v,prod_v,mod);\n\t\t}\n\t}\n\tp_u= 1;\n\tp_v= 1;\n\tfor(j = 0; j<length; j++){\n\t\tif(basis_vec->at(j)->at(0)==t){\n\t\t\tMulMod(p_u,p_u,a_u.at(j),mod);\n\t\t\tMulMod(p_v,p_v,a_v.at(j),mod);\n\t\t}\n\t}\n\ttemp_1_u = p_u;\n\ttemp_2_u = p_u;\n\ttemp_1_v = p_v;\n\ttemp_2_v = p_v;\n\tfor(k = t-1; k>0; k--){\n\t\tp_u= 1;\n\t\tp_v = 1;\n\t\tfor(j = 0; j<length; j++){\n\t\t\tif(basis_vec->at(j)->at(0)==k){\n\t\t\t\tMulMod(p_u,p_u,a_u.at(j),mod);\n\t\t\t\tMulMod(p_v,p_v,a_v.at(j),mod);\n\t\t\t}\n\t\t}\n\t\tMulMod(temp_1_u ,temp_1_u,p_u,mod);\n\t\tMulMod(temp_2_u ,temp_1_u,temp_2_u,mod);\n\t\tMulMod(temp_1_v, temp_1_v,p_v,mod);\n\t\tMulMod(temp_2_v ,temp_1_v,temp_2_v,mod);\n\t}\n\tMulMod(prod_u,prod_u,temp_2_u,mod);\n\tMulMod(prod_v,prod_v,temp_2_v,mod);\n\tprod = Cipher_elg(prod_u, prod_v, mod);\n\tj = basis_vec->size();\n\tfor(i=0; i<j; i++){\n\t\tdelete basis_vec->at(i);\n\t\tbasis_vec->at(i)=0;\n\t}\n\tdelete basis_vec;\n}\n\nZZ multi_expo::expo_mult(const vector<ZZ>* a, vector<vector<ZZ>*>* e, int omega, long pos ){\n\tlong i, j, k, l,t;\n\tvector<vector<long>* >* basis_vec;\n\n\tlong length;\n\tZZ prod, p, temp_1, temp_2, mod;\n\n\tdouble two;\n\tlong num_b;\n\n\tlength = e->size();\n\tmod = H.get_mod();\n\tnum_b = NumBits(H.get_ord());\n\tl = num_b/omega +1;\n\n\tbasis_vec = new vector<vector<long>* >(length);\n\n\tfor(i = 0; i<length; i++){\n\t\tbasis_vec->at(i) = to_basis(e->at(i)->at(pos), num_b,omega);\n\t}\n\tprod = 1;\n\ttwo = 2;\n\tt = pow(two, omega)-1;\n\tfor(i=l-1; i>0; i--){\n\t\tp= 1;\n\t\tfor(j = 0; j<length; j++){\n\t\t\tif(basis_vec->at(j)->at(i)==t){\n\t\t\t\tMulMod(p,p,a->at(j),mod);\n\t\t\t}\n\t\t}\n\t\ttemp_1 = p;\n\t\ttemp_2 = p;\n\t\tfor(k = t-1; k>0; k--){\n\t\t\tp= 1;\n\t\t\tfor(j = 0; j<length; j++){\n\t\t\t\tif(basis_vec->at(j)->at(i)==k){\n\t\t\t\t\tMulMod(p,p,a->at(j),mod);\n\t\t\t\t}\n\t\t\t}\n\t\t\ttemp_1 = MulMod(temp_1,p,mod);\n\t\t\ttemp_2 = MulMod(temp_1,temp_2,mod);\n\n\t\t}\n\t\tprod = MulMod(prod,temp_2,mod);\n\t\tfor(k =0; k<omega; k++){\n\t\t\tSqrMod(prod,prod,mod);\n\t\t}\n\t}\n\tp= 1;\n\tfor(j = 0; j<length; j++){\n\t\tif(basis_vec->at(j)->at(0)==t){\n\t\t\tMulMod(p,p,a->at(j),mod);\n\t\t}\n\t}\n\ttemp_1 = p;\n\ttemp_2 = p;\n\tfor(k = t-1; k>0; k--){\n\t\tp= 1;\n\t\tfor(j = 0; j<length; j++){\n\t\t\tif(basis_vec->at(j)->at(0)==k){\n\t\t\t\tMulMod(p,p,a->at(j),mod);\n\t\t\t}\n\t\t}\n\t\tMulMod(temp_1,temp_1,p,mod);\n\t\tMulMod(temp_2,temp_1,temp_2,mod);\n\t}\n\tMulMod(prod,prod,temp_2,mod);\n\tj = basis_vec->size();\n\tfor(i=0; i<j; i++){\n\t\tdelete basis_vec->at(i);\n\t\tbasis_vec->at(i)=0;\n\t}\n\tdelete basis_vec;\n\treturn prod;\n}\n\nvoid multi_expo::expo_mult(ZZ& prod, const vector<ZZ>* a, vector<vector<ZZ>*>* e, int omega, long pos ){\n\tlong i, j, k, l,t;\n\tvector<vector<long>* >* basis_vec;\n\n\tlong length;\n\tZZ  p, temp_1, temp_2, mod;\n\n\tdouble two;\n\tlong num_b;\n\n\tlength = e->size();\n\tmod = H.get_mod();\n\tnum_b = NumBits(H.get_ord());\n\tl = num_b/omega +1;\n\n\tbasis_vec = new vector<vector<long>* >(length);\n\n\tfor(i = 0; i<length; i++){\n\t\tbasis_vec->at(i) = to_basis(e->at(i)->at(pos), num_b,omega);\n\t}\n\tprod = 1;\n\ttwo = 2;\n\tt = pow(two, omega)-1;\n\tfor(i=l-1; i>0; i--){\n\t\tp= 1;\n\t\tfor(j = 0; j<length; j++){\n\t\t\tif(basis_vec->at(j)->at(i)==t){\n\t\t\t\tMulMod(p,p,a->at(j),mod);\n\t\t\t}\n\t\t}\n\t\ttemp_1 = p;\n\t\ttemp_2 = p;\n\t\tfor(k = t-1; k>0; k--){\n\t\t\tp= 1;\n\t\t\tfor(j = 0; j<length; j++){\n\t\t\t\tif(basis_vec->at(j)->at(i)==k){\n\t\t\t\t\tMulMod(p,p,a->at(j),mod);\n\t\t\t\t}\n\t\t\t}\n\t\t\ttemp_1 = MulMod(temp_1,p,mod);\n\t\t\ttemp_2 = MulMod(temp_1,temp_2,mod);\n\n\t\t}\n\t\tprod = MulMod(prod,temp_2,mod);\n\t\tfor(k =0; k<omega; k++){\n\t\t\tSqrMod(prod,prod,mod);\n\t\t}\n\t}\n\tp= 1;\n\tfor(j = 0; j<length; j++){\n\t\tif(basis_vec->at(j)->at(0)==t){\n\t\t\tMulMod(p,p,a->at(j),mod);\n\t\t}\n\t}\n\ttemp_1 = p;\n\ttemp_2 = p;\n\tfor(k = t-1; k>0; k--){\n\t\tp= 1;\n\t\tfor(j = 0; j<length; j++){\n\t\t\tif(basis_vec->at(j)->at(0)==k){\n\t\t\t\tMulMod(p,p,a->at(j),mod);\n\t\t\t}\n\t\t}\n\t\tMulMod(temp_1,temp_1,p,mod);\n\t\tMulMod(temp_2,temp_1,temp_2,mod);\n\t}\n\tMulMod(prod,prod,temp_2,mod);\n\tj = basis_vec->size();\n\tfor(i=0; i<j; i++){\n\t\tdelete basis_vec->at(i);\n\t\tbasis_vec->at(i)=0;\n\t}\n\tdelete basis_vec;\n}\n\nZZ multi_expo::expo_mult(const vector<vector<vector<ZZ>* >*>* a, vector<vector<ZZ>*>* e, int omega, long pos, long pos_2 ){\n\tlong i, j, k, l,t;\n\tvector<vector<long>* >* basis_vec;\n\n\tlong length;\n\tZZ prod, p, temp_1, temp_2, mod;\n\n\tdouble two;\n\tlong num_b;\n\n\tlength = e->size();\n\tmod = H.get_mod();\n\tnum_b = NumBits(H.get_ord());\n\tl = num_b/omega +1;\n\tbasis_vec = new vector<vector<long>* >(length);\n\n\tfor(i = 0; i<length; i++){\n\t\tbasis_vec->at(i) = to_basis(e->at(i)->at(pos), num_b,omega);\n\t}\n\n\tprod = 1;\n\ttwo = 2;\n\tt = pow(two, omega)-1;\n\tfor(i=l-1; i>0; i--){\n\t\tp= 1;\n\t\tfor(j = 0; j<length; j++){\n\t\t\tif(basis_vec->at(j)->at(i)==t){\n\t\t\t\tMulMod(p,p,a->at(j)->at(pos_2)->at(pos),mod);\n\t\t\t}\n\t\t}\n\t\ttemp_1 = p;\n\t\ttemp_2 = p;\n\t\tfor(k = t-1; k>0; k--){\n\t\t\tp= 1;\n\t\t\tfor(j = 0; j<length; j++){\n\t\t\t\tif(basis_vec->at(j)->at(i)==k){\n\t\t\t\t\tMulMod(p,p,a->at(j)->at(pos_2)->at(pos),mod);\n\t\t\t\t}\n\t\t\t}\n\t\t\tMulMod(temp_1,temp_1,p,mod);\n\t\t\tMulMod(temp_2,temp_1,temp_2,mod);\n\n\t\t}\n\t\tMulMod(prod,prod,temp_2,mod);\n\t\tfor(k =0; k<omega; k++){\n\t\t\tSqrMod(prod,prod,mod);\n\t\t}\n\t}\n\tp= 1;\n\tfor(j = 0; j<length; j++){\n\t\tif(basis_vec->at(j)->at(0)==t){\n\t\t\tMulMod(p,p,a->at(j)->at(pos_2)->at(pos),mod);\n\t\t}\n\t}\n\ttemp_1 = p;\n\ttemp_2 = p;\n\tfor(k = t-1; k>0; k--){\n\t\tp= 1;\n\t\tfor(j = 0; j<length; j++){\n\t\t\tif(basis_vec->at(j)->at(0)==k){\n\t\t\t\tMulMod(p,p,a->at(j)->at(pos_2)->at(pos),mod);\n\t\t\t}\n\t\t}\n\t\tMulMod(temp_1,temp_1,p,mod);\n\t\tMulMod(temp_2,temp_1,temp_2,mod);\n\t}\n\tMulMod(prod,prod,temp_2,mod);\n\tj = basis_vec->size();\n\tfor(i=0; i<j; i++){\n\t\tdelete basis_vec->at(i);\n\t\tbasis_vec->at(i)=0;\n\t}\n\tdelete basis_vec;\n\treturn prod;\n}\n\nvoid multi_expo::expo_mult(ZZ& prod, const vector<vector<vector<ZZ>* >*>* a, vector<vector<ZZ>*>* e, int omega, long pos, long pos_2 ){\n\tlong i, j, k, l,t;\n\tvector<vector<long>* >* basis_vec;\n\n\tlong length;\n\tZZ  p, temp_1, temp_2, mod;\n\n\tdouble two;\n\tlong num_b;\n\n\tlength = e->size();\n\tmod = H.get_mod();\n\tnum_b = NumBits(H.get_ord());\n\tl = num_b/omega +1;\n\tbasis_vec = new vector<vector<long>* >(length);\n\n\tfor(i = 0; i<length; i++){\n\t\tbasis_vec->at(i) = to_basis(e->at(i)->at(pos), num_b,omega);\n\t}\n\n\tprod = 1;\n\ttwo = 2;\n\tt = pow(two, omega)-1;\n\tfor(i=l-1; i>0; i--){\n\t\tp= 1;\n\t\tfor(j = 0; j<length; j++){\n\t\t\tif(basis_vec->at(j)->at(i)==t){\n\t\t\t\tMulMod(p,p,a->at(j)->at(pos_2)->at(pos),mod);\n\t\t\t}\n\t\t}\n\t\ttemp_1 = p;\n\t\ttemp_2 = p;\n\t\tfor(k = t-1; k>0; k--){\n\t\t\tp= 1;\n\t\t\tfor(j = 0; j<length; j++){\n\t\t\t\tif(basis_vec->at(j)->at(i)==k){\n\t\t\t\t\tMulMod(p,p,a->at(j)->at(pos_2)->at(pos),mod);\n\t\t\t\t}\n\t\t\t}\n\t\t\tMulMod(temp_1,temp_1,p,mod);\n\t\t\tMulMod(temp_2,temp_1,temp_2,mod);\n\n\t\t}\n\t\tMulMod(prod,prod,temp_2,mod);\n\t\tfor(k =0; k<omega; k++){\n\t\t\tSqrMod(prod,prod,mod);\n\t\t}\n\t}\n\tp= 1;\n\tfor(j = 0; j<length; j++){\n\t\tif(basis_vec->at(j)->at(0)==t){\n\t\t\tMulMod(p,p,a->at(j)->at(pos_2)->at(pos),mod);\n\t\t}\n\t}\n\ttemp_1 = p;\n\ttemp_2 = p;\n\tfor(k = t-1; k>0; k--){\n\t\tp= 1;\n\t\tfor(j = 0; j<length; j++){\n\t\t\tif(basis_vec->at(j)->at(0)==k){\n\t\t\t\tMulMod(p,p,a->at(j)->at(pos_2)->at(pos),mod);\n\t\t\t}\n\t\t}\n\t\tMulMod(temp_1,temp_1,p,mod);\n\t\tMulMod(temp_2,temp_1,temp_2,mod);\n\t}\n\tMulMod(prod,prod,temp_2,mod);\n\tj = basis_vec->size();\n\tfor(i=0; i<j; i++){\n\t\tdelete basis_vec->at(i);\n\t\tbasis_vec->at(i)=0;\n\t}\n\tdelete basis_vec;\n}\n\nCipher_elg multi_expo::expo_mult(const vector<Cipher_elg>* a, vector<vector<long>*>* basis_vec, int omega ){\n\tlong i, j, k, l,t;\n\tlong length;\n\tZZ prod_u, p_u, temp_1_u, temp_2_u,prod_v, p_v, temp_1_v, temp_2_v, mod;\n\tCipher_elg prod;\n\tdouble two;\n\tlong num_b;\n\n\tlength = a->size();\n\tmod = H.get_mod();\n\tnum_b = NumBits(H.get_ord());\n\tl = num_b/omega +1;\n\n\tvector<ZZ> a_u(length);\n\tvector<ZZ> a_v(length);\n\n\tfor(i = 0; i<length; i++){\n\t\ta_u.at(i)=a->at(i).get_u();\n\t\ta_v.at(i)=a->at(i).get_v();\n\t}\n\tprod_u = 1;\n\tprod_v= 1;\n\ttwo = 2;\n\tt = pow(two, omega)-1;\n\tfor(i=l-1; i>0; i--){\n\t\tp_u= 1;\n\t\tp_v= 1;\n\t\tfor(j = 0; j<length; j++){\n\t\t\tif(basis_vec->at(j)->at(i)==t){\n\t\t\t\tMulMod(p_u,p_u,a_u.at(j),mod);\n\t\t\t\tMulMod(p_v,p_v,a_v.at(j), mod);\n\t\t\t}\n\t\t}\n\t\ttemp_1_u = p_u;\n\t\ttemp_2_u = p_u;\n\t\ttemp_1_v = p_v;\n\t\ttemp_2_v = p_v;\n\t\tfor(k = t-1; k>0; k--){\n\t\t\tp_u= 1;\n\t\t\tp_v = 1;\n\t\t\tfor(j = 0; j<length; j++){\n\t\t\t\tif(basis_vec->at(j)->at(i)==k){\n\t\t\t\t\tMulMod(p_u,p_u,a_u.at(j),mod);\n\t\t\t\t\tMulMod(p_v,p_v,a_v.at(j),mod);\n\t\t\t\t}\n\t\t\t}\n\t\t\tMulMod(temp_1_u ,temp_1_u,p_u,mod);\n\t\t\tMulMod(temp_2_u ,temp_1_u,temp_2_u,mod);\n\t\t\tMulMod(temp_1_v,temp_1_v,p_v,mod);\n\t\t\tMulMod(temp_2_v, temp_1_v,temp_2_v,mod);\n\n\t\t}\n\t\tMulMod(prod_u,prod_u,temp_2_u,mod);\n\t\tMulMod(prod_v,prod_v,temp_2_v,mod);\n\t\tfor(k =0; k<omega; k++){\n\t\t\tSqrMod(prod_u,prod_u,mod);\n\t\t\tSqrMod(prod_v,prod_v,mod);\n\t\t}\n\t}\n\tp_u= 1;\n\tp_v= 1;\n\tfor(j = 0; j<length; j++){\n\t\tif(basis_vec->at(j)->at(0)==t){\n\t\t\tMulMod(p_u,p_u,a_u.at(j),mod);\n\t\t\tMulMod(p_v,p_v,a_v.at(j),mod);\n\t\t}\n\t}\n\ttemp_1_u = p_u;\n\ttemp_2_u = p_u;\n\ttemp_1_v = p_v;\n\ttemp_2_v = p_v;\n\tfor(k = t-1; k>0; k--){\n\t\tp_u= 1;\n\t\tp_v = 1;\n\t\tfor(j = 0; j<length; j++){\n\t\t\tif(basis_vec->at(j)->at(0)==k){\n\t\t\t\tMulMod(p_u,p_u,a_u.at(j),mod);\n\t\t\t\tMulMod(p_v,p_v,a_v.at(j),mod);\n\t\t\t}\n\t\t}\n\t\tMulMod(temp_1_u ,temp_1_u,p_u,mod);\n\t\tMulMod(temp_2_u ,temp_1_u,temp_2_u,mod);\n\t\tMulMod(temp_1_v, temp_1_v,p_v,mod);\n\t\tMulMod(temp_2_v ,temp_1_v,temp_2_v,mod);\n\t}\n\tMulMod(prod_u, prod_u,temp_2_u,mod);\n\tMulMod(prod_v,prod_v,temp_2_v,mod);\n\tprod = Cipher_elg(prod_u, prod_v, mod);\n\n\treturn prod;\n}\n\nvoid multi_expo::expo_mult(Cipher_elg& prod, const vector<Cipher_elg>* a, vector<vector<long>*>* basis_vec, int omega ){\n\tlong i, j, k, l,t;\n\tlong length;\n\tZZ prod_u, p_u, temp_1_u, temp_2_u,prod_v, p_v, temp_1_v, temp_2_v, mod;\n\tdouble two;\n\tlong num_b;\n\n\tlength = a->size();\n\tmod = H.get_mod();\n\tnum_b = NumBits(H.get_ord());\n\tl = num_b/omega +1;\n\n\tvector<ZZ> a_u(length);\n\tvector<ZZ> a_v(length);\n\n\tfor(i = 0; i<length; i++){\n\t\ta_u.at(i)=a->at(i).get_u();\n\t\ta_v.at(i)=a->at(i).get_v();\n\t}\n\tprod_u = 1;\n\tprod_v= 1;\n\ttwo = 2;\n\tt = pow(two, omega)-1;\n\tfor(i=l-1; i>0; i--){\n\t\tp_u= 1;\n\t\tp_v= 1;\n\t\tfor(j = 0; j<length; j++){\n\t\t\tif(basis_vec->at(j)->at(i)==t){\n\t\t\t\tMulMod(p_u,p_u,a_u.at(j),mod);\n\t\t\t\tMulMod(p_v,p_v,a_v.at(j), mod);\n\t\t\t}\n\t\t}\n\t\ttemp_1_u = p_u;\n\t\ttemp_2_u = p_u;\n\t\ttemp_1_v = p_v;\n\t\ttemp_2_v = p_v;\n\t\tfor(k = t-1; k>0; k--){\n\t\t\tp_u= 1;\n\t\t\tp_v = 1;\n\t\t\tfor(j = 0; j<length; j++){\n\t\t\t\tif(basis_vec->at(j)->at(i)==k){\n\t\t\t\t\tMulMod(p_u,p_u,a_u.at(j),mod);\n\t\t\t\t\tMulMod(p_v,p_v,a_v.at(j),mod);\n\t\t\t\t}\n\t\t\t}\n\t\t\tMulMod(temp_1_u ,temp_1_u,p_u,mod);\n\t\t\tMulMod(temp_2_u ,temp_1_u,temp_2_u,mod);\n\t\t\tMulMod(temp_1_v,temp_1_v,p_v,mod);\n\t\t\tMulMod(temp_2_v, temp_1_v,temp_2_v,mod);\n\n\t\t}\n\t\tMulMod(prod_u,prod_u,temp_2_u,mod);\n\t\tMulMod(prod_v,prod_v,temp_2_v,mod);\n\t\tfor(k =0; k<omega; k++){\n\t\t\tSqrMod(prod_u,prod_u,mod);\n\t\t\tSqrMod(prod_v,prod_v,mod);\n\t\t}\n\t}\n\tp_u= 1;\n\tp_v= 1;\n\tfor(j = 0; j<length; j++){\n\t\tif(basis_vec->at(j)->at(0)==t){\n\t\t\tMulMod(p_u,p_u,a_u.at(j),mod);\n\t\t\tMulMod(p_v,p_v,a_v.at(j),mod);\n\t\t}\n\t}\n\ttemp_1_u = p_u;\n\ttemp_2_u = p_u;\n\ttemp_1_v = p_v;\n\ttemp_2_v = p_v;\n\tfor(k = t-1; k>0; k--){\n\t\tp_u= 1;\n\t\tp_v = 1;\n\t\tfor(j = 0; j<length; j++){\n\t\t\tif(basis_vec->at(j)->at(0)==k){\n\t\t\t\tMulMod(p_u,p_u,a_u.at(j),mod);\n\t\t\t\tMulMod(p_v,p_v,a_v.at(j),mod);\n\t\t\t}\n\t\t}\n\t\tMulMod(temp_1_u ,temp_1_u,p_u,mod);\n\t\tMulMod(temp_2_u ,temp_1_u,temp_2_u,mod);\n\t\tMulMod(temp_1_v, temp_1_v,p_v,mod);\n\t\tMulMod(temp_2_v ,temp_1_v,temp_2_v,mod);\n\t}\n\tMulMod(prod_u, prod_u,temp_2_u,mod);\n\tMulMod(prod_v,prod_v,temp_2_v,mod);\n\tprod = Cipher_elg(prod_u, prod_v, mod);\n\n}\n\n\nCipher_elg multi_expo::expo_mult(const vector<Cipher_elg>* a, ZZ f, vector<ZZ>* e, int omega ){\n\tlong i, j, k, l,t;\n\tvector<vector<long>* >* basis_vec;\n\tZZ ord = H.get_ord();\n\tlong length;\n\tZZ prod_u, p_u, temp_1_u, temp_2_u,prod_v, p_v, temp_1_v, temp_2_v, mod,temp;\n\tCipher_elg prod;\n\tdouble two;\n\tlong num_b;\n\n\tlength = e->size();\n\tmod = H.get_mod();\n\tnum_b = NumBits(ord);\n\tl = num_b/omega +1;\n\n\tvector<ZZ> a_u(length);\n\tvector<ZZ> a_v(length);\n\tbasis_vec = new vector<vector<long>* >(length);\n\tfor(i = 0; i<length; i++){\n\t\ttemp = MulMod(f,e->at(i),ord);\n\t\tbasis_vec->at(i) = to_basis(temp, num_b,omega);\n\t\ta_u.at(i)=a->at(i).get_u();\n\t\ta_v.at(i)=a->at(i).get_v();\n\t}\n\tprod_u = 1;\n\tprod_v= 1;\n\ttwo = 2;\n\tt = pow(two, omega)-1;\n\tfor(i=l-1; i>0; i--){\n\t\tp_u= 1;\n\t\tp_v= 1;\n\t\tfor(j = 0; j<length; j++){\n\t\t\tif(basis_vec->at(j)->at(i)==t){\n\t\t\t\tMulMod(p_u,p_u,a_u.at(j),mod);\n\t\t\t\tMulMod(p_v,p_v,a_v.at(j), mod);\n\t\t\t}\n\t\t}\n\t\ttemp_1_u = p_u;\n\t\ttemp_2_u = p_u;\n\t\ttemp_1_v = p_v;\n\t\ttemp_2_v = p_v;\n\t\tfor(k = t-1; k>0; k--){\n\t\t\tp_u= 1;\n\t\t\tp_v = 1;\n\t\t\tfor(j = 0; j<length; j++){\n\t\t\t\tif(basis_vec->at(j)->at(i)==k){\n\t\t\t\t\tMulMod(p_u,p_u,a_u.at(j),mod);\n\t\t\t\t\tMulMod(p_v,p_v,a_v.at(j),mod);\n\t\t\t\t}\n\t\t\t}\n\t\t\tMulMod(temp_1_u ,temp_1_u,p_u,mod);\n\t\t\tMulMod(temp_2_u ,temp_1_u,temp_2_u,mod);\n\t\t\tMulMod(temp_1_v ,temp_1_v,p_v,mod);\n\t\t\tMulMod(temp_2_v ,temp_1_v,temp_2_v,mod);\n\n\t\t}\n\t\tprod_u = MulMod(prod_u,temp_2_u,mod);\n\t\tprod_v = MulMod(prod_v,temp_2_v,mod);\n\t\tfor(k =0; k<omega; k++){\n\t\t\tSqrMod(prod_u,prod_u,mod);\n\t\t\tSqrMod(prod_v,prod_v,mod);\n\t\t}\n\t}\n\tp_u= 1;\n\tp_v= 1;\n\tfor(j = 0; j<length; j++){\n\t\tif(basis_vec->at(j)->at(0)==t){\n\t\t\tMulMod(p_u,p_u,a_u.at(j),mod);\n\t\t\tMulMod(p_v,p_v,a_v.at(j),mod);\n\t\t}\n\t}\n\ttemp_1_u = p_u;\n\ttemp_2_u = p_u;\n\ttemp_1_v = p_v;\n\ttemp_2_v = p_v;\n\tfor(k = t-1; k>0; k--){\n\t\tp_u= 1;\n\t\tp_v = 1;\n\t\tfor(j = 0; j<length; j++){\n\t\t\tif(basis_vec->at(j)->at(0)==k){\n\t\t\t\tMulMod(p_u,p_u,a_u.at(j),mod);\n\t\t\t\tMulMod(p_v,p_v,a_v.at(j),mod);\n\t\t\t}\n\t\t}\n\t\tMulMod(temp_1_u ,temp_1_u,p_u,mod);\n\t\tMulMod(temp_2_u ,temp_1_u,temp_2_u,mod);\n\t\tMulMod(temp_1_v, temp_1_v,p_v,mod);\n\t\tMulMod(temp_2_v ,temp_1_v,temp_2_v,mod);\n\t}\n\tMulMod(prod_u,prod_u,temp_2_u,mod);\n\tMulMod(prod_v,prod_v,temp_2_v,mod);\n\tprod = Cipher_elg(prod_u, prod_v, mod);\n\tj = basis_vec->size();\n\tfor(i=0; i<j; i++){\n\t\tdelete basis_vec->at(i);\n\t\tbasis_vec->at(i)=0;\n\t}\n\tdelete basis_vec;\n\treturn prod;\n}\n\nvoid multi_expo::expo_mult(Cipher_elg& prod, const vector<Cipher_elg>* a, ZZ f, vector<ZZ>* e, int omega ){\n\tlong i, j, k, l,t;\n\tvector<vector<long>* >* basis_vec;\n\tZZ ord = H.get_ord();\n\tlong length;\n\tZZ prod_u, p_u, temp_1_u, temp_2_u,prod_v, p_v, temp_1_v, temp_2_v, mod,temp;\n\tdouble two;\n\tlong num_b;\n\n\tlength = e->size();\n\tmod = H.get_mod();\n\tnum_b = NumBits(ord);\n\tl = num_b/omega +1;\n\tvector<ZZ> a_u(length);\n\tvector<ZZ> a_v(length);\n\tbasis_vec = new vector<vector<long>* >(length);\n\tfor(i = 0; i<length; i++){\n\t\ttemp = MulMod(f,e->at(i),ord);\n\t\tbasis_vec->at(i) = to_basis(temp, num_b,omega);\n\t\ta_u.at(i)=a->at(i).get_u();\n\t\ta_v.at(i)=a->at(i).get_v();\n\t}\n\tprod_u = 1;\n\tprod_v= 1;\n\ttwo = 2;\n\tt = pow(two, omega)-1;\n\tfor(i=l-1; i>0; i--){\n\t\tp_u= 1;\n\t\tp_v= 1;\n\t\tfor(j = 0; j<length; j++){\n\t\t\tif(basis_vec->at(j)->at(i)==t){\n\t\t\t\tMulMod(p_u,p_u,a_u.at(j),mod);\n\t\t\t\tMulMod(p_v,p_v,a_v.at(j), mod);\n\t\t\t}\n\t\t}\n\t\ttemp_1_u = p_u;\n\t\ttemp_2_u = p_u;\n\t\ttemp_1_v = p_v;\n\t\ttemp_2_v = p_v;\n\t\tfor(k = t-1; k>0; k--){\n\t\t\tp_u= 1;\n\t\t\tp_v = 1;\n\t\t\tfor(j = 0; j<length; j++){\n\t\t\t\tif(basis_vec->at(j)->at(i)==k){\n\t\t\t\t\tMulMod(p_u,p_u,a_u.at(j),mod);\n\t\t\t\t\tMulMod(p_v,p_v,a_v.at(j),mod);\n\t\t\t\t}\n\t\t\t}\n\t\t\tMulMod(temp_1_u ,temp_1_u,p_u,mod);\n\t\t\tMulMod(temp_2_u ,temp_1_u,temp_2_u,mod);\n\t\t\tMulMod(temp_1_v ,temp_1_v,p_v,mod);\n\t\t\tMulMod(temp_2_v ,temp_1_v,temp_2_v,mod);\n\n\t\t}\n\t\tprod_u = MulMod(prod_u,temp_2_u,mod);\n\t\tprod_v = MulMod(prod_v,temp_2_v,mod);\n\t\tfor(k =0; k<omega; k++){\n\t\t\tSqrMod(prod_u,prod_u,mod);\n\t\t\tSqrMod(prod_v,prod_v,mod);\n\t\t}\n\t}\n\tp_u= 1;\n\tp_v= 1;\n\tfor(j = 0; j<length; j++){\n\t\tif(basis_vec->at(j)->at(0)==t){\n\t\t\tMulMod(p_u,p_u,a_u.at(j),mod);\n\t\t\tMulMod(p_v,p_v,a_v.at(j),mod);\n\t\t}\n\t}\n\ttemp_1_u = p_u;\n\ttemp_2_u = p_u;\n\ttemp_1_v = p_v;\n\ttemp_2_v = p_v;\n\tfor(k = t-1; k>0; k--){\n\t\tp_u= 1;\n\t\tp_v = 1;\n\t\tfor(j = 0; j<length; j++){\n\t\t\tif(basis_vec->at(j)->at(0)==k){\n\t\t\t\tMulMod(p_u,p_u,a_u.at(j),mod);\n\t\t\t\tMulMod(p_v,p_v,a_v.at(j),mod);\n\t\t\t}\n\t\t}\n\t\tMulMod(temp_1_u ,temp_1_u,p_u,mod);\n\t\tMulMod(temp_2_u ,temp_1_u,temp_2_u,mod);\n\t\tMulMod(temp_1_v, temp_1_v,p_v,mod);\n\t\tMulMod(temp_2_v ,temp_1_v,temp_2_v,mod);\n\t}\n\tMulMod(prod_u,prod_u,temp_2_u,mod);\n\tMulMod(prod_v,prod_v,temp_2_v,mod);\n\tprod = Cipher_elg(prod_u, prod_v, mod);\n\tj = basis_vec->size();\n\tfor(i=0; i<j; i++){\n\t\tdelete basis_vec->at(i);\n\t\tbasis_vec->at(i)=0;\n\t};\n\tdelete basis_vec;\n}\n\nCipher_elg multi_expo::expo_mult(const vector<vector<Cipher_elg>*>* a, vector<ZZ>* s1, vector<ZZ>* s2, int omega ){\n\tCipher_elg prod;\n\tlong i,l;\n\tl = a->size();\n\tprod = expo_mult(a->at(0), s1->at(0), s2, omega);\n\tfor(i = 1; i<l; i++){\n\t\tprod = prod*expo_mult(a->at(i), s1->at(i), s2, omega);\n\t}\n\treturn prod;\n\n}\n\n\nvoid  multi_expo::expo_mult(Cipher_elg& prod, const vector<vector<Cipher_elg>*>* a, vector<ZZ>* s1, vector<ZZ>* s2, int omega ){\n\tCipher_elg temp;\n\tlong i,l;\n\tl = a->size();\n\texpo_mult(prod,a->at(0), s1->at(0), s2, omega);\n\tfor(i = 1; i<l; i++){\n\t\texpo_mult(temp,a->at(i), s1->at(i), s2, omega);\n\t\tCipher_elg::mult(prod,prod,temp);\n\t}\n}\n\nMod_p multi_expo::expo_mult(const vector<Mod_p>* a, vector<vector<long>*>* basis_vec, int omega ){\n\tlong i, j, k, l,t;\n\n\tlong length;\n\tZZ prod, p, temp_1, temp_2, mod;\n\tMod_p pro;\n\tdouble two;\n\tlong num_b;\n\n\tlength = a->size();\n\tmod = G.get_mod();\n\tnum_b = NumBits(H.get_ord());\n\tl = num_b/omega +1;\n\n\tvector<ZZ> a_temp(length);\n\n\tfor(i = 0; i<length; i++){\n\t\ta_temp.at(i)=a->at(i).get_val();\n\t}\n\tprod = 1;\n\ttwo = 2;\n\tt = pow(two, omega)-1;\n\tfor(i=l-1; i>0; i--){\n\t\tp= 1;\n\t\tfor(j = 0; j<length; j++){\n\t\t\tif(basis_vec->at(j)->at(i)==t){\n\t\t\t\tMulMod(p,p,a_temp.at(j),mod);\n\t\t\t}\n\t\t}\n\t\ttemp_1 = p;\n\t\ttemp_2 = p;\n\t\tfor(k = t-1; k>0; k--){\n\t\t\tp= 1;\n\t\t\tfor(j = 0; j<length; j++){\n\t\t\t\tif(basis_vec->at(j)->at(i)==k){\n\t\t\t\t\tMulMod(p,p,a_temp.at(j),mod);\n\t\t\t\t}\n\t\t\t}\n\t\t\tMulMod(temp_1,temp_1,p,mod);\n\t\t\tMulMod(temp_2,temp_1,temp_2,mod);\n\n\t\t}\n\t\tprod = MulMod(prod,temp_2,mod);\n\t\tfor(k =0; k<omega; k++){\n\t\t\tSqrMod(prod,prod,mod);\n\t\t}\n\t}\n\tp= 1;\n\tfor(j = 0; j<length; j++){\n\t\tif(basis_vec->at(j)->at(0)==t){\n\t\t\tMulMod(p,p,a_temp.at(j),mod);\n\t\t}\n\t}\n\ttemp_1 = p;\n\ttemp_2 = p;\n\tfor(k = t-1; k>0; k--){\n\t\tp= 1;\n\t\tfor(j = 0; j<length; j++){\n\t\t\tif(basis_vec->at(j)->at(0)==k){\n\t\t\t\tMulMod(p,p,a_temp.at(j),mod);\n\t\t\t}\n\t\t}\n\t\tMulMod(temp_1,temp_1,p,mod);\n\t\tMulMod(temp_2,temp_1,temp_2,mod);\n\t}\n\tMulMod(prod, prod,temp_2,mod);\n\tpro = Mod_p(prod,  mod);\n\treturn pro;\n}\n\nvoid multi_expo::expo_mult(Mod_p& pro, const vector<Mod_p>* a, vector<vector<long>*>* basis_vec, int omega ){\n\tlong i, j, k, l,t;\n\tlong length;\n\tZZ prod, p, temp_1, temp_2, mod;\n\t//Mod_p pro;\n\tdouble two;\n\tlong num_b;\n\n\tlength = a->size();\n\tmod = G.get_mod();\n\tnum_b = NumBits(H.get_ord());\n\tl = num_b/omega +1;\n\n\tvector<ZZ> a_temp(length);\n\n\tfor(i = 0; i<length; i++){\n\t\ta_temp.at(i)=a->at(i).get_val();\n\t}\n\tprod = 1;\n\ttwo = 2;\n\tt = pow(two, omega)-1;\n\tfor(i=l-1; i>0; i--){\n\t\tp= 1;\n\t\tfor(j = 0; j<length; j++){\n\t\t\tif(basis_vec->at(j)->at(i)==t){\n\t\t\t\tMulMod(p,p,a_temp.at(j),mod);\n\t\t\t}\n\t\t}\n\t\ttemp_1 = p;\n\t\ttemp_2 = p;\n\t\tfor(k = t-1; k>0; k--){\n\t\t\tp= 1;\n\t\t\tfor(j = 0; j<length; j++){\n\t\t\t\tif(basis_vec->at(j)->at(i)==k){\n\t\t\t\t\tMulMod(p,p,a_temp.at(j),mod);\n\t\t\t\t}\n\t\t\t}\n\t\t\tMulMod(temp_1,temp_1,p,mod);\n\t\t\tMulMod(temp_2,temp_1,temp_2,mod);\n\n\t\t}\n\t\tprod = MulMod(prod,temp_2,mod);\n\t\tfor(k =0; k<omega; k++){\n\t\t\tSqrMod(prod,prod,mod);\n\t\t}\n\t}\n\tp= 1;\n\tfor(j = 0; j<length; j++){\n\t\tif(basis_vec->at(j)->at(0)==t){\n\t\t\tMulMod(p,p,a_temp.at(j),mod);\n\t\t}\n\t}\n\ttemp_1 = p;\n\ttemp_2 = p;\n\tfor(k = t-1; k>0; k--){\n\t\tp= 1;\n\t\tfor(j = 0; j<length; j++){\n\t\t\tif(basis_vec->at(j)->at(0)==k){\n\t\t\t\tMulMod(p,p,a_temp.at(j),mod);\n\t\t\t}\n\t\t}\n\t\tMulMod(temp_1,temp_1,p,mod);\n\t\tMulMod(temp_2,temp_1,temp_2,mod);\n\t}\n\tMulMod(prod, prod,temp_2,mod);\n\tpro = Mod_p(prod,  mod);\n}\n\n\nvector<vector<ZZ>* >* multi_expo::calc_Yk(vector<ZZ>* y, int win){\n\tvector<vector<ZZ>* >* ret;\n\tvector<ZZ>* temp;\n\tlong h,t, i,j,k,e;\n\tdouble two=2;\n\tZZ prod, mod, tem;\n\tmod = H.get_mod();\n\tvector<vector<int>* >* binary;\n\n\th= y->size()/win;\n\te = pow(two, win);\n\tbinary = to_binary(win);\n\n\tif((unsigned) h*win ==y->size()){\n\t\tret = new vector<vector<ZZ>* >(h);\n\t\tfor(i =0; i<h; i++){\n\t\t\ttemp = new vector<ZZ>(e);\n\t\t\tfor(j=0; j<e; j++){\n\t\t\t\tprod = 1;\n\t\t\t\tfor(k=0; k<win; k++){\n\t\t\t\t\tPowerMod(tem,y->at(i*win+k), binary->at(j)->at(k), mod);\n\t\t\t\t\tMulMod(prod,prod,tem,mod);\n\t\t\t\t}\n\t\t\t\ttemp->at(j)=prod;\n\t\t\t}\n\t\t\tret->at(i)=temp;\n\t\t}\n\t}\n\telse{\n\t\tret = new vector<vector<ZZ>* >(h+1);\n\t\tt= y->size()-h*win;\n\t\tfor(i =0; i<h; i++){\n\t\t\ttemp = new vector<ZZ>(e);\n\t\t\tfor(j=0; j<e; j++){\n\t\t\t\tprod = 1;\n\t\t\t\tfor(k=0; k<win; k++){\n\t\t\t\t\tPowerMod(tem,y->at(i*win+k), binary->at(j)->at(k), mod);\n\t\t\t\t\tMulMod(prod,prod,tem,mod);\n\t\t\t\t}\n\t\t\t\ttemp->at(j)=prod;\n\t\t\t}\n\t\t\tret->at(i)=temp;\n\t\t}\n\t\ttemp = new vector<ZZ>(e);\n\t\tfor(j=0; j<e; j++){\n\t\t\tprod = 1;\n\t\t\tfor(k=0; k<t; k++){\n\t\t\t\tPowerMod(tem,y->at(h*win+k), binary->at(j)->at(k), mod);\n\t\t\t\tMulMod(prod,prod,tem,mod);\n\t\t\t}\n\t\t\ttemp->at(j)=prod;\n\t\t}\n\t\tret->at(h)=temp;\n\n\t}\n\tfor (i = 0; i<e; i++){\n\t\tdelete binary->at(i);\n\t\tbinary->at(i)= 0;\n\t}\n\tdelete binary;\n\treturn ret;\n\n}\n\nvector<vector<Mod_p>* >* multi_expo::calc_Yk(vector<Mod_p>* y, int win){\n\tvector<vector<Mod_p>* >* ret;\n\tvector<Mod_p>* temp;\n\tlong h,t, i,j,k,e;\n\tdouble two=2;\n\tMod_p prod, tem;\n\tvector<vector<int>* >* binary;\n\n\th= y->size()/win;\n\te = pow(two, win);\n\tbinary = to_binary(win);\n\n\tif((unsigned)h*win == y->size()){\n\t\tret = new vector<vector<Mod_p>* >(h);\n\t\tfor(i =0; i<h; i++){\n\t\t\ttemp = new vector<Mod_p>(e);\n\t\t\tfor(j=0; j<e; j++){\n\t\t\t\tprod = Mod_p(1,G.get_mod());\n\t\t\t\tfor(k=0; k<win; k++){\n\t\t\t\t\tMod_p::expo(tem,y->at(i*win+k), binary->at(j)->at(k));\n\t\t\t\t\tMod_p::mult(prod,prod,tem);\n\t\t\t\t}\n\t\t\t\ttemp->at(j)=prod;\n\t\t\t}\n\t\t\tret->at(i)=temp;\n\t\t}\n\t}\n\telse{\n\t\tret = new vector<vector<Mod_p>* >(h+1);\n\t\tt=y->size()-h*win;\n\t\tfor(i =0; i<h; i++){\n\t\t\ttemp = new vector<Mod_p>(e);\n\t\t\tfor(j=0; j<e; j++){\n\t\t\t\tprod = Mod_p(1,G.get_mod());\n\t\t\t\tfor(k=0; k<win; k++){\n\t\t\t\t\tMod_p::expo(tem,y->at(i*win+k), binary->at(j)->at(k));\n\t\t\t\t\tMod_p::mult(prod,prod, tem);\n\t\t\t\t}\n\t\t\t\ttemp->at(j)=prod;\n\t\t\t}\n\t\t\tret->at(i)=temp;\n\t\t}\n\t\ttemp = new vector<Mod_p>(e);\n\t\tfor(j=0; j<e; j++){\n\t\t\tprod =  Mod_p(1,G.get_mod());;\n\t\t\tfor(k=0; k<t; k++){\n\t\t\t\tMod_p::expo(tem,y->at(h*win+k), binary->at(j)->at(k));\n\t\t\t\tMod_p::mult(prod,prod,tem);\n\t\t\t}\n\t\t\ttemp->at(j)=prod;\n\t\t}\n\t\tret->at(h)=temp;\n\n\t}\n\tj = binary->size();\n\tfor(i=0; i<j; i++){\n\t\tdelete binary->at(i);\n\t\tbinary->at(i)=0;\n\t}\n\tfor (i = 0; i<e; i++){\n\t\tdelete binary->at(i);\n\t\tbinary->at(i)= 0;\n\t}\n\tdelete binary;\n\treturn ret;\n\n}\nvector<vector<ZZ>* >* multi_expo::calc_Yk(vector<vector<vector<ZZ>*>*>* y, int win, long pos, long pos_2){\n\tvector<vector<ZZ>* >* ret;\n\tvector<ZZ>* temp;\n\tlong h,t, i,j,k,e;\n\tdouble two=2;\n\tZZ prod, mod;\n\tmod = H.get_mod();\n\tvector<vector<int>* >* binary;\n\n\th= y->size()/win;\n\te = pow(two, win);\n\tbinary = to_binary(win);\n\n\tif((unsigned)h*win ==y->size()){\n\t\tret = new vector<vector<ZZ>* >(h);\n\t\tfor(i =0; i<h; i++){\n\t\t\ttemp = new vector<ZZ>(e);\n\t\t\tfor(j=0; j<e; j++){\n\t\t\t\tprod = 1;\n\t\t\t\tfor(k=0; k<win; k++){\n\t\t\t\t\tMulMod(prod,prod,PowerMod(y->at(i*win+k)->at(pos_2)->at(pos), binary->at(j)->at(k), mod),mod);\n\t\t\t\t}\n\t\t\t\ttemp->at(j)=prod;\n\t\t\t}\n\t\t\tret->at(i)=temp;\n\t\t}\n\t}\n\telse{\n\t\tret = new vector<vector<ZZ>*>(h+1);\n\t\tt= y->size()-h*win;\n\t\tfor(i =0; i<h; i++){\n\t\t\ttemp = new vector<ZZ>(e);\n\t\t\tfor(j=0; j<e; j++){\n\t\t\t\tprod = 1;\n\t\t\t\tfor(k=0; k<win; k++){\n\t\t\t\t\tMulMod(prod,prod,PowerMod(y->at(i*win+k)->at(pos_2)->at(pos), binary->at(j)->at(k), mod),mod);\n\t\t\t\t}\n\t\t\t\ttemp->at(j)=prod;\n\t\t\t}\n\t\t\tret->at(i)=temp;\n\t\t}\n\t\ttemp = new vector<ZZ>(e);\n\t\tfor(j=0; j<e; j++){\n\t\t\tprod = 1;\n\t\t\tfor(k=0; k<t; k++){\n\t\t\t\tMulMod(prod,prod,PowerMod(y->at(h*win+k)->at(pos_2)->at(pos), binary->at(j)->at(k), mod),mod);\n\t\t\t}\n\t\t\ttemp->at(j)=prod;\n\t\t}\n\t\tret->at(h)=temp;\n\n\t}\n\tfor (i = 0; i<e; i++){\n\t\t\tdelete binary->at(i);\n\t\t\tbinary->at(i)= 0;\n\t\t}\n\tdelete binary;\n\treturn ret;\n\n}\n\n\n\nZZ multi_expo::multi_expo_LL(vector<ZZ>* y, vector<vector<ZZ>*>* e, int win, long pos){\n\tvector<vector<ZZ>*>* Yk;\n\tZZ ret;\n\tdouble two = 2;\n\tint expo, tem, i,j,k,h;\n\n\tZZ mod = H.get_mod();\n\tlong t = NumBits(H.get_ord());\n\th= y->size()/win;\n\tYk = calc_Yk(y,win);\n\tret = 1;\n\n\tif((unsigned)h*win == y->size()){\n\t\tfor(i=0; i<h; i++){\n\t\t\texpo=0;\n\t\t\tfor(j=i*win; j<(i+1)*win; j++){\n\t\t\t\texpo = expo + bit(e->at(j)->at(pos),t-1)*pow(two,j-i*win);\n\t\t\t}\n\t\t\tMulMod(ret,ret,Yk->at(i)->at(expo),mod);\n\t\t}\n\t\tfor(k=t-2;k>=0; k--){\n\t\t\tSqrMod(ret, ret,mod);\n\t\t\tfor(i=0; i<h; i++){\n\t\t\t\texpo=0;\n\t\t\t\tfor(j=i*win; j<(i+1)*win; j++){\n\t\t\t\t\texpo = expo+ bit(e->at(j)->at(pos),k)*pow(two,j-i*win);\n\t\t\t\t}\n\t\t\t\tMulMod(ret,ret,Yk->at(i)->at(expo),mod);\n\t\t\t}\n\t\t}\n\t}\n\telse{\n\t\ttem= y->size()-h*win;\n\t\tfor(i=0; i<h; i++){\n\t\t\texpo=0;\n\t\t\tfor(j=i*win; j<(i+1)*win; j++){\n\t\t\t\texpo = expo + bit(e->at(j)->at(pos),t-1)*pow(two,j-i*win);\n\t\t\t}\n\t\t\tMulMod(ret,ret,Yk->at(i)->at(expo),mod);\n\t\t}\n\t\texpo=0;\n\t\tfor(j=h*win; j<h*win+tem; j++){\n\t\t\texpo = expo + bit(e->at(j)->at(pos),t-1)*pow(two,j-h*win);\n\t\t}\n\t\tMulMod(ret,ret,Yk->at(h)->at(expo),mod);\n\t\tfor(k=t-2;k>=0; k--){\n\t\t\tSqrMod(ret, ret,mod);\n\t\t\tfor(i=0; i<h; i++){\n\t\t\t\texpo=0;\n\t\t\t\tfor(j=i*win; j<(i+1)*win; j++){\n\t\t\t\t\texpo = expo+ bit(e->at(j)->at(pos),k)*pow(two,j-i*win);\n\t\t\t\t}\n\t\t\t\tMulMod(ret,ret,Yk->at(i)->at(expo),mod);\n\t\t\t}\n\t\t\texpo=0;\n\t\t\tfor(j=h*win; j<h*win+tem; j++){\n\t\t\t\texpo = expo+ bit(e->at(j)->at(pos),k)*pow(two,j-h*win);\n\t\t\t}\n\t\t\tMulMod(ret,ret,Yk->at(h)->at(expo),mod);\n\t\t}\n\t}\n\tj = Yk->size();\n\tfor(i=0; i<j; i++){\n\t\tdelete Yk->at(i);\n\t\tYk->at(i)=0;\n\t}\n\tdelete Yk;\n\treturn ret;\n\n}\n\nvoid multi_expo::multi_expo_LL(ZZ& ret, vector<ZZ>* y, vector<vector<ZZ>*>* e, int win, long pos){\n\tvector<vector<ZZ>*>* Yk;\n\t//ZZ ret;\n\tdouble two = 2;\n\tint expo, tem, i,j,k,h;\n\n\tZZ mod = H.get_mod();\n\tlong t = NumBits(H.get_ord());\n\th= y->size()/win;\n\tYk = calc_Yk(y,win);\n\tret = 1;\n\n\tif((unsigned)h*win == y->size()){\n\t\tfor(i=0; i<h; i++){\n\t\t\texpo=0;\n\t\t\tfor(j=i*win; j<(i+1)*win; j++){\n\t\t\t\texpo = expo + bit(e->at(j)->at(pos),t-1)*pow(two,j-i*win);\n\t\t\t}\n\t\t\tMulMod(ret,ret,Yk->at(i)->at(expo),mod);\n\t\t}\n\t\tfor(k=t-2;k>=0; k--){\n\t\t\tSqrMod(ret, ret,mod);\n\t\t\tfor(i=0; i<h; i++){\n\t\t\t\texpo=0;\n\t\t\t\tfor(j=i*win; j<(i+1)*win; j++){\n\t\t\t\t\texpo = expo+ bit(e->at(j)->at(pos),k)*pow(two,j-i*win);\n\t\t\t\t}\n\t\t\t\tMulMod(ret,ret,Yk->at(i)->at(expo),mod);\n\t\t\t}\n\t\t}\n\t}\n\telse{\n\t\ttem= y->size()-h*win;\n\t\tfor(i=0; i<h; i++){\n\t\t\texpo=0;\n\t\t\tfor(j=i*win; j<(i+1)*win; j++){\n\t\t\t\texpo = expo + bit(e->at(j)->at(pos),t-1)*pow(two,j-i*win);\n\t\t\t}\n\t\t\tMulMod(ret,ret,Yk->at(i)->at(expo),mod);\n\t\t}\n\t\texpo=0;\n\t\tfor(j=h*win; j<h*win+tem; j++){\n\t\t\texpo = expo + bit(e->at(j)->at(pos),t-1)*pow(two,j-h*win);\n\t\t}\n\t\tMulMod(ret,ret,Yk->at(h)->at(expo),mod);\n\t\tfor(k=t-2;k>=0; k--){\n\t\t\tSqrMod(ret, ret,mod);\n\t\t\tfor(i=0; i<h; i++){\n\t\t\t\texpo=0;\n\t\t\t\tfor(j=i*win; j<(i+1)*win; j++){\n\t\t\t\t\texpo = expo+ bit(e->at(j)->at(pos),k)*pow(two,j-i*win);\n\t\t\t\t}\n\t\t\t\tMulMod(ret,ret,Yk->at(i)->at(expo),mod);\n\t\t\t}\n\t\t\texpo=0;\n\t\t\tfor(j=h*win; j<h*win+tem; j++){\n\t\t\t\texpo = expo+ bit(e->at(j)->at(pos),k)*pow(two,j-h*win);\n\t\t\t}\n\t\t\tMulMod(ret,ret,Yk->at(h)->at(expo),mod);\n\t\t}\n\t}\n\tj = Yk->size();\n\tfor(i=0; i<j; i++){\n\t\tdelete Yk->at(i);\n\t\tYk->at(i)=0;\n\t}\n\tdelete Yk;\n\n}\n\nZZ multi_expo::multi_expo_LL(vector<vector<vector<ZZ>*>*>* y, vector<vector<ZZ>*>* e, int win, long pos, long pos_2){\n\tvector<vector<ZZ>*>* Yk;\n\tZZ ret;\n\tdouble two = 2;\n\tint expo, tem, i,j,k,h;\n\n\tZZ mod = H.get_mod();\n\tlong t = NumBits(H.get_ord());\n\th= y->size()/win;\n\tYk = calc_Yk(y,win, pos, pos_2);\n\n\tret = 1;\n\n\tif((unsigned)h*win == y->size()){\n\t\tfor(i=0; i<h; i++){\n\t\t\texpo=0;\n\t\t\tfor(j=i*win; j<(i+1)*win; j++){\n\t\t\t\texpo = expo + bit(e->at(j)->at(pos),t-1)*pow(two,j-i*win);\n\t\t\t}\n\t\t\tMulMod(ret,ret,Yk->at(i)->at(expo),mod);\n\t\t}\n\t\tfor(k=t-2;k>=0; k--){\n\t\t\tSqrMod(ret,ret,mod);\n\t\t\tfor(i=0; i<h; i++){\n\t\t\t\texpo=0;\n\t\t\t\tfor(j=i*win; j<(i+1)*win; j++){\n\t\t\t\t\texpo = expo+ bit(e->at(j)->at(pos),k)*pow(two,j-i*win);\n\t\t\t\t}\n\t\t\t\tMulMod(ret, ret,Yk->at(i)->at(expo),mod);\n\t\t\t}\n\t\t}\n\t}\n\telse{\n\t\ttem= y->size()-h*win;\n\t\tfor(i=0; i<h; i++){\n\t\t\texpo=0;\n\t\t\tfor(j=i*win; j<(i+1)*win; j++){\n\t\t\t\texpo = expo + bit(e->at(j)->at(pos),t-1)*pow(two,j-i*win);\n\t\t\t}\n\t\t\tMulMod(ret,ret,Yk->at(i)->at(expo),mod);\n\t\t}\n\t\texpo=0;\n\t\tfor(j=h*win; j<h*win+tem; j++){\n\t\t\texpo = expo + bit(e->at(j)->at(pos),t-1)*pow(two,j-h*win);\n\t\t}\n\t\tMulMod(ret,ret,Yk->at(h)->at(expo),mod);\n\t\tfor(k=t-2;k>=0; k--){\n\t\t\tSqrMod(ret,ret,mod);\n\t\t\tfor(i=0; i<h; i++){\n\t\t\t\texpo=0;\n\t\t\t\tfor(j=i*win; j<(i+1)*win; j++){\n\t\t\t\t\texpo = expo+ bit(e->at(j)->at(pos),k)*pow(two,j-i*win);\n\t\t\t\t}\n\t\t\t\tMulMod(ret,ret,Yk->at(i)->at(expo),mod);\n\t\t\t}\n\t\t\texpo=0;\n\t\t\tfor(j=h*win; j<h*win+tem; j++){\n\t\t\t\texpo = expo+ bit(e->at(j)->at(pos),k)*pow(two,j-h*win);\n\t\t\t}\n\t\t\tMulMod(ret,ret,Yk->at(h)->at(expo),mod);\n\t\t}\n\t}\n\tj = Yk->size();\n\tfor(i=0; i<j; i++){\n\t\tdelete Yk->at(i);\n\t\tYk->at(i)=0;\n\t}\n\tdelete Yk;\n\treturn ret;\n\n}\n\nvoid multi_expo::multi_expo_LL(ZZ& ret, vector<vector<vector<ZZ>*>*>* y, vector<vector<ZZ>*>* e, int win, long pos, long pos_2){\n\tvector<vector<ZZ>*>* Yk;\n\t//ZZ ret;\n\tdouble two = 2;\n\tint expo, tem, i,j,k,h;\n\n\tZZ mod = H.get_mod();\n\tlong t = NumBits(H.get_ord());\n\th= y->size()/win;\n\tYk = calc_Yk(y,win, pos, pos_2);\n\n\tret = 1;\n\n\tif((unsigned)h*win == y->size()){\n\t\tfor(i=0; i<h; i++){\n\t\t\texpo=0;\n\t\t\tfor(j=i*win; j<(i+1)*win; j++){\n\t\t\t\texpo = expo + bit(e->at(j)->at(pos),t-1)*pow(two,j-i*win);\n\t\t\t}\n\t\t\tMulMod(ret,ret,Yk->at(i)->at(expo),mod);\n\t\t}\n\t\tfor(k=t-2;k>=0; k--){\n\t\t\tSqrMod(ret,ret,mod);\n\t\t\tfor(i=0; i<h; i++){\n\t\t\t\texpo=0;\n\t\t\t\tfor(j=i*win; j<(i+1)*win; j++){\n\t\t\t\t\texpo = expo+ bit(e->at(j)->at(pos),k)*pow(two,j-i*win);\n\t\t\t\t}\n\t\t\t\tMulMod(ret, ret,Yk->at(i)->at(expo),mod);\n\t\t\t}\n\t\t}\n\t}\n\telse{\n\t\ttem= y->size()-h*win;\n\t\tfor(i=0; i<h; i++){\n\t\t\texpo=0;\n\t\t\tfor(j=i*win; j<(i+1)*win; j++){\n\t\t\t\texpo = expo + bit(e->at(j)->at(pos),t-1)*pow(two,j-i*win);\n\t\t\t}\n\t\t\tMulMod(ret,ret,Yk->at(i)->at(expo),mod);\n\t\t}\n\t\texpo=0;\n\t\tfor(j=h*win; j<h*win+tem; j++){\n\t\t\texpo = expo + bit(e->at(j)->at(pos),t-1)*pow(two,j-h*win);\n\t\t}\n\t\tMulMod(ret,ret,Yk->at(h)->at(expo),mod);\n\t\tfor(k=t-2;k>=0; k--){\n\t\t\tSqrMod(ret,ret,mod);\n\t\t\tfor(i=0; i<h; i++){\n\t\t\t\texpo=0;\n\t\t\t\tfor(j=i*win; j<(i+1)*win; j++){\n\t\t\t\t\texpo = expo+ bit(e->at(j)->at(pos),k)*pow(two,j-i*win);\n\t\t\t\t}\n\t\t\t\tMulMod(ret,ret,Yk->at(i)->at(expo),mod);\n\t\t\t}\n\t\t\texpo=0;\n\t\t\tfor(j=h*win; j<h*win+tem; j++){\n\t\t\t\texpo = expo+ bit(e->at(j)->at(pos),k)*pow(two,j-h*win);\n\t\t\t}\n\t\t\tMulMod(ret,ret,Yk->at(h)->at(expo),mod);\n\t\t}\n\t}\n\tj = Yk->size();\n\tfor(i=0; i<j; i++){\n\t\tdelete Yk->at(i);\n\t\tYk->at(i)=0;\n\t}\n\tdelete Yk;\n}\n\nMod_p multi_expo::multi_expo_LL(vector<Mod_p>* y, vector<ZZ>* e, int win){\n\tvector<vector<Mod_p>*>* Yk;\n\tMod_p ret;\n\tdouble two = 2;\n\tint expo, i,j,k,h,t,tem;\n\tt = NumBits(G.get_ord());\n\n\th= y->size()/win;\n\tYk = calc_Yk(y,win);\n\tret = Mod_p(1,G.get_mod());\n\tif((unsigned)win*h==y->size()){\n\t\tfor(i=0; i<h; i++){\n\t\t\texpo=0;\n\t\t\tfor(j=i*win; j<(i+1)*win; j++){\n\t\t\t\texpo = expo + bit(e->at(j),t-1)*pow(two,j-i*win);\n\t\t\t}\n\t\t\tMod_p::mult(ret ,ret,Yk->at(i)->at(expo));\n\t\t}\n\n\t\tfor(k=t-2;k>=0; k--){\n\t\t\tret = ret*ret;\n\t\t\tfor(i=0; i<h; i++){\n\t\t\t\texpo=0;\n\t\t\t\tfor(j=i*win; j<(i+1)*win; j++){\n\t\t\t\t\texpo = expo+ bit(e->at(j),k)*pow(two,j-i*win);\n\t\t\t\t}\n\t\t\t\tMod_p::mult(ret ,ret,Yk->at(i)->at(expo));\n\t\t\t}\n\t\t}\n\t}\n\telse{\n\t\ttem=y->size()-h*win;\n\t\tfor(i=0; i<h; i++){\n\t\t\texpo=0;\n\t\t\tfor(j=i*win; j<(i+1)*win; j++){\n\t\t\t\texpo = expo + bit(e->at(j),t-1)*pow(two,j-i*win);\n\t\t\t}\n\t\t\tMod_p::mult(ret ,ret,Yk->at(i)->at(expo));\n\t\t}\n\t\texpo=0;\n\t\tfor(j=h*win; j<h*win+tem; j++){\n\t\t\texpo = expo + bit(e->at(j),t-1)*pow(two,j-h*win);\n\t\t}\n\t\tMod_p::mult(ret ,ret,Yk->at(h)->at(expo));\n\n\t\tfor(k=t-2;k>=0; k--){\n\t\t\tret = ret*ret;\n\t\t\tfor(i=0; i<h; i++){\n\t\t\t\texpo=0;\n\t\t\t\tfor(j=i*win; j<(i+1)*win; j++){\n\t\t\t\t\texpo = expo+ bit(e->at(j),k)*pow(two,j-i*win);\n\t\t\t\t}\n\t\t\t\tMod_p::mult(ret,ret,Yk->at(i)->at(expo));\n\t\t\t}\n\t\t\texpo=0;\n\t\t\tfor(j=h*win; j<h*win+tem; j++){\n\t\t\t\texpo = expo + bit(e->at(j),k)*pow(two,j-h*win);\n\t\t\t}\n\t\t\tMod_p::mult(ret ,ret,Yk->at(h)->at(expo));\n\t\t}\n\n\t}\n\tj = Yk->size();\n\tfor(i=0; i<j; i++){\n\t\tdelete Yk->at(i);\n\t\tYk->at(i)=0;\n\t}\n\tdelete Yk;\n\treturn ret;\n}\n\n\nvoid multi_expo::multi_expo_LL(Mod_p& ret, vector<Mod_p>* y, vector<ZZ>* e, int win){\n\tvector<vector<Mod_p>*>* Yk;\n\n\tdouble two = 2;\n\tint expo, i,j,k,h,t,tem;\n\tlong length;\n\n\tt = NumBits(G.get_ord());\n/*\tif(e->size() < y->size()){\n\t\tlength = e->size();\n\t\th= length/win;\n\t} else {*/\n\t\tlength = y->size();\n\t\th = length/win;\n\t//}\n\tYk = calc_Yk(y,win);\n\tret = Mod_p(1,G.get_mod());\n\n\tif(win*h==length){\n\t\tfor(i=0; i<h; i++){\n\t\t\texpo=0;\n\t\t\tfor(j=i*win; j<(i+1)*win; j++){\n\t\t\t\texpo = expo + bit(e->at(j),t-1)*pow(two,j-i*win);\n\t\t\t}\n\t\t\tMod_p::mult(ret ,ret,Yk->at(i)->at(expo));\n\t\t}\n\n\t\tfor(k=t-2;k>=0; k--){\n\t\t\tret = ret*ret;\n\t\t\tfor(i=0; i<h; i++){\n\t\t\t\texpo=0;\n\t\t\t\tfor(j=i*win; j<(i+1)*win; j++){\n\t\t\t\t\texpo = expo+ bit(e->at(j),k)*pow(two,j-i*win);\n\t\t\t\t}\n\t\t\t\tMod_p::mult(ret ,ret,Yk->at(i)->at(expo));\n\t\t\t}\n\t\t}\n\t}\n\telse{\n\t\ttem=length-h*win;\n\t\tfor(i=0; i<h; i++){\n\t\t\texpo=0;\n\t\t\tfor(j=i*win; j<(i+1)*win; j++){\n\t\t\t\texpo = expo + bit(e->at(j),t-1)*pow(two,j-i*win);\n\t\t\t}\n\t\t\tMod_p::mult(ret ,ret,Yk->at(i)->at(expo));\n\t\t}\n\t\texpo=0;\n\t\tfor(j=h*win; j<h*win+tem; j++){\n\t\t\texpo = expo + bit(e->at(j),t-1)*pow(two,j-h*win);\n\t\t}\n\t\tMod_p::mult(ret ,ret,Yk->at(h)->at(expo));\n\n\t\tfor(k=t-2;k>=0; k--){\n\t\t\tret = ret*ret;\n\t\t\tfor(i=0; i<h; i++){\n\t\t\t\texpo=0;\n\t\t\t\tfor(j=i*win; j<(i+1)*win; j++){\n\t\t\t\t\texpo = expo+ bit(e->at(j),k)*pow(two,j-i*win);\n\t\t\t\t}\n\t\t\t\tMod_p::mult(ret,ret,Yk->at(i)->at(expo));\n\t\t\t}\n\t\t\texpo=0;\n\t\t\tfor(j=h*win; j<h*win+tem; j++){\n\t\t\t\texpo = expo + bit(e->at(j),k)*pow(two,j-h*win);\n\t\t\t}\n\t\t\tMod_p::mult(ret ,ret,Yk->at(h)->at(expo));\n\t\t}\n\n\t}\n\tj = Yk->size();\n\tfor(i=0; i<j; i++){\n\t\tdelete Yk->at(i);\n\t\tYk->at(i)=0;\n\t}\n\tdelete Yk;\n}\n\nvoid multi_expo::multi_expo_LL(ZZ& ret, vector<ZZ>* y, vector<ZZ>* e, int win){\n\tvector<vector<ZZ>*>* Yk;\n\n\tdouble two = 2;\n\tint expo, tem, i,j,k,h;\n\n\tZZ mod = H.get_mod();\n\tlong t = NumBits(H.get_ord());\n\th= y->size()/win;\n\tYk = calc_Yk(y,win);\n\tret = 1;\n\n\tif((unsigned)h*win == y->size()){\n\t\tfor(i=0; i<h; i++){\n\t\t\texpo=0;\n\t\t\tfor(j=i*win; j<(i+1)*win; j++){\n\t\t\t\texpo = expo + bit(e->at(j),t-1)*pow(two,j-i*win);\n\t\t\t}\n\t\t\tMulMod(ret,ret,Yk->at(i)->at(expo),mod);\n\t\t}\n\t\tfor(k=t-2;k>=0; k--){\n\t\t\tSqrMod(ret, ret,mod);\n\t\t\tfor(i=0; i<h; i++){\n\t\t\t\texpo=0;\n\t\t\t\tfor(j=i*win; j<(i+1)*win; j++){\n\t\t\t\t\texpo = expo+ bit(e->at(j),k)*pow(two,j-i*win);\n\t\t\t\t}\n\t\t\t\tMulMod(ret,ret,Yk->at(i)->at(expo),mod);\n\t\t\t}\n\t\t}\n\t}\n\telse{\n\t\ttem= y->size()-h*win;\n\t\tfor(i=0; i<h; i++){\n\t\t\texpo=0;\n\t\t\tfor(j=i*win; j<(i+1)*win; j++){\n\t\t\t\texpo = expo + bit(e->at(j),t-1)*pow(two,j-i*win);\n\t\t\t}\n\t\t\tMulMod(ret,ret,Yk->at(i)->at(expo),mod);\n\t\t}\n\t\texpo=0;\n\t\tfor(j=h*win; j<h*win+tem; j++){\n\t\t\texpo = expo + bit(e->at(j),t-1)*pow(two,j-h*win);\n\t\t}\n\t\tMulMod(ret,ret,Yk->at(h)->at(expo),mod);\n\t\tfor(k=t-2;k>=0; k--){\n\t\t\tSqrMod(ret, ret,mod);\n\t\t\tfor(i=0; i<h; i++){\n\t\t\t\texpo=0;\n\t\t\t\tfor(j=i*win; j<(i+1)*win; j++){\n\t\t\t\t\texpo = expo+ bit(e->at(j),k)*pow(two,j-i*win);\n\t\t\t\t}\n\t\t\t\tMulMod(ret,ret,Yk->at(i)->at(expo),mod);\n\t\t\t}\n\t\t\texpo=0;\n\t\t\tfor(j=h*win; j<h*win+tem; j++){\n\t\t\t\texpo = expo+ bit(e->at(j),k)*pow(two,j-h*win);\n\t\t\t}\n\t\t\tMulMod(ret,ret,Yk->at(h)->at(expo),mod);\n\t\t}\n\t}\n\tj = Yk->size();\n\tfor(i=0; i<j; i++){\n\t\tdelete Yk->at(i);\n\t\tYk->at(i)=0;\n\t}\n\tdelete Yk;\n\n}\n\nvoid multi_expo::multi_expo_LL(Cipher_elg& ret, Cipher_elg c1, Cipher_elg c2, Cipher_elg c3, Cipher_elg c4, vector<ZZ>* e, int win){\n\n\tZZ ret_u, ret_v;\n\tvector<ZZ>* c_u;\n\tvector<ZZ>* c_v;\n\n\tc_u = new vector<ZZ>(4);\n\tc_u->at(0) = c1.get_u();\n\tc_u->at(1) = c2.get_u();\n\tc_u ->at(2) = c3.get_u();\n\tc_u->at(3) = c4.get_u();\n\n\tc_v = new vector<ZZ>(4);\n\tc_v->at(0) = c1.get_v();\n\tc_v->at(1) = c2.get_v();\n\tc_v ->at(2) = c3.get_v();\n\tc_v->at(3) = c4.get_v();\n\n\tmulti_expo_LL(ret_u, c_u, e, win);\n\tmulti_expo_LL(ret_v, c_v, e, win);\n\tdelete c_u;\n\tdelete c_v;\n\tret = Cipher_elg(ret_u, ret_v, H.get_mod());\n\n\n}\n\nvector<int>* multi_expo::to_basis_sw(ZZ e, long num_b, int omega_sw){\n\n\tlong i, j, t, te;\n\tvector<int>* temp;\n\tvector<int>* basis;\n\ttemp = new vector<int>(omega_sw);\n\tbasis = new vector<int>(num_b);\n\n\ti = num_b-1;\n\twhile(i>=omega_sw){\n\t\tif (bit(e,i)==0){\n\t\t\tbasis->at(i)=0;\n\t\t\ti=i-1;\n\t\t}\n\t\telse{\n\t\t\tfor(t= i-omega_sw+1; t < i+1; t++){\n\t\t\t\tif(bit(e,t)==1){\n\t\t\t\t\tte = i-t;\n\t\t\t\t\tfor(j = 0; j<= te; j++){\n\t\t\t\t\t\ttemp->at(j)=bit(e, t+j);\n\t\t\t\t\t}\n\t\t\t\t\tfor(j =te+1; j<omega_sw; j++){\n\t\t\t\t\t\ttemp->at(j) =0;\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\tbasis->at(t)= to_long(temp);\n\t\t\tfor(j = t+1; j<=i; j++){\n\t\t\t\tbasis->at(j)=0;\n\t\t\t}\n\t\t\ti=t-1;\n\t\t}\n\t}\n\twhile(i>=0){\n\t\tif (bit(e,i)==0){\n\t\t\tbasis->at(i)=0;\n\t\t\ti=i-1;\n\t\t}\n\t\telse{\n\t\t\tfor(t= 0; t < i+1; t++){\n\t\t\t\tif(bit(e,t)==1){\n\t\t\t\t\tte = i-t;\n\t\t\t\t\tfor(j = 0; j<= te; j++){\n\t\t\t\t\t\ttemp->at(j)=bit(e, t+j);\n\t\t\t\t\t}\n\t\t\t\t\tfor(j =te+1; j<omega_sw; j++){\n\t\t\t\t\t\ttemp->at(j) =0;\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\tbasis->at(t)= to_long(temp);\n\t\t\tfor(j = t+1; j<=i; j++){\n\t\t\t\tbasis->at(j)=0;\n\t\t\t}\n\t\t\ti=t-1;\n\t\t}\n\n\t}\n\tdelete temp;\n\treturn basis;\n}\n\n\nZZ multi_expo::multi_expo_sw( ZZ e_1, ZZ e_2, int omega_sw,  vector<vector<ZZ>* >* gen_prec){\n\tlong i;\n\tint t_1, t_2;\n\tZZ prod, p;\n\tvector<int>* E_1;\n\tvector<int>* E_2;\n\tlong num_b;\n\tZZ mod;\n\tmod = G.get_mod();\n\tnum_b = NumBits(G.get_ord());\n\tE_1 = to_basis_sw(e_1, num_b, omega_sw);\n\tE_2 = to_basis_sw(e_2, num_b, omega_sw);\n\tprod = 1;\n\tt_1 = 0;\n\tt_2 = 0;\n\tt_1 = (E_1->at(num_b-1)+1)/2;\n\tt_2 = (E_2->at(num_b-1)+1)/2;\n\tif ( t_1> 0){\n\t\tMulMod(prod,prod,gen_prec->at(0)->at(t_1-1),mod);\n\t}\n\tif ( t_2> 0){\n\t\tMulMod(prod,prod,gen_prec->at(1)->at(t_2-1),mod);\n\t}\n\tfor(i = num_b-2; i>=0; i--){\n\t\tt_1 = (E_1->at(i)+1)/2;\n\t\tt_2 = (E_2->at(i)+1)/2;\n\t\tSqrMod(prod,prod, mod);\n\t\tif ( t_1> 0){\n\t\t\tMulMod(prod,prod,gen_prec->at(0)->at(t_1-1),mod);\n\t\t}\n\t\tif ( t_2> 0){\n\t\t\tMulMod(prod,prod,gen_prec->at(1)->at(t_2-1),mod);\n\t\t}\n\t}\n\tdelete E_1;\n\tdelete E_2;\n\t return prod;\n}\n\nvoid multi_expo::multi_expo_sw(ZZ& prod, ZZ e_1, ZZ e_2, int omega_sw, vector<vector<ZZ>* >* gen_prec){\n\tlong i;\n\tint t_1, t_2;\n\tZZ p;\n\tvector<int>* E_1;\n\tvector<int>* E_2;\n\tlong num_b;\n\tZZ mod;\n\tmod = G.get_mod();\n\tnum_b = NumBits(G.get_ord());\n\tE_1 = to_basis_sw(e_1, num_b, omega_sw);\n\tE_2 = to_basis_sw(e_2, num_b, omega_sw);\n\tprod = 1;\n\tt_1 = 0;\n\tt_2 = 0;\n\tt_1 = (E_1->at(num_b-1)+1)/2;\n\tt_2 = (E_2->at(num_b-1)+1)/2;\n\tif ( t_1> 0){\n\t\tMulMod(prod,prod,gen_prec->at(0)->at(t_1-1),mod);\n\t}\n\tif ( t_2> 0){\n\t\tMulMod(prod,prod,gen_prec->at(1)->at(t_2-1),mod);\n\t}\n\tfor(i = num_b-2; i>=0; i--){\n\t\tt_1 = (E_1->at(i)+1)/2;\n\t\tt_2 = (E_2->at(i)+1)/2;\n\t\tSqrMod(prod,prod, mod);\n\t\tif ( t_1> 0){\n\t\t\tMulMod(prod,prod,gen_prec->at(0)->at(t_1-1),mod);\n\t\t}\n\t\tif ( t_2> 0){\n\t\t\tMulMod(prod,prod,gen_prec->at(1)->at(t_2-1),mod);\n\t\t}\n\t}\n\tdelete E_1;\n\tdelete E_2;\n\t// return prod;\n}\n\n\n", "meta": {"hexsha": "45b6203a71f0df1ec3d978bd8522db200cd3c5b4", "size": 47166, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/multi_expo.cpp", "max_stars_repo_name": "3for/verifiable-shuffle", "max_stars_repo_head_hexsha": "73f92b41bbe76eee4ef8ad35e6ccf7e83acef28b", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2018-01-11T14:06:41.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-27T08:28:26.000Z", "max_issues_repo_path": "src/multi_expo.cpp", "max_issues_repo_name": "3for/verifiable-shuffle", "max_issues_repo_head_hexsha": "73f92b41bbe76eee4ef8ad35e6ccf7e83acef28b", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/multi_expo.cpp", "max_forks_repo_name": "3for/verifiable-shuffle", "max_forks_repo_head_hexsha": "73f92b41bbe76eee4ef8ad35e6ccf7e83acef28b", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-04-13T06:11:06.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-03T15:21:49.000Z", "avg_line_length": 21.4293502953, "max_line_length": 135, "alphanum_fraction": 0.5535343256, "num_tokens": 19771, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7461389930307512, "lm_q2_score": 0.411110869232168, "lm_q1q2_score": 0.3067458499928866}}
{"text": "//////////////////////////////////////////////////////////////////////////////\n//\n// (C) Copyright Alejandro Cabrera 2011.\n// Distributed under the Boost\n// Software License, Version 1.0.\n// (See accompanying file LICENSE_1_0.txt or\n// copy at http://www.boost.org/LICENSE_1_0.txt)\n//\n// See http://www.boost.org/libs/bloom_filter for documentation.\n//\n//////////////////////////////////////////////////////////////////////////////\n\n#ifndef BOOST_BLOOM_FILTER_BLOOM_FILTER_HPP\n#define BOOST_BLOOM_FILTER_BLOOM_FILTER_HPP 1\n\n#include <cmath>\n#include <bitset>\n\n#include <boost/config.hpp>\n#include <boost/mpl/vector.hpp>\n#include <boost/mpl/size.hpp>\n\n#include <boost/bloom_filter/detail/apply_hash.hpp>\n#include <boost/bloom_filter/hash/default.hpp>\n\n#ifndef BOOST_NO_0X_HDR_INITIALIZER_LIST\n#include <initializer_list>\n#endif \n\nnamespace boost {\n  namespace bloom_filters {\n    template <typename T,\n\t      size_t Size,\n\t      class HashFunctions = mpl::vector<boost_hash<T> > >\n    class basic_bloom_filter {\n    public:\n      typedef T value_type;\n      typedef T key_type;\n      typedef std::bitset<Size> bitset_type;\n      typedef HashFunctions hash_function_type;\n      typedef basic_bloom_filter<T, Size,\n\t\t\t\t HashFunctions> this_type;\n\n    private:\n      typedef detail::apply_hash<mpl::size<HashFunctions>::value - 1,\n\t\t\t\t this_type> apply_hash_type;\n\n    public:\n      basic_bloom_filter() {}\n\n      template <typename InputIterator>\n      basic_bloom_filter(const InputIterator start, const InputIterator end) {\n\tfor (InputIterator i = start; i != end; ++i)\n\t  this->insert(*i);\n      }\n\n#ifndef BOOST_NO_0X_HDR_INITIALIZER_LIST\n      basic_bloom_filter(const std::initializer_list<T>& ilist) {\n\ttypedef typename std::initializer_list<T>::const_iterator citer;\n\tfor (citer i = ilist.begin(), end = ilist.end(); i != end; ++i) {\n\t  this->insert(*i);\n\t}\n      }\n#endif\n\n      static BOOST_CONSTEXPR size_t bit_capacity() {\n        return Size;\n      }\n\n      static BOOST_CONSTEXPR size_t num_hash_functions() {\n        return mpl::size<HashFunctions>::value;\n      };\n\n      double false_positive_rate() const {\n        const double n = static_cast<double>(this->bits.count());\n        static const double k = static_cast<double>(num_hash_functions());\n        static const double m = static_cast<double>(Size);\n        static const double e =\n\t  2.718281828459045235360287471352662497757247093699959574966;\n        return std::pow(1 - std::pow(e, -k * n / m), k);\n      };\n\n      size_t count() const {\n        return this->bits.count();\n      };\n\n      bool empty() const {\n\treturn this->count() == 0;\n      }\n\n      const bitset_type&\n      data() const\n      {\n\treturn this->bits;\n      }\n\n      void insert(const T& t) {\n        apply_hash_type::insert(t, bits);\n      }\n\n      template <typename InputIterator>\n      void insert(const InputIterator start, const InputIterator end) {\n\tfor (InputIterator i = start; i != end; ++i) {\n\t  this->insert(*i);\n\t}\n      }\n\n      bool probably_contains(const T& t) const {\n        return apply_hash_type::contains(t, bits);\n      }\n\n      void clear() {\n        this->bits.reset();\n      }\n\n      void swap(basic_bloom_filter& other) {\n\tbasic_bloom_filter tmp = other;\n\tother = *this;\n\t*this = tmp;\n      }\n\n      basic_bloom_filter& operator|=(const basic_bloom_filter& rhs) {\n        this->bits |= rhs.bits;\n        return *this;\n      }\n\n      basic_bloom_filter& operator&=(const basic_bloom_filter& rhs) {\n        this->bits &= rhs.bits;\n        return *this;\n      }\n\n      template<class _T, size_t _Size, class _HashFunctions>\n      friend bool\n      operator==(const basic_bloom_filter<_T, _Size, _HashFunctions>&,\n\t\t const basic_bloom_filter<_T, _Size, _HashFunctions>&);\n\n      template<class _T, size_t _Size, class _HashFunctions>\n      friend bool\n      operator!=(const basic_bloom_filter<_T, _Size, _HashFunctions>&,\n\t\t const basic_bloom_filter<_T, _Size, _HashFunctions>&);\n      \n    private:\n      bitset_type bits;\n    };\n\n    template<class _T, size_t _Size, class _HashFunctions>\n    bool\n    operator==(const basic_bloom_filter<_T, _Size, _HashFunctions>& lhs,\n\t       const basic_bloom_filter<_T, _Size, _HashFunctions>& rhs)\n    {\n      return (lhs.bits == rhs.bits);\n    }\n\n    template<class _T, size_t _Size, class _HashFunctions>\n    bool\n    operator!=(const basic_bloom_filter<_T, _Size, _HashFunctions>& lhs,\n\t       const basic_bloom_filter<_T, _Size, _HashFunctions>& rhs)\n    {\n      return !(lhs == rhs);\n    }\n\n    template<class _T, size_t _Size, class _HashFunctions>\n    basic_bloom_filter<_T, _Size, _HashFunctions>\n    operator|(const basic_bloom_filter<_T, _Size, _HashFunctions>& lhs,\n\t      const basic_bloom_filter<_T, _Size, _HashFunctions>& rhs)\n    {\n      basic_bloom_filter<_T, _Size, _HashFunctions> ret(lhs);\n      ret |= rhs;\n      return ret;\n    }\n\n    template<class _T, size_t _Size, class _HashFunctions>\n    basic_bloom_filter<_T, _Size, _HashFunctions>\n    operator&(const basic_bloom_filter<_T, _Size, _HashFunctions>& lhs,\n\t      const basic_bloom_filter<_T, _Size, _HashFunctions>& rhs)\n    {\n      basic_bloom_filter<_T, _Size, _HashFunctions> ret(lhs);\n      ret &= rhs;\n      return ret;\n    }\n\n    template<class _T, size_t _Size, class _HashFunctions>\n    void\n    swap(basic_bloom_filter<_T, _Size, _HashFunctions>& lhs,\n\t basic_bloom_filter<_T, _Size, _HashFunctions>& rhs)\n    {\n      lhs.swap(rhs);\n    }\n  } // namespace bloom_filters\n} // namespace boost\n#endif\n", "meta": {"hexsha": "7fb374e384f5ac5b9a26caeab789c26a3bc10c72", "size": 5493, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/bloom_filter/basic_bloom_filter.hpp", "max_stars_repo_name": "tetzank/boost-bloom-filters", "max_stars_repo_head_hexsha": "7c6717f403c041a092187568908f3661782ddb24", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 15.0, "max_stars_repo_stars_event_min_datetime": "2016-10-18T16:05:37.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-23T03:01:42.000Z", "max_issues_repo_path": "boost/bloom_filter/basic_bloom_filter.hpp", "max_issues_repo_name": "tetzank/boost-bloom-filters", "max_issues_repo_head_hexsha": "7c6717f403c041a092187568908f3661782ddb24", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "boost/bloom_filter/basic_bloom_filter.hpp", "max_forks_repo_name": "tetzank/boost-bloom-filters", "max_forks_repo_head_hexsha": "7c6717f403c041a092187568908f3661782ddb24", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 12.0, "max_forks_repo_forks_event_min_datetime": "2016-04-15T18:17:24.000Z", "max_forks_repo_forks_event_max_datetime": "2020-04-16T06:29:58.000Z", "avg_line_length": 28.609375, "max_line_length": 78, "alphanum_fraction": 0.6444565811, "num_tokens": 1371, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6039318337259584, "lm_q2_score": 0.5078118642792044, "lm_q1q2_score": 0.30668375038193746}}
{"text": "//#define BZ_DEBUG\n\n#ifdef BZ_DEBUG\n#warning BZ_DEBUG aktiviert!\n#define DEBUG_MSG \"BZ_DEBUG aktiviert! \"\n#else\n#warning ohne BZ_DEBUG\n#define DEBUG_MSG \"ohne BZ_DEBUG: \"\n#endif\n\n#include <cstdio>\n#include <cmath>\n#include <string>\n#include <iostream>\n#include <sstream>\n#include <fstream>\n#include <typeinfo>\n#include <stdexcept>\n#include <complex>\n#include <algorithm>\n#include <Magick++.h>\n#include <fftw3.h>\n#include <sys/time.h>\n#include <boost/any.hpp>\n#include <boost/program_options.hpp>\n#include <boost/program_options/options_description.hpp>\n#include <boost/algorithm/string.hpp>\n#include <boost/numeric/conversion/bounds.hpp>\n#include <boost/limits.hpp>\n#include <blitz/array.h>\n#include \"fm3.h\"\n#include \"sourcecode.h\"\n\n template <class T>\n inline std::string stringify (const T& t)\n {\n\t  std::stringstream ss;\n\t  ss << t;\n\t  return ss.str();\n }\n\nusing namespace std;\nusing namespace Magick;\nusing namespace blitz;\nusing namespace boost::program_options;\nusing namespace boost::algorithm;\n\ntemplate<typename T> inline T sqr(T x) { return x*x; };\ntemplate<typename T> inline T identity(T x) { return x; }\ninline double deg2rad(double x) { return x*M_PI/180.0; };\ninline double rad2deg(double x) { return x*180.0/M_PI; };\n\ndouble y_mxPlusB(double x, double x1, double y1, double x2, double y2) {\n\tdouble m=(y2-y1)/(x2-x1);\n\tdouble b=y1-m*x1;\n\treturn m*x+b;\n}\n\ntemplate<typename T1, typename T2> void checkBound(Array<T1, 2> &a, Array<T2, 2> &b) {\n\tfor(int i=0; i<2; i++) {\n\t\tFIF(a.lbound(i)!=b.lbound(i));\n\t\tFIF(a.ubound(i)!=b.ubound(i));\n\t}\n};\n\nvoid imageCacheToArray(unsigned char *ic, Array<int, 2> &a) {\n\tfor(int y=a.ubound(1); y>=a.lbound(1); y--) {\n\t\tfor(int x=a.lbound(0); x<=a.ubound(0); x++) {\n\t\t\ta(x, y)=*(ic++);\n\t\t}\n\t}\n}\n\nvoid plotAsciiPixel(double v) {\n\tint x=int(v*10.999);\n\tif(x>10) { printf(\"^\"); return; }\n\tif(x<0) { printf(\"v\"); return; }\n\tswitch(x) {\n\t\tcase 10: printf(\" \"); break;\n\t\tcase 9: printf(\"·\"); break;\n\t\tcase 8: printf(\":\"); break;\n\t\tcase 7: printf(\"¬\"); break;\n\t\tcase 6: printf(\"÷\"); break;\n\t\tcase 5: printf(\"Y\"); break;\n\t\tcase 4: printf(\"I\"); break;\n\t\tcase 3: printf(\"U\"); break;\n\t\tcase 2: printf(\"D\"); break;\n\t\tcase 1: printf(\"N\"); break;\n\t\tcase 0: printf(\"Ø\"); break;\n\t}\n}\n\nvoid printArrayAscii(Array<int, 2> &a) {\n\tprintf(\"%d\\n\", a.ubound(1)-a.lbound(1));\n\tfor(int y=a.ubound(1); y>=a.lbound(1)+1; y-=2) {\n\t\tprintf(\"%5d:\", y);\n\t\tfor(int x=a.lbound(0); x<=a.ubound(0); x++) {\n\t\t\tplotAsciiPixel((a(x, y)+a(x, y-1))/2.0/255.0);\n\t\t}\n\t\tprintf(\" :%d\\n\", y);\n\t}\n}\n\ninline int intImageCenterMax(int x) { return (x-1)/2; }\ninline int intImageCenterMin(int x) { return intImageCenterMax(x)-(x-1); }\n\nvoid derivateTo(\n\t\tint (*diffTransform)(int),\n\t\tArray<int, 2> &from,\n\t\tArray<int, 2> &deri,\n\t\tdouble rxD, double ryD) {\n\n\tcheckBound(from, deri);\n\n\tint rx=int(round(rxD));\n\tint ry=int(round(ryD));\n\tfor(int x=from.lbound(0); x<=from.ubound(0); x++) {\n\t\tfor(int y=from.lbound(1); y<=from.ubound(1); y++) {\n\t\t\tArray<int, 2> window(from,\n\t\t\t\tRange(max(from.lbound(0), x-rx),\n\t\t\t\t\tmin(from.ubound(0), x+rx)),\n\t\t\t\tRange(max(from.lbound(1), y-ry),\n\t\t\t\t\tmin(from.ubound(1), y+ry))\n\t\t\t\t\t); // Achtung: Konstruktor -> Referenz, NICHT Kopie!\n\t\t\tint m=int(round(mean(window)));\n\t\t\tderi(x, y)=diffTransform(from(x, y)-m);\n\t\t}\n\t}\n}\n\n\nclass dRange: public Range {\npublic:\n\tint iMin, iMax;\n\tdouble dMin, dMax;\n\n\tdRange(int iMin, int iMax, double dMin, double dMax):\n\t\tRange(iMin, iMax),\n\t\tiMin(iMin), iMax(iMax),\n\t\tdMin(dMin), dMax(dMax) {}\n\n\tdouble indexToReal(double x) {\n\t\treturn y_mxPlusB(x, iMin, dMin, iMax, dMax);\n\t\t//return (x-iMin)/(iMax-iMin)*(dMax-dMin)+dMin;\n\t}\n\n\tint realToIndex(double x) {\n\t\treturn int(round(\n\t\t\t\ty_mxPlusB(x, dMin, iMin, dMax, iMax)\n\t\t\t\t));\n\t\t/*return int(round(\n\t\t\t\t(x-dMin)/(dMax-dMin)*(iMax-iMin)+iMin\n\t\t\t\t));*/\n\t}\n};\n\nint theoreticMaxDForImage(Array<int, 2> &a) {\n\treturn int(ceil(sqrt(\n\t\t\tsqr(a.ubound(0))+sqr(a.ubound(1))\n\t\t\t)));\n}\n\nint theoreticMinDForImage(Array<int, 2> &a) {\n\treturn int(floor(-sqrt(\n\t\t\tsqr(a.lbound(0))+sqr(a.lbound(1))\n\t\t\t)));\n}\n\ninline double sin90(double x) {\treturn sin(x+M_PI/2); }\ninline double cos90(double x) { return cos(x+M_PI/2); }\n\nvoid imageToDrt(Array<int, 2> &img, Array<int, 2> &drt, dRange &thetaRange) {\n\tfor(int thetaIndex=drt.lbound(0); thetaIndex<=drt.ubound(0); thetaIndex++) {\n\t\tdouble theta=thetaRange.indexToReal(thetaIndex);\n\n\t\tArray<int, 1> summandYA(Range(img.lbound(1), img.ubound(1)));\n\t\tfor(int y=img.lbound(1); y<=img.ubound(1); y++)\n\t\t\tsummandYA(y)=int(round(65536.0*(sin90(theta)*y +0.5)));\n\n\t\tfor(int x=img.lbound(0); x<=img.ubound(0); x++) {\n\t\t\tint summandX=int(round(65536.0*cos90(theta)*x));\n\t\t\tfor(int y=img.lbound(1); y<=img.ubound(1); y++) {\n\t\t\t\tdrt(thetaIndex, (summandYA(y)+summandX)>>16)\n\t\t\t\t\t+=img(x, y);\n\t\t\t}\n\t\t}\n\n\t}\n}\n\nvoid normalize(Array<int, 2> &a, int toMaxVal) {\n\tint aMin=min(a);\n\tint aMax=max(a);\n\ta=((a-aMin)*toMaxVal+(aMax-aMin)/2)/(aMax-aMin);\n}\n\nvoid normalize(Array<double, 2> &a) {\n\tdouble aMin=min(a);\n\tdouble aMax=max(a);\n\ta=(a-aMin)/(aMax-aMin);\n}\n\nvoid buildAxis(Array<int, 2> &drt, int t1, int d1, int t2, int d2, Array<int, 1> sharpDrtAxis) {\n\tdouble tStep=double(t2-t1)/(d2-d1);\n\tdouble t=t1+0.5;\n\tfor(int d=d1; d<=d2; d++) {\n\t\tint t_int=int(floor(t));\n\t\tif(t_int<drt.lbound(firstDim)) t_int=drt.lbound(firstDim);\n\t\tif(t_int>drt.ubound(firstDim)) t_int=drt.ubound(firstDim);\n\t\tsharpDrtAxis(d)=drt(t_int, d);\n\t\tt+=tStep;\n\t}\n}\n\nvoid findMaxDrtAxis(Array<int, 2> &drt, dRange &thetaRange, double tStart, double tStop, Array<int, 2> &img, int *pT1, int *pT2, int *pT1GleichT2) {\n\tint indexTStart=thetaRange.realToIndex(tStart);\n\tint indexTStop =thetaRange.realToIndex(tStop);\n\t//!*!*!*!*!*!*! double Max=std::numeric_limits<double>::min(); // min()>0!!!\n\tdouble Max=boost::numeric::bounds<double>::lowest(); // -1E308\n\tdouble t1GleichT2Max=Max;\n\tfor(int t1=indexTStart; t1<=indexTStop; t1++) {\n\t\tint d1=img.lbound(1);\n\t\tfor(int t2=indexTStart; t2<=indexTStop; t2++) {\n\t\t\tint d2=img.ubound(1);\n\t\t\tArray<int, 1> sharpDrtAxis(Range(d1, d2));\n\t\t\tbuildAxis(drt, t1, d1, t2, d2, sharpDrtAxis);\n\t\t\tdouble m=mean(sharpDrtAxis);\n\t\t\tif(m>=Max) { // *pT1+*pT2 werden sonst ggf. nie gesetzt - z. B. bei ganz weißem Bild.\n\t\t\t\tMax=m;\n\t\t\t\t*pT1=t1;\n\t\t\t\t*pT2=t2;\n\t\t\t}\n\t\t\tif(t1==t2 && m>=t1GleichT2Max) { // dito\n\t\t\t\tt1GleichT2Max=m;\n\t\t\t\t*pT1GleichT2=t1;\n\t\t\t}\n\t\t}\n\t}\n}\n\nvoid writeToImage(Array<double, 2> &a, Image &i) {\n\tfor(int y=a.ubound(1), yImage=0; y>=a.lbound(1); y--, yImage++) {\n\t\tfor(int x=a.lbound(0), xImage=0; x<=a.ubound(0); x++, xImage++) {\n\t\t\tif(a(x, y)<0) i.pixelColor(xImage, yImage, \"blue\");\n\t\t\telse\n\t\t\t\tif(a(x, y)>1) i.pixelColor(xImage, yImage, \"red\");\n\t\t\t\telse i.pixelColor(xImage, yImage, Magick::ColorGray(a(x, y)));\n\t\t}\n\t}\n}\n\ndouble calcSchwerpunktD(Array<int, 1> &sharpDrtAxis) {\n\tdouble sumD=0;\n\tdouble n=0;\n\tfor(int d=sharpDrtAxis.lbound(0); d<=sharpDrtAxis.ubound(0); d++) {\n\t\tsumD+=d*sharpDrtAxis(d);\n\t\tn+=sharpDrtAxis(d);\n\t}\n\treturn sumD/n;\n}\n\nclass fftPoint {\npublic:\n\tdouble abs;\n\tdouble halfWavelength; /* nur historische Gründe */\n\tdouble lines;\n\tfftPoint() {}\n\tfftPoint(double a, double b, double c): abs(a), halfWavelength(b), lines(c) {}\n\n};\nbool operator<(const fftPoint& a, const fftPoint& b) {\n    return a.abs < b.abs;\n}\n\ndouble sd(double sumX, double sumXX, double length) {\n\tif(length==0.0) { return 0.0; }\n\treturn sqrt((sumXX-sqr(sumX)/length)/length);\n}\n\n\nclass drtParams {\npublic:\n\tdouble zoomFactor;\n\tdouble graphW2;\n\tdouble graphH2;\n\tdouble graphW;\n\tdouble radT1;\n\tdouble radT2;\n\tint drtAxisFftLength;\n\tvector<fftPoint> drtAxisFftOrderedByAbsDesc;\n\tvector<double> drtAxis;\n};\n\nvoid getDrtParamsFromImage(variables_map &cmdLine, Image &graphImg, drtParams &drtParam) {\n\tdouble pmMaxTheta=deg2rad(cmdLine[\"angle\"].as<double>());\n\tdouble thetaCompare=deg2rad(cmdLine[\"compareAngle\"].as<double>());\n\n\tgraphImg.type( GrayscaleType );\n\n\tgraphImg.normalize();\n\tgraphImg.negate(true);\n\n\tif (cmdLine.count(\"zoom\")) {\n\t\tcout << \"zooming image to \" << cmdLine[\"zoom\"].as<string>() << \"\\n\";\n\t\tgraphImg.scale(cmdLine[\"zoom\"].as<string>());\n\t}\n\tdrtParam.zoomFactor=graphImg.size().height()/(drtParam.graphH2*2);\n\n\tunsigned char *imageCache=new unsigned char[graphImg.size().width()*graphImg.size().height()];\n\tgraphImg.write(0, 0, graphImg.size().width(), graphImg.size().height(), \"R\", CharPixel, imageCache);\n\n\tRange imageRangeX(intImageCenterMin(graphImg.size().width() ), intImageCenterMax(graphImg.size().width() ));\n\tRange imageRangeY(intImageCenterMin(graphImg.size().height()), intImageCenterMax(graphImg.size().height()));\n\n\tArray<int, 2> img(imageRangeX, imageRangeY);\n\timageCacheToArray(imageCache, img);\n\tdelete imageCache;\n\n\tArray<int, 2> sharpImg(imageRangeX, imageRangeY);\n\n\tprintf(\"sharpening image...\"); fflush(stdout);\n\tderivateTo(identity, img, sharpImg,\n\t\t\tgraphImg.size().height()*cmdLine[\"sr\"].as<double>()/100,\n\t\t\tgraphImg.size().height()*cmdLine[\"sr\"].as<double>()/100);\n\tprintf(\"done.\\n\");\n\n\tdouble maxWinkelRad=pmMaxTheta +thetaCompare;\n\tdRange drtThetaRange(\n\t\t\tint(round(-maxWinkelRad*graphImg.size().height())),\n\t\t\tint(round( maxWinkelRad*graphImg.size().height())),\n\t\t\t-maxWinkelRad,\n\t\t\t maxWinkelRad\n\t\t\t);\n\n\tdRange drtDRange(theoreticMinDForImage(sharpImg), theoreticMaxDForImage(sharpImg),\n\t\t\t-double(theoreticMinDForImage(sharpImg))/sharpImg.lbound(1)/2,\n\t\t\tdouble(theoreticMaxDForImage(sharpImg))/sharpImg.ubound(1)/2);\n\n\tArray<int, 2> drt(drtThetaRange, drtDRange);\n\tdrt=0; // Initialisierung\n\n\tprintf(\"imageToDrt...\"); fflush(stdout);\n\timageToDrt(sharpImg, drt, drtThetaRange);\n\tprintf(\"done.\\n\");\n\n\tArray<int, 2> raiseDrt(drtThetaRange, drtDRange);\n\tprintf(\"raising drt...\"); fflush(stdout);\n\tderivateTo(abs, drt, raiseDrt,\n\t\t\tgraphImg.size().height()*cmdLine[\"sr\"].as<double>()/100,\n\t\t\tgraphImg.size().height()*cmdLine[\"sr\"].as<double>()/100);\n\n\tprintf(\"sharpening drt...\"); fflush(stdout);\n\tArray<int, 2> sharpDrt(drtThetaRange, drtDRange);\n\tderivateTo(identity, drt, sharpDrt,\n\t\t\tgraphImg.size().height()*cmdLine[\"sr\"].as<double>()/100,\n\t\t\tgraphImg.size().height()*cmdLine[\"sr\"].as<double>()/100);\n\tprintf(\"done.\\n\");\n\n\tint t1, t2, t1GleichT2;\n\tint d1=sharpImg.lbound(1);\n\tint d2=sharpImg.ubound(1);\n\tprintf(\"find max(raiseDrt)...\"); fflush(stdout);\n\n\tfindMaxDrtAxis(raiseDrt, drtThetaRange,\n\t\t-pmMaxTheta,\n\t\t pmMaxTheta,\n\t\tsharpImg, &t1, &t2, &t1GleichT2);\n\tprintf(\"done.\\n\");\n\n\tdrtParam.radT1=drtThetaRange.indexToReal(t1);\n\tdrtParam.radT2=drtThetaRange.indexToReal(t2);\n\n\tprintf(\"angle at 0%%: %f; angle at 100%%: %f degrees\\n\", rad2deg(drtParam.radT1), rad2deg(drtParam.radT2));\n\tprintf(\"max. var. at constant angle: %lf degrees\\n\", rad2deg(drtThetaRange.indexToReal(t1GleichT2)));\n\n\t//\n\n\tArray<int, 1> sharpDrtAxis(Range(d1, d2));\n\tbuildAxis(sharpDrt, t1, d1, t2, d2, sharpDrtAxis);\n\n\tdouble doubleDrtAxis[d2-d1+1];\n\tprintf(\"iDrtAxisVal:\");\n\tfor(int d=d1; d<=d2; d++) {\n\t\tdoubleDrtAxis[d-d1]=double(sharpDrtAxis(d))/(sharpImg.ubound(0)-sharpImg.lbound(0)+1);\n\t\tprintf(\" %f\", doubleDrtAxis[d-d1]);\n\t\tdrtParam.drtAxis.push_back(doubleDrtAxis[d-d1]);\n\t}\n\tprintf(\"\\n\");\n\n\tfftw_plan fftPlan;\n\tdrtParam.drtAxisFftLength=(d2-d1+1)/2+1;\n\tcomplex<double>* fft = new complex<double>[drtParam.drtAxisFftLength];\n\tdrtParam.drtAxisFftOrderedByAbsDesc=vector<fftPoint>(drtParam.drtAxisFftLength-1);\n\t//vector<fftPoint> drtParam.drtParam.drtAxisFftOrderedByAbsDesc(drtAxisFftLength-1);\n/*  C++ has its own complex<T> template class, defined in the standard <complex> header file.\n\t  Reportedly, the C++ standards committee has recently agreed to mandate that the storage\n\tformat used for this type be binary-compatible with the C99 type, i.e. an array T[2] with consecutive\n\treal [0] and imaginary [1] parts. (See report WG21/N1388.)\n\t  Although not part of the official standard as of this writing, the proposal stated that:\n\t“This solution has been tested with all current major implementations of the standard library and\n\tshown to be working.”\n\t  To the extent that this is true, if you have a variable complex<double> *x, you can pass it directly\n\tto FFTW via reinterpret_cast<fftw_complex*>(x).*/\n\tfftPlan = fftw_plan_dft_r2c_1d(d2-d1+1, doubleDrtAxis, reinterpret_cast<fftw_complex*>(fft), FFTW_ESTIMATE);\n\tfftw_execute(fftPlan);\n\tprintf(\"iDrtAxisFFT(n=%d):\", d2-d1+1);\n\tfor(int i=1; i<drtParam.drtAxisFftLength; i++) {\n\t\tdrtParam.drtAxisFftOrderedByAbsDesc[i-1].abs=abs(fft[i])/drtParam.drtAxisFftLength;\n\t\t// nächste Zeile: 33% (=0.33) war der default-Zoomfaktor der alten drt-Version.\n\t\t// damit die Zahlen vergleichbar sind, wird umgerechnet.\n\t\tdrtParam.drtAxisFftOrderedByAbsDesc[i-1].halfWavelength=double(drtParam.drtAxisFftLength)*0.33/drtParam.zoomFactor/i;\n\t\tdrtParam.drtAxisFftOrderedByAbsDesc[i-1].lines=i;\n\t\tprintf(\" %f\", drtParam.drtAxisFftOrderedByAbsDesc[i-1].abs);\n\t}\n\tprintf(\"\\n\");\n\tfftw_destroy_plan(fftPlan);\n\tdelete[] fft;\n\n\t//\n\n\tArray<int, 1> raiseDrtAxis(Range(d1, d2));\n\tbuildAxis(raiseDrt, t1, d1, t2, d2, raiseDrtAxis);\n\tdouble dSchwerRel=(calcSchwerpunktD(raiseDrtAxis)-d1)/(d2-d1);\n\n\tArray<int, 1> raiseDrtAxisVar1(Range(d1, d2));\n\tbuildAxis(raiseDrt,\n\t\tt1-drtThetaRange.realToIndex(thetaCompare*   dSchwerRel ), d1,\n\t\tt2+drtThetaRange.realToIndex(thetaCompare*(1-dSchwerRel)), d2, raiseDrtAxisVar1);\n\n\tArray<int, 1> raiseDrtAxisVar2(Range(d1, d2));\n\tbuildAxis(raiseDrt,\n\t\tt1+drtThetaRange.realToIndex(thetaCompare*   dSchwerRel ), d1,\n\t\tt2-drtThetaRange.realToIndex(thetaCompare*(1-dSchwerRel)), d2, raiseDrtAxisVar2);\n\n\tdouble var1qual=mean(raiseDrtAxisVar1)/mean(raiseDrtAxis);\n\tdouble var2qual=mean(raiseDrtAxisVar2)/mean(raiseDrtAxis);\n\tprintf(\"drtAxis Var1:%f%% Var2:%f%% => %f\\n\",\n\t\t\tvar1qual*100, var2qual*100, 100*(1-max(var1qual, var2qual)));\n\n\tif(cmdLine.count(\"drt\")) {\n\t\tstring sizeStr=stringify(drtThetaRange.iMax-drtThetaRange.iMin+1)\n\t\t\t\t\t\t\t+\"x\"+stringify(drtDRange.iMax-drtDRange.iMin+1);\n\t\tImage drtOut(sizeStr.c_str(), \"black\");\n\t\tdrtOut.quality(100);\n\n\t\tArray<double, 2> tmpDrt(drtThetaRange, drtDRange);\n\t\ttmpDrt=raiseDrt*1.0;\n\t\tnormalize(tmpDrt);\n\n\t\tdouble tStep=double(t2-t1)/(d2-d1);\n\t\tdouble t=t1+0.5;\n\t\tfor(int d=d1; d<=d2; d++) {\n\t\t\ttmpDrt(int(floor(t)), d)=-1.0;\n\t\t\tt+=tStep;\n\t\t}\n\n\t\twriteToImage(tmpDrt, drtOut);\n\n\t\ttry {\n\t\t\tdrtOut.write(cmdLine[\"drt\"].as<string>());\n\t\t}\n\t\tcatch( Magick::WarningCoder &warning ) {\n\t\t\tcerr << \"Coder Warning: \" << warning.what() << endl;\n\t\t}\n\t    catch( Magick::Warning &warning ) {\n\t    \tcerr << \"Warning: \" << warning.what() << endl;\n\t    }\n\t    catch( Magick::ErrorBlob &error) {\n\t    \tcerr << \"Error: \" << error.what() << endl;\n\t    }\n\t}\n}\n\nstring &after(string &haystack, const char *key, string &val) {\n\tif(haystack.find(key, 0)!=0) {\n\t    val=string(\"\");\n\t    return val;\n\t}\n\tval=haystack.substr(strlen(key));\n\treturn val;\n}\n\nint getDrtParamsFromDrtlog(variables_map &cmdLine, Image &graphImg, drtParams &drtParam) {\n\tdrtParam.zoomFactor=0.33;\n\n\tifstream drtLog;\n\tdrtLog.open(cmdLine[\"import\"].as<string>().c_str());\n\tif(drtLog.fail()) return 0;\n\n\tint paramcount=0;\n\twhile(! drtLog.eof()) {\n\t\tstring line;\n\t\tgetline(drtLog, line);\n\t\tstring val;\n\n//\t\t\tgraphW/H wird nicht mehr angefasst, da bereits beim Laden des Bildes bestimmt.\n\n\t\tif((after(line, \"size: \", val)).size()>0) {\n\t\t\tvector<string> size;\n\t\t\tsplit(size, val, is_any_of(\"x\"));\n\t\t\tif(strtoul(size[0].c_str(), NULL, 10) != graphImg.size().width()\n\t\t\t|| strtoul(size[1].c_str(), NULL, 10) != graphImg.size().height()) {\n\t\t\t\tprintf(\"FEHLER: Bildgröße aus %s stimmt nicht mit tatsächlicher Bildgröße überein.\\n\", cmdLine[\"import\"].as<string>().c_str());\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t}\n\n\n\t\tif((after(line, \"angle at \", val)).size()>0) {\n\t\t\tvector<string> angleParam;\n\t\t\tsplit(angleParam, val, is_any_of(\"%:; \")); // trennzeichen zusammenfassen\n\n\t\t\tdouble perD1=atof(angleParam[0].c_str());\n\t\t\tdouble radT1=deg2rad(atof(angleParam[3].c_str()));\n\t\t\tdouble perD2=atof(angleParam[7].c_str());\n\t\t\tdouble radT2=deg2rad(atof(angleParam[10].c_str()));\n\n\t\t\tdrtParam.radT1=y_mxPlusB(  0, perD1, radT1, perD2, radT2);\n\t\t\tdrtParam.radT2=y_mxPlusB(100, perD1, radT1, perD2, radT2);\n\t\t\tprintf(\"radT1=%f\\n\", drtParam.radT1);\n\t\t\tprintf(\"radT2=%f\\n\", drtParam.radT2);\n\t\t\tparamcount++;\n\t\t}\n\n\t\tif((after(line, \"iDrtAxisFFT(n=\", val)).size()>0) {\n\t\t\tvector<string> sfft;\n\t\t\tsplit(sfft, val, is_any_of(\" \"));\n\t\t\tvector<string> n;\n\t\t\tsplit(n, sfft[0], is_any_of(\")\"));\n\t\t\tint fftInputLength=atoi(n[0].c_str());\n\t\t\tdrtParam.drtAxisFftLength=(fftInputLength-1)/2;\n\t\t\t// ja, war wohl in altem drt-Programm so;\n\t\t\t// die paar % machen den Kohl nicht fett.\n\t\t\tprintf(\"drtParam.drtAxisFftLength=%d\\n\", drtParam.drtAxisFftLength);\n\t\t\tfor(unsigned i=1; i<sfft.size(); i++) {\n\t\t\t\tdrtParam.drtAxisFftOrderedByAbsDesc.push_back(fftPoint(\n\t\t\t\t\t\tatof(sfft[i].c_str()),\n\t\t\t\t\t\tdouble(drtParam.drtAxisFftLength)/i,\n\t\t\t\t\t\tdouble(i)\n\t\t\t\t\t\t));\n\t\t\t}\n\t\t\tparamcount++;\n\t\t}\n\n\t\tif((after(line, \"iDrtAxisVal: \", val)).size()>0) {\n\t\t\tvector<string> string_drtAxis;\n\t\t\tsplit(string_drtAxis, val, is_any_of(\" \"));\n\t\t\tfor(unsigned i=0; i<string_drtAxis.size(); i++) {\n\t\t\t\tdrtParam.drtAxis.push_back(atof(string_drtAxis[i].c_str()));\n\t\t\t}\n\t\t\tparamcount++;\n\t\t}\n\n\t\t// \"shrinking\"=\"zooming\"\n\t\tif((after(line, \"shrinking image to \", val)).size()>0) {\n\t\t\tvector<string> zoom;\n\t\t\tsplit(zoom, val, is_any_of(\"%\"));\n\t\t\tdrtParam.zoomFactor=atof(zoom[0].c_str())/100;\n\t\t\tprintf(\"zoomFactor=%f\\n\", drtParam.zoomFactor);\n\t\t\tparamcount++;\n\t\t}\n\t\tif((after(line, \"zooming image to \", val)).size()>0) {\n\t\t\tvector<string> zoom;\n\t\t\tsplit(zoom, val, is_any_of(\"%\"));\n\t\t\tdrtParam.zoomFactor=atof(zoom[0].c_str())/100;\n\t\t\tprintf(\"zoomFactor=%f\\n\", drtParam.zoomFactor);\n\t\t\tparamcount++;\n\t\t}\n\t}\n\n\tif(paramcount!=4) return 0;\n\treturn 1;\n}\n\n\nint main(int argc, char **argv)\n{\n\tFIF(sizeof(int)!=4);\n\tFIF((3>>1)!=1);\n\tFIF((-3>>1)!=-2);\n\n\toptions_description optDesc(string(DEBUG_MSG)+string(__FILE__)+\" @ \"+string(__DATE__)+\" \"+string(__TIME__)+\"\\nAllowed options\");\n\toptDesc.add_options()\n\t    (\"help\", \"produce help message\")\n\t    (\"source\", \"print program source code\")\n\t    (\"if\",  value<string>(), \"input image file\")\n\t    (\"import\", value<string>(), \"import drtLog file\")\n\t    (\"drt\", value<string>(), \"drt image file (visualization of drt)\")\n\t    (\"tmpfile\",  value<string>(), \"temporary image file (format conversion only); will not be deleted\")\n\t    (\"of\",  value<string>(), \"output image file (after spherical correction)\")\n\t    (\"python\", value<string>()->default_value(\"python\"), \"python command (requires PIL)\")\n\t    (\"doTrans\", \"does format conversion with transCmd, if applicable (sd<maxSd)\")\n\t    (\"noTransDeskew\", \"format conversion&statistics only\")\n\t    (\"maxSd\", value<double>()->default_value(0.8), \"max. sd(halfWavelength) allowing transformation\")\n\t    (\"sr\",  value<double>()->default_value(1.0), \"shapen radius [image height %]\")\n\t    (\"zoom\",  value<string>()->default_value(\"33%\"), \"zoom +'%'\")\n\t    (\"angle\",  value<double>()->default_value(5.0), \"drt angle probe range [Grad]\")\n\t    (\"compareAngle\",  value<double>()->default_value(1.0), \"+/- angle variation to compare\")\n\t    (\"halfWavelengthVarianceAbsFactor\",  value<double>()->default_value(50), \"variance(halfWavelength(fft where abs(fft)>=max(abs(fft))*hWVAF))\")\n\n\t    (\"minPageHeight\",  value<double>()->default_value(150.0), \"page height minus border[mm]\")\n\t    (\"maxPageHeight\",  value<double>()->default_value(600.0), \"page height minus border[mm]\")\n\t    (\"minLineSpaceSize\", value<double>()->default_value(10.0), \"[pt] (1/72 inch = 0.35277mm)\")\n\t    (\"maxLineSpaceSize\", value<double>()->default_value(16.0), \"[pt] (1/72 inch = 0.35277mm)\")\n\t    (\"minLineSpaceRatio\", value<double>()->default_value(0.7))\n\t\t(\"maxLineSpaceRatio\", value<double>()->default_value(2.0))\n\t\t(\"minLineLike\", value<double>()->default_value(26.664827), \"%\")\n\t\t(\"hysteresis\", value<double>()->default_value(4.278268))\n\t\t(\"maxSdLineSpace\", value<double>()->default_value(6.272757))\n\t\t(\"gamma\", value<double>()->default_value(2.2), \"sRGB gamma correction before(1/x)&after(x) transform\")\n\t;\n\n\tvariables_map cmdLine;\n\tstore(parse_command_line(argc, argv, optDesc), cmdLine);\n\tnotify(cmdLine);\n\n\tif (cmdLine.count(\"help\")) {\n\t    cout << optDesc << \"\\n\";\n\t    return 1;\n\t}\n\tif (cmdLine.count(\"source\")) {\n\t\tcerr << SOURCECODE_TIMESTAMP << endl;\n\t    fwrite(SOURCECODE, 1, SOURCECODE_LENGTH, stdout);\n\t    return 1;\n\t}\n\n\tFIF(!cmdLine.count(\"if\"));\n\n\tImage graphImg;\n\tprintf(\"reading image...\"); fflush(stdout);\n\ttry {\n\t\tgraphImg.read(cmdLine[\"if\"].as<string>()); printf(\"done.\\n\");\n\t}\n\tcatch( Magick::WarningCoder &warning ) {\n\t\tcerr << \"Coder Warning: \" << warning.what() << endl;\n\t}\n\tcatch( Magick::Warning &warning ) {\n\t\tcerr << \"Warning: \" << warning.what() << endl;\n\t}\n\tcatch( Magick::ErrorBlob &error) {\n\t\tcerr << \"Error: \" << error.what() << endl;\n\t}\n\n\tImage transImg=graphImg; // wird unten gebraucht\n\n\tgraphImg.modifyImage();\n\t//SetImageVirtualPixelMethod( graphImg.image(), MagickCore::WhiteVirtualPixelMethod);\n\t//TODO: will in aktueller Version noch nicht\n\t// graphImg.options()->virtualPixelMethod( MagickCore::WhiteVirtualPixelMethod );\n\n\tgraphImg.virtualPixelMethod(MagickCore::WhiteVirtualPixelMethod); // aber auch das will in Magick++ unter (ubuntu) karmic koala nicht\n\n\tdrtParams drtParam;\n\tprintf(\"size: %lux%lu\\n\", graphImg.size().width(), graphImg.size().height());\n\tdrtParam.graphW2=double(graphImg.size().width())/2;\n\tdrtParam.graphH2=double(graphImg.size().height())/2;\n\tdrtParam.graphW=drtParam.graphW2*2;\n\n\tif(cmdLine.count(\"tmpfile\")) {\n\t\t// ist ja nur ein tmpfile: graphImg.density(Geometry(300, 300)); // 300 dpi setzen\n\t\tgraphImg.quality(100);\n\t\tprintf(\"saving image...\"); fflush(stdout);\n\t\t//graphImg.write(cmdLine[\"tmpfile\"].as<string>());\n\t\tprintf(\"done.\\n\");\n\t}\n\n\tif(!cmdLine.count(\"import\")) {\n\t\tgetDrtParamsFromImage(cmdLine, graphImg, drtParam);\n\t} else {\n\t\tif(!getDrtParamsFromDrtlog(cmdLine, graphImg, drtParam)) {\n\t\t\tfprintf(stderr, \"WARNUNG: drtLog-(import)-Datei %s fehlerhaft. DRT-Analyse wird vom Bild durchgefuehrt.\\n\", cmdLine[\"import\"].as<string>().c_str());\n\t\t\tgetDrtParamsFromImage(cmdLine, graphImg, drtParam);\n\t\t}\n\t}\n\n\tdouble radT12avg=(drtParam.radT1+drtParam.radT2)/2;\n\tdouble radT1rel=drtParam.radT1-radT12avg;\n\tdouble radT2rel=drtParam.radT2-radT12avg;\n\n\t// 0 3\n\t// 1 2\n\n\tvector<complex<double> > transKoord(4);\n\n\tif(radT2rel<0) {\n\t\ttransKoord[0]=complex<double>(-drtParam.graphW2, drtParam.graphH2);\n\t\ttransKoord[3]=transKoord[0]+polar(drtParam.graphW, radT2rel);\n\t} else {\n\t\ttransKoord[3]=complex<double>(drtParam.graphW2, drtParam.graphH2);\n\t\ttransKoord[0]=transKoord[3]-polar(drtParam.graphW, radT2rel);\n\t}\n\n\tif(radT1rel>0) {\n\t\ttransKoord[1]=complex<double>(-drtParam.graphW2, -drtParam.graphH2);\n\t\ttransKoord[2]=transKoord[1]+polar(drtParam.graphW, radT1rel);\n\t} else {\n\t\ttransKoord[2]=complex<double>(drtParam.graphW2, -drtParam.graphH2);\n\t\ttransKoord[1]=transKoord[2]-polar(drtParam.graphW, radT1rel);\n\t}\n\n\tdouble distortParam[16];\n\tfor(int i=0; i<4; i++) {\n\t\tint x, y;\n\t\tswitch(i) {\n\t\t\tcase 0: x=0; y=0; break;\n\t\t\tcase 1: x=0; y=drtParam.graphH2*2-1; break;\n\t\t\tcase 2: x=drtParam.graphW2*2-1; y=drtParam.graphH2*2-1; break;\n\t\t\tcase 3: x=drtParam.graphW2*2-1; y=0; break;\n\t\t}\n\t\tdouble r=abs(transKoord[i]);\n\t\tdouble phi=std::arg(transKoord[i])+radT12avg;\n\t\tdistortParam[i*4+0]=r*cos(phi)+drtParam.graphW2; //+pilXoff;\n\t\tdistortParam[i*4+1]=(drtParam.graphH2*2-1)-(r*sin(phi)+drtParam.graphH2); //+pilYoff;\n\t\tdistortParam[i*4+2]=x;\n\t\tdistortParam[i*4+3]=y;\n\n\t\tprintf(\"%d: %f,%f %f,%f\\n\", i, distortParam[i*4+0], distortParam[i*4+1], distortParam[i*4+2], distortParam[i*4+3]);\n\t}\n\n\tsort(drtParam.drtAxisFftOrderedByAbsDesc.begin(), drtParam.drtAxisFftOrderedByAbsDesc.end());\n\treverse(drtParam.drtAxisFftOrderedByAbsDesc.begin(), drtParam.drtAxisFftOrderedByAbsDesc.end());\n\tprintf(\"iDrtAxisFFT ordered by abs: \");\n\tdouble sumW=0;\n\tdouble sumL=0;\n\tdouble sumWW=0;\n\tint n=0;\n\tfor(int i=0; i<drtParam.drtAxisFftLength-1\n\t\t&& drtParam.drtAxisFftOrderedByAbsDesc[i].abs>=\n\t\t\tdrtParam.drtAxisFftOrderedByAbsDesc[0].abs\n\t\t\t\t*cmdLine[\"halfWavelengthVarianceAbsFactor\"].as<double>()/100;\n\t\ti++) {\n\t\tsumW+=drtParam.drtAxisFftOrderedByAbsDesc[i].halfWavelength;\n\t\tsumWW+=pow(drtParam.drtAxisFftOrderedByAbsDesc[i].halfWavelength, 2);\n\t\tsumL+=drtParam.drtAxisFftOrderedByAbsDesc[i].lines;\n\t\tn++;\n\t\tprintf(\" (%.3lf:%.3lf)\", drtParam.drtAxisFftOrderedByAbsDesc[i].abs,\n\t\t\t\tdrtParam.drtAxisFftOrderedByAbsDesc[i].halfWavelength);\n\t}\n\tprintf(\"\\n\");\n\tprintf(\"sd=%lf halfWl=%lf lines=%lf\\n\", sd(sumW, sumWW, n), sumW/n, sumL/n);\n\n\t// neue Evaluierung der Drt-Achse:\n\n\tdouble minLines=cmdLine[\"minPageHeight\"].as<double>() / (cmdLine[\"maxLineSpaceSize\"].as<double>()*0.35277);\n\tdouble maxLines=cmdLine[\"maxPageHeight\"].as<double>() / (cmdLine[\"minLineSpaceSize\"].as<double>()*0.35277);\n\tint minLineSpace=int(drtParam.drtAxis.size()/maxLines);\n\tint maxLineSpace=int(drtParam.drtAxis.size()/minLines+0.999);\n\tprintf(\"minLineSpace:%d\\n\", minLineSpace);\n\tprintf(\"maxLineSpace:%d\\n\", maxLineSpace);\n\tdouble minRatio=cmdLine[\"minLineSpaceRatio\"].as<double>();\n\tdouble maxRatio=cmdLine[\"maxLineSpaceRatio\"].as<double>();\n\n\tdouble line=0;\n\tdouble space=0;\n\tdouble sumLine=0;\n\tdouble sumLine2=0;\n\tdouble sumSpace=0;\n\tdouble sumSpace2=0;\n\tdouble sumN=0;\n\n\tint state=0;\n\tdouble hyst=cmdLine[\"hysteresis\"].as<double>();\n\n\tdouble insgesamt=0;\n\tdouble zeilenartig=0;\n\n\tif(drtParam.drtAxis[0]>0) { state=1; space++; } else { state=0; line++; }\n\n\tprintf(\"iDrtAxis-LineSpacePattern:\");\n\tfor(unsigned i=1; i<drtParam.drtAxis.size(); i++) {\n\t\tif(state==0) {\n\t\t\tif(drtParam.drtAxis[i]>hyst) {\n\t\t\t\tprintf(\"(l:%.0lf;s:%.0lf)s\", line, space);\n\t\t\t\tif(space==0.0) { space+=0.000001; }\n\t\t\t\tdouble ratio=line/space;\n\t\t\t\tinsgesamt+=line+space;\n\t\t\t\tif(line+space>=minLineSpace && line+space<=maxLineSpace)\t{\n\t\t\t\t\tif(ratio>=minRatio/1.55 && ratio<=maxRatio*1.55) {\n\t\t\t\t\t\tsumLine+=line;\n\t\t\t\t\t\tsumLine2+=line*line;\n\t\t\t\t\t\tsumSpace+=space;\n\t\t\t\t\t\tsumSpace2+=space*space;\n\t\t\t\t\t\tsumN++;\n\t\t\t\t\t}\n\t\t\t\t\tif(ratio>=minRatio && ratio<=maxRatio) {\n\t\t\t\t\t\tzeilenartig+=line+space;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tline=0; space=1;\n\t\t\t\tstate=1;\n\t\t\t} else { printf(\"l\"); line++; } // hyst. n. überschr.\n\t\t} else { // status=1\n\t\t\tif(drtParam.drtAxis[i]<(-hyst)) {\n\t\t\t\tline++;\n\t\t\t\tprintf(\"l\");\n\t\t\t\tstate=0;\n\t\t\t} else { printf(\"s\"); space++; }\n\t\t}\n\t}\n\tprintf(\"\\n\");\n\tdouble sdLine=sd(sumLine, sumLine2, sumN);\n\tdouble sdSpace=sd(sumSpace, sumSpace2, sumN);\n\tdouble sdLineSpace=sqrt(sdLine*sdLine+sdSpace*sdSpace);\n\n\tdouble proz_zeilenartig=double(zeilenartig)*100.0/(insgesamt+boost::numeric::bounds<double>::smallest()); // sicherheitshalber, falls weißes Blatt etc.\n\tprintf(\"line-like: %.2f%%; sdLineSpace=%.3f\\n\", proz_zeilenartig, sdLineSpace);\n\n\tif(cmdLine.count(\"doTrans\") && cmdLine.count(\"of\")) {\n\t\t//if(sd(sumW, sumWW, n) < cmdLine[\"maxSd\"].as<double>() && cmdLine.count(\"noTransDeskew\")==0)\n\t\t// wird nun in doUnzip...sh erledigt: transImg.density(Geometry(300, 300)); // 300 dpi setzen\n\t\tif(proz_zeilenartig >= cmdLine[\"minLineLike\"].as<double>()\n\t\t\t\t&& sdLineSpace <= cmdLine[\"maxSdLineSpace\"].as<double>()\n\t\t\t\t&& cmdLine.count(\"noTransDeskew\")==0) {\n\t\t\ttransImg.compressType(NoCompression);\n\t\t\ttransImg.depth(16);\n\t\t\ttransImg.gamma(1/cmdLine[\"gamma\"].as<double>());\n\t\t\ttransImg.distort(MagickCore::PerspectiveDistortion,  16, distortParam);\n\t\t\ttransImg.gamma(cmdLine[\"gamma\"].as<double>());\n\t\t\ttransImg.depth(8);\n\t\t}\n\t\ttry {\n\t\t\ttransImg.write(cmdLine[\"of\"].as<string>());\n\t\t}\n\t\tcatch( Magick::WarningCoder &warning ) {\n\t\t\tcerr << \"Coder Warning: \" << warning.what() << endl;\n\t\t}\n\t\tcatch( Magick::Warning &warning ) {\n\t\t\tcerr << \"Warning: \" << warning.what() << endl;\n\t\t}\n\t\tcatch( Magick::ErrorBlob &error) {\n\t\t\tcerr << \"Error: \" << error.what() << endl;\n\t\t}\n\t}\n}\n\n", "meta": {"hexsha": "69dfaa880e9dfdcc26e554bb1fd467b7dfe409a9", "size": 27469, "ext": "c++", "lang": "C++", "max_stars_repo_path": "blitzDrt.c++", "max_stars_repo_name": "kba/blitzDrt", "max_stars_repo_head_hexsha": "dbb5d37b13eb0441c1d5faa19c41bb7d66cf8f60", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2021-02-03T12:50:41.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-03T20:18:20.000Z", "max_issues_repo_path": "blitzDrt.c++", "max_issues_repo_name": "kba/blitzDrt", "max_issues_repo_head_hexsha": "dbb5d37b13eb0441c1d5faa19c41bb7d66cf8f60", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "blitzDrt.c++", "max_forks_repo_name": "kba/blitzDrt", "max_forks_repo_head_hexsha": "dbb5d37b13eb0441c1d5faa19c41bb7d66cf8f60", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-03-04T12:11:05.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-03T20:18:15.000Z", "avg_line_length": 32.8576555024, "max_line_length": 152, "alphanum_fraction": 0.6746514252, "num_tokens": 9150, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5813031051514763, "lm_q2_score": 0.5273165233795671, "lm_q1q2_score": 0.30653073243822343}}
{"text": "/**\n * Copyright (c) 2011-2017 libbitcoin developers (see AUTHORS)\n *\n * This file is part of libbitcoin.\n *\n * This program is free software: you can redistribute it and/or modify\n * it under the terms of the GNU Affero General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU Affero General Public License for more details.\n *\n * You should have received a copy of the GNU Affero General Public License\n * along with this program.  If not, see <http://www.gnu.org/licenses/>.\n */\n#include <bitcoin/bitcoin/formats/base_58.hpp>\n\n#include <boost/algorithm/string.hpp>\n#include <bitcoin/bitcoin/utility/assert.hpp>\n\nnamespace libbitcoin {\n\nconst std::string base58_chars =\n    \"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz\";\n\nbool is_base58(const char ch)\n{\n    // This works because the base58 characters happen to be in sorted order\n    return std::binary_search(base58_chars.begin(), base58_chars.end(), ch);\n}\n\nbool is_base58(const std::string& text)\n{\n    const auto test = [](const char ch)\n    {\n        return is_base58(ch);\n    };\n\n    return std::all_of(text.begin(), text.end(), test);\n}\n\ntemplate <typename Data>\nauto search_first_nonzero(const Data& data) -> decltype(data.cbegin())\n{\n    auto first_nonzero = data.cbegin();\n    while (first_nonzero != data.end() && *first_nonzero == 0)\n        ++first_nonzero;\n\n    return first_nonzero;\n}\n\nsize_t count_leading_zeros(data_slice unencoded)\n{\n    // Skip and count leading '1's.\n    size_t leading_zeros = 0;\n    for (const uint8_t byte: unencoded)\n    {\n        if (byte != 0)\n            break;\n\n        ++leading_zeros;\n    }\n\n    return leading_zeros;\n}\n\nvoid pack_value(data_chunk& indexes, size_t carry)\n{\n    // Apply \"b58 = b58 * 256 + ch\".\n    for (auto it = indexes.rbegin(); it != indexes.rend(); ++it)\n    {\n        carry += 256 * (*it);\n        *it = carry % 58;\n        carry /= 58;\n    }\n\n    BITCOIN_ASSERT(carry == 0);\n}\n\nstd::string encode_base58(data_slice unencoded)\n{\n    size_t leading_zeros = count_leading_zeros(unencoded);\n\n    // size = log(256) / log(58), rounded up.\n    const size_t number_nonzero = unencoded.size() - leading_zeros;\n    const size_t indexes_size = number_nonzero * 138 / 100 + 1;\n\n    // Allocate enough space in big-endian base58 representation.\n    data_chunk indexes(indexes_size);\n\n    // Process the bytes.\n    for (auto it = unencoded.begin() + leading_zeros;\n        it != unencoded.end(); ++it)\n    {\n        pack_value(indexes, *it);\n    }\n\n    // Skip leading zeroes in base58 result.\n    auto first_nonzero = search_first_nonzero(indexes);\n\n    // Translate the result into a string.\n    std::string encoded;\n    const size_t estimated_size = leading_zeros +\n        (indexes.end() - first_nonzero);\n    encoded.reserve(estimated_size);\n    encoded.assign(leading_zeros, '1');\n\n    // Set actual main bytes.\n    for (auto it = first_nonzero; it != indexes.end(); ++it)\n    {\n        const size_t index = *it;\n        encoded += base58_chars[index];\n    }\n\n    return encoded;\n}\n\nsize_t count_leading_zeros(const std::string& encoded)\n{\n    // Skip and count leading '1's.\n    size_t leading_zeros = 0;\n    for (const uint8_t digit: encoded)\n    {\n        if (digit != base58_chars[0])\n            break;\n\n        ++leading_zeros;\n    }\n\n    return leading_zeros;\n}\n\nvoid unpack_char(data_chunk& data, size_t carry)\n{\n    for (auto it = data.rbegin(); it != data.rend(); it++)\n    {\n        carry += 58 * (*it);\n        *it = carry % 256;\n        carry /= 256;\n    }\n\n    BITCOIN_ASSERT(carry == 0);\n}\n\nbool decode_base58(data_chunk& out, const std::string& in)\n{\n    // Trim spaces and newlines around the string.\n    const auto leading_zeros = count_leading_zeros(in);\n\n    // log(58) / log(256), rounded up.\n    const size_t data_size = in.size() * 733 / 1000 + 1;\n\n    // Allocate enough space in big-endian base256 representation.\n    data_chunk data(data_size);\n\n    // Process the characters.\n    for (auto it = in.begin() + leading_zeros; it != in.end(); ++it)\n    {\n        const auto carry = base58_chars.find(*it);\n        if (carry == std::string::npos)\n            return false;\n\n        unpack_char(data, carry);\n    }\n\n    // Skip leading zeroes in data.\n    auto first_nonzero = search_first_nonzero(data);\n\n    // Copy result into output vector.\n    data_chunk decoded;\n    const size_t estimated_size = leading_zeros + (data.end() - first_nonzero);\n    decoded.reserve(estimated_size);\n    decoded.assign(leading_zeros, 0x00);\n    decoded.insert(decoded.end(), first_nonzero, data.cend());\n\n    out = decoded;\n    return true;\n}\n\n// For support of template implementation only, do not call directly.\nbool decode_base58_private(uint8_t* out, size_t out_size, const char* in)\n{\n    data_chunk buffer;\n    if (!decode_base58(buffer, in) || buffer.size() != out_size)\n        return false;\n\n    for (size_t i = 0; i < out_size; ++i)\n        out[i] = buffer[i];\n\n    return true;\n}\n\n} // namespace libbitcoin\n", "meta": {"hexsha": "0e0b43f76fee3bf316dfe1b8f7db8879a7d50b72", "size": 5254, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "3rdparty/libbitcoin/src/formats/base_58.cpp", "max_stars_repo_name": "anatolse/beam", "max_stars_repo_head_hexsha": "43c4ce0011598641d9cdeffbfdee66fde0a49730", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 631.0, "max_stars_repo_stars_event_min_datetime": "2018-11-10T05:56:05.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T13:21:00.000Z", "max_issues_repo_path": "3rdparty/libbitcoin/src/formats/base_58.cpp", "max_issues_repo_name": "anatolse/beam", "max_issues_repo_head_hexsha": "43c4ce0011598641d9cdeffbfdee66fde0a49730", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1824.0, "max_issues_repo_issues_event_min_datetime": "2018-11-08T11:32:58.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-28T12:33:03.000Z", "max_forks_repo_path": "3rdparty/libbitcoin/src/formats/base_58.cpp", "max_forks_repo_name": "anatolse/beam", "max_forks_repo_head_hexsha": "43c4ce0011598641d9cdeffbfdee66fde0a49730", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 216.0, "max_forks_repo_forks_event_min_datetime": "2018-11-12T08:07:21.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-08T20:50:19.000Z", "avg_line_length": 26.6700507614, "max_line_length": 79, "alphanum_fraction": 0.6534069281, "num_tokens": 1308, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5273165233795672, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.30653072478835675}}
{"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 * EigenSVDPointAlign.hpp\n *\n *  @date Feb 21, 2014\n *  @author Thomas Wiemann\n */\n#ifndef EIGENSVDPOINTALIGN_HPP_\n#define EIGENSVDPOINTALIGN_HPP_\n\n#include \"SLAMScanWrapper.hpp\"\n#include \"lvr2/types/MatrixTypes.hpp\"\n\n#include <Eigen/Dense>\n\nnamespace lvr2\n{\n\ntemplate<typename T, typename PointT = float>\nclass EigenSVDPointAlign\n{\npublic:\n    using Vec3 = Vector3<T>;\n    using Mat4 = Transform<T>;\n    using Mat3 = Eigen::Matrix<T, 3, 3>;\n    using Point3 = Vector3<PointT>;\n    using PointPairVector = std::vector<std::pair<Point3, Point3>>;\n\n    EigenSVDPointAlign() {};\n\n    /**\n     * @brief Calculates the estimated Transformation to match a Data Pointcloud to a Model\n     *        Pointcloud\n     * \n     * Apply the resulting Transform to the Data Pointcloud.\n     *\n     * @param scan       The Data Pointcloud\n     * @param neighbors  An array containing a Pointer to a neighbor in the Model Pointcloud for\n     *                   each Point in `scan`, or nullptr if there is no neighbor for a Point\n     * @param centroid_m The center of the Model Pointcloud\n     * @param centroid_d The center of the Data Pointcloud\n     * @param align      Will be set to the Transformation\n     *\n     * @return The average Point-to-Point error of the Scans\n     */\n    T alignPoints(\n        SLAMScanPtr scan,\n        Point3** neighbors,\n        const Vec3& centroid_m,\n        const Vec3& centroid_d,\n        Mat4& align) const;\n\n    /**\n     * @brief Calculates the estimated Transformation to match a Data Pointcloud to a Model\n     *        Pointcloud\n     * \n     * Apply the resulting Transform to the Data Pointcloud.\n     *\n     * @param points     A vector of pairs with (model, data) Points\n     * @param centroid_m The center of the Model Pointcloud\n     * @param centroid_d The center of the Data Pointcloud\n     * @param align      Will be set to the Transformation\n     *\n     * @return The average Point-to-Point error of the Scans\n     */\n    T alignPoints(\n        PointPairVector& points,\n        const Vec3& centroid_m,\n        const Vec3& centroid_d,\n        Mat4& align) const;\n};\n\n} /* namespace lvr2 */\n\n#include \"EigenSVDPointAlign.tcc\"\n\n#endif /* EIGENSVDPOINTALIGN_HPP_ */\n", "meta": {"hexsha": "33d4cf1140028dcca352e30da2c65becc7baf24f", "size": 3800, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/lvr2/registration/EigenSVDPointAlign.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/EigenSVDPointAlign.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/EigenSVDPointAlign.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": 36.5384615385, "max_line_length": 96, "alphanum_fraction": 0.6971052632, "num_tokens": 875, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5813030906443133, "lm_q2_score": 0.5273165233795671, "lm_q1q2_score": 0.3065307247883567}}
{"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 calculation of the surface of a cell.\n */\n\n#ifndef ALGORHITHMS_CELL_SURFACE_HPP\n#define ALGORHITHMS_CELL_SURFACE_HPP\n\n#include <boost/python.hpp>\nusing namespace boost::python;\n\n#include \"../points/cartesian.hpp\"\n#include \"../points/cylindrical.hpp\"\n#include \"../points/polar.hpp\"\n#include \"../points/spherical.hpp\"\n\n#include \"../cells/linear.hpp\"\n#include \"../cells/triangular.hpp\"\n#include \"../cells/quadrilateral.hpp\"\n#include \"../cells/tetrahedral.hpp\"\n\n////////////\n// Linear //\n////////////\n\n/**\n * Calculate the surface of a linear cartesian 1D cell.\n * \n * @param cell Cell whose surface will be computed.\n * @return Real number in double precision which represents the surface of the cell.\n * \n * @since 0.1.0\n */\ndouble LinearCartesian1D_Cell_surface(LinearCartesian1D_Cell cell);\n\n/**\n * Calculate the surface of a linear cartesian 2D cell.\n * \n * @param cell Cell whose surface will be computed.\n * @return Real number in double precision which represents the surface of the cell.\n * \n * @since 0.1.0\n */\ndouble LinearCartesian2D_Cell_surface(LinearCartesian2D_Cell cell);\n\n/**\n * Calculate the surface of a linear cartesian 3D cell.\n * \n * @param cell Cell whose surface will be computed.\n * @return Real number in double precision which represents the surface of the cell.\n * \n * @since 0.1.0\n */\ndouble LinearCartesian3D_Cell_surface(LinearCartesian3D_Cell cell);\n\n/**\n * Calculate the surface of a linear cylindrical cell.\n * \n * @param cell Cell whose surface will be computed.\n * @return Real number in double precision which represents the surface of the cell.\n * \n * @since 0.1.0\n */\ndouble LinearCylindrical3D_Cell_surface(LinearCylindrical3D_Cell cell);\n\n/**\n * Calculate the surface of a linear polar cell.\n * \n * @param cell Cell whose surface will be computed.\n * @return Real number in double precision which represents the surface of the cell.\n * \n * @since 0.1.0\n */\ndouble LinearPolar2D_Cell_surface(LinearPolar2D_Cell cell);\n\n/**\n * Calculate the surface of a linear spherical cell.\n * \n * @param cell Cell whose surface will be computed.\n * @return Real number in double precision which represents the surface of the cell.\n * \n * @since 0.1.0\n */\ndouble LinearSpherical3D_Cell_surface(LinearSpherical3D_Cell cell);\n\n////////////////\n// Triangular //\n////////////////\n\n/**\n * Calculate the surface of a triangular cartesian 2D cell.\n * \n * @param cell Cell whose surface will be computed.\n * @return Real number in double precision which represents the surface of the cell.\n * \n * @since 0.1.0\n */\ndouble TriangularCartesian2D_Cell_surface(TriangularCartesian2D_Cell cell);\n\n/**\n * Calculate the surface of a triangular cartesian 3D cell.\n * \n * @param cell Cell whose surface will be computed.\n * @return Real number in double precision which represents the surface of the cell.\n * \n * @since 0.1.0\n */\ndouble TriangularCartesian3D_Cell_surface(TriangularCartesian3D_Cell cell);\n\n/**\n * Calculate the surface of a triangular cylindrical cell.\n * \n * @param cell Cell whose surface will be computed.\n * @return Real number in double precision which represents the surface of the cell.\n * \n * @since 0.1.0\n */\ndouble TriangularCylindrical3D_Cell_surface(TriangularCylindrical3D_Cell cell);\n\n/**\n * Calculate the surface of a triangular polar cell.\n * \n * @param cell Cell whose surface will be computed.\n * @return Real number in double precision which represents the surface of the cell.\n * \n * @since 0.1.0\n */\ndouble TriangularPolar2D_Cell_surface(TriangularPolar2D_Cell cell);\n\n/**\n * Calculate the surface of a triangular spherical cell.\n * \n * @param cell Cell whose surface will be computed.\n * @return Real number in double precision which represents the surface of the cell.\n * \n * @since 0.1.0\n */\ndouble TriangularSpherical3D_Cell_surface(TriangularSpherical3D_Cell cell);\n\n///////////////////\n// Quadrilateral //\n///////////////////\n\n/**\n * Calculate the surface of a quadrilateral cartesian 2D cell.\n * \n * @param cell Cell whose surface will be computed.\n * @return Real number in double precision which represents the surface of the cell.\n * \n * @since 0.1.0\n */\ndouble QuadrilateralCartesian2D_Cell_surface(QuadrilateralCartesian2D_Cell cell);\n\n/**\n * Calculate the surface of a quadrilateral cartesian 3D cell.\n * \n * @param cell Cell whose surface will be computed.\n * @return Real number in double precision which represents the surface of the cell.\n * \n * @since 0.1.0\n */\ndouble QuadrilateralCartesian3D_Cell_surface(QuadrilateralCartesian3D_Cell cell);\n\n/**\n * Calculate the surface of a quadrilateral cylindrical cell.\n * \n * @param cell Cell whose surface will be computed.\n * @return Real number in double precision which represents the surface of the cell.\n * \n * @since 0.1.0\n */\ndouble QuadrilateralCylindrical3D_Cell_surface(QuadrilateralCylindrical3D_Cell cell);\n\n/**\n * Calculate the surface of a quadrilateral polar cell.\n * \n * @param cell Cell whose surface will be computed.\n * @return Real number in double precision which represents the surface of the cell.\n * \n * @since 0.1.0\n */\ndouble QuadrilateralPolar2D_Cell_surface(QuadrilateralPolar2D_Cell cell);\n\n/**\n * Calculate the surface of a quadrilateral spherical cell.\n * \n * @param cell Cell whose surface will be computed.\n * @return Real number in double precision which represents the surface of the cell.\n * \n * @since 0.1.0\n */\ndouble QuadrilateralSpherical3D_Cell_surface(QuadrilateralSpherical3D_Cell cell);\n\n/////////////////\n// Tetrahedral //\n/////////////////\n\n/**\n * Calculate the surface of a tetrahedral cartesian 3D cell.\n * \n * @param cell Cell whose surface will be computed.\n * @return Real number in double precision which represents the surface of the cell.\n * \n * @since 0.1.0\n */\ndouble TetrahedralCartesian3D_Cell_surface(TetrahedralCartesian3D_Cell cell);\n\n/**\n * Calculate the surface of a tetrahedral cylindrical cell.\n * \n * @param cell Cell whose surface will be computed.\n * @return Real number in double precision which represents the surface of the cell.\n * \n * @since 0.1.0\n */\ndouble TetrahedralCylindrical3D_Cell_surface(TetrahedralCylindrical3D_Cell cell);\n\n/**\n * Calculate the surface of a tetrahedral spherical cell.\n * \n * @param cell Cell whose surface will be computed.\n * @return Real number in double precision which represents the surface of the cell.\n * \n * @since 0.1.0\n */\ndouble TetrahedralSpherical3D_Cell_surface(TetrahedralSpherical3D_Cell cell);\n\n#endif /* end of include guard: ALGORHITHMS_CELL_SURFACE_HPP */\n", "meta": {"hexsha": "41e64cbadbcbba50f8a17819bedaee2552d491b6", "size": 6689, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/algorithms/cell_surface.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/cell_surface.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/cell_surface.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": 28.5854700855, "max_line_length": 85, "alphanum_fraction": 0.7346389595, "num_tokens": 1612, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5813030761371503, "lm_q2_score": 0.5273165233795671, "lm_q1q2_score": 0.3065307171384899}}
{"text": "/* boost random/non_central_chi_squared_distribution.hpp header file\n *\n * Copyright Thijs van den Berg 2014\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 * See http://www.boost.org for most recent version including documentation.\n *\n * $Id$\n */\n\n#ifndef BOOST_RANDOM_NON_CENTRAL_CHI_SQUARED_DISTRIBUTION_HPP\n#define BOOST_RANDOM_NON_CENTRAL_CHI_SQUARED_DISTRIBUTION_HPP\n\n#include <boost/config/no_tr1/cmath.hpp>\n#include <iosfwd>\n#include <istream>\n#include <boost/limits.hpp>\n#include <boost/random/detail/config.hpp>\n#include <boost/random/detail/operators.hpp>\n#include <boost/random/uniform_real_distribution.hpp>\n#include <boost/random/normal_distribution.hpp>\n#include <boost/random/chi_squared_distribution.hpp>\n#include <boost/random/poisson_distribution.hpp>\n\nnamespace boost {\nnamespace random {\n\n/**\n * The noncentral chi-squared distribution is a real valued distribution with\n * two parameter, @c k and @c lambda.  The distribution produces values > 0.\n *\n * This is the distribution of the sum of squares of k Normal distributed\n * variates each with variance one and \\f$\\lambda\\f$ the sum of squares of the\n * normal means.\n *\n * The distribution function is\n * \\f$\\displaystyle P(x) = \\frac{1}{2} e^{-(x+\\lambda)/2} \\left( \\frac{x}{\\lambda} \\right)^{k/4-1/2} I_{k/2-1}( \\sqrt{\\lambda x} )\\f$.\n *  where  \\f$\\displaystyle I_\\nu(z)\\f$ is a modified Bessel function of the\n * first kind.\n *\n * The algorithm is taken from\n *\n *  @blockquote\n *  \"Monte Carlo Methods in Financial Engineering\", Paul Glasserman,\n *  2003, XIII, 596 p, Stochastic Modelling and Applied Probability, Vol. 53,\n *  ISBN 978-0-387-21617-1, p 124, Fig. 3.5.\n *  @endblockquote\n */\ntemplate <typename RealType = double>\nclass non_central_chi_squared_distribution {\npublic:\n    typedef RealType result_type;\n    typedef RealType input_type;\n    \n    class param_type {\n    public:\n        typedef non_central_chi_squared_distribution distribution_type;\n        \n        /**\n         * Constructs the parameters of a non_central_chi_squared_distribution.\n         * @c k and @c lambda are the parameter of the distribution.\n         *\n         * Requires: k > 0 && lambda > 0\n         */\n        explicit\n        param_type(RealType k_arg = RealType(1), RealType lambda_arg = RealType(1))\n        : _k(k_arg), _lambda(lambda_arg)\n        {\n            BOOST_ASSERT(k_arg > RealType(0));\n            BOOST_ASSERT(lambda_arg > RealType(0));\n        }\n        \n        /** Returns the @c k parameter of the distribution */\n        RealType k() const { return _k; }\n        \n        /** Returns the @c lambda parameter of the distribution */\n        RealType lambda() const { return _lambda; }\n\n        /** Writes the parameters of the distribution to a @c std::ostream. */\n        BOOST_RANDOM_DETAIL_OSTREAM_OPERATOR(os, param_type, parm)\n        {\n            os << parm._k << ' ' << parm._lambda;\n            return os;\n        }\n        \n        /** Reads the parameters of the distribution from a @c std::istream. */\n        BOOST_RANDOM_DETAIL_ISTREAM_OPERATOR(is, param_type, parm)\n        {\n            is >> parm._k >> std::ws >> parm._lambda;\n            return is;\n        }\n\n        /** Returns true if the parameters have the same values. */\n        BOOST_RANDOM_DETAIL_EQUALITY_OPERATOR(param_type, lhs, rhs)\n        { return lhs._k == rhs._k && lhs._lambda == rhs._lambda; }\n        \n        /** Returns true if the parameters have different values. */\n        BOOST_RANDOM_DETAIL_INEQUALITY_OPERATOR(param_type)\n        \n    private:\n        RealType _k;\n        RealType _lambda;\n    };\n\n    /**\n     * Construct a @c non_central_chi_squared_distribution object. @c k and\n     * @c lambda are the parameter of the distribution.\n     *\n     * Requires: k > 0 && lambda > 0\n     */\n    explicit\n    non_central_chi_squared_distribution(RealType k_arg = RealType(1), RealType lambda_arg = RealType(1))\n      : _param(k_arg, lambda_arg)\n    {\n        BOOST_ASSERT(k_arg > RealType(0));\n        BOOST_ASSERT(lambda_arg > RealType(0));\n    }\n\n    /**\n     * Construct a @c non_central_chi_squared_distribution object from the parameter.\n     */\n    explicit\n    non_central_chi_squared_distribution(const param_type& parm)\n      : _param( parm )\n    { }\n    \n    /**\n     * Returns a random variate distributed according to the\n     * non central chi squared distribution specified by @c param.\n     */\n    template<typename URNG>\n    RealType operator()(URNG& eng, const param_type& parm) const\n    { return non_central_chi_squared_distribution(parm)(eng); }\n    \n    /**\n     * Returns a random variate distributed according to the\n     * non central chi squared distribution.\n     */\n    template<typename URNG> \n    RealType operator()(URNG& eng) \n    {\n        using std::sqrt;\n        if (_param.k() > 1) {\n            boost::random::normal_distribution<RealType> n_dist;\n            boost::random::chi_squared_distribution<RealType> c_dist(_param.k() - RealType(1));\n            RealType _z = n_dist(eng);\n            RealType _x = c_dist(eng);\n            RealType term1 = _z + sqrt(_param.lambda());\n            return term1*term1 + _x;\n        }\n        else {\n            boost::random::poisson_distribution<> p_dist(_param.lambda()/RealType(2));\n            boost::random::poisson_distribution<>::result_type _p = p_dist(eng);\n            boost::random::chi_squared_distribution<RealType> c_dist(_param.k() + RealType(2)*_p);\n            return c_dist(eng);\n        }\n    }\n\n    /** Returns the @c k parameter of the distribution. */\n    RealType k() const { return _param.k(); }\n    \n    /** Returns the @c lambda parameter of the distribution. */\n    RealType lambda() const { return _param.lambda(); }\n    \n    /** Returns the parameters of the distribution. */\n    param_type param() const { return _param; }\n    \n    /** Sets parameters of the distribution. */\n    void param(const param_type& parm) { _param = parm; }\n    \n    /** Resets the distribution, so that subsequent uses does not depend on values already produced by it.*/\n    void reset() {}\n    \n    /** Returns the smallest value that the distribution can produce. */\n    RealType min BOOST_PREVENT_MACRO_SUBSTITUTION() const\n    { return RealType(0); }\n    \n    /** Returns the largest value that the distribution can produce. */\n    RealType max BOOST_PREVENT_MACRO_SUBSTITUTION() const\n    { return (std::numeric_limits<RealType>::infinity)(); }\n\n    /** Writes the parameters of the distribution to a @c std::ostream. */\n    BOOST_RANDOM_DETAIL_OSTREAM_OPERATOR(os, non_central_chi_squared_distribution, dist)\n    {\n        os << dist.param();\n        return os;\n    }\n    \n    /** reads the parameters of the distribution from a @c std::istream. */\n    BOOST_RANDOM_DETAIL_ISTREAM_OPERATOR(is, non_central_chi_squared_distribution, dist)\n    {\n        param_type parm;\n        if(is >> parm) {\n            dist.param(parm);\n        }\n        return is;\n    }\n\n    /** Returns true if two distributions have the same parameters and produce \n        the same sequence of random numbers given equal generators.*/\n    BOOST_RANDOM_DETAIL_EQUALITY_OPERATOR(non_central_chi_squared_distribution, lhs, rhs)\n    { return lhs.param() == rhs.param(); }\n    \n    /** Returns true if two distributions have different parameters and/or can produce \n       different sequences of random numbers given equal generators.*/\n    BOOST_RANDOM_DETAIL_INEQUALITY_OPERATOR(non_central_chi_squared_distribution)\n    \nprivate:\n\n    /// @cond show_private\n    param_type  _param;\n    /// @endcond\n};\n\n} // namespace random\n} // namespace boost\n\n#endif\n", "meta": {"hexsha": "28c9ff6d9a4ea1bb4093aea5e4405eaa1b3bf8b8", "size": 7724, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "contrib/libboost/boost_1_62_0/boost/random/non_central_chi_squared_distribution.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/random/non_central_chi_squared_distribution.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/random/non_central_chi_squared_distribution.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": 34.7927927928, "max_line_length": 134, "alphanum_fraction": 0.6556188503, "num_tokens": 1812, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6224593452091672, "lm_q2_score": 0.49218813572079556, "lm_q1q2_score": 0.3063671046804871}}
{"text": "/*! \\file Peridigm_ElasticMaterial.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_ElasticMaterial.hpp\"\n#include \"Peridigm_Field.hpp\"\n#include \"elastic.h\"\n#ifdef PERIDIGM_KOKKOS\n  #include \"elastic_kokkos.h\"\n#endif\n#include \"material_utilities.h\"\n#include <Teuchos_Assert.hpp>\n#include <Epetra_SerialComm.h>\n#include <Sacado.hpp>\n#include <boost/math/special_functions/fpclassify.hpp>\n\n\n\nusing namespace std;\n\nPeridigmNS::ElasticMaterial::ElasticMaterial(const Teuchos::ParameterList& params)\n  : Material(params),\n    m_bulkModulus(0.0), m_shearModulus(0.0), m_density(0.0), m_alpha(0.0), m_horizon(0.0),\n    m_applyAutomaticDifferentiationJacobian(true),\n    m_applyThermalStrains(false),\n    m_computePartialStress(false),\n    m_OMEGA(PeridigmNS::InfluenceFunction::self().getInfluenceFunction()),\n    m_volumeFieldId(-1), m_damageFieldId(-1), m_weightedVolumeFieldId(-1), m_dilatationFieldId(-1), m_modelCoordinatesFieldId(-1),\n    m_coordinatesFieldId(-1), m_forceDensityFieldId(-1), m_partialStressFieldId(-1), m_bondDamageFieldId(-1),\n    m_deltaTemperatureFieldId(-1), m_planeStrain(false), m_planeStress(false), m_damageModelFieldId(-1)\n{\n  //! \\todo Add meaningful asserts on material properties.\n  m_bulkModulus = calculateBulkModulus(params);\n  m_shearModulus = calculateShearModulus(params);\n  m_density = params.get<double>(\"Density\");\n  m_horizon = params.get<double>(\"Horizon\");\n  if(params.isParameter(\"Apply Automatic Differentiation Jacobian\"))\n    m_applyAutomaticDifferentiationJacobian = params.get<bool>(\"Apply Automatic Differentiation Jacobian\");\n  if(params.isParameter(\"Plane Stress\"))\n    m_planeStress = params.get<bool>(\"Plane Stress\");\n  if(params.isParameter(\"Plane Strain\"))\n    m_planeStrain = params.get<bool>(\"Plane Strain\");\n\n  if(params.isParameter(\"Thermal Expansion Coefficient\")){\n    m_alpha = params.get<double>(\"Thermal Expansion Coefficient\");\n    m_applyThermalStrains = true;\n  }\n\n  if(params.isParameter(\"Compute Partial Stress\"))\n    m_computePartialStress = params.get<bool>(\"Compute Partial Stress\");\n\n  PeridigmNS::FieldManager& fieldManager = PeridigmNS::FieldManager::self();\n  m_volumeFieldId                  = fieldManager.getFieldId(PeridigmField::ELEMENT, PeridigmField::SCALAR,      PeridigmField::CONSTANT, \"Volume\");\n  m_damageFieldId                  = fieldManager.getFieldId(PeridigmField::ELEMENT, PeridigmField::SCALAR,      PeridigmField::TWO_STEP, \"Damage\");\n  m_weightedVolumeFieldId          = fieldManager.getFieldId(PeridigmField::ELEMENT, PeridigmField::SCALAR,      PeridigmField::CONSTANT, \"Weighted_Volume\");\n  m_dilatationFieldId              = fieldManager.getFieldId(PeridigmField::ELEMENT, PeridigmField::SCALAR,      PeridigmField::TWO_STEP, \"Dilatation\");\n  m_modelCoordinatesFieldId        = fieldManager.getFieldId(PeridigmField::NODE,    PeridigmField::VECTOR,      PeridigmField::CONSTANT, \"Model_Coordinates\");\n  m_coordinatesFieldId             = fieldManager.getFieldId(PeridigmField::NODE,    PeridigmField::VECTOR,      PeridigmField::TWO_STEP, \"Coordinates\");\n  m_forceDensityFieldId            = fieldManager.getFieldId(PeridigmField::NODE,    PeridigmField::VECTOR,      PeridigmField::TWO_STEP, \"Force_Density\");\n  m_bondDamageFieldId              = fieldManager.getFieldId(PeridigmField::BOND,    PeridigmField::SCALAR,      PeridigmField::TWO_STEP, \"Bond_Damage\");\n  int m_horizonFieldId             = fieldManager.getFieldId(PeridigmField::ELEMENT, PeridigmField::SCALAR, \t PeridigmField::CONSTANT, \"Horizon\");\n  m_damageModelFieldId \t\t\t   = fieldManager.getFieldId(PeridigmField::NODE,    PeridigmField::VECTOR, \t PeridigmField::TWO_STEP, \"Damage_Model_Data\");\n     \n  if(m_applyThermalStrains)\n    m_deltaTemperatureFieldId      = fieldManager.getFieldId(PeridigmField::NODE,    PeridigmField::SCALAR,      PeridigmField::TWO_STEP, \"Temperature_Change\");\n  if(m_computePartialStress)\n    m_partialStressFieldId         = fieldManager.getFieldId(PeridigmField::ELEMENT, PeridigmField::FULL_TENSOR, PeridigmField::TWO_STEP, \"Partial_Stress\");\n\n  m_fieldIds.push_back(m_volumeFieldId);\n  m_fieldIds.push_back(m_damageFieldId);\n  m_fieldIds.push_back(m_weightedVolumeFieldId);\n  m_fieldIds.push_back(m_dilatationFieldId);\n  m_fieldIds.push_back(m_modelCoordinatesFieldId);\n  m_fieldIds.push_back(m_coordinatesFieldId);\n  m_fieldIds.push_back(m_forceDensityFieldId);\n  m_fieldIds.push_back(m_bondDamageFieldId);\n  m_fieldIds.push_back(m_horizonFieldId);\n  m_fieldIds.push_back(m_damageModelFieldId);\n  if(m_applyThermalStrains)\n    m_fieldIds.push_back(m_deltaTemperatureFieldId);\n  if(m_computePartialStress)\n    m_fieldIds.push_back(m_partialStressFieldId);\n}\n\nPeridigmNS::ElasticMaterial::~ElasticMaterial()\n{\n}\n\nvoid\nPeridigmNS::ElasticMaterial::initialize(const double dt,\n                                        const int numOwnedPoints,\n                                        const int* ownedIDs,\n                                        const int* neighborhoodList,\n                                        PeridigmNS::DataManager& dataManager)\n{\n  // Extract pointers to the underlying data\n  double *xOverlap,  *cellVolumeOverlap, *weightedVolume;\n  dataManager.getData(m_modelCoordinatesFieldId, PeridigmField::STEP_NONE)->ExtractView(&xOverlap);\n  dataManager.getData(m_volumeFieldId, PeridigmField::STEP_NONE)->ExtractView(&cellVolumeOverlap);\n  dataManager.getData(m_weightedVolumeFieldId, PeridigmField::STEP_NONE)->ExtractView(&weightedVolume);\n  // have to be initialized here, to have no probelm with damage - no daamge model mix\n  dataManager.getData(m_damageModelFieldId, PeridigmField::STEP_NP1)->PutScalar(0.0);\n  MATERIAL_EVALUATION::computeWeightedVolume(xOverlap,cellVolumeOverlap,weightedVolume,numOwnedPoints,neighborhoodList,m_horizon);\n  dataManager.getData(m_dilatationFieldId, PeridigmField::STEP_NP1)->PutScalar(0.0);\n\n}\n\nvoid\nPeridigmNS::ElasticMaterial::computeForce(const double dt,\n                                          const int numOwnedPoints,\n                                          const int* ownedIDs,\n                                          const int* neighborhoodList,\n                                          PeridigmNS::DataManager& dataManager) const\n{\n  // Zero out the forces\n  dataManager.getData(m_forceDensityFieldId, PeridigmField::STEP_NP1)->PutScalar(0.0);\n  if(m_computePartialStress)\n    dataManager.getData(m_partialStressFieldId, PeridigmField::STEP_NP1)->PutScalar(0.0);\n\n  // Extract pointers to the underlying data\n  double *x, *y, *cellVolume, *weightedVolume, *dilatation, *bondDamage, *force, *deltaTemperature, *partialStress;\n\n  dataManager.getData(m_modelCoordinatesFieldId, PeridigmField::STEP_NONE)->ExtractView(&x);\n  dataManager.getData(m_coordinatesFieldId, PeridigmField::STEP_NP1)->ExtractView(&y);\n  dataManager.getData(m_volumeFieldId, PeridigmField::STEP_NONE)->ExtractView(&cellVolume);\n  dataManager.getData(m_weightedVolumeFieldId, PeridigmField::STEP_NONE)->ExtractView(&weightedVolume);\n  dataManager.getData(m_dilatationFieldId, PeridigmField::STEP_NP1)->ExtractView(&dilatation);\n  dataManager.getData(m_dilatationFieldId, PeridigmField::STEP_NP1)->PutScalar(0.0);\n  dataManager.getData(m_bondDamageFieldId, PeridigmField::STEP_NP1)->ExtractView(&bondDamage);\n  dataManager.getData(m_forceDensityFieldId, PeridigmField::STEP_NP1)->ExtractView(&force);\n  \n  deltaTemperature = NULL;\n  if(m_applyThermalStrains)\n    dataManager.getData(m_deltaTemperatureFieldId, PeridigmField::STEP_NP1)->ExtractView(&deltaTemperature);\n  partialStress = NULL;\n  if(m_computePartialStress)\n    dataManager.getData(m_partialStressFieldId, PeridigmField::STEP_NP1)->ExtractView(&partialStress);\n\n  MATERIAL_EVALUATION::computeDilatation(x,y,weightedVolume,cellVolume,bondDamage,dilatation,neighborhoodList,numOwnedPoints,m_horizon,m_OMEGA,m_alpha,deltaTemperature);\n  \n#ifdef PERIDIGM_KOKKOS\n  MATERIAL_EVALUATION::computeInternalForceLinearElasticKokkos(x,y,weightedVolume,cellVolume,dilatation,bondDamage,scf,force,neighborhoodList,numOwnedPoints,m_bulkModulus,m_shearModulus,m_horizon,m_alpha,deltaTemperature);\n#else\n  MATERIAL_EVALUATION::computeInternalForceLinearElastic(x,y,weightedVolume,cellVolume,dilatation,bondDamage,force,partialStress,neighborhoodList,numOwnedPoints,m_bulkModulus,m_shearModulus,m_horizon,m_alpha,deltaTemperature, m_planeStrain, m_planeStress);\n#endif\n}\n\nvoid\nPeridigmNS::ElasticMaterial::computeStoredElasticEnergyDensity(const double dt,\n                                                               const int numOwnedPoints,\n                                                               const int* ownedIDs,\n                                                               const int* neighborhoodList,\n                                                               PeridigmNS::DataManager& dataManager) const\n{\n  // This function is intended to be called from a compute class.\n  // The compute class should have already created the Stored_Elastic_Energy_Density field id.\n  //int storedElasticEnergyDensityFieldId = PeridigmNS::FieldManager::self().getFieldId(\"Stored_Elastic_Energy_Density\");\n\n  double *x, *y, *cellVolume, *weightedVolume, *dilatation, *bondDamage; \n  dataManager.getData(m_modelCoordinatesFieldId, PeridigmField::STEP_NONE)->ExtractView(&x);\n  dataManager.getData(m_coordinatesFieldId, PeridigmField::STEP_NP1)->ExtractView(&y);\n  dataManager.getData(m_volumeFieldId, PeridigmField::STEP_NONE)->ExtractView(&cellVolume);\n  dataManager.getData(m_weightedVolumeFieldId, PeridigmField::STEP_NONE)->ExtractView(&weightedVolume);\n  dataManager.getData(m_dilatationFieldId, PeridigmField::STEP_NP1)->ExtractView(&dilatation);\n  dataManager.getData(m_bondDamageFieldId, PeridigmField::STEP_NP1)->ExtractView(&bondDamage);\n  //double *storedElasticEnergyDensity;\n  //dataManager.getData(storedElasticEnergyDensityFieldId, PeridigmField::STEP_NONE)->ExtractView(&storedElasticEnergyDensity);\n\n  double *deltaTemperature = NULL;\n  if(m_applyThermalStrains)\n    dataManager.getData(m_deltaTemperatureFieldId, PeridigmField::STEP_NP1)->ExtractView(&deltaTemperature);\n\n  double *damageModel;\n  dataManager.getData(m_damageModelFieldId, PeridigmField::STEP_NP1)->ExtractView(&damageModel);\n  int iID, iNID, numNeighbors, nodeId, neighborId;\n  double omega, nodeInitialX[3], nodeCurrentX[3];\n  double initialDistance, currentDistance, deviatoricExtension, neighborBondDamage;\n  double nodeDilatation, alpha, temp;\n//tbd plane strain/stress\n  int neighborhoodListIndex(0), bondIndex(0);\n  MATERIAL_EVALUATION::computeDilatation(x,y,weightedVolume,cellVolume,bondDamage,dilatation,neighborhoodList,numOwnedPoints,m_horizon,m_OMEGA,m_alpha,deltaTemperature);\n\n  for(iID=0 ; iID<numOwnedPoints ; ++iID){\n\n    nodeId = ownedIDs[iID];\n    nodeInitialX[0] = x[nodeId*3];\n    nodeInitialX[1] = x[nodeId*3+1];\n    nodeInitialX[2] = x[nodeId*3+2];\n    nodeCurrentX[0] = y[nodeId*3];\n    nodeCurrentX[1] = y[nodeId*3+1];\n    nodeCurrentX[2] = y[nodeId*3+2];\n    nodeDilatation = dilatation[nodeId];\n    alpha = 15.0*m_shearModulus/weightedVolume[nodeId];\n\n    temp = 0.0;\n      \n    numNeighbors = neighborhoodList[neighborhoodListIndex++];\n    for(iNID=0 ; iNID<numNeighbors ; ++iNID){\n      neighborId = neighborhoodList[neighborhoodListIndex++];\n      neighborBondDamage = bondDamage[bondIndex++];\n      initialDistance = \n        distance(nodeInitialX[0], nodeInitialX[1], nodeInitialX[2],\n                 x[neighborId*3], x[neighborId*3+1], x[neighborId*3+2]);\n      currentDistance = \n        distance(nodeCurrentX[0], nodeCurrentX[1], nodeCurrentX[2],\n                 y[neighborId*3], y[neighborId*3+1], y[neighborId*3+2]);\n      if(m_applyThermalStrains)\n      currentDistance -= m_alpha*deltaTemperature[nodeId]*initialDistance;\n      deviatoricExtension = (currentDistance - initialDistance) - nodeDilatation*initialDistance/3.0;\n      omega=m_OMEGA(initialDistance,m_horizon);\n      temp += (1.0-neighborBondDamage)*omega*deviatoricExtension*deviatoricExtension*cellVolume[neighborId];\n    }\n    //storedElasticEnergyDensity[nodeId] = 0.5*m_bulkModulus*nodeDilatation*nodeDilatation + 0.5*alpha*temp;\n    damageModel[3*iID] = 0.5*m_bulkModulus*nodeDilatation*nodeDilatation + 0.5*alpha*temp;\n  }\n}\n\nvoid\nPeridigmNS::ElasticMaterial::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  if(m_applyAutomaticDifferentiationJacobian){\n    // Compute the Jacobian via automatic differentiation\n    computeAutomaticDifferentiationJacobian(dt, numOwnedPoints, ownedIDs, neighborhoodList, dataManager, jacobian, jacobianType);  \n  }\n  else{\n    // Call the base class function, which computes the Jacobian by finite difference\n    PeridigmNS::Material::computeJacobian(dt, numOwnedPoints, ownedIDs, neighborhoodList, dataManager, jacobian, jacobianType);\n  }\n}\n\n\nvoid\nPeridigmNS::ElasticMaterial::computeAutomaticDifferentiationJacobian(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 contributions to the tangent matrix on an element-by-element basis\n\n  // To reduce memory re-allocation, use static variable to store Fad types for\n  // current coordinates (independent variables).\n  static vector<Sacado::Fad::DFad<double> > y_AD;\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    int numEntries = numNeighbors+1;\n    int numDof = 3*numEntries;\n    vector<int> tempMyGlobalIDs(numEntries);\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(numEntries); \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(numEntries, numEntries, &tempMyGlobalIDs[0], 1, 0, serialComm));\n    Teuchos::RCP<Epetra_BlockMap> tempThreeDimensionalMap = Teuchos::rcp(new Epetra_BlockMap(numEntries, numEntries, &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 field specs 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(tempNumOwnedPoints);\n    tempOwnedIDs[0] = 0;\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() < numDof)\n      scratchMatrix.Resize(numDof);\n\n    // Create a list of global indices for the rows/columns in the scratch matrix.\n    vector<int> globalIndices(numDof);\n    for(int i=0 ; i<numEntries ; ++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    // Extract pointers to the underlying data in the constitutiveData array.\n    double *x, *y, *cellVolume, *weightedVolume, *damage, *bondDamage, *deltaTemperature;\n    tempDataManager.getData(m_modelCoordinatesFieldId, PeridigmField::STEP_NONE)->ExtractView(&x);\n    tempDataManager.getData(m_coordinatesFieldId, PeridigmField::STEP_NP1)->ExtractView(&y);\n    tempDataManager.getData(m_volumeFieldId, PeridigmField::STEP_NONE)->ExtractView(&cellVolume);\n    tempDataManager.getData(m_weightedVolumeFieldId, PeridigmField::STEP_NONE)->ExtractView(&weightedVolume);\n    tempDataManager.getData(m_damageFieldId, PeridigmField::STEP_NP1)->ExtractView(&damage);\n    tempDataManager.getData(m_bondDamageFieldId, PeridigmField::STEP_NP1)->ExtractView(&bondDamage);\n    deltaTemperature = NULL;\n    if(m_applyThermalStrains)\n      tempDataManager.getData(m_deltaTemperatureFieldId, PeridigmField::STEP_NP1)->ExtractView(&deltaTemperature);\n    // Create arrays of Fad objects for the current coordinates, dilatation, and force density\n    // Modify the existing vector of Fad objects for the current coordinates\n    if((int)y_AD.size() < numDof)\n      y_AD.resize(numDof);\n    for(int i=0 ; i<numDof ; ++i){\n      y_AD[i].diff(i, numDof);\n      y_AD[i].val() = y[i];\n    }\n    // Create vectors of empty AD types for the dependent variables\n    vector<Sacado::Fad::DFad<double> > dilatation_AD(numEntries);\n    vector<Sacado::Fad::DFad<double> > force_AD(numDof);\n\n    vector<Sacado::Fad::DFad<double> > partialStress_AD;\n    Sacado::Fad::DFad<double> *partialStress_AD_Ptr = NULL;\n    if(m_computePartialStress){\n      partialStress_AD.resize(numDof*numDof);\n      partialStress_AD_Ptr = &partialStress_AD[0];\n    }\n\n    // Evaluate the constitutive model using the AD types\n    MATERIAL_EVALUATION::computeDilatation(x,&y_AD[0],weightedVolume,cellVolume,bondDamage,&dilatation_AD[0],&tempNeighborhoodList[0],tempNumOwnedPoints,m_horizon,m_OMEGA,m_alpha,deltaTemperature);\n    MATERIAL_EVALUATION::computeInternalForceLinearElastic(x,&y_AD[0],weightedVolume,cellVolume,&dilatation_AD[0],bondDamage,&force_AD[0],partialStress_AD_Ptr,&tempNeighborhoodList[0],tempNumOwnedPoints,m_bulkModulus,m_shearModulus,m_horizon,m_alpha,deltaTemperature);\n\n    // Load derivative values into scratch matrix\n    // Multiply by volume along the way to convert force density to force\n    double value;\n    for(int row=0 ; row<numDof ; ++row){\n      for(int col=0 ; col<numDof ; ++col){\n\tvalue = force_AD[row].dx(col) * cellVolume[row/3];\n\tTEUCHOS_TEST_FOR_EXCEPT_MSG(!boost::math::isfinite(value), \"**** NaN detected in ElasticMaterial::computeAutomaticDifferentiationJacobian().\\n\");\n        scratchMatrix(row, col) = value;\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}\nvoid\nPeridigmNS::ElasticMaterial::evalDilatation(const double dt,\n                                                               const int numOwnedPoints,\n                                                               const int* ownedIDs,\n                                                               const int* neighborhoodList,\n                                                               PeridigmNS::DataManager& dataManager) const\n{\n  double *x, *y, *cellVolume, *weightedVolume, *dilatation, *bondDamage, *damageModel, *deltaTemperature;\n  dataManager.getData(m_damageModelFieldId, PeridigmField::STEP_NP1)->ExtractView(&damageModel);\n  dataManager.getData(m_modelCoordinatesFieldId, PeridigmField::STEP_NONE)->ExtractView(&x);\n  dataManager.getData(m_coordinatesFieldId, PeridigmField::STEP_NP1)->ExtractView(&y);\n  dataManager.getData(m_volumeFieldId, PeridigmField::STEP_NONE)->ExtractView(&cellVolume);\n  dataManager.getData(m_weightedVolumeFieldId, PeridigmField::STEP_NONE)->ExtractView(&weightedVolume);\n  dataManager.getData(m_dilatationFieldId, PeridigmField::STEP_NP1)->ExtractView(&dilatation);\n  dataManager.getData(m_dilatationFieldId, PeridigmField::STEP_NP1)->PutScalar(0.0);\n  dataManager.getData(m_bondDamageFieldId, PeridigmField::STEP_NP1)->ExtractView(&bondDamage);\n  const double *m = weightedVolume;\n  int iID;\n  deltaTemperature = NULL;\n  if(m_applyThermalStrains)\n    dataManager.getData(m_deltaTemperatureFieldId, PeridigmField::STEP_NP1)->ExtractView(&deltaTemperature);\n\n  MATERIAL_EVALUATION::computeDilatation(x,y,weightedVolume,cellVolume,bondDamage,dilatation,neighborhoodList,numOwnedPoints,m_horizon,m_OMEGA,m_alpha,deltaTemperature);\n  //std::cout<<m_shearModulus / (*m)<<\" \"<<m_bulkModulus  / (*m)<< \" \" << <<std::endl;\n  for(iID=0 ; iID<numOwnedPoints ; ++iID, dilatation++, m++){\n\t\t\n        damageModel[3*iID]   = *dilatation;\n        damageModel[3*iID+1] = m_bulkModulus  / (*m);\n        damageModel[3*iID+2] = m_shearModulus / (*m);\n\t\t\n  }\n  \n}\n", "meta": {"hexsha": "403bc2a04d7fc0f4d4b8beb452a798d079af44f3", "size": 24337, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Peridigm/Code/Anisotropic_Material/materials/Peridigm_ElasticMaterial.cpp", "max_stars_repo_name": "oldninja/PeriDoX", "max_stars_repo_head_hexsha": "f31bccc7b8ea60cd814d00732aebdbbe876a2ac7", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Peridigm/Code/Anisotropic_Material/materials/Peridigm_ElasticMaterial.cpp", "max_issues_repo_name": "oldninja/PeriDoX", "max_issues_repo_head_hexsha": "f31bccc7b8ea60cd814d00732aebdbbe876a2ac7", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Peridigm/Code/Anisotropic_Material/materials/Peridigm_ElasticMaterial.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": 55.3113636364, "max_line_length": 268, "alphanum_fraction": 0.7106052513, "num_tokens": 6056, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6224593312018546, "lm_q2_score": 0.49218813572079556, "lm_q1q2_score": 0.30636709778625404}}
{"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 DYNAMIC_SAMPLER_HH\n#define DYNAMIC_SAMPLER_HH\n\n#include \"random.hh\"\n#include <functional>\n#include <boost/mpl/if.hpp>\n\nnamespace graph_tool\n{\nusing namespace std;\nusing namespace boost;\n\ntemplate <class Value>\nclass DynamicSampler\n{\npublic:\n    DynamicSampler() : _back(0), _n_items(0) {}\n\n    DynamicSampler(const vector<Value>& items,\n                   const vector<double>& probs)\n        : _back(0), _n_items(0)\n    {\n        for (size_t i = 0; i < items.size(); ++i)\n            insert(items[i], probs[i]);\n    }\n\n    typedef Value value_type;\n\n    size_t get_left(size_t i)   const { return 2 * i + 1;               }\n    size_t get_right(size_t i)  const { return 2 * i + 2;               }\n    size_t get_parent(size_t i) const { return i > 0 ? (i - 1) / 2 : 0; }\n\n    template <class RNG>\n    const Value& sample(RNG& rng) const\n    {\n        uniform_real_distribution<> sample(0, _tree[0]);\n        double u = sample(rng), c = 0;\n\n        size_t pos = 0;\n        while (_idx[pos] == numeric_limits<size_t>::max())\n        {\n            size_t l = get_left(pos);\n            double a = _tree[l];\n            if (u < a + c)\n            {\n                pos = l;\n            }\n            else\n            {\n                pos = get_right(pos);\n                c += a;\n            }\n        }\n        size_t i = _idx[pos];\n        return _items[i];\n    }\n\n    size_t insert(const Value& v, double w)\n    {\n        size_t pos;\n        if (_free.empty())\n        {\n            if (_back > 0)\n            {\n                // move parent to left leaf\n                pos = get_parent(_back);\n                size_t l = get_left(pos);\n                _idx[l] = _idx[pos];\n                _ipos[_idx[l]] = l;\n                _tree[l] = _tree[pos];\n                _idx[pos] = numeric_limits<size_t>::max();\n\n                // position new item to the right\n                _back = get_right(pos);\n            }\n\n            pos = _back;\n            check_size(pos);\n\n            _idx[pos] = _items.size();\n            _items.push_back(v);\n            _valid.push_back(true);\n            _ipos.push_back(pos);\n            _tree[pos] = w;\n            _back++;\n            check_size(_back);\n        }\n        else\n        {\n            pos = _free.back();\n            auto i = _idx[pos];\n            _items[i] = v;\n            _valid[i] = true;\n            _tree[pos] = w;\n            _free.pop_back();\n        }\n\n        insert_leaf_prob(pos);\n        _n_items++;\n        return _idx[pos];\n    }\n\n    void remove(size_t i)\n    {\n        size_t pos = _ipos[i];\n        remove_leaf_prob(pos);\n        _free.push_back(pos);\n        _items[i] = Value();\n        _valid[i] = false;\n        _n_items--;\n    }\n\n    void clear(bool shrink)\n    {\n        _items.clear();\n        _ipos.clear();\n        _tree.clear();\n        _idx.clear();\n        _free.clear();\n        _valid.clear();\n        if (shrink)\n        {\n            _items.shrink_to_fit();\n            _ipos.shrink_to_fit();\n            _tree.shrink_to_fit();\n            _idx.shrink_to_fit();\n            _free.shrink_to_fit();\n            _valid.shrink_to_fit();\n        }\n        _back = 0;\n        _n_items = 0;\n    }\n\n    void rebuild()\n    {\n        vector<Value> items;\n        vector<double> probs;\n\n        for (size_t i = 0; i < _tree.size(); ++i)\n        {\n            if (_idx[i] == numeric_limits<size_t>::max())\n                continue;\n            size_t j = _idx[i];\n            if (!_valid[j])\n                continue;\n            items.push_back(_items[j]);\n            probs.push_back(_tree[i]);\n        }\n\n        clear(true);\n\n        for (size_t i = 0; i < items.size(); ++i)\n            insert(items[i], probs[i]);\n    }\n\n    const Value& operator[](size_t i) const\n    {\n        return _items[i];\n    }\n\n    bool is_valid(size_t i) const\n    {\n        return ((i < _items.size()) && _valid[i]);\n    }\n\n    const auto& items() const\n    {\n        return _items;\n    }\n\n    auto begin() const\n    {\n        return _items.begin();\n    }\n\n    auto end() const\n    {\n        return _items.end();\n    }\n\n    size_t size() const\n    {\n        return _items.size();\n    }\n\n    bool empty() const\n    {\n        return _n_items == 0;\n    }\n\nprivate:\n\n    void check_size(size_t i)\n    {\n        if (i >= _tree.size())\n        {\n            _idx.resize(i + 1, numeric_limits<size_t>::max());\n            _tree.resize(i + 1, 0);\n        }\n    }\n\n    void remove_leaf_prob(size_t i)\n    {\n        size_t parent = i;\n        double w = _tree[i];\n        while (parent > 0)\n        {\n            parent = get_parent(parent);\n            _tree[parent] -= w;\n        }\n        _tree[i] = 0;\n    }\n\n    void insert_leaf_prob(size_t i)\n    {\n        size_t parent = i;\n        double w = _tree[i];\n\n        while (parent > 0)\n        {\n            parent = get_parent(parent);\n            _tree[parent] += w;\n        }\n    }\n\n\n    vector<Value>  _items;\n    vector<size_t> _ipos;  // position of the item in the tree\n\n    vector<double> _tree;  // tree nodes with weight sums\n    vector<size_t> _idx;   // index in _items\n    int _back;             // last item in tree\n\n    vector<size_t> _free;  // empty leafs\n    vector<bool> _valid;   // non-removed items\n    size_t _n_items;\n};\n\n\n\n} // namespace graph_tool\n\n#endif // DYNAMIC_SAMPLER_HH\n", "meta": {"hexsha": "b1f154393f63162690cb09cf45c702d54dcde050", "size": 6107, "ext": "hh", "lang": "C++", "max_stars_repo_path": "graph-tool-2.27/src/graph/generation/dynamic_sampler.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/dynamic_sampler.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/dynamic_sampler.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": 23.398467433, "max_line_length": 73, "alphanum_fraction": 0.5045030293, "num_tokens": 1522, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6224593312018546, "lm_q2_score": 0.4921881357207955, "lm_q1q2_score": 0.306367097786254}}
{"text": "/**\n * Orthanc - A Lightweight, RESTful DICOM Store\n * Copyright (C) 2012-2016 Sebastien Jodogne, Medical Physics\n * Department, University Hospital of Liege, Belgium\n * Copyright (C) 2017-2020 Osimis S.A., Belgium\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 as\n * published by the Free Software Foundation, either version 3 of the\n * License, or (at your option) any later version.\n *\n * In addition, as a special exception, the copyright holders of this\n * program give permission to link the code of its release with the\n * OpenSSL project's \"OpenSSL\" library (or with modified versions of it\n * that use the same license as the \"OpenSSL\" library), and distribute\n * the linked executables. You must obey the GNU General Public License\n * in all respects for all of the code used other than \"OpenSSL\". If you\n * modify file(s) with this exception, you may extend this exception to\n * your version of the file(s), but you are not obligated to do so. If\n * you do not wish to do so, delete this exception statement from your\n * version. If you delete this exception statement from all source files\n * in the program, then also delete it here.\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. 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 this program. If not, see <http://www.gnu.org/licenses/>.\n **/\n\n\n#include \"PrecompiledHeadersServer.h\"\n#include \"SliceOrdering.h\"\n\n#include \"../../OrthancFramework/Sources/Logging.h\"\n#include \"../../OrthancFramework/Sources/Toolbox.h\"\n#include \"ServerEnumerations.h\"\n#include \"ServerIndex.h\"\n\n#include <algorithm>\n#include <boost/lexical_cast.hpp>\n#include <boost/noncopyable.hpp>\n\n\nnamespace Orthanc\n{\n  static bool TokenizeVector(std::vector<float>& result,\n                             const std::string& value,\n                             unsigned int expectedSize)\n  {\n    std::vector<std::string> tokens;\n    Toolbox::TokenizeString(tokens, value, '\\\\');\n\n    if (tokens.size() != expectedSize)\n    {\n      return false;\n    }\n\n    result.resize(tokens.size());\n\n    for (size_t i = 0; i < tokens.size(); i++)\n    {\n      try\n      {\n        const std::string token = Toolbox::StripSpaces(tokens[i]);\n        result[i] = boost::lexical_cast<float>(token);\n      }\n      catch (boost::bad_lexical_cast&)\n      {\n        return false;\n      }\n    }\n\n    return true;\n  }\n\n\n  static bool TokenizeVector(std::vector<float>& result,\n                             const DicomMap& map,\n                             const DicomTag& tag,\n                             unsigned int expectedSize)\n  {\n    const DicomValue* value = map.TestAndGetValue(tag);\n\n    if (value == NULL ||\n        value->IsNull() ||\n        value->IsBinary())\n    {\n      return false;\n    }\n    else\n    {\n      return TokenizeVector(result, value->GetContent(), expectedSize);\n    }\n  }\n\n\n  static bool IsCloseToZero(double x)\n  {\n    return fabs(x) < 10.0 * std::numeric_limits<float>::epsilon();\n  }\n\n  \n  bool SliceOrdering::ComputeNormal(Vector& normal,\n                                    const DicomMap& dicom)\n  {\n    std::vector<float> cosines;\n\n    if (TokenizeVector(cosines, dicom, DICOM_TAG_IMAGE_ORIENTATION_PATIENT, 6))\n    {\n      assert(cosines.size() == 6);\n      normal[0] = cosines[1] * cosines[5] - cosines[2] * cosines[4];\n      normal[1] = cosines[2] * cosines[3] - cosines[0] * cosines[5];\n      normal[2] = cosines[0] * cosines[4] - cosines[1] * cosines[3];\n      return true;\n    }\n    else\n    {\n      return false;\n    }\n  }\n\n\n  bool SliceOrdering::IsParallelOrOpposite(const Vector& u,\n                                           const Vector& v)\n  {\n    // Check out \"GeometryToolbox::IsParallelOrOpposite()\" in Stone of\n    // Orthanc for explanations\n    const double u1 = u[0];\n    const double u2 = u[1];\n    const double u3 = u[2];\n    const double normU = sqrt(u1 * u1 + u2 * u2 + u3 * u3);\n\n    const double v1 = v[0];\n    const double v2 = v[1];\n    const double v3 = v[2];\n    const double normV = sqrt(v1 * v1 + v2 * v2 + v3 * v3);\n\n    if (IsCloseToZero(normU * normV))\n    {\n      return false;\n    }\n    else\n    {\n      const double cosAngle = (u1 * v1 + u2 * v2 + u3 * v3) / (normU * normV);\n\n      return (IsCloseToZero(cosAngle - 1.0) ||      // Close to +1: Parallel, non-opposite\n              IsCloseToZero(fabs(cosAngle) - 1.0)); // Close to -1: Parallel, opposite\n    }\n  }\n\n  \n  struct SliceOrdering::Instance : public boost::noncopyable\n  {\n  private:\n    std::string   instanceId_;\n    bool          hasPosition_;\n    Vector        position_;   \n    bool          hasNormal_;\n    Vector        normal_;   \n    bool          hasIndexInSeries_;\n    size_t        indexInSeries_;\n    unsigned int  framesCount_;\n\n  public:\n    Instance(ServerIndex& index,\n             const std::string& instanceId) :\n      instanceId_(instanceId),\n      framesCount_(1)\n    {\n      DicomMap instance;\n      if (!index.GetMainDicomTags(instance, instanceId, ResourceType_Instance, ResourceType_Instance))\n      {\n        throw OrthancException(ErrorCode_UnknownResource);\n      }\n\n      const DicomValue* frames = instance.TestAndGetValue(DICOM_TAG_NUMBER_OF_FRAMES);\n      if (frames != NULL &&\n          !frames->IsNull() &&\n          !frames->IsBinary())\n      {\n        try\n        {\n          const std::string token = Toolbox::StripSpaces(frames->GetContent());\n          framesCount_ = boost::lexical_cast<unsigned int>(token);\n        }\n        catch (boost::bad_lexical_cast&)\n        {\n        }\n      }\n      \n      std::vector<float> tmp;\n      hasPosition_ = TokenizeVector(tmp, instance, DICOM_TAG_IMAGE_POSITION_PATIENT, 3);\n\n      if (hasPosition_)\n      {\n        position_[0] = tmp[0];\n        position_[1] = tmp[1];\n        position_[2] = tmp[2];\n      }\n\n      hasNormal_ = ComputeNormal(normal_, instance);\n\n      std::string s;\n      hasIndexInSeries_ = false;\n\n      try\n      {\n        if (index.LookupMetadata(s, instanceId, MetadataType_Instance_IndexInSeries))\n        {\n          indexInSeries_ = boost::lexical_cast<size_t>(s);\n          hasIndexInSeries_ = true;\n        }\n      }\n      catch (boost::bad_lexical_cast&)\n      {\n      }\n    }\n\n    const std::string& GetIdentifier() const\n    {\n      return instanceId_;\n    }\n\n    bool HasPosition() const\n    {\n      return hasPosition_;\n    }\n\n    float ComputeRelativePosition(const Vector& normal) const\n    {\n      assert(HasPosition());\n      return (normal[0] * position_[0] + \n              normal[1] * position_[1] +\n              normal[2] * position_[2]);\n    }\n\n    bool HasIndexInSeries() const\n    {\n      return hasIndexInSeries_;\n    }\n    \n    size_t GetIndexInSeries() const\n    {\n      assert(HasIndexInSeries());\n      return indexInSeries_;\n    }\n\n    unsigned int GetFramesCount() const\n    {\n      return framesCount_;\n    }\n\n    bool HasNormal() const\n    {\n      return hasNormal_;\n    }\n\n    const Vector& GetNormal() const\n    {\n      assert(hasNormal_);\n      return normal_;\n    }\n  };\n\n\n  class SliceOrdering::PositionComparator\n  {\n  private:\n    const Vector&  normal_;\n\n  public:\n    explicit PositionComparator(const Vector& normal) : normal_(normal)\n    {\n    }\n    \n    int operator() (const Instance* a,\n                    const Instance* b) const\n    {\n      return a->ComputeRelativePosition(normal_) < b->ComputeRelativePosition(normal_);\n    }\n  };\n\n\n  bool SliceOrdering::IndexInSeriesComparator(const SliceOrdering::Instance* a,\n                                              const SliceOrdering::Instance* b)\n  {\n    return a->GetIndexInSeries() < b->GetIndexInSeries();\n  }  \n\n\n  void SliceOrdering::ComputeNormal()\n  {\n    DicomMap series;\n    if (!index_.GetMainDicomTags(series, seriesId_, ResourceType_Series, ResourceType_Series))\n    {\n      throw OrthancException(ErrorCode_UnknownResource);\n    }\n\n    hasNormal_ = ComputeNormal(normal_, series);\n  }\n\n\n  void SliceOrdering::CreateInstances()\n  {\n    std::list<std::string> instancesId;\n    index_.GetChildren(instancesId, seriesId_);\n\n    instances_.reserve(instancesId.size());\n    for (std::list<std::string>::const_iterator\n           it = instancesId.begin(); it != instancesId.end(); ++it)\n    {\n      instances_.push_back(new Instance(index_, *it));\n    }\n  }\n  \n\n  bool SliceOrdering::SortUsingPositions()\n  {\n    if (instances_.size() <= 1)\n    {\n      // One single instance: It is sorted by default\n      return true;\n    }\n\n    if (!hasNormal_)\n    {\n      return false;\n    }\n\n    for (size_t i = 0; i < instances_.size(); i++)\n    {\n      assert(instances_[i] != NULL);\n\n      if (!instances_[i]->HasPosition() ||\n          (instances_[i]->HasNormal() &&\n           !IsParallelOrOpposite(instances_[i]->GetNormal(), normal_)))\n      {\n        return false;\n      }\n    }\n\n    PositionComparator comparator(normal_);\n    std::sort(instances_.begin(), instances_.end(), comparator);\n\n    float a = instances_[0]->ComputeRelativePosition(normal_);\n    for (size_t i = 1; i < instances_.size(); i++)\n    {\n      float b = instances_[i]->ComputeRelativePosition(normal_);\n\n      if (std::fabs(b - a) <= 10.0f * std::numeric_limits<float>::epsilon())\n      {\n        // Not enough space between two slices along the normal of the volume\n        return false;\n      }\n\n      a = b;\n    }\n\n    // This is a 3D volume\n    isVolume_ = true;\n    return true;\n  }\n\n\n  bool SliceOrdering::SortUsingIndexInSeries()\n  {\n    if (instances_.size() <= 1)\n    {\n      // One single instance: It is sorted by default\n      return true;\n    }\n\n    for (size_t i = 0; i < instances_.size(); i++)\n    {\n      assert(instances_[i] != NULL);\n      if (!instances_[i]->HasIndexInSeries())\n      {\n        return false;\n      }\n    }\n\n    std::sort(instances_.begin(), instances_.end(), IndexInSeriesComparator);\n    \n    for (size_t i = 1; i < instances_.size(); i++)\n    {\n      if (instances_[i - 1]->GetIndexInSeries() == instances_[i]->GetIndexInSeries())\n      {\n        // The current \"IndexInSeries\" occurs 2 times: Not a proper ordering\n        LOG(WARNING) << \"This series contains 2 slices with the same index, trying to display it anyway\";\n        break;\n      }\n    }\n\n    return true;\n  }\n\n\n  SliceOrdering::SliceOrdering(ServerIndex& index,\n                               const std::string& seriesId) :\n    index_(index),\n    seriesId_(seriesId),\n    isVolume_(false)\n  {\n    ComputeNormal();\n    CreateInstances();\n\n    if (!SortUsingPositions() &&\n        !SortUsingIndexInSeries())\n    {\n      throw OrthancException(ErrorCode_CannotOrderSlices,\n                             \"Unable to order the slices of series \" + seriesId);\n    }\n  }\n\n\n  SliceOrdering::~SliceOrdering()\n  {\n    for (std::vector<Instance*>::iterator\n           it = instances_.begin(); it != instances_.end(); ++it)\n    {\n      if (*it != NULL)\n      {\n        delete *it;\n      }\n    }\n  }\n\n\n  const std::string& SliceOrdering::GetInstanceId(size_t index) const\n  {\n    if (index >= instances_.size())\n    {\n      throw OrthancException(ErrorCode_ParameterOutOfRange);\n    }\n    else\n    {\n      return instances_[index]->GetIdentifier();\n    }\n  }\n\n\n  unsigned int SliceOrdering::GetFramesCount(size_t index) const\n  {\n    if (index >= instances_.size())\n    {\n      throw OrthancException(ErrorCode_ParameterOutOfRange);\n    }\n    else\n    {\n      return instances_[index]->GetFramesCount();\n    }\n  }\n\n\n  void SliceOrdering::Format(Json::Value& result) const\n  {\n    result = Json::objectValue;\n    result[\"Type\"] = (isVolume_ ? \"Volume\" : \"Sequence\");\n    \n    Json::Value tmp = Json::arrayValue;\n    for (size_t i = 0; i < GetInstancesCount(); i++)\n    {\n      tmp.append(GetBasePath(ResourceType_Instance, GetInstanceId(i)) + \"/file\");\n    }\n\n    result[\"Dicom\"] = tmp;\n\n    Json::Value slicesShort = Json::arrayValue;\n\n    tmp.clear();\n    for (size_t i = 0; i < GetInstancesCount(); i++)\n    {\n      std::string base = GetBasePath(ResourceType_Instance, GetInstanceId(i));\n      for (size_t j = 0; j < GetFramesCount(i); j++)\n      {\n        tmp.append(base + \"/frames/\" + boost::lexical_cast<std::string>(j));\n      }\n\n      Json::Value tmp2 = Json::arrayValue;\n      tmp2.append(GetInstanceId(i));\n      tmp2.append(0);\n      tmp2.append(GetFramesCount(i));\n      \n      slicesShort.append(tmp2);\n    }\n\n    result[\"Slices\"] = tmp;\n    result[\"SlicesShort\"] = slicesShort;\n  }\n}\n", "meta": {"hexsha": "177f04d5965df7610b42dd3845e36fdc213ed244", "size": 12621, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "DicomWebStorge/Orthanc-1.7.4/OrthancServer/Sources/SliceOrdering.cpp", "max_stars_repo_name": "a2609194449/Assistant-decision-making-system-for-gallbladder-cancer-", "max_stars_repo_head_hexsha": "75a9d3432cb510ea94fa09cc9b440e8b8e7f0a84", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "DicomWebStorge/Orthanc-1.7.4/OrthancServer/Sources/SliceOrdering.cpp", "max_issues_repo_name": "a2609194449/Assistant-decision-making-system-for-gallbladder-cancer-", "max_issues_repo_head_hexsha": "75a9d3432cb510ea94fa09cc9b440e8b8e7f0a84", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "DicomWebStorge/Orthanc-1.7.4/OrthancServer/Sources/SliceOrdering.cpp", "max_forks_repo_name": "a2609194449/Assistant-decision-making-system-for-gallbladder-cancer-", "max_forks_repo_head_hexsha": "75a9d3432cb510ea94fa09cc9b440e8b8e7f0a84", "max_forks_repo_licenses": ["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.548582996, "max_line_length": 105, "alphanum_fraction": 0.602487917, "num_tokens": 3158, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6224593171945416, "lm_q2_score": 0.49218813572079556, "lm_q1q2_score": 0.3063670908920208}}
{"text": "// It works if the --p2p option is given!??\n#include <iostream>\n#include <boost/program_options.hpp>\n#include <boost/math/distributions/normal.hpp>\n#include <boost/random.hpp>\n#include <boost/random/uniform_real.hpp>\n#include <boost/random/variate_generator.hpp>\n\n#include <ndt_registration/ndt_matcher_d2d.h>\n#include <ndt_registration/ndt_matcher_d2d_feature.h>\n#include <ndt_map/ndt_map.h>\n#include <ndt_map/cell_vector.h>\n#include <ndt_map/lazy_grid.h>\n#include <pointcloud_vrml/pointcloud_utils.h>\n\nusing namespace std;\nusing namespace perception_oru;\nnamespace po = boost::program_options;\n\nint main(int argc, char** argv)\n{\n    cout << \"--------------------------------------------------\" << endl;\n    cout << \"Small test program of CellVector + F2F matcher \" << endl;\n    cout << \"--------------------------------------------------\" << endl;\n\n    po::options_description desc(\"Allowed options\");\n    Eigen::Matrix<double,6,1> pose_increment_v;\n    string static_file_name, moving_file_name;\n    int nb_clusters, nb_points;\n    double std_dev, min, max;\n    desc.add_options()\n    (\"help\", \"produce help message\")\n    (\"x\", po::value<double>(&pose_increment_v(0))->default_value(1.), \"x pos gt offset\")\n    (\"y\", po::value<double>(&pose_increment_v(1))->default_value(1.), \"y pos gt offset\")\n    (\"z\", po::value<double>(&pose_increment_v(2))->default_value(1.), \"z pos gt offset\")\n    (\"X\", po::value<double>(&pose_increment_v(3))->default_value(0.1), \"x axis rot gt offset\")\n    (\"Y\", po::value<double>(&pose_increment_v(4))->default_value(0.1), \"y axis rot gt offset\")\n    (\"Z\", po::value<double>(&pose_increment_v(5))->default_value(0.1), \"z axis rot gt offset\")\n    (\"nb_clusters\", po::value<int>(&nb_clusters)->default_value(20), \"number of clusters\")\n    (\"nb_points\", po::value<int>(&nb_points)->default_value(10), \"number of points per clusters\")\n    (\"std_dev\", po::value<double>(&std_dev)->default_value(0.1), \"standard deviation of the points drawn from a normal distribution (here independent on the axes\")\n    (\"min\", po::value<double>(&min)->default_value(-10), \"minimum center point\")\n    (\"max\", po::value<double>(&max)->default_value(10), \"maximum center point\")\n    (\"lazzy\", \"use lazzygrid\")\n    (\"p2preg\", \"calculate NDTMatchF2F using two pointclouds\")\n    (\"irregular_grid\", \"use irregular grid in the p2p registration\")\n    (\"nfeaturecorr\", \"feature_f2f should NOT be evaluated (NDTMatcherFeatureF2F)\")\n    (\"singleres\", \"use single resolution in the 'p2p' matching\")\n    (\"nf2f\", \"if f2f should NOT be evaluated\")\n    (\"usegt\", \"if the ground truth should be used as initial estimate\")\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    {\n        cout << desc << \"\\n\";\n        return 1;\n    }\n    bool use_lazzy = vm.count(\"lazzy\");\n    bool use_p2preg = vm.count(\"p2preg\");\n    bool use_irregular_grid = vm.count(\"irregular_grid\");\n    bool use_featurecorr = !vm.count(\"nfeaturecorr\");\n    bool use_singleres = vm.count(\"singleres\");\n    bool use_f2f = !vm.count(\"nf2f\");\n    bool usegt = vm.count(\"usegt\");\n    pcl::PointCloud<pcl::PointXYZ> static_pc, moving_pc, tmp_pc;\n    Eigen::Transform<double,3,Eigen::Affine,Eigen::ColMajor> gt_transform;\n\n    // Generate the static point cloud + indices...\n    boost::mt19937 rng;\n    boost::uniform_real<> ud(min,max);\n    boost::normal_distribution<> nd(0.0, std_dev);\n    boost::variate_generator<boost::mt19937&, boost::normal_distribution<> > var_nor(rng, nd);\n    boost::variate_generator<boost::mt19937&, boost::uniform_real<> > var_uni(rng, ud);\n    std::vector<std::pair<int,int> > corresp;\n\n    size_t index = 0;\n    std::vector<std::vector<size_t> > all_indices;\n    for (int i = 0; i < nb_clusters; i++)\n    {\n        std::vector<size_t> indices;\n        double c_x = var_uni();\n        double c_y = var_uni();\n        double c_z = var_uni();\n        for (int j = 0; j < nb_points; j++)\n        {\n            static_pc.push_back(pcl::PointXYZ(c_x+var_nor(), c_y+var_nor(), c_z+var_nor()));\n            indices.push_back(index);\n            index++;\n        }\n        all_indices.push_back(indices);\n        corresp.push_back(std::pair<int,int>(i,nb_clusters-1-i)); // nb_clusters-1-i -> To check the da functions is working.\n    }\n    std::vector<std::vector<size_t> > all_indices_moving(all_indices.size());  // Reverse the correspondances (To check the da functions)\n    std::reverse_copy(all_indices.begin(), all_indices.end(), all_indices_moving.begin());\n\n    for (int i = 0; i < 1/*nb_clusters*/; i++)\n    {\n        tmp_pc.push_back(pcl::PointXYZ(i,i,i));\n    }\n\n    // Specify some offset...\n    gt_transform = Eigen::Translation<double,3>(pose_increment_v(0),pose_increment_v(1),pose_increment_v(2))*\n                   Eigen::AngleAxis<double>(pose_increment_v(3),Eigen::Vector3d::UnitX()) *\n                   Eigen::AngleAxis<double>(pose_increment_v(4),Eigen::Vector3d::UnitY()) *\n                   Eigen::AngleAxis<double>(pose_increment_v(5),Eigen::Vector3d::UnitZ()) ;\n\n\n    std::vector<double> resolutions;\n    if (use_singleres)\n        resolutions.push_back(1.);\n    NDTMatcherD2D<pcl::PointXYZ,pcl::PointXYZ> matcher(use_irregular_grid,!use_singleres,resolutions);\n    Eigen::Transform<double,3,Eigen::Affine,Eigen::ColMajor> T_f2f,T_p2p, T_feat;\n    T_f2f.setIdentity();\n    T_p2p.setIdentity();\n    T_feat.setIdentity();\n    if (usegt)\n    {\n        T_f2f = gt_transform;\n        T_p2p = gt_transform;\n        T_feat = gt_transform;\n    }\n\n    moving_pc = transformPointCloud(gt_transform, static_pc);\n\n    if (use_p2preg)\n    {\n        matcher.match(moving_pc, static_pc, T_p2p);\n    }\n    {\n        double current_resolution = 1;\n\n        SpatialIndex<pcl::PointXYZ>* index = NULL;\n        if (use_lazzy)\n        {\n            index = new LazyGrid<pcl::PointXYZ>(current_resolution);\n        }\n        else\n        {\n            index = new CellVector<pcl::PointXYZ>();\n        }\n\n        NDTMap<pcl::PointXYZ> ndt(index);\n        if (!use_lazzy)\n            ndt.loadPointCloud( static_pc, all_indices );\n        else\n            ndt.loadPointCloud (static_pc );\n        ndt.computeNDTCells();\n\n        NDTMap<pcl::PointXYZ> mov(index);\n        if (!use_lazzy)\n            mov.loadPointCloud( moving_pc, all_indices_moving );\n        else\n            mov.loadPointCloud( moving_pc );\n        mov.computeNDTCells();\n\n        if (use_f2f)\n        {\n            matcher.match( mov, ndt, T_f2f );\n        }\n        if (use_featurecorr)\n        {\n            NDTMatcherFeatureD2D<pcl::PointXYZ,pcl::PointXYZ> matcher_feat(corresp);\n            matcher_feat.match( mov, ndt, T_feat );\n        }\n        delete index;\n    }\n\n    std::cout<<\"GT translation \"<<gt_transform.translation().transpose()\n             <<\" (norm) \"<<gt_transform.translation().norm()<<std::endl;\n    std::cout<<\"GT rotation \"<<gt_transform.rotation().eulerAngles(0,1,2).transpose()\n             <<\" (norm) \"<<gt_transform.rotation().eulerAngles(0,1,2).norm()<<std::endl;\n\n    if (use_f2f)\n    {\n        std::cout<<\"f2f translation \"<<T_f2f.translation().transpose()\n                 <<\" (norm) \"<<T_f2f.translation().norm()<<std::endl;\n        std::cout<<\"f2f rotation \"<<T_f2f.rotation().eulerAngles(0,1,2).transpose()\n                 <<\" (norm) \"<<T_f2f.rotation().eulerAngles(0,1,2).norm()<<std::endl;\n    }\n\n    if (use_featurecorr)\n    {\n        std::cout<<\"feat translation \"<<T_feat.translation().transpose()\n                 <<\" (norm) \"<<T_feat.translation().norm()<<std::endl;\n        std::cout<<\"feat rotation \"<<T_feat.rotation().eulerAngles(0,1,2).transpose()\n                 <<\" (norm) \"<<T_feat.rotation().eulerAngles(0,1,2).norm()<<std::endl;\n    }\n\n    if (use_p2preg)\n    {\n        std::cout<<\"p2preg translation \"<<T_p2p.translation().transpose()\n                 <<\" (norm) \"<<T_p2p.translation().norm()<<std::endl;\n        std::cout<<\"p2preg rotation \"<<T_p2p.rotation().eulerAngles(0,1,2).transpose()\n                 <<\" (norm) \"<<T_p2p.rotation().eulerAngles(0,1,2).norm()<<std::endl;\n    }\n    cout << \"done.\" << endl;\n}\n", "meta": {"hexsha": "0a7a845dd7846e2c5820e784e68f3358ea351f56", "size": 8121, "ext": "cc", "lang": "C++", "max_stars_repo_path": "perception_oru-port-kinetic/ndt_registration/test/ndt_feature_test.cc", "max_stars_repo_name": "lllray/ndt-loam", "max_stars_repo_head_hexsha": "331867941e0764b40e1a980dd85d2174f861e9c8", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-11-14T08:21:13.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-14T08:21:13.000Z", "max_issues_repo_path": "perception_oru-port-kinetic/ndt_registration/test/ndt_feature_test.cc", "max_issues_repo_name": "lllray/ndt-loam", "max_issues_repo_head_hexsha": "331867941e0764b40e1a980dd85d2174f861e9c8", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-07-28T04:47:56.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-28T04:47:56.000Z", "max_forks_repo_path": "perception_oru-port-kinetic/ndt_registration/test/ndt_feature_test.cc", "max_forks_repo_name": "lllray/ndt-loam", "max_forks_repo_head_hexsha": "331867941e0764b40e1a980dd85d2174f861e9c8", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-12-18T11:25:53.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-19T12:59:59.000Z", "avg_line_length": 40.202970297, "max_line_length": 163, "alphanum_fraction": 0.6188892993, "num_tokens": 2157, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6224593171945416, "lm_q2_score": 0.4921881357207956, "lm_q1q2_score": 0.3063670908920208}}
{"text": "#include <boost/python.hpp>\n#include <lightspeed/tensor.hpp>\n\nusing namespace lightspeed;\nusing namespace boost::python;\n\n/**\n * Compute the UED or X-Ray elastic scattering intensity for a molecule,\n * averaging over a molecular orientation quadrature grid, and accounting for\n * anisotropy and/or modifications to the scattering intensity definition. Uses\n * the independent atom model.\n *\n * First, the scattering angles theta are computed according to the elastic\n * scattering formula,\n *\n * s = 4 pi / lambda * sin(theta / 2) => theta = 2 arcsin(s * lambda / (4 * pi))\n *\n * This will throw if s * lambda / (4 * pi) is outside [+1, -1]\n *\n * Next, the scattering vectors are computed according to,\n *\n * \\vec s = {sx, sy, sz} = s { cos(theta/2)sin(eta), sin(theta/2), cos(theta/2)cos(eta) }\n *  \n * Next the (isotropic) atomic scattering intensity is computed according to,\n *\n * D(s) = \\sum_{A} | f_A (s) |^2\n *\n * Next, the scattering intensity is computed for each point in the molecular\n * orientation quadrature { R, w_R }, and summed up, including the possible\n * anisotropy weighting factor a(R).\n *\n * I(s, eta) = \\sum_{R} w_{R} a(R) I_R (s, eta)\n *\n * Here the raw scattering intensity for a given molecular orientation is computed as,\n *\n * I_R (s, eta) = | \\sum_{A} exp(i \\vec s * (R^\\dagger r_{A})) |^2\n *\n * e.g., the diffraction pattern of the rotated molecular geometry. \n *\n * If the \"anisotropy\" option is set to true, the factor a(R) will be computed as\n * the square of the projection of the rotated z axis on the original z axis\n * (cos^2 zeta perpendicular one-photon pump-probe anisotropy)\n *\n * If the \"mod\" option is set to true, the modified scattering intensity will\n * replace the raw scattering intensity in the result:\n *\n * M_R (s, eta) = [I_R (s, eta) - D(s)] / D(s)\n *\n * @param lambda (double) - probe wavelength (e.g., deBroglie wavelength) [Angstrom].\n * @param ss (Tensor of shape (ns,)) - s values to collocate to [Angstrom^-1]\n * @param etas (Tensor of shape (neta,)) - eta values to collocate to [Radian]\n * @param xyzs (Tensor of shape (natom, 3)) - x, y, z centers of atoms [Anstrom]\n * @param fs (Tensor of shape (natom, ns)) - atomic form factors f_A (s)\n *  computed for the above atoms and s values. Specialization to UED or X-Ray\n *  can be made outside of the present code by computing these factors\n *  appropriately. E.g., f_A^UED (s) = 1 / s^2 (Z_A - f_A^XRAY (s)).\n * @param Rs (Tensor of shape (nrot, 3, 3)) - rotation matrices in the\n *  molecular orientation quadrature grid.\n * @param ws (Tensor of shape (nrot,)) - weights of rotation matrices in the\n *  molecular orientation quadrature grid.\n * @param anisotropy (bool) - a(R) will be computed as R_zz'^2 if true\n *  (perpendicular one-photon anisotropy), else a(R) will be set to 1 if false\n *  (parallel arrangement or isotropic pump-probe experiment).\n * @param mod (bool) - compute M(s,eta) if true, else compute I(s,eta) if false.\n *\n * @return I (Tensor of shape (ns, neta)) - molecular scattering intensity I(s, eta) \n *  or M(s, eta)\n **/\nlightspeed::shared_ptr<Tensor> compute_diffraction(\n    double lambda,\n    const lightspeed::shared_ptr<Tensor>& ss,\n    const lightspeed::shared_ptr<Tensor>& etas,\n    const lightspeed::shared_ptr<Tensor>& xyzs,\n    const lightspeed::shared_ptr<Tensor>& fs,\n    const lightspeed::shared_ptr<Tensor>& Rs,\n    const lightspeed::shared_ptr<Tensor>& ws,\n    bool anisotropy,\n    bool mod\n    )\n{\n    // Validity checks\n    ss->ndim_error(1);\n    etas->ndim_error(1);\n    xyzs->ndim_error(2);\n    xyzs->shape_error({xyzs->shape()[0], 3});\n    fs->shape_error({xyzs->shape()[0], ss->shape()[0]});\n    Rs->ndim_error(3);\n    Rs->shape_error({Rs->shape()[0], 3, 3});\n    ws->shape_error({Rs->shape()[0]});\n\n    // Sizes\n    size_t ns = ss->shape()[0];\n    size_t neta = etas->shape()[0];\n    size_t nA = xyzs->shape()[0];\n    size_t nR = Rs->shape()[0];\n\n    // Pointers\n    const double* sp = ss->data().data();\n    const double* etap = etas->data().data();\n    const double* xyzp = xyzs->data().data();\n    const double* fp = fs->data().data();\n    const double* Rp = Rs->data().data();\n    const double* wp = ws->data().data();\n\n    // Scattering vectors\n    lightspeed::shared_ptr<Tensor> sxyz(new Tensor({ns, neta, 3}));\n    double* sxyzp = sxyz->data().data();\n    for (size_t sind = 0; sind < ns; sind++) {\n        double arg = lambda * sp[sind] / (4.0 * M_PI);\n        if (arg > 1.0 or arg < -1.0) throw std::runtime_error(\"Invalid s:\" + std::to_string(sp[sind]));\n        double theta = 2.0 * asin(arg);\n        for (size_t eind = 0; eind < neta; eind++) {\n            sxyzp[3 * (sind * neta + eind) + 0] = sp[sind] * cos(theta / 2.0) * sin(etap[eind]);\n            sxyzp[3 * (sind * neta + eind) + 1] = sp[sind] * sin(theta / 2.0);\n            sxyzp[3 * (sind * neta + eind) + 2] = sp[sind] * cos(theta / 2.0) * cos(etap[eind]);\n        }\n    }\n\n    // Atomic scattering intensity\n    lightspeed::shared_ptr<Tensor> Ds(new Tensor({ns}));\n    double* Dp = Ds->data().data();\n    for (size_t sind = 0; sind < ns; sind++) {\n        for (size_t A = 0; A < nA; A++) {\n            Dp[sind] += pow(fp[A * ns + sind], 2);\n        }\n    }\n\n    // Target\n    lightspeed::shared_ptr<Tensor> Is(new Tensor({ns, neta}));\n    double* Ip = Is->data().data();\n\n    // #pragma omp parallel for schedule(static, 16)\n    #pragma omp parallel for schedule(static)\n    for (size_t P = 0; P < ns * neta; P++) {\n        size_t sind = P / neta;\n        size_t eind = P % neta;\n        double sx = sxyzp[3*P + 0];\n        double sy = sxyzp[3*P + 1];\n        double sz = sxyzp[3*P + 2];\n        double D = Dp[sind];\n        double I = 0.0;\n        for (size_t Rind = 0; Rind < Rs->shape()[0]; Rind++) {\n            // Rotation quadrature\n            const double* R2p = Rp + Rind * 9;\n            double w = wp[Rind];\n            // Anisotropy weight\n            if (anisotropy) {\n                w *= pow(R2p[8], 2);\n            }\n            // Diffraction cross section\n            double NR = 0.0;\n            double NI = 0.0;\n            for (size_t A = 0; A < xyzs->shape()[0]; A++) {\n                // Rotate coordinates to frame\n                double x = R2p[0] * xyzp[3*A + 0] + R2p[1] * xyzp[3*A + 1] + R2p[2] * xyzp[3*A + 2];\n                double y = R2p[3] * xyzp[3*A + 0] + R2p[4] * xyzp[3*A + 1] + R2p[5] * xyzp[3*A + 2];\n                double z = R2p[6] * xyzp[3*A + 0] + R2p[7] * xyzp[3*A + 1] + R2p[8] * xyzp[3*A + 2];\n                double theta = sx * x + sy * y + sz * z;\n                double fA = fp[A * ns + sind];\n                NR += fA * cos(theta);\n                NI += fA * sin(theta);\n            }\n            double F = NR * NR + NI * NI;\n            if (mod) {\n                F = (F - D) / D;\n            }\n            I += w * F;\n        }\n        Ip[P] = I;\n    }\n\n    return Is;\n}\n\nBOOST_PYTHON_MODULE(pyplugin)\n{\n    def(\"compute_diffraction\", compute_diffraction);\n}\n\n", "meta": {"hexsha": "5b240a686313c00648576f60d52341448045eaf2", "size": 6952, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "aimsprop/iam/ext/test.cpp", "max_stars_repo_name": "cbannwarth/aimsprop", "max_stars_repo_head_hexsha": "9efd317f9d1e8f66e33b7a468845d5ace3e1852d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-03-28T13:11:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T13:11:56.000Z", "max_issues_repo_path": "aimsprop/iam/ext/test.cpp", "max_issues_repo_name": "cbannwarth/aimsprop", "max_issues_repo_head_hexsha": "9efd317f9d1e8f66e33b7a468845d5ace3e1852d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 11.0, "max_issues_repo_issues_event_min_datetime": "2021-03-17T17:53:58.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-17T17:59:25.000Z", "max_forks_repo_path": "aimsprop/iam/ext/test.cpp", "max_forks_repo_name": "cbannwarth/aimsprop", "max_forks_repo_head_hexsha": "9efd317f9d1e8f66e33b7a468845d5ace3e1852d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-04-05T08:36:35.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-20T22:12:12.000Z", "avg_line_length": 38.6222222222, "max_line_length": 103, "alphanum_fraction": 0.581127733, "num_tokens": 2172, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7122321842389469, "lm_q2_score": 0.4301473485858429, "lm_q1q2_score": 0.30636478562788655}}
{"text": "/*\nID: septicmk\nLANG: C++\nTASK: Kmeans.cpp\n*/\n#include <boost/archive/text_oarchive.hpp>\n#include <boost/archive/text_iarchive.hpp>\n#include <boost/serialization/vector.hpp>\n#include <boost/serialization/queue.hpp>\n#include <boost/serialization/export.hpp> \n#include <boost/mpi.hpp>\n#include <algorithm>\n#include <vector>\n#include <queue>\n#include <cmath>\n#include <cstdio>\n#include <iostream>\n#include <sstream>\n#include <fstream>  \n#include <string>\n\n//namespace mpi = boost::mpi;\n\ninline int Random(int mod){\n    return static_cast<int> (static_cast<double>(rand())/ RAND_MAX * mod);\n}\n\ninline int Round(double r){  \n    return static_cast<int> ((r > 0.0) ? floor(r + 0.5) : ceil(r - 0.5));\n}  \n\n\nclass MLalgorithm{\n    private:\n        friend class boost::serialization::access;\n        template <typename Archive>\n        void serialize (Archive &ar, const unsigned int version){\n                ar &nrow;\n                ar &ncol;\n                ar &data;\n            }\n\n    public:\n        size_t nrow, ncol;\n        std::vector<double> data;\n\n        void Init(size_t nrow, size_t ncol){\n            this->nrow = nrow;\n            this->ncol = ncol;\n            data.resize(nrow * ncol);\n            std::fill(data.begin(), data.end(), 0.0f);\n        }\n\n        void add (std::vector<double> record, size_t i){\n            for (size_t j = 0; j < record.size(); ++j){\n                data[ i*ncol + j ] += record[j];\n            }\n        }\n\n        std::vector<double> get_value(size_t i){\n            std::vector<double> ret;\n            for (size_t j = 0; j < ncol; ++j){\n                ret.push_back(data[i*ncol + j]);\n            }\n            return ret;\n        }\n        \n        virtual MLalgorithm* operator + (MLalgorithm &rhs)=0;\n        virtual void beginDataScan(std::vector<double> records, size_t feat_dim) = 0;\n        virtual MLalgorithm* processRecord (std::vector<double> records, size_t feat_dim)=0;\n        virtual void endDataScan()=0;\n        virtual bool isConverged(MLalgorithm* rhs, size_t feat_dim, double eps)=0;\n        virtual void finish(std::vector<double> records, size_t feat_dim)=0;\n};\n\nclass Kmeans:public MLalgorithm{\n    private:\n        friend class boost::serialization::access;\n        template <typename Archive>\n        void serialize (Archive &ar, const unsigned int version){\n            ar & boost::serialization::base_object<MLalgorithm>(*this);\n        }\n\n    public:\n        MLalgorithm* operator +(MLalgorithm &rhs){\n            MLalgorithm *pret = new Kmeans();\n            pret->Init(this->nrow, this->ncol);\n            for(size_t i = 0; i< data.size() ; ++i)\n                pret->data[i] = data[i] + rhs.data[i];\n            return pret;\n        }\n\n        void beginDataScan(std::vector<double> records, size_t feat_dim){\n            std::priority_queue<int> q;\n            std::vector<int> weight;\n            size_t n_records = records.size();\n            size_t n_cluster = this->nrow;\n            for (size_t i = 0; i < n_records; ++ i){\n                int x = Random(10007);\n                weight.push_back(x);\n                if (q.size() < n_cluster){\n                    q.push(i);\n                }else if (x < weight[q.top()]){\n                    q.pop();\n                    q.push(i);\n                }\n            }\n            while(!q.empty()){\n                std::vector<double> record;\n                record.clear();\n                size_t i = q.top();\n                for(size_t j = 0; j < feat_dim ; ++j){\n                    record.push_back(records[i*feat_dim+j]);\n                }\n                add(record, n_cluster - q.size());\n                q.pop();\n            }\n        }\n\n        void endDataScan(){\n            for(size_t i = 0; i < nrow; ++i){\n                for(size_t j = 0; j < ncol; ++j){\n                    data[i*ncol+j] /= data[i*ncol + ncol-1];\n                }\n                data[i*ncol + ncol-1] = 1;\n            } \n\n            //for(size_t i = 0; i < nrow; ++i){\n                //for(size_t j = 0; j < ncol; ++j){\n                    //std::cout << data[i*ncol+j] << \" \";\n                //}\n                //std::puts(\"\");\n            //}\n        }\n\n        MLalgorithm* processRecord(std::vector<double> records, size_t feat_dim){\n            MLalgorithm* pret = new Kmeans();\n            pret->Init(this->nrow, this->ncol);\n            size_t n_records = records.size()/feat_dim;\n            for (size_t i = 0 ; i < n_records ; i++){\n                std::vector<double> record;\n                record.clear();\n                for(size_t j = 0; j < feat_dim ; j ++){\n                    record.push_back(records[i*feat_dim+j]);\n                }\n                double dis = (1L<<16)-1;\n                int who = -1;\n                //std::cout<<\"bp\"<<std::endl;\n                for(size_t k = 0; k < this->nrow; k++){\n                    std::vector<double> centroid = this->get_value(k);\n                    double tmp = 0;\n                    for (size_t u = 0; u < record.size(); ++u){\n                        tmp += (centroid[u] - record[u])*(centroid[u] - record[u]);\n                    }\n\n                    if (tmp < dis){\n                        who = k;\n                        dis = tmp;\n                    }\n                }\n                record.push_back(1);\n                pret->add(record, who);\n            }\n            return pret;\n        }\n\n        bool isConverged(MLalgorithm* rhs, size_t feat_dim, double eps){\n            double diff = 0;\n            for(size_t i = 0; i < nrow; i ++){\n                double tmp = 0;\n                for(size_t j = 0;  j < feat_dim; j++){\n                    tmp += (data[i*ncol+j] - rhs->data[i*ncol+j]) * (data[i*ncol+j] - rhs->data[i*ncol+j]);\n                }\n                tmp = sqrt(tmp);\n                diff += tmp;\n            }\n            if (diff <= eps) return true;\n            else return false;\n\n        }\n\n        void finish(std::vector<double> records, size_t feat_dim){\n            std::ofstream file;\n            file.open(\"./ans.txt\");\t\n            std::vector<float> record;\n            size_t n_records = records.size()/feat_dim;\n            for(size_t i = 0; i < n_records; ++i){\n                std::vector<double> record;\n                record.clear();\n                for(size_t j = 0; j < feat_dim; ++ j){\n                    record.push_back(records[i*feat_dim+j]);\n                }\n                double dis = (1<<16)-1;\n                int who = -1;\n                for(size_t k = 0; k < this->nrow; k++){\n                    std::vector<double> centroid = this->get_value(k);\n                    double tmp = 0;\n                    for (size_t u = 0; u < record.size(); ++u){\n                        tmp += (centroid[u] - record[u])*(centroid[u] - record[u]);\n                    }\n\n                    if (tmp < dis){\n                        who = k;\n                        dis = tmp;\n                    }\n                }\n                file << who << std::endl;\n\n            }\n\n        }\n};\nBOOST_CLASS_EXPORT(Kmeans)\n\n\nclass Core{\n    public:\n     \n        std::string Trim (std::string &str){\n            str.erase(0,str.find_first_not_of(\" \\t\\r\\n\"));\n            str.erase(str.find_last_not_of(\" \\t\\r\\n\") + 1);\n            return str;\n        }\n\n        inline std::vector<std::string> ReadCSV(std::string pwd){\n            std::ifstream fin(pwd.c_str());\n            std::string e,line;\n            std::vector<std::string> data;\n            while (std::getline(fin, line)){\n                std::stringstream  lineStream(line);\n                while(std::getline(lineStream, e,',')){\n                    data.push_back(e);\n                }\n            }\n            return data;\n        }\n\n        inline double praser(std::vector<std::string> data, int feat_dim, size_t i, size_t j){\n            return atof(data[i*feat_dim+j].c_str());\n        }\n\n        inline std::vector<double> partition(std::vector<std::string> origin, size_t number, size_t loc, size_t feat_dim){\n            std::vector<double> ret;\n            ret.clear();\n            size_t n_records = origin.size()/feat_dim;\n            int members = n_records/number;\n            size_t lim = std::min(loc*members+members, n_records);\n            for (size_t i = loc*members; i < lim ; i++){\n                for(size_t j = 0 ; j < feat_dim; j ++){\n                    ret.push_back(praser(origin, feat_dim, i, j));\n                }\n            }\n            return ret;\n        }\n\n        MLalgorithm* mainLoop(int argc, char* argv[], \n                MLalgorithm *ptr,\n                double eps,\n                size_t feat_dim){\n            std::vector<std::string> data = ReadCSV(\"../data/iris_n.csv\");\n            ptr->beginDataScan(partition(data,1,0,feat_dim), feat_dim);\n            boost::mpi::environment env(argc, argv);\n            boost::mpi::communicator world;\n            int rank = world.rank();\n            size_t number = world.size();\n            size_t n_records = data.size()/ feat_dim;\n            size_t iter_num = 0;\n            std::vector<double> records = partition(data, number, rank, feat_dim);\n            if (rank == 0) std::cout << \"[processor] \"<< world.size() << std::endl;\n\n            bool done = 0;\n            while(!done){\n                boost::mpi::broadcast(world, ptr, 0);\n                MLalgorithm* local_update = ptr->processRecord(records, feat_dim);\n                \n                world.barrier();\n                //if(rank ==0 ) std::cout<<\"flag\"<<std::endl;\n                if(rank == 0){\n                    std::cout << \"[iteration] \" << iter_num++ << std::endl;\n                    MLalgorithm* ptmp;\n                    MLalgorithm* global_updata = local_update;\n                    for(size_t i = 1; i < world.size(); ++i){\n                        world.recv(boost::mpi::any_source, i, ptmp);\n                        global_updata = *global_updata + *ptmp;\n                    }\n                    MLalgorithm *pafter = *ptr + *global_updata;\n                    pafter->endDataScan();\n                    done = pafter->isConverged(ptr, feat_dim, eps);\n                    ptr = pafter;\n                }else{\n                    world.send(0, rank, local_update);\n                }\n                boost::mpi::broadcast(world, done, 0);\n            }\n            if(rank == 0){\n                std::cout << \"done\" << std::endl;\n                std::vector<double> records;\n                for(size_t i = 0; i < data.size(); ++i){\n                    records.push_back(atof(data[i].c_str()));\n                }\n                ptr->finish(records, feat_dim);\n            }\n        }\n};\n\nint main(int argc,char *argv[]){\n    Core *p = new Core();\n    MLalgorithm *ptr = new Kmeans();\n    ptr->Init(3,5);\n\n    p->mainLoop(argc, argv, ptr, 1e-7, 4);\n    return 0;\n}\n", "meta": {"hexsha": "a19cb275571b825bb8ea5f335ba4d0381e34a2d7", "size": 10833, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "back/core.cpp", "max_stars_repo_name": "NCIC-PARALLEL/Graphine-LIB", "max_stars_repo_head_hexsha": "c241cc4fd9071b82c97d5f46cdc5af348e7e54c2", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 207.0, "max_stars_repo_stars_event_min_datetime": "2021-07-22T09:45:59.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-26T07:59:24.000Z", "max_issues_repo_path": "back/core.cpp", "max_issues_repo_name": "PAA-NCIC/HPML", "max_issues_repo_head_hexsha": "c241cc4fd9071b82c97d5f46cdc5af348e7e54c2", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "back/core.cpp", "max_forks_repo_name": "PAA-NCIC/HPML", "max_forks_repo_head_hexsha": "c241cc4fd9071b82c97d5f46cdc5af348e7e54c2", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 37.0, "max_forks_repo_forks_event_min_datetime": "2021-07-22T09:46:06.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-25T10:21:37.000Z", "avg_line_length": 34.5, "max_line_length": 122, "alphanum_fraction": 0.461183421, "num_tokens": 2525, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7185943925708561, "lm_q2_score": 0.42632159254749036, "lm_q1q2_score": 0.30635230583650386}}
{"text": "/**\n *****************************************************************************\n * @author     This file is part of libsnark, developed by SCIPR Lab\n *             and contributors (see AUTHORS).\n * @copyright  MIT license (see LICENSE file)\n *****************************************************************************/\n#include <fstream>\n#include <iostream>\n#ifndef MINDEPS\n#include <boost/program_options.hpp>\n#endif\n\n#include <libsnark/common/default_types/ram_ppzksnark_pp.hpp>\n#include <libsnark/relations/ram_computations/rams/tinyram/tinyram_params.hpp>\n#include <libsnark/zk_proof_systems/ppzksnark/ram_ppzksnark/ram_ppzksnark.hpp>\n\n#ifndef MINDEPS\nnamespace po = boost::program_options;\n\nbool process_generator_command_line(\n    const int argc,\n    const char **argv,\n    std::string &architecture_params_fn,\n    std::string &computation_bounds_fn,\n    std::string &proving_key_fn,\n    std::string &verification_key_fn)\n{\n    try {\n        po::options_description desc(\"Usage\");\n        desc.add_options()(\"help\", \"print this help message\")(\n            \"architecture_params\",\n            po::value<std::string>(&architecture_params_fn)->required())(\n            \"computation_bounds\",\n            po::value<std::string>(&computation_bounds_fn)->required())(\n            \"proving_key\", po::value<std::string>(&proving_key_fn)->required())(\n            \"verification_key\",\n            po::value<std::string>(&verification_key_fn)->required());\n\n        po::variables_map vm;\n        po::store(po::parse_command_line(argc, argv, desc), vm);\n\n        if (vm.count(\"help\")) {\n            std::cout << desc << \"\\n\";\n            return false;\n        }\n\n        po::notify(vm);\n    } catch (std::exception &e) {\n        std::cerr << \"Error: \" << e.what() << \"\\n\";\n        return false;\n    }\n\n    return true;\n}\n#endif\n\nusing namespace libsnark;\n\nint main(int argc, const char *argv[])\n{\n    ram_ppzksnark_snark_pp<default_ram_ppzksnark_pp>::init_public_params();\n#ifdef MINDEPS\n    std::string architecture_params_fn = \"architecture_params.txt\";\n    std::string computation_bounds_fn = \"computation_bounds.txt\";\n    std::string proving_key_fn = \"proving_key.txt\";\n    std::string verification_key_fn = \"verification_key.txt\";\n#else\n    std::string architecture_params_fn;\n    std::string computation_bounds_fn;\n    std::string proving_key_fn;\n    std::string verification_key_fn;\n\n    if (!process_generator_command_line(\n            argc,\n            argv,\n            architecture_params_fn,\n            computation_bounds_fn,\n            proving_key_fn,\n            verification_key_fn)) {\n        return 1;\n    }\n#endif\n    libff::start_profiling();\n\n    /* load everything */\n    ram_ppzksnark_architecture_params<default_ram_ppzksnark_pp> ap;\n    std::ifstream f_ap(architecture_params_fn);\n    f_ap >> ap;\n\n    std::ifstream f_rp(computation_bounds_fn);\n    size_t tinyram_input_size_bound, tinyram_program_size_bound, time_bound;\n    f_rp >> tinyram_input_size_bound >> tinyram_program_size_bound >>\n        time_bound;\n\n    const size_t boot_trace_size_bound =\n        tinyram_program_size_bound + tinyram_input_size_bound;\n\n    const ram_ppzksnark_keypair<default_ram_ppzksnark_pp> keypair =\n        ram_ppzksnark_generator<default_ram_ppzksnark_pp>(\n            ap, boot_trace_size_bound, time_bound);\n\n    std::ofstream pk(proving_key_fn);\n    pk << keypair.pk;\n    pk.close();\n\n    std::ofstream vk(verification_key_fn);\n    vk << keypair.vk;\n    vk.close();\n}\n", "meta": {"hexsha": "4fcd25d812fd406efb988b712c05bc5d8d8882c7", "size": 3482, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libsnark/zk_proof_systems/ppzksnark/ram_ppzksnark/examples/demo_ram_ppzksnark_generator.cpp", "max_stars_repo_name": "clearmatics/libsnark", "max_stars_repo_head_hexsha": "1e8e22d3b60f2baeea23cf87a510bda20f2610d4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "libsnark/zk_proof_systems/ppzksnark/ram_ppzksnark/examples/demo_ram_ppzksnark_generator.cpp", "max_issues_repo_name": "clearmatics/libsnark", "max_issues_repo_head_hexsha": "1e8e22d3b60f2baeea23cf87a510bda20f2610d4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 18.0, "max_issues_repo_issues_event_min_datetime": "2019-04-15T10:46:09.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-23T15:40:31.000Z", "max_forks_repo_path": "libsnark/zk_proof_systems/ppzksnark/ram_ppzksnark/examples/demo_ram_ppzksnark_generator.cpp", "max_forks_repo_name": "clearmatics/libsnark", "max_forks_repo_head_hexsha": "1e8e22d3b60f2baeea23cf87a510bda20f2610d4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-08-09T11:18:02.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-09T11:18:02.000Z", "avg_line_length": 31.6545454545, "max_line_length": 80, "alphanum_fraction": 0.6421596783, "num_tokens": 808, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7185943925708561, "lm_q2_score": 0.42632159254749036, "lm_q1q2_score": 0.30635230583650386}}
{"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 <Eigen/LU>\n#include <math.h>\n#include \"MeasurementModel.hpp\"\n\n/******** Implementation of 2d measurement Model (Range and Bearing) **********/\n\nRangeBearingModel::RangeBearingModel(){\n\n  config.probabilityOfDetection_ = 0.95;\n  config.uniformClutterIntensity_ = 0.1;\n  config.rangeLimMax_ = 5;\n  config.rangeLimMin_ = 0.3;\n  config.rangeLimBuffer_ = 0.25;\n}\n\n\nRangeBearingModel::RangeBearingModel(Eigen::Matrix2d &covZ){\n\n  setNoise(covZ);\n  config.probabilityOfDetection_ = 0.95;\n  config.uniformClutterIntensity_ = 0.1;\n  config.rangeLimMax_ = 5;\n  config.rangeLimMin_ = 0.3;\n  config.rangeLimBuffer_ = 0.25;\n}\n\nRangeBearingModel::RangeBearingModel(double Sr, double Sb){\n\n  Eigen::Matrix2d covZ;\n  covZ <<  Sr, 0, 0, Sb;\n  setNoise(covZ);\n  config.probabilityOfDetection_ = 0.95;\n  config.uniformClutterIntensity_ = 0.1;\n  config.rangeLimMax_ = 5;\n  config.rangeLimMin_ = 0.3;\n  config.rangeLimBuffer_ = 0.25;\n}\n\nRangeBearingModel::~RangeBearingModel(){}\n\nbool RangeBearingModel::measure(Pose2d  &pose, Landmark2d &landmark, \n\t\t\t\tMeasurement2d &measurement, \n\t\t\t\tEigen::Matrix2d *jacobian){\n\n  Eigen::Vector3d robotPose;\n  Eigen::Vector2d mean, landmarkState;\n  Eigen::Matrix2d H, landmarkUncertainty, cov;\n  double range, bearing;\n\n  pose.get(robotPose);\n  landmark.get(landmarkState,landmarkUncertainty);\n\n  range = sqrt(  pow(landmarkState(0) - robotPose(0), 2)\n\t\t+pow(landmarkState(1) - robotPose(1), 2) );\n\n  bearing = atan2( landmarkState(1) - robotPose(1) , landmarkState(0) - robotPose(0) ) - robotPose(2);\n\n  while(bearing>PI) bearing-=2*PI;\n  while(bearing<-PI) bearing+=2*PI;\n\n  mean << range, bearing ;\n\n  H <<  (landmarkState(0)-robotPose(0))/mean(0)          , (landmarkState(1)-robotPose(1))/mean(0) ,\n        -(landmarkState(1)-robotPose(1))/(pow(mean(0),2)), (landmarkState(0)-robotPose(0))/pow(mean(0),2) ;\n  \n  cov = H * landmarkUncertainty * H.transpose() + R_;\n  measurement.set(mean, cov);\n  \n  if(jacobian != NULL)\n    *jacobian = H;\n\n  if(range > config.rangeLimMax_ || range < config.rangeLimMin_)\n    return false;\n  else\n    return true;\n}\n\nvoid RangeBearingModel::inverseMeasure(Pose2d &pose, Measurement2d &measurement, \n\t\t\t\t       Landmark2d &landmark){\n  Eigen::Vector3d poseState;\n  Eigen::Vector2d measurementState, mean;\n  Eigen::Matrix2d measurementUncertainty, covariance, Hinv;\n  double t;\n \n  pose.get(poseState);\n  measurement.get(measurementState, t);\n  this->getNoise(measurementUncertainty); \n  mean << poseState(0) + measurementState(0) *cos( poseState(2) + measurementState(1) ),\n          poseState(1) + measurementState(0) *sin( poseState(2) + measurementState(1) );\n\n  Hinv << cos(poseState(2)+measurementState(1)) , -measurementState(0)*sin(poseState(2)+measurementState(1)) ,\n          sin(poseState(2)+measurementState(1)) , measurementState(0)*cos(poseState(2)+measurementState(1));\n\n  covariance = Hinv * measurementUncertainty *Hinv.transpose();\n  landmark.set( mean, covariance );\n\n}\n\ndouble RangeBearingModel::probabilityOfDetection( Pose2d &pose,\n\t\t\t\t\t\t  Landmark2d &landmark,\n\t\t\t\t\t\t  bool &isCloseToSensingLimit ){\n\n  Pose2d::Vec robotPose;\n  Landmark2d::Vec landmarkState;\n  double range, Pd;\n  \n  isCloseToSensingLimit = false;\n\n  pose.get(robotPose);\n  landmark.get(landmarkState);\n\n  range = sqrt(  pow(landmarkState(0) - robotPose(0), 2)\n\t\t+pow(landmarkState(1) - robotPose(1), 2) );\n\n  if( range <= config.rangeLimMax_ && range >= config.rangeLimMin_){\n    Pd = config.probabilityOfDetection_;\n    if( range >= (config.rangeLimMax_ - config.rangeLimBuffer_ ) ||\n\trange <= (config.rangeLimMin_ + config.rangeLimBuffer_ ) )\n      isCloseToSensingLimit = true;\n  }else{\n    Pd = 0;\n    if( range <= (config.rangeLimMax_ + config.rangeLimBuffer_ ) || \n\trange >= (config.rangeLimMin_ - config.rangeLimBuffer_ ) )\n      isCloseToSensingLimit = true;\n  } \n\n  return Pd;\n}\n\ndouble RangeBearingModel::clutterIntensity( Measurement2d &z,\n\t\t\t\t\t    int nZ){\n  return config.uniformClutterIntensity_;\n}\n\n\ndouble RangeBearingModel::clutterIntensityIntegral( int nZ ){\n  double sensingArea_ = 2 * PI * (config.rangeLimMax_ - config.rangeLimMin_);\n  return ( config.uniformClutterIntensity_ * sensingArea_ );\n}\n\n/************* Implementation of 1d measurement model **************************/\n\nMeasurementModel1d::MeasurementModel1d(){\n\n  config.probabilityOfDetection_ = 0.95;\n  config.uniformClutterIntensity_ = 0.1;\n  config.rangeLimMax_ = 5;\n  config.rangeLimMin_ = 0.3;\n  config.rangeLimBuffer_ = 0.25;\n}\n\nMeasurementModel1d::MeasurementModel1d(Eigen::Matrix<double, 1, 1> &Sr){\n  setNoise(Sr);\n  config.probabilityOfDetection_ = 0.95;\n  config.uniformClutterIntensity_ = 0.1;\n  config.rangeLimMax_ = 5;\n  config.rangeLimMin_ = 0.3;\n  config.rangeLimBuffer_ = 0.25;\n}\n\nMeasurementModel1d::MeasurementModel1d(double Sr){\n  Measurement1d::Mat S;\n  S << Sr;\n  setNoise(S);\n  config.probabilityOfDetection_ = 0.95;\n  config.uniformClutterIntensity_ = 0.1;\n  config.rangeLimMax_ = 5;\n  config.rangeLimMin_ = 0.3;\n  config.rangeLimBuffer_ = 0.25;\n}\n\nMeasurementModel1d::~MeasurementModel1d(){}\n\nbool MeasurementModel1d::measure(Pose1d &pose, Landmark1d &landmark, \n\t\t\t\t Measurement1d &measurement, \n\t\t\t\t Eigen::Matrix<double, 1, 1> *jacobian){\n\n  Pose1d::Vec robotPos;\n  Landmark1d::Vec lmkPos;\n  Landmark1d::Mat lmkPosUncertainty;\n  Measurement1d::Vec z;\n  Eigen::Matrix<double, 1, 1> H;\n  Eigen::Matrix<double, 1, 1> var;\n\n  pose.get(robotPos);\n  landmark.get(lmkPos, lmkPosUncertainty);\n  z = lmkPos - robotPos;\n  H << 1;\n  var = H * lmkPosUncertainty * H.transpose() + R_;\n\n  measurement.set(z, var);\n\n  if(jacobian != NULL)\n    *jacobian = H;\n\n  if(fabs(z(0)) > config.rangeLimMax_ || fabs(z(0)) < config.rangeLimMin_)\n    return false;\n  else\n    return true;\n\n}\n\nvoid MeasurementModel1d::inverseMeasure(Pose1d &pose, Measurement1d &measurement, \n\t\t\t\t\tLandmark1d &landmark){\n\n  Pose1d::Vec x;\n  Measurement1d::Vec z;\n  Landmark1d::Vec m;\n \n  pose.get(x);\n  measurement.get(z);\n  landmark.get(m);\n\n  m = x + z;\n  landmark.set( m, R_ );\n\n}\n\ndouble MeasurementModel1d::probabilityOfDetection( Pose1d &pose,\n\t\t\t\t\t\t   Landmark1d &landmark,\n\t\t\t\t\t\t   bool &isCloseToSensingLimit ){\n\n  Pose1d::Vec robotPose;\n  Landmark1d::Vec landmarkState;\n  double range, Pd;\n  \n  isCloseToSensingLimit = false;\n\n  pose.get(robotPose);\n  landmark.get(landmarkState);\n  range = fabs( landmarkState(0) - robotPose(0) );\n\n  if( range <= config.rangeLimMax_ && range >= config.rangeLimMin_){\n    Pd = config.probabilityOfDetection_;\n  }else{\n    Pd = 0;\n  } \n\n  if( ( range >= (config.rangeLimMax_ - config.rangeLimBuffer_ ) &&\n\trange <= (config.rangeLimMax_ + config.rangeLimBuffer_ ) ) ||\n      ( range >= (config.rangeLimMin_ - config.rangeLimBuffer_ ) &&\n\trange <= (config.rangeLimMin_ + config.rangeLimBuffer_ ) ) )\n    isCloseToSensingLimit = true;\n\n  return Pd;\n}\n\ndouble MeasurementModel1d::clutterIntensity( Measurement1d &z,\n\t\t\t\t\t     int nZ){\n  return config.uniformClutterIntensity_;\n}\n\n\ndouble MeasurementModel1d::clutterIntensityIntegral( int nZ ){\n  double sensingLength = config.rangeLimMax_ - config.rangeLimMin_;\n  return ( config.uniformClutterIntensity_ * sensingLength );\n}\n", "meta": {"hexsha": "5524d5b50f2db1c2a4165ce5ab70b6548ccaa16c", "size": 8889, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/MeasurementModel.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/MeasurementModel.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/MeasurementModel.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": 30.8645833333, "max_line_length": 110, "alphanum_fraction": 0.7096411295, "num_tokens": 2524, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6757646140788307, "lm_q2_score": 0.4532618480153862, "lm_q1q2_score": 0.3062983178007751}}
{"text": "#include <sstream>\n#include \"Ligero.hpp\"\n#include \"Math.hpp\"\n#include <boost/multiprecision/miller_rabin.hpp>\n#include \"LatticeEncryption.hpp\"\n#include \"Factoring.hpp\"\n#include \"Common.hpp\"\n\n#include <boost/filesystem.hpp>\n#include <boost/filesystem/fstream.hpp>\n\n#include <boost/archive/binary_iarchive.hpp>\n\n\nusing namespace ligero;\n\nstd::vector<mpz_class> alphasPS, alphasCAN, alphasGCD;\nstd::vector<size_t> bucketSizePS, bucketSizeCAN, bucketSizeGCD;\n\n\nconstexpr auto degree = 1 << 16;\nconstexpr auto p = 9;\nconstexpr auto q = 21;\nconstexpr auto sigma = 8;\nconstexpr auto lambda = 128;\nconstexpr auto tau_limit_bit = 175;\nconstexpr auto tau = 1000;\nconstexpr auto numCandidates = 2048;\nconstexpr auto pbs = 1000;\n\nusing Q = nfl::poly_p<uint64_t, degree, q>;\n\nstatic boost::filesystem::ifstream ifs(\"script.data\", std::ios::in | std::ios::binary);\nstatic boost::archive::binary_iarchive ia(ifs, boost::archive::no_header);\n\nstatic int numParties;\nstatic int currentStep = 1;\nstatic size_t minRowSize = -1;\n\nstd::vector<std::vector<mpz_class>> pruneAndReorderEIT (\n        const std::vector<mpz_class>& eit,\n        const std::vector<int>& flags,\n        int numAlphas) {\n\n    assert (eit.size() == flags.size());\n\n    // Now we can construct a result matrix\n    std::vector<std::vector<mpz_class>> result;\n\n    // And finally we fill the result matrix compactly with valid shares from `as`\n    int k = 0;\n    size_t min_size = 0;\n    for (size_t c = 0; c < numAlphas; ++c) {\n\n        std::vector<mpz_class> col;\n        for (int r = 0; r < bucketSizePS[c]; ++r) {\n            if (flags[k] == 1) {\n                col.push_back(eit[k]);\n            }\n            k++;\n        }\n        result.push_back(col);\n        if (min_size == 0) { min_size = col.size(); }\n        if (min_size > col.size()) { min_size = col.size(); }\n    }\n\n    std::vector<mpz_class> col(bucketSizePS[0], mpz_class(1));\n    result.insert(result.begin(), col);\n\n    minRowSize = min_size;\n    // resize and transpose\n    std::vector<std::vector<mpz_class>> transposed(min_size);\n\n    for (size_t i = 0; i < result.size(); ++i) {\n        for (size_t j = 0; j < min_size; ++j) {\n            transposed[j].push_back(result[i][j]);\n        }\n    }\n\n    return transposed;\n}\n\nstd::tuple<std::vector<mpz_class>, std::vector<int>, std::vector<mpz_class>> computeEITAndFlags(std::array<mpz_t, degree> c_mpz_t) {\n\n    std::vector<mpz_class> eit(primesPS);\n\n    int pq_size = bucketSizePS[0];\n    std::vector<int> flags(primesPS);\n    assert(eit.size() == flags.size());\n    std::vector<mpz_class> c(c_mpz_t.size());\n\n    for (size_t i = 0; i < c.size(); ++i) {\n        c[i] = mpz_class(c_mpz_t[i]);\n    }\n\n\n    mpz_t one;\n    mpz_init(one);\n    mpz_set_ui(one, 1);\n\n    mpz_t gcdResult;\n    mpz_init(gcdResult);\n\n\n    //assert(eit.size() == alphas.size() * bucketSize);\n    int k = 0;\n    for (int j = 0; j < alphasPS.size(); ++j) {\n\n        int ick = 0;\n        int sum = 0;\n        for (int i = 0; i < bucketSizePS[j]; ++i) {\n\n            mpz_gcd(gcdResult, alphasPS[j].get_mpz_t(), c_mpz_t[k]);\n            eit[k] = c[k];\n\n            flags[k] = mpz_cmp(gcdResult, one) == 0;\n            sum += flags[k];\n            /*\n            if (flags[k] == 1) {\n                index_candidates[k] = ick++;\n            } else {\n                index_candidates[k] = -1;\n            }\n            */\n\n            k++;\n        }\n\n        if (sum < pq_size) {\n            pq_size = sum;\n        }\n    }\n\n    // free mem\n    mpz_clear(one);\n    mpz_clear(gcdResult);\n    std::for_each(c_mpz_t.begin(), c_mpz_t.end(), mpz_clear);\n\n    return {eit, flags, c};\n}\n\n\ntemplate <typename T>\nT validate(MessageType expectedMessageType, std::function<T(T, T)> op, T origAccumulator) {\n    T computedAccumulator = origAccumulator;\n    //try {\n    if (ifs.is_open()) {\n        // Now read and validate each round\n        MessageType t;\n        ia >> t;\n\n        int msgId = int(t);\n        //std::cout << \"t: \" << msgId << std::endl;\n        if (msgId > 0) msgId = 1 + msgId - int(MessageType::ID_PARTY);\n        std::cout << currentStep++ << \". \" << msgs[msgId] << std::endl;\n\n        if (t != expectedMessageType) {\n            std::cout << \"Unexpected MessageType. Expected message type: \" << msgs[1 + int(expectedMessageType) - int(MessageType::ID_PARTY)]; \n            if (1 + int(t) - int(MessageType::ID_PARTY) < msgs.size()) {\n                std::cout << \"Got MessageType \" << msgs[1 + int(t) - int(MessageType::ID_PARTY)];\n            } else {\n                std::cout << \"Got MessageType\" << 1 + int(t) - int(MessageType::ID_PARTY);\n            }\n            assert(false);\n        }\n        bool initialized = false;\n        for (size_t i = 0; i < numParties; ++i) {\n            std::cout << \"i = \" << i << std::endl;\n            if (ifs && ifs.peek() != EOF) {\n                std::pair<MessageType, T> zzz;\n                ia >> zzz;\n                auto [ti, x] = zzz;\n                MessageType xt = MessageType(ti);\n                if (xt != t) {\n                    std::cout << \"Unexpected MessageType\" << std::endl;\n                    std::cout << \"Expected: \" << \">>\" << int(t) << \"<<\" << \" -- \"  << msgs[1 + int(t) - int(MessageType::ID_PARTY)];\n                    std::cout << \"Got: \" << \">>\" << int(xt) << \"<<\" << \" -- \"  << msgs[1 + int(xt) - int(MessageType::ID_PARTY)];\n                    assert(false);\n                }\n\n\n                if (!initialized) {\n                    initialized = true;\n                    computedAccumulator = x;\n                } else {\n                    computedAccumulator = op(computedAccumulator, x);\n                }\n            } else {\n                LOG(FATAL) << \"Something went wrong, not enough data to read...\";\n            }\n        }\n        if (computedAccumulator == origAccumulator) {\n            LOG(FATAL) << \"Computed accumulator did not change, aborting...\";\n        }\n\n        std::pair<MessageType, T> ea;\n        ia >> ea;\n        auto [at, expectedAccumulator] = ea;\n\n        if (at != expectedMessageType || expectedAccumulator != computedAccumulator) {\n            LOG(FATAL) << \"Accumulated result did NOT match expected value\";\n        }\n    } else {\n        std::cout << \"file is not good\" << std::endl;\n    }\n    return computedAccumulator;\n}\n\n\nint main(int argc, char** argv)\n{\n    \n    //try {\n    if (ifs.is_open()) {\n\n        // Read the number of parties\n        ia >> numParties;\n        std::cout << \"numParties: \" << numParties << std::endl;\n\n        std::vector<mpz_class> candidatesCAN, candidatesPostSieve, candidatesJacobi;\n\n        ProtocolConfig<uint64_t> config = ProtocolConfig<uint64_t>(numParties, p, q, degree, sigma, lambda, tau_limit_bit, pbs, ProtocolMode::NORMAL);\n        auto e = lattice::LatticeEncryption<uint64_t, degree, p, q>(config);\n\n        std::tie(alphasPS, bucketSizePS) = math::balanced_bucket_n_primes(config.pbs(), primesPS, config.tauLimitBit(), 1);\n        std::tie(alphasCAN, bucketSizeCAN) = math::fixed_bucket_n_primes(config.pbs()+48, primesCAN, config.tauLimitBit());\n\n        std::vector<size_t> bucketSizeGCD;\n        std::tie(alphasGCD, bucketSizeGCD) = math::fixed_bucket_n_primes(3*config.pbs()+210, primesGCD, config.tauLimitBit());\n\n        std::vector<std::vector<mpz_class>> eit_prunedPS;\n        std::vector<mpz_class> c_can(primesCAN);\n        auto alphasPS_tick = alphasPS;\n        std::vector<mpz_class> c_gcd(primesGCD);\n\n\n        // set equal buckets for bucketSizeCan and bucketSizeGCD\n        auto bucketSizeCAN_value = lrint(floor(double(primesCAN) / double(alphasCAN.size())));\n        for (int i = 0; i < bucketSizeCAN.size(); ++i) {\n            bucketSizeCAN[i] = bucketSizeCAN_value;\n        }\n        auto bucketSizeGCD_value = lrint(floor(double(primesGCD) / double(alphasGCD.size())));\n        for (int i = 0; i < bucketSizeGCD.size(); ++i) {\n            bucketSizeGCD[i] = bucketSizeGCD_value;\n        }\n\n\n        // Validate Keygen\n        {\n            validate<Q>(MessageType::PUBLIC_KEY_A_SHARES, std::plus<Q>(), 0);\n            validate<Q>(MessageType::PUBLIC_KEY_B_SHARES, std::plus<Q>(), 0);\n            std::cout << \"Keygen: [SUCCESS]\" << std::endl;\n        }\n\n        // Validate pre-sieve\n        {\n            validate<std::pair<Q, Q>>(\n                    MessageType::ENCRYPTED_X_SHARES,\n                    lattice::pair_add<Q>, \n                    std::pair<Q, Q>{0, 0}\n                    );\n\n            validate<std::pair<Q, Q>>(\n                    MessageType::ENCRYPTED_XY_PLUS_Z_SHARES, \n                    lattice::pair_add<Q>,\n                    std::pair<Q, Q>{0, 0}\n                    );\n\n            {\n                Q computedAccumulator = validate<Q>(\n                    MessageType::PARTIAL_XY_MINUS_Z_SHARES,\n                    std::plus<Q>(), \n                    Q{0}\n                    );\n\n                std::vector<mpz_class> eitPS;\n                std::vector<int> flags_can;\n                Q eit_poly = computedAccumulator;\n\n                // convert eit_poly to eit\n                std::vector<mpz_class> tauVector(degree);\n                {\n                    int tvk = 0;\n\n\n                    // pre-sieving\n                    for (size_t i = 0; i < alphasPS.size(); ++i) {\n                        for (size_t j = 0; j < bucketSizePS[i]; ++j) {\n                            tauVector[tvk] = alphasPS[i];\n                            tvk++;\n                        }\n                    }\n\n                    DBG(\"tvk << \" << tvk);\n                    DBG(\"primesPS << \" << primesPS);\n                    assert(tvk == primesPS);\n                    tvk = primesPS;\n                    // candidate generation\n                    //index_candidates.resize(Degree);\n                    for (size_t j = 0; j < bucketSizeCAN_value; ++j) {\n                        for (size_t i = 0; i < alphasCAN.size(); ++i) {\n                            //index_candidates[tvk] = j;\n                            tauVector[tvk] = alphasCAN[i];\n                            tvk++;\n                        }\n                    }\n\n                    // GCD\n                    for (size_t j = 0; j < bucketSizeGCD_value; ++j) {\n                        for (size_t i = 0; i < alphasGCD.size(); ++i) {\n                            /*\n                            if (j < 1) {\n                                index_candidates[tvk] = -2;\n                            } else {\n                                index_candidates[tvk] = -3;\n                            }\n                            */\n                            tauVector[tvk] = alphasGCD[i];\n                            tvk++;\n                        }\n                    }\n\n                    // fill the rest with dummy values from pre-sieving\n                    for (; tvk < degree; ++tvk) {\n                        tauVector[tvk] = alphasPS[0];\n                    }\n                }\n\n                DBG(\"before eval poly\");\n\n                auto c_mpz_t = e.eval_poly(eit_poly, tauVector);\n\n                DBG(\"after eval poly\");\n\n                // Need to compute presieve flags\n                std::vector<mpz_class> c;\n                std::tie(eitPS, flags_can, c) = computeEITAndFlags(c_mpz_t);\n\n                \n                eit_prunedPS = pruneAndReorderEIT(eitPS, flags_can, alphasPS.size());\n\n                alphasPS_tick.insert(alphasPS_tick.begin(), mpz_class(4));\n                for (int i = primesPS; i < primesPS + primesCAN; ++i) {\n                    c_can[i - primesPS] = c[i];\n                }\n\n                for (int i = primesPS + primesCAN; i < primesPS + primesCAN + primesGCD; ++i) {\n                    c_gcd[i - primesPS - primesCAN] = c[i];\n                }\n\n                std::vector<int> expectedFlagsCan;\n                MessageType expectedFlagsType;\n                ia >> expectedFlagsType;\n\n                if (expectedFlagsType != MessageType::PS_SIEVING_FLAGS) {\n                    std::cout << \"Unexpected MessageType \" << int(expectedFlagsType) << std::endl;\n                    std::cout << \"Expected: \" << msgs[1 + int(MessageType::PS_SIEVING_FLAGS) - int(MessageType::ID_PARTY)] << std::endl;\n                    std::cout << \"Got: \" << msgs[1 + int(expectedFlagsType) - int(MessageType::ID_PARTY)];\n                    assert(false);\n                }\n\n                ia >> expectedFlagsCan;\n                \n                if (expectedFlagsCan.size() != flags_can.size()) {\n                    std::cout << \"Expected eit flags size \" << expectedFlagsCan.size()\n                              << \" does not match compute flags size \" << flags_can.size();\n                    assert(false);\n                }\n                for (size_t i = 0; i < expectedFlagsCan.size(); i++) {\n                    if (flags_can[i] != expectedFlagsCan[i]) {\n                        std::cout << \"Expected flag flags_can[\" << i << \"] = \" << expectedFlagsCan[i]\n                                  << \" does not match computed flags[\" << i << \"] = \" << flags_can[i];\n                        assert(false);\n                    }\n                }\n            }\n\n            std::cout << \"Pre-sieve: [SUCCESS]\" << std::endl;\n        }\n\n        // Validate modulus candidate generation\n        {\n            auto bucketSize = lrint(floor(double(primesCAN) / double(alphasCAN.size())));\n            if (bucketSize > eit_prunedPS.size()) {\n                bucketSize = eit_prunedPS.size();\n            }\n            std::vector<mpz_class> alphas_combined(alphasCAN.size() + alphasPS_tick.size());\n            int aci = 0;\n            for (size_t i = 0; i < alphasCAN.size(); ++i) {\n                alphas_combined[aci] = alphasCAN[i];\n                ++aci;\n            }\n            for (size_t i = 0; i < alphasPS_tick.size(); ++i) {\n                alphas_combined[aci] = alphasPS_tick[i];\n                ++aci;\n            }\n\n            using PairOfVec = std::pair<std::vector<mpz_class>, std::vector<mpz_class>>; \n            auto acc_pair = std::pair<std::vector<mpz_class>, std::vector<mpz_class>>(std::vector<mpz_class>(primesCAN), std::vector<mpz_class>(primesCAN));\n            auto ax_by_sum = validate<PairOfVec>(\n                    MessageType::AX_BY_SHARES,\n                    [](const PairOfVec& a, const PairOfVec& b) {\n                    assert(a.first.size() == b.second.size());\n                    assert(a.second.size() == b.first.size());\n\n                    std::vector<mpz_class> rf(a.first.size());\n                    std::vector<mpz_class> rs(a.second.size());\n\n                    for(size_t i = 0; i < a.first.size(); ++i) {\n                    rf[i] = a.first[i] + b.first[i]; \n                    rs[i] = a.second[i] + b.second[i];\n                    }\n                    return std::pair{rf, rs};\n                    },\n                    acc_pair\n                    );\n\n            {\n                int k = 0;\n                for (int j = 0; j < bucketSize; ++j) {\n                    for (int i = 0; i < alphasCAN.size(); ++i) {\n                        ax_by_sum.first[k] = ax_by_sum.first[k] % alphasCAN[i];\n                        ax_by_sum.second[k] = ax_by_sum.second[k] % alphasCAN[i];\n                        ++k;\n                    }\n                }\n            }\n            auto ab = validate<std::vector<mpz_class>>(\n                    MessageType::AXB_MINUS_BYA_SHARES,\n                    [](const std::vector<mpz_class>& a, const std::vector<mpz_class>& b) {\n                    assert(a.size() == b.size());\n\n                    std::vector<mpz_class> result(a.size());\n\n                    for(size_t i = 0; i < a.size(); ++i) {\n                    result[i] = a[i] + b[i]; \n                    }\n                    return result;\n                    },\n                    std::vector<mpz_class>(primesCAN)\n                    );\n\n            {\n                int k = 0;\n                for (int j = 0; j < bucketSize; ++j) {\n                    for (int i = 0; i < alphasCAN.size(); ++i) {\n                        ab[k] = math::mod(ab[k] + c_can[k] - ax_by_sum.first[k] * ax_by_sum.second[k], alphasCAN[i]);\n                        ++k;\n                    }\n                }\n            }\n\n            // Validate MODULUS_CANDIDATES\n            {\n\n               \n\n                std::vector<mpz_class> candidates_raw(bucketSize);\n\n                int k = 0;\n                auto pq_size = bucketSize;\n                if (pq_size > eit_prunedPS.size()) {\n                    pq_size = eit_prunedPS.size();\n                }\n                for (int i = 0; i < pq_size; ++i) {\n\n                    std::vector<mpz_class> x(alphasCAN.size() + alphasPS_tick.size());\n\n                    //DBG(\"copy from can\");\n                    for (int zz = 0; zz < alphasCAN.size(); ++zz) {\n                        x[zz] = mpz_class(ab[i * alphasCAN.size() + zz]);\n                    }\n                    //DBG(\"copy from ps\");\n                    // copy from ps\n                    for (int zz = 0; zz < alphasPS_tick.size(); ++zz) {\n                        x[zz + alphasCAN.size()] = mpz_class(eit_prunedPS[i][zz]);\n                    }\n\n                    //DBG(\"before crt_reconstruct\");\n                    std::vector<mpz_class> coefs;\n                    candidates_raw[k] = math::crt_reconstruct(x, coefs, alphas_combined);\n                    for(int zz=1; zz < 127; ++zz)\n                    {\n                        mpz_t result;\n                        mpz_init(result);\n                        mpz_class prime = boost::math::prime(zz);\n                        mpz_gcd(result, candidates_raw[k].get_mpz_t(),prime.get_mpz_t());\n                        if(mpz_cmp_ui(result,1) != 0)\n                        {\n                            LOG(INFO) << \"Candidate[\" << k << \"] = \" << candidates_raw[k] << \" is divisible by \" << boost::math::prime(zz);\n                            assert(false);\n                        }\n                        mpz_clear(result);\n                    }\n                    //DBG(\"after crt_reconstruct\");\n                    k++;\n                }\n\n                DBG(\"k = \" << k);\n\n                // Compute pq_size\n                std::vector<mpz_class> candidates(k);\n                for (int i = 0; i < k; ++i) {\n                    candidates[i] = candidates_raw[i];\n                }\n\n                // Now compare with the expected one from file\n                std::vector<mpz_class> expectedModulusCandidates;\n                MessageType expectedModulusCandidatesType;\n                ia >> expectedModulusCandidatesType;\n\n                if (expectedModulusCandidatesType != MessageType::MODULUS_CANDIDATE) {\n                    std::cout << \"Unexpected MessageType \" << int(expectedModulusCandidatesType) << std::endl;\n                    std::cout << \"Expected: \" << msgs[1 + int(MessageType::MODULUS_CANDIDATE) - int(MessageType::ID_PARTY)] << std::endl;\n                    std::cout << \"Got: \" << msgs[1 + int(expectedModulusCandidatesType) - int(MessageType::ID_PARTY)];\n                    assert(false);\n                }\n                ia >> expectedModulusCandidates;\n\n                if (expectedModulusCandidates.size() != candidates.size()) {\n                    std::cout << \"Size does not match\" << std::endl;\n                    std::cout << \"Expected candidates size: \" << expectedModulusCandidates.size() << std::endl;\n                    std::cout << \"Computed candidates size: \" << candidates.size();\n                    assert(false);\n                }\n                candidatesCAN = candidates;\n            }\n\n\n\n            // validate sync step\n            validate<int>(\n                    MessageType::SYNCHRONIZE_NOW,\n                    [](const int& a, const int& b) {\n                    return a+b;\n                    },\n                    0);\n\n            std::cout << \"Candidate generation: [SUCCESS]\" << std::endl;\n        }\n\n        // Validate PostSieve\n        {\n            // read post sieve flags\n            boost::dynamic_bitset<> postSieveFlags;\n            MessageType postSieveType;\n\n            ia >> postSieveType;\n            if (postSieveType != MessageType::POST_SIEVE) {\n                std::cout << \"Unexpected MessageType \" << int(postSieveType) << std::endl;\n                std::cout << \"Expected: \" << msgs[1 + int(MessageType::POST_SIEVE) - int(MessageType::ID_PARTY)] << std::endl;\n                std::cout << \"Got: \" << msgs[1 + int(postSieveType) - int(MessageType::ID_PARTY)];\n                assert(false);\n            }\n\n            ia >> postSieveFlags;\n\n            auto [Bs, Ms] = ligero::math::compute_m_b_vec(4096, 104729, 2);\n            auto nb_threads = 90;\n            auto postSieve = std::bind(ligero::math::test_factorizable_threaded, std::placeholders::_1, Bs, Ms, nb_threads);\n\n\n            std::vector<mpz_class> nonBiPrimes;\n            for (size_t i = 0; i < candidatesCAN.size(); i++) {\n                if (postSieveFlags[i] == 1) {\n                    nonBiPrimes.push_back(candidatesCAN[i]);\n                }\n            }\n\n            auto discardFlagsToValidate = postSieve(std::vector<mpz_class>(nonBiPrimes.data(), nonBiPrimes.data() + nonBiPrimes.size()));\n\n            // Check that all nonBiPrimes were eliminated\n            if (discardFlagsToValidate.count() != nonBiPrimes.size()) {\n                std::cout << \"Post sieve validation failed\" << std::endl;\n                std::cout << \"Total amount of non-biprimes which were not eliminated is: \" << nonBiPrimes.size() - discardFlagsToValidate.count() << std::endl;\n                std::cout << \"The following non-biprimes were not eliminated:\" << std::endl;\n                for (size_t i = 0; i < nonBiPrimes.size(); i++) {\n                    if (discardFlagsToValidate[i] == 0) {\n                        std::cout << \"index: \" << i << \" = \" <<  nonBiPrimes[i] << std::endl;\n                        assert(false);\n                    }\n                }\n            }\n            candidatesPostSieve = discardCandidates(candidatesCAN, postSieveFlags);\n            std::cout << currentStep++ << \". \" << \"Post-Sieve: [SUCCESS]\" << std::endl;\n        }\n\n        // Validate jacobi\n        {\n            auto candidates = candidatesPostSieve;\n            validate<mpz_class>(\n                    MessageType::GAMMA_RANDOM_SEED_SHARES,\n                    [](const mpz_class& a,\n                        const mpz_class& b) { return a ^ b; },\n                    mpz_class(0)\n                    );\n\n            auto ggs = validate<std::vector<mpz_class>>(\n                    MessageType::EXPONENTIATED_GAMMA_VALUE,\n                    [](const std::vector<mpz_class>& a, const std::vector<mpz_class>& b) {\n\n                    if (a.size() == 0) return b;\n\n                    std::vector<mpz_class> c(b.size());\n                    for (size_t i = 0; i < c.size(); ++i) {\n                    c[i] = a[i] * b[i];\n                    }\n                    return c;\n                    },\n                    std::vector<mpz_class>()\n                    );\n\n            boost::dynamic_bitset<> discard (candidates.size());\n\n            int discarded = 0;\n            //DBG(\"my candidates = \" << candidates);\n            for (int i = 0; i < candidates.size(); ++i) {\n                const mpz_class& N = candidates[i];\n                mpz_class& gg = ggs[i];\n                mpz_class x = gg % N;\n\n                // Elimination\n                if (x != 1 && x != (N - 1)) {\n                    discard[i] = 1;\n                    discarded++;\n                }\n            }\n\n            boost::dynamic_bitset<> discardFlagsJacobi;\n            MessageType discardFlagsJacobiType;\n            ia >> discardFlagsJacobiType;\n            if (discardFlagsJacobiType != MessageType::DISCARD_FLAGS) {\n                std::cout << \"Unexpected MessageType \" << int(discardFlagsJacobiType) << std::endl;\n                std::cout << \"Expected: \" << msgs[1 + int(MessageType::DISCARD_FLAGS) - int(MessageType::ID_PARTY)] << std::endl;\n                std::cout << \"Got: \" << msgs[1 + int(discardFlagsJacobiType) - int(MessageType::ID_PARTY)];\n                assert(false);\n            }\n            ia >> discardFlagsJacobi;\n\n            for (size_t i = 0; i < candidates.size(); i++) {\n                if (discardFlagsJacobi[i] != discard[i]) {\n                    std::cout << \"Discard flags for jacobi do not match the computed ones\" << std::endl;\n                    std::cout << \"Computed[\" << i << \"] = \" << discard[i] << std::endl;\n                    std::cout << \"Expected[\" << i << \"] = \" << discardFlagsJacobi[i] << std::endl;\n                }\n            }\n\n            candidatesJacobi = discardCandidates(candidates, discardFlagsJacobi);\n            std::cout << currentStep++ << \". \" << \"Jacobi flags validation passed\" << std::endl;\n            std::cout << \"Jacobi: [SUCCESS]\" << std::endl;\n        }\n\n        // Validate GCD and Jacobi\n        {\n            std::vector<mpz_class> ggsGCD;\n            const int bucketSize = lrint(floor(double(primesGCD) / double(alphasGCD.size())));\n            auto candidates = candidatesJacobi;\n            candidates.resize(1);\n\n            auto acc_pair = std::pair{std::pair{std::vector<mpz_class>(primesGCD), std::vector<mpz_class>(primesGCD)}, mpz_class(0)};\n\n            auto result_value = validate<PairOfVecGCD> \n                (\n                 MessageType::GCD_AX_BY_SHARES,\n                 [](const PairOfVecGCD& a, const PairOfVecGCD& b) {\n                 auto [pair_a, at] = a;\n                 auto [pair_b, bt] = b;\n                 auto [af, as] = pair_a;\n                 auto [bf, bs] = pair_b;\n                 assert(af.size() == bf.size());\n                 assert(as.size() == bs.size());\n\n                 std::vector<mpz_class> rf(af.size());\n                 std::vector<mpz_class> rs(as.size());\n\n                 for(size_t i = 0; i < af.size(); ++i) {\n                 rf[i] = af[i] + bf[i]; \n                 rs[i] = as[i] + bs[i];\n                 }\n\n                 mpz_class rt = at ^ bt;\n\n                 return std::pair{std::pair{rf, rs}, rt};\n                 },\n                 acc_pair\n                     );\n\n            auto [pair_axby, gammaSeed] = result_value;\n\n            auto [ax_sum, by_sum] = pair_axby;\n\n            {\n                int k = 0;\n                for (int j = 0; j < bucketSize; ++j) {\n                    for (int i = 0; i < alphasGCD.size(); ++i) {\n                        ax_sum[k] = ax_sum[k] % alphasGCD[i];\n                        by_sum[k] = by_sum[k] % alphasGCD[i];\n                        ++k;\n                    }\n                }\n            }\n            auto zcrt_value = validate<std::pair<std::vector<mpz_class>, std::vector<mpz_class>>>(\n                    MessageType::AXB_MINUS_BYA_SHARES,\n                    [](const std::pair<std::vector<mpz_class>, std::vector<mpz_class>>& pa,\n                        const std::pair<std::vector<mpz_class>, std::vector<mpz_class>>& pb) {\n                    auto [a, expGa] = pa;\n                    auto [b, expGb] = pb;\n\n                    if (a.size() == 0) return pb; \n\n                    assert(expGa.size() == expGb.size());\n\n                    std::vector<mpz_class> expResult(expGb.size());\n                    for (size_t i = 0; i < expResult.size(); ++i) {\n                    expResult[i] = expGa[i] * expGb[i];\n                    }\n\n                    assert(a.size() == b.size());\n\n                    std::vector<mpz_class> result(a.size());\n\n                    for(size_t i = 0; i < a.size(); ++i) {\n                        result[i] = a[i] + b[i]; \n                    }\n                    return std::pair{result, expResult};\n                    },\n                        std::pair{std::vector<mpz_class>(), std::vector<mpz_class>()}\n            );\n\n            std::vector<mpz_class> zCRTs;\n\n            std::tie(zCRTs, ggsGCD) = zcrt_value;\n\n\n            {\n                int k = 0;\n                for (int j = 0; j < bucketSize; ++j) {\n                    for (int i = 0; i < alphasGCD.size(); ++i) {\n                        zCRTs[k] = math::mod(zCRTs[k] + c_gcd[k] - ax_sum[k] * by_sum[k], alphasGCD[i]);\n                        ++k;\n                    }\n                }\n            }\n            // reconstruct z from CRT representation\n            std::vector<mpz_class> zs(candidates.size());\n            int zc = 0;\n            for (int i = 0; i < candidates.size(); ++i) {\n\n                std::vector<mpz_class> x(alphasGCD.size());\n                for (int zz = 0; zz < alphasGCD.size(); ++zz) {\n                    x[zz] = zCRTs[zc];\n                    ++zc;\n                }\n\n                std::vector<mpz_class> coefs;\n                zs[i] = math::crt_reconstruct(x, coefs, alphasGCD);\n            }\n\n\n            // GCD: compute discard vector\n            boost::dynamic_bitset<> discardGCD (zs.size());\n            {\n                {\n                    mpz_t one;\n                    mpz_init(one);\n                    mpz_set_ui(one, 1);\n\n                    mpz_t gcdResult;\n                    mpz_init(gcdResult);\n                    for (int i = 0; i < zs.size(); ++i) {\n                        DBG(\"i = \" << i);\n                        const mpz_class& N = candidates[i];\n                        DBG(\"N = \" << N);\n\n                        const mpz_class z = zs[i] % N;\n\n                        DBG(\"z = \" << z);\n                        DBG(\"before mpz_gcd\");\n                        mpz_gcd(gcdResult, N.get_mpz_t(), z.get_mpz_t());\n\n                        if (mpz_cmp(gcdResult, one) != 0) {\n                            discardGCD[i] = 1;\n                        }\n\n                    }\n                    mpz_clear(gcdResult);\n                    mpz_clear(one);\n                }\n            }\n\n            assert(zs.size() == candidates.size());\n\n            // Jacobi: compute discard vector\n            boost::dynamic_bitset<> discardJacobi (candidates.size());\n            {\n\n                //DBG(\"my candidates = \" << candidates);\n                DBG(\"Taking gamma values modulo N\");\n                for (int i = 0; i < candidates.size(); ++i) {\n                    for (int j = 0; j < config.lambda(); ++j) {\n                        const mpz_class& N = candidates[i];\n                        mpz_class& gg = ggsGCD[i * config.lambda() + j];\n                        mpz_class x = gg % N;\n\n                        DBG(\"x = \" << x);\n                        DBG(\"N = \" << N);\n                        DBG(\"ggs[\" << i << \"] =\" << ggsGCD[i * config.lambda() + j]);\n\n                        // Elimination\n                        if (x != 1 && x != (N - 1)) {\n                            discardJacobi[i] = 1;\n                        }\n                    }\n                }\n            }\n\n            // Final step: merge discardGCD and discardJacobi\n            boost::dynamic_bitset<> discard (candidates.size());\n            DBG(\"hostGCDandJacobiTest candidates.size() = \" << candidates.size());\n            for (int i = 0; i < candidates.size(); ++i) {\n                DBG(\"discardGCD[\" << i << \"] = \" << discardGCD[i]);\n                DBG(\"discardJacobi[\" << i << \"] = \" << discardJacobi[i]);\n                discard[i] = discardGCD[i] | discardJacobi[i];\n            }\n\n            boost::dynamic_bitset<> discardFlagsGCD;\n            MessageType discardFlagsGCDType;\n            ia >> discardFlagsGCDType;\n\n            if (discardFlagsGCDType != MessageType::DISCARD_FLAGS) {\n                std::cout << \"Unexpected MessageType \" << int(discardFlagsGCDType) << std::endl;\n                std::cout << \"Expected: \" << msgs[1 + int(MessageType::DISCARD_FLAGS) - int(MessageType::ID_PARTY)] << std::endl;\n                std::cout << \"Got: \" << msgs[1 + int(discardFlagsGCDType) - int(MessageType::ID_PARTY)];\n                assert(false);\n            }\n\n            ia >> discardFlagsGCD;\n\n            for (size_t i = 0; i < candidates.size(); i++) {\n                if (discardFlagsGCD[i] != discard[i]) {\n                    std::cout << \"Discard flags for GCD and jacobi do not match the computed ones\" << std::endl;\n                    std::cout << \"Computed[\" << i << \"] = \" << discard[i] << std::endl;\n                    std::cout << \"Expected[\" << i << \"] = \" << discardFlagsGCD[i] << std::endl;\n                }\n            }\n\n            std::cout << currentStep++ << \". \" << \"GCD Jacobi flags validation passed\" << std::endl;\n            std::cout << \"GCD and Jacobi: [SUCCESS]\" << std::endl;\n        }\n\n        std::cout << std::endl << \">>>>  VALIDATION PASSED <<<<\" << std::endl;\n        /*\n           while (ifs && ifs.peek() != EOF) {\n           MessageType t;\n           ia >> t;\n           int msgId = int(t);\n           std::cout << \"t: \" << msgId << std::endl;\n           if (msgId > 0) msgId = msgId - int(MessageType::ID_PARTY);\n           std::cout << \"header: \" << msgs[msgId] << std::endl;\n\n           }\n           */\n    }\n    /*\n       } catch (...) {\n       std::cout << \"caught exception\" << std::endl;\n       ifs.close();\n       }\n       */\n\n    ifs.close();\n    return 0;\n}\n\n", "meta": {"hexsha": "570a7bd5b352484dc13be6fdcfaf47d372f48349", "size": 33169, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/validator.cpp", "max_stars_repo_name": "Eleven-Z/LigeroRSA", "max_stars_repo_head_hexsha": "17d8b3d00604da1e0272035e871fac3add8d7551", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/validator.cpp", "max_issues_repo_name": "Eleven-Z/LigeroRSA", "max_issues_repo_head_hexsha": "17d8b3d00604da1e0272035e871fac3add8d7551", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-08-09T05:48:09.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-09T05:48:09.000Z", "max_forks_repo_path": "src/validator.cpp", "max_forks_repo_name": "Eleven-Z/LigeroRSA", "max_forks_repo_head_hexsha": "17d8b3d00604da1e0272035e871fac3add8d7551", "max_forks_repo_licenses": ["Apache-2.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.9074285714, "max_line_length": 159, "alphanum_fraction": 0.4570834213, "num_tokens": 7854, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6757646010190476, "lm_q2_score": 0.45326184801538616, "lm_q1q2_score": 0.3062983118812736}}
{"text": "#include \"Lib/spin_system.h\"\n#include \"lib/log_trace.h\"\n#include \"Lib/simulate.h\"\n#include \"lib/grid.h\"\n#include \"lib/constants.h\"\n#include \"lib/P_lists.h\"\n#include \"Lib/load_parameters.h\"\n\n#include <omp.h>\n\n#include <iostream>\n#include <filesystem>\n#include <unsupported/Eigen/MatrixFunctions>\n#include <Eigen/Eigenvalues>\n#include <Eigen/Geometry>\n#include <vector>\n#include <fstream>\n#include <string>\n#include <vector>\n#include <boost/tuple/tuple.hpp>\n#include <boost/tuple/tuple_io.hpp>\n#include <boost/ref.hpp>\n#include <math.h>\n\n#include <chrono>\n\n\nnamespace fs = std::experimental::filesystem;\n\ntemplate<class P_list>\nP_list create_8_ns_P_list(P_list const & P_list_2ns) {\n\n\t/*\n\tthis function creates propagators that capture an 8ns step from propagators that capture a 2ns step\n\t*/\n\n\t//2ns\n\tP_list temp(P_list_2ns); \n\t//4ns\n\ttemp.multiply(temp,true);\n\t//8ns\n\ttemp.multiply(temp, true);\n\n\n\n\treturn temp;\n}\n\n\ntemplate<class P_list>\nP_list repeat_P_list(P_list const & P_list_step,double t_end) {\n\n\t/*\n\tthis function repeats the propagators in P_list_step upto a time step t_end is captured\n\t*/\n\n\tP_list temp(P_list_step);\n\ttemp.reset();\n\n\n\twhile (temp.t_step < t_end ) {\n\t\ttemp.multiply(P_list_step, true);\n\t}\n\n\treturn temp;\n}\n\n\ntemplate<class P_list>\nP_list reverse_P_list(P_list const & P_list_start, P_list const & P_list_step, double t_end) {\n\n\t/*\n\tthis function calculates propagators that capture a time step of the length t_end by reverting the\n\tpropgatros in P_list_start with the propagators in P_list_step\n\t*/\n\n\n\tP_list temp(P_list_start);\n\n\n\twhile ( temp.t_step > t_end) {\n\t\ttemp.multiply(P_list_step, false);\n\t\t\n\t}\n\n\treturn temp;\n}\n\n\n\n\nint main(int argc, char *argv[]) {\n\n\ttry {\n\t\tif (argc < 4)\n\t\t{\n\t\t\tthrow std::runtime_error(\"Not enough arguments given\");\n\t\t}\n\t}\n\tcatch (std::runtime_error &er) {\n\t\tstd::cout << er.what() << \"\\n\";\n\t}\n\n\n\n\tdouble t_step;\n\tstd::vector<double> taus;\n\tSpin_System_Doublet_Triplet spin_time_2;\n\tSpin_System_Doublet_Triplet spin_pulse_2;\n\tstd::vector<double> t;\n\n\n\tSpin_System_Doublet spin_time;\n\tSpin_System_Doublet spin_pulse;\n\t\t\n\tauto temp = boost::make_tuple(boost::ref(spin_time), boost::ref(spin_pulse), boost::ref(t_step), boost::ref(taus), boost::ref(t));\n\ttemp = load_parameters_doublet(argv[1]);\n\n\n\tauto temp2 = boost::make_tuple(boost::ref(spin_time_2), boost::ref(spin_pulse_2), boost::ref(t_step), boost::ref(taus), boost::ref(t));\n\ttemp2 = load_parameters_Doublet_Triplet(argv[1]);\n\n\n\tdouble const t0 = t[0];\n\tdouble const t1 = t[1];\n\tdouble const t2 = t[2];\n\tdouble const t3 = t[3];\n\tdouble const t4 = t[4];\n\tdouble const t5 = t[5];\n\tdouble t_pi_2 = t[1];\n\n\tdouble t_tau = taus[1] - taus[0];\n\n\tLog_stream log_stream(argv[2], \"integral\", t_step);\n\n\tstd::vector<double> phi_doublet;\n\tstd::vector<double> theta_doublet;\n\tstd::vector<double> weights_doublet;\n\tauto temp_doublet = boost::make_tuple(boost::ref(phi_doublet), boost::ref(theta_doublet), boost::ref(weights_doublet));\n\ttemp_doublet = grid(argv[3],spin_time_2.symmetrie_doublet, spin_time_2.knots_doublet);\n\n\n\tstd::vector<double> phi_triplet;\n\tstd::vector<double> theta_triplet;\n\tstd::vector<double> weights_triplet;\n\tauto temp_triplet = boost::make_tuple(boost::ref(phi_triplet), boost::ref(theta_triplet), boost::ref(weights_triplet));\n\ttemp_triplet = grid(argv[3], spin_time_2.symmetrie_triplet, spin_time_2.knots_triplet);\n\n\tstd::vector<double> phi_dipolar;\n\tstd::vector<double> theta_dipolar;\n\tstd::vector<double> weights_dipolar;\n\tauto temp_dipolar = boost::make_tuple(boost::ref(phi_dipolar), boost::ref(theta_dipolar), boost::ref(weights_dipolar));\n\ttemp_dipolar = grid(argv[3], spin_time_2.symmetrie_dipolar, spin_time_2.knots_dipolar);\n\n\t//the propagators for the Doublet system (before Laser excitation) are simulated in advance, they are updated later on capture the shift of the laser flash\n\n\n\tP_list_one_rot<Spin_System_Doublet> P_list_time_2ns(spin_time, t_step, theta_doublet, phi_doublet); P_list_time_2ns.create_P_list();\n\tP_list_one_rot<Spin_System_Doublet> P_list_time_8ns(create_8_ns_P_list(P_list_time_2ns));\n\tP_list_one_rot<Spin_System_Doublet> P_list_time_fid1(repeat_P_list(P_list_time_8ns, t2 - t1)); \n\tP_list_one_rot<Spin_System_Doublet> P_list_time_fid2(repeat_P_list(P_list_time_8ns, t4 - t3));\n\n\n\tP_list_one_rot<Spin_System_Doublet> P_list_pulse_2ns(spin_pulse, t_step, theta_doublet, phi_doublet); P_list_pulse_2ns.create_P_list();\n\tP_list_one_rot<Spin_System_Doublet> P_list_pulse_8ns(create_8_ns_P_list(P_list_pulse_2ns)); \n\tP_list_one_rot<Spin_System_Doublet>  P_list_pulse_pi_2(repeat_P_list(P_list_pulse_2ns, t_pi_2)); \n\tP_list_one_rot<Spin_System_Doublet>  P_list_pulse_pi(P_list_pulse_pi_2);  P_list_pulse_pi.multiply(P_list_pulse_pi, true);\n\n\n\tP_list_one_rot<Spin_System_Doublet> P_list_dummy(P_list_pulse_2ns);\n\tSpin_System_Doublet::operator_type rho_eq = spin_time.get_rho_equ();\n\t\t\n\tSpin_System_Doublet::operator_type rho_doublet = Spin_System_Doublet::operator_type::Zero();\n\t\t\n\n\tstd::vector<std::vector<Spin_System_Doublet::operator_type>> rho_doublets;\n\n\t\t\n\n\n\tfor (auto tau : taus) {\n\n\t\t\n\t\tstd::vector<Spin_System_Doublet::operator_type > rho_doublet_angles;\n\t\t\n\t\tlog_stream.save_x(tau);\n\t\t\n\t\tstd::cout << tau*1e9 << std::endl;\n\n\t\tif (tau < t0) {  //laser before first pulse\n\n\n\t\t}\n\t\telse if (tau >= t0 && tau < t1) {  //laser during first pulse\n\n\t\t\tif ((tau - t0) < t_tau) {\n\t\t\t\tP_list_dummy.copy_P_list(repeat_P_list(P_list_pulse_2ns, tau - t0));\n\t\t\t}\n\t\t\telse {\n\t\t\t\tP_list_dummy.multiply(P_list_pulse_8ns, true);\n\t\t\t}\n\n\n\n\t\t}\n\t\telse if (tau >= t1 && tau < t2) { //laser during first fid\n\n\t\t\tif ((tau - t1) < t_tau) {\n\t\t\t\tP_list_dummy.copy_P_list(repeat_P_list(P_list_time_2ns, tau - t1));\n\t\t\t}\n\t\t\telse {\n\t\t\t\tP_list_dummy.multiply(P_list_time_8ns, true);\n\t\t\t}\n\t\t}\n\t\telse if (tau >= t2 && tau < t3) { //laser during refocussing pulse\n\n\t\t\tif ((tau - t2) < t_tau) {\n\t\t\t\tP_list_dummy.copy_P_list(repeat_P_list(P_list_pulse_2ns, tau - t2));\n\t\t\t}\n\t\t\telse {\n\t\t\t\tP_list_dummy.multiply(P_list_pulse_8ns, true);\n\t\t\t}\n\n\n\n\t\t}\n\t\telse if (tau >= t3 && tau < t4) { //laser during second fid(echo)\n\n\t\t\tif ((tau - t3) < t_tau) {\n\t\t\t\tP_list_dummy.copy_P_list(repeat_P_list(P_list_time_2ns, tau - t3));\n\t\t\t}\n\t\t\telse {\n\t\t\t\tP_list_dummy.multiply(P_list_time_8ns, true);\n\t\t\t}\n\t\t}\n\t\telse {}\n\n\n\n\t\tfor (int i = 0; i < phi_doublet.size(); ++i) {\n\n\t\t\t\t\n\t\t\tdouble w_doublet = weights_doublet[i];\n\t\t\tSpin_System_Doublet::operator_type rho;\n\n\n\t\t\tif (tau < t0) {  //laser before first pulse\n\n\t\t\t\trho = rho_eq;\n\n\t\t\t}\n\t\t\telse if (tau >= t0 && tau < t1) {  //laser during first pulse\n\t\t\t\trho = simulate_P(spin_pulse, P_list_dummy.P_list[i], t0, tau, w_doublet, rho_eq, Log_trace_none{});\n\n\t\t\t}\n\t\t\telse if (tau >= t1 && tau < t2) { //laser during first fid\n\t\t\t\trho = simulate_P(spin_pulse, P_list_pulse_pi_2.P_list[i], t0, t1, w_doublet, rho_eq, Log_trace_none{});\n\t\t\t\trho = simulate_P(spin_time, P_list_dummy.P_list[i], t1, tau, w_doublet, rho, Log_trace_none{});\n\n\t\t\t}\n\t\t\telse if (tau >= t2 && tau < t3) { //laser during refocussing pulse\n\t\t\t\trho = simulate_P(spin_pulse, P_list_pulse_pi_2.P_list[i], t0, t1, w_doublet, rho_eq, Log_trace_none{});\n\t\t\t\trho = simulate_P(spin_time, P_list_time_fid1.P_list[i], t1, t2, w_doublet, rho, Log_trace_none{});\n\t\t\t\trho = simulate_P(spin_pulse, P_list_dummy.P_list[i], t2, tau, w_doublet, rho, Log_trace_none{});\n\n\t\t\t}\n\t\t\telse if (tau >= t3 && tau < t4) { //laser during second fid(echo)\n\t\t\t\trho = simulate_P(spin_pulse, P_list_pulse_pi_2.P_list[i], t0, t1, w_doublet, rho_eq, Log_trace_none{});\n\t\t\t\trho = simulate_P(spin_time, P_list_time_fid1.P_list[i], t1, t2, w_doublet, rho, Log_trace_none{});\n\t\t\t\trho = simulate_P(spin_pulse, P_list_pulse_pi.P_list[i], t2, t3, w_doublet, rho, Log_trace_none{});\n\t\t\t\trho = simulate_P(spin_time, P_list_dummy.P_list[i], t3, tau, w_doublet, rho, Log_trace_none{});\n\n\t\t\t}\n\t\t\telse if (tau >= t4 && tau < t5) { //laser during echo-detection\n\t\t\t\trho = simulate_P(spin_pulse, P_list_pulse_pi_2.P_list[i], t0, t1, w_doublet, rho_eq, Log_trace_none{});\n\t\t\t\trho = simulate_P(spin_time, P_list_time_fid1.P_list[i], t1, t2, w_doublet, rho, Log_trace_none{});\n\t\t\t\trho = simulate_P(spin_pulse, P_list_pulse_pi.P_list[i], t2, t3, w_doublet, rho, Log_trace_none{});\n\t\t\t\trho = simulate_P(spin_time, P_list_time_fid2.P_list[i], t3, t4, w_doublet, rho, Log_trace_none{});\n\t\t\t\trho = simulate_P(spin_time, P_list_time_2ns.P_list[i], t4, tau, w_doublet, rho, log_stream);\n\n\n\t\t\t}\n\t\t\telse if (tau >= t5) { //laser after echo\n\t\t\t\trho = simulate_P(spin_pulse, P_list_pulse_pi_2.P_list[i], t0, t1, w_doublet, rho_eq, Log_trace_none{});\n\t\t\t\trho = simulate_P(spin_time, P_list_time_fid1.P_list[i], t1, t2, w_doublet, rho, Log_trace_none{});\n\t\t\t\trho = simulate_P(spin_pulse, P_list_pulse_pi.P_list[i], t2, t3, w_doublet, rho, Log_trace_none{});\n\t\t\t\trho = simulate_P(spin_time, P_list_time_fid2.P_list[i], t3, t4, w_doublet, rho, Log_trace_none{});\n\t\t\t\trho = simulate_P(spin_time, P_list_time_2ns.P_list[i], t4, t5, w_doublet, rho, log_stream);\n\t\t\t}\n\t\t\telse {\n\t\t\t}\n\t\t\trho_doublet_angles.push_back(rho);\n\t\t}\n\n\t\trho_doublets.push_back(rho_doublet_angles);\n\t\tlog_stream.next();\n\t}\n\n\tlog_stream.reset();\n\n\t\t\n\tEigen::Matrix3cd rho_T;\n\n\n\t\t\t\n\t\t\n\tspin_time_2.create_rho_T_list(theta_triplet, phi_triplet);\n\t\n\tbool first_part=false;\n\n\t\t\n\t//the propagators for the Doublet_Triplet system (after Laser excitation) are simulated in advance, they are updated later on capture the shift of the laser flash\n\n\n\tSpin_System_Doublet_Triplet::operator_type rho = Spin_System_Doublet_Triplet::operator_type::Zero();\n\n\tP_list_three_rot<Spin_System_Doublet_Triplet> P_list_full_time_2ns(spin_time_2, t_step, theta_doublet, phi_doublet, theta_triplet, phi_triplet, theta_dipolar, phi_dipolar); P_list_full_time_2ns.create_P_list();\n\tP_list_three_rot<Spin_System_Doublet_Triplet> P_list_full_time_8ns(create_8_ns_P_list(P_list_full_time_2ns));\n\tP_list_three_rot<Spin_System_Doublet_Triplet> P_list_full_time_fid1(repeat_P_list(P_list_full_time_8ns, t2 - t1));\n\tP_list_three_rot<Spin_System_Doublet_Triplet> P_list_full_time_fid2(repeat_P_list(P_list_full_time_8ns, t4 - t3));\n\n\tP_list_three_rot<Spin_System_Doublet_Triplet> P_list_full_pulse_2ns(spin_pulse_2, t_step, theta_doublet, phi_doublet, theta_triplet, phi_triplet, theta_dipolar, phi_dipolar); P_list_full_pulse_2ns.create_P_list();\n\tP_list_three_rot<Spin_System_Doublet_Triplet> P_list_full_pulse_8ns(create_8_ns_P_list(P_list_full_pulse_2ns));\n\tP_list_three_rot<Spin_System_Doublet_Triplet> P_list_full_pulse_pi_2(repeat_P_list(P_list_full_pulse_2ns, t_pi_2));\n\tP_list_three_rot<Spin_System_Doublet_Triplet> P_list_full_pulse_pi(P_list_full_pulse_pi_2);  P_list_full_pulse_pi.multiply(P_list_full_pulse_pi, true);\n\n\tP_list_three_rot<Spin_System_Doublet_Triplet> P_list_full_dummy(P_list_full_pulse_2ns);\n\n\n\tfor (int q = 0; q < taus.size();++q) {\n\t\tdouble tau = taus[q];\n\t\tlog_stream.save_x(tau);\n\n\t\t//show current tau on screen\n\t\tstd::cout << tau*1e9 << \"\\n\";\n\t\t\t\t\n\t\tfor (int i = 0; i < phi_doublet.size(); ++i) {\n\t\t\t\t\t\n\t\t\trho_doublet = rho_doublets[q][i];\n\n\t\t\tfor (int k = 0; k < phi_dipolar.size(); ++k) {\n\t\t\t\t\n\n\t\t\t\tfor (int m = 0; m < phi_triplet.size(); ++m) {\n\n\t\t\t\t\trho_T = spin_time_2.get_rho_T_list(m);\n\n\t\t\t\t\t\n\t\t\t\t\tdouble w= weights_doublet[i] * weights_dipolar[k] * weights_triplet[m];\n\t\t\t\t\t\t\n\t\t\t\t\tif (tau < t0) {  //laser before first pulse\n\n\t\t\t\t\t\tif (!first_part) {\n\t\t\t\t\t\t\trho = Eigen::kroneckerProduct(rho_eq, rho_T);\n\t\t\t\t\t\t\trho = simulate_P(spin_pulse_2, P_list_full_pulse_pi_2.P_list[i][m][k], t0, t1, w, rho, Log_trace_none{});\n\t\t\t\t\t\t\trho = simulate_P(spin_time_2, P_list_full_time_fid1.P_list[i][m][k], t1, t2, w, rho, Log_trace_none{});\n\t\t\t\t\t\t\trho = simulate_P(spin_pulse_2, P_list_full_pulse_pi.P_list[i][m][k], t2, t3, w, rho, Log_trace_none{});\n\t\t\t\t\t\t\trho = simulate_P(spin_time_2, P_list_full_time_fid2.P_list[i][m][k], t3, t4, w, rho, Log_trace_none{});\n\t\t\t\t\t\t\trho = simulate_P(spin_time_2, P_list_full_time_2ns.P_list[i][m][k], t4, t5, w, rho, log_stream);\n\t\t\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\tlog_stream.copy_last_point();\n\t\t\t\t\t\t\tgoto escape_point;\n\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t}\n\t\t\t\t\telse if (tau >= t0 && tau < t1) {  //laser during first pulse\n\t\t\t\t\t\t\t\n\t\t\t\t\t\trho = Eigen::kroneckerProduct(rho_doublet, rho_T);\n\t\t\t\t\t\trho = simulate_P(spin_pulse_2, P_list_full_dummy.P_list[i][m][k], tau, t1, w, rho, Log_trace_none{  });\n\t\t\t\t\t\trho = simulate_P(spin_time_2, P_list_full_time_fid1.P_list[i][m][k], t1, t2, w, rho, Log_trace_none{  });\n\t\t\t\t\t\trho = simulate_P(spin_pulse_2, P_list_full_pulse_pi.P_list[i][m][k], t2, t3, w, rho, Log_trace_none{  });\n\t\t\t\t\t\trho = simulate_P(spin_time_2, P_list_full_time_fid2.P_list[i][m][k], t3, t4, w, rho, Log_trace_none{  });\n\t\t\t\t\t\trho = simulate_P(spin_time_2, P_list_full_time_2ns.P_list[i][m][k], t4, t5, w, rho, log_stream);\n\t\t\t\t\t}\n\t\t\t\t\telse if (tau >= t1 && tau < t2) { //laser during first fid\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\trho = Eigen::kroneckerProduct(rho_doublet, rho_T);\n\t\t\t\t\t\trho = simulate_P(spin_time_2, P_list_full_dummy.P_list[i][m][k], tau, t2, w, rho, Log_trace_none{  });\n\t\t\t\t\t\trho = simulate_P(spin_pulse_2, P_list_full_pulse_pi.P_list[i][m][k], t2, t3, w, rho, Log_trace_none{  });\n\t\t\t\t\t\trho = simulate_P(spin_time_2, P_list_full_time_fid2.P_list[i][m][k], t3, t4, w, rho, Log_trace_none{  });\n\t\t\t\t\t\trho = simulate_P(spin_time_2, P_list_full_time_2ns.P_list[i][m][k], t4, t5, w, rho, log_stream);\n\n\t\t\t\t\t}\n\t\t\t\t\telse if (tau >= t2 && tau < t3) { //laser during refocussing pulse\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\trho = Eigen::kroneckerProduct(rho_doublet, rho_T);\n\t\t\t\t\t\trho = simulate_P(spin_pulse_2, P_list_full_dummy.P_list[i][m][k], tau, t3, w, rho, Log_trace_none{  });\n\t\t\t\t\t\trho = simulate_P(spin_time_2, P_list_full_time_fid2.P_list[i][m][k], t3, t4, w, rho, Log_trace_none{  });\n\t\t\t\t\t\trho = simulate_P(spin_time_2, P_list_full_time_2ns.P_list[i][m][k], t4, t5, w, rho, log_stream);\n\n\t\t\t\t\t}\n\t\t\t\t\telse if (tau >= t3 && tau < t4) { //laser during second fid(echo)\n\n\t\t\t\t\t\trho = Eigen::kroneckerProduct(rho_doublet, rho_T);\n\t\t\t\t\t\trho = simulate_P(spin_time_2, P_list_full_dummy.P_list[i][m][k], tau, t4, w, rho, Log_trace_none{  });\n\t\t\t\t\t\trho = simulate_P(spin_time_2, P_list_full_time_2ns.P_list[i][m][k], t4, t5, w, rho, log_stream);\n\t\t\t\t\t\t\n\t\t\t\t\t}\n\t\t\t\t\telse if (tau >= t4 && tau < t5) { //laser during echo-detection\n\t\t\t\t\t\t\n\t\t\t\t\t\trho = Eigen::kroneckerProduct(rho_doublet, rho_T);\n\t\t\t\t\t\trho = simulate_P(spin_time_2, P_list_full_time_2ns.P_list[i][m][k], tau, t5, w, rho, log_stream);\n\t\t\t\t\t}\n\t\t\t\t\telse if (tau >= t5) { //laser after echo\n\n\t\t\t\t\t}\n\t\t\t\t\telse {\t}\n\n\t\t\n\n\t\t\t\t}//end T angle loop\n\t\t\t}//end dipolar angle loop\n\t\t\t\t\n\t\t}//end obs loop\n\n\t\tfirst_part = true;\n\t\tescape_point:;\n\t\tlog_stream.next();\n\n\t\tif (tau < t0) {  //laser before first pulse\n\t\t\tif ((t0 - tau) < t_tau) {\n\t\t\t\tP_list_full_dummy.copy_P_list(reverse_P_list(P_list_full_pulse_pi_2, P_list_full_pulse_2ns, t1  - (tau + t_tau)));\n\t\t\t}\n\t\t\telse {\n\n\t\t\t}\n\n\n\t\t}\n\t\telse if (tau >= t0 && tau < t1) {  //laser during first pulse\n\n\n\t\t\tif ((t1 - tau) < t_tau) {\n\t\t\t\tP_list_full_dummy.copy_P_list(reverse_P_list(P_list_full_time_fid1, P_list_full_time_2ns, t2  - (tau + t_tau)));\n\t\t\t}\n\t\t\telse {\n\t\t\t\tP_list_full_dummy.multiply(P_list_full_pulse_8ns, false);\n\t\t\t}\n\t\t}\n\t\telse if (tau >= t1 && tau < t2) { //laser during first fid\n\n\t\t\tif ((t2 - tau) < t_tau) {\n\t\t\t\tP_list_full_dummy.copy_P_list(reverse_P_list(P_list_full_pulse_pi, P_list_full_pulse_2ns, t3 - (tau + t_tau)));\n\t\t\t}\n\t\t\telse {\n\t\t\t\tP_list_full_dummy.multiply(P_list_full_time_8ns, false);\n\t\t\t}\n\n\t\t}\n\t\telse if (tau >= t2 && tau < t3) { //laser during refocussing pulse\n\n\t\t\tif ((t3 - tau) < t_tau) {\n\t\t\t\tP_list_full_dummy.copy_P_list(reverse_P_list(P_list_full_time_fid2, P_list_full_time_2ns, t4  - (tau + t_tau)));\n\t\t\t}\n\t\t\telse {\n\t\t\t\tP_list_full_dummy.multiply(P_list_full_pulse_8ns, false);\n\t\t\t}\n\n\t\t}\n\t\telse if (tau >= t3 && tau < t4) { //laser during second fid(echo)\n\n\t\t\tif ((t4 - tau) < t_tau) {\n\n\t\t\t}\n\t\t\telse {\n\t\t\t\tP_list_full_dummy.multiply(P_list_full_time_8ns, false);\n\t\t\t}\n\t\t}\n\t\telse if (tau >= t4 && tau < t5) { //laser during echo-detection\n\t\t\n\t\t}\n\t\telse if (tau >= t5) { //laser after echo\n\n\t\t}\n\t\telse {}\n\t\t\t\n\n\t} //end tau loop\t\t\n\tlog_stream.reset();\n\n\n\n\tlog_stream.save_data();\n\t\t\n}\n\n\n", "meta": {"hexsha": "5b9fe1e94b393a2bf063d925d0bbf56889256cfc", "size": 16064, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "source_code/LaserIMD.cpp", "max_stars_repo_name": "andreas-scherer/LaserIMD_simulation", "max_stars_repo_head_hexsha": "ef91f6b8b75772f399325740177bc92b59e055f2", "max_stars_repo_licenses": ["MIT"], "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_code/LaserIMD.cpp", "max_issues_repo_name": "andreas-scherer/LaserIMD_simulation", "max_issues_repo_head_hexsha": "ef91f6b8b75772f399325740177bc92b59e055f2", "max_issues_repo_licenses": ["MIT"], "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_code/LaserIMD.cpp", "max_forks_repo_name": "andreas-scherer/LaserIMD_simulation", "max_forks_repo_head_hexsha": "ef91f6b8b75772f399325740177bc92b59e055f2", "max_forks_repo_licenses": ["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.7836734694, "max_line_length": 214, "alphanum_fraction": 0.70250249, "num_tokens": 5127, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7057850402140659, "lm_q2_score": 0.43398146480389854, "lm_q1q2_score": 0.3062976255887787}}
{"text": "//\n// Created by Dmitri Bagaev on 2019-03-22.\n//\n\n#include \"bayesian.h\"\n\n#define USE_NLOPT\n\n#include <nlopt.hpp>\n\n#include <boost/parameter/aux_/void.hpp>\n\n#include <limbo/opt/nlopt_no_grad.hpp>\n#include <Eigen/Core>\n#include <limbo/kernel/exp.hpp>\n#include <limbo/kernel/squared_exp_ard.hpp>\n#include <limbo/mean/function_ard.hpp>\n#include <limbo/model/gp.hpp>\n#include <limbo/model/gp/kernel_lf_opt.hpp>\n#include <limbo/tools.hpp>\n#include <limbo/tools/macros.hpp>\n#include <limbo/bayes_opt/bo_base.hpp>\n#include <limbo/bayes_opt/boptimizer.hpp>\n#include <limbo/model/gp/kernel_mean_lf_opt.hpp>\n#include <limbo/model/multi_gp.hpp>\n#include <limbo/acqui/gp_ucb.hpp>\n#include <limbo/acqui/ei.hpp>\n\nnamespace INMOST {\n\n    BayesianUniformDistribution::BayesianUniformDistribution() : distribution(0.0, 1.0) {\n        int rank, size;\n\n        MPI_Comm_rank(MPI_COMM_WORLD, &rank);\n        MPI_Comm_size(MPI_COMM_WORLD, &size);\n\n        unsigned int seed = static_cast<unsigned int>(time(NULL));\n\n        if (rank == 0) {\n            for (int i = 1; i < size; i++) {\n                MPI_Send(&seed, 1, MPI_UNSIGNED, i, 0, MPI_COMM_WORLD);\n            }\n        } else {\n            MPI_Status status;\n            MPI_Recv(&seed, 1, MPI_UNSIGNED, 0, 0, MPI_COMM_WORLD, &status);\n        }\n\n        generator.seed(seed);\n    }\n\n    double BayesianUniformDistribution::next() {\n        return distribution(generator);\n    }\n\n    unsigned int BayesianUniformDistribution::operator()(unsigned int n) {\n        return static_cast<unsigned int>(next() * n);\n    }\n\n    unsigned int    BayesianOptimizer::DEFAULT_UNIQUE_POINTS_MAX_COUNT    = 7;\n    unsigned int    BayesianOptimizer::DEFAULT_UNIQUE_POINTS_RANDOM_COUNT = 5;\n    unsigned int    BayesianOptimizer::DEFAULT_INITIAL_ITERATIONS_COUNT   = 5;\n    double          BayesianOptimizer::DEFAULT_INITIAL_ITERATIONS_RADIUS  = 0.2;\n    double          BayesianOptimizer::DEFAULT_MAX_JUMP_BARRIER           = 0.1;\n\n    BayesianOptimizer::BayesianOptimizer(const std::string &name, const OptimizationParameters &space, const OptimizerProperties &properties, std::size_t buffer_capacity) :\n            OptimizerInterface(name, space, properties, buffer_capacity),\n            unique_points_max_count(BayesianOptimizer::DEFAULT_UNIQUE_POINTS_MAX_COUNT),\n            unique_points_random_count(BayesianOptimizer::DEFAULT_UNIQUE_POINTS_RANDOM_COUNT),\n            initial_iterations_count(BayesianOptimizer::DEFAULT_INITIAL_ITERATIONS_COUNT),\n            initial_iterations_radius(BayesianOptimizer::DEFAULT_INITIAL_ITERATIONS_RADIUS),\n            max_jump_barrier(BayesianOptimizer::DEFAULT_MAX_JUMP_BARRIER) {\n\n        if (this->HasProperty(\"unique_points_max_count\")) {\n            unique_points_max_count = static_cast<unsigned int>(std::atoi(this->GetProperty(\"unique_points_max_count\").c_str()));\n        }\n\n        if (this->HasProperty(\"unique_points_random_count\")) {\n            unique_points_random_count = static_cast<unsigned int>(std::atoi(this->GetProperty(\"unique_points_random_count\").c_str()));\n        }\n\n        if (this->HasProperty(\"initial_iterations_count\")) {\n            initial_iterations_count = static_cast<unsigned int>(std::atoi(this->GetProperty(\"initial_iterations_count\").c_str()));\n        }\n\n        if (this->HasProperty(\"initial_iterations_radius\")) {\n            initial_iterations_radius = std::atof(this->GetProperty(\"initial_iterations_radius\").c_str());\n        }\n\n        if (this->HasProperty(\"max_jump_barrier\")) {\n            max_jump_barrier = std::atof(this->GetProperty(\"max_jump_barrier\").c_str());\n        }\n\n    }\n\n    SuggestionChangedParameters BayesianOptimizer::AlgorithmMakeSuggestion() const {\n\n        auto unique  = results.GetLastUniqueEntries(unique_points_max_count);\n        auto entries = parameters.GetParameterEntries();\n\n        std::vector<SuggestionChangedParameter> changed_parameters;\n\n        if (unique.size() == 0) {\n\n            std::size_t index = 0;\n            std::for_each(entries.cbegin(), entries.cend(), [&index, &changed_parameters](const OptimizationParametersEntry &entry) {\n                changed_parameters.emplace_back(SuggestionChangedParameter(index++, entry.first.GetDefaultValue()));\n            });\n\n            return changed_parameters;\n        } else if (unique.size() < initial_iterations_count) {\n\n            std::size_t index = 0;\n            std::for_each(entries.cbegin(), entries.cend(), [&index, &changed_parameters, this, &unique](const OptimizationParametersEntry &entry) {\n                auto parameter = entry.first;\n\n                double min_bound = parameter.GetMinimalValue();\n                double max_bound = parameter.GetMaximumValue();\n\n                double r = random.next() * (max_bound - min_bound) * initial_iterations_radius;\n\n                double next = entry.second + r * (2.0 * (unique.size() % 2) - 1.0);\n\n                while (next < min_bound || next > max_bound) {\n                    r    = random.next() * (max_bound - min_bound) * initial_iterations_radius;\n                    next = entry.second + r * (2.0 * (unique.size() % 2) - 1.0);\n                }\n\n                changed_parameters.emplace_back(SuggestionChangedParameter(index++, next));\n            });\n\n            return changed_parameters;\n        }\n\n        std::random_shuffle(unique.begin() + 1, unique.end(), random);\n\n        struct Params {\n            struct kernel {\n                // BO_PARAM(double, noise, 0.01); default\n                // BO_PARAM(bool, optimize_noise, false); default\n                BO_PARAM(double, noise, 0.01);\n\n                BO_PARAM(bool, optimize_noise, false);\n            };\n\n            struct kernel_squared_exp_ard : public limbo::defaults::kernel_squared_exp_ard {\n                // BO_PARAM(int, k, 0); default\n                // BO_PARAM(double, sigma_sq, 1); default\n\n                BO_PARAM(int, k, 4);\n\n                BO_PARAM(double, sigma_sq, 0.2);\n            };\n\n            struct opt_rprop : public limbo::defaults::opt_rprop {\n            };\n            struct opt_nloptnograd : public limbo::defaults::opt_nloptnograd {\n            };\n\n            struct acqui_ucb {\n                // BO_PARAM(double, alpha, 0.5); default\n\n                BO_PARAM(double, alpha, 0.25);\n            };\n\n            struct acqui_gpucb : public limbo::defaults::acqui_gpucb {\n            };\n            struct acqui_ei : public limbo::defaults::acqui_ei {\n            };\n        };\n\n        using Kernel2_t = limbo::kernel::SquaredExpARD<Params>;\n        using Mean_t = limbo::mean::FunctionARD<Params, limbo::mean::Data<Params>>;\n        using GP2_t = limbo::model::GP<Params, Kernel2_t, Mean_t, limbo::model::gp::KernelMeanLFOpt<Params>>;\n\n        GP2_t gp_ard;\n\n        std::vector<Eigen::VectorXd> samples;\n        std::vector<Eigen::VectorXd> observations;\n\n        std::for_each(unique.cbegin(), unique.cbegin() + std::min(static_cast<std::size_t>(unique_points_random_count), unique.size()), [this, &samples, &observations]\n                (const OptimizationParameterResult &result) {\n            Eigen::VectorXd sample(parameters.Size());\n\n            int i = 0;\n            std::for_each(result.GetPointsAfter().cbegin(), result.GetPointsAfter().cend(), [&i, &sample, this](const OptimizationParameterPoint &point) {\n                auto parameter = parameters.GetParameter(static_cast<size_t>(i));\n\n                double min_bound = parameter.GetMinimalValue();\n                double max_bound = parameter.GetMaximumValue();\n\n                double normalized = (parameter.ExtractValueFromPoint(point) - min_bound) / (max_bound - min_bound); // Normalize here to [0, 1]\n\n                sample(i) = normalized;\n\n                i += 1;\n            });\n\n            samples.push_back(sample);\n            observations.push_back(limbo::tools::make_vector(-1.0 * result.GetMetricsAfter()));\n        });\n\n        double min_observation = (*std::min_element(observations.cbegin(), observations.cend(), [](const Eigen::VectorXd &l, const Eigen::VectorXd &r) {\n            return l(0) < r(0);\n        }))(0);\n\n        double max_observation = (*std::max_element(observations.cbegin(), observations.cend(), [](const Eigen::VectorXd &l, const Eigen::VectorXd &r) {\n            return l(0) < r(0);\n        }))(0);\n\n        std::transform(observations.cbegin(), observations.cend(), observations.begin(), [min_observation, max_observation](const Eigen::VectorXd &ob) {\n            return limbo::tools::make_vector((ob(0) - min_observation) / ((10.0 / 6.0) * (max_observation - min_observation)) + 0.2); // Normalize here to [ 0.2, 0.8 ]\n        });\n\n        gp_ard.compute(samples, observations);\n        gp_ard.optimize_hyperparams();\n\n        using acquiopt_t = limbo::opt::NLOptNoGrad<Params, nlopt::GN_ISRES>;\n        using acquisition_function_t = limbo::acqui::UCB<Params, GP2_t>;\n\n        acquiopt_t             acquiopt;\n        acquisition_function_t acqui(gp_ard, 0);\n\n        auto afun               = limbo::FirstElem();\n        auto acqui_optimization = [&](const Eigen::VectorXd &x, bool g) { return acqui(x, afun, g); };\n\n        Eigen::VectorXd starting_point(parameters.Size());\n\n        int i = 0;\n        std::for_each(parameters.GetParameterEntries().cbegin(), parameters.GetParameterEntries().cend(), [&i, &starting_point](const OptimizationParametersEntry &entry) {\n\n            auto parameter = entry.first;\n\n            double min_bound = parameter.GetMinimalValue();\n            double max_bound = parameter.GetMaximumValue();\n\n            starting_point(i) = (entry.second - min_bound) / (max_bound - min_bound);\n\n            i += 1;\n        });\n\n        Eigen::VectorXd new_sample = acquiopt(acqui_optimization, starting_point, true);\n\n        for (int k = 0; k < parameters.Size(); ++k) {\n            auto parameter = parameters.GetParameter(static_cast<size_t>(k));\n\n            double min_bound = parameter.GetMinimalValue();\n            double max_bound = parameter.GetMaximumValue();\n\n            double barrier = max_jump_barrier;\n            if (std::abs(new_sample(k) - starting_point(k)) > barrier) {\n                new_sample(k) = starting_point(k) + barrier * (new_sample(k) - starting_point(k));\n            }\n\n            changed_parameters.emplace_back(SuggestionChangedParameter(k, (new_sample(k) * (max_bound - min_bound)) + min_bound));\n        }\n\n        return changed_parameters;\n    }\n\n    bool BayesianOptimizer::UpdateSpaceWithLatestResults() {\n        const OptimizationParameterResult &last = results.at(0);\n\n\n        if (last.IsGood() && (last.GetMetricsBefore() < 0.0 || (last.GetMetricsAfter() < last.GetMetricsBefore()))) {\n            parameters.Update(last.GetChangedParameters(), last.GetMetricsAfter());\n            return true;\n        } else {\n            return false;\n        }\n    }\n\n    BayesianOptimizer::~BayesianOptimizer() {}\n\n\n}\n", "meta": {"hexsha": "86170850773abc78d9a203f80a1390cacdf228b3", "size": 10891, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Source/Optimizer/optimizers/bayesian/bayesian.cpp", "max_stars_repo_name": "INM-RAS/INMOST", "max_stars_repo_head_hexsha": "2846aa63c1fc11c406cb2d558646237223183201", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 25.0, "max_stars_repo_stars_event_min_datetime": "2016-03-14T19:34:00.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-17T13:34:59.000Z", "max_issues_repo_path": "Source/Optimizer/optimizers/bayesian/bayesian.cpp", "max_issues_repo_name": "INMOST-DEV/INMOST", "max_issues_repo_head_hexsha": "c2209a6378b0d2ecc2f3ec9a12e0217cca011ca8", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 22.0, "max_issues_repo_issues_event_min_datetime": "2015-01-17T18:43:16.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-26T08:09:43.000Z", "max_forks_repo_path": "Source/Optimizer/optimizers/bayesian/bayesian.cpp", "max_forks_repo_name": "INM-RAS/INMOST", "max_forks_repo_head_hexsha": "2846aa63c1fc11c406cb2d558646237223183201", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 13.0, "max_forks_repo_forks_event_min_datetime": "2015-04-22T16:04:21.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-31T10:51:48.000Z", "avg_line_length": 39.4601449275, "max_line_length": 172, "alphanum_fraction": 0.6281333211, "num_tokens": 2452, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7057850402140659, "lm_q2_score": 0.43398146480389854, "lm_q1q2_score": 0.3062976255887787}}
{"text": "//// DO NOT USE. UNDER CONSTRUCTION.\n\n#include <cstdio>\n#include <string>\n#include <limits>\n#include <set>\n\n#include <boost/algorithm/cxx11/all_of.hpp>\n#include <boost/algorithm/cxx11/any_of.hpp>\n#include <cctbx/error.h>\n// iostream is included by this one\n#include <cctbx/sgtbx/direct_space_asu/proto/asymmetric_unit.h>\n\n#include \"cctbx/maptbx/skeletons.h\"\n\nnamespace cctbx { namespace maptbx\n{\n\ninline bool any_lt(const int3_t &a, const int3_t &b)\n{\n  for(short j=0; j<3; ++j)\n    if( a[j]<b[j] )\n      return true;\n  return false;\n}\n\ninline bool any_lt(const int3_t &a, int b)\n{\n  for(short j=0; j<3; ++j)\n    if( a[j]<b )\n      return true;\n  return false;\n}\n\ninline bool any_ge(const int3_t &a, const int3_t &b)\n{\n  for(short j=0; j<3; ++j)\n    if( a[j]>=b[j] )\n      return true;\n  return false;\n}\n\n// faster version of small size std::set ?\ntemplate<typename T, unsigned short N=1000> class array_as_set :\n  private scitbx::af::small<T,N>\n{\npublic:\n  typedef scitbx::af::small<T,N> buf_t;\n  using buf_t::begin;\n  using buf_t::end;\n  using buf_t::empty;\n  using buf_t::size;\n  using typename buf_t::iterator;\n  using typename buf_t::const_iterator;\n  void insert(const T &v)\n  {\n    iterator l=std::lower_bound(this->begin(), this->end(),v);\n    // *l >= v;\n    if( l!=this->end() )\n    {\n      if( *l != v )\n        this->buf_t::insert(l,v);\n    }\n    else\n        this->buf_t::insert(l,v);\n    //CCTBX_ASSERT( !this->empty() );\n    //CCTBX_ASSERT( std::is_sorted(this->begin(), this->end()) );\n    //CCTBX_ASSERT(std::adjacent_find(this->begin(),this->end())==this->end());\n  }\n};\n\nskeleton swanson(const cctbx::maptbx::asymmetric_map &amap, double sigma)\n{\n  double mean=0., esd=0., mx=-9.E200;\n  const auto &map_data = amap.data().const_ref();\n  for(std::size_t ii=0; ii<map_data.size(); ++ii)\n  {\n    //! @todo discard points outside asu\n    double m = map_data[ii];\n    mean += m;\n    esd += m*m;\n    if( m > mx )\n      mx = m;\n  }\n  mean /= map_data.size();\n  esd = esd/map_data.size() - mean*mean;\n  esd = std::sqrt(esd);\n  double mapcutoff = mean + esd * sigma;\n\n  std::vector<xyzm_t> xyzm;\n  xyzm.reserve(10000);\n  //! @todo code duplication: mmtbx::masks::atom_mask::mask_asu\n  std::size_t inside=0, tot=0;\n  const auto &opt_asu = amap.optimized_asu();\n  const double *md = map_data.begin();\n  for(auto i3=amap.grid_begin(); !i3.over(); i3.incr(), ++md)\n  {\n    int3_t p=i3();\n    double m = *md;\n    if( m>mapcutoff )\n    {\n      ++tot;\n      if( opt_asu.where_is(p) != 0 ) // inside or on the face\n      {\n        ++inside;\n        xyzm_t x(p,m);\n        xyzm.push_back( x );\n      }\n    }\n  }\n  std::sort(xyzm.begin(), xyzm.end(),\n    [](const xyzm_t &a, const xyzm_t &b) {return (get<1>(a)) > (get<1>(b));}\n  );\n\n  CCTBX_ASSERT( get<1>(xyzm.front()) == mx );\n  marks_t marks(map_data.accessor(), 0UL); // 0 means no mark\n  std::size_t nmarks=0, nbonds=0, min_count = 0, grows_count=0, join_count=0;\n  const unsigned short cube_size = 26; // 3*3 + (3*3-1) + (3*3) == 3^3 - 1\n  typedef int3_t i3t;\n  int3_t cube[cube_size] = {\n    i3t(-1,-1,-1),  i3t(0,-1,-1),  i3t(1,-1,-1),  i3t(-1,0,-1),  i3t(0,0,-1),\n    i3t(1,0,-1),    i3t(-1,1,-1),  i3t(0,1,-1),   i3t(1,1,-1),   i3t(-1,-1,0),\n    i3t(0,-1,0),    i3t(1,-1,0),   i3t(-1,0,0),   i3t(1,0,0),    i3t(-1,1,0),\n    i3t(0,1,0),     i3t(1,1,0),    i3t(-1,-1,1),  i3t(0,-1,1),   i3t(1,-1,1),\n    i3t(-1,0,1),    i3t(0,0,1),    i3t(1,0,1),    i3t(-1,1,1),   i3t(0,1,1),\n    i3t(1,1,1)\n  };\n\n  auto ibox_min = amap.box_begin();\n  auto ibox_max = amap.box_end();\n  skeleton result;\n  result.maximums.reserve(1000);\n  for(std::size_t jj=0; jj<xyzm.size(); ++jj)\n  {\n    // typedef std::set<std::size_t> feature_set_t;\n    typedef array_as_set<std::size_t> feature_set_t;\n    feature_set_t featureset;\n    int3_t x = get<0>(xyzm[jj]);\n    for(unsigned short ic=0; ic<cube_size; ++ic)\n    {\n      int3_t neighbor = x + cube[ic]; //! @todo check if in cell ?\n      if( any_lt(neighbor,ibox_min) || any_ge(neighbor,ibox_max) )\n        continue;\n      unsigned mark = marks(neighbor);\n      if( mark != 0U ) // 0 is not a mark\n        featureset.insert(mark);\n    }\n\n    const unsigned fssize = featureset.size();\n    if( fssize==0U ) // all_eq(featureset, 0) )\n    {\n      // 2a: new maximum\n      ++nmarks;\n      marks(x) = nmarks;\n      result.maximums.push_back(x);\n    }\n    else if( fssize == 1 )\n    {\n      // 2b: part of the growing nodule\n      std::size_t mark = *featureset.begin();\n      CCTBX_ASSERT( mark != 0 );\n      marks(x) = mark;\n      ++grows_count;\n    }\n    else if( fssize == cube_size )\n    {\n      // 2d: local minimum will not be in the neighborhood of any point\n      ++min_count;\n      marks(x) = *featureset.begin(); // highest nodule\n    }\n    else if( fssize>1 )\n    {\n      // 2c: two or more nodules merging\n      ++join_count;\n      marks(x) = *featureset.begin(); // highest nodule\n      for(feature_set_t::const_iterator i=featureset.begin();\n          i!=featureset.end(); ++i)\n      {\n        std::size_t fi = *i;\n        CCTBX_ASSERT( fi>0U && fi<=nmarks );\n        feature_set_t::const_iterator j=i;\n        ++j;\n        for( ; j!=featureset.end(); ++j)\n        {\n          std::size_t fj = *j;\n          CCTBX_ASSERT( fj>0U && fj<=nmarks );\n          CCTBX_ASSERT( fi<fj );\n          join_t join;\n          join.ilt = fi;\n          join.igt = fj;\n          result.joins.insert(join); // inserts only new joins\n        }\n      }\n    }\n  }\n  CCTBX_ASSERT( nmarks + grows_count + join_count + min_count == xyzm.size() );\n  result.min_count = min_count;\n  result.grows_count = grows_count;\n  result.join_count = join_count;\n  result.marks = std::move(marks);\n  result.mapcutoff = mapcutoff;\n  return result;\n}\n\nstd::vector<std::size_t> find_clusters(const skeleton &skelet)\n{\n  std::size_t nmaxs = skelet.maximums.size(), mol_id=0;\n  std::vector<std::size_t> atoms(nmaxs,0);\n  for(joins_t::const_iterator i=skelet.joins.begin(); i!=skelet.joins.end();\n    ++i)\n  {\n    const join_t &join = *i;\n    long i_cat = join.ilt;\n    long i_an = join.igt;\n    CCTBX_ASSERT( i_cat < i_an && i_cat>0 && i_an>0 && i_cat<=nmaxs\n      && i_an<=nmaxs );\n    if( atoms[i_cat-1U]==0 && atoms[i_an-1U]==0 )\n    {\n      ++mol_id;\n      atoms[i_cat] = mol_id;\n      atoms[i_an] = mol_id;\n    }\n    else\n    {\n      if(atoms[i_cat]!=0 && atoms[i_an]!=0 && atoms[i_cat]!=atoms[i_an])\n      {\n        std::size_t imn = std::min(atoms[i_cat],atoms[i_an]);\n        atoms[i_cat] = imn;\n        atoms[i_an] = imn;\n      }\n      else\n      {\n        if( atoms[i_cat]!=0 )\n          atoms[i_an] = atoms[i_cat];\n        if( atoms[i_an]!=0 )\n          atoms[i_cat] = atoms[i_an];\n      }\n    }\n  }\n  std::size_t imn = 0, imx=0;\n  do\n  {\n    imx = *std::max_element(atoms.begin(), atoms.end());\n    for(joins_t::const_iterator i=skelet.joins.begin(); i!=skelet.joins.end();\n      ++i)\n    {\n      const join_t &join = *i;\n      long i_cat = join.ilt;\n      long i_an = join.igt;\n      if( atoms[i_cat]==0 || atoms[i_an]==0 )\n        throw std::logic_error(\"disaster\");\n      if( atoms[i_cat] != atoms[i_an] )\n      {\n        imn = std::min(atoms[i_cat],atoms[i_an]);\n        atoms[i_cat] = imn;\n        atoms[i_an] = imn;\n      }\n    }\n  }while( imn!=0 );\n  imx = *std::max_element(atoms.begin(), atoms.end());\n\n  std::vector< array<std::size_t,2> > molecules;\n  molecules.reserve(imx);\n  std::size_t imxsz = 0;\n  for(std::size_t i=0; i<imx; ++i)\n  {\n    imn = std::count(atoms.begin(), atoms.end(), i);\n    array< std::size_t,2 > m = {imn,0};\n    molecules.push_back(m);\n    if( imn!=0 )\n      ++mol_id;\n    if( imn>imxsz )\n    {\n      imx = i;\n      imxsz = imn;\n    }\n  }\n  if( imx!=0 )\n  {\n    mol_id = 1;\n    for(std::size_t i=0; i<molecules.size(); ++i)\n    {\n      get<1>(molecules[i]) = mol_id;\n      ++mol_id;\n    }\n  }\n  std::vector<std::size_t> molids;\n  for(std::size_t i=0; i<atoms.size(); ++i)\n  {\n    if( atoms[i] == 0 )\n      continue; // ?\n    molids.push_back( get<1>(molecules[atoms[i]]) );\n  }\n  return molids;\n}\n\n}} // cctbx::maptbx\n", "meta": {"hexsha": "28fc266aa53aa9b0fd593aeb89d7f70a05a1641d", "size": 8019, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cctbx/maptbx/skeletons.cpp", "max_stars_repo_name": "rimmartin/cctbx_project", "max_stars_repo_head_hexsha": "644090f9432d9afc22cfb542fc3ab78ca8e15e5d", "max_stars_repo_licenses": ["BSD-3-Clause-LBNL"], "max_stars_count": 155.0, "max_stars_repo_stars_event_min_datetime": "2016-11-23T12:52:16.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T15:35:44.000Z", "max_issues_repo_path": "cctbx/maptbx/skeletons.cpp", "max_issues_repo_name": "rimmartin/cctbx_project", "max_issues_repo_head_hexsha": "644090f9432d9afc22cfb542fc3ab78ca8e15e5d", "max_issues_repo_licenses": ["BSD-3-Clause-LBNL"], "max_issues_count": 590.0, "max_issues_repo_issues_event_min_datetime": "2016-12-10T11:31:18.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T23:10:09.000Z", "max_forks_repo_path": "cctbx/maptbx/skeletons.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": 26.9093959732, "max_line_length": 79, "alphanum_fraction": 0.5634118967, "num_tokens": 2756, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7057850278370112, "lm_q2_score": 0.43398146480389854, "lm_q1q2_score": 0.30629762021736645}}
{"text": "//#include <boost/program_options.hpp>\n//namespace po = boost::program_options;\n\n//#include <vector>\n#include <iostream>\n#include <complex>\n\n//#include <stdio.h>\n\n#include <fftw3.h>\n\n//#include <tiffio.h>\n\n#define cimg_use_tiff\n#include <CImg.h>\nusing namespace cimg_library;\n\n#ifdef _WIN32\n#define _USE_MATH_DEFINES\n#define rint(fp) (int)((fp) >= 0 ? (fp) + 0.5 : (fp) - 0.5)\n#endif\n\n#include <math.h>\n\n\n\nextern int save_tiff(TIFF *tif, const unsigned int directory, int colind, const int nwaves, int width, int height, float * buffer);\nextern int load_tiff(TIFF *const tif, const unsigned int directory, const unsigned colind, float *const buffer);\n\nfloat fitparabola(float a1, float a2, float a3);\nvoid determine_center_and_background(float *stack5phases, int nx, int ny, int nz, float *xc, float *yc, float *zc, float *background);\nvoid shift_center(std::complex<float> *bands, int nx, int ny, int nz, float xc, float yc, float zc);\nvoid cleanup(std::complex<float> *otfkxkz, int nx, int nz, float dkr, float dkz, float linespacing, int lambdanm, int twolens, float NA, float NIMM);\nvoid radialft(std::complex<float> *bands, int nx, int ny, int nz, std::complex<float> *avg);\n\nbool fixorigin(std::complex<float> *otfkxkz, int nx, int nz, int kx2);\nvoid rescale(std::complex<float> *otfkxkz, int nx, int nz);\n\n\n#ifdef _WIN32\n#ifdef RADIALFT_IMPORT\n  #define RADIALFT_API __declspec( dllimport )\n#else\n  #define RADIALFT_API __declspec( dllexport )\n#endif\n#else\n  #define RADIALFT_API\n#endif\n\nextern \"C\" {\nRADIALFT_API int makeOTF(const char *const ifiles, const char *const ofiles,\n      int lambdanm = 520, float dz = 0.102, int interpkr = 10,\n      bool bUserBackground = false, float background = 90,\n      float NA = 1.25, float NIMM = 1.3, float dr = 0.102,\n      int krmax = 0, bool bDoCleanup = false);\n}\n\n\n\n//   (\"na\", po::value<float>(&NA)->default_value(1.25), \"NA of detection objective\")\n//   (\"nimm\", po::value<float>(&NIMM)->default_value(1.3), \"refractive index of immersion medium\")\n//   (\"xyres\", po::value<float>(&dr)->default_value(.102), \"x-y pixel size\")\n//   (\"zres\", po::value<float>(&dz)->default_value(.102), \"z pixel size\")\n//   (\"wavelength\", po::value<int>(&lambdanm)->default_value(520), \"emission wavelength in nm\")\n//   (\"fixorigin\", po::value<int>(&interpkr)->default_value(10),\n//    \"for all kz, extrapolate using pixels kr=1 to this pixel to get value for kr=0\")\n//   (\"krmax\", po::value<int>(&krmax)->default_value(0),\n//    \"pixels outside this limit will be zeroed (overwriting estimated value from NA and NIMM)\")\n//   (\"nocleanup\", po::bool_switch(&bDoCleanup)->implicit_value(false), \"elect not to do clean-up outside OTF support\")\n//   (\"background\", po::value<float>(&background), \"use user-supplied background instead of the estimated\")\n//   (\"input-file\", po::value<std::string>(&ifiles)->required(), \"input file\")\n//   (\"output-file\", po::value<std::string>(&ofiles)->required(), \"output file\")\n\n\nstd::string ifiles, ofiles;\nint nx, ny, nz, nxy;\nint i, j, z;\nfloat dkr, dkz, background, estBackground, xcofm, ycofm, zcofm;\nfloat *floatimage;\nstd::complex<float> *bands, *avg_output;\nfftwf_plan rfftplan3d;\n\n// float dr = 0.102;\n// float dz = 0.102;\n// int interpkr = 10;\n// float NA = 1.25;\n// float NIMM = 1.3;\n// int lambdanm = 520;\n// int krmax = 0;\n// bool bDoCleanup = true;\n// bool bUserBackground = false;\n\nint makeOTF(const char *const ifiles, const char *const ofiles, int lambdanm,\n    float dz, int interpkr, bool bUserBackground, float background,\n    float NA, float NIMM, float dr, int krmax, bool bDoCleanup)\n{\n  printf(\"called\");\n\n  TIFFSetWarningHandler(NULL);\n\n  CImg<> rawtiff(ifiles);\n\n  nz = rawtiff.depth();\n  ny = rawtiff.height();\n  nx = rawtiff.width();\n\n  printf(\"nx=%d, ny=%d, nz=%d\\n\", nx, ny, nz);\n\n  dkr = 1/(ny*dr);\n  dkz = 1/(nz*dz);\n\n  nxy=(nx+2)*ny;\n\n  floatimage = (float *) malloc(nxy*nz*sizeof(float));\n  bands = (std::complex<float> *) floatimage;\n\n // printf(\"Reading data...\\n\\n\");\n\n  for(z=0; z<nz; z++)\n    for (i=0; i<ny; i++) {\n      for (j=0; j<nx; j++)\n        floatimage[z*nxy+i*(nx+2)+j] = rawtiff(j, i, z);\n    }\n\n  /* Before FFT, estimate bead center position */\n  determine_center_and_background(floatimage, nx, ny, nz, &xcofm, &ycofm, &zcofm, &estBackground);\n\n  printf(\"Center of mass is (%.3f, %.3f, %.3f)\\n\", xcofm, ycofm, zcofm);\n\n  if (!bUserBackground)\n    background = estBackground;\n\n  printf(\"Background is %.3f\\n\", background);\n\n  for(z=0; z<nz; z++) {\n    for(i=0;i<ny;i++)\n      for(j=0;j<nx;j++)\n        floatimage[z*nxy + i*(nx+2) + j] -= background;\n  }\n\n  rfftplan3d = fftwf_plan_dft_r2c_3d(nz, ny, nx, floatimage,\n                                     (fftwf_complex *) floatimage, FFTW_ESTIMATE);\n\n  //printf(\"Before fft\\n\");\n\n  fftwf_execute_dft_r2c(rfftplan3d, floatimage, (fftwf_complex *) floatimage);\n\n  fftwf_destroy_plan(rfftplan3d);\n\n  //printf(\"After fft\\n\\n\");\n\n  /* modify the phase of bands, so that it corresponds to FFT of a bead at origin */\n  //printf(\"Shifting center...\\n\");\n\n  shift_center(bands, nx, ny, nz, xcofm, ycofm, zcofm);\n\n  CImg<> output_tiff(nz*2, nx/2+1, 1, 1, 0.f);\n  avg_output = (std::complex<float> *) output_tiff.data();\n\n  radialft(bands, nx, ny, nz, avg_output);\n\n  if (bDoCleanup)\n    cleanup(avg_output, nx, nz, dkr, dkz, 1.0, lambdanm, krmax, NA, NIMM);\n\n  if (interpkr > 0)\n    try {\n    while (!fixorigin(avg_output, nx, nz, interpkr)) {\n      interpkr --;\n      if (interpkr < 4)\n        throw std::runtime_error(\"#pixels < 4 used in kr=0 extrapolation\");\n    }}\n  catch (std::exception &e) {\n    std::cout << \"\\n!!Error occurred: \" << e.what() << std::endl;\n    return 1;\n  }\n\n//  printf(\"%d\\n\", interpkr);\n  rescale(avg_output, nx, nz);\n\n  /* For side bands, combine bandre's and bandim's into bandplus */\n  /* Shouldn't this be done later on the averaged bands? */\n\n  output_tiff.save_tiff(ofiles);\n\n  return 0;\n}\n\n/*  locate peak pixel to subpixel accuracy by fitting parabolas  */\nvoid determine_center_and_background(float *stack3d, int nx, int ny, int nz, float *xc, float *yc, float *zc, float *background)\n{\n  int i, j, k, maxi, maxj, maxk, ind, nxy2, infocus_sec;\n  int iminus, iplus, jminus, jplus, kminus, kplus;\n  float maxval, reval, valminus, valplus;\n  double sum;\n\n  //printf(\"In determine_center_and_background()\\n\");\n  nxy2 = (nx+2)*ny;\n\n  /* Search for the peak pixel */\n  /* Be aware that stack3d is of dimension (nx+2)xnyxnz */\n  maxval=0.0;\n  for(k=0;k<nz;k++)\n    for(i=0;i<ny;i++)\n      for(j=0;j<nx;j++) {\n    ind=k*nxy2+i*(nx+2)+j;\n    reval=stack3d[ind];\n    if( reval > maxval ) {\n      maxval = reval;\n      maxi=i; maxj=j;\n      maxk=k;\n    }\n      }\n\n  iminus = maxi-1; iplus = maxi+1;\n  if( iminus<0 ) iminus+=ny;\n  if( iplus>=ny ) iplus-=ny;\n  jminus = maxj-1; jplus = maxj+1;\n  if( jminus<0 ) jminus+=nx;\n  if( jplus>=nx ) jplus-=nx;\n  kminus = maxk-1; kplus = maxk+1;\n  if( kminus<0 ) kminus+=nz;\n  if( kplus>=nz ) kplus-=nz;\n\n  valminus = stack3d[kminus*nxy2+maxi*(nx+2)+maxj];\n  valplus  = stack3d[kplus *nxy2+maxi*(nx+2)+maxj];\n  *zc = maxk + fitparabola(valminus, maxval, valplus);\n\n  *zc += 0.6;\n\n  valminus = stack3d[maxk*nxy2+iminus*(nx+2)+maxj];\n  valplus  = stack3d[maxk*nxy2+iplus *(nx+2)+maxj];\n  *yc = maxi + fitparabola(valminus, maxval, valplus);\n\n  valminus = stack3d[maxk*nxy2+maxi*(nx+2)+jminus];\n  valplus  = stack3d[maxk*nxy2+maxi*(nx+2)+jplus];\n  *xc = maxj + fitparabola(valminus, maxval, valplus);\n\n  sum = 0;\n  infocus_sec = floor(*zc);\n  for (i=0; i<*yc-20; i++)\n    for (j=0; j<nx; j++)\n    sum += stack3d[infocus_sec*nxy2 + i*(nx+2) + j];\n  *background = sum / ((*yc-20)*nx);\n}\n\n/***************************** fitparabola **********************************/\n/*     Fits a parabola to the three points (-1,a1), (0,a2), and (1,a3).     */\n/*     Returns the x-value of the max (or min) of the parabola.             */\n/****************************************************************************/\n\nfloat fitparabola( float a1, float a2, float a3 )\n{\n float slope,curve,peak;\n\n slope = 0.5* (a3-a1);         /* the slope at (x=0). */\n curve = (a3+a1) - 2*a2;       /* (a3-a2)-(a2-a1). The change in slope per unit of x. */\n if( curve == 0 )\n {\n   printf(\"no peak: a1=%f, a2=%f, a3=%f, slope=%f, curvature=%f\\n\",a1,a2,a3,slope,curve);\n   return( 0.0 );\n }\n peak = -slope/curve;          /* the x value where slope = 0  */\n if( peak>1.5 || peak<-1.5 )\n {\n   printf(\"bad peak position: a1=%f, a2=%f, a3=%f, slope=%f, curvature=%f, peak=%f\\n\",a1,a2,a3,slope,curve,peak);\n   return( 0.0 );\n }\n return( peak );\n}\n\n\n/* To get rid of checkerboard effect in the OTF bands */\n/* (xc, yc, zc) is the estimated center of the point source, which in most cases is the bead */\n/* Converted from Fortran code. kz is treated differently than kx and ky. don't know why */\nvoid shift_center(std::complex<float> *bands, int nx, int ny, int nz, float xc, float yc, float zc)\n{\n  int kin, iin, jin, indin, nxy, kz, kx, ky, kycent, kxcent, kzcent;\n  std::complex<float> exp_iphi;\n  float phi1, phi2, phi, dphiz, dphiy, dphix;\n\n  kycent = ny/2;\n  kxcent = nx/2;\n  kzcent = nz/2;\n  nxy = (nx/2+1)*ny;\n\n  dphiz = 2*M_PI*zc/nz;\n  dphiy = 2*M_PI*yc/ny;\n  dphix = 2*M_PI*xc/nx;\n\n  for (kin=0; kin<nz; kin++) {    /* the origin of Fourier space is at (0,0) */\n    kz = kin;\n    if (kz>kzcent) kz -= nz;\n    phi1 = dphiz*kz;      /* first part of phi */\n    for (iin=0; iin<ny; iin++) {\n      ky = iin;\n      if (iin>kycent) ky -= ny;\n      phi2 = dphiy*ky;   /* second part of phi */\n      for (jin=0; jin<kxcent+1; jin++) {\n        kx = jin;\n        indin = kin*nxy+iin*(nx/2+1)+jin;\n        phi = phi1+phi2+dphix*kx;  /* third part of phi */\n        /* kz part of Phi has a minus sign, I don't know why. */\n        exp_iphi = std::complex<float> (cos(phi), sin(phi));\n        bands[indin] = bands[indin] * exp_iphi;\n      }\n    }\n  }\n}\n\nvoid radialft(std::complex<float> *band, int nx, int ny, int nz, std::complex<float> *avg_output)\n{\n  int kin, iin, jin, indin, indout, indout_conj, kz, kx, ky, kycent, kxcent, kzcent;\n  int *count, nxz, nxy;\n  float rdist;\n\n  printf(\"In radialft()\\n\");\n  kycent = ny/2;\n  kxcent = nx/2;\n  kzcent = nz/2;\n  nxy = (nx/2+1)*ny;\n  nxz = (nx/2+1)*nz;\n\n  count = (int *) calloc(nxz, sizeof(int));\n\n  if (!count) {\n    printf(\"No memory availale in radialft()\\n\");\n    exit(-1);\n  }\n\n  for (kin=0; kin<nz; kin++) {\n    kz = kin;\n    if (kin>kzcent) kz -= nz;\n    for (iin=0; iin<ny; iin++) {\n      ky = iin;\n      if (iin>kycent) ky -= ny;\n      for (jin=0; jin<kxcent+1; jin++) {\n        kx = jin;\n        rdist = sqrt(kx*kx+ky*ky);\n        if (rdist < nx/2+1) {\n          indin = kin*nxy+iin*(nx/2+1)+jin;\n          indout = rint(rdist)*nz+kin;\n          if (indout < nxz) {\n            avg_output[indout] += band[indin];\n            count[indout] ++;\n          }\n          // printf(\"kz=%d, ky=%d, kx=%d, indout=%d\\n\", kz, ky, kx, indout);\n        }\n      }\n    }\n  }\n\n  for (indout=0; indout<nxz; indout++) {\n    if (count[indout]>0) {\n      avg_output[indout] /= count[indout];\n    }\n  }\n\n  /* Then complete the rotational averaging and scaling*/\n  for (kx=0; kx<nx/2+1; kx++) {\n    indout = kx*nz+0;\n    avg_output[indout] = std::complex<float>(avg_output[indout].real(), 0);\n    for (kz=1; kz<=nz/2; kz++) {\n      indout = kx*nz+kz;\n      indout_conj = kx*nz + (nz-kz);\n      avg_output[indout] = (avg_output[indout] + conj(avg_output[indout_conj])) / 2.f;\n      avg_output[indout_conj] = conj(avg_output[indout]);\n    }\n  }\n  free(count);\n}\n\nvoid cleanup(std::complex<float> *otfkxkz, int nx, int nz, float dkr, float dkz, float linespacing, int lamdanm, int krmax_user, float NA, float NIMM)\n{\n  int ix, iz, kzstart, kzend, icleanup=nx/2+1;\n  float lamda, sinalpha, cosalpha, kr, krmax, beta, kzedge;\n\n\n  lamda = lamdanm * 0.001;\n  sinalpha = NA/NIMM;\n  cosalpha = cos(asin(sinalpha));\n  krmax = 2*NA/lamda;\n  if (krmax_user*dkr<krmax && krmax_user!=0)\n    krmax = krmax_user*dkr;\n\n  printf(\"krmax=%f, lambda=%f\\n\", krmax, lamda);\n  for (ix=0; ix<icleanup; ix++) {\n    kr = ix * dkr;\n    if ( kr <= krmax ) {\n      beta = asin( ( NA - kr*lamda ) /NIMM );\n      kzedge = (NIMM/lamda) * ( cos(beta) - cosalpha );\n      /* kzstart = floor((kzedge/dkz) + 1.999); */ /* In fortran, it's 2.999 */\n      kzstart = rint((kzedge/dkz) + 1);\n      kzend = nz - kzstart;\n      for (iz=kzstart; iz<=kzend; iz++)\n        otfkxkz[ix*nz+iz] = 0;\n    }\n    else {   /* outside of lateral resolution limit */\n      for (iz=0; iz<nz; iz++)\n        otfkxkz[ix*nz+iz] = 0;\n    }\n  }\n}\n\nbool fixorigin(std::complex<float> *otfkxkz, int nx, int nz, int kx2)\n{\n  // linear fit the value at kx=0 using kx in [1, kx2]\n  double mean_kx = (kx2+1)/2.; // the mean of [1, 2, ..., n] is (n+1)/2\n\n  // printf(\"In fixorigin(), kx2=%d\\n\", nx, nz, kx2);\n\n  for (int z=0; z<nz; z++) {\n    std::complex<double> mean_val=0;\n    std::complex<double> slope_numerator=0;\n    std::complex<double> slope_denominat=0;\n\n    for (int x=1; x<=kx2; x++)\n      mean_val += otfkxkz[x*nz + z];\n\n    mean_val /= kx2;\n    for (int x=1; x<=kx2; x++) {\n      std::complex<double> complexval = otfkxkz [x*nz+z];\n      slope_numerator += (x - mean_kx) * (complexval - mean_val);\n      slope_denominat += (x - mean_kx) * (x - mean_kx);\n    }\n    std::complex<double> slope = slope_numerator / slope_denominat;\n    otfkxkz[z] = mean_val - slope * mean_kx;  // intercept at kx=0\n    if (z==0 && std::abs(otfkxkz[z]) <= std::abs(otfkxkz[nz+z])) {\n      return false; // indicating kx2 may be too large\n    }\n  }\n  return true;\n}\n\nvoid rescale(std::complex<float> *otfkxkz, int nx, int nz)\n{\n  int nxz, ind;\n  float valmax=0, mag, scalefactor;\n\n  nxz = (nx/2+1)*nz;\n  for (ind=0; ind<nxz; ind++) {\n    mag = abs(otfkxkz[ind]);\n    if (mag > valmax)\n      valmax = mag;\n  }\n  scalefactor = 1/valmax;\n\n  for (ind=0; ind<nxz; ind++) {\n    otfkxkz[ind] *= scalefactor;\n  }\n}\n\n\n\n", "meta": {"hexsha": "6df50bd1e93fd64cf32e398dde94c40c94431daf", "size": 13844, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/radialft_interface.cpp", "max_stars_repo_name": "abcucberkeley/cudaDecon", "max_stars_repo_head_hexsha": "d21ae81f47701bdd68ba155ccf2be97cf6bc3feb", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 13.0, "max_stars_repo_stars_event_min_datetime": "2020-03-11T18:41:04.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-10T09:46:47.000Z", "max_issues_repo_path": "src/radialft_interface.cpp", "max_issues_repo_name": "abcucberkeley/cudaDecon", "max_issues_repo_head_hexsha": "d21ae81f47701bdd68ba155ccf2be97cf6bc3feb", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 8.0, "max_issues_repo_issues_event_min_datetime": "2019-12-16T15:38:14.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-25T20:38:44.000Z", "max_forks_repo_path": "src/radialft_interface.cpp", "max_forks_repo_name": "abcucberkeley/cudaDecon", "max_forks_repo_head_hexsha": "d21ae81f47701bdd68ba155ccf2be97cf6bc3feb", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 11.0, "max_forks_repo_forks_event_min_datetime": "2019-02-28T22:37:16.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-12T15:05:54.000Z", "avg_line_length": 30.4933920705, "max_line_length": 150, "alphanum_fraction": 0.6022825773, "num_tokens": 4852, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6076631698328917, "lm_q2_score": 0.5039061705290805, "lm_q1q2_score": 0.3062052208820547}}
{"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// debugging.cpp - debugging utilities\n#include <NTL/xdouble.h>\n#include <helib/debugging.h>\n#include <helib/norms.h>\n#include <helib/Context.h>\n#include <helib/Ctxt.h>\n#include <helib/EncryptedArray.h>\n//#include <helib/powerful.h>\n\nnamespace helib {\n\nSecKey* dbgKey = nullptr;\nstd::shared_ptr<const EncryptedArray> dbgEa = nullptr;\nNTL::ZZX dbg_ptxt;\n\n// return the ratio between the real noise <sk,ct> and the estimated one\ndouble realToEstimatedNoise(const Ctxt& ctxt, const SecKey& sk)\n{\n  NTL::xdouble noiseEst = ctxt.getNoiseBound();\n  if (ctxt.isCKKS())\n    noiseEst += ctxt.getRatFactor() * ctxt.getPtxtMag();\n  NTL::xdouble actualNoise = embeddingLargestCoeff(ctxt, sk);\n\n  return NTL::conv<double>(actualNoise / noiseEst);\n}\n\ndouble log2_realToEstimatedNoise(const Ctxt& ctxt, const SecKey& sk)\n{\n  NTL::xdouble noiseEst = ctxt.getNoiseBound();\n  if (ctxt.isCKKS())\n    noiseEst += ctxt.getRatFactor() * ctxt.getPtxtMag();\n  NTL::xdouble actualNoise = embeddingLargestCoeff(ctxt, sk);\n\n  return log(actualNoise / noiseEst) / log(2.0);\n}\n\n// check that real-to-estimated ratio is not too large, print warning otherwise\nvoid checkNoise(const Ctxt& ctxt,\n                const SecKey& sk,\n                const std::string& msg,\n                double thresh)\n{\n  double ratio;\n  if ((ratio = realToEstimatedNoise(ctxt, sk)) > thresh) {\n    std::cerr << \"\\n*** too much noise: \" << msg << \": \" << ratio << \"\\n\";\n  }\n}\n\n// Decrypt and find the l-infinity norm of the result in canonical embedding\nNTL::xdouble embeddingLargestCoeff(const Ctxt& ctxt, const SecKey& sk)\n{\n  const Context& context = ctxt.getContext();\n  NTL::ZZX p, pp;\n  sk.Decrypt(p, ctxt, pp);\n  return embeddingLargestCoeff(pp, context.zMStar);\n}\n\nvoid decryptAndPrint(std::ostream& s,\n                     const Ctxt& ctxt,\n                     const SecKey& sk,\n                     const EncryptedArray& ea,\n                     long flags)\n{\n  const Context& context = ctxt.getContext();\n  std::vector<NTL::ZZX> ptxt;\n  NTL::ZZX p, pp;\n  sk.Decrypt(p, ctxt, pp);\n\n  NTL::xdouble modulus = NTL::xexp(context.logOfProduct(ctxt.getPrimeSet()));\n  NTL::xdouble actualNoise =\n      embeddingLargestCoeff(pp, ctxt.getContext().zMStar);\n  NTL::xdouble noiseEst = ctxt.getNoiseBound();\n  if (ctxt.isCKKS())\n    noiseEst += ctxt.getRatFactor() * ctxt.getPtxtMag();\n\n  s << \"plaintext space mod \" << ctxt.getPtxtSpace()\n    << \", bitCapacity=\" << ctxt.bitCapacity() << \", \\n           |noise|=q*\"\n    << (actualNoise / modulus) << \", |noiseBound|=q*\" << (noiseEst / modulus);\n  if (ctxt.isCKKS()) {\n    s << \", \\n           ratFactor=\" << ctxt.getRatFactor()\n      << \", ptxtMag=\" << ctxt.getPtxtMag()\n      << \", realMag=\" << (actualNoise / ctxt.getRatFactor());\n  }\n  s << std::endl;\n\n  if (flags & FLAG_PRINT_ZZX) {\n    s << \"   before mod-p reduction=\";\n    printZZX(s, pp) << std::endl;\n  }\n  if (flags & FLAG_PRINT_POLY) {\n    s << \"   after mod-p reduction=\";\n    printZZX(s, p) << std::endl;\n  }\n  if (flags & FLAG_PRINT_VEC) { // decode to a vector of ZZX\n    ea.decode(ptxt, p);\n    if (ea.getAlMod().getTag() == PA_zz_p_tag &&\n        ctxt.getPtxtSpace() != ea.getAlMod().getPPowR()) {\n      long g = NTL::GCD(ctxt.getPtxtSpace(), ea.getAlMod().getPPowR());\n      for (long i = 0; i < ea.size(); i++)\n        PolyRed(ptxt[i], g, true);\n    }\n    s << \"   decoded to \";\n    if (deg(p) < 40) // just pring the whole thing\n      s << ptxt << std::endl;\n    else if (ptxt.size() == 1) // a single slot\n      printZZX(s, ptxt[0]) << std::endl;\n    else { // print first and last slots\n      printZZX(s, ptxt[0], 20) << \"--\";\n      printZZX(s, ptxt[ptxt.size() - 1], 20) << std::endl;\n    }\n  } else if (flags & FLAG_PRINT_DVEC) { // decode to a vector of doubles\n    const EncryptedArrayCx& eacx = ea.getCx();\n    std::vector<double> v;\n    eacx.decrypt(ctxt, sk, v);\n    printVec(s << \"           \", v, 20) << std::endl;\n  } else if (flags & FLAG_PRINT_XVEC) { // decode to a vector of complex\n    const EncryptedArrayCx& eacx = ea.getCx();\n    std::vector<cx_double> v;\n    eacx.decrypt(ctxt, sk, v);\n    printVec(s << \"           \", v, 20) << std::endl;\n  }\n}\n\nbool decryptAndCompare(const Ctxt& ctxt,\n                       const SecKey& sk,\n                       const EncryptedArray& ea,\n                       const PlaintextArray& pa)\n{\n  PlaintextArray ppa(ea);\n  ea.decrypt(ctxt, sk, ppa);\n\n  return equals(ea, pa, ppa);\n}\n\n// Compute decryption with.without mod-q on a vector of ZZX'es,\n// useful when debugging bootstrapping (after \"raw mod-switch\")\nvoid rawDecrypt(NTL::ZZX& plaintxt,\n                const std::vector<NTL::ZZX>& zzParts,\n                const DoubleCRT& sKey,\n                long q)\n{\n  const Context& context = sKey.getContext();\n\n  // Set to zzParts[0] + sKey * zzParts[1] \"over the integers\"\n  DoubleCRT ptxt = sKey;\n  ptxt *= zzParts[1];\n  ptxt += zzParts[0];\n\n  // convert to coefficient representation\n  ptxt.toPoly(plaintxt);\n\n  if (q > 1)\n    PolyRed(plaintxt, q, false /*reduce to [-q/2,1/2]*/);\n}\n\nvoid CheckCtxt(const Ctxt& c, const char* label)\n{\n  std::cerr << \"  \" << label\n            << \", log2(modulus/noise)=\" << (-c.log_of_ratio() / log(2.0))\n            << \", p^r=\" << c.getPtxtSpace();\n\n  if (dbgKey) {\n    double ratio = log2_realToEstimatedNoise(c, *dbgKey);\n    std::cerr << \", log2(noise/bound)=\" << ratio;\n    if (ratio > 0)\n      std::cerr << \" BAD-BOUND\";\n  }\n\n#if 0\n  // This is not really a useful test\n\n  if (dbgKey && c.getContext().isBootstrappable()) {\n    Ctxt c1(c);\n    //c1.dropSmallAndSpecialPrimes();\n\n    const Context& context = c1.getContext();\n    const RecryptData& rcData = context.rcData;\n    const PAlgebra& palg = context.zMStar;\n\n    NTL::ZZX p, pp;\n    dbgKey->Decrypt(p, c1, pp);\n    NTL::Vec<NTL::ZZ> powerful;\n    rcData.p2dConv->ZZXtoPowerful(powerful, pp);\n\n    NTL::ZZ q;\n    q = context.productOfPrimes(c1.getPrimeSet());\n    vecRed(powerful, powerful, q, false);\n\n    NTL::ZZX pp_alt;\n    rcData.p2dConv->powerfulToZZX(pp_alt, powerful);\n\n    NTL::xdouble max_coeff = NTL::conv<NTL::xdouble>(largestCoeff(pp));\n    NTL::xdouble max_pwrfl = NTL::conv<NTL::xdouble>(largestCoeff(powerful));\n    NTL::xdouble max_canon = embeddingLargestCoeff(pp_alt, palg);\n    double ratio = log(max_pwrfl/max_canon)/log(2.0);\n\n    //cerr << \", max_coeff=\" << max_coeff;\n    //cerr << \", max_pwrfl=\" << max_pwrfl;\n    //cerr << \", max_canon=\" << max_canon;\n    std::cerr << \", log2(max_pwrfl/max_canon)=\" << ratio;\n    if (ratio > 0) std::cerr << \" BAD-BOUND\";\n  }\n#endif\n\n  std::cerr << std::endl;\n}\n\n} // namespace helib\n", "meta": {"hexsha": "73cbffb9a649ce45a296c9463d6a775f4377a7c6", "size": 7207, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/debugging.cpp", "max_stars_repo_name": "Souhail-MEFTAH/HElib", "max_stars_repo_head_hexsha": "5f97813b99407d6f9a6251cee920b4e419edc028", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/debugging.cpp", "max_issues_repo_name": "Souhail-MEFTAH/HElib", "max_issues_repo_head_hexsha": "5f97813b99407d6f9a6251cee920b4e419edc028", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/debugging.cpp", "max_forks_repo_name": "Souhail-MEFTAH/HElib", "max_forks_repo_head_hexsha": "5f97813b99407d6f9a6251cee920b4e419edc028", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-11-18T14:03:29.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-18T14:03:29.000Z", "avg_line_length": 32.7590909091, "max_line_length": 79, "alphanum_fraction": 0.6220341335, "num_tokens": 2129, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.30620522088205465}}
{"text": "/*\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 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\" 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 THE COPYRIGHT HOLDER 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#include \"itkio.h\"\n#include \"miaImageProcessing.h\"\n\n#include <cstdio>\n#include <cmath>\n\n#include <vector>\n#include <string>\n#include <sstream> //for ostringstream.\n#include <fstream>\n#include \"densecrf.h\"\n\n#include \"ioparsing.hpp\"\n#include \"parameters.h\"\n#include <boost/program_options.hpp>\n#include <boost/filesystem.hpp>\n#include <chrono>\n\nnamespace po = boost::program_options;\nnamespace fs = boost::filesystem;\n\nusing namespace mia;\n\nstd::vector<Image> load_multi_channel_image(std::vector<std::string> image_filenames)\n{\n\n\tstd::vector<Image> images;\n\timages.push_back(itkio::load(image_filenames[0]));\n\n\tfor (int c = 1; c < image_filenames.size(); c++)\n\t{\n\t\tImage img = itkio::load(image_filenames[c]);\n\t\tif (img.size() != images[0].size())\n\t\t{\n\t\t\tstd::cout << \"Image modalities size mismatch! Aborting...\" << std::endl;\n\t\t\texit(0);\n\t\t}\n\t\telse\n\t\t\timages.push_back(img);\n\t}\n\treturn images;\n}\n\nfloat cap_prob(float p)\n{\n\n\treturn std::fmax(0.05, std::fmin(p, 0.95));\n}\n\n//Loads the nii with the unary potentials and makes a matrix that the rest of the original code needs.\nvoid setupUnaryEnergyMatrix(MatrixXf &unaryCosts, std::vector<Image> probmaps, int numberOfForegroundClasses, bool computeBackgroundProbmap = true)\n{\n\n\tint numberOfVoxelsInImage = probmaps[0].size();\n\tint start_class_index = 0;\n\tint numberOfClasses = numberOfForegroundClasses + 1;\n\tif (computeBackgroundProbmap)\n\t\tstart_class_index = 1;\n\n\tfloat eps = 0.001;\n\tunaryCosts.setZero();\n\tfor (int c = 0; c < numberOfForegroundClasses; ++c)\n\t{\n\n\t\tint index = 0;\n\t\tfor (int z = 0; z < probmaps[c].sizeZ(); z++)\n\t\t{\n\t\t\tfor (int y = 0; y < probmaps[c].sizeY(); y++)\n\t\t\t{\n\t\t\t\tfor (int x = 0; x < probmaps[c].sizeX(); x++)\n\t\t\t\t{\n\t\t\t\t\tfloat val = probmaps[c](x, y, z);\n\n\t\t\t\t\tval = -log(cap_prob(probmaps[c](x, y, z)));\n\t\t\t\t\tunaryCosts(c + start_class_index, index) = val;\n\t\t\t\t\tif (computeBackgroundProbmap)\n\t\t\t\t\t\tunaryCosts(0, index) += std::fmax(0, probmaps[c](x, y, z));\n\t\t\t\t\tindex++;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tif (computeBackgroundProbmap)\n\t{\n\t\tint index = 0;\n\t\tfor (int z = 0; z < probmaps[0].sizeZ(); z++)\n\t\t{\n\t\t\tfor (int y = 0; y < probmaps[0].sizeY(); y++)\n\t\t\t{\n\t\t\t\tfor (int x = 0; x < probmaps[0].sizeX(); x++)\n\t\t\t\t{\n\n\t\t\t\t\tunaryCosts(0, index) = -log(cap_prob(1 - unaryCosts(0, index)));\n\t\t\t\t\tindex++;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\nvoid addPairwiseBilateralMultiMod(DenseCRF3D &crf3d, std::vector<float> sXYZ, std::vector<float> sMod, std::vector<Image> &images, LabelCompatibility *function = NULL, KernelType kernel_type = DIAG_KERNEL, NormalizationType normalization_type = NORMALIZE_SYMMETRIC)\n{\n\tint numImages = images.size();\n\tint sizeX = images[0].sizeX();\n\tint sizeY = images[0].sizeY();\n\tint sizeZ = images[0].sizeZ();\n\n\tMatrixXf feature(3 + numImages, images[0].size());\n\tfeature.setZero();\n\tint index = 0;\n\tfor (int z = 0; z < images[0].sizeZ(); z++)\n\t{\n\t\tfor (int y = 0; y < images[0].sizeY(); y++)\n\t\t{\n\t\t\tfor (int x = 0; x < images[0].sizeX(); x++)\n\t\t\t{\n\t\t\t\tfeature(0, index) = x / sXYZ[0];\n\t\t\t\tfeature(1, index) = y / sXYZ[1];\n\t\t\t\tfeature(2, index) = z / sXYZ[2];\n\n\t\t\t\tfor (int imgIdx = 0; imgIdx < numImages; imgIdx++)\n\t\t\t\t\tfeature(3 + imgIdx, index) = images[imgIdx](x, y, z) / sMod[imgIdx];\n\n\t\t\t\tindex++;\n\t\t\t}\n\t\t}\n\t}\n\tcrf3d.addPairwiseEnergy(feature, function, kernel_type, normalization_type);\n}\n\nint main(int argc, char *argv[])\n{\n\n\tParameters params;\n\n\tstd::string config_file;\n\n\tstd::vector<std::string> simages;\n\tstd::vector<std::string> simagelists;\n\tstd::vector<std::string> sprobmaps;\n\tstd::vector<std::string> sprobmaplists;\n\n\tstd::string output_path = \".\";\n\n\tint numberOfModalities = 0;\n\tint numberOfForegroundClasses = 0;\n\tbool computeBackgroundProbmap = true;\n\tbool overwrite_output = false;\n\tbool do_output_probmaps = false;\n\tbool do_output_unary = false;\n\tstd::vector<std::string> sbilateralXYZStds;\n\tstd::vector<std::string> sposXYZStds;\n\tstd::vector<std::string> sbilateralModStds;\n\n\tfloat minIntensity = -3, maxIntensity = +3;\n\n\t//====================================\n\n\ttry\n\t{\n\t\t// Declare the supported options.\n\t\tpo::options_description generic(\"generic options\");\n\t\tgeneric.add_options()(\"help\", \"produce help message\")(\"config\", po::value<std::string>(&config_file), \"configuration file\")(\"probs\", po::bool_switch(&do_output_probmaps)->default_value(false), \"\")(\"unary\", po::bool_switch(&do_output_unary)->default_value(false), \"\")(\"overwrite\", po::bool_switch(&overwrite_output)->default_value(false), \"\");\n\n\t\tpo::options_description config(\"specific options\");\n\t\tconfig.add_options()(\"output\", po::value<std::string>(&output_path), \"output path\")(\"image\", po::value<std::vector<std::string>>(&simages)->multitoken(), \"filename(s) of multi-modality images\")(\"imagelist\", po::value<std::vector<std::string>>(&simagelists)->multitoken(), \"text file(s) listing images\")(\"probmap\", po::value<std::vector<std::string>>(&sprobmaps)->multitoken(), \"filename(s) of multi-modality images\")(\"probmaplist\", po::value<std::vector<std::string>>(&sprobmaplists)->multitoken(), \"text file(s) listing images\")(\"posXYZStds\", po::value<std::vector<std::string>>(&sposXYZStds), \"posXYZStds\")(\"biModStds\", po::value<std::vector<std::string>>(&sbilateralModStds), \"bilateralModStds\")(\"biXYZStds\", po::value<std::vector<std::string>>(&sbilateralXYZStds), \"bilateralXYZStds\")(\"numberOfForegroundClasses\", po::value<int>(&numberOfForegroundClasses), \"numberOfForegroundClasses\")(\"posW\", po::value<float>(&params.posW), \"posW\")(\"biW\", po::value<float>(&params.bilateralW), \"biW\")(\"maxIterations\", po::value<int>(&params.maxIterations), \"maxIteration\");\n\n\t\tpo::options_description cmdline_options(\"options\");\n\t\tcmdline_options.add(generic).add(config);\n\n\t\tpo::options_description config_file_options;\n\t\tconfig_file_options.add(config);\n\n\t\tpo::variables_map vm;\n\n\t\tpo::store(po::parse_command_line(argc, argv, cmdline_options), vm);\n\t\tpo::notify(vm);\n\n\t\tif (vm.count(\"config\"))\n\t\t{\n\t\t\tstd::ifstream ifs(config_file.c_str());\n\t\t\tif (!ifs)\n\t\t\t{\n\t\t\t\tstd::cout << \"cannot open config file: \" << config_file << std::endl;\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tpo::store(parse_config_file(ifs, config_file_options), vm);\n\t\t\t\tpo::notify(vm);\n\t\t\t}\n\t\t}\n\n\t\tif (vm.count(\"help\"))\n\t\t{\n\t\t\tstd::cout << cmdline_options << std::endl;\n\t\t\treturn 0;\n\t\t}\n\t}\n\tcatch (std::exception &e)\n\t{\n\t\tstd::cout << e.what() << std::endl;\n\t\treturn 1;\n\t}\n\n\tif (!fs::exists(output_path)) fs::create_directories(output_path);\n\n\t//================================\n\n\tstd::vector<std::string> images;\n\tstrings_to_values(simages, images);\n\n\tstd::vector<std::string> imagelists;\n\tstrings_to_values(simagelists, imagelists);\n\n\tstrings_to_values(sbilateralXYZStds, params.bilateralXYZStds, true);\n\n\tstrings_to_values(sposXYZStds, params.posXYZStds, true);\n\n\tstd::vector<std::string> probmaps;\n\tstrings_to_values(sprobmaps, probmaps);\n\n\tstd::vector<std::string> probmaplists;\n\tstrings_to_values(sprobmaplists, probmaplists);\n\n\tstd::vector<std::vector<std::string>> image_filenames = parse_multichannel_filepaths(images, imagelists);\n\tstd::vector<std::vector<std::string>> probmap_filenames = parse_multichannel_filepaths(probmaps, probmaplists);\n\n\tint numberOfImages = image_filenames.size();\n\tint numberOfProbChannels = probmap_filenames.size();\n\n\tif (numberOfImages == 0)\n\t{\n\t\tstd::cout << \"No images provided. Aborting...\" << std::endl;\n\t}\n\tif (numberOfProbChannels == 0)\n\t{\n\t\tstd::cout << \"No probmaps provided. Aborting...\" << std::endl;\n\t\texit(EXIT_FAILURE);\n\t}\n\n\tif (numberOfProbChannels == numberOfForegroundClasses)\n\t\tcomputeBackgroundProbmap = true;\n\telse if (numberOfForegroundClasses > 0 && numberOfProbChannels == numberOfForegroundClasses + 1)\n\t\tcomputeBackgroundProbmap = false;\n\telse\n\t{\n\t\tstd::cout << \"number of probmaps mismatches with provided number of foreground classes\" << std::endl;\n\t\texit(EXIT_FAILURE);\n\t}\n\n\tnumberOfModalities = image_filenames[0].size();\n\tint numClasses = numberOfForegroundClasses + 1;\n\n\tparams.setNumberOfModalities(numberOfModalities);\n\tstrings_to_values(sbilateralModStds, params.bilateralModsStds, true);\n\n\tstd::vector<std::vector<Image>> intensity_images;\n\n\tparams.print();\n\n\tfor (int imgIdx = 0; imgIdx < numberOfImages; imgIdx++)\n\t{\n\n\t\tfs::path input_path(image_filenames[imgIdx][0]);\n\n\t\tstd::string basename = fs::basename(input_path);\n\t\tif (fs::extension(basename) != \"\")\n\t\t\tbasename = fs::basename(basename);\n\t\tstd::stringstream base_output_sfilename;\n\t\tstd::stringstream labelmap_output_path;\n\n\t\tbase_output_sfilename << output_path << \"/\" << basename;\n\t\tlabelmap_output_path << base_output_sfilename.str() << \"_labelmap.nii.gz\";\n\n\t\tif (fs::exists(labelmap_output_path.str()))\n\t\t{\n\t\t\tif (!overwrite_output)\n\t\t\t{\n\t\t\t\tstd::cout << labelmap_output_path.str() << \" already exists. skipping.\" << std::endl;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\telse\n\t\t\t\tstd::cout << labelmap_output_path.str() << \" already exists. Overwriting.\" << std::endl;\n\t\t}\n\t\tstd::cout << labelmap_output_path.str() << std::endl;\n\n\t\tnamespace ch = std::chrono;\n\t\tauto start = ch::high_resolution_clock::now();\n\n\t\tstd::cout << \"loading data \" << imgIdx + 1 << \" of \" << image_filenames.size() << \" with \" << numberOfModalities << \" channel(s)\" << std::endl;\n\n\t\tstd::vector<Image> multiChannelImage = load_multi_channel_image(image_filenames[imgIdx]);\n\t\tstd::vector<Image> imageProbmaps = load_multi_channel_image(probmap_filenames[imgIdx]);\n\n\t\tint sizeX = multiChannelImage[0].sizeX();\n\t\tint sizeY = multiChannelImage[0].sizeY();\n\t\tint sizeZ = multiChannelImage[0].sizeZ();\n\n\t\tDenseCRF3D crf3d(sizeX, sizeY, sizeZ, numberOfForegroundClasses + 1);\n\n\t\tstd::cout << \"********** Setting up Unary. **********\" << std::endl;\n\t\tMatrixXf unaryCost = MatrixXf(numClasses, multiChannelImage[0].size());\n\t\tsetupUnaryEnergyMatrix(unaryCost, imageProbmaps, numberOfForegroundClasses, computeBackgroundProbmap);\n\t\tcrf3d.setUnaryEnergy(unaryCost);\n\n\t\tstd::cout << \"********** Setting up Pairwise potentials **********\" << std::endl;\n\t\tcrf3d.addPairwiseGaussian(params.posXYZStds[0],\n\t\t\t\t\t\t\t\t  params.posXYZStds[1],\n\t\t\t\t\t\t\t\t  params.posXYZStds[2],\n\t\t\t\t\t\t\t\t  new PottsCompatibility(params.posW));\n\n\t\taddPairwiseBilateralMultiMod(crf3d,\n\t\t\t\t\t\t\t\t\t params.bilateralXYZStds,\n\t\t\t\t\t\t\t\t\t params.bilateralModsStds,\n\t\t\t\t\t\t\t\t\t multiChannelImage,\n\t\t\t\t\t\t\t\t\t new PottsCompatibility(params.bilateralW));\n\n\t\tstd::cout << \"++++++++++++++++++++++++++ Performing Inference ++++++++++++++++++++++++++\" << std::endl;\n\n\t\tMatrixXf probMapsMatrix = crf3d.inference(params.maxIterations);\n\n\t\tif (do_output_probmaps)\n\t\t{\n\t\t\tImage output_probmap = imageProbmaps[0].clone();\n\t\t\tfor (int i = 0; i < numClasses; ++i)\n\t\t\t{\n\t\t\t\tstd::stringstream output_filename;\n\t\t\t\toutput_filename << base_output_sfilename.str() << \"_probmap\" << i << \".nii.gz\";\n\t\t\t\tint index = 0;\n\t\t\t\tfor (int z = 0; z < imageProbmaps[0].sizeZ(); z++)\n\t\t\t\t{\n\t\t\t\t\tfor (int y = 0; y < imageProbmaps[0].sizeY(); y++)\n\t\t\t\t\t{\n\t\t\t\t\t\tfor (int x = 0; x < imageProbmaps[0].sizeX(); x++)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\toutput_probmap(x, y, z) = probMapsMatrix(i, index++);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\titkio::save(output_probmap, output_filename.str());\n\t\t\t}\n\t\t}\n\n\t\tif (do_output_unary)\n\t\t{\n\t\t\tImage output_probmap = imageProbmaps[0].clone();\n\t\t\tfor (int i = 0; i < numClasses; ++i)\n\t\t\t{\n\t\t\t\tstd::stringstream output_filename;\n\t\t\t\toutput_filename << base_output_sfilename.str() << \"_unary\" << i << \".nii.gz\";\n\t\t\t\tint index = 0;\n\t\t\t\tfor (int z = 0; z < imageProbmaps[0].sizeZ(); z++)\n\t\t\t\t{\n\t\t\t\t\tfor (int y = 0; y < imageProbmaps[0].sizeY(); y++)\n\t\t\t\t\t{\n\t\t\t\t\t\tfor (int x = 0; x < imageProbmaps[0].sizeX(); x++)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\toutput_probmap(x, y, z) = unaryCost(i, index++);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\titkio::save(output_probmap, output_filename.str());\n\t\t\t}\n\t\t}\n\n\t\tVectorXs segmentationVector = crf3d.currentMap(probMapsMatrix);\n\n\t\tImage output_labelmap = imageProbmaps[0].clone();\n\t\toutput_labelmap.dataType(mia::USHORT);\n\t\tint index = 0;\n\t\tfor (int z = 0; z < imageProbmaps[0].sizeZ(); z++)\n\t\t{\n\t\t\tfor (int y = 0; y < imageProbmaps[0].sizeY(); y++)\n\t\t\t{\n\t\t\t\tfor (int x = 0; x < imageProbmaps[0].sizeX(); x++)\n\t\t\t\t{\n\t\t\t\t\toutput_labelmap(x, y, z) = segmentationVector[index++];\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\titkio::save(output_labelmap, labelmap_output_path.str());\n\n\t\tstd::cout << \"++++++++++++++++++++++++++ Done. ++++++++++++++++++++++++++\" << std::endl;\n\t\tauto stop = ch::high_resolution_clock::now();\n\t\tstd::cout << \"done. took \" << ch::duration_cast<ch::milliseconds>(stop - start).count() << \" ms\" << std::endl;\n\t}\n}\n", "meta": {"hexsha": "0fac22ae0ed6b45172d90f5bbc5bf1becc9d23d0", "size": 13896, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "app/src/dense3DCrfInference.cpp", "max_stars_repo_name": "fk128/dense3dcrf", "max_stars_repo_head_hexsha": "dccdea0545200c5813e5c069761558e76a6c5c28", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-04-08T13:13:49.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-08T13:13:49.000Z", "max_issues_repo_path": "app/src/dense3DCrfInference.cpp", "max_issues_repo_name": "dazzag24/dense3dcrf", "max_issues_repo_head_hexsha": "dccdea0545200c5813e5c069761558e76a6c5c28", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "app/src/dense3DCrfInference.cpp", "max_forks_repo_name": "dazzag24/dense3dcrf", "max_forks_repo_head_hexsha": "dccdea0545200c5813e5c069761558e76a6c5c28", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-04-08T13:13:36.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-08T13:13:36.000Z", "avg_line_length": 33.4843373494, "max_line_length": 1065, "alphanum_fraction": 0.6729994243, "num_tokens": 3851, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6076631556226291, "lm_q2_score": 0.5039061705290805, "lm_q1q2_score": 0.3062052137214157}}
{"text": "/*\n * Copyright (c) 2019, The Regents of the University of California (Regents).\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met:\n *\n *    1. Redistributions of source code must retain the above copyright\n *       notice, this list of conditions and the following disclaimer.\n *\n *    2. Redistributions in binary form must reproduce the above\n *       copyright notice, this list of conditions and the following\n *       disclaimer in the documentation and/or other materials provided\n *       with the distribution.\n *\n *    3. Neither the name of the copyright holder nor the names of its\n *       contributors may be used to endorse or promote products derived\n *       from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\n * Please contact the author(s) of this library if you have any questions.\n * Authors: David Fridovich-Keil   ( dfk@eecs.berkeley.edu )\n */\n\n///////////////////////////////////////////////////////////////////////////////\n//\n// 12D quadrotor dynamics.\n//\n///////////////////////////////////////////////////////////////////////////////\n\n#include <quads/quadrotor12d.h>\n\n#include <math.h>\n#include <ros/ros.h>\n#include <Eigen/Dense>\n#include <string>\n\nnamespace quads {\n\nVector12d Quadrotor12D::operator()(const Vector12d& x,\n                                   const Vector3d& u) const {\n  ROS_ASSERT(initialized_);\n\n  const double gx = std::sin(x(kThetaIdx)) * std::cos(x(kPhiIdx)) / m_;\n  const double gy = -std::sin(x(kPhiIdx)) / m_;\n  const double gz = std::cos(x(kPhiIdx)) * std::cos(x(kThetaIdx)) / m_;\n\n  Vector12d xdot;\n  xdot << x(kDxIdx), x(kDyIdx), x(kDzIdx), x(kQIdx), x(kRIdx), gx * x(kZetaIdx),\n      gy * x(kZetaIdx), gz * x(kZetaIdx) - 9.81, x(kXiIdx), u(0), u(1) / Ix_,\n      u(2) / Iy_;\n  return xdot;\n}\n\nMatrix12x12d Quadrotor12D::StateJacobian(const Vector12d& x,\n                                         const Vector3d& u) const {\n  const double theta = x(kThetaIdx);\n  const double phi = x(kPhiIdx);\n  const double zeta = x(kZetaIdx);\n\n  Matrix12x12d F;\n  F << 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0,\n      0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0,\n      0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0,\n      zeta * std::cos(phi) * std::cos(theta),\n      -zeta * std::sin(phi) * std::sin(theta), 0, 0, 0,\n      std::cos(phi) * std::sin(theta), 0, 0, 0, 0, 0, 0, 0,\n      -zeta * std::cos(phi), 0, 0, 0, -std::sin(phi), 0, 0, 0, 0, 0, 0,\n      -zeta * std::cos(phi) * std::sin(theta),\n      -zeta * std::cos(theta) * std::sin(phi), 0, 0, 0,\n      std::cos(phi) * std::cos(theta), 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0,\n      0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n      0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0;\n  return F;\n}\n\nMatrix5x12d Quadrotor12D::OutputJacobian(const Vector12d& x) const {\n  Matrix5x12d H(Matrix5x12d::Zero());\n  H(0, 0) = 1.0;\n  H(1, 1) = 1.0;\n  H(2, 2) = 1.0;\n  H(3, 3) = 1.0;\n  H(4, 4) = 1.0;\n  return H;\n}\n\nbool Quadrotor12D::Initialize(const ros::NodeHandle& n) {\n  name_ = ros::names::append(n.getNamespace(), \"quadrotor12d\");\n\n  if (!LoadParameters(n)) {\n    ROS_ERROR(\"%s: Failed to load parameters.\", name_.c_str());\n    return false;\n  }\n\n  initialized_ = true;\n  return true;\n}\n\nbool Quadrotor12D::LoadParameters(const ros::NodeHandle& n) {\n  ros::NodeHandle nl(n);\n\n  // Mass and inertia.\n  if (!nl.getParam(\"dynamics/m\", m_)) return false;\n  if (!nl.getParam(\"dynamics/Ix\", Ix_)) return false;\n  if (!nl.getParam(\"dynamics/Iy\", Iy_)) return false;\n\n  return true;\n}\n\n}  // namespace quads\n", "meta": {"hexsha": "2721d81aad0e0eef101c2185fbc27b60965a12a3", "size": 4494, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ros/src/quads/src/quadrotor12d.cpp", "max_stars_repo_name": "HJReachability/learning_feedback_linearization", "max_stars_repo_head_hexsha": "cb655ade4cfbf53f5dd19f79c943f7665666f2cb", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2020-12-18T01:51:30.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-12T14:49:31.000Z", "max_issues_repo_path": "ros/src/quads/src/quadrotor12d.cpp", "max_issues_repo_name": "HJReachability/learning_feedback_linearization", "max_issues_repo_head_hexsha": "cb655ade4cfbf53f5dd19f79c943f7665666f2cb", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-09-19T22:41:50.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-19T22:41:51.000Z", "max_forks_repo_path": "ros/src/quads/src/quadrotor12d.cpp", "max_forks_repo_name": "HJReachability/learning_feedback_linearization", "max_forks_repo_head_hexsha": "cb655ade4cfbf53f5dd19f79c943f7665666f2cb", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.5365853659, "max_line_length": 80, "alphanum_fraction": 0.6112594571, "num_tokens": 1509, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6477982179521103, "lm_q2_score": 0.4726834766204328, "lm_q1q2_score": 0.3062035138101244}}
{"text": "// This file is part of the reference implementation for the paper\n//   Bayesian Collaborative Denoising for Monte-Carlo Rendering\n//   Malik Boughida and Tamy Boubekeur.\n//   Computer Graphics Forum (Proc. EGSR 2017), vol. 36, no. 4, p. 137-153, 2017\n//\n// All rights reserved. Use of this source code is governed by a\n// BSD-style license that can be found in the LICENSE.txt file.\n\n// BCD headers.\n#include \"bcd/DeepImage.h\"\n#include \"bcd/Denoiser.h\"\n#include \"bcd/IDenoiser.h\"\n#include \"bcd/ImageIO.h\"\n#include \"bcd/MultiscaleDenoiser.h\"\n#include \"bcd/SpikeRemovalFilter.h\"\n#include \"bcd/Utils.h\"\n\n// Eigen headers.\n#include <Eigen/Dense>\n\n// Standard headers.\n#include <cstdlib>\n#include <ctime>\n#include <fstream>\n#include <iostream>\n#include <memory>\n#include <string>\n\nusing namespace std;\nusing namespace bcd;\n\nstatic const char* g_pProgramPath;\n\nclass ProgramArguments\n{\n  public:\n    ProgramArguments() :\n        m_denoisedOutputFilePath(\"\"),\n        m_colorImage(), m_nbOfSamplesImage(), m_histogramImage(), m_covarianceImage(),\n        m_histogramPatchDistanceThreshold(1.f),\n        m_patchRadius(1), m_searchWindowRadius(6),\n        m_minEigenValue(1.e-8f),\n        m_useRandomPixelOrder(false),\n        m_prefilterSpikes(false),\n        m_prefilterThresholdStDevFactor(2.f),\n        m_markedPixelsSkippingProbability(1.f),\n        m_nbOfScales(3),\n        m_nbOfCores(0)\n    {\n    }\n\n    string m_denoisedOutputFilePath; // File path to the denoised image output\n    Deepimf m_colorImage; // Pixel color values\n    Deepimf m_nbOfSamplesImage; // Pixel number of samples\n    Deepimf m_histogramImage; // Pixel histograms\n    Deepimf m_covarianceImage; // Pixel covariances\n    float m_histogramPatchDistanceThreshold; // Histogram patch distance threshold\n    int m_patchRadius; // Patch has (1 + 2 x m_patchRadius)^2 pixels\n    int m_searchWindowRadius; // Search windows (for neighbors) spreads across (1 + 2 x m_patchRadius)^2 pixels\n    float m_minEigenValue; // Minimum eigen value for matrix inversion\n    bool m_useRandomPixelOrder; // True means the pixel will be processed in a random order ; could be useful to remove some \"grid\" artifacts\n    bool m_prefilterSpikes; // True means a spike removal prefiltering will be applied\n    float m_prefilterThresholdStDevFactor; // See SpikeRemovalFilter::filter argument\n    float m_markedPixelsSkippingProbability; // 1 means the marked centers of the denoised patches will be skipped to accelerate a lot the computations\n    int m_nbOfScales;\n    int m_nbOfCores; // Number of cores used by OpenMP. O means using the value defined in environment variable OMP_NUM_THREADS\n};\n\nclass Callbacks\n  : public ICallbacks\n{\n  public:\n    Callbacks()\n    {\n    }\n\n    void progress(const float i_progress) const override\n    {\n    }\n\n    bool isAborted() const override\n    {\n        return false;\n    }\n\n  private:\n    void logInfo(const char* msg) const override\n    {\n        cout << \"Info: \" << msg << std::endl;\n    }\n\n    void logWarning(const char* msg) const override\n    {\n        cout << \"Warning: \" << msg << std::endl;\n    }\n\n    void logError(const char* msg) const override\n    {\n        cout << \"Error: \" << msg << std::endl;\n    }\n\n    void logDebug(const char* msg) const override\n    {\n        cout << \"Debug: \" << msg << std::endl;\n    }\n};\n\nCallbacks g_callbacks;\n\nvoid initializeRandomSeed()\n{\n    srand(static_cast<unsigned int>(time(0)));\n}\n\nstatic void printUsage()\n{\n    ProgramArguments defaultProgramArgs;\n    cout << \"Bayesian Collaborative Denoising\"<< endl << endl;\n    cout << \"Usage: \" << g_pProgramPath << \" <arguments list>\" << endl;\n    cout << \"Only EXR images are supported.\" << endl << endl;\n    cout << \"Required arguments list:\" << endl;\n    cout << \"    -o <output>          The file path to the output image\" << endl;\n    cout << \"    -i <input>           The file path to the input image\" << endl;\n    cout << \"    -h <hist>            The file path to the input histograms buffer\" << endl;\n    cout << \"    -c <cov>             The file path to the input covariance matrices buffer\" << endl;\n    cout << \"Optional arguments list:\" << endl;\n    cout << \"    -d <float>           Histogram patch distance threshold (default: \" << defaultProgramArgs.m_histogramPatchDistanceThreshold << \")\" << endl;\n    cout << \"    -b <int>             Radius of search windows (default: \" << defaultProgramArgs.m_searchWindowRadius << \")\" << endl;\n    cout << \"    -w <int>             Radius of patches (default: \" << defaultProgramArgs.m_patchRadius << \")\" << endl;\n    cout << \"    -r <0/1>             1 for random pixel order (in case of grid artifacts) (default: \" << (defaultProgramArgs.m_useRandomPixelOrder ? 1 : 0) << \")\" << endl;\n    cout << \"    -p <0/1>             1 for a spike removal prefiltering (default: \" << (defaultProgramArgs.m_prefilterSpikes ? 1 : 0) << \")\" << endl;\n    cout << \"    --p-factor <float>   Factor that is multiplied by standard deviation to get the threshold for classifying spikes during prefiltering. Put lower value to remove more spikes (default: \" << defaultProgramArgs.m_prefilterThresholdStDevFactor << \")\" << endl;\n    cout << \"    -m <float in [0,1]>  Probability of skipping marked centers of denoised patches. 1 accelerates a lot the computations. 0 helps removing potential grid artifacts (default: \" << defaultProgramArgs.m_markedPixelsSkippingProbability << \")\" << endl;\n    cout << \"    -s <int>             Number of Scales for Multi-Scaling (default: \" << defaultProgramArgs.m_nbOfScales << \")\" << endl;\n    cout << \"    --ncores <nbOfCores> Number of cores used by OpenMP (default: environment variable OMP_NUM_THREADS)\" << endl;\n    cout << \"    -e <float>           Minimum eigen value for matrix inversion (default: \" << defaultProgramArgs.m_minEigenValue << \")\" << endl;\n}\n\nbool parseProgramArguments(int argc, const char** argv, ProgramArguments& o_rProgramArguments)\n{\n    int argIndex = 0;\n    bool missingColor = true, missingHist = true, missingCov = true, missingOutput = true;\n    string inputColorFilePath;\n    while (++argIndex < argc)\n    {\n        if (strcmp(argv[argIndex], \"-o\") == 0)\n        {\n            argIndex++;\n            if (argIndex == argc)\n            {\n                cout << \"Error in program arguments: expecting file path to the output image after '-o'\" << endl;\n                return false;\n            }\n            o_rProgramArguments.m_denoisedOutputFilePath = string(argv[argIndex]);\n            ofstream outputFile(o_rProgramArguments.m_denoisedOutputFilePath, ofstream::out | ofstream::app);\n            if(!outputFile)\n            {\n                cout << \"Error in program arguments: cannot write output file '\" << o_rProgramArguments.m_denoisedOutputFilePath << \"'\" << endl;\n                return false;\n            }\n            missingOutput = false;\n        }\n        else if (strcmp(argv[argIndex], \"-i\") == 0)\n        {\n            argIndex++;\n            if (argIndex == argc)\n            {\n                cout << \"Error in program arguments: expecting file path to the input color image after '-i'\" << endl;\n                return false;\n            }\n            inputColorFilePath = argv[argIndex];\n            if (!ImageIO::loadEXR(o_rProgramArguments.m_colorImage, argv[argIndex]))\n            {\n                cout << \"Error in program arguments: couldn't load input color image file '\" << argv[argIndex] << \"'\" << endl;\n                return false;\n            }\n            missingColor = false;\n        }\n        else if (strcmp(argv[argIndex], \"-h\") == 0)\n        {\n            argIndex++;\n            if (argIndex == argc)\n            {\n                cout << \"Error in program arguments: expecting file path to the input histogram image after '-h'\" << endl;\n                return false;\n            }\n            Deepimf histAndNbOfSamplesImage;\n            if (!ImageIO::loadMultiChannelsEXR(histAndNbOfSamplesImage, argv[argIndex]))\n            {\n                cout << \"Error in program arguments: couldn't load input histogram image file '\" << argv[argIndex] << \"'\" << endl;\n                return false;\n            }\n            Utils::separateNbOfSamplesFromHistogram(o_rProgramArguments.m_histogramImage, o_rProgramArguments.m_nbOfSamplesImage, histAndNbOfSamplesImage);\n            missingHist = false;\n        }\n        else if (strcmp(argv[argIndex], \"-c\") == 0)\n        {\n            argIndex++;\n            if (argIndex == argc)\n            {\n                cout << \"Error in program arguments: expecting file path to the input covariance matrix image after '-c'\" << endl;\n                return false;\n            }\n            if (!ImageIO::loadMultiChannelsEXR(o_rProgramArguments.m_covarianceImage, argv[argIndex]))\n            {\n                cout << \"Error in program arguments: couldn't load input covariance matrix image file '\" << argv[argIndex] << \"'\" << endl;\n                return false;\n            }\n            missingCov = false;\n        }\n        else if (strcmp(argv[argIndex], \"-d\") == 0)\n        {\n            argIndex++;\n            if (argIndex == argc)\n            {\n                cout << \"Error in program arguments: expecting histogram patch distance threshold after '-d'\" << endl;\n                return false;\n            }\n            istringstream iss(argv[argIndex]);\n            iss >> o_rProgramArguments.m_histogramPatchDistanceThreshold;\n        }\n        else if (strcmp(argv[argIndex], \"-b\") == 0)\n        {\n            argIndex++;\n            if (argIndex == argc)\n            {\n                cout << \"Error in program arguments: expecting radius of search window after '-b'\" << endl;\n                return false;\n            }\n            istringstream iss(argv[argIndex]);\n            iss >> o_rProgramArguments.m_searchWindowRadius;\n        }\n        else if (strcmp(argv[argIndex], \"-w\") == 0)\n        {\n            argIndex++;\n            if (argIndex == argc)\n            {\n                cout << \"Error in program arguments: expecting radius of patch after '-w'\" << endl;\n                return false;\n            }\n            istringstream iss(argv[argIndex]);\n            iss >> o_rProgramArguments.m_patchRadius;\n        }\n        else if (strcmp(argv[argIndex], \"-e\") == 0)\n        {\n            argIndex++;\n            if (argIndex == argc)\n            {\n                cout << \"Error in program arguments: expecting minimum eigen value after '-e'\" << endl;\n                return false;\n            }\n            istringstream iss(argv[argIndex]);\n            iss >> o_rProgramArguments.m_minEigenValue;\n        }\n        else if (strcmp(argv[argIndex], \"-r\") == 0)\n        {\n            argIndex++;\n            if (argIndex == argc)\n            {\n                cout << \"Error in program arguments: expecting 0 or 1 after '-r'\" << endl;\n                return false;\n            }\n            istringstream iss(argv[argIndex]);\n            int useRandomPixelOrder;\n            iss >> useRandomPixelOrder;\n            if(useRandomPixelOrder != 0 && useRandomPixelOrder != 1)\n            {\n                cout << \"Error in program arguments: expecting 0 or 1 after '-r'\" << endl;\n                return false;\n            }\n            o_rProgramArguments.m_useRandomPixelOrder = (useRandomPixelOrder==1);\n        }\n        else if (strcmp(argv[argIndex], \"-p\") == 0)\n        {\n            argIndex++;\n            if (argIndex == argc)\n            {\n                cout << \"Error in program arguments: expecting 0 or 1 after '-p'\" << endl;\n                return false;\n            }\n            istringstream iss(argv[argIndex]);\n            int prefilterSpikes;\n            iss >> prefilterSpikes;\n            if(prefilterSpikes != 0 && prefilterSpikes != 1)\n            {\n                cout << \"Error in program arguments: expecting 0 or 1 after '-p'\" << endl;\n                return false;\n            }\n            o_rProgramArguments.m_prefilterSpikes = (prefilterSpikes==1);\n        }\n        else if (strcmp(argv[argIndex], \"--p-factor\") == 0)\n        {\n            argIndex++;\n            if (argIndex == argc)\n            {\n                cout << \"Error in program arguments: expecting standard deviation factor for spike prefiltering threshold after '--p-factor'\" << endl;\n                return false;\n            }\n            istringstream iss(argv[argIndex]);\n            iss >> o_rProgramArguments.m_prefilterThresholdStDevFactor;\n        }\n        else if(strcmp(argv[argIndex], \"-m\") == 0)\n        {\n            argIndex++;\n            if(argIndex == argc)\n            {\n                cout << \"Error in program arguments: expecting float in [0,1] after '-m'\" << endl;\n                return false;\n            }\n            istringstream iss(argv[argIndex]);\n            float markedPixelsSkippingProbability;\n            iss >> markedPixelsSkippingProbability;\n            if(markedPixelsSkippingProbability < 0 || markedPixelsSkippingProbability > 1)\n            {\n                cout << \"Error in program arguments: expecting float in [0,1] after '-m'\" << endl;\n                return false;\n            }\n            o_rProgramArguments.m_markedPixelsSkippingProbability = markedPixelsSkippingProbability;\n        }\n        else if(strcmp(argv[argIndex], \"-s\") == 0)\n        {\n            argIndex++;\n            if (argIndex == argc)\n            {\n                cout << \"Error in program arguments: expecting number of scales after '-s'\" << endl;\n                return false;\n            }\n            istringstream iss(argv[argIndex]);\n            iss >> o_rProgramArguments.m_nbOfScales;\n        }\n        else if (strcmp(argv[argIndex], \"--ncores\") == 0)\n        {\n            argIndex++;\n            if (argIndex == argc)\n            {\n                cout << \"Error in program arguments: expecting number of cores for OpenMP after '--ncores'\" << endl;\n                return false;\n            }\n            istringstream iss(argv[argIndex]);\n            iss >> o_rProgramArguments.m_nbOfCores;\n        }\n    }\n    if(!missingColor)\n    {\n        if(missingHist)\n        {\n            string inputHistFilePath = inputColorFilePath.substr(0, inputColorFilePath.length() - 4) + \"_hist.exr\"; // \"-4\" for removing extension .exr\n            cout << \"Warning: input histogram file not provided by -h argument: assuming '\" + inputHistFilePath + \"'\" << endl;\n            Deepimf histAndNbOfSamplesImage;\n            if (!ImageIO::loadMultiChannelsEXR(histAndNbOfSamplesImage, inputHistFilePath.c_str()))\n            {\n                cout << \"Error in program arguments: couldn't load input histogram image file '\" << inputHistFilePath << \"'\" << endl;\n                return false;\n            }\n            Utils::separateNbOfSamplesFromHistogram(o_rProgramArguments.m_histogramImage, o_rProgramArguments.m_nbOfSamplesImage, histAndNbOfSamplesImage);\n            missingHist = false;\n        }\n        if(missingCov)\n        {\n            string inputCovFilePath = inputColorFilePath.substr(0, inputColorFilePath.length() - 4) + \"_cov.exr\"; // \"-4\" for removing extension .exr\n            cout << \"Warning: input covariance file not provided by -c argument: assuming '\" + inputCovFilePath + \"'\" << endl;\n            if (!ImageIO::loadMultiChannelsEXR(o_rProgramArguments.m_covarianceImage, inputCovFilePath.c_str()))\n            {\n                cout << \"Error in program arguments: couldn't load input covariance matrix image file '\" << inputCovFilePath << \"'\" << endl;\n                return false;\n            }\n            missingCov = false;\n        }\n    }\n    if (missingColor || missingHist || missingCov || missingOutput)\n    {\n        cout << \"Error: Missing required program argument(s):\";\n        if (missingColor)\n            cout << \" -i\";\n        if (missingHist)\n            cout << \" -h\";\n        if (missingCov)\n            cout << \" -c\";\n        if (missingOutput)\n            cout << \" -o\";\n        cout << endl << endl;\n        printUsage();\n        return false;\n    }\n    return true;\n}\n\nint launchBayesianCollaborativeDenoising(int argc, const char** argv)\n{\n    ProgramArguments programArgs;\n    if(!parseProgramArguments(argc, argv, programArgs))\n        return 1;\n\n    if(programArgs.m_prefilterSpikes)\n        SpikeRemovalFilter::filter(\n                programArgs.m_colorImage,\n                programArgs.m_nbOfSamplesImage,\n                programArgs.m_histogramImage,\n                programArgs.m_covarianceImage,\n                programArgs.m_prefilterThresholdStDevFactor);\n\n    DenoiserInputs inputs;\n    DenoiserOutputs outputs;\n    DenoiserParameters parameters;\n\n    inputs.m_pColors = &(programArgs.m_colorImage);\n    inputs.m_pNbOfSamples = &(programArgs.m_nbOfSamplesImage);\n    inputs.m_pHistograms = &(programArgs.m_histogramImage);\n    inputs.m_pSampleCovariances = &(programArgs.m_covarianceImage);\n\n    Deepimf outputDenoisedColorImage(programArgs.m_colorImage);\n    outputs.m_pDenoisedColors = &outputDenoisedColorImage;\n\n    parameters.m_histogramDistanceThreshold = programArgs.m_histogramPatchDistanceThreshold;\n    parameters.m_patchRadius = programArgs.m_patchRadius;\n    parameters.m_searchWindowRadius = programArgs.m_searchWindowRadius;\n    parameters.m_minEigenValue = programArgs.m_minEigenValue;\n    parameters.m_useRandomPixelOrder = programArgs.m_useRandomPixelOrder;\n    parameters.m_markedPixelsSkippingProbability = programArgs.m_markedPixelsSkippingProbability;\n    parameters.m_nbOfCores = programArgs.m_nbOfCores;\n\n    unique_ptr<IDenoiser> uDenoiser = nullptr;\n\n    if(programArgs.m_nbOfScales > 1)\n        uDenoiser.reset(new MultiscaleDenoiser(programArgs.m_nbOfScales));\n    else\n        uDenoiser.reset(new Denoiser());\n\n    uDenoiser->setCallbacks(&g_callbacks);\n\n    uDenoiser->setInputs(inputs);\n    uDenoiser->setOutputs(outputs);\n    uDenoiser->setParameters(parameters);\n\n    if (!uDenoiser->inputsOutputsAreOk())\n        return 1;\n\n    uDenoiser->denoise();\n\n    ImageIO::writeEXR(outputDenoisedColorImage, programArgs.m_denoisedOutputFilePath.c_str());\n\n    cout << \"Written denoised output in file \" << programArgs.m_denoisedOutputFilePath.c_str() << std::endl;\n\n    return 0;\n}\n\nint main(int argc, const char** argv)\n{\n    g_pProgramPath = argv[0];\n    return launchBayesianCollaborativeDenoising(argc, argv);\n}\n", "meta": {"hexsha": "c9772e4ce5ccea7b82a32642c05893ecd7568951", "size": 18321, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/tools/denoiser/main.cpp", "max_stars_repo_name": "oktomus/appleseed", "max_stars_repo_head_hexsha": "067d2ed3483d97ed58058efbe418299e9dc8ca4f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1907.0, "max_stars_repo_stars_event_min_datetime": "2015-01-04T00:13:22.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T15:14:00.000Z", "max_issues_repo_path": "src/tools/denoiser/main.cpp", "max_issues_repo_name": "oktomus/appleseed", "max_issues_repo_head_hexsha": "067d2ed3483d97ed58058efbe418299e9dc8ca4f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1196.0, "max_issues_repo_issues_event_min_datetime": "2015-01-04T10:50:01.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-04T09:18:22.000Z", "max_forks_repo_path": "src/tools/denoiser/main.cpp", "max_forks_repo_name": "oktomus/appleseed", "max_forks_repo_head_hexsha": "067d2ed3483d97ed58058efbe418299e9dc8ca4f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 373.0, "max_forks_repo_forks_event_min_datetime": "2015-01-06T10:08:53.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-12T10:25:57.000Z", "avg_line_length": 40.5331858407, "max_line_length": 270, "alphanum_fraction": 0.5994760111, "num_tokens": 4168, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.658417500561683, "lm_q2_score": 0.46490157137338844, "lm_q1q2_score": 0.3060993306308653}}
{"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 triclip.hpp\n *  @author Tomas Drinovsky <tomas.drinovsky@citationtech.net>\n *\n *  Triangle clipping stuff based on Jakub Cerveny's code\n */\n\n#ifndef geometry_triclip_hpp_included_\n#define geometry_triclip_hpp_included_\n\n#include <boost/numeric/ublas/vector.hpp>\n#include \"math/geometry_core.hpp\"\n#include \"dbglog/dbglog.hpp\"\n\nnamespace ublas = boost::numeric::ublas;\n\nnamespace geometry { \n\n/** Textured 3D triangle representation suitable for clipping algorithm.\n *\n * Triangle holds positions and tex. coordinates of its vertices.\n */\nstruct ClipTriangle\n{\n        typedef std::vector<ClipTriangle> list;\n        math::Point3 pos[3]; // vertices\n        math::Point2 uv[3];  // texture coordinates\n\n        bool texCoordsAvailable;\n\n        ClipTriangle(math::Point3 a, math::Point3 b, math::Point3 c)\n            : texCoordsAvailable(false)\n        {\n            pos[0] = a, pos[1] = b, pos[2] = c;\n        }\n\n        ClipTriangle(math::Point3 a, math::Point3 b, math::Point3 c,\n                     math::Point2 ta, math::Point2 tb, math::Point2 tc)\n            : texCoordsAvailable(true)\n        {\n            pos[0] = a, pos[1] = b, pos[2] = c;\n            uv[0] = ta, uv[1] = tb, uv[2] = tc;\n        }\n};\n\n/** Clipping plane\n *\n * Plane is defined by it's normal and the shift in the direction of the normal\n */\nstruct ClipPlane\n{\n        math::Point3 normal;\n        double d;\n\n        ClipPlane(double a, double b, double c, double d)\n            : normal(a, b, c), d(d)\n        {}\n\n        ClipPlane()\n            : normal(0, 0, 0), d(0)\n        {}\n};\n\nnamespace detail {\n    inline double signedDistance(const math::Point3 &point, const ClipPlane &plane)\n    {\n        return ublas::inner_prod(point,plane.normal) - plane.d;\n    }\n\n    inline math::Point3 intersection(const math::Point3 &p1, const math::Point3 &p2,\n                       const ClipPlane &plane, double& t)\n    {\n        // sort points to prevent numerical inaccuracies \n        math::Point3 sp1(std::max(p1,p2));\n        math::Point3 sp2(std::min(p1,p2));\n\n        double dot1 = ublas::inner_prod(sp1,plane.normal);\n        double dot2 = ublas::inner_prod(sp2,plane.normal);\n        double den = dot1 - dot2;\n\n        // line parallel with plane, return the midpoint\n        if (std::abs(den) < 1e-10) {\n            t = 0.5;\n            return (sp1 + sp2) * t;\n        }\n\n        t = (dot1 - plane.d) / den;\n        return (1.0 - t)*sp1 + t*sp2;\n    }\n}\n\n/** Clip triangles with given plane\n *\n * \\param triangles list of triangles to be clipped\n * \\param plane plane used to clip triangles \n * \\param triangleInfos additional triangle informations,\n                        each newly created triangle will have same triangleInfo\n                        as it's origin\n * \\return list of the clipped triangles\n */\ntemplate<typename TriangleInfo>\nClipTriangle::list clipTriangles( const ClipTriangle::list &triangles\n                                , const ClipPlane &plane\n                                , std::vector<TriangleInfo> &triangleInfos)\n{\n    ClipTriangle::list result;\n    std::vector<TriangleInfo> resultInfo;\n\n    if (triangleInfos.size() && triangleInfos.size()!=triangles.size()) {\n        LOGTHROW(err3, std::runtime_error)\n            << \"Triangle count and triangle informations count mismatch.\";\n    }\n\n    for ( std::size_t tid=0; tid<triangles.size(); ++tid)\n    {\n        auto &tri(triangles[tid]);\n\n        bool positive[3] = {\n            detail::signedDistance(tri.pos[0], plane) >= 0,\n            detail::signedDistance(tri.pos[1], plane) >= 0,\n            detail::signedDistance(tri.pos[2], plane) >= 0\n        };\n\n        int count = 0;\n        for (int i = 0; i < 3; i++) {\n            if (positive[i]) count++;\n        }\n\n        // triangle completely on negative side - do nothing\n        if (count == 0) continue;\n\n        // trinagle completely on positive side - copy to result\n        if (count == 3) {\n            result.push_back(tri);\n            if(triangleInfos.size()){\n                resultInfo.emplace_back(triangleInfos[tid]);\n            }\n            continue;\n        }\n\n        int a = 0, b = 0, c = 0;\n        double t = 0.0;\n\n        // case 1: one vertex on positive side, just adjust the other two\n        if (count == 1)\n        {\n            if (positive[0]) a = 0, b = 1, c = 2;\n            else if (positive[1]) a = 1, b = 2, c = 0;\n            else a = 2, b = 0, c = 1;\n\n            math::Point3 x1pos(detail::intersection(tri.pos[a], tri.pos[b], plane, t));\n            math::Point2 x1uv((1.0 - t)*tri.uv[a] + t*tri.uv[b]);\n\n            math::Point3 x2pos(detail::intersection(tri.pos[c], tri.pos[a], plane, t));\n            math::Point2 x2uv((1.0 - t)*tri.uv[c] + t*tri.uv[a]);\n\n            result.emplace_back(tri.pos[a], x1pos, x2pos,\n                                tri.uv[a],  x1uv,  x2uv);\n            if(triangleInfos.size()){\n                resultInfo.emplace_back(triangleInfos[tid]);\n            }\n        }\n        // case 2: two vertices on positive side, adjust triangle and add one more\n        else\n        {\n            if (!positive[0]) a = 0, b = 1, c = 2;\n            else if (!positive[1]) a = 1, b = 2, c = 0;\n            else a = 2, b = 0, c = 1;\n\n            auto tmp(1.0 - t);\n            math::Point3 x1pos(detail::intersection(tri.pos[a], tri.pos[b], plane, t));\n            math::Point2 x1uv(tmp*tri.uv[a] + t*tri.uv[b]);\n\n            math::Point3 x2pos(detail::intersection(tri.pos[c], tri.pos[a], plane, t));\n            math::Point2 x2uv(tmp*tri.uv[c] + t*tri.uv[a]);\n\n            result.emplace_back(x1pos, tri.pos[b], tri.pos[c],\n                                x1uv,  tri.uv[b],  tri.uv[c]);\n            if(triangleInfos.size()){\n                resultInfo.emplace_back(triangleInfos[tid]);\n            }\n\n            result.emplace_back(x1pos, tri.pos[c], x2pos,\n                                x1uv,  tri.uv[c],  x2uv);\n            if(triangleInfos.size()){\n                resultInfo.emplace_back(triangleInfos[tid]);\n            }\n        }\n    }\n\n    triangleInfos.swap(resultInfo);\n    return result;\n}\n\n} // namespace geometry\n#endif // geometry_triclip_hpp_included_\n", "meta": {"hexsha": "73fab074bafdcf91c961c2c55951201e4267f04c", "size": 7527, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "geometry/triclip.hpp", "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/triclip.hpp", "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/triclip.hpp", "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": 33.9054054054, "max_line_length": 87, "alphanum_fraction": 0.5868207785, "num_tokens": 1909, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6584175005616829, "lm_q2_score": 0.46490157137338844, "lm_q1q2_score": 0.30609933063086525}}
{"text": "/**\n * @file DynamicsState.hpp\n * @author Brahayam Ponton (brahayam.ponton@tuebingen.mpg.de)\n * @license License BSD-3-Clause\n * @copyright Copyright (c) 2019, New York University and Max Planck Gesellschaft.\n * @date 2019-10-08\n */\n\n#pragma once\n\n#include <array>\n#include <vector>\n#include <string>\n#include <iostream>\n#include <Eigen/Eigen>\n\n#include <momentumopt/setting/Definitions.hpp>\n#include <momentumopt/cntopt/ContactState.hpp>\n\nnamespace momentumopt {\n\n  /**\n   * This class is a container for all variables required to define a\n   * dynamic state: center of mass position, linear and angular momenta\n   * and its rates; forces, torques and center of pressure of the end-\n   * effectors; positions, orientations, activations and contact types\n   * of each end-effector.\n   */\n  struct DynamicsState\n  {\n    public:\n\t  EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n\n    public:\n\t  DynamicsState();\n\t  ~DynamicsState(){}\n\n\t  // Center of mass, linear and angular momenta\n\t  double& time() { return dtime_; }\n\t  Eigen::Vector3d& centerOfMass() { return com_; }\n\t  Eigen::Vector3d& linearMomentum() { return lmom_; }\n\t  Eigen::Vector3d& angularMomentum() { return amom_; }\n\t  Eigen::Vector3d& linearMomentumRate() { return lmomd_; }\n\t  Eigen::Vector3d& angularMomentumRate() { return amomd_; }\n\n\t  const double& time() const { return dtime_; }\n\t  const Eigen::Vector3d& centerOfMass() const { return com_; }\n\t  const Eigen::Vector3d& linearMomentum() const { return lmom_; }\n\t  const Eigen::Vector3d& angularMomentum() const { return amom_; }\n\t  const Eigen::Vector3d& linearMomentumRate() const { return lmomd_; }\n\t  const Eigen::Vector3d& angularMomentumRate() const { return amomd_; }\n\n\t  void time(const double& dtime) { dtime_ = dtime; }\n\t  void centerOfMass(const Eigen::Vector3d& com) { com_ = com; }\n\t  void linearMomentum(const Eigen::Vector3d& lmom) { lmom_ = lmom; }\n\t  void angularMomentum(const Eigen::Vector3d& amom) { amom_ = amom; }\n\t  void linearMomentumRate(const Eigen::Vector3d& lmomd) { lmomd_ = lmomd; }\n\t  void angularMomentumRate(const Eigen::Vector3d& amomd) { amomd_ = amomd; }\n\n\t  void setCenterOfMass(const Eigen::Vector3d& com) {\n\t      std::cout << \"setting CoM to: \" << std::endl;\n\t      com_ = com;\n\t      std::cout << com_ << std::endl;\n\t  }\n\n\t  void setCenterOfMass2(double x, double y, double z) {\n\t      com_ << x, y, z;\n\t  }\n\n      // Endeffector forces, torques and cops\n      Eigen::Vector3d& endeffectorCoP(int eff_id) { return eff_cops_[eff_id]; }\n      Eigen::Vector3d& endeffectorForce(int eff_id) { return eff_forces_[eff_id]; }\n      Eigen::Vector3d& endeffectorTorque(int eff_id) { return eff_torques_[eff_id]; }\n      Eigen::Vector3d& endeffectorTorqueAtContactPoint(int eff_id) { return eefs_trqs_contact_point_[eff_id]; }\n\n      const long endeffectorNum() { return eff_cops_.size(); }\n      const Eigen::Vector3d& endeffectorCoP(int eff_id) const { return eff_cops_[eff_id]; }\n      const Eigen::Vector3d& endeffectorForce(int eff_id) const { return eff_forces_[eff_id]; }\n      const Eigen::Vector3d& endeffectorTorque(int eff_id) const { return eff_torques_[eff_id]; }\n      const Eigen::Vector3d& endeffectorTorqueAtContactPoint(int eff_id) const { return eefs_trqs_contact_point_[eff_id]; }\n\n      const std::vector<Eigen::Vector3d>& pyEndeffectorCops() const { return eff_cops_; }\n      const std::vector<Eigen::Vector3d>& pyEndeffectorForces() const { return eff_forces_; }\n      const std::vector<Eigen::Vector3d>& pyEndeffectorTorques() const { return eff_torques_; }\n\n      void pyEndeffectorCops(const std::vector<Eigen::Vector3d>& eff_cops) { eff_cops_ = eff_cops; }\n      void pyEndeffectorForces(const std::vector<Eigen::Vector3d>& eff_forces) { eff_forces_ = eff_forces; }\n      void pyEndeffectorTorques(const std::vector<Eigen::Vector3d>& eff_torques) { eff_torques_ = eff_torques; }\n\n\t  // Endeffector activations, activation and contact ids\n      int& endeffectorContactId(int eff_id) { return cnt_ids_[eff_id]; }\n      int& endeffectorActivationId(int eff_id) { return eff_ids_[eff_id]; }\n      bool& endeffectorActivation(int eff_id) { return eff_activations_[eff_id]; }\n\n      const int& endeffectorContactId(int eff_id) const { return cnt_ids_[eff_id]; }\n      const int& endeffectorActivationId(int eff_id) const { return eff_ids_[eff_id]; }\n      bool endeffectorActivation(int eff_id) const { return eff_activations_[eff_id]; }\n\n      // endeffector poses\n      Eigen::Vector3d& endeffectorPosition(int eff_id) { return eff_positions_[eff_id]; }\n      Eigen::Vector3d& endeffectorVelocity(int eff_id) { return eff_velocities_[eff_id]; }\n      Eigen::Vector3d& endeffectorAcceleration(int eff_id) { return eff_accelerations_[eff_id]; }\n      Eigen::Quaternion<double>& endeffectorOrientation(int eff_id) { return eff_orientations_[eff_id]; }\n\n      const Eigen::Vector3d& endeffectorPosition(int eff_id) const { return eff_positions_[eff_id]; }\n      const Eigen::Vector3d& endeffectorVelocity(int eff_id) const { return eff_velocities_[eff_id]; }\n      const Eigen::Vector3d& endeffectorAcceleration(int eff_id) const { return eff_accelerations_[eff_id]; }\n      const Eigen::Quaternion<double>& endeffectorOrientation(int eff_id) const { return eff_orientations_[eff_id]; }\n\n      const std::vector<Eigen::Vector3d>& pyEndeffectorPositions() const { return eff_positions_; }\n      void pyEndeffectorPositions(const std::vector<Eigen::Vector3d>& eff_positions) { eff_positions_ = eff_positions; }\n\n\t  // Helper functions\n\t  std::string toString() const;\n\t  friend std::ostream& operator<<(std::ostream &os, const DynamicsState& obj) { return os << obj.toString(); }\n\t  void fillInitialRobotState(const std::string cfg_file, const std::string robot_state = \"initial_robot_configuration\");\n\n    private:\n\t  double dtime_;\n\t  Eigen::Vector3d com_, amom_, lmom_, amomd_, lmomd_;\n      std::array<bool, Problem::n_endeffs_> eff_activations_;\n      std::array<int, Problem::n_endeffs_> eff_ids_, cnt_ids_;\n\n      std::vector<Eigen::Quaternion<double>> eff_orientations_;\n      std::vector<Eigen::Vector3d> eff_positions_, eff_velocities_, eff_accelerations_;\n      std::vector<Eigen::Vector3d> eff_forces_, eff_torques_, eff_cops_, eefs_trqs_contact_point_;\n  };\n\n  /**\n   * This class is a container for a sequence of dynamic states,\n   * for all time steps in the optimization.\n   */\n  class DynamicsSequence\n  {\n    public:\n      EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n\n    public:\n\t  DynamicsSequence(){}\n\t  ~DynamicsSequence(){}\n\n\t  void resize(int num_timesteps);\n\t  void clean() { dynamics_sequence_.clear(); }\n\t  int size() const { return dynamics_sequence_.size(); }\n\n\t  const std::vector<DynamicsState>& dynamicsSequence() const { return dynamics_sequence_; }\n\t  void dynamicsSequence(const std::vector<DynamicsState>& dynamics_sequence) { dynamics_sequence_ = dynamics_sequence; }\n\n\t  void setCoMAtTime(const Eigen::VectorXd& com, int time_id) { dynamics_sequence_[time_id].setCenterOfMass(com); }\n\n      DynamicsState& dynamicsState(int time_id) { return dynamics_sequence_[time_id]; }\n\t  const DynamicsState& dynamicsState(int time_id) const { return dynamics_sequence_[time_id]; }\n\n\t  Eigen::Matrix<int, Problem::n_endeffs_, 1>& activeEndeffectorSteps() { return active_endeffector_steps_; }\n\t  const Eigen::Matrix<int, Problem::n_endeffs_, 1>& activeEndeffectorSteps() const { return active_endeffector_steps_; }\n\n\t  std::string toString() const;\n  \t  friend std::ostream& operator<<(std::ostream &os, const DynamicsSequence& obj) { return os << obj.toString(); }\n\n    private:\n      std::vector<DynamicsState> dynamics_sequence_;\n      Eigen::Matrix<int, Problem::n_endeffs_, 1> active_endeffector_steps_;\n  };\n\n}\n", "meta": {"hexsha": "faf41a43cf4101193d1a8ac5f343d769ba217e03", "size": 7686, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "momentumopt/include/momentumopt/dynopt/DynamicsState.hpp", "max_stars_repo_name": "Neotriple/kino_dynamic_opt", "max_stars_repo_head_hexsha": "abc157d589adf5a0a5d7d25a3c8cad8baaef221d", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-09-28T14:01:21.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-28T14:01:21.000Z", "max_issues_repo_path": "momentumopt/include/momentumopt/dynopt/DynamicsState.hpp", "max_issues_repo_name": "Neotriple/kino_dynamic_opt", "max_issues_repo_head_hexsha": "abc157d589adf5a0a5d7d25a3c8cad8baaef221d", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "momentumopt/include/momentumopt/dynopt/DynamicsState.hpp", "max_forks_repo_name": "Neotriple/kino_dynamic_opt", "max_forks_repo_head_hexsha": "abc157d589adf5a0a5d7d25a3c8cad8baaef221d", "max_forks_repo_licenses": ["BSD-3-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.3012048193, "max_line_length": 123, "alphanum_fraction": 0.7230028623, "num_tokens": 2085, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6584175005616829, "lm_q2_score": 0.46490157137338844, "lm_q1q2_score": 0.30609933063086525}}
{"text": "//==================================================================================================\n/*!\n  @file\n\n  @copyright 2016 NumScale SAS\n\n  Distributed under the Boost Software License, Version 1.0.\n  (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\n**/\n//==================================================================================================\n#ifndef BOOST_SIMD_ALGORITHM_REDUCE_HPP_INCLUDED\n#define BOOST_SIMD_ALGORITHM_REDUCE_HPP_INCLUDED\n\n#include <boost/simd/range/segmented_input_range.hpp>\n#include <boost/simd/function/sum.hpp>\n#include <boost/simd/pack.hpp>\n\nnamespace boost { namespace simd\n{\n  /*!\n    @ingroup group-std\n\n    Computes the sum over elements in the given Contiguous Range @range{first,last} and\n    the initial value @c init.\n\n    \\notebox{The summation order can be different from the order of a sequential summation\n            , thus leading to different results.\n            }\n\n    @par Example:\n    @snippet reduce.simple.cpp reduce-simple\n    Possible output:\n    @code\n    SIMD reduce     : 45\n    STD  accumulate : 45\n    @endcode\n\n    @param first  Beginning of the range of elements to sum\n    @param last   End of the range of elements to sum\n    @param init   Initial value of the sum\n\n    @return The sum of the given value and elements in the given range.\n  **/\n  template<typename T> T reduce(T const* first, T const* last, T init)\n  {\n    pack<T> acc(0);\n    auto pr = segmented_input_range(first,last);\n\n    for( auto const& e : std::get<0>(pr) ) init += e;\n    for( auto const& e : std::get<1>(pr) ) acc  += e;\n    for( auto const& e : std::get<2>(pr) ) init += e;\n\n    return init + sum(acc);\n  }\n\n  /*!\n    @ingroup group-std\n\n    Computes the generalized sum of the elements in the given Contiguous Range @range{first,last}\n    over the binary functions @c binop and @c reduce, using @c init as the initial value.\n\n    While @c binop is applied over the result of dereferencing the input pointers, @c reduce is to\n    be used in the final reduction of the SIMD part of the generalized sum.\n\n    \\notebox{The summation order can be different from the order of a sequential summation\n            , thus leading to different results.\n            }\n\n    @par Example:\n    @snippet reduce.phases.cpp reduce-phases\n    Possible output:\n    @code\n    SIMD reduce     : 285\n    @endcode\n\n    @param first    Beginning of the range of elements to sum\n    @param last     End of the range of elements to sum\n    @param init     Initial value of the reduction\n    @param binop    Binary function object that will be applied in unspecified order to the\n                    result of dereferencing the input pointers, the results of other @c binop\n                    and @ init.\n    @param neutral  Value containing the neutral element of @c binop\n    @param reduce   Binary function object that will be applied to complete the reduction\n\n    @return The generalized sum of the given value and elements in the given range over @ binop.\n  **/\n  template<typename T, typename U, typename F, typename N, typename G>\n  U reduce( T const* first, T const* last, U init, F binop, N neutral, G reduce )\n  {\n    pack<U> acc(neutral);\n    auto pr = segmented_input_range(first,last);\n\n    for( auto const& e : std::get<0>(pr) ) init = binop(init,e);\n    for( auto const& e : std::get<1>(pr) ) acc  = binop(acc,e);\n    for( auto const& e : std::get<2>(pr) ) init = binop(init,e);\n    for( U           e : acc)              init = reduce(init,e);\n\n    return init;\n  }\n\n  /*!\n    @ingroup group-std\n\n    Computes the generalized sum of the elements in the given Contiguous Range @range{first,last}\n    over the binary function @c binop, using @c init as the initial value.\n\n    @c binop is applied over the result of dereferencing the input pointers and in the final\n    reduction of the SIMD part of the generalized sum.\n\n    \\notebox{The summation order can be different from the order of a sequential summation\n            , thus leading to different results.\n            }\n\n    @par Example:\n    @snippet reduce.phase.cpp reduce-phase\n    Possible output:\n    @code\n    SIMD reduce     : 362880\n    @endcode\n\n    @param first    Beginning of the range of elements to sum\n    @param last     End of the range of elements to sum\n    @param init     Initial value of the reduction\n    @param binop    Binary function object that will be applied in unspecified order to the\n                    result of dereferencing the input pointers, the results of other @c binop\n                    and @c init.\n    @param neutral  Value containing the neutral element of @c binop\n\n    @return The sum of the given value and elements in the given range.\n  **/\n  template<typename T, typename U, typename F, typename N>\n  U reduce(T const* first, T const* last, U init, F binop, N neutral)\n  {\n    return reduce(first,last,init,binop,neutral,binop);\n  }\n} }\n\n#endif\n", "meta": {"hexsha": "11b2a290a787beb6f90e28febd5050ae2105a0e8", "size": 4926, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/algorithm/reduce.hpp", "max_stars_repo_name": "xmar/pythran", "max_stars_repo_head_hexsha": "dbf2e8b70ed1e4d4ac6b5f26ead4add940a72592", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2018-02-20T11:21:12.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-12T13:45:09.000Z", "max_issues_repo_path": "third_party/boost/simd/algorithm/reduce.hpp", "max_issues_repo_name": "xmar/pythran", "max_issues_repo_head_hexsha": "dbf2e8b70ed1e4d4ac6b5f26ead4add940a72592", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "third_party/boost/simd/algorithm/reduce.hpp", "max_forks_repo_name": "xmar/pythran", "max_forks_repo_head_hexsha": "dbf2e8b70ed1e4d4ac6b5f26ead4add940a72592", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2017-12-12T12:29:52.000Z", "max_forks_repo_forks_event_max_datetime": "2019-04-08T15:55:25.000Z", "avg_line_length": 35.4388489209, "max_line_length": 100, "alphanum_fraction": 0.6427121397, "num_tokens": 1183, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6370308082623217, "lm_q2_score": 0.48047867804790706, "lm_q1q2_score": 0.3060797206296701}}
{"text": "#include <fstream>\n#include <iostream>\n#include <filesystem>\n#include <string>\n#include <unordered_map>\n#include <algorithm>\n#include <chrono>\n#include <future>\n#include <utility>\n#include <boost/iostreams/filtering_streambuf.hpp>\n#include <boost/iostreams/filter/gzip.hpp>\n#include <xtensor/xarray.hpp>\n#include <xtensor/xmath.hpp>\n#include \"csv.hpp\"\n#include \"../assembly/assembly.cpp\"\n#include \"../probability/probability.cpp\"\n#include \"../probability/probability_util.cpp\"\n#include \"../domain/domain.cpp\"\n#include \"./context.cpp\"\n\nusing namespace std;\nusing namespace std::chrono;\nusing namespace csv;\n\nbool task_compute_domain_probabilities_per_assembly(\n\tconst int task_nb,\n\tconst DomainProbabilityContext ctx,\n\tconst vector<string>& assembly_ids\n) {\n\tauto start = system_clock::now();\n\n\tcerr << \"Thread \" << task_nb << \" started.\" << endl;\n\n\tconst string kind = ctx.kind;\n\tconst string query = ctx.query;\n\tconst string tail = ctx.tail;\n\n\tstring dataFolder = \"../data/\";\n\tstring sequencesFolder = dataFolder + \"sequences/\";\n\tauto n_assemblies = assembly_ids.size();\n\n\tstring metadata_path = dataFolder + query + \"_master.csv\";\n\tauto metadata = LoadDomainMetadata(metadata_path);\n\n\tint i = 0;\n\tfor (auto& accession : assembly_ids) {\n\t\tif (i == 0 || (i+1) % 100 == 0) {\n\t\t\tauto tp = system_clock::now();\n\t\t\tauto elapsed = duration_cast<seconds>(tp - start).count();\n\t\t\tcerr << \"Thread \" << task_nb << \": \";\n\t\t\tcerr << \"Processing assembly \" << i + 1 << \" / \" << n_assemblies;\n\t\t\tcerr << \" (elapsed: \" << elapsed << \" seconds)\" << endl;\n\t\t}\n\t\t++i;\n\n\t\tstring gene_probs_path = (\n\t\t\tsequencesFolder + accession + \"/\" + \n\t\t\taccession + ctx.distance_to_mean_suffix\n\t\t);\n\n\t\ttry {\n\t\t\tifstream gene_probs_file(gene_probs_path);\n\t\t\tGeneProbabilies gene_probs(gene_probs_file, tail);\n\t\t\t\n\t\t\tstring protein_domains_path = (\n\t\t\t\tsequencesFolder + accession + \"/\" + \n\t\t\t\taccession + \"_\" + query + \".csv.gz\"\n\t\t\t);\n\t\t\tifstream protein_domains_file(protein_domains_path);\n\t\t\tboost::iostreams::filtering_streambuf<boost::iostreams::input> inbuf;\n\t\t\tinbuf.push(boost::iostreams::gzip_decompressor());\n\t\t\tinbuf.push(protein_domains_file);\n\t\t\tistream instream(&inbuf);\n\t\t\tProteinDomains domains(instream);\n\n\t\t\tstring outputFolder;\n\t\t\tif (ctx.assembly_output_folder.empty()) {\n\t\t\t\toutputFolder = sequencesFolder + accession;\n\t\t\t} else {\n\t\t\t\toutputFolder = ctx.assembly_output_folder;\n\t\t\t}\n\n\t\t\tstring assembly_domain_prob_out_path;\n\t\t\tif (kind == \"tri-nucleotide\") {\n\t\t\t\tassembly_domain_prob_out_path = (\n\t\t\t\t\toutputFolder + \"/\" + \n\t\t\t\t\taccession + \"_\" + query + \"_probability_\" + tail + \".csv\"\n\t\t\t\t);\n\t\t\t} else {\n\t\t\t\tassembly_domain_prob_out_path = (\n\t\t\t\t\toutputFolder + \"/\" + \n\t\t\t\t\taccession + \"_\" + query + \"_aa_probability_\" + tail + \".csv\"\n\t\t\t\t);\n\t\t\t}\n\t\t\t\n\t\t\tofstream of(assembly_domain_prob_out_path);\n\t\t\tauto writer = make_csv_writer(of);\n\t\t\twriter << DomainProbability::RecordHeader();\n\n\t\t\tvector<DomainProbability> records;\n\t\t\tfor (ProteinDomain& domain : domains.Keys()) {\n\t\t\t\tif (metadata.find(domain.id) != metadata.end()) {\n\t\t\t\t\tauto& [domain_query, domain_description] = metadata[domain.id];\n\t\t\t\t\tdomain.query = domain_query;\n\t\t\t\t\tdomain.description = domain_description;\n\t\t\t\t}\n\n\t\t\t\txt::xarray<double> probs = domains.Probabilities(domain, gene_probs);\n\t\t\t\txt::xarray<double> probs_random = domains.Probabilities(domain, gene_probs, true);\n\n\t\t\t\txt::xarray<double> log_probabilities = xt::eval(xt::log(probs));\n\t\t\t\txt::xarray<double> log_probabilities_random = xt::eval(xt::log(probs_random));\n\n\t\t\t\tdouble log_prob = product_rule_log(log_probabilities);\n\t\t\t\tdouble log_prob_random = product_rule_log(log_probabilities_random);\n\n\t\t\t\tDomainProbability record(\n\t\t\t\t\tdomain, \n\t\t\t\t\tlog_prob, \n\t\t\t\t\tlog_prob_random, \n\t\t\t\t\tlog_probabilities.size()\n\t\t\t\t);\n\t\t\t\trecords.push_back(record);\n\t\t\t}\n\n\t\t\tsort(records.begin(), records.end(), greater<DomainProbability>()); \n\n\t\t\tfor (auto& record : records) {\n\t\t\t\twriter << record.Record();\n\t\t\t}\n\t\t}\n\t\tcatch (exception& e) {\n\t\t\tcerr << \"Thread \" << task_nb << \" | Assembly: \" << accession << \" | \";\n\t\t\tcerr << \"Exception: \" << e.what() << endl;\n\t\t\tthrow;\n\t\t}\n\t}\n\n\tauto tp = system_clock::now();\n\tauto elapsed = duration_cast<seconds>(tp - start).count();\n\tcerr << \"Thread \" << task_nb << \": DONE\";\n\tcerr << \" (elapsed: \" << elapsed << \" seconds)\" << endl;\n\treturn true;\n}\n\nbool task_compute_domain_probabilities_per_phylum(\n\tconst int task_nb,\n\tconst DomainProbabilityContext ctx,\n\tconst vector<string>& phyla,\n\tconst unordered_map<string, vector<string>>& assemblies_per_phylum\n) {\n\tcerr << \"Thread \" << task_nb << \" started.\" << endl;\n\n\tconst string kind = ctx.kind;\n\tconst string query = ctx.query;\n\tconst string tail = ctx.tail;\n\n\tstring dataFolder = \"../data/\";\n\tstring sequencesFolder = dataFolder + \"sequences/\";\n\tstring phylumFolder = dataFolder + \"phylum/\";\n\tauto n_phyla = phyla.size();\n\n\t// Create phylum directory if it does not exist.\n\tfilesystem::create_directory(phylumFolder);\n\n\tint i = 0;\n\tfor (auto& phylum : phyla) {\n\t\tauto& assembly_ids = assemblies_per_phylum.at(phylum);\n\t\tauto n_assemblies = assembly_ids.size();\n\n\t\tcerr << \"Thread \" << task_nb << \": \";\n\t\tcerr << \"Processing phylum \" << i + 1 << \" / \" << n_phyla;\n\t\tcerr << \": \" << phylum << \" (\" << n_assemblies << \" assemblies)\";\n\t\tcerr << endl;\n\t\t++i;\n\n\t\tset<ProteinDomain> protein_domains;\n\t\tunordered_map<ProteinDomain, vector<DomainProbability>> protein_domain_probs;\n\t\tfor (auto& accession : assembly_ids) {\n\t\t\tstring assemblyFolder;\n\t\t\tif (ctx.assembly_output_folder.empty()) {\n\t\t\t\tassemblyFolder = sequencesFolder + accession;\n\t\t\t} else {\n\t\t\t\tassemblyFolder = ctx.assembly_output_folder;\n\t\t\t}\n\n\t\t\tstring path;\n\t\t\tif (kind == \"tri-nucleotide\") {\n\t\t\t\tpath = (\n\t\t\t\t\tassemblyFolder + \"/\" + \n\t\t\t\t\taccession + \"_\" + query + \"_probability_\" + tail + \".csv\"\n\t\t\t\t);\n\t\t\t} else {\n\t\t\t\tpath = (\n\t\t\t\t\tassemblyFolder + \"/\" + \n\t\t\t\t\taccession + \"_\" + query + \"_aa_probability_\" + tail + \".csv\"\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tvector<DomainProbability> domains = LoadDomainProbabilities(path);\n\t\t\tfor (auto& domain_prob : domains) {\n\t\t\t\tauto& domain = domain_prob.domain;\n\t\t\t\tprotein_domains.insert(domain);\n\n\t\t\t\tif (protein_domain_probs.find(domain) == protein_domain_probs.end()) {\n\t\t\t\t\tprotein_domain_probs[domain] = vector<DomainProbability>{domain_prob};\n\t\t\t\t} else {\n\t\t\t\t\tprotein_domain_probs[domain].push_back(domain_prob);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tstring phylum_lower = phylum;\n\t\ttransform(phylum_lower.begin(), phylum_lower.end(), phylum_lower.begin(), ::tolower);\n\t\ttransform(phylum_lower.begin(), phylum_lower.end(), phylum_lower.begin(), [](char ch) {\n\t\t    return ch == ' ' ? '_' : ch;\n\t\t});\n\n\t\tstring phylumDir = phylumFolder + phylum_lower + \"/\";\n\t\tif (!ctx.phylum_output_folder.empty()) {\n\t\t\tphylumDir = ctx.phylum_output_folder + \"/\";\n\t\t}\n\t\tfilesystem::create_directory(phylumDir);\n\n\t\tstring phylum_domain_prob_out_path;\n\t\tif (kind == \"tri-nucleotide\") {\n\t\t\tphylum_domain_prob_out_path = (\n\t\t\t\tphylumDir + \n\t\t\t\tphylum_lower + \"_\" + query + \"_probability_\" + tail + \".csv\"\n\t\t\t);\n\t\t} else {\n\t\t\tphylum_domain_prob_out_path = (\n\t\t\t\tphylumDir + \n\t\t\t\tphylum_lower + \"_\" + query + \"_aa_probability_\" + tail + \".csv\"\n\t\t\t);\n\t\t}\n\n\t\tofstream of(phylum_domain_prob_out_path);\n\t\tauto writer = make_csv_writer(of);\n\t\twriter << DomainProbability::RecordHeader();\n\n\t\tvector<DomainProbability> records;\n\t\tfor (auto& domain : protein_domains) {\n\t\t\tauto& domain_probs = protein_domain_probs[domain];\n\t\t\tauto n_probs = domain_probs.size();\n\t\t\txt::xarray<double> log_probs = xt::zeros<double>({n_probs});\n\t\t\txt::xarray<double> log_probs_random = xt::zeros<double>({n_probs});\n\t\t\tfor (int ix = 0; ix < n_probs; ++ix) {\n\t\t\t\tlog_probs[ix] = domain_probs[ix].log_probability;\n\t\t\t\tlog_probs_random[ix] = domain_probs[ix].log_probability_random;\n\t\t\t}\n\n\t\t\tdouble log_prob = product_rule_log(log_probs);\n\t\t\tdouble log_prob_random = product_rule_log(log_probs_random);\n\n\t\t\ttry {\n\t\t\t\tDomainProbability record(\n\t\t\t\t\tdomain, \n\t\t\t\t\tlog_prob, \n\t\t\t\t\tlog_prob_random,\n\t\t\t\t\tn_probs\n\t\t\t\t);\n\t\t\t\trecords.push_back(record);\n\t\t\t}\n\t\t\tcatch (exception& e) {\n\t\t\t\tcerr << \"Thread \" << task_nb << \" | Phylum: \" << phylum << \" | \";\n\t\t\t\tcerr << \"Exception: \" << e.what() << endl;\n\t\t\t\tthrow;\n\t\t\t}\n\t\t}\n\n\t\tsort(records.begin(), records.end(), greater<DomainProbability>()); \n\n\t\tfor (auto& record : records) {\n\t\t\twriter << record.Record();\n\t\t}\n\t}\n\tcerr << \"Thread \" << task_nb << \": DONE\" << endl;\n\treturn true;\n}\n\nvoid compute_domain_probabilities(const DomainProbabilityContext ctx) {\n\tauto start = system_clock::now();\n\n\tconst string kind = ctx.kind;\n\tconst string query = ctx.query;\n\tconst string tail = ctx.tail;\n\tconst int n_threads = ctx.n_threads;\n\n\tstring dataFolder = \"../data/\";\n\tstring assembliesPath = dataFolder + \"assemblies.csv\";\n\n\tAssemblies assemblies(assembliesPath, ctx.complete_genome_only);\n\tauto assembly_ids = assemblies.GetIds();\n\tauto n_per_thread = ceil((double) assembly_ids.size() / (double) n_threads);\n\n\t// \n\t// 1) Compute probability of domains for each assembly individually.\n\t//\n\tcerr << \"Processing of domain probabilities per assembly\" << endl;\n\tcerr << \"Processing \" << assemblies.Size() << \" assemblies\" << endl;\n\tcerr << \"Starting \" << n_threads << \" threads\" << endl;\n\n\tvector<future<bool>> futures;\n\tfor (int i = 0; i < n_threads; ++i) {\n\t\tauto start = assembly_ids.begin() + i * n_per_thread;\n\t\tauto end = assembly_ids.end();\n\t\tint endInt = i * n_per_thread + n_per_thread;\n\t\tif (endInt < assembly_ids.size()) {\n\t\t\tend = assembly_ids.begin() + endInt;\n\t\t}\n\t\tauto ids = vector<string>(start, end);\n\t\tfutures.push_back(async(\n\t\t\ttask_compute_domain_probabilities_per_assembly, \n\t\t\ti+1, \n\t\t\tctx,\n\t\t\tids\n\t\t));\n\t}\n\tfor (auto& f : futures) {\n\t\tif(!f.get()) {\n\t\t\tthrow runtime_error(\"Unexpected error while processing assembly output\");\n\t\t}\n\t}\n\n\tauto tp = system_clock::now();\n\tauto elapsed = duration_cast<seconds>(tp - start).count();\n\tcerr << \"Processing of domain probabilities per assembly is complete\" << endl;\n\tcerr << \"Elapsed: \" << elapsed << \" seconds\" << endl;\n\n\t// \n\t// 2) Compute probability of domains for each phylum \n\t//    with at least 10 assemblies within it.\n\t//\n\tsize_t min_n_phyla = 10;\n\tcerr << \"Processing of domain probabilities per phylum\" << endl;\n\n\tunordered_map<string, vector<string>> assemblies_per_phylum;\n\tfor (auto& assembly_id : assembly_ids) {\n\t\tAssembly& assembly = assemblies.Get(assembly_id);\n\t\tstring phylum = assembly.phylum;\n\t\tif (phylum.empty()) {\n\t\t\tcontinue;\n\t\t}\n\t\tif (assemblies_per_phylum.find(phylum) == assemblies_per_phylum.end()) {\n\t\t\tassemblies_per_phylum[phylum] = vector<string>{assembly_id};\n\t\t} else {\n\t\t\tassemblies_per_phylum[phylum].push_back(assembly_id);\n\t\t}\n\t}\n\n\tset<string> phyla_set;\n\tfor (auto& assembly_id : assembly_ids) {\n\t\tAssembly& assembly = assemblies.Get(assembly_id);\n\t\tstring phylum = assembly.phylum;\n\t\tif (!phylum.empty() && assemblies_per_phylum[phylum].size() >= min_n_phyla) {\n\t\t\tphyla_set.insert(phylum);\n\t\t}\n\t}\n\n\tvector<string> phyla;\n\tphyla.assign(phyla_set.begin(), phyla_set.end());\n\tauto n_phyla = phyla.size();\n\n\tcerr << \"Processing \" << n_phyla << \" phyla\" << endl;\n\tcerr << \"Starting \" << n_threads << \" threads\" << endl;\n\n\tn_per_thread = ceil((double) n_phyla / (double) n_threads);\n\n\tvector<future<bool>> futuresP;\n\tfor (int i = 0; i < n_threads; ++i) {\n\t\tauto start = phyla.begin() + i * n_per_thread;\n\t\tauto end = phyla.end();\n\t\tint endInt = i * n_per_thread + n_per_thread;\n\t\tif (endInt < n_phyla) {\n\t\t\tend = phyla.begin() + endInt;\n\t\t}\n\t\tfuturesP.push_back(async(\n\t\t\ttask_compute_domain_probabilities_per_phylum, \n\t\t\ti+1, \n\t\t\tctx,\n\t\t\tvector<string>(start, end),\n\t\t\tassemblies_per_phylum\n\t\t));\n\t}\n\tfor (auto& f : futuresP) {\n\t\tif(!f.get()) {\n\t\t\tthrow runtime_error(\"Unexpected error while processing phylum output\");\n\t\t}\n\t}\n\n\ttp = system_clock::now();\n\telapsed = duration_cast<seconds>(tp - start).count();\n\tcerr << \"Processing of domain probabilities per phylum is complete\" << endl;\n\tcerr << \"Elapsed: \" << elapsed << \" seconds\" << endl;\n\n\t//\n\t// 3) Compute probability of domains per superkingdom.\n\t//\n\tcerr << \"Processing of domain probabilities per superkingdom\" << endl;\n\tvector<string> superkingdoms;\n\tunordered_map<string, vector<string>> phyla_per_superkingdom;\n\tfor (auto& phylum : phyla) {\n\t\tauto assembly_id = assemblies_per_phylum[phylum][0];\n\t\tAssembly& assembly = assemblies.Get(assembly_id);\n\t\tconst string superkingdom_raw = assembly.domain;\n\t\tif (superkingdom_raw.empty()) {\n\t\t\tcontinue;\n\t\t}\n\t\tstring superkingdom = superkingdom_raw;\n\t\ttransform(\n\t\t\tsuperkingdom.begin(), \n\t\t\tsuperkingdom.end(), \n\t\t\tsuperkingdom.begin(), \n\t\t\t::tolower\n\t\t);\n\t\tsuperkingdom[0] = toupper(superkingdom[0]);\n\n\t\tif (phyla_per_superkingdom.find(superkingdom) == phyla_per_superkingdom.end()) {\n\t\t\tphyla_per_superkingdom[superkingdom] = vector<string>{phylum};\n\t\t\tsuperkingdoms.push_back(superkingdom);\n\t\t} else {\n\t\t\tphyla_per_superkingdom[superkingdom].push_back(phylum);\n\t\t}\n\t}\n\n\tstring superkingdom_folder = dataFolder + \"superkingdom/\";\n\tfilesystem::create_directory(superkingdom_folder);\n\n\tfor (auto& superkingdom : superkingdoms) {\n\t\tstring superkingdom_lower = superkingdom;\n\t\ttransform(\n\t\t\tsuperkingdom_lower.begin(), \n\t\t\tsuperkingdom_lower.end(), \n\t\t\tsuperkingdom_lower.begin(), \n\t\t\t::tolower\n\t\t);\n\t\t\n\t\tstring superkingdom_inner_folder = (\n\t\t\tsuperkingdom_folder + \"/\" + superkingdom_lower + \"/\"\n\t\t);\n\t\tif (!ctx.superkingdom_output_folder.empty()) {\n\t\t\tsuperkingdom_inner_folder = ctx.superkingdom_output_folder + \"/\";\n\t\t}\n\t\tfilesystem::create_directory(superkingdom_inner_folder);\n\n\t\tauto& superkingdom_phyla = phyla_per_superkingdom[superkingdom];\n\t\tauto n_superkingdom_phyla = superkingdom_phyla.size();\n\n\t\tset<ProteinDomain> protein_domains;\n\t\tunordered_map<ProteinDomain, vector<DomainProbability>> protein_domain_probs;\n\t\tfor (auto& phylum : superkingdom_phyla) {\n\t\t\tstring phylum_lower = phylum;\n\t\t\ttransform(\n\t\t\t\tphylum_lower.begin(), \n\t\t\t\tphylum_lower.end(), \n\t\t\t\tphylum_lower.begin(), \n\t\t\t\t::tolower\n\t\t\t);\n\t\t\ttransform(\n\t\t\t\tphylum_lower.begin(), \n\t\t\t\tphylum_lower.end(), \n\t\t\t\tphylum_lower.begin(), \n\t\t\t\t[](char ch) {\n\t\t\t\t    return ch == ' ' ? '_' : ch;\n\t\t\t\t}\n\t\t\t);\n\t\t\tstring phylumDir = dataFolder + \"phylum/\" + phylum_lower + \"/\";\n\t\t\tif (!ctx.phylum_output_folder.empty()) {\n\t\t\t\tphylumDir = ctx.phylum_output_folder + \"/\";\n\t\t\t}\n\n\t\t\tstring phylum_domain_prob_path;\n\t\t\tif (kind == \"tri-nucleotide\") {\n\t\t\t\tphylum_domain_prob_path = (\n\t\t\t\t\tphylumDir + \n\t\t\t\t\tphylum_lower + \"_\" + query + \"_probability_\" + tail + \".csv\"\n\t\t\t\t);\n\t\t\t} else {\n\t\t\t\tphylum_domain_prob_path = (\n\t\t\t\t\tphylumDir + \n\t\t\t\t\tphylum_lower + \"_\" + query + \"_aa_probability_\" + tail + \".csv\"\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tvector<DomainProbability> domains = LoadDomainProbabilities(\n\t\t\t\tphylum_domain_prob_path\n\t\t\t);\n\t\t\tfor (auto& domain_prob : domains) {\n\t\t\t\tauto& domain = domain_prob.domain;\n\t\t\t\tprotein_domains.insert(domain);\n\n\t\t\t\tif (protein_domain_probs.find(domain) == protein_domain_probs.end()) {\n\t\t\t\t\tprotein_domain_probs[domain] = vector<DomainProbability>{domain_prob};\n\t\t\t\t} else {\n\t\t\t\t\tprotein_domain_probs[domain].push_back(domain_prob);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tstring superkingdom_out_path; \n\t\tif (kind == \"tri-nucleotide\") {\n\t\t\tsuperkingdom_out_path= (\n\t\t\t\tsuperkingdom_inner_folder + \n\t\t\t\tsuperkingdom_lower + \"_\" + query + \"_probability_\" + tail + \".csv\"\n\t\t\t);\n\t\t} else {\n\t\t\tsuperkingdom_out_path= (\n\t\t\t\tsuperkingdom_inner_folder + \n\t\t\t\tsuperkingdom_lower + \"_\" + query + \"_aa_probability_\" + tail + \".csv\"\n\t\t\t);\n\t\t}\n\n\t\tofstream superkingdom_of(superkingdom_out_path);\n\t\tauto writer = make_csv_writer(superkingdom_of);\n\t\twriter << DomainProbability::RecordHeader();\n\n\t\txt::xarray<double> uniform_log_prior = xt::eval(\n\t\t\txt::log(make_uniform_prior(n_superkingdom_phyla))\n\t\t);\n\n\t\tvector<DomainProbability> records;\n\t\tfor (auto& domain : protein_domains) {\n\t\t\tauto& domain_probs = protein_domain_probs[domain];\n\t\t\tauto n_probs = domain_probs.size();\n\t\t\txt::xarray<double> log_probs = xt::zeros<double>({n_superkingdom_phyla});\n\t\t\txt::xarray<double> log_probs_random = xt::zeros<double>({n_superkingdom_phyla});\n\t\t\tfor (int ix = 0; ix < n_probs; ++ix) {\n\t\t\t\tlog_probs[ix] = domain_probs[ix].log_probability;\n\t\t\t\tlog_probs_random[ix] = domain_probs[ix].log_probability_random;\n\t\t\t}\n\n\t\t\tdouble log_prob = marginalization_log(\n\t\t\t\tuniform_log_prior, \n\t\t\t\tlog_probs\n\t\t\t);\n\t\t\tdouble log_prob_random = marginalization_log(\n\t\t\t\tuniform_log_prior, \n\t\t\t\tlog_probs_random\n\t\t\t);\n\n\t\t\ttry {\n\t\t\t\tDomainProbability record(\n\t\t\t\t\tdomain, \n\t\t\t\t\tlog_prob, \n\t\t\t\t\tlog_prob_random,\n\t\t\t\t\tn_probs\n\t\t\t\t);\n\t\t\t\trecords.push_back(record);\n\t\t\t}\n\t\t\tcatch (exception& e) {\n\t\t\t\tcerr << \"Global computation | \";\n\t\t\t\tcerr << \"Exception: \" << e.what() << endl;\n\t\t\t\tthrow;\n\t\t\t}\n\t\t}\n\n\t\tsort(records.begin(), records.end(), greater<DomainProbability>()); \n\n\t\tfor (auto& record : records) {\n\t\t\twriter << record.Record();\n\t\t}\n\t}\n\tcerr << \"Processing of domain probabilities per superkingdom is complete\" << endl;\n\n\t//\n\t// 4) Compute global probability of domains.\n\t//\n\tcerr << \"Processing of domain probabilities globally\" << endl;\n\tset<ProteinDomain> protein_domains;\n\tunordered_map<ProteinDomain, vector<DomainProbability>> protein_domain_probs;\n\tfor (auto& phylum : phyla) {\n\t\tstring phylum_lower = phylum;\n\t\ttransform(phylum_lower.begin(), phylum_lower.end(), phylum_lower.begin(), ::tolower);\n\t\ttransform(phylum_lower.begin(), phylum_lower.end(), phylum_lower.begin(), [](char ch) {\n\t\t    return ch == ' ' ? '_' : ch;\n\t\t});\n\t\tstring phylumDir = dataFolder + \"phylum/\" + phylum_lower + \"/\";\n\t\tif (!ctx.phylum_output_folder.empty()) {\n\t\t\tphylumDir = ctx.phylum_output_folder + \"/\";\n\t\t}\n\n\t\tstring phylum_domain_prob_path;\n\t\tif (kind == \"tri-nucleotide\") {\n\t\t\tphylum_domain_prob_path = (\n\t\t\t\tphylumDir + \n\t\t\t\tphylum_lower + \"_\" + query + \"_probability_\" + tail + \".csv\"\n\t\t\t);\n\t\t} else {\n\t\t\tphylum_domain_prob_path = (\n\t\t\t\tphylumDir + \n\t\t\t\tphylum_lower + \"_\" + query + \"_aa_probability_\" + tail + \".csv\"\n\t\t\t);\n\t\t}\n\n\t\tvector<DomainProbability> domains = LoadDomainProbabilities(phylum_domain_prob_path);\n\t\tfor (auto& domain_prob : domains) {\n\t\t\tauto& domain = domain_prob.domain;\n\t\t\tprotein_domains.insert(domain);\n\n\t\t\tif (protein_domain_probs.find(domain) == protein_domain_probs.end()) {\n\t\t\t\tprotein_domain_probs[domain] = vector<DomainProbability>{domain_prob};\n\t\t\t} else {\n\t\t\t\tprotein_domain_probs[domain].push_back(domain_prob);\n\t\t\t}\n\t\t}\n\t}\n\n\tstring overallOutputFolder = dataFolder;\n\tif (!ctx.overall_output_folder.empty()) {\n\t\toverallOutputFolder = ctx.overall_output_folder + \"/\";\n\t}\n\n\tstring protein_out_path;\n\tif (kind == \"tri-nucleotide\") {\n\t\tprotein_out_path = overallOutputFolder + query + \"_probability_\" + tail + \".csv\";\n\t} else {\n\t\tprotein_out_path = overallOutputFolder + query + \"_aa_probability_\" + tail + \".csv\";\n\t}\n\t\n\tofstream output_file(protein_out_path);\n\tauto writer = make_csv_writer(output_file);\n\twriter << DomainProbability::RecordHeader();\n\n\txt::xarray<double> uniform_log_prior = xt::eval(\n\t\txt::log(make_uniform_prior(n_phyla))\n\t);\n\n\tvector<DomainProbability> records;\n\tfor (auto& domain : protein_domains) {\n\t\tauto& domain_probs = protein_domain_probs[domain];\n\t\tauto n_probs = domain_probs.size();\n\t\txt::xarray<double> log_probs = xt::zeros<double>({n_phyla});\n\t\txt::xarray<double> log_probs_random = xt::zeros<double>({n_phyla});\n\t\tfor (int ix = 0; ix < n_probs; ++ix) {\n\t\t\tlog_probs[ix] = domain_probs[ix].log_probability;\n\t\t\tlog_probs_random[ix] = domain_probs[ix].log_probability_random;\n\t\t}\n\n\t\tdouble log_prob = marginalization_log(\n\t\t\tuniform_log_prior, \n\t\t\tlog_probs\n\t\t);\n\t\tdouble log_prob_random = marginalization_log(\n\t\t\tuniform_log_prior, \n\t\t\tlog_probs_random\n\t\t);\n\n\t\ttry {\n\t\t\tDomainProbability record(\n\t\t\t\tdomain, \n\t\t\t\tlog_prob, \n\t\t\t\tlog_prob_random,\n\t\t\t\tn_probs\n\t\t\t);\n\t\t\trecords.push_back(record);\n\t\t}\n\t\tcatch (exception& e) {\n\t\t\tcerr << \"Global computation | \";\n\t\t\tcerr << \"Exception: \" << e.what() << endl;\n\t\t\tthrow;\n\t\t}\n\t}\n\n\tsort(records.begin(), records.end(), greater<DomainProbability>()); \n\n\tfor (auto& record : records) {\n\t\twriter << record.Record();\n\t}\n\n\ttp = system_clock::now();\n\telapsed = duration_cast<seconds>(tp - start).count();\n\tcerr << \"Processing of global domain probabilities is complete\" << endl;\n\tcerr << \"Elapsed: \" << elapsed << \" seconds\" << endl;\n\tcerr << \"DONE\" << endl;\n}\n", "meta": {"hexsha": "06dd99ea3ba0b780581cf63a9183c0147ed9a66a", "size": 20139, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/task/domain_probability_task.cpp", "max_stars_repo_name": "srom/nbias", "max_stars_repo_head_hexsha": "be8cf8dd623038dcf08d38ed3d19f635ee2dbeae", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/task/domain_probability_task.cpp", "max_issues_repo_name": "srom/nbias", "max_issues_repo_head_hexsha": "be8cf8dd623038dcf08d38ed3d19f635ee2dbeae", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/task/domain_probability_task.cpp", "max_forks_repo_name": "srom/nbias", "max_forks_repo_head_hexsha": "be8cf8dd623038dcf08d38ed3d19f635ee2dbeae", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.7474150665, "max_line_length": 89, "alphanum_fraction": 0.6777893639, "num_tokens": 5328, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6370307806984444, "lm_q2_score": 0.48047867804790706, "lm_q1q2_score": 0.30607970738581475}}
{"text": "#include <math.h>\n#include <stdio.h>\n#include <stdlib.h>\n\n#include <Eigen/Geometry>\n#include <arc_utilities/arc_helpers.hpp>\n#include <arc_utilities/eigen_typedefs.hpp>\n#include <map>\n#include <vector>\n\n#ifndef IIWA_7_FK_FAST_HPP\n#define IIWA_7_FK_FAST_HPP\n\nnamespace IIWA_7_FK_FAST {\nconst size_t IIWA_7_NUM_ACTIVE_JOINTS = 7;\nconst size_t IIWA_7_NUM_LINKS = 8;\n\nconst std::string IIWA_7_ACTIVE_JOINT_1_NAME = \"iiwa_joint_1\";\nconst std::string IIWA_7_ACTIVE_JOINT_2_NAME = \"iiwa_joint_2\";\nconst std::string IIWA_7_ACTIVE_JOINT_3_NAME = \"iiwa_joint_3\";\nconst std::string IIWA_7_ACTIVE_JOINT_4_NAME = \"iiwa_joint_4\";\nconst std::string IIWA_7_ACTIVE_JOINT_5_NAME = \"iiwa_joint_5\";\nconst std::string IIWA_7_ACTIVE_JOINT_6_NAME = \"iiwa_joint_6\";\nconst std::string IIWA_7_ACTIVE_JOINT_7_NAME = \"iiwa_joint_7\";\n\nconst std::string IIWA_7_LINK_1_NAME = \"iiwa_link_0\";\nconst std::string IIWA_7_LINK_2_NAME = \"iiwa_link_1\";\nconst std::string IIWA_7_LINK_3_NAME = \"iiwa_link_2\";\nconst std::string IIWA_7_LINK_4_NAME = \"iiwa_link_3\";\nconst std::string IIWA_7_LINK_5_NAME = \"iiwa_link_4\";\nconst std::string IIWA_7_LINK_6_NAME = \"iiwa_link_5\";\nconst std::string IIWA_7_LINK_7_NAME = \"iiwa_link_6\";\nconst std::string IIWA_7_LINK_8_NAME = \"iiwa_link_7\";\n\ninline Eigen::Isometry3d Get_link_0_joint_1_LinkJointTransform(const double joint_val) {\n  const Eigen::Translation3d pre_joint_translation(0.0, 0.0, 0.15);\n  const Eigen::Quaterniond pre_joint_rotation = EigenHelpers::QuaternionFromUrdfRPY(0.0, 0.0, 0.0);\n  const Eigen::Isometry3d pre_joint_transform = pre_joint_translation * pre_joint_rotation;\n  const Eigen::Translation3d joint_translation(0.0, 0.0, 0.0);\n  const Eigen::Quaterniond joint_rotation(Eigen::AngleAxisd(joint_val, Eigen::Vector3d::UnitZ()));\n  const Eigen::Isometry3d joint_transform = joint_translation * joint_rotation;\n  return (pre_joint_transform * joint_transform);\n}\n\ninline Eigen::Isometry3d Get_link_1_joint_2_LinkJointTransform(const double joint_val) {\n  const Eigen::Translation3d pre_joint_translation(0.0, 0.0, 0.19);\n  const Eigen::Quaterniond pre_joint_rotation = EigenHelpers::QuaternionFromUrdfRPY(M_PI_2, 0.0, M_PI);\n  const Eigen::Isometry3d pre_joint_transform = pre_joint_translation * pre_joint_rotation;\n  const Eigen::Translation3d joint_translation(0.0, 0.0, 0.0);\n  const Eigen::Quaterniond joint_rotation(Eigen::AngleAxisd(joint_val, Eigen::Vector3d::UnitZ()));\n  const Eigen::Isometry3d joint_transform = joint_translation * joint_rotation;\n  return (pre_joint_transform * joint_transform);\n}\n\ninline Eigen::Isometry3d Get_link_2_joint_3_LinkJointTransform(const double joint_val) {\n  const Eigen::Translation3d pre_joint_translation(0.0, 0.21, 0.0);\n  const Eigen::Quaterniond pre_joint_rotation = EigenHelpers::QuaternionFromUrdfRPY(M_PI_2, 0.0, M_PI);\n  const Eigen::Isometry3d pre_joint_transform = pre_joint_translation * pre_joint_rotation;\n  const Eigen::Translation3d joint_translation(0.0, 0.0, 0.0);\n  const Eigen::Quaterniond joint_rotation(Eigen::AngleAxisd(joint_val, Eigen::Vector3d::UnitZ()));\n  const Eigen::Isometry3d joint_transform = joint_translation * joint_rotation;\n  return (pre_joint_transform * joint_transform);\n}\n\ninline Eigen::Isometry3d Get_link_3_joint_4_LinkJointTransform(const double joint_val) {\n  const Eigen::Translation3d pre_joint_translation(0.0, 0.0, 0.19);\n  const Eigen::Quaterniond pre_joint_rotation = EigenHelpers::QuaternionFromUrdfRPY(M_PI_2, 0.0, 0.0);\n  const Eigen::Isometry3d pre_joint_transform = pre_joint_translation * pre_joint_rotation;\n  const Eigen::Translation3d joint_translation(0.0, 0.0, 0.0);\n  const Eigen::Quaterniond joint_rotation(Eigen::AngleAxisd(joint_val, Eigen::Vector3d::UnitZ()));\n  const Eigen::Isometry3d joint_transform = joint_translation * joint_rotation;\n  return (pre_joint_transform * joint_transform);\n}\n\ninline Eigen::Isometry3d Get_link_4_joint_5_LinkJointTransform(const double joint_val) {\n  const Eigen::Translation3d pre_joint_translation(0.0, 0.21, 0.0);\n  const Eigen::Quaterniond pre_joint_rotation = EigenHelpers::QuaternionFromUrdfRPY(-M_PI_2, M_PI, 0.0);\n  const Eigen::Isometry3d pre_joint_transform = pre_joint_translation * pre_joint_rotation;\n  const Eigen::Translation3d joint_translation(0.0, 0.0, 0.0);\n  const Eigen::Quaterniond joint_rotation(Eigen::AngleAxisd(joint_val, Eigen::Vector3d::UnitZ()));\n  const Eigen::Isometry3d joint_transform = joint_translation * joint_rotation;\n  return (pre_joint_transform * joint_transform);\n}\n\ninline Eigen::Isometry3d Get_link_5_joint_6_LinkJointTransform(const double joint_val) {\n  const Eigen::Translation3d pre_joint_translation(0.0, 0.06070, 0.19);\n  const Eigen::Quaterniond pre_joint_rotation = EigenHelpers::QuaternionFromUrdfRPY(M_PI_2, 0.0, 0.0);\n  const Eigen::Isometry3d pre_joint_transform = pre_joint_translation * pre_joint_rotation;\n  const Eigen::Translation3d joint_translation(0.0, 0.0, 0.0);\n  const Eigen::Quaterniond joint_rotation(Eigen::AngleAxisd(joint_val, Eigen::Vector3d::UnitZ()));\n  const Eigen::Isometry3d joint_transform = joint_translation * joint_rotation;\n  return (pre_joint_transform * joint_transform);\n}\n\ninline Eigen::Isometry3d Get_link_6_joint_7_LinkJointTransform(const double joint_val) {\n  const Eigen::Translation3d pre_joint_translation(0.0, 0.081, 0.06070);\n  const Eigen::Quaterniond pre_joint_rotation = EigenHelpers::QuaternionFromUrdfRPY(-M_PI_2, M_PI, 0.0);\n  const Eigen::Isometry3d pre_joint_transform = pre_joint_translation * pre_joint_rotation;\n  const Eigen::Translation3d joint_translation(0.0, 0.0, 0.0);\n  const Eigen::Quaterniond joint_rotation(Eigen::AngleAxisd(joint_val, Eigen::Vector3d::UnitZ()));\n  const Eigen::Isometry3d joint_transform = joint_translation * joint_rotation;\n  return (pre_joint_transform * joint_transform);\n}\n\ninline EigenHelpers::VectorIsometry3d GetLinkTransforms(\n    const std::vector<double>& configuration, const Eigen::Isometry3d& base_transform = Eigen::Isometry3d::Identity()) {\n  assert(configuration.size() == IIWA_7_NUM_ACTIVE_JOINTS);\n  EigenHelpers::VectorIsometry3d link_transforms(IIWA_7_NUM_LINKS);\n  link_transforms[0] = base_transform;\n  link_transforms[1] = link_transforms[0] * Get_link_0_joint_1_LinkJointTransform(configuration[0]);\n  link_transforms[2] = link_transforms[1] * Get_link_1_joint_2_LinkJointTransform(configuration[1]);\n  link_transforms[3] = link_transforms[2] * Get_link_2_joint_3_LinkJointTransform(configuration[2]);\n  link_transforms[4] = link_transforms[3] * Get_link_3_joint_4_LinkJointTransform(configuration[3]);\n  link_transforms[5] = link_transforms[4] * Get_link_4_joint_5_LinkJointTransform(configuration[4]);\n  link_transforms[6] = link_transforms[5] * Get_link_5_joint_6_LinkJointTransform(configuration[5]);\n  link_transforms[7] = link_transforms[6] * Get_link_6_joint_7_LinkJointTransform(configuration[6]);\n  return link_transforms;\n}\n\ninline EigenHelpers::VectorIsometry3d GetLinkTransforms(\n    const std::map<std::string, double>& configuration,\n    const Eigen::Isometry3d& base_transform = Eigen::Isometry3d::Identity()) {\n  std::vector<double> configuration_vector(IIWA_7_NUM_ACTIVE_JOINTS);\n  configuration_vector[0] = arc_helpers::RetrieveOrDefault(configuration, IIWA_7_ACTIVE_JOINT_1_NAME, 0.0);\n  configuration_vector[1] = arc_helpers::RetrieveOrDefault(configuration, IIWA_7_ACTIVE_JOINT_2_NAME, 0.0);\n  configuration_vector[2] = arc_helpers::RetrieveOrDefault(configuration, IIWA_7_ACTIVE_JOINT_3_NAME, 0.0);\n  configuration_vector[3] = arc_helpers::RetrieveOrDefault(configuration, IIWA_7_ACTIVE_JOINT_4_NAME, 0.0);\n  configuration_vector[4] = arc_helpers::RetrieveOrDefault(configuration, IIWA_7_ACTIVE_JOINT_5_NAME, 0.0);\n  configuration_vector[5] = arc_helpers::RetrieveOrDefault(configuration, IIWA_7_ACTIVE_JOINT_6_NAME, 0.0);\n  configuration_vector[6] = arc_helpers::RetrieveOrDefault(configuration, IIWA_7_ACTIVE_JOINT_7_NAME, 0.0);\n  return GetLinkTransforms(configuration_vector, base_transform);\n}\n\ninline EigenHelpers::MapStringIsometry3d GetLinkTransformsMap(\n    const std::vector<double>& configuration, const Eigen::Isometry3d& base_transform = Eigen::Isometry3d::Identity()) {\n  const EigenHelpers::VectorIsometry3d link_transforms = GetLinkTransforms(configuration, base_transform);\n  EigenHelpers::MapStringIsometry3d link_transforms_map;\n  link_transforms_map[IIWA_7_LINK_1_NAME] = link_transforms[0];\n  link_transforms_map[IIWA_7_LINK_2_NAME] = link_transforms[1];\n  link_transforms_map[IIWA_7_LINK_3_NAME] = link_transforms[2];\n  link_transforms_map[IIWA_7_LINK_4_NAME] = link_transforms[3];\n  link_transforms_map[IIWA_7_LINK_5_NAME] = link_transforms[4];\n  link_transforms_map[IIWA_7_LINK_6_NAME] = link_transforms[5];\n  link_transforms_map[IIWA_7_LINK_7_NAME] = link_transforms[6];\n  link_transforms_map[IIWA_7_LINK_8_NAME] = link_transforms[7];\n  return link_transforms_map;\n}\n\ninline EigenHelpers::MapStringIsometry3d GetLinkTransformsMap(\n    const std::map<std::string, double>& configuration,\n    const Eigen::Isometry3d& base_transform = Eigen::Isometry3d::Identity()) {\n  const EigenHelpers::VectorIsometry3d link_transforms = GetLinkTransforms(configuration, base_transform);\n  EigenHelpers::MapStringIsometry3d link_transforms_map;\n  link_transforms_map[IIWA_7_LINK_1_NAME] = link_transforms[0];\n  link_transforms_map[IIWA_7_LINK_2_NAME] = link_transforms[1];\n  link_transforms_map[IIWA_7_LINK_3_NAME] = link_transforms[2];\n  link_transforms_map[IIWA_7_LINK_4_NAME] = link_transforms[3];\n  link_transforms_map[IIWA_7_LINK_5_NAME] = link_transforms[4];\n  link_transforms_map[IIWA_7_LINK_6_NAME] = link_transforms[5];\n  link_transforms_map[IIWA_7_LINK_7_NAME] = link_transforms[6];\n  link_transforms_map[IIWA_7_LINK_8_NAME] = link_transforms[7];\n  return link_transforms_map;\n}\n}  // namespace IIWA_7_FK_FAST\n\n#endif  // IIWA_7_FK_FAST_HPP\n", "meta": {"hexsha": "1b58328c9bbb32d71f8309666ed2dc3533ef0982", "size": 9809, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/arc_utilities/iiwa_7_fk_fast.hpp", "max_stars_repo_name": "UM-ARM-Lab/arc_utilities", "max_stars_repo_head_hexsha": "e21bd5062983b25e61e33f832ec66b937540ba10", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2017-01-09T14:37:14.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-16T08:02:08.000Z", "max_issues_repo_path": "include/arc_utilities/iiwa_7_fk_fast.hpp", "max_issues_repo_name": "UM-ARM-Lab/arc_utilities", "max_issues_repo_head_hexsha": "e21bd5062983b25e61e33f832ec66b937540ba10", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 62.0, "max_issues_repo_issues_event_min_datetime": "2017-05-25T16:52:38.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-08T20:05:09.000Z", "max_forks_repo_path": "include/arc_utilities/iiwa_7_fk_fast.hpp", "max_forks_repo_name": "UM-ARM-Lab/arc_utilities", "max_forks_repo_head_hexsha": "e21bd5062983b25e61e33f832ec66b937540ba10", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2017-08-04T13:06:17.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-16T08:02:11.000Z", "avg_line_length": 58.7365269461, "max_line_length": 120, "alphanum_fraction": 0.8089509634, "num_tokens": 2843, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.8267117940706734, "lm_q2_score": 0.37022537869825406, "lm_q1q2_score": 0.30606968703412807}}
{"text": "#pragma once\n\n#ifdef USE_FIBONACCI_HEAP\n#include <boost/heap/fibonacci_heap.hpp>\n#endif\n\n#include <boost/heap/d_ary_heap.hpp>\n#include <unordered_map>\n#include <unordered_set>\n\n#include \"neighbor.hpp\"\n#include \"planresult.hpp\"\n\n// #define REBUILT_FOCAL_LIST\n// #define CHECK_FOCAL_LIST\n\nnamespace libMultiRobotPlanning {\n\n/*!\n  \\example a_star_epsilon.cpp Simple example using a 2D grid world and\n  up/down/left/right\n  actions\n*/\n\n/*! \\brief A*_epsilon Algorithm to find the shortest path with a given\nsuboptimality bound (also known as focal search)\nThis class implements the A*_epsilon algorithm, an informed search\nalgorithm\nthat finds the shortest path for a given map up to a suboptimality factor.\nIt uses an admissible heuristic (to keep track of the optimum) and an\ninadmissible heuristic (\nto guide the search within a suboptimal bound w.)\nDetails of the algorithm can be found in the following paper:\\n\nJudea Pearl, Jin H. Kim:\\n\n\"Studies in Semi-Admissible Heuristics.\"\" IEEE Trans. Pattern Anal. Mach.\nIntell. 4(4): 392-399 (1982)\\n\nhttps://doi.org/10.1109/TPAMI.1982.4767270\nThis class can either use a fibonacci heap, or a d-ary heap. The latter is the\ndefault. Define \"USE_FIBONACCI_HEAP\" to use the fibonacci heap instead.\n\\tparam State Custom state for the search. Needs to be copy'able\n\\tparam Action Custom action for the search. Needs to be copy'able\n\\tparam Cost Custom Cost type (integer or floating point types)\n\\tparam Environment This class needs to provide the custom logic. In\n    particular, it needs to support the following functions:\n  - `Cost admissibleHeuristic(const State& s)`\\n\n    This function can return 0 if no suitable heuristic is available.\n  - `Cost focalStateHeuristic(const State& s, Cost gScore)`\\n\n    This function computes a (potentially inadmissible) heuristic for the given\nstate.\n  - `Cost focalTransitionHeuristic(const State& s1, const State& s2, Cost\ngScoreS1, Cost gScoreS2)`\\n\n    This function computes a (potentially inadmissible) heuristic for the given\nstate transition.\n  - `bool isSolution(const State& s)`\\n\n    Return true if the given state is a goal state.\n  - `void getNeighbors(const State& s, std::vector<Neighbor<State, Action,\n   int> >& neighbors)`\\n\n    Fill the list of neighboring state for the given state s.\n  - `void onExpandNode(const State& s, int fScore, int gScore)`\\n\n    This function is called on every expansion and can be used for statistical\npurposes.\n  - `void onDiscover(const State& s, int fScore, int gScore)`\\n\n    This function is called on every node discovery and can be used for\n   statistical purposes.\n    \\tparam StateHasher A class to convert a state to a hash value. Default:\n   std::hash<State>\n*/\ntemplate <typename State, typename Action, typename Cost, typename Environment,\n          typename StateHasher = std::hash<State> >\nclass IOS {\n public:\n  IOS(Environment& environment, float w)\n      : m_env(environment), m_w(w) {}\n\n  bool search(const State& startState,\n              PlanResult<State, Action, Cost>& solution) {\n    solution.states.clear();\n    solution.states.push_back(std::make_pair<>(startState, 0));\n    solution.actions.clear();\n    solution.cost = INT32_MAX;\n\n    openSet_t openSet;\n    focalSet_t\n        focalSet;  // subset of open nodes that are within suboptimality bound\n    anopenset_t anopen;\n    std::unordered_map<State, fibHeapHandle_t, StateHasher> stateToHeap;\n    std::unordered_map<State, fibHeapHandle_t, StateHasher> stateToFocal;\n    std::unordered_set<State, StateHasher> closedSet;\n    std::unordered_map<State, std::tuple<State, Action, Cost, Cost>,\n                       StateHasher>\n        cameFrom;\n\n    auto handle = openSet.push(\n        Node(startState, m_env.admissibleHeuristic(startState), 0, 0,0));\n    stateToHeap.insert(std::make_pair<>(startState, handle));\n    (*handle).handle = handle;\n\n    anopen.push(handle);\n    focalSet.push(handle);\n\n    stateToFocal.insert(std::make_pair<>(startState, handle));\n\n    std::vector<Neighbor<State, Action, Cost> > neighbors;\n    neighbors.reserve(10);\n\n    Cost bestFScore = (*handle).fScore;\n\n    std::cout << \"new search\" << std::endl;\n\n//my work\nwhile(!openSet.empty()){\n\n  //printf(\"In Open\\n\");\n\n  const auto& nopen = openSet.top();\n  //std:: cout << m_w <<std::endl;\n  if(solution.cost <= m_w * nopen.fScore ){\n        //printf(\"Found\\n\");\n        return true;\n  }\n  //Node nopen = *nopen_handle;\n  if(focalSet.empty()){\n    printf(\"Empty\\n\");\n    return false;\n  }\n  auto currentHandle = focalSet.top();\n  Node current = *currentHandle;\n\n  auto currentHandle_anop = anopen.top();\n  Node current_anop = *currentHandle_anop;\n\n\n  if(current.focalHeuristic < solution.cost){\n    // Do greedy step\n\n    //printf(\"greedy\\n\");\n\n    focalSet.pop();\n    // openSet.erase(currentHandle);\n    stateToFocal.erase(current.state);\n    closedSet.insert(current.state);\n\n    m_env.onExpandNode(current.state, current.fScore, current.gScore);\n\n    if (m_env.isSolution(current.state)) {\n        printf(\"Solution\\n\");\n        solution.states.clear();\n        solution.actions.clear();\n        auto iter = cameFrom.find(current.state);\n        while (iter != cameFrom.end()) {\n          solution.states.push_back(\n              std::make_pair<>(iter->first, std::get<3>(iter->second)));\n          solution.actions.push_back(std::make_pair<>(\n              std::get<1>(iter->second), std::get<2>(iter->second)));\n          iter = cameFrom.find(std::get<0>(iter->second));\n        }\n        solution.states.push_back(std::make_pair<>(startState, 0));\n        std::reverse(solution.states.begin(), solution.states.end());\n        std::reverse(solution.actions.begin(), solution.actions.end());\n        solution.cost = current.gScore;\n        if(openSet.empty())\n          solution.fmin = current.fScore;\n        else\n          solution.fmin = openSet.top().fScore;\n        if(current.focalHeuristic <= (m_w*current_anop.fopenmax)){\n          return true;\n        }\n        \n\n      }\n    else{\n      neighbors.clear();\n      m_env.getNeighbors(current.state, neighbors);\n      for (const Neighbor<State, Action, Cost>& neighbor : neighbors) {\n        //printf(\"Neighbour\\n\");\n        if (closedSet.find(neighbor.state) == closedSet.end()) {\n          Cost tentative_gScore = current.gScore + neighbor.cost;\n          auto iter = stateToHeap.find(neighbor.state);\n          auto iterFocal = stateToFocal.find(neighbor.state);\n          if (iter == stateToHeap.end() && iterFocal == stateToFocal.end()) {  // Discover a new node\n            //std::cout << \"  this is a new node\" << std::endl;\n\n            // I didn't add Improved termination condition\n\n            Cost fScore =\n                tentative_gScore + m_env.admissibleHeuristic(neighbor.state);\n\n            // std::cout << tentative_gScore << \" \" << current.focalHeuristic << \" \" << m_env.focalStateHeuristic(neighbor.state, tentative_gScore) << \" \" << m_env.focalTransitionHeuristic(current.state, neighbor.state,\n            //                                    current.gScore,\n            //                                    tentative_gScore) << std::endl;\n\n            Cost focalHeuristic = tentative_gScore + ((2*m_w-1) * m_env.admissibleHeuristic(neighbor.state)) ;\n\n            Cost fopenmax = (tentative_gScore/m_w) +  m_env.admissibleHeuristic(neighbor.state);\n\n\n            /*\n            ((2*m_w - 1)* \n                (m_env.focalStateHeuristic(neighbor.state, tentative_gScore) +\n                 m_env.focalTransitionHeuristic(current.state, neighbor.state,\n                                               current.gScore,\n                                               tentative_gScore)));\n                                               */\n\n            auto handle = openSet.push(\n                Node(neighbor.state, fScore, tentative_gScore, focalHeuristic, fopenmax));\n            (*handle).handle = handle;\n            focalSet.push(handle);\n            anopen.push(handle);\n            // if (fScore <= bestFScore * m_w) {\n            //   // std::cout << \"focalAdd: \" << *handle << std::endl;\n            //   focalSet.push(handle);\n            // }\n            stateToHeap.insert(std::make_pair<>(neighbor.state, handle));\n            stateToFocal.insert(std::make_pair<>(neighbor.state, handle));\n            m_env.onDiscover(neighbor.state, fScore, tentative_gScore);\n            // std::cout << \"  this is a new node \" << fScore << \",\" <<\n            // tentative_gScore << std::endl;\n            cameFrom.erase(neighbor.state);\n            cameFrom.insert(std::make_pair<>(\n              neighbor.state,\n              std::make_tuple<>(current.state, neighbor.action, neighbor.cost,\n                                tentative_gScore)));\n          }\n        }\n      }\n    }\n\n  }\n  else{\n\n    //Do optimal step\n\n    std::cout<< \"In Optimal\" <<std::endl;\n\n    const auto& nopen2 = openSet.top();\n    std:: cout<< anopen.size() << std:: endl;\n    openSet.pop();\n    std:: cout<< anopen.size() << std:: endl;\n    auto iter_for_open = stateToHeap.find(nopen2.state);\n    currentHandle = iter_for_open->second;\n    current = *currentHandle;\n    // openSet.pop();\n    // openSet.erase(currentHandle);\n    //anopen.erase(current);\n    stateToHeap.erase(current.state);\n    if(closedSet.find(current.state)==closedSet.end()){\n      std::cout<< \"New Low level node\" << std::endl;\n      //m_env.onExpandNode(current.state, current.fScore, current.gScore);\n      closedSet.insert(current.state);\n    }\n\n    //Do i need to add this node to closed set\n\n    m_env.onExpandNode(current.state, current.fScore, current.gScore);\n\n    if (m_env.isSolution(current.state)) {\n        solution.states.clear();\n        solution.actions.clear();\n        auto iter = cameFrom.find(current.state);\n        while (iter != cameFrom.end()) {\n          solution.states.push_back(\n              std::make_pair<>(iter->first, std::get<3>(iter->second)));\n          solution.actions.push_back(std::make_pair<>(\n              std::get<1>(iter->second), std::get<2>(iter->second)));\n          iter = cameFrom.find(std::get<0>(iter->second));\n        }\n        solution.states.push_back(std::make_pair<>(startState, 0));\n        std::reverse(solution.states.begin(), solution.states.end());\n        std::reverse(solution.actions.begin(), solution.actions.end());\n        solution.cost = current.gScore;\n        solution.fmin = current.fScore;\n        return true;\n      }\n    else{\n      neighbors.clear();\n      m_env.getNeighbors(current.state, neighbors);\n      for (const Neighbor<State, Action, Cost>& neighbor : neighbors) {\n\n        Cost tentative_gScore = current.gScore + neighbor.cost;\n        auto iter = stateToHeap.find(neighbor.state);\n        auto iterFocal = stateToFocal.find(neighbor.state);\n\n        if (iter != stateToHeap.end()) {\n          std::cout<< \"In open\" <<std::endl;\n          auto handle = iter->second;\n            // We found this node with a better path than previous path\n            if (tentative_gScore < (*handle).gScore) {\n              std:: cout << \"Update Open\" <<std::endl;\n              (*handle).gScore = tentative_gScore;\n              (*handle).fScore = tentative_gScore + m_env.admissibleHeuristic(neighbor.state);\n              (*handle).focalHeuristic = tentative_gScore + ((2*m_w-1) * m_env.admissibleHeuristic(neighbor.state)) ;\n              (*handle).fopenmax = (tentative_gScore/m_w) +  m_env.admissibleHeuristic(neighbor.state);\n              // (*handle).focalHeuristic = tentative_gScore + ((2*m_w - 1)* \n              //   (m_env.focalStateHeuristic(neighbor.state, tentative_gScore) +\n              //    m_env.focalTransitionHeuristic(current.state, neighbor.state,\n              //                                  current.gScore,\n              //                                  tentative_gScore)));\n                openSet.update(handle);\n                // m_env.onDiscover(neighbor.state, (*handle).fScore,\n                //              (*handle).gScore);\n\n                //Do i need to include this node to focal\n                if(iterFocal != stateToFocal.end()){\n                  std:: cout << \"Update Focal\" <<std::endl;\n                  // handle = iterFocal->second;\n                  // focalSet.update(handle);\n                \n                }\n              cameFrom.erase(neighbor.state);\n                  cameFrom.insert(std::make_pair<>(\n                  neighbor.state,\n                  std::make_tuple<>(current.state, neighbor.action, neighbor.cost,\n                                    tentative_gScore)));\n            }\n        }\n        else if(closedSet.find(neighbor.state) == closedSet.end()){\n\n          if (iter == stateToHeap.end()) {  // Discover a new node\n            // std::cout << \"  this is a new node\" << std::endl;\n            Cost fScore =\n                tentative_gScore + m_env.admissibleHeuristic(neighbor.state);\n\n            Cost focalHeuristic = tentative_gScore + ((2*m_w-1) * m_env.admissibleHeuristic(neighbor.state)) ;\n\n            Cost fopenmax = (tentative_gScore/m_w) +  m_env.admissibleHeuristic(neighbor.state);\n\n            // Cost focalHeuristic = tentative_gScore + ((2*m_w - 1)* \n            //     (m_env.focalStateHeuristic(neighbor.state, tentative_gScore) +\n            //      m_env.focalTransitionHeuristic(current.state, neighbor.state,\n            //                                    current.gScore,\n            //                                    tentative_gScore)));\n            auto handle = openSet.push(\n                Node(neighbor.state, fScore, tentative_gScore, focalHeuristic,fopenmax));\n            (*handle).handle = handle;\n            \n            focalSet.push(handle);\n            anopen.push(handle);\n            \n            stateToHeap.insert(std::make_pair<>(neighbor.state, handle));\n            stateToFocal.insert(std::make_pair<>(neighbor.state, handle));\n            m_env.onDiscover(neighbor.state, fScore, tentative_gScore);\n            // std::cout << \"  this is a new node \" << fScore << \",\" <<\n            // tentative_gScore << std::endl;\n\n            cameFrom.erase(neighbor.state);\n            cameFrom.insert(std::make_pair<>(\n              neighbor.state,\n              std::make_tuple<>(current.state, neighbor.action, neighbor.cost,\n                                tentative_gScore)));\n        }\n        }\n      }\n\n    }\n\n\n  }\n}\n\n    return false;\n  }\n\n private:\n  struct Node;\n\n#ifdef USE_FIBONACCI_HEAP\n  typedef typename boost::heap::fibonacci_heap<Node> openSet_t;\n  typedef typename openSet_t::handle_type fibHeapHandle_t;\n// typedef typename boost::heap::fibonacci_heap<fibHeapHandle_t,\n// boost::heap::compare<compareFocalHeuristic> > focalSet_t;\n#else\n  typedef typename boost::heap::d_ary_heap<Node, boost::heap::arity<2>,\n                                           boost::heap::mutable_<true> >\n      openSet_t;\n  typedef typename openSet_t::handle_type fibHeapHandle_t;\n// typedef typename boost::heap::d_ary_heap<fibHeapHandle_t,\n// boost::heap::arity<2>, boost::heap::mutable_<true>,\n// boost::heap::compare<compareFocalHeuristic> > focalSet_t;\n#endif\n\n  struct Node {\n    Node(const State& state, Cost fScore, Cost gScore, Cost focalHeuristic, Cost fopenmax)\n        : state(state),\n          fScore(fScore),\n          gScore(gScore),\n          focalHeuristic(focalHeuristic),\n          fopenmax(fopenmax) {}\n\n    bool operator<(const Node& other) const {\n      //printf(\"InOpenCompare\\n\");\n      // Sort order\n      // 1. lowest fScore\n      // 2. highest gScore\n\n      // Our heap is a maximum heap, so we invert the comperator function here\n      if (fScore != other.fScore) {\n        return fScore > other.fScore;\n      } else {\n        return gScore < other.gScore;\n      }\n    }\n\n    friend std::ostream& operator<<(std::ostream& os, const Node& node) {\n      os << \"state: \" << node.state << \" fScore: \" << node.fScore\n         << \" gScore: \" << node.gScore << \" focal: \" << node.focalHeuristic;\n      return os;\n    }\n\n    State state;\n\n    Cost fScore;\n    Cost gScore;\n    Cost focalHeuristic;\n    Cost fopenmax;\n\n    fibHeapHandle_t handle;\n    // #ifdef USE_FIBONACCI_HEAP\n    //   typename boost::heap::fibonacci_heap<Node>::handle_type handle;\n    // #else\n    //   typename boost::heap::d_ary_heap<Node, boost::heap::arity<2>,\n    //   boost::heap::mutable_<true> >::handle_type handle;\n    // #endif\n  };\n\n  struct compareFocalHeuristic {\n    bool operator()(const fibHeapHandle_t& h1,\n                    const fibHeapHandle_t& h2) const {\n      // Sort order (see \"Improved Solvers for Bounded-Suboptimal Multi-Agent\n      // Path Finding\" by Cohen et. al.)\n      // 1. lowest focalHeuristic\n      // 2. lowest fScore\n      // 3. highest gScore\n\n      //printf(\"InfocalCompare\\n\");\n\n      // Our heap is a maximum heap, so we invert the comperator function here\n\n      //compare fun() for A*eps\n      if ((*h1).focalHeuristic != (*h2).focalHeuristic) {\n        return (*h1).focalHeuristic > (*h2).focalHeuristic;\n      } \n      else if ((*h1).fScore != (*h2).fScore) {\n          return (*h1).fScore > (*h2).fScore;\n      } \n      else {\n        return (*h1).gScore < (*h2).gScore;\n      }\n\n      \n      //compare fun() for IOS\n      // if ((*h1).focalHeuristic != (*h2).focalHeuristic) {\n      //   return (*h1).focalHeuristic > (*h2).focalHeuristic;\n      //   // } else if ((*h1).fScore != (*h2).fScore) {\n      //   //   return (*h1).fScore > (*h2).fScore;\n      // } \n      // // else if ((*h1).fScore != (*h2).fScore) {\n      // //   return (*h1).fScore > (*h2).fScore;\n      // //}\n      // else {\n      //   return (*h1).gScore < (*h2).gScore;\n      // }\n\n\n\n      \n    }\n  };\n\n#ifdef USE_FIBONACCI_HEAP\n  // typedef typename boost::heap::fibonacci_heap<Node> openSet_t;\n  // typedef typename openSet_t::handle_type fibHeapHandle_t;\n  typedef typename boost::heap::fibonacci_heap<\n      fibHeapHandle_t, boost::heap::compare<compareFocalHeuristic> >\n      focalSet_t;\n#else\n  // typedef typename boost::heap::d_ary_heap<Node, boost::heap::arity<2>,\n  // boost::heap::mutable_<true> > openSet_t;\n  // typedef typename openSet_t::handle_type fibHeapHandle_t;\n  typedef typename boost::heap::d_ary_heap<\n      fibHeapHandle_t, boost::heap::arity<2>, boost::heap::mutable_<true>,\n      boost::heap::compare<compareFocalHeuristic> >\n      focalSet_t;\n#endif\n\n\nstruct compareOpenMax {\n    bool operator()(const fibHeapHandle_t& h1,\n                    const fibHeapHandle_t& h2) const {\n      // Sort order (see \"Improved termination condition\")\n\n      // Our heap is a maximum heap, so we invert the comperator function here\n\n      //compare fun() for A*eps\n      return (*h1).fopenmax < (*h2).fopenmax;\n\n\n      \n    }\n  };\n\n  typedef typename boost::heap::d_ary_heap<\n      fibHeapHandle_t, boost::heap::arity<2>, boost::heap::mutable_<true>,\n      boost::heap::compare<compareOpenMax> >\n      anopenset_t;\n\n private:\n  Environment& m_env;\n  float m_w;\n};\n\n}  // namespace libMultiRobotPlanning\n\n  \n  \n\n", "meta": {"hexsha": "4f5558989fcb9e5ab104dfef209abf4bf83f1c61", "size": 18957, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/libMultiRobotPlanning/IOS.hpp", "max_stars_repo_name": "MustafizSaadi/libMultiRobotPlanning", "max_stars_repo_head_hexsha": "8d083c0bb1352142ccd4a222c1c87a3424ce4a79", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/libMultiRobotPlanning/IOS.hpp", "max_issues_repo_name": "MustafizSaadi/libMultiRobotPlanning", "max_issues_repo_head_hexsha": "8d083c0bb1352142ccd4a222c1c87a3424ce4a79", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/libMultiRobotPlanning/IOS.hpp", "max_forks_repo_name": "MustafizSaadi/libMultiRobotPlanning", "max_forks_repo_head_hexsha": "8d083c0bb1352142ccd4a222c1c87a3424ce4a79", "max_forks_repo_licenses": ["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.667311412, "max_line_length": 219, "alphanum_fraction": 0.6090626154, "num_tokens": 4571, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.588889130767832, "lm_q2_score": 0.519521321952093, "lm_q1q2_score": 0.30594045969972306}}
{"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 ITL_PC_SUB_MATRIX_PC_INCLUDE\n#define ITL_PC_SUB_MATRIX_PC_INCLUDE\n\n#include <boost/static_assert.hpp>\n#include <boost/mpl/if.hpp>\n\n#include <boost/numeric/mtl/utility/range_generator.hpp>\n#include <boost/numeric/mtl/utility/property_map.hpp>\n#include <boost/numeric/mtl/vector/dense_vector.hpp>\n#include <boost/numeric/mtl/interface/vpt.hpp>\n#include <boost/numeric/itl/pc/solver.hpp>\n\nnamespace itl { namespace pc {\n\n/// Class for applying \\tparam Preconditioner only on a sub-matrix\n/** Other entries are just copied. \n    Optionally preconditioner can be referred from outside instead of storing it by setting\n    \\tparam Store to true. \n**/\ntemplate <typename Preconditioner, typename Matrix, bool Store= true>\nclass sub_matrix_pc\n{\n    typedef mtl::dense_vector<bool>                                               tag_type;\n    typedef typename boost::mpl::if_c<Store, Preconditioner, const Preconditioner&>::type pc_type;\n\n    struct matrix_container\n    {\n\tmatrix_container() : Ap(0) {} \n\n\tmatrix_container(const tag_type& tags, const Matrix& src)\n\t{\n\t    using std::size_t; \n\t    using namespace mtl;\n\n\t    mtl::dense_vector<size_t> perm(size(tags));\n\t    size_t n= 0;\n\t    for (size_t i= 0; i < size(tags); ++i) {\n\t\tperm[i]= n;\n\t\tif (tags[i])\n\t\t    ++n;\n\t    }\n\n\t    Ap= new Matrix(n, n);\n\n\t    typename traits::row<Matrix>::type             row(src); \n\t    typename traits::col<Matrix>::type             col(src); \n\t    typename traits::const_value<Matrix>::type     value(src); \n\t    typedef typename traits::range_generator<tag::major, Matrix>::type  cursor_type;\n\n\t    mat::inserter<Matrix> ins(*Ap, Ap->nnz() / Ap->dim1());\n\t    \n\t    for (cursor_type cursor = mtl::begin<tag::major>(src), cend = mtl::end<tag::major>(src); \n\t\t cursor != cend; ++cursor) {\n\t\t// std::cout << dest << '\\n';\n\t    \n\t\ttypedef typename traits::range_generator<tag::nz, cursor_type>::type icursor_type;\n\t\tfor (icursor_type icursor = mtl::begin<tag::nz>(cursor), icend = mtl::end<tag::nz>(cursor); \n\t\t     icursor != icend; ++icursor) \n\t\t    if (tags[row(*icursor)] && tags[col(*icursor)])\n\t\t\tins(perm[row(*icursor)], perm[col(*icursor)]) << value(*icursor); \n\t    }\n\t}\n\n\t~matrix_container() { delete Ap; }\n\n\tMatrix* Ap;\n    };\n\n    size_t count_entries() const\n    {\n\tusing mtl::size;\n\tsize_t n= 0;\n\tfor (size_t i= 0; i < size(tags); ++i) \n\t    if (tags[i]) ++n;\n\treturn n;\n    }\n\n  public:\n\n    sub_matrix_pc(const tag_type& tags, const Matrix& A)\n      : tags(tags), n(count_entries()), mc(tags, A), P(*mc.Ap)\n    {\n\tBOOST_STATIC_ASSERT((Store));\n\tdelete mc.Ap; \n\tmc.Ap= 0;\n    }\n\n#if 0 // to do later\n    sub_matrix_pc(const tag_type& tags, const Preconditioner& P)\n      : tags(tags), P(P)\n    {\n\t// check sizes\n    }\n#endif\n\n  private:\n    template <typename VectorIn>\n    VectorIn& create_x0(VectorIn) const\n    {\n\tstatic VectorIn  x0(n);\n\treturn x0;\n    }\n\n    template <typename VectorOut>\n    VectorOut& create_y0(VectorOut) const\n    {\n\tstatic VectorOut  y0(n);\n\treturn y0;\n    }\n\n    template <typename VectorIn>\n    void restrict(const VectorIn& x, VectorIn& x0) const\n    {\n\tfor (size_t i= 0, j= 0; i < size(tags); ++i) \n\t    if (tags[i]) \n\t\tx0[j++]= x[i];\n    }\n\n    template <typename VectorIn, typename VectorOut>\n    void prolongate(const VectorIn& x, const VectorOut& y0, VectorOut& y) const\n    {\n\tfor (size_t i= 0, j= 0; i < size(tags); ++i) \n\t    if (tags[i]) \n\t\ty[i]= y0[j++];\n\t    else\n\t\ty[i]= x[i];\t\n    }\n\n  public:\n    /// Solve Px = y approximately on according sub-system; remaining entries are copied\n    template <typename VectorIn, typename VectorOut>\n    void solve(const VectorIn& x, VectorOut& y) const\n    {\n\tmtl::vampir_trace<5056> tracer;\n\ty.checked_change_resource(x);\n\n\tVectorIn&  x0= create_x0(x);\n\tVectorOut& y0= create_y0(y);\n\n\trestrict(x, x0);\n\tP.solve(x0, y0);\n\t// y0= solve(P, x0); // doesn't compile yet for unknown reasons\n\tprolongate(x, y0, y);\n    }\n\n    /// Solve Px = y approximately on according sub-system; remaining entries are copied\n    template <typename VectorIn, typename VectorOut>\n    void adjoint_solve(const VectorIn& x, VectorOut& y) const\n    {\n\tmtl::vampir_trace<5057> tracer;\n\ty.checked_change_resource(x);\n\n\tVectorIn&  x0= create_x0(x);\n\tVectorOut& y0= create_y0(y);\n\n\trestrict(x, x0);\n\tP.adjoint_solve(x0, y0);\n\t// y0= adjoint_solve(P, x0); // doesn't compile yet for unknown reasons\n\tprolongate(x, y0, y);\n    }\n\n  private:\n    tag_type          tags;\n    size_t            n;\n    matrix_container  mc;\n    pc_type           P;\n};\n\ntemplate <typename Preconditioner, typename Matrix, bool Store, typename Vector>\nsolver<sub_matrix_pc<Preconditioner, Matrix, Store>, Vector, false>\ninline solve(const sub_matrix_pc<Preconditioner, Matrix, Store>& P, const Vector& x)\n{\n    return solver<sub_matrix_pc<Preconditioner, Matrix, Store>, Vector, false>(P, x);\n}\n\ntemplate <typename Preconditioner, typename Matrix, bool Store, typename Vector>\nsolver<sub_matrix_pc<Preconditioner, Matrix, Store>, Vector, true>\ninline adjoint_solve(const sub_matrix_pc<Preconditioner, Matrix, Store>& P, const Vector& x)\n{\n    return solver<sub_matrix_pc<Preconditioner, Matrix, Store>, Vector, true>(P, x);\n}\n\n\n}} // namespace itl::pc\n\n#endif // ITL_PC_SUB_MATRIX_PC_INCLUDE\n", "meta": {"hexsha": "10d5130fc4a528b8603a788e2bb5e43cad14f4da", "size": 5660, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/numeric/itl/pc/sub_matrix_pc.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/itl/pc/sub_matrix_pc.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/itl/pc/sub_matrix_pc.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.4422110553, "max_line_length": 98, "alphanum_fraction": 0.6586572438, "num_tokens": 1576, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.30594045969972306}}
{"text": "/*\n Copyright (C) 2016-2020 Quaternion Risk Management Ltd\n All rights reserved.\n\n This file is part of ORE, a free-software/open-source library\n for transparent pricing and risk analysis - http://opensourcerisk.org\n\n ORE is free software: you can redistribute it and/or modify it\n under the terms of the Modified BSD License.  You should have received a\n copy of the license along with this program.\n The license is also available online at <http://opensourcerisk.org>\n\n This program is distributed on the basis that it will form a useful\n contribution to risk analytics and model standardisation, but WITHOUT\n ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n FITNESS FOR A PARTICULAR PURPOSE. See the license for more details.\n*/\n\n#include <orea/aggregation/postprocess.hpp>\n#include <orea/aggregation/exposureallocator.hpp>\n#include <orea/aggregation/dimcalculator.hpp>\n#include <orea/aggregation/dimregressioncalculator.hpp>\n#include <orea/aggregation/dynamiccreditxvacalculator.hpp>\n#include <orea/aggregation/xvacalculator.hpp>\n#include <orea/aggregation/staticcreditxvacalculator.hpp>\n#include <orea/aggregation/cvaspreadsensitivitycalculator.hpp>\n#include <ored/utilities/log.hpp>\n#include <ored/utilities/vectorutils.hpp>\n#include <ql/errors.hpp>\n#include <ql/time/calendars/weekendsonly.hpp>\n#include <ql/version.hpp>\n\n#include <ql/math/distributions/normaldistribution.hpp>\n#include <ql/math/generallinearleastsquares.hpp>\n#include <ql/math/kernelfunctions.hpp>\n#include <ql/methods/montecarlo/lsmbasissystem.hpp>\n#include <ql/time/daycounters/actualactual.hpp>\n\n#include <qle/math/nadarayawatson.hpp>\n#include <qle/math/stabilisedglls.hpp>\n\n#include <boost/accumulators/accumulators.hpp>\n#include <boost/accumulators/statistics/error_of_mean.hpp>\n#include <boost/accumulators/statistics/mean.hpp>\n#include <boost/accumulators/statistics/stats.hpp>\n\nusing namespace std;\nusing namespace QuantLib;\n\nusing namespace boost::accumulators;\n\nnamespace ore {\nnamespace analytics {\n\nPostProcess::PostProcess(\n    const boost::shared_ptr<Portfolio>& portfolio, const boost::shared_ptr<NettingSetManager>& nettingSetManager,\n    const boost::shared_ptr<Market>& market, const std::string& configuration, const boost::shared_ptr<NPVCube>& cube,\n    const boost::shared_ptr<AggregationScenarioData>& scenarioData, const map<string, bool>& analytics,\n    const string& baseCurrency, const string& allocMethod, Real marginalAllocationLimit, Real quantile,\n    const string& calculationType, const string& dvaName, const string& fvaBorrowingCurve,\n    const string& fvaLendingCurve,const boost::shared_ptr<DynamicInitialMarginCalculator>& dimCalculator,\n    const boost::shared_ptr<CubeInterpretation>& cubeInterpretation, bool fullInitialCollateralisation,\n    vector<Period> cvaSensiGrid, Real cvaSensiShiftSize,\n    Real kvaCapitalDiscountRate, Real kvaAlpha, Real kvaRegAdjustment, Real kvaCapitalHurdle, Real kvaOurPdFloor,\n    Real kvaTheirPdFloor, Real kvaOurCvaRiskWeight, Real kvaTheirCvaRiskWeight, const boost::shared_ptr<NPVCube>& cptyCube,\n    const string& flipViewBorrowingCurvePostfix, const string& flipViewLendingCurvePostfix)\n    : portfolio_(portfolio), nettingSetManager_(nettingSetManager), market_(market), configuration_(configuration),\n      cube_(cube), cptyCube_(cptyCube), scenarioData_(scenarioData), analytics_(analytics), baseCurrency_(baseCurrency), quantile_(quantile),\n      calcType_(parseCollateralCalculationType(calculationType)), dvaName_(dvaName),\n      fvaBorrowingCurve_(fvaBorrowingCurve), fvaLendingCurve_(fvaLendingCurve), dimCalculator_(dimCalculator),\n      cubeInterpretation_(cubeInterpretation), fullInitialCollateralisation_(fullInitialCollateralisation),\n      cvaSpreadSensiGrid_(cvaSensiGrid), cvaSpreadSensiShiftSize_(cvaSensiShiftSize),\n      kvaCapitalDiscountRate_(kvaCapitalDiscountRate), kvaAlpha_(kvaAlpha), kvaRegAdjustment_(kvaRegAdjustment),\n      kvaCapitalHurdle_(kvaCapitalHurdle), kvaOurPdFloor_(kvaOurPdFloor), kvaTheirPdFloor_(kvaTheirPdFloor),\n      kvaOurCvaRiskWeight_(kvaOurCvaRiskWeight), kvaTheirCvaRiskWeight_(kvaTheirCvaRiskWeight) {\n\n    // set a default value for the cube interpretation object if it is NULL\n    if (!cubeInterpretation_) {\n        WLOG(\"cube interpretation is not set, use regular\");\n        cubeInterpretation_ = boost::make_shared<RegularCubeInterpretation>();\n    }\n    boost::shared_ptr<RegularCubeInterpretation> regularCubeInterpretation =\n        boost::dynamic_pointer_cast<RegularCubeInterpretation>(cubeInterpretation_);\n    bool isRegularCubeStorage = (regularCubeInterpretation != NULL);\n\n    LOG(\"cube storage is regular: \" << isRegularCubeStorage);\n    LOG(\"cube dates: \" << cube->dates().size());\n\n    QL_REQUIRE(marginalAllocationLimit > 0.0, \"positive allocationLimit expected\");\n\n    // check portfolio and cube have the same trade ids, in the same order\n    QL_REQUIRE(portfolio->size() == cube_->ids().size(),\n               \"PostProcess::PostProcess(): portfolio size (\"\n                   << portfolio->size() << \") does not match cube trade size (\" << cube_->ids().size() << \")\");\n    for (Size i = 0; i < portfolio->size(); ++i) {\n        QL_REQUIRE(portfolio->trades()[i]->id() == cube_->ids()[i], \"PostProcess::PostProcess(): portfolio trade #\"\n                                                                        << i << \" (id=\" << portfolio->trades()[i]->id()\n                                                                        << \") does not match cube trade id (\"\n                                                                        << cube_->ids()[i]);\n    }\n\n    if (analytics_[\"dynamicCredit\"]) {\n        QL_REQUIRE(cptyCube_, \"cptyCube cannot be null when dynamicCredit is ON\");\n        // check portfolio and cptyCube have the same counterparties, in the same order\n        QL_REQUIRE(portfolio->counterparties().size() + 1 == cptyCube_->ids().size(),\n                   \"PostProcess::PostProcess(): portfolio counterparty size (\"\n                   << portfolio->counterparties().size() << \") does not match cpty cube trade size (\"\n                   << cptyCube_->ids().size() << \")\");\n        for (Size i = 0; i < portfolio->counterparties().size(); ++i) {\n            QL_REQUIRE(portfolio->counterparties()[i] == cptyCube_->ids()[i],\n                       \"PostProcess::PostProcess(): portfolio counterparty #\"\n                       << i << \" (id=\" << portfolio->counterparties()[i]\n                       << \") does not match cube name id (\"\n                       << cptyCube_->ids()[i]);\n        }\n        QL_REQUIRE(dvaName == cptyCube_->ids().back(),\n                       \"PostProcess::PostProcess(): dvaName (\" << dvaName\n                       << \") does not match cube name id (\"\n                       << cptyCube_->ids().back());\n    }\n\n    ExposureAllocator::AllocationMethod allocationMethod = parseAllocationMethod(allocMethod);\n\n    /***********************************************\n     * Step 0: Netting as of today\n     * a) Compute the netting set NPV as of today\n     * b) Find the final maturity of the netting set\n     */\n    LOG(\"Compute netting set NPVs as of today and netting set maturity\");\n    // Don't use Settings::instance().evaluationDate() here, this has moved to simulation end date.\n    Date today = market->asofDate();\n    LOG(\"AsOfDate = \" << QuantLib::io::iso_date(today));\n\n    /***************************************************************\n     * Step 1: Dynamic Initial Margin calculation\n     * Fills DIM cube per netting set that can be\n     * - returned to be further analysed\n     * - used in collateral calculation\n     * - used in MVA calculation\n     */\n    if (analytics_[\"dim\"] || analytics_[\"mva\"]) {\n        QL_REQUIRE(dimCalculator_, \"DIM calculator not set\");\n        dimCalculator_->build();\n    }\n\n    /************************************************************\n     * Step 2: Trade Exposure and Netting\n     * a) Aggregation across scenarios per trade and date\n     *    This yields single trade exposure profiles, EPE and ENE\n     * b) Aggregation of NPVs within netting sets per date\n     *    and scenario. This prepares the netting set exposure\n     *    calculation below\n     */\n    exposureCalculator_ =\n        boost::make_shared<ExposureCalculator>(\n            portfolio, cube_, cubeInterpretation_,\n            market_, analytics_[\"exerciseNextBreak\"], baseCurrency_, configuration_,\n            quantile_, calcType_, analytics_[\"dynamicCredit\"], analytics_[\"flipViewXVA\"]\n        );\n    exposureCalculator_->build();\n\n    /******************************************************************\n     * Step 3: Netting set exposure and allocation to trades\n     *\n     * a) Compute all netting set exposure profiles EPE and ENE using\n     *    collateral if CSAs are given and active.\n     * b) Compute the expected collateral balance for each netting set.\n     * c) Allocate each netting set's exposure profile to the trade\n     *    level such that the trade exposures add up to the netting\n     *    set exposure.\n     *    Reference:\n     *    Michael Pykhtin & Dan Rosen, Pricing Counterparty Risk\n     *    at the Trade Level and CVA Allocations, October 2010\n     */\n    nettedExposureCalculator_ =\n        boost::make_shared<NettedExposureCalculator>(\n            portfolio_, market_, cube_, baseCurrency, configuration_, quantile_,\n            calcType_, analytics_[\"dynamicCredit\"], nettingSetManager_,\n\t        exposureCalculator_->nettingSetDefaultValue(),\n\t        exposureCalculator_->nettingSetCloseOutValue(),\n            scenarioData_, cubeInterpretation_, analytics_[\"dim\"],\n            dimCalculator_, fullInitialCollateralisation_,\n            allocationMethod == ExposureAllocator::AllocationMethod::Marginal, marginalAllocationLimit,\n            exposureCalculator_->exposureCube(), ExposureCalculator::allocatedEPE, ExposureCalculator::allocatedENE,\n            analytics_[\"flipViewXVA\"]\n        );\n    nettedExposureCalculator_->build();\n\n    /********************************************************\n     * Update Stand Alone XVAs\n     * needed for some of the simple allocation methods below\n     */\n    if (analytics_[\"dynamicCredit\"]) {\n        cvaCalculator_ = boost::make_shared<DynamicCreditXvaCalculator>(\n            portfolio_, market_, configuration_,baseCurrency_, dvaName_,\n            fvaBorrowingCurve_, fvaLendingCurve_, analytics_[\"dim\"],\n            dimCalculator, exposureCalculator_->exposureCube(),\n            nettedExposureCalculator_->exposureCube(), cptyCube_,\n            ExposureCalculator::ExposureIndex::EPE,\n            ExposureCalculator::ExposureIndex::ENE,\n            NettedExposureCalculator::ExposureIndex::EPE,\n            NettedExposureCalculator::ExposureIndex::ENE, 0, analytics_[\"flipViewXVA\"], \n            flipViewBorrowingCurvePostfix, flipViewLendingCurvePostfix);\n    } else {\n        cvaCalculator_ = boost::make_shared<StaticCreditXvaCalculator>(\n            portfolio_, market_, configuration_,baseCurrency_, dvaName_,\n            fvaBorrowingCurve_, fvaLendingCurve_, analytics_[\"dim\"],\n            dimCalculator, exposureCalculator_->exposureCube(),\n            nettedExposureCalculator_->exposureCube(),\n            ExposureCalculator::ExposureIndex::EPE,\n            ExposureCalculator::ExposureIndex::ENE,\n            NettedExposureCalculator::ExposureIndex::EPE,\n            NettedExposureCalculator::ExposureIndex::ENE, analytics_[\"flipViewXVA\"], \n            flipViewBorrowingCurvePostfix, flipViewLendingCurvePostfix);\n    }\n    cvaCalculator_->build();\n\n    /***************************\n     * Simple allocation methods\n     */\n    boost::shared_ptr<ExposureAllocator> exposureAllocator;\n    if (allocationMethod == ExposureAllocator::AllocationMethod::Marginal) {\n        DLOG(\"Marginal Calculation handled in NettedExposureCalculator\");\n    }\n    else if (allocationMethod == ExposureAllocator::AllocationMethod::RelativeFairValueNet)\n        exposureAllocator = boost::make_shared<RelativeFairValueNetExposureAllocator>(\n            portfolio, exposureCalculator_->exposureCube(),\n            nettedExposureCalculator_->exposureCube(), cube_,\n            ExposureCalculator::allocatedEPE, ExposureCalculator::allocatedENE,\n            ExposureCalculator::EPE, ExposureCalculator::ENE,\n            NettedExposureCalculator::EPE, NettedExposureCalculator::ENE);\n    else if (allocationMethod == ExposureAllocator::AllocationMethod::RelativeFairValueGross)\n        exposureAllocator = boost::make_shared<RelativeFairValueGrossExposureAllocator>(\n            portfolio, exposureCalculator_->exposureCube(),\n            nettedExposureCalculator_->exposureCube(), cube_,\n            ExposureCalculator::allocatedEPE, ExposureCalculator::allocatedENE,\n            ExposureCalculator::EPE, ExposureCalculator::ENE,\n            NettedExposureCalculator::EPE, NettedExposureCalculator::ENE);\n    else if (allocationMethod == ExposureAllocator::AllocationMethod::RelativeXVA)\n        exposureAllocator = boost::make_shared<RelativeXvaExposureAllocator>(\n            portfolio, exposureCalculator_->exposureCube(),\n            nettedExposureCalculator_->exposureCube(), cube_,\n            cvaCalculator_->tradeCva(), cvaCalculator_->tradeDva(),\n            cvaCalculator_->nettingSetSumCva(), cvaCalculator_->nettingSetSumDva(),\n            ExposureCalculator::allocatedEPE, ExposureCalculator::allocatedENE,\n            ExposureCalculator::EPE, ExposureCalculator::ENE,\n            NettedExposureCalculator::EPE, NettedExposureCalculator::ENE);\n    else if (allocationMethod == ExposureAllocator::AllocationMethod::None)\n        exposureAllocator = boost::make_shared<NoneExposureAllocator>(\n            portfolio, exposureCalculator_->exposureCube(),\n            nettedExposureCalculator_->exposureCube());\n    else\n        QL_FAIL(\"allocationMethod \" << allocationMethod << \" not available\");\n    if(exposureAllocator)\n        exposureAllocator->build();\n\n    /********************************************************\n     * Update Allocated XVAs\n     */\n    if (analytics_[\"dynamicCredit\"]) {\n        allocatedCvaCalculator_ = boost::make_shared<DynamicCreditXvaCalculator>(\n            portfolio_, market_, configuration_, baseCurrency_, dvaName_, fvaBorrowingCurve_, fvaLendingCurve_,\n            analytics_[\"dim\"], dimCalculator, exposureCalculator_->exposureCube(),\n            nettedExposureCalculator_->exposureCube(), cptyCube_, ExposureCalculator::ExposureIndex::allocatedEPE,\n            ExposureCalculator::ExposureIndex::allocatedENE, NettedExposureCalculator::ExposureIndex::EPE,\n            NettedExposureCalculator::ExposureIndex::ENE, 0, analytics_[\"flipViewXVA\"], flipViewBorrowingCurvePostfix,\n            flipViewLendingCurvePostfix);\n    } else {\n        allocatedCvaCalculator_ = boost::make_shared<StaticCreditXvaCalculator>(\n            portfolio_, market_, configuration_, baseCurrency_, dvaName_, fvaBorrowingCurve_, fvaLendingCurve_,\n            analytics_[\"dim\"], dimCalculator, exposureCalculator_->exposureCube(),\n            nettedExposureCalculator_->exposureCube(), ExposureCalculator::ExposureIndex::allocatedEPE,\n            ExposureCalculator::ExposureIndex::allocatedENE, NettedExposureCalculator::ExposureIndex::EPE,\n            NettedExposureCalculator::ExposureIndex::ENE, analytics_[\"flipViewXVA\"], flipViewBorrowingCurvePostfix,\n            flipViewLendingCurvePostfix);\n    }\n    allocatedCvaCalculator_->build();\n\n    /********************************************************\n     * Cache average EPE and ENE\n     */\n    for (auto tradeId : tradeIds()) {\n        tradeEPE_[tradeId] = exposureCalculator_->epe(tradeId);\n        tradeENE_[tradeId] = exposureCalculator_->ene(tradeId);\n        allocatedTradeEPE_[tradeId] = exposureCalculator_->allocatedEpe(tradeId);\n        allocatedTradeENE_[tradeId] = exposureCalculator_->allocatedEne(tradeId);\n    }\n    for (auto nettingSetId : nettingSetIds()) {\n        netEPE_[nettingSetId] = nettedExposureCalculator_->epe(nettingSetId);\n        netENE_[nettingSetId] = nettedExposureCalculator_->ene(nettingSetId);\n    }\n\n    /********************************************************\n     * Calculate netting set KVA-CCR and KVA-CVA\n     */\n    updateNettingSetKVA();\n\n    /***************************************\n     * Calculate netting set CVA sensitivity\n     */\n    updateNettingSetCvaSensitivity();\n}\n\nvoid PostProcess::updateNettingSetKVA() {\n\n    // Loop over all netting sets\n    for (auto nettingSetId : nettingSetIds()) {\n        // Init results\n        ourNettingSetKVACCR_[nettingSetId] = 0.0;\n        theirNettingSetKVACCR_[nettingSetId] = 0.0;\n        ourNettingSetKVACVA_[nettingSetId] = 0.0;\n        theirNettingSetKVACVA_[nettingSetId] = 0.0;\n    }\n\n    if (!analytics_[\"kva\"])\n        return;\n\n    LOG(\"Update netting set KVA\");\n    \n    vector<Date> dateVector = cube_->dates();\n    Size dates = dateVector.size();\n    Date today = market_->asofDate();\n    Handle<YieldTermStructure> discountCurve = market_->discountCurve(baseCurrency_, configuration_);\n    DayCounter dc = ActualActual();\n\n    // Loop over all netting sets\n    for (auto nettingSetId : nettingSetIds()) {\n        string cid;\n        if (analytics_[\"flipViewXVA\"]) {\n            cid = dvaName_;\n        } else {\n            cid = nettedExposureCalculator_->counterparty(nettingSetId);\n        }\n        LOG(\"KVA for netting set \" << nettingSetId);\n\n        // Main input are the EPE and ENE profiles, previously computed\n        vector<Real> epe = netEPE_[nettingSetId];\n        vector<Real> ene = netENE_[nettingSetId];\n\n        // PD from counterparty Dts, floored to avoid 0 ...\n        // Today changed to today+1Y to get the one-year PD\n        Handle<DefaultProbabilityTermStructure> cvaDts = market_->defaultCurve(cid, configuration_);\n        QL_REQUIRE(!cvaDts.empty(), \"Default curve missing for counterparty \" << cid);\n        Real cvaRR = market_->recoveryRate(cid, configuration_)->value();\n        Real PD1 = std::max(cvaDts->defaultProbability(today + 1 * Years), 0.000000000001);\n        Real LGD1 = (1 - cvaRR);\n\n        // FIXME: if flipViewXVA is sufficient, then all code for their KVA-CCR could be discarded here...\n        Handle<DefaultProbabilityTermStructure> dvaDts;\n        Real dvaRR = 0.0;\n        Real PD2 = 0;\n        if (analytics_[\"flipViewXVA\"]) {\n            dvaName_ = nettedExposureCalculator_->counterparty(nettingSetId);\n        }\n        if (dvaName_ != \"\") {\n            dvaDts = market_->defaultCurve(dvaName_, configuration_);\n            dvaRR = market_->recoveryRate(dvaName_, configuration_)->value();\n            PD2 = std::max(dvaDts->defaultProbability(today + 1 * Years), 0.000000000001);\n        } else {\n            ALOG(\"dvaName not specified, own PD set to zero for their KVA calculation\");\n        }\n        Real LGD2 = (1 - dvaRR);\n\n        // Granularity adjustment, Gordy (2004):\n        Real rho1 = 0.12 * (1 - std::exp(-50 * PD1)) / (1 - std::exp(-50)) +\n                    0.24 * (1 - (1 - std::exp(-50 * PD1)) / (1 - std::exp(-50)));\n        Real rho2 = 0.12 * (1 - std::exp(-50 * PD2)) / (1 - std::exp(-50)) +\n                    0.24 * (1 - (1 - std::exp(-50 * PD2)) / (1 - std::exp(-50)));\n\n        // Basel II internal rating based (IRB) estimate of worst case PD:\n        // Large homogeneous pool (LHP) approximation of Vasicek (1997)\n        InverseCumulativeNormal icn;\n        CumulativeNormalDistribution cnd;\n        Real PD99_1 = cnd((icn(PD1) + std::sqrt(rho1) * icn(0.999)) / (std::sqrt(1 - rho1))) - PD1;\n        Real PD99_2 = cnd((icn(PD2) + std::sqrt(rho2) * icn(0.999)) / (std::sqrt(1 - rho2))) - PD2;\n\n        // KVA regulatory PD, worst case PD, floored at 0.03 for corporates and banks, not floored for sovereigns\n        Real kva99PD1 = std::max(PD99_1, kvaTheirPdFloor_);\n        Real kva99PD2 = std::max(PD99_2, kvaOurPdFloor_);\n\n        // Factor B(PD) for the maturity adjustment factor, B(PD) = (0.11852 - 0.05478 * ln(PD)) ^ 2\n        Real kvaMatAdjB1 = std::pow((0.11852 - 0.05478 * std::log(PD1)), 2.0);\n        Real kvaMatAdjB2 = std::pow((0.11852 - 0.05478 * std::log(PD2)), 2.0);\n\n        DLOG(\"Our KVA-CCR \" << nettingSetId << \": PD=\" << PD1);\n        DLOG(\"Our KVA-CCR \" << nettingSetId << \": LGD=\" << LGD1);\n        DLOG(\"Our KVA-CCR \" << nettingSetId << \": rho=\" << rho1);\n        DLOG(\"Our KVA-CCR \" << nettingSetId << \": PD99=\" << PD99_1);\n        DLOG(\"Our KVA-CCR \" << nettingSetId << \": PD Floor=\" << kvaTheirPdFloor_);\n        DLOG(\"Our KVA-CCR \" << nettingSetId << \": Floored PD99=\" << kva99PD1);\n        DLOG(\"Our KVA-CCR \" << nettingSetId << \": B(PD)=\" << kvaMatAdjB1);\n\n        DLOG(\"Their KVA-CCR \" << nettingSetId << \": PD=\" << PD2);\n        DLOG(\"Their KVA-CCR \" << nettingSetId << \": LGD=\" << LGD2);\n        DLOG(\"Their KVA-CCR \" << nettingSetId << \": rho=\" << rho2);\n        DLOG(\"Their KVA-CCR \" << nettingSetId << \": PD99=\" << PD99_2);\n        DLOG(\"Their KVA-CCR \" << nettingSetId << \": PD Floor=\" << kvaOurPdFloor_);\n        DLOG(\"Their KVA-CCR \" << nettingSetId << \": Floored PD99=\" << kva99PD2);\n        DLOG(\"Their KVA-CCR \" << nettingSetId << \": B(PD)=\" << kvaMatAdjB2);\n\n        for (Size j = 0; j < dates; ++j) {\n            Date d0 = j == 0 ? today : cube_->dates()[j - 1];\n            Date d1 = cube_->dates()[j];\n\n            // Preprocess:\n            // 1) Effective maturity from effective expected exposure as of time j\n            //    Index _1 corresponds to our perspective, index _2 to their perspective.\n            // 2) Basel EEPE as of time j, i.e. as time averge over EEE, starting at time j\n            // More accuracy may be achieved here by using a Longstaff-Schwartz method / regression\n            Real eee_kva_1 = 0.0, eee_kva_2 = 0.0;\n            Real effMatNumer1 = 0.0, effMatNumer2 = 0.0;\n            Real effMatDenom1 = 0.0, effMatDenom2 = 0.0;\n            Real eepe_kva_1 = 0, eepe_kva_2 = 0.0;\n            Size kmax = j, count = 0;\n            // Cut off index for EEPE/EENE calculation: One year ahead\n            while (dateVector[kmax] < dateVector[j] + 1 * Years + 4 * Days && kmax < dates - 1)\n                kmax++;\n            Real sumdt = 0.0, eee1_b = 0.0, eee2_b = 0.0;\n            for (Size k = j; k < dates; ++k) {\n                Date d2 = cube_->dates()[k];\n                Date prevDate = k == 0 ? today : dateVector[k - 1];\n\n                eee_kva_1 = std::max(eee_kva_1, epe[k + 1]);\n                eee_kva_2 = std::max(eee_kva_2, ene[k + 1]);\n\n                // Components of the KVA maturity adjustment MA as of time j\n                if (dc.yearFraction(d1, d2) > 1.0) {\n                    effMatNumer1 += epe[k + 1] * dc.yearFraction(prevDate, d2);\n                    effMatNumer2 += ene[k + 1] * dc.yearFraction(prevDate, d2);\n                }\n                if (dc.yearFraction(d1, d2) <= 1.0) {\n                    effMatDenom1 += eee_kva_1 * dc.yearFraction(prevDate, d2);\n                    effMatDenom2 += eee_kva_2 * dc.yearFraction(prevDate, d2);\n                }\n\n                if (k < kmax) {\n                    Real dt = dc.yearFraction(cube_->dates()[k], cube_->dates()[k + 1]);\n                    sumdt += dt;\n                    Real epe_b = epe[k + 1] / discountCurve->discount(dateVector[k]);\n                    Real ene_b = ene[k + 1] / discountCurve->discount(dateVector[k]);\n                    eee1_b = std::max(epe_b, eee1_b);\n                    eee2_b = std::max(ene_b, eee2_b);\n                    eepe_kva_1 += eee1_b * dt;\n                    eepe_kva_2 += eee2_b * dt;\n                    count++;\n                }\n            }\n\n            // Normalize EEPE/EENE calculation\n            eepe_kva_1 = count > 0 ? eepe_kva_1 / sumdt : 0.0;\n            eepe_kva_2 = count > 0 ? eepe_kva_2 / sumdt : 0.0;\n\n            // KVA CCR using the IRB risk weighted asset method and IMM:\n            // KVA effective maturity of the nettingSet, capped at 5\n            Real kvaNWMaturity1 = std::min(1.0 + (effMatDenom1 == 0.0 ? 0.0 : effMatNumer1 / effMatDenom1), 5.0);\n            Real kvaNWMaturity2 = std::min(1.0 + (effMatDenom2 == 0.0 ? 0.0 : effMatNumer2 / effMatDenom2), 5.0);\n\n            // Maturity adjustment factor for the RWA method:\n            // MA(PD, M) = (1 + (M - 2.5) * B(PD)) / (1 - 1.5 * B(PD)), capped at 5, floored at 1, M = effective\n            // maturity\n            Real kvaMatAdj1 =\n                std::max(std::min((1.0 + (kvaNWMaturity1 - 2.5) * kvaMatAdjB1) / (1.0 - 1.5 * kvaMatAdjB1), 5.0), 1.0);\n            Real kvaMatAdj2 =\n                std::max(std::min((1.0 + (kvaNWMaturity2 - 2.5) * kvaMatAdjB2) / (1.0 - 1.5 * kvaMatAdjB2), 5.0), 1.0);\n\n            // CCR Capital: RC = EAD x LGD x PD99.9 x MA(PD, M); EAD = alpha x EEPE(t) (approximated by EPE here);\n            Real kvaRC1 = kvaAlpha_ * eepe_kva_1 * LGD1 * kva99PD1 * kvaMatAdj1;\n            Real kvaRC2 = kvaAlpha_ * eepe_kva_2 * LGD2 * kva99PD2 * kvaMatAdj2;\n\n            // Expected risk capital discounted at capital discount rate\n            Real kvaCapitalDiscount = 1 / std::pow(1 + kvaCapitalDiscountRate_, dc.yearFraction(today, d0));\n            Real kvaCCRIncrement1 =\n                kvaRC1 * kvaCapitalDiscount * dc.yearFraction(d0, d1) * kvaCapitalHurdle_ * kvaRegAdjustment_;\n            Real kvaCCRIncrement2 =\n                kvaRC2 * kvaCapitalDiscount * dc.yearFraction(d0, d1) * kvaCapitalHurdle_ * kvaRegAdjustment_;\n\n            ourNettingSetKVACCR_[nettingSetId] += kvaCCRIncrement1;\n            theirNettingSetKVACCR_[nettingSetId] += kvaCCRIncrement2;\n\n            DLOG(\"Our KVA-CCR for \" << nettingSetId << \": \" << j << \" EEPE=\" << setprecision(2) << eepe_kva_1\n                                    << \" EPE=\" << epe[j] << \" RC=\" << kvaRC1 << \" M=\" << setprecision(6)\n                                    << kvaNWMaturity1 << \" MA=\" << kvaMatAdj1 << \" Cost=\" << setprecision(2)\n                                    << kvaCCRIncrement1 << \" KVA=\" << ourNettingSetKVACCR_[nettingSetId]);\n            DLOG(\"Their KVA-CCR for \" << nettingSetId << \": \" << j << \" EENE=\" << eepe_kva_2 << \" ENE=\" << ene[j]\n                                      << \" RC=\" << kvaRC2 << \" M=\" << setprecision(6) << kvaNWMaturity2\n                                      << \" MA=\" << kvaMatAdj2 << \" Cost=\" << setprecision(2) << kvaCCRIncrement2\n                                      << \" KVA=\" << theirNettingSetKVACCR_[nettingSetId]);\n\n            // CVA Capital\n            // effective maturity without cap at 5, DF set to 1 for IMM banks\n            // TODO: Set MA in CCR capital calculation to 1\n            Real kvaCvaMaturity1 = 1.0 + (effMatDenom1 == 0.0 ? 0.0 : effMatNumer1 / effMatDenom1);\n            Real kvaCvaMaturity2 = 1.0 + (effMatDenom2 == 0.0 ? 0.0 : effMatNumer2 / effMatDenom2);\n            Real scva1 = kvaTheirCvaRiskWeight_ * kvaCvaMaturity1 * eepe_kva_1;\n            Real scva2 = kvaOurCvaRiskWeight_ * kvaCvaMaturity2 * eepe_kva_2;\n            Real kvaCVAIncrement1 =\n                scva1 * kvaCapitalDiscount * dc.yearFraction(d0, d1) * kvaCapitalHurdle_ * kvaRegAdjustment_;\n            Real kvaCVAIncrement2 =\n                scva2 * kvaCapitalDiscount * dc.yearFraction(d0, d1) * kvaCapitalHurdle_ * kvaRegAdjustment_;\n\n            DLOG(\"Our KVA-CVA for \" << nettingSetId << \": \" << j << \" EEPE=\" << eepe_kva_1 << \" SCVA=\" << scva1\n                                    << \" Cost=\" << kvaCVAIncrement1);\n            DLOG(\"Their KVA-CVA for \" << nettingSetId << \": \" << j << \" EENE=\" << eepe_kva_2 << \" SCVA=\" << scva2\n                                      << \" Cost=\" << kvaCVAIncrement2);\n\n            ourNettingSetKVACVA_[nettingSetId] += kvaCVAIncrement1;\n            theirNettingSetKVACVA_[nettingSetId] += kvaCVAIncrement2;\n        }\n    }\n\n    LOG(\"Update netting set KVA done\");\n}\n\nvoid PostProcess::updateNettingSetCvaSensitivity() {\n\n    if (!analytics_[\"cvaSensi\"])\n        return;\n\n    LOG(\"Update netting set CVA sensitvities\");\n\n    Handle<YieldTermStructure> discountCurve = market_->discountCurve(baseCurrency_, configuration_);\n\n    for (auto n : netEPE_) {\n        string nettingSetId = n.first;\n        vector<Real> epe = netEPE_[nettingSetId];\n        string cid;\n        Handle<DefaultProbabilityTermStructure> cvaDts;\n        Real cvaRR;\n        if (analytics_[\"flipViewXVA\"]) {\n            cid = dvaName_;\n        } else {\n            cid = nettedExposureCalculator_->counterparty(nettingSetId);\n        }\n        cvaDts = market_->defaultCurve(cid);\n        QL_REQUIRE(!cvaDts.empty(), \"Default curve missing for counterparty \" << cid);\n        cvaRR = market_->recoveryRate(cid, configuration_)->value();\n\n\t    bool cvaSensi = analytics_[\"cvaSensi\"];\n\t    LOG(\"CVA Sensitivity: \" << cvaSensi);\n\t    if (cvaSensi) {\n\t        boost::shared_ptr<CVASpreadSensitivityCalculator> cvaSensiCalculator = boost::make_shared<CVASpreadSensitivityCalculator>(\n\t             nettingSetId, market_->asofDate(), epe, cube_->dates(), cvaDts, cvaRR, discountCurve, cvaSpreadSensiGrid_, cvaSpreadSensiShiftSize_);\n\n\t        for (Size i = 0; i < cvaSensiCalculator->shiftTimes().size(); ++i) {\n\t            DLOG(\"CVA Sensi Calculator: t=\" << cvaSensiCalculator->shiftTimes()[i]\n\t\t         << \" h=\" << cvaSensiCalculator->hazardRateSensitivities()[i] \n\t\t         << \" s=\" << cvaSensiCalculator->cdsSpreadSensitivities()[i]); \n\t        }\n\n\t        netCvaHazardRateSensi_[nettingSetId] = cvaSensiCalculator->hazardRateSensitivities();\n\t        netCvaSpreadSensi_[nettingSetId] = cvaSensiCalculator->cdsSpreadSensitivities();\n\t        cvaSpreadSensiTimes_ = cvaSensiCalculator->shiftTimes();\n\t    } else {\n\t        cvaSpreadSensiTimes_ = vector<Real>();\n\t        netCvaHazardRateSensi_[nettingSetId] = vector<Real>();\n\t        netCvaSpreadSensi_[nettingSetId] = vector<Real>();\n\t    }\n    }\n\n    LOG(\"Update netting set CVA sensitivities done\");\n}\n  \nconst vector<Real>& PostProcess::tradeEPE(const string& tradeId) {\n    QL_REQUIRE(tradeEPE_.find(tradeId) != tradeEPE_.end(), \"Trade \" << tradeId << \" not found in exposure map\");\n    return tradeEPE_[tradeId];\n}\n\nconst vector<Real>& PostProcess::tradeENE(const string& tradeId) {\n    QL_REQUIRE(tradeENE_.find(tradeId) != tradeENE_.end(), \"Trade \" << tradeId << \" not found in exposure map\");\n    return tradeENE_[tradeId];\n}\n\nconst vector<Real>& PostProcess::tradeEE_B(const string& tradeId) {\n    return exposureCalculator_->ee_b(tradeId);\n}\n\nconst Real& PostProcess::tradeEPE_B(const string& tradeId) {\n    return exposureCalculator_->epe_b(tradeId);\n}\n\nconst vector<Real>& PostProcess::tradeEEE_B(const string& tradeId) {\n    return exposureCalculator_->eee_b(tradeId);\n}\n\nconst Real& PostProcess::tradeEEPE_B(const string& tradeId) {\n    return exposureCalculator_->eepe_b(tradeId);\n}\n\nconst vector<Real>& PostProcess::tradePFE(const string& tradeId) {\n    return exposureCalculator_->pfe(tradeId);\n}\n\nconst vector<Real>& PostProcess::netEPE(const string& nettingSetId) {\n    QL_REQUIRE(netEPE_.find(nettingSetId) != netEPE_.end(),\n               \"Netting set \" << nettingSetId << \" not found in exposure map\");\n    return netEPE_[nettingSetId];\n}\n\nconst vector<Real>& PostProcess::netENE(const string& nettingSetId) {\n    QL_REQUIRE(netENE_.find(nettingSetId) != netENE_.end(),\n               \"Netting set \" << nettingSetId << \" not found in exposure map\");\n    return netENE_[nettingSetId];\n}\n\nvector<Real> PostProcess::netCvaHazardRateSensitivity(const string& nettingSetId) {\n    if (netCvaHazardRateSensi_.find(nettingSetId) != netCvaHazardRateSensi_.end())\n        return netCvaHazardRateSensi_[nettingSetId];\n    else\n        return vector<Real>();\n}\n\nvector<Real> PostProcess::netCvaSpreadSensitivity(const string& nettingSetId) {\n    if (netCvaSpreadSensi_.find(nettingSetId) != netCvaSpreadSensi_.end())\n        return netCvaSpreadSensi_[nettingSetId];\n    else\n        return vector<Real>();\n}\n\nconst vector<Real>& PostProcess::netEE_B(const string& nettingSetId) {\n    return nettedExposureCalculator_->ee_b(nettingSetId);\n}\n\nconst Real& PostProcess::netEPE_B(const string& nettingSetId) {\n    return nettedExposureCalculator_->epe_b(nettingSetId);\n}\n\nconst vector<Real>& PostProcess::netEEE_B(const string& nettingSetId) {\n    return nettedExposureCalculator_->eee_b(nettingSetId);\n}\n\nconst Real& PostProcess::netEEPE_B(const string& nettingSetId) {\n    return nettedExposureCalculator_->eepe_b(nettingSetId);\n}\n\nconst vector<Real>& PostProcess::netPFE(const string& nettingSetId) {\n    return nettedExposureCalculator_->pfe(nettingSetId);\n}\n\nconst vector<Real>& PostProcess::expectedCollateral(const string& nettingSetId) {\n    return nettedExposureCalculator_->expectedCollateral(nettingSetId);\n}\n\nconst vector<Real>& PostProcess::colvaIncrements(const string& nettingSetId) {\n    return nettedExposureCalculator_->colvaIncrements(nettingSetId);\n}\n\nconst vector<Real>& PostProcess::collateralFloorIncrements(const string& nettingSetId) {\n    return nettedExposureCalculator_->collateralFloorIncrements(nettingSetId);\n}\n\nconst vector<Real>& PostProcess::allocatedTradeEPE(const string& tradeId) {\n    QL_REQUIRE(allocatedTradeEPE_.find(tradeId) != allocatedTradeEPE_.end(),\n               \"Trade \" << tradeId << \" not found in exposure map\");\n    return allocatedTradeEPE_[tradeId];\n}\n\nconst vector<Real>& PostProcess::allocatedTradeENE(const string& tradeId) {\n    QL_REQUIRE(allocatedTradeENE_.find(tradeId) != allocatedTradeENE_.end(),\n               \"Trade \" << tradeId << \" not found in exposure map\");\n    return allocatedTradeENE_[tradeId];\n}\n\nReal PostProcess::tradeCVA(const string& tradeId) {\n    return cvaCalculator_->tradeCva(tradeId);\n}\n\nReal PostProcess::tradeDVA(const string& tradeId) {\n    return cvaCalculator_->tradeDva(tradeId);\n}\n\nReal PostProcess::tradeMVA(const string& tradeId) {\n    return cvaCalculator_->tradeMva(tradeId);\n}\n\nReal PostProcess::tradeFBA(const string& tradeId) {\n    return cvaCalculator_->tradeFba(tradeId);\n}\n\nReal PostProcess::tradeFCA(const string& tradeId) {\n    return cvaCalculator_->tradeFca(tradeId);\n}\n\nReal PostProcess::tradeFBA_exOwnSP(const string& tradeId) {\n    return cvaCalculator_->tradeFba_exOwnSp(tradeId);\n}\n\nReal PostProcess::tradeFCA_exOwnSP(const string& tradeId) {\n    return cvaCalculator_->tradeFca_exOwnSp(tradeId);\n}\n\nReal PostProcess::tradeFBA_exAllSP(const string& tradeId) {\n    return cvaCalculator_->tradeFba_exAllSp(tradeId);\n}\n\nReal PostProcess::tradeFCA_exAllSP(const string& tradeId) {\n    return cvaCalculator_->tradeFca_exAllSp(tradeId);\n}\n\nReal PostProcess::nettingSetCVA(const string& nettingSetId) {\n    return cvaCalculator_->nettingSetCva(nettingSetId);\n}\n\nReal PostProcess::nettingSetDVA(const string& nettingSetId) {\n    return cvaCalculator_->nettingSetDva(nettingSetId);\n}\n\nReal PostProcess::nettingSetMVA(const string& nettingSetId) {\n    return cvaCalculator_->nettingSetMva(nettingSetId);\n\n}\n\nReal PostProcess::nettingSetFBA(const string& nettingSetId) {\n    return cvaCalculator_->nettingSetFba(nettingSetId);\n\n}\n\nReal PostProcess::nettingSetFCA(const string& nettingSetId) {\n    return cvaCalculator_->nettingSetFca(nettingSetId);\n\n}\n\nReal PostProcess::nettingSetOurKVACCR(const string& nettingSetId) {\n    QL_REQUIRE(ourNettingSetKVACCR_.find(nettingSetId) != ourNettingSetKVACCR_.end(),\n               \"NettingSetId \" << nettingSetId << \" not found in nettingSet KVACCR map\");\n    return ourNettingSetKVACCR_[nettingSetId];\n}\n\nReal PostProcess::nettingSetTheirKVACCR(const string& nettingSetId) {\n    QL_REQUIRE(theirNettingSetKVACCR_.find(nettingSetId) != theirNettingSetKVACCR_.end(),\n               \"NettingSetId \" << nettingSetId << \" not found in nettingSet KVACCR map\");\n    return theirNettingSetKVACCR_[nettingSetId];\n}\n\nReal PostProcess::nettingSetOurKVACVA(const string& nettingSetId) {\n    QL_REQUIRE(ourNettingSetKVACVA_.find(nettingSetId) != ourNettingSetKVACVA_.end(),\n               \"NettingSetId \" << nettingSetId << \" not found in nettingSet KVACVA map\");\n    return ourNettingSetKVACVA_[nettingSetId];\n}\n\nReal PostProcess::nettingSetTheirKVACVA(const string& nettingSetId) {\n    QL_REQUIRE(theirNettingSetKVACVA_.find(nettingSetId) != theirNettingSetKVACVA_.end(),\n               \"NettingSetId \" << nettingSetId << \" not found in nettingSet KVACVA map\");\n    return theirNettingSetKVACVA_[nettingSetId];\n}\n\nReal PostProcess::nettingSetFBA_exOwnSP(const string& nettingSetId) {\n    return cvaCalculator_->nettingSetFba_exOwnSp(nettingSetId);\n}\n\nReal PostProcess::nettingSetFCA_exOwnSP(const string& nettingSetId) {\n    return cvaCalculator_->nettingSetFca_exOwnSp(nettingSetId);\n}\n\nReal PostProcess::nettingSetFBA_exAllSP(const string& nettingSetId) {\n    return cvaCalculator_->nettingSetFba_exAllSp(nettingSetId);\n}\n\nReal PostProcess::nettingSetFCA_exAllSP(const string& nettingSetId) {\n    return cvaCalculator_->nettingSetFca_exAllSp(nettingSetId);\n}\n\nReal PostProcess::allocatedTradeCVA(const string& allocatedTradeId) {\n    return allocatedCvaCalculator_->tradeCva(allocatedTradeId);\n}\n\nReal PostProcess::allocatedTradeDVA(const string& allocatedTradeId) {\n    return allocatedCvaCalculator_->tradeDva(allocatedTradeId);\n}\n\nReal PostProcess::nettingSetCOLVA(const string& nettingSetId) {\n    return nettedExposureCalculator_->colva(nettingSetId);\n}\n\nReal PostProcess::nettingSetCollateralFloor(const string& nettingSetId) {\n    return nettedExposureCalculator_->collateralFloor(nettingSetId);\n}\n\nvoid PostProcess::exportDimEvolution(ore::data::Report& dimEvolutionReport) {\n    dimCalculator_->exportDimEvolution(dimEvolutionReport);\n}\n  \nvoid PostProcess::exportDimRegression(const std::string& nettingSet, const std::vector<Size>& timeSteps,\n                                      const std::vector<boost::shared_ptr<ore::data::Report>>& dimRegReports) {\n\n    boost::shared_ptr<RegressionDynamicInitialMarginCalculator> regCalc =\n        boost::dynamic_pointer_cast<RegressionDynamicInitialMarginCalculator>(dimCalculator_);\n\n    if (regCalc)\n        regCalc->exportDimRegression(nettingSet, timeSteps, dimRegReports);\n}\n\n} // namespace analytics\n} // namespace ore\n", "meta": {"hexsha": "0e5359e0d9e9c3c4db8fbe0ab273cfbedecf1657", "size": 38081, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "OREAnalytics/orea/aggregation/postprocess.cpp", "max_stars_repo_name": "mrslezak/Engine", "max_stars_repo_head_hexsha": "c46ff278a2c5f4162db91a7ab500a0bb8cef7657", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 335.0, "max_stars_repo_stars_event_min_datetime": "2016-10-07T16:31:10.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-02T07:12:03.000Z", "max_issues_repo_path": "OREAnalytics/orea/aggregation/postprocess.cpp", "max_issues_repo_name": "mrslezak/Engine", "max_issues_repo_head_hexsha": "c46ff278a2c5f4162db91a7ab500a0bb8cef7657", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 59.0, "max_issues_repo_issues_event_min_datetime": "2016-10-31T04:20:24.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-03T16:39:57.000Z", "max_forks_repo_path": "OREAnalytics/orea/aggregation/postprocess.cpp", "max_forks_repo_name": "mrslezak/Engine", "max_forks_repo_head_hexsha": "c46ff278a2c5f4162db91a7ab500a0bb8cef7657", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 180.0, "max_forks_repo_forks_event_min_datetime": "2016-10-08T14:23:50.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T10:43:05.000Z", "avg_line_length": 47.9609571788, "max_line_length": 147, "alphanum_fraction": 0.65581261, "num_tokens": 10118, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6926419704455588, "lm_q2_score": 0.4416730056646256, "lm_q1q2_score": 0.3059212609361587}}
{"text": "/**\n * Copyright (c) 2011-2013 Andreas Sembrant\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met:\n *\n *  - Redistributions of source code must retain the above copyright\n *    notice, this list of conditions and the following disclaimer.\n *  - Redistributions in binary form must reproduce the above copyright\n *    notice, this list of conditions and the following disclaimer in the\n *    documentation and/or other materials provided with the distribution.\n *  - Neither the name of the copyright holders nor the names of its\n *    contributors may be used to endorse or promote products derived\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 * Authors: Andreas Sembrant\n *\n */\n\n#ifndef __SCARPHASE_INTERNAL_UTIL_RANDOM_PROJECTION_HPP\n#define __SCARPHASE_INTERNAL_UTIL_RANDOM_PROJECTION_HPP\n\n#include <stdint.h>\n#include <boost/array.hpp>\n\nnamespace scarphase {\nnamespace internal {\nnamespace util {\n\n/**\n * @brief Random projection to reduce the dimentioality of a large vector\n *        space.\n *\n *  V[1,n] * M[n,m] = V[1,m]\n *\n */\ntemplate<typename value_type,\n         int      OUTPUT_SIZE>\nclass RandomProjection //-----------------------------------------------------//\n{\n\npublic: //--------------------------------------------------------------------//\n\n    /**\n     * @brief C-tor.\n     */\n    RandomProjection();\n\n    /**\n     * @brief Hash a value using random projection.\n     *        y = x * M, where y << x\n     *\n     * @param[in]  x Value to hash.\n     * @returns A hash of x.\n     *\n     */\n    value_type Hash(value_type x);\n\nprivate: //-------------------------------------------------------------------//\n\n    /**\n     * @brief The size of the input variable.\n     */\n    #define INPUT_SIZE int(sizeof(value_type) * 8)\n\n    /**\n     * @brief Random projection matrix.\n     */\n    boost::array< boost::array< uint8_t, INPUT_SIZE >, OUTPUT_SIZE > m;\n\n};\n\n} /* namespace util */\n} /* namespace internal */\n} /* namespace scarphase */\n\n//----------------------------------------------------------------------------//\n// Inline Definitions                                                         //\n//----------------------------------------------------------------------------//\n\n#include <cstdlib>\n#include <boost/random.hpp>\n#include <boost/static_assert.hpp>\n\nnamespace scarphase {\nnamespace internal {\nnamespace util {\n\ntemplate<typename value_type,\n         int      OUTPUT_SIZE>\nRandomProjection<value_type, OUTPUT_SIZE>::RandomProjection()\n{\n    BOOST_STATIC_ASSERT(OUTPUT_SIZE > 0);\n\n    boost::mt19937 rng;\n    boost::uniform_int<> bin(0,1);\n    boost::variate_generator< boost::mt19937&,\n                              boost::uniform_int<> > die(rng, bin);\n\n    for (int i = 0; i < OUTPUT_SIZE; i++)\n    {\n        for (int j = 0; j < INPUT_SIZE; j++)\n        {\n            m[i][j] = die(); //std::rand() % 2;\n        }\n    }\n\n}\n\ntemplate<typename value_type,\n         int      OUTPUT_SIZE>\ninline value_type\nRandomProjection<value_type, OUTPUT_SIZE>::Hash(value_type x)\n{\n    value_type result = 0;\n    for (int i = 0; i < OUTPUT_SIZE; i++)\n    {\n        int t = 0;\n        for (int j = 0; j < INPUT_SIZE; j++)\n        {\n            t += m[i][j] & ((x >> j) & 0x01);\n        }\n        result |= (t % 2) << i;\n    }\n    return result;\n}\n\n} /* namespace util */\n} /* namespace internal */\n} /* namespace scarphase */\n\n#endif /* __SCARPHASE_INTERNAL_UTIL_RANDOM_PROJECTION_HPP */\n", "meta": {"hexsha": "cb639edceecaf1fa06bf87872c9c6cea854e9888", "size": 4350, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/scarphase/internal/util/random_projection.hpp", "max_stars_repo_name": "uart/libscarphase", "max_stars_repo_head_hexsha": "ddbff517dad30e94148f80c2c4e1a9f565f3d85c", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2016-12-03T15:18:57.000Z", "max_stars_repo_stars_event_max_datetime": "2016-12-03T15:18:57.000Z", "max_issues_repo_path": "include/scarphase/internal/util/random_projection.hpp", "max_issues_repo_name": "uart/libscarphase", "max_issues_repo_head_hexsha": "ddbff517dad30e94148f80c2c4e1a9f565f3d85c", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2015-12-31T06:22:17.000Z", "max_issues_repo_issues_event_max_datetime": "2015-12-31T06:22:17.000Z", "max_forks_repo_path": "include/scarphase/internal/util/random_projection.hpp", "max_forks_repo_name": "uart/libscarphase", "max_forks_repo_head_hexsha": "ddbff517dad30e94148f80c2c4e1a9f565f3d85c", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2015-12-29T17:05:37.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-27T17:01:30.000Z", "avg_line_length": 29.5918367347, "max_line_length": 80, "alphanum_fraction": 0.5972413793, "num_tokens": 936, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6688802603710086, "lm_q2_score": 0.45713671682749474, "lm_q1q2_score": 0.3057697261767227}}
{"text": "///////////////////////////////////////////////////////////////////////////////\r\n/// \\file vector.hpp\r\n///\r\n//  Copyright 2005 Eric Niebler. Distributed under the Boost\r\n//  Software License, Version 1.0. (See accompanying file\r\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\r\n\r\n#ifndef BOOST_NUMERIC_FUNCTIONAL_VECTOR_HPP_EAN_12_12_2005\r\n#define BOOST_NUMERIC_FUNCTIONAL_VECTOR_HPP_EAN_12_12_2005\r\n\r\n#ifdef BOOST_NUMERIC_FUNCTIONAL_HPP_INCLUDED\r\n# error Include this file before boost/accumulators/numeric/functional.hpp\r\n#endif\r\n\r\n#include <vector>\r\n#include <functional>\r\n#include <boost/assert.hpp>\r\n#include <boost/mpl/and.hpp>\r\n#include <boost/mpl/not.hpp>\r\n#include <boost/utility/enable_if.hpp>\r\n#include <boost/type_traits/is_same.hpp>\r\n#include <boost/type_traits/is_scalar.hpp>\r\n#include <boost/type_traits/remove_const.hpp>\r\n#include <boost/typeof/std/vector.hpp>\r\n#include <boost/accumulators/numeric/functional_fwd.hpp>\r\n\r\nnamespace boost { namespace numeric\r\n{\r\n    namespace operators\r\n    {\r\n        namespace acc_detail\r\n        {\r\n            template<typename Fun>\r\n            struct make_vector\r\n            {\r\n                typedef std::vector<typename Fun::result_type> type;\r\n            };\r\n        }\r\n\r\n        ///////////////////////////////////////////////////////////////////////////////\r\n        // Handle vector<Left> / Right where Right is a scalar.\r\n        template<typename Left, typename Right>\r\n        typename lazy_enable_if<\r\n            is_scalar<Right>\r\n          , acc_detail::make_vector<functional::divides<Left, Right> >\r\n        >::type\r\n        operator /(std::vector<Left> const &left, Right const &right)\r\n        {\r\n            typedef typename functional::divides<Left, Right>::result_type value_type;\r\n            std::vector<value_type> result(left.size());\r\n            for(std::size_t i = 0, size = result.size(); i != size; ++i)\r\n            {\r\n                result[i] = numeric::divides(left[i], right);\r\n            }\r\n            return result;\r\n        }\r\n\r\n        ///////////////////////////////////////////////////////////////////////////////\r\n        // Handle vector<Left> / vector<Right>.\r\n        template<typename Left, typename Right>\r\n        std::vector<typename functional::divides<Left, Right>::result_type>\r\n        operator /(std::vector<Left> const &left, std::vector<Right> const &right)\r\n        {\r\n            typedef typename functional::divides<Left, Right>::result_type value_type;\r\n            std::vector<value_type> result(left.size());\r\n            for(std::size_t i = 0, size = result.size(); i != size; ++i)\r\n            {\r\n                result[i] = numeric::divides(left[i], right[i]);\r\n            }\r\n            return result;\r\n        }\r\n\r\n        ///////////////////////////////////////////////////////////////////////////////\r\n        // Handle vector<Left> * Right where Right is a scalar.\r\n        template<typename Left, typename Right>\r\n        typename lazy_enable_if<\r\n            is_scalar<Right>\r\n          , acc_detail::make_vector<functional::multiplies<Left, Right> >\r\n        >::type\r\n        operator *(std::vector<Left> const &left, Right const &right)\r\n        {\r\n            typedef typename functional::multiplies<Left, Right>::result_type value_type;\r\n            std::vector<value_type> result(left.size());\r\n            for(std::size_t i = 0, size = result.size(); i != size; ++i)\r\n            {\r\n                result[i] = numeric::multiplies(left[i], right);\r\n            }\r\n            return result;\r\n        }\r\n\r\n        ///////////////////////////////////////////////////////////////////////////////\r\n        // Handle Left * vector<Right> where Left is a scalar.\r\n        template<typename Left, typename Right>\r\n        typename lazy_enable_if<\r\n            is_scalar<Left>\r\n          , acc_detail::make_vector<functional::multiplies<Left, Right> >\r\n        >::type\r\n        operator *(Left const &left, std::vector<Right> const &right)\r\n        {\r\n            typedef typename functional::multiplies<Left, Right>::result_type value_type;\r\n            std::vector<value_type> result(right.size());\r\n            for(std::size_t i = 0, size = result.size(); i != size; ++i)\r\n            {\r\n                result[i] = numeric::multiplies(left, right[i]);\r\n            }\r\n            return result;\r\n        }\r\n\r\n        ///////////////////////////////////////////////////////////////////////////////\r\n        // Handle vector<Left> * vector<Right>\r\n        template<typename Left, typename Right>\r\n        std::vector<typename functional::multiplies<Left, Right>::result_type>\r\n        operator *(std::vector<Left> const &left, std::vector<Right> const &right)\r\n        {\r\n            typedef typename functional::multiplies<Left, Right>::result_type value_type;\r\n            std::vector<value_type> result(left.size());\r\n            for(std::size_t i = 0, size = result.size(); i != size; ++i)\r\n            {\r\n                result[i] = numeric::multiplies(left[i], right[i]);\r\n            }\r\n            return result;\r\n        }\r\n\r\n        ///////////////////////////////////////////////////////////////////////////////\r\n        // Handle vector<Left> + vector<Right>\r\n        template<typename Left, typename Right>\r\n        std::vector<typename functional::plus<Left, Right>::result_type>\r\n        operator +(std::vector<Left> const &left, std::vector<Right> const &right)\r\n        {\r\n            typedef typename functional::plus<Left, Right>::result_type value_type;\r\n            std::vector<value_type> result(left.size());\r\n            for(std::size_t i = 0, size = result.size(); i != size; ++i)\r\n            {\r\n                result[i] = numeric::plus(left[i], right[i]);\r\n            }\r\n            return result;\r\n        }\r\n\r\n        ///////////////////////////////////////////////////////////////////////////////\r\n        // Handle vector<Left> - vector<Right>\r\n        template<typename Left, typename Right>\r\n        std::vector<typename functional::minus<Left, Right>::result_type>\r\n        operator -(std::vector<Left> const &left, std::vector<Right> const &right)\r\n        {\r\n            typedef typename functional::minus<Left, Right>::result_type value_type;\r\n            std::vector<value_type> result(left.size());\r\n            for(std::size_t i = 0, size = result.size(); i != size; ++i)\r\n            {\r\n                result[i] = numeric::minus(left[i], right[i]);\r\n            }\r\n            return result;\r\n        }\r\n\r\n        ///////////////////////////////////////////////////////////////////////////////\r\n        // Handle vector<Left> += vector<Left>\r\n        template<typename Left>\r\n        std::vector<Left> &\r\n        operator +=(std::vector<Left> &left, std::vector<Left> const &right)\r\n        {\r\n            BOOST_ASSERT(left.size() == right.size());\r\n            for(std::size_t i = 0, size = left.size(); i != size; ++i)\r\n            {\r\n                numeric::plus_assign(left[i], right[i]);\r\n            }\r\n            return left;\r\n        }\r\n\r\n        ///////////////////////////////////////////////////////////////////////////////\r\n        // Handle -vector<Arg>\r\n        template<typename Arg>\r\n        std::vector<typename functional::unary_minus<Arg>::result_type>\r\n        operator -(std::vector<Arg> const &arg)\r\n        {\r\n            typedef typename functional::unary_minus<Arg>::result_type value_type;\r\n            std::vector<value_type> result(arg.size());\r\n            for(std::size_t i = 0, size = result.size(); i != size; ++i)\r\n            {\r\n                result[i] = numeric::unary_minus(arg[i]);\r\n            }\r\n            return result;\r\n        }\r\n    }\r\n\r\n    namespace functional\r\n    {\r\n        struct std_vector_tag;\r\n\r\n        template<typename T, typename Al>\r\n        struct tag<std::vector<T, Al> >\r\n        {\r\n            typedef std_vector_tag type;\r\n        };\r\n\r\n        ///////////////////////////////////////////////////////////////////////////////\r\n        // element-wise min of std::vector\r\n        template<typename Left, typename Right>\r\n        struct min_assign<Left, Right, std_vector_tag, std_vector_tag>\r\n          : std::binary_function<Left, Right, void>\r\n        {\r\n            void operator ()(Left &left, Right &right) const\r\n            {\r\n                BOOST_ASSERT(left.size() == right.size());\r\n                for(std::size_t i = 0, size = left.size(); i != size; ++i)\r\n                {\r\n                    if(numeric::less(right[i], left[i]))\r\n                    {\r\n                        left[i] = right[i];\r\n                    }\r\n                }\r\n            }\r\n        };\r\n\r\n        ///////////////////////////////////////////////////////////////////////////////\r\n        // element-wise max of std::vector\r\n        template<typename Left, typename Right>\r\n        struct max_assign<Left, Right, std_vector_tag, std_vector_tag>\r\n          : std::binary_function<Left, Right, void>\r\n        {\r\n            void operator ()(Left &left, Right &right) const\r\n            {\r\n                BOOST_ASSERT(left.size() == right.size());\r\n                for(std::size_t i = 0, size = left.size(); i != size; ++i)\r\n                {\r\n                    if(numeric::greater(right[i], left[i]))\r\n                    {\r\n                        left[i] = right[i];\r\n                    }\r\n                }\r\n            }\r\n        };\r\n\r\n        // partial specialization for std::vector.\r\n        template<typename Left, typename Right>\r\n        struct fdiv<Left, Right, std_vector_tag, void>\r\n          : mpl::if_<\r\n                are_integral<typename Left::value_type, Right>\r\n              , divides<Left, double const>\r\n              , divides<Left, Right>\r\n            >::type\r\n        {};\r\n\r\n        // promote\r\n        template<typename To, typename From>\r\n        struct promote<To, From, std_vector_tag, std_vector_tag>\r\n          : std::unary_function<From, To>\r\n        {\r\n            To operator ()(From &arr) const\r\n            {\r\n                typename remove_const<To>::type res(arr.size());\r\n                for(std::size_t i = 0, size = arr.size(); i != size; ++i)\r\n                {\r\n                    res[i] = numeric::promote<typename To::value_type>(arr[i]);\r\n                }\r\n                return res;\r\n            }\r\n        };\r\n\r\n        template<typename ToFrom>\r\n        struct promote<ToFrom, ToFrom, std_vector_tag, std_vector_tag>\r\n          : std::unary_function<ToFrom, ToFrom>\r\n        {\r\n            ToFrom &operator ()(ToFrom &tofrom) const\r\n            {\r\n                return tofrom;\r\n            }\r\n        };\r\n\r\n        ///////////////////////////////////////////////////////////////////////////////\r\n        // functional::as_min\r\n        template<typename T>\r\n        struct as_min<T, std_vector_tag>\r\n          : std::unary_function<T, typename remove_const<T>::type>\r\n        {\r\n            typename remove_const<T>::type operator ()(T &arr) const\r\n            {\r\n                return 0 == arr.size()\r\n                  ? T()\r\n                  : T(arr.size(), numeric::as_min(arr[0]));\r\n            }\r\n        };\r\n\r\n        ///////////////////////////////////////////////////////////////////////////////\r\n        // functional::as_max\r\n        template<typename T>\r\n        struct as_max<T, std_vector_tag>\r\n          : std::unary_function<T, typename remove_const<T>::type>\r\n        {\r\n            typename remove_const<T>::type operator ()(T &arr) const\r\n            {\r\n                return 0 == arr.size()\r\n                  ? T()\r\n                  : T(arr.size(), numeric::as_max(arr[0]));\r\n            }\r\n        };\r\n\r\n        ///////////////////////////////////////////////////////////////////////////////\r\n        // functional::as_zero\r\n        template<typename T>\r\n        struct as_zero<T, std_vector_tag>\r\n          : std::unary_function<T, typename remove_const<T>::type>\r\n        {\r\n            typename remove_const<T>::type operator ()(T &arr) const\r\n            {\r\n                return 0 == arr.size()\r\n                  ? T()\r\n                  : T(arr.size(), numeric::as_zero(arr[0]));\r\n            }\r\n        };\r\n\r\n        ///////////////////////////////////////////////////////////////////////////////\r\n        // functional::as_one\r\n        template<typename T>\r\n        struct as_one<T, std_vector_tag>\r\n          : std::unary_function<T, typename remove_const<T>::type>\r\n        {\r\n            typename remove_const<T>::type operator ()(T &arr) const\r\n            {\r\n                return 0 == arr.size()\r\n                  ? T()\r\n                  : T(arr.size(), numeric::as_one(arr[0]));\r\n            }\r\n        };\r\n\r\n    } // namespace functional\r\n\r\n}} // namespace boost::numeric\r\n\r\n#endif\r\n\r\n", "meta": {"hexsha": "b4c814c4ce2c36bb9a6325abb01dede3aa78e00a", "size": 12747, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ios/Pods/boost-for-react-native/boost/accumulators/numeric/functional/vector.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/accumulators/numeric/functional/vector.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/accumulators/numeric/functional/vector.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.6272727273, "max_line_length": 90, "alphanum_fraction": 0.4594806621, "num_tokens": 2492, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6261241772283034, "lm_q2_score": 0.4882833952958347, "lm_q1q2_score": 0.30572603913384694}}
{"text": "//==============================================================================\n//          Copyright 2015 - J.T. Lapreste\n//\n//          Distributed under the Boost Software License, Version 1.0.\n//                 See accompanying file LICENSE.txt or copy at\n//                     http://www.boost.org/LICENSE_1_0.txt\n//==============================================================================\n#ifndef BOOST_SIMD_ARITHMETIC_FUNCTIONS_TENPOWER_HPP_INCLUDED\n#define BOOST_SIMD_ARITHMETIC_FUNCTIONS_TENPOWER_HPP_INCLUDED\n#include <boost/simd/include/functor.hpp>\n#include <boost/dispatch/include/functor.hpp>\n\nnamespace boost { namespace simd { namespace tag\n  {\n    /*!\n      @brief  tenpower generic tag\n\n      Represents the tenpower function in generic contexts.\n\n      @par Models:\n      Hierarchy\n    **/\n    struct tenpower_ : ext::elementwise_<tenpower_>\n    {\n      /// @brief Parent hierarchy\n      typedef ext::elementwise_<tenpower_> parent;\n      template<class... Args>\n      static BOOST_FORCEINLINE BOOST_AUTO_DECLTYPE dispatch(Args&&... args)\n      BOOST_AUTO_DECLTYPE_BODY( dispatching_tenpower_( ext::adl_helper(), static_cast<Args&&>(args)... ) )\n    };\n  }\n  namespace ext\n  {\n    template<class Site, class... Ts>\n    BOOST_FORCEINLINE generic_dispatcher<tag::tenpower_, Site> dispatching_tenpower_(adl_helper, boost::dispatch::meta::unknown_<Site>, boost::dispatch::meta::unknown_<Ts>...)\n    {\n      return generic_dispatcher<tag::tenpower_, Site>();\n    }\n    template<class... Args>\n    struct impl_tenpower_;\n  }\n\n  /*!\n    @brief Returns \\f$10^n\\f$ in the floating type  corresponding to A0\n\n    @par semantic:\n    For any given value n  of integral type @c I, and T of type as_floating<I>::type\n\n    @code\n    T r = tenpower(n);\n    @endcode\n\n    code is similar to:\n\n    @code\n    T r = exp10(T(n));\n    @endcode\n\n    @par Note:\n\n    This function is not defined for floating entries\n\n    @param  n\n\n    @return a value of the floating associated type.\n\n  **/\n  BOOST_DISPATCH_FUNCTION_IMPLEMENTATION(tag::tenpower_, tenpower, 1)\n} }\n#endif\n", "meta": {"hexsha": "732cd9dff79861707eb7aa95626c7ffa5d4a5fdb", "size": 2077, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/boost/simd/base/include/boost/simd/arithmetic/functions/tenpower.hpp", "max_stars_repo_name": "psiha/nt2", "max_stars_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "modules/boost/simd/base/include/boost/simd/arithmetic/functions/tenpower.hpp", "max_issues_repo_name": "psiha/nt2", "max_issues_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "modules/boost/simd/base/include/boost/simd/arithmetic/functions/tenpower.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": 29.2535211268, "max_line_length": 175, "alphanum_fraction": 0.6191622532, "num_tokens": 477, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6261241632752915, "lm_q2_score": 0.4882833952958347, "lm_q1q2_score": 0.3057260323208229}}
{"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_MULTI_OBJECTIVE_HPP\n#define PAGMO_MULTI_OBJECTIVE_HPP\n\n/** \\file multi_objective.hpp\n * \\brief Multi objective optimization utilities.\n *\n * This header contains utilities used to compute non dominated fronts and other\n * quantities useful for multi objective optimization\n */\n\n#include <algorithm>\n#include <boost/numeric/conversion/cast.hpp>\n#include <limits>\n#include <numeric>\n#include <stdexcept>\n#include <string>\n#include <tuple>\n#include <vector>\n\n#include <pagmo/detail/custom_comparisons.hpp>\n#include <pagmo/exceptions.hpp>\n#include <pagmo/io.hpp>\n#include <pagmo/population.hpp>\n#include <pagmo/types.hpp>\n#include <pagmo/utils/discrepancy.hpp> // halton\n\nnamespace pagmo\n{\n\nnamespace detail\n{\n// Recursive function building all m-ple of elements of X summing to s\n// In C/C++ implementations there exists a limit on the number of times you\n// can call recursively a function. It depends on a variety of factors,\n// but probably it a number around few thousands on modern machines.\n// If the limit is surpassed, the program terminates.\n// I was thinking that one could create a problem with a few thousands objectives,\n// call this function thus causing a crash from Python. In principle I think we\n// can prevent this by limiting the recursion (e.g., via a function parameter that\n// gets increased each time the function is called from itself).\n// But for now I'd just put a note about this.\ninline void reksum(std::vector<std::vector<double>> &retval, const std::vector<population::size_type> &X,\n                   population::size_type m, population::size_type s, std::vector<double> eggs = std::vector<double>())\n{\n    if (m == 1u) {\n        if (std::find(X.begin(), X.end(), s) == X.end()) { // not found\n            return;\n        } else {\n            eggs.push_back(static_cast<double>(s));\n            retval.push_back(eggs);\n        }\n    } else {\n        for (decltype(X.size()) i = 0u; i < X.size(); ++i) {\n            eggs.push_back(static_cast<double>(X[i]));\n            reksum(retval, X, m - 1u, s - X[i], eggs);\n            eggs.pop_back();\n        }\n    }\n}\n} // namespace detail\n\n/// Pareto-dominance\n/**\n * Return true if \\p obj1 Pareto dominates \\p obj2, false otherwise. Minimization\n * is assumed.\n *\n * Each pair of corresponding elements in \\p obj1 and \\p obj2 is compared: if all\n * elements in \\p obj1 are less or equal to the corresponding element in \\p obj2,\n * but at least one is different, \\p true will be returned. Otherwise, \\p false will be returned.\n *\n * @param obj1 first vector of objectives.\n * @param obj2 second vector of objectives.\n *\n * @return \\p true if \\p obj1 is dominating \\p obj2, \\p false otherwise.\n *\n * @throws std::invalid_argument if the dimensions of the two objectives are different\n */\ninline bool pareto_dominance(const vector_double &obj1, const vector_double &obj2)\n{\n    if (obj1.size() != obj2.size()) {\n        pagmo_throw(std::invalid_argument,\n                    \"Different number of objectives found in input fitnesses: \" + std::to_string(obj1.size()) + \" and \"\n                        + std::to_string(obj2.size()) + \". I cannot define dominance\");\n    }\n    vector_double::size_type count1 = 0u;\n    vector_double::size_type count2 = 0u;\n    for (decltype(obj1.size()) i = 0u; i < obj1.size(); ++i) {\n        if (obj1[i] < obj2[i]) {\n            ++count1;\n        }\n        if (obj1[i] == obj2[i]) {\n            ++count2;\n        }\n    }\n    return (((count1 + count2) == obj1.size()) && (count1 > 0u));\n}\n\n/// Non dominated front 2D (Kung's algorithm)\n/**\n * Finds the non dominated front of a set of two dimensional objectives. Complexity is O(N logN) and is thus lower than\n * the\n * complexity of calling pagmo::fast_non_dominated_sorting\n *\n * See: Jensen, Mikkel T. \"Reducing the run-time complexity of multiobjective EAs: The NSGA-II and other algorithms.\"\n * IEEE Transactions on Evolutionary Computation 7.5 (2003): 503-515.\n *\n * @param input_objs an <tt>std::vector</tt> containing the points (i.e. vector of objectives)\n *\n * @return A <tt>std::vector</tt> containing the indexes of the points in the non-dominated front\n *\n * @throws std::invalid_argument If the objective vectors are not all containing two-objectives\n */\ninline std::vector<vector_double::size_type> non_dominated_front_2d(const std::vector<vector_double> &input_objs)\n{\n    // If the input is empty return an empty vector\n    if (input_objs.size() == 0u) {\n        return {};\n    }\n    // How many objectives? M, of course.\n    auto M = input_objs[0].size();\n    // We make sure all input_objs contain M objectives\n    if (!std::all_of(input_objs.begin(), input_objs.end(),\n                     [M](const vector_double &item) { return item.size() == M; })) {\n        pagmo_throw(std::invalid_argument, \"Input contains vector of objectives with heterogeneous dimensionalities\");\n    }\n    // We make sure this function is only requested for two objectives.\n    if (M != 2u) {\n        pagmo_throw(std::invalid_argument, \"The number of objectives detected is \" + std::to_string(M)\n                                               + \", while Kung's algorithm only works for two objectives.\");\n    }\n    // Sanity checks are over. We may run Kung's algorithm.\n    std::vector<vector_double::size_type> front;\n    std::vector<vector_double::size_type> indexes(input_objs.size());\n    std::iota(indexes.begin(), indexes.end(), vector_double::size_type(0u));\n    // Sort in ascending order with respect to the first component\n    std::sort(indexes.begin(), indexes.end(),\n              [&input_objs](vector_double::size_type idx1, vector_double::size_type idx2) {\n                  if (input_objs[idx1][0] == input_objs[idx2][0]) {\n                      return detail::less_than_f(input_objs[idx1][1], input_objs[idx2][1]);\n                  }\n                  return detail::less_than_f(input_objs[idx1][0], input_objs[idx2][0]);\n              });\n    for (auto i : indexes) {\n        bool flag = false;\n        for (auto j : front) {\n            if (pareto_dominance(input_objs[j], input_objs[i])) {\n                flag = true;\n                break;\n            }\n        }\n        if (!flag) {\n            front.push_back(i);\n        }\n    }\n    return front;\n}\n\n/// Return type for the fast_non_dominated_sorting algorithm\nusing fnds_return_type\n    = std::tuple<std::vector<std::vector<vector_double::size_type>>, std::vector<std::vector<vector_double::size_type>>,\n                 std::vector<vector_double::size_type>, std::vector<vector_double::size_type>>;\n\n/// Fast non dominated sorting\n/**\n * An implementation of the fast non dominated sorting algorithm. Complexity is \\f$ O(MN^2)\\f$ where \\f$M\\f$ is the\n * number of objectives\n * and \\f$N\\f$ is the number of individuals.\n *\n * See: Deb, Kalyanmoy, et al. \"A fast elitist non-dominated sorting genetic algorithm\n * for multi-objective optimization: NSGA-II.\" Parallel problem solving from nature PPSN VI. Springer Berlin Heidelberg,\n * 2000.\n *\n * @param points An std::vector containing the objectives of different individuals. Example\n * {{1,2,3},{-2,3,7},{-1,-2,-3},{0,0,0}}\n *\n * @return an std::tuple containing:\n *  - the non dominated fronts, an <tt>std::vector<std::vector<vector_double::size_type>></tt>\n * containing the non dominated fronts. Example {{1,2},{3},{0}}\n *  - the domination list, an <tt>std::vector<std::vector<vector_double::size_type>></tt>\n * containing the domination list, i.e. the indexes of all individuals\n * dominated by the individual at position \\f$i\\f$. Example {{},{},{0,3},{0}}\n *  - the domination count, an <tt>std::vector<vector_double::size_type></tt> containing the number of individuals\n * that dominate the individual at position \\f$i\\f$. Example {2, 0, 0, 1}\n *  - the non domination rank, an <tt>std::vector<vector_double::size_type></tt> containing the index of the non\n * dominated front to which the individual at position \\f$i\\f$ belongs. Example {2,0,0,1}\n *\n * @throws std::invalid_argument If the size of \\p points is not at least 2\n */\ninline fnds_return_type fast_non_dominated_sorting(const std::vector<vector_double> &points)\n{\n    auto N = points.size();\n    // We make sure to have two points at least (one could also be allowed)\n    if (N < 2u) {\n        pagmo_throw(std::invalid_argument, \"At least two points are needed for fast_non_dominated_sorting: \"\n                                               + std::to_string(N) + \" detected.\");\n    }\n    // Initialize the return values\n    std::vector<std::vector<vector_double::size_type>> non_dom_fronts(1u);\n    std::vector<std::vector<vector_double::size_type>> dom_list(N);\n    std::vector<vector_double::size_type> dom_count(N);\n    std::vector<vector_double::size_type> non_dom_rank(N);\n\n    // Start the fast non dominated sort algorithm\n    for (decltype(N) i = 0u; i < N; ++i) {\n        dom_list[i].clear();\n        dom_count[i] = 0u;\n        for (decltype(N) j = 0u; j < N; ++j) {\n            if (i == j) {\n                continue;\n            }\n            if (pareto_dominance(points[i], points[j])) {\n                dom_list[i].push_back(j);\n            } else if (pareto_dominance(points[j], points[i])) {\n                ++dom_count[i];\n            }\n        }\n        if (dom_count[i] == 0u) {\n            non_dom_rank[i] = 0u;\n            non_dom_fronts[0].push_back(i);\n        }\n    }\n    // we copy dom_count as we want to output its value at this point\n    auto dom_count_copy(dom_count);\n    auto current_front = non_dom_fronts[0];\n    std::vector<std::vector<vector_double::size_type>>::size_type front_counter(0u);\n    while (current_front.size() != 0u) {\n        std::vector<vector_double::size_type> next_front;\n        for (decltype(current_front.size()) p = 0u; p < current_front.size(); ++p) {\n            for (decltype(dom_list[current_front[p]].size()) q = 0u; q < dom_list[current_front[p]].size(); ++q) {\n                --dom_count_copy[dom_list[current_front[p]][q]];\n                if (dom_count_copy[dom_list[current_front[p]][q]] == 0u) {\n                    non_dom_rank[dom_list[current_front[p]][q]] = front_counter + 1u;\n                    next_front.push_back(dom_list[current_front[p]][q]);\n                }\n            }\n        }\n        ++front_counter;\n        current_front = next_front;\n        if (current_front.size() != 0u) {\n            non_dom_fronts.push_back(current_front);\n        }\n    }\n    return std::make_tuple(std::move(non_dom_fronts), std::move(dom_list), std::move(dom_count),\n                           std::move(non_dom_rank));\n}\n\n/// Crowding distance\n/**\n * An implementation of the crowding distance. Complexity is \\f$ O(MNlog(N))\\f$ where \\f$M\\f$ is the number of\n * objectives\n * and \\f$N\\f$ is the number of individuals. The function assumes the input is a non-dominated front. Failiure to this\n * condition\n * will result in undefined behaviour.\n *\n * See: Deb, Kalyanmoy, et al. \"A fast elitist non-dominated sorting genetic algorithm\n * for multi-objective optimization: NSGA-II.\" Parallel problem solving from nature PPSN VI. Springer Berlin Heidelberg,\n * 2000.\n *\n * @param non_dom_front An <tt>std::vector<vector_double></tt> containing a non dominated front. Example\n * {{0,0},{-1,1},{2,-2}}\n *\n * @returns a vector_double containing the crowding distances. Example: {2, inf, inf}\n *\n * @throws std::invalid_argument If \\p non_dom_front does not contain at least two points\n * @throws std::invalid_argument If points in \\p do not all have at least two objectives\n * @throws std::invalid_argument If points in \\p non_dom_front do not all have the same dimensionality\n */\ninline vector_double crowding_distance(const std::vector<vector_double> &non_dom_front)\n{\n   \n    auto N = non_dom_front.size();\n\n    if (N < 2u)\n    {\n        vector_double retval(N, std::numeric_limits<double>::infinity());\n        return retval;\n    }\n\n    // We make sure to have two points at least\n    if (N < 2u) {\n        pagmo_throw(std::invalid_argument,\n                    \"A non dominated front must contain at least two points: \" + std::to_string(N) + \" detected.\");\n    }\n    auto M = non_dom_front[0].size();\n    // We make sure the first point of the input non dominated front contains at least two objectives\n    if (M < 2u) {\n        pagmo_throw(std::invalid_argument, \"Points in the non dominated front must contain at least two objectives: \"\n                                               + std::to_string(M) + \" detected.\");\n    }\n    // We make sure all points contain the same number of objectives\n    if (!std::all_of(non_dom_front.begin(), non_dom_front.end(),\n                     [M](const vector_double &item) { return item.size() == M; })) {\n        pagmo_throw(std::invalid_argument, \"A non dominated front must contain points of uniform dimensionality. Some \"\n                                           \"different sizes were instead detected.\");\n    }\n    std::vector<vector_double::size_type> indexes(N);\n    std::iota(indexes.begin(), indexes.end(), vector_double::size_type(0u));\n    vector_double retval(N, 0.);\n    for (decltype(M) i = 0u; i < M; ++i) {\n        std::sort(indexes.begin(), indexes.end(),\n                  [i, &non_dom_front](vector_double::size_type idx1, vector_double::size_type idx2) {\n                      return detail::less_than_f(non_dom_front[idx1][i], non_dom_front[idx2][i]);\n                  });\n        retval[indexes[0]] = std::numeric_limits<double>::infinity();\n        retval[indexes[N - 1u]] = std::numeric_limits<double>::infinity();\n        double df = non_dom_front[indexes[N - 1u]][i] - non_dom_front[indexes[0]][i];\n        for (decltype(N - 2u) j = 1u; j < N - 1u; ++j) {\n            retval[indexes[j]] += (non_dom_front[indexes[j + 1u]][i] - non_dom_front[indexes[j - 1u]][i]) / df;\n        }\n    }\n    return retval;\n}\n\n/// Sorts a population in multi-objective optimization\n/**\n * Sorts a population (intended here as an <tt>std::vector<vector_double></tt> containing the  objective vectors)\n * with respect to the following strict ordering:\n * - \\f$f_1 \\prec f_2\\f$ if the non domination ranks are such that \\f$i_1 < i_2\\f$. In case\n * \\f$i_1 = i_2\\f$, then \\f$f_1 \\prec f_2\\f$ if the crowding distances are such that \\f$d_1 > d_2\\f$.\n *\n * Complexity is \\f$ O(MN^2)\\f$ where \\f$M\\f$ is the number of objectives and \\f$N\\f$ is the number of individuals.\n *\n * This function will also work for single objective optimization, i.e. with 1 objective\n * in which case, though, it is more efficient to sort using directly one of the following forms:\n *\n * @code{.unparsed}\n * std::sort(input_f.begin(), input_f.end(), [] (auto a, auto b) {return a[0] < b[0];});\n * @endcode\n * @code{.unparsed}\n * std::vector<vector_double::size_type> idx(input_f.size());\n * std::iota(idx.begin(), idx.end(), vector_double::size_type(0u));\n * std::sort(idx.begin(), idx.end(), [] (auto a, auto b) {return input_f[a][0] < input_f[b][0];});\n * @endcode\n *\n * @param input_f Input objectives vectors. Example {{0.25,0.25},{-1,1},{2,-2}};\n *\n * @returns an <tt>std::vector</tt> containing the indexes of the sorted objectives vectors. Example {1,2,0}\n *\n * @throws unspecified all exceptions thrown by pagmo::fast_non_dominated_sorting and pagmo::crowding_distance\n */\ninline std::vector<vector_double::size_type> sort_population_mo(const std::vector<vector_double> &input_f)\n{\n    if (input_f.size() < 2u) { // corner cases\n        if (input_f.size() == 0u) {\n            return {};\n        }\n        if (input_f.size() == 1u) {\n            return {0u};\n        }\n    }\n    // Create the indexes 0....N-1\n    std::vector<vector_double::size_type> retval(input_f.size());\n    std::iota(retval.begin(), retval.end(), vector_double::size_type(0u));\n    // Run fast-non-dominated sorting and compute the crowding distance for all input objectives vectors\n    auto tuple = fast_non_dominated_sorting(input_f);\n    vector_double crowding(input_f.size());\n    for (const auto &front : std::get<0>(tuple)) {\n        if (front.size() == 1u) {\n            crowding[front[0]] = 0u; // corner case of a non dominated front containing one individual. Crowding\n                                     // distance is not defined nor it will be used\n        } else {\n            std::vector<vector_double> non_dom_fits(front.size());\n            for (decltype(front.size()) i = 0u; i < front.size(); ++i) {\n                non_dom_fits[i] = input_f[front[i]];\n            }\n            vector_double tmp(crowding_distance(non_dom_fits));\n            for (decltype(front.size()) i = 0u; i < front.size(); ++i) {\n                crowding[front[i]] = tmp[i];\n            }\n        }\n    }\n    // Sort the indexes\n    std::sort(retval.begin(), retval.end(),\n              [&tuple, &crowding](vector_double::size_type idx1, vector_double::size_type idx2) {\n                  if (std::get<3>(tuple)[idx1] == std::get<3>(tuple)[idx2]) {        // same non domination rank\n                      return detail::greater_than_f(crowding[idx1], crowding[idx2]); // crowding distance decides\n                  } else {                                                           // different non domination ranks\n                      return std::get<3>(tuple)[idx1] < std::get<3>(tuple)[idx2];    // non domination rank decides\n                  };\n              });\n    return retval;\n}\n\n/// Selects the best N individuals in multi-objective optimization\n/**\n * Selects the best N individuals out of a population, (intended here as an\n * <tt>std::vector<vector_double></tt> containing the  objective vectors). The strict ordering used\n * is the same as that defined in pagmo::sort_population_mo.\n *\n * Complexity is \\f$ O(MN^2)\\f$ where \\f$M\\f$ is the number of objectives and \\f$N\\f$ is the number of individuals.\n *\n * While the complexity is the same as that of pagmo::sort_population_mo, this function returns a permutation\n * of:\n *\n * @code{.unparsed}\n * auto ret = pagmo::sort_population_mo(input_f).resize(N);\n * @endcode\n *\n * but it is faster than the above code: it avoids to compute the crowding distance for all individuals and only\n * computes\n * it for the last non-dominated front that contains individuals included in the best N.\n *\n * @param input_f Input objectives vectors. Example {{0.25,0.25},{-1,1},{2,-2}};\n * @param N Number of best individuals to return\n *\n * @returns an <tt>std::vector</tt> containing the indexes of the best N objective vectors. Example {2,1}\n *\n * @throws unspecified all exceptions thrown by pagmo::fast_non_dominated_sorting and pagmo::crowding_distance\n */\ninline std::vector<vector_double::size_type> select_best_N_mo(const std::vector<vector_double> &input_f,\n                                                              vector_double::size_type N)\n{\n    if (N < 1u) {\n        pagmo_throw(std::invalid_argument,\n                    \"The best: \" + std::to_string(N) + \" individuals were requested, while 1 is the minimum\");\n    }\n    if (input_f.size() == 0u) { // corner case\n        return {};\n    }\n    if (input_f.size() == 1u) { // corner case\n        return {0u};\n    }\n    if (N >= input_f.size()) { // corner case\n        std::vector<vector_double::size_type> retval(input_f.size());\n        std::iota(retval.begin(), retval.end(), vector_double::size_type(0u));\n        return retval;\n    }\n    std::vector<vector_double::size_type> retval;\n    std::vector<vector_double::size_type>::size_type front_id(0u);\n    // Run fast-non-dominated sorting\n    auto tuple = fast_non_dominated_sorting(input_f);\n    // Insert all non dominated fronts if not more than N\n    for (const auto &front : std::get<0>(tuple)) {\n        if (retval.size() + front.size() <= N) {\n            for (auto i : front) {\n                retval.push_back(i);\n            }\n            if (retval.size() == N) {\n                return retval;\n            }\n            ++front_id;\n        } else {\n            break;\n        }\n    }\n    auto front = std::get<0>(tuple)[front_id];\n    std::vector<vector_double> non_dom_fits(front.size());\n    // Run crowding distance for the front\n    for (decltype(front.size()) i = 0u; i < front.size(); ++i) {\n        non_dom_fits[i] = input_f[front[i]];\n    }\n    vector_double cds(crowding_distance(non_dom_fits));\n    // We now have front and crowding distance, we sort the front w.r.t. the crowding\n    std::vector<vector_double::size_type> idxs(front.size());\n    std::iota(idxs.begin(), idxs.end(), vector_double::size_type(0u));\n    std::sort(idxs.begin(), idxs.end(), [&cds](vector_double::size_type idx1, vector_double::size_type idx2) {\n        return detail::greater_than_f(cds[idx1], cds[idx2]);\n    }); // Descending order1\n    auto remaining = N - retval.size();\n    for (decltype(remaining) i = 0u; i < remaining; ++i) {\n        retval.push_back(front[idxs[i]]);\n    }\n    return retval;\n}\n\n/// Ideal point\n/**\n * Computes the ideal point of an input population, (intended here as an\n * <tt>std::vector<vector_double></tt> containing the  objective vectors).\n *\n * Complexity is \\f$ O(MN)\\f$ where \\f$M\\f$ is the number of objectives and \\f$N\\f$ is the number of individuals.\n *\n * @param points Input objectives vectors. Example {{-1,3,597},{1,2,3645},{2,9,789},{0,0,231},{6,-2,4576}};\n *\n * @returns A vector_double containing the ideal point. Example: {-1,-2,231}\n *\n * @throws std::invalid_argument if the input objective vectors are not all of the same size\n */\ninline vector_double ideal(const std::vector<vector_double> &points)\n{\n    // Corner case\n    if (points.size() == 0u) {\n        return {};\n    }\n\n    // Sanity checks\n    auto M = points[0].size();\n    for (const auto &f : points) {\n        if (f.size() != M) {\n            pagmo_throw(std::invalid_argument,\n                        \"Input vector of objectives must contain fitness vector of equal dimension \"\n                            + std::to_string(M));\n        }\n    }\n    // Actual algorithm\n    vector_double retval(M);\n    for (decltype(M) i = 0u; i < M; ++i) {\n        retval[i]\n            = (*std::min_element(points.begin(), points.end(),\n                                 [i](const vector_double &f1, const vector_double &f2) { return f1[i] < f2[i]; }))[i];\n    }\n    return retval;\n}\n\n/// Nadir point\n/**\n * Computes the nadir point of an input population, (intended here as an\n * <tt>std::vector<vector_double></tt> containing the  objective vectors).\n *\n * Complexity is \\f$ O(MN^2)\\f$ where \\f$M\\f$ is the number of objectives and \\f$N\\f$ is the number of individuals.\n *\n * @param points Input objective vectors. Example {{0,7},{1,5},{2,3},{4,2},{7,1},{10,0},{6,6},{9,15}}\n *\n * @returns A vector_double containing the nadir point. Example: {10,7}\n *\n */\ninline vector_double nadir(const std::vector<vector_double> &points)\n{\n    // Corner case\n    if (points.size() == 0u) {\n        return {};\n    }\n    // Sanity checks\n    auto M = points[0].size();\n    // We extract all objective vectors belonging to the first non dominated front (the Pareto front)\n    auto pareto_idx = std::get<0>(fast_non_dominated_sorting(points))[0];\n    std::vector<vector_double> nd_points;\n    for (auto idx : pareto_idx) {\n        nd_points.push_back(points[idx]);\n    }\n    // And compute the nadir over them\n    vector_double retval(M);\n    for (decltype(M) i = 0u; i < M; ++i) {\n        retval[i]\n            = (*std::max_element(nd_points.begin(), nd_points.end(),\n                                 [i](const vector_double &f1, const vector_double &f2) { return f1[i] < f2[i]; }))[i];\n    }\n    return retval;\n}\n\n/// Decomposition weights generation\n/**\n * Generates a requested number of weight vectors to be used to decompose a multi-objective problem. Three methods are\n *available:\n * - \"grid\" generates weights on an uniform grid. This method may only be used when the number of requested weights to\n *be genrated is such that a uniform grid is indeed possible. In\n * two dimensions this is always the case, but in larger dimensions uniform grids are possible only in special cases\n * - \"random\" generates weights randomly distributing them uniformly on the simplex (weights are such that \\f$\\sum_i\n * \\lambda_i = 1\\f$)\n * - \"low discrepancy\" generates weights using a low-discrepancy sequence to, eventually, obtain a\n * better coverage of the Pareto front. Halton sequence is used since low dimensionalities are expected in the number of\n * objectives (i.e. less than 20), hence Halton sequence is deemed as appropriate.\n *\n * \\verbatim embed:rst:leading-asterisk\n * .. note::\n *\n *    All genration methods are guaranteed to generate weights on the simplex (:math:`\\sum_i \\lambda_i = 1`). All\n *    weight generation methods are guaranteed to generate the canonical weights [1,0,0,...], [0,1,0,..], ... first.\n *\n * \\endverbatim\n *\n * Example: to generate 10 weights distributed somehow regularly to decompose a three dimensional problem:\n * @code{.unparsed}\n * detail::random_engine_type r_engine();\n * auto lambdas = decomposition_weights(3u, 10u, \"low discrepancy\", r_engine);\n * @endcode\n *\n * @param n_f dimension of each weight vector (i.e. fitness dimension)\n * @param n_w number of weights to be generated\n * @param method methods to generate the weights of the decomposed problems. One of \"grid\", \"random\",\n *\"low discrepancy\"\n * @param r_engine random engine\n *\n * @returns an <tt>std:vector</tt> containing the weight vectors\n *\n * @throws if \\p nf and \\p nw are not compatible with the selected weight generation method or if \\p method\n * is not one of \"grid\", \"random\" or \"low discrepancy\"\n */\ninline std::vector<vector_double> decomposition_weights(vector_double::size_type n_f, vector_double::size_type n_w,\n                                                        const std::string &method, detail::random_engine_type &r_engine)\n{\n    // Sanity check\n    if (n_f > n_w) {\n        pagmo_throw(std::invalid_argument,\n                    \"A fitness size of \" + std::to_string(n_f)\n                        + \" was requested to the weight generation routine, while \" + std::to_string(n_w)\n                        + \" weights were requested to be generated. To allow weight be generated correctly the number \"\n                          \"of weights must be strictly larger than the number of objectives\");\n    }\n\n    if (n_f < 2u) {\n        pagmo_throw(\n            std::invalid_argument,\n            \"A fitness size of \" + std::to_string(n_f)\n                + \" was requested to generate decomposed weights. A dimension of at least two must be requested.\");\n    }\n\n    // Random distributions\n    std::uniform_real_distribution<double> drng(0., 1.); // to generate a number in [0, 1)\n    std::vector<vector_double> retval;\n    if (method == \"grid\") {\n        // find the largest H resulting in a population smaller or equal to NP\n        decltype(n_w) H;\n        if (n_f == 2u) {\n            H = n_w - 1u;\n        } else if (n_f == 3u) {\n            H = static_cast<decltype(H)>(std::floor(0.5 * (std::sqrt(8. * static_cast<double>(n_w) + 1.) - 3.)));\n        } else {\n            H = 1u;\n            while (binomial_coefficient(H + n_f - 1u, n_f - 1u) <= static_cast<double>(n_w)) {\n                ++H;\n            }\n            H--;\n        }\n        // We check that NP equals the population size resulting from H\n        if (std::abs(static_cast<double>(n_w) - binomial_coefficient(H + n_f - 1u, n_f - 1u)) > 1E-8) {\n            std::ostringstream error_message;\n            error_message << \"Population size of \" << std::to_string(n_w) << \" is detected, but not supported by the '\"\n                          << method << \"' weight generation method selected. A size of \"\n                          << binomial_coefficient(H + n_f - 1u, n_f - 1u) << \" or \"\n                          << binomial_coefficient(H + n_f, n_f - 1u) << \" is possible.\";\n            pagmo_throw(std::invalid_argument, error_message.str());\n        }\n        // We generate the weights\n        std::vector<population::size_type> range(H + 1u);\n        std::iota(range.begin(), range.end(), std::vector<population::size_type>::size_type(0u));\n        detail::reksum(retval, range, n_f, H);\n        for (decltype(retval.size()) i = 0u; i < retval.size(); ++i) {\n            for (decltype(retval[i].size()) j = 0u; j < retval[i].size(); ++j) {\n                retval[i][j] /= static_cast<double>(H);\n            }\n        }\n    } else if (method == \"low discrepancy\") {\n        // We first push back the \"corners\" [1,0,0,...], [0,1,0,...]\n        for (decltype(n_f) i = 0u; i < n_f; ++i) {\n            retval.push_back(vector_double(n_f, 0.));\n            retval[i][i] = 1.;\n        }\n        // Then we add points on the simplex randomly genrated using Halton low discrepancy sequence\n        halton ld_seq{boost::numeric_cast<unsigned int>(n_f - 1u), boost::numeric_cast<unsigned int>(n_f)};\n        for (decltype(n_w) i = n_f; i < n_w; ++i) {\n            retval.push_back(sample_from_simplex(ld_seq()));\n        }\n    } else if (method == \"random\") {\n        // We first push back the \"corners\" [1,0,0,...], [0,1,0,...]\n        for (decltype(n_f) i = 0u; i < n_f; ++i) {\n            retval.push_back(vector_double(n_f, 0.));\n            retval[i][i] = 1.;\n        }\n        for (decltype(n_w) i = n_f; i < n_w; ++i) {\n            vector_double dummy(n_f - 1u, 0.);\n            for (decltype(n_f) j = 0u; j < n_f - 1u; ++j) {\n                dummy[j] = drng(r_engine);\n            }\n            retval.push_back(sample_from_simplex(dummy));\n        }\n    } else {\n        pagmo_throw(std::invalid_argument,\n                    \"Weight generation method \" + method\n                        + \" is unknown. One of 'grid', 'random' or 'low discrepancy' was expected\");\n    }\n    return retval;\n}\n\n/// Decomposes a vector of objectives.\n/**\n * A vector of objectives is reduced to one only objective using a decomposition\n * technique.\n *\n * Three different *decomposition methods* are here made available:\n *\n * - weighted decomposition,\n * - Tchebycheff decomposition,\n * - boundary interception method (with penalty constraint).\n *\n * In the case of \\f$n\\f$ objectives, we indicate with: \\f$ \\mathbf f(\\mathbf x) = [f_1(\\mathbf x), \\ldots,\n * f_n(\\mathbf x)] \\f$ the vector containing the original multiple objectives, with: \\f$ \\boldsymbol \\lambda =\n * (\\lambda_1, \\ldots, \\lambda_n) \\f$ an \\f$n\\f$-dimensional weight vector and with: \\f$ \\mathbf z^* = (z^*_1, \\ldots,\n * z^*_n) \\f$ an \\f$n\\f$-dimensional reference point. We also ussume \\f$\\lambda_i > 0, \\forall i=1..n\\f$ and \\f$\\sum_i\n * \\lambda_i = 1\\f$.\n *\n * The resulting single objective is thus defined as:\n *\n * - weighted decomposition: \\f$ f_d(\\mathbf x) = \\boldsymbol \\lambda \\cdot \\mathbf f \\f$,\n * - Tchebycheff decomposition: \\f$ f_d(\\mathbf x) = \\max_{1 \\leq i \\leq m} \\lambda_i \\vert f_i(\\mathbf x) - z^*_i \\vert\n * \\f$,\n * - boundary interception method (with penalty constraint): \\f$ f_d(\\mathbf x) = d_1 + \\theta d_2\\f$,\n *\n * where \\f$d_1 = (\\mathbf f - \\mathbf z^*) \\cdot \\hat {\\mathbf i}_{\\lambda}\\f$,\n * \\f$d_2 = \\vert (\\mathbf f - \\mathbf z^*) - d_1 \\hat {\\mathbf i}_{\\lambda})\\vert\\f$ and\n * \\f$ \\hat {\\mathbf i}_{\\lambda} = \\frac{\\boldsymbol \\lambda}{\\vert \\boldsymbol \\lambda \\vert}\\f$.\n *\n * @param f input vector of objectives.\n * @param weight the weight to be used in the decomposition.\n * @param ref_point the reference point to be used if either \"tchebycheff\" or \"bi\".\n * was indicated as a decomposition method. Its value is ignored if \"weighted\" was indicated.\n * @param method decomposition method: one of \"weighted\", \"tchebycheff\" or \"bi\"\n *\n * @return the decomposed objective.\n *\n * @throws std::invalid_argument if \\p f, \\p weight and \\p ref_point have different sizes\n * @throws std::invalid_argument if \\p method is not one of \"weighted\", \"tchebycheff\" or \"bi\"\n */\ninline vector_double decompose_objectives(const vector_double &f, const vector_double &weight,\n                                          const vector_double &ref_point, const std::string &method)\n{\n    if (weight.size() != f.size()) {\n        pagmo_throw(std::invalid_argument,\n                    \"Weight vector size must be equal to the number of objectives. The size of the weight vector is \"\n                        + std::to_string(weight.size()) + \" while \" + std::to_string(f.size())\n                        + \" objectives were detected\");\n    }\n    if (ref_point.size() != f.size()) {\n        pagmo_throw(\n            std::invalid_argument,\n            \"Reference point size must be equal to the number of objectives. The size of the reference point is \"\n                + std::to_string(ref_point.size()) + \" while \" + std::to_string(f.size())\n                + \" objectives were detected\");\n    }\n    if (f.size() == 0u) {\n        pagmo_throw(std::invalid_argument, \"The number of objectives detected is: \" + std::to_string(f.size())\n                                               + \". Cannot decompose this into anything.\");\n    }\n    double fd = 0.;\n    if (method == \"weighted\") {\n        for (decltype(f.size()) i = 0u; i < f.size(); ++i) {\n            fd += weight[i] * f[i];\n        }\n    } else if (method == \"tchebycheff\") {\n        double tmp, fixed_weight;\n        for (decltype(f.size()) i = 0u; i < f.size(); ++i) {\n            (weight[i] == 0.) ? (fixed_weight = 1e-4)\n                              : (fixed_weight = weight[i]); // fixes the numerical problem of 0 weights\n            tmp = fixed_weight * std::abs(f[i] - ref_point[i]);\n            if (tmp > fd) {\n                fd = tmp;\n            }\n        }\n    } else if (method == \"bi\") { // BI method\n        const double THETA = 5.;\n        double d1 = 0.;\n        double weight_norm = 0.;\n        for (decltype(f.size()) i = 0u; i < f.size(); ++i) {\n            d1 += (f[i] - ref_point[i]) * weight[i];\n            weight_norm += std::pow(weight[i], 2);\n        }\n        weight_norm = std::sqrt(weight_norm);\n        d1 = d1 / weight_norm;\n\n        double d2 = 0.;\n        for (decltype(f.size()) i = 0u; i < f.size(); ++i) {\n            d2 += std::pow(f[i] - (ref_point[i] + d1 * weight[i] / weight_norm), 2);\n        }\n        d2 = std::sqrt(d2);\n        fd = d1 + THETA * d2;\n    } else {\n        pagmo_throw(std::invalid_argument, \"The decomposition method chosen was: \" + method\n                                               + R\"(, but only \"weighted\", \"tchebycheff\" or \"bi\" are allowed)\");\n    }\n    return {fd};\n}\n\n} // namespace pagmo\n#endif\n", "meta": {"hexsha": "01c494331d762b08e8480326539fa5bb93f0945f", "size": 35364, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Gui/pagmo/utils/multi_objective.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/multi_objective.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/multi_objective.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": 44.5952080706, "max_line_length": 120, "alphanum_fraction": 0.6196414433, "num_tokens": 9089, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6113819732941511, "lm_q2_score": 0.5, "lm_q1q2_score": 0.30569098664707556}}
{"text": "#include <boost/serialization/export.hpp>\n#include \"StochasticGradientDescent.hpp\"\n#include \"../layer/neuron/RecurrentNeuron.hpp\"\n#include \"../layer/neuron/SimpleNeuron.hpp\"\n\nusing namespace std;\nusing namespace snn;\nusing namespace internal;\n\nBOOST_CLASS_EXPORT(StochasticGradientDescent)\n\nStochasticGradientDescent::StochasticGradientDescent(const float learningRate, const float momentum)\n    : learningRate(learningRate), momentum(momentum)\n{\n}\n\nshared_ptr<NeuralNetworkOptimizer> StochasticGradientDescent::clone() const\n{\n    return make_shared<StochasticGradientDescent>(*this);\n}\n\nvoid StochasticGradientDescent::updateWeights(SimpleNeuron& neuron, float error) const\n{\n    for (size_t w = 0; w < neuron.weights.size(); ++w)\n    {\n        auto deltaWeights = this->learningRate * error * neuron.lastInputs[w];\n        deltaWeights += this->momentum * neuron.previousDeltaWeights[w];\n        neuron.weights[w] += deltaWeights;\n        neuron.previousDeltaWeights[w] = deltaWeights;\n    }\n}\n\nvoid StochasticGradientDescent::updateWeights(RecurrentNeuron& neuron, float error) const\n{\n    size_t w;\n    for (w = 0; w < neuron.lastInputs.size(); ++w)\n    {\n        auto deltaWeights = this->learningRate * error * neuron.lastInputs[w];\n        deltaWeights += this->momentum * neuron.previousDeltaWeights[w];\n        neuron.weights[w] += deltaWeights;\n        neuron.previousDeltaWeights[w] = deltaWeights;\n    }\n    neuron.recurrentError = error + neuron.recurrentError * neuron.outputFunction->derivative(neuron.previousSum) *\n        neuron.weights[w];\n\n    auto deltaWeights = this->learningRate * neuron.recurrentError * neuron.previousOutput;\n    deltaWeights += this->momentum * neuron.previousDeltaWeights[w];\n    neuron.weights[w] += deltaWeights;\n    neuron.previousDeltaWeights[w] = deltaWeights;\n}\n\nint StochasticGradientDescent::isValid()\n{\n    if (this->learningRate <= 0.0f || this->learningRate >= 1.0f)\n        return 103;\n    if (this->momentum < 0.0f || this->momentum > 1.0f)\n        return 104;\n    return 0;\n}\n\nbool StochasticGradientDescent::operator==(const NeuralNetworkOptimizer& optimizer) const\n{\n    try\n    {\n        const auto& o = dynamic_cast<const StochasticGradientDescent&>(optimizer);\n        return this->NeuralNetworkOptimizer::operator==(optimizer)\n            && this->learningRate == o.learningRate\n            && this->momentum == o.momentum;\n    }\n    catch (bad_cast&)\n    {\n        return false;\n    }\n}\n\nbool StochasticGradientDescent::operator!=(const NeuralNetworkOptimizer& optimizer) const\n{\n    return !(*this == optimizer);\n}\n", "meta": {"hexsha": "a27b67499e0dd2af28b5ae522ad15a551d40179f", "size": 2583, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/neural_network/optimizer/StochasticGradientDescent.cpp", "max_stars_repo_name": "sehe/StraightforwardNeuralNetwork", "max_stars_repo_head_hexsha": "9758a808cdb87ffa5f1606fde9d673ef922fe6bc", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-02-16T22:13:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-16T22:13:25.000Z", "max_issues_repo_path": "src/neural_network/optimizer/StochasticGradientDescent.cpp", "max_issues_repo_name": "sehe/StraightforwardNeuralNetwork", "max_issues_repo_head_hexsha": "9758a808cdb87ffa5f1606fde9d673ef922fe6bc", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/neural_network/optimizer/StochasticGradientDescent.cpp", "max_forks_repo_name": "sehe/StraightforwardNeuralNetwork", "max_forks_repo_head_hexsha": "9758a808cdb87ffa5f1606fde9d673ef922fe6bc", "max_forks_repo_licenses": ["Apache-2.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.2875, "max_line_length": 115, "alphanum_fraction": 0.7065427797, "num_tokens": 613, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6113819732941511, "lm_q2_score": 0.5, "lm_q1q2_score": 0.30569098664707556}}
{"text": "// Copyright 2021 Apex.AI, Inc.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//     http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//\n// Co-developed by Tier IV, Inc. and Apex.AI, Inc.\n\n/// \\copyright Copyright 2021 Apex.AI, Inc.\n/// All rights reserved.\n\n#ifndef STATE_ESTIMATION_NODES__KALMAN_FILTER_WRAPPER_HPP_\n#define STATE_ESTIMATION_NODES__KALMAN_FILTER_WRAPPER_HPP_\n\n#include <common/types.hpp>\n#include <measurement_conversion/measurement_typedefs.hpp>\n#include <nav_msgs/msg/odometry.hpp>\n#include <state_estimation/kalman_filter/kalman_filter.hpp>\n#include <state_estimation_nodes/filter_typedefs.hpp>\n#include <state_estimation_nodes/history.hpp>\n#include <state_estimation_nodes/steady_time_grid.hpp>\n#include <state_estimation_nodes/visibility_control.hpp>\n#include <state_vector/common_states.hpp>\n\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n\n#include <chrono>\n#include <cstdint>\n#include <limits>\n#include <memory>\n#include <string>\n#include <vector>\n\nnamespace autoware\n{\nnamespace common\n{\nnamespace state_estimation\n{\n\n///\n/// @brief      This class provides a high level interface to the Kalman Filter allowing to predict\n///             the state of the filter with time and observe it by receiving ROS messages.\n///\n/// @tparam     FilterT           Type of filter used internally.\n///\ntemplate<typename FilterT>\nclass STATE_ESTIMATION_NODES_PUBLIC KalmanFilterWrapper\n{\n  using HistoryT = History<\n    FilterT,\n    PredictionEvent,\n    ResetEvent<FilterT>,\n    PoseMeasurementXYZ32,\n    PoseMeasurementXYZRPY32>;\n\npublic:\n  EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n  using State = typename FilterT::State;\n\n  ///\n  /// @brief      Create an EKF wrapper.\n  ///\n  /// @param[in]  motion_model              The motion model that is to be used.\n  /// @param[in]  noise_model               The noise model that is to be used.\n  /// @param[in]  initial_state_covariance  The initial covariances for the state. This is usually a\n  ///                                       diagonal matrix with sigmas squared for each state\n  ///                                       dimension on the diagonal.\n  /// @param[in]  expected_dt               Expected time difference between updates of the filter.\n  /// @param[in]  frame_id                  The frame id in which tracking takes place.\n  /// @param[in]  history_duration          Length of the history of events.\n  /// @param[in]  mahalanobis_threshold     The threshold on the Mahalanobis distance for outlier\n  ///                                       rejection.\n  ///\n  KalmanFilterWrapper(\n    const typename FilterT::MotionModel motion_model,\n    const typename FilterT::NoiseModel noise_model,\n    const typename FilterT::State::Matrix initial_state_covariance,\n    const std::chrono::nanoseconds & expected_dt,\n    const std::string & frame_id,\n    const std::chrono::nanoseconds & history_duration = std::chrono::milliseconds{5000},\n    common::types::float32_t mahalanobis_threshold =\n    std::numeric_limits<common::types::float32_t>::max())\n  : m_initial_covariance{initial_state_covariance},\n    m_frame_id{frame_id},\n    m_mahalanobis_threshold{mahalanobis_threshold},\n    m_expected_prediction_period{expected_dt},\n    m_filter{\n      motion_model,\n      noise_model,\n      State{},\n      initial_state_covariance,\n    },\n    m_history{\n      m_filter,\n      static_cast<std::size_t>(history_duration / expected_dt),\n      m_mahalanobis_threshold} {}\n\n  ///\n  /// Reset the filter state using the default covariance and state derived from the measurement.\n  ///\n  /// @param[in]  measurement   The measurement from which we initialize the state.\n  ///\n  /// @tparam     MeasurementT  Type of measurement.\n  ///\n  template<typename MeasurementT>\n  inline void add_reset_event_to_history(const MeasurementT & measurement)\n  {\n    add_reset_event_to_history(\n      measurement.measurement.map_into(State{}),\n      m_initial_covariance,\n      measurement.timestamp);\n  }\n\n  ///\n  /// Reset the filter state. This must be called at least once to start / tracking.\n  ///\n  /// @param[in]  state               The full state to set the system to.\n  /// @param[in]  initial_covariance  The initial covariance.\n  /// @param[in]  event_timestamp     The event timestamp. Ideally this should be in the same clock\n  ///                                 as the one that timestamps the messages.\n  ///\n  inline void add_reset_event_to_history(\n    const State & state,\n    const typename State::Matrix & initial_covariance,\n    const std::chrono::system_clock::time_point & event_timestamp)\n  {\n    m_history.emplace_event(event_timestamp, ResetEvent<FilterT>{state, initial_covariance});\n    m_time_grid = SteadyTimeGrid{event_timestamp, m_expected_prediction_period};\n  }\n\n  ///\n  /// Predict state of filter at the next timestep defined by the period of this node.\n  ///\n  /// @return     true if the update was successful and false otherwise. In case false is returned,\n  ///             this update had no effect on the state of the filter.\n  ///\n  inline common::types::bool8_t add_next_temporal_update_to_history()\n  {\n    if (!is_initialized()) {return false;}\n    const auto next_prediction_timestamp =\n      m_time_grid.get_next_timestamp_after(m_history.get_last_timestamp());\n    m_history.emplace_event(next_prediction_timestamp, PredictionEvent{});\n    return true;\n  }\n\n  ///\n  /// Update the filter state with a measurement.\n  ///\n  /// @param[in]  measurement            The measurement. It is expected to be a concrete\n  ///                                    instantiation of the Measurement class.\n  ///\n  /// @tparam     MeasurementT           Measurement type that is a concrete template specialization\n  ///                                    of the Measurement class.\n  ///\n  /// @return     true if the observation was successful, false otherwise. In case of an\n  ///             unsuccessful update, the state of the underlying filter has not been changed.\n  ///\n  template<typename MeasurementT>\n  common::types::bool8_t add_observation_to_history(const MeasurementT & measurement)\n  {\n    if (!is_initialized()) {return false;}\n    m_history.emplace_event(measurement.timestamp, measurement.measurement);\n    return true;\n  }\n\n  /// Check if the filter is is_initialized with a state.\n  inline common::types::bool8_t is_initialized() const noexcept\n  {\n    return (!m_history.empty()) && m_time_grid.is_initialized();\n  }\n\n  /// Get the current state of the system as an odometry message.\n  nav_msgs::msg::Odometry get_state() const;\n\nprivate:\n  /// Initial covariance of the filter.\n  typename State::Matrix m_initial_covariance{};\n  /// Time represented in a frame based on the last measurement timestamp.\n  SteadyTimeGrid m_time_grid{};\n  /// Frame in which the estimation happens, e.g. \"odom\".\n  std::string m_frame_id{};\n  /// The threshold on the Mahalanobis distance used to reject outliers.\n  common::types::float32_t m_mahalanobis_threshold{};\n  /// What duration passes between prediction events.\n  std::chrono::nanoseconds m_expected_prediction_period{};\n  /// Wrapper owns the filter implementation.\n  FilterT m_filter{};\n  /// History of all events is stored here.\n  HistoryT m_history{};\n};\n\nusing ConstantAccelerationFilterWrapperXY =\n  KalmanFilterWrapper<ConstAccelerationKalmanFilterXY>;\n\nusing ConstantAccelerationFilterWrapperXYZRPY =\n  KalmanFilterWrapper<ConstAccelerationKalmanFilterXYZRPY>;\n\n}  // namespace state_estimation\n}  // namespace common\n}  // namespace autoware\n\n#endif  // STATE_ESTIMATION_NODES__KALMAN_FILTER_WRAPPER_HPP_\n", "meta": {"hexsha": "39d888b6f14c99e29ebd2cbcaeb2ce4a0746dbab", "size": 8006, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/common/state_estimation_nodes/include/state_estimation_nodes/kalman_filter_wrapper.hpp", "max_stars_repo_name": "ruvus/auto", "max_stars_repo_head_hexsha": "25ae62d6e575cae40212356eed43ec3e76e9a13e", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 19.0, "max_stars_repo_stars_event_min_datetime": "2021-05-28T06:14:21.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-10T10:03:08.000Z", "max_issues_repo_path": "src/common/state_estimation_nodes/include/state_estimation_nodes/kalman_filter_wrapper.hpp", "max_issues_repo_name": "ruvus/auto", "max_issues_repo_head_hexsha": "25ae62d6e575cae40212356eed43ec3e76e9a13e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 222.0, "max_issues_repo_issues_event_min_datetime": "2021-10-29T22:00:27.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-29T20:56:34.000Z", "max_forks_repo_path": "src/common/state_estimation_nodes/include/state_estimation_nodes/kalman_filter_wrapper.hpp", "max_forks_repo_name": "ruvus/auto", "max_forks_repo_head_hexsha": "25ae62d6e575cae40212356eed43ec3e76e9a13e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 14.0, "max_forks_repo_forks_event_min_datetime": "2021-05-29T14:59:17.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-10T10:03:09.000Z", "avg_line_length": 37.5868544601, "max_line_length": 100, "alphanum_fraction": 0.7065950537, "num_tokens": 1748, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6113819732941511, "lm_q2_score": 0.5, "lm_q1q2_score": 0.30569098664707556}}
{"text": "/*===================================================================\r\n\r\nThe Medical Imaging Interaction Toolkit (MITK)\r\n\r\nCopyright (c) German Cancer Research Center,\r\nDivision of Medical and Biological Informatics.\r\nAll rights reserved.\r\n\r\nThis software is distributed WITHOUT ANY WARRANTY; without\r\neven the implied warranty of MERCHANTABILITY or FITNESS FOR\r\nA PARTICULAR PURPOSE.\r\n\r\nSee LICENSE.txt or http://www.mitk.org for details.\r\n\r\n===================================================================*/\r\n#ifndef __itkOdfMaximaExtractionFilter_cpp\r\n#define __itkOdfMaximaExtractionFilter_cpp\r\n\r\n\r\n#include \"itkOdfMaximaExtractionFilter.h\"\r\n#include <itkImageRegionIterator.h>\r\n#include <itkContinuousIndex.h>\r\n\r\n#include <vtkSmartPointer.h>\r\n#include <vtkPolyData.h>\r\n#include <vtkCellArray.h>\r\n#include <vtkPoints.h>\r\n#include <vtkPolyLine.h>\r\n\r\n#include <boost/progress.hpp>\r\n#include <boost/math/special_functions.hpp>\r\n#include <vnl/vnl_det.h>\r\n#include <vnl/vnl_trace.h>\r\n\r\nusing namespace boost::math;\r\nusing namespace std;\r\n\r\nnamespace itk {\r\n\r\ntemplate< class TOdfPixelType >\r\nOdfMaximaExtractionFilter< TOdfPixelType >::OdfMaximaExtractionFilter():\r\n    m_NormalizationMethod(MAX_VEC_NORM),\r\n    m_PeakThreshold(0.2),\r\n    m_MaxNumPeaks(10),\r\n    m_ShCoeffImage(NULL),\r\n    m_OutputFiberBundle(NULL),\r\n    m_NumDirectionsImage(NULL),\r\n    m_DirectionImageContainer(NULL)\r\n{\r\n\r\n}\r\n\r\n// solve ax? + bx? + cx + d = 0 using cardanos method\r\ntemplate< class TOdfPixelType >\r\nbool OdfMaximaExtractionFilter<TOdfPixelType>::ReconstructQballImage()\r\n{\r\n    if (m_ShCoeffImage.IsNotNull())\r\n    {\r\n        cout << \"Using preset coefficient image\\n\";\r\n        return true;\r\n    }\r\n\r\n    cout << \"Starting qball reconstruction\\n\";\r\n    try {\r\n        QballReconstructionFilterType::Pointer filter = QballReconstructionFilterType::New();\r\n        filter->SetGradientImage( m_DiffusionGradients, m_DiffusionImage );\r\n        filter->SetBValue(m_Bvalue);\r\n        filter->SetLambda(0.006);\r\n        filter->SetNormalizationMethod(QballReconstructionFilterType::QBAR_SOLID_ANGLE);\r\n        filter->Update();\r\n        m_ShCoeffImage = filter->GetCoefficientImage();\r\n        if (m_ShCoeffImage.IsNull())\r\n            return false;\r\n        return true;\r\n    }\r\n    catch (...)\r\n    {\r\n        return false;\r\n    }\r\n}\r\n\r\n// solve ax³ + bx² + cx + d = 0 using cardanos method\r\ntemplate< class TOdfPixelType >\r\nstd::vector<double> OdfMaximaExtractionFilter< TOdfPixelType >\r\n::SolveCubic(const double& a, const double& b, const double& c, const double& d)\r\n{\r\n    double A, B, p, q, r, D, offset, ee, tmp, root;\r\n    vector<double> roots;\r\n    double inv3 = 1.0/3.0;\r\n\r\n    if (a!=0) // solve ax³ + bx² + cx + d = 0\r\n    {\r\n        p = b/a; q = c/a; r = d/a; // x³ + px² + qx + r = 0\r\n        A = q-p*p*inv3;\r\n        B = (2.0*p*p*p-9.0*p*q+27.0*r)/27.0;\r\n        A = A*inv3;\r\n        B = B*0.5;\r\n        D = B*B+A*A*A;\r\n        offset = p*inv3;\r\n\r\n        if (D>0.0) // one real root\r\n        {\r\n            ee = sqrt(D);\r\n            tmp = -B+ee;  root  = cbrt(tmp);\r\n            tmp = -B-ee;  root += cbrt(tmp);\r\n            root -= offset; roots.push_back(root);\r\n        }\r\n        else if (D<0.0) // three real roots\r\n        {\r\n            ee = sqrt(-D);\r\n            double tmp2 = -B;\r\n            double angle =  2.0*inv3*atan(ee/(sqrt(tmp2*tmp2+ee*ee)+tmp2));\r\n            double sqrt3 = sqrt(3.0);\r\n            tmp = cos(angle);\r\n            tmp2 = sin(angle);\r\n            ee = sqrt(-A);\r\n            root = 2*ee*tmp-offset;             roots.push_back(root);\r\n            root = -ee*(tmp+sqrt3*tmp2)-offset; roots.push_back(root);\r\n            root = -ee*(tmp-sqrt3*tmp2)-offset; roots.push_back(root);\r\n        }\r\n        else // one or two real roots\r\n        {\r\n            tmp=-B;\r\n            tmp=cbrt(tmp);\r\n            root=2*tmp-offset;      roots.push_back(root);\r\n            if (A!=0 || B!=0)\r\n                root=-tmp-offset;   roots.push_back(root);\r\n        }\r\n    }\r\n    else if (b!=0) // solve bx² + cx + d = 0\r\n    {\r\n        D = c*c-4*b*d;\r\n        if (D>0)\r\n        {\r\n            tmp = sqrt(D);\r\n            root = (-c+tmp)/(2.0*b); roots.push_back(root);\r\n            root = (-c-tmp)/(2.0*b); roots.push_back(root);\r\n        }\r\n        else if (D==0)\r\n            root = -c/(2.0*b); roots.push_back(root);\r\n    }\r\n    else if (c!=0) // solve cx + d = 0\r\n        root = -d/c; roots.push_back(root);\r\n\r\n    return roots;\r\n}\r\n\r\ntemplate< class TOdfPixelType >\r\ndouble OdfMaximaExtractionFilter< TOdfPixelType >\r\n::ODF_dtheta(const double& sn, const double& cs, const double& A, const double& B, const double& C, const double& D, const double& E, const double& F, const double& G, const double& H)\r\n{\r\n    double dtheta=(G-7*E)*sn*sn + (7*F-35*D-H)*sn*cs + (H+C-F-3*A-5*D)*sn + (0.5*E+B+0.5*G)*cs -0.5*G+3.5*E;\r\n    return dtheta;\r\n}\r\n\r\ntemplate< class TOdfPixelType >\r\ndouble OdfMaximaExtractionFilter< TOdfPixelType >\r\n::ODF_dtheta2(const double& sn, const double& cs, const double& A, const double& B, const double& C, const double& D, const double& E, const double& F, const double& G, const double& H)\r\n{\r\n    double dtheta2=4*(G-7*E)*sn*cs + 2*(7*F-35*D-H)*(2*cs*cs-1) + 2*(H+C-F-3*A-5*D)*cs -(E+2*B+G)*sn;\r\n    return dtheta2;\r\n}\r\n\r\ntemplate< class TOdfPixelType >\r\ndouble OdfMaximaExtractionFilter< TOdfPixelType >\r\n::ODF_dphi2(const double& sn, const double& cs, const double& A, const double& B, const double& C, const double& D, const double& E, const double& F, const double& G, const double& H)\r\n{\r\n    double dphi2=35*D*((1+cs)*(1+cs)/4)+(3*A-30*D)*(1+cs)/2.0+3*D-A + 0.5*(7*E*(1+cs)/2.0-3*E+B)*sn + (7*F*(1+cs)/2+C-F)*(1-cs)/2.0 + G*sn*(1-cs)/4.0 + H*((1-cs)*(1-cs)/4);\r\n    return dphi2;\r\n}\r\n\r\ntemplate< class TOdfPixelType >\r\nvoid OdfMaximaExtractionFilter< TOdfPixelType >\r\n::FindCandidatePeaks(const CoefficientPixelType& SHcoeff)\r\n{\r\n    const double thr = 0.03;             // threshold on the derivative of the ODF with respect to theta\r\n    const double phi_step = 0.005;       // step size for 1D exhaustive search on phi\r\n    bool highRes;                        // when close to maxima increase resolution\r\n    double mag, Y, Yp, sn, cs;\r\n    double phi, dPhi;\r\n    double A, B, C, D, E, F, G, H, Bp, Cp, Ep, Fp, Gp, Hp, Bs, Cs, Es, Fs, Gs, Hs;\r\n    CoefficientPixelType a, ap;\r\n    a = SHcoeff; ap = SHcoeff;\r\n\r\n    m_CandidatePeaks.clear();   // clear peaks of last voxel\r\n\r\n    for (int adaptiveStepwidth=0; adaptiveStepwidth<=1; adaptiveStepwidth++)\r\n    {\r\n    phi=0;\r\n    while (phi<(2*M_PI)) // phi exhaustive search 0..pi\r\n    {\r\n        // calculate 4th order SH representtaion of ODF and according derivative\r\n        for (int l=0; l<=4; l=l+2)\r\n        {\r\n            for (int m=-l; m<=l; m++)\r\n            {\r\n                int j=l*(l+1)/2+m;\r\n                if (m<0)\r\n                {\r\n                    mag = sqrt(((2*l+1)/(2*M_PI))*factorial<double>(l+m)/factorial<double>(l-m));\r\n                    Y = mag*cos(m*phi);\r\n                    Yp = -m*mag*sin(m*phi);\r\n                }\r\n                else if (m==0)\r\n                {\r\n                    Y = sqrt((2*l+1)/(4*M_PI));\r\n                    Yp = 0;\r\n                }\r\n                else\r\n                {\r\n                    mag = pow(-1.0,m)*sqrt(((2*l+1)/(2*M_PI))*factorial<double>(l-m)/factorial<double>(l+m));\r\n                    Y = mag*sin(m*phi);\r\n                    Yp = m*mag*cos(m*phi);\r\n                }\r\n                a[j] = SHcoeff[j]*Y;\r\n                ap[j] = SHcoeff[j]*Yp;\r\n            }\r\n        }\r\n\r\n        // ODF\r\n        A=0.5*a[3]; B=-3*(a[2]+a[4]); C=3*(a[1]+a[5]); D=0.125*a[10]; E=-2.5*(a[9]+a[11]);\r\n        F=7.5*(a[8]+a[12]); G=-105*(a[7]+a[13]); H=105*(a[6]+a[14]);\r\n\r\n        // phi derivative\r\n        Bp=-3*(ap[2]+ap[4]); Cp=3*(ap[1]+ap[5]); Ep=-2.5*(ap[9]+ap[11]);\r\n        Fp=7.5*(ap[8]+ap[12]); Gp=-105*(ap[7]+ap[13]); Hp=105*(ap[6]+ap[14]);\r\n\r\n        // 2phi derivative\r\n        Bs=-B;    Cs=-4*C;  Es=-E;\r\n        Fs=-4*F;  Gs=-9*G;  Hs=-16*H;\r\n\r\n        // solve cubic for tan(theta)\r\n        std::vector<double> tanTheta = SolveCubic(Hp+Cp-Fp, Gp+Bp-3*Ep, 6*Fp+Cp, Bp+4*Ep);\r\n\r\n        highRes = false;\r\n        dPhi = phi_step;\r\n\r\n        //for each real cubic solution for tan(theta)\r\n        for (int n=0; n<tanTheta.size(); n++)\r\n        {\r\n            double tmp = atan(tanTheta[n]); // arcus tangens of root (theta -pi/2..pi/2)\r\n            double theta = floor(tmp/M_PI); // project theta to 0..pi ...\r\n            theta = tmp - theta*M_PI;       // ... as the modulo of the division atan(tth[n])/M_PI\r\n\r\n            sn = sin(2*theta); cs = cos(2*theta);\r\n            tmp = ODF_dtheta(sn, cs, A, B, C, D, E, F, G, H);\r\n\r\n            if (fabs(tmp) < thr) // second condition for maximum is true (theta derivative < eps)\r\n            {\r\n                //Compute the Hessian\r\n                vnl_matrix_fixed< double, 2, 2 > hessian;\r\n                hessian(0,0) = ODF_dtheta2(sn, cs, A, B, C, D, E, F, G, H);\r\n                hessian(0,1) = ODF_dtheta(sn, cs, 0, Bp, Cp, 0, Ep, Fp, Gp, Hp);\r\n                hessian(1,0) = hessian(0,1);\r\n                hessian(1,1) = ODF_dphi2(sn, cs, 0, Bs, Cs, 0, Es, Fs, Gs, Hs);\r\n\r\n                double det = vnl_det(hessian);  // determinant\r\n                double tr = vnl_trace(hessian); // trace\r\n\r\n                highRes = true; // we are close to a maximum, so turn on high resolution 1D exhaustive search\r\n                if (det>=0 && tr<=0) // check if we really have a local maximum\r\n                {\r\n                    vnl_vector_fixed< double, 2 > peak;\r\n                    peak[0] = theta;\r\n                    peak[1] = phi;\r\n                    m_CandidatePeaks.push_back(peak);\r\n                }\r\n            }\r\n\r\n            if (adaptiveStepwidth) // calculate adaptive step width\r\n            {\r\n                double t2=tanTheta[n]*tanTheta[n];  double t3=t2*tanTheta[n]; double t4=t3*tanTheta[n];\r\n                double const_step=phi_step*(1+t2)/sqrt(t2+t4+pow((((Hs+Cs-Fs)*t3+(Gs+Bs-3*Es)*t2+(6*Fs+Cs)*tanTheta[n]+(Bs+4*Es))/(3*(Hp+Cp-Fp)*t2+2*(Gp+Bp-3*Ep)*tanTheta[n]+(6*Fp+Cp))),2.0));\r\n                if (const_step<dPhi)\r\n                    dPhi=const_step;\r\n            }\r\n        }\r\n\r\n        // update phi\r\n        if (highRes)\r\n            phi=phi+dPhi*0.5;\r\n        else\r\n            phi=phi+dPhi;\r\n    }\r\n    }\r\n}\r\n\r\ntemplate< class TOdfPixelType >\r\nstd::vector< vnl_vector_fixed< double, 3 > > OdfMaximaExtractionFilter< TOdfPixelType >\r\n::ClusterPeaks(const CoefficientPixelType& shCoeff)\r\n{\r\n    const double distThres = 0.4;\r\n    int npeaks = 0, nMin = 0;\r\n    double dMin, dPos, dNeg, d;\r\n    Vector3D u;\r\n    vector< Vector3D > v;\r\n\r\n    // initialize container for vector clusters\r\n    std::vector < std::vector< Vector3D > > clusters;\r\n    clusters.resize(m_CandidatePeaks.size());\r\n\r\n    for (int i=0; i<m_CandidatePeaks.size(); i++)\r\n    {\r\n        // calculate cartesian representation of peak\r\n        u[0] = sin(m_CandidatePeaks[i](0))*cos(m_CandidatePeaks[i](1));\r\n        u[1] = sin(m_CandidatePeaks[i](0))*sin(m_CandidatePeaks[i](1));\r\n        u[2] = cos(m_CandidatePeaks[i](0));\r\n\r\n        dMin = itk::NumericTraits<double>::max();\r\n        for (int n=0; n<npeaks; n++) //for each other maximum v already visited\r\n        {\r\n            // euclidean distance from u/-u to other clusters\r\n            dPos = vnl_vector_ssd(v[n],u);\r\n            dNeg = vnl_vector_ssd(v[n],-u);\r\n            d = std::min(dPos,dNeg);\r\n\r\n            if ( d<dMin )\r\n            {\r\n                dMin = d; // adjust minimum\r\n                nMin = n; // store its index\r\n                if ( dNeg<dPos ) // flip u if neccesary\r\n                    u=-u;\r\n            }\r\n        }\r\n        if ( dMin<distThres ) // if u is very close to any other maximum v\r\n        {\r\n            clusters[nMin].push_back(u);  //store it with all other vectors that are close to v vector (with index nMin)\r\n        }\r\n        else // otherwise store u as output peak\r\n        {\r\n            v.push_back(u);\r\n            npeaks++;\r\n        }\r\n    }\r\n\r\n    // calculate mean vector of each cluster\r\n    for (int i=0; i<m_CandidatePeaks.size(); i++)\r\n        if ( !clusters[i].empty() )\r\n        {\r\n            v[i].fill(0.0);\r\n            for (int vc=0; vc<clusters[i].size(); vc++)\r\n                v[i]=v[i]+clusters[i][vc];\r\n            v[i].normalize();\r\n        }\r\n\r\n\r\n    if (npeaks!=0)\r\n    {\r\n        // check the ODF amplitudes at each candidate peak\r\n        vnl_matrix< double > shBasis, sphCoords;\r\n\r\n        Cart2Sph(v, sphCoords);                 // convert candidate peaks to spherical angles\r\n        shBasis = CalcShBasis(sphCoords, 4);  // evaluate spherical harmonics at each peak\r\n        vnl_vector<double> odfVals(npeaks);\r\n        odfVals.fill(0.0);\r\n        double maxVal = itk::NumericTraits<double>::NonpositiveMin();\r\n        int maxPos;\r\n        for (int i=0; i<npeaks; i++) //compute the ODF value at each peak\r\n        {\r\n            for (int j=0; j<15; j++)\r\n                odfVals(i) += shCoeff[j]*shBasis(i,j);\r\n\r\n            if ( odfVals(i)>maxVal )\r\n            {\r\n                maxVal = odfVals(i);\r\n                maxPos = i;\r\n            }\r\n        }\r\n        v.clear();\r\n        vector< double > restVals;\r\n        for (int i=0; i<npeaks; i++) // keep only peaks with high enough amplitude and convert back to cartesian coordinates\r\n            if ( odfVals(i)>=m_PeakThreshold*maxVal )\r\n            {\r\n                u[0] = odfVals(i)*cos(sphCoords(i,1))*sin(sphCoords(i,0));\r\n                u[1] = odfVals(i)*sin(sphCoords(i,1))*sin(sphCoords(i,0));\r\n                u[2] = odfVals(i)*cos(sphCoords(i,0));\r\n                restVals.push_back(odfVals(i));\r\n                v.push_back(u);\r\n            }\r\n        npeaks = v.size();\r\n\r\n        if (npeaks>m_MaxNumPeaks) // if still too many peaks, keep only the m_MaxNumPeaks with maximum value\r\n        {\r\n            vector< Vector3D > v2;\r\n            for (int i=0; i<m_MaxNumPeaks; i++)\r\n            {\r\n                maxVal = itk::NumericTraits<double>::NonpositiveMin();  //Get the maximum ODF peak value and the corresponding peak index\r\n                for (int i=0; i<npeaks; i++)\r\n                    if ( restVals[i]>maxVal )\r\n                    {\r\n                        maxVal = restVals[i];\r\n                        maxPos = i;\r\n                    }\r\n\r\n                v2.push_back(v[maxPos]);\r\n                restVals[maxPos] = 0;               //zero that entry in order to find the next maximum\r\n            }\r\n            return v2;\r\n        }\r\n    }\r\n    return v;\r\n}\r\n\r\n// convert cartesian to spherical coordinates\r\ntemplate< class TOdfPixelType >\r\nvoid OdfMaximaExtractionFilter< TOdfPixelType >\r\n::Cart2Sph(const std::vector< Vector3D >& dir, vnl_matrix<double>& sphCoords)\r\n{\r\n    sphCoords.set_size(dir.size(), 2);\r\n\r\n    for (int i=0; i<dir.size(); i++)\r\n    {\r\n        double mag = dir[i].magnitude();\r\n\r\n        if( mag<mitk::eps )\r\n        {\r\n            sphCoords(i,0) = M_PI/2; // theta\r\n            sphCoords(i,1) = M_PI/2; // phi\r\n        }\r\n        else\r\n        {\r\n            sphCoords(i,0) = acos(dir[i](2)/mag); // theta\r\n            sphCoords(i,1) = atan2(dir[i](1), dir[i](0)); // phi\r\n        }\r\n    }\r\n}\r\n\r\n// generate spherical harmonic values of the desired order for each input direction\r\ntemplate< class TOdfPixelType >\r\nvnl_matrix<double> OdfMaximaExtractionFilter< TOdfPixelType >\r\n::CalcShBasis(vnl_matrix<double>& sphCoords, const int& shOrder)\r\n{\r\n    int R = (shOrder+1)*(shOrder+2)/2;\r\n    int M = sphCoords.rows();\r\n    int j, m; double mag, plm;\r\n    vnl_matrix<double> shBasis;\r\n    shBasis.set_size(M,R);\r\n\r\n    for (int p=0; p<M; p++)\r\n    {\r\n        j=0;\r\n        for (int l=0; l<=shOrder; l=l+2)\r\n            for (m=-l; m<=l; m++)\r\n            {\r\n                plm = legendre_p<double>(l,abs(m),cos(sphCoords(p,0)));\r\n                mag = sqrt((double)(2*l+1)/(4.0*M_PI)*factorial<double>(l-abs(m))/factorial<double>(l+abs(m)))*plm;\r\n\r\n                if (m<0)\r\n                    shBasis(p,j) = sqrt(2.0)*mag*cos(fabs((double)m)*sphCoords(p,1));\r\n                else if (m==0)\r\n                    shBasis(p,j) = mag;\r\n                else\r\n                    shBasis(p,j) = pow(-1.0, m)*sqrt(2.0)*mag*sin(m*sphCoords(p,1));\r\n                j++;\r\n            }\r\n    }\r\n    return shBasis;\r\n}\r\n\r\ntemplate< class TOdfPixelType >\r\nvoid OdfMaximaExtractionFilter< TOdfPixelType >\r\n::GenerateData()\r\n{\r\n    if (!ReconstructQballImage())\r\n        return;\r\n\r\n    std::cout << \"Starting maxima extraction\\n\";\r\n\r\n    switch (m_NormalizationMethod)\r\n    {\r\n    case NO_NORM:\r\n        std::cout << \"NO_NORM\\n\";\r\n        break;\r\n    case SINGLE_VEC_NORM:\r\n        std::cout << \"SINGLE_VEC_NORM\\n\";\r\n        break;\r\n    case MAX_VEC_NORM:\r\n        std::cout << \"MAX_VEC_NORM\\n\";\r\n        break;\r\n    }\r\n\r\n    typedef ImageRegionConstIterator< CoefficientImageType > InputIteratorType;\r\n\r\n\r\n    InputIteratorType git(m_ShCoeffImage, m_ShCoeffImage->GetLargestPossibleRegion() );\r\n\r\n    itk::Vector<double,3> spacing = m_ShCoeffImage->GetSpacing();\r\n    double minSpacing = spacing[0];\r\n    if (spacing[1]<minSpacing)\r\n        minSpacing = spacing[1];\r\n    if (spacing[2]<minSpacing)\r\n        minSpacing = spacing[2];\r\n\r\n    mitk::Point3D origin = m_ShCoeffImage->GetOrigin();\r\n    itk::Matrix<double, 3, 3> direction = m_ShCoeffImage->GetDirection();\r\n    ImageRegion<3> imageRegion = m_ShCoeffImage->GetLargestPossibleRegion();\r\n\r\n    // initialize num directions image\r\n    m_NumDirectionsImage = ItkUcharImgType::New();\r\n    m_NumDirectionsImage->SetSpacing( spacing );\r\n    m_NumDirectionsImage->SetOrigin( origin );\r\n    m_NumDirectionsImage->SetDirection( direction );\r\n    m_NumDirectionsImage->SetRegions( imageRegion );\r\n    m_NumDirectionsImage->Allocate();\r\n    m_NumDirectionsImage->FillBuffer(0);\r\n\r\n    vtkSmartPointer<vtkCellArray> m_VtkCellArray = vtkSmartPointer<vtkCellArray>::New();\r\n    vtkSmartPointer<vtkPoints>    m_VtkPoints = vtkSmartPointer<vtkPoints>::New();\r\n\r\n    m_DirectionImageContainer = ItkDirectionImageContainer::New();\r\n    for (int i=0; i<m_MaxNumPeaks; i++)\r\n    {\r\n        itk::Vector< float, 3 > nullVec; nullVec.Fill(0.0);\r\n        ItkDirectionImage::Pointer img = ItkDirectionImage::New();\r\n        img->SetSpacing( spacing );\r\n        img->SetOrigin( origin );\r\n        img->SetDirection( direction );\r\n        img->SetRegions( imageRegion );\r\n        img->Allocate();\r\n        img->FillBuffer(nullVec);\r\n        m_DirectionImageContainer->InsertElement(m_DirectionImageContainer->Size(), img);\r\n    }\r\n\r\n    if (m_MaskImage.IsNull())\r\n    {\r\n        m_MaskImage = ItkUcharImgType::New();\r\n        m_MaskImage->SetSpacing( spacing );\r\n        m_MaskImage->SetOrigin( origin );\r\n        m_MaskImage->SetDirection( direction );\r\n        m_MaskImage->SetRegions( imageRegion );\r\n        m_MaskImage->Allocate();\r\n        m_MaskImage->FillBuffer(1);\r\n    }\r\n\r\n    itk::ImageRegionIterator<ItkUcharImgType> dirIt(m_NumDirectionsImage, m_NumDirectionsImage->GetLargestPossibleRegion());\r\n    itk::ImageRegionIterator<ItkUcharImgType> maskIt(m_MaskImage, m_MaskImage->GetLargestPossibleRegion());\r\n\r\n    int maxProgress = m_MaskImage->GetLargestPossibleRegion().GetSize()[0]*m_MaskImage->GetLargestPossibleRegion().GetSize()[1]*m_MaskImage->GetLargestPossibleRegion().GetSize()[2];\r\n\r\n    boost::progress_display disp(maxProgress);\r\n\r\n    git.GoToBegin();\r\n    while( !git.IsAtEnd() )\r\n    {\r\n        ++disp;\r\n        if (maskIt.Value()<=0)\r\n        {\r\n            ++git;\r\n            ++dirIt;\r\n            ++maskIt;\r\n            continue;\r\n        }\r\n\r\n        CoefficientPixelType c = git.Get();\r\n        FindCandidatePeaks(c);\r\n        std::vector< Vector3D > directions = ClusterPeaks(c);\r\n\r\n        typename CoefficientImageType::IndexType index = git.GetIndex();\r\n\r\n        float max = 0.0;\r\n        for (int i=0; i<directions.size(); i++)\r\n            if (directions.at(i).magnitude()>max)\r\n                max = directions.at(i).magnitude();\r\n        if (max<0.0001)\r\n            max = 1.0;\r\n\r\n        for (int i=0; i<directions.size(); i++)\r\n        {\r\n            ItkDirectionImage::Pointer img = m_DirectionImageContainer->GetElement(i);\r\n            itk::Vector< float, 3 > pixel;\r\n            vnl_vector<double> dir = directions.at(i);\r\n\r\n            vtkSmartPointer<vtkPolyLine> container = vtkSmartPointer<vtkPolyLine>::New();\r\n            itk::ContinuousIndex<double, 3> center;\r\n            center[0] = index[0];\r\n            center[1] = index[1];\r\n            center[2] = index[2];\r\n            itk::Point<double> worldCenter;\r\n            m_ShCoeffImage->TransformContinuousIndexToPhysicalPoint( center, worldCenter );\r\n\r\n            switch (m_NormalizationMethod)\r\n            {\r\n            case NO_NORM:\r\n                break;\r\n            case SINGLE_VEC_NORM:\r\n                dir.normalize();\r\n                break;\r\n            case MAX_VEC_NORM:\r\n                dir /= max;\r\n                break;\r\n            }\r\n\r\n            dir = m_MaskImage->GetDirection()*dir;\r\n            pixel.SetElement(0, dir[0]);\r\n            pixel.SetElement(1, dir[1]);\r\n            pixel.SetElement(2, dir[2]);\r\n            img->SetPixel(index, pixel);\r\n\r\n            itk::Point<double> worldStart;\r\n            worldStart[0] = worldCenter[0]-dir[0]/2 * minSpacing;\r\n            worldStart[1] = worldCenter[1]-dir[1]/2 * minSpacing;\r\n            worldStart[2] = worldCenter[2]-dir[2]/2 * minSpacing;\r\n            vtkIdType id = m_VtkPoints->InsertNextPoint(worldStart.GetDataPointer());\r\n            container->GetPointIds()->InsertNextId(id);\r\n            itk::Point<double> worldEnd;\r\n            worldEnd[0] = worldCenter[0]+dir[0]/2 * minSpacing;\r\n            worldEnd[1] = worldCenter[1]+dir[1]/2 * minSpacing;\r\n            worldEnd[2] = worldCenter[2]+dir[2]/2 * minSpacing;\r\n            id = m_VtkPoints->InsertNextPoint(worldEnd.GetDataPointer());\r\n            container->GetPointIds()->InsertNextId(id);\r\n            m_VtkCellArray->InsertNextCell(container);\r\n        }\r\n\r\n        dirIt.Set(directions.size());\r\n\r\n        ++git;\r\n        ++dirIt;\r\n        ++maskIt;\r\n    }\r\n\r\n    vtkSmartPointer<vtkPolyData> directionsPolyData = vtkSmartPointer<vtkPolyData>::New();\r\n    directionsPolyData->SetPoints(m_VtkPoints);\r\n    directionsPolyData->SetLines(m_VtkCellArray);\r\n    m_OutputFiberBundle = mitk::FiberBundle::New(directionsPolyData);\r\n    std::cout << \"Maxima extraction finished\\n\";\r\n}\r\n}\r\n\r\n#endif // __itkOdfMaximaExtractionFilter_cpp\r\n", "meta": {"hexsha": "d6a2a69c7e867c0c041bb3032a2ca0393a2f3a0c", "size": 22618, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Modules/DiffusionImaging/DiffusionCore/include/Algorithms/itkOdfMaximaExtractionFilter.cpp", "max_stars_repo_name": "liu3xing3long/MITK-2016.11", "max_stars_repo_head_hexsha": "385c506f9792414f40337e106e13d5fd61aa3ccc", "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": "Modules/DiffusionImaging/DiffusionCore/include/Algorithms/itkOdfMaximaExtractionFilter.cpp", "max_issues_repo_name": "liu3xing3long/MITK-2016.11", "max_issues_repo_head_hexsha": "385c506f9792414f40337e106e13d5fd61aa3ccc", "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": "Modules/DiffusionImaging/DiffusionCore/include/Algorithms/itkOdfMaximaExtractionFilter.cpp", "max_forks_repo_name": "liu3xing3long/MITK-2016.11", "max_forks_repo_head_hexsha": "385c506f9792414f40337e106e13d5fd61aa3ccc", "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.9015873016, "max_line_length": 193, "alphanum_fraction": 0.5401450172, "num_tokens": 6268, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6113819591324418, "lm_q2_score": 0.5, "lm_q1q2_score": 0.3056909795662209}}
{"text": "﻿///////////////////////////////////////////////////////////////////\n//  Copyright Christopher Kormanyos 2019 - 2022.                 //\n//  Distributed under the Boost Software License,                //\n//  Version 1.0. (See accompanying file LICENSE_1_0.txt          //\n//  or copy at http://www.boost.org/LICENSE_1_0.txt)             //\n///////////////////////////////////////////////////////////////////\n\n#ifndef UINTWIDE_T_BACKEND_2019_12_15_HPP // NOLINT(llvm-header-guard)\n  #define UINTWIDE_T_BACKEND_2019_12_15_HPP\n\n  #include <cstdint>\n  #include <limits>\n  #include <string>\n  #include <type_traits>\n  #include <utility>\n  #include <vector>\n\n  #include <boost/version.hpp>\n\n  #if !defined(BOOST_VERSION)\n  #error BOOST_VERSION is not defined. Ensure that <boost/version.hpp> is properly included.\n  #endif\n\n  #if ((BOOST_VERSION >= 107900) && !defined(BOOST_MP_STANDALONE))\n  #define BOOST_MP_STANDALONE\n  #endif\n\n  #if (BOOST_VERSION < 108000)\n  #if defined(__GNUC__)\n  #pragma GCC diagnostic push\n  #pragma GCC diagnostic ignored \"-Wconversion\"\n  #pragma GCC diagnostic push\n  #pragma GCC diagnostic ignored \"-Wsign-conversion\"\n  #pragma GCC diagnostic push\n  #pragma GCC diagnostic ignored \"-Wunused-parameter\"\n  #endif\n  #endif\n\n  #if (defined(__GNUC__) && !defined(__clang__) && (__GNUC__ >= 12))\n  #pragma GCC diagnostic push\n  #pragma GCC diagnostic ignored \"-Wrestrict\"\n  #endif\n\n  #if (BOOST_VERSION < 108000)\n  #if (defined(__clang__) && (__clang_major__ > 9)) && !defined(__APPLE__)\n  #pragma GCC diagnostic push\n  #pragma GCC diagnostic ignored \"-Wdeprecated-copy\"\n  #endif\n  #endif\n\n  #if (BOOST_VERSION < 107900)\n  #include <boost/config.hpp>\n  #endif\n  #include <boost/multiprecision/number.hpp>\n\n  #include <math/wide_integer/uintwide_t.h>\n\n  #if(__cplusplus >= 201703L)\n  namespace boost::multiprecision {\n  #else\n  namespace boost { namespace multiprecision { // NOLINT(modernize-concat-nested-namespaces)\n  #endif\n\n  // Forward declaration of the uintwide_t_backend multiple precision class.\n  // This class binds native (WIDE_INTEGER_NAMESPACE)::math::wide_integer::uintwide_t\n  // to boost::multiprecsion::uintwide_t_backend.\n  template<\n  #if defined(WIDE_INTEGER_NAMESPACE)\n           const WIDE_INTEGER_NAMESPACE::math::wide_integer::size_t MyWidth2,\n  #else\n           const ::math::wide_integer::size_t MyWidth2,\n  #endif\n           typename MyLimbType = std::uint32_t,\n           typename MyAllocatorType = void>\n  class uintwide_t_backend;\n\n  // Define the number category as an integer number kind\n  // for the uintwide_t_backend. This is needed for properly\n  // interacting as a backend with boost::muliprecision.\n  #if (BOOST_VERSION <= 107200)\n  template<\n  #if defined(WIDE_INTEGER_NAMESPACE)\n           const WIDE_INTEGER_NAMESPACE::math::wide_integer::size_t MyWidth2,\n  #else\n           const ::math::wide_integer::size_t MyWidth2,\n  #endif\n           typename MyLimbType,\n           typename MyAllocatorType>\n  struct number_category<uintwide_t_backend<MyWidth2, MyLimbType, MyAllocatorType>>\n    : public boost::mpl::int_<number_kind_integer> { };\n  #elif (BOOST_VERSION <= 107500)\n  template<\n  #if defined(WIDE_INTEGER_NAMESPACE)\n           const WIDE_INTEGER_NAMESPACE::math::wide_integer::size_t MyWidth2,\n  #else\n           const ::math::wide_integer::size_t MyWidth2,\n  #endif\n           typename MyLimbType,\n           typename MyAllocatorType>\n  struct number_category<uintwide_t_backend<MyWidth2, MyLimbType, MyAllocatorType>>\n    : public boost::integral_constant<unsigned int, number_kind_integer> { };\n  #else\n  template<\n  #if defined(WIDE_INTEGER_NAMESPACE)\n           const WIDE_INTEGER_NAMESPACE::math::wide_integer::size_t MyWidth2,\n  #else\n           const ::math::wide_integer::size_t MyWidth2,\n  #endif\n           typename MyLimbType,\n           typename MyAllocatorType>\n  struct number_category<uintwide_t_backend<MyWidth2, MyLimbType, MyAllocatorType>>\n    : public std::integral_constant<unsigned int, number_kind_integer> { };\n  #endif\n\n  // This is the uintwide_t_backend multiple precision class.\n  template<\n  #if defined(WIDE_INTEGER_NAMESPACE)\n           const WIDE_INTEGER_NAMESPACE::math::wide_integer::size_t MyWidth2,\n  #else\n           const ::math::wide_integer::size_t MyWidth2,\n  #endif\n           typename MyLimbType,\n           typename MyAllocatorType>\n  class uintwide_t_backend // NOLINT(cppcoreguidelines-special-member-functions,hicpp-special-member-functions)\n  {\n  public:\n    using representation_type =\n    #if defined(WIDE_INTEGER_NAMESPACE)\n      WIDE_INTEGER_NAMESPACE::math::wide_integer::uintwide_t<MyWidth2, MyLimbType, MyAllocatorType>;\n    #else\n      ::math::wide_integer::uintwide_t<MyWidth2, MyLimbType, MyAllocatorType>;\n    #endif\n\n    #if (BOOST_VERSION <= 107500)\n    using signed_types   = mpl::list<std::int64_t>;\n    using unsigned_types = mpl::list<std::uint64_t>;\n    using float_types    = mpl::list<long double>;\n    #else\n    using   signed_types = std::tuple<  signed char,   signed short,   signed int,   signed long,   signed long long, std::intmax_t>;  // NOLINT(google-runtime-int)\n    using unsigned_types = std::tuple<unsigned char, unsigned short, unsigned int, unsigned long, unsigned long long, std::uintmax_t>; // NOLINT(google-runtime-int)\n    using float_types    = std::tuple<float, double, long double>;\n    #endif\n\n    constexpr uintwide_t_backend() : m_value() { }\n\n    explicit constexpr uintwide_t_backend(const representation_type& rep)\n      : m_value(std::move(rep)) { }\n\n    constexpr uintwide_t_backend(const uintwide_t_backend& other) : m_value(other.m_value) { }\n\n    constexpr uintwide_t_backend(uintwide_t_backend&& other) noexcept\n      : m_value(static_cast<representation_type&&>(other.m_value)) { }\n\n    template<typename UnsignedIntegralType,\n             std::enable_if_t<(   (std::is_integral<UnsignedIntegralType>::value)\n                               && (std::is_unsigned<UnsignedIntegralType>::value))> const* = nullptr>\n    constexpr uintwide_t_backend(UnsignedIntegralType u) : m_value(representation_type(std::uint64_t(u))) { } // NOLINT(google-explicit-constructor,hicpp-explicit-conversions)\n\n    template<typename SignedIntegralType,\n             std::enable_if_t<(   (std::is_integral<SignedIntegralType>::value)\n                               && (std::is_signed  <SignedIntegralType>::value))> const* = nullptr>\n    constexpr uintwide_t_backend(SignedIntegralType n) : m_value(representation_type(std::int64_t(n))) { } // NOLINT(google-explicit-constructor,hicpp-explicit-conversions)\n\n    template<typename FloatingPointType,\n             std::enable_if_t<std::is_floating_point<FloatingPointType>::value> const* = nullptr>\n    constexpr uintwide_t_backend(FloatingPointType f) : m_value(representation_type(static_cast<long double>(f))) { } // NOLINT(google-explicit-constructor,hicpp-explicit-conversions)\n\n    constexpr uintwide_t_backend(const char* c) : m_value(c) { } // NOLINT(google-explicit-constructor,hicpp-explicit-conversions)\n\n    constexpr uintwide_t_backend(const std::string& str) : m_value(str) { } // NOLINT(google-explicit-constructor,hicpp-explicit-conversions)\n\n    WIDE_INTEGER_CONSTEXPR ~uintwide_t_backend() = default;\n\n    WIDE_INTEGER_CONSTEXPR auto operator=(const uintwide_t_backend& other) -> uintwide_t_backend& // NOLINT(cert-oop54-cpp)\n    {\n      if(this != &other)\n      {\n        m_value.representation() = other.m_value.crepresentation();\n      }\n\n      return *this;\n    }\n\n    WIDE_INTEGER_CONSTEXPR auto operator=(uintwide_t_backend&& other) noexcept -> uintwide_t_backend&\n    {\n      m_value = static_cast<representation_type&&>(other.m_value);\n\n      return *this;\n    }\n\n    template<typename ArithmeticType,\n             std::enable_if_t<std::is_arithmetic<ArithmeticType>::value> const* = nullptr>\n    WIDE_INTEGER_CONSTEXPR auto operator=(const ArithmeticType& x) -> uintwide_t_backend&\n    {\n      m_value = representation_type(x);\n\n      return *this;\n    }\n\n    WIDE_INTEGER_CONSTEXPR auto operator=(const std::string& str_rep)  -> uintwide_t_backend& { m_value = representation_type(str_rep);  return *this; }\n    WIDE_INTEGER_CONSTEXPR auto operator=(const char*        char_ptr) -> uintwide_t_backend& { m_value = representation_type(char_ptr); return *this; }\n\n    WIDE_INTEGER_CONSTEXPR auto swap(uintwide_t_backend& other) -> void\n    {\n      m_value.representation().swap(other.m_value.representation());\n    }\n\n    WIDE_INTEGER_CONSTEXPR auto swap(uintwide_t_backend&& other) noexcept -> void\n    {\n      auto tmp = std::move(m_value.representation());\n\n      m_value.representation() = std::move(other.m_value.representation());\n\n      other.m_value.representation() = std::move(tmp);\n    }\n\n                           WIDE_INTEGER_CONSTEXPR auto  representation()       ->       representation_type& { return m_value; }\n    WIDE_INTEGER_NODISCARD WIDE_INTEGER_CONSTEXPR auto  representation() const -> const representation_type& { return m_value; }\n    WIDE_INTEGER_NODISCARD WIDE_INTEGER_CONSTEXPR auto crepresentation() const -> const representation_type& { return m_value; }\n\n    WIDE_INTEGER_NODISCARD auto str(std::streamsize number_of_digits, const std::ios::fmtflags format_flags) const -> std::string\n    {\n      static_cast<void>(number_of_digits);\n\n      // Use simple vector dynamic memory here. When using uintwide_t as a\n      // Boost.Multiprecision number backend, we assume vector is available.\n\n      std::vector<char>\n        pstr\n        (\n          static_cast<typename std::vector<char>::size_type>(representation_type::wr_string_max_buffer_size_dec)\n        );\n\n      const std::uint_fast8_t base_rep     = (((format_flags & std::ios::hex)       != 0) ? 16U : 10U);\n      const bool              show_base    = ( (format_flags & std::ios::showbase)  != 0);\n      const bool              show_pos     = ( (format_flags & std::ios::showpos)   != 0);\n      const bool              is_uppercase = ( (format_flags & std::ios::uppercase) != 0);\n\n      const bool wr_string_is_ok = m_value.wr_string(pstr.data(), base_rep, show_base, show_pos, is_uppercase);\n\n      std::string str_result = (wr_string_is_ok ? std::string(pstr.data()) : std::string());\n\n      return str_result;\n    }\n\n    WIDE_INTEGER_CONSTEXPR auto negate() -> void\n    {\n      m_value.negate();\n    }\n\n    WIDE_INTEGER_NODISCARD constexpr auto compare(const uintwide_t_backend& other_mp_cpp_backend) const -> int\n    {\n      return static_cast<int>(m_value.compare(other_mp_cpp_backend.crepresentation()));\n    }\n\n    template<typename ArithmeticType,\n             std::enable_if_t<std::is_arithmetic<ArithmeticType>::value> const* = nullptr>\n    WIDE_INTEGER_NODISCARD constexpr auto compare(ArithmeticType x) const -> int\n    {\n      return static_cast<int>(m_value.compare(representation_type(x)));\n    }\n\n    WIDE_INTEGER_NODISCARD WIDE_INTEGER_CONSTEXPR auto hash() const -> std::size_t\n    {\n      auto result = static_cast<std::size_t>(0U);\n\n      #if (BOOST_VERSION < 107800)\n      using boost::hash_combine;\n      #else\n      using boost::multiprecision::detail::hash_combine;\n      #endif\n      for(auto   i = static_cast<typename representation_type::representation_type::size_type>(0U);\n                 i < crepresentation().crepresentation().size();\n               ++i)\n      {\n        hash_combine(result, crepresentation().crepresentation()[i]);\n      }\n\n      return result;\n    }\n\n    auto operator=(const representation_type&) -> uintwide_t_backend& = delete;\n\n  private:\n    representation_type m_value; // NOLINT(readability-identifier-naming)\n  };\n\n  template<\n  #if defined(WIDE_INTEGER_NAMESPACE)\n           const WIDE_INTEGER_NAMESPACE::math::wide_integer::size_t MyWidth2,\n  #else\n           const ::math::wide_integer::size_t MyWidth2,\n  #endif\n           typename MyLimbType,\n           typename MyAllocatorType>\n  WIDE_INTEGER_CONSTEXPR auto eval_add(uintwide_t_backend<MyWidth2, MyLimbType, MyAllocatorType>& result, const uintwide_t_backend<MyWidth2, MyLimbType, MyAllocatorType>& x) -> void\n  {\n    result.representation() += x.crepresentation();\n  }\n\n  template<\n  #if defined(WIDE_INTEGER_NAMESPACE)\n           const WIDE_INTEGER_NAMESPACE::math::wide_integer::size_t MyWidth2,\n  #else\n           const ::math::wide_integer::size_t MyWidth2,\n  #endif\n           typename MyLimbType,\n           typename MyAllocatorType>\n  WIDE_INTEGER_CONSTEXPR auto eval_subtract(uintwide_t_backend<MyWidth2, MyLimbType, MyAllocatorType>& result, const uintwide_t_backend<MyWidth2, MyLimbType, MyAllocatorType>& x) -> void\n  {\n    result.representation() -= x.crepresentation();\n  }\n\n  template<\n  #if defined(WIDE_INTEGER_NAMESPACE)\n           const WIDE_INTEGER_NAMESPACE::math::wide_integer::size_t MyWidth2,\n  #else\n           const ::math::wide_integer::size_t MyWidth2,\n  #endif\n           typename MyLimbType,\n           typename MyAllocatorType>\n  WIDE_INTEGER_CONSTEXPR auto eval_multiply(uintwide_t_backend<MyWidth2, MyLimbType, MyAllocatorType>& result, const uintwide_t_backend<MyWidth2, MyLimbType, MyAllocatorType>& x) -> void\n  {\n    result.representation() *= x.crepresentation();\n  }\n\n  template<\n  #if defined(WIDE_INTEGER_NAMESPACE)\n           const WIDE_INTEGER_NAMESPACE::math::wide_integer::size_t MyWidth2,\n  #else\n           const ::math::wide_integer::size_t MyWidth2,\n  #endif\n           typename MyLimbType,\n           typename MyAllocatorType,\n           typename IntegralType,\n           std::enable_if_t<(std::is_integral<IntegralType>::value)> const* = nullptr>\n  WIDE_INTEGER_CONSTEXPR auto eval_multiply(uintwide_t_backend<MyWidth2, MyLimbType, MyAllocatorType>& result, const IntegralType& n) -> void\n  {\n    result.representation() *= n;\n  }\n\n  template<\n  #if defined(WIDE_INTEGER_NAMESPACE)\n           const WIDE_INTEGER_NAMESPACE::math::wide_integer::size_t MyWidth2,\n  #else\n           const ::math::wide_integer::size_t MyWidth2,\n  #endif\n           typename MyLimbType,\n           typename MyAllocatorType>\n  WIDE_INTEGER_CONSTEXPR auto eval_divide(uintwide_t_backend<MyWidth2, MyLimbType, MyAllocatorType>& result, const uintwide_t_backend<MyWidth2, MyLimbType, MyAllocatorType>& x) -> void\n  {\n    result.representation() /= x.crepresentation();\n  }\n\n  template<\n  #if defined(WIDE_INTEGER_NAMESPACE)\n           const WIDE_INTEGER_NAMESPACE::math::wide_integer::size_t MyWidth2,\n  #else\n           const ::math::wide_integer::size_t MyWidth2,\n  #endif\n           typename MyLimbType,\n           typename MyAllocatorType,\n           typename IntegralType,\n           std::enable_if_t<(   (std::is_integral   <IntegralType>::value)\n                             && (std::is_unsigned   <IntegralType>::value)\n                             && (std::numeric_limits<IntegralType>::digits <= std::numeric_limits<MyLimbType>::digits))> const* = nullptr>\n  WIDE_INTEGER_CONSTEXPR auto eval_divide(uintwide_t_backend<MyWidth2, MyLimbType, MyAllocatorType>& result, const IntegralType& n) -> void\n  {\n    using local_wide_integer_type = typename uintwide_t_backend<MyWidth2, MyLimbType, MyAllocatorType>::representation_type;\n\n    using local_limb_type = typename local_wide_integer_type::limb_type;\n\n    result.representation().eval_divide_by_single_limb(static_cast<local_limb_type>(n), 0U, nullptr);\n  }\n\n  template<\n  #if defined(WIDE_INTEGER_NAMESPACE)\n           const WIDE_INTEGER_NAMESPACE::math::wide_integer::size_t MyWidth2,\n  #else\n           const ::math::wide_integer::size_t MyWidth2,\n  #endif\n           typename MyLimbType,\n           typename MyAllocatorType,\n           typename IntegralType,\n           std::enable_if_t<(   (std::is_integral   <IntegralType>::value)\n                             && (std::is_unsigned   <IntegralType>::value)\n                             && (std::numeric_limits<IntegralType>::digits) > std::numeric_limits<MyLimbType>::digits)> const* = nullptr>\n  WIDE_INTEGER_CONSTEXPR auto eval_divide(uintwide_t_backend<MyWidth2, MyLimbType, MyAllocatorType>& result, const IntegralType& n) -> void\n  {\n    result.representation() /= n;\n  }\n\n  template<\n  #if defined(WIDE_INTEGER_NAMESPACE)\n           const WIDE_INTEGER_NAMESPACE::math::wide_integer::size_t MyWidth2,\n  #else\n           const ::math::wide_integer::size_t MyWidth2,\n  #endif\n           typename MyLimbType,\n           typename MyAllocatorType>\n  WIDE_INTEGER_CONSTEXPR auto eval_modulus(uintwide_t_backend<MyWidth2, MyLimbType, MyAllocatorType>& result, const uintwide_t_backend<MyWidth2, MyLimbType, MyAllocatorType>& x) -> void\n  {\n    result.representation() %= x.crepresentation();\n  }\n\n  template<\n  #if defined(WIDE_INTEGER_NAMESPACE)\n           const WIDE_INTEGER_NAMESPACE::math::wide_integer::size_t MyWidth2,\n  #else\n           const ::math::wide_integer::size_t MyWidth2,\n  #endif\n           typename MyLimbType,\n           typename MyAllocatorType,\n           typename IntegralType,\n           std::enable_if_t<(   (std::is_integral   <IntegralType>::value)\n                             && (std::is_unsigned   <IntegralType>::value)\n                             && (std::numeric_limits<IntegralType>::digits <= std::numeric_limits<MyLimbType>::digits))> const* = nullptr>\n  WIDE_INTEGER_CONSTEXPR auto eval_integer_modulus(uintwide_t_backend<MyWidth2, MyLimbType, MyAllocatorType>& x, const IntegralType& n) -> IntegralType\n  {\n    using local_wide_integer_type = typename uintwide_t_backend<MyWidth2, MyLimbType, MyAllocatorType>::representation_type;\n\n    typename uintwide_t_backend<MyWidth2, MyLimbType, MyAllocatorType>::representation_type rem;\n\n    local_wide_integer_type(x.crepresentation()).eval_divide_by_single_limb(n, 0U, &rem);\n\n    return static_cast<IntegralType>(rem);\n  }\n\n  template<\n  #if defined(WIDE_INTEGER_NAMESPACE)\n           const WIDE_INTEGER_NAMESPACE::math::wide_integer::size_t MyWidth2,\n  #else\n           const ::math::wide_integer::size_t MyWidth2,\n  #endif\n           typename MyLimbType,\n           typename MyAllocatorType,\n           typename IntegralType,\n           std::enable_if_t<(   (std::is_integral   <IntegralType>::value)\n                             && (std::is_unsigned   <IntegralType>::value)\n                             && (std::numeric_limits<IntegralType>::digits) > std::numeric_limits<MyLimbType>::digits)> const* = nullptr>\n  WIDE_INTEGER_CONSTEXPR auto eval_integer_modulus(uintwide_t_backend<MyWidth2, MyLimbType, MyAllocatorType>& x, const IntegralType& n) -> IntegralType\n  {\n    const uintwide_t_backend<MyWidth2, MyLimbType, MyAllocatorType> rem = x.crepresentation() % uintwide_t_backend<MyWidth2, MyLimbType, MyAllocatorType>(n);\n\n    return static_cast<IntegralType>(rem);\n  }\n\n  template<\n  #if defined(WIDE_INTEGER_NAMESPACE)\n           const WIDE_INTEGER_NAMESPACE::math::wide_integer::size_t MyWidth2,\n  #else\n           const ::math::wide_integer::size_t MyWidth2,\n  #endif\n           typename MyLimbType,\n           typename MyAllocatorType>\n  WIDE_INTEGER_CONSTEXPR auto eval_bitwise_and(uintwide_t_backend<MyWidth2, MyLimbType, MyAllocatorType>& result, const uintwide_t_backend<MyWidth2, MyLimbType, MyAllocatorType>& x) -> void\n  {\n    result.representation() &= x.crepresentation();\n  }\n\n  template<\n  #if defined(WIDE_INTEGER_NAMESPACE)\n           const WIDE_INTEGER_NAMESPACE::math::wide_integer::size_t MyWidth2,\n  #else\n           const ::math::wide_integer::size_t MyWidth2,\n  #endif\n           typename MyLimbType,\n           typename MyAllocatorType>\n  WIDE_INTEGER_CONSTEXPR auto eval_bitwise_or(      uintwide_t_backend<MyWidth2, MyLimbType, MyAllocatorType>& result,\n                                              const uintwide_t_backend<MyWidth2, MyLimbType, MyAllocatorType>& x) -> void\n  {\n    result.representation() |= x.crepresentation();\n  }\n\n  template<\n  #if defined(WIDE_INTEGER_NAMESPACE)\n           const WIDE_INTEGER_NAMESPACE::math::wide_integer::size_t MyWidth2,\n  #else\n           const ::math::wide_integer::size_t MyWidth2,\n  #endif\n           typename MyLimbType,\n           typename MyAllocatorType>\n  WIDE_INTEGER_CONSTEXPR auto eval_bitwise_xor(uintwide_t_backend<MyWidth2, MyLimbType, MyAllocatorType>& result, const uintwide_t_backend<MyWidth2, MyLimbType, MyAllocatorType>& x) -> void\n  {\n    result.representation() ^= x.crepresentation();\n  }\n\n  template<\n  #if defined(WIDE_INTEGER_NAMESPACE)\n           const WIDE_INTEGER_NAMESPACE::math::wide_integer::size_t MyWidth2,\n  #else\n           const ::math::wide_integer::size_t MyWidth2,\n  #endif\n           typename MyLimbType,\n           typename MyAllocatorType>\n  WIDE_INTEGER_CONSTEXPR auto eval_complement(      uintwide_t_backend<MyWidth2, MyLimbType, MyAllocatorType>& result,\n                                              const uintwide_t_backend<MyWidth2, MyLimbType, MyAllocatorType>& x) -> void\n  {\n    using local_limb_array_type =\n      typename uintwide_t_backend<MyWidth2, MyLimbType, MyAllocatorType>::representation_type::representation_type;\n\n    using local_size_type = typename local_limb_array_type::size_type;\n\n    for(auto   i = static_cast<local_size_type>(0U);\n               i < result.crepresentation().crepresentation().size();\n             ++i)\n    {\n      using local_value_type = typename local_limb_array_type::value_type;\n\n      result.representation().representation()[i] =\n        static_cast<local_value_type>\n        (\n          ~x.crepresentation().crepresentation()[i]\n        );\n    }\n  }\n\n  template<\n  #if defined(WIDE_INTEGER_NAMESPACE)\n           const WIDE_INTEGER_NAMESPACE::math::wide_integer::size_t MyWidth2,\n  #else\n           const ::math::wide_integer::size_t MyWidth2,\n  #endif\n           typename MyLimbType,\n           typename MyAllocatorType>\n  WIDE_INTEGER_CONSTEXPR auto eval_powm(      uintwide_t_backend<MyWidth2, MyLimbType, MyAllocatorType>& result,\n                                        const uintwide_t_backend<MyWidth2, MyLimbType, MyAllocatorType>& b,\n                                        const uintwide_t_backend<MyWidth2, MyLimbType, MyAllocatorType>& p,\n                                        const uintwide_t_backend<MyWidth2, MyLimbType, MyAllocatorType>& m) -> void\n  {\n    result.representation() = powm(b.crepresentation(),\n                                   p.crepresentation(),\n                                   m.crepresentation());\n  }\n\n  template<\n  #if defined(WIDE_INTEGER_NAMESPACE)\n           const WIDE_INTEGER_NAMESPACE::math::wide_integer::size_t MyWidth2,\n  #else\n           const ::math::wide_integer::size_t MyWidth2,\n  #endif\n           typename MyLimbType,\n           typename MyAllocatorType,\n           typename OtherIntegralTypeM,\n           std::enable_if_t<(std::is_integral<OtherIntegralTypeM>::value)> const* = nullptr>\n  WIDE_INTEGER_CONSTEXPR auto eval_powm(      uintwide_t_backend<MyWidth2, MyLimbType, MyAllocatorType>& result,\n                                        const uintwide_t_backend<MyWidth2, MyLimbType, MyAllocatorType>& b,\n                                        const uintwide_t_backend<MyWidth2, MyLimbType, MyAllocatorType>& p,\n                                        const OtherIntegralTypeM                                         m) -> void\n  {\n    result.representation() = powm(b.crepresentation(),\n                                   p.crepresentation(),\n                                   m);\n  }\n\n  template<\n  #if defined(WIDE_INTEGER_NAMESPACE)\n           const WIDE_INTEGER_NAMESPACE::math::wide_integer::size_t MyWidth2,\n  #else\n           const ::math::wide_integer::size_t MyWidth2,\n  #endif\n           typename MyLimbType,\n           typename MyAllocatorType,\n           typename OtherIntegralTypeP,\n           std::enable_if_t<(std::is_integral<OtherIntegralTypeP>::value)> const* = nullptr>\n  WIDE_INTEGER_CONSTEXPR auto eval_powm(      uintwide_t_backend<MyWidth2, MyLimbType, MyAllocatorType>& result,\n                                        const uintwide_t_backend<MyWidth2, MyLimbType, MyAllocatorType>& b,\n                                        const OtherIntegralTypeP                                         p,\n                                        const uintwide_t_backend<MyWidth2, MyLimbType, MyAllocatorType>& m) -> void\n  {\n    result.representation() = powm(b.crepresentation(),\n                                   p,\n                                   m.crepresentation());\n  }\n\n  template<\n  #if defined(WIDE_INTEGER_NAMESPACE)\n           const WIDE_INTEGER_NAMESPACE::math::wide_integer::size_t MyWidth2,\n  #else\n           const ::math::wide_integer::size_t MyWidth2,\n  #endif\n           typename MyLimbType,\n           typename MyAllocatorType,\n           typename IntegralType,\n           std::enable_if_t<(std::is_integral<IntegralType>::value)> const* = nullptr>\n  WIDE_INTEGER_CONSTEXPR auto eval_left_shift(uintwide_t_backend<MyWidth2, MyLimbType, MyAllocatorType>& result, const IntegralType& n) -> void\n  {\n    result.representation() <<= n;\n  }\n\n  template<\n  #if defined(WIDE_INTEGER_NAMESPACE)\n           const WIDE_INTEGER_NAMESPACE::math::wide_integer::size_t MyWidth2,\n  #else\n           const ::math::wide_integer::size_t MyWidth2,\n  #endif\n           typename MyLimbType,\n           typename MyAllocatorType,\n           typename IntegralType,\n           std::enable_if_t<(std::is_integral<IntegralType>::value)> const* = nullptr>\n  WIDE_INTEGER_CONSTEXPR auto eval_right_shift(uintwide_t_backend<MyWidth2, MyLimbType, MyAllocatorType>& result, const IntegralType& n) -> void\n  {\n    result.representation() >>= n;\n  }\n\n  template<\n  #if defined(WIDE_INTEGER_NAMESPACE)\n           const WIDE_INTEGER_NAMESPACE::math::wide_integer::size_t MyWidth2,\n  #else\n           const ::math::wide_integer::size_t MyWidth2,\n  #endif\n           typename MyLimbType,\n           typename MyAllocatorType>\n  constexpr auto eval_lsb(const uintwide_t_backend<MyWidth2, MyLimbType, MyAllocatorType>& a) -> unsigned\n  {\n    return static_cast<unsigned>(lsb(a.crepresentation()));\n  }\n\n  template<\n  #if defined(WIDE_INTEGER_NAMESPACE)\n           const WIDE_INTEGER_NAMESPACE::math::wide_integer::size_t MyWidth2,\n  #else\n           const ::math::wide_integer::size_t MyWidth2,\n  #endif\n           typename MyLimbType,\n           typename MyAllocatorType>\n  constexpr auto eval_msb(const uintwide_t_backend<MyWidth2, MyLimbType, MyAllocatorType>& a) -> unsigned\n  {\n    return static_cast<unsigned>(msb(a.crepresentation()));\n  }\n\n  template<\n  #if defined(WIDE_INTEGER_NAMESPACE)\n           const WIDE_INTEGER_NAMESPACE::math::wide_integer::size_t MyWidth2,\n  #else\n           const ::math::wide_integer::size_t MyWidth2,\n  #endif\n           typename MyLimbType,\n           typename MyAllocatorType>\n  constexpr auto eval_eq(const uintwide_t_backend<MyWidth2, MyLimbType, MyAllocatorType>& a,\n                         const uintwide_t_backend<MyWidth2, MyLimbType, MyAllocatorType>& b) -> bool\n  {\n    return (a.compare(b) == 0);\n  }\n\n  template<\n  #if defined(WIDE_INTEGER_NAMESPACE)\n           const WIDE_INTEGER_NAMESPACE::math::wide_integer::size_t MyWidth2,\n  #else\n           const ::math::wide_integer::size_t MyWidth2,\n  #endif\n           typename MyLimbType,\n           typename MyAllocatorType,\n           typename ArithmeticType,\n           std::enable_if_t<(std::is_arithmetic <ArithmeticType>::value)> const* = nullptr>\n  constexpr auto eval_eq(const uintwide_t_backend<MyWidth2, MyLimbType, MyAllocatorType>& a,\n                               ArithmeticType                                             b) -> bool\n  {\n    return (a.compare(b) == 0);\n  }\n\n  template<\n  #if defined(WIDE_INTEGER_NAMESPACE)\n           const WIDE_INTEGER_NAMESPACE::math::wide_integer::size_t MyWidth2,\n  #else\n           const ::math::wide_integer::size_t MyWidth2,\n  #endif\n           typename MyLimbType,\n           typename MyAllocatorType,\n           typename ArithmeticType,\n           std::enable_if_t<(std::is_arithmetic <ArithmeticType>::value)> const* = nullptr>\n  constexpr auto eval_eq(      ArithmeticType                                             a,\n                         const uintwide_t_backend<MyWidth2, MyLimbType, MyAllocatorType>& b) -> bool\n  {\n    return (uintwide_t_backend<MyWidth2, MyLimbType, MyAllocatorType>(a).compare(b) == 0);\n  }\n\n  template<\n  #if defined(WIDE_INTEGER_NAMESPACE)\n           const WIDE_INTEGER_NAMESPACE::math::wide_integer::size_t MyWidth2,\n  #else\n           const ::math::wide_integer::size_t MyWidth2,\n  #endif\n           typename MyLimbType,\n           typename MyAllocatorType>\n  constexpr auto eval_gt(const uintwide_t_backend<MyWidth2, MyLimbType, MyAllocatorType>& a,\n                         const uintwide_t_backend<MyWidth2, MyLimbType, MyAllocatorType>& b) -> bool\n  {\n    return (a.compare(b) == 1);\n  }\n\n  template<\n  #if defined(WIDE_INTEGER_NAMESPACE)\n           const WIDE_INTEGER_NAMESPACE::math::wide_integer::size_t MyWidth2,\n  #else\n           const ::math::wide_integer::size_t MyWidth2,\n  #endif\n           typename MyLimbType,\n           typename MyAllocatorType,\n           typename ArithmeticType,\n           std::enable_if_t<(std::is_arithmetic <ArithmeticType>::value)> const* = nullptr>\n  constexpr auto eval_gt(const uintwide_t_backend<MyWidth2, MyLimbType, MyAllocatorType>& a,\n                               ArithmeticType                                             b) -> bool\n  {\n    return (a.compare(b) == 1);\n  }\n\n  template<\n  #if defined(WIDE_INTEGER_NAMESPACE)\n           const WIDE_INTEGER_NAMESPACE::math::wide_integer::size_t MyWidth2,\n  #else\n           const ::math::wide_integer::size_t MyWidth2,\n  #endif\n           typename MyLimbType,\n           typename MyAllocatorType,\n           typename ArithmeticType,\n           std::enable_if_t<(std::is_arithmetic <ArithmeticType>::value)> const* = nullptr>\n  constexpr auto eval_gt(      ArithmeticType                                             a,\n                         const uintwide_t_backend<MyWidth2, MyLimbType, MyAllocatorType>& b) -> bool\n  {\n    return (uintwide_t_backend<MyWidth2, MyLimbType, MyAllocatorType>(a).compare(b) == 1);\n  }\n\n  template<\n  #if defined(WIDE_INTEGER_NAMESPACE)\n           const WIDE_INTEGER_NAMESPACE::math::wide_integer::size_t MyWidth2,\n  #else\n           const ::math::wide_integer::size_t MyWidth2,\n  #endif\n           typename MyLimbType,\n           typename MyAllocatorType>\n  constexpr auto eval_lt(const uintwide_t_backend<MyWidth2, MyLimbType, MyAllocatorType>& a,\n                         const uintwide_t_backend<MyWidth2, MyLimbType, MyAllocatorType>& b) -> bool\n  {\n    return (a.compare(b) == -1);\n  }\n\n  template<\n  #if defined(WIDE_INTEGER_NAMESPACE)\n           const WIDE_INTEGER_NAMESPACE::math::wide_integer::size_t MyWidth2,\n  #else\n           const ::math::wide_integer::size_t MyWidth2,\n  #endif\n           typename MyLimbType,\n           typename MyAllocatorType,\n           typename ArithmeticType,\n           std::enable_if_t<(std::is_arithmetic <ArithmeticType>::value)> const* = nullptr>\n  constexpr auto eval_lt(const uintwide_t_backend<MyWidth2, MyLimbType, MyAllocatorType>& a,\n                               ArithmeticType                                             b) -> bool\n  {\n    return (a.compare(b) == -1);\n  }\n\n  template<\n  #if defined(WIDE_INTEGER_NAMESPACE)\n           const WIDE_INTEGER_NAMESPACE::math::wide_integer::size_t MyWidth2,\n  #else\n           const ::math::wide_integer::size_t MyWidth2,\n  #endif\n           typename MyLimbType,\n           typename MyAllocatorType,\n           typename ArithmeticType,\n           std::enable_if_t<(std::is_arithmetic <ArithmeticType>::value)> const* = nullptr>\n  constexpr auto eval_lt(      ArithmeticType                                             a,\n                         const uintwide_t_backend<MyWidth2, MyLimbType, MyAllocatorType>& b) -> bool\n  {\n    return (uintwide_t_backend<MyWidth2, MyLimbType, MyAllocatorType>(a).compare(b) == -1);\n  }\n\n  template<\n  #if defined(WIDE_INTEGER_NAMESPACE)\n           const WIDE_INTEGER_NAMESPACE::math::wide_integer::size_t MyWidth2,\n  #else\n           const ::math::wide_integer::size_t MyWidth2,\n  #endif\n           typename MyLimbType,\n           typename MyAllocatorType>\n  constexpr auto eval_is_zero(const uintwide_t_backend<MyWidth2, MyLimbType, MyAllocatorType>& x) -> bool\n  {\n    return (x.crepresentation().is_zero());\n  }\n\n  template<\n  #if defined(WIDE_INTEGER_NAMESPACE)\n           const WIDE_INTEGER_NAMESPACE::math::wide_integer::size_t MyWidth2,\n  #else\n           const ::math::wide_integer::size_t MyWidth2,\n  #endif\n           typename MyLimbType,\n           typename MyAllocatorType>\n  constexpr auto eval_get_sign(const uintwide_t_backend<MyWidth2, MyLimbType, MyAllocatorType>& x) -> int\n  {\n    return (eval_is_zero(x) ? 0 : 1);\n  }\n\n  template<typename UnsignedIntegralType,\n  #if defined(WIDE_INTEGER_NAMESPACE)\n           const WIDE_INTEGER_NAMESPACE::math::wide_integer::size_t MyWidth2,\n  #else\n           const ::math::wide_integer::size_t MyWidth2,\n  #endif\n           typename MyLimbType,\n           typename MyAllocatorType>\n  WIDE_INTEGER_CONSTEXPR auto eval_convert_to\n  (\n          UnsignedIntegralType*                                                                 result,\n    const uintwide_t_backend<MyWidth2, MyLimbType, MyAllocatorType>&                            val,\n          std::enable_if_t<(    (std::is_integral<UnsignedIntegralType>::value)\n                            && (!std::is_signed  <UnsignedIntegralType>::value))>* p_nullparam = nullptr\n  ) -> void\n  {\n    static_cast<void>(p_nullparam);\n\n    using local_unsigned_integral_type = UnsignedIntegralType;\n\n    static_assert((!std::is_signed<local_unsigned_integral_type>::value),\n                  \"Error: Wrong signed instantiation (destination type should be unsigned).\");\n\n    *result = static_cast<local_unsigned_integral_type>(val.crepresentation());\n  }\n\n  template<typename SignedIntegralType,\n  #if defined(WIDE_INTEGER_NAMESPACE)\n           const WIDE_INTEGER_NAMESPACE::math::wide_integer::size_t MyWidth2,\n  #else\n           const ::math::wide_integer::size_t MyWidth2,\n  #endif\n           typename MyLimbType,\n           typename MyAllocatorType>\n  WIDE_INTEGER_CONSTEXPR auto eval_convert_to\n  (\n          SignedIntegralType*                                                                result,\n    const uintwide_t_backend<MyWidth2, MyLimbType, MyAllocatorType>&                         val,\n          std::enable_if_t<(   (std::is_integral<SignedIntegralType>::value)\n                            && (std::is_signed  <SignedIntegralType>::value))>* p_nullparam = nullptr\n  ) -> void\n  {\n    static_cast<void>(p_nullparam);\n\n    using local_signed_integral_type = SignedIntegralType;\n\n    static_assert(std::is_signed<local_signed_integral_type>::value,\n                  \"Error: Wrong unsigned instantiation (destination type should be signed).\");\n\n    *result = static_cast<local_signed_integral_type>(val.crepresentation());\n  }\n\n  template<\n  #if defined(WIDE_INTEGER_NAMESPACE)\n           const WIDE_INTEGER_NAMESPACE::math::wide_integer::size_t MyWidth2,\n  #else\n           const ::math::wide_integer::size_t MyWidth2,\n  #endif\n           typename MyLimbType,\n           typename MyAllocatorType>\n  WIDE_INTEGER_CONSTEXPR auto eval_convert_to(long double* result,\n                                              const uintwide_t_backend<MyWidth2, MyLimbType, MyAllocatorType>& val) -> void\n  {\n    *result = static_cast<long double>(val.crepresentation());\n  }\n\n  template<\n  #if defined(WIDE_INTEGER_NAMESPACE)\n           const WIDE_INTEGER_NAMESPACE::math::wide_integer::size_t MyWidth2,\n  #else\n           const ::math::wide_integer::size_t MyWidth2,\n  #endif\n           typename MyLimbType,\n           typename MyAllocatorType>\n  constexpr auto hash_value(const uintwide_t_backend<MyWidth2, MyLimbType, MyAllocatorType>& val) -> std::size_t\n  {\n    return val.hash();\n  }\n\n  #if(__cplusplus >= 201703L)\n  } // namespace boost::multiprecision\n  #else\n  } // namespace multiprecision\n  } // namespace boost\n  #endif\n\n  #if (BOOST_VERSION < 107900)\n\n  #if(__cplusplus >= 201703L)\n  namespace boost::math::policies {\n  #else\n  namespace boost { namespace math { namespace policies { // NOLINT(modernize-concat-nested-namespaces)\n  #endif\n\n  // Specialization of the precision structure.\n  template<\n  #if defined(WIDE_INTEGER_NAMESPACE)\n           const WIDE_INTEGER_NAMESPACE::math::wide_integer::size_t MyWidth2,\n  #else\n           const ::math::wide_integer::size_t MyWidth2,\n  #endif\n           typename MyLimbType,\n           typename MyAllocatorType,\n           typename ThisPolicy,\n           const boost::multiprecision::expression_template_option ExpressionTemplatesOptions>\n  struct precision<boost::multiprecision::number<boost::multiprecision::uintwide_t_backend<MyWidth2, MyLimbType, MyAllocatorType>,\n                                                 ExpressionTemplatesOptions>,\n                   ThisPolicy>\n  {\n    using precision_type = typename ThisPolicy::precision_type;\n\n    using local_digits_2 = digits2<MyWidth2>;\n\n    #if (BOOST_VERSION <= 107500)\n    using type = typename mpl::if_c       <((local_digits_2::value <= precision_type::value) || (precision_type::value <= 0)),\n                                             local_digits_2,\n                                             precision_type>::type;\n    #else\n    using type = typename std::conditional<((local_digits_2::value <= precision_type::value) || (precision_type::value <= 0)),\n                                             local_digits_2,\n                                             precision_type>::type;\n    #endif\n  };\n\n  #if(__cplusplus >= 201703L)\n  } // namespace boost::math::policies\n  #else\n  } // namespace policies\n  } // namespace math\n  } // namespace boost\n  #endif\n\n  #endif\n\n  namespace std // NOLINT(cert-dcl58-cpp)\n  {\n    template<\n    #if defined(WIDE_INTEGER_NAMESPACE)\n             const WIDE_INTEGER_NAMESPACE::math::wide_integer::size_t MyWidth2,\n    #else\n             const ::math::wide_integer::size_t MyWidth2,\n    #endif\n             typename MyLimbType,\n             typename MyAllocatorType,\n             const boost::multiprecision::expression_template_option ExpressionTemplatesOptions>\n    class numeric_limits<boost::multiprecision::number<boost::multiprecision::uintwide_t_backend<MyWidth2, MyLimbType, MyAllocatorType>,\n                                                       ExpressionTemplatesOptions>>\n    {\n    public:\n      static constexpr bool is_specialized = true;\n      static constexpr bool is_signed      = false;\n      static constexpr bool is_integer     = true;\n      static constexpr bool is_exact       = true;\n      static constexpr bool is_bounded     = true;\n      static constexpr bool is_modulo      = false;\n      static constexpr bool is_iec559      = false;\n      static constexpr int  digits         = MyWidth2;\n      static constexpr int  digits10       = static_cast<int>((MyWidth2 * 301LL) / 1000LL);\n      static constexpr int  max_digits10   = static_cast<int>((MyWidth2 * 301LL) / 1000LL);\n\n      #if defined(WIDE_INTEGER_NAMESPACE)\n      static constexpr int max_exponent    = std::numeric_limits<WIDE_INTEGER_NAMESPACE::math::wide_integer::uintwide_t<MyWidth2, MyLimbType, MyAllocatorType>>::max_exponent;\n      static constexpr int max_exponent10  = std::numeric_limits<WIDE_INTEGER_NAMESPACE::math::wide_integer::uintwide_t<MyWidth2, MyLimbType, MyAllocatorType>>::max_exponent10;\n      static constexpr int min_exponent    = std::numeric_limits<WIDE_INTEGER_NAMESPACE::math::wide_integer::uintwide_t<MyWidth2, MyLimbType, MyAllocatorType>>::min_exponent;\n      static constexpr int min_exponent10  = std::numeric_limits<WIDE_INTEGER_NAMESPACE::math::wide_integer::uintwide_t<MyWidth2, MyLimbType, MyAllocatorType>>::min_exponent10;\n      #else\n      static constexpr int max_exponent    = std::numeric_limits<::math::wide_integer::uintwide_t<MyWidth2, MyLimbType, MyAllocatorType>>::max_exponent;\n      static constexpr int max_exponent10  = std::numeric_limits<::math::wide_integer::uintwide_t<MyWidth2, MyLimbType, MyAllocatorType>>::max_exponent10;\n      static constexpr int min_exponent    = std::numeric_limits<::math::wide_integer::uintwide_t<MyWidth2, MyLimbType, MyAllocatorType>>::min_exponent;\n      static constexpr int min_exponent10  = std::numeric_limits<::math::wide_integer::uintwide_t<MyWidth2, MyLimbType, MyAllocatorType>>::min_exponent10;\n      #endif\n\n      static constexpr int                     radix             = 2;\n      static constexpr std::float_round_style  round_style       = std::round_to_nearest;\n      static constexpr bool                    has_infinity      = false;\n      static constexpr bool                    has_quiet_NaN     = false;\n      static constexpr bool                    has_signaling_NaN = false;\n      static constexpr std::float_denorm_style has_denorm        = std::denorm_absent;\n      static constexpr bool                    has_denorm_loss   = false;\n      static constexpr bool                    traps             = false;\n      static constexpr bool                    tinyness_before   = false;\n\n      #if defined(WIDE_INTEGER_NAMESPACE)\n      static WIDE_INTEGER_CONSTEXPR auto (min)        () -> boost::multiprecision::number<boost::multiprecision::uintwide_t_backend<MyWidth2, MyLimbType, MyAllocatorType>, ExpressionTemplatesOptions> { return boost::multiprecision::uintwide_t_backend<MyWidth2, MyLimbType, MyAllocatorType>((std::numeric_limits<WIDE_INTEGER_NAMESPACE::math::wide_integer::uintwide_t<MyWidth2, MyLimbType, MyAllocatorType>>::min)()       ); }\n      static WIDE_INTEGER_CONSTEXPR auto (max)        () -> boost::multiprecision::number<boost::multiprecision::uintwide_t_backend<MyWidth2, MyLimbType, MyAllocatorType>, ExpressionTemplatesOptions> { return boost::multiprecision::uintwide_t_backend<MyWidth2, MyLimbType, MyAllocatorType>((std::numeric_limits<WIDE_INTEGER_NAMESPACE::math::wide_integer::uintwide_t<MyWidth2, MyLimbType, MyAllocatorType>>::max)()       ); }\n      static WIDE_INTEGER_CONSTEXPR auto lowest       () -> boost::multiprecision::number<boost::multiprecision::uintwide_t_backend<MyWidth2, MyLimbType, MyAllocatorType>, ExpressionTemplatesOptions> { return boost::multiprecision::uintwide_t_backend<MyWidth2, MyLimbType, MyAllocatorType> (std::numeric_limits<WIDE_INTEGER_NAMESPACE::math::wide_integer::uintwide_t<MyWidth2, MyLimbType, MyAllocatorType>>::lowest       ); }\n      static WIDE_INTEGER_CONSTEXPR auto epsilon      () -> boost::multiprecision::number<boost::multiprecision::uintwide_t_backend<MyWidth2, MyLimbType, MyAllocatorType>, ExpressionTemplatesOptions> { return boost::multiprecision::uintwide_t_backend<MyWidth2, MyLimbType, MyAllocatorType> (std::numeric_limits<WIDE_INTEGER_NAMESPACE::math::wide_integer::uintwide_t<MyWidth2, MyLimbType, MyAllocatorType>>::epsilon      ); }\n      static WIDE_INTEGER_CONSTEXPR auto round_error  () -> boost::multiprecision::number<boost::multiprecision::uintwide_t_backend<MyWidth2, MyLimbType, MyAllocatorType>, ExpressionTemplatesOptions> { return boost::multiprecision::uintwide_t_backend<MyWidth2, MyLimbType, MyAllocatorType> (std::numeric_limits<WIDE_INTEGER_NAMESPACE::math::wide_integer::uintwide_t<MyWidth2, MyLimbType, MyAllocatorType>>::round_error  ); }\n      static WIDE_INTEGER_CONSTEXPR auto infinity     () -> boost::multiprecision::number<boost::multiprecision::uintwide_t_backend<MyWidth2, MyLimbType, MyAllocatorType>, ExpressionTemplatesOptions> { return boost::multiprecision::uintwide_t_backend<MyWidth2, MyLimbType, MyAllocatorType> (std::numeric_limits<WIDE_INTEGER_NAMESPACE::math::wide_integer::uintwide_t<MyWidth2, MyLimbType, MyAllocatorType>>::infinity     ); }\n      static WIDE_INTEGER_CONSTEXPR auto quiet_NaN    () -> boost::multiprecision::number<boost::multiprecision::uintwide_t_backend<MyWidth2, MyLimbType, MyAllocatorType>, ExpressionTemplatesOptions> { return boost::multiprecision::uintwide_t_backend<MyWidth2, MyLimbType, MyAllocatorType> (std::numeric_limits<WIDE_INTEGER_NAMESPACE::math::wide_integer::uintwide_t<MyWidth2, MyLimbType, MyAllocatorType>>::quiet_NaN    ); } // NOLINT(readability-identifier-naming)\n      static WIDE_INTEGER_CONSTEXPR auto signaling_NaN() -> boost::multiprecision::number<boost::multiprecision::uintwide_t_backend<MyWidth2, MyLimbType, MyAllocatorType>, ExpressionTemplatesOptions> { return boost::multiprecision::uintwide_t_backend<MyWidth2, MyLimbType, MyAllocatorType> (std::numeric_limits<WIDE_INTEGER_NAMESPACE::math::wide_integer::uintwide_t<MyWidth2, MyLimbType, MyAllocatorType>>::signaling_NaN); } // NOLINT(readability-identifier-naming)\n      static WIDE_INTEGER_CONSTEXPR auto denorm_min   () -> boost::multiprecision::number<boost::multiprecision::uintwide_t_backend<MyWidth2, MyLimbType, MyAllocatorType>, ExpressionTemplatesOptions> { return boost::multiprecision::uintwide_t_backend<MyWidth2, MyLimbType, MyAllocatorType> (std::numeric_limits<WIDE_INTEGER_NAMESPACE::math::wide_integer::uintwide_t<MyWidth2, MyLimbType, MyAllocatorType>>::denorm_min   ); }\n      #else\n      static WIDE_INTEGER_CONSTEXPR auto (min)        () -> boost::multiprecision::number<boost::multiprecision::uintwide_t_backend<MyWidth2, MyLimbType, MyAllocatorType>, ExpressionTemplatesOptions> { return boost::multiprecision::uintwide_t_backend<MyWidth2, MyLimbType, MyAllocatorType>((std::numeric_limits<::math::wide_integer::uintwide_t<MyWidth2, MyLimbType, MyAllocatorType>>::min)()       ); }\n      static WIDE_INTEGER_CONSTEXPR auto (max)        () -> boost::multiprecision::number<boost::multiprecision::uintwide_t_backend<MyWidth2, MyLimbType, MyAllocatorType>, ExpressionTemplatesOptions> { return boost::multiprecision::uintwide_t_backend<MyWidth2, MyLimbType, MyAllocatorType>((std::numeric_limits<::math::wide_integer::uintwide_t<MyWidth2, MyLimbType, MyAllocatorType>>::max)()       ); }\n      static WIDE_INTEGER_CONSTEXPR auto lowest       () -> boost::multiprecision::number<boost::multiprecision::uintwide_t_backend<MyWidth2, MyLimbType, MyAllocatorType>, ExpressionTemplatesOptions> { return boost::multiprecision::uintwide_t_backend<MyWidth2, MyLimbType, MyAllocatorType> (std::numeric_limits<::math::wide_integer::uintwide_t<MyWidth2, MyLimbType, MyAllocatorType>>::lowest       ); }\n      static WIDE_INTEGER_CONSTEXPR auto epsilon      () -> boost::multiprecision::number<boost::multiprecision::uintwide_t_backend<MyWidth2, MyLimbType, MyAllocatorType>, ExpressionTemplatesOptions> { return boost::multiprecision::uintwide_t_backend<MyWidth2, MyLimbType, MyAllocatorType> (std::numeric_limits<::math::wide_integer::uintwide_t<MyWidth2, MyLimbType, MyAllocatorType>>::epsilon      ); }\n      static WIDE_INTEGER_CONSTEXPR auto round_error  () -> boost::multiprecision::number<boost::multiprecision::uintwide_t_backend<MyWidth2, MyLimbType, MyAllocatorType>, ExpressionTemplatesOptions> { return boost::multiprecision::uintwide_t_backend<MyWidth2, MyLimbType, MyAllocatorType> (std::numeric_limits<::math::wide_integer::uintwide_t<MyWidth2, MyLimbType, MyAllocatorType>>::round_error  ); }\n      static WIDE_INTEGER_CONSTEXPR auto infinity     () -> boost::multiprecision::number<boost::multiprecision::uintwide_t_backend<MyWidth2, MyLimbType, MyAllocatorType>, ExpressionTemplatesOptions> { return boost::multiprecision::uintwide_t_backend<MyWidth2, MyLimbType, MyAllocatorType> (std::numeric_limits<::math::wide_integer::uintwide_t<MyWidth2, MyLimbType, MyAllocatorType>>::infinity     ); }\n      static WIDE_INTEGER_CONSTEXPR auto quiet_NaN    () -> boost::multiprecision::number<boost::multiprecision::uintwide_t_backend<MyWidth2, MyLimbType, MyAllocatorType>, ExpressionTemplatesOptions> { return boost::multiprecision::uintwide_t_backend<MyWidth2, MyLimbType, MyAllocatorType> (std::numeric_limits<::math::wide_integer::uintwide_t<MyWidth2, MyLimbType, MyAllocatorType>>::quiet_NaN    ); } // NOLINT(readability-identifier-naming)\n      static WIDE_INTEGER_CONSTEXPR auto signaling_NaN() -> boost::multiprecision::number<boost::multiprecision::uintwide_t_backend<MyWidth2, MyLimbType, MyAllocatorType>, ExpressionTemplatesOptions> { return boost::multiprecision::uintwide_t_backend<MyWidth2, MyLimbType, MyAllocatorType> (std::numeric_limits<::math::wide_integer::uintwide_t<MyWidth2, MyLimbType, MyAllocatorType>>::signaling_NaN); } // NOLINT(readability-identifier-naming)\n      static WIDE_INTEGER_CONSTEXPR auto denorm_min   () -> boost::multiprecision::number<boost::multiprecision::uintwide_t_backend<MyWidth2, MyLimbType, MyAllocatorType>, ExpressionTemplatesOptions> { return boost::multiprecision::uintwide_t_backend<MyWidth2, MyLimbType, MyAllocatorType> (std::numeric_limits<::math::wide_integer::uintwide_t<MyWidth2, MyLimbType, MyAllocatorType>>::denorm_min   ); }\n      #endif\n    };\n\n    #ifndef BOOST_NO_INCLASS_MEMBER_INITIALIZATION\n\n    #if defined(WIDE_INTEGER_NAMESPACE)\n    template<const WIDE_INTEGER_NAMESPACE::math::wide_integer::size_t MyWidth2, typename MyLimbType, typename MyAllocatorType, const boost::multiprecision::expression_template_option ExpressionTemplatesOptions> constexpr bool std::numeric_limits<boost::multiprecision::number<boost::multiprecision::uintwide_t_backend<MyWidth2, MyLimbType, MyAllocatorType>, ExpressionTemplatesOptions>>::is_specialized; // NOLINT(readability-redundant-declaration)\n    template<const WIDE_INTEGER_NAMESPACE::math::wide_integer::size_t MyWidth2, typename MyLimbType, typename MyAllocatorType, const boost::multiprecision::expression_template_option ExpressionTemplatesOptions> constexpr bool std::numeric_limits<boost::multiprecision::number<boost::multiprecision::uintwide_t_backend<MyWidth2, MyLimbType, MyAllocatorType>, ExpressionTemplatesOptions>>::is_signed;      // NOLINT(readability-redundant-declaration)\n    template<const WIDE_INTEGER_NAMESPACE::math::wide_integer::size_t MyWidth2, typename MyLimbType, typename MyAllocatorType, const boost::multiprecision::expression_template_option ExpressionTemplatesOptions> constexpr bool std::numeric_limits<boost::multiprecision::number<boost::multiprecision::uintwide_t_backend<MyWidth2, MyLimbType, MyAllocatorType>, ExpressionTemplatesOptions>>::is_integer;     // NOLINT(readability-redundant-declaration)\n    template<const WIDE_INTEGER_NAMESPACE::math::wide_integer::size_t MyWidth2, typename MyLimbType, typename MyAllocatorType, const boost::multiprecision::expression_template_option ExpressionTemplatesOptions> constexpr bool std::numeric_limits<boost::multiprecision::number<boost::multiprecision::uintwide_t_backend<MyWidth2, MyLimbType, MyAllocatorType>, ExpressionTemplatesOptions>>::is_exact;       // NOLINT(readability-redundant-declaration)\n    template<const WIDE_INTEGER_NAMESPACE::math::wide_integer::size_t MyWidth2, typename MyLimbType, typename MyAllocatorType, const boost::multiprecision::expression_template_option ExpressionTemplatesOptions> constexpr bool std::numeric_limits<boost::multiprecision::number<boost::multiprecision::uintwide_t_backend<MyWidth2, MyLimbType, MyAllocatorType>, ExpressionTemplatesOptions>>::is_bounded;     // NOLINT(readability-redundant-declaration)\n    template<const WIDE_INTEGER_NAMESPACE::math::wide_integer::size_t MyWidth2, typename MyLimbType, typename MyAllocatorType, const boost::multiprecision::expression_template_option ExpressionTemplatesOptions> constexpr bool std::numeric_limits<boost::multiprecision::number<boost::multiprecision::uintwide_t_backend<MyWidth2, MyLimbType, MyAllocatorType>, ExpressionTemplatesOptions>>::is_modulo;      // NOLINT(readability-redundant-declaration)\n    template<const WIDE_INTEGER_NAMESPACE::math::wide_integer::size_t MyWidth2, typename MyLimbType, typename MyAllocatorType, const boost::multiprecision::expression_template_option ExpressionTemplatesOptions> constexpr bool std::numeric_limits<boost::multiprecision::number<boost::multiprecision::uintwide_t_backend<MyWidth2, MyLimbType, MyAllocatorType>, ExpressionTemplatesOptions>>::is_iec559;      // NOLINT(readability-redundant-declaration)\n    template<const WIDE_INTEGER_NAMESPACE::math::wide_integer::size_t MyWidth2, typename MyLimbType, typename MyAllocatorType, const boost::multiprecision::expression_template_option ExpressionTemplatesOptions> constexpr int  std::numeric_limits<boost::multiprecision::number<boost::multiprecision::uintwide_t_backend<MyWidth2, MyLimbType, MyAllocatorType>, ExpressionTemplatesOptions>>::digits;         // NOLINT(readability-redundant-declaration)\n    template<const WIDE_INTEGER_NAMESPACE::math::wide_integer::size_t MyWidth2, typename MyLimbType, typename MyAllocatorType, const boost::multiprecision::expression_template_option ExpressionTemplatesOptions> constexpr int  std::numeric_limits<boost::multiprecision::number<boost::multiprecision::uintwide_t_backend<MyWidth2, MyLimbType, MyAllocatorType>, ExpressionTemplatesOptions>>::digits10;       // NOLINT(readability-redundant-declaration)\n    template<const WIDE_INTEGER_NAMESPACE::math::wide_integer::size_t MyWidth2, typename MyLimbType, typename MyAllocatorType, const boost::multiprecision::expression_template_option ExpressionTemplatesOptions> constexpr int  std::numeric_limits<boost::multiprecision::number<boost::multiprecision::uintwide_t_backend<MyWidth2, MyLimbType, MyAllocatorType>, ExpressionTemplatesOptions>>::max_digits10;   // NOLINT(readability-redundant-declaration)\n\n    template<const WIDE_INTEGER_NAMESPACE::math::wide_integer::size_t MyWidth2, typename MyLimbType, typename MyAllocatorType, const boost::multiprecision::expression_template_option ExpressionTemplatesOptions> constexpr int std::numeric_limits<boost::multiprecision::number<boost::multiprecision::uintwide_t_backend<MyWidth2, MyLimbType, MyAllocatorType>, ExpressionTemplatesOptions>>::max_exponent;   // NOLINT(readability-redundant-declaration)\n    template<const WIDE_INTEGER_NAMESPACE::math::wide_integer::size_t MyWidth2, typename MyLimbType, typename MyAllocatorType, const boost::multiprecision::expression_template_option ExpressionTemplatesOptions> constexpr int std::numeric_limits<boost::multiprecision::number<boost::multiprecision::uintwide_t_backend<MyWidth2, MyLimbType, MyAllocatorType>, ExpressionTemplatesOptions>>::max_exponent10; // NOLINT(readability-redundant-declaration)\n    template<const WIDE_INTEGER_NAMESPACE::math::wide_integer::size_t MyWidth2, typename MyLimbType, typename MyAllocatorType, const boost::multiprecision::expression_template_option ExpressionTemplatesOptions> constexpr int std::numeric_limits<boost::multiprecision::number<boost::multiprecision::uintwide_t_backend<MyWidth2, MyLimbType, MyAllocatorType>, ExpressionTemplatesOptions>>::min_exponent;   // NOLINT(readability-redundant-declaration)\n    template<const WIDE_INTEGER_NAMESPACE::math::wide_integer::size_t MyWidth2, typename MyLimbType, typename MyAllocatorType, const boost::multiprecision::expression_template_option ExpressionTemplatesOptions> constexpr int std::numeric_limits<boost::multiprecision::number<boost::multiprecision::uintwide_t_backend<MyWidth2, MyLimbType, MyAllocatorType>, ExpressionTemplatesOptions>>::min_exponent10; // NOLINT(readability-redundant-declaration)\n\n    template<const WIDE_INTEGER_NAMESPACE::math::wide_integer::size_t MyWidth2, typename MyLimbType, typename MyAllocatorType, const boost::multiprecision::expression_template_option ExpressionTemplatesOptions> constexpr int                     std::numeric_limits<boost::multiprecision::number<boost::multiprecision::uintwide_t_backend<MyWidth2, MyLimbType, MyAllocatorType>, ExpressionTemplatesOptions>>::radix;             // NOLINT(readability-redundant-declaration)\n    template<const WIDE_INTEGER_NAMESPACE::math::wide_integer::size_t MyWidth2, typename MyLimbType, typename MyAllocatorType, const boost::multiprecision::expression_template_option ExpressionTemplatesOptions> constexpr std::float_round_style  std::numeric_limits<boost::multiprecision::number<boost::multiprecision::uintwide_t_backend<MyWidth2, MyLimbType, MyAllocatorType>, ExpressionTemplatesOptions>>::round_style;       // NOLINT(readability-redundant-declaration)\n    template<const WIDE_INTEGER_NAMESPACE::math::wide_integer::size_t MyWidth2, typename MyLimbType, typename MyAllocatorType, const boost::multiprecision::expression_template_option ExpressionTemplatesOptions> constexpr bool                    std::numeric_limits<boost::multiprecision::number<boost::multiprecision::uintwide_t_backend<MyWidth2, MyLimbType, MyAllocatorType>, ExpressionTemplatesOptions>>::has_infinity;      // NOLINT(readability-redundant-declaration)\n    template<const WIDE_INTEGER_NAMESPACE::math::wide_integer::size_t MyWidth2, typename MyLimbType, typename MyAllocatorType, const boost::multiprecision::expression_template_option ExpressionTemplatesOptions> constexpr bool                    std::numeric_limits<boost::multiprecision::number<boost::multiprecision::uintwide_t_backend<MyWidth2, MyLimbType, MyAllocatorType>, ExpressionTemplatesOptions>>::has_quiet_NaN;     // NOLINT(readability-redundant-declaration)\n    template<const WIDE_INTEGER_NAMESPACE::math::wide_integer::size_t MyWidth2, typename MyLimbType, typename MyAllocatorType, const boost::multiprecision::expression_template_option ExpressionTemplatesOptions> constexpr bool                    std::numeric_limits<boost::multiprecision::number<boost::multiprecision::uintwide_t_backend<MyWidth2, MyLimbType, MyAllocatorType>, ExpressionTemplatesOptions>>::has_signaling_NaN; // NOLINT(readability-redundant-declaration)\n    template<const WIDE_INTEGER_NAMESPACE::math::wide_integer::size_t MyWidth2, typename MyLimbType, typename MyAllocatorType, const boost::multiprecision::expression_template_option ExpressionTemplatesOptions> constexpr std::float_denorm_style std::numeric_limits<boost::multiprecision::number<boost::multiprecision::uintwide_t_backend<MyWidth2, MyLimbType, MyAllocatorType>, ExpressionTemplatesOptions>>::has_denorm;        // NOLINT(readability-redundant-declaration)\n    template<const WIDE_INTEGER_NAMESPACE::math::wide_integer::size_t MyWidth2, typename MyLimbType, typename MyAllocatorType, const boost::multiprecision::expression_template_option ExpressionTemplatesOptions> constexpr bool                    std::numeric_limits<boost::multiprecision::number<boost::multiprecision::uintwide_t_backend<MyWidth2, MyLimbType, MyAllocatorType>, ExpressionTemplatesOptions>>::has_denorm_loss;   // NOLINT(readability-redundant-declaration)\n    template<const WIDE_INTEGER_NAMESPACE::math::wide_integer::size_t MyWidth2, typename MyLimbType, typename MyAllocatorType, const boost::multiprecision::expression_template_option ExpressionTemplatesOptions> constexpr bool                    std::numeric_limits<boost::multiprecision::number<boost::multiprecision::uintwide_t_backend<MyWidth2, MyLimbType, MyAllocatorType>, ExpressionTemplatesOptions>>::traps;             // NOLINT(readability-redundant-declaration)\n    template<const WIDE_INTEGER_NAMESPACE::math::wide_integer::size_t MyWidth2, typename MyLimbType, typename MyAllocatorType, const boost::multiprecision::expression_template_option ExpressionTemplatesOptions> constexpr bool                    std::numeric_limits<boost::multiprecision::number<boost::multiprecision::uintwide_t_backend<MyWidth2, MyLimbType, MyAllocatorType>, ExpressionTemplatesOptions>>::tinyness_before;   // NOLINT(readability-redundant-declaration)\n    #else\n    template<const ::math::wide_integer::size_t MyWidth2, typename MyLimbType, typename MyAllocatorType, const boost::multiprecision::expression_template_option ExpressionTemplatesOptions> constexpr bool std::numeric_limits<boost::multiprecision::number<boost::multiprecision::uintwide_t_backend<MyWidth2, MyLimbType, MyAllocatorType>, ExpressionTemplatesOptions>>::is_specialized; // NOLINT(readability-redundant-declaration)\n    template<const ::math::wide_integer::size_t MyWidth2, typename MyLimbType, typename MyAllocatorType, const boost::multiprecision::expression_template_option ExpressionTemplatesOptions> constexpr bool std::numeric_limits<boost::multiprecision::number<boost::multiprecision::uintwide_t_backend<MyWidth2, MyLimbType, MyAllocatorType>, ExpressionTemplatesOptions>>::is_signed;      // NOLINT(readability-redundant-declaration)\n    template<const ::math::wide_integer::size_t MyWidth2, typename MyLimbType, typename MyAllocatorType, const boost::multiprecision::expression_template_option ExpressionTemplatesOptions> constexpr bool std::numeric_limits<boost::multiprecision::number<boost::multiprecision::uintwide_t_backend<MyWidth2, MyLimbType, MyAllocatorType>, ExpressionTemplatesOptions>>::is_integer;     // NOLINT(readability-redundant-declaration)\n    template<const ::math::wide_integer::size_t MyWidth2, typename MyLimbType, typename MyAllocatorType, const boost::multiprecision::expression_template_option ExpressionTemplatesOptions> constexpr bool std::numeric_limits<boost::multiprecision::number<boost::multiprecision::uintwide_t_backend<MyWidth2, MyLimbType, MyAllocatorType>, ExpressionTemplatesOptions>>::is_exact;       // NOLINT(readability-redundant-declaration)\n    template<const ::math::wide_integer::size_t MyWidth2, typename MyLimbType, typename MyAllocatorType, const boost::multiprecision::expression_template_option ExpressionTemplatesOptions> constexpr bool std::numeric_limits<boost::multiprecision::number<boost::multiprecision::uintwide_t_backend<MyWidth2, MyLimbType, MyAllocatorType>, ExpressionTemplatesOptions>>::is_bounded;     // NOLINT(readability-redundant-declaration)\n    template<const ::math::wide_integer::size_t MyWidth2, typename MyLimbType, typename MyAllocatorType, const boost::multiprecision::expression_template_option ExpressionTemplatesOptions> constexpr bool std::numeric_limits<boost::multiprecision::number<boost::multiprecision::uintwide_t_backend<MyWidth2, MyLimbType, MyAllocatorType>, ExpressionTemplatesOptions>>::is_modulo;      // NOLINT(readability-redundant-declaration)\n    template<const ::math::wide_integer::size_t MyWidth2, typename MyLimbType, typename MyAllocatorType, const boost::multiprecision::expression_template_option ExpressionTemplatesOptions> constexpr bool std::numeric_limits<boost::multiprecision::number<boost::multiprecision::uintwide_t_backend<MyWidth2, MyLimbType, MyAllocatorType>, ExpressionTemplatesOptions>>::is_iec559;      // NOLINT(readability-redundant-declaration)\n    template<const ::math::wide_integer::size_t MyWidth2, typename MyLimbType, typename MyAllocatorType, const boost::multiprecision::expression_template_option ExpressionTemplatesOptions> constexpr int  std::numeric_limits<boost::multiprecision::number<boost::multiprecision::uintwide_t_backend<MyWidth2, MyLimbType, MyAllocatorType>, ExpressionTemplatesOptions>>::digits;         // NOLINT(readability-redundant-declaration)\n    template<const ::math::wide_integer::size_t MyWidth2, typename MyLimbType, typename MyAllocatorType, const boost::multiprecision::expression_template_option ExpressionTemplatesOptions> constexpr int  std::numeric_limits<boost::multiprecision::number<boost::multiprecision::uintwide_t_backend<MyWidth2, MyLimbType, MyAllocatorType>, ExpressionTemplatesOptions>>::digits10;       // NOLINT(readability-redundant-declaration)\n    template<const ::math::wide_integer::size_t MyWidth2, typename MyLimbType, typename MyAllocatorType, const boost::multiprecision::expression_template_option ExpressionTemplatesOptions> constexpr int  std::numeric_limits<boost::multiprecision::number<boost::multiprecision::uintwide_t_backend<MyWidth2, MyLimbType, MyAllocatorType>, ExpressionTemplatesOptions>>::max_digits10;   // NOLINT(readability-redundant-declaration)\n\n    template<const ::math::wide_integer::size_t MyWidth2, typename MyLimbType, typename MyAllocatorType, const boost::multiprecision::expression_template_option ExpressionTemplatesOptions> constexpr int std::numeric_limits<boost::multiprecision::number<boost::multiprecision::uintwide_t_backend<MyWidth2, MyLimbType, MyAllocatorType>, ExpressionTemplatesOptions>>::max_exponent;    // NOLINT(readability-redundant-declaration)\n    template<const ::math::wide_integer::size_t MyWidth2, typename MyLimbType, typename MyAllocatorType, const boost::multiprecision::expression_template_option ExpressionTemplatesOptions> constexpr int std::numeric_limits<boost::multiprecision::number<boost::multiprecision::uintwide_t_backend<MyWidth2, MyLimbType, MyAllocatorType>, ExpressionTemplatesOptions>>::max_exponent10;  // NOLINT(readability-redundant-declaration)\n    template<const ::math::wide_integer::size_t MyWidth2, typename MyLimbType, typename MyAllocatorType, const boost::multiprecision::expression_template_option ExpressionTemplatesOptions> constexpr int std::numeric_limits<boost::multiprecision::number<boost::multiprecision::uintwide_t_backend<MyWidth2, MyLimbType, MyAllocatorType>, ExpressionTemplatesOptions>>::min_exponent;    // NOLINT(readability-redundant-declaration)\n    template<const ::math::wide_integer::size_t MyWidth2, typename MyLimbType, typename MyAllocatorType, const boost::multiprecision::expression_template_option ExpressionTemplatesOptions> constexpr int std::numeric_limits<boost::multiprecision::number<boost::multiprecision::uintwide_t_backend<MyWidth2, MyLimbType, MyAllocatorType>, ExpressionTemplatesOptions>>::min_exponent10;  // NOLINT(readability-redundant-declaration)\n\n    template<const ::math::wide_integer::size_t MyWidth2, typename MyLimbType, typename MyAllocatorType, const boost::multiprecision::expression_template_option ExpressionTemplatesOptions> constexpr int                     std::numeric_limits<boost::multiprecision::number<boost::multiprecision::uintwide_t_backend<MyWidth2, MyLimbType, MyAllocatorType>, ExpressionTemplatesOptions>>::radix;             // NOLINT(readability-redundant-declaration)\n    template<const ::math::wide_integer::size_t MyWidth2, typename MyLimbType, typename MyAllocatorType, const boost::multiprecision::expression_template_option ExpressionTemplatesOptions> constexpr std::float_round_style  std::numeric_limits<boost::multiprecision::number<boost::multiprecision::uintwide_t_backend<MyWidth2, MyLimbType, MyAllocatorType>, ExpressionTemplatesOptions>>::round_style;       // NOLINT(readability-redundant-declaration)\n    template<const ::math::wide_integer::size_t MyWidth2, typename MyLimbType, typename MyAllocatorType, const boost::multiprecision::expression_template_option ExpressionTemplatesOptions> constexpr bool                    std::numeric_limits<boost::multiprecision::number<boost::multiprecision::uintwide_t_backend<MyWidth2, MyLimbType, MyAllocatorType>, ExpressionTemplatesOptions>>::has_infinity;      // NOLINT(readability-redundant-declaration)\n    template<const ::math::wide_integer::size_t MyWidth2, typename MyLimbType, typename MyAllocatorType, const boost::multiprecision::expression_template_option ExpressionTemplatesOptions> constexpr bool                    std::numeric_limits<boost::multiprecision::number<boost::multiprecision::uintwide_t_backend<MyWidth2, MyLimbType, MyAllocatorType>, ExpressionTemplatesOptions>>::has_quiet_NaN;     // NOLINT(readability-redundant-declaration)\n    template<const ::math::wide_integer::size_t MyWidth2, typename MyLimbType, typename MyAllocatorType, const boost::multiprecision::expression_template_option ExpressionTemplatesOptions> constexpr bool                    std::numeric_limits<boost::multiprecision::number<boost::multiprecision::uintwide_t_backend<MyWidth2, MyLimbType, MyAllocatorType>, ExpressionTemplatesOptions>>::has_signaling_NaN; // NOLINT(readability-redundant-declaration)\n    template<const ::math::wide_integer::size_t MyWidth2, typename MyLimbType, typename MyAllocatorType, const boost::multiprecision::expression_template_option ExpressionTemplatesOptions> constexpr std::float_denorm_style std::numeric_limits<boost::multiprecision::number<boost::multiprecision::uintwide_t_backend<MyWidth2, MyLimbType, MyAllocatorType>, ExpressionTemplatesOptions>>::has_denorm;        // NOLINT(readability-redundant-declaration)\n    template<const ::math::wide_integer::size_t MyWidth2, typename MyLimbType, typename MyAllocatorType, const boost::multiprecision::expression_template_option ExpressionTemplatesOptions> constexpr bool                    std::numeric_limits<boost::multiprecision::number<boost::multiprecision::uintwide_t_backend<MyWidth2, MyLimbType, MyAllocatorType>, ExpressionTemplatesOptions>>::has_denorm_loss;   // NOLINT(readability-redundant-declaration)\n    template<const ::math::wide_integer::size_t MyWidth2, typename MyLimbType, typename MyAllocatorType, const boost::multiprecision::expression_template_option ExpressionTemplatesOptions> constexpr bool                    std::numeric_limits<boost::multiprecision::number<boost::multiprecision::uintwide_t_backend<MyWidth2, MyLimbType, MyAllocatorType>, ExpressionTemplatesOptions>>::traps;             // NOLINT(readability-redundant-declaration)\n    template<const ::math::wide_integer::size_t MyWidth2, typename MyLimbType, typename MyAllocatorType, const boost::multiprecision::expression_template_option ExpressionTemplatesOptions> constexpr bool                    std::numeric_limits<boost::multiprecision::number<boost::multiprecision::uintwide_t_backend<MyWidth2, MyLimbType, MyAllocatorType>, ExpressionTemplatesOptions>>::tinyness_before;   // NOLINT(readability-redundant-declaration)\n    #endif\n\n    #endif // !BOOST_NO_INCLASS_MEMBER_INITIALIZATION\n\n  } // namespace std\n\n  #if (BOOST_VERSION < 108000)\n  #if (defined(__clang__) && (__clang_major__ > 9)) && !defined(__APPLE__)\n  #pragma GCC diagnostic pop\n  #endif\n  #endif\n\n  #if (defined(__GNUC__) && !defined(__clang__) && (__GNUC__ >= 12))\n  #pragma GCC diagnostic pop\n  #endif\n\n  #if (BOOST_VERSION < 108000)\n  #if defined(__GNUC__)\n  #pragma GCC diagnostic pop\n  #pragma GCC diagnostic pop\n  #pragma GCC diagnostic pop\n  #endif\n  #endif\n\n#endif // UINTWIDE_T_BACKEND_2019_12_15_HPP\n", "meta": {"hexsha": "d011ece61c0736469904f4892c6805b0626dc43f", "size": 69975, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/multiprecision/uintwide_t_backend.hpp", "max_stars_repo_name": "clayne/wide-integer", "max_stars_repo_head_hexsha": "a4e6828d28bda6313b206cd795b83ea6d1133f05", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "boost/multiprecision/uintwide_t_backend.hpp", "max_issues_repo_name": "clayne/wide-integer", "max_issues_repo_head_hexsha": "a4e6828d28bda6313b206cd795b83ea6d1133f05", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "boost/multiprecision/uintwide_t_backend.hpp", "max_forks_repo_name": "clayne/wide-integer", "max_forks_repo_head_hexsha": "a4e6828d28bda6313b206cd795b83ea6d1133f05", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 64.7916666667, "max_line_length": 470, "alphanum_fraction": 0.7284030011, "num_tokens": 16315, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6859494550081926, "lm_q2_score": 0.44552953503957266, "lm_q1q2_score": 0.30561074175044833}}
{"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// This file contains fixed_point details.\r\n\r\n#ifndef FIXED_POINT_DETAIL_2015_05_23_HPP_\r\n  #define FIXED_POINT_DETAIL_2015_05_23_HPP_\r\n\r\n  #include <array>\r\n  #include <cstdint>\r\n\r\n  #include <boost/config.hpp>\r\n  #include <boost/fixed_point/detail/fixed_point_detail_cstdfloat.hpp>\r\n\r\n  #if (   (!defined(BOOST_FIXED_POINT_FLOAT32_C))   \\\r\n       && (!defined(BOOST_FIXED_POINT_FLOAT64_C))   \\\r\n       && (!defined(BOOST_FIXED_POINT_FLOAT80_C))   \\\r\n       && (!defined(BOOST_FIXED_POINT_FLOAT128_C)))\r\n    #error Configuration error: Sorry, fixed_point can not detect any IEEE-754 built-in floating-point types!\r\n  #endif\r\n\r\n  // Do not produce Doxygen indexing of items in namespace detail unless specifically required.\r\n  // The section between \\cond and \\endcond can be included by adding its section label DETAIL\r\n  // to the ENABLED_SECTIONS configuration option. \r\n  // If the section label is omitted, the section will be excluded from processing unconditionally.\r\n\r\n  //! \\cond DETAIL\r\n\r\n  namespace boost { namespace fixed_point { namespace detail {\r\n\r\n  template<typename UnsignedIntegralType>\r\n  UnsignedIntegralType left_shift_helper(const UnsignedIntegralType& u, const int shift_count)\r\n  {\r\n    #if !defined(BOOST_FIXED_POINT_ENABLE_GMP_BACKENDS)\r\n\r\n      static_assert(    (std::numeric_limits<UnsignedIntegralType>::is_integer == true)\r\n                     && (std::numeric_limits<UnsignedIntegralType>::is_signed  == false),\r\n                     \"The UnsignedIntegralType for left shift must be an unsigned integral type.\");\r\n\r\n    #endif\r\n\r\n    return ((shift_count > 0) ? UnsignedIntegralType(u << +shift_count)\r\n                              : UnsignedIntegralType(u >> -shift_count));\r\n  }\r\n\r\n  template<typename UnsignedIntegralType>\r\n  UnsignedIntegralType right_shift_helper(const UnsignedIntegralType& u, const int shift_count)\r\n  {\r\n    #if !defined(BOOST_FIXED_POINT_ENABLE_GMP_BACKENDS)\r\n\r\n      static_assert(    (std::numeric_limits<UnsignedIntegralType>::is_integer == true)\r\n                     && (std::numeric_limits<UnsignedIntegralType>::is_signed  == false),\r\n                     \"The UnsignedIntegralType for right shift must be an unsigned integral type.\");\r\n\r\n    #endif\r\n\r\n    return ((shift_count > 0) ? UnsignedIntegralType(u >> +shift_count)\r\n                              : UnsignedIntegralType(u << -shift_count));\r\n  }\r\n\r\n  #if !defined(BOOST_FIXED_POINT_DISABLE_MULTIPRECISION)\r\n\r\n    template<const std::uint32_t BitCount,\r\n             typename EnableType = void>\r\n    struct integer_type_helper\r\n    {\r\n    private:\r\n      static BOOST_CONSTEXPR_OR_CONST std::uint32_t bit_count_nearest_power_of_two =\r\n        (BitCount <= std::uint32_t(UINT32_C(1) <<  7)) ? std::uint32_t(UINT32_C(1) <<  7) :\r\n        (BitCount <= std::uint32_t(UINT32_C(1) <<  8)) ? std::uint32_t(UINT32_C(1) <<  8) :\r\n        (BitCount <= std::uint32_t(UINT32_C(1) <<  9)) ? std::uint32_t(UINT32_C(1) <<  9) :\r\n        (BitCount <= std::uint32_t(UINT32_C(1) << 10)) ? std::uint32_t(UINT32_C(1) << 10) :\r\n        (BitCount <= std::uint32_t(UINT32_C(1) << 11)) ? std::uint32_t(UINT32_C(1) << 11) :\r\n        (BitCount <= std::uint32_t(UINT32_C(1) << 12)) ? std::uint32_t(UINT32_C(1) << 12) :\r\n        (BitCount <= std::uint32_t(UINT32_C(1) << 13)) ? std::uint32_t(UINT32_C(1) << 13) :\r\n        (BitCount <= std::uint32_t(UINT32_C(1) << 14)) ? std::uint32_t(UINT32_C(1) << 14) :\r\n        (BitCount <= std::uint32_t(UINT32_C(1) << 15)) ? std::uint32_t(UINT32_C(1) << 15) :\r\n        (BitCount <= std::uint32_t(UINT32_C(1) << 16)) ? std::uint32_t(UINT32_C(1) << 16) :\r\n        (BitCount <= std::uint32_t(UINT32_C(1) << 17)) ? std::uint32_t(UINT32_C(1) << 17) :\r\n        (BitCount <= std::uint32_t(UINT32_C(1) << 18)) ? std::uint32_t(UINT32_C(1) << 18) :\r\n        (BitCount <= std::uint32_t(UINT32_C(1) << 19)) ? std::uint32_t(UINT32_C(1) << 19) :\r\n        (BitCount <= std::uint32_t(UINT32_C(1) << 20)) ? std::uint32_t(UINT32_C(1) << 20) :\r\n        (BitCount <= std::uint32_t(UINT32_C(1) << 21)) ? std::uint32_t(UINT32_C(1) << 21) :\r\n        (BitCount <= std::uint32_t(UINT32_C(1) << 22)) ? std::uint32_t(UINT32_C(1) << 22) :\r\n        (BitCount <= std::uint32_t(UINT32_C(1) << 23)) ? std::uint32_t(UINT32_C(1) << 23) :\r\n        (BitCount <= std::uint32_t(UINT32_C(1) << 24)) ? std::uint32_t(UINT32_C(1) << 24) :\r\n        (BitCount <= std::uint32_t(UINT32_C(1) << 25)) ? std::uint32_t(UINT32_C(1) << 25) :\r\n        (BitCount <= std::uint32_t(UINT32_C(1) << 26)) ? std::uint32_t(UINT32_C(1) << 26) :\r\n        (BitCount <= std::uint32_t(UINT32_C(1) << 27)) ? std::uint32_t(UINT32_C(1) << 27) :\r\n        (BitCount <= std::uint32_t(UINT32_C(1) << 28)) ? std::uint32_t(UINT32_C(1) << 28) :\r\n        (BitCount <= std::uint32_t(UINT32_C(1) << 29)) ? std::uint32_t(UINT32_C(1) << 29) :\r\n        (BitCount <= std::uint32_t(UINT32_C(1) << 30)) ? std::uint32_t(UINT32_C(1) << 30) :\r\n                    (std::uint32_t(UINT32_C(1) << 31));\r\n\r\n      #if defined(BOOST_FIXED_POINT_ENABLE_GMP_BACKENDS)\r\n\r\n        typedef boost::multiprecision::gmp_int signed_integral_backend_type;\r\n        typedef boost::multiprecision::gmp_int unsigned_integral_backend_type;\r\n\r\n      #else\r\n\r\n      typedef boost::multiprecision::cpp_int_backend<unsigned(bit_count_nearest_power_of_two),\r\n                                                     unsigned(bit_count_nearest_power_of_two),\r\n                                                     boost::multiprecision::signed_magnitude,\r\n                                                     boost::multiprecision::unchecked,\r\n                                                     void>\r\n      signed_integral_backend_type;\r\n\r\n      typedef boost::multiprecision::cpp_int_backend<unsigned(bit_count_nearest_power_of_two),\r\n                                                     unsigned(bit_count_nearest_power_of_two),\r\n                                                     boost::multiprecision::unsigned_magnitude,\r\n                                                     boost::multiprecision::unchecked,\r\n                                                     void>\r\n      unsigned_integral_backend_type;\r\n\r\n      #endif\r\n\r\n    public:\r\n      typedef boost::multiprecision::number<signed_integral_backend_type,\r\n                                            boost::multiprecision::et_off> exact_signed_type;\r\n\r\n      typedef boost::multiprecision::number<unsigned_integral_backend_type,\r\n                                            boost::multiprecision::et_off> exact_unsigned_type;\r\n    };\r\n\r\n  #endif // !BOOST_FIXED_POINT_DISABLE_MULTIPRECISION\r\n\r\n  #if defined(BOOST_FIXED_POINT_DISABLE_MULTIPRECISION)\r\n\r\n    template<const std::uint32_t BitCount,\r\n             typename EnableType = void>\r\n    struct integer_type_helper\r\n    {\r\n    private:\r\n      typedef signed long long   exact_signed_type;\r\n      typedef unsigned long long exact_unsigned_type;\r\n    };\r\n\r\n  #endif // BOOST_FIXED_POINT_DISABLE_MULTIPRECISION\r\n\r\n  template<const std::uint32_t BitCount>\r\n  struct integer_type_helper<BitCount,\r\n                             typename std::enable_if<(BitCount <= UINT32_C(8))>::type>\r\n  {\r\n    typedef std::int8_t  exact_signed_type;\r\n    typedef std::uint8_t exact_unsigned_type;\r\n  };\r\n\r\n  template<const std::uint32_t BitCount>\r\n  struct integer_type_helper<BitCount,\r\n                             typename std::enable_if<   (BitCount >  UINT32_C( 8))\r\n                                                     && (BitCount <= UINT32_C(16))>::type>\r\n  {\r\n    typedef std::int16_t  exact_signed_type;\r\n    typedef std::uint16_t exact_unsigned_type;\r\n  };\r\n\r\n  template<const std::uint32_t BitCount>\r\n  struct integer_type_helper<BitCount,\r\n                             typename std::enable_if<   (BitCount >  UINT32_C(16))\r\n                                                     && (BitCount <= UINT32_C(32))>::type>\r\n  {\r\n    typedef std::int32_t  exact_signed_type;\r\n    typedef std::uint32_t exact_unsigned_type;\r\n  };\r\n\r\n  template<const std::uint32_t BitCount>\r\n  struct integer_type_helper<BitCount,\r\n                             typename std::enable_if<   (BitCount >  UINT32_C(32))\r\n                                                     && (BitCount <= UINT32_C(64))>::type>\r\n  {\r\n    typedef std::int64_t  exact_signed_type;\r\n    typedef std::uint64_t exact_unsigned_type;\r\n  };\r\n\r\n  #if !defined(BOOST_FIXED_POINT_DISABLE_MULTIPRECISION)\r\n\r\n    template<const std::uint32_t BitCount,\r\n             typename EnableType = void>\r\n    struct float_type_helper\r\n    {\r\n    private:\r\n\r\n      #if defined(BOOST_FIXED_POINT_ENABLE_GMP_BACKENDS)\r\n\r\n        typedef boost::multiprecision::gmp_float<unsigned((static_cast<long long>(static_cast<long long>(BitCount) * 301LL) + 500LL) / 1000LL)> floating_point_backend_type;\r\n\r\n      #else\r\n\r\n        typedef boost::multiprecision::backends::cpp_bin_float<unsigned(BitCount),\r\n                                                               boost::multiprecision::backends::digit_base_2>\r\n        floating_point_backend_type;\r\n\r\n      #endif\r\n\r\n    public:\r\n      typedef boost::multiprecision::number<floating_point_backend_type,\r\n                                            boost::multiprecision::et_off> exact_float_type;\r\n    };\r\n\r\n  #endif // !BOOST_FIXED_POINT_DISABLE_MULTIPRECISION\r\n\r\n  #if defined(BOOST_FIXED_POINT_DISABLE_MULTIPRECISION)\r\n\r\n    template<const std::uint32_t BitCount,\r\n             typename EnableType = void>\r\n    struct float_type_helper\r\n    {\r\n      // Here multiprecision is disabled. We have no choice\r\n      // other than using built-in long double here\r\n      // (even if built-in long double does not have\r\n      // enough bits).\r\n      typedef long double exact_float_type;\r\n    };\r\n\r\n  #endif\r\n\r\n  #if defined(BOOST_FIXED_POINT_FLOAT32_C)\r\n\r\n    template<const std::uint32_t BitCount>\r\n    struct float_type_helper<BitCount,\r\n                             typename std::enable_if<(BitCount <= UINT32_C(24))>::type>\r\n    {\r\n      typedef boost::fixed_point::detail::float32_t exact_float_type;\r\n    };\r\n\r\n  #endif // BOOST_FIXED_POINT_FLOAT32_C\r\n\r\n  #if defined(BOOST_FIXED_POINT_FLOAT64_C)\r\n\r\n    // For 64-bit float, we have two cases.\r\n    //\r\n    // * !float32_t : float64_t covers bits  0...53\r\n    // *  float32_t : float64_t covers bits 24...53\r\n\r\n    template<const std::uint32_t BitCount>\r\n    struct float_type_helper<BitCount,\r\n    #if defined(BOOST_FIXED_POINT_FLOAT32_C)\r\n                             typename std::enable_if<   (BitCount >  UINT32_C(24))\r\n                                                     && (BitCount <= UINT32_C(53))>::type>\r\n    #else\r\n                             typename std::enable_if<   (BitCount <= UINT32_C(53))>::type>\r\n    #endif\r\n    {\r\n      typedef boost::fixed_point::detail::float64_t exact_float_type;\r\n    };\r\n\r\n  #endif // BOOST_FIXED_POINT_FLOAT64_C\r\n\r\n  #if defined(BOOST_FIXED_POINT_FLOAT80_C)\r\n\r\n    // For 80-bit float, we have four cases (2^2 = 4). There are\r\n    // two redundant cases.\r\n    //\r\n    // * !float32_t && !float64_t : float80_t covers bits  0...64\r\n    // *  float32_t && !float64_t : float80_t covers bits 24...64\r\n    // *  float32_t &&  float64_t : float80_t covers bits 53...64\r\n    // * !float32_t &&  float64_t : float80_t covers bits 53...64\r\n\r\n    template<const std::uint32_t BitCount>\r\n    struct float_type_helper<BitCount,\r\n    #if   (!defined(BOOST_FIXED_POINT_FLOAT32_C) && !defined(BOOST_FIXED_POINT_FLOAT64_C))\r\n                             typename std::enable_if<   (BitCount <= UINT32_C(64))>::type>\r\n    #elif ( defined(BOOST_FIXED_POINT_FLOAT32_C) && !defined(BOOST_FIXED_POINT_FLOAT64_C))\r\n                             typename std::enable_if<   (BitCount >  UINT32_C(24))\r\n                                                     && (BitCount <= UINT32_C(64))>::type>\r\n    #else\r\n                             typename std::enable_if<   (BitCount >  UINT32_C(53))\r\n                                                     && (BitCount <= UINT32_C(64))>::type>\r\n    #endif\r\n    {\r\n      typedef boost::fixed_point::detail::float80_t exact_float_type;\r\n    };\r\n\r\n  #endif // BOOST_FIXED_POINT_FLOAT80_C\r\n\r\n  #if defined(BOOST_FIXED_POINT_FLOAT128_C)\r\n\r\n    // For 128-bit float, we have eight cases (2^3 = 8). There are two groups\r\n    // of redundancies. These contain two and four redundant results, respectively.\r\n    //\r\n    // * !float32_t && !float64_t && !float80_t : float128_t covers bits  0...113\r\n    // *  float32_t && !float64_t && !float80_t : float128_t covers bits 24...113\r\n    // * !float32_t &&  float64_t && !float80_t : float128_t covers bits 53...113\r\n    // *  float32_t &&  float64_t && !float80_t : float128_t covers bits 53...113\r\n    // * !float32_t && !float64_t &&  float80_t : float128_t covers bits 64...113\r\n    // *  float32_t && !float64_t &&  float80_t : float128_t covers bits 64...113\r\n    // * !float32_t &&  float64_t &&  float80_t : float128_t covers bits 64...113\r\n    // *  float32_t &&  float64_t &&  float80_t : float128_t covers bits 64...113\r\n\r\n    template<const std::uint32_t BitCount>\r\n    struct float_type_helper<BitCount,\r\n    #if   (!defined(BOOST_FIXED_POINT_FLOAT32_C) && !defined(BOOST_FIXED_POINT_FLOAT64_C) && !defined(BOOST_FIXED_POINT_FLOAT80_C))\r\n                             typename std::enable_if<   (BitCount <= UINT32_C(113))>::type>\r\n    #elif ( defined(BOOST_FIXED_POINT_FLOAT32_C) && !defined(BOOST_FIXED_POINT_FLOAT64_C) && !defined(BOOST_FIXED_POINT_FLOAT80_C))\r\n                             typename std::enable_if<   (BitCount >  UINT32_C( 24))\r\n                                                     && (BitCount <= UINT32_C(113))>::type>\r\n    #elif ( defined(BOOST_FIXED_POINT_FLOAT64_C) && !defined(BOOST_FIXED_POINT_FLOAT80_C))\r\n                             typename std::enable_if<   (BitCount >  UINT32_C( 53))\r\n                                                     && (BitCount <= UINT32_C(113))>::type>\r\n    #else\r\n                             typename std::enable_if<   (BitCount >  UINT32_C( 64))\r\n                                                     && (BitCount <= UINT32_C(113))>::type>\r\n    #endif\r\n    {\r\n      typedef boost::fixed_point::detail::float128_t exact_float_type;\r\n    };\r\n\r\n  #endif // BOOST_FIXED_POINT_FLOAT128_C\r\n\r\n  #if !defined(BOOST_FIXED_POINT_DISABLE_MULTIPRECISION)\r\n\r\n    template<typename UnsignedIntegralType,\r\n             typename FloatingPointType,\r\n             typename EnableType = void>\r\n    struct conversion_helper\r\n    {\r\n      static void convert_floating_point_to_unsigned_integer(const FloatingPointType& floating_point_source,\r\n                                                             UnsignedIntegralType& unsigned_destination)\r\n      {\r\n        unsigned_destination = floating_point_source.template convert_to<UnsignedIntegralType>();\r\n      }\r\n    };\r\n\r\n    template<typename UnsignedIntegralType,\r\n             typename FloatingPointType>\r\n    struct conversion_helper<UnsignedIntegralType,\r\n                             FloatingPointType,\r\n                             typename std::enable_if<std::is_floating_point<FloatingPointType>::value>::type>\r\n    {\r\n      static void convert_floating_point_to_unsigned_integer(const FloatingPointType& floating_point_source,\r\n                                                             UnsignedIntegralType& unsigned_destination)\r\n      {\r\n        unsigned_destination = static_cast<UnsignedIntegralType>(floating_point_source);\r\n      }\r\n    };\r\n\r\n    #if !defined(BOOST_FIXED_POINT_FLOAT80_C)\r\n\r\n      // Here is a somewhat significant work-around for the conversion of\r\n      // cpp_bin_float to uint64_t. It is used for unique cases when\r\n      // float80_t is not available, but we are still trying to convert\r\n      // a small multiprecision floating point type to uint64_t.\r\n\r\n      // Say, for instsance, that float64_t is the largest width built-in\r\n      // floating-point type. It only has, however, 53 bits of precision.\r\n      // In this case, we might use a multiprecision type for precision\r\n      // ranging from 54...64 bits such as cpp_bin_float<64, digit_base_2>.\r\n      // When being converted to uint64_t in this precision range,\r\n      // multiprecision does not yet handle this case. In particular,\r\n      // see the TODO in the comment at line 1113 of cpp_bin_float.hpp\r\n      // from Boost 1.58. Hence we need this work-around.\r\n\r\n      template<typename FloatingPointType>\r\n      struct conversion_helper<std::uint64_t,\r\n                               FloatingPointType,\r\n                               typename std::enable_if<std::is_floating_point<FloatingPointType>::value == false>::type>\r\n      {\r\n      private:\r\n        typedef boost::fixed_point::detail::float_type_helper<UINT32_C(64)>::exact_float_type floating_point_type;\r\n\r\n      public:\r\n        static void convert_floating_point_to_unsigned_integer(const floating_point_type& floating_point_source,\r\n                                                               std::uint64_t& unsigned_destination)\r\n        {\r\n          std::stringstream ss;\r\n\r\n          ss << std::fixed << floating_point_source;\r\n\r\n          std::string str(ss.str());\r\n\r\n          const std::string::size_type position_of_dot = str.find(\".\");\r\n\r\n          if(position_of_dot != std::string::npos)\r\n          {\r\n            str = str.substr(std::string::size_type(0U), position_of_dot);\r\n          }\r\n\r\n          unsigned_destination = boost::lexical_cast<std::uint64_t>(str);\r\n        }\r\n      };\r\n\r\n    #endif // !BOOST_FIXED_POINT_FLOAT80_C\r\n\r\n  #endif // !BOOST_FIXED_POINT_DISABLE_MULTIPRECISION\r\n\r\n  #if defined(BOOST_FIXED_POINT_DISABLE_MULTIPRECISION)\r\n\r\n    template<typename UnsignedIntegralType,\r\n             typename FloatingPointType,\r\n             typename EnableType = void>\r\n    struct conversion_helper\r\n    {\r\n      static void convert_floating_point_to_unsigned_integer(const FloatingPointType& floating_point_source,\r\n                                                             UnsignedIntegralType& unsigned_destination)\r\n      {\r\n        unsigned_destination = static_cast<UnsignedIntegralType>(floating_point_source);\r\n      }\r\n    };\r\n\r\n  #endif // BOOST_FIXED_POINT_DISABLE_MULTIPRECISION\r\n\r\n  template<typename UnsignedIntegralType>\r\n  std::uint_fast16_t msb_helper(UnsignedIntegralType& u,\r\n                                UnsignedIntegralType& mask,\r\n                                const std::uint_fast16_t bit_count)\r\n  {\r\n    // Use O(log2[N]) binary-halving search algorithm to find the msb.\r\n    // The binary-halving search algorithm uses a recursive function call.\r\n\r\n    static_assert(   (std::numeric_limits<UnsignedIntegralType>::is_signed  == false)\r\n                  && (std::numeric_limits<UnsignedIntegralType>::is_integer == true),\r\n                  \"The UnsignedIntegralType for msb_helper must be an unsigned integral type.\");\r\n\r\n    if(u < 2U)\r\n    {\r\n      return UINT32_C(0);\r\n    }\r\n\r\n    const UnsignedIntegralType hi_part = (u >> (bit_count / 2U));\r\n\r\n    mask = (mask >> (bit_count / 2U));\r\n\r\n    if((hi_part & mask) != 0)\r\n    {\r\n      u = hi_part;\r\n\r\n      return (bit_count / 2U) + msb_helper(u, mask, std::uint_fast16_t(bit_count / 2U));\r\n    }\r\n    else\r\n    {\r\n      u = (u & mask);\r\n\r\n      return msb_helper(u, mask, (bit_count / 2U));\r\n    }\r\n  }\r\n\r\n  // Make a template specialization of msb_helper() for std::uint32_t.\r\n  template<>\r\n  std::uint_fast16_t msb_helper(std::uint32_t& u,\r\n                                std::uint32_t&,\r\n                                const std::uint_fast16_t)\r\n  {\r\n    std::uint_fast8_t r(0);\r\n\r\n    // Use O(log2[N]) binary-halving in an unrolled loop to find the msb.\r\n    if((u & UINT32_C(0xFFFF0000)) != UINT32_C(0)) { u >>= 16; r |= UINT8_C(16); }\r\n    if((u & UINT32_C(0x0000FF00)) != UINT32_C(0)) { u >>=  8; r |= UINT8_C( 8); }\r\n    if((u & UINT32_C(0x000000F0)) != UINT32_C(0)) { u >>=  4; r |= UINT8_C( 4); }\r\n    if((u & UINT32_C(0x0000000C)) != UINT32_C(0)) { u >>=  2; r |= UINT8_C( 2); }\r\n    if((u & UINT32_C(0x00000002)) != UINT32_C(0)) { u >>=  1; r |= UINT8_C( 1); }\r\n\r\n    return std::uint_fast16_t(r);\r\n  }\r\n\r\n  // Make a template specialization of msb_helper() for std::uint16_t.\r\n  template<>\r\n  std::uint_fast16_t msb_helper(std::uint16_t& u,\r\n                                std::uint16_t&,\r\n                                const std::uint_fast16_t)\r\n  {\r\n    std::uint_fast8_t r(0);\r\n\r\n    // Use O(log2[N]) binary-halving in an unrolled loop to find the msb.\r\n    if((u & UINT16_C(0xFF00)) != UINT16_C(0)) { u >>= 8; r |= UINT8_C(8); }\r\n    if((u & UINT16_C(0x00F0)) != UINT16_C(0)) { u >>= 4; r |= UINT8_C(4); }\r\n    if((u & UINT16_C(0x000C)) != UINT16_C(0)) { u >>= 2; r |= UINT8_C(2); }\r\n    if((u & UINT16_C(0x0002)) != UINT16_C(0)) { u >>= 1; r |= UINT8_C(1); }\r\n\r\n    return std::uint_fast16_t(r);\r\n  }\r\n\r\n  // Make a template specialization of msb_helper() for std::uint8_t.\r\n  template<>\r\n  std::uint_fast16_t msb_helper(std::uint8_t& u,\r\n                                std::uint8_t&,\r\n                                const std::uint_fast16_t)\r\n  {\r\n    std::uint_fast8_t r(0);\r\n\r\n    // Use O(log2[N]) binary-halving in an unrolled loop to find the msb.\r\n    if((u & UINT8_C(0xF0)) != UINT8_C(0)) { u >>= 4; r |= UINT8_C(4); }\r\n    if((u & UINT8_C(0x0C)) != UINT8_C(0)) { u >>= 2; r |= UINT8_C(2); }\r\n    if((u & UINT8_C(0x02)) != UINT8_C(0)) { u >>= 1; r |= UINT8_C(1); }\r\n\r\n    return std::uint_fast16_t(r);\r\n  }\r\n\r\n  template<typename ArithmeticType>\r\n  ArithmeticType power_of_two_helper(int p2)\r\n  {\r\n    if(p2 == 0)\r\n    {\r\n      return ArithmeticType(1);\r\n    }\r\n    else if(p2 < 0)\r\n    {\r\n      return ArithmeticType(1) / power_of_two_helper<ArithmeticType>(-p2);\r\n    }\r\n    else\r\n    {\r\n      // The variable xn stores the binary powers of x.\r\n      ArithmeticType the_result(((p2 % 2) != 0) ? ArithmeticType(2) : ArithmeticType(1));\r\n\r\n      ArithmeticType xn(2);\r\n\r\n      while((p2 /= 2) != 0)\r\n      {\r\n        // Square xn for each binary power.\r\n        xn *= xn;\r\n\r\n        const bool has_binary_power = ((p2 % 2) != 0);\r\n\r\n        if(has_binary_power)\r\n        {\r\n          // Multiply the result with each binary power contained in the exponent.\r\n          the_result *= xn;\r\n        }\r\n      }\r\n\r\n      return the_result;\r\n    }\r\n  }\r\n\r\n  template<typename UnsignedLargeType,\r\n           typename UnsignedSmallType = typename integer_type_helper<std::numeric_limits<UnsignedLargeType>::digits / 2>::exact_unsigned_type>\r\n  UnsignedSmallType lo_part(const UnsignedLargeType& lt)\r\n  {\r\n    static_assert(   (std::numeric_limits<UnsignedLargeType>::is_integer == true)\r\n                  && (std::numeric_limits<UnsignedLargeType>::is_signed  == false),\r\n                  \"The UnsignedLargeType for lo_part must be an unsigned integral type.\");\r\n\r\n    static_assert(   (std::numeric_limits<UnsignedSmallType>::is_integer == true)\r\n                  && (std::numeric_limits<UnsignedSmallType>::is_signed  == false),\r\n                  \"The UnsignedSmallType for lo_part must be an unsigned integral type.\");\r\n\r\n    return UnsignedSmallType(lt);\r\n  }\r\n\r\n  template<typename UnsignedLargeType,\r\n           typename UnsignedSmallType = typename integer_type_helper<std::numeric_limits<UnsignedLargeType>::digits / 2>::exact_unsigned_type>\r\n  UnsignedSmallType hi_part(const UnsignedLargeType& lt)\r\n  {\r\n    static_assert(   (std::numeric_limits<UnsignedLargeType>::is_integer == true)\r\n                  && (std::numeric_limits<UnsignedLargeType>::is_signed  == false),\r\n                  \"The UnsignedLargeType for hi_part must be an unsigned integral type.\");\r\n\r\n    static_assert(   (std::numeric_limits<UnsignedSmallType>::is_integer == true)\r\n                  && (std::numeric_limits<UnsignedSmallType>::is_signed  == false),\r\n                  \"The UnsignedSmallType for hi_part must be an unsigned integral type.\");\r\n\r\n    return UnsignedSmallType(lt >> std::numeric_limits<UnsignedSmallType>::digits);\r\n  }\r\n\r\n  template<typename UnsignedLargeType,\r\n           typename UnsignedSmallType = typename integer_type_helper<std::numeric_limits<UnsignedLargeType>::digits / 2>::exact_unsigned_type>\r\n  UnsignedLargeType make_large(const UnsignedSmallType& lo, const UnsignedSmallType& hi)\r\n  {\r\n    static_assert(   (std::numeric_limits<UnsignedLargeType>::is_integer == true)\r\n                  && (std::numeric_limits<UnsignedLargeType>::is_signed  == false),\r\n                  \"The UnsignedLargeType for make_large must be an unsigned integral type.\");\r\n\r\n    static_assert(   (std::numeric_limits<UnsignedSmallType>::is_integer == true)\r\n                  && (std::numeric_limits<UnsignedSmallType>::is_signed  == false),\r\n                  \"The UnsignedSmallType for make_large must be an unsigned integral type.\");\r\n\r\n    return UnsignedLargeType( (UnsignedLargeType(hi) << std::numeric_limits<UnsignedSmallType>::digits)\r\n                             | UnsignedLargeType(lo));\r\n  }\r\n\r\n  template<typename UnsignedSmallType,\r\n           typename UnsignedHalfType = typename integer_type_helper<std::numeric_limits<UnsignedSmallType>::digits / 2>::exact_unsigned_type>\r\n  void two_component_multiply(const UnsignedSmallType& u,\r\n                              const UnsignedSmallType& v,\r\n                                    UnsignedSmallType& result_lo,\r\n                                    UnsignedSmallType& result_hi)\r\n  {\r\n    // Multiply u * v, where u and v are both unsigned\r\n    // and both have 2^n bits. The result has 2*(2^n) bits.\r\n    // The result is stored in a pair of two unsigned integers,\r\n    // result_lo and result_hi.\r\n\r\n    // Use an elementary school multiplication algorithm.\r\n\r\n    // For example, multiply:\r\n    //   uint64_t * uint64_t --> uint128_t result,\r\n    // where result is stored in a (uint64_t, uint64_t) pair.\r\n\r\n    // The result of the multiplication of (u * v) is:\r\n    //   (u_hi_v_hi << n) + (uv_cross << (n/2)) + u_lo_v_lo,\r\n    // where\r\n    //   u_hi_v_hi = (u_hi * v_hi),\r\n    // and\r\n    //   uv_cross  = (u_lo * v_hi) + (u_hi * v_lo),\r\n    // and\r\n    //   u_lo_v_lo = (u_lo * v_lo).\r\n\r\n    // Care is taken to properly handle shifts and carries.\r\n\r\n    static_assert(   (std::numeric_limits<UnsignedSmallType>::is_integer == true)\r\n                  && (std::numeric_limits<UnsignedSmallType>::is_signed  == false),\r\n                  \"The UnsignedSmallType for two_component_multiply must be an unsigned integral type.\");\r\n\r\n    static_assert(   (std::numeric_limits<UnsignedHalfType>::is_integer == true)\r\n                  && (std::numeric_limits<UnsignedHalfType>::is_signed  == false),\r\n                  \"The UnsignedHalfType for two_component_multiply must be an unsigned integral type.\");\r\n\r\n    static_assert((std::numeric_limits<UnsignedHalfType>::digits * 2) == std::numeric_limits<UnsignedSmallType>::digits,\r\n                  \"The UnsignedSmallType for two_component_multiply must have exactly twice as many digits as the UnsignedHalfType.\");\r\n\r\n    typedef UnsignedSmallType local_unsigned_small_type;\r\n    typedef UnsignedHalfType  local_unsigned_half_type;\r\n\r\n    BOOST_CONSTEXPR_OR_CONST int digits_half = std::numeric_limits<local_unsigned_half_type>::digits;\r\n\r\n    const local_unsigned_half_type u_lo(static_cast<local_unsigned_half_type>(u));\r\n    const local_unsigned_half_type v_lo(static_cast<local_unsigned_half_type>(v));\r\n\r\n    const local_unsigned_half_type u_hi(static_cast<local_unsigned_half_type>(u >> digits_half));\r\n    const local_unsigned_half_type v_hi(static_cast<local_unsigned_half_type>(v >> digits_half));\r\n\r\n    const local_unsigned_small_type u_lo_v_lo(u_lo * local_unsigned_small_type(v_lo));\r\n    const local_unsigned_small_type u_hi_v_lo(u_hi * local_unsigned_small_type(v_lo));\r\n    const local_unsigned_small_type u_lo_v_hi(u_lo * local_unsigned_small_type(v_hi));\r\n\r\n    const local_unsigned_small_type uv_cross_lo =\r\n          local_unsigned_small_type(   local_unsigned_small_type(lo_part(u_lo_v_hi)))\r\n        + local_unsigned_small_type(   local_unsigned_small_type(lo_part(u_hi_v_lo))\r\n                                    +  local_unsigned_small_type(hi_part(u_lo_v_lo)));\r\n\r\n    const local_unsigned_small_type uv_cross_hi =\r\n          local_unsigned_small_type(   local_unsigned_small_type(hi_part(u_hi_v_lo)))\r\n        + local_unsigned_small_type(   local_unsigned_small_type(hi_part(u_lo_v_hi))\r\n                                    +  local_unsigned_small_type(hi_part(uv_cross_lo)));\r\n\r\n    result_hi = local_unsigned_small_type(local_unsigned_small_type(u_hi * local_unsigned_small_type(v_hi)) + uv_cross_hi);\r\n\r\n    result_lo = local_unsigned_small_type(  local_unsigned_small_type(uv_cross_lo << digits_half)\r\n                                          | local_unsigned_small_type(lo_part(u_lo_v_lo)));\r\n  }\r\n\r\n  template<typename UnsignedSmallType,\r\n           typename UnsignedHalfType = typename integer_type_helper<std::numeric_limits<UnsignedSmallType>::digits / 2>::exact_unsigned_type>\r\n  void two_component_divide(const UnsignedSmallType& u_lo,\r\n                            const UnsignedSmallType& u_hi,\r\n                            const UnsignedSmallType& v_lo,\r\n                                  UnsignedSmallType& result_lo,\r\n                                  UnsignedSmallType& result_hi)\r\n  {\r\n    // Divide the pair (u_lo, u_hi) in the numerator\r\n    // by v_lo in the denominator. The result is stored\r\n    // in the pair (result_lo, result_hi).\r\n\r\n    // Here the numerator has 2*(2^n) bits and the denominator\r\n    // has up to 2^n bits. The result has up to 2*(2^n) bits.\r\n\r\n    // For example, divide:\r\n    //   uint128_t numerator / uint64_t --> uint128_t result,\r\n    // where the both the numerator as well as the result are\r\n    // stored in a (uint64_t, uint64_t) pair.\r\n\r\n    // A simplified version of Knuth's long division algorithm\r\n    // is used. The loop-ordering of Knuth's algorithm has been\r\n    // reversed. Some internal loops of the algorithm have been\r\n    // manually unrolled to improve efficiency.\r\n\r\n    // The division algorithm is carried out with arrays\r\n    // of limbs having a type that is half as wide\r\n    // as the type of the input parameters.\r\n\r\n    // See also:\r\n    // D.E. Knuth, \"The Art of Computer Programming, Volume 2:\r\n    // Seminumerical Algorithms\", Addison-Wesley (1998),\r\n    // Section 4.3.1 Algorithm D and Exercise 16.\r\n\r\n    static_assert(   (std::numeric_limits<UnsignedSmallType>::is_integer == true)\r\n                  && (std::numeric_limits<UnsignedSmallType>::is_signed  == false),\r\n                  \"The UnsignedSmallType for two_component_divide must be an unsigned integral type.\");\r\n\r\n    static_assert(   (std::numeric_limits<UnsignedHalfType>::is_integer == true)\r\n                  && (std::numeric_limits<UnsignedHalfType>::is_signed  == false),\r\n                  \"The UnsignedHalfType for two_component_divide must be an unsigned integral type.\");\r\n\r\n    static_assert((std::numeric_limits<UnsignedHalfType>::digits * 2) == std::numeric_limits<UnsignedSmallType>::digits,\r\n                  \"The UnsignedSmallType for two_component_divide must have exactly twice as many digits as the UnsignedHalfType.\");\r\n\r\n    typedef UnsignedSmallType local_unsigned_small_type;\r\n    typedef UnsignedHalfType  local_unsigned_half_type;\r\n\r\n    std::array<local_unsigned_half_type, 4U + 1U> u_tmp =\r\n    {{\r\n      lo_part(u_lo),\r\n      hi_part(u_lo),\r\n      lo_part(u_hi),\r\n      hi_part(u_hi),\r\n      local_unsigned_half_type(0U)\r\n    }};\r\n\r\n    std::array<local_unsigned_half_type, 2U> v_tmp =\r\n    {{\r\n      lo_part(v_lo),\r\n      hi_part(v_lo)\r\n    }};\r\n\r\n    std::array<local_unsigned_half_type, 4U> result =\r\n    {{\r\n      local_unsigned_half_type(0U),\r\n      local_unsigned_half_type(0U),\r\n      local_unsigned_half_type(0U),\r\n      local_unsigned_half_type(0U)\r\n    }};\r\n\r\n    // Handling zero numerator and/or zero denominator\r\n    // has already been done by the function that calls\r\n    // this subroutine.\r\n\r\n    if(v_tmp[1U] == 0U)\r\n    {\r\n      // The denominator has one single limb.\r\n      // Use a simplified linear division algorithm.\r\n      // The loop has been unrolled.\r\n\r\n      result[3U] = u_tmp[3U] / v_tmp[0U];\r\n\r\n      local_unsigned_small_type val\r\n                  = local_unsigned_small_type(u_tmp[2U]) + local_unsigned_small_type(local_unsigned_small_type(local_unsigned_small_type(u_tmp[3U]) - local_unsigned_small_type(local_unsigned_small_type(v_tmp[0U]) * result[3U])) << std::numeric_limits<local_unsigned_half_type>::digits);\r\n      result[2U]  = lo_part(local_unsigned_small_type(val / local_unsigned_small_type(v_tmp[0U])));\r\n\r\n      val         = local_unsigned_small_type(u_tmp[1U]) + local_unsigned_small_type(local_unsigned_small_type(val - local_unsigned_small_type(local_unsigned_small_type(v_tmp[0U]) * result[2U])) << std::numeric_limits<local_unsigned_half_type>::digits);\r\n      result[1U]  = lo_part(local_unsigned_small_type(val / local_unsigned_small_type(v_tmp[0U])));\r\n\r\n      val         = local_unsigned_small_type(u_tmp[0U]) + local_unsigned_small_type(local_unsigned_small_type(val - local_unsigned_small_type(local_unsigned_small_type(v_tmp[0U]) * result[1U])) << std::numeric_limits<local_unsigned_half_type>::digits);\r\n      result[0U]  = lo_part(local_unsigned_small_type(val / local_unsigned_small_type(v_tmp[0U])));\r\n\r\n      result_lo = make_large<local_unsigned_small_type>(result[0U], result[1U]);\r\n      result_hi = make_large<local_unsigned_small_type>(result[2U], result[3U]);\r\n\r\n      return;\r\n    }\r\n\r\n    // Calculate the number of significant limbs in u.\r\n    std::uint_fast8_t sig_limbs_u = 4U;\r\n\r\n    for(std::uint_fast8_t i = std::uint_fast8_t(4U - 1U); ((std::int_fast8_t(i) >= std::int_fast8_t(0)) && (u_tmp[i] == 0U)); --i)\r\n    {\r\n      --sig_limbs_u;\r\n    }\r\n\r\n    // The result of the division is 0 if the\r\n    // denominator is larger than the numerator.\r\n\r\n    // The result of the division is 1 if the\r\n    // denominator is equal to the numerator.\r\n\r\n    // Check if the denominator is larger than\r\n    // or equal to the numerator.\r\n\r\n    // At this point in the subroutine, we know\r\n    // that v has exactly 2 significant limbs.\r\n\r\n    bool b_zero = false;\r\n\r\n    if(sig_limbs_u < 2U)\r\n    {\r\n      // The denominator is larger than the numerator.\r\n      // The result of the division is 0.\r\n      b_zero = true;\r\n    }\r\n    else if(sig_limbs_u == 2U)\r\n    {\r\n      const bool u1_v1_are_equal = (u_tmp[1U] <  v_tmp[1U]);\r\n\r\n      if(    u1_v1_are_equal\r\n         || (u1_v1_are_equal && (u_tmp[0U] < v_tmp[0U])))\r\n      {\r\n        // The denominator is larger than the numerator.\r\n        // The result of the division is 0.\r\n        b_zero = true;\r\n      }\r\n      else if(u1_v1_are_equal && (u_tmp[0U] == v_tmp[0U]))\r\n      {\r\n        // The denominator is equal to the numerator.\r\n        // The result of the division is 1.\r\n        result_lo = 1U;\r\n        result_hi = 0U;\r\n\r\n        return;\r\n      }\r\n    }\r\n\r\n    if(b_zero)\r\n    {\r\n      // The result is 0.\r\n      result_lo = 0U;\r\n      result_hi = 0U;\r\n\r\n      return;\r\n    }\r\n\r\n    // Now use the simplified version of Knuth's\r\n    // long division algorithm.\r\n\r\n    {\r\n      // Compute the normalization factor.\r\n\r\n      const local_unsigned_half_type norm =\r\n        lo_part(local_unsigned_small_type(local_unsigned_small_type(1U) << std::numeric_limits<local_unsigned_half_type>::digits) / (local_unsigned_small_type(v_tmp[1U]) + 1U));\r\n\r\n      if(norm != 1U)\r\n      {\r\n        // Step D1(b): Multiply u with the normalization.\r\n\r\n        local_unsigned_half_type carry(0U);\r\n\r\n        std::uint_fast8_t i;\r\n\r\n        for(i = 0U; i < sig_limbs_u; ++i)\r\n        {\r\n          const local_unsigned_small_type val(local_unsigned_small_type(local_unsigned_small_type(u_tmp[i]) * norm) + local_unsigned_small_type(carry));\r\n\r\n          u_tmp[i] = lo_part(val);\r\n          carry    = hi_part(val);\r\n        }\r\n\r\n        u_tmp[i] = carry;\r\n\r\n        // Step D1(c): Multiply v with the normalization.\r\n        // The loop has been unrolled.\r\n\r\n        local_unsigned_small_type val\r\n                  = local_unsigned_small_type(local_unsigned_small_type(v_tmp[0U]) * norm);\r\n        v_tmp[0U] = lo_part(val);\r\n\r\n        val       = local_unsigned_small_type(local_unsigned_small_type(v_tmp[1U]) * norm) + local_unsigned_small_type(hi_part(val));\r\n        v_tmp[1U] = lo_part(val);\r\n      }\r\n    }\r\n\r\n    // Steps D2 and D7.\r\n    for(std::uint_fast8_t j = 0U; j <= (sig_limbs_u - 2U); ++j)\r\n    {\r\n      // Step D3: Calculate q_guess.\r\n\r\n      // Here q_guess is the initial guess of the next\r\n      // iteration in the result of the long division.\r\n\r\n      const std::uint_fast8_t uj(sig_limbs_u - j);\r\n\r\n      const local_unsigned_small_type uj_ujm1(make_large<local_unsigned_small_type>(u_tmp[uj - 1U], u_tmp[uj]));\r\n\r\n      local_unsigned_small_type q_guess =\r\n        ((u_tmp[uj] == v_tmp[1U]) ? local_unsigned_small_type((std::numeric_limits<local_unsigned_half_type>::max)())\r\n                                  : local_unsigned_small_type(uj_ujm1 / local_unsigned_small_type(v_tmp[1U])));\r\n\r\n      // Decrease q_guess as needed.\r\n      for( ; ; --q_guess)\r\n      {\r\n        const local_unsigned_small_type val(uj_ujm1 - local_unsigned_small_type(q_guess * v_tmp[1U]));\r\n\r\n        if(hi_part(val) != 0U)\r\n        {\r\n          break;\r\n        }\r\n\r\n        if(local_unsigned_small_type(q_guess * v_tmp[0U]) <= make_large<local_unsigned_small_type>(u_tmp[uj - 2U], lo_part(val)))\r\n        {\r\n          break;\r\n        }\r\n\r\n        // If either of the two break statements above has\r\n        // been executed, then q_guess is not decremented.\r\n      }\r\n\r\n      // Step D4: Multiply and subtract.\r\n      // The loop has been unrolled.\r\n\r\n      std::array<local_unsigned_half_type, 2U + 1U> n_tmp;\r\n\r\n      std::uint_fast8_t borrow;\r\n\r\n      {\r\n        // Multiply.\r\n        local_unsigned_small_type val\r\n                  = local_unsigned_small_type(v_tmp[0U] * q_guess);\r\n        n_tmp[0U] = lo_part(val);\r\n\r\n        val       = local_unsigned_small_type(v_tmp[1U] * q_guess) + local_unsigned_small_type(hi_part(val));\r\n        n_tmp[1U] = lo_part(val);\r\n\r\n        n_tmp[2U] = hi_part(val);\r\n\r\n        // Subtract.\r\n        val            = local_unsigned_small_type(local_unsigned_small_type(u_tmp[uj - 2U]) - local_unsigned_small_type(n_tmp[0U]));\r\n        u_tmp[uj - 2U] = lo_part(val);\r\n        borrow         = ((hi_part(val) != 0U) ? 1U : 0U);\r\n\r\n        val            = local_unsigned_small_type(local_unsigned_small_type(u_tmp[uj - 1U]) - local_unsigned_small_type(n_tmp[1U])) - borrow;\r\n        u_tmp[uj - 1U] = lo_part(val);\r\n        borrow         = ((hi_part(val) != 0U) ? 1U : 0U);\r\n\r\n        val            = local_unsigned_small_type(local_unsigned_small_type(u_tmp[uj - 0U]) - local_unsigned_small_type(n_tmp[2U])) - borrow;\r\n        u_tmp[uj - 0U] = lo_part(val);\r\n        borrow         = ((hi_part(val) != 0U) ? 1U : 0U);\r\n      }\r\n\r\n      // Get the result data.\r\n      result[uj - 2U] = lo_part(q_guess);\r\n\r\n      // Step D5: Test the remainder.\r\n      if(borrow != 0U)\r\n      {\r\n        // Step D6: Add v to u and decrement the result.\r\n        // The loop has been unrolled.\r\n\r\n        local_unsigned_small_type val\r\n                       = local_unsigned_small_type(local_unsigned_small_type(u_tmp[uj - 2U]) + local_unsigned_small_type(n_tmp[0U]));\r\n        u_tmp[uj - 2U] = lo_part(val);\r\n\r\n        val            = local_unsigned_small_type(local_unsigned_small_type(u_tmp[uj - 1U]) + local_unsigned_small_type(n_tmp[1U])) + std::uint_fast8_t((hi_part(val) != 0U) ? 1U : 0U);\r\n        u_tmp[uj - 1U] = lo_part(val);\r\n\r\n        val            = local_unsigned_small_type(local_unsigned_small_type(u_tmp[uj - 0U]) + local_unsigned_small_type(n_tmp[2U])) + std::uint_fast8_t((hi_part(val) != 0U) ? 1U : 0U);\r\n        u_tmp[uj - 0U] = lo_part(val);\r\n\r\n        u_tmp[uj - 2U] += std::uint_fast8_t((hi_part(val) != 0U) ? 1U : 0U);\r\n\r\n        --result[uj - 2U];\r\n      }\r\n    }\r\n\r\n    // Compose the low and high parts of the result.\r\n    result_lo = make_large<local_unsigned_small_type>(result[0U], result[1U]);\r\n    result_hi = make_large<local_unsigned_small_type>(result[2U], result[3U]);\r\n  }\r\n\r\n  } } } // namespace boost::fixed_point::detail\r\n  //! \\endcond // DETAIL\r\n\r\n#endif // FIXED_POINT_DETAIL_2015_05_23_HPP_\r\n", "meta": {"hexsha": "42851248def5c12d4ca11dd14b14dabc64b230f1", "size": 40648, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/fixed_point/detail/fixed_point_detail.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/detail/fixed_point_detail.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/detail/fixed_point_detail.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": 42.9682875264, "max_line_length": 287, "alphanum_fraction": 0.6145689825, "num_tokens": 9995, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.3055907023201637}}
{"text": "/*\n * workModel.hh\n *\n *  Created on: May 4, 2015\n *      Author: sunayana_ghosh\n */\n/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */\n/*                                                                           */\n/*  This file is part of the library KASKADE 7                               */\n/*    see http://www.zib.de/projects/kaskade7-finite-element-toolbox         */\n/*                                                                           */\n/*  Copyright (C) 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#ifndef KASKADE_TIMESTEPPING_EULERSDC_WORKMODEL_HH_\n#define KASKADE_TIMESTEPPING_EULERSDC_WORKMODEL_HH_\n\n//includes from current project\n#include \"norm.hh\"\n#include \"util.hh\"\n\n//includes from c, c++\n#include <cmath>\n#include <iostream>\n#include <vector>\n\n//includes from boost\n#include <boost/math/special_functions/round.hpp>\n#include <boost/math/tools/minima.hpp>   //used for Brent's method to compute minima of a function\n\n//includes from DUNE\n#include \"dune/common/dynmatrix.hh\"\n#include \"dune/common/dynvector.hh\"\n\nnamespace Kaskade {\n  //========================================================================================\n  //     Implementation for enum class WorkModelType\n  //========================================================================================\n\n  /**\n   * \\ingroup eulerSDC\n   * \\brief Enum class to define the norm type is class Norm.\n   */\n\n  //--C++11 strongly typed enums.\n  enum class WorkModelType {\n    ITERATION,      //!< ITERATION\n    FED             //!< FED\n  };\n\n  /**\n   * \\ingroup eulerSDC\n   * \\brief Abstract base class for different work models\n   *\n   * This class represents a generic base class for an arbitrary work model\n   */\n\n  //================================================================================================\n  //      Implementation of the abstract base class WorkModel to compute the local tolerances.\n  //================================================================================================\n\n  /**\n   * \\ingroup eulerSDC\n   * \\brief Abstract base class WorkModel which provides an interface for different kinds of work models for\n   * computation of the cost function, maximum number of iterations and local tolerances.\n   */\n\n   template<class Vector, class Norm, class Utils>\n   class WorkModel\n   {\n   public:\n     using field_type = typename Vector::value_type;\n     using RealVector = Dune::DynamicVector<double>;\n     using RealMatrix = Dune::DynamicMatrix<double>;\n\n\n\n     //pure virtual functions\n\n       /**\n        * \\ingroup eulerSDC\n        * \\brief Pure virtual function implemented in derived classes for different work models. Computes the\n        *        local tolerances for every time point and every iteration step given global tolerance.\n        *\n        * @param yPrev      An (i-1)-th iterative approximation to the solution using sdc Iteration step.\n        * @param yCurrent   An i-th iterative approximation to the solution using sdc Iteration step.\n        * @param yNext      An (i+1)-th iterative approximation to the solution using sdc Iteration step.\n        * @return Returns the matrix of local tolerances.\n        */\n       virtual RealMatrix const& computeLocalTolerances(std::vector<Vector> const& yPrev,\n                                                        std::vector<Vector> const& yCurrent,\n                                                        std::vector<Vector> const& yNext) = 0;\n\n       /**\n        * \\ingroup eulerSDC\n        *\n        * @param yPrev\n        * @param yCurrent\n        * @param rho\n        *\n        * @return\n        */\n       virtual field_type lowerBoundIterJ(std::vector<Vector> const& yPrev,\n                                          std::vector<Vector> const& yCurrent,\n                                          field_type rho) = 0;\n\n\n       //virtual destructor\n       virtual ~WorkModel() {}\n   };\n\n   //========================================================================================================\n   //             Implementation of the derived class Iteration representing the iteration work model.\n   //========================================================================================================\n\n   template<class Vector, class Norm, class Utils>\n   class Iteration : public WorkModel<Vector, Norm, Utils>\n   {\n   public:\n     using field_type = typename Vector::value_type;\n     using RealVector = Dune::DynamicVector<double>;\n     using RealMatrix = Dune::DynamicMatrix<double>;\n\n     //constructor for the derived class Iteration\n     Iteration(field_type tol_,\n               std::vector<Vector> const& y0_, std::vector<Vector> const& y1_,\n               Norm& norm_, Utils& util_,\n               RealVector const& timePts_, RealMatrix const& integrationMatrix_,\n               field_type tolNewton_, int maxIterNewton_,\n               field_type rhoit_, int mmin_);\n\n     // function to compute cost\n     /**\n      * \\ingroup eulerSDC\n      * @param yPrev\n      * @param yCurrent\n      * @param yNext\n      * @param tolMat\n      *\n      * @return\n      */\n\n     field_type computeCost(std::vector<Vector> const& yPrev,\n                            std::vector<Vector> const& yCurrent,\n                            std::vector<Vector> const& yNext,\n                            RealMatrix const& tolMat);\n\n\n     /**\n      * \\ingroup eulerSDC\n      * @param yPrev\n      * @param yCurrent\n      * @param yNext\n      * @param rho\n      *\n      * @return\n      */\n     field_type getIterJ(std::vector<Vector> const& yPrev,\n                         std::vector<Vector> const& yCurrent,\n                         std::vector<Vector> const& yNext,\n                         field_type rho);\n\n\n     virtual RealMatrix const& computeLocalTolerances(std::vector<Vector> const& yPrev,\n                                                      std::vector<Vector> const& yCurrent,\n                                                      std::vector<Vector> const& yNext)\n     {\n       //To compute optimal local tolerances we first need the value of maxSDCIterations\n       auto rho = util.sdcContractionFactor(yPrev, yCurrent, yNext, norm);\n       //compute maxSDCIterations\n       auto maxSDCIterations = getIterJ(yPrev, yCurrent, yNext, rho);\n       //then we need to compute the value of mu which depends on maxSDCIterations\n       auto mu = computeMu(yPrev, yCurrent, rho, maxSDCIterations, nIntervals, tol, norm);\n       //compute the value of alphaVec\n       auto alphaVec = util.computeAlphaVec(timePts, integrationMatrix, yPrev, yCurrent, yNext);\n       //initialize the matrix\n       int itJ = (int) maxSDCIterations;\n       xijMat = RealMatrix(nIntervals, itJ, 0.0);\n       for (auto i = 0; i < nIntervals; ++i)\n       {\n         for (auto j = 0; j < itJ; ++j)\n         {\n           xijMat[i][j] = -1/(mu * std::pow(rho, itJ-1-j) * alphaVec[i]);\n         }\n       }\n       return xijMat;\n     }\n\n\n     //function computes the lower bound of maxSDCIterations\n     virtual field_type lowerBoundIterJ(std::vector<Vector> const& yPrev,\n                                        std::vector<Vector> const& yCurrent,\n                                        field_type rho)\n     {\n       auto val = Kaskade::normVecDiff(yPrev,yCurrent,norm);\n       auto lboundJ = std::log((1-rho) * tol / val) / std::log(rho);\n       return boost::math::round(lboundJ);\n     }\n\n\n     //delete later\n     field_type static f (std::vector<Vector> const& yPrev,\n         std::vector<Vector> const& yCurrent,\n         std::vector<Vector> const& yNext,\n         double rho)\n       {\n         auto yTotal = yPrev[0] + yCurrent[0] + yNext[0];\n         return (yTotal[0] + yTotal[1]) * rho;\n       }\n\n     //destructor\n     virtual ~Iteration(){}\n\n   private:\n     field_type tol;\n     std::vector<Vector> y0;\n     std::vector<Vector> y1;\n     Norm norm;\n     Utils util;\n     field_type normy01;\n     RealVector timePts;\n     RealMatrix integrationMatrix;\n     int nIntervals;\n     field_type maxPrecisionBrent = 20;  //computation with 20 bit precision\n     field_type rhoit;\n     int mmin;\n     RealMatrix xijMat;\n\n     //private cost function\n\n     field_type static costFunction(std::vector<Vector> const& yPrev,\n                                    std::vector<Vector> const& yCurrent,\n                                    std::vector<Vector> const& yNext,\n                                    field_type maxSDCIterations,\n                                    Norm& norm,\n                                    Utils& util,\n                                    field_type normy01,\n                                    RealVector const& timePts,\n                                    RealMatrix const& integrationMatrix,\n                                    int nIntervals, field_type tol);\n\n\n     field_type static computeMu(std::vector<Vector> const& yPrev,\n                          std::vector<Vector> const& yCurrent,\n                          field_type rho,\n                          field_type maxSDCIterations,\n                          int nIntervals,\n                          field_type tol,\n                          Norm& norm);\n\n     field_type computeDerivativeMu(std::vector<Vector> const& yPrev,\n                                    std::vector<Vector> const& yCurrent,\n                                    field_type rho,\n                                    field_type maxSDCIterations);\n\n     field_type derivativeCostFunction(std::vector<Vector> const& yPrev,\n                                       std::vector<Vector> const& yCurrent,\n                                       field_type rho,\n                                       field_type alphaProd,\n                                       field_type c,\n                                       field_type maxSDCIterations);\n\n     //compute product of entries of alphaVec\n     field_type static computeProduct(RealVector const& alpha);\n\n\n     //This method is based on the ***assumption*** that cost function is monotonically decreasing\n     field_type computeIterJ(std::vector<Vector> const& yPrev,\n                       std::vector<Vector> const& yCurrent,\n                       std::vector<Vector> const& yNext,\n                       field_type rho);\n\n\n   };\n\n\n   //=======================================================================================================\n   //   Implementation of the derived class FiniteElementDiscretization representing the FED work model.\n   //======================================================================================================\n\n   template<class Vector, class Norm, class Utils>\n   class FiniteElementDiscretization : public WorkModel<Vector, Norm, Utils>\n   {\n   public:\n     using field_type = typename Vector::value_type;\n     using RealVector = Dune::DynamicVector<double>;\n     using RealMatrix = Dune::DynamicMatrix<double>;\n\n\n     //constructor for the derived class FiniteElementDiscretization\n     FiniteElementDiscretization(field_type tol_,\n                                 std::vector<Vector> const& y0_, std::vector<Vector> const& y1_,\n                                 Norm& norm_, Utils& util_,\n                                 RealVector const& timePts_, RealMatrix const& integrationMatrix_,\n                                 int dim_);\n\n\n     //function to compute cost\n     //(cannot be a pure virtual function since the parameters are different for different work models.)\n     field_type computeCost(RealMatrix const& tolMat);\n\n     field_type getIterJ(std::vector<Vector> const& yPrev,\n                         std::vector<Vector> const& yCurrent,\n                         field_type rho);\n\n     virtual RealMatrix const& computeLocalTolerances(std::vector<Vector> const& yPrev,\n                                                      std::vector<Vector> const& yCurrent,\n                                                      std::vector<Vector> const& yNext)\n     {\n       field_type d1 = 0.0;\n       field_type d2 = -1.0 / ((double) dim + 1.0);\n       auto rho = util.sdcContractionFactor(yPrev, yCurrent, yNext, norm);\n       //std::cout << \"rho = \" <<  rho << std::endl;\n       //compute max sdc iterations\n       maxSDCIterations = getIterJ(yPrev, yCurrent, rho);\n       auto alphaVec = util.computeAlphaVec(timePts, integrationMatrix, yPrev, yCurrent, yNext);\n       auto lambda = computeLambda(yPrev, yCurrent, yNext, maxSDCIterations);\n       //std::cout << \"lambda = \" << lambda << std::endl;\n       //initialize the matrix\n       int itJ = (int) maxSDCIterations;\n       xijMat = RealMatrix(nIntervals, itJ, 0.0);\n       for (auto i = 0; i < nIntervals; ++i)\n       {\n         auto val = std::pow(alphaVec[i], d2);\n         for (auto j = 0; j < itJ; ++j)\n         {\n           d1 = (maxSDCIterations-1-j)/(d2);\n           xijMat[i][j] = lambda * std::pow(rho, d1) * val;\n         }\n       }\n       return xijMat;\n     }\n\n\n     //function computes the lower bound of maxSDCIterations\n     virtual field_type lowerBoundIterJ(std::vector<Vector> const& yPrev,\n                                        std::vector<Vector> const& yCurrent,\n                                        field_type rho)\n     {\n       auto val = Kaskade::normVecDiff(yPrev, yCurrent, norm);\n       auto lboundJ = std::log((1-rho)*tol/val)/std::log(rho);\n       return boost::math::round(lboundJ);\n     }\n\n\n     //destructor\n     virtual ~FiniteElementDiscretization(){}\n\n   private:\n     field_type tol;\n     std::vector<Vector> y0;\n     std::vector<Vector> y1;\n     Norm norm;\n     field_type normy01;\n     Utils util;\n     RealVector timePts;\n     RealMatrix integrationMatrix;\n     int nIntervals;\n     int dim;\n     field_type maxSDCIterations;\n     RealMatrix xijMat;\n\n     //private methods\n     //computes A or B depending on the norm\n     field_type computeA(std::vector<Vector> const& yPrev,\n                         std::vector<Vector> const& yCurrent,\n                         std::vector<Vector> const& yNext);\n\n     field_type computeLambda(std::vector<Vector> const& yPrev,\n                              std::vector<Vector> const& yCurrent,\n                              std::vector<Vector> const& yNext,\n                              field_type maxSDCIterations);\n   };\n\n   //=================================================================================================\n   //   FUNCTION DEFINITION BEGINS FROM HERE\n   //=================================================================================================\n\n   //=================================================================================================\n   //   ITERATION  WORKMODEL\n   //=================================================================================================\n\n   //=================================================================================================\n   //   Constructor for the class Iteration\n   //=================================================================================================\n\n   template<class Vector, class Norm, class Utils>\n   Iteration<Vector, Norm, Utils>::Iteration(field_type tol_,\n               std::vector<Vector> const& y0_, std::vector<Vector> const& y1_,\n               Norm& norm_, Utils& util_,\n               RealVector const& timePts_, RealMatrix const& integrationMatrix_,\n               field_type tolNewton_, int maxPrecisionBrent_,\n               field_type rhoit_, int mmin_)\n               : tol(tol_), y0(y0_), y1(y1_),\n                 norm(norm_), util(util_), normy01(Kaskade::normVecDiff(y0,y1,norm)),\n                 timePts(timePts_), integrationMatrix(integrationMatrix_), nIntervals(timePts.size()-1),\n                 maxPrecisionBrent(maxPrecisionBrent_),\n                 rhoit(rhoit_), mmin(mmin_){}\n\n   //=================================================================================================\n   //   Public member function for Iteration WorkModel to compute total cost.\n   //=================================================================================================\n\n   template<class Vector, class Norm, class Utils>\n   typename Vector::value_type Iteration<Vector, Norm, Utils>::computeCost(std::vector<Vector> const& yPrev,\n                                                                           std::vector<Vector> const& yCurrent,\n                                                                           std::vector<Vector> const& yNext,\n                                                                           RealMatrix const& tolMat)\n   {\n     //initialize the total cost\n     field_type totalCost = 0;\n     //compute SDC contraction factor\n     auto rho = util.sdcContractionFactor(yPrev, yCurrent, yNext, norm);\n     //compute c = log(|y1-y0|)\n     auto c = std::log(normy01);\n     //compute the constant k = -mmin * log(rhoit)\n     auto k = -mmin * std::log(rhoit);\n     //dimensions of the tolerance matrix\n     auto rows = tolMat.rows();\n     auto cols = tolMat.cols();\n     for (auto i = 0u; i < rows; ++i)\n     {\n       for (auto j = 0u; j < cols; ++j)\n       {\n         totalCost += std::max(k, c - std::log(tolMat[i][j]/std::pow(rho,j)));\n       }\n     }\n     return totalCost;\n   }\n\n   //=================================================================================================\n   //   Public member function for Iteration WorkModel to get the maxSDCIterations.\n   //=================================================================================================\n   template<class Vector, class Norm, class Utils>\n   typename Vector::value_type Iteration<Vector, Norm, Utils>::getIterJ(std::vector<Vector> const& yPrev,\n                                                                        std::vector<Vector> const& yCurrent,\n                                                                        std::vector<Vector> const& yNext,\n                                                                        field_type rho)\n   {\n     auto maxSDCIterations = computeIterJ(yPrev, yCurrent, yNext, rho);\n     return boost::math::round(maxSDCIterations);\n   }\n\n\n   //=================================================================================================\n   //   Private member function for Iteration WorkModel for the costFunction.\n   //=================================================================================================\n\n\n   //make it a static function, and do not use any private member variables.\n   template<class Vector, class Norm, class Utils>\n   typename Vector::value_type Iteration<Vector, Norm, Utils>::costFunction(std::vector<Vector> const& yPrev,\n                                                                            std::vector<Vector> const& yCurrent,\n                                                                            std::vector<Vector> const& yNext,\n                                                                            field_type maxSDCIterations,\n                                                                            Norm& norm,\n                                                                            Utils& util,\n                                                                            field_type normy01,\n                                                                            RealVector const& timePts,\n                                                                            RealMatrix const& integrationMatrix,\n                                                                            int nIntervals,\n                                                                            field_type tol)\n   {\n     //compute SDC contraction factor\n     auto rho = util.sdcContractionFactor(yPrev, yCurrent, yNext, norm);\n     //compute c = log(|y1-y0|)\n     auto c = std::log(normy01);\n     //compute mu\n     auto mu = computeMu(yPrev, yCurrent, rho, maxSDCIterations, nIntervals, tol, norm);\n     auto alphaVec = util.computeAlphaVec(timePts, integrationMatrix, yPrev, yCurrent, yNext);\n     auto alphaProd = computeProduct(alphaVec);\n     auto cost = nIntervals * c + nIntervals * maxSDCIterations * std::log(rho) + nIntervals * std::log(-mu) + std::log(alphaProd);\n     return cost;\n   }\n\n\n   //==========================================================================================================\n   //   Private member function for Iteration WorkModel for computing the mu function as described in the paper\n   //==========================================================================================================\n   template<class Vector, class Norm, class Utils>\n   typename Vector::value_type Iteration<Vector, Norm, Utils>::computeMu(std::vector<Vector> const& yPrev,\n                                                                         std::vector<Vector> const& yCurrent,\n                                                                         field_type rho,\n                                                                         field_type maxSDCIterations,\n                                                                         int nIntervals,\n                                                                         field_type tol,\n                                                                         Norm& norm)\n   {\n     auto mu = -((1-rho) * (maxSDCIterations - 1) * nIntervals)/((1-rho) * tol - std::pow(rho, maxSDCIterations) * Kaskade::normVecDiff(yPrev,yCurrent,norm));\n     return mu;\n   }\n\n   //========================================================================================================================\n   //   Private member function for Iteration WorkModel for computing the derivative of mu function as described in the paper\n   //========================================================================================================================\n   template<class Vector, class Norm, class Utils>\n   typename Vector::value_type Iteration<Vector, Norm, Utils>::computeDerivativeMu(std::vector<Vector> const& yPrev,\n                                                                                   std::vector<Vector> const& yCurrent,\n                                                                                   field_type rho,\n                                                                                   field_type maxSDCIterations)\n   {\n     auto val = Kaskade::normVecDiff(yPrev,yCurrent,norm);\n     auto rhoJ = std::pow(rho, maxSDCIterations);\n     auto dervMu = nIntervals * (1-rho) *\n         (-(1-rho) * tol + val * rhoJ * (1 - (maxSDCIterations - 1) * std::log(rho)))/\n         (std::pow((rhoJ * val - (1-rho) * tol), 2));\n     return dervMu;\n   }\n\n   //========================================================================================================================\n   //   Private member function for Iteration WorkModel for computing the derivative of cost Function\n   //========================================================================================================================\n   template<class Vector, class Norm, class Utils>\n   typename Vector::value_type Iteration<Vector, Norm, Utils>::derivativeCostFunction(std::vector<Vector> const& yPrev,\n                                                                                      std::vector<Vector> const& yCurrent,\n                                                                                      field_type rho,\n                                                                                      field_type alphaProd,\n                                                                                      field_type c,\n                                                                                      field_type maxSDCIterations)\n   {\n\n     auto mu = computeMu(yPrev, yCurrent, rho, maxSDCIterations, nIntervals, tol, norm);\n     auto dervMu = computeDerivativeMu(yPrev, yCurrent, rho, maxSDCIterations);\n     auto dervCost = nIntervals * c + nIntervals * (2*maxSDCIterations - 1) * std::log(rho) + std::log(alphaProd)\n                     + nIntervals * std::log(-mu) + nIntervals * (maxSDCIterations - 1) * dervMu/mu;\n     return dervCost;\n   }\n\n   //==========================================================================================================================\n   //   Private member function for Iteration WorkModel for computing the product of alphaVector where all entries are positive\n   //==========================================================================================================================\n   template<class Vector, class Norm, class Utils>\n   typename Vector::value_type Iteration<Vector, Norm, Utils>::computeProduct(RealVector const& alpha)\n   {\n     field_type alphaProd = 1;\n     for(auto i = 0u; i < alpha.size(); ++i)\n       alphaProd *= alpha[i];\n\n     return alphaProd;\n   }\n\n   //============================================================================================\n   //   Private member function for Iteration WorkModel for computing maxSDCIterations\n   //============================================================================================\n\n//   //Use Brent's method to compute the minimum of the cost function\n//   template<class Vector, class Norm, class Utils>\n//   typename Vector::value_type Iteration<Vector, Norm, Utils>::computeIterJ(std::vector<Vector> const& yPrev,\n//                                                                            std::vector<Vector> const& yCurrent,\n//                                                                            std::vector<Vector> const& yNext,\n//                                                                            field_type rho)\n//   {\n//     using Result = std::pair<double, double>;\n//     //compute lower bound of maxSDCIterations to give as starting value for to Brent's method\n//     field_type lbmaxSDCIterations = lowerBoundIterJ(yPrev, yCurrent, rho);\n//     //initialize interval where the minima is searched\n//     field_type left = lbmaxSDCIterations;\n//     //initialize the lower bound on maxSDCIterations as input guess.\n//     //auto func = std::bind(f, yPrev, yCurrent, yNext, std::placeholders::_1);\n//     auto func = std::bind(costFunction, yPrev, yCurrent, yNext, std::placeholders::_1, norm, util, normy01,\n//                           timePts, integrationMatrix, nIntervals, tol);\n//     Result soln = boost::math::tools::brent_find_minima(func, left, left+6, maxPrecisionBrent);\n//\n//     return soln.first;\n//   }\n\n   //Numeric method to find minimia of the function\n   template<class Vector, class Norm, class Utils>\n   typename Vector::value_type Iteration<Vector, Norm, Utils>::computeIterJ(std::vector<Vector> const& yPrev,\n                                                                            std::vector<Vector> const& yCurrent,\n                                                                            std::vector<Vector> const& yNext,\n                                                                            field_type rho)\n     {\n     //compute lower bound of maxSDCIterations\n     field_type lbmaxSDCIterations = lowerBoundIterJ(yPrev, yCurrent, rho);\n     field_type maxSDCIterations = lbmaxSDCIterations + 1;\n     //compute the cost at lbmaxSDCIterations\n     field_type minCost = costFunction(yPrev, yCurrent, yNext, lbmaxSDCIterations, norm, util, normy01,\n                                       timePts, integrationMatrix, nIntervals, tol);\n     field_type val = costFunction(yPrev, yCurrent, yNext, maxSDCIterations, norm, util, normy01,\n                                   timePts, integrationMatrix, nIntervals, tol);\n     while(val > minCost)\n     {\n       minCost = val;\n       maxSDCIterations++;\n       val = costFunction(yPrev, yCurrent, yNext, maxSDCIterations, norm, util, normy01,\n                          timePts, integrationMatrix, nIntervals, tol);\n     }\n     return maxSDCIterations;\n     }\n\n\n\n   //=================================================================================================\n   //   FINITE ELEMENT DISCRETIZATION  WORKMODEL\n   //=================================================================================================\n\n   //=================================================================================================\n   //   Constructor for the class FiniteElementDiscretization\n   //=================================================================================================\n   template<class Vector, class Norm, class Utils>\n   FiniteElementDiscretization<Vector, Norm, Utils>::FiniteElementDiscretization(field_type tol_,\n                                    std::vector<Vector> const& y0_, std::vector<Vector> const& y1_,\n                                    Norm& norm_, Utils& util_,\n                                    RealVector const& timePts_, RealMatrix const& integrationMatrix_,\n                                    int dim_)\n                                    : tol(tol_),\n                                      y0(y0_), y1(y1_), norm(norm_), normy01(Kaskade::normVecDiff(y0, y1, norm)),\n                                      util(util_),\n                                      timePts(timePts_), integrationMatrix(integrationMatrix_), nIntervals(timePts.size()-1),\n                                      dim(dim_){}\n\n   //========================================================================================================\n   //   Public member function computeCost for the class FiniteElementDiscretization, computes the total cost\n   //========================================================================================================\n   template<class Vector, class Norm, class Utils>\n   typename Vector::value_type FiniteElementDiscretization<Vector, Norm, Utils>::computeCost(RealMatrix const& tolMat)\n   {\n     //initialize the total cost\n     field_type totalCost = 0.0;\n     //dimensions of the tolerance matrix\n     auto rows = tolMat.rows();\n     auto cols = tolMat.cols();\n     for (auto i = 0u; i < rows; ++i)\n     {\n       for (auto j = 0u; j < cols; ++j)\n         totalCost += 1/std::pow(tolMat[i][j], dim);\n     }\n     return totalCost;\n   }\n\n\n   //===========================================================================================================\n   //   Public member function getIterJ for the class FiniteElementDiscretization, returns the maxSDCIterations\n   //===========================================================================================================\n   template<class Vector, class Norm, class Utils>\n   typename Vector::value_type FiniteElementDiscretization<Vector, Norm, Utils>::getIterJ(std::vector<Vector> const& yPrev,\n                                                                                          std::vector<Vector> const& yCurrent,\n                                                                                          field_type rho)\n   {\n     auto val = Kaskade::normVecDiff(yPrev, yCurrent, norm);\n     maxSDCIterations = (dim + 1)/(std::log(rho)) * std::log((1-rho)*tol / val);\n\n     return boost::math::round(maxSDCIterations);\n   }\n\n   //===============================================================================================================\n   //   Private member function for FiniteElementDiscretization WorkModel for computing A or B depending on the norm\n   //===============================================================================================================\n   template<class Vector, class Norm, class Utils>\n   typename Vector::value_type FiniteElementDiscretization<Vector, Norm, Utils>::computeA(std::vector<Vector> const& yPrev,\n                                                                                          std::vector<Vector> const& yCurrent,\n                                                                                          std::vector<Vector> const& yNext)\n   {\n     //compute alphaVec\n     auto alphaVec = util.computeAlphaVec(timePts, integrationMatrix, yPrev, yCurrent, yNext);\n     //initialize alphaTildeVec\n     auto alphaTildeVec = RealVector(alphaVec.size(), 0.0);\n     //casting dim/(dim + 1) to double\n     double d = ((double) dim)/((double) dim + 1);\n     field_type sumAlphaTilde = 0.0;\n     //compute alphaTildeVec and A the sum of alphaTilde\n     for (auto i = 0u; i < alphaVec.size(); ++i)\n     {\n       alphaTildeVec[i] = std::pow(alphaVec[i], d);\n       sumAlphaTilde += alphaTildeVec[i];\n     }\n     return sumAlphaTilde;\n   }\n\n   //====================================================================================================================\n   //   Private member function for FiniteElementDiscretization WorkModel for computing lambda as described in the paper.\n   //====================================================================================================================\n   template<class Vector, class Norm, class Utils>\n   typename Vector::value_type FiniteElementDiscretization<Vector, Norm, Utils>::computeLambda\n                                                                           (std::vector<Vector> const& yPrev,\n                                                                            std::vector<Vector> const& yCurrent,\n                                                                            std::vector<Vector> const& yNext,\n                                                                            field_type maxSDCIterations)\n   {\n     //compute rho, sdc-contraction factor\n     auto rho = util.sdcContractionFactor(yPrev, yCurrent, yNext, norm);\n     //casting\n     double d = ((double) dim)/((double) dim + 1);\n     field_type tildeRho = std::pow(rho, d);\n     auto sumAlphaTilde = computeA(yPrev, yCurrent, yNext);\n     auto val = Kaskade::normVecDiff(yPrev, yCurrent, norm);\n     auto lambda = ((1-rho) * tol - val * std::pow(rho, maxSDCIterations)) * (1 - tildeRho) / ((1 - rho) * (1 - std::pow(tildeRho, maxSDCIterations)) * sumAlphaTilde);\n\n     return lambda;\n   }\n\n} //end namespace Kaskade\n\n#endif /* KASKADE_TIMESTEPPING_EULERSDC_WORKMODEL_HH_ */\n", "meta": {"hexsha": "a58b2e72397f88c3587715233c3af94e8a00a76e", "size": 34361, "ext": "hh", "lang": "C++", "max_stars_repo_path": "Kaskade/timestepping/eulerSDC/workModel.hh", "max_stars_repo_name": "chenzongxiong/streambox", "max_stars_repo_head_hexsha": "76f95780d1bf6c02731e39d8ac73937cea352b95", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2019-07-03T14:03:31.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-19T10:18:49.000Z", "max_issues_repo_path": "Kaskade/timestepping/eulerSDC/workModel.hh", "max_issues_repo_name": "chenzongxiong/streambox", "max_issues_repo_head_hexsha": "76f95780d1bf6c02731e39d8ac73937cea352b95", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2020-02-17T12:01:30.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-09T22:02:33.000Z", "max_forks_repo_path": "Kaskade/timestepping/eulerSDC/workModel.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": 49.1573676681, "max_line_length": 167, "alphanum_fraction": 0.4633450714, "num_tokens": 6532, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5926665999540698, "lm_q2_score": 0.5156199157230156, "lm_q1q2_score": 0.30559070232016367}}
{"text": "#define PY_ARRAY_UNIQUE_SYMBOL libpreviewer_ARRAY_API\n\n#include <iostream>\n#include <boost/python.hpp>\n#include <pyboostcvconverter/pyboostcvconverter.hpp>\n\nnamespace libpreviewer {\n\n    using namespace boost::python;\n\n    std::ostream& operator<<(std::ostream& os, const boost::python::object& o) {\n        return os << boost::python::extract<std::string>(boost::python::str(o))();\n    }\n\n    class Projector {\n    private:\n        double scale;\n        double imageMidWidth;\n        double imageMidHeight;\n        int previewWidth;\n        int previewHeight;\n        cv::Mat R_Kinv;\n        cv::Mat mapX;\n        cv::Mat mapY;\n\n        /**\n         * Map backward the final preview image pixel (x,y) to the \n         * original equirectangular coords (u,v)\n         */\n        void mapBackward(double x, double y, double& u, double& v) {\n            double x_ = R_Kinv.at<double>(0,0) * x + R_Kinv.at<double>(0,1) * y + R_Kinv.at<double>(0,2);\n            double y_ = R_Kinv.at<double>(1,0) * x + R_Kinv.at<double>(1,1) * y + R_Kinv.at<double>(1,2);\n            double z_ = R_Kinv.at<double>(2,0) * x + R_Kinv.at<double>(2,1) * y + R_Kinv.at<double>(2,2);\n\n            // project on a spherical map\n\n            // DEBUG\n            // std::cout << \"(x,y,z) = \" << \"(\" << x_ << \", \" << y_ << \", \" << z_ << \")\" << std::endl;\n            // ENDDEBUG\n\n            u = scale * atan2f(x_, z_) + imageMidWidth;\n            v = scale * ((M_PI / 2.0) - acosf(y_ / sqrtf(x_ * x_ + y_ * y_ + z_ * z_))) + imageMidHeight;\n        }\n\n    public:\n        Projector(int _imageWidth, int _imageHeight, int _previewWidth, int _previewHeight, cv::Mat _R_Kinv) : \n            imageMidWidth(static_cast<double>(_imageWidth)/2),\n            imageMidHeight(static_cast<double>(_imageHeight)/2),\n            previewWidth(_previewWidth),\n            previewHeight(_previewHeight),\n            R_Kinv(_R_Kinv) {\n                scale = imageMidWidth / M_PI;\n\n                // DEBUG\n                // std::cout << std::endl;\n                // std::cout << \"scale = \" << scale << std::endl;\n                // std::cout << \"R_Kinv[0] = \" << R_Kinv.at<double>(0,0) << \", \" << R_Kinv.at<double>(0,1) << \", \" << R_Kinv.at<double>(0,2) << std::endl;\n                // std::cout << \"R_Kinv[1] = \" << R_Kinv.at<double>(1,0) << \", \" << R_Kinv.at<double>(1,1) << \", \" << R_Kinv.at<double>(1,2) << std::endl;\n                // std::cout << \"R_Kinv[2] = \" << R_Kinv.at<double>(2,0) << \", \" << R_Kinv.at<double>(2,1) << \", \" << R_Kinv.at<double>(2,2) << std::endl;\n                // std::cout << std::endl;\n                // ENDDEBUG\n            }\n\n        cv::Mat get_map_x() const { return mapX; }\n        cv::Mat get_map_y() const { return mapY; }\n\n        void unproject() {\n            mapX = cv::Mat(previewHeight, previewWidth, CV_32FC1);\n            mapY = cv::Mat(previewHeight, previewWidth, CV_32FC1);\n\n            for (int x = 0; x < previewWidth; ++x) {\n                for (int y = 0; y < previewHeight; ++y) {\n                    double u,v;\n                    mapBackward(static_cast<double>(x), static_cast<double>(y), u, v);\n                    // std::cout << \"u,v = \" << u << \",\" << v << std::endl;\n                    mapX.at<float>(y,x) = static_cast<float>(u);\n                    mapY.at<float>(y,x) = static_cast<float>(v);\n                }\n            }\n        }\n    };\n\n    /**\n     * Unproject. Basic inner matrix product using implicit matrix conversion.\n     * @param leftMat left-hand matrix operand\n     * @param rightMat right-hand matrix operand\n     * @return an NdArray representing the dot-product of the left and right operands\n     */\n    // cv::Mat unproject(cv::Mat leftMat, cv::Mat rightMat) {\n    //     auto c1 = leftMat.cols, r2 = rightMat.rows;\n    //     if (c1 != r2) {\n    //         PyErr_SetString(PyExc_TypeError,\n    //                         \"Incompatible sizes for matrix multiplication.\");\n    //         throw_error_already_set();\n    //     }\n    //     cv::Mat result = leftMat * rightMat;\n\n    //     return result;\n    // }\n\n\n#if (PY_VERSION_HEX >= 0x03000000)\n    static void *init_ar() {\n#else\n    static void init_ar(){\n#endif\n        Py_Initialize();\n\n        import_array();\n        return NUMPY_IMPORT_ARRAY_RETVAL;\n    }\n\n    BOOST_PYTHON_MODULE (libpreviewer) {\n        //using namespace XM;\n        init_ar();\n\n        //initialize converters\n        boost::python::type_info info = boost::python::type_id<cv::Mat>(); \n        const boost::python::converter::registration* reg = boost::python::converter::registry::query(info); \n        if (reg == NULL || (*reg).m_to_python == NULL)  {\n            to_python_converter<cv::Mat, libpreviewer::matToNDArrayBoostConverter>();\n            libpreviewer::matFromNDArrayBoostConverter();\n        }\n\n        //expose module-level functions\n        class_<Projector>(\"Projector\", init<int, int, int, int, cv::Mat>())\n            .def(\"unproject\", &Projector::unproject)\n            .def(\"get_map_x\", &Projector::get_map_x)\n            .def(\"get_map_y\", &Projector::get_map_y);\n    }\n\n} //end namespace libpreviewer\n", "meta": {"hexsha": "6ff24f12b935b84dd6b9e92093f6089e9d7065ee", "size": 5103, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "native/src/python_module.cpp", "max_stars_repo_name": "Photonomie/previewer", "max_stars_repo_head_hexsha": "5353f453b7ae60f506af2f013ae8f870c1eec90c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2017-02-10T12:40:21.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-31T23:17:56.000Z", "max_issues_repo_path": "native/src/python_module.cpp", "max_issues_repo_name": "Photonomie/previewer", "max_issues_repo_head_hexsha": "5353f453b7ae60f506af2f013ae8f870c1eec90c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "native/src/python_module.cpp", "max_forks_repo_name": "Photonomie/previewer", "max_forks_repo_head_hexsha": "5353f453b7ae60f506af2f013ae8f870c1eec90c", "max_forks_repo_licenses": ["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.3684210526, "max_line_length": 154, "alphanum_fraction": 0.5383107976, "num_tokens": 1383, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5926665999540698, "lm_q2_score": 0.5156199157230156, "lm_q1q2_score": 0.30559070232016367}}
{"text": "#include <iostream>\n#include <unordered_map>\n#include <elemental.hpp>\n#include <boost/mpi.hpp>\n#include <boost/format.hpp>\n#include <boost/program_options.hpp>\n#include <skylark.hpp>\n\nnamespace bmpi =  boost::mpi;\nnamespace bpo = boost::program_options;\nnamespace skybase = skylark::base;\nnamespace skysketch =  skylark::sketch;\nnamespace skynla = skylark::nla;\nnamespace skyalg = skylark::algorithms;\nnamespace skyml = skylark::ml;\nnamespace skyutil = skylark::utility;\n\n\nstruct simple_unweighted_graph_t {\n\n\n    simple_unweighted_graph_t(const std::string &gf);\n\n    ~simple_unweighted_graph_t() {\n        delete[] _out;\n    }\n\n    int num_vertices() const { return _num_vertices; }\n    int num_edges() const { return _num_edges; }\n    int degree(int vertex) const { return _nodepairs.at(vertex).first; }\n    const int *adjanct(int vertex) const { return _nodepairs.at(vertex).second; }\n\nprivate:\n    typedef std::pair<int, int *> nodepair_t;\n\n    std::unordered_map<int, nodepair_t> _nodepairs;\n    int *_out;\n    int _num_vertices;\n    int _num_edges;\n};\n\n\nsimple_unweighted_graph_t::simple_unweighted_graph_t(const std::string &gf) {\n\n    std::ifstream in(gf);\n    std::string line, token;\n\n    _num_edges = 0;\n    while(true) {\n        getline(in, line);\n        if (in.eof())\n            break;\n        if (line[0] == '#')\n            continue;\n\n        std::istringstream tokenstream(line);\n        tokenstream >> token;\n        int i = atoi(token.c_str());\n        tokenstream >> token;\n        int j = atoi(token.c_str());\n\n        if (i == j)\n            continue;\n\n        _nodepairs[i].first++;\n        _nodepairs[j].first++;\n        _num_edges += 2;\n    }\n\n    _num_vertices = _nodepairs.size();\n\n    std::cout << \"Finished first pass. Vertices = \" << _num_vertices\n              << \" Edges = \" << _num_edges << std::endl;\n    _out = new int[_num_edges];\n\n    // Set pointers and zero degrees.\n    int count = 0;\n    for(auto it = _nodepairs.begin(); it != _nodepairs.end(); it++) {\n        int nodeid = it->first;\n        int deg = it->second.first;\n        _nodepairs[nodeid] = nodepair_t(0, _out + count);\n        count += deg;\n    }\n\n    // Second pass\n    in.clear();\n    in.seekg(0, std::ios::beg);\n    while(!in.eof()) {\n        getline(in, line);\n        if (line[0] == '#')\n            continue;\n\n        std::istringstream tokenstream(line);\n        tokenstream >> token;\n        int i = atoi(token.c_str());\n        tokenstream >> token;\n        int j = atoi(token.c_str());\n\n        if (i == j)\n            continue;\n\n        nodepair_t &npi = _nodepairs[i];\n        npi.second[npi.first] = j;\n        npi.first++;\n\n        nodepair_t &npj = _nodepairs[j];\n        npj.second[npj.first] = i;\n        npj.first++;\n    }\n\n    std::cout << \"Finished reading... \";\n    in.close();\n}\n\nint main(int argc, char** argv) {\n\n    elem::Initialize(argc, argv);\n\n    boost::mpi::timer timer;\n\n    // Parse options\n    double gamma, alpha, epsilon;\n    bool recursive, interactive;\n    std::string graphfile, indexfile;\n    std::vector<std::string> seedss;\n    std::vector<int> seeds;\n    bpo::options_description\n        desc(\"Options:\");\n    desc.add_options()\n        (\"help,h\", \"produce a help message\")\n        (\"graphfile,g\",\n            bpo::value<std::string>(&graphfile),\n            \"File holding the graph. REQUIRED.\")\n        (\"indexfile,d\",\n            bpo::value<std::string>(&indexfile)->default_value(\"\"),\n            \"Index files mapping node-ids to strings. OPTIONAL.\")\n        (\"interactive,i\", \"Whether to run in interactive mode.\")\n        (\"seed,s\",\n            bpo::value<std::vector<std::string> >(&seedss),\n            \"Seed node. Use multiple times for multiple seeds. REQUIRED. \")\n        (\"recursive,r\",\n            bpo::value<bool>(&recursive)->default_value(true),\n            \"Whether to try to recursively improve clusters \"\n            \"(use cluster found as a seed)\" )\n        (\"gamma\",\n            bpo::value<double>(&gamma)->default_value(5.0),\n            \"Time to derive the diffusion. As gamma->inf we get closer to ppr.\")\n        (\"alpha\",\n            bpo::value<double>(&alpha)->default_value(0.85),\n            \"PPR component parameter. alpha=1 will result in pure heat-kernel.\")\n        (\"epsilon\",\n            bpo::value<double>(&epsilon)->default_value(0.001),\n            \"Accuracy parameter for convergence.\");\n\n    bpo::variables_map vm;\n    try {\n        bpo::store(bpo::command_line_parser(argc, argv)\n            .options(desc).run(), vm);\n\n        if (vm.count(\"help\")) {\n            std::cout << desc;\n            return 0;\n        }\n\n        interactive = vm.count(\"interactive\");\n\n        if (!vm.count(\"graphfile\")) {\n            std::cout << \"Input graph-file is required.\" << std::endl;\n            return -1;\n        }\n\n        if (!interactive && !vm.count(\"seed\")) {\n            std::cout << \"A seed is required in non-interactive mode.\"\n                      << std::endl;\n            return -1;\n        }\n\n        bpo::notify(vm);\n    } catch(bpo::error& e) {\n        std::cerr << e.what() << std::endl;\n        std::cerr << desc << std::endl;\n        return -1;\n    }\n\n    std::cout << \"Reading the adjacency matrix... \" << std::endl;\n    std::cout.flush();\n    timer.restart();\n    simple_unweighted_graph_t G(graphfile);\n    std::cout <<\"took \" << boost::format(\"%.2e\") % timer.elapsed() << \" sec\\n\";\n\n    bool use_index = !indexfile.empty();\n    std::unordered_map<int, std::string> id_to_name_map;\n    std::unordered_map<std::string, int> name_to_id_map;\n    if (use_index) {\n        std::cout << \"Reading index files... \";\n        std::cout.flush();\n        timer.restart();\n\n        std::ifstream in(indexfile);\n        std::string line, token;\n\n        while(true) {\n            getline(in, line);\n            if (in.eof())\n                break;\n\n            if (line[0] == '#')\n                continue;\n\n            std::istringstream tokenstream(line);\n            tokenstream >> token;\n            std::string name = token;\n            tokenstream >> token;\n            int node = atoi(token.c_str());\n\n            id_to_name_map[node] = name;\n            name_to_id_map[name] = node;\n        }\n\n        in.close();\n\n        std::cout <<\"took \" << boost::format(\"%.2e\") % timer.elapsed() << \" sec\\n\";\n    }\n\n    do {\n        if (interactive) {\n            std::cout << \"Please input seeds: \";\n            std::string line;\n            std::getline(std::cin, line);\n            if (line.empty())\n                break;\n\n            seeds.clear();\n            std::stringstream strs(line);\n            if (use_index) {\n                std::string seed;\n                int c = 0;\n                while (strs >> seed) {\n                    seeds.push_back(name_to_id_map[seed]);\n                    c++;\n                    if (c == 200)\n                        exit(-1);\n                }\n            } else {\n                int seed;\n                int c = 0;\n                while(strs >> seed) {\n                    seeds.push_back(seed);\n                    c++;\n                    if (c == 200)\n                        exit(-1);\n                }\n            }\n        } else {\n            for(auto it = seedss.begin(); it != seedss.end(); it++)\n                if (use_index)\n                    seeds.push_back(name_to_id_map[*it]);\n                else\n                    seeds.push_back(atoi(it->c_str()));\n        }\n\n\n        timer.restart();\n        std::vector<int> cluster;\n        double cond = skyml::FindLocalCluster(G, seeds, cluster,\n            alpha, gamma, epsilon, recursive);\n        std::cout <<\"Analysis complete! Took \"\n                  << boost::format(\"%.2e\") % timer.elapsed() << \" sec\\n\";\n        std::cout << \"Cluster found:\" << std::endl;\n        for (auto it = cluster.begin(); it != cluster.end(); it++)\n            if (use_index)\n                std::cout << id_to_name_map[*it] << std::endl;\n            else\n                std::cout << *it << \" \";\n        if (!use_index)\n            std::cout << std::endl;\n        std::cout << \"Conductivity = \" << cond << std::endl;\n    } while (interactive);\n\n    return 0;\n}\n", "meta": {"hexsha": "2f813a5e0ec3ee3c8783c0462d90ee092e73dd47", "size": 8142, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/community.cpp", "max_stars_repo_name": "wangg12/libskylark", "max_stars_repo_head_hexsha": "e8836190be854d0284d38772c48e110b3c6d5e51", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-06-12T07:26:43.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-12T07:26:47.000Z", "max_issues_repo_path": "examples/community.cpp", "max_issues_repo_name": "cjiyer/libskylark", "max_issues_repo_head_hexsha": "e8836190be854d0284d38772c48e110b3c6d5e51", "max_issues_repo_licenses": ["Apache-2.0"], "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/community.cpp", "max_forks_repo_name": "cjiyer/libskylark", "max_forks_repo_head_hexsha": "e8836190be854d0284d38772c48e110b3c6d5e51", "max_forks_repo_licenses": ["Apache-2.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.8723404255, "max_line_length": 83, "alphanum_fraction": 0.5186686318, "num_tokens": 1940, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5926665855647394, "lm_q2_score": 0.5156199157230157, "lm_q1q2_score": 0.30559069490073837}}
{"text": "#ifndef STAN_MATH_REV_MAT_FUN_QUAD_FORM_SYM_HPP\n#define STAN_MATH_REV_MAT_FUN_QUAD_FORM_SYM_HPP\n\n#include <boost/utility/enable_if.hpp>\n#include <boost/type_traits.hpp>\n#include <stan/math/rev/core.hpp>\n#include <stan/math/prim/mat/fun/Eigen.hpp>\n#include <stan/math/prim/mat/fun/typedefs.hpp>\n#include <stan/math/rev/mat/fun/typedefs.hpp>\n#include <stan/math/prim/mat/fun/value_of.hpp>\n#include <stan/math/prim/mat/fun/quad_form.hpp>\n#include <stan/math/prim/mat/err/check_multiplicable.hpp>\n#include <stan/math/prim/mat/err/check_square.hpp>\n#include <stan/math/prim/mat/err/check_symmetric.hpp>\n#include <stan/math/rev/mat/fun/quad_form.hpp>\n\nnamespace stan {\n  namespace math {\n\n    template <typename TA, int RA, int CA, typename TB, int RB, int CB>\n    inline typename\n    boost::enable_if_c< boost::is_same<TA, var>::value ||\n    boost::is_same<TB, var>::value,\n                        Eigen::Matrix<var, CB, CB> >::type\n      quad_form_sym(const Eigen::Matrix<TA, RA, CA>& A,\n                    const Eigen::Matrix<TB, RB, CB>& B) {\n      check_square(\"quad_form\", \"A\", A);\n      check_symmetric(\"quad_form_sym\", \"A\", A);\n      check_multiplicable(\"quad_form_sym\",\n                          \"A\", A,\n                          \"B\", B);\n\n      quad_form_vari<TA, RA, CA, TB, RB, CB> *baseVari\n        = new quad_form_vari<TA, RA, CA, TB, RB, CB>(A, B, true);\n\n      return baseVari->impl_->C_;\n    }\n    template <typename TA, int RA, int CA, typename TB, int RB>\n    inline typename\n    boost::enable_if_c< boost::is_same<TA, var>::value ||\n    boost::is_same<TB, var>::value,\n                        var >::type\n      quad_form_sym(const Eigen::Matrix<TA, RA, CA>& A,\n                    const Eigen::Matrix<TB, RB, 1>& B) {\n      check_square(\"quad_form\", \"A\", A);\n      check_symmetric(\"quad_form_sym\", \"A\", A);\n      check_multiplicable(\"quad_form_sym\",\n                          \"A\", A,\n                          \"B\", B);\n\n      quad_form_vari<TA, RA, CA, TB, RB, 1> *baseVari\n        = new quad_form_vari<TA, RA, CA, TB, RB, 1>(A, B, true);\n\n      return baseVari->impl_->C_(0, 0);\n    }\n\n  }\n}\n#endif\n", "meta": {"hexsha": "6f38e7d9a69cbac8cd58af24db225ef7d448d9d0", "size": 2115, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "cmdstan/stan/lib/stan_math/stan/math/rev/mat/fun/quad_form_sym.hpp", "max_stars_repo_name": "yizhang-cae/torsten", "max_stars_repo_head_hexsha": "dc82080ca032325040844cbabe81c9a2b5e046f9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cmdstan/stan/lib/stan_math/stan/math/rev/mat/fun/quad_form_sym.hpp", "max_issues_repo_name": "yizhang-cae/torsten", "max_issues_repo_head_hexsha": "dc82080ca032325040844cbabe81c9a2b5e046f9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cmdstan/stan/lib/stan_math/stan/math/rev/mat/fun/quad_form_sym.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": 35.25, "max_line_length": 71, "alphanum_fraction": 0.6094562648, "num_tokens": 596, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5926665855647395, "lm_q2_score": 0.5156199157230156, "lm_q1q2_score": 0.30559069490073837}}
{"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/// Code implementing the full BTE solution by the Omini-Sparavigna\n/// iterative method, as implemented in ShengBTE.\n\n#include <Eigen/Dense>\n#include <processes.hpp>\n#include <isotopic_scattering.hpp>\n\nnamespace alma {\n/// Class implementing an iterative solution to the BTE following\n/// the scheme devised by Omini and Sparavigna.\nclass ShengBTE_iterator {\nprivate:\n    /// Number of points in the grid.\n    const std::size_t nqpoints;\n    /// Number of irreducible q points.\n    const std::size_t nirred;\n    /// Number of branches.\n    const std::size_t nbranches;\n    /// Volume of the unit cell.\n    const double V;\n    /// Iteration number.\n    std::size_t n;\n    /// Angular frequencies for all points on the grid [rad / ps].\n    Eigen::MatrixXd omega;\n    /// Velocities for all points on the grid [nm / ps].\n    Eigen::MatrixXd vg;\n    /// Lifetimes for all points on the grid [nm / ps]\n    Eigen::MatrixXd tau0;\n    /// Value of the intermediate quantity F, measuring the distance to\n    /// equilibrium, for the current iteration.\n    Eigen::MatrixXd F;\n    /// MPI communicator used to coordinate different processes.\n    const boost::mpi::communicator& comm;\n\npublic:\n    /// Basic constructor to initialize F.\n    ///\n    /// @param[in] poscar - description of the unit cell\n    /// @param[in] grid - phonon spectrum on a regular q-point grid\n    /// @param[in] syms - symmetry operations object\n    /// @param[inout] threeph_procs - list of 3-phonon processes\n    /// @param[inout] twoph_procs - list of 2-phonon processes\n    /// @param[in] T - temperature in K\n    /// @param[in] comm - communicator used to synchronize all processes\n    ShengBTE_iterator(const Crystal_structure& poscar,\n                      const Gamma_grid& grid,\n                      const Symmetry_operations& syms,\n                      std::vector<Threeph_process>& threeph_procs,\n                      std::vector<Twoph_process>& twoph_procs,\n                      double T,\n                      const boost::mpi::communicator& comm_);\n\n\n    /// Advance to the next iteration.\n    ///\n    /// @param[in] poscar - description of the unit cell\n    /// @param[in] grid - phonon spectrum on a regular q-point grid\n    /// @param[in] syms - symmetry operations object\n    /// @param[inout] threeph_procs - list of 3-phonon processes\n    /// @param[inout] twoph_procs - list of 2-phonon processes\n    /// @param[in] T - temperature in K\n    void next(const Crystal_structure& poscar,\n              const Gamma_grid& grid,\n              const Symmetry_operations& syms,\n              std::vector<Threeph_process>& threeph_procs,\n              std::vector<Twoph_process>& twoph_procs,\n              double T);\n\n\n    /// Get the current estimate of the thermal conductivity tensor.\n    ///\n    /// @param[in] T - temperature in K\n    /// @return a 3x3 matrix with all the components of kappa\n    /// [W / (m K)]\n    Eigen::Matrix3d calc_current_kappa(double T) const;\n\n\n    /// Get the current estimate of the contribution to the thermal conductivity\n    /// tensor from a single branch.\n    ///\n    /// In this context, a branch is defined as the set of modes with the same\n    /// index\n    /// when energies are sorted in ascending order at each q point.\n    /// @param[in] T - temperature in K\n    /// @param[in] branch - branch index\n    /// @return a 3x3 matrix with all the components of kappa\n    /// [W / (m K)]\n    Eigen::Matrix3d calc_current_kappa_branch(double T,\n                                              std::size_t branch) const;\n\n\n    /// Obtain the cumulative histogram of contributions to the thermal\n    /// conductivity as a function of angular frequency.\n    ///\n    /// @param[in] T - temperature in K\n    /// @param[ticks] - upper edges of the histogram bins\n    /// @return a std::vector of thermal conductivity tensors with\n    /// the cumulative histogram\n    std::vector<Eigen::Matrix3d> calc_cumulative_kappa_omega(\n        double T,\n        Eigen::ArrayXd ticks);\n\n\n    /// Obtain the cumulative histogram of contributions to the thermal\n    /// conductivity as a function of pseudo-mean free path.\n    ///\n    /// @param[in] T - temperature in K\n    /// @param[ticks] - upper edges of the histogram bins\n    /// @return a std::vector of thermal conductivity tensors with\n    /// the cumulative histogram\n    std::vector<Eigen::Matrix3d> calc_cumulative_kappa_lambda(\n        double T,\n        Eigen::ArrayXd ticks);\n\n\n    /// Obtain a set of pseudo-scattering rates from the current estimate of the\n    /// solution.\n    ///\n    /// Note that these are not the inverse of any real relaxation time, since\n    /// no such thing exist in the full linearized BTE formalism for phonons.\n    /// Substituting these into the RTA expression for kappa will not yield\n    /// the right thermal conductivity. Moreover, some elements can be negative.\n    /// See the ShengBTE paper for details.\n    /// @return an array of pseudo-scattering rates for each q point and each\n    /// mode [ps ** (-1)]\n    Eigen::ArrayXXd calc_w() const;\n\n\n    /// Obtain a set of pseudo-mean free paths from the current estimate of the\n    /// solution.\n    ///\n    /// Note that these are not real MFPs, since no such thing exist in the full\n    /// linearized BTE formalism for phonons. Substituting these into the RTA\n    /// expression for kappa will not yield the right thermal conductivity.\n    /// Moreover, some elements can be negative.See the ShengBTE paper for\n    /// details.\n    /// @return an array of pseudo-scattering rates for each q point and each\n    /// mode [ps ** (-1)]\n    Eigen::ArrayXXd calc_lambda() const;\n};\n\n\n/// Compute the full thermal conductivity tensor use the\n/// Omini-Sparavigna\n/// iterative approach.\n///\n/// @param[in] poscar - description of the unit cell\n/// @param[in] grid - phonon spectrum on a regular q-point grid\n/// @param[in] syms - symmetry operations object\n/// @param[inout] threeph_procs - list of 3-phonon processes\n/// @param[inout] twoph_procs - list of 2-phonon processes\n/// @param[in] T - temperature in K\n/// @param[in] comm - communicator used to synchronize all processes\n/// @param[in] tolerance - maximum change in the norm betwwen iterations\n/// used as the convergence criterion\n/// @param[in] maxiter - maximum number of iterations before giving up\n/// @return the thermal conductivity tensor in SI units\nEigen::MatrixXd calc_shengbte_kappa(\n    const alma::Crystal_structure& poscar,\n    const alma::Gamma_grid& grid,\n    const alma::Symmetry_operations& syms,\n    std::vector<alma::Threeph_process>& threeph_procs,\n    std::vector<alma::Twoph_process>& twoph_procs,\n    double T,\n    const boost::mpi::communicator& comm,\n    double tolerance = 1e-4,\n    std::size_t maxiter = 1000);\n} // namespace alma", "meta": {"hexsha": "319985227fe747614d4ba78ef688e17e270f58fe", "size": 7398, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/shengbte_iter.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/shengbte_iter.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/shengbte_iter.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": 39.9891891892, "max_line_length": 80, "alphanum_fraction": 0.6695052717, "num_tokens": 1770, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6513548646660542, "lm_q2_score": 0.46879062662624377, "lm_q1q2_score": 0.30534905516285177}}
{"text": "/* pcmsolver_copyright_start */\n/*\n *     PCMSolver, an API for the Polarizable Continuum Model\n *     Copyright (C) 2013-2016 Roberto Di Remigio, Luca Frediani and contributors\n *     \n *     This file is part of PCMSolver.\n *     \n *     PCMSolver is free software: you can redistribute it and/or modify\n *     it under the terms of the GNU Lesser General Public License as published by\n *     the Free Software Foundation, either version 3 of the License, or\n *     (at your option) any later version.\n *     \n *     PCMSolver is distributed in the hope that it will be useful,\n *     but WITHOUT ANY WARRANTY; without even the implied warranty of\n *     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n *     GNU Lesser General Public License for more details.\n *     \n *     You should have received a copy of the GNU Lesser General Public License\n *     along with PCMSolver.  If not, see <http://www.gnu.org/licenses/>.\n *     \n *     For information on the complete list of contributors to the\n *     PCMSolver API, see: <http://pcmsolver.readthedocs.io/>\n */\n/* pcmsolver_copyright_end */\n\n#ifndef COLLOCATIONINTEGRATOR_HPP\n#define COLLOCATIONINTEGRATOR_HPP\n\n#include <cmath>\n#include <iosfwd>\n#include <vector>\n\n#include \"Config.hpp\"\n\n#include <Eigen/Core>\n\n#include \"IntegratorHelperFunctions.hpp\"\n#include \"cavity/Element.hpp\"\n#include \"green/AnisotropicLiquid.hpp\"\n#include \"green/IonicLiquid.hpp\"\n#include \"green/SphericalDiffuse.hpp\"\n#include \"green/UniformDielectric.hpp\"\n#include \"green/Vacuum.hpp\"\n\n/*! \\file CollocationIntegrator.hpp\n *  \\struct CollocationIntegrator\n *  \\brief Implementation of the single and double layer operators matrix representation using one-point collocation\n *  \\author Roberto Di Remigio\n *  \\date 2015\n *\n *  Calculates the diagonal elements of S as:\n *  \\f[\n *  \tS_{ii} = factor * \\sqrt{\\frac{4\\pi}{a_i}}\n *  \\f]\n *  while the diagonal elements of D are:\n *  \\f[\n *  \tD_{ii} = -factor * \\sqrt{\\frac{\\pi}{a_i}} \\frac{1}{R_I}\n *  \\f]\n */\n\nstruct CollocationIntegrator\n{\n    CollocationIntegrator() : factor(1.07) {}\n    CollocationIntegrator(double f) : factor(f) {}\n    ~CollocationIntegrator() {}\n\n    /**@{ Single and double layer potentials for a Vacuum Green's function by collocation */\n    /*! \\tparam DerivativeTraits how the derivatives of the Greens's function are calculated\n     *  \\param[in] gf Green's function\n     *  \\param[in] e  list of finite elements\n     */\n    template <typename DerivativeTraits>\n    Eigen::MatrixXd singleLayer(const Vacuum<DerivativeTraits, CollocationIntegrator> & gf, const std::vector<Element> & e) const {\n        return integrator::singleLayer(e,\n                pcm::bind(integrator::SI, this->factor, 1.0, pcm::_1),\n                gf.exportKernelS());\n    }\n    /*! \\tparam DerivativeTraits how the derivatives of the Greens's function are calculated\n     *  \\param[in] gf Green's function\n     *  \\param[in] e  list of finite elements\n     */\n    template <typename DerivativeTraits>\n    Eigen::MatrixXd doubleLayer(const Vacuum<DerivativeTraits, CollocationIntegrator> & gf, const std::vector<Element> & e) const {\n        return integrator::doubleLayer(e,\n                                       pcm::bind(integrator::DI, this->factor, pcm::_1),\n                                       gf.exportKernelD());\n    }\n    /**@}*/\n\n    /**@{ Single and double layer potentials for a UniformDielectric Green's function by collocation */\n    /*! \\tparam DerivativeTraits how the derivatives of the Greens's function are calculated\n     *  \\param[in] gf Green's function\n     *  \\param[in] e  list of finite elements\n     */\n    template <typename DerivativeTraits>\n    Eigen::MatrixXd singleLayer(const UniformDielectric<DerivativeTraits, CollocationIntegrator> & gf, const std::vector<Element> & e) const {\n        return integrator::singleLayer(e,\n                pcm::bind(integrator::SI, this->factor, gf.epsilon(), pcm::_1),\n                gf.exportKernelS());\n    }\n    /*! \\tparam DerivativeTraits how the derivatives of the Greens's function are calculated\n     *  \\param[in] gf Green's function\n     *  \\param[in] e  list of finite elements\n     */\n    template <typename DerivativeTraits>\n    Eigen::MatrixXd doubleLayer(const UniformDielectric<DerivativeTraits, CollocationIntegrator> & gf, const std::vector<Element> & e) const {\n        return integrator::doubleLayer(e,\n                                       pcm::bind(integrator::DI, this->factor, pcm::_1),\n                                       gf.exportKernelD());\n    }\n    /**@}*/\n\n    /**@{ Single and double layer potentials for a IonicLiquid Green's function by collocation */\n    template <typename DerivativeTraits>\n    Eigen::MatrixXd singleLayer(const IonicLiquid<DerivativeTraits, CollocationIntegrator> & /* gf */, const std::vector<Element> & e) const {\n        PCMSOLVER_ERROR(\"CollocationIntegrator::singleLayer not implemented yet for IonicLiquid\", BOOST_CURRENT_FUNCTION);\n        return Eigen::MatrixXd::Zero(e.size(), e.size());\n    }\n    template <typename DerivativeTraits>\n    Eigen::MatrixXd doubleLayer(const IonicLiquid<DerivativeTraits, CollocationIntegrator> & /* gf */, const std::vector<Element> & e) const {\n        PCMSOLVER_ERROR(\"CollocationIntegrator::doubleLayer not implemented yet for IonicLiquid\", BOOST_CURRENT_FUNCTION);\n        return Eigen::MatrixXd::Zero(e.size(), e.size());\n    }\n    /**@}*/\n\n    /**@{ Single and double layer potentials for an AnisotropicLiquid Green's function by collocation */\n    template <typename DerivativeTraits>\n    Eigen::MatrixXd singleLayer(const AnisotropicLiquid<DerivativeTraits, CollocationIntegrator> & /* gf */, const std::vector<Element> & e) const {\n        PCMSOLVER_ERROR(\"CollocationIntegrator::singleLayer not implemented yet for AnisotropicLiquid\", BOOST_CURRENT_FUNCTION);\n        return Eigen::MatrixXd::Zero(e.size(), e.size());\n    }\n    template <typename DerivativeTraits>\n    Eigen::MatrixXd doubleLayer(const AnisotropicLiquid<DerivativeTraits, CollocationIntegrator> & /* gf */, const std::vector<Element> & e) const {\n        PCMSOLVER_ERROR(\"CollocationIntegrator::doubleLayer not implemented yet for AnisotropicLiquid\", BOOST_CURRENT_FUNCTION);\n        return Eigen::MatrixXd::Zero(e.size(), e.size());\n    }\n    /**@}*/\n\n    /**@{ Single and double layer potentials for a SphericalDiffuse Green's function by collocation */\n    /*! \\tparam ProfilePolicy the permittivity profile for the diffuse interface\n     *  \\param[in] gf Green's function\n     *  \\param[in] e  list of finite elements\n     */\n    template <typename ProfilePolicy>\n    Eigen::MatrixXd singleLayer(const SphericalDiffuse<CollocationIntegrator, ProfilePolicy> & gf, const std::vector<Element> & e) const {\n        // The singular part is \"integrated\" as usual, while the nonsingular part is evaluated in full\n        PCMSolverIndex mat_size = e.size();\n        Eigen::MatrixXd S = Eigen::MatrixXd::Zero(mat_size, mat_size);\n        for (PCMSolverIndex i = 0; i < mat_size; ++i) {\n            // Fill diagonal\n            // Diagonal of S inside the cavity\n            double Sii_I = factor * std::sqrt(4 * M_PI / e[i].area());\n            // \"Diagonal\" of Coulomb singularity separation coefficient\n            double coulomb_coeff = gf.coefficientCoulomb(e[i].center(), e[i].center());\n            // \"Diagonal\" of the image Green's function\n            double image = gf.imagePotential(e[i].center(), e[i].center());\n            S(i, i) = Sii_I / coulomb_coeff + image;\n            Eigen::Vector3d source = e[i].center();\n            for (PCMSolverIndex j = 0; j < mat_size; ++j) {\n                // Fill off-diagonal\n                Eigen::Vector3d probe = e[j].center();\n                if (i != j) S(i, j) = gf.kernelS(source, probe);\n            }\n        }\n        return S;\n    }\n    /*! \\tparam ProfilePolicy the permittivity profile for the diffuse interface\n     *  \\param[in] gf Green's function\n     *  \\param[in] e  list of finite elements\n     */\n    template <typename ProfilePolicy>\n    Eigen::MatrixXd doubleLayer(const SphericalDiffuse<CollocationIntegrator, ProfilePolicy> & gf, const std::vector<Element> & e) const {\n        // The singular part is \"integrated\" as usual, while the nonsingular part is evaluated in full\n        PCMSolverIndex mat_size = e.size();\n        Eigen::MatrixXd D = Eigen::MatrixXd::Zero(mat_size, mat_size);\n        for (PCMSolverIndex i = 0; i < mat_size; ++i) {\n            // Fill diagonal\n            double area = e[i].area();\n            double radius = e[i].sphere().radius;\n            // Diagonal of S inside the cavity\n            double Sii_I = factor * std::sqrt(4 * M_PI / area);\n            // Diagonal of D inside the cavity\n            double Dii_I = -factor * std::sqrt(M_PI/ area) * (1.0 / radius);\n            // \"Diagonal\" of Coulomb singularity separation coefficient\n            double coulomb_coeff = gf.coefficientCoulomb(e[i].center(), e[i].center());\n            // \"Diagonal\" of the directional derivative of the Coulomb singularity separation coefficient\n            double coeff_grad = gf.coefficientCoulombDerivative(e[i].normal(), e[i].center(), e[i].center()) / std::pow(coulomb_coeff, 2);\n            // \"Diagonal\" of the directional derivative of the image Green's function\n            double image_grad = gf.imagePotentialDerivative(e[i].normal(), e[i].center(), e[i].center());\n\n            double eps_r2 = 0.0;\n            pcm::tie(eps_r2, pcm::ignore) = gf.epsilon(e[i].center());\n\n            D(i, i) = eps_r2 * (Dii_I / coulomb_coeff - Sii_I * coeff_grad + image_grad);\n            Eigen::Vector3d source = e[i].center();\n            for (PCMSolverIndex j = 0; j < mat_size; ++j) {\n                // Fill off-diagonal\n                Eigen::Vector3d probe = e[j].center();\n                Eigen::Vector3d probeNormal = e[j].normal();\n                probeNormal.normalize();\n                if (i != j) D(i, j) = gf.kernelD(probeNormal, source, probe);\n            }\n        }\n        return D;\n    }\n    /**@}*/\n\n    /// Scaling factor for the collocation formulas\n    double factor;\n};\n\n#endif // COLLOCATIONINTEGRATOR_HPP\n", "meta": {"hexsha": "3dd055e6b3f6d39237c448f0cf80e3cbfcaf7a2e", "size": 10158, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "external/PCMSolver/PCMSolver-source/src/bi_operators/CollocationIntegrator.hpp", "max_stars_repo_name": "robertodr/externalize", "max_stars_repo_head_hexsha": "c7b1dda2009dab329a6efb580c57ef8e1494cf3b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2017-02-15T22:16:34.000Z", "max_stars_repo_stars_event_max_datetime": "2017-02-15T22:16:34.000Z", "max_issues_repo_path": "external/PCMSolver/PCMSolver-source/src/bi_operators/CollocationIntegrator.hpp", "max_issues_repo_name": "robertodr/externalize", "max_issues_repo_head_hexsha": "c7b1dda2009dab329a6efb580c57ef8e1494cf3b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "external/PCMSolver/PCMSolver-source/src/bi_operators/CollocationIntegrator.hpp", "max_forks_repo_name": "robertodr/externalize", "max_forks_repo_head_hexsha": "c7b1dda2009dab329a6efb580c57ef8e1494cf3b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 47.6901408451, "max_line_length": 148, "alphanum_fraction": 0.6479621973, "num_tokens": 2448, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6513548646660542, "lm_q2_score": 0.4687906266262437, "lm_q1q2_score": 0.3053490551628517}}
{"text": "/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */\n\n/*\n Copyright (C) 2001, 2002, 2003 Sadruddin Rejeb\n Copyright (C) 2006 Cristina Duminuco\n Copyright (C) 2006 Marco Bianchetti\n Copyright (C) 2007 StatPro Italia srl\n Copyright (C) 2014 Ferdinando Ametrano\n Copyright (C) 2016 Peter Caspers\n\n This file is part of QuantLib, a free-software/open-source library\n for financial quantitative analysts and developers - http://quantlib.org/\n\n QuantLib is free software: you can redistribute it and/or modify it\n under the terms of the QuantLib license.  You should have received a\n copy of the license along with this program; if not, please email\n <quantlib-dev@lists.sf.net>. The license is also available online at\n <http://quantlib.org/license.shtml>.\n\n This program is distributed in the hope that it will be useful, but WITHOUT\n ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n FOR A PARTICULAR PURPOSE.  See the license for more details.\n*/\n\n#include <ql/instruments/swaption.hpp>\n#include <ql/pricingengines/swaption/blackswaptionengine.hpp>\n#include <ql/math/solvers1d/newtonsafe.hpp>\n#include <ql/quotes/simplequote.hpp>\n#include <ql/exercise.hpp>\n\n#include <boost/make_shared.hpp>\n\nnamespace QuantLib {\n\n    namespace {\n\n        class ImpliedSwaptionVolHelper {\n          public:\n            ImpliedSwaptionVolHelper(const Swaption&,\n                                     const Handle<YieldTermStructure>& discountCurve,\n                                     Real targetValue,\n                                     Real displacement,\n                                     VolatilityType type);\n            Real operator()(Volatility x) const;\n            Real derivative(Volatility x) const;\n          private:\n            boost::shared_ptr<PricingEngine> engine_;\n            Handle<YieldTermStructure> discountCurve_;\n            Real targetValue_;\n            boost::shared_ptr<SimpleQuote> vol_;\n            const Instrument::results* results_;\n        };\n\n        ImpliedSwaptionVolHelper::ImpliedSwaptionVolHelper(\n                              const Swaption& swaption,\n                              const Handle<YieldTermStructure>& discountCurve,\n                              Real targetValue,\n                              Real displacement,\n                              VolatilityType type)\n        : discountCurve_(discountCurve), targetValue_(targetValue) {\n\n            // set an implausible value, so that calculation is forced\n            // at first ImpliedSwaptionVolHelper::operator()(Volatility x) call\n            vol_ = boost::shared_ptr<SimpleQuote>(new SimpleQuote(-1.0));\n            Handle<Quote> h(vol_);\n\n            switch (type) {\n            case ShiftedLognormal:\n                engine_ = boost::make_shared<BlackSwaptionEngine>(\n                    discountCurve_, h, Actual365Fixed(), displacement);\n                break;\n            case Normal:\n                engine_ = boost::make_shared<BachelierSwaptionEngine>(\n                    discountCurve_, h, Actual365Fixed());\n                break;\n            default:\n                QL_FAIL(\"unknown VolatilityType (\" << type << \")\");\n                break;\n            }\n            swaption.setupArguments(engine_->getArguments());\n            results_ = dynamic_cast<const Instrument::results *>(\n                engine_->getResults());\n        }\n\n        Real ImpliedSwaptionVolHelper::operator()(Volatility x) const {\n            if (x!=vol_->value()) {\n                vol_->setValue(x);\n                engine_->calculate();\n            }\n            return results_->value-targetValue_;\n        }\n\n        Real ImpliedSwaptionVolHelper::derivative(Volatility x) const {\n            if (x!=vol_->value()) {\n                vol_->setValue(x);\n                engine_->calculate();\n            }\n            std::map<std::string,boost::any>::const_iterator vega_ =\n                results_->additionalResults.find(\"vega\");\n            QL_REQUIRE(vega_ != results_->additionalResults.end(),\n                       \"vega not provided\");\n            return boost::any_cast<Real>(vega_->second);\n        }\n    }\n\n    std::ostream& operator<<(std::ostream& out,\n                             Settlement::Type t) {\n        switch (t) {\n          case Settlement::Physical:\n            return out << \"Delivery\";\n          case Settlement::Cash:\n            return out << \"Cash\";\n          default:\n            QL_FAIL(\"unknown Settlement::Type(\" << Integer(t) << \")\");\n        }\n    }\n\n    Swaption::Swaption(const boost::shared_ptr<VanillaSwap>& swap,\n                       const boost::shared_ptr<Exercise>& exercise,\n                       Settlement::Type delivery)\n    : Option(boost::shared_ptr<Payoff>(), exercise), swap_(swap),\n      settlementType_(delivery) {\n        registerWith(swap_);\n        registerWithObservables(swap_);\n    }\n\n    bool Swaption::isExpired() const {\n        return detail::simple_event(exercise_->dates().back()).hasOccurred();\n    }\n\n    void Swaption::setupArguments(PricingEngine::arguments* args) const {\n\n        swap_->setupArguments(args);\n\n        Swaption::arguments* arguments =\n            dynamic_cast<Swaption::arguments*>(args);\n\n        QL_REQUIRE(arguments != 0, \"wrong argument type\");\n\n        arguments->swap = swap_;\n        arguments->settlementType = settlementType_;\n        arguments->exercise = exercise_;\n    }\n\n    void Swaption::arguments::validate() const {\n        VanillaSwap::arguments::validate();\n        QL_REQUIRE(swap, \"vanilla swap not set\");\n        QL_REQUIRE(exercise, \"exercise not set\");\n    }\n\n    Volatility Swaption::impliedVolatility(Real targetValue,\n                                           const Handle<YieldTermStructure>& d,\n                                           Volatility guess,\n                                           Real accuracy,\n                                           Natural maxEvaluations,\n                                           Volatility minVol,\n                                           Volatility maxVol,\n                                           VolatilityType type,\n                                           Real displacement) const {\n        //calculate();\n        QL_REQUIRE(!isExpired(), \"instrument expired\");\n\n        ImpliedSwaptionVolHelper f(*this, d, targetValue, displacement, type);\n        //Brent solver;\n        NewtonSafe solver;\n        solver.setMaxEvaluations(maxEvaluations);\n        return solver.solve(f, accuracy, guess, minVol, maxVol);\n    }\n\n    Volatility Swaption::impliedVolatility(Real targetValue,\n                                           const Handle<YieldTermStructure>& d,\n                                           Volatility guess,\n                                           Real accuracy,\n                                           Natural maxEvaluations,\n                                           Volatility minVol,\n                                           Volatility maxVol,\n                                           Real displacement,\n                                           VolatilityType type) const {\n        return impliedVolatility(targetValue, d, guess, accuracy,\n                                 maxEvaluations, minVol, maxVol,\n                                 type, displacement);\n    }\n\n}\n", "meta": {"hexsha": "73ae6e9e81c26998fa675312e2a38b62f7a9d0ac", "size": 7318, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ql/instruments/swaption.cpp", "max_stars_repo_name": "grandtiger/quantlib", "max_stars_repo_head_hexsha": "4cf3d80ffc071ae74f026bb25fbb1dd9093e6301", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2017-07-19T11:17:48.000Z", "max_stars_repo_stars_event_max_datetime": "2017-07-19T11:17:48.000Z", "max_issues_repo_path": "ql/instruments/swaption.cpp", "max_issues_repo_name": "grandtiger/quantlib", "max_issues_repo_head_hexsha": "4cf3d80ffc071ae74f026bb25fbb1dd9093e6301", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/instruments/swaption.cpp", "max_forks_repo_name": "grandtiger/quantlib", "max_forks_repo_head_hexsha": "4cf3d80ffc071ae74f026bb25fbb1dd9093e6301", "max_forks_repo_licenses": ["BSD-3-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.5567567568, "max_line_length": 85, "alphanum_fraction": 0.5482372233, "num_tokens": 1406, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.640635854839898, "lm_q2_score": 0.476579651063676, "lm_q1q2_score": 0.3053140121584784}}
{"text": "\n/**\n * @file OccupancyGridMap.hpp\n * @author bwu\n * @brief Grid map define and generation algorithm\n * @version 0.1\n * @date 2022-02-22 \n */\n#ifndef GENERIC_GEOMETRY_OCCUPANCYGRIDMAP_HPP\n#define GENERIC_GEOMETRY_OCCUPANCYGRIDMAP_HPP\n#include \"generic/thread/ThreadPool.hpp\"\n#include \"generic/math/MathUtility.hpp\"\n#include \"generic/common/Exception.hpp\"\n#include \"generic/tools/Tools.hpp\"\n#include \"BooleanOperation.hpp\"\n#include \"Triangulation.hpp\"\n#include \"Rasterization.hpp\"\n#include \"Triangulator.hpp\"\n#include \"Geometries.hpp\"\n#include \"GeometryIO.hpp\"\n#include \"Trapezoid.hpp\"\n#include \"Utility.hpp\"\n#include <boost/lockfree/queue.hpp>\n#include <vector>\n#include <atomic>\n\n#ifdef BOOST_GIL_IO_PNG_SUPPORT\n#include \"generic/tools/FileSystem.hpp\"\n#include \"generic/tools/Color.hpp\"\n#include <boost/gil/extension/io/png.hpp>\n#include <boost/gil.hpp>\n#include <png.h>\n#endif\n\nnamespace generic {\nnamespace geometry {\n\n/**\n * @brief represents a 2d dense grid map with Occupancy objects\n * \n * @tparam Occupancy occupancy object type, should be trivial\n */\ntemplate <typename Occupancy>\nclass OccupancyGridMap\n{\n    using Container = std::vector<std::vector<Occupancy> >;\npublic:\n    using ResultType = Occupancy;\n    OccupancyGridMap(size_t width, size_t height)\n     : m_width(width),\n       m_height(height),\n       m_grids(width, std::vector<Occupancy>(height, Occupancy{}))\n    {}\n    ~OccupancyGridMap() = default;\n    \n    ///@brief accesses Occupancy reference by 1d index `i`, `i` = x * height + y\n    Occupancy & operator[] (size_t i) { return m_grids[i / m_height][i % m_height]; }\n    const Occupancy & operator[](size_t i) const { return m_grids[i / m_height][i % m_height]; }\n\n    ///@brief  accesses Occupancy reference by 2d index `x`, `y`\n    Occupancy & operator() (size_t x, size_t y) { return m_grids[x][y]; }\n    const Occupancy & operator() (size_t x, size_t y) const { return m_grids[x][y]; }\n\n    ///@brief resizes grid map with `width` and `height`\n    void Resize(size_t width, size_t height)\n    {\n        m_width = width;\n        m_height = height;\n        m_grids.resize(width);\n        for(auto & col : m_grids)\n            col.resize(height);\n    }\n\n    ///@brief resets all occupancy values in grid map with default data\n    void Reset()\n    {\n        for(auto & col : m_grids){\n            std::fill(col.begin(), col.end(), Occupancy{});\n        }\n    }\n\n    ///@brief clears all occupancy data\n    void Clear() { m_grids.clear(); }\n    \n    ///@brief returns grid map width\n    size_t Width() const { return m_width; }\n\n    ///@brief returns grid map height\n    size_t Height() const { return m_height; }\n\n    ///@brief returns grid map size\n    size_t Size() const { return Width() * Height(); }\n\n    /**\n     * @brief gets max occupancy object with the compare functioner\n     * \n     * @tparam Compare the compare functioner\n     * @param cmp the Compare functioner object\n     * @return const reference of Occupancy object \n     */\n    template <typename Compare>\n    const Occupancy & MaxOccupancy(Compare && cmp) const\n    {\n        auto [i, j] = MaxElement(std::forward<Compare>(cmp));\n        return m_grids[i][j];\n    }\n\n    /**\n     * @brief gets x, y index of max occupancy object with the compare functioner\n     * \n     * @tparam Compare the compare functioner\n     * @param cmp the Compare functioner object\n     * @return x, y index of max ocupancy object\n     */\n    template <typename Compare>\n    std::pair<size_t, size_t> MaxElement(Compare && cmp) const\n    {\n        size_t xMax(0), yMax(0);\n        for(size_t i = 0; i < m_width; ++i){\n            for(size_t j = 0; j < m_height; ++j){\n                if(cmp(m_grids[i][j], m_grids[xMax][yMax])){\n                    xMax = i; yMax = j;\n                }\n            }\n        }\n        return std::make_pair(xMax, yMax);\n    }\n\n#ifdef BOOST_GIL_IO_PNG_SUPPORT\n    /**\n     * @brief converts grid map to png image with the color mapping functioner\n     * \n     * @tparam RGBaFunc rgba functioner that take Occupancy as input and return r, g, b, a values range from 0 to 255\n     * @param[in] filename output image file path\n     * @param[in] rgbaFunc RGBaFunc functioner object \n     * @return whether write the image file successfully\n     */\n    template <typename RGBaFunc>\n    bool WriteImgProfile(const std::string & filename, RGBaFunc && rgbaFunc)\n    {\n        auto dir = generic::filesystem::DirName(filename);\n        if(!generic::filesystem::PathExists(dir))\n            generic::filesystem::CreateDir(dir);\n\n        using namespace boost::gil;\n        rgb8_image_t img(m_width, m_height);\n        rgb8_image_t::view_t v = view(img);\n        for(auto i = 0; i < m_width; ++i){\n            for(auto j = 0; j < m_height; ++j){\n                auto [r, g, b, a] = rgbaFunc(m_grids[i][j]);\n                v(i, m_height - j - 1) = rgba8_pixel_t(r, g, b, a);\n            }\n        }\n        write_view(filename, view(img), png_tag());\n        return true;\n    }\n#endif\n\nprivate:\n    size_t m_width;\n    size_t m_height;\n    Container m_grids;\n};\n\n///@brief represents a factory class that calculate occupancy grid map from input geometries\nclass OccupancyGridMappingFactory\n{  \npublic:\n    ///@brief grid map data type\n    template <typename Occupancy>\n    using GridMap = OccupancyGridMap<Occupancy>;\n\n    /**\n     * @brief grid mapping factory product\n     * \n     * @tparam property_type user defined property\n     * @param x grid x index\n     * @param y grid y index\n     * @param property user defined property mark\n     * @param ratio the proportion that the piece of the geometry ocuupying the grid area\n     */\n    template <typename property_type>\n    struct Product { int x, y; property_type property; double ratio; };\n\n    ///@brief a lockfree queue that hold and consume the grid mapping product\n    template <typename property_type>\n    using ProductPipe = boost::lockfree::queue<Product<property_type>, boost::lockfree::fixed_sized<false> >;\n\n    template <typename num_type>\n    struct GridCtrl\n    {\n        size_t threads = 1;\n        Box2D<num_type> bbox;\n        Point2D<num_type> ref;\n        Vector2D<num_type> stride;\n\n        GridCtrl(const Box2D<num_type> & _bbox, const Vector2D<num_type> & _stride, size_t _threads = 1)\n         : GridCtrl(_bbox, _bbox[0], _stride, _threads) {}\n        \n        GridCtrl(const Box2D<num_type> & _bbox, const Point2D<num_type> & _ref, const Vector2D<num_type> & _stride, size_t _threads = 1)\n         : threads(_threads), bbox(_bbox), ref(_ref), stride(_stride) {}\n    };\n\n    template <typename num_type>\n    struct GridWorkItem\n    {\n        size_t begin, end;\n        GridCtrl<num_type> ctrl;\n    };\n    \n    /**\n     * @brief function that calculate grid map size from bounding box and x, y stride\n     * @param[in] bbox input bounding box\n     * @param[in] stride grid width and length in x, y direction \n     * @return std::pair<size_t, size_t> x, y size of the grid map\n     */\n    template <typename num_type>\n    static std::pair<size_t, size_t> GetGridMapSize(const Box2D<num_type> & bbox, const Vector2D<num_type> & stride)\n    {\n        using float_t = common::float_type<num_type>;\n        size_t x = static_cast<size_t>(std::ceil(float_t(bbox.Length()) / stride[0]));\n        size_t y = static_cast<size_t>(std::ceil(float_t(bbox.Width() ) / stride[1]));\n        return std::make_pair(x, y);\n    }\n\n    /**\n     * @brief mapping the property of geometries to grid based on occupying area proportion\n     * \n     * @tparam property_type geometry property type, for call back function when mapping the result\n     * @tparam Object input object type used for generating grid map\n     * @tparam GeomGetter functor tpye to convert user input object type to internal geometry type\n     * @note the GeomGetter functor should have operator() (const & T) function, the return type could be one of Box2D or Polygon2D\n     * @tparam Occupancy occupancy object type, should be trivial\n     * @tparam BlendFunc blend function type, used for calculating the occupying area proportion, for example, blend function usually different with solid and hole geometry\n     * @param[in] properties the properties of each input object\n     * @param[in] objects input objects\n     * @param[in] getter GeomGetter object\n     * @param[in] ctrl grid map generation ctrl parameters\n     * @param[out] gridMap output grid map that hold the the data of `Occupancy` each grid\n     * @param[in] blend BlendFunc object \n     */\n    template <typename property_type, typename Object, typename GeomGetter, typename Occupancy, typename BlendFunc,\n              typename std::enable_if<traits::is_2d_geometry_t<typename std::result_of<GeomGetter(const Object&)>::type>::value &&\n                                     (traits::is_polygon_t<typename std::result_of<GeomGetter(const Object&)>::type>::value ||\n                                      traits::is_box_t<typename std::result_of<GeomGetter(const Object&)>::type>::value), bool>::type = true>\n    static void Map2Grid(const std::vector<property_type> & properties, const std::vector<Object> & objects, GeomGetter && getter,\n                         const GridCtrl<typename std::result_of<GeomGetter(const Object&)>::type::coor_t> & ctrl, GridMap<Occupancy> & gridMap, BlendFunc && blend)\n    {\n        static_assert(std::is_trivial<Product<property_type> >::value, \"only trivial property supported!\");\n        GENERIC_ASSERT(properties.size() == objects.size())\n        \n        using geom_t = typename std::result_of<GeomGetter(const Object&)>::type;\n        using coor_t = typename geom_t::coor_t;\n        std::vector<geom_t> geometries;\n        geometries.reserve(objects.size());\n        for(const auto & object : objects){\n            geometries.push_back(getter(object));\n        }\n\n        std::vector<const geom_t *> geomPtrs;\n        geomPtrs.reserve(geometries.size());\n        for(const auto & geom : geometries) geomPtrs.push_back(&geom);\n        Map2Grid<property_type, geom_t, Occupancy, BlendFunc>(properties, geomPtrs, ctrl, gridMap, std::forward<BlendFunc>(blend));\n    }\n\n    ///@brief Map2Grid implementation for internal geometry_type\n    ///@note the geometry_type should be one of Box2D or Polygon2D\n    template <typename property_type, typename geometry_type, typename Occupancy, typename BlendFunc>\n    static void Map2Grid(const std::vector<property_type> & properties, const std::vector<const geometry_type * > & geometries, const GridCtrl<typename geometry_type::coor_t> & ctrl, GridMap<Occupancy> & gridMap, BlendFunc && blend)\n    {\n        static_assert(std::is_trivial<Product<property_type> >::value, \"only trivial property supported!\");\n        GENERIC_ASSERT(properties.size() == geometries.size())\n\n        std::atomic_bool done{false};\n        auto pipeline = std::make_unique<ProductPipe<property_type> >(32767);\n\n        // For single-thread\n        // Gridding<property_type, geometry_type>(properties, geometries, ctrl, *pipeline);\n        // done.store(true);\n        // Mapping<property_type, Occupancy, BlendFunc>(*pipeline, done, gridMap, std::forward<BlendFunc>(blend));\n\n        std::thread gridding(&OccupancyGridMappingFactory::Gridding<property_type, geometry_type>, std::ref(properties), std::ref(geometries), std::ref(ctrl), std::ref(*pipeline));\n        std::thread mapping(&OccupancyGridMappingFactory::Mapping<property_type, Occupancy, BlendFunc>, std::ref(*pipeline), std::ref(done), std::ref(gridMap), std::ref(blend));\n        \n        gridding.join();\n        done.store(true);\n        mapping.join();\n    }\n\nprivate:\n    template <typename property_type, typename Occupancy, typename BlendFunc>\n    static void Mapping(ProductPipe<property_type> & pipeline, std::atomic_bool & done, GridMap<Occupancy> & gridMap, BlendFunc && blend)\n    {\n        using Result = Product<property_type>;\n        auto width = static_cast<int>(gridMap.Width());\n        auto height = static_cast<int>(gridMap.Height());\n        auto mapping = [&](const Result & res)\n        {\n            if(res.x < 0 || res.x >= width) return;\n            if(res.y < 0 || res.y >= height) return;\n            auto & origin = gridMap(res.x, res.y);\n            blend(origin, res);\n        };\n\n        while(!done.load()){\n            while(pipeline.consume_one(mapping)){}\n        }\n        pipeline.consume_all(mapping);\n    }\n\n    template <typename property_type, typename geometry_type>\n    static void Gridding(const std::vector<property_type> & properties, const std::vector<const geometry_type * > & geometries, const GridCtrl<typename geometry_type::coor_t> & ctrl, ProductPipe<property_type> & pipeline)\n    {\n        thread::ThreadPool pool(ctrl.threads);\n        size_t size = geometries.size();\n        size_t blocks = pool.Threads();\n        size_t blockSize = size / blocks;\n\n        size_t begin = 0;\n        using num_type = typename geometry_type::coor_t;\n        for(size_t i = 0; i < blocks && blockSize > 0; ++i){\n            size_t end = begin + blockSize;\n            pool.Submit(std::bind(&OccupancyGridMappingFactory::GriddingImp<property_type, geometry_type>, std::ref(properties), std::ref(geometries), GridWorkItem<num_type>{begin, end, ctrl}, std::ref(pipeline)));\n            begin = end;\n        }\n        size_t end = size;\n        if(begin != end)\n            pool.Submit(std::bind(&OccupancyGridMappingFactory::GriddingImp<property_type, geometry_type>, std::ref(properties), std::ref(geometries), GridWorkItem<num_type>{begin, end, ctrl}, std::ref(pipeline)));\n        \n        pool.Wait();\n    }\n\n    template <typename property_type, typename geometry_type,\n              typename std::enable_if<traits::is_2d_geometry_t<geometry_type>::value && traits::is_polygon_t<geometry_type>::value, bool>::type = true>\n    static void GriddingImp(const std::vector<property_type> & properties, const std::vector<const geometry_type * > & polygons, GridWorkItem<typename geometry_type::coor_t> workItem, ProductPipe<property_type> & pipeline)\n    {\n        //TriangulationGriddingImp<property_type, geometry_type>(properties, polygons, workItem, pipeline);\n        TrapezoidationGriddingImp<property_type, typename geometry_type::coor_t>(properties, polygons, workItem, pipeline);\n    }\n\n    template <typename property_type, typename geometry_type,\n              typename std::enable_if<traits::is_2d_geometry_t<geometry_type>::value && traits::is_box_t<geometry_type>::value, bool>::type = true>\n    static void GriddingImp(const std::vector<property_type> & properties, const std::vector<const geometry_type * > & boxes, GridWorkItem<typename geometry_type::coor_t> workItem, ProductPipe<property_type> & pipeline)\n    {\n        using num_type = typename geometry_type::coor_t; \n        for(size_t i = workItem.begin; i < workItem.end; ++i){\n            const auto & property = properties[i];\n            const auto & box = boxes[i];\n            if(nullptr == box) continue;\n\n            GriddingRectangle<property_type, num_type>(property, *box, workItem.ctrl, pipeline);\n        }\n    }\n\n    template <typename property_type, typename num_type>\n    static void TriangulationGriddingImp(const std::vector<property_type> & properties, const std::vector<const Polygon2D<num_type> * > & polygons, GridWorkItem<num_type> workItem, ProductPipe<property_type> & pipeline)\n    {\n        for(size_t i = workItem.begin; i < workItem.end; ++i){\n            const auto & property = properties[i];\n            const auto & polygon = polygons[i];\n            if(nullptr == polygon) continue;\n\n            tri::Triangulation<Point2D<num_type> > triangulation;\n            GENERIC_ASSERT(TriangulationPolygon(polygon, triangulation))\n\n            GriddingTriangulation<property_type, num_type>(property, triangulation, workItem.ctrl, pipeline);\n        }\n    }\n\n    template <typename property_type, typename num_type>\n    static void TrapezoidationGriddingImp(const std::vector<property_type> & properties, const std::vector<const Polygon2D<num_type> * > & polygons, GridWorkItem<num_type> workItem, ProductPipe<property_type> & pipeline,  const Orientation2D o = Orientation2D::Vertical)\n    {\n        for(size_t i = workItem.begin; i < workItem.end; ++i){\n            const auto & property = properties[i];\n            const auto & polygon = polygons[i];\n            if(nullptr == polygon) continue;\n\n            std::vector<Polygon2D<num_type> > trapezoids;\n            TrapezoidationPolygon(polygon, trapezoids, o);\n\n            GriddingTrapezoidation<property_type, num_type>(property, trapezoids, o, workItem.ctrl, pipeline);\n        }\n    }\n\n    template <typename num_type>\n    static bool TrapezoidationPolygon(const Polygon2D<num_type> * polygon, std::vector<Polygon2D<num_type> > & trapezoids, const Orientation2D o)\n    {\n        using namespace boost::polygon;\n        trapezoids.clear();\n        boolean::PolygonSet2D<num_type> ps;\n        ps.insert(*polygon);\n        ps.get_trapezoids(trapezoids, (o == Orientation2D::Horizontal) ? orientation_2d_enum::HORIZONTAL : orientation_2d_enum::VERTICAL);\n    } \n\n    template <typename num_type>\n    static bool TriangulationPolygon(const Polygon2D<num_type> * polygon, tri::Triangulation<Point2D<num_type> > & triangulation)\n    {\n        using Point = Point2D<num_type>;\n        using Edge = tri::IndexEdge;\n        using Triangulator = tri::Triangulator2D<num_type>;\n        if(nullptr == polygon) return false;\n\n        std::list<Edge> edges;\n        size_t size = polygon->Size();\n        for(size_t i = 0; i < size; ++i)\n            edges.push_back(Edge{i, (i + 1) % size});\n\n        auto points = polygon->GetPoints();\n        if constexpr (std::is_integral<num_type>::value){\n            tri::RemoveDuplicatesAndRemapEdges(points, edges, num_type(2));\n        }\n\n        triangulation.Clear();\n        Triangulator triangulator(triangulation);\n        try {\n            triangulator.InsertVertices(points.begin(), points.end(), [](const Point & p){ return p[0]; }, [](const Point & p){ return p[1]; });\n            triangulator.InsertEdges(edges.begin(), edges.end(), [](const Edge & e){ return e.v1(); }, [](const Edge & e){ return e.v2(); });\n            triangulator.EraseOuterTriangles();\n        }\n        catch ( ... ){\n            return false;\n        }\n\n        return true;\n    }\n\n    template <typename property_type, typename num_type>\n    static void GriddingTriangulation(const property_type & property, const tri::Triangulation<Point2D<num_type> > & triangulation, const GridCtrl<num_type> & ctrl, ProductPipe<property_type> & pipeline)\n    {\n        using Utility = tri::TriangulationUtility<Point2D<num_type> >;\n        for(auto it = 0; it < triangulation.triangles.size(); ++it){\n            auto triangle = Utility::GetTriangle(triangulation, it);\n            GriddingTriangle<property_type, num_type>(property, triangle, ctrl, pipeline);\n        }\n    }\n\n    template <typename property_type, typename num_type>\n    static void GriddingTrapezoidation(const property_type & property, std::vector<Polygon2D<num_type> > & trapezoidation, const Orientation2D o, const GridCtrl<num_type> & ctrl, ProductPipe<property_type> & pipeline)\n    {\n        for(auto & trapezoid : trapezoidation){\n            if(trapezoid.Front() == trapezoid.Back()) trapezoid.PopBack();\n            GriddingTrapezoid<property_type, num_type>(property, trapezoid, o, ctrl, pipeline);\n        }\n    }\n\n    template <typename property_type, typename num_type>\n    static void GriddingTrapezoid(const property_type & property, const Polygon2D<num_type> & trapezoid, const Orientation2D o, const GridCtrl<num_type> & ctrl, ProductPipe<property_type> & pipeline)\n    {\n        std::list<Box2D<num_type> > rects;\n        std::list<Triangle2D<num_type> > triangles;\n        DecomposeTrapezoid(trapezoid, o, rects, triangles);\n\n        for(const auto & rect : rects)\n            GriddingRectangle<property_type, num_type>(property, rect, ctrl, pipeline);\n        \n        for(const auto & triangle : triangles)\n            GriddingTriangle<property_type, num_type>(property, triangle, ctrl, pipeline);\n    }\n\n    template <typename num_type>\n    static void DecomposeTrapezoid(const Polygon2D<num_type> & trapezoid, const Orientation2D o, std::list<Box2D<num_type> > & rects, std::list<Triangle2D<num_type> > & triangles)\n    {\n        rects.clear();\n        triangles.clear();\n        auto size = trapezoid.Size();\n        if(3 == size){\n            triangles.push_back({trapezoid[0], trapezoid[1], trapezoid[2]});\n            return;\n        }\n        else if(4 == size){\n            bool res;\n            auto points = std::array<Point2D<num_type>, 4>{trapezoid[0], trapezoid[1], trapezoid[2], trapezoid[3]};\n            auto t = toTrapezoid(points, o, res);\n            GENERIC_ASSERT(res);\n\n            DecomposeTrapezoid(t, rects, triangles);\n            return;\n        }\n        else {\n            auto polygon = trapezoid;\n            Polygon2D<num_type>::Clean(polygon);\n            GENERIC_ASSERT(polygon.Size() != trapezoid.Size())\n            DecomposeTrapezoid(polygon, o, rects, triangles);\n        }\n    }\n\n    template <typename num_type>\n    static void DecomposeTrapezoid(const Trapezoid<num_type> & trapezoid, std::list<Box2D<num_type> > & rects, std::list<Triangle2D<num_type> > & triangles)\n    {\n        GENERIC_ASSERT(trapezoid.isValid())\n        Point2D<num_type> p[4] = { trapezoid[0], trapezoid[1], trapezoid[2], trapezoid[3] };\n        if(math::EQ<num_type>(trapezoid.length[0], 0)){\n            triangles.push_back({p[0], p[2], p[3]});\n            return;\n        }\n        if(math::EQ<num_type>(trapezoid.length[1], 0)){\n            triangles.push_back({p[0], p[1], p[3]});\n            return;\n        }\n\n        auto i = trapezoid.direction == Orientation2D::Horizontal ? 0 : 1;\n        auto h = trapezoid.direction == Orientation2D::Horizontal ? true : false;\n        auto d03 = p[3][i] - p[0][i];\n        auto d12 = p[2][i] - p[1][i];\n        if(math::isNegative(d03) && math::isNegative(d03 + trapezoid.length[1])){\n            triangles.push_back({p[0], p[1], p[2]});\n            triangles.push_back({p[0], p[2], p[3]});\n            return;\n        }\n        if(math::isPositive(d03) && math::isPositive(d03 - trapezoid.length[0])){\n            triangles.push_back({p[0], p[1], p[2]});\n            triangles.push_back({p[0], p[2], p[3]});\n            return; \n        }\n        auto s03 = h ? Point2D<num_type>(d03, 0) : Point2D<num_type>(0, d03);\n        auto s12 = h ? Point2D<num_type>(d12, 0) : Point2D<num_type>(0, d12);\n        auto p03 = math::isPositive(d03) ? p[0] + s03 : p[3] - s03;\n        auto p12 = math::isPositive(d12) ? p[2] - s12 : p[1] + s12;\n\n        if(math::NE<num_type>(d03, 0)) triangles.push_back({p[0], p03, p[3]});\n        if(math::NE<num_type>(d12, 0)) triangles.push_back({p[1], p[2], p12});\n        Box2D<num_type> rect;\n        rect |= p03;\n        rect |= p12;\n        rect |= math::isNegative(d03) ? p[0] : p[3];\n        rect |= math::isNegative(d12) ? p[2] : p[1];\n        rects.push_back(std::move(rect));\n    }\n\n    template <typename property_type, typename num_type>\n    static void GriddingRectangle(const property_type & property, const Box2D<num_type> & rect, const GridCtrl<num_type> & ctrl, ProductPipe<property_type> & pipeline)\n    {\n        auto [sx, sy] = Rasterization::Rasterize(rect[0], ctrl.stride, ctrl.ref);\n        auto [ex, ey] = Rasterization::Rasterize(rect[1], ctrl.stride, ctrl.ref);\n\n        bool swapped = false;\n        if(math::GT(ey - sy, ex - sx)){\n            std::swap(sx, sy);\n            std::swap(ex, ey);\n            swapped = true;\n        }\n\n        auto boundLLStride = [&rect, &ctrl](int index, size_t coor) { return ctrl.ref[coor] + (index + 1) * ctrl.stride[coor] - rect[0][coor]; };\n        auto boundURStride = [&rect, &ctrl](int index, size_t coor) { return rect[1][coor] - index * ctrl.stride[coor] - ctrl.ref[coor]; };\n        auto middleStride  = [&rect](size_t coor) {return rect[1][coor] - rect[0][coor]; };\n        auto gridLength = [&](int i, int lb, int ub, size_t coor)\n        {\n            auto len = ctrl.stride[coor];\n            if(lb == ub) len = middleStride(coor);\n            else if(i == lb) len = boundLLStride(i, coor);\n            else if(i == ub) len = boundURStride(i, coor);\n            return len;\n        };\n\n        auto area = ctrl.stride[0] * ctrl.stride[1];\n        using Result = Product<property_type>;\n        for(auto i = sx; i <= ex; ++i){\n            auto len1 = gridLength(i, sx, ex, swapped ? 1 : 0);\n            GENERIC_ASSERT(len1 >= 0)\n            for(auto j = sy; j <= ey; ++j){\n                auto len2 = gridLength(j, sy, ey, swapped ? 0 : 1);\n                GENERIC_ASSERT(len2 >= 0)\n                auto ratio = double(len1 * len2) / area;\n                auto res = swapped ? Result{j, i, property, ratio} : Result{i, j, property, ratio};\n                while(!pipeline.push(res));\n            }\n        }\n    }\n\n    template <typename property_type, typename num_type>\n    static void GriddingTriangle(const property_type & property, const Triangle2D<num_type> & triangle, const GridCtrl<num_type> & ctrl, ProductPipe<property_type> & pipeline)\n    {\n        std::vector<std::array<int, 2> > grids;\n        std::map<int, std::set<int> > orderedGrids;\n        Rasterization::Rasterize(triangle, ctrl.stride, grids, ctrl.ref);\n        for(const auto & grid : grids){\n            if(!orderedGrids.count(grid[0]))\n                orderedGrids.insert(std::make_pair(grid[0], std::set<int>{}));\n            orderedGrids[grid[0]].insert(grid[1]);\n        }\n\n        auto getBox = [&ctrl](int x, int y)\n        {\n            Point2D<num_type> ll = ctrl.ref + Point2D<num_type>(x * ctrl.stride[0], y * ctrl.stride[1]);\n            Point2D<num_type> ur = ll + ctrl.stride;\n            return Box2D<num_type>(ll, ur);\n        };\n        \n        auto area = ctrl.stride[0] * ctrl.stride[1];\n        using Result = Product<property_type>;\n        auto iter_x = orderedGrids.begin();\n        for(; iter_x != orderedGrids.end(); ++iter_x){\n            const auto & x = iter_x->first;\n            const auto & orderedYs = iter_x->second;\n            auto sy = *orderedYs.begin();\n            auto ey = *orderedYs.rbegin();\n            for(auto y = sy; y <= ey; ++y){\n                double ratio(0);\n                auto box = getBox(x, y);\n                if(Contains(box, triangle)) ratio = double(triangle.Area()) / area;\n                else if(Contains(triangle, box)) ratio = 1.0;\n                else {\n                    std::list<Polygon2D<num_type> > intersects;\n                    boolean::Intersect(box, triangle, intersects);\n                    for(const auto & intersect : intersects)\n                        ratio += double(boost::polygon::area(intersect)) / area;\n                }  \n                while(!pipeline.push(Result{x, y, property, ratio}));\n            }\n        }\n    }\n};\n\n///@brief a demo class that use `OccupancyGridMappingFactory` to calculate grid metal density for a collection of geometries\ntemplate <typename num_type>\nclass DensityGridMapCalculator\n{\n    using Occupancy = float;\n    using Property = const Polygon2D<num_type> *;\npublic:\n    using DensityGridMap = OccupancyGridMap<Occupancy>;\n    using Factory = OccupancyGridMappingFactory;\n    using Product = Factory::Product<Property>;\n\n    /**\n     * @brief insert a polygon object to the calculator\n     * @param[in] polygon input polygon object\n     * @param[in] isHole whether input is a hole polyogn \n     */\n    void Insert(const Polygon2D<num_type> & polygon, bool isHole = false)\n    {\n        if(!isHole){\n            m_solids.push_back(&polygon);\n            m_solidPropties.push_back(&polygon);        \n        }\n        else{\n            m_holes.push_back(&polygon);\n            m_holePropties.push_back(&polygon);\n        }\n    }\n\n    /**\n     * @brief insert a polygon with hole object to the calculator\n     * @param[in] pwh input polygon with hole object \n     */\n    void Insert(const PolygonWithHoles2D<num_type> & pwh)\n    {\n        Insert(pwh.outline);\n        for(const auto & hole : pwh.holes)\n            Insert(hole, true);\n    }\n\n    /**\n     * @brief calculate metal density grid map of inserted geometries\n     * @param[in] bbox the bounding region of input geometries \n     * @param[in] stride the grid width and length\n     * @param[in] threads thread number when generating the grid map parallelly\n     * @return[in] an unique pointer that hold the generated density grid map\n     */\n    std::unique_ptr<DensityGridMap> CalculateGridMap(const Box2D<num_type> & bbox, const Vector2D<num_type> & stride, size_t threads = 1)\n    {\n        auto [width, height] = Factory::GetGridMapSize(bbox, stride);\n        auto gridMap = std::make_unique<DensityGridMap>(width, height);\n\n        auto ctrl = typename Factory::GridCtrl<num_type>(bbox, stride, threads);\n        \n        auto solidBlend = [](typename DensityGridMap::ResultType & res, const Product & p) { res += p.ratio;};\n        auto holeBlend =  [](typename DensityGridMap::ResultType & res, const Product & p) { res -= p.ratio;};\n\n        Factory::Map2Grid<Property>(m_solidPropties, m_solids, ctrl, *gridMap, solidBlend);\n        Factory::Map2Grid<Property>(m_holePropties, m_holes, ctrl, *gridMap, holeBlend);\n\n        return gridMap;\n    }\nprivate:\n    std::vector<Property> m_solidPropties;\n    std::vector<Property> m_holePropties;\n    std::vector<const Polygon2D<num_type> * > m_solids;\n    std::vector<const Polygon2D<num_type> * > m_holes;\n};\n\n}//namespace geometry\n}//namespace generic\n#endif//GENERIC_GEOMETRY_OCCUPANCYGRIDMAP_HPP", "meta": {"hexsha": "b5f09689edd10e75410a023d11cfa92604c2949b", "size": 29667, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "geometry/OccupancyGridMap.hpp", "max_stars_repo_name": "Draaaaaaven/generic", "max_stars_repo_head_hexsha": "f72a1896058486ef865cb2a0a722d70b2398a7af", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2022-01-05T02:34:04.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-19T13:51:50.000Z", "max_issues_repo_path": "geometry/OccupancyGridMap.hpp", "max_issues_repo_name": "Draaaaaaven/generic", "max_issues_repo_head_hexsha": "f72a1896058486ef865cb2a0a722d70b2398a7af", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "geometry/OccupancyGridMap.hpp", "max_forks_repo_name": "Draaaaaaven/generic", "max_forks_repo_head_hexsha": "f72a1896058486ef865cb2a0a722d70b2398a7af", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 43.3728070175, "max_line_length": 270, "alphanum_fraction": 0.6331951326, "num_tokens": 7501, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5544704796847396, "lm_q2_score": 0.5506073655352404, "lm_q1q2_score": 0.30529553008627547}}
{"text": "//==============================================================================\n//         Copyright 2003 - 2011   LASMEA UMR 6602 CNRS/Univ. Clermont II\n//         Copyright 2009 - 2011   LRI    UMR 8623 CNRS/Univ Paris Sud XI\n//\n//          Distributed under the Boost Software License, Version 1.0.\n//                 See accompanying file LICENSE.txt or copy at\n//                     http://www.boost.org/LICENSE_1_0.txt\n//==============================================================================\n#ifndef NT2_TRIGONOMETRIC_CONSTANTS_PIO2_3T_HPP_INCLUDED\n#define NT2_TRIGONOMETRIC_CONSTANTS_PIO2_3T_HPP_INCLUDED\n\n#include <nt2/include/functor.hpp>\n#include <boost/simd/constant/hierarchy.hpp>\n#include <boost/simd/constant/register.hpp>\nnamespace nt2\n{\n  namespace tag\n  {\n   /*!\n     @brief Pio2_3t generic tag\n\n     Represents the Pio2_3t constant in generic contexts.\n\n     @par Models:\n        Hierarchy\n   **/\n    // 8.47842766036889956997e-32\n    BOOST_SIMD_CONSTANT_REGISTER( Pio2_3t, double\n                                , 0, 0x248d3132\n                                , 0x397B839A252049C1ll\n                                )\n  }\n  namespace ext\n  {\n   template<class Site, class... Ts>\n   BOOST_FORCEINLINE generic_dispatcher<tag::Pio2_3t, Site> dispatching_Pio2_3t(adl_helper, boost::dispatch::meta::unknown_<Site>, boost::dispatch::meta::unknown_<Ts>...)\n   {\n     return generic_dispatcher<tag::Pio2_3t, Site>();\n   }\n   template<class... Args>\n   struct impl_Pio2_3t;\n  }\n  /*!\n    Constant used in modular computation involving \\f$\\pi\\f$\n\n    @par Semantic:\n\n    For type T0:\n\n    @code\n    T0 r = Pio2_3t<T0>();\n    @endcode\n\n    @return a value of type T0\n  **/\n  BOOST_SIMD_CONSTANT_IMPLEMENTATION(tag::Pio2_3t, Pio2_3t);\n}\n\n#endif\n\n", "meta": {"hexsha": "333915c4a4ce2718e2bf1934b44aa744ddf8f496", "size": 1762, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/core/trigonometric/include/nt2/trigonometric/constants/pio2_3t.hpp", "max_stars_repo_name": "psiha/nt2", "max_stars_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "modules/core/trigonometric/include/nt2/trigonometric/constants/pio2_3t.hpp", "max_issues_repo_name": "psiha/nt2", "max_issues_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "modules/core/trigonometric/include/nt2/trigonometric/constants/pio2_3t.hpp", "max_forks_repo_name": "psiha/nt2", "max_forks_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.8852459016, "max_line_length": 170, "alphanum_fraction": 0.5817253121, "num_tokens": 472, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5467381667555714, "lm_q2_score": 0.5583269943353745, "lm_q1q2_score": 0.30525867733307094}}
{"text": "/*****************************************************************************\n * This file is huge, it contains everything from parsing yaml files, linear\n * algebra functions to networking code used for robotics.\n *\n * Contents:\n * - Data Type\n * - Macros\n * - Data\n * - Filesystem\n * - Algebra\n * - Linear Algebra\n * - Geometry\n * - Differential Geometry\n * - Statistics\n * - Transform\n * - Time\n *\n ****************************************************************************/\n#pragma once\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <time.h>\n#include <sys/time.h>\n#include <inttypes.h>\n#include <dirent.h>\n#include <execinfo.h>\n#include <signal.h>\n#include <unistd.h>\n#include <errno.h>\n#include <pthread.h>\n#include <netdb.h>\n#include <netinet/in.h>\n#include <arpa/inet.h>\n#include <sys/types.h>\n#include <sys/socket.h>\n#include <sys/poll.h>\n\n#include <iostream>\n#include <sstream>\n#include <fstream>\n#include <string>\n#include <random>\n#include <set>\n#include <list>\n#include <deque>\n#include <vector>\n#include <map>\n#include <unordered_map>\n#include <unordered_set>\n#include <type_traits>\n\n#include <Eigen/Dense>\n\n/******************************************************************************\n *                                DATA TYPE\n *****************************************************************************/\n\n/* PRECISION TYPE */\n#define PRECISION 1 // Single Precision\n// #define PRECISION 2 // Double Precision\n\n#if PRECISION == 1\n  #define real_t float\n#elif PRECISION == 2\n  #define real_t double\n#else\n  #define real_t double\n#endif\n\n#define col_major_t Eigen::ColMajor\n#define row_major_t Eigen::RowMajor\n\ntypedef Eigen::Matrix<real_t, 2, 1> vec2_t;\ntypedef Eigen::Matrix<real_t, 3, 1> vec3_t;\ntypedef Eigen::Matrix<real_t, 4, 1> vec4_t;\ntypedef Eigen::Matrix<real_t, 5, 1> vec5_t;\ntypedef Eigen::Matrix<real_t, 6, 1> vec6_t;\ntypedef Eigen::Matrix<real_t, Eigen::Dynamic, 1> vecx_t;\ntypedef Eigen::Matrix<real_t, 2, 2> mat2_t;\ntypedef Eigen::Matrix<real_t, 3, 3> mat3_t;\ntypedef Eigen::Matrix<real_t, 4, 4> mat4_t;\ntypedef Eigen::Matrix<real_t, Eigen::Dynamic, Eigen::Dynamic> matx_t;\ntypedef Eigen::Matrix<real_t, 3, 4> mat34_t;\ntypedef Eigen::Quaternion<real_t> quat_t;\ntypedef Eigen::AngleAxis<real_t> angle_axis_t;\ntypedef Eigen::Matrix<real_t, 1, Eigen::Dynamic> row_vector_t;\ntypedef Eigen::Matrix<real_t, Eigen::Dynamic, 1> col_vector_t;\ntypedef Eigen::Array<real_t, Eigen::Dynamic, 1> arrayx_t;\n\ntypedef std::vector<vec2_t, Eigen::aligned_allocator<vec2_t>> vec2s_t;\ntypedef std::vector<vec3_t, Eigen::aligned_allocator<vec3_t>> vec3s_t;\ntypedef std::vector<vec4_t, Eigen::aligned_allocator<vec4_t>> vec4s_t;\ntypedef std::vector<vec5_t, Eigen::aligned_allocator<vec5_t>> vec5s_t;\ntypedef std::vector<vec6_t, Eigen::aligned_allocator<vec6_t>> vec6s_t;\ntypedef std::vector<vecx_t> vecxs_t;\ntypedef std::vector<mat2_t, Eigen::aligned_allocator<mat2_t>> mat2s_t;\ntypedef std::vector<mat3_t, Eigen::aligned_allocator<mat3_t>> mat3s_t;\ntypedef std::vector<mat4_t, Eigen::aligned_allocator<mat4_t>> mat4s_t;\ntypedef std::vector<matx_t, Eigen::aligned_allocator<matx_t>> matxs_t;\ntypedef std::vector<quat_t, Eigen::aligned_allocator<quat_t>> quats_t;\n\ntemplate <int LENGTH, Eigen::StorageOptions STRIDE_TYPE = Eigen::ColMajor>\nusing vec_t = Eigen::Matrix<real_t, LENGTH, 1, STRIDE_TYPE>;\n\ntemplate <int ROWS,\n          int COLS,\n          Eigen::StorageOptions STRIDE_TYPE = Eigen::ColMajor>\nusing mat_t = Eigen::Matrix<real_t, ROWS, COLS, STRIDE_TYPE>;\n\ntemplate <int ROWS,\n          int COLS,\n          Eigen::StorageOptions STRIDE_TYPE = Eigen::ColMajor>\nusing map_mat_t = Eigen::Map<Eigen::Matrix<real_t, ROWS, COLS, STRIDE_TYPE>>;\n\ntemplate <int ROWS>\nusing map_vec_t = Eigen::Map<Eigen::Matrix<real_t, ROWS, 1>>;\n\ntypedef uint64_t timestamp_t;\ntypedef std::vector<timestamp_t> timestamps_t;\n\n/******************************************************************************\n *                                MACROS\n *****************************************************************************/\n\n#define __FILENAME__                                                           \\\n  (strrchr(__FILE__, '/') ? strrchr(__FILE__, '/') + 1 : __FILE__)\n\n#define LOG_ERROR(M, ...)                                                      \\\n  fprintf(stderr,                                                              \\\n          \"\\033[31m[ERROR] [%s:%d] \" M \"\\033[0m\\n\",                            \\\n          __FILENAME__,                                                        \\\n          __LINE__,                                                            \\\n          ##__VA_ARGS__)\n\n#define LOG_INFO(M, ...) fprintf(stdout, \"[INFO] \" M \"\\n\", ##__VA_ARGS__)\n#define LOG_WARN(M, ...)                                                       \\\n  fprintf(stdout, \"\\033[33m[WARN] \" M \"\\033[0m\\n\", ##__VA_ARGS__)\n\n#define FATAL(M, ...)                                                          \\\n  fprintf(stdout,                                                              \\\n          \"\\033[31m[FATAL] [%s:%d] \" M \"\\033[0m\\n\",                            \\\n          __FILENAME__,                                                        \\\n          __LINE__,                                                            \\\n          ##__VA_ARGS__);                                                      \\\n  exit(-1)\n\n#ifdef NDEBUG\n#define DEBUG(M, ...)\n#else\n#define DEBUG(M, ...) fprintf(stdout, \"[DEBUG] \" M \"\\n\", ##__VA_ARGS__)\n#endif\n\n#define UNUSED(expr)                                                           \\\n  do {                                                                         \\\n    (void) (expr);                                                             \\\n  } while (0)\n\n#ifndef CHECK\n#define CHECK(A, M, ...)                                                       \\\n  if (!(A)) {                                                                  \\\n    LOG_ERROR(M, ##__VA_ARGS__);                                               \\\n    goto error;                                                                \\\n  }\n#endif\n\n/******************************************************************************\n *                                  DATA\n *****************************************************************************/\n\n/**\n * Convert bytes to signed 8bit number\n */\nint8_t int8(const uint8_t *data, const size_t offset);\n\n/**\n * Convert bytes to unsigned 8bit number\n */\nuint8_t uint8(const uint8_t *data, const size_t offset);\n\n/**\n * Convert bytes to signed 16bit number\n */\nint16_t int16(const uint8_t *data, const size_t offset);\n\n/**\n * Convert bytes to unsigned 16bit number\n */\nuint16_t uint16(const uint8_t *data, const size_t offset);\n\n/**\n * Convert bytes to signed 32bit number\n */\nint32_t int32(const uint8_t *data, const size_t offset);\n\n/**\n * Convert bytes to unsigned 32bit number\n */\nuint32_t uint32(const uint8_t *data, const size_t offset);\n\n/**\n * Allocate memory for a C-style string\n */\nchar *malloc_string(const char *s);\n\n/**\n * Get number of rows in CSV file.\n * @returns Number of rows in CSV file else -1 for failure.\n */\nint csv_rows(const char *fp);\n\n/**\n * Get number of cols in CSV file.\n * @returns Number of cols in CSV file else -1 for failure.\n */\nint csv_cols(const char *fp);\n\n/**\n * Return csv fields as strings and number of fields in csv file.\n */\nchar **csv_fields(const char *fp, int *nb_fields);\n\n/**\n * Load data in csv file `fp`. Assumming the data are real_ts. Also returns\n * number of rows and cols in `nb_rows` and `nb_cols` respectively.\n */\nreal_t **csv_data(const char *fp, int *nb_rows, int *nb_cols);\n\n/**\n * Load integer arrays in csv file located at `csv_path`. The number of arrays\n * is returned in `nb_arrays`.\n */\nint **load_iarrays(const char *csv_path, int *nb_arrays);\n\n/**\n * Load real_t arrays in csv file located at `csv_path`. The number of arrays\n * is returned in `nb_arrays`.\n */\nreal_t **load_darrays(const char *csv_path, int *nb_arrays);\n\n/**\n * Get number of rows in CSV file.\n * @returns Number of rows in CSV file else -1 for failure.\n */\nint csv_rows(const std::string &file_path);\n\n/**\n * Get number of columns in CSV file.\n * @returns Number of columns in CSV file else -1 for failure.\n */\nint csv_cols(const std::string &file_path);\n\n/**\n * Convert CSV file to matrix.\n * @returns 0 for success, -1 for failure\n */\nint csv2mat(const std::string &file_path, const bool header, matx_t &data);\n\n/**\n * Convert matrix to csv file.\n * @returns 0 for success, -1 for failure\n */\nint mat2csv(const std::string &file_path, const matx_t &data);\n\n/**\n * Convert vector to csv file.\n * @returns 0 for success, -1 for failure\n */\nint vec2csv(const std::string &file_path, const std::deque<vec3_t> &data);\n\n/**\n * Convert timestamps to csv file.\n * @returns 0 for success, -1 for failure\n */\nint ts2csv(const std::string &file_path, const std::deque<timestamp_t> &data);\n\n/**\n * Print progress to screen\n */\nvoid print_progress(const real_t percentage);\n\n/**\n * Check if vector `x` is all true.\n */\nbool all_true(const std::vector<bool> x);\n\nint check_jacobian(const std::string &jac_name,\n                   const matx_t &fdiff,\n                   const matx_t &jac,\n                   const real_t threshold,\n                   const bool print = false);\n\n/******************************************************************************\n *                                FILESYSTEM\n *****************************************************************************/\n\n/**\n * Open file in `path` with `mode` and set `nb_rows`.\n * @returns File pointer on success, nullptr on failure.\n */\nFILE *file_open(const std::string &path,\n                const std::string &mode,\n                int *nb_rows = nullptr);\n\n/**\n * Skip file line in file `fp`.\n */\nvoid skip_line(FILE *fp);\n\n/**\n * Get number of rows in file.\n * @returns Number of rows in file else -1 for failure.\n */\nint file_rows(const std::string &file_path);\n\n/**\n * Copy file from path `src` to path `dest.\n *\n * @returns 0 for success else -1 if `src` file could not be opend, or -2 if\n * `dest` file could not be opened.\n */\nint file_copy(const std::string &src, const std::string &dest);\n\n/**\n * Return file extension in `path`.\n */\nstd::string parse_fext(const std::string &path);\n\n/**\n * Return basename\n */\nstd::string parse_fname(const std::string &path);\n\n/**\n * Check if file exists\n *\n * @param path Path to file\n * @returns true or false\n */\nbool file_exists(const std::string &path);\n\n/**\n * Check if path exists\n *\n * @param path Path\n * @returns true or false\n */\nbool dir_exists(const std::string &path);\n\n/**\n * Create directory\n *\n * @param path Path\n * @returns 0 for success, -1 for failure\n */\nint dir_create(const std::string &path);\n\n/**\n * Return directory name\n *\n * @param path Path\n * @returns directory name\n */\nstd::string dir_name(const std::string &path);\n\n/**\n * Strips a target character from the start and end of a string\n *\n * @param s String to strip\n * @param target Target character to strip\n * @returns Stripped string\n */\nstd::string strip(const std::string &s, const std::string &target = \" \");\n\n/**\n * Strips a target character from the end of a string\n *\n * @param s String to strip\n * @param target Target character to strip\n * @returns Stripped string\n */\nstd::string strip_end(const std::string &s, const std::string &target = \" \");\n\n/**\n * Create directory\n *\n * @param path Path to directory\n * @returns 0 for success, -1 for failure\n */\nint create_dir(const std::string &path);\n\n/**\n * Remove directory\n *\n * @param path Path to directory\n * @returns 0 for success, -1 for failure\n */\nint remove_dir(const std::string &path);\n\n/**\n * Remove file extension\n *\n * @param path Path to directory\n * @returns File path without extension\n */\nstd::string remove_ext(const std::string &path);\n\n/**\n * List directory\n *\n * @param path Path to directory\n * @param results List of files and directories\n * @returns 0 for success, -1 for failure\n */\nint list_dir(const std::string &path, std::vector<std::string> &results);\n\n/**\n * Split path into a number of elements\n *\n * @param path Path\n * @returns List of path elements\n */\nstd::vector<std::string> path_split(const std::string path);\n\n/**\n * Combine `path1` and `path2`\n *\n * @param path1 Path 1\n * @param path2 Path 22\n * @returns Combined path\n */\nstd::string paths_combine(const std::string path1, const std::string path2);\n\n/******************************************************************************\n *                                  ALGEBRA\n *****************************************************************************/\n\n/**\n * Sign of number\n *\n * @param[in] x Number to check sign\n * @return\n *    - 0: Number is zero\n *    - 1: Positive number\n *    - -1: Negative number\n */\nint sign(const real_t x);\n\n/**\n * Floating point comparator\n *\n * @param[in] f1 First value\n * @param[in] f2 Second value\n * @return\n *    - 0: if equal\n *    - 1: if f1 > f2\n *    - -1: if f1 < f2\n */\nint fltcmp(const real_t f1, const real_t f2);\n\n/**\n * Calculate binomial coefficient\n *\n * @param[in] n\n * @param[in] k\n * @returns Binomial coefficient\n */\nreal_t binomial(const real_t n, const real_t k);\n\n/**\n * Return evenly spaced numbers over a specified interval.\n */\ntemplate <typename T>\nstd::vector<T> linspace(const T start, const T end, const int num) {\n  std::vector<T> linspaced;\n\n  if (num == 0) {\n    return linspaced;\n  }\n  if (num == 1) {\n    linspaced.push_back(start);\n    return linspaced;\n  }\n\n  const real_t diff = static_cast<real_t>(end - start);\n  const real_t delta = diff / static_cast<real_t>(num - 1);\n  for (int i = 0; i < num - 1; ++i) {\n    linspaced.push_back(start + delta * i);\n  }\n  linspaced.push_back(end);\n  return linspaced;\n}\n\n/******************************************************************************\n *                              LINEAR ALGEBRA\n *****************************************************************************/\n\n/**\n * Print shape of a matrix\n *\n * @param[in] name Name of matrix\n * @param[in] A Matrix\n */\nvoid print_shape(const std::string &name, const matx_t &A);\n\n/**\n * Print shape of a vector\n *\n * @param[in] name Name of vector\n * @param[in] v Vector\n */\nvoid print_shape(const std::string &name, const vecx_t &v);\n\n/**\n * Print array\n *\n * @param[in] name Name of array\n * @param[in] array Target array\n * @param[in] size Size of target array\n */\nvoid print_array(const std::string &name,\n                 const real_t *array,\n                 const size_t size);\n\n/**\n * Print vector `v` with a `name`.\n */\nvoid print_vector(const std::string &name, const vecx_t &v);\n\n/**\n * Print matrix `m` with a `name`.\n */\nvoid print_matrix(const std::string &name, const matx_t &m);\n\n/**\n * Print quaternion `q` with a `name`.\n */\nvoid print_quaternion(const std::string &name, const quat_t &q);\n\n/**\n * Array to string\n *\n * @param[in] array Target array\n * @param[in] size Size of target array\n * @returns String of array\n */\nstd::string array2str(const real_t *array, const size_t size);\n\n/**\n * Convert real_t array to Eigen::Vector\n *\n * @param[in] x Input array\n * @param[in] size Size of input array\n * @param[out] y Output vector\n */\nvoid array2vec(const real_t *x, const size_t size, vecx_t &y);\n\n/**\n * Vector to array\n *\n * @param[in] v Vector\n * @returns Array\n */\nreal_t *vec2array(const vecx_t &v);\n\n/**\n * Matrix to array\n *\n * @param[in] m Matrix\n * @returns Array\n */\nreal_t *mat2array(const matx_t &m);\n\n/**\n * Quaternion to array\n *\n * *VERY IMPORTANT*: The returned array is (x, y, z, w).\n *\n * @param[in] q Quaternion\n * @returns Array\n */\nreal_t *quat2array(const quat_t &q);\n\n/**\n * Vector to array\n *\n * @param[in] v Vector\n * @param[out] out Output array\n */\nvoid vec2array(const vecx_t &v, real_t *out);\n\n/**\n * Matrix to array\n *\n * @param[in] m Matrix\n * @param[in] out Output array\n */\nvoid mat2array(const matx_t &m, real_t *out);\n\n/**\n * Matrix to list of vectors\n *\n * @param[in] m Matrix\n * @param[in] row_wise Row wise\n * @returns Vectors\n */\nstd::vector<vecx_t> mat2vec(const matx_t &m, const bool row_wise = true);\n\n/**\n * Matrix to list of vectors of size 3\n *\n * @param[in] m Matrix\n * @param[in] row_wise Row wise\n * @returns Vectors\n */\nvec3s_t mat2vec3(const matx_t &m, const bool row_wise = true);\n\n/**\n * Matrix to list of vectors of size 3\n *\n * @param[in] m Matrix\n * @param[in] row_wise Row wise\n * @returns Vectors\n */\nvec2s_t mat2vec2(const matx_t &m, const bool row_wise = true);\n\n/**\n * Vectors to matrix\n */\nmatx_t vecs2mat(const vec3s_t &vs);\n\n/**\n * Vector to string\n *\n * @param[in] v Vector\n * @param[in] brackets Brakcets around vector string\n * @returns Vector as a string\n */\nstd::string vec2str(const vecx_t &v, const bool brackets = true);\n\n/**\n * Array to string\n *\n * @param[in] arr Array\n * @param[in] len Length of array\n * @param[in] brackets Brakcets around vector string\n * @returns Array as a string\n */\nstd::string arr2str(const real_t *arr, const size_t len, bool brackets = true);\n\n/**\n * Matrix to string\n *\n * @param[in] m Matrix\n * @param[in] indent Indent string\n * @returns Array as a string\n */\nstd::string mat2str(const matx_t &m, const std::string &indent = \"  \");\n\n/**\n * Normalize vector x\n */\nvec2_t normalize(const vec2_t &x);\n\n/**\n * Normalize vector `v`.\n */\nvec3_t normalize(const vec3_t &v);\n\n/**\n * Condition number of `A`.\n */\nreal_t cond(const matx_t &A);\n\n/**\n * Zeros-matrix\n *\n * @param rows Number of rows\n * @param cols Number of cols\n * @returns Zeros matrix\n */\nmatx_t zeros(const int rows, const int cols);\n\n/**\n * Zeros square matrix\n *\n * @param size Square size of matrix\n * @returns Zeros matrix\n */\nmatx_t zeros(const int size);\n\n/**\n * Identity-matrix\n *\n * @param rows Number of rows\n * @param cols Number of cols\n * @returns Identity matrix\n */\nmatx_t I(const int rows, const int cols);\n\n/**\n * Identity square matrix\n *\n * @param size Square size of matrix\n * @returns Identity square matrix\n */\nmatx_t I(const int size);\n\n/**\n * Ones-matrix\n *\n * @param rows Number of rows\n * @param cols Number of cols\n * @returns Ones square matrix\n */\nmatx_t ones(const int rows, const int cols);\n\n/**\n * Ones square matrix\n *\n * @param size Square size of matrix\n * @returns Ones square matrix\n */\nmatx_t ones(const int size);\n\n/**\n * Horizontally stack matrices A and B\n *\n * @param A Matrix A\n * @param B Matrix B\n * @returns Stacked matrix\n */\nmatx_t hstack(const matx_t &A, const matx_t &B);\n\n/**\n * Vertically stack matrices A and B\n *\n * @param A Matrix A\n * @param B Matrix B\n * @returns Stacked matrix\n */\nmatx_t vstack(const matx_t &A, const matx_t &B);\n\n/**\n * Diagonally stack matrices A and B\n *\n * @param A Matrix A\n * @param B Matrix B\n * @returns Stacked matrix\n */\nmatx_t dstack(const matx_t &A, const matx_t &B);\n\n/**\n * Skew symmetric-matrix\n *\n * @param w Input vector\n * @returns Skew symmetric matrix\n */\nmat3_t skew(const vec3_t &w);\n\n/**\n * Skew symmetric-matrix squared\n *\n * @param w Input vector\n * @returns Skew symmetric matrix squared\n */\nmat3_t skewsq(const vec3_t &w);\n\n/**\n * Enforce Positive Semi-Definite\n *\n * @param A Input matrix\n * @returns Positive semi-definite matrix\n */\nmatx_t enforce_psd(const matx_t &A);\n\n/**\n * Null-space of A\n *\n * @param A Input matrix\n * @returns Null space of A\n */\nmatx_t nullspace(const matx_t &A);\n\n/**\n * Load std::vector of real_ts to an Eigen::Matrix\n *\n * @param[in] x Matrix values\n * @param[in] rows Number of matrix rows\n * @param[in] cols Number of matrix colums\n * @param[out] y Output matrix\n */\nvoid load_matrix(const std::vector<real_t> &x,\n                 const int rows,\n                 const int cols,\n                 matx_t &y);\n\n/**\n * Load an Eigen::Matrix into a std::vector of real_ts\n *\n * @param[in] A Matrix\n * @param[out] x Output vector of matrix values\n */\nvoid load_matrix(const matx_t A, std::vector<real_t> &x);\n\n/**\n * Perform Schur's Complement\n */\nvoid schurs_complement(const matx_t &H, const vecx_t &b,\n                       const size_t m, const size_t r,\n                       matx_t &H_marg, vecx_t &b_marg,\n                       const bool precond=false, const bool debug=false);\n\n/******************************************************************************\n *                                 Geometry\n *****************************************************************************/\n\n/**\n * Sinc function.\n */\nreal_t sinc(const real_t x);\n\n/**\n * Degrees to radians\n *\n * @param[in] d Degree to be converted\n * @return Degree in radians\n */\nreal_t deg2rad(const real_t d);\n\n/**\n * Degrees to radians\n *\n * @param[in] d Degree to be converted\n * @return Degree in radians\n */\nvec3_t deg2rad(const vec3_t d);\n\n/**\n * Radians to degree\n *\n * @param[in] r Radian to be converted\n * @return Radian in degrees\n */\nreal_t rad2deg(const real_t r);\n\n/**\n * Radians to degree\n *\n * @param[in] r Radian to be converted\n * @return Radian in degrees\n */\nvec3_t rad2deg(const vec3_t &r);\n\n/**\n * Wrap angle in degrees to 180\n *\n * @param[in] d Degrees\n * @return Angle wraped to 180\n */\nreal_t wrap180(const real_t d);\n\n/**\n * Wrap angle in degrees to 360\n *\n * @param[in] d Degrees\n * @return Angle wraped to 360\n */\nreal_t wrap360(const real_t d);\n\n/**\n * Wrap angle in radians to PI\n *\n * @param[in] r Radians\n * @return Angle wraped to PI\n */\nreal_t wrapPi(const real_t r);\n\n/**\n * Wrap angle in radians to 2 PI\n *\n * @param[in] r Radians\n * @return Angle wraped to 2 PI\n */\nreal_t wrap2Pi(const real_t r);\n\n/**\n * Create a circle point of radius `r` at angle `theta` radians.\n */\nvec2_t circle(const real_t r, const real_t theta);\n\n/**\n * Create the sphere point with sphere radius `rho` at longitude `theta`\n * [radians] and latitude `phi` [radians].\n */\nvec3_t sphere(const real_t rho, const real_t theta, const real_t phi);\n\n/**\n * Create look at matrix.\n */\nmat4_t lookat(const vec3_t &cam_pos,\n              const vec3_t &target,\n              const vec3_t &up_axis = vec3_t{0.0, -1.0, 0.0});\n\n/**\n * Cross-Track error based on waypoint line between p1, p2, and robot position\n *\n * @param[in] p1 Waypoint 1\n * @param[in] p2 Waypoint 2\n * @param[in] pos Robot position\n * @return Cross track error\n */\nreal_t cross_track_error(const vec2_t &p1, const vec2_t &p2, const vec2_t &pos);\n\n/**\n * Check if point `pos` is left or right of line formed by `p1` and `p2`\n *\n * @param[in] p1 Waypoint 1\n * @param[in] p2 Waypoint 2\n * @param[in] pos Robot position\n * @returns\n *    - 1: Point is left of waypoint line formed by `p1` and `p2`\n *    - 2: Point is right of waypoint line formed by `p1` and `p2`\n *    - 0: Point is colinear with waypoint line formed by `p1` and `p2`\n */\nint point_left_right(const vec2_t &p1, const vec2_t &p2, const vec2_t &pos);\n\n/**\n * Calculate closest point given waypoint line between `p1`, `p2` and robot\n * position\n *\n * @param[in] p1 Waypoint 1\n * @param[in] p2 Waypoint 2\n * @param[in] p3 Robot position\n * @param[out] closest Closest point\n * @returns\n *    Unit number denoting where the closest point is on waypoint line. For\n *    example, a return value of 0.5 denotes the closest point is half-way\n *    (50%) of the waypoint line, alternatively a negative number denotes the\n *    closest point is behind the first waypoint.\n */\nreal_t closest_point(const vec2_t &p1,\n                     const vec2_t &p2,\n                     const vec2_t &p3,\n                     vec2_t &closest);\n\n#define EARTH_RADIUS_M 6378137.0\n\n/**\n * Calculate new latitude and logitude coordinates with an offset in North and\n * East direction.\n *\n * IMPORTANT NOTE: This function is only an approximation. As such do not rely\n * on this function for precise latitude, longitude offsets.\n *\n * @param lat_ref Latitude of origin (decimal format)\n * @param lon_ref Longitude of origin (decimal format)\n * @param offset_N Offset in North direction (meters)\n * @param offset_E Offset in East direction (meters)\n * @param lat_new New latitude (decimal format)\n * @param lon_new New longitude (decimal format)\n */\nvoid latlon_offset(real_t lat_ref,\n                   real_t lon_ref,\n                   real_t offset_N,\n                   real_t offset_E,\n                   real_t *lat_new,\n                   real_t *lon_new);\n\n/**\n * Calculate difference in distance in North and East from two GPS coordinates\n *\n * IMPORTANT NOTE: This function is only an approximation. As such do not rely\n * on this function for precise latitude, longitude diffs.\n *\n * @param lat_ref Latitude of origin (decimal format)\n * @param lon_ref Longitude of origin (decimal format)\n * @param lat Latitude of point of interest (decimal format)\n * @param lon Longitude of point of interest (decimal format)\n * @param dist_N Distance of point of interest in North axis [m]\n * @param dist_E Distance of point of interest in East axis [m]\n */\nvoid latlon_diff(real_t lat_ref,\n                 real_t lon_ref,\n                 real_t lat,\n                 real_t lon,\n                 real_t *dist_N,\n                 real_t *dist_E);\n\n/**\n * Calculate Euclidean distance between two GPS coordintes\n *\n * IMPORTANT NOTE: This function is only an approximation. As such do not rely\n * on this function for precise latitude, longitude distance.\n *\n * @param lat_ref Latitude of origin (decimal format)\n * @param lon_ref Longitude of origin (decimal format)\n * @param lat Latitude of point of interest (decimal format)\n * @param lon Longitude of point of interest (decimal format)\n *\n * @returns Euclidean distance between two GPS coordinates [m]\n */\nreal_t latlon_dist(real_t lat_ref, real_t lon_ref, real_t lat, real_t lon);\n\n/*****************************************************************************\n *                         DIFFERENTIAL GEOMETRY\n *****************************************************************************/\n\nnamespace lie {\n\nmat3_t Exp(const vec3_t &phi);\nvec3_t Log(const mat3_t &C);\nmat3_t Jr(const vec3_t &psi);\n\n} // namespace lie\n\n\n/******************************************************************************\n *                                STATISTICS\n *****************************************************************************/\n\n/**\n * Create random integer\n *\n * @param[in] ub Upper bound\n * @param[in] lb Lower bound\n * @return Random integer\n */\nint randi(const int ub, const int lb);\n\n/**\n * Create random real_t\n *\n * @param[in] ub Upper bound\n * @param[in] lb Lower bound\n * @return Random floating point\n */\nreal_t randf(const real_t ub, const real_t lb);\n\n/**\n * Calculate median given an array of numbers\n *\n * @param[in] v Array of numbers\n * @return Median of given array\n */\nreal_t median(const std::vector<real_t> &v);\n\n/**\n * Mean vector\n *\n * @param[in] x List of vectors\n * @return Mean vector\n */\nvec3_t mean(const vec3s_t &x);\n\n/**\n * Shannon Entropy of a given covariance matrix `covar`.\n */\nreal_t shannon_entropy(const matx_t &covar);\n\n/**\n * Multivariate normal.\n */\nvec3_t mvn(std::default_random_engine &engine,\n           const vec3_t &mu = vec3_t{0.0, 0.0, 0.0},\n           const vec3_t &stdev = vec3_t{1.0, 1.0, 1.0});\n\n/**\n * Gassian normal.\n * http://c-faq.com/lib/gaussian.html\n */\nreal_t gauss_normal();\n\n/*****************************************************************************\n *                               TRANSFORM\n *****************************************************************************/\n\n/**\n * Form a 4x4 homogeneous transformation matrix from a\n * rotation matrix `C` and translation vector `r`.\n */\ntemplate <typename T>\nEigen::Matrix<T, 4, 4> tf(const Eigen::Matrix<T, 3, 3> &C,\n                          const Eigen::Matrix<T, 3, 1> &r) {\n  Eigen::Matrix<T, 4, 4> transform = Eigen::Matrix<T, 4, 4>::Identity();\n  transform.block(0, 0, 3, 3) = C;\n  transform.block(0, 3, 3, 1) = r;\n  return transform;\n}\n\n/**\n * Form a 4x4 homogeneous transformation matrix from a pointer to real_t array\n * containing (quaternion + translation) 7 elements: (qw, qx, qy, qz, x, y, z)\n */\nmat4_t tf(const vecx_t &params);\n\n/**\n * Form a 4x4 homogeneous transformation matrix from a\n * rotation matrix `C` and translation vector `r`.\n */\nmat4_t tf(const mat3_t &C, const vec3_t &r);\n\n/**\n * Form a 4x4 homogeneous transformation matrix from a\n * Hamiltonian quaternion `q` and translation vector `r`.\n */\nmat4_t tf(const quat_t &q, const vec3_t &r);\n\n/**\n * Extract rotation from transform\n */\ninline mat3_t tf_rot(const mat4_t &tf) { return tf.block<3, 3>(0, 0); }\n\n/**\n * Extract rotation and convert to quaternion from transform\n */\ninline quat_t tf_quat(const mat4_t &tf) { return quat_t{tf.block<3, 3>(0, 0)}; }\n\n/**\n * Extract translation from transform\n */\ninline vec3_t tf_trans(const mat4_t &tf) { return tf.block<3, 1>(0, 3); }\n\n\n/**\n * Perturb the rotation element in the tranform `T` by `step_size` at index\n * `i`. Where i = 0 for x-axis, i = 1 for y-axis, and i = 2 for z-axis.\n */\nmat4_t tf_perturb_rot(const mat4_t &T, real_t step_size, const int i);\n\n/**\n * Perturb the translation element in the tranform `T` by `step_size` at index\n * `i`. Where i = 0 for x-axis, i = 1 for y-axis, and i = 2 for z-axis.\n */\nmat4_t tf_perturb_trans(const mat4_t &T, real_t step_size, const int i);\n\n/**\n * Transform point `p` with transform `T`.\n */\nvec3_t tf_point(const mat4_t &T, const vec3_t &p);\n\n/**\n * Rotation matrix around x-axis (counter-clockwise, right-handed).\n * @returns Rotation matrix\n */\nmat3_t rotx(const real_t theta);\n\n/**\n * Rotation matrix around y-axis (counter-clockwise, right-handed).\n * @returns Rotation matrix\n */\nmat3_t roty(const real_t theta);\n\n/**\n * Rotation matrix around z-axis (counter-clockwise, right-handed).\n * @returns Rotation matrix\n */\nmat3_t rotz(const real_t theta);\n\n/**\n * Convert euler sequence 123 to rotation matrix R\n * This function assumes we are performing a body fixed intrinsic rotation.\n *\n * Source:\n *\n *     Kuipers, Jack B. Quaternions and Rotation Sequences: A Primer with\n *     Applications to Orbits, Aerospace, and Virtual Reality. Princeton, N.J:\n *     Princeton University Press, 1999. Print.\n *\n *     Page 86.\n *\n * @returns Rotation matrix\n */\nmat3_t euler123(const vec3_t &euler);\n\n/**\n * Convert euler sequence 321 to rotation matrix R\n * This function assumes we are performing a body fixed intrinsic rotation.\n *\n * Source:\n *\n *     Kuipers, Jack B. Quaternions and Rotation Sequences: A Primer with\n *     Applications to Orbits, Aerospace, and Virtual Reality. Princeton, N.J:\n *     Princeton University Press, 1999. Print.\n *\n *     Page 86.\n *\n * @returns Rotation matrix\n */\nmat3_t euler321(const vec3_t &euler);\n\n/**\n * Convert roll, pitch and yaw to quaternion.\n */\nquat_t euler2quat(const vec3_t &euler);\n\n/**\n * Convert rotation vectors to rotation matrix using measured acceleration\n * `a_m` from an IMU and gravity vector `g`.\n */\nmat3_t vecs2rot(const vec3_t &a_m, const vec3_t &g);\n\n/**\n * Convert rotation vector `rvec` to rotation matrix.\n */\nmat3_t rvec2rot(const vec3_t &rvec, const real_t eps = 1e-5);\n\n/**\n * Convert quaternion to euler angles.\n */\nvec3_t quat2euler(const quat_t &q);\n\n/**\n * Convert quaternion to rotation matrix.\n */\nmat3_t quat2rot(const quat_t &q);\n\n/**\n * Convert small angle euler angle to quaternion.\n */\nquat_t quat_delta(const vec3_t &dalpha);\n\n/**\n * Return left quaternion product matrix.\n */\nmat4_t quat_lmul(const quat_t &q);\n\n/**\n * Return left quaternion product matrix (but only for x, y, z components).\n */\nmat3_t quat_lmul_xyz(const quat_t &q);\n\n/**\n * Return right quaternion product matrix.\n */\nmat4_t quat_rmul(const quat_t &q);\n\n/**\n * Return right quaternion product matrix (but only for x, y, z components).\n */\nmat3_t quat_rmul_xyz(const quat_t &q);\n\n/**\n * Return only the x, y, z, components of a quaternion matrix.\n */\nmat3_t quat_mat_xyz(const mat4_t &Q);\n\n/**\n * Initialize attitude using IMU gyroscope `w_m` and accelerometer `a_m`\n * measurements. The calculated attitude outputted into to `C_WS`. Note: this\n * function does not calculate initial yaw angle in the world frame. Only the\n * roll, and pitch are inferred from IMU measurements.\n */\nvoid imu_init_attitude(const vec3s_t w_m,\n                       const vec3s_t a_m,\n                       mat3_t &C_WS,\n                       const size_t buffer_size = 50);\n\n/*****************************************************************************\n *                                    TIME\n *****************************************************************************/\n\n/**\n * Print timestamp.\n */\nvoid timestamp_print(const timestamp_t &ts, const std::string &prefix = \"\");\n\n/**\n * Convert ts to second.\n */\nreal_t ts2sec(const timestamp_t &ts);\n\n/**\n * Convert nano-second to second.\n */\nreal_t ns2sec(const uint64_t ns);\n\n/**\n * Start timer.\n */\nstruct timespec tic();\n\n/**\n * Stop timer and return number of seconds.\n */\nfloat toc(struct timespec *tic);\n\n/**\n * Stop timer and return miliseconds elasped.\n */\nfloat mtoc(struct timespec *tic);\n\n/**\n * Get time now in milliseconds since epoch\n */\nreal_t time_now();\n\n/*****************************************************************************\n *                                BA DATA\n ****************************************************************************/\n\nstruct pose_t {\n  vec_t<7> param;\n\n  pose_t();\n  pose_t(const mat4_t &T);\n\n  quat_t rot() const;\n  vec3_t trans() const;\n  mat4_t T() const;\n\n  quat_t rot();\n  vec3_t trans();\n  mat4_t T();\n\n  void set_trans(const vec3_t &r);\n  void set_rot(const quat_t &q);\n  void set_rot(const mat3_t &C);\n};\ntypedef std::vector<pose_t> poses_t;\ntypedef std::vector<vec2_t> keypoints_t;\n\nvoid pose_print(const std::string &prefix, const pose_t &pose);\n\nposes_t load_poses(const std::string &csv_path);\nkeypoints_t parse_keypoints_line(const char *line);\nstd::vector<keypoints_t> load_keypoints(const std::string &data_path);\nvoid keypoints_print(const keypoints_t &keypoints);\nposes_t load_poses(const std::string &csv_path);\nkeypoints_t parse_keypoints_line(const char *line);\nstd::vector<keypoints_t> load_keypoints(const std::string &data_path);\nvoid keypoints_print(const keypoints_t &keypoints);\nmat3_t load_camera(const std::string &data_path);\nposes_t load_camera_poses(const std::string &data_path);\nposes_t load_target_pose(const std::string &data_path);\nreal_t **load_points(const std::string &data_path, int *nb_points);\nint **load_point_ids(const std::string &data_path, int *nb_points);\n", "meta": {"hexsha": "a5bf0f71a832694ccbad2556117e8b43ebc3980e", "size": 34321, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ba/cpp/util.hpp", "max_stars_repo_name": "daoran/ba", "max_stars_repo_head_hexsha": "d38e58a1f9a1130e78626de34bfc3d722a968e5c", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 9.0, "max_stars_repo_stars_event_min_datetime": "2020-04-26T02:40:48.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-13T10:22:00.000Z", "max_issues_repo_path": "ba/cpp/util.hpp", "max_issues_repo_name": "daoran/ba", "max_issues_repo_head_hexsha": "d38e58a1f9a1130e78626de34bfc3d722a968e5c", "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": "ba/cpp/util.hpp", "max_forks_repo_name": "daoran/ba", "max_forks_repo_head_hexsha": "d38e58a1f9a1130e78626de34bfc3d722a968e5c", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-11-27T07:12:36.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-09T04:22:32.000Z", "avg_line_length": 25.6509715994, "max_line_length": 80, "alphanum_fraction": 0.6026922292, "num_tokens": 8566, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.5583269943353745, "lm_q1q2_score": 0.3052586690860466}}
{"text": "#include \"expr.hpp\"\n\n#include \"version.hpp\"\n#include \"env.hpp\"\n\n#include <string_view>\n#include <iostream>\n#include <cmath>\n#include <numeric>\n#ifdef ENABLE_NIVALIS_BOOST_MATH\n#include <boost/math/special_functions/beta.hpp>\n#include <boost/math/special_functions/gamma.hpp>\n#include <boost/math/special_functions/digamma.hpp>\n#include <boost/math/special_functions/trigamma.hpp>\n#include <boost/math/special_functions/polygamma.hpp>\n#include <boost/math/special_functions/zeta.hpp>\n#include <boost/math/special_functions/binomial.hpp>\n#include <boost/math/special_functions/factorials.hpp>\n#endif\n#include \"opcodes.hpp\"\n#include \"util.hpp\"\n\nnamespace nivalis {\n\nnamespace {\nconst double NONE = std::numeric_limits<double>::quiet_NaN();\nusing ::nivalis::OpCode::repr;\n#ifndef ENABLE_NIVALIS_BOOST_MATH\nvoid print_boost_warning(uint32_t opcode) {\n    std::cerr << \"Function \" << OpCode::repr(opcode)\n        << \" requires Nivalis to be compiled with Boost\" << std::endl;\n}\n\n// Falling factorial\ndouble fa_fact (size_t x, size_t to_exc = 1) {\n    if (x >= to_exc + 175) // too expensive\n        return std::numeric_limits<double>::quiet_NaN();\n    double result = 1.;\n    while (x > to_exc) result *= x--;\n    return result;\n}\n#endif\n}  // namespace\n\nnamespace detail {\ndouble eval_ast(Environment& env, const Expr::AST& ast,\n        const std::vector<double>& arg_vals) {\n    // Main AST evaluation stack\n    thread_local std::vector<double> stk;\n    // Stack of thunks available:\n    // contains positions of thunk_jmp encountered\n    thread_local std::vector<size_t> thunks;\n    // Thunk call stack: contains positions to return to\n    // after reaching thunk_ret\n    thread_local std::vector<size_t> thunks_stk;\n\n    // Max function call stack height\n    static const size_t MAX_CALL_STK_HEIGHT = 256;\n    // Curr function call stack height\n    thread_local size_t call_stk_height = 0;\n\n    thread_local size_t top = -1;\n    size_t init_top = top;\n\n    // Make sure there is enough space\n    stk.resize(top + ast.size() + 1);\n\n#ifdef ENABLE_NIVALIS_BOOST_MATH\n    using namespace boost;\n    using namespace boost::math;\n#endif\n    using namespace nivalis::OpCode;\n\n    bool _is_thunk_ret = false;\n\n    // Shorthands for first, 2nd, 3rd arguments to operator\n#define ARG3 stk[top-2]\n#define ARG2 stk[top-1]\n#define ARG1 stk[top]\n// Return value from thunk or func call\n#define RET_VAL stk[top+1]\n// Quit without messing up stack\n#define FAIL_AND_QUIT do {top = init_top; return NONE; } while(0)\n\n    for (size_t cidx = ast.size() - 1; ~cidx; --cidx) {\n        const auto& node = ast[cidx];\n        switch(node.opcode) {\n            case null: stk[++top] = NONE; break;\n            case val:\n                stk[++top] = node.val;  break;\n            case ref:\n                stk[++top] = env.vars[node.ref]; break;\n            case arg:\n                stk[++top] = arg_vals[node.ref]; break;\n            case thunk_jmp:\n                thunks.push_back(cidx);\n                cidx -= ast[cidx].ref;\n                break;\n            case thunk_ret:\n                cidx = thunks_stk.back() + 1;\n                thunks_stk.pop_back();\n                _is_thunk_ret = true;\n                break;\n            case call:\n                {\n                    size_t n_args = node.call_info[1];\n                    auto& func = env.funcs[node.call_info[0]];\n                    std::vector<double> f_args(n_args);\n                    for (size_t i = 0; i < n_args; ++i) {\n                        f_args[i] = stk[top--];\n                    }\n                    if (n_args != func.n_args ||               // Should not happen\n                        &func.expr.ast[0] == &ast[0] ||        // Disallow recursion\n                        call_stk_height > MAX_CALL_STK_HEIGHT) // Too many nested calls\n                            FAIL_AND_QUIT;\n                    ++call_stk_height;\n                    eval_ast(env, func.expr.ast, f_args);\n                    --call_stk_height;\n                    ++top;\n                }\n                break;\n            case bnz:\n                if (_is_thunk_ret) {\n                    --top; _is_thunk_ret = false;\n                    ARG1 = RET_VAL;\n                } else {\n                    thunks_stk.push_back(cidx);\n                    cidx = thunks[thunks.size() - (ARG1 == 0.) - 1];\n                    thunks.resize(thunks.size() - 2);\n                }\n                break;\n\n            case sums: case prods:\n                {\n                    if (_is_thunk_ret) {\n                        --top; _is_thunk_ret = false;\n                        // update arg3 (the output)\n                        if (node.opcode == prods)\n                            ARG3 *= RET_VAL;\n                        else\n                            ARG3 += RET_VAL; // arg3 is output\n                    } else {\n                        // Move over the arguments and use arg3\n                        // as output\n                        ++top; ARG1 = ARG2; ARG2 = ARG3;\n                        ARG3 = node.opcode == prods ? 1. : 0.;\n                    }\n                    uint64_t var_id = node.ref;\n                    int64_t a = static_cast<int64_t>(ARG1),\n                            b = static_cast<int64_t>(ARG2);\n                    int64_t step = (a <= b) ? 1 : -1;\n                    if (std::isnan(ARG1)) {\n                        top -= 2; thunks.pop_back();\n                    } else {\n                        env.vars[var_id] = static_cast<double>(a);\n                        a += step;\n                        if (a == b + step) ARG1 = NONE;\n                        else ARG1 = static_cast<double>(a);\n                        thunks_stk.push_back(cidx);\n                        cidx = thunks.back();\n                    }\n                }\n                break;\n\n            case bsel: --top; break;\n            case add: ARG2 += ARG1; --top; break;\n            case sub: ARG2 = ARG1 - ARG2; --top; break;\n            case mul: ARG2 *= ARG1;  --top; break;\n            case divi: ARG2 = ARG1 / ARG2; --top; break;\n            case mod: ARG2 = std::fmod(ARG1, ARG2); --top; break;\n            case power: ARG2 = std::pow(ARG1, ARG2); --top; break;\n            case logbase: ARG2 = log(ARG1) / log(ARG2); --top; break;\n            case max: ARG2 = std::max(ARG1, ARG2); --top; break;\n            case min: ARG2 = std::min(ARG1, ARG2); --top; break;\n            case land: ARG2 = static_cast<double>(ARG1 && ARG2); --top; break;\n            case lor: ARG2 = static_cast<double>(ARG1 || ARG2); --top; break;\n            case lxor: ARG2 = static_cast<double>(\n                               (ARG1 != 0.) ^ (ARG2 != 0.)); --top; break;\n            case gcd: ARG2 = static_cast<double>(\n                              std::gcd((int64_t) ARG1,\n                                       (int64_t) ARG2)); --top; break;\n            case lcm: ARG2 = ARG1 * ARG2 /\n                      static_cast<double>(std::gcd(\n                          (int64_t) ARG1, (int64_t) ARG2)); --top; break;\n#ifdef ENABLE_NIVALIS_BOOST_MATH\n            case choose: ARG2 = binomial_coefficient<double>(\n                            (uint32_t)ARG1, (uint32_t)ARG2); --top; break;\n            case fafact: ARG2 = falling_factorial<double>(\n                            (uint32_t)ARG1, (uint32_t)ARG2); --top; break;\n            case rifact: ARG2 = rising_factorial<double>(\n                            (uint32_t)ARG1, (uint32_t)ARG2); --top; break;\n            case betab: ARG2 = beta<double>(ARG1, ARG2); --top; break;\n            case polygammab:\n                        ARG2 = polygamma<double>((int)ARG1, ARG2); --top;\n                        break;\n#else\n            case choose: {\n                             double ad = std::round(ARG1);\n                             double bd = std::round(ARG2);\n                             if (ad < 0 || bd < 0) {\n                                 ARG2 = std::numeric_limits<double>::quiet_NaN(); --top; break;\n                             }\n                             size_t a = static_cast<size_t>(ad), b = static_cast<size_t>(bd);\n                             b = std::min(b, a-b);\n                             ARG2 = fa_fact(a, a-b) / fa_fact(b);\n                             --top; break;\n                         }\n            case fafact: {\n                             double ad = std::round(ARG1);\n                             double bd = std::round(ARG2);\n                             if (ad < 0 || bd < 0) {\n                                 ARG2 = std::numeric_limits<double>::quiet_NaN(); --top; break;\n                             }\n                             size_t a = static_cast<size_t>(ad), b = static_cast<size_t>(bd);\n                             ARG2 = fa_fact(a, a-b);\n                             --top; break;\n                         }\n            case rifact: {\n                             double ad = std::round(ARG1);\n                             double bd = std::round(ARG2);\n                             if (ad < 0 || bd < 0) {\n                                 ARG2 = std::numeric_limits<double>::quiet_NaN(); --top; break;\n                             }\n                             size_t a = static_cast<size_t>(ad), b = static_cast<size_t>(bd);\n                             ARG2 = fa_fact(a+b-1, a-1);\n                             --top; break;\n                         }\n            case betab: case polygammab:\n                ARG1 = NONE; print_boost_warning(node.opcode); break;\n#endif\n            case lt: ARG2 = static_cast<double>(ARG1 < ARG2); --top; break;\n            case le: ARG2 = static_cast<double>(ARG1 <= ARG2); --top; break;\n            case eq: ARG2 = static_cast<double>(ARG1 == ARG2); --top; break;\n            case ne: ARG2 = static_cast<double>(ARG1 != ARG2); --top; break;\n            case ge: ARG2 = static_cast<double>(ARG1 >= ARG2); --top; break;\n            case gt: ARG2 = static_cast<double>(ARG1 > ARG2); --top; break;\n\n            case unaryminus: ARG1 = -ARG1; break;\n            case lnot: ARG1 = static_cast<double>(!(ARG1)); break;\n            case absb: ARG1 = std::fabs(ARG1); break;\n            case sqrtb: ARG1 = std::sqrt(ARG1); break;\n            case sqrb: ARG1 *= ARG1; break;\n            case sgn: ARG1 = ARG1 > 0 ? 1 : (ARG1 == 0 ? 0 : -1); break;\n            case floorb: ARG1 = floor(ARG1); break;\n            case ceilb: ARG1 = ceil(ARG1); break; case roundb: ARG1 = round(ARG1); break;\n\n            case expb:   ARG1 = exp(ARG1); break; case exp2b: ARG1 = exp2(ARG1); break;\n            case logb:   ARG1 = log(ARG1); break;\n            case factb:\n                        {\n                            unsigned n = static_cast<unsigned>(std::max(\n                                        ARG1, 0.));\n#ifdef ENABLE_NIVALIS_BOOST_MATH\n                            ARG1 = factorial<double>(n);\n#else\n                            ARG1 = fa_fact(n, 1);\n#endif\n                        }\n                        break;\n            case log2b: ARG1 = log2(ARG1); break;  case log10b: ARG1 = log10(ARG1); break;\n            case sinb: ARG1 = sin(ARG1); break;   case cosb:   ARG1 = cos(ARG1); break;\n            case tanb: ARG1 = tan(ARG1); break;   case asinb: ARG1 = asin(ARG1); break;\n            case acosb: ARG1 = acos(ARG1); break;  case atanb: ARG1 = atan(ARG1); break;\n            case sinhb: ARG1 = sinh(ARG1); break;  case coshb: ARG1 = cosh(ARG1); break;\n            case tanhb: ARG1 = tanh(ARG1); break;\n            case tgammab: ARG1 = std::tgamma(ARG1); break;\n            case lgammab: ARG1 = std::lgamma(ARG1); break;\n#ifdef ENABLE_NIVALIS_BOOST_MATH\n            case digammab: ARG1 = digamma<double>(ARG1); break;\n            case trigammab: ARG1 = trigamma<double>(ARG1); break;\n            case zetab: ARG1 = zeta<double>(ARG1); break;\n#else\n           // The following functions are unavailable without Boost\n            case digammab: case trigammab: case zetab:\n                ARG1 = NONE; print_boost_warning(node.opcode); break;\n#endif\n            case erfb: ARG1 = erf(ARG1); break; break;\n        }\n    }\n    return stk[top--];\n}\n}  // namespace detail\n\n// Interface for evaluating expression\ndouble Expr::operator()(Environment& env) const {\n    return detail::eval_ast(env, ast);\n}\ndouble Expr::operator()(double arg, Environment& env) const {\n    return detail::eval_ast(env, ast, {arg});\n}\ndouble Expr::operator()(const std::vector<double>& args,\n        Environment& env) const {\n\n    return detail::eval_ast(env, ast, args);\n}\n\n}  // namespace nivalis\n", "meta": {"hexsha": "7a9e8453742ae4fdfd0db02f25d8637308be8e08", "size": 12522, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/eval_expr.cpp", "max_stars_repo_name": "sxyu/nivalis", "max_stars_repo_head_hexsha": "3b05e3105ef640f6d24670d2ecff23ec6ab1d2d9", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 11.0, "max_stars_repo_stars_event_min_datetime": "2020-05-17T04:13:52.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-07T06:38:48.000Z", "max_issues_repo_path": "src/eval_expr.cpp", "max_issues_repo_name": "sxyu/nivalis", "max_issues_repo_head_hexsha": "3b05e3105ef640f6d24670d2ecff23ec6ab1d2d9", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/eval_expr.cpp", "max_forks_repo_name": "sxyu/nivalis", "max_forks_repo_head_hexsha": "3b05e3105ef640f6d24670d2ecff23ec6ab1d2d9", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-03-17T09:57:36.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-20T02:25:51.000Z", "avg_line_length": 42.0201342282, "max_line_length": 95, "alphanum_fraction": 0.4928126497, "num_tokens": 3023, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6791787121629466, "lm_q2_score": 0.4493926344647597, "lm_q1q2_score": 0.3052179107312893}}
{"text": "/*\n * Copyright 2020 California  Institute  of Technology (“Caltech”)\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 <x/vio/slam_update.h>\n#include <x/vio/tools.h>\n#include <x/ekf/state.h>\n#include <boost/math/distributions.hpp>\n\nusing namespace x;\nusing namespace Eigen;\n\nSlamUpdate::SlamUpdate(const x::TrackList& trks,\n                       const x::AttitudeList& quats,\n                       const x::TranslationList& poss,\n                       const MatrixXd& feature_states,\n                       const std::vector<int>& anchor_idxs,\n                       const MatrixXd& cov_s,\n                       const int n_poses_max,\n                       const double sigma_img)\n{\n  // Number of features\n  const size_t n_trks = trks.size();\n\n  // Initialize Kalman update matrices\n  const size_t rows = 2 * n_trks;\n  const size_t cols = cov_s.cols();\n  jac_ = MatrixXd::Zero(rows, cols);\n  cov_m_diag_ = VectorXd::Ones(rows);\n  res_ = MatrixXd::Zero(rows, 1);\n  \n  // For each track, compute residual, Jacobian and covariance block\n  const double var_img = sigma_img * sigma_img;\n  for (size_t i = 0, row_h = 0; i < n_trks; ++i) {\n    processOneTrack(trks[i],\n                    quats,\n                    poss,\n                    feature_states,\n                    anchor_idxs,\n                    cov_s,\n                    n_poses_max,\n                    var_img,\n                    i,\n                    row_h);\n  }\n}\n\nvoid SlamUpdate::processOneTrack(const x::Track& track,\n                                 const x::AttitudeList& C_q_G,\n                                 const x::TranslationList& G_p_C,\n                                 const MatrixXd& feature_states,\n                                 const std::vector<int>& anchor_idxs,\n                                 const MatrixXd& P,\n                                 const int n_poses_max,\n                                 const double var_img,\n                                 const size_t& j,\n                                 size_t& row_h)\n{\n  const size_t cols = P.cols();\n  MatrixXd h_j(MatrixXd::Zero(2, cols));\n  MatrixXd Hf_j(MatrixXd::Zero(2, cols));\n  MatrixXd res_j(MatrixXd::Zero(2, 1));\n \n  //==========================================================================\n  // Feature information\n  //==========================================================================\n  // A-priori inverse-depth parameters in last observation frame\n  double alpha = feature_states(j * 3, 0);\n  double beta = feature_states(j * 3 + 1, 0);\n  double rho = feature_states(j * 3 + 2, 0);\n\n  // Anchor pose\n  unsigned int anchor_idx = anchor_idxs[j];\n  x::Quaternion Ca_q_G;\n  Ca_q_G.x() = C_q_G[anchor_idx].ax;\n  Ca_q_G.y() = C_q_G[anchor_idx].ay;\n  Ca_q_G.z() = C_q_G[anchor_idx].az;\n  Ca_q_G.w() = C_q_G[anchor_idx].aw;\n\n  Vector3d G_p_Ca(G_p_C[anchor_idx].tx, G_p_C[anchor_idx].ty, G_p_C[anchor_idx].tz);\n\n  // Coordinate of feature in global frame\n  Vector3d G_p_fj = 1 / (rho)*Ca_q_G.normalized().toRotationMatrix() * Vector3d(alpha, beta, 1) + G_p_Ca;\n\n  // FOR LAST FEATURE OBSERVATION\n  x::Translation G_p_Cn(G_p_C.back());\n  x::Attitude Cn_q_G(C_q_G.back());\n\n  x::Quatern attitude_to_quaternion;\n  Quaterniond Ci_q_G_ = attitude_to_quaternion(Cn_q_G);\n  Vector3d G_p_Ci_(G_p_Cn.tx, G_p_Cn.ty, G_p_Cn.tz);\n\n  // Feature position expressed in camera frame.\n  Vector3d Ci_p_fj;\n  Ci_p_fj << Ci_q_G_.normalized().toRotationMatrix().transpose() * (G_p_fj - G_p_Ci_);\n\n  // eq. 20(a)\n  Vector2d z;\n  const size_t track_size(track.size());\n  const unsigned int i = track_size - 1;\n  z(0) = track[i].getX();\n  z(1) = track[i].getY();\n\n  Vector2d z_hat(z);\n  assert(Ci_p_fj(2));\n  z_hat(0) = Ci_p_fj(0) / Ci_p_fj(2);\n  z_hat(1) = Ci_p_fj(1) / Ci_p_fj(2);\n\n  // eq. 20(b)\n  res_j(0, 0) = z(0) - z_hat(0);\n  res_j(1, 0) = z(1) - z_hat(1);\n\n  //============================\n  // Measurement Jacobian matrix\n  //============================\n\n  const unsigned int pos = C_q_G.size() - 1;\n  if (anchor_idx == pos)  // Handle special case\n  {\n    // Inverse-depth feature coordinates jacobian\n    MatrixXd mat(MatrixXd::Zero(2, 3));\n    mat(0, 0) = 1.0;\n    mat(1, 1) = 1.0;\n\n    // Update stacked Jacobian matrices associated to the current feature\n    unsigned int row = 0;\n    unsigned int col = (n_poses_max * 2 + j) * kJacCols;\n    h_j.block<kVisJacRows, kJacCols>(row, kSizeCoreErr + col) = mat;\n  }\n  else\n  {\n    // Set Jacobian of pose for i'th measurement of feature j (eq.22, 23)\n    VisJacBlock J_i(VisJacBlock::Zero());\n    // first row\n    J_i(0, 0) = 1.0 / Ci_p_fj(2);\n    J_i(0, 1) = 0.0;\n    J_i(0, 2) = -Ci_p_fj(0) / std::pow((double)Ci_p_fj(2), 2);\n    // second row\n    J_i(1, 0) = 0.0;\n    J_i(1, 1) = 1.0 / Ci_p_fj(2);\n    J_i(1, 2) = -Ci_p_fj(1) / std::pow((double)Ci_p_fj(2), 2);\n\n    // Attitude\n    Vector3d skew_vector = Ci_q_G_.normalized().toRotationMatrix().transpose() * (G_p_fj - G_p_Ci_);\n    VisJacBlock J_attitude = J_i * x::Skew(skew_vector(0), skew_vector(1), skew_vector(2)).matrix;\n\n    // Position\n    VisJacBlock J_position = -J_i * Ci_q_G_.normalized().toRotationMatrix().transpose();\n\n    // Anchor attitude\n    VisJacBlock J_anchor_att = -1 / rho * J_i * Ci_q_G_.normalized().toRotationMatrix().transpose() *\n                                    Ca_q_G.normalized().toRotationMatrix() * x::Skew(alpha, beta, 1).matrix;\n\n    // Anchor position\n    VisJacBlock J_anchor_pos = -J_position;\n\n    // Inverse-depth feature coordinates\n    MatrixXd mat(MatrixXd::Identity(3, 3));\n    mat(0, 2) = -alpha / rho;\n    mat(1, 2) = -beta / rho;\n    mat(2, 2) = -1 / rho;\n    VisJacBlock Hf_j1 = 1 / rho * J_i * Ci_q_G_.normalized().toRotationMatrix().transpose() *\n                             Ca_q_G.normalized().toRotationMatrix() * mat;\n\n    // Update stacked Jacobian matrices associated to the current feature\n    unsigned int row = 0;\n    const unsigned int pos = C_q_G.size() - 1;\n    unsigned int col = pos * kJacCols;\n    h_j.block<kVisJacRows, kJacCols>(row, kSizeCoreErr + col) = J_position;\n\n    col += n_poses_max * kJacCols;\n    h_j.block<kVisJacRows, kJacCols>(row, kSizeCoreErr + col) = J_attitude;\n\n    col = anchor_idx * kJacCols;\n    h_j.block<kVisJacRows, kJacCols>(row, kSizeCoreErr + col) = J_anchor_pos;\n\n    col += n_poses_max * kJacCols;\n    h_j.block<kVisJacRows, kJacCols>(row, kSizeCoreErr + col) = J_anchor_att;\n\n    col = (n_poses_max * 2 + j) * kJacCols;\n    h_j.block<kVisJacRows, kJacCols>(row, kSizeCoreErr + col) = Hf_j1;\n  }\n\n  //==========================================================================\n  // Outlier rejection\n  //==========================================================================\n  const VectorXd r_j_diag = var_img * VectorXd::Ones(2); \n  MatrixXd r_j = var_img * MatrixXd::Identity(2, 2);\n  MatrixXd S_inv = (h_j * P * h_j.transpose() + r_j).inverse();\n  MatrixXd gamma = res_j.transpose() * S_inv * res_j;\n  boost::math::chi_squared_distribution<> my_chisqr(2 * track_size);\n  double chi = quantile(my_chisqr, 0.9);  // 95-th percentile\n\n  if (gamma(0, 0) < chi)  // Inlier\n  {\n    jac_.block(row_h,          // startRow\n             0,               // startCol\n             2,               // numRows\n             cols) = h_j;  // numCols\n\n    // Residual vector (one feature)\n    res_.block(row_h, 0, 2, 1) = res_j;\n\n    // Measurement covariance matrix\n    cov_m_diag_.segment(row_h, 2) = r_j_diag;\n\n    row_h += 2;\n  }\n}\n\nvoid SlamUpdate::computeInverseDepthsNew(const x::TrackList& new_trks,\n                                         const double rho_0,\n                                         MatrixXd& ivds) const\n{\n  const size_t n_new_slam_std_trks = new_trks.size();\n  ivds = MatrixXd::Zero(n_new_slam_std_trks * 3, 1);\n\n  // For each standard SLAM feature to init\n  for (size_t j = 0; j < n_new_slam_std_trks; ++j) {\n    // Compute inverse-depth coordinates of new feature state\n    // (last observation in track)\n    computeOneInverseDepthNew(new_trks[j].back(), rho_0, j, ivds);\n  }\n}\n\nvoid SlamUpdate::computeOneInverseDepthNew(const x::Feature& feature,\n                                           const double rho_0,\n                                           const unsigned int& idx,\n                                           MatrixXd& ivds) const\n{\n  // Inverse-depth parameters anchored in last observation frame\n  const double alpha = feature.getX();\n  const double beta  = feature.getY();\n  // const double rho = 1.0 / G_p_Ci.back().tz; // height-based init:\n\n  ivds(3*idx)     = alpha;\n  ivds(3*idx + 1) = beta;\n  ivds(3*idx + 2) = rho_0;\n}\n", "meta": {"hexsha": "f356ea727d3624c15b9e56f6aeb585580eae2d24", "size": 9051, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/x/vio/slam_update.cpp", "max_stars_repo_name": "jpl-x/x_events", "max_stars_repo_head_hexsha": "e9d0b6e578f045eb7b57acadf75b77d8a323f51d", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 57.0, "max_stars_repo_stars_event_min_datetime": "2020-10-20T18:01:14.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T18:44:43.000Z", "max_issues_repo_path": "src/x/vio/slam_update.cpp", "max_issues_repo_name": "jpl-x/x_events", "max_issues_repo_head_hexsha": "e9d0b6e578f045eb7b57acadf75b77d8a323f51d", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2022-03-11T15:53:17.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-11T15:53:17.000Z", "max_forks_repo_path": "src/x/vio/slam_update.cpp", "max_forks_repo_name": "jpl-x/x_events", "max_forks_repo_head_hexsha": "e9d0b6e578f045eb7b57acadf75b77d8a323f51d", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 11.0, "max_forks_repo_forks_event_min_datetime": "2020-10-17T00:36:02.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T18:44:45.000Z", "avg_line_length": 35.9166666667, "max_line_length": 108, "alphanum_fraction": 0.5760689427, "num_tokens": 2567, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.679178699175393, "lm_q2_score": 0.44939263446475963, "lm_q1q2_score": 0.30521790489477835}}
{"text": "// Boost.Geometry\n\n// 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#ifndef BOOST_GEOMETRY_STRATEGIES_GEOGRAPHIC_PARAMETERS_HPP\n#define BOOST_GEOMETRY_STRATEGIES_GEOGRAPHIC_PARAMETERS_HPP\n\n#include <boost/geometry/formulas/andoyer_inverse.hpp>\n#include <boost/geometry/formulas/thomas_direct.hpp>\n#include <boost/geometry/formulas/thomas_inverse.hpp>\n#include <boost/geometry/formulas/vincenty_direct.hpp>\n#include <boost/geometry/formulas/vincenty_inverse.hpp>\n\n#include <boost/mpl/assert.hpp>\n#include <boost/mpl/integral_c.hpp>\n\n\nnamespace boost { namespace geometry { namespace strategy\n{\n\nstruct andoyer\n{\n    template\n    <\n        typename CT,\n        bool EnableCoordinates = true,\n        bool EnableReverseAzimuth = false,\n        bool EnableReducedLength = false,\n        bool EnableGeodesicScale = false\n    >\n    struct direct\n            : formula::thomas_direct\n              <\n                  CT, false,\n                  EnableCoordinates, EnableReverseAzimuth,\n                  EnableReducedLength, EnableGeodesicScale\n              >\n    {};\n\n    template\n    <\n        typename CT,\n        bool EnableDistance,\n        bool EnableAzimuth,\n        bool EnableReverseAzimuth = false,\n        bool EnableReducedLength = false,\n        bool EnableGeodesicScale = false\n    >\n    struct inverse\n        : formula::andoyer_inverse\n            <\n                CT, EnableDistance,\n                EnableAzimuth, EnableReverseAzimuth,\n                EnableReducedLength, EnableGeodesicScale\n            >\n    {};\n};\n\nstruct thomas\n{\n    template\n    <\n        typename CT,\n        bool EnableCoordinates = true,\n        bool EnableReverseAzimuth = false,\n        bool EnableReducedLength = false,\n        bool EnableGeodesicScale = false\n    >\n    struct direct\n            : formula::thomas_direct\n              <\n                  CT, true,\n                  EnableCoordinates, EnableReverseAzimuth,\n                  EnableReducedLength, EnableGeodesicScale\n              >\n    {};\n\n    template\n    <\n        typename CT,\n        bool EnableDistance,\n        bool EnableAzimuth,\n        bool EnableReverseAzimuth = false,\n        bool EnableReducedLength = false,\n        bool EnableGeodesicScale = false\n    >\n    struct inverse\n        : formula::thomas_inverse\n            <\n                CT, EnableDistance,\n                EnableAzimuth, EnableReverseAzimuth,\n                EnableReducedLength, EnableGeodesicScale\n            >\n    {};\n};\n\nstruct vincenty\n{\n    template\n    <\n        typename CT,\n        bool EnableCoordinates = true,\n        bool EnableReverseAzimuth = false,\n        bool EnableReducedLength = false,\n        bool EnableGeodesicScale = false\n    >\n    struct direct\n            : formula::vincenty_direct\n              <\n                  CT, EnableCoordinates, EnableReverseAzimuth,\n                  EnableReducedLength, EnableGeodesicScale\n              >\n    {};\n\n    template\n    <\n        typename CT,\n        bool EnableDistance,\n        bool EnableAzimuth,\n        bool EnableReverseAzimuth = false,\n        bool EnableReducedLength = false,\n        bool EnableGeodesicScale = false\n    >\n    struct inverse\n        : formula::vincenty_inverse\n            <\n                CT, EnableDistance,\n                EnableAzimuth, EnableReverseAzimuth,\n                EnableReducedLength, EnableGeodesicScale\n            >\n    {};\n};\n\n\ntemplate <typename FormulaPolicy>\nstruct default_order\n{\n    BOOST_MPL_ASSERT_MSG\n    (\n        false, NOT_IMPLEMENTED_FOR_THIS_TYPE\n        , (types<FormulaPolicy>)\n    );\n};\n\ntemplate<>\nstruct default_order<andoyer>\n    : boost::mpl::integral_c<unsigned int, 1>\n{};\n\ntemplate<>\nstruct default_order<thomas>\n    : boost::mpl::integral_c<unsigned int, 2>\n{};\n\ntemplate<>\nstruct default_order<vincenty>\n    : boost::mpl::integral_c<unsigned int, 4>\n{};\n\n}}} // namespace boost::geometry::strategy\n\n\n#endif // BOOST_GEOMETRY_STRATEGIES_GEOGRAPHIC_PARAMETERS_HPP\n", "meta": {"hexsha": "92ebe08f2a9a5fd69872c493c0361b1283b53adc", "size": 4215, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "3rdParty/boost/1.71.0/boost/geometry/strategies/geographic/parameters.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/strategies/geographic/parameters.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/strategies/geographic/parameters.hpp", "max_forks_repo_name": "rajeev02101987/arangodb", "max_forks_repo_head_hexsha": "817e6c04cb82777d266f3b444494140676da98e2", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1343.0, "max_forks_repo_forks_event_min_datetime": "2017-12-08T19:47:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-26T11:31:36.000Z", "avg_line_length": 24.9408284024, "max_line_length": 79, "alphanum_fraction": 0.6241992883, "num_tokens": 922, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.596433160611502, "lm_q2_score": 0.5117166047041654, "lm_q1q2_score": 0.3052047518810919}}
{"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_ASHAPE_INCLUDE\n#define MTL_ASHAPE_INCLUDE\n\n#include <vector>\n#include <boost/type_traits/is_same.hpp>\n#include <boost/mpl/if.hpp>\n\n#include <boost/numeric/mtl/mtl_fwd.hpp>\n#include <boost/numeric/mtl/utility/tag.hpp>\n#include <boost/numeric/mtl/utility/root.hpp>\n#include <boost/numeric/mtl/concept/collection.hpp>\n#include <boost/numeric/mtl/utility/static_assert.hpp>\n\n// Not elegant but necessary to treat ITL types right\n#include <boost/numeric/itl/itl_fwd.hpp>\n\n#ifdef MTL_WITH_INITLIST\n# include <initializer_list>\n#endif\n\nnamespace mtl { \n\n/// Namespace for algebraic shapes; used for sophisticated dispatching between operations\nnamespace ashape {\n\n// forward declaration\ntemplate <typename T> struct ashape_aux;\n\n/// Tag for arbitrary algebraic shape\nstruct universe {};\n\n// Types (tags)\n/// Scalar algebraic shape\nstruct scal : universe {};\n\n/// Non-scalar algebraic shape\nstruct nonscal : universe {};\n/// Row vector as algebraic shape\ntemplate <typename Value> struct rvec : nonscal {};\n/// Column vector as algebraic shape\ntemplate <typename Value> struct cvec : nonscal {};\n/// Matrix as algebraic shape\ntemplate <typename Value> struct mat : nonscal {};\n/// Undefined shape, e.g., for undefined results of operations\nstruct ndef {};\n/// Future shape, i.e. after appropriate evaluation it will have the shape \\p Value\ntemplate <typename Value> struct future : nonscal {};\n\n/// Meta-function for algebraic shape of T\n/** Unknown types are treated like scalars. ashape of collections are template\n    parameterized with ashape of their elements, e.g., ashape< matrix < vector < double > > >::type is\n    mat< rvec < scal > > >. \n    Implemented with ashape_aux after type is cleaned up with mtl::traits::root.\n**/\ntemplate <typename T>\nstruct ashape\n  : ashape_aux<typename mtl::traits::root<T>::type> {};\n\ntemplate <typename T>\nstruct ashape_aux\n{\n    typedef scal type;\n};\n\n/// Vectors must be distinguished between row and column vectors\ntemplate <typename Value, typename Parameters>\nstruct ashape_aux<mtl::vector::dense_vector<Value, Parameters> >\n{\n    typedef typename boost::mpl::if_<\n\tboost::is_same<typename Parameters::orientation, row_major>\n      , rvec<typename ashape<Value>::type>\n      , cvec<typename ashape<Value>::type>\n    >::type type;\n};\n\n/// Same as dense vector\ntemplate <typename Value, typename Parameters>\nstruct ashape_aux<vector::strided_vector_ref<Value, Parameters> >\n  : ashape<mtl::vector::dense_vector<Value, Parameters> > {};\n\n/// Same as dense vector\ntemplate <typename Value, typename Parameters>\nstruct ashape_aux<vector::sparse_vector<Value, Parameters> >\n  : ashape<mtl::vector::dense_vector<Value, Parameters> > {};\n\n/// One-dimensional arrays have rvec ashape; 2D arrays are matrices see below\ntemplate <typename Value, unsigned Rows>\nstruct ashape_aux<Value[Rows]>\n{\n    typedef rvec<typename ashape<Value>::type> type;\n};\n   \n#ifdef MTL_WITH_INITLIST\n/// Non-nested initializer_list have rvec ashape, nested lists are matrices see below\ntemplate <typename Value>\nstruct ashape_aux<std::initializer_list<Value> >\n{\n    typedef rvec<typename ashape<Value>::type> type;\n};\n#endif\n\n/// std::vectors have rvec ashape\ntemplate <typename Value, typename Allocator>\nstruct ashape_aux<std::vector<Value, Allocator> >\n{\n    typedef rvec<typename ashape<Value>::type> type;\n};\n   \n/// One-dimensional arrays have rvec ashape; 2D arrays are matrices see below\ntemplate <typename Value>\nstruct ashape_aux<Value*>\n{\n    typedef rvec<typename ashape<Value>::type> type;\n};\n   \ntemplate <typename E1, typename E2, typename SFunctor>\nstruct ashape_aux< vector::vec_vec_pmop_expr<E1, E2, SFunctor> >\n{\n    MTL_STATIC_ASSERT((boost::is_same<typename ashape<E1>::type, \n\t\t\t                typename ashape<E2>::type>::value), \"Operands must have same algebraic shape.\");\n    typedef typename ashape<E1>::type type;\n};\n\ntemplate <typename E1, typename E2, typename SFunctor>\nstruct ashape_aux< vector::vec_vec_op_expr<E1, E2, SFunctor> >\n{\n#if 0 // not sure if this is true in all operations\n    MTL_STATIC_ASSERT((boost::is_same<typename ashape<E1>::type, \n\t\t\t\t      typename ashape<E2>::type>::value), \"Operands must have same algebraic shape.\");\n#endif\n    typedef typename ashape<E1>::type type;\n};\n\ntemplate <typename E1, typename E2, typename SFunctor>\nstruct ashape_aux< vector::vec_vec_aop_expr<E1, E2, SFunctor> >\n{\n    typedef typename ashape<E1>::type type;\n};\n\ntemplate <typename E1, typename E2, typename SFunctor>\nstruct ashape_aux< vector::vec_scal_aop_expr<E1, E2, SFunctor> >\n{\n    typedef typename ashape<E1>::type type;\n};\n\ntemplate <typename Vector>\nstruct ashape_aux< vector::vec_const_ref_expr<Vector> >\n{\n    typedef typename ashape<Vector>::type type;\n};\n\n\n// ========\n// Matrices\n// ========\n\ntemplate <typename Value, typename Parameters>\nstruct ashape_aux<mtl::matrix::compressed2D<Value, Parameters> >\n{\n    typedef mat<typename ashape<Value>::type> type;\n};\n\ntemplate <typename Value, typename Parameters>\nstruct ashape_aux<mtl::matrix::coordinate2D<Value, Parameters> >\n{\n    typedef mat<typename ashape<Value>::type> type;\n};\n\ntemplate <typename Value, typename Parameters>\nstruct ashape_aux<mtl::matrix::sparse_banded<Value, Parameters> >\n{\n    typedef mat<typename ashape<Value>::type> type;\n};\n\ntemplate <typename Value, typename Parameters>\nstruct ashape_aux<mtl::matrix::dense2D<Value, Parameters> >\n{\n    typedef mat<typename ashape<Value>::type> type;\n};\n   \ntemplate <typename Value, std::size_t Mask, typename Parameters>\nstruct ashape_aux<mtl::matrix::morton_dense<Value, Mask, Parameters> >\n{\n    typedef mat<typename ashape<Value>::type> type;\n};\n\ntemplate <typename Functor>\nstruct ashape_aux<mtl::matrix::implicit_dense<Functor> >\n{\n    typedef mat<typename ashape<typename Functor::result_type>::type> type;\n};\n\n/// Two-dimensional arrays have mat ashape; 1D arrays are vectors see above\ntemplate <typename Value, unsigned Rows, unsigned Cols>\nstruct ashape_aux<Value[Rows][Cols]>\n{\n    typedef mat<typename ashape<Value>::type> type;\n};\n\n/// Two-dimensional arrays have mat ashape; 1D arrays are vectors see above\ntemplate <typename Value, unsigned Cols>\nstruct ashape_aux<Value (*)[Cols]>\n{\n    typedef mat<typename ashape<Value>::type> type;\n};\n\n#ifdef MTL_WITH_INITLIST\n/// Nested initializer_list are matrices, non-nested are vectors see above\ntemplate <typename Value>\nstruct ashape_aux<std::initializer_list<std::initializer_list<Value> > >\n{\n    typedef mat<typename ashape<Value>::type> type;\n};\n#endif\n\ntemplate <typename Vector>\nstruct ashape_aux<mtl::matrix::multi_vector<Vector> >\n{\n    typedef mat<typename ashape<typename mtl::Collection<mtl::matrix::multi_vector<Vector> >::value_type>::type> type;\n};\n  \ntemplate <typename Value>\nstruct ashape_aux<matrix::element_structure<Value> >\n{\n   typedef mat<typename ashape<Value>::type> type;\n};\n\ntemplate <typename Value, typename Parameters>\nstruct ashape_aux<mtl::matrix::ell_matrix<Value, Parameters> >\n{\n   typedef mat<typename ashape<Value>::type> type;\n};\n\n \ntemplate <typename Vector>\nstruct ashape_aux<matrix::multi_vector_range<Vector> >\n{\n    typedef mat<typename ashape<typename mtl::Collection<matrix::multi_vector_range<Vector> >::value_type>::type> type;\n};\n\ntemplate <typename E1, typename E2, typename SFunctor>\nstruct ashape_aux< matrix::mat_mat_op_expr<E1, E2, SFunctor> >\n{\n    MTL_STATIC_ASSERT((boost::is_same<typename ashape<E1>::type, \n\t\t\t\t      typename ashape<E2>::type>::value), \"Operands must have same algebraic shape.\");\n    typedef typename ashape<E1>::type type;\n};\n\ntemplate <typename Vector1, typename Vector2>\nstruct ashape< matrix::outer_product_matrix<Vector1, Vector2> >\n{\n    // BOOST_STATIC_ASSERT((boost::is_same<typename ashape<E1>::type, \n    // \t\t\t                typename transposed_shape<typename ashape<E2>::type>::type>::value));    \n    typedef mat<typename ashape<typename mtl::Collection<Vector1>::value_type>::type> type;\n};\n\ntemplate <typename Matrix, typename VectorIn> \nstruct ashape< vector::mat_cvec_multiplier<Matrix, VectorIn> >\n{\n    typedef cvec<scal> type;\n};\n\n// =====\n// Views\n// =====\n\ntemplate <typename Functor, typename Coll>\nstruct ashape_aux<matrix::map_view<Functor, Coll> >\n{\n    typedef typename ashape<Coll>::type type;\n};\n\ntemplate <typename Functor, typename Coll>\nstruct ashape_aux<vector::map_view<Functor, Coll> >\n{\n    typedef typename ashape<Coll>::type type;\n};\n\ntemplate <typename Coll>\nstruct ashape_aux<vector::conj_view<Coll> >\n{\n    typedef typename ashape<Coll>::type type;\n};\n\ntemplate <typename Coll>\nstruct ashape_aux<vector::real_view<Coll> >\n{\n    typedef typename ashape<Coll>::type type;\n};\n\ntemplate <typename Coll>\nstruct ashape_aux<vector::imag_view<Coll> >\n{\n    typedef typename ashape<Coll>::type type;\n};\n\n#if 1\n// shouldn't be needed \ntemplate <typename Coll>\nstruct ashape_aux<mtl::matrix::transposed_view<const matrix::conj_view<Coll> > >\n{\n    typedef typename ashape<Coll>::type type;\n};\n#endif\n\ntemplate <typename Matrix>\nstruct ashape_aux<matrix::transposed_view<Matrix> >\n{\n    typedef typename ashape<Matrix>::type type;\n};\n\ntemplate <typename Matrix>\nstruct ashape_aux<matrix::banded_view<Matrix> >\n{\n    typedef typename ashape<Matrix>::type type;\n};\n\ntemplate <typename Matrix>\nstruct ashape_aux<matrix::indirect<Matrix> >\n{\n    typedef typename ashape<Matrix>::type type;\n};\n\n// Rule out other types as algebraic shape\ntemplate <typename IFStream, typename OFStream>\nstruct ashape_aux<io::matrix_file<IFStream, OFStream> > \n{\n    typedef ndef type;\n};\n\n\n// =====================\n// Shapes of products:\n// =====================\n\n// a) The result's shape\n// b) Classify operation in terms of shape\n\n// Operation types:\n\nstruct scal_scal_mult {};\nstruct cvec_rvec_mult {}; // outer product\nstruct rvec_cvec_mult {}; // inner product (without conj)\nstruct rvec_mat_mult {};\nstruct mat_cvec_mult {};\nstruct mat_mat_mult {};\nstruct scal_rvec_mult {};\nstruct scal_cvec_mult {};\nstruct scal_mat_mult {};\nstruct rvec_scal_mult {};\nstruct cvec_scal_mult {};\nstruct mat_scal_mult {};\n\n\n\n// =====================\n// Results of operations\n// =====================\n\n/* \n      s  cv  rv   m\n-------------------\n s |  s  cv* rv*  m*\ncv | cv*  x   m   x\nrv | rv*  s   x  rv\n m |  m* cv   x   m \n\n * only on outer level, forbidden for elements of collections\n\n*/\n\n// Results for elements of collections, i.e. scalar * matrix (vector) are excluded\n\n\n/// Algebraic shape of multiplication's result when elements of collections are multiplied.\n/** The types are the same as for multiplications of entire collections except that scalar *\n    matrix (or vector) is excluded to avoid ambiguities. \n    emult_shape <Shape1, Shape2> is only properly defined if emult_op <Shape1, Shape2>::type is not ndef!\n**/\ntemplate <typename Shape1, typename Shape2>\nstruct emult_shape\n{\n    typedef ndef type;\n};\n\n/// Type of operation when values of Shape1 and Shape2 are multiplied (so far only for elements of collections)\n/** The types are the same as for multiplications of entire collections except that scalar *\n    matrix (or vector) is excluded to avoid ambiguities. **/\ntemplate <typename Shape1, typename Shape2>\nstruct emult_op\n{\n    typedef ndef type;\n};\n\n\n// Scalar * scalar -> scalar\ntemplate <>\nstruct emult_shape<scal, scal>\n{\n    typedef scal type;\n};\n\ntemplate <>\nstruct emult_op<scal, scal>\n{\n    typedef scal_scal_mult type;\n};\n\n// Column times row vector, i.e. outer product\ntemplate <typename Value1, typename Value2>\nstruct emult_shape<cvec<Value1>, rvec<Value2> >\n{\n    typedef mat<typename emult_shape<Value1, Value2>::type> type;\n};\n\ntemplate <typename Value1, typename Value2>\nstruct emult_op<cvec<Value1>, rvec<Value2> >\n{\n    // if product of elements is undefined then product is undefined too\n    typedef typename boost::mpl::if_<\n\tboost::is_same<typename emult_op<Value1, Value2>::type, ndef>\n      , ndef\n      , cvec_rvec_mult\n    >::type type;\n};\n\n\n// Row times column vector, i.e. inner product (without conj)\ntemplate <typename Value1, typename Value2>\nstruct emult_shape<rvec<Value1>, cvec<Value2> >\n{\n    typedef typename emult_shape<Value1, Value2>::type type;\n};\n\ntemplate <typename Value1, typename Value2>\nstruct emult_op<rvec<Value1>, cvec<Value2> >\n{\n    // if product of elements is undefined then product is undefined too\n    typedef typename boost::mpl::if_<\n\tboost::is_same<typename emult_op<Value1, Value2>::type, ndef>\n      , ndef\n      , rvec_cvec_mult\n    >::type type;\n};\n\n// Row vector times matrix\ntemplate <typename Value1, typename Value2>\nstruct emult_shape<rvec<Value1>, mat<Value2> >\n{\n    typedef rvec<typename emult_shape<Value1, Value2>::type> type;\n};\n\n\ntemplate <typename Value1, typename Value2>\nstruct emult_op<rvec<Value1>, mat<Value2> >\n{\n    // if product of elements is undefined then product is undefined too\n    typedef typename boost::mpl::if_<\n\tboost::is_same<typename emult_op<Value1, Value2>::type, ndef>\n      , ndef\n      , rvec_mat_mult\n    >::type type;\n};\n\n// Matrix times column vector\ntemplate <typename Value1, typename Value2>\nstruct emult_shape<mat<Value1>, cvec<Value2> >\n{\n    typedef cvec<typename emult_shape<Value1, Value2>::type> type;\n};\n\ntemplate <typename Value1, typename Value2>\nstruct emult_op<mat<Value1>, cvec<Value2> >\n{\n    // if product of elements is undefined then product is undefined too\n    typedef typename boost::mpl::if_<\n\tboost::is_same<typename emult_op<Value1, Value2>::type, ndef>\n      , ndef\n      , mat_cvec_mult\n    >::type type;\n};\n\n\n// Matrix product\ntemplate <typename Value1, typename Value2>\nstruct emult_shape<mat<Value1>, mat<Value2> >\n{\n    typedef mat<typename emult_shape<Value1, Value2>::type> type;\n};\n\ntemplate <typename Value1, typename Value2>\nstruct emult_op<mat<Value1>, mat<Value2> >\n{\n    // if product of elements is undefined then product is undefined too\n    typedef typename boost::mpl::if_<\n\tboost::is_same<typename emult_op<Value1, Value2>::type, ndef>\n      , ndef\n      , mat_mat_mult\n    >::type type;\n};\n\n\n// Results for entire collections, i.e. scalar * matrix (vector) are allowed\n\n// Multiplying collections as emult\n\ntemplate  <typename Shape1, typename Shape2>\nstruct mult_shape\n    : public emult_shape<Shape1, Shape2>\n{};\n\ntemplate  <typename Shape1, typename Shape2>\nstruct mult_op\n    : public emult_op<Shape1, Shape2>\n{};\n\n// Scale collection from left\n\ntemplate <typename Shape2>\nstruct mult_shape<scal, Shape2>\n{\n    typedef Shape2 type;\n};\n\ntemplate <typename Value2>\nstruct mult_op<scal, rvec<Value2> >\n{\n    typedef scal_rvec_mult type;\n};\n\ntemplate <typename Value2>\nstruct mult_op<scal, cvec<Value2> >\n{\n    typedef scal_cvec_mult type;\n};\n\ntemplate <typename Value2>\nstruct mult_op<scal, mat<Value2> >\n{\n    typedef scal_mat_mult type;\n};\n\n// Scale collection from right\n\ntemplate <typename Shape1>\nstruct mult_shape<Shape1, scal>\n{\n    typedef Shape1 type;\n};\n\ntemplate <typename Value1>\nstruct mult_op<rvec<Value1>, scal>\n{\n    typedef rvec_scal_mult type;\n};\n\ntemplate <typename Value1>\nstruct mult_op<cvec<Value1>, scal>\n{\n    typedef cvec_scal_mult type;\n};\n\ntemplate <typename Value1>\nstruct mult_op<mat<Value1>, scal>\n{\n    typedef mat_scal_mult type;\n};\n\n// Arbitration\ntemplate <>\nstruct mult_shape<scal, scal>\n{\n    typedef scal type;\n};\n\n\n// Needs to be verified for nested matrix types, cf. #140\ntemplate <typename E1, typename E2>\nstruct ashape< matrix::mat_mat_times_expr<E1, E2> >\n{\n    // typedef typename ashape<E1>::type type;\n    typedef typename mult_shape<typename ashape<E1>::type, \n\t\t\t\ttypename ashape<E2>::type>::type type;\n};\n\n\ntemplate <typename E1, typename E2>\nstruct ashape< mat_cvec_times_expr<E1, E2> >\n{\n    // Resulting vector has the same shape as the multiplied\n    typedef typename ashape<E2>::type type;\n};\n\ntemplate <typename E1, typename E2>\nstruct ashape< vector::rvec_mat_times_expr<E1, E2> >\n{\n    // Resulting vector has the same shape as the multiplied\n    typedef typename ashape<E1>::type type;\n};\n\n\n// added by Hui Li (below) -----------------------------------------\n\n// =====================\n// Shapes of divisions:\n// =====================\n\n// Operation types:\n\nstruct scal_scal_div {};\nstruct cvec_scal_div {};\nstruct rvec_scal_div {};\nstruct mat_scal_div {};\n\ntemplate < typename Shape1, typename Shape2 >\nstruct div_shape\n{\n\ttypedef ndef type;\n};\n\ntemplate < typename Shape1, typename Shape2 >\nstruct div_op\n{\n\ttypedef ndef type;\n};\n\ntemplate <>\nstruct div_shape<scal,scal>\n{\n\ttypedef scal type;\n};\n\ntemplate<>\nstruct div_op<scal,scal>\n{\n\ttypedef scal type;\n};\n\ntemplate < typename Value1 >\nstruct div_shape < rvec<Value1>, scal >\n{\n\ttypedef typename boost::mpl::if_<\n\t\ttypename boost::is_same<typename div_shape<Value1,scal>::type,ndef>::type,\n\t\tndef,\n\t\trvec<typename div_shape<Value1,scal>::type>\n\t>::type type;\n};\n\ntemplate < typename Value1 >\nstruct div_op< rvec<Value1>, scal >\n{\n\ttypedef typename boost::mpl::if_<\n\t\ttypename boost::is_same<typename div_shape<rvec<Value1>,scal>::type,ndef>::type,\n\t\tndef,\n\t\trvec_scal_div\n\t>::type type;\n};\n\ntemplate < typename Value1 >\nstruct div_shape < cvec<Value1>, scal >\n{\n\ttypedef typename boost::mpl::if_<\n\t\ttypename boost::is_same<typename div_shape<Value1,scal>::type,ndef>::type,\n\t\tndef,\n\t\tcvec<typename div_shape<Value1,scal>::type>\n\t>::type type;\n};\n\ntemplate < typename Value1 >\nstruct div_op< cvec<Value1>, scal >\n{\n\ttypedef typename boost::mpl::if_<\n\t\ttypename boost::is_same<typename div_shape<cvec<Value1>,scal>::type,ndef>::type,\n\t\tndef,\n\t\tcvec_scal_div\n\t>::type type;\n};\n\ntemplate < typename Value1 >\nstruct div_shape < mat<Value1>, scal >\n{\n\ttypedef typename boost::mpl::if_<\n\t\ttypename boost::is_same<typename div_shape<Value1,scal>::type,ndef>::type,\n\t\tndef,\n\t\tmat<typename div_shape<Value1,scal>::type>\n\t>::type type;\n};\n\ntemplate < typename Value1 >\nstruct div_op < mat<Value1>, scal >\n{\n\ttypedef typename boost::mpl::if_<\n\t\ttypename boost::is_same<typename div_shape<mat<Value1>,scal>::type,ndef>::type,\n\t\tndef,\n\t\tmat_scal_div\n\t>::type type;\n};\n\t\n// added by Hui Li (above) -----------------------------------------\n\n// ==================== ITL types ==================================\n\ntemplate <typename PC, typename Vector, bool Adjoint>\nstruct ashape<itl::pc::solver<PC, Vector, Adjoint> >\n{\n    typedef future<cvec<scal> > type; // might be a problem with nested matrices and vectors\n};\n\n\n}} // namespace mtl::ashape\n\n#endif // MTL_ASHAPE_INCLUDE\n", "meta": {"hexsha": "e559fb30cf8aeda52faf0a9e7f01f98ad74b44af", "size": 18813, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "lib/mtl4/boost/numeric/mtl/utility/ashape.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/ashape.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/ashape.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": 25.9489655172, "max_line_length": 119, "alphanum_fraction": 0.71285813, "num_tokens": 4727, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.305204744539557}}
{"text": "#include <iostream>\r\n#include <stdexcept>\r\n\r\n#include <boost/lexical_cast.hpp>\r\n\r\n#include \"Tudat/Astrodynamics/BasicAstrodynamics/physicalConstants.h\"\r\n#include \"Tudat/Astrodynamics/BasicAstrodynamics/timeConversions.h\"\r\n#include \"Tudat/External/SpiceInterface/spiceInterface.h\"\r\n#include \"Tudat/External/SpiceInterface/spiceRotationalEphemeris.h\"\r\n\r\nnamespace tudat\r\n{\r\n\r\nnamespace ephemerides\r\n{\r\n\r\n\r\n//! Function to calculate the rotation quaternion from target frame to original frame.\r\nEigen::Quaterniond SpiceRotationalEphemeris::getRotationToBaseFrame(\r\n        const double secondsSinceEpoch, const double julianDayAtEpoch )\r\n{\r\n    // Set number of seconds since J2000.\r\n    double ephemerisTime = secondsSinceEpoch;\r\n    if ( julianDayAtEpoch != basic_astrodynamics::JULIAN_DAY_ON_J2000 )\r\n    {\r\n        ephemerisTime -= ( basic_astrodynamics::JULIAN_DAY_ON_J2000 - julianDayAtEpoch )\r\n                * physical_constants::JULIAN_DAY;\r\n    }\r\n\r\n    // Get rotational quaternion from spice wrapper function\r\n    return spice_interface::computeRotationQuaternionBetweenFrames(\r\n                targetFrameOrientation_, baseFrameOrientation_, ephemerisTime );\r\n}\r\n\r\n//! Function to calculate the derivative of the rotation matrix from target frame to original\r\n//! frame.\r\nEigen::Matrix3d SpiceRotationalEphemeris::getDerivativeOfRotationToBaseFrame(\r\n        const double secondsSinceEpoch, const double julianDayAtEpoch )\r\n{\r\n    // Set number of seconds since J2000.\r\n    double ephemerisTime = secondsSinceEpoch;\r\n    if ( julianDayAtEpoch != basic_astrodynamics::JULIAN_DAY_ON_J2000 )\r\n    {\r\n        ephemerisTime -= ( basic_astrodynamics::JULIAN_DAY_ON_J2000 - julianDayAtEpoch )\r\n                * physical_constants::JULIAN_DAY;\r\n    }\r\n\r\n    // Get rotation matrix derivative from spice wrapper function\r\n    return spice_interface::computeRotationMatrixDerivativeBetweenFrames(\r\n                targetFrameOrientation_, baseFrameOrientation_, ephemerisTime );\r\n}\r\n\r\n//! Function to calculate the full rotational state at given time\r\nvoid SpiceRotationalEphemeris::getFullRotationalQuantitiesToTargetFrame(\r\n        Eigen::Quaterniond& currentRotationToLocalFrame,\r\n        Eigen::Matrix3d& currentRotationToLocalFrameDerivative,\r\n        Eigen::Vector3d& currentAngularVelocityVectorInGlobalFrame,\r\n        const double secondsSinceEpoch, const double julianDayAtEpoch)\r\n{\r\n    // Set number of seconds since J2000.\r\n    double ephemerisTime = secondsSinceEpoch;\r\n    if ( julianDayAtEpoch != basic_astrodynamics::JULIAN_DAY_ON_J2000 )\r\n    {\r\n        ephemerisTime -= ( basic_astrodynamics::JULIAN_DAY_ON_J2000 - julianDayAtEpoch )\r\n                * physical_constants::JULIAN_DAY;\r\n    }\r\n\r\n    // Calculate rotation (and its time derivative) directly from spice.\r\n    std::pair< Eigen::Quaterniond, Eigen::Matrix3d > fullRotation =\r\n            spice_interface::computeRotationQuaternionAndRotationMatrixDerivativeBetweenFrames(\r\n                baseFrameOrientation_, targetFrameOrientation_, ephemerisTime );\r\n    currentRotationToLocalFrame = fullRotation.first;\r\n    currentRotationToLocalFrameDerivative = fullRotation.second;\r\n\r\n    // Calculate angular velocity vector.\r\n    currentAngularVelocityVectorInGlobalFrame = getRotationalVelocityVectorInBaseFrameFromMatrices(\r\n                Eigen::Matrix3d( currentRotationToLocalFrame ), currentRotationToLocalFrameDerivative.transpose( ) );\r\n}\r\n\r\n\r\n} // namespace ephemerides\r\n\r\n} // namespace tudat\r\n", "meta": {"hexsha": "5ee05354fed2f0e9cca7226fb924665c4682367d", "size": 3482, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Tudat/External/SpiceInterface/spiceRotationalEphemeris.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/spiceRotationalEphemeris.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/spiceRotationalEphemeris.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": 41.4523809524, "max_line_length": 118, "alphanum_fraction": 0.7455485353, "num_tokens": 793, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5964331462646254, "lm_q2_score": 0.5117166047041654, "lm_q1q2_score": 0.305204744539557}}
{"text": "/* Copyright (C) 2012,2013 IBM Corp.\n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n * See the GNU General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License along\n * with this program; if not, write to the Free Software Foundation, Inc.,\n * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n */\n\n#include <algorithm>   // defines count(...), min(...)\n\n#include \"PAlgebra.h\"\n#include \"hypercube.h\"\n#include \"timing.h\"\n\n#include <NTL/ZZXFactoring.h>\n#include <NTL/GF2EXFactoring.h>\n#include <NTL/lzz_pEXFactoring.h>\n\n// polynomials are sorted lexicographically, with the\n// constant term being the \"most significant\"\n\ntemplate<class RX> bool poly_comp(const RX& a, const RX& b) \n{\n  long na = deg(a) + 1;\n  long nb = deg(b) + 1;\n\n  long i = 0;\n  while (i < na && i < nb && coeff(a, i) == coeff(b, i)) i++;\n\n  if (i < na && i < nb)\n    return coeff(a, i) < coeff(b, i);\n  else \n    return na < nb;\n}\n\nnamespace NTL {\n\n// for some weird reason, these need to be in either the std or NTL \n// namespace; otherwise, the compiler won't find them...\n\nbool operator<(GF2 a, GF2 b) { return rep(a) < rep(b); }\nbool operator<(zz_p a, zz_p b) { return rep(a) < rep(b); }\n\nbool operator<(const GF2X& a, const GF2X& b) { return poly_comp(a, b); }\nbool operator<(const zz_pX& a, const zz_pX& b) { return poly_comp(a, b); }\n\nbool operator<(const GF2E& a, const GF2E& b) { return rep(a) < rep(b); }\nbool operator<(const zz_pE& a, const zz_pE& b) { return rep(a) < rep(b); }\n\nbool operator<(const GF2EX& a, const GF2EX& b) { return poly_comp(a, b); }\nbool operator<(const zz_pEX& a, const zz_pEX& b) { return poly_comp(a, b); }\n\n}\n\n\nbool PAlgebra::operator==(const PAlgebra& other) const\n{\n  if (m != other.m) return false;\n  if (p != other.p) return false;\n\n  return true;\n}\n\nbool PAlgebra::nextExpVector(vector<unsigned long>& buffer) const\n{\n  // increment the vector in lexicographic order\n  if (!isDryRun()) for (long i=gens.size()-1; i>=0; i--) {\n    if (i>=(long)buffer.size()) continue; // sanity check\n    // increment current index, set all the ones after it to zero\n    if (buffer[i] < OrderOf(i)-1) { \n      buffer[i]++;\n      for (unsigned long j=i+1; j<buffer.size(); j++) buffer[j] = 0;\n      return true;  // succeeded in incrementing the vector\n    }\n    // if buffer[i] >= OrderOf(i)-1, mover to previous index i\n  }\n  return false;     // cannot increment the vector anymore\n}\n\nlong PAlgebra::coordinate(long i, long k) const\n{\n  if (isDryRun()) return 0;\n  long t = ith_rep(k); // element of Zm^* representing the k'th slot\n\n  // dLog returns the representation of t along the generators, so the\n  // i'th entry there is the coordinate relative to i'th geneator\n  return dLog(t)[i];\n}\n\nlong PAlgebra::addCoord(long i, long k, long offset) const\n{\n  if (isDryRun()) return 0;\n  assert(k >= 0 && k < (long) nSlots);\n  assert(i >= 0 && i < (long) gens.size());\n  \n  offset = offset % ((long) OrderOf(i));\n  if (offset < 0) offset += OrderOf(i);\n  \n  long k_i = coordinate(i, k);\n  long k_i1 = (k_i + offset) % OrderOf(i);\n  \n  long k1 = k + (k_i1 - k_i) * prods[i+1];\n  \n  return k1;\n}\n\nunsigned long PAlgebra::exponentiate(const vector<unsigned long>& exps,\n\t\t\t\tbool onlySameOrd) const\n{\n  if (isDryRun()) return 1;\n  unsigned long t = 1;\n  unsigned long n = min(exps.size(),gens.size());\n  for (unsigned long i=0; i<n; i++) {\n    if (onlySameOrd && !SameOrd(i)) continue;\n    unsigned long g = PowerMod(gens[i] ,exps[i], m); \n    t = MulMod(t, g, m);\n  }\n  return t;\n}\n\nvoid PAlgebra::printout() const\n{\n  cout << \"m = \" << m << \", p = \" << p;\n  if (isDryRun()) { cout << \" (dry run)\\n\"; return; }\n  cout << \", phi(m) = \" << phiM << endl;\n  cout << \"  ord(p)=\" << ordP << endl;\n\n  unsigned long i;\n  for (i=0; i<gens.size(); i++) if (gens[i]) {\n      cout << \"  generator \" << gens[i] << \" has order (\"\n           << (SameOrd(i)? \"=\":\"!\") << \"= Z_m^*) of \" \n\t   << OrderOf(i) << endl;\n  }\n  if (qGrpOrd()<100) {\n    cout << \"  T = [\";\n    for (i=0; i<T.size(); i++) cout << T[i] << \" \";\n    cout << \"]\\n\";\n  }\n}\n\n\nPAlgebra::PAlgebra(unsigned long mm, unsigned long pp,  \n                   const vector<long>& _gens, const vector<long>& _ords )\n{\n  assert( ProbPrime(pp) );\n  assert( (mm % pp) != 0 );\n  assert( mm < NTL_SP_BOUND );\n  assert( mm > 1 );\n\n  cM  = 1.0; // default value for the ring constant\n  m = mm;\n  p = pp;\n\n  long k = NextPowerOfTwo(m);\n  if (mm == (1UL << k))\n    pow2 = k;\n  else\n    pow2 = 0;\n\n   \n\n  // For dry-run, use a tiny m value for the PAlgebra tables\n  if (isDryRun()) mm = (p==3)? 4 : 3;\n\n  // Compute the generators for (Z/mZ)^* (defined in NumbTh.cpp)\n\n  if (_gens.size() == 0 || isDryRun()) \n      ordP = findGenerators(this->gens, this->ords, mm, pp);\n  else {\n    assert(_gens.size() == _ords.size());\n    gens = _gens;\n    ords = _ords;\n    ordP = multOrd(pp, mm);\n  }\n  nSlots = qGrpOrd();\n  phiM = ordP * nSlots;\n\n  // Allocate space for the various arrays\n  T.resize(nSlots);\n  dLogT.resize(nSlots*gens.size());\n  Tidx.assign(mm,-1);    // allocate m slots, initialize them to -1\n  zmsIdx.assign(mm,-1);  // allocate m slots, initialize them to -1\n  long i, idx;\n  for (i=idx=0; i<(long)mm; i++) if (GCD(i,mm)==1) zmsIdx[i] = idx++;\n\n  // Now fill the Tidx and dLogT translation tables. We identify an element\n  // t\\in T with its representation t = \\prod_{i=0}^n gi^{ei} mod m (where\n  // the gi's are the generators in gens[]) , represent t by the vector of\n  // exponents *in reverse order* (en,...,e1,e0), and order these vectors\n  // in lexicographic order.\n\n  // FIXME: is the comment above about reverse order true? It doesn't \n  // seem like it to me.  VJS.\n\n  // buffer is initialized to all-zero, which represents 1=\\prod_i gi^0\n  vector<unsigned long> buffer(gens.size()); // temporaty holds exponents\n  i = idx = 0;\n  long ctr = 0;\n  do {\n    ctr++;\n    unsigned long t = exponentiate(buffer);\n    for (unsigned long j=0; j<buffer.size(); j++) dLogT[idx++] = buffer[j];\n\n    assert(GCD(t,mm) == 1); // sanity check for user-supplied gens\n    assert(Tidx[t] == -1);\n\n    T[i] = t;       // The i'th element in T it t\n    Tidx[t] = i++;  // the index of t in T is i\n\n    // increment buffer by one (in lexigoraphic order)\n  } while (nextExpVector(buffer)); // until we cover all the group\n\n  assert(ctr == long(nSlots)); // sanity check for user-supplied gens\n\n  PhimX = Cyclotomic(mm); // compute and store Phi_m(X)\n\n  // initialize prods array\n  long ndims = gens.size();\n  prods.resize(ndims+1);\n  prods[ndims] = 1;\n  for (long j = ndims-1; j >= 0; j--) {\n    prods[j] = OrderOf(j) * prods[j+1];\n  }\n  //  pp_factorize(mFactors,mm); // prime-power factorization from NumbTh.cpp\n}\n\n/***********************************************************************\n\n  PAlgebraMod stuff....\n\n************************************************************************/\n\nPAlgebraModBase *buildPAlgebraMod(const PAlgebra& zMStar, long r)\n{\n  unsigned long p = zMStar.getP();\n  assert(r > 0);\n\n  if (p == 2 && r == 1) \n    return new PAlgebraModDerived<PA_GF2>(zMStar, r);\n  else\n    return new  PAlgebraModDerived<PA_zz_p>(zMStar, r);\n}\n\n\ntemplate<class T> \nvoid PAlgebraLift(const ZZX& phimx, const T& lfactors, T& factors, T& crtc, long r);\n\n\n\n// Missing NTL functionality\n\nvoid EDF(vec_zz_pX& v, const zz_pX& f, long d)\n{\n   EDF(v, f, PowerXMod(zz_p::modulus(), f), d);\n}\n\nzz_pEX FrobeniusMap(const zz_pEXModulus& F)\n{\n  return PowerXMod(zz_pE::cardinality(), F);\n}\n\n\ntemplate<class type> \nPAlgebraModDerived<type>::PAlgebraModDerived(const PAlgebra& _zMStar, long _r) \n  : zMStar(_zMStar), r(_r)\n\n{\n  long p = zMStar.getP();\n  long m = zMStar.getM();\n\n  // For dry-run, use a tiny m value for the PAlgebra tables\n  if (isDryRun()) m = (p==3)? 4 : 3;\n\n  assert(r > 0);\n\n  ZZ BigPPowR = power_ZZ(p, r);\n  assert(BigPPowR.SinglePrecision());\n  pPowR = to_long(BigPPowR);\n\n  long nSlots = zMStar.getNSlots();\n\n  RBak bak; bak.save();\n  SetModulus(p);\n\n  // Compute the factors Ft of Phi_m(X) mod p, for all t \\in T\n\n  RX phimxmod;\n\n  conv(phimxmod, zMStar.getPhimX()); // Phi_m(X) mod p\n\n  vec_RX localFactors;\n\n  EDF(localFactors, phimxmod, zMStar.getOrdP()); // equal-degree factorization\n\n  \n\n  RX* first = &localFactors[0];\n  RX* last = first + localFactors.length();\n  RX* smallest = min_element(first, last);\n  swap(*first, *smallest);\n\n  // We make the lexicographically smallest factor have index 0.\n  // The remaining factors are ordered according to their representives.\n\n  RXModulus F1(localFactors[0]); \n  for (long i=1; i<nSlots; i++) {\n    unsigned long t =zMStar.ith_rep(i); // Ft is minimal polynomial of x^{1/t} mod F1\n    unsigned long tInv = InvMod(t, m);  // tInv = t^{-1} mod m\n    RX X2tInv = PowerXMod(tInv,F1);     // X2tInv = X^{1/t} mod F1\n    IrredPolyMod(localFactors[i], X2tInv, F1);\n  }\n  /* Debugging sanity-check #1: we should have Ft= GCD(F1(X^t),Phi_m(X))\n  for (i=1; i<nSlots; i++) {\n    unsigned long t = T[i];\n    RX X2t = PowerXMod(t,phimxmod);  // X2t = X^t mod Phi_m(X)\n    RX Ft = GCD(CompMod(F1,X2t,phimxmod),phimxmod);\n    if (Ft != localFactors[i]) {\n      cout << \"Ft != F1(X^t) mod Phi_m(X), t=\" << t << endl;\n      exit(0);\n    }\n  }*******************************************************************/\n\n  if (r == 1) {\n    build(PhimXMod, phimxmod);\n    factors = localFactors;\n    pPowRContext.save();\n\n    // Compute the CRT coefficients for the Ft's\n    crtCoeffs.SetLength(nSlots);\n    for (long i=0; i<nSlots; i++) {\n      RX te = phimxmod / factors[i]; // \\prod_{j\\ne i} Fj\n      te %= factors[i];              // \\prod_{j\\ne i} Fj mod Fi\n      InvMod(crtCoeffs[i], te, factors[i]); // \\prod_{j\\ne i} Fj^{-1} mod Fi\n    }\n  }\n  else {\n    PAlgebraLift(zMStar.getPhimX(), localFactors, factors, crtCoeffs, r);\n    RX phimxmod1;\n    conv(phimxmod1, zMStar.getPhimX());\n    build(PhimXMod, phimxmod1);\n    pPowRContext.save();\n  }\n\n  // set factorsOverZZ\n  factorsOverZZ.resize(nSlots);\n  for (long i = 0; i < nSlots; i++)\n    conv(factorsOverZZ[i], factors[i]);\n\n  genCrtTable();\n  genMaskTable();\n}\n\n// Assumes current zz_p modulus is p^r\n// computes S = F^{-1} mod G via Hensel lifting\nvoid InvModpr(zz_pX& S, const zz_pX& F, const zz_pX& G, long p, long r)\n{\n  ZZX ff, gg, ss, tt;\n\n  ff = to_ZZX(F); \n  gg = to_ZZX(G);\n\n  zz_pBak bak;\n  bak.save();\n  zz_p::init(p);\n\n  zz_pX f, g, s, t;\n  f = to_zz_pX(ff);\n  g = to_zz_pX(gg);\n  s = InvMod(f, g);\n  t = (1-s*f)/g;\n  assert(s*f + t*g == 1);\n  ss = to_ZZX(s);\n  tt = to_ZZX(t);\n\n  ZZ pk = to_ZZ(1);\n\n  for (long k = 1; k < r; k++) {\n    // lift from p^k to p^{k+1}\n    pk = pk * p;\n\n    assert(divide(ss*ff + tt*gg - 1, pk));\n\n    zz_pX d = to_zz_pX( (1 - (ss*ff + tt*gg))/pk );\n    zz_pX s1, t1;\n    s1 = (s * d) % g;\n    t1 = (d-s1*f)/g;\n    ss = ss + pk*to_ZZX(s1);\n    tt = tt + pk*to_ZZX(t1);\n  }\n\n  bak.restore();\n\n  S = to_zz_pX(ss);\n\n  assert((S*F) % G == 1);\n}\n\ntemplate<class T> \nvoid PAlgebraLift(const ZZX& phimx, const T& lfactors, T& factors, T& crtc, long r)\n{\n   Error(\"uninstatiated version of PAlgebraLift\");\n}\n\n// This specialized version of PAlgebraLift does the hensel\n// lifting needed to finish off the initialization.\n// It assumes the zz_p modulus is initialized to p\n// when called, and leaves it set to p^r\n\ntemplate<> \nvoid PAlgebraLift(const ZZX& phimx, const vec_zz_pX& lfactors, vec_zz_pX& factors, vec_zz_pX& crtc, long r)\n{\n  long p = zz_p::modulus(); \n  long nSlots = lfactors.length();\n\n\n  vec_ZZX vzz;             // need to go via ZZX\n\n  // lift the factors of Phi_m(X) from mod-2 to mod-2^r\n  if (lfactors.length() > 1)\n    MultiLift(vzz, lfactors, phimx, r); // defined in NTL::ZZXFactoring\n  else {\n    vzz.SetLength(1);\n    vzz[0] = phimx;\n  }\n\n  // Compute the zz_pContext object for mod p^r arithmetic\n  zz_p::init(power_long(p, r));\n\n  zz_pX phimxmod = to_zz_pX(phimx);\n  factors.SetLength(nSlots);\n  for (long i=0; i<nSlots; i++)             // Convert from ZZX to zz_pX\n    conv(factors[i], vzz[i]);\n\n  // Finally compute the CRT coefficients for the factors\n  crtc.SetLength(nSlots);\n  for (long i=0; i<nSlots; i++) {\n    zz_pX& fct = factors[i];\n    zz_pX te = phimxmod / fct; // \\prod_{j\\ne i} Fj\n    te %= fct;                // \\prod_{j\\ne i} Fj mod Fi\n    InvModpr(crtc[i], te, fct, p, r);// \\prod_{j\\ne i} Fj^{-1} mod Fi\n  }\n\n}\n\n// Returns a vector crt[] such that crt[i] = p mod Ft (with t = T[i])\ntemplate<class type> \nvoid PAlgebraModDerived<type>::CRT_decompose(vector<RX>& crt, const RX& H) const\n{\n  unsigned long nSlots = zMStar.getNSlots();\n\n  if (isDryRun()) {\n    crt.clear();\n    return;\n  }\n  crt.resize(nSlots);\n  for (unsigned long i=0; i<nSlots; i++)\n    rem(crt[i], H, factors[i]); // crt[i] = H % factors[i]\n}\n\ntemplate<class type>\nvoid PAlgebraModDerived<type>::embedInAllSlots(RX& H, const RX& alpha, \n                                            const MappingData<type>& mappingData) const\n{\n  if (isDryRun()) {\n    H = RX::zero();\n    return;\n  }\n  FHE_TIMER_START;\n  long nSlots = zMStar.getNSlots();\n\n  vector<RX> crt(nSlots); // alloate space for CRT components\n\n  // The i'th CRT component is (H mod F_t) = alpha(maps[i]) mod F_t,\n  // where with t=T[i].\n\n  \n  if (IsX(mappingData.G) || deg(alpha) <= 0) {\n    // special case...no need for CompMod, which is\n    // is not optimized for this case\n\n    for (long i=0; i<nSlots; i++)   // crt[i] = alpha(maps[i]) mod Ft\n      crt[i] = ConstTerm(alpha);\n  }\n  else {\n    // general case...\n\n    for (long i=0; i<nSlots; i++)   // crt[i] = alpha(maps[i]) mod Ft\n      CompMod(crt[i], alpha, mappingData.maps[i], factors[i]);\n  }\n\n  CRT_reconstruct(H,crt); // interpolate to get H\n  FHE_TIMER_STOP;\n}\n\ntemplate<class type>\nvoid PAlgebraModDerived<type>::embedInSlots(RX& H, const vector<RX>& alphas, \n                                         const MappingData<type>& mappingData) const\n{\n  if (isDryRun()) {\n    H = RX::zero();\n    return;\n  }\n  FHE_TIMER_START;\n\n  long nSlots = zMStar.getNSlots();\n  assert(lsize(alphas) == nSlots);\n\n  for (long i = 0; i < nSlots; i++) assert(deg(alphas[i]) < mappingData.degG); \n \n  vector<RX> crt(nSlots); // alloate space for CRT components\n\n  // The i'th CRT component is (H mod F_t) = alphas[i](maps[i]) mod F_t,\n  // where with t=T[i].\n\n  if (IsX(mappingData.G)) {\n    // special case...no need for CompMod, which is\n    // is not optimized for this case\n\n    for (long i=0; i<nSlots; i++)   // crt[i] = alpha(maps[i]) mod Ft\n      crt[i] = ConstTerm(alphas[i]);\n  }\n  else {\n    // general case...still try to avoid CompMod when possible,\n    // which is the common case for encoding masks\n\n    for (long i=0; i<nSlots; i++) {   // crt[i] = alpha(maps[i]) mod Ft\n      if (deg(alphas[i]) <= 0) \n        crt[i] = alphas[i];\n      else\n        CompMod(crt[i], alphas[i], mappingData.maps[i], factors[i]);\n    }\n  }\n\n  CRT_reconstruct(H,crt); // interpolate to get p\n\n  FHE_TIMER_STOP;\n}\n\ntemplate<class type>\nvoid PAlgebraModDerived<type>::CRT_reconstruct(RX& H, vector<RX>& crt) const\n{\n  if (isDryRun()) {\n    H = RX::zero();\n    return;\n  }\n  FHE_TIMER_START;\n  long nslots = zMStar.getNSlots();\n\n\n  const vector<RX>& ctab = crtTable;\n\n  clear(H);\n  RX tmp1, tmp2;\n\n  bool easy = true;\n  for (long i = 0; i < nslots; i++) \n    if (!IsZero(crt[i]) && !IsOne(crt[i])) {\n      easy = false;\n      break;\n    }\n    \n  if (easy) {\n    for (long i=0; i<nslots; i++) \n      if (!IsZero(crt[i])) \n        H += ctab[i];\n  }\n  else {\n    vector<RX> crt1;\n    crt1.resize(nslots);\n    for (long i = 0; i < nslots; i++)\n       MulMod(crt1[i], crt[i], crtCoeffs[i], factors[i]);\n\n    evalTree(H, crtTree, crt1, 0, nslots);\n  }\n  FHE_TIMER_STOP;\n}\n\ntemplate<class type>\nvoid PAlgebraModDerived<type>::mapToFt(RX& w,\n\t\t\t     const RX& G,unsigned long t,const RX* rF1) const\n{\n  if (isDryRun()) {\n    w = RX::zero();\n    return;\n  }\n  long i = zMStar.indexOfRep(t);\n  if (i < 0) { clear(w); return; }\n\n\n  if (rF1==NULL) {               // Compute the representation \"from scratch\"\n    // special case\n    if (G == factors[i]) {\n      SetX(w);\n      return;\n    }\n\n    //special case\n    if (deg(G) == 1) {\n      w = -ConstTerm(G);\n      return;\n    }\n\n    // the general case: currently only works when r == 1\n    assert(r == 1);  \n\n    REBak bak; bak.save();\n    RE::init(factors[i]);        // work with the extension field GF_p[X]/Ft(X)\n    REX Ga;\n    conv(Ga, G);                 // G as a polynomial over the extension field\n\n    vec_RE roots;\n    FindRoots(roots, Ga);        // Find roots of G in this field\n    RE* first = &roots[0];\n    RE* last = first + roots.length();\n    RE* smallest = min_element(first, last);\n                                // make a canonical choice\n    w=rep(*smallest);         \n    return;\n  }\n  // if rF1 is set, then use it instead, setting w = rF1(X^t) mod Ft(X)\n  RXModulus Ft(factors[i]);\n  //  long tInv = InvMod(t,m);\n  RX X2t = PowerXMod(t,Ft);    // X2t = X^t mod Ft\n  w = CompMod(*rF1,X2t,Ft);      // w = F1(X2t) mod Ft\n\n  /* Debugging sanity-check: G(w)=0 in the extension field (Z/2Z)[X]/Ft(X)\n  RE::init(factors[i]);\n  REX Ga;\n  conv(Ga, G); // G as a polynomial over the extension field\n  RE ra;\n  conv(ra, w);         // w is an element in the extension field\n  eval(ra,Ga,ra);  // ra = Ga(ra)\n  if (!IsZero(ra)) {// check that Ga(w)=0 in this extension field\n    cout << \"rF1(X^t) mod Ft(X) != root of G mod Ft, t=\" << t << endl;\n    exit(0);    \n  }*******************************************************************/\n}\n\ntemplate<class type> \nvoid PAlgebraModDerived<type>::mapToSlots(MappingData<type>& mappingData, const RX& G) const \n{\n  assert(deg(G) > 0 && zMStar.getOrdP() % deg(G) == 0);\n  assert(LeadCoeff(G) == 1);\n  mappingData.G = G;\n  mappingData.degG = deg(mappingData.G);\n\n  long nSlots = zMStar.getNSlots();\n  long m = zMStar.getM();\n\n  mappingData.maps.resize(nSlots);\n\n  mapToF1(mappingData.maps[0],mappingData.G); // mapping from base-G to base-F1\n  for (long i=1; i<nSlots; i++)\n    mapToFt(mappingData.maps[i], mappingData.G, zMStar.ith_rep(i), &(mappingData.maps[0])); \n\n  REBak bak; bak.save(); \n  RE::init(mappingData.G);\n  mappingData.contextForG.save();\n\n  if (deg(mappingData.G)==1) return;\n\n  mappingData.rmaps.resize(nSlots);\n\n  if (G == factors[0]) {\n    // an important special case\n\n    for (long i = 0; i < nSlots; i++) {\n        long t = zMStar.ith_rep(i);\n        long tInv = InvMod(t, m);\n\n        RX ct_rep;\n        PowerXMod(ct_rep, tInv, G);\n        \n        RE ct;\n        conv(ct, ct_rep);\n\n        REX Qi;\n        SetCoeff(Qi, 1, 1);\n        SetCoeff(Qi, 0, -ct);\n\n        mappingData.rmaps[i] = Qi;\n    }\n  }\n  else\n  {\n    // the general case: currently only works when r == 1\n\n    assert(r == 1);\n\n    vec_REX FRts;\n    for (long i=0; i<nSlots; i++) {\n      // We need to lift Fi from R[Y] to (R[X]/G(X))[Y]\n      REX  Qi;\n      long t, tInv=0;\n\n      if (i == 0) {\n        conv(Qi,factors[i]);\n        FRts=EDF(Qi, FrobeniusMap(Qi), deg(Qi)/deg(G)); \n        // factor Fi over GF(p)[X]/G(X)\n      }\n      else {\n        t = zMStar.ith_rep(i);\n        tInv = InvMod(t, m);\n      }\n\n      // need to choose the right factor, the one that gives us back X\n      long j;\n      for (j=0; j<FRts.length(); j++) { \n        // lift maps[i] to (R[X]/G(X))[Y] and reduce mod j'th factor of Fi\n\n        REX FRtsj;\n        if (i == 0) \n           FRtsj = FRts[j];\n        else {\n            REX X2tInv = PowerXMod(tInv, FRts[j]);\n            IrredPolyMod(FRtsj, X2tInv, FRts[j]);\n        }\n\n        // FRtsj is the jth factor of factors[i] over the extension field.\n        // For j > 0, we save some time by computing it from the jth factor \n        // of factors[0] via a minimal polynomial computation.\n        \n        REX GRti;\n        conv(GRti, mappingData.maps[i]);\n        GRti %= FRtsj;\n\n        if (IsX(rep(ConstTerm(GRti)))) { // is GRti == X?\n          Qi = FRtsj;                // If so, we found the right factor\n          break;\n        } // If this does not happen then move to the next factor of Fi\n      }\n\n      assert(j < FRts.length());\n      mappingData.rmaps[i] = Qi;\n    }\n  }\n}\n\ntemplate<class type> \nvoid PAlgebraModDerived<type>::decodePlaintext(\n   vector<RX>& alphas, const RX& ptxt, const MappingData<type>& mappingData) const\n{\n  long nSlots = zMStar.getNSlots();\n  if (isDryRun()) {\n    alphas.assign(nSlots, RX::zero());\n    return;\n  }\n\n  // First decompose p into CRT components\n  vector<RX> CRTcomps(nSlots); // allocate space for CRT component\n  CRT_decompose(CRTcomps, ptxt);  // CRTcomps[i] = p mod facors[i]\n\n  if (mappingData.degG==1) {\n    alphas = CRTcomps;\n    return;\n  }\n\n  alphas.resize(nSlots);\n\n  REBak bak; bak.save(); mappingData.contextForG.restore();\n\n  for (long i=0; i<nSlots; i++) {\n    REX te; \n    conv(te, CRTcomps[i]);   // lift i'th CRT componnet to mod G(X)\n    te %= mappingData.rmaps[i];  // reduce CRTcomps[i](Y) mod Qi(Y), over (Z_2[X]/G(X))\n\n    // the free term (no Y component) should be our answer (as a poly(X))\n    alphas[i] = rep(ConstTerm(te));\n  }\n}\n\ntemplate<class type>\nvoid PAlgebraModDerived<type>::decodeSlots(std::vector <RX> &alphas,\n                                           const RX &ptxt,\n                                           const std::vector<long> &positions,\n                                           const MappingData <type> &mappingData) const\n{\n  long nSlots = zMStar.getNSlots();\n  for (auto position : positions)\n    assert(position >= 0 && position < nSlots && \"Invalid positions\");\n\n  if (isDryRun()) {\n    alphas = std::vector<RX>(positions.size(), RX::zero());\n    return;\n  }\n\n  size_t nPos = positions.size();\n  vector<RX> CRTcomps(nPos); // allocate space for CRT component\n  for (size_t i = 0; i < nPos; i++)\n    rem(CRTcomps[i], ptxt, factors[positions[i]]); // CRTcomp = H % factors[i]\n\n  if (mappingData.degG==1) {\n    alphas = CRTcomps;\n    return;\n  }\n\n  alphas.resize(nPos);\n\n  REBak bak; bak.save(); mappingData.contextForG.restore();\n\n  for (size_t i = 0; i < nPos; i++) {\n    REX te;\n    conv(te, CRTcomps[i]);   // lift i'th CRT componnet to mod G(X)\n    te %= mappingData.rmaps[positions[i]];  // reduce CRTcomps[i](Y) mod Qi(Y), over (Z_2[X]/G(X))\n\n    // the free term (no Y component) should be our answer (as a poly(X))\n    alphas[i] = rep(ConstTerm(te));\n  }\n}\n\ntemplate<class type>\nvoid PAlgebraModDerived<type>::decode1Slot(RX &alpha, const RX &ptxt, const long i,\n                                           const MappingData <type> &mappingData) const\n{\n  std::vector<RX> oneSlot;\n  std::vector<long> position(1, i);\n  decodeSlots(oneSlot, ptxt, position, mappingData);\n  alpha = position.front();\n}\n\ntemplate<class type> \nvoid PAlgebraModDerived<type>::\nbuildLinPolyCoeffs(vector<RX>& C, const vector<RX>& L,\n                   const MappingData<type>& mappingData) const\n{\n  REBak bak; bak.save(); mappingData.contextForG.restore();\n\n  long d = RE::degree();\n  long p = zMStar.getP();\n\n  assert(lsize(L) == d);\n\n  vec_RE LL;\n  LL.SetLength(d);\n\n  for (long i = 0; i < d; i++)\n    conv(LL[i], L[i]);\n\n  vec_RE CC;\n  ::buildLinPolyCoeffs(CC, LL, p, r);\n\n  C.resize(d);\n  for (long i = 0; i < d; i++)\n    C[i] = rep(CC[i]);\n}\n\n// code for generating mask tables\n// the tables are generated \"on demand\"\n\ntemplate<class type> \nvoid PAlgebraModDerived<type>::genMaskTable() \n{\n  // This is only called by the constructor, which has already\n  // set the zz_p context\n\n  RX tmp1;\n  \n  maskTable.resize(zMStar.numOfGens());\n  for (long i = 0; i < (long)zMStar.numOfGens(); i++) {\n    long ord = zMStar.OrderOf(i);\n    maskTable[i].resize(ord+1);\n    maskTable[i][ord] = 0;\n    for (long j = ord-1; j >= 1; j--) {\n      // initialize mask that is 1 whenever the ith coordinate is at least j\n      // Note: maskTable[i][0] = constant 1, maskTable[i][ord] = constant 0\n      maskTable[i][j] = maskTable[i][j+1];\n      for (long k = 0; k < (long)zMStar.getNSlots(); k++) {\n         if (zMStar.coordinate(i, k) == j) {\n           div(tmp1, PhimXMod, factors[k]);\n           mul(tmp1, tmp1, crtCoeffs[k]);\n           add(maskTable[i][j], maskTable[i][j], tmp1);\n         }\n      }\n    }\n    maskTable[i][0] = 1;\n  }\n}\n\n// code for generating crt tables\n// the tables are generated \"on demand\"\n\ntemplate<class type> \nvoid PAlgebraModDerived<type>::genCrtTable() \n{\n  // This is only called by the constructor, which has already\n  // set the zz_p context\n\n  long nslots = zMStar.getNSlots();\n  crtTable.resize(nslots);\n  for (long i = 0; i < nslots; i++) {\n    RX allBut_i = PhimXMod / factors[i]; // = \\prod_{j \\ne i }Fj\n    allBut_i *= crtCoeffs[i]; // = 1 mod Fi and = 0 mod Fj for j \\ne i\n    crtTable[i] = allBut_i;\n  }\n\n  buildTree(crtTree, 0, nslots);\n}\n\ntemplate<class type> \nvoid PAlgebraModDerived<type>::\n  buildTree(shared_ptr< TNode<RX> >& res, long offset, long extent) const\n{\n  if (extent == 1)\n    res = buildTNode<RX>(nullTNode<RX>(), nullTNode<RX>(), \n                            factors[offset]);\n  else {\n    long half = extent/2;\n    shared_ptr< TNode<RX> > left, right;\n    buildTree(left, offset, half);\n    buildTree(right, offset+half, extent-half);\n    RX data = left->data * right->data;\n    res = buildTNode<RX>(left, right, data);\n  }\n}\n\ntemplate<class type> \nvoid PAlgebraModDerived<type>::evalTree(RX& res,\n              shared_ptr< TNode<RX> > tree,\n              const vector<RX>& crt1,\n              long offset, long extent) const\n{\n  if (extent == 1) \n    res = crt1[offset];\n  else {\n    long half = extent/2;\n    RX lres, rres;\n    evalTree(lres, tree->left, crt1, offset, half);\n    evalTree(rres, tree->right, crt1, offset+half, extent-half);\n    RX tmp1, tmp2;\n    mul(tmp1, lres, tree->right->data);\n    mul(tmp2, rres, tree->left->data);\n    add(tmp1, tmp1, tmp2);\n    res = tmp1;\n  }\n}\n\n// Explicit instantiation\n\ntemplate class PAlgebraModDerived<PA_GF2>;\ntemplate class PAlgebraModDerived<PA_zz_p>;\n\n// Helper function\nCubeSignature::CubeSignature(const PAlgebra& alg): ndims(0)\n{\n  Vec<long> _dims(INIT_SIZE, alg.numOfGens());\n  for (long i=0; i<(long)alg.numOfGens(); i++) _dims[i] = alg.OrderOf(i);\n  initSignature(_dims);\n}\n", "meta": {"hexsha": "a8be253849642bea760889142ced9c4555ae5371", "size": 26425, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "core/src/HElib/PAlgebra.cpp", "max_stars_repo_name": "fionser/CODA", "max_stars_repo_head_hexsha": "db234a1e9761d379fb96ae17eef3b77254f8781c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 12.0, "max_stars_repo_stars_event_min_datetime": "2017-02-24T19:28:07.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-05T04:40:47.000Z", "max_issues_repo_path": "core/src/HElib/PAlgebra.cpp", "max_issues_repo_name": "fionser/CODA", "max_issues_repo_head_hexsha": "db234a1e9761d379fb96ae17eef3b77254f8781c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2017-04-15T03:41:18.000Z", "max_issues_repo_issues_event_max_datetime": "2017-04-24T09:06:15.000Z", "max_forks_repo_path": "core/src/HElib/PAlgebra.cpp", "max_forks_repo_name": "fionser/CODA", "max_forks_repo_head_hexsha": "db234a1e9761d379fb96ae17eef3b77254f8781c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2017-05-14T10:12:50.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-07T03:50:56.000Z", "avg_line_length": 27.6123301985, "max_line_length": 107, "alphanum_fraction": 0.5915988647, "num_tokens": 8445, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5621765008857981, "lm_q2_score": 0.5428632831725052, "lm_q1q2_score": 0.3051849809932951}}
{"text": "// Copyright (c) 2019, Torsten Sattler\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are met:\n//\n//     * Redistributions of source code must retain the above copyright\n//       notice, this list of conditions and the following disclaimer.\n//\n//     * Redistributions in binary form must reproduce the above copyright\n//       notice, this list of conditions and the following disclaimer in the\n//       documentation and/or other materials provided with the distribution.\n//\n//     * Neither the name of the copyright holder nor the\n//       names of its contributors may be used to endorse or promote products\n//       derived from this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n// ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY\n// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n//\n// author: Torsten Sattler, torsten.sattler.de@googlemail.com\n\n#include <algorithm>\n#include <cmath>\n#include <cstddef>\n#include <cstdint>\n#include <limits>\n#include <random>\n#include <vector>\n\n#include <Eigen/Core>\n#include <Eigen/Dense>\n#include <Eigen/Eigenvalues>\n#include <Eigen/Geometry>\n\n#include \"line_estimator.h\"\n\nnamespace ransac_lib {\n\nLineEstimator::LineEstimator(const Eigen::Matrix2Xd& data) {\n  data_ = data;\n  num_data_ = data_.cols();\n}\n\nint LineEstimator::MinimalSolver(const std::vector<int>& sample,\n                                 std::vector<Eigen::Vector3d>* lines) const {\n  lines->clear();\n  if (sample.size() < 2u) return 0;\n\n  lines->resize(1);\n  Eigen::Vector3d p1(data_(0, sample[0]), data_(1, sample[0]), 1.0);\n  Eigen::Vector3d p2(data_(0, sample[1]), data_(1, sample[1]), 1.0);\n  (*lines)[0] = p1.cross(p2);\n  // Normalizes the line such that the normal of the line has unit length.\n  double normal_norm = (*lines)[0].head<2>().norm();\n  if (normal_norm == 0.0) {\n    lines->clear();\n    return 0;\n  }\n\n  (*lines)[0] /= normal_norm;\n\n  return 1;\n}\n\nint LineEstimator::NonMinimalSolver(const std::vector<int>& sample,\n                                    Eigen::Vector3d* line) const {\n  if (sample.size() < 6u) return 0;\n\n  const int kNumSamples = static_cast<int>(sample.size());\n\n  // We fit the line by estimating the eigenvectors of the covariance matrix\n  // of the data.\n  Eigen::Vector2d mean(0.0, 0.0);\n  for (int i = 0; i < kNumSamples; ++i) {\n    mean += data_.col(sample[i]);\n  }\n  mean /= static_cast<double>(kNumSamples);\n\n  // Builds the covariance matrix C.\n  Eigen::Matrix2d C = Eigen::Matrix2d::Zero();\n\n  for (int i = 0; i < kNumSamples; ++i) {\n    Eigen::Vector2d d = data_.col(sample[i]) - mean;\n    C += d * d.transpose();\n  }\n  C /= static_cast<double>(kNumSamples - 1);\n\n  Eigen::SelfAdjointEigenSolver<Eigen::Matrix2d> eig_solver(C);\n  if (eig_solver.info() != Eigen::Success) return 0;\n\n  line->head<2>() = eig_solver.eigenvectors().col(1);\n\n  // Re-estimates the translation along the line to account for subtraction\n  // of mean.\n  (*line)[2] = -line->head<2>().dot(mean);\n\n  return 1;\n}\n\n// Evaluates the line on the i-th data point.\ndouble LineEstimator::EvaluateModelOnPoint(const Eigen::Vector3d& line,\n                                           int i) const {\n  double residual = line.dot(data_.col(i).homogeneous());\n  return residual * residual;\n}\n\n}  // namespace ransac_lib\n", "meta": {"hexsha": "7274f0030f388f8b0052446e9c9b175a06759647", "size": 4029, "ext": "cc", "lang": "C++", "max_stars_repo_path": "examples/line_estimator.cc", "max_stars_repo_name": "erikstenborg/RansacLib", "max_stars_repo_head_hexsha": "9c2d140dd11b3b62661083266d20a2f90db70eaa", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 216.0, "max_stars_repo_stars_event_min_datetime": "2019-08-17T14:22:38.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T06:19:08.000Z", "max_issues_repo_path": "examples/line_estimator.cc", "max_issues_repo_name": "erikstenborg/RansacLib", "max_issues_repo_head_hexsha": "9c2d140dd11b3b62661083266d20a2f90db70eaa", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 11.0, "max_issues_repo_issues_event_min_datetime": "2019-09-27T07:26:19.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-04T16:41:41.000Z", "max_forks_repo_path": "examples/line_estimator.cc", "max_forks_repo_name": "erikstenborg/RansacLib", "max_forks_repo_head_hexsha": "9c2d140dd11b3b62661083266d20a2f90db70eaa", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 32.0, "max_forks_repo_forks_event_min_datetime": "2019-08-18T05:52:30.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-29T07:01:54.000Z", "avg_line_length": 34.4358974359, "max_line_length": 80, "alphanum_fraction": 0.6850335071, "num_tokens": 1023, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6150878414043814, "lm_q2_score": 0.49609382947091946, "lm_q1q2_score": 0.30514128270330115}}
{"text": "/* Author: David Neckels, Boulder, Colorado, 2007, 2008 */\n\n/*    $Id: step-33.cc 28601 2013-02-27 04:47:34Z heister $       */\n/*                                                                */\n/*    Copyright (C) 2007-2012 by the deal.II authors and David Neckels */\n/*                                                                */\n/*    This file is subject to QPL and may not be  distributed     */\n/*    without copyright and license information. Please refer     */\n/*    to the file deal.II/doc/license.html for the  text  and     */\n/*    further information on this license.                        */\n\n// @sect3{Include files}\n\n// First a standard set of deal.II includes. Nothing special to comment on\n// here:\n#include <deal.II/base/quadrature_lib.h>\n#include <deal.II/base/function.h>\n#include <deal.II/base/parameter_handler.h>\n#include <deal.II/base/function_parser.h>\n#include <deal.II/base/utilities.h>\n#include <deal.II/base/conditional_ostream.h>\n\n#include <deal.II/lac/vector.h>\n#include <deal.II/lac/compressed_sparsity_pattern.h>\n\n#include <deal.II/grid/tria.h>\n#include <deal.II/grid/grid_generator.h>\n#include <deal.II/grid/grid_out.h>\n#include <deal.II/grid/grid_refinement.h>\n#include <deal.II/grid/tria_accessor.h>\n#include <deal.II/grid/tria_iterator.h>\n#include <deal.II/grid/grid_in.h>\n\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\n#include <deal.II/fe/fe_values.h>\n#include <deal.II/fe/fe_system.h>\n#include <deal.II/fe/mapping_q1.h>\n#include <deal.II/fe/fe_q.h>\n\n#include <deal.II/numerics/data_out.h>\n#include <deal.II/numerics/vector_tools.h>\n#include <deal.II/numerics/solution_transfer.h>\n\n// Then, as mentioned in the introduction, we use various Trilinos packages as\n// linear solvers as well as for automatic differentiation. These are in the\n// following include files.\n//\n// Since deal.II provides interfaces to the basic Trilinos matrices, vectors,\n// preconditioners and solvers, we include them similarly as deal.II linear\n// algebra structures.\n#include <deal.II/lac/trilinos_sparse_matrix.h>\n#include <deal.II/lac/trilinos_vector.h>\n#include <deal.II/lac/trilinos_precondition.h>\n#include <deal.II/lac/trilinos_solver.h>\n\n\n// Sacado is the automatic differentiation package within Trilinos, which is\n// used to find the Jacobian for a fully implicit Newton iteration:\n#include <Sacado.hpp>\n\n\n// And this again is C++:\n#include <iostream>\n#include <fstream>\n#include <vector>\n#include <memory>\n\n// To end this section, introduce everything in the dealii library into the\n// namespace into which the contents of this program will go:\nnamespace Step33\n{\n  using namespace dealii;\n\n\n  // @sect3{Euler equation specifics}\n\n  // Here we define the flux function for this particular system of\n  // conservation laws, as well as pretty much everything else that's specific\n  // to the Euler equations for gas dynamics, for reasons discussed in the\n  // introduction. We group all this into a structure that defines everything\n  // that has to do with the flux. All members of this structure are static,\n  // i.e. the structure has no actual state specified by instance member\n  // variables. The better way to do this, rather than a structure with all\n  // static members would be to use a namespace -- but namespaces can't be\n  // templatized and we want some of the member variables of the structure to\n  // depend on the space dimension, which we in our usual way introduce using\n  // a template parameter.\n  template <int dim>\n  struct EulerEquations\n  {\n    // @sect4{Component description}\n\n    // First a few variables that describe the various components of our\n    // solution vector in a generic way. This includes the number of\n    // components in the system (Euler's equations have one entry for momenta\n    // in each spatial direction, plus the energy and density components, for\n    // a total of <code>dim+2</code> components), as well as functions that\n    // describe the index within the solution vector of the first momentum\n    // component, the density component, and the energy density\n    // component. Note that all these %numbers depend on the space dimension;\n    // defining them in a generic way (rather than by implicit convention)\n    // makes our code more flexible and makes it easier to later extend it,\n    // for example by adding more components to the equations.\n    static const unsigned int n_components             = dim + 2;\n    static const unsigned int first_momentum_component = 0;\n    static const unsigned int density_component        = dim;\n    static const unsigned int energy_component         = dim+1;\n\n    // When generating graphical output way down in this program, we need to\n    // specify the names of the solution variables as well as how the various\n    // components group into vector and scalar fields. We could describe this\n    // there, but in order to keep things that have to do with the Euler\n    // equation localized here and the rest of the program as generic as\n    // possible, we provide this sort of information in the following two\n    // functions:\n    static\n    std::vector<std::string>\n    component_names ()\n    {\n      std::vector<std::string> names (dim, \"momentum\");\n      names.push_back (\"density\");\n      names.push_back (\"energy_density\");\n\n      return names;\n    }\n\n\n    static\n    std::vector<DataComponentInterpretation::DataComponentInterpretation>\n    component_interpretation ()\n    {\n      std::vector<DataComponentInterpretation::DataComponentInterpretation>\n      data_component_interpretation\n      (dim, DataComponentInterpretation::component_is_part_of_vector);\n      data_component_interpretation\n      .push_back (DataComponentInterpretation::component_is_scalar);\n      data_component_interpretation\n      .push_back (DataComponentInterpretation::component_is_scalar);\n\n      return data_component_interpretation;\n    }\n\n\n    // @sect4{Transformations between variables}\n\n    // Next, we define the gas constant. We will set it to 1.4 in its\n    // definition immediately following the declaration of this class (unlike\n    // integer variables, like the ones above, static const floating point\n    // member variables cannot be initialized within the class declaration in\n    // C++). This value of 1.4 is representative of a gas that consists of\n    // molecules composed of two atoms, such as air which consists up to small\n    // traces almost entirely of $N_2$ and $O_2$.\n    static const double gas_gamma;\n\n\n    // In the following, we will need to compute the kinetic energy and the\n    // pressure from a vector of conserved variables. This we can do based on\n    // the energy density and the kinetic energy $\\frac 12 \\rho |\\mathbf v|^2\n    // = \\frac{|\\rho \\mathbf v|^2}{2\\rho}$ (note that the independent\n    // variables contain the momentum components $\\rho v_i$, not the\n    // velocities $v_i$).\n    //\n    // There is one slight problem: We will need to call the following\n    // functions with input arguments of type\n    // <code>std::vector@<number@></code> and\n    // <code>Vector@<number@></code>. The problem is that the former has an\n    // access operator <code>operator[]</code> whereas the latter, for\n    // historical reasons, has <code>operator()</code>. We wouldn't be able to\n    // write the function in a generic way if we were to use one or the other\n    // of these. Fortunately, we can use the following trick: instead of\n    // writing <code>v[i]</code> or <code>v(i)</code>, we can use\n    // <code>*(v.begin() + i)</code>, i.e. we generate an iterator that points\n    // to the <code>i</code>th element, and then dereference it. This works\n    // for both kinds of vectors -- not the prettiest solution, but one that\n    // works.\n    template <typename number, typename InputVector>\n    static\n    number\n    compute_kinetic_energy (const InputVector &W)\n    {\n      number kinetic_energy = 0;\n      for (unsigned int d=0; d<dim; ++d)\n        kinetic_energy += *(W.begin()+first_momentum_component+d) *\n                          *(W.begin()+first_momentum_component+d);\n      kinetic_energy *= 1./(2 * *(W.begin() + density_component));\n\n      return kinetic_energy;\n    }\n\n\n    template <typename number, typename InputVector>\n    static\n    number\n    compute_pressure (const InputVector &W)\n    {\n      return ((gas_gamma-1.0) *\n              (*(W.begin() + energy_component) -\n               compute_kinetic_energy<number>(W)));\n    }\n\n\n    // @sect4{EulerEquations::compute_flux_matrix}\n\n    // We define the flux function $F(W)$ as one large matrix.  Each row of\n    // this matrix represents a scalar conservation law for the component in\n    // that row.  The exact form of this matrix is given in the\n    // introduction. Note that we know the size of the matrix: it has as many\n    // rows as the system has components, and <code>dim</code> columns; rather\n    // than using a FullMatrix object for such a matrix (which has a variable\n    // number of rows and columns and must therefore allocate memory on the\n    // heap each time such a matrix is created), we use a rectangular array of\n    // numbers right away.\n    //\n    // We templatize the numerical type of the flux function so that we may\n    // use the automatic differentiation type here.  Similarly, we will call\n    // the function with different input vector data types, so we templatize\n    // on it as well:\n    template <typename InputVector, typename number>\n    static\n    void compute_flux_matrix (const InputVector &W,\n                              number (&flux)[n_components][dim])\n    {\n      // First compute the pressure that appears in the flux matrix, and then\n      // compute the first <code>dim</code> columns of the matrix that\n      // correspond to the momentum terms:\n      const number pressure = compute_pressure<number> (W);\n\n      for (unsigned int d=0; d<dim; ++d)\n        {\n          for (unsigned int e=0; e<dim; ++e)\n            flux[first_momentum_component+d][e]\n              = W[first_momentum_component+d] *\n                W[first_momentum_component+e] /\n                W[density_component];\n\n          flux[first_momentum_component+d][d] += pressure;\n        }\n\n      // Then the terms for the density (i.e. mass conservation), and, lastly,\n      // conservation of energy:\n      for (unsigned int d=0; d<dim; ++d)\n        flux[density_component][d] = W[first_momentum_component+d];\n\n      for (unsigned int d=0; d<dim; ++d)\n        flux[energy_component][d] = W[first_momentum_component+d] /\n                                    W[density_component] *\n                                    (W[energy_component] + pressure);\n    }\n\n\n    // @sect4{EulerEquations::compute_normal_flux}\n\n    // On the boundaries of the domain and across hanging nodes we use a\n    // numerical flux function to enforce boundary conditions.  This routine\n    // is the basic Lax-Friedrich's flux with a stabilization parameter\n    // $\\alpha$. It's form has also been given already in the introduction:\n    template <typename InputVector>\n    static\n    void numerical_normal_flux (const Point<dim>          &normal,\n                                const InputVector         &Wplus,\n                                const InputVector         &Wminus,\n                                const double               alpha,\n                                Sacado::Fad::DFad<double> (&normal_flux)[n_components])\n    {\n      Sacado::Fad::DFad<double> iflux[n_components][dim];\n      Sacado::Fad::DFad<double> oflux[n_components][dim];\n\n      compute_flux_matrix (Wplus, iflux);\n      compute_flux_matrix (Wminus, oflux);\n\n      for (unsigned int di=0; di<n_components; ++di)\n        {\n          normal_flux[di] = 0;\n          for (unsigned int d=0; d<dim; ++d)\n            normal_flux[di] += 0.5*(iflux[di][d] + oflux[di][d]) * normal[d];\n\n          normal_flux[di] += 0.5*alpha*(Wplus[di] - Wminus[di]);\n        }\n    }\n\n    // @sect4{EulerEquations::compute_forcing_vector}\n\n    // In the same way as describing the flux function $\\mathbf F(\\mathbf w)$,\n    // we also need to have a way to describe the right hand side forcing\n    // term. As mentioned in the introduction, we consider only gravity here,\n    // which leads to the specific form $\\mathbf G(\\mathbf w) = \\left(\n    // g_1\\rho, g_2\\rho, g_3\\rho, 0, \\rho \\mathbf g \\cdot \\mathbf v\n    // \\right)^T$, shown here for the 3d case. More specifically, we will\n    // consider only $\\mathbf g=(0,0,-1)^T$ in 3d, or $\\mathbf g=(0,-1)^T$ in\n    // 2d. This naturally leads to the following function:\n    template <typename InputVector, typename number>\n    static\n    void compute_forcing_vector (const InputVector &W,\n                                 number (&forcing)[n_components])\n    {\n      const double gravity = -1.0;\n\n      for (unsigned int c=0; c<n_components; ++c)\n        switch (c)\n          {\n          case first_momentum_component+dim-1:\n            forcing[c] = gravity * W[density_component];\n            break;\n          case energy_component:\n            forcing[c] = gravity *\n                         W[density_component] *\n                         W[first_momentum_component+dim-1];\n            break;\n          default:\n            forcing[c] = 0;\n          }\n    }\n\n\n    // @sect4{Dealing with boundary conditions}\n\n    // Another thing we have to deal with is boundary conditions. To this end,\n    // let us first define the kinds of boundary conditions we currently know\n    // how to deal with:\n    enum BoundaryKind\n    {\n      inflow_boundary,\n      outflow_boundary,\n      no_penetration_boundary,\n      pressure_boundary\n    };\n\n\n    // The next part is to actually decide what to do at each kind of\n    // boundary. To this end, remember from the introduction that boundary\n    // conditions are specified by choosing a value $\\mathbf w^-$ on the\n    // outside of a boundary given an inhomogeneity $\\mathbf j$ and possibly\n    // the solution's value $\\mathbf w^+$ on the inside. Both are then passed\n    // to the numerical flux $\\mathbf H(\\mathbf{w}^+, \\mathbf{w}^-,\n    // \\mathbf{n})$ to define boundary contributions to the bilinear form.\n    //\n    // Boundary conditions can in some cases be specified for each component\n    // of the solution vector independently. For example, if component $c$ is\n    // marked for inflow, then $w^-_c = j_c$. If it is an outflow, then $w^-_c\n    // = w^+_c$. These two simple cases are handled first in the function\n    // below.\n    //\n    // There is a little snag that makes this function unpleasant from a C++\n    // language viewpoint: The output vector <code>Wminus</code> will of\n    // course be modified, so it shouldn't be a <code>const</code>\n    // argument. Yet it is in the implementation below, and needs to be in\n    // order to allow the code to compile. The reason is that we call this\n    // function at a place where <code>Wminus</code> is of type\n    // <code>Table@<2,Sacado::Fad::DFad@<double@> @></code>, this being 2d\n    // table with indices representing the quadrature point and the vector\n    // component, respectively. We call this function with\n    // <code>Wminus[q]</code> as last argument; subscripting a 2d table yields\n    // a temporary accessor object representing a 1d vector, just what we want\n    // here. The problem is that a temporary accessor object can't be bound to\n    // a non-const reference argument of a function, as we would like here,\n    // according to the C++ 1998 and 2003 standards (something that will be\n    // fixed with the next standard in the form of rvalue references).  We get\n    // away with making the output argument here a constant because it is the\n    // <i>accessor</i> object that's constant, not the table it points to:\n    // that one can still be written to. The hack is unpleasant nevertheless\n    // because it restricts the kind of data types that may be used as\n    // template argument to this function: a regular vector isn't going to do\n    // because that one can not be written to when marked\n    // <code>const</code>. With no good solution around at the moment, we'll\n    // go with the pragmatic, even if not pretty, solution shown here:\n    template <typename DataVector>\n    static\n    void\n    compute_Wminus (const BoundaryKind  (&boundary_kind)[n_components],\n                    const Point<dim>     &normal_vector,\n                    const DataVector     &Wplus,\n                    const Vector<double> &boundary_values,\n                    const DataVector     &Wminus)\n    {\n      for (unsigned int c = 0; c < n_components; c++)\n        switch (boundary_kind[c])\n          {\n          case inflow_boundary:\n          {\n            Wminus[c] = boundary_values(c);\n            break;\n          }\n\n          case outflow_boundary:\n          {\n            Wminus[c] = Wplus[c];\n            break;\n          }\n\n          // Prescribed pressure boundary conditions are a bit more\n          // complicated by the fact that even though the pressure is\n          // prescribed, we really are setting the energy component here,\n          // which will depend on velocity and pressure. So even though this\n          // seems like a Dirichlet type boundary condition, we get\n          // sensitivities of energy to velocity and density (unless these are\n          // also prescribed):\n          case pressure_boundary:\n          {\n            const typename DataVector::value_type\n            density = (boundary_kind[density_component] ==\n                       inflow_boundary\n                       ?\n                       boundary_values(density_component)\n                       :\n                       Wplus[density_component]);\n\n            typename DataVector::value_type kinetic_energy = 0;\n            for (unsigned int d=0; d<dim; ++d)\n              if (boundary_kind[d] == inflow_boundary)\n                kinetic_energy += boundary_values(d)*boundary_values(d);\n              else\n                kinetic_energy += Wplus[d]*Wplus[d];\n            kinetic_energy *= 1./2./density;\n\n            Wminus[c] = boundary_values(c) / (gas_gamma-1.0) +\n                        kinetic_energy;\n\n            break;\n          }\n\n          case no_penetration_boundary:\n          {\n            // We prescribe the velocity (we are dealing with a particular\n            // component here so that the average of the velocities is\n            // orthogonal to the surface normal.  This creates sensitivies of\n            // across the velocity components.\n            Sacado::Fad::DFad<double> vdotn = 0;\n            for (unsigned int d = 0; d < dim; d++)\n              {\n                vdotn += Wplus[d]*normal_vector[d];\n              }\n\n            Wminus[c] = Wplus[c] - 2.0*vdotn*normal_vector[c];\n            break;\n          }\n\n          default:\n            Assert (false, ExcNotImplemented());\n          }\n    }\n\n\n    // @sect4{EulerEquations::compute_refinement_indicators}\n\n    // In this class, we also want to specify how to refine the mesh. The\n    // class <code>ConservationLaw</code> that will use all the information we\n    // provide here in the <code>EulerEquation</code> class is pretty agnostic\n    // about the particular conservation law it solves: as doesn't even really\n    // care how many components a solution vector has. Consequently, it can't\n    // know what a reasonable refinement indicator would be. On the other\n    // hand, here we do, or at least we can come up with a reasonable choice:\n    // we simply look at the gradient of the density, and compute\n    // $\\eta_K=\\log\\left(1+|\\nabla\\rho(x_K)|\\right)$, where $x_K$ is the\n    // center of cell $K$.\n    //\n    // There are certainly a number of equally reasonable refinement\n    // indicators, but this one does, and it is easy to compute:\n    static\n    void\n    compute_refinement_indicators (const DoFHandler<dim> &dof_handler,\n                                   const Mapping<dim>    &mapping,\n                                   const Vector<double> &solution,\n                                   Vector<double>        &refinement_indicators)\n    {\n      const unsigned int dofs_per_cell = dof_handler.get_fe().dofs_per_cell;\n      std::vector<unsigned int> dofs (dofs_per_cell);\n\n      const QMidpoint<dim>  quadrature_formula;\n      const UpdateFlags update_flags = update_gradients;\n      FEValues<dim> fe_v (mapping, dof_handler.get_fe(),\n                          quadrature_formula, update_flags);\n\n      std::vector<std::vector<Tensor<1,dim> > >\n      dU (1, std::vector<Tensor<1,dim> >(n_components));\n\n      typename DoFHandler<dim>::active_cell_iterator\n      cell = dof_handler.begin_active(),\n      endc = dof_handler.end();\n      for (unsigned int cell_no=0; cell!=endc; ++cell, ++cell_no)\n        {\n          fe_v.reinit(cell);\n          fe_v.get_function_grads (solution, dU);\n\n          refinement_indicators(cell_no)\n            = std::log(1+\n                       std::sqrt(dU[0][density_component] *\n                                 dU[0][density_component]));\n        }\n    }\n\n\n\n    // @sect4{EulerEquations::Postprocessor}\n\n    // Finally, we declare a class that implements a postprocessing of data\n    // components. The problem this class solves is that the variables in the\n    // formulation of the Euler equations we use are in conservative rather\n    // than physical form: they are momentum densities $\\mathbf m=\\rho\\mathbf\n    // v$, density $\\rho$, and energy density $E$. What we would like to also\n    // put into our output file are velocities $\\mathbf v=\\frac{\\mathbf\n    // m}{\\rho}$ and pressure $p=(\\gamma-1)(E-\\frac{1}{2} \\rho |\\mathbf\n    // v|^2)$.\n    //\n    // In addition, we would like to add the possibility to generate schlieren\n    // plots. Schlieren plots are a way to visualize shocks and other sharp\n    // interfaces. The word \"schlieren\" is a German word that may be\n    // translated as \"striae\" -- it may be simpler to explain it by an\n    // example, however: schlieren is what you see when you, for example, pour\n    // highly concentrated alcohol, or a transparent saline solution, into\n    // water; the two have the same color, but they have different refractive\n    // indices and so before they are fully mixed light goes through the\n    // mixture along bent rays that lead to brightness variations if you look\n    // at it. That's \"schlieren\". A similar effect happens in compressible\n    // flow because the refractive index depends on the pressure (and\n    // therefore the density) of the gas.\n    //\n    // The origin of the word refers to two-dimensional projections of a\n    // three-dimensional volume (we see a 2d picture of the 3d fluid). In\n    // computational fluid dynamics, we can get an idea of this effect by\n    // considering what causes it: density variations. Schlieren plots are\n    // therefore produced by plotting $s=|\\nabla \\rho|^2$; obviously, $s$ is\n    // large in shocks and at other highly dynamic places. If so desired by\n    // the user (by specifying this in the input file), we would like to\n    // generate these schlieren plots in addition to the other derived\n    // quantities listed above.\n    //\n    // The implementation of the algorithms to compute derived quantities from\n    // the ones that solve our problem, and to output them into data file,\n    // rests on the DataPostprocessor class. It has extensive documentation,\n    // and other uses of the class can also be found in step-29. We therefore\n    // refrain from extensive comments.\n    class Postprocessor : public DataPostprocessor<dim>\n    {\n    public:\n      Postprocessor (const bool do_schlieren_plot);\n\n      virtual\n      void\n      compute_derived_quantities_vector (const std::vector<Vector<double> >              &uh,\n                                         const std::vector<std::vector<Tensor<1,dim> > > &duh,\n                                         const std::vector<std::vector<Tensor<2,dim> > > &dduh,\n                                         const std::vector<Point<dim> >                  &normals,\n                                         const std::vector<Point<dim> >                  &evaluation_points,\n                                         std::vector<Vector<double> >                    &computed_quantities) const;\n\n      virtual std::vector<std::string> get_names () const;\n\n      virtual\n      std::vector<DataComponentInterpretation::DataComponentInterpretation>\n      get_data_component_interpretation () const;\n\n      virtual UpdateFlags get_needed_update_flags () const;\n\n    private:\n      const bool do_schlieren_plot;\n    };\n  };\n\n\n  template <int dim>\n  const double EulerEquations<dim>::gas_gamma = 1.4;\n\n\n\n  template <int dim>\n  EulerEquations<dim>::Postprocessor::\n  Postprocessor (const bool do_schlieren_plot)\n    :\n    do_schlieren_plot (do_schlieren_plot)\n  {}\n\n\n  // This is the only function worth commenting on. When generating graphical\n  // output, the DataOut and related classes will call this function on each\n  // cell, with values, gradients, hessians, and normal vectors (in case we're\n  // working on faces) at each quadrature point. Note that the data at each\n  // quadrature point is itself vector-valued, namely the conserved\n  // variables. What we're going to do here is to compute the quantities we're\n  // interested in at each quadrature point. Note that for this we can ignore\n  // the hessians (\"dduh\") and normal vectors; to avoid compiler warnings\n  // about unused variables, we comment out their names.\n  template <int dim>\n  void\n  EulerEquations<dim>::Postprocessor::\n  compute_derived_quantities_vector (const std::vector<Vector<double> >              &uh,\n                                     const std::vector<std::vector<Tensor<1,dim> > > &duh,\n                                     const std::vector<std::vector<Tensor<2,dim> > > & /*dduh*/,\n                                     const std::vector<Point<dim> >                  & /*normals*/,\n                                     const std::vector<Point<dim> >                  & /*evaluation_points*/,\n                                     std::vector<Vector<double> >                    &computed_quantities) const\n  {\n    // At the beginning of the function, let us make sure that all variables\n    // have the correct sizes, so that we can access individual vector\n    // elements without having to wonder whether we might read or write\n    // invalid elements; we also check that the <code>duh</code> vector only\n    // contains data if we really need it (the system knows about this because\n    // we say so in the <code>get_needed_update_flags()</code> function\n    // below). For the inner vectors, we check that at least the first element\n    // of the outer vector has the correct inner size:\n    const unsigned int n_quadrature_points = uh.size();\n\n    if (do_schlieren_plot == true)\n      Assert (duh.size() == n_quadrature_points,\n              ExcInternalError())\n      else\n        Assert (duh.size() == 0,\n                ExcInternalError());\n\n    Assert (computed_quantities.size() == n_quadrature_points,\n            ExcInternalError());\n\n    Assert (uh[0].size() == n_components,\n            ExcInternalError());\n\n    if (do_schlieren_plot == true)\n      Assert (computed_quantities[0].size() == dim+2, ExcInternalError())\n      else\n        Assert (computed_quantities[0].size() == dim+1, ExcInternalError());\n\n    // Then loop over all quadrature points and do our work there. The code\n    // should be pretty self-explanatory. The order of output variables is\n    // first <code>dim</code> velocities, then the pressure, and if so desired\n    // the schlieren plot. Note that we try to be generic about the order of\n    // variables in the input vector, using the\n    // <code>first_momentum_component</code> and\n    // <code>density_component</code> information:\n    for (unsigned int q=0; q<n_quadrature_points; ++q)\n      {\n        const double density = uh[q](density_component);\n\n        for (unsigned int d=0; d<dim; ++d)\n          computed_quantities[q](d)\n            = uh[q](first_momentum_component+d) / density;\n\n        computed_quantities[q](dim) = compute_pressure<double> (uh[q]);\n\n        if (do_schlieren_plot == true)\n          computed_quantities[q](dim+1) = duh[q][density_component] *\n                                          duh[q][density_component];\n      }\n  }\n\n\n  template <int dim>\n  std::vector<std::string>\n  EulerEquations<dim>::Postprocessor::\n  get_names () const\n  {\n    std::vector<std::string> names;\n    for (unsigned int d=0; d<dim; ++d)\n      names.push_back (\"velocity\");\n    names.push_back (\"pressure\");\n\n    if (do_schlieren_plot == true)\n      names.push_back (\"schlieren_plot\");\n\n    return names;\n  }\n\n\n  template <int dim>\n  std::vector<DataComponentInterpretation::DataComponentInterpretation>\n  EulerEquations<dim>::Postprocessor::\n  get_data_component_interpretation () const\n  {\n    std::vector<DataComponentInterpretation::DataComponentInterpretation>\n    interpretation (dim,\n                    DataComponentInterpretation::component_is_part_of_vector);\n\n    interpretation.push_back (DataComponentInterpretation::\n                              component_is_scalar);\n\n    if (do_schlieren_plot == true)\n      interpretation.push_back (DataComponentInterpretation::\n                                component_is_scalar);\n\n    return interpretation;\n  }\n\n\n\n  template <int dim>\n  UpdateFlags\n  EulerEquations<dim>::Postprocessor::\n  get_needed_update_flags () const\n  {\n    if (do_schlieren_plot == true)\n      return update_values | update_gradients;\n    else\n      return update_values;\n  }\n\n\n  // @sect3{Run time parameter handling}\n\n  // Our next job is to define a few classes that will contain run-time\n  // parameters (for example solver tolerances, number of iterations,\n  // stabilization parameter, and the like). One could do this in the main\n  // class, but we separate it from that one to make the program more modular\n  // and easier to read: Everything that has to do with run-time parameters\n  // will be in the following namespace, whereas the program logic is in the\n  // main class.\n  //\n  // We will split the run-time parameters into a few separate structures,\n  // which we will all put into a namespace <code>Parameters</code>. Of these\n  // classes, there are a few that group the parameters for individual groups,\n  // such as for solvers, mesh refinement, or output. Each of these classes\n  // have functions <code>declare_parameters()</code> and\n  // <code>parse_parameters()</code> that declare parameter subsections and\n  // entries in a ParameterHandler object, and retrieve actual parameter\n  // values from such an object, respectively. These classes declare all their\n  // parameters in subsections of the ParameterHandler.\n  //\n  // The final class of the following namespace combines all the previous\n  // classes by deriving from them and taking care of a few more entries at\n  // the top level of the input file, as well as a few odd other entries in\n  // subsections that are too short to warrant a structure by themselves.\n  //\n  // It is worth pointing out one thing here: None of the classes below have a\n  // constructor that would initialize the various member variables. This\n  // isn't a problem, however, since we will read all variables declared in\n  // these classes from the input file (or indirectly: a ParameterHandler\n  // object will read it from there, and we will get the values from this\n  // object), and they will be initialized this way. In case a certain\n  // variable is not specified at all in the input file, this isn't a problem\n  // either: The ParameterHandler class will in this case simply take the\n  // default value that was specified when declaring an entry in the\n  // <code>declare_parameters()</code> functions of the classes below.\n  namespace Parameters\n  {\n\n    // @sect4{Parameters::Solver}\n    //\n    // The first of these classes deals with parameters for the linear inner\n    // solver. It offers parameters that indicate which solver to use (GMRES\n    // as a solver for general non-symmetric indefinite systems, or a sparse\n    // direct solver), the amount of output to be produced, as well as various\n    // parameters that tweak the thresholded incomplete LU decomposition\n    // (ILUT) that we use as a preconditioner for GMRES.\n    //\n    // In particular, the ILUT takes the following parameters:\n    // - ilut_fill: the number of extra entries to add when forming the ILU\n    //   decomposition\n    // - ilut_atol, ilut_rtol: When forming the preconditioner, for certain\n    //   problems bad conditioning (or just bad luck) can cause the\n    //   preconditioner to be very poorly conditioned.  Hence it can help to\n    //   add diagonal perturbations to the original matrix and form the\n    //   preconditioner for this slightly better matrix.  ATOL is an absolute\n    //   perturbation that is added to the diagonal before forming the prec,\n    //   and RTOL is a scaling factor $rtol \\geq 1$.\n    // - ilut_drop: The ILUT will drop any values that have magnitude less\n    //   than this value.  This is a way to manage the amount of memory used\n    //   by this preconditioner.\n    //\n    // The meaning of each parameter is also briefly described in the third\n    // argument of the ParameterHandler::declare_entry call in\n    // <code>declare_parameters()</code>.\n    struct Solver\n    {\n      enum SolverType { gmres, direct };\n      SolverType solver;\n\n      enum  OutputType { quiet, verbose };\n      OutputType output;\n\n      double linear_residual;\n      int max_iterations;\n\n      double ilut_fill;\n      double ilut_atol;\n      double ilut_rtol;\n      double ilut_drop;\n\n      static void declare_parameters (ParameterHandler &prm);\n      void parse_parameters (ParameterHandler &prm);\n    };\n\n\n\n    void Solver::declare_parameters (ParameterHandler &prm)\n    {\n      prm.enter_subsection(\"linear solver\");\n      {\n        prm.declare_entry(\"output\", \"quiet\",\n                          Patterns::Selection(\"quiet|verbose\"),\n                          \"State whether output from solver runs should be printed. \"\n                          \"Choices are <quiet|verbose>.\");\n        prm.declare_entry(\"method\", \"gmres\",\n                          Patterns::Selection(\"gmres|direct\"),\n                          \"The kind of solver for the linear system. \"\n                          \"Choices are <gmres|direct>.\");\n        prm.declare_entry(\"residual\", \"1e-10\",\n                          Patterns::Double(),\n                          \"Linear solver residual\");\n        prm.declare_entry(\"max iters\", \"300\",\n                          Patterns::Integer(),\n                          \"Maximum solver iterations\");\n        prm.declare_entry(\"ilut fill\", \"2\",\n                          Patterns::Double(),\n                          \"Ilut preconditioner fill\");\n        prm.declare_entry(\"ilut absolute tolerance\", \"1e-9\",\n                          Patterns::Double(),\n                          \"Ilut preconditioner tolerance\");\n        prm.declare_entry(\"ilut relative tolerance\", \"1.1\",\n                          Patterns::Double(),\n                          \"Ilut relative tolerance\");\n        prm.declare_entry(\"ilut drop tolerance\", \"1e-10\",\n                          Patterns::Double(),\n                          \"Ilut drop tolerance\");\n      }\n      prm.leave_subsection();\n    }\n\n\n\n\n    void Solver::parse_parameters (ParameterHandler &prm)\n    {\n      prm.enter_subsection(\"linear solver\");\n      {\n        const std::string op = prm.get(\"output\");\n        if (op == \"verbose\")\n          output = verbose;\n        if (op == \"quiet\")\n          output = quiet;\n\n        const std::string sv = prm.get(\"method\");\n        if (sv == \"direct\")\n          solver = direct;\n        else if (sv == \"gmres\")\n          solver = gmres;\n\n        linear_residual = prm.get_double(\"residual\");\n        max_iterations  = prm.get_integer(\"max iters\");\n        ilut_fill       = prm.get_double(\"ilut fill\");\n        ilut_atol       = prm.get_double(\"ilut absolute tolerance\");\n        ilut_rtol       = prm.get_double(\"ilut relative tolerance\");\n        ilut_drop       = prm.get_double(\"ilut drop tolerance\");\n      }\n      prm.leave_subsection();\n    }\n\n\n\n    // @sect4{Parameters::Refinement}\n    //\n    // Similarly, here are a few parameters that determine how the mesh is to\n    // be refined (and if it is to be refined at all). For what exactly the\n    // shock parameters do, see the mesh refinement functions further down.\n    struct Refinement\n    {\n      bool do_refine;\n      double shock_val;\n      double shock_levels;\n\n      static void declare_parameters (ParameterHandler &prm);\n      void parse_parameters (ParameterHandler &prm);\n    };\n\n\n\n    void Refinement::declare_parameters (ParameterHandler &prm)\n    {\n\n      prm.enter_subsection(\"refinement\");\n      {\n        prm.declare_entry(\"refinement\", \"true\",\n                          Patterns::Bool(),\n                          \"Whether to perform mesh refinement or not\");\n        prm.declare_entry(\"refinement fraction\", \"0.1\",\n                          Patterns::Double(),\n                          \"Fraction of high refinement\");\n        prm.declare_entry(\"unrefinement fraction\", \"0.1\",\n                          Patterns::Double(),\n                          \"Fraction of low unrefinement\");\n        prm.declare_entry(\"max elements\", \"1000000\",\n                          Patterns::Double(),\n                          \"maximum number of elements\");\n        prm.declare_entry(\"shock value\", \"4.0\",\n                          Patterns::Double(),\n                          \"value for shock indicator\");\n        prm.declare_entry(\"shock levels\", \"3.0\",\n                          Patterns::Double(),\n                          \"number of shock refinement levels\");\n      }\n      prm.leave_subsection();\n    }\n\n\n    void Refinement::parse_parameters (ParameterHandler &prm)\n    {\n      prm.enter_subsection(\"refinement\");\n      {\n        do_refine     = prm.get_bool (\"refinement\");\n        shock_val     = prm.get_double(\"shock value\");\n        shock_levels  = prm.get_double(\"shock levels\");\n      }\n      prm.leave_subsection();\n    }\n\n\n\n    // @sect4{Parameters::Flux}\n    //\n    // Next a section on flux modifications to make it more stable. In\n    // particular, two options are offered to stabilize the Lax-Friedrichs\n    // flux: either choose $\\mathbf{H}(\\mathbf{a},\\mathbf{b},\\mathbf{n}) =\n    // \\frac{1}{2}(\\mathbf{F}(\\mathbf{a})\\cdot \\mathbf{n} +\n    // \\mathbf{F}(\\mathbf{b})\\cdot \\mathbf{n} + \\alpha (\\mathbf{a} -\n    // \\mathbf{b}))$ where $\\alpha$ is either a fixed number specified in the\n    // input file, or where $\\alpha$ is a mesh dependent value. In the latter\n    // case, it is chosen as $\\frac{h}{2\\delta T}$ with $h$ the diameter of\n    // the face to which the flux is applied, and $\\delta T$ the current time\n    // step.\n    struct Flux\n    {\n      enum StabilizationKind { constant, mesh_dependent };\n      StabilizationKind stabilization_kind;\n\n      double stabilization_value;\n\n      static void declare_parameters (ParameterHandler &prm);\n      void parse_parameters (ParameterHandler &prm);\n    };\n\n\n    void Flux::declare_parameters (ParameterHandler &prm)\n    {\n      prm.enter_subsection(\"flux\");\n      {\n        prm.declare_entry(\"stab\", \"mesh\",\n                          Patterns::Selection(\"constant|mesh\"),\n                          \"Whether to use a constant stabilization parameter or \"\n                          \"a mesh-dependent one\");\n        prm.declare_entry(\"stab value\", \"1\",\n                          Patterns::Double(),\n                          \"alpha stabilization\");\n      }\n      prm.leave_subsection();\n    }\n\n\n    void Flux::parse_parameters (ParameterHandler &prm)\n    {\n      prm.enter_subsection(\"flux\");\n      {\n        const std::string stab = prm.get(\"stab\");\n        if (stab == \"constant\")\n          stabilization_kind = constant;\n        else if (stab == \"mesh\")\n          stabilization_kind = mesh_dependent;\n        else\n          AssertThrow (false, ExcNotImplemented());\n\n        stabilization_value = prm.get_double(\"stab value\");\n      }\n      prm.leave_subsection();\n    }\n\n\n\n    // @sect4{Parameters::Output}\n    //\n    // Then a section on output parameters. We offer to produce Schlieren\n    // plots (the squared gradient of the density, a tool to visualize shock\n    // fronts), and a time interval between graphical output in case we don't\n    // want an output file every time step.\n    struct Output\n    {\n      bool schlieren_plot;\n      double output_step;\n\n      static void declare_parameters (ParameterHandler &prm);\n      void parse_parameters (ParameterHandler &prm);\n    };\n\n\n\n    void Output::declare_parameters (ParameterHandler &prm)\n    {\n      prm.enter_subsection(\"output\");\n      {\n        prm.declare_entry(\"schlieren plot\", \"true\",\n                          Patterns::Bool (),\n                          \"Whether or not to produce schlieren plots\");\n        prm.declare_entry(\"step\", \"-1\",\n                          Patterns::Double(),\n                          \"Output once per this period\");\n      }\n      prm.leave_subsection();\n    }\n\n\n\n    void Output::parse_parameters (ParameterHandler &prm)\n    {\n      prm.enter_subsection(\"output\");\n      {\n        schlieren_plot = prm.get_bool(\"schlieren plot\");\n        output_step = prm.get_double(\"step\");\n      }\n      prm.leave_subsection();\n    }\n\n\n\n    // @sect4{Parameters::AllParameters}\n    //\n    // Finally the class that brings it all together. It declares a number of\n    // parameters itself, mostly ones at the top level of the parameter file\n    // as well as several in section too small to warrant their own\n    // classes. It also contains everything that is actually space dimension\n    // dependent, like initial or boundary conditions.\n    //\n    // Since this class is derived from all the ones above, the\n    // <code>declare_parameters()</code> and <code>parse_parameters()</code>\n    // functions call the respective functions of the base classes as well.\n    //\n    // Note that this class also handles the declaration of initial and\n    // boundary conditions specified in the input file. To this end, in both\n    // cases, there are entries like \"w_0 value\" which represent an expression\n    // in terms of $x,y,z$ that describe the initial or boundary condition as\n    // a formula that will later be parsed by the FunctionParser\n    // class. Similar expressions exist for \"w_1\", \"w_2\", etc, denoting the\n    // <code>dim+2</code> conserved variables of the Euler system. Similarly,\n    // we allow up to <code>max_n_boundaries</code> boundary indicators to be\n    // used in the input file, and each of these boundary indicators can be\n    // associated with an inflow, outflow, or pressure boundary condition,\n    // with inhomogenous boundary conditions being specified for each\n    // component and each boundary indicator separately.\n    //\n    // The data structure used to store the boundary indicators is a bit\n    // complicated. It is an array of <code>max_n_boundaries</code> elements\n    // indicating the range of boundary indicators that will be accepted. For\n    // each entry in this array, we store a pair of data in the\n    // <code>BoundaryCondition</code> structure: first, an array of size\n    // <code>n_components</code> that for each component of the solution\n    // vector indicates whether it is an inflow, outflow, or other kind of\n    // boundary, and second a FunctionParser object that describes all\n    // components of the solution vector for this boundary id at once.\n    //\n    // The <code>BoundaryCondition</code> structure requires a constructor\n    // since we need to tell the function parser object at construction time\n    // how many vector components it is to describe. This initialization can\n    // therefore not wait till we actually set the formulas the FunctionParser\n    // object represents later in\n    // <code>AllParameters::parse_parameters()</code>\n    //\n    // For the same reason of having to tell Function objects their vector\n    // size at construction time, we have to have a constructor of the\n    // <code>AllParameters</code> class that at least initializes the other\n    // FunctionParser object, i.e. the one describing initial conditions.\n    template <int dim>\n    struct AllParameters : public Solver,\n      public Refinement,\n      public Flux,\n      public Output\n    {\n      static const unsigned int max_n_boundaries = 10;\n\n      struct BoundaryConditions\n      {\n        typename EulerEquations<dim>::BoundaryKind\n        kind[EulerEquations<dim>::n_components];\n\n        FunctionParser<dim> values;\n\n        BoundaryConditions ();\n      };\n\n\n      AllParameters ();\n\n      double diffusion_power;\n\n      double time_step, final_time;\n      double theta;\n      bool is_stationary;\n\n      std::string mesh_filename;\n\n      FunctionParser<dim> initial_conditions;\n      BoundaryConditions  boundary_conditions[max_n_boundaries];\n\n      static void declare_parameters (ParameterHandler &prm);\n      void parse_parameters (ParameterHandler &prm);\n    };\n\n\n\n    template <int dim>\n    AllParameters<dim>::BoundaryConditions::BoundaryConditions ()\n      :\n      values (EulerEquations<dim>::n_components)\n    {}\n\n\n    template <int dim>\n    AllParameters<dim>::AllParameters ()\n      :\n      initial_conditions (EulerEquations<dim>::n_components)\n    {}\n\n\n    template <int dim>\n    void\n    AllParameters<dim>::declare_parameters (ParameterHandler &prm)\n    {\n      prm.declare_entry(\"mesh\", \"grid.inp\",\n                        Patterns::Anything(),\n                        \"intput file name\");\n\n      prm.declare_entry(\"diffusion power\", \"2.0\",\n                        Patterns::Double(),\n                        \"power of mesh size for diffusion\");\n\n      prm.enter_subsection(\"time stepping\");\n      {\n        prm.declare_entry(\"time step\", \"0.1\",\n                          Patterns::Double(0),\n                          \"simulation time step\");\n        prm.declare_entry(\"final time\", \"10.0\",\n                          Patterns::Double(0),\n                          \"simulation end time\");\n        prm.declare_entry(\"theta scheme value\", \"0.5\",\n                          Patterns::Double(0,1),\n                          \"value for theta that interpolated between explicit \"\n                          \"Euler (theta=0), Crank-Nicolson (theta=0.5), and \"\n                          \"implicit Euler (theta=1).\");\n      }\n      prm.leave_subsection();\n\n\n      for (unsigned int b=0; b<max_n_boundaries; ++b)\n        {\n          prm.enter_subsection(\"boundary_\" +\n                               Utilities::int_to_string(b));\n          {\n            prm.declare_entry(\"no penetration\", \"false\",\n                              Patterns::Bool(),\n                              \"whether the named boundary allows gas to \"\n                              \"penetrate or is a rigid wall\");\n\n            for (unsigned int di=0; di<EulerEquations<dim>::n_components; ++di)\n              {\n                prm.declare_entry(\"w_\" + Utilities::int_to_string(di),\n                                  \"outflow\",\n                                  Patterns::Selection(\"inflow|outflow|pressure\"),\n                                  \"<inflow|outflow|pressure>\");\n\n                prm.declare_entry(\"w_\" + Utilities::int_to_string(di) +\n                                  \" value\", \"0.0\",\n                                  Patterns::Anything(),\n                                  \"expression in x,y,z\");\n              }\n          }\n          prm.leave_subsection();\n        }\n\n      prm.enter_subsection(\"initial condition\");\n      {\n        for (unsigned int di=0; di<EulerEquations<dim>::n_components; ++di)\n          prm.declare_entry(\"w_\" + Utilities::int_to_string(di) + \" value\",\n                            \"0.0\",\n                            Patterns::Anything(),\n                            \"expression in x,y,z\");\n      }\n      prm.leave_subsection();\n\n      Parameters::Solver::declare_parameters (prm);\n      Parameters::Refinement::declare_parameters (prm);\n      Parameters::Flux::declare_parameters (prm);\n      Parameters::Output::declare_parameters (prm);\n    }\n\n\n    template <int dim>\n    void\n    AllParameters<dim>::parse_parameters (ParameterHandler &prm)\n    {\n      mesh_filename = prm.get(\"mesh\");\n      diffusion_power = prm.get_double(\"diffusion power\");\n\n      prm.enter_subsection(\"time stepping\");\n      {\n        time_step = prm.get_double(\"time step\");\n        if (time_step == 0)\n          {\n            is_stationary = true;\n            time_step = 1.0;\n            final_time = 1.0;\n          }\n        else\n          is_stationary = false;\n\n        final_time = prm.get_double(\"final time\");\n        theta = prm.get_double(\"theta scheme value\");\n      }\n      prm.leave_subsection();\n\n      for (unsigned int boundary_id=0; boundary_id<max_n_boundaries;\n           ++boundary_id)\n        {\n          prm.enter_subsection(\"boundary_\" +\n                               Utilities::int_to_string(boundary_id));\n          {\n            std::vector<std::string>\n            expressions(EulerEquations<dim>::n_components, \"0.0\");\n\n            const bool no_penetration = prm.get_bool(\"no penetration\");\n\n            for (unsigned int di=0; di<EulerEquations<dim>::n_components; ++di)\n              {\n                const std::string boundary_type\n                  = prm.get(\"w_\" + Utilities::int_to_string(di));\n\n                if ((di < dim) && (no_penetration == true))\n                  boundary_conditions[boundary_id].kind[di]\n                    = EulerEquations<dim>::no_penetration_boundary;\n                else if (boundary_type == \"inflow\")\n                  boundary_conditions[boundary_id].kind[di]\n                    = EulerEquations<dim>::inflow_boundary;\n                else if (boundary_type == \"pressure\")\n                  boundary_conditions[boundary_id].kind[di]\n                    = EulerEquations<dim>::pressure_boundary;\n                else if (boundary_type == \"outflow\")\n                  boundary_conditions[boundary_id].kind[di]\n                    = EulerEquations<dim>::outflow_boundary;\n                else\n                  AssertThrow (false, ExcNotImplemented());\n\n                expressions[di] = prm.get(\"w_\" + Utilities::int_to_string(di) +\n                                          \" value\");\n              }\n\n            boundary_conditions[boundary_id].values\n            .initialize (FunctionParser<dim>::default_variable_names(),\n                         expressions,\n                         std::map<std::string, double>());\n          }\n          prm.leave_subsection();\n        }\n\n      prm.enter_subsection(\"initial condition\");\n      {\n        std::vector<std::string> expressions (EulerEquations<dim>::n_components,\n                                              \"0.0\");\n        for (unsigned int di = 0; di < EulerEquations<dim>::n_components; di++)\n          expressions[di] = prm.get(\"w_\" + Utilities::int_to_string(di) +\n                                    \" value\");\n        initial_conditions.initialize (FunctionParser<dim>::default_variable_names(),\n                                       expressions,\n                                       std::map<std::string, double>());\n      }\n      prm.leave_subsection();\n\n      Parameters::Solver::parse_parameters (prm);\n      Parameters::Refinement::parse_parameters (prm);\n      Parameters::Flux::parse_parameters (prm);\n      Parameters::Output::parse_parameters (prm);\n    }\n  }\n\n\n\n\n  // @sect3{Conservation law class}\n\n  // Here finally comes the class that actually does something with all the\n  // Euler equation and parameter specifics we've defined above. The public\n  // interface is pretty much the same as always (the constructor now takes\n  // the name of a file from which to read parameters, which is passed on the\n  // command line). The private function interface is also pretty similar to\n  // the usual arrangement, with the <code>assemble_system</code> function\n  // split into three parts: one that contains the main loop over all cells\n  // and that then calls the other two for integrals over cells and faces,\n  // respectively.\n  template <int dim>\n  class ConservationLaw\n  {\n  public:\n    ConservationLaw (const char *input_filename);\n    void run ();\n\n  private:\n    void setup_system ();\n\n    void assemble_system ();\n    void assemble_cell_term (const FEValues<dim>             &fe_v,\n                             const std::vector<unsigned int> &dofs);\n    void assemble_face_term (const unsigned int               face_no,\n                             const FEFaceValuesBase<dim>     &fe_v,\n                             const FEFaceValuesBase<dim>     &fe_v_neighbor,\n                             const std::vector<unsigned int> &dofs,\n                             const std::vector<unsigned int> &dofs_neighbor,\n                             const bool                       external_face,\n                             const unsigned int               boundary_id,\n                             const double                     face_diameter);\n\n    std::pair<unsigned int, double> solve (Vector<double> &solution);\n\n    void compute_refinement_indicators (Vector<double> &indicator) const;\n    void refine_grid (const Vector<double> &indicator);\n\n    void output_results () const;\n\n\n\n    // The first few member variables are also rather standard. Note that we\n    // define a mapping object to be used throughout the program when\n    // assembling terms (we will hand it to every FEValues and FEFaceValues\n    // object); the mapping we use is just the standard $Q_1$ mapping --\n    // nothing fancy, in other words -- but declaring one here and using it\n    // throughout the program will make it simpler later on to change it if\n    // that should become necessary. This is, in fact, rather pertinent: it is\n    // known that for transsonic simulations with the Euler equations,\n    // computations do not converge even as $h\\rightarrow 0$ if the boundary\n    // approximation is not of sufficiently high order.\n    Triangulation<dim>   triangulation;\n    const MappingQ1<dim> mapping;\n\n    const FESystem<dim>  fe;\n    DoFHandler<dim>      dof_handler;\n\n    const QGauss<dim>    quadrature;\n    const QGauss<dim-1>  face_quadrature;\n\n    // Next come a number of data vectors that correspond to the solution of\n    // the previous time step (<code>old_solution</code>), the best guess of\n    // the current solution (<code>current_solution</code>; we say\n    // <i>guess</i> because the Newton iteration to compute it may not have\n    // converged yet, whereas <code>old_solution</code> refers to the fully\n    // converged final result of the previous time step), and a predictor for\n    // the solution at the next time step, computed by extrapolating the\n    // current and previous solution one time step into the future:\n    Vector<double>       old_solution;\n    Vector<double>       current_solution;\n    Vector<double>       predictor;\n\n    Vector<double>       right_hand_side;\n\n    // This final set of member variables (except for the object holding all\n    // run-time parameters at the very bottom and a screen output stream that\n    // only prints something if verbose output has been requested) deals with\n    // the inteface we have in this program to the Trilinos library that\n    // provides us with linear solvers. Similarly to including PETSc matrices\n    // in step-17, step-18, and step-19, all we need to do is to create a\n    // Trilinos sparse matrix instead of the standard deal.II class. The\n    // system matrix is used for the Jacobian in each Newton step. Since we do\n    // not intend to run this program in parallel (which wouldn't be too hard\n    // with Trilinos data structures, though), we don't have to think about\n    // anything else like distributing the degrees of freedom.\n    TrilinosWrappers::SparseMatrix system_matrix;\n\n    Parameters::AllParameters<dim>  parameters;\n    ConditionalOStream              verbose_cout;\n  };\n\n\n  // @sect4{ConservationLaw::ConservationLaw}\n  //\n  // There is nothing much to say about the constructor. Essentially, it reads\n  // the input file and fills the parameter object with the parsed values:\n  template <int dim>\n  ConservationLaw<dim>::ConservationLaw (const char *input_filename)\n    :\n    mapping (),\n    fe (FE_Q<dim>(1), EulerEquations<dim>::n_components),\n    dof_handler (triangulation),\n    quadrature (2),\n    face_quadrature (2),\n    verbose_cout (std::cout, false)\n  {\n    ParameterHandler prm;\n    Parameters::AllParameters<dim>::declare_parameters (prm);\n\n    prm.read_input (input_filename);\n    parameters.parse_parameters (prm);\n\n    verbose_cout.set_condition (parameters.output == Parameters::Solver::verbose);\n  }\n\n\n\n  // @sect4{ConservationLaw::setup_system}\n  //\n  // The following (easy) function is called each time the mesh is\n  // changed. All it does is to resize the Trilinos matrix according to a\n  // sparsity pattern that we generate as in all the previous tutorial\n  // programs.\n  template <int dim>\n  void ConservationLaw<dim>::setup_system ()\n  {\n    CompressedSparsityPattern sparsity_pattern (dof_handler.n_dofs(),\n                                                dof_handler.n_dofs());\n    DoFTools::make_sparsity_pattern (dof_handler, sparsity_pattern);\n\n    system_matrix.reinit (sparsity_pattern);\n  }\n\n\n  // @sect4{ConservationLaw::assemble_system}\n  //\n  // This and the following two functions are the meat of this program: They\n  // assemble the linear system that results from applying Newton's method to\n  // the nonlinear system of conservation equations.\n  //\n  // This first function puts all of the assembly pieces together in a routine\n  // that dispatches the correct piece for each cell/face.  The actual\n  // implementation of the assembly on these objects is done in the following\n  // functions.\n  //\n  // At the top of the function we do the usual housekeeping: allocate\n  // FEValues, FEFaceValues, and FESubfaceValues objects necessary to do the\n  // integrations on cells, faces, and subfaces (in case of adjoining cells on\n  // different refinement levels). Note that we don't need all information\n  // (like values, gradients, or real locations of quadrature points) for all\n  // of these objects, so we only let the FEValues classes whatever is\n  // actually necessary by specifying the minimal set of UpdateFlags. For\n  // example, when using a FEFaceValues object for the neighboring cell we\n  // only need the shape values: Given a specific face, the quadrature points\n  // and <code>JxW</code> values are the same as for the current cells, and\n  // the normal vectors are known to be the negative of the normal vectors of\n  // the current cell.\n  template <int dim>\n  void ConservationLaw<dim>::assemble_system ()\n  {\n    const unsigned int dofs_per_cell = dof_handler.get_fe().dofs_per_cell;\n\n    std::vector<unsigned int> dof_indices (dofs_per_cell);\n    std::vector<unsigned int> dof_indices_neighbor (dofs_per_cell);\n\n    const UpdateFlags update_flags               = update_values\n                                                   | update_gradients\n                                                   | update_q_points\n                                                   | update_JxW_values,\n                                                   face_update_flags          = update_values\n                                                       | update_q_points\n                                                       | update_JxW_values\n                                                       | update_normal_vectors,\n                                                       neighbor_face_update_flags = update_values;\n\n    FEValues<dim>        fe_v                  (mapping, fe, quadrature,\n                                                update_flags);\n    FEFaceValues<dim>    fe_v_face             (mapping, fe, face_quadrature,\n                                                face_update_flags);\n    FESubfaceValues<dim> fe_v_subface          (mapping, fe, face_quadrature,\n                                                face_update_flags);\n    FEFaceValues<dim>    fe_v_face_neighbor    (mapping, fe, face_quadrature,\n                                                neighbor_face_update_flags);\n    FESubfaceValues<dim> fe_v_subface_neighbor (mapping, fe, face_quadrature,\n                                                neighbor_face_update_flags);\n\n    // Then loop over all cells, initialize the FEValues object for the\n    // current cell and call the function that assembles the problem on this\n    // cell.\n    typename DoFHandler<dim>::active_cell_iterator\n    cell = dof_handler.begin_active(),\n    endc = dof_handler.end();\n    for (; cell!=endc; ++cell)\n      {\n        fe_v.reinit (cell);\n        cell->get_dof_indices (dof_indices);\n\n        assemble_cell_term(fe_v, dof_indices);\n\n        // Then loop over all the faces of this cell.  If a face is part of\n        // the external boundary, then assemble boundary conditions there (the\n        // fifth argument to <code>assemble_face_terms</code> indicates\n        // whether we are working on an external or internal face; if it is an\n        // external face, the fourth argument denoting the degrees of freedom\n        // indices of the neighbor is ignored, so we pass an empty vector):\n        for (unsigned int face_no=0; face_no<GeometryInfo<dim>::faces_per_cell;\n             ++face_no)\n          if (cell->at_boundary(face_no))\n            {\n              fe_v_face.reinit (cell, face_no);\n              assemble_face_term (face_no, fe_v_face,\n                                  fe_v_face,\n                                  dof_indices,\n                                  std::vector<unsigned int>(),\n                                  true,\n                                  cell->face(face_no)->boundary_indicator(),\n                                  cell->face(face_no)->diameter());\n            }\n\n        // The alternative is that we are dealing with an internal face. There\n        // are two cases that we need to distinguish: that this is a normal\n        // face between two cells at the same refinement level, and that it is\n        // a face between two cells of the different refinement levels.\n        //\n        // In the first case, there is nothing we need to do: we are using a\n        // continuous finite element, and face terms do not appear in the\n        // bilinear form in this case. The second case usually does not lead\n        // to face terms either if we enforce hanging node constraints\n        // strongly (as in all previous tutorial programs so far whenever we\n        // used continuous finite elements -- this enforcement is done by the\n        // ConstraintMatrix class together with\n        // DoFTools::make_hanging_node_constraints). In the current program,\n        // however, we opt to enforce continuity weakly at faces between cells\n        // of different refinement level, for two reasons: (i) because we can,\n        // and more importantly (ii) because we would have to thread the\n        // automatic differentiation we use to compute the elements of the\n        // Newton matrix from the residual through the operations of the\n        // ConstraintMatrix class. This would be possible, but is not trivial,\n        // and so we choose this alternative approach.\n        //\n        // What needs to be decided is which side of an interface between two\n        // cells of different refinement level we are sitting on.\n        //\n        // Let's take the case where the neighbor is more refined first. We\n        // then have to loop over the children of the face of the current cell\n        // and integrate on each of them. We sprinkle a couple of assertions\n        // into the code to ensure that our reasoning trying to figure out\n        // which of the neighbor's children's faces coincides with a given\n        // subface of the current cell's faces is correct -- a bit of\n        // defensive programming never hurts.\n        //\n        // We then call the function that integrates over faces; since this is\n        // an internal face, the fifth argument is false, and the sixth one is\n        // ignored so we pass an invalid value again:\n          else\n            {\n              if (cell->neighbor(face_no)->has_children())\n                {\n                  const unsigned int neighbor2=\n                    cell->neighbor_of_neighbor(face_no);\n\n                  for (unsigned int subface_no=0;\n                       subface_no < cell->face(face_no)->n_children();\n                       ++subface_no)\n                    {\n                      const typename DoFHandler<dim>::active_cell_iterator\n                      neighbor_child\n                        = cell->neighbor_child_on_subface (face_no, subface_no);\n\n                      Assert (neighbor_child->face(neighbor2) ==\n                              cell->face(face_no)->child(subface_no),\n                              ExcInternalError());\n                      Assert (neighbor_child->has_children() == false,\n                              ExcInternalError());\n\n                      fe_v_subface.reinit (cell, face_no, subface_no);\n                      fe_v_face_neighbor.reinit (neighbor_child, neighbor2);\n\n                      neighbor_child->get_dof_indices (dof_indices_neighbor);\n\n                      assemble_face_term (face_no, fe_v_subface,\n                                          fe_v_face_neighbor,\n                                          dof_indices,\n                                          dof_indices_neighbor,\n                                          false,\n                                          numbers::invalid_unsigned_int,\n                                          neighbor_child->face(neighbor2)->diameter());\n                    }\n                }\n\n              // The other possibility we have to care for is if the neighbor\n              // is coarser than the current cell (in particular, because of\n              // the usual restriction of only one hanging node per face, the\n              // neighbor must be exactly one level coarser than the current\n              // cell, something that we check with an assertion). Again, we\n              // then integrate over this interface:\n              else if (cell->neighbor(face_no)->level() != cell->level())\n                {\n                  const typename DoFHandler<dim>::cell_iterator\n                  neighbor = cell->neighbor(face_no);\n                  Assert(neighbor->level() == cell->level()-1,\n                         ExcInternalError());\n\n                  neighbor->get_dof_indices (dof_indices_neighbor);\n\n                  const std::pair<unsigned int, unsigned int>\n                  faceno_subfaceno = cell->neighbor_of_coarser_neighbor(face_no);\n                  const unsigned int neighbor_face_no    = faceno_subfaceno.first,\n                                     neighbor_subface_no = faceno_subfaceno.second;\n\n                  Assert (neighbor->neighbor_child_on_subface (neighbor_face_no,\n                                                               neighbor_subface_no)\n                          == cell,\n                          ExcInternalError());\n\n                  fe_v_face.reinit (cell, face_no);\n                  fe_v_subface_neighbor.reinit (neighbor,\n                                                neighbor_face_no,\n                                                neighbor_subface_no);\n\n                  assemble_face_term (face_no, fe_v_face,\n                                      fe_v_subface_neighbor,\n                                      dof_indices,\n                                      dof_indices_neighbor,\n                                      false,\n                                      numbers::invalid_unsigned_int,\n                                      cell->face(face_no)->diameter());\n                }\n            }\n      }\n\n    // After all this assembling, notify the Trilinos matrix object that the\n    // matrix is done:\n    system_matrix.compress(VectorOperation::add);\n  }\n\n\n  // @sect4{ConservationLaw::assemble_cell_term}\n  //\n  // This function assembles the cell term by computing the cell part of the\n  // residual, adding its negative to the right hand side vector, and adding\n  // its derivative with respect to the local variables to the Jacobian\n  // (i.e. the Newton matrix). Recall that the cell contributions to the\n  // residual read $F_i = \\left(\\frac{\\mathbf{w}_{n+1} - \\mathbf{w}_n}{\\delta\n  // t},\\mathbf{z}_i\\right)_K - \\left(\\mathbf{F}(\\tilde{\\mathbf{w}}),\n  // \\nabla\\mathbf{z}_i\\right)_K + h^{\\eta}(\\nabla \\mathbf{w} , \\nabla\n  // \\mathbf{z}_i)_K - (\\mathbf{G}(\\tilde{\\mathbf w}), \\mathbf{z}_i)_K$ where\n  // $\\tilde{\\mathbf w}$ is represented by the variable <code>W_theta</code>,\n  // $\\mathbf{z}_i$ is the $i$th test function, and the scalar product\n  // $\\left(\\mathbf{F}(\\tilde{\\mathbf{w}}), \\nabla\\mathbf{z}\\right)_K$ is\n  // understood as $\\int_K \\sum_{c=1}^{\\text{n\\_components}}\n  // \\sum_{d=1}^{\\text{dim}} \\mathbf{F}(\\tilde{\\mathbf{w}})_{cd}\n  // \\frac{\\partial z_c}{x_d}$.\n  //\n  // At the top of this function, we do the usual housekeeping in terms of\n  // allocating some local variables that we will need later. In particular,\n  // we will allocate variables that will hold the values of the current\n  // solution $W_{n+1}^k$ after the $k$th Newton iteration (variable\n  // <code>W</code>), the previous time step's solution $W_{n}$ (variable\n  // <code>W_old</code>), as well as the linear combination $\\theta W_{n+1}^k\n  // + (1-\\theta)W_n$ that results from choosing different time stepping\n  // schemes (variable <code>W_theta</code>).\n  //\n  // In addition to these, we need the gradients of the current variables.  It\n  // is a bit of a shame that we have to compute these; we almost don't.  The\n  // nice thing about a simple conservation law is that the flux doesn't\n  // generally involve any gradients.  We do need these, however, for the\n  // diffusion stabilization.\n  //\n  // The actual format in which we store these variables requires some\n  // explanation. First, we need values at each quadrature point for each of\n  // the <code>EulerEquations::n_components</code> components of the solution\n  // vector. This makes for a two-dimensional table for which we use deal.II's\n  // Table class (this is more efficient than\n  // <code>std::vector@<std::vector@<T@> @></code> because it only needs to\n  // allocate memory once, rather than once for each element of the outer\n  // vector). Similarly, the gradient is a three-dimensional table, which the\n  // Table class also supports.\n  //\n  // Secondly, we want to use automatic differentiation. To this end, we use\n  // the Sacado::Fad::DFad template for everything that is a computed from the\n  // variables with respect to which we would like to compute\n  // derivatives. This includes the current solution and gradient at the\n  // quadrature points (which are linear combinations of the degrees of\n  // freedom) as well as everything that is computed from them such as the\n  // residual, but not the previous time step's solution. These variables are\n  // all found in the first part of the function, along with a variable that\n  // we will use to store the derivatives of a single component of the\n  // residual:\n  template <int dim>\n  void\n  ConservationLaw<dim>::\n  assemble_cell_term (const FEValues<dim>             &fe_v,\n                      const std::vector<unsigned int> &dof_indices)\n  {\n    const unsigned int dofs_per_cell = fe_v.dofs_per_cell;\n    const unsigned int n_q_points    = fe_v.n_quadrature_points;\n\n    Table<2,Sacado::Fad::DFad<double> >\n    W (n_q_points, EulerEquations<dim>::n_components);\n\n    Table<2,double>\n    W_old (n_q_points, EulerEquations<dim>::n_components);\n\n    Table<2,Sacado::Fad::DFad<double> >\n    W_theta (n_q_points, EulerEquations<dim>::n_components);\n\n    Table<3,Sacado::Fad::DFad<double> >\n    grad_W (n_q_points, EulerEquations<dim>::n_components, dim);\n\n    std::vector<double> residual_derivatives (dofs_per_cell);\n\n    // Next, we have to define the independent variables that we will try to\n    // determine by solving a Newton step. These independent variables are the\n    // values of the local degrees of freedom which we extract here:\n    std::vector<Sacado::Fad::DFad<double> > independent_local_dof_values(dofs_per_cell);\n    for (unsigned int i=0; i<dofs_per_cell; ++i)\n      independent_local_dof_values[i] = current_solution(dof_indices[i]);\n\n    // The next step incorporates all the magic: we declare a subset of the\n    // autodifferentiation variables as independent degrees of freedom,\n    // whereas all the other ones remain dependent functions. These are\n    // precisely the local degrees of freedom just extracted. All calculations\n    // that reference them (either directly or indirectly) will accumulate\n    // sensitivies with respect to these variables.\n    //\n    // In order to mark the variables as independent, the following does the\n    // trick, marking <code>independent_local_dof_values[i]</code> as the\n    // $i$th independent variable out of a total of\n    // <code>dofs_per_cell</code>:\n    for (unsigned int i=0; i<dofs_per_cell; ++i)\n      independent_local_dof_values[i].diff (i, dofs_per_cell);\n\n    // After all these declarations, let us actually compute something. First,\n    // the values of <code>W</code>, <code>W_old</code>, <code>W_theta</code>,\n    // and <code>grad_W</code>, which we can compute from the local DoF values\n    // by using the formula $W(x_q)=\\sum_i \\mathbf W_i \\Phi_i(x_q)$, where\n    // $\\mathbf W_i$ is the $i$th entry of the (local part of the) solution\n    // vector, and $\\Phi_i(x_q)$ the value of the $i$th vector-valued shape\n    // function evaluated at quadrature point $x_q$. The gradient can be\n    // computed in a similar way.\n    //\n    // Ideally, we could compute this information using a call into something\n    // like FEValues::get_function_values and FEValues::get_function_grads,\n    // but since (i) we would have to extend the FEValues class for this, and\n    // (ii) we don't want to make the entire <code>old_solution</code> vector\n    // fad types, only the local cell variables, we explicitly code the loop\n    // above. Before this, we add another loop that initializes all the fad\n    // variables to zero:\n    for (unsigned int q=0; q<n_q_points; ++q)\n      for (unsigned int c=0; c<EulerEquations<dim>::n_components; ++c)\n        {\n          W[q][c]       = 0;\n          W_old[q][c]   = 0;\n          W_theta[q][c] = 0;\n          for (unsigned int d=0; d<dim; ++d)\n            grad_W[q][c][d] = 0;\n        }\n\n    for (unsigned int q=0; q<n_q_points; ++q)\n      for (unsigned int i=0; i<dofs_per_cell; ++i)\n        {\n          const unsigned int c = fe_v.get_fe().system_to_component_index(i).first;\n\n          W[q][c] += independent_local_dof_values[i] *\n                     fe_v.shape_value_component(i, q, c);\n          W_old[q][c] += old_solution(dof_indices[i]) *\n                         fe_v.shape_value_component(i, q, c);\n          W_theta[q][c] += (parameters.theta *\n                            independent_local_dof_values[i]\n                            +\n                            (1-parameters.theta) *\n                            old_solution(dof_indices[i])) *\n                           fe_v.shape_value_component(i, q, c);\n\n          for (unsigned int d = 0; d < dim; d++)\n            grad_W[q][c][d] += independent_local_dof_values[i] *\n                               fe_v.shape_grad_component(i, q, c)[d];\n        }\n\n\n    // Next, in order to compute the cell contributions, we need to evaluate\n    // $F(\\tilde{\\mathbf w})$ and $G(\\tilde{\\mathbf w})$ at all quadrature\n    // points. To store these, we also need to allocate a bit of memory. Note\n    // that we compute the flux matrices and right hand sides in terms of\n    // autodifferentiation variables, so that the Jacobian contributions can\n    // later easily be computed from it:\n    typedef Sacado::Fad::DFad<double> FluxMatrix[EulerEquations<dim>::n_components][dim];\n    FluxMatrix *flux = new FluxMatrix[n_q_points];\n\n    typedef Sacado::Fad::DFad<double> ForcingVector[EulerEquations<dim>::n_components];\n    ForcingVector *forcing = new ForcingVector[n_q_points];\n\n    for (unsigned int q=0; q<n_q_points; ++q)\n      {\n        EulerEquations<dim>::compute_flux_matrix (W_theta[q], flux[q]);\n        EulerEquations<dim>::compute_forcing_vector (W_theta[q], forcing[q]);\n      }\n\n\n    // We now have all of the pieces in place, so perform the assembly.  We\n    // have an outer loop through the components of the system, and an inner\n    // loop over the quadrature points, where we accumulate contributions to\n    // the $i$th residual $F_i$. The general formula for this residual is\n    // given in the introduction and at the top of this function. We can,\n    // however, simplify it a bit taking into account that the $i$th\n    // (vector-valued) test function $\\mathbf{z}_i$ has in reality only a\n    // single nonzero component (more on this topic can be found in the @ref\n    // vector_valued module). It will be represented by the variable\n    // <code>component_i</code> below. With this, the residual term can be\n    // re-written as $F_i = \\left(\\frac{(\\mathbf{w}_{n+1} -\n    // \\mathbf{w}_n)_{\\text{component\\_i}}}{\\delta\n    // t},(\\mathbf{z}_i)_{\\text{component\\_i}}\\right)_K$ $-\n    // \\sum_{d=1}^{\\text{dim}} \\left(\\mathbf{F}\n    // (\\tilde{\\mathbf{w}})_{\\text{component\\_i},d},\n    // \\frac{\\partial(\\mathbf{z}_i)_{\\text{component\\_i}}} {\\partial\n    // x_d}\\right)_K$ $+ \\sum_{d=1}^{\\text{dim}} h^{\\eta} \\left(\\frac{\\partial\n    // \\mathbf{w}_{\\text{component\\_i}}}{\\partial x_d} , \\frac{\\partial\n    // (\\mathbf{z}_i)_{\\text{component\\_i}}}{\\partial x_d} \\right)_K$\n    // $-(\\mathbf{G}(\\tilde{\\mathbf{w}} )_{\\text{component\\_i}},\n    // (\\mathbf{z}_i)_{\\text{component\\_i}})_K$, where integrals are\n    // understood to be evaluated through summation over quadrature points.\n    //\n    // We initialy sum all contributions of the residual in the positive\n    // sense, so that we don't need to negative the Jacobian entries.  Then,\n    // when we sum into the <code>right_hand_side</code> vector, we negate\n    // this residual.\n    for (unsigned int i=0; i<fe_v.dofs_per_cell; ++i)\n      {\n        Sacado::Fad::DFad<double> F_i = 0;\n\n        const unsigned int\n        component_i = fe_v.get_fe().system_to_component_index(i).first;\n\n        // The residual for each row (i) will be accumulating into this fad\n        // variable.  At the end of the assembly for this row, we will query\n        // for the sensitivities to this variable and add them into the\n        // Jacobian.\n\n        for (unsigned int point=0; point<fe_v.n_quadrature_points; ++point)\n          {\n            if (parameters.is_stationary == false)\n              F_i += 1.0 / parameters.time_step *\n                     (W[point][component_i] - W_old[point][component_i]) *\n                     fe_v.shape_value_component(i, point, component_i) *\n                     fe_v.JxW(point);\n\n            for (unsigned int d=0; d<dim; d++)\n              F_i -= flux[point][component_i][d] *\n                     fe_v.shape_grad_component(i, point, component_i)[d] *\n                     fe_v.JxW(point);\n\n            for (unsigned int d=0; d<dim; d++)\n              F_i += 1.0*std::pow(fe_v.get_cell()->diameter(),\n                                  parameters.diffusion_power) *\n                     grad_W[point][component_i][d] *\n                     fe_v.shape_grad_component(i, point, component_i)[d] *\n                     fe_v.JxW(point);\n\n            F_i -= forcing[point][component_i] *\n                   fe_v.shape_value_component(i, point, component_i) *\n                   fe_v.JxW(point);\n          }\n\n        // At the end of the loop, we have to add the sensitivities to the\n        // matrix and subtract the residual from the right hand side. Trilinos\n        // FAD data type gives us access to the derivatives using\n        // <code>F_i.fastAccessDx(k)</code>, so we store the data in a\n        // temporary array. This information about the whole row of local dofs\n        // is then added to the Trilinos matrix at once (which supports the\n        // data types we have chosen).\n        for (unsigned int k=0; k<dofs_per_cell; ++k)\n          residual_derivatives[k] = F_i.fastAccessDx(k);\n        system_matrix.add(dof_indices[i], dof_indices, residual_derivatives);\n        right_hand_side(dof_indices[i]) -= F_i.val();\n      }\n\n    delete[] forcing;\n    delete[] flux;\n  }\n\n\n  // @sect4{ConservationLaw::assemble_face_term}\n  //\n  // Here, we do essentially the same as in the previous function. t the top,\n  // we introduce the independent variables. Because the current function is\n  // also used if we are working on an internal face between two cells, the\n  // independent variables are not only the degrees of freedom on the current\n  // cell but in the case of an interior face also the ones on the neighbor.\n  template <int dim>\n  void\n  ConservationLaw<dim>::assemble_face_term(const unsigned int           face_no,\n                                           const FEFaceValuesBase<dim> &fe_v,\n                                           const FEFaceValuesBase<dim> &fe_v_neighbor,\n                                           const std::vector<unsigned int>   &dof_indices,\n                                           const std::vector<unsigned int>   &dof_indices_neighbor,\n                                           const bool                   external_face,\n                                           const unsigned int           boundary_id,\n                                           const double                 face_diameter)\n  {\n    const unsigned int n_q_points = fe_v.n_quadrature_points;\n    const unsigned int dofs_per_cell = fe_v.dofs_per_cell;\n\n    std::vector<Sacado::Fad::DFad<double> >\n    independent_local_dof_values (dofs_per_cell),\n                                 independent_neighbor_dof_values (external_face == false ?\n                                     dofs_per_cell :\n                                     0);\n\n    const unsigned int n_independent_variables = (external_face == false ?\n                                                  2 * dofs_per_cell :\n                                                  dofs_per_cell);\n\n    for (unsigned int i = 0; i < dofs_per_cell; i++)\n      {\n        independent_local_dof_values[i] = current_solution(dof_indices[i]);\n        independent_local_dof_values[i].diff(i, n_independent_variables);\n      }\n\n    if (external_face == false)\n      for (unsigned int i = 0; i < dofs_per_cell; i++)\n        {\n          independent_neighbor_dof_values[i]\n            = current_solution(dof_indices_neighbor[i]);\n          independent_neighbor_dof_values[i]\n          .diff(i+dofs_per_cell, n_independent_variables);\n        }\n\n\n    // Next, we need to define the values of the conservative variables\n    // $\\tilde {\\mathbf W}$ on this side of the face ($\\tilde {\\mathbf W}^+$)\n    // and on the opposite side ($\\tilde {\\mathbf W}^-$). The former can be\n    // computed in exactly the same way as in the previous function, but note\n    // that the <code>fe_v</code> variable now is of type FEFaceValues or\n    // FESubfaceValues:\n    Table<2,Sacado::Fad::DFad<double> >\n    Wplus (n_q_points, EulerEquations<dim>::n_components),\n          Wminus (n_q_points, EulerEquations<dim>::n_components);\n\n    for (unsigned int q=0; q<n_q_points; ++q)\n      for (unsigned int i=0; i<dofs_per_cell; ++i)\n        {\n          const unsigned int component_i = fe_v.get_fe().system_to_component_index(i).first;\n          Wplus[q][component_i] += (parameters.theta *\n                                    independent_local_dof_values[i]\n                                    +\n                                    (1.0-parameters.theta) *\n                                    old_solution(dof_indices[i])) *\n                                   fe_v.shape_value_component(i, q, component_i);\n        }\n\n    // Computing $\\tilde {\\mathbf W}^-$ is a bit more complicated. If this is\n    // an internal face, we can compute it as above by simply using the\n    // independent variables from the neighbor:\n    if (external_face == false)\n      {\n        for (unsigned int q=0; q<n_q_points; ++q)\n          for (unsigned int i=0; i<dofs_per_cell; ++i)\n            {\n              const unsigned int component_i = fe_v_neighbor.get_fe().\n                                               system_to_component_index(i).first;\n              Wminus[q][component_i] += (parameters.theta *\n                                         independent_neighbor_dof_values[i]\n                                         +\n                                         (1.0-parameters.theta) *\n                                         old_solution(dof_indices_neighbor[i]))*\n                                        fe_v_neighbor.shape_value_component(i, q, component_i);\n            }\n      }\n    // On the other hand, if this is an external boundary face, then the\n    // values of $W^-$ will be either functions of $W^+$, or they will be\n    // prescribed, depending on the kind of boundary condition imposed here.\n    //\n    // To start the evaluation, let us ensure that the boundary id specified\n    // for this boundary is one for which we actually have data in the\n    // parameters object. Next, we evaluate the function object for the\n    // inhomogeneity.  This is a bit tricky: a given boundary might have both\n    // prescribed and implicit values.  If a particular component is not\n    // prescribed, the values evaluate to zero and are ignored below.\n    //\n    // The rest is done by a function that actually knows the specifics of\n    // Euler equation boundary conditions. Note that since we are using fad\n    // variables here, sensitivities will be updated appropriately, a process\n    // that would otherwise be tremendously complicated.\n    else\n      {\n        Assert (boundary_id < Parameters::AllParameters<dim>::max_n_boundaries,\n                ExcIndexRange (boundary_id, 0,\n                               Parameters::AllParameters<dim>::max_n_boundaries));\n\n        std::vector<Vector<double> >\n        boundary_values(n_q_points, Vector<double>(EulerEquations<dim>::n_components));\n        parameters.boundary_conditions[boundary_id]\n        .values.vector_value_list(fe_v.get_quadrature_points(),\n                                  boundary_values);\n\n        for (unsigned int q = 0; q < n_q_points; q++)\n          EulerEquations<dim>::compute_Wminus (parameters.boundary_conditions[boundary_id].kind,\n                                               fe_v.normal_vector(q),\n                                               Wplus[q],\n                                               boundary_values[q],\n                                               Wminus[q]);\n      }\n\n\n    // Now that we have $\\mathbf w^+$ and $\\mathbf w^-$, we can go about\n    // computing the numerical flux function $\\mathbf H(\\mathbf w^+,\\mathbf\n    // w^-, \\mathbf n)$ for each quadrature point. Before calling the function\n    // that does so, we also need to determine the Lax-Friedrich's stability\n    // parameter:\n    typedef Sacado::Fad::DFad<double> NormalFlux[EulerEquations<dim>::n_components];\n    NormalFlux *normal_fluxes = new NormalFlux[n_q_points];\n\n    double alpha;\n\n    switch (parameters.stabilization_kind)\n      {\n      case Parameters::Flux::constant:\n        alpha = parameters.stabilization_value;\n        break;\n      case Parameters::Flux::mesh_dependent:\n        alpha = face_diameter/(2.0*parameters.time_step);\n        break;\n      default:\n        Assert (false, ExcNotImplemented());\n        alpha = 1;\n      }\n\n    for (unsigned int q=0; q<n_q_points; ++q)\n      EulerEquations<dim>::numerical_normal_flux(fe_v.normal_vector(q),\n                                                 Wplus[q], Wminus[q], alpha,\n                                                 normal_fluxes[q]);\n\n    // Now assemble the face term in exactly the same way as for the cell\n    // contributions in the previous function. The only difference is that if\n    // this is an internal face, we also have to take into account the\n    // sensitivies of the residual contributions to the degrees of freedom on\n    // the neighboring cell:\n    std::vector<double> residual_derivatives (dofs_per_cell);\n    for (unsigned int i=0; i<fe_v.dofs_per_cell; ++i)\n      if (fe_v.get_fe().has_support_on_face(i, face_no) == true)\n        {\n          Sacado::Fad::DFad<double> F_i = 0;\n\n          for (unsigned int point=0; point<n_q_points; ++point)\n            {\n              const unsigned int\n              component_i = fe_v.get_fe().system_to_component_index(i).first;\n\n              F_i += normal_fluxes[point][component_i] *\n                     fe_v.shape_value_component(i, point, component_i) *\n                     fe_v.JxW(point);\n            }\n\n          for (unsigned int k=0; k<dofs_per_cell; ++k)\n            residual_derivatives[k] = F_i.fastAccessDx(k);\n          system_matrix.add(dof_indices[i], dof_indices, residual_derivatives);\n\n          if (external_face == false)\n            {\n              for (unsigned int k=0; k<dofs_per_cell; ++k)\n                residual_derivatives[k] = F_i.fastAccessDx(dofs_per_cell+k);\n              system_matrix.add (dof_indices[i], dof_indices_neighbor,\n                                 residual_derivatives);\n            }\n\n          right_hand_side(dof_indices[i]) -= F_i.val();\n        }\n\n    delete[] normal_fluxes;\n  }\n\n\n  // @sect4{ConservationLaw::solve}\n  //\n  // Here, we actually solve the linear system, using either of Trilinos'\n  // Aztec or Amesos linear solvers. The result of the computation will be\n  // written into the argument vector passed to this function. The result is a\n  // pair of number of iterations and the final linear residual.\n\n  template <int dim>\n  std::pair<unsigned int, double>\n  ConservationLaw<dim>::solve (Vector<double> &newton_update)\n  {\n    switch (parameters.solver)\n      {\n        // If the parameter file specified that a direct solver shall be used,\n        // then we'll get here. The process is straightforward, since deal.II\n        // provides a wrapper class to the Amesos direct solver within\n        // Trilinos. All we have to do is to create a solver control object\n        // (which is just a dummy object here, since we won't perform any\n        // iterations), and then create the direct solver object. When\n        // actually doing the solve, note that we don't pass a\n        // preconditioner. That wouldn't make much sense for a direct solver\n        // anyway.  At the end we return the solver control statistics &mdash;\n        // which will tell that no iterations have been performed and that the\n        // final linear residual is zero, absent any better information that\n        // may be provided here:\n      case Parameters::Solver::direct:\n      {\n        SolverControl solver_control (1,0);\n        TrilinosWrappers::SolverDirect direct (solver_control,\n                                               parameters.output ==\n                                               Parameters::Solver::verbose);\n\n        direct.solve (system_matrix, newton_update, right_hand_side);\n\n        return std::pair<unsigned int, double> (solver_control.last_step(),\n                                                solver_control.last_value());\n      }\n\n      // Likewise, if we are to use an iterative solver, we use Aztec's GMRES\n      // solver. We could use the Trilinos wrapper classes for iterative\n      // solvers and preconditioners here as well, but we choose to use an\n      // Aztec solver directly. For the given problem, Aztec's internal\n      // preconditioner implementations are superior over the ones deal.II has\n      // wrapper classes to, so we use ILU-T preconditioning within the\n      // AztecOO solver and set a bunch of options that can be changed from\n      // the parameter file.\n      //\n      // There are two more practicalities: Since we have built our right hand\n      // side and solution vector as deal.II Vector objects (as opposed to the\n      // matrix, which is a Trilinos object), we must hand the solvers\n      // Trilinos Epetra vectors.  Luckily, they support the concept of a\n      // 'view', so we just send in a pointer to our deal.II vectors. We have\n      // to provide an Epetra_Map for the vector that sets the parallel\n      // distribution, which is just a dummy object in serial. The easiest way\n      // is to ask the matrix for its map, and we're going to be ready for\n      // matrix-vector products with it.\n      //\n      // Secondly, the Aztec solver wants us to pass a Trilinos\n      // Epetra_CrsMatrix in, not the deal.II wrapper class itself. So we\n      // access to the actual Trilinos matrix in the Trilinos wrapper class by\n      // the command trilinos_matrix(). Trilinos wants the matrix to be\n      // non-constant, so we have to manually remove the constantness using a\n      // const_cast.\n      case Parameters::Solver::gmres:\n      {\n        Epetra_Vector x(View, system_matrix.domain_partitioner(),\n                        newton_update.begin());\n        Epetra_Vector b(View, system_matrix.range_partitioner(),\n                        right_hand_side.begin());\n\n        AztecOO solver;\n        solver.SetAztecOption(AZ_output,\n                              (parameters.output ==\n                               Parameters::Solver::quiet\n                               ?\n                               AZ_none\n                               :\n                               AZ_all));\n        solver.SetAztecOption(AZ_solver, AZ_gmres);\n        solver.SetRHS(&b);\n        solver.SetLHS(&x);\n\n        solver.SetAztecOption(AZ_precond,         AZ_dom_decomp);\n        solver.SetAztecOption(AZ_subdomain_solve, AZ_ilut);\n        solver.SetAztecOption(AZ_overlap,         0);\n        solver.SetAztecOption(AZ_reorder,         0);\n\n        solver.SetAztecParam(AZ_drop,      parameters.ilut_drop);\n        solver.SetAztecParam(AZ_ilut_fill, parameters.ilut_fill);\n        solver.SetAztecParam(AZ_athresh,   parameters.ilut_atol);\n        solver.SetAztecParam(AZ_rthresh,   parameters.ilut_rtol);\n\n        solver.SetUserMatrix(const_cast<Epetra_CrsMatrix *>\n                             (&system_matrix.trilinos_matrix()));\n\n        solver.Iterate(parameters.max_iterations, parameters.linear_residual);\n\n        return std::pair<unsigned int, double> (solver.NumIters(),\n                                                solver.TrueResidual());\n      }\n      }\n\n    Assert (false, ExcNotImplemented());\n    return std::pair<unsigned int, double> (0,0);\n  }\n\n\n  // @sect4{ConservationLaw::compute_refinement_indicators}\n\n  // This function is real simple: We don't pretend that we know here what a\n  // good refinement indicator would be. Rather, we assume that the\n  // <code>EulerEquation</code> class would know about this, and so we simply\n  // defer to the respective function we've implemented there:\n  template <int dim>\n  void\n  ConservationLaw<dim>::\n  compute_refinement_indicators (Vector<double> &refinement_indicators) const\n  {\n    EulerEquations<dim>::compute_refinement_indicators (dof_handler,\n                                                        mapping,\n                                                        predictor,\n                                                        refinement_indicators);\n  }\n\n\n\n  // @sect4{ConservationLaw::refine_grid}\n\n  // Here, we use the refinement indicators computed before and refine the\n  // mesh. At the beginning, we loop over all cells and mark those that we\n  // think should be refined:\n  template <int dim>\n  void\n  ConservationLaw<dim>::refine_grid (const Vector<double> &refinement_indicators)\n  {\n    typename DoFHandler<dim>::active_cell_iterator\n    cell = dof_handler.begin_active(),\n    endc = dof_handler.end();\n\n    for (unsigned int cell_no=0; cell!=endc; ++cell, ++cell_no)\n      {\n        cell->clear_coarsen_flag();\n        cell->clear_refine_flag();\n\n        if ((cell->level() < parameters.shock_levels) &&\n            (std::fabs(refinement_indicators(cell_no)) > parameters.shock_val))\n          cell->set_refine_flag();\n        else if ((cell->level() > 0) &&\n                 (std::fabs(refinement_indicators(cell_no)) < 0.75*parameters.shock_val))\n          cell->set_coarsen_flag();\n      }\n\n    // Then we need to transfer the various solution vectors from the old to\n    // the new grid while we do the refinement. The SolutionTransfer class is\n    // our friend here; it has a fairly extensive documentation, including\n    // examples, so we won't comment much on the following code. The last\n    // three lines simply re-set the sizes of some other vectors to the now\n    // correct size:\n    std::vector<Vector<double> > transfer_in;\n    std::vector<Vector<double> > transfer_out;\n\n    transfer_in.push_back(old_solution);\n    transfer_in.push_back(predictor);\n\n    triangulation.prepare_coarsening_and_refinement();\n\n    SolutionTransfer<dim> soltrans(dof_handler);\n    soltrans.prepare_for_coarsening_and_refinement(transfer_in);\n\n    triangulation.execute_coarsening_and_refinement ();\n\n    dof_handler.clear();\n    dof_handler.distribute_dofs (fe);\n\n    {\n      Vector<double> new_old_solution(1);\n      Vector<double> new_predictor(1);\n\n      transfer_out.push_back(new_old_solution);\n      transfer_out.push_back(new_predictor);\n      transfer_out[0].reinit(dof_handler.n_dofs());\n      transfer_out[1].reinit(dof_handler.n_dofs());\n    }\n\n    soltrans.interpolate(transfer_in, transfer_out);\n\n    old_solution.reinit (transfer_out[0].size());\n    old_solution = transfer_out[0];\n\n    predictor.reinit (transfer_out[1].size());\n    predictor = transfer_out[1];\n\n    current_solution.reinit(dof_handler.n_dofs());\n    current_solution = old_solution;\n    right_hand_side.reinit (dof_handler.n_dofs());\n  }\n\n\n  // @sect4{ConservationLaw::output_results}\n\n  // This function now is rather straightforward. All the magic, including\n  // transforming data from conservative variables to physical ones has been\n  // abstracted and moved into the EulerEquations class so that it can be\n  // replaced in case we want to solve some other hyperbolic conservation law.\n  //\n  // Note that the number of the output file is determined by keeping a\n  // counter in the form of a static variable that is set to zero the first\n  // time we come to this function and is incremented by one at the end of\n  // each invokation.\n  template <int dim>\n  void ConservationLaw<dim>::output_results () const\n  {\n    typename EulerEquations<dim>::Postprocessor\n    postprocessor (parameters.schlieren_plot);\n\n    DataOut<dim> data_out;\n    data_out.attach_dof_handler (dof_handler);\n\n    data_out.add_data_vector (current_solution,\n                              EulerEquations<dim>::component_names (),\n                              DataOut<dim>::type_dof_data,\n                              EulerEquations<dim>::component_interpretation ());\n\n    data_out.add_data_vector (current_solution, postprocessor);\n\n    data_out.build_patches ();\n\n    static unsigned int output_file_number = 0;\n    std::string filename = \"solution-\" +\n                           Utilities::int_to_string (output_file_number, 3) +\n                           \".vtk\";\n    std::ofstream output (filename.c_str());\n    data_out.write_vtk (output);\n\n    ++output_file_number;\n  }\n\n\n\n\n  // @sect4{ConservationLaw::run}\n\n  // This function contains the top-level logic of this program:\n  // initialization, the time loop, and the inner Newton iteration.\n  //\n  // At the beginning, we read the mesh file specified by the parameter file,\n  // setup the DoFHandler and various vectors, and then interpolate the given\n  // initial conditions on this mesh. We then perform a number of mesh\n  // refinements, based on the initial conditions, to obtain a mesh that is\n  // already well adapted to the starting solution. At the end of this\n  // process, we output the initial solution.\n  template <int dim>\n  void ConservationLaw<dim>::run ()\n  {\n    {\n      GridIn<dim> grid_in;\n      grid_in.attach_triangulation(triangulation);\n\n      std::ifstream input_file(parameters.mesh_filename.c_str());\n      Assert (input_file, ExcFileNotOpen(parameters.mesh_filename.c_str()));\n\n      grid_in.read_ucd(input_file);\n    }\n\n    dof_handler.clear();\n    dof_handler.distribute_dofs (fe);\n\n    // Size all of the fields.\n    old_solution.reinit (dof_handler.n_dofs());\n    current_solution.reinit (dof_handler.n_dofs());\n    predictor.reinit (dof_handler.n_dofs());\n    right_hand_side.reinit (dof_handler.n_dofs());\n\n    setup_system();\n\n    VectorTools::interpolate(dof_handler,\n                             parameters.initial_conditions, old_solution);\n    current_solution = old_solution;\n    predictor = old_solution;\n\n    if (parameters.do_refine == true)\n      for (unsigned int i=0; i<parameters.shock_levels; ++i)\n        {\n          Vector<double> refinement_indicators (triangulation.n_active_cells());\n\n          compute_refinement_indicators(refinement_indicators);\n          refine_grid(refinement_indicators);\n\n          setup_system();\n\n          VectorTools::interpolate(dof_handler,\n                                   parameters.initial_conditions, old_solution);\n          current_solution = old_solution;\n          predictor = old_solution;\n        }\n\n    output_results ();\n\n    // We then enter into the main time stepping loop. At the top we simply\n    // output some status information so one can keep track of where a\n    // computation is, as well as the header for a table that indicates\n    // progress of the nonlinear inner iteration:\n    Vector<double> newton_update (dof_handler.n_dofs());\n\n    double time = 0;\n    double next_output = time + parameters.output_step;\n\n    predictor = old_solution;\n    while (time < parameters.final_time)\n      {\n        std::cout << \"T=\" << time << std::endl\n                  << \"   Number of active cells:       \"\n                  << triangulation.n_active_cells()\n                  << std::endl\n                  << \"   Number of degrees of freedom: \"\n                  << dof_handler.n_dofs()\n                  << std::endl\n                  << std::endl;\n\n        std::cout << \"   NonLin Res     Lin Iter       Lin Res\" << std::endl\n                  << \"   _____________________________________\" << std::endl;\n\n        // Then comes the inner Newton iteration to solve the nonlinear\n        // problem in each time step. The way it works is to reset matrix and\n        // right hand side to zero, then assemble the linear system. If the\n        // norm of the right hand side is small enough, then we declare that\n        // the Newton iteration has converged. Otherwise, we solve the linear\n        // system, update the current solution with the Newton increment, and\n        // output convergence information. At the end, we check that the\n        // number of Newton iterations is not beyond a limit of 10 -- if it\n        // is, it appears likely that iterations are diverging and further\n        // iterations would do no good. If that happens, we throw an exception\n        // that will be caught in <code>main()</code> with status information\n        // being displayed before the program aborts.\n        //\n        // Note that the way we write the AssertThrow macro below is by and\n        // large equivalent to writing something like <code>if (!(nonlin_iter\n        // @<= 10)) throw ExcMessage (\"No convergence in nonlinear\n        // solver\");</code>. The only significant difference is that\n        // AssertThrow also makes sure that the exception being thrown carries\n        // with it information about the location (file name and line number)\n        // where it was generated. This is not overly critical here, because\n        // there is only a single place where this sort of exception can\n        // happen; however, it is generally a very useful tool when one wants\n        // to find out where an error occurred.\n        unsigned int nonlin_iter = 0;\n        current_solution = predictor;\n        while (true)\n          {\n            system_matrix = 0;\n\n            right_hand_side = 0;\n            assemble_system ();\n\n            const double res_norm = right_hand_side.l2_norm();\n            if (std::fabs(res_norm) < 1e-10)\n              {\n                std::printf(\"   %-16.3e (converged)\\n\\n\", res_norm);\n                break;\n              }\n            else\n              {\n                newton_update = 0;\n\n                std::pair<unsigned int, double> convergence\n                  = solve (newton_update);\n\n                current_solution += newton_update;\n\n                std::printf(\"   %-16.3e %04d        %-5.2e\\n\",\n                            res_norm, convergence.first, convergence.second);\n              }\n\n            ++nonlin_iter;\n            AssertThrow (nonlin_iter <= 10,\n                         ExcMessage (\"No convergence in nonlinear solver\"));\n          }\n\n        // We only get to this point if the Newton iteration has converged, so\n        // do various post convergence tasks here:\n        //\n        // First, we update the time and produce graphical output if so\n        // desired. Then we update a predictor for the solution at the next\n        // time step by approximating $\\mathbf w^{n+1}\\approx \\mathbf w^n +\n        // \\delta t \\frac{\\partial \\mathbf w}{\\partial t} \\approx \\mathbf w^n\n        // + \\delta t \\; \\frac{\\mathbf w^n-\\mathbf w^{n-1}}{\\delta t} = 2\n        // \\mathbf w^n - \\mathbf w^{n-1}$ to try and make adaptivity work\n        // better.  The idea is to try and refine ahead of a front, rather\n        // than stepping into a coarse set of elements and smearing the\n        // old_solution.  This simple time extrapolator does the job. With\n        // this, we then refine the mesh if so desired by the user, and\n        // finally continue on with the next time step:\n        time += parameters.time_step;\n\n        if (parameters.output_step < 0)\n          output_results ();\n        else if (time >= next_output)\n          {\n            output_results ();\n            next_output += parameters.output_step;\n          }\n\n        predictor = current_solution;\n        predictor.sadd (2.0, -1.0, old_solution);\n\n        old_solution = current_solution;\n\n        if (parameters.do_refine == true)\n          {\n            Vector<double> refinement_indicators (triangulation.n_active_cells());\n            compute_refinement_indicators(refinement_indicators);\n\n            refine_grid(refinement_indicators);\n            setup_system();\n\n            newton_update.reinit (dof_handler.n_dofs());\n          }\n      }\n  }\n}\n\n// @sect3{main()}\n\n// The following ``main'' function is similar to previous examples and need\n// not to be commented on. Note that the program aborts if no input file name\n// is given on the command line.\nint main (int argc, char *argv[])\n{\n  try\n    {\n      using namespace dealii;\n      using namespace Step33;\n\n      deallog.depth_console(0);\n      if (argc != 2)\n        {\n          std::cout << \"Usage:\" << argv[0] << \" input_file\" << std::endl;\n          std::exit(1);\n        }\n\n      Utilities::System::MPI_InitFinalize mpi_initialization (argc, argv);\n\n      ConservationLaw<2> cons (argv[1]);\n      cons.run ();\n    }\n  catch (std::exception &exc)\n    {\n      std::cerr << std::endl << std::endl\n                << \"----------------------------------------------------\"\n                << std::endl;\n      std::cerr << \"Exception on processing: \" << std::endl\n                << exc.what() << std::endl\n                << \"Aborting!\" << std::endl\n                << \"----------------------------------------------------\"\n                << std::endl;\n      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": "79b28292e65051abf6c0401a07c0f0941839b373", "size": 108502, "ext": "cc", "lang": "C++", "max_stars_repo_path": "MHD/examples/step-33/step-33.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-33/step-33.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-33/step-33.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": 43.1419483101, "max_line_length": 117, "alphanum_fraction": 0.6156199886, "num_tokens": 24215, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.30507449306892004}}
{"text": "#include <cstdio>\n#include <cmath>\n#include <cfloat>\n#include <cstdarg>\n#include <iostream>\n#include <fstream>\n#include <sstream>\n#include <vector>\n#include <map>\n#include <Eigen/Dense>\n#include <unsupported/Eigen/CXX11/Tensor>\n#include <boost/filesystem.hpp>\n#include <omp.h>\n#include <H5Cpp.h>\n\n#include \"icp/icpPointToPoint.h\"\n#include \"timer/timer.h\"\n\n/** \\brief Read all files in a directory matching the given extension.\n * \\param[in] directory path to directory\n * \\param[out] files read file paths\n * \\param[in] extension extension to filter for\n */\nvoid read_directory(const boost::filesystem::path directory, std::map<int, boost::filesystem::path>& files, const std::string extension = \".off\") {\n  files.clear();\n  boost::filesystem::directory_iterator end;\n\n  for (boost::filesystem::directory_iterator it(directory); it != end; ++it) {\n    if (it->path().extension().string() == extension) {\n      if (!boost::filesystem::is_empty(it->path()) && !it->path().empty() && it->path().filename().string() != \"\") {\n        int number = std::stoi(it->path().filename().string());\n        files.insert(std::pair<int, boost::filesystem::path>(number, it->path()));\n      }\n    }\n  }\n}\n\n/** \\brief Just encapsulating vertices and faces. */\nclass Mesh {\npublic:\n  /** \\brief Empty constructor. */\n  Mesh() {\n\n  }\n\n  /** \\brief Add a vertex.\n   * \\param[in] vertex vertex to add\n   */\n  void add_vertex(Eigen::Vector3f& vertex) {\n    this->vertices.push_back(vertex);\n  }\n\n  /** \\brief Get the number of vertices.\n   * \\return number of vertices\n   */\n  int num_vertices() const {\n    return static_cast<int>(this->vertices.size());\n  }\n\n  Eigen::Vector3f vertex(int v) {\n    assert(v >= 0 && v < this->vertices.size());\n    return this->vertices[v];\n  }\n\n  /** \\brief Add a face.\n   * \\param[in] face face to add\n   */\n  void add_face(Eigen::Vector3i& face) {\n    this->faces.push_back(face);\n  }\n\n  /** \\brief Get the number of faces.\n   * \\return number of faces\n   */\n  int num_faces() const {\n    return static_cast<int>(this->faces.size());\n  }\n\n  Eigen::Vector3i face(int f) {\n    assert(f >= 0 && f < this->num_faces());\n    return this->faces[f];\n  }\n\n  /** \\brief Rotate the point cloud around the origin.\n   * \\param[in] rotation rotation matrix\n   */\n  void rotate(const Eigen::Matrix3f &rotation) {\n    for (int v = 0; v < this->num_vertices(); ++v) {\n      this->vertices[v] = rotation*this->vertices[v];\n    }\n  }\n\n  /** \\brief Translate the mesh.\n   * \\param[in] translation translation vector\n   */\n  void translate(const Eigen::Vector3f& translation) {\n    for (int v = 0; v < this->num_vertices(); ++v) {\n      for (int i = 0; i < 3; ++i) {\n        this->vertices[v](i) += translation(i);\n      }\n    }\n  }\n\n  /** \\brief Scale the mesh.\n   * \\param[in] scale scale vector\n   */\n  void scale(const Eigen::Vector3f& scale) {\n    for (int v = 0; v < this->num_vertices(); ++v) {\n      for (int i = 0; i < 3; ++i) {\n        this->vertices[v](i) *= scale(i);\n      }\n    }\n  }\n\n  /** \\brief Sample points from the mesh\n   * \\param[in] mesh mesh to sample from\n   * \\param[in] n batch index in points\n   * \\param[in] points pre-initialized tensor holding points\n   */\n  bool sample(const int N, std::vector<Eigen::Vector3f> &points) {\n\n    // Stores the areas of faces.\n    std::vector<float> areas(this->num_faces());\n    float sum = 0;\n\n    // Build a probability distribution over faces.\n    for (int f = 0; f < this->num_faces(); f++) {\n      Eigen::Vector3f a = this->vertices[this->faces[f][0]];\n      Eigen::Vector3f b = this->vertices[this->faces[f][1]];\n      Eigen::Vector3f c = this->vertices[this->faces[f][2]];\n\n      // Angle between a->b and a->c.\n      Eigen::Vector3f ab = b - a;\n      Eigen::Vector3f ac = c - a;\n      float cos_angle = ab.dot(ac)/(ab.norm()*ac.norm());\n      float angle = std::acos(cos_angle);\n\n      // Compute triangle area.\n      float area = std::max(0., 0.5*ab.norm()*ac.norm()*std::sin(angle));\n      //std::cout << area << \" \" << std::pow(area, 1./4.) << \" \" << angle << \" \" << ab.norm() << \" \" << ac.norm() << \" \" << std::sin(angle) << std::endl;\n\n      // Accumulate.\n      //area = std::sqrt(area);\n      areas[f] = area;\n      sum += area;\n      //areas.push_back(1);\n      //sum += 1;\n    }\n\n    //std::cout << sum << std::endl;\n    if (sum < 1e-6) {\n      std::cout << \"[Error] face area sum of \" << sum << std::endl;\n      return false;\n    }\n\n    for (int f = 0; f < this->num_faces(); f++) {\n      //std::cout << areas[f] << \" \";\n      areas[f] /= sum;\n      //std::cout << areas[f] << std::endl;\n    }\n\n    std::vector<float> cum_areas(areas.size());\n    cum_areas[0] = areas[0];\n\n    for (int f = 1; f < this->num_faces(); f++) {\n      cum_areas[f] = areas[f] + cum_areas[f - 1];\n    }\n\n    for (int f = 0; f < this->num_faces(); f++) {\n      int n = std::max(static_cast<int>(areas[f]*N), 1);\n\n      for (int i = 0; i < n; i++) {\n        float r1 = 0;\n        float r2 = 0;\n        do {\n          r1 = static_cast<float>(std::rand())/static_cast<float>(RAND_MAX);\n          r2 = static_cast<float>(std::rand())/static_cast<float>(RAND_MAX);\n        }\n        while (r1 + r2 > 1.f);\n\n        int s = std::rand()%3;\n        //std::cout << face << \" \" << areas[face] << std::endl;\n\n        Eigen::Vector3f a = this->vertices[this->faces[f](s)];\n        Eigen::Vector3f b = this->vertices[this->faces[f]((s + 1)%3)];\n        Eigen::Vector3f c = this->vertices[this->faces[f]((s + 2)%3)];\n\n        Eigen::Vector3f ab = b - a;\n        Eigen::Vector3f ac = c - a;\n\n        Eigen::Vector3f point = a + r1*ab + r2*ac;\n        points.push_back(point);\n      }\n    }\n\n    return true;\n  }\n\n  /** \\brief Sample points from the mesh\n   * \\param[in] mesh mesh to sample from\n   * \\param[in] n batch index in points\n   * \\param[out] points sampled points\n   */\n  bool sample2(const int N, std::vector<Eigen::Vector3f> &points) {\n\n    std::vector<float> areas(this->num_faces());\n\n    #pragma omp parallel\n    {\n      #pragma omp for\n      for (int f = 0; f < this->num_faces(); f++) {\n        Eigen::Vector3f a = this->vertices[this->faces[f][0]];\n        Eigen::Vector3f b = this->vertices[this->faces[f][1]];\n        Eigen::Vector3f c = this->vertices[this->faces[f][2]];\n\n        // Angle between a->b and a->c.\n        Eigen::Vector3f ab = b - a;\n        Eigen::Vector3f ac = c - a;\n        float cos_angle = ab.dot(ac)/(ab.norm()*ac.norm());\n        float angle = std::acos(cos_angle);\n\n        // Compute triangle area.\n        float area = std::max(0., 0.5*ab.norm()*ac.norm()*std::sin(angle));\n\n        // Accumulate.\n        areas[f] = area;\n      }\n    }\n\n    float sum = 0;\n    for (int f = 0; f < this->num_faces(); f++) {\n      sum += areas[f];\n    }\n\n    if (sum < 1e-6) {\n      std::cout << \"[Error] face area sum of \" << sum << std::endl;\n      return false;\n    }\n\n    for (int f = 0; f < this->num_faces(); f++) {\n      areas[f] /= sum;\n    }\n\n    std::vector<int> cum_sum(this->num_faces() + 1);\n    cum_sum[0] = 0;\n\n    for (int f = 1; f < this->num_faces() + 1; f++) {\n      cum_sum[f] = std::max(static_cast<int>(std::ceil(areas[f - 1]*N)), 1) + cum_sum[f - 1];\n    }\n\n    //std::cout << cum_sum[this->num_faces()] << \" \" << sum << std::endl;\n    points.resize(cum_sum[this->num_faces()]);\n\n    #pragma omp parallel\n    {\n      for (int f = 0; f < this->num_faces(); f++) {\n        int n = cum_sum[f + 1] - cum_sum[f];\n\n        #pragma omp for\n        for (int i = 0; i < n; i++) {\n          float r1 = 0;\n          float r2 = 0;\n          do {\n            r1 = static_cast<float>(std::rand())/static_cast<float>(RAND_MAX);\n            r2 = static_cast<float>(std::rand())/static_cast<float>(RAND_MAX);\n          }\n          while (r1 + r2 > 1.f);\n\n          int s = std::rand()%3;\n\n          Eigen::Vector3f a = this->vertices[this->faces[f](s)];\n          Eigen::Vector3f b = this->vertices[this->faces[f]((s + 1)%3)];\n          Eigen::Vector3f c = this->vertices[this->faces[f]((s + 2)%3)];\n\n          Eigen::Vector3f ab = b - a;\n          Eigen::Vector3f ac = c - a;\n\n          Eigen::Vector3f point = a + r1*ab + r2*ac;\n          //std::cout << points.size() << \" \" << cum_sum[f] + i << std::endl;\n          //assert(cum_sum[f] + i < points.size());\n          points[cum_sum[f] + i] = point;\n        }\n      }\n    }\n\n    return true;\n  }\n\n  /** \\brief Reading an off file and returning the vertices x, y, z coordinates and the\n   * face indices.\n   * \\param[in] filepath path to the OFF file\n   * \\param[out] mesh read mesh with vertices and faces\n   * \\return success\n   */\n  static bool from_off(const std::string filepath, Mesh& mesh) {\n\n    std::ifstream* file = new std::ifstream(filepath.c_str());\n    std::string line;\n    std::stringstream ss;\n    int line_nb = 0;\n\n    std::getline(*file, line);\n    ++line_nb;\n\n    if (line != \"off\" && line != \"OFF\") {\n      std::cout << \"[Error] Invalid header: \\\"\" << line << \"\\\", \" << filepath << std::endl;\n      return false;\n    }\n\n    size_t n_edges;\n    std::getline(*file, line);\n    ++line_nb;\n\n    int n_vertices;\n    int n_faces;\n    ss << line;\n    ss >> n_vertices;\n    ss >> n_faces;\n    ss >> n_edges;\n\n    for (size_t v = 0; v < n_vertices; ++v) {\n      std::getline(*file, line);\n      ++line_nb;\n\n      ss.clear();\n      ss.str(\"\");\n\n      Eigen::Vector3f vertex;\n      ss << line;\n      ss >> vertex(0);\n      ss >> vertex(1);\n      ss >> vertex(2);\n\n      mesh.add_vertex(vertex);\n    }\n\n    size_t n;\n    for (size_t f = 0; f < n_faces; ++f) {\n      std::getline(*file, line);\n      ++line_nb;\n\n      ss.clear();\n      ss.str(\"\");\n\n      size_t n;\n      ss << line;\n      ss >> n;\n\n      if(n != 3) {\n        std::cout << \"[Error] Not a triangle (\" << n << \" points) at \" << (line_nb - 1) << std::endl;\n        return false;\n      }\n\n      Eigen::Vector3i face;\n      ss >> face(0);\n      ss >> face(1);\n      ss >> face(2);\n\n      mesh.add_face(face);\n    }\n\n    if (n_vertices != mesh.num_vertices()) {\n      std::cout << \"[Error] Number of vertices in header differs from actual number of vertices.\" << std::endl;\n      return false;\n    }\n\n    if (n_faces != mesh.num_faces()) {\n      std::cout << \"[Error] Number of faces in header differs from actual number of faces.\" << std::endl;\n      return false;\n    }\n\n    file->close();\n    delete file;\n\n    return true;\n  }\n\n  /** \\brief Write mesh to OFF file.\n   * \\param[in] filepath path to OFF file to write\n   * \\return success\n   */\n  bool to_off(const std::string filepath) {\n    std::ofstream* out = new std::ofstream(filepath, std::ofstream::out);\n    if (!static_cast<bool>(*out)) {\n      return false;\n    }\n\n    (*out) << \"OFF\" << std::endl;\n    (*out) << this->vertices.size() << \" \" << this->num_faces() << \" 0\" << std::endl;\n\n    for (unsigned int v = 0; v < this->vertices.size(); v++) {\n      (*out) << this->vertices[v](0) << \" \" << this->vertices[v](1) << \" \" << this->vertices[v](2) << std::endl;\n    }\n\n    for (unsigned int f = 0; f < this->num_faces(); f++) {\n      (*out) << \"3 \" << this->faces[f](0) << \" \" << this->faces[f](1) << \" \" << this->faces[f](2) << std::endl;\n    }\n\n    out->close();\n    delete out;\n\n    return true;\n  }\n\n  /** \\brief Write mesh to obj file.\n   * \\param[in] filepath\n   * \\param[in] mtl_lib\n   * \\param[in] materials\n   * \\return success\n   */\n  bool to_obj(const std::string filepath) {\n\n    std::ofstream* out = new std::ofstream(filepath, std::ofstream::out);\n    if (!static_cast<bool>(out)) {\n      return false;\n    }\n\n    for (unsigned int v = 0; v < this->vertices.size(); v++) {\n      (*out) << \"v \" << this->vertices[v](0) << \" \" << this->vertices[v](1) << \" \" << this->vertices[v](2) << std::endl;\n    }\n\n    for (unsigned int f = 0; f < this->num_faces(); f++) {\n      (*out) << \"f \" << this->faces[f](0) + 1 << \" \" << this->faces[f](1) + 1 << \" \" << this->faces[f](2) + 1 << std::endl;\n    }\n\n    out->close();\n    delete out;\n\n    return true;\n  }\n\nprivate:\n\n  /** \\brief Vertices as (x,y,z)-vectors. */\n  std::vector<Eigen::Vector3f> vertices;\n\n  /** \\brief Faces as list of vertex indices. */\n  std::vector<Eigen::Vector3i> faces;\n};\n\n/** \\brief Class representing a point cloud in 3D. */\nclass PointCloud {\npublic:\n  /** \\brief Constructor. */\n  PointCloud() {\n\n  }\n\n  /** \\brief Copy constructor.\n   * \\param[in] point_cloud point cloud to copy\n   */\n  PointCloud(const PointCloud &point_cloud) {\n    this->points.clear();\n    this->colors.clear();\n\n    for (unsigned int i = 0; i < point_cloud.points.size(); i++) {\n      this->points.push_back(point_cloud.points[i]);\n      this->colors.push_back(point_cloud.colors[i]);\n    }\n  }\n\n  /** \\brief Constructor\n   * \\param[in] points\n   */\n  PointCloud(const std::vector<Eigen::Vector3f> &points) {\n    this->points.clear();\n    this->colors.clear();\n\n    for (unsigned int i = 0; i < points.size(); i++) {\n      this->add_point(points[i]);\n    }\n  }\n\n  /** \\brief Constructor\n   * \\param[in] points\n   */\n  PointCloud(const int k, const Eigen::Tensor<float, 3, Eigen::RowMajor> &points) {\n    this->points.clear();\n    this->colors.clear();\n\n    for (unsigned int i = 0; i < points.dimension(1); i++) {\n      if (points(k, i, 0) != 0 && points(k, i, 1) != 0 && points(k, i, 0) != 2) {\n        this->add_point(Eigen::Vector3f(points(k, i, 0), points(k, i, 1), points(k, i, 2)));\n      }\n    }\n  }\n\n\n  /** \\brief Destructor. */\n  ~PointCloud() {\n\n  }\n\n  /** \\brief Read point cloud from txt file.\n   * \\param[in] filepath path to txt file\n   * \\param[out] point_cloud read point cloud\n   */\n  static bool from_txt(const std::string &filepath, PointCloud &point_cloud) {\n    std::ifstream file(filepath.c_str());\n    std::string line;\n    std::stringstream ss;\n\n    std::getline(file, line);\n    ss << line;\n\n    int n_points;\n    ss >> n_points;\n\n    if (n_points <= 0) {\n      return false;\n    }\n\n    for (int i = 0; i < n_points; i++) {\n      std::getline(file, line);\n\n      ss.clear();\n      ss.str(\"\");\n      ss << line;\n\n      Eigen::Vector3f point;\n\n      ss >> point(0);\n      ss >> point(1);\n      ss >> point(2);\n\n      point_cloud.add_point(point);\n    }\n\n    return true;\n  }\n\n  /** \\brief Read point cloud from binary file.\n   * \\param[in] filepath path to binary file\n   * \\param[out] point_cloud read point cloud\n   */\n  static bool from_bin(const std::string &filepath, PointCloud &point_cloud) {\n\n    // allocate 4 MB buffer (only ~130*4*4 KB are needed)\n    int32_t num = 1000000;\n    float *data = (float*)malloc(num*sizeof(float));\n\n    // pointers\n    float *px = data+0;\n    float *py = data+1;\n    float *pz = data+2;\n    float *pr = data+3;\n\n    // load point cloud\n    FILE *stream;\n    stream = fopen (filepath.c_str(), \"rb\");\n    num = fread(data,sizeof(float),num,stream)/4;\n    for (int32_t i=0; i<num; i++) {\n      point_cloud.add_point(Eigen::Vector3f(-*py,*pz,*px));\n      //std::cout << *px << \" \" << *px << \" \" << *pz << std::endl;\n      px+=4; py+=4; pz+=4; pr+=4;\n    }\n\n    fclose(stream);\n\n    //exit(1);\n    return true;\n  }\n\n  /** \\brief Given the angle in radians, construct a rotation matrix around the x-axis.\n   * \\param[in] radians angle in radians\n   * \\param[out] rotation rotation matrix\n   */\n  static void rotation_matrix_x(const float radians, Eigen::Matrix3f &rotation) {\n    rotation = Eigen::Matrix3f::Zero();\n\n    rotation(0, 0) = 1;\n    rotation(1, 1) = std::cos(radians); rotation(1, 2) = -std::sin(radians);\n    rotation(2, 1) = std::sin(radians); rotation(2, 2) = std::cos(radians);\n  }\n\n  /** \\brief Given the angle in radians, construct a rotation matrix around the y-axis.\n   * \\param[in] radians angle in radians\n   * \\param[out] rotation rotation matrix\n   */\n  static void rotation_matrix_y(const float radians, Eigen::Matrix3f &rotation) {\n    rotation = Eigen::Matrix3f::Zero();\n\n    rotation(0, 0) = std::cos(radians); rotation(0, 2) = std::sin(radians);\n    rotation(1, 1) = 1;\n    rotation(2, 0) = -std::sin(radians); rotation(2, 2) = std::cos(radians);\n  }\n\n  /** \\brief Given the angle in radians, construct a rotation matrix around the z-axis.\n   * \\param[in] radians angle in radians\n   * \\param[out] rotation rotation matrix\n   */\n  static void rotation_matrix_z(const float radians, Eigen::Matrix3f &rotation) {\n    rotation = Eigen::Matrix3f::Zero();\n\n    rotation(0, 0) = std::cos(radians); rotation(0, 1) = -std::sin(radians);\n    rotation(1, 0) = std::sin(radians); rotation(1, 1) = std::cos(radians);\n    rotation(2, 2) = 1;\n  }\n\n  /** \\brief Computes the rotation matrix corresponding to the given ray.\n   * \\param[in] ray ray defining the direction to rotate to\n   * \\param[out] rotation final rotation\n   */\n  static void rotation_matrix(const Eigen::Vector3f ray, Eigen::Matrix3f &rotation) {\n    Eigen::Matrix3f rotation_x;\n    Eigen::Matrix3f rotation_y;\n    Eigen::Matrix3f rotation_z;\n\n    Eigen::Vector3f axis_x = Eigen::Vector3f(1, 0, 0);\n    Eigen::Vector3f axis_y = Eigen::Vector3f(0, 1, 0);\n    Eigen::Vector3f axis_z = Eigen::Vector3f(0, 0, 1);\n\n    Eigen::Vector3f ray_x = ray; ray_x(0) = 0; ray_x /= ray_x.norm();\n    Eigen::Vector3f ray_y = ray; ray_y(1) = 0; ray_y /= ray_y.norm();\n    Eigen::Vector3f ray_z = ray; ray_z(2) = 0; ray_y /= ray_z.norm();\n\n    float radians_x = std::acos(axis_x.dot(ray_x));\n    PointCloud::rotation_matrix_x(radians_x, rotation_x);\n\n    float radians_y = std::acos(axis_y.dot(ray_y));\n    PointCloud::rotation_matrix_y(radians_y, rotation_y);\n\n    float radians_z = std::acos(axis_z.dot(ray_z));\n    PointCloud::rotation_matrix_z(radians_z, rotation_z);\n    std::cout << \"[Data] radians \" << radians_x << \" \" << radians_y << \" \" << radians_z << std::endl;\n\n    rotation = Eigen::Matrix3f::Zero();\n    rotation = rotation_z*rotation_y*rotation_x;\n  }\n\n  /** \\brief Add a point to the point cloud.\n   * \\param[in] point point to add\n   */\n  void add_point(const Eigen::Vector3f &point) {\n    this->points.push_back(point);\n    this->colors.push_back(Eigen::Vector3i::Zero());\n  }\n\n  /** \\brief Add a colored point to the point cloud.\n   * \\param[in] point point to add\n   * \\param[in] color color of the point\n   */\n  void add_point(const Eigen::Vector3f &point, const Eigen::Vector3i &color) {\n    this->points.push_back(point);\n    this->colors.push_back(color);\n  }\n\n  /** \\brief Add points from a point cloud.\n   * \\param[in] point_cloud point cloud whose points to add\n   */\n  void add_points(const PointCloud &point_cloud) {\n    for (unsigned int i = 0; i < point_cloud.num_points(); i++) {\n      this->add_point(point_cloud.points[i], point_cloud.colors[i]);\n    }\n  }\n\n  /** \\brief Merge/add points from another point cloud.\n   * \\param[in] point_cloud point_cloud to take points from\n   */\n  void merge(const PointCloud &point_cloud) {\n    for (unsigned int i = 0; i < point_cloud.points.size(); i++) {\n      this->add_point(point_cloud.points[i], point_cloud.colors[i]);\n    }\n  }\n\n  /** \\brief Get number of points.\n   * \\return number of points\n   */\n  unsigned int num_points() const {\n    return this->points.size();\n  }\n\n  /** \\brief Write point cloud to txt file.\n   * \\param[in] filepath path to file\n   * \\return success\n   */\n  bool to_txt(const std::string &filepath) {\n    std::ofstream* out = new std::ofstream(filepath, std::ofstream::out);\n    if (!static_cast<bool>(*out)) {\n      return false;\n    }\n\n    (*out) << this->points.size() << std::endl;\n    for (unsigned int i = 0; i < this->points.size(); i++) {\n     (*out) << this->points[i](0) << \" \" << this->points[i](1) << \" \" << this->points[i](2) << std::endl;\n    }\n\n    out->close();\n    delete out;\n\n    return true;\n  }\n\n  /** \\brief Write point cloud to txt file.\n   * \\param[in] filepath path to file\n   * \\return success\n   */\n  bool to_ply(const std::string &filepath) {\n    std::ofstream* out = new std::ofstream(filepath, std::ofstream::out);\n    if (!static_cast<bool>(*out)) {\n      return false;\n    }\n\n    if (this->points.size() != this->colors.size()) {\n      return false;\n    }\n\n    (*out) << \"ply\" << std::endl;\n    (*out) << \"format ascii 1.0\" << std::endl;\n    (*out) << \"element vertex \" << this->points.size() << std::endl;\n    (*out) << \"property float32 x\" << std::endl;\n    (*out) << \"property float32 y\" << std::endl;\n    (*out) << \"property float32 z\" << std::endl;\n    (*out) << \"property uchar red\" << std::endl;\n    (*out) << \"property uchar green\" << std::endl;\n    (*out) << \"property uchar blue\" << std::endl;\n    (*out) << \"end_header\" << std::endl;\n\n    for (unsigned int i = 0; i < this->points.size(); i++) {\n      //(*out) << this->points[i](0) << \" \" << this->points[i](1) << \" \" << this->points[i](2) << std::endl;\n      (*out) << this->points[i](0) << \" \" << this->points[i](1) << \" \" << this->points[i](2) << \" \"\n        << this->colors[i](0) << \" \" << this->colors[i](1) << \" \" << this->colors[i](2) << std::endl;\n    }\n\n    out->close();\n    delete out;\n\n    return true;\n  }\n\n  /** \\brief Get the extents of the point cloud in all three axes.\n   * \\param[out] min minimum coordinate values per axis\n   * \\param[out] max maximum coordinate values per axis\n   */\n  void extents(Eigen::Vector3f &min, Eigen::Vector3f &max) {\n    for (int d = 0; d < 3; d++) {\n      min(d) = FLT_MAX;\n      max(d) = FLT_MIN;\n    }\n\n    for (unsigned int i = 0; i < this->points.size(); i++) {\n      for (int d = 0; d < 3; d++) {\n        if (this->points[i](d) < min(d)) {\n          min(d) = this->points[i](d);\n        }\n        if (this->points[i](d) > max(d)) {\n          max(d) = this->points[i](d);\n        }\n      }\n    }\n  }\n\n  /** \\brief Scale the point cloud.\n   * \\param[in] scale scales for each axis\n   */\n  void scale(const Eigen::Vector3f &scale) {\n    for (unsigned int i = 0; i < this->points.size(); i++) {\n      for (int d = 0; d < 3; d++) {\n        this->points[i](d) *= scale(d);\n      }\n    }\n  }\n\n  /** \\brief Scale the point cloud.\n   * \\param[in] scale overlal scale for all axes\n   */\n  void scale(float scale) {\n    this->scale(Eigen::Vector3f(scale, scale, scale));\n  }\n\n  /** \\brief Rotate the point cloud around the origin.\n   * \\param[in] rotation rotation matrix\n   */\n  void rotate(const Eigen::Matrix3f &rotation) {\n    for (unsigned int i = 0; i < this->points.size(); i++) {\n      this->points[i] = rotation*this->points[i];\n    }\n  }\n\n  /** \\brief Translate the point cloud.\n   * \\brief translation translation vector\n   */\n  void translate(const Eigen::Vector3f &translation) {\n    for (unsigned int i = 0; i < this->points.size(); i++) {\n      this->points[i] += translation;\n    }\n  }\n\n  /** \\brief Get a point.\n   * \\param[in] n\n   * \\return point n\n   */\n  Eigen::Vector3f get(int n) const {\n    assert(n < this->num_points() && n >= 0);\n    return this->points[n];\n  }\n\nprivate:\n  /** \\brief The points of the point cloud. */\n  std::vector<Eigen::Vector3f> points;\n  /** \\brief Colors of the points. */\n  std::vector<Eigen::Vector3i> colors;\n\n};\n\n/** \\brief Read a Hdf5 file into an Eigen tensor.\n * \\param[in] filepath path to file\n * \\param[out] dense Eigen tensor\n * \\return success\n */\ntemplate<int RANK>\nbool read_hdf5(const std::string filepath, Eigen::Tensor<float, RANK, Eigen::RowMajor>& dense) {\n\n  try {\n    H5::H5File file(filepath, H5F_ACC_RDONLY);\n    H5::DataSet dataset = file.openDataSet(\"tensor\");\n\n    /*\n     * Get filespace for rank and dimension\n     */\n    H5::DataSpace filespace = dataset.getSpace();\n\n    /*\n     * Get number of dimensions in the file dataspace\n     */\n    size_t rank = filespace.getSimpleExtentNdims();\n\n    if (rank != RANK) {\n      std::cout << \"[Error] invalid rank read: \" << rank << std::endl;\n      exit(1);\n    }\n\n    /*\n     * Get and print the dimension sizes of the file dataspace\n     */\n    hsize_t dimsf[rank];\n    filespace.getSimpleExtentDims(dimsf);\n\n    std::cout << \"[Data] HDF5 size: \";\n    for (int i = 0; i < RANK; ++i) {\n      std::cout << dimsf[i] << \" \";\n    }\n    std::cout << std::endl;\n\n    /*\n     * Define the memory space to read dataset.\n     */\n    std::cout << \"[Data] HDF5 allocating ...\" << std::endl;\n    H5::DataSpace mspace(rank, dimsf);\n\n    //size_t buffer_size = 1;\n    //for (int i = 0; i < RANK; ++i) {\n    //  buffer_size *= dimsf[i];\n    //}\n\n    std::cout << \"[Data] HDF5 casting ...\" << std::endl;\n    float* buffer = static_cast<float*>(dense.data());\n    std::cout << \"[Data] HDF5 reading ...\" << std::endl;\n    dataset.read(buffer, H5::PredType::NATIVE_FLOAT, mspace, filespace);\n\n    //for (int i = 0; i < buffer_size; ++i) {\n    //  std::cout << buffer[i] << std::endl;\n    //}\n  }\n\n  // catch failure caused by the H5File operations\n  catch(H5::FileIException error) {\n    error.printError();\n    return false;\n  }\n\n  // catch failure caused by the DataSet operations\n  catch(H5::DataSetIException error) {\n    error.printError();\n    return false;\n  }\n\n  // catch failure caused by the DataSpace operations\n  catch(H5::DataSpaceIException error) {\n    error.printError();\n    return false;\n  }\n}\n\n/** \\brief Perform ICP using a point-to-point distance.\n * \\param[in] point_cloud_from\n * \\param[in] point_cloud_to\n * \\param[out] rotation\n * \\param[out] translation\n */\nvoid point_to_point_icp(const PointCloud &point_cloud_from, const PointCloud &point_cloud_to,\n    Eigen::Matrix3f &rotation, Eigen::Vector3f &translation, float &residual, int &inliers) {\n\n  double* M = new double[3*point_cloud_to.num_points()];\n  for (unsigned int i = 0; i < point_cloud_to.num_points(); i++) {\n    for (int d = 0; d < 3; d++) {\n      M[i*3 + d] = point_cloud_to.get(i)(d);\n    }\n  }\n\n  double* T = new double[3*point_cloud_from.num_points()];\n  for (unsigned int i = 0; i < point_cloud_from.num_points(); i++) {\n    for (int d = 0; d < 3; d++) {\n      T[i*3 + d] = point_cloud_from.get(i)(d);\n    }\n  }\n\n  unsigned int I = std::min(point_cloud_from.num_points(), point_cloud_to.num_points());\n  translation(0) = 0; translation(1) = 0; translation(2) = 0;\n\n  for (unsigned int i = 0; i < I; i++) {\n    translation += point_cloud_to.get(i) - point_cloud_from.get(i);\n  }\n\n  translation /= I;\n\n  Matrix R = Matrix::eye(3);\n  Matrix t(3, 1);\n  t.val[0][0] = 0;\n  t.val[1][0] = 0;\n  t.val[2][0] = 0;\n\n  IcpPointToPoint icp(M, point_cloud_to.num_points(), 3);\n  icp.setMaxIterations(100);\n  icp.setMinDeltaParam(0.0001);\n\n  residual = icp.fit(T, point_cloud_from.num_points(), R, t);\n  inliers = icp.getInlierCount();\n\n  for (int i = 0; i < 3; i++) {\n    for (int j = 0; j < 3; j++) {\n      rotation(i, j) = R.val[i][j];\n    }\n\n    translation(i) = t.val[i][0];\n  }\n\n  delete[] M;\n  delete[] T;\n}\n\nint main(int argc, char** argv) {\n  if (argc < 5) {\n    std::cout << \"[Error] Usage: icp txt_file off_directory h5_file out_off out_log\" << std::endl;\n    exit(1);\n  }\n\n  boost::filesystem::path txt_file(argv[1]);\n  boost::filesystem::path off_directory(argv[2]);\n  boost::filesystem::path h5_file(argv[3]);\n  boost::filesystem::path out_off_file(argv[4]);\n\n  boost::filesystem::path out_log_file;\n  if (argc > 5) {\n    out_log_file = boost::filesystem::path(argv[5]);\n  }\n\n  if (!boost::filesystem::is_regular_file(txt_file)) {\n    std::cout << \"[Error] file \" << txt_file.string() << \" not found\" << std::endl;\n    exit(1);\n  }\n\n  if (!boost::filesystem::is_directory(off_directory)) {\n    std::cout << \"[Error] directory \" << off_directory.string() << \" not found\" << std::endl;\n    exit(1);\n  }\n\n  if (!boost::filesystem::is_regular_file(h5_file)) {\n    std::cout << \"[Error] file \" << h5_file.string() << \" not found\" << std::endl;\n    exit(1);\n  }\n\n  std::map<int, boost::filesystem::path> off_files;\n  read_directory(off_directory, off_files);\n  std::cout << \"[ICP] found \" << off_files.size() << \" files\" << std::endl;\n\n  std::vector<int> indices;\n  for (std::map<int, boost::filesystem::path>::iterator it = off_files.begin(); it != off_files.end(); it++) {\n    indices.push_back(it->first);\n  }\n\n  int N_points = 1000000;\n  Eigen::Tensor<float, 3, Eigen::RowMajor> points(indices.size(), N_points, 3);\n  points.setZero();\n  read_hdf5(h5_file.string(), points);\n\n  PointCloud point_cloud;\n  PointCloud::from_txt(txt_file.string(), point_cloud);\n  std::cout << \"[ICP] read \" << point_cloud.num_points() << \" points\" << std::endl;\n\n  std::string log = \"n n_points residual inliers\\n\";\n  float min_residual = 1e32;\n  float min_index = 0;\n\n  Timer timer;\n  float total = 0;\n\n  std::vector<Eigen::Matrix3f> rotations;\n  std::vector<Eigen::Vector3f> translations;\n  for (unsigned int i = 0; i < indices.size(); i++) {\n    rotations.push_back(Eigen::Matrix3f::Identity());\n    translations.push_back(Eigen::Vector3f::Zero());\n  }\n\n  omp_set_num_threads(16);\n  #pragma omp parallel\n  {\n    #pragma omp for\n    for (unsigned int i = 0; i < indices.size(); i++) {\n      int n = indices[i];\n\n      PointCloud mesh_point_cloud(i, points);\n      //mesh_point_cloud.to_ply(std::to_string(i) + \".ply\");\n      float residual = 1e32;\n      int inliers = 0;\n\n      timer.start();\n      point_to_point_icp(point_cloud, mesh_point_cloud, rotations[i], translations[i], residual, inliers);\n      timer.stop();\n\n      float elapsed = timer.getElapsedTimeInMilliSec();\n      std::cout << \"[ICP] residual \" << residual << \" (inliers \" << inliers << \", \" << elapsed << \"ms)\" << std::endl;\n      total += elapsed;\n\n      #pragma omp critical\n      {\n        log += std::to_string(n) + \" \" + std::to_string(point_cloud.num_points()) + \" \" + std::to_string(residual) + \" \" + std::to_string(inliers) + \"\\n\";\n\n        if (residual < min_residual) {\n          min_residual = residual;\n          min_index = i;\n        }\n      }\n    }\n  }\n\n  Mesh mesh;\n  std::string off_file = off_files[indices[min_index]].string();\n  Mesh::from_off(off_file, mesh);\n  mesh.rotate(rotations[min_index].transpose());\n  mesh.translate(-translations[min_index]);\n  mesh.to_off(out_off_file.string());\n\n  if (!out_log_file.empty()) {\n    std::ofstream out(out_log_file.string());\n    out << log;\n    out.close();\n  }\n  else {\n    std::cout << log;\n  }\n\n  std::cout << \"[ICP] wrote \" << off_file << \" to \" << out_off_file.string() << std::endl;\n  std::cout << \"[ICP] needed on average \" << total/indices.size() << \"ms\" << std::endl;\n\n\n  exit(0);\n}\n", "meta": {"hexsha": "03b1e09fcf3e9a15559026cd3fba9af2d5afd82c", "size": 30076, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "icp/icp.cpp", "max_stars_repo_name": "davidstutz/aml-improved-shape-completion", "max_stars_repo_head_hexsha": "9337a0421994199fa218d564cc34a7e7af1a275f", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 9.0, "max_stars_repo_stars_event_min_datetime": "2018-10-11T08:03:59.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-17T11:16:07.000Z", "max_issues_repo_path": "icp/icp.cpp", "max_issues_repo_name": "jtpils/aml-improved-shape-completion", "max_issues_repo_head_hexsha": "9337a0421994199fa218d564cc34a7e7af1a275f", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-07-08T16:43:53.000Z", "max_issues_repo_issues_event_max_datetime": "2019-11-25T17:08:07.000Z", "max_forks_repo_path": "icp/icp.cpp", "max_forks_repo_name": "jtpils/aml-improved-shape-completion", "max_forks_repo_head_hexsha": "9337a0421994199fa218d564cc34a7e7af1a275f", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2018-07-19T13:06:16.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-09T00:59:56.000Z", "avg_line_length": 28.4003777148, "max_line_length": 154, "alphanum_fraction": 0.5761736933, "num_tokens": 8837, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.30507449306892004}}
{"text": "// boost\\math\\distributions\\non_central_f.hpp\n\n// Copyright John Maddock 2008.\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_SPECIAL_NON_CENTRAL_F_HPP\n#define BOOST_MATH_SPECIAL_NON_CENTRAL_F_HPP\n\n#include <boost/math/distributions/non_central_beta.hpp>\n#include <boost/math/distributions/detail/generic_mode.hpp>\n#include <boost/math/special_functions/pow.hpp>\n\nnamespace boost\n{\n   namespace math\n   {\n      template <class RealType = double, class Policy = policies::policy<> >\n      class non_central_f_distribution\n      {\n      public:\n         typedef RealType value_type;\n         typedef Policy policy_type;\n\n         non_central_f_distribution(RealType v1_, RealType v2_, RealType lambda) : v1(v1_), v2(v2_), ncp(lambda)\n         {\n            const char* function = \"boost::math::non_central_f_distribution<%1%>::non_central_f_distribution(%1%,%1%)\";\n            RealType r;\n            detail::check_df(\n               function,\n               v1, &r, Policy());\n            detail::check_df(\n               function,\n               v2, &r, Policy());\n            detail::check_non_centrality(\n               function,\n               lambda,\n               &r,\n               Policy());\n         } // non_central_f_distribution constructor.\n\n         RealType degrees_of_freedom1()const\n         {\n            return v1;\n         }\n         RealType degrees_of_freedom2()const\n         {\n            return v2;\n         }\n         RealType non_centrality() const\n         { // Private data getter function.\n            return ncp;\n         }\n      private:\n         // Data member, initialized by constructor.\n         RealType v1;   // alpha.\n         RealType v2;   // beta.\n         RealType ncp; // non-centrality parameter\n      }; // template <class RealType, class Policy> class non_central_f_distribution\n\n      typedef non_central_f_distribution<double> non_central_f; // Reserved name of type double.\n\n      // Non-member functions to give properties of the distribution.\n\n      template <class RealType, class Policy>\n      inline const std::pair<RealType, RealType> range(const non_central_f_distribution<RealType, Policy>& /* dist */)\n      { // Range of permissible values for random variable k.\n         using boost::math::tools::max_value;\n         return std::pair<RealType, RealType>(static_cast<RealType>(0), max_value<RealType>());\n      }\n\n      template <class RealType, class Policy>\n      inline const std::pair<RealType, RealType> support(const non_central_f_distribution<RealType, Policy>& /* dist */)\n      { // Range of supported values for random variable k.\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>(static_cast<RealType>(0), max_value<RealType>());\n      }\n\n      template <class RealType, class Policy>\n      inline RealType mean(const non_central_f_distribution<RealType, Policy>& dist)\n      {\n         const char* function = \"mean(non_central_f_distribution<%1%> const&)\";\n         RealType v1 = dist.degrees_of_freedom1();\n         RealType v2 = dist.degrees_of_freedom2();\n         RealType l = dist.non_centrality();\n         RealType r;\n         if(!detail::check_df(\n            function,\n            v1, &r, Policy())\n               ||\n            !detail::check_df(\n               function,\n               v2, &r, Policy())\n               ||\n            !detail::check_non_centrality(\n               function,\n               l,\n               &r,\n               Policy()))\n               return r;\n         if(v2 <= 2)\n            return policies::raise_domain_error(\n               function,\n               \"Second degrees of freedom parameter was %1%, but must be > 2 !\",\n               v2, Policy());\n         return v2 * (v1 + l) / (v1 * (v2 - 2));\n      } // mean\n\n      template <class RealType, class Policy>\n      inline RealType mode(const non_central_f_distribution<RealType, Policy>& dist)\n      { // mode.\n         static const char* function = \"mode(non_central_chi_squared_distribution<%1%> const&)\";\n\n         RealType n = dist.degrees_of_freedom1();\n         RealType m = dist.degrees_of_freedom2();\n         RealType l = dist.non_centrality();\n         RealType r;\n         if(!detail::check_df(\n            function,\n            n, &r, Policy())\n               ||\n            !detail::check_df(\n               function,\n               m, &r, Policy())\n               ||\n            !detail::check_non_centrality(\n               function,\n               l,\n               &r,\n               Policy()))\n               return r;\n         RealType guess = m > 2 ? RealType(m * (n + l) / (n * (m - 2))) : RealType(1);\n         return detail::generic_find_mode(\n            dist,\n            guess,\n            function);\n      }\n\n      template <class RealType, class Policy>\n      inline RealType variance(const non_central_f_distribution<RealType, Policy>& dist)\n      { // variance.\n         const char* function = \"variance(non_central_f_distribution<%1%> const&)\";\n         RealType n = dist.degrees_of_freedom1();\n         RealType m = dist.degrees_of_freedom2();\n         RealType l = dist.non_centrality();\n         RealType r;\n         if(!detail::check_df(\n            function,\n            n, &r, Policy())\n               ||\n            !detail::check_df(\n               function,\n               m, &r, Policy())\n               ||\n            !detail::check_non_centrality(\n               function,\n               l,\n               &r,\n               Policy()))\n               return r;\n         if(m <= 4)\n            return policies::raise_domain_error(\n               function,\n               \"Second degrees of freedom parameter was %1%, but must be > 4 !\",\n               m, Policy());\n         RealType result = 2 * m * m * ((n + l) * (n + l)\n            + (m - 2) * (n + 2 * l));\n         result /= (m - 4) * (m - 2) * (m - 2) * n * n;\n         return result;\n      }\n\n      // RealType standard_deviation(const non_central_f_distribution<RealType, Policy>& dist)\n      // standard_deviation provided by derived accessors.\n\n      template <class RealType, class Policy>\n      inline RealType skewness(const non_central_f_distribution<RealType, Policy>& dist)\n      { // skewness = sqrt(l).\n         const char* function = \"skewness(non_central_f_distribution<%1%> const&)\";\n         BOOST_MATH_STD_USING\n         RealType n = dist.degrees_of_freedom1();\n         RealType m = dist.degrees_of_freedom2();\n         RealType l = dist.non_centrality();\n         RealType r;\n         if(!detail::check_df(\n            function,\n            n, &r, Policy())\n               ||\n            !detail::check_df(\n               function,\n               m, &r, Policy())\n               ||\n            !detail::check_non_centrality(\n               function,\n               l,\n               &r,\n               Policy()))\n               return r;\n         if(m <= 6)\n            return policies::raise_domain_error(\n               function,\n               \"Second degrees of freedom parameter was %1%, but must be > 6 !\",\n               m, Policy());\n         RealType result = 2 * constants::root_two<RealType>();\n         result *= sqrt(m - 4);\n         result *= (n * (m + n - 2) *(m + 2 * n - 2)\n            + 3 * (m + n - 2) * (m + 2 * n - 2) * l\n            + 6 * (m + n - 2) * l * l + 2 * l * l * l);\n         result /= (m - 6) * pow(n * (m + n - 2) + 2 * (m + n - 2) * l + l * l, RealType(1.5f));\n         return result;\n      }\n\n      template <class RealType, class Policy>\n      inline RealType kurtosis_excess(const non_central_f_distribution<RealType, Policy>& dist)\n      {\n         const char* function = \"kurtosis_excess(non_central_f_distribution<%1%> const&)\";\n         BOOST_MATH_STD_USING\n         RealType n = dist.degrees_of_freedom1();\n         RealType m = dist.degrees_of_freedom2();\n         RealType l = dist.non_centrality();\n         RealType r;\n         if(!detail::check_df(\n            function,\n            n, &r, Policy())\n               ||\n            !detail::check_df(\n               function,\n               m, &r, Policy())\n               ||\n            !detail::check_non_centrality(\n               function,\n               l,\n               &r,\n               Policy()))\n               return r;\n         if(m <= 8)\n            return policies::raise_domain_error(\n               function,\n               \"Second degrees of freedom parameter was %1%, but must be > 8 !\",\n               m, Policy());\n         RealType l2 = l * l;\n         RealType l3 = l2 * l;\n         RealType l4 = l2 * l2;\n         RealType result = (3 * (m - 4) * (n * (m + n - 2)\n            * (4 * (m - 2) * (m - 2)\n            + (m - 2) * (m + 10) * n\n            + (10 + m) * n * n)\n            + 4 * (m + n - 2) * (4 * (m - 2) * (m - 2)\n            + (m - 2) * (10 + m) * n\n            + (10 + m) * n * n) * l + 2 * (10 + m)\n            * (m + n - 2) * (2 * m + 3 * n - 4) * l2\n            + 4 * (10 + m) * (-2 + m + n) * l3\n            + (10 + m) * l4))\n            /\n            ((-8 + m) * (-6 + m) * boost::math::pow<2>(n * (-2 + m + n)\n            + 2 * (-2 + m + n) * l + l2));\n            return result;\n      } // kurtosis_excess\n\n      template <class RealType, class Policy>\n      inline RealType kurtosis(const non_central_f_distribution<RealType, Policy>& dist)\n      {\n         return kurtosis_excess(dist) + 3;\n      }\n\n      template <class RealType, class Policy>\n      inline RealType pdf(const non_central_f_distribution<RealType, Policy>& dist, const RealType& x)\n      { // Probability Density/Mass Function.\n         typedef typename policies::evaluation<RealType, Policy>::type value_type;\n         typedef typename policies::normalise<\n            Policy,\n            policies::promote_float<false>,\n            policies::promote_double<false>,\n            policies::discrete_quantile<>,\n            policies::assert_undefined<> >::type forwarding_policy;\n\n         value_type alpha = dist.degrees_of_freedom1() / 2;\n         value_type beta = dist.degrees_of_freedom2() / 2;\n         value_type y = x * alpha / beta;\n         value_type r = pdf(boost::math::non_central_beta_distribution<value_type, forwarding_policy>(alpha, beta, dist.non_centrality()), y / (1 + y));\n         return policies::checked_narrowing_cast<RealType, forwarding_policy>(\n            r * (dist.degrees_of_freedom1() / dist.degrees_of_freedom2()) / ((1 + y) * (1 + y)),\n            \"pdf(non_central_f_distribution<%1%>, %1%)\");\n      } // pdf\n\n      template <class RealType, class Policy>\n      RealType cdf(const non_central_f_distribution<RealType, Policy>& dist, const RealType& x)\n      {\n         const char* function = \"cdf(const non_central_f_distribution<%1%>&, %1%)\";\n         RealType r;\n         if(!detail::check_df(\n            function,\n            dist.degrees_of_freedom1(), &r, Policy())\n               ||\n            !detail::check_df(\n               function,\n               dist.degrees_of_freedom2(), &r, Policy())\n               ||\n            !detail::check_non_centrality(\n               function,\n               dist.non_centrality(),\n               &r,\n               Policy()))\n               return r;\n\n         if((x < 0) || !(boost::math::isfinite)(x))\n         {\n            return policies::raise_domain_error<RealType>(\n               function, \"Random Variable parameter was %1%, but must be > 0 !\", x, Policy());\n         }\n\n         RealType alpha = dist.degrees_of_freedom1() / 2;\n         RealType beta = dist.degrees_of_freedom2() / 2;\n         RealType y = x * alpha / beta;\n         RealType c = y / (1 + y);\n         RealType cp = 1 / (1 + y);\n         //\n         // To ensure accuracy, we pass both x and 1-x to the\n         // non-central beta cdf routine, this ensures accuracy\n         // even when we compute x to be ~ 1:\n         //\n         r = detail::non_central_beta_cdf(c, cp, alpha, beta,\n            dist.non_centrality(), false, Policy());\n         return r;\n      } // cdf\n\n      template <class RealType, class Policy>\n      RealType cdf(const complemented2_type<non_central_f_distribution<RealType, Policy>, RealType>& c)\n      { // Complemented Cumulative Distribution Function\n         const char* function = \"cdf(complement(const non_central_f_distribution<%1%>&, %1%))\";\n         RealType r;\n         if(!detail::check_df(\n            function,\n            c.dist.degrees_of_freedom1(), &r, Policy())\n               ||\n            !detail::check_df(\n               function,\n               c.dist.degrees_of_freedom2(), &r, Policy())\n               ||\n            !detail::check_non_centrality(\n               function,\n               c.dist.non_centrality(),\n               &r,\n               Policy()))\n               return r;\n\n         if((c.param < 0) || !(boost::math::isfinite)(c.param))\n         {\n            return policies::raise_domain_error<RealType>(\n               function, \"Random Variable parameter was %1%, but must be > 0 !\", c.param, Policy());\n         }\n\n         RealType alpha = c.dist.degrees_of_freedom1() / 2;\n         RealType beta = c.dist.degrees_of_freedom2() / 2;\n         RealType y = c.param * alpha / beta;\n         RealType x = y / (1 + y);\n         RealType cx = 1 / (1 + y);\n         //\n         // To ensure accuracy, we pass both x and 1-x to the\n         // non-central beta cdf routine, this ensures accuracy\n         // even when we compute x to be ~ 1:\n         //\n         r = detail::non_central_beta_cdf(x, cx, alpha, beta,\n            c.dist.non_centrality(), true, Policy());\n         return r;\n      } // ccdf\n\n      template <class RealType, class Policy>\n      inline RealType quantile(const non_central_f_distribution<RealType, Policy>& dist, const RealType& p)\n      { // Quantile (or Percent Point) function.\n         RealType alpha = dist.degrees_of_freedom1() / 2;\n         RealType beta = dist.degrees_of_freedom2() / 2;\n         RealType x = quantile(boost::math::non_central_beta_distribution<RealType, Policy>(alpha, beta, dist.non_centrality()), p);\n         if(x == 1)\n            return policies::raise_overflow_error<RealType>(\n               \"quantile(const non_central_f_distribution<%1%>&, %1%)\",\n               \"Result of non central F quantile is too large to represent.\",\n               Policy());\n         return (x / (1 - x)) * (dist.degrees_of_freedom2() / dist.degrees_of_freedom1());\n      } // quantile\n\n      template <class RealType, class Policy>\n      inline RealType quantile(const complemented2_type<non_central_f_distribution<RealType, Policy>, RealType>& c)\n      { // Quantile (or Percent Point) function.\n         RealType alpha = c.dist.degrees_of_freedom1() / 2;\n         RealType beta = c.dist.degrees_of_freedom2() / 2;\n         RealType x = quantile(complement(boost::math::non_central_beta_distribution<RealType, Policy>(alpha, beta, c.dist.non_centrality()), c.param));\n         if(x == 1)\n            return policies::raise_overflow_error<RealType>(\n               \"quantile(complement(const non_central_f_distribution<%1%>&, %1%))\",\n               \"Result of non central F quantile is too large to represent.\",\n               Policy());\n         return (x / (1 - x)) * (c.dist.degrees_of_freedom2() / c.dist.degrees_of_freedom1());\n      } // quantile complement.\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_MATH_SPECIAL_NON_CENTRAL_F_HPP\n\n\n\n", "meta": {"hexsha": "780dbff9a715c82468758204087bd46906762ad8", "size": 15848, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "contrib/libboost/boost_1_62_0/boost/math/distributions/non_central_f.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/non_central_f.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/non_central_f.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.5596107056, "max_line_length": 152, "alphanum_fraction": 0.5425921252, "num_tokens": 3904, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6297745935070806, "lm_q2_score": 0.48438008427698437, "lm_q1q2_score": 0.3050502706784633}}
{"text": "/*******************************************************************************\n *\n * Forward fixpoint iterators of varying complexity and precision.\n *\n * The interleaved fixpoint iterator is described in G. Amato and F. Scozzari's\n * paper: Localizing widening and narrowing. In Proceedings of SAS 2013,\n * pages 25-42. LNCS 7935, 2013.\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_FWD_FIXPOINT_ITERATORS_HPP\n#define IKOS_FWD_FIXPOINT_ITERATORS_HPP\n\n#include <map>\n#include <boost/shared_ptr.hpp>\n#include <crab/common/types.hpp>\n#include <crab/common/debug.hpp>\n#include <crab/common/stats.hpp>\n#include <crab/iterators/wto.hpp>\n#include <crab/iterators/fixpoint_iterators_api.hpp>\n#include <crab/iterators/thresholds.hpp>\n\nnamespace ikos {\n\n  namespace interleaved_fwd_fixpoint_iterator_impl {\n    \n    template< typename NodeName, typename CFG, typename AbstractValue >\n    class wto_iterator;\n\n    template< typename NodeName, typename CFG, typename AbstractValue >\n    class wto_processor;\n    \n  } // namespace interleaved_fwd_fixpoint_iterator_impl\n  \n  template< typename NodeName, typename CFG, typename AbstractValue >\n  class interleaved_fwd_fixpoint_iterator: \n      public forward_fixpoint_iterator< NodeName, CFG, AbstractValue > {\n\n    friend class interleaved_fwd_fixpoint_iterator_impl::wto_iterator< NodeName, CFG, AbstractValue >;\n\n  private:\n    typedef std::map< NodeName, AbstractValue > invariant_table_t;\n    typedef boost::shared_ptr< invariant_table_t > invariant_table_ptr;\n    typedef wto< NodeName, CFG > wto_t;\n    typedef interleaved_fwd_fixpoint_iterator_impl::wto_iterator< NodeName, CFG, AbstractValue > wto_iterator_t;\n    typedef interleaved_fwd_fixpoint_iterator_impl::wto_processor< NodeName, CFG, AbstractValue > wto_processor_t;\n    typedef crab::iterators::thresholds<z_number> thresholds_t;\n    \n  private:\n    CFG _cfg;\n    wto_t _wto;\n    invariant_table_ptr _pre, _post;\n    // number of iterations until triggering widening\n    unsigned int _widening_delay;\n    // number of narrowing iterations. If the narrowing operator is\n    // indeed a narrowing operator this parameter is not\n    // needed. However, there are abstract domains for which a sound\n    // narrowing operation is not available so we must enforce\n    // termination.\n    unsigned int _descending_iterations;\n    // whether jump set is used for widening\n    bool _use_widening_jump_set;    \n    // set of thresholds to jump during widening\n    thresholds_t _jump_set;\n\n  private:\n    void set(invariant_table_ptr table, NodeName node, const AbstractValue& v) {\n      std::pair< typename invariant_table_t::iterator, bool > res = \n          table->insert(std::make_pair(node, v));\n      if (!res.second) {\n        (res.first)->second = v;\n      }\n    }\n    \n    void set_pre(NodeName node, const AbstractValue& v) {\n      this->set(this->_pre, node, v);\n    }\n\n    void set_post(NodeName node, const AbstractValue& v) {\n      this->set(this->_post, node, v);\n    }\n\n    AbstractValue get(invariant_table_ptr table, NodeName n) {\n      typename invariant_table_t::iterator it = table->find(n);\n      if (it != table->end()) {\n        return it->second;\n      } else {\n        return AbstractValue::bottom();\n      }\n    }\n    \n  public:\n    interleaved_fwd_fixpoint_iterator(CFG cfg, \n                                      unsigned int widening_delay,\n                                      unsigned int descending_iterations,\n                                      size_t jump_set_size): \n        _cfg(cfg),\n        _wto(cfg),\n        _pre(boost::make_shared<invariant_table_t>()),\n        _post(boost::make_shared<invariant_table_t>()),\n        _widening_delay(widening_delay),\n        _descending_iterations(descending_iterations),\n        _use_widening_jump_set (jump_set_size > 0) {\n\n      if (_use_widening_jump_set) {\n        crab::CrabStats::resume (\"Fixpo\");\n        // select statically some widening points to jump to.\n        _jump_set = _cfg.initialize_thresholds_for_widening(jump_set_size);\n        crab::CrabStats::stop (\"Fixpo\");\n      }      \n    }\n        \n    CFG get_cfg() const {\n      return this->_cfg;\n    }\n\n    const wto_t& get_wto() const {\n      return this->_wto;\n    }\n\n    AbstractValue get_pre(NodeName node) {\n      return this->get(this->_pre, node);\n    }\n    \n    AbstractValue get_post(NodeName node) {\n      return this->get(this->_post, node);\n    }\n    \n   private:\n    \n    AbstractValue extrapolate(NodeName /* node */, unsigned int iteration, \n                              AbstractValue before, AbstractValue after) {\n\n      CRAB_LOG(\"fixpo\", crab::outs() << \"Increasing iteration=\" << iteration << \"\\n\";);\n\n      if (iteration <= _widening_delay) {\n        CRAB_LOG(\"fixpo\",\n                 crab::outs() << \"Widening \\n\";\n                 auto widen_res = before | after;\n                 crab::outs() << \"Prev   : \" << before << \"\\n\"\n                           << \"Current: \" << after << \"\\n\"\n                           << \"Res    : \" << widen_res << \"\\n\");\n        //crab::CrabStats::count (AbstractValue::getDomainName() + \".count.join\");\n        //crab::ScopedCrabStats __st__(AbstractValue::getDomainName() + \".join\");\n        return before | after; \n      } else {\n        CRAB_LOG(\"fixpo\",\n                 crab::outs() << \"Widening \\n\";\n                 crab::outs() << \"Prev   : \" << before << \"\\n\"\n                           << \"Current: \" << after << \"\\n\");\n        \n        if (_use_widening_jump_set) {\n          CRAB_LOG(\"fixpo\",\n                   auto widen_res = before.widening_thresholds (after, _jump_set);\n                   crab::outs() << \"Res    : \" << widen_res << \"\\n\");\n          //crab::CrabStats::count (AbstractValue::getDomainName() + \".count.widening\");\n          //crab::ScopedCrabStats __st__(AbstractValue::getDomainName() + \".widening\");\n          return before.widening_thresholds (after, _jump_set);\n        } else {\n          CRAB_LOG(\"fixpo\",\n                   auto widen_res = before || after;\n                   crab::outs() << \"Res    : \" << widen_res << \"\\n\");\n          //crab::CrabStats::count (AbstractValue::getDomainName() + \".count.widening\");\n          //crab::ScopedCrabStats __st__(AbstractValue::getDomainName() + \".widening\");\n          return before || after;\n        }\n      }\n    }\n\n    AbstractValue refine(NodeName /* node */, unsigned int iteration, \n                         AbstractValue before, AbstractValue after) {\n\n      CRAB_LOG(\"fixpo\", \n               crab::outs() << \"Decreasing iteration=\" << iteration << \"\\n\";);\n\n      if (iteration == 1) {\n        CRAB_LOG(\"fixpo\",\n                 crab::outs() << \"Narrowing \\n\";\n                 auto narrow_res = before && after;\n                 crab::outs() << \"Prev   : \" << before << \"\\n\"\n                           << \"Current: \" << after << \"\\n\"\n                           << \"Res    : \" << narrow_res << \"\\n\");\n        //crab::CrabStats::count (AbstractValue::getDomainName() + \".count.meet\");\n        //crab::ScopedCrabStats __st__(AbstractValue::getDomainName() + \".meet\");\n        return before & after; \n      } else {\n        CRAB_LOG(\"fixpo\",\n                 crab::outs() << \"Narrowing \\n\";\n                 auto narrow_res = before && after;\n                 crab::outs() << \"Prev   : \" << before << \"\\n\"\n                 << \"Current: \" << after << \"\\n\"\n                           << \"Res    : \" << narrow_res << \"\\n\");\n        //crab::CrabStats::count (AbstractValue::getDomainName() + \".count.narrowing\");\n        //crab::ScopedCrabStats __st__(AbstractValue::getDomainName() + \".narrowing\");\n        return before && after; \n      }\n    }\n\n   public:\n\n    void run(AbstractValue init) {\n      crab::ScopedCrabStats __st__(\"Fixpo\");\n      this->set_pre(this->_cfg.entry(), init);\n      wto_iterator_t iterator(this);\n      this->_wto.accept(&iterator);\n      wto_processor_t processor(this);\n      this->_wto.accept(&processor);\n      this->_pre.reset();\n      this->_post.reset();      \n    }\n\n    virtual ~interleaved_fwd_fixpoint_iterator() { }\n\n  }; // class interleaved_fwd_fixpoint_iterator\n\n  namespace interleaved_fwd_fixpoint_iterator_impl {\n    \n    template< typename NodeName, typename CFG, typename AbstractValue >\n    class wto_iterator: public wto_component_visitor< NodeName, CFG > {\n      \n    public:\n      typedef interleaved_fwd_fixpoint_iterator< NodeName, CFG, AbstractValue > interleaved_iterator_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      typedef typename wto_t::wto_nesting_t wto_nesting_t;\n      \n    private:\n      interleaved_iterator_t *_iterator;\n      \n    public:\n      wto_iterator(interleaved_iterator_t *iterator): _iterator(iterator) { }\n      \n      void visit(wto_vertex_t& vertex) {\n        AbstractValue pre;\n        NodeName node = vertex.node();\n        if (node == this->_iterator->get_cfg().entry()) {\n          pre = this->_iterator->get_pre(node);\n        } else {\n          auto prev_nodes = this->_iterator->_cfg.prev_nodes(node);\n          pre = AbstractValue::bottom();\n          CRAB_LOG (\"fixpo\", crab::outs() << \"Joining predecessors ...\\n\");\n          for (NodeName prev : prev_nodes) {\n            //crab::CrabStats::count (AbstractValue::getDomainName() + \".count.join\");\n            //crab::ScopedCrabStats __st__(AbstractValue::getDomainName() + \".join\");\n            pre |= this->_iterator->get_post(prev);  \n          }\n          this->_iterator->set_pre(node, pre);\n        }\n        CRAB_LOG (\"fixpo\", crab::outs() << \"Analyzing node ...\\n\");\n        this->_iterator->analyze(node, pre);\n        this->_iterator->set_post(node, pre);\n      }\n      \n      void visit(wto_cycle_t& cycle) {\n        NodeName head = cycle.head();\n        wto_nesting_t cycle_nesting = this->_iterator->_wto.nesting(head);\n        auto prev_nodes = this->_iterator->_cfg.prev_nodes(head);\n        AbstractValue pre = AbstractValue::bottom();\n        CRAB_LOG (\"fixpo\", crab::outs() << \"Merging predecessors at widening point ...\\n\");\n        for (NodeName prev : prev_nodes) {\n          if (!(this->_iterator->_wto.nesting(prev) > cycle_nesting)) {\n            //crab::CrabStats::count (AbstractValue::getDomainName() + \".count.join\");\n            //crab::ScopedCrabStats __st__(AbstractValue::getDomainName() + \".join\");\n            pre |= this->_iterator->get_post(prev); \n          }\n        }\n        for(unsigned int iteration = 1; ; ++iteration) {\n          // Increasing iteration sequence with widening\n          this->_iterator->set_pre(head, pre);\n          AbstractValue post(pre); \n          CRAB_LOG (\"fixpo\", crab::outs() << \"Analyzing node ...\\n\");\n          this->_iterator->analyze(head, post);\n          this->_iterator->set_post(head, post);\n          for (typename wto_cycle_t::iterator it = cycle.begin(); it != cycle.end(); ++it) {\n            it->accept(this);\n          }\n          AbstractValue new_pre = AbstractValue::bottom();\n          for (NodeName prev : prev_nodes) {\n            //crab::CrabStats::count (AbstractValue::getDomainName() + \".count.join\");\n            //crab::ScopedCrabStats __st__(AbstractValue::getDomainName() + \".join\");\n            new_pre |= this->_iterator->get_post(prev); \n          }\n          //crab::CrabStats::count (AbstractValue::getDomainName() + \".count.leq\");\n          //crab::CrabStats::resume (AbstractValue::getDomainName() + \".leq\");\n          if (new_pre <= pre) {\n            //crab::CrabStats::stop (AbstractValue::getDomainName() + \".leq\");\n            // Post-fixpoint reached\n            CRAB_LOG (\"fixpo\", crab::outs() << \"post-fixpoint reached\\n\");\n            this->_iterator->set_pre(head, new_pre);\n            pre = new_pre;\n            break;\n          } else {\n            //crab::CrabStats::stop (AbstractValue::getDomainName() + \".leq\");\n            pre = this->_iterator->extrapolate(head, iteration, pre, new_pre);\n          }\n        }\n        for(unsigned int iteration = 1; ; ++iteration) {\n          // Decreasing iteration sequence with narrowing\n          AbstractValue post(pre); \n          CRAB_LOG (\"fixpo\", crab::outs() << \"Analyzing node ...\\n\");\n          this->_iterator->analyze(head, post);\n          this->_iterator->set_post(head, post);\n          for (typename wto_cycle_t::iterator it = cycle.begin(); it != cycle.end(); ++it) {\n            it->accept(this);\n          }\n          AbstractValue new_pre = AbstractValue::bottom();\n          for (NodeName prev : prev_nodes) {\n            //crab::CrabStats::count (AbstractValue::getDomainName() + \".count.join\");\n            //crab::ScopedCrabStats __st__(AbstractValue::getDomainName() + \".join\");\n            new_pre |= this->_iterator->get_post(prev); \n          }\n          //crab::CrabStats::count (AbstractValue::getDomainName() + \".count.leq\");\n          //crab::CrabStats::resume (AbstractValue::getDomainName() + \".leq\");\n          if (pre <= new_pre) {\n            //crab::CrabStats::stop (AbstractValue::getDomainName() + \".leq\");\n            CRAB_LOG (\"fixpo\", crab::outs() << \"No more refinement possible.\\n\");\n            // No more refinement possible (pre == new_pre)\n            break;\n          } else {\n            //crab::CrabStats::stop (AbstractValue::getDomainName() + \".leq\");\n            if (iteration > this->_iterator->_descending_iterations) break; \n            pre = this->_iterator->refine(head, iteration, pre, new_pre);\n            this->_iterator->set_pre(head, pre);\n          }\n        }\n      }\n      \n    }; // class wto_iterator\n  \n    template< typename NodeName, typename CFG, typename AbstractValue >\n    class wto_processor: public wto_component_visitor< NodeName, CFG > {\n\n    public:\n      typedef interleaved_fwd_fixpoint_iterator< NodeName, CFG, AbstractValue > interleaved_iterator_t;\n      typedef wto_vertex< NodeName, CFG > wto_vertex_t;\n      typedef wto_cycle< NodeName, CFG > wto_cycle_t;\n\n    private:\n      interleaved_iterator_t *_iterator;\n      \n    public:\n      wto_processor(interleaved_iterator_t *iterator): _iterator(iterator) { }\n      \n      void visit(wto_vertex_t& vertex) {\n        NodeName node = vertex.node();\n        this->_iterator->process_pre(node, this->_iterator->get_pre(node));\n        this->_iterator->process_post(node, this->_iterator->get_post(node));\n      }\n      \n      void visit(wto_cycle_t& cycle) {\n        NodeName head = cycle.head();\n        this->_iterator->process_pre(head, this->_iterator->get_pre(head));\n        this->_iterator->process_post(head, this->_iterator->get_post(head));\n        for (typename wto_cycle_t::iterator it = cycle.begin(); it != cycle.end(); ++it) {\n          it->accept(this);\n        }\t\n      }\n      \n    }; // class wto_processor\n  \n  } // interleaved_fwd_fixpoint_iterator_impl  \n} // namespace ikos\n#endif // IKOS_FWD_FIXPOINT_ITERATORS\n", "meta": {"hexsha": "70dac6f0390edff6b6cebd8c53db71f721ec8c0b", "size": 16842, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/crab/iterators/fwd_fixpoint_iterators.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/fwd_fixpoint_iterators.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/fwd_fixpoint_iterators.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": 42.2105263158, "max_line_length": 114, "alphanum_fraction": 0.6123975775, "num_tokens": 4047, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6297745935070806, "lm_q2_score": 0.48438008427698437, "lm_q1q2_score": 0.3050502706784633}}
{"text": "#include \"Mesh.hpp\"\n\n#include \"igl/barycentric_coordinates.h\"\n#include \"Util.hpp\"\n\n#include <Eigen/QR>\n\n#include <iostream>\n#include <cstdlib>\n#include <iostream>\n\ntemplate <typename T> using Mat = Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>;\ntemplate <typename T> using VecC3 = Eigen::Matrix<T, 3, 1>;\ntemplate <typename T> using VecC2 = Eigen::Matrix<T, 2, 1>;\ntemplate <typename T> using VecR3 = Eigen::Matrix<T, 1, 3>;\n\ntemplate <typename T>\nMesh<T>::Mesh()\n{\n#ifdef ENABLE_CUDA\n  std::cout << \" ----**** Creating mesh with CUDA solver ****----\" << std::endl;\n#else\n  std::cout << \" ----**** Creating mesh with CPU solver ****----\" << std::endl;\n#endif  \n\n  color_counter =  Eigen::MatrixXi::Zero(TEXTURE_RESOLUTION, TEXTURE_RESOLUTION);\n\n  texture.red   = Eigen::Matrix<unsigned char, Eigen::Dynamic, Eigen::Dynamic>::Constant(TEXTURE_RESOLUTION,TEXTURE_RESOLUTION, static_cast<unsigned char>(115));\n  texture.green = Eigen::Matrix<unsigned char, Eigen::Dynamic, Eigen::Dynamic>::Constant(TEXTURE_RESOLUTION,TEXTURE_RESOLUTION, static_cast<unsigned char>(115));\n  texture.blue  = Eigen::Matrix<unsigned char, Eigen::Dynamic, Eigen::Dynamic>::Constant(TEXTURE_RESOLUTION,TEXTURE_RESOLUTION, static_cast<unsigned char>(115));\n}\n\ntemplate <typename T>\nMesh<T>::~Mesh()\n{\n  std::ofstream residual_file;\n  residual_file.open(\"error.csv\");\n  residual_file << \"pc_idx,level,iteration,residuals\\n\";\n\n  for (int pci = 0; pci < residuals.size(); ++pci)\n  {\n    for (int li = 0; li < residuals[pci].size(); ++li)\n    {\n      for (int it = 0; it < residuals[pci][li].size(); ++it)\n        residual_file << pci << \",\" << li << \",\" << it << \",\" << residuals[pci][li][it] << std::endl;\n    }\n  }\n\n  residual_file.close();\n}\n\ntemplate <typename T>\nvoid Mesh<T>::cleanup()\n{\n#ifdef ENABLE_CUDA\n    cudaDeviceSynchronize();\n#endif\n\n    for (auto& m : JtJ)\n        m.clear();\n\n    for (auto& v : Jtz)\n        v.clear();\n}\n\ninline int subdivided_side_length(const int level, const int base_resolution)\n{\n  return (base_resolution-1)*static_cast<int>(std::pow(2,level))+1;\n}\n\ntemplate <typename T>\nvoid upsample(const Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>& V, const Eigen::MatrixXi& F, Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>& V_out, Eigen::MatrixXi& F_out)\n{\n    const int old_resolution = static_cast<int>(std::sqrt(static_cast<double>(V.rows())));\n    const int resolution = subdivided_side_length(1, old_resolution);\n    const int faces = (resolution - 1) * (resolution - 1) * 2;\n    const int vertices = resolution * resolution;\n    \n    F_out = Eigen::MatrixXi::Zero(faces, 3);\n    V_out = Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>::Zero(vertices, 3);\n        \n#pragma omp parallel for\n    for (int y_step = 0; y_step < old_resolution-1; ++y_step)\n    {\n      for (int x_step = 0; x_step < old_resolution-1; ++x_step)\n      {\n        \n        Eigen::Vector3i f_u = F.row(x_step*2 + y_step*(old_resolution-1)*2);\n        Eigen::Vector3i f_l = F.row(x_step*2 + y_step*(old_resolution-1)*2 + 1);\n\n        const VecC3<T> old_v0 = V.row(f_u(0));\n        const VecC3<T> old_v1 = V.row(f_u(1));\n        const VecC3<T> old_v2 = V.row(f_u(2));\n        \n        const VecC3<T> old_v3 = V.row(f_l(0));\n        const VecC3<T> old_v4 = V.row(f_l(1));\n        //const TvecC3 old_v5 = V.row(f_l(2));\n\n        const VecC3<T> v0 = old_v0;\n        const VecC3<T> v1 = (old_v0 + old_v1) * T(0.5);\n        const VecC3<T> v2 = old_v1;\n        const VecC3<T> v3 = (old_v0 + old_v2) * T(0.5);\n        const VecC3<T> v4 = (old_v2 + old_v1) * T(0.5);\n        const VecC3<T> v5 = (old_v3 + old_v1) * T(0.5);\n        const VecC3<T> v6 = old_v2;\n        const VecC3<T> v7 = (old_v3 + old_v4) * T(0.5);\n        const VecC3<T> v8 = old_v3;\n\n        const int new_v_xi = x_step * 2;\n        const int new_v_yi = y_step * 2;\n        \n        int\n          v0i = new_v_xi       + new_v_yi * resolution,\n          v1i = new_v_xi + 1 + new_v_yi * resolution,\n          v2i = new_v_xi + 2+ new_v_yi * resolution,\n          v3i = new_v_xi + (new_v_yi+1) * resolution,\n          v4i = new_v_xi + 1 + (new_v_yi+1) * resolution,\n          v5i = new_v_xi + 2 + (new_v_yi+1) * resolution,\n          v6i = new_v_xi       + (new_v_yi+2) * resolution,\n          v7i = new_v_xi + 1 + (new_v_yi+2) * resolution,\n          v8i = new_v_xi + 2 + (new_v_yi+2) * resolution;\n        \n        V_out.row(v0i) = v0;\n        V_out.row(v1i) = v1;\n        V_out.row(v3i) = v3;\n        V_out.row(v4i) = v4;\n        \n        if (x_step == old_resolution-2)\n        {\n          V_out.row(v2i) = v2;\n          V_out.row(v5i) = v5;\n        }\n        \n        if (y_step == old_resolution-2)\n        {\n          V_out.row(v6i) = v6;\n          V_out.row(v7i) = v7;\n        }\n\n        if (x_step == old_resolution - 2 && y_step == old_resolution-2)\n          V_out.row(v8i) = v8;\n\n        const int new_f_xi = x_step * 2;\n        const int new_f_yi = y_step * 2;\n        \n        F_out.row(2*new_f_xi     + new_f_yi * (resolution-1) * 2) << v0i,v1i,v3i;\n        F_out.row(2*new_f_xi + 1 + new_f_yi * (resolution-1) * 2) << v4i,v3i,v1i;\n        F_out.row(2*new_f_xi + 2 + new_f_yi * (resolution-1) * 2) << v1i,v2i,v4i;\n        F_out.row(2*new_f_xi + 3 + new_f_yi * (resolution-1) * 2) << v5i,v4i,v2i;\n        F_out.row(2*new_f_xi +     (new_f_yi+1) * (resolution-1)*2) << v3i,v4i,v6i;\n        F_out.row(2*new_f_xi + 1 + (new_f_yi+1) * (resolution-1)*2) << v7i,v6i,v4i;\n        F_out.row(2*new_f_xi + 2 + (new_f_yi+1) * (resolution-1)*2) << v4i,v5i,v7i;\n        F_out.row(2*new_f_xi + 3 + (new_f_yi+1) * (resolution-1)*2) << v8i,v7i,v5i;\n      }\n    }\n}\n\n\ntemplate <typename T>\nvoid upsample(const unsigned int levels, const Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>& V, const Eigen::MatrixXi& F, Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>& V_out, Eigen::MatrixXi& F_out)\n{\n    if (levels < 1)\n    {\n      V_out = V;\n      F_out = F;\n      return;\n    }\n    \n    Eigen::MatrixXi F_in = F;\n    Mat<T> V_in = V;\n    \n    for (unsigned int i = 0; i < levels; ++i)\n    {\n      upsample(V_in, F_in, V_out, F_out);\n      F_in = F_out;\n      V_in = V_out;\n    }\n}\n\n// Compute barycentric coordinates based on the corner points of a triangle\ntemplate <typename T>\nvoid barycentric(const VecC2<T>& p, const Eigen::Matrix<T, 2, 1>& a, const Eigen::Matrix<T, 2, 1>& b, const Eigen::Matrix<T, 2, 1>& c, T &u, T &v, T &w)\n{\n    Eigen::Matrix<T, 2, 1> v0 = b - a,\n                                           v1 = c - a,\n                                           v2 = p - a;\n    T a00 = v0.dot(v0);\n    T a01 = v0.dot(v1);\n    T a11 = v1.dot(v1);\n    T a20 = v2.dot(v0);\n    T a21 = v2.dot(v1);\n    T den = 1 / (a00 * a11 - a01 * a01);\n    v =  (a11 * a20 - a01 * a21) * den;\n    w = (a00 * a21 - a01 * a20) * den;\n    u = T(1.0) - v - w;\n}\n\ntemplate <typename T>\ntemplate <typename Derived>\nvoid Mesh<T>::align_to_point_cloud(const Eigen::MatrixBase<Derived>& P)\n{    \n  const VecR3<T> bb_min = P.colwise().minCoeff();\n  const VecR3<T> bb_max = P.colwise().maxCoeff();\n  const VecR3<T> bb_d = (bb_max - bb_min).cwiseAbs();\n  \n  JtJ.resize(MESH_LEVELS);\n  Jtz.resize(MESH_LEVELS);\n  V.resize(MESH_LEVELS);\n  F.resize(MESH_LEVELS);\n\n  const int max_resolution = subdivided_side_length(MESH_LEVELS - 1, MESH_RESOLUTION);\n  const Eigen::Matrix<T, 2, 1> a(0.f, 0.f), b(1.f, 0.f), c(0.f, 1.f), d(1.f, 1.f);\n\n  for (int li = 0; li < MESH_LEVELS; ++li)\n  {  \n    const T scaling_factor(MESH_SCALING_FACTOR);\n    const int resolution = subdivided_side_length(li, MESH_RESOLUTION);\n    \n    // Scaling matrix\n    const Eigen::Transform<T, 3, Eigen::Affine> scaling(Eigen::Scaling(VecC3<T>(scaling_factor*bb_d(0)/T(resolution), 0.f,scaling_factor*bb_d(2)/T(resolution))));\n    \n    //const TvecR3 pc_mean = P.colwise().mean();\n    // P_centr: mean of the point cloud\n    VecR3<T> P_centr = bb_min + 0.5f*(bb_max - bb_min);\n    P_centr(1) = 0.0;\n    \n    const Eigen::Transform<T, 3, Eigen::Affine> t(Eigen::Translation<T, 3>(P_centr.transpose()));\n    \n    transform = t.matrix();\n      \n    V[li].resize(resolution*resolution, 3);\n    F[li].resize((resolution-1)*(resolution-1)*2, 3);\n    JtJ[li].resize(resolution);\n    Jtz[li].resize(resolution);\n\n  #pragma omp parallel for\n    for (int z_step = 0; z_step < resolution; ++z_step)\n    {\n      for (int x_step = 0; x_step < resolution; ++x_step)\n      {\n        Eigen::Matrix<T, 1, 4> v; v << VecR3<T>(T(x_step)-T(resolution-1)/2.f,T(0.0), T(z_step)-T(resolution-1)/2.f),T(1.0);\n        VecR3<T> pos;\n        \n        if (li == 0) // Only transform the first layer. Subsequent layers only denot a difference between the first\n          pos << (v * scaling.matrix().transpose() * transform.transpose()).template head<3>();\n        else\n          pos << (v * scaling.matrix().transpose()).template head<3>();\n   \n        V[li].row(x_step + z_step*resolution) << pos;\n      }\n    }\n    \n  #pragma omp parallel for\n    for (int y_step = 0; y_step < resolution-1; ++y_step)\n    {\n      for (int x_step = 0; x_step < resolution-1; ++x_step)\n      {\n        F[li].row(x_step*2 + y_step*(resolution-1)*2)     << x_step+   y_step   *resolution,x_step+1+y_step*   resolution,x_step+(y_step+1)*resolution;\n        F[li].row(x_step*2 + y_step*(resolution-1)*2 + 1) << x_step+1+(y_step+1)*resolution,x_step+ (y_step+1)*resolution,x_step+1+y_step*resolution;\n      }\n    }\n  \n    const int factor = static_cast<int>(std::pow(2, MESH_LEVELS - li - 1));\n\n    // Place constraints for every vertex on the highest resolution grid for all levels\n    for (int i = 0; i < (max_resolution-1) * (max_resolution-1); ++i)\n    {\n\n      const int x = i % (max_resolution-1);\n      const int y = i / (max_resolution-1);\n\n      const int gx = x / factor;\n      const int gy = y / factor;\n\n      const int t = (gx + (resolution-1) * gy) * 2;\n\n      // inside current resolution rect\n      const T tx(static_cast<T>(x % factor) / static_cast<T>(factor));\n      const T ty(static_cast<T>(y % factor) / static_cast<T>(factor));\n\n      T u,v,w;\n      const VecC2<T> p(tx, ty);\n\n      if (tx + ty > T(1.))\n      {\n        // lower right triangle\n        barycentric(p, d, c, b, u, v, w);\n        JtJ[li].update_triangle(t+1, u, v);\n        Jtz[li].update_triangle(t+1, u, v, 0.f);\n      }\n      else\n      {\n        // upper left triangle\n        barycentric(p, a, b, c, u, v, w);\n        JtJ[li].update_triangle(t, u, v);\n        Jtz[li].update_triangle(t, u, v, 0.f);\n      }\n\n      // Special cases > last cell, last column, last row\n      if (x + 1 >= max_resolution - 1 && y + 1 >= max_resolution - 1)\n      {\n        const VecC2<T> p2(T(1.), T(1.));\n        barycentric(p2, d, c, b, u, v, w);\n        JtJ[li].update_triangle(t+1, u, v);\n        Jtz[li].update_triangle(t+1, u, v, 0.f);\n      }\n      if (x + 1 >= max_resolution - 1)\n      {\n        const VecC2<T> p2(T(1.), ty);\n        barycentric(p2, d, c, b, u, v, w);\n        JtJ[li].update_triangle(t+1, u, v);\n        Jtz[li].update_triangle(t+1, u, v, 0.f);\n      }\n      if (y + 1 >= max_resolution - 1)\n      {\n        const VecC2<T> p2(tx, T(1.));\n        barycentric(p2, d, c, b, u, v, w);\n        JtJ[li].update_triangle(t+1, u, v);\n        Jtz[li].update_triangle(t+1, u, v, 0.f);\n      }\n    }\n  }\n}\n\ntemplate <typename T>\nvoid Mesh<T>::get_mesh(const unsigned int level, Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>& V_out, Eigen::MatrixXi& F_out, ColorData& colordata) const\n{\n    const int mesh_resolution = JtJ[level].get_mesh_width();\n    \n    colordata.UV.resize(mesh_resolution*mesh_resolution, 2);\n    const T tdx = T(1.0) / (mesh_resolution-1);\n    for(int i = 0; i < mesh_resolution; i++)\n    {\n      for(int j = 0; j < mesh_resolution; j++)\n      {\n        const int index = j * mesh_resolution + i;\n        colordata.UV(index, 0) = i*tdx;\n        colordata.UV(index, 1) = j*tdx;\n      }\n    }\n    \n    colordata.texture.red = texture.red;\n    colordata.texture.green = texture.green;\n    colordata.texture.blue = texture.blue;\n    \n    get_mesh(level, V_out, F_out);\n}\n\ntemplate <typename T>\nvoid Mesh<T>::get_mesh(const unsigned int level, Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>& V_out, Eigen::MatrixXi& F_out) const\n{\n  if (level < 1 || level > MESH_LEVELS - 1)\n  {\n    V_out = V[0];\n    F_out = F[0];\n  }\n  else\n  {    \n    upsample(level, V[0], F[0], V_out, F_out);\n    \n    for (unsigned int li = 1; li <= level; ++li)\n    {\n      Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic> V_upsampled;\n      Eigen::MatrixXi F_upsampled;\n      upsample(level-li, V[li], F[li], V_upsampled, F_upsampled);\n      \n       V_out.col(1) += V_upsampled.col(1);\n    }\n  }\n}\n\n// Project all points onto the 2D plane, we only need to project onto XZ plane as the algorithm only runs on height fields\n// Also why we only need to project only when the input point cloud changes\ntemplate <typename T>\nvoid Mesh<T>::project_points(const int level, Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>& bc) const\n{\n  bc = Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>::Zero(current_target_point_cloud.rows(), 3);\n  \n  Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic> Vl;\n  Eigen::MatrixXi Fl;\n  get_mesh(level, Vl, Fl);\n  \n  const int resolution = subdivided_side_length(level, MESH_RESOLUTION);\n  \n  // Upper left triangle. Used to compute the index of the triangle that is hit\n  const VecC2<T> V_ul(Vl.row(0)(0), Vl.row(0)(2));\n  const VecC2<T> V_00(Vl.row(Fl.row(0)(0))(0), Vl.row(Fl.row(0)(0))(2));\n  const VecC2<T> V_01(Vl.row(Fl.row(0)(1))(0), Vl.row(Fl.row(0)(1))(2));\n  const VecC2<T> V_10(Vl.row(Fl.row(0)(2))(0), Vl.row(Fl.row(0)(2))(2));\n  \n  const double dx = (V_01- V_00).norm();\n  const double dy = (V_10 - V_00).norm();\n  \n#pragma omp parallel for\n  for (int pi = 0; pi < current_target_point_cloud.rows(); ++pi)\n  {\n    const VecC2<T> current_point(current_target_point_cloud.row(pi)(0), current_target_point_cloud.row(pi)(2));\n    const VecC2<T> offset(current_point - V_ul);\n    \n    const int c = static_cast<int>(offset(0) / dx);\n    const int r = static_cast<int>(offset(1) / dy);\n    \n    const int inner_size = resolution - 1;\n\n    // Indices are outside of mesh borders => a triangle cannot be hit\n    if (c >= inner_size || r >= inner_size || c < 0 || r < 0)\n    {\n      bc.row(pi) << -1, T(0.0), T(0.0);\n      continue;\n    } \n    const  VecC3<T> ul_3d = Vl.row(c + r*resolution);\n    const  VecC3<T> br_3d = Vl.row(c + 1 + (r+1)*resolution);\n    \n    const VecC2<T> ul_reference(ul_3d(0), ul_3d(2));\n    const VecC2<T> br_reference(br_3d(0), br_3d(2));\n    \n    const double ul_squared_dist = (ul_reference - current_point).squaredNorm();\n    const double br_squared_dist = (br_reference - current_point).squaredNorm();\n    \n    VecC2<T> v_a;\n    VecC2<T> v_b;\n    VecC2<T> v_c;\n    \n    int f_idx = -1;\n    \n    // Find corner vertices of hit triangle\n    if (ul_squared_dist <= br_squared_dist)\n    {\n      f_idx = 2 * c + r * 2 * inner_size;\n      \n      v_a << Vl.row(c + r*resolution)(0), Vl.row(c + r*resolution)(2);\n      v_b << Vl.row(c+1 + r*resolution)(0),Vl.row(c+1 + r*resolution)(2);\n      v_c << Vl.row(c + (r+1)*resolution)(0),Vl.row(c + (r+1)*resolution)(2);\n    }else\n    {\n      f_idx = 2 * c + r * 2 * inner_size + 1;\n      \n      v_a << Vl.row(c+1 + (r+1)*resolution)(0),Vl.row(c+1 + (r+1)*resolution)(2);\n      v_b << Vl.row(c + (r+1)*resolution)(0),Vl.row(c + (r+1)*resolution)(2);\n      v_c << Vl.row(c+1 + r*resolution)(0),Vl.row(c+1 + r*resolution)(2);\n    }\n    \n    T u,v,w;\n    barycentric(current_point, v_a, v_b, v_c, u, v, w);\n    \n    bc.row(pi) << T(f_idx), u, v;\n  }\n}\n\ntemplate <typename T>\nvoid Mesh<T>::set_target_point_cloud(const Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>& P)\n{\n  current_target_point_cloud = P;\n  \n  residuals.push_back(std::vector<std::vector<T>>(MESH_LEVELS-1));\n  \n  // First fuse to base level\n  Mat<T> bc;\n  project_points(0, bc);\n  update_JtJ(0, bc); // Update lh\n  update_Jtz(0, bc, current_target_point_cloud.col(1));\n  \n  for (int li = 1; li < MESH_LEVELS; ++li)\n  { \n    Mat<T> V_upsampled;\n    Eigen::MatrixXi F_upsampled;\n    \n    get_mesh(li, V_upsampled, F_upsampled);\n    project_points(li, bc);\n    \n    update_JtJ(li, bc); // Update lh\n  }  \n}\n\ntemplate <typename T>\nvoid Mesh<T>::set_target_point_cloud(const Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>& P, const Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>& C)\n{ \n  set_target_point_cloud(P);\n  \n  if (C.rows() != P.rows())\n    return;\n    \n  const VecC3<T> bb_min = V[0].row(0);\n  const VecC3<T> bb_max = V[0].row(V[0].rows()-1);\n\n  const T cdx = (bb_max(0)-bb_min(0)) / static_cast<T>(TEXTURE_RESOLUTION-1);\n  const T cdz = (bb_max(2)-bb_min(2)) / static_cast<T>(TEXTURE_RESOLUTION-1);\n\n  for(int i=0; i<current_target_point_cloud.rows(); i++)\n  { \n    T x = current_target_point_cloud(i, 0) - bb_min(0);\n    T z = current_target_point_cloud(i, 2) - bb_min(2);\n    x = std::floor(x / cdx);\n    z = std::floor(z / cdz);\n    \n    const int xi = static_cast<int>(x);\n    const int zi = static_cast<int>(z);\n    \n    if (xi >= color_counter.rows() || zi >= color_counter.cols() || xi < 0 || zi < 0)\n      continue;\n\n    const int count = color_counter(xi, zi);\n        \n    texture.red(xi, zi)   = static_cast<unsigned char>((texture.red(xi, zi)  * count + (C(i,0)*255)) / (count + 1));\n    texture.green(xi, zi) = static_cast<unsigned char>((texture.green(xi, zi) * count + (C(i,1)*255)) / (count + 1));\n    texture.blue(xi, zi)  = static_cast<unsigned char>((texture.blue(xi, zi)  * count + (C(i,2)*255)) / (count + 1));\n    ++color_counter(xi, zi);\n  }\n}\n\ntemplate <typename T>\nvoid Mesh<T>::update_JtJ(const int level, const Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>& bc)\n{    \n  for (int i = 0; i < bc.rows(); ++i)\n  {\n    const VecR3<T>& row = bc.row(i);\n\n    if (static_cast<int>(row(0)) == -1)\n      continue;\n    \n    JtJ[level].update_triangle(static_cast<int>(row(0)), row(1), row(2));\n  }\n}\n\ntemplate <typename T>\nvoid Mesh<T>::update_Jtz(const int level, const Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>& bc, const Eigen::Matrix<T, Eigen::Dynamic, 1>& z)\n{    \n  for (int i = 0; i < bc.rows(); ++i)\n  {\n    const VecR3<T>& row = bc.row(i);\n\n    if (static_cast<int>(row(0)) == -1)\n      continue;\n    \n    Jtz[level].update_triangle(static_cast<int>(row(0)), row(1), row(2), z(i));\n  }\n}\n  \ntemplate <typename T>\nvoid Mesh<T>::solve(const int iterations)\n{\n  \n  // First fuse to ba se level\n  Mat<T> bc;\n\n// lh and rh for first layer already updated in set_target_point_cloud\n#ifdef ENABLE_CUDA\n  sor_gpu(iterations, 0, V[0].col(1));\n#else\n  sor_parallel(iterations, 0, V[0].col(1));\n#endif\n  \n  for (int li = 1; li < MESH_LEVELS; ++li)\n  {\n    Mat<T> residual_height = Mat<T>::Zero(current_target_point_cloud.rows(), current_target_point_cloud.cols());\n    \n    Mat<T> V_upsampled;\n    Eigen::MatrixXi F_upsampled;\n    get_mesh(li, V_upsampled, F_upsampled);\n    project_points(li, bc);\n    \n    // Compute residual\n#pragma omp parallel for\n    for (int pi = 0; pi < bc.rows(); ++pi)\n    {\n      if (static_cast<int>(bc.row(pi)(0)) == -1) // No hit\n        continue;\n      \n      const VecC3<T> v0 = V_upsampled.row(F_upsampled.row(static_cast<int>(bc.row(pi)(0)))(0));\n      const VecC3<T> v1 = V_upsampled.row(F_upsampled.row(static_cast<int>(bc.row(pi)(0)))(1));\n      const VecC3<T> v2 = V_upsampled.row(F_upsampled.row(static_cast<int>(bc.row(pi)(0)))(2));\n      \n      // Ideally these should be equal, then there is no error\n      const VecC3<T> solved_point = bc.row(pi)(1) * v0 + bc.row(pi)(2) * v1 + (1.f - bc.row(pi)(1) - bc.row(pi)(2)) * v2;\n      const VecC3<T> measured_point = current_target_point_cloud.row(pi);\n      \n      residual_height.row(pi) = measured_point - solved_point;\n    }\n    \n    residuals.back()[li-1].push_back(residual_height.array().sum());\n    \n    // Update equation rh with residual\n    update_Jtz(li, bc, residual_height.col(1));\n\n#ifdef ENABLE_CUDA\n      sor_gpu(iterations, li, V[li].col(1));\n#else\n      sor_parallel(iterations, li, V[li].col(1));\n#endif\n  }\n}\n\n// Basic solve without any parallelism\ntemplate <typename T>\nvoid Mesh<T>::sor(const int iterations, const int level, Eigen::Ref<Eigen::Matrix<T, Eigen::Dynamic, 1>> h) const\n{\n  const auto& Jtz_vec = Jtz[level];\n  const auto& Jtj_mat = JtJ[level];\n  \n  // For each iteration, solve system for each vertex\n  for(int it = 0; it < iterations; it++)\n  {\n    for (int vi = 0; vi < h.rows(); vi++)\n      sor_inner(vi, Jtj_mat, Jtz_vec, h.data());\n  }\n}\n\n/* \n Solve system for a single vertex vi in the mesh\n vi is the vertex index,\n JtJ is the MatrixGrid, matrix on the lhs\n Jtz is the vector on the rhs\n h is an array of the vertex heights\n*/\ntemplate <typename T>\nCUDA_HOST_DEVICE inline void sor_inner(const int vi, const JtJMatrixGrid<T>& JtJ, const JtzVector<T>& Jtz_vec, T* h)\n{\n  T xn = Jtz_vec.get(vi);\n  T acc = 0;\n\n  T vals[6];\n  int ids[6];\n\n  T a;\n  JtJ.get_matrix_values_for_vertex(vi, vals, ids, a);\n\n  for (int j = 0; j < 6; ++j)\n    acc += vals[j] * h[ids[j]];\n\n  xn -= acc;\n\n  // Weighting of previous height vs newly solved height\n  // only use new height if w = 1.\n  const T w = 1.0;\n  h[vi] = (1.f-w) * h[vi] + w*xn/a;\n}\n\n// Run solve in parallel by using four-color reordering\ntemplate <typename T>\nvoid Mesh<T>::sor_parallel(const int iterations, const int level, Eigen::Ref<Eigen::Matrix<T, Eigen::Dynamic, 1>> h) const\n{\n  const auto& Jtz_vec = Jtz[level];\n  const auto& Jtj_mat = JtJ[level];\n  const int resolution = JtJ[level].get_mesh_width();\n    \n  for(int it = 0; it < iterations; it++)\n  {\n#pragma omp parallel for collapse(2)\n    for (int x = 0; x < resolution; x+=2)\n      for (int y = 0; y < resolution; y+=2)\n      {\n        const int vi = x + y * resolution;\n        sor_inner(vi, Jtj_mat, Jtz_vec, h.data());\n      }\n\n#pragma omp parallel for collapse(2)    \n    for (int x = 1; x < resolution; x+=2)\n      for (int y = 0; y < resolution; y+=2)\n      {\n        const int vi = x + y * resolution;\n        sor_inner(vi, Jtj_mat, Jtz_vec, h.data());\n      }\n\n#pragma omp parallel for collapse(2)\n    for (int x = 0; x < resolution; x+=2)\n      for (int y = 1; y < resolution; y+=2)\n      {\n        const int vi = x + y * resolution;\n        sor_inner(vi, Jtj_mat, Jtz_vec, h.data());\n      }\n      \n#pragma omp parallel for collapse(2)\n    for (int x = 1; x < resolution; x+=2)\n      for (int y = 1; y < resolution; y+=2)\n      {\n        const int vi = x + y * resolution;\n        sor_inner(vi, Jtj_mat, Jtz_vec, h.data());\n      }\n  }\n}\n\n// Define CUDA specific functions here\n#ifdef ENABLE_CUDA\n\n// This function solves a single iteration for a point based on the index\n// xoffset and yoffset define the offset of the four-color reordering\n__global__ void solve_kernel(const int xoffset, const int yoffset, const int mesh_width, const JtzVector<float> Jtz_vec, const JtJMatrixGrid<float> JtJ_mat, float* h) {\n\tconst int idx = blockIdx.x * blockDim.x + threadIdx.x;\n\t\n    if (idx >= mesh_width*mesh_width)\n    {\n\t    return;\n    }\n\n\tconst int x = ((idx) % mesh_width);\n\tconst int y = ((idx) / mesh_width);\n\tconst int vi = x + y * mesh_width;\n\n  // Make sure that indices is okay for our offsets\n\tif ((x % 2 == xoffset) && (y % 2 == yoffset))\n\t\tsor_inner(vi, JtJ_mat, Jtz_vec, h);\n}\n\n// GPU solve for non-float meshes, does not work\ntemplate <typename T>\nvoid Mesh<T>::sor_gpu(const int, const int, Eigen::Ref<Eigen::Matrix<T, Eigen::Dynamic, 1>>)\n{\n    assert(false && \"GPU solver works only with float meshes\");\n}\n\n/*\n Function for solving the system on the GPU using CUDA\n Similar to the parallel solve this method uses four-color reordering\n and therefore there are four solve_kernel calls,\n GPU solver also only works with float meshes\n*/ \ntemplate <>\nvoid Mesh<float>::sor_gpu(const int iterations, const int level, Eigen::Ref<Eigen::Matrix<float, Eigen::Dynamic, 1>> h)\n{\n    const JtJMatrixGrid<float> JtJ_mat = JtJ[level];\n    const JtzVector<float> Jtz_vec = Jtz[level];\n    const int mesh_width = JtJ[level].get_mesh_width();\n    const int mesh_width_squared = mesh_width*mesh_width;\n    const int mat_width = JtJ[level].get_matrix_width();\n    //const int mat_width_squared = mat_width*mat_width;\n\n    float *devH;\n    CUDA_CHECK(cudaMalloc(&devH, h.rows() * sizeof(float)));\n    CUDA_CHECK(cudaMemcpy(devH, h.data(), h.rows() * sizeof(float), cudaMemcpyHostToDevice));\n\n    dim3 block(64);\n    dim3 grid((mesh_width_squared + block.x - 1) / block.x);\n\n    for (int it = 0; it < iterations; it++) {\n\t    solve_kernel<<<grid, block>>>(0, 0, mesh_width, Jtz_vec, JtJ_mat, devH);\n\t    cudaDeviceSynchronize();\n\t    solve_kernel<<<grid, block>>>(1, 0, mesh_width, Jtz_vec, JtJ_mat, devH);\n\t    cudaDeviceSynchronize();\n\t    solve_kernel<<<grid, block>>>(0, 1, mesh_width, Jtz_vec, JtJ_mat, devH);\n\t    cudaDeviceSynchronize();\n\t    solve_kernel<<<grid, block>>>(1, 1, mesh_width, Jtz_vec, JtJ_mat, devH);\n\t    cudaDeviceSynchronize();\n    }\n\n    CUDA_CHECK(cudaMemcpy(h.data(), devH, h.rows() * sizeof(float), cudaMemcpyDeviceToHost));\n    CUDA_CHECK(cudaFree(devH));\n}\n#endif\n", "meta": {"hexsha": "5d046db8b032c2f006e354bb31dacdfa8b42143b", "size": 25047, "ext": "tpp", "lang": "C++", "max_stars_repo_path": "src/Mesh.tpp", "max_stars_repo_name": "asterycs/rtsr", "max_stars_repo_head_hexsha": "176bf342581daa58f84eaffc6d34034a98cfa255", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 13.0, "max_stars_repo_stars_event_min_datetime": "2018-07-09T23:38:29.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-05T09:06:46.000Z", "max_issues_repo_path": "src/Mesh.tpp", "max_issues_repo_name": "haohanxingkong/rtsr", "max_issues_repo_head_hexsha": "176bf342581daa58f84eaffc6d34034a98cfa255", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2019-01-05T14:38:55.000Z", "max_issues_repo_issues_event_max_datetime": "2019-02-14T18:33:46.000Z", "max_forks_repo_path": "src/Mesh.tpp", "max_forks_repo_name": "haohanxingkong/rtsr", "max_forks_repo_head_hexsha": "176bf342581daa58f84eaffc6d34034a98cfa255", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2018-08-22T12:30:28.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-20T13:09:24.000Z", "avg_line_length": 33.4405874499, "max_line_length": 206, "alphanum_fraction": 0.6048628578, "num_tokens": 8046, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7154239957834733, "lm_q2_score": 0.4263215925474903, "lm_q1q2_score": 0.3050006972290993}}
{"text": "// --------------------------------------------------------------------------\n//                   OpenMS -- Open-Source Mass Spectrometry\n// --------------------------------------------------------------------------\n// Copyright The OpenMS Team -- Eberhard Karls University Tuebingen,\n// ETH Zurich, and Freie Universitaet Berlin 2002-2015.\n//\n// This software is released under a three-clause BSD license:\n//  * Redistributions of source code must retain the above copyright\n//    notice, this list of conditions and the following disclaimer.\n//  * Redistributions in binary form must reproduce the above copyright\n//    notice, this list of conditions and the following disclaimer in the\n//    documentation and/or other materials provided with the distribution.\n//  * Neither the name of any author or any participating institution\n//    may be used to endorse or promote products derived from this software\n//    without specific prior written permission.\n// For a full list of authors, refer to the file AUTHORS.\n// --------------------------------------------------------------------------\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n// ARE DISCLAIMED. IN NO EVENT SHALL ANY OF THE AUTHORS OR THE CONTRIBUTING\n// INSTITUTIONS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;\n// OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR\n// OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF\n// ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n//\n// --------------------------------------------------------------------------\n// $Maintainer: Stephan Aiche $\n// $Authors: Stephan Aiche $\n// --------------------------------------------------------------------------\n\n#include <OpenMS/SIMULATION/EGHFitter1D.h>\n#include <OpenMS/TRANSFORMATIONS/FEATUREFINDER/InterpolationModel.h>\n#include <OpenMS/MATH/STATISTICS/StatisticFunctions.h>\n#include <OpenMS/CONCEPT/Constants.h>\n#include <OpenMS/CONCEPT/LogStream.h>\n#include <OpenMS/CONCEPT/Factory.h>\n\n#include <boost/math/special_functions/fpclassify.hpp>\n\n#define DEBUG_EGHFITTER\n\nnamespace OpenMS\n{\n  int EGHFitter1D::EGHFitterFunctor::operator()(const Eigen::VectorXd& x, Eigen::VectorXd& fvec)\n  {\n    Size n = m_data->n;\n    RawDataArrayType set = m_data->set;\n\n    CoordinateType H  = x(0);\n    CoordinateType tR = x(1);\n    CoordinateType sigma_square = x(2);\n    CoordinateType tau = x(3);\n\n    CoordinateType t_diff, t_diff2, denominator = 0.0;\n\n    CoordinateType fegh = 0.0;\n\n    // iterate over all points of the signal\n    for (Size i = 0; i < n; i++)\n    {\n      double t = set[i].getPos();\n\n      t_diff = t - tR;\n      t_diff2 = t_diff * t_diff; // -> (t - t_R)^2\n\n      denominator = 2 * sigma_square + tau * t_diff; // -> 2\\sigma_{g}^{2} + \\tau \\left(t - t_R\\right)\n\n      if (denominator > 0.0)\n      {\n        fegh = H * exp(-t_diff2 / denominator);\n      }\n      else\n      {\n        fegh = 0.0;\n      }\n\n      fvec(i) = (fegh - set[i].getIntensity());\n    }\n    return 0;\n  }\n\n  // compute Jacobian matrix for the different parameters\n  int EGHFitter1D::EGHFitterFunctor::df(const Eigen::VectorXd& x, Eigen::MatrixXd& J)\n  {\n    Size n =  m_data->n;\n    RawDataArrayType set = m_data->set;\n\n    CoordinateType H  = x(0);\n    CoordinateType tR = x(1);\n    CoordinateType sigma_square = x(2);\n    CoordinateType tau = x(3);\n\n    CoordinateType derivative_H, derivative_tR, derivative_sigma_square, derivative_tau = 0.0;\n    CoordinateType t_diff, t_diff2, exp1, denominator = 0.0;\n\n\n    // iterate over all points of the signal\n    for (Size i = 0; i < n; i++)\n    {\n      CoordinateType t = set[i].getPos();\n\n      t_diff = t - tR;\n      t_diff2 = t_diff * t_diff; // -> (t - t_R)^2\n\n      denominator = 2 * sigma_square + tau * t_diff; // -> 2\\sigma_{g}^{2} + \\tau \\left(t - t_R\\right)\n\n      if (denominator > 0)\n      {\n        exp1 = exp(-t_diff2 / denominator);\n\n        // \\partial H f_{egh}(t) = \\exp\\left( \\frac{-\\left(t-t_R \\right)}{2\\sigma_{g}^{2} + \\tau \\left(t - t_R\\right)} \\right)\n        derivative_H = exp1;\n\n        // \\partial t_R f_{egh}(t) &=& H \\exp \\left( \\frac{-\\left(t-t_R \\right)}{2\\sigma_{g}^{2} + \\tau \\left(t - t_R\\right)} \\right) \\left( \\frac{\\left( 4 \\sigma_{g}^{2} + \\tau \\left(t-t_R \\right) \\right) \\left(t-t_R \\right)}{\\left( 2\\sigma_{g}^{2} + \\tau \\left(t - t_R\\right) \\right)^2} \\right)\n        derivative_tR = H * exp1 * (((4 * sigma_square + tau * t_diff) * t_diff) / (denominator * denominator));\n\n        // \\partial \\sigma_{g}^{2} f_{egh}(t) &=& H \\exp \\left( \\frac{-\\left(t-t_R \\right)^2}{2\\sigma_{g}^{2} + \\tau \\left(t - t_R\\right)} \\right) \\left( \\frac{ 2 \\left(t - t_R\\right)^2}{\\left( 2\\sigma_{g}^{2} + \\tau \\left(t - t_R\\right) \\right)^2} \\right)\n        derivative_sigma_square = H * exp1 * ((2 * t_diff2) / (denominator * denominator));\n\n        // \\partial \\tau f_{egh}(t) &=& H \\exp \\left( \\frac{-\\left(t-t_R \\right)^2}{2\\sigma_{g}^{2} + \\tau \\left(t - t_R\\right)} \\right) \\left( \\frac{ \\left(t - t_R\\right)^3}{\\left( 2\\sigma_{g}^{2} + \\tau \\left(t - t_R\\right) \\right)^2} \\right)\n        derivative_tau = H * exp1 * ((t_diff * t_diff2) / (denominator * denominator));\n      }\n      else\n      {\n        derivative_H = 0.0;\n        derivative_tR = 0.0;\n        derivative_sigma_square = 0.0;\n        derivative_tau = 0.0;\n      }\n\n      // set the jacobian matrix\n      J(i, 0) = derivative_H;\n      J(i, 1) = derivative_tR;\n      J(i, 2) = derivative_sigma_square;\n      J(i, 3) = derivative_tau;\n    }\n    return 0;\n  }\n\n  EGHFitter1D::EGHFitter1D() :\n    LevMarqFitter1D()\n  {\n    setName(getProductName());\n    defaults_.setValue(\"statistics:variance\", 1.0, \"Variance of the model.\", ListUtils::create<String>(\"advanced\"));\n    defaultsToParam_();\n  }\n\n  EGHFitter1D::EGHFitter1D(const EGHFitter1D& source) :\n    LevMarqFitter1D(source)\n  {\n    setParameters(source.getParameters());\n    updateMembers_();\n  }\n\n  EGHFitter1D::~EGHFitter1D()\n  {\n  }\n\n  EGHFitter1D& EGHFitter1D::operator=(const EGHFitter1D& source)\n  {\n    if (&source == this)\n      return *this;\n\n    LevMarqFitter1D::operator=(source);\n    setParameters(source.getParameters());\n    updateMembers_();\n\n    return *this;\n  }\n\n  EGHFitter1D::QualityType EGHFitter1D::fit1d(const RawDataArrayType& set, InterpolationModel*& model)\n  {\n    // Calculate bounding box\n    CoordinateType min_bb = set[0].getPos(), max_bb = set[0].getPos();\n    for (Size pos = 1; pos < set.size(); ++pos)\n    {\n      CoordinateType tmp = set[pos].getPos();\n      if (min_bb > tmp)\n        min_bb = tmp;\n      if (max_bb < tmp)\n        max_bb = tmp;\n    }\n\n    // Enlarge the bounding box by a few multiples of the standard deviation\n\n    const CoordinateType stdev = sqrt(statistics_.variance()) * tolerance_stdev_box_;\n    min_bb -= stdev;\n    max_bb += stdev;\n\n\n    // Set advanced parameters for residual_  und jacobian_ method\n    EGHFitter1D::Data d;\n    d.n = set.size();\n    d.set = set;\n\n    // Compute start parameters\n    setInitialParameters_(set);\n\n    Eigen::VectorXd x_init(4);\n    x_init(0) = height_;\n    x_init(1) = retention_;\n    x_init(2) = sigma_square_;\n    x_init(3) = tau_;\n\n    EGHFitterFunctor functor(4, &d);\n    optimize_(x_init, functor);\n\n    // Set optimized parameters\n    height_ = x_init[0];\n    retention_ = x_init[1];\n    sigma_square_ = x_init[2];\n    tau_ = x_init[3];\n\n#ifdef DEBUG_EGHFITTER\n    LOG_DEBUG << \"Fitter returned \\n\";\n    LOG_DEBUG << \"height:       \" << height_ << \"\\n\";\n    LOG_DEBUG << \"retention:    \" << retention_ << \"\\n\";\n    LOG_DEBUG << \"sigma_square: \" << sigma_square_ << \"\\n\";\n    LOG_DEBUG << \"tau:          \" << tau_ << std::endl;\n#endif\n\n    // build model\n    model = static_cast<InterpolationModel*>(Factory<BaseModel<1> >::create(\"EGHModel\"));\n    model->setInterpolationStep(interpolation_step_);\n\n    Param tmp;\n    tmp.setValue(\"statistics:variance\", statistics_.variance());\n    tmp.setValue(\"statistics:mean\", statistics_.mean());\n\n    tmp.setValue(\"bounding_box:compute\", \"false\"); // disable auto computation of bounding box\n    tmp.setValue(\"bounding_box:min\", min_bb);\n    tmp.setValue(\"bounding_box:max\", max_bb);\n\n    tmp.setValue(\"egh:height\", height_);\n    tmp.setValue(\"egh:retention\", retention_);\n\n    tmp.setValue(\"egh:guess_parameter\", \"false\"); // disable guessing of parameters from A/B\n    tmp.setValue(\"egh:tau\", tau_);\n    tmp.setValue(\"egh:sigma_square\", sigma_square_);\n\n    model->setParameters(tmp);\n\n\n    // calculate pearson correlation\n    std::vector<float> real_data;\n    real_data.reserve(set.size());\n    std::vector<float> model_data;\n    model_data.reserve(set.size());\n\n    for (Size i = 0; i < set.size(); ++i)\n    {\n      real_data.push_back(set[i].getIntensity());\n      model_data.push_back(model->getIntensity(DPosition<1>(set[i].getPosition())));\n    }\n\n    QualityType correlation = Math::pearsonCorrelationCoefficient(real_data.begin(), real_data.end(), model_data.begin(), model_data.end());\n    if (boost::math::isnan(correlation))\n      correlation = -1.0;\n\n    return correlation;\n  }\n\n  void EGHFitter1D::setInitialParameters_(const RawDataArrayType& set)\n  {\n    // sum over all intensities\n    CoordinateType sum = 0.0;\n    for (Size i = 0; i < set.size(); ++i)\n      sum += set[i].getIntensity();\n\n    // calculate the median\n    //Size median = 0;\n    //float count = 0.0;\n    Size apex_rt = 0;\n    CoordinateType apex = 0.0;\n    for (Size i = 0; i < set.size(); ++i)\n    {\n      //count += set[i].getIntensity();\n      //if ( count <= sum / 2 ) median = i;\n\n      if (set[i].getIntensity() > apex)\n      {\n        apex = set[i].getIntensity();\n        apex_rt = i;\n      }\n\n    }\n\n    // calculate the height of the peak\n    height_ = set[apex_rt].getIntensity();\n\n    // calculate retention time\n    retention_ = set[apex_rt].getPos();\n\n\n    // guess A / B for alpha = 0.5 -> left/right half max distance\n\n    Size i = apex_rt;\n    while (i > 0)\n    {\n      if (set[i].getIntensity() / height_ < 0.5)\n        break;\n      else\n        --i;\n    }\n    CoordinateType A = retention_ - set[i + 1].getPos();\n\n    i = apex_rt;\n    while (i < set.size())\n    {\n      if (set[i].getIntensity() / height_ < 0.5)\n        break;\n      else\n        ++i;\n    }\n    CoordinateType B = set[i - 1].getPos() - retention_;\n\n    // compute estimates for tau / sigma_square based on A/B\n    CoordinateType log_alpha = log(0.5);\n\n    tau_ = (-1 / log_alpha) * (B - A);\n    sigma_square_ = (-1 / (2 * log_alpha)) * (B * A);\n\n#ifdef DEBUG_EGHFITTER\n    LOG_DEBUG << \"Initial parameters\\n\";\n    LOG_DEBUG << \"height:       \" << height_ << \"\\n\";\n    LOG_DEBUG << \"retention:    \" << retention_ << \"\\n\";\n    LOG_DEBUG << \"A:            \" << A << \"\\n\";\n    LOG_DEBUG << \"B:            \" << B << \"\\n\";\n    LOG_DEBUG << \"sigma_square: \" << sigma_square_ << \"\\n\";\n    LOG_DEBUG << \"tau:          \" << tau_ << std::endl;\n#endif\n  }\n\n  void EGHFitter1D::updateMembers_()\n  {\n    LevMarqFitter1D::updateMembers_();\n    statistics_.setVariance(param_.getValue(\"statistics:variance\"));\n  }\n\n}\n", "meta": {"hexsha": "4fbc0142cbd84e146cd28d808022911ee9ac532f", "size": 11405, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/openms/source/SIMULATION/EGHFitter1D.cpp", "max_stars_repo_name": "tomas-pluskal/openms", "max_stars_repo_head_hexsha": "136ec9057435f6d45d65a8e1465b2a6cff9621a8", "max_stars_repo_licenses": ["Zlib", "Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/openms/source/SIMULATION/EGHFitter1D.cpp", "max_issues_repo_name": "tomas-pluskal/openms", "max_issues_repo_head_hexsha": "136ec9057435f6d45d65a8e1465b2a6cff9621a8", "max_issues_repo_licenses": ["Zlib", "Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/openms/source/SIMULATION/EGHFitter1D.cpp", "max_forks_repo_name": "tomas-pluskal/openms", "max_forks_repo_head_hexsha": "136ec9057435f6d45d65a8e1465b2a6cff9621a8", "max_forks_repo_licenses": ["Zlib", "Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.0579710145, "max_line_length": 296, "alphanum_fraction": 0.6053485313, "num_tokens": 3213, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7090191337850932, "lm_q2_score": 0.43014734858584286, "lm_q1q2_score": 0.3049827004942888}}
{"text": "#if HAVE_CONFIG_H\n# include <config.h>\n#endif\n\n#include \"RegPT.h\"\n#include \"SPT.h\"\n#include \"PowerSpectrum.h\"\n#include \"LinearPS.h\"\n#include \"Quadrature.h\"\n#include \"SpecialFunctions.h\"\n#include \"array.h\"\n#include \"Spline.h\"\n#include <gsl/gsl_sf_bessel.h>\n\n#include <cassert>\n#include <cmath>\n#include <cstdio>\n#include <cerrno>\n#include <cstdlib>\n#include <stdlib.h>\n#include <sys/stat.h>\n#include <math.h>\n#include <vector>\n#include <boost/bind.hpp>\nusing boost::cref;\n\n\n// Load Linear PS\nRegPT::RegPT(const Cosmology& C, const PowerSpectrum& P_l, real epsrel_)\n: C(C), P_l(P_l)\n{\n    epsrel = epsrel_;\n}\n\n//Error in exponential index integral\nconst double error1 = 1e-3;\n//Atsushi limit on k-angular integration\ninline double ATS(real k, real r){\n real KMAX = QMAXp/k;\n real KMIN = QMINp/k;\n if(r>=0.5) {\n return 1./(2.*r);\n }\n else{\n return  Min(XMAX, (1.+r*r-KMIN*KMIN)/2./r);\n }\n}\n\ninline int num_selec_mag(double kmin, double kmax, double y){\n    \tint mag_int;\n    //\t mag_int = (n2*1.-1)*(y-QMINp/0.5)*0.005/QMAXp + 1./n2; // linear\n    //\t mag_int = sqrt((y-QMINp/kmax)*kmin/QMAXp)*(n2-1); //quadratic\n    mag_int = (int)round((n2-1)*log((y*kmax)/QMINp)/log(QMAXp*kmax/(kmin*QMINp))); //exponential\n    \t\treturn mag_int;\n}\n\n// spline linear growth for sigma_d^2 integral\nSpline F1_reg;\n// Regularized PT exponential\nstatic real regpt_exp(const PowerSpectrum& P_l, double q){\n  return  P_l(q)/(6.*pow2(M_PI));\n}\n// Initialization of sigma_d damping term\nSpline damp_term;\nvoid RegPT::sigmad_init() const{\nvector<double> kval_table, sigd_table;\ndouble k,sigd;\nint n3 = 200;\n  for(int i = 0; i<n3; i++ ){\n    k = QMINp*exp(i*log(2.*QMAXp/(QMINp))/(n3-1.));\n    sigd = pow2(k)*Integrate<ExpSub>(bind(regpt_exp, cref(P_l), _1), QMINp, k/2., error1);\n    kval_table.push_back(k);\n    sigd_table.push_back(sigd);\n      }\n    damp_term = LinearSpline(kval_table,sigd_table);\n  }\n\n\n  // used to treat f as free parameter in GR template\ndouble rempfr;\nvoid RegPT::rempreg(real f) const{\nrempfr = f/fl_spt;\n}\n\n// normalization of linear growth\ndouble sig_8r;\n// function to set normalization of linear growth to fiducial for data comparisons\nvoid RegPT::Greg(real dfid) const {\n  sig_8r = dfid/D_spt;\n       }\n\n/* P_{ab}(k) 1-loop in regpt: analytical LCDM and nDGP */\n// 1:  P_dd, 2: P_dt , 3: P_tt ;\nreal RegPT::PLOOPr(int a, real k) const {\n  SPT spt(C,P_l,1e-3);\n  double D0,D1,D2,D3;\n  if(pow2(D_spt/dnorm_spt)*damp_term(k) >= 80. ){\n    return 0;\n  }\n  else{\n  switch (a) {\n    case 1:\n      D0= pow2(sig_8r)*pow2(D_spt/dnorm_spt);\n      D1 = pow4(sig_8r)*spt.P13D(k,1);\n      D2 = pow2(D1/P_l(k)/2.)/D0;\n      D3 = pow4(sig_8r);\n      break;\n    case 2:\n      D0= -rempfr*fdgp_spt*pow2(sig_8r)*pow2(D_spt/dnorm_spt);\n      D1= rempfr*pow4(sig_8r)*spt.P13D(k,2);\n      D2 =  pow6(sig_8r)*spt.P13D(k,1)*spt.P13D(k,3)*pow2(dnorm_spt/(D_spt*P_l(k)*2.))/(-rempfr*fdgp_spt);\n      D3 =  pow4(sig_8r)*rempfr;\n      break;\n    case 3:\n      D0=  pow2(sig_8r)*pow2(rempfr*fdgp_spt*D_spt/dnorm_spt);\n      D1 = rempfr*rempfr* pow4(sig_8r)*spt.P13D(k,3);\n      D2 = pow2(D1/P_l(k)/2.)/D0;\n      D3 =  pow4(sig_8r)*pow2(rempfr);\n      break;\n  }\n  return exp(-pow2(D_spt/dnorm_spt)*damp_term(k))*(D0*P_l(k)+D1+ D3*spt.P22D(k,a)+pow2(D_spt/dnorm_spt)*damp_term(k)/2.*(2.*D0*P_l(k)+ D1) + pow2(pow2(D_spt/dnorm_spt)*damp_term(k))/4.*D0*P_l(k) + P_l(k)*D2);\n}\n}\n\n/* P_{ab}(k) 1-loop regpt :  numerical for arbitrary model of gravity - kernel dependent */\n\n// kmin and kmax are only used if the gravity model is scale independant and kernels only need be initialized once\n//kmin and kmax then refer to the limits of the desired output range of scales\n\n\nreal RegPT::PLOOPnr(real kmin, real kmax, int a, real k) const {\n  SPT spt(C,P_l,1e-3);\n  double D0;\n  double D1;\n  double D2;\n  if(pow2(F1_nk/dnorm_spt)*damp_term(k) >= 80. ){\n    return 0;\n  }\n  else{\n  switch (a) {\n    case 1:\n      D0= pow2(F1_nk/dnorm_spt);\n      D1 = spt.P13n(kmin,kmax,1,k);\n      D2 = pow2(D1/P_l(k)/2.)/D0;\n      break;\n    case 2:\n      D0= F1_nk*G1_nk/pow2(dnorm_spt);\n      D1 =  spt.P13n(kmin,kmax,2,k);\n      D2 = spt.P13n(kmin,kmax,1,k)*spt.P13n(kmin,kmax,3,k)*pow2(1./(P_l(k)*2.))/D0;\n      break;\n    case 3:\n      D0=  pow2(G1_nk/dnorm_spt);\n      D1 =  spt.P13n(kmin,kmax,3,k);\n      D2 = pow2(D1/P_l(k)/2.)/D0;\n      break;\n  }\n  return exp(-pow2(F1_nk/dnorm_spt)*damp_term(k))*(D0*P_l(k) + D1 + spt.P22n(kmin,kmax,a,k) + pow2(F1_nk/dnorm_spt)*damp_term(k)/2.*(2.*D0*P_l(k)+ D1) + pow2(pow2(F1_nk/dnorm_spt)*damp_term(k))/4.*D0*P_l(k) + P_l(k)*D2);\n  }\n}\n\n\n/* TNS  Multipoles  */\n//bl is linear galaxy bias\n// a = 1 : Monopole\n// a = 2 : Quadrupole\n// a = 3 : Hexdecapole\nreal RegPT::PTNSMnDGPr(real k, real bl, real sigma_v, int a) const {\n  if(pow2(D_spt/dnorm_spt)*damp_term(k) >= 80. ){\n    return 0;\n  }\n  else{\n\treturn  (pow2(bl)*factL(k,sigma_v,fl_spt,1.,0,a,6)*PLOOPr(1, k) - 2*factL(k,sigma_v,fl_spt,1.,1,a,6)*bl*PLOOPr(2, k) + factL(k,sigma_v,fl_spt,1.,2,a,6)* PLOOPr(3, k)+  pow4(sig_8r)*ABr(k, bl, sigma_v,a));\n}\n}\n\n\n/*  Arbitrary model TNS  Multipoles with DFoG term  */\n//bl is linear galaxy bias\n// a = 1 : Monopole\n// a = 2 : Quadrupole\n// a = 3 : Hexdecapole\nreal RegPT::PTNSMmgr(real k, double kmin, double kmax, int a,real bl, real sigma_v1 ) const {\n  if(pow2(F1_nk/dnorm_spt)*damp_term(k) >= 80. ){\n    return 0;\n  }\n  else{\n\treturn  (pow2(bl)*factL(k,sigma_v1,fl_spt,1.,0,a,6)*PLOOPnr(kmin,kmax,1, k)  - 2*factL(k,sigma_v1,fl_spt,1.,1,a,6)*bl*PLOOPnr(kmin,kmax,2, k)  + factL(k,sigma_v1,fl_spt,1.,2,a,6)* PLOOPnr(kmin,kmax,3, k)+  ABnr(kmin,kmax, bl, k, sigma_v1, a));\n}\n}\n\n\n\n\n//REDSHIFT SPACE MODEL-TNS TERMS with damping\n\n/* Non vanishing A, B and C terms */\n\n// Notes for analytic ABC terms : DEFINITION OF THETA= - DEL V / aHf (and is accounted for in definition of Cross Bispectrum)\n// See http://arxiv.org/pdf/1006.0699v1.pdf for derivation\n\n// NOTE ON PARAMETERS: x =k1.k/(k^2*r)\n\n\nstatic real ABC(int a, const PowerSpectrum& P_L, real k, real r, real x) {\n    real d = 1 + r*r - 2*r*x;\n    double dampexpa = exp(-pow2(D_spt/dnorm_spt)*damp_term(k*r)/2.-pow2(D_spt/dnorm_spt)*damp_term(k*sqrt(d))/2.-pow2(D_spt/dnorm_spt)*damp_term(k)/2.);\n    double dampexpb = exp(-pow2(D_spt/dnorm_spt)*damp_term(k*sqrt(d))-pow2(D_spt/dnorm_spt)*damp_term(k*r));\n    if(d < 1e-5)\n        return 0;\n    else\n\t\tswitch(a) {\n\t\t// A terms\n\t\t\t\t//A11\n\t\t\tcase 1:\n\t\t\t\treturn dampexpa*(-r*r*r/7.)*(x+6*x*x*x+r*r*x*(-3+10*x*x)+r*(-3+x*x-12*x*x*x*x))*P_L(k) * P_L(k*sqrt(d))/pow2(d);\n      \t//A12\n\t\t\tcase 2:\n\t\t\t\treturn  dampexpa*(r*r*r*r/14.)*(x*x-1)*(-1+7*r*x-6*x*x) * P_L(k) * P_L(k*sqrt(d))/pow2(d);\n      \t//A22\n\t\t\tcase 3:\n\t\t\t\treturn  dampexpa*(r*r*r/14.)*(r*r*x*(13-41*x*x)-4*(x+6*x*x*x)+r*(5+9*x*x+42*x*x*x*x))*P_L(k)*P_L(k*sqrt(d))/pow2(d);\n      \t//A33\n\t\t\tcase 4:\n\t\t\t\treturn dampexpa*(r*r*r/14.)*(1-7*r*x+6*x*x)*(-2*x+r*(-1+3*x*x))*P_L(k)*P_L(k*sqrt(d))/pow2(d);\n      \t//A11t\n\t\t\tcase 5:\n\t\t\t\treturn  dampexpa*(1./7.)*(x+r-2*r*x*x)*(3*r+7*x-10*r*x*x)*P_L(k*r)*P_L(k*sqrt(d))/pow2(d);\n      \t//A12t\n\t\t\tcase 6:\n\t\t\t\treturn dampexpa*(r/14.)*(x*x-1)*(3*r+7*x-10*r*x*x)*P_L(k*r)*P_L(k*sqrt(d))/pow2(d);\n      \t//A22t\n\t\t\tcase 7:\n\t\t\t\treturn dampexpa*(1./14.)*(28*x*x+r*x*(25-81*x*x)+r*r*(1-27*x*x+54*x*x*x*x))*P_L(k*r)*P_L(k*sqrt(d))/pow2(d);\n      \t//A23t\n\t\t\tcase 8:\n\t\t\t\treturn dampexpa*(r/14.)*(-x*x+1)*(r-7*x+6*r*x*x)*P_L(k*r)*P_L(k*sqrt(d))/pow2(d);\n\t\t//A33t\n\t\t\tcase 9:\n\t\t\t\treturn dampexpa*(1./14.)*(-2*x-r+3*r*x*x)*(r-7*x+6*r*x*x)*P_L(k*r)*P_L(k*sqrt(d))/pow2(d);\n\t\t//a11\n\t\t\tcase 10:\n\t\t\t\treturn dampexpa*(-7*x*x+pow3(r)*x*(-3+10*x*x)+3*r*(x+6*pow3(x))+r*r*(6-19*x*x-8*pow4(x)))*P_L(k)*P_L(k*r)/(7.*d);\n\t\t//a12\n\t\t\tcase 11:\n\t\t\t\treturn dampexpa*r*(-1+x*x)*(6*r-7*(1+r*r)*x + 8*r*x*x)*P_L(k)*P_L(k*r)/(14.*d);\n\t\t\t//a22\n\t\t\tcase 12:\n\t\t\t\treturn dampexpa*(-28*x*x+r*r*r*x*(-13+41*x*x)+r*x*(11+73*x*x)-2*r*r*(-9+31*x*x+20*x*x*x*x))*P_L(k)*P_L(k*r)/(14.*d);\n\t\t//a33\n\t\t\tcase 13:\n\t\t\t\treturn dampexpa*(7*x + r*(-6+7*r*x-8*x*x))*(-2*x+r*(-1+3*x*x))*P_L(k)*P_L(k*r)/(14.*d);\n\t\t//B terms\n\t\t\t\t//B111\n\t\t\tcase 14:\n\t\t\t\treturn dampexpb*(r*r/2.)*(x*x-1)*P_L(k*r)*P_L(k*sqrt(d))/d;\n\t   //B112\n\t\t\tcase 15:\n\t\t\t\treturn dampexpb*(3*r*r/8.)*pow2(x*x-1)*P_L(k*r)*P_L(k*sqrt(d))/d;\n\t\t//B121\n\t\t\tcase 16:\n\t\t\t\treturn dampexpb*(3.*r*r*r*r/8.)*pow2(x*x-1)*P_L(k*r)*P_L(k*sqrt(d))/pow2(d);\n\t\t\t//B122\n\t\t\tcase 17:\n\t\t\t\treturn dampexpb*(5*r*r*r*r/16.)*pow3(x*x-1)*P_L(k*r)*P_L(k*sqrt(d))/pow2(d);\n\t\t\t//B211\n\t\t\tcase 18:\n\t\t\t\treturn dampexpb*(r/2.)*(r+2*x-3*r*x*x)*P_L(k*r)*P_L(k*sqrt(d))/d;\n\t\t//B212\n\t\t\tcase 19:\n\t\t\t\treturn dampexpb*(-3*r/4.)*(x*x-1)*(-r-2*x+5*r*x*x)*P_L(k*r)*P_L(k*sqrt(d))/d;\n\t\t\t//B221\n\t\t\tcase 20:\n\t\t\t\treturn dampexpb*(3*r*r/4.)*(x*x-1)*(-2+r*r+6*r*x-5*r*r*x*x)*P_L(k*r)*P_L(k*sqrt(d))/pow2(d);\n\t\t\t//B222\n\t\t\tcase 21:\n\t\t\t\treturn dampexpb*(-3*r*r/16.)*pow2(x*x-1)*(6-30*r*x-5*r*r+35*r*r*x*x)*P_L(k*r)*P_L(k*sqrt(d))/pow2(d);\n\t\t//B312\n\t\t\tcase 22:\n\t\t\t\treturn dampexpb*(r/8.)*(4*x*(3-5*x*x)+r*(3-30*x*x+35*x*x*x*x))*P_L(k*r)*P_L(k*sqrt(d))/d;\n\t\t//B321\n\t\t\tcase 23:\n\t\t\t\treturn dampexpb*(r/8.)*(-8*x+r*(-12+36*x*x+12*r*x*(3-5*x*x)+r*r*(3-30*x*x+35*x*x*x*x)))*P_L(k*r)*P_L(k*sqrt(d))/pow2(d);\n\t\t//B322\n\t\t\tcase 24:\n\t\t\t\treturn dampexpb*(3*r/16.)*(x*x-1)*(-8*x+r*(-12+60*x*x+20*r*x*(3-7*x*x)+5*r*r*(1-14*x*x+21*x*x*x*x)))*P_L(k*r)*P_L(k*sqrt(d))/pow2(d);\n\t\t//B422 \t\t//B422 // HAVE INCLUDED THE 'TYPO' IN 3RD TERM : 6rr -> 6rrx\n\t\t\tcase 25:\n\t\t\t\treturn dampexpb*(r/16.)*(8*x*(-3+5*x*x)-6*r*(3-30*x*x+35*x*x*x*x)+6*r*r*x*(15-70*x*x+63*x*x*x*x)+r*r*r*(5-21*x*x*(5-15*x*x+11*x*x*x*x)))*P_L(k*r)*P_L(k*sqrt(d))/pow2(d);\n  \t// C terms\n\t\t\t//C11\n\t\t\tcase 26:\n\t\t\t\treturn dampexpa*2.*((r*r*r)*(x*x-1)*(Dd_spt*F_spt*r*(r*x-1)-D_spt*Fd_spt*x*d)*P_L(k)*P_L(k*sqrt(d)))/ (Dd_spt*pow2(d));\n\t\t\t//C12\n\t\t\tcase 27:\n\t\t\t\treturn -dampexpa*D_spt*Fd_spt*((r*r*r*r)*pow2(x*x-1)*P_L(k)*P_L(k*sqrt(d)))/(Dd_spt*pow2(d));\n\t\t\t//C22\n\t\t\tcase 28:\n\t\t\t\treturn dampexpa*((r*r*r)*(x*x-1)*(2*Dd_spt*F_spt*r*(r*x-1)-D_spt*Fd_spt*(r+4*x+2*r*r*x-7*r*x*x))*P_L(k)*P_L(k*sqrt(d)))/ (Dd_spt*pow2(d));\n\t\t\t//C23\n\t\t\tcase 29:\n\t\t\t\treturn -dampexpa*D_spt*Fd_spt*((r*r*r*r)*pow2(x*x-1)*P_L(k)*P_L(k*sqrt(d)))/ (Dd_spt*pow2(d));\n      //C33\n\t\t\tcase 30:\n\t\t\t\treturn dampexpa*D_spt*Fd_spt*((r*r*r)*(x*x-1)*(-2*x+r*(-1+3*x*x))*P_L(k)*P_L(k*sqrt(d)))/ (Dd_spt*pow2(d));\n\t\t\t\t//C11t\n\t\t\tcase 31:\n\t\t\t\treturn dampexpa*2*F_spt*(r*(x*x-1)*(-x+r*(-1+2*x*x))*P_L(k*r)*P_L(k*sqrt(d)))/ pow2(d);\n\t\t\t\t//C12t\n\t\t\tcase 32:\n\t\t\t\treturn -dampexpa*F_spt*(r*r*pow2(x*x-1)*P_L(k*r)*P_L(k*sqrt(d)))/ pow2(d);\n\t\t\t\t//C22t\n\t\t\tcase 33:\n\t\t\t\treturn dampexpa*r*(x*x-1)*(2*D_spt*Fd_spt*(-x+r*(-1+2*x*x)) + Dd_spt*F_spt*(-2*x+r*(-1+3*x*x)))*P_L(k*r)*P_L(k*sqrt(d))/ (Dd_spt*pow2(d));\n\t\t\t\t//C23t\n\t\t\tcase 34:\n\t\t\t\treturn -dampexpa*D_spt*Fd_spt*(r*r*pow2(x*x-1)*P_L(k*r)*P_L(k*sqrt(d)))/ (Dd_spt*pow2(d));\n\t\t\t\t//C33t\n\t\t\tcase 35:\n\t\t\t\treturn dampexpa*D_spt*Fd_spt*(r*(x*x-1)*(-2*x+r*(-1+3*x*x))*P_L(k*r)*P_L(k*sqrt(d)))/ (Dd_spt*pow2(d));\n\t\t\t\t//c11\n\t\t\tcase 36:\n\t\t\t\treturn  -dampexpa*2*r*(1-x*x)*(D_spt*Fd_spt*r*(r*x-1)-Dd_spt*F_spt*x*d)*P_L(k*r)*P_L(k)/(Dd_spt*d);\n\t\t\t\t//c12\n\t\t\tcase 37:\n\t\t\t\treturn -dampexpa*D_spt*Fd_spt*r*r*pow2(-1+x*x)*P_L(k*r)*P_L(k)/(Dd_spt*d);\n\t\t\t\t//c22\n\t\t\tcase 38:\n\t\t\t\treturn dampexpa*r*(-1+x*x)*(-2*Dd_spt*F_spt*x*d+D_spt*Fd_spt*(-2*x+2*r*r*x+3*r*(-1+x*x)))*P_L(k*r)*P_L(k)/(Dd_spt*d);\n\t\t\t\t//c33\n\t\t\tcase 39:\n\t\t\t\treturn dampexpa*D_spt*Fd_spt*r*(-1+x*x)*(-2*x+r*(-1+3*x*x))*P_L(k*r)*P_L(k)/(Dd_spt*d);\n\t\t\tdefault:\n\t\t\twarning(\"SPT: invalid indices, a = %d\\n\", a);\n\t\t\t\treturn 0;\n      }\n}\n\n\n\n\n/* function to select multipole or u-dependent Redshift PS */\n// it gives either u^(2n) or factL(k, u(i.e.sigma_v), n, a, b, e, f) - see factL\n\n// e = 0:  RSD PS\n// e = 1 : Monopole\n// e = 2 : Quadrupole\n// e = 3 : Hexdecapole\n\n\n\n// e = 3 : Hexdecapole\n\n\nstatic real u0(real k, real u,real F0, int n, int a){\n\tif (a >= 1) {\n\t\treturn factL(k,u,F0,1.,n,a,6); }\n\t\telse\n\t\t\treturn pow(u,2*n);\n}\n\n\nstatic real midintabc(real bl, int a, const PowerSpectrum& P_L, real k, real u, real r) {\n  real KMAX = QMAXp/k;\n  real KMIN = QMINp/k;\n\treal YMIN = Max(XMIN, (1.+r*r-KMAX*KMAX)/2./r);\n  real YMAX = ATS(k,r);\n\treal F0 =rempfr*fdgp_spt;\n  real D1 = D_spt;\n  real X1 = 1;\n  real u01 = u0(k,u,F0,1,a);\n  real u02 = u0(k,u,F0,2,a);\n  real u03 = u0(k,u,F0,3,a);\n  real u04 = u0(k,u,F0,4,a);\n\n\t//A term\n\t\treturn     pow4(D1/dnorm_spt)*2.*(F0*u01*pow2(bl)*(Integrate(bind(ABC,1, cref(P_L), k, r, _1),  YMIN, YMAX ,  1e-3*P_L(k))\n\t\t\t\t\t\t\t\t\t\t   + Integrate(bind(ABC,5, cref(P_L), k,  r, _1),  YMIN, YMAX ,  1e-3*P_L(k))\n\t\t\t\t\t\t\t\t\t\t   + Integrate(bind(ABC,10, cref(P_L), k, r, _1),  YMIN, YMAX ,  1e-3*P_L(k)))\n\n\t\t\t\t\t\t\t+ F0*F0*u01*bl*(Integrate(bind(ABC,2, cref(P_L), k,  r, _1),  YMIN, YMAX , 1e-3*P_L(k))\n\t\t\t\t\t\t\t\t\t\t   + Integrate(bind(ABC,6, cref(P_L), k,  r, _1), YMIN, YMAX ,  1e-3*P_L(k))\n\t\t\t\t\t\t\t\t\t\t   + Integrate(bind(ABC,11, cref(P_L), k,  r, _1), YMIN, YMAX ,  1e-3*P_L(k)))\n\n\t\t\t\t\t\t\t+ F0*F0*u02*bl*(Integrate(bind(ABC,3, cref(P_L), k,  r, _1),   YMIN, YMAX , 1e-3*P_L(k))\n\t\t\t\t\t\t\t\t\t\t   + Integrate(bind(ABC,7, cref(P_L), k,  r, _1),   YMIN, YMAX ,  1e-3*P_L(k))\n\t\t\t\t\t\t\t\t\t\t   + Integrate(bind(ABC,12, cref(P_L), k,  r, _1),  YMIN, YMAX ,  1e-3*P_L(k)))\n\n\t\t\t\t\t     + F0*F0*F0*u02*(Integrate(bind(ABC,2, cref(P_L), k,  r, _1),  YMIN, YMAX ,  1e-3*P_L(k))\n\t\t\t\t\t\t\t\t\t\t   + Integrate(bind(ABC,8, cref(P_L), k,  r, _1),   YMIN, YMAX ,  1e-3*P_L(k))\n\t\t\t\t\t\t\t\t\t\t   + Integrate(bind(ABC,11, cref(P_L), k, r, _1), YMIN, YMAX ,  1e-3*P_L(k)))\n\n\t\t\t\t\t\t   + F0*F0*F0*u03*(Integrate(bind(ABC,4, cref(P_L), k, r, _1),   YMIN, YMAX , 1e-3*P_L(k))\n\t\t\t\t\t\t\t\t\t\t   + Integrate(bind(ABC,9, cref(P_L), k,  r, _1),  YMIN, YMAX ,  1e-3*P_L(k))\n\t\t\t\t\t\t\t\t\t\t   + Integrate(bind(ABC,13, cref(P_L), k,  r, _1),YMIN, YMAX ,  1e-3*P_L(k))))\n\n\t//B term\n\t\t  +      pow4(D1/dnorm_spt)*2*(F0*F0*pow2(bl)*u01*Integrate(bind(ABC,14,  cref(P_L), k, r, _1), YMIN, YMAX , 1e-3* P_L(k))\n\n\t\t\t\t\t\t  -F0*F0*F0*bl*u01*(Integrate(bind(ABC,15, cref(P_L), k, r, _1), YMIN, YMAX , 1e-3*P_L(k))\n\t\t\t\t\t\t\t\t\t\t\t    +Integrate(bind(ABC,16, cref(P_L),  k,  r, _1),YMIN, YMAX , 1e-3*P_L(k)))\n\n\t\t\t\t\t\t+F0*F0*F0*F0*u01*Integrate(bind(ABC,17, cref(P_L),  k, r, _1), YMIN, YMAX , 1e-3*P_L(k))\n\n\t\t\t\t\t\t\t  +F0*F0*pow2(bl)*u02*Integrate(bind(ABC,18,  cref(P_L), k,  r, _1),YMIN, YMAX ,  1e-3*P_L(k))\n\n\t\t\t\t\t\t -F0*F0*F0*bl*u02*(Integrate(bind(ABC,19, cref(P_L), k,  r, _1), YMIN, YMAX , 1e-3*P_L(k))\n\t\t\t\t\t\t\t\t\t\t      + Integrate(bind(ABC,20, cref(P_L),  k,  r, _1), YMIN, YMAX ,  1e-3*P_L(k)))\n\n\t\t\t\t\t  +F0*F0*F0*F0*u02*Integrate(bind(ABC,21, cref(P_L),  k,  r, _1),YMIN, YMAX , 1e-3*P_L(k))\n\n\t\t\t\t\t    - F0*F0*F0*bl*u03*(Integrate(bind(ABC,22,  cref(P_L), k,  r, _1), YMIN, YMAX ,  1e-3*P_L(k))\n\t\t\t\t\t\t\t\t\t\t\t  + Integrate(bind(ABC,23,  cref(P_L), k,  r, _1), YMIN, YMAX , 1e-3*P_L(k)))\n\n\t\t\t\t\t  + F0*F0*F0*F0*u03*Integrate(bind(ABC,24,  cref(P_L), k,  r, _1),YMIN, YMAX ,  1e-3*P_L(k))\n\n\t\t\t\t\t\t\t+F0*F0*F0*F0*u04*Integrate(bind(ABC,25,  cref(P_L), k,  r, _1), YMIN, YMAX , 1e-3*P_L(k)))\n\n\t//C - nDGP analytic\n\n\t\t  +       X1*D1*D1*2/pow4(dnorm_spt)*(F0*pow2(bl)*u01*(Integrate(bind(ABC,26, cref(P_L), k, r, _1),   YMIN, YMAX ,  1e-3*P_L(k))\n\t\t\t\t\t\t\t\t\t\t+ Integrate(bind(ABC,31, cref(P_L), k, r, _1),   YMIN, YMAX ,  1e-3*P_L(k))\n\t\t\t\t\t\t\t\t\t\t+ Integrate(bind(ABC,36, cref(P_L), k, r, _1), YMIN, YMAX ,  1e-3*P_L(k))) +\n\n\t\t\t\t\t\t\tF0*F0*bl*u01*(Integrate(bind(ABC,27, cref(P_L), k, r, _1),   YMIN, YMAX ,  1e-3*P_L(k))\n\t\t\t\t\t\t\t\t\t\t+ Integrate(bind(ABC,32, cref(P_L), k, r, _1),   YMIN, YMAX ,  1e-3*P_L(k))\n\t\t\t\t\t\t\t\t\t\t+ Integrate(bind(ABC,37, cref(P_L), k, r, _1),  YMIN, YMAX ,  1e-3*P_L(k))) +\n\n\t\t\t\t\t\t   F0*F0*bl*u02*(Integrate(bind(ABC,28, cref(P_L), k, r, _1),   YMIN, YMAX ,  1e-3*P_L(k))\n\t\t\t\t\t\t\t\t\t\t+ Integrate(bind(ABC,33, cref(P_L), k, r, _1),   YMIN, YMAX ,  1e-3*P_L(k))\n\t\t\t\t\t\t\t\t\t\t+ Integrate(bind(ABC,38, cref(P_L), k,  r, _1), YMIN, YMAX ,  1e-3*P_L(k))) +\n\n\t\t\t\t\t\tF0*F0*F0*u02*(Integrate(bind(ABC,29, cref(P_L), k, r, _1),   YMIN, YMAX ,  1e-3*P_L(k))\n\t\t\t\t\t\t\t\t\t\t+ Integrate(bind(ABC,34, cref(P_L), k, r, _1),   YMIN, YMAX ,  1e-3*P_L(k))\n\t\t\t\t\t\t\t\t\t\t+ Integrate(bind(ABC,37, cref(P_L), k,  r, _1),  YMIN, YMAX ,  1e-3*P_L(k))) +\n\n\t\t\t\t\t   F0*F0*F0*u03*(Integrate(bind(ABC,30, cref(P_L), k, r, _1),   YMIN, YMAX ,  1e-3*P_L(k))\n\t\t\t\t\t\t\t\t\t   + Integrate(bind(ABC,35, cref(P_L), k, r, _1),   YMIN, YMAX ,  1e-3*P_L(k))\n\t\t\t\t\t\t\t\t\t   + Integrate(bind(ABC,39, cref(P_L), k,  r, _1),  YMIN, YMAX ,  1e-3*P_L(k))));\n\n}\n\n\n\n/* Non vanishing A, B and C terms */\n//numerical calculations\n// Notes for numerical AB terms : DEFINITION OF THETA=  DEL V / aH (and is accounted for in definition of Cross Bispectrum)\n// Integrating them over angle\nstatic real ABCn(double u0x[], int y, real bl, int a, const PowerSpectrum& P_L, real k, real u, real r) {\n  double myresult = 0.;\n\tdouble temp_abc;\n  double abc[10];\n  // Set the limits of angular integration\n  double KMAX = QMAXp/k;\n  double KMIN = QMINp/k;\n  double YMIN = Max(XMIN, (1.+r*r-KMAX*KMAX)/2./r);\n  double YMAX = ATS(k,r);\n  // Multipole factors\n  real u01 = u0x[0];//u0(k,u,fl_spt,1,a);\n  real u02 = u0x[1];//u0(k,u,fl_spt,2,a);\n  real u03 = u0x[2];//u0(k,u,fl_spt,3,a);\n  real u04 = u0x[3];//u0(k,u,fl_spt,4,a);\n  // Find those corresponding limits in the GL Quad abscissae (See SpecialFunctions.h)\n  int x_min = searchnearest(x128, YMIN);\n  int x_max = searchnearest(x128, YMAX);\n  for( int i = x_min; i <= x_max; i++ )\n    \t\t\t\t{\n    \t\t \t\tdouble x = x128[i];\n    \t\t \t\tdouble d = 1+ r*r - 2*r*x;\n    \t\t \t\tif(d < 1e-5){\n    \t\t\t \ttemp_abc=0.;\n    \t\t \t\t}\n    \t\t  \telse {\n              // 1st order kernels F1/G1(k-p)\n              abc[0] = F1kmp_nk[i*n2 + y];\n              abc[1] = G1kmp_nk[i*n2 + y]/bl;\n              // 1st order kernels F1/G1(p)\n              abc[2] = F1p_nk[i*n2 + y];\n              abc[3] = G1p_nk[i*n2 + y]/bl;\n              //symmetrized 2nd order kernels for ps F2/G2(p,k-p)\n              abc[4] = F2_nk[i*n2 + y];\n              abc[5] = G2_nk[i*n2 + y]/bl;\n              //symmetrized 2nd order kernels F2/G2(-p,k)\n              abc[6] = F2B_nk[i*n2 + y];\n              abc[7] = G2B_nk[i*n2 + y]/bl;\n              //symmetrized 2nd order kernels F2/G2(-k,k-p)\n              abc[8] = F2C_nk[i*n2 + y];\n              abc[9] = G2C_nk[i*n2 + y]/bl;\n\n              double dampexpa = exp(-pow2(F1_nk/dnorm_spt)*damp_term(k*r)/2.-pow2(F1_nk/dnorm_spt)*damp_term(k*sqrt(d))/2.-pow2(F1_nk/dnorm_spt)*damp_term(k)/2.);\n              double dampexpb = exp(-pow2(F1_nk/dnorm_spt)*damp_term(k*sqrt(d))-pow2(F1_nk/dnorm_spt)*damp_term(k*r));\n\n// A terms\n//u^2\n    \t\t  temp_abc =  pow3(bl)*dampexpa/d*(-u01*(F1_nk*r*(-2*abc[8]*abc[1]*r*(r*x-1)+abc[9]*(2*abc[0]*x*d+abc[1]*r*(1-x*x)))*P_L(k)*P_L(k*sqrt(d))\n            \t\t\t\t\t\t+ abc[4]*r*(-2*abc[2]*abc[1]*r*(-1+r*x)+abc[3]*(2*abc[0]*x*d+abc[1]*r*(1-x*x)))*P_L(k*r)*P_L(k*sqrt(d))\n            \t\t\t\t\t\t+ F1_nk*r*(-2*abc[7]*abc[2]*r*(r*x-1)+abc[3]*(2*abc[6]*x*d+abc[7]*r*(1-x*x)))*P_L(k)*P_L(k*r))\n//u^4\n            -u02*(r*(2*abc[8]*G1_nk/bl*abc[1]*r*(r*x-1)+abc[9]*(G1_nk/bl*(-2*abc[0]*x*d+abc[1]*r*(x*x-1))+F1_nk*abc[1]*(-2*x+r*(-1+3*x*x))))*P_L(k)*P_L(k*sqrt(d))\n                           +r*(abc[4]*abc[1]*abc[3]*(-2*x+r*(-1+3*x*x))+abc[5]*(2*abc[2]*abc[1]*r*(r*x-1)+abc[3]*(-2*abc[0]*x*d+abc[1]*r*(x*x-1))))*P_L(k*r)*P_L(k*sqrt(d))\n                           +r*(abc[3]*abc[7]*F1_nk*(-2*x-r+3*x*x*r)+2*abc[2]*G1_nk/bl*abc[7]*r*(r*x-1)+G1_nk/bl*abc[3]*(-2*abc[6]*x*d+abc[7]*r*(x*x-1)))*P_L(k)*P_L(k*r))\n//u^6\n           -u03*(G1_nk/bl*abc[1]*abc[9]*r*(r+2*x-3*r*x*x)*P_L(k)*P_L(k*sqrt(d))\n                        +abc[3]*abc[1]*abc[5]*r*(r+2*x-3*r*x*x)*P_L(k*r)*P_L(k*sqrt(d))\n                        +abc[3]*G1_nk/bl*abc[7]*r*(r+2*x-3*r*x*x)*P_L(k*r)*P_L(k)))\n\n\n// B terms\n          +pow4(bl)*dampexpb*P_L(k*r)*P_L(k*sqrt(d))/(16.*d*d)*\n//u^2\n          (u01*(abc[1]*abc[3]*r*r*(x*x-1)*(2*abc[0]*d*(4*abc[2]+3*abc[3]*(x*x-1))\n                         +abc[1]*r*r*(x*x-1)*(6*abc[2]+5*abc[3]*(x*x-1))))\n//u^4\n          +u02*(abc[1]*abc[3]*r*(-4*abc[0]*d*(3*abc[3]*(x*x-1)*(-2*x+r*(5*x*x-1))+abc[2]*(-4*x+r*(-2+6*x*x)))\n                \t\t\t\t\t   -3*abc[1]*r*(x*x-1)*(4*abc[2]*(2-6*r*x+r*r*(-1+5*x*x))\n                \t\t\t\t\t\t +abc[3]*(x*x-1)*(6-30*r*x+5*r*r*(-1+7*x*x)))))\n//u^6\n          +u03*(abc[1]*abc[3]*r*(3*abc[3]*abc[1]*(x*x-1)*(-8*x+12*r*(5*x*x-1)-20*r*r*x*(7*x*x-3)+5*pow3(r)*(1-14*x*x+21*pow4(x)))\n                              +2*abc[0]*abc[3]*(4*x*(3-5*x*x)+pow3(r)*(3-30*x*x+35*pow4(x))+r*(3-54*x*x+75*pow4(x))+r*r*(6*x+40*pow3(x)-70*pow5(x)))\n                              +2*abc[2]*abc[1]*(-8*x+12*r*(3*x*x-1)+r*r*(36*x-60*pow3(x))+pow3(r)*(3-30*x*x+35*pow4(x)))))\n//u^8\n          +u04*(pow2(abc[1]*abc[3])*r*(8*x*(5*x*x-3)-6*r*(3-30*x*x+35*pow4(x))\n                     \t\t\t\t+6*r*r*x*(15-70*x*x+63*pow4(x))  \t\t// HAVE INCLUDED THE 'TYPO' IN TERM : 6rr -> 6rrx\n                     \t\t\t\t+pow3(r)*(5-105*x*x+315*pow4(x)-231*pow6(x)))));\n    \t\t\t\t}\n    \t\t\t\tmyresult += w128[i] * temp_abc;\n    \t\t\t\t}\n          return  2*myresult;\n}\n\n/*Generalised A and B correction term */\n\n/*Analytical A and B*/\n// a = 1 : LCDM\n// a = 2 : MG\n\n// e = 0:  RSD PS\n// e = 1 : Monopole\n// e = 2 : Quadrupole\n// e = 3 : Hexdecapole\n\n//U = u for RSD PS\n//U = sigma_v for multipoles\n\nreal RegPT::ABr(real k, real bl, real U, int a) const{\n    int n3 = 300;\n    real KMAX = QMAXp/k;\n    real KMIN = QMINp/k;\n    double y[n3];\n    double integrand[n3];\n    for (int i = 0; i<n3; i++){\n    y[i] = KMIN * exp(i*log(KMAX/KMIN)/(n3-1.));\n    integrand[i] = midintabc(bl, a,cref(P_l), k, U, y[i]);\n    }\n  double res = 0.;\n    for( int i = 1; i < n3; ++ i ){\n  res += 0.5 * (y[i] - y[i-1])*(integrand[i] + integrand[i-1]);\n      }\n    return  k*k*k/(4*M_PI*M_PI) * res;\n    }\n\n\n/*Numerical A and B */\n\n// e = 0:  RSD PS\n// e = 1 : Monopole\n// e = 2 : Quadrupole\n// e = 3 : Hexdecapole\n\n//U = u for RSD PS\n//U = sigma_v for multipoles\n\nreal RegPT::ABnr(double kmin, double kmax, real bl, real k, real U, int a) const{\n\treal KMAX = QMAXp/k;\n  real KMIN = QMINp/k;\n  int y1 = num_selec_mag(kmin, kmax, KMIN);\n  int y2 = num_selec_mag(kmin, kmax, KMAX);\n  double y[n2];\n  double integrand[n2];\n  double u0x[4];\n  u0x[0]=u0(k,U,fl_spt,1,a);\n  u0x[1]=u0(k,U,fl_spt,2,a);\n  u0x[2]=u0(k,U,fl_spt,3,a);\n  u0x[3]=u0(k,U,fl_spt,4,a);\n  for (int i = y1; i<=y2; i++){\n  y[i] = QMINp/kmax * exp(i*log(QMAXp*kmax/(QMINp*kmin))/(n2*1.-1.));\n  integrand[i] = ABCn(u0x,i, bl, a, cref(P_l), k, U, y[i]);\n  }\ndouble res = 0.;\n  for( int i = y1+1; i <= y2; ++ i ){\nres += 0.5 * (y[i] - y[i-1])*(integrand[i] + integrand[i-1]);\n}\n  return  k*k*k/(4*M_PI*M_PI)/pow4(dnorm_spt) * res;\n}\n\n\n// Separation of numerical A B terms for interpolation\n\nstatic void ABnr_selec(double abarray[], int y, const PowerSpectrum& P_L, real k, real r) {\n  double myresult[14];\n  for(int ii=0;ii<14;ii++){\n    myresult[ii]=0.;\n  }\n\tdouble temp_abs[14];\n  double abc[10];\n  // Set the limits of angular integration\n  double KMAX = QMAXp/k;\n  double KMIN = QMINp/k;\n  double YMIN = Max(XMIN, (1.+r*r-KMAX*KMAX)/2./r);\n  double YMAX = ATS(k,r);\n  // Find those corresponding limits in the GL Quad abscissae (See SpecialFunctions.h)\n  int x_min = searchnearest(x128, YMIN);\n  int x_max = searchnearest(x128, YMAX);\n  for( int i = x_min; i <= x_max; i++ )\n    \t\t\t\t{\n    \t\t \t\tdouble x = x128[i];\n    \t\t \t\tdouble d = 1+ r*r - 2*r*x;\n    \t\t \t\tif(d < 1e-5){\n              for(int ii=0;ii<14;ii++){\n                temp_abs[ii]=0.;\n              }\n    \t\t \t\t}\n    \t\t  \telse {\n              // 1st order kernels F1/G1(k-p)\n              abc[0] = F1kmp_nk[i*n2 + y];\n              abc[1] = G1kmp_nk[i*n2 + y];\n              // 1st order kernels F1/G1(p)\n              abc[2] = F1p_nk[i*n2 + y];\n              abc[3] = G1p_nk[i*n2 + y];\n              //symmetrized 2nd order kernels for ps F2/G2(p,k-p)\n              abc[4] = F2_nk[i*n2 + y];\n              abc[5] = G2_nk[i*n2 + y];\n              //symmetrized 2nd order kernels F2/G2(-p,k)\n              abc[6] = F2B_nk[i*n2 + y];\n              abc[7] = G2B_nk[i*n2 + y];\n              //symmetrized 2nd order kernels F2/G2(-k,k-p)\n              abc[8] = F2C_nk[i*n2 + y];\n              abc[9] = G2C_nk[i*n2 + y];\n\n              double dampexpa = exp(-pow2(F1_nk/dnorm_spt)*damp_term(k*r)/2.-pow2(F1_nk/dnorm_spt)*damp_term(k*sqrt(d))/2.-pow2(F1_nk/dnorm_spt)*damp_term(k)/2.);\n              double dampexpb = exp(-pow2(F1_nk/dnorm_spt)*damp_term(k*sqrt(d))-pow2(F1_nk/dnorm_spt)*damp_term(k*r));\n              double prefacb = dampexpb*P_L(k*r)*P_L(k*sqrt(d))/(16.*d*d);\n//A terms\n//u^2b^2\n          temp_abs[0] =  -dampexpa/d*((F1_nk*r*(-2*abc[8]*abc[1]*r*(r*x-1)+abc[9]*2*abc[0]*x*d))*P_L(k)*P_L(k*sqrt(d))\n                                    + abc[4]*r*(-2*abc[2]*abc[1]*r*(-1+r*x)+abc[3]*2*abc[0]*x*d)*P_L(k*r)*P_L(k*sqrt(d))\n                                    +F1_nk*r*(-2*abc[7]*abc[2]*r*(r*x-1)+abc[3]*2*abc[6]*x*d)*P_L(k)*P_L(k*r));\n//u^2b\n          temp_abs[1] =  -dampexpa/d*((F1_nk*r*(abc[9]*abc[1]*r*(1-x*x))*P_L(k)*P_L(k*sqrt(d))\n            \t\t\t\t\t\t            + abc[4]*r*(abc[3]*abc[1]*r*(1-x*x))*P_L(k*r)*P_L(k*sqrt(d))\n            \t\t\t\t\t\t            + F1_nk*r*(abc[3]*abc[7]*r*(1-x*x))*P_L(k)*P_L(k*r)));\n//u^4 b\n          temp_abs[2] = -dampexpa/d*(r*(2*abc[8]*G1_nk*abc[1]*r*(r*x-1)+abc[9]*(G1_nk*(-2*abc[0]*x*d)+F1_nk*abc[1]*(-2*x+r*(-1+3*x*x))))*P_L(k)*P_L(k*sqrt(d))\n                                     +r*(abc[4]*abc[1]*abc[3]*(-2*x+r*(-1+3*x*x))+abc[5]*(2*abc[2]*abc[1]*r*(r*x-1)+abc[3]*(-2*abc[0]*x*d)))*P_L(k*r)*P_L(k*sqrt(d))\n                                     +r*(abc[3]*abc[7]*F1_nk*(-2*x-r+3*x*x*r)+2*abc[2]*G1_nk*abc[7]*r*(r*x-1)+G1_nk*abc[3]*(-2*abc[6]*x*d))*P_L(k)*P_L(k*r));\n// u^4\n          temp_abs[3] = -dampexpa/d*(r*(abc[9]*(G1_nk*(abc[1]*r*(x*x-1))))*P_L(k)*P_L(k*sqrt(d))\n                                     +r*(abc[5]*(abc[3]*(abc[1]*r*(x*x-1))))*P_L(k*r)*P_L(k*sqrt(d))\n                                     +r*(G1_nk*abc[3]*(abc[7]*r*(x*x-1)))*P_L(k)*P_L(k*r));\n\n//u^6\n          temp_abs[4] = -dampexpa/d*(G1_nk*abc[1]*abc[9]*r*(r+2*x-3*r*x*x)*P_L(k)*P_L(k*sqrt(d))\n                                  +abc[3]*abc[1]*abc[5]*r*(r+2*x-3*r*x*x)*P_L(k*r)*P_L(k*sqrt(d))\n                                  +abc[3]*G1_nk*abc[7]*r*(r+2*x-3*r*x*x)*P_L(k*r)*P_L(k));\n\n//B terms\n//u^2 b^2\n          temp_abs[5]= prefacb*(abc[1]*abc[3]*r*r*(x*x-1)*(2*abc[0]*d*(4*abc[2])));\n//u^2 b\n          temp_abs[6]= prefacb*(abc[1]*abc[3]*r*r*(x*x-1)*(2*abc[0]*d*(3*abc[3]*(x*x-1))\n                         +abc[1]*r*r*(x*x-1)*(6*abc[2])));\n//u^2\n          temp_abs[7]= prefacb*(abc[1]*abc[3]*r*r*(x*x-1)*(abc[1]*r*r*(x*x-1)*(5*abc[3]*(x*x-1))));\n//u^4b^2\n          temp_abs[8]= prefacb*(abc[1]*abc[3]*r*(-4*abc[0]*d*(abc[2]*(-4*x+r*(-2+6*x*x)))));\n//u^4 b\n          temp_abs[9]= prefacb*(abc[1]*abc[3]*r*(-4*abc[0]*d*(3*abc[3]*(x*x-1)*(-2*x+r*(5*x*x-1)))\n                \t\t\t\t\t   -3*abc[1]*r*(x*x-1)*(4*abc[2]*(2-6*r*x+r*r*(-1+5*x*x)))));\n//u^4\n          temp_abs[10]= prefacb*(abc[1]*abc[3]*r*(-3*abc[1]*r*(x*x-1)*(abc[3]*(x*x-1)*(6-30*r*x+5*r*r*(-1+7*x*x)))));\n\n//u^6 b\n          temp_abs[11] = prefacb*(abc[1]*abc[3]*r*(2*abc[0]*abc[3]*(4*x*(3-5*x*x)+pow3(r)*(3-30*x*x+35*pow4(x))+r*(3-54*x*x+75*pow4(x))+r*r*(6*x+40*pow3(x)-70*pow5(x)))\n                                +2*abc[2]*abc[1]*(-8*x+12*r*(3*x*x-1)+r*r*(36*x-60*pow3(x))+pow3(r)*(3-30*x*x+35*pow4(x)))));\n\n//u^6\n          temp_abs[12]= prefacb*(abc[1]*abc[3]*r*(3*abc[3]*abc[1]*(x*x-1)*(-8*x+12*r*(5*x*x-1)-20*r*r*x*(7*x*x-3)+5*pow3(r)*(1-14*x*x+21*pow4(x)))));\n\n//u^8\n          temp_abs[13]= prefacb*(pow2(abc[1]*abc[3])*r*(8*x*(5*x*x-3)-6*r*(3-30*x*x+35*pow4(x))\n                               \t\t\t\t+6*r*r*x*(15-70*x*x+63*pow4(x))  \t\t// HAVE INCLUDED THE 'TYPO' IN TERM : 6rr -> 6rrx\n                               \t\t\t\t+pow3(r)*(5-105*x*x+315*pow4(x)-231*pow6(x))));\n\n    \t\t\t\t}\n            for(int ii=0;ii<14;ii++){\n              myresult[ii] += w128[i]*temp_abs[ii];\n            }\n    \t\t\t\t}\n            for(int ii=0;ii<14;ii++){\n              abarray[ii]=2*myresult[ii];\n            }\n}\n\n\nvoid RegPT::ABr_selec(double myarray[], real k) const {\n  \treal KMAX = QMAXp/k;\n    real KMIN = QMINp/k;\n    int y1 = num_selec_mag(k, k, KMIN);\n    int y2 = num_selec_mag(k, k, KMAX);\n    double y[n2];\n    double integrand[n2][14];\n    double abarray[14];\n    for (int i = y1; i<=y2; i++){\n    y[i] = QMINp/k * exp(i*log(QMAXp/QMINp)/(n2*1.-1.));\n    ABnr_selec(abarray,i, cref(P_l), k, y[i]);\n    for(int ii=0;ii<14;ii++){\n    integrand[i][ii] = abarray[ii];\n      }\n    }\n  double res[14];\n  for(int ii=0;ii<14;ii++){\n    res[ii]=0.;\n  }\n    for( int i = y1+1; i <= y2; ++ i ){\n      for(int ii=0;ii<14;ii++){\n        res[ii] += 0.5 * (y[i] - y[i-1])*(integrand[i][ii] + integrand[i-1][ii]);\n      }\n  }\n  for(int ii=0;ii<14;ii++){\n    myarray[ii] = k*k*k/(4*M_PI*M_PI)/pow4(dnorm_spt) * res[ii];\n  }\n}\n", "meta": {"hexsha": "a33d18a1bdc40b25587a7b55a3fd59f3ea13e025", "size": 28519, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "reactions/src/extra_libraries/RegPT.cpp", "max_stars_repo_name": "PedroCarrilho/ReACT", "max_stars_repo_head_hexsha": "507866e9462ecf10c298fcd3e2c81249f32e7d50", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2020-07-07T11:34:02.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-15T12:48:05.000Z", "max_issues_repo_path": "reactions/src/extra_libraries/RegPT.cpp", "max_issues_repo_name": "PedroCarrilho/ReACT", "max_issues_repo_head_hexsha": "507866e9462ecf10c298fcd3e2c81249f32e7d50", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 11.0, "max_issues_repo_issues_event_min_datetime": "2020-05-29T16:26:06.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-07T08:59:52.000Z", "max_forks_repo_path": "reactions/src/extra_libraries/RegPT.cpp", "max_forks_repo_name": "PedroCarrilho/ReACT", "max_forks_repo_head_hexsha": "507866e9462ecf10c298fcd3e2c81249f32e7d50", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-08-31T15:35:28.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-31T15:35:28.000Z", "avg_line_length": 38.9603825137, "max_line_length": 244, "alphanum_fraction": 0.5342753954, "num_tokens": 12444, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7279754489059774, "lm_q2_score": 0.41869690935568665, "lm_q1q2_score": 0.30480107054375133}}
{"text": "/// Copyright (c) 2014-2016 Andrew Hundt, Johns Hopkins University\n/// \n/// @author Andrew Hundt <ATHundt@gmail.com>\n/// \n/// Dual licensed under the BSD or Apache License, Version 2.0 \n/// (the \"Licenses\") licenses at users option. Contributions shall be made such \n/// that users can continue to choose between the Licenses. \n/// You may not use this project except in compliance with the Licenses.\n/// \n/// BSD license:\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/// 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 grl Project.\n/// \n/// Apache v2 license:\n/// ------------------\n/// \n/// You may obtain a copy of the Apache License, Version 2.0 (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 RTREE_PLANNER_HPP_\n#define RTREE_PLANNER_HPP_\n\n#include <vector>\n\n#include <boost/random/mersenne_twister.hpp>\n\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/breadth_first_search.hpp>\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/dijkstra_shortest_paths.hpp>\n\n#include <boost/pending/indirect_cmp.hpp>\n#include <boost/range/irange.hpp>\n#include <boost/range/numeric.hpp>\n#include <boost/range/algorithm/transform.hpp>\n#include <boost/range/algorithm/fill.hpp>\n\n\n#include <boost/geometry.hpp>\n#include <boost/geometry/algorithms/distance.hpp>\n#include <boost/geometry/geometries/register/point.hpp>\n#include <boost/geometry/geometries/point.hpp>\n#include <boost/geometry/geometries/box.hpp>\n#include <boost/geometry/geometries/polygon.hpp>\n#include <boost/geometry/algorithms/correct.hpp>\n#include <boost/geometry/geometries/adapted/boost_array.hpp>\n#include <boost/geometry/geometries/register/linestring.hpp>\n#include <boost/geometry/index/rtree.hpp>\n\n#include <boost/math/special_functions/fpclassify.hpp>\n#include <boost/math/constants/constants.hpp>\n#include <boost/math/special_functions/sign.hpp>\n\nnamespace bg = boost::geometry;\nnamespace bgi = boost::geometry::index;\n\nBOOST_GEOMETRY_REGISTER_BOOST_ARRAY_CS(cs::cartesian)\n    \n\n\nnamespace plan {\n    \n// Define properties for vertex\n// source boost geometry graph example: https://github.com/boostorg/geometry/blob/bd9455207bb0012237c1853c3281ea95f146f91c/example/07_b_graph_route_example.cpp\ntemplate <typename Point>\nstruct bg_vertex_property\n{\n    bg_vertex_property()\n    {\n        boost::geometry::assign_zero(location);\n    }\n    bg_vertex_property(Point const& loc)\n        : location(loc)\n    {\n    }\n\n    Point location;\n};\n\n// Define properties for edge\n// source boost geometry graph example: https://github.com/boostorg/geometry/blob/bd9455207bb0012237c1853c3281ea95f146f91c/example/07_b_graph_route_example.cpp\ntemplate <typename Line>\nstruct bg_edge_property\n{\n    bg_edge_property(Line const& line)\n        : length(boost::geometry::length(line))\n        , m_line(line)\n    {\n    }\n\n    inline Line const& line() const\n    {\n        return m_line;\n    }\n\n    double length;\nprivate :\n    Line m_line;\n};\n\n    \n    //typedef bg::model::point<double, 3, bg::cs::cartesian> point;\n    typedef boost::array<double,6> ArmPos;\n    typedef ArmPos point_type;\n    typedef bg::model::box<point_type> box;\n    //typedef bg::model::referring_segment<point_type> line_type; /// @todo maybe better to use refs?\n    typedef bg::model::segment<point_type> line_type;\n    typedef line_type edge_type;\n    //typedef bg::model::polygon<point, false, false> polygon; // ccw, open polygon\n    \n    typedef boost::adjacency_list\n            <\n                boost::vecS, boost::vecS, boost::undirectedS\n                , bg_vertex_property<point_type> // bundled\n                , bg_edge_property<line_type>\n            > graph_type;\n\n    typedef boost::graph_traits<graph_type>::vertex_descriptor vertex_descriptor_type;\n    typedef bg_vertex_property<point_type>                     vertex_property_type;\n    typedef bg_edge_property<edge_type>                        edge_property_type;\n\n    typedef std::pair<point_type, vertex_descriptor_type> rtree_value;\n    typedef boost::geometry::index::rtree<rtree_value,bgi::rstar<16, 4> > knn_rtree_type;\n    \n} // namespace plan\n\n\nBOOST_GEOMETRY_REGISTER_LINESTRING(std::vector<plan::ArmPos>)\n\n\ntemplate<typename T>\ninline T normalizeRadiansPiToMinusPi(T rad)\n{\n  // copy the sign of the value in radians to the value of pi\n  T signedPI = boost::math::copysign(boost::math::constants::pi<T>(),rad);\n  // set the value of rad to the appropriate signed value between pi and -pi\n  rad = std::fmod(rad+signedPI,(boost::math::constants::two_pi<T>())) - signedPI;\n\n  return rad;\n} \n\n\n// functor for getting sum of previous result and square of current element\n// source: http://stackoverflow.com/questions/1326118/sum-of-square-of-each-elements-in-the-vector-using-for-each\ntemplate<typename T>\nstruct square\n{\n    T operator()(const T& Left, const T& Right) const\n    {   \n        return (Left + Right*Right);\n    }\n};\n\nnamespace boost { namespace geometry {\n    \n\n/// distance on an n-torus, so any dimensions offset by 2pi are equal and distances wrap\n/// @example comparable_distance(pi-.01,-pi+.01) == .02 radians \ndouble comparable_distance(plan::ArmPos const& p1, plan::ArmPos const& p2 ) {\n    plan::ArmPos diff;\n    boost::transform(p1,p2,diff.begin(),std::minus<plan::ArmPos::value_type>());\n    boost::transform(diff,diff.begin(),&normalizeRadiansPiToMinusPi<plan::ArmPos::value_type>);\n    return boost::accumulate(diff,0,square<plan::ArmPos::value_type>());\n}\n\n\n\n/// distance between a a point and an axis aligned \"box\" on the surface of an n-torus\n//  so any dimensions offset by 2pi are equal and distances wrap\ntemplate<typename Box>\ndouble comparable_distance(plan::ArmPos const& armpos, Box const& box ){\n    namespace bg = boost::geometry;\n    plan::ArmPos normAP = normalizeRadiansPiToMinusPi(armpos);\n    plan::ArmPos mindiff;\n    boost::transform(normAP,bg::get<bg::min_corner>(box),mindiff.begin(),std::minus<plan::ArmPos::value_type>());\n    boost::transform(mindiff,mindiff.begin(),&normalizeRadiansPiToMinusPi<plan::ArmPos::value_type>);\n    plan::ArmPos maxdiff;\n    boost::transform(normAP,bg::get<bg::max_corner>(box),maxdiff.begin(),std::minus<plan::ArmPos::value_type>());\n    boost::transform(maxdiff,maxdiff.begin(),&normalizeRadiansPiToMinusPi<plan::ArmPos::value_type>);\n    \n    plan::ArmPos::value_type final_distance = 0.0;\n    for(int i = 0; i < armpos.size(); ++i){\n        if(mindiff[i] >= 0.0 && maxdiff[i] <= 0.0) continue; // between the min and max means \"in the box\" for this dimension\n        plan::ArmPos::value_type min_dist = std::min(std::abs(mindiff[i]),std::abs(maxdiff[i]));\n        final_distance+=min_dist*min_dist;\n    }\n    \n    return final_distance;\n//    diff (min<D> - p<D>), (p<D> - max<D>)\n}\n\n}} // namespace boost::geometry\n\n\n/// \n/// source boost geometry graph example: https://github.com/boostorg/geometry/blob/bd9455207bb0012237c1853c3281ea95f146f91c/example/07_b_graph_route_example.cpp\ntemplate <typename Graph, typename Route>\ninline void add_edge_to_route(Graph const& graph,\n            typename boost::graph_traits<Graph>::vertex_descriptor vertex1,\n            typename boost::graph_traits<Graph>::vertex_descriptor vertex2,\n            Route& route)\n{\n    std::pair\n        <\n            typename boost::graph_traits<Graph>::edge_descriptor,\n            bool\n        > opt_edge = boost::edge(vertex1, vertex2, graph);\n    if (opt_edge.second)\n    {\n        // Get properties of edge and of vertex\n        plan::edge_property_type const& edge_prop = graph[opt_edge.first];\n        plan::bg_vertex_property\n            <\n                typename boost::geometry::point_type<plan::edge_type>::type\n            > const& vertex_prop = graph[vertex2];\n\n        // Depending on how edge connects to vertex, copy it forward or backward\n        if (boost::geometry::equals(*bg::segment_view<plan::edge_type>(edge_prop.line()).begin(), vertex_prop.location))\n        {\n            std::copy(bg::segment_view<plan::edge_type>(edge_prop.line()).begin(), bg::segment_view<plan::edge_type>(edge_prop.line()).end(),\n                std::back_inserter(route));\n        }\n        else\n        {\n            std::reverse_copy(bg::segment_view<plan::edge_type>(edge_prop.line()).begin(), bg::segment_view<plan::edge_type>(edge_prop.line()).end(),\n                std::back_inserter(route));\n        }\n    }\n}\n\n/// After running dijkstra's algorithm build list of shortest path steps between start and end position.\n/// @note there will be duplicate positions that should be removed.\n/// source boost geometry graph example: https://github.com/boostorg/geometry/blob/bd9455207bb0012237c1853c3281ea95f146f91c/example/07_b_graph_route_example.cpp\ntemplate <typename Graph, typename Route>\ninline void build_route(Graph const& graph,\n            std::vector<typename boost::graph_traits<Graph>::vertex_descriptor> const& predecessors,\n            typename boost::graph_traits<Graph>::vertex_descriptor vertex1,\n            typename boost::graph_traits<Graph>::vertex_descriptor vertex2,\n            Route& route)\n{\n    typedef typename boost::graph_traits<Graph>::vertex_descriptor vertex_type;\n    vertex_type pred = predecessors[vertex2];\n\n    add_edge_to_route(graph, pred, vertex2, route);\n    while (pred != vertex1)\n    {\n        add_edge_to_route(graph, predecessors[pred], pred, route);\n        pred = predecessors[pred];\n    }\n}\n\n#endif", "meta": {"hexsha": "2f4d1b0f2d63645c1572434cae35b36327bdadd2", "size": 11158, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/grl/rtree_graph_planner.hpp", "max_stars_repo_name": "hany606/grl", "max_stars_repo_head_hexsha": "b99ee6fa72163f22dddc5547a09a461a914889ac", "max_stars_repo_licenses": ["BSD-2-Clause", "Apache-2.0"], "max_stars_count": 140.0, "max_stars_repo_stars_event_min_datetime": "2015-03-28T21:30:26.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-16T18:43:11.000Z", "max_issues_repo_path": "include/grl/rtree_graph_planner.hpp", "max_issues_repo_name": "hany606/grl", "max_issues_repo_head_hexsha": "b99ee6fa72163f22dddc5547a09a461a914889ac", "max_issues_repo_licenses": ["BSD-2-Clause", "Apache-2.0"], "max_issues_count": 173.0, "max_issues_repo_issues_event_min_datetime": "2015-03-28T21:56:54.000Z", "max_issues_repo_issues_event_max_datetime": "2020-06-25T17:29:02.000Z", "max_forks_repo_path": "include/grl/rtree_graph_planner.hpp", "max_forks_repo_name": "hany606/grl", "max_forks_repo_head_hexsha": "b99ee6fa72163f22dddc5547a09a461a914889ac", "max_forks_repo_licenses": ["BSD-2-Clause", "Apache-2.0"], "max_forks_count": 68.0, "max_forks_repo_forks_event_min_datetime": "2015-04-03T20:37:12.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-02T20:59:11.000Z", "avg_line_length": 39.5673758865, "max_line_length": 160, "alphanum_fraction": 0.7106112206, "num_tokens": 2649, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6001883735630721, "lm_q2_score": 0.5078118642792044, "lm_q1q2_score": 0.3047827768977672}}
{"text": "//==============================================================================\n//         Copyright 2003 - 2012   LASMEA UMR 6602 CNRS/Univ. Clermont II\n//         Copyright 2009 - 2012   LRI    UMR 8623 CNRS/Univ Paris Sud XI\n//\n//          Distributed under the Boost Software License, Version 1.0.\n//                 See accompanying file LICENSE.txt or copy at\n//                     http://www.boost.org/LICENSE_1_0.txt\n//==============================================================================\n#ifndef NT2_LINALG_FUNCTIONS_TIED_BALANCE_HPP_INCLUDED\n#define NT2_LINALG_FUNCTIONS_TIED_BALANCE_HPP_INCLUDED\n\n#include <nt2/linalg/functions/balance.hpp>\n\n#include <nt2/include/functions/colon.hpp>\n#include <nt2/include/functions/colvect.hpp>\n#include <nt2/include/functions/eye.hpp>\n#include <nt2/include/functions/gebak.hpp>\n#include <nt2/include/functions/gebal.hpp>\n#include <nt2/include/functions/height.hpp>\n#include <nt2/include/functions/is_nez.hpp>\n#include <nt2/include/functions/issquare.hpp>\n#include <nt2/include/functions/of_size.hpp>\n#include <nt2/include/functions/ones.hpp>\n#include <nt2/include/functions/real.hpp>\n#include <nt2/include/functions/resize.hpp>\n#include <nt2/include/functions/tie.hpp>\n#include <nt2/linalg/details/utility/lapack_verify.hpp>\n#include <nt2/sdk/meta/as_integer.hpp>\n#include <nt2/sdk/meta/as_real.hpp>\n#include <nt2/linalg/options.hpp>\n#include <nt2/core/container/table/table.hpp>\n#include <nt2/core/container/colon/colon.hpp>\n#include <nt2/core/container/dsl/as_terminal.hpp>\n#include <boost/assert.hpp>\n#include <boost/dispatch/attributes.hpp>\n\nnamespace nt2 { namespace ext\n{\n  //============================================================================\n  //BALANCE Scalar\n  //============================================================================\n  BOOST_DISPATCH_IMPLEMENT  ( balance_, tag::cpu_\n                            , (A0)\n                            , (scalar_<unspecified_<A0> >)\n                            )\n  {\n    typedef A0 result_type;\n\n    BOOST_FORCEINLINE result_type operator()(const A0& a0) const\n    {\n      return a0;\n    }\n  };\n\n  BOOST_DISPATCH_IMPLEMENT  ( balance_, tag::cpu_\n                            , (A0)(A1)\n                            , (scalar_<unspecified_<A0> >)\n                              (unspecified_<A1>)\n                            )\n  {\n    typedef A0 result_type;\n\n    BOOST_FORCEINLINE result_type operator()(const A0& a0, const A1&) const\n    {\n      return a0;\n    }\n  };\n\n\n  //============================================================================\n  //BALANCE\n  //============================================================================\n  BOOST_DISPATCH_IMPLEMENT  ( balance_, tag::cpu_\n                            , (A0)(N0)(A1)(N1)\n                            , ((node_<A0, nt2::tag::balance_\n                                    , N0, nt2::container::domain\n                                      >\n                              ))\n                              ((node_<A1, nt2::tag::tie_\n                                    , N1, nt2::container::domain\n                                     >\n                              ))\n                            )\n  {\n    typedef void  result_type;\n    typedef typename boost::proto::result_of::child_c<A0&,0>::value_type child0;\n    typedef typename child0::value_type                                  type_t;\n    typedef typename meta::as_real<type_t>::type                        rtype_t;\n    typedef typename meta::as_integer<rtype_t>::type                    itype_t;\n    typedef nt2::memory::container<tag::table_,  type_t, nt2::_2D>   o_semantic;\n    typedef nt2::memory::container<tag::table_, rtype_t, nt2::_2D>   r_semantic;\n\n    BOOST_FORCEINLINE result_type operator()( A0& a0, A1& a1 ) const\n    {\n      eval(a0, a1, N0(), N1());\n    }\n  private:\n    //==========================================================================\n    /// INTERNAL ONLY - B = BALANCE(A)\n    BOOST_FORCEINLINE\n    void eval ( A0& a0, A1& a1\n              , boost::mpl::long_<1> const&\n              , boost::mpl::long_<1> const&\n              ) const\n    {\n      eval2_1(a0, a1, nt2::both_);\n    }\n\n    /// INTERNAL ONLY - B = BALANCE(A, perm_/no_perm_/both_/none_)\n    BOOST_FORCEINLINE\n    void eval ( A0& a0, A1& a1\n              , boost::mpl::long_<2> const&\n              , boost::mpl::long_<1> const&\n              ) const\n    {\n      eval2_1(a0, a1\n             , boost::proto::value(boost::proto::child_c<1>(a0)));\n    }\n\n    //perm_\n    /// INTERNAL ONLY: 1o 2i\n    BOOST_FORCEINLINE\n    void eval2_1 ( A0& a0, A1& a1\n                   , nt2::policy<ext::perm_>\n                   ) const\n    {\n      NT2_AS_TERMINAL_INOUT(o_semantic, a, boost::proto::child_c<0>(a0), boost::proto::child_c<0>(a1));\n      BOOST_ASSERT_MSG(issquare(boost::proto::child_c<0>(a1)),\n                       \"matrix to balance must be square\");\n      nt2_la_int ilo, ihi;\n      nt2::container::table<rtype_t> scale(of_size(height(a), 1));\n      NT2_LAPACK_VERIFY(gebal(boost::proto::value(a)\n                       , boost::proto::value(scale)\n                       , ilo, ihi, 'P'));\n      boost::proto::child_c<0>(a1) = a;\n    }\n\n    //no_perm_\n    /// INTERNAL ONLY: 1o 2i\n    BOOST_FORCEINLINE\n      void eval2_1 ( A0& a0, A1& a1\n                   , nt2::policy<ext::no_perm_>\n                   ) const\n    {\n      NT2_AS_TERMINAL_INOUT(o_semantic, a, boost::proto::child_c<0>(a0), boost::proto::child_c<0>(a1));\n      BOOST_ASSERT_MSG(issquare(a),\n                       \"matrix to balance must be square\");\n      nt2_la_int ilo, ihi;\n      nt2::container::table<rtype_t> scale(of_size(height(a), 1));\n      NT2_LAPACK_VERIFY(gebal( boost::proto::value(a)\n                         , boost::proto::value(scale)\n                         , ilo, ihi, 'S'));\n      boost::proto::child_c<0>(a1) = a;\n    }\n\n    //both_\n    /// INTERNAL ONLY: 1o 2i\n    BOOST_FORCEINLINE\n      void eval2_1 ( A0& a0, A1& a1\n                   , nt2::policy<ext::both_>\n                   ) const\n    {\n      NT2_AS_TERMINAL_INOUT(o_semantic, a, boost::proto::child_c<0>(a0), boost::proto::child_c<0>(a1));\n      BOOST_ASSERT_MSG(issquare(a), \"matrix to balance must be square\");\n      nt2_la_int ilo, ihi;\n      nt2::container::table<rtype_t> scale(of_size(height(a), 1));\n      NT2_LAPACK_VERIFY(gebal(boost::proto::value(a)\n                         , boost::proto::value(scale)\n                         , ilo, ihi, 'B'));\n      boost::proto::child_c<0>(a1) = a;\n    }\n\n    // none_\n    /// INTERNAL ONLY\n    BOOST_FORCEINLINE\n      void eval2_1 ( A0& a0, A1& a1\n                   , nt2::policy<ext::none_>\n                   ) const\n    {\n      NT2_AS_TERMINAL_INOUT(o_semantic, a, boost::proto::child_c<0>(a0), boost::proto::child_c<0>(a1));\n      BOOST_ASSERT_MSG(issquare(a), \"matrix to balance must be square\");\n      boost::proto::child_c<0>(a1) = a;\n    }\n\n    //==========================================================================\n    /// INTERNAL ONLY - [T, B] = BALANCE(A)\n    // finds a similarity transformation T such\n    // that B = T\\A*T has, as nearly as possible, approximately equal\n    // row and column norms and balanced matrix B\n    BOOST_FORCEINLINE\n    void eval ( A0& a0, A1& a1\n              , boost::mpl::long_<1> const&\n              , boost::mpl::long_<2> const&\n              ) const\n    {\n      eval2_2(a0, a1, 'B');\n    }\n\n    //==========================================================================\n    /// INTERNAL ONLY - [T, B] = BALANCE(A, perm_/noperm_/both_/none_)\n    // finds a similarity transformation T such\n    // that B = T\\A*T has, as nearly as possible, approximately equal\n    // row and column norms and balanced matrix B\n    BOOST_FORCEINLINE\n    void eval ( A0& a0, A1& a1\n              , boost::mpl::long_<2> const&\n              , boost::mpl::long_<2> const&\n              ) const\n    {\n      eval2_2(a0, a1, boost::proto::value(boost::proto::child_c<1>(a0)));\n    }\n\n    /// INTERNAL ONLY\n    BOOST_FORCEINLINE\n    void eval2_2 ( A0& a0, A1& a1\n                 , char job\n                 ) const\n    {\n      NT2_AS_TERMINAL_INOUT(o_semantic, a, boost::proto::child_c<0>(a0), boost::proto::child_c<1>(a1));\n      NT2_AS_TERMINAL_OUT  (o_semantic, t, boost::proto::child_c<0>(a1));\n      BOOST_ASSERT_MSG(issquare(a),\n                       \"matrix to balance must be square\");\n      nt2_la_int ilo, ihi;\n      nt2_la_int n = height(a);\n      nt2::container::table<rtype_t> scale(of_size(n, 1));\n      NT2_LAPACK_VERIFY(gebal(boost::proto::value(a)\n                             , boost::proto::value(scale)\n                             , ilo, ihi, job));\n      t = nt2::eye(n, n, meta::as_<type_t>());\n      NT2_LAPACK_VERIFY(gebak(boost::proto::value(t)\n                             , boost::proto::value(scale)\n                             , ilo, ihi,  job, 'R'));\n      boost::proto::child_c<0>(a1) = t;\n      boost::proto::child_c<1>(a1) = a;\n    }\n\n    // both_\n    /// INTERNAL ONLY\n    BOOST_FORCEINLINE\n    void eval2_2 ( A0& a0, A1& a1\n                   , nt2::policy<ext::both_>\n                   ) const\n    {\n      eval2_2(a0, a1, 'B');\n    }\n\n    /// INTERNAL ONLY\n    BOOST_FORCEINLINE\n    void eval2_2 ( A0& a0, A1& a1\n                   , nt2::policy<ext::perm_>\n                   ) const\n    {\n      eval2_2(a0, a1, 'P');\n    }\n    /// INTERNAL ONLY\n    BOOST_FORCEINLINE\n    void eval2_2 ( A0& a0, A1& a1\n                   , nt2::policy<ext::no_perm_>\n                   ) const\n    {\n      eval2_2(a0, a1, 'S');\n    }\n    /// INTERNAL ONLY\n    BOOST_FORCEINLINE\n    void eval2_2 ( A0& a0, A1& a1\n                   , nt2::policy<ext::none_>\n                   ) const\n    {\n      NT2_AS_TERMINAL_INOUT(o_semantic, a, boost::proto::child_c<0>(a0), boost::proto::child_c<1>(a1));\n      nt2_la_int n = height(a);\n      BOOST_ASSERT_MSG(issquare(a), \"matrix to balance must be square\");\n      boost::proto::child_c<0>(a1) = nt2::eye(n, n, meta::as_<type_t>());\n      boost::proto::child_c<1>(a1) = a;\n    }\n\n    //==========================================================================\n    /// INTERNAL ONLY - [S, P, B] = BALANCE(A)\n    // finds a similarity transformation T such\n    // that B = T\\A*T has, as nearly as possible, approximately equal\n    // row and column norms and balanced matrix B\n    BOOST_FORCEINLINE\n    void eval ( A0& a0, A1& a1\n              , boost::mpl::long_<1> const&\n              , boost::mpl::long_<3> const&\n              ) const\n    {\n      eval3_2(a0, a1, 'B');\n    }\n\n    //==========================================================================\n    /// INTERNAL ONLY - [S, P, B] = BALANCE(A, perm_/noperm_/both_/none_)\n    // finds a similarity transformation T such\n    // that B = T\\A*T has, as nearly as possible, approximately equal\n    // row and column norms and balanced matrix B\n    BOOST_FORCEINLINE\n    void eval ( A0& a0, A1& a1\n              , boost::mpl::long_<2> const&\n              , boost::mpl::long_<3> const&\n              ) const\n    {\n      eval3_2(a0, a1, boost::proto::value(boost::proto::child_c<1>(a0)));\n    }\n\n    /// INTERNAL ONLY\n    BOOST_FORCEINLINE\n    void eval3_2 ( A0& a0, A1& a1, char job) const\n    {\n      typedef typename boost::proto::result_of::child_c<A1&,1>::value_type child1;\n      typedef typename child1::value_type                                 itype1_t;\n      typedef nt2::memory::container<tag::table_, itype1_t, nt2::_2D>   i_semantic;\n      NT2_AS_TERMINAL_INOUT(o_semantic, a,   boost::proto::child_c<0>(a0), boost::proto::child_c<2>(a1));\n      NT2_AS_TERMINAL_OUT  (i_semantic, ips, boost::proto::child_c<1>(a1));\n      NT2_AS_TERMINAL_OUT  (o_semantic, s,   boost::proto::child_c<0>(a1));\n      BOOST_ASSERT_MSG(issquare(a),\n                       \"matrix to balance must be square\");\n      nt2_la_int ilo, ihi;\n      nt2_la_int n = height(a);\n      nt2::container::table<rtype_t> scale(of_size(n, 1));\n      NT2_LAPACK_VERIFY(gebal(boost::proto::value(a)\n                             , boost::proto::value(scale)\n                             , ilo, ihi, job));\n      nt2::container::table<type_t> t = nt2::eye(n, n, meta::as_<type_t>());\n      NT2_LAPACK_VERIFY(gebak(boost::proto::value(t)\n                             , boost::proto::value(scale)\n                             , ilo, ihi,  job, 'R'));\n      extract_ips(ips, s, t);\n      boost::proto::child_c<0>(a1) = s;\n      boost::proto::child_c<1>(a1) = ips;\n      boost::proto::child_c<2>(a1) = a;\n    }\n\n    /// INTERNAL ONLY\n    template < class IPS,  class SCA, class T>\n    BOOST_FORCEINLINE\n    void  extract_ips(IPS& ips, SCA& sca, const T& t) const\n    {\n      size_t n =  height(t);\n      ips.resize(of_size(n, 1));\n      sca.resize(of_size(n, 1));\n      for(size_t i=1; i <= n; ++i)\n      {\n        for(size_t j=1; j <= n; ++j)\n        {\n          if(is_nez(t(i, j)))\n          {\n            ips(i) = j;\n            sca(i) = real(t(i, j));\n            break;\n          }\n        }\n      }\n    }\n\n    /// INTERNAL ONLY\n    BOOST_FORCEINLINE\n    void eval3_2 ( A0& a0, A1& a1\n                   , nt2::policy<ext::both_>\n                   ) const\n    {\n      eval3_2(a0, a1, 'B');\n    }\n\n    /// INTERNAL ONLY\n    BOOST_FORCEINLINE\n    void eval3_2 ( A0& a0, A1& a1\n                   , nt2::policy<ext::perm_>\n                   ) const\n    {\n      eval3_2(a0, a1, 'P');\n    }\n    /// INTERNAL ONLY\n    BOOST_FORCEINLINE\n    void eval3_2 ( A0& a0, A1& a1\n                   , nt2::policy<ext::no_perm_>\n                   ) const\n    {\n      eval3_2(a0, a1, 'S');\n    }\n    /// INTERNAL ONLY\n    BOOST_FORCEINLINE\n    void eval3_2 ( A0& a0, A1& a1\n                   , nt2::policy<ext::none_>\n                   ) const\n    {\n      BOOST_ASSERT_MSG(issquare(boost::proto::child_c<0>(a0)),\n                       \"matrix to balance must be square\");\n      boost::proto::child_c<2>(a1) = boost::proto::child_c<0>(a0);\n      itype_t n = height(boost::proto::child_c<0>(a0));\n      boost::proto::child_c<0>(a1) = nt2::ones(n, 1, meta::as_<type_t>());\n      boost::proto::child_c<1>(a1) = nt2::colvect(nt2::_(itype_t(1), n));\n    }\n\n\n  };\n} }\n\n#endif\n", "meta": {"hexsha": "2e7206297094ebfa5128e49ea70016c7dd706054", "size": 14139, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/core/linalg/include/nt2/linalg/functions/tied/balance.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/tied/balance.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/tied/balance.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": 35.5251256281, "max_line_length": 105, "alphanum_fraction": 0.5032887757, "num_tokens": 3877, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6001883592602049, "lm_q2_score": 0.5078118642792044, "lm_q1q2_score": 0.30478276963460155}}
{"text": "// This file is part of the pyMOR project (http://www.pymor.org).\n// Copyright 2013-2018 pyMOR developers and contributors. All rights reserved.\n// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)\n\n\n#include <deal.II/lac/dynamic_sparsity_pattern.h>\n#include <deal.II/lac/precondition.h>\n#include <deal.II/lac/solver_cg.h>\n#include <deal.II/lac/sparse_matrix.h>\n#include <deal.II/lac/vector.h>\n\n#include <pybind11/functional.h>\n#include <pybind11/numpy.h>\n#include <pybind11/operators.h>\n#include <pybind11/pybind11.h>\n\nnamespace py = pybind11;\n\ntemplate <typename Number>\nvoid bind_vector(pybind11::module& module) {\n  typedef dealii::Vector<Number> Vector;\n  typedef typename Vector::size_type size_type;\n  py::class_<Vector>(module, \"Vector\")\n      .def(py::init<>())\n      .def(py::init<const Vector&>())\n      .def(py::init<const size_type>())\n      .def(\"swap\", &Vector::swap)\n      .def(py::self == py::self)\n      .def(py::self != py::self)\n      .def(py::self * py::self)\n      .def(py::self += py::self)\n      .def(py::self -= py::self)\n      .def(py::self *= Number())\n      .def(py::self /= Number())\n      .def(\"axpy\", [](Vector& self, Number a, const Vector& x) { self.add(a, x); })\n      .def(\"norm_sqr\", &Vector::norm_sqr)\n      .def(\"mean_value\", &Vector::mean_value)\n      .def(\"norm_sqr\", &Vector::norm_sqr)\n      .def(\"l1_norm\", &Vector::l1_norm)\n      .def(\"l2_norm\", &Vector::l2_norm)\n      .def(\"lp_norm\", &Vector::lp_norm, py::arg(\"p\"))\n      .def(\"linfty_norm\", &Vector::linfty_norm)\n      .def(\"all_zero\", &Vector::all_zero)\n      .def(\"norm_sqr\", &Vector::norm_sqr)\n      .def(\"size\", &Vector::size)\n      .def(\"__getitem__\",\n           [](const Vector& s, size_type i) {\n             if (i >= s.size())\n               throw py::index_error();\n             return s[i];\n           })\n      .def(\"__setitem__\",\n           [](Vector& s, size_type i, Number v) {\n             if (i >= s.size())\n               throw py::index_error();\n             s[i] = v;\n           })\n      /// Slicing protocol (optional)\n      .def(\"__getitem__\",\n           [](const Vector& s, py::slice slice) -> Vector* {\n             std::size_t start, stop, step, slicelength;\n             if (!slice.compute(s.size(), &start, &stop, &step, &slicelength))\n               throw py::error_already_set();\n             Vector* seq = new Vector(slicelength);\n             for (int i = 0; i < slicelength; ++i) {\n               (*seq)[i] = s[start];\n               start += step;\n             }\n             return seq;\n           })\n      .def(\"__setitem__\",\n           [](Vector& s, py::slice slice, const Vector& value) {\n             std::size_t start, stop, step, slicelength;\n             if (!slice.compute(s.size(), &start, &stop, &step, &slicelength))\n               throw py::error_already_set();\n             if ((size_t)slicelength != value.size())\n               throw std::runtime_error(\"Left and right hand size of slice assignment have different sizes!\");\n             for (int i = 0; i < slicelength; ++i) {\n               s[start] = value[i];\n               start += step;\n             }\n           })\n      .def(\"__setitem__\",\n           [](Vector& s, py::slice slice, py::array_t<Number> value) {\n             std::size_t start, stop, step, slicelength;\n             py::buffer_info info = value.request();\n             if (!slice.compute(s.size(), &start, &stop, &step, &slicelength))\n               throw py::error_already_set();\n             if (slicelength != info.size) {\n               std::stringstream ss;\n               ss << \"Left and right hand size of slice assignment have different sizes!\";\n               ss << slicelength << \" vs. \" << info.ndim;\n               throw std::runtime_error(ss.str());\n             }\n             for (int i = 0; i < slicelength; ++i) {\n               s[start] = *(static_cast<Number*>(info.ptr) + i);\n               start += step;\n             }\n           })\n      /// Provide buffer access\n      .def_buffer([](Vector& m) -> py::buffer_info {\n        return py::buffer_info(&m[0],                                /* Pointer to buffer */\n                               sizeof(Number),                       /* Size of one scalar */\n                               py::format_descriptor<Number>::value, /* Python struct-style format descriptor */\n                               1,                                    /* Number of dimensions */\n                               {\n                                   m.size(),\n                               }, /* Buffer dimensions */\n                               {sizeof(Number)});\n      })\n      .def(\"__len__\", &Vector::size)\n      .def(\"__repr__\", [](const Vector& a) {\n        std::stringstream ss;\n        ss << \"<dealii.Vector<Number> with size '\" << a.size() << \"'>\";\n        return ss.str();\n      });\n}\n\ntemplate <typename Number>\nvoid bind_sparse_matrix(pybind11::module& module) {\n  typedef dealii::SparseMatrix<Number> Matrix;\n  typedef dealii::Vector<Number> Vector;\n\n  auto cg_solve = [](Matrix& self, Vector& solution, const Vector& rhs) {\n    dealii::SolverControl solver_control(20000, 1e-12);\n    dealii::SolverCG<> solver(solver_control);\n    dealii::PreconditionSSOR<> preconditioner;\n    preconditioner.initialize(self, 1.2);\n    solver.solve(self, solution, rhs, preconditioner);\n\n    // We have made one addition, though: since we suppress output from the\n    // linear solvers, we have to print the number of iterations by hand.\n    std::cout << \"   \" << solver_control.last_step() << \" CG iterations needed to obtain convergence.\" << std::endl;\n  };\n\n  py::class_<Matrix>(module, \"SparseMatrix\")\n      .def(py::init<>())\n      .def(py::init<const dealii::SparsityPattern&>())\n      .def(py::self *= Number())\n      .def(\"n\", [](const Matrix& mat) { return 0 ? mat.empty() : mat.n(); })\n      .def(\"m\", [](const Matrix& mat) { return 0 ? mat.empty() : mat.m(); })\n      .def(\"clear\", &Matrix::clear)\n      .def(\"l1_norm\", &Matrix::l1_norm)\n      .def(\"linfty_norm\", &Matrix::linfty_norm)\n      .def(\"vmult\", &Matrix::template vmult<Vector, Vector>)\n      .def(\"Tvmult\", &Matrix::template Tvmult<Vector, Vector>)\n      .def(\"get_sparsity_pattern\", &Matrix::get_sparsity_pattern, py::return_value_policy::reference)\n      .def(\"add\", (void (Matrix::*)(Number, const Matrix&)) & Matrix::template add<Number>)\n      .def(\"copy_from\", (Matrix & (Matrix::*)(const Matrix&)) & Matrix::template copy_from<Number>)\n      .def(\"cg_solve\", cg_solve);\n}\n\nPYBIND11_PLUGIN(pymor_dealii_bindings) {\n  py::module m(\"pymor_dealii_bindings\", \"Python bindings for deal.II\");\n  py::class_<dealii::SparsityPattern>(m, \"SparsityPattern\");\n  bind_vector<double>(m);\n  bind_sparse_matrix<double>(m);\n  return m.ptr();\n}\n", "meta": {"hexsha": "b977469057eb695590e70f10e7022a5bcd425665", "size": 6752, "ext": "cc", "lang": "C++", "max_stars_repo_path": "lib/bindings.cc", "max_stars_repo_name": "DavidSCN/pymor-deal.II", "max_stars_repo_head_hexsha": "e8817fbec023f317cadf231abb7f3ac6e5751611", "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": "lib/bindings.cc", "max_issues_repo_name": "DavidSCN/pymor-deal.II", "max_issues_repo_head_hexsha": "e8817fbec023f317cadf231abb7f3ac6e5751611", "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": "lib/bindings.cc", "max_forks_repo_name": "DavidSCN/pymor-deal.II", "max_forks_repo_head_hexsha": "e8817fbec023f317cadf231abb7f3ac6e5751611", "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.2, "max_line_length": 116, "alphanum_fraction": 0.5510959716, "num_tokens": 1726, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5736784220301065, "lm_q2_score": 0.5312093733737563, "lm_q1q2_score": 0.3047433550846582}}
{"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/lev2/config.h>\n#if defined(ENABLE_IGL)\n\n#include <ork/kernel/orklut.hpp>\n#include <ork/math/plane.h>\n#include <ork/lev2/gfx/meshutil/submesh.h>\n#include <ork/lev2/gfx/meshutil/igl.h>\n#include <iostream>\n\n#include <igl/collapse_edge.h>\n#include <igl/doublearea.h>\n#include <igl/edge_flaps.h>\n#include <igl/is_edge_manifold.h>\n#include <igl/is_irregular_vertex.h>\n#include <igl/is_vertex_manifold.h>\n#include <igl/PI.h>\n#include <igl/per_vertex_normals.h>\n#include <igl/per_face_normals.h>\n#include <igl/per_corner_normals.h>\n#include <igl/polygon_mesh_to_triangle_mesh.h>\n#include <igl/shortest_edge_and_midpoint.h>\n#include <igl/unique_edge_map.h>\n#include <igl/avg_edge_length.h>\n\n//#include <igl/arap.h>\n//#include <igl/boundary_facets.h>\n//#include <igl/circulation.h>\n//#include <igl/decimate.h>\n//#include <igl/exterior_edges.h>\n//#include <igl/orientable_patches.h>\n//#include <igl/randperm.h>\n//#include <igl/slice.h>\n//#include <igl/copyleft/cgal/mesh_boolean.h>\n//#include <igl/MeshBooleanType.h>\n\n#include <Eigen/Core>\n\nnamespace ork::meshutil {\n//////////////////////////////////////////////////////////////////////////////\niglmesh_ptr_t submesh::toIglMesh(int numsides) const {\n  return std::make_shared<IglMesh>(*this, numsides);\n}\n//////////////////////////////////////////////////////////////////////////////\nIglMesh::IglMesh(const Eigen::MatrixXd& verts, const Eigen::MatrixXi& faces)\n    : _verts(verts)\n    , _faces(faces) {\n  OrkAssert(_verts.cols() == 3); // make sure we have vec3's\n}\n//////////////////////////////////////////////////////////////////////////////\nIglMesh::IglMesh(const submesh& inp_submesh, int numsides)\n    : _verts(inp_submesh._vtxpool.GetNumVertices(), 3)\n    , _faces(inp_submesh.GetNumPolys(numsides), numsides) {\n  size_t numverts = inp_submesh._vtxpool.GetNumVertices();\n  size_t numfaces = inp_submesh.GetNumPolys(numsides);\n  _verts          = Eigen::MatrixXd(numverts, 3);\n  _normals        = Eigen::MatrixXd(numverts, 3);\n  _binormals      = Eigen::MatrixXd(numverts, 3);\n  _tangents       = Eigen::MatrixXd(numverts, 3);\n  _uvs            = Eigen::MatrixXd(numverts, 2);\n  _colors         = Eigen::MatrixXd(numverts, 4);\n  _faces          = Eigen::MatrixXi(numfaces, numsides);\n  ///////////////////////////////////////////////\n  // fill in vertices\n  ///////////////////////////////////////////////\n  for (int v = 0; v < numverts; v++) {\n    const auto& inpvtx = inp_submesh._vtxpool.GetVertex(v);\n    const auto& inpuv  = inpvtx.mUV[0];\n    _verts.row(v) << inpvtx.mPos.x, inpvtx.mPos.y, inpvtx.mPos.z;\n    _normals.row(v) << inpvtx.mNrm.x, inpvtx.mNrm.y, inpvtx.mNrm.z;\n    _binormals.row(v) << inpuv.mMapBiNormal.x, inpuv.mMapBiNormal.y, inpuv.mMapBiNormal.z;\n    _tangents.row(v) << inpuv.mMapTangent.x, inpuv.mMapTangent.y, inpuv.mMapTangent.z;\n    _uvs.row(v) << inpuv.mMapTexCoord.x, inpuv.mMapTexCoord.y;\n    _colors.row(v) << inpvtx.mCol[0].x, inpvtx.mCol[0].y, inpvtx.mCol[0].z, inpvtx.mCol[0].w;\n  }\n  ///////////////////////////////////////////////\n  // fill in faces\n  ///////////////////////////////////////////////\n  orkvector<int> face_indices;\n  inp_submesh.FindNSidedPolys(face_indices, numsides);\n  for (int f = 0; f < face_indices.size(); f++) {\n    const auto& face = inp_submesh.RefPoly(f);\n    switch (numsides) {\n      case 3:\n        _faces.row(f) <<         //\n            face.GetVertexID(0), // tri index 0\n            face.GetVertexID(1), // tri index 1\n            face.GetVertexID(2); // tri index 2\n        break;\n      case 4:\n        _faces.row(f) <<         //\n            face.GetVertexID(0), // tri index 0\n            face.GetVertexID(1), // tri index 1\n            face.GetVertexID(2), // tri index 2\n            face.GetVertexID(3); // tri index 3\n        break;\n      default:\n        OrkAssert(false);\n        break;\n    }\n  }\n}\n//////////////////////////////////////////////////////////////////////////////\nsize_t IglMesh::numFaces() const {\n  return _faces.rows();\n}\n//////////////////////////////////////////////////////////////////////////////\nsize_t IglMesh::numVertices() const {\n  return _verts.rows();\n}\n//////////////////////////////////////////////////////////////////////////////\nunique_edges_ptr_t IglMesh::uniqueEdges() const {\n  auto rval = std::make_shared<UniqueEdges>();\n  igl::unique_edge_map(_faces, rval->E, rval->uE, rval->EMAP, rval->_ue2e);\n  rval->_count = rval->uE.rows();\n  return rval;\n}\n//////////////////////////////////////////////////////////////////////////////\nsize_t IglMesh::numEdges() const {\n  return uniqueEdges()->_count;\n}\n//////////////////////////////////////////////////////////////////////////////\nsize_t IglMesh::sidesPerFace() const {\n  return _faces.cols();\n}\n//////////////////////////////////////////////////////////////////////////////\nbool IglMesh::isVertexManifold() const {\n  Eigen::MatrixXi B;\n  return igl::is_vertex_manifold(_faces, B);\n}\n//////////////////////////////////////////////////////////////////////////////\nbool IglMesh::isEdgeManifold() const {\n  return igl::is_edge_manifold(_faces);\n}\n//////////////////////////////////////////////////////////////////////////////\ndouble IglMesh::averageEdgeLength() const {\n  return igl::avg_edge_length(_verts, _faces);\n}\n//////////////////////////////////////////////////////////////////////////////\nfvec4 IglMesh::computeAreaStatistics() const {\n  Eigen::VectorXd area;\n  igl::doublearea(_verts, _faces, area);\n  area              = area.array() / 2;\n  double area_avg   = area.mean();\n  double area_min   = area.minCoeff() / area_avg;\n  double area_max   = area.maxCoeff() / area_avg;\n  double area_sigma = sqrt(((area.array() - area_avg) / area_avg).square().mean());\n  return fvec4(area_min, area_max, area_avg, area_sigma);\n}\n//////////////////////////////////////////////////////////////////////////////\nfvec4 IglMesh::computeAngleStatistics() const {\n  Eigen::MatrixXd angles;\n  igl::internal_angles(_verts, _faces, angles);\n  angles             = 360.0 * (angles / (2 * igl::PI)); // Convert to degrees\n  double angle_avg   = angles.mean();\n  double angle_min   = angles.minCoeff();\n  double angle_max   = angles.maxCoeff();\n  double angle_sigma = sqrt((angles.array() - angle_avg).square().mean());\n  return fvec4(angle_min, angle_max, angle_avg, angle_sigma);\n}\n//////////////////////////////////////////////////////////////////////////////\nsize_t IglMesh::countIrregularVertices() const {\n  // Count the number of irregular vertices, the border is ignored\n  auto irregular                = igl::is_irregular_vertex(_verts, _faces);\n  size_t vertex_count           = _verts.rows();\n  size_t irregular_vertex_count = std::count(\n      irregular.begin(), //\n      irregular.end(),\n      true);\n  return irregular_vertex_count;\n}\n//////////////////////////////////////////////////////////////////////////////\nsize_t IglMesh::genus() const {\n\n  // an orientable 2-manifold mesh M with g“handles” (i.e., genus)\n  // has Euler-Poincaré characteristic χ(M) = V-E+F = 2(1-g)\n\n  // 2(1-g)=v-e+f     : 2-2g == Euler-Poincaré characteristic\n  //-2g=v-e+f-2\n  // 2g=-v+e-f+2\n  // 2g=2+e-f-v\n  // g = (2+e-f-v)/2\n  const size_t this_genus = (2 + numEdges() - numFaces() - numVertices()) / 2;\n  return this_genus;\n}\n//////////////////////////////////////////////////////////////////////////////\nsubmesh_ptr_t IglMesh::toSubMesh() const {\n  auto subm           = std::make_shared<submesh>();\n  size_t numFaces     = this->numFaces();\n  size_t sidesPerFace = this->sidesPerFace();\n  OrkAssert(sidesPerFace == 3 or sidesPerFace == 4);\n  /////////////////////////////////////////////\n  std::vector<vertex> submeshverts;\n  submeshverts.resize(numFaces * sidesPerFace);\n  /////////////////////////////////////////////\n  OrkAssert(_verts.cols() == 3); // make sure we have vec3's\n  size_t numVerts     = _verts.rows();\n  size_t numNormals   = _normals.rows();\n  size_t numBinormals = _binormals.rows();\n  size_t numTangents  = _tangents.rows();\n  size_t numUvs       = _uvs.rows();\n  size_t numColors    = _colors.rows();\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    /////////////////////////////////////////////\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 = subm->newMergeVertex(generateVertex(f, 0));\n        auto o1 = subm->newMergeVertex(generateVertex(f, 1));\n        auto o2 = subm->newMergeVertex(generateVertex(f, 2));\n        subm->MergePoly(poly(o0, o1, o2));\n        break;\n      }\n      case 4: {\n        auto o0 = subm->newMergeVertex(generateVertex(f, 0));\n        auto o1 = subm->newMergeVertex(generateVertex(f, 1));\n        auto o2 = subm->newMergeVertex(generateVertex(f, 2));\n        auto o3 = subm->newMergeVertex(generateVertex(f, 3));\n        subm->MergePoly(poly(o0, o1, o2, o3));\n        break;\n      }\n      default:\n        OrkAssert(false);\n        break;\n    }\n  }\n  return subm;\n}\n//////////////////////////////////////////////////////////////////////////////\niglmesh_ptr_t IglMesh::triangulated() const {\n  auto rval = std::make_shared<IglMesh>();\n  igl::polygon_mesh_to_triangle_mesh(_faces, rval->_faces);\n  rval->_verts = _verts;\n  return rval;\n}\n//////////////////////////////////////////////////////////////////////////////\niglmesh_ptr_t IglMesh::decimated(float amount) const {\n  auto rval = std::make_shared<IglMesh>();\n  Eigen::MatrixXd V;\n  Eigen::MatrixXi F;\n  Eigen::MatrixXd OV = _verts;\n  Eigen::MatrixXi OF = _faces;\n  // Prepare array-based edge data structures and priority queue\n  Eigen::VectorXi EMAP;\n  Eigen::MatrixXi E, EF, EI;\n  typedef std::set<std::pair<double, int>> PriorityQueue;\n  PriorityQueue Q;\n  std::vector<PriorityQueue::iterator> Qit;\n  // If an edge were collapsed, we'd collapse it to these points:\n  Eigen::MatrixXd C;\n  int num_collapsed;\n  { // prep\n    F = OF;\n    V = OV;\n    igl::edge_flaps(F, E, EMAP, EF, EI);\n    Qit.resize(E.rows());\n\n    C.resize(E.rows(), V.cols());\n    Eigen::VectorXd costs(E.rows());\n    Q.clear();\n    for (int e = 0; e < E.rows(); e++) {\n      double cost = e;\n      Eigen::RowVectorXd p(1, 3);\n      igl::shortest_edge_and_midpoint(e, V, F, E, EMAP, EF, EI, cost, p);\n      C.row(e) = p;\n      Qit[e]   = Q.insert(std::pair<double, int>(cost, e)).first;\n    }\n    num_collapsed = 0;\n  }\n  { // decimate\n    while (not Q.empty()) {\n      bool something_collapsed = false;\n      // collapse edge\n      const int max_iter = std::ceil(amount * Q.size());\n      for (int j = 0; j < max_iter; j++) {\n        if (not igl::collapse_edge(\n                igl::shortest_edge_and_midpoint, //\n                V,\n                F,\n                E,\n                EMAP,\n                EF,\n                EI,\n                Q,\n                Qit,\n                C)) {\n          break;\n        }\n        something_collapsed = true;\n        num_collapsed++;\n      }\n    }\n  }\n  rval->_verts = V;\n  rval->_faces = F;\n  return rval;\n}\n//////////////////////////////////////////////////////////////////////////////\nEigen::MatrixXd IglMesh::computeFaceNormals() const {\n  Eigen::MatrixXd rval;\n  igl::per_face_normals(_verts, _faces, rval);\n  return rval;\n}\nEigen::MatrixXd IglMesh::computeVertexNormals() const {\n  Eigen::MatrixXd rval;\n  igl::per_vertex_normals(_verts, _faces, rval);\n  return rval;\n}\nEigen::MatrixXd IglMesh::computeCornerNormals(float dihedral_angle) const {\n  Eigen::MatrixXd rval;\n  igl::per_corner_normals(_verts, _faces, dihedral_angle, rval);\n  return rval;\n}\n\n//////////////////////////////////////////////////////////////////////////////\nvoid submesh::igl_test() {\n  auto trimesh = submesh();\n  submeshTriangulate(*this, trimesh);\n}\n//////////////////////////////////////////////////////////////////////////////\n} // namespace ork::meshutil\n#endif", "meta": {"hexsha": "829b4ca7e81fe3934e27e5b9c7affe22d650a789", "size": 15657, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ork.lev2/src/gfx/meshutil/submesh_igl.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_igl.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_igl.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": 36.1593533487, "max_line_length": 93, "alphanum_fraction": 0.5128057738, "num_tokens": 4049, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.672331699179286, "lm_q2_score": 0.45326184801538616, "lm_q1q2_score": 0.30474230844932787}}
{"text": "// This file is part of the dune-hdd project:\n//   http://users.dune-project.org/projects/dune-hdd\n// Copyright holders: Felix Schindler\n// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)\n\n#ifndef DUNE_HDD_LINEARELLIPTIC_DISCRETIZATIONS_BLOCK_SWIPDG_HH\n#define DUNE_HDD_LINEARELLIPTIC_DISCRETIZATIONS_BLOCK_SWIPDG_HH\n\n#include <memory>\n#include <algorithm>\n#include <vector>\n#include <map>\n#include <set>\n#include <cmath>\n#include <limits>\n#include <type_traits>\n\n#include <boost/numeric/conversion/cast.hpp>\n\n#include <dune/stuff/common/disable_warnings.hh>\n# if HAVE_EIGEN\n#   include <Eigen/Eigenvalues>\n# endif\n\n# include <dune/common/timer.hh>\n# include <dune/common/dynmatrix.hh>\n\n# if HAVE_ALUGRID\n#   include <dune/grid/alugrid.hh>\n# endif\n\n# include <dune/geometry/quadraturerules.hh>\n#include <dune/stuff/common/reenable_warnings.hh>\n\n#include <dune/grid/multiscale/provider.hh>\n\n#include <dune/stuff/common/logging.hh>\n#include <dune/stuff/common/timedlogging.hh>\n#include <dune/stuff/common/configuration.hh>\n#include <dune/stuff/common/float_cmp.hh>\n#include <dune/stuff/common/fixed_map.hh>\n#include <dune/stuff/grid/layers.hh>\n#include <dune/stuff/grid/boundaryinfo.hh>\n#include <dune/stuff/functions/constant.hh>\n#include <dune/stuff/functions/interfaces.hh>\n#include <dune/stuff/la/container.hh>\n#include <dune/stuff/la/solver.hh>\n#include <dune/stuff/grid/walker.hh>\n\n#include <dune/pymor/common/exceptions.hh>\n\n#include <dune/gdt/spaces/dg.hh>\n#include <dune/gdt/playground/spaces/block.hh>\n#include <dune/gdt/playground/localevaluation/swipdg.hh>\n#include <dune/gdt/discretefunction/default.hh>\n#include <dune/gdt/operators/oswaldinterpolation.hh>\n#include <dune/gdt/operators/projections.hh>\n#include <dune/gdt/spaces/fv/default.hh>\n#include <dune/gdt/spaces/rt/pdelab.hh>\n#include <dune/gdt/playground/operators/fluxreconstruction.hh>\n#include <dune/gdt/playground/products/swipdgpenalty.hh>\n#include <dune/gdt/products/boundaryl2.hh>\n#include <dune/gdt/products/l2.hh>\n#include <dune/gdt/products/h1.hh>\n#include <dune/gdt/products/elliptic.hh>\n#include <dune/gdt/assembler/system.hh>\n\n#include <dune/hdd/linearelliptic/problems/default.hh>\n#include <dune/hdd/linearelliptic/problems/zero-boundary.hh>\n\n#include \"base.hh\"\n#include \"swipdg.hh\"\n\nnamespace Dune {\nnamespace HDD {\nnamespace LinearElliptic {\nnamespace Discretizations {\n\n\n// forward, needed in the Traits\ntemplate< class GridImp, class RangeFieldImp, int rangeDim, int polynomialOrder = 1\n        , Stuff::LA::ChooseBackend la_backend = Stuff::LA::default_sparse_backend >\nclass BlockSWIPDG;\n\n\nnamespace internal {\n\n\ntemplate< class GridType, class RangeFieldType, int dimRange, int polOrder, Stuff::LA::ChooseBackend la_backend >\nclass LocalDiscretizationsContainer\n{\n  typedef grid::Multiscale::ProviderInterface< GridType > GridProviderType;\npublic:\n  typedef SWIPDG< GridType, Stuff::Grid::ChooseLayer::local, RangeFieldType, dimRange\n                , polOrder, GDT::ChooseSpaceBackend::fem, la_backend > DiscretizationType;\n  typedef SWIPDG< GridType, Stuff::Grid::ChooseLayer::local_oversampled, RangeFieldType, dimRange\n                , polOrder, GDT::ChooseSpaceBackend::fem, la_backend > OversampledDiscretizationType;\n  typedef typename DiscretizationType::ProblemType     ProblemType;\n  typedef typename DiscretizationType::TestSpaceType   TestSpaceType;\n  typedef typename DiscretizationType::AnsatzSpaceType AnsatzSpaceType;\n\nprivate:\n  typedef Problems::ZeroBoundary< ProblemType > FakeProblemType;\n  typedef typename DiscretizationType::GridViewType::Intersection IntersectionType;\n\npublic:\n  LocalDiscretizationsContainer(const GridProviderType& grid_provider,\n                                const ProblemType& prob,\n                                const std::vector< std::string >& only_these_products)\n    : zero_boundary_problem_(prob)\n    , all_dirichlet_boundary_config_(Stuff::Grid::BoundaryInfos::AllDirichlet< IntersectionType >::default_config())\n    , all_neumann_boundary_config_(Stuff::Grid::BoundaryInfos::AllNeumann< IntersectionType >::default_config())\n    , multiscale_boundary_config_(Stuff::Grid::BoundaryInfoConfigs::IdBased::default_config())\n    , local_discretizations_(grid_provider.num_subdomains(), nullptr)\n    , oversampled_discretizations_dirichlet_(grid_provider.num_subdomains(), nullptr)\n    , oversampled_discretizations_neumann_(grid_provider.num_subdomains(), nullptr)\n    , local_test_spaces_(grid_provider.num_subdomains(), nullptr)\n    , local_ansatz_spaces_(grid_provider.num_subdomains(), nullptr)\n  {\n    multiscale_boundary_config_[\"neumann\"] = \"7\";\n    for (size_t ss = 0; ss < grid_provider.num_subdomains(); ++ss) {\n      local_discretizations_[ss] = std::make_shared< DiscretizationType >(grid_provider,\n                                                                          all_neumann_boundary_config_,\n                                                                          zero_boundary_problem_,\n                                                                          ss,\n                                                                          only_these_products);\n      local_test_spaces_[ss]   = std::make_shared< TestSpaceType >(  local_discretizations_[ss]->test_space());\n      local_ansatz_spaces_[ss] = std::make_shared< AnsatzSpaceType >(local_discretizations_[ss]->ansatz_space());\n    }\n  }\n\nprotected:\n  const FakeProblemType zero_boundary_problem_;\n  const Stuff::Common::Configuration all_dirichlet_boundary_config_;\n  const Stuff::Common::Configuration all_neumann_boundary_config_;\n  Stuff::Common::Configuration multiscale_boundary_config_;\n  std::vector< std::shared_ptr< DiscretizationType > > local_discretizations_;\n  mutable std::vector< std::shared_ptr< OversampledDiscretizationType > > oversampled_discretizations_dirichlet_;\n  mutable std::vector< std::shared_ptr< OversampledDiscretizationType > > oversampled_discretizations_neumann_;\n  std::vector< std::shared_ptr< const TestSpaceType > > local_test_spaces_;\n  std::vector< std::shared_ptr< const AnsatzSpaceType > > local_ansatz_spaces_;\n}; // class LocalDiscretizationsContainer\n\n\ntemplate< class GridImp, class RangeFieldImp, int rangeDim, int polynomialOrder, Stuff::LA::ChooseBackend la_backend >\nclass BlockSWIPDGTraits\n  : public ContainerBasedDefaultTraits< typename Stuff::LA::Container< RangeFieldImp, la_backend >::MatrixType,\n                                        typename Stuff::LA::Container< RangeFieldImp, la_backend >::VectorType >\n{\npublic:\n  typedef BlockSWIPDG< GridImp, RangeFieldImp, rangeDim, polynomialOrder, la_backend > derived_type;\n  typedef GridImp GridType;\n  typedef RangeFieldImp     RangeFieldType;\n  static const unsigned int dimRange = rangeDim;\n  static const unsigned int polOrder = polynomialOrder;\nprivate:\n  friend class BlockSWIPDG< GridImp, RangeFieldImp, rangeDim, polynomialOrder, la_backend >;\n  typedef grid::Multiscale::ProviderInterface< GridType > GridProviderType;\n  typedef LocalDiscretizationsContainer< GridType, RangeFieldType, dimRange, polOrder, la_backend >\n      LocalDiscretizationsContainerType;\n  typedef typename LocalDiscretizationsContainerType::TestSpaceType   LocalTestSpaceType;\n  typedef typename LocalDiscretizationsContainerType::AnsatzSpaceType LocalAnsatzSpaceType;\npublic:\n  typedef GDT::Spaces::Block< LocalTestSpaceType >   TestSpaceType;\n  typedef GDT::Spaces::Block< LocalAnsatzSpaceType > AnsatzSpaceType;\n  typedef typename TestSpaceType::GridViewType GridViewType;\n}; // class BlockSWIPDGTraits\n\n\n} // namespace internal\n\n\n/**\n * \\attention The given problem is replaced by a Problems::ZeroBoundary.\n * \\attention The given boundary info config is replaced by a Stuff::Grid::BoundaryInfos::AllDirichlet.\n * \\attention The boundary info for the local oversampled discretizations is hardwired to dirichlet zero atm!\n */\ntemplate< class GridImp, class RangeFieldImp, int rangeDim, int polynomialOrder, Stuff::LA::ChooseBackend la_backend >\nclass BlockSWIPDG\n  : internal::LocalDiscretizationsContainer< GridImp, RangeFieldImp, rangeDim, polynomialOrder, la_backend >\n  , public ContainerBasedDefault< internal::BlockSWIPDGTraits< GridImp, RangeFieldImp, rangeDim\n                                                             , polynomialOrder, la_backend > >\n\n{\n  typedef internal::LocalDiscretizationsContainer< GridImp, RangeFieldImp, rangeDim, polynomialOrder, la_backend >\n    LocalDiscretizationsBaseType;\n  typedef ContainerBasedDefault< internal::BlockSWIPDGTraits< GridImp, RangeFieldImp, rangeDim\n                                                            , polynomialOrder, la_backend > > BaseType;\n  typedef BlockSWIPDG< GridImp, RangeFieldImp, rangeDim, polynomialOrder, la_backend >        ThisType;\npublic:\n  typedef internal::BlockSWIPDGTraits< GridImp, RangeFieldImp, rangeDim, polynomialOrder, la_backend > Traits;\n  typedef typename BaseType::ProblemType     ProblemType;\n  typedef typename BaseType::GridViewType    GridViewType;\n  typedef typename BaseType::TestSpaceType   TestSpaceType;\n  typedef typename BaseType::AnsatzSpaceType AnsatzSpaceType;\n  typedef typename BaseType::EntityType      EntityType;\n  typedef typename BaseType::DomainFieldType DomainFieldType;\n  typedef typename BaseType::RangeFieldType  RangeFieldType;\n  typedef typename BaseType::MatrixType      MatrixType;\n  typedef typename BaseType::VectorType      VectorType;\n  typedef typename BaseType::OperatorType    OperatorType;\n  typedef typename BaseType::ProductType     ProductType;\n  typedef typename BaseType::FunctionalType  FunctionalType;\n\n  static const unsigned int dimDomain = BaseType::dimDomain;\n  static const unsigned int dimRange  = BaseType::dimRange;\n\n  typedef grid::Multiscale::ProviderInterface< GridImp > GridProviderType;\n  typedef typename GridProviderType::GridType   GridType;\n  typedef typename GridProviderType::MsGridType MsGridType;\n\n  typedef typename Traits::LocalDiscretizationsContainerType::DiscretizationType            LocalDiscretizationType;\n  typedef typename Traits::LocalDiscretizationsContainerType::OversampledDiscretizationType OversampledDiscretizationType;\n  typedef typename TestSpaceType::PatternType PatternType;\n\nprivate:\n  using typename BaseType::AffinelyDecomposedMatrixType;\n  using typename BaseType::AffinelyDecomposedVectorType;\n  typedef Pymor::LA::AffinelyDecomposedConstContainer< MatrixType > AffinelyDecomposedConstMatrixType;\n  typedef Pymor::LA::AffinelyDecomposedConstContainer< VectorType > AffinelyDecomposedConstVectorType;\n\npublic:\n  typedef typename LocalDiscretizationType::ProblemType LocalProblemType;\n  typedef typename LocalDiscretizationType::ProductType LocalProductType;\n\n  static std::string static_id();\n\n  BlockSWIPDG(const GridProviderType& grid_provider,\n              const Stuff::Common::Configuration& bound_inf_cfg,\n              const ProblemType& prob,\n              const std::vector< std::string >& only_these_products = {});\n\n  const std::vector< std::shared_ptr< LocalDiscretizationType > >& local_discretizations() const;\n\n  void init(const bool prune = false);\n\n  ssize_t num_subdomains() const;\n\n  std::vector< ssize_t > neighbouring_subdomains(const ssize_t ss) const;\n\n  VectorType localize_vector(const VectorType& global_vector, const size_t ss) const;\n\n  VectorType globalize_vectors(const std::vector< VectorType >& local_vectors) const;\n\n  VectorType* globalize_vectors_and_return_ptr(const std::vector< VectorType >& local_vectors) const;\n\n  VectorType* localize_vector_and_return_ptr(const VectorType& global_vector, const ssize_t ss) const;\n\n  ProductType get_local_product(const size_t ss, const std::string id) const;\n\n  ProductType* get_local_product_and_return_ptr(const ssize_t ss, const std::string id) const;\n\n  OperatorType get_local_operator(const size_t ss) const;\n\n  OperatorType* get_local_operator_and_return_ptr(const ssize_t ss) const;\n\n  OperatorType get_coupling_operator(const size_t ss, const size_t nn) const;\n\n  OperatorType* get_coupling_operator_and_return_ptr(const ssize_t ss, const ssize_t nn) const;\n\n  FunctionalType get_local_functional(const size_t ss) const;\n\n  FunctionalType* get_local_functional_and_return_ptr(const ssize_t ss) const;\n\n  VectorType solve_for_local_correction(const std::vector< VectorType >& local_vectors,\n                                        const size_t subdomain,\n                                        const Pymor::Parameter mu = Pymor::Parameter()) const;\n\n  LocalDiscretizationType get_local_discretization(const size_t subdomain) const;\n\n  LocalDiscretizationType* pb_get_local_discretization(const ssize_t subdomain) const;\n\n  OversampledDiscretizationType get_oversampled_discretization(const size_t subdomain,\n                                                               const std::string boundary_value_type) const;\n\n  OversampledDiscretizationType* pb_get_oversampled_discretization(const ssize_t subdomain,\n                                                                   const std::string boundary_value_type) const;\n\n//  OversampledDiscretizationType* pb_get_oversampled_discretization(const ssize_t subdomain,\n//                                                                   const std::string boundary_value_type,\n//                                                                   const VectorType& boundary_values) const;\n\nprivate:\n  class CouplingAssembler\n  {\n    typedef Dune::DynamicMatrix< RangeFieldType > LocalMatrixType;\n    typedef Dune::DynamicVector< RangeFieldType > LocalVectorType;\n    typedef std::vector< std::vector< LocalMatrixType > > LocalMatricesContainerType;\n    typedef std::vector< std::vector< LocalVectorType > > LocalVectorsContainerType;\n    typedef std::vector< Dune::DynamicVector< size_t > > IndicesContainer;\n\n    typedef typename LocalDiscretizationType::TestSpaceType LocalTestSpaceType;\n    typedef typename LocalDiscretizationType::AnsatzSpaceType LocalAnsatzSpaceType;\n    typedef typename MsGridType::CouplingGridPartType CouplingGridPartType;\n\n    class LocalCodim1MatrixAssemblerApplication\n    {\n    public:\n      virtual ~LocalCodim1MatrixAssemblerApplication(){}\n\n      virtual void apply(const LocalTestSpaceType& /*inner_test_space*/,\n                         const LocalAnsatzSpaceType& /*inner_ansatz_space*/,\n                         const LocalTestSpaceType& /*outer_test_space*/,\n                         const LocalAnsatzSpaceType& /*outer_ansatz_space*/,\n                         const typename CouplingGridPartType::IntersectionType& /*_intersection*/,\n                         LocalMatricesContainerType& /*_localMatricesContainer*/,\n                         IndicesContainer& /*indicesContainer*/) const = 0;\n\n      virtual std::vector< size_t > numTmpObjectsRequired() const = 0;\n    };\n\n    template< class LocalAssemblerType, class M >\n    class LocalCodim1MatrixAssemblerWrapper\n      : public LocalCodim1MatrixAssemblerApplication\n    {\n    public:\n      LocalCodim1MatrixAssemblerWrapper(const LocalAssemblerType& localAssembler,\n                                        Dune::Stuff::LA::MatrixInterface< M >& in_in_matrix,\n                                        Dune::Stuff::LA::MatrixInterface< M >& in_out_matrix,\n                                        Dune::Stuff::LA::MatrixInterface< M >& out_in_matrix,\n                                        Dune::Stuff::LA::MatrixInterface< M >& out_out_matrix)\n        : localMatrixAssembler_(localAssembler)\n        , in_in_matrix_(in_in_matrix)\n        , out_out_matrix_(out_out_matrix)\n        , in_out_matrix_(in_out_matrix)\n        , out_in_matrix_(out_in_matrix)\n      {}\n\n      virtual void apply(const LocalTestSpaceType& inner_test_space,\n                         const LocalAnsatzSpaceType& inner_ansatz_space,\n                         const LocalTestSpaceType& outer_test_space,\n                         const LocalAnsatzSpaceType& outer_ansatz_space,\n                         const typename CouplingGridPartType::IntersectionType& intersection,\n                         LocalMatricesContainerType& localMatricesContainer,\n                         IndicesContainer& indicesContainer) const\n      {\n        localMatrixAssembler_.assembleLocal(inner_test_space, inner_ansatz_space,\n                                            outer_test_space, outer_ansatz_space,\n                                            intersection,\n                                            in_in_matrix_, out_out_matrix_, in_out_matrix_, out_in_matrix_,\n                                            localMatricesContainer, indicesContainer);\n      }\n\n      virtual std::vector< size_t > numTmpObjectsRequired() const\n      {\n        return localMatrixAssembler_.numTmpObjectsRequired();\n      }\n\n    private:\n      const LocalAssemblerType& localMatrixAssembler_;\n      Dune::Stuff::LA::MatrixInterface< M >& in_in_matrix_;\n      Dune::Stuff::LA::MatrixInterface< M >& out_out_matrix_;\n      Dune::Stuff::LA::MatrixInterface< M >& in_out_matrix_;\n      Dune::Stuff::LA::MatrixInterface< M >& out_in_matrix_;\n    }; // class LocalCodim1MatrixAssemblerWrapper\n\n  public:\n    CouplingAssembler(const LocalTestSpaceType& inner_test_space,\n                      const LocalAnsatzSpaceType& inner_ansatz_space,\n                      const LocalTestSpaceType& outer_test_space,\n                      const LocalAnsatzSpaceType& outer_ansatz_space,\n                      const CouplingGridPartType& grid_part)\n      : innerTestSpace_(inner_test_space)\n      , innerAnsatzSpace_(inner_ansatz_space)\n      , outerTestSpace_(outer_test_space)\n      , outerAnsatzSpace_(outer_ansatz_space)\n      , grid_part_(grid_part)\n    {}\n\n    ~CouplingAssembler()\n    {\n      clearLocalAssemblers();\n    }\n\n    void clearLocalAssemblers()\n    {\n      for (auto& element: localCodim1MatrixAssemblers_)\n        delete element;\n    }\n\n    template< class L, class M >\n    void addLocalAssembler(const GDT::LocalAssembler::Codim1CouplingMatrix< L >& localAssembler,\n                           Dune::Stuff::LA::MatrixInterface< M >& in_in_matrix,\n                           Dune::Stuff::LA::MatrixInterface< M >& in_out_matrix,\n                           Dune::Stuff::LA::MatrixInterface< M >& out_in_matrix,\n                           Dune::Stuff::LA::MatrixInterface< M >& out_out_matrix)\n    {\n      assert(in_in_matrix.rows() == innerTestSpace_.mapper().size());\n      assert(in_in_matrix.cols() == innerAnsatzSpace_.mapper().size());\n      assert(in_out_matrix.rows() == innerTestSpace_.mapper().size());\n      assert(in_out_matrix.cols() == outerAnsatzSpace_.mapper().size());\n      assert(out_in_matrix.rows() == outerTestSpace_.mapper().size());\n      assert(out_in_matrix.cols() == innerAnsatzSpace_.mapper().size());\n      assert(out_out_matrix.rows() == outerTestSpace_.mapper().size());\n      assert(out_out_matrix.cols() == outerAnsatzSpace_.mapper().size());\n      localCodim1MatrixAssemblers_.push_back(\n            new LocalCodim1MatrixAssemblerWrapper< GDT::LocalAssembler::Codim1CouplingMatrix< L >, M >(\n              localAssembler, in_in_matrix, in_out_matrix, out_in_matrix, out_out_matrix));\n    }\n\n    void assemble() const\n    {\n      // only do something, if there are local assemblers\n      if (localCodim1MatrixAssemblers_.size() > 0) {\n        // common tmp storage for all entities\n        // * for the matrix assemblers\n        std::vector< size_t > numberOfTmpMatricesNeeded(2, 0);\n        for (auto& localCodim1MatrixAssembler : localCodim1MatrixAssemblers_) {\n          const auto tmp = localCodim1MatrixAssembler->numTmpObjectsRequired();\n          assert(tmp.size() == 2);\n          numberOfTmpMatricesNeeded[0] = std::max(numberOfTmpMatricesNeeded[0], tmp[0]);\n          numberOfTmpMatricesNeeded[1] = std::max(numberOfTmpMatricesNeeded[1], tmp[1]);\n        }\n        const size_t maxLocalSize = std::max(innerTestSpace_.mapper().maxNumDofs(),\n                                             std::max(innerAnsatzSpace_.mapper().maxNumDofs(),\n                                                      std::max(outerTestSpace_.mapper().maxNumDofs(),\n                                                               outerAnsatzSpace_.mapper().maxNumDofs())));\n        std::vector< LocalMatrixType > tmpLocalAssemblerMatrices( numberOfTmpMatricesNeeded[0],\n                                                                  LocalMatrixType(maxLocalSize,\n                                                                                  maxLocalSize,\n                                                                                  RangeFieldType(0)));\n        std::vector< LocalMatrixType > tmpLocalOperatorMatrices(numberOfTmpMatricesNeeded[1],\n                                                                LocalMatrixType(maxLocalSize,\n                                                                                maxLocalSize,\n                                                                                RangeFieldType(0)));\n        std::vector< std::vector< LocalMatrixType > > tmpLocalMatricesContainer;\n        tmpLocalMatricesContainer.push_back(tmpLocalAssemblerMatrices);\n        tmpLocalMatricesContainer.push_back(tmpLocalOperatorMatrices);\n        // * for the global indices\n        std::vector< Dune::DynamicVector< size_t > > tmpIndices = {\n            Dune::DynamicVector< size_t >(maxLocalSize)\n          , Dune::DynamicVector< size_t >(maxLocalSize)\n          , Dune::DynamicVector< size_t >(maxLocalSize)\n          , Dune::DynamicVector< size_t >(maxLocalSize)\n        };\n\n        // walk the grid\n        const auto entityEndIt = grid_part_.template end< 0 >();\n        for(auto entityIt = grid_part_.template begin< 0 >(); entityIt != entityEndIt; ++entityIt ) {\n          const auto& entity = *entityIt;\n          // walk the intersections\n          const auto intersectionEndIt = grid_part_.iend(entity);\n          for (auto intersectionIt = grid_part_.ibegin(entity);\n               intersectionIt != intersectionEndIt;\n               ++intersectionIt) {\n            const auto& intersection = *intersectionIt;\n            // for a coupling grid part, we can be sure to only get the inner coupling intersetcions\n            // so no further check neccesarry then\n            assert(intersection.neighbor() && !intersection.boundary());\n            // call local matrix assemblers\n            for (auto& localCodim1MatrixAssembler : localCodim1MatrixAssemblers_) {\n              localCodim1MatrixAssembler->apply(innerTestSpace_, innerAnsatzSpace_,\n                                                outerTestSpace_, outerAnsatzSpace_,\n                                                intersection,\n                                                tmpLocalMatricesContainer, tmpIndices);\n            }\n          } // walk the intersections\n        } // walk the grid\n      } // only do something, if there are local assemblers\n    } // void assemble() const\n\n  private:\n    const LocalTestSpaceType& innerTestSpace_;\n    const LocalAnsatzSpaceType& innerAnsatzSpace_;\n    const LocalTestSpaceType& outerTestSpace_;\n    const LocalAnsatzSpaceType& outerAnsatzSpace_;\n    const CouplingGridPartType grid_part_;\n    std::vector< LocalCodim1MatrixAssemblerApplication* > localCodim1MatrixAssemblers_;\n  }; // class CouplingAssembler\n\n  void add_local_to_global_pattern(const PatternType& local,\n                                   const size_t test_subdomain,\n                                   const size_t ansatz_subdomain,\n                                   PatternType& global) const;\n\n  void copy_local_to_global_matrix(const AffinelyDecomposedConstMatrixType& local_matrix,\n                                   const PatternType& local_pattern,\n                                   const size_t subdomain,\n                                   const size_t neighbor,\n                                   AffinelyDecomposedMatrixType& global_matrix) const;\n\n  template< class ML, class MG >\n  void copy_local_to_global_matrix(const Stuff::LA::MatrixInterface< ML >& local_matrix,\n                                   const PatternType& local_pattern,\n                                   const size_t test_subdomain,\n                                   const size_t ansatz_subdomain,\n                                   Stuff::LA::MatrixInterface< MG >& global_matrix) const\n  {\n    for (size_t local_ii = 0; local_ii < local_pattern.size(); ++local_ii) {\n      const size_t global_ii = this->test_space().mapper().mapToGlobal(test_subdomain, local_ii);\n      for (const size_t& local_jj : local_pattern.inner(local_ii)) {\n        const size_t global_jj = this->ansatz_space().mapper().mapToGlobal(ansatz_subdomain, local_jj);\n        global_matrix.add_to_entry(global_ii, global_jj, local_matrix.get_entry(local_ii, local_jj));\n      }\n    }\n  } // ... copy_local_to_global_matrix(...)\n\n  void copy_local_to_global_vector(const AffinelyDecomposedConstVectorType& local_vector,\n                                   const size_t subdomain,\n                                   AffinelyDecomposedVectorType& global_vector) const;\n\n  template< class VL, class VG >\n  void copy_local_to_global_vector(const Stuff::LA::VectorInterface< VL >& local_vector,\n                                   const size_t subdomain,\n                                   Stuff::LA::VectorInterface< VG >& global_vector) const\n  {\n    for (size_t local_ii = 0; local_ii < local_vector.size(); ++local_ii) {\n      const size_t global_ii = this->test_space().mapper().mapToGlobal(subdomain, local_ii);\n      global_vector.add_to_entry(global_ii, local_vector.get_entry(local_ii));\n    }\n  } // ... copy_local_to_global_vector(...)\n\n  void assemble_boundary_contributions(const size_t subdomain) const;\n\n  /**\n   * \\note  We take the matrices as input here becaus we would have to look them up in the maps otherwise. Since that\n   *        has already been done above we save a little.\n   */\n  void assemble_coupling_contributions(const size_t subdomain,\n                                       const size_t neighbour,\n                                       AffinelyDecomposedMatrixType& inside_inside_matrix,\n                                       AffinelyDecomposedMatrixType& inside_outside_matrix,\n                                       AffinelyDecomposedMatrixType& outside_inside_matrix,\n                                       AffinelyDecomposedMatrixType& outside_outside_matrix) const;\n\n  void build_global_containers();\n\n  template< class AffinelyDecomposedContainerType >\n  ssize_t find_component(const AffinelyDecomposedContainerType& container,\n                         const Pymor::ParameterFunctional& coefficient) const\n  {\n    for (size_t qq = 0; qq < boost::numeric_cast< size_t >(container.num_components()); ++qq)\n      if (*(container.coefficient(qq)) == coefficient)\n        return qq;\n    return -1;\n  } // ... find_component(...)\n\n  const GridProviderType& grid_provider_;\n  std::shared_ptr< const MsGridType > ms_grid_;\n  const std::vector< std::string > only_these_products_;\n  using BaseType::pattern_;\n  std::vector< std::shared_ptr< AffinelyDecomposedMatrixType > > local_matrices_;\n  std::vector< std::shared_ptr< AffinelyDecomposedVectorType > > local_vectors_;\n  std::vector< std::map< size_t, std::shared_ptr< PatternType > > > inside_outside_patterns_;\n  std::vector< std::map< size_t, std::shared_ptr< PatternType > > > outside_inside_patterns_;\n  std::vector< std::map< size_t, std::shared_ptr< AffinelyDecomposedMatrixType > > > inside_outside_matrices_;\n  std::vector< std::map< size_t, std::shared_ptr< AffinelyDecomposedMatrixType > > > outside_inside_matrices_;\n}; // BlockSWIPDG\n\n\n#if HAVE_ALUGRID && HAVE_DUNE_FEM\n# if HAVE_DUNE_ISTL\n\nextern template class BlockSWIPDG< ALUGrid< 2, 2, simplex, conforming, No_Comm >,\n                                   double,\n                                   1,\n                                   1,\n                                   Stuff::LA::ChooseBackend::istl_sparse >;\n\n#   if HAVE_MPI\n\nextern template class BlockSWIPDG< ALUGrid< 2, 2, simplex, conforming, MPI_Comm >,\n                                   double,\n                                   1,\n                                   1,\n                                   Stuff::LA::ChooseBackend::istl_sparse >;\n\n#   endif // HAVE_MPI\n# endif // HAVE_DUNE_ISTL\n# if HAVE_EIGEN\n\nextern template class BlockSWIPDG< ALUGrid< 2, 2, simplex, conforming, No_Comm >,\n                                   double,\n                                   1,\n                                   1,\n                                   Stuff::LA::ChooseBackend::eigen_sparse >;\n\n#   if HAVE_MPI\n\nextern template class BlockSWIPDG< ALUGrid< 2, 2, simplex, conforming, MPI_Comm >,\n                                   double,\n                                   1,\n                                   1,\n                                   Stuff::LA::ChooseBackend::eigen_sparse >;\n\n#   endif // HAVE_MPI\n# endif // HAVE_EIGEN\n#endif // HAVE_ALUGRID && HAVE_DUNE_FEM && HAVE_DUNE_ISTL\n\n\ntemplate< Stuff::LA::ChooseBackend la, class G, class R, int r = 1, int p = 1 >\nBlockSWIPDG< G, R, r, p, la > make_block_swipdg(const grid::Multiscale::ProviderInterface< G >& grid_provider,\n                                                const DSC::Configuration& boundary_info,\n                                                const ProblemInterface< typename G::template Codim< 0 >::Entity,\n                                                                        typename G::ctype, G::dimension,\n                                                                        R, r >& problem,\n                                                const std::vector< std::string >& only_these_products = {})\n{\n  return BlockSWIPDG< G, R, r, p, la >(grid_provider, boundary_info, problem, only_these_products);\n}\n\n\n} // namespace Discretizations\n} // namespace LinearElliptic\n} // namespace HDD\n} // namespace Dune\n\n#endif // DUNE_HDD_LINEARELLIPTIC_DISCRETIZATIONS_BLOCK_SWIPDG_HH\n", "meta": {"hexsha": "062d6684d3c1aedf2d947660029d1e90a9d30518", "size": 29964, "ext": "hh", "lang": "C++", "max_stars_repo_path": "dune/hdd/linearelliptic/discretizations/block-swipdg.hh", "max_stars_repo_name": "pymor/dune-hdd", "max_stars_repo_head_hexsha": "1ded1451a04a44c035db4cff7905661813afa935", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-02-08T04:10:59.000Z", "max_stars_repo_stars_event_max_datetime": "2020-02-08T04:10:59.000Z", "max_issues_repo_path": "dune/hdd/linearelliptic/discretizations/block-swipdg.hh", "max_issues_repo_name": "dune-community/dune-hdd", "max_issues_repo_head_hexsha": "1ded1451a04a44c035db4cff7905661813afa935", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 11.0, "max_issues_repo_issues_event_min_datetime": "2018-07-31T08:29:42.000Z", "max_issues_repo_issues_event_max_datetime": "2019-06-28T08:53:34.000Z", "max_forks_repo_path": "dune/hdd/linearelliptic/discretizations/block-swipdg.hh", "max_forks_repo_name": "pymor/dune-hdd", "max_forks_repo_head_hexsha": "1ded1451a04a44c035db4cff7905661813afa935", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-02-08T04:11:02.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-08T04:11:02.000Z", "avg_line_length": 49.2019704433, "max_line_length": 122, "alphanum_fraction": 0.6632292084, "num_tokens": 6487, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.672331699179286, "lm_q2_score": 0.45326184801538616, "lm_q1q2_score": 0.30474230844932787}}
{"text": "/*    Copyright (c) 2010-2018, Delft University of Technology\n *    All rigths reserved\n *\n *    This file is part of the Tudat. Redistribution and use in source and\n *    binary forms, with or without modification, are permitted exclusively\n *    under the terms of the Modified BSD license. You should have received\n *    a copy of the license with this file. If not, please or visit:\n *    http://tudat.tudelft.nl/LICENSE.\n */\n\n#include <boost/bind.hpp>\n\n#include \"Tudat/Astrodynamics/OrbitDetermination/LightTimeCorrectionPartials/lightTimeCorrectionPartial.h\"\n#include \"Tudat/Astrodynamics/OrbitDetermination/LightTimeCorrectionPartials/firstOrderRelativisticLightTimeCorrectionPartial.h\"\n#include \"Tudat/Astrodynamics/OrbitDetermination/LightTimeCorrectionPartials/jw_lighttime_correction_partial.h\"\n\nnamespace tudat\n{\n\nnamespace observation_partials\n{\n\n//! Function to get the function returning the light-time correction partial for given correction partial and parameter.\n\nstd::pair< std::function< LightTimeCorrectionPartial::SingleOneWayRangePartialReturnType(\n        const std::vector< Eigen::Vector6d >&, const std::vector< double >& ) >, bool >\ngetLightTimeParameterPartialFunction(\n        const estimatable_parameters::EstimatebleParameterIdentifier parameterId,\n        const std::shared_ptr< LightTimeCorrectionPartial > lightTimeCorrectionPartial )\n{\n    // Declare return type, set second part to 0 (no dependency found).\n    std::pair< std::function< LightTimeCorrectionPartial::SingleOneWayRangePartialReturnType(\n                const std::vector< Eigen::Vector6d >&, const std::vector< double >& ) >, bool > partialFunction;\n    partialFunction.second = 0;\n\n    // Check type of light-time correction\n    switch( lightTimeCorrectionPartial->getCorrectionType( ) )\n    {\n    // Correction type of 1st-order relativistic\n    case observation_models::first_order_relativistic:\n    {\n        // Check consistency of input.\n        std::shared_ptr< FirstOrderRelativisticLightTimeCorrectionPartial > currentLightTimeCorrectorPartial =\n                std::dynamic_pointer_cast< FirstOrderRelativisticLightTimeCorrectionPartial >( lightTimeCorrectionPartial );\n        if( currentLightTimeCorrectorPartial == nullptr )\n        {\n            std::string errorMessage = \"Error when getting light time correction partial function, type \" +\n                    std::to_string( lightTimeCorrectionPartial->getCorrectionType( ) ) +\n                       \"is inconsistent.\";\n            throw std::runtime_error( errorMessage );\n        }\n\n        // Set partial of gravitational parameter\n        if( parameterId.first == estimatable_parameters::gravitational_parameter )\n        {\n            // Retrieve function from FirstOrderRelativisticLightTimeCorrectionPartial if correction depends on\n            // body associated with parameter.\n            std::vector< std::string > perturbingBodies = currentLightTimeCorrectorPartial->getPerturbingBodies( );\n            std::vector< std::string >::iterator findIterator = std::find(\n                        perturbingBodies.begin( ), perturbingBodies.end( ), parameterId.second.first );\n            if( findIterator != perturbingBodies.end( ) )\n            {\n                int bodyIndex = std::distance( perturbingBodies.begin( ),  findIterator );\n                partialFunction = std::make_pair(\n                            std::bind( &FirstOrderRelativisticLightTimeCorrectionPartial::wrtBodyGravitationalParameter,\n                                         currentLightTimeCorrectorPartial, std::placeholders::_1, std::placeholders::_2, bodyIndex ), 1 );\n            }\n        }\n        else if( parameterId.first == estimatable_parameters::ppn_parameter_gamma )\n        {\n            partialFunction = std::make_pair(\n                        std::bind( &FirstOrderRelativisticLightTimeCorrectionPartial::wrtPpnParameterGamma,\n                                     currentLightTimeCorrectorPartial, std::placeholders::_1, std::placeholders::_2 ), 1 );\n        }\n        break;\n    }\n\n    case observation_models::jw_lighttime:\n    {\n        // Check consistency of input.\n        std::shared_ptr< jw_lighttime_correction_partial > currentLightTimeCorrectorPartial =\n                std::dynamic_pointer_cast< jw_lighttime_correction_partial >( lightTimeCorrectionPartial );\n        if( currentLightTimeCorrectorPartial == nullptr )\n        {\n            std::string errorMessage = \"Error when getting light time correction partial function, type \" +\n                    std::to_string( lightTimeCorrectionPartial->getCorrectionType( ) ) +\n                       \"is inconsistent with expected type, jw_lighttime.\";\n            throw std::runtime_error( errorMessage );\n        }\n\n        // Set partial of gravitational parameter\n        if( parameterId.first == estimatable_parameters::gravitational_parameter )\n        {\n            // Retrieve function from jw_lighttime_correction_partial if correction depends on\n            // body associated with parameter.\n            std::vector< std::string > perturbingBodies = currentLightTimeCorrectorPartial->getPerturbingBodies( );\n            std::vector< std::string >::iterator findIterator = std::find(\n                        perturbingBodies.begin( ), perturbingBodies.end( ), parameterId.second.first );\n            if( findIterator != perturbingBodies.end( ) )\n            {\n                int bodyIndex = std::distance( perturbingBodies.begin( ),  findIterator );\n                partialFunction = std::make_pair(\n                            std::bind( &jw_lighttime_correction_partial::wrtBodyGravitationalParameter,\n                                         currentLightTimeCorrectorPartial, std::placeholders::_1, std::placeholders::_2, bodyIndex ), 1 );\n            }\n        }\n        else if( parameterId.first == estimatable_parameters::ppn_parameter_gamma )\n        {\n            partialFunction = std::make_pair(\n                        std::bind( &jw_lighttime_correction_partial::wrtPpnParameterGamma,\n                                     currentLightTimeCorrectorPartial, std::placeholders::_1, std::placeholders::_2 ), 1 );\n        }\n        break;\n    }\n\n    default:\n        std::string errorMessage = \"Error, light time correction type \" + std::to_string(\n                    lightTimeCorrectionPartial->getCorrectionType( ) ) + \"not found when creating partial \";\n        throw std::runtime_error( errorMessage );\n    }\n\n    return partialFunction;\n}\n\n}\n\n}\n", "meta": {"hexsha": "a6512bce2bcf9c5e8d035b7173f92c6900aab1b9", "size": 6499, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Tudat/Astrodynamics/OrbitDetermination/LightTimeCorrectionPartials/lightTimeCorrectionPartial.cpp", "max_stars_repo_name": "J-Westin/tudat", "max_stars_repo_head_hexsha": "82ebe9e6e2dd51d0688b77960e62e980e6b8bcb8", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Tudat/Astrodynamics/OrbitDetermination/LightTimeCorrectionPartials/lightTimeCorrectionPartial.cpp", "max_issues_repo_name": "J-Westin/tudat", "max_issues_repo_head_hexsha": "82ebe9e6e2dd51d0688b77960e62e980e6b8bcb8", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Tudat/Astrodynamics/OrbitDetermination/LightTimeCorrectionPartials/lightTimeCorrectionPartial.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": 50.7734375, "max_line_length": 138, "alphanum_fraction": 0.666410217, "num_tokens": 1351, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6959583376458152, "lm_q2_score": 0.43782349911420193, "lm_q1q2_score": 0.304706914625794}}
{"text": "#include <math.h>\n#include <Eigen/KroneckerProduct>\n#include \"Core/Utilities/Tools/MatrixDecomposition.h\"\nUSING_QPANDA\n\nstatic void upper_partition(int order, MatrixOperator &entries)\n{\n    auto index = (int)std::log2(entries.size() + 1) - (int)std::log2(order) - 1;\n\n    for (auto cdx = 0; cdx < order - 1; ++cdx)\n    {\n        for (auto rdx = 0; rdx < order - cdx - 1; ++rdx)\n        {\n            auto Entry = entries[cdx][rdx];\n\n            Entry.first += order;\n            Entry.second[index] = MatrixUnit::SINGLE_P1;\n                \n            entries[cdx + order].emplace_back(Entry);\n        }\n    }\n}\n\n\nstatic bool entry_requirement(const MatrixSequence& units, int udx, int cdx)\n{\n    int M = 0;\n    while (cdx)\n    {\n        cdx >>= 1;\n        M += cdx ? 1 : 0;\n    }\n\n    //if 1 ≤ j ≤ m and cj = lj' = 1 , return true\n    auto unit = units[units.size() - udx - 1];\n    return udx >= 1\n        && udx <= M\n        && cdx == 1 \n        && unit == MatrixUnit::SINGLE_P1;\n}\n\nstatic bool steps_requirement(const MatrixSequence& units, int udx, int cdx)\n{\n    int M = 0;\n    while (cdx)\n    {\n        cdx >>= 1;\n        M += cdx ? 1 : 0;\n    }\n\n    //if j = n and none of cn...cm+1 is 1 , return true\n    if (udx != units.size() - 1)\n    {\n        return false;\n    }\n    else\n    {\n        auto iter = std::find(units.begin(), units.end() - M, MatrixUnit::SINGLE_P1);\n        return (units.end() - M) == iter;\n    }\n}\n\nstatic void under_partition(int order, MatrixOperator& entries)\n{\n    auto qubits =(int)std::log2(entries.size() + 1);\n\n    for (auto cdx = 1; cdx < order; ++cdx)\n    {\n        if (cdx & 1)\n        {\n            for (auto rdx = 0; rdx < order; ++rdx)\n            {\n                auto entry = entries[0][rdx + order - 1].first ^ cdx;\n                entries[cdx].emplace_back(make_pair(entry, entries[cdx - 1][rdx + order - 1].second));\n            }\n\n            auto &units = entries[cdx].back().second;\n            for (auto idx = 0; idx < (int)std::log2(order); ++idx)\n            {\n                if ((cdx >> idx) & 1)\n                {\n                    units[qubits - idx - 1] = MatrixUnit::SINGLE_P1;\n                }\n                else\n                {\n                    units[qubits - idx - 1] = MatrixUnit::SINGLE_I2;\n                }\n            }\n        }\n        else\n        {\n            for (auto rdx = 0; rdx < order; ++rdx)\n            {\n                auto units = entries[0][rdx + order].second;\n                auto entry = entries[0][rdx + order].first ^ cdx;\n\n                for (auto udx = 0; udx < qubits; ++udx)\n                {\n                    bool steps_accord = entry_requirement(units, udx, cdx);\n                    bool entry_accord = entry_requirement(units, udx, cdx);\n\n                    if (steps_accord)\n                    {\n                        units[udx] = MatrixUnit::SINGLE_P1;\n                    }\n                    else if (entry_accord)\n                    {\n                        units[udx] = MatrixUnit::SINGLE_P0;\n                    }\n                    else\n                    {\n                    }\n                }\n\n                entries[cdx].emplace_back(make_pair(entry, units));\n            }\n\n            auto &units = entries[0].back().second;\n            for (auto idx = 0; idx < (int)std::log2(order); ++idx)\n            {\n                if ((cdx >> idx) & 1)\n                {\n                    units[qubits - idx - 1] = MatrixUnit::SINGLE_P1;\n                }\n                else\n                {\n                    units[qubits - idx - 1] = MatrixUnit::SINGLE_I2;\n                }\n            }\n        }\n    }\n}\n\nstatic void voluation(Eigen::MatrixXcf& matrix, MatrixOperator& entries)\n{\n    auto qubits = (int)std::log2(matrix.rows());\n\n    MatrixSequence Cns(qubits, MatrixUnit::SINGLE_I2);\n    Cns.back() = MatrixUnit::SINGLE_V2;\n    entries.front().emplace_back(make_pair(1, Cns));\n\n    ColumnOperator& column = entries.front();\n    for (auto idx = 1; idx < qubits; ++idx)\n    {\n        size_t path = 1ull << idx;\n        for (auto opt = 0; opt < (1 << idx) - 1; ++opt)\n        {\n            auto units = column[opt].second;\n\n            // 1 : none of cn−1, . . . , c1 equals 1\n            // * : otherwise\n            auto iter = std::find(units.begin() + 1, units.end(), MatrixUnit::SINGLE_P1);\n            if (units.end() == iter)\n            {\n                units.front() = MatrixUnit::SINGLE_P1;;\n            }\n            else\n            {\n                units.front() = MatrixUnit::SINGLE_I2;;\n            }\n\n            column.emplace_back(make_pair(opt + path + 1, units));\n        }\n          \n        MatrixSequence Lns(qubits, MatrixUnit::SINGLE_I2);\n        Lns[qubits - idx - 1] = MatrixUnit::SINGLE_V2;\n\n        column.emplace_back(make_pair((1ull << idx), Lns));\n    } \n}\n\nstatic void controller(MatrixSequence &sequence, const Eigen::Matrix2cf U2, Eigen::MatrixXcf &matrix)\n{\n    Eigen::Matrix2cf P0;\n    Eigen::Matrix2cf P1;\n    Eigen::Matrix2cf I2;\n\n    P0 << Eigen::scomplex(1, 0), Eigen::scomplex(0, 0), \n          Eigen::scomplex(0, 0), Eigen::scomplex(0, 0);\n    P1 << Eigen::scomplex(0, 0), Eigen::scomplex(0, 0), \n          Eigen::scomplex(0, 0), Eigen::scomplex(1, 0);\n    I2 << Eigen::scomplex(1, 0), Eigen::scomplex(0, 0), \n          Eigen::scomplex(0, 0), Eigen::scomplex(1, 0);\n\n    std::map<MatrixUnit, std::function<Eigen::Matrix2cf()>> mapping =\n    {\n        { MatrixUnit::SINGLE_P0, [&]() {return P0; } },\n        { MatrixUnit::SINGLE_P1, [&]() {return P1; } },\n        { MatrixUnit::SINGLE_I2, [&]() {return I2; } },\n        { MatrixUnit::SINGLE_V2, [&]() {return U2 - I2; } }\n    };\n\n    auto order = sequence.size();\n    Eigen::MatrixXcf Un = Eigen::MatrixXcf::Identity(1, 1);\n    Eigen::MatrixXcf In = Eigen::MatrixXcf::Identity(1ull << order, 1ull << order);\n\n    for (const auto &val : sequence)\n    {\n        Eigen::Matrix2cf M2 = mapping.find(val)->second();\n        Un = Eigen::kroneckerProduct(Un, M2).eval();\n    }\n\n    matrix = In + Un;\n}\n\nstatic void operation(Eigen::MatrixXcf& matrix, MatrixOperator& entries)\n{\n    for (auto cdx = 0; cdx < entries.size(); ++cdx)\n    {\n        for (auto idx = 0; idx < entries[cdx].size(); ++idx)\n        {\n            auto rdx = entries[cdx][idx].first;\n            auto opt = entries[cdx][idx].second;\n\n            if (Eigen::scomplex(0, 0) == matrix(rdx, cdx))\n            {\n                continue;;\n            }\n            else\n            {\n                auto order = opt.size();\n\n                Eigen::Matrix2cf C2; /*placeholder*/\n                C2 << Eigen::scomplex(0, 1), Eigen::scomplex(0, 1), \n                      Eigen::scomplex(0, 1), Eigen::scomplex(0, 1); \n\n                Eigen::MatrixXcf Cn;\n                controller(opt, C2, Cn);\n\n                Qnum indices(2);\n                for (Eigen::Index index = 0; index < (1ull << order); ++index)\n                {\n                    if (Cn(rdx, index) != Eigen::scomplex(0, 0))\n                    {\n                        indices[index == rdx] = index;\n                    }\n                }\n\n                Eigen::scomplex C0 = matrix(indices[0], cdx);\n                Eigen::scomplex C1 = matrix(indices[1], cdx);\n\n                Eigen::scomplex V11 = std::conj(C0) / std::sqrt(std::norm(C0) + std::norm(C1));\n                Eigen::scomplex V12 = std::conj(C1) / std::sqrt(std::norm(C0) + std::norm(C1));\n                Eigen::scomplex V21 =  C1 / std::sqrt(std::norm(C0) + std::norm(C1));\n                Eigen::scomplex V22 = -C0 / std::sqrt(std::norm(C0) + std::norm(C1));\n\n                Eigen::Matrix2cf V2;\n                V2 << V11 , V12 , V21 , V22;\n\n                Eigen::MatrixXcf Un;\n                controller(opt, V2, Un);\n\n                matrix = Un * matrix;\n            }\n        }\n    }\n}\n\nstatic void partition(Eigen::MatrixXcf& sub_matrix, MatrixOperator &entries)\n{\n    Eigen::Index order = sub_matrix.rows();\n    if (1 == order)\n    {\n        return;\n    }\n    else\n    {\n        Eigen::MatrixXcf corner = sub_matrix.topLeftCorner(order / 2, order / 2);\n\n        partition(corner, entries);\n\n        upper_partition(order / 2, entries);\n        under_partition(order / 2, entries);\n    }\n}\n\nstatic void general_scheme(Eigen::MatrixXcf& matrix)\n{\n    MatrixOperator entries;\n    for (auto idx = 1; idx < matrix.cols(); ++idx)\n    {\n        ColumnOperator Co;\n        entries.emplace_back(Co);\n    }\n\n    voluation(matrix, entries);\n    partition(matrix, entries);\n    operation(matrix, entries);\n}\n\nvoid QMatrix::decompose()\n{\n    auto order = (int)std::log2(this->size());\n\n    Eigen::MatrixXcf matrix = Eigen::MatrixXcf::Zero(order, order);\n    for (auto rdx = 0; rdx < order; ++rdx)\n    {\n        for (auto cdx = 0; cdx < order; ++cdx)\n        {\n            matrix(rdx, cdx) = this->at(rdx*order + cdx);\n        }\n    }\n\n    if (!matrix.isUnitary(1e-3))\n    {\n        QCERR(\"Non-unitary matrix\");\n        return;\n    }\n\n    general_scheme(matrix);\n}", "meta": {"hexsha": "e47875a21a66e38d375956522b876900a8f49e6e", "size": 8992, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Core/Utilities/Tools/MatrixDecomposition.cpp", "max_stars_repo_name": "4ier/QPanda-2", "max_stars_repo_head_hexsha": "ce44256bd7eb81f0982e6092090c9fc1b8b3f6b7", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2020-05-14T09:30:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-17T10:58:53.000Z", "max_issues_repo_path": "Core/Utilities/Tools/MatrixDecomposition.cpp", "max_issues_repo_name": "4ier/QPanda-2", "max_issues_repo_head_hexsha": "ce44256bd7eb81f0982e6092090c9fc1b8b3f6b7", "max_issues_repo_licenses": ["Apache-2.0"], "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/Utilities/Tools/MatrixDecomposition.cpp", "max_forks_repo_name": "4ier/QPanda-2", "max_forks_repo_head_hexsha": "ce44256bd7eb81f0982e6092090c9fc1b8b3f6b7", "max_forks_repo_licenses": ["Apache-2.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.9131832797, "max_line_length": 102, "alphanum_fraction": 0.4839857651, "num_tokens": 2515, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6959583250334526, "lm_q2_score": 0.4378234991142019, "lm_q1q2_score": 0.3047069091038052}}
{"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 \"massmatrix.h\"\r\n#include \"massmatrix_intrinsic.h\"\r\n#include \"edge_lengths.h\"\r\n#include \"normalize_row_sums.h\"\r\n#include \"sparse.h\"\r\n#include \"doublearea.h\"\r\n#include \"repmat.h\"\r\n#include <Eigen/Geometry>\r\n#include <iostream>\r\n\r\ntemplate <typename DerivedV, typename DerivedF, typename Scalar>\r\nIGL_INLINE void igl::massmatrix(\r\n  const Eigen::MatrixBase<DerivedV> & V, \r\n  const Eigen::MatrixBase<DerivedF> & F, \r\n  const MassMatrixType type,\r\n  Eigen::SparseMatrix<Scalar>& M)\r\n{\r\n  using namespace Eigen;\r\n  using namespace std;\r\n\r\n  const int n = V.rows();\r\n  const int m = F.rows();\r\n  const int simplex_size = F.cols();\r\n\r\n  MassMatrixType eff_type = type;\r\n  // Use voronoi of for triangles by default, otherwise barycentric\r\n  if(type == MASSMATRIX_TYPE_DEFAULT)\r\n  {\r\n    eff_type = (simplex_size == 3?MASSMATRIX_TYPE_VORONOI:MASSMATRIX_TYPE_BARYCENTRIC);\r\n  }\r\n\r\n  // Not yet supported\r\n  assert(type!=MASSMATRIX_TYPE_FULL);\r\n\r\n  if(simplex_size == 3)\r\n  {\r\n    // Triangles\r\n    // edge lengths numbered same as opposite vertices\r\n    Matrix<Scalar,Dynamic,3> l;\r\n    igl::edge_lengths(V,F,l);\r\n    return massmatrix_intrinsic(l,F,type,M);\r\n  }else if(simplex_size == 4)\r\n  {\r\n    Matrix<int,Dynamic,1> MI;\r\n    Matrix<int,Dynamic,1> MJ;\r\n    Matrix<Scalar,Dynamic,1> MV;\r\n    assert(V.cols() == 3);\r\n    assert(eff_type == MASSMATRIX_TYPE_BARYCENTRIC);\r\n    MI.resize(m*4,1); MJ.resize(m*4,1); MV.resize(m*4,1);\r\n    MI.block(0*m,0,m,1) = F.col(0);\r\n    MI.block(1*m,0,m,1) = F.col(1);\r\n    MI.block(2*m,0,m,1) = F.col(2);\r\n    MI.block(3*m,0,m,1) = F.col(3);\r\n    MJ = MI;\r\n    // loop over tets\r\n    for(int i = 0;i<m;i++)\r\n    {\r\n      // http://en.wikipedia.org/wiki/Tetrahedron#Volume\r\n      Matrix<Scalar,3,1> v0m3,v1m3,v2m3;\r\n      v0m3.head(V.cols()) = V.row(F(i,0)) - V.row(F(i,3));\r\n      v1m3.head(V.cols()) = V.row(F(i,1)) - V.row(F(i,3));\r\n      v2m3.head(V.cols()) = V.row(F(i,2)) - V.row(F(i,3));\r\n      Scalar v = fabs(v0m3.dot(v1m3.cross(v2m3)))/6.0;\r\n      MV(i+0*m) = v/4.0;\r\n      MV(i+1*m) = v/4.0;\r\n      MV(i+2*m) = v/4.0;\r\n      MV(i+3*m) = v/4.0;\r\n    }\r\n    sparse(MI,MJ,MV,n,n,M);\r\n  }else\r\n  {\r\n    // Unsupported simplex size\r\n    assert(false && \"Unsupported simplex size\");\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::massmatrix<Eigen::Matrix<double, -1, -1, 1, -1, -1>, Eigen::Matrix<int, -1, -1, 0, -1, -1>, double>(Eigen::MatrixBase<Eigen::Matrix<double, -1, -1, 1, -1, -1> > const&, Eigen::MatrixBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> > const&, igl::MassMatrixType, Eigen::SparseMatrix<double, 0, int>&);\r\n// generated by autoexplicit.sh\r\ntemplate void igl::massmatrix<Eigen::Matrix<double, -1, 3, 0, -1, 3>, Eigen::Matrix<int, -1, 4, 0, -1, 4>, double>(Eigen::MatrixBase<Eigen::Matrix<double, -1, 3, 0, -1, 3> > const&, Eigen::MatrixBase<Eigen::Matrix<int, -1, 4, 0, -1, 4> > const&, igl::MassMatrixType, Eigen::SparseMatrix<double, 0, int>&);\r\n// generated by autoexplicit.sh\r\ntemplate void igl::massmatrix<Eigen::Matrix<double, -1, 3, 0, -1, 3>, Eigen::Matrix<int, -1, 3, 0, -1, 3>, double>(Eigen::MatrixBase<Eigen::Matrix<double, -1, 3, 0, -1, 3> > const&, Eigen::MatrixBase<Eigen::Matrix<int, -1, 3, 0, -1, 3> > const&, igl::MassMatrixType, Eigen::SparseMatrix<double, 0, int>&);\r\ntemplate void igl::massmatrix<Eigen::Matrix<double, -1, 3, 1, -1, 3>, Eigen::Matrix<int, -1, 3, 1, -1, 3>, double>(Eigen::MatrixBase<Eigen::Matrix<double, -1, 3, 1, -1, 3> > const&, Eigen::MatrixBase<Eigen::Matrix<int, -1, 3, 1, -1, 3> > const&, igl::MassMatrixType, Eigen::SparseMatrix<double, 0, int>&);\r\ntemplate void igl::massmatrix<Eigen::Matrix<double, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, -1, 0, -1, -1>, double>(Eigen::MatrixBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> > const&, Eigen::MatrixBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> > const&, igl::MassMatrixType, Eigen::SparseMatrix<double, 0, int>&);\r\n#endif\r\n", "meta": {"hexsha": "b9b81789bd0799c41fd9c7d8da95c42219cea5c1", "size": 4310, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "igl/massmatrix.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/massmatrix.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/massmatrix.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": 45.3684210526, "max_line_length": 314, "alphanum_fraction": 0.6303944316, "num_tokens": 1477, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6187804478040616, "lm_q2_score": 0.49218813572079556, "lm_q1q2_score": 0.30455639502516013}}
{"text": "#include <cfloat>\n#include <vector>\n#include <algorithm>\n#include <iostream>\n\n#include <boost/archive/text_oarchive.hpp>\n#include <boost/archive/text_iarchive.hpp>\n#include <boost/serialization/export.hpp>\n\n#include \"core/Common.h\"\n#include \"math/Random.h\"\n#include \"Approximator.h\"\n#include \"ai/AI.h\"\n#include \"TD.h\"\n\nnamespace OpenNero\n{\n\n    /// called right before the agent is born\n    bool TDBrain::initialize(const AgentInitInfo& init)\n    {\n        mInfo = init;\n        this->fitness = mInfo.reward.getInstance();\n\n        int bins = action_bins;\n\n        if (num_tiles > 0)\n        {\n            AssertMsg(action_bins == 0, \"action_bins must be 0 for num_tiles > 0\");\n            AssertMsg(state_bins == 0, \"state_bins must be 0 for num_tiles > 0\");\n            mApproximator.reset(\n                new TilesApproximator(mInfo, num_tiles, num_weights));\n            bins = 7; // XXX force bins > 0 to discretize action_list below\n        }\n        else\n        {\n            AssertMsg(action_bins > 0, \"action_bins > 0 for num_tiles == 0\");\n            AssertMsg(state_bins > 0, \"action_bins > 0 for num_tiles == 0\");\n            mApproximator.reset(\n                new TableApproximator(mInfo, action_bins, state_bins));\n        }\n\n        // Similar to FeatureVectorInfo::enumerate (from AI.cpp).\n        //\n        // We want to enumerate all possible actions in a discrete way, so that\n        // we can store them in a policy table somehow. So, for each action\n        // dimension, if it's discrete we just enumerate the integral values for\n        // that dimension, and if it's continuous, we split it into \"bins\"\n        // different values.\n        //\n        // An example: Suppose some action dimension is continuous and spans the\n        // closed interval [-1, 1]. Additionally suppose we want to split\n        // continuous action dimensions into 5 bins. We'd like to preserve the\n        // actual range of action values, but only store the 5 discrete values\n        // that equally partition this space, i.e., {-1, -.5, 0, .5, 1}. So we\n        // traverse the action dimension from -1 to 1 (inclusive), adding\n        // (hi - lo) / (bins - 1) == (1 - -1) / 4 == 0.5 each time.\n        const FeatureVectorInfo& info = init.actions;\n        action_list.clear();\n        action_list.push_back(info.getInstance());\n        for (size_t i = 0; i < info.size(); ++i)\n        {\n            const double lo = info.getMin(i), hi = info.getMax(i);\n            const double inc = info.isDiscrete(i) ? 1.0f : (hi - lo) / (bins - 1);\n            std::vector< Actions > new_action_list;\n            std::vector< Actions >::const_iterator iter;\n            for (iter = action_list.begin(); iter != action_list.end(); ++iter)\n            {\n                for (double a = lo; a <= hi; a += inc)\n                {\n                    FeatureVector v = *iter;\n                    v[i] = a;\n                    new_action_list.push_back(v);\n                }\n            }\n            action_list = new_action_list;\n        }\n\n        return true;\n    }\n\n    /// called for agent to take its first step\n    Actions TDBrain::start(const TimeType& time, const Observations& new_state)\n    {\n        epsilon_greedy(new_state);\n        action = new_action;\n        state = new_state;\n        return action;\n    }\n\n    /// act based on time, sensor arrays, and last reward\n    Actions TDBrain::act(const TimeType& time, const Observations& new_state, const Reward& reward)\n    {\n\t\tAssertMsg(reward.size() == 1, \"multi-objective rewards not supported\");\n        // select new action and estimate its value\n        double new_Q = epsilon_greedy(new_state);\n        double old_Q = mApproximator->predict(state, action);\n        // Q(s_t, a_t) <- Q(s_t, a_t) + \\alpha [r_{t+1} + \\gamma Q(s_{t+1}, a_{t+1}) - Q(s_t, a_t)\n        mApproximator->update(state, action, old_Q + mAlpha * (reward[0] + mGamma * new_Q - old_Q));\n        action = new_action;\n        state = new_state;\n        return action;\n    }\n\n    /// called to tell agent about its last reward\n    bool TDBrain::end(const TimeType& time, const Reward& reward)\n    {\n\t\tAssertMsg(reward.size() == 1, \"multi-objective rewards not supported\");\n\t\t// Q(s_t, a_t) <- Q(s_t, a_t) + \\alpha [r_{t+1} - Q(s_t, a_t)]\n        // LOG_F_DEBUG(\"ai\", \"TD FINAL UPDATE s1: \" << state << \", a1: \" << action << \", r: \" << reward);\n        double old_Q = mApproximator->predict(state, action);\n        mApproximator->update(state, action, old_Q + mAlpha * (reward[0] - old_Q));\n        return true;\n    }\n\n    /// select action according to the epsilon-greedy policy\n    double TDBrain::epsilon_greedy(const Observations& new_state)\n    {\n        // with chance epsilon, select random action\n        if (RANDOM.randF() < mEpsilon)\n        {\n            new_action = mInfo.actions.getRandom();\n            double value = predict(new_state);\n            return value;\n        }\n        // enumerate all possible actions (actions must be discrete!)\n        new_action = mInfo.actions.getInstance();\n        // select the greedy action in random order\n        std::random_shuffle(action_list.begin(), action_list.end());\n        double max_value = -DBL_MAX;\n        std::vector< Actions >::const_iterator iter;\n        for (iter = action_list.begin(); iter != action_list.end(); ++iter)\n        {\n            double value = mApproximator->predict(new_state, *iter);\n            if (value > max_value)\n            {\n                max_value = value;\n                new_action = *iter;\n            }\n        }\n        // Assuming if you choose max value, you will want to update with that as your prediction\n        return max_value;\n    }\n\n    /// called right before the agent dies\n    bool TDBrain::destroy()\n    {\n        return true;\n    }\n\n    /// serialize this brain to a text string\n    std::string TDBrain::to_string() const\n    {\n        std::ostringstream oss;\n        boost::archive::text_oarchive oa(oss);\n        oa << *this;\n        return oss.str();\n    }\n\n    /// deserialize this brain from a text string\n    void TDBrain::from_string(const std::string& s)\n    {\n        try {\n            std::istringstream iss(s);\n            boost::archive::text_iarchive ia(iss);\n            ia >> *this;\n        } catch (boost::archive::archive_exception const& e) {\n            LOG_F_ERROR(\"ai.rl\", \"unable to load agent because of error, \" << e.what());\n        }\n    }\n}\n\nBOOST_CLASS_EXPORT(OpenNero::TDBrain)\n\n", "meta": {"hexsha": "d68c137598fb392ec120382aa967f936c91ca060", "size": 6461, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "source/ai/rl/TD.cpp", "max_stars_repo_name": "SummitChen/opennero", "max_stars_repo_head_hexsha": "1bb1ba083cf2576e09bb7cfeac013d6940a47afe", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 215.0, "max_stars_repo_stars_event_min_datetime": "2015-08-26T19:41:28.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-19T13:23:17.000Z", "max_issues_repo_path": "source/ai/rl/TD.cpp", "max_issues_repo_name": "SummitChen/opennero", "max_issues_repo_head_hexsha": "1bb1ba083cf2576e09bb7cfeac013d6940a47afe", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2015-11-03T19:40:24.000Z", "max_issues_repo_issues_event_max_datetime": "2019-10-15T11:19:32.000Z", "max_forks_repo_path": "source/ai/rl/TD.cpp", "max_forks_repo_name": "SummitChen/opennero", "max_forks_repo_head_hexsha": "1bb1ba083cf2576e09bb7cfeac013d6940a47afe", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 56.0, "max_forks_repo_forks_event_min_datetime": "2015-08-26T19:42:05.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-26T16:45:41.000Z", "avg_line_length": 36.92, "max_line_length": 105, "alphanum_fraction": 0.5838105556, "num_tokens": 1570, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6442251064863697, "lm_q2_score": 0.47268347662043286, "lm_q1q2_score": 0.3045145630601458}}
{"text": "/* \n * Copyright (c) 2015-2017, 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#include <cmath>\n#include \"HelperFunctions.hpp\"\nusing namespace arma;\n\nconst static double LOWDENSITYFORCUTOFF = 1E-2;\nconst static double HIGHDENSITYORCUTOFF = 100.0;\nconst static double HIPOWER = exp(100.0);\n\ntemplate<class GridComputer, template<class> class GridType>\nvoid CutoffFunctions::WGCVacuumCutoff(unique_ptr<GridType<GridComputer> >& density, const double rhoV, const double rhoStep){\n    \n    const double ct = exp(rhoV/rhoStep);\n    const double ctP1Sq = (ct+1.0)*(ct+1.0);\n    const double rhoStepSq = rhoStep*rhoStep;\n    const double t1 = (rhoStep+ct*rhoStep);\n    const double t2 = (2.0*ctP1Sq*rhoStepSq);\n    const double cutHi = (HIPOWER-1.0)/(HIPOWER+ct);\n    \n    cube* dens = density->getRealGrid();\n    const size_t nSlices = dens->n_slices;\n    const size_t nRows = dens->n_rows;\n    const size_t nCols = dens->n_cols;\n    #pragma omp parallel for default(none) shared(dens)\n    for(size_t x = 0; x < nSlices; ++x){\n        for(size_t col = 0; col < nCols; ++col){\n            for(size_t row = 0; row < nRows; ++row){\n                const double div = dens->at(row,col,x)/rhoStep;\n                if(div < LOWDENSITYFORCUTOFF){\n                    // the cutoff function is taylor expanded to 2nd order\n                    const double d = dens->at(row,col,x);\n                    dens->at(row,col,x) = d/t1 + (-1.0+ct)*d*d/t2;\n                } else if(div > HIGHDENSITYORCUTOFF){\n                    dens->at(row,col,x) = cutHi; // density is much bigger\n                } else {\n                    const double powDens = exp(div);\n                    dens->at(row,col,x) = (powDens-1.0)/(powDens+ct);\n                }\n            }\n        }\n    }\n    density->complete(dens);\n}\n\ndouble CutoffFunctions::vacuumCutoff(const double density, const double rhoV, const double rhoStep){\n    \n    // XXX not happy about this block, as it is a lot of recomputing but to save memory, this function may still be useful\n    const double ct = exp(rhoV/rhoStep);\n    const double ctP1Sq = (ct+1.0)*(ct+1.0);\n    const double rhoStepSq = rhoStep*rhoStep;\n    const double t1 = (rhoStep+ct*rhoStep);\n    const double t2 = (2.0*ctP1Sq*rhoStepSq);\n    const double cutHi = (HIPOWER-1.0)/(HIPOWER+ct);\n    \n    const double div = density/rhoStep;\n    if(div < LOWDENSITYFORCUTOFF){\n        // the cutoff function is taylor expanded to 2nd order\n        return density/t1 + (-1.0+ct)*density*density/t2;\n    } else if(div > HIGHDENSITYORCUTOFF){\n        return cutHi; // density is much bigger\n    } else {\n        const double powDens = exp(div);\n        return (powDens-1.0)/(powDens+ct);\n    }\n}\n\ntemplate<class GridComputer, template<class> class GridType>\nvoid CutoffFunctions::WGCVacuumCutoffDeriv(unique_ptr<GridType<GridComputer> >& density, const double rhoV, const double rhoStep){\n    \n    const double ct = exp(rhoV/rhoStep);\n    const double ctP1Sq = (ct+1.0)*(ct+1.0);\n    const double rhoStepSq = rhoStep*rhoStep;\n    const double hiCtSq = (HIPOWER+ct)*(HIPOWER+ct);\n    const double t1 = (rhoStep+ct*rhoStep);\n    const double t2 = (ctP1Sq*rhoStepSq);\n    const double cutHi = HIPOWER*(1.0+ct)/(hiCtSq*rhoStep);\n    \n    cube* dens = density->getRealGrid();\n    const size_t nSlices = dens->n_slices;\n    const size_t nRows = dens->n_rows;\n    const size_t nCols = dens->n_cols;\n    #pragma omp parallel for default(none) shared(dens)\n    for(size_t x = 0; x < nSlices; ++x){\n        for(size_t col = 0; col < nCols; ++col){\n            for(size_t row = 0; row < nRows; ++row){\n                const double div = dens->at(row,col,x)/rhoStep;\n                if(div < LOWDENSITYFORCUTOFF){\n                    // the cutoff function is taylor expanded to 2nd order\n                    const double d = dens->at(row,col,x);\n                    dens->at(row,col,x) = 1.0/t1 + (-1.0+ct)*d/t2;\n                } else if(div > HIGHDENSITYORCUTOFF){\n                    dens->at(row,col,x) = cutHi; // density is much bigger\n                } else {\n                    const double powDens = exp(div);\n                    const double powCt = powDens+ct;\n                    const double powCtSq = powCt*powCt;\n                    dens->at(row,col,x) = powDens*(1.0+ct)/(powCtSq*rhoStep);\n                }\n            }\n        }\n    }\n}\n\ndouble CutoffFunctions::vacuumCutoffDeriv(const double density, const double rhoV, const double rhoStep){\n    \n    // XXX not happy about this block, as it is a lot of recomputing but to save memory, this function may still be useful\n    const double ct = exp(rhoV/rhoStep);\n    const double ctP1Sq = (ct+1.0)*(ct+1.0);\n    const double rhoStepSq = rhoStep*rhoStep;\n    const double hiCtSq = (HIPOWER+ct)*(HIPOWER+ct);\n    const double t1 = (rhoStep+ct*rhoStep);\n    const double t2 = (ctP1Sq*rhoStepSq);\n    const double cutHi = HIPOWER*(1.0+ct)/(hiCtSq*rhoStep);\n    \n    const double div = density/rhoStep;\n    if(div < LOWDENSITYFORCUTOFF){\n        // the cutoff function is taylor expanded to 2nd order\n        return 1.0/t1 + (-1.0+ct)*density/t2;\n    } else if(div > HIGHDENSITYORCUTOFF){\n        return  cutHi; // density is much bigger\n    } else {\n        const double powDens = exp(div);\n        const double powCt = powDens+ct;\n        const double powCtSq = powCt*powCt;\n        return powDens*(1.0+ct)/(powCtSq*rhoStep);\n    }\n}\n\ndouble MathFunctions::lindhardResponse(const double eta, const double lambda, const double mu){\n    \n    if(eta < 0.0){return 0.0;}\n    // limit for small eta\n    else if(eta < 1e-10){\n        const double lind = 1.0 - lambda + eta*eta * (1.0/3.0-3.0*mu);\n        return lind;\n    } else if(abs(eta-1.0) < 1e-10){\n        const double lind = 2.0 - lambda - 3.0*mu + 20.0*(eta-1.0);\n        return lind;\n    } else if(eta > 3.65){\n        // Taylor expansion for high eta\n        const double etaSq = eta*eta;\n        const double invEtaSq = 1.0/etaSq;\n        const double lind = 3.0*(1.0-mu)*etaSq\n            - lambda - 0.6\n            + invEtaSq *  (-0.13714285714285712\n            + invEtaSq * (-6.39999999999999875E-2\n            + invEtaSq * (-3.77825602968460128E-2\n            + invEtaSq * (-2.51824061652633074E-2\n            + invEtaSq * (-1.80879839616166146E-2\n            + invEtaSq * (-1.36715733124818332E-2\n            + invEtaSq * (-1.07236045520990083E-2\n            + invEtaSq * (-8.65192783339199453E-3 \n            + invEtaSq * (-7.1372762502456763E-3 \n            + invEtaSq * (-5.9945117538835746E-3 \n            + invEtaSq * (-5.10997527675418131E-3 \n            + invEtaSq * (-4.41060829979912465E-3 \n            + invEtaSq * (-3.84763737842981233E-3 \n            + invEtaSq * (-3.38745061493813488E-3 \n            + invEtaSq * (-3.00624946457977689E-3)))))))))))))));\n        return lind;\n    } else {\n        const double lind = 1.0 / (0.5 + 0.25 * (1.-eta*eta) * log((1.0 + eta)\n            / abs(1.0-eta))/eta) - 3.0 * mu * eta*eta - lambda;\n        return lind;\n    }\n}\n\ndouble MathFunctions::derivativeLindhardResponse(const double eta, const double mu){\n    \n    if(eta < 0.0){\n        return 0.0;\n    } else if(eta < 1e-10){\n        return 2*eta*(1.0/3.0 - 3.0*mu);\n    } else if(abs(eta-1.0) < 1e-10){\n        return 40.0;\n    } else {\n        const double etaSq = eta*eta;\n        const double oneMEta = 1-eta;\n        const double onePEta = 1+eta;\n        const double denom = (0.5 + 0.25*(1-eta*eta) * log(onePEta/abs(oneMEta))/eta);\n        const double denomSq = denom*denom;\n        const double gprim = ((etaSq + 1)*0.25 / etaSq * log(abs((1.0+eta)/(oneMEta))) - 0.5/eta) / denomSq - 6*eta*mu;\n        \n        return gprim;\n    }\n}", "meta": {"hexsha": "2b3b8351696c019bf3bb9020244458fd1f6c4c13", "size": 9220, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/HelperFunctions.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": "src/HelperFunctions.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": "src/HelperFunctions.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": 42.8837209302, "max_line_length": 130, "alphanum_fraction": 0.6198481562, "num_tokens": 2714, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6442251064863697, "lm_q2_score": 0.4726834766204328, "lm_q1q2_score": 0.30451456306014574}}
{"text": "//\n//  PowerNet.cpp\n//\n//\n//  Created by Hassan Hijazi on 03/06/2017.\n//\n\n#include \"PowerNet.h\"\n#include <algorithm>\n#include <map>\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 <xlnt/xlnt.hpp>\n#include <gravity/solver.h>\n#include <rapidjson/document.h>\n#include <rapidjson/reader.h>\n#include <rapidjson/istreamwrapper.h>\n#include <armadillo>\n#include <ctime>\n\nusing namespace std;\nusing namespace rapidjson;\n\n\n\nPowerNet::PowerNet() {\n    time ( &_rawtime );\n    _start_date = localtime ( &_rawtime );\n    _start_date->tm_year = 2019 - 1900;\n    _start_date->tm_mon = 0;\n    _start_date->tm_mday = 1;\n    _start_date->tm_hour = 1;\n    _start_date->tm_min = 0;\n    _start_date->tm_sec = 0;\n    mktime ( _start_date );\n//    time ( &_loadrawtime );\n//    _demand_start_date = localtime ( &_loadrawtime );\n//    _demand_start_date->tm_year = 2019 - 1900;\n//    _demand_start_date->tm_mon = 0;\n//    _demand_start_date->tm_mday = 1;\n//    _demand_start_date->tm_hour = 1;\n//    _demand_start_date->tm_min = 0;\n//    _demand_start_date->tm_sec = 0;\n//    mktime ( _demand_start_date );\n    bMVA = 0;\n    pg_min.set_name(\"pg_min\");\n    pg_max.set_name(\"pg_max\");\n    qg_min.set_name(\"qg_min\");\n    qg_max.set_name(\"qg_max\");\n    pb_min.set_name(\"pb_min\");\n    pb_max.set_name(\"pb_max\");\n    qb_min.set_name(\"qb_min\");\n    qb_max.set_name(\"qb_max\");\n    pv_min.set_name(\"pv_min\");\n    pv_max.set_name(\"pv_max\");\n    qv_min.set_name(\"qv_min\");\n    qv_max.set_name(\"qv_max\");\n    pw_min.set_name(\"pw_min\");\n    pw_max.set_name(\"pw_max\");\n    qw_min.set_name(\"qw_min\");\n    qw_max.set_name(\"qw_max\");\n    pv_out.set_name(\"pv_out\");\n    pv_capcost.set_name(\"pv_capcost\");\n    pv_varcost.set_name(\"pv_varcost\");\n    pg_s.set_name(\"pg_s\");\n    qg_s.set_name(\"qg_s\");\n    cb_f.set_name(\"cb_f\");\n    cb_v.set_name(\"cb_v\");\n    c0.set_name(\"c0\");\n    c1.set_name(\"c1\");\n    c2.set_name(\"c2\");\n    ramp_up.set_name(\"ramp_up\");\n    ramp_down.set_name(\"ramp_down\");\n    gen_eff.set_name(\"gen_eff\");\n    min_ut.set_name(\"min_ut\");\n    min_dt.set_name(\"min_dt\");\n    min_diesel_invest.set_name(\"min_diesel_invest\");\n    max_diesel_invest.set_name(\"max_diesel_invest\");\n    min_batt_invest.set_name(\"min_batt_invest\");\n    max_batt_invest.set_name(\"max_batt_invest\");\n    gen_capcost.set_name(\"cg\");\n    expansion_capcost.set_name(\"ce\");\n    inverter_capcost.set_name(\"cb\");\n    th_min.set_name(\"th_min\");\n    th_max.set_name(\"th_max\");\n    cphi.set_name(\"cphi\");\n    sphi.set_name(\"sphi\");\n    cos_d.set_name(\"cos_d\");\n    tan_th_min.set_name(\"tan_th_min\");\n    tan_th_max.set_name(\"tan_th_max\");\n    v_diff_max.set_name(\"v_diff_max\");\n    v_min.set_name(\"v_min\");\n    v_max.set_name(\"v_max\");\n    w_min.set_name(\"w_min\");\n    w_max.set_name(\"w_max\");\n    wr_min.set_name(\"wr_min\");\n    wr_max.set_name(\"wr_max\");\n    wi_min.set_name(\"wi_min\");\n    wi_max.set_name(\"wi_max\");\n    v_s.set_name(\"v_s\");\n    pl.set_name(\"pl\");\n    pl_ratio.set_name(\"pl_ratio\");\n    ql.set_name(\"ql\");\n    g.set_name(\"g\");\n    b.set_name(\"b\");\n    r.set_name(\"r\");\n    x.set_name(\"x\");\n    ch.set_name(\"ch\");\n    as.set_name(\"as\");\n    tr.set_name(\"tr\");\n    S_max.set_name(\"S_max\");\n    eff_a.set_name(\"eff_a\");\n    eff_b.set_name(\"eff_b\");\n    g_ff.set_name(\"g_ff\");\n    g_ft.set_name(\"g_ft\");\n    g_tf.set_name(\"g_tf\");\n    g_tt.set_name(\"g_tt\");\n\n    b_ff.set_name(\"b_ff\");\n    b_ft.set_name(\"b_ft\");\n    b_tf.set_name(\"b_tf\");\n    b_tt.set_name(\"b_tt\");\n    Y.set_name(\"Y\");\n}\n\nPowerNet::~PowerNet() {\n    if(!gens.empty()) {\n        for (Gen* g:gens) {\n            delete g;\n        }\n        gens.clear();\n    }\n    for (Node* n:nodes) {\n        delete n;\n    }\n    nodes.clear();\n    for (Arc* a:arcs) {\n        delete a;\n    }\n    arcs.clear();\n}\n\n\nindices PowerNet::out_arcs_per_node_time() const{\n    auto ids = Et;\n    ids._name = \"out_arcs_per_node_time\";\n    ids._ids = make_shared<vector<vector<size_t>>>();\n    ids._ids->resize(Nt.size());\n    string key, time_stamp;\n    size_t inst = 0;\n    for (auto key: *Nt._keys) {\n        auto pos = key.find_last_of(\",\");\n        auto name = key.substr(pos+1);\n        key = key.substr(0,pos);\n        pos = key.find_last_of(\",\");\n        auto ph = key.substr(pos+1);\n        time_stamp = key.substr(0,pos);\n        auto n = get_node(name);\n        if (!n->_active) {\n            continue;\n        }\n        for (auto a:n->get_out()) {\n            if (!a->_active || !a->has_phase(ph)) {\n                continue;\n            }\n            key = time_stamp+\",\"+ph+\",\"+a->_name;\n            auto it1 = ids._keys_map->find(key);\n            if (it1 == ids._keys_map->end()){\n                throw invalid_argument(\"In function out_arcs_per_node(), unknown key.\");\n            }\n            ids._ids->at(inst).push_back(it1->second);\n        }\n        inst++;\n    }\n    return ids;\n}\n\nindices PowerNet::in_arcs_per_node_time_cont(const map<string,shared_ptr<Scenario>>& scenarios) const{\n    auto ids = Et_c;\n    ids._name = \"in_arcs_per_node_time_cont\";\n    ids._ids = make_shared<vector<vector<size_t>>>();\n    ids._ids->resize(Nt_c.size());\n    string key, time_stamp;\n    size_t inst = 0;\n    for (auto key: *Nt_c._keys) {\n        auto pos = key.find_last_of(\",\");\n        auto scen_name = key.substr(0,key.find_first_of(\",\"));\n        auto name = key.substr(pos+1);\n        key = key.substr(0,pos);\n        pos = key.find_last_of(\",\");\n        auto ph = key.substr(pos+1);\n        time_stamp = key.substr(0,pos);\n        auto n = get_node(name);\n        if (!n->_active) {\n            continue;\n        }\n        for (auto a:n->get_in()) {\n            if (!a->_active || !a->has_phase(ph) || scenarios.at(scen_name)->_out_arcs.count(a->_name)!=0) {\n                continue;\n            }\n            key = time_stamp+\",\"+ph+\",\"+a->_name;\n            auto it1 = ids._keys_map->find(key);\n            if (it1 == ids._keys_map->end()){\n                throw invalid_argument(\"In function in_arcs_per_node_time_cont(), unknown key.\");\n            }\n            ids._ids->at(inst).push_back(it1->second);\n        }\n        inst++;\n    }\n    return ids;\n}\n\nindices PowerNet::in_arcs_per_node_time() const{\n    auto ids = Et;\n    ids._name = \"in_arcs_per_node_time\";\n    ids._ids = make_shared<vector<vector<size_t>>>();\n    ids._ids->resize(Nt.size());\n    string key, time_stamp;\n    size_t inst = 0;\n    for (auto key: *Nt._keys) {\n        auto pos = key.find_last_of(\",\");\n        auto name = key.substr(pos+1);\n        key = key.substr(0,pos);\n        pos = key.find_last_of(\",\");\n        auto ph = key.substr(pos+1);\n        time_stamp = key.substr(0,pos);\n        auto n = get_node(name);\n        if (!n->_active) {\n            continue;\n        }\n        for (auto a:n->get_in()) {\n            if (!a->_active || !a->has_phase(ph)) {\n                continue;\n            }\n            key = time_stamp+\",\"+ph+\",\"+a->_name;\n            auto it1 = ids._keys_map->find(key);\n            if (it1 == ids._keys_map->end()){\n                throw invalid_argument(\"In function in_arcs_per_node_time(), unknown key.\");\n            }\n            ids._ids->at(inst).push_back(it1->second);\n        }\n        inst++;\n    }\n    return ids;\n}\n\nindices PowerNet::to_branch_phase(unsigned ph, bool contingency) const{\n    indices Ei;\n    string phi;\n    switch (ph) {\n        case 1:\n            if(contingency){\n                Ei = Et1_c;\n            }\n            else {\n                Ei = Et1;\n            }\n            phi = \"ph1\";\n            break;\n        case 2:\n            if(contingency){\n                Ei = Et2_c;\n            }\n            else {\n                Ei = Et2;\n            }\n            phi = \"ph2\";\n            break;\n        case 3:\n            if(contingency){\n                Ei = Et3_c;\n            }\n            else {\n                Ei = Et3;\n            }\n            phi = \"ph3\";\n            break;\n        default:\n            break;\n    }\n    indices ids;\n    if(contingency){\n        ids = indices(Nt_c);\n    }\n    else {\n        ids = indices(Nt);\n    }\n\n    ids._name = \"to_branch_phase\"+to_string(ph);\n    ids._ids = make_shared<vector<vector<size_t>>>();\n    ids._ids->resize(Ei.size());\n    string key, time_stamp;\n    size_t inst = 0;\n    for (auto key: *Ei._keys) {\n        auto key_dest = key.substr(key.find_last_of(\",\")+1,key.size());\n        auto key_arc = key.substr(0, key.find_last_of(\",\"));\n        key_arc = key_arc.substr(0, key_arc.find_last_of(\",\"));\n        key_arc = key.substr(key_arc.find_last_of(\",\")+1,key.size());\n        time_stamp = key.substr(0, key.find_last_of(\",\"));//dest\n        time_stamp = time_stamp.substr(0, time_stamp.find_last_of(\",\"));//src\n        time_stamp = time_stamp.substr(0, time_stamp.find_last_of(\",\"));//arcid\n        time_stamp = time_stamp.substr(0, time_stamp.find_last_of(\",\"));//phase\n        auto dest = get_node(key_dest);\n        auto arc = arcMap.at(key_arc);\n        if (!arc->_active) {\n            throw invalid_argument(\"inactive arc in E_phi\");\n        }\n        for (auto ph2:arc->_phases) {\n            if(ph2==ph){\n                continue;\n            }\n            if(dest->_phases.count(ph2)==0){\n                throw invalid_argument(\"In function to_branch_phase(), destination bus \" + key_dest + \" is missing phase \" + to_string(ph2)+\", but arc \" + key_arc + \" has it\");\n            }\n            key = time_stamp+\",ph\"+to_string(ph2)+\",\"+key_dest;\n            auto it1 = ids._keys_map->find(key);\n            if (it1 == ids._keys_map->end()){\n                throw invalid_argument(\"In function to_branch_phase(), unknown key.\");\n            }\n            ids._ids->at(inst).push_back(it1->second);\n        }\n        inst++;\n    }\n    return ids;\n}\n\nindices PowerNet::fixed_to_branch_phase(unsigned ph, bool contingency) const{\n    indices Ei;\n    string phi;\n    switch (ph) {\n        case 1:\n            if(contingency){\n                Ei = Et1_c;\n            }\n            else {\n                Ei = Et1;\n            }\n            phi = \"ph1\";\n            break;\n        case 2:\n            if(contingency){\n                Ei = Et2_c;\n            }\n            else {\n                Ei = Et2;\n            }\n            phi = \"ph2\";\n            break;\n        case 3:\n            if(contingency){\n                Ei = Et3_c;\n            }\n            else {\n                Ei = Et3;\n            }\n            phi = \"ph3\";\n            break;\n        default:\n            break;\n    }\n    indices ids;\n    if(contingency){\n        ids = indices(Nt_c);\n    }\n    else {\n        ids = indices(Nt);\n    }\n    ids._name = \"ref_to_phase\"+to_string(ph);\n    ids._ids = make_shared<vector<vector<size_t>>>();\n    ids._ids->resize(Ei.size());\n    string key, time_stamp;\n    size_t inst = 0;\n    for (auto key: *Ei._keys) {\n        auto key_dest = key.substr(key.find_last_of(\",\")+1,key.size());\n        auto key_arc = key.substr(0, key.find_last_of(\",\"));\n        key_arc = key_arc.substr(0, key_arc.find_last_of(\",\"));\n        key_arc = key.substr(key_arc.find_last_of(\",\")+1,key.size());\n        time_stamp = key.substr(0, key.find_last_of(\",\"));//dest\n        time_stamp = time_stamp.substr(0, time_stamp.find_last_of(\",\"));//src\n        time_stamp = time_stamp.substr(0, time_stamp.find_last_of(\",\"));//arcid\n        time_stamp = time_stamp.substr(0, time_stamp.find_last_of(\",\"));//phase\n        auto arc = arcMap.at(key_arc);\n        if (!arc->_active) {\n            throw invalid_argument(\"inactive arc in E_phi\");\n        }\n        for (auto ph2:arc->_phases) {\n            if(ph2==ph){\n                continue;\n            }\n            key = time_stamp+\",\"+phi+\",\"+key_dest;\n            auto it1 = ids._keys_map->find(key);\n            if (it1 == ids._keys_map->end()){\n                throw invalid_argument(\"In function fixed_to_branch_phase(), unknown key.\");\n            }\n            ids._ids->at(inst).push_back(it1->second);\n        }\n        inst++;\n    }\n    return ids;\n}\n\nindices PowerNet::fixed_from_branch_phase(unsigned ph, bool contingency) const{\n    indices Ei;\n    string phi;\n    switch (ph) {\n        case 1:\n            if(contingency){\n                Ei = Et1_c;\n            }\n            else {\n                Ei = Et1;\n            }\n            phi = \"ph1\";\n            break;\n        case 2:\n            if(contingency){\n                Ei = Et2_c;\n            }\n            else {\n                Ei = Et2;\n            }\n            phi = \"ph2\";\n            break;\n        case 3:\n            if(contingency){\n                Ei = Et3_c;\n            }\n            else {\n                Ei = Et3;\n            }\n            phi = \"ph3\";\n            break;\n        default:\n            break;\n    }\n    indices ids;\n    if(contingency){\n        ids = indices(Nt_c);\n    }\n    else {\n        ids = indices(Nt);\n    }\n    ids._name = \"ref_from_branch_phase\"+to_string(ph);\n    ids._ids = make_shared<vector<vector<size_t>>>();\n    ids._ids->resize(Ei.size());\n    string key, time_stamp;\n    size_t inst = 0;\n    for (auto key: *Ei._keys) {\n        auto key_src = key.substr(0, key.find_last_of(\",\"));\n        key_src = key_src.substr(key_src.find_last_of(\",\")+1,key_src.size());\n        auto key_arc = key.substr(0, key.find_last_of(\",\"));\n        key_arc = key_arc.substr(0, key_arc.find_last_of(\",\"));\n        key_arc = key.substr(key_arc.find_last_of(\",\")+1,key.size());\n        time_stamp = key.substr(0, key.find_last_of(\",\"));//dest\n        time_stamp = time_stamp.substr(0, time_stamp.find_last_of(\",\"));//src\n        time_stamp = time_stamp.substr(0, time_stamp.find_last_of(\",\"));//arcid\n        time_stamp = time_stamp.substr(0, time_stamp.find_last_of(\",\"));//phase\n        auto arc = arcMap.at(key_arc);\n        if (!arc->_active) {\n            throw invalid_argument(\"inactive arc in E_phi\");\n        }\n        for (auto ph2:arc->_phases) {\n            if(ph2==ph){\n                continue;\n            }\n            key = time_stamp+\",\"+phi+\",\"+key_src;\n            auto it1 = ids._keys_map->find(key);\n            if (it1 == ids._keys_map->end()){\n                throw invalid_argument(\"In function fixed_from_branch_phase(), unknown key: \" + key);\n            }\n            ids._ids->at(inst).push_back(it1->second);\n        }\n        inst++;\n    }\n    return ids;\n}\n\nindices PowerNet::from_branch_phase(unsigned ph, bool contingency) const{\n    indices Ei;\n    string phi;\n    switch (ph) {\n        case 1:\n            if(contingency){\n                Ei = Et1_c;\n            }\n            else {\n                Ei = Et1;\n            }\n            phi = \"ph1\";\n            break;\n        case 2:\n            if(contingency){\n                Ei = Et2_c;\n            }\n            else {\n                Ei = Et2;\n            }\n            phi = \"ph2\";\n            break;\n        case 3:\n            if(contingency){\n                Ei = Et3_c;\n            }\n            else {\n                Ei = Et3;\n            }\n            phi = \"ph3\";\n            break;\n        default:\n            break;\n    }\n    indices ids;\n    if(contingency){\n        ids = indices(Nt_c);\n    }\n    else {\n        ids = indices(Nt);\n    }\n    ids._name = \"from_branch_phase\"+to_string(ph);\n    ids._ids = make_shared<vector<vector<size_t>>>();\n    ids._ids->resize(Ei.size());\n    string key, time_stamp;\n    size_t inst = 0;\n    for (auto key: *Ei._keys) {\n        auto key_src = key.substr(0, key.find_last_of(\",\"));\n        key_src = key_src.substr(key_src.find_last_of(\",\")+1,key_src.size());\n        auto key_arc = key.substr(0, key.find_last_of(\",\"));\n        key_arc = key_arc.substr(0, key_arc.find_last_of(\",\"));\n        key_arc = key.substr(key_arc.find_last_of(\",\")+1,key.size());\n        time_stamp = key.substr(0, key.find_last_of(\",\"));//dest\n        time_stamp = time_stamp.substr(0, time_stamp.find_last_of(\",\"));//src\n        time_stamp = time_stamp.substr(0, time_stamp.find_last_of(\",\"));//arcid\n        time_stamp = time_stamp.substr(0, time_stamp.find_last_of(\",\"));//phase\n        auto src = get_node(key_src);\n        auto arc = arcMap.at(key_arc);\n        if (!arc->_active) {\n            throw invalid_argument(\"inactive arc in E_phi\");\n        }\n        for (auto ph2:arc->_phases) {\n            if(ph2==ph){\n                continue;\n            }\n            if(src->_phases.count(ph2)==0){\n                throw invalid_argument(\"In function from_branch_phase(), source bus \" + key_src + \" is missing phase \" + to_string(ph2)+\", but arc \" + key_arc + \" has it\");\n            }\n            key = time_stamp+\",ph\"+to_string(ph2)+\",\"+key_src;\n            auto it1 = ids._keys_map->find(key);\n            if (it1 == ids._keys_map->end()){\n                throw invalid_argument(\"In function from_branch_phase(), unknown key.\");\n            }\n            ids._ids->at(inst).push_back(it1->second);\n        }\n        inst++;\n    }\n    return ids;\n}\n\nindices PowerNet::get_branch_id_phase(unsigned ph, bool contingency) const{\n    indices ids(cross_phase);\n    ids._name = \"branch_phase_id\"+to_string(ph);\n    ids._ids = make_shared<vector<vector<size_t>>>();\n    indices Ei;\n    string phi;\n    switch (ph) {\n        case 1:\n            if(contingency){\n                Ei = Et1_c;\n            }\n            else {\n                Ei = Et1;\n            }\n            phi = \"ph1\";\n            break;\n        case 2:\n            if(contingency){\n                Ei = Et2_c;\n            }\n            else {\n                Ei = Et2;\n            }\n            phi = \"ph2\";\n            break;\n        case 3:\n            if(contingency){\n                Ei = Et3_c;\n            }\n            else {\n                Ei = Et3;\n            }\n            phi = \"ph3\";\n            break;\n        default:\n            break;\n    }\n    ids._ids->resize(1);\n    string key, time_stamp;\n    for (auto key: *Ei._keys) {\n        auto key_arc = key.substr(0, key.find_last_of(\",\"));\n        key_arc = key_arc.substr(0, key_arc.find_last_of(\",\"));\n        key_arc = key.substr(key_arc.find_last_of(\",\")+1,key.size());\n        auto arc = arcMap.at(key_arc);\n        if (!arc->_active) {\n            throw invalid_argument(\"inactive arc in E_phi\");\n        }\n        key = phi+\",\"+phi+\",\"+arc->_name;\n        auto it1 = ids._keys_map->find(key);\n        if (it1 == ids._keys_map->end()){\n            throw invalid_argument(\"In function get_branch_phase(), unknown key: \" + key);\n        }\n        ids._ids->at(0).push_back(it1->second);\n    }\n    return ids;\n}\n\nindices PowerNet::get_branch_phase(unsigned ph, bool contingency) const{\n    indices ids(cross_phase);\n    ids._name = \"branch_phase\"+to_string(ph);\n    ids._ids = make_shared<vector<vector<size_t>>>();\n    indices Ei;\n    string phi;\n    switch (ph) {\n        case 1:\n            if(contingency){\n                Ei = Et1_c;\n            }\n            else {\n                Ei = Et1;\n            }\n            phi = \"ph1\";\n            break;\n        case 2:\n            if(contingency){\n                Ei = Et2_c;\n            }\n            else {\n                Ei = Et2;\n            }\n            phi = \"ph2\";\n            break;\n        case 3:\n            if(contingency){\n                Ei = Et3_c;\n            }\n            else {\n                Ei = Et3;\n            }\n            phi = \"ph3\";\n            break;\n        default:\n            break;\n    }\n    ids._ids->resize(Ei.size());\n    string key, time_stamp;\n    size_t inst = 0;\n    for (auto key: *Ei._keys) {\n        auto key_arc = key.substr(0, key.find_last_of(\",\"));\n        key_arc = key_arc.substr(0, key_arc.find_last_of(\",\"));\n        key_arc = key.substr(key_arc.find_last_of(\",\")+1,key.size());\n        auto arc = arcMap.at(key_arc);\n        if (!arc->_active) {\n            throw invalid_argument(\"inactive arc in E_phi\");\n        }\n        for (auto ph2:arc->_phases) {\n            if(ph2==ph){\n                continue;\n            }\n            key = phi+\",ph\"+to_string(ph2)+\",\"+arc->_name;\n            auto it1 = ids._keys_map->find(key);\n            if (it1 == ids._keys_map->end()){\n                throw invalid_argument(\"In function get_branch_phase(), unknown key.\");\n            }\n            ids._ids->at(inst).push_back(it1->second);\n        }\n        inst++;\n    }\n    return ids;\n}\n\nindices PowerNet::Load_per_node_time() const{\n    auto ids = Lt;\n    ids._name = \"Load_per_node_time\";\n    ids._ids = make_shared<vector<vector<size_t>>>();\n    ids._ids->resize(Nt.size());\n    string key, time_stamp;\n    size_t inst = 0;\n    for (auto key: *Nt._keys) {\n        auto pos = key.find_last_of(\",\");\n        auto name = key.substr(pos+1);\n        key = key.substr(0,pos);\n        pos = key.find_last_of(\",\");\n        auto ph = key.substr(pos+1);\n        key = key.substr(0,pos);\n        auto n = get_node(name);\n        if (!n->_active) {\n            continue;\n        }\n        for (auto p:((Bus*)n)->_loads) {\n            auto l = p.second;\n            if (!l->_active || !l->has_phase(ph)) {\n                continue;\n            }\n            auto lname = key+\",\"+ph+\",\"+l->_name;\n            auto it1 = ids._keys_map->find(lname);\n            if (it1 == ids._keys_map->end()){\n                throw invalid_argument(\"In function loads_per_node_time(), unknown key: \" + lname);\n            }\n            ids._ids->at(inst).push_back(it1->second);\n        }\n        inst++;\n    }\n    return ids;\n}\n\nindices PowerNet::Batt_per_node_time_cont() const{\n    auto ids = Bt_c;\n    ids._name = \"batt_per_node_time_cont\";\n    ids._ids = make_shared<vector<vector<size_t>>>();\n    ids._ids->resize(Nt_c.size());\n    string key, time_stamp;\n    size_t inst = 0;\n    for (auto key: *Nt_c._keys) {\n        auto pos = key.find_last_of(\",\");\n        auto name = key.substr(pos+1);\n        key = key.substr(0,pos);\n        pos = key.find_last_of(\",\");\n        auto ph = key.substr(pos+1);\n        key = key.substr(0,pos);\n        auto n = get_node(name);\n        if (!n->_active) {\n            continue;\n        }\n        for (auto g:((Bus*)n)->_bat) {\n            if (!g->_active || !g->has_phase(ph)) {\n                continue;\n            }\n            auto gname = key+\",\"+g->_name;\n            auto it1 = ids._keys_map->find(gname);\n            if (it1 == ids._keys_map->end()){\n                throw invalid_argument(\"In function batt_per_node_time_cont(), unknown key: \" + gname);\n            }\n            ids._ids->at(inst).push_back(it1->second);\n        }\n        inst++;\n    }\n    return ids;\n}\n\n\nindices PowerNet::Batt_per_node_time() const{\n    auto ids = Bt;\n    ids._name = \"batt_per_node_time\";\n    ids._ids = make_shared<vector<vector<size_t>>>();\n    ids._ids->resize(Nt.size());\n    string key, time_stamp;\n    size_t inst = 0;\n    for (auto key: *Nt._keys) {\n        auto pos = key.find_last_of(\",\");\n        auto name = key.substr(pos+1);\n        key = key.substr(0,pos);\n        pos = key.find_last_of(\",\");\n        auto ph = key.substr(pos+1);\n        key = key.substr(0,pos);\n        auto n = get_node(name);\n        if (!n->_active) {\n            continue;\n        }\n        for (auto g:((Bus*)n)->_bat) {\n            if (!g->_active || !g->has_phase(ph)) {\n                continue;\n            }\n            auto gname = key+\",\"+g->_name;\n            auto it1 = ids._keys_map->find(gname);\n            if (it1 == ids._keys_map->end()){\n                throw invalid_argument(\"In function batt_per_node_time(), unknown key: \" + gname);\n            }\n            ids._ids->at(inst).push_back(it1->second);\n        }\n        inst++;\n    }\n    return ids;\n}\n\nindices PowerNet::PV_per_node_time_cont() const{\n    auto ids = PVt_c;\n    ids._name = \"PV_per_node_time_cont\";\n    ids._ids = make_shared<vector<vector<size_t>>>();\n    ids._ids->resize(Nt_c.size());\n    string key, time_stamp;\n    size_t inst = 0;\n    for (auto key: *Nt_c._keys) {\n        auto pos = key.find_last_of(\",\");\n        auto name = key.substr(pos+1);\n        key = key.substr(0,pos);\n        pos = key.find_last_of(\",\");\n        auto ph = key.substr(pos+1);\n        key = key.substr(0,pos);\n        auto n = get_node(name);\n        if (!n->_active) {\n            continue;\n        }\n        for (auto g:((Bus*)n)->_pv) {\n            if (!g->_active || !g->has_phase(ph)) {\n                continue;\n            }\n            auto gname = key+\",\"+g->_name;\n            auto it1 = ids._keys_map->find(gname);\n            if (it1 == ids._keys_map->end()){\n                throw invalid_argument(\"In function pv_per_node_time(), unknown key: \" + gname);\n            }\n            ids._ids->at(inst).push_back(it1->second);\n        }\n        inst++;\n    }\n    return ids;\n}\n\nindices PowerNet::PV_per_node_time() const{\n    auto ids = PVt;\n    ids._name = \"PV_per_node_time\";\n    ids._ids = make_shared<vector<vector<size_t>>>();\n    ids._ids->resize(Nt.size());\n    string key, time_stamp;\n    size_t inst = 0;\n    for (auto key: *Nt._keys) {\n        auto pos = key.find_last_of(\",\");\n        auto name = key.substr(pos+1);\n        key = key.substr(0,pos);\n        pos = key.find_last_of(\",\");\n        auto ph = key.substr(pos+1);\n        key = key.substr(0,pos);\n        auto n = get_node(name);\n        if (!n->_active) {\n            continue;\n        }\n        for (auto g:((Bus*)n)->_pv) {\n            if (!g->_active || !g->has_phase(ph)) {\n                continue;\n            }\n            auto gname = key+\",\"+g->_name;\n            auto it1 = ids._keys_map->find(gname);\n            if (it1 == ids._keys_map->end()){\n                throw invalid_argument(\"In function pv_per_node_time(), unknown key: \" + gname);\n            }\n            ids._ids->at(inst).push_back(it1->second);\n        }\n        inst++;\n    }\n    return ids;\n}\n\nindices PowerNet::Wind_per_node_time_cont() const{\n    auto ids = Windt_c;\n    ids._name = \"Wind_per_node_time_cont\";\n    ids._ids = make_shared<vector<vector<size_t>>>();\n    ids._ids->resize(Nt_c.size());\n    string key, time_stamp;\n    size_t inst = 0;\n    for (auto key: *Nt_c._keys) {\n        auto pos = key.find_last_of(\",\");\n        auto name = key.substr(pos+1);\n        key = key.substr(0,pos);\n        pos = key.find_last_of(\",\");\n        auto ph = key.substr(pos+1);\n        key = key.substr(0,pos);\n        auto n = get_node(name);\n        if (!n->_active) {\n            continue;\n        }\n        for (auto g:((Bus*)n)->_wind) {\n            if (!g->_active) {\n                continue;\n            }\n            auto gname = key+\",\"+ph+\",\"+g->_name;\n            auto it1 = ids._keys_map->find(gname);\n            if (it1 == ids._keys_map->end()){\n                throw invalid_argument(\"In function Wind_per_node_time_cont(), unknown key: \" + gname);\n            }\n            ids._ids->at(inst).push_back(it1->second);\n        }\n        inst++;\n    }\n    return ids;\n}\n\nindices PowerNet::Wind_per_node_time() const{\n    auto ids = Wt;\n    ids._name = \"Wind_per_node_time\";\n    ids._ids = make_shared<vector<vector<size_t>>>();\n    ids._ids->resize(Nt.size());\n    string key, time_stamp;\n    size_t inst = 0;\n    for (auto key: *Nt._keys) {\n        auto pos = key.find_last_of(\",\");\n        auto name = key.substr(pos+1);\n        key = key.substr(0,pos);\n        pos = key.find_last_of(\",\");\n        auto ph = key.substr(pos+1);\n        key = key.substr(0,pos);\n        auto n = get_node(name);\n        if (!n->_active) {\n            continue;\n        }\n        for (auto g:((Bus*)n)->_wind) {\n            if (!g->_active) {\n                continue;\n            }\n            auto gname = key+\",\"+ph+\",\"+g->_name;\n            auto it1 = ids._keys_map->find(gname);\n            if (it1 == ids._keys_map->end()){\n                throw invalid_argument(\"In function wind_per_node_time(), unknown key: \" + gname);\n            }\n            ids._ids->at(inst).push_back(it1->second);\n        }\n        inst++;\n    }\n    return ids;\n}\n\nindices PowerNet::get_conting_gens_pot(const map<string,shared_ptr<Scenario>>& conts) const{\n    indices ids(\"gens_cont_pot\");\n    for (auto &sc_p: conts) {\n        auto year_month_day_hour = sc_p.second->_year_month_day_hour;\n        auto h0 = get<3>(sc_p.second->_year_month_day_hour);\n        auto nb_hours = sc_p.second->_nb_hours;\n        string start_day_type = \"week\";\n        if(is_weekend(year_month_day_hour)){\n            start_day_type = \"weekend\";\n        }\n        string day_type = start_day_type;\n        auto cont_key = sc_p.first;\n        for (auto h = 0; h<nb_hours; h++) {\n            int hour = (h0+h)%24;\n            if((h+h0)%72>=48 && start_day_type==\"week\"){\n                day_type = \"weekend\";\n            }\n            else if((h+h0)%72>=48 && start_day_type==\"weekend\"){\n                day_type = \"week\";\n            }\n            else if((h+h0)%72>=24){\n                day_type = \"peak\";\n            }\n            auto time_stamp = \"year\"+to_string(get<0>(sc_p.second->_year_month_day_hour)-2018)+\",\";\n            auto season_str = _months_season.at((get<1>(sc_p.second->_year_month_day_hour) + (h+h0)/72)%_months_season.size()); /* < change season every 72 hours */\n            time_stamp += season_str +\",\"+day_type+\",\"+to_string(hour+1);\n            for (auto g: _potential_diesel_gens) {\n                auto node_key = sc_p.first+\",\"+g->_bus->_name;\n                if(g->_active && !N_out.has(node_key) && sc_p.second->_out_gens.count(g->_name)==0){\n                    for (auto i = 0; i<3; i++) {\n                        if(g->_phases.count(i+1)!=0 && g->_bus->_phases.count(i+1)!=0){\n                            auto ph_key = \"ph\"+to_string(i+1)+\",\"+g->_name;\n                            ids.insert(sc_p.first+\",\"+time_stamp+\",\"+ph_key);\n                        }\n                    }\n                }\n            }\n        }\n    }\n    return ids;\n}\n\nbool isolated_node(Bus* b, const shared_ptr<Scenario>& sc){\n    bool isolated = true;\n    if(!b->_loads.empty()){/* If it has loads */\n        for (auto l:b->_loads) {/* If it has a critical load */\n            if(l.second->_critical_level>0){\n                isolated = false;\n                break;\n            }\n        }\n//        if(isolated){\n//            for (auto g:b->_gen) {/* If it has a generator that is not outaged */\n//                if(sc->_out_gens.count(g->_name)==0){\n//                    isolated = false;\n//                    break;\n//                }\n//            }\n//        }\n//        if(!b->_p || !b->_wind.empty()){/* If it has renewable generation */\n//            isolated = false;\n//        }\n    }\n    if(isolated){\n        for (auto a:b->branches) {/* If at least one edge is not outaged */\n            if(sc->_out_arcs.count(a->_name)==0){\n                isolated = false;\n                break;\n            }\n        }\n    }\n    return isolated;\n}\n\nindices PowerNet::get_conting_nodes(const map<string,shared_ptr<Scenario>>& conts) const{\n    indices ids(\"nodes_cont\");\n    for (auto &sc_p: conts) {\n        auto year_month_day_hour = sc_p.second->_year_month_day_hour;\n        auto h0 = get<3>(sc_p.second->_year_month_day_hour);\n        auto nb_hours = sc_p.second->_nb_hours;\n        string start_day_type = \"week\";\n        if(is_weekend(year_month_day_hour)){\n            start_day_type = \"weekend\";\n        }\n        string day_type = start_day_type;\n        auto cont_key = sc_p.first;\n        for (auto h = 0; h<nb_hours; h++) {\n            int hour = (h0+h)%24;\n            if((h+h0)%72>=48 && start_day_type==\"week\"){\n                day_type = \"weekend\";\n            }\n            else if((h+h0)%72>=48 && start_day_type==\"weekend\"){\n                day_type = \"week\";\n            }\n            else if((h+h0)%72>=24){\n                day_type = \"peak\";\n            }\n            auto time_stamp = \"year\"+to_string(get<0>(sc_p.second->_year_month_day_hour)-2018)+\",\";\n            auto season_str = _months_season.at((get<1>(sc_p.second->_year_month_day_hour) + (h+h0)/72)%_months_season.size()); /* < change season every 72 hours */\n            time_stamp += season_str +\",\"+day_type+\",\"+to_string(hour+1);\n            for (auto n: nodes) {\n                auto b = (Bus*)n;\n                if(!isolated_node(b,sc_p.second)){\n                    for (auto i = 0; i<3; i++) {\n                        if(n->_phases.count(i+1)!=0){\n                            auto ph_key = \"ph\"+to_string(i+1)+\",\"+n->_name;\n                            ids.insert(sc_p.first+\",\"+time_stamp+\",\"+ph_key);\n                        }\n                    }\n                }\n            }\n        }\n    }\n    return ids;\n}\n\n\nindices PowerNet::get_outaged_nodes(const map<string,shared_ptr<Scenario>>& conts) const{\n    indices ids(\"nodes_out\");\n    for (auto &sc_p: conts) {\n        for (auto n: nodes) {\n            auto b = (Bus*)n;\n            if(isolated_node(b,sc_p.second)){\n                ids.insert(sc_p.first+\",\"+n->_name);\n            }\n        }\n    }\n    return ids;\n}\n\n\nindices PowerNet::get_conting_gens(const map<string,shared_ptr<Scenario>>& conts) const{\n    indices ids(\"gens_cont\");\n    for (auto &sc_p: conts) {\n        auto year_month_day_hour = sc_p.second->_year_month_day_hour;\n        auto h0 = get<3>(sc_p.second->_year_month_day_hour);\n        auto nb_hours = sc_p.second->_nb_hours;\n        string start_day_type = \"week\";\n        if(is_weekend(year_month_day_hour)){\n            start_day_type = \"weekend\";\n        }\n        string day_type = start_day_type;\n        auto cont_key = sc_p.first;\n        for (auto h = 0; h<nb_hours; h++) {\n            int hour = (h0+h)%24;\n            if((h+h0)%72>=48 && start_day_type==\"week\"){\n                day_type = \"weekend\";\n            }\n            else if((h+h0)%72>=48 && start_day_type==\"weekend\"){\n                day_type = \"week\";\n            }\n            else if((h+h0)%72>=24){\n                day_type = \"peak\";\n            }\n            auto time_stamp = \"year\"+to_string(get<0>(sc_p.second->_year_month_day_hour)-2018)+\",\";\n            auto season_str = _months_season.at((get<1>(sc_p.second->_year_month_day_hour) + (h+h0)/72)%_months_season.size()); /* < change season every 72 hours */\n            time_stamp += season_str +\",\"+day_type+\",\"+to_string(hour+1);\n            for (auto g: gens) {\n                auto node_key = sc_p.first+\",\"+g->_bus->_name;\n                if(g->_active && !N_out.has(node_key) && sc_p.second->_out_gens.count(g->_name)==0){\n                    for (auto i = 0; i<3; i++) {\n                        if(g->_phases.count(i+1)!=0 && g->_bus->_phases.count(i+1)!=0){\n                            auto ph_key = \"ph\"+to_string(i+1)+\",\"+g->_name;\n                            ids.insert(sc_p.first+\",\"+time_stamp+\",\"+ph_key);\n                        }\n                    }\n                }\n            }\n        }\n    }\n    return ids;\n}\n\n\nindices PowerNet::get_phase(const indices& set, int ph) const{\n    indices Eti(\"Et\"+to_string(ph)+\"_c\");\n    auto ph_str = \"ph\"+to_string(ph);\n    for (auto &edge_key: *set._keys) {\n        auto pos = edge_key.find_last_of(\",\");\n        auto key = edge_key.substr(0,pos);\n        pos = key.find_last_of(\",\");\n        key = key.substr(0,pos);\n        pos = key.find_last_of(\",\");\n        key = key.substr(0,pos);\n        pos = key.find_last_of(\",\");\n        auto ph = key.substr(pos+1);\n        if(ph==ph_str){\n            Eti.add(edge_key);\n        }\n    }\n    return Eti;\n}\n\nindices PowerNet::get_tielines() const{\n    indices ids(\"Tielines\");\n    for (auto a: _potential_expansion) {\n        if(a->_tie_line){\n            for (auto i = 0; i<3; i++) {\n                if(a->_phases.count(i+1)!=0 && a->_src->_phases.count(i+1)!=0 && a->_dest->_phases.count(i+1)!=0){\n                    auto ph_key = \"ph\"+to_string(i+1)+\",\"+a->_name;\n                    ids.insert(ph_key);\n                }\n            }\n        }\n    }\n    return ids;\n}\n\nindices PowerNet::get_conting_arcs(const map<string,shared_ptr<Scenario>>& conts) const{\n    indices ids(\"arcs_cont\");\n    for (auto &sc_p: conts) {\n        auto year_month_day_hour = sc_p.second->_year_month_day_hour;\n        auto h0 = get<3>(sc_p.second->_year_month_day_hour);\n        auto nb_hours = sc_p.second->_nb_hours;\n        string start_day_type = \"week\";\n        if(is_weekend(year_month_day_hour)){\n            start_day_type = \"weekend\";\n        }\n        string day_type = start_day_type;\n        auto cont_key = sc_p.first;\n        for (auto h = 0; h<nb_hours; h++) {\n            int hour = (h0+h)%24;\n            if((h+h0)%72>=48 && start_day_type==\"week\"){\n                day_type = \"weekend\";\n            }\n            else if((h+h0)%72>=48 && start_day_type==\"weekend\"){\n                day_type = \"week\";\n            }\n            else if((h+h0)%72>=24){\n                day_type = \"peak\";\n            }\n            auto time_stamp = \"year\"+to_string(get<0>(sc_p.second->_year_month_day_hour)-2018)+\",\";\n            auto season_str = _months_season.at((get<1>(sc_p.second->_year_month_day_hour) + (h+h0)/72)%_months_season.size()); /* < change season every 72 hours */\n            time_stamp += season_str +\",\"+day_type+\",\"+to_string(hour+1);\n            for (auto a: arcs) {\n                auto src_key = sc_p.first+\",\"+a->_src->_name;\n                auto dest_key = sc_p.first+\",\"+a->_dest->_name;\n                if(a->_active && !N_out.has(src_key) && !N_out.has(dest_key) && sc_p.second->_out_arcs.count(a->_name)==0){\n                    for (auto i = 0; i<3; i++) {\n                        if(a->_phases.count(i+1)!=0 && a->_src->_phases.count(i+1)!=0 && a->_dest->_phases.count(i+1)!=0){\n                            auto ph_key = \"ph\"+to_string(i+1)+\",\"+a->_name;\n                            ids.insert(sc_p.first+\",\"+time_stamp+\",\"+ph_key);\n                        }\n                    }\n                }\n            }\n        }\n    }\n    return ids;\n}\n\nindices PowerNet::get_conting_arcs_exist(const map<string,shared_ptr<Scenario>>& conts) const{\n    indices ids(\"arcs_cont_exist\");\n    for (auto &sc_p: conts) {\n        auto year_month_day_hour = sc_p.second->_year_month_day_hour;\n        auto h0 = get<3>(sc_p.second->_year_month_day_hour);\n        auto nb_hours = sc_p.second->_nb_hours;\n        string start_day_type = \"week\";\n        if(is_weekend(year_month_day_hour)){\n            start_day_type = \"weekend\";\n        }\n        string day_type = start_day_type;\n        auto cont_key = sc_p.first;\n        for (auto h = 0; h<nb_hours; h++) {\n            int hour = (h0+h)%24;\n            if((h+h0)%72>=48 && start_day_type==\"week\"){\n                day_type = \"weekend\";\n            }\n            else if((h+h0)%72>=48 && start_day_type==\"weekend\"){\n                day_type = \"week\";\n            }\n            else if((h+h0)%72>=24){\n                day_type = \"peak\";\n            }\n            auto time_stamp = \"year\"+to_string(get<0>(sc_p.second->_year_month_day_hour)-2018)+\",\";\n            auto season_str = _months_season.at((get<1>(sc_p.second->_year_month_day_hour) + (h+h0)/72)%_months_season.size()); /* < change season every 72 hours */\n            time_stamp += season_str +\",\"+day_type+\",\"+to_string(hour+1);\n            for (auto a: _exist_arcs) {\n                auto src_key = sc_p.first+\",\"+a->_src->_name;\n                auto dest_key = sc_p.first+\",\"+a->_dest->_name;\n                if(a->_active && !N_out.has(src_key) && !N_out.has(dest_key) && sc_p.second->_out_arcs.count(a->_name)==0){\n                    for (auto i = 0; i<3; i++) {\n                        if(a->_phases.count(i+1)!=0 && a->_src->_phases.count(i+1)!=0 && a->_dest->_phases.count(i+1)!=0){\n                            auto ph_key = \"ph\"+to_string(i+1)+\",\"+a->_name;\n                            ids.insert(sc_p.first+\",\"+time_stamp+\",\"+ph_key);\n                        }\n                    }\n                }\n            }\n        }\n    }\n    return ids;\n}\n\nindices PowerNet::get_conting_arcs_pot(const map<string,shared_ptr<Scenario>>& conts) const{\n    indices ids(\"arcs_cont_pot\");\n    for (auto &sc_p: conts) {\n        auto year_month_day_hour = sc_p.second->_year_month_day_hour;\n        auto h0 = get<3>(sc_p.second->_year_month_day_hour);\n        auto nb_hours = sc_p.second->_nb_hours;\n        string start_day_type = \"week\";\n        if(is_weekend(year_month_day_hour)){\n            start_day_type = \"weekend\";\n        }\n        string day_type = start_day_type;\n        auto cont_key = sc_p.first;\n        for (auto h = 0; h<nb_hours; h++) {\n            int hour = (h0+h)%24;\n            if((h+h0)%72>=48 && start_day_type==\"week\"){\n                day_type = \"weekend\";\n            }\n            else if((h+h0)%72>=48 && start_day_type==\"weekend\"){\n                day_type = \"week\";\n            }\n            else if((h+h0)%72>=24){\n                day_type = \"peak\";\n            }\n            auto time_stamp = \"year\"+to_string(get<0>(sc_p.second->_year_month_day_hour)-2018)+\",\";\n            auto season_str = _months_season.at((get<1>(sc_p.second->_year_month_day_hour) + (h+h0)/72)%_months_season.size()); /* < change season every 72 hours */\n            time_stamp += season_str +\",\"+day_type+\",\"+to_string(hour+1);\n            for (auto a: _potential_expansion) {\n                auto src_key = sc_p.first+\",\"+a->_src->_name;\n                auto dest_key = sc_p.first+\",\"+a->_dest->_name;\n                if(a->_active && !N_out.has(src_key) && !N_out.has(dest_key) && sc_p.second->_out_arcs.count(a->_name)==0){\n                    for (auto i = 0; i<3; i++) {\n                        if(a->_phases.count(i+1)!=0 && a->_src->_phases.count(i+1)!=0 && a->_dest->_phases.count(i+1)!=0){\n                            auto ph_key = \"ph\"+to_string(i+1)+\",\"+a->_name;\n                            ids.insert(sc_p.first+\",\"+time_stamp+\",\"+ph_key);\n                        }\n                    }\n                }\n            }\n        }\n    }\n    return ids;\n}\n\nindices PowerNet::get_critical(int level) const{/**< Get indices of nodes with critical loads corresopnding to the level specified or higher */\n    indices critical(\"critical\");\n    for (auto n:nodes) {\n        if(((Bus*)n)->_critical_level>= level){\n            for(auto const &i: n->_phases){\n                auto ph_key = \"ph\"+to_string(i)+\",\"+n->_name;\n                critical.add(ph_key);\n            }\n        }\n    }\n    return critical;\n}\n\nindices PowerNet::get_all_conting(const map<string,shared_ptr<Scenario>>& scenarios) const{\n    indices ids(\"all_conting\");\n    for(auto &pair: scenarios){\n        ids.insert(pair.first);\n    }\n    return ids;\n}\n\nindices PowerNet::get_time_ids_conting(const map<string,shared_ptr<Scenario>>& scenarios) const{\n    indices ids(\"all_conting_time\");\n    for(auto sc_p: scenarios){\n        auto year_month_day_hour = sc_p.second->_year_month_day_hour;\n        auto h0 = get<3>(sc_p.second->_year_month_day_hour);\n        auto nb_hours = sc_p.second->_nb_hours;\n        string start_day_type = \"week\";\n        if(is_weekend(year_month_day_hour)){\n            start_day_type = \"weekend\";\n        }\n        string day_type = start_day_type;\n        auto cont_key = sc_p.first;\n        for (auto h = 0; h<nb_hours; h++) {\n            int hour = (h0+h)%24;\n            if((h+h0)%72>=48 && start_day_type==\"week\"){\n                day_type = \"weekend\";\n            }\n            else if((h+h0)%72>=48 && start_day_type==\"weekend\"){\n                day_type = \"week\";\n            }\n            else if((h+h0)%72>=24){\n                day_type = \"peak\";\n            }\n            auto time_stamp = \"year\"+to_string(get<0>(sc_p.second->_year_month_day_hour)-2018)+\",\";\n            auto season_str = _months_season.at((get<1>(sc_p.second->_year_month_day_hour) + (h+h0)/72)%_months_season.size()); /* < change season every 72 hours */\n            time_stamp += season_str +\",\"+day_type+\",\"+to_string(hour+1);\n            auto key = cont_key+\",\"+time_stamp;\n            ids.insert(key);\n        }\n    }\n    return ids;\n}\n\n\nint nb_time_steps(const map<string,shared_ptr<Scenario>>& scenarios){\n    int res = 0;\n    for(auto sc_p: scenarios){\n        res += sc_p.second->_nb_hours;\n    }\n    return res;\n}\n\nindices PowerNet::out_arcs_per_node_time_cont(const map<string,shared_ptr<Scenario>>& scenarios) const{\n    auto ids = Et_c;\n    ids._name = \"out_arcs_per_node_time_cont\";\n    ids._ids = make_shared<vector<vector<size_t>>>();\n    ids._ids->resize(Nt_c.size());\n    string key, time_stamp;\n    size_t inst = 0;\n    for (auto key: *Nt_c._keys) {\n        auto pos = key.find_last_of(\",\");\n        auto scen_name = key.substr(0,key.find_first_of(\",\"));\n        auto name = key.substr(pos+1);\n        key = key.substr(0,pos);\n        pos = key.find_last_of(\",\");\n        auto ph = key.substr(pos+1);\n        time_stamp = key.substr(0,pos);\n        auto n = get_node(name);\n        if (!n->_active) {\n            continue;\n        }\n        for (auto a:n->get_out()) {\n            if (!a->_active || !a->has_phase(ph) || scenarios.at(scen_name)->_out_arcs.count(a->_name)!=0) {\n                continue;\n            }\n            key = time_stamp+\",\"+ph+\",\"+a->_name;\n            auto it1 = ids._keys_map->find(key);\n            if (it1 == ids._keys_map->end()){\n                throw invalid_argument(\"In function out_arcs_per_node_time_cont(), unknown key.\");\n            }\n            ids._ids->at(inst).push_back(it1->second);\n        }\n        inst++;\n    }\n    return ids;\n}\n\n//indices PowerNet::out_arcs_per_node_time_cont(const map<string,shared_ptr<Scenario>>& scenarios) const{\n//    auto ids = Et_c;\n//    ids._name = \"out_arcs_per_node_time_cont\";\n//    ids._ids = make_shared<vector<vector<size_t>>>();\n//    auto nT = nb_time_steps(scenarios);\n//    ids._ids->resize(nodes.size()*nT);\n//    string key, time_stamp, cont_key;\n//    size_t inst = 0;\n//    for(auto sc_p: scenarios){\n//        auto year_month_day_hour = sc_p.second->_year_month_day_hour;\n//        auto h0 = get<3>(sc_p.second->_year_month_day_hour);\n//        auto nb_hours = sc_p.second->_nb_hours;\n//        string start_day_type = \"week\";\n//        if(is_weekend(year_month_day_hour)){\n//            start_day_type = \"weekend\";\n//        }\n//        string day_type = start_day_type;\n//        cont_key = sc_p.first;\n//        for (auto h = 0; h<nb_hours; h++) {\n//            int hour = (h0+h)%24;\n//            if((h+h0)%72>=48 && start_day_type==\"week\"){\n//                day_type = \"weekend\";\n//            }\n//            else if((h+h0)%72>=48 && start_day_type==\"weekend\"){\n//                day_type = \"week\";\n//            }\n//            else if((h+h0)%72>=24){\n//                day_type = \"peak\";\n//            }\n//            for (auto key: *N_ph._keys) {\n//                auto pos = key.find_last_of(\",\");\n//                auto name = key.substr(pos+1);\n//                key = key.substr(0,pos);\n//                pos = key.find_last_of(\",\");\n//                auto ph = key.substr(pos+1);\n//                time_stamp = \"year\"+to_string(get<0>(sc_p.second->_year_month_day_hour)-2018)+\",\";\n//                auto season_str = _months_season.at(get<1>(sc_p.second->_year_month_day_hour));\n//                time_stamp += season_str +\",\"+day_type+\",\"+to_string(hour);\n//                auto n = get_node(name);\n//                if (!n->_active) {\n//                    continue;\n//                }\n//                for (auto a:n->get_out()) {\n//                    if (!a->_active || !a->has_phase(ph) || sc_p.second->_out_arcs.count(a->_name)!=0) {\n//                        continue;\n//                    }\n//                    key = cont_key+\",\"+time_stamp+\",\"+ph+\",\"+a->_name;\n//                    auto it1 = ids._keys_map->find(key);\n//                    if (it1 == ids._keys_map->end()){\n//                        throw invalid_argument(\"In function out_arcs_per_node_time_cont(), unknown key.\");\n//                    }\n//                    ids._ids->at(inst).push_back(it1->second);\n//                }\n//                inst++;\n//            }\n//        }\n//    }\n//    return ids;\n//}\n\n//indices PowerNet::in_arcs_per_node_time_cont(const map<string,shared_ptr<Scenario>>& scenarios) const{\n//    auto ids = Et_c;\n//    ids._name = \"in_arcs_per_node_time_cont\";\n//    ids._ids = make_shared<vector<vector<size_t>>>();\n//    auto nT = nb_time_steps(scenarios);\n//    ids._ids->resize(nodes.size()*nT);\n//    string key, time_stamp, cont_key;\n//    size_t inst = 0;\n//    for(auto sc_p: scenarios){\n//        auto year_month_day_hour = sc_p.second->_year_month_day_hour;\n//        auto h0 = get<3>(sc_p.second->_year_month_day_hour);\n//        auto nb_hours = sc_p.second->_nb_hours;\n//        string start_day_type = \"week\";\n//        if(is_weekend(year_month_day_hour)){\n//            start_day_type = \"weekend\";\n//        }\n//        string day_type = start_day_type;\n//        cont_key = sc_p.first;\n//        for (auto h = 0; h<nb_hours; h++) {\n//            int hour = (h0+h)%24;\n//            if((h+h0)%72>=48 && start_day_type==\"week\"){\n//                day_type = \"weekend\";\n//            }\n//            else if((h+h0)%72>=48 && start_day_type==\"weekend\"){\n//                day_type = \"week\";\n//            }\n//            else if((h+h0)%72>=24){\n//                day_type = \"peak\";\n//            }\n//            for (auto key: *N_ph._keys) {\n//                auto pos = key.find_last_of(\",\");\n//                auto name = key.substr(pos+1);\n//                key = key.substr(0,pos);\n//                pos = key.find_last_of(\",\");\n//                auto ph = key.substr(pos+1);\n//                time_stamp = \"year\"+to_string(get<0>(sc_p.second->_year_month_day_hour)-2018)+\",\";\n//                auto season_str = _months_season.at(get<1>(sc_p.second->_year_month_day_hour));\n//                time_stamp += season_str +\",\"+day_type+\",\"+to_string(hour);\n//                auto n = get_node(name);\n//                if (!n->_active) {\n//                    continue;\n//                }\n//                for (auto a:n->get_in()) {\n//                    if (!a->_active || !a->has_phase(ph) || sc_p.second->_out_arcs.count(a->_name)!=0) {\n//                        continue;\n//                    }\n//                    key = cont_key+\",\"+time_stamp+\",\"+ph+\",\"+a->_name;\n//                    auto it1 = ids._keys_map->find(key);\n//                    if (it1 == ids._keys_map->end()){\n//                        throw invalid_argument(\"In function in_arcs_per_node_time_cont(), unknown key.\");\n//                    }\n//                    ids._ids->at(inst).push_back(it1->second);\n//                }\n//                inst++;\n//            }\n//        }\n//    }\n//    return ids;\n//}\n\n\nindices PowerNet::gens_cont(const map<string,shared_ptr<Scenario>>& conts) const{\n    indices ids(\"gens_cont\");\n    for (auto &sc_p: conts) {\n        auto cont_key = sc_p.first;\n        for (auto g: gens) {\n            auto node_key = sc_p.first+\",\"+g->_bus->_name;\n            if(g->_active && !N_out.has(node_key) && sc_p.second->_out_gens.count(g->_name)==0){\n                for (auto i = 0; i<3; i++) {\n                    if(g->_phases.count(i+1)!=0 && g->_bus->_phases.count(i+1)!=0){\n                        auto ph_key = \"ph\"+to_string(i+1)+\",\"+g->_name;\n                        ids.insert(sc_p.first+\",\"+ph_key);\n                    }\n                }\n            }\n        }\n    }\n    return ids;\n}\n\nindices PowerNet::gens_time(const indices& g_conts) const{\n    auto ids = Gt_c;\n    ids._name = \"gens_time\";\n    ids._ids = make_shared<vector<vector<size_t>>>();\n    ids._ids->resize(g_conts.size());\n    string key, time_stamp;\n    size_t inst = 0;\n    for (auto key: *g_conts._keys) {\n        auto pos = key.find_first_of(\",\");\n        auto scen_name = key.substr(0,pos);\n        auto name = key.substr(pos+1);\n        auto sc_p = this->_res_scenarios.at(scen_name);\n        auto year_month_day_hour = sc_p->_year_month_day_hour;\n        auto h0 = get<3>(sc_p->_year_month_day_hour);\n        auto nb_hours = sc_p->_nb_hours;\n        string start_day_type = \"week\";\n        if(is_weekend(year_month_day_hour)){\n            start_day_type = \"weekend\";\n        }\n        string day_type = start_day_type;\n//        auto cont_key = sc_p.first;\n        for (auto h = 0; h<nb_hours; h++) {\n            int hour = (h0+h)%24;\n            if((h+h0)%72>=48 && start_day_type==\"week\"){\n                day_type = \"weekend\";\n            }\n            else if((h+h0)%72>=48 && start_day_type==\"weekend\"){\n                day_type = \"week\";\n            }\n            else if((h+h0)%72>=24){\n                day_type = \"peak\";\n            }\n            auto time_stamp = \"year\"+to_string(get<0>(sc_p->_year_month_day_hour)-2018)+\",\";\n            auto season_str = _months_season.at((get<1>(sc_p->_year_month_day_hour) + (h+h0)/72)%_months_season.size()); /* < change season every 72 hours */\n            time_stamp += season_str +\",\"+day_type+\",\"+to_string(hour+1);\n            auto gname = scen_name + \",\" + time_stamp + \",\" + name;\n            auto it1 = ids._keys_map->find(gname);\n            if (it1 == ids._keys_map->end()){\n                throw invalid_argument(\"In function gens_time(), unknown key: \" + gname);\n            }\n            ids._ids->at(inst).push_back(it1->second);\n        }\n        inst++;\n    }\n    return ids;\n}\n\n\nindices PowerNet::gens_per_node_time_cont(const map<string,shared_ptr<Scenario>>& scenarios) const{\n    auto ids = Gt_c;\n    ids._name = \"gens_per_node_time_cont\";\n    ids._ids = make_shared<vector<vector<size_t>>>();\n    ids._ids->resize(Nt_c.size());\n    string key, time_stamp;\n    size_t inst = 0;\n    for (auto key: *Nt_c._keys) {\n        auto pos = key.find_last_of(\",\");\n        auto scen_name = key.substr(0,key.find_first_of(\",\"));\n        auto name = key.substr(pos+1);\n        key = key.substr(0,pos);\n        pos = key.find_last_of(\",\");\n        auto ph = key.substr(pos+1);\n        key = key.substr(0,pos);\n        auto n = get_node(name);\n        if (!n->_active) {\n            continue;\n        }\n        for (auto g:((Bus*)n)->_gen) {\n            if (!g->_active || !g->has_phase(ph) || scenarios.at(scen_name)->_out_gens.count(g->_name)!=0) {\n                continue;\n            }\n            auto gname = key+\",\"+ph+\",\"+g->_name;\n            auto it1 = ids._keys_map->find(gname);\n            if (it1 == ids._keys_map->end()){\n                throw invalid_argument(\"In function gens_per_node_time_cont(), unknown key: \" + gname);\n            }\n            ids._ids->at(inst).push_back(it1->second);\n        }\n        inst++;\n    }\n    return ids;\n}\n\n//indices PowerNet::gens_per_node_time_cont(const map<string,shared_ptr<Scenario>>& scenarios) const{\n//    auto ids = Gt_c;\n//    ids._name = \"gens_per_node_time_cont\";\n//    ids._ids = make_shared<vector<vector<size_t>>>();\n//    ids._ids->resize(scenarios.size()*Nt.size());\n//    string key, cont_key;\n//    size_t inst = 0;\n//    for(auto sc_p: scenarios){\n//        cont_key = sc_p.first;\n//        for (auto key: *Nt._keys) {\n//            auto pos = key.find_last_of(\",\");\n//            auto name = key.substr(pos+1);\n//            key = key.substr(0,pos);\n//            pos = key.find_last_of(\",\");\n//            auto ph = key.substr(pos+1);\n//            key = key.substr(0,pos);\n//            auto n = get_node(name);\n//            if (!n->_active) {\n//                continue;\n//            }\n//            for (auto g:((Bus*)n)->_gen) {\n//                if (!g->_active || !g->has_phase(ph) || sc_p.second->_out_gens.count(g->_name)!=0) {\n//                    continue;\n//                }\n//                auto gname = cont_key+\",\"+key+\",\"+ph+\",\"+g->_name;\n//                auto it1 = ids._keys_map->find(gname);\n//                if (it1 == ids._keys_map->end()){\n//                    throw invalid_argument(\"In function gens_per_node_time_cont(), unknown key: \" + gname);\n//                }\n//                ids._ids->at(inst).push_back(it1->second);\n//            }\n//            inst++;\n//        }\n//    }\n//    return ids;\n//}\n\n\nindices PowerNet::gens_per_node_time() const{\n    auto ids = Gt;\n    ids._name = \"gens_per_node_time\";\n    ids._ids = make_shared<vector<vector<size_t>>>();\n    ids._ids->resize(Nt.size());\n    string key, time_stamp;\n    size_t inst = 0;\n    for (auto key: *Nt._keys) {\n        auto pos = key.find_last_of(\",\");\n        auto name = key.substr(pos+1);\n        key = key.substr(0,pos);\n        pos = key.find_last_of(\",\");\n        auto ph = key.substr(pos+1);\n        key = key.substr(0,pos);\n        auto n = get_node(name);\n        if (!n->_active) {\n            continue;\n        }\n        for (auto g:((Bus*)n)->_gen) {\n            if (!g->_active || !g->has_phase(ph)) {\n                continue;\n            }\n            auto gname = key+\",\"+ph+\",\"+g->_name;\n            auto it1 = ids._keys_map->find(gname);\n            if (it1 == ids._keys_map->end()){\n                throw invalid_argument(\"In function gens_per_node_time(), unknown key: \" + gname);\n            }\n            ids._ids->at(inst).push_back(it1->second);\n        }\n        inst++;\n    }\n    return ids;\n}\n\nindices PowerNet::gens_per_node() const{\n    indices ids(\"gens_per_node\");\n    ids = indices(gens);\n    ids._ids = make_shared<vector<vector<size_t>>>();\n    ids._ids->resize(get_nb_active_nodes());\n    string key;\n    size_t inst = 0;\n    for (auto n: nodes) {\n        if (n->_active) {\n            for(auto g: ((Bus*)n)->_gen){\n                if (!g->_active) {\n                    continue;\n                }\n                key = g->_name;\n                auto it1 = ids._keys_map->find(key);\n                if (it1 == ids._keys_map->end()){\n                    throw invalid_argument(\"In function gen_ids(), unknown key.\");\n                }\n                ids._ids->at(inst).push_back(it1->second);\n            }\n            inst++;\n        }\n    }\n    return ids;\n}\n\nindices PowerNet::out_arcs_per_node() const{\n    auto ids = indices(arcs);\n    ids._name = \"out_arcs_per_node\";\n    ids._ids = make_shared<vector<vector<size_t>>>();\n    ids._ids->resize(get_nb_active_nodes());\n    string key;\n    size_t inst = 0;\n    for (auto n: nodes) {\n        if (n->_active) {\n            for (auto a:n->get_out()) {\n                if (!a->_active) {\n                    continue;\n                }\n                key = a->_name;\n                auto it1 = ids._keys_map->find(key);\n                if (it1 == ids._keys_map->end()){\n                    throw invalid_argument(\"In function out_arcs_per_node(), unknown key.\");\n                }\n                ids._ids->at(inst).push_back(it1->second);\n            }\n            inst++;\n        }\n    }\n    return ids;\n}\n\nindices PowerNet::in_arcs_per_node() const{\n    auto ids = indices(arcs);\n    ids._name = \"in_arcs_per_node\";\n    ids._ids = make_shared<vector<vector<size_t>>>();\n    ids._ids->resize(get_nb_active_nodes());\n    string key;\n    size_t inst = 0;\n    for (auto n: nodes) {\n        if (n->_active) {\n            for (auto a:n->get_in()) {\n                if (!a->_active) {\n                    continue;\n                }\n                key = a->_name;\n                auto it1 = ids._keys_map->find(key);\n                if (it1 == ids._keys_map->end()){\n                    throw invalid_argument(\"In function in_arcs_per_node(), unknown key.\");\n                }\n                ids._ids->at(inst).push_back(it1->second);\n            }\n            inst++;\n        }\n    }\n    return ids;\n}\n\nunsigned PowerNet::get_nb_active_gens() const {\n    unsigned nb=0;\n    for (auto g: gens) {\n        if (g->_active) {\n            nb++;\n        }\n    }\n    return nb;\n}\n\nunsigned PowerNet::get_nb_active_bus_pairs() const {\n    unsigned nb=0;\n    for (auto bp: _bus_pairs._keys) {\n        if (bp->_active) {\n            nb++;\n        }\n    }\n    return nb;\n}\n\n\nunsigned PowerNet::get_nb_active_arcs() const {\n    unsigned nb=0;\n    for (auto a: arcs) {\n        if (a->_active) {\n            nb++;\n        }\n    }\n    return nb;\n}\n\nunsigned PowerNet::get_nb_active_nodes() const {\n    unsigned nb=0;\n    for (auto n: nodes) {\n        if (n->_active) {\n            nb++;\n        }\n        else {\n            DebugOff(\"Inactive Node\" << n->_name << endl);\n        }\n    }\n    return nb;\n}\n\n\nint PowerNet::readODO(const string& fname){\n    size_t index = 0;\n    string name;\n    xlnt::workbook wb;\n    double wall0 = get_wall_time();\n    clog << \"Opening excel file...\\n\";\n    wb.load(fname);\n    double wall1 = get_wall_time();\n    clog << \"Done.\\n\";\n    clog << \"Wall clock computing time =  \" << wall1 - wall0 << \"\\n\";\n    xlnt::worksheet ws;\n    bool RunSettings = true;\n    try{\n        ws = wb.sheet_by_title(\"RunSettings\");\n    }\n    catch(xlnt::key_not_found err) {\n        RunSettings = false;\n        cerr << \"Cannot find sheet RunSettings, ignoring RunSettings options\" << endl;\n    }\n    if (RunSettings) {\n        auto row_it = ws.rows().begin();\n        auto row = *row_it++;\n        _max_time = row[1].value<int>();\n        row = *row_it++;\n        _max_it = row[1].value<int>();\n        row = *row_it++;\n        _tol = row[1].value<double>();\n        row = *row_it++;\n        _nb_years = row[1].value<int>();\n        row = *row_it++;\n        _inflation_rate = row[1].value<double>();\n        row = *row_it++;\n        _demand_growth = row[1].value<double>();\n        row = *row_it++;\n        _networked = (row[1].to_string()==\"Yes\");\n        row = *row_it++;\n        _nb_fuel_hours = row[1].value<int>();\n    }\n    \n    ws = wb.sheet_by_title(\"CableParams\");\n    clog << \"Processing CableParams for branch expansion costs and line properties\" << std::endl;\n    auto row_it = ws.rows().begin();\n    row_it++;//SKIP FRIST ROW\n    vector<string> r; /* Matrix of resistance */\n    vector<string> x; /* Matrix of reactance */\n    vector<double> cost; /* Vector of expansion costs */\n    vector<double> Smax; /* Vector of thermal limits */\n    vector<string> phase_list;\n    while (row_it!=ws.rows().end()) {\n        auto row = *row_it++;\n        cost.push_back(row[2].value<double>());\n        r.push_back(row[3].to_string());\n        x.push_back(row[4].to_string());\n        Smax.push_back(row[5].value<double>()/bMVA);\n        phase_list.push_back(row[6].to_string());\n    }\n    \n    bool found_branch_expansion = true;\n    try{\n        ws = wb.sheet_by_title(\"BranchInvest\");\n    }\n    catch(xlnt::key_not_found err) {\n        found_branch_expansion = false;\n        cerr << \"Cannot find sheet BranchInvest, ignoring branch expansion options\" << endl;\n    }\n    if (found_branch_expansion) {\n        index = this->arcs.size();\n        clog << \"Processing BranchInvest\" << std::endl;\n        auto row_it = ws.rows().begin();\n        row_it++;//SKIP FRIST ROW\n        for (size_t i = 0; i<nb_nodes-1; i++) {\n            auto row = *row_it++;\n            for (size_t j = i+1; j<nb_nodes; j++) {\n                if (row[j].has_value()) {\n                    string list = row[j].to_string();\n                    size_t sz = 0;\n                    int b_id = 0;\n                    b_id = stoi(list, &sz);\n                    if (list.size()==1 && b_id==0) {\n                        continue;\n                    }\n                    while (true) {\n                        auto src = to_string(i+1);\n                        auto dest = to_string(j);\n                        DebugOn(\"Expansion possible on arc (\" << i+1 << \",\" << j << \") with type \" << b_id << endl);\n                        auto arc = new Line(\"Potential_Type\"+to_string(b_id) + \",\" + src + \",\" + dest); // Name of lines\n                        arc->_expansion = true;\n                        arc->_active = true;\n                        arc->b_type = b_id;\n                        arc->smax = Smax[b_id-1];\n                        arc->cost = cost[b_id-1];\n                        arc->set_phases(phase_list[b_id-1]);\n                        arc->_id = index++;\n                        arc->_src = get_node(src);\n                        arc->_dest= get_node(dest);\n                        arc->connect();\n                        arc->_tie_line = arc->_src->_net_id!=arc->_dest->_net_id;\n                        add_arc(arc);\n                        expansion_capcost.add_val(arc->_name, arc->cost);\n                        _potential_expansion.push_back(arc);\n                        auto r_str = r[b_id-1];\n                        auto x_str = x[b_id-1];\n                        auto ymat = arma::cx_mat(3,3);\n                        for (auto i = 0; i<3; i++) {\n                            if(arc->_phases.count(i+1)!=0 && arc->_src->_phases.count(i+1)!=0 && arc->_dest->_phases.count(i+1)!=0){\n                                auto ph_key = \"ph\"+to_string(i+1)+\",\"+arc->_name;\n                                E_ph.insert(ph_key);\n                                pot_E_ph.insert(ph_key);\n                                this->S_max.add_val(ph_key, arc->smax);\n                                if(i==0){\n                                    E_ph1.insert(ph_key);\n                                }\n                                else if(i==1){\n                                    E_ph2.insert(ph_key);\n                                }\n                                else {\n                                    E_ph3.insert(ph_key);\n                                }\n                                for (auto j= 0; j<3; j++) {\n                                    if(arc->_phases.count(i+1)!=0 && arc->_src->_phases.count(i+1)!=0 && arc->_dest->_phases.count(i+1)!=0){\n                                        auto key = \"ph\"+to_string(i+1)+\",ph\"+to_string(j+1)+\",\"+arc->_name;\n                                        r_str = r_str.substr(0,r_str.find_first_of(\",\"));\n                                        x_str = x_str.substr(0,x_str.find_first_of(\",\"));\n                                        br_r_.add_val(key, stod(r_str));\n                                        br_x_.add_val(key, stod(x_str));\n                                        ymat(i,j) = complex<double>(br_r_.eval(),br_x_.eval());\n//                                            b.add_val(key, ymat_inv(i,j).imag());\n                                    }\n                                }\n                                b_fr_.add_val(ph_key, 0);\n                                b_to_.add_val(ph_key, 0);\n                                g_fr_.add_val(ph_key, 0);\n                                g_to_.add_val(ph_key, 0);\n                                shift_.add_val(ph_key, 0);\n                                tap_.add_val(ph_key, 1);\n                            }\n                        }\n                        arma::cx_mat ymat_inv = arma::pinv(ymat);\n                        for (auto i= 0; i<3; i++) {\n                            if(arc->_phases.count(i+1)==0)\n                                continue;\n                            for (auto j= 0; j<3; j++) {\n                                if(arc->_phases.count(j+1)==0)\n                                    continue;\n                                auto key = \"ph\"+to_string(i+1)+\",ph\"+to_string(j+1)+\",\"+arc->_name;\n                                cross_phase.insert(key);\n                                g.add_val(key, ymat_inv(i,j).real());\n                                b.add_val(key, ymat_inv(i,j).imag());\n                            }\n                        }\n                        if (list.size()<= sz) {\n                            break;\n                        }\n                        list = list.substr(sz+1);\n                        b_id = stoi(list, &sz);\n                    }\n                }\n            }\n        }\n    }\n    \n    bool found_SwitchParams = true;\n    try{\n        ws = wb.sheet_by_title(\"SwitchParams\");\n    }\n    catch(xlnt::key_not_found err) {\n        found_SwitchParams = false;\n        cerr << \"Cannot find sheet SwitchParams, using default switch gear parameters (Capital cost: capital cost $80,000, remote controlled)   \" << endl;\n    }\n    if(found_SwitchParams){\n        size_t idx = 0;\n        clog << \"Processing SwitchParams (Switch gear capital cost and operation type)\" << std::endl;\n        row_it = ws.rows().begin();\n        while (row_it!=ws.rows().end()) {\n            auto row = *row_it++;\n            _all_switches.push_back(Switch(\"Switch\"+to_string(idx++),row[2].value<double>(), row[3].value<bool>(), row[4].value<bool>()));\n            _all_switches.back().print();\n        }\n    }\n    \n    bool found_switch_invest = true;\n    try{\n        ws = wb.sheet_by_title(\"SwitchInvest\");\n    }\n    catch(xlnt::key_not_found err) {\n        found_switch_invest = false;\n        cerr << \"Cannot find sheet SwitchInvest, ignoring switch gear investment options\" << endl;\n    }\n    if (found_switch_invest) {\n        index = this->arcs.size();\n        clog << \"Processing SwitchInvest\" << std::endl;\n        auto row_it = ws.rows().begin();\n        row_it++;//SKIP FRIST ROW\n        for (size_t i = 0; i<nb_nodes-1; i++) {\n            auto row = *row_it++;\n            for (size_t j = i+1; j<nb_nodes; j++) {\n                if (row[j].has_value()) {\n                    string list = row[j].to_string();\n                    size_t sz = 0;\n                    int s_id = 0;\n                    s_id = stoi(list, &sz);\n                    if (list.size()==1 && s_id==0) {\n                        continue;\n                    }\n                    while (true) {\n                        auto src = to_string(i+1);\n                        auto dest = to_string(j);\n                        DebugOn(\"Switch possible on branch (\" << i+1 << \",\" << j << \") with type \" << s_id << endl);\n                        auto a = (Line*)get_arc(src,dest);\n                        a->_switches.push_back(_all_switches[s_id]);\n                        _potential_switches.push_back(&_all_switches[s_id]);\n                        if (list.size()<= sz) {\n                            break;\n                        }\n                        list = list.substr(sz+1);\n                        s_id = stoi(list, &sz);\n                    }\n                }\n            }\n        }\n    }\n    \n    ws = wb.sheet_by_title(\"CableLen\");\n    clog << \"Processing CableLen\" << std::endl;\n    row_it = ws.rows().begin();\n    row_it++;//SKIP FRIST ROW\n    index = 0;\n    double len = 0;\n    for (size_t i = 0; i<nb_nodes-1; i++) {\n        auto row = *row_it++;\n        for (size_t j = i+1; j<nb_nodes; j++) {\n            if (row[j].has_value() && row[j].value<unsigned>()>0) {\n                auto src = to_string(i+1);\n                auto dest = to_string(j);\n                len = row[j].value<unsigned>();\n                auto a = get_arc(src, dest);\n                if(a){\n                    DebugOn(\"(\" << i+1 << \",\" << j << \") has len \" << len << endl);\n                    a->_len = len;\n                }\n            }\n        }\n    }\n    \n    \n    unsigned exist = 0, min_bat = 0, max_bat = 0, min_d = 0, max_d = 0, age = 0;\n    double min_PV = 0, max_PV = 0;\n    double min_Wind = 0, max_Wind = 0;\n    \n    bool found_PvWindInvest = true;\n    try{\n        ws = wb.sheet_by_title(\"PvWindInvest\");\n    }\n    catch(xlnt::key_not_found err) {\n        found_PvWindInvest = false;\n        cerr << \"Cannot find sheet PvWindInvest, ignoring investments in renewable generation\" << endl;\n    }\n    if(found_PvWindInvest){\n        clog << \"Processing PvWindInvest (Pv and Wind investment options at each node)\" << std::endl;\n        row_it = ws.rows().begin();\n        row_it++;\n        row_it++;//SKIP SECOND ROW\n        vector<string> pv_phase_list;\n        auto row = *row_it;\n        for (auto i = 0; i<nodes.size(); i++) {\n            auto bname = row[0].to_string();\n            bname = bname.substr(4);//remove the node string\n            auto bus = (Bus*)get_node(bname);\n            min_PV = row[1].value<double>();\n            max_PV = row[2].value<double>();\n            exist = row[3].value<double>();\n            bus->_min_PV_cap = min_PV;\n            bus->_max_PV_cap = max_PV;\n            bus->_existing_PV_cap = exist;\n            if (max_PV>0 || exist >0) {\n                pv_phase_list.push_back(row[5].to_string());\n                if(exist>0){\n                    for (int ph = 1; ph<=3; ph++) {\n                        if(bus->_phases.count(ph)==0 || pv_phase_list.back().find(to_string(ph))==string::npos){\n                            continue;\n                        }\n                        auto name = \"ph\"+to_string(ph)+\",\"+\"exist,\"+bus->_name;\n                        bus->_pv.push_back(new PV(name,min_PV,max_PV));\n                        bus->_pv.back()->set_phases(to_string(ph));\n                        bus->_exist_pv.push_back(bus->_pv.back());\n                        DebugOn(\"existing PV cap at bus\" << bus->_name << \" = \" << exist << endl);\n                        DebugOn(\"On phases: \" << to_string(ph) << endl);\n                        exist_PV_ph.insert(name);\n                        PV_ph.insert(name);\n                    }\n                }\n                if(max_PV-exist>0){\n                    for (int ph = 1; ph<=3; ph++) {\n                        if(bus->_phases.count(ph)==0 || pv_phase_list.back().find(to_string(ph))==string::npos){\n                            continue;\n                        }\n                        auto name = \"ph\"+to_string(ph)+\",\"+\"potential,\"+bus->_name;\n                        bus->_pv.push_back(new PV(name,min_PV,max_PV));\n                        bus->_pv.back()->set_phases(to_string(ph));\n                        bus->_pot_pv.push_back(bus->_pv.back());\n                        DebugOn(\"min PV cap at bus\" << bus->_name << \" = \" << min_PV << endl);\n                        DebugOn(\"max PV cap at bus\" << bus->_name << \" = \" << max_PV << endl);\n                        DebugOn(\"Potential PV cap at bus\" << bus->_name << \" = \" << max_PV-exist << endl);\n                        DebugOn(\"On phases: \" << to_string(ph) << endl);\n                        pot_PV_ph.insert(name);\n                        PV_ph.insert(name);\n                    }\n                }\n            }\n            row_it++;\n            row = *row_it;\n        }\n        assert(row[0].value<string>()==\"Wind\");\n        row_it++;\n        row_it++;//SKIP SECOND ROW\n        row = *row_it;\n        for (auto i = 0; i<nodes.size(); i++) {\n            auto bname = row[0].to_string();\n            bname = bname.substr(4);//remove the node string\n            auto bus = (Bus*)get_node(bname);\n            min_Wind = row[1].value<double>();\n            max_Wind = row[2].value<double>();\n            exist = row[3].value<double>();\n            bus->_min_Wind_cap = min_Wind;\n            bus->_max_Wind_cap = max_Wind;\n            bus->_existing_Wind_cap = exist;\n            if(exist>0){\n                auto name = \"exist,\"+bus->_name;\n                bus->_wind.push_back(new WindGen(name,min_Wind,max_Wind));\n                DebugOn(\"min Wind cap at bus\" << bus->_name << \" = \" << min_Wind << endl);\n                DebugOn(\"max Wind cap at bus\" << bus->_name << \" = \" << max_Wind << endl);\n                DebugOn(\"existing Wind cap at bus\" << bus->_name << \" = \" << exist << endl);\n                for (int ph = 1; ph<=3; ph++) {\n                    if(bus->_phases.count(ph)==0){\n                        continue;\n                    }\n                    exist_Wind_ph.insert(\"ph\"+to_string(ph)+\",\"+name);\n                    Wind_ph.insert(\"ph\"+to_string(ph)+\",\"+name);\n                }\n            }\n            if(max_Wind-exist>0){\n                auto name = \"potential,\"+bus->_name;\n                bus->_wind.push_back(new WindGen(name,min_Wind,max_Wind));\n                DebugOn(\"min Wind cap at bus\" << bus->_name << \" = \" << min_Wind << endl);\n                DebugOn(\"max Wind cap at bus\" << bus->_name << \" = \" << max_Wind << endl);\n                DebugOn(\"potential Wind cap at bus\" << bus->_name << \" = \" << max_Wind-exist << endl);\n                for (int ph = 1; ph<=3; ph++) {\n                    if(bus->_phases.count(ph)==0){\n                        continue;\n                    }\n                    pot_Wind_ph.insert(\"ph\"+to_string(ph)+\",\"+name);\n                    Wind_ph.insert(\"ph\"+to_string(ph)+\",\"+name);\n                }\n            }\n            row_it++;\n            row = *row_it;\n        }\n    }\n    \n    bool found_PvWindParams = true;\n    try{\n        ws = wb.sheet_by_title(\"PvWindParams\");\n    }\n    catch(xlnt::key_not_found err) {\n        found_PvWindParams = false;\n        cerr << \"Cannot find sheet PvWindParams, using default PV nd Wind parameters (Capital cost: 2500 $/kW, 80% efficiency)\" << endl;\n    }\n    if(found_PvWindParams){\n        clog << \"Processing PvWindParams (Pv and Wind capital cost and efficiency)\" << std::endl;\n        row_it = ws.rows().begin();\n        auto row = *row_it;\n        _pv_cap_cost = row[1].value<double>();\n        row_it++;\n        row = *row_it;\n        _pv_eff = row[1].value<double>();\n        DebugOn(\"PV cap cost = \" << _pv_cap_cost << endl);\n        DebugOn(\"PV eff = \" << _pv_eff << endl);\n        row_it++;\n        row = *row_it;\n        _wind_cap_cost = row[1].value<double>();\n        row_it++;\n        row = *row_it;\n        _wind_eff = row[1].value<double>();\n        DebugOn(\"Wind cap cost = \" << _wind_cap_cost << endl);\n        DebugOn(\"Wind eff = \" << _wind_eff << endl);\n    }\n    \n    \n    \n    ws = wb.sheet_by_title(\"DieselParams\");\n    clog << \"Processing DieselParams\" << std::endl;\n    row_it = ws.rows().begin();\n    row_it++;//SKIP FRIST ROW\n    \n    unsigned lifetime,type,idx = 1;\n    vector<string> gen_phase_list;\n    auto first_row = *(ws.rows().begin());\n    while (row_it!=ws.rows().end()) {\n        double max_p = 0, max_s =  0, capcost = 0, c0 = 0,c1 = 0,c2 = 0,eff = 0,max_ramp_up = 0,max_ramp_down = 0,min_up_time = 0,min_down_time = 0;\n        auto row = *row_it++;\n        max_s = row[2].value<double>()*1e-3/bMVA;\n        max_p = max_s;\n        capcost = row[3].value<double>();\n        c0 = row[4].value<double>();\n        c1 = row[5].value<double>()*bMVA;\n        c2 = row[6].value<double>()*pow(bMVA,2);\n        lifetime = row[11].value<int>();\n        for (auto i = 7; i<first_row.length(); i++) {\n            if (first_row[i].to_string().compare(\"Type\")==0) {\n                type = row[i].value<int>();\n            }\n            if (first_row[i].to_string().compare(\"efficiency\")==0) {\n                eff = row[i].value<double>();\n            }\n            if (first_row[i].to_string().compare(\"MaxRampUp\")==0) {\n                max_ramp_up = row[i].value<double>();\n            }\n            if (first_row[i].to_string().compare(\"MaxRampDown\")==0) {\n                max_ramp_down = row[i].value<double>();\n            }\n            if (first_row[i].to_string().compare(\"MinDownTime\")==0) {\n                min_down_time = row[i].value<int>();\n            }\n            if (first_row[i].to_string().compare(\"MinUpTime\")==0) {\n                min_up_time = row[i].value<int>();\n            }\n            if (first_row[i].to_string().compare(\"phases (1,2,3)\")==0) {\n                gen_phase_list.push_back(row[i].to_string());\n            }\n        }\n        _all_diesel_gens.push_back(DieselGen(\"DG\"+to_string(idx++), max_p, max_s, lifetime, capcost, c0, c1, c2, type, eff, max_ramp_down, max_ramp_up,min_down_time,min_up_time));\n        _all_diesel_gens.back().set_phases(gen_phase_list.back());\n        _all_diesel_gens.back().print();//check phases\n    }\n    \n    /* Diesel Investment Options */\n    bool found_diesel_invest = true;\n    try{\n        ws = wb.sheet_by_title(\"DieselInvest\");\n    }\n    catch(xlnt::key_not_found err) {\n        found_diesel_invest = false;\n        cerr << \"Cannot find sheet DieselInvest, ignoring diesel generation investment\" << endl;\n    }\n    if(found_diesel_invest){\n        clog << \"Processing DieselInvest (Diesel investment options at each node)\" << std::endl;\n        row_it = ws.rows().begin();\n        row_it++;//SKIP FRIST ROW\n        for (auto i = 0; i<nodes.size(); i++) {\n            \n            auto row = *row_it++;\n            auto bname = row[0].to_string();\n            bname = bname.substr(4);//remove the node string\n            auto bus = (Bus*)get_node(bname);\n            unsigned index = 0;\n            while (row[0].to_string().compare((*row_it)[0].to_string())==0) {\n                max_d = row[6].value<int>();\n                exist = row[7].value<int>();\n                if (max_d>0 || exist>0) {\n                    min_d = row[5].value<int>();\n                    assert(max_d>=min_d);\n                    age = row[8].value<int>();\n                    bus->_diesel_data[index] = DieselData(min_d,max_d,exist,age);\n                    auto copy = _all_diesel_gens[index];\n                    for (auto i = 0; i<exist; i++) {\n                            auto name = copy._name + \"_Exist,\" + bus->_name + \",\" + \"slot\"+to_string(i);\n                            auto gen = new Gen(bus, name, 0, copy._max_p, -copy._max_s, copy._max_s);\n                            gen->set_costs(copy._c0, copy._c1, copy._c2);\n                            gen->_phases = copy._phases;\n                            _existing_diesel_gens.push_back(gen);\n                            gens.push_back(gen);\n                            bus->_gen.push_back(gen);\n                            this->c0.add_val(name,copy._c0);\n                            this->c1.add_val(name,copy._c1);\n                            this->c2.add_val(name,copy._c2);\n                            this->pg_min.add_val(name,0);\n                            this->pg_max.add_val(name,copy._max_p);\n                            this->qg_min.add_val(name,-copy._max_s);\n                            this->qg_max.add_val(name,copy._max_s);\n                            this->min_dt.add_val(name,copy._min_down_time);\n                            this->min_ut.add_val(name,copy._min_up_time);\n                            this->ramp_up.add_val(name,copy._max_ramp_up);\n                            this->ramp_down.add_val(name,copy._max_ramp_down);\n                            this->gen_eff.add_val(name,copy._eff);\n                        for (int ph = 1; ph<=3; ph++) {\n                            if(bus->_phases.count(ph)==0 || _all_diesel_gens[index]._phases.count(ph)==0){\n                                continue;\n                            }\n                            G_ph.insert(\"ph\"+to_string(ph)+\",\"+name);\n                            exist_G_ph.insert(\"ph\"+to_string(ph)+\",\"+name);\n                        }\n                    }\n                    assert(max_d>=exist);\n                    for (auto i = exist; i<max_d - exist; i++) {\n                        auto copy = _all_diesel_gens[index];\n                        auto name = copy._name + \"_Potential,\" + bus->_name + \",\" + \"slot\"+to_string(i);\n                        auto gen = new Gen(bus, name, 0, copy._max_p, -copy._max_s, copy._max_s);\n                        gen->set_costs(copy._c0, copy._c1, copy._c2);\n                        _potential_diesel_gens.push_back(gen);\n                        gen->_gen_type = index+1;\n                        gen->_phases = copy._phases;\n                        gens.push_back(gen);\n                        bus->_gen.push_back(gen);\n                        bus->_pot_gen.push_back(gen);\n                        this->min_diesel_invest.add_val(name, min_d);\n                        this->max_diesel_invest.add_val(name, max_d);\n                        this->c0.add_val(name,copy._c0);\n                        this->c1.add_val(name,copy._c1);\n                        this->c2.add_val(name,copy._c2);\n                        this->pg_min.add_val(name,0);\n                        this->pg_max.add_val(name,copy._max_p);\n                        this->qg_min.add_val(name,-copy._max_s);\n                        this->qg_max.add_val(name,copy._max_s);\n                        this->gen_capcost.add_val(name,copy._capcost);\n                        this->min_dt.add_val(name,copy._min_down_time);\n                        this->min_ut.add_val(name,copy._min_up_time);\n                        this->ramp_up.add_val(name,copy._max_ramp_up);\n                        this->ramp_down.add_val(name,copy._max_ramp_down);\n                        this->gen_eff.add_val(name,copy._eff);\n                        for (int ph = 1; ph<=3; ph++) {\n                            if(bus->_phases.count(ph)==0 || _all_diesel_gens[index]._phases.count(ph)==0){\n                                continue;\n                            }\n                            G_ph.insert(\"ph\"+to_string(ph)+\",\"+name);\n                            pot_G_ph.insert(\"ph\"+to_string(ph)+\",\"+name);\n                        }\n                    }\n                    \n                }\n                row = *row_it++;\n                index++;\n            }\n        }\n    }\n    \n    ws = wb.sheet_by_title(\"BattParams\");\n    clog << \"Processing BattParams (Battery Properties)\" << std::endl;\n    row_it = ws.rows().begin();\n    row_it++;//SKIP FRIST ROW\n    vector<double> x_eff;\n    vector<double> y_eff;\n    vector<string> batt_phase_list;\n    idx = 1;\n    double max_s = 0, capcost = 0;\n    while (row_it!=ws.rows().end()) {\n        auto row = *row_it++;\n        max_s = row[1].value<double>()/bMVA;\n        lifetime = row[2].value<int>();\n        capcost = row[3].value<double>();\n        auto nb_points = (row.length() - 5)/2;\n        x_eff.resize(nb_points);\n        y_eff.resize(nb_points);\n        for (int i = 0; i<nb_points; i++) {\n            x_eff[i] = row[2*i+4].value<double>();\n            y_eff[i] = row[2*i+5].value<double>();\n        }\n        _all_battery_inverters.push_back(BatteryInverter(\"BI\"+to_string(idx++),max_s, lifetime, capcost, x_eff, y_eff));\n        Debug(\"Battery \" << _all_battery_inverters.size() << \": \");\n        batt_phase_list.push_back(row[row.length()-1].to_string());\n        _all_battery_inverters.back().set_phases(batt_phase_list.back());\n        _all_battery_inverters.back().print();        \n    }\n    \n    \n    /* Battery Investment Options */\n    /* Battery Investment Options */\n    bool found_BattInvest = true;\n    try{\n        ws = wb.sheet_by_title(\"BattInvest\");\n    }\n    catch(xlnt::key_not_found err) {\n        found_BattInvest = false;\n        cerr << \"Cannot find sheet BattInvest, ignoring storage.\" << endl;\n    }\n    if(found_BattInvest){\n        DebugOn(\"Processing BattInvest\" << std::endl);\n        row_it = ws.rows().begin();\n        row_it++;//SKIP FRIST ROW\n        \n         for (auto i = 0; i<nodes.size(); i++) {\n            unsigned index = 0;\n            auto row = *row_it++;\n             auto bname = row[0].to_string();\n             bname = bname.substr(4);//remove the node string\n             auto bus = (Bus*)get_node(bname);\n\n            while (row[0].to_string().compare((*row_it)[0].to_string())==0) {\n                if (row[3].value<int>()!=0) {\n                    min_bat = row[2].value<int>();\n                    max_bat = row[3].value<int>();\n                    exist = row[4].value<int>();\n                    age = row[5].value<int>();\n                    \n                    bus->_battery_data[index] = BatteryData(min_bat,max_bat,exist,age);\n                    for (unsigned i = 0; i<exist; i++) {\n                        \n                        for (int ph = 1; ph<=3; ph++) {\n                            if(bus->_phases.count(ph)==0 || _all_battery_inverters[index]._phases.count(ph)==0){\n                                continue;\n                            }\n                            auto copy = new BatteryInverter(_all_battery_inverters[index]);\n                            copy->_name = \"ph\"+to_string(ph)+\",\"+copy->_name+\"_Exist,\" + bus->_name + \",\" + \"slot\"+to_string(i);\n                            _existing_battery_inverters.push_back(copy);\n                            _battery_inverters.push_back(copy);\n                            bus->_bat.push_back(copy);\n                            this->pb_min.add_val(copy->_name, -copy->_max_s/bMVA);\n                            this->pb_max.add_val(copy->_name, copy->_max_s/bMVA);\n                            this->qb_min.add_val(copy->_name, -copy->_max_s/bMVA);\n                            this->qb_max.add_val(copy->_name, copy->_max_s/bMVA);\n                            auto nb_eff_pieces = copy->_x_eff.size() - 1;\n                            if(_nb_eff_pieces<nb_eff_pieces){\n                                _nb_eff_pieces = nb_eff_pieces;\n                            }\n                            B_ph.insert(copy->_name);\n                            exist_B_ph.insert(copy->_name);\n                            for(auto p =1; p<= _nb_eff_pieces;p++){\n                                auto str = copy->_name+\",eff\"+to_string(p);\n                                if (p > nb_eff_pieces) {\n                                    eff_a.add_val(str, (copy->_y_eff[nb_eff_pieces] - copy->_y_eff[nb_eff_pieces-1])/(copy->_x_eff[nb_eff_pieces] - copy->_x_eff[nb_eff_pieces-1]));\n                                    eff_b.add_val(str, copy->_y_eff[nb_eff_pieces] - eff_a.eval()*copy->_x_eff[nb_eff_pieces]);\n                                }\n                                else{\n                                    eff_a.add_val(str, (copy->_y_eff[p] - copy->_y_eff[p-1])/(copy->_x_eff[p] - copy->_x_eff[p-1]));\n                                    eff_b.add_val(str, copy->_y_eff[p] - eff_a.eval()*copy->_x_eff[p]);\n                                }\n                            }\n                        }\n                        \n                    }\n                    assert(max_bat>=exist);\n                    for (unsigned i = exist; i<max_bat-exist; i++) {\n                        \n                        for (int ph = 1; ph<=3; ph++) {\n                            if(bus->_phases.count(ph)==0 || _all_battery_inverters[index]._phases.count(ph)==0){\n                                continue;\n                            }\n                            auto copy = new BatteryInverter(_all_battery_inverters[index]);\n                            copy->_name = \"ph\"+to_string(ph)+\",\"+copy->_name+\"_Potential,\" + bus->_name + \",\" + \"slot\"+to_string(i);\n                            copy->_bat_type = index+1;\n                            bus->_bat.push_back(copy);\n                            bus->_pot_bat.push_back(copy);\n                            _potential_battery_inverters.push_back(copy);\n                            _battery_inverters.push_back(copy);\n                            this->min_batt_invest.add_val(copy->_name, min_bat);\n                            this->max_batt_invest.add_val(copy->_name, max_bat);\n                            this->inverter_capcost.add_val(copy->_name,copy->_capcost);\n                            this->pb_min.add_val(copy->_name, -copy->_max_s/bMVA);\n                            this->pb_max.add_val(copy->_name, copy->_max_s/bMVA);\n                            this->qb_min.add_val(copy->_name, -copy->_max_s/bMVA);\n                            this->qb_max.add_val(copy->_name, copy->_max_s/bMVA);\n                            auto nb_eff_pieces = copy->_x_eff.size() - 1;\n                            if(_nb_eff_pieces<nb_eff_pieces){\n                                _nb_eff_pieces = nb_eff_pieces;\n                            }\n                            B_ph.insert(copy->_name);\n                            pot_B_ph.insert(copy->_name);\n                            for(auto p =1; p<= _nb_eff_pieces;p++){\n                                auto str = copy->_name+\",eff\"+to_string(p);\n                                if (p > nb_eff_pieces) {\n                                    eff_a.add_val(str, (copy->_y_eff[nb_eff_pieces] - copy->_y_eff[nb_eff_pieces-1])/(copy->_x_eff[nb_eff_pieces] - copy->_x_eff[nb_eff_pieces-1]));\n                                    eff_b.add_val(str, copy->_y_eff[nb_eff_pieces] - eff_a.eval()*copy->_x_eff[nb_eff_pieces]);\n                                }\n                                else{\n                                    eff_a.add_val(str, (copy->_y_eff[p] - copy->_y_eff[p-1])/(copy->_x_eff[p] - copy->_x_eff[p-1]));\n                                    eff_b.add_val(str, copy->_y_eff[p] - eff_a.eval()*copy->_x_eff[p]);\n                                }\n                            }\n                        }\n                        \n                    }\n                }\n                row = *row_it++;\n                index++;\n            }\n            bus->print();\n        }\n        for (auto i = 1; i<=_nb_eff_pieces; i++) {\n            _eff_pieces.insert(\"eff\"+to_string(i));\n        }\n    }\n    indices months = time(\"jan\",\"feb\",\"mar\",\"apr\",\"may\",\"jun\",\"jul\",\"aug\",\"sep\",\"oct\",\"nov\",\"dec\"); /**< Months */\n    bool has_monthseason = true;\n    try{\n        ws = wb.sheet_by_title(\"MonthSeason\");\n    }\n    catch(xlnt::key_not_found err){\n        has_monthseason = false;\n    }\n    unsigned week_days = 0,weekend_days = 0,peak_days = 0;\n    if (has_monthseason) {\n        clog << \"Processing MonthSeason\" << std::endl;\n        row_it = ws.rows().begin();\n        row_it++;//SKIP FRIST ROW\n        SeasonType season;\n        int month_id = 1;\n        while (row_it!=ws.rows().end()) {\n            auto row = *row_it++;\n            name = row[0].to_string();\n            if (row[1].value<int>()==1) {\n                season = winter_;\n                _months_season[month_id] = \"winter\";\n            }\n            else if (row[2].value<int>()==1) {\n                season = spring_;\n                _months_season[month_id] = \"spring\";\n            }\n            else if (row[3].value<int>()==1) {\n                season = summer_;\n                _months_season[month_id] = \"summer\";\n            }\n            else  {\n                season = autumn_;\n                _months_season[month_id] = \"autumn\";\n            }\n            _months_data.push_back(Month(name, season,week_days,weekend_days,peak_days));\n            month_id++;\n        }\n    }\n    else {\n        for (unsigned m = 0; m<12; m++) {\n            name = months._keys->at(m);\n            _months_data.push_back(Month(name, summer_,week_days,weekend_days,peak_days));\n        }\n    }\n    \n    bool has_nb_days = true;\n    try{\n        ws = wb.sheet_by_title(\"numberOfDays\");\n    }\n    catch(xlnt::key_not_found err) {\n        has_nb_days = false;\n    }\n    if(has_nb_days){\n        clog << \"Processing numberOfDays\" << std::endl;\n        row_it = ws.rows().begin();\n        row_it++;//SKIP FRIST ROW\n        for (unsigned m = 0; m<12; m++) {\n            auto row = *row_it++;\n            week_days = row[2].value<int>();\n            weekend_days = row[3].value<int>();\n            peak_days = row[1].value<int>();\n            _months_data[m]._nb_week_days = week_days;\n            _months_data[m]._nb_weekend_days = weekend_days;\n            _months_data[m]._nb_peak_days = peak_days;\n        }\n    }\n    else {\n        for (unsigned m = 0; m<12; m++) {\n            _months_data[m]._nb_week_days = 18;\n            _months_data[m]._nb_weekend_days = 9;\n            _months_data[m]._nb_peak_days = 3;\n        }\n    }\n    \n    bool found_SolarAverage = true;\n    try{\n        ws = wb.sheet_by_title(\"SolarAverage\");\n    }\n    catch(xlnt::key_not_found err) {\n        found_SolarAverage = false;\n        cerr << \"Cannot find sheet SolarAverage, setting solar generation to 0.\" << endl;\n    }\n    if(found_SolarAverage){\n        ws = wb.sheet_by_title(\"SolarAverage\");\n        clog << \"Processing SolarAverage (Hourly average radiance for each month)\" << std::endl;\n        row_it = ws.rows().begin();\n        row_it++;//SKIP FRIST ROW\n        for (unsigned m = 0; m<12; m++) {\n            auto row = *row_it++;\n            for (unsigned t=0; t<24; t++) {\n                _months_data[m]._solar_average[t] = row[t+1].value<double>();\n                \n            }\n        }\n    }\n    bool found_PV_Variance = true;\n    try{\n        ws = wb.sheet_by_title(\"SolarVariance\");\n    }\n    catch(xlnt::key_not_found err) {\n        found_PV_Variance = false;\n        cerr << \"Cannot find sheet SolarVariance, setting variance to 10% of average.\" << endl;\n    }\n    if(found_PV_Variance){\n        clog << \"Processing SolarVariance (Hourly Variance for each month)\" << std::endl;\n        row_it = ws.rows().begin();\n        row_it++;//SKIP FRIST ROW\n        for (unsigned m = 0; m<12; m++) {\n            auto row = *row_it++;\n            for (unsigned t=0; t<24; t++) {\n                _months_data[m]._solar_variance[t] = row[t+1].value<double>()/bMVA;\n            }\n        }\n    }\n    else{\n        for (unsigned m = 0; m<12; m++) {\n            for (unsigned t=0; t<24; t++) {\n                _months_data[m]._solar_variance[t] = _months_data[m]._solar_average[t]/10.;\n            }\n        }\n    }\n    bool found_WindAverage = true;\n    try{\n        ws = wb.sheet_by_title(\"WindAverage\");\n    }\n    catch(xlnt::key_not_found err) {\n        found_WindAverage = false;\n        cerr << \"Cannot find sheet WindAverage, setting wind generation to 0.\" << endl;\n    }\n    if(found_WindAverage){\n        clog << \"Processing WindAverage (Hourly Average for each month)\" << std::endl;\n        row_it = ws.rows().begin();\n        row_it++;//SKIP FRIST ROW\n        for (unsigned m = 0; m<12; m++) {\n            auto row = *row_it++;\n            for (unsigned t=0; t<24; t++) {\n                _months_data[m]._wind_average[t] = 0.0006*0.42*row[t+1].value<double>()/bMVA;\n            }\n        }\n    }\n    bool found_WindVariance = true;\n    try{\n        ws = wb.sheet_by_title(\"WindVariance\");\n    }\n    catch(xlnt::key_not_found err) {\n        found_WindVariance = false;\n        cerr << \"Cannot find sheet WindVariance, setting variance to 10% of average.\" << endl;\n    }\n    if(found_WindVariance){\n        clog << \"Processing WindVariance (Hourly Variance for each month)\" << std::endl;\n        row_it = ws.rows().begin();\n        row_it++;//SKIP FRIST ROW\n        for (unsigned m = 0; m<12; m++) {\n            auto row = *row_it++;\n            for (unsigned t=0; t<24; t++) {\n                _months_data[m]._wind_variance[t] = 0.0006*0.42*row[t+1].value<double>()/bMVA;\n            }\n        }\n    }\n    else{\n        for (unsigned m = 0; m<12; m++) {\n            for (unsigned t=0; t<24; t++) {\n                _months_data[m]._wind_variance[t] = 0.0006*0.42*_months_data[m]._wind_average[t]/10.;\n            }\n        }\n    }\n    bool found_LoadData = true;\n    try{\n        ws = wb.sheet_by_title(\"LoadTimeSeries\");\n    }\n    catch(xlnt::key_not_found err) {\n        found_LoadData = false;\n        cerr << \"Cannot find sheet LoadTimeSeries, setting all loads to 0.\" << endl;\n    }\n    if(found_LoadData){\n//    if(false){\n        clog << \"Processing LoadTimeSeries\" << std::endl;\n        size_t row_id = 1;\n        row_it = ws.rows().begin();\n        row_it++;//SKIP FRIST ROW\n        auto row = *row_it++;\n        auto tstamp = row[0].value<xlnt::datetime>();\n        int day = tstamp.day;\n        DebugOn(\"day = \" << to_string(day) << endl);\n        int month = tstamp.month;\n        DebugOn(\"month = \" << to_string(month) << endl);\n        int year = tstamp.year;\n        DebugOn(\"year = \" << to_string(year) << endl);\n        int hour = std::min(23,(int)round(tstamp.hour + tstamp.minute*1./60.));\n        assert(hour<24 && hour >=0);\n        DebugOn(\"hour = \" << to_string(hour) << endl);\n//        _demand_start_date->tm_year = year - 1900;\n//        _demand_start_date->tm_mon = month-1;\n//        _demand_start_date->tm_mday = day;\n//        _demand_start_date->tm_hour = hour;\n//        mktime ( _demand_start_date );\n//        DebugOn(\"Historical load data start time is: \" << asctime(_demand_start_date));\n        auto col_start = ws.columns().begin();\n        auto col_end = ws.columns().end();\n        auto col_it = col_start;\n        col_it++;\n        Cpx load;\n        while (col_it!=col_end) {\n            auto col = *col_it++;\n            auto load_name = col[0].value<string>();\n            auto phase = stoi(load_name.substr(load_name.size()-1));\n            load_name = load_name.substr(0,load_name.size()-8);\n            load_name = \"ph\"+to_string(phase)+\",\"+load_name;\n            auto load_val = col[1].value<string>();\n            istringstream is(load_val);\n            is >> load;\n            auto bus = (Bus*)_load_map.at(load_name);\n            auto l = bus->_loads.at(load_name);\n            l->_phases.insert(phase);\n            l->_val[{year,month,day,hour}] = load;\n        }\n        auto rows_end = ws.rows().end();\n        while (row_it!=rows_end) {\n            row = *row_it++;\n            row_id++;\n            tstamp = row[0].value<xlnt::datetime>();\n            day = tstamp.day;\n            DebugOff(\"day = \" << to_string(day) << endl);\n            month = tstamp.month;\n            DebugOff(\"month = \" << to_string(month) << endl);\n            year = tstamp.year;\n            DebugOff(\"year = \" << to_string(year) << endl);\n            hour = std::min(23,(int)round(tstamp.hour + tstamp.minute*1./60.));\n            DebugOff(\"hour = \" << to_string(hour) << endl);\n            assert(hour<24 && hour >=0);\n//            auto _date = tm();\n//            _date.tm_year = tstamp.year - 1900;\n//            _date.tm_mon = tstamp.month-1;\n//            _date.tm_mday = tstamp.day;\n//            _date.tm_hour = tstamp.hour;\n//            mktime ( &_date );\n            \n//            DebugOff(\"Time stamp: \" << asctime(&_date) << endl);\n            col_it = col_start;\n            col_it++;\n            while (col_it!=col_end) {\n                auto col = *col_it++;\n                auto load_name = col[0].value<string>();\n                auto phase = stoi(load_name.substr(load_name.size()-1));\n                load_name = load_name.substr(0,load_name.size()-8);\n                load_name = \"ph\"+to_string(phase)+\",\"+load_name;\n                DebugOff(\"load name = \" << load_name << endl);\n                auto load_val = col[row_id].value<string>();\n                istringstream is(load_val);\n                is >> load;\n                auto bus = (Bus*)_load_map.at(load_name);\n                auto l = bus->_loads.at(load_name);\n                l->_phases.insert(phase);\n                l->_val[{year,month,day,hour}] = load;\n            }\n\n        }\n        compute_loads();\n    }\n    \n    bool found_ResiliencyData = true;\n    try{\n        ws = wb.sheet_by_title(\"ResiliencyScenarios\");\n    }\n    catch(xlnt::key_not_found err) {\n        found_ResiliencyData = false;\n        cerr << \"Cannot find sheet ResiliencyScenarios, no resiliency scenarios considered.\" << endl;\n    }\n    if(found_ResiliencyData){\n        clog << \"Processing ResiliencyScenarios\" << std::endl;\n        size_t row_id = 0;\n        row_it = ws.rows().begin();\n        row_it++;//SKIP FRIST ROW\n        auto rows_end = ws.rows().end();\n        while (row_it!=rows_end) {\n            auto row = *row_it++;\n            auto name = row[0].to_string();\n            auto tstamp = row[1].value<xlnt::datetime>();\n            auto day = tstamp.day;\n            DebugOff(\"day = \" << to_string(day) << endl);\n            auto month = tstamp.month;\n            DebugOff(\"month = \" << to_string(month) << endl);\n            auto year = tstamp.year;\n            DebugOff(\"year = \" << to_string(year) << endl);\n            auto hour = std::min(23,(int)round(tstamp.hour + tstamp.minute*1./60.));\n            DebugOff(\"hour = \" << to_string(hour) << endl);\n            assert(hour<24 && hour >=0);\n            row_id++;\n            auto nb_hours = row[2].value<int>();\n            DebugOff(\"nb hours in resiliency scenario = \" << to_string(nb_hours) << endl);\n            auto scen = make_shared<Scenario>(name,year,month,day,hour,nb_hours);\n            _res_scenarios[name] = scen;\n            auto col_start = row.begin();\n            auto col_end = row.end();\n            auto col_it = col_start;\n            col_it++;col_it++;col_it++;\n            while (col_it!=col_end) {\n                auto col = *col_it++;\n                auto conting_name = col.to_string();\n                auto conting_type = conting_name.substr(0,conting_name.find_first_of(\"_\"));\n                if(conting_type==\"branch\"){\n                    auto br = conting_name.substr(conting_name.find_first_of(\"_\")+1);\n                    auto src = br.substr(0,br.find_first_of(\"_\"));\n                    auto dest = br.substr(br.find_first_of(\"_\")+1);\n                    auto arc = get_arc(src, dest);\n                    scen->_out_arcs[arc->_name]=arc;\n                }\n                else if(conting_type==\"gen\"){\n                    int gen_id = stoi(conting_name.substr(conting_name.find_first_of(\"_\")+1));\n                    auto gen = gens.at(gen_id);\n                    scen->_out_gens[gen->_name] = gen;\n                }\n                else {\n                    throw invalid_argument(\"unsupported contingency type, use branch_srcId_desId or gen_busId\");\n                }\n            }\n        }\n    }\n\n    \n    \n    \n    \n    string key;\n    //Building PV and Wind generation parameters\n    for (unsigned i = 0; i<nb_nodes; i++) {\n        auto b = (Bus*)nodes[i];\n        auto potential_PV = b->_max_PV_cap*1e-3;\n        auto potential_wind = b->_max_Wind_cap*1e-3;\n        if (potential_PV - b->_existing_PV_cap>0) {\n            for(auto new_pv: b->_pot_pv){\n                auto name = new_pv->_name;\n                this->pv_max.add_val(name, potential_PV/bMVA);\n                this->pv_min.add_val(name, 0);\n                this->pv_capcost.add_val(name,_pv_cap_cost);\n                this->pv_varcost.add_val(name,_pv_cap_cost/bMVA);\n                for (unsigned y = 0; y<_nb_years; y++) {\n                    for (unsigned m = 0; m<this->months.size(); m++) {\n                        for (unsigned t=0; t<_nb_hours; t++) {\n                                auto key = \"year\" + to_string(y+1) + \",\" + this->months._keys->at(m) + \",week,\" + to_string(t+1) + \",\" + name;\n                                pv_out.add_val(key, _months_data[m]._solar_average[t]/bMVA);\n                                key = \"year\" + to_string(y+1) + \",\" + this->months._keys->at(m) + \",peak,\" + to_string(t+1) + \",\" + name;\n                                pv_out.add_val(key, _months_data[m]._solar_average[t]/bMVA + _months_data[m]._solar_variance[t]/bMVA);\n                                key = \"year\" + to_string(y+1) + \",\" + this->months._keys->at(m) + \",weekend,\" + to_string(t+1) + \",\" + name;\n                                pv_out.add_val(key, _months_data[m]._solar_average[t]/bMVA);\n                        }\n                    }\n                }\n            }\n        }\n        if (b->_existing_PV_cap > 0) {\n            for(auto new_pv: b->_exist_pv){\n                auto name = new_pv->_name;\n                this->pv_max.add_val(name, b->_existing_PV_cap*1e-3/bMVA);\n                this->pv_min.add_val(name, 0);\n                for (unsigned y = 0; y<_nb_years; y++) {\n                    for (unsigned m = 0; m<this->months.size(); m++) {\n                        for (unsigned t=0; t<_nb_hours; t++) {\n                            auto key = \"year\" + to_string(y+1) + \",\" + this->months._keys->at(m) + \",week,\" + to_string(t+1) + \",\" + name;\n                            pv_out.add_val(key, _months_data[m]._solar_average[t]/bMVA);\n                            key = \"year\" + to_string(y+1) + \",\" + this->months._keys->at(m) + \",peak,\" + to_string(t+1) + \",\" + name;\n                            pv_out.add_val(key, _months_data[m]._solar_average[t]/bMVA + _months_data[m]._solar_variance[t]/bMVA);\n                            key = \"year\" + to_string(y+1) + \",\" + this->months._keys->at(m) + \",weekend,\" + to_string(t+1) + \",\" + name;\n                            pv_out.add_val(key, _months_data[m]._solar_average[t]/bMVA);\n                        }\n                    }\n                }\n            }\n        }\n        if (potential_wind - b->_existing_Wind_cap>0) {\n            auto new_wind = b->_wind.back();\n            auto name = new_wind->_name;\n            for (unsigned y = 0; y<_nb_years; y++) {\n                for (unsigned m = 0; m<this->months.size(); m++) {\n                    for (unsigned t=0; t<_nb_hours; t++) {\n                        for (auto &ph: {1,2,3}){\n                            auto key = \"year\" + to_string(y+1) + \",\" + this->months._keys->at(m) + \",week,\" + to_string(t+1) + \",ph\" + to_string(ph) + \",\" + name;\n                            pw_max.add_val(key, _months_data[m]._wind_average[t]);\n                            key = \"year\" + to_string(y+1) + \",\" + this->months._keys->at(m) + \",peak,\" + to_string(t+1) + \",ph\" + to_string(ph) + \",\" + name;\n                            pw_max.add_val(key, _months_data[m]._wind_average[t] +  _months_data[m]._wind_variance[t]);\n                            key = \"year\" + to_string(y+1) + \",\" + this->months._keys->at(m) + \",weekend,\" + to_string(t+1) + \",ph\" + to_string(ph) + \",\" + name;\n                            pw_max.add_val(key, _months_data[m]._wind_average[t] +  _months_data[m]._wind_variance[t]);\n                        }\n                    }\n                }\n            }\n        }\n        if (b->_existing_Wind_cap>0) {\n            auto new_wind = b->_wind.front();\n            auto name = new_wind->_name;\n            for (unsigned y = 0; y<_nb_years; y++) {\n                for (unsigned m = 0; m<this->months.size(); m++) {\n                    for (unsigned t=0; t<_nb_hours; t++) {\n                        for (auto &ph: {1,2,3}){\n                            auto key = \"year\" + to_string(y+1) + \",\" + this->months._keys->at(m) + \",week,\" + to_string(t+1) + \",ph\" + to_string(ph) + \",\" + name;\n                            pw_max.add_val(key, _months_data[m]._wind_average[t]);\n                            key = \"year\" + to_string(y+1) + \",\" + this->months._keys->at(m) + \",peak,\" + to_string(t+1) + \",ph\" + to_string(ph) + \",\" + name;\n                            pw_max.add_val(key, _months_data[m]._wind_average[t] +  _months_data[m]._wind_variance[t]);\n                            key = \"year\" + to_string(y+1) + \",\" + this->months._keys->at(m) + \",weekend,\" + to_string(t+1) + \",ph\" + to_string(ph) + \",\" + name;\n                            pw_max.add_val(key, _months_data[m]._wind_average[t] +  _months_data[m]._wind_variance[t]);\n                        }\n                    }\n                }\n            }\n        }\n    }\n    //    clog << \"Loads:\\n\";\n    //    pl.print(true);\n    \n    clog << \"Reading excel file complete\" << std::endl;\n    cout << \"Number of hours of fuel availibility = \" << _nb_fuel_hours << endl;\n    return 0;\n}\n\n\nPowerNet* PowerNet::clone(int net_id) const{\n    PowerNet* copy_net = new PowerNet();\n    Bus* node = NULL;\n    \n    for (int i=0; i<nodes.size(); i++) {\n        node = (Bus*)this->nodes[i];\n        if(node->_net_id==net_id){\n            copy_net->add_node(new Bus(*node));\n        }\n    }\n    \n    Line* arc = NULL;\n    for (int i=0; i < arcs.size(); i++) {\n        \n        arc = (Line*)arcs[i];\n        if(arc->_tie_line){\n            continue;\n        }\n        arc = new Line(*arc);\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\n\nvector<shared_ptr<PowerNet>> PowerNet::get_separate_microgrids() const{\n    \n    DebugOn(\"Number of Microgrids detected = \" << _microgrid_ids.size() << endl);\n    vector<shared_ptr<PowerNet>> res;\n    for (auto net_id: _microgrid_ids) {\n        res.push_back(shared_ptr<PowerNet>(this->clone(net_id)));\n    }\n    return res;\n}\n\nvoid PowerNet::readJSON(const string& fname){\n    ifstream ifs(fname);\n    if ( !ifs.is_open() )\n    {\n        throw invalid_argument(\"Cannot open file: \" + fname);\n    }\n    \n    IStreamWrapper isw { ifs };\n    Document d;\n    if (d.ParseStream( isw ).HasParseError()) {\n        throw invalid_argument(\"Parse error while reading JSON file: \" + fname);\n    }\n    DebugOn(\"Successfuly parsed JSON file: \" << fname << endl);\n    \n    bMVA = d[\"baseMVA\"].GetDouble();\n    bV = d[\"baseKV\"].GetDouble();\n    Value& buses = d[\"bus\"];\n    nb_nodes = buses.MemberCount();\n    DebugOn(\"nb_nodes = \" << nb_nodes << endl);\n    for (auto& v : buses.GetObject()) {\n        Value& list = v.value;\n        auto btype = list[\"bus_type\"].GetInt();\n        Debug(\"btype = \" << btype << endl);\n        auto index = list[\"index\"].GetInt();\n        auto net_id = list[\"microgrid_id\"].GetInt();\n        auto name = string(list[\"name\"].GetString());\n        auto status =  list[\"status\"].GetInt();\n        auto va =  list[\"va\"].GetArray();\n        auto vm =  list[\"vm\"].GetArray();\n        auto vmax =  list[\"vmax\"].GetArray();\n        auto vmin =  list[\"vmin\"].GetArray();\n        auto bus = new Bus(to_string(index));\n        bus->vbound.min = vmin[0].GetDouble();\n        bus->vbound.max = vmax[0].GetDouble();\n        bus->_net_id = net_id;\n        _microgrid_ids.insert(net_id);\n//        vm_s_.add_val(\"ph1,\"+bus->_name, 0.9999742573517363);\n//        vm_s_.add_val(\"ph2,\"+bus->_name, 1.0000038391442767);\n//        vm_s_.add_val(\"ph3,\"+bus->_name, 0.9999622416976457);\n        vm_s_.add_val(\"ph1,\"+bus->_name, vm[0].GetDouble());\n        vm_s_.add_val(\"ph2,\"+bus->_name, vm[1].GetDouble());\n        vm_s_.add_val(\"ph3,\"+bus->_name, vm[2].GetDouble());\n        //        theta_s_.add_val(bus->_name+\",ph0\", va[0].GetDouble());\n        //        theta_s_.add_val(bus->_name+\",ph1\", va[1].GetDouble());\n        //        theta_s_.add_val(bus->_name+\",ph2\", va[2].GetDouble());\n        //        theta_s_.add_val(bus->_name+\",ph0\", 0);\n        //        theta_s_.add_val(bus->_name+\",ph1\", -2.094395);\n        //        theta_s_.add_val(bus->_name+\",ph2\", 2.094395);\n//        theta_s_.add_val(\"ph1,\"+bus->_name, 30.*pi/180.);\n//        theta_s_.add_val(\"ph2,\"+bus->_name, -90.*pi/180.);\n//        theta_s_.add_val(\"ph3,\"+bus->_name, 150.*pi/180.);\n        for(auto i = 0;i<3;i++){\n            auto ph_key = \"ph\"+to_string(i+1)+\",\"+bus->_name;\n            if(vm[i].GetDouble()!=0){\n                bus->_phases.insert(i+1);\n                v_min.add_val(ph_key, vmin[i].GetDouble());\n                v_max.add_val(ph_key, vmax[i].GetDouble());\n                N_ph.insert(ph_key);\n                if(i==0){\n                    N_ph1.insert(ph_key);\n                }\n                else if(i==1){\n                    N_ph2.insert(ph_key);\n                }\n                else {\n                    N_ph3.insert(ph_key);\n                }\n                gs_.add_val(ph_key, 0);\n                bs_.add_val(ph_key, 0);\n                pl.add_val(ph_key, 0);\n                ql.add_val(ph_key, 0);\n            }\n            else {\n                DebugOn(\"excluding bus: \" << bus->_name << \" on phase \" << i+1 << endl);\n            }\n        }\n        \n        \n//        theta_.add_val(bus->_name+\",ph0\", va[0].GetDouble());\n//        theta_.add_val(bus->_name+\",ph1\", va[1].GetDouble());\n//        theta_.add_val(bus->_name+\",ph2\", va[2].GetDouble());\n        bus->_active = status;\n        bus->_id = nodes.size();\n        bus->_type = btype;\n        if (btype==3) {\n            ref_bus = bus->_name;\n//            theta_s_.add_val(\"ph1,\"+bus->_name, std::tan(0));\n//            theta_s_.add_val(\"ph2,\"+bus->_name, std::tan(-2*pi/3));\n//            theta_s_.add_val(\"ph3,\"+bus->_name, std::tan(2*pi/3));\n            theta_s_.add_val(\"ph1,\"+bus->_name, 0);\n            theta_s_.add_val(\"ph2,\"+bus->_name, (-2*pi/3));\n            theta_s_.add_val(\"ph3,\"+bus->_name, (2*pi/3));\n\n        }\n        assert(bus->_id<nb_nodes);\n        if (!nodeID.insert(pair<string,Node*>(bus->_name, bus)).second) {\n            throw invalid_argument(\"ERROR: adding the same bus twice!\");\n        }\n        nodes.push_back(bus);\n        if (!bus->_active) {\n            DebugOn(\"INACTIVE NODE: \" << name << endl);\n        }\n    }\n    Value& branches = d[\"branch\"];\n    nb_branches = branches.MemberCount();\n    DebugOn(\"nb_branches = \" << nb_branches << endl);\n    for (auto& a : branches.GetObject()) {\n        Value& list = a.value;\n        auto index = list[\"index\"].GetInt();\n        auto name = string(list[\"name\"].GetString());\n        auto status =  list[\"status\"].GetInt();\n        auto length = list[\"length\"].GetDouble();\n        auto angmin =  list[\"angmin\"].GetArray();\n        auto angmax =  list[\"angmax\"].GetArray();\n        auto b_fr = list[\"b_fr\"].GetArray();\n        auto f_bus = list[\"f_bus\"].GetInt();\n        auto t_bus = list[\"t_bus\"].GetInt();\n        auto b_to = list[\"b_to\"].GetArray();\n        auto g_fr = list[\"g_fr\"].GetArray();\n        auto g_to = list[\"g_to\"].GetArray();\n        auto br_r = list[\"br_r\"].GetArray();\n        auto br_x = list[\"br_x\"].GetArray();\n        auto rating = list[\"current_rating_a\"].GetArray();\n        auto shift = list[\"shift\"].GetArray();\n        auto tap = list[\"tap\"].GetArray();\n        auto tr = string(list[\"transformer\"].GetString());\n        \n        auto arc = new Line(to_string(index) + \",\" + to_string(f_bus)+\",\"+to_string(t_bus)); // Name of lines\n        arc->_id = index-1;\n        arc->_src = get_node(to_string(f_bus));\n        arc->_dest= get_node(to_string(t_bus));\n        arc->_tie_line = arc->_src->_net_id!=arc->_dest->_net_id;\n        if(arc->_tie_line){\n            DebugOn(\"Tie line: \" << arc->_name << endl);\n        }\n        arc->status = status;\n        arc->_len = length;\n        arc->_is_transformer = (tr==\"true\");\n        arc->connect();\n        add_arc(arc);\n        _exist_arcs.push_back(arc);\n        auto ymat = arma::cx_mat(3,3);\n        for (auto i = 0; i<3; i++) {\n            auto ph_key = \"ph\"+to_string(i+1)+\",\"+arc->_name;\n            auto src = arc->_src->_name;\n            auto dest = arc->_dest->_name;\n            if (arc->_src->_phases.count(i+1)!=0 && arc->_dest->_phases.count(i+1)!=0) {\n                exist_E_ph.insert(ph_key);\n                E_ph.insert(ph_key);\n                if(i==0){\n                    E_ph1.insert(ph_key);\n                }\n                else if(i==1){\n                    E_ph2.insert(ph_key);\n                }\n                else {\n                    E_ph3.insert(ph_key);\n                }\n                arc->_phases.insert(i+1);\n            }\n            else {\n                DebugOn(\"excluding arc: \" << arc->_name << \" on phase \" << i+1 << endl);\n                continue;\n            }\n            r.add_val(ph_key, br_r[i][i].GetDouble());\n            x.add_val(ph_key, br_x[i][i].GetDouble());\n            arc->r = std::max(arc->r, r.eval());\n            arc->x = std::max(arc->x, x.eval());\n            for (auto j = 0; j<3; j++) {\n                br_r_.add_val(arc->_name+\",\"+to_string(i)+\",\"+to_string(j), br_r[i][j].GetDouble());\n                br_x_.add_val(arc->_name+\",\"+to_string(i)+\",\"+to_string(j), br_x[i][j].GetDouble());\n                ymat(i,j) = complex<double>(br_r_.eval(),br_x_.eval());\n            }\n            \n            b_fr_.add_val(ph_key, b_fr[i].GetDouble());\n            b_to_.add_val(ph_key, b_to[i].GetDouble());\n            g_fr_.add_val(ph_key, g_fr[i].GetDouble());\n            g_to_.add_val(ph_key, g_to[i].GetDouble());\n            shift_.add_val(ph_key, shift[i].GetDouble());\n            tap_.add_val(ph_key, tap[i].GetDouble());\n            this->S_max.add_val(ph_key, 10*rating[i].GetDouble());\n        }\n//        br_r_.print();\n        arma::cx_mat ymat_inv = arma::pinv(ymat);\n        if(arc->_phases.count(1)>0){\n            Yr11.add_val(\"ph1,\"+arc->_name, ymat_inv(0,0).real()/3.);\n            Yi11.add_val(\"ph1,\"+arc->_name, -ymat_inv(0,0).imag()/3.);\n            Yr12.add_val(\"ph1,\"+arc->_name, ymat_inv(0,1).real()/3.);\n            Yi12.add_val(\"ph1,\"+arc->_name, -ymat_inv(0,1).imag()/3.);\n            Yr13.add_val(\"ph1,\"+arc->_name, ymat_inv(0,2).real()/3.);\n            Yi13.add_val(\"ph1,\"+arc->_name, -ymat_inv(0,2).imag()/3.);\n        }\n        if(arc->_phases.count(2)>0){\n            Yr21.add_val(\"ph2,\"+arc->_name, ymat_inv(1,0).real()/3.);\n            Yi21.add_val(\"ph2,\"+arc->_name, -ymat_inv(1,0).imag()/3.);\n            Yr22.add_val(\"ph2,\"+arc->_name, ymat_inv(1,1).real()/3.);\n            Yi22.add_val(\"ph2,\"+arc->_name, -ymat_inv(1,1).imag()/3.);\n            Yr23.add_val(\"ph2,\"+arc->_name, ymat_inv(1,2).real()/3.);\n            Yi23.add_val(\"ph2,\"+arc->_name, -ymat_inv(1,2).imag()/3.);\n        }\n        if(arc->_phases.count(3)>0){\n            Yr31.add_val(\"ph3,\"+arc->_name, ymat_inv(2,0).real()/3.);\n            Yi31.add_val(\"ph3,\"+arc->_name, -ymat_inv(2,0).imag()/3.);\n            Yr32.add_val(\"ph3,\"+arc->_name, ymat_inv(2,1).real()/3.);\n            Yi32.add_val(\"ph3,\"+arc->_name, -ymat_inv(2,1).imag()/3.);\n            Yr33.add_val(\"ph3,\"+arc->_name, ymat_inv(2,2).real()/3.);\n            Yi33.add_val(\"ph3,\"+arc->_name, -ymat_inv(2,2).imag()/3.);\n        }\n        \n        for (auto i= 0; i<3; i++) {\n            if(arc->_phases.count(i+1)==0)\n                continue;\n            for (auto j= 0; j<3; j++) {\n                if(arc->_phases.count(j+1)==0)\n                    continue;\n                auto key = \"ph\"+to_string(i+1)+\",ph\"+to_string(j+1)+\",\"+arc->_name;\n                cross_phase.insert(key);\n                g.add_val(key, ymat_inv(i,j).real());\n                b.add_val(key, ymat_inv(i,j).imag());\n            }\n        }\n//        g.print(true);\n//        b.print(true);\n        \n    }\n    \n    Value& generatos = d[\"generator\"];\n    nb_gens = generatos.MemberCount();\n    DebugOn(\"nb_gens = \" << nb_gens << endl);\n    for (auto& g : generatos.GetObject()) {\n        Value& list = g.value;\n        auto gbus = list[\"gen_bus\"].GetInt();\n        Debug(\"bus = \" << gbus << endl);\n        auto index = list[\"index\"].GetInt();\n        auto name = string(list[\"name\"].GetString());\n        auto status =  list[\"status\"].GetInt();\n        auto cost =  list[\"cost\"].GetArray();\n        auto pg =  list[\"pg\"].GetArray();\n        auto qg =  list[\"qg\"].GetArray();\n        auto qgmax =  list[\"qmax\"].GetArray();\n        auto qgmin =  list[\"qmin\"].GetArray();\n        auto pgmax =  list[\"pmax\"].GetArray();\n        auto pgmin =  list[\"pmin\"].GetArray();\n        auto bus = (Bus*)get_node(to_string(gbus));\n        bus->_has_gen = true;\n        name = \"Existing_Gen,\" + bus->_name + \",\" + \"slot\"+to_string(index-1);\n        Gen* gen = new Gen(bus, name, 0, 0, 0, 0);\n        gen->_id = index-1;\n        gen->_active = status;\n        gen->_phases = {1,2,3};\n        gens.push_back(gen);\n        bus->_gen.push_back(gen);\n        _existing_diesel_gens.push_back(gen);\n        \n        if(!bus->_active) {\n            DebugOff(\"INACTIVE GENERATOR GIVEN INACTIVE BUS: \" << gen->_name << endl);\n            gen->_active = false;\n        }\n        else if (!gen->_active) {\n            DebugOn(\"INACTIVE GENERATOR: \" << name << endl);\n        }\n        this->c0.add_val(name,cost[0].GetDouble());\n        this->c1.add_val(name,cost[1].GetDouble());\n        this->c2.add_val(name,cost[2].GetDouble());\n        this->gen_eff.add_val(gen->_name,1);\n        if(bus->_type==3){\n            pg_min.add_val(gen->_name, 0);\n            pg_max.add_val(gen->_name, 1000);\n            qg_min.add_val(gen->_name, -1000);\n            qg_max.add_val(gen->_name, 1000);\n        }\n        else {\n            pg_min.add_val(gen->_name, pgmin[0].GetDouble());\n            pg_max.add_val(gen->_name, pgmax[0].GetDouble());\n            qg_min.add_val(gen->_name, qgmin[0].GetDouble());\n            qg_max.add_val(gen->_name, qgmax[0].GetDouble());\n        }\n        for(auto i=0; i<3; i++){\n            auto ph_key = \"ph\"+to_string(i+1)+\",\"+gen->_name;\n            G_ph.insert(ph_key);\n            exist_G_ph.insert(ph_key);\n            pg_.add_val(ph_key, pg[i].GetDouble());\n            qg_.add_val(ph_key, qg[i].GetDouble());\n        }\n    }\n    Value& loads = d[\"load\"];\n    for (auto& l : loads.GetObject()) {\n        Value& list = l.value;\n        auto lbus = list[\"load_bus\"].GetInt();\n        Debug(\"bus = \" << lbus << endl);\n        auto status =  list[\"status\"].GetInt();\n        auto pd =  list[\"pd\"].GetArray();\n        auto qd =  list[\"qd\"].GetArray();\n        auto load_name = list[\"name\"].GetString();\n        auto critical = list[\"critical\"].GetInt();\n        auto bus = (Bus*)get_node(to_string(lbus));\n        bus->_critical_level = std::max(bus->_critical_level, critical);\n        for(auto ph=1; ph<=3; ph++){\n            auto key = \"ph\"+to_string(ph) +\",\"+string(load_name);\n            _load_map[key] = bus;\n            bus->_loads[key] = make_shared<Load>(load_name, critical);\n        }\n        auto name = bus->_name;\n        for(auto i=0; i<3; i++){\n            auto ph_key = \"ph\"+to_string(i+1)+\",\"+name;\n            if(bus->has_phase(i+1)){\n                bus->_cond[i]->_pl = pd[i].GetDouble();\n                bus->_cond[i]->_ql = qd[i].GetDouble();\n                if(status){\n                    pl.set_val(ph_key, pd[i].GetDouble());\n                    ql.set_val(ph_key, qd[i].GetDouble());\n                }\n                else {\n                    pl.set_val(ph_key, 0);\n                    ql.set_val(ph_key, 0);\n                }\n            }\n        }\n    }\n    Value& shunt = d[\"shunt\"];\n    for (auto& sh : shunt.GetObject()) {\n        Value& list = sh.value;\n        auto bus_id = list[\"shunt_bus\"].GetInt();\n        Debug(\"bus = \" << lbus << endl);\n        auto status =  list[\"status\"].GetInt();\n        auto bs = list[\"bs\"].GetArray();\n        auto gs = list[\"gs\"].GetArray();\n        auto bus = (Bus*)get_node(to_string(bus_id));        \n        for (auto i = 0; i<3; i++) {\n            auto ph_key = \"ph\"+to_string(i+1)+\",\"+bus->_name;\n            bus->_cond[i]->_bs = bs[i].GetDouble();\n            bus->_cond[i]->_gs = gs[i].GetDouble();\n            gs_.add_val(ph_key, bus->_cond[i]->_gs);\n            bs_.add_val(ph_key, bus->_cond[i]->_bs);\n            //            gs_.add_val(bus->_name+\",ph\"+to_string(i+1), 0);\n            //            bs_.add_val(bus->_name+\",ph\"+to_string(i+1), 0);\n        }\n        \n    }\n}\n\n/** Use the time series data to compute averages for typical days */\nvoid PowerNet::compute_loads(){\n    for (unsigned i = 0; i<nb_nodes; i++) {\n        auto b = (Bus*)nodes[i];\n        for (auto year = 0; year < _nb_years; year++) {\n            for (string season :{\"summer\",\"winter\",\"spring\", \"autumn\"}) {\n                for (auto h = 0; h<24; h++) {\n                    for (string phase: {\"ph1\",\"ph2\",\"ph3\"}) {\n                        auto week_key = \"year\"+to_string(year+1)+\",\"+season+\",week,\"+to_string(h+1) + \",\" + phase+ \",\" + b->_name;\n                        auto weekend_key = \"year\"+to_string(year+1)+\",\"+season+\",weekend,\"+to_string(h+1) + \",\" + phase+ \",\" + b->_name;\n                        auto peak_key = \"year\"+to_string(year+1)+\",\"+season+\",peak,\"+to_string(h+1) + \",\" + phase+ \",\" + b->_name;\n                        pl.add_val(week_key, 0);\n                        ql.add_val(week_key, 0);\n                        pl.add_val(weekend_key, 0);\n                        ql.add_val(weekend_key, 0);\n                        pl.add_val(peak_key, 0);\n                        ql.add_val(peak_key, 0);\n                    }\n                }\n            }\n        }\n        for(auto &l: b->_loads){\n            if(!l.second->_active || l.second->_val.empty()){\n                continue;\n            }\n            auto key = l.first;\n            double p_av_week[4][24], p_av_weekend[4][24], p_peak[4][24];\n            double q_av_week[4][24], q_av_weekend[4][24], q_peak[4][24];\n            int nb_week[4][24], nb_weekend[4][24];\n            for (auto i = 0; i<4; i++) {\n                for (auto j = 0; j<24; j++) {\n                    p_av_week[i][j] = 0;\n                    p_av_weekend[i][j] = 0;\n                    p_peak[i][j] = 0;\n                    q_av_week[i][j] = 0;\n                    q_av_weekend[i][j] = 0;\n                    q_peak[i][j] = 0;\n                    nb_week[i][j] = 0;\n                    nb_weekend[i][j] = 0;\n                }\n            }\n            for (auto &p: l.second->_val) {\n                auto tuple = p.first;\n                assert(get<1>(tuple)>0);\n                assert(get<3>(tuple)>=0 && get<3>(tuple)<24);\n                auto season = _months_data.at(get<1>(tuple)-1)._season;\n                auto season_str = _months_season.at(get<1>(tuple));\n                DebugOff(\"month id = \" << to_string(get<1>(tuple)) << endl);\n                DebugOff(\"season = \" << season_str << endl);\n                DebugOff(\"season int = \" << to_string(season) << endl);\n                if(is_weekend(tuple)){\n                    p_av_weekend[season][get<3>(tuple)]+=p.second.real();\n                    q_av_weekend[season][get<3>(tuple)]+=p.second.imag();\n                    nb_weekend[season][get<3>(tuple)]++;\n                }\n                else {\n                    p_av_week[season][get<3>(tuple)]+=p.second.real();\n                    q_av_week[season][get<3>(tuple)]+=p.second.imag();\n                    nb_week[season][get<3>(tuple)]++;\n                }\n                p_peak[season][get<3>(tuple)]=std::max(p_peak[season][get<3>(tuple)],p.second.real());\n                q_peak[season][get<3>(tuple)]=std::max(q_peak[season][get<3>(tuple)],p.second.imag());\n            }\n            //{ summer_=0, winter_=1, spring_=2, autumn_=3}\n            for (auto year = 0; year < _nb_years; year++) {\n                auto season_id = 0;\n                for (string season :{\"summer\",\"winter\",\"spring\", \"autumn\"}) {\n                    for (auto h = 0; h<24; h++) {\n                        assert(nb_weekend[season_id][h]!=0);\n                        p_av_weekend[season_id][h] /= nb_weekend[season_id][h];\n                        assert(nb_week[season_id][h]!=0);\n                        p_av_week[season_id][h] /= nb_week[season_id][h];\n                        q_av_weekend[season_id][h] /= nb_weekend[season_id][h];\n                        q_av_week[season_id][h] /= nb_week[season_id][h];\n                        auto phase = key.substr(0,3);\n                        auto week_key = \"year\"+to_string(year+1)+\",\"+season+\",week,\"+to_string(h+1) + \",\" + phase+ \",\" + b->_name;\n                        auto weekend_key = \"year\"+to_string(year+1)+\",\"+season+\",weekend,\"+to_string(h+1) + \",\" + phase+ \",\" + b->_name;\n                        auto peak_key = \"year\"+to_string(year+1)+\",\"+season+\",peak,\"+to_string(h+1) + \",\" + phase+ \",\" + b->_name;\n                        pl.add_val(week_key, p_av_week[season_id][h]);\n                        ql.add_val(week_key, q_av_week[season_id][h]);\n                        pl.add_val(weekend_key, p_av_weekend[season_id][h]);\n                        ql.add_val(weekend_key, q_av_weekend[season_id][h]);\n                        pl.add_val(peak_key, p_peak[season_id][h]);\n                        ql.add_val(peak_key, q_peak[season_id][h]);\n                    }\n                    season_id++;\n                }\n            }\n        }\n    }\n}\n\nvoid PowerNet::time_expand(const indices& T) {\n    //    c0.time_expand(T);\n    //    c1.time_expand(T);\n    //    c2.time_expand(T);\n//    pl._time_extended = true;\n//    pl_ratio._time_extended = true;\n//    ql._time_extended = true;\n//    pv_out._time_extended = true;\n//    pw_min._time_extended = true;\n//    pw_max._time_extended = true;\n    //    S_max.time_expand(T);\n    //    th_min.time_expand(T);\n    //    th_max.time_expand(T);\n    //    tan_th_min.time_expand(T);\n    //    tan_th_max.time_expand(T);\n    //    r.time_expand(T);\n    //    x.time_expand(T);\n    //    pg_min.time_expand(T);\n    //    pg_max.time_expand(T);\n    //    pv_min.time_expand(T);\n    //    pv_max.time_expand(T);\n    //    qg_min.time_expand(T);\n    //    qg_max.time_expand(T);\n    //    pb_min.time_expand(T);\n    //    pb_max.time_expand(T);\n    //    qb_min.time_expand(T);\n    //    qb_max.time_expand(T);\n    //    w_min.time_expand(T);\n    //    w_max.time_expand(T);\n    //    v_min.time_expand(T);\n    //    v_max.time_expand(T);\n    //    eff_a.time_expand(T);\n    //    eff_b.time_expand(T);\n}\n\n\n//shared_ptr<Model<>> PowerNet::build_ODO_model_polar(int output, double tol, int max_nb_hours, bool networked){\n//\n//\n//    /* Grid Parameters */\n//    _nb_hours = max_nb_hours;\n//\n//    /** Indices Sets */\n//    hours = time(1,max_nb_hours); /**< Hours */\n//    hours._name = \"hours\";\n//    //            indices months = time(\"jan\",\"feb\",\"mar\",\"apr\",\"may\",\"jun\",\"jul\",\"aug\",\"sep\",\"oct\",\"nov\",\"dec\"); /**< Months */\n//    //    indices months = time(\"jan\",\"feb\",\"mar\",\"apr\",\"may\",\"jun\"); /**< Months */\n//    //    months = time(\"apr\", \"aug\", \"dec\"); /**< Months */\n//    //    indices months = time(\"jan\", \"feb\");\n//    //    indices years = time(\"year1\", \"year2\", \"year3\");\n//    years._name = \"years\";\n//    //    indices months = time(\"summer\", \"spring\", \"autumn\", \"winter\");\n//    months._name = \"months\";\n//    indices phases = indices(\"ph1\",\"ph2\",\"ph3\");\n//    phases._name = \"phases\";\n//    //    typical_days = time(\"week\",\"peak\",\"weekend\");\n//    typical_days = time(\"week\");\n//    typical_days._name = \"typical_days\";\n//    T = indices(years,months,typical_days,hours);\n//    double nT = T.size();\n//    DebugOn(\"number of time periods = \" << nT << endl);\n//    Nt = indices(T,N_ph);\n//    Et = indices(T,E_ph);\n//    Et1 = indices(T,E_ph1);\n//    Et2 = indices(T,E_ph2);\n//    Et3 = indices(T,E_ph3);\n//    Gt = indices(T,G_ph);\n//    PVt = indices(T,PV_ph);\n//    Wt = indices(T,Wind_ph);\n//    exist_Gt = indices(T,exist_G_ph);\n//    exist_Bt = indices(T,exist_B_ph);\n//    exist_Et = indices(T,exist_E_ph);\n//    exist_PVt = indices(T,exist_PV_ph);\n//    exist_Windt = indices(T,exist_Wind_ph);\n//    pot_Gt = indices(T,pot_G_ph);\n//    pot_Bt = indices(T,pot_B_ph);\n//    pot_Et = indices(T,pot_E_ph);\n//    pot_PVt = indices(T,pot_PV_ph);\n//    pot_Windt = indices(T,pot_Wind_ph);\n//    Bt = indices(T,B_ph);\n//    /** Sets */\n//    auto bus_pairs = this->get_bus_pairs();\n//    auto gen_nodes = this->gens_per_node_time();\n//    auto batt_nodes = this->Batt_per_node_time();\n//    auto PV_nodes = this->PV_per_node_time();\n//    auto Wind_nodes = this->Wind_per_node_time();\n//    auto out_arcs = this->out_arcs_per_node_time();\n//    auto in_arcs = this->in_arcs_per_node_time();\n//\n//    /** MODEL DECLARATION */\n//    shared_ptr<Model<>> ODO(new Model<>(\"ODO Model\"));\n//    /** VARIABLES */\n//\n//\n//    /* Investment binaries */\n//\n//    var<> Pv_cap(\"Pv_cap\", 0, pv_max); /**< Real variable indicating the extra capacity of PV to be installed on bus b */\n//    ODO->add(Pv_cap.in(pot_PV_ph));\n//    var<int> w_g(\"w_g\",0,1); /**< Binary variable indicating if generator g is built on bus */\n//    var<int> w_b(\"w_b\",0,1); /**< Binary variable indicating if battery b is built on bus */\n//    var<int> w_e(\"w_e\",1,1); /**< Binary variable indicating if expansion is selected for edge e */\n//    var<int> w_pv(\"w_pv\",0,1); /**< Binary variable indicating if PV is installed on bus b */\n//    var<int> w_wind(\"w_wind\",0,1); /**< Binary variable indicating if Wind is installed on bus b */\n//    ODO->add(w_g.in(pot_G_ph),w_b.in(pot_B_ph),w_e.in(pot_E_ph),w_pv.in(pot_PV_ph),w_wind.in(pot_Wind_ph));\n//    w_g.initialize_all(1);\n//    w_b.initialize_all(1);\n//    w_e.initialize_all(1);\n//    w_pv.initialize_all(1);\n//    w_wind.initialize_all(1);\n//\n//    this->w_g = w_g;\n//    this->w_b = w_b;\n//    this->w_e = w_e;\n//    this->w_pv = w_pv;\n//    this->w_wind = w_wind;\n//    this->Pv_cap = Pv_cap;\n//\n//    DebugOff(\"size w_g = \" << w_g.get_dim() << endl);\n//    DebugOff(\"size w_b = \" << w_b.get_dim() << endl);\n//    DebugOff(\"size w_e = \" << w_e.get_dim() << endl);\n//    DebugOff(\"size w_pv = \" << w_pv.get_dim() << endl);\n//    DebugOff(\"size w_wind = \" << w_wind.get_dim() << endl);\n//    DebugOff(\"size Pv_cap = \" << Pv_cap.get_dim() << endl);\n//\n//\n//    /* Diesel power generation variables */\n//    var<> Pg(\"Pg\", pg_min.in(Gt), pg_max.in(Gt));\n//    var<> Qg (\"Qg\", qg_min.in(Gt), qg_max.in(Gt));\n//    var<> Pg_ (\"Pg_\", pg_min.in(Gt), pg_max.in(Gt));/**< Active power generation before losses */\n//    var<> Pg2(\"Pg2\", 0, pow(pg_max.in(pot_Gt),2));/**< Square of Pg */\n//    ODO->add(Pg.in(Gt));\n//    ODO->add(Pg_.in(Gt));\n//    ODO->add(Qg.in(Gt));\n//    ODO->add(Pg2.in(pot_Gt));\n//    DebugOff(\"size Pg = \" << Pg.get_dim() << endl);\n//    DebugOff(\"size Pg_ = \" << Pg_.get_dim() << endl);\n//    DebugOff(\"size Qg = \" << Qg.get_dim() << endl);\n//    DebugOff(\"size Pg2 = \" << Pg2.get_dim() << endl);\n//\n//    this->Pg_ = Pg_;\n//\n//    /* Battery power generation variables */\n//    var<> Pb(\"Pb\", pb_min.in(Bt), pb_max.in(Bt));/**< Active power generation outside the battery */\n//    var<> Qb (\"Qb\", qb_min.in(Bt), qb_max.in(Bt));/**< Reactive power generation outside the battery */\n//    var<> Pb_(\"Pb_\", pb_min.in(Bt), pb_max.in(Bt));/**< Active power generation in the battery */\n//    ODO->add(Pb.in(Bt), Qb.in(Bt), Pb_.in(Bt));\n//    DebugOff(\"size Pb = \" << Pb.get_dim() << endl);\n//    DebugOff(\"size Qb = \" << Qb.get_dim() << endl);\n//\n//\n//    /* PV power generation variables */\n//    var<> Pv(\"Pv\", 0,pv_max.in(PVt));\n//    ODO->add(Pv.in(PVt));\n//    DebugOff(\"size Pv = \" << Pv.get_dim() << endl);\n//\n//    /* Battery state of charge variables */\n//    var<> Sc(\"Sc\", pos_);\n//    ODO->add(Sc.in(Bt));\n//    DebugOff(\"size Sc = \" << Sc.get_dim() << endl);\n//\n//    /* Wind power generation variables */\n//    var<> Pw(\"Pw\", 0, pw_max.in(Wt));\n//    ODO->add(Pw.in(Wt));\n//    DebugOff(\"size Pw = \" << Pw.get_dim() << endl);\n//\n//    /* Power flow variables */\n//    var<> Pij(\"Pfrom\", -1*S_max.in(Et), S_max.in(Et));\n//    var<> Qij(\"Qfrom\", -1*S_max.in(Et), S_max.in(Et));\n//    var<> Pji(\"Pto\", -1*S_max.in(Et), S_max.in(Et));\n//    var<> Qji(\"Qto\", -1*S_max.in(Et), S_max.in(Et));\n//\n//    ODO->add(Pij.in(Et),Pji.in(Et),Qij.in(Et),Qji.in(Et));\n//    DebugOff(\"size Pij = \" << Pij.get_dim() << endl);\n//    ODO->add(Pji.in(Et),Qji.in(Et));\n//\n//    /** Voltage magnitude (squared) variables */\n//    var<> v(\"v\", v_min.in(Nt), v_max.in(Nt));\n//    var<> theta(\"𝛉\");\n//    var<> vr(\"vr\", -1*v_max.in(Nt),v_max.in(Nt));\n//    var<> vi(\"vi\", -1*v_max.in(Nt),v_max.in(Nt));\n//\n//    var<> v_fr, v_to, theta_fr, theta_to;\n//    var<> v_fr1, v_to1, theta_fr1, theta_to1;\n//    var<> v_fr2, v_to2, theta_fr2, theta_to2;\n//    var<> v_fr3, v_to3, theta_fr3, theta_to3;\n//    var<> vr_fr, vr_to, vi_fr, vi_to;\n//    var<> vr_fr1,vr_fr2,vr_fr3,vi_fr1,vi_fr2,vi_fr3;\n//    var<> vr_to1,vr_to2,vr_to3,vi_to1,vi_to2,vi_to3;\n//\n//    ODO->add(v.in(Nt));\n//    ODO->add(theta.in(Nt));\n//    Debug(\"size v = \" << v.get_dim() << endl);\n//    v.initialize_all(1);\n//    v_fr = v.from(Et);\n//    v_to = v.to(Et);\n//    theta_fr = theta.from(Et);\n//    theta_to = theta.to(Et);\n//    /* Indexing the voltage variables */\n//    v_fr1 = v.from(Et1); theta_fr1 = theta.from(Et1);\n//    v_fr2 = v.from(Et2); theta_fr2 = theta.from(Et2);\n//    v_fr3 = v.from(Et3); theta_fr3 = theta.from(Et3);\n//    v_to1 = v.to(Et1); theta_to1 = theta.to(Et1);\n//    v_to2 = v.to(Et2); theta_to2 = theta.to(Et2);\n//    v_to3 = v.to(Et3); theta_to3 = theta.to(Et3);\n//    auto Pij1 = Pij.in(Et1);auto Pij2 = Pij.in(Et2);auto Pij3 = Pij.in(Et3);\n//    auto Pji1 = Pji.in(Et1);auto Pji2 = Pji.in(Et2);auto Pji3 = Pji.in(Et3);\n//    auto Qij1 = Qij.in(Et1);auto Qij2 = Qij.in(Et2);auto Qij3 = Qij.in(Et3);\n//    auto Qji1 = Qji.in(Et1);auto Qji2 = Qji.in(Et2);auto Qji3 = Qji.in(Et3);\n//    /** Indices */\n//    auto branch_id_ph1 = get_branch_id_phase(1);\n//    auto branch_id_ph2 = get_branch_id_phase(2);\n//    auto branch_id_ph3 = get_branch_id_phase(3);\n//    auto branch_ph1 = get_branch_phase(1);\n//    auto branch_ph2 = get_branch_phase(2);\n//    auto branch_ph3 = get_branch_phase(3);\n//    auto ref_from_ph1 = fixed_from_branch_phase(1);\n//    auto ref_from_ph2 = fixed_from_branch_phase(2);\n//    auto ref_from_ph3 = fixed_from_branch_phase(3);\n//    auto ref_to_ph1 = fixed_to_branch_phase(1);\n//    auto ref_to_ph2 = fixed_to_branch_phase(2);\n//    auto ref_to_ph3 = fixed_to_branch_phase(3);\n//    auto from_ph1 = from_branch_phase(1);\n//    auto from_ph2 = from_branch_phase(2);\n//    auto from_ph3 = from_branch_phase(3);\n//    auto to_ph1 = to_branch_phase(1);\n//    auto to_ph2 = to_branch_phase(2);\n//    auto to_ph3 = to_branch_phase(3);\n//\n//    /** Power Flows */\n//    param<Cpx> Y0(\"Y0\"), Y1(\"Y1\"), Y2(\"Y2\"), Y3(\"Y3\");\n//    param<Cpx> Yc_fr(\"Yc_fr\"), Yc_to(\"Yc_to\");/* Line charging */\n//    var<Cpx> Vfr(\"Vfr\"), Vto(\"Vto\");\n//    var<Cpx> Sij(\"Sij\"), Sji(\"Sji\"), Vi(\"Vi\"), Vj(\"Vj\"), Vi1(\"Vi1\"), Vi2(\"Vi2\"), Vi3(\"Vi3\"), Vj1(\"Vj1\"), Vj2(\"Vj2\"), Vj3(\"Vj3\");\n//    /* Phase 1 */\n//    Yc_fr.real_imag(g_fr_.in(Et1),b_fr_.in(Et1));\n//    Yc_to.real_imag(g_to_.in(Et1),b_to_.in(Et1));\n//    Y0.real_imag(g.in(branch_id_ph1),b.in(branch_id_ph1));\n//    Y1.real_imag(g.in(branch_ph1),b.in(branch_ph1));\n//    Vfr.mag_ang(v_fr1,theta_fr1);\n//    Vto.mag_ang(v_to1,theta_to1);\n//    Vi.mag_ang(v.in(ref_from_ph1),theta.in(ref_from_ph1));\n//    Vj.mag_ang(v.in(ref_to_ph1),theta.in(ref_to_ph1));\n//    Vi1.mag_ang(v.in(from_ph1),theta.in(from_ph1));\n//    Vj1.mag_ang(v.in(to_ph1),theta.in(to_ph1));\n//    Sij.real_imag(Pij1,Qij1);\n//    Sji.real_imag(Pji1,Qji1);\n//\n//\n//    Constraint<Cpx> S_fr1(\"S_fr1\"), S_to1(\"S_to1\");\n//    S_fr1 = Sij - (conj(Y0)+conj(Yc_fr))*Vfr*conj(Vfr) + conj(Y0)*Vfr*conj(Vto) - (conj(Y1)*Vi)*(conj(Vi1) - conj(Vj1));\n//    S_to1 = Sji - (conj(Y0)+conj(Yc_to))*Vto*conj(Vto) + conj(Y0)*Vto*conj(Vfr) - (conj(Y1)*Vj)*(conj(Vj1) - conj(Vi1));\n//    ODO->add(S_fr1.in(Et1)==0);\n//    ODO->add(S_to1.in(Et1)==0);\n//    /* Phase 2 */\n//    Yc_fr.real_imag(g_fr_.in(Et2),b_fr_.in(Et2));\n//    Yc_to.real_imag(g_to_.in(Et2),b_to_.in(Et2));\n//    Y0.real_imag(g.in(branch_id_ph2),b.in(branch_id_ph2));\n//    Y2.real_imag(g.in(branch_ph2),b.in(branch_ph2));\n//\n//    Vfr.mag_ang(v_fr2,theta_fr2);\n//    Vto.mag_ang(v_to2,theta_to2);\n//    Vi.mag_ang(v.in(ref_from_ph2),theta.in(ref_from_ph2));\n//    Vj.mag_ang(v.in(ref_to_ph2),theta.in(ref_to_ph2));\n//    Vi2.mag_ang(v.in(from_ph2),theta.in(from_ph2));\n//    Vj2.mag_ang(v.in(to_ph2),theta.in(to_ph2));\n//\n//    Sij.real_imag(Pij2,Qij2);\n//    Sji.real_imag(Pji2,Qji2);\n//    Constraint<Cpx> S_fr2(\"S_fr2\"), S_to2(\"S_to2\");\n//    S_fr2 = Sij - (conj(Y0)+conj(Yc_fr))*Vfr*conj(Vfr) + conj(Y0)*Vfr*conj(Vto) - (conj(Y2)*Vi)*(conj(Vi2) - conj(Vj2));\n//    S_to2 = Sji - (conj(Y0)+conj(Yc_to))*Vto*conj(Vto) + conj(Y0)*Vto*conj(Vfr) - (conj(Y2)*Vj)*(conj(Vj2) - conj(Vi2));\n//    ODO->add(S_fr2.in(Et2)==0);\n//    ODO->add(S_to2.in(Et2)==0);\n//    /* Phase 3 */\n//    Yc_fr.real_imag(g_fr_.in(Et3),b_fr_.in(Et3));\n//    Yc_to.real_imag(g_to_.in(Et3),b_to_.in(Et3));\n//    Y0.real_imag(g.in(branch_id_ph3),b.in(branch_id_ph3));\n//    Y3.real_imag(g.in(branch_ph3),b.in(branch_ph3));\n//    Vfr.mag_ang(v_fr3,theta_fr3);\n//    Vto.mag_ang(v_to3,theta_to3);\n//    Vi.mag_ang(v.in(ref_from_ph3),theta.in(ref_from_ph3));\n//    Vj.mag_ang(v.in(ref_to_ph3),theta.in(ref_to_ph3));\n//    Vi3.mag_ang(v.in(from_ph3),theta.in(from_ph3));\n//    Vj3.mag_ang(v.in(to_ph3),theta.in(to_ph3));\n//\n//    Sij.real_imag(Pij3,Qij3);\n//    Sji.real_imag(Pji3,Qji3);\n//    Constraint<Cpx> S_fr3(\"S_fr3\"), S_to3(\"S_to3\");\n//    S_fr3 = Sij - (conj(Y0)+conj(Yc_fr))*Vfr*conj(Vfr) + conj(Y0)*Vfr*conj(Vto) - (conj(Y3)*Vi)*(conj(Vi3) - conj(Vj3));\n//    S_to3 = Sji - (conj(Y0)+conj(Yc_to))*Vto*conj(Vto) + conj(Y0)*Vto*conj(Vfr) - (conj(Y3)*Vj)*(conj(Vj3) - conj(Vi3));\n//    ODO->add(S_fr3.in(Et3)==0);\n//    ODO->add(S_to3.in(Et3)==0);\n//    //        ODO->print();\n//    //        exit(-1);\n//    //\n//    //    /** Power loss variables */\n//    //    var<Real> ploss(\"ploss\");\n//    //    var<Real> qloss(\"qloss\");\n//    //    if (pmt==DISTF || pmt==CDISTF) {\n//    //        ODO->add(ploss.in(Et));\n//    //        ODO->add(qloss.in(Et));\n//    //    }\n//    //\n//    /** Loss constraint */\n//    //    Constraint<> PLosses1(\"PLosses1\");\n//    //    PLosses1 = Pij + Pji;\n//    //    ODO->add(PLosses1.in(Et) >= 0.004149/nb_branches*Pij);\n//    //\n//    //    Constraint<> PLosses2(\"PLosses2\");\n//    //    PLosses2 = Pij + Pji;\n//    //    ODO->add(PLosses2.in(Et) >= 0.004149/nb_branches*Pji);\n//    //\n//    //    Constraint<> QLosses(\"QLosses\");\n//    //    QLosses = Qij + Qji;\n//    //    ODO->add(QLosses.in(Et) >= 0);\n//    //\n//    /** OBJECTIVE FUNCTION */\n//    //check pot_gen\n//    func<> obj = product(c1.in(exist_Gt), Pg_.in(exist_Gt)) + product(c1.in(pot_Gt), Pg_.in(pot_Gt)) + product(c2.in(exist_Gt), pow(Pg_.in(exist_Gt),2)) + product(c2.in(pot_Gt), Pg2.in(pot_Gt)) + sum(c0.in(exist_Gt));\n//    //    obj *= 12./months.size();\n//    //    obj += nT*product(c0.in(pot_G_ph),w_g);\n//    obj += 1e-3*product(gen_capcost.in(pot_G_ph), w_g);\n//    obj += 1e-3*product(inverter_capcost.in(pot_B_ph), w_b);\n//    obj += 1e-3*product(expansion_capcost.in(pot_E_ph), w_e);\n//    obj += 1e-3*product(pv_capcost.in(pot_PV_ph), w_pv);\n//    obj += 1e-3*product(pv_varcost.in(pot_PV_ph), Pv_cap);\n//    ODO->min(obj);\n//    //    obj += sum(Pg);\n//    //    ODO->min(sum(Pg));\n//    //    func<> obj = product(c2.in(Gt), pow(Pg.in(Gt),2));\n//    //    ODO->min(obj);\n//\n//    /** CONSTRAINTS **/\n//\n//    /** Voltage magnitude at source bus **/\n//    //    indices ref_id(\"ref_id\");\n//    //    ref_id.insert(ref_bus);\n//    //    ref_id = indices(T,phases,ref_id);\n//    //    Constraint<> fix_voltage_mag(\"fix_voltage_mag\");\n//    //    if(pmt==ACPOL){\n//    //        fix_voltage_mag += v.in(ref_id) - vm_s_;\n//    //    }\n//    //    else {\n//    //        fix_voltage_mag += pow(vr.in(ref_id),2) + pow(vi.in(ref_id),2) - pow(vm_s_.in(ref_id),2);\n//    //    }\n//    //    ODO->add(fix_voltage_mag.in(ref_id)==0);\n//\n//\n//    /** Voltage angle at source bus **/\n//    //    Constraint<> fix_voltage_ang(\"fix_voltage_ang\");\n//    //    if(pmt==ACPOL){\n//    //        fix_voltage_ang += theta.in(ref_id) - theta_s_.in(ref_id);\n//    //    }\n//    //    else {\n//    //        fix_voltage_ang += vi.in(ref_id) - theta_s_.in(ref_id)*vr.in(ref_id);\n//    //    }\n//    //    ODO->add(fix_voltage_ang.in(ref_id)==0);\n//\n//    /** FLOW CONSERVATION **/\n//\n//    /** KCL Flow conservation */\n//    Constraint<> KCL_P(\"KCL_P\");\n//    Constraint<> KCL_Q(\"KCL_Q\");\n//    KCL_P  = sum(Pij, out_arcs) + sum(Pji, in_arcs) + pl.in(Nt) - sum(Pg, gen_nodes) - sum(Pv, PV_nodes) - sum(Pb, batt_nodes) - sum(Pw, Wind_nodes);\n//    KCL_Q  = sum(Qij, out_arcs) + sum(Qji, in_arcs) + ql.in(Nt)  - sum(Qg, gen_nodes);\n//    KCL_P += gs_.in(Nt)*pow(v.in(Nt),2);\n//    KCL_Q -= bs_.in(Nt)*pow(v.in(Nt),2);\n//    ODO->add(KCL_P.in(Nt) == 0);\n//    ODO->add(KCL_Q.in(Nt) == 0);\n//\n//    /**  THERMAL LIMITS **/\n//\n//    /*  Thermal Limit Constraints for existing lines */\n//    Constraint<> Thermal_Limit_from(\"Thermal_Limit_from\");\n//    Thermal_Limit_from += pow(Pij.in(exist_Et), 2) + pow(Qij.in(exist_Et), 2);\n//    Thermal_Limit_from -= pow(S_max.in(exist_Et), 2);\n//    ODO->add(Thermal_Limit_from.in(exist_Et) <= 0);\n//\n//    Constraint<> Thermal_Limit_to(\"Thermal_Limit_to\");\n//    Thermal_Limit_to += pow(Pji.in(exist_Et), 2) + pow(Qji.in(exist_Et), 2);\n//    Thermal_Limit_to -= pow(S_max.in(exist_Et), 2);\n//    ODO->add(Thermal_Limit_to.in(exist_Et) <= 0);\n//\n//\n//    /*  Thermal Limit Constraints for expansion edges */\n//    Constraint<> Thermal_Limit_from_exp(\"Thermal_Limit_From_Exp\");\n//    Thermal_Limit_from_exp += pow(Pij.in(pot_Et), 2) + pow(Qij.in(pot_Et), 2);\n//    Thermal_Limit_from_exp -= pow(w_e.in(pot_Et),2)*pow(S_max.in(pot_Et), 2);\n//    ODO->add(Thermal_Limit_from_exp.in(pot_Et) <= 0);\n//\n//    Constraint<> Thermal_Limit_to_exp(\"Thermal_Limit_to_Exp\");\n//    Thermal_Limit_to_exp += pow(Pji.in(pot_Et), 2) + pow(Qji.in(pot_Et), 2);\n//    Thermal_Limit_to_exp -= pow(w_e.in(pot_Et),2)*pow(S_max.in(pot_Et), 2);\n//    ODO->add(Thermal_Limit_to_exp.in(pot_Et) <= 0);\n//\n//    /**  GENERATOR INVESTMENT **/\n//\n//    /*  On/Off status */\n//    Constraint<> OnOff_maxP(\"OnOff_maxP\");\n//    OnOff_maxP += Pg_.in(pot_Gt) - pg_max.in(pot_Gt)*w_g.in(pot_Gt);\n//    ODO->add(OnOff_maxP.in(pot_Gt) <= 0);\n//\n//    Constraint<> Perspective_OnOff(\"Perspective_OnOff\");\n//    Perspective_OnOff += pow(Pg_.in(pot_Gt),2) - Pg2.in(pot_Gt)*w_g.in(pot_Gt);\n//    ODO->add(Perspective_OnOff.in(pot_Gt) <= 0);\n//\n//    Constraint<> OnOff_maxQ(\"OnOff_maxQ\");\n//    OnOff_maxQ += Qg.in(pot_Gt) - qg_max.in(pot_Gt)*w_g.in(pot_Gt);\n//    ODO->add(OnOff_maxQ.in(pot_Gt) <= 0);\n//\n//    Constraint<> OnOff_maxQ_N(\"OnOff_maxQ_N\");\n//    OnOff_maxQ_N += Qg.in(pot_Gt) - qg_min.in(pot_Gt)*w_g.in(pot_Gt);\n//    ODO->add(OnOff_maxQ_N.in(pot_Gt) >= 0);\n//\n//    /**  PV **/\n//\n//    /*  On/Off on Potential PV */\n//    Constraint<> OnOffPV(\"OnOffPV\");\n//    OnOffPV += Pv_cap.in(pot_PV_ph) - w_pv*pv_max.in(pot_PV_ph);\n//    ODO->add(OnOffPV.in(pot_PV_ph) <= 0);\n//\n//    /*  Max Cap on Potential PV */\n//    Constraint<> MaxCapPV(\"MaxCapPV\");\n//    MaxCapPV += Pv.in(pot_PVt) - Pv_cap.in(pot_PVt)*pv_out.in(pot_PVt);\n//    ODO->add(MaxCapPV.in(pot_PVt) <= 0);\n//\n//    /*  Existing PV */\n//    Constraint<> existPV(\"existPV\");\n//    existPV += Pv.in(exist_PVt) - pv_max.in(exist_PVt)*pv_out.in(exist_PVt);\n//    ODO->add(existPV.in(exist_PVt) <= 0);\n//\n//\n//    /**  BATTERIES **/\n//\n//    /*  Apparent Power Limit on Potential Batteries */\n//    Constraint<> Apparent_Limit_Batt_Pot(\"Apparent_Limit_Batt_Potential\");\n//    Apparent_Limit_Batt_Pot += pow(Pb.in(pot_Bt), 2) + pow(Qb.in(pot_Bt), 2);\n//    Apparent_Limit_Batt_Pot -= pow(w_b.in(pot_Bt),2)*pow(pb_max.in(pot_Bt), 2);\n//    ODO->add(Apparent_Limit_Batt_Pot.in(pot_Bt) <= 0);\n//\n//    /*  Apparent Power Limit on Existing Batteries */\n//    Constraint<> Apparent_Limit_Batt(\"Apparent_Limit_Batt_Existing\");\n//    Apparent_Limit_Batt += pow(Pb.in(exist_Bt), 2) + pow(Qb.in(exist_Bt), 2);\n//    Apparent_Limit_Batt -= pow(pb_max.in(exist_Bt), 2);\n//    ODO->add(Apparent_Limit_Batt.in(exist_Bt) <= 0);\n//\n//\n//    /*  State Of Charge */\n//    auto T1 = T.exclude(T.first());/**< Excluding first time step */\n//    auto Tn = T.exclude(T.last());/**< Excluding last time step */\n//    Bt1 = indices(T1,B_ph);\n//    Btn = indices(Tn,B_ph);\n//    Constraint<> State_Of_Charge(\"State_Of_Charge\");\n//    State_Of_Charge = Sc.in(Bt1) - Sc.in(Btn) + Pb_.in(Bt1);\n//    ODO->add(State_Of_Charge.in(Bt1) == 0);\n//\n//    /*  State Of Charge 0 */\n//    auto T0 = indices(\"T0\");\n//    T0.insert(T.first());\n//    auto Bat0 = indices(T0,B_ph);\n//    Constraint<> State_Of_Charge0(\"State_Of_Charge0\");\n//    State_Of_Charge0 = Sc.in(Bat0);\n//    ODO->add(State_Of_Charge0.in(Bat0) == 0);\n//    Constraint<> Pb0(\"Pb0\");\n//    Pb0 = Pb_.in(Bat0);\n//    ODO->add(Pb0.in(Bat0) == 0);\n//\n//    /*  EFFICIENCIES */\n//    Constraint<> DieselEff(\"DieselEff\");\n//    DieselEff += Pg - gen_eff.in(Gt)*Pg_;\n//    ODO->add(DieselEff.in(Gt) == 0);\n//\n//    auto exist_batt_eff = indices(exist_Bt,_eff_pieces);\n//    auto pot_batt_eff = indices(pot_Bt,_eff_pieces);\n//    Constraint<> EfficiencyExist(\"BatteryEfficiencyExisting\");\n//    EfficiencyExist += Pb.in(exist_batt_eff)  - eff_a.in(exist_batt_eff)*Pb_.in(exist_batt_eff) - eff_b.in(exist_batt_eff);\n//    ODO->add(EfficiencyExist.in(exist_batt_eff) <= 0);\n//\n//    Constraint<> EfficiencyPot(\"BatteryEfficiencyPotential\");\n//    EfficiencyPot += Pb.in(pot_batt_eff)  - eff_a.in(pot_batt_eff)*Pb_.in(pot_batt_eff) - eff_b.in(pot_batt_eff)*w_b.in(pot_batt_eff);\n//    ODO->add(EfficiencyPot.in(pot_batt_eff) <= 0);\n//    //\n//    //\n//    //    for (auto n:nodes) {\n//    //        auto b = (Bus*)n;\n//    //        //        b->print();\n//    //        for (auto i = 0; i < b->_pot_gen.size(); i++) {\n//    //            auto gen = b->_pot_gen[i];\n//    //            if(min_diesel_invest.eval(gen->_name)==max_diesel_invest.eval(gen->_name)){\n//    //                Constraint FixedDieselInvest(\"FixedDieselInvest\"+gen->_name);\n//    //                FixedDieselInvest += w_g(gen->_name);\n//    //                ODO->add(FixedDieselInvest == 1);\n//    //                for (auto j = i+1; j < b->_pot_gen.size(); j++) {\n//    //                    auto gen2 = b->_pot_gen[j];\n//    //                    if (gen2->_gen_type==gen->_gen_type) {\n//    //                        Constraint FixedDieselInvest(\"FixedDieselInvest\"+gen2->_name);\n//    //                        FixedDieselInvest += w_g(gen2->_name);\n//    //                        ODO->add(FixedDieselInvest == 1);\n//    //                    }\n//    //                }\n//    //            }\n//    //            else {\n//    //                Constraint MinDieselInvest(\"MinDieselInvest_\"+b->_name+\"_DG\"+to_string(gen->_gen_type));\n//    //                MinDieselInvest += w_g(gen->_name);\n//    //                for (auto j = i+1; j < b->_pot_gen.size(); j++) {\n//    //                    auto gen2 = b->_pot_gen[j];\n//    //                    if (gen2->_gen_type==gen->_gen_type) {\n//    //                        MinDieselInvest += w_g(gen2->_name);\n//    //                    }\n//    //                }\n//    //                auto rhs = min_diesel_invest.eval(gen->_name);\n//    //                if (rhs>0) {\n//    //                    ODO->add(MinDieselInvest >= rhs);\n//    //                }\n//    //            }\n//    //        }\n//    //        for (auto i = 0; i < b->_pot_bat.size(); i++) {\n//    //            auto bat = b->_pot_bat[i];\n//    //            if(min_batt_invest.eval(bat->_name)==max_batt_invest.eval(bat->_name)){\n//    //                Constraint FixedBattInvest(\"FixedBattInvest\"+bat->_name);\n//    //                FixedBattInvest += w_b(bat->_name);\n//    //                ODO->add(FixedBattInvest == 1);\n//    //                for (auto j = i+1; j < b->_pot_bat.size(); j++) {\n//    //                    auto bat2 = b->_pot_bat[j];\n//    //                    if (bat2->_bat_type==bat->_bat_type) {\n//    //                        Constraint FixedBattInvest(\"FixedBattInvest\"+bat2->_name);\n//    //                        FixedBattInvest += w_b(bat2->_name);\n//    //                        ODO->add(FixedBattInvest == 1);\n//    //                    }\n//    //                }\n//    //            }\n//    //            else {\n//    //                Constraint MinBattInvest(\"MinBattInvest_\"+b->_name+\"_DG\"+to_string(bat->_bat_type));\n//    //                MinBattInvest += w_b(bat->_name);\n//    //                for (auto j = i+1; j < b->_pot_bat.size(); j++) {\n//    //                    auto bat2 = b->_pot_bat[j];\n//    //                    if (bat2->_bat_type==bat->_bat_type) {\n//    //                        MinBattInvest += w_b(bat2->_name);\n//    //                    }\n//    //                }\n//    //                auto rhs = min_batt_invest.eval(bat->_name);\n//    //                if (rhs>0) {\n//    //                    ODO->add(MinBattInvest >= rhs);\n//    //                }\n//    //            }\n//    //        }\n//    //    }\n//    //    ODO->print();\n//    bool build_contingency = true;\n//    if(build_contingency){\n//        DebugOn(\"Building resiliency constraints\" << endl);\n//        Gt_c = get_conting_gens(_res_scenarios);\n//        Et_c = get_conting_arcs(_res_scenarios);\n//        auto ConT = get_time_ids_conting(_res_scenarios);\n//        PVt_c = indices(ConT, PV_ph);\n//        Bt_c = indices(ConT, B_ph);\n//    }\n//\n//\n//    return ODO;\n//}\n\n\nshared_ptr<Model<>> PowerNet::build_ODO_model(PowerModelType pmt, int output, double tol, int max_nb_hours, bool networked){\n    \n   \n    /* Grid Parameters */\n    _nb_hours = max_nb_hours;\n    \n    /** Indices Sets */\n    hours = time(1,max_nb_hours); /**< Hours */\n    hours._name = \"hours\";\n//            indices months = time(\"jan\",\"feb\",\"mar\",\"apr\",\"may\",\"jun\",\"jul\",\"aug\",\"sep\",\"oct\",\"nov\",\"dec\"); /**< Months */\n    //    indices months = time(\"jan\",\"feb\",\"mar\",\"apr\",\"may\",\"jun\"); /**< Months */\n    //    months = time(\"apr\", \"aug\", \"dec\"); /**< Months */\n//    indices months = time(\"jan\", \"feb\");\n//    indices years = time(\"year1\", \"year2\", \"year3\");\n    years._name = \"years\";\n//    indices months = time(\"summer\", \"spring\", \"autumn\", \"winter\");\n    months._name = \"months\";\n    indices phases = indices(\"ph1\",\"ph2\",\"ph3\");\n    phases._name = \"phases\";\n//    typical_days = time(\"week\",\"peak\",\"weekend\");\n//    typical_days = time(\"week\");\n    typical_days._name = \"typical_days\";\n    T = indices(years,months,typical_days,hours);\n    double nT = T.size();\n    DebugOn(\"number of time periods = \" << nT << endl);\n    Nt = indices(T,N_ph);\n    Nt_c = get_conting_nodes(_res_scenarios);\n    N_out = get_outaged_nodes(_res_scenarios);\n    Et = indices(T,E_ph);\n    Et1 = indices(T,E_ph1);\n    Et2 = indices(T,E_ph2);\n    Et3 = indices(T,E_ph3);\n    Gt = indices(T,G_ph);\n    PVt = indices(T,PV_ph);\n    Wt = indices(T,Wind_ph);\n    exist_Gt = indices(T,exist_G_ph);\n    exist_Bt = indices(T,exist_B_ph);\n    exist_Et = indices(T,exist_E_ph);\n    exist_PVt = indices(T,exist_PV_ph);\n    exist_Windt = indices(T,exist_Wind_ph);\n    pot_Gt = indices(T,pot_G_ph);\n    pot_Bt = indices(T,pot_B_ph);\n    pot_Et = indices(T,pot_E_ph);\n    pot_PVt = indices(T,pot_PV_ph);\n    pot_Windt = indices(T,pot_Wind_ph);\n    Bt = indices(T,B_ph);\n    \n    T_c = get_time_ids_conting(_res_scenarios);\n\n    \n    /** Sets */\n    auto bus_pairs = this->get_bus_pairs();\n    auto gen_nodes = this->gens_per_node_time();\n    auto batt_nodes = this->Batt_per_node_time();\n    auto PV_nodes = this->PV_per_node_time();\n    auto Wind_nodes = this->Wind_per_node_time();\n    auto out_arcs = this->out_arcs_per_node_time();\n    auto in_arcs = this->in_arcs_per_node_time();\n    \n    /** MODEL DECLARATION */\n    shared_ptr<Model<>> ODO(new Model<>(\"ODO Model\"));\n    /** VARIABLES */\n\n\n    /* Investment binaries */\n\n    var<> Pv_cap(\"Pv_cap\", 0, pv_max); /**< Real variable indicating the extra capacity of PV to be installed on bus b */\n    ODO->add(Pv_cap.in(pot_PV_ph));\n    var<int> w_g(\"w_g\",0,1); /**< Binary variable indicating if generator g is built on bus */\n    var<int> w_b(\"w_b\",0,1); /**< Binary variable indicating if battery b is built on bus */\n    var<int> w_e(\"w_e\",0,1); /**< Binary variable indicating if expansion is selected for edge e */\n    var<int> w_pv(\"w_pv\",0,1); /**< Binary variable indicating if PV is installed on bus b */\n    var<int> w_wind(\"w_wind\",0,1); /**< Binary variable indicating if Wind is installed on bus b */\n    ODO->add(w_g.in(pot_G_ph),w_b.in(pot_B_ph),w_e.in(pot_E_ph),w_pv.in(pot_PV_ph),w_wind.in(pot_Wind_ph));\n//    w_g.initialize_uniform();\n//    w_b.initialize_uniform();\n//    w_e.initialize_uniform();\n//    w_pv.initialize_uniform();\n//    w_wind.initialize_uniform();\n    w_b.initialize_all(1);\n    w_e.initialize_all(1);\n    w_pv.initialize_all(1);\n    w_wind.initialize_all(1);\n\n//    this->w_g = w_g;\n//    this->w_b = w_b;\n//    this->w_e = w_e;\n//    this->w_pv = w_pv;\n//    this->w_wind = w_wind;\n    this->Pv_cap = Pv_cap;\n\n    DebugOff(\"size w_g = \" << w_g.get_dim() << endl);\n    DebugOff(\"size w_b = \" << w_b.get_dim() << endl);\n    DebugOff(\"size w_e = \" << w_e.get_dim() << endl);\n    DebugOff(\"size w_pv = \" << w_pv.get_dim() << endl);\n    DebugOff(\"size w_wind = \" << w_wind.get_dim() << endl);\n    DebugOff(\"size Pv_cap = \" << Pv_cap.get_dim() << endl);\n\n\n    /* Diesel power generation variables */\n    var<> Pg(\"Pg\", pg_min.in(Gt), pg_max.in(Gt));\n    var<> Qg (\"Qg\", qg_min.in(Gt), qg_max.in(Gt));\n    var<> Pg_ (\"Pg_\", pg_min.in(Gt), pg_max.in(Gt));/**< Active power generation before losses */\n    var<> Pg2(\"Pg2\", 0, pow(pg_max.in(pot_Gt),2));/**< Square of Pg */\n    ODO->add(Pg.in(Gt));\n    ODO->add(Pg_.in(Gt));\n    ODO->add(Qg.in(Gt));\n    ODO->add(Pg2.in(pot_Gt));\n    DebugOff(\"size Pg = \" << Pg.get_dim() << endl);\n    DebugOff(\"size Pg_ = \" << Pg_.get_dim() << endl);\n    DebugOff(\"size Qg = \" << Qg.get_dim() << endl);\n    DebugOff(\"size Pg2 = \" << Pg2.get_dim() << endl);\n\n    this->Pg_ = Pg_;\n\n    /* Battery power generation variables */\n    var<> Pb(\"Pb\", pb_min.in(Bt), pb_max.in(Bt));/**< Active power generation outside the battery */\n    var<> Qb (\"Qb\", qb_min.in(Bt), qb_max.in(Bt));/**< Reactive power generation outside the battery */\n    var<> Pb_(\"Pb_\", pb_min.in(Bt), pb_max.in(Bt));/**< Active power generation in the battery */\n    ODO->add(Pb.in(Bt), Qb.in(Bt), Pb_.in(Bt));\n    DebugOff(\"size Pb = \" << Pb.get_dim() << endl);\n    DebugOff(\"size Qb = \" << Qb.get_dim() << endl);\n\n\n    /* PV power generation variables */\n    var<> Pv(\"Pv\", 0,pv_max.in(PVt));\n    ODO->add(Pv.in(PVt));\n    DebugOff(\"size Pv = \" << Pv.get_dim() << endl);\n\n    /* Battery state of charge variables */\n    var<> Sc(\"Sc\", pos_);\n    ODO->add(Sc.in(Bt));\n    DebugOff(\"size Sc = \" << Sc.get_dim() << endl);\n\n    /* Wind power generation variables */\n    var<> Pw(\"Pw\", 0, pw_max.in(Wt));\n    ODO->add(Pw.in(Wt));\n    DebugOff(\"size Pw = \" << Pw.get_dim() << endl);\n\n    /* Power flow variables */\n    var<> Pij(\"Pfrom\", -1*S_max.in(Et), S_max.in(Et));\n    var<> Qij(\"Qfrom\", -1*S_max.in(Et), S_max.in(Et));\n    var<> Pji(\"Pto\", -1*S_max.in(Et), S_max.in(Et));\n    var<> Qji(\"Qto\", -1*S_max.in(Et), S_max.in(Et));\n\n    ODO->add(Pij.in(Et),Pji.in(Et),Qij.in(Et),Qji.in(Et));\n    DebugOff(\"size Pij = \" << Pij.get_dim() << endl);\n\n    /** Voltage magnitude variables */\n    var<> vr(\"vr\", -1*v_max.in(Nt),v_max.in(Nt));\n    var<> vi(\"vi\", -1*v_max.in(Nt),v_max.in(Nt));\n    \n    var<> v_fr, v_to, theta_fr, theta_to;\n    var<> v_fr1, v_to1, theta_fr1, theta_to1;\n    var<> v_fr2, v_to2, theta_fr2, theta_to2;\n    var<> v_fr3, v_to3, theta_fr3, theta_to3;\n    var<> vr_fr, vr_to, vi_fr, vi_to;\n    var<> vr_fr1,vr_fr2,vr_fr3,vi_fr1,vi_fr2,vi_fr3;\n    var<> vr_to1,vr_to2,vr_to3,vi_to1,vi_to2,vi_to3;\n    \n    if (pmt==ACRECT) {\n        ODO->add(vr.in(Nt));\n        ODO->add(vi.in(Nt));\n        vr.initialize_all(1);\n        vr_fr = vr.from(Et);\n        vr_to = vr.to(Et);\n        vi_fr = vi.from(Et);\n        vi_to = vi.to(Et);\n        \n        /* Indexing the voltage variables */\n        vr_fr1 = vr.from(Et1); vi_fr1 = vi.from(Et1);\n        vr_fr2 = vr.from(Et2); vi_fr2 = vi.from(Et2);\n        vr_fr3 = vr.from(Et3); vi_fr3 = vi.from(Et3);\n        vr_to1 = vr.to(Et1); vi_to1 = vi.to(Et1);\n        vr_to2 = vr.to(Et2); vi_to2 = vi.to(Et2);\n        vr_to3 = vr.to(Et3); vi_to3 = vi.to(Et3);\n        \n    }\n    auto Pij1 = Pij.in(Et1);auto Pij2 = Pij.in(Et2);auto Pij3 = Pij.in(Et3);\n    auto Pji1 = Pji.in(Et1);auto Pji2 = Pji.in(Et2);auto Pji3 = Pji.in(Et3);\n    auto Qij1 = Qij.in(Et1);auto Qij2 = Qij.in(Et2);auto Qij3 = Qij.in(Et3);\n    auto Qji1 = Qji.in(Et1);auto Qji2 = Qji.in(Et2);auto Qji3 = Qji.in(Et3);\n    /** Indices */\n    auto branch_id_ph1 = get_branch_id_phase(1);\n    auto branch_id_ph2 = get_branch_id_phase(2);\n    auto branch_id_ph3 = get_branch_id_phase(3);\n    auto branch_ph1 = get_branch_phase(1);\n    auto branch_ph2 = get_branch_phase(2);\n    auto branch_ph3 = get_branch_phase(3);\n    auto ref_from_ph1 = fixed_from_branch_phase(1);\n    auto ref_from_ph2 = fixed_from_branch_phase(2);\n    auto ref_from_ph3 = fixed_from_branch_phase(3);\n    auto ref_to_ph1 = fixed_to_branch_phase(1);\n    auto ref_to_ph2 = fixed_to_branch_phase(2);\n    auto ref_to_ph3 = fixed_to_branch_phase(3);\n    auto from_ph1 = from_branch_phase(1);\n    auto from_ph2 = from_branch_phase(2);\n    auto from_ph3 = from_branch_phase(3);\n    auto to_ph1 = to_branch_phase(1);\n    auto to_ph2 = to_branch_phase(2);\n    auto to_ph3 = to_branch_phase(3);\n    bool ACPower = false;\n    if(ACPower){\n        /** Power Flows */\n        param<Cpx> Y0(\"Y0\"), Y1(\"Y1\"), Y2(\"Y2\"), Y3(\"Y3\");\n        param<Cpx> Yc_fr(\"Yc_fr\"), Yc_to(\"Yc_to\");/* Line charging */\n        var<Cpx> Vfr(\"Vfr\"), Vto(\"Vto\");\n        var<Cpx> Sij(\"Sij\"), Sji(\"Sji\"), Vi(\"Vi\"), Vj(\"Vj\"), Vi1(\"Vi1\"), Vi2(\"Vi2\"), Vi3(\"Vi3\"), Vj1(\"Vj1\"), Vj2(\"Vj2\"), Vj3(\"Vj3\");\n        /* Phase 1 */\n        Yc_fr.real_imag(g_fr_.in(Et1),b_fr_.in(Et1));\n        Yc_to.real_imag(g_to_.in(Et1),b_to_.in(Et1));\n        Y0.real_imag(g.in(branch_id_ph1),b.in(branch_id_ph1));\n        Y1.real_imag(g.in(branch_ph1),b.in(branch_ph1));\n        if(pmt==ACRECT){\n            Vfr.real_imag(vr_fr1,vi_fr1);\n            Vto.real_imag(vr_to1,vi_to1);\n            Vi.real_imag(vr.in(ref_from_ph1),vi.in(ref_from_ph1));\n            Vj.real_imag(vr.in(ref_to_ph1),vi.in(ref_to_ph1));\n            Vi1.real_imag(vr.in(from_ph1),vi.in(from_ph1));\n            Vj1.real_imag(vr.in(to_ph1),vi.in(to_ph1));\n        }\n        Sij.real_imag(Pij1,Qij1);\n        Sji.real_imag(Pji1,Qji1);\n    \n    \n        Constraint<Cpx> S_fr1(\"S_fr1\"), S_to1(\"S_to1\");\n        S_fr1 = Sij - (conj(Y0)+conj(Yc_fr))*Vfr*conj(Vfr) + conj(Y0)*Vfr*conj(Vto) - (conj(Y1)*Vi)*(conj(Vi1) - conj(Vj1));\n        S_to1 = Sji - (conj(Y0)+conj(Yc_to))*Vto*conj(Vto) + conj(Y0)*Vto*conj(Vfr) - (conj(Y1)*Vj)*(conj(Vj1) - conj(Vi1));\n        ODO->add(S_fr1.in(Et1)==0);\n        ODO->add(S_to1.in(Et1)==0);\n        /* Phase 2 */\n        Yc_fr.real_imag(g_fr_.in(Et2),b_fr_.in(Et2));\n        Yc_to.real_imag(g_to_.in(Et2),b_to_.in(Et2));\n        Y0.real_imag(g.in(branch_id_ph2),b.in(branch_id_ph2));\n        Y2.real_imag(g.in(branch_ph2),b.in(branch_ph2));\n    \n        if(pmt==ACRECT){\n            Vfr.real_imag(vr_fr2,vi_fr2);\n            Vto.real_imag(vr_to2,vi_to2);\n            Vi.real_imag(vr.in(ref_from_ph2),vi.in(ref_from_ph2));\n            Vj.real_imag(vr.in(ref_to_ph2),vi.in(ref_to_ph2));\n            Vi2.real_imag(vr.in(from_ph2),vi.in(from_ph2));\n            Vj2.real_imag(vr.in(to_ph2),vi.in(to_ph2));\n        }\n    \n        Sij.real_imag(Pij2,Qij2);\n        Sji.real_imag(Pji2,Qji2);\n        Constraint<Cpx> S_fr2(\"S_fr2\"), S_to2(\"S_to2\");\n        S_fr2 = Sij - (conj(Y0)+conj(Yc_fr))*Vfr*conj(Vfr) + conj(Y0)*Vfr*conj(Vto) - (conj(Y2)*Vi)*(conj(Vi2) - conj(Vj2));\n        S_to2 = Sji - (conj(Y0)+conj(Yc_to))*Vto*conj(Vto) + conj(Y0)*Vto*conj(Vfr) - (conj(Y2)*Vj)*(conj(Vj2) - conj(Vi2));\n        ODO->add(S_fr2.in(Et2)==0);\n        ODO->add(S_to2.in(Et2)==0);\n        /* Phase 3 */\n        Yc_fr.real_imag(g_fr_.in(Et3),b_fr_.in(Et3));\n        Yc_to.real_imag(g_to_.in(Et3),b_to_.in(Et3));\n        Y0.real_imag(g.in(branch_id_ph3),b.in(branch_id_ph3));\n        Y3.real_imag(g.in(branch_ph3),b.in(branch_ph3));\n        if(pmt==ACRECT){\n            Vfr.real_imag(vr_fr3,vi_fr3);\n            Vto.real_imag(vr_to3,vi_to3);\n            Vi.real_imag(vr.in(ref_from_ph3),vi.in(ref_from_ph3));\n            Vj.real_imag(vr.in(ref_to_ph3),vi.in(ref_to_ph3));\n            Vi3.real_imag(vr.in(from_ph3),vi.in(from_ph3));\n            Vj3.real_imag(vr.in(to_ph3),vi.in(to_ph3));\n        }\n    \n        Sij.real_imag(Pij3,Qij3);\n        Sji.real_imag(Pji3,Qji3);\n        Constraint<Cpx> S_fr3(\"S_fr3\"), S_to3(\"S_to3\");\n        S_fr3 = Sij - (conj(Y0)+conj(Yc_fr))*Vfr*conj(Vfr) + conj(Y0)*Vfr*conj(Vto) - (conj(Y3)*Vi)*(conj(Vi3) - conj(Vj3));\n        S_to3 = Sji - (conj(Y0)+conj(Yc_to))*Vto*conj(Vto) + conj(Y0)*Vto*conj(Vfr) - (conj(Y3)*Vj)*(conj(Vj3) - conj(Vi3));\n        ODO->add(S_fr3.in(Et3)==0);\n        ODO->add(S_to3.in(Et3)==0);\n    }\n    else { /* Just add loss constraints */\n        Constraint<> Loss1(\"Loss1\");\n        Loss1 = Pij1 + Pji1;\n        ODO->add(Loss1.in(Et1)==0);\n        \n        Constraint<> Loss2(\"Loss2\");\n        Loss2 = Pij2 + Pji2;\n        ODO->add(Loss2.in(Et2)==0);\n        \n        Constraint<> Loss3(\"Loss3\");\n        Loss3 = Pij3 + Pji3;\n        ODO->add(Loss3.in(Et3)==0);\n    }\n\n    var<> pls(\"pls\", 0, 1);/**< percentage of real load shed */\n    var<> qls(\"qls\", 0, 1);/**< percentage of reactive load shed */\n    ODO->add(pls.in(Nt_c), qls.in(Nt_c));\n//        ODO->print();\n//        exit(-1);\n//\n//    /** Power loss variables */\n//    var<Real> ploss(\"ploss\");\n//    var<Real> qloss(\"qloss\");\n//    if (pmt==DISTF || pmt==CDISTF) {\n//        ODO->add(ploss.in(Et));\n//        ODO->add(qloss.in(Et));\n//    }\n//\n    /** Loss constraint */\n//    Constraint<> PLosses1(\"PLosses1\");\n//    PLosses1 = Pij + Pji;\n//    ODO->add(PLosses1.in(Et) >= 0.004149/nb_branches*Pij);\n//\n//    Constraint<> PLosses2(\"PLosses2\");\n//    PLosses2 = Pij + Pji;\n//    ODO->add(PLosses2.in(Et) >= 0.004149/nb_branches*Pji);\n//\n//    Constraint<> QLosses(\"QLosses\");\n//    QLosses = Qij + Qji;\n//    ODO->add(QLosses.in(Et) >= 0);\n//\n    /** OBJECTIVE FUNCTION */\n    //check pot_gen\n    func<> obj = product(c1.in(exist_Gt), Pg_.in(exist_Gt)) + product(c1.in(pot_Gt), Pg_.in(pot_Gt)) + product(c2.in(exist_Gt), pow(Pg_.in(exist_Gt),2)) + product(c2.in(pot_Gt), Pg2.in(pot_Gt)) + sum(c0.in(exist_Gt));\n    //    obj *= 12./months.size();\n//    obj += nT*product(c0.in(pot_G_ph),w_g);\n    obj += 1e-2*product(gen_capcost.in(pot_G_ph), w_g);\n    obj += 1e-2*product(inverter_capcost.in(pot_B_ph), w_b);\n    obj += 1e-2*product(expansion_capcost.in(pot_E_ph), w_e);\n    obj += 1e-2*product(pv_capcost.in(pot_PV_ph), w_pv);\n    obj += 1e-2*product(pv_varcost.in(pot_PV_ph), Pv_cap);\n    obj += 1e+3*(sum(pls) + sum(qls));\n//    for(auto &key: *pot_PV_ph._keys){\n//        obj += pow(pow(w_pv(key),2) - w_pv(key),2);\n//    }\n    ODO->min(obj);\n//    obj.print();\n//    pv_capcost.print();\n//    obj += sum(Pg);\n//    ODO->min(sum(Pg));\n//    func<> obj = product(c2.in(Gt), pow(Pg.in(Gt),2));\n//    ODO->min(obj);\n\n    /** CONSTRAINTS **/\n\n    /** Voltage magnitude at source bus **/\n//    indices ref_id(\"ref_id\");\n//    ref_id.insert(ref_bus);\n//    ref_id = indices(T,phases,ref_id);\n//    Constraint<> fix_voltage_mag(\"fix_voltage_mag\");\n//    if(pmt==ACPOL){\n//        fix_voltage_mag += v.in(ref_id) - vm_s_;\n//    }\n//    else {\n//        fix_voltage_mag += pow(vr.in(ref_id),2) + pow(vi.in(ref_id),2) - pow(vm_s_.in(ref_id),2);\n//    }\n//    ODO->add(fix_voltage_mag.in(ref_id)==0);\n\n\n    /** Voltage angle at source bus **/\n//    Constraint<> fix_voltage_ang(\"fix_voltage_ang\");\n//    if(pmt==ACPOL){\n//        fix_voltage_ang += theta.in(ref_id) - theta_s_.in(ref_id);\n//    }\n//    else {\n//        fix_voltage_ang += vi.in(ref_id) - theta_s_.in(ref_id)*vr.in(ref_id);\n//    }\n//    ODO->add(fix_voltage_ang.in(ref_id)==0);\n\n    if(_networked){\n        cout << endl << \"Running in networked mode\" << endl;\n    }\n    else {\n        cout << endl << \"Running in isolated mode\" << endl;\n    }\n\n    \n    /** Networking Constraints **/\n    indices Tielines = get_tielines();\n    if(!_networked){\n        Constraint<> Tielines_Off(\"Tielines_Off\");\n        Tielines_Off += w_e.in(Tielines);\n        ODO->add(Tielines_Off.in(Tielines) == 0);\n    }\n    /** FLOW CONSERVATION **/\n    \n    /** KCL Flow conservation */\n    Constraint<> KCL_P(\"KCL_P\");\n    Constraint<> KCL_Q(\"KCL_Q\");\n    KCL_P  = sum(Pij, out_arcs) + sum(Pji, in_arcs) + pl.in(Nt) - sum(Pg, gen_nodes) - sum(Pv, PV_nodes) - sum(Pb, batt_nodes) - sum(Pw, Wind_nodes);\n    KCL_Q  = sum(Qij, out_arcs) + sum(Qji, in_arcs) + ql.in(Nt)  - sum(Qg, gen_nodes);\n    KCL_P += gs_.in(Nt)*(pow(vr.in(Nt),2)+pow(vi.in(Nt),2));\n    KCL_Q -= bs_.in(Nt)*(pow(vr.in(Nt),2)+pow(vi.in(Nt),2));\n    ODO->add(KCL_P.in(Nt) == 0);\n    ODO->add(KCL_Q.in(Nt) == 0);\n\n    /**  THERMAL LIMITS **/\n\n    /*  Thermal Limit Constraints for existing lines */\n    Constraint<> Thermal_Limit_from(\"Thermal_Limit_from\");\n    Thermal_Limit_from += pow(Pij.in(exist_Et), 2) + pow(Qij.in(exist_Et), 2);\n    Thermal_Limit_from -= pow(S_max.in(exist_Et), 2);\n    ODO->add(Thermal_Limit_from.in(exist_Et) <= 0);\n\n    Constraint<> Thermal_Limit_to(\"Thermal_Limit_to\");\n    Thermal_Limit_to += pow(Pji.in(exist_Et), 2) + pow(Qji.in(exist_Et), 2);\n    Thermal_Limit_to -= pow(S_max.in(exist_Et), 2);\n    ODO->add(Thermal_Limit_to.in(exist_Et) <= 0);\n\n\n    /*  Thermal Limit Constraints for expansion edges */\n    Constraint<> Thermal_Limit_from_exp(\"Thermal_Limit_From_Exp\");\n    Thermal_Limit_from_exp += pow(Pij.in(pot_Et), 2) + pow(Qij.in(pot_Et), 2);\n    Thermal_Limit_from_exp -= pow(w_e.in(pot_Et),2)*pow(S_max.in(pot_Et), 2);\n    ODO->add(Thermal_Limit_from_exp.in(pot_Et) <= 0);\n    \n    Constraint<> Thermal_Limit_to_exp(\"Thermal_Limit_to_Exp\");\n    Thermal_Limit_to_exp += pow(Pji.in(pot_Et), 2) + pow(Qji.in(pot_Et), 2);\n    Thermal_Limit_to_exp -= pow(w_e.in(pot_Et),2)*pow(S_max.in(pot_Et), 2);\n    ODO->add(Thermal_Limit_to_exp.in(pot_Et) <= 0);\n\n    /** AC voltage limit constraints. */\n    if (pmt==ACRECT) {\n        Constraint<> Vol_limit_UB(\"Vol_limit_UB\");\n        Vol_limit_UB = pow(vr.in(Nt), 2) + pow(vi.in(Nt), 2);\n        Vol_limit_UB -= pow(v_max.in(Nt), 2);\n        ODO->add(Vol_limit_UB.in(Nt) <= 0);\n        \n        Constraint<> Vol_limit_LB(\"Vol_limit_LB\");\n        Vol_limit_LB = pow(vr.in(Nt), 2) + pow(vi.in(Nt), 2);\n        Vol_limit_LB -= pow(v_min.in(Nt),2);\n        ODO->add(Vol_limit_LB.in(Nt) >= 0);\n    }\n    \n    /**  GENERATOR INVESTMENT **/\n\n    /*  On/Off status */\n    Constraint<> OnOff_maxP(\"OnOff_maxP\");\n    OnOff_maxP += Pg_.in(pot_Gt) - pg_max.in(pot_Gt)*w_g.in(pot_Gt);\n    ODO->add(OnOff_maxP.in(pot_Gt) <= 0);\n\n    Constraint<> Perspective_OnOff(\"Perspective_OnOff\");\n    Perspective_OnOff += pow(Pg_.in(pot_Gt),2) - Pg2.in(pot_Gt)*w_g.in(pot_Gt);\n    ODO->add(Perspective_OnOff.in(pot_Gt) <= 0);\n\n    Constraint<> OnOff_maxQ(\"OnOff_maxQ\");\n    OnOff_maxQ += Qg.in(pot_Gt) - qg_max.in(pot_Gt)*w_g.in(pot_Gt);\n    ODO->add(OnOff_maxQ.in(pot_Gt) <= 0);\n\n    Constraint<> OnOff_maxQ_N(\"OnOff_maxQ_N\");\n    OnOff_maxQ_N += Qg.in(pot_Gt) - qg_min.in(pot_Gt)*w_g.in(pot_Gt);\n    ODO->add(OnOff_maxQ_N.in(pot_Gt) >= 0);\n\n     /**  PV **/\n\n    /*  On/Off on Potential PV */\n    Constraint<> OnOffPV(\"OnOffPV\");\n    OnOffPV += Pv_cap.in(pot_PV_ph) - w_pv*pv_max.in(pot_PV_ph);\n    ODO->add(OnOffPV.in(pot_PV_ph) <= 0);\n    Pv_cap.print();\n\n    /*  Max Cap on Potential PV */\n    Constraint<> MaxCapPV(\"MaxCapPV\");\n    MaxCapPV += Pv.in(pot_PVt) - Pv_cap.in(pot_PVt)*pv_out.in(pot_PVt);\n    ODO->add(MaxCapPV.in(pot_PVt) <= 0);\n\n    /*  Existing PV */\n    Constraint<> existPV(\"existPV\");\n    existPV += Pv.in(exist_PVt) - pv_max.in(exist_PVt)*pv_out.in(exist_PVt);\n    ODO->add(existPV.in(exist_PVt) <= 0);\n\n\n    /**  BATTERIES **/\n\n    /*  Apparent Power Limit on Potential Batteries */\n    Constraint<> Apparent_Limit_Batt_Pot(\"Apparent_Limit_Batt_Potential\");\n    Apparent_Limit_Batt_Pot += pow(Pb.in(pot_Bt), 2) + pow(Qb.in(pot_Bt), 2);\n    Apparent_Limit_Batt_Pot -= pow(w_b.in(pot_Bt),2)*pow(pb_max.in(pot_Bt), 2);\n    ODO->add(Apparent_Limit_Batt_Pot.in(pot_Bt) <= 0);\n\n    /*  Apparent Power Limit on Existing Batteries */\n    Constraint<> Apparent_Limit_Batt(\"Apparent_Limit_Batt_Existing\");\n    Apparent_Limit_Batt += pow(Pb.in(exist_Bt), 2) + pow(Qb.in(exist_Bt), 2);\n    Apparent_Limit_Batt -= pow(pb_max.in(exist_Bt), 2);\n    ODO->add(Apparent_Limit_Batt.in(exist_Bt) <= 0);\n\n\n    /*  State Of Charge */\n    auto T1 = T.exclude(T.first());/**< Excluding first time step */\n    auto Tn = T.exclude(T.last());/**< Excluding last time step */\n    Bt1 = indices(T1,B_ph);\n    Btn = indices(Tn,B_ph);\n    Constraint<> State_Of_Charge(\"State_Of_Charge\");\n    State_Of_Charge = Sc.in(Bt1) - Sc.in(Btn) + Pb_.in(Bt1);\n    ODO->add(State_Of_Charge.in(Bt1) == 0);\n\n    /*  State Of Charge 0 */\n    auto T0 = indices(\"T0\");\n    T0.insert(T.first());\n    auto Bat0 = indices(T0,B_ph);\n    Constraint<> State_Of_Charge0(\"State_Of_Charge0\");\n    State_Of_Charge0 = Sc.in(Bat0);\n    ODO->add(State_Of_Charge0.in(Bat0) == 0);\n    Constraint<> Pb0(\"Pb0\");\n    Pb0 = Pb_.in(Bat0);\n    ODO->add(Pb0.in(Bat0) == 0);\n\n    /*  EFFICIENCIES */\n    Constraint<> DieselEff(\"DieselEff\");\n    DieselEff += Pg - gen_eff.in(Gt)*Pg_;\n    ODO->add(DieselEff.in(Gt) == 0);\n\n    auto exist_batt_eff = indices(exist_Bt,_eff_pieces);\n    auto pot_batt_eff = indices(pot_Bt,_eff_pieces);\n    Constraint<> EfficiencyExist(\"BatteryEfficiencyExisting\");\n    EfficiencyExist += Pb.in(exist_batt_eff)  - eff_a.in(exist_batt_eff)*Pb_.in(exist_batt_eff) - eff_b.in(exist_batt_eff);\n    ODO->add(EfficiencyExist.in(exist_batt_eff) <= 0);\n\n    Constraint<> EfficiencyPot(\"BatteryEfficiencyPotential\");\n    EfficiencyPot += Pb.in(pot_batt_eff)  - eff_a.in(pot_batt_eff)*Pb_.in(pot_batt_eff) - eff_b.in(pot_batt_eff)*w_b.in(pot_batt_eff);\n    ODO->add(EfficiencyPot.in(pot_batt_eff) <= 0);\n//\n//\n//    for (auto n:nodes) {\n//        auto b = (Bus*)n;\n//        //        b->print();\n//        for (auto i = 0; i < b->_pot_gen.size(); i++) {\n//            auto gen = b->_pot_gen[i];\n//            if(min_diesel_invest.eval(gen->_name)==max_diesel_invest.eval(gen->_name)){\n//                Constraint FixedDieselInvest(\"FixedDieselInvest\"+gen->_name);\n//                FixedDieselInvest += w_g(gen->_name);\n//                ODO->add(FixedDieselInvest == 1);\n//                for (auto j = i+1; j < b->_pot_gen.size(); j++) {\n//                    auto gen2 = b->_pot_gen[j];\n//                    if (gen2->_gen_type==gen->_gen_type) {\n//                        Constraint FixedDieselInvest(\"FixedDieselInvest\"+gen2->_name);\n//                        FixedDieselInvest += w_g(gen2->_name);\n//                        ODO->add(FixedDieselInvest == 1);\n//                    }\n//                }\n//            }\n//            else {\n//                Constraint MinDieselInvest(\"MinDieselInvest_\"+b->_name+\"_DG\"+to_string(gen->_gen_type));\n//                MinDieselInvest += w_g(gen->_name);\n//                for (auto j = i+1; j < b->_pot_gen.size(); j++) {\n//                    auto gen2 = b->_pot_gen[j];\n//                    if (gen2->_gen_type==gen->_gen_type) {\n//                        MinDieselInvest += w_g(gen2->_name);\n//                    }\n//                }\n//                auto rhs = min_diesel_invest.eval(gen->_name);\n//                if (rhs>0) {\n//                    ODO->add(MinDieselInvest >= rhs);\n//                }\n//            }\n//        }\n//        for (auto i = 0; i < b->_pot_bat.size(); i++) {\n//            auto bat = b->_pot_bat[i];\n//            if(min_batt_invest.eval(bat->_name)==max_batt_invest.eval(bat->_name)){\n//                Constraint FixedBattInvest(\"FixedBattInvest\"+bat->_name);\n//                FixedBattInvest += w_b(bat->_name);\n//                ODO->add(FixedBattInvest == 1);\n//                for (auto j = i+1; j < b->_pot_bat.size(); j++) {\n//                    auto bat2 = b->_pot_bat[j];\n//                    if (bat2->_bat_type==bat->_bat_type) {\n//                        Constraint FixedBattInvest(\"FixedBattInvest\"+bat2->_name);\n//                        FixedBattInvest += w_b(bat2->_name);\n//                        ODO->add(FixedBattInvest == 1);\n//                    }\n//                }\n//            }\n//            else {\n//                Constraint MinBattInvest(\"MinBattInvest_\"+b->_name+\"_DG\"+to_string(bat->_bat_type));\n//                MinBattInvest += w_b(bat->_name);\n//                for (auto j = i+1; j < b->_pot_bat.size(); j++) {\n//                    auto bat2 = b->_pot_bat[j];\n//                    if (bat2->_bat_type==bat->_bat_type) {\n//                        MinBattInvest += w_b(bat2->_name);\n//                    }\n//                }\n//                auto rhs = min_batt_invest.eval(bat->_name);\n//                if (rhs>0) {\n//                    ODO->add(MinBattInvest >= rhs);\n//                }\n//            }\n//        }\n//    }\n//    ODO->print();\n    bool build_contingency = true;\n    if(build_contingency){\n        DebugOn(\"Building resiliency constraints\" << endl);\n        auto scenarios = get_all_conting(_res_scenarios);\n        Gt_c = get_conting_gens(_res_scenarios);\n        Et_c = get_conting_arcs(_res_scenarios);\n        PVt_c = indices(T_c, PV_ph);\n        Bt_c = indices(T_c, B_ph);\n        Windt_c = indices(T_c, Wind_ph);\n        Et1_c = get_phase(Et_c,1);\n        Et2_c = get_phase(Et_c,2);\n        Et3_c = get_phase(Et_c,3);\n        \n        \n        auto gen_nodes_c = this->gens_per_node_time_cont(_res_scenarios);\n        auto batt_nodes_c = this->Batt_per_node_time_cont();\n        auto PV_nodes_c = this->PV_per_node_time_cont();\n        auto Wind_nodes_c = this->Wind_per_node_time_cont();\n        auto out_arcs_c = this->out_arcs_per_node_time_cont(_res_scenarios);\n        auto in_arcs_c = this->in_arcs_per_node_time_cont(_res_scenarios);\n        \n\n        /* Diesel power generation variables in each contingency/resiliency scenario*/\n        var<> Pg_c(\"Pg_c\", pg_min.in(Gt_c), pg_max.in(Gt_c));\n        var<> Qg_c (\"Qg_c\", qg_min.in(Gt_c), qg_max.in(Gt_c));\n        var<> Pg_c_ (\"Pg_c_\", pg_min.in(Gt_c), pg_max.in(Gt_c));/**< Active power generation before losses */\n        ODO->add(Pg_c.in(Gt_c),Pg_c_.in(Gt_c),Qg_c.in(Gt_c));\n        DebugOff(\"size Pg_c = \" << Pg_c.get_dim() << endl);\n        DebugOff(\"size Pg_c_ = \" << Pg_c_.get_dim() << endl);\n        DebugOff(\"size Qg_c = \" << Qg_c.get_dim() << endl);\n        \n        \n        /* Battery power generation variables */\n        var<> Pb_c(\"Pb_c\", pb_min.in(Bt_c), pb_max.in(Bt_c));/**< Active power generation outside the battery */\n        var<> Qb_c (\"Qb_c\", qb_min.in(Bt_c), qb_max.in(Bt_c));/**< Reactive power generation outside the battery */\n        var<> Pb_c_(\"Pb_c_\", pb_min.in(Bt_c), pb_max.in(Bt_c));/**< Active power generation in the battery */\n        ODO->add(Pb_c.in(Bt_c), Qb_c.in(Bt_c), Pb_c_.in(Bt_c));\n        DebugOff(\"size Pb_c = \" << Pb_c.get_dim() << endl);\n        DebugOff(\"size Qb_c = \" << Qb_c.get_dim() << endl);\n        \n        \n        /* PV power generation variables */\n        var<> Pv_c(\"Pv_c\", 0,pv_max.in(PVt_c));\n        ODO->add(Pv_c.in(PVt_c));\n        DebugOff(\"size Pv_c = \" << Pv_c.get_dim() << endl);\n        \n        /* Battery state of charge variables */\n        var<> Sc_c(\"Sc_c\", pos_);\n        ODO->add(Sc_c.in(Bt_c));\n        DebugOff(\"size Sc_c = \" << Sc_c.get_dim() << endl);\n        \n        /* Wind power generation variables */\n        var<> Pw_c(\"Pw_c\", 0, pw_max.in(Windt_c));\n        ODO->add(Pw_c.in(Windt_c));\n        DebugOff(\"size Pw_c = \" << Pw_c.get_dim() << endl);\n        \n        /* Power flow variables */\n        var<> Pij_c(\"Pfr_c\", -1*S_max.in(Et_c), S_max.in(Et_c));\n        var<> Qij_c(\"Qfr_c\", -1*S_max.in(Et_c), S_max.in(Et_c));\n        var<> Pji_c(\"Pto_c\", -1*S_max.in(Et_c), S_max.in(Et_c));\n        var<> Qji_c(\"Qto_c\", -1*S_max.in(Et_c), S_max.in(Et_c));\n        \n        ODO->add(Pij_c.in(Et_c),Pji_c.in(Et_c),Qij_c.in(Et_c),Qji_c.in(Et_c));\n        DebugOff(\"size Pij_c = \" << Pij_c.get_dim() << endl);\n        \n        /** Voltage magnitude variables */\n        \n        \n        var<> vr_c(\"vr_c\", -1*v_max.in(Nt_c),v_max.in(Nt_c));\n        var<> vi_c(\"vi_c\", -1*v_max.in(Nt_c),v_max.in(Nt_c));\n        \n        var<> v_fr_c, v_to_c;\n        var<> v_fr1_c, v_to1_c;\n        var<> v_fr2_c, v_to2_c;\n        var<> v_fr3_c, v_to3_c;\n        var<> vr_fr_c, vr_to_c, vi_fr_c, vi_to_c;\n        var<> vr_fr1_c,vr_fr2_c,vr_fr3_c,vi_fr1_c,vi_fr2_c,vi_fr3_c;\n        var<> vr_to1_c,vr_to2_c,vr_to3_c,vi_to1_c,vi_to2_c,vi_to3_c;\n        \n        if (pmt==ACRECT) {\n            ODO->add(vr_c.in(Nt_c),vi_c.in(Nt_c));\n            vr_c.initialize_all(1);\n            vr_fr_c = vr_c.from(Et_c);\n            vr_to_c = vr_c.to(Et_c);\n            vi_fr_c = vi_c.from(Et_c);\n            vi_to_c = vi_c.to(Et_c);\n            \n            /* Indexing the voltage variables */\n            vr_fr1_c = vr_c.from(Et1_c); vi_fr1_c = vi_c.from(Et1_c);\n            vr_fr2_c = vr_c.from(Et2_c); vi_fr2_c = vi_c.from(Et2_c);\n            vr_fr3_c = vr_c.from(Et3_c); vi_fr3_c = vi_c.from(Et3_c);\n            vr_to1_c = vr_c.to(Et1_c); vi_to1_c = vi_c.to(Et1_c);\n            vr_to2_c = vr_c.to(Et2_c); vi_to2_c = vi_c.to(Et2_c);\n            vr_to3_c = vr_c.to(Et3_c); vi_to3_c = vi_c.to(Et3_c);\n            \n        }\n        auto Pij1_c = Pij_c.in(Et1_c);auto Pij2_c = Pij_c.in(Et2_c);auto Pij3_c = Pij_c.in(Et3_c);\n        auto Pji1_c = Pji_c.in(Et1_c);auto Pji2_c = Pji_c.in(Et2_c);auto Pji3_c = Pji_c.in(Et3_c);\n        auto Qij1_c = Qij_c.in(Et1_c);auto Qij2_c = Qij_c.in(Et2_c);auto Qij3_c = Qij_c.in(Et3_c);\n        auto Qji1_c = Qji_c.in(Et1_c);auto Qji2_c = Qji_c.in(Et2_c);auto Qji3_c = Qji_c.in(Et3_c);\n        /** Indices */\n        auto branch_id_ph1_c = get_branch_id_phase(1,true);\n        auto branch_id_ph2_c = get_branch_id_phase(2,true);\n        auto branch_id_ph3_c = get_branch_id_phase(3,true);\n        auto branch_ph1_c = get_branch_phase(1,true);\n        auto branch_ph2_c = get_branch_phase(2,true);\n        auto branch_ph3_c = get_branch_phase(3,true);\n        \n        auto ref_from_ph1_c = fixed_from_branch_phase(1,true);\n        auto ref_from_ph2_c = fixed_from_branch_phase(2,true);\n        auto ref_from_ph3_c = fixed_from_branch_phase(3,true);\n        auto ref_to_ph1_c = fixed_to_branch_phase(1,true);\n        auto ref_to_ph2_c = fixed_to_branch_phase(2,true);\n        auto ref_to_ph3_c = fixed_to_branch_phase(3,true);\n        auto from_ph1_c = from_branch_phase(1,true);\n        auto from_ph2_c = from_branch_phase(2,true);\n        auto from_ph3_c = from_branch_phase(3,true);\n        auto to_ph1_c = to_branch_phase(1,true);\n        auto to_ph2_c = to_branch_phase(2,true);\n        auto to_ph3_c = to_branch_phase(3,true);\n        \n        bool add_AC_Flow = false;\n        if(add_AC_Flow){\n            /** Power Flows */\n            param<Cpx> Y0_c(\"Y0_c\"), Y1_c(\"Y1_c\"), Y2_c(\"Y2_c\"), Y3_c(\"Y3_c\");\n            param<Cpx> Yc_fr_c(\"Yc_fr_c\"), Yc_to_c(\"Yc_to_c\");/* Line charging */\n            var<Cpx> Vfr_c(\"Vfr_c\"), Vto_c(\"Vto_c\");\n            var<Cpx> Sij_c(\"Sij_c\"), Sji_c(\"Sji_c\"), Vi_c(\"Vi_c\"), Vj_c(\"Vj_c\"), Vi1_c(\"Vi1_c\"), Vi2_c(\"Vi2_c\"), Vi3_c(\"Vi3_c\"), Vj1_c(\"Vj1_c\"), Vj2_c(\"Vj2_c\"), Vj3_c(\"Vj3_c\");\n            /* Phase 1 */\n            Yc_fr_c.real_imag(g_fr_.in(Et1_c),b_fr_.in(Et1_c));\n            Yc_to_c.real_imag(g_to_.in(Et1_c),b_to_.in(Et1_c));\n            Y0_c.real_imag(g.in(branch_id_ph1_c),b.in(branch_id_ph1_c));\n            Y1_c.real_imag(g.in(branch_ph1_c),b.in(branch_ph1_c));\n            if(pmt==ACRECT){\n                Vfr_c.real_imag(vr_fr1_c,vi_fr1_c);\n                Vto_c.real_imag(vr_to1_c,vi_to1_c);\n                Vi_c.real_imag(vr_c.in(ref_from_ph1_c),vi_c.in(ref_from_ph1_c));\n                Vj_c.real_imag(vr_c.in(ref_to_ph1_c),vi_c.in(ref_to_ph1_c));\n                Vi1_c.real_imag(vr_c.in(from_ph1_c),vi_c.in(from_ph1_c));\n                Vj1_c.real_imag(vr_c.in(to_ph1_c),vi_c.in(to_ph1_c));\n            }\n            Sij_c.real_imag(Pij1_c,Qij1_c);\n            Sji_c.real_imag(Pji1_c,Qji1_c);\n            \n            \n            Constraint<Cpx> S_fr1_c(\"S_fr1_c\"), S_to1_c(\"S_to1_c\");\n            S_fr1_c = Sij_c - (conj(Y0_c)+conj(Yc_fr_c))*Vfr_c*conj(Vfr_c) + conj(Y0_c)*Vfr_c*conj(Vto_c) - (conj(Y1_c)*Vi_c)*(conj(Vi1_c) - conj(Vj1_c));\n            S_to1_c = Sji_c - (conj(Y0_c)+conj(Yc_to_c))*Vto_c*conj(Vto_c) + conj(Y0_c)*Vto_c*conj(Vfr_c) - (conj(Y1_c)*Vj_c)*(conj(Vj1_c) - conj(Vi1_c));\n            ODO->add(S_fr1_c.in(Et1_c)==0);\n            ODO->add(S_to1_c.in(Et1_c)==0);\n            /* Phase 2 */\n            Yc_fr_c.real_imag(g_fr_.in(Et2_c),b_fr_.in(Et2_c));\n            Yc_to_c.real_imag(g_to_.in(Et2_c),b_to_.in(Et2_c));\n            Y0_c.real_imag(g.in(branch_id_ph2_c),b.in(branch_id_ph2_c));\n            Y2_c.real_imag(g.in(branch_ph2_c),b.in(branch_ph2_c));\n            \n            if(pmt==ACRECT){\n                Vfr_c.real_imag(vr_fr2_c,vi_fr2_c);\n                Vto_c.real_imag(vr_to2_c,vi_to2_c);\n                Vi_c.real_imag(vr_c.in(ref_from_ph2_c),vi_c.in(ref_from_ph2_c));\n                Vj_c.real_imag(vr_c.in(ref_to_ph2_c),vi_c.in(ref_to_ph2_c));\n                Vi2_c.real_imag(vr_c.in(from_ph2_c),vi_c.in(from_ph2_c));\n                Vj2_c.real_imag(vr_c.in(to_ph2_c),vi_c.in(to_ph2_c));\n            }\n            \n            Sij_c.real_imag(Pij2_c,Qij2_c);\n            Sji_c.real_imag(Pji2_c,Qji2_c);\n            Constraint<Cpx> S_fr2_c(\"S_fr2_c\"), S_to2_c(\"S_to2_c\");\n            S_fr2_c = Sij_c - (conj(Y0_c)+conj(Yc_fr_c))*Vfr_c*conj(Vfr_c) + conj(Y0_c)*Vfr_c*conj(Vto_c) - (conj(Y2_c)*Vi_c)*(conj(Vi2_c) - conj(Vj2_c));\n            S_to2_c = Sji_c - (conj(Y0_c)+conj(Yc_to_c))*Vto_c*conj(Vto_c) + conj(Y0_c)*Vto_c*conj(Vfr_c) - (conj(Y2_c)*Vj_c)*(conj(Vj2_c) - conj(Vi2_c));\n            ODO->add(S_fr2_c.in(Et2_c)==0);\n            ODO->add(S_to2_c.in(Et2_c)==0);\n            /* Phase 3 */\n            Yc_fr_c.real_imag(g_fr_.in(Et3_c),b_fr_.in(Et3_c));\n            Yc_to_c.real_imag(g_to_.in(Et3_c),b_to_.in(Et3_c));\n            Y0_c.real_imag(g.in(branch_id_ph3_c),b.in(branch_id_ph3_c));\n            Y3_c.real_imag(g.in(branch_ph3_c),b.in(branch_ph3_c));\n            if(pmt==ACRECT){\n                Vfr_c.real_imag(vr_fr3_c,vi_fr3_c);\n                Vto_c.real_imag(vr_to3_c,vi_to3_c);\n                Vi_c.real_imag(vr_c.in(ref_from_ph3_c),vi_c.in(ref_from_ph3_c));\n                Vj_c.real_imag(vr_c.in(ref_to_ph3_c),vi_c.in(ref_to_ph3_c));\n                Vi3_c.real_imag(vr_c.in(from_ph3_c),vi_c.in(from_ph3_c));\n                Vj3_c.real_imag(vr_c.in(to_ph3_c),vi_c.in(to_ph3_c));\n            }\n            \n            Sij_c.real_imag(Pij3_c,Qij3_c);\n            Sji_c.real_imag(Pji3_c,Qji3_c);\n            Constraint<Cpx> S_fr3_c(\"S_fr3_c\"), S_to3_c(\"S_to3_c\");\n            S_fr3_c = Sij_c - (conj(Y0_c)+conj(Yc_fr_c))*Vfr_c*conj(Vfr_c) + conj(Y0_c)*Vfr_c*conj(Vto_c) - (conj(Y3_c)*Vi_c)*(conj(Vi3_c) - conj(Vj3_c));\n            S_to3_c = Sji_c - (conj(Y0_c)+conj(Yc_to_c))*Vto_c*conj(Vto_c) + conj(Y0_c)*Vto_c*conj(Vfr_c) - (conj(Y3_c)*Vj_c)*(conj(Vj3_c) - conj(Vi3_c));\n            ODO->add(S_fr3_c.in(Et3_c)==0);\n            ODO->add(S_to3_c.in(Et3_c)==0);\n        }\n        else { /* Just add loss constraints */\n            Constraint<> Loss1(\"Loss1_c\");\n            Loss1 = Pij1_c + Pji1_c;\n            ODO->add(Loss1.in(Et1_c)==0);\n            \n            Constraint<> Loss2(\"Loss2_c\");\n            Loss2 = Pij2_c + Pji2_c;\n            ODO->add(Loss2.in(Et2_c)==0);\n\n            Constraint<> Loss3(\"Loss3_c\");\n            Loss3 = Pij3_c + Pji3_c;\n            ODO->add(Loss3.in(Et3_c)==0);\n        }\n        \n//        Constraint<> BinaryCstrG(\"BinaryCstrG\");\n//        BinaryCstrG += pow(w_g,2) - w_g;\n//        ODO->add(BinaryCstrG.in(pot_G_ph)>=0);\n//\n//        Constraint<> BinaryCstrPV(\"BinaryCstrPV\");\n//        BinaryCstrPV += pow(w_pv,2) - w_pv;\n//        ODO->add(BinaryCstrPV.in(pot_PV_ph)>=0);\n//\n//        Constraint<> BinaryCstrBatt(\"BinaryCstrBatt\");\n//        BinaryCstrBatt += pow(w_b,2) - w_b;\n//        ODO->add(BinaryCstrBatt.in(pot_B_ph)>=0);\n//\n//        Constraint<> BinaryCstrE(\"BinaryCstrE\");\n//        BinaryCstrE += pow(w_e,2) - w_e;\n//        ODO->add(BinaryCstrE.in(pot_E_ph)>=0);\n        /** Fuel limit on generators */\n        auto gens_cont = this->gens_cont(_res_scenarios);\n        auto gens_time = this->gens_time(gens_cont);\n        Constraint<> Fuel(\"Fuel\");\n        Fuel  = sum(Pg_c, gens_time);\n//        ODO->add(Fuel.in(gens_cont) <= _nb_fuel_hours*pg_max.in(gens_cont));\n//        Fuel.print();\n        /** KCL Flow conservation in contingency/resiliency mode */\n        Constraint<> KCL_P_c(\"KCL_P_c\");\n        Constraint<> KCL_Q_c(\"KCL_Q_c\");\n        KCL_P_c  = sum(Pij_c, out_arcs_c) + sum(Pji_c, in_arcs_c) + pl.in(Nt_c)*(1-pls.in(Nt_c)) - sum(Pg_c, gen_nodes_c) - sum(Pv_c, PV_nodes_c) - sum(Pb_c, batt_nodes_c) - sum(Pw_c, Wind_nodes_c);\n        KCL_Q_c  = sum(Qij_c, out_arcs_c) + sum(Qji_c, in_arcs_c) + ql.in(Nt_c)*(1-qls.in(Nt_c))  - sum(Qg_c, gen_nodes_c);\n        KCL_P_c += gs_.in(Nt_c)*(pow(vr_c.in(Nt_c),2)+pow(vi_c.in(Nt_c),2));\n        KCL_Q_c -= bs_.in(Nt_c)*(pow(vr_c.in(Nt_c),2)+pow(vi_c.in(Nt_c),2));\n        ODO->add(KCL_P_c.in(Nt_c) == 0);\n        ODO->add(KCL_Q_c.in(Nt_c) == 0);\n        /**  THERMAL LIMITS **/\n        auto exist_Et_c = get_conting_arcs_exist(_res_scenarios);\n        /*  Thermal Limit Constraints for existing lines */\n        Constraint<> Thermal_Limit_from_c(\"Thermal_Limit_from_c\");\n        Thermal_Limit_from_c += pow(Pij_c.in(exist_Et_c), 2) + pow(Qij_c.in(exist_Et_c), 2);\n        Thermal_Limit_from_c -= pow(S_max.in(exist_Et_c), 2);\n        ODO->add(Thermal_Limit_from_c.in(exist_Et_c) <= 0);\n\n        Constraint<> Thermal_Limit_to_c(\"Thermal_Limit_to_c\");\n        Thermal_Limit_to_c += pow(Pji_c.in(exist_Et_c), 2) + pow(Qji_c.in(exist_Et_c), 2);\n        Thermal_Limit_to_c -= pow(S_max.in(exist_Et_c), 2);\n        ODO->add(Thermal_Limit_to_c.in(exist_Et_c) <= 0);\n        \n        \n        auto pot_Gt_c = get_conting_gens_pot(_res_scenarios);\n        auto pot_Et_c = get_conting_arcs_pot(_res_scenarios);\n\n        /*  Thermal Limit Constraints for expansion edges */\n        Constraint<> Thermal_Limit_from_exp_c(\"Thermal_Limit_From_Exp_c\");\n        Thermal_Limit_from_exp_c += pow(Pij_c.in(pot_Et_c), 2) + pow(Qij_c.in(pot_Et_c), 2);\n        Thermal_Limit_from_exp_c -= pow(w_e.in(pot_Et_c),2)*pow(S_max.in(pot_Et_c), 2);\n        ODO->add(Thermal_Limit_from_exp_c.in(pot_Et_c) <= 0);\n\n        Constraint<> Thermal_Limit_to_exp_c(\"Thermal_Limit_to_Exp_c\");\n        Thermal_Limit_to_exp_c += pow(Pji_c.in(pot_Et_c), 2) + pow(Qji_c.in(pot_Et_c), 2);\n        Thermal_Limit_to_exp_c -= pow(w_e.in(pot_Et_c),2)*pow(S_max.in(pot_Et_c), 2);\n        ODO->add(Thermal_Limit_to_exp_c.in(pot_Et_c) <= 0);\n        \n        /** AC voltage limit constraints. */\n        if (pmt==ACRECT) {\n            Constraint<> Vol_limit_UB_c(\"Vol_limit_UB_c\");\n            Vol_limit_UB_c = pow(vr_c.in(Nt_c), 2) + pow(vi_c.in(Nt_c), 2);\n            Vol_limit_UB_c -= pow(v_max.in(Nt_c), 2);\n            ODO->add(Vol_limit_UB_c.in(Nt_c) <= 0);\n\n            Constraint<> Vol_limit_LB_c(\"Vol_limit_LB_c\");\n            Vol_limit_LB_c = pow(vr_c.in(Nt_c), 2) + pow(vi_c.in(Nt_c), 2);\n            Vol_limit_LB_c -= pow(v_min.in(Nt_c),2);\n            ODO->add(Vol_limit_LB_c.in(Nt_c) >= 0);\n        }\n        auto Nt_critical = indices(T_c, get_critical(1));\n        Constraint<> Critical_Loads_p(\"Critical_Loads_p\");\n        Critical_Loads_p = pls.in(Nt_critical);\n        ODO->add(Critical_Loads_p.in(Nt_critical) == 0);\n\n        Constraint<> Critical_Loads_q(\"Critical_Loads_q\");\n        Critical_Loads_q = qls.in(Nt_critical);\n        ODO->add(Critical_Loads_q.in(Nt_critical) == 0);\n        \n        /**  GENERATOR INVESTMENT **/\n        \n        /*  On/Off status */\n        Constraint<> OnOff_maxP_c(\"OnOff_maxP_c\");\n        OnOff_maxP_c += Pg_c_.in(pot_Gt_c) - pg_max.in(pot_Gt_c)*w_g.in(pot_Gt_c);\n        ODO->add(OnOff_maxP_c.in(pot_Gt_c) <= 0);\n\n        Constraint<> OnOff_maxQ_c(\"OnOff_maxQ_c\");\n        OnOff_maxQ_c += Qg_c.in(pot_Gt_c) - qg_max.in(pot_Gt_c)*w_g.in(pot_Gt_c);\n        ODO->add(OnOff_maxQ_c.in(pot_Gt_c) <= 0);\n\n        Constraint<> OnOff_minQ_c(\"OnOff_minQ_c\");\n        OnOff_minQ_c += Qg_c.in(pot_Gt_c) - qg_min.in(pot_Gt_c)*w_g.in(pot_Gt_c);\n        ODO->add(OnOff_minQ_c.in(pot_Gt_c) >= 0);\n\n        /**  PV **/\n\n        auto pot_Bt_c = indices(T_c,pot_B_ph);\n        auto pot_PVt_c = indices(T_c,pot_PV_ph);\n        auto pot_Windt_c = indices(T_c,pot_Wind_ph);\n        Bt_c = indices(T_c,B_ph);\n\n        /*  Max Cap on Potential PV */\n        Constraint<> MaxCapPV_c(\"MaxCapPV_c\");\n        MaxCapPV_c += Pv_c.in(pot_PVt_c) - Pv_cap.in(pot_PVt_c)*pv_out.in(pot_PVt_c);\n        ODO->add(MaxCapPV_c.in(pot_PVt_c) <= 0);\n\n        auto exist_Bt_c = indices(T_c,exist_B_ph);\n        auto exist_PVt_c = indices(T_c,exist_PV_ph);\n        auto exist_Windt_c = indices(T_c,exist_Wind_ph);\n\n        /*  Existing PV */\n        Constraint<> existPV_c(\"existPV_c\");\n        existPV_c += Pv_c.in(exist_PVt_c) - pv_max.in(exist_PVt_c)*pv_out.in(exist_PVt_c);\n        ODO->add(existPV_c.in(exist_PVt_c) <= 0);\n\n\n        /**  BATTERIES **/\n\n        /*  Apparent Power Limit on Potential Batteries */\n        Constraint<> Apparent_Limit_Batt_Pot_c(\"Apparent_Limit_Batt_Potential_c\");\n        Apparent_Limit_Batt_Pot_c += pow(Pb_c.in(pot_Bt_c), 2) + pow(Qb_c.in(pot_Bt_c), 2);\n        Apparent_Limit_Batt_Pot_c -= pow(w_b.in(pot_Bt_c),2)*pow(pb_max.in(pot_Bt_c), 2);\n        ODO->add(Apparent_Limit_Batt_Pot_c.in(pot_Bt_c) <= 0);\n\n        /*  Apparent Power Limit on Existing Batteries */\n        Constraint<> Apparent_Limit_Batt_c(\"Apparent_Limit_Batt_Existing_c\");\n        Apparent_Limit_Batt_c += pow(Pb_c.in(exist_Bt_c), 2) + pow(Qb_c.in(exist_Bt_c), 2);\n        Apparent_Limit_Batt_c -= pow(pb_max.in(exist_Bt_c), 2);\n        ODO->add(Apparent_Limit_Batt_c.in(exist_Bt_c) <= 0);\n\n\n        /*  State Of Charge */\n        auto T1_c = T_c.exclude_first_each(scenarios);/**< Excluding first time step in each contingency/resiliency scenario */\n        auto Tn_c = T_c.exclude_last_each(scenarios);/**< Excluding last time step in each contingency/resiliency scenario */\n        auto Bt1_c = indices(T1_c,B_ph);\n        auto Btn_c = indices(Tn_c,B_ph);\n        Constraint<> State_Of_Charge_c(\"State_Of_Charge_c\");\n        State_Of_Charge_c = Sc_c.in(Bt1_c) - Sc_c.in(Btn_c) + Pb_c_.in(Bt1_c);\n        ODO->add(State_Of_Charge_c.in(Bt1_c) == 0);\n\n        /*  State Of Charge at t0 for each contingency */\n        auto T0_c = T_c.first_each(scenarios);\n        auto Bat0_c = indices(T0_c,B_ph);\n        Constraint<> State_Of_Charge0_c(\"State_Of_Charge0_c\");\n        State_Of_Charge0_c = Sc_c.in(Bat0_c);\n        ODO->add(State_Of_Charge0_c.in(Bat0_c) == 0);\n        Constraint<> Pb0_c(\"Pb0_c\");\n        Pb0_c = Pb_c_.in(Bat0_c);\n        ODO->add(Pb0_c.in(Bat0_c) == 0);\n\n        /*  EFFICIENCIES */\n        Constraint<> DieselEff_c(\"DieselEff_c\");\n        DieselEff_c += Pg_c - gen_eff.in(Gt_c)*Pg_c_;\n        ODO->add(DieselEff_c.in(Gt_c) == 0);\n\n        auto exist_batt_eff_c = indices(exist_Bt_c,_eff_pieces);\n        auto pot_batt_eff_c = indices(pot_Bt_c,_eff_pieces);\n        Constraint<> EfficiencyExist_c(\"BatteryEfficiencyExisting_c\");\n        EfficiencyExist_c += Pb_c.in(exist_batt_eff_c)  - eff_a.in(exist_batt_eff_c)*Pb_c_.in(exist_batt_eff_c) - eff_b.in(exist_batt_eff_c);\n        ODO->add(EfficiencyExist_c.in(exist_batt_eff_c) <= 0);\n\n        Constraint<> EfficiencyPot_c(\"BatteryEfficiencyPotential_c\");\n        EfficiencyPot_c += Pb_c.in(pot_batt_eff_c)  - eff_a.in(pot_batt_eff_c)*Pb_c_.in(pot_batt_eff_c) - eff_b.in(pot_batt_eff_c)*w_b.in(pot_batt_eff_c);\n        ODO->add(EfficiencyPot_c.in(pot_batt_eff_c) <= 0);\n    }\n    \n    return ODO;\n}\n\n\n\n\nint PowerNet::readgrid(const string& fname, bool reverse_arcs) {\n    double pi = 4.*atan(1.);\n    string name;\n    double kvb = 0;\n//    int id = 0;\n    unsigned index = 0;\n    cout << \"Loading file \" << fname << endl;\n    ifstream file(fname.c_str(), std::ifstream::in);\n    if(!file.is_open()) {\n        throw invalid_argument(\"Could not open file \" + fname);\n    }\n    string word;\n    while (word.compare(\"function\")) {\n        file >> word;\n    }\n\n    file.ignore(6);\n    file >> word;\n    _name = word;\n\n//  cout << _name << endl;\n    while (word.compare(\"mpc.baseMVA\")) {\n        file >> word;\n    }\n\n    file.ignore(3);\n    getline(file, word,';');\n    bMVA = atoi(word.c_str());\n    /* Nodes data */\n    while (word.compare(\"mpc.bus\")) {\n        file >> word;\n    }\n\n    getline(file, word);\n    Bus* bus = NULL;\n//    Bus* bus_clone= NULL;\n    file >> word;\n    int status;\n    double total_p_load = 0, total_q_load = 0;\n    while(word.compare(\"];\")) {\n        name = word.c_str();\n        file >> ws >> word;\n        status = atoi(word.c_str());\n        if (status==3) {\n            ref_bus = name;\n            DebugOn(\"Ref bus = \" << ref_bus << endl);\n        }\n        file >> ws >> word;\n        pl.add_val(name,atof(word.c_str())/bMVA);\n        file >> word;\n        ql.add_val(name,atof(word.c_str())/bMVA);\n        file >> word;\n        gs_.add_val(name,atof(word.c_str())/bMVA);\n        file >> word;\n        bs_.add_val(name,atof(word.c_str())/bMVA);\n        file >> ws >> word >> ws >> word;\n        v_s.add_val(name,atof(word.c_str()));\n        file >> ws >> word >> ws >> word;\n        kvb = atof(word.c_str());\n        file >> ws >> word >> ws >> word;\n        v_max.add_val(name,atof(word.c_str()));\n        getline(file, word,';');\n        v_min.add_val(name,atof(word.c_str()));\n        w_min.add_val(name,pow(v_min.eval(), 2));\n        w_max.add_val(name,pow(v_max.eval(), 2));\n        // single phase\n\n        bus = new Bus(name, pl.eval(), ql.eval(), gs_.eval(), bs_.eval(), v_min.eval(), v_max.eval(), kvb, 1);\n//        bus_clone = new Bus(name, pl.eval(), ql.eval(), gs.eval(), bs.eval(), v_min.eval(), v_max.eval(), kvb, 1);\n        total_p_load += pl.eval();\n        total_q_load += ql.eval();\n        bus->vs = v_s.eval();\n        if (status>=4) {\n            bus->_active = false;\n//            bus_clone->_active = false;\n        }\n\n        this->Net::add_node(bus);\n        if (status>=4) {\n            DebugOn(\"INACTIVE NODE!\\n\" << name << endl);\n        }\n        file >> word;\n    }\n//    ref_bus = nodes.front()->_name;\n    file.seekg (0, file.beg);\n\n\n    /* Generator data */\n    while (word.compare(\"mpc.gen\")) {\n        file >> word;\n    }\n//    double qmin = 0, qmax = 0, pmin = 0, pmax = 0, ps = 0, qs = 0;\n//    int status = 0;\n    getline(file, word);\n\n\n    file >> word;\n//    std::vector<bool> gen_status;\n    index = 0;\n    string bus_name;\n    while(word.compare(\"];\")) {\n        bus_name = word.c_str();\n        // name -> node.\n        bus = (Bus*)(Net::get_node(bus_name));\n        name = to_string(index);\n        file >> word;\n        pg_s.add_val(name,atof(word.c_str())/bMVA);\n        file >> word;\n        qg_s.add_val(name,atof(word.c_str())/bMVA);\n        file >> word;\n        qg_max.add_val(name,atof(word.c_str())/bMVA);\n        file >> word;\n        qg_min.add_val(name,atof(word.c_str())/bMVA);\n\n        file >> ws >> word >> ws >> word >> ws >> word;\n        status = atoi(word.c_str());\n        file >> word;\n        pg_max.add_val(name,atof(word.c_str())/bMVA);\n\n        \n        file >> word;\n        pg_min.add_val(name,atof(word.c_str())/bMVA);\n        getline(file, word,'\\n');\n//        gen_status.push_back(status==1);\n\n\n        bus->_has_gen = true;\n        /** generator name, ID */\n        Gen* g = new Gen(bus, name, pg_min.eval(index), pg_max.eval(index), qg_min.eval(index), qg_max.eval(index));\n        g->_id = index;\n        g->_ps = pg_s.eval();\n        g->_qs = qg_s.eval();\n        \n        gens.push_back(g);\n        bus->_gen.push_back(g);\n        if(status!=1 || !bus->_active) {\n            DebugOff(\"INACTIVE GENERATOR!\\n\" << name << endl);\n            g->_active = false;\n        }\n        index++;\n//        getline(file, word);\n        file >> word;\n    }\n\n\n    file.seekg (0, file.beg);\n\n    /* Generator costs */\n    while (word.compare(\"mpc.gencost\")) {\n        file >> word;\n    }\n//    double c0 = 0, c1 = 0,c2 = 0;\n    getline(file, word);\n\n    int gen_counter = 0;\n    for (size_t i = 0; i < gens.size(); ++i) {\n        file >> ws >> word >> ws >> word >> ws >> word >> ws >> word >> ws >> word;\n        c2.add_val(to_string(i),atof(word.c_str())*pow(bMVA,2));\n        file >> word;\n        c1.add_val(to_string(i),atof(word.c_str())*bMVA);\n        file >> word;\n        c0.add_val(to_string(i),atof(word.c_str()));\n//        c2(i) = atof(word.c_str())*pow(bMVA,2);\n//        file >> word;\n//        c1(i) = atof(word.c_str())*bMVA;\n//        file >> word;\n//        c0(i) = atof(word.c_str());\n        gens[gen_counter++]->set_costs(c0.eval(), c1.eval(), c2.eval());\n        getline(file, word);\n    }\n    file.seekg (0, file.beg);\n\n    /* Lines data */\n    while (word.compare(\"mpc.branch\")) {\n        file >> word;\n    }\n    getline(file, word);\n    double res = 0;\n    set<string> bus_pair_names;\n    Line* arc = NULL;\n    string src,dest,key;\n    file >> word;\n    index = 0;\n    bool reversed = false;\n    while(word.compare(\"];\")) {\n        src = word;\n        file >> dest;\n        key = dest+\",\"+src;//Taking care of reversed direction arcs\n        reversed = false;\n//        if(get_node(src)->_id > get_node(dest)->_id) {//Reverse arc direction\n        if((reverse_arcs && get_node(src)->_id > get_node(dest)->_id) || arcID.find(key)!=arcID.end()) {//Reverse arc direction\n            Warning(\"Adding arc linking \" +src+\" and \"+dest);\n            Warning(\" with reversed direction, reversing source and destination.\\n\");\n            reversed = true;\n            key = src;\n            src = dest;\n            dest = key;\n        }\n        \n        arc = new Line(to_string(index) + \",\" + src + \",\" + dest); // Name of lines\n        arc->_id = index++;\n        arc->_src = get_node(src);\n        arc->_dest= get_node(dest);\n        \n        file >> word;\n        arc->r = atof(word.c_str());\n        file >> word;\n        arc->x = atof(word.c_str());\n        res = pow(arc->r,2) + pow(arc->x,2);\n        \n        if (res==0) {\n            cerr << \" line with r = x = 0\" << endl;\n            exit(-1);\n        }\n        // define g and b for each conductor.\n        arc->g = arc->r/res;\n        arc->b = -arc->x/res;\n        file >> word;\n        arc->ch = atof(word.c_str());\n        file >> word;\n        arc->limit = atof(word.c_str())/bMVA;\n        \n        // skip rate A rate B rate C.\n        file >> ws >> word >> ws >> word >> ws >> word;\n        if(atof(word.c_str()) == 0)\n            arc->tr = 1.0;\n        else\n            arc->tr = atof(word.c_str());\n        file >> ws >> word;\n        arc->as = (atof(word.c_str())*pi)/180.;\n        file >> ws >> word;\n        \n        \n        \n        arc->status = atoi(word.c_str());\n        file >> ws >> word;\n        \n        arc->tbound.min = atof(word.c_str())*pi/180.;\n        //        arc->tbound.min = -30*pi/180;\n        m_theta_lb += arc->tbound.min;\n        file >>  ws >>word;\n        \n        arc->tbound.max = atof(word.c_str())*pi/180.;\n        if (arc->tbound.min==0 && arc->tbound.max==0) {\n            DebugOn(\"Angle bounds are equal to zero. Setting them to -+60\");\n            arc->tbound.min = -60.*pi/180.;\n            arc->tbound.max = 60.*pi/180.;\n            \n        }\n        if (reversed && reverse_arcs) {\n            arc->g /= pow(arc->tr,2);\n            arc->b /= pow(arc->tr,2);\n            arc->ch /= pow(arc->tr,2);\n            arc->tr = 1./arc->tr;\n            arc->as *= -1.;\n            auto temp = arc->tbound.max;\n            arc->tbound.max = -1.*arc->tbound.min;\n            arc->tbound.min = -1.*temp;\n        }\n        arc->cc = arc->tr*cos(arc->as); // Rectangular values for transformer phase shifters\n        arc->dd = arc->tr*sin(arc->as);\n        //        arc->tbound.max = 30*pi/180;\n        m_theta_ub += arc->tbound.max;\n        \n        Bus* bus_s = (Bus*)(arc->_src);\n        Bus* bus_d = (Bus*)(arc->_dest);\n        \n        arc->smax = gravity::max(\n                        pow(bus_s->vbound.max,2)*(arc->g*arc->g + arc->b*arc->b)*(pow(bus_s->vbound.max,2) + pow(bus_d->vbound.max,2)),\n                        pow(bus_d->vbound.max,2)*(arc->g*arc->g+arc->b*arc->b)*(pow(bus_d->vbound.max,2) + pow(bus_s->vbound.max,2))\n                        );\n        name = arc->_name;\n        g.add_val(name,arc->g);\n        b.add_val(name,arc->b);\n        tr.add_val(name,arc->tr);\n        as.add_val(name,arc->as);\n        //(g+g_fr)/tm^2\n        g_ff.add_val(name,arc->g/(pow(arc->cc, 2) + pow(arc->dd, 2)));\n        g_ft.add_val(name,(-arc->g*arc->cc + arc->b*arc->dd)/(pow(arc->cc, 2) + pow(arc->dd, 2)));\n        \n        g_tt.add_val(name,arc->g);\n        g_tf.add_val(name,(-arc->g*arc->cc - arc->b*arc->dd)/(pow(arc->cc, 2) + pow(arc->dd, 2)));\n        \n        \n        b_ff.add_val(name,(arc->ch*0.5 + arc->b)/(pow(arc->cc, 2) + pow(arc->dd, 2)));\n        b_ft.add_val(name,(-arc->b*arc->cc - arc->g*arc->dd)/(pow(arc->cc, 2) + pow(arc->dd, 2)));\n        \n        b_tt.add_val(name,(arc->ch*0.5 + arc->b));\n        b_tf.add_val(name,(-arc->b*arc->cc + arc->g*arc->dd)/(pow(arc->cc, 2) + pow(arc->dd, 2)));\n        \n        ch.add_val(name,arc->ch);\n//        S_max.add_val(name,gravity::min(arc->limit,max(2.*total_p_load, 2.*total_q_load)));\n        S_max.add_val(name,arc->limit);\n        \n        \n        if(arc->status != 1 || !bus_s->_active || !bus_d->_active) {\n            arc->_active = false;\n            DebugOn(\"INACTIVE ARC!\\n\" << arc->_name << endl);\n        }\n        arc->connect();\n        add_arc(arc);\n        /* Switching to bus_pairs keys */\n        name = bus_s->_name + \",\" + bus_d->_name;\n        if (arc->_active && bus_pair_names.count(name)==0) {\n//            _bus_pairs._keys.push_back(new index_pair(index_(bus_s->_name), index_(bus_d->_name), arc->_active));\n            bus_pair_names.insert(name);\n        }\n        if (!arc->_parallel) {\n            th_min.add_val(name,arc->tbound.min);\n            th_max.add_val(name,arc->tbound.max);\n            tan_th_min.add_val(name,tan(arc->tbound.min));\n            tan_th_max.add_val(name,tan(arc->tbound.max));\n            \n        }\n        else {\n            th_min.add_val(name,gravity::max(th_min.eval(name), arc->tbound.min));\n            th_max.add_val(name,gravity::min(th_max.eval(name), arc->tbound.max));\n            tan_th_min.add_val(name,tan(th_min.eval(name)));\n            tan_th_max.add_val(name,tan(th_max.eval(name)));\n        }\n        if (arc->tbound.min >= 0) {\n            wr_max.add_val(name,bus_s->vbound.max*bus_d->vbound.max*cos(th_min.eval(name)));\n            wr_min.add_val(name,bus_s->vbound.min*bus_d->vbound.min*cos(th_max.eval(name)));\n            wi_max.add_val(name,bus_s->vbound.max*bus_d->vbound.max*sin(th_max.eval(name)));\n            wi_min.add_val(name,bus_s->vbound.min*bus_d->vbound.min*sin(th_min.eval(name)));\n        };\n        if (arc->tbound.max <= 0) {\n            wr_max.add_val(name,bus_s->vbound.max*bus_d->vbound.max*cos(th_max.eval(name)));\n            wr_min.add_val(name,bus_s->vbound.min*bus_d->vbound.min*cos(th_min.eval(name)));\n            wi_max.add_val(name,bus_s->vbound.min*bus_d->vbound.min*sin(th_max.eval(name)));\n            wi_min.add_val(name,bus_s->vbound.max*bus_d->vbound.max*sin(th_min.eval(name)));\n        }\n        if (arc->tbound.min < 0 && arc->tbound.max > 0) {\n            wr_max.add_val(name,bus_s->vbound.max*bus_d->vbound.max);\n            wr_min.add_val(name,bus_s->vbound.min*bus_d->vbound.min*gravity::min(cos(th_min.eval(name)), cos(th_max.eval(name))));\n            wi_max.add_val(name,bus_s->vbound.max*bus_d->vbound.max*sin(th_max.eval(name)));\n            wi_min.add_val(name,bus_s->vbound.max*bus_d->vbound.max*sin(th_min.eval(name)));\n        }\n        cphi.add_val(name, cos(0.5*(arc->tbound.min+arc->tbound.max)));\n        sphi.add_val(name, sin(0.5*(arc->tbound.min+arc->tbound.max)));\n        cos_d.add_val(name, cos(0.5*(arc->tbound.max-arc->tbound.min)));\n        getline(file, word,'\\n');\n        file >> word;\n    }\n    DebugOff(ch.to_str(true) << endl);\n    DebugOff(as.to_str(true) << endl);\n    DebugOff(tr.to_str(true) << endl);\n    \n    file.close();\n//    if (nodes.size()>1000) {\n//        add_3d_nlin = false;\n//    }\n    return 0;\n}\n\n/* Create imaginary lines, fill bus_pairs_chord, set lower and upper bounds */\nvoid PowerNet::update_net(){\n    string name;\n    double cos_max_, cos_min_, sin_max_, sin_min_;\n    double wr_max_, wr_min_, wi_max_, wi_min_, w_max_, w_min_;\n    Node *src, *dest, *n;\n    Arc *new_arc;\n    int fixed = 1, id_sorted = 0; //id of the current bag in bags_sorted\n    Arc *a12, *a13, *a32;\n    std::vector<std::vector<Node*>> bags_sorted;\n\n    // bags are cliques in the chordal completion graph\n    for(auto& b: _bags){\n        for(int i = 0; i < b.size()-1; i++) {\n            for(int j = i+1; j < b.size(); j++) {\n                Arc* a = get_arc(b[i]->_name,b[j]->_name);\n                if (a==nullptr) {\n                    src = get_node(b[i]->_name);\n                    dest = get_node(b[j]->_name);\n                    new_arc = new Line(to_string((int) arcs.size() + 1));\n                    new_arc->_id = arcs.size();\n                    new_arc->_src = src;\n                    new_arc->_dest = dest;\n                    new_arc->_active = false;\n                    new_arc->_imaginary = true;\n                    new_arc->_free = true;\n                    new_arc->connect();\n                    add_undirected_arc(new_arc);\n                }\n            }\n        }\n    }\n\n    while (fixed != 0) {\n        fixed = 0;\n        DebugOff(\"\\nNew iteration\");\n        for(auto b_it = _bags.begin(); b_it != _bags.end();) {\n            std::vector<Node*> b = *b_it;\n            if(b.size() == 3) {\n                DebugOff(\"\\nBag: \" << b[0]->_name << \", \" << b[1]->_name << \", \" << b[2]->_name);\n                a12 = get_arc(b[0], b[1]);\n                a13 = get_arc(b[0], b[2]);\n                a32 = get_arc(b[2], b[1]);\n                if ((a12->_free && a13->_free) || (a12->_free && a32->_free) || (a13->_free && a32->_free) ||\n                    (!a12->_free && !a13->_free && !a32->_free)) { // at least two missing lines or all lines real\n                    ++b_it;\n                    continue;\n                }\n                if (a12->_free) {\n                    a12->_free = false;\n                    DebugOff(\"\\nFixing arc a12 (\" << a12->_src->_name << \", \" << a12->_dest->_name << \"), adding bag #\" << id_sorted);\n                    fixed++;\n                }\n                if (a13->_free) {\n                    a13->_free = false;\n                    DebugOff(\"\\nFixing arc a13 (\" << a13->_src->_name << \", \" << a13->_dest->_name << \"), adding bag #\" << id_sorted);\n                    fixed++;\n                }\n                if (a32->_free) {\n                    a32->_free = false;\n                    DebugOff(\"\\nFixing arc a32 (\" << a32->_src->_name << \", \" << a32->_dest->_name << \"), adding bag #\" << id_sorted);\n                    fixed++;\n                }\n                bags_sorted.push_back(b);\n                _bags.erase(b_it);\n                id_sorted++;\n            }\n            else{ // Bags with size > 3; todo: leave only this as the general case?\n                DebugOff(\"\\nBag with size > 3\");\n\n                for(int i = 0; i < b.size()-1; i++) {\n                    for (int j = i + 1; j < b.size(); j++) {\n                        Arc* a = get_arc(b[i]->_name, b[j]->_name);\n                        if (!a->_free) continue;\n                        n = a->_src;\n                        //by now, all arcs in bags should be created\n                        for (auto n1: b) {\n                            if(n==n1) continue;\n                            Arc* a2 = get_arc(n->_name, n1->_name);\n                            if (a2->_free) continue;\n                            Arc *a1 = get_arc(a->_dest, n1);\n                            if (!a1->_free) {\n                                a->_free = false;\n\n                                vector<Node *> bag;\n                                bag.push_back(get_node(n->_name));\n                                bag.push_back(get_node(a->_dest->_name));\n                                bag.push_back(get_node(n1->_name));\n//                                sort(bag.begin(), bag.end(),\n//                                     [](const Node *a, const Node *b) -> bool { return a->_id < b->_id; });\n\n                                fixed++;\n                                sort(bag.begin(), bag.end(), [](const Node* a, const Node* b) -> bool{return a->_id < b->_id;});\n                                bags_sorted.push_back(bag);\n                                id_sorted++;\n                                DebugOff(\"\\nFixing arc in a larger bag (\" << a->_src->_name << \", \" << a->_dest->_name << \")\");\n                                break;\n                            }\n                        }\n                    } // j\n                } // i\n                ++b_it;\n\n            } // size > 3\n        } // bags loop\n    } // while\n\n    //add all remaining bags to bags_sorted\n    for(auto b_it = _bags.begin(); b_it != _bags.end();) {\n        std::vector<Node*> b = *b_it;\n            if(b.size() >= 2) bags_sorted.push_back(b);\n            _bags.erase(b_it);\n//            id_sorted++;\n    }\n    _bags = bags_sorted;\n\n    for(auto& a: arcs) {\n        if(a->_imaginary) a->_free = true;\n    }\n\n\n    for(auto& k: _bus_pairs._keys){\n        _bus_pairs_chord._keys.push_back(new index_pair(*k));\n    }\n\n    for(auto& a: arcs){\n        if(a->_imaginary){\n            Bus* bus_s = (Bus*)(a->_src);\n            Bus* bus_d = (Bus*)(a->_dest);\n\n            name = bus_s->_name + \",\" + bus_d->_name;\n            _bus_pairs_chord._keys.push_back(new index_pair(index_(bus_s->_name), index_(bus_d->_name)));\n\n            if (m_theta_lb < -3.14 && m_theta_ub > 3.14) {\n                cos_max_ = 1;\n                cos_min_ = -1;\n            } else if (m_theta_lb < 0 && m_theta_ub > 0){\n                cos_max_ = 1;\n                cos_min_ = gravity::min(cos(m_theta_lb), cos(m_theta_ub));\n            } else{\n                cos_max_ = gravity::max(cos(m_theta_lb),cos(m_theta_ub));\n                cos_min_ = gravity::min(cos(m_theta_lb), cos(m_theta_ub));\n            }\n            w_max_ = bus_s->vbound.max*bus_d->vbound.max;\n            w_min_ = bus_s->vbound.min*bus_d->vbound.min;\n\n            wr_max_ = cos_max_*w_max_;\n            if(cos_min_ < 0) wr_min_ = cos_min_*w_max_;\n            else wr_min_ = cos_min_*w_min_;\n\n            if(m_theta_lb < -1.57 && m_theta_ub > 1.57){\n                sin_max_ = 1;\n                sin_min_ = -1;\n            } else{\n                sin_max_ = sin(m_theta_ub);\n                sin_min_ = sin(m_theta_lb);\n            }\n\n            if(sin_max_ > 0) wi_max_ = sin_max_*w_max_;\n            else wi_max_ = sin_max_*w_min_;\n            if(sin_min_ > 0) wi_min_ = sin_min_*w_min_;\n            else wi_min_ = sin_min_*w_max_;\n\n//            cout << \"\\nImaginary line, bounds: (\" << wr_min_ << \",\" << wr_max_ << \"); (\" << wi_min_ << \",\" << wi_max_ << \")\";\n\n            wr_max.add_val(name,wr_max_);\n            wr_min.add_val(name,wr_min_);\n            wi_max.add_val(name,wi_max_);\n            wi_min.add_val(name,wi_min_);\n        }\n    }\n    DebugOff(\"\\nBags sorted: \" << endl);\n    for(auto& b: _bags) {\n        DebugOff(\"bag = {\");\n        for (int i = 0; i < b.size(); i++) {\n            DebugOff(b.at(i)->_name << \" \");\n        }\n        DebugOff(\"}\" << endl);\n        if(add_3d_nlin && b.size()==3){\n            for(int i = 0; i < 2; i++) {\n                for(int j = i+1; j < 3; j++) {\n                    Arc* aij = get_arc(b[i],b[j]);\n                    aij->_free = false;\n                }\n            }\n        }\n    }\n}\n\n\n\nshared_ptr<Model<>> PowerNet::build_SCOPF(PowerModelType pmt, int output, double tol){\n    auto bus_pairs = get_bus_pairs();\n    /** MODEL DECLARATION */\n    shared_ptr<Model<>> SOCPF(new Model<>(\"SCOPF Model\"));\n    /** Variables */\n    /* power generation variables */\n    var<double> Pg(\"Pg\", pg_min, pg_max);\n    var<double> Qg (\"Qg\", qg_min, qg_max);\n    SOCPF->add(Pg.in(gens));\n    SOCPF->add(Qg.in(gens));\n\n\n    /* power flow variables */\n    var<double> Pf_from(\"Pf_from\", -1*S_max,S_max);\n    var<double> Qf_from(\"Qf_from\", -1*S_max,S_max);\n    var<double> Pf_to(\"Pf_to\", -1*S_max,S_max);\n    var<double> Qf_to(\"Qf_to\", -1*S_max,S_max);\n    SOCPF->add(Pf_from.in(arcs));\n    SOCPF->add(Qf_from.in(arcs));\n    SOCPF->add(Pf_to.in(arcs));\n    SOCPF->add(Qf_to.in(arcs));\n\n    /* Real part of Wij = ViVj */\n    var<double>  R_Wij(\"R_Wij\", wr_min, wr_max);\n    /* Imaginary part of Wij = ViVj */\n    var<double>  Im_Wij(\"Im_Wij\", wi_min, wi_max);\n    /* Magnitude of Wii = Vi^2 */\n    var<double>  Wii(\"Wii\", w_min, w_max);\n    SOCPF->add(Wii.in(nodes));\n    SOCPF->add(R_Wij.in(bus_pairs));\n    SOCPF->add(Im_Wij.in(bus_pairs));\n\n    /* Initialize variables */\n    R_Wij.initialize_all(1.0);\n    Wii.initialize_all(1.001);\n    \n    /** Sets */\n    auto gens = gens_per_node();\n    auto out_arcs = out_arcs_per_node();\n    auto in_arcs = in_arcs_per_node();\n\n    /**  Objective */\n    auto obj = c1.tr()*Pg + c2.tr()*pow(Pg,2) + sum(c0);\n    SOCPF->min(obj);\n\n    /** Constraints */\n    /* Second-order cone constraints */\n    Constraint<> SOC(\"SOC\");\n    SOC = pow(R_Wij, 2) + pow(Im_Wij, 2) - Wii.from(bus_pairs)*Wii.to(bus_pairs);\n    SOCPF->add(SOC.in(bus_pairs) <= 0);\n\n    /* Flow conservation */\n    Constraint<> KCL_P(\"KCL_P\");\n    KCL_P  = sum(Pf_from, out_arcs) + sum(Pf_to, in_arcs) + pl - sum(Pg, gens) + gs_*Wii;\n    SOCPF->add(KCL_P.in(nodes) == 0);\n\n    Constraint<> KCL_Q(\"KCL_Q\");\n    KCL_Q  = sum(Qf_from, out_arcs) + sum(Qf_to, in_arcs) + ql - sum(Qg, gens) - bs_*Wii;\n    SOCPF->add(KCL_Q.in(nodes) == 0);\n\n    /* AC Power Flow */\n    Constraint<> Flow_P_From(\"Flow_P_From\");\n    Flow_P_From = Pf_from - (g_ff*Wii.from(arcs) + g_ft*R_Wij + b_ft*Im_Wij);\n    SOCPF->add(Flow_P_From.in(arcs) == 0);\n\n    Constraint<> Flow_P_To(\"Flow_P_To\");\n    Flow_P_To = Pf_to - (g_tt*Wii.to(arcs) + g_tf*R_Wij - b_tf*Im_Wij);\n    SOCPF->add(Flow_P_To.in(arcs) == 0);\n\n    Constraint<> Flow_Q_From(\"Flow_Q_From\");\n    Flow_Q_From = Qf_from - (g_ft*Im_Wij - b_ff*Wii.from(arcs) - b_ft*R_Wij);\n    SOCPF->add(Flow_Q_From.in(arcs) == 0);\n\n    Constraint<> Flow_Q_To(\"Flow_Q_To\");\n    Flow_Q_To = Qf_to + (b_tt*Wii.to(arcs) + b_tf*R_Wij + g_tf*Im_Wij);\n    SOCPF->add(Flow_Q_To.in(arcs) == 0);\n\n    /* Phase Angle Bounds constraints */\n    Constraint<> PAD_UB(\"PAD_UB\");\n    PAD_UB = Im_Wij;\n    PAD_UB <= tan_th_max*R_Wij;\n    SOCPF->add(PAD_UB);\n\n    Constraint<> PAD_LB(\"PAD_LB\");\n    PAD_LB =  Im_Wij;\n    PAD_LB >= tan_th_min*R_Wij;\n    SOCPF->add(PAD_LB);\n\n    /* Thermal Limit Constraints */\n    Constraint<> Thermal_Limit_from(\"Thermal_Limit_from\");\n    Thermal_Limit_from = pow(Pf_from, 2) + pow(Qf_from, 2);\n    Thermal_Limit_from <= pow(S_max,2);\n    SOCPF->add(Thermal_Limit_from);\n\n\n    Constraint<> Thermal_Limit_to(\"Thermal_Limit_to\");\n    Thermal_Limit_to = pow(Pf_to, 2) + pow(Qf_to, 2);\n    Thermal_Limit_to <= pow(S_max,2);\n    SOCPF->add(Thermal_Limit_to);\n\n    /* Lifted Nonlinear Cuts */\n    Constraint<> LNC1(\"LNC1\");\n    LNC1 += (v_min.from(bus_pairs)+v_max.from(bus_pairs))*(v_min.to(bus_pairs)+v_max.to(bus_pairs))*(sphi*Im_Wij + cphi*R_Wij);\n    LNC1 -= v_max.to(bus_pairs)*cos_d*(v_min.to(bus_pairs)+v_max.to(bus_pairs))*Wii.from(bus_pairs);\n    LNC1 -= v_max.from(bus_pairs)*cos_d*(v_min.from(bus_pairs)+v_max.from(bus_pairs))*Wii.to(bus_pairs);\n    LNC1 -= v_max.from(bus_pairs)*v_max.to(bus_pairs)*cos_d*(v_min.from(bus_pairs)*v_min.to(bus_pairs) - v_max.from(bus_pairs)*v_max.to(bus_pairs));\n    SOCPF->add(LNC1.in(bus_pairs) >= 0);\n\n    Constraint<> LNC2(\"LNC2\");\n    LNC2 += (v_min.from(bus_pairs)+v_max.from(bus_pairs))*(v_min.to(bus_pairs)+v_max.to(bus_pairs))*(sphi*Im_Wij + cphi*R_Wij);\n    LNC2 -= v_min.to(bus_pairs)*cos_d*(v_min.to(bus_pairs)+v_max.to(bus_pairs))*Wii.from(bus_pairs);\n    LNC2 -= v_min.from(bus_pairs)*cos_d*(v_min.from(bus_pairs)+v_max.from(bus_pairs))*Wii.to(bus_pairs);\n    LNC2 += v_min.from(bus_pairs)*v_min.to(bus_pairs)*cos_d*(v_min.from(bus_pairs)*v_min.to(bus_pairs) - v_max.from(bus_pairs)*v_max.to(bus_pairs));\n    SOCPF->add(LNC2.in(bus_pairs) >= 0);\n    return SOCPF;\n}\n\n\n\nshared_ptr<Model<>> build_ACOPF(PowerNet& grid, PowerModelType pmt, int output, double tol){\n    /** Sets */\n    auto bus_pairs = grid.get_bus_pairs();\n    auto nodes = indices(grid.nodes);\n    auto arcs = indices(grid.arcs);\n    auto gens = indices(grid.gens);\n    auto gen_nodes = grid.gens_per_node();\n    auto out_arcs = grid.out_arcs_per_node();\n    auto in_arcs = grid.in_arcs_per_node();\n    \n    /* Grid Parameters */\n    auto pg_min = grid.pg_min.in(gens);\n    auto pg_max = grid.pg_max.in(gens);\n    auto qg_min = grid.qg_min.in(gens);\n    auto qg_max = grid.qg_max.in(gens);\n    auto c1 = grid.c1.in(gens);\n    auto c2 = grid.c2.in(gens);\n    auto c0 = grid.c0.in(gens);\n    auto pl = grid.pl.in(nodes);\n    auto ql = grid.ql.in(nodes);\n    auto gs = grid.gs_.in(nodes);\n    auto bs = grid.bs_.in(nodes);\n    auto b = grid.b.in(arcs);\n    auto g = grid.g.in(arcs);\n    auto as = grid.as.in(arcs);\n    auto ch = grid.ch.in(arcs);\n    auto tr = grid.tr.in(arcs);\n    auto th_min = grid.th_min.in(bus_pairs);\n    auto th_max = grid.th_max.in(bus_pairs);\n    auto g_ft = grid.g_ft.in(arcs);\n    auto g_ff = grid.g_ff.in(arcs);\n    auto g_tt = grid.g_tt.in(arcs);\n    auto g_tf = grid.g_tf.in(arcs);\n    auto b_ft = grid.b_ft.in(arcs);\n    auto b_ff = grid.b_ff.in(arcs);\n    auto b_tf = grid.b_tf.in(arcs);\n    auto b_tt = grid.b_tt.in(arcs);\n    auto S_max = grid.S_max.in(arcs);\n    auto v_max = grid.v_max.in(nodes);\n    auto v_min = grid.v_min.in(nodes);\n    auto tan_th_min = grid.tan_th_min.in(bus_pairs);\n    auto tan_th_max = grid.tan_th_max.in(bus_pairs);\n    \n    bool polar = (pmt==ACPOL);\n    if (polar) {\n        DebugOn(\"Using polar model\\n\");\n    }\n    else {\n        DebugOn(\"Using rectangular model\\n\");\n    }\n    auto ACOPF = make_shared<Model<>>(\"AC-OPF Model\");\n    /** Variables */\n    /* Power generation variables */\n    var<> Pg(\"Pg\", pg_min, pg_max);\n    var<> Qg (\"Qg\", qg_min, qg_max);\n    ACOPF->add(Pg.in(gens),Qg.in(gens));\n    //    Pg.copy_vals(grid.pg_s);\n    //    Pg.initialize_av();\n    //    Qg.initialize_uniform();\n    /* Power flow variables */\n    var<> Pf_from(\"Pf_from\", -1.*S_max,S_max);\n    var<> Qf_from(\"Qf_from\", -1.*S_max,S_max);\n    var<> Pf_to(\"Pf_to\", -1.*S_max,S_max);\n    var<> Qf_to(\"Qf_to\", -1.*S_max,S_max);\n    ACOPF->add(Pf_from.in(arcs), Qf_from.in(arcs),Pf_to.in(arcs),Qf_to.in(arcs));\n    \n    /** Voltage related variables */\n    var<> theta(\"theta\");\n    var<> v(\"|V|\", v_min, v_max);\n    var<> vr(\"vr\", -1.*v_max,v_max);\n    var<> vi(\"vi\", -1.*v_max,v_max);\n    \n    var<> v_from, v_to, theta_from, theta_to;\n    var<> vr_from, vr_to, vi_from, vi_to;\n    if (polar) {\n        ACOPF->add(v.in(nodes));\n        ACOPF->add(theta.in(nodes));\n        v.initialize_all(1.0);\n        v_from = v.from(arcs);\n        v_to = v.to(arcs);\n        theta_from = theta.from(arcs);\n        theta_to = theta.to(arcs);\n        \n    }\n    else {\n        ACOPF->add(vr.in(nodes));\n        ACOPF->add(vi.in(nodes));\n        vr.initialize_all(1);\n        vr_from = vr.from(arcs);\n        vr_to = vr.to(arcs);\n        vi_from = vi.from(arcs);\n        vi_to = vi.to(arcs);\n        //        vr.initialize_uniform(0.99,1.01);\n    }\n    \n    /** Construct the objective function */\n    /**  Objective */\n    auto obj = product(c1,Pg) + product(c2,pow(Pg,2)) + sum(c0);\n    ACOPF->min(obj);\n    \n    /** Define constraints */\n    \n    /* REF BUS */\n    Constraint<> Ref_Bus(\"Ref_Bus\");\n    if (polar) {\n        Ref_Bus = theta(grid.ref_bus);\n    }\n    else {\n        Ref_Bus = vi(grid.ref_bus);\n    }\n    ACOPF->add(Ref_Bus == 0);\n    \n    /** KCL Flow conservation */\n    Constraint<> KCL_P(\"KCL_P\");\n    Constraint<> KCL_Q(\"KCL_Q\");\n    KCL_P  = sum(Pf_from, out_arcs) + sum(Pf_to, in_arcs) + pl - sum(Pg, gen_nodes);\n    KCL_Q  = sum(Qf_from, out_arcs) + sum(Qf_to, in_arcs) + ql - sum(Qg, gen_nodes);\n    /* Shunts */\n    if (polar) {\n        KCL_P +=  gs*pow(v,2);\n        KCL_Q -=  bs*pow(v,2);\n    }\n    else {\n        KCL_P +=  gs*(pow(vr,2)+pow(vi,2));\n        KCL_Q -=  bs*(pow(vr,2)+pow(vi,2));\n    }\n    ACOPF->add(KCL_P.in(nodes) == 0);\n    ACOPF->add(KCL_Q.in(nodes) == 0);\n    \n    /** AC Power Flows */\n    /** TODO write the constraints in Complex form */\n    Constraint<> Flow_P_From(\"Flow_P_From\");\n    Flow_P_From += Pf_from;\n    if (polar) {\n        Flow_P_From -= g/pow(tr,2)*pow(v_from,2);\n        Flow_P_From += g/tr*(v_from*v_to*cos(theta_from - theta_to - as));\n        Flow_P_From += b/tr*(v_from*v_to*sin(theta_from - theta_to - as));\n    }\n    else {\n        Flow_P_From -= g_ff*(pow(vr_from, 2) + pow(vi_from, 2));\n        Flow_P_From -= g_ft*(vr_from*vr_to + vi_from*vi_to);\n        Flow_P_From -= b_ft*(vi_from*vr_to - vr_from*vi_to);\n    }\n    ACOPF->add(Flow_P_From.in(arcs)==0);\n    \n    Constraint<> Flow_P_To(\"Flow_P_To\");\n    Flow_P_To += Pf_to;\n    if (polar) {\n        Flow_P_To -= g*pow(v_to, 2);\n        Flow_P_To += g/tr*(v_from*v_to*cos(theta_to - theta_from + as));\n        Flow_P_To += b/tr*(v_from*v_to*sin(theta_to - theta_from + as));\n    }\n    else {\n        Flow_P_To -= g_tt*(pow(vr_to, 2) + pow(vi_to, 2));\n        Flow_P_To -= g_tf*(vr_from*vr_to + vi_from*vi_to);\n        Flow_P_To -= b_tf*(vi_to*vr_from - vr_to*vi_from);\n    }\n    ACOPF->add(Flow_P_To.in(arcs)==0);\n    \n    Constraint<> Flow_Q_From(\"Flow_Q_From\");\n    Flow_Q_From += Qf_from;\n    if (polar) {\n        Flow_Q_From += (0.5*ch+b)/pow(tr,2)*pow(v_from,2);\n        Flow_Q_From -= b/tr*(v_from*v_to*cos(theta_from - theta_to - as));\n        Flow_Q_From += g/tr*(v_from*v_to*sin(theta_from - theta_to - as));\n    }\n    else {\n        Flow_Q_From += b_ff*(pow(vr_from, 2) + pow(vi_from, 2));\n        Flow_Q_From += b_ft*(vr_from*vr_to + vi_from*vi_to);\n        Flow_Q_From -= g_ft*(vi_from*vr_to - vr_from*vi_to);\n    }\n    ACOPF->add(Flow_Q_From.in(arcs)==0);\n    \n    Constraint<> Flow_Q_To(\"Flow_Q_To\");\n    Flow_Q_To += Qf_to;\n    if (polar) {\n        Flow_Q_To += (0.5*ch+b)*pow(v_to,2);\n        Flow_Q_To -= b/tr*(v_from*v_to*cos(theta_to - theta_from + as));\n        Flow_Q_To += g/tr*(v_from*v_to*sin(theta_to - theta_from + as));\n    }\n    else {\n        Flow_Q_To += b_tt*(pow(vr_to, 2) + pow(vi_to, 2));\n        Flow_Q_To += b_tf*(vr_from*vr_to + vi_from*vi_to);\n        Flow_Q_To -= g_tf*(vi_to*vr_from - vr_to*vi_from);\n    }\n    ACOPF->add(Flow_Q_To.in(arcs)==0);\n    \n    /** AC voltage limit constraints. */\n    if (!polar) {\n        Constraint<> Vol_limit_UB(\"Vol_limit_UB\");\n        Vol_limit_UB = pow(vr, 2) + pow(vi, 2);\n        Vol_limit_UB -= pow(v_max, 2);\n        ACOPF->add(Vol_limit_UB.in(nodes) <= 0);\n        \n        Constraint<> Vol_limit_LB(\"Vol_limit_LB\");\n        Vol_limit_LB = pow(vr, 2) + pow(vi, 2);\n        Vol_limit_LB -= pow(v_min,2);\n        ACOPF->add(Vol_limit_LB.in(nodes) >= 0);\n    }\n    \n    \n    /* Phase Angle Bounds constraints */\n    Constraint<> PAD_UB(\"PAD_UB\");\n    Constraint<> PAD_LB(\"PAD_LB\");\n    if (polar) {\n        PAD_UB = theta.from(bus_pairs) - theta.to(bus_pairs);\n        PAD_UB -= th_max;\n        PAD_LB = theta.from(bus_pairs) - theta.to(bus_pairs);\n        PAD_LB -= th_min;\n    }\n    else {\n        DebugOff(\"Number of bus_pairs = \" << bus_pairs.size() << endl);\n        PAD_UB = vi.from(bus_pairs)*vr.to(bus_pairs) - vr.from(bus_pairs)*vi.to(bus_pairs);\n        PAD_UB -= tan_th_max*(vr.from(bus_pairs)*vr.to(bus_pairs) + vi.from(bus_pairs)*vi.to(bus_pairs));\n        \n        PAD_LB = vi.from(bus_pairs)*vr.to(bus_pairs) - vr.from(bus_pairs)*vi.to(bus_pairs);\n        PAD_LB -= tan_th_min*(vr.from(bus_pairs)*vr.to(bus_pairs) + vi.from(bus_pairs)*vi.to(bus_pairs));\n    }\n    ACOPF->add(PAD_UB.in(bus_pairs) <= 0);\n    ACOPF->add(PAD_LB.in(bus_pairs) >= 0);\n    \n    \n    /*  Thermal Limit Constraints */\n    Constraint<> Thermal_Limit_from(\"Thermal_Limit_from\");\n    Thermal_Limit_from += pow(Pf_from, 2) + pow(Qf_from, 2);\n    Thermal_Limit_from -= pow(S_max, 2);\n    ACOPF->add(Thermal_Limit_from.in(arcs) <= 0);\n    \n    Constraint<> Thermal_Limit_to(\"Thermal_Limit_to\");\n    Thermal_Limit_to += pow(Pf_to, 2) + pow(Qf_to, 2);\n    Thermal_Limit_to -= pow(S_max,2);\n    ACOPF->add(Thermal_Limit_to.in(arcs) <= 0);\n    return ACOPF;\n}\n\n\n\n/** Return the vector of arcs of the chordal completion ignoring parallel lines **/\nindices PowerNet::get_bus_pairs_chord(){\n    set<pair<Node*,Node*>> unique_pairs;\n    indices bpairs(\"bus_pairs\");\n    for (auto a: arcs) {\n        if (!a->_parallel) {\n            unique_pairs.insert({a->_src,a->_dest});\n            bpairs.insert(a->_src->_name+\",\"+a->_dest->_name);\n        }\n    }\n    string key;\n    double cos_max_, cos_min_, sin_max_, sin_min_;\n    double wr_max_, wr_min_, wi_max_, wi_min_, w_max_, w_min_;\n    if (m_theta_lb < -3.14 && m_theta_ub > 3.14) {\n        cos_max_ = 1;\n        cos_min_ = -1;\n    } else if (m_theta_lb < 0 && m_theta_ub > 0){\n        cos_max_ = 1;\n        cos_min_ = gravity::min(cos(m_theta_lb), cos(m_theta_ub));\n    } else{\n        cos_max_ = gravity::max(cos(m_theta_lb),cos(m_theta_ub));\n        cos_min_ = gravity::min(cos(m_theta_lb), cos(m_theta_ub));\n    }\n    if(m_theta_lb < -1.57 && m_theta_ub > 1.57){\n        sin_max_ = 1;\n        sin_min_ = -1;\n    } else{\n        sin_max_ = sin(m_theta_ub);\n        sin_min_ = sin(m_theta_lb);\n    }\n    for (auto &bag: _bags) {\n        for (size_t i = 0; i< bag.size()-1; i++) {\n            if (unique_pairs.insert({bag[i],bag[i+1]}).second) {\n                auto bus_s = (Bus*)bag[i];\n                auto bus_d = (Bus*)bag[i+1];\n                w_max_ = bus_s->vbound.max*bus_d->vbound.max;\n                w_min_ = bus_s->vbound.min*bus_d->vbound.min;\n                wr_max_ = cos_max_*w_max_;\n                if(cos_min_ < 0) wr_min_ = cos_min_*w_max_;\n                else wr_min_ = cos_min_*w_min_;\n                if(sin_max_ > 0) wi_max_ = sin_max_*w_max_;\n                else wi_max_ = sin_max_*w_min_;\n                if(sin_min_ > 0) wi_min_ = sin_min_*w_min_;\n                else wi_min_ = sin_min_*w_max_;\n                auto name = bag[i]->_name + \",\" + bag[i+1]->_name;\n                wr_max.add_val(name,wr_max_);\n                wr_min.add_val(name,wr_min_);\n                wi_max.add_val(name,wi_max_);\n                wi_min.add_val(name,wi_min_);\n                bpairs.insert(name);\n            }\n        }\n        /* Loop back pair */\n        if (unique_pairs.insert({bag[0],bag[bag.size()-1]}).second) {\n            auto name = bag[0]->_name + \",\" + bag[bag.size()-1]->_name;\n            auto bus_s = (Bus*)bag[0];\n            auto bus_d = (Bus*)bag[bag.size()-1];\n            w_max_ = bus_s->vbound.max*bus_d->vbound.max;\n            w_min_ = bus_s->vbound.min*bus_d->vbound.min;\n            wr_max_ = cos_max_*w_max_;\n            if(cos_min_ < 0) wr_min_ = cos_min_*w_max_;\n            else wr_min_ = cos_min_*w_min_;\n            if(sin_max_ > 0) wi_max_ = sin_max_*w_max_;\n            else wi_max_ = sin_max_*w_min_;\n            if(sin_min_ > 0) wi_min_ = sin_min_*w_min_;\n            else wi_min_ = sin_min_*w_max_;\n            wr_max.add_val(name,wr_max_);\n            wr_min.add_val(name,wr_min_);\n            wi_max.add_val(name,wi_max_);\n            wi_min.add_val(name,wi_min_);\n            bpairs.insert(name);\n        }\n    }\n    return bpairs;\n}\n\ndouble PowerNet::solve_acopf(PowerModelType pmt, int output, double tol){\n    \n    auto ACOPF = build_ACOPF(*this,pmt,output,tol);\n    bool relax;\n    solver<> OPF(ACOPF,ipopt);\n//    auto mipgap = 1e-6;\n    OPF.run(output, tol);\n    return ACOPF->_obj->get_val();\n}\n\n\nvoid PowerNet::fill_wbnds(){\n    double cos_max_, cos_min_, w_max_, w_min_, wr_max_, wr_min_, sin_max_, sin_min_, wi_max_, wi_min_;\n    for(int i = 0; i < nodes.size()-1; i++) {\n        for(int j = i+1; j < nodes.size(); j++) {\n            Bus *bus_s = (Bus *) (nodes[i]);\n            Bus *bus_d = (Bus *) (nodes[j]);\n            \n            if(get_arc(bus_s, bus_d)) continue;\n            \n            string name = bus_s->_name + \",\" + bus_d->_name;\n//            _bus_pairs_chord._keys.push_back(new index_pair(index_(bus_s->_name), index_(bus_d->_name)));\n            \n            if (m_theta_lb < -3.14 && m_theta_ub > 3.14) {\n                cos_max_ = 1;\n                cos_min_ = -1;\n            } else if (m_theta_lb < 0 && m_theta_ub > 0) {\n                cos_max_ = 1;\n                cos_min_ = gravity::min(cos(m_theta_lb), cos(m_theta_ub));\n            } else {\n                cos_max_ = gravity::max(cos(m_theta_lb), cos(m_theta_ub));\n                cos_min_ = gravity::min(cos(m_theta_lb), cos(m_theta_ub));\n            }\n            w_max_ = bus_s->vbound.max * bus_d->vbound.max;\n            w_min_ = bus_s->vbound.min * bus_d->vbound.min;\n            \n            wr_max_ = cos_max_ * w_max_;\n            if (cos_min_ < 0) wr_min_ = cos_min_ * w_max_;\n            else wr_min_ = cos_min_ * w_min_;\n            \n            if (m_theta_lb < -1.57 && m_theta_ub > 1.57) {\n                sin_max_ = 1;\n                sin_min_ = -1;\n            } else {\n                sin_max_ = sin(m_theta_ub);\n                sin_min_ = sin(m_theta_lb);\n            }\n            \n            if (sin_max_ > 0) wi_max_ = sin_max_ * w_max_;\n            else wi_max_ = sin_max_ * w_min_;\n            if (sin_min_ > 0) wi_min_ = sin_min_ * w_min_;\n            else wi_min_ = sin_min_ * w_max_;\n            \n            //            cout << \"\\nImaginary line, bounds: (\" << wr_min_ << \",\" << wr_max_ << \"); (\" << wi_min_ << \",\" << wi_max_ << \")\";\n            \n            wr_max.add_val(name, wr_max_);\n            wr_min.add_val(name, wr_min_);\n            wi_max.add_val(name, wi_max_);\n            wi_min.add_val(name, wi_min_);\n        }\n    }\n}\n\n\n\n", "meta": {"hexsha": "4b248587cc62da579bcffdf64004b81c055eee19", "size": 237026, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/MINLP/Power/PowerNet.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": "examples/MINLP/Power/PowerNet.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": "examples/MINLP/Power/PowerNet.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": 40.0111411209, "max_line_length": 219, "alphanum_fraction": 0.5193101179, "num_tokens": 66765, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6548947290421275, "lm_q2_score": 0.4649015713733885, "lm_q1q2_score": 0.30446158861583456}}
{"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 \"add_stg.hpp\"\n\n#include <numeric>\n\n#include <boost/random/detail/integer_log2.hpp>\n\n#include <core/utils/range_utils.hpp>\n#include <reversible/functions/add_gates.hpp>\n#include <reversible/target_tags.hpp>\n#include <reversible/utils/permutation.hpp>\n\nnamespace cirkit\n{\n\n/******************************************************************************\n * Types                                                                      *\n ******************************************************************************/\n\n/******************************************************************************\n * Private functions                                                          *\n ******************************************************************************/\n\n/******************************************************************************\n * Public functions                                                           *\n ******************************************************************************/\n\nvoid add_stg_as_other( circuit& circ, const tt& func, const tt& func_real, const std::vector<unsigned>& line_map )\n{\n  const auto num_vars = tt_num_vars( func );\n\n  std::vector<kitty::detail::spectral_operation> trans;\n  const auto func_norm = kitty::exact_spectral_canonization( to_kitty( func ),\n                                                             [&trans]( const std::vector<kitty::detail::spectral_operation>& ops ) {\n                                                               std::copy( ops.begin(), ops.end(), std::back_inserter( trans ) );\n                                                             } );\n  const auto func_real_norm = kitty::exact_spectral_canonization( to_kitty( func_real ),\n                                                                  [&trans]( const std::vector<kitty::detail::spectral_operation>& ops ) {\n                                                                    std::copy( ops.rbegin(), ops.rend(), std::back_inserter( trans ) );\n                                                                  } );\n\n  assert( func_norm == func_real_norm );\n\n  std::vector<unsigned> line( num_vars + 1u );\n  if ( !line_map.empty() )\n  {\n    std::copy( line_map.begin(), line_map.end(), line.begin() );\n  }\n  else\n  {\n    std::iota( line.begin(), line.end(), 0u );\n  }\n\n  auto index = circ.num_gates();\n\n  /* we defer the adding of NOT gates to the end, but NOT gates are just stored\n     and used to adjust the polarities of the controls.\n     We also try to merge an output inversion into the control line of a disjoint\n     transformation. */\n  boost::dynamic_bitset<> not_mask( num_vars + 1 );\n\n  /* we also defer adding SWAP gates to the end.  The swaps are stored in a permutation\n     that is used when other gates are added.  Finally the SWAP gates are computed by\n     decomposing the permutation into transpositions. */\n  permutation_t perm = identity_permutation( num_vars );\n\n  for ( const auto& t : trans )\n  {\n    switch ( t._kind )\n    {\n    default:\n      assert( false );\n    case kitty::detail::spectral_operation::kind::permutation:\n      std::swap( perm[boost::integer_log2( t._var1 )], perm[boost::integer_log2( t._var2 )] );\n      break;\n    case kitty::detail::spectral_operation::kind::input_negation:\n      not_mask.flip( perm[boost::integer_log2( t._var1 )] );\n      break;\n    case kitty::detail::spectral_operation::kind::output_negation:\n      not_mask.flip( num_vars );\n      break;\n    case kitty::detail::spectral_operation::kind::spectral_translation:\n    {\n      const auto v1 = perm[boost::integer_log2( t._var1 )];\n      const auto v2 = perm[boost::integer_log2( t._var2 )];\n      insert_cnot( circ, index, make_var( line[v2], !not_mask.test( v2 ) ), line[v1] );\n      insert_cnot( circ, index, make_var( line[v2], !not_mask.test( v2 ) ), line[v1] );\n      ++index;\n    }\n    break;\n    case kitty::detail::spectral_operation::kind::disjoint_translation:\n    { /* disjoint transformation of output */\n      const auto v1 = perm[boost::integer_log2( t._var1 )];\n\n      auto pol = !not_mask.test( v1 );\n      if ( not_mask.test( num_vars ) )\n      {\n        not_mask.reset( num_vars );\n        pol = !pol;\n      }\n      insert_cnot( circ, index, make_var( line[v1], pol ), line[num_vars] );\n    }\n    break;\n    }\n  }\n\n  /* add SWAPS */\n  const auto perm_inv = permutation_invert( perm );\n  for ( const auto& trans : permutation_to_transpositions( perm_inv ) )\n  {\n    insert_fredkin( circ, index, {}, line[trans.first], line[trans.second] );\n    insert_fredkin( circ, index, {}, line[trans.first], line[trans.second] );\n    ++index;\n  }\n\n  /* add inverters from mask */\n  for ( auto i = 0u; i < num_vars; ++i )\n  {\n    if ( not_mask.test( i ) )\n    {\n      insert_not( circ, index, line[perm_inv[i]] );\n      insert_not( circ, index, line[perm_inv[i]] );\n      ++index;\n    }\n  }\n  if ( not_mask.test( num_vars ) )\n  {\n    insert_not( circ, index, line[num_vars] );\n  }\n\n  /* add middle gate */\n  auto& g = circ.insert_gate( index );\n  g.set_type( stg_tag( func_real ) );\n  for ( auto i = 0u; i < num_vars; ++i )\n  {\n    g.add_control( make_var( line[i], true ) );\n  }\n  g.add_target( line[num_vars] );\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": "0cd5ffcd78ceca0ffb6d921ee8713518c6602764", "size": 6525, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "addons/cirkit-addon-reversible/src/reversible/functions/add_stg.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/add_stg.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/add_stg.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": 37.9360465116, "max_line_length": 137, "alphanum_fraction": 0.5644444444, "num_tokens": 1464, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6334102498375401, "lm_q2_score": 0.480478678047907, "lm_q1q2_score": 0.3043401195039358}}
{"text": "/*--------------------------------------------------------------------------*\\\n |                                                                          |\n |  This program is free software; you can redistribute it and/or modify    |\n |  it under the terms of the GNU General Public License as published by    |\n |  the Free Software Foundation; either version 2, or (at your option)     |\n |  any later version.                                                      |\n |                                                                          |\n |  This program is distributed in the hope that it will be useful,         |\n |  but WITHOUT ANY WARRANTY; without even the implied warranty of          |\n |  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the           |\n |  GNU General Public License for more details.                            |\n |                                                                          |\n |  You should have received a copy of the GNU General Public License       |\n |  along with this program; if not, write to the Free Software             |\n |  Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.               |\n |                                                                          |\n |  Copyright (C) 2003                                                      |\n |                                                                          |\n |         , __                 , __                                        |\n |        /|/  \\               /|/  \\                                       |\n |         | __/ _   ,_         | __/ _   ,_                                | \n |         |   \\|/  /  |  |   | |   \\|/  /  |  |   |                        |\n |         |(__/|__/   |_/ \\_/|/|(__/|__/   |_/ \\_/|/                       |\n |                           /|                   /|                        |\n |                           \\|                   \\|                        |\n |                                                                          |\n |      Enrico Bertolazzi                                                   |\n |      Dipartimento di Ingegneria Meccanica e Strutturale                  |\n |      Universita` degli Studi di Trento                                   |\n |      Via Mesiano 77, I-38050 Trento, Italy                               |\n |      email: enrico.bertolazzi@unitn.it                                   |\n |                                                                          |\n\\*--------------------------------------------------------------------------*/\n\n/*\n  http://www.sfu.ca/~ssurjano/optimization.html\n  http://www-optima.amp.i.kyoto-u.ac.jp/member/student/hedar/Hedar_files/TestGO_files/Page364.htm\n*/\n\n#ifndef TESTS_NONLIN_HH\n#define TESTS_NONLIN_HH\n\n#include <iostream>\n#include <sstream>\n\n#include <string>\n#include <vector>\n#include <cstdint>\n#include <cstdio>\n#include <cmath>\n#include <map>\n\n#define DEBUG 1\n#define EIGEN_NO_AUTOMATIC_RESIZING 1\n\n#include <Utils.hh>\n#include <Eigen/Core>\n#include <Eigen/Dense>\n\nnamespace NLproblem {\n\n  typedef std::basic_ostream<char> ostream_type;\n\n  using std::string;\n  using std::map;\n  using std::vector;\n  using std::pair;\n  using std::max;\n  using std::min;\n\n  using std::numeric_limits;\n\n  typedef double  real_type;\n  typedef int32_t integer;\n\n  //! `m_e` the value of \\f$ e \\f$.\n  static real_type const m_e = 2.718281828459045235360287471352662497757;\n\n  //! `m_pi` the value of \\f$ \\pi \\f$.\n  static real_type const m_pi = 3.141592653589793238462643383279502884197;\n\n  //! `m_2pi` the value of \\f$ 2\\pi \\f$.\n  static real_type const m_2pi = 6.283185307179586476925286766559005768394;\n\n  //! `m_pi_2` the value of \\f$ \\pi/2 \\f$.\n  static real_type const m_pi_2 = 1.570796326794896619231321691639751442098;\n\n  //! `m_pi_4` the value of \\f$ \\pi/4 \\f$.\n  static real_type const m_pi_4 = 0.7853981633974483096156608458198757210492;\n\n  //! `m_1_pi` the value of \\f$ 1/\\pi \\f$.\n  static real_type const m_1_pi = 0.3183098861837906715377675267450287240689;\n\n  //! `m_2_pi` the value of \\f$ 2/\\pi \\f$.\n  static real_type const m_2_pi = 0.6366197723675813430755350534900574481378;\n\n  //! `m_sqrtpi` the value of \\f$ \\sqrt{\\pi} \\f$.\n  static real_type const m_sqrtpi = 1.772453850905516027298167483341145182798;\n\n  //! `m_2_sqrtpi` the value of \\f$ 2/\\sqrt{\\pi} \\f$.\n  static real_type const m_2_sqrtpi = 1.128379167095512573896158903121545171688;\n\n  //! `m_sqrt2` the value of \\f$ \\sqrt{2} \\f$.\n  static real_type const m_sqrt2 = 1.414213562373095048801688724209698078570;\n\n  //! `m_1_sqrt2` the value of \\f$ 1/\\sqrt{2} \\f$.\n  static real_type const m_1_sqrt2 = 0.7071067811865475244008443621048490392850;\n\n  static real_type real_max = numeric_limits<real_type>::max();\n\n  typedef Eigen::Matrix<real_type,Eigen::Dynamic,Eigen::Dynamic> dmat_t;\n  typedef Eigen::Matrix<real_type,Eigen::Dynamic,1>              dvec_t;\n  typedef Eigen::Matrix<integer,Eigen::Dynamic,1>               ivec_t;\n\n  class nonlinearBase {\n\n    string const _title;\n    string const _bibtex;\n\n    nonlinearBase();\n    nonlinearBase( nonlinearBase const & );\n    nonlinearBase const & operator = ( nonlinearBase const & );\n\n  protected:\n\n    // U T I L I T Y  F U N C T I O N S -----------------------------------------\n\n    real_type power2( real_type a ) const { return a*a; }\n    real_type power3( real_type a ) const { return a*a*a; }\n    real_type power4( real_type a ) const { real_type a2 = a*a; return a2*a2; }\n    real_type power5( real_type a ) const { real_type a2 = a*a; return a2*a2*a; }\n    real_type power6( real_type a ) const { real_type a2 = a*a; return a2*a2*a2; }\n\n    void\n    checkMinEquations( integer i, integer i_min ) const {\n      UTILS_ASSERT(\n        i >= i_min, \"checkMinEquations:: i = {} < {}\", i, i_min\n      );\n    }\n\n    void\n    checkEven( integer i, integer i_min ) const {\n      UTILS_ASSERT(\n        (i % 2) == 0 && i >= i_min, \"checkEven:: odd index i = {}\", i\n      );\n    }\n\n    void\n    checkOdd( integer i, integer i_min ) const {\n      UTILS_ASSERT(\n        (i % 2) != 0 && i >= i_min, \"checkOdd:: odd index i = {}\", i\n      );\n    }\n\n    void\n    checkThree( integer i, integer i_min ) const {\n      UTILS_ASSERT(\n        (i % 3) == 0 && i >= i_min, \"checkThree:: index i = {}\", i\n      );\n    }\n\n    void\n    checkFour( integer i, integer i_min ) const {\n      UTILS_ASSERT(\n        (i % 4) == 0 && i >= i_min, \"checkFour:: index i = {}\", i\n      );\n    }\n\n  public:\n\n    explicit nonlinearBase( string const & t, string const & b )\n    : _title( t )\n    , _bibtex( b )\n    {}\n\n    virtual ~nonlinearBase() {}\n\n    string const & bibtex() const { return _bibtex; }\n    string const & title()  const { return _title; }\n\n  };\n\n  // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\n  // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\n\n  class multivariateFunction : public nonlinearBase {\n\n    multivariateFunction( multivariateFunction const & );\n    multivariateFunction const & operator = ( multivariateFunction const & );\n\n  protected:\n    integer n;\n\n  public:\n\n    multivariateFunction( string const & t, string const & b, integer _n )\n    : nonlinearBase( fmt::format(\"{} neq = {}\", t, _n ), b )\n    , n(_n)\n    { }\n\n    virtual ~multivariateFunction() {}\n\n    virtual real_type eval( dvec_t const & x ) const = 0;\n    virtual void      gradient( dvec_t const & x, dvec_t & g ) const = 0;\n\n    virtual integer hessianNnz() const = 0;\n    virtual void    hessian( dvec_t const & x, dvec_t & jac ) const = 0;\n    virtual void    hessianPattern( ivec_t & i, ivec_t & j ) const = 0;\n\n    virtual integer numExactSolution() const = 0;\n    virtual void    getExactSolution( dvec_t & x, integer idx ) const = 0;\n\n    virtual integer numInitialPoint() const = 0;\n    virtual void    getInitialPoint( dvec_t & x, integer idx ) const = 0;\n\n    virtual void    checkIfAdmissible( dvec_t const & x ) const = 0;\n\n    virtual void\n    boundingBox( dvec_t & L, dvec_t & U ) const {\n      L.fill( -real_max );\n      U.fill( real_max );\n    }\n\n    integer dimX( void ) const { return n; }\n\n  };\n\n  // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\n  // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\n\n  class nonlinearLeastSquares: public nonlinearBase {\n\n    nonlinearLeastSquares( nonlinearLeastSquares const & );\n    nonlinearLeastSquares const & operator = ( nonlinearLeastSquares const & );\n\n  protected:\n\n    integer n, m;\n\n  public:\n\n    nonlinearLeastSquares(\n      string const & t,\n      string const & b,\n      integer       _n,\n      integer       _m\n    )\n    : nonlinearBase(\n        fmt::format( \"{} dimF = {}, dimX = {}\", t, _n, _m ), b\n      )\n    , n(_n)\n    , m(_m)\n    {}\n\n    virtual ~nonlinearLeastSquares() {}\n\n    virtual real_type evalFk( dvec_t const & x, integer k ) const = 0;\n    virtual void      evalF ( dvec_t const & x, dvec_t & f ) const = 0;\n\n    virtual integer jacobianNnz() const = 0;\n    virtual void    jacobian( dvec_t const & x, dvec_t & jac ) const = 0;\n    virtual void    jacobianPattern( ivec_t & i, ivec_t & j ) const = 0;\n\n    virtual integer tensorNnz() const = 0;\n    virtual void    tensor( dvec_t const & x, dvec_t const & lambda, dvec_t & jac ) const = 0;\n    virtual void    tensorPattern( ivec_t & i, ivec_t & j ) const = 0;\n\n    virtual integer numExactSolution() const = 0;\n    virtual void    getExactSolution( dvec_t & x, integer idx ) const = 0;\n\n    virtual integer numInitialPoint() const = 0;\n    virtual void    getInitialPoint( dvec_t & x, integer idx ) const = 0;\n\n    virtual void checkIfAdmissible( dvec_t const & x ) const = 0;\n\n    virtual void\n    boundingBox( dvec_t & L, dvec_t & U ) const {\n      L.fill( -real_max );\n      U.fill( real_max );\n    }\n\n    integer dimF( void ) const { return n; }\n    integer dimX( void ) const { return m; }\n\n  };\n\n  // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\n  // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\n\n  class nonlinearSystem: public nonlinearBase {\n  \n    nonlinearSystem( nonlinearSystem const & );\n    nonlinearSystem const & operator = ( nonlinearSystem const & );\n\n  protected:\n\n    // U T I L I T Y  F U N C T I O N S -----------------------------------------\n  \n    // n = dimensione matrice\n    // i = riga\n    // j = colonna\n    // indirizzamento fortran\n    integer faddr( integer i, integer j ) const\n    { return (i-1) + (j-1) * n; }\n    \n    integer caddr( integer i, integer j ) const\n    { return i + j * n; }\n\n    integer n;\n\n  public:\n\n    nonlinearSystem( string const & t, string const & b, integer _n )\n    : nonlinearBase( fmt::format(\"{} neq = {}\", t, _n ), b )\n    , n(_n)\n    { }\n\n    virtual ~nonlinearSystem() {}\n\n    //void\n    //setup( string const & t, integer _n )\n    //{ theTitle = t; n = _n; }\n\n    virtual real_type evalFk( dvec_t const & x, integer k ) const = 0;\n    virtual void      evalF ( dvec_t const & x, dvec_t & f ) const = 0;\n\n    virtual integer jacobianNnz() const = 0;\n    virtual void    jacobian( dvec_t const & x, dvec_t & jac ) const = 0;\n    virtual void    jacobianPattern( ivec_t & i, ivec_t & j ) const = 0;\n\n    virtual integer numExactSolution() const = 0;\n    virtual void    getExactSolution( dvec_t & x, integer idx ) const = 0;\n\n    virtual integer numInitialPoint() const = 0;\n    virtual void    getInitialPoint( dvec_t & x, integer idx ) const = 0;\n\n    virtual void checkIfAdmissible( dvec_t const & x ) const = 0;\n\n    virtual void\n    boundingBox( dvec_t & L, dvec_t & U ) const {\n      L.fill( -real_max );\n      U.fill( real_max );\n    }\n\n    integer numEqns( void ) const { return n; }\n\n    integer\n    fill_CSR(\n      dvec_t const & x,\n      ivec_t       & R,\n      ivec_t       & J,\n      dvec_t       & values\n    ) const;\n\n  };\n\n  // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\n  // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\n\n  class nonlinearSystemFromMultivariateFunction: public nonlinearSystem {\n\n    nonlinearSystemFromMultivariateFunction(\n      nonlinearSystemFromMultivariateFunction const &\n    );\n    nonlinearSystemFromMultivariateFunction const &\n    operator = (nonlinearSystemFromMultivariateFunction const &);\n\n    multivariateFunction const * pMF;\n\n  public:\n\n    nonlinearSystemFromMultivariateFunction(\n      multivariateFunction const * _pMF\n    )\n    : nonlinearSystem( _pMF->title(), _pMF->bibtex(), _pMF->dimX() )\n    , pMF(_pMF) {\n    }\n\n    virtual ~nonlinearSystemFromMultivariateFunction() {}\n\n    virtual\n    real_type\n    evalFk( dvec_t const & x, integer k ) const {\n      dvec_t g(n);\n      evalF( x, g );\n      return g(k);\n    }\n\n    virtual\n    void\n    evalF( dvec_t const & x, dvec_t & g ) const {\n      pMF->gradient( x, g );\n    }\n\n    virtual\n    integer\n    jacobianNnz() const\n    { return pMF->hessianNnz(); }\n\n    virtual\n    void\n    jacobian( dvec_t const & x, dvec_t & hess ) const\n    { pMF->hessian(x,hess); }\n\n    virtual\n    void\n    jacobianPattern( ivec_t & i, ivec_t & j ) const\n    { pMF->hessianPattern( i, j ); }\n\n    virtual\n    integer\n    numExactSolution() const\n    { return pMF->numExactSolution(); }\n\n    virtual\n    void\n    getExactSolution( dvec_t & x, integer idx ) const\n    { pMF->getExactSolution( x, idx ); }\n\n    virtual\n    integer\n    numInitialPoint() const\n    { return pMF->numInitialPoint(); }\n\n    virtual\n    void\n    getInitialPoint( dvec_t & x, integer idx ) const\n    { pMF->getInitialPoint( x, idx ); }\n\n    virtual\n    void\n    checkIfAdmissible( dvec_t const & x ) const\n    { pMF->checkIfAdmissible( x ); }\n\n    virtual\n    void\n    boundingBox( dvec_t & L, dvec_t & U ) const\n    { pMF->boundingBox( L, U ); }\n\n    integer numEqns( void ) const { return pMF->dimX(); }\n\n    string const & title(void) const { return pMF->title(); }\n\n  };\n\n  // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\n  // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\n\n#if 0\n  class nonlinearSystemFromLeastSquares: public nonlinearSystem {\n\n    nonlinearSystemFromLeastSquares(nonlinearSystemFromLeastSquares const &);\n    nonlinearSystemFromLeastSquares const &\n    operator = (nonlinearSystemFromLeastSquares const &);\n\n    nonlinearLeastSquares const * pLS;\n\n  public:\n\n    nonlinearSystemFromLeastSquares( nonlinearLeastSquares const * _pLS )\n    : nonlinearSystem( _pLS->title(), _pLS->dimX() )\n    , pLS(_pLS) {\n    }\n\n    virtual ~nonlinearSystemFromLeastSquares() {}\n\n    virtual\n    real_type\n    evalFk( dvec_t const & x, integer k ) const {\n      dvec_t g(n);\n      evalF( x, g );\n      return g(k);\n    }\n\n    virtual\n    void\n    evalF( dvec_t const & x, dvec_t & g ) const {\n      pLS->gradient( x, g );\n    }\n\n    virtual\n    integer\n    jacobianNnz() const\n    { return pMF->hessianNnz(); }\n\n    virtual\n    void\n    jacobian( dvec_t const & x, dmat_t & hess ) const\n    { pMF->hessian(x,hess); }\n\n    virtual\n    void\n    jacobianPattern( ivec_t & i, ivec_t & j ) const\n    { pMF->hessianPattern(i,j); }\n\n    virtual\n    integer\n    numExactSolution() const\n    { return pMF->numExactSolution(); }\n\n    virtual\n    void\n    getExactSolution( dvec_t & x, integer idx ) const\n    { pMF->getExactSolution(x,idx); }\n\n    virtual\n    integer\n    numInitialPoint() const\n    { return pMF->numInitialPoint(); }\n\n    virtual\n    void\n    getInitialPoint( dvec_t & x, integer idx ) const\n    { pMF->getInitialPoint(x,idx); }\n\n    virtual\n    void\n    checkIfAdmissible( dvec_t const & x ) const\n    { pMF->checkIfAdmissible(x); }\n\n    virtual\n    void\n    boundingBox( dvec_t & L, dvec_t & U ) const\n    { pMF->boundingBox(L,U); }\n\n    integer numEqns( void ) const { return pMF->dimX(); }\n\n    string const & title(void) const { return pMF->title(); }\n\n  };\n#endif\n\n  extern vector<nonlinearSystem*> theProblems;\n  extern map<string,integer>      theProblemsMap;\n  void initProblems();\n\n}\n\n#endif\n", "meta": {"hexsha": "f7176e3686f14b6ed7e31ec3d4ed01f5294adb25", "size": 16045, "ext": "hh", "lang": "C++", "max_stars_repo_path": "toolbox/src/testsNonlin.hh", "max_stars_repo_name": "ebertolazzi/NLtoolbox", "max_stars_repo_head_hexsha": "99e47bdc346f3ac7b4834f2a6b431327d00e5ab1", "max_stars_repo_licenses": ["BSD-2-Clause", "Unlicense"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-06-28T09:12:53.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-28T09:12:53.000Z", "max_issues_repo_path": "toolbox/src/testsNonlin.hh", "max_issues_repo_name": "ebertolazzi/NLtoolbox", "max_issues_repo_head_hexsha": "99e47bdc346f3ac7b4834f2a6b431327d00e5ab1", "max_issues_repo_licenses": ["BSD-2-Clause", "Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "toolbox/src/testsNonlin.hh", "max_forks_repo_name": "ebertolazzi/NLtoolbox", "max_forks_repo_head_hexsha": "99e47bdc346f3ac7b4834f2a6b431327d00e5ab1", "max_forks_repo_licenses": ["BSD-2-Clause", "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.712962963, "max_line_length": 97, "alphanum_fraction": 0.5369897164, "num_tokens": 4630, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.6039318337259584, "lm_q1q2_score": 0.30432497759345306}}
{"text": "//=======================================================================\n// Copyright 2013 University of Warsaw.\n// Authors: Piotr Wygocki\n//\n// Distributed under the Boost Software License, Version 1.0. (See\n// accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n//=======================================================================\n//\n// This algorithm is described in \"Network Flows: Theory, Algorithms, and\n// Applications\"\n// by Ahuja, Magnanti, Orlin.\n\n#ifndef BOOST_GRAPH_SUCCESSIVE_SHORTEST_PATH_HPP\n#define BOOST_GRAPH_SUCCESSIVE_SHORTEST_PATH_HPP\n\n#include <numeric>\n\n#include <boost/property_map/property_map.hpp>\n#include <boost/graph/graph_traits.hpp>\n#include <boost/graph/graph_concepts.hpp>\n#include <boost/pending/indirect_cmp.hpp>\n#include <boost/graph/dijkstra_shortest_paths.hpp>\n#include <boost/graph/properties.hpp>\n#include <boost/graph/iteration_macros.hpp>\n#include <boost/graph/detail/augment.hpp>\n\nnamespace boost\n{\n\nnamespace detail\n{\n\n    template < class Graph, class Weight, class Distance, class Reversed >\n    class MapReducedWeight\n    : public put_get_helper< typename property_traits< Weight >::value_type,\n          MapReducedWeight< Graph, Weight, Distance, Reversed > >\n    {\n        typedef graph_traits< Graph > gtraits;\n\n    public:\n        typedef boost::readable_property_map_tag category;\n        typedef typename property_traits< Weight >::value_type value_type;\n        typedef value_type reference;\n        typedef typename gtraits::edge_descriptor key_type;\n        MapReducedWeight(const Graph& g, Weight w, Distance d, Reversed r)\n        : g_(g), weight_(w), distance_(d), rev_(r)\n        {\n        }\n\n        reference operator[](key_type v) const\n        {\n            return get(distance_, source(v, g_)) - get(distance_, target(v, g_))\n                + get(weight_, v);\n        }\n\n    private:\n        const Graph& g_;\n        Weight weight_;\n        Distance distance_;\n        Reversed rev_;\n    };\n\n    template < class Graph, class Weight, class Distance, class Reversed >\n    MapReducedWeight< Graph, Weight, Distance, Reversed > make_mapReducedWeight(\n        const Graph& g, Weight w, Distance d, Reversed r)\n    {\n        return MapReducedWeight< Graph, Weight, Distance, Reversed >(\n            g, w, d, r);\n    }\n\n} // detail\n\ntemplate < class Graph, class Capacity, class ResidualCapacity, class Reversed,\n    class Pred, class Weight, class Distance, class Distance2,\n    class VertexIndex >\nvoid successive_shortest_path_nonnegative_weights(const Graph& g,\n    typename graph_traits< Graph >::vertex_descriptor s,\n    typename graph_traits< Graph >::vertex_descriptor t, Capacity capacity,\n    ResidualCapacity residual_capacity, Weight weight, Reversed rev,\n    VertexIndex index, Pred pred, Distance distance, Distance2 distance_prev)\n{\n    filtered_graph< const Graph, is_residual_edge< ResidualCapacity > > gres\n        = detail::residual_graph(g, residual_capacity);\n    typedef typename graph_traits< Graph >::edge_descriptor edge_descriptor;\n\n    BGL_FORALL_EDGES_T(e, g, Graph)\n    {\n        put(residual_capacity, e, get(capacity, e));\n    }\n\n    BGL_FORALL_VERTICES_T(v, g, Graph) { put(distance_prev, v, 0); }\n\n    while (true)\n    {\n        BGL_FORALL_VERTICES_T(v, g, Graph) { put(pred, v, edge_descriptor()); }\n        dijkstra_shortest_paths(gres, s,\n            weight_map(\n                detail::make_mapReducedWeight(gres, weight, distance_prev, rev))\n                .distance_map(distance)\n                .vertex_index_map(index)\n                .visitor(make_dijkstra_visitor(\n                    record_edge_predecessors(pred, on_edge_relaxed()))));\n\n        if (get(pred, t) == edge_descriptor())\n        {\n            break;\n        }\n\n        BGL_FORALL_VERTICES_T(v, g, Graph)\n        {\n            put(distance_prev, v, get(distance_prev, v) + get(distance, v));\n        }\n\n        detail::augment(g, s, t, pred, residual_capacity, rev);\n    }\n}\n\n// in this namespace argument dispatching tak place\nnamespace detail\n{\n\n    template < class Graph, class Capacity, class ResidualCapacity,\n        class Weight, class Reversed, class Pred, class Distance,\n        class Distance2, class VertexIndex >\n    void successive_shortest_path_nonnegative_weights_dispatch3(const Graph& g,\n        typename graph_traits< Graph >::vertex_descriptor s,\n        typename graph_traits< Graph >::vertex_descriptor t, Capacity capacity,\n        ResidualCapacity residual_capacity, Weight weight, Reversed rev,\n        VertexIndex index, Pred pred, Distance dist, Distance2 dist_pred)\n    {\n        successive_shortest_path_nonnegative_weights(g, s, t, capacity,\n            residual_capacity, weight, rev, index, pred, dist, dist_pred);\n    }\n\n    // setting default distance map\n    template < class Graph, class Capacity, class ResidualCapacity,\n        class Weight, class Reversed, class Pred, class Distance,\n        class VertexIndex >\n    void successive_shortest_path_nonnegative_weights_dispatch3(Graph& g,\n        typename graph_traits< Graph >::vertex_descriptor s,\n        typename graph_traits< Graph >::vertex_descriptor t, Capacity capacity,\n        ResidualCapacity residual_capacity, Weight weight, Reversed rev,\n        VertexIndex index, Pred pred, Distance dist, param_not_found)\n    {\n        typedef typename property_traits< Weight >::value_type D;\n\n        std::vector< D > d_map(num_vertices(g));\n\n        successive_shortest_path_nonnegative_weights(g, s, t, capacity,\n            residual_capacity, weight, rev, index, pred, dist,\n            make_iterator_property_map(d_map.begin(), index));\n    }\n\n    template < class Graph, class P, class T, class R, class Capacity,\n        class ResidualCapacity, class Weight, class Reversed, class Pred,\n        class Distance, class VertexIndex >\n    void successive_shortest_path_nonnegative_weights_dispatch2(Graph& g,\n        typename graph_traits< Graph >::vertex_descriptor s,\n        typename graph_traits< Graph >::vertex_descriptor t, Capacity capacity,\n        ResidualCapacity residual_capacity, Weight weight, Reversed rev,\n        VertexIndex index, Pred pred, Distance dist,\n        const bgl_named_params< P, T, R >& params)\n    {\n        successive_shortest_path_nonnegative_weights_dispatch3(g, s, t,\n            capacity, residual_capacity, weight, rev, index, pred, dist,\n            get_param(params, vertex_distance2));\n    }\n\n    // setting default distance map\n    template < class Graph, class P, class T, class R, class Capacity,\n        class ResidualCapacity, class Weight, class Reversed, class Pred,\n        class VertexIndex >\n    void successive_shortest_path_nonnegative_weights_dispatch2(Graph& g,\n        typename graph_traits< Graph >::vertex_descriptor s,\n        typename graph_traits< Graph >::vertex_descriptor t, Capacity capacity,\n        ResidualCapacity residual_capacity, Weight weight, Reversed rev,\n        VertexIndex index, Pred pred, param_not_found,\n        const bgl_named_params< P, T, R >& params)\n    {\n        typedef typename property_traits< Weight >::value_type D;\n\n        std::vector< D > d_map(num_vertices(g));\n\n        successive_shortest_path_nonnegative_weights_dispatch3(g, s, t,\n            capacity, residual_capacity, weight, rev, index, pred,\n            make_iterator_property_map(d_map.begin(), index),\n            get_param(params, vertex_distance2));\n    }\n\n    template < class Graph, class P, class T, class R, class Capacity,\n        class ResidualCapacity, class Weight, class Reversed, class Pred,\n        class VertexIndex >\n    void successive_shortest_path_nonnegative_weights_dispatch1(Graph& g,\n        typename graph_traits< Graph >::vertex_descriptor s,\n        typename graph_traits< Graph >::vertex_descriptor t, Capacity capacity,\n        ResidualCapacity residual_capacity, Weight weight, Reversed rev,\n        VertexIndex index, Pred pred, const bgl_named_params< P, T, R >& params)\n    {\n        successive_shortest_path_nonnegative_weights_dispatch2(g, s, t,\n            capacity, residual_capacity, weight, rev, index, pred,\n            get_param(params, vertex_distance), params);\n    }\n\n    // setting default predecessors map\n    template < class Graph, class P, class T, class R, class Capacity,\n        class ResidualCapacity, class Weight, class Reversed,\n        class VertexIndex >\n    void successive_shortest_path_nonnegative_weights_dispatch1(Graph& g,\n        typename graph_traits< Graph >::vertex_descriptor s,\n        typename graph_traits< Graph >::vertex_descriptor t, Capacity capacity,\n        ResidualCapacity residual_capacity, Weight weight, Reversed rev,\n        VertexIndex index, param_not_found,\n        const bgl_named_params< P, T, R >& params)\n    {\n        typedef typename graph_traits< Graph >::edge_descriptor edge_descriptor;\n        std::vector< edge_descriptor > pred_vec(num_vertices(g));\n\n        successive_shortest_path_nonnegative_weights_dispatch2(g, s, t,\n            capacity, residual_capacity, weight, rev, index,\n            make_iterator_property_map(pred_vec.begin(), index),\n            get_param(params, vertex_distance), params);\n    }\n\n} // detail\n\ntemplate < class Graph, class P, class T, class R >\nvoid successive_shortest_path_nonnegative_weights(Graph& g,\n    typename graph_traits< Graph >::vertex_descriptor s,\n    typename graph_traits< Graph >::vertex_descriptor t,\n    const bgl_named_params< P, T, R >& params)\n{\n\n    return detail::successive_shortest_path_nonnegative_weights_dispatch1(g, s,\n        t,\n        choose_const_pmap(get_param(params, edge_capacity), g, edge_capacity),\n        choose_pmap(get_param(params, edge_residual_capacity), g,\n            edge_residual_capacity),\n        choose_const_pmap(get_param(params, edge_weight), g, edge_weight),\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        get_param(params, vertex_predecessor), params);\n}\n\ntemplate < class Graph >\nvoid successive_shortest_path_nonnegative_weights(Graph& g,\n    typename graph_traits< Graph >::vertex_descriptor s,\n    typename graph_traits< Graph >::vertex_descriptor t)\n{\n    bgl_named_params< int, buffer_param_t > params(0);\n    successive_shortest_path_nonnegative_weights(g, s, t, params);\n}\n\n} // boost\n#endif /* BOOST_GRAPH_SUCCESSIVE_SHORTEST_PATH_HPP */\n", "meta": {"hexsha": "8e1f5ad94aa619429f25cbd1ebf71a58e39c9076", "size": 10413, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ReactNativeFrontend/ios/Pods/boost/boost/graph/successive_shortest_path_nonnegative_weights.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/successive_shortest_path_nonnegative_weights.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/successive_shortest_path_nonnegative_weights.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": 40.67578125, "max_line_length": 80, "alphanum_fraction": 0.6880822049, "num_tokens": 2253, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6039318337259584, "lm_q2_score": 0.5039061705290805, "lm_q1q2_score": 0.30432497759345306}}
{"text": "#include <iostream>\n#include <fstream>\n#include <sstream>\n#include <algorithm>\n#include <cmath>\n#include <numeric>\n#include <chrono>\n#include <limits>\n#include <float.h>\n\n#include <CGAL/Polygon_mesh_processing/measure.h>\n\n#include <boost/algorithm/string/split.hpp>\n#include <boost/algorithm/string/classification.hpp>\n#include <boost/algorithm/string/trim.hpp>\n\n#include \"Utils.h\"\n#include \"OBJ_printer.h\"\n#include \"SymMat.h\"\n#include \"cluster_settings.h\"\n#include \"ErrorQuadric.h\"\n#include \"Chart.h\"\n#include \"JoinOperation.h\"\n#include \"polyhedron_builder.h\"\n#include \"eig.h\"\n\n#include \"CGAL_typedefs.h\"\n\n\n\n#define SEPARATE_CHART_FILE false\n\n\nVector normalise(Vector v) {return v / std::sqrt(v.squared_length());}\n\n\n//key: face_id, value: chart_id\nstd::map<uint32_t, uint32_t> chart_id_map;\n\n\n\nvoid count_faces_in_active_charts(std::vector<Chart> &charts) {\n  uint32_t active_faces = 0;\n  for (auto& chart : charts)\n  {\n    if (chart.active) \n    {\n      active_faces += chart.facets.size();\n    }\n  }\n  std::cout << \"found \" << active_faces << \" active faces\\n\";\n}\n\nuint32_t \ncreate_charts (Polyhedron &P, const double cost_threshold , const uint32_t chart_threshold, CLUSTER_SETTINGS cluster_settings){\n  std::stringstream report;\n\n  //calculate areas of each face\n  std::cout << \"Calculating face areas...\\n\";\n  std::map<face_descriptor,double> fareas;\n  for(face_descriptor fd: faces(P)){\n    fareas[fd] = CGAL::Polygon_mesh_processing::face_area  (fd,P);\n  }\n  //calculate normals of each faces\n  std::cout << \"Calculating face normals...\\n\";\n  std::map<face_descriptor,Vector> fnormals;\n  CGAL::Polygon_mesh_processing::compute_face_normals(P,boost::make_assoc_property_map(fnormals));\n\n  //get boost face iterator\n  face_iterator fb_boost, fe_boost;\n  boost::tie(fb_boost, fe_boost) = faces(P);\n\n  //each face begins as its own chart\n  std::cout << \"Creating initial charts...\\n\";\n  std::vector<Chart> charts;\n  for ( Facet_iterator fb = P.facets_begin(); fb != P.facets_end(); ++fb){\n    //assign id to face\n    fb->id() = charts.size();  \n\n    // std::cout << \"normal \" << charts.size() << \": \" << fnormals[*fb_boost] << std::endl;\n\n    //init chart instance for face\n    Chart c(charts.size(),*fb, fnormals[*fb_boost], fareas[*fb_boost]);\n    charts.push_back(c);\n\n\n    // //check uv coords saved\n    // double u = fb->halfedge()->vertex()->point().get_u();\n    // double v = fb->halfedge()->vertex()->point().get_v();\n    // std::cout << \"tex coords:  u \" << u << \", v \" << v << std::endl;\n\n    fb_boost++;\n  }\n\n  //for reporting and calculating when to stop merging\n  const uint32_t initial_charts = charts.size();\n  const uint32_t desired_merges = initial_charts - chart_threshold;\n  uint32_t chart_merges = 0;\n\n  //create possible join list/queue. Each original edge in the mesh becomes a join (if not a boundary edge)\n  std::cout << \"Creating initial joins...\\n\";\n  std::list<JoinOperation> joins;\n  std::list<JoinOperation>::iterator it;\n\n  int edgecount = 0;\n\n  for( Edge_iterator eb = P.edges_begin(), ee = P.edges_end(); eb != ee; ++ eb){\n\n    edgecount++;\n\n    //only create join if halfedge is not a boundary edge\n    if ( !(eb->is_border()) && !(eb->opposite()->is_border()) )\n    {\n          uint32_t face1 = eb->facet()->id();\n          uint32_t face2 = eb->opposite()->facet()->id();\n          JoinOperation join (face1,face2,JoinOperation::cost_of_join(charts[face1],charts[face2], cluster_settings));\n          joins.push_back(join);\n    }\n  } \n\n  std::cout << joins.size() << \" joins\\n\" << edgecount << \" edges\\n\";\n\n  // join charts until target is reached\n  int prev_cost_percent = -1;\n  int prev_charts_percent = -1;\n  int overall_percent = -1;\n\n  joins.sort(JoinOperation::sort_joins);\n  const double lowest_cost = joins.front().cost;\n\n\n  //execute lowest join cost and update affected joins.  re-sort.\n  std::cout << \"Processing join queue...\\n\";\n  while (joins.front().cost < cost_threshold  \n        &&  !joins.empty()\n        &&  (charts.size() - chart_merges) > chart_threshold){\n\n    //reporting-------------\n    int percent = (int)(((joins.front().cost - lowest_cost) / (cost_threshold - lowest_cost)) * 100);\n    if (percent != prev_cost_percent && percent > overall_percent) {\n      prev_cost_percent = percent;\n      overall_percent = percent;\n      std::cout << percent << \" percent complete\\n\";\n    } \n    percent = (int)(((float)chart_merges / (float)desired_merges) * 100);\n    if (percent != prev_charts_percent && percent > overall_percent) {\n      prev_charts_percent = percent;\n      overall_percent = percent;\n      std::cout << percent << \" percent complete\\n\";\n    }\n\n    //implement the join with lowest cost\n    JoinOperation join_todo = joins.front();\n    joins.pop_front();\n\n    // std::cout << \"join cost : \" << join_todo.cost << std::endl; \n\n    //merge faces from chart2 into chart 1\n    // std::cout << \"merging charts \" << join_todo.chart1_id << \" and \" << join_todo.chart2_id << std::endl;\n    charts[join_todo.chart1_id].merge_with(charts[join_todo.chart2_id], join_todo.cost);\n\n\n    //DEactivate chart 2\n    if (charts[join_todo.chart2_id].active == false)\n    {\n      report << \"chart \" << join_todo.chart2_id << \" was already inactive at merge \" << chart_merges << std::endl; // should not happen\n      continue;\n    }\n    charts[join_todo.chart2_id].active = false;\n    \n    int current_item = 0;\n    std::list<int> to_erase;\n    std::vector<JoinOperation> to_replace;\n\n    //update itremaining joins that include either of the merged charts\n    for (it = joins.begin(); it != joins.end(); ++it)\n    {\n      //if join is affected, update references and cost\n      if (it->chart1_id == join_todo.chart1_id \n         || it->chart1_id == join_todo.chart2_id \n         || it->chart2_id == join_todo.chart1_id \n         || it->chart2_id == join_todo.chart2_id )\n      {\n\n        //eliminate references to joined chart 2 (it is no longer active)\n        // by pointing them to chart 1\n        if (it->chart1_id == join_todo.chart2_id){\n          it->chart1_id = join_todo.chart1_id;\n        }\n        if (it->chart2_id == join_todo.chart2_id){\n          it->chart2_id = join_todo.chart1_id; \n        }\n\n        //search for duplicates\n        if ((it->chart1_id == join_todo.chart1_id && it->chart2_id == join_todo.chart2_id) \n          || (it->chart2_id == join_todo.chart1_id && it->chart1_id == join_todo.chart2_id) ){\n          report << \"duplicate found : c1 = \" << it->chart1_id << \", c2 = \" << it->chart2_id << std::endl; \n\n          to_erase.push_back(current_item);\n        }\n        //check for joins within a chart\n        else if (it->chart1_id == it->chart2_id)\n        {\n          report << \"Join found within a chart: \" << it->chart1_id << std::endl;\n          to_erase.push_back(current_item);\n          \n        }\n        else {\n          //update cost with new cost\n          it->cost = JoinOperation::cost_of_join(charts[it->chart1_id], charts[it->chart2_id], cluster_settings);\n\n          //save this join to be deleted and replaced in correct position after deleting duplicates\n          to_replace.push_back(*it);\n          to_erase.push_back(current_item);\n        }\n      }\n      current_item++;\n    }\n\n    //adjust ID to be deleted to account for previously deleted items\n    to_erase.sort();\n    int num_erased = 0;\n    for (auto id : to_erase) {\n      std::list<JoinOperation>::iterator it2 = joins.begin();\n      std::advance(it2, id - num_erased);\n      joins.erase(it2);\n      num_erased++;\n    }\n\n    // replace joins that were filtered out to be sorted\n    if (to_replace.size() > 0)\n    {\n      std::sort(to_replace.begin(), to_replace.end(), JoinOperation::sort_joins);\n      std::list<JoinOperation>::iterator it2;\n      uint32_t insert_item = 0;\n      for (it2 = joins.begin(); it2 != joins.end(); ++it2){\n        //insert items while join list item has bigger cost than element to be inserted\n        while (it2->cost > to_replace[insert_item].cost\n              && insert_item < to_replace.size()){\n          joins.insert(it2, to_replace[insert_item]);\n          insert_item++;\n        }\n        //if all items are in place, we are done\n        if (insert_item >= to_replace.size())\n        {\n          break;\n        }\n      }\n      //add any remaining items\n      for (uint32_t i = insert_item; i < to_replace.size(); i++){\n        joins.push_back(to_replace[i]);\n      }\n    }\n\n#if 0\n    //CHECK that each join would give a chart with at least 3 neighbours\n    //TODO also need to check boundary edges\n    to_erase.clear();\n    std::vector<std::vector<uint32_t> > neighbour_count (charts.size(), std::vector<uint32_t>(0));\n    std::list<JoinOperation>::iterator it2;\n    for (it2 = joins.begin(); it2 != joins.end(); ++it2){\n      //for chart 1 , add entry in vector for that chart containing id of chart 2\n      // and vice versa\n      neighbour_count[it2->chart1_id].push_back(it2->chart2_id);\n      neighbour_count[it2->chart2_id].push_back(it2->chart1_id);\n    }\n\n    uint32_t join_id = 0;\n    for (it2 = joins.begin(); it2 != joins.end(); ++it2){\n      // combined neighbour count of joins' 2 charts should be at least 5\n      // they will both contain each other (accounting for 2 neighbours) and require 3 more\n\n      //merge the vectors for each chart in the join and count unique neighbours\n      std::vector<uint32_t> combined_nbrs (neighbour_count[it2->chart1_id]);\n      combined_nbrs.insert(combined_nbrs.end(), neighbour_count[it2->chart2_id].begin(), neighbour_count[it2->chart2_id].end());\n\n      //find unique\n      std::sort(combined_nbrs.begin(), combined_nbrs.end());\n      uint32_t unique = 1;\n      for (uint32_t i = 1; i < combined_nbrs.size(); i++){\n        if (combined_nbrs[i] != combined_nbrs [i-1])\n        {\n          unique++;\n        }\n      }\n      if (unique < 5)\n      {\n        to_erase.push_back(join_id);\n      }\n      join_id++;\n    }\n    //erase joins that would result in less than 3 corners\n    to_erase.sort();\n    num_erased = 0;\n    for (auto id : to_erase) {\n      std::list<JoinOperation>::iterator it2 = joins.begin();\n      std::advance(it2, id - num_erased);\n      joins.erase(it2);\n      num_erased++;\n    }\n#endif\n\n    chart_merges++;\n\n    \n  }\n\n  // std::cout << \"Printing Joins:\\n\";  \n  // int index = 0;\n  // std::list<JoinOperation>::iterator it2;\n  // for (it2 = joins.begin(); it2 != joins.end(); ++it2){\n  //   std::cout << \"Join \" << ++index << \", cost \" << it2->cost << std::endl;\n  // }\n\n\n  //reporting//testing\n\n\n  std::cout << \"front join cost: \" << joins.front().cost << \", num joins: \" << joins.size() << \"chart threshold: \" << chart_threshold << std::endl; \n\n  std::cout << \"--------------------\\nCharts:\\n----------------------\\n\";\n\n  uint32_t total_faces = 0;\n  uint32_t total_active_charts = 0;\n  for (uint32_t i = 0; i < charts.size(); ++i)\n  {\n    if (charts[i].active)\n    {\n      uint32_t num_faces = charts[i].facets.size();\n      total_faces += num_faces;\n      total_active_charts++;\n      // std::cout << \"Chart \" << i << \" : \" << num_faces << \" faces\" << std::endl;\n    }\n  }\n  std::cout << \"Total number of faces in charts = \" << total_faces << std::endl;\n  std::cout << \"Initial charts = \" << charts.size() << std::endl;\n  std::cout << \"Total number merges = \" << chart_merges << std::endl;\n  std::cout << \"Total active charts = \" << total_active_charts << std::endl;\n\n\n  std::cout << \"--------------------\\nReport:\\n----------------------\\n\";\n  // std::cout << report.str();\n\n  //populate LUT for face to chart mapping\n  //count charts on the way to apply new chart ids\n  uint32_t active_charts = 0;\n  for (uint32_t id = 0; id < charts.size(); ++id) {\n    auto& chart = charts[id];\n    if (chart.active) {\n      for (auto& f : chart.facets) {\n        chart_id_map[f.id()] = active_charts;\n      }\n      active_charts++;\n    }\n  }\n\n  return active_charts;\n\n}\n\n\n\nint main( int argc, char** argv ) \n{\n\n  \n\n\n  std::string obj_filename = \"dino.obj\";\n  if (Utils::cmdOptionExists(argv, argv+argc, \"-f\")) {\n    obj_filename = std::string(Utils::getCmdOption(argv, argv + argc, \"-f\"));\n  }\n  else {\n    std::cout << \"Please provide an obj filename using -f <filename.obj>\" << std::endl;\n    std::cout << \"Optional: -ch specifies chart threshold (=100)\" << std::endl;\n    std::cout << \"Optional: -co specifies cost threshold (=double max)\" << std::endl;\n\n    std::cout << \"Optional: -ef specifies error fit coefficient (=1)\" << std::endl;\n    std::cout << \"Optional: -eo specifies error orientation coefficient (=1)\" << std::endl;\n    std::cout << \"Optional: -es specifies error shape coefficient (=1)\" << std::endl;\n    return 1;\n  }\n\n  double cost_threshold = std::numeric_limits<double>::max();\n  if (Utils::cmdOptionExists(argv, argv+argc, \"-co\")) {\n    cost_threshold = atof(Utils::getCmdOption(argv, argv + argc, \"-co\"));\n  }\n  uint32_t chart_threshold = 100;\n  if (Utils::cmdOptionExists(argv, argv+argc, \"-ch\")) {\n    chart_threshold = atoi(Utils::getCmdOption(argv, argv + argc, \"-ch\"));\n  }\n  double e_fit_cf = 1.0;\n  if (Utils::cmdOptionExists(argv, argv+argc, \"-ef\")) {\n    e_fit_cf = atof(Utils::getCmdOption(argv, argv + argc, \"-ef\"));\n  }\n  double e_ori_cf = 1.0;\n  if (Utils::cmdOptionExists(argv, argv+argc, \"-eo\")) {\n    e_ori_cf = atof(Utils::getCmdOption(argv, argv + argc, \"-eo\"));\n  }\n  double e_shape_cf = 1.0;\n  if (Utils::cmdOptionExists(argv, argv+argc, \"-es\")) {\n    e_shape_cf = atof(Utils::getCmdOption(argv, argv + argc, \"-es\"));\n  }\n  CLUSTER_SETTINGS cluster_settings (e_fit_cf, e_ori_cf, e_shape_cf);\n\n    //load OBJ into arrays\n  std::vector<double> vertices;\n  std::vector<int> tris;\n  std::vector<double> t_coords;\n  std::vector<int> tindices;\n  Utils::load_obj( obj_filename, vertices, tris, t_coords, tindices);\n\n\n  if (vertices.size() == 0 ) {\n    std::cout << \"didnt find any vertices\" << std::endl;\n    return 1;\n  }\n  std::cout << \"Mesh loaded (\" << vertices.size() / 3 << \" vertices, \" << tris.size() / 3 << \" faces, \" << t_coords.size() / 2 << \" tex coords)\" << std::endl;\n\n  auto start_time = std::chrono::system_clock::now();\n\n  // build a polyhedron from the loaded arrays\n  Polyhedron polyMesh;\n  bool check_vertices = true;\n  polyhedron_builder<HalfedgeDS> builder( vertices, tris, t_coords, tindices, check_vertices );\n\n\n  polyMesh.delegate( builder );\n\n  if (polyMesh.is_valid(false)){\n    std::cout << \"mesh valid\\n\"; \n  }\n\n\n  if (!CGAL::is_triangle_mesh(polyMesh)){\n    std::cerr << \"Input geometry is not triangulated.\" << std::endl;\n    return EXIT_FAILURE;\n  }\n  else {\n    std::cout << \"mesh is triangulated\\n\";\n  }\n\n  uint32_t active_charts = create_charts(polyMesh, cost_threshold, chart_threshold, cluster_settings);\n\n\n  std::string out_filename = \"data/charts.obj\";\n  std::ofstream ofs( out_filename );\n  OBJ_printer::print_polyhedron_wavefront_with_charts( ofs, polyMesh,chart_id_map, active_charts, SEPARATE_CHART_FILE);\n  ofs.close();\n  std::cout << \"simplified mesh was written to \" << out_filename << std::endl;\n\n  //Logging\n  auto time = std::chrono::system_clock::now();\n  std::chrono::duration<double> diff = time - start_time;\n  std::time_t now_c = std::chrono::system_clock::to_time_t(time);\n  std::string log_path = \"../../data/logs/chart_creation_log.txt\";\n  ofs.open (log_path, std::ofstream::out | std::ofstream::app);\n  ofs << \"\\n-------------------------------------\\n\";\n  \n  ofs << \"Executed at \" << std::put_time(std::localtime(&now_c), \"%F %T\") << std::endl;\n  ofs << \"Ran for \" << (int)diff.count() / 60 << \" m \"<< (int)diff.count() % 60 << \" s\" << std::endl;\n  ofs << \"Input file: \" << obj_filename << \"\\nOutput file: \" << out_filename << std::endl;\n  ofs << \"Vertices: \" << vertices.size()/3 << \" , faces: \" << tris.size()/3 << std::endl; \n  ofs << \"Desired Charts: \" << chart_threshold << \", active charts: \" << active_charts << std::endl;\n  ofs << \"Cost threshold: \" << cost_threshold << std::endl;\n  ofs << \"Cluster settings: e_fit: \" << cluster_settings.e_fit_cf << \", e_ori: \" << cluster_settings.e_ori_cf << \", e_shape\" << cluster_settings.e_shape_cf << std::endl;\n\n    ofs.close();\n  std::cout << \"Log written to \" << log_path << std::endl;\n\n\n\n  return EXIT_SUCCESS ; \n}", "meta": {"hexsha": "88e6f6853617685310400c51ff008619b78b8c01", "size": 16136, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "apps/face_clustering/main.cpp", "max_stars_repo_name": "gary444/lamure", "max_stars_repo_head_hexsha": "0b57a70d8496cd9632873628dc4064e09c57fef7", "max_stars_repo_licenses": ["BSD-3-Clause"], "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/face_clustering/main.cpp", "max_issues_repo_name": "gary444/lamure", "max_issues_repo_head_hexsha": "0b57a70d8496cd9632873628dc4064e09c57fef7", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/face_clustering/main.cpp", "max_forks_repo_name": "gary444/lamure", "max_forks_repo_head_hexsha": "0b57a70d8496cd9632873628dc4064e09c57fef7", "max_forks_repo_licenses": ["BSD-3-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.0421940928, "max_line_length": 169, "alphanum_fraction": 0.6247521071, "num_tokens": 4369, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6039318337259584, "lm_q2_score": 0.5039061705290805, "lm_q1q2_score": 0.30432497759345306}}
{"text": "// Copyright (c) 2018 yshurik\n//\n// Distributed under the MIT/X11 software license, see the accompanying\n// file COPYING or http://www.opensource.org/licenses/mit-license.php.\n//\n// The use in another cyptocurrency project the code is licensed under\n// Jelurida Public License (JPL). See https://www.jelurida.com/resources/jpl\n\n#include \"pegdata.h\"\n#include \"utilstrencodings.h\"\n\n#include <map>\n#include <set>\n#include <cstdint>\n#include <utility>\n#include <algorithm>\n#include <type_traits>\n\n#include <boost/multiprecision/cpp_int.hpp>\n\n#include <zconf.h>\n#include <zlib.h>\n\nusing namespace std;\nusing namespace boost;\n\nint64_t RatioPart(int64_t nValue,\n                  int64_t nPartValue,\n                  int64_t nTotalValue) {\n    if (nPartValue == 0 || nTotalValue == 0)\n        return 0;\n\n    bool has_overflow = false;\n    if (std::is_same<int64_t,long>()) {\n        long m_test;\n        has_overflow = __builtin_smull_overflow(nValue, nPartValue, &m_test);\n    } else if (std::is_same<int64_t,long long>()) {\n        long long m_test;\n        has_overflow = __builtin_smulll_overflow(nValue, nPartValue, &m_test);\n    } else {\n        assert(0); // todo: compile error\n    }\n\n    if (has_overflow) {\n        multiprecision::uint128_t v128(nValue);\n        multiprecision::uint128_t part128(nPartValue);\n        multiprecision::uint128_t f128 = (v128*part128)/nTotalValue;\n        return f128.convert_to<int64_t>();\n    }\n\n    return (nValue*nPartValue)/nTotalValue;\n}\n\nCPegData::CPegData(std::string pegdata64)\n{\n    if (pegdata64.empty()) {\n        peglevel = CPegLevel(0,0,0,0,0,0);\n        return; // defaults, zeros\n    }\n\n    string pegdata = DecodeBase64(pegdata64);\n    CDataStream finp(pegdata.data(),\n                     pegdata.data() + pegdata.size(),\n                     SER_NETWORK, CLIENT_VERSION);\n    bool ok = Unpack(finp);\n    if (!ok) {\n        // try prev versions\n        CDataStream finp(pegdata.data(),\n                         pegdata.data() + pegdata.size(),\n                         SER_DISK, CLIENT_VERSION);\n\n        bool ok = Unpack2(finp);\n        if (!ok) {\n            // try prev versions\n            CDataStream finp(pegdata.data(),\n                              pegdata.data() + pegdata.size(),\n                              SER_DISK, CLIENT_VERSION);\n            ok = Unpack1(finp);\n\n            if (!ok) {\n                // peglevel to inicate invalid\n                peglevel = CPegLevel();\n            }\n        }\n    }\n}\n\nbool CPegData::IsValid() const\n{\n    if (!peglevel.IsValid()) return false;\n\n    // match total\n    if ((nReserve+nLiquid) != fractions.Total()) return false;\n\n    // validate liquid/reserve match peglevel\n    int nSupplyEffective = peglevel.nSupply+peglevel.nShift;\n    bool fPartial = peglevel.nShiftLastPart >0 && peglevel.nShiftLastTotal >0;\n    if (fPartial) {\n        nSupplyEffective++;\n        int64_t nLiquidWithoutPartial = fractions.High(nSupplyEffective);\n        int64_t nReserveWithoutPartial = fractions.Low(nSupplyEffective-1);\n        if (nLiquid < nLiquidWithoutPartial) return false;\n        if (nReserve < nReserveWithoutPartial) return false;\n    }\n    else {\n        int64_t nLiquidCalc = fractions.High(nSupplyEffective);\n        int64_t nReserveCalc = fractions.Low(nSupplyEffective);\n        if (nLiquid != nLiquidCalc) return false;\n        if (nReserve != nReserveCalc) return false;\n    }\n\n    return true;\n}\n\nbool CPegData::Pack(CDataStream & fout) const {\n    fout << nVersion;\n    fractions.Pack(fout);\n    peglevel.Pack(fout);\n    fout << nReserve;\n    fout << nLiquid;\n    fout << nId;\n    return true;\n}\n\nbool CPegData::Unpack(CDataStream & finp) {\n    try {\n        finp >> nVersion;\n        if (!fractions.Unpack(finp)) return false;\n        if (!peglevel.Unpack(finp)) return false;\n        finp >> nReserve;\n        finp >> nLiquid;\n        finp >> nId;\n\n        if (!IsValid())\n            return false;\n    }\n    catch (std::exception &) {\n        return false;\n    }\n\n    fractions = fractions.Std();\n    return true;\n}\n\nstd::string CPegData::ToString() const {\n    CDataStream fout(SER_NETWORK, CLIENT_VERSION);\n    Pack(fout);\n    return EncodeBase64(fout.str());\n}\n\n", "meta": {"hexsha": "63214552afd45fcb7d06c3a05596b8cd5c35f45e", "size": 4186, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/peg/pegdata.cpp", "max_stars_repo_name": "bitbaymarket/BitBay", "max_stars_repo_head_hexsha": "99498d8509b439bee6d18be21c78577f1c654c01", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 29.0, "max_stars_repo_stars_event_min_datetime": "2016-07-12T01:05:24.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-30T03:11:36.000Z", "max_issues_repo_path": "src/peg/pegdata.cpp", "max_issues_repo_name": "bitbaymarket/BitBay", "max_issues_repo_head_hexsha": "99498d8509b439bee6d18be21c78577f1c654c01", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 14.0, "max_issues_repo_issues_event_min_datetime": "2016-05-06T11:02:05.000Z", "max_issues_repo_issues_event_max_datetime": "2018-12-26T12:43:20.000Z", "max_forks_repo_path": "src/peg/pegdata.cpp", "max_forks_repo_name": "bitbaymarket/BitBay", "max_forks_repo_head_hexsha": "99498d8509b439bee6d18be21c78577f1c654c01", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 23.0, "max_forks_repo_forks_event_min_datetime": "2017-01-04T11:55:46.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-10T19:20:16.000Z", "avg_line_length": 27.7218543046, "max_line_length": 78, "alphanum_fraction": 0.610367893, "num_tokens": 1048, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7401743620390163, "lm_q2_score": 0.411110869232168, "lm_q1q2_score": 0.3042937253612254}}
{"text": "﻿/*! \\file tdxscene.cpp\n    \\brief TDXSceneクラスの実装\n    Copyright ©  2015 @dc1394 All Rights Reserved.\n    This software is released under the BSD 2-Clause License.\n*/\n\n#include \"DXUT.h\"\n#include \"DXUTmisc.h\"\n#include \"myrandom/myrand.h\"\n#include \"resource.h\"\n#include \"TDXScene.h\"\n#include <mutex>                                                // for std::mutex\n#include <boost/assert.hpp>                                     // for BOOST_ASSERT\n#include <boost/cast.hpp>                                       // for boost::numeric_cast\n#include <boost/math/special_functions/spherical_harmonic.hpp>  // for boost::math::spherical_harmonic\n#include <boost/range/algorithm.hpp>                            // for boost::fill\n#include <tbb/parallel_for.h>                                   // for tbb::parallel_for\n#include <tbb/partitioner.h>                                    // for tbb::auto_partitioner\n\nnamespace tdxscene {\n\tfloat const TDXScene::MAGNIFICATION = 1.2f;\n\n\tTDXScene::TDXScene(std::shared_ptr<getdata::GetData> const & pgd) :\n\t\tComplete([this]{ return complete_.load(); }, nullptr),\n\t\tPth([this]{ return std::cref(pth_); }, nullptr),\n\t\tPgd(nullptr, [this](std::shared_ptr<getdata::GetData> const & val) {\n\t\t\trmax_ = GetRmax(val);\n\t\t\tSetCamera();\n\t\t\treturn pgd_ = val;\n\t\t}),\n\t\tPInputLayout([this]{ return std::cref(pInputLayout_); }, nullptr),\n\t\tRedraw(nullptr, [this](bool redraw){ return redraw_ = redraw; }),\n\t\tThread_end(nullptr, [this](bool thread_end){ \n\t\t\tthread_end_.store(thread_end);\n\t\t\treturn thread_end; }),\n\t\tVertexsize([this]{ return vertexsize_.load(); }, [this](std::vector<SimpleVertex2>::size_type size) { \n\t\t\t\tvertexsize_.store(size);\n\t\t\t\treturn size; }),\n\t\tprojectionVariable_(nullptr),\n\t\tpgd_(pgd),\n\t\trmax_(GetRmax(pgd)),\n\t\ttechnique_(nullptr),\n\t\tvertices_(VERTEXSIZE_FIRST),\n\t\tviewVariable_(nullptr),\n\t\tworldVariable_(nullptr)\n\t{\n\t}\n\n\n\tHRESULT TDXScene::Init(ID3D10Device* pd3dDevice)\n\t{\n\t\t// Read the D3DX effect_ file\n\t\tauto dwShaderFlags = D3D10_SHADER_ENABLE_STRICTNESS;\n#if defined( DEBUG ) || defined( _DEBUG )\n\t\t// Set the D3D10_SHADER_DEBUG flag to embed debug information in the shaders.\n\t\t// Setting this flag improves the shader debugging experience, but still allows \n\t\t// the shaders to be optimized and to run exactly the way they will run in \n\t\t// the release configuration of this program.\n\t\tdwShaderFlags |= D3D10_SHADER_DEBUG;\n#endif\n\n\t\tID3D10Effect * effect_tmp;\n\n\t\tauto hr = D3DX10CreateEffectFromFile(\n\t\t\tL\"SchracVisualize.fx\",\n\t\t\tnullptr,\n\t\t\tnullptr,\n\t\t\t\"fx_4_0\",\n\t\t\tdwShaderFlags,\n\t\t\t0,\n\t\t\tpd3dDevice,\n\t\t\tnullptr,\n\t\t\tnullptr,\n\t\t\t&effect_tmp,\n\t\t\tnullptr,\n\t\t\tnullptr);\n\n\t\teffect_.reset(effect_tmp);\n\n\t\tif (FAILED(hr))\n\t\t{\n\t\t\t::MessageBox(nullptr,\n\t\t\t\tL\"The FX file cannot be located.  Please run this executable from the directory that contains the FX file.\",\n\t\t\t\tL\"Error\",\n\t\t\t\tMB_OK);\n\t\t\tif (!utility::v_return(hr)) {\n\t\t\t\treturn S_FALSE;\n\t\t\t}\n\t\t}\n\n\t\ttechnique_ = effect_->GetTechniqueByName(\"Render2\");\n\t\tworldVariable_ = effect_->GetVariableByName(\"World\")->AsMatrix();\n\t\tviewVariable_ = effect_->GetVariableByName(\"View\")->AsMatrix();\n\t\tprojectionVariable_ = effect_->GetVariableByName(\"Projection\")->AsMatrix();\n\n\t\t// Define the input layout\n\t\tD3D10_INPUT_ELEMENT_DESC layout[] =\n\t\t{\n\t\t\t{ \"POSITION\", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D10_INPUT_PER_VERTEX_DATA, 0 },\n\t\t\t{ \"COLOR\", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, 12, D3D10_INPUT_PER_VERTEX_DATA, 0 },\n\t\t};\n\n\t\tauto const numElements = sizeof(layout) / sizeof(layout[0]);\n\n\t\t// Create the input layout\n\t\tD3D10_PASS_DESC PassDesc;\n\t\ttechnique_->GetPassByIndex(0)->GetDesc(&PassDesc);\n\t\tID3D10InputLayout * pVertexLayout;\n\n\t\tif (!utility::v_return(\n\t\t\tpd3dDevice->CreateInputLayout(\n\t\t\tlayout,\n\t\t\tnumElements,\n\t\t\tPassDesc.pIAInputSignature,\n\t\t\tPassDesc.IAInputSignatureSize,\n\t\t\t&pVertexLayout))) {\n\t\t\treturn S_FALSE;\n\t\t}\n\n\t\tpInputLayout_.reset(pVertexLayout, utility::Safe_Release<ID3D10InputLayout>());\n\n\t\t// Set the input layout\n\t\tpd3dDevice->IASetInputLayout(pInputLayout_.get());\n\n\t\tbd_.Usage = D3D10_USAGE_DEFAULT;\n\t\tbd_.BindFlags = D3D10_BIND_VERTEX_BUFFER;\n\t\tbd_.CPUAccessFlags = 0;\n\t\tbd_.MiscFlags = 0;\n\n\t\t// Initialize the world matrices\n\t\tD3DXMatrixIdentity(&world_);\n\n\t\t// Initialize the view matrix\n\t\tSetCamera();\n\n\t\treturn S_OK;\n\t}\n\n\n\tLRESULT TDXScene::MsgPrc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)\n\t{\n\t\treturn camera_.HandleMessages(hWnd, uMsg, wParam, lParam);\n\t}\n\n\n\tHRESULT TDXScene::OnFrameMove(double fTime, float fElapsedTime, void* pUserContext)\n\t{\n\t\t// Update the camera_'s position based on user input \n\t\tcamera_.FrameMove(fElapsedTime);\n\n\t\treturn S_OK;\n\t}\n\n\n\tHRESULT TDXScene::OnRender(ID3D10Device* pd3dDevice, double fTime, float fElapsedTime, void* pUserContext)\n\t{\n\t\t//\n\t\t// Clear the back buffer\n\t\t//\n\t\tauto const ClearColor = { 0.0f, 0.0f, 0.0f, 0.0f }; // red, green, blue, alpha\n\t\tauto pRTV = DXUTGetD3D10RenderTargetView();\n\t\tpd3dDevice->ClearRenderTargetView(pRTV, ClearColor.begin());\n\n\t\t//\n\t\t// Clear the depth stencil\n\t\t//\n\t\tauto pDSV = DXUTGetD3D10DepthStencilView();\n\t\tpd3dDevice->ClearDepthStencilView(pDSV, D3D10_CLEAR_DEPTH, 1.0, 0);\n\n\t\t//\n\t\t// Update variables that change once per frame\n\t\t//\n\t\tauto matcamera = camera_.GetProjMatrix();\n\t\tprojectionVariable_->SetMatrix(reinterpret_cast<float *>(const_cast<D3DXMATRIX *>(matcamera)));\n\t\tauto matview = camera_.GetViewMatrix();\n\t\tviewVariable_->SetMatrix(reinterpret_cast<float *>(const_cast<D3DXMATRIX *>(matview)));\n\n\t\tworldVariable_->SetMatrix(reinterpret_cast<float *>(&world_));\n\n\t\t//\n\t\t// Render the cube\n\t\t//\n\t\tD3D10_TECHNIQUE_DESC techDesc;\n\t\ttechnique_->GetDesc(&techDesc);\n\t\tfor (auto p = 0U; p < techDesc.Passes; ++p)\n\t\t{\n\t\t\ttechnique_->GetPassByIndex(p)->Apply(0);\n\t\t\tpd3dDevice->Draw(vertexsize_, 0);\n\t\t}\n\n\t\treturn S_OK;\n\t}\n\n\n\tHRESULT TDXScene::OnResize(ID3D10Device* pd3dDevice, IDXGISwapChain* pSwapChain,\n\t\tconst DXGI_SURFACE_DESC* pBackBufferSurfaceDesc, void* pUserContext)\n\t{\n\t\t// Setup the projection parameters again\n\t\tauto const fAspect = static_cast<float>(pBackBufferSurfaceDesc->Width) / static_cast<float>(pBackBufferSurfaceDesc->Height);\n\n\t\tcamera_.SetProjParams(D3DX_PI / 4, fAspect, 0.1f, 100.0f);\n\t\tcamera_.SetWindow(pBackBufferSurfaceDesc->Width, pBackBufferSurfaceDesc->Height);\n\t\tcamera_.SetButtonMasks(MOUSE_MIDDLE_BUTTON, MOUSE_WHEEL, MOUSE_LEFT_BUTTON);\n\n\t\treturn S_OK;\n\t}\n\n\n\tHRESULT TDXScene::RedrawFunc(std::int32_t m, ID3D10Device * pd3dDevice, TDXScene::Re_Im_type reim)\n\t{\n\t\tif (redraw_) {\n\t\t\tif (vertices_.size() != vertexsize_) {\n\t\t\t\tvertices_.resize(vertexsize_);\n\t\t\t}\n\n\t\t\tpth_.reset(new std::thread([this, m, reim]{ ClearFillSimpleVertex2(m, reim); }), [this](std::thread * pth)\n\t\t\t{\n\t\t\t\tif (pth->joinable()) {\n\t\t\t\t\tthread_end_.store(true);\n\t\t\t\t\tpth->join();\n\t\t\t\t}\n\n\t\t\t\tutility::Safe_Delete<std::thread> sd;\n\t\t\t\tsd(pth);\n\t\t\t});\n\t\t\tredraw_ = false;\n\t\t}\n\n\t\tbd_.ByteWidth = sizeof(SimpleVertex2) * vertexsize_;\n\n\t\tstatic D3D10_SUBRESOURCE_DATA InitData;\n\t\tInitData.pSysMem = vertices_.data();\n\n\t\tID3D10Buffer * vertexBuffertmp;\n\t\tif (!utility::v_return(pd3dDevice->CreateBuffer(&bd_, &InitData, &vertexBuffertmp))) {\n\t\t\treturn S_FALSE;\n\t\t}\n\n\t\t// Set vertex buffer\n\t\tstatic auto const stride = static_cast<UINT>(sizeof(SimpleVertex2));\n\t\tstatic auto const offset = 0U;\n\t\tpd3dDevice->IASetVertexBuffers(0, 1, &vertexBuffertmp, &stride, &offset);\n\t\tpVertexBuffer_.reset(vertexBuffertmp);\n\n\t\treturn S_OK;\n\t}\n\n\n\tvoid TDXScene::ClearFillSimpleVertex2(std::int32_t m, TDXScene::Re_Im_type reim)\n\t{\n\t\tcomplete_.store(false);\n\n\t\tSimpleVertex2 sv2;\n\t\tsv2.Col = { 0.0f, 0.0f, 0.0f, 0.0f };\n\t\tsv2.Pos = { 0.0f, 0.0f, 0.0f };\n\t\tboost::fill(vertices_, sv2);\n\n\t\ttbb::parallel_for(\n\t\t\t0,\n\t\t\tboost::numeric_cast<std::int32_t>(vertexsize_.load()),\n\t\t\t1,\n\t\t\t[this, m, reim](std::int32_t i) { FillSimpleVertex2(m, reim, vertices_[i]); });\n\n\t\tcomplete_.store(true);\n\t}\n\n\n\tvoid TDXScene::FillSimpleVertex2(std::int32_t m, TDXScene::Re_Im_type reim, SimpleVertex2 & ver)\n\t{\n\t\tif (thread_end_) {\n\t\t\treturn;\n\t\t}\n\n\t\tauto pp = 0.0, p = 0.0;\n\t\tauto sign = 0;\n\t\tdouble x, y, z;\n\n\t\tmyrandom::MyRand mr(-rmax_, rmax_);\n\t\tmyrandom::MyRand mr2(pgd_->Funcmin, pgd_->Funcmax);\n\n\t\tdo {\n\t\t\tif (thread_end_) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tx = mr.myrand();\n\t\t\ty = mr.myrand();\n\t\t\tz = mr.myrand();\n\n\t\t\tauto const r = std::sqrt(x * x + y * y + z * z);\n\t\t\tif (r < pgd_->R_meshmin()) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tswitch (pgd_->Rho_wf_type_) {\n\t\t\tcase getdata::GetData::Rho_Wf_type::RHO:\n\t\t\t{\n\t\t\t\tauto const phi = std::acos(x / std::sqrt(x * x + y * y));\n                double v;\n                if (m >= 0) {\n                    v = boost::math::spherical_harmonic_r(pgd_->L, m, std::acos(z / r), phi);\n                }\n                else {\n                    v = boost::math::spherical_harmonic_i(pgd_->L, m, std::acos(z / r), phi);\n                }\n                \n                pp = ((*pgd_)(r) * v * v);\n\t\t\t\tp = mr2.myrand();\n\t\t\t}\n\t\t\tbreak;\n\n\t\t\tcase getdata::GetData::Rho_Wf_type::WF:\n\t\t\t{\n\t\t\t\tauto const phi = std::acos(x / std::sqrt(x * x + y * y));\n\t\t\t\tdouble ylm = 0.0;\n\t\t\t\tswitch (reim) {\n\t\t\t\tcase TDXScene::Re_Im_type::REAL:\n\t\t\t\t\tylm = boost::math::spherical_harmonic_r(pgd_->L, m, std::acos(z / r), phi);\n\t\t\t\t\tbreak;\n\n\t\t\t\tcase TDXScene::Re_Im_type::IMAGINARY:\n\t\t\t\t\tylm = boost::math::spherical_harmonic_i(pgd_->L, m, std::acos(z / r), phi);\n\t\t\t\t\tbreak;\n\n\t\t\t\tdefault:\n\t\t\t\t\tBOOST_ASSERT(!\"何かがおかしい!\");\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\t\tpp = (*pgd_)(r) * ylm;\n\t\t\t\tp = mr2.myrand();\n\t\t\t}\n\t\t\tbreak;\n\n\t\t\tdefault:\n\t\t\t\tBOOST_ASSERT(!\"何かがおかしい!\");\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tswitch (pgd_->Rho_wf_type_) {\n\t\t\tcase getdata::GetData::Rho_Wf_type::RHO:\n\t\t\t\tsign = 1;\n\t\t\t\tbreak;\n\n\t\t\tcase getdata::GetData::Rho_Wf_type::WF:\n\t\t\t\tsign = (pp > 0.0) - (pp < 0.0);\n\t\t\t\tbreak;\n\n\t\t\tdefault:\n\t\t\t\tBOOST_ASSERT(!\"何かがおかしい!\");\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tif (!m && pgd_->Rho_wf_type_ == getdata::GetData::Rho_Wf_type::WF && reim == TDXScene::Re_Im_type::IMAGINARY) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\t\n\t\t} while (std::fabs(pp) < std::fabs(p));\n\n\t\tver.Pos.x = static_cast<float>(x);\n\t\tver.Pos.y = static_cast<float>(y);\n\t\tver.Pos.z = static_cast<float>(z);\n\n\t\tver.Col.r = sign > 0 ? 0.8f : 0.0f;\n\t\tver.Col.b = 0.8f;\n\t\tver.Col.g = sign < 0 ? 0.8f : 0.0f;\n\t\tver.Col.a = 1.0f;\n\t}\n\n\n\tvoid TDXScene::SetCamera()\n\t{\n\t\t// Initialize the view matrix\n\t\tauto const pos = static_cast<float>(rmax_)* TDXScene::MAGNIFICATION;\n\t\tD3DXVECTOR3 Eye(0.0f, pos, -pos);\n\t\tD3DXVECTOR3 At(0.0f, 0.0f, 0.0f);\n\t\tcamera_.SetViewParams(&Eye, &At);\n\t}\n\n\n\tdouble GetRmax(std::shared_ptr<getdata::GetData> const & pgd)\n\t{\n\t\tauto const n = static_cast<double>(pgd->N);\n\t\treturn (2.3622 * n + 3.3340) * n + 1.3228;\n\t}\n}", "meta": {"hexsha": "ba55bfa4ceb24d00105530be99e357e346ae1cca", "size": 10547, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "TDXScene.cpp", "max_stars_repo_name": "dc1394/SchracVisualize", "max_stars_repo_head_hexsha": "0ac49e883a4f9b92a48d224350f3d1967a1dbfe7", "max_stars_repo_licenses": ["Intel", "X11", "OLDAP-2.2.1", "Unlicense"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2015-05-02T05:26:00.000Z", "max_stars_repo_stars_event_max_datetime": "2016-01-08T04:52:02.000Z", "max_issues_repo_path": "TDXScene.cpp", "max_issues_repo_name": "dc1394/SchracVisualize", "max_issues_repo_head_hexsha": "0ac49e883a4f9b92a48d224350f3d1967a1dbfe7", "max_issues_repo_licenses": ["Intel", "X11", "OLDAP-2.2.1", "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": "TDXScene.cpp", "max_forks_repo_name": "dc1394/SchracVisualize", "max_forks_repo_head_hexsha": "0ac49e883a4f9b92a48d224350f3d1967a1dbfe7", "max_forks_repo_licenses": ["Intel", "X11", "OLDAP-2.2.1", "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.3238341969, "max_line_length": 126, "alphanum_fraction": 0.6536455864, "num_tokens": 3360, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5813030906443133, "lm_q2_score": 0.523420348936324, "lm_q1q2_score": 0.30426586654281007}}
{"text": "/* \n// Copyright 2018 University of Liege\n// \n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n// \n//     http://www.apache.org/licenses/LICENSE-2.0\n// \n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//\n// Authors:\n// - Adrien Crovato\n*/\n\n//// Surface grid reading\n// Read data from /IO/*.pts file which contain coordinates of points defining the corner of each panel\n//\n// I/O:\n// - path: path to *.pts file\n// - sGrid: temporary dynamic array to store panel vertices\n// - bPan: body panel (structure)\n\n#include <iostream>\n#include <fstream>\n#include <sstream>\n#include <Eigen/Dense>\n#include \"read_sgrid.h\"\n\n#define NDIM 3\n\nusing namespace std;\nusing namespace Eigen;\n\nvoid read_sgrid(string path, MatrixX3d &sGrid, Network &bPan){\n\n    ifstream infile(path);\n    string line;\n\n    int i = 2;\n    int a = 0;\n    string section;\n    bool secFLAG = 1;\n\n    if(!infile.is_open())\n    {\n        cout << \"File not found: \" << path << endl;\n        exit(EXIT_FAILURE);\n    }\n    else\n        cout << \"Found grid file: \" << path << endl;\n\n    getline(infile, line);\n    cout << \"Reading file... '\" << line << \"'\" << endl;\n\n    while (getline(infile, line))\n    {\n\n        if (secFLAG) {\n            stringstream ss(line);\n            ss >> section;\n            secFLAG = 0;\n        }\n\n        else {\n\n            if (section == \"$size\") {\n                stringstream ss(line);\n                ss >> bPan.nC >> bPan.nS;\n                sGrid.resize(bPan.nC * bPan.nS, NDIM);\n                secFLAG = 1;\n            }\n\n            else if (section == \"$points\") {\n                stringstream ss(line);\n                ss >> sGrid(a,0) >> sGrid(a,1) >> sGrid(a,2);\n                a++;\n            }\n\n            else {\n                cout << \"Invalid section name: \" << section << \" at line \" << i-1 << endl;\n                exit(EXIT_FAILURE);\n            }\n\n        }\n        i++;\n    }\n\n    // Set number of panels\n    bPan.nC_ = bPan.nC - 1;\n    bPan.nS_ = bPan.nS - 1;\n    bPan.nP = bPan.nC_ * bPan.nS_;\n\n    cout << \"Done reading surface sGrid file!\" << endl;\n    cout << \"Number of chordwise points: \" << bPan.nC << endl;\n    cout << \"Number of spanwise points: \" << bPan.nS << endl;\n    cout << \"Number of panels: \" << bPan.nP << endl;\n    #ifdef VERBOSE\n        cout << \"Surface points: \" << sGrid.rows() << 'X' << sGrid.cols() << endl;\n        for (int i = 0; i < bPan.nC*bPan.nS; ++i)\n            cout << i << ' ' << sGrid(i,0) << ' ' << sGrid(i,1) << ' ' << sGrid(i,2) << endl;\n    #endif\n    cout << endl;\n}", "meta": {"hexsha": "0644c8909266c8458d41e003314d05ab8abf2404", "size": 2920, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/read_sgrid.cpp", "max_stars_repo_name": "acrovato/aero", "max_stars_repo_head_hexsha": "310e6840670f5a39ca015c61c9090f123da8cfd6", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2020-11-16T15:24:12.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-15T09:36:09.000Z", "max_issues_repo_path": "src/read_sgrid.cpp", "max_issues_repo_name": "acrovato/aero", "max_issues_repo_head_hexsha": "310e6840670f5a39ca015c61c9090f123da8cfd6", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/read_sgrid.cpp", "max_forks_repo_name": "acrovato/aero", "max_forks_repo_head_hexsha": "310e6840670f5a39ca015c61c9090f123da8cfd6", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.037037037, "max_line_length": 102, "alphanum_fraction": 0.5489726027, "num_tokens": 772, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.30426586654281007}}
{"text": "// std c\n#include <stdio.h>\n#include <math.h>\n#include <iostream>\n#include <fstream>\n#include <iostream>\n#include <string> \n#include <sstream>\n#include <ctime>\n\n// opencv pcl\n#include <opencv/cv.h>\n#include <opencv2/core/core.hpp>\n#include <opencv2/highgui/highgui.hpp>\n#include \"opencv2/imgproc/imgproc.hpp\"\n\n// ros\n#include <ros/ros.h>\n#include <sensor_msgs/Image.h>\n#include <sensor_msgs/CameraInfo.h>\n#include <sensor_msgs/PointCloud2.h>\n\n// Eigen\n#include <Eigen/Dense>\n#include <Eigen/Core>\n\n// ours\n#include \"detect_3d_cuboid/matrix_utils.h\"\n#include \"detect_3d_cuboid/object_3d_util.h\"\n#include \"tictoc_profiler/profiler.hpp\"\n\n\nusing namespace std;\n// using namespace cv;\nusing namespace Eigen;\n\n\nvoid detect_3d_cuboid::set_calibration(const Matrix3d& Kalib)\n{\n      cam_pose.Kalib = Kalib;\n      cam_pose.invK = Kalib.inverse();\n}\n\n// BRIEF 相机位姿：将 Matrix4d 表示的相机位姿转换成自定义的 cam_pose_infos 位姿结构体.\nvoid detect_3d_cuboid::set_cam_pose(const Matrix4d& transToWolrd)\n{\n      cam_pose.transToWolrd = transToWolrd;\n      cam_pose.rotationToWorld = transToWolrd.topLeftCorner<3,3>();\n      Vector3d euler_angles; quat_to_euler_zyx(Quaterniond(cam_pose.rotationToWorld),euler_angles(0),euler_angles(1),euler_angles(2));\n      cam_pose.euler_angle = euler_angles;\n      cam_pose.invR = cam_pose.rotationToWorld.inverse();\n      cam_pose.projectionMatrix = cam_pose.Kalib*transToWolrd.inverse().topRows<3>();  // project world coordinate to camera\n      cam_pose.KinvR = cam_pose.Kalib * cam_pose.invR;\n      cam_pose.camera_yaw = cam_pose.euler_angle(2);\n      //TODO relative measure? not good... then need to change transToWolrd.\n}\n\n// NOTE 立方体检测函数.\n/* 输入：原始图像 rgb_img\n\t\t相机位姿 transToWolrd\n\t\t2D 检测框信息 obj_bbox_coors\n\t\t提取的边缘矩阵信息 all_lines_raw\n   输出：立方体提案 all_object_cuboids\n*/\nvoid detect_3d_cuboid::detect_cuboid(\tconst cv::Mat& rgb_img,\n\t\t\t\t\t\t\t\t\t\tconst Matrix4d& transToWolrd, \n\t\t\t\t\t\t\t\t\t\tconst MatrixXd& obj_bbox_coors,\n\t\t\t\t     \t\t\t\t \tMatrixXd all_lines_raw, \n\t\t\t\t\t\t\t\t\t\tstd::vector<ObjectSet>& all_object_cuboids)\n{\n\tcv::Mat merge_lines_img = rgb_img.clone();\n\t// 绘制上边缘采样点\n\ttypedef cv::Point_<int> Point2i;\n\tstd::vector<Point2i> simple_points;\t\n\tcv::Mat image_point = rgb_img;\t\n\n\t// 读取相机位姿，将 Matrix4d 表示的相机位姿转换成自定义的 cam_pose_infos 位姿结构体格式.\n    set_cam_pose(transToWolrd);\n    cam_pose_raw = cam_pose;\t// 先保存一份位姿信息在 cam_pose_raw 中.\n\n\t// 转换成灰度图.\n    cv::Mat gray_img; \n    if (rgb_img.channels()==3)\n\t  \tcv::cvtColor(rgb_img, gray_img, CV_BGR2GRAY);\n    else\n\t  \tgray_img = rgb_img;\n\n\t// 读取图像大小.\n    int img_width = rgb_img.cols;  \n\tint img_height = rgb_img.rows;\n\n\t// 读取检测框信息的行数，也即图像帧数.\n    int num_2d_objs = obj_bbox_coors.rows();\n    all_object_cuboids.resize(num_2d_objs);\n\n\t// @PARAM all_configs\t每帧视图的模式：1.观察到三个面；2.观察到两个面.\n    vector<bool> all_configs;\n\tall_configs.push_back(consider_config_1);\n\tall_configs.push_back(consider_config_2);\n\n    // 误差计算的一些阈值.\n    double vp12_edge_angle_thre = 15; \t\t// 消失点 1 2 与边的夹角阈值.\n\tdouble vp3_edge_angle_thre = 10;  \t\t// 消失点 3 与边的夹角阈值.\n    double shorted_edge_thre = 20;  \t\t// 边的阈值.if box edge are too short. box might be too thin. most possibly wrong.\n    bool reweight_edge_distance = true;  \t// if want to compare with all configurations. we need to reweight\n\n    // 归一化误差的权重.\n    bool whether_normalize_two_errors = true; \t// 是否归一化角度和距离误差\n\tdouble weight_vp_angle = 0.8; \t\t\t\t// NOTE 角度对齐误差的权重，训练的经验值，论文中为 0.7.\n\tdouble weight_skew_error = 1.5; \t\t\t// NOTE 形状误差的权重，训练的经验值，论文中为 1.5.\n    // NOTE ：if also consider config2, need to weight two erros, in order to compare two configurations\n\n    // STEP 【1.确保边缘线段的两个端点是从左到右存储的】\n    align_left_right_edges(all_lines_raw); // this should be guaranteed when detecting edges\n\t// 显示边缘检测的图.\n    if(whether_plot_detail_images)\n    {\n\t\tcv::Mat output_img;  \n\t\t// NOTE plot_image_with_edges() 函数绘制线段.\n\t\tplot_image_with_edges(rgb_img, output_img, all_lines_raw, cv::Scalar(255,0,0));\n\t\tcvNamedWindow(\"Raw detected Edges\");\n\t\tcvMoveWindow(\"Raw detected Edges\", 20, 300);\n\t\tcv::imshow(\"Raw detected Edges\", output_img);\t //cv::waitKey(0);\n\t\tcv::waitKey(0);\n    }\n    \n\t// STEP 【2.世界坐标系下的平面和相机坐标系下平面】\n    // TODO find ground-wall boundary edges\n\t// 作为列向量处理，在 pop up 中，使用的是 [0 0 -1 0]，在这里，希望法线指向内部，朝向相机以匹配表面法线预测\n    Vector4d ground_plane_world(0,0,1,0);  // treated as column vector % in my pop-up code, I use [0 0 -1 0]. here I want the normal pointing innerwards, towards the camera to match surface normal prediction\n\tVector4d ground_plane_sensor = cam_pose.transToWolrd.transpose() * ground_plane_world;\n\n\t// 逐帧处理.\n\t//int object_id=1;\n    for (int object_id = 0; object_id < num_2d_objs; object_id++)\n    {\n\t\t//std::cout<<\"object id  \"<<object_id<<std::endl;\n\t\t// 计时？\n\t\tca::Profiler::tictoc(\"One 3D object total time\"); \n\n\t\t// STEP 【3.2D 检测框大小，坐标和扩张】\n\t\t// 读取YOLO边界框的左上角点的坐标 x y 和长宽.\n\t\tint left_x_raw = obj_bbox_coors(object_id,0); \n\t\tint top_y_raw = obj_bbox_coors(object_id,1); \n\t\tint obj_width_raw = obj_bbox_coors(object_id,2); \n\t\tint obj_height_raw = obj_bbox_coors(object_id,3);\n\t\t// 计算右下角点的坐标.\n\t\tint right_x_raw = left_x_raw+obj_bbox_coors(object_id,2); \n\t\tint down_y_raw = top_y_raw + obj_height_raw;\n\n\t\t// NOTE 绘制检测框.\n\t\trectangle(\trgb_img,\n\t\t\t\t\tcv::Point(left_x_raw, top_y_raw),     \n        \t\t\tcv::Point(right_x_raw, down_y_raw),  \n\t\t\t\t\tcv::Scalar(0,255,255), \n\t\t\t\t\t2,   \n\t\t\t\t\t8);\n\n\t\t// @PARAM down_expand_sample_all\n\t\tstd::vector<int> down_expand_sample_all;\n\t\tdown_expand_sample_all.push_back(0);\t\t\t\t\t\t\t\t\t\t\t// 0.\n\t\t// TODO：2D 目标检测可能不准确，是否采样物体高度？？ 如果不采样 down_expand_sample_all.size()=1，采样则为3.\n\t\tif (whether_sample_bbox_height)  // 2D object detection might not be accurate\n\t\t{\n\t\t\tint down_expand_sample_ranges = max(min(20, obj_height_raw-90),20);\n\t\t\tdown_expand_sample_ranges = min(down_expand_sample_ranges, img_height - top_y_raw - obj_height_raw-1);  // should lie inside the image  -1 for c++ index\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// 图像高度 - 边界框左上角y轴坐标 - 检测框高度 - 1\n\t\t\t// 如果扩大边界，则提供更多样本.\n\t\t\tif (down_expand_sample_ranges > 10)  // if expand large margin, give more samples.\n\t\t\t\tdown_expand_sample_all.push_back(round(down_expand_sample_ranges/2));\t// 10.\n\t\t\tdown_expand_sample_all.push_back(down_expand_sample_ranges);\t\t\t// 20.\n\t\t}\n\t\t// for(int i=0; i<down_expand_sample_all.size(); i++)\n        //     std::cout << down_expand_sample_all[i] << \" \" ;\n\t\t// down_expand_sample_all: 0 10 20\n\n\t\t// STEP 【4.对偏航角进行采样】\n\t\t// NOTE later if in video, could use previous object yaw..., also reduce search range\n\t\t// @PARAM 【偏航角】初始化为面向相机，与相机光轴对齐.\n\t\tdouble yaw_init = cam_pose.camera_yaw - 90.0 / 180.0 * M_PI;  // yaw init is directly facing the camera, align with camera optical axis\t  \n\t\t// NOTE 偏航物体的角采样 -45 °到45°，每隔6°采样一个值，共15个.\n\t\tstd::vector<double> obj_yaw_samples; \n\t\t// BRIEF linespace()函数从 a 到 b 以步长 c 产生采样的 d.\n\t\tlinespace<double>(yaw_init - 45.0/180.0*M_PI, yaw_init + 45.0/180.0*M_PI, 6.0/180.0*M_PI, obj_yaw_samples);\n\t\t// std::cout << \"初始化偏航角：\\n\" << yaw_init << std::endl;\n\t\t// for(int i = 0; i < obj_yaw_samples.size(); i++)\n\t\t// \tstd::cout << \"采样偏航角：\\n\" << obj_yaw_samples[i] << std::endl;\n\n\n\t\tMatrixXd all_configs_errors(400,9); \n\t\tMatrixXd all_box_corners_2ds(800,8); \t// initialize a large eigen matrix\n\t\tint valid_config_number_all_height=0; \t// 高度样本的有效对象.all valid objects of all height samples\n\t\t\n\t\t// @PARAM 一系列立方体序列 raw_obj_proposals\n\t\tObjectSet raw_obj_proposals;\n\t\traw_obj_proposals.reserve(100);\t\t// 序列长度为 100.\n\n\t\t// 循环 1 次或 3 次(采样高度).\n\t\t// int sample_down_expan_id=1;\n\t\tfor (int sample_down_expan_id = 0; sample_down_expan_id < down_expand_sample_all.size(); sample_down_expan_id++)\n\t\t{\n\t\t\tint down_expand_sample = down_expand_sample_all[sample_down_expan_id]; \t// = 0 ,10 或 20 \n\t\t\t// 高度检测框的高度.\n\t\t\tint obj_height_expan = obj_height_raw + down_expand_sample;\t\t\t\t\n\t\t\tint down_y_expan = top_y_raw + obj_height_expan; \t\t\t\t\t\n\t\t\t// 宽度没变，高度变高了，求取对角线的长度. // TODO 为什么只拓宽了高度没有拓宽宽度呢？后面扩大检测框的大小高宽都变大了\t\t\n\t\t\tdouble obj_diaglength_expan = sqrt(obj_width_raw * obj_width_raw + obj_height_expan * obj_height_expan);\n\t\t\t\n\t\t\t// STEP 【5. 上边缘采样点】\n\t\t\t// 【顶边上的采样点的x坐标】，如果边太大，则提供更多样本。为所有边缘提供至少10个样本。对于小物体，物体位姿会改变很多.\n\t\t\t// NOTE 从边界框的最左边 left_x_raw+5 到最右边 right_x_raw-5 每隔 top_sample_resolution（20像素）的距离采样一个点top_x_samples[i].\n\t\t\tint top_sample_resolution = round(min(20,obj_width_raw/10 )); //  25 pixels\n\t\t\t\n\t\t\t// NOTE 修复 bug，若 top_sample_resolution = 0 会出现 Floating point exception (core dumped) 的错误.\n\t\t\tif(top_sample_resolution < 1)\n\t\t\t\tbreak;\n\t\t\t\n\t\t\tstd::vector<int> top_x_samples; \n\t\t\tlinespace<int>(left_x_raw+5, right_x_raw-5, top_sample_resolution, top_x_samples);\n\t\t\t// std::cout << \"左：\" << left_x_raw+5 << std::endl;\n\t\t\t// std::cout << \"右：\" << right_x_raw-5 << std::endl;\n\t\t\t// std::cout << \"top_x_samples 采样点数：\" << top_x_samples.size() << std::endl;\n\t\t\t// for(int i=0; i<top_x_samples.size(); i++)\n\t\t\t// \tstd::cout << top_x_samples[i] << \" \" ;\n\t\t\t// std::cout << std::endl;\n\n\t\t\t// 存储顶边采样的点\n\t\t\tMatrixXd sample_top_pts(2,top_x_samples.size());\n\t\t\tfor (int ii = 0; ii < top_x_samples.size(); ii++)\n\t\t\t{\n\t\t\t\tsample_top_pts(0,ii)=top_x_samples[ii];\n\t\t\t\tsample_top_pts(1,ii)=top_y_raw;\n\n\t\t\t\t// NOTE 保存采样点的坐标并绘制\n\t\t\t\tsimple_points.push_back(Point2i(top_x_samples[ii], top_y_raw));\n\t\t\t\tcircle(image_point, simple_points[ii], 3, cv::Scalar(255,0,0),-1,8,0);\n\t\t\t}\n\t      \n\t\t  \t// STEP 【扩大边界范围】\n\t\t\t// TODO expand some small margin for distance map  [10 20]\n\t\t\t// @PARAM 拓宽检测框的边界.\n\t\t\tint distmap_expand_wid = min(max(min(20, obj_width_raw-100),10), max(min(20, obj_height_expan-100),10));\t// 20.\n\t\t\tint left_x_expan_distmap = max(0,left_x_raw-distmap_expand_wid); \t\t\t\t// 检测框左边界 x 坐标往左扩大 20.\n\t\t\tint right_x_expan_distmap = min(img_width-1,right_x_raw+distmap_expand_wid);\t// 检测框右边界 x 坐标往右扩大 20.\n\t\t\tint top_y_expan_distmap = max(0,top_y_raw-distmap_expand_wid); \t\t\t\t\t// 检测框上边界 y 坐标往上扩大 20.\n\t\t\tint down_y_expan_distmap = min(img_height-1,down_y_expan+distmap_expand_wid);\t// 检测框下边界 y 坐标往上扩大 20.\n\t\t\tint height_expan_distmap = down_y_expan_distmap - top_y_expan_distmap; \t\t\t// 扩大后的高度.\n\t\t\tint width_expan_distmap = right_x_expan_distmap - left_x_expan_distmap;\t\t\t// 扩大后的宽度.\n\t\t\t// std::cout << \"distmap_expand_wid：\" << distmap_expand_wid << std::endl;\n\t\t\t// std::cout << \"left_x_expan_distmap：\" << left_x_expan_distmap << std::endl;\n\t\t\t// std::cout << \"right_x_expan_distmap：\" << right_x_expan_distmap  << std::endl;\n\t\t\t// std::cout << \"top_y_expan_distmap：\" << top_y_expan_distmap << std::endl;\n\t\t\t// std::cout << \"down_y_expan_distmap：\" << down_y_expan_distmap << std::endl;\n\t\t\t// std::cout << \"width_expan_distmap：\" << width_expan_distmap << std::endl;\n\t\t\tVector2d expan_distmap_lefttop = Vector2d(left_x_expan_distmap, top_y_expan_distmap);\t\t\t// 左上角坐标.\n\t\t\tVector2d expan_distmap_rightbottom = Vector2d(right_x_expan_distmap, down_y_expan_distmap);\t\t// 右下角坐标.\n\n\t\t\tif(sample_down_expan_id == 0)\n\t\t\t\t// NOTE 绘制拓宽的边界.\n\t\t\t\trectangle(\trgb_img,\n\t\t\t\t\t\t\tcv::Point(left_x_expan_distmap, top_y_expan_distmap),     \n\t\t\t\t\t\t\tcv::Point(right_x_expan_distmap, down_y_expan_distmap),  \n\t\t\t\t\t\t\tcv::Scalar(255,0,0), \n\t\t\t\t\t\t\t2,   \n\t\t\t\t\t\t\t8);\n\n\t\t\t// STEP 【6.线段处理】\n\t\t\t// STEP 【6.1 找出在扩大后的边界框内的线段.】\n\t      \t// find edges inside the object bounding box\n\t\t\t// @PARAM all_lines_inside_object：存储所有在扩大后的边界框内的线段.\n\t\t\tMatrixXd all_lines_inside_object(all_lines_raw.rows(),all_lines_raw.cols()); // first allocate a large matrix, then only use the toprows to avoid copy, alloc\n\t\t\tint inside_obj_edge_num = 0;\n\t\t\t// 遍历 all_lines_raw 中的每一条线\n\t\t\tfor (int edge_id = 0; edge_id < all_lines_raw.rows(); edge_id++)\n\t\t\t\t// 判断 all_lines_raw 矩阵中第 edge_id 线段的一个端点.head<2> 是否在区域中.\n\t\t\t\tif (check_inside_box(all_lines_raw.row(edge_id).head<2>(), expan_distmap_lefttop, expan_distmap_rightbottom ))\n\t\t\t\t\t// 判断 all_lines_raw 矩阵中第 edge_id 线段的另一个端点.tail<2> 是否在区域中.\n\t\t\t\t\tif (check_inside_box(all_lines_raw.row(edge_id).tail<2>(),expan_distmap_lefttop, expan_distmap_rightbottom ))\n\t\t\t\t\t{\n\t\t\t\t\t\t// 存储所有在扩大后的边界框内的线段.\n\t\t\t\t\t\tall_lines_inside_object.row(inside_obj_edge_num) = all_lines_raw.row(edge_id);\n\t\t\t\t\t\tinside_obj_edge_num++;\n\t\t\t\t\t}\n\t      \n\t\t  \t// STEP 【6.2 在找到物体的边缘线之后合并边，并剔除短边，小区域的边缘合并应该更快.】\n\t\t\t// merge edges and remove short lines, after finding object edges.  edge merge in small regions should be faster than all.\n\t\t\t// @PARAM 线段合并与筛选参数.\n\t\t\tdouble pre_merge_dist_thre = 20; \n\t\t\tdouble pre_merge_angle_thre = 5; \n\t\t\tdouble edge_length_threshold = 30;\n\t\t\tMatrixXd all_lines_merge_inobj; \t// NOTE 合并之后的线段存储矩阵.\n\t\t\tmerge_break_lines(\tall_lines_inside_object.topRows(inside_obj_edge_num), /*输入all_lines_inside_object矩阵的前inside_obj_edge_num行*/\n\t\t\t\t\t\t\t\tall_lines_merge_inobj, \t\t/*输出的合并后的线段矩阵*/\n\t\t\t\t\t\t\t\tpre_merge_dist_thre,\t\t/*两条线段的距离（水平）阈值 20 像素*/\n\t\t\t\t\t\t\t  \tpre_merge_angle_thre, \t\t/*角度阈值 5°*/\n\t\t\t\t\t\t\t\tedge_length_threshold);\t\t/*长度阈值 30 像素*/\n\t\t\t// 显示筛选之后的边缘线段.\n\t\t\t// cv::Mat output_img;\n\t\t\t// plot_image_with_edges(merge_lines_img, output_img, all_lines_merge_inobj, cv::Scalar(0,255,0));\n\t\t\t// cvNamedWindow(\"merge_lines_img\");\n\t\t\t// cvMoveWindow(\"merge_lines_img\",500, 300);\n\t\t\t// cv::imshow(\"merge_lines_img\", output_img);\t //cv::waitKey(0);\n\t\t\t// cv::waitKey(0);\n\n\t\t\t// STEP 【7. 计算角度、中点，Canny 边缘检测，距离变换】\n\t\t\t// 计算每条边缘线段的角度和中点.\n\t\t\t// @PARAM lines_inobj_angles\t线段角度.\n\t\t\t// @PARAM edge_mid_pts\t\t\t线段的中点.\n\t\t\tVectorXd lines_inobj_angles(all_lines_merge_inobj.rows());\n\t\t\tMatrixXd edge_mid_pts(all_lines_merge_inobj.rows(),2);\n\t\t\tfor (int i=0; i < all_lines_merge_inobj.rows(); i++)\n\t\t\t{\n\t\t\t\tlines_inobj_angles(i) = std::atan2(all_lines_merge_inobj(i,3)-all_lines_merge_inobj(i,1), all_lines_merge_inobj(i,2)-all_lines_merge_inobj(i,0));   // [-pi/2 -pi/2]\n\t\t\t\tedge_mid_pts.row(i).head<2>() = (all_lines_merge_inobj.row(i).head<2>()+all_lines_merge_inobj.row(i).tail<2>())/2;\n\t\t\t}\n\n\t\t\t// TODO could canny or distance map outside sampling height to speed up!!!!   Then only need to compute canny onces.\n\t\t\t// detect canny edges and compute distance transform  NOTE opencv canny maybe different from matlab. but roughly same\n\t\t\t// @PARAM\t\tobject_bbox\t\t扩大后的检测框.\n\t\t\tcv::Rect object_bbox = cv::Rect(left_x_expan_distmap, top_y_expan_distmap, width_expan_distmap, height_expan_distmap);//\n\t\t\t\n\t\t\t// NOTE Canny 算子边缘检测.\n\t\t\tcv::Mat im_canny; \n\t\t\tcv::Canny(gray_img(object_bbox),im_canny,80,200); // low thre, high thre    im_canny 0 or 255   [80 200  40 100]\n\t\t\t// 距离变换.\n\t\t\tcv::Mat dist_map; \n\t\t\tcv::distanceTransform(255 - im_canny, dist_map, CV_DIST_L2, 3); // dist_map is float datatype\n\n\t\t\t// 是否显示处理细节.\n\t\t\tif (whether_plot_detail_images)\n\t\t\t{\n\t\t\t\tcv::imshow(\"im_canny\",im_canny);\n\t\t\t\tcv::Mat dist_map_img;cv::normalize(dist_map, dist_map_img, 0.0, 1.0, cv::NORM_MINMAX);\n\t\t\t\tcv::imshow(\"normalized distance map\", dist_map_img);cv::waitKey();\n\t\t\t}\n\n\t\t\t// STEP 【8.生成立方体】\n\t\t\tMatrixXd all_configs_error_one_objH(200,9);   \t\t// 误差. \n\t\t\tMatrixXd all_box_corners_2d_one_objH(400,8); \t\t// 2D坐标\n\t\t\tint valid_config_number_one_objH = 0;\t\t\t\t// 有效测量次数\n\n\t\t\t// STEP 【8.1 采样相机的 roll pitch 角】\n\t\t  \t// 采样相机 roll pitch 角，在相机偏角的+-6°每隔3°采样一个值 或者 直接使用相机的roll pitch角.\n\t      \tstd::vector<double> cam_roll_samples; \n\t\t\tstd::vector<double> cam_pitch_samples;\n\t\t\tif (whether_sample_cam_roll_pitch)\n\t\t\t{\n\t\t\t\tlinespace<double>(cam_pose_raw.euler_angle(0)-6.0/180.0*M_PI, cam_pose_raw.euler_angle(0)+6.0/180.0*M_PI, 3.0/180.0*M_PI, cam_roll_samples);\n\t\t\t\tlinespace<double>(cam_pose_raw.euler_angle(1)-6.0/180.0*M_PI, cam_pose_raw.euler_angle(1)+6.0/180.0*M_PI, 3.0/180.0*M_PI, cam_pitch_samples);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tcam_roll_samples.push_back(cam_pose_raw.euler_angle(0));\n\t\t\t\tcam_pitch_samples.push_back(cam_pose_raw.euler_angle(1));\n\t\t\t}\n\n\t\t\t// different from matlab. first for loop yaw, then for configurations.\n\t\t\t// int obj_yaw_id = 8;\n\t\t\t// 分别遍历采样的 roll，pitch 和 yaw 角.\n\t\t\tfor (int cam_roll_id = 0; cam_roll_id < cam_roll_samples.size(); cam_roll_id++)\n\t\t\tfor (int cam_pitch_id = 0; cam_pitch_id < cam_pitch_samples.size(); cam_pitch_id++)\n\t\t\tfor (int obj_yaw_id = 0; obj_yaw_id < obj_yaw_samples.size(); obj_yaw_id++)\n\t\t\t{\n\t\t\t\tstd::cout << \"第 \" << cam_roll_id << \" 个相机 roll 采样角\" << std::endl;\n\t\t\t\tstd::cout << \"第 \" << cam_pitch_id << \" 个相机 pitch 采样角\" << std::endl;\n\t\t\t\tstd::cout << \"第 \" << obj_yaw_id << \" 个物体 yaw 采样角\" << std::endl;\n\t\t\t\t\n\t\t\t\tif (whether_sample_cam_roll_pitch)\n\t\t\t\t{\n\t\t\t\t\tMatrix4d transToWolrd_new = transToWolrd;\n\t\t\t\t\t// 将当前角度值转换成旋转矩阵. \n\t\t\t\t\t// NOTE 这里yaw为什么不用采样的值而用相机的值？：yaw 采样是真对物体的，并没有对相机的 yaw 值进行采样。\n\t\t\t\t\ttransToWolrd_new.topLeftCorner<3,3>() = euler_zyx_to_rot<double>(cam_roll_samples[cam_roll_id], cam_pitch_samples[cam_pitch_id], cam_pose_raw.euler_angle(2));\n\t\t\t\t\tset_cam_pose(transToWolrd_new);\n\t\t\t\t\t// TODO 平面？？\n\t\t\t\t\tground_plane_sensor = cam_pose.transToWolrd.transpose() * ground_plane_world;\n\t\t\t\t}\n\n\t\t\t\t// 读取采样的物体偏航角.\n\t\t\t\tdouble obj_yaw_esti = obj_yaw_samples[obj_yaw_id];\n\n\t\t\t\t// STEP 【8.2 计算三个消失点】\n\t\t\t\t// @PARAM\tvp_1, vp_2, vp_3\t三个消失点.\n\t\t\t\tVector2d vp_1, vp_2, vp_3;\n\t\t\t\tgetVanishingPoints(cam_pose.KinvR, obj_yaw_esti, vp_1, vp_2, vp_3); // for object x y z  axis\n\t\t\t\t// std::cout << \"vp_1:\\n\" << vp_1 << std::endl;\n\t\t\t\t// std::cout << \"vp_2:\\n\" << vp_2 << std::endl;\n\t\t\t\t// std::cout << \"vp_3:\\n\" << vp_3 << std::endl;\n\t\t\t\t// circle(image_point, cv::Point(vp_1(0)/5, vp_1(1))/5, 3, cv::Scalar(255,0,0),-1,8,0);\n\t\t\t\t\n\t\t\t\t// @PARAM all_vps(3,2) 存储三个消失点.\n\t\t\t\tMatrixXd all_vps(3,2);\n\t\t\t\tall_vps.row(0) = vp_1;\n\t\t\t\tall_vps.row(1) = vp_2;\n\t\t\t\tall_vps.row(2) = vp_3;\n\n\t\t\t\t// 输出采样的偏航角.\n\t\t\t\t// std::cout<<\"obj_yaw_esti  \" << obj_yaw_esti << \"  \" << obj_yaw_id << std::endl;\n\n\t\t\t\t// STEP 【8.3 寻找形成消失点的两条边】\n\t\t\t\tMatrixXd all_vp_bound_edge_angles = VP_support_edge_infos(\tall_vps, \t\t\t\t/* 消失点矩阵 3*2 */\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tedge_mid_pts,\t\t\t/* 每条线段的中点 n×2 */\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tlines_inobj_angles,\t\t/* 每条线段的偏角 n×1 */\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tVector2d(vp12_edge_angle_thre, vp3_edge_angle_thre));\t/* 消失点与各边的夹角阈值*/\n\t\t\t\t// int sample_top_pt_id=15;\n\t\t\t\t// STEP 【8.4.遍历上边缘的采样点，得到 8 个点的 2D 坐标.】\n\t\t\t\tfor (int sample_top_pt_id = 0; sample_top_pt_id < sample_top_pts.cols(); sample_top_pt_id++)\n\t\t\t\t{\n\t\t\t\t\tstd::cout << \"第 \" << sample_top_pt_id << \" 个上边缘采样点\" << std::endl;\n\t\t\t\t\t// std::cout << \"sample_top_pt_id \" << sample_top_pt_id << std::endl;\n\t\t\t\t\t// STEP 【8.4.1 采样得到立方体上边缘的第一个点.】\n\t\t\t\t\t// @PARAM corner_1_top 当前采样点.\n\t\t\t\t\tVector2d corner_1_top = sample_top_pts.col(sample_top_pt_id);\n\t\t\t\t\tbool config_good = true;\n\n\t\t\t\t\t// cv::putText(rgb_img, \n\t\t\t\t\t// \t\t\t\"1\", \n\t\t\t\t\t// \t\t\tcv::Point(corner_1_top(0), corner_1_top(1)),\n\t\t\t\t\t// \t\t\t2,      // fontFace\n\t\t\t\t\t// \t\t\t0.5,    // fontScale\n\t\t\t\t\t// \t\t\tcv::Scalar(0, 255, 0), \n\t\t\t\t\t// \t\t\t1);     // 粗细\n\n\t\t\t\t\t// @PARAM vp_1_position\t消失点1的位置，1 是左边，2 是右边.\n\t\t\t\t\tint vp_1_position = 0;  // 0 initial as fail,  1  on left   2 on right\n\n\t\t\t\t\t// STEP 【8.4.2 计算立方体上边缘的第二个点.】\n\t\t\t\t\t// NOTE 检查【消失点1-上边缘采样点的射线是否与右边边界有交集】.\n\t\t\t\t\t// @PARAM corner_2_top 消失点1-上边缘采样点射线与边界框左右边界的交点.\n\t\t\t\t\tVector2d corner_2_top = seg_hit_boundary(\tvp_1,\t\t\t\t/* 消失点 */\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tcorner_1_top,\t\t/* 上边缘的采样点 */\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tVector4d(right_x_raw, top_y_raw, right_x_raw, down_y_expan) /* 右边边缘 */);\n\t\t\t\t\t// NOTE 如果消失点1-上边缘采样点的连线与右边边缘没有交集，再检查【是否与左边边缘有交集】.\n\t\t\t\t\tif (corner_2_top(0) == -1)\n\t\t\t\t\t{  \t// vp1-corner1 doesn't hit the right boundary. check whether hit left\n\t\t\t\t\t\tcorner_2_top = seg_hit_boundary(\tvp_1,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tcorner_1_top,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tVector4d(left_x_raw, top_y_raw, left_x_raw, down_y_expan));\n\t\t\t\t\t\t// 如果与左边边界有交集，说明消失点在右边（2）\n\t\t\t\t\t\tif (corner_2_top(0) != -1) // vp1-corner1 hit the left boundary   vp1 on the right\n\t\t\t\t\t\t\tvp_1_position = 2;\n\t\t\t\t\t}\n\t\t\t\t\t// 如果与右边边界有交集，说明消失点在左边（1）\n\t\t\t\t\telse    // vp1-corner1 hit the right boundary   vp1 on the left\n\t\t\t\t\t\tvp_1_position = 1;\n\t\t      \n\t\t\t  \t\t// 检查消失点与采样点配置.\n\t\t\t\t\tconfig_good = vp_1_position > 0;\n\t\t\t\t\tif (!config_good)\n\t\t\t\t\t{\n\t\t\t\t\t\tif (print_details) \n\t\t\t\t\t\t\tprintf(\"Configuration fails at corner 2, outside segment\\n\"); \n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\t// 上边缘采样点与边界上的交集点（消失点1）的距离\n\t\t\t\t\tif ((corner_1_top - corner_2_top).norm() < shorted_edge_thre)\n\t\t\t\t\t{\n\t\t\t\t\t\tif (print_details) \n\t\t\t\t\t\t\tprintf(\"Configuration fails at edge 1-2, too short\\n\"); \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\t// cout << \"上边缘采样点1和交点corner_1/2   \" << corner_1_top.transpose() << \"   \" << corner_2_top.transpose() << endl;\n\n\t\t\t\t\t// int config_ind = 0; // have to consider config now.\n\t\t\t\t\tfor (int config_id = 1; config_id < 3; config_id++)  // configuration one or two of matlab version\n\t\t\t\t\t{\n\t\t\t\t\t\tif (!all_configs[config_id-1])  \n\t\t\t\t\t\t\tcontinue;\n\n\t\t\t\t\t\t// @PARAM corner_4_top\t消失点2-上边缘采样点射线与左右边界的交点.\n\t\t\t\t\t\t// NOTE 代码中的 3 4 与论文中相反，代码中的第三个点对应论文中第四个点.\n\t\t\t\t\t\tVector2d corner_3_top, corner_4_top;\n\n\t\t\t\t\t\t// STEP 【8.4.3 第一种情形下的顶部第 3, 4 个点】\n\t\t\t\t\t\t// NOTE 第一种情形，可以观察到物体的三个面.\n\t\t\t\t\t\tif (config_id == 1)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t// STEP 【计算消失点 2 与左右边界的交点(第三个点).】\n\t\t\t\t\t\t\t// 如果消失点 1 在左边，则消失点vp2在右边，与左侧边界有交点 corner_4_top\n\t\t\t\t\t\t\tif (vp_1_position == 1)   // then vp2 hit the left boundary\n\t\t\t\t\t\t\t\tcorner_4_top = seg_hit_boundary(vp_2, corner_1_top, Vector4d(left_x_raw, top_y_raw, left_x_raw, down_y_expan));\n\t\t\t\t\t\t\t// 如果消失点 1 在右边，则消失点vp2在左边，与右侧边界有交点 corner_4_top\n\t\t\t\t\t\t\telse  // or, then vp2 hit the right boundary\n\t\t\t\t\t\t\t\tcorner_4_top = seg_hit_boundary(vp_2, corner_1_top, Vector4d(right_x_raw, top_y_raw, right_x_raw, down_y_expan));\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t// 如果没有交点.\n\t\t\t\t\t\t\tif (corner_4_top(1) == -1)\t// TODO 这里用的y坐标 corner_4_top(1)，前面用的x坐标corner_2_top(0)？？\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tconfig_good = false;\n\t\t\t\t\t\t\t\tif (print_details)  \n\t\t\t\t\t\t\t\t\tprintf(\"Configuration %d fails at corner 4, outside segment\\n\",config_id); \n\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t// 上边缘采样点与边界上的交集点（消失点2）的距离\n\t\t\t\t\t\t\tif ((corner_1_top - corner_4_top).norm() < shorted_edge_thre)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tif (print_details) \n\t\t\t\t\t\t\t\t\tprintf(\"Configuration %d fails at edge 1-4, too short\\n\",config_id);\n\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t// compute the last point in the top face\n\t\t\t\t\t\t\t// STEP 【计算立方体上边缘第四个点（最后一个点）】\n\t\t\t\t\t\t\tcorner_3_top = lineSegmentIntersect(vp_2, corner_2_top, vp_1, corner_4_top, true);\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t// 检查.\n\t\t\t\t\t\t\tif (!check_inside_box( corner_3_top, Vector2d(left_x_raw,top_y_raw), Vector2d(right_x_raw, down_y_expan)))\n\t\t\t\t\t\t\t{    // check inside boundary. otherwise edge visibility might be wrong\n\t\t\t\t\t\t\t\tconfig_good = false;  \n\t\t\t\t\t\t\t\tif (print_details) \n\t\t\t\t\t\t\t\t\tprintf(\"Configuration %d fails at corner 3, outside box\\n\",config_id); \n\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif ( ((corner_3_top-corner_4_top).norm()<shorted_edge_thre) || ((corner_3_top-corner_2_top).norm()<shorted_edge_thre) )\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tif (print_details) \n\t\t\t\t\t\t\t\t\tprintf(\"Configuration %d fails at edge 3-4/3-2, too short\\n\",config_id); \n\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t// 输出立方体上边缘第三四个点的位置.\n\t\t\t\t\t\t\t//cout<<\"corner_3/4   \"<<corner_3_top.transpose()<<\"   \"<<corner_4_top.transpose()<<endl;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// STEP 【8.4.4 第二种情形下的顶部第 3, 4 个点】\n\t\t\t\t\t\t// NOTE 第二种情形，可以观察到物体的两个面.\n\t\t\t\t\t\tif (config_id==2)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t// STEP 计算消失点2——顶点2与左侧边界的交点（第三个点）.\n\t\t\t\t\t\t\t// 如果消失点1在左侧，则其交点在右侧\n\t\t\t\t\t\t\tif (vp_1_position==1)   // then vp2 hit the left boundary\n\t\t\t\t\t\t\t\tcorner_3_top = seg_hit_boundary(vp_2, corner_2_top, Vector4d(left_x_raw, top_y_raw, left_x_raw, down_y_expan));\n\t\t\t\t\t\t\telse  // or, then vp2 hit the right boundary\n\t\t\t\t\t\t\t\tcorner_3_top = seg_hit_boundary(vp_2, corner_2_top, Vector4d(right_x_raw, top_y_raw, right_x_raw, down_y_expan));\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t// 检查.\n\t\t\t\t\t\t\tif (corner_3_top(1)==-1)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tconfig_good = false; \n\t\t\t\t\t\t\t\tif (print_details)  \n\t\t\t\t\t\t\t\t\tprintf(\"Configuration %d fails at corner 3, outside segment\\n\",config_id); \n\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif ((corner_2_top-corner_3_top).norm()<shorted_edge_thre)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tif (print_details) \n\t\t\t\t\t\t\t\t\tprintf(\"Configuration %d fails at edge 2-3, too short\\n\",config_id);\n\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t// STEP 计算立方体上边缘第四个点（最后一个点）\n\t\t\t\t\t\t\tcorner_4_top = lineSegmentIntersect(vp_1, corner_3_top, vp_2, corner_1_top, true);\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t// 检查.\n\t\t\t\t\t\t\tif (!check_inside_box( corner_4_top, Vector2d(left_x_raw,top_y_expan_distmap), Vector2d(right_x_raw, down_y_expan_distmap)))\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tconfig_good=false;\n\t\t\t\t\t\t\t\tif (print_details) \n\t\t\t\t\t\t\t\t\tprintf(\"Configuration %d fails at corner 4, outside box\\n\",config_id); \n\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif ( ((corner_3_top-corner_4_top).norm()<shorted_edge_thre) || ((corner_4_top-corner_1_top).norm()<shorted_edge_thre) )\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tif (print_details) \n\t\t\t\t\t\t\t\t\tprintf(\"Configuration %d fails at edge 3-4/4-1, too short\\n\",config_id); \n\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t// 输出情形2中立方体上边缘第三四个点的位置.\n\t\t\t\t\t\t\t// cout<<\"corner_3/4   \"<<corner_3_top.transpose()<<\"   \"<<corner_4_top.transpose()<<endl;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// compute first bottom points    computing bottom points is the same for config 1,2\n\t\t\t\t\t\t// NOTE 计算底部点（情形 1 和 2 的计算方法一样）\n\t\t\t\t\t\t// STEP 【8.5 计算第五个点\tvp3—4线段与边界框下边界的交点】\n\t\t\t\t\t\tVector2d corner_5_down = seg_hit_boundary(vp_3, corner_3_top, Vector4d(left_x_raw, down_y_expan, right_x_raw, down_y_expan));\n\t\t\t\t\t\t// 检查.\n\t\t\t\t\t\tif (corner_5_down(1)==-1){\n\t\t\t\t\t\t\tconfig_good = false; \n\t\t\t\t\t\t\tif (print_details) printf(\"Configuration %d fails at corner 5, outside segment\\n\",config_id); \n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif ((corner_3_top-corner_5_down).norm()<shorted_edge_thre){\n\t\t\t\t\t\t\tif (print_details) printf(\"Configuration %d fails at edge 3-5, too short\\n\",config_id); \n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// STEP 【8.6 计算第 6 个点\tvp2—5线段与vp3—2的交点.】\n\t\t\t\t\t\tVector2d corner_6_down = lineSegmentIntersect(vp_2, corner_5_down, vp_3, corner_2_top, true);\n\t\t\t\t\t\tif (!check_inside_box( corner_6_down, expan_distmap_lefttop, expan_distmap_rightbottom)){\n\t\t\t\t\t\t\tconfig_good=false;  \n\t\t\t\t\t\t\tif (print_details) printf(\"Configuration %d fails at corner 6, outside box\\n\",config_id); \n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif ( ((corner_6_down-corner_2_top).norm()<shorted_edge_thre) || ((corner_6_down-corner_5_down).norm()<shorted_edge_thre) ){\n\t\t\t\t\t\t\tif (print_details) printf(\"Configuration %d fails at edge 6-5/6-2, too short\\n\",config_id); \n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// STEP 【8.7 计算第 7 个点\tvp1—6线段与vp3—1的交点.】\n\t\t\t\t\t\tVector2d corner_7_down=lineSegmentIntersect(vp_1, corner_6_down, vp_3, corner_1_top, true);\n\t\t\t\t\t\tif (!check_inside_box( corner_7_down, expan_distmap_lefttop, expan_distmap_rightbottom)){// might be slightly different from matlab\n\t\t\t\t\t\t\tconfig_good=false;  \n\t\t\t\t\t\t\tif (print_details) printf(\"Configuration %d fails at corner 7, outside box\\n\",config_id); \n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif ( ((corner_7_down-corner_1_top).norm()<shorted_edge_thre) || ((corner_7_down-corner_6_down).norm()<shorted_edge_thre) ){\n\t\t\t\t\t\t\tif (print_details) printf(\"Configuration %d fails at edge 7-1/7-6, too short\\n\",config_id); \n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// STEP 【8.8 计算第 8 个点\tvp1—5线段与vp5—7的交点.】\n\t\t\t\t\t\tVector2d corner_8_down=lineSegmentIntersect(vp_1,corner_5_down,vp_2, corner_7_down,true);\n\t\t\t\t\t\tif (!check_inside_box( corner_8_down, expan_distmap_lefttop, expan_distmap_rightbottom)){\n\t\t\t\t\t\t\tconfig_good=false;  \n\t\t\t\t\t\t\tif (print_details) printf(\"Configuration %d fails at corner 8, outside box\\n\",config_id); \n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif ( ((corner_8_down-corner_4_top).norm()<shorted_edge_thre) || ((corner_8_down-corner_5_down).norm()<shorted_edge_thre) || ((corner_8_down-corner_7_down).norm()<shorted_edge_thre)){\n\t\t\t\t\t\t\tif (print_details) printf(\"Configuration %d fails at edge 8-4/8-5/8-7, too short\\n\",config_id); \n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\t\t\t  \n\t\t\t\t\t\t// @PARAM box_corners_2d_float\t存储物体的 8 个顶点（2D）.\n\t\t\t\t\t\tMatrixXd box_corners_2d_float(2,8);\n\t\t\t\t\t\tbox_corners_2d_float << \tcorner_1_top, corner_2_top, corner_3_top, corner_4_top, \n\t\t\t\t\t\t\t\t\t\t\t\t\tcorner_5_down, corner_6_down, corner_7_down, corner_8_down;\n\t\t\t\t\t\t// std::cout<<\"box_corners_2d_float \\n \"<<box_corners_2d_float<<std::endl;\n\t\t\t\t\t\t\n\t\t\t\t\t\t// @PARAM box_corners_2d_float_shift 8 个顶点x坐标距离左边边界框边界的距离和 y坐标距离上边边界的距离（以检测框左上边界为轴的坐标）.\n\t\t\t\t\t\tMatrixXd box_corners_2d_float_shift(2,8);\n\t\t\t\t\t\tbox_corners_2d_float_shift.row(0) = box_corners_2d_float.row(0).array() - left_x_expan_distmap;\n\t\t\t\t\t\tbox_corners_2d_float_shift.row(1) = box_corners_2d_float.row(1).array() - top_y_expan_distmap;\n\n\t\t\t\t\t\tMatrixXi visible_edge_pt_ids, vps_box_edge_pt_ids;\n\t\t\t\t\t\tdouble sum_dist;\n\t\t\t\t\t\t\n\t\t\t\t\t\t// STEP 【9.1 距离误差计算】，第一种情形.\n\t\t\t\t\t\tif (config_id == 1)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t// 可以看到三个面，共9条边.\n\t\t\t\t\t\t\tvisible_edge_pt_ids.resize(9,2); \n\t\t\t\t\t\t\tvisible_edge_pt_ids << 1,2, 2,3, 3,4, 4,1, 2,6, 3,5, 4,8, 5,8, 5,6;\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t// 计算三个消失点所需要的两条边\n\t\t\t\t\t\t\tvps_box_edge_pt_ids.resize(3,4); \n\t\t\t\t\t\t\t// 1_2 与 8_5 交点得到vp1\t4_1 与 5_6 交点得到vp1\t\n\t\t\t\t\t\t\tvps_box_edge_pt_ids << 1,2,8,5, 4,1,5,6, 4,8,2,6; // six edges. each row represents two edges [e1_1 e1_2   e2_1 e2_2;...] of one VP\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tvisible_edge_pt_ids.array() -=1; \n\t\t\t\t\t\t\tvps_box_edge_pt_ids.array() -=1; //change to c++ index\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t// TODO  计算距离\tdist_map？？\n\t\t\t\t\t\t\tsum_dist = box_edge_sum_dists(dist_map, box_corners_2d_float_shift, visible_edge_pt_ids);\n\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{\n\t\t\t\t\t\t\tvisible_edge_pt_ids.resize(7,2); \n\t\t\t\t\t\t\tvisible_edge_pt_ids<<1,2, 2,3, 3,4, 4,1, 2,6, 3,5, 5,6;\n\t\t\t\t\t\t\tvps_box_edge_pt_ids.resize(3,4); \n\t\t\t\t\t\t\tvps_box_edge_pt_ids<<1,2,3,4, 4,1,5,6, 3,5,2,6; // six edges. each row represents two edges [e1_1 e1_2   e2_1 e2_2;...] of one VP\t\t\t\t  \n\t\t\t\t\t\t\tvisible_edge_pt_ids.array() -=1; \n\t\t\t\t\t\t\tvps_box_edge_pt_ids.array() -=1;\n\t\t\t\t\t\t\tsum_dist = box_edge_sum_dists(dist_map, box_corners_2d_float_shift, visible_edge_pt_ids, reweight_edge_distance);\n\t\t\t\t\t\t}\n\t\t\t\t\t\t\n\t\t\t\t\t\t// STEP 【9.2 计算角度误差.】\n\t\t\t\t\t\tdouble total_angle_diff = box_edge_alignment_angle_error(\tall_vp_bound_edge_angles,\t/* 消失点与边的两个角度 */\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tvps_box_edge_pt_ids,\t\t/* 每个消失点来源的两条边 */\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tbox_corners_2d_float);\t\t/* 8 个顶点的 2D坐标 */\n\n\t\t\t\t\t\t// @PARAM \tall_configs_error_one_objH\t存储所有的误差.\n\t\t\t\t\t\tall_configs_error_one_objH.row(valid_config_number_one_objH).head<4>() = Vector4d(\tconfig_id, \t\t\t/* 模式 */\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\tvp_1_position, \t\t/* vp1的位置 */\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\tobj_yaw_esti, \t\t/* 偏航角采样 */\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\tsample_top_pt_id);\t/* 上边缘采样点 */\n\t\t\t\t\t\tall_configs_error_one_objH.row(valid_config_number_one_objH).segment<3>(4) = Vector3d(\tsum_dist/obj_diaglength_expan, \t/* 平均距离误差？ */\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\ttotal_angle_diff, \t\t\t\t/* 角度误差 */\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\tdown_expand_sample);\t\t\t/* 高度？受是否采样了高度影响？ */\n\t\t\t\t\t\t// 是否采样相机的 roll 和 pitch 角.\n\t\t\t\t\t\tif (whether_sample_cam_roll_pitch)\n\t\t\t\t\t\t\tall_configs_error_one_objH.row(valid_config_number_one_objH).segment<2>(7) = Vector2d(\tcam_roll_samples[cam_roll_id],\t\t/* 采样相机 roll 角 */\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\tcam_pitch_samples[cam_pitch_id]);\t/* 采样相机 pitch 角 */\n\t\t\t\t\t\telse\n\t\t\t\t\t\t\tall_configs_error_one_objH.row(valid_config_number_one_objH).segment<2>(7) = Vector2d(\tcam_pose_raw.euler_angle(0),\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\tcam_pose_raw.euler_angle(1));\n\n\t\t\t\t\t\t// TODO 所有情况下的物体的八个顶点的 2D坐标？\n\t\t\t\t\t\tall_box_corners_2d_one_objH.block(2*valid_config_number_one_objH,0,2,8) = box_corners_2d_float;\n\n\t\t\t\t\t\t// 有效的测量次数？？\n\t\t\t\t\t\tvalid_config_number_one_objH++;\n\n\t\t\t\t\t\tif (valid_config_number_one_objH >= all_configs_error_one_objH.rows())\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tall_configs_error_one_objH.conservativeResize(2*valid_config_number_one_objH,NoChange);\n\t\t\t\t\t\t\tall_box_corners_2d_one_objH.conservativeResize(4*valid_config_number_one_objH,NoChange);\n\t\t\t\t\t\t}\n\t\t      \t\t} //end of config loop\t两种情形.\n\t\t  \t\t} //end of top id\t上边缘采样点.\n\t      \t} //end of yaw\t采样的yaw角.\n\t      \n\t\t\t// std::cout << \"valid_config_number_one_hseight  \" << valid_config_number_one_objH << std::endl;\n\t\t\t// std::cout << \"all_configs_error_one_objH  \\n\" << all_configs_error_one_objH.topRows(valid_config_number_one_objH) << std::endl;\n\t\t\t// MatrixXd all_corners = all_box_corners_2d_one_objH.topRows(2*valid_config_number_one_objH);\n\t\t\t// std::cout<<\"all corners   \"<<all_corners<<std::endl;\n\n\t\t\t// STEP 计算距离-角度的综合得分：normalized_score，和有效的提案ID：good_proposal_ids.\n\t\t\tVectorXd normalized_score; \n\t\t\tvector<int> good_proposal_ids;\n\t\t\tfuse_normalize_scores_v2(\tall_configs_error_one_objH.col(4).head(valid_config_number_one_objH), \t/* 距离误差 */\n\t\t\t\t\t\t\t\t\t\tall_configs_error_one_objH.col(5).head(valid_config_number_one_objH),\t/* 角度误差 */\n\t\t\t\t\t\t\t\t\t\tnormalized_score, \t\t\t\t/* 综合得分 */\n\t\t\t\t\t\t\t\t\t\tgood_proposal_ids, \t\t\t\t/* 最终纳入计算的测量的ID */\n\t\t\t\t\t\t\t\t\t\tweight_vp_angle,\t\t\t\t/* 角度误差的权重 */\n\t\t\t\t\t\t\t\t\t\twhether_normalize_two_errors);\t/* 是否归一化两个误差 */\n\n\t\t\t// 遍历所有有效的提案.\n\t\t\tfor (int box_id = 0; box_id < good_proposal_ids.size(); box_id++)\n\t\t\t{\n\t\t\t\tint raw_cube_ind = good_proposal_ids[box_id];\n\t\t\t\t// 对相机的 roll 和 pitch 角进行采样.\n\t\t\t\tif (whether_sample_cam_roll_pitch)\n\t\t\t\t{\n\t\t\t\t\tMatrix4d transToWolrd_new = transToWolrd;\n\t\t\t\t\t// 将当前旋转转换成角度值.\n\t\t\t\t\ttransToWolrd_new.topLeftCorner<3,3>() = euler_zyx_to_rot<double>(all_configs_error_one_objH(raw_cube_ind,7), \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t all_configs_error_one_objH(raw_cube_ind,8), \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t cam_pose_raw.euler_angle(2));\n\t\t\t\t\tset_cam_pose(transToWolrd_new);\n\t\t\t\t\t// 相机系下的地平面\n\t\t\t\t\tground_plane_sensor = cam_pose.transToWolrd.transpose()*ground_plane_world;\n\t\t\t\t}\n\n\t\t\t\t// NOTE 计算立方体对象sample_obj.\n\t\t  \t\tcuboid* sample_obj = new cuboid();\n\t\t  \t\tchange_2d_corner_to_3d_object(\tall_box_corners_2d_one_objH.block(2*raw_cube_ind,0,2,8), /* 8 个点的 2D 坐标*/\n\t\t\t\t  \t\t\t\t\t\t\t\tall_configs_error_one_objH.row(raw_cube_ind).head<3>(),\t /* 模式，vp1的位置，偏航角*/\n\t\t\t\t\t\t\t\t\t\t\t\tground_plane_sensor,  \t\t\t\t\t/* 法平面？*/\n\t\t\t\t\t\t\t\t\t\t\t\tcam_pose.transToWolrd, \t\t\t\t\t/* 相机旋转 */\n\t\t\t\t\t\t\t\t\t\t\t\tcam_pose.invK, \t\t\t\t\t\t\t/* 相机内参的逆矩阵 */\n\t\t\t\t\t\t\t\t\t\t\t\tcam_pose.projectionMatrix,\t\t\t\t/* 投影矩阵 */\n\t\t\t\t\t\t\t\t\t\t\t\t*sample_obj);\t\t\t\t\t\t\t/* 3D提案 */\n\t\t\t\t// 输出提案的具体信息.\n\t\t\t\t// sample_obj->print_cuboid();\n\t\t\t\t/*\n\t\t\t\tprinting cuboids info....\n\t\t\t\t【pos】     -1.58339 0.373187 0.300602\n\t\t\t\t【scale】   0.155737 0.436576 0.300602\n\t\t\t\t【rotY】    -2.90009\n\t\t\t\t【box_config_type】   1  1\n\t\t\t\t【box_corners_2d】 \n\t\t\t\t503 279 213 430 559 261 174 459\n\t\t\t\t245 396 319 200  56 184 116  23\n\t\t\t\t【box_corners_3d_world】 \n\t\t\t\t-1.6302   -1.83902   -1.53659   -1.32776    -1.6302   -1.83902   -1.53659   -1.32776\n\t\t\t\t-0.087966   0.759848    0.83434 -0.0134734  -0.087966   0.759848    0.83434 -0.0134734\n\t\t\t\t\t\t0          0          0          0   0.601204   0.601204   0.601204   0.601204\n\t\t\t\t*/\n\t\t\t\t\n\t\t\t\t// 保证尺度为正.\n\t\t\t\tif ((sample_obj->scale.array() < 0).any())     \n\t\t\t\t\tcontinue;                        // scale should be positive\n\t\t\t\t\n\t\t\t\t// STEP 存储对象的信息.\n\t\t\t\t// 2D 检测框.\n\t\t\t\tsample_obj->rect_detect_2d =  Vector4d(left_x_raw, top_y_raw, obj_width_raw, obj_height_raw);\n\t\t\t\t// 边缘误差.\n\t\t\t\tsample_obj->edge_distance_error = all_configs_error_one_objH(raw_cube_ind,4); // record the original error\n\t\t\t\t// 角度误差.\n\t\t\t\tsample_obj->edge_angle_error = all_configs_error_one_objH(raw_cube_ind,5);\n\t\t\t\t// 归一化误差.\n\t\t\t\tsample_obj->normalized_error = normalized_score(box_id);\n\t\t\t\t// NOTE 歪斜比：长/宽.\n\t\t\t\t// head(2).maxCoeff()：尺度的前两项xy中较大者：长\n\t\t\t\t// head(2).minCoeff()：尺度的前两项xy中较小者：宽\n\t\t\t\tdouble skew_ratio = sample_obj->scale.head(2).maxCoeff()/sample_obj->scale.head(2).minCoeff();\n\t\t\t\tsample_obj->skew_ratio = skew_ratio;\n\t\t\t\t// 是否对高度进行了采样？ 0,10,20.\n\t\t\t\tsample_obj->down_expand_height = all_configs_error_one_objH(raw_cube_ind,6);\n\n\t\t\t\t// 如果对相机的 roll 和 pitch 角进行采样.用采样得到的角-相机的原始角度.（否则直接使用相机的角度，角度差为0）\n\t\t\t\t// 保存 roll 和 pitch 角的【角度差】.\n\t\t\t\tif (whether_sample_cam_roll_pitch)\n\t\t\t\t{\n\t\t\t\t\tsample_obj->camera_roll_delta = all_configs_error_one_objH(raw_cube_ind,7) - cam_pose_raw.euler_angle(0);\n\t\t\t\t\tsample_obj->camera_pitch_delta = all_configs_error_one_objH(raw_cube_ind,8) - cam_pose_raw.euler_angle(1);\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{   \n\t\t\t\t\tsample_obj->camera_roll_delta = 0;\n\t\t\t\t\tsample_obj->camera_pitch_delta = 0; }\n\t\t\t\t\traw_obj_proposals.push_back(sample_obj);\n\t\t\t\t}\n\t  \t\t} // end of differnet object height sampling\n\n\t\t\t// STEP 最后对所有提案进行排名（归一化误差+歪斜比）\n\t\t\t// %finally rank all proposals. [normalized_error   skew_error]\n\t\t\t// 准确提案的数量 1 ？0？\n\t\t\tint actual_cuboid_num_small = std::min(max_cuboid_num, (int)raw_obj_proposals.size());\n\n\t\t\tVectorXd all_combined_score(raw_obj_proposals.size());\n\n\t\t\t// 计算总体误差\n\t\t\tfor (int box_id = 0; box_id < raw_obj_proposals.size(); box_id++)\n\t\t\t{\n\t\t\t\tcuboid* sample_obj = raw_obj_proposals[box_id];\n\t\t\t\t// 计算歪斜比误差 skew_ratio - 1，要求大于0\n\t\t\t\tdouble skew_error = weight_skew_error*std::max(sample_obj->skew_ratio - nominal_skew_ratio,0.0);\n\t\t\t\t\n\t\t\t\t// TODO 若大于最大歪斜比 3 ，则误差为100\n\t\t\t\tif (sample_obj->skew_ratio > max_cut_skew)\n\t\t\t\t\tskew_error = 100;\n\n\t\t\t\t// NOTE 新的误差：距离+角度+歪斜比误差\n\t\t\t\tdouble new_combined_error = sample_obj->normalized_error + weight_skew_error*skew_error;\t// TODO 这里还乘了一个权重？前面也乘了.\n\t\t\t\tall_combined_score(box_id) = new_combined_error;\n\t\t\t}\n\t  \n\t  \t\t// STEP 保留误差最小的提案.\n\t  \t\t// 提案的索引（ID）并从 0 开始递增赋值.\n\t\t\tstd::vector<int> sort_idx_small(all_combined_score.rows());   \n\t\t\tiota(sort_idx_small.begin(), sort_idx_small.end(), 0);\n\n\t\t\t// 对 all_combined_score 的前 actual_cuboid_num_small（1） 项进行递增.\n\t\t\tsort_indexes(\tall_combined_score, \t\t/* 检索比较的序列 */\n\t\t\t\t\t\t\tsort_idx_small,\t\t\t\t/* 按照all_combined_score中误差从小到达排序误差对应的ID */\n\t\t\t\t\t\t\tactual_cuboid_num_small);\n\n\t\t\tfor (int ii = 0; ii < actual_cuboid_num_small; ii++) // use sorted index\n\t\t\t{\n\t\t\t\tall_object_cuboids[object_id].push_back(raw_obj_proposals[sort_idx_small[ii]]);\n\t\t\t\t//std::cout << \"sort_idx_small[ii]：\" << sort_idx_small[ii] << std::endl;\n\t\t\t}\n\t\t\tca::Profiler::tictoc(\"One 3D object total time\"); \n\t}// end of different objects\n\t\t\n\t\t// STEP 绘制最终图案，保存结果.\n\t\tif (whether_plot_final_images || whether_save_final_images)\n\t\t{\n\t\t\tcv::Mat frame_all_cubes_img = rgb_img.clone();\n\t\t\tfor (int object_id = 0; object_id < all_object_cuboids.size(); object_id++)\n\t\t\t{\tif ( all_object_cuboids[object_id].size()>0 )\n\t\t\t\t{\t\n\t\t\t\t\t// NOTE 绘制提案.\n\t\t\t\t\tplot_image_with_cuboid(frame_all_cubes_img, all_object_cuboids[object_id][0]);\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (whether_save_final_images)\n\t\t\t\tcuboids_2d_img = frame_all_cubes_img;\n\t\t\tif (whether_plot_final_images)\n\t\t\t{\n\t\t\t\tcv::imshow(\"frame_all_cubes_img\", frame_all_cubes_img);\t \n\t\t\t\tcv::waitKey(0);\n\t\t\t}\n\t\t}\n}\n\n\n", "meta": {"hexsha": "59d4bb70c9e03013e0f56d5f5c113287b95b7ebc", "size": 37380, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "detect_3d_cuboid/src/box_proposal_detail.cpp", "max_stars_repo_name": "sdkmsdn/Cube_SLAM_wu", "max_stars_repo_head_hexsha": "b14219c13cfc91310de08f45079ee179379f197d", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 113.0, "max_stars_repo_stars_event_min_datetime": "2019-01-29T12:11:32.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-05T13:52:28.000Z", "max_issues_repo_path": "detect_3d_cuboid/src/box_proposal_detail.cpp", "max_issues_repo_name": "sdkmsdn/Cube_SLAM_wu", "max_issues_repo_head_hexsha": "b14219c13cfc91310de08f45079ee179379f197d", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2019-05-22T10:49:19.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-16T06:41:39.000Z", "max_forks_repo_path": "detect_3d_cuboid/src/box_proposal_detail.cpp", "max_forks_repo_name": "wuxiaolang/Cube_SLAM_wu", "max_forks_repo_head_hexsha": "e73808b4d06f3be36172b6e8ec0eaa53c4761713", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 29.0, "max_forks_repo_forks_event_min_datetime": "2019-02-11T12:10:39.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-02T03:20:40.000Z", "avg_line_length": 43.2638888889, "max_line_length": 207, "alphanum_fraction": 0.6687265918, "num_tokens": 14186, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6654105454764747, "lm_q2_score": 0.45713671682749485, "lm_q1q2_score": 0.3041835921015081}}
{"text": "// __BEGIN_LICENSE__\n// Copyright (C) 2006-2010 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//\n#include <vw/Camera/CAHVModel.h>\n#include <boost/algorithm/string.hpp>\n\nnamespace vw {\nnamespace camera {\n\n  // FIXME -- Double check anything related to PinholeModel\n  CAHVModel CAHVModel::operator= (PinholeModel const& pin_model) {\n\n    //  Pinhole model parameters (in pixel units)\n    double fH, fV, Hc, Vc;\n    pin_model.intrinsic_parameters(fH, fV, Hc, Vc);\n\n    //  Unit vectors defining camera coordinate frame\n    Vector3 u,v,w;\n    pin_model.coordinate_frame(u,v,w);\n\n    //  The true rotation between world and camera coordinate\n    //  frames includes the rotation R --AND-- a rotation from\n    //  specifying the directions of increasing u,v,w pixels\n    Matrix<double,3,3> R = pin_model.camera_pose().rotation_matrix();\n\n    //  Now create the components of the CAHV model...\n    Vector3 Hvec = R*u;\n    Vector3 Vvec = R*v;\n\n    C = pin_model.camera_center();\n    A = R*w;\n    H = fH*Hvec + Hc*A;\n    V = fV*Vvec + Vc*A;\n\n    return *this;\n  }\n\n\n  /// This constructor takes a filename and reads in a camera model\n  /// from the file.  The file may contain either CAHV parameters or\n  /// pinhole camera parameters.\n  CAHVModel::CAHVModel(std::string const& filename) {\n    if (filename.empty())\n      vw_throw( IOErr() << \"CAHVModel: null file name passed to constructor.\" );\n\n    if (boost::ends_with(filename, \".cahv\"))\n      read_cahv(filename);\n    else if (boost::ends_with(filename, \".pin\"))\n      read_pinhole(filename);\n    else\n      vw_throw( IOErr() << \"CAHVModel: Unknown camera file suffix.\" );\n  }\n\n  Vector2 CAHVModel::point_to_pixel(Vector3 const& point) const {\n    double dDot = dot_prod(point-C, A);\n    return Vector2( dot_prod(point-C, H) / dDot,\n                    dot_prod(point-C, V) / dDot );\n  }\n\n  Vector3 CAHVModel::pixel_to_vector(Vector2 const& pix) const {\n    Vector3 va, vb;\n\n    // Vertical component in a plane perpendicular to the vector\n    va = V + (-(pix.y()) * A);\n\n    // Horizontal component in a plane perpendicular to the vector\n    vb = H + (-(pix.x()) * A);\n\n    // Find vector\n    Vector3 vec = cross_prod(va, vb);\n\n    // Normalize vector\n    vec *= 1.0 / norm_2(vec);\n\n    // The vector VxH should be pointing in the same directions as A,\n    // if it isn't (because we have a left handed system), flip the\n    // vector.\n    Vector3 temp = cross_prod(V, H);\n    if (dot_prod(temp, A) < 0.0){\n      vec *= -1.0;\n      //cout << \"CAHV PixelToVector changed sign of vec\" << endl;\n    }\n    return vec;\n  }\n\n  // --------------------------------------------------\n  //                 Private Methods\n  // --------------------------------------------------\n  void CAHVModel::read_cahv(std::string const& filename) {\n\n    FILE *cahvFP = fopen(filename.c_str(), \"r\");\n    if (cahvFP == 0)\n      vw_throw( IOErr() << \"CAHVModel::read_cahv: Could not open file\\n\" );\n\n    char line[4096];\n\n    // Scan through comments\n    fgets(line, sizeof(line), cahvFP);\n    while(line[0] == '#')\n      fgets(line, sizeof(line), cahvFP);\n\n    if (sscanf(line,\"C = %lf %lf %lf\", &C(0), &C(1), &C(2)) != 3) {\n      vw_throw( IOErr() << \"CAHVModel::read_CAHV: Could not read C vector\\n\" );\n      fclose(cahvFP);\n    }\n\n    fgets(line, sizeof(line), cahvFP);\n    if (sscanf(line,\"A = %lf %lf %lf\", &A(0),&A(1), &A(2)) != 3) {\n      vw_throw( IOErr() << \"CAHVModel::read_CAHV: Could not read A vector\\n\" );\n      fclose(cahvFP);\n    }\n\n    fgets(line, sizeof(line), cahvFP);\n    if (sscanf(line,\"H = %lf %lf %lf\", &H(0), &H(1), &H(2)) != 3) {\n      vw_throw( IOErr() << \"CAHVModel::read_CAHV: Could not read H vector\\n\" );\n      fclose(cahvFP);\n    }\n\n    fgets(line, sizeof(line), cahvFP);\n    if (sscanf(line,\"V = %lf %lf %lf\", &V(0), &V(1), &V(2)) != 3) {\n      vw_throw( IOErr() << \"CAHVModel::read_CAHV: Could not read V vector\\n\" );\n      fclose(cahvFP);\n    }\n\n    fclose(cahvFP);\n  }\n\n  void CAHVModel::read_pinhole(std::string const& filename) {\n    FILE *camFP = fopen(filename.c_str(), \"r\");\n\n    if (camFP == 0)\n      vw_throw( IOErr() << \"CAHVModel::read_pinhole: Could not open file\\n\" );\n\n    char line[2048];\n    double f, fH, fV, Hc, Vc;\n    Vector2 pixelSize;\n    Vector3 Hvec, Vvec;\n\n    // Read intrinsic parameters\n    fgets(line, sizeof(line), camFP);\n    if (sscanf(line,\"f = %lf\", &f) != 1) {\n      vw_throw( IOErr() << \"CAHVModel::read_pinhole: Could not read focal length\\n\" );\n      fclose(camFP);\n    }\n\n    fgets(line, sizeof(line), camFP);\n    if (sscanf(line,\"SP = %lf %lf\", &pixelSize.x(), &pixelSize.y()) != 2) {\n      vw_throw( IOErr() << \"CAHVModel::read_pinhole: Could not read pixel size\\n\" );\n      fclose(camFP);\n    }\n\n    fgets(line, sizeof(line), camFP);\n    if (sscanf(line,\"IC = %lf %lf\", &Hc, &Vc) != 2) {\n      vw_throw( IOErr() << \"CAHVModel::ReadPinhole: Could not read image center pos\\n\" );\n      fclose(camFP);\n    }\n\n    // Read extrinsic parameters\n    fgets(line, sizeof(line), camFP);\n    if (sscanf(line,\"C = %lf %lf %lf\", &C(0), &C(1), &C(2)) != 3) {\n      vw_throw( IOErr() << \"CAHVModel::read_pinhole: Could not read C vector\\n\" );\n      fclose(camFP);\n    }\n\n    fgets(line, sizeof(line), camFP);\n    if (sscanf(line,\"A = %lf %lf %lf\", &A(0), &A(1), &A(2)) != 3) {\n      vw_throw( IOErr() << \"CAHVModel::read_pinhole: Could not read A vector\\n\" );\n      fclose(camFP);\n    }\n\n    fgets(line, sizeof(line), camFP);\n    if (sscanf(line,\"Hv = %lf %lf %lf\", &Hvec(0), &Hvec(1), &Hvec(2)) != 3) {\n      vw_throw( IOErr() << \"CAHVModel::read_pinhole: Could not read Hvec\\n\" );\n      fclose(camFP);\n    }\n\n    fgets(line, sizeof(line), camFP);\n    if (sscanf(line,\"Vv = %lf %lf %lf\", &Vvec(0), &Vvec(1), &Vvec(2)) != 3) {\n      vw_throw( IOErr() << \"CAHVModel::read_pinhole: Could not read Vvec\\n\" );\n      fclose(camFP);\n    }\n\n    // In the future, we should also read in a view matrix -- LJE\n    //     double dummy\n    //     if (sscanf(line, \"VM = %lf %lf %lf %f %lf %lf %lf %f \"\n    //        \"%lf %lf %lf %f %lf %lf %lf %f \",\n    //        &Hvec(0), &Hvec(1), &Hvec(2), &dummy,\n    //        &Vvec(0), &Vvec(1), &Vvec(2), &dummy,\n    //        &A(0), &A(1), &A(2), &dummy,\n    //        &C(0), &C(1), &C(2), &dummy) != 16)\n    //     {\n    //       vw_throw( IOErr()\n    //  << \"CAHVModel::ReadPinhole: Could not read view matrix\\n\" );\n    //       fclose(camFP);\n    //     }\n\n    fH = f/pixelSize.x();\n    fV = f/pixelSize.y();\n\n    H = fH*Hvec + Hc*A;\n    V = fV*Vvec + Vc*A;\n\n    fclose(camFP);\n  }\n\n\n  // This is a re-implementation of the Epipolar math that is easier\n  // to read, however it disagrees with the other epipolar code below\n  // slightly.  It needs another look to clean up this discrepancy,\n  // which is due to the direction chosen for Hvec. -mbroxton\n\n//   void epipolar(CAHVModel const src_camera0, CAHVModel const src_camera1,\n//                 CAHVModel &dst_camera0, CAHVModel &dst_camera1) {\n\n//     double fh, fv, hc, vc;\n//     Vector3 f, g;\n//     Vector3 A, H, V;\n\n//     // Compute a common image center and scale for the two models\n//     hc = dot_prod(src_camera0.H, src_camera0.A) / 2.0 + dot_prod(src_camera1.H, src_camera1.A) / 2.0;\n//     vc = dot_prod(src_camera0.V, src_camera0.A) / 2.0 + dot_prod(src_camera1.V, src_camera1.A) / 2.0;\n\n//     // Find the magnitude of the new H and V vectors (this will be the\n//     // average of the focal lengths of these cameras).\n//     f = cross_prod(src_camera0.A, src_camera0.H);\n//     g = cross_prod(src_camera1.A, src_camera1.H);\n//     fh = (norm_2(f) + norm_2(g)) / 2.0;\n\n//     f = cross_prod(src_camera0.A, src_camera0.V);\n//     g = cross_prod(src_camera1.A, src_camera1.V);\n//     fv = (norm_2(f) + norm_2(g)) / 2.0;\n\n//     // Use common center and scale to construct an average A vector\n//     Vector3 A_avg  = 0.5 * (src_camera0.A + src_camera1.A);\n\n//     // Then adjust A to be perpindicular to the baseline between the\n//     // two imagers.  This will move the epipoles to infinity.\n//     Vector3 Hvec = normalize(src_camera1.C - src_camera0.C);\n//     Vector3 Vvec = normalize(cross_prod(Hvec,A_avg));\n//     A = normalize(cross_prod(Vvec,Hvec));\n\n//     std::cout << \"Fh: \" << fh << \"   Fv: \" << fv << \"\\n\";\n//     std::cout << \"Ch: \" << hc << \"   Cv: \" << vc << \"\\n\";\n//     std::cout << \"Hvec: \" << Hvec << \"   Vvec: \" << Vvec << \"\\n\";\n\n//     // Use the standard equations for the epipolar camera model to\n//     // determine H and V given the camera intristics and the\n//     // horizontal and vertical vectors.\n//     H = fh*Hvec + hc*A;\n//     V = fv*Vvec + vc*A;\n\n//     dst_camera0.C = src_camera0.C;\n//     dst_camera0.A = A;\n//     dst_camera0.H = H;\n//     dst_camera0.V = V;\n\n//     dst_camera1.C = src_camera1.C;\n//     dst_camera1.A = A;\n//     dst_camera1.H = H;\n//     dst_camera1.V = V;\n//   }\n\n  void epipolar(CAHVModel const src_camera0, CAHVModel const src_camera1,\n                CAHVModel &dst_camera0, CAHVModel &dst_camera1) {\n\n    double hs, hc, vs, vc;\n    Vector3 f, g, hp, ap, app, vp;\n    Vector3 a, h, v;\n\n    // Compute a common image center and scale for the two models\n    hc = dot_prod(src_camera0.H, src_camera0.A) / 2.0 + dot_prod(src_camera1.H, src_camera1.A) / 2.0;\n    vc = dot_prod(src_camera0.V, src_camera0.A) / 2.0 + dot_prod(src_camera1.V, src_camera1.A) / 2.0;\n\n    f = cross_prod(src_camera0.A, src_camera0.H);\n    g = cross_prod(src_camera1.A, src_camera1.H);\n    hs = (norm_2(f) + norm_2(g)) / 2.0;\n\n    f = cross_prod(src_camera0.A, src_camera0.V);\n    g = cross_prod(src_camera1.A, src_camera1.V);\n    vs = (norm_2(f) + norm_2(g)) / 2.0;\n\n    // Use common center and scale to construct common A, H, V\n    app  = src_camera0.A + src_camera1.A;\n\n    // Note the directionality of f here, for consistency later\n    f = src_camera1.C - src_camera0.C;\n    g = cross_prod(app, f); // alter f (CxCy) to be\n    f = cross_prod(g, app); // perpendicular to average A\n\n    if (dot_prod(f, src_camera0.H) > 0)\n      hp = f * hs / (norm_2(f));\n    else\n      hp = -f * hs / (norm_2(f));\n\n    app = 0.5 * app;\n    g = hp * dot_prod(app,hp) / (hs * hs);\n    ap = app -g;\n    a = ap/norm_2(ap);\n    f = cross_prod(a, hp);\n    vp = f * vs / hs;\n    f = hc * a;\n    h = hp + f;\n\n    f = vc * a;\n    v = vp + f;\n\n    dst_camera0.C = src_camera0.C;\n    dst_camera0.A = a;\n    dst_camera0.H = h;\n    dst_camera0.V = v;\n\n    dst_camera1.C = src_camera1.C;\n    dst_camera1.A = a;\n    dst_camera1.H = h;\n    dst_camera1.V = v;\n  }\n\n}} // namespace vw::camera\n", "meta": {"hexsha": "9dd6bcc1157ef186c8e4a78957aaeec277274e4b", "size": 10603, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/vw/Camera/CAHVModel.cc", "max_stars_repo_name": "tkeemon/visionworkbench", "max_stars_repo_head_hexsha": "df59fcb31191e1fc4fecfe1901963da1614a52b1", "max_stars_repo_licenses": ["NASA-1.3"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-06-02T04:06:43.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-02T04:06:43.000Z", "max_issues_repo_path": "src/vw/Camera/CAHVModel.cc", "max_issues_repo_name": "tkeemon/visionworkbench", "max_issues_repo_head_hexsha": "df59fcb31191e1fc4fecfe1901963da1614a52b1", "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/CAHVModel.cc", "max_forks_repo_name": "tkeemon/visionworkbench", "max_forks_repo_head_hexsha": "df59fcb31191e1fc4fecfe1901963da1614a52b1", "max_forks_repo_licenses": ["NASA-1.3"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.725308642, "max_line_length": 104, "alphanum_fraction": 0.5826652834, "num_tokens": 3381, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6825737473266735, "lm_q2_score": 0.4455295350395727, "lm_q1q2_score": 0.30410676427667166}}
{"text": "/*\n * Implementation of EDM methods, including S-map and cross-mapping\n *\n * - Patrick Laub, Department of Management and Marketing,\n *   The University of Melbourne, patrick.laub@unimelb.edu.au\n * - Edoardo Tescari, Melbourne Data Analytics Platform,\n *  The University of Melbourne, e.tescari@unimelb.edu.au\n *\n */\n\n#pragma warning(disable : 4018)\n\n#include \"edm.h\"\n#include \"cpu.h\"\n#include \"distances.h\"\n#include \"library_prediction_split.h\"\n#include \"stats.h\" // for correlation and mean_absolute_error\n#include \"thread_pool.h\"\n\n#ifndef FMT_HEADER_ONLY\n#define FMT_HEADER_ONLY\n#endif\n\n#define EIGEN_NO_DEBUG\n#define EIGEN_DONT_PARALLELIZE\n#include <Eigen/SVD>\n#include <algorithm> // std::partial_sort\n#include <chrono>\n#include <cmath>\n\n#if defined(DUMP_LOW_LEVEL_INPUTS) || defined(WITH_ARRAYFIRE)\n#include <fstream>\n#include <iostream>\n#endif\n\n#if defined(WITH_ARRAYFIRE)\n#include <af/macros.h>\n#include <arrayfire.h>\n#if WITH_GPU_PROFILING\n#include <nvtx3/nvToolsExt.h>\n#endif\n#endif\n\nusing MatrixXd = Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>;\nusing MatrixXi = Eigen::Matrix<int, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>;\n\nPredictionResult edm_task(const std::shared_ptr<ManifoldGenerator> generator, Options opts, int E,\n                          const std::vector<bool>& libraryRows, const std::vector<bool> predictionRows, IO* io,\n                          bool keep_going(), void all_tasks_finished());\n\nvoid make_prediction(int Mp_i, const Options& opts, const Manifold& M, const Manifold& Mp,\n                     Eigen::Map<MatrixXd> predictionsView, Eigen::Map<MatrixXi> rcView, Eigen::Map<MatrixXd> coeffsView,\n                     int* kUsed, bool keep_going());\n\nDistanceIndexPairs k_nearest_neighbours(const DistanceIndexPairs& potentialNeighbours, int k);\n\nvoid simplex_prediction(int Mp_i, int t, const Options& opts, const Manifold& M, const std::vector<double>& dists,\n                        const std::vector<int>& kNNInds, Eigen::Map<MatrixXd> predictionsView,\n                        Eigen::Map<MatrixXi> rcView);\n\nvoid smap_prediction(int Mp_i, int t, const Options& opts, const Manifold& M, const Manifold& Mp,\n                     const std::vector<double>& dists, const std::vector<int>& kNNInds,\n                     Eigen::Map<MatrixXd> predictionsView, Eigen::Map<MatrixXd> coeffsView,\n                     Eigen::Map<MatrixXi> rcView);\n\n#if defined(WITH_ARRAYFIRE)\nvoid af_make_prediction(const int numPredictions, const Options& opts, const Manifold& hostM, const Manifold& hostMp,\n                        const ManifoldOnGPU& M, const ManifoldOnGPU& Mp, const af::array& metricOpts,\n                        Eigen::Map<MatrixXd> ystar, Eigen::Map<MatrixXi> rc, Eigen::Map<MatrixXd> coeffs,\n                        std::vector<int>& kUseds, bool keep_going());\n#endif\n\nstd::atomic<int> totalNumPredictions = 0;\nstd::atomic<int> estimatedTotalNumPredictions = 0;\n\nstd::atomic<int> numPredictionsFinished = 0;\nstd::atomic<int> numTasksFinished = 0;\n\n#ifdef _WIN32\n// Must leak resource, because windows + R deadlock otherwise. Memory\n// is released on shutdown.\nThreadPool* workerPoolPtr = new ThreadPool(0);\nThreadPool* taskRunnerPoolPtr = new ThreadPool(0);\n#else\nThreadPool workerPool(0), taskRunnerPool(0);\nThreadPool* workerPoolPtr = &workerPool;\nThreadPool* taskRunnerPoolPtr = &taskRunnerPool;\n#endif\n\nstd::vector<std::future<PredictionResult>> launch_task_group(\n  const std::shared_ptr<ManifoldGenerator> generator, Options opts, const std::vector<int>& Es,\n  const std::vector<int>& libraries, int k, int numReps, int crossfold, bool explore, bool full, bool shuffle,\n  bool saveFinalPredictions, bool saveFinalCoPredictions, bool saveSMAPCoeffs, bool copredictMode,\n  const std::vector<bool>& usable, const std::string& rngState, IO* io, bool keep_going(), void all_tasks_finished())\n{\n  static bool initOnce = [&]() {\n#if defined(WITH_ARRAYFIRE)\n    af::setMemStepSize(1024 * 1024 * 5);\n    taskRunnerPoolPtr->set_num_workers(1); // Avoid oversubscribing to the GPU\n#else\n    taskRunnerPoolPtr->set_num_workers(1);\n#endif\n    return true;\n  }();\n\n  workerPoolPtr->set_num_workers(opts.nthreads);\n\n  // Construct the instance which will (repeatedly) split the data\n  // into either the library set or the prediction set.\n  LibraryPredictionSetSplitter splitter(explore, full, shuffle, crossfold, usable, rngState);\n\n  int numLibraries = (explore ? 1 : libraries.size());\n\n  // Note: the 'numIters' either refers to the 'replicate' option\n  // used for bootstrap resampling, or the 'crossfold' number of\n  // cross-validation folds. Both options can't be used together.\n  int numIters = numReps > crossfold ? numReps : crossfold;\n\n  opts.explore = explore;\n  opts.numTasks = numIters * Es.size() * numLibraries;\n  opts.configNum = 0;\n  opts.taskNum = 0;\n  opts.saveKUsed = true;\n\n  int maxE = Es[Es.size() - 1];\n\n  std::vector<bool> cousable;\n\n  if (copredictMode) {\n    opts.numTasks *= 2;\n    cousable = generator->generate_usable(maxE, true);\n  }\n\n  int E, kAdj, library, librarySize;\n\n  std::vector<std::future<PredictionResult>> futures;\n\n  bool newLibraryPredictionSplit = true;\n\n  for (int iter = 1; iter <= numIters; iter++) {\n    if (explore) {\n      newLibraryPredictionSplit = true;\n      librarySize = splitter.next_library_size(iter);\n    }\n\n    if (keep_going != nullptr && !keep_going()) {\n      break;\n    }\n\n    for (int i = 0; i < Es.size(); i++) {\n      E = Es[i];\n\n      // 'libraries' is implicitly set to one value in explore mode\n      // though in xmap mode it is a user-supplied list which we loop over.\n      for (int l = 0; l == 0 || l < libraries.size(); l++) {\n        if (!explore) {\n          newLibraryPredictionSplit = true;\n        }\n\n        if (explore) {\n          library = librarySize;\n        } else {\n          library = libraries[l];\n        }\n\n        // Set the number of neighbours to use\n        if (k > 0) {\n          kAdj = k;\n        } else if (k < 0) {\n          kAdj = -1; // Leave a sentinel value so we know to skip the nearest neighbours calculation\n        } else if (k == 0) {\n          bool isSMap = opts.algorithm == Algorithm::SMap;\n          int defaultK = generator->E_actual(E) + 1 + isSMap;\n          kAdj = defaultK < library ? defaultK : library;\n        }\n\n        bool lastConfig = (E == maxE) && (l + 1 == numLibraries);\n\n        if (explore) {\n          opts.savePrediction = saveFinalPredictions && ((iter == numReps) || (crossfold > 0)) && lastConfig;\n        } else {\n          opts.savePrediction = saveFinalPredictions && (iter == numReps) && lastConfig;\n        }\n        opts.saveSMAPCoeffs = saveSMAPCoeffs;\n\n        if (newLibraryPredictionSplit) {\n          splitter.update_library_prediction_split(library, iter);\n          newLibraryPredictionSplit = false;\n        }\n\n        opts.copredict = false;\n        opts.k = kAdj;\n        opts.library = library;\n\n        futures.emplace_back(\n          taskRunnerPoolPtr->enqueue([generator, opts, E, splitter, io, keep_going, all_tasks_finished] {\n            return edm_task(generator, opts, E, splitter.libraryRows(), splitter.predictionRows(), io, keep_going,\n                            all_tasks_finished);\n          }));\n\n        opts.taskNum += 1;\n\n        if (copredictMode) {\n          opts.copredict = true;\n          if (explore) {\n            opts.savePrediction = saveFinalCoPredictions && ((iter == numReps) || (crossfold > 0)) && lastConfig;\n          } else {\n            opts.savePrediction = saveFinalCoPredictions && ((iter == numReps)) && lastConfig;\n          }\n          opts.saveSMAPCoeffs = false;\n\n          futures.emplace_back(\n            taskRunnerPoolPtr->enqueue([generator, opts, E, splitter, cousable, io, keep_going, all_tasks_finished] {\n              return edm_task(generator, opts, E, splitter.libraryRows(), cousable, io, keep_going, all_tasks_finished);\n            }));\n\n          opts.taskNum += 1;\n        }\n\n        opts.configNum += opts.thetas.size();\n      }\n    }\n  }\n\n  return futures;\n}\n\nPredictionResult edm_task(const std::shared_ptr<ManifoldGenerator> generator, Options opts, int E,\n                          const std::vector<bool>& libraryRows, const std::vector<bool> predictionRows, IO* io,\n                          bool keep_going(), void all_tasks_finished())\n{\n  opts.metrics = expand_metrics(*generator, E, opts.distance, opts.metrics);\n\n  if (opts.taskNum == 0) {\n    numPredictionsFinished = 0;\n    numTasksFinished = 0;\n\n    totalNumPredictions = 0;\n    estimatedTotalNumPredictions = 0;\n  }\n\n#ifdef DUMP_LOW_LEVEL_INPUTS\n  // This hack is simply to dump some really low level data structures\n  // purely for the purpose of generating microbenchmarks.\n  if (io != nullptr && io->verbosity > 4) {\n    json lowLevelInputDump;\n    lowLevelInputDump[\"generator\"] = *generator;\n    lowLevelInputDump[\"opts\"] = opts;\n    lowLevelInputDump[\"E\"] = E;\n    lowLevelInputDump[\"libraryRows\"] = libraryRows;\n    lowLevelInputDump[\"predictionRows\"] = predictionRows;\n\n    std::ofstream o(\"lowLevelInputDump.json\");\n    o << lowLevelInputDump << std::endl;\n  }\n#endif\n\n  Manifold M(generator, E, libraryRows, false, opts.copredict, opts.lowMemoryMode);\n  Manifold Mp(generator, E, predictionRows, true, opts.copredict, opts.lowMemoryMode);\n\n  bool multiThreaded = opts.nthreads > 1;\n\n#if defined(WITH_ARRAYFIRE)\n  af::setDevice(0); // TODO potentially can cycle through GPUS if > 1\n\n  // Char is the internal representation of bool in ArrayFire\n  std::vector<char> mopts;\n  for (int j = 0; j < M.E_actual(); j++) {\n    mopts.push_back(opts.metrics[j] == Metric::Diff);\n  }\n\n  af::array metricOpts(M.E_actual(), mopts.data());\n\n  const ManifoldOnGPU gpuM = M.toGPU(false);\n  const ManifoldOnGPU gpuMp = Mp.toGPU(false);\n\n  constexpr bool useAF = true;\n  multiThreaded = multiThreaded && !useAF;\n#endif\n\n  int numThetas = (int)opts.thetas.size();\n  int numPredictions = Mp.numPoints();\n  int numCoeffCols = M.E_actual() + 1;\n\n  totalNumPredictions += numPredictions;\n  estimatedTotalNumPredictions = (opts.numTasks / (1.0 + opts.taskNum)) * totalNumPredictions;\n\n  auto predictions = std::make_unique<double[]>(numThetas * numPredictions);\n  std::fill_n(predictions.get(), numThetas * numPredictions, MISSING_D);\n  Eigen::Map<MatrixXd> predictionsView(predictions.get(), numThetas, numPredictions);\n\n  // If we're saving the coefficients (i.e. in xmap mode), then we're not running with multiple 'theta' values.\n  auto coeffs = std::make_unique<double[]>(numPredictions * numCoeffCols);\n  std::fill_n(coeffs.get(), numPredictions * numCoeffCols, MISSING_D);\n  Eigen::Map<MatrixXd> coeffsView(coeffs.get(), numPredictions, numCoeffCols);\n\n  auto rc = std::make_unique<retcode[]>(numThetas * numPredictions);\n  std::fill_n(rc.get(), numThetas * numPredictions, UNKNOWN_ERROR);\n  Eigen::Map<MatrixXi> rcView(rc.get(), numThetas, numPredictions);\n\n  std::vector<int> kUsed;\n  for (int i = 0; i < numPredictions; i++) {\n    kUsed.push_back(MISSING_I);\n  }\n\n  if (io != nullptr && opts.taskNum == 0) {\n    io->progress_bar(0.0);\n  }\n\n  if (multiThreaded) {\n    std::vector<std::future<void>> results(numPredictions);\n#if WITH_GPU_PROFILING\n    workerPoolPtr->sync();\n    auto start = std::chrono::high_resolution_clock::now();\n#endif\n    {\n      std::unique_lock<std::mutex> lock(workerPoolPtr->queue_mutex);\n\n      for (int i = 0; i < numPredictions; i++) {\n        if (keep_going != nullptr && !keep_going()) {\n          break;\n        }\n\n        results[i] = workerPoolPtr->unsafe_enqueue(\n          [&, i] { make_prediction(i, opts, M, Mp, predictionsView, rcView, coeffsView, &(kUsed[i]), keep_going); });\n      }\n    }\n\n    for (int i = 0; i < numPredictions; i++) {\n      results[i].get();\n      if (io != nullptr) {\n        numPredictionsFinished += 1;\n        io->progress_bar(numPredictionsFinished / ((double)estimatedTotalNumPredictions));\n      }\n    }\n#if WITH_GPU_PROFILING\n    workerPoolPtr->sync();\n    auto end = std::chrono::high_resolution_clock::now();\n    std::chrono::duration<double> diff = end - start;\n    printf(\"CPU(t=%d): Task(%lu) took %lf seconds for %d predictions \\n\", opts.nthreads, opts.taskNum, diff.count(),\n           numPredictions);\n#endif\n  } else {\n#if defined(WITH_ARRAYFIRE)\n    if (useAF) {\n#if WITH_GPU_PROFILING\n      af::sync(0);\n      auto start = std::chrono::high_resolution_clock::now();\n#endif\n      af_make_prediction(numPredictions, opts, M, Mp, gpuM, gpuMp, metricOpts, predictionsView, rcView, coeffsView,\n                         kUsed, keep_going);\n#if WITH_GPU_PROFILING\n      af::sync(0);\n      auto end = std::chrono::high_resolution_clock::now();\n      std::chrono::duration<double> diff = end - start;\n      printf(\"GPU: Task(%lu) took %lf seconds for %d predictions \\n\", opts.taskNum, diff.count(), numPredictions);\n#endif\n    } else {\n#endif\n\n      for (int i = 0; i < numPredictions; i++) {\n        if (keep_going != nullptr && !keep_going()) {\n          break;\n        }\n        make_prediction(i, opts, M, Mp, predictionsView, rcView, coeffsView, &(kUsed[i]), keep_going);\n\n        if (io != nullptr) {\n          numPredictionsFinished += 1;\n          io->progress_bar(numPredictionsFinished / ((double)estimatedTotalNumPredictions));\n        }\n      }\n#if defined(WITH_ARRAYFIRE)\n    }\n#endif\n  }\n\n  PredictionResult pred;\n\n  pred.explore = opts.explore;\n\n  // Store the results, so long as we weren't interrupted by a 'break'.\n  if (keep_going == nullptr || keep_going()) {\n    // Start by calculating the MAE & rho of prediction, if requested\n    for (int t = 0; t < numThetas * opts.calcRhoMAE; t++) {\n      PredictionStats stats;\n\n      stats.library = opts.library; // Could store 'M.numPoints()' here for a more accurate version\n      stats.E = M.E_actual();\n      stats.theta = opts.thetas[t];\n\n      // POTENTIAL SPEEDUP: if predictions and y exist on GPU this could potentially be faster on GPU\n      std::vector<double> y1, y2;\n\n      for (int i = 0; i < Mp.numTargets(); i++) {\n        if (Mp.target(i) != MISSING_D && predictionsView(t, i) != MISSING_D) {\n          y1.push_back(Mp.target(i));\n          y2.push_back(predictionsView(t, i));\n        }\n      }\n\n      if (!(y1.empty() || y2.empty())) {\n        stats.mae = mean_absolute_error(y1, y2);\n        stats.rho = correlation(y1, y2);\n      } else {\n        stats.mae = MISSING_D;\n        stats.rho = MISSING_D;\n      }\n\n      pred.stats.push_back(stats);\n    }\n\n    pred.configNum = opts.configNum;\n\n    // Check if any make_prediction call failed, and if so find the most serious error\n    pred.rc = *std::max_element(rc.get(), rc.get() + numThetas * numPredictions);\n\n    if (opts.saveManifolds) {\n      pred.M = std::make_unique<Manifold>(generator, E, libraryRows, false, opts.copredict, false);\n      pred.Mp = std::make_unique<Manifold>(generator, E, predictionRows, true, opts.copredict, false);\n    } else {\n      pred.M = nullptr;\n      pred.Mp = nullptr;\n    }\n\n    // If we're storing the prediction and/or the S-map coefficients, put them\n    // into the resulting PredictionResult struct. Otherwise, let them be deleted.\n    if (opts.savePrediction) {\n      // Take only the predictions for the largest theta value.\n      if (numThetas == 1) {\n        pred.predictions = std::move(predictions);\n      } else {\n        pred.predictions = std::make_unique<double[]>(numPredictions);\n        for (int i = 0; i < numPredictions; i++) {\n          pred.predictions[i] = predictionsView(numThetas - 1, i);\n        }\n      }\n    } else {\n      pred.predictions = nullptr;\n    }\n\n    if (opts.saveSMAPCoeffs) {\n      pred.coeffs = std::move(coeffs);\n    } else {\n      pred.coeffs = nullptr;\n    }\n\n    if (opts.savePrediction || opts.saveSMAPCoeffs) {\n      pred.predictionRows = std::move(predictionRows);\n    }\n\n    if (opts.saveKUsed) {\n      auto cleanedKUsed = remove_value<int>(kUsed, MISSING_I);\n      if (cleanedKUsed.size() > 0) {\n        pred.kMin = *std::min_element(cleanedKUsed.begin(), cleanedKUsed.end());\n        pred.kMax = *std::max_element(cleanedKUsed.begin(), cleanedKUsed.end());\n      } else {\n        pred.kMin = MISSING_I;\n        pred.kMax = MISSING_I;\n      }\n    }\n\n    pred.cmdLine = opts.cmdLine;\n    pred.copredict = opts.copredict;\n\n    pred.numThetas = numThetas;\n    pred.numPredictions = numPredictions;\n    pred.numCoeffCols = numCoeffCols;\n  }\n\n  numTasksFinished += 1;\n\n  if (numTasksFinished == opts.numTasks) {\n\n    if (io != nullptr) {\n      io->progress_bar(1.0);\n    }\n\n    if (all_tasks_finished != nullptr) {\n      all_tasks_finished();\n    }\n  }\n\n  return pred;\n}\n\n// Use a library set 'M' to make a prediction about the prediction set 'Mp'.\n// Specifically, predict the 'Mp_i'-th value of the prediction set 'Mp'.\n//\n// The predicted value is stored in 'predictionsView', along with any return codes in 'rcView'.\n// Optionally, the user may ask to store some S-map intermediate values in 'coeffsView'.\n//\n// The 'opts' value specifies the kind of prediction to make (e.g. S-map, or simplex method).\n// This function is usually run in a worker thread, and the 'keep_going' callback is frequently called to\n// see whether the user still wants this result, or if they have given up & simply want the execution\n// to terminate.\n//\n// We sometimes let 'M' and 'Mp' be the same set, so we train and predict using the same values.\n// In this case, the algorithm may cheat by pulling out the identical trajectory from the library set\n// and using this as the prediction. As such, we throw away any neighbours which have a distance of 0 from\n// the target point.\nvoid make_prediction(int Mp_i, const Options& opts, const Manifold& M, const Manifold& Mp,\n                     Eigen::Map<MatrixXd> predictionsView, Eigen::Map<MatrixXi> rcView, Eigen::Map<MatrixXd> coeffsView,\n                     int* kUsed, bool keep_going())\n{\n  // An impatient user may want to cancel a long-running EDM command, so we occasionally check using this\n  // callback to see whether we ought to keep going with this EDM command. Of course, this adds a tiny inefficiency,\n  // but there doesn't seem to be a simple way to easily kill running worker threads across all OSs.\n  if (keep_going != nullptr && !keep_going()) {\n    rcView(0, Mp_i) = BREAK_HIT;\n    return;\n  }\n\n  DistanceIndexPairs potentialNN;\n  if (opts.distance == Distance::Wasserstein) {\n    potentialNN = wasserstein_distances(Mp_i, opts, M, Mp);\n  } else {\n    if (opts.lowMemoryMode) {\n      potentialNN = lazy_lp_distances(Mp_i, opts, M, Mp);\n    } else {\n      potentialNN = eager_lp_distances(Mp_i, opts, M, Mp);\n    }\n  }\n\n  if (keep_going != nullptr && !keep_going()) {\n    rcView(0, Mp_i) = BREAK_HIT;\n    return;\n  }\n\n  // Do we have enough distances to find k neighbours?\n  int numValidDistances = potentialNN.inds.size();\n  int k = opts.k;\n\n  if (k > numValidDistances) {\n    if (opts.forceCompute) {\n      k = numValidDistances;\n    } else {\n      rcView(0, Mp_i) = INSUFFICIENT_UNIQUE;\n      return;\n    }\n  }\n\n  if (k == 0 || numValidDistances == 0) {\n    // Whether we throw an error or just silently ignore this prediction\n    // depends on whether we are in 'strict' mode or not.\n    rcView(0, Mp_i) = opts.forceCompute ? SUCCESS : INSUFFICIENT_UNIQUE;\n    return;\n  }\n\n  // If we asked for all of the neighbours to be considered (e.g. with k = -1), return this index vector directly.\n  DistanceIndexPairs kNNs;\n  if (k < 0 || k == potentialNN.inds.size()) {\n    kNNs = potentialNN;\n  } else {\n    kNNs = k_nearest_neighbours(potentialNN, k);\n  }\n\n  *kUsed = kNNs.inds.size();\n\n  if (keep_going != nullptr && !keep_going()) {\n    rcView(0, Mp_i) = BREAK_HIT;\n    return;\n  }\n\n  if (opts.algorithm == Algorithm::Simplex) {\n    for (int t = 0; t < opts.thetas.size(); t++) {\n      simplex_prediction(Mp_i, t, opts, M, kNNs.dists, kNNs.inds, predictionsView, rcView);\n    }\n  } else if (opts.algorithm == Algorithm::SMap) {\n    for (int t = 0; t < opts.thetas.size(); t++) {\n      smap_prediction(Mp_i, t, opts, M, Mp, kNNs.dists, kNNs.inds, predictionsView, coeffsView, rcView);\n    }\n  } else {\n    rcView(0, Mp_i) = INVALID_ALGORITHM;\n  }\n}\n\n// For a given point, find the k nearest neighbours of this point.\n//\n// If there are many potential neighbours with the exact same distances, we\n// prefer the neighbours with the smallest index value. This corresponds\n// to a stable sort in C++ STL terminology.\n//\n// In typical use-cases of 'edm explore' the value of 'k' is small, like 5-20.\n// However for a typical 'edm xmap' the value of 'k' is set as large as possible.\n// If 'k' is small, the partial_sort is efficient as it only finds the 'k' smallest\n// distances. If 'k' is larger, then it is faster to simply sort the entire distance\n// vector.\nDistanceIndexPairs k_nearest_neighbours(const DistanceIndexPairs& potentialNeighbours, int k)\n{\n  std::vector<int> idx(potentialNeighbours.inds.size());\n  std::iota(idx.begin(), idx.end(), 0);\n\n  if (k >= (int)(idx.size() / 2)) {\n    auto comparator = [&potentialNeighbours](int i1, int i2) {\n      return potentialNeighbours.dists[i1] < potentialNeighbours.dists[i2];\n    };\n    std::stable_sort(idx.begin(), idx.end(), comparator);\n  } else {\n    auto stableComparator = [&potentialNeighbours](int i1, int i2) {\n      if (potentialNeighbours.dists[i1] != potentialNeighbours.dists[i2])\n        return potentialNeighbours.dists[i1] < potentialNeighbours.dists[i2];\n      else\n        return i1 < i2;\n    };\n    std::partial_sort(idx.begin(), idx.begin() + k, idx.end(), stableComparator);\n  }\n\n  std::vector<int> kNNInds(k);\n  std::vector<double> kNNDists(k);\n\n  for (int i = 0; i < k; i++) {\n    kNNInds[i] = potentialNeighbours.inds[idx[i]];\n    kNNDists[i] = potentialNeighbours.dists[idx[i]];\n  }\n\n  return { kNNInds, kNNDists };\n}\n\n// An alternative version of 'k_nearest_neighbours' which doesn't sort the neighbours.\n// This version splits ties differently on different OS's, so it can't be used directly,\n// though perhaps a platform-independent implementation of std::nth_element would solve this problem.\nDistanceIndexPairs k_nearest_neighbours_unstable(const DistanceIndexPairs& potentialNeighbours, int k)\n{\n  std::vector<int> indsToPartition(potentialNeighbours.inds.size());\n  std::iota(indsToPartition.begin(), indsToPartition.end(), 0);\n\n  auto comparator = [&potentialNeighbours](int i1, int i2) {\n    return potentialNeighbours.dists[i1] < potentialNeighbours.dists[i2];\n  };\n  std::nth_element(indsToPartition.begin(), indsToPartition.begin() + k, indsToPartition.end(), comparator);\n\n  std::vector<int> kNNInds(k);\n  std::vector<double> kNNDists(k);\n\n  for (int i = 0; i < k; i++) {\n    kNNInds[i] = potentialNeighbours.inds[indsToPartition[i]];\n    kNNDists[i] = potentialNeighbours.dists[indsToPartition[i]];\n  }\n\n  return { kNNInds, kNNDists };\n}\n\nvoid simplex_prediction(int Mp_i, int t, const Options& opts, const Manifold& M, const std::vector<double>& dists,\n                        const std::vector<int>& kNNInds, Eigen::Map<MatrixXd> predictionsView,\n                        Eigen::Map<MatrixXi> rcView)\n{\n  int k = kNNInds.size();\n\n  // Find the smallest distance (closest neighbour) among the supplied neighbours.\n  double minDist = *std::min_element(dists.begin(), dists.end());\n\n  // Calculate our weighting of each neighbour, and the total sum of these weights.\n  std::vector<double> w(k);\n  double sumw = 0.0;\n  const double theta = opts.thetas[t];\n\n  for (int j = 0; j < k; j++) {\n    w[j] = exp(-theta * (dists[j] / minDist));\n    sumw = sumw + w[j];\n  }\n\n  // Make the simplex projection/prediction.\n  double r = 0.0;\n  for (int j = 0; j < k; j++) {\n    r = r + M.target(kNNInds[j]) * (w[j] / sumw);\n  }\n\n  // Store the results & return value.\n  predictionsView(t, Mp_i) = r;\n  rcView(t, Mp_i) = SUCCESS;\n}\n\nvoid smap_prediction(int Mp_i, int t, const Options& opts, const Manifold& M, const Manifold& Mp,\n                     const std::vector<double>& dists, const std::vector<int>& kNNInds,\n                     Eigen::Map<MatrixXd> predictionsView, Eigen::Map<MatrixXd> coeffsView, Eigen::Map<MatrixXi> rcView)\n{\n  int k = kNNInds.size();\n\n  // Calculate the weight for each neighbour\n  Eigen::Map<const Eigen::VectorXd> distsMap(&(dists[0]), dists.size());\n  Eigen::VectorXd w = Eigen::exp(-opts.thetas[t] * (distsMap.array() / distsMap.mean()));\n\n  // Pull out the nearest neighbours from the manifold, and\n  // simultaneously prepend a column of ones in front of the manifold data.\n  MatrixXd X_ls_cj(k, M.E_actual() + 1);\n\n  if (opts.lowMemoryMode) {\n    for (int i = 0; i < k; i++) {\n      X_ls_cj(i, 0) = w[i];\n      M.lazy_fill_in_point(kNNInds[i], &(X_ls_cj(i, 1)));\n      for (int j = 1; j < M.E_actual() + 1; j++) {\n        X_ls_cj(i, j) *= w[i];\n      }\n    }\n  } else {\n    for (int i = 0; i < k; i++) {\n      X_ls_cj(i, 0) = w[i];\n      for (int j = 1; j < M.E_actual() + 1; j++) {\n        X_ls_cj(i, j) = w[i] * M(kNNInds[i], j - 1);\n      }\n    }\n  }\n\n  // Scale targets by our weights vector\n  Eigen::VectorXd y_ls(k);\n  for (int i = 0; i < k; i++) {\n    y_ls[i] = w[i] * M.target(kNNInds[i]);\n  }\n\n  // The old way to solve this system:\n  // Eigen::BDCSVD<MatrixXd> svd(X_ls_cj, Eigen::ComputeThinU | Eigen::ComputeThinV);\n  //  Eigen::VectorXd ics = svd.solve(y_ls);\n\n  // The pseudo-inverse of X can be calculated as (X^T * X)^(-1) * X^T\n  // see https://scicomp.stackexchange.com/a/33375\n  const int svdOpts = Eigen::ComputeThinU | Eigen::ComputeThinV; // 'ComputeFull*' would probably work identically here.\n  Eigen::JacobiSVD<MatrixXd> svd(X_ls_cj.transpose() * X_ls_cj, svdOpts);\n  Eigen::VectorXd ics = svd.solve(X_ls_cj.transpose() * y_ls);\n\n  double r = ics(0);\n\n  auto y = std::unique_ptr<double[]>(new double[M.E_actual()], std::default_delete<double[]>());\n\n  if (opts.lowMemoryMode) {\n    Mp.lazy_fill_in_point(Mp_i, y.get());\n  } else {\n    Mp.eager_fill_in_point(Mp_i, y.get());\n  }\n\n  for (int j = 0; j < M.E_actual(); j++) {\n    if (y[j] != MISSING_D) {\n      r += y[j] * ics(j + 1);\n    }\n  }\n\n  // If the 'savesmap' option is given, save the 'ics' coefficients\n  // for the largest value of theta.\n  if (opts.saveSMAPCoeffs && t == opts.thetas.size() - 1) {\n    for (int j = 0; j < M.E_actual() + 1; j++) {\n      if (std::abs(ics(j)) < 1.0e-11) {\n        coeffsView(Mp_i, j) = MISSING_D;\n      } else {\n        coeffsView(Mp_i, j) = ics(j);\n      }\n    }\n  }\n\n  predictionsView(t, Mp_i) = r;\n  rcView(t, Mp_i) = SUCCESS;\n}\n\n/////////////////////////////////////////////////////////////// ArrayFire PORTED versions BEGIN HERE\n\n#if defined(WITH_ARRAYFIRE)\n\n// Returns b8 array of shape [numLibraryPoints numPredictions 1 1] when either of skip flags are true\n//        otherwise of shape [numLibraryPoints 1 1 1]\naf::array afPotentialNeighbourIndices(const int& numPredictions, const bool& skipOtherPanels,\n                                      const bool& skipMissingData, const ManifoldOnGPU& M, const ManifoldOnGPU& Mp)\n{\n  using af::anyTrue;\n  using af::array;\n  using af::dim4;\n  using af::iota;\n  using af::seq;\n  using af::tile;\n\n#if WITH_GPU_PROFILING\n  auto range = nvtxRangeStartA(__FUNCTION__);\n#endif\n\n  const dim_t numLibraryPoints = M.numPoints;\n\n  array result;\n  if (skipOtherPanels && skipMissingData) {\n    array numPredictionsMp = Mp.panel(seq(numPredictions));\n    array panelM = tile(M.panel, 1, numPredictions);\n    array panelMp = tile(numPredictionsMp.T(), numLibraryPoints);\n    array mssngM = (M.mdata == M.missing);\n    array msngCols = anyTrue(mssngM, 0);\n    array msngFlags = tile(msngCols.T(), 1, numPredictions);\n\n    result = !(msngFlags || (panelM != panelMp));\n  } else if (skipOtherPanels) {\n    array numPredictionsMp = Mp.panel(seq(numPredictions));\n    array panelM = tile(M.panel, 1, numPredictions);\n    array panelMp = tile(numPredictionsMp.T(), numLibraryPoints);\n\n    result = !(panelM != panelMp);\n  } else if (skipMissingData) {\n    result = tile(!(anyTrue(M.mdata == M.missing, 0).T()), 1, numPredictions);\n  } else {\n    result = af::constant(1.0, M.numPoints, numPredictions, b8);\n  }\n#if WITH_GPU_PROFILING\n  nvtxRangeEnd(range);\n#endif\n  return result;\n}\n\nvoid afNearestNeighbours(af::array& pValids, af::array& sDists, af::array& yvecs, af::array& smData,\n                         const af::array& vDists, const af::array& yvec, const af::array& mdata, const Algorithm algo,\n                         const int eacts, const int numLibraryPoints, const int numPredictions, const int k)\n{\n  using af::array;\n  using af::dim4;\n  using af::iota;\n  using af::moddims;\n  using af::sort;\n  using af::tile;\n\n#if WITH_GPU_PROFILING\n  auto searchRange = nvtxRangeStartA(\"sortData\");\n#endif\n  array maxs = af::max(pValids * vDists, 0);\n  array pDists = pValids * vDists + (1 - pValids) * tile(maxs + 100, numLibraryPoints);\n\n  array indices;\n  topk(sDists, indices, pDists, k, 0, AF_TOPK_MIN);\n\n  yvecs = moddims(yvec(indices), k, numPredictions);\n\n  array vIdx = indices + iota(dim4(1, numPredictions), dim4(k)) * numLibraryPoints;\n\n  pValids = moddims(pValids(vIdx), k, numPredictions);\n\n  // Manifold data also needs to be reorder for SMap prediction\n  if (algo == Algorithm::SMap) {\n    array tmdata = tile(mdata, 1, 1, numPredictions);\n    array soffs = iota(dim4(1, 1, numPredictions), dim4(eacts, k)) * (eacts * numLibraryPoints);\n    array d0offs = iota(dim4(eacts), dim4(1, k, numPredictions));\n\n    indices = tile(moddims(indices, 1, k, numPredictions), eacts) * eacts;\n    indices += (soffs + d0offs);\n\n    smData = moddims(tmdata(indices), eacts, k, numPredictions);\n  }\n\n#if WITH_GPU_PROFILING\n  nvtxRangeEnd(searchRange);\n#endif\n}\n\nvoid afSimplexPrediction(af::array& retcodes, af::array& ystar, const int numPredictions, const Options& opts,\n                         const af::array& yvecs, const DistanceIndexPairsOnGPU& pair, const af::array& thetas,\n                         const bool isKNeg)\n{\n  using af::array;\n  using af::sum;\n  using af::tile;\n\n#if WITH_GPU_PROFILING\n  auto range = nvtxRangeStartA(__FUNCTION__);\n#endif\n\n  const array& valids = pair.valids;\n  const array& dists = pair.dists;\n  const int k = valids.dims(0);\n  const int tcount = opts.thetas.size();\n  const array thetasT = tile(thetas, k, numPredictions);\n\n  array weights;\n  {\n    array minDist;\n    if (isKNeg) {\n      minDist = tile(min(dists, 0), k, 1, tcount);\n    } else {\n      minDist = tile(dists(0, af::span), k, 1, tcount);\n    }\n    array tadist = tile(dists, 1, 1, tcount);\n\n    weights = tile(valids, 1, 1, tcount) * af::exp(-thetasT * (tadist / minDist));\n  }\n  array r4thetas = tile(yvecs, 1, (isKNeg ? numPredictions : 1), tcount) * (weights / tile(sum(weights, 0), k));\n\n  ystar = moddims(sum(r4thetas, 0), numPredictions, tcount);\n  retcodes = af::constant(SUCCESS, numPredictions, tcount, s32);\n\n#if WITH_GPU_PROFILING\n  nvtxRangeEnd(range);\n#endif\n}\n\ntemplate<typename T>\nvoid afSMapPrediction(af::array& retcodes, af::array& ystar, af::array& coeffs, const int numPredictions,\n                      const Options& opts, const ManifoldOnGPU& M, const ManifoldOnGPU& Mp,\n                      const DistanceIndexPairsOnGPU& pair, const af::array& mdata, const af::array& yvecs,\n                      const af::array& thetas, const bool useLoops)\n{\n  using af::array;\n  using af::constant;\n  using af::dim4;\n  using af::end;\n  using af::matmulTN;\n  using af::mean;\n  using af::moddims;\n  using af::pinverse;\n  using af::select;\n  using af::seq;\n  using af::span;\n  using af::tile;\n\n#if WITH_GPU_PROFILING\n  auto range = nvtxRangeStartA(__FUNCTION__);\n#endif\n\n  const array& valids = pair.valids;\n  const array& dists = pair.dists;\n  const int k = valids.dims(0);\n  const int tcount = opts.thetas.size();\n  const int MEactualp1 = M.E_actual + 1;\n  const af_dtype cType = M.mdata.type();\n\n  if (useLoops) {\n    array meanDists = tile((k * mean(valids * dists, 0) / count(valids, 0)), k);\n    array mdValids = tile(moddims(valids, 1, k, numPredictions), M.E_actual);\n    array Mp_i_j = Mp.mdata(span, seq(numPredictions));\n    array scaleval = ((Mp_i_j != double(MISSING_D)) * Mp_i_j);\n\n    // Allocate Output arrays\n    ystar = array(tcount, numPredictions, cType);\n\n    for (int t = 0; t < tcount; ++t) {\n      double theta = opts.thetas[t];\n\n      array weights = valids * af::exp(-theta * (dists / meanDists));\n      array y_ls = weights * tile(yvecs, 1, numPredictions);\n\n      array icsOuts = array(MEactualp1, numPredictions, cType);\n      for (int p = 0; p < numPredictions; ++p) {\n        array X_ls_cj = constant(1.0, dim4(MEactualp1, k), cType);\n\n        X_ls_cj(seq(1, end), span) = mdValids(span, span, p) * mdata;\n\n        X_ls_cj *= tile(moddims(weights(span, p), 1, k), MEactualp1);\n\n        icsOuts(span, p) = matmulTN(pinverse(X_ls_cj, 1e-9), y_ls(span, p));\n      }\n      array r2d = icsOuts(seq(1, end), span) * scaleval;\n      array r = icsOuts(0, span) + sum(r2d, 0);\n\n      ystar(t, span) = r;\n\n      if (t == tcount - 1) {\n        if (opts.saveSMAPCoeffs) {\n          coeffs = select(af::abs(icsOuts) < 1.0e-11, double(MISSING_D), icsOuts).T();\n        }\n      }\n    }\n  } else {\n    array thetasT = tile(thetas, k, numPredictions);\n    array weights, y_ls;\n    {\n      array meanDists = (k * mean(valids * dists, 0) / count(valids, 0));\n      array meanDistsT = tile(meanDists, k, 1, tcount);\n      array ptDists = tile(dists, 1, 1, tcount);\n      array validsT = tile(valids, 1, 1, tcount);\n\n      weights = validsT * af::exp(-thetasT * (ptDists / meanDistsT));\n      y_ls = weights * tile(yvecs, 1, 1, tcount);\n    }\n\n    array mdValids = tile(moddims(valids, 1, k, numPredictions), M.E_actual);\n    array X_ls_cj = constant(1.0, dim4(MEactualp1, k, numPredictions), cType);\n\n    X_ls_cj(seq(1, end), span) = mdValids * mdata;\n\n    array X_ls_cj_T = tile(X_ls_cj, 1, 1, 1, tcount);\n\n    X_ls_cj_T *= tile(moddims(weights, 1, k, numPredictions, tcount), MEactualp1);\n\n    array icsOuts = matmulTN(pinverse(X_ls_cj_T, 1e-9), moddims(y_ls, k, 1, numPredictions, tcount));\n\n    icsOuts = moddims(icsOuts, MEactualp1, numPredictions, tcount);\n    array Mp_i_j = tile(Mp.mdata(span, seq(numPredictions)), 1, 1, tcount);\n    array r2d = icsOuts(seq(1, end), span, span) * ((Mp_i_j != double(MISSING_D)) * Mp_i_j);\n    array r = icsOuts(0, span, span) + sum(r2d, 0);\n\n    ystar = moddims(r, numPredictions, tcount).T();\n    retcodes = constant(SUCCESS, numPredictions, tcount);\n    if (opts.saveSMAPCoeffs) {\n      array lastTheta = icsOuts(span, span, tcount - 1);\n\n      coeffs = select(af::abs(lastTheta) < 1.0e-11, double(MISSING_D), lastTheta).T();\n    }\n  }\n\n  retcodes = constant(SUCCESS, numPredictions, tcount);\n#if WITH_GPU_PROFILING\n  nvtxRangeEnd(range);\n#endif\n}\n\nvoid af_make_prediction(const int numPredictions, const Options& opts, const Manifold& hostM, const Manifold& hostMp,\n                        const ManifoldOnGPU& M, const ManifoldOnGPU& Mp, const af::array& metricOpts,\n                        Eigen::Map<MatrixXd> ystar, Eigen::Map<MatrixXi> rc, Eigen::Map<MatrixXd> coeffs,\n                        std::vector<int>& kUseds, bool keep_going())\n{\n  try {\n    using af::array;\n    using af::constant;\n    using af::dim4;\n    using af::iota;\n\n#if WITH_GPU_PROFILING\n    auto mpRange = nvtxRangeStartA(__FUNCTION__);\n#endif\n\n    const int numThetas = opts.thetas.size();\n    const af_dtype cType = M.mdata.type();\n\n    if (opts.algorithm != Algorithm::Simplex && opts.algorithm != Algorithm::SMap) {\n      array retcodes = constant(INVALID_ALGORITHM, numPredictions, numThetas, s32);\n      retcodes.host(rc.data());\n      return;\n    }\n    using af::span;\n    using af::tile;\n    using af::where;\n\n    const bool skipOtherPanels = opts.panelMode && (opts.idw < 0);\n    const bool skipMissingData = (opts.algorithm == Algorithm::SMap);\n\n    array thetas = array(1, 1, opts.thetas.size(), opts.thetas.data()).as(cType);\n\n    auto pValids = afPotentialNeighbourIndices(numPredictions, skipOtherPanels, skipMissingData, M, Mp);\n\n    auto validDistPair = afLPDistances(numPredictions, opts, M, Mp, metricOpts);\n\n#if WITH_GPU_PROFILING\n    auto kisRange = nvtxRangeStartA(\"kNearestSelection\");\n#endif\n    // TODO add code path for wasserstein later\n    pValids = pValids && validDistPair.valids;\n\n    // smData is set only if algo is SMap\n    array retcodes, kUsed, sDists, yvecs, smData;\n\n    const int k = opts.k;\n    bool isKNeg = k < 0;\n\n    if (k == 0) {\n      af::array retcodes = af::constant(SUCCESS, numPredictions, opts.thetas.size(), s32);\n      retcodes.host(rc.data());\n      return;\n    }\n\n    if (k > 0) {\n      try {\n        afNearestNeighbours(pValids, sDists, yvecs, smData, validDistPair.dists, M.targets, M.mdata, opts.algorithm,\n                            M.E_actual, M.numPoints, numPredictions, k);\n      } catch (const af::exception& e) {\n        // When 'k' is too large, afNearestNeighbours will crash.\n        // For now, just continue as if k=-1 was specified.\n        isKNeg = true;\n        sDists = af::select(pValids, validDistPair.dists, MISSING_D);\n        yvecs = M.targets;\n        smData = M.mdata;\n      }\n    } else {\n      sDists = af::select(pValids, validDistPair.dists, MISSING_D);\n      yvecs = M.targets;\n      smData = M.mdata;\n    }\n#if WITH_GPU_PROFILING\n    nvtxRangeEnd(kisRange);\n#endif\n\n    if (opts.saveKUsed) {\n      kUsed = af::sum(pValids, 0);\n    }\n\n    array ystars, dcoeffs;\n    if (opts.algorithm == Algorithm::Simplex) {\n      afSimplexPrediction(retcodes, ystars, numPredictions, opts, yvecs, { pValids, sDists }, thetas, isKNeg);\n    } else if (opts.algorithm == Algorithm::SMap) {\n      if (cType == f32) {\n        afSMapPrediction<float>(retcodes, ystars, dcoeffs, numPredictions, opts, M, Mp, { pValids, sDists }, smData,\n                                yvecs, thetas, isKNeg);\n      } else {\n        afSMapPrediction<double>(retcodes, ystars, dcoeffs, numPredictions, opts, M, Mp, { pValids, sDists }, smData,\n                                 yvecs, thetas, isKNeg);\n      }\n    }\n\n#if WITH_GPU_PROFILING\n    auto returnRange = nvtxRangeStartA(\"ReturnValues\");\n#endif\n    if (opts.algorithm == Algorithm::Simplex) {\n      ystars.as(f64).host(ystar.data());\n    } else {\n      ystars.T().as(f64).host(ystar.data());\n    }\n\n    retcodes.T().host(rc.data());\n    if (opts.saveKUsed) {\n      kUsed.host(kUseds.data());\n    }\n    if (opts.saveSMAPCoeffs) {\n      dcoeffs.T().as(f64).host(coeffs.data());\n    }\n#if WITH_GPU_PROFILING\n    nvtxRangeEnd(returnRange);\n    nvtxRangeEnd(mpRange);\n#endif\n  } catch (af::exception& e) {\n    std::cerr << \"ArrayFire threw an exception with message: \\n\" << std::endl;\n    std::cerr << e << std::endl;\n\n    af::array retcodes = af::constant(UNKNOWN_ERROR, numPredictions, opts.thetas.size(), s32);\n    retcodes.host(rc.data());\n  }\n}\n\n#endif", "meta": {"hexsha": "dfc6aae09cc77ade607cc2e759a546e18d80ac9b", "size": 38751, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/edm.cpp", "max_stars_repo_name": "EDM-Developers/fastEDM", "max_stars_repo_head_hexsha": "9724bf609d09beae53a89ca5cbe52d407787dbf2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/edm.cpp", "max_issues_repo_name": "EDM-Developers/fastEDM", "max_issues_repo_head_hexsha": "9724bf609d09beae53a89ca5cbe52d407787dbf2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/edm.cpp", "max_forks_repo_name": "EDM-Developers/fastEDM", "max_forks_repo_head_hexsha": "9724bf609d09beae53a89ca5cbe52d407787dbf2", "max_forks_repo_licenses": ["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.7542600897, "max_line_length": 120, "alphanum_fraction": 0.6470542696, "num_tokens": 10964, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6825737473266735, "lm_q2_score": 0.44552953503957277, "lm_q1q2_score": 0.30410676427667166}}
{"text": "#include <iostream>\n#include <Eigen/Dense>\n#include <random>\n#include <vector>\n#include <iomanip>\n#include <fstream>\n#include <bitset>\n#include <string>\n#include <map>\n\n#ifndef QST_TESTTOMOGRPHY_HPP\n#define QST_TESTTOMOGRPHY_HPP\n\nnamespace qst{\n\n//Quantum State Tomography class\ntemplate<class NNState,class Observer> class Test{\n\n    NNState & NNstate_;                   // Neural network representation of the state\n    Observer &obs_;\n\n    int N_;\n    int npar_;                          // Number of variational parameters\n    int nparLambda_;                    // Number of amplitude variational parameters\n    int nparMu_;\n    std::string basis_;\n    Eigen::VectorXd grad_;         // Gradient \n    Eigen::VectorXcd rotated_grad_;\n    std::mt19937 rgen_;                 // Random number generator\n    std::map<std::string,Eigen::MatrixXcd> U_;\n    Eigen::MatrixXd basis_states_;   \n    Eigen::VectorXcd target_psi_;\n    std::vector<Eigen::VectorXcd> rotated_wf_;\n    std::vector<std::vector<std::string> > basisSet_;\n\npublic:\n     \n    Test(NNState & NNstate,Observer &obs,Parameters &par):NNstate_(NNstate),obs_(obs),N_(NNstate.N()){\n            \n        npar_=NNstate_.Npar();\n        nparLambda_ = NNstate_.NparLambda();\n        nparMu_ = npar_ - nparLambda_;\n        grad_.resize(npar_);\n        rotated_grad_.resize(npar_);\n        basis_ = par.basis_;\n        basis_states_.resize(1<<N_,N_);\n        std::bitset<10> bit;\n        // Create the basis of the Hilbert space\n        for(int i=0;i<1<<N_;i++){\n            bit = i;\n            for(int j=0;j<N_;j++){\n                basis_states_(i,j) = bit[N_-j-1];\n            }\n        }\n\n    }\n\n    // Test the derivatives of the KL divergence\n    void DerKL(double eps=1.0e-4){\n        auto pars = NNstate_.GetParameters();\n        obs_.ExactPartitionFunction();\n        Eigen::VectorXcd derKL(npar_);\n        Eigen::VectorXd ders(npar_);\n        ders.setZero(npar_);\n\n        //-- ALGORITHMIC DERIVATIVES --//\n        //Standard Basis\n        for(int j=0;j<1<<N_;j++){\n            //Positive phase - Lambda gradient in reference basis\n            ders.head(nparLambda_) +=  norm(target_psi_(j))*NNstate_.LambdaGrad(basis_states_.row(j));\n            //Negative phase - Lambda gradient in reference basis\n            ders.head(nparLambda_) -= NNstate_.LambdaGrad(basis_states_.row(j))*norm(NNstate_.psi(basis_states_.row(j)))/obs_.Z_;\n            //std::cout << (NNstate_.LambdaGrad(basis_states_.row(j)).head(10)).transpose() << std::endl<<std::endl;\n        }\n        if (basis_.compare(\"std\")!=0){\n            //Rotated Basis\n            for(int b=1;b<basisSet_.size();b++){\n                for(int j=0;j<1<<N_;j++){\n                    NNstate_.rotatedGrad(basisSet_[b],basis_states_.row(j),U_,derKL);\n                    //Positive phase - Lambda gradient in basis b\n                    ders.head(nparLambda_) += norm(rotated_wf_[b-1](j))*derKL.head(nparLambda_).real();\n                    //Positive phase - Mu gradient in basis b\n                    ders.tail(nparMu_) -= norm(rotated_wf_[b-1](j))*derKL.tail(nparMu_).imag();\n                    //Negative phase - Lambda gradient in basis b (identical to the reference basis\n                    ders.head(nparLambda_) -= NNstate_.LambdaGrad(basis_states_.row(j))*norm(NNstate_.psi(basis_states_.row(j)))/obs_.Z_;\n                }\n            }\n        }\n        //-- NUMERICAL DERIVATIVES --//\n        for(int p=0;p<npar_;p++){\n            pars(p)+=eps;\n            NNstate_.SetParameters(pars);\n            double valp=0.0;\n            obs_.ExactPartitionFunction();\n            obs_.ExactKL();\n            valp = obs_.KL_;\n            pars(p)-=2*eps;\n            NNstate_.SetParameters(pars);\n            double valm=0.0;\n            obs_.ExactPartitionFunction();\n            obs_.ExactKL();\n            valm = obs_.KL_;\n            pars(p)+=eps;\n            double numder=(-valm+valp)/(eps*2);\n            std::cout<<\"Derivative wrt par \"<<p<<\". Grad =: \"<<ders(p)<<\" Numerical = : \"<<numder<<std::endl;\n        }\n    }\n\n    // Test the derivatives of the KL divergence\n    void DerNLL(Eigen::MatrixXd &data,double eps=1.0e-4){\n        auto pars = NNstate_.GetParameters();\n        obs_.ExactPartitionFunction();\n        Eigen::VectorXcd derKL(npar_);\n        Eigen::VectorXd ders(npar_);\n        ders.setZero(npar_);\n\n        //-- ALGORITHMIC DERIVATIVES --//\n        //Standard Basis\n        std::cout << data.rows() <<std::endl;\n        for(int j=0;j<data.rows();j++){\n            //Positive phase - Lambda gradient in reference basis\n            ders.head(nparLambda_) +=  NNstate_.LambdaGrad(data.row(j))/float(data.rows());\n        }\n        //for(int j=0;j<1<<N_;j++){ \n        //    ders.head(nparLambda_) -= NNstate_.LambdaGrad(basis_states_.row(j))*norm(NNstate_.psi(basis_states_.row(j)))/obs_.Z_;\n        //    //std::cout << (NNstate_.LambdaGrad(basis_states_.row(j)).head(10)).transpose() << std::endl<<std::endl;\n        //}\n        //NNstate_.SetVisibleLayer(data);\n        NNstate_.Sample(100);\n        std::cout << NNstate_.VisibleStateRow(0) << std::endl;\n        for(int k=0;k<NNstate_.Nchains();k++){ \n            ders.head(nparLambda_) -= NNstate_.LambdaGrad(NNstate_.VisibleStateRow(k))/double(NNstate_.Nchains());\n        }\n        //if (basis_.compare(\"std\")!=0){\n        //    //Rotated Basis\n        //    for(int b=1;b<basisSet_.size();b++){\n        //        for(int j=0;j<1<<N_;j++){\n        //            NNstate_.rotatedGrad(basisSet_[b],basis_states_.row(j),U_,derKL);\n        //            //Positive phase - Lambda gradient in basis b\n        //            ders.head(nparLambda_) += norm(rotated_wf_[b-1](j))*derKL.head(nparLambda_).real();\n        //            //Positive phase - Mu gradient in basis b\n        //            ders.tail(nparMu_) -= norm(rotated_wf_[b-1](j))*derKL.tail(nparMu_).imag();\n        //            //Negative phase - Lambda gradient in basis b (identical to the reference basis\n        //            ders.head(nparLambda_) -= NNstate_.LambdaGrad(basis_states_.row(j))*norm(NNstate_.psi(basis_states_.row(j)))/obs_.Z_;\n        //        }\n        //    }\n        //}\n        //-- NUMERICAL DERIVATIVES --//\n        for(int p=0;p<npar_;p++){\n            pars(p)+=eps;\n            NNstate_.SetParameters(pars);\n            double valp=0.0;\n            obs_.ExactPartitionFunction();\n            obs_.NLL(data);\n            valp = obs_.NLL_;\n            pars(p)-=2*eps;\n            NNstate_.SetParameters(pars);\n            double valm=0.0;\n            obs_.ExactPartitionFunction();\n            obs_.NLL(data);\n            valm = obs_.NLL_;\n            pars(p)+=eps;\n            double numder=(-valm+valp)/(eps*2);\n            std::cout<<\"Derivative wrt par \"<<p<<\". Grad =: \"<<ders(p)<<\" Numerical = : \"<<numder<<std::endl;\n        }\n    }\n    //Set the value of the target wavefunction\n    void setBasisRotations(std::map<std::string,Eigen::MatrixXcd> & U){\n        U_ = U;\n    }\n    void setBasis(std::vector<std::vector<std::string> > basis) {\n        basisSet_ = basis;\n    }\n    //Set the value of the target wavefunction\n    void setWavefunction(Eigen::VectorXcd & psi){\n        target_psi_.resize(1<<N_);\n        for(int i=0;i<1<<N_;i++){\n            target_psi_(i) = psi(i);\n        }\n    }\n    void setRotatedWavefunctions(std::vector<Eigen::VectorXcd> & psi){\n        for(int b=0;b<psi.size();b++){\n            rotated_wf_.push_back(psi[b]);\n        }\n    }\n};\n}\n\n#endif\n", "meta": {"hexsha": "de06283c9570a0df932b885d4d6fb0bdc2478d4b", "size": 7468, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "qucumber/cpp/test_tomography.hpp", "max_stars_repo_name": "PatrickHuembeli/QuCumber", "max_stars_repo_head_hexsha": "a9f8912a086f334ab2af20bf52493a528332a214", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-10-02T10:03:45.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-02T10:03:45.000Z", "max_issues_repo_path": "qucumber/cpp/test_tomography.hpp", "max_issues_repo_name": "PatrickHuembeli/QuCumber", "max_issues_repo_head_hexsha": "a9f8912a086f334ab2af20bf52493a528332a214", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "qucumber/cpp/test_tomography.hpp", "max_forks_repo_name": "PatrickHuembeli/QuCumber", "max_forks_repo_head_hexsha": "a9f8912a086f334ab2af20bf52493a528332a214", "max_forks_repo_licenses": ["Apache-2.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.3052631579, "max_line_length": 139, "alphanum_fraction": 0.5587841457, "num_tokens": 1983, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6825737344123242, "lm_q2_score": 0.4455295350395727, "lm_q1q2_score": 0.30410675852294755}}
{"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 <iostream>\n#include <cstdio>\n#include <set>\n#include <algorithm>\n#include <cmath>\n\n#include <boost/thread.hpp>\n\n#include \"saveload_bz2.hpp\"\n#include \"saveload_gz.hpp\"\n#include \"sdr.hpp\"\n\nusing namespace std;\n\nnamespace hashclash {\n\n\tstd::ostream& operator<<(std::ostream& o, const sdr& n)\n\t{\n\t\to << \"[!\";\n\t\tbool first = true;\n\t\tfor (unsigned b = 0; b < 32; ++b)\n\t\t{\n\t\t\tif (n[b] != 0)\n\t\t\t{\n\t\t\t\tif (first)\n\t\t\t\t\tfirst = false;\n\t\t\t\telse\n\t\t\t\t\to << \",\";\n\t\t\t\tif (n[b] == -1)\n\t\t\t\t\to << \"-\";\n\t\t\t\to << b;\n\t\t\t}\n\t\t}\n\t\to << \"!]\";\n\t\treturn o;\n\t}\n\n\tstd::istream& operator>>(std::istream& i, sdr& n)\n\t{\n\t\tn.clear();\n\t\tchar c;\n\t\tif (!(i >> c)) return i;\n\t\tif (c != '[') {\n\t\t\ti.putback(c);\n\t\t\ti.setstate(std::ios::failbit);\n\t\t\treturn i;\n\t\t}\n\t\tif (!(i >> c)) return i;\n\t\tif (c != '!') {\n\t\t\ti.putback(c);\n\t\t\ti.setstate(std::ios::failbit);\n\t\t\treturn i;\n\t\t}\n\t\t// check for empty sdr\n\t\tif (!(i >> c)) return i;\n\t\tif (c == '!') {\n\t\t\tif (!(i >> c)) return i;\n\t\t\tif (c != ']') {\n\t\t\t\ti.putback(c);\n\t\t\t\ti.setstate(std::ios::failbit);\n\t\t\t}\n\t\t\treturn i;\n\t\t}\n\t\ti.putback(c);\n\t\t\t\n\t\tchar s;\n\t\tbool neg = true;\n\t\tif (!(i >> s)) return i;\n\t\tif (s != '-') {\n\t\t\tneg = false;\n\t\t\ti.putback(s);\n\t\t}\n\t\tunsigned bit;\n\t\twhile (i >> bit >> c) {\n\t\t\tif (!(bit < 32 && (c == ',' || c == '!'))) {\n\t\t\t\ti.putback(c);\n\t\t\t\ti.setstate(std::ios::failbit);\n\t\t\t\treturn i;\n\t\t\t}\n\t\t\tn.mask |= 1<<bit;\n\t\t\tif (!neg)\n\t\t\t\tn.sign |= 1<<bit;\n\n\t\t\tif (c == '!') break;\n\t\t\tneg = true;\n\t\t\tif (!(i >> s)) return i;\n\t\t\tif (s != '-') {\n\t\t\t\tneg = false;\n\t\t\t\ti.putback(s);\n\t\t\t}\n\t\t}\n\t\tif (!(i >> c)) return i;\n\t\tif (c != ']') {\n\t\t\ti.putback(c);\n\t\t\ti.setstate(std::ios::failbit);\n\t\t\treturn i;\n\t\t}\n\t\treturn i;\n\t}\n\n\tuint32 best_rotated_difference(uint32 diff, int rc)\n\t{\n\t\tif (diff == 0 || (rc&31)==0)\n\t\t\treturn diff;\n\n\t\tint rc2 = 32 - rc;\n\t\tuint32 bound = 1 << rc2;\n\t\tuint32 bound2 = 1 << rc;\n\t\tuint32 y = diff >> rc2;\n\t\tuint32 x = diff - (y<<rc2);\n\t\tuint32 p1 = (bound-x)*y;\n\t\tuint32 d1 = ((x<<rc)|y);\n\t\tif ((y<<1) > bound2)\n\t\t\td1 -= bound2;\n\t\telse\n\t\t\tp1 = ((bound-x)<<rc) - p1;\n\n\t\tif (x == 0)\n\t\t\treturn d1;\n\n\t\ty += 1;\n\t\ty &= ~bound2; // erase possible carry at rc-th bit\n\t\tuint32 p2 = x*y;\n\t\tuint32 d2 = ((x<<rc)|y);\n\t\tif ((y<<1) > bound2)\n\t\t\td2 -= bound2;\n\t\telse\n\t\t\tp2 = (x<<rc) - p2;\n\t\tif (p1 > p2)\n\t\t\treturn d1;\n\t\treturn d2;\n\t}\n\n\tvoid rotate_difference(uint32 diff, int rc, std::vector<uint32>& rotateddiff, uint32 minprob)\n\t{\n\t\trotateddiff.clear();\n\t\tif (diff == 0 || (rc&31)==0) {\n\t\t\trotateddiff.push_back(diff);\n\t\t\treturn;\n\t\t}\n\t\t// now p1,p2,p3,p4 < 1 * 2^32, no overflows\n\n\t\tint rc2 = 32 - rc;\n\t\tuint32 bound = 1 << rc2;\n\t\tuint32 bound2 = 1 << rc;\n\t\tuint32 y = diff >> rc2;\n\t\tuint32 x = diff - (y<<rc2);\n\n\t\tuint32 p1 = (bound-x) * y;\n\t\tif (p1 >= minprob)\n\t\t\trotateddiff.push_back( ((x<<rc)|y) - bound2 );\n\t\tuint32 p2 = ((bound-x)<<rc) - p1;\n\t\tif (p2 >= minprob)\n\t\t\trotateddiff.push_back( (x<<rc)|y );\n\n\t\tif (x != 0) {\n\t\t\ty += 1; \n\t\t\ty &= ~bound2; // erase possible carry at rc-th bit\n\n\t\t\tuint32 p3 = x * y;\n\t\t\tif (p3 >= minprob)\n\t\t\t\trotateddiff.push_back( ((x<<rc)|y) - bound2 );\n\t\t\tuint32 p4 = (x<<rc) - p1;\n\t\t\tif (p4 >= minprob)\n\t\t\t\trotateddiff.push_back( (x<<rc)|y );\n\t\t}\n\t}\n\n\tvoid rotate_difference(uint32 diff, int rc, std::vector<std::pair<uint32,double> >& rotateddiff)\n\t{\n\t\tdouble pinv = pow(double(2),-32);\n\n\t\trotateddiff.clear();\n\t\tif (diff == 0 || (rc&31)==0) {\n\t\t\trotateddiff.push_back(std::pair<uint32,double>(diff,1));\n\t\t\treturn;\n\t\t}\n\n\t\tint rc2 = 32 - rc;\n\t\tuint32 bound = 1 << rc2;\n\t\tuint32 bound2 = 1 << rc;\n\t\tuint32 y = diff >> rc2;\n\t\tuint32 x = diff - (y<<rc2);\n\n\t\tuint32 p1 = 0;\n\t\tif (y) {\n\t\t\tp1 = (bound-x) * y;\n\t\t\trotateddiff.push_back( std::pair<uint32,double>\n\t\t\t\t( ((x<<rc)|y) - bound2, double(p1)*pinv ));\t\t\t\n\t\t}\n\n\t\tuint32 p2 = ((bound-x)<<rc) - p1;\n\t\trotateddiff.push_back( std::pair<uint32,double>\n\t\t\t\t( (x<<rc)|y, double(p2)*pinv ));\n\n\t\tuint32 p3 = 0, p4 = 0;\n\t\tif (x != 0) {\n\t\t\ty += 1; \n\t\t\ty &= ~bound2; // erase possible carry at rc-th bit\n\n\t\t\tif (y) {\n\t\t\t\tp3 = x * y;\n\t\t\t\trotateddiff.push_back( std::pair<uint32,double>\n\t\t\t\t\t( ((x<<rc)|y) - bound2, double(p3)*pinv ));\t\t\t\n\t\t\t}\n\n\t\t\tp4 = (x<<rc) - p3;\n\t\t\trotateddiff.push_back( std::pair<uint32,double>\n\t\t\t\t\t( (x<<rc)|y, double(p4)*pinv ));\n\t\t}\n\t}\n\n\tunsigned hw_table[0x800];\n\tstruct sdr_carry {\n\t\tstd::vector< std::vector<sdr> > positive, negative;\n\t};\n\tstd::vector<sdr_carry> hashclash_sc(0);\n\tstd::vector< std::vector< std::pair<unsigned,unsigned> > > hashclash_scn(0);\n\tvoid hashclash_init_scn();\n\n\tunsigned count_sdrs(uint32 n, unsigned maxw)\n\t{\n\t\tif (hashclash_scn.size() == 0) hashclash_init_scn();\n\n\t\tuint32 l = n & 0xFFFF;\n\t\tuint32 h1 = n - l;\n\t\tuint32 h2 = h1 + 0x10000;\n\t\tunsigned h1w = hwnaf(h1);\n\t\tunsigned h2w = hwnaf(h2);\n\t\tunsigned hw = h1w;\n\t\tif (h2w<hw) hw = h2w;\n\n\t\tstd::vector< std::pair<unsigned,unsigned> >& vl = hashclash_scn[l];\n\t\tstd::vector< std::pair<unsigned,unsigned> >& vh1 = hashclash_scn[h1>>16];\n\t\tstd::vector< std::pair<unsigned,unsigned> >& vh2 = hashclash_scn[h2>>16];\n\t\tunsigned tot = 0;\n\n\t\tfor (unsigned i = 0; i < vl.size() && i+hw <= maxw; ++i)\n\t\t{\n\t\t\tif (vl[i].first == 0 && vl[i].second == 0) continue;\n\t\t\tunsigned m = 0;\n\t\t\tfor (unsigned j = 0; j < vh1.size() && i+j<=maxw; ++j)\n\t\t\t\tm += vh1[j].first + vh1[j].second;\n\t\t\ttot += vl[i].first * m;\n\t\t\tm = 0;\n\t\t\tfor (unsigned j = 0; j < vh2.size() && i+j<=maxw; ++j)\n\t\t\t\tm += vh2[j].first + vh2[j].second;\n\t\t\ttot += vl[i].second * m;\n\t\t}\n\t\treturn tot;\n\t}\n\n\ttypedef std::vector< std::vector<sdr> > vec_vec_sdr_t;\n\tvoid table_sdrs(std::vector<sdr>& result, uint32 n, unsigned maxw)\n\t{\n\t\tif (hashclash_scn.size() == 0) hashclash_init_scn();\n\n\t\tresult.clear();\n\t\tif (maxw < hwnaf(n)) return;\n\t\tstd::vector< triple<uint32,uint32,uint32> > breakn(8);\n\t\tstd::vector< triple<vec_vec_sdr_t*, vec_vec_sdr_t*, vec_vec_sdr_t*> > breaknsdr(8);\n\t\tuint32 m0 = n & 0x7FF;\n\t\tuint32 n0 = n - m0;\n\t\tuint32 m1 = n0 & 0x3FFFFF;\n\t\tuint32 m2 = n0 - m1;\n\t\tbreakn[0]=make_triple(m0,m1,m2);\n\t\tbreakn[4]=make_triple(m0,m1,m2);\n\t\tbreaknsdr[0]=make_triple(\n\t\t\t&hashclash_sc[m0].positive,\n\t\t\t&hashclash_sc[m1>>11].positive,\n\t\t\t&hashclash_sc[m2>>21].positive);\n\t\tbreaknsdr[4]=make_triple(\n\t\t\t&hashclash_sc[m0].positive,\n\t\t\t&hashclash_sc[m1>>11].positive,\n\t\t\t&hashclash_sc[m2>>21].negative);\n\n\t\tm2 += 0x400000;\n\t\tbreakn[2]=make_triple(m0,m1,m2);\n\t\tbreakn[6]=make_triple(m0,m1,m2);\n\t\tbreaknsdr[2]=make_triple(\n\t\t\t&hashclash_sc[m0].positive,\n\t\t\t&hashclash_sc[m1>>11].negative,\n\t\t\t&hashclash_sc[m2>>21].positive);\n\t\tbreaknsdr[6]=make_triple(\n\t\t\t&hashclash_sc[m0].positive,\n\t\t\t&hashclash_sc[m1>>11].negative,\n\t\t\t&hashclash_sc[m2>>21].negative);\n\n\t\tn0 += 0x800;\n\t\tm1 = n0 & 0x3FFFFF;\n\t\tm2 = n0 - m1;\n\t\tbreakn[1]=make_triple(m0,m1,m2);\n\t\tbreakn[5]=make_triple(m0,m1,m2);\n\t\tbreaknsdr[1]=make_triple(\n\t\t\t&hashclash_sc[m0].negative,\n\t\t\t&hashclash_sc[m1>>11].positive,\n\t\t\t&hashclash_sc[m2>>21].positive);\n\t\tbreaknsdr[5]=make_triple(\n\t\t\t&hashclash_sc[m0].negative,\n\t\t\t&hashclash_sc[m1>>11].positive,\n\t\t\t&hashclash_sc[m2>>21].negative);\n\n\t\tm2 += 0x400000;\n\t\tbreakn[3]=make_triple(m0,m1,m2);\n\t\tbreakn[7]=make_triple(m0,m1,m2);\n\t\tbreaknsdr[3]=make_triple(\n\t\t\t&hashclash_sc[m0].negative,\n\t\t\t&hashclash_sc[m1>>11].negative,\n\t\t\t&hashclash_sc[m2>>21].positive);\n\t\tbreaknsdr[7]=make_triple(\n\t\t\t&hashclash_sc[m0].negative,\n\t\t\t&hashclash_sc[m1>>11].negative,\n\t\t\t&hashclash_sc[m2>>21].negative);\n\t\tstd::vector<sdr>::const_iterator cit, citend;\n\t\tfor (unsigned l = 0; l < breakn.size(); ++l)\n\t\t{\n\t\t\tm0 = breakn[l].first;\n\t\t\tm1 = breakn[l].second;\n\t\t\tm2 = breakn[l].third;\n\t\t\tvec_vec_sdr_t& v0 = *breaknsdr[l].first;\n\t\t\tvec_vec_sdr_t& v1 = *breaknsdr[l].second;\n\t\t\tvec_vec_sdr_t& v2 = *breaknsdr[l].third;\n\t\t\tunsigned w0 = 0; while (w0 < v0.size() && 0 == v0[w0].size()) ++w0;\n\t\t\tunsigned w1 = 0; while (w1 < v1.size() && 0 == v1[w1].size()) ++w1;\n\t\t\tunsigned w2 = 0; while (w2 < v2.size() && 0 == v2[w2].size()) ++w2;\n\t\t\tunsigned w0max = maxw - w1 - w2;\n\t\t\tunsigned w1max = maxw - w2;\n\t\t\tfor (unsigned i0 = w0; i0 <= w0max && i0 < v0.size(); ++i0)\n\t\t\tfor (unsigned j0 = 0; j0 < v0[i0].size(); ++j0)\n\t\t\t{\n\t\t\t\tsdr temp0 = v0[i0][j0];\n\t\t\t\tfor (unsigned i1 = w1; i0+i1 <= w1max && i1 < v1.size(); ++i1)\n\t\t\t\tfor (unsigned j1 = 0; j1 < v1[i1].size(); ++j1)\n\t\t\t\t{\n\t\t\t\t\tsdr temp1 = temp0;\n\t\t\t\t\ttemp1.mask ^= v1[i1][j1].mask << 11;\n\t\t\t\t\ttemp1.sign ^= v1[i1][j1].sign << 11;\n\t\t\t\t\tfor (unsigned i2 = w2; i0+i1+i2 <= maxw && i2 < v2.size(); ++i2)\n\t\t\t\t\t{\n\t\t\t\t\t\tcit = v2[i2].begin();\n\t\t\t\t\t\tcitend = v2[i2].end();\n\t\t\t\t\t\tfor (; cit != citend; ++cit)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tsdr temp2 = temp1;\n\t\t\t\t\t\t\ttemp2.mask ^= cit->mask << 21;\n\t\t\t\t\t\t\ttemp2.sign ^= cit->sign << 21;\n\t\t\t\t\t\t\tresult.push_back(temp2);\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}\n\n\tunsigned count_sdrs(uint32 n, unsigned w, bool signpos)\n\t{\n\t\tif (hashclash_scn.size() == 0) hashclash_init_scn();\n\n\t\tuint32 l = n & 0xFFFF;\n\t\tuint32 h1 = n - l;\n\t\tuint32 h2 = h1 + 0x10000;\n\t\tunsigned h1w = hwnaf(h1);\n\t\tunsigned h2w = hwnaf(h2);\n\t\tunsigned hw = h1w;\n\t\tif (h2w<hw) hw = h2w;\n\n\t\tstd::vector< std::pair<unsigned,unsigned> >& vl = hashclash_scn[l];\n\t\tstd::vector< std::pair<unsigned,unsigned> >& vh1 = hashclash_scn[h1>>16];\n\t\tstd::vector< std::pair<unsigned,unsigned> >& vh2 = hashclash_scn[h2>>16];\n\t\tunsigned tot = 0;\n\n\t\tfor (unsigned i = 0; i < vl.size() && i+hw <= w; ++i)\n\t\t{\n\t\t\tif (signpos) {\n\t\t\t\tif (w-i < vh1.size())\n\t\t\t\t\ttot += vl[i].first * vh1[w-i].first;\n\t\t\t\tif (w-i < vh2.size())\n\t\t\t\t\ttot += vl[i].second * vh2[w-i].first;\n\t\t\t} else {\n\t\t\t\tif (w-i < vh1.size())\n\t\t\t\t\ttot += vl[i].first * vh1[w-i].second;\n\t\t\t\tif (w-i < vh2.size())\n\t\t\t\t\ttot += vl[i].second * vh2[w-i].second;\n\t\t\t}\n\t\t}\n\t\treturn tot;\n\t}\n\n\tunsigned count_sdrs(sdr n, unsigned maxw, unsigned rot)\n\t{\n\t\tif (hashclash_scn.size() == 0) hashclash_init_scn();\n\n\t\tsdr low = n, high = n;\n\t\thigh.mask >>= 32-rot; high.sign >>= 32-rot;\n\t\tlow.mask &= (~uint32(0))>>rot; low.sign &= low.mask;\n\n\t\tuint32 highdiff = high.adddiff();\n\t\tuint32 lowdiff = low.adddiff();\n\t\tbool lowpos = (lowdiff & 0x80000000)==0;\n\t\tbool highpos = (highdiff & 0x80000000)==0;\n\n\t\tunsigned lowcnt[33];\n\t\tunsigned highcnt[33];\n\t\tunsigned lowhw = hwnaf(lowdiff);\n\t\tunsigned highhw = hwnaf(highdiff);\n\t\tlowdiff <<= rot;\n\t\thighdiff <<= 32-rot;\n\t\tfor (unsigned i = lowhw; i+highhw <= maxw; ++i)\n\t\t\tlowcnt[i] = count_sdrs(lowdiff, i, lowpos);\n\t\tfor (unsigned i = highhw; i+lowhw <= maxw; ++i)\n\t\t\thighcnt[i] = count_sdrs(highdiff, i, highpos);\n\t\tunsigned tot = 0;\n\t\tfor (unsigned wl = lowhw; wl+highhw <= maxw; ++wl)\n\t\t{\n\t\t\tunsigned m = 0;\n\t\t\tfor (unsigned wh = highhw; wh+wl <= maxw; ++wh)\n\t\t\t\tm += highcnt[wh];\n\t\t\ttot += lowcnt[wl] * m;\n\t\t}\n\t\treturn tot;\n\t}\n\n\tvoid table_sdrs(std::vector<sdr>& result, uint32 n, unsigned w, bool signpos)\n\t{\n\t\tif (hashclash_scn.size() == 0) hashclash_init_scn();\n\n\t\tresult.clear();\n\t\tif (w < hwnaf(n)) return;\n\t\tstd::vector< triple<uint32,uint32,uint32> > breakn(4);\n\t\tstd::vector< triple<vec_vec_sdr_t*, vec_vec_sdr_t*, vec_vec_sdr_t*> > breaknsdr(4);\n\t\tuint32 m0 = n & 0x7FF;\n\t\tuint32 n0 = n - m0;\n\t\tuint32 m1 = n0 & 0x3FFFFF;\n\t\tuint32 m2 = n0 - m1;\n\t\tbreakn[0]=make_triple(m0,m1,m2);\n\t\tif (signpos)\n\t\t\tbreaknsdr[0]=make_triple(\n\t\t\t\t&hashclash_sc[m0].positive,\n\t\t\t\t&hashclash_sc[m1>>11].positive,\n\t\t\t\t&hashclash_sc[m2>>21].positive);\n\t\telse\n\t\t\tbreaknsdr[0]=make_triple(\n\t\t\t\t&hashclash_sc[m0].positive,\n\t\t\t\t&hashclash_sc[m1>>11].positive,\n\t\t\t\t&hashclash_sc[m2>>21].negative);\n\n\t\tm2 += 0x400000;\n\t\tbreakn[2]=make_triple(m0,m1,m2);\n\t\tif (signpos)\n\t\t\tbreaknsdr[2]=make_triple(\n\t\t\t\t&hashclash_sc[m0].positive,\n\t\t\t\t&hashclash_sc[m1>>11].negative,\n\t\t\t\t&hashclash_sc[m2>>21].positive);\n\t\telse\n\t\t\tbreaknsdr[2]=make_triple(\n\t\t\t\t&hashclash_sc[m0].positive,\n\t\t\t\t&hashclash_sc[m1>>11].negative,\n\t\t\t\t&hashclash_sc[m2>>21].negative);\n\n\t\tn0 += 0x800;\n\t\tm1 = n0 & 0x3FFFFF;\n\t\tm2 = n0 - m1;\n\t\tbreakn[1]=make_triple(m0,m1,m2);\n\t\tif (signpos)\n\t\t\tbreaknsdr[1]=make_triple(\n\t\t\t\t&hashclash_sc[m0].negative,\n\t\t\t\t&hashclash_sc[m1>>11].positive,\n\t\t\t\t&hashclash_sc[m2>>21].positive);\n\t\telse\n\t\t\tbreaknsdr[1]=make_triple(\n\t\t\t\t&hashclash_sc[m0].negative,\n\t\t\t\t&hashclash_sc[m1>>11].positive,\n\t\t\t\t&hashclash_sc[m2>>21].negative);\n\n\t\tm2 += 0x400000;\n\t\tbreakn[3]=make_triple(m0,m1,m2);\n\t\tif (signpos)\n\t\t\tbreaknsdr[3]=make_triple(\n\t\t\t\t&hashclash_sc[m0].negative,\n\t\t\t\t&hashclash_sc[m1>>11].negative,\n\t\t\t\t&hashclash_sc[m2>>21].positive);\n\t\telse\n\t\t\tbreaknsdr[3]=make_triple(\n\t\t\t\t&hashclash_sc[m0].negative,\n\t\t\t\t&hashclash_sc[m1>>11].negative,\n\t\t\t\t&hashclash_sc[m2>>21].negative);\n\t\tstd::vector<sdr>::const_iterator cit, citend;\n\t\tfor (unsigned l = 0; l < breakn.size(); ++l)\n\t\t{\n\t\t\tm0 = breakn[l].first;\n\t\t\tm1 = breakn[l].second;\n\t\t\tm2 = breakn[l].third;\n\t\t\tvec_vec_sdr_t& v0 = *breaknsdr[l].first;\n\t\t\tvec_vec_sdr_t& v1 = *breaknsdr[l].second;\n\t\t\tvec_vec_sdr_t& v2 = *breaknsdr[l].third;\n\t\t\tunsigned w0 = 0; while (w0 < v0.size() && 0 == v0[w0].size()) ++w0;\n\t\t\tunsigned w1 = 0; while (w1 < v1.size() && 0 == v1[w1].size()) ++w1;\n\t\t\tunsigned w2 = 0; while (w2 < v2.size() && 0 == v2[w2].size()) ++w2;\n\t\t\tunsigned w0max = w - w1 - w2;\n\t\t\tunsigned w1max = w - w2;\n\t\t\tfor (unsigned i0 = w0; i0 <= w0max && i0 < v0.size(); ++i0)\n\t\t\tfor (unsigned j0 = 0; j0 < v0[i0].size(); ++j0)\n\t\t\t{\n\t\t\t\tsdr temp0 = v0[i0][j0];\n\t\t\t\tfor (unsigned i1 = w1; i0+i1 <= w1max && i1 < v1.size(); ++i1)\n\t\t\t\tif (w-i0-i1 < v2.size())\n\t\t\t\tfor (unsigned j1 = 0; j1 < v1[i1].size(); ++j1)\n\t\t\t\t{\n\t\t\t\t\tsdr temp1 = temp0;\n\t\t\t\t\ttemp1.mask ^= v1[i1][j1].mask << 11;\n\t\t\t\t\ttemp1.sign ^= v1[i1][j1].sign << 11;\n\t\t\t\t\tcit = v2[w - i0 - i1].begin();\n\t\t\t\t\tcitend = v2[w - i0 - i1].end();\n\t\t\t\t\tfor (; cit != citend; ++cit)\n\t\t\t\t\t{\n\t\t\t\t\t\tsdr temp2 = temp1;\n\t\t\t\t\t\ttemp2.mask ^= cit->mask << 21;\n\t\t\t\t\t\ttemp2.sign ^= cit->sign << 21;\n\t\t\t\t\t\tresult.push_back(temp2);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tvoid table_sdrs(std::vector<sdr>& result, sdr n, unsigned maxw, unsigned rot)\n\t{\n\t\tif (hashclash_scn.size() == 0) hashclash_init_scn();\n\n\t\tresult.clear();\n\t\tif (maxw < hwnaf(n)) return;\n\t\tsdr low = n, high = n;\n\t\thigh.mask >>= 32-rot; high.sign >>= 32-rot;\n\t\tlow.mask &= (~uint32(0))>>rot; low.sign &= low.mask;\n\n\t\tuint32 highdiff = high.adddiff();\n\t\tuint32 lowdiff = low.adddiff();\n\t\tbool lowpos = (lowdiff & 0x80000000)==0;\n\t\tbool highpos = (highdiff & 0x80000000)==0;\n\n\t\tstd::vector< std::vector<sdr> > lowsdrs(33);\n\t\tstd::vector< std::vector<sdr> > highsdrs(33);\n\t\tunsigned lowhw = hwnaf(lowdiff);\n\t\tunsigned highhw = hwnaf(highdiff);\n\t\tlowdiff <<= rot;\n\t\thighdiff <<= 32-rot;\n\t\tfor (unsigned i = lowhw; i <= maxw-highhw; ++i)\n\t\t\ttable_sdrs(lowsdrs[i], lowdiff, i, lowpos);\t\t\t\n\t\tfor (unsigned i = highhw; i <= maxw-lowhw; ++i)\n\t\t\ttable_sdrs(highsdrs[i], highdiff, i, highpos);\n\t\tfor (unsigned wl = lowhw; wl <= maxw-highhw; ++wl)\n\t\t\tfor (unsigned l0 = 0; l0 < lowsdrs[wl].size(); ++l0)\n\t\t\t{\n\t\t\t\tsdr temp0 = lowsdrs[wl][l0];\n\t\t\t\tif (temp0.hw() != wl) throw;\n\t\t\t\ttemp0.mask >>= rot;\n\t\t\t\ttemp0.sign >>= rot;\n\t\t\t\tfor (unsigned wh = highhw; wh+wl <= maxw; ++wh)\n\t\t\t\t\tfor (unsigned h0 = 0; h0 < highsdrs[wh].size(); ++h0)\n\t\t\t\t\t{\n\t\t\t\t\t\tsdr temp1 = highsdrs[wh][h0];\n\t\t\t\t\t\tif (temp1.hw() != wh) throw;\n\t\t\t\t\t\ttemp1.mask ^= temp0.mask;\n\t\t\t\t\t\ttemp1.sign ^= temp0.sign;\n\t\t\t\t\t\tresult.push_back(temp1);\n\t\t\t\t\t}\n\t\t\t}\n\t}\n\n\n\tboost::mutex hashclash_init_scn_mutex;\n\tvoid hashclash_init_scn()\n\t{\n\t\tboost::lock_guard<boost::mutex> lock(hashclash_init_scn_mutex);\n\t\tif (hashclash_scn.size()) return;\n\t\tstd::vector< std::vector< std::pair<unsigned,unsigned> > > hashclash_scn2(0);\n/*\t\ttry {\n\t\t\tload_gz(hashclash_scn2, \"hashclash_scn\", binary_archive);\n\t\t\thashclash_scn.swap(hashclash_scn2);\n\t\t} catch(...) {\n\t\t\thashclash_scn2.clear();\n\t\t}\n\t\tif (hashclash_scn.size()) return;\n*/\n\t\tsdr temp(0);\n\t\thashclash_scn2.resize(1<<16);\t\n\t\tfor (temp.mask = 0; temp.mask < 0x10000; ++temp.mask)\n\t\t\tfor (temp.sign = 0; temp.sign <= temp.mask; ++temp.sign)\n\t\t\t{\n\t\t\t\tif (temp.sign & (~temp.mask)) continue;\n\t\t\t\tunsigned w = temp.hw();\n\t\t\t\tuint32 n = temp.adddiff();\n\t\t\t\tif (n & 0x80000000) // negative\n\t\t\t\t{\n\t\t\t\t\tn += 0x10000;\n\t\t\t\t\tif (hashclash_scn2[n].size() < w+1)\n\t\t\t\t\t\thashclash_scn2[n].resize(w+1);\n\t\t\t\t\t++hashclash_scn2[n][w].second;\n\t\t\t\t} else // positive\n\t\t\t\t{\n\t\t\t\t\tif (hashclash_scn2[n].size() < w+1)\n\t\t\t\t\t\thashclash_scn2[n].resize(w+1);\n\t\t\t\t\t++hashclash_scn2[n][w].first;\n\t\t\t\t}\n\t\t\t}\n/*\n\t\ttry {\n\t\t\tsave_gz(hashclash_scn2, \"hashclash_scn\", binary_archive);\n\t\t} catch (...)\n\t\t{}\n*/\n\t\thashclash_scn.swap(hashclash_scn2);\n\t}\n\n\tstruct hashclash_sdr__init {\n\t\thashclash_sdr__init()\n\t\t{\n\t\t\tinit_hwtable();\n\t\t\tinit_sc();\n\t\t}\n\n\t\tvoid init_hwtable()\n\t\t{\n\t\t\tfor (uint32 n = 0; n < 0x800; ++n)\n\t\t\t{\n\t\t\t\tunsigned w = 0;\n\t\t\t\tuint32 k = n;\n\t\t\t\twhile (k) {\n\t\t\t\t\tw += k & 1;\n\t\t\t\t\tk >>= 1;\n\t\t\t\t}\n\t\t\t\thw_table[n] = w;\n\t\t\t}\n\t\t}\n\n\t\tvoid init_sc()\n\t\t{\n\t\t\thashclash_sc.resize(0x800);\n\t\t\tsdr temp;\n\t\t\tfor (temp.mask = 0; temp.mask < 0x800; ++temp.mask)\n\t\t\t\tfor (temp.sign = 0; temp.sign < 0x800; ++temp.sign)\n\t\t\t\t{\n\t\t\t\t\tif (temp.mask != (temp.sign | temp.mask)) continue;\n\t\t\t\t\tuint32 n = temp.adddiff();\n\t\t\t\t\tunsigned w = temp.hw();\n\t\t\t\t\tif (n & 0x80000000) // negative\n\t\t\t\t\t{\n\t\t\t\t\t\tn += 0x800;\n\t\t\t\t\t\tif (hashclash_sc[n].negative.size() < w+1)\n\t\t\t\t\t\t\thashclash_sc[n].negative.resize(w+1);\n\t\t\t\t\t\thashclash_sc[n].negative[w].push_back(temp);\n\t\t\t\t\t} else // positive\n\t\t\t\t\t{\n\t\t\t\t\t\tif (hashclash_sc[n].positive.size() < w+1)\n\t\t\t\t\t\t\thashclash_sc[n].positive.resize(w+1);\n\t\t\t\t\t\thashclash_sc[n].positive[w].push_back(temp);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t}\n\t};\n\thashclash_sdr__init hashclash_sdr__init__now;\n\n\tvoid hashclash_sdr_hpp_init()\n\t{\n\t\thashclash_sdr__init here;\n\t}\n\n\n} // namespace\n", "meta": {"hexsha": "cf979767dd7a9b7139ff4ffdb1ad8d0bf1e4b096", "size": 18130, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lib/hashclash/sdr.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": "lib/hashclash/sdr.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": "lib/hashclash/sdr.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": 26.2753623188, "max_line_length": 97, "alphanum_fraction": 0.5808604523, "num_tokens": 6821, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5195213219520929, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.303972525107358}}
{"text": "/* Copyright (c) 2017, United States Government, as represented by the\n * Administrator of the National Aeronautics and Space Administration.\n * \n * All rights reserved.\n * \n * The Astrobee platform is licensed under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with the\n * License. You may obtain a copy of the License at\n * \n *     http://www.apache.org/licenses/LICENSE-2.0\n * \n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n * License for the specific language governing permissions and limitations\n * under the License.\n */\n\n/**\n * Given camera parameters and noise estimates, this program\n * estimates the error that global localization via either\n * RANSAC or least-squares will have.\n **/\n#include <common/init.h>\n#include <common/thread.h>\n#include <camera/camera_model.h>\n#include <sparse_mapping/reprojection.h>\n\n#include <Eigen/Geometry>\n#include <ceres/ceres.h>\n#include <gflags/gflags.h>\n#include <glog/logging.h>\n#include <opencv2/features2d/features2d.hpp>\n\nDEFINE_bool(ransac, false,\n              \"Use RANSAC algorithm. If not use ceres solver.\");\n\n// Observation parameters\nDEFINE_uint64(num_observations, 20,\n             \"Number of landmarks to observe.\");\nDEFINE_double(map_error, 0.01,\n             \"Std. dev. error of the mapped position, in m, for each dimension.\");\nDEFINE_double(feature_error, 0,\n             \"Std. dev. error from feature detection, in pixels, for each dimension.\");\nDEFINE_double(mismatch_prob, 0.0,\n             \"The probability of an observation matching to the wrong landmark.\");\n\n// Camera parameters\nDEFINE_double(fov_x, 170.0,\n              \"Horizontal field of view in degrees.\");\nDEFINE_int32(xres, 640,\n             \"Horizontal resolution.\");\nDEFINE_int32(yres, 480,\n             \"Vertical resolution.\");\n\n// Environment parameters\nDEFINE_double(visible_distance, 8.0,\n             \"Distance features are visible to camera.\");\nDEFINE_double(env_width, 6.0,\n             \"Width of the rectangular prism camera is inside.\");\nDEFINE_double(env_height, 6.0,\n             \"Height of the rectangular prism camera is inside.\");\nDEFINE_double(env_length, 20.0,\n             \"Length of the rectangular prism camera is inside.\");\nDEFINE_double(env_clutter, 0.5,\n             \"Distance within landmarks are located from the walls.\");\n\n// Initial error parameters\nDEFINE_double(guess_angle_error, 0.04 * M_PI,\n             \"Std. dev. angle error of initial transform guess.\");\nDEFINE_double(guess_distance_error, 0.5,\n             \"Std. dev. distance error of initial transform guess.\");\n\n// Number of trials\nDEFINE_int32(num_trials, 250,\n             \"Number of trials to gather statistics on\");\n\n// Ceres parameters\nDEFINE_int32(max_num_iterations, 10000,\n             \"Maximum number of iterations for solver\");\n\n// RANSAC parameters\nDEFINE_int32(ransac_inlier_tolerance, 3,\n              \"Maximum error in pixels for a projection to be considered correct.\");\nDEFINE_int32(ransac_iterations, 100,\n              \"Number of iterations of RANSAC.\");\n\n\nunsigned int rand_seed;\ndouble rand_d() {\n  return static_cast<double>(rand_r(&rand_seed)) / RAND_MAX;\n}\n\nEigen::Vector3d EnvironmentIntersection(Eigen::Vector3d origin, Eigen::Vector3d dir) {\n  double W = FLAGS_env_width / 2, H = FLAGS_env_height / 2, L = FLAGS_env_length / 2, P = FLAGS_env_clutter;\n  // check each plane for intersection\n  // x = -W plane\n  // origin + dir * t = (-W, a, b)\n  double t = (-W - origin.x()) / dir.x();\n  if (t >= 0) {\n    Eigen::Vector3d p = origin + t * dir;\n    if (p.z() >= -L && p.z() <= L && p.y() >= -H && p.y() <= H)\n      return p + rand_d() * P * Eigen::Vector3d(0, 0, 1);\n  }\n  // x = W\n  t = (W - origin.x()) / dir.x();\n  if (t >= 0) {\n    Eigen::Vector3d p = origin + t * dir;\n    if (p.z() >= -L && p.z() <= L && p.y() >= -H && p.y() <= H)\n      return p + rand_d() * P * Eigen::Vector3d(0, 0, -1);\n  }\n  // y = -H\n  t = (-H - origin.y()) / dir.y();\n  if (t >= 0) {\n    Eigen::Vector3d p = origin + t * dir;\n    if (p.x() >= -W && p.x() <= W && p.z() >= -L && p.z() <= L)\n      return p + rand_d() * P * Eigen::Vector3d(0, 1, 0);\n  }\n  // y = H\n  t = (H - origin.y()) / dir.y();\n  if (t >= 0) {\n    Eigen::Vector3d p = origin + t * dir;\n    if (p.x() >= -W && p.x() <= W && p.z() >= -L && p.z() <= L)\n      return p + rand_d() * P * Eigen::Vector3d(0, -1, 0);\n  }\n  // z = -L\n  t = (-L - origin.z()) / dir.z();\n  if (t >= 0) {\n    Eigen::Vector3d p = origin + t * dir;\n    if (p.x() >= -W && p.x() <= W && p.y() >= -H && p.y() <= H)\n      return p + rand_d() * P * Eigen::Vector3d(0, 0, 1);\n  }\n  // z = L\n  t = (L - origin.z()) / dir.z();\n  Eigen::Vector3d p = origin + t * dir;\n  return p + rand_d() * P * Eigen::Vector3d(0, 0, -1);\n}\n\nEigen::Vector3d RandomLandmark(std::default_random_engine gen) {\n  double W = FLAGS_env_width / 2, H = FLAGS_env_height / 2, L = FLAGS_env_length / 2, P = FLAGS_env_clutter;\n  std::uniform_int_distribution<int> face(0, 5);\n  std::uniform_real_distribution<double> uniform(-1.0, 1.0);\n  std::uniform_real_distribution<double> clutter(0.0, P);\n  int f = face(gen);\n  if (f == 0)\n    return Eigen::Vector3d(uniform(gen) * W, uniform(gen) * H, L - clutter(gen));\n  else if (f == 1)\n    return Eigen::Vector3d(uniform(gen) * W, uniform(gen) * H, -L + clutter(gen));\n  else if (f == 2)\n    return Eigen::Vector3d(uniform(gen) * W, H - clutter(gen), uniform(gen) * L);\n  else if (f == 3)\n    return Eigen::Vector3d(uniform(gen) * W, -H + clutter(gen), uniform(gen) * L);\n  else if (f == 4)\n    return Eigen::Vector3d(W - clutter(gen), uniform(gen) * H, uniform(gen) * L);\n  return Eigen::Vector3d(-W + clutter(gen), uniform(gen) * H, uniform(gen) * L);\n}\n\nvoid GenerateLandmarkObservations(const camera::CameraModel & camera,\n                                  std::vector<Eigen::Vector3d>* pid_to_xyz,\n                                  std::vector<Eigen::Vector2d>* observations) {\n  std::default_random_engine gen;\n  std::normal_distribution<double> map_error(0.0, FLAGS_map_error);\n  std::normal_distribution<double> feature_error(0.0, FLAGS_feature_error);\n  std::uniform_real_distribution<double> uniform(0.0, 1.0);\n  while (pid_to_xyz->size() < FLAGS_num_observations) {\n    Eigen::Vector3d ray = camera.Ray(rand_d() * FLAGS_xres, rand_d() * FLAGS_yres);\n    Eigen::Vector3d landmark = EnvironmentIntersection(camera.GetPosition(), ray);\n    if (!camera.IsInFov(landmark) ||\n        (landmark - camera.GetPosition()).norm() > FLAGS_visible_distance)\n      continue;\n    Eigen::Vector3d map_landmark =\n      landmark + Eigen::Vector3d(map_error(gen), map_error(gen), map_error(gen));\n    // Purposely introducing rounding error here.\n    Eigen::Vector2i image_coords = (camera.ImageCoordinates(landmark).array() + 0.5).cast<int>();\n    Eigen::Vector2d obs(image_coords.x() + feature_error(gen), image_coords.y() + feature_error(gen));\n\n    if (FLAGS_mismatch_prob > 0.0 && uniform(gen) <= FLAGS_mismatch_prob)\n      map_landmark = RandomLandmark(gen);\n    pid_to_xyz->push_back(map_landmark);\n    observations->push_back(obs);\n  }\n}\n\nvoid EstimateRandomCameraError(double* dist_error, double* angle_error) {\n  // initialize random camera model with specified parameters\n  double C = 4 * FLAGS_env_clutter;\n  double W = FLAGS_env_width - 2 * C, H = FLAGS_env_height - 2 * C, L = FLAGS_env_length - 2 * C;\n  Eigen::Vector3d true_camera_pos(rand_d() * W - W / 2, rand_d() * H - H / 2, rand_d() * L - L / 2);\n  Eigen::Matrix3d true_camera_rotation;\n  true_camera_rotation = Eigen::AngleAxisd(rand_d() * M_2_PI, Eigen::Vector3d::UnitX())\n                       * Eigen::AngleAxisd(rand_d() * M_2_PI, Eigen::Vector3d::UnitY())\n                       * Eigen::AngleAxisd(rand_d() * M_2_PI, Eigen::Vector3d::UnitZ());\n  camera::CameraModel camera(true_camera_pos, true_camera_rotation,\n                     FLAGS_fov_x * M_PI / 180.0, FLAGS_xres, FLAGS_yres);\n\n  // create landmarks in field of view and simulate observations\n  std::vector<Eigen::Vector3d> pid_to_xyz;  // landmark locations\n  std::vector<Eigen::Vector2d> observations;  // observed camera coordinates of each landmark\n  GenerateLandmarkObservations(camera, &pid_to_xyz, &observations);\n\n  // create initial pose estimate\n  std::default_random_engine gen;\n  std::normal_distribution<double> guess_dist_err(0.0, FLAGS_guess_distance_error);\n  std::normal_distribution<double> guess_angle_err(0.0, FLAGS_guess_angle_error);\n  Eigen::Vector3d guess_pos(true_camera_pos);\n  guess_pos += Eigen::Vector3d(guess_dist_err(gen), guess_dist_err(gen), guess_dist_err(gen));\n  Eigen::Matrix3d guess_rotation(true_camera_rotation);\n  guess_rotation = guess_rotation * Eigen::AngleAxisd(guess_angle_err(gen), Eigen::Vector3d::UnitX())\n                    * Eigen::AngleAxisd(guess_angle_err(gen), Eigen::Vector3d::UnitY())\n                    * Eigen::AngleAxisd(guess_angle_err(gen), Eigen::Vector3d::UnitZ());\n  camera::CameraModel guess(guess_pos, guess_rotation, camera.GetParameters());\n\n  if (!FLAGS_ransac) {\n    // Solve the problem\n    ceres::Solver::Options options;\n    options.linear_solver_type = ceres::ITERATIVE_SCHUR;\n    options.num_threads = FLAGS_num_threads;\n    options.max_num_iterations = FLAGS_max_num_iterations;\n    options.minimizer_progress_to_stdout = false;\n    ceres::Solver::Summary summary;\n    sparse_mapping::EstimateCamera(&guess, &pid_to_xyz, observations, options, &summary);\n  } else {\n    sparse_mapping::RansacEstimateCamera(pid_to_xyz, observations, FLAGS_ransac_iterations,\n                                         FLAGS_ransac_inlier_tolerance, &guess);\n  }\n\n  Eigen::Vector3d orig_angle = camera.GetRotation() * Eigen::Vector3d::UnitX();\n  Eigen::Vector3d observed_angle = guess.GetRotation() * Eigen::Vector3d::UnitX();\n\n  // set errors\n  *dist_error = (true_camera_pos - guess.GetPosition()).norm();\n  *angle_error = acos(observed_angle.dot(orig_angle));\n}\n\nint main(int argc, char** argv) {\n  common::InitFreeFlyerApplication(&argc, &argv);\n  rand_seed = time(NULL);\n\n  double dist_error_mean = 0.0, dist_error_mean_2 = 0.0;\n  double angle_error_mean = 0.0, angle_error_mean_2 = 0.0;\n  for (int i = 0; i < FLAGS_num_trials; i++) {\n    double dist_error = 0.0, angle_error = 0.0;\n    EstimateRandomCameraError(&dist_error, &angle_error);\n    dist_error_mean += dist_error;\n    dist_error_mean_2 += dist_error * dist_error;\n    angle_error_mean += angle_error;\n    angle_error_mean_2 += angle_error * angle_error;\n  }\n  dist_error_mean    /= FLAGS_num_trials;\n  angle_error_mean   /= FLAGS_num_trials;\n  dist_error_mean_2  /= FLAGS_num_trials;\n  angle_error_mean_2 /= FLAGS_num_trials;\n  double dist_std_dev = sqrt(dist_error_mean_2 - dist_error_mean * dist_error_mean);\n  double angle_std_dev = sqrt(angle_error_mean_2 - angle_error_mean * angle_error_mean);\n  std::cout << \"Distance Error: \" << (dist_error_mean * 100.0) << \" +/- \" <<\n    (dist_std_dev * 100.0) << \" cm\" << \"\\n\";\n  std::cout << \"Angle Error: \" << (angle_error_mean * 180.0 / M_PI) << \" +/- \" <<\n    (angle_std_dev * 180.0 / M_PI) << \" degrees\" << \"\\n\";\n\n  return 0;\n}\n", "meta": {"hexsha": "9f6a41e3381e63d391d49449c5c2ed3d9f4ac3e3", "size": 11236, "ext": "cc", "lang": "C++", "max_stars_repo_path": "localization/sparse_mapping/tools/evaluate_camera.cc", "max_stars_repo_name": "PeterWofford/astrobee", "max_stars_repo_head_hexsha": "d4c05f6a938f0d56f071ee79ce86d90c24f1b2cb", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2018-01-04T02:00:49.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-29T20:32:07.000Z", "max_issues_repo_path": "localization/sparse_mapping/tools/evaluate_camera.cc", "max_issues_repo_name": "PeterWofford/astrobee", "max_issues_repo_head_hexsha": "d4c05f6a938f0d56f071ee79ce86d90c24f1b2cb", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "localization/sparse_mapping/tools/evaluate_camera.cc", "max_forks_repo_name": "PeterWofford/astrobee", "max_forks_repo_head_hexsha": "d4c05f6a938f0d56f071ee79ce86d90c24f1b2cb", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-02-20T06:02:33.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-21T11:45:47.000Z", "avg_line_length": 42.8854961832, "max_line_length": 108, "alphanum_fraction": 0.6621573514, "num_tokens": 3095, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6224593312018546, "lm_q2_score": 0.48828339529583464, "lm_q1q2_score": 0.303936555672816}}
{"text": "// Copyright (c) 2019-2020 Ricardo Tonet\n// Use of this source code is governed by the MIT license, see LICENSE\n\n/**\n * \\file trajectory_planner.cpp\n * \\brief Defines TrajectoryPlanner class for robot arm trajectory planning.\n */\n\n#include <smalldrop_toolpath/trajectory_planner.h>\n#include <smalldrop_state/exceptions.h>\n\n#include <Eigen/Dense>\n\nnamespace smalldrop\n{\nnamespace smalldrop_toolpath\n{\n/*****************************************************************************************\n * Public methods & constructors/destructors\n *****************************************************************************************/\n\n/**\n * \\copybrief TrajectoryPlanner::TrajectoryPlanner(const double duration, const double frequency, const PLAN_MODE\n * plan_mode)\n */\nTrajectoryPlanner::TrajectoryPlanner(const double duration, const double frequency, const PLAN_MODE plan_mode)\n  : duration_(duration), frequency_(frequency), plan_mode_(plan_mode), max_speed_(50)\n{\n}\n\n/**\n * \\copybrief TrajectoryPlanner::TrajectoryPlanner(const double duration, const double frequency, const PLAN_MODE plan_mode, const double max_speed) \n */\nTrajectoryPlanner::TrajectoryPlanner(const double duration, const double frequency, const PLAN_MODE plan_mode, const double max_speed)\n  : duration_(duration), frequency_(frequency), plan_mode_(plan_mode), max_speed_(max_speed)\n{\n}\n\n/**\n * \\copybrief TrajectoryPlanner::plan(const Path& path)\n */\nTrajectory TrajectoryPlanner::plan(const Path& path)\n{\n  // Check if speed exceeds upper bound\n  if (duration_ > 0 && path.length()/duration_ > max_speed_)\n    throw smalldrop_state::TrajectoryMaxSpeedExceededException();\n\n  poses_t trajectory;\n  poses_t poses = path.poses();\n  unsigned int npoints = poses.size();\n  double t_interval = duration_ / ((double)npoints-1);\n\n  Trajectory t(trajectory, 0, duration_);\n\n  if (duration_ > 0 && frequency_ > 0)\n  {\n    for (size_t i = 0; i < npoints - 1; i++)\n    {\n      double t = 0;\n      while (t <= t_interval + 0.0001)\n      {\n        switch (plan_mode_)\n        {\n          case PLAN_MODE::LSPB:\n            trajectory.push_back(lspb(poses[i], poses[i + 1], LSPB_ACCEL, 0, t_interval, t));\n            break;\n          default:  // PLAN_MODE::POLY3\n            trajectory.push_back(poly3(poses[i], poses[i + 1], 0, t_interval, t));\n            break;\n        }\n        t += 1 / frequency_;\n      }\n    }\n\n    Trajectory traj(trajectory, path.length(), duration_);\n    t = traj;\n  }\n\n  return t;\n}\n\n/**\n * \\copybrief TrajectoryPlanner::plan(const paths_t paths)\n */\nTrajectory TrajectoryPlanner::plan(const paths_t paths)\n{\n  // Check if speed exceeds upper bound\n  if (duration_ > 0 && getFullPathLength(paths)/duration_ > max_speed_)\n    throw smalldrop_state::TrajectoryMaxSpeedExceededException();\n\n  poses_t trajectory;\n  double path_duration = duration_ / paths.size();\n\n  Trajectory t(trajectory, 0, duration_);\n\n  if (duration_ > 0 && frequency_ > 0)\n  {\n    for (size_t i = 0; i < paths.size(); i++)\n    {\n      poses_t poses = paths[i].poses();\n      unsigned int npoints = poses.size();\n      double t_interval = path_duration / ((double)npoints-1);\n\n      for (size_t j = 0; j < npoints - 1; j++)\n      {\n        double t = 0;\n        while (t <= t_interval + 0.0001)\n        {\n          switch (plan_mode_)\n          {\n            case PLAN_MODE::LSPB:\n              trajectory.push_back(lspb(poses[j], poses[j + 1], LSPB_ACCEL, 0, t_interval, t));\n              break;\n            default:  // PLAN_MODE::POLY3\n              trajectory.push_back(poly3(poses[j], poses[j + 1], 0, t_interval, t));\n              break;\n          }\n          t += 1 / frequency_;\n        }\n      }\n    }\n\n    Trajectory traj(trajectory, getFullPathLength(paths), duration_);\n    t = traj;\n  }\n\n  return t;\n}\n\n/**\n * \\copybrief TrajectoryPlanner::plan(const Toolpath& toolpath)\n */\nTrajectory TrajectoryPlanner::plan(const ToolPath& toolpath)\n{\n  // Check if speed exceeds upper bound\n  if (duration_ > 0 && toolpath.length()/duration_ > max_speed_)\n    throw smalldrop_state::TrajectoryMaxSpeedExceededException();\n\n  poses_t trajectory;\n  path_actions_t trajectory_actions;\n  poses_t poses = toolpath.poses();\n  unsigned int npoints = poses.size();\n  double t_interval = duration_ / ((double)npoints-1);\n\n  Trajectory t(trajectory, trajectory_actions, 0, duration_);\n\n  if (duration_ > 0 && frequency_ > 0)\n  {\n    for (size_t i = 0; i < npoints - 1; i++)\n    {\n      double t = 0;\n      while (t <= t_interval + 0.0001)\n      {\n        switch (plan_mode_)\n        {\n          case PLAN_MODE::LSPB:\n            trajectory.push_back(lspb(poses[i], poses[i + 1], LSPB_ACCEL, 0, t_interval, t));\n            break;\n          default:  // PLAN_MODE::POLY3\n            trajectory.push_back(poly3(poses[i], poses[i + 1], 0, t_interval, t));\n            break;\n        }\n        t += 1 / frequency_;\n      }\n    }\n\n    Trajectory traj(trajectory, toolpath.actions(), toolpath.length(), duration_);\n    t = traj;\n  }\n\n  return t;\n}\n\n/**\n * \\copybrief Trajectory TrajectoryPlanner::plan(const toolpaths_t toolpaths)\n */\nTrajectory TrajectoryPlanner::plan(const toolpaths_t toolpaths)\n{\n  // Check if speed exceeds upper bound\n  if (duration_ > 0 && getFullPathLength(toolpaths)/duration_ > max_speed_)\n    throw smalldrop_state::TrajectoryMaxSpeedExceededException();\n\n  poses_t trajectory;\n  path_actions_t trajectory_actions;\n  double path_duration = duration_ / toolpaths.size();\n\n  Trajectory t(trajectory, trajectory_actions, 0, duration_);\n\n  if (duration_ > 0 && frequency_ > 0)\n  {\n    for (size_t i = 0; i < toolpaths.size(); i++)\n    {\n      poses_t poses = toolpaths[i].poses();\n      path_actions_t actions = toolpaths[i].actions();\n      unsigned int npoints = poses.size();\n      double t_interval = path_duration / ((double)npoints-1);\n\n      for (size_t j = 0; j < npoints - 1; j++)\n      {\n        PRINT_ACTION action = actions[j];\n        double t = 0;\n        while (t <= t_interval + 0.0001)\n        {\n          switch (plan_mode_)\n          {\n            case PLAN_MODE::LSPB:\n              trajectory.push_back(lspb(poses[j], poses[j + 1], LSPB_ACCEL, 0, t_interval, t));\n              trajectory_actions.push_back(action);\n              break;\n            default:  // PLAN_MODE::POLY3\n              trajectory.push_back(poly3(poses[j], poses[j + 1], 0, t_interval, t));\n              trajectory_actions.push_back(action);\n              break;\n          }\n          t += 1 / frequency_;\n        }\n      }\n    }\n\n    Trajectory traj(trajectory, trajectory_actions, getFullPathLength(toolpaths), duration_);\n    t = traj;\n  }\n\n  return t;\n}\n\n/**\n * \\copybrief TrajectoryPlanner::setDuration()\n */\nvoid TrajectoryPlanner::setDuration(const double duration)\n{\n  duration_ = duration;\n}\n\n/**\n * \\copybrief TrajectoryPlanner::setFrequency()\n */\nvoid TrajectoryPlanner::setFrequency(const double frequency)\n{\n  frequency_ = frequency;\n}\n\n/**\n * \\copybrief TrajectoryPlanner::setPlanMode()\n */\nvoid TrajectoryPlanner::setPlanMode(const PLAN_MODE plan_mode)\n{\n  plan_mode_ = plan_mode;\n}\n\n/**\n * \\copybrief TrajectoryPlanner::setMaxSpeed(const double max_speed)\n */\nvoid TrajectoryPlanner::setMaxSpeed(const double max_speed)\n{\n  max_speed_ = max_speed;\n}\n\n/*****************************************************************************************\n * Private methods\n *****************************************************************************************/\n\n/**\n * \\copybrief double viaVelocity(const double pos_before, const double pos, const double pos_after, const double\n * t_before, const double t, const double t_after) const\n */\ndouble TrajectoryPlanner::viaVelocity(const double pos_before, const double pos, const double pos_after,\n                                      const double t_before, const double t, const double t_after) const\n{\n  double velocity_i, velocity_ii;\n\n  velocity_i = (pos - pos_before) / (t - t_before);  // Mean velocity before via point\n  velocity_ii = (pos_after - pos) / (t_after - t);   // Mean velocity after via point\n\n  if ((velocity_i * velocity_ii) < 0)  // Mean velocities change signal at via point\n    return 0.0;                        // Velocity at via point is zero\n  else\n    return 0.5 * (velocity_ii + velocity_i);  // Velocity at via point is the average of the mean velocities\n}\n\n/**\n * \\copybrief pose_t poly3(const pose_t pose_i, const pose_t pose_f, const double t0, const double tf, const double t)\n * const\n */\npose_t TrajectoryPlanner::poly3(const pose_t pose_i, const pose_t pose_f, const double t0, const double tf,\n                                const double t) const\n{\n  std::vector<double> a0 = { pose_i.position.x, pose_i.position.y, pose_i.position.z };\n  std::vector<double> a1 = { 0, 0, 0 };\n  std::vector<double> a2 = { (3 / pow(tf - t0, 2)) * (pose_f.position.x - pose_i.position.x),\n                             (3 / pow(tf - t0, 2)) * (pose_f.position.y - pose_i.position.y),\n                             (3 / pow(tf - t0, 2)) * (pose_f.position.z - pose_i.position.z) };\n  std::vector<double> a3 = { -(2 / pow(tf - t0, 3)) * (pose_f.position.x - pose_i.position.x),\n                             -(2 / pow(tf - t0, 3)) * (pose_f.position.y - pose_i.position.y),\n                             -(2 / pow(tf - t0, 3)) * (pose_f.position.z - pose_i.position.z) };\n\n  // Apply slerp\n  Eigen::Quaterniond qres;\n  Eigen::Quaterniond q0(pose_i.orientation.w, pose_i.orientation.x, pose_i.orientation.y, pose_i.orientation.z);\n  Eigen::Quaterniond qf(pose_f.orientation.w, pose_f.orientation.x, pose_f.orientation.y, pose_f.orientation.z);\n  qres = q0.slerp((t - t0) / (tf - t0), qf);\n\n  pose_t pose;\n  pose.position.x = a0[0] + a1[0] * (t - t0) + a2[0] * pow(t - t0, 2) + a3[0] * pow(t - t0, 3);\n  pose.position.y = a0[1] + a1[1] * (t - t0) + a2[1] * pow(t - t0, 2) + a3[1] * pow(t - t0, 3);\n  pose.position.z = a0[2] + a1[2] * (t - t0) + a2[2] * pow(t - t0, 2) + a3[2] * pow(t - t0, 3);\n  pose.orientation.x = qres.x();\n  pose.orientation.y = qres.y();\n  pose.orientation.z = qres.z();\n  pose.orientation.w = qres.w();\n\n  return pose;\n}\n\n/**\n * \\copybrief pose_t poly3c(const pose_t pose_i, const pose_t pose_f, const std::vector<double> velocity0, const\n * std::vector<double> velocityf, const double t0, const double tf, const double t) const\n */\npose_t TrajectoryPlanner::poly3c(const pose_t pose_i, const pose_t pose_f, const std::vector<double> velocity0,\n                                 const std::vector<double> velocityf, const double t0, const double tf,\n                                 const double t) const\n{\n  std::vector<double> a0 = { pose_i.position.x, pose_i.position.y, pose_i.position.z };\n  std::vector<double> a1 = { velocity0[0], velocity0[1], velocity0[2] };\n  std::vector<double> a2 = { (3 / pow(tf - t0, 2)) * (pose_f.position.x - pose_i.position.x) -\n                                 (2 / (tf - t0)) * velocity0[0] - (1 / (tf - t0)) * velocityf[0],\n                             (3 / pow(tf - t0, 2)) * (pose_f.position.y - pose_i.position.y) -\n                                 (2 / (tf - t0)) * velocity0[1] - (1 / (tf - t0)) * velocityf[1],\n                             (3 / pow(tf - t0, 2)) * (pose_f.position.z - pose_i.position.z) -\n                                 (2 / (tf - t0)) * velocity0[2] - (1 / (tf - t0)) * velocityf[2] };\n  std::vector<double> a3 = { -(2 / pow(tf - t0, 3)) * (pose_f.position.x - pose_i.position.x) +\n                                 (1 / pow(tf - t0, 2)) * (velocityf[0] + velocity0[0]),\n                             -(2 / pow(tf - t0, 3)) * (pose_f.position.y - pose_i.position.y) +\n                                 (1 / pow(tf - t0, 2)) * (velocityf[1] + velocity0[1]),\n                             -(2 / pow(tf - t0, 3)) * (pose_f.position.z - pose_i.position.z) +\n                                 (1 / pow(tf - t0, 2)) * (velocityf[2] + velocity0[2]) };\n\n  // Apply slerp\n  Eigen::Quaterniond qres;\n  Eigen::Quaterniond q0(pose_i.orientation.w, pose_i.orientation.x, pose_i.orientation.y, pose_i.orientation.z);\n  Eigen::Quaterniond qf(pose_f.orientation.w, pose_f.orientation.x, pose_f.orientation.y, pose_f.orientation.z);\n  qres = q0.slerp((t - t0) / (tf - t0), qf);\n\n  pose_t pose;\n  pose.position.x = a0[0] + a1[0] * (t - t0) + a2[0] * pow(t - t0, 2) + a3[0] * pow(t - t0, 3);\n  pose.position.y = a0[1] + a1[1] * (t - t0) + a2[1] * pow(t - t0, 2) + a3[1] * pow(t - t0, 3);\n  pose.position.z = a0[2] + a1[2] * (t - t0) + a2[2] * pow(t - t0, 2) + a3[2] * pow(t - t0, 3);\n  pose.orientation.x = qres.x();\n  pose.orientation.y = qres.y();\n  pose.orientation.z = qres.z();\n  pose.orientation.w = qres.w();\n\n  return pose;\n}\n\n/**\n * \\copybrief pose_t poly3cVias(const poses_t poses, const std::vector<double> times, const double t) const\n */\npose_t TrajectoryPlanner::poly3cVias(const poses_t poses, const std::vector<double> times, const double t) const\n{\n  if (poses.size() != times.size())\n  {\n    throw std::runtime_error(\"The poses vector should be the same size as times vector.\");\n  }\n\n  std::vector<double> velocity0;\n  std::vector<double> velocityf;\n  velocity0.resize(3, 0);\n  velocityf.resize(3, 0);\n\n  pose_t pose;\n  for (size_t i = 1; i < times.size(); i++)\n  {\n    if (t >= times[i - 1] && t <= times[i])\n    {\n      if (i == 1)\n      {\n        // velocity0 is already {0, 0, 0}\n        velocityf[0] = viaVelocity(poses[i - 1].position.x, poses[i].position.x, poses[i + 1].position.x, times[i - 1],\n                                   times[i], times[i + 1]);\n        velocityf[1] = viaVelocity(poses[i - 1].position.y, poses[i].position.y, poses[i + 1].position.y, times[i - 1],\n                                   times[i], times[i + 1]);\n        velocityf[2] = viaVelocity(poses[i - 1].position.z, poses[i].position.z, poses[i + 1].position.z, times[i - 1],\n                                   times[i], times[i + 1]);\n      }\n      else if (i == times.size() - 1)\n      {\n        velocity0[0] = viaVelocity(poses[i - 1].position.x, poses[i].position.x, poses[i + 1].position.x, times[i - 1],\n                                   times[i], times[i + 1]);\n        velocity0[1] = viaVelocity(poses[i - 1].position.y, poses[i].position.y, poses[i + 1].position.y, times[i - 1],\n                                   times[i], times[i + 1]);\n        velocity0[2] = viaVelocity(poses[i - 1].position.z, poses[i].position.z, poses[i + 1].position.z, times[i - 1],\n                                   times[i], times[i + 1]);\n        // velocityf is already {0, 0, 0}\n      }\n      else\n      {\n        velocity0[0] = viaVelocity(poses[i - 2].position.x, poses[i - 1].position.x, poses[i].position.x, times[i - 1],\n                                   times[i], times[i + 1]);\n        velocity0[1] = viaVelocity(poses[i - 2].position.y, poses[i - 1].position.y, poses[i].position.y, times[i - 1],\n                                   times[i], times[i + 1]);\n        velocity0[2] = viaVelocity(poses[i - 2].position.z, poses[i - 1].position.z, poses[i].position.z, times[i - 1],\n                                   times[i], times[i + 1]);\n\n        velocityf[0] = viaVelocity(poses[i - 1].position.x, poses[i].position.x, poses[i + 1].position.x, times[i - 1],\n                                   times[i], times[i + 1]);\n        velocityf[1] = viaVelocity(poses[i - 1].position.y, poses[i].position.y, poses[i + 1].position.y, times[i - 1],\n                                   times[i], times[i + 1]);\n        velocityf[2] = viaVelocity(poses[i - 1].position.z, poses[i].position.z, poses[i + 1].position.z, times[i - 1],\n                                   times[i], times[i + 1]);\n      }\n\n      pose = poly3c(poses[i - 1], poses[i], velocity0, velocityf, times[i - 1], times[i], t);\n      break;\n    }\n  }\n\n  return pose;\n}\n\n/**\n * \\copybrief pose_t lspb(const pose_t pose_i, const pose_t pose_f, const double accel, const double t0, const double\n * tf, const double t) const\n */\npose_t TrajectoryPlanner::lspb(const pose_t pose_i, const pose_t pose_f, const double accel, const double t0,\n                               const double tf, const double t) const\n{\n  // It is assumed that accel param is always positive\n\n  if (accel < (4 * abs(pose_f.position.x - pose_i.position.x)) / pow(tf - t0, 2) ||\n      accel < (4 * abs(pose_f.position.y - pose_i.position.y)) / pow(tf - t0, 2) ||\n      accel < (4 * abs(pose_f.position.z - pose_i.position.z)) / pow(tf - t0, 2))\n  {\n    throw std::runtime_error(\"Invalid acceleration! The value needs to be larger.\");\n  }\n\n  // Change accel sign depending on growth direction of position (eg. x0 > xf => accel0 < 0)\n  std::vector<double> accel_vec;\n  accel_vec.resize(3, 0);\n  accel_vec[0] = (pose_i.position.x > pose_f.position.x) ? -accel : accel;\n  accel_vec[1] = (pose_i.position.y > pose_f.position.y) ? -accel : accel;\n  accel_vec[2] = (pose_i.position.z > pose_f.position.z) ? -accel : accel;\n\n  pose_t pose;\n  std::vector<double> velocity, acceleration;\n  velocity.resize(3, 0);\n  acceleration.resize(3, 0);\n  std::vector<double> delta_tb;\n  delta_tb.resize(3, 0);\n  delta_tb[0] =\n      (tf - t0) / 2 - sqrt(pow(tf - t0, 2) / 4 - abs(pose_f.position.x - pose_i.position.x) / abs(accel_vec[0]));\n  delta_tb[1] =\n      (tf - t0) / 2 - sqrt(pow(tf - t0, 2) / 4 - abs(pose_f.position.y - pose_i.position.y) / abs(accel_vec[1]));\n  delta_tb[2] =\n      (tf - t0) / 2 - sqrt(pow(tf - t0, 2) / 4 - abs(pose_f.position.z - pose_i.position.z) / abs(accel_vec[2]));\n  std::vector<double> tb;\n  tb.resize(3, 0);\n  tb[0] = t0 + delta_tb[0];\n  tb[1] = t0 + delta_tb[1];\n  tb[2] = t0 + delta_tb[2];\n  std::vector<double> velocity_b;\n  velocity_b.resize(3, 0);\n  velocity_b[0] = accel_vec[0] * delta_tb[0];\n  velocity_b[1] = accel_vec[1] * delta_tb[1];\n  velocity_b[2] = accel_vec[2] * delta_tb[2];\n  std::vector<double> poseb;\n  poseb.resize(3, 0);\n  poseb[0] = pose_i.position.x + 0.5 * accel_vec[0] * pow(delta_tb[0], 2);\n  poseb[1] = pose_i.position.y + 0.5 * accel_vec[1] * pow(delta_tb[1], 2);\n  poseb[2] = pose_i.position.z + 0.5 * accel_vec[2] * pow(delta_tb[2], 2);\n  std::vector<double> posebf;\n  posebf.resize(3, 0);\n  posebf[0] = poseb[0] + velocity_b[0] * ((tf - t0) - 2 * delta_tb[0]);\n  posebf[1] = poseb[1] + velocity_b[1] * ((tf - t0) - 2 * delta_tb[1]);\n  posebf[2] = poseb[2] + velocity_b[2] * ((tf - t0) - 2 * delta_tb[2]);\n\n  // Apply slerp\n  Eigen::Quaterniond qres;\n  Eigen::Quaterniond q0(pose_i.orientation.w, pose_i.orientation.x, pose_i.orientation.y, pose_i.orientation.z);\n  Eigen::Quaterniond qf(pose_f.orientation.w, pose_f.orientation.x, pose_f.orientation.y, pose_f.orientation.z);\n  qres = q0.slerp((t - t0) / (tf - t0), qf);\n  pose.orientation.x = qres.x();\n  pose.orientation.y = qres.y();\n  pose.orientation.z = qres.z();\n  pose.orientation.w = qres.w();\n\n  for (size_t i = 0; i < 3; i++)\n  {\n    if (t >= t0 && t <= tb[i])\n    {\n      acceleration[i] = accel_vec[i];\n      velocity[i] = accel_vec[i] * (t - t0);\n      switch (i)\n      {\n        case 1:\n          pose.position.y = pose_i.position.y + 0.5 * acceleration[i] * pow(t - t0, 2);\n          break;\n        case 2:\n          pose.position.z = pose_i.position.z + 0.5 * acceleration[i] * pow(t - t0, 2);\n          break;\n        default:\n          pose.position.x = pose_i.position.x + 0.5 * acceleration[i] * pow(t - t0, 2);\n          break;\n      }\n    }\n    else if (t >= (tf - delta_tb[i]) && t <= tf + 0.0001)\n    {\n      acceleration[i] = -accel_vec[i];\n      velocity[i] = velocity_b[i] + acceleration[i] * (t - (tf - delta_tb[i]));\n      switch (i)\n      {\n        case 1:\n          pose.position.y = posebf[i] + velocity_b[i] * (t - (tf - delta_tb[i])) +\n                            0.5 * acceleration[i] * pow(t - (tf - delta_tb[i]), 2);\n          break;\n        case 2:\n          pose.position.z = posebf[i] + velocity_b[i] * (t - (tf - delta_tb[i])) +\n                            0.5 * acceleration[i] * pow(t - (tf - delta_tb[i]), 2);\n          break;\n        default:\n          pose.position.x = posebf[i] + velocity_b[i] * (t - (tf - delta_tb[i])) +\n                            0.5 * acceleration[i] * pow(t - (tf - delta_tb[i]), 2);\n          break;\n      }\n    }\n    else\n    {\n      acceleration[i] = 0;\n      velocity[i] = velocity_b[i];\n      switch (i)\n      {\n        case 1:\n          pose.position.y = poseb[i] + velocity_b[i] * (t - tb[i]);\n          break;\n        case 2:\n          pose.position.z = poseb[i] + velocity_b[i] * (t - tb[i]);\n          break;\n        default:\n          pose.position.x = poseb[i] + velocity_b[i] * (t - tb[i]);\n          break;\n      }\n    }\n  }\n\n  return pose;\n}\n\n/**\n * \\copybrief TrajectoryPlanner::getFullPathLength(const paths_t path)\n */\ndouble TrajectoryPlanner::getFullPathLength(const paths_t paths)\n{\n  double total_length = 0;\n  for (size_t i = 0; i < paths.size(); i++)\n    total_length += paths[i].length();\n  \n  return total_length;\n}\n\n/**\n * \\copybrief TrajectoryPlanner::getFullPathLength(const toolpaths_t path)\n */\ndouble TrajectoryPlanner::getFullPathLength(const toolpaths_t toolpaths)\n{\n  double total_length = 0;\n  for (size_t i = 0; i < toolpaths.size(); i++)\n    total_length += toolpaths[i].length();\n  \n  return total_length;\n}\n\n/**\n * \\copybrief TrajectoryPlanner::getFullPathSize(const paths_t path)\n */\ndouble TrajectoryPlanner::getFullPathSize(const paths_t paths)\n{\n  double total_size = 0;\n  for (size_t i = 0; i < paths.size(); i++)\n    total_size += paths[i].poses().size();\n  \n  return total_size;\n}\n\n/**\n * \\copybrief TrajectoryPlanner::getFullPathSize(const toolpaths_t toolpaths)\n */\ndouble TrajectoryPlanner::getFullPathSize(const toolpaths_t toolpaths)\n{\n  double total_size = 0;\n  for (size_t i = 0; i < toolpaths.size(); i++)\n    total_size += toolpaths[i].poses().size();\n  \n  return total_size;\n}\n\n}  // namespace smalldrop_toolpath\n\n}  // namespace smalldrop", "meta": {"hexsha": "2fcaec27281428ea8b4c2e874083fff7d0b273d3", "size": 21786, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "smalldrop/smalldrop_toolpath/src/smalldrop_toolpath/trajectory_planner.cpp", "max_stars_repo_name": "blackchacal/Master-Thesis----Software", "max_stars_repo_head_hexsha": "9a9858ede3086eee99d1fc969e32b4fb13278f00", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-08-16T14:37:09.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-16T14:37:09.000Z", "max_issues_repo_path": "smalldrop/smalldrop_toolpath/src/smalldrop_toolpath/trajectory_planner.cpp", "max_issues_repo_name": "blackchacal/Master-Thesis----Software", "max_issues_repo_head_hexsha": "9a9858ede3086eee99d1fc969e32b4fb13278f00", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-06-26T09:14:45.000Z", "max_issues_repo_issues_event_max_datetime": "2020-07-18T08:46:50.000Z", "max_forks_repo_path": "smalldrop/smalldrop_toolpath/src/smalldrop_toolpath/trajectory_planner.cpp", "max_forks_repo_name": "blackchacal/Master-Thesis----Software", "max_forks_repo_head_hexsha": "9a9858ede3086eee99d1fc969e32b4fb13278f00", "max_forks_repo_licenses": ["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.4314381271, "max_line_length": 149, "alphanum_fraction": 0.5815202424, "num_tokens": 6274, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6076631698328917, "lm_q2_score": 0.5, "lm_q1q2_score": 0.30383158491644585}}
{"text": "//\n// this is for testing the timing of the given individual integrals\n//\n\n#include \"libgen.h\"\n#include <boost/algorithm/string.hpp>   // string handling\n#include <boost/lexical_cast.hpp>\n#include <boost/timer.hpp>\nusing namespace boost;\n\nextern void hgp_os_eri_sp_sp_sp_sp(const UInt& inp2, const UInt& jnp2, const Double& pMax, \n\t\tconst Double& omega, const Double* icoe, const Double* iexp, const Double* ifac, \n\t\tconst Double* P, const Double* A, const Double* B, const Double* jcoe, const Double* jexp, \n\t\tconst Double* jfac, const Double* Q, const Double* C, const Double* D, Double* abcd);\n\nextern void hgp_os_eri_sp_sp_sp_sp_d1(const UInt& inp2, const UInt& jnp2, const Double& pMax, \n\t\tconst Double& omega, const Double* icoe, const Double* iexp, const Double* iexpdiff, \n\t\tconst Double* ifac, const Double* P, const Double* A, const Double* B, const Double* jcoe, \n\t\tconst Double* jexp, const Double* jexpdiff, const Double* jfac, const Double* Q, const Double* C, \n\t\tconst Double* D, Double* abcd);\n\nInt main(int argc, char* argv[])\n{\n\t/////////////////////////////////////////////////////////////////////////////\n\t// setting the shell data\n\t// all of shell data are in default to be composite shell\n\t// which contains two sub-shells\n\t/////////////////////////////////////////////////////////////////////////////\n\t\n\t// shell 1\n\tInt inp = 2;\n\tvector<Double> iexp(inp);\n\tvector<Double> icoe(2*inp);\n\tiexp[0] = 0.1812885;\n\tiexp[1] = 0.0442493;\n\ticoe[0] = 0.1193324;\n\ticoe[1] = 0.1608542;\n\ticoe[2] = 0.8434564;\n\ticoe[3] = 0.0689991;\n\tDouble A[3];\n\tA[0]    = 1.0;\n\tA[1]    = 0.0;\n\tA[2]    = 0.0;\n\n\t// shell 2\n\tInt jnp = 2;\n\tvector<Double> jexp(jnp);\n\tvector<Double> jcoe(2*jnp);\n\tjexp[0] = 0.1439130;\n\tjexp[1] = 0.0914760;\n\tjcoe[0] = 6.139703E-02;\n\tjcoe[1] = 3.061130E-01;\n\tjcoe[2] = 1.154890;\n\tjcoe[3] = 0.1891265;\n\tDouble B[3];\n\tB[0]    = 0.0;\n\tB[1]    = 1.0;\n\tB[2]    = 0.0;\n\n\t// shell 3\n\tInt knp = 2;\n\tvector<Double> kexp(knp);\n\tvector<Double> kcoe(2*knp);\n\tkexp[0] = 0.03628970;\n\tkexp[1] = 0.14786010;\n\tkcoe[0] = 0.09996723;\n\tkcoe[1] = 0.39951283;\n\tkcoe[2] = 0.70011547;\n\tkcoe[3] = 0.15591627;\n\tDouble C[3];\n\tC[0]    = 0.0;\n\tC[1]    = 0.0;\n\tC[2]    = 1.0;\n\n\t// shell 4\n\tInt lnp = 2;\n\tvector<Double> lexp(lnp);\n\tvector<Double> lcoe(2*lnp);\n\tlexp[0] = 0.01982050;\n\tlexp[1] = 0.16906180;\n\tlcoe[0] = 0.06723;\n\tlcoe[1] = 0.51283;\n\tlcoe[2] = 0.30011547;\n\tlcoe[3] = 0.5591627;\n\tDouble D[3];\n\tD[0]    = 0.0;\n\tD[1]    = 1.0;\n\tD[2]    = 1.0;\n\n\t/////////////////////////////////////////////////////////////////////////////\n\t// setting the shell data\n\t// all of shell data are in default to be composite shell\n\t// which contains two sub-shells\n\t/////////////////////////////////////////////////////////////////////////////\n\t//\n\t// form the data for hgp calculation\n\t// firstly it's the bra side\n\t//\n\tDouble AB2 = (A[0]-B[0])*(A[0]-B[0])+(A[1]-B[1])*(A[1]-B[1])+(A[2]-B[2])*(A[2]-B[2]);\n\tInt inp2 = inp*jnp;\n\tvector<Double> iexp2(inp2,ZERO);\n\tvector<Double> fbra(inp2,ZERO);\n\tvector<Double> P(3*inp2,ZERO);\n\tvector<Double> iexpdiff(inp2,ZERO);\n\tInt count = 0;\n\tfor(Int jp=0; jp<jnp; jp++) {\n\t\tfor(Int ip=0; ip<inp; ip++) {\n\n\t\t\t// prefactors etc.\n\t\t\tDouble ia   = iexp[ip];\n\t\t\tDouble ja   = jexp[jp];\n\t\t\tDouble alpla= ia+ja; \n\t\t\tDouble diff = ia-ja; \n\t\t\tDouble ab   = -ia*ja/alpla;\n\t\t\tDouble pref = exp(ab*AB2)*pow(PI/alpla,1.5E0);\n\t\t\tiexp2[count]= ONE/alpla;\n\t\t\tfbra[count] = pref;\n\t\t\tiexpdiff[count]= diff;\n\n\t\t\t// form P point according to the \n\t\t\t// Gaussian pritimive product theorem\n\t\t\tDouble adab = ia/alpla; \n\t\t\tDouble bdab = ja/alpla; \n\t\t\tDouble Px   = A[0]*adab + B[0]*bdab;\n\t\t\tDouble Py   = A[1]*adab + B[1]*bdab;\n\t\t\tDouble Pz   = A[2]*adab + B[2]*bdab;\n\t\t\tP[3*count+0]= Px;\n\t\t\tP[3*count+1]= Py;\n\t\t\tP[3*count+2]= Pz;\n\t\t\tcount++;\n\t\t}\n\t}\n\n\t// now it's ket side data\n\tDouble CD2 = (C[0]-D[0])*(C[0]-D[0])+(C[1]-D[1])*(C[1]-D[1])+(C[2]-D[2])*(C[2]-D[2]);\n\tInt jnp2 = knp*lnp;\n\tvector<Double> jexp2(jnp2,ZERO);\n\tvector<Double> jexpdiff(jnp2,ZERO);\n\tvector<Double> fket(jnp2,ZERO);\n\tvector<Double> Q(3*jnp2,ZERO);\n\tcount = 0;\n\tfor(Int lp=0; lp<lnp; lp++) {\n\t\tfor(Int kp=0; kp<knp; kp++) {\n\n\t\t\t// prefactors etc.\n\t\t\tDouble ia   = kexp[kp];\n\t\t\tDouble ja   = lexp[lp];\n\t\t\tDouble alpla= ia+ja; \n\t\t\tDouble diff = ia-ja; \n\t\t\tDouble ab   = -ia*ja/alpla;\n\t\t\tDouble pref = exp(ab*CD2)*pow(PI/alpla,1.5E0);\n\t\t\tjexp2[count]= ONE/alpla;\n\t\t\tfket[count] = pref;\n\t\t\tjexpdiff[count]= diff;\n\n\t\t\t// form P point according to the \n\t\t\t// Gaussian pritimive product theorem\n\t\t\tDouble adab = ia/alpla; \n\t\t\tDouble bdab = ja/alpla; \n\t\t\tDouble Qx   = C[0]*adab + D[0]*bdab;\n\t\t\tDouble Qy   = C[1]*adab + D[1]*bdab;\n\t\t\tDouble Qz   = C[2]*adab + D[2]*bdab;\n\t\t\tQ[3*count+0]= Qx;\n\t\t\tQ[3*count+1]= Qy;\n\t\t\tQ[3*count+2]= Qz;\n\t\t\tcount++;\n\t\t}\n\t}\n\n\t/////////////////////////////////////////////////////////////////////////////\n\t// now it's the formal timing compare\n\t/////////////////////////////////////////////////////////////////////////////\n\t\n\t// set the angular momentum of the results\n\t// here the user need to do that\n\tInt lmin1 = 0;\n\tInt lmax1 = 1;\n\tInt lmin2 = 0;\n\tInt lmax2 = 1;\n\tInt lmin3 = 0;\n\tInt lmax3 = 1;\n\tInt lmin4 = 0;\n\tInt lmax4 = 1;\n\tInt nBas1 = ((lmax1+1)*(lmax1+2)*(lmax1+3)-lmin1*(lmin1+1)*(lmin1+2))/6;\n\tInt nBas2 = ((lmax2+1)*(lmax2+2)*(lmax2+3)-lmin2*(lmin2+1)*(lmin2+2))/6;\n\tInt nBas3 = ((lmax3+1)*(lmax3+2)*(lmax3+3)-lmin3*(lmin3+1)*(lmin3+2))/6;\n\tInt nBas4 = ((lmax4+1)*(lmax4+2)*(lmax4+3)-lmin4*(lmin4+1)*(lmin4+2))/6;\n\n\t// make the coefficients pair\n\t// bra side\n\tInt nL1 = lmax1-lmin1+1;\n\tInt nL2 = lmax2-lmin2+1;\n\tcount = 0;\n\tvector<Double> braCoePair(inp*jnp*nL1*nL2,ZERO);\n\tfor(Int j=0; j<nL2; j++) {\n\t\tfor(Int i=0; i<nL1; i++) {\n\t\t\tfor(Int jp=0; jp<jnp; jp++) {\n\t\t\t\tfor(Int ip=0; ip<inp; ip++) {\n\t\t\t\t\tDouble ic = icoe[ip+i*inp];\n\t\t\t\t\tDouble jc = jcoe[jp+j*jnp];\n\t\t\t\t\tbraCoePair[count] = ic*jc;\n\t\t\t\t\tcount++;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// ket side\n\tnL1 = lmax3-lmin3+1;\n\tnL2 = lmax4-lmin4+1;\n\tcount = 0;\n\tvector<Double> ketCoePair(knp*lnp*nL1*nL2,ZERO);\n\tfor(Int j=0; j<nL2; j++) {\n\t\tfor(Int i=0; i<nL1; i++) {\n\t\t\tfor(Int jp=0; jp<lnp; jp++) {\n\t\t\t\tfor(Int ip=0; ip<knp; ip++) {\n\t\t\t\t\tDouble ic = kcoe[ip+i*inp];\n\t\t\t\t\tDouble jc = lcoe[jp+j*jnp];\n\t\t\t\t\tketCoePair[count] = ic*jc;\n\t\t\t\t\tcount++;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// now set up the result vectors\n\t// N is the total number of running times\n\tInt N = 1000000;\n\tDouble pMax   = 1.0E0;\n\tDouble omega  = 0.0E0;\n\tvector<Double> result1(nBas1*nBas2*nBas3*nBas4);\n\ttimer t1;\n\tfor(Int i=0; i<N; i++) {\n\t\thgp_os_eri_sp_sp_sp_sp(inp2,jnp2,pMax,omega,\n\t\t\t\t&braCoePair.front(),&iexp2.front(),&fbra.front(),&P.front(),A,B, \n\t\t\t\t&ketCoePair.front(),&jexp2.front(),&fket.front(),&Q.front(),C,D, \n\t\t\t\t&result1.front());\n\t}\n\tprintf(\"hgp sp_sp_sp_sp energy time consuming: %-14.7f\\n\", t1.elapsed());\n\n\t// this is another integral file\n\tvector<Double> result2(nBas1*nBas2*nBas3*nBas4*9); // dimension is responsible by the user\n\ttimer t2;\n\tfor(Int i=0; i<N; i++) {\n\t\thgp_os_eri_sp_sp_sp_sp_d1(inp2,jnp2,pMax,omega,\n\t\t\t\t&braCoePair.front(),&iexp2.front(),&iexpdiff.front(),&fbra.front(),&P.front(),A,B, \n\t\t\t\t&ketCoePair.front(),&jexp2.front(),&jexpdiff.front(),&fket.front(),&Q.front(),C,D, \n\t\t\t\t&result2.front());\n\t}\n\tprintf(\"hgp sp_sp_sp_sp gradient time consuming: %-14.7f\\n\", t2.elapsed());\n\n\treturn 0;\n\n}\n", "meta": {"hexsha": "bbf6f9c2a224fb88277b7eedb8c2f6ccfcb942d9", "size": 7228, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "util/timingtest.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": "util/timingtest.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": "util/timingtest.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": 28.3450980392, "max_line_length": 100, "alphanum_fraction": 0.5697288323, "num_tokens": 2769, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6757646010190476, "lm_q2_score": 0.44939263446475963, "lm_q1q2_score": 0.30368363432997697}}
{"text": "﻿//*****************************************************************************\r\n// Class: CLaricobiusNigrinus\r\n//          \r\n//\r\n// Description: the CLaricobiusNigrinus represents a group of LNF insect. scale by m_ScaleFactor\r\n//*****************************************************************************\r\n// 15/10/2019   Rémi Saint-Amant    Creation\r\n//*****************************************************************************\r\n\r\n#include \"LaricobiusNigrinusEquations.h\"\r\n#include \"LaricobiusNigrinus.h\"\r\n//#include <boost/math/distributions/weibull.hpp>\r\n#include <boost/math/distributions/logistic.hpp>\r\n\r\nusing namespace std;\r\nusing namespace WBSF::HOURLY_DATA;\r\nusing namespace WBSF::LNF;\r\n\r\n\r\nnamespace WBSF\r\n{\r\n\r\n\t//*********************************************************************************\r\n\t//CLaricobiusNigrinus class\r\n\r\n\r\n\t//*****************************************************************************\r\n\t// Object creator\r\n\t//\r\n\t// Input: See CIndividual creator\r\n\t//\r\n\t// Note: m_RDR (relative Development Rate)  member is init with random values.\r\n\t//*****************************************************************************\r\n\tCLaricobiusNigrinus::CLaricobiusNigrinus(CHost* pHost, CTRef creationDate, double age, TSex sex, bool bFertil, size_t generation, double scaleFactor) :\r\n\t\tCIndividual(pHost, creationDate, age, sex, bFertil, generation, scaleFactor)\r\n\t{\r\n\t\t//reset creation date\r\n\t\tint year = creationDate.GetYear();\r\n\t\tm_creationDate = GetCreationDate(year);\r\n\t\tm_adult_emergence = GetAdultEmergence(year);\r\n\r\n\t\tm_adult_longevity = Equations().GetAdultLongevity(m_sex);\r\n\t\tm_F = (m_sex == FEMALE) ? Equations().GetFecondity(m_adult_longevity) : 0;\r\n\t}\r\n\r\n\tCTRef CLaricobiusNigrinus::GetCreationDate(int year)const\r\n\t{\r\n\t\tCTRef creationDate;\r\n\t\tdouble creationCDD = Equations().GetCreationCDD();\r\n\r\n\t\tconst CWeatherStation& weather_station = GetStand()->GetModel()->m_weather;\r\n\t\tCTRef begin = CTRef(year, JANUARY, DAY_01);\r\n\t\tCTRef end = CTRef(year, JUNE, DAY_30);\r\n\r\n\t\tdouble CDD = 0;\r\n\t\tfor (CTRef TRef = begin; TRef <= end && !creationDate.IsInit(); TRef++)\r\n\t\t{\r\n\t\t\tconst CWeatherDay& wDay = weather_station.GetDay(TRef);\r\n\t\t\tdouble DD = GetStand()->m_DD.GetDD(wDay);\r\n\t\t\tCDD += DD;\r\n\t\t\tif (CDD >= creationCDD)\r\n\t\t\t{\r\n\t\t\t\tcreationDate = wDay.GetTRef();\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tASSERT(creationDate.IsInit());\r\n\r\n\t\treturn creationDate;\r\n\t}\r\n\t\r\n\tCTRef CLaricobiusNigrinus::GetAdultEmergence(int year)const\r\n\t{\r\n\t\tconst CWeatherStation& weather_station = GetStand()->GetModel()->m_weather;\r\n\t\tCTPeriod p = weather_station.GetEntireTPeriod(CTM::DAILY);\r\n\r\n\t\tCTRef adult_emergence;\r\n\t\tdouble adult_emerging_CDD = Equations().GetAdultEmergingCDD();\r\n\r\n\t\tCTRef begin = GetStand()->m_diapause_end;\r\n\t\tCTRef end = p.End();\r\n\t\tif(weather_station[year].HaveNext())\r\n\t\t\tend = min(p.End(), CTRef(begin.GetYear() + 1, JUNE, DAY_30));\r\n\r\n\t\tdouble CDD = 0;\r\n\t\tfor (CTRef TRef = begin; TRef <= end && !adult_emergence.IsInit(); TRef++)\r\n\t\t{\r\n\t\t\tconst CWeatherDay& wday = weather_station.GetDay(TRef);\r\n\t\t\tdouble T = wday[H_TNTX][MEAN];\r\n\t\t\tT = CLaricobiusNigrinus::AdjustTLab(wday.GetWeatherStation()->m_name, NOT_INIT, wday.GetTRef(), T);\r\n\r\n\t\t\tdouble DD = max(0.0, T - Equations().m_EAS[Τᴴ]);\r\n\t\t\tCDD += DD;\r\n\t\t\tif (CDD >= adult_emerging_CDD)\r\n\t\t\t{\r\n\t\t\t\tadult_emergence = wday.GetTRef();\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\treturn adult_emergence;\r\n\t}\r\n\r\n\tCLaricobiusNigrinus& CLaricobiusNigrinus::operator=(const CLaricobiusNigrinus& in)\r\n\t{\r\n\t\tif (&in != this)\r\n\t\t{\r\n\t\t\tCIndividual::operator=(in);\r\n\t\t\t\r\n\t\t\tm_adult_emergence = in.m_adult_emergence;\r\n\t\t\tm_adult_longevity = in.m_adult_longevity;// Equations().GetAdultLongevity(m_sex) / 2;\r\n\t\t\tm_F = in.m_F;\r\n\t\t}\r\n\r\n\t\treturn *this;\r\n\t}\r\n\t\r\n\t//destructor\r\n\tCLaricobiusNigrinus::~CLaricobiusNigrinus(void)\r\n\t{}\r\n\r\n\r\n\tdouble CLaricobiusNigrinus::AdjustTLab(const string& name, size_t s, CTRef TRef, double T)\r\n\t{\r\n\t\tif (name == \"BlacksburgLab\")\r\n\t\t{\r\n\t\t\tif (s == -1)\r\n\t\t\t{\r\n\t\t\t\tif (TRef.GetJDay() < CTRef(0, MARCH, DAY_25).GetJDay())\r\n\t\t\t\t\ts = EGG;\r\n\t\t\t\telse if (TRef.GetJDay() < CTRef(0, APRIL, DAY_15).GetJDay())\r\n\t\t\t\t\ts = LARVAE;\r\n\t\t\t\telse if (TRef.GetJDay() < CTRef(0, MAY, DAY_25).GetJDay())\r\n\t\t\t\t\ts = PUPAE;\r\n\t\t\t\telse\r\n\t\t\t\t\ts = AESTIVAL_DIAPAUSE_ADULT;\r\n\t\t\t}\r\n\r\n\t\t\t//if we are in Blacksburg lab situation, take temperature depend of year\r\n\t\t\t//lab rearing: change temperature Lamb(2005) thesis\r\n\t\t\tif (s == LARVAE)\r\n\t\t\t\tT = 13;\r\n\t\t\telse if (s == PREPUPAE || s == PUPAE)\r\n\t\t\t\tT = 15;\r\n\t\t\telse if (s == AESTIVAL_DIAPAUSE_ADULT && TRef.GetYear() == 2003)\r\n\t\t\t\tT = 15;\r\n\t\t\telse if (s == AESTIVAL_DIAPAUSE_ADULT && TRef.GetYear() == 2004)\r\n\t\t\t{\r\n\t\t\t\tif (TRef < CTRef(2004, SEPTEMBER, DAY_27))\r\n\t\t\t\t\tT = 19;\r\n\t\t\t\telse\r\n\t\t\t\t\tT = 13;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\r\n\t\treturn T;\r\n\t}\r\n\r\n\tdouble CLaricobiusNigrinus::AdjustDLLab(const string& name, size_t s, CTRef TRef, double day_length)\r\n\t{\r\n\t\t/*if (name == \"VictoriaLab\")\r\n\t\t{\r\n\t\t\tday_length = 12;\r\n\t\t}\r\n\t\telse */\r\n\t\tif (name == \"BlacksburgLab\")\r\n\t\t{\r\n\t\t\t//if we are in Blacksburg lab situation, take 12 hours\r\n\t\t\tif (TRef.GetYear() == 2003)\r\n\t\t\t\tday_length = 14;\r\n\t\t\telse if (TRef < CTRef(2004, SEPTEMBER, DAY_27))\r\n\t\t\t\tday_length = 16;\r\n\t\t\telse\r\n\t\t\t\tday_length = 10;\r\n\t\t}\r\n\r\n\t\treturn day_length;\r\n\t}\r\n\r\n\r\n\tvoid CLaricobiusNigrinus::OnNewDay(const CWeatherDay& weather)\r\n\t{\r\n\t\tCIndividual::OnNewDay(weather);\r\n\r\n\t\tif (weather.GetTRef() == m_creationDate)\r\n\t\t{\r\n\t\t\tm_age = EGG;\r\n\t\t}\r\n\t}\r\n\r\n\t//*****************************************************************************\r\n\t// Develops all stages for one time step\r\n\t// Input:\tweather: weather of the hour\r\n\t//\t\t\ttimeStep: timeStep [h]\r\n\t//*****************************************************************************\r\n\tvoid CLaricobiusNigrinus::Live(const CHourlyData& weather, size_t timeStep)\r\n\t{\r\n\t\tassert(IsAlive());\r\n\t\tassert(m_status == HEALTHY);\r\n\r\n\t\tCLNFHost* pHost = GetHost();\r\n\t\tCLNFStand* pStand = GetStand();\r\n\r\n\t\tdouble nb_steps = (24.0 / timeStep);\r\n\t\tsize_t h = weather.GetTRef().GetHour();\r\n\t\tsize_t s = GetStage();\r\n\r\n\t\tdouble T = weather[H_TAIR];\r\n\t\tT = AdjustTLab(weather.GetWeatherStation()->m_name, s, weather.GetTRef(), T);\r\n\r\n\t\tdouble day_length = weather.GetLocation().GetDayLength(weather.GetTRef()) / 3600.0;//[h]\r\n\t\tday_length = AdjustDLLab(weather.GetWeatherStation()->m_name, s, weather.GetTRef(), day_length);\r\n\t\t\r\n\t\tif (s < AESTIVAL_DIAPAUSE_ADULT)\r\n\t\t{\r\n\t\t\t//Time step development rate\r\n\t\t\tdouble r = Equations().GetRate(s, T) / nb_steps;\r\n\t\t\t\r\n\t\t\tdouble corr_r = (s == EGG || s == LARVAE) ? Equations().m_RDR[s][0] : 1;\r\n\r\n\t\t\t//Relative development rate for this individual\r\n\t\t\t//double rr = (s == EGG || s == LARVAE) ? m_RDR[s] : 1;\r\n\r\n\t\t\t//Time step development rate for this individual\r\n\t\t\tr *= corr_r;\r\n\t\t\tASSERT(r >= 0 && r < 1);\r\n\r\n\t\t\t//Adjust age\r\n\t\t\tm_age += r;\r\n\r\n\t\t\tif (!m_dropToGroundDate.IsInit() && m_age > LARVAE + 0.9)//drop to the soil when 90% competed (guess)\r\n\t\t\t\tm_dropToGroundDate = weather.GetTRef().as(CTM::DAILY);\r\n\t\t}\r\n\t\telse if (s == AESTIVAL_DIAPAUSE_ADULT)\r\n\t\t{\r\n\t\t\tCTRef TRef = weather.GetTRef().as(CTM::DAILY);\r\n\t\t\tif (TRef == m_adult_emergence)\r\n\t\t\t\tm_age = ACTIVE_ADULT;\r\n\t\t}\r\n\t\telse//ACTIVE_ADULT\r\n\t\t{\r\n\t\t\tdouble r = (1.0 / m_adult_longevity) / nb_steps;\r\n\t\t\tASSERT(r >= 0 && r < 1);\r\n\r\n\t\t\tm_age += r;\r\n\t\t}\r\n\t}\r\n\r\n\r\n\r\n\r\n\t//*****************************************************************************\r\n\t// Develops all stages, including adults\r\n\t// Input:\tweather: the weather of the day\r\n\t//*****************************************************************************\r\n\tvoid CLaricobiusNigrinus::Live(const CWeatherDay& weather)\r\n\t{\r\n\t\tCIndividual::Live(weather);\r\n\r\n\t\tASSERT(IsCreated(weather.GetTRef()));\r\n\t\t\r\n\t\tif (!IsCreated(weather.GetTRef()))\r\n\t\t\treturn;\r\n\r\n\t\tsize_t nbSteps = GetTimeStep().NbSteps();\r\n\t\tfor (size_t step = 0; step < nbSteps&&m_age < DEAD_ADULT; step++)\r\n\t\t{\r\n\t\t\tsize_t h = step * GetTimeStep();\r\n\t\t\tLive(weather[h], GetTimeStep());\r\n\t\t}\r\n\r\n\t\tif (weather.GetTRef() == m_creationDate || HasChangedStage())\r\n\t\t\tm_reachDate[GetStage()] = weather.GetTRef();\r\n\t}\r\n\r\n\r\n\tvoid CLaricobiusNigrinus::Brood(const CWeatherDay& weather)\r\n\t{\r\n\t\tassert(IsAlive() && m_sex == FEMALE);\r\n\r\n\r\n\t\tif (GetStage() == ACTIVE_ADULT)\r\n\t\t{\r\n\t\t\t//no brood process done\r\n\r\n\t\t\t//brooding\r\n\t\t\t//m_broods = m_F;\r\n\t\t\t//m_totalBroods = m_F;\r\n\t\t\t//m_F = 0;\r\n\t\t}\r\n\t}\r\n\r\n\t// kills by old age and frost\r\n\t// Output:  Individual's state is updated to follow update\r\n\tvoid CLaricobiusNigrinus::Die(const CWeatherDay& weather)\r\n\t{\r\n\t\t//attrition mortality. Killed at the end of time step \r\n\t\tif (GetStage() == DEAD_ADULT)\r\n\t\t{\r\n\t\t\t//Old age\r\n\t\t\tm_status = DEAD;\r\n\t\t\tm_death = OLD_AGE;\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\tsize_t s = GetStage();\r\n\r\n\t\t\t//Preliminary assessment of the cold tolerance of Laricobius nigrinus, a winter - active predator of the hemlock woolly adelgid from western canada\r\n\t\t\t//Leland M.Humble\r\n\t\t\tstatic const double COLD_TOLERENCE_T[NB_STAGES] = { -27.5,-22.1, -99.0,-99.0,-19.0,-19.0 };\r\n\t\t\t//Toland:L. nigrinus was -13.6 oC (± 0.5) with temperatures that ranged from -6 oC to -21 oC.\r\n\t\t\tif (weather[H_TMIN][MEAN] < COLD_TOLERENCE_T[s])\r\n\t\t\t{\r\n\t\t\t\tm_status = DEAD;\r\n\t\t\t\tm_death = FROZEN;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\r\n\t}\r\n\r\n\t//*****************************************************************************\r\n\t// GetStat gather information of this object\r\n\t//\r\n\t// Input: stat: the statistic object\r\n\t// Output: The stat is modified\r\n\t//*****************************************************************************\r\n\tvoid CLaricobiusNigrinus::GetStat(CTRef d, CModelStat& stat)\r\n\t{\r\n\t\tif (IsCreated(d))\r\n\t\t{\r\n\t\t\tsize_t s = GetStage();\r\n\t\t\tASSERT(s <= DEAD_ADULT);\r\n\r\n\t\t\tif (IsAlive() || (s == DEAD_ADULT))\r\n\t\t\t\tstat[S_EGG + s] += m_scaleFactor;\r\n\r\n\r\n\t\t\tif (m_status == DEAD && m_death == FROZEN)\r\n\t\t\t\tstat[S_DEAD_FROST] += m_scaleFactor;\r\n\r\n\t\t\tif (HasChangedStage())\r\n\t\t\t\tstat[S_M_EGG + s] += m_scaleFactor;\r\n\r\n\t\t\t//if (s == ACTIVE_ADULT)\r\n\t\t\t//{\r\n\t\t\t//\tstat[S_ADULT_ABUNDANCE] += m_scaleFactor * m_adult_abundance;\r\n\t\t\t//}\r\n\t\t}\r\n\t}\r\n\r\n\r\n\tvoid CLaricobiusNigrinus::Pack(const CIndividualPtr& pBug)\r\n\t{\r\n\t\tassert(m_sex == pBug->GetSex());\r\n\r\n\t\tCLaricobiusNigrinus* in = (CLaricobiusNigrinus*)(pBug.get());\r\n\t\tCIndividual::Pack(pBug);\r\n\t}\r\n\r\n\tdouble CLaricobiusNigrinus::GetInstar(bool includeLast)const\r\n\t{\r\n\t\treturn (IsAlive() || m_death == OLD_AGE) ? GetStage() : CBioSIMModelBase::VMISS;\r\n\t}\r\n\r\n\t//*********************************************************************************************************************\r\n\r\n\t//*********************************************************************************\r\n\t//CLNFHost\r\n\r\n\tCLNFHost::CLNFHost(CStand* pStand) :\r\n\t\tCHost(pStand)\r\n\t{\r\n\t}\r\n\r\n\r\n\tvoid CLNFHost::Live(const CWeatherDay& weather)\r\n\t{\r\n\t\tCHost::Live(weather);\r\n\t}\r\n\r\n\tvoid CLNFHost::GetStat(CTRef d, CModelStat& stat, size_t generation)\r\n\t{\r\n\t\tCHost::GetStat(d, stat, generation);\r\n\t}\r\n\r\n\t//*************************************************\r\n\t//CLNFStand\r\n\r\n\tvoid CLNFStand::init(int year, const CWeatherYears& weather)\r\n\t{\r\n\t\tm_diapause_end = ComputeDiapauseEnd(weather[year]);\r\n\t}\r\n\r\n\tCTRef CLNFStand::ComputeDiapauseEnd(const CWeatherYear& weather)const\r\n\t{\r\n\t\tCTPeriod p = weather.GetEntireTPeriod(CTM::DAILY);\r\n\r\n\t\tdouble sumDD = 0;\r\n\r\n\t\tfor (size_t ii = (m_equations.m_ADE[ʎ0] - 1); ii <= (m_equations.m_ADE[ʎ1] - 1); ii++)\r\n\t\t{\r\n\t\t\tCTRef TRef = p.Begin() + ii;\r\n\t\t\tconst CWeatherDay& wday = weather.GetDay(TRef);\r\n\t\t\tdouble T = wday[H_TNTX][MEAN];\r\n\r\n\t\t\tT = CLaricobiusNigrinus::AdjustTLab(wday.GetWeatherStation()->m_name, NOT_INIT, wday.GetTRef(), T);\r\n\t\t\tdouble DD = min(0.0, T - m_equations.m_ADE[ʎb]);//DD is negative\r\n\t\t\tsumDD += DD;\r\n\t\t}\r\n\r\n\t\tboost::math::logistic_distribution<double> begin_dist(m_equations.m_ADE[ʎ2], m_equations.m_ADE[ʎ3]);\r\n\t\tint begin = (int)Round((m_equations.m_ADE[ʎ1] - 1) + m_equations.m_ADE[ʎa] * cdf(begin_dist, sumDD), 0);\r\n\r\n\r\n\t\treturn p.Begin() + begin;\r\n\t}\r\n\r\n\r\n\r\n\tvoid CLNFStand::GetStat(CTRef d, CModelStat& stat, size_t generation)\r\n\t{\r\n\t\tCStand::GetStat(d, stat, generation);\r\n\r\n\t\tconst CWeatherStation& weather_station = GetModel()->m_weather;\r\n\t\tconst CWeatherDay& wday = weather_station.GetDay(d);\r\n\t\t\r\n\t\t//use year of diapause to compute correctly the adult emergence cdd\r\n\t\tint year = m_diapause_end.GetYear();\r\n\t\tCTRef begin = CTRef(year, JANUARY, DAY_01);\r\n\t\tCTRef end = CTRef(year, DECEMBER, DAY_31);\r\n\r\n\t\tif (d >= begin && d<= end)\r\n\t\t{\r\n\t\t\t//Egg creation DD (allen 1976)\r\n\t\t\tm_egg_creation_CDD += m_DD.GetDD(wday);\r\n\t\t\tstat[S_EGG_CREATION_CDD] = m_egg_creation_CDD;\r\n\r\n\t\t\t//diapause end negative DD\r\n\t\t\tdouble T = wday[H_TNTX][MEAN];\r\n\t\t\tT = CLaricobiusNigrinus::AdjustTLab(wday.GetWeatherStation()->m_name, NOT_INIT, wday.GetTRef(), T);\r\n\t\t\t//T = max(m_equations.m_ADE[ʎa], T);\r\n\t\t\tdouble NDD = min(0.0, T - m_equations.m_ADE[ʎb]);//DD is negative\r\n\r\n\t\t\tint ii = d-begin;\r\n\t\t\t//if( ii>=(172-1) && ii<=int(m_equations.m_ADE[ʎ0]-1))\r\n\t\t\tif (ii >= int(m_equations.m_ADE[ʎ0] - 1) && ii <= int(m_equations.m_ADE[ʎ1] - 1))\r\n\t\t\t\tm_diapause_end_NCDD += NDD;\r\n\r\n\t\t\tstat[S_DIAPAUSE_END_NCDD] = m_diapause_end_NCDD;\r\n\t\t}\r\n\r\n\r\n\t\tbegin = m_diapause_end;\r\n\t\tend = CTRef(m_diapause_end.GetYear()+1, JANUARY, DAY_31);\r\n\t\tif (d >= begin && d <= end)\r\n\t\t{\r\n\t\t\t//adult emergence (growing DD)\r\n\t\t\tdouble T = wday[H_TNTX][MEAN];\r\n\t\t\tT = CLaricobiusNigrinus::AdjustTLab(wday.GetWeatherStation()->m_name, NOT_INIT, wday.GetTRef(), T);\r\n\r\n\t\t\tdouble GDD = max(0.0, T - m_equations.m_EAS[Τᴴ]);\r\n\t\t\tm_adult_emergence_CDD += GDD;\r\n\t\t\tstat[S_ADULT_EMERGENCE_CDD] = m_adult_emergence_CDD;\r\n\t\t}\r\n\t}\r\n\r\n\r\n}", "meta": {"hexsha": "9a8462e0e175c3b453e9d3ef8b2c634c5eeff43c", "size": 13427, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "wbsModels/LaricobiusNigrinus/LaricobiusNigrinus.cpp", "max_stars_repo_name": "RNCan/WeatherBasedSimulationFramework", "max_stars_repo_head_hexsha": "19df207d11b1dddf414d78e52bece77f31d45df8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2017-05-26T21:19:41.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-03T14:17:29.000Z", "max_issues_repo_path": "wbsModels/LaricobiusNigrinus/LaricobiusNigrinus.cpp", "max_issues_repo_name": "RNCan/WeatherBasedSimulationFramework", "max_issues_repo_head_hexsha": "19df207d11b1dddf414d78e52bece77f31d45df8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2016-02-18T12:39:58.000Z", "max_issues_repo_issues_event_max_datetime": "2016-03-13T12:57:45.000Z", "max_forks_repo_path": "wbsModels/LaricobiusNigrinus/LaricobiusNigrinus.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": 28.6289978678, "max_line_length": 153, "alphanum_fraction": 0.5848663141, "num_tokens": 4090, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6757645879592642, "lm_q2_score": 0.44939263446475963, "lm_q1q2_score": 0.30368362846100655}}
{"text": "/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */\n\n/*\n Copyright (C) 2000, 2001, 2002, 2003 RiskMap srl\n Copyright (C) 2003, 2004, 2005, 2006, 2007 StatPro Italia srl\n Copyright (C) 2006, 2008 Ferdinando Ametrano\n Copyright (C) 2010 Andre Miemiec\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 irregularswap.hpp\n    \\brief Irregular fixed-rate vs Libor swap\n*/\n\n#ifndef quantlib_irregular_swap_hpp\n#define quantlib_irregular_swap_hpp\n\n#include <ql/cashflows/fixedratecoupon.hpp>\n#include <ql/cashflows/iborcoupon.hpp>\n#include <ql/instruments/swap.hpp>\n#include <ql/time/daycounter.hpp>\n#include <ql/time/schedule.hpp>\n#include <boost/optional.hpp>\n\nnamespace QuantLib {\n\n    class IborIndex;\n\n    //! Irregular swap: fixed vs floating leg\n    class IrregularSwap : public Swap {\n      public:\n        enum Type { Receiver = -1, Payer = 1 };\n        class arguments;\n        class results;\n        class engine;\n        IrregularSwap(\n            Type type,\n            const Leg& fixLeg,\n            const Leg& floatLeg);\n        //! \\name Inspectors\n        //@{\n        Type type() const;\n\n        const Leg& fixedLeg() const;\n        const Leg& floatingLeg() const;\n        //@}\n\n        //! \\name Results\n        //@{\n        Real fixedLegBPS() const;\n        Real fixedLegNPV() const;\n        Rate fairRate() const;\n\n        Real floatingLegBPS() const;\n        Real floatingLegNPV() const;\n        Spread fairSpread() const;\n        //@}\n        // other\n        void setupArguments(PricingEngine::arguments* args) const override;\n        void fetchResults(const PricingEngine::results*) const override;\n\n      private:\n        void setupExpired() const override;\n        Type type_;\n\n        // results\n        mutable Rate fairRate_;\n        mutable Spread fairSpread_;\n    };\n\n\n    //! %Arguments for irregular-swap calculation\n    class IrregularSwap::arguments : public Swap::arguments {\n      public:\n        arguments() : type(Receiver){}\n        Type type;\n        \n\n        std::vector<Date> fixedResetDates;\n        std::vector<Date> fixedPayDates;\n        std::vector<Real> fixedCoupons;\n        std::vector<Real> fixedNominals;\n\n        std::vector<Date> floatingResetDates;\n        std::vector<Date> floatingFixingDates;\n        std::vector<Date> floatingPayDates;\n        std::vector<Time> floatingAccrualTimes;\n        std::vector<Real> floatingNominals;\n        std::vector<Spread> floatingSpreads;\n        std::vector<Real> floatingCoupons;\n\n        void validate() const override;\n    };\n\n    //! %Results from irregular-swap calculation\n    class IrregularSwap::results : public Swap::results {\n      public:\n        Rate fairRate;\n        Spread fairSpread;\n        void reset() override;\n    };\n\n    class IrregularSwap::engine : public GenericEngine<IrregularSwap::arguments,\n                                                       IrregularSwap::results> {};\n\n\n    // inline definitions\n\n    inline IrregularSwap::Type IrregularSwap::type() const {\n        return type_;\n    }\n\n    inline const Leg& IrregularSwap::fixedLeg() const {\n        return legs_[0];\n    }\n\n    inline const Leg& IrregularSwap::floatingLeg() const {\n        return legs_[1];\n    }\n\n    std::ostream& operator<<(std::ostream& out,\n                             IrregularSwap::Type t);\n\n}\n\n#endif\n", "meta": {"hexsha": "a5f036fee47ea893e9d57cb20f7fbfc11967712a", "size": 3973, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ql/experimental/swaptions/irregularswap.hpp", "max_stars_repo_name": "SoftwareIngenieur/QuantLib", "max_stars_repo_head_hexsha": "7a59dd749869f7a679536df322482bf9c6531d38", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ql/experimental/swaptions/irregularswap.hpp", "max_issues_repo_name": "SoftwareIngenieur/QuantLib", "max_issues_repo_head_hexsha": "7a59dd749869f7a679536df322482bf9c6531d38", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ql/experimental/swaptions/irregularswap.hpp", "max_forks_repo_name": "SoftwareIngenieur/QuantLib", "max_forks_repo_head_hexsha": "7a59dd749869f7a679536df322482bf9c6531d38", "max_forks_repo_licenses": ["BSD-3-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.5827338129, "max_line_length": 82, "alphanum_fraction": 0.6390636798, "num_tokens": 922, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6370307944803832, "lm_q2_score": 0.476579651063676, "lm_q1q2_score": 0.30359591375027734}}
{"text": "// Copyright Nick Thompson, 2020\n// Use, modification and distribution are subject to the\n// Boost Software License, Version 1.0.\n// (See accompanying file LICENSE_1_0.txt\n// or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n#ifndef BOOST_MATH_INTERPOLATORS_CUBIC_HERMITE_HPP\n#define BOOST_MATH_INTERPOLATORS_CUBIC_HERMITE_HPP\n#include <memory>\n#include <boost/math/interpolators/detail/cubic_hermite_detail.hpp>\n\nnamespace boost::math::interpolators {\n\ntemplate<class RandomAccessContainer>\nclass cubic_hermite {\npublic:\n    using Real = typename RandomAccessContainer::value_type;\n\n    cubic_hermite(RandomAccessContainer && x, RandomAccessContainer && y, RandomAccessContainer && dydx) \n    : impl_(std::make_shared<detail::cubic_hermite_detail<RandomAccessContainer>>(std::move(x), std::move(y), std::move(dydx)))\n    {}\n\n    Real operator()(Real x) const {\n        return impl_->operator()(x);\n    }\n\n    Real prime(Real x) const {\n        return impl_->prime(x);\n    }\n\n    friend std::ostream& operator<<(std::ostream & os, const cubic_hermite & m)\n    {\n        os << *m.impl_;\n        return os;\n    }\n\n    void push_back(Real x, Real y, Real dydx) {\n        impl_->push_back(x, y, dydx);\n    }\n\nprivate:\n    std::shared_ptr<detail::cubic_hermite_detail<RandomAccessContainer>> impl_;\n};\n\n}\n#endif", "meta": {"hexsha": "6785906581a14f90232784dfe1d5ba6104655c15", "size": 1306, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "eosio.evm/external/boost/math/interpolators/cubic_hermite.hpp", "max_stars_repo_name": "conr2d/eosio.evm", "max_stars_repo_head_hexsha": "93e6b9bd46bef24e356f924ed1bf0c33196e7432", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 84.0, "max_stars_repo_stars_event_min_datetime": "2020-02-26T22:26:47.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T20:21:47.000Z", "max_issues_repo_path": "eosio.evm/external/boost/math/interpolators/cubic_hermite.hpp", "max_issues_repo_name": "cnamway/eosio.evm", "max_issues_repo_head_hexsha": "93e6b9bd46bef24e356f924ed1bf0c33196e7432", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-02-22T04:15:22.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-23T20:06:16.000Z", "max_forks_repo_path": "eosio.evm/external/boost/math/interpolators/cubic_hermite.hpp", "max_forks_repo_name": "cnamway/eosio.evm", "max_forks_repo_head_hexsha": "93e6b9bd46bef24e356f924ed1bf0c33196e7432", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 28.0, "max_forks_repo_forks_event_min_datetime": "2020-02-27T14:07:00.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-10T07:53:36.000Z", "avg_line_length": 28.3913043478, "max_line_length": 127, "alphanum_fraction": 0.7082695253, "num_tokens": 338, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.658417500561683, "lm_q2_score": 0.4610167793123159, "lm_q1q2_score": 0.303541515551812}}
{"text": "// Std\n#include <algorithm>\n#include <deque>\n#include <unordered_map>\n// Boost\n#include <boost/graph/graphviz.hpp>\n#include <boost/graph/depth_first_search.hpp>\n#include <boost/graph/visitors.hpp>\n// Our stuff \n#include \"chemgraph.hpp\"\n#include \"ctab.hpp\"\n#include \"log.hpp\"\n#include \"gauss.hpp\"\n\nusing namespace std;\nusing namespace boost;\n\nChemGraph toGraph(CTab& tab)\n{\n    ChemGraph graph;\n    //add_vertex\n    for_each(tab.atoms.begin(), tab.atoms.end(), [&graph](const AtomEntry& a)\n    {\n        add_vertex(AtomVertex(a.code), graph);\n    });\n    auto vrange = vertices(graph);\n    //add edges\n    for_each(tab.bounds.begin(), tab.bounds.end(), [&graph, &vrange](const BoundEntry& b)\n    {\n        add_edge(vrange.first[b.a1] - 1, vrange.first[b.a2] - 1, Bound(b.type), graph);\n    });\n    return graph;\n}\n\nint getValence(ChemGraph& graph, ChemGraph::vertex_descriptor vertex)\n{\n    auto edges = out_edges(vertex, graph);\n    int valence = 0;\n    for (auto p = edges.first; p != edges.second; p++)\n    {\n        valence += graph[*p].type;\n    }\n    return valence;\n}\n\nChemGraph& addHydrogen(ChemGraph& graph)\n{\n    std::unordered_map<int, int> valences;\n    valences.insert(make_pair(C.code(), 4));\n    valences.insert(make_pair(N.code(), 3));\n    valences.insert(make_pair(O.code(), 2));\n    auto vtx = vertices(graph);\n    for(auto p = vtx.first; p != vtx.second; p++)\n    {\n        //Note: no extra hydrogens for negative ions\n        if(valences.find(graph[*p].code.code()) != valences.end()\n            && graph[*p].code.charge() >= 0)\n        {\n            int normal_valence = valences[graph[*p].code.code()];\n            // FIXME: counts 1.5 as 4 but that is \"works for me\"\n            int cur_val = getValence(graph, *p); \n            // fit with hydrogens if not enough valence\n            for(int i=cur_val; i<normal_valence; i++) \n            {\n                size_t v = add_vertex(AtomVertex(H), graph);\n                add_edge(*p, v, Bound(1), graph);\n            }\n        }\n    }\n    return graph;\n}\n\n\nclass CodeWriter {\npublic:\n    CodeWriter(ChemGraph& graph):g(graph){}\n    template <class VertexOrEdge>\n    void operator()(ostream& out, const VertexOrEdge& v) const {\n      out << \"[label=\\\"\" << g[v].code.symbol() << \" [\" << v << \"]\" << \"\\\"]\";\n    }\nprivate:\n    ChemGraph& g;\n};\n\n\nvoid dumpGraph(ChemGraph& graph, ostream& out)\n{\n    write_graphviz(out, graph, CodeWriter(graph));\n}\n\nostream& operator<<(ostream& stream, const Cycle& cycle)\n{\n    for (auto & e : cycle.edges)\n    {\n        stream << e.first << \"--\" << e.second << '\\n';\n    }\n    return stream;\n}\n\ninline set<pair<size_t, size_t>> chainToEdgeSet(const vector<size_t>& v){\n    assert(v.size() > 1);\n    set<pair<size_t,size_t>> out;\n    for(size_t i=1; i<v.size(); i++){\n        if(v[i-1] < v[i])\n            out.insert(make_pair(v[i-1], v[i]));\n        else\n            out.insert(make_pair(v[i], v[i-1]));\n    }\n    if(v.front() < v.back())\n        out.insert(make_pair(v.front(), v.back()));\n    else\n        out.insert(make_pair(v.back(), v.front()));\n    return out;\n}\n\n\nvoid logCycle(vector<pair<vd,vd>>& c)\n{\n    for (auto & e : c)\n    {\n        LOG(DEBUG) << e.first << \"--\" << e.second << '\\n';\n    }\n    LOG(DEBUG) << endline;\n}\n\n\nCycle::Cycle(vector<pair<vd, vd>> edges_):edges(edges_)\n{\n    chain = cycleToChain(edges, [](const pair<vd,vd>&p){ return p; });\n}\n\nCycle::Cycle(vector<vd> chain_):chain(chain_)\n{\n    auto eset = chainToEdgeSet(chain_);\n    edges.resize(eset.size());\n    copy(eset.begin(), eset.end(), edges.begin());\n}\n\nbool Cycle::intersects(const Cycle& that)const\n{\n   return intersection(that).size() > 0; // can be optimized futher\n}\n\nvector<pair<vd,vd>> Cycle::intersection(const Cycle& c)const\n{\n    vector<pair<vd,vd>> ret;\n    auto& c1 = edges;\n    auto& c2 = c.edges;\n    set_intersection(c1.begin(), c1.end(), c2.begin(), c2.end(), \n        back_inserter(ret));\n    return ret;\n}\n\nCycle& Cycle::markAromatic(ChemGraph& g)\n{\n    LOG(TRACE) << \"CHAIN: \";\n    for (int k : chain)\n        LOG(TRACE) << k << \" - \";\n    LOG(TRACE) << endline;\n    int piEl = 0;\n    for_each(chain.begin(), chain.end(), [&g, &piEl](int n){\n        LOG(TRACE) << \"Atom # \" << n << \" \" << g[n].code.symbol() << \" pi E = \" << g[n].piE << endline;\n        if (g[n].piE > 0)\n            piEl += g[n].piE;\n        //TODO: add debug trace for < 0\n    });\n    aromatic_ = ((piEl - 2) % 4 == 0); // Hukkel rule 4n + 2\n    LOG(TRACE) << \"PI E \" << piEl << \" aromatic? : \" << aromatic_ << endline;\n    //assign cyclic-only DC    \n    if (aromatic_)\n    {\n        for (auto n : chain)\n        {\n            g[n].inAromaCycle = true;\n        }\n        for (auto e : edges)\n        {\n            auto ed = edge(e.first, e.second, g);\n            g[ed.first].type = AROMATIC;\n        }\n    }\n    return *this;\n}\n\n\nstruct BfsNoop{\n    void onVertex(size_t v){}\n};\n\n// assuming constant edge weight - no priority queue required\ntemplate<class Policy=BfsNoop>\nstruct ShortestPaths : Policy{\npublic:\n    using G = ChemGraph;\n    \n    ShortestPaths(G& graph, size_t start, const vector<bool>& m=vector<bool>()):\n    g(graph), visited(num_vertices(graph)), edgeTo(num_vertices(graph)), s(start), mask(m){\n        queue.push_back(start);\n        visited[start] = true;\n        edgeTo[start] = (size_t)1<<(sizeof(size_t)*8-1);\n        bfs();\n    }\n    // apply functor to each node along the shortest path from v to starting point \n    // except the starting point itself\n    template<class Fn>\n    void apply(size_t v, Fn&& fn, bool includeStart=false){\n        if(!visited[v]) // cut apply for unexplored vertices\n            return;\n        size_t w = v;\n        while(w != s){\n            fn(w);\n            w = edgeTo[w];\n        }\n        if(includeStart)\n            fn(s);\n    }\n    // get shortest path to s\n    vector<size_t> path(size_t v, bool includeStart=false){\n        vector<size_t> vec;\n        apply(v, [&vec](size_t w){ vec.push_back(w); }, includeStart);\n        return vec;\n    }\n\n    // get prior vertex on path to this one\n    size_t prev(size_t p){\n        return edgeTo[p];\n    }\nprivate:\n    void bfs(){\n        while(!queue.empty()){\n            size_t v = queue.front();\n            queue.pop_front();\n            // push all not visited\n            auto adj = adjacent_vertices(v, g);\n            for(auto p = adj.first; p != adj.second; p++ ){\n                auto w = *p;\n                if(!visited[w] && (mask.empty() || mask[w])){\n                    edgeTo[w] = v;\n                    visited[w] = true;\n                    queue.push_back(w);\n                }\n            }\n        }\n    }\n    G& g;\n    vector<bool> visited;\n    vector<size_t> edgeTo;\n    deque<size_t> queue;\n    size_t s;\n    const vector<bool>& mask;\n    \n};\n\nShortestPaths<> shortestPaths(ChemGraph& g, size_t start, const vector<bool>& mask){\n    return ShortestPaths<>(g, start, mask);\n}\n\n\n// depth-first search to detect all cycles\n// ploicy-based design, final processing is deffered to the inherited policy\ntemplate<class Policy>\nstruct CycleDetect : Policy{\npublic:\n    using G = ChemGraph;\n    CycleDetect(G& graph, size_t start):Policy(), g(graph), visited(num_vertices(graph)){\n        dfs(start);\n    }\n\nprivate:\n    void dfs(size_t v){\n        visited[v] = true;\n        auto prev = path.size() ? path.back() : -1;\n        path.push_back(v);\n        auto adj = adjacent_vertices(v, g);\n        for(auto p = adj.first; p != adj.second; p++ ){\n            auto w = *p;\n            auto e = edge(v, w, g);\n            // TODO: turn to predicate or just use Boost DFS\n            if(g[e.first].type >= STEREO)\n                continue;\n            if(!visited[w]){\n                dfs(w); //pushes w on path\n                path.pop_back();\n            }\n            else if(w != prev){ // visited and not previous one\n                auto i = find(path.begin(), path.end(), w);\n                if(i != path.end()) //cycle\n                    Policy::onCycle(i, path.end());\n            }\n        }\n    }\n    G& g;\n    vector<bool> visited;\n    vector<int> path;\n};\n\nstruct FetchCycles{\n    vector<vector<size_t>> cycles;\n    template<class I>\n    void onCycle(I beg, I end){\n        cycles.emplace_back(beg, end);\n    }\n};\n\n//some cycle basis not even Horton's cycle basis\nvector<vector<size_t>> cycleBasis(ChemGraph& g, size_t start=0){\n    return CycleDetect<FetchCycles>(g, start).cycles;\n}\n\nvector<Cycle> minimalCycleBasis(ChemGraph& g){\n    vector<vector<size_t>> isolatedCycles; // \n    vector<vector<size_t>> basisCandidates; // that are not isolated\n    auto const V = num_vertices(g);\n    vector<vd> inCycle(V); // >0 if v is on some cycle\n    vector<bool> inCycleSystem(V); // if v is in some cycle system\n    LOG(DEBUG)<<\"IN CYCLE: \"<<inCycle<<endline;\n    // find isolated cycles and enumerate vertices belonging to some cycle\n    {\n        vector<vector<size_t>> someCycles = cycleBasis(g);\n        LOG(DEBUG) << \"G SIZE:\" << V << endline << \"CYCLES ARE:\" << endline;\n        for(auto &c : someCycles)\n            LOG(DEBUG) << c << endline;\n        // count number of times a cycles passes through a vertex\n        for(auto& c : someCycles){\n            for(size_t v : c){\n                inCycle[v]++;\n                inCycleSystem[v] = 1; // consider every as non-isoalted\n            }\n        }\n        \n        // test each cycle\n        for(auto& c : someCycles){\n            int total = accumulate(c.begin(), c.end(), 0, \n                [&inCycle](int sum, size_t v){\n                return sum + inCycle[v];\n            });\n            // no other cycles passing though isolated cycle's vertices\n            // therefore sum == length of cycle\n            if(total == (int)c.size()){\n                isolatedCycles.push_back(c);\n                for(auto v : c) // filter out isolated cycles from cycle systems\n                    inCycleSystem[v] = 0;\n            }\n            \n        }\n    }\n    LOG(DEBUG)<<\"IN CYCLE: \"<<inCycle<<endline;\n\n    // from now on consider only vertices from some cycles\n    // find connection points - vertices with > 2 adjacent\n    vector<size_t> connPts; \n    for(size_t v=0; v<num_vertices(g); v++){\n        if(inCycle[v] <= 1)\n            continue; //vertex in an isolated cycle\n        auto adj = adjacent_vertices(v, g);\n        size_t neib = count_if(adj.first, adj.second,\n            [&inCycle](vd a){\n                return inCycle[a] > 0;\n        });\n        if(neib > 2){\n            connPts.push_back(v);\n        }\n    }\n    LOG(DEBUG) << \"Conn pts.:\" << connPts <<endline;\n    // Modified Horton's algorithm (1987)\n    // Each cycle in minimal cycle base\n    // has form : Puw + Pvw + {u, v} (where Pxy is shortest path from x -> y)\n    // Puw & Pvw = {w} (the paths have no common edges)     \n    // Find candidates using these principles\n\n    // Combined with knowledge of connection points, all points being\n    // on some cycle & no isolated cycles we can examine only connection points\n    // for shortest-path trees\n    {\n        for(size_t con : connPts){\n            auto spf = shortestPaths(g, con, inCycleSystem);\n            auto eds = edges(g);\n            for(auto ep = eds.first ; ep != eds.second; ep++){\n                auto a = target(*ep, g);\n                auto b = source(*ep, g);\n                if(!inCycleSystem[a] || !inCycleSystem[b])\n                    continue;\n                // drop these along the paths\n                if(spf.prev(a) == b || spf.prev(b) == a)\n                    continue;\n                auto pa = spf.path(a);\n                auto pb = spf.path(b);\n                LOG(DEBUG) << \"Two shortest paths from \" << con << \": A \"<< a \n                    << \"  B \" << b << endline;\n                LOG(DEBUG) << pa << endline;\n                LOG(DEBUG) << pb << endline;\n                // both paths w/o starting point 'con'\n                size_t missingLink = con;\n                if(pa.empty() || pb.empty())\n                    continue;\n                // if have common suffix - drop\n                // they must pass through some connection point\n                // that we are going to process anyway\n                if(pa.back() == pb.back())\n                    continue;\n                // add missing link\n                pa.push_back(missingLink);\n                // and follow 2nd path \n                for_each(pb.rbegin(), pb.rend(), [&pa](size_t v){\n                    pa.push_back(v);\n                });\n                basisCandidates.push_back(pa);\n            }\n        }\n    }\n    // now perform Gaussian ellimination of candidate cycles\n    sort(basisCandidates.begin(), basisCandidates.end(), \n        [](const vector<size_t>& v1, const vector<size_t>& v2){\n            return v1.size() < v2.size();\n    });\n    vector<set<pair<size_t,size_t>>> basis; // basis accumulated as sets of edges\n    vector<size_t> basisIdx; // indices of these candidates that are in final basis\n    for(size_t i=0; i<basisCandidates.size(); i++){\n        auto s = chainToEdgeSet(basisCandidates[i]);\n        if(!elimination(s, basis)){\n            basis.push_back(s);\n            basisIdx.push_back(i);\n        }\n    }\n    LOG(DEBUG) << \"Isolated cycles:\\n\";\n    for(auto & c : isolatedCycles){\n        LOG(DEBUG) << c << endline;\n    }\n    LOG(DEBUG)<<\"Cycle base candidates:\\n\";\n    for(auto & c : basisCandidates){\n        LOG(DEBUG) << c << endline;\n    }\n    using std::move;\n    vector<Cycle> results;\n    copy(isolatedCycles.begin(), isolatedCycles.end(), back_inserter(results));\n    for(size_t i : basisIdx){\n        results.push_back(Cycle{basisCandidates[i]});\n    }\n    LOG(DEBUG)<<\"Minimal cycle base :\\n\";\n    for(auto& v : results){\n        LOG(DEBUG) << v << endline;\n    }\n    return results;\n}\n", "meta": {"hexsha": "cc878fb332b4f7a025cb53993cc3b477589a6f35", "size": 13741, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/chemgraph.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/chemgraph.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/chemgraph.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": 30.8786516854, "max_line_length": 103, "alphanum_fraction": 0.5428280329, "num_tokens": 3486, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.658417500561683, "lm_q2_score": 0.4610167793123159, "lm_q1q2_score": 0.303541515551812}}
{"text": "#ifndef STAN_MATH_TORSTEN_ONECPT_RK45_HPP\n#define STAN_MATH_TORSTEN_ONECPT_RK45_HPP\n\n#include <Eigen/Dense>\n#include <stan/math/torsten/to_array_2d.hpp>\n#include <stan/math/torsten/ev_manager.hpp>\n#include <stan/math/torsten/pmx_ode_model.hpp>\n#include <stan/math/torsten/pmx_coupled_model.hpp>\n#include <stan/math/torsten/pmx_onecpt_model.hpp>\n#include <stan/math/torsten/dsolve/pmx_odeint_integrator.hpp>\n#include <vector>\n#include <string>\n#include <stan/math/torsten/ev_solver.hpp>\n\nnamespace torsten {\n\n/**\n * Compute the predicted amounts in each compartment at each event\n * of an ODEs model. The model contains a base 1 Compartment PK\n * component which gets solved analytically, while the other ODEs\n * are solved numerically using stan::math::integrate_ode_rk45. This\n * amounts to using the mixed solver method.\n *\n * <b>Warning:</b> This prototype does not handle steady state events.\n *\n * @tparam T0 type of scalar for time of events.\n * @tparam T1 type of scalar for amount at each event.\n * @tparam T2 type of scalar for rate at each event.\n * @tparam T3 type of scalar for inter-dose inteveral at each event.\n * @tparam T4 type of scalars for the model parameters.\n * @tparam T5 type of scalars for the bio-variability parameters.\n * @tparam T6 type of scalars for the model tlag parameters.\n * @tparam F type of ODE system function.\n * @param[in] f functor for base ordinary differential equation\n *            which gets solved numerically.\n * @param[in] nOde number of ODEs we solve numerically.\n * @param[in] time times of events\n * @param[in] amt amount at each event\n * @param[in] rate rate at each event\n * @param[in] ii inter-dose interval at each event\n * @param[in] evid event identity:\n *                    (0) observation\n *                    (1) dosing\n *                    (2) other\n *                    (3) reset\n *                    (4) reset AND dosing\n * @param[in] cmt compartment number at each event\n * @param[in] addl additional dosing at each event\n * @param[in] ss steady state approximation at each event (0: no, 1: yes)\n * @param[in] theta vector of ODE parameters\n * @param[in] biovar bio-availability in each compartment\n * @param[in] tlag lag time in each compartment\n * @param[in] rel_tol relative tolerance for the Boost ode solver\n * @param[in] abs_tol absolute tolerance for the Boost ode solver\n * @param[in] max_num_steps maximal number of steps to take within\n *            the Boost ode solver\n * @return a matrix with predicted amount in each compartment\n *         at each event.\n *\n * FIX ME: msg should be passed on to functor (allows use of\n * print statement inside ODE system).\n */\ntemplate <typename T0, typename T1, typename T2, typename T3, typename T4,\n          typename T5, typename T6, typename F>\nEigen::Matrix <typename stan::return_type_t<T0, T1, T2, T3, T4, T5, T6>,\n               Eigen::Dynamic, Eigen::Dynamic>\npmx_solve_onecpt_rk45(const F& f,\n                      const int nOde,\n                      const std::vector<T0>& time,\n                      const std::vector<T1>& amt,\n                      const std::vector<T2>& rate,\n                      const std::vector<T3>& ii,\n                      const std::vector<int>& evid,\n                      const std::vector<int>& cmt,\n                      const std::vector<int>& addl,\n                      const std::vector<int>& ss,\n                      const std::vector<std::vector<T4> >& theta,\n                      const std::vector<std::vector<T5> >& biovar,\n                      const std::vector<std::vector<T6> >& tlag,\n                     double rel_tol,\n                     double abs_tol,\n                     long int max_num_steps,\n                     double as_rel_tol,\n                     double as_abs_tol,\n                     long int as_max_num_steps,\n                     std::ostream* msgs = 0) {\n  using std::vector;\n  using Eigen::Dynamic;\n  using Eigen::Matrix;\n  using boost::math::tools::promote_args;\n  using torsten::dsolve::odeint_scheme_rk45;\n\n  // check arguments\n  static const char* function(\"pmx_solve_onecpt_rk45\");\n  torsten::pmx_check(time, amt, rate, ii, evid, cmt, addl, ss, theta, function);\n\n  // Construct dummy array of matrix for last argument of pred\n  Matrix<T4, Dynamic, Dynamic> dummy_system;\n  vector<Matrix<T4, Dynamic, Dynamic> > dummy_systems(1, dummy_system);\n\n  const int &nPK = torsten::PMXOneCptModel<double>::Ncmt;\n\n  dsolve::PMXOdeIntegrator<dsolve::PMXVariadicOdeSystem, dsolve::PMXOdeintIntegrator<odeint_scheme_rk45>>\n    integrator(rel_tol, abs_tol, max_num_steps, as_rel_tol, as_abs_tol, as_max_num_steps, msgs);\n  const int nCmt = nPK + nOde;\n\n  using ER = NONMENEventsRecord<T0, T1, T2, T3>;\n  using EM = EventsManager<ER, NonEventParameters<T0, T4, std::vector, std::tuple<T5, T6> >>;\n  const ER events_rec(nCmt, time, amt, rate, ii, evid, cmt, addl, ss);\n\n  Matrix<typename EM::T_scalar, Dynamic, Dynamic> pred =\n    Matrix<typename EM::T_scalar, Dynamic, Dynamic>::Zero(events_rec.num_event_times(), EM::nCmt(events_rec));\n\n  using model_type = torsten::PkOneCptOdeModel<typename EM::T_par, F>;\n  EventSolver<model_type, EM> pr;\n  pr.pred(0, events_rec, pred, integrator, theta, biovar, tlag, nOde, f);\n  return pred;\n}\n\n  /*\n   * overload with default ode & algebra solver controls\n   */\ntemplate <typename T0, typename T1, typename T2, typename T3, typename T4,\n          typename T5, typename T6, typename F>\nEigen::Matrix <typename stan::return_type_t<T0, T1, T2, T3, T4, T5, T6>,\n               Eigen::Dynamic, Eigen::Dynamic>\npmx_solve_onecpt_rk45(const F& f,\n                      const int nOde,\n                      const std::vector<T0>& time,\n                      const std::vector<T1>& amt,\n                      const std::vector<T2>& rate,\n                      const std::vector<T3>& ii,\n                      const std::vector<int>& evid,\n                      const std::vector<int>& cmt,\n                      const std::vector<int>& addl,\n                      const std::vector<int>& ss,\n                      const std::vector<std::vector<T4> >& theta,\n                      const std::vector<std::vector<T5> >& biovar,\n                      const std::vector<std::vector<T6> >& tlag,\n                      std::ostream* msgs = 0) {\n  return pmx_solve_onecpt_rk45(f, nOde,\n                               time, amt, rate, ii, evid, cmt, addl, ss,\n                               theta, biovar, tlag,\n                               1.e-6, 1.e-6, 1e6,\n                               1.e-6, 1.e-6, 1e2,\n                               msgs);\n}\n\n  /*\n   * overload with default algebra solver controls\n   */\ntemplate <typename T0, typename T1, typename T2, typename T3, typename T4,\n          typename T5, typename T6, typename F>\nEigen::Matrix <typename stan::return_type_t<T0, T1, T2, T3, T4, T5, T6>,\n               Eigen::Dynamic, Eigen::Dynamic>\npmx_solve_onecpt_rk45(const F& f,\n                      const int nOde,\n                      const std::vector<T0>& time,\n                      const std::vector<T1>& amt,\n                      const std::vector<T2>& rate,\n                      const std::vector<T3>& ii,\n                      const std::vector<int>& evid,\n                      const std::vector<int>& cmt,\n                      const std::vector<int>& addl,\n                      const std::vector<int>& ss,\n                      const std::vector<std::vector<T4> >& theta,\n                      const std::vector<std::vector<T5> >& biovar,\n                      const std::vector<std::vector<T6> >& tlag,\n                     double rel_tol,\n                     double abs_tol,\n                     long int max_num_steps,\n                     std::ostream* msgs = 0) {\n  return pmx_solve_onecpt_rk45(f, nOde,\n                               time, amt, rate, ii, evid, cmt, addl, ss,\n                               theta, biovar, tlag,\n                               rel_tol, abs_tol, max_num_steps,\n                               1.e-6, 1.e-6, 1e2,\n                               msgs);\n}\n\n  /**\n   * Overload function to allow user to pass an std::vector for \n   * pMatrix/bioavailability/tlag\n   */\n  template <typename T0, typename T1, typename T2, typename T3,\n            typename T_par, typename T_biovar, typename T_tlag,\n            typename F,\n            typename = require_any_not_std_vector_t<T_par, T_biovar, T_tlag> >\n  stan::matrix_return_t<T0, T1, T2, T3, T_par, T_biovar, T_tlag>\n  pmx_solve_onecpt_rk45(const F& f,\n                        const int nOde,\n                        const std::vector<T0>& time,\n                        const std::vector<T1>& amt,\n                        const std::vector<T2>& rate,\n                        const std::vector<T3>& ii,\n                        const std::vector<int>& evid,\n                        const std::vector<int>& cmt,\n                        const std::vector<int>& addl,\n                        const std::vector<int>& ss,\n                        const std::vector<T_par>& pMatrix,\n                        const std::vector<T_biovar>& biovar,\n                        const std::vector<T_tlag>& tlag,\n                       double rel_tol,\n                       double abs_tol,\n                       long int max_num_steps,\n                       double as_rel_tol,\n                       double as_abs_tol,\n                       long int as_max_num_steps,\n                       std::ostream* msgs = 0) {\n    auto param_ = torsten::to_array_2d(pMatrix);\n    auto biovar_ = torsten::to_array_2d(biovar);\n    auto tlag_ = torsten::to_array_2d(tlag);\n\n    return pmx_solve_onecpt_rk45(f, nOde,\n                                 time, amt, rate, ii, evid, cmt, addl, ss,\n                                 param_, biovar_, tlag_,\n                                 rel_tol, abs_tol, max_num_steps,\n                                 as_rel_tol, as_abs_tol, as_max_num_steps,\n                                 msgs);\n  }\n\n  /**\n   * Overload function to allow user to pass an std::vector for \n   * pMatrix/bioavailability/tlag, with default ode &\n   * algebra solver controls\n   */\n  template <typename T0, typename T1, typename T2, typename T3,\n            typename T_par, typename T_biovar, typename T_tlag,\n            typename F,\n            typename = require_any_not_std_vector_t<T_par, T_biovar, T_tlag> >\n  stan::matrix_return_t<T0, T1, T2, T3, T_par, T_biovar, T_tlag>\n  pmx_solve_onecpt_rk45(const F& f,\n                        const int nOde,\n                        const std::vector<T0>& time,\n                        const std::vector<T1>& amt,\n                        const std::vector<T2>& rate,\n                        const std::vector<T3>& ii,\n                        const std::vector<int>& evid,\n                        const std::vector<int>& cmt,\n                        const std::vector<int>& addl,\n                        const std::vector<int>& ss,\n                        const std::vector<T_par>& pMatrix,\n                        const std::vector<T_biovar>& biovar,\n                        const std::vector<T_tlag>& tlag,\n                        std::ostream* msgs = 0) {\n    return pmx_solve_onecpt_rk45(f, nOde,\n                                 time, amt, rate, ii, evid, cmt, addl, ss,\n                                 pMatrix, biovar, tlag,\n                                 1.e-6, 1.e-6, 1e6,\n                                 1.e-6, 1.e-6, 1e2,\n                                 msgs);\n  }\n\n  /**\n   * Overload function to allow user to pass an std::vector for \n   * pMatrix/bioavailability/tlag, with default\n   * algebra solver controls\n   */\n  template <typename T0, typename T1, typename T2, typename T3,\n            typename T_par, typename T_biovar, typename T_tlag,\n            typename F,\n            typename = require_any_not_std_vector_t<T_par, T_biovar, T_tlag> >\n  stan::matrix_return_t<T0, T1, T2, T3, T_par, T_biovar, T_tlag>\n  pmx_solve_onecpt_rk45(const F& f,\n                        const int nOde,\n                        const std::vector<T0>& time,\n                        const std::vector<T1>& amt,\n                        const std::vector<T2>& rate,\n                        const std::vector<T3>& ii,\n                        const std::vector<int>& evid,\n                        const std::vector<int>& cmt,\n                        const std::vector<int>& addl,\n                        const std::vector<int>& ss,\n                        const std::vector<T_par>& pMatrix,\n                        const std::vector<T_biovar>& biovar,\n                        const std::vector<T_tlag>& tlag,\n                        double rel_tol,\n                        double abs_tol,\n                        long int max_num_steps,\n                        std::ostream* msgs = 0) {\n    return pmx_solve_onecpt_rk45(f, nOde,\n                                 time, amt, rate, ii, evid, cmt, addl, ss,\n                                 pMatrix, biovar, tlag,\n                                 rel_tol, abs_tol, max_num_steps,\n                                 1.e-6, 1.e-6, 1e2,\n                                 msgs);\n  }\n\n  // old version\ntemplate <typename T0, typename T1, typename T2, typename T3, typename T4,\n          typename T5, typename T6, typename F>\nstan::matrix_return_t<T0, T1, T2, T3, T4, T5, T6>\nmixOde1CptModel_rk45(const F& f,\n                     const int nOde,\n                     const std::vector<T0>& time,\n                     const std::vector<T1>& amt,\n                     const std::vector<T2>& rate,\n                     const std::vector<T3>& ii,\n                     const std::vector<int>& evid,\n                     const std::vector<int>& cmt,\n                     const std::vector<int>& addl,\n                     const std::vector<int>& ss,\n                     const std::vector<std::vector<T4> >& theta,\n                     const std::vector<std::vector<T5> >& biovar,\n                     const std::vector<std::vector<T6> >& tlag,\n                     double rel_tol = 1e-6,\n                     double abs_tol = 1e-6,\n                     long int max_num_steps = 1e6,\n                     std::ostream* msgs = 0) {\n  auto x = pmx_solve_onecpt_rk45(f, nOde,\n                                 time, amt, rate, ii, evid, cmt, addl, ss,\n                                 theta, biovar, tlag,\n                                 rel_tol, abs_tol, max_num_steps,\n                                 msgs);\n  return x.transpose();\n}\n\n  template <typename T0, typename T1, typename T2, typename T3,\n            typename T_par, typename T_biovar, typename T_tlag,\n            typename F,\n            typename = require_any_not_std_vector_t<T_par, T_biovar, T_tlag> >\n  stan::matrix_return_t<T0, T1, T2, T3, T_par, T_biovar, T_tlag>\n  mixOde1CptModel_rk45(const F& f,\n                        const int nOde,\n                        const std::vector<T0>& time,\n                        const std::vector<T1>& amt,\n                        const std::vector<T2>& rate,\n                        const std::vector<T3>& ii,\n                        const std::vector<int>& evid,\n                        const std::vector<int>& cmt,\n                        const std::vector<int>& addl,\n                        const std::vector<int>& ss,\n                        const std::vector<T_par>& pMatrix,\n                        const std::vector<T_biovar>& biovar,\n                        const std::vector<T_tlag>& tlag,\n                        double rel_tol = 1e-6,\n                        double abs_tol = 1e-6,\n                       long int max_num_steps = 1e6,\n                       std::ostream* msgs = 0) {\n    auto x = pmx_solve_onecpt_rk45(f, nOde,\n                                   time, amt, rate, ii, evid, cmt, addl, ss,\n                                   pMatrix, biovar, tlag,\n                                   rel_tol, abs_tol, max_num_steps,\n                                   msgs);\n    return x.transpose();\n  }\n\n}\n#endif\n", "meta": {"hexsha": "feb5aa38b8020436c8c0929700b0ece7fffbb03b", "size": 15914, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "pmx_solve_onecpt_rk45.hpp", "max_stars_repo_name": "metrumresearchgroup/torsten_math", "max_stars_repo_head_hexsha": "318cee4199342bd36d5f2b1241c6760acfcf58b7", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "pmx_solve_onecpt_rk45.hpp", "max_issues_repo_name": "metrumresearchgroup/torsten_math", "max_issues_repo_head_hexsha": "318cee4199342bd36d5f2b1241c6760acfcf58b7", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-04-27T23:53:22.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-27T23:57:43.000Z", "max_forks_repo_path": "pmx_solve_onecpt_rk45.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": 45.4685714286, "max_line_length": 110, "alphanum_fraction": 0.5256378032, "num_tokens": 3850, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7248702761768249, "lm_q2_score": 0.41869690935568665, "lm_q1q2_score": 0.30350094431903957}}
{"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// Purpose: Implementation of the HEALPix and rHEALPix projections.\n//          For background see <http://code.scenzgrid.org/index.php/p/scenzgrid-py/source/tree/master/docs/rhealpix_dggs.pdf>.\n// Authors: Alex Raichev (raichev@cs.auckland.ac.nz)\n//          Michael Speth (spethm@landcareresearch.co.nz)\n// Notes:   Raichev implemented these projections in Python and\n//          Speth translated them into C here.\n\n// Copyright (c) 2001, Thomas Flemming, tf@ttqv.com\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_HEALPIX_HPP\n#define BOOST_GEOMETRY_PROJECTIONS_HEALPIX_HPP\n\n#include <boost/geometry/util/math.hpp>\n\n#include <boost/geometry/srs/projections/impl/base_static.hpp>\n#include <boost/geometry/srs/projections/impl/base_dynamic.hpp>\n#include <boost/geometry/srs/projections/impl/projects.hpp>\n#include <boost/geometry/srs/projections/impl/factory_entry.hpp>\n#include <boost/geometry/srs/projections/impl/pj_auth.hpp>\n#include <boost/geometry/srs/projections/impl/pj_qsfn.hpp>\n\nnamespace boost { namespace geometry\n{\n\nnamespace projections\n{\n    #ifndef DOXYGEN_NO_DETAIL\n    namespace detail { namespace healpix\n    {\n\n            /* Fuzz to handle rounding errors: */\n            static const double epsilon = 1e-15;\n\n            template <typename T>\n            struct par_healpix\n            {\n                int north_square;\n                int south_square;\n                T qp;\n                detail::apa<T> apa;\n            };\n\n            template <typename T>\n            struct cap_map\n            {\n                int cn; /* An integer 0--3 indicating the position of the polar cap. */\n                T x, y; /* Coordinates of the pole point (point of most extreme latitude on the polar caps). */\n                enum region_type {north, south, equatorial} region;\n            };\n            template <typename T>\n            struct point_xy\n            {\n                T x, y;\n            };\n\n            /* IDENT, R1, R2, R3, R1 inverse, R2 inverse, R3 inverse:*/\n            static double rot[7][2][2] = {\n                /* Identity matrix */\n                {{1, 0},{0, 1}},\n                /* Matrix for counterclockwise rotation by pi/2: */\n                {{ 0,-1},{ 1, 0}},\n                /* Matrix for counterclockwise rotation by pi: */\n                {{-1, 0},{ 0,-1}},\n                /* Matrix for counterclockwise rotation by 3*pi/2:  */\n                {{ 0, 1},{-1, 0}},\n                {{ 0, 1},{-1, 0}}, // 3*pi/2\n                {{-1, 0},{ 0,-1}}, // pi\n                {{ 0,-1},{ 1, 0}}  // pi/2\n            };\n\n            /**\n             * Returns the sign of the double.\n             * @param v the parameter whose sign is returned.\n             * @return 1 for positive number, -1 for negative, and 0 for zero.\n             **/\n            template <typename T>\n            inline T pj_sign (T const& v)\n            {\n                return v > 0 ? 1 : (v < 0 ? -1 : 0);\n            }\n            /**\n             * Return the index of the matrix in {{{1, 0},{0, 1}}, {{ 0,-1},{ 1, 0}}, {{-1, 0},{ 0,-1}}, {{ 0, 1},{-1, 0}}, {{ 0, 1},{-1, 0}}, {{-1, 0},{ 0,-1}}, {{ 0,-1},{ 1, 0}}}.\n             * @param index ranges from -3 to 3.\n             */\n            inline int get_rotate_index(int index)\n            {\n                switch(index) {\n                case 0:\n                    return 0;\n                case 1:\n                    return 1;\n                case 2:\n                    return 2;\n                case 3:\n                    return 3;\n                case -1:\n                    return 4;\n                case -2:\n                    return 5;\n                case -3:\n                    return 6;\n                }\n                return 0;\n            }\n            /**\n             * Return 1 if point (testx, testy) lies in the interior of the polygon\n             * determined by the vertices in vert, and return 0 otherwise.\n             * See http://paulbourke.net/geometry/polygonmesh/ for more details.\n             * @param nvert the number of vertices in the polygon.\n             * @param vert the (x, y)-coordinates of the polygon's vertices\n             **/\n            template <typename T>\n            inline int pnpoly(int nvert, T vert[][2], T const& testx, T const& testy)\n            {\n                int i;\n                int counter = 0;\n                T xinters;\n                point_xy<T> p1, p2;\n\n                /* Check for boundrary cases */\n                for (i = 0; i < nvert; i++) {\n                    if (testx == vert[i][0] && testy == vert[i][1]) {\n                        return 1;\n                    }\n                }\n\n                p1.x = vert[0][0];\n                p1.y = vert[0][1];\n\n                for (i = 1; i < nvert; i++) {\n                    p2.x = vert[i % nvert][0];\n                    p2.y = vert[i % nvert][1];\n                    if (testy > (std::min)(p1.y, p2.y)  &&\n                        testy <= (std::max)(p1.y, p2.y) &&\n                        testx <= (std::max)(p1.x, p2.x) &&\n                        p1.y != p2.y)\n                    {\n                        xinters = (testy-p1.y)*(p2.x-p1.x)/(p2.y-p1.y)+p1.x;\n                        if (p1.x == p2.x || testx <= xinters)\n                            counter++;\n                    }\n                    p1 = p2;\n                }\n\n                if (counter % 2 == 0) {\n                    return 0;\n                } else {\n                    return 1;\n                }\n            }\n            /**\n             * Return 1 if (x, y) lies in (the interior or boundary of) the image of the\n             * HEALPix projection (in case proj=0) or in the image the rHEALPix projection\n             * (in case proj=1), and return 0 otherwise.\n             * @param north_square the position of the north polar square (rHEALPix only)\n             * @param south_square the position of the south polar square (rHEALPix only)\n             **/\n            template <typename T>\n            inline int in_image(T const& x, T const& y, int proj, int north_square, int south_square)\n            {\n                static const T pi = detail::pi<T>();\n                static const T half_pi = detail::half_pi<T>();\n                static const T fourth_pi = detail::fourth_pi<T>();\n\n                if (proj == 0) {\n                    T healpixVertsJit[][2] = {\n                        {-pi - epsilon,   fourth_pi},\n                        {-3.0*fourth_pi,  half_pi + epsilon},\n                        {-half_pi,        fourth_pi + epsilon},\n                        {-fourth_pi,      half_pi + epsilon},\n                        {0.0,             fourth_pi + epsilon},\n                        {fourth_pi,       half_pi + epsilon},\n                        {half_pi,         fourth_pi + epsilon},\n                        {3.0*fourth_pi,   half_pi + epsilon},\n                        {pi + epsilon,    fourth_pi},\n                        {pi + epsilon,   -fourth_pi},\n                        {3.0*fourth_pi,  -half_pi - epsilon},\n                        {half_pi,        -fourth_pi - epsilon},\n                        {fourth_pi,      -half_pi - epsilon},\n                        {0.0,            -fourth_pi - epsilon},\n                        {-fourth_pi,     -half_pi - epsilon},\n                        {-half_pi,       -fourth_pi - epsilon},\n                        {-3.0*fourth_pi, -half_pi - epsilon},\n                        {-pi - epsilon,  -fourth_pi}\n                    };\n                    return pnpoly((int)sizeof(healpixVertsJit)/\n                                  sizeof(healpixVertsJit[0]), healpixVertsJit, x, y);\n                } else {\n                    T rhealpixVertsJit[][2] = {\n                        {-pi - epsilon,                                 fourth_pi + epsilon},\n                        {-pi + north_square*half_pi - epsilon,          fourth_pi + epsilon},\n                        {-pi + north_square*half_pi - epsilon,          3.0*fourth_pi + epsilon},\n                        {-pi + (north_square + 1.0)*half_pi + epsilon,  3.0*fourth_pi + epsilon},\n                        {-pi + (north_square + 1.0)*half_pi + epsilon,  fourth_pi + epsilon},\n                        {pi + epsilon,                                  fourth_pi + epsilon},\n                        {pi + epsilon,                                 -fourth_pi - epsilon},\n                        {-pi + (south_square + 1.0)*half_pi + epsilon, -fourth_pi - epsilon},\n                        {-pi + (south_square + 1.0)*half_pi + epsilon, -3.0*fourth_pi - epsilon},\n                        {-pi + south_square*half_pi - epsilon,         -3.0*fourth_pi - epsilon},\n                        {-pi + south_square*half_pi - epsilon,         -fourth_pi - epsilon},\n                        {-pi - epsilon,                                -fourth_pi - epsilon}\n                    };\n\n                    return pnpoly((int)sizeof(rhealpixVertsJit)/\n                                  sizeof(rhealpixVertsJit[0]), rhealpixVertsJit, x, y);\n                }\n            }\n            /**\n             * Return the authalic latitude of latitude alpha (if inverse=0) or\n             * return the approximate latitude of authalic latitude alpha (if inverse=1).\n             * P contains the relavent ellipsoid parameters.\n             **/\n            template <typename Parameters, typename T>\n            inline T auth_lat(const Parameters& par, const par_healpix<T>& proj_parm, T const& alpha, int inverse)\n            {\n                if (inverse == 0) {\n                    /* Authalic latitude. */\n                    T q = pj_qsfn(sin(alpha), par.e, 1.0 - par.es);\n                    T qp = proj_parm.qp;\n                    T ratio = q/qp;\n\n                    if (math::abs(ratio) > 1) {\n                        /* Rounding error. */\n                        ratio = pj_sign(ratio);\n                    }\n\n                    return asin(ratio);\n                } else {\n                    /* Approximation to inverse authalic latitude. */\n                    return pj_authlat(alpha, proj_parm.apa);\n                }\n            }\n            /**\n             * Return the HEALPix projection of the longitude-latitude point lp on\n             * the unit sphere.\n            **/\n            template <typename T>\n            inline void healpix_sphere(T const& lp_lam, T const& lp_phi, T& xy_x, T& xy_y)\n            {               \n                static const T pi = detail::pi<T>();\n                static const T half_pi = detail::half_pi<T>();\n                static const T fourth_pi = detail::fourth_pi<T>();\n\n                T lam = lp_lam;\n                T phi = lp_phi;\n                T phi0 = asin(T(2.0)/T(3.0));\n\n                /* equatorial region */\n                if ( fabsl(phi) <= phi0) {\n                    xy_x = lam;\n                    xy_y = 3.0*pi/8.0*sin(phi);\n                } else {\n                    T lamc;\n                    T sigma = sqrt(3.0*(1 - math::abs(sin(phi))));\n                    T cn = floor(2*lam / pi + 2);\n                    if (cn >= 4) {\n                        cn = 3;\n                    }\n                    lamc = -3*fourth_pi + half_pi*cn;\n                    xy_x = lamc + (lam - lamc)*sigma;\n                    xy_y = pj_sign(phi)*fourth_pi*(2 - sigma);\n                }\n                return;\n            }\n            /**\n             * Return the inverse of healpix_sphere().\n            **/\n            template <typename T>\n            inline void healpix_sphere_inverse(T const& xy_x, T const& xy_y, T& lp_lam, T& lp_phi)\n            {                \n                static const T pi = detail::pi<T>();\n                static const T half_pi = detail::half_pi<T>();\n                static const T fourth_pi = detail::fourth_pi<T>();\n\n                T x = xy_x;\n                T y = xy_y;\n                T y0 = fourth_pi;\n\n                /* Equatorial region. */\n                if (math::abs(y) <= y0) {\n                    lp_lam = x;\n                    lp_phi = asin(8.0*y/(3.0*pi));\n                } else if (fabsl(y) < half_pi) {\n                    T cn = floor(2.0*x/pi + 2.0);\n                    T xc, tau;\n                    if (cn >= 4) {\n                        cn = 3;\n                    }\n                    xc = -3.0*fourth_pi + (half_pi)*cn;\n                    tau = 2.0 - 4.0*fabsl(y)/pi;\n                    lp_lam = xc + (x - xc)/tau;\n                    lp_phi = pj_sign(y)*asin(1.0 - math::pow(tau, 2)/3.0);\n                } else {\n                    lp_lam = -1.0*pi;\n                    lp_phi = pj_sign(y)*half_pi;\n                }\n                return;\n            }\n            /**\n             * Return the vector sum a + b, where a and b are 2-dimensional vectors.\n             * @param ret holds a + b.\n             **/\n            template <typename T>\n            inline void vector_add(const T a[2], const T b[2], T ret[2])\n            {\n                int i;\n                for(i = 0; i < 2; i++) {\n                    ret[i] = a[i] + b[i];\n                }\n            }\n            /**\n             * Return the vector difference a - b, where a and b are 2-dimensional vectors.\n             * @param ret holds a - b.\n             **/\n            template <typename T>\n            inline void vector_sub(const T a[2], const T b[2], T ret[2])\n            {\n                int i;\n                for(i = 0; i < 2; i++) {\n                    ret[i] = a[i] - b[i];\n                }\n            }\n            /**\n             * Return the 2 x 1 matrix product a*b, where a is a 2 x 2 matrix and\n             * b is a 2 x 1 matrix.\n             * @param ret holds a*b.\n             **/\n            template <typename T1, typename T2>\n            inline void dot_product(const T1 a[2][2], const T2 b[2], T2 ret[2])\n            {\n                int i, j;\n                int length = 2;\n                for(i = 0; i < length; i++) {\n                    ret[i] = 0;\n                    for(j = 0; j < length; j++) {\n                        ret[i] += a[i][j]*b[j];\n                    }\n                }\n            }\n            /**\n             * Return the number of the polar cap, the pole point coordinates, and\n             * the region that (x, y) lies in.\n             * If inverse=0, then assume (x,y) lies in the image of the HEALPix\n             * projection of the unit sphere.\n             * If inverse=1, then assume (x,y) lies in the image of the\n             * (north_square, south_square)-rHEALPix projection of the unit sphere.\n             **/\n            template <typename T>\n            inline cap_map<T> get_cap(T x, T const& y, int north_square, int south_square,\n                                     int inverse)\n            {\n                static const T pi = detail::pi<T>();\n                static const T half_pi = detail::half_pi<T>();\n                static const T fourth_pi = detail::fourth_pi<T>();\n\n                cap_map<T> capmap;\n                T c;\n                capmap.x = x;\n                capmap.y = y;\n                if (inverse == 0) {\n                    if (y > fourth_pi) {\n                        capmap.region = cap_map<T>::north;\n                        c = half_pi;\n                    } else if (y < -fourth_pi) {\n                        capmap.region = cap_map<T>::south;\n                        c = -half_pi;\n                    } else {\n                        capmap.region = cap_map<T>::equatorial;\n                        capmap.cn = 0;\n                        return capmap;\n                    }\n                    /* polar region */\n                    if (x < -half_pi) {\n                        capmap.cn = 0;\n                        capmap.x = (-3.0*fourth_pi);\n                        capmap.y = c;\n                    } else if (x >= -half_pi && x < 0) {\n                        capmap.cn = 1;\n                        capmap.x = -fourth_pi;\n                        capmap.y = c;\n                    } else if (x >= 0 && x < half_pi) {\n                        capmap.cn = 2;\n                        capmap.x = fourth_pi;\n                        capmap.y = c;\n                    } else {\n                        capmap.cn = 3;\n                        capmap.x = 3.0*fourth_pi;\n                        capmap.y = c;\n                    }\n                } else {\n                    if (y > fourth_pi) {\n                        capmap.region = cap_map<T>::north;\n                        capmap.x = (-3.0*fourth_pi + north_square*half_pi);\n                        capmap.y = half_pi;\n                        x = x - north_square*half_pi;\n                    } else if (y < -fourth_pi) {\n                        capmap.region = cap_map<T>::south;\n                        capmap.x = (-3.0*fourth_pi + south_square*pi/2);\n                        capmap.y = -half_pi;\n                        x = x - south_square*half_pi;\n                    } else {\n                        capmap.region = cap_map<T>::equatorial;\n                        capmap.cn = 0;\n                        return capmap;\n                    }\n                    /* Polar Region, find the HEALPix polar cap number that\n                       x, y moves to when rHEALPix polar square is disassembled. */\n                    if (capmap.region == cap_map<T>::north) {\n                        if (y >= -x - fourth_pi - epsilon && y < x + 5.0*fourth_pi - epsilon) {\n                            capmap.cn = (north_square + 1) % 4;\n                        } else if (y > -x -fourth_pi + epsilon && y >= x + 5.0*fourth_pi - epsilon) {\n                            capmap.cn = (north_square + 2) % 4;\n                        } else if (y <= -x -fourth_pi + epsilon && y > x + 5.0*fourth_pi + epsilon) {\n                            capmap.cn = (north_square + 3) % 4;\n                        } else {\n                            capmap.cn = north_square;\n                        }\n                    } else if (capmap.region == cap_map<T>::south) {\n                        if (y <= x + fourth_pi + epsilon && y > -x - 5.0*fourth_pi + epsilon) {\n                            capmap.cn = (south_square + 1) % 4;\n                        } else if (y < x + fourth_pi - epsilon && y <= -x - 5.0*fourth_pi + epsilon) {\n                            capmap.cn = (south_square + 2) % 4;\n                        } else if (y >= x + fourth_pi - epsilon && y < -x - 5.0*fourth_pi - epsilon) {\n                            capmap.cn = (south_square + 3) % 4;\n                        } else {\n                            capmap.cn = south_square;\n                        }\n                    }\n                }\n                return capmap;\n            }\n            /**\n             * Rearrange point (x, y) in the HEALPix projection by\n             * combining the polar caps into two polar squares.\n             * Put the north polar square in position north_square and\n             * the south polar square in position south_square.\n             * If inverse=1, then uncombine the polar caps.\n             * @param north_square integer between 0 and 3.\n             * @param south_square integer between 0 and 3.\n             **/\n            template <typename T>\n            inline void combine_caps(T& xy_x, T& xy_y, int north_square, int south_square,\n                                     int inverse)\n            {\n                static const T half_pi = detail::half_pi<T>();\n                static const T fourth_pi = detail::fourth_pi<T>();\n\n                T v[2];\n                T c[2];\n                T vector[2];\n                T v_min_c[2];\n                T ret_dot[2];\n                const double (*tmpRot)[2];\n                int pole = 0;\n\n                cap_map<T> capmap = get_cap(xy_x, xy_y, north_square, south_square, inverse);\n                if (capmap.region == cap_map<T>::equatorial) {\n                    xy_x = capmap.x;\n                    xy_y = capmap.y;\n                    return;\n                }\n\n                v[0] = xy_x; v[1] = xy_y;\n                c[0] = capmap.x; c[1] = capmap.y;\n\n                if (inverse == 0) {\n                    /* Rotate (xy_x, xy_y) about its polar cap tip and then translate it to\n                       north_square or south_square. */\n\n                    if (capmap.region == cap_map<T>::north) {\n                        pole = north_square;\n                        tmpRot = rot[get_rotate_index(capmap.cn - pole)];\n                    } else {\n                        pole = south_square;\n                        tmpRot = rot[get_rotate_index(-1*(capmap.cn - pole))];\n                    }\n                } else {\n                    /* Inverse function.\n                     Unrotate (xy_x, xy_y) and then translate it back. */\n\n                    /* disassemble */\n                    if (capmap.region == cap_map<T>::north) {\n                        pole = north_square;\n                        tmpRot = rot[get_rotate_index(-1*(capmap.cn - pole))];\n                    } else {\n                        pole = south_square;\n                        tmpRot = rot[get_rotate_index(capmap.cn - pole)];\n                    }\n                }\n\n                vector_sub(v, c, v_min_c);\n                dot_product(tmpRot, v_min_c, ret_dot);\n\n                {\n                    T a[2];\n                    /* Workaround cppcheck git issue */\n                    T* pa = a;\n                    // TODO: in proj4 5.0.0 this line is used instead\n                    //pa[0] = -3.0*fourth_pi + ((inverse == 0) ? 0 : capmap.cn) *half_pi;\n                    pa[0] = -3.0*fourth_pi + ((inverse == 0) ? pole : capmap.cn) *half_pi;\n                    pa[1] = half_pi;\n                    vector_add(ret_dot, a, vector);\n                }\n\n                xy_x = vector[0];\n                xy_y = vector[1];\n            }\n\n            // template class, using CRTP to implement forward/inverse\n            template <typename T, typename Parameters>\n            struct base_healpix_ellipsoid\n                : public base_t_fi<base_healpix_ellipsoid<T, Parameters>, T, Parameters>\n            {\n                par_healpix<T> m_proj_parm;\n\n                inline base_healpix_ellipsoid(const Parameters& par)\n                    : base_t_fi<base_healpix_ellipsoid<T, Parameters>, T, Parameters>(*this, par)\n                {}\n\n                // FORWARD(e_healpix_forward)  ellipsoid\n                // Project coordinates from geographic (lon, lat) to cartesian (x, y)\n                inline void fwd(T const& lp_lon, T lp_lat, T& xy_x, T& xy_y) const\n                {\n                    lp_lat = auth_lat(this->params(), m_proj_parm, lp_lat, 0);\n                    return healpix_sphere(lp_lon, lp_lat, xy_x, xy_y);\n                }\n\n                // INVERSE(e_healpix_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                    /* Check whether (x, y) lies in the HEALPix image. */\n                    if (in_image(xy_x, xy_y, 0, 0, 0) == 0) {\n                        lp_lon = HUGE_VAL;\n                        lp_lat = HUGE_VAL;\n                        BOOST_THROW_EXCEPTION( projection_exception(error_invalid_x_or_y) );\n                    }\n                    healpix_sphere_inverse(xy_x, xy_y, lp_lon, lp_lat);\n                    lp_lat = auth_lat(this->params(), m_proj_parm, lp_lat, 1);\n                }\n\n                static inline std::string get_name()\n                {\n                    return \"healpix_ellipsoid\";\n                }\n\n            };\n\n            // template class, using CRTP to implement forward/inverse\n            template <typename T, typename Parameters>\n            struct base_healpix_spheroid\n                : public base_t_fi<base_healpix_spheroid<T, Parameters>, T, Parameters>\n            {\n                par_healpix<T> m_proj_parm;\n\n                inline base_healpix_spheroid(const Parameters& par)\n                    : base_t_fi<base_healpix_spheroid<T, Parameters>, T, Parameters>(*this, par)\n                {}\n\n                // FORWARD(s_healpix_forward)  sphere\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                    return healpix_sphere(lp_lon, lp_lat, xy_x, xy_y);\n                }\n\n                // INVERSE(s_healpix_inverse)  sphere\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                    /* Check whether (x, y) lies in the HEALPix image */\n                    if (in_image(xy_x, xy_y, 0, 0, 0) == 0) {\n                        lp_lon = HUGE_VAL;\n                        lp_lat = HUGE_VAL;\n                        BOOST_THROW_EXCEPTION( projection_exception(error_invalid_x_or_y) );\n                    }\n                    return healpix_sphere_inverse(xy_x, xy_y, lp_lon, lp_lat);\n                }\n\n                static inline std::string get_name()\n                {\n                    return \"healpix_spheroid\";\n                }\n\n            };\n\n            // template class, using CRTP to implement forward/inverse\n            template <typename T, typename Parameters>\n            struct base_rhealpix_ellipsoid\n                : public base_t_fi<base_rhealpix_ellipsoid<T, Parameters>, T, Parameters>\n            {\n                par_healpix<T> m_proj_parm;\n\n                inline base_rhealpix_ellipsoid(const Parameters& par)\n                    : base_t_fi<base_rhealpix_ellipsoid<T, Parameters>, T, Parameters>(*this, par)\n                {}\n\n                // FORWARD(e_rhealpix_forward)  ellipsoid\n                // Project coordinates from geographic (lon, lat) to cartesian (x, y)\n                inline void fwd(T const& lp_lon, T lp_lat, T& xy_x, T& xy_y) const\n                {\n                    lp_lat = auth_lat(this->params(), m_proj_parm, lp_lat, 0);\n                    healpix_sphere(lp_lon, lp_lat, xy_x, xy_y);\n                    combine_caps(xy_x, xy_y, this->m_proj_parm.north_square, this->m_proj_parm.south_square, 0);\n                }\n\n                // INVERSE(e_rhealpix_inverse)  ellipsoid\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                    /* Check whether (x, y) lies in the rHEALPix image. */\n                    if (in_image(xy_x, xy_y, 1, this->m_proj_parm.north_square, this->m_proj_parm.south_square) == 0) {\n                        lp_lon = HUGE_VAL;\n                        lp_lat = HUGE_VAL;\n                        BOOST_THROW_EXCEPTION( projection_exception(error_invalid_x_or_y) );\n                    }\n                    combine_caps(xy_x, xy_y, this->m_proj_parm.north_square, this->m_proj_parm.south_square, 1);\n                    healpix_sphere_inverse(xy_x, xy_y, lp_lon, lp_lat);\n                    lp_lat = auth_lat(this->params(), m_proj_parm, lp_lat, 1);\n                }\n\n                static inline std::string get_name()\n                {\n                    return \"rhealpix_ellipsoid\";\n                }\n\n            };\n\n            // template class, using CRTP to implement forward/inverse\n            template <typename T, typename Parameters>\n            struct base_rhealpix_spheroid\n                : public base_t_fi<base_rhealpix_spheroid<T, Parameters>, T, Parameters>\n            {\n                par_healpix<T> m_proj_parm;\n\n                inline base_rhealpix_spheroid(const Parameters& par)\n                    : base_t_fi<base_rhealpix_spheroid<T, Parameters>, T, Parameters>(*this, par)\n                {}\n\n                // FORWARD(s_rhealpix_forward)  sphere\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                    healpix_sphere(lp_lon, lp_lat, xy_x, xy_y);\n                    combine_caps(xy_x, xy_y, this->m_proj_parm.north_square, this->m_proj_parm.south_square, 0);\n                }\n\n                // INVERSE(s_rhealpix_inverse)  sphere\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                    /* Check whether (x, y) lies in the rHEALPix image. */\n                    if (in_image(xy_x, xy_y, 1, this->m_proj_parm.north_square, this->m_proj_parm.south_square) == 0) {\n                        lp_lon = HUGE_VAL;\n                        lp_lat = HUGE_VAL;\n                        BOOST_THROW_EXCEPTION( projection_exception(error_invalid_x_or_y) );\n                    }\n                    combine_caps(xy_x, xy_y, this->m_proj_parm.north_square, this->m_proj_parm.south_square, 1);\n                    return healpix_sphere_inverse(xy_x, xy_y, lp_lon, lp_lat);\n                }\n\n                static inline std::string get_name()\n                {\n                    return \"rhealpix_spheroid\";\n                }\n\n            };\n\n            // HEALPix\n            template <typename Parameters, typename T>\n            inline void setup_healpix(Parameters& par, par_healpix<T>& proj_parm)\n            {\n                if (par.es != 0.0) {\n                    proj_parm.apa = pj_authset<T>(par.es); /* For auth_lat(). */\n                    proj_parm.qp = pj_qsfn(1.0, par.e, par.one_es); /* For auth_lat(). */\n                    par.a = par.a*sqrt(0.5*proj_parm.qp); /* Set par.a to authalic radius. */\n                    pj_calc_ellipsoid_params(par, par.a, par.es); /* Ensure we have a consistent parameter set */\n                } else {\n                }\n            }\n\n            // rHEALPix\n            template <typename Params, typename Parameters, typename T>\n            inline void setup_rhealpix(Params const& params, Parameters& par, par_healpix<T>& proj_parm)\n            {\n                proj_parm.north_square = pj_get_param_i<srs::spar::north_square>(params, \"north_square\", srs::dpar::north_square);\n                proj_parm.south_square = pj_get_param_i<srs::spar::south_square>(params, \"south_square\", srs::dpar::south_square);\n                /* Check for valid north_square and south_square inputs. */\n                if ((proj_parm.north_square < 0) || (proj_parm.north_square > 3)) {\n                    BOOST_THROW_EXCEPTION( projection_exception(error_axis) );\n                }\n                if ((proj_parm.south_square < 0) || (proj_parm.south_square > 3)) {\n                    BOOST_THROW_EXCEPTION( projection_exception(error_axis) );\n                }\n                if (par.es != 0.0) {\n                    proj_parm.apa = pj_authset<T>(par.es); /* For auth_lat(). */\n                    proj_parm.qp = pj_qsfn(1.0, par.e, par.one_es); /* For auth_lat(). */\n                    par.a = par.a*sqrt(0.5*proj_parm.qp); /* Set par.a to authalic radius. */\n                    // TODO: why not the same as in healpix?\n                    //pj_calc_ellipsoid_params(par, par.a, par.es);\n                    par.ra = 1.0/par.a;\n                } else {\n                }\n            }\n\n    }} // namespace detail::healpix\n    #endif // doxygen\n\n    /*!\n        \\brief HEALPix projection\n        \\ingroup projections\n        \\tparam Geographic latlong point type\n        \\tparam Cartesian xy point type\n        \\tparam Parameters parameter type\n        \\par Projection characteristics\n         - Spheroid\n         - Ellipsoid\n        \\par Example\n        \\image html ex_healpix.gif\n    */\n    template <typename T, typename Parameters>\n    struct healpix_ellipsoid : public detail::healpix::base_healpix_ellipsoid<T, Parameters>\n    {\n        template <typename Params>\n        inline healpix_ellipsoid(Params const& , Parameters const& par)\n            : detail::healpix::base_healpix_ellipsoid<T, Parameters>(par)\n        {\n            detail::healpix::setup_healpix(this->m_par, this->m_proj_parm);\n        }\n    };\n\n    /*!\n        \\brief HEALPix projection\n        \\ingroup projections\n        \\tparam Geographic latlong point type\n        \\tparam Cartesian xy point type\n        \\tparam Parameters parameter type\n        \\par Projection characteristics\n         - Spheroid\n         - Ellipsoid\n        \\par Example\n        \\image html ex_healpix.gif\n    */\n    template <typename T, typename Parameters>\n    struct healpix_spheroid : public detail::healpix::base_healpix_spheroid<T, Parameters>\n    {\n        template <typename Params>\n        inline healpix_spheroid(Params const& , Parameters const& par)\n            : detail::healpix::base_healpix_spheroid<T, Parameters>(par)\n        {\n            detail::healpix::setup_healpix(this->m_par, this->m_proj_parm);\n        }\n    };\n\n    /*!\n        \\brief rHEALPix projection\n        \\ingroup projections\n        \\tparam Geographic latlong point type\n        \\tparam Cartesian xy point type\n        \\tparam Parameters parameter type\n        \\par Projection characteristics\n         - Spheroid\n         - Ellipsoid\n        \\par Projection parameters\n         - north_square (integer)\n         - south_square (integer)\n        \\par Example\n        \\image html ex_rhealpix.gif\n    */\n    template <typename T, typename Parameters>\n    struct rhealpix_ellipsoid : public detail::healpix::base_rhealpix_ellipsoid<T, Parameters>\n    {\n        template <typename Params>\n        inline rhealpix_ellipsoid(Params const& params, Parameters const& par)\n            : detail::healpix::base_rhealpix_ellipsoid<T, Parameters>(par)\n        {\n            detail::healpix::setup_rhealpix(params, this->m_par, this->m_proj_parm);\n        }\n    };\n\n    /*!\n        \\brief rHEALPix projection\n        \\ingroup projections\n        \\tparam Geographic latlong point type\n        \\tparam Cartesian xy point type\n        \\tparam Parameters parameter type\n        \\par Projection characteristics\n         - Spheroid\n         - Ellipsoid\n        \\par Projection parameters\n         - north_square (integer)\n         - south_square (integer)\n        \\par Example\n        \\image html ex_rhealpix.gif\n    */\n    template <typename T, typename Parameters>\n    struct rhealpix_spheroid : public detail::healpix::base_rhealpix_spheroid<T, Parameters>\n    {\n        template <typename Params>\n        inline rhealpix_spheroid(Params const& params, Parameters const& par)\n            : detail::healpix::base_rhealpix_spheroid<T, Parameters>(par)\n        {\n            detail::healpix::setup_rhealpix(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_healpix, healpix_spheroid, healpix_ellipsoid)\n        BOOST_GEOMETRY_PROJECTIONS_DETAIL_STATIC_PROJECTION(srs::spar::proj_rhealpix, rhealpix_spheroid, rhealpix_ellipsoid)\n\n        // Factory entry(s)\n        BOOST_GEOMETRY_PROJECTIONS_DETAIL_FACTORY_ENTRY_FI2(healpix_entry, healpix_spheroid, healpix_ellipsoid)\n        BOOST_GEOMETRY_PROJECTIONS_DETAIL_FACTORY_ENTRY_FI2(rhealpix_entry, rhealpix_spheroid, rhealpix_ellipsoid)\n        \n        BOOST_GEOMETRY_PROJECTIONS_DETAIL_FACTORY_INIT_BEGIN(healpix_init)\n        {\n            BOOST_GEOMETRY_PROJECTIONS_DETAIL_FACTORY_INIT_ENTRY(healpix, healpix_entry)\n            BOOST_GEOMETRY_PROJECTIONS_DETAIL_FACTORY_INIT_ENTRY(rhealpix, rhealpix_entry)\n        }\n\n    } // namespace detail\n    #endif // doxygen\n\n} // namespace projections\n\n}} // namespace boost::geometry\n\n#endif // BOOST_GEOMETRY_PROJECTIONS_HEALPIX_HPP\n\n", "meta": {"hexsha": "414935c040b0a674df11de9587725d96db8d9e7d", "size": 37780, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "deps/boost/boost/geometry/srs/projections/proj/healpix.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/healpix.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/healpix.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": 43.2760595647, "max_line_length": 181, "alphanum_fraction": 0.4827951297, "num_tokens": 8717, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6992544335934766, "lm_q2_score": 0.43398146480389854, "lm_q1q2_score": 0.30346346336151736}}
{"text": "#include <Rcpp.h>\n#include <RcppEigen.h>\n#include <vector>\n\n#include \"experimentalSetup.hpp\"\n#include \"encodingScheme.hpp\"\n#include \"individual.hpp\"\n#include \"population.hpp\"\n#include \"evolutionaryAlgorithm.hpp\"\n#include \"AuxiliaryFunctions.hpp\"\n#include \"logLikelihoods.hpp\"\n\n#include <boost/random/mersenne_twister.hpp>\n#include <boost/random/uniform_int_distribution.hpp>\n#include <boost/random/uniform_real_distribution.hpp>\n#include <boost/math/distributions/students_t.hpp>\n#include <boost/math/distributions/normal.hpp>\n\n\nEvolutionaryAlgorithm::EvolutionaryAlgorithm() { }\n\nEvolutionaryAlgorithm::EvolutionaryAlgorithm(ExperimentalSetup & ES, const std::size_t & populationSize, InitialPopulationRandomVariates & RV)\n{\n    PopulationSize = populationSize;\n    CurrentPopulation = InitialisePopulation(ES, RV);\n}\n\nEvolutionaryAlgorithm::EvolutionaryAlgorithm(ExperimentalSetup & ES, const std::size_t & populationSize,\n                                             const std::size_t & numberOfIterations, const std::size_t & numberOfIterationsEqualMinMax,\n                                             const std::size_t & numberOfFittestIndividuals,\n                                             const int & parentSelectionWindowSize, const bool & allowParentSurvival,\n                                             const double & crossoverProbability, const double & mutationProbabilityLowerLimit,\n                                             const std::size_t & mutationIterations, const double & mutationDegreesOfFreedom,\n                                             const Eigen::VectorXd & mutationDecay, const double & fractionFittestIndividuals,\n                                             const std::size_t & hillClimbingIterations, InitialPopulationRandomVariates & RV)\n{\n    PopulationSize = populationSize;\n    NumberOfFittestIndividuals = numberOfFittestIndividuals;\n    NumberOfIterations = numberOfIterations;\n    NumberOfIterationsEqualMinMax = numberOfIterationsEqualMinMax;\n\n    ParentSelectionWindowSize = parentSelectionWindowSize;\n    AllowParentSurvival = allowParentSurvival;\n\n    CrossoverProbability = crossoverProbability;\n\n    MutationProbabilityLowerLimit = mutationProbabilityLowerLimit;\n    MutationIterations = mutationIterations;\n\n    MutationDegreesOfFreedom = mutationDegreesOfFreedom;\n    MutationDecay = mutationDecay;\n    MutationDecay_t = MutationDecay[0];\n\n    FittestEnsuredSurvivalFraction = fractionFittestIndividuals;\n    FitnessEnsuredSurvivalFraction = -HUGE_VAL;\n\n    HillClimbingIterations = hillClimbingIterations;\n\n    CurrentPopulation = InitialisePopulation(ES, RV);\n    Iteration = 0;\n\n    // Finds maximum fitness index\n    Eigen::VectorXd::Index fittestIndividualIndex;\n    CurrentPopulation.Fitness.maxCoeff(&fittestIndividualIndex);\n    FittestIndividualIndex = fittestIndividualIndex;\n}\n\nEvolutionaryAlgorithm::EvolutionaryAlgorithm(ExperimentalSetup & ES, Population & P,\n                                             const std::size_t & numberOfIterations, const std::size_t & numberOfIterationsEqualMinMax,\n                                             const std::size_t & numberOfFittestIndividuals,\n                                             const int & parentSelectionWindowSize, const bool & allowParentSurvival,\n                                             const double & crossoverProbability, const double & mutationProbabilityLowerLimit,\n                                             const std::size_t & mutationIterations, const double & mutationDegreesOfFreedom,\n                                             const Eigen::VectorXd & mutationDecay, const double & fractionFittestIndividuals,\n                                             const std::size_t & hillClimbingIterations)\n{\n    CurrentPopulation = P;\n\n    PopulationSize = P.Individuals.size();\n    NumberOfFittestIndividuals = numberOfFittestIndividuals;\n    NumberOfIterations = numberOfIterations;\n    NumberOfIterationsEqualMinMax = numberOfIterationsEqualMinMax;\n\n    ParentSelectionWindowSize = parentSelectionWindowSize;\n    AllowParentSurvival = allowParentSurvival;\n\n    CrossoverProbability = crossoverProbability;\n\n    MutationProbabilityLowerLimit = mutationProbabilityLowerLimit;\n    MutationIterations = mutationIterations;\n    MutationDegreesOfFreedom = mutationDegreesOfFreedom;\n    MutationDecay = mutationDecay;\n    MutationDecay_t = MutationDecay[0];\n\n    FittestEnsuredSurvivalFraction = fractionFittestIndividuals;\n    FitnessEnsuredSurvivalFraction = -HUGE_VAL;\n\n    HillClimbingIterations = hillClimbingIterations;\n    Iteration = 0;\n\n    // Finds maximum fitness index\n    Eigen::VectorXd::Index fittestIndividualIndex;\n    CurrentPopulation.Fitness.maxCoeff(&fittestIndividualIndex);\n    FittestIndividualIndex = fittestIndividualIndex;\n}\n\nvoid EvolutionaryAlgorithm::RestructingIndividual(Individual & I, const ExperimentalSetup & ES)\n{\n    const std::size_t & NumberOfUnknownContributors = ES.NumberOfContributors - ES.NumberOfKnownContributors;\n    // Sorting unknown contributor mixtures\n    const Eigen::VectorXd & Mixtures = I.MixtureParameters.segment(ES.NumberOfKnownContributors, NumberOfUnknownContributors);\n\n    const std::vector<int> & sortedMixtures = sortedIndex(Mixtures);\n    for (std::size_t n = 0; n < NumberOfUnknownContributors; n++)\n    {\n        I.MixtureParameters[ES.NumberOfKnownContributors + n] = Mixtures[sortedMixtures[n]];\n    }\n\n    // Sorting unknown genotypes\n    const Eigen::VectorXd unsortedEncodedProfile = I.EncodedProfile;\n    const std::vector<Eigen::MatrixXd> unsortedReducedContributionMatrix = I.ReducedExpectedContributionMatrix;\n    for (std::size_t m = 0; m < ES.NumberOfMarkers; m++)\n    {\n        const Eigen::MatrixXd & unsortedReducedContributionMatrix_m = unsortedReducedContributionMatrix[m];\n        for (std::size_t c = 0; c < NumberOfUnknownContributors; c++)\n        {\n            I.ReducedExpectedContributionMatrix[m].col(c) = unsortedReducedContributionMatrix_m.col(sortedMixtures[c]);\n\n            std::size_t k = 2 * NumberOfUnknownContributors * m + 2 * c;\n            std::size_t contributorElement = 2 * NumberOfUnknownContributors * m + 2 * sortedMixtures[c];\n\n            if (unsortedEncodedProfile[contributorElement] <= unsortedEncodedProfile[contributorElement + 1]) {\n                I.EncodedProfile[k] = unsortedEncodedProfile[contributorElement];\n                I.EncodedProfile[k + 1] = unsortedEncodedProfile[contributorElement + 1];\n            }\n            else {\n                I.EncodedProfile[k] = unsortedEncodedProfile[contributorElement + 1];\n                I.EncodedProfile[k + 1] = unsortedEncodedProfile[contributorElement];\n            }\n        }\n    }\n}\n\nPopulation EvolutionaryAlgorithm::InitialisePopulation(ExperimentalSetup & ES, InitialPopulationRandomVariates & RV)\n{\n    std::vector<Individual> I(PopulationSize);\n    for (std::size_t n = 0; n < PopulationSize; n++)\n    {\n        Eigen::VectorXd U = ES.GenerateUnknownGenotype(RV);\n\n        Individual I_n = Individual(U, ES);\n\n        RestructingIndividual(I_n, ES);\n        I[n] = I_n;\n    }\n\n    Population P(I);\n    return P;\n}\n\n\nstd::size_t EvolutionaryAlgorithm::ChoosePartner(const Population & P, int currentIndividual, RandomVariates & RV)\n{\n    int lowerWindow = std::round(std::max(0.0, static_cast<double>(currentIndividual - ParentSelectionWindowSize)));\n    int upperWindow = std::round(std::min(currentIndividual + ParentSelectionWindowSize, static_cast<int>(PopulationSize - 1)));\n\n    int leftBound = (currentIndividual - ParentSelectionWindowSize + PopulationSize) % PopulationSize;\n    int rightBound = (currentIndividual + ParentSelectionWindowSize) % PopulationSize;\n\n    Eigen::VectorXd neighbourhood = Eigen::VectorXd::Zero(2 * ParentSelectionWindowSize);\n    Eigen::VectorXd logNeighbourhoodFitness = Eigen::VectorXd::Zero(2 * ParentSelectionWindowSize);\n    for (std::size_t i = 0; i < 2 * ParentSelectionWindowSize; i++)\n    {\n        bool j = (i >= ParentSelectionWindowSize);\n        int k = (leftBound + i + j) % PopulationSize;\n        neighbourhood[i] = k;\n        logNeighbourhoodFitness[i] = P.Fitness[k];\n    }\n\n    double logNeighbourhoodFitnessCenter = logNeighbourhoodFitness.maxCoeff();\n    Eigen::VectorXd neighbourhoodFitness = Eigen::VectorXd::Zero(2 * ParentSelectionWindowSize);\n    for (std::size_t i = 0; i < 2 * ParentSelectionWindowSize; i++)\n    {\n        neighbourhoodFitness[i] = std::exp(logNeighbourhoodFitness[i] - logNeighbourhoodFitnessCenter);\n    }\n\n    Eigen::VectorXd windowProbabilities = partialSumEigen(neighbourhoodFitness / neighbourhoodFitness.sum());\n\n    double u = RV.generate_uniform_real();\n\n    int h = 0;\n    while ((u > windowProbabilities[h + 1])) {\n        h++;\n    }\n\n    std::size_t partnerIndex = neighbourhood[h];\n    return partnerIndex;\n}\n\nIndividual EvolutionaryAlgorithm::Crossover(const Individual & I, const Individual & J, const ExperimentalSetup & ES, RandomVariates & RV)\n{\n    Eigen::MatrixXd E_IJ = bindColumns(I.EncodedProfile, J.EncodedProfile);\n\n    int columnIndex = RV.generate_uniform_binary();\n\n    std::size_t N = E_IJ.rows();\n    Eigen::VectorXd E = Eigen::VectorXd::Zero(N);\n    for (std::size_t n = 0; n < N; n++)\n    {\n        double p = RV.generate_uniform_real();\n        if (p < CrossoverProbability)\n        {\n            columnIndex = (columnIndex + 1) % 2;\n        }\n\n        E[n] = E_IJ.row(n)[columnIndex];\n    }\n\n    Individual K(E, ES);\n    RestructingIndividual(K, ES);\n\n    return K;\n}\n\nEigen::VectorXd EvolutionaryAlgorithm::CreateMutationProbability(Individual & I, const ExperimentalSetup & ES)\n{\n    const Eigen::VectorXd & E = I.EncodedProfile;\n    const double & referenceMarkerAverage = I.SampleParameters[0];\n    const double & dispersion = I.SampleParameters[1];\n\n    const Eigen::VectorXd & Coverage = ES.Coverage;\n    const Eigen::VectorXd & MarkerImbalance = I.MarkerImbalanceParameters;\n    const Eigen::VectorXd & NumberOfAlleles = ES.NumberOfAlleles;\n\n    std::size_t N = ES.Coverage.size();\n    boost::math::students_t devianceDistribution(MutationDegreesOfFreedom);\n\n    Eigen::VectorXd mutation = MutationProbabilityLowerLimit * Eigen::VectorXd::Ones(E.size());\n    if (std::abs(MutationDecay_t - MutationProbabilityLowerLimit) > DBL_EPSILON)\n    {\n        for (std::size_t m = 0; m < MarkerImbalance.size(); m++)\n        {\n            const Eigen::VectorXd & alleleIndex_m = I.ReducedAlleleIndex[m];\n            const std::size_t A = alleleIndex_m.size();\n\n            const Eigen::MatrixXd & expectedContributionProfile_m = I.ReducedExpectedContributionMatrix[m];\n            const Eigen::VectorXd & EC = expectedContributionProfile_m * I.MixtureParameters;\n\n            const Eigen::VectorXd & E_m = E.segment(2 * (ES.NumberOfContributors - ES.NumberOfKnownContributors) * m, 2 * (ES.NumberOfContributors - ES.NumberOfKnownContributors));\n            for (std::size_t i = 0; i < E_m.size(); i++)\n            {\n                const std::size_t & n = ES.PartialSumAlleles[m] + E_m[i];\n                std::size_t a = 0;\n                while ((alleleIndex_m[a] != E_m[i]) & (a < A - 1))\n                {\n                    a++;\n                }\n\n                double mu_ma = referenceMarkerAverage * MarkerImbalance[m] * EC[a];\n                if ((mu_ma == 0) & (Coverage[n] != 0))\n                {\n                    mu_ma += 2e-8;\n                }\n\n                double deviance_n = devianceResidualPoissonGammaDistribution(Coverage[n], mu_ma, mu_ma / dispersion);\n                if (std::isnan(deviance_n))\n                {\n                    deviance_n = 0.0;\n                    Rcpp::warning(\"Deviance returned 'nan'.\");\n                }\n                else if (std::isinf(deviance_n))\n                {\n                    deviance_n = HUGE_VAL;\n                    Rcpp::warning(\"Deviance returned 'inf'.\");\n                }\n\n                mutation[2 * (ES.NumberOfContributors - ES.NumberOfKnownContributors) * m + i] =\n                    MutationDecay_t - (MutationDecay_t - MutationProbabilityLowerLimit) * boost::math::pdf(devianceDistribution, deviance_n) /\n                        boost::math::pdf(devianceDistribution, 0.0);\n            }\n        }\n    }\n\n    return mutation;\n}\n\nvoid updateMarkerIndividual(const Eigen::VectorXd & E, std::vector<Eigen::MatrixXd> reducedExpectedContributionMatrix, std::vector<Eigen::VectorXd> reducedAlleleIndex,\n                            std::vector<Eigen::VectorXd> reducedNoiseIndex, const std::size_t & m, const ExperimentalSetup & ES)\n{\n    const std::size_t & numberOfUnknownContributors = ES.NumberOfContributors - ES.NumberOfKnownContributors;\n\n    // Creating genotype matrix of marker m\n    Eigen::MatrixXd decodedProfile_m = Eigen::MatrixXd::Zero(ES.NumberOfAlleles[m], ES.NumberOfContributors);\n    for (std::size_t i = 0; i < ES.NumberOfAlleles[m]; i++)\n    {\n        for (std::size_t j = 0; j < ES.NumberOfKnownContributors; j++)\n        {\n            decodedProfile_m(i, j) = ES.KnownProfiles(ES.PartialSumAlleles[m] + i, j);\n        }\n    }\n\n    for (std::size_t i = 0; i < numberOfUnknownContributors; i++)\n    {\n        for (std::size_t j = 0; j <= 1; j++)\n        {\n            std::size_t l = 2 * m * numberOfUnknownContributors + 2 * i + j;\n            decodedProfile_m(E[l], i + ES.NumberOfKnownContributors) += 1;\n        }\n    }\n\n    // Creating ECM of row n\n    std::vector<Eigen::MatrixXd> potentialParents_m = ES.PotentialParents[m];\n    Eigen::MatrixXd expectedContributionProfile_m = Eigen::MatrixXd::Zero(ES.NumberOfAlleles[m], ES.NumberOfContributors);\n    for (std::size_t u = 0; u < ES.NumberOfContributors; u++)\n    {\n        Eigen::VectorXd decodedProfile_mu = decodedProfile_m.col(u);\n        Eigen::VectorXd stutterContribution = Eigen::VectorXd::Zero(ES.NumberOfAlleles[m]);\n        for (std::size_t a = 0; a < ES.NumberOfAlleles[m]; a++)\n        {\n            stutterContribution[a] = ParentStutterContribution(a, ES.LevelsOfStutterRecursion, 1, decodedProfile_mu, potentialParents_m, ES.NumberOfAlleles[m]);\n        }\n\n        expectedContributionProfile_m.col(u) = decodedProfile_mu + stutterContribution;\n    }\n\n    double noiseProfileSum_m = 0.0;\n    double noiseProfileSize_m = expectedContributionProfile_m.rows();\n    for (std::size_t i = 0; i < noiseProfileSize_m; i++)\n    {\n        const double & ecps = expectedContributionProfile_m.row(i).sum();\n        if (!(ecps > 2e-16))\n        {\n            noiseProfileSum_m++;\n        }\n    }\n\n    Eigen::MatrixXd reducedExpectedContributionMatrix_m = Eigen::MatrixXd::Zero(noiseProfileSize_m - noiseProfileSum_m, ES.NumberOfContributors);\n    Eigen::VectorXd reducedAlleleIndex_m = Eigen::VectorXd::Zero(noiseProfileSize_m - noiseProfileSum_m);\n    Eigen::VectorXd reducedNoiseIndex_m = Eigen::VectorXd::Zero(noiseProfileSum_m);\n\n    std::size_t n = 0;\n    std::size_t i = 0, j = 0;\n    for (std::size_t a = 0; a < ES.NumberOfAlleles[m]; a++)\n    {\n        const Eigen::VectorXd & expectedContributionProfile_mn = expectedContributionProfile_m.row(n);\n\n        if (expectedContributionProfile_mn.sum() > 0)\n        {\n            reducedExpectedContributionMatrix_m.row(i) = expectedContributionProfile_mn;\n            reducedAlleleIndex_m[i] = a;\n            i++;\n        }\n        else\n        {\n            reducedNoiseIndex_m[j] = a;\n            j++;\n        }\n\n        n++;\n    }\n\n    reducedExpectedContributionMatrix[m] = reducedExpectedContributionMatrix_m;\n    reducedAlleleIndex[m] = reducedAlleleIndex_m;\n    reducedNoiseIndex[m] = reducedNoiseIndex_m;\n}\n\nvoid EvolutionaryAlgorithm::Mutation(Individual & I, const ExperimentalSetup & ES, RandomVariates & RV)\n{\n    std::size_t numberOfUnknownContributors = ES.NumberOfContributors - ES.NumberOfKnownContributors;\n\n    Eigen::VectorXd E = I.EncodedProfile;\n    Eigen::VectorXd encodedMutation = CreateMutationProbability(I, ES);\n\n    // const std::vector<Eigen::MatrixXd> reducedExpectedContributionMatrix = I.ReducedExpectedContributionMatrix;\n    // const std::vector<Eigen::VectorXd> reducedAlleleIndex = I.ReducedAlleleIndex;\n    // const std::vector<Eigen::VectorXd> reducedNoiseIndex = I.ReducedNoiseIndex;\n    for (std::size_t m = 0; m < ES.NumberOfMarkers; m++)\n    {\n        std::size_t j = 0;\n        const std::size_t i = 2 * numberOfUnknownContributors * m;\n        for (std::size_t k = 0; k < 2 * numberOfUnknownContributors; k++)\n        {\n            double mutate = RV.generate_uniform_real();\n            if (mutate < encodedMutation[i + k])\n            {\n                int mutationShift = 0;\n                if (ES.NumberOfAlleles[m] > 1)\n                {\n                    while(mutationShift == 0)\n                    {\n                        mutationShift += RV.generate_uniform_mutation[m]();\n                    }\n                }\n\n                const double E_k = E[i + k];\n                E[i + k] = static_cast<int>(E_k + mutationShift) % static_cast<int>(ES.NumberOfAlleles[m]);\n                j++;\n            }\n        }\n\n        // if (j > 0)\n        // {\n        //     updateMarkerIndividual(E, reducedExpectedContributionMatrix, reducedAlleleIndex, reducedNoiseIndex, m, ES);\n        // }\n    }\n\n    Individual J(E, ES); // J(E, reducedExpectedContributionMatrix, reducedAlleleIndex, reducedNoiseIndex, ES);\n    I = J;\n}\n\nEigen::VectorXd expectedContributionMatrixRow(const Eigen::VectorXd & E, const ExperimentalSetup & ES,\n                                              const int & m, const std::size_t & k, const std::size_t & n)\n{\n\n    const std::size_t & a = E[k];\n    const std::size_t & numberOfUnknownContributors = ES.NumberOfContributors - ES.NumberOfKnownContributors;\n\n    // Creating genotype matrix of marker m\n    Eigen::MatrixXd decodedProfile_m = Eigen::MatrixXd::Zero(ES.NumberOfAlleles[m], ES.NumberOfContributors);\n    for (std::size_t i = 0; i < ES.NumberOfAlleles[m]; i++)\n    {\n        for (std::size_t j = 0; j < ES.NumberOfKnownContributors; j++)\n        {\n            decodedProfile_m(i, j) = ES.KnownProfiles(ES.PartialSumAlleles[m] + i, j);\n        }\n    }\n\n    for (std::size_t i = 0; i < numberOfUnknownContributors; i++)\n    {\n        for (std::size_t j = 0; j <= 1; j++)\n        {\n            std::size_t l = 2 * m * numberOfUnknownContributors + 2 * i + j;\n            decodedProfile_m(E[l], i + ES.NumberOfKnownContributors) += 1;\n        }\n    }\n\n    // Creating ECM of row n\n    std::vector<Eigen::MatrixXd> potentialParents_m = ES.PotentialParents[m];\n    Eigen::VectorXd ECM_n = Eigen::VectorXd::Zero(decodedProfile_m.cols());\n    for (std::size_t j = 0; j < ECM_n.size(); j++)\n    {\n        const Eigen::VectorXd & decodedProfile_mj = decodedProfile_m.col(j);\n\n        double potentialParentContribution = ParentStutterContribution(a, ES.LevelsOfStutterRecursion, 1, decodedProfile_mj, potentialParents_m, ES.NumberOfAlleles[m]);\n        ECM_n[j] = decodedProfile_mj[a] + potentialParentContribution;\n    }\n\n    return ECM_n;\n}\n\nvoid EvolutionaryAlgorithm::HillClimbing(Individual & I, ExperimentalSetup & ES, RandomVariates & RV)\n{\n    std::size_t numberOfUnknownContributors = ES.NumberOfContributors - ES.NumberOfKnownContributors;\n\n    for (std::size_t i = 0; i < HillClimbingIterations; i++)\n    {\n        int stepMarker = RV.generate_uniform_marker();\n        int stepContributor = RV.generate_uniform_unknown_contributor();\n        int stepBinary = RV.generate_uniform_binary();\n        std::size_t k = 2 * stepMarker * numberOfUnknownContributors + 2 * stepContributor + stepBinary;\n\n        // Create n'th row of the decoded and ecm matrix\n        std::size_t n = ES.PartialSumAlleles[stepMarker] + I.EncodedProfile[k];\n        Eigen::VectorXd expectedContributionMatrixRow_n_i = expectedContributionMatrixRow(I.EncodedProfile, ES, stepMarker, k, n);\n\n        double I_mu_ma = I.SampleParameters[0] * ES.MarkerImbalances[n] * expectedContributionMatrixRow_n_i.transpose() * I.MixtureParameters;\n\n        std::vector< Eigen::VectorXd > surroundings(ES.NumberOfAlleles[stepMarker] - 1);\n        Eigen::VectorXd surroundingResiduals = Eigen::VectorXd::Zero(ES.NumberOfAlleles[stepMarker] - 1);\n        for (std::size_t j = 1; j < ES.NumberOfAlleles[stepMarker]; j++)\n        {\n            Eigen::VectorXd I_j = I.EncodedProfile;\n\n            I_j[k] = static_cast<int>(I_j[k] + j) % static_cast<int>(ES.NumberOfAlleles[stepMarker]);\n            std::size_t m = ES.PartialSumAlleles[stepMarker] + I_j[k];\n\n            Eigen::VectorXd expectedContributionMatrixRow_n_j = expectedContributionMatrixRow(I_j, ES, stepMarker, k, m);\n            double J_mu_ma = I.SampleParameters[0] * ES.MarkerImbalances[m] * expectedContributionMatrixRow_n_j.transpose() * I.MixtureParameters;\n\n            surroundings[j - 1] = I_j;\n            surroundingResiduals[j - 1] = std::abs(ES.Coverage[n] - I_mu_ma + ES.Coverage[m] - J_mu_ma);\n        }\n\n        Eigen::MatrixXf::Index minIndex;\n        double smallestValue = surroundingResiduals.minCoeff(&minIndex);\n\n        // std::vector<Eigen::MatrixXd> reducedExpectedContributionMatrix = I.ReducedExpectedContributionMatrix;\n        // std::vector<Eigen::VectorXd> reducedAlleleIndex = I.ReducedAlleleIndex;\n        // std::vector<Eigen::VectorXd> reducedNoiseIndex = I.ReducedNoiseIndex;\n        //\n        // updateMarkerIndividual(surroundings[minIndex], reducedExpectedContributionMatrix, reducedAlleleIndex, reducedNoiseIndex, stepMarker, ES);\n\n        Individual K(surroundings[minIndex], ES); // K(surroundings[minIndex], reducedExpectedContributionMatrix, reducedAlleleIndex, reducedNoiseIndex, ES);\n        if (K.Fitness > I.Fitness)\n        {\n            I = K;\n        }\n    }\n}\n\nPopulation EvolutionaryAlgorithm::SelectionCrossoverMutation(const Population & P, ExperimentalSetup & ES, RandomVariates & RV)\n{\n    // Creating new child population\n    std::vector<Individual> childPopulation(PopulationSize);\n    for (std::size_t i = 0; i < PopulationSize; i++)\n    {\n        Individual parent = P.Individuals[i];\n\n        // Parent partner selection\n        std::size_t partnerIndex = ChoosePartner(P, i, RV);\n\n        // Crossover\n        Individual child = Crossover(parent, P.Individuals[partnerIndex], ES, RV);\n\n        // Mutation\n        Mutation(child, ES, RV);\n\n        if (AllowParentSurvival)\n        {\n            // Hill-climbing\n            if (HillClimbingIterations != 0)\n            {\n                HillClimbing(parent, ES, RV);\n                RestructingIndividual(parent, ES);\n            }\n\n            if (parent.Fitness < child.Fitness)\n            {\n                // Restructuring\n                RestructingIndividual(child, ES);\n                childPopulation[i] = child;\n            }\n            else\n            {\n                childPopulation[i] = parent;\n            }\n        }\n        else\n        {\n            // Hill-climbing\n            if (HillClimbingIterations != 0)\n            {\n                HillClimbing(child, ES, RV);\n            }\n\n            // Restructuring\n            RestructingIndividual(child, ES);\n            childPopulation[i] = child;\n        }\n\n\n    }\n\n    Population C(childPopulation);\n    return C;\n}\n\nbool individualsEqual(Individual & I, Individual & J)\n{\n    Eigen::VectorXd K = I.EncodedProfile - J.EncodedProfile;\n    return (K.sum() < 2e-16);\n}\n\nvoid EvolutionaryAlgorithm::Run(ExperimentalSetup & ES, RandomVariates & RV, const bool & trace)\n{\n    std::vector<Individual> TI(NumberOfFittestIndividuals);\n    std::vector<double> TF(NumberOfFittestIndividuals, -HUGE_VAL);\n\n    std::size_t n = 0;\n    std::size_t terminationCounter = 0;\n    bool terminate = false;\n    while (!terminate)\n    {\n        // Updating current population\n        MutationDecay_t = MutationDecay[n];\n\n        Population C = SelectionCrossoverMutation(CurrentPopulation, ES, RV);\n        CurrentPopulation = C;\n\n        // Updating the list of fittest individuals\n        std::vector<int> sortedFitness = sortedIndex(C.Fitness);\n\n        std::size_t m = 0;\n        bool updateFittest = true;\n        while (updateFittest)\n        {\n            Individual I_m = C.Individuals[sortedFitness[m]];\n\n            double F_m = I_m.Fitness;\n            if (F_m > TF[0])\n            {\n                auto it_front = std::lower_bound(TF.cbegin(), TF.cend(), F_m);\n                auto it_end = std::upper_bound(TF.cbegin(), TF.cend(), F_m);\n                std::size_t i = it_front - TF.cbegin();\n                std::size_t j = it_end - TF.cbegin();\n\n                bool isDuplicate = false;\n                if (F_m == TF[j - 1]) {\n                    for (std::size_t k = i - 1; k < j; k++)\n                    {\n                        Eigen::VectorXd K = I_m.EncodedProfile - TI[k].EncodedProfile;\n                        double sumAbs = 0.0;\n                        for (std::size_t h = 0; h < K.size(); h++) {\n                            sumAbs += std::abs(K[h]);\n                        }\n\n                        isDuplicate = (sumAbs < 2e-16);\n                    }\n                }\n\n                if (!isDuplicate)\n                {\n                    for (std::size_t k = 0; k < j - 1; k++)\n                    {\n                        TI[k] = TI[k + 1];\n                        TF[k] = TF[k + 1];\n                    }\n\n                    TI[j - 1] = I_m;\n                    TF[j - 1] = F_m;\n                }\n            }\n\n            m++;\n            updateFittest = (m < NumberOfFittestIndividuals) & (F_m > TF[0]);\n        }\n\n        // Updates the termination counter\n        if (std::abs(C.Fitness[sortedFitness[0]] - C.Fitness.mean()) / std::abs(C.Fitness[sortedFitness[0]]) < ES.Tolerance[0])\n        {\n            terminationCounter++;\n        }\n        else\n        {\n            terminationCounter = 0;\n        }\n\n        n++;\n        terminate = (terminationCounter >= NumberOfIterationsEqualMinMax) || (n >= NumberOfIterations);\n\n        if (trace)\n        {\n            Rcpp::Rcout << \"\\tCurrent iteration: \" << n << \"\\n\"\n                        << \"\\t\\tPopulation Fitness: \" << \"\\n\"\n                        << \"\\t\\t  Highest: \" << C.Fitness[sortedFitness[0]] << \"\\n\"\n                        << \"\\t\\t  Average: \" << C.Fitness.mean() << \"\\n\"\n                        << \"\\t\\t  Lowest: \" << C.Fitness[sortedFitness[sortedFitness.size() - 1]] << \"\\n\"\n                        << \"\\t\\tTermination counter: \" << terminationCounter << \" / \" << NumberOfIterationsEqualMinMax << \"\\n\";\n        }\n    }\n\n    Population FittestMembers(TI);\n    FittestMembersOfEntireRun = FittestMembers;\n}\n", "meta": {"hexsha": "7e8c3bd32a6a611afe63ce328b8b32aace9f6a33", "size": 26546, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/evolutionaryAlgorithm.cpp", "max_stars_repo_name": "svilsen/MPSMixtures", "max_stars_repo_head_hexsha": "07b21c593bee795162f6282446ff370985ceec38", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/evolutionaryAlgorithm.cpp", "max_issues_repo_name": "svilsen/MPSMixtures", "max_issues_repo_head_hexsha": "07b21c593bee795162f6282446ff370985ceec38", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/evolutionaryAlgorithm.cpp", "max_forks_repo_name": "svilsen/MPSMixtures", "max_forks_repo_head_hexsha": "07b21c593bee795162f6282446ff370985ceec38", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.5282442748, "max_line_length": 180, "alphanum_fraction": 0.6279665486, "num_tokens": 6220, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6113819732941511, "lm_q2_score": 0.4960938294709195, "lm_q1q2_score": 0.3033028244009829}}
{"text": "/******************************************************************************\n * Copyright (C) 2013 by Jerome Maye                                          *\n * jerome.maye@gmail.com                                                      *\n *                                                                            *\n * This program is free software; you can redistribute it and/or modify       *\n * it under the terms of the Lesser 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 * Lesser GNU General Public License for more details.                        *\n *                                                                            *\n * You should have received a copy of the Lesser GNU General Public License   *\n * along with this program. If not, see <http://www.gnu.org/licenses/>.       *\n ******************************************************************************/\n\n#include \"aslam/calibration/error-terms/ErrorTermAngularVelocity.h\"\n\n#include <Eigen/Dense>\n\nusing namespace aslam::backend;\n\nnamespace aslam {\n  namespace calibration {\n\n/******************************************************************************/\n/* Constructors and Destructor                                                */\n/******************************************************************************/\n\n  ErrorTermAngularVelocity::ErrorTermAngularVelocity(const aslam::backend::EuclideanExpression& r_w_mr,\n                                                     const aslam::backend::EuclideanExpression& r_w_mr_m,\n                                                     const Covariance& sigma2_ang_velZ) :\n        _r_w_mr(r_w_mr),\n        _r_w_mr_m(r_w_mr_m),\n        _sigma2_ang_velZ(sigma2_ang_velZ) {\n      setInvR(_sigma2_ang_velZ.inverse());\n      DesignVariable::set_t dv;\n      _r_w_mr.getDesignVariables(dv);\n      _r_w_mr_m.getDesignVariables(dv);\n      setDesignVariablesIterator(dv.begin(), dv.end());\n    }\n\n  ErrorTermAngularVelocity::ErrorTermAngularVelocity(const ErrorTermAngularVelocity& other) :\n        ErrorTermFs<1>(other),\n        _r_w_mr(other. _r_w_mr),\n        _r_w_mr_m(other. _r_w_mr_m),\n        _sigma2_ang_velZ(other._sigma2_ang_velZ){\n    }\n\n  ErrorTermAngularVelocity& ErrorTermAngularVelocity::operator =\n        (const ErrorTermAngularVelocity& other) {\n      if (this != &other) {\n        ErrorTermFs<1>::operator=(other);\n        _r_w_mr = other._r_w_mr;\n        _r_w_mr_m = other._r_w_mr_m;\n       _sigma2_ang_velZ = other._sigma2_ang_velZ;\n      }\n      return *this;\n    }\n\n    ErrorTermAngularVelocity::~ErrorTermAngularVelocity() {\n    }\n\n/******************************************************************************/\n/* Methods                                                                    */\n/******************************************************************************/\n\n    double ErrorTermAngularVelocity::evaluateErrorImplementation() {\n      error_t error;\n      const double wz = _r_w_mr.toEuclidean()(2);\n      const double wzm = _r_w_mr_m.toEuclidean()(2);\n\n      error(0) = wz - wzm;\n\n      setError(error);\n      return evaluateChiSquaredError();\n    }\n\n    void ErrorTermAngularVelocity::evaluateJacobiansImplementation(JacobianContainer&\n        jacobians) {\n      Eigen::Matrix<double, 1, 3> Jw = Eigen::Matrix<double, 1, 3>::Zero();\n      Eigen::Matrix<double, 1, 3> Jwm = Eigen::Matrix<double, 1, 3>::Zero();\n\n\n      Jw(2) = 1.0;\n      Jwm(2) = 1.0;\n\n      _r_w_mr.evaluateJacobians(jacobians, Jw);\n      _r_w_mr_m.evaluateJacobians(jacobians, -Jwm);\n    }\n\n  }\n}\n", "meta": {"hexsha": "7eb560173350e5f8e9ebec9a4258b7320a09c23c", "size": 4001, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "oomact/src/error-terms/ErrorTermAngularVelocity.cpp", "max_stars_repo_name": "OnyxBlack7/oomact", "max_stars_repo_head_hexsha": "5ae5fbbaddaf58e2fc24adaabedf711619934ac9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 21.0, "max_stars_repo_stars_event_min_datetime": "2017-06-19T13:57:59.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-20T02:40:58.000Z", "max_issues_repo_path": "oomact/src/error-terms/ErrorTermAngularVelocity.cpp", "max_issues_repo_name": "OnyxBlack7/oomact", "max_issues_repo_head_hexsha": "5ae5fbbaddaf58e2fc24adaabedf711619934ac9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 19.0, "max_issues_repo_issues_event_min_datetime": "2017-05-10T09:11:25.000Z", "max_issues_repo_issues_event_max_datetime": "2019-03-11T16:41:36.000Z", "max_forks_repo_path": "oomact/src/error-terms/ErrorTermAngularVelocity.cpp", "max_forks_repo_name": "OnyxBlack7/oomact", "max_forks_repo_head_hexsha": "5ae5fbbaddaf58e2fc24adaabedf711619934ac9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 11.0, "max_forks_repo_forks_event_min_datetime": "2017-06-19T13:39:12.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-16T19:53:27.000Z", "avg_line_length": 41.6770833333, "max_line_length": 105, "alphanum_fraction": 0.4931267183, "num_tokens": 773, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.611381973294151, "lm_q2_score": 0.49609382947091946, "lm_q1q2_score": 0.3033028244009828}}
{"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 _ABSTRACTLINEARELLIPTICPDE_HPP_\n#define _ABSTRACTLINEARELLIPTICPDE_HPP_\n\n#include \"ChasteSerialization.hpp\"\n#include <boost/serialization/base_object.hpp>\n\n#include \"AbstractLinearPde.hpp\"\n#include \"UblasCustomFunctions.hpp\"\n#include \"ChastePoint.hpp\"\n#include \"Node.hpp\"\n#include \"Element.hpp\"\n#include <petscvec.h>\n\n/**\n * AbstractLinearEllipticPde class.\n *\n * A general PDE of the form:\n * 0 =   Grad.(DiffusionTerm(x)*Grad(u))\n *     + ComputeConstantInUSourceTerm(x)\n *     + ComputeLinearInUCoeffInSourceTerm(x, u)\n *\n * Parabolic PDEs are be derived from this (AbstractLinearParabolicPde)\n */\ntemplate <unsigned ELEMENT_DIM, unsigned SPACE_DIM>\nclass AbstractLinearEllipticPde : public AbstractLinearPde<ELEMENT_DIM, SPACE_DIM>\n{\nprivate:\n\n    /** Needed for serialization. */\n    friend class boost::serialization::access;\n    /**\n     * Serialize the PDE object.\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<AbstractLinearPde<ELEMENT_DIM, SPACE_DIM> >(*this);\n    }\n\npublic:\n\n    /**\n     * Constructor.\n     */\n    AbstractLinearEllipticPde()\n        : AbstractLinearPde<ELEMENT_DIM, SPACE_DIM>()\n    {}\n\n    /**\n     * Destructor.\n     */\n    virtual ~AbstractLinearEllipticPde()\n    {}\n\n    /**\n     * @return computed constant in u part of the source term, i.e g(x) in\n     * Div(D Grad u)  +  f(x)u + g(x) = 0, at a given point.\n     *\n     * @param rX The point in space\n     * @param pElement The element\n     */\n    virtual double ComputeConstantInUSourceTerm(const ChastePoint<SPACE_DIM>& rX,\n                                                Element<ELEMENT_DIM,SPACE_DIM>* pElement)=0;\n\n    /**\n     * @return computed 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, at a given point in space.\n     *\n     * @param rX The point in space\n     * @param pElement\n     */\n    virtual double ComputeLinearInUCoeffInSourceTerm(const ChastePoint<SPACE_DIM>& rX,\n                                                     Element<ELEMENT_DIM,SPACE_DIM>* pElement)=0;\n\n    /**\n     * @return computed diffusion term at a given point. The diffusion tensor should be symmetric and positive definite\n     *\n     * @param rX The point in space at which the diffusion term is computed.\n     * @return A matrix.\n     */\n    virtual c_matrix<double, SPACE_DIM, SPACE_DIM> ComputeDiffusionTerm(const ChastePoint<SPACE_DIM>& rX)=0;\n\n    /**\n     * @return computed constant in u part of the source term, i.e g(x) in\n     * Div(D Grad u)  +  f(x)u + g(x) = 0, at a given node.\n     *\n     * @param rNode the node\n     */\n    virtual double ComputeConstantInUSourceTermAtNode(const Node<SPACE_DIM>& rNode);\n\n    /**\n     * @return computed 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, at a given node.\n     *\n     * @param rNode the node\n     */\n    virtual double ComputeLinearInUCoeffInSourceTermAtNode(const Node<SPACE_DIM>& rNode);\n};\n\ntemplate <unsigned ELEMENT_DIM, unsigned SPACE_DIM>\ndouble AbstractLinearEllipticPde<ELEMENT_DIM, SPACE_DIM>::ComputeConstantInUSourceTermAtNode(const Node<SPACE_DIM>& rNode)\n{\n    return ComputeConstantInUSourceTerm(rNode.GetPoint(), nullptr);\n}\n\ntemplate <unsigned ELEMENT_DIM, unsigned SPACE_DIM>\ndouble AbstractLinearEllipticPde<ELEMENT_DIM, SPACE_DIM>::ComputeLinearInUCoeffInSourceTermAtNode(const Node<SPACE_DIM>& rNode)\n{\n    return ComputeLinearInUCoeffInSourceTerm(rNode.GetPoint(), nullptr);\n}\n\n#endif //_ABSTRACTLINEARELLIPTICPDE_HPP_\n", "meta": {"hexsha": "10640b738ab5572e82c370685b4eb0d51a410d7f", "size": 5449, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "pde/src/problem/AbstractLinearEllipticPde.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": "pde/src/problem/AbstractLinearEllipticPde.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": "pde/src/problem/AbstractLinearEllipticPde.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.0860927152, "max_line_length": 127, "alphanum_fraction": 0.7160946963, "num_tokens": 1303, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.611381973294151, "lm_q2_score": 0.49609382947091946, "lm_q1q2_score": 0.3033028244009828}}
{"text": "/**\n *\n * RenderPipeline\n *\n * Copyright (c) 2014-2016 tobspr <tobias.springer1@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\n// Only include the pssm helper if actually required\n#ifdef RP_REQ_PSSM_HELPER\n\n#include \"pssm_helper.h\"\n\n#include <Eigen/Dense>\n\n/**\n * @brief Internal method to generate a set of equations\n * @details This generates a set of equations into a given equation system.\n *   Based on a given start point and end point, it inserts an equation to the\n *   system which will, when solved, solve the following equation:\n *   vec * <SOLVED-TRANSFORM> = expected\n *\n * @param eq_system The equation system\n * @param eq_results The target result vector of the equation system\n * @param vec The actual vector to be transformed\n * @param expected The expected output of the transformation\n * @param offset The index of the equation\n */\nvoid generate_equations(Eigen::MatrixXf &eq_system, Eigen::VectorXf &eq_results, const LVector4f &vec, LVector4f expected, size_t offset) {\n    size_t write_offset = offset * 4;\n    for (size_t row = 0; row < 4; ++row) {\n        float expected_coeff = expected.get_cell(row);\n        size_t col_offset = row * 4;\n        for (size_t col = 0; col < 4; ++col) {\n            eq_system(write_offset, col_offset + col) = vec.get_cell(col);\n        }\n        eq_results(write_offset++) = expected_coeff;\n    }\n}\n/**\n * @brief Finds a projection mat arround the given set of points.\n * @details This methods finds a projection matrix which projects the given set\n *   of frustum points to a unit cube, which can be used as a camera matrix.\n *   The eight points should determine the frustum uniquely.\n *\n *  @param near_ul The Upper-Left point of the frustum on the near plane\n *  @param near_ur The Upper-Right point of the frustum on the near plane\n *  @param near_ll The Lower-Left point of the frustum on the near plane\n *  @param near_lr The Lower-Right point of the frustum on the near plane\n *  @param far_ul The Upper-Left point of the frustum on the far plane\n *  @param far_ur The Upper-Right point of the frustum on the far plane\n *  @param far_ll The Lower-Left point of the frustum on the far plane\n *  @param far_lr The Lower-Right point of the frustum on the far plane\n *\n */\nLMatrix4f PSSMHelper::find_projection_mat(\n            const LVector4f &near_ul,\n            const LVector4f &near_ur,\n            const LVector4f &near_ll,\n            const LVector4f &near_lr,\n\n            const LVector4f &far_ul,\n            const LVector4f &far_ur,\n            const LVector4f &far_ll,\n            const LVector4f &far_lr) {\n\n    // We have 8*4 = 32 equations, which require 16 coefficients each\n    Eigen::MatrixXf equation_system(32, 16);\n    Eigen::VectorXf equation_results(32);\n    equation_system.fill(0);\n\n    // Generate the equations\n    size_t offset = 0;\n    generate_equations(equation_system, equation_results, near_ul, LVector4f(-1,  1, 0, 1), offset++);\n    generate_equations(equation_system, equation_results, near_ur, LVector4f( 1,  1, 0, 1), offset++);\n    generate_equations(equation_system, equation_results, near_ll, LVector4f(-1, -1, 0, 1), offset++);\n    generate_equations(equation_system, equation_results, near_lr, LVector4f( 1, -1, 0, 1), offset++);\n\n    generate_equations(equation_system, equation_results, far_ul,  LVector4f(-1,  1, 1, 1), offset++);\n    generate_equations(equation_system, equation_results, far_ur,  LVector4f( 1,  1, 1, 1), offset++);\n    generate_equations(equation_system, equation_results, far_ll,  LVector4f(-1, -1, 1, 1), offset++);\n    generate_equations(equation_system, equation_results, far_lr,  LVector4f( 1, -1, 1, 1), offset++);\n\n    // Solve the equation system\n    Eigen::VectorXf solved_system = equation_system.colPivHouseholderQr().solve(equation_results);\n\n    // Construct result matrix and return it. We also need to transpose the matrix.\n    LMatrix4f result(\n            solved_system(0), solved_system(4), solved_system(8),  solved_system(12),\n            solved_system(1), solved_system(5), solved_system(9),  solved_system(13),\n            solved_system(2), solved_system(6), solved_system(10), solved_system(14),\n            solved_system(3), solved_system(7), solved_system(11), solved_system(15)\n        );\n    return result;\n}\n\n\n#endif // RP_REQ_PSSM_HELPER\n", "meta": {"hexsha": "df0ea3548122753b47746b6252df611b38868ca1", "size": 5340, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "rpcore/native/source/pssm_helper.cpp", "max_stars_repo_name": "bluekyu/RenderPipeline", "max_stars_repo_head_hexsha": "8e0212d88a138de59f08fe9d6dce148227cf8216", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1031.0, "max_stars_repo_stars_event_min_datetime": "2015-01-06T08:51:29.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T20:10:43.000Z", "max_issues_repo_path": "rpcore/native/source/pssm_helper.cpp", "max_issues_repo_name": "bluekyu/RenderPipeline", "max_issues_repo_head_hexsha": "8e0212d88a138de59f08fe9d6dce148227cf8216", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 101.0, "max_issues_repo_issues_event_min_datetime": "2015-02-24T01:30:43.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-03T11:11:06.000Z", "max_forks_repo_path": "rpcore/native/source/pssm_helper.cpp", "max_forks_repo_name": "bluekyu/RenderPipeline", "max_forks_repo_head_hexsha": "8e0212d88a138de59f08fe9d6dce148227cf8216", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 180.0, "max_forks_repo_forks_event_min_datetime": "2015-01-01T22:47:25.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-03T17:23:19.000Z", "avg_line_length": 45.641025641, "max_line_length": 139, "alphanum_fraction": 0.7134831461, "num_tokens": 1386, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6261241772283034, "lm_q2_score": 0.4843800842769843, "lm_q1q2_score": 0.3032820817337031}}
{"text": "/**\n * @file\n * This file is part of SeisSol.\n *\n * @author Sebastian Wolf (wolf.sebastian AT tum.de, https://www5.in.tum.de/wiki/index.php/Sebastian_Wolf,_M.Sc.)\n * @section LICENSE\n * Copyright (c) 2019 - 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#ifndef MODEL_ANISOTROPIC_DATASTRUCTURES_H_\n#define MODEL_ANISOTROPIC_DATASTRUCTURES_H_\n\n#include <Model/common_datastructures.hpp>\n#include <Equations/elastic/Model/datastructures.hpp>\n#include <Eigen/Eigen>\n#include <Eigen/Eigenvalues>\n#include <generated_code/init.h>\n#include <generated_code/tensor.h>\n#include <generated_code/kernel.h>\n\nnamespace seissol {\n  namespace model {\n    struct AnisotropicMaterial : Material {\n      double c11;\n      double c12;\n      double c13;\n      double c14;\n      double c15;\n      double c16;\n      double c22;\n      double c23;\n      double c24;\n      double c25;\n      double c26;\n      double c33;\n      double c34;\n      double c35;\n      double c36;\n      double c44;\n      double c45;\n      double c46;\n      double c55;\n      double c56;\n      double c66;\n\n      AnisotropicMaterial() {}\n\n      explicit AnisotropicMaterial(ElasticMaterial m) {\n        rho = m.rho;\n        c11 = m.lambda + 2*m.mu;\n        c12 = m.lambda;\n        c13 = m.lambda;\n        c14 = 0;\n        c15 = 0;\n        c16 = 0; \n        c22 = m.lambda + 2*m.mu;\n        c23 = m.lambda;\n        c24 = 0;\n        c25 = 0;\n        c26 = 0;\n        c33 = m.lambda + 2*m.mu;\n        c34 = 0;\n        c35 = 0;\n        c36 = 0;\n        c44 = m.mu; \n        c45 = 0;\n        c46 = 0;\n        c55 = m.mu; \n        c56 = 0; \n        c66 = m.mu; \n      }\n\n      AnisotropicMaterial( double* materialValues, int numMaterialValues)\n      {\n        assert(numMaterialValues == 22);\n\n        this->rho = materialValues[0];\n        this->c11 = materialValues[1];\n        this->c12 = materialValues[2];\n        this->c13 = materialValues[3];\n        this->c14 = materialValues[4];\n        this->c15 = materialValues[5];\n        this->c16 = materialValues[6];\n        this->c22 = materialValues[7];\n        this->c23 = materialValues[8];\n        this->c24 = materialValues[9];\n        this->c25 = materialValues[10];\n        this->c26 = materialValues[11];\n        this->c33 = materialValues[12];\n        this->c34 = materialValues[13];\n        this->c35 = materialValues[14];\n        this->c36 = materialValues[15];\n        this->c44 = materialValues[16];\n        this->c45 = materialValues[17];\n        this->c46 = materialValues[18];\n        this->c55 = materialValues[19];\n        this->c56 = materialValues[20];\n        this->c66 = materialValues[21];\n      }\n\n      virtual ~AnisotropicMaterial() {};\n\n      \n      void getFullStiffnessTensor(std::array<real, 81>& fullTensor) const final {\n        auto stiffnessTensorView = init::stiffnessTensor::view::create(fullTensor.data());\n        stiffnessTensorView.setZero();\n        stiffnessTensorView(0,0,0,0) = c11;\n        stiffnessTensorView(0,0,0,1) = c16;\n        stiffnessTensorView(0,0,0,2) = c15;\n        stiffnessTensorView(0,0,1,0) = c16;\n        stiffnessTensorView(0,0,1,1) = c12;\n        stiffnessTensorView(0,0,1,2) = c14;\n        stiffnessTensorView(0,0,2,0) = c15;\n        stiffnessTensorView(0,0,2,1) = c14;\n        stiffnessTensorView(0,0,2,2) = c13;\n        stiffnessTensorView(0,1,0,0) = c16;\n        stiffnessTensorView(0,1,0,1) = c66;\n        stiffnessTensorView(0,1,0,2) = c56;\n        stiffnessTensorView(0,1,1,0) = c66;\n        stiffnessTensorView(0,1,1,1) = c26;\n        stiffnessTensorView(0,1,1,2) = c46;\n        stiffnessTensorView(0,1,2,0) = c56;\n        stiffnessTensorView(0,1,2,1) = c46;\n        stiffnessTensorView(0,1,2,2) = c36;\n        stiffnessTensorView(0,2,0,0) = c15;\n        stiffnessTensorView(0,2,0,1) = c56;\n        stiffnessTensorView(0,2,0,2) = c55;\n        stiffnessTensorView(0,2,1,0) = c56;\n        stiffnessTensorView(0,2,1,1) = c25;\n        stiffnessTensorView(0,2,1,2) = c45;\n        stiffnessTensorView(0,2,2,0) = c55;\n        stiffnessTensorView(0,2,2,1) = c45;\n        stiffnessTensorView(0,2,2,2) = c35;\n        stiffnessTensorView(1,0,0,0) = c16;\n        stiffnessTensorView(1,0,0,1) = c66;\n        stiffnessTensorView(1,0,0,2) = c56;\n        stiffnessTensorView(1,0,1,0) = c66;\n        stiffnessTensorView(1,0,1,1) = c26;\n        stiffnessTensorView(1,0,1,2) = c46;\n        stiffnessTensorView(1,0,2,0) = c56;\n        stiffnessTensorView(1,0,2,1) = c46;\n        stiffnessTensorView(1,0,2,2) = c36;\n        stiffnessTensorView(1,1,0,0) = c12;\n        stiffnessTensorView(1,1,0,1) = c26;\n        stiffnessTensorView(1,1,0,2) = c25;\n        stiffnessTensorView(1,1,1,0) = c26;\n        stiffnessTensorView(1,1,1,1) = c22;\n        stiffnessTensorView(1,1,1,2) = c24;\n        stiffnessTensorView(1,1,2,0) = c25;\n        stiffnessTensorView(1,1,2,1) = c24;\n        stiffnessTensorView(1,1,2,2) = c23;\n        stiffnessTensorView(1,2,0,0) = c14;\n        stiffnessTensorView(1,2,0,1) = c46;\n        stiffnessTensorView(1,2,0,2) = c45;\n        stiffnessTensorView(1,2,1,0) = c46;\n        stiffnessTensorView(1,2,1,1) = c24;\n        stiffnessTensorView(1,2,1,2) = c44;\n        stiffnessTensorView(1,2,2,0) = c45;\n        stiffnessTensorView(1,2,2,1) = c44;\n        stiffnessTensorView(1,2,2,2) = c34;\n        stiffnessTensorView(2,0,0,0) = c15;\n        stiffnessTensorView(2,0,0,1) = c56;\n        stiffnessTensorView(2,0,0,2) = c55;\n        stiffnessTensorView(2,0,1,0) = c56;\n        stiffnessTensorView(2,0,1,1) = c25;\n        stiffnessTensorView(2,0,1,2) = c45;\n        stiffnessTensorView(2,0,2,0) = c55;\n        stiffnessTensorView(2,0,2,1) = c45;\n        stiffnessTensorView(2,0,2,2) = c35;\n        stiffnessTensorView(2,1,0,0) = c14;\n        stiffnessTensorView(2,1,0,1) = c46;\n        stiffnessTensorView(2,1,0,2) = c45;\n        stiffnessTensorView(2,1,1,0) = c46;\n        stiffnessTensorView(2,1,1,1) = c24;\n        stiffnessTensorView(2,1,1,2) = c44;\n        stiffnessTensorView(2,1,2,0) = c45;\n        stiffnessTensorView(2,1,2,1) = c44;\n        stiffnessTensorView(2,1,2,2) = c34;\n        stiffnessTensorView(2,2,0,0) = c13;\n        stiffnessTensorView(2,2,0,1) = c36;\n        stiffnessTensorView(2,2,0,2) = c35;\n        stiffnessTensorView(2,2,1,0) = c36;\n        stiffnessTensorView(2,2,1,1) = c23;\n        stiffnessTensorView(2,2,1,2) = c34;\n        stiffnessTensorView(2,2,2,0) = c35;\n        stiffnessTensorView(2,2,2,1) = c34;\n        stiffnessTensorView(2,2,2,2) = c33;\n      }\n\n      //calculate maximal wave speed\n      //Wavespeeds for anisotropic materials depend on the direction of propagation.\n      //An analytic solution for the maximal wave speed is hard to obtain.\n      //Instead of solving an optimization problem we sample the velocitiy for\n      //different directions and take the maximum.\n      double getMaxWaveSpeed() const final{\n        auto samplingDirections = init::samplingDirections::view::create(const_cast<real*>(init::samplingDirections::Values));\n\n        Eigen::SelfAdjointEigenSolver<Eigen::Matrix<double, 3, 3>> saes;\n\n        double maxEv = 0;\n\n        std::array<real, 81> fullTensor;\n        getFullStiffnessTensor(fullTensor);\n        kernel::computeChristoffel computeChristoffel;\n        computeChristoffel.stiffnessTensor = fullTensor.data();\n\n        for(unsigned j = 0; j < 200; ++j)\n        {\n          real n[3] = { samplingDirections(j, 0),\n                        samplingDirections(j, 1),\n                        samplingDirections(j, 2)\n          };\n          real M[9];\n          computeChristoffel.direction = n;\n          computeChristoffel.christoffel = M;\n          computeChristoffel.execute();\n\n          saes.compute(Eigen::Matrix<real, 3, 3>(M).cast<double>());\n          auto eigenvalues = saes.eigenvalues();\n          for(unsigned i = 0; i < 3; ++i) {\n            maxEv = std::max(eigenvalues(i), maxEv);\n          }\n        }\n        return sqrt(maxEv / rho);\n      }\n\n      //calculate P-wave speed based on averaged material parameters\n      double getPWaveSpeed() const final {\n        double muBar = (c44 + c55 + c66) / 3.0;\n        double lambdaBar = (c11 + c22 + c33) / 3.0 - 2.0*muBar;\n        return std::sqrt((lambdaBar + 2*muBar) / rho);\n      }\n\n      //calculate S-wave speed based on averaged material parameters\n      double getSWaveSpeed() const final {\n        double muBar = (c44 + c55 + c66) / 3.0;\n        return std::sqrt(muBar / rho);\n      }\n\n      MaterialType getMaterialType() const {\n        return MaterialType::anisotropic;\n      }\n    };\n\n\n  }\n}\n\n#endif\n", "meta": {"hexsha": "0286f791f5e99407e64b9ff7223bf979626f9062", "size": 10070, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/Equations/anisotropic/Model/datastructures.hpp", "max_stars_repo_name": "fabian-kutschera/SeisSol", "max_stars_repo_head_hexsha": "d5656cd38e9eb1d91c05ebcbf173acbc3083da57", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 165.0, "max_stars_repo_stars_event_min_datetime": "2015-01-30T18:19:05.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T17:22:14.000Z", "max_issues_repo_path": "src/Equations/anisotropic/Model/datastructures.hpp", "max_issues_repo_name": "fabian-kutschera/SeisSol", "max_issues_repo_head_hexsha": "d5656cd38e9eb1d91c05ebcbf173acbc3083da57", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 351.0, "max_issues_repo_issues_event_min_datetime": "2015-10-06T15:06:48.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T11:23:13.000Z", "max_forks_repo_path": "src/Equations/anisotropic/Model/datastructures.hpp", "max_forks_repo_name": "fabian-kutschera/SeisSol", "max_forks_repo_head_hexsha": "d5656cd38e9eb1d91c05ebcbf173acbc3083da57", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 96.0, "max_forks_repo_forks_event_min_datetime": "2015-07-27T15:13:33.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-25T19:19:32.000Z", "avg_line_length": 36.0931899642, "max_line_length": 126, "alphanum_fraction": 0.6161866931, "num_tokens": 3010, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6926419831347361, "lm_q2_score": 0.43782349911420193, "lm_q1q2_score": 0.3032549366894502}}
{"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\nNumericMatrix lpoly_sde(nlopt_stepper &stepper\n\t\t\t, NumericVector start\n\t\t\t, double from, double to, int steps \n\t\t\t, double x_tol\n\t\t\t, const char* algorithm) {\n\n  const double dt = (to - from)/steps;\n  vector<double> state = as<vector<double> >(start);\n  NumericMatrix result(steps+1, start.size());\n\n  for(int j = 0; j < start.size(); ++j){\n    result(0, j) = state[j];\n  }\n\n  for(int i = 1; i <= steps; ++i) {\n    stepper.do_step(state, (i-1)*dt);\n    for(int j = 0; j < start.size(); ++j){\n      result(i, j) = state[j];\n    }\n  }\n\n  return result;\n}\n", "meta": {"hexsha": "dcb2842e92b3014485bc2b742a62f0fa3ebcde38", "size": 2536, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/lpoly_sde.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_sde.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_sde.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": 33.8133333333, "max_line_length": 83, "alphanum_fraction": 0.7231861199, "num_tokens": 589, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5506073802837477, "lm_q2_score": 0.5506073655352404, "lm_q1q2_score": 0.30316847910229455}}
{"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_MATH_RANDOM_HPP_\n#define DART_MATH_RANDOM_HPP_\n\n#include <random>\n\n#include <Eigen/Core>\n\n#ifdef DART_USE_ARBITRARY_PRECISION\n#include \"mpreal.h\"\n#endif\n\nnamespace dart {\nnamespace math {\n\nclass Random final\n{\npublic:\n  using GeneratorType = std::mt19937;\n\n  template <typename FloatType>\n  using UniformRealDist = std::uniform_real_distribution<FloatType>;\n\n  template <typename IntType>\n  using UniformIntDist = std::uniform_int_distribution<IntType>;\n\n  template <typename FloatType>\n  using NormalRealDist = std::normal_distribution<FloatType>;\n\n  /// Returns a mutable reference to the random generator\n  static GeneratorType& getGenerator();\n\n  /// Sets the seed value.\n  ///\n  /// The same seed gives the same sequence of random values so that you can\n  /// regenerate the same sequencial random values as long as you knot the seed\n  /// value.\n  static void setSeed(unsigned int seed);\n\n  /// Generates a seed value using the default random device.\n  ///\n  /// \\param[in] applyGeneratedSeed Whether to apply the generated seed.\n  /// \\return The new seed value.\n  static unsigned int generateSeed(bool applyGeneratedSeed = false);\n\n  /// \\return The current seed value.\n  static unsigned int getSeed();\n\n  /// Returns a random number from an uniform distribution.\n  ///\n  ///\n  /// This template function can generate different scalar types of random\n  /// numbers as:\n  /// - Floating-point number: \\c float, \\c s_t, \\c long s_t\n  /// - Integer number: [\\c unsigned] \\c short, [\\c unsigned] \\c int,\n  ///   [\\c unsigned] \\c long, [\\c unsigned] \\c long \\c long\n  ///\n  /// and vectors and matrices as:\n  /// - Fixed-size: Eigen::Vector3i, Eigen::Vector3s, Eigen::Matrix4d, and so\n  ///   on.\n  /// - Dynamic-size: Eigen::VectorXi, Eigen::VectorXs, Eigen::MatrixXs, and so\n  ///   on.\n  ///\n  /// Example:\n  /// \\code\n  /// // Generate a random int in [0, 10]\n  /// int intVal1 = Random::uniform(0, 10);\n  /// int intVal2 = Random::uniform<int>(0, 10);\n  ///\n  /// // Generate a random s_t in [0.0, 10.0)\n  /// s_t dblVal1 = Random::uniform(0.0, 10.0);\n  /// s_t dblVal2 = Random::uniform<s_t>(0, 10);\n  ///\n  /// // Generate a random vector in [lb, ub)\n  /// Eigen::Vector3s lb = Eigen::Vector3s::Constant(1);\n  /// Eigen::Vector3s ub = Eigen::Vector3s::Constant(4);\n  /// Eigen::Vector3s vecVal1 = Random::uniform(lb, ub);\n  /// Eigen::Vector3s vecVal2 = Random::uniform<Eigen::Vector3s>(lb, ub);\n  ///\n  /// // Generate a random matrix in [lb, ub)\n  /// Eigen::Matrix4f lb = Eigen::Matrix4f::Constant(1);\n  /// Eigen::Matrix4f ub = Eigen::Matrix4f::Constant(4);\n  /// Eigen::Matrix4f vecVal1 = Random::uniform(lb, ub);\n  /// Eigen::Matrix4f vecVal2 = Random::uniform<Eigen::Matrix4f>(lb, ub);\n  /// \\endcode\n  ///\n  /// Note that the end of the range is closed for integer types (i.e.,\n  /// [int_min, int_max]), but open for floating-point types (i.e., [float_min,\n  /// float_max)).\n  ///\n  /// \\tparam S The type of random value.\n  /// \\param[in] min Lower bound of the distribution.\n  /// \\param[in] max Upper bound of the distribution.\n  ///\n  /// \\sa normal()\n  template <typename S>\n  static S uniform(S min, S max);\n\n  /// Returns a random vector or matrix from an uniform distribution.\n  ///\n  /// This is a helper function for the case that the each of lower and upper\n  /// bound has an uniform element value in it. For example, the lower bound is\n  /// [1, 1, 1] or [-2, -2].\n  ///\n  /// This variant is meant to be used for fixed-size vector or matrix types.\n  /// For dynamic-size types, please use other variants that takes the size of\n  /// vector or matrix.\n  ///\n  /// Example:\n  /// \\code\n  /// // Generate random vectors\n  /// Eigen::VectorXi vecXi = Random::uniform<Eigen::VectorXi>(0, 10);\n  /// Eigen::VectorXs vecXd = Random::uniform<Eigen::VectorXs>(0.0, 10.0);\n  /// \\endcode\n  ///\n  /// \\tparam FixedSizeT The type of fixed-size vector or fixed-size matrix.\n  /// \\param[in] min The constant value of the lower bound.\n  /// \\param[in] max The constant value of the upper bound.\n  ///\n  /// \\sa uniform()\n  template <typename FixedSizeT>\n  static FixedSizeT uniform(\n      typename FixedSizeT::Scalar min, typename FixedSizeT::Scalar max);\n\n  /// Returns a random vector from an uniform distribution.\n  ///\n  /// This variant is meant to be used for dynamic-size vector.\n  ///\n  /// Example:\n  /// \\code\n  /// // Generate random matrices\n  /// Eigen::MatrixXi matXi = Random::uniform<Eigen::MatrixXi>(0, 10);\n  /// Eigen::MatrixXs matXd = Random::uniform<Eigen::MatrixXs>(0.0, 10.0);\n  /// \\endcode\n  ///\n  /// \\tparam DynamicSizeVectorT The type of dynamic-size vector.\n  /// \\param[in] size The size of the vectors.\n  /// \\param[in] min The constant value of the lower bound vector.\n  /// \\param[in] max The constant value of the upper bound vector.\n  template <typename DynamicSizeVectorT>\n  static DynamicSizeVectorT uniform(\n      int size,\n      typename DynamicSizeVectorT::Scalar min,\n      typename DynamicSizeVectorT::Scalar max);\n\n  /// Returns a random matrix from an uniform distribution.\n  ///\n  /// This variant is meant to be used for dynamic-size matrix.\n  ///\n  /// \\tparam DynamicSizeMatrixT The type of dynamic-size matrix.\n  /// \\param[in] rows The row size of the matrices.\n  /// \\param[in] cols The col size of the matrices.\n  /// \\param[in] min The constant value of the lower bound matrix.\n  /// \\param[in] max The constant value of the upper bound matrix.\n  ///\n  /// \\sa uniform()\n  template <typename DynamicSizeMatrixT>\n  static DynamicSizeMatrixT uniform(\n      int rows,\n      int cols,\n      typename DynamicSizeMatrixT::Scalar min,\n      typename DynamicSizeMatrixT::Scalar max);\n\n  /// Returns a random number from a normal distribution.\n  ///\n  /// This template function can generate different scalar types of random\n  /// numbers as:\n  /// - Floating-point number: \\c float, \\c s_t, \\c long s_t\n  /// - Integer number: [\\c unsigned] \\c short, [\\c unsigned] \\c int,\n  ///   [\\c unsigned] \\c long, [\\c unsigned] \\c long \\c long\n  ///\n  /// Example:\n  /// \\code\n  /// // Generate a random int\n  /// int intVal = Random::normal(0, 10);\n  ///\n  /// // Generate a random s_t\n  /// s_t dblVal = Random::normal(0.0, 10.0);\n  /// \\endcode\n  ///\n  /// \\param[in] mean Mean of the normal distribution.\n  /// \\param[in] sigma Standard deviation of the distribution.\n  ///\n  /// \\sa uniform()\n  template <typename S>\n  static S normal(S mean, S sigma);\n\nprivate:\n  /// \\return A mutable reference to the seed.\n  static unsigned int& getSeedMutable();\n};\n\n} // namespace math\n} // namespace dart\n\n#include \"dart/math/detail/Random-impl.hpp\"\n\n#endif // DART_MATH_RANDOM_HPP_\n", "meta": {"hexsha": "4ae8e0e1a723d4ab5b8ebc83404567f216329da8", "size": 8263, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "dart/math/Random.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/math/Random.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/math/Random.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": 35.9260869565, "max_line_length": 79, "alphanum_fraction": 0.6777199564, "num_tokens": 2126, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.546738151984614, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.30315015734251366}}
{"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: lambertGridLatLong.cc,v $\n//       Version: $Revision: 1.1 $  Dated: $Date: 2012-01-04 00:33:41 $\n//\n//==============================================================================\n\n/**\n * @file lambertGridLatLong.cc\n *\n * Convert lat-longs cloud 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 \"LambertConfigReader.hh\"\n#include \"Proj4Wrap.hh\"\n#include \"writeBinary.hh\"\n\nusing boost::format;\nusing std::string;\nusing std::vector;\n\n// Functions\n\n\n\nvoid usage(char *programName)\n{\n  fprintf(stderr, \"Usage: %s configFile latFile lonFile\\n\", programName);\n}\n\n\nint main(int argc, char **argv)\n{\n  if (argc != 4)\n    {\n      usage(argv[0]);\n      exit(2);\n    }\n\n  LambertConfigReader cfg(argv[1]);\n  if (cfg.error != string(\"\"))\n    {\n      printf(\"Error: configuration file error %s\\n\", cfg.error.c_str());\n      return 1;\n    }\n\n  // Uses latitude where lambert conformal projection is true and\n  // median aligned with cartesian y-axis\n  string paramString = str(format(\"+proj=lcc +R=6371200 +lon_0=%1% +lat_0=%2% +lat_1=%3% +lat_2=%4%\") % cfg.lov % cfg.latin1 % cfg.latin1 % cfg.latin2);\n\n  p4w::Proj4Wrap lambertProj(paramString, p4w::Proj4Wrap::LON_LAT_TYPE, cfg.lo1, cfg.la1, cfg.dx, cfg.dy);\n  double xc;\n  double yc;\n  double lon;\n  double lat;\n  \n  vector<float> xvec;\n  vector<float> yvec;\n\n  for (int i=0; i<cfg.ny; i++)\n    {\n      for (int j=0; j<cfg.nx; j++)\n\t{\n\t  xc = j;\n\t  yc = i;\n\t  lambertProj.xy2ll(xc, yc, &lon, &lat);\n\t  xvec.push_back(lon);\n\t  yvec.push_back(lat);\n\t}\n    }\n\n  string error;\n  writeBinary(yvec, argv[2], error);\n  writeBinary(xvec, argv[3], error);\n}\n\n\n", "meta": {"hexsha": "73ef346b6d8351728e23aaadc50adc1c937cbf18", "size": 1997, "ext": "cc", "lang": "C++", "max_stars_repo_path": "libs/Proj4Wrap/src/Proj4Wrap/lambertGridLatLong.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/lambertGridLatLong.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/lambertGridLatLong.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": 22.1888888889, "max_line_length": 152, "alphanum_fraction": 0.5843765648, "num_tokens": 569, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5583269943353745, "lm_q2_score": 0.5428632831725052, "lm_q1q2_score": 0.3030952252287381}}
{"text": "// This file is part of libigl, a simple c++ geometry processing library.\r\n//\r\n// Copyright (C) 2014 Daniele Panozzo <daniele.panozzo@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\r\n#include \"nrosy.h\"\r\n\r\n#include <igl/copyleft/comiso/nrosy.h>\r\n#include <igl/triangle_triangle_adjacency.h>\r\n#include <igl/edge_topology.h>\r\n#include <igl/per_face_normals.h>\r\n\r\n#include <stdexcept>\r\n#include \"../../PI.h\"\r\n\r\n#include <Eigen/Geometry>\r\n#include <Eigen/Sparse>\r\n#include <queue>\r\n#include <vector>\r\n\r\n#include <gmm/gmm.h>\r\n#include <CoMISo/Solver/ConstrainedSolver.hh>\r\n#include <CoMISo/Solver/MISolver.hh>\r\n#include <CoMISo/Solver/GMM_Tools.hh>\r\n\r\nnamespace igl\r\n{\r\nnamespace copyleft\r\n{\r\n\r\nnamespace comiso\r\n{\r\nclass NRosyField\r\n{\r\npublic:\r\n  // Init\r\n  IGL_INLINE NRosyField(const Eigen::MatrixXd& _V, const Eigen::MatrixXi& _F);\r\n\r\n  // Generate the N-rosy field\r\n  // N degree of the rosy field\r\n  // round separately: round the integer variables one at a time, slower but higher quality\r\n  IGL_INLINE void solve(int N = 4);\r\n\r\n  // Set a hard constraint on fid\r\n  // fid: face id\r\n  // v: direction to fix (in 3d)\r\n  IGL_INLINE void setConstraintHard(int fid, const Eigen::Vector3d& v);\r\n\r\n  // Set a soft constraint on fid\r\n  // fid: face id\r\n  // w: weight of the soft constraint, clipped between 0 and 1\r\n  // v: direction to fix (in 3d)\r\n  IGL_INLINE void setConstraintSoft(int fid, double w, const Eigen::Vector3d& v);\r\n\r\n  // Set the ratio between smoothness and soft constraints (0 -> smoothness only, 1 -> soft constr only)\r\n  IGL_INLINE void setSoftAlpha(double alpha);\r\n\r\n  // Reset constraints (at least one constraint must be present or solve will fail)\r\n  IGL_INLINE void resetConstraints();\r\n\r\n  // Return the current field\r\n  IGL_INLINE Eigen::MatrixXd getFieldPerFace();\r\n\r\n  // Compute singularity indexes\r\n  IGL_INLINE void findCones(int N);\r\n\r\n  // Return the singularities\r\n  IGL_INLINE Eigen::VectorXd getSingularityIndexPerVertex();\r\n\r\nprivate:\r\n  // Compute angle differences between reference frames\r\n  IGL_INLINE void computek();\r\n\r\n  // Remove useless matchings\r\n  IGL_INLINE void reduceSpace();\r\n\r\n  // Prepare the system matrix\r\n  IGL_INLINE void prepareSystemMatrix(int N);\r\n\r\n  // Solve with roundings using CoMIso\r\n  IGL_INLINE void solveRoundings();\r\n\r\n  // Convert a vector in 3d to an angle wrt the local reference system\r\n  IGL_INLINE double convert3DtoLocal(unsigned fid, const Eigen::Vector3d& v);\r\n\r\n  // Convert an angle wrt the local reference system to a 3d vector\r\n  IGL_INLINE Eigen::Vector3d convertLocalto3D(unsigned fid, double a);\r\n\r\n  // Compute the per vertex angle defect\r\n  IGL_INLINE Eigen::VectorXd angleDefect();\r\n\r\n  // Temporary variable for the field\r\n  Eigen::VectorXd angles;\r\n\r\n  // Hard constraints\r\n  Eigen::VectorXd hard;\r\n  std::vector<bool> isHard;\r\n\r\n  // Soft constraints\r\n  Eigen::VectorXd soft;\r\n  Eigen::VectorXd wSoft;\r\n  double softAlpha;\r\n\r\n  // Face Topology\r\n  Eigen::MatrixXi TT, TTi;\r\n\r\n  // Edge Topology\r\n  Eigen::MatrixXi EV, FE, EF;\r\n  std::vector<bool> isBorderEdge;\r\n\r\n  // Per Edge information\r\n  // Angle between two reference frames\r\n  Eigen::VectorXd k;\r\n\r\n  // Jumps\r\n  Eigen::VectorXi p;\r\n  std::vector<bool> pFixed;\r\n\r\n  // Mesh\r\n  Eigen::MatrixXd V;\r\n  Eigen::MatrixXi F;\r\n\r\n  // Normals per face\r\n  Eigen::MatrixXd N;\r\n\r\n  // Singularity index\r\n  Eigen::VectorXd singularityIndex;\r\n\r\n  // Reference frame per triangle\r\n  std::vector<Eigen::MatrixXd> TPs;\r\n\r\n  // System stuff\r\n  Eigen::SparseMatrix<double> A;\r\n  Eigen::VectorXd b;\r\n  Eigen::VectorXi tag_t;\r\n  Eigen::VectorXi tag_p;\r\n\r\n};\r\n\r\n} // NAMESPACE COMISO\r\n} // NAMESPACE COPYLEFT\r\n} // NAMESPACE IGL\r\n\r\nigl::copyleft::comiso::NRosyField::NRosyField(const Eigen::MatrixXd& _V, const Eigen::MatrixXi& _F)\r\n{\r\n  V = _V;\r\n  F = _F;\r\n\r\n  assert(V.rows() > 0);\r\n  assert(F.rows() > 0);\r\n\r\n  // Generate topological relations\r\n  igl::triangle_triangle_adjacency(F,TT,TTi);\r\n  igl::edge_topology(V,F, EV, FE, EF);\r\n\r\n  // Flag border edges\r\n  isBorderEdge.resize(EV.rows());\r\n  for(unsigned i=0; i<EV.rows(); ++i)\r\n    isBorderEdge[i] = (EF(i,0) == -1) || ((EF(i,1) == -1));\r\n\r\n  // Generate normals per face\r\n  igl::per_face_normals(V, F, N);\r\n\r\n  // Generate reference frames\r\n  for(unsigned fid=0; fid<F.rows(); ++fid)\r\n  {\r\n    // First edge\r\n    Eigen::Vector3d e1 = V.row(F(fid,1)) - V.row(F(fid,0));\r\n    e1.normalize();\r\n    Eigen::Vector3d e2 = N.row(fid);\r\n    e2 = e2.cross(e1);\r\n    e2.normalize();\r\n\r\n    Eigen::MatrixXd TP(2,3);\r\n    TP << e1.transpose(), e2.transpose();\r\n    TPs.push_back(TP);\r\n  }\r\n\r\n  // Alloc internal variables\r\n  angles = Eigen::VectorXd::Zero(F.rows());\r\n  p = Eigen::VectorXi::Zero(EV.rows());\r\n  pFixed.resize(EV.rows());\r\n  k = Eigen::VectorXd::Zero(EV.rows());\r\n  singularityIndex = Eigen::VectorXd::Zero(V.rows());\r\n\r\n  // Reset the constraints\r\n  resetConstraints();\r\n\r\n  // Compute k, differences between reference frames\r\n  computek();\r\n  softAlpha = 0.5;\r\n}\r\n\r\nvoid igl::copyleft::comiso::NRosyField::setSoftAlpha(double alpha)\r\n{\r\n  assert(alpha >= 0 && alpha < 1);\r\n  softAlpha = alpha;\r\n}\r\n\r\n\r\nvoid igl::copyleft::comiso::NRosyField::prepareSystemMatrix(const int N)\r\n{\r\n  double Nd = N;\r\n\r\n  // Minimize the MIQ energy\r\n  // Energy on edge ij is\r\n  //     (t_i - t_j + kij + pij*(2*pi/N))^2\r\n  // Partial derivatives:\r\n  //   t_i: 2     ( t_i - t_j + kij + pij*(2*pi/N)) = 0\r\n  //   t_j: 2     (-t_i + t_j - kij - pij*(2*pi/N)) = 0\r\n  //   pij: 4pi/N ( t_i - t_j + kij + pij*(2*pi/N)) = 0\r\n  //\r\n  //          t_i      t_j         pij       kij\r\n  // t_i [     2       -2           4pi/N      2    ]\r\n  // t_j [    -2        2          -4pi/N     -2    ]\r\n  // pij [   4pi/N   -4pi/N    2*(2pi/N)^2   4pi/N  ]\r\n\r\n  // Count and tag the variables\r\n  tag_t = Eigen::VectorXi::Constant(F.rows(),-1);\r\n  std::vector<int> id_t;\r\n  size_t count = 0;\r\n  for(unsigned i=0; i<F.rows(); ++i)\r\n    if (!isHard[i])\r\n    {\r\n      tag_t(i) = count++;\r\n      id_t.push_back(i);\r\n    }\r\n\r\n  size_t count_t = id_t.size();\r\n\r\n  tag_p = Eigen::VectorXi::Constant(EF.rows(),-1);\r\n  std::vector<int> id_p;\r\n  for(unsigned i=0; i<EF.rows(); ++i)\r\n  {\r\n    if (!pFixed[i])\r\n    {\r\n      // if it is not fixed then it is a variable\r\n      tag_p(i) = count++;\r\n    }\r\n\r\n    // if it is not a border edge,\r\n    if (!isBorderEdge[i])\r\n    {\r\n      // and it is not between two fixed faces\r\n      if (!(isHard[EF(i,0)] && isHard[EF(i,1)]))\r\n      {\r\n          // then it participates in the energy!\r\n          id_p.push_back(i);\r\n      }\r\n    }\r\n  }\r\n\r\n  size_t count_p = count - count_t;\r\n  // System sizes: A (count_t + count_p) x (count_t + count_p)\r\n  //               b (count_t + count_p)\r\n\r\n  b.resize(count_t + count_p);\r\n  b.setZero();\r\n\r\n  std::vector<Eigen::Triplet<double> > T;\r\n  T.reserve(3 * 4 * count_p);\r\n\r\n  for(auto eid : id_p)\r\n  {\r\n    int i = EF(eid, 0);\r\n    int j = EF(eid, 1);\r\n    bool isFixed_i = isHard[i];\r\n    bool isFixed_j = isHard[j];\r\n    bool isFixed_p = pFixed[eid];\r\n    int row;\r\n    // (i)-th row: t_i [     2       -2           4pi/N      2    ]\r\n    if (!isFixed_i)\r\n    {\r\n      row = tag_t[i];\r\n      T.emplace_back(row, tag_t[i], 2);\r\n      if (isFixed_j)\r\n        b(row) +=  2 * hard[j];\r\n      else\r\n        T.emplace_back(row, tag_t[j], -2);\r\n      if (isFixed_p)\r\n        b(row) += -((4. * igl::PI) / Nd) * p[eid];\r\n      else\r\n        T.emplace_back(row, tag_p[eid], ((4. * igl::PI) / Nd));\r\n      b(row) += -2 * k[eid];\r\n      assert(hard[i] == hard[i]);\r\n      assert(hard[j] == hard[j]);\r\n      assert(p[eid] == p[eid]);\r\n      assert(k[eid] == k[eid]);\r\n      assert(b(row) == b(row));\r\n    }\r\n    // (j)+1 -th row: t_j [    -2        2          -4pi/N     -2    ]\r\n    if (!isFixed_j)\r\n    {\r\n      row = tag_t[j];\r\n      T.emplace_back(row, tag_t[j], 2);\r\n      if (isFixed_i)\r\n        b(row) += 2 * hard[i];\r\n      else\r\n        T.emplace_back(row, tag_t[i], -2);\r\n      if (isFixed_p)\r\n        b(row) += ((4. * igl::PI) / Nd) * p[eid];\r\n      else\r\n        T.emplace_back(row, tag_p[eid], -((4. * igl::PI) / Nd));\r\n      b(row) += 2 * k[eid];\r\n      assert(k[eid] == k[eid]);\r\n      assert(b(row) == b(row));\r\n    }\r\n    // (r*3)+2 -th row: pij [   4pi/N   -4pi/N    2*(2pi/N)^2   4pi/N  ]\r\n    if (!isFixed_p)\r\n    {\r\n      row = tag_p[eid];\r\n      T.emplace_back(row, tag_p[eid], (2. * pow(((2. * igl::PI) / Nd), 2)));\r\n      if (isFixed_i)\r\n        b(row) += -(4. * igl::PI) / Nd * hard[i];\r\n      else\r\n        T.emplace_back(row, tag_t[i], (4. * igl::PI) / Nd);\r\n      if (isFixed_j)\r\n        b(row) += (4. * igl::PI) / Nd * hard[j];\r\n      else\r\n        T.emplace_back(row,tag_t[j], -(4. * igl::PI) / Nd);\r\n      b(row) += - (4 * igl::PI)/Nd * k[eid];\r\n      assert(k[eid] == k[eid]);\r\n      assert(b(row) == b(row));\r\n    }\r\n  }\r\n\r\n  A.resize(count_t + count_p, count_t + count_p);\r\n  A.setFromTriplets(T.begin(), T.end());\r\n\r\n  // Soft constraints\r\n  bool addSoft = false;\r\n\r\n  for(unsigned i=0; i<wSoft.size();++i)\r\n    if (wSoft[i] != 0)\r\n      addSoft = true;\r\n\r\n  if (addSoft)\r\n  {\r\n    Eigen::VectorXd bSoft = Eigen::VectorXd::Zero(count_t + count_p);\r\n    std::vector<Eigen::Triplet<double> > TSoft;\r\n    TSoft.reserve(2 * count_p);\r\n\r\n    for(unsigned i=0; i<F.rows(); ++i)\r\n    {\r\n      int varid = tag_t[i];\r\n      if (varid != -1) // if it is a variable in the system\r\n      {\r\n        TSoft.emplace_back(varid, varid, wSoft[i]);\r\n        bSoft[varid] += wSoft[i] * soft[i];\r\n      }\r\n    }\r\n    Eigen::SparseMatrix<double> ASoft(count_t + count_p, count_t + count_p);\r\n    ASoft.setFromTriplets(TSoft.begin(), TSoft.end());\r\n\r\n    A = (1.0 - softAlpha) * A + softAlpha * ASoft;\r\n    b = b * (1.0 - softAlpha) + bSoft * softAlpha;\r\n  }\r\n}\r\n\r\nvoid igl::copyleft::comiso::NRosyField::solveRoundings()\r\n{\r\n  unsigned n = A.rows();\r\n\r\n  gmm::col_matrix< gmm::wsvector< double > > gmm_A(n, n);\r\n  std::vector<double> gmm_b(n);\r\n  std::vector<int> ids_to_round;\r\n  std::vector<double> x(n);\r\n\r\n  // Copy A\r\n  for (int k=0; k<A.outerSize(); ++k)\r\n    for (Eigen::SparseMatrix<double>::InnerIterator it(A, k); it; ++it)\r\n    {\r\n      gmm_A(it.row(),it.col()) += it.value();\r\n    }\r\n\r\n  // Copy b\r\n  for(unsigned int i = 0; i < n;++i)\r\n    gmm_b[i] = b[i];\r\n\r\n  // Set variables to round\r\n  ids_to_round.clear();\r\n  for(unsigned i=0; i<tag_p.size();++i)\r\n    if(tag_p[i] != -1)\r\n      ids_to_round.push_back(tag_p[i]);\r\n\r\n  // Empty constraints\r\n  gmm::row_matrix< gmm::wsvector< double > > gmm_C(0, n);\r\n\r\n  COMISO::ConstrainedSolver cs;\r\n  cs.solve(gmm_C, gmm_A, x, gmm_b, ids_to_round, 0.0, false, true);\r\n\r\n  // Copy the result back\r\n  for(unsigned i=0; i<F.rows(); ++i)\r\n    if (tag_t[i] != -1)\r\n      angles[i] = x[tag_t[i]];\r\n    else\r\n      angles[i] = hard[i];\r\n\r\n  for(unsigned i=0; i<EF.rows(); ++i)\r\n    if(tag_p[i]  != -1)\r\n      p[i] = (int)std::round(x[tag_p[i]]);\r\n}\r\n\r\n\r\nvoid igl::copyleft::comiso::NRosyField::solve(const int N)\r\n{\r\n  // Reduce the search space by fixing matchings\r\n  reduceSpace();\r\n\r\n  // Build the system\r\n  prepareSystemMatrix(N);\r\n\r\n  // Solve with integer roundings\r\n  solveRoundings();\r\n\r\n  // Find the cones\r\n  findCones(N);\r\n}\r\n\r\nvoid igl::copyleft::comiso::NRosyField::setConstraintHard(const int fid, const Eigen::Vector3d& v)\r\n{\r\n  isHard[fid] = true;\r\n  hard(fid) = convert3DtoLocal(fid, v);\r\n}\r\n\r\nvoid igl::copyleft::comiso::NRosyField::setConstraintSoft(const int fid, const double w, const Eigen::Vector3d& v)\r\n{\r\n  wSoft(fid) = w;\r\n  soft(fid) = convert3DtoLocal(fid, v);\r\n}\r\n\r\nvoid igl::copyleft::comiso::NRosyField::resetConstraints()\r\n{\r\n  isHard.resize(F.rows());\r\n  for(unsigned i = 0; i < F.rows(); ++i)\r\n    isHard[i] = false;\r\n  hard   = Eigen::VectorXd::Zero(F.rows());\r\n  wSoft = Eigen::VectorXd::Zero(F.rows());\r\n  soft = Eigen::VectorXd::Zero(F.rows());\r\n}\r\n\r\nEigen::MatrixXd igl::copyleft::comiso::NRosyField::getFieldPerFace()\r\n{\r\n  Eigen::MatrixXd result(F.rows(),3);\r\n  for(unsigned int i = 0; i < F.rows(); ++i)\r\n    result.row(i) = convertLocalto3D(i, angles(i));\r\n  return result;\r\n}\r\n\r\nvoid igl::copyleft::comiso::NRosyField::computek()\r\n{\r\n  // For every non-border edge\r\n  for (unsigned eid = 0; eid < EF.rows(); ++eid)\r\n  {\r\n    if (!isBorderEdge[eid])\r\n    {\r\n      int fid0 = EF(eid,0);\r\n      int fid1 = EF(eid,1);\r\n\r\n      Eigen::Vector3d N0 = N.row(fid0);\r\n      Eigen::Vector3d N1 = N.row(fid1);\r\n\r\n      // find common edge on triangle 0 and 1\r\n      int fid0_vc = -1;\r\n      int fid1_vc = -1;\r\n      for (unsigned i=0;i<3;++i)\r\n      {\r\n        if (EV(eid,0) == F(fid0,i))\r\n          fid0_vc = i;\r\n        if (EV(eid,1) == F(fid1,i))\r\n          fid1_vc = i;\r\n      }\r\n      assert(fid0_vc != -1);\r\n      assert(fid1_vc != -1);\r\n\r\n      Eigen::Vector3d common_edge = V.row(F(fid0,(fid0_vc+1)%3)) - V.row(F(fid0,fid0_vc));\r\n      common_edge.normalize();\r\n\r\n      // Map the two triangles in a new space where the common edge is the x axis and the N0 the z axis\r\n      Eigen::MatrixXd P(3,3);\r\n      Eigen::VectorXd o = V.row(F(fid0,fid0_vc));\r\n      Eigen::VectorXd tmp = -N0.cross(common_edge);\r\n      P << common_edge, tmp, N0;\r\n      P.transposeInPlace();\r\n\r\n\r\n      Eigen::MatrixXd V0(3,3);\r\n      V0.row(0) = V.row(F(fid0,0)).transpose() -o;\r\n      V0.row(1) = V.row(F(fid0,1)).transpose() -o;\r\n      V0.row(2) = V.row(F(fid0,2)).transpose() -o;\r\n\r\n      V0 = (P*V0.transpose()).transpose();\r\n\r\n      assert(V0(0,2) < 10e-10);\r\n      assert(V0(1,2) < 10e-10);\r\n      assert(V0(2,2) < 10e-10);\r\n\r\n      Eigen::MatrixXd V1(3,3);\r\n      V1.row(0) = V.row(F(fid1,0)).transpose() -o;\r\n      V1.row(1) = V.row(F(fid1,1)).transpose() -o;\r\n      V1.row(2) = V.row(F(fid1,2)).transpose() -o;\r\n      V1 = (P*V1.transpose()).transpose();\r\n\r\n      assert(V1(fid1_vc,2) < 10e-10);\r\n      assert(V1((fid1_vc+1)%3,2) < 10e-10);\r\n\r\n      // compute rotation R such that R * N1 = N0\r\n      // i.e. map both triangles to the same plane\r\n      double alpha = -std::atan2(V1((fid1_vc + 2) % 3, 2), V1((fid1_vc + 2) % 3, 1));\r\n\r\n      Eigen::MatrixXd R(3,3);\r\n      R << 1,          0,            0,\r\n           0, std::cos(alpha), -std::sin(alpha) ,\r\n           0, std::sin(alpha),  std::cos(alpha);\r\n      V1 = (R*V1.transpose()).transpose();\r\n\r\n      assert(V1(0,2) < 10e-10);\r\n      assert(V1(1,2) < 10e-10);\r\n      assert(V1(2,2) < 10e-10);\r\n\r\n      // measure the angle between the reference frames\r\n      // k_ij is the angle between the triangle on the left and the one on the right\r\n      Eigen::VectorXd ref0 = V0.row(1) - V0.row(0);\r\n      Eigen::VectorXd ref1 = V1.row(1) - V1.row(0);\r\n\r\n      ref0.normalize();\r\n      ref1.normalize();\r\n\r\n      double ktemp = std::atan2(ref1(1), ref1(0)) - std::atan2(ref0(1), ref0(0));\r\n\r\n      // just to be sure, rotate ref0 using angle ktemp...\r\n      Eigen::MatrixXd R2(2,2);\r\n      R2 << std::cos(ktemp), -std::sin(ktemp), std::sin(ktemp), std::cos(ktemp);\r\n\r\n      tmp = R2*ref0.head<2>();\r\n\r\n      assert(tmp(0) - ref1(0) < 10^10);\r\n      assert(tmp(1) - ref1(1) < 10^10);\r\n\r\n      k[eid] = ktemp;\r\n    }\r\n  }\r\n\r\n}\r\n\r\nvoid igl::copyleft::comiso::NRosyField::reduceSpace()\r\n{\r\n  // All variables are free in the beginning\r\n  for(unsigned int i = 0; i < EV.rows(); ++i)\r\n    pFixed[i] = false;\r\n\r\n  std::vector<bool> visited(EV.rows(), false);\r\n  std::vector<bool> starting(EV.rows(), false);\r\n\r\n  std::queue<int> q;\r\n  for(unsigned int i = 0; i < F.rows(); ++i)\r\n    if (isHard[i] || wSoft[i] != 0)\r\n    {\r\n      q.push(i);\r\n      starting[i] = true;\r\n    }\r\n\r\n  // Reduce the search space (see MI paper)\r\n  while (!q.empty())\r\n  {\r\n    int c = q.front();\r\n    q.pop();\r\n\r\n    visited[c] = true;\r\n    for(int i=0; i<3; ++i)\r\n    {\r\n      int eid = FE(c,i);\r\n      int fid = TT(c,i);\r\n\r\n      // skip borders\r\n      if (fid != -1)\r\n      {\r\n        assert((EF(eid,0) == c && EF(eid,1) == fid) || (EF(eid,1) == c && EF(eid,0) == fid));\r\n        // for every neighbouring face\r\n        if (!visited[fid] && !starting[fid])\r\n        {\r\n          pFixed[eid] = true;\r\n          p[eid] = 0;\r\n          visited[fid] = true;\r\n          q.push(fid);\r\n        }\r\n      }\r\n      else\r\n      {\r\n        // fix borders\r\n        pFixed[eid] = true;\r\n        p[eid] = 0;\r\n      }\r\n    }\r\n  }\r\n\r\n  // Force matchings between fixed faces\r\n  for(unsigned int i = 0; i < F.rows();++i)\r\n  {\r\n    if (isHard[i])\r\n    {\r\n      for(unsigned int j = 0; j < 3; ++j)\r\n      {\r\n        int fid = TT(i,j);\r\n        if ((fid!=-1) && (isHard[fid]))\r\n        {\r\n          // i and fid are adjacent and fixed\r\n          int eid = FE(i,j);\r\n          int fid0 = EF(eid,0);\r\n          int fid1 = EF(eid,1);\r\n\r\n          pFixed[eid] = true;\r\n          p[eid] = (int)std::round(2.0 / igl::PI * (hard(fid1) - hard(fid0) - k(eid)));\r\n        }\r\n      }\r\n    }\r\n  }\r\n}\r\n\r\ndouble igl::copyleft::comiso::NRosyField::convert3DtoLocal(unsigned fid, const Eigen::Vector3d& v)\r\n{\r\n  // Project onto the tangent plane\r\n  Eigen::Vector2d vp = TPs[fid] * v;\r\n\r\n  // Convert to angle\r\n  return std::atan2(vp(1), vp(0));\r\n}\r\n\r\nEigen::Vector3d igl::copyleft::comiso::NRosyField::convertLocalto3D(unsigned fid, double a)\r\n{\r\n  Eigen::Vector2d vp(std::cos(a), std::sin(a));\r\n  return vp.transpose() * TPs[fid];\r\n}\r\n\r\nEigen::VectorXd igl::copyleft::comiso::NRosyField::angleDefect()\r\n{\r\n  Eigen::VectorXd A = Eigen::VectorXd::Constant(V.rows(),-2*igl::PI);\r\n\r\n  for (unsigned int i = 0; i < F.rows(); ++i)\r\n  {\r\n    for (int j = 0; j < 3; ++j)\r\n    {\r\n      Eigen::VectorXd a = V.row(F(i,(j+1)%3)) - V.row(F(i,j));\r\n      Eigen::VectorXd b = V.row(F(i,(j+2)%3)) - V.row(F(i,j));\r\n      double t = a.transpose() * b;\r\n      if(a.norm() > 0. && b.norm() > 0.)\r\n        t /= (a.norm() * b.norm());\r\n      else\r\n        throw std::runtime_error(\"igl::copyleft::comiso::NRosyField::angleDefect: Division by zero!\");\r\n      A(F(i, j)) += std::acos(std::max(std::min(t, 1.), -1.));\r\n    }\r\n  }\r\n\r\n  return A;\r\n}\r\n\r\nvoid igl::copyleft::comiso::NRosyField::findCones(int N)\r\n{\r\n  // Compute I0, see http://www.graphics.rwth-aachen.de/media/papers/bommes_zimmer_2009_siggraph_011.pdf for details\r\n\r\n  singularityIndex = Eigen::VectorXd::Zero(V.rows());\r\n\r\n  // first the k\r\n  for (unsigned i = 0; i < EV.rows(); ++i)\r\n  {\r\n    if (!isBorderEdge[i])\r\n    {\r\n      singularityIndex(EV(i, 0)) -= k(i);\r\n      singularityIndex(EV(i, 1)) += k(i);\r\n    }\r\n  }\r\n\r\n  // then the A\r\n  Eigen::VectorXd A = angleDefect();\r\n  singularityIndex += A;\r\n  // normalize\r\n  singularityIndex /= (2 * igl::PI);\r\n\r\n  // round to integer (remove numerical noise)\r\n  for (unsigned i = 0; i < singularityIndex.size(); ++i)\r\n    singularityIndex(i) = round(singularityIndex(i));\r\n\r\n  for (unsigned i = 0; i < EV.rows(); ++i)\r\n  {\r\n    if (!isBorderEdge[i])\r\n    {\r\n      singularityIndex(EV(i, 0)) -= double(p(i)) / double(N);\r\n      singularityIndex(EV(i, 1)) += double(p(i)) / double(N);\r\n    }\r\n  }\r\n\r\n  // Clear the vertices on the edges\r\n  for (unsigned i = 0; i < EV.rows(); ++i)\r\n  {\r\n    if (isBorderEdge[i])\r\n    {\r\n      singularityIndex(EV(i,0)) = 0;\r\n      singularityIndex(EV(i,1)) = 0;\r\n    }\r\n  }\r\n}\r\n\r\nEigen::VectorXd igl::copyleft::comiso::NRosyField::getSingularityIndexPerVertex()\r\n{\r\n  return singularityIndex;\r\n}\r\n\r\nIGL_INLINE void igl::copyleft::comiso::nrosy(\r\n  const Eigen::MatrixXd& V,\r\n  const Eigen::MatrixXi& F,\r\n  const Eigen::VectorXi& b,\r\n  const Eigen::MatrixXd& bc,\r\n  const Eigen::VectorXi& b_soft,\r\n  const Eigen::VectorXd& w_soft,\r\n  const Eigen::MatrixXd& bc_soft,\r\n  const int N,\r\n  const double soft,\r\n  Eigen::MatrixXd& R,\r\n  Eigen::VectorXd& S\r\n  )\r\n{\r\n  // Init solver\r\n  igl::copyleft::comiso::NRosyField solver(V, F);\r\n\r\n  // Add hard constraints\r\n  for (unsigned i = 0; i < b.size(); ++i)\r\n    solver.setConstraintHard(b(i), bc.row(i));\r\n\r\n  // Add soft constraints\r\n  for (unsigned i = 0; i < b_soft.size(); ++i)\r\n    solver.setConstraintSoft(b_soft(i), w_soft(i), bc_soft.row(i));\r\n\r\n  // Set the soft constraints global weight\r\n  solver.setSoftAlpha(soft);\r\n\r\n  // Interpolate\r\n  solver.solve(N);\r\n\r\n  // Copy the result back\r\n  R = solver.getFieldPerFace();\r\n\r\n  // Extract singularity indices\r\n  S = solver.getSingularityIndexPerVertex();\r\n}\r\n\r\n\r\nIGL_INLINE void igl::copyleft::comiso::nrosy(\r\n                           const Eigen::MatrixXd& V,\r\n                           const Eigen::MatrixXi& F,\r\n                           const Eigen::VectorXi& b,\r\n                           const Eigen::MatrixXd& bc,\r\n                           const int N,\r\n                           Eigen::MatrixXd& R,\r\n                           Eigen::VectorXd& S\r\n                           )\r\n{\r\n  // Init solver\r\n  igl::copyleft::comiso::NRosyField solver(V, F);\r\n\r\n  // Add hard constraints\r\n  for (unsigned i= 0; i < b.size(); ++i)\r\n    solver.setConstraintHard(b(i), bc.row(i));\r\n\r\n  // Interpolate\r\n  solver.solve(N);\r\n\r\n  // Copy the result back\r\n  R = solver.getFieldPerFace();\r\n\r\n  // Extract singularity indices\r\n  S = solver.getSingularityIndexPerVertex();\r\n}\r\n", "meta": {"hexsha": "ba995a0c1d23ee0c5e6cf8c37c3cd6734f8c43fd", "size": 21047, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "igl/copyleft/comiso/nrosy.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/copyleft/comiso/nrosy.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/copyleft/comiso/nrosy.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": 27.1224226804, "max_line_length": 117, "alphanum_fraction": 0.5572765715, "num_tokens": 6468, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5583269943353745, "lm_q2_score": 0.5428632831725052, "lm_q1q2_score": 0.3030952252287381}}
{"text": "//==============================================================================\n//         Copyright 2003 - 2011   LASMEA UMR 6602 CNRS/Univ. Clermont II\n//         Copyright 2009 - 2011   LRI    UMR 8623 CNRS/Univ Paris Sud XI\n//\n//          Distributed under the Boost Software License, Version 1.0.\n//                 See accompanying file LICENSE.txt or copy at\n//                     http://www.boost.org/LICENSE_1_0.txt\n//==============================================================================\n#ifndef NT2_TRIGONOMETRIC_CONSTANTS_PIO2_2T_HPP_INCLUDED\n#define NT2_TRIGONOMETRIC_CONSTANTS_PIO2_2T_HPP_INCLUDED\n\n#include <nt2/include/functor.hpp>\n#include <boost/simd/constant/hierarchy.hpp>\n#include <boost/simd/constant/register.hpp>\nnamespace nt2\n{\n  namespace tag\n  {\n   /*!\n     @brief Pio2_2t generic tag\n\n     Represents the Pio2_2t constant in generic contexts.\n\n     @par Models:\n        Hierarchy\n   **/\n    // 2.02226624879595063154e-21\n    BOOST_SIMD_CONSTANT_REGISTER( Pio2_2t, double\n                                , 0, 0x2e85a308\n                                , 0x3BA3198A2E037073ll\n                                )\n  }\n  namespace ext\n  {\n   template<class Site, class... Ts>\n   BOOST_FORCEINLINE generic_dispatcher<tag::Pio2_2t, Site> dispatching_Pio2_2t(adl_helper, boost::dispatch::meta::unknown_<Site>, boost::dispatch::meta::unknown_<Ts>...)\n   {\n     return generic_dispatcher<tag::Pio2_2t, Site>();\n   }\n   template<class... Args>\n   struct impl_Pio2_2t;\n  }\n  /*!\n    Constant used in modular computation involving \\f$\\pi\\f$\n\n    @par Semantic:\n\n    For type T0:\n\n    @code\n    T0 r = Pio2_2t<T0>();\n    @endcode\n\n    @return a value of type T0\n  **/\n  BOOST_SIMD_CONSTANT_IMPLEMENTATION(tag::Pio2_2t, Pio2_2t);\n}\n\n#endif\n\n", "meta": {"hexsha": "6071cf89adf747b2cc968e6b46e390c5ef404999", "size": 1762, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/core/trigonometric/include/nt2/trigonometric/constants/pio2_2t.hpp", "max_stars_repo_name": "psiha/nt2", "max_stars_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "modules/core/trigonometric/include/nt2/trigonometric/constants/pio2_2t.hpp", "max_issues_repo_name": "psiha/nt2", "max_issues_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "modules/core/trigonometric/include/nt2/trigonometric/constants/pio2_2t.hpp", "max_forks_repo_name": "psiha/nt2", "max_forks_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.8852459016, "max_line_length": 170, "alphanum_fraction": 0.5817253121, "num_tokens": 474, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5621765008857981, "lm_q2_score": 0.5389832206876841, "lm_q1q2_score": 0.30300370104236013}}
{"text": "#include \"Astronomy.h\"\n#include \"AstronomyHelperFunctions.h\"\n#include \"Exception.h\"\n#include <boost/date_time/c_local_time_adjustor.hpp>\n#include <boost/date_time/gregorian/gregorian.hpp>\n#include <boost/date_time/local_time_adjustor.hpp>\n#include <boost/date_time/posix_time/posix_time_types.hpp>\n#include <cmath>\n#include <limits>\n#include <vector>\n\n/*=== Public interface =====================*/\n\nnamespace Fmi\n{\nnamespace Astronomy\n{\nnamespace\n{\nstd::vector<double> quad(double ym, double yz, double yp)\n{\n  try\n  {\n    double nz(0.0);\n    double z1(0.0);\n    double z2(0.0);\n    double a = 0.5 * (ym + yp) - yz;\n    double b = 0.5 * (yp - ym);\n    double c = yz;\n    double xe = -b / (2 * a);\n    double ye = (a * xe + b) * xe + c;\n    double dis = b * b - 4 * a * c;\n    if (dis > 0)\n    {\n      double dx = 0.5 * sqrt(dis) / fabs(a);\n      z1 = xe - dx;\n      z2 = xe + dx;\n      nz = fabs(z1) < 1 ? nz + 1 : nz;\n      nz = fabs(z2) < 1 ? nz + 1 : nz;\n      z1 = z1 < -1 ? z2 : z1;\n    }\n\n    std::vector<double> ret;\n    ret.push_back(nz);\n    ret.push_back(z1);\n    ret.push_back(z2);\n    ret.push_back(xe);\n    ret.push_back(ye);\n\n    return ret;\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n\n/**\n *      returns an angle in degrees in the range 0 to 360\n */\ndouble degRange(double x)\n{\n  try\n  {\n    double b = x / 360;\n    double a = 360 * (b - static_cast<int>(b));\n    double retVal = (a < 0 ? a + 360 : a);\n    return retVal;\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n\ndouble lmst(double mjd, double glon)\n{\n  try\n  {\n    double d = mjd - 51544.5;\n    double t = d / 36525;\n    double lst =\n        degRange(280.46061839 + 360.98564736629 * d + 0.000387933 * t * t - t * t * t / 38710000);\n    return lst / 15 + glon / 15;\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n\n/**\n *      returns the self::fractional part of x\n */\ndouble frac(double x)\n{\n  try\n  {\n    x -= static_cast<int>(x);\n    return x < 0 ? x + 1 : x;\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n\n/**\n * takes t and returns the geocentric ra and dec in an array mooneq\n * claimed good to 5' (angle) in ra and 1' in dec\n * tallies with another approximate method and with ICE for a couple of dates\n */\nstd::vector<double> minimoon(double t)\n{\n  try\n  {\n    double p2 = 6.283185307;\n    double arc = 206264.8062;\n    double coseps = 0.91748;\n    double sineps = 0.39778;\n\n    double lo = frac(0.606433 + 1336.855225 * t);\n    double l = p2 * frac(0.374897 + 1325.552410 * t);\n    double l2 = l * 2;\n    double ls = p2 * frac(0.993133 + 99.997361 * t);\n    double d = p2 * frac(0.827361 + 1236.853086 * t);\n    double d2 = d * 2;\n    double f = p2 * frac(0.259086 + 1342.227825 * t);\n    double f2 = f * 2;\n\n    double sinls = sin(ls);\n    double sinf2 = sin(f2);\n\n    double dl = 22640 * sin(l);\n    dl += -4586 * sin(l - d2);\n    dl += 2370 * sin(d2);\n    dl += 769 * sin(l2);\n    dl += -668 * sinls;\n    dl += -412 * sinf2;\n    dl += -212 * sin(l2 - d2);\n    dl += -206 * sin(l + ls - d2);\n    dl += 192 * sin(l + d2);\n    dl += -165 * sin(ls - d2);\n    dl += -125 * sin(d);\n    dl += -110 * sin(l + ls);\n    dl += 148 * sin(l - ls);\n    dl += -55 * sin(f2 - d2);\n\n    double s = f + (dl + 412 * sinf2 + 541 * sinls) / arc;\n    double h = f - d2;\n    double n = -526 * sin(h);\n    n += 44 * sin(l + h);\n    n += -31 * sin(-l + h);\n    n += -23 * sin(ls + h);\n    n += 11 * sin(-ls + h);\n    n += -25 * sin(-l2 + f);\n    n += 21 * sin(-l + f);\n\n    double L_moon = p2 * frac(lo + dl / 1296000);\n    double B_moon = (18520.0 * sin(s) + n) / arc;\n\n    double cb = cos(B_moon);\n    double x = cb * cos(L_moon);\n    double v = cb * sin(L_moon);\n    double w = sin(B_moon);\n    double y = coseps * v - sineps * w;\n    double z = sineps * v + coseps * w;\n    double rho = sqrt(1 - z * z);\n    double dec = (360 / p2) * atan(z / rho);\n    double ra = (48 / p2) * atan(y / (x + rho));\n    ra = ra < 0 ? ra + 24 : ra;\n\n    std::vector<double> retval;\n    retval.push_back(dec);\n    retval.push_back(ra);\n\n    return retval;\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n\ndouble sinAlt(double mjd, double hour, double glon, double cglat, double sglat)\n{\n  try\n  {\n    mjd += (hour / 24.0);\n    double t = (mjd - 51544.5) / 36525;\n    std::vector<double> objpos = minimoon(t);\n\n    double ra = objpos[1];\n    double dec = objpos[0];\n    double decRad = deg2rad(dec);\n    double tau = 15 * (lmst(mjd, glon) - ra);\n\n    return sglat * sin(decRad) + cglat * cos(decRad) * cos(deg2rad(tau));\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n\n}  // namespace\n\nconst boost::local_time::local_date_time& lunar_time_t::risesettime(SetAndRiseOccurence occ) const\n{\n  try\n  {\n    if (occ == FIRST_RISE)\n      return moonrise;\n    if (occ == SECOND_RISE)\n      return moonrise2;\n    if (occ == FIRST_SET)\n      return moonset;\n\n    return moonset2;\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n\nstd::string lunar_time_t::as_string(SetAndRiseOccurence occ) const\n{\n  try\n  {\n    std::stringstream ss;\n\n    bool rise_occurence(occ == FIRST_RISE || occ == SECOND_RISE);\n\n    const boost::local_time::local_date_time& occ_ldt =\n        (rise_occurence ? (occ == FIRST_RISE ? moonrise : moonrise2)\n                        : (occ == FIRST_SET ? moonset : moonset2));\n\n    if (!occ_ldt.is_not_a_date_time())\n    {\n      ss << std::setfill('0') << std::setw(2) << occ_ldt.local_time().time_of_day().hours()\n         << std::setfill('0') << std::setw(2) << occ_ldt.local_time().time_of_day().minutes();\n    }\n\n    return ss.str();\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n\nstd::string lunar_time_t::as_string_long(SetAndRiseOccurence occ) const\n{\n  try\n  {\n    std::stringstream ss;\n\n    bool rise_occurence(occ == FIRST_RISE || occ == SECOND_RISE);\n\n    const boost::local_time::local_date_time& occ_ldt =\n        (rise_occurence ? (occ == FIRST_RISE ? moonrise : moonrise2)\n                        : (occ == FIRST_SET ? moonset : moonset2));\n\n    std::cout << occ_ldt;\n\n    if (occ_ldt.is_not_a_date_time())\n      ss << occ_ldt;\n    else\n      ss << occ_ldt.date() << \" \" << as_string(occ);\n\n    return ss.str();\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n\nstd::ostream& operator<<(std::ostream& ostream, const lunar_time_t& lt)\n{\n  try\n  {\n    std::string risestr(lt.as_string(FIRST_RISE));\n    std::string setstr(lt.as_string(FIRST_SET));\n\n    if (risestr.empty())\n    {\n      if (!lt.moonset_today())\n      {\n        if (lt.above_hz_24h)\n          risestr = \"****\";\n        else\n          risestr = \"----\";\n      }\n      else\n      {\n        risestr = \"    \";\n      }\n    }\n    if (setstr.empty())\n    {\n      if (!lt.moonrise_today())\n      {\n        if (lt.above_hz_24h)\n          setstr = \"****\";\n        else\n          setstr = \"----\";\n      }\n      else\n      {\n        setstr = \"    \";\n      }\n    }\n\n    ostream << risestr << \" \" << setstr;\n\n    return ostream;\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n\nbool dst_on(const boost::posix_time::ptime& theTime, const boost::local_time::local_date_time& ldt)\n{\n  try\n  {\n    auto zone = ldt.zone();\n\n    bool dst_on(false);\n    if (zone->has_dst())\n    {\n      auto dst_starttime = zone->dst_local_start_time(ldt.local_time().date().year());\n      auto dst_endtime = zone->dst_local_end_time(ldt.local_time().date().year());\n\n      if (dst_starttime < dst_endtime)\n      {\n        if (theTime >= dst_starttime && theTime <= dst_endtime)\n          dst_on = true;\n      }\n      else\n      {\n        if (theTime >= dst_starttime || theTime <= dst_endtime)\n          dst_on = true;\n      }\n    }\n    return dst_on;\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n\ndouble timezone_offset(const boost::local_time::local_date_time& ldt)\n{\n  try\n  {\n    auto zone = ldt.zone();\n\n    double base_offset(zone->base_utc_offset().hours() +\n                       (static_cast<float>(zone->base_utc_offset().minutes()) / 60.0));\n    double dst_offset(dst_on(ldt.local_time(), ldt)\n                          ? (zone->dst_offset().hours() + zone->dst_offset().minutes())\n                          : 0.0);\n\n    return (base_offset + dst_offset);\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n\nvoid get_hours_and_minutes(double hours, int& hr, int& min)\n{\n  try\n  {\n    double hrs(hours);\n\n    // if time is greater than 23:59:29 use value 23:59, so that we do not move to 00:00 (backwards)\n    if (hrs > 23.991 && hrs < 24.0)\n      hrs = 23.991;\n\n    hr = static_cast<int>(floor(hrs));\n    min = static_cast<int>(round(60.0 * (hrs - hr)));\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n\nboost::local_time::local_date_time parse_local_date_time(\n    const boost::local_time::local_date_time& ldt, double hours)\n{\n  try\n  {\n    double hrs(hours);\n    int hour(0);\n    int min(0);\n\n    get_hours_and_minutes(hrs, hour, min);\n    // utc time of the beginning of the day\n    auto utc_ptime = ldt.utc_time();\n    // add hour offset\n    utc_ptime += boost::posix_time::time_duration(hour, min, 0, 0);\n\n    // return local time\n    boost::local_time::local_date_time ldt_riseset(utc_ptime, ldt.zone());\n\n    return ldt_riseset;\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n\n/*\n * Calculate moonrise, moonset for given location\n */\nlunar_time_t lunar_time_calculation(const boost::local_time::local_date_time& ldt,\n                                    double offset,\n                                    double lon,\n                                    double lat)\n{\n  try\n  {\n    double utrise(0.0);\n    double utset(0.0);\n    double utrise2(0.0);\n    double utset2(0.0);\n\n    // beginning of the day\n    boost::local_time::local_date_time ldt_beg(\n        ldt.local_time().date(),\n        boost::posix_time::time_duration(0, 0, 0, 0),\n        ldt.zone(),\n        boost::local_time::local_date_time::NOT_DATE_TIME_ON_ERROR);\n\n    double date = ldt_beg.local_time().date().modjulian_day();\n\n    date -= (static_cast<float>(offset) / 24.0);\n\n    double latRad = deg2rad(lat);\n    double sinho = 0.0023271056;\n    double sglat = sin(latRad);\n    double cglat = cos(latRad);\n\n    bool rise = false;\n    bool set = false;\n    bool rise2 = false;\n    bool set2 = false;\n    bool above = false;\n    double hour = 1.0;\n\n    double ym = sinAlt(date, hour - 1.0, lon, cglat, sglat) - sinho;\n\n    above = (ym > 0);\n    while (hour < 25)\n    {\n      double yz = sinAlt(date, hour, lon, cglat, sglat) - sinho;\n      double yp = sinAlt(date, hour + 1.0, lon, cglat, sglat) - sinho;\n\n      std::vector<double> quadout = quad(ym, yz, yp);\n      double nz = quadout[0];\n      double z1 = quadout[1];\n      double z2 = quadout[2];\n      // double xe = quadout[3];\n      double ye = quadout[4];\n\n      if (nz == 1)\n      {\n        if (ym < 0)\n        {\n          if (!set || !rise)\n          {\n            utrise = hour + z1;\n            rise = true;\n          }\n          else\n          {\n            utrise2 = hour + z1;\n            rise2 = true;\n          }\n        }\n        else\n        {\n          if (!set || !rise)\n          {\n            utset = hour + z1;\n            set = true;\n          }\n          else\n          {\n            utset2 = hour + z1;\n            set2 = true;\n          }\n        }\n      }\n\n      if (nz == 2)\n      {\n        if (ye < 0)\n        {\n          if (!set || !rise)\n          {\n            utrise = hour + z2;\n            utset = hour + z1;\n          }\n          else\n          {\n            utrise2 = hour + z2;\n            utset2 = hour + z1;\n          }\n        }\n        else\n        {\n          if (!set || !rise)\n          {\n            utrise = hour + z1;\n            utset = hour + z2;\n          }\n          else\n          {\n            utrise2 = hour + z1;\n            utset2 = hour + z2;\n          }\n        }\n      }\n#ifdef MYDEBUG\n      std::cout << \"nz: \" << nz << endl;\n      std::cout << \"z1: \" << z1 << endl;\n      std::cout << \"z2: \" << z2 << endl;\n      // std::cout << \"xe: \" << xe << endl;\n      std::cout << \"ye: \" << ye << endl;\n      std::cout << \"utrise: \" << utrise << endl;\n      std::cout << \"utset: \" << utset << endl;\n      std::cout << \"utrise2: \" << utrise2 << endl;\n      std::cout << \"utset2: \" << utset2 << endl;\n      std::cout << \"rise: \" << rise << endl;\n      std::cout << \"rise2: \" << rise2 << endl;\n      std::cout << \"set: \" << set << endl;\n      std::cout << \"set2: \" << set2 << endl << endl;\n#endif\n\n      ym = yp;\n      hour += 2.0;\n    }\n\n#ifdef MYDEBUG\n    cout << \"\\noffset: \" << offset << endl;\n    cout << \"rise: \" << rise << endl;\n    cout << \"rise2: \" << rise2 << endl;\n    cout << \"utrise: \" << utrise << endl;\n    cout << \"utrise2: \" << utrise2 << endl;\n    cout << \"set: \" << set << endl;\n    cout << \"set2: \" << set2 << endl;\n    cout << \"utset: \" << utset << endl;\n    cout << \"utset2: \" << utset2 << endl;\n    cout << \"julian: \" << date << endl;\n    cout << \"ldt: \" << ldt << endl;\n    cout << \"ldt.local_time(): \" << ldt.local_time() << endl;\n    cout << \"ldt.utc_time(): \" << ldt.utc_time() << endl;\n    cout << \"ldt_beg: \" << ldt_beg << endl;\n#endif\n\n    lunar_time_t retval(\n        (rise ? parse_local_date_time(ldt_beg, utrise)\n              : boost::local_time::local_date_time(boost::posix_time::not_a_date_time)),\n        (set ? parse_local_date_time(ldt_beg, utset)\n             : boost::local_time::local_date_time(boost::posix_time::not_a_date_time)),\n        (rise2 ? parse_local_date_time(ldt_beg, utrise2)\n               : boost::local_time::local_date_time(boost::posix_time::not_a_date_time)),\n        (set2 ? parse_local_date_time(ldt_beg, utset2)\n              : boost::local_time::local_date_time(boost::posix_time::not_a_date_time)),\n        rise,\n        set,\n        rise2,\n        set2,\n        (!rise && !set && above));\n\n    return retval;\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n\nlunar_time_t lunar_time_i(const boost::local_time::local_date_time& ldt, double lon, double lat)\n{\n  try\n  {\n    // beginning of the day\n    boost::local_time::local_date_time ldt_beg(\n        ldt.local_time().date(),\n        boost::posix_time::time_duration(0, 0, 0, 0),\n        ldt.zone(),\n        boost::local_time::local_date_time::NOT_DATE_TIME_ON_ERROR);\n    boost::local_time::local_date_time ldt_end(\n        ldt.local_time().date(),\n        boost::posix_time::time_duration(23, 59, 59, 0),\n        ldt.zone(),\n        boost::local_time::local_date_time::NOT_DATE_TIME_ON_ERROR);\n\n    boost::posix_time::ptime dst_endtime(\n        ldt.zone()->dst_local_end_time(ldt.local_time().date().year()));\n    bool dst_ends_today(ldt_beg.local_time().date() == dst_endtime.date());\n\n    double offset_before_dst_ends = timezone_offset(ldt_beg);\n\n    lunar_time_t retval;\n\n    // if dst ends today we have to handle the extended time\n    if (dst_ends_today)\n    {\n      double offset_after_dst_ends = timezone_offset(ldt_end);\n\n      lunar_time_t lt_before = lunar_time_calculation(ldt_beg, offset_before_dst_ends, lon, lat);\n\n      // if rise and set is found return\n      if (lt_before.moonrise_today() && lt_before.moonset_today())\n        return lt_before;\n\n      // do calculation using wintertime offset\n      lunar_time_t lt_after = lunar_time_calculation(ldt_beg, offset_after_dst_ends, lon, lat);\n      if (lt_after.moonrise_today())\n        lt_after.moonrise += boost::posix_time::hours(1);\n      if (lt_after.moonset_today())\n        lt_after.moonset += boost::posix_time::hours(1);\n      if (lt_after.moonrise2_today())\n        lt_after.moonrise2 += boost::posix_time::hours(1);\n      if (lt_after.moonset2_today())\n        lt_after.moonset2 += boost::posix_time::hours(1);\n\n      lunar_time_t lt_combined(\n          lt_before.moonrise_today() ? lt_before.moonrise : lt_after.moonrise,\n          lt_before.moonset_today() ? lt_before.moonset : lt_after.moonset,\n          lt_before.moonrise2_today() ? lt_before.moonrise2 : lt_after.moonrise2,\n          lt_before.moonset2_today() ? lt_before.moonset2 : lt_after.moonset2,\n          lt_before.rise_today,\n          lt_before.set_today,\n          lt_before.rise2_today,\n          lt_before.set2_today,\n          lt_before.above_hz_24h && lt_after.above_hz_24h);\n\n      retval = lt_combined;\n    }\n    else\n    {\n      retval = lunar_time_calculation(ldt_beg, offset_before_dst_ends, lon, lat);\n    }\n    return retval;\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n\nlunar_time_t lunar_time(const boost::local_time::local_date_time& ldt,\n                        double lon,\n                        double lat,\n                        bool allow_missing_dates /*= false*/)\n{\n  try\n  {\n    lunar_time_t lt_ret = lunar_time_i(ldt, lon, lat);\n\n    if (allow_missing_dates)\n      return lt_ret;\n\n    unsigned int iteration_limit(366);\n    if (!lt_ret.moonrise_today())\n    {\n      unsigned int counter(0);  // just in case something goes wrong\n      boost::local_time::local_date_time ldt_iter(ldt);\n      if (lt_ret.above_hz_24h || lt_ret.moonset_today())\n      {\n        // find the previous moonrise\n        lunar_time_t lt_prev;\n        while (!lt_prev.moonrise_today() && counter < iteration_limit)\n        {\n          ldt_iter -= boost::posix_time::hours(24);\n          lt_prev = lunar_time_i(ldt_iter, lon, lat);\n          counter++;\n        }\n        if (counter < iteration_limit)\n          lt_ret.moonrise = lt_prev.moonrise;\n      }\n      else\n      {\n        // find the next moonrise\n        lunar_time_t lt_next;\n        while (!lt_next.moonrise_today() && counter < iteration_limit)\n        {\n          ldt_iter += boost::posix_time::hours(24);\n          lt_next = lunar_time_i(ldt_iter, lon, lat);\n          counter++;\n        }\n        if (counter < iteration_limit)\n          lt_ret.moonrise = lt_next.moonrise;\n      }\n    }\n    if (!lt_ret.moonset_today())\n    {\n      unsigned int counter(0);  // just in case something goes wrong\n      boost::local_time::local_date_time ldt_iter(ldt);\n      if (lt_ret.above_hz_24h || lt_ret.moonrise_today())\n      {\n        // find the next moonset\n        lunar_time_t lt_next;\n        while (!lt_next.moonset_today() && counter < iteration_limit)\n        {\n          ldt_iter += boost::posix_time::hours(24);\n          lt_next = lunar_time_i(ldt_iter, lon, lat);\n          counter++;\n        }\n        if (counter < iteration_limit)\n          lt_ret.moonset = lt_next.moonset;\n      }\n      else\n      {\n        // find the previous moonset\n        lunar_time_t lt_prev;\n        while (!lt_prev.moonset_today() && counter < iteration_limit)\n        {\n          ldt_iter -= boost::posix_time::hours(24);\n          lt_prev = lunar_time_i(ldt_iter, lon, lat);\n          counter++;\n        }\n        if (counter < iteration_limit)\n          lt_ret.moonset = lt_prev.moonset;\n      }\n    }\n    return lt_ret;\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n\n}  // namespace Astronomy\n}  // namespace Fmi\n\n// ======================================================================\n", "meta": {"hexsha": "02894ab02e294961b366b2fec1b4ce256cfde28c", "size": 19466, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "macgyver/AstronomyLunarTime.cpp", "max_stars_repo_name": "fmidev/smartmet-library-macgyver", "max_stars_repo_head_hexsha": "c91c28535c5df15856caf59e1d29f96917378eca", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "macgyver/AstronomyLunarTime.cpp", "max_issues_repo_name": "fmidev/smartmet-library-macgyver", "max_issues_repo_head_hexsha": "c91c28535c5df15856caf59e1d29f96917378eca", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2017-03-13T18:40:43.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-08T11:47:22.000Z", "max_forks_repo_path": "macgyver/AstronomyLunarTime.cpp", "max_forks_repo_name": "fmidev/smartmet-library-macgyver", "max_forks_repo_head_hexsha": "c91c28535c5df15856caf59e1d29f96917378eca", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2017-03-16T07:47:23.000Z", "max_forks_repo_forks_event_max_datetime": "2017-03-16T07:47:23.000Z", "avg_line_length": 25.8856382979, "max_line_length": 100, "alphanum_fraction": 0.5511147642, "num_tokens": 5700, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7577943822145998, "lm_q2_score": 0.399811640739795, "lm_q1q2_score": 0.3029750152966185}}
{"text": "// original source:https://github.com/AgileDrones/OptiTrack-Motive-2-Client \n// by Winter Guerra\n// winterg@mit.edu\n//https://winter.industries/ \n\n\n// Include motion capture framework\n#include \"optitrack_motive_2_client/motionCaptureClientFramework.h\"\n// Include ACL message types (https://bitbucket.org/brettlopez/acl_msgs.git)\n#include \"acl_msgs/ViconState.h\"\n\n// Includes for ROS\n#include \"ros/ros.h\"\n\n// Includes for node\n#include <boost/program_options.hpp>\n#include <Eigen/Core>\n#include <Eigen/Dense>\n#include <Eigen/Geometry>\n#include <iostream>\n#include <fstream>\n\nnamespace po = boost::program_options;\nusing namespace Eigen;\nconst double pi  = 3.1415926535897932384626433832795028841971;\n\n\n// Used to convert mocap frame (NUE) to LCM NED.\n// static Eigen::Matrix3d R_NUE2NED = [] {\n//     Eigen::Matrix3d tmp;\n//     tmp <<  1, 0, 0, \n//             0, 0, 1, \n//             0, -1, 0;\n//     return tmp;\n// }();\n\n\n// Used to convert mocap frame (NUE) to ROS ENU.\nstatic Eigen::Matrix3d R_NUE2ENU = [] {\n    Eigen::Matrix3d tmp;\n    tmp <<  0, 0, 1, \n            1, 0, 0, \n            0, 1, 0;\n    return tmp;\n}();\n\nVector3d positionConvertNUE2ENU(double* positionNUE){\n  Vector3d positionNUEVector, positionENUVector;\n  positionNUEVector << positionNUE[0], positionNUE[1], positionNUE[2];\n  \n  positionENUVector = R_NUE2ENU * positionNUEVector;\n  return positionENUVector;\n}\n\nQuaterniond quaternionConvertNUE2ENU(double* quaternionNUE){\n    Quaterniond quaternionInNUE;\n    quaternionInNUE.x() = quaternionNUE[0];\n    quaternionInNUE.y() = quaternionNUE[1];\n    quaternionInNUE.z() = quaternionNUE[2];\n    quaternionInNUE.w() = quaternionNUE[3];\n\n    Quaterniond quaternionInENU = Quaterniond(R_NUE2ENU * quaternionInNUE.normalized().toRotationMatrix()\n                              * R_NUE2ENU.transpose());\n    return quaternionInENU;\n}\n\nint main(int argc, char *argv[])\n{\n  // Keep track of ntime offset.\n  int64_t offset_between_windows_and_linux = std::numeric_limits<int64_t>::max();\n  ROS_INFO(\"1\");  \n  // Init ROS\n  ros::init(argc, argv, \"optitrack_motive_2_client_node\");\n  ros::NodeHandle n;\n\n  std::string szMyIPAddress; \n  std::string szServerIPAddress; \n\n  // Get CMDline arguments for server and local IP addresses.\n\n\n //自己加的，方便调整IP read ip from launch, added by Peter Li\n  n.getParam(\n      \"/optitrack_motive_2_client_node/MyIPAddress\",\n      szMyIPAddress); //因为这个参数不是server那边发送的，是这个节点私有的，因此要加范围\n  ROS_INFO(\"MyIPAddress is %s\", szMyIPAddress.c_str());   \n\n  n.getParam(\n      \"/optitrack_motive_2_client_node/ServerIPAddress\",\n      szServerIPAddress); //因为这个参数不是server那边发送的，是这个节点私有的，因此要加范围\n  ROS_INFO(\"ServerIPAddress is %s\", szServerIPAddress.c_str());     \n\n/*\n// test for direct input here，added by Peter Li\nszMyIPAddress = \"192.168.50.170\";\nszServerIPAddress = \"192.168.50.171\";\n*/\n\n  try {\n    po::options_description desc (\"Options\");\n    desc.add_options()\n        (\"help,h\", \"print usage message\")\n        (\"local\",po::value<std::string>(&szMyIPAddress),\"local IP Address\")\n        (\"server\",po::value<std::string>(&szServerIPAddress), \"server address\");\n\n    po::variables_map vm;\n    try {\n      po::store(po::parse_command_line(argc, argv, desc), vm);\n      po::notify (vm);\n    }\n    catch (po::error& e) {\n      std::cerr << e.what() << std::endl;\n      return 0;\n    }\n    if (vm.count(\"help\")) {\n      std::cout << desc << \"\\n\";\n      return 0;\n    }\n  }\n  catch (...) {}\n\n  // Init mocap framework\n  agile::motionCaptureClientFramework mocap_ = agile::motionCaptureClientFramework(szMyIPAddress, szServerIPAddress);\n\n  \n  // Some vars to calculate twist/acceleration and dts\n  // Also keeps track of the various publishers\n  std::map<int, ros::Publisher> rosPublishers;\n  std::map<int, acl_msgs::ViconState> pastStateMessages;\n\n  while (true){\n    // Wait for mocap packet\n    mocap_.spin();\n    \n    std::vector<agile::Packet> mocap_packets = mocap_.getPackets();\n  \n    for (agile::Packet mocap_packet : mocap_packets){\n\n      // @TODO: Make getPackets return a list.\n\n      // Skip this rigid body if tracking is invalid\n      if (!mocap_packet.tracking_valid)\n        continue;\n\n      // estimate the windows to linux constant offset by taking the minimum seen offset.\n      // @TODO: Make offset a rolling average instead of a latching offset.\n      int64_t offset = mocap_packet.transmit_timestamp - mocap_packet.receive_timestamp;\n      if (offset < offset_between_windows_and_linux ){\n        offset_between_windows_and_linux = offset;\n      }\n      uint64_t packet_ntime = mocap_packet.mid_exposure_timestamp - offset_between_windows_and_linux;\n\n      // Get past state and publisher (if they exist)\n      bool hasPreviousMessage = (rosPublishers.find(mocap_packet.rigid_body_id) != rosPublishers.end());\n      ros::Publisher publisher;\n      acl_msgs::ViconState lastState;\n      acl_msgs::ViconState currentState;\n      \n      // Initialize publisher for rigid body if not exist.\n      if (!hasPreviousMessage){\n        std::string topic = \"/\" + mocap_packet.model_name + \"/vicon\";\n\n        publisher = n.advertise<acl_msgs::ViconState>(topic, 1);\n        rosPublishers[mocap_packet.rigid_body_id] = publisher;\n      } else {\n        // Get saved publisher and last state\n        publisher = rosPublishers[mocap_packet.rigid_body_id];\n        lastState = pastStateMessages[mocap_packet.rigid_body_id];\n      }\n\n      // Add timestamp\n      currentState.header.stamp = ros::Time(packet_ntime/1e9, packet_ntime%(int64_t)1e9);\n\n      // Convert rigid body position from NUE to ROS ENU\n      Vector3d positionENUVector = positionConvertNUE2ENU(mocap_packet.pos);\n      currentState.pose.position.x = positionENUVector(0);\n      currentState.pose.position.y = positionENUVector(1);\n      currentState.pose.position.z = positionENUVector(2);\n      // Convert rigid body rotation from NUE to ROS ENU\n      Quaterniond quaternionENUVector = quaternionConvertNUE2ENU(mocap_packet.orientation);\n      currentState.pose.orientation.x = quaternionENUVector.x();\n      currentState.pose.orientation.y = quaternionENUVector.y();\n      currentState.pose.orientation.z = quaternionENUVector.z();\n      currentState.pose.orientation.w = quaternionENUVector.w();\n     /***************************************************/\n      //加上欧拉角 convert Quaterniond to Eulers, added by Peter Li\n      //四元数->旋转矩阵->欧拉角 Quaterniond->RotationMatrix->Eulers\n      ////!!!!!Be aware you can convert rad to degree here， which is convenient for comparing with Mtoive panels.\n      ///Custom for your need.注意此处是 rad。\n      Matrix3d RotationMatrix_cur = quaternionENUVector.toRotationMatrix();\n      Vector3d Eulers_cur = RotationMatrix_cur.eulerAngles(2,1,0);\n      currentState.Eulers.z = Eulers_cur(0);//yaw(why only within [0,pi] why?)\n      currentState.Eulers.y = Eulers_cur(1);//pitch (-pi,pi]\n      currentState.Eulers.x = Eulers_cur(2);//roll (-pi,pi]\n      /***************************************************/\n      currentState.has_pose = true;\n      \n      // Loop through markers and convert positions from NUE to ENU\n      // @TODO since the state message does not understand marker locations.\n\n      if (hasPreviousMessage){\n        int64_t dt_nsec = packet_ntime - (lastState.header.stamp.sec*1e9 + lastState.header.stamp.nsec);\n\n       // printf(\"time interval = %ld\",dt_nsec);\n\n        // Calculate twist. Requires last state message.\n        currentState.twist.linear.x = (currentState.pose.position.x - lastState.pose.position.x)/(dt_nsec / 1e9);\n        currentState.twist.linear.y = (currentState.pose.position.y - lastState.pose.position.y)/(dt_nsec / 1e9);\n        currentState.twist.linear.z = (currentState.pose.position.z - lastState.pose.position.z)/(dt_nsec / 1e9);\n\n        // @TODO: not sure how to calculate the angular twist. Is it in local frame or global frame?\n        //计算角速度 calculate the derivation of Eulers in global frame, i.e. angular velocity, added by Peter Li\n\n        currentState.twist.angular.x = (currentState.Eulers.x - lastState.Eulers.x)/(dt_nsec / 1e9);//roll\n        currentState.twist.angular.y = (currentState.Eulers.y - lastState.Eulers.y)/(dt_nsec / 1e9);//pitch\n        currentState.twist.angular.z = (currentState.Eulers.z - lastState.Eulers.z)/(dt_nsec / 1e9);//yaw\n        currentState.has_twist = true;\n        \n        // Calculate accelerations of both positon and Eulers. Requires last state message.\n        currentState.pos_accel.x = (currentState.twist.linear.x - lastState.twist.linear.x)/(dt_nsec / 1e9);\n        currentState.pos_accel.y = (currentState.twist.linear.y - lastState.twist.linear.y)/(dt_nsec / 1e9);\n        currentState.pos_accel.z = (currentState.twist.linear.z - lastState.twist.linear.z)/(dt_nsec / 1e9);\n        currentState.Eulers_accel.x = (currentState.twist.angular.x - lastState.twist.angular.x)/(dt_nsec / 1e9);\n        currentState.Eulers_accel.y = (currentState.twist.angular.y - lastState.twist.angular.y)/(dt_nsec / 1e9);\n        currentState.Eulers_accel.z = (currentState.twist.angular.z - lastState.twist.angular.z)/(dt_nsec / 1e9);\n\n        currentState.has_accel = true;\n      }\n      \n      // Save state for future acceleration and twist computations\n      pastStateMessages[mocap_packet.rigid_body_id] = currentState;\n\n      // Publish ROS state.\n      publisher.publish(currentState);\n\n    }\n  }\n}\n", "meta": {"hexsha": "11f8ace81f61171ee946f864530571c655a95f7c", "size": 9329, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/optitrack_motive_1.8_client/src/optitrack_motive_2_client_node.cpp", "max_stars_repo_name": "orcasdli/SMCinROS", "max_stars_repo_head_hexsha": "2574c9390e800df2fcd51c31eee86924cc1a48ee", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 17.0, "max_stars_repo_stars_event_min_datetime": "2019-01-09T06:17:02.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-02T03:15:18.000Z", "max_issues_repo_path": "src/optitrack_motive_1.8_client/src/optitrack_motive_2_client_node.cpp", "max_issues_repo_name": "orcasdli/SMCinROS", "max_issues_repo_head_hexsha": "2574c9390e800df2fcd51c31eee86924cc1a48ee", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-06-29T07:06:20.000Z", "max_issues_repo_issues_event_max_datetime": "2020-07-03T13:23:06.000Z", "max_forks_repo_path": "src/optitrack_motive_1.8_client/src/optitrack_motive_2_client_node.cpp", "max_forks_repo_name": "orcasdli/SMCinROS", "max_forks_repo_head_hexsha": "2574c9390e800df2fcd51c31eee86924cc1a48ee", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2019-05-31T02:20:46.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-30T03:19:41.000Z", "avg_line_length": 39.0334728033, "max_line_length": 117, "alphanum_fraction": 0.6815307107, "num_tokens": 2419, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5964331606115021, "lm_q2_score": 0.5078118642792044, "lm_q1q2_score": 0.30287583520806505}}
{"text": "#pragma once\n\n#include \"splines.h\"\n#include <algorithm>\n#include <iterator>\n#include <functional>\n#include <cmath>\t\t\t// for fmin/fmax\n#include <cassert>\n#ifdef MSVC_LIMITATIONS\n#include <boost/math/special_functions/binomial.hpp>\n#endif\n#include \"general math.h\"\t// for lerp\n#include \"misc.h\"\t\t\t// for Reserve()\n\n#pragma region CompositePoint\nnamespace Math::Splines\n{\n\ttemplate<class Pos, class ...Attribs>\n\tstruct CompositePoint<Pos, Attribs...>::AddAssign\n\t{\n\t\ttemplate<typename Dst, typename Src>\n\t\tconstexpr void operator ()(Dst &dst, const Src &src) const { dst += src; }\n\t};\n\n\ttemplate<class Pos, class ...Attribs>\n\tstruct CompositePoint<Pos, Attribs...>::SubAssign\n\t{\n\t\ttemplate<typename Dst, typename Src>\n\t\tconstexpr void operator ()(Dst &dst, const Src &src) const { dst -= src; }\n\t};\n\n\ttemplate<class Pos, class ...Attribs>\n\tstruct CompositePoint<Pos, Attribs...>::MulAssign\n\t{\n\t\ttemplate<typename Dst, typename Src>\n\t\tconstexpr void operator ()(Dst &dst, const Src &src) const { dst *= src; }\n\t};\n\n\ttemplate<class Pos, class ...Attribs>\n\tstruct CompositePoint<Pos, Attribs...>::DivAssign\n\t{\n\t\ttemplate<typename Dst, typename Src>\n\t\tconstexpr void operator ()(Dst &dst, const Src &src) const { dst /= src; }\n\t};\n\n\t// op point\n\ttemplate<class Pos, class ...Attribs>\n\ttemplate<class Functor, size_t ...idx>\n\tinline auto CompositePoint<Pos, Attribs...>::OpPoint(std::index_sequence<idx...>) const\n#ifdef MSVC_LIMITATIONS\n\t\t-> CompositePoint<Pos, Attribs...>\n#else\n\t\t-> CompositePoint<std::decay_t<decltype(std::declval<Functor>()(pos))>, std::decay_t<decltype(std::declval<Functor>()(std::get<idx>(attribs)))>...>\n#endif\n\t{\n\t\tconstexpr Functor op;\n\t\treturn{ op(pos), op(std::get<idx>(attribs))... };\n\t}\n\n\t// point op point\n\ttemplate<class Pos, class ...Attribs>\n\ttemplate<class Functor, size_t ...idx, class RightPos, class ...RightAttribs>\n\tinline auto CompositePoint<Pos, Attribs...>::PointOpPoint(std::index_sequence<idx...>, const CompositePoint<Pos, Attribs...> &left, const CompositePoint<RightPos, RightAttribs...> &right)\n#ifdef MSVC_LIMITATIONS\n\t\t-> CompositePoint<Pos, Attribs...>\n#else\n\t\t-> CompositePoint<std::decay_t<decltype(std::declval<Functor>()(left.pos, right.pos))>, std::decay_t<decltype(std::declval<Functor>()(std::get<idx>(left.attribs), std::get<idx>(right.attribs)))>...>\n#endif\n\t{\n\t\tconstexpr Functor op;\n\t\treturn{ op(left.pos, right.pos), op(std::get<idx>(left.attribs), std::get<idx>(right.attribs))... };\n\t}\n\n\t// point op scalar\n\ttemplate<class Pos, class ...Attribs>\n\ttemplate<class Functor, size_t ...idx, typename Scalar>\n\tinline auto CompositePoint<Pos, Attribs...>::PointOpScalar(std::index_sequence<idx...>, const CompositePoint<Pos, Attribs...> &left, const Scalar &right)\n#ifdef MSVC_LIMITATIONS\n\t\t-> CompositePoint<Pos, Attribs...>\n#else\n\t\t-> CompositePoint<std::decay_t<decltype(std::declval<Functor>()(left.pos, right))>, std::decay_t<decltype(std::declval<Functor>()(std::get<idx>(left.attribs), right))>...>\n#endif\n\t{\n\t\tconstexpr Functor op;\n\t\treturn{ op(left.pos, right), op(std::get<idx>(left.attribs), right)... };\n\t}\n\n\t// scalar op point\n\ttemplate<class Pos, class ...Attribs>\n\ttemplate<class Functor, size_t ...idx, typename Scalar>\n\tinline auto CompositePoint<Pos, Attribs...>::ScalarOpPoint(std::index_sequence<idx...>, const Scalar &left, const CompositePoint<Pos, Attribs...> &right)\n#ifdef MSVC_LIMITATIONS\n\t\t-> CompositePoint<Pos, Attribs...>\n#else\n\t\t-> CompositePoint<std::decay_t<decltype(std::declval<Functor>()(left, right.pos))>, std::decay_t<decltype(std::declval<Functor>()(left, std::get<idx>(right.attribs)))>...>\n#endif\n\t{\n\t\tconstexpr Functor op;\n\t\treturn { op(left, right.pos), op(left, std::get<idx>(right.attribs))... };\n\t}\n\n\t// point op= point\n\ttemplate<class Pos, class ...Attribs>\n\ttemplate<class Functor, size_t idx, class SrcPos, class ...SrcAttribs>\n\tinline auto CompositePoint<Pos, Attribs...>::PointOpPoint(const CompositePoint<SrcPos, SrcAttribs...> &src) -> std::enable_if_t<idx < sizeof...(Attribs), CompositePoint &>\n\t{\n\t\tFunctor()(std::get<idx>(attribs), std::get<idx>(src.attribs));\n\t\treturn PointOpPoint<Functor, idx + 1>(src);\n\t}\n\n\ttemplate<class Pos, class ...Attribs>\n\ttemplate<class Functor, size_t idx, class SrcPos, class ...SrcAttribs>\n\tinline auto CompositePoint<Pos, Attribs...>::PointOpPoint(const CompositePoint<SrcPos, SrcAttribs...> &src) -> std::enable_if_t<idx == sizeof...(Attribs), CompositePoint &>\n\t{\n\t\tFunctor()(pos, src.pos);\n\t\treturn *this;\n\t}\n\n\t// point op= scalar\n\ttemplate<class Pos, class ...Attribs>\n\ttemplate<class Functor, size_t idx, typename Scalar>\n\tinline auto CompositePoint<Pos, Attribs...>::PointOpScalar(const Scalar &src) -> std::enable_if_t<idx < sizeof...(Attribs), CompositePoint &>\n\t{\n\t\tFunctor()(std::get<idx>(attribs), src);\n\t\treturn PointOpScalar<Functor, idx + 1>(src);\n\t}\n\n\ttemplate<class Pos, class ...Attribs>\n\ttemplate<class Functor, size_t idx, typename Scalar>\n\tinline auto CompositePoint<Pos, Attribs...>::PointOpScalar(const Scalar &src) -> std::enable_if_t<idx == sizeof...(Attribs), CompositePoint &>\n\t{\n\t\tFunctor()(pos, src);\n\t\treturn *this;\n\t}\n\n\ttemplate<class Pos, class ...Attribs>\n\ttemplate<class SrcPos, class ...SrcAttribs>\n\tinline CompositePoint<Pos, Attribs...>::CompositePoint(SrcPos &&pos, SrcAttribs &&...attribs) :\n\tpos(std::forward<SrcPos>(pos)), attribs(std::forward<SrcAttribs>(attribs)...) {}\n\n\ttemplate<class Pos, class ...Attribs>\n\ttemplate<class SrcPos, class ...SrcAttribs>\n\tinline CompositePoint<Pos, Attribs...>::CompositePoint(const CompositePoint<SrcPos, SrcAttribs...> &src) :\n\tpos(src.pos), attribs(src.attribs) {}\n\n\ttemplate<class Pos, class ...Attribs>\n\ttemplate<class SrcPos, class ...SrcAttribs>\n\tinline CompositePoint<Pos, Attribs...>::CompositePoint(CompositePoint<SrcPos, SrcAttribs...> &&src) :\n\tpos(std::move(src.pos)), attribs(std::move(src.attribs)) {}\n\n\ttemplate<class Pos, class ...Attribs>\n\ttemplate<class SrcPos, class ...SrcAttribs>\n\tinline auto CompositePoint<Pos, Attribs...>::operator =(const CompositePoint<SrcPos, SrcAttribs...> &src) -> CompositePoint &\n\t{\n\t\tpos = src.pos;\n\t\tattribs = src.attribs;\n\t\treturn *this;\n\t}\n\n\ttemplate<class Pos, class ...Attribs>\n\ttemplate<class SrcPos, class ...SrcAttribs>\n\tinline auto CompositePoint<Pos, Attribs...>::operator =(CompositePoint<SrcPos, SrcAttribs...> &&src) -> CompositePoint &\n\t{\n\t\tpos = std::move(src.pos);\n\t\tattribs = std::move(src.attribs);\n\t\treturn *this;\n\t}\n\n\ttemplate<class Pos, class ...Attribs>\n\tinline auto CompositePoint<Pos, Attribs...>::operator -() const\n\t{\n\t\treturn OpPoint<std::negate<>>(std::index_sequence_for<Attribs...>());\n\t}\n\n\t// point += point\n\ttemplate<class Pos, class ...Attribs>\n\ttemplate<class SrcPos, class ...SrcAttribs>\n\tinline auto CompositePoint<Pos, Attribs...>::operator +=(const CompositePoint<SrcPos, SrcAttribs...> &src) -> CompositePoint &\n\t{\n\t\treturn PointOpPoint<AddAssign>(src);\n\t}\n\n\t// point -= point\n\ttemplate<class Pos, class ...Attribs>\n\ttemplate<class SrcPos, class ...SrcAttribs>\n\tinline auto CompositePoint<Pos, Attribs...>::operator -=(const CompositePoint<SrcPos, SrcAttribs...> &src) -> CompositePoint &\n\t{\n\t\treturn PointOpPoint<SubAssign>(src);\n\t}\n\n\t// point *= scalar\n\ttemplate<class Pos, class ...Attribs>\n\ttemplate<typename Scalar>\n\tinline auto CompositePoint<Pos, Attribs...>::operator *=(const Scalar &src) -> CompositePoint &\n\t{\n\t\treturn PointOpScalar<MulAssign>(src);\n\t}\n\n\t// point /= scalar\n\ttemplate<class Pos, class ...Attribs>\n\ttemplate<typename Scalar>\n\tinline auto CompositePoint<Pos, Attribs...>::operator /=(const Scalar &src) -> CompositePoint &\n\t{\n\t\treturn PointOpScalar<DivAssign>(src);\n\t}\n\n\t// point + point\n\ttemplate<class LeftPos, class ...LeftAttribs, class RightPos, class ...RightAttribs>\n\tinline auto operator +(const CompositePoint<LeftPos, LeftAttribs...> &left, const CompositePoint<RightPos, RightAttribs...> &right)\n\t{\n\t\treturn CompositePoint<LeftPos, LeftAttribs...>::PointOpPoint<std::plus<>>(std::index_sequence_for<LeftAttribs...>(), left, right);\n\t}\n\n\t// point - point\n\ttemplate<class LeftPos, class ...LeftAttribs, class RightPos, class ...RightAttribs>\n\tinline auto operator -(const CompositePoint<LeftPos, LeftAttribs...> &left, const CompositePoint<RightPos, RightAttribs...> &right)\n\t{\n\t\treturn CompositePoint<LeftPos, LeftAttribs...>::PointOpPoint<std::minus<>>(std::index_sequence_for<LeftAttribs...>(), left, right);\n\t}\n\n\t// point * scalar\n\ttemplate<class Pos, class ...Attribs, typename Scalar>\n\tinline auto operator *(const CompositePoint<Pos, Attribs...> &left, const Scalar &right)\n\t{\n\t\treturn CompositePoint<Pos, Attribs...>::PointOpScalar<std::multiplies<>>(std::index_sequence_for<Attribs...>(), left, right);\n\t}\n\n\t// scalar * point\n\ttemplate<class Pos, class ...Attribs, typename Scalar>\n\tinline auto operator *(const Scalar &left, const CompositePoint<Pos, Attribs...> &right)\n\t{\n\t\treturn CompositePoint<Pos, Attribs...>::ScalarOpPoint<std::multiplies<>>(std::index_sequence_for<Attribs...>(), left, right);\n\t}\n\n\t// point / scalar\n\ttemplate<class Pos, class ...Attribs, typename Scalar>\n\tinline auto operator /(const CompositePoint<Pos, Attribs...> &left, const Scalar &right)\n\t{\n\t\treturn CompositePoint<Pos, Attribs...>::PointOpScalar<std::divides<>>(std::index_sequence_for<Attribs...>(), left, right);\n\t}\n}\n#pragma endregion\n\ntemplate<typename ScalarType, unsigned int dimension, unsigned int degree, class ...Attribs>\ntemplate<size_t ...idx>\ninline Math::Splines::CBezier<ScalarType, dimension, degree, Attribs...>::CBezier(const typename ControlPoints::value_type (&src)[degree + 1], std::index_sequence<idx...>) :\n\tcontrolPoints{ typename ControlPoints::value_type(src[idx])... } {}\n\ntemplate<typename ScalarType, unsigned int dimension, unsigned int degree, class ...Attribs>\nMath::Splines::CBezier<ScalarType, dimension, degree, Attribs...>::CBezier(const typename ControlPoints::value_type (&src)[degree + 1]) :\n\tCBezier(src, std::make_index_sequence<degree + 1>()) {}\n\ntemplate<typename ScalarType, unsigned int dimension, unsigned int degree, class ...Attribs>\nMath::Splines::CBezier<ScalarType, dimension, degree, Attribs...>::CBezier(const ControlPoints &controlPoints) :\n\tcontrolPoints(controlPoints) {}\n\ntemplate<typename ScalarType, unsigned int dimension, unsigned int degree, class ...Attribs>\nMath::Splines::CBezier<ScalarType, dimension, degree, Attribs...>::CBezier(ControlPoints &&controlPoints) :\n\tcontrolPoints(std::move(controlPoints)) {}\n\ntemplate<typename ScalarType, unsigned int dimension, unsigned int degree, class ...Attribs>\ntemplate<class ...Points>\nMath::Splines::CBezier<ScalarType, dimension, degree, Attribs...>::CBezier(Points &&...controlPoints) :\ncontrolPoints{ std::forward<Points>(controlPoints)... }\n{\n\tconstexpr auto count = degree + 1;\n\tstatic_assert(sizeof...(Points) >= count, \"too few control points\");\n\tstatic_assert(sizeof...(Points) <= count, \"too many control points\");\n}\n\n#ifndef MSVC_LIMITATIONS\ntemplate<typename ScalarType, unsigned int dimension, unsigned int degree, class ...Attribs>\ntemplate<size_t ...idx>\ninline auto Math::Splines::CBezier<ScalarType, dimension, degree, Attribs...>::operator ()(ScalarType u, std::index_sequence<idx...>) const -> typename ControlPoints::value_type\n{\n\tstatic_assert(degree >= 2);\n\tScalarType factor1 = u;\n\tconst ScalarType factors2[degree] = { 1 - u, factors2[idx] * factors2[0] ... };\n\tusing Combinatorics::C;\n\treturn C<degree, 0> * factors2[degree - 1] * controlPoints[0] +\n\t\tC<degree, 1> * factor1 * factors2[degree - 2] * controlPoints[1] +\n\t\t(C<degree, idx + 2> * (factor1 *= u) * factors2[degree - 3 - idx] * controlPoints[2 + idx] + ... + C<degree, degree> * factor1 * u * controlPoints[degree]);\n}\n#endif\n\ntemplate<typename ScalarType, unsigned int dimension, unsigned int degree, class ...Attribs>\nauto Math::Splines::CBezier<ScalarType, dimension, degree, Attribs...>::operator ()(ScalarType u) const -> typename ControlPoints::value_type\n{\n#ifdef MSVC_LIMITATIONS\n\tScalarType factor1 = 1, factors2[degree + 1];\n\tfactors2[degree] = 1;\n\tfor (signed i = degree - 1; i >= 0; i--)\n\t\tfactors2[i] = factors2[i + 1] * (1 - u);\n\tauto result = typename ControlPoints::value_type();\t// value init\n\tfor (unsigned i = 0; i <= degree; i++, factor1 *= u)\n\t\tresult += boost::math::binomial_coefficient<ScalarType>(degree, i) * factor1 * factors2[i] * controlPoints[i];\n\treturn result;\n#else\n\tif constexpr (degree == 0)\n\t\treturn controlPoints[0];\n\telse if constexpr (degree == 1)\n\t\treturn lerp(controlPoints[0], controlPoints[1], u);\n\telse\n\t\treturn operator ()(u, std::make_index_sequence<degree - 2>());\n#endif\n}\n\ntemplate<typename ScalarType, unsigned int dimension, unsigned int degree, class ...Attribs>\ntemplate<typename Iterator>\nvoid Math::Splines::CBezier<ScalarType, dimension, degree, Attribs...>::Tessellate(Iterator output, ScalarType delta, bool emitFirstPoint) const\n{\n\tif (emitFirstPoint) *output++ = controlPoints[0];\n\tSubdiv(output, delta, controlPoints);\n}\n\ntemplate<typename ScalarType, unsigned int dimension, unsigned int degree, class ...Attribs>\ntemplate<typename Iterator, size_t ...idx>\nvoid Math::Splines::CBezier<ScalarType, dimension, degree, Attribs...>::Subdiv(Iterator output, ScalarType delta, const ControlPoints &controlPoints, std::index_sequence<idx...>)\n{\n\t// TODO: move to Math\n\tconst auto point_line_dist = [](typename ControlPoints::const_reference point, typename ControlPoints::const_reference lineBegin, typename ControlPoints::const_reference lineEnd) -> ScalarType\n\t{\n\t\tconst auto point_dir = GetPos(point) - GetPos(lineBegin), line_dir = GetPos(lineEnd) - GetPos(lineBegin);\n\t\t// project point_dir on line_dir\n\t\tconst auto proj = dot(point_dir, line_dir) / dot(line_dir, line_dir) * line_dir;\n\t\treturn length(point_dir - proj);\n\t};\n\n\tconst auto stop_test = [&point_line_dist, &controlPoints, delta]\n\t{\n#ifdef MSVC_LIMITATIONS\n\t\tfor (unsigned i = 1; i < degree; i++)\n\t\t{\n\t\t\tif (point_line_dist(controlPoints[i], controlPoints[0], controlPoints[degree]) > delta)\n\t\t\t\treturn false;\n\t\t}\n\t\treturn true;\n#else\n\t\treturn (point_line_dist(controlPoints[idx + 1], controlPoints[0], controlPoints[degree]) > delta || ...);\n#endif\n\t};\n\n\tif (stop_test())\n\t\t*output++ = (controlPoints[degree]);\n\telse\n\t{\n\t\tconstexpr auto intermediate_points_count = (degree + 1) * 2 - 1;\n\t\ttypename ControlPoints::value_type intermediate_points[intermediate_points_count];\t// will hold control points for 2 subdivided curves (with 1 common point)\n\t\tfor (unsigned i = 0; i <= degree; i++)\n\t\t\tintermediate_points[i * 2] = controlPoints[i];\n\t\tfor (unsigned insert_idx_begin = 1, insert_idx_end = intermediate_points_count; insert_idx_begin <= degree; insert_idx_begin++, insert_idx_end--)\n\t\t{\n\t\t\tfor (unsigned insert_idx = insert_idx_begin; insert_idx < insert_idx_end; insert_idx += 2)\n\t\t\t\tintermediate_points[insert_idx] = lerp(intermediate_points[insert_idx - 1], intermediate_points[insert_idx + 1], ScalarType(.5));\n\t\t}\n\t\tSubdiv(output, delta, intermediate_points + 0);\n\t\tSubdiv(output, delta, intermediate_points + degree);\n\t}\n}\n\ntemplate<template<typename ScalarType, unsigned int dimension, class ...Attribs> class CBezierInterpolationImpl, typename ScalarType, unsigned int dimension, class ...Attribs>\ntemplate<typename Iterator>\nvoid Math::Splines::Impl::CBezierInterpolationCommon<CBezierInterpolationImpl, ScalarType, dimension, Attribs...>::Tessellate(Iterator output, ScalarType delta) const\n{\n\tfor (Points::size_type i = 1; i < points.size() - 2; i++)\n\t\tSegment(i).Tessellate(output, delta, i == 1);\n}\n\ntemplate<typename ScalarType, unsigned int dimension, class ...Attribs>\ntemplate<typename Iterator>\nMath::Splines::Impl::CCatmullRom<ScalarType, dimension, Attribs...>::CCatmullRom(Iterator begin, Iterator end) :\npoints(begin, end)\n{\n\tassert(points.size() >= 4);\n}\n\ntemplate<typename ScalarType, unsigned int dimension, class ...Attribs>\nMath::Splines::Impl::CCatmullRom<ScalarType, dimension, Attribs...>::CCatmullRom(std::initializer_list<Point> points) :\npoints(points)\n{\n\tassert(points.size() >= 4);\n}\n\ntemplate<typename ScalarType, unsigned int dimension, class ...Attribs>\nauto Math::Splines::Impl::CCatmullRom<ScalarType, dimension, Attribs...>::operator ()(ScalarType u) const -> Point\n{\n\t//assert(u >= 0 && u <= 1);\n\t// [0..1]->[0..m-2]->[1..m-1]\n\tu *= points.size() - 3, u++;\n\t// ensure 1 <= i < m\n\t//const Points::size_type i = std::min<Points::size_type>(floor(u), points.size() - 3);\n\tconst ScalarType i = fmin(fmax(floor(u), 1), points.size() - 3);\n\treturn Segment(i)(u - i);\n}\n\ntemplate<typename ScalarType, unsigned int dimension, class ...Attribs>\nauto Math::Splines::Impl::CCatmullRom<ScalarType, dimension, Attribs...>::Segment(typename Points::size_type i) const -> Bezier\n{\n\tassert(i >= 1 && i < points.size() - 2);\n\treturn { points[i], points[i] + (points[i + 1] - points[i - 1]) / 6, points[i + 1] - (points[i + 2] - points[i]) / 6, points[i + 1] };\n}\n\ntemplate<typename ScalarType, unsigned int dimension, class ...Attribs>\ntemplate<typename Iterator>\nMath::Splines::Impl::CBesselOverhauser<ScalarType, dimension, Attribs...>::CBesselOverhauser(Iterator begin, Iterator end)\n{\n\tReserve(points, begin, end);\n\tInit(begin, end);\n}\n\ntemplate<typename ScalarType, unsigned int dimension, class ...Attribs>\nMath::Splines::Impl::CBesselOverhauser<ScalarType, dimension, Attribs...>::CBesselOverhauser(std::initializer_list<Point> points)\n{\n\tthis->points.reserve(points.size());\n\tInit(points.begin(), points.end());\n}\n\ntemplate<typename ScalarType, unsigned int dimension, class ...Attribs>\ntemplate<typename Iterator>\nvoid Math::Splines::Impl::CBesselOverhauser<ScalarType, dimension, Attribs...>::Init(Iterator begin, Iterator end)\n{\n\tassert(begin != end);\n\tpoints.emplace_back(typename Points::value_type(0, *begin));\n\ttransform(std::next(begin), end, std::back_inserter(points), [this](const Point &curPoint)\n\t{\n\t\t/*\n\t\t\tit seems that 'std' namespace used here ('VectorMath::' before 'distance' required)\n\t\t\tTODO: try with other compilers\n\t\t*/\n\t\treturn typename Points::value_type(points.back().first + VectorMath::distance(GetPos(points.back().second), GetPos(curPoint)), curPoint);\n\t});\n\tassert(points.size() >= 4);\n}\n\ntemplate<typename ScalarType, unsigned int dimension, class ...Attribs>\nauto Math::Splines::Impl::CBesselOverhauser<ScalarType, dimension, Attribs...>::operator ()(ScalarType u) const -> Point\n{\n\t//assert(u >= 0 && u <= 1);\n\t// [0..1]->[u_begin..u_end]\n\tconst ScalarType u_begin = std::next(points.begin())->first, u_end = std::prev(points.end(), 2)->first;\n\tu *= u_end - u_begin, u += u_begin;\n\t// ensure u in [u_begin..u_end]\n\t//u = fmin(fmax(u, u_begin), u_end);\n\tstruct\n\t{\n\t\tbool operator ()(ScalarType left, typename Points::const_reference right) const\n\t\t{\n\t\t\treturn left < right.first;\n\t\t}\n\t\tbool operator ()(typename Points::const_reference left, ScalarType right) const\n\t\t{\n\t\t\treturn left.first < right;\n\t\t}\n\t} point_order;\n\tauto p1 = std::lower_bound(points.begin(), points.end(), u, point_order);\n\tif (std::distance(points.begin(), p1) < 2)\n\t\tp1 = std::next(points.begin(), 2);\n\telse if (std::distance(p1, points.end()) < 2)\n\t\tp1 = std::prev(points.end(), 2);\n\tconst auto p0 = std::prev(p1);\n\treturn Segment(std::distance(points.begin(), p0))((u - p0->first) / (p1->first - p0->first));\n}\n\ntemplate<typename ScalarType, unsigned int dimension, class ...Attribs>\nauto Math::Splines::Impl::CBesselOverhauser<ScalarType, dimension, Attribs...>::Segment(typename Points::size_type i) const -> Bezier\n{\n\tassert(i >= 1 && i < points.size() - 2);\n\tconst auto v_segment = [this](typename Points::size_type j)\n\t{\n\t\treturn (points[j + 1].second - points[j].second) / (points[j + 1].first - points[j].first);\n\t};\n\tconst Point segment_vels[3] = {v_segment(i - 1), v_segment(i), v_segment(i + 1)};\n\tconst auto offset = [this, &segment_vels, i](typename Points::size_type shift)\n\t{\n\t\treturn\n\t\t\t(\n\t\t\t\t(points[i + 1 + shift].first - points[i + shift].first) * segment_vels[0 + shift] +\n\t\t\t\t(points[i + shift].first - points[i - 1 + shift].first) * segment_vels[1 + shift]\n\t\t\t) /\n\t\t\t((points[i + 1 + shift].first - points[i - 1 + shift].first) * 3) *\n\t\t\t(points[i + 1].first - points[i].first);\n\t};\n\treturn { points[i].second, points[i].second + offset(0), points[i + 1].second - offset(1), points[i + 1].second };\n}", "meta": {"hexsha": "31b9e163399188305e7edd5d627f06b0afa560de", "size": 20220, "ext": "inl", "lang": "C++", "max_stars_repo_path": "General/splines.inl", "max_stars_repo_name": "ash3D/NextGen", "max_stars_repo_head_hexsha": "0288513ce85632738abc52a1dae5a4f70cead94d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 11.0, "max_stars_repo_stars_event_min_datetime": "2018-11-23T07:57:03.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-07T23:21:19.000Z", "max_issues_repo_path": "General/splines.inl", "max_issues_repo_name": "ash3D/NextGen", "max_issues_repo_head_hexsha": "0288513ce85632738abc52a1dae5a4f70cead94d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "General/splines.inl", "max_forks_repo_name": "ash3D/NextGen", "max_forks_repo_head_hexsha": "0288513ce85632738abc52a1dae5a4f70cead94d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-04-19T13:40:11.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-29T16:40:54.000Z", "avg_line_length": 41.7768595041, "max_line_length": 200, "alphanum_fraction": 0.709446093, "num_tokens": 5550, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.596433160611502, "lm_q2_score": 0.5078118642792044, "lm_q1q2_score": 0.302875835208065}}
{"text": "\r\n///////////////////////////////////////////////////////////////////////////////\r\n// density.hpp\r\n//\r\n//  Copyright 2006 Daniel Egloff, Olivier Gygi. Distributed under the Boost\r\n//  Software License, Version 1.0. (See accompanying file\r\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\r\n\r\n#ifndef BOOST_ACCUMULATORS_STATISTICS_DENSITY_HPP_DE_01_01_2006\r\n#define BOOST_ACCUMULATORS_STATISTICS_DENSITY_HPP_DE_01_01_2006\r\n\r\n#include <vector>\r\n#include <limits>\r\n#include <functional>\r\n#include <boost/range.hpp>\r\n#include <boost/parameter/keyword.hpp>\r\n#include <boost/mpl/placeholders.hpp>\r\n#include <boost/accumulators/accumulators_fwd.hpp>\r\n#include <boost/accumulators/framework/accumulator_base.hpp>\r\n#include <boost/accumulators/framework/extractor.hpp>\r\n#include <boost/accumulators/numeric/functional.hpp>\r\n#include <boost/accumulators/framework/parameters/sample.hpp>\r\n#include <boost/accumulators/framework/depends_on.hpp>\r\n#include <boost/accumulators/statistics_fwd.hpp>\r\n#include <boost/accumulators/statistics/count.hpp>\r\n#include <boost/accumulators/statistics/max.hpp>\r\n#include <boost/accumulators/statistics/min.hpp>\r\n\r\nnamespace boost { namespace accumulators\r\n{\r\n\r\n///////////////////////////////////////////////////////////////////////////////\r\n// cache_size and num_bins named parameters\r\n//\r\nBOOST_PARAMETER_NESTED_KEYWORD(tag, density_cache_size, cache_size)\r\nBOOST_PARAMETER_NESTED_KEYWORD(tag, density_num_bins, num_bins)\r\n\r\nBOOST_ACCUMULATORS_IGNORE_GLOBAL(density_cache_size)\r\nBOOST_ACCUMULATORS_IGNORE_GLOBAL(density_num_bins)\r\n\r\nnamespace impl\r\n{\r\n    ///////////////////////////////////////////////////////////////////////////////\r\n    // density_impl\r\n    //  density histogram\r\n    /**\r\n        @brief Histogram density estimator\r\n\r\n        The histogram density estimator returns a histogram of the sample distribution. The positions and sizes of the bins\r\n        are determined using a specifiable number of cached samples (cache_size). The range between the minimum and the\r\n        maximum of the cached samples is subdivided into a specifiable number of bins (num_bins) of same size. Additionally,\r\n        an under- and an overflow bin is added to capture future under- and overflow samples. Once the bins are determined,\r\n        the cached samples and all subsequent samples are added to the correct bins. At the end, a range of std::pair is\r\n        return, where each pair contains the position of the bin (lower bound) and the samples count (normalized with the\r\n        total number of samples).\r\n\r\n        @param  density_cache_size Number of first samples used to determine min and max.\r\n        @param  density_num_bins Number of bins (two additional bins collect under- and overflow samples).\r\n    */\r\n    template<typename Sample>\r\n    struct density_impl\r\n      : accumulator_base\r\n    {\r\n        typedef typename numeric::functional::average<Sample, std::size_t>::result_type float_type;\r\n        typedef std::vector<std::pair<float_type, float_type> > histogram_type;\r\n        typedef std::vector<float_type> array_type;\r\n        // for boost::result_of\r\n        typedef iterator_range<typename histogram_type::iterator> result_type;\r\n\r\n        template<typename Args>\r\n        density_impl(Args const &args)\r\n            : cache_size(args[density_cache_size])\r\n            , cache(cache_size)\r\n            , num_bins(args[density_num_bins])\r\n            , samples_in_bin(num_bins + 2, 0.)\r\n            , bin_positions(num_bins + 2)\r\n            , histogram(\r\n                num_bins + 2\r\n              , std::make_pair(\r\n                    numeric::average(args[sample | Sample()],(std::size_t)1)\r\n                  , numeric::average(args[sample | Sample()],(std::size_t)1)\r\n                )\r\n              )\r\n            , is_dirty(true)\r\n        {\r\n        }\r\n\r\n        template<typename Args>\r\n        void operator ()(Args const &args)\r\n        {\r\n            this->is_dirty = true;\r\n\r\n            std::size_t cnt = count(args);\r\n\r\n            // Fill up cache with cache_size first samples\r\n            if (cnt <= this->cache_size)\r\n            {\r\n                this->cache[cnt - 1] = args[sample];\r\n            }\r\n\r\n            // Once cache_size samples have been accumulated, create num_bins bins of same size between\r\n            // the minimum and maximum of the cached samples as well as under and overflow bins.\r\n            // Store their lower bounds (bin_positions) and fill the bins with the cached samples (samples_in_bin).\r\n            if (cnt == this->cache_size)\r\n            {\r\n                float_type minimum = numeric::average((min)(args), (std::size_t)1);\r\n                float_type maximum = numeric::average((max)(args), (std::size_t)1);\r\n                float_type bin_size = numeric::average(maximum - minimum, this->num_bins );\r\n\r\n                // determine bin positions (their lower bounds)\r\n                for (std::size_t i = 0; i < this->num_bins + 2; ++i)\r\n                {\r\n                    this->bin_positions[i] = minimum + (i - 1.) * bin_size;\r\n                }\r\n\r\n                for (typename array_type::const_iterator iter = this->cache.begin(); iter != this->cache.end(); ++iter)\r\n                {\r\n                    if (*iter < this->bin_positions[1])\r\n                    {\r\n                        ++(this->samples_in_bin[0]);\r\n                    }\r\n                    else if (*iter >= this->bin_positions[this->num_bins + 1])\r\n                    {\r\n                        ++(this->samples_in_bin[this->num_bins + 1]);\r\n                    }\r\n                    else\r\n                    {\r\n                        typename array_type::iterator it = std::upper_bound(\r\n                            this->bin_positions.begin()\r\n                          , this->bin_positions.end()\r\n                          , *iter\r\n                        );\r\n\r\n                        std::size_t d = std::distance(this->bin_positions.begin(), it);\r\n                        ++(this->samples_in_bin[d - 1]);\r\n                    }\r\n                }\r\n            }\r\n            // Add each subsequent sample to the correct bin\r\n            else if (cnt > this->cache_size)\r\n            {\r\n                if (args[sample] < this->bin_positions[1])\r\n                {\r\n                    ++(this->samples_in_bin[0]);\r\n                }\r\n                else if (args[sample] >= this->bin_positions[this->num_bins + 1])\r\n                {\r\n                    ++(this->samples_in_bin[this->num_bins + 1]);\r\n                }\r\n                else\r\n                {\r\n                    typename array_type::iterator it = std::upper_bound(\r\n                        this->bin_positions.begin()\r\n                      , this->bin_positions.end()\r\n                      , args[sample]\r\n                    );\r\n\r\n                    std::size_t d = std::distance(this->bin_positions.begin(), it);\r\n                    ++(this->samples_in_bin[d - 1]);\r\n                }\r\n            }\r\n        }\r\n\r\n        /**\r\n            @pre The number of samples must meet or exceed the cache size\r\n        */\r\n        template<typename Args>\r\n        result_type result(Args const &args) const\r\n        {\r\n            if (this->is_dirty)\r\n            {\r\n                this->is_dirty = false;\r\n\r\n                // creates a vector of std::pair where each pair i holds\r\n                // the values bin_positions[i] (x-axis of histogram) and\r\n                // samples_in_bin[i] / cnt (y-axis of histogram).\r\n\r\n                for (std::size_t i = 0; i < this->num_bins + 2; ++i)\r\n                {\r\n                    this->histogram[i] = std::make_pair(this->bin_positions[i], numeric::average(this->samples_in_bin[i], count(args)));\r\n                }\r\n            }\r\n            // returns a range of pairs\r\n            return make_iterator_range(this->histogram);\r\n        }\r\n\r\n    private:\r\n        std::size_t            cache_size;      // number of cached samples\r\n        array_type             cache;           // cache to store the first cache_size samples\r\n        std::size_t            num_bins;        // number of bins\r\n        array_type             samples_in_bin;  // number of samples in each bin\r\n        array_type             bin_positions;   // lower bounds of bins\r\n        mutable histogram_type histogram;       // histogram\r\n        mutable bool is_dirty;\r\n    };\r\n\r\n} // namespace impl\r\n\r\n///////////////////////////////////////////////////////////////////////////////\r\n// tag::density\r\n//\r\nnamespace tag\r\n{\r\n    struct density\r\n      : depends_on<count, min, max>\r\n      , density_cache_size\r\n      , density_num_bins\r\n    {\r\n        /// INTERNAL ONLY\r\n        ///\r\n        typedef accumulators::impl::density_impl<mpl::_1> impl;\r\n\r\n        #ifdef BOOST_ACCUMULATORS_DOXYGEN_INVOKED\r\n        /// tag::density::cache_size named parameter\r\n        /// tag::density::num_bins named parameter\r\n        static boost::parameter::keyword<density_cache_size> const cache_size;\r\n        static boost::parameter::keyword<density_num_bins> const num_bins;\r\n        #endif\r\n    };\r\n}\r\n\r\n///////////////////////////////////////////////////////////////////////////////\r\n// extract::density\r\n//\r\nnamespace extract\r\n{\r\n    extractor<tag::density> const density = {};\r\n\r\n    BOOST_ACCUMULATORS_IGNORE_GLOBAL(density)\r\n}\r\n\r\nusing extract::density;\r\n\r\n// So that density can be automatically substituted\r\n// with weighted_density when the weight parameter is non-void.\r\ntemplate<>\r\nstruct as_weighted_feature<tag::density>\r\n{\r\n    typedef tag::weighted_density type;\r\n};\r\n\r\ntemplate<>\r\nstruct feature_of<tag::weighted_density>\r\n  : feature_of<tag::density>\r\n{\r\n};\r\n\r\n}} // namespace boost::accumulators\r\n\r\n#endif\r\n", "meta": {"hexsha": "b426329a60b90c250e8d350c93984c19359a1dec", "size": 9746, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "BoostSharp/include/boost/accumulators/statistics/density.hpp", "max_stars_repo_name": "Icenium/BoostSharp", "max_stars_repo_head_hexsha": "1dd31065fcd65ae6304b182c558bac7c7a738ad5", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2017-05-11T05:30:19.000Z", "max_stars_repo_stars_event_max_datetime": "2019-04-24T05:41:33.000Z", "max_issues_repo_path": "src/third_party/boost/boost/accumulators/statistics/density.hpp", "max_issues_repo_name": "wugh7125/installwizard", "max_issues_repo_head_hexsha": "42f8aeb78026ff81838528968b1503e73f6c2864", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/third_party/boost/boost/accumulators/statistics/density.hpp", "max_forks_repo_name": "wugh7125/installwizard", "max_forks_repo_head_hexsha": "42f8aeb78026ff81838528968b1503e73f6c2864", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-03-26T17:00:08.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-26T17:00:08.000Z", "avg_line_length": 38.828685259, "max_line_length": 137, "alphanum_fraction": 0.5481223066, "num_tokens": 1932, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5964331462646255, "lm_q2_score": 0.5078118642792044, "lm_q1q2_score": 0.3028758279225509}}
{"text": "//\n//  Copyright (c) 2013, Novartis Institutes for BioMedical Research 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\n// met:\n//\n//     * Redistributions of source code must retain the above copyright\n//       notice, this list of conditions and the following disclaimer.\n//     * Redistributions in binary form must reproduce the above\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 Novartis Institutes for BioMedical Research Inc.\n//       nor the names of its contributors may be used to endorse or promote\n//       products 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 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#include <Geometry/point.h>\n#include <Numerics/Vector.h>\n#include <GraphMol/RDKitBase.h>\n#include <GraphMol/SmilesParse/SmilesParse.h>\n#include <GraphMol/Substruct/SubstructMatch.h>\n#include \"USRDescriptor.h\"\n\n#include <boost/flyweight.hpp>\n#include <boost/flyweight/key_value.hpp>\n#include <boost/flyweight/no_tracking.hpp>\n\nnamespace RDKit {\n\nnamespace {\nvoid calcDistances(const RDGeom::Point3DConstPtrVect &coords,\n                   const RDGeom::Point3D &point,\n                   std::vector<double> &distances) {\n  distances.resize(coords.size());\n  unsigned int i = 0;\n  // loop over coordinates\n  for (const auto *tpp : coords) {\n    distances[i++] = (*tpp - point).length();\n  }\n}\n\nvoid calcCentroid(const RDGeom::Point3DConstPtrVect &coords,\n                  RDGeom::Point3D &pt) {\n  PRECONDITION(!coords.empty(), \"no coordinates\");\n  // set pt to zero\n  pt *= 0.0;\n  // loop over coordinates\n  for (const auto *opt : coords) {\n    pt += *opt;\n  }\n  pt /= coords.size();\n}\n\nunsigned int largestValId(const std::vector<double> &v) {\n  PRECONDITION(!v.empty(), \"no values\");\n  double res = v[0];\n  unsigned int id = 0;\n  for (unsigned int i = 1; i < v.size(); ++i) {\n    if (v[i] > res) {\n      res = v[i];\n      id = i;\n    }\n  }\n  return id;\n}\n\nunsigned int smallestValId(const std::vector<double> &v) {\n  PRECONDITION(!v.empty(), \"no values\");\n  double res = v[0];\n  unsigned int id = 0;\n  for (unsigned int i = 1; i < v.size(); ++i) {\n    if (v[i] < res) {\n      res = v[i];\n      id = i;\n    }\n  }\n  return id;\n}\n\nvoid calcMoments(const std::vector<double> &dist,\n                 std::vector<double> &descriptor, int idx) {\n  std::vector<double> moments(3, 0.0);\n  unsigned int numPts = dist.size();\n  if (numPts > 0) {\n    // 1. moment: mean\n    for (unsigned int i = 0; i < numPts; ++i) {\n      moments[0] += dist[i];\n    }\n    moments[0] /= numPts;\n    // 2. moment: standard deviation\n    // 3. moment: cubic root of skewness\n    for (unsigned int i = 0; i < numPts; ++i) {\n      double diff = dist[i] - moments[0];\n      moments[1] += diff * diff;\n      moments[2] += diff * diff * diff;\n    }\n    moments[1] = sqrt(moments[1] / numPts);\n    moments[2] /= numPts;\n    if (moments[1] == 0) {\n      moments[2] = 0.0;\n    } else {\n#ifdef WIN32\n      moments[2] = moments[2] / (moments[1] * moments[1] * moments[1]);\n      if (moments[2] >= 0)\n        moments[2] = pow(moments[2], 1. / 3.);\n      else\n        moments[2] = -1. * pow(-1. * moments[2], 1. / 3.);\n#else\n      moments[2] = cbrt(moments[2] / (moments[1] * moments[1] * moments[1]));\n#endif\n    }\n  }\n  // add moments to descriptor\n  std::copy(moments.begin(), moments.end(), descriptor.begin() + idx);\n}\n\nclass ss_matcher {\n public:\n  ss_matcher(){};\n  ss_matcher(const std::string &pattern) {\n    RDKit::RWMol *p = RDKit::SmartsToMol(pattern);\n    TEST_ASSERT(p);\n    m_matcher.reset(p);\n  };\n  const RDKit::ROMol *getMatcher() const { return m_matcher.get(); };\n\n private:\n  RDKit::ROMOL_SPTR m_matcher;\n};\n\n// Definitions for feature points from\n// https://bitbucket.org/aschreyer/usrcat/src/2aa77f970c2c/usrcat/__init__.py\nconst char *smartsPatterns[4] = {\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$([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};\nstd::vector<std::string> featureSmarts(smartsPatterns, smartsPatterns + 4);\ntypedef boost::flyweight<boost::flyweights::key_value<std::string, ss_matcher>,\n                         boost::flyweights::no_tracking>\n    pattern_flyweight;\n\nvoid getAtomIdsForFeatures(const ROMol &mol,\n                           std::vector<std::vector<unsigned int>> &atomIds) {\n  unsigned int numFeatures = featureSmarts.size();\n  PRECONDITION(atomIds.size() == numFeatures,\n               \"atomIds must have be the same size as featureSmarts\");\n  std::vector<const ROMol *> featureMatchers;\n  featureMatchers.reserve(numFeatures);\n  for (const auto &feature : featureSmarts) {\n    const ROMol *matcher = pattern_flyweight(feature).get().getMatcher();\n    featureMatchers.push_back(matcher);\n  }\n  for (unsigned int i = 0; i < numFeatures; ++i) {\n    std::vector<MatchVectType> matchVect;\n    // to maintain thread safety, we have to copy the pattern molecules:\n    SubstructMatch(mol, ROMol(*featureMatchers[i], true), matchVect);\n    for (const auto &mv : matchVect) {\n      for (auto mi : mv) {\n        atomIds[i].push_back(mi.second);\n      }\n    }\n  }  // end loop over features\n}\n\n}  // end namespace\n\nnamespace Descriptors {\n\nvoid USR(const ROMol &mol, std::vector<double> &descriptor, int confId) {\n  PRECONDITION(descriptor.size() == 12, \"descriptor must have 12 elements\");\n  unsigned int na = mol.getNumAtoms();\n  // check that number of atoms > 3\n  if (na < 3) {\n    throw ValueErrorException(\"Number of atoms must be greater than 3\");\n  }\n  // check that minimum a conformer exists\n  if (mol.getNumConformers() == 0) {\n    throw ConformerException(\"No conformations available on this molecule\");\n  }\n\n  const Conformer &conf = mol.getConformer(confId);\n  RDGeom::Point3DConstPtrVect coords(na);\n  // loop over atoms\n  for (unsigned int ai = 0; ai < na; ++ai) {\n    coords[ai] = &conf.getAtomPos(ai);\n  }\n  // the four distances\n  std::vector<std::vector<double>> dist(4);\n  std::vector<RDGeom::Point3D> points(4);\n  calcUSRDistributions(coords, dist, points);\n\n  calcUSRFromDistributions(dist, descriptor);\n}\n\nvoid USRCAT(const ROMol &mol, std::vector<double> &descriptor,\n            std::vector<std::vector<unsigned int>> &atomIds, int confId) {\n  unsigned int na = mol.getNumAtoms();\n  // check that number of atoms > 3\n  if (na < 3) {\n    throw ValueErrorException(\"Number of atoms must be greater than 3\");\n  }\n  // check that minimum a conformer exists\n  if (mol.getNumConformers() == 0) {\n    throw ConformerException(\"No conformations available on this molecule\");\n  }\n\n  // get atom selections\n  unsigned int numClasses = atomIds.size();\n  if (numClasses == 0) {  // no user input, use default values\n    numClasses = featureSmarts.size();\n    atomIds.resize(numClasses);\n    getAtomIdsForFeatures(mol, atomIds);\n  }\n  PRECONDITION(descriptor.size() == 12 * (numClasses + 1),\n               \"descriptor wrong size\");\n\n  const Conformer &conf = mol.getConformer(confId);\n  RDGeom::Point3DConstPtrVect coords(na);\n  // loop over atoms\n  for (unsigned int ai = 0; ai < na; ++ai) {\n    coords[ai] = &conf.getAtomPos(ai);\n  }\n  // the original USR\n  std::vector<std::vector<double>> distribs(4);\n  std::vector<RDGeom::Point3D> points(4);\n  calcUSRDistributions(coords, distribs, points);\n  std::vector<double> tmpDescriptor(12);\n  calcUSRFromDistributions(distribs, tmpDescriptor);\n  std::copy(tmpDescriptor.begin(), tmpDescriptor.end(), descriptor.begin());\n\n  // loop over the atom selections\n  unsigned int featIdx = 12;\n  for (const auto &atomsInClass : atomIds) {\n    // reduce the coordinates to the atoms of interest\n    RDGeom::Point3DConstPtrVect reducedCoords;\n    reducedCoords.reserve(atomsInClass.size());\n    for (const auto idx : atomsInClass) {\n      reducedCoords.push_back(coords[idx]);\n    }\n    calcUSRDistributionsFromPoints(reducedCoords, points, distribs);\n    calcUSRFromDistributions(distribs, tmpDescriptor);\n    std::copy(tmpDescriptor.begin(), tmpDescriptor.end(),\n              descriptor.begin() + featIdx);\n    featIdx += 12;\n  }\n}\n\nvoid calcUSRDistributions(const RDGeom::Point3DConstPtrVect &coords,\n                          std::vector<std::vector<double>> &dist,\n                          std::vector<RDGeom::Point3D> &points) {\n  PRECONDITION(dist.size() == 4, \"dist must have 4 elements\");\n  PRECONDITION(points.size() == 4, \"points must have 4 elements\");\n  // ctd = centroid\n  calcCentroid(coords, points[0]);\n  calcDistances(coords, points[0], dist[0]);\n  // catc = closest atom to centroid\n  points[1] = (*coords[smallestValId(dist[0])]);\n  calcDistances(coords, points[1], dist[1]);\n  // fatc = farthest atom to centroid\n  points[2] = (*coords[largestValId(dist[0])]);\n  calcDistances(coords, points[2], dist[2]);\n  // fatf = farthest atom to fatc\n  points[3] = (*coords[largestValId(dist[2])]);\n  calcDistances(coords, points[3], dist[3]);\n}\n\nvoid calcUSRDistributionsFromPoints(const RDGeom::Point3DConstPtrVect &coords,\n                                    const std::vector<RDGeom::Point3D> &points,\n                                    std::vector<std::vector<double>> &dist) {\n  PRECONDITION(points.size() == dist.size(),\n               \"points and dist must have the same size\");\n  for (unsigned int i = 0; i < points.size(); ++i) {\n    calcDistances(coords, points[i], dist[i]);\n  }\n}\n\nvoid calcUSRFromDistributions(const std::vector<std::vector<double>> &dist,\n                              std::vector<double> &descriptor) {\n  PRECONDITION(descriptor.size() == 3 * dist.size(),\n               \"descriptor must have 3 times more elements than dist\");\n  for (unsigned int i = 0; i < dist.size(); ++i) {\n    calcMoments(dist[i], descriptor, 3 * i);\n  }\n}\n\ndouble calcUSRScore(const std::vector<double> &d1,\n                    const std::vector<double> &d2,\n                    const std::vector<double> &weights) {\n  unsigned int num = 12;  // length of each subset\n  PRECONDITION(d1.size() == d2.size(), \"descriptors must have the same size\");\n  PRECONDITION(weights.size() == (d1.size() / num),\n               \"size of weights not correct\");\n  double score = 1.0;\n  for (unsigned int w = 0; w < (d1.size() / num); ++w) {\n    double tmpScore = 0.0;\n    unsigned int offset = num * w;\n    for (unsigned int i = 0; i < num; ++i) {\n      tmpScore += fabs(d1[i + offset] - d2[i + offset]);\n    }\n    tmpScore /= num;\n    score += weights[w] * tmpScore;\n  }\n  return 1.0 / score;\n}\n\n}  // end of namespace Descriptors\n}  // end of namespace RDKit\n", "meta": {"hexsha": "a31d617f9ac20af99c5dda1498b82adc06b7d06f", "size": 11692, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Code/GraphMol/Descriptors/USRDescriptor.cpp", "max_stars_repo_name": "kazuyaujihara/rdkit", "max_stars_repo_head_hexsha": "06027dcd05674787b61f27ba46ec0d42a6037540", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1609.0, "max_stars_repo_stars_event_min_datetime": "2015-01-05T02:41:13.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T21:57:24.000Z", "max_issues_repo_path": "Code/GraphMol/Descriptors/USRDescriptor.cpp", "max_issues_repo_name": "kazuyaujihara/rdkit", "max_issues_repo_head_hexsha": "06027dcd05674787b61f27ba46ec0d42a6037540", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 3412.0, "max_issues_repo_issues_event_min_datetime": "2015-01-06T12:13:33.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T17:25:41.000Z", "max_forks_repo_path": "Code/GraphMol/Descriptors/USRDescriptor.cpp", "max_forks_repo_name": "kazuyaujihara/rdkit", "max_forks_repo_head_hexsha": "06027dcd05674787b61f27ba46ec0d42a6037540", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 811.0, "max_forks_repo_forks_event_min_datetime": "2015-01-11T03:33:48.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T11:57:49.000Z", "avg_line_length": 35.755351682, "max_line_length": 79, "alphanum_fraction": 0.6400102634, "num_tokens": 3236, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5964331462646254, "lm_q2_score": 0.5078118642792044, "lm_q1q2_score": 0.30287582792255086}}
{"text": "/* ------------------------------------------------------------------------- */\n/* UMFPACK Version 4.1 (Apr. 30, 2003), Copyright (c) 2003 by Timothy A.     */\n/* Davis.  All Rights Reserved.  See ../README for License.                  */\n/* email: davis@cise.ufl.edu    CISE Department, Univ. of Florida.           */\n/* web: http://www.cise.ufl.edu/research/sparse/umfpack                      */\n/* ------------------------------------------------------------------------- */\n\n\n/***********************************************************************/\n/*         UMFPACK Copyright, License and Availability                 */\n/***********************************************************************/\n/*\n *\n * UMFPACK Version 4.1 (Apr. 30, 2003),  Copyright (c) 2003 by Timothy A.\n * Davis.  All Rights Reserved.\n *\n * UMFPACK License:\n *\n *   Your use or distribution of UMFPACK or any modified version of\n *   UMFPACK implies that you agree to this License.\n *\n *   THIS MATERIAL IS PROVIDED AS IS, WITH ABSOLUTELY NO WARRANTY\n *   EXPRESSED OR IMPLIED.  ANY USE IS AT YOUR OWN RISK.\n *\n *   Permission is hereby granted to use or copy this program, provided\n *   that the Copyright, this License, and the Availability of the original\n *   version is retained on all copies.  User documentation of any code that\n *   uses UMFPACK or any modified version of UMFPACK code must cite the\n *   Copyright, this License, the Availability note, and \"Used by permission.\"\n *   Permission to modify the code and to distribute modified code is granted,\n *   provided the Copyright, this License, and the Availability note are\n *   retained, and a notice that the code was modified is included.  This\n *   software was developed with support from the National Science Foundation,\n *   and is provided to you free of charge.\n *\n * Availability:\n *\n *   http://www.cise.ufl.edu/research/sparse/umfpack\n *\n */\n\n/* Used by permission. */\n\n\n/* Simple demo program for UMFPACK               */\n/* from UMFPACK Version 4.1 Quick Start Guide    */\n\n/* modified by Kresimir Fresl, 2003              */\n/* UMFPACK bindings & ublas::compressed_matrix<> */\n\n\n#if !defined(TEST_MATLIB_UBLAS) && !defined(TEST_MATLIB_GLAS) && !defined(TEST_MATLIB_MTL) && !defined(TEST_MATLIB_EIGEN)\n#define TEST_MATLIB_UBLAS\n#endif\n\n#include <iostream>\n#include <boost/numeric/bindings/umfpack/umfpack.hpp>\n#include <boost/numeric/bindings/ublas/vector.hpp>\n#include <boost/numeric/ublas/io.hpp>\n\n#if defined(TEST_MATLIB_UBLAS)\n\n#include <boost/numeric/bindings/ublas/matrix_sparse.hpp>\nnamespace ublas = boost::numeric::ublas;\ntypedef ublas::compressed_matrix<double, ublas::column_major, 0, \n    ublas::unbounded_array<int>, ublas::unbounded_array<double> > m_t;\ntypedef m_t& mi_t;\n#define AA(i,j, val) a(i,j) = val\n\n#elif defined(TEST_MATLIB_GLAS)\n\n#include <boost/numeric/bindings/glas/compressed.hpp>\ntypedef glas::sparse_matrix< double, glas::compressed_sparse_structure<\n    glas::column_orientation, std::ptrdiff_t, std::ptrdiff_t, 0> > m_t;\ntypedef m_t& mi_t;\n#define AA(i,j, val) insert(a,i,j, val)\n\n#elif defined(TEST_MATLIB_MTL)\n\n#include <boost/numeric/bindings/mtl/compressed2D.hpp>\ntypedef mtl::compressed2D<double, mtl::matrix::parameters<mtl::tag::col_major> > m_t;\ntypedef mtl::matrix::inserter<m_t> mi_t;\n#define AA(i,j, val) a(i,j) = val\n\n#elif defined(TEST_MATLIB_EIGEN)\n\n#include <boost/numeric/bindings/eigen/sparsematrix.hpp>\ntypedef Eigen::SparseMatrix<double> m_t;\ntypedef Eigen::RandomSetter<m_t> mi_t;\n#define AA(i,j, val) a(i,j) = val\n\n#endif\n\ntypedef boost::numeric::ublas::vector<double> v_t;\nnamespace umf = boost::numeric::bindings::umfpack;\n\nint main() {\n\n  m_t A (5,5\n#if !defined(TEST_MATLIB_EIGEN)\n        ,12\n#endif\n        );\n  v_t B (5), X (5);\n\n  {\n    mi_t a(A);\n    AA(0,0, 2.); AA(0,1, 3.);\n    AA(1,0, 3.); AA(1,2, 4.); AA(1,4, 6.);\n    AA(2,1,-1.); AA(2,2,-3.); AA(2,3, 2.);\n    AA(3,2, 1.);\n    AA(4,1, 4.); AA(4,2, 2.); AA(4,4, 1.);\n  }\n  B(0) = 8.; B(1) = 45.; B(2) = -3.; B(3) = 3.; B(4) = 19.;\n\n  umf::symbolic_type<double> Symbolic;\n  umf::numeric_type<double> Numeric;\n\n  umf::symbolic (A, Symbolic);\n  umf::numeric (A, Symbolic, Numeric);\n  umf::solve (A, X, B, Numeric);\n\n  std::cout << X << std::endl;  // output: [5](1,2,3,4,5)\n}\n", "meta": {"hexsha": "b36f88fcc811d46736d767403011ccc1cbda6bf0", "size": 4250, "ext": "cc", "lang": "C++", "max_stars_repo_path": "externals/numeric_bindings/libs/numeric/bindings/umfpack/test/umfpack_simple.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/umfpack/test/umfpack_simple.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/umfpack/test/umfpack_simple.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": 34.0, "max_line_length": 121, "alphanum_fraction": 0.6232941176, "num_tokens": 1208, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.30287582792255086}}
{"text": "/*=========================================================================\n Program:   ORFEO Toolbox\n Language:  C++\n Date:      $Date$\n Version:   $Revision$\n Created By:Bouceffa Walid\n Email:\t    bouceffa.walid@gmail.com\n\n\n Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.\n See OTBCopyright.txt for details.\n\n\n This software is distributed WITHOUT ANY WARRANTY; without even\n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n PURPOSE.  See the above copyright notices for more information.\n\n =========================================================================*/\n\n#include \"otbFeatureSelection.h\"\n\n#include <boost/smart_ptr.hpp>\n#include <exception>\n#include <iostream>\n#include <cstdlib>\n#include <string>\n#include <vector>\n#include \"error.hpp\"\n#include \"global.hpp\"\n#include \"subset.hpp\"\n\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_holdout.hpp\"\n//#include \"data_splitter_leave1out.hpp\"\n//#include \"data_splitter_resub.hpp\"\n#include \"data_splitter_randrand.hpp\"\n//#include \"data_splitter_randfix.hpp\"\n#include \"data_scaler.hpp\"\n#include \"data_scaler_void.hpp\"\n//#include \"data_scaler_to01.hpp\"\n//#include \"data_scaler_white.hpp\"\n\n#include \"data_accessor_splitting_memOTB.hpp\"\n\n#include \"criterion_normal_bhattacharyya.hpp\"\n//#include \"criterion_normal_gmahalanobis.hpp\"\n//#include \"criterion_normal_divergence.hpp\"\n//#include \"criterion_multinom_bhattacharyya.hpp\"\n#include \"criterion_wrapper.hpp\"\n//#include \"criterion_wrapper_bias_estimate.hpp\"\n//#include \"criterion_subsetsize.hpp\"\n//#include \"criterion_sumofweights.hpp\"\n//#include \"criterion_negative.hpp\"\n\n#include \"distance_euclid.hpp\"\n//#include \"distance_L1.hpp\"\n#include \"distance_Lp.hpp\"\n#include \"classifier_knn.hpp\"\n//#include \"classifier_normal_bayes.hpp\"\n//#include \"classifier_multinom_naivebayes.hpp\"\n#include \"classifier_svm.hpp\"\n\n//#include \"search_bif.hpp\"\n//#include \"search_bif_threaded.hpp\"\n\n\n//#include \"search_exhaustive.hpp\"\n//#include \"search_exhaustive_threaded.hpp\"\n#include \"branch_and_bound_predictor_averaging.hpp\"\n//#include \"search_branch_and_bound_basic.hpp\"\n#include \"search_branch_and_bound_improved.hpp\"\n#include \"search_branch_and_bound_partial_prediction.hpp\"\n#include \"search_branch_and_bound_fast.hpp\"\n#include \"seq_step_straight.hpp\"\n//#include \"seq_step_straight_threaded.hpp\"\n//#include \"seq_step_hybrid.hpp\"\n//#include \"seq_step_ensemble.hpp\"\n//#include \"search_seq_sfs.hpp\"\n#include \"search_seq_sffs.hpp\"\n//#include \"search_seq_sfrs.hpp\"\n//#include \"search_seq_os.hpp\"\n#include \"search_seq_dos.hpp\"\n#include \"result_tracker_dupless.hpp\"\n//#include \"result_tracker_regularizer.hpp\"\n#include \"result_tracker_feature_stats.hpp\"\n//#include \"result_tracker_stabileval.hpp\"\n\nnamespace otb\n{\nnamespace Wrapper\n{\n\ntypedef double RETURNTYPE;\ntypedef float DATATYPE;\ntypedef double REALTYPE;\ntypedef int IDXTYPE;\ntypedef unsigned int DIMTYPE;\ntypedef short BINTYPE;\ntypedef FST::Subset<BINTYPE, DIMTYPE> SUBSET;\n\n\ntypedef FST::Data_Intervaller<std::vector<FST::Data_Interval<IDXTYPE> >,IDXTYPE> INTERVALLER;\ntypedef boost::shared_ptr<FST::Data_Splitter<INTERVALLER,IDXTYPE> > PSPLITTER;\ntypedef FST::Data_Splitter_CV<INTERVALLER,IDXTYPE> SPLITTERCV;\ntypedef FST::Data_Splitter_5050<INTERVALLER,IDXTYPE> SPLITTER5050;\ntypedef FST::Data_Splitter_RandomRandom<INTERVALLER,IDXTYPE,BINTYPE> SPLITTERRR;\ntypedef FST::Data_Accessor_Splitting_MemOTB<DATATYPE,IDXTYPE,INTERVALLER> DATAACCESSOR;\ntypedef FST::Distance_Euclid<DATATYPE,DIMTYPE,SUBSET> DISTANCE;\n\ntypedef FST::Classifier_kNN<RETURNTYPE,DATATYPE,IDXTYPE,DIMTYPE,SUBSET,DATAACCESSOR,DISTANCE> CLASSIFIERKNN;\ntypedef FST::Classifier_LIBSVM<RETURNTYPE,IDXTYPE,DIMTYPE,SUBSET,DATAACCESSOR> CLASSIFIERSVM;\n\ntypedef FST::Criterion_Wrapper<RETURNTYPE,SUBSET,CLASSIFIERKNN,DATAACCESSOR> WRAPPERKNN;\ntypedef FST::Criterion_Wrapper<RETURNTYPE,SUBSET,CLASSIFIERSVM,DATAACCESSOR> WRAPPERSVM;\n\ntypedef FST::Sequential_Step_Straight<RETURNTYPE,DIMTYPE,SUBSET,WRAPPERKNN> EVALUATOR;\ntypedef FST::Sequential_Step_Straight<RETURNTYPE,DIMTYPE,SUBSET,WRAPPERSVM> EVALUATOR_SVM;\n\n\ntypedef FST::Result_Tracker_Feature_Stats<RETURNTYPE,IDXTYPE,DIMTYPE,SUBSET> TRACKERSTATS;\n\n\nvoid FeatureSelection::InitFSTParams()\n{\n  \n   AddChoice ( \"method.sffs\", \"sffs Wrapper-based feature selection with Floating Search\" );\n   AddParameter ( ParameterType_Choice, \"method.sffs.searchdirection\", \"Sequential Forward Floating Selection search procedure\" );\n   AddChoice(\"method.sffs.searchdirection.forward\", \"forward search \");\n   AddChoice(\"method.sffs.searchdirection.backward\", \"backward search \");\n   SetParameterString(\"method.sffs.searchdirection\", \"forward\"); \n    \n\n   AddChoice ( \"method.dos\", \"dos Combined feature subset contents, size and SVM parameters optimization..\" );\n   AddParameter ( ParameterType_Choice, \"method.dos.svmkernel\", \"svm kernel to use \" );\n   AddChoice(\"method.dos.svmkernel.linear\", \"linear kernel\");\n   AddChoice(\"method.dos.svmkernel.rbf\", \"rbf kernel  \");\n   AddChoice(\"method.dos.svmkernel.poly\", \"poly kernel \");   \n   SetParameterString(\"method.dos.svmkernel\", \"rbf\");     \n}\n\n\nFeatureSelection::ImportanceVector FeatureSelection::getFeatureImportanceDOS ( ListSampleType::Pointer trainingListSample,\n        LabelListSampleType::Pointer trainingLabeledListSample )\n{\n\n  \n          std::cout << \"Starting (Missing data substitution) Combined feature subset contents, size and SVM parameters optimization...\" << std::endl;\n        // randomly sample 50% of data for training and randomly sample (disjunct) 40% for independent testing of final classification performance\n        PSPLITTER dsp_outer ( new SPLITTERRR ( 1, 50, 40 ) ); // (there will be one outer randomized split only)\n        // in the course of search use the first half of data by 3-fold cross-validation in wrapper FS criterion evaluation\n        PSPLITTER dsp_inner ( new SPLITTERCV ( 3 ) );\n        // do not scale data\n        const DATATYPE missing_value_code=5;\n        boost::shared_ptr<FST::Data_Scaler<DATATYPE> > dsc ( new FST::Data_Scaler_void<DATATYPE> ( missing_value_code,1/*to choose correct constructor*/ ) );\n        // set-up data access\n        boost::shared_ptr<std::vector<PSPLITTER> > splitters ( new std::vector<PSPLITTER> );\n        splitters->push_back ( dsp_outer );\n        splitters->push_back ( dsp_inner );\n        boost::shared_ptr<DATAACCESSOR> da ( new DATAACCESSOR ( trainingListSample,trainingLabeledListSample,splitters,dsc ) );\n        da->initialize();\n        // initiate access to split data parts\n        da->setSplittingDepth ( 0 );\n        if ( !da->getFirstSplit() ) throw FST::fst_error ( \"50/40 random data split failed.\" );\n        da->setSplittingDepth ( 1 );\n        if ( !da->getFirstSplit() ) throw FST::fst_error ( \"3-fold cross-validation failure.\" );\n        // initiate the storage for subset to-be-selected + another one as temporary storage\n        boost::shared_ptr<SUBSET> sub ( new SUBSET ( da->getNoOfFeatures() ) );\n        boost::shared_ptr<SUBSET> sub_temp ( new SUBSET ( da->getNoOfFeatures() ) );\n        // set-up SVM (interface to external library LibSVM)\n        boost::shared_ptr<CLASSIFIERSVM> csvm ( new CLASSIFIERSVM );\n\t\n        //csvm->set_kernel_type ( RBF ); // (option: LINEAR, RBF, POLY)\n        \n        std::string svm_kernel  = GetParameterAsString(\"method.dos.svmkernel\");\n\t\n\tif( svm_kernel == \"linear\")\n\t    csvm->set_kernel_type ( LINEAR );\n\t   \n\telse if( svm_kernel == \"poly\")\n\t   csvm->set_kernel_type ( POLY );\n\n\telse \n\t     csvm->set_kernel_type ( RBF );   \n        \n        csvm->initialize ( da );\n        // wrap the SVM classifier to enable its usage as FS criterion (criterion value will be estimated by 3-fold cross-val.)\n        boost::shared_ptr<WRAPPERSVM> wsvm ( new WRAPPERSVM );\n        wsvm->initialize ( csvm,da );\n        // set-up the standard sequential search step object (option: hybrid, ensemble)\n        boost::shared_ptr<EVALUATOR_SVM> eval ( new EVALUATOR_SVM );\n        // set-up Dynamic Oscillating Search procedure\n        FST::Search_DOS<RETURNTYPE,DIMTYPE,SUBSET,WRAPPERSVM,EVALUATOR_SVM> srch ( eval );\n        srch.set_delta ( 3 );\n        // run the search\n        std::cout << \"Feature selection setup:\" << std::endl << *da << std::endl << srch << std::endl << *wsvm << std::endl << std::endl;\n        RETURNTYPE bestcritval_train, critval_train, critval_test;\n        sub->select_all();\n        csvm->optimize_parameters ( da,sub );\n        double best_svm_param_C=csvm->get_parameter_C();\n        double best_svm_param_gamma=csvm->get_parameter_gamma();\n        double best_svm_param_coef0=csvm->get_parameter_coef0();\n        bool stop=false;\n        sub->deselect_all();\n        if ( !srch.search ( 0,bestcritval_train,sub,wsvm, std::cout ) ) throw FST::fst_error ( \"Search not finished.\" );\n\n        /**\n        \t\tsub_temp->stateless_copy(*sub);\n        \t\twhile(!stop)\n        \t\t{\n        \t\t\tcsvm->optimize_parameters(da,sub);\n        \t\t\tif(!srch.search(0,critval_train,sub_temp,wsvm,std::cout)) throw FST::fst_error(\"Search not finished.\");\n        \t\t\tif(critval_train>bestcritval_train)\n        \t\t\t{\n        \t\t\t\tbestcritval_train=critval_train;\n        \t\t\t\tsub->stateless_copy(*sub_temp);\n        \t\t\t\tbest_svm_param_C=csvm->get_parameter_C();\n        \t\t\t\tbest_svm_param_gamma=csvm->get_parameter_gamma();\n        \t\t\t\tbest_svm_param_coef0=csvm->get_parameter_coef0();\n        \t\t\t} else stop=true;\n        \t\t}\n        \t\tstd::cout << std::endl << \"Search result: \" << std::endl << *sub << std::endl << \"Criterion value=\" << bestcritval_train << std::endl << std::endl;\n        **/\n        // \t// (optionally) validate result by estimating SVM accuracy on selected feature sub-space on independent test data\n// \t\tda->setSplittingDepth(0);\n// \t\tcsvm->set_parameter_C(best_svm_param_C);\n// \t\tcsvm->set_parameter_gamma(best_svm_param_gamma);\n// \t\tcsvm->set_parameter_coef0(best_svm_param_coef0);\n// \t\tcsvm->train(da,sub);\n// \t\tcsvm->test(critval_test,da);\n// \t\tstd::cout << \"Validated SVM accuracy=\" << critval_test << std::endl << std::endl;\n//\n\nImportanceVector vImp;\n        vImp.reserve ( sub->get_n() );\n        for ( DIMTYPE d=0; d<sub->get_n(); d++ )\n        {\n            if ( sub->selected_raw ( d ) )\n                vImp.push_back ( std::make_pair ( d+1, 1 ) );\n            else\n                vImp.push_back ( std::make_pair ( d+1, 0 ) );\n        }\n\n\n  \n  return vImp;\n}\n\n\n\n\n\nFeatureSelection::ImportanceVector FeatureSelection::getFeatureImportanceSFFS ( ListSampleType::Pointer trainingListSample,\n        LabelListSampleType::Pointer trainingLabeledListSample )\n{\n\n    \n\n\n  // otbAppLogINFO ( \"SFFS GetFeatureImporance \" );\n\n    std::cout << \"Generalized sequential feature subset search...\" << std::endl;\n        // keep second half of data for independent testing of final classification performance\n        PSPLITTER dsp_outer ( new SPLITTER5050() );\n        // in the course of search use the first half of data by 3-fold cross-validation in wrapper FS criterion evaluation\n        PSPLITTER dsp_inner ( new SPLITTERCV ( 3 ) );\n        // do not scale data\n        boost::shared_ptr<FST::Data_Scaler<DATATYPE> > dsc ( new FST::Data_Scaler_void<DATATYPE>() );\n        // set-up data access\n        boost::shared_ptr<std::vector<PSPLITTER> > splitters ( new std::vector<PSPLITTER> );\n        splitters->push_back ( dsp_outer );\n        splitters->push_back ( dsp_inner );\n\n        //boost::shared_ptr<DATAACCESSOR> da(new DATAACCESSOR(\"data/speech_15.trn\",splitters,dsc));\n        boost::shared_ptr<DATAACCESSOR> da ( new DATAACCESSOR ( trainingListSample,trainingLabeledListSample,splitters,dsc ) );\n\n        da->initialize();\n        // initiate access to split data parts\n        da->setSplittingDepth ( 0 );\n        if ( !da->getFirstSplit() ) throw FST::fst_error ( \"50/50 data split failed.\" );\n        da->setSplittingDepth ( 1 );\n        if ( !da->getFirstSplit() ) throw FST::fst_error ( \"3-fold cross-validation failure.\" );\n        // initiate the storage for subset to-be-selected\n        boost::shared_ptr<SUBSET> sub ( new SUBSET ( da->getNoOfFeatures() ) );\n        sub->deselect_all();\n        // set-up 3-Nearest Neighbor classifier based on Euclidean distances\n        boost::shared_ptr<CLASSIFIERKNN> cknn ( new CLASSIFIERKNN );\n        cknn->set_k ( 5 );\n        // wrap the 3-NN classifier to enable its usage as FS criterion (criterion value will be estimated by 3-fold cross-val.)\n        boost::shared_ptr<WRAPPERKNN> wknn ( new WRAPPERKNN );\n        wknn->initialize ( cknn,da );\n        // set-up the standard sequential search step object (option: hybrid, ensemble, etc.)\n        boost::shared_ptr<EVALUATOR> eval ( new EVALUATOR );\n        // set-up Sequential Forward Floating Selection search procedure\n        FST::Search_SFFS<RETURNTYPE,DIMTYPE,SUBSET,WRAPPERKNN,EVALUATOR> srch ( eval );\n        \n\t\n\t//srch.set_search_direction ( FST::FORWARD ); // try FST::BACKWARD\t\n      std::string search_method = GetParameterAsString(\"method.sffs.searchdirection\") ;\n      \n      if(search_method == \"backward\")\n\tsrch.set_search_direction ( FST::BACKWARD ); \n      else\n\tsrch.set_search_direction ( FST::FORWARD ); \n\n      \n      // set the size of feature groups to be evaluated for inclusion/removal in each sequential step (can be applied to SFS, SFFS, OS, DOS, SFRS)\n        srch.set_generalization_level ( 2 );\n        // run the search\n        std::cout << \"Feature selection setup:\" << std::endl << *da << std::endl << srch << std::endl << *wknn << std::endl << std::endl;\n        RETURNTYPE critval_train, critval_test;\n        srch.set_output_detail ( FST::NORMAL ); // set FST::SILENT to disable all text output in the course of search (FST::NORMAL is default)\n        if ( !srch.search ( 0,critval_train,sub,wknn,std::cout ) ) throw FST::fst_error ( \"Search not finished.\" );\n        // (optionally) validate result by estimating kNN accuracy on selected feature sub-space on independent test data\n        //da->setSplittingDepth(0);\n        //cknn->train(da,sub);\n        //cknn->test(critval_test,da);\n        //std::cout << \"Validated \"<<cknn->get_k()<<\"-NN accuracy=\" << critval_test << std::endl << std::endl;\n        // (optionally) list the best known solutions for each cardinality as recorded throughout the course of search\n        //std::cout << \"Best recorded solution for subset size:\" << std::endl;\n        //for(DIMTYPE d=1;d<=sub->get_n();d++)\n        //if(srch.get_result(d,critval_train,sub)) std::cout << d << \": val=\"<< critval_train << \", \"<<*sub << std::endl;\n\n\tImportanceVector vImp;\n\n        vImp.reserve ( sub->get_n() );\n        for ( DIMTYPE d=0; d<sub->get_n(); d++ )\n        {\n            if ( sub->selected_raw ( d ) )\n                vImp.push_back ( std::make_pair ( d+1, 1 ) );\n            else\n                vImp.push_back ( std::make_pair ( d+1, 0 ) );\n        }\n        \n    return vImp;\n}\n\n\n\n\n} //end namespace wrapper\n} //end namespace otb\n", "meta": {"hexsha": "bc5b7d796f9fd2b4a91e372639f83ca8e3c6b6be", "size": 15024, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "app/otbSelectFST.cxx", "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": "app/otbSelectFST.cxx", "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": "app/otbSelectFST.cxx", "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": 43.547826087, "max_line_length": 157, "alphanum_fraction": 0.6873003195, "num_tokens": 3913, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5964331319177487, "lm_q2_score": 0.5078118642792044, "lm_q1q2_score": 0.30287582063703666}}
{"text": "// Copyright (C) 2015 The Regents of the University of California (Regents).\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are\n// met:\n//\n//     * 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 <Eigen/Core>\n#include <glog/logging.h>\n#include <gflags/gflags.h>\n#include <theia/theia.h>\n\n#include <memory>\n#include <string>\n\nDEFINE_string(1dsfm_dataset_directory, \"\",\n              \"Dataset where the 1dSFM dataset is located. Do not include a \"\n              \"trailing slash.\");\n\nusing theia::Reconstruction;\nusing theia::TrackId;\nusing theia::ViewId;\n\n// Computes the error in the relative rotation based on the ground truth\n// rotations rotation1 and rotation2 (which specify world-to-camera\n// transformations).\ndouble ComputeRelativeRotationError(const Eigen::Matrix3d& rotation1,\n                                    const Eigen::Matrix3d& rotation2,\n                                    const Eigen::Vector3d& relative_rotation) {\n  Eigen::Matrix3d relative_rotation_matrix;\n  ceres::AngleAxisToRotationMatrix(\n      relative_rotation.data(),\n      ceres::ColumnMajorAdapter3x3(relative_rotation_matrix.data()));\n  const Eigen::Matrix3d loop_rotation = relative_rotation_matrix.transpose() *\n                                        (rotation2 * rotation1.transpose());\n  Eigen::Vector3d loop_rotation_aa;\n  ceres::RotationMatrixToAngleAxis(\n      ceres::ColumnMajorAdapter3x3(loop_rotation.data()),\n      loop_rotation_aa.data());\n  return theia::RadToDeg(loop_rotation_aa.norm());\n}\n\ndouble ComputeRelativeTranslationError(\n    const Eigen::Vector3d& position1,\n    const Eigen::Vector3d& position2,\n    const Eigen::Matrix3d& rotation1,\n    const Eigen::Vector3d& relative_translation) {\n  const Eigen::Vector3d world_translation =\n      rotation1 * (position2 - position1).normalized();\n  return theia::RadToDeg(acos(\n      theia::Clamp(relative_translation.dot(world_translation), -1.0, 1.0)));\n}\n\nvoid EvaluateRelativeError(\n    const theia::ViewGraph& view_graph,\n    const Reconstruction& reconstruction_1dsfm,\n    const Reconstruction& gt_reconstruction) {\n  // For each edge, get the rotate translation and check the error.\n  std::vector<double> histogram_bins = {2,  5,   10,  15,  25,  50,\n                                        90, 135, 180, 225, 270, 315};\n  theia::PoseError pose_error(histogram_bins, histogram_bins);\n\n  const auto& edges = view_graph.GetAllEdges();\n  for (const auto& edge : edges) {\n    // The reconstruction/view graph from 1dSFM may have a different mapping of\n    // names to ViewIds than the ground truth reconstruction, so we have to do a\n    // name lookup in the ground truth reconstruction to ensure we have the same\n    // view.\n    const theia::View* view1_1dsfm =\n        reconstruction_1dsfm.View(edge.first.first);\n    const theia::View* view2_1dsfm =\n        reconstruction_1dsfm.View(edge.first.second);\n    if (view1_1dsfm == nullptr || view2_1dsfm == nullptr) {\n      continue;\n    }\n\n    const ViewId view_id1 =\n        gt_reconstruction.ViewIdFromName(view1_1dsfm->Name());\n    const ViewId view_id2 =\n        gt_reconstruction.ViewIdFromName(view2_1dsfm->Name());\n    const theia::View* view1 = gt_reconstruction.View(view_id1);\n    const theia::View* view2 = gt_reconstruction.View(view_id2);\n    if (view1 == nullptr || view2 == nullptr) {\n      continue;\n    }\n    const theia::Camera& camera1 = view1->Camera();\n    const theia::Camera& camera2 = view2->Camera();\n\n    const double rotation_angular_error =\n        ComputeRelativeRotationError(camera1.GetOrientationAsRotationMatrix(),\n                                     camera2.GetOrientationAsRotationMatrix(),\n                                     edge.second.rotation_2);\n\n    const double translation_angular_error = ComputeRelativeTranslationError(\n        camera1.GetPosition(),\n        camera2.GetPosition(),\n        camera1.GetOrientationAsRotationMatrix(),\n        edge.second.position_2);\n    pose_error.AddError(rotation_angular_error, translation_angular_error);\n  }\n\n  LOG(INFO) << \"Relative pose errors for 1dsfm = \\n\"\n            << pose_error.PrintMeanMedianHistogram();\n}\n\nint main(int argc, char* argv[]) {\n  google::InitGoogleLogging(argv[0]);\n  THEIA_GFLAGS_NAMESPACE::ParseCommandLineFlags(&argc, &argv, true);\n\n  LOG(INFO) << \"Reading the relative poses from the 1dsfm dataset.\";\n  std::unique_ptr<Reconstruction> reconstruction_1dsfm(new Reconstruction);\n  std::unique_ptr<theia::ViewGraph> view_graph_1dsfm(new theia::ViewGraph);\n  CHECK(Read1DSFM(FLAGS_1dsfm_dataset_directory,\n                  reconstruction_1dsfm.get(),\n                  view_graph_1dsfm.get()))\n      << \"Could not read 1dsfm dataset from \" << FLAGS_1dsfm_dataset_directory;\n\n  const std::string lists_file = FLAGS_1dsfm_dataset_directory + \"/list.txt\";\n  const std::string bundle_file =\n      FLAGS_1dsfm_dataset_directory + \"/gt_bundle.out\";\n  std::unique_ptr<theia::Reconstruction> gt_reconstruction(\n      new theia::Reconstruction());\n  LOG(INFO) << \"Converting ground truth bundler file to Theia reconstruction.\";\n  CHECK(\n      theia::ReadBundlerFiles(lists_file, bundle_file, gt_reconstruction.get()))\n      << \"Could not the ground truth Bundler file at \" << bundle_file;\n\n  EvaluateRelativeError(*view_graph_1dsfm,\n                        *reconstruction_1dsfm,\n                        *gt_reconstruction);\n\n  return 0;\n}\n", "meta": {"hexsha": "ad5565c087330b6ca12e80cc26f01aafd32ce9b3", "size": 6957, "ext": "cc", "lang": "C++", "max_stars_repo_path": "applications/verify_1dsfm_input.cc", "max_stars_repo_name": "maxchernet/TheiaSfM", "max_stars_repo_head_hexsha": "603f3ad8bfea1e54fe23fa553f268760a9c9276c", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 770.0, "max_stars_repo_stars_event_min_datetime": "2015-02-12T14:32:01.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-16T00:54:33.000Z", "max_issues_repo_path": "applications/verify_1dsfm_input.cc", "max_issues_repo_name": "maxchernet/TheiaSfM", "max_issues_repo_head_hexsha": "603f3ad8bfea1e54fe23fa553f268760a9c9276c", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 237.0, "max_issues_repo_issues_event_min_datetime": "2015-02-20T18:50:16.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-18T05:21:48.000Z", "max_forks_repo_path": "applications/verify_1dsfm_input.cc", "max_forks_repo_name": "maxchernet/TheiaSfM", "max_forks_repo_head_hexsha": "603f3ad8bfea1e54fe23fa553f268760a9c9276c", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 278.0, "max_forks_repo_forks_event_min_datetime": "2015-02-12T06:20:26.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-23T17:25:21.000Z", "avg_line_length": 43.2111801242, "max_line_length": 80, "alphanum_fraction": 0.7047577979, "num_tokens": 1589, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5350984286266116, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.3028756287569703}}
{"text": "//==============================================================================\n//         Copyright 2003 - 2012   LASMEA UMR 6602 CNRS/Univ. Clermont II\n//         Copyright 2009 - 2012   LRI    UMR 8623 CNRS/Univ Paris Sud XI\n//\n//          Distributed under the Boost Software License, Version 1.0.\n//                 See accompanying file LICENSE.txt or copy at\n//                     http://www.boost.org/LICENSE_1_0.txt\n//==============================================================================\n#ifndef NT2_LINALG_FUNCTIONS_DETAILS_RREF_HPP_INCLUDED\n#define NT2_LINALG_FUNCTIONS_DETAILS_RREF_HPP_INCLUDED\n\n#include <nt2/linalg/details/utility/f77_wrapper.hpp>\n#include <nt2/include/functions/height.hpp>\n#include <nt2/include/functions/width.hpp>\n#include <nt2/include/functions/expand.hpp>\n#include <nt2/include/constants/zero.hpp>\n#include <nt2/include/constants/mone.hpp>\n#include <nt2/include/constants/eps.hpp>\n#include <nt2/include/functions/ismatrix.hpp>\n#include <nt2/include/functions/max.hpp>\n#include <nt2/include/functions/globalmax.hpp>\n#include <nt2/include/functions/mnorminf.hpp>\n#include <nt2/include/functions/zeros.hpp>\n#include <boost/dispatch/meta/mpl.hpp>\n#include <nt2/core/container/table/table.hpp>\n//  rref   reduced row echelon form.\n//     r = rref(a) produces the reduced row echelon form of a.\n\n//     [r,jb] = rref(a) also returns a vector, jb, so that:\n//         r = length(jb) is this algorithm's idea of the rank of a,\n//         x(jb) are the bound variables in a linear system, ax = b,\n//         a(:,jb) is a basis for the range of a,\n//         r(1:r,jb) is the r-by-r identity matrix.\n\n//     [r,jb] = rref(a,tol) uses the given tolerance in the rank tests.\n\n//     roundoff errors may cause this algorithm to compute a different\n//     value for the rank than rank, orth and null.\n\nnamespace nt2 { namespace details\n{\n  template<class T> struct rref_result\n  {\n    typedef typename meta::strip<T>::type                   source_t;\n    typedef typename source_t::value_type                     type_t;\n    typedef typename source_t::index_type                    index_t;\n    typedef typename meta::as_real<type_t>::type              base_t;\n    typedef T                                                 data_t;\n    typedef typename meta::as_integer<base_t, signed>::type  itype_t;\n    typedef nt2::container::table<type_t,nt2::matlab_index_>              tab_t;\n    typedef nt2::container::table<base_t,nt2::matlab_index_>             btab_t;\n    typedef nt2::container::table<itype_t,nt2::matlab_index_>            itab_t;\n    typedef nt2::container::table<nt2_la_int,nt2::matlab_index_>         ibuf_t;\n    typedef nt2::container::table<type_t,index_t>                   result_type;\n    typedef nt2::container::table<base_t,index_t>                  bresult_type;\n    typedef nt2::container::table<itype_t,index_t>                 iresult_type;\n    //must be dry I think\n\n    template<class Input>\n    rref_result ( Input& xpr, base_t tol)\n      : tol_(tol)\n      , a_(xpr)\n      , n_( nt2::height(a_)  )\n      , m_( nt2::width(a_)  )\n      , jb_(of_size(1, n_))\n    {\n      BOOST_ASSERT_MSG(ismatrix(a_), \"input to rref must be matrix\");\n      if (tol < Zero<base_t>()) tol = nt2::max(m_,n_)*nt2::Eps<base_t>()*nt2::mnorminf(a_);\n      itype_t i = 1, j = 1;\n      itype_t k = 0;\n      base_t p;\n      itype_t cnt = 1;\n      while(i <= m_ && j <= n_)\n      {\n        //          tie(p, k) =  nt2::max(nt2::abs(a_(_(i, m_),j))); //TODO\n        p = nt2::globalmax(nt2::abs(a_(_(i, m_),j)));\n        for(int l = i; l <= m_; ++l) if (nt2::abs(a_(l, j)) == p) { k = l; break; }\n        //k = k+i-1;\n        if (p <= tol)\n        {\n          // the column is negligible, zero it out.\n          a_(_(i, m_),j) = nt2::zeros(m_-i+1, 1, meta::as_<type_t>());\n          ++j;\n        }\n        else\n        {\n          // remember column index\n          //jb_ = cath(jb_, j); //TODO\n          jb_(cnt) = j; ++cnt;\n          // swap i-th and k-th rows.\n          tab_t tmp = a_(i, _(j, n_));\n          a_(i, _(j, n_)) = a_(k, _(j, n_));\n          a_(k, _(j, n_)) = tmp;\n          //              a_(cath(i, k),_(j, n)) = a_(cath(k, i),_(j, n));\n          // divide the pivot row by the pivot element.\n          type_t tmp1 =  a_(i, j);\n          a_(i,_(j, n_)) = a_(i,_(j, n_))/tmp1;\n          // subtract multiples of the pivot row from all the other rows.\n          for (itype_t kk = 1; kk <= m_; ++kk)//[1:i-1 i+1:m]\n          {\n            if (kk!=i)\n            {\n              type_t tmp2 = a_(kk,j);\n              a_(kk,_(j, n_)) = a_(kk,_(j, n_))- tmp2*a_(i,_(j, n_));\n            }\n          }\n          ++i; ++j;\n        }\n      }\n      jb_ =  nt2::expand(jb_, 1, --cnt);\n    }\n\n    rref_result& operator=(rref_result const& src)\n    {\n      tol_    = src.tol_;\n      a_      = src.a_;\n      n_      = src.n_;\n      m_      = src.m_;\n      jb_     = src.jb_;\n      return *this;\n    }\n\n    rref_result(rref_result const& src)\n      : tol_(src.tol_),\n        a_(src.a_),\n        n_(src.n_),\n        m_(src.m_),\n        jb_(src.jb_)\n    {}\n\n    //==========================================================================\n    // Return raw values\n    //==========================================================================\n    data_t values() const { return a_; }\n    data_t rref() const { return a_; }\n\n    //==========================================================================\n    // Return permutation\n    //==========================================================================\n    const itab_t& jb() const\n    {\n      //typedef typename boost::mpl::at_c<typename index_t::type,0>::type base;\n      return jb_; //+ base::value + Mone<itype_t>();\n    }\n\n  private:\n    btab_t                         tol_;\n    data_t                           a_;\n    nt2_la_int                       n_;\n    nt2_la_int                       m_;\n    itab_t                          jb_;\n  };\n} }\n\n\n\n#endif\n\n// /////////////////////////////////////////////////////////////////////////////\n// End of rref.hpp\n// /////////////////////////////////////////////////////////////////////////////\n", "meta": {"hexsha": "dc73eab26782adead374f8d5d4966043757b372c", "size": 6141, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/core/linalg/include/nt2/linalg/functions/details/rref.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/details/rref.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/details/rref.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": 37.9074074074, "max_line_length": 91, "alphanum_fraction": 0.4860771861, "num_tokens": 1615, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5660185351961015, "lm_q2_score": 0.5350984286266115, "lm_q1q2_score": 0.30287562875697027}}
{"text": "// Software License for MTL\n// \n// Copyright (c) 2007 The Trustees of Indiana University.\n//               2008 Dresden University of Technology and the Trustees of Indiana University.\n//               2010 SimuNova UG (haftungsbeschränkt), www.simunova.com.\n// All rights reserved.\n// Authors: Peter Gottschling and Andrew Lumsdaine\n// \n// This file is part of the Matrix Template Library\n// \n// See also license.mtl.txt in the distribution.\n\n#ifndef ITL_ITL_INCLUDE\n#define ITL_ITL_INCLUDE\n\n\n#include <boost/numeric/itl/iteration/basic_iteration.hpp>\n#include <boost/numeric/itl/iteration/cyclic_iteration.hpp>\n#include <boost/numeric/itl/iteration/noisy_iteration.hpp>\n\n#include <boost/numeric/itl/krylov/cg.hpp>\n#include <boost/numeric/itl/krylov/cgs.hpp>\n#include <boost/numeric/itl/krylov/bicg.hpp>\n#include <boost/numeric/itl/krylov/bicgstab.hpp>\n#include <boost/numeric/itl/krylov/bicgstab_2.hpp>\n#include <boost/numeric/itl/krylov/bicgstab_ell.hpp>\n#include <boost/numeric/itl/krylov/fsm.hpp>\n#include <boost/numeric/itl/krylov/idr_s.hpp>\n#include <boost/numeric/itl/krylov/gmres.hpp>\n#include <boost/numeric/itl/krylov/tfqmr.hpp>\n#include <boost/numeric/itl/krylov/qmr.hpp>\n#include <boost/numeric/itl/krylov/pc_solver.hpp>\n\n#include <boost/numeric/itl/krylov/repeating_solver.hpp>\n\n#include <boost/numeric/itl/minimization/quasi_newton.hpp>\n\n#include <boost/numeric/itl/pc/identity.hpp>\n#include <boost/numeric/itl/pc/is_identity.hpp>\n#include <boost/numeric/itl/pc/diagonal.hpp>\n#include <boost/numeric/itl/pc/ilu.hpp>\n#include <boost/numeric/itl/pc/ilu_0.hpp>\n#include <boost/numeric/itl/pc/ilut.hpp>\n#include <boost/numeric/itl/pc/ic_0.hpp>\n\n#include <boost/numeric/itl/pc/imf_preconditioner.hpp>\n#include <boost/numeric/itl/pc/imf_algorithms.hpp>\n\n#include <boost/numeric/itl/pc/sub_matrix_pc.hpp>\n#include <boost/numeric/itl/pc/concat.hpp>\n\n#include <boost/numeric/itl/smoother/gauss_seidel.hpp>\n\n#include <boost/numeric/itl/stepper/armijo.hpp>\n#include <boost/numeric/itl/stepper/wolf.hpp>\n\n#include <boost/numeric/itl/updater/bfgs.hpp>\n#include <boost/numeric/itl/updater/broyden.hpp>\n#include <boost/numeric/itl/updater/dfp.hpp>\n#include <boost/numeric/itl/updater/psb.hpp>\n#include <boost/numeric/itl/updater/sr1.hpp>\n\n#endif // ITL_ITL_INCLUDE\n", "meta": {"hexsha": "964a02014f90bdaf2dfebdf88693a6b07282f2ed", "size": 2265, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/numeric/itl/itl.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/itl/itl.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/itl/itl.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": 35.390625, "max_line_length": 94, "alphanum_fraction": 0.7721854305, "num_tokens": 687, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5660185351961015, "lm_q2_score": 0.5350984286266115, "lm_q1q2_score": 0.30287562875697027}}
{"text": "//////////////////////////////////////////////////////////////////////////////\n// distribution::toolkit::map_pdf::product_pdf::product_pdf.hpp              //\n//                                                                          //\n//  (C) Copyright 2009 Erwann Rogard                                        //\n//  Use, modification and distribution are subject to the                   //\n//  Boost Software License, Version 1.0. (See accompanying file             //\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)        //\n//////////////////////////////////////////////////////////////////////////////\n#ifndef BOOST_STATISTICS_DETAIL_DISTRIBUTION_TOOLKIT_MAP_PDF_PRODUCT_PDF_PRODUCT_PDF_HPP_ER_2009\n#define BOOST_STATISTICS_DETAIL_DISTRIBUTION_TOOLKIT_MAP_PDF_PRODUCT_PDF_PRODUCT_PDF_HPP_ER_2009\n#include <boost/statistics/detail/distribution_common/meta/inherit/policy.hpp>\n#include <boost/statistics/detail/distribution_common/meta/inherit/value.hpp>\n#include <boost/statistics/detail/distribution_toolkit/meta/is_pseudo_scalar_distribution.hpp>\n\nnamespace boost{\nnamespace statistics{\nnamespace detail{\nnamespace distribution{\nnamespace toolkit{\n\n    // A pseudo distribution resulting from product of the pdf of two\n    // distributions\n    template<typename A,typename B>\n    class product_pdf : public distribution::meta::inherit_policy<\n        A,\n        distribution::meta::inherit_value<A> \n    >{\n\n        public:\n\n        product_pdf(){}\n        explicit product_pdf(\n            const A& a,\n            const B& b\n        ):a_(a),b_(b){}\n        \n        product_pdf(const product_pdf& that):a_(that.a_),b_(that.b_){}\n\n        product_pdf&\n        operator=(const product_pdf& that){\n            if(&that!=this){\n                a_ = that.a_;\n                b_ = that.b_;\n            }\n            return *this;\n        }\n\n        const A& first()const{ return a_; }\n        const B& second()const{ return b_; }\n\n        protected:\n        A a_;\n        B b_;\n    };\n\n    template<typename A,typename B>\n    product_pdf<A,B>\n    make_product_pdf(const A& a,const B& b){ \n        return product_pdf<A,B>(a,b); \n    }\n\n}// distribution\n}// toolkit\n\n}// detail\n}// statistics\n}// boost\n\n#endif\n", "meta": {"hexsha": "fc0768155d52aaa4aca1318662f6f64e1e6c58c6", "size": 2236, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "distribution_toolkit/boost/statistics/detail/distribution_toolkit/map_pdf/product_pdf/product_pdf.hpp", "max_stars_repo_name": "rogard/boost_sandbox_statistics", "max_stars_repo_head_hexsha": "16aacbc716a31a9f7bb6c535b1c90dc343282a23", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "distribution_toolkit/boost/statistics/detail/distribution_toolkit/map_pdf/product_pdf/product_pdf.hpp", "max_issues_repo_name": "rogard/boost_sandbox_statistics", "max_issues_repo_head_hexsha": "16aacbc716a31a9f7bb6c535b1c90dc343282a23", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "distribution_toolkit/boost/statistics/detail/distribution_toolkit/map_pdf/product_pdf/product_pdf.hpp", "max_forks_repo_name": "rogard/boost_sandbox_statistics", "max_forks_repo_head_hexsha": "16aacbc716a31a9f7bb6c535b1c90dc343282a23", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.9428571429, "max_line_length": 96, "alphanum_fraction": 0.5644007156, "num_tokens": 459, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.30287562875697027}}
{"text": "#include <include/common.hpp>\n\n#include <include/options.hpp>\n\n#include <include/prob.hpp>\n#include <include/util.hpp>\n\n#include <vector>\n#include <iostream>\n#include <random>\n\n#include <boost/math/special_functions/binomial.hpp>\n\n// random number generator object for std random library\nstd::mt19937 gen;\n\n// probability of equality of two calls of the SAME reference position\ndouble p_equal_calls = 0.0;\ndouble q_equal_calls = 0.0;\n\n// probability of 'sequenced position' which represents the probability of a read\n// starting at a given position of the reference\ndouble p_read_start = 0.0;\n\n// geometric distribution for inter-read distance\nstd::geometric_distribution<> geom;\n\n// lookup tables for probability of the form\n// p^x * (1-p)^{m-s}\ndouble *power_peq_lookup = NULL; // p^i\ndouble *power_qeq_lookup = NULL; // q^i = (1-p)^i\n\n/* lookup tables for the approximated expected score defined as:\n                         4^s * tildeI(s, peq)\n     tildeE(A,B,s) =  ----------------------------\n                      4^s * tildeI(s, peq) + N - 1\n */\ndouble *approxExpScoreNum = NULL;\ndouble *approxExpScoreDen = NULL;\n\nvoid initProbabilities() {\n\n    std::random_device rd;\n    gen = std::mt19937(rd());\n\n    // convenience variables\n    double p_err = Options::opts.pe;\n    double q_err = 1.0 - p_err;\n\n    // init p_equal_calls and q_equal_call\n    p_equal_calls = q_err * q_err + (1.0 / 3.0) * (p_err * p_err);\n    q_equal_calls = (1.0 - p_equal_calls) / 3.0;\n\n    // init p_read_start\n    p_read_start = (double) Options::opts.M / (double) Options::opts.N;\n\n    // init online inter-read distance distribution (i.e., geomtric)\n    geom = std::geometric_distribution<>(p_read_start);\n\n    // lookup tables\n    int m = Options::opts.m;\n    int N = Options::opts.N;\n    power_peq_lookup = new double[m + 1];\n    power_qeq_lookup = new double[m + 1];\n    approxExpScoreNum = new double[m + 1];\n    approxExpScoreDen = new double[m + 1];\n    for (int s = 0; s <= m; ++s) {\n        power_peq_lookup[s] = pow(p_equal_calls, s);\n        power_qeq_lookup[s] = pow(q_equal_calls, s);\n        double tmp = p_equal_calls * p_equal_calls + q_equal_calls * (1 - p_equal_calls);\n        double tildeI = pow(tmp, s);\n        approxExpScoreNum[s] = pow(4, s) * tildeI;\n        approxExpScoreDen[s] = (pow(4, s) * tildeI) + N - 1;\n\n    }\n}\n\n\nvoid clearProbabilities() {\n    delete[] approxExpScoreNum;\n    delete[] approxExpScoreDen;\n    delete[] power_qeq_lookup;\n    delete[] power_peq_lookup;\n\n}\n\ndouble indicatorErr(const std::string &r1, const std::string &r2, size_t s) {\n    if (s > 0) {\n        size_t hamm_d = prefixSuffixHammingDistance(r1, r2, s);\n        return (power_peq_lookup[s - hamm_d] * power_qeq_lookup[hamm_d]);\n    }\n    return 1.0;\n\n}\n\ndouble indicatorNoErr(const std::string &r1, const std::string &r2, size_t s) {\n    return (prefixSuffixHammingDistance(r1, r2, s) == 0);\n}\n\ndouble probabilityReads(const std::string &s1, const std::string &s2, size_t d) {\n\n    // probability of D = d distance between reads\n    double p_s = p_read_start * pow(1.0 - p_read_start, d);\n    // no overlap\n    if (d >= Options::opts.m) {\n        return pow(4, 2 * Options::opts.m) * p_s;\n    }\n\n    size_t dh = prefixSuffixHammingDistance(s1, s2, Options::opts.m - d);\n    // probability of dh unequal bases on the common part\n    double p_err = pow(p_equal_calls, (Options::opts.m - d - dh)) * pow(1.0 - p_equal_calls, dh);\n    // probability of indipendent parts\n    double p_ind = pow(4, 2 * d);\n\n    return p_s * p_err * p_ind;\n}\n\n\n/**\n * Compute\n *  \\sum_{s}{I(A,B,s)4^s}\n */\ndouble overlappingStringsSum(const std::string &s1, const std::string &s2) {\n    size_t m = Options::opts.m;\n    double sum = 0.0;\n    for (size_t s = 1; s <= m - 1; ++s) {\n        size_t indicator_ab = (prefixSuffixHammingDistance(s2, s1, s) == 0) ? 1 : 0;\n        size_t indicator_ba = (prefixSuffixHammingDistance(s1, s2, s) == 0) ? 1 : 0;\n        sum += power4_lookup[s] * (indicator_ab + indicator_ba);\n    }\n    size_t indic_m = (prefixSuffixHammingDistance(s2, s1, m) == 0) ? 1 : 0;\n    sum += indic_m * power4_lookup[m];\n    return sum;\n}\n\ndouble overlappingStringsSumWithErr(const std::string &s1, const std::string &s2) {\n    double sum = 0.0;\n    size_t m = Options::opts.m;\n    for (size_t s = 1; s <= m - 1; ++s) {\n        // WARNING: If needed here we can use lookup tables to make things faster\n        double tab = indicatorErr(s1, s2, s);\n        double tba = indicatorErr(s2, s1, s);\n        sum += power4_lookup[s] * (tab + tba);\n    }\n    sum += power4_lookup[m] * indicatorErr(s1, s2, m);\n    return sum;\n}\n\n/**\n * Computes probability of a random overlap of 's' bases with an hamming distance dh\n */\ndouble randomReadsOverlapProbNoErr(const std::string &s1, const std::string &s2, size_t s) {\n    size_t dh_for_s = prefixSuffixHammingDistance(s1, s2, s);\n    if (dh_for_s != 0) {\n        return 0;\n    }\n    double olap_p = overlappingStringsSum(s1, s2) + (double) Options::opts.N - 2 * (double) Options::opts.m + 1.0;\n    return (pow(4, s) / (olap_p));\n}\n\n/**\n * Gets the distance until the next read\n */\nsize_t generateInterReadDistance() {\n    return geom(gen);\n}\n\nEmpiricalDistribution::EmpiricalDistribution(double a, double b, size_t N)\n        : f(N + 1, 0.0) {\n    this->xa = a;\n    this->xb = b;\n    this->n = N + 1;\n    this->step = (b - a) / (double) N;\n    this->total = 0;\n}\n\nsize_t EmpiricalDistribution::indexForSample(double x) const {\n    return floor((x - xa) / step);\n}\n\n\ndouble EmpiricalDistribution::valueAtIndex(size_t i) const {\n    return (f[i] / (double) total);\n}\n\nvoid EmpiricalDistribution::addSample(double x) {\n    total++;\n    size_t i = indexForSample(x);\n    f[i] += 1;\n}\n\nvoid EmpiricalDistribution::getCDF(std::vector<double> &cdf) const {\n    if (this->n == 0) {\n        return;\n    }\n    cdf.reserve(this->n);\n    cdf[0] = this->f[0];\n    for (size_t i = 1; i < this->n; ++i) {\n        cdf[i] = cdf[i - 1] + f[i];\n    }\n    // normalize between 0 and 1\n    for (size_t i = 0; i < this->n; ++i) {\n        cdf[i] /= cdf[this->n - 1];\n    }\n}\n\nsize_t percentileIndex(const std::vector<double> &cdf, double perc) {\n    size_t idx = 0;\n    size_t n = cdf.size();\n    for (size_t i = 0; i < n; ++i) {\n        if (cdf[i] >= perc) {\n            break;\n        }\n        ++idx;\n    }\n    return idx;\n}\n\ndouble approximatedScore(size_t s, double *num_den) {\n    num_den[0] = approxExpScoreNum[s];\n    num_den[1] = approxExpScoreDen[s];\n    return approxExpScoreNum[s] / approxExpScoreDen[s];\n}\n\ndouble approximatedScore(size_t s) {\n    return approxExpScoreNum[s] / approxExpScoreDen[s];\n}\n\ndouble score(const std::string &r1, const std::string &r2, size_t s) {\n\n    static double iidTerm = power4_lookup[0] *\n                            ((double) Options::opts.N - 2.0 * (double) Options::opts.m + 1.0);\n\n    double den = iidTerm + overlappingStringsSumWithErr(r1, r2);\n    double num = indicatorErr(r1, r2, s) * power4_lookup[s];\n\n    return num / den;\n}\n\ndouble scoreExt(const std::string &r1, const std::string &r2, size_t s, double *num_den) {\n\n    static double iidTerm = power4_lookup[0] *\n                            ((double) Options::opts.N - 2.0 * (double) Options::opts.m + 1.0);\n\n    num_den[0] = iidTerm + overlappingStringsSumWithErr(r1, r2);\n    num_den[1] = indicatorErr(r1, r2, s) * power4_lookup[s];\n\n    return num_den[1] / num_den[0];\n}\n\nnamespace lbio {\nnamespace prob {\n\n//////////////////////////////////////////////////////////////////////\n//               SamplingEstimationProcess CLASS\n//////////////////////////////////////////////////////////////////////\n\nSamplingEstimationProcess::SamplingEstimationProcess(size_t n_)\n        : n{n_}, cumulativeSum{0}, cumulativeSumSquare{0}, k{0} {\n    this->frequency = new size_t[n + 1];\n    std::fill_n(this->frequency, n + 1, 0);\n}\n\nSamplingEstimationProcess::~SamplingEstimationProcess() {\n    delete[] frequency;\n}\n\nvoid\nSamplingEstimationProcess::newSample(size_t sample) {\n    this->frequency[sample]++;\n    this->cumulativeSum += sample;\n    this->cumulativeSumSquare += (sample * sample);\n    this->k++;\n}\n\ndouble\nSamplingEstimationProcess::sampleMean() const {\n    return ((double) cumulativeSum) / ((double) k);\n}\n\ndouble\nSamplingEstimationProcess::sampleVariance() const {\n    double sMean = sampleMean();\n    double meanTerm = ((double) k) * sMean * sMean;\n    return ((this->cumulativeSumSquare - meanTerm) / ((double) k - 1));\n}\n\ndouble\nSamplingEstimationProcess::standardError() const {\n    return std::sqrt(sampleMean() / sampleVariance());\n}\n\n\nsize_t\nSamplingEstimationProcess::medianForSampleDistribution() const {\n    return medianFromFrequency<size_t>(frequency, n + 1);\n}\n\nsize_t\nSamplingEstimationProcess::sampleSize() const {\n    return k;\n}\n\nvoid\nSamplingEstimationProcess::writeFrequencyOnFile(const std::string &path) {\n    std::ofstream os(path, std::ofstream::out);\n    writeVectorOnStream<size_t>(frequency, n + 1, os);\n    os.close();\n}\n\nSampleEstimates\nSamplingEstimationProcess::toSampleEstimates() const {\n    SampleEstimates est;\n    est.sampleSize = k;\n    est.sampleMean = sampleMean();\n    est.sampleVariance = sampleVariance();\n    return est;\n}\n\n}\n} // namespaces\n", "meta": {"hexsha": "2c22be2084c949a8711c5cd2f727db48c42cb8f8", "size": 9199, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/simulator/prob.cpp", "max_stars_repo_name": "skimmy/lib-bio", "max_stars_repo_head_hexsha": "221d97f3aa37a3d276c21ade7c83d1aba4558c89", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/simulator/prob.cpp", "max_issues_repo_name": "skimmy/lib-bio", "max_issues_repo_head_hexsha": "221d97f3aa37a3d276c21ade7c83d1aba4558c89", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2015-10-06T13:03:30.000Z", "max_issues_repo_issues_event_max_datetime": "2015-10-06T13:03:30.000Z", "max_forks_repo_path": "src/simulator/prob.cpp", "max_forks_repo_name": "skimmy/lib-bio", "max_forks_repo_head_hexsha": "221d97f3aa37a3d276c21ade7c83d1aba4558c89", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2015-11-05T11:20:06.000Z", "max_forks_repo_forks_event_max_datetime": "2019-04-04T14:26:44.000Z", "avg_line_length": 28.5683229814, "max_line_length": 114, "alphanum_fraction": 0.6276769214, "num_tokens": 2675, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6513548511303336, "lm_q2_score": 0.4649015713733885, "lm_q1q2_score": 0.30281589381217167}}
{"text": "/********************************************************************************\n *\n * Data structures for the symbolic manipulation of extended linear constraints.\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#ifndef IKOS_EXTENDED_CONSTRAINTS_HPP\n#define IKOS_EXTENDED_CONSTRAINTS_HPP\n\n#include <boost/optional.hpp>\n#include <ikos/common.hpp>\n#include <ikos/patricia_trees.hpp>\n#include <ikos/collections.hpp>\n#include <ikos/linear_constraints.hpp>\n\nnamespace ikos {\n\n  template< typename Number, typename VariableName >\n  class extended_constraint: public writeable {\n\n  public:\n    typedef extended_constraint< Number, VariableName > extended_constraint_t;\n    typedef linear_constraint< Number, VariableName > linear_constraint_t;\n    typedef variable< Number, VariableName > variable_t;\n    typedef linear_expression< Number, VariableName > linear_expression_t;\n    typedef patricia_tree_set< variable_t > variable_set_t;\n    typedef enum {\n      INF,\n      INF_EQ,\n      SUP,\n      SUP_EQ,\n      EQ,\n      NOT_EQ,\n      MOD\n    } kind_t;\n    typedef typename linear_expression_t::iterator iterator;\n\n  private:\n    kind_t _kind;\n    linear_expression_t _expr;\n    boost::optional<Number> _modulus;\n\n  public:\n    extended_constraint(): _kind(EQ) { }\n\n    extended_constraint(linear_expression_t expr, kind_t kind, Number modulus): _kind(kind), _expr(expr), _modulus(modulus) { }\n\n    extended_constraint(linear_expression_t expr, kind_t kind): _kind(kind), _expr(expr) { }\n\n    extended_constraint(linear_constraint_t constraint): _kind(EQ), _expr(constraint.expression()) {\n      if(constraint.is_inequality()) {\n        _kind = INF_EQ;\n      } else if(constraint.is_equality()) {\n        _kind = EQ;\n      } else {\n        _kind = NOT_EQ;\n      }\n    }\n\n    bool is_tautology() {\n      switch (this->_kind) {\n        case INF: {\n          return (this->_expr.is_constant() && this->_expr.constant() < 0);\n        }\n        case INF_EQ: {\n          return (this->_expr.is_constant() && this->_expr.constant() <= 0);\n        }\n        case SUP: {\n          return (this->_expr.is_constant() && this->_expr.constant() > 0);\n        }\n        case SUP_EQ: {\n          return (this->_expr.is_constant() && this->_expr.constant() >= 0);\n        }\n        case EQ: {\n          return (this->_expr.is_constant() && this->_expr.constant() == 0);\n        }\n        case NOT_EQ: {\n          return (this->_expr.is_constant() && this->_expr.constant() != 0);\n        }\n        case MOD: {\n          return false; // TODO: type dependent\n        }\n        default: {\n          throw error(\"Unreachable\");\n        }\n      }\n    }\n\n    bool is_contradiction() {\n      switch (this->_kind) {\n        case INF: {\n          return (this->_expr.is_constant() && this->_expr.constant() >= 0);\n        }\n        case INF_EQ: {\n          return (this->_expr.is_constant() && this->_expr.constant() > 0);\n        }\n        case SUP: {\n          return (this->_expr.is_constant() && this->_expr.constant() <= 0);\n        }\n        case SUP_EQ: {\n          return (this->_expr.is_constant() && this->_expr.constant() < 0);\n        }\n        case EQ: {\n          return (this->_expr.is_constant() && this->_expr.constant() != 0);\n        }\n        case NOT_EQ: {\n          return (this->_expr.is_constant() && this->_expr.constant() == 0);\n        }\n        case MOD: {\n          return false; // TODO: type dependent\n        }\n        default: {\n          throw error(\"Unreachable\");\n        }\n      }\n    }\n\n    linear_expression_t expression() {\n      return this->_expr;\n    }\n\n    kind_t kind() {\n      return this->_kind;\n    }\n\n    boost::optional<Number> modulus() {\n      return this->_modulus;\n    }\n\n    iterator begin() {\n      return this->_expr.begin();\n    }\n\n    iterator end() {\n      return this->_expr.end();\n    }\n\n    Number constant() {\n      return -this->_expr.constant();\n    }\n\n    std::size_t size() {\n      return this->_expr.size();\n    }\n\n    Number operator[](variable_t x) {\n      return this->_expr.operator[](x);\n    }\n\n    variable_set_t variables() {\n      return this->_expr.variables();\n    }\n\n    std::ostream& write(std::ostream& o) {\n      if (this->is_contradiction()) {\n        o << \"false\";\n      } else if (this->is_tautology()) {\n        o << \"true\";\n      } else {\n        linear_expression_t e = this->_expr - this->_expr.constant();\n        o << e;\n        switch (this->_kind) {\n          case INF: {\n            o << \" < \";\n            break;\n          }\n          case INF_EQ: {\n            o << \" <= \";\n            break;\n          }\n          case SUP: {\n            o << \" > \";\n            break;\n          }\n          case SUP_EQ: {\n            o << \" >= \";\n            break;\n          }\n          case EQ: {\n            o << \" = \";\n            break;\n          }\n          case NOT_EQ: {\n            o << \" != \";\n            break;\n          }\n          case MOD: {\n            o << \" = \";\n            break;\n          }\n          default: {\n            throw error(\"Unreachable\");\n          }\n        }\n        Number c = -this->_expr.constant();\n        o << c;\n\n        if (this->_kind == MOD) {\n          o << \" [\";\n          o << *_modulus;\n          o << \"]\";\n        }\n      }\n      return o;\n    }\n\n  }; // class extended_constraint\n\n  template< typename Number, typename VariableName >\n  class extended_constraint_system: public writeable {\n\n  public:\n    typedef extended_constraint< Number, VariableName > extended_constraint_t;\n    typedef extended_constraint_system< Number, VariableName > extended_constraint_system_t;\n    typedef linear_constraint< Number, VariableName > linear_constraint_t;\n    typedef linear_constraint_system< Number, VariableName > linear_constraint_system_t;\n    typedef variable< Number, VariableName > variable_t;\n    typedef patricia_tree_set< variable_t > variable_set_t;\n\n  private:\n    typedef collection< extended_constraint_t > cst_collection_t;\n\n  public:\n    typedef typename cst_collection_t::iterator iterator;\n\n  private:\n    cst_collection_t _csts;\n\n  public:\n    extended_constraint_system() { }\n\n    extended_constraint_system(extended_constraint_t cst) {\n      this->_csts += cst;\n    }\n\n    extended_constraint_system_t& operator+=(extended_constraint_t cst) {\n      this->_csts += cst;\n      return *this;\n    }\n\n    extended_constraint_system_t& operator+=(extended_constraint_system_t s) {\n      this->_csts += s._csts;\n      return *this;\n    }\n\n    extended_constraint_system_t& operator+=(linear_constraint_t cst) {\n      this->_csts += extended_constraint_t(cst);\n      return *this;\n    }\n\n    extended_constraint_system_t& operator+=(linear_constraint_system_t csts) {\n      for(typename linear_constraint_system_t::iterator it = csts.begin(); it != csts.end(); ++it) {\n        this->_csts += extended_constraint_t(*it);\n      }\n\n      return *this;\n    }\n\n    extended_constraint_system_t operator+(extended_constraint_system_t s) {\n      extended_constraint_system_t r;\n      r.operator+=(s);\n      r.operator+=(*this);\n      return r;\n    }\n\n    iterator begin() {\n      return this->_csts.begin();\n    }\n\n    iterator end() {\n      return this->_csts.end();\n    }\n\n    variable_set_t variables() {\n      variable_set_t variables;\n      for (iterator it = this->begin(); it != this->end(); ++it) {\n        variables |= it->variables();\n      }\n      return variables;\n    }\n\n    std::size_t size() {\n      return this->_csts.size();\n    }\n\n    std::ostream& write(std::ostream& o) {\n      return this->_csts.write(o);\n    }\n\n  }; // class extended_constraint_system\n}\n\n#endif // IKOS_EXTENDED_CONSTRAINTS_HPP\n", "meta": {"hexsha": "0dd32391fe00ccb13bfc389f296133453ba050c8", "size": 8835, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ikos-core/api/extended_constraints.hpp", "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": "ikos-core/api/extended_constraints.hpp", "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": "ikos-core/api/extended_constraints.hpp", "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": 27.9588607595, "max_line_length": 127, "alphanum_fraction": 0.586417657, "num_tokens": 1978, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6150878555160665, "lm_q2_score": 0.4921881357207955, "lm_q1q2_score": 0.30273894491095477}}
{"text": "#include <Data/DATA.h>\n#include <Driver/SIMULATION.h>\n#include <Equation/EQUATION.h>\n#include <Equation/NONLINEAR_EQUATION.h>\n#include <Equation/TRUST_REGION.h>\n#include <Force/FORCE.h>\n#include <Parsing/PARSER_REGISTRY.h>\n#include <Utilities/EIGEN_HELPERS.h>\n#include <Utilities/LOG.h>\n#include <Utilities/MATH.h>\n#include <Utilities/RANDOM.h>\n#include <Eigen/Eigenvalues>\n#include <iomanip>\nusing namespace Mechanics;\n///////////////////////////////////////////////////////////////////////\ntemplate<class TV> TRUST_REGION<TV>::\nTRUST_REGION()\n{\n    precision=1e-6;\n    contract_factor=.25;\n    expand_factor=2.5;\n    contract_threshold=.4;\n    expand_threshold=.8;\n    expand_threshold_rad=.8;\n    trust_iterations=20;\n    tol=1e-8;\n}\n///////////////////////////////////////////////////////////////////////\ntemplate<class TV> void TRUST_REGION<TV>::\nLinearize(SIMULATION<TV>& simulation,const T dt,const T time)\n{\n    DATA<TV>& data=simulation.data;\n    FORCE<TV>& force=simulation.force;\n\n    // zero velocities\n    equation->Initialize(data,force);\n    current_velocities.resize(equation->Velocity_DOF(),1);current_velocities.setZero();\n    equation->Unpack_Velocities(data,current_velocities);\n\n    // zero forces\n    force.Pack_Forces(solve_forces);\n    solve_forces.setZero();\n    force.Unpack_Forces(solve_forces);\n\n    // store positions\n    data.Pack_Positions(positions);\n\n    equation->Linearize(data,force,dt,time,true);\n    equation->RHS(rhs);\n    force.Pack_Forces(solve_forces);\n}\n///////////////////////////////////////////////////////////////////////\ntemplate<class TV> void TRUST_REGION<TV>::\nLinearize_Around(SIMULATION<TV>& simulation,const T dt,const T time,const Vector& solve_vector)\n{\n    DATA<TV>& data=simulation.data;\n    FORCE<TV>& force=simulation.force;\n    // sk is solve_vector\n    int velocity_dof=equation->Velocity_DOF();\n    Vector solve_velocities=solve_vector.block(0,0,velocity_dof,1);\n    solve_forces.Set(solve_vector.block(velocity_dof,0,solve_vector.rows()-velocity_dof,1));\n    data.Unpack_Positions(positions);\n    force.Increment_Forces(solve_forces,1);\n    \n    candidate_velocities=current_velocities+solve_velocities;\n    equation->Unpack_Velocities(data,candidate_velocities);\n    data.Step();\n    equation->Linearize(data,force,dt,time,false);\n    force.Increment_Forces(solve_forces,-1);\n}\n///////////////////////////////////////////////////////////////////////\ntemplate<class TV> void TRUST_REGION<TV>::\nIncrement_X(SIMULATION<TV>& simulation)\n{\n    // sk is solve_vector\n    int velocity_dof=equation->Velocity_DOF();\n    Vector solve_velocities=sk.block(0,0,velocity_dof,1);\n    solve_forces.Set(sk.block(velocity_dof,0,sk.rows()-velocity_dof,1));\n    simulation.force.Increment_Forces(solve_forces,1);\n    simulation.force.Pack_Forces(solve_forces);\n    current_velocities+=solve_velocities;\n    rhs=try_rhs;\n    \n    // store errors\n    T one_over_maxabs=1;\n    if(rhs.rows()>0){\n        T maxabs=rhs.array().abs().maxCoeff();\n        if(!maxabs){maxabs=1;}\n        one_over_maxabs=1/maxabs;}\n    equation->Store_Errors(simulation.data,rhs.block(0,0,velocity_dof,1)*one_over_maxabs);\n    solve_forces.Set(rhs.block(velocity_dof,0,rhs.rows()-velocity_dof,1)*one_over_maxabs);\n    simulation.force.Store_Errors(solve_forces);\n}\n///////////////////////////////////////////////////////////////////////\ntemplate<class TV> void TRUST_REGION<TV>::\nStep(SIMULATION<TV>& simulation,const T dt,const T time)\n{\n    static int call_count=0;\n    static int total_steps=0;\n    // loosely based on trustOptim implementation\n    status=CONTINUE;\n\n    iteration=0;\n    max_iterations=100;\n    radius=1;\n    min_radius=1e-9;\n    preconditioner_refresh_frequency=1;\n\n    Linearize(simulation,dt,time);\n    f=equation->Evaluate();\n    equation->Gradient(gk);\n    norm_gk=gk.norm();\n    Update_Hessian(false);\n    Update_Preconditioner(false);\n\n    static int failed_radius=0;\n    do{\n        iteration++;\n        LOG::cout<<std::endl<<\"BEGINNING STEP \"<<iteration<<std::endl;\n        status=Update_One_Step(simulation,dt,time);\n        LOG::cout<<\"norm_gk: \"<<norm_gk<<\" norm_gk/sqrt(nvars): \"<<norm_gk/sqrt(T(nvars))<<std::endl;\n        //if(norm_gk/sqrt(T(nvars))<=precision && f<=precision){status=SUCCESS;}\n        if(norm_gk/sqrt(T(nvars))<=precision){status=SUCCESS;}\n        if(iteration>=max_iterations){status=EMAXITER;}\n        if(radius<=min_radius){ // trust region collapse\n            status=ETOLG;\n            failed_radius++;\n        }\n\n        // update Hessian\n        if(status==MOVED || status==EXPAND){\n            //Update_Hessian(status!=EXPAND);\n            Update_Hessian(false);\n            //Check_Derivative(simulation,dt,time);\n            if(simulation.force.Equations_Changed() || iteration%preconditioner_refresh_frequency==0){Update_Preconditioner(false);}\n            status=CONTINUE;}\n        if(simulation.substeps){\n            std::string frame_name=\"Frame \"+std::to_string(simulation.current_frame)+\" substep \"+std::to_string(iteration)+\" real \"+std::to_string(int(status==CONTINUE))+ \" f \"+std::to_string(f);\n            simulation.Write(frame_name);}\n        if(status==CONTRACT){status=CONTINUE;}\n    }while(status==CONTINUE);\n    std::string frame_name=\"End frame \"+std::to_string(simulation.current_frame)+\" substep \"+std::to_string(iteration)+\" real \"+std::to_string(int(status==CONTINUE))+ \" f \"+std::to_string(f);\n    simulation.Write(frame_name);\n    //Check_Derivative(simulation,dt,time);\n    LOG::cout<<\"SOLVE STEPS: \"<<iteration<<\" Failed due to radius: \"<<failed_radius<<std::endl;\n    call_count++;\n    total_steps+=iteration;\n    LOG::cout<<\"Current average: \"<<total_steps/(T)call_count<<std::endl;\n}\n///////////////////////////////////////////////////////////////////////\ntemplate<class TV> void TRUST_REGION<TV>::\nUpdate_Preconditioner(bool identity)\n{\n    /*Matrix<T,Dynamic,Dynamic> dense(hessian);\n    EigenSolver<Matrix<T,Dynamic,Dynamic>> es(dense,false);\n    LOG::cout<<es.eigenvalues()<<std::endl;*/\n    if(!identity){\n        preconditioner.compute(hessian);}\n    if(identity || preconditioner.info()!=ComputationInfo::Success){\n        LOG::cout<<\"Preconditioner computation failed; using identity\"<<std::endl;\n        SparseMatrix<T> BB(nvars,nvars);\n        BB.setIdentity();\n        preconditioner.compute(BB);}\n    /*inverse_scale.resize(nvars);\n    for(int i=0;i<nvars;i++){\n    inverse_scale(i)=1/preconditioner.scalingS()(i);}*/\n}\n///////////////////////////////////////////////////////////////////////\ntemplate<class TV> void TRUST_REGION<TV>::\nUpdate_Hessian(bool use_accurate_hessian)\n{\n    if(use_accurate_hessian){\n        equation->Accurate_Hessian(hessian);}\n    else{\n        equation->Hessian(hessian);}\n    equation->Jacobian(jacobian);\n    nvars=hessian.rows();\n}\n///////////////////////////////////////////////////////////////////////\ntemplate<class M>\nvoid Print_No_Angular(const M& m)\n{\n    for(int i=0;i<m.rows();i++){\n        if(i%6>2){continue;}\n        for(int j=0;j<m.cols();j++){\n            if(j%6>2){continue;}\n            LOG::cout<<std::setw(13)<<m(i,j)<<\" \";\n        }\n        LOG::cout<<std::endl;\n    }\n}\ntemplate<class TV> typename TRUST_REGION<TV>::STATUS TRUST_REGION<TV>::\nUpdate_One_Step(SIMULATION<TV>& simulation,const T dt,const T time)\n{\n    auto step_status=UNKNOWN;\n    T try_f,step_quality,predicted_reduction;\n    /*LOG::cout<<\"Jacobian adjoint: \"<<std::endl;\n    Print_No_Angular(Matrix<T,Dynamic,Dynamic>(jacobian.adjoint()));\n    LOG::cout<<\"Error: \"<<std::endl;\n    LOG::cout<<\"Un-adjusted hessian sk:\"<<std::endl;*/\n    //hessian=jacobian.adjoint()*jacobian;\n    //Solve_Trust_Conjugate_Gradient(sk);\n    //equation->Hessian(hessian);\n    Solve_Trust_Conjugate_Gradient(sk);\n    //Solve_Trust_MINRES(sk);\n    T norm_sk_scaled=Norm(preconditioner,sk,wd);\n    if(!std::isfinite(norm_sk_scaled)){step_status=FAILEDCG;}\n    else{\n        Linearize_Around(simulation,dt,time,sk);\n        try_f=equation->Evaluate();\n        if(std::isfinite(try_f)){\n            T actual_reduction=f-try_f;\n            T gs=gk.dot(sk);\n            T sBs=sk.dot(hessian.template selfadjointView<Lower>()*sk);\n            predicted_reduction=-(gs+sBs/2);\n            //Jsk=jacobian*sk;\n            //componentwise_prediction=gk.cwiseProduct(Jsk)+Jsk.cwiseProduct(Jsk)/2;\n            equation->RHS(try_rhs);\n            //LOG::cout<<\"Try RHS: \"<<std::endl<<try_rhs<<std::endl;\n            //LOG::cout<<\"Componentwise quality: \"<<componentwise_prediction.sum()<<std::endl<<rhs.Diff(try_rhs).cwiseQuotient(componentwise_prediction)<<std::endl;\n            //int index;\n            //LOG::cout<<\"Min value at index \"<<index<<\" is \"<<componentwise_prediction.minCoeff(&index)<<std::endl;\n            //LOG::cout<<\"Max value at index \"<<index<<\" is \"<<componentwise_prediction.maxCoeff(&index)<<std::endl;\n            if(predicted_reduction<0){step_status=ENEGMOVE;}\n            step_quality=actual_reduction/predicted_reduction;\n            LOG::cout<<\"Candidate error with value \"<<try_f<<\":\"<<std::endl;\n            /*Matrix<T,Dynamic,1> error;\n            equation->RHS(error);\n            LOG::cout<<\"Current error: \"<<std::endl;\n            Print_No_Angular(error.transpose());*/\n            LOG::cout<<\"AP: \"<<step_quality<<\" old f: \"<<f<<\" try f: \"<<try_f<<\" ared: \"<<actual_reduction<<\" pred: \"<<predicted_reduction<<\" radius: \"<<radius<<\" gs: \"<<gs<<\" sBs: \"<<sBs<<\" norm_sk_scaled: \"<<norm_sk_scaled<<std::endl;}\n        else{step_status=FAILEDCG;}}\n    if(step_status!=FAILEDCG && step_status!=ENEGMOVE){\n        if(step_quality>contract_threshold){\n            equation->Gradient(try_g);\n            if(std::isfinite(try_g.norm())){\n                f=try_f;\n                Increment_X(simulation);\n                gk=try_g;\n                norm_gk=gk.norm();\n                /*LOG::cout<<\"Resolved error:\"<<std::endl;\n                Matrix<T,Dynamic,1> error;\n                equation->RHS(error);\n                Print_No_Angular(error.transpose());*/\n                if(step_quality>expand_threshold){// && norm_sk_scaled>=expand_threshold_rad*radius){\n                    step_status=EXPAND;}\n                else{step_status=MOVED;}}\n            else{step_status=FAILEDCG;}}\n        else if(step_quality<0){step_status=NEGRATIO;}\n        else{step_status=CONTRACT;}}\n\n    LOG::cout<<\"Step status: \"<<step_status<<std::endl;\n    switch(step_status){\n        case NEGRATIO:{\n            T gksk=gk.dot(sk);\n            T gamma_bad=(1-contract_threshold)*gksk/((1-contract_threshold)*(f+gksk+contract_threshold*(f-predicted_reduction)-try_f));\n            radius=std::min(contract_factor*norm_sk_scaled,std::max((T)0.0625,gamma_bad)*radius);\n            step_status=CONTRACT;\n            break;}\n        case CONTRACT:\n        case FAILEDCG:\n        case ENEGMOVE:\n            step_status=CONTRACT;\n            //radius=norm_sk_scaled*contract_factor;\n            radius*=contract_factor;\n            break;\n        case EXPAND:\n            //radius=std::max(expand_factor*norm_sk_scaled,radius);\n            radius*=expand_factor;\n            break;\n        default:\n            break;\n    };\n    return step_status;\n}\n///////////////////////////////////////////////////////////////////////\ntemplate<class TV> typename TV::Scalar TRUST_REGION<TV>::\nNorm(const Preconditioner& preconditioner,const Vector& v,Vector& scratch)\n{\n    if(preconditioner.permutationP().rows() == v.rows()){\n        scratch=preconditioner.permutationP()*v;}\n    else{scratch=v;}\n    scratch=preconditioner.matrixL().adjoint().template triangularView<Upper>()*scratch;\n    return scratch.norm();\n}\n///////////////////////////////////////////////////////////////////////\ntemplate<class TV> void TRUST_REGION<TV>::\nSolve_Trust_MINRES(Vector& sol)\n{\n    std::array<T,2> alpha,beta,res;\n    std::array<Vector,2> v,d;\n    int n=hessian.rows();\n    for(int i=0;i<2;i++){\n        v[i].resize(n);\n        v[i].setZero();\n        d[i].resize(n);\n        d[i].setZero();\n    }\n    T norm_A=0;\n    T cond_A=1;\n    T c=-1,s=0; // givens\n\n    T gamma_min=1e99;\n    std::array<T,2> delta1,delta2,ep,gamma1,gamma2;\n    delta1[1]=0;\n    Vector pk,tk,old_sol;\n    sol.resize(n);sol.setZero();\n    T tau=0;\n    T epsilon=1e-8;\n    beta[0]=0;\n    T norm_rhs=gk.norm();\n    beta[1]=norm_rhs;\n    v[1]=-gk/norm_rhs;\n    res[0]=norm_rhs;\n    tau=norm_rhs;\n\n    auto sign=[&](T x) {return (std::fabs(x)<epsilon?0:x/std::fabs(x));};\n\n    int i;\n    std::stringstream reason;\n    for(i=0;i<trust_iterations;i++){\n        int cur=(i+1)%2,next=i%2;\n\n        pk=hessian*v[cur];\n        alpha[cur]=v[cur].dot(pk);\n        pk-=alpha[cur]*v[cur];\n        v[next]=pk-beta[cur]*v[next];\n        beta[next]=v[next].norm();\n        if(fabs(beta[next])>epsilon){\n            v[next]/=beta[next];}\n\n        delta2[cur]=c*delta1[cur]+s*alpha[cur];\n        gamma1[cur]=s*delta1[cur]-c*alpha[cur];\n\n        ep[next]=s*beta[next];\n        delta1[next]=-c*beta[next];\n\n\n        T a=gamma1[cur],b=beta[next];\n        if(fabs(b)<epsilon){\n            s=0;\n            gamma2[cur]=fabs(a);\n            if(fabs(a)<epsilon){\n                c=1;}\n            else{\n                c=sign(a);}\n        }\n        else if(fabs(a)<epsilon){\n            c=0;\n            s=sign(b);\n            gamma2[cur]=fabs(b);\n        }\n        else if(fabs(b)>fabs(a)){\n            T t=a/b;\n            s=sign(b)/sqrt(1+sqr(t));\n            c=s*t;\n            gamma2[cur]=b/s;}\n        else{\n            T t=b/a;\n            c=sign(a)/sqrt(1+sqr(t));\n            s=c*t;\n            gamma2[cur]=a/c;}\n\n        tau=c*res[next];\n        res[cur]=s*res[next];\n\n        if(i==0){norm_A=sqrt(sqr(alpha[cur])+sqr(beta[next]));}\n        else{\n            T tnorm=sqrt(sqr(alpha[cur])+sqr(beta[next])+sqr(beta[cur]));\n            norm_A=std::max(norm_A,tnorm);}\n\n        if(fabs(gamma2[cur])>epsilon){\n            d[cur]=(v[cur]-delta2[cur]*d[next]-ep[cur]*d[cur])/gamma2[cur];\n\n            old_sol=sol;\n            sol+=tau*d[cur];\n            if(sol.norm()>=radius){\n                LOG::cout<<\"tau was originally \"<<tau<<std::endl;\n                LOG::cout<<\"Direction \"<<d[cur].transpose()<<std::endl;\n                d[cur]*=tau;\n                tau=Find_Tau(old_sol,d[cur]);\n                LOG::cout<<\"Chosen tau is \"<<tau<<std::endl;\n                sol=old_sol+tau*d[cur];\n                reason<<\"Intersect TR bound\";\n                break;\n            }\n            gamma_min=std::min(gamma_min,gamma2[cur]);\n            cond_A=norm_A/gamma_min;\n        }\n\n        LOG::cout<<\"residual: \"<<res[i%2]<<std::endl;\n        if(res[i%2]/norm_rhs<tol){\n            reason<<\"Reached tolerance\";\n            break;\n        }\n    }\n    CG_stop_reason=reason.str();\n    LOG::cout<<\"MINRES reason: \"<<CG_stop_reason<<\" iterations: \"<<i<<std::endl;\n    LOG::cout<<\"solutn: \"<<sol.transpose()<<std::endl;\n    LOG::cout<<\"result: \"<<(hessian*sol).transpose()<<std::endl;\n    LOG::cout<<\"actual: \"<<-gk.transpose()<<std::endl;\n}\n///////////////////////////////////////////////////////////////////////\ntemplate<class TV> void TRUST_REGION<TV>::\nSolve_Trust_Conjugate_Gradient(Vector& pk)\n{\n    T dot_ry,dot_ry_old,aj,tau,dBd,p_norm_gk;\n    int j;\n    zj.resize(hessian.rows());\n    zj.setZero();\n    rj=-gk;\n    p_norm_gk=Norm(preconditioner,gk,wd);\n    T local_tol=std::min((T).5,(T)sqrt(p_norm_gk))*p_norm_gk;\n    LOG::cout<<\"Local tol: \"<<local_tol<<\" tol: \"<<tol<<std::endl;\n\n    // Solve LL'y=r\n    yj=preconditioner.solve(rj);\n    dj=yj;\n    \n    std::stringstream reason;\n    for(j=0;j<trust_iterations;j++){\n        dBd=dj.dot(hessian.template selfadjointView<Lower>()*dj);\n        if(dBd<=0){\n            tau=Find_Tau(zj,dj);\n            pk.noalias()=zj+tau*dj;\n            num_CG_iterations=j+1;\n            reason<<\"Negative curvature: \"<<dBd;\n            break;}\n\n        aj=rj.dot(yj)/dBd;\n        zj_old=zj;\n        zj.noalias()+=aj*dj;\n\n        if(Norm(preconditioner,zj,wd)>=radius){\n            // find tau>=0 s.t. p intersects trust region\n            tau=Find_Tau(zj_old,dj);\n            pk.noalias()=zj_old+tau*dj;\n            num_CG_iterations=j+1;\n            reason<<\"Intersect TR bound\";\n            break;}\n\n        dot_ry=rj.dot(yj);\n        rj.noalias()-=aj*(hessian.template selfadjointView<Lower>()*dj).eval();\n        \n        if(Norm(preconditioner,rj,wd)/p_norm_gk<local_tol){\n            pk=zj;\n            num_CG_iterations=j+1;\n            reason<<\"Reached tolerance\";\n            break;}\n\n        dot_ry_old=dot_ry;\n        \n        //updating yj\n        yj=preconditioner.solve(rj);\n        dot_ry=rj.dot(yj);\n        dj*=dot_ry/dot_ry_old;\n        dj.noalias()+=yj;}\n    \n    if(j>=trust_iterations){\n        pk=zj;\n        num_CG_iterations=j;\n        reason<<\"Exceeded max CG iterations\";}\n\n    CG_stop_reason=reason.str();\n    LOG::cout<<\"CG reason: \"<<CG_stop_reason<<\" iterations: \"<<num_CG_iterations<<std::endl;\n}\n///////////////////////////////////////////////////////////////////////\ntemplate<class TV> void TRUST_REGION<TV>::\nMultiply(const Preconditioner& X,const Vector& v,Vector& out)\n{\n    if(X.permutationP().rows() == v.rows()){\n        out=X.permutationP()*v;}\n    else{out=v;}\n    out=X.matrixL().adjoint().template triangularView<Upper>()*out;\n    out=X.matrixL().template triangularView<Lower>()*out;\n    if(X.permutationP().rows() == v.rows()){\n        out=X.permutationP().inverse()*out;}\n}\n///////////////////////////////////////////////////////////////////////\ntemplate<class TV> typename TV::Scalar TRUST_REGION<TV>::\nFind_Tau(const Vector& z,const Vector& d)\n{\n    Multiply(preconditioner,d,wd);\n    Multiply(preconditioner,z,wz);\n    \n    T pCd=z.dot(wd);\n    T dCd=d.dot(wd);\n    T pCp=z.dot(wz);\n    return (-2*pCd+sqrt(4*pCd*pCd-4*dCd*(pCp-radius*radius)))/(2*dCd);\n}\n///////////////////////////////////////////////////////////////////////\ntemplate<class TV> void TRUST_REGION<TV>::\nCheck_Derivative(SIMULATION<TV>& simulation,const T dt,const T time)\n{\n    DATA<TV>& data=simulation.data;\n    FORCE<TV>& force=simulation.force;\n\n    T epsilon=1e-2;\n    Matrix<T,Dynamic,1> variables=equation->Get_Unknowns(data,force);\n    variables.setZero();\n    if(!sk.rows()){sk.resize(variables.rows());sk.setZero();}\n    Linearize_Around(simulation,dt,time,variables);\n\n    data.random.Direction(variables);\n    T f0=equation->Evaluate();\n    Matrix<T,Dynamic,1> gradient;equation->Gradient(gradient);\n    SparseMatrix<T> h;equation->Hessian(h);\n    auto Evaluate_Step_Error = [&](T eps){\n        Linearize_Around(simulation,dt,time,eps*variables);\n\n        T f1=equation->Evaluate();\n        T predicted_delta_f=gradient.dot(eps*variables)+(T).5*eps*eps*variables.transpose()*h*variables;\n        T error=f1-f0-predicted_delta_f;\n        LOG::cout<<\"Error for \"<<eps<<\": \"<<error<<std::endl;\n        return error;\n    };\n    T last_error=Evaluate_Step_Error(epsilon);\n    int divisors=8;\n    for(int i=0;i<divisors;i++){\n        epsilon/=2;\n        T new_error=Evaluate_Step_Error(epsilon);\n        LOG::cout<<\"Ratio: \"<<last_error/new_error<<std::endl;\n        last_error=new_error;\n    }\n    //LOG::cout<<\"Ratio: \"<<Evaluate_Step_Error(epsilon)/Evaluate_Step_Error(epsilon/2)<<std::endl;\n    Linearize_Around(simulation,dt,time,sk);\n}\n///////////////////////////////////////////////////////////////////////\nGENERIC_TYPE_DEFINITION(TRUST_REGION)\nDEFINE_AND_REGISTER_PARSER(TRUST_REGION,void)\n{\n    auto step=std::make_shared<TRUST_REGION<TV>>();\n    step->equation=new NONLINEAR_EQUATION<TV>();\n    Parse_Scalar(node[\"precision\"],step->precision,step->precision);\n    Parse_Scalar(node[\"contract_threshold\"],step->contract_threshold,step->contract_threshold);\n    Parse_Scalar(node[\"expand_threshold\"],step->expand_threshold,step->expand_threshold);\n    Parse_Scalar(node[\"contract_factor\"],step->contract_factor,step->contract_factor);\n    Parse_Scalar(node[\"expand_factor\"],step->expand_factor,step->expand_factor);\n    Parse_Scalar(node[\"trust_iterations\"],step->trust_iterations,step->trust_iterations);\n    Parse_Scalar(node[\"tol\"],step->tol,step->tol);\n    simulation.evolution.push_back(step);\n    return 0;\n}\n", "meta": {"hexsha": "e90f79a19eeaf8ea14a2a53612e0a035a54bf594", "size": 20118, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Library/Equation/TRUST_REGION.cpp", "max_stars_repo_name": "avimosher/shapesifter", "max_stars_repo_head_hexsha": "8b42200220764b8082fadad9bf5346b5d1844c06", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Library/Equation/TRUST_REGION.cpp", "max_issues_repo_name": "avimosher/shapesifter", "max_issues_repo_head_hexsha": "8b42200220764b8082fadad9bf5346b5d1844c06", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Library/Equation/TRUST_REGION.cpp", "max_forks_repo_name": "avimosher/shapesifter", "max_forks_repo_head_hexsha": "8b42200220764b8082fadad9bf5346b5d1844c06", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.9816176471, "max_line_length": 237, "alphanum_fraction": 0.5892235809, "num_tokens": 5145, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.679178699175393, "lm_q2_score": 0.4455295350395727, "lm_q1q2_score": 0.30259417005239464}}
{"text": "// SPDX-License-Identifier: MIT\n// SPDX-FileCopyrightText: Copyright 2019-2021 Heal Research\n\n#ifndef OPERON_EVAL_DETAIL\n#define OPERON_EVAL_DETAIL\n\n#include \"core/node.hpp\"\n#include \"core/types.hpp\"\n#include \"interpreter/functions.hpp\"\n\n#include \"robin_hood.h\"\n#include <Eigen/Dense>\n#include <fmt/core.h>\n\n#include <tuple>\n\nnamespace Operon {\n\nnamespace detail {\n    // this should be good enough - tests show 512 is about optimal\n    template<typename T>\n    struct batch_size {\n        static const size_t value = 512 / sizeof(T);\n    };\n\n    template<typename T>\n    using eigen_t = typename Eigen::Array<T, batch_size<T>::value, Eigen::Dynamic, Eigen::ColMajor>;\n\n    template<typename T>\n    using eigen_ref = Eigen::Ref<eigen_t<T>, Eigen::Unaligned, Eigen::Stride<batch_size<T>::value, 1>>;\n\n    // dispatching mechanism\n    // compared to the simple/naive way of evaluating n-ary symbols, this method has the following advantages:\n    // 1) improved performance: the naive method accumulates into the result for each argument, leading to unnecessary assignments\n    // 2) minimizing the number of intermediate steps which might improve floating point accuracy of some operations\n    //    if arity > 4, one accumulation is performed every 4 args\n    template<NodeType Type, typename T>\n    inline void dispatch_op_nary(eigen_t<T>& m, Operon::Vector<Node> const& nodes, size_t parentIndex, size_t /* row number - not used */)\n    {\n        static_assert(Type < NodeType::Aq);\n        auto result = m.col(parentIndex);\n        const auto f = [](bool cont, decltype(result) res, auto&&... args) {\n            if (cont) {\n                ContinuedFunction<Type>{}(res, std::forward<decltype(args)>(args)...);\n            } else {\n                Function<Type>{}(res, std::forward<decltype(args)>(args)...);\n            }\n        };\n        const auto nextArg = [&](size_t i) { return i - (nodes[i].Length + 1); };\n\n        auto arg1 = parentIndex - 1;\n\n        bool continued = false;\n\n        int arity = nodes[parentIndex].Arity;\n        while (arity > 0) {\n            switch (arity) {\n            case 1: {\n                f(continued, result, m.col(arg1));\n                arity = 0;\n                break;\n            }\n            case 2: {\n                auto arg2 = nextArg(arg1);\n                f(continued, result, m.col(arg1), m.col(arg2));\n                arity = 0;\n                break;\n            }\n            case 3: {\n                auto arg2 = nextArg(arg1), arg3 = nextArg(arg2);\n                f(continued, result, m.col(arg1), m.col(arg2), m.col(arg3));\n                arity = 0;\n                break;\n            }\n            default: {\n                auto arg2 = nextArg(arg1), arg3 = nextArg(arg2), arg4 = nextArg(arg3);\n                f(continued, result, m.col(arg1), m.col(arg2), m.col(arg3), m.col(arg4));\n                arity -= 4;\n                arg1 = nextArg(arg4);\n                break;\n            }\n            }\n            continued = true;\n        }\n    }\n\n    template<NodeType Type, typename T>\n    inline void dispatch_op_unary(eigen_t<T>& m, Operon::Vector<Node> const&, size_t i, size_t /* row number - not used */)\n    {\n        static_assert(Type < NodeType::Constant && Type > NodeType::Pow);\n        Function<Type>{}(m.col(i), m.col(i - 1));\n    }\n\n    template<NodeType Type, typename T>\n    inline void dispatch_op_binary(eigen_t<T>& m, Operon::Vector<Node> const& nodes, size_t i, size_t /* row number - not used */)\n    {\n        static_assert(Type < NodeType::Log && Type > NodeType::Div);\n        auto j = i - 1;\n        auto k = j - nodes[j].Length - 1;\n        Function<Type>{}(m.col(i), m.col(j), m.col(k));\n    }\n\n    template<NodeType Type, typename T>\n    inline void dispatch_op_simple_unary_or_binary(eigen_t<T>& m, Operon::Vector<Node> const& nodes, size_t parentIndex, size_t /* row number - not used */)\n    {\n        auto r = m.col(parentIndex);\n        size_t i = parentIndex - 1;\n        size_t arity = nodes[parentIndex].Arity;\n\n        Function<Type> f{};\n\n        if (arity == 1) {\n            f(r, m.col(i));\n        } else {\n            auto j = i - (nodes[i].Length + 1);\n            f(r, m.col(i), m.col(j));\n        }\n    }\n\n    template<NodeType Type, typename T>\n    inline void dispatch_op_simple_nary(eigen_t<T>& m, Operon::Vector<Node> const& nodes, size_t parentIndex, size_t /* row number - not used */)\n    {\n        auto r = m.col(parentIndex);\n        size_t arity = nodes[parentIndex].Arity;\n\n        auto i = parentIndex - 1;\n\n        Function<Type> f{};\n\n        if (arity == 1) {\n            f(r, m.col(i));\n        } else {\n            r = m.col(i);\n\n            for (size_t k = 1; k < arity; ++k) {\n                i -= nodes[i].Length + 1;\n                f(r, m.col(i));\n            }\n        }\n    }\n\n    struct noop {\n        template<typename... Args>\n        void operator()(Args&&...) {}\n    };\n\n    template<typename X, typename Tuple>\n    class tuple_index;\n\n    template<typename X, typename... T>\n    class tuple_index<X, std::tuple<T...>> {\n        template<std::size_t... idx>\n        static constexpr ssize_t find_idx(std::index_sequence<idx...>)\n        {\n            return -1 + ((std::is_same<X, T>::value ? idx + 1 : 0) + ...);\n        }\n\n    public:\n        static constexpr ssize_t value = find_idx(std::index_sequence_for<T...>{});\n    };\n\n    template<typename T>\n    using Callable = typename std::function<void(detail::eigen_t<T>&, Operon::Vector<Node> const&, size_t, size_t)>;\n\n    template<NodeType Type, typename T>\n    static constexpr Callable<T> MakeCall()\n    {\n        if constexpr (Type < NodeType::Aq) { // nary: add, sub, mul, div\n            return Callable<T>(detail::dispatch_op_nary<Type, T>);\n        } else if constexpr (Type < NodeType::Log) { // binary: aq, pow\n            return Callable<T>(detail::dispatch_op_binary<Type, T>);\n        } else if constexpr (Type < NodeType::Constant) { // unary: exp, log, sin, cos, tan, tanh, sqrt, cbrt, square, dynamic\n            return Callable<T>(detail::dispatch_op_unary<Type, T>);\n        }\n    }\n\n    template<NodeType Type, typename... Ts, std::enable_if_t<sizeof...(Ts) != 0, bool> = true>\n    static constexpr auto MakeTuple()\n    {\n        return std::tuple(MakeCall<Type, Ts>()...);\n    };\n\n    template<typename F, typename... Ts, std::enable_if_t<sizeof...(Ts) != 0 && (std::is_invocable_r_v<void, F, detail::eigen_t<Ts>&, Vector<Node> const&, size_t, size_t> && ...), bool> = true>\n    static constexpr auto MakeTuple(F&& f)\n    {\n        return std::tuple(Callable<Ts>(std::forward<F&&>(f))...);\n    }\n\n    template<typename F, typename... Ts, std::enable_if_t<sizeof...(Ts) != 0 && (std::is_invocable_r_v<void, F, detail::eigen_t<Ts>&, Vector<Node> const&, size_t, size_t> && ...), bool> = true>\n    static constexpr auto MakeTuple(F const& f)\n    {\n        return std::tuple(Callable<Ts>(f)...);\n    }\n\n    template<NodeType Type>\n    static constexpr auto MakeDefaultTuple()\n    {\n        return MakeTuple<Type, Operon::Scalar, Operon::Dual>();\n    }\n\n    template<typename F, std::enable_if_t<\n        std::is_invocable_r_v<\n            void, F, detail::eigen_t<Operon::Scalar>&, Operon::Vector<Node> const&, size_t, size_t\n        > &&\n        std::is_invocable_r_v<\n            void, F, detail::eigen_t<Operon::Dual>&, Operon::Vector<Node> const&, size_t, size_t\n        >, bool> = true>\n    static constexpr auto MakeDefaultTuple(F&& f)\n    {\n        return MakeTuple<F, Operon::Scalar, Operon::Dual>(std::forward<F&&>(f));\n    }\n\n} // namespace detail\n\nstruct DispatchTable {\n    template<typename T>\n    using Callable = detail::Callable<T>;\n\n    using Tuple    = std::tuple<Callable<Operon::Scalar>, Callable<Operon::Dual>>;\n    using Map      = robin_hood::unordered_flat_map<Operon::Hash, Tuple>;\n    using Pair     = robin_hood::pair<Operon::Hash, Tuple>;\n\n    DispatchTable()\n    {\n        InitializeMap();\n    }\n\n    DispatchTable(DispatchTable const& other) : map(other.map) { }\n    DispatchTable(DispatchTable &&other) : map(std::move(other.map)) { }\n\n    void InitializeMap()\n    {\n        const auto hash = [](auto t) { return Node(t).HashValue; };\n\n        map = Map{\n            { hash(NodeType::Add), detail::MakeDefaultTuple<NodeType::Add>() },\n            { hash(NodeType::Sub), detail::MakeDefaultTuple<NodeType::Sub>() },\n            { hash(NodeType::Mul), detail::MakeDefaultTuple<NodeType::Mul>() },\n            { hash(NodeType::Sub), detail::MakeDefaultTuple<NodeType::Sub>() },\n            { hash(NodeType::Div), detail::MakeDefaultTuple<NodeType::Div>() },\n            { hash(NodeType::Aq),  detail::MakeDefaultTuple<NodeType::Aq>() },\n            { hash(NodeType::Pow), detail::MakeDefaultTuple<NodeType::Pow>() },\n            { hash(NodeType::Log), detail::MakeDefaultTuple<NodeType::Log>() },\n            { hash(NodeType::Exp), detail::MakeDefaultTuple<NodeType::Exp>() },\n            { hash(NodeType::Sin), detail::MakeDefaultTuple<NodeType::Sin>() },\n            { hash(NodeType::Cos), detail::MakeDefaultTuple<NodeType::Cos>() },\n            { hash(NodeType::Tan), detail::MakeDefaultTuple<NodeType::Tan>() },\n            { hash(NodeType::Tanh), detail::MakeDefaultTuple<NodeType::Tanh>() },\n            { hash(NodeType::Sqrt), detail::MakeDefaultTuple<NodeType::Sqrt>() },\n            { hash(NodeType::Cbrt), detail::MakeDefaultTuple<NodeType::Cbrt>() },\n            { hash(NodeType::Square), detail::MakeDefaultTuple<NodeType::Square>() },\n            /* constants and variables not needed here */\n        };\n    };\n\n    template<typename T>\n    inline Callable<T>& Get(Operon::Hash const h)\n    {\n        constexpr ssize_t idx = detail::tuple_index<Callable<T>, Tuple>::value;\n        static_assert(idx >= 0, \"Tuple does not contain type T\");\n        if (auto it = map.find(h); it != map.end()) {\n            return std::get<static_cast<size_t>(idx)>(it->second);\n        }\n        throw std::runtime_error(fmt::format(\"Hash value {} is not in the map\\n\", h));\n    }\n\n    template<typename T>\n    inline Callable<T> const& Get(Operon::Hash const h) const\n    {\n        constexpr ssize_t idx = detail::tuple_index<Callable<T>, Tuple>::value;\n        static_assert(idx >= 0, \"Tuple does not contain type T\");\n        if (auto it = map.find(h); it != map.end()) {\n            return std::get<static_cast<size_t>(idx)>(it->second);\n        }\n        throw std::runtime_error(fmt::format(\"Hash value {} is not in the map\\n\", h));\n    }\n\n    template<typename F, std::enable_if_t<std::is_invocable_r_v<void, F, detail::eigen_t<Operon::Dual>&, Vector<Node> const&, size_t, size_t>, bool> = true>\n    void RegisterCallable(Operon::Hash hash, F const& f) {\n        map[hash] = detail::MakeTuple<F, Operon::Scalar, Operon::Dual>(f);\n    }\n\nprivate:\n    Map map;\n};\n\n} // namespace Operon\n\n#endif\n", "meta": {"hexsha": "681f1b92c52dbae1d9534c2d4d5184734bbaf8b5", "size": 10838, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/operon/interpreter/dispatch_table.hpp", "max_stars_repo_name": "lf-shaw/operon", "max_stars_repo_head_hexsha": "09a6ac1932d552b8be505f235318e50e923b0da1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 50.0, "max_stars_repo_stars_event_min_datetime": "2020-10-14T10:08:21.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-10T12:55:05.000Z", "max_issues_repo_path": "include/operon/interpreter/dispatch_table.hpp", "max_issues_repo_name": "lf-shaw/operon", "max_issues_repo_head_hexsha": "09a6ac1932d552b8be505f235318e50e923b0da1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 16.0, "max_issues_repo_issues_event_min_datetime": "2020-10-26T13:05:47.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-22T20:24:41.000Z", "max_forks_repo_path": "include/operon/interpreter/dispatch_table.hpp", "max_forks_repo_name": "lf-shaw/operon", "max_forks_repo_head_hexsha": "09a6ac1932d552b8be505f235318e50e923b0da1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 16.0, "max_forks_repo_forks_event_min_datetime": "2020-10-26T13:05:38.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-14T02:52:13.000Z", "avg_line_length": 37.3724137931, "max_line_length": 193, "alphanum_fraction": 0.5818416682, "num_tokens": 2780, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.66192288918838, "lm_q2_score": 0.4571367168274948, "lm_q1q2_score": 0.3025892563565457}}
{"text": "#include \"problems/mga_1dsm_transx.h\"\n\n#include <keplerian_toolbox/core_functions/array3D_operations.h>\n#include <keplerian_toolbox/core_functions/fb_vel.h>\n#include <keplerian_toolbox/core_functions/propagate_lagrangian.h>\n#include <keplerian_toolbox/core_functions/fb_prop.h>\n#include <keplerian_toolbox/lambert_problem.h>\n\n#include <string>\n#include <cmath>\n#include <numeric>\n#include <vector>\n\n#include <boost/array.hpp>\n#include <boost/math/constants/constants.hpp>\n\nnamespace pagmo { namespace problem {\n\nint dimension_from_params(const std::vector<kep_toolbox::planet::planet_ptr> seq, const std::vector<bool> m_dsm) {\n    int dim = 2;\n    int n = seq.size();\n    bool dsm = m_dsm.size() == 0 || (m_dsm.size() > 0 && m_dsm[0]);\n    dim += (dsm ? 4 : 1);\n    for (int i = 1; i < seq.size() - 1; ++i) {\n        dsm = m_dsm.size() == 0 || (m_dsm.size() > i && m_dsm[i]);\n        dim += (dsm ? 4 : 1);\n    }\n    return dim;\n}\n\nbool mga_1dsm_transx::dsm_in_leg_i(int i) const {\n    return (m_dsm.size() == 0) || (m_dsm.size() > i && m_dsm[i]);\n}\n\nint mga_1dsm_transx::t0_index() const { return 0; }\nint mga_1dsm_transx::tof_index() const { return 1; }\nint mga_1dsm_transx::vinf_index() const { return 3; } // 3, 4\n\nint mga_1dsm_transx::base_idx(int i) const{\n    bool dsm = dsm_in_leg_i(0);\n    int base = (tof_index() + 1);\n    if (i == 0) return base;\n\n    int idx = (base + (dsm ? 4 : 1));\n    for (int j = 1; j < i; ++j) {\n        dsm = dsm_in_leg_i(j);\n        idx += (dsm ? 4 : 1);\n    }\n    return idx;\n}\nint mga_1dsm_transx::T_idx(int i) const {\n    int base = base_idx(i);\n    if (i == 0) return base;\n\n    return base;\n}\n\nint mga_1dsm_transx::Beta_idx(int i) const {\n    int base = base_idx(i);\n    return base + 1;\n}\n\nint mga_1dsm_transx::R_idx(int i) const {\n    int base = base_idx(i);\n    return base + 2;\n}\n\nint mga_1dsm_transx::DSM_idx(int i) const {\n    int base = base_idx(i);\n    if (i == 0) return base + 4;\n\n    return base + 3;\n}\n\nmga_1dsm_transx::mga_1dsm_transx(const std::vector<kep_toolbox::planet::planet_ptr> seq,\n                    const std::vector<bool> dsm,\n                    const double dep_altitude, const double arr_altitude, const bool circularize,\n                    const kep_toolbox::epoch t0_l, const kep_toolbox::epoch t0_u,\n                    const double tof_l, const double tof_u,\n                    const double vinf_l, const double vinf_u,\n                    const bool add_vinf_dep, const bool add_vinf_arr,\n                    const bool multi_objective) : transx_problem(seq, dep_altitude, arr_altitude, circularize, dimension_from_params(seq, dsm), 1 + (int)multi_objective), m_add_vinf_dep(add_vinf_dep), m_add_vinf_arr(add_vinf_arr), m_dsm(dsm) {\n    size_t dim(get_dimension());\n    decision_vector lb(dim, 0.0), ub(dim, 0.0);\n\n      lb[0] = t0_l.mjd2000(); ub[0] = t0_u.mjd2000();\n      lb[1] = tof_l * 365.25; ub[1] = tof_u * 365.25;\n\n      lb[2] = 1e-5; ub[2] = 1 - 1e-5;\n\n      if (dsm_in_leg_i(0)) {\n        lb[vinf_index()] = lb[vinf_index() + 1] = 0.0; ub[vinf_index()] = ub[vinf_index() + 1] = 1.0;\n        lb[vinf_index() + 2] = vinf_l * 1000; ub[vinf_index() + 2] = vinf_u * 1000;\n        lb[DSM_idx(0)] = 1e-5; ub[DSM_idx(0)] = 1 - 1e-5;\n      }\n\n      for (int i = 0; i < get_n_legs() - 1; ++i) {\n        auto planet = seq[i + 1];\n\n        int j = base_idx(i + 1);\n        bool dsm = dsm_in_leg_i(i + 1);\n        lb[j] = 1e-5;  ub[j] = 1 - 1e-5; // T[i]\n        if (dsm) {\n\n            double a = planet->compute_elements()[0];\n            double soi = a * pow((planet->get_mu_self() / planet->get_mu_central_body()), 2/5);\n            double soiRad = soi / planet->get_radius();\n\n            double safeDistanceRatio = planet->get_safe_radius() / planet->get_radius();\n\n            lb[j + 1] = -2 * boost::math::constants::pi<double>(); ub[j + 1] = 2 * boost::math::constants::pi<double>(); // Beta\n            lb[j + 2] = safeDistanceRatio;   ub[j + 2] = soiRad; // Rad\n            lb[j + 3] = 1e-5;  ub[j + 3] = 1 - 1e-5;\n        }\n      }\n\n        for (int i = 1; i < get_n_legs() - 1; ++i) {\n            bool dsm = dsm_in_leg_i(i);\n            if (dsm) {\n                kep_toolbox::planet::planet_ptr pl = get_seq()[i];\n                lb[R_idx(i)] = pl->get_safe_radius() / pl->get_radius();\n            }\n        }\n\n    set_bounds(lb, ub);\n}\n\nmga_1dsm_transx::mga_1dsm_transx(const mga_1dsm_transx &p) : transx_problem(p.get_seq(), p.get_dep_altitude(), p.get_arr_altitude(), p.get_circularize(), p.get_dimension(), p.get_f_dimension()), m_dsm(p.m_dsm), m_add_vinf_arr(p.get_add_vinf_arr()), m_add_vinf_dep(p.get_add_vinf_dep()), m_multi_obj(p.get_multi_obj()) {\n  set_bounds(p.get_lb(), p.get_ub());\n}\n\nbase_ptr mga_1dsm_transx::clone() const {\n  return base_ptr(new mga_1dsm_transx(*this));\n}\n\nvoid mga_1dsm_transx::calc_objective(fitness_vector &f, const decision_vector &x, bool should_print, TransXSolution * solution) const {\n\n  std::vector<double> T(get_n_legs());\n  double alpha_sum = 0;\n  for (int i = 0; i < T.size(); ++i) {\n    T[i] = - log(x[T_idx(i)]);\n    alpha_sum += T[i];\n  }\n\n\n\n  bool dsm = dsm_in_leg_i(0);\n\n  kep_toolbox::array3D Vinf;\n  if (dsm) {\n    double theta = 2 * M_PI * x[vinf_index()];\n    double phi = acos(2 * x[vinf_index() + 1] - 1) - M_PI / 2;\n\n    double vinf = x[vinf_index() + 2];\n    Vinf[0] = vinf * cos(phi) * cos(theta);\n    Vinf[1] = vinf * cos(phi) * sin(theta);\n    Vinf[2] = vinf * sin(phi);\n\n    }\n\n  for (int i = 0; i < T.size(); ++i) {\n    T[i] = x[tof_index()] * T[i] / alpha_sum;\n  }\n\n\n  int n = get_seq().size();\n  std::vector<kep_toolbox::epoch> t_P(n);\n  std::vector<kep_toolbox::array3D> r_P(n);\n  std::vector<kep_toolbox::array3D> v_P(n);\n  std::vector<double> DV(n + 1, 0.0);\n\n  for (int i = 0; i < n; ++i) {\n    kep_toolbox::planet::planet_ptr planet = get_seq()[i];\n    t_P[i] = kep_toolbox::epoch(x[t0_index()] + std::accumulate(T.begin(), T.begin() + i, 0.0));\n    planet->eph(t_P[i], r_P[i], v_P[i]);\n  }\n\n  if (should_print) {\n    transx_time_info(solution->mutable_times(), get_seq(), t_P);\n  }\n\n  kep_toolbox::array3D r, v;\n  r = r_P[0];\n  if (dsm) {\n    if (m_add_vinf_dep) {\n        DV[0] += burn_cost(get_seq()[0], Vinf, false, true);\n    }\n    if (should_print) {\n        transx_escape(solution->mutable_escape(), get_seq()[0], v_P[0], r_P[0], Vinf, t_P[0].mjd());\n    }\n\n    kep_toolbox::array3D v0;\n    kep_toolbox::sum(v0, v_P[0], Vinf);\n    v = v0;\n    kep_toolbox::propagate_lagrangian(r, v, (dsm ? x[DSM_idx(0)] : 0) * T[0] * ASTRO_DAY2SEC, get_common_mu());\n  }\n\n  double dt = (1 - (dsm ? x[DSM_idx(0)] : 0)) * T[0] * ASTRO_DAY2SEC;\n  kep_toolbox::lambert_problem l(r, r_P[1], dt, get_common_mu());\n  kep_toolbox::array3D v_end_l(l.get_v2()[0]);\n  kep_toolbox::array3D v_beg_l(l.get_v1()[0]);\n\n  if (!dsm) {\n    kep_toolbox::diff(Vinf, v_beg_l, v_P[0]);\n    v = Vinf;\n    kep_toolbox::sum(v, v_P[0], Vinf);\n\n    if (m_add_vinf_dep) {\n        DV[0] += burn_cost(get_seq()[0], Vinf, false, true);\n    }\n    if (should_print) {\n        transx_escape(solution->mutable_escape(), get_seq()[0], v_P[0], r_P[0], Vinf, t_P[0].mjd());\n    }\n  }\n\n  kep_toolbox::array3D deltaV;\n  kep_toolbox::diff(deltaV, v_beg_l, v);\n  DV[0] += kep_toolbox::norm(deltaV);\n\n  if (dsm && should_print) {\n    transx_dsm(solution->add_dsms(), v, r, deltaV, v_beg_l, t_P[0].mjd() + T[0] - dt / ASTRO_DAY2SEC, 0);\n  }\n\n  for (int i = 1; i < n - 1; ++i) {\n    dsm = dsm_in_leg_i(i);\n\n    kep_toolbox::array3D v_rel_in, v_rel_out;\n    if (dsm) {\n        double radius = x[R_idx(i)] * get_seq()[i]->get_radius();\n        double beta = x[Beta_idx(i)];\n        kep_toolbox::array3D v_out;\n        kep_toolbox::fb_prop(v_out, v_end_l, v_P[i], radius, beta, get_seq()[i]->get_mu_self());\n\n        kep_toolbox::diff(v_rel_in, v_end_l, v_P[i]);\n        kep_toolbox::diff(v_rel_out, v_out, v_P[i]);\n\n        if (should_print) {\n            transx_flyby(solution->add_flybyes(), get_seq()[i], v_P[i], r_P[i], v_rel_in, v_rel_out, t_P[i].mjd());\n        }\n\n        r = r_P[i]; v = v_out;\n\n        kep_toolbox::propagate_lagrangian(r, v, (dsm ? x[DSM_idx(i)] : 0) * T[i] * ASTRO_DAY2SEC, get_common_mu());\n    } else {\n        r = r_P[i]; v = v_end_l;\n    }\n\n    dt = (1 - (dsm ? x[DSM_idx(i)] : 0)) * T[i] * ASTRO_DAY2SEC;\n    kep_toolbox::lambert_problem l2(r, r_P[i + 1], dt, get_common_mu());\n    v_beg_l = l2.get_v1()[0];\n    v_end_l = l2.get_v2()[0];\n\n    if (dsm) {\n        kep_toolbox::diff(deltaV, v_beg_l, v);\n        DV[i] = kep_toolbox::norm(deltaV);\n\n        if (should_print) {\n            transx_dsm(solution->add_dsms(), v, r, deltaV, v_beg_l, t_P[i].mjd() + T[i] - dt / ASTRO_DAY2SEC, 1);\n        }\n    } else {\n        kep_toolbox::diff(v_rel_in, v, v_P[i]);\n        kep_toolbox::diff(v_rel_out, v_beg_l, v_P[i]);\n\n        kep_toolbox::planet::planet_ptr planet = get_seq()[i];\n        kep_toolbox::fb_vel(DV[i], v_rel_in, v_rel_out, *planet);\n\n        double ta  = acos(kep_toolbox::dot(v_rel_in, v_rel_out)/sqrt(kep_toolbox::dot(v_rel_in,v_rel_in))/sqrt(kep_toolbox::dot(v_rel_out,v_rel_out)));\n        double alt = (planet->get_mu_self() / kep_toolbox::dot(v_rel_in,v_rel_in)*(1/sin(ta/2)-1) - planet->get_radius())/1000;\n        if (alt > planet->get_safe_radius()) {\n            f[0] = DBL_MAX;\n            return;\n        }\n\n        if (should_print) {\n            transx_flyby(solution->add_flybyes(), planet, v_P[i], r_P[i], v_rel_in, v_rel_out, t_P[i].mjd());\n        }\n    }\n\n  }\n\n  kep_toolbox::array3D Vexc_arr(v_end_l);\n  kep_toolbox::diff(Vexc_arr, v_end_l, v_P[v_P.size() - 1]);\n  if (m_add_vinf_arr) {\n    DV[DV.size() - 1] += burn_cost(get_seq()[get_seq().size() - 1], Vexc_arr, true, get_circularize());\n  }\n  if (should_print) {\n    transx_arrival(solution->mutable_arrival(), get_seq()[get_seq().size() - 1], Vexc_arr, t_P[t_P.size() - 1].mjd());\n  }\n\n  double sumDeltaV = std::accumulate(DV.begin(), DV.end(), 0.0);\n  double sumT = std::accumulate(T.begin(), T.end(), 0.0);\n\n  if (should_print) {\n    solution->set_fuel_cost(sumDeltaV);\n  }\n\n  f[0] = sumDeltaV;\n  if (get_f_dimension() == 2) {\n    f[1] = sumT;\n  }\n\n}\n\nstd::string mga_1dsm_transx::get_name() const {\n  return \"MGA-1DSM\";\n}\n\n}} // namespaces\n\nBOOST_CLASS_EXPORT_IMPLEMENT(pagmo::problem::mga_1dsm_transx)\n", "meta": {"hexsha": "cc5e1d294a001cd5c42d1621114ce71f4701e936", "size": 10227, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "orbiterkep-lib/src/problems/mga_1dsm_transx.cpp", "max_stars_repo_name": "tuzcsaba/orbiter-kep", "max_stars_repo_head_hexsha": "cf61ca82c1d171b8187ae505b3370ee9368de9f7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2016-08-28T08:49:30.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-19T11:45:50.000Z", "max_issues_repo_path": "orbiterkep-lib/src/problems/mga_1dsm_transx.cpp", "max_issues_repo_name": "tuzcsaba/orbiter-kep", "max_issues_repo_head_hexsha": "cf61ca82c1d171b8187ae505b3370ee9368de9f7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "orbiterkep-lib/src/problems/mga_1dsm_transx.cpp", "max_forks_repo_name": "tuzcsaba/orbiter-kep", "max_forks_repo_head_hexsha": "cf61ca82c1d171b8187ae505b3370ee9368de9f7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-06-12T04:28:24.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-10T10:28:24.000Z", "avg_line_length": 32.884244373, "max_line_length": 319, "alphanum_fraction": 0.59391806, "num_tokens": 3562, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6619228758499942, "lm_q2_score": 0.4571367168274948, "lm_q1q2_score": 0.3025892502590798}}
{"text": "\n//          Copyright Gavin Band 2008 - 2012.\n// Distributed under the Boost Software License, Version 1.0.\n//    (See accompanying file LICENSE_1_0.txt or copy at\n//          http://www.boost.org/LICENSE_1_0.txt)\n\n#include <string>\n#include <vector>\n#include <boost/function.hpp>\n#include <boost/bind.hpp>\n#include <boost/math/distributions/chi_squared.hpp>\n#include \"genfile/Error.hpp\"\n#include \"genfile/ToGP.hpp\"\n#include \"genfile/VariantDataReader.hpp\"\n#include \"metro/likelihood/Multinomial.hpp\"\n#include \"components/SNPSummaryComponent/SNPHWE.hpp\"\n#include \"components/SNPSummaryComponent/SNPSummaryComputation.hpp\"\n#include \"components/SNPSummaryComponent/HWEComputation.hpp\"\n#include \"components/SNPSummaryComponent/IntensitySummaryComputation.hpp\"\n#include \"components/SNPSummaryComponent/ClusterFitComputation.hpp\"\n#include \"components/SNPSummaryComponent/InfoComputation.hpp\"\n\n// #define DEBUG_SNP_SUMMARY_COMPUTATION 1\n\nnamespace stats {\t\n\tnamespace {\n\t\tstruct AlleleCountClient: public genfile::VariantDataReader::PerSampleSetter {\n\t\t\tAlleleCountClient( std::vector< double >* counts ):\n\t\t\t\tm_counts( counts ),\n\t\t\t\tm_number_of_alleles( 0 )\n\t\t\t{\n\t\t\t\tassert( counts != 0 ) ;\n\t\t\t}\n\n\t\t\t~AlleleCountClient() throw() {}\n\t\t\t\n\t\t\tvoid set_counts( std::vector< double >* counts ) {\n\t\t\t\tassert( counts != 0 ) ;\n\t\t\t\tm_counts = counts ;\n\t\t\t}\n\t\t\t\n\t\t\tvoid initialise( std::size_t number_of_samples, std::size_t number_of_alleles ) {\n\t\t\t\tm_number_of_alleles = number_of_alleles ;\n\t\t\t\tassert( m_counts->size() == number_of_alleles ) ;\n\t\t\t}\n\t\t\t\n\t\t\tbool set_sample( std::size_t i ) {\n\t\t\t\tm_ploidy = 0 ;\n\t\t\t\tm_table = 0 ;\n\t\t\t\treturn true ;\n\t\t\t}\n\t\t\t\n\t\t\tvoid set_number_of_entries( uint32_t ploidy, std::size_t n, OrderType const order_type, ValueType const value_type ) {\n\t\t\t\tassert( order_type == genfile::ePerUnorderedGenotype ) ;\n\t\t\t\tassert( value_type == genfile::eProbability ) ;\n\t\t\t\t\n\t\t\t\tstd::map< uint32_t, genfile::impl::Enumeration >::iterator where = m_tables.find( ploidy ) ;\n\t\t\t\tif( where == m_tables.end() ) {\n\t\t\t\t\tstd::pair< std::map< uint32_t, genfile::impl::Enumeration >::iterator, bool >\n\t\t\t\t\t\tresult = m_tables.insert( std::make_pair( ploidy, genfile::impl::enumerate_unphased_genotypes( ploidy ) )) ;\n\t\t\t\t\tassert( result.second ) ;\n\t\t\t\t\twhere = result.first ;\n\t\t\t\t}\n\t\t\t\tm_ploidy = ploidy ;\n\t\t\t\tm_table = &(where->second) ;\n\t\t\t}\n\t\t\t\n\t\t\tvoid set_value( std::size_t value_i, genfile::MissingValue const value ) {\n\t\t\t\tset_value( value_i, 0.0 ) ;\n\t\t\t}\n\n\t\t\tvoid set_value( std::size_t value_i, double const value ) {\n\t\t\t\tassert( value_i <= std::size_t( std::numeric_limits< uint16_t >::max() )) ;\n\t\t\t\tgenfile::impl::Enumeration const& enumeration = *m_table ;\n\t\t\t\tstd::size_t const& maxAlleles = enumeration.first.second ;\n\t\t\t\tassert( m_number_of_alleles <= maxAlleles ) ;\n\t\t\t\tuint16_t const encodedGenotype = enumeration.second.second[ uint16_t( value_i ) ] ;\n\t\t\t\tuint32_t const bitsPerAllele = enumeration.first.first ;\n\t\t\t\tuint16_t mask = uint16_t( 0xFFFF ) >> ( 16 - bitsPerAllele ) ;\n\t\t\t\t// Dosage of the 1st allele in the genotype is not encoded directly.\n\t\t\t\t// We compute it as the ploidy minus the dosage of other alleles.\n\t\t\t\tuint16_t dosage_of_nonref_alleles = 0 ;\n\t\t\t\tfor( std::size_t allele = 1; allele < m_number_of_alleles; ++allele ) {\n\t\t\t\t\tuint16_t const dosage = ( encodedGenotype >> ( (allele-1) * bitsPerAllele )) & mask ;\n\t\t\t\t\t(*m_counts)[allele] += value * dosage ;\n\t\t\t\t\tdosage_of_nonref_alleles += dosage ;\n\t\t\t\t}\n\t\t\t\t(*m_counts)[0] += value * (m_ploidy - dosage_of_nonref_alleles) ;\n\t\t\t}\n\t\t\t\n\t\t\tvoid finalise() {}\n\t\tprivate:\n\t\t\tstd::vector< double >* m_counts ;\n\t\t\tstd::size_t m_number_of_alleles ;\n\t\t\tuint32_t m_ploidy ;\n\t\t\tstd::map< uint32_t, genfile::impl::Enumeration > m_tables ;\n\t\t\tgenfile::impl::Enumeration* m_table ;\n\t\t} ;\n\t}\n\n\tstruct AlleleCountComputation: public SNPSummaryComputation {\n\tpublic:\n\t\t\n\t\tAlleleCountComputation():\n\t\t\tm_counter( &m_counts )\n\t\t{}\n\n\t\tvoid list_variables( NameCallback callback ) const {\n\t\t\tusing genfile::string_utils::to_string ;\n\t\t\t// By default we list 10 alleles\n\t\t\tcallback( \"number_of_alleles\" ) ;\n\t\t\tfor( std::size_t i = 0; i < 10; ++i ) {\n\t\t\t\tcallback( \"allele\" + to_string(i+1) + \"_count\" ) ;\n\t\t\t}\n\t\t}\n\n\t\tvoid operator()(\n\t\t\tVariantIdentifyingData const& snp,\n\t\t\tGenotypes const& genotypes,\n\t\t\tPloidy const& ploidy,\n\t\t\tgenfile::VariantDataReader& data_reader,\n\t\t\tResultCallback callback\n\t\t) {\n\t\t\tusing genfile::string_utils::to_string ;\n\t\t\tm_counts = std::vector< double >( snp.number_of_alleles(), 0.0 ) ;\n\t\t\tm_counter.set_counts( &m_counts ) ;\n\t\t\tcallback( \"number_of_alleles\", int64_t( snp.number_of_alleles() )) ;\n\t\t\tdata_reader.get( \":genotypes:\", genfile::to_GP_unphased( m_counter ) ) ;\n\t\t\tstd::size_t i = 0 ;\n\t\t\tfor( ; i < snp.number_of_alleles(); ++i ) {\n\t\t\t\tcallback( \"allele\" + to_string(i+1) + \"_count\", m_counts[i] ) ;\n\t\t\t}\n\t\t\tfor( ; i < 10; ++i ) {\n\t\t\t\tcallback( \"allele\" + to_string(i+1) + \"_count\", genfile::MissingValue() ) ;\n\t\t\t}\n\t\t}\n\t\t\n\t\tstd::string get_summary( std::string const& prefix, std::size_t column_width ) const {\n\t\t\treturn prefix + \"AlleleCountComputation\" ;\n\t\t}\n\tprivate:\n\t\tstd::vector< double > m_counts ;\n\t\tAlleleCountClient m_counter ;\n\t} ;\n\n\tstruct AlleleFrequencyComputation: public SNPSummaryComputation\n\t{\n\t\tAlleleFrequencyComputation( std::string const& what ):\n\t\t\tm_compute_counts( what == \"everything\" || what == \"counts\" ),\n\t\t\tm_compute_frequencies( what == \"everything\" )\n\t\t{\n\t\t\tassert( what == \"counts\" || what == \"everything\" ) ;\n\t\t}\n\t\tvoid operator()(\n\t\t\tVariantIdentifyingData const& snp,\n\t\t\tGenotypes const& genotypes,\n\t\t\tPloidy const& ploidy,\n\t\t\tgenfile::VariantDataReader&,\n\t\t\tResultCallback callback\n\t\t) {\n\t\t\tif( snp.number_of_alleles() == 2 ) {\n\t\t\t\tbool const allDiploid = ( ploidy.array() == 2 ).cast< int >().sum() == ploidy.size() ;\n\t\t\t\tif( allDiploid ) {\n\t\t\t\t\tcompute_autosomal_frequency( snp, genotypes, callback ) ;\n\t\t\t\t} else {\n\t\t\t\t\tcompute_sex_chromosome_frequency( snp, genotypes, ploidy, callback ) ;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\tvoid compute_sex_chromosome_frequency(\n\t\t\tVariantIdentifyingData const& snp,\n\t\t\tGenotypes const& genotypes,\n\t\t\tPloidy const& ploidy,\n\t\t\tResultCallback callback\n\t\t) {\n\t\t\tGenotypes haploid_genotypes = genotypes ;\n\t\t\tGenotypes diploid_genotypes = genotypes ;\n\t\t\tassert( std::size_t( genotypes.rows() ) == ploidy.size() ) ;\n\n\t\t\tfor( int i = 0; i < genotypes.rows(); ++i ) {\n\t\t\t\tif( ploidy(i) != 1 ) {\n\t\t\t\t\thaploid_genotypes.row(i).setZero() ;\n\t\t\t\t}\n\t\t\t\tif( ploidy(i) != 2 ) {\n\t\t\t\t\tdiploid_genotypes.row(i).setZero() ;\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\tdouble const a_allele_count = haploid_genotypes.col(0).sum()\n\t\t\t\t+ ( ( 2.0 * diploid_genotypes.col(0).sum() ) + diploid_genotypes.col(1).sum() ) ;\n\t\t\tdouble const b_allele_count = haploid_genotypes.col(1).sum()\n\t\t\t\t+ ( ( 2.0 * diploid_genotypes.col(2).sum() ) + diploid_genotypes.col(1).sum() ) ;\n\n\t\t\tif( m_compute_counts ) {\n\t\t\t\tcallback( \"alleleA_count\", a_allele_count ) ;\n\t\t\t\tcallback( \"alleleB_count\", b_allele_count ) ;\n\t\t\t}\n\n\t\t\tif( m_compute_frequencies ) {\n\t\t\t\tdouble const total_allele_count = ( haploid_genotypes.sum() + 2.0 * diploid_genotypes.sum() ) ;\n\t\t\t\tdouble const a_allele_freq = a_allele_count / total_allele_count ;\n\t\t\t\tdouble const b_allele_freq = b_allele_count / total_allele_count ;\n\n\t\t\t\tcallback( \"alleleA_frequency\", a_allele_freq ) ;\n\t\t\t\tcallback( \"alleleB_frequency\", b_allele_freq ) ;\n\n\t\t\t\tif( a_allele_freq < b_allele_freq ) {\n\t\t\t\t\tcallback( \"minor_allele_frequency\", a_allele_freq ) ;\n\t\t\t\t\tcallback( \"minor_allele\", snp.get_allele(0) ) ;\n\t\t\t\t\tcallback( \"major_allele\", snp.get_allele(1) ) ;\n\t\t\t\t}\n\t\t\t\telse if( a_allele_freq > b_allele_freq ) {\n\t\t\t\t\tcallback( \"minor_allele_frequency\", b_allele_freq ) ;\n\t\t\t\t\tcallback( \"minor_allele\", snp.get_allele(1) ) ;\n\t\t\t\t\tcallback( \"major_allele\", snp.get_allele(0) ) ;\n\t\t\t\t} else {\n\t\t\t\t\tcallback( \"minor_allele_frequency\", a_allele_freq ) ;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tvoid compute_autosomal_frequency( VariantIdentifyingData const& snp, Genotypes const& genotypes, ResultCallback callback ) {\n\t\t\tdouble const a_allele_count = ( 2.0 * genotypes.col(0).sum() ) + genotypes.col(1).sum() ;\n\t\t\tdouble const b_allele_count = ( 2.0 * genotypes.col(2).sum() ) + genotypes.col(1).sum() ;\n\n\t\t\tif( m_compute_counts ) {\n\t\t\t\tcallback( \"alleleA_count\", a_allele_count ) ;\n\t\t\t\tcallback( \"alleleB_count\", b_allele_count ) ;\n\t\t\t}\n\t\t\t\n\t\t\tif( m_compute_frequencies ) {\n\t\t\t\tdouble const total_allele_count = ( 2.0 * genotypes.sum() ) ;\n\t\t\t\tdouble const a_allele_freq = a_allele_count / total_allele_count ;\n\t\t\t\tdouble const b_allele_freq = b_allele_count / total_allele_count ;\n\n\t\t\t\tcallback( \"alleleA_frequency\", a_allele_freq ) ;\n\t\t\t\tcallback( \"alleleB_frequency\", b_allele_freq ) ;\n\n\t\t\t\tif( a_allele_freq < b_allele_freq ) {\n\t\t\t\t\tcallback( \"minor_allele_frequency\", a_allele_freq ) ;\n\t\t\t\t\tcallback( \"minor_allele\", snp.get_allele(0) ) ;\n\t\t\t\t\tcallback( \"major_allele\", snp.get_allele(1) ) ;\n\t\t\t\t}\n\t\t\t\telse if( a_allele_freq > b_allele_freq ) {\n\t\t\t\t\tcallback( \"minor_allele_frequency\", b_allele_freq ) ;\n\t\t\t\t\tcallback( \"minor_allele\", snp.get_allele(1) ) ;\n\t\t\t\t\tcallback( \"major_allele\", snp.get_allele(0) ) ;\n\t\t\t\t} else {\n\t\t\t\t\tcallback( \"minor_allele_frequency\", a_allele_freq ) ;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\tstd::string get_summary( std::string const& prefix, std::size_t column_width ) const {\n\t\t\treturn prefix + \"AlleleFrequencyComputation\" ;\n\t\t}\n\tprivate:\n\t\tbool const m_compute_counts ;\n\t\tbool const m_compute_frequencies ;\n\t} ;\n\n\t// What proportion of the mass on a genotype is due to high-confidence calls?\n\tstruct CallMassComputation: public SNPSummaryComputation\n\t{\n\t\t\n\t\tCallMassComputation( double const threshhold = 0.9 ):\n\t\t\tm_threshhold(threshhold)\n\t\t{}\n\n\t\tvoid operator()( VariantIdentifyingData const& snp, Genotypes const& genotypes, Ploidy const& ploidy, genfile::VariantDataReader&, ResultCallback callback ) {\n\t\t\tbool const allDiploid = ( ploidy.array() == 2 ).cast< int >().sum() == ploidy.size() ;\n\t\t\tif( allDiploid ) {\n\t\t\t\tcompute_autosomal_call_mass( snp, genotypes, callback ) ;\n\t\t\t} else {\n\t\t\t\treturn ;\n\t\t\t}\n\t\t}\n\t\t\n\t\tvoid compute_autosomal_call_mass( VariantIdentifyingData const& snp, Genotypes const& genotypes, ResultCallback callback ) {\n\t\t\tEigen::VectorXd const masses = genotypes.colwise().sum() ;\n\t\t\tm_hcGenotypes = ( genotypes.array() > m_threshhold ).cast< double >()  * genotypes.array() ;\t\n\t\t\tEigen::VectorXd const hcMasses = m_hcGenotypes.colwise().sum() ; \n\n\t\t\tcallback( \"AA_mass_propn\", hcMasses(0)/masses(0) ) ;\n\t\t\tcallback( \"AB_mass_propn\", hcMasses(1)/masses(1) ) ;\n\t\t\tcallback( \"BB_mass_propn\", hcMasses(2)/masses(2) ) ;\n\n\t\t\tcallback( \"non-AA-mass_propn\", (hcMasses(1)+hcMasses(2))/(masses(1)+masses(2))) ;\n\t\t\tcallback( \"non-BB-mass_propn\", (hcMasses(1)+hcMasses(0))/(masses(1)+masses(0))) ;\n\t\t}\n\t\t\n\t\tstd::string get_summary( std::string const& prefix, std::size_t column_width ) const {\n\t\t\treturn prefix + \"CallMassComputation\" ;\n\t\t}\n\tprivate:\n\t\tdouble const m_threshhold ;\n\t\tGenotypes m_hcGenotypes ;\n\t} ;\n\t\n\tstruct MissingnessComputation: public SNPSummaryComputation {\n\t\tMissingnessComputation( double call_threshhold = 0.9 ): m_call_threshhold( call_threshhold ) {}\n\t\tvoid operator()(\n\t\t\tVariantIdentifyingData const& snp,\n\t\t\tGenotypes const& genotypes,\n\t\t\tPloidy const& ploidy,\n\t\t\tgenfile::VariantDataReader&,\n\t\t\tResultCallback callback\n\t\t) {\n\t\t\tassert( std::size_t( genotypes.rows() ) == ploidy.size() ) ;\n\n\t\t\tdouble missingness = double( genotypes.rows() ) - genotypes.array().sum() ;\n\t\t\tcallback( \"missing_proportion\", missingness / double( genotypes.rows() ) ) ;\n\n\t\t\tbool const allDiploid = ( ploidy.array() == 2 ).cast< int >().sum() == ploidy.size() ;\n\t\t\tif( allDiploid ) {\n\t\t\t\tcallback( \"A\", 0 ) ;\n\t\t\t\tcallback( \"B\", 0 ) ;\n\t\t\t\tif( snp.number_of_alleles() == 2 ) {\n\t\t\t\t\tcallback( \"AA\", genotypes.col(0).sum() ) ;\n\t\t\t\t\tcallback( \"AB\", genotypes.col(1).sum() ) ;\n\t\t\t\t\tcallback( \"BB\", genotypes.col(2).sum() ) ;\n\t\t\t\t}\n\t\t\t\tcallback( \"NULL\", genotypes.rows() - genotypes.sum() ) ;\n\t\t\t} else {\n\t\t\t\tcompute_haploid_diploid_counts( snp, genotypes, ploidy, callback ) ;\n\t\t\t}\n\t\t\tcallback( \"total\", genfile::VariantEntry::Integer( genotypes.rows() )) ;\n\t\t}\n\t\t\n\t\tvoid compute_haploid_diploid_counts(\n\t\t\tVariantIdentifyingData const& snp,\n\t\t\tGenotypes const& genotypes,\n\t\t\tPloidy const& ploidy,\n\t\t\tResultCallback callback\n\t\t) {\n\t\t\tstd::map< int, Eigen::VectorXd > counts ;\n\t\t\tstd::map< int, double > null_counts ;\n\t\t\tcounts[ -1 ] = Eigen::VectorXd::Zero( 3 ) ;\n\t\t\tcounts[ 0 ] = Eigen::VectorXd::Zero( 3 ) ;\n\t\t\tcounts[ 1 ] = Eigen::VectorXd::Zero( 3 ) ;\n\t\t\tcounts[ 2 ] = Eigen::VectorXd::Zero( 3 ) ;\n\t\t\tstd::map< int, std::size_t > sample_counts ;\n\n\t\t\tfor( std::size_t i = 0; i < ploidy.size(); ++i ) {\n\t\t\t\tcounts[ ploidy(i) ] += genotypes.row( i ) ;\n\t\t\t\tnull_counts[ ploidy(i) ] += ( 1 - genotypes.row(i).sum() ) ;\n\t\t\t\t++sample_counts[ ploidy(i) ] ;\n#if DEBUG_SNP_SUMMARY_COMPUTATION\n\t\t\t\tif( ploidy(i) == 1 && genotypes(i,2) != 0 ) {\n\t\t\t\t\tstd::cerr << \"! ( MissingnessComputation::compute_sex_chromosome_counts() ): individual \" << (i+1) << \"is male but has genotype \" << genotypes.row(i) << \"!!\\n\" ;\n\t\t\t\t}\n#endif\n\t\t\t}\n\t\t\t\n\t\t\tcallback( \"A\", counts[ 1 ]( 0 ) ) ;\n\t\t\tcallback( \"B\", counts[ 1 ]( 1 ) ) ;\n\t\t\tcallback( \"AA\", counts[ 2 ]( 0 ) ) ;\n\t\t\tcallback( \"AB\", counts[ 2 ]( 1 ) ) ;\n\t\t\tcallback( \"BB\", counts[ 2 ]( 2 ) ) ;\n\t\t\tcallback( \"NULL\", null_counts[ 'm' ] + null_counts[ 'f' ] ) ;\n\t\t\tcallback( \"unknown_ploidy\", counts[ -1 ].sum() + null_counts[ -1 ] ) ;\n\t\t\tassert( counts[ 1 ]( 2 ) == 0 ) ;\n\t\t}\n\t\t\n\t\tstd::string get_summary( std::string const& prefix = \"\", std::size_t column_width = 20 ) const { return prefix + \"MissingnessComputation\" ; }\n\tprivate:\n\t\tdouble const m_call_threshhold ;\n\t} ;\n\n\tSNPSummaryComputation::UniquePtr SNPSummaryComputation::create(\n\t\tstd::string const& name\n\t) {\n\t\tUniquePtr result ;\n\t\tif( name == \"allele-frequencies\" ) { result.reset( new stats::AlleleFrequencyComputation( \"everything\" )) ; }\n\t\telse if( name == \"allele-counts\" ) { result.reset( new stats::AlleleFrequencyComputation( \"counts\" )) ; }\n\t\telse if( name == \"HWE\" ) { result.reset( new stats::HWEComputation()) ; }\n\t\telse if( name == \"missingness\" ) { result.reset( new stats::MissingnessComputation()) ; }\n\t\telse if( name == \"info\" ) { result.reset( new stats::InfoComputation()) ; }\n\t\telse if( name == \"call-mass-proportion\" ) { result.reset( new stats::CallMassComputation()) ; }\n\t\telse if( name == \"intensity-stats\" ) { result.reset( new stats::IntensitySummaryComputation() ) ; }\n\t\telse if( name == \"multi-allele-counts\" ) { result.reset( new stats::AlleleCountComputation() ) ; }\n\t\telse {\n\t\t\tthrow genfile::BadArgumentError( \"SNPSummaryComputation::create()\", \"name=\\\"\" + name + \"\\\"\" ) ;\n\t\t}\n\t\treturn result ;\n\t}\n}\n", "meta": {"hexsha": "5728725de7f79edd1a1895fa36bb6aeba1d7ca8a", "size": 14590, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "components/SNPSummaryComponent/src/SNPSummaryComputation.cpp", "max_stars_repo_name": "gavinband/qctool", "max_stars_repo_head_hexsha": "8d8adb45151c91f953fe4a9af00498073b1132ba", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2021-04-21T05:42:24.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-26T14:59:43.000Z", "max_issues_repo_path": "components/SNPSummaryComponent/src/SNPSummaryComputation.cpp", "max_issues_repo_name": "gavinband/qctool", "max_issues_repo_head_hexsha": "8d8adb45151c91f953fe4a9af00498073b1132ba", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-04-09T16:11:04.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-10T11:18:56.000Z", "max_forks_repo_path": "components/SNPSummaryComponent/src/SNPSummaryComputation.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": 37.5064267352, "max_line_length": 166, "alphanum_fraction": 0.6662782728, "num_tokens": 4438, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6001883735630721, "lm_q2_score": 0.5039061705290805, "lm_q1q2_score": 0.30243862491824486}}
{"text": "#include <cmath>\n\n#include <boost/scoped_ptr.hpp>\n/*#include <boost/accumulators/accumulators.hpp>\n #include <boost/accumulators/statistics/stats.hpp>\n #include <boost/accumulators/statistics/min.hpp>\n #include <boost/accumulators/statistics/mean.hpp>\n #include <boost/accumulators/statistics/variance.hpp>\n #include <boost/accumulators/statistics/max.hpp>*/\n\n#include <BnSimulator/util/utility.hpp>\n#include <BnSimulator/util/state_util.hpp>\n#include <BnSimulator/core/BooleanNetwork.hpp>\n#include <BnSimulator/experiment/DamianiPlotter.hpp>\n\nnamespace bn {\n\nusing namespace std;\n\nusing namespace boost;\n\nDamianiPlotter::PlotData DamianiPlotter::computePlot(BooleanNetwork& net,\n\t\tconst size_t order) const {\n\tassert(order > 0);\n\tPlotData data(maxSteps);\n\tfor (size_t p = 0; p < probes; ++p) {\n\t\tState s0 = util::random_state(net.size());\n\t\tState sx = util::perturb_state_randomly(s0, order);\n\t\tassert(util::hamming_distance(s0, sx) == order);\n\t\tscoped_ptr<vector<State> > t0(traceNetwork(net, s0));\n\t\tscoped_ptr<vector<State> > tx(traceNetwork(net, sx));\n\t\tfor (size_t i = 0; i < maxSteps; ++i) {\n\t\t\tdata[i] += (static_cast<double> (util::hamming_distance((*t0)[i],\n\t\t\t\t\t(*tx)[i])) / net.size()) / probes;\n\t\t}\n\t}\n\treturn data;\n}\n\nDamianiPlotter::PlotData DamianiPlotter::computePlot(BooleanNetwork& net,\n\t\tconst double d) const {\n\tassert(d >= 0 && d <= 1);\n\treturn computePlot(net,\n\t\t\tstatic_cast<size_t> (std::floor(net.size() * d)));\n}\n\nvector<State>* DamianiPlotter::traceNetwork(BooleanNetwork& net,\n\t\tconst State& s0) const {\n\tnet.setState(s0);\n\tvector<State>* trajectory = new vector<State> (maxSteps);\n\tfor (size_t t = 0; t < maxSteps; ++t, net.update()) {\n\t\t(*trajectory)[t] = net.getState();\n\t}\n\treturn trajectory;\n}\n\n} // namespace bn\n", "meta": {"hexsha": "0a83ac307a36f4044ab2748849a85d659cad02dd", "size": 1747, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "booleannetwork-code-66-trunk/booleannetwork-code-66-trunk/src/BnSimulator/experiment/DamianiPlotter.cpp", "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/src/BnSimulator/experiment/DamianiPlotter.cpp", "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/src/BnSimulator/experiment/DamianiPlotter.cpp", "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": 30.1206896552, "max_line_length": 73, "alphanum_fraction": 0.7126502576, "num_tokens": 487, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6001883735630721, "lm_q2_score": 0.5039061705290805, "lm_q1q2_score": 0.30243862491824486}}
{"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 aig_from_bdd.hpp\n *\n * @brief Create AIGs from BDDs\n *\n * @author Mathias Soeken\n * @since  2.0\n */\n\n#include \"aig_from_bdd.hpp\"\n\n#include <boost/format.hpp>\n\n#include <cuddInt.h>\n\n#include <classical/utils/aig_utils.hpp>\n\nnamespace cirkit\n{\n\naig_function aig_from_bdd_rec( aig_graph& aig, DdManager* dd, DdNode* node )\n{\n  const auto& info = aig_info( aig );\n\n  auto   is_complement = Cudd_IsComplement( node );\n  auto * r = Cudd_Regular( node );\n\n  aig_function f;\n\n  if ( Cudd_IsConstant( r ) )\n  {\n    f = aig_get_constant( aig, r == DD_ONE( dd ) );\n  }\n  else\n  {\n    auto index = Cudd_NodeReadIndex( r );\n\n    auto f_true  = aig_from_bdd_rec( aig, dd, cuddT( r ) );\n    auto f_false = aig_from_bdd_rec( aig, dd, cuddE( r ) );\n\n    f = aig_create_ite( aig, {info.inputs[index], false}, f_true, f_false );\n  }\n\n  return is_complement ? !f : f;\n}\n\naig_function aig_from_bdd( aig_graph& aig, DdManager* dd, DdNode* node )\n{\n  const auto& info = aig_info( aig );\n\n  auto n = Cudd_ReadSize( dd );\n  auto num_pis = info.inputs.size();\n\n  for ( auto i = num_pis; static_cast<int>( i ) < n; ++i )\n  {\n    aig_create_pi( aig, boost::str( boost::format( \"x%d\" ) % i ) );\n  }\n\n  return aig_from_bdd_rec( aig, dd, node );\n}\n\naig_function aig_from_bdd( aig_graph& aig, const BDD& node )\n{\n  return aig_from_bdd( aig, node.manager(), node.getNode() );\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": "e5d434bed2ad760f0495b8b18850b4a50ad593ec", "size": 2695, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/classical/utils/aig_from_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/utils/aig_from_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/utils/aig_from_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.95, "max_line_length": 76, "alphanum_fraction": 0.6927643785, "num_tokens": 776, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.577495350642608, "lm_q2_score": 0.523420348936324, "lm_q1q2_score": 0.3022728179424587}}
{"text": "/*\n * EigenvalueCovariance.cpp\n *\n *  Created on: May 6, 2015\n *      Author: dbazazian\n */\n\n     #include <iostream>\n     #include <Eigen/Eigenvalues>\n     #include <Eigen/Dense>\n     #include <vector>\n     #include <math.h>\n     #include <cmath>\n     #include <fstream>\n     #include <string>\n     #include <vector>\n     #include <pcl/io/io.h>\n     #include <pcl/io/pcd_io.h>\n     #include <pcl/point_types.h>\n     #include <pcl/features/integral_image_normal.h>\n     #include <pcl/features/normal_3d.h>\n     #include <pcl/common/common_headers.h>\n     #include <pcl/features/integral_image_normal.h>\n     #include <pcl/features/normal_3d.h>\n     #include <pcl/visualization/cloud_viewer.h>\n     #include <pcl/filters/passthrough.h>\n     #include <pcl/ModelCoefficients.h>\n     #include <pcl/filters/project_inliers.h>\n     #include <pcl/features/shot_omp.h>\n     #include \"pcl/features/fpfh.h\"\n     #include <pcl/io/ply_io.h>\n\nusing namespace std;\nusing namespace Eigen;\n\n\nint\nmain (int argc, char*argv[])\n{\n\t  pcl::PointCloud<pcl::PointXYZRGBA>::Ptr cloud (new pcl::PointCloud<pcl::PointXYZRGBA>);\n\t\tpcl::PointCloud<pcl::PointXYZRGBA>::Ptr RelevantElements(new pcl::PointCloud<pcl::PointXYZRGBA>);\n\t\tpcl::PointCloud<pcl::PointXYZRGBA>::Ptr SelectedElements(new pcl::PointCloud<pcl::PointXYZRGBA>);\n\n\n\t // pcl::io::loadPCDFile (\"/Path/TO/ArtificialPointClouds/TwoPlane45.pcd\", *cloud);\n\t // pcl::io::loadPCDFile (\"/Path/TO/ArtificialPointClouds/CubeSharpEdge.pcd\", *cloud);\n\t  // pcl::io::loadPCDFile (\"/Path/TO/ArtificialPointClouds/OnePlane.pcd\", *cloud);\n\t      // pcl::io::loadPCDFile (\"/Path/TO/ArtificialPointClouds/bunny.pcd\",*cloud);\n\t     //  pcl::io::loadPCDFile (\"/Path/TO/ArtificialPointClouds/Statue.pcd\", *cloud);\n\t  //  pcl::io::loadPCDFile (\"/Path/TO/ArtificialPointClouds/dragon.pcd\", *cloud);\n\n\n\t  //   pcl::io::loadPCDFile (\"/Path/TO/ArtificialPointClouds/AimAtShape/trim-starC.pcd\", *cloud);\n\t      //\tpcl::io::loadPCDFile (\"/Path/TO/ArtificialPointClouds/AimAtShape/VaseC.pcd\", *cloud);\n\t       //  pcl::io::loadPCDFile (\"/Path/TO/ArtificialPointClouds/AimAtShape/twirlC.pcd\", *cloud);\n\t      \t//  pcl::io::loadPCDFile (\"/Path/TO/ArtificialPointClouds/AimAtShape/fandiskC.pcd\", *cloud);\n\t      // pcl::io::loadPCDFile (\"/Path/TO/ArtificialPointClouds/AimAtShape/sharp_sphereC.pcd\", *cloud);\n\t\t// pcl::io::loadPCDFile (\"/Path/TO/ArtificialPointClouds/CubeFractal2.pcd\", *cloud);\n\t\t//  pcl::io::loadPCDFile (\"/Path/TO/ArtificialPointClouds/AddingNoise/Frac2Guass12Noise.pcd\", *cloud);\n\t\t  // pcl::io::loadPCDFile (\"/Path/TO/ArtificialPointClouds/IntersectionThreePlanes.pcd\", *cloud);\n\t\t// pcl::io::loadPCDFile (\"/Path/TO/ArtificialPointClouds/SpherMultiple.pcd\", *cloud);\n\t\t // pcl::io::loadPCDFile (\"/Path/TO/ArtificialPointClouds/Tetrahedron.pcd\", *cloud);\n\t\t //pcl::io::loadPCDFile (\"/Path/TO/ArtificialPointClouds/AddingNoise/TetrahedronNoise35.pcd\", *cloud);\n\t\t   pcl::io::loadPCDFile (\"/Path/TO/ArtificialPointClouds/TetrahedronMultiple.pcd\", *cloud);\n\n\n\n\t  pcl::PointCloud<pcl::PointXYZRGBA>::Ptr edge (new pcl::PointCloud<pcl::PointXYZRGBA>);\n\t // pcl::io::loadPCDFile (\"/Path/TO/GroundTruth/GroundTruthTwoPlaneX.pcd\", *edge);\n\t  \t  // pcl::io::loadPCDFile (\"/Path/TO/GroundTruth/GroundTruthTwoPlaneY.pcd\", *edge);\n\t  \t// pcl::io::loadPCDFile (\"/Path/TO/GroundTruth/ExactEdge.pcd\", *edge);\n\t  \t// pcl::io::loadPCDFile (\t\"/Path/TO/GroundTruth/GroundtruthFractal2.pcd\", *edge);\n\t // pcl::io::loadPCDFile (\t\"/Path/TO/GroundTruth/GroundTruthThreeoPlanes.pcd\", *edge);\n\t // pcl::io::loadPCDFile (\t\"/Path/TO/GroundTruth/GroundTruthTetrahedron.pcd\", *edge);\n\t  pcl::io::loadPCDFile (\"/Path/TO/GroundTruth/GroundTruthTetrahedronMultiple.pcd\", *edge);\n\n\n\t   std::cout << \"Number of points in the Cube Input cloud is:\"<< cloud->points.size() << std::endl;\n\t   std::cout << \"Number of points in the Edge Ground Truth cloud is:\"<< edge->points.size() << std::endl;\n\n\n\t   // Compute distance between all the points of the flat cloud and points of the Edge cloud\n\t   \tstd::vector<std::vector <double> > Distances ; // 2D vector(Matrix) for each point that has the Angle between lines of normals around barycenter\n\t   \t\t int heightD;\n\t   \t\t int widthD;\n\t    // defining an empty 2D vector (matrix)\n\t   \t heightD= cloud ->points.size ();\n\t   \t\t widthD = edge ->points.size ();\n\t   \t\t\t Distances.resize(heightD); // to defining numbers of row in 2D vector\n\t   \t\t\t\t   for(int jj=0; jj< heightD; ++jj)\n\t   \t\t\t\t   \t{Distances[jj].resize(widthD);}   // to defining numbers of column for each row in 2d vector\n\n\t   for (size_t ii = 0; ii < cloud ->points.size (); ++ii) {\n\t    for (size_t jj = 0; jj< edge ->points.size (); ++jj) {\n\t   double distance = sqrt (   \t( ( (cloud->points[ii].x)\t-  (edge->points[jj].x) ) *  ( (cloud->points[ii].x)\t-  (edge->points[jj].x) ) ) +   ( ( (cloud->points[ii].y)\t-  (edge->points[jj].y) ) *  ( (cloud->points[ii].y)\t-  (edge->points[jj].y) ) ) + ( ( (cloud->points[ii].z)\t-  (edge->points[jj].z) ) *  ( (cloud->points[ii].z)\t-  (edge->points[jj].z) ) )   );\n\t   \t\tDistances [ii][jj] = distance;\n\t   \t\t\t }\n\t   \t\t }\n\t   \t // Define a cloud for the relevant elements\n\t   \t double relevantsize = 0.00 ;\n\t   \t\t // find minimum distance for each line\n\t   \t\tstd::vector<double> MinDistances;\n\t   \t\t for (size_t ii = 0; ii < cloud ->points.size (); ++ii) {\n\t   \t\t double min = 100.00;\n\t   \t\tfor (size_t jj = 0; jj< edge ->points.size (); ++jj) {\n\t   \t\t if (Distances [ii][jj] < min ){\n\t   \t\t\t min = Distances [ii][jj] ;}\n\t   \t\t\t\t   }\n\t   \tMinDistances .push_back (min );\n\t   \t if (min< 0.0075){\n\t   // Copy the \tcoordinates on to  the relevant cloud\n\t   \t\t\t\tpcl::PointXYZRGBA basic_point;\n\t   \t\t\t\tbasic_point.x = cloud->points[ii].x;\n\t   \t\t\t\tbasic_point.y = cloud->points[ii].y;\n\t   \t\t\t\tbasic_point.z = cloud->points[ii].z;\n\t   \t\t\t\tbasic_point.r = 255;\n\t   \t\t\t\tbasic_point.g = 255;\n\t   \t\t\t\tbasic_point.b= 255;\n\t   \t\t\t\tRelevantElements->points.push_back(basic_point);\n\t   \t\t\t\trelevantsize += 1.00 ;\n\t   \t\t\t\t         }// change the color in main cloud\n\t   \t\t \t }// if min <0.03\n\t   // Size of the RelevantElements Cloud\n\t   \t\t RelevantElements->width = (int) RelevantElements->points.size ();\n\t   \t\t RelevantElements->height = 1;\n\t   \t\t std::cout << \"Number of points in the relevant location is:\"<< relevantsize << std::endl;\n\t   \t\t std::cout << \"size of the relevant cloud is:\"<< RelevantElements->points.size () << std::endl;\n\n\n// to visualize the relevant points\n\t   \t//  pcl::visualization::CloudViewer viewer1(\"Relevant points\");\n\t   \t//  viewer1.showCloud(RelevantElements);\n\t   \t //   while (!viewer1.wasStopped ())\n\t   \t  // {}\n\n\n\n\t  pcl::PointCloud<pcl::PointXYZRGBA>::Ptr Normals (new pcl::PointCloud<pcl::PointXYZRGBA>);\n\t  Normals->resize(cloud->size());\n\n\t  // K nearest neighbor search\n\t  int KNumbersNeighbor = 10; // numbers of neighbors 7\n\t  std::vector<int> NeighborsKNSearch(KNumbersNeighbor);\n\t  std::vector<float> NeighborsKNSquaredDistance(KNumbersNeighbor);\n\n\t  int* NumbersNeighbor = new  int [cloud ->points.size ()];\n\t  pcl::KdTreeFLANN<pcl::PointXYZRGBA> kdtree;\n\t  kdtree.setInputCloud (cloud);\n\t  pcl::PointXYZRGBA searchPoint;\n\n\n\n\t  double* SmallestEigen = new  double [cloud->points.size() ];\n\t  double* MiddleEigen = new  double [cloud->points.size() ];\n\t  double* LargestEigen = new  double [cloud->points.size() ];\n\n\t  double* DLS = new  double [cloud->points.size() ];\n\t  double* DLM = new  double [cloud->points.size() ];\n\t  double* DMS = new  double [cloud->points.size() ];\n\t  double* Sigma = new  double [cloud->points.size() ];\n\n//\t\tstd::vector<double> SmallestEigen;\n//\t\tstd::vector<double> MiddleEigen;\n//\t\tstd::vector<double> LargestEigen;\n//\n//\t\tstd::vector<double> DLS;\n//\t\tstd::vector<double> DML;\n//\t\tstd::vector<double> DMS;\n\n\t    //  ************ All the Points of the cloud *******************\n\tfor (size_t i = 0; i < cloud ->points.size (); ++i) {\n\n\tsearchPoint.x =   cloud->points[i].x;\n\tsearchPoint.y =   cloud->points[i].y;\n\tsearchPoint.z =   cloud->points[i].z;\n\n\tif ( kdtree.nearestKSearch (searchPoint, KNumbersNeighbor, NeighborsKNSearch, NeighborsKNSquaredDistance) > 0 ) {\n\t\t NumbersNeighbor[i]= NeighborsKNSearch.size (); }\n\t    else { NumbersNeighbor[i] = 0; }\n\n\tfloat Xmean; float Ymean; float Zmean;\n\tfloat sum= 0.00;\n// Computing Covariance Matrix\n\tfor (size_t ii = 0; ii < NeighborsKNSearch.size (); ++ii){\n      sum += cloud->points[ NeighborsKNSearch[ii] ].x; }\n\tXmean = sum / NumbersNeighbor[i] ;\n\tsum= 0.00;\n\t\t\tfor (size_t ii = 0; ii < NeighborsKNSearch.size (); ++ii){\n\t\t\tsum += cloud->points[NeighborsKNSearch[ii] ].y;}\n\t\t\tYmean = sum / NumbersNeighbor[i] ;\n\t\t sum= 0.00;\n\t\t\tfor (size_t ii = 0; ii < NeighborsKNSearch.size (); ++ii){\n\t\t\tsum += cloud->points[NeighborsKNSearch[ii] ].z;}\n\t\t\tZmean = sum / NumbersNeighbor[i] ;\n\n\t\t\tfloat\tCovXX;  float CovXY; float CovXZ; float CovYX; float CovYY; float CovYZ; float CovZX; float CovZY; float CovZZ;\n\n\t\t\tsum = 0.00 ;\n\t\t\tfor (size_t ii = 0; ii < NeighborsKNSearch.size (); ++ii){\n\t\t\tsum += ( (cloud->points[NeighborsKNSearch[ii] ].x - Xmean ) * ( cloud->points[NeighborsKNSearch[ii] ].x - Xmean )  );}\n\t\t\tCovXX = sum / ( NumbersNeighbor[i]-1) ;\n\n\t\t\tsum = 0.00 ;\n\t\t\tfor (size_t ii = 0; ii < NeighborsKNSearch.size (); ++ii){\n\t\t\tsum += ( (cloud->points[NeighborsKNSearch[ii] ].x - Xmean ) * ( cloud->points[NeighborsKNSearch[ii] ].y - Ymean )  );}\n\t\t\tCovXY = sum / ( NumbersNeighbor[i]-1) ;\n\n\t\t\tCovYX = CovXY ;\n\n\t\t\tsum = 0.00 ;\n\t\t\tfor (size_t ii = 0; ii < NeighborsKNSearch.size (); ++ii){\n\t\t\tsum += ( (cloud->points[NeighborsKNSearch[ii] ].x - Xmean ) * ( cloud->points[NeighborsKNSearch[ii] ].z - Zmean )  );}\n\t\t\tCovXZ= sum / ( NumbersNeighbor[i]-1) ;\n\n\t\t\tCovZX = CovXZ;\n\n\t\t\tsum = 0.00 ;\n\t\t\tfor (size_t ii = 0; ii < NeighborsKNSearch.size (); ++ii){\n\t\t\tsum += ( (cloud->points[NeighborsKNSearch[ii] ].y - Ymean ) * ( cloud->points[NeighborsKNSearch[ii] ].y - Ymean )  );}\n\t\t\tCovYY = sum / ( NumbersNeighbor[i]-1) ;\n\n\t\t\tsum = 0.00 ;\n\t\t\tfor (size_t ii = 0; ii < NeighborsKNSearch.size (); ++ii){\n\t\t\tsum += ( (cloud->points[NeighborsKNSearch[ii] ].y - Ymean ) * ( cloud->points[NeighborsKNSearch[ii] ].z - Zmean )  );}\n\t\t\tCovYZ = sum / ( NumbersNeighbor[i]-1) ;\n\n\t\t\tCovZY = CovYZ;\n\n\t\t\tsum = 0.00 ;\n\t\t\tfor (size_t ii = 0; ii < NeighborsKNSearch.size (); ++ii){\n\t\t\tsum += ( (cloud->points[NeighborsKNSearch[ii] ].z - Zmean ) * ( cloud->points[NeighborsKNSearch[ii] ].z - Zmean )  );}\n\t\t\tCovZZ = sum / ( NumbersNeighbor[i]-1) ;\n\n// Computing Eigenvalue and EigenVector\n   Matrix3f Cov;\n   Cov << CovXX, CovXY, CovXZ, CovYX, CovYY, CovYZ, CovZX, CovZY, CovZZ;\n\n  SelfAdjointEigenSolver<Matrix3f> eigensolver(Cov);\n  if (eigensolver.info() != Success) abort();\n\n  double EigenValue1 = eigensolver.eigenvalues()[0];\n  double EigenValue2 = eigensolver.eigenvalues()[1];\n  double EigenValue3 = eigensolver.eigenvalues()[2];\n\n  double Smallest = 0.00; double Middle = 0.00; double Largest= 0.00;\n  if (EigenValue1<  EigenValue2 ) { Smallest =  EigenValue1 ; } else { Smallest = EigenValue2 ; }\n  if (EigenValue3<  Smallest ) { Smallest =  EigenValue3 ; }\n\n\n  if(EigenValue1 <= EigenValue2 && EigenValue1 <= EigenValue3) {\n\t  Smallest = EigenValue1;\n  if(EigenValue2 <= EigenValue3) {Middle = EigenValue2; Largest = EigenValue3;}\n  else {Middle = EigenValue3; Largest = EigenValue2;}\n  }\n\n  if(EigenValue1 >= EigenValue2 && EigenValue1 >= EigenValue3)\n  {\n\t  Largest = EigenValue1;\n  if(EigenValue2 <= EigenValue3) { Smallest = EigenValue2; Middle = EigenValue3; }\n  else {Smallest = EigenValue3; Middle = EigenValue2;}\n  }\n\n  if ((EigenValue1 >= EigenValue2 && EigenValue1 <= EigenValue3) || (EigenValue1 <= EigenValue2 && EigenValue1 >= EigenValue3))\n  {\n\t  Middle = EigenValue1;\n  if(EigenValue2 >= EigenValue3){Largest = EigenValue2; Smallest = EigenValue3;}\n  else{Largest = EigenValue3; Smallest = EigenValue2;}\n  }\n\nSmallestEigen[i]= Smallest ;\nMiddleEigen[i]= Middle;\nLargestEigen[i]= Largest;\n\nDLS[i] = std::abs ( LargestEigen[i] -  SmallestEigen[i] ) ;\nDLM[i] = std::abs (  LargestEigen[i] - MiddleEigen[i] ) ;\nDMS[i] = std::abs ( MiddleEigen[i] -  SmallestEigen[i] ) ;\nSigma[i] = (SmallestEigen[i] ) / ( SmallestEigen[i] + MiddleEigen[i] + LargestEigen[i] ) ;\n\t} // For each point of the cloud\n\n// Color Map For the difference of the eigen values\n\n\t  double MaxD=0.00 ;\n\t  double MinD= cloud ->points.size ();\n\t  int Ncolors=256;\n\n\t  for (size_t i = 0; i < cloud ->points.size (); ++i) {\n\t  \tif (  Sigma [i] < MinD) MinD= Sigma [i];\n\t  \tif (  Sigma[i] > MaxD) MaxD = Sigma [i];\n\t  }\n\n\t  std::cout<< \" Minimum is :\" << MinD<< std::endl;\n\t  std::cout<< \" Maximum  is :\" << MaxD << std::endl;\n\n\t double ss = 0.00 ;\n\t  for (size_t i = 0; i < cloud ->points.size (); ++i) {\n\t\t  ss += Sigma [i] ;}\n\t  double avg = ss / cloud ->points.size () ;\n\t  ss = 0.00 ;\n\t  for (size_t i = 0; i < cloud ->points.size (); ++i) {\n\t\t  ss += (Sigma [i] -  avg ) * (  Sigma [i] -  avg ) ;}\n\t  double stddvtion =   sqrt (  ss  /  ( cloud ->points.size () - 1 )  ) ;\n\n\t  std::cout<< \" Standard Deviation is :\" << stddvtion << std::endl;\n\n\t  MaxD = ( 2 )* stddvtion;\n\n/*\n\t  // Color table\n\t\tdouble line;\n\t\tdouble code[Ncolors][3];\n\t   ifstream colorcode ( \"/Path/TO/ArtificialPointCloud/JetColorDensity/ColorCodes256.txt\" );\n\t   //store color codes in array\n\t    int i=0,j=0;\n\t    while( colorcode>> line ) {\n\t    code[i][j]=line;\n\t    j++;\n\t    if (j == 3)\n\t    i++;\n\t}\n\t    code[1][0] = 0;\n\t    code[1][1] = 0;\n\t    code[1][2] = 135.468;\n\n\tint level = 0;\n\tfloat step = ( ( MaxD -  MinD) / Ncolors ) ;\n\t    for (size_t i = 0; i < cloud ->points.size (); ++i) {\nif (  Sigma [i] < MaxD ) {\n\t    level = floor( (Sigma [i] - MinD ) /  step ) ;\n\n\t    cloud->points[i].r = code[ level ][0];\n\t    cloud->points[i].g =  code[ level ][1];\n\t    cloud->points[i].b =  code[ level ][2];\n} // if sigma less than MAx\n\t    }\n*/\n\n\t  int level = 0;\n\t  float step = ( ( MaxD -  MinD) / Ncolors ) ;\n\t //  level = floor( (Sigma [i] - MinD ) /  step ) ;\nfor (size_t i = 0; i < cloud ->points.size (); ++i) {\n\t  if ( Sigma [i] > ( MinD + ( 0.003* step) ) ) {   // for the 3 plane ( Sigma [i] > ( MinD + ( 0.003* step) ) )\n\t    cloud->points[i].r = 0;\n\t    cloud->points[i].g =  0 ;\n\t    cloud->points[i].b =  128;\n\t\tpcl::PointXYZRGBA basic_point2;\n\t\tbasic_point2.x = cloud->points[i].x;\n\t\tbasic_point2.y = cloud->points[i].y;\n\t\tbasic_point2.z = cloud->points[i].z;\n\t\tbasic_point2.r = 255;\n\t\tbasic_point2.g = 255;\n\t\tbasic_point2.b= 255;\n\t\tSelectedElements->points.push_back(basic_point2);\n        }\n     }\n\n\n\n\n// Computing\n\nSelectedElements->width = (int) SelectedElements->points.size ();\nSelectedElements->height = 1;\nstd::cout <<\"Size of the Edge  cloud by clustering method is:  \" << SelectedElements->points.size ()<< std::endl;\n\n\n// Compute the  True Positive by Comparing the two Clouds of Relevant and Selective\ndouble TruePositive = 0.00 ;\n\n\t for (size_t ii = 0; ii< RelevantElements ->points.size (); ++ii) {\n \t for (size_t jj = 0; jj< SelectedElements ->points.size (); ++jj) {\n \t\t if ( ((RelevantElements->points[ii].x) == (SelectedElements->points[jj].x)) &&   ((RelevantElements->points[ii].y) == (SelectedElements->points[jj].y)) &&  ((RelevantElements->points[ii].z) == (SelectedElements->points[jj].z)) ) {\n\t\t\tTruePositive += 1.00 ; \t } // if\n\t\t     } // jj\n \t } // ii\n\nstd::cout <<\"Numbers of True Positive  is:  \" << TruePositive << std::endl;\ndouble FalseNegative = (RelevantElements ->points.size () ) - TruePositive ;\nstd::cout <<\"Numbers of False Negative  is:  \" << FalseNegative << std::endl;\ndouble FalsePositive = (SelectedElements ->points.size ()) - TruePositive;\nstd::cout <<\"Numbers of False Positive  is:  \" << FalsePositive << std::endl;\ndouble TrueNegative = ((cloud ->points.size ()) -  (RelevantElements ->points.size () ) ) -  FalsePositive ;\nstd::cout <<\"Numbers of True Negative  is:  \" << TrueNegative << std::endl;\n\ndouble Precision = (TruePositive / ( SelectedElements ->points.size () ) ) ;\nstd::cout <<\"Numbers of Precision  is:  \" << Precision << std::endl;\ndouble Recall = (TruePositive / (RelevantElements ->points.size () ) ) ;\nstd::cout <<\"Numbers of Recall   is:  \" << Recall << std::endl;\ndouble FScore = 2* (   ( Precision * Recall  ) / (Precision +  Recall )) ;\nstd::cout <<\"F1 Score of True Positive  is:  \" << FScore << std::endl;\n\n\n\n  \tpcl::PLYWriter writePLY;\n  //\twritePLY.write (\"/Path/TO/CUbeEigenJetColor.ply\", *cloud,  false);\n\t //   writePLY.write (\"/Path/TO/CloudEigeJnetTwirl.ply\", *cloud,  false);\n\t// writePLY.write (\"/Path/TO/CloudEigeJnetDragon.ply\", *cloud,  false);\n  \t//  writePLY.write (\"/Path/TO/CloudEigeJnetTwoPlane22.ply\", *cloud,  false);\n\n  pcl::visualization::CloudViewer viewer(\"Cloud Viewer\");\n  viewer.showCloud(cloud);\n  while (!viewer.wasStopped ())\n  {}\n\n  return 0;\n  }", "meta": {"hexsha": "4ffc2ef1110fcee5322b2bf70b7f5e7739c0c6c7", "size": 16661, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "F1Score-Eigenvalues.cpp", "max_stars_repo_name": "n1ckfg/Edge_Extraction", "max_stars_repo_head_hexsha": "2bbe215350faf02334652af54eac4f4666872d4e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 102.0, "max_stars_repo_stars_event_min_datetime": "2017-12-14T14:17:29.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T12:26:13.000Z", "max_issues_repo_path": "F1Score-Eigenvalues.cpp", "max_issues_repo_name": "n1ckfg/Edge_Extraction", "max_issues_repo_head_hexsha": "2bbe215350faf02334652af54eac4f4666872d4e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2019-08-22T23:08:55.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-30T10:24:35.000Z", "max_forks_repo_path": "F1Score-Eigenvalues.cpp", "max_forks_repo_name": "n1ckfg/Edge_Extraction", "max_forks_repo_head_hexsha": "2bbe215350faf02334652af54eac4f4666872d4e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 33.0, "max_forks_repo_forks_event_min_datetime": "2017-07-12T03:05:59.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-01T09:00:30.000Z", "avg_line_length": 41.1382716049, "max_line_length": 363, "alphanum_fraction": 0.6335153952, "num_tokens": 5221, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7154239957834734, "lm_q2_score": 0.4225046348141882, "lm_q1q2_score": 0.30226995407580376}}
{"text": "#pragma once\n#include <Eigen/Core>\n#include <memory>\n#include <numeric>\n#include <set>\n#include <string>\n#include \"ear/layout.hpp\"\n#include \"ear/metadata.hpp\"\n\nnamespace ear {\n\n  /** @brief An interface for objects that can calculate gains for some\n   * positions, e.g. a triangle of loudspeakers.\n   */\n  class RegionHandler {\n   public:\n    RegionHandler(Eigen::VectorXi outputChannels, Eigen::MatrixXd positions);\n    virtual boost::optional<Eigen::VectorXd> handle(\n        Eigen::Vector3d position) const = 0;\n    virtual ~RegionHandler() = default;\n\n    boost::optional<Eigen::VectorXd> handleRemap(Eigen::Vector3d position,\n                                                 int numberOfChannels) const;\n    Eigen::VectorXi outputChannels();\n\n   protected:\n    Eigen::VectorXi _outputChannels;\n    Eigen::MatrixXd _positions;\n  };\n\n  /** @brief Region handler representing a triplet of loudspeakers, implementing\n   * VBAP.\n   *\n   * This is implemented such that if handle(pos) returns array x:\n   *\n   *  - dot(x, positions) is collinear with pos\n   *  - x[i] >= 0 for all i\n   *  - norm(x) == 1\n   *\n   * Note that the positions are *not* normalised, as this is not always\n   * desirable.\n   */\n  class Triplet : public RegionHandler {\n   public:\n    /** @brief Ctor\n     *\n     * @param  output_channels The channel numbers of the values returned by\n     *   handle.\n     * @param  positions  Cartesian positions of the three speakers; index order\n     *   is speaker, axis.\n     */\n    Triplet(Eigen::Vector3i outputChannels, Eigen::Matrix3d positions);\n\n    boost::optional<Eigen::VectorXd> handle(\n        Eigen::Vector3d position) const override;\n\n   private:\n    Eigen::Matrix3d _basis;\n  };\n\n  /** @brief Region handler representing n real loudspeakers and a central\n   * virtual loudspeaker, whose gain is distributed to the real loudspeakers.\n   *\n   * Triplet regions are formed between the virtual speaker and pairs of real\n   * speakers on the edge of the ngon. Any gain sent to the virtual speaker is\n   * multiplied by centre_downmix and summed into the gains for the real\n   * loudspeakers,which are then normalised.\n   */\n  class VirtualNgon : public RegionHandler {\n   public:\n    /** @brief Ctor\n     *\n     * @param  output_channels The channel numbers of the values returned by\n     *   handle.\n     * @param  positions Cartesian positions of the n loudspeakers.\n     * @param  centrePosition Cartesian position of the central virtual\n     *   loudspeaker\n     * @param  centreDownmix Downmix coefficients for distributing gains from\n     * the centre virtual loudspeaker to the loudspeakers defined by\n     * positions.\n     */\n    VirtualNgon(Eigen::VectorXi outputChannels, Eigen::MatrixXd positions,\n                Eigen::Vector3d centrePosition, Eigen::VectorXd centreDownmix);\n\n    boost::optional<Eigen::VectorXd> handle(\n        Eigen::Vector3d position) const override;\n\n   private:\n    Eigen::Vector3d _centrePosition;\n    Eigen::VectorXd _centreDownmix;\n    std::vector<std::unique_ptr<RegionHandler>> _regions;\n  };\n\n  class QuadRegion : public RegionHandler {\n   public:\n    QuadRegion(Eigen::VectorXi outputChannels, Eigen::MatrixXd positions);\n\n    boost::optional<Eigen::VectorXd> handle(\n        Eigen::Vector3d position) const override;\n\n   private:\n    Eigen::Matrix3d _calcPolyBasis(Eigen::MatrixXd positions);\n\n    boost::optional<double> _pan(Eigen::Vector3d position,\n                                 Eigen::Matrix3d polyBasis) const;\n\n    Eigen::VectorXi _order;\n    Eigen::Matrix3d _polyBasisX;\n    Eigen::Matrix3d _polyBasisY;\n  };\n\n  /** @brief Base class for all PointSourcePanner like classes\n   */\n  class PointSourcePanner {\n   public:\n    virtual boost::optional<Eigen::VectorXd> handle(\n        Eigen::Vector3d position) = 0;\n    virtual int numberOfOutputChannels() const = 0;\n  };\n\n  /** @brief Wrapper around multiple regions.\n   */\n  class PolarPointSourcePanner : public PointSourcePanner {\n   public:\n    /** @brief Ctor\n     *\n     * @param  regions Regions used to handle a position.\n     * @param  numberOfChannels Number of output channels; this is computed\n     * from the output channels of the regions if not provided.\n     */\n    PolarPointSourcePanner(std::vector<std::unique_ptr<RegionHandler>> regions,\n                           boost::optional<int> numberOfChannels = boost::none);\n\n    boost::optional<Eigen::VectorXd> handle(Eigen::Vector3d position) override;\n\n    int numberOfOutputChannels() const override;\n\n   private:\n    int _numberOfRequiredChannels();\n\n    const std::vector<std::unique_ptr<RegionHandler>> _regions;\n    int _numberOfOutputChannels;\n  };\n\n  /** @brief Wrapper around a point source panner with an additional downmix.\n   */\n  class PointSourcePannerDownmix : public PointSourcePanner {\n   public:\n    /** @brief Ctor\n     *\n     * @param  psp Inner point source panner.\n     * @param  downmix Downmix matrix (mxn) from m inputs to n outputs.\n     */\n    PointSourcePannerDownmix(std::shared_ptr<PointSourcePanner> psp,\n                             Eigen::MatrixXd downmix);\n    ~PointSourcePannerDownmix() = default;\n\n    boost::optional<Eigen::VectorXd> handle(Eigen::Vector3d position) override;\n\n    int numberOfOutputChannels() const override;\n\n   private:\n    std::shared_ptr<PointSourcePanner> _psp;\n    Eigen::MatrixXd _downmix;\n  };\n\n  /** @brief Generate extra loudspeaker positions to fill gaps in layers.\n   *\n   * @param  layout Original layout without the LFE channels\n   *\n   * @returns\n   *   - list of extra channels (layout.Channel).\n   *   - downmix matrix to mix the extra channel outputs to the real channels\n   */\n  std::pair<std::vector<Channel>, Eigen::MatrixXd> extraPosVerticalNominal(\n      Layout layout);\n\n  // given a layout, determine the full set of loudspeaker positions used for\n  // panning. returns:\n  //\n  // - the real position of real and virtual loudspeakers\n  // - the nominal position of the real and virtual loudspeakers\n  // - the indices of the virtual loudspeakers in the two position lists\n  // - a downmix matrix to be applied to the output of the real loudspeakers\n  std::tuple<std::vector<Eigen::Vector3d>, std::vector<Eigen::Vector3d>,\n             std::set<int>, Eigen::MatrixXd>\n  getAugmentedLayout(const Layout& layout);\n\n  std::shared_ptr<PointSourcePanner> configureFullPolarPanner(\n      const Layout& layout);\n\n  class StereoPannerDownmix : public RegionHandler {\n   public:\n    StereoPannerDownmix(Eigen::VectorXi outputChannels,\n                        Eigen::MatrixXd positions);\n\n    boost::optional<Eigen::VectorXd> handle(\n        Eigen::Vector3d position) const override;\n\n   private:\n    std::shared_ptr<PointSourcePanner> _psp;\n  };\n\n  class AllocentricPanner : public PointSourcePanner {\n   public:\n    AllocentricPanner() = default;\n    ~AllocentricPanner() = default;\n\n    boost::optional<Eigen::VectorXd> handle(Eigen::Vector3d position) override;\n    int numberOfOutputChannels() const override;\n  };\n\n  std::shared_ptr<PointSourcePanner> configureStereoPolarPanner(\n      const Layout& layout);\n\n  std::shared_ptr<PointSourcePanner> configureFullPolarPanner(\n      const Layout& layout);\n\n  std::shared_ptr<PointSourcePanner> configureAllocentricPanner(\n      const Layout& layout);\n\n  std::shared_ptr<PointSourcePanner> configurePolarPanner(const Layout& layout);\n\n}  // namespace ear\n", "meta": {"hexsha": "eb323b51cc759a294dfe6043f284caa2848b7248", "size": 7367, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/common/point_source_panner.hpp", "max_stars_repo_name": "rsjtaylor/libear", "max_stars_repo_head_hexsha": "40a4000296190c3f91eba79e5b92141e368bd72a", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2019-07-30T17:58:00.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-15T15:33:36.000Z", "max_issues_repo_path": "src/common/point_source_panner.hpp", "max_issues_repo_name": "rsjtaylor/libear", "max_issues_repo_head_hexsha": "40a4000296190c3f91eba79e5b92141e368bd72a", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 27.0, "max_issues_repo_issues_event_min_datetime": "2019-07-30T18:01:58.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-14T10:24:52.000Z", "max_forks_repo_path": "src/common/point_source_panner.hpp", "max_forks_repo_name": "rsjtaylor/libear", "max_forks_repo_head_hexsha": "40a4000296190c3f91eba79e5b92141e368bd72a", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2019-07-30T15:12:02.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-14T16:22:43.000Z", "avg_line_length": 32.7422222222, "max_line_length": 80, "alphanum_fraction": 0.6914619248, "num_tokens": 1766, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7217432182679956, "lm_q2_score": 0.41869690935568665, "lm_q1q2_score": 0.30219165483723653}}
{"text": "/************************************************\n增加发布速度的话题/mavros/setpoint_raw/local，\n引入接收相对相机相对Apriltag码的话题/tag_detections\n引入相机参数话题/camera/camera_info\n实现从相机坐标系到像素坐标系的变换，根据Apriltag码大小\n得出四个角点的像素坐标。引入图像距，计算得到期望\n速度值，进行发布\nDate:2022/04/12\nEditor:Lizhicheng\n***************************************************/\n\n#include \"ros/ros.h\"\n\n#include \"mavros_msgs/PositionTarget.h\"\n#include<vector>\n\n// #include \"apriltags_ros/AprilTagDetectionArray.h\"\n#include \"apriltag2_ros/Apriltags.h\"\n\n// #include \"sensor_msgs/CameraInfo.h\"\n// #include <geometry_msgs/PoseStamped.h>\n\n#include <opencv2/opencv.hpp>\n#include <highgui.h>\n#include <Eigen/Dense>\n#include <eigen_conversions/eigen_msg.h>\n#include <tf/transform_datatypes.h>\n#include <cmath>\n\n// void tagCallback(const apriltags_ros::AprilTagDetectionArray::ConstPtr& tag)\n// {\n//     last_msg_=tag;\n//     center_x = last_msg_->detections[0].pose.pose.pose.position.x;      //可视作Apriltag码中心点在相机坐标系下的位置\n//     center_y = last_msg_->detections[0].pose.pose.pose.position.y;\n//     center_z = last_msg_->detections[0].pose.pose.pose.position.z;\n\n//     //使用相机内参矩阵将相机坐标系下的点转换为像素坐标\n\n// }\n\n\nros::Publisher vel_pub;\n\n\n\n\ndouble sq(double a)\n{\n    return a * a;\n}\n\nvoid cornerCallback(const apriltag2_ros::Apriltags& msg)\n{\n\n\n\nmavros_msgs::PositionTarget velmsg;\nvelmsg.header.stamp = ros::Time::now();\nstatic int seq = 1;\nvelmsg.header.seq = seq++;\nvelmsg.header.frame_id = 1;\nvelmsg.coordinate_frame = mavros_msgs::PositionTarget::FRAME_LOCAL_NED;\nvelmsg.type_mask = mavros_msgs::PositionTarget::IGNORE_PX +\n                    mavros_msgs::PositionTarget::IGNORE_PY +\n                    mavros_msgs::PositionTarget::IGNORE_PZ +\n                    mavros_msgs::PositionTarget::IGNORE_AFX +\n                    mavros_msgs::PositionTarget::IGNORE_AFY +\n                    mavros_msgs::PositionTarget::IGNORE_AFZ +\n                    mavros_msgs::PositionTarget::FORCE +\n                    mavros_msgs::PositionTarget::IGNORE_YAW +\n                    mavros_msgs::PositionTarget::IGNORE_YAW_RATE;\n\n\n        cv::Mat r1 = cv::Mat(3, 1, CV_64FC1);\n        cv::Mat r2 = cv::Mat(3, 1, CV_64FC1);\n        cv::Mat r3 = cv::Mat(3, 1, CV_64FC1);\n        cv::Mat r4 = cv::Mat(3, 1, CV_64FC1);\n\n        tf::Matrix3x3 R_rp;\n\n        cv::Matx33d mK(205.46963709898583, 0.0, 320.5, 0.0, 205.46963709898583, 180.5, 0.0, 0.0, 1.0);\n                                // fx, 0.0, cx, \n                                // 0.0, fy, cy, \n                                // 0.0, 0.0, 1.0\n\n        // cv::Vec4f distParam(params_.D.at<double>(0), params_.D.at<double>(1), params_.D.at<double>(2), params_.D.at<double>(3));\n        cv::Vec4f distParam(0.0, 0.0, 0.0, 0.0);\n\n    // cv::Vec3d rvec, tvec;\n    //相机内参\n\n        // geometry_msgs::PoseStamped vpdata_pose;  //20180425 image moment in the virtual plane\n\n    //接收角点像素坐标\n        r1.at<double>(0, 0) = msg.apriltags[0].corners[0].x; //\n        r1.at<double>(1, 0) = msg.apriltags[0].corners[0].y; //\n        r1.at<double>(2, 0) = 1;\n        r2.at<double>(0, 0) = msg.apriltags[0].corners[1].x; //\n        r2.at<double>(1, 0) = msg.apriltags[0].corners[1].y; //\n        r2.at<double>(2, 0) = 1;\n        r3.at<double>(0, 0) = msg.apriltags[0].corners[2].x; //\n        r3.at<double>(1, 0) = msg.apriltags[0].corners[2].y; //\n        r3.at<double>(2, 0) = 1;\n        r4.at<double>(0, 0) = msg.apriltags[0].corners[3].x; //\n        r4.at<double>(1, 0) = msg.apriltags[0].corners[3].y; //\n        r4.at<double>(2, 0) = 1;\n\n\n        ROS_INFO(\"r1 [0]%f\",msg.apriltags[0].corners[0].x);\n        ROS_INFO(\"r1 [1]%f\",r1.at<double>(1,0));\n\n        ROS_INFO(\"r2 [0]%f\",msg.apriltags[0].corners[1].x);\n        ROS_INFO(\"r2 [1]%f\",r2.at<double>(1,0));\n    \n        ROS_INFO(\"r3 [0]%f\",msg.apriltags[0].corners[2].x);\n        ROS_INFO(\"r3 [1]%f\",r3.at<double>(1,0));\n    \n        ROS_INFO(\"r4 [0]%f\",msg.apriltags[0].corners[3].x);\n        ROS_INFO(\"r4 [1]%f\",r4.at<double>(1,0));\n\n\n        cv::Matx33d mK_inv = mK.inv();//求逆//A矩阵相机固有参数矩阵\n        //cv::Vec3d _r1 ;\n        //cv::Vec3d  _r1= (mK_inv * r1);//标准化图像坐标系\n        // cv::Vec3d _r2 = mK_inv * r2;\n        // cv::Vec3d _r3 = mK_inv * r3;\n        // cv::Vec3d _r4 = mK_inv * r4;\n\n        cv::Mat  _r1= (mK_inv * r1);//标准化图像坐标系\n        cv::Mat _r2 = mK_inv * r2;\n        cv::Mat _r3 = mK_inv * r3;\n        cv::Mat _r4 = mK_inv * r4;\n\n        /*virtual image plane with full rotation*/\n\n        // R_rp.setRPY(0,0,0);\n        // tf::Vector3 swap_p;\n        // double beta;\n        // // swap_p.setValue(_r1[0], _r1[1], 1);//标准化\n        // swap_p.setValue(_r1.at<double>(0,0), _r1.at<double>(1,0), 1);//标准化\n        // // swap_p = R_rp * swap_p;//R_rp为实际平面到虚平面的旋转矩阵\n        // beta = (double)1.0 / (swap_p.z());\n        // // _r1[0] = beta * swap_p.x();\n        // // _r1[1] = beta * swap_p.y();//m_v\n        // _r1.at<double>(0,0) = beta * swap_p.x();\n        // _r1.at<double>(1,0) = beta * swap_p.y();//m_v\n\n        // // swap_p.setValue(_r2[0], _r2[1], 1);\n        // swap_p.setValue(_r2.at<double>(0,0), _r2.at<double>(1,0), 1);\n        // // swap_p = R_rp * swap_p;\n        // beta = (double)1.0 / (swap_p.z());\n        // // _r2[0] = beta * swap_p.x();\n        // // _r2[1] = beta * swap_p.y();\n        // _r2.at<double>(0,0)= beta * swap_p.x();\n        // _r2.at<double>(1,0)= beta * swap_p.y();\n\n        // // swap_p.setValue(_r3[0], _r3[1], 1);\n        // swap_p.setValue(_r3.at<double>(0,0), _r3.at<double>(1,0), 1);\n        // // swap_p = R_rp * swap_p;\n        // beta = (double)1.0 / (swap_p.z());\n        // // _r3[0] = beta * swap_p.x();\n        // // _r3[1] = beta * swap_p.y();\n        // _r3.at<double>(0,0) = beta * swap_p.x();\n        // _r3.at<double>(1,0) = beta * swap_p.y();\n\n        // // swap_p.setValue(_r4[0], _r4[1], 1);\n        // swap_p.setValue(_r4.at<double>(0,0), _r4.at<double>(1,0), 1);\n        // // swap_p = R_rp * swap_p;\n        // beta = (double)1.0 / (swap_p.z());\n        // // _r4[0] = beta * swap_p.x();\n        // // _r4[1] = beta * swap_p.y();\n        // _r4.at<double>(0,0) = beta * swap_p.x();\n        // _r4.at<double>(1,0) = beta * swap_p.y();\n\n\n        double cake = 0;\n        double ug = 0,vg = 0;\n        double az_u = 0, az_v = 0;\n        double az = 0;\n        double dug = 0, dvg = 0, daz = 0.125;\n        \n            ug = (_r1.at<double>(0, 0) + _r2.at<double>(0, 0) + _r3.at<double>(0, 0) + _r4.at<double>(0, 0)) * 0.25;//gravity center\n            vg = (_r1.at<double>(1, 0) + _r2.at<double>(1, 0) + _r3.at<double>(1, 0) + _r4.at<double>(1, 0)) * 0.25;\n\n            az_u = (sq(ug - _r1.at<double>(0, 0)) + sq(ug - _r2.at<double>(0, 0)) + sq(ug - _r3.at<double>(0, 0)) + sq(ug - _r4.at<double>(0, 0)));\n            az_v = (sq(vg - _r1.at<double>(1, 0)) + sq(vg - _r2.at<double>(1, 0)) + sq(vg - _r3.at<double>(1, 0)) + sq(vg - _r4.at<double>(1, 0)));\n\n        \n\n        // ug = (_r1[0] + _r2[0] + _r3[0] + _r4[0]) * 0.25;\n        // vg = (_r1[1] + _r2[1] + _r3[1] + _r4[1]) * 0.25;\n\n        // az_u = (sq(ug - _r1[0]) + sq(ug - _r2[0]) + sq(ug - _r3[0]) + sq(ug - _r4[0]));\n        // az_v = (sq(vg - _r1[1]) + sq(vg - _r2[1]) + sq(vg - _r3[1]) + sq(vg - _r4[1]));\n\n\n        az = az_u + az_v;\n        /* 1M  height */\n        // daz = 0.055778;\n\n        /* M  height */\n        // daz = 0.087153125;\n        //\n\n        cake = sqrt(daz / az);\n        // vpdata_pose.header.stamp = ros::Time::now();  //what is this? \n        // vpdata_pose.pose.position.x = (cake * (dvg - vg));\n        // vpdata_pose.pose.position.y = (cake * (dug - ug));\n        // vpdata_pose.pose.position.z = (1 - cake);\n        // vpdata_pose.pose.orientation = msg.apriltags[0].pose.orientation;//\n\n        velmsg.velocity.x=  10*(cake * (dvg - vg));//发布速度\n        velmsg.velocity.y=  10*(cake * (dug - ug));\n        velmsg.velocity.z=   (1 - cake);\n\n\n        vel_pub.publish(velmsg);\n        ROS_INFO(\"velmsg.x is %f\",velmsg.velocity.x);\n        ROS_INFO(\"velmsg.y is %f\",velmsg.velocity.y);\n        ROS_INFO(\"velmsg.z is %f\",velmsg.velocity.z);\n\n        // pub_vppose.publish(vpdata_pose);\n\n}\n\n\n// void camCallback(const sensor_msgs::CameraInfo::ConstPtr& cam_info)\n// {\n\n// // # Intrinsic camera matrix for the raw (distorted) images.\n// // #         [fx  0 cx]\n// // # K = [ 0 fy cy]\n// // #         [ 0  0  1]\n// // # Projects 3D points in the camera coordinate frame to 2D pixel\n// // # coordinates using the focal lengths (fx, fy) and principal point\n// // # (cx, cy).\n    \n//     // fx = cam_info->K[0];  //相机内参矩阵，使用焦距（fx,fy）及主点坐标(cx,cy), 单位为像素\n//     // fy = cam_info->K[4];\n//     // cx = cam_info->K[2];\n//     // cy = cam_info->K[5];\n//     // height = cam_info->height;\n//     // width = cam_info->width;\n\n//     //cgo3_camera K: [205.46963709898583, 0.0, 320.5, 0.0, 205.46963709898583, 180.5, 0.0, 0.0, 1.0]\n//     //                             D: [0.0, 0.0, 0.0, 0.0, 0.0]\n\n//     // cv::Vec4f distParam(params_.D.at<double>(0), params_.D.at<double>(1), params_.D.at<double>(2), params_.D.at<double>(3)); // all 0?\n//     // cv::solvePnP(objPts, imgPts, cameraMatrix, distParam, rvec, tvec);\n//     // cv::Matx33f r;\n//     // cv::Rodrigues(rvec, r);\n\n        \n\n// }\n\n\n\n\nint main(int argc, char **argv)\n{\n    ros::init(argc, argv, \"ImageMoment\");\n    // uint32 height,width;\n    // float64 fx,fy,cx,cy;\n    //float64 center_x,center.y,center.z;\n\n\n    tf::Matrix3x3 R_rp;\n\n    cv::Matx33f mK(205.46963709898583, 0.0, 320.5, 0.0, 205.46963709898583, 180.5, 0.0, 0.0, 1.0);\n                                // fx, 0.0, cx, \n                                // 0.0, fy, cy, \n                                // 0.0, 0.0, 1.0\n\n    // cv::Vec4f distParam(params_.D.at<double>(0), params_.D.at<double>(1), params_.D.at<double>(2), params_.D.at<double>(3));\n    cv::Vec4f distParam(0.0, 0.0, 0.0, 0.0);\n\n    // cv::Vec3d rvec, tvec;\n    //相机内参\n\n    // geometry_msgs::PoseStamped vpdata_pose;  //20180425 image moment in the virtual plane\n\n    // apriltags_ros::AprilTagDetectionArrayConstPtr last_msg_;\n\n    ros::NodeHandle nh;\n\n    vel_pub = nh.advertise<mavros_msgs::PositionTarget>(\"/mavros/setpoint_raw/local\", 6);\n    // ros::Subscriber tag_sub = nh.subscribe(\"/tag_detections\",1000,tagCallback);\n    ros::Subscriber corners_sub = nh.subscribe(\"/apriltag_detector/tags\" , 1, cornerCallback);\n    // ros::Subscriber cam_info_sub = nh.subscribe(\"/camera/camera_info\",1000,camCallback);\n    //ros::Publisher pub_vppose = nh.advertise<geometry_msgs::PoseStamped>(\"setpoint/relative_pos\", 5);\n\n\n\n\n    ros::Rate loop_rate(10);\n\n    // mavros_msgs::PositionTarget msg;\n    // msg.header.stamp = ros::Time::now();\n    // static int seq = 1;\n    // msg.header.seq = seq++;\n    // msg.header.frame_id = 1;\n    // msg.coordinate_frame = mavros_msgs::PositionTarget::FRAME_LOCAL_NED;\n    // msg.type_mask = mavros_msgs::PositionTarget::IGNORE_PX +\n    //                 mavros_msgs::PositionTarget::IGNORE_PY +\n    //                 mavros_msgs::PositionTarget::IGNORE_PZ +\n    //                 mavros_msgs::PositionTarget::IGNORE_AFX +\n    //                 mavros_msgs::PositionTarget::IGNORE_AFY +\n    //                 mavros_msgs::PositionTarget::IGNORE_AFZ +\n    //                 mavros_msgs::PositionTarget::FORCE +\n    //                 mavros_msgs::PositionTarget::IGNORE_YAW +\n    //                 mavros_msgs::PositionTarget::IGNORE_YAW_RATE;\n\n\n\n    while (ros::ok())\n    {\n\n        // msg.velocity.x=     ;//发布速度\n        // msg.velocity.y=    ;\n        // msg.velocity.z=    ;\n\n\n        // vel_pub.publish(msg);\n\n        ros::spinOnce();\n\n        loop_rate.sleep();\n\n\n    }\n\n\n    return 0;\n}\n", "meta": {"hexsha": "a4a30fb0068d1f11a61b4f1a3d0dbef6aa0ceee8", "size": 11550, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ImageMoment.cpp", "max_stars_repo_name": "LizhichengDlut/hexa_-x_tilt", "max_stars_repo_head_hexsha": "abcf1f323dc6e4ff84633614e25774069f8182ef", "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": "ImageMoment.cpp", "max_issues_repo_name": "LizhichengDlut/hexa_-x_tilt", "max_issues_repo_head_hexsha": "abcf1f323dc6e4ff84633614e25774069f8182ef", "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": "ImageMoment.cpp", "max_forks_repo_name": "LizhichengDlut/hexa_-x_tilt", "max_forks_repo_head_hexsha": "abcf1f323dc6e4ff84633614e25774069f8182ef", "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.375, "max_line_length": 147, "alphanum_fraction": 0.5398268398, "num_tokens": 4126, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6959583250334526, "lm_q2_score": 0.43398146480389854, "lm_q1q2_score": 0.3020330133404855}}
{"text": "#include \"mp_class.h\"\n#include <boost/multiprecision/miller_rabin.hpp>\n#include <boost/mpl/int.hpp>\n#include <utility>\n#include <cmath>\n#include <symengine/symengine_assert.h>\n#include <symengine/symengine_exception.h>\n\nusing boost::multiprecision::numerator;\nusing boost::multiprecision::denominator;\nusing boost::multiprecision::miller_rabin_test;\nusing boost::multiprecision::detail::find_lsb;\nusing boost::mpl::int_;\n\n#if SYMENGINE_INTEGER_CLASS == SYMENGINE_BOOSTMP\n\nnamespace SymEngine\n{\n\ninteger_class pow(const integer_class &a, unsigned long b)\n{\n    return boost::multiprecision::pow(a, numeric_cast<unsigned>(b));\n}\n\nvoid mp_fdiv_qr(integer_class &q, integer_class &r, const integer_class &a,\n                const integer_class &b)\n{\n    /*boost::multiprecision doesn't have a built-in fdiv_qr (floored division).\n      Its divide_qr uses truncated division, as does its\n      modulus operator. Thus, using boost::multiprecision::divide_qr we get:\n      divide_qr(-5, 3, quo, rem) //quo == -1, rem == -2\n      divide_qr(5, -3, quo, rem) //quo == -1, rem == 2\n      but we want:\n      mp_fdiv_r(quo, rem, -5, 3) //quo == -2, rem == 1\n      mp_fdiv_r(quo, rem, 5, -3) //rem == -2, rem == -1\n      The problem arises only when the quotient is negative.  To convert\n      a truncated result into a floored result in this case, simply subtract\n      one from the truncated quotient and add the divisor to the truncated\n      remainder.\n      */\n\n    // must copy a and b before calling divide_qr because a or b may refer to\n    // the same\n    // object as q or r, causing incorrect results\n    integer_class a_cpy = a, b_cpy = b;\n    bool neg_quotient = ((a < 0 && b > 0) || (a > 0 && b < 0)) ? true : false;\n    boost::multiprecision::divide_qr(a_cpy, b_cpy, q, r);\n    // floor the quotient if necessary\n    if (neg_quotient && r != 0) {\n        q -= 1;\n    }\n    // remainder should have same sign as divisor\n    if ((b_cpy > 0 && r < 0) || (b_cpy < 0 && r > 0)) {\n        r += b_cpy;\n        return;\n    }\n}\n\nvoid mp_cdiv_qr(integer_class &q, integer_class &r, const integer_class &a,\n                const integer_class &b)\n{\n    integer_class a_cpy = a, b_cpy = b;\n    bool pos_quotient = ((a < 0 && b < 0) || (a > 0 && b > 0)) ? true : false;\n    boost::multiprecision::divide_qr(a_cpy, b_cpy, q, r);\n    // ceil the quotient if necessary\n    if (pos_quotient && r != 0) {\n        q += 1;\n    }\n    // remainder should have opposite sign as divisor\n    if ((b_cpy > 0 && r > 0) || (b_cpy < 0 && r < 0)) {\n        r -= b_cpy;\n        return;\n    }\n}\n\nvoid mp_gcdext(integer_class &gcd, integer_class &s, integer_class &t,\n               const integer_class &a, const integer_class &b)\n{\n\n    integer_class this_s(1);\n    integer_class this_t(0);\n    integer_class next_s(0);\n    integer_class next_t(1);\n    integer_class this_r(a);\n    integer_class next_r(b);\n    integer_class q;\n    while (next_r != 0) {\n        // should use truncated division, so use\n        // boost::multiprecision::divide_qr\n        // beware of overwriting this_r during internal operations of divide_qr\n        // copy it first\n        integer_class this_r_cpy = this_r;\n        boost::multiprecision::divide_qr(this_r_cpy, next_r, q, this_r);\n        this_s -= q * next_s;\n        this_t -= q * next_t;\n        std::swap(this_s, next_s);\n        std::swap(this_t, next_t);\n        std::swap(this_r, next_r);\n    }\n    // normalize the gcd, s and t\n    if (this_r < 0) {\n        this_r *= -1;\n        this_s *= -1;\n        this_t *= -1;\n    }\n    gcd = std::move(this_r);\n    s = std::move(this_s);\n    t = std::move(this_t);\n}\n\nbool mp_invert(integer_class &res, const integer_class &a,\n               const integer_class &m)\n{\n    integer_class gcd, s, t;\n    mp_gcdext(gcd, s, t, a, m);\n    if (gcd != 1) {\n        res = 0;\n        return false;\n    } else {\n        mp_fdiv_r(s, s, m); // reduce s modulo m.  undefined behavior when m ==\n                            // 0, so don't need to check\n        if (s < 0) {\n            s += mp_abs(m);\n        } // give the canonical representative of s\n        res = s;\n        return true;\n    }\n}\n\n// floored modulus\ninteger_class fmod(const integer_class &a, const integer_class &mod)\n{\n    integer_class res = a % mod;\n    if (res < 0) {\n        res += mod;\n    }\n    return res;\n}\n\nvoid mp_pow_ui(rational_class &res, const rational_class &i, unsigned long n)\n{\n    integer_class num = numerator(i);   // copy\n    integer_class den = denominator(i); // copy\n    num = pow(num, n);\n    den = pow(den, n);\n    res = rational_class(std::move(num), std::move(den));\n}\n\nvoid mp_powm(integer_class &res, const integer_class &base,\n             const integer_class &exp, const integer_class &m)\n{\n    // if exp is negative, interpret as follows\n    // base**(exp) mod m \t== (base**(-1))**abs(exp) mod m\n    // \t\t\t\t\t\t== (base**(-1) mod m) ** abs(exp) mod m\n    // where base**(-1) mod m is the modular inverse\n    if (exp < 0) {\n        integer_class base_inverse;\n        if (!mp_invert(base_inverse, base, m)) {\n            throw SymEngine::SymEngineException(\"negative exponent undefined \"\n                                                \"in powm if base is not \"\n                                                \"invertible mod m\");\n        }\n        res = boost::multiprecision::powm(base_inverse, mp_abs(exp), m);\n        return;\n    } else {\n        res = boost::multiprecision::powm(base, exp, m);\n        // boost's powm calculates base**exp % m, but uses truncated\n        // modulus, e.g. powm(-2,3,5) == -3.  We want powm(-2,3,5) == 2\n        if (res < 0) {\n            res += m;\n        }\n    }\n}\n\ninteger_class step(const unsigned long &n, const integer_class &i,\n                   integer_class &x)\n{\n    SYMENGINE_ASSERT(n > 1);\n    unsigned long m = n - 1;\n    integer_class &&x_m = pow(x, m);\n    return integer_class((integer_class(m * x) + integer_class(i / x_m)) / n);\n}\n\nbool positive_root(integer_class &res, const integer_class &i,\n                   const unsigned long n)\n{\n    integer_class x\n        = 1; // TODO: make a better starting guess based on (number of bits)/n\n    integer_class y = step(n, i, x);\n    do {\n        x = y;\n        y = step(n, i, x);\n    } while (y < x);\n    res = x;\n    if (pow(x, n) == i) {\n        return true;\n    }\n    return false;\n}\n\n// return true if i is a perfect nth power, i.e. res**i == n\nbool mp_root(integer_class &res, const integer_class &i, const unsigned long n)\n{\n    if (n == 0) {\n        throw std::runtime_error(\"0th root is undefined\");\n    }\n    if (n == 1) {\n        res = i;\n        return true;\n    }\n    if (i == 0) {\n        res = 0;\n        return true;\n    }\n    if (i > 0) {\n        return positive_root(res, i, n);\n    }\n    if (i < 0 && (n % 2 == 0)) {\n        throw std::runtime_error(\"even root of a negative is non-real\");\n    }\n    bool b = positive_root(res, -i, n);\n    res *= -1;\n    return b;\n}\n\ninteger_class mp_sqrt(const integer_class &i)\n{\n    // as of 11/1/2016, boost::multiprecision::sqrt() is buggy:\n    // https://svn.boost.org/trac/boost/ticket/12559\n    // implement with mp_root for now\n    integer_class res;\n    mp_root(res, i, 2);\n    return res;\n}\n\nvoid mp_rootrem(integer_class &a, integer_class &b, const integer_class &i,\n                unsigned long n)\n{\n    mp_root(a, i, n);\n    integer_class p = pow(a, n);\n    ;\n    b = i - p;\n}\n\nvoid mp_sqrtrem(integer_class &a, integer_class &b, const integer_class &i)\n{\n    a = mp_sqrt(i);\n    b = i - boost::multiprecision::pow(a, 2);\n}\n\n// return nonzero if i is probably prime.\nint mp_probab_prime_p(const integer_class &i, unsigned retries)\n{\n    if (i % 2 == 0)\n        return (i == 2);\n    return miller_rabin_test(i, retries);\n}\n\nvoid mp_nextprime(integer_class &res, const integer_class &i)\n{\n    // simple implementation:  just check all odds bigger than i for primality\n    if (i < 2) {\n        res = 2;\n        return;\n    }\n    integer_class candidate;\n    candidate = (i % 2 == 0) ? i + 1 : i + 2;\n    // Knuth recommends 25 trials for a pretty strong likelihood that candidate\n    // is prime\n    while (!mp_probab_prime_p(candidate, 25)) {\n        candidate += 2;\n    }\n    res = std::move(candidate);\n}\n\nunsigned long mp_scan1(const integer_class &i)\n{\n    if (i == 0) {\n        return ULONG_MAX;\n    }\n    return find_lsb(i, int_<0>());\n}\n\n// define simple 2x2 matrix with exponentiation by repeated squaring\n// to use in logarithmic-time fibonacci calculation\n\nstruct two_by_two_matrix {\n    integer_class data[2][2]; // data[1][0] is row 1, column 0 entry of matrix\n\n    two_by_two_matrix(integer_class a, integer_class b, integer_class c,\n                      integer_class d)\n        : data{{a, b}, {c, d}}\n    {\n    }\n    two_by_two_matrix() : data{{0, 0}, {0, 0}}\n    {\n    }\n    two_by_two_matrix &operator=(const two_by_two_matrix &other)\n    {\n        this->data[0][0] = other.data[0][0];\n        this->data[0][1] = other.data[0][1];\n        this->data[1][0] = other.data[1][0];\n        this->data[1][1] = other.data[1][1];\n        return *this;\n    }\n    two_by_two_matrix operator*(const two_by_two_matrix &other)\n    {\n        two_by_two_matrix res;\n        res.data[0][0] = this->data[0][0] * other.data[0][0]\n                         + this->data[0][1] * other.data[1][0];\n        res.data[0][1] = this->data[0][0] * other.data[0][1]\n                         + this->data[0][1] * other.data[1][1];\n        res.data[1][0] = this->data[1][0] * other.data[0][0]\n                         + this->data[1][1] * other.data[1][0];\n        res.data[1][1] = this->data[1][0] * other.data[0][1]\n                         + this->data[1][1] * other.data[1][1];\n        return res;\n    }\n    // recursive repeated squaring\n    two_by_two_matrix pow(unsigned long n)\n    {\n        if (n == 0) {\n            return two_by_two_matrix::identity();\n        }\n        if (n == 1) {\n            return *this;\n        }\n        if (n == 2) {\n            return (*this) * (*this);\n        }\n        if (n % 2 == 0) {\n            return (this->pow(n / 2)).pow(2);\n        }\n        return ((this->pow((n - 1) / 2)).pow(2)) * (*this);\n    }\n\n    static two_by_two_matrix identity()\n    {\n        return two_by_two_matrix(1, 0, 0, 1);\n    }\n};\n\ninline two_by_two_matrix fib_matrix(unsigned long n)\n{\n    two_by_two_matrix x(1, 1, 1, 0);\n    return x.pow(n);\n}\n\nvoid mp_fib_ui(integer_class &res, unsigned long n)\n{\n    // reference: https://www.nayuki.io/page/fast-fibonacci-algorithms\n    res = fib_matrix(n).data[0][1];\n}\n\n// sets a = Fibonacci(n) and b = Fibonacci(n-1)\nvoid mp_fib2_ui(integer_class &a, integer_class &b, unsigned long n)\n{\n    // reference: https://www.nayuki.io/page/fast-fibonacci-algorithms\n    two_by_two_matrix result_matrix = fib_matrix(n);\n    a = result_matrix.data[0][1];\n    b = result_matrix.data[1][1];\n}\n\ninline two_by_two_matrix luc_matrix(unsigned long n)\n{\n    two_by_two_matrix multiplier(1, 1, 1, 0);\n    two_by_two_matrix start(1, 0, 2, 0);\n    return multiplier.pow(n) * start;\n}\n\nvoid mp_lucnum_ui(integer_class &res, unsigned long n)\n{\n    // implementation based on the following fact:\n    // [[1,1],[1,0]]^(n-1)*[2,0,1,0] = [[L(n+1),0][L(n),0]]\n    // where L(n) is the nth Lucas number\n    res = luc_matrix(n).data[1][0];\n}\n\nvoid mp_lucnum2_ui(integer_class &a, integer_class &b, unsigned long n)\n{\n    if (n == 0) {\n        throw std::runtime_error(\"index of lucas number cannot be negative\");\n    }\n    two_by_two_matrix result_matrix = luc_matrix(n - 1);\n    a = result_matrix.data[0][0];\n    b = result_matrix.data[1][0];\n}\n\nvoid mp_fac_ui(integer_class &res, unsigned long n)\n{\n    // couldn't make boost's template version of factorial work,\n    // so implement slow, naive version for now\n    res = 1;\n    for (unsigned long i = 2; i <= n; ++i) {\n        res *= i;\n    }\n}\n\nvoid mp_bin_ui(integer_class &res, const integer_class &n, unsigned long r)\n{\n    // slow, naive implementation\n    integer_class x = n - r;\n    res = 1;\n    for (unsigned long i = 1; i <= r; ++i) {\n        res *= x + i;\n        res /= i;\n    }\n}\n\n// this is extremely slow!\nbool mp_perfect_power_p(const integer_class &i)\n{\n    if (i == 0 || i == 1 || i == -1) {\n        return true;\n    }\n    // if i == a**k, with k == pq for some integers p,q\n    // then i == a**(pq) == (a**p)**q == (a**q)**p\n    // hence i is a pth power and a qth power\n    // Hence if i == p**k, then i is a pth power for any p\n    // in the prime factorization of k, and it suffices\n    // to check whether i is a prime power.\n\n    // the largest possible prime p would arise from the\n    // case where i is a prime power of two\n    // so check all prime roots up to log(i) base 2.\n\n    unsigned long max = std::ilogb(i.convert_to<double>());\n\n    // treat case p=2 separately b/c mp_root throws exception\n    // with an even root of a negative\n    if (mp_perfect_square_p(i)) {\n        return true;\n    }\n    integer_class p(2);\n    integer_class root(0);\n    while (true) {\n        mp_nextprime(p, p);\n        if (p > max) {\n            return false;\n        }\n        if (mp_root(root, i, p.convert_to<unsigned long>())) {\n            return true;\n        }\n    }\n}\n\nbool mp_perfect_square_p(const integer_class &i)\n{\n    if (i < 0) {\n        return false;\n    }\n    integer_class root;\n    return mp_root(root, i, 2);\n}\n\n// according to the gmp documentation, the behavior of the\n// corresponding function mpz_legendre is\n// undefined if n is not a positive odd prime.\n// hence we treat n as though it were a positive odd prime\n// but it is up to the caller to very this.\nint mp_legendre(const integer_class &a, const integer_class &n)\n{\n    integer_class res;\n    mp_powm(res, a, integer_class((n - 1) / 2), n);\n    return res <= 1 ? res.convert_to<int>() : -1;\n}\n\n// private function that computes jacobi symbols\n// without checking that arguments satisfy a >= 0\n// and n is odd.\nint unchecked_jacobi(const integer_class &a, const integer_class &n)\n{\n    // https://en.wikipedia.org/wiki/Jacobi_symbol#Calculating_the_Jacobi_symbol\n    if (a == 1) {\n        return 1;\n    }\n    integer_class num = a;\n    integer_class den = n;\n    // (1) Reduce the \"numerator\" modulo the \"denominator\"\n    num = fmod(num, den);\n\n    // (2) Extract any factors of 2 from the \"numerator\"\n    unsigned long factors_of_two = 0;\n    while (num % 2 == 0 && num != 0) {\n        num /= 2; // use a shift instead of division here? faster?\n        ++factors_of_two;\n    }\n    int product_of_twos = 1; // (2 | den)**factors_of_two\n\n    // (2 | den) is -1 iff den % 8 = 3 or den % 8 = 5.\n    // If factors_of_two is odd and (2 | den) is -1,\n    // then (2 | den)**factors_of_two is -1.\n    // Otherwise, (2 | den)**factors_of_two is 1.\n    int den_mod_8 = fmod(den, 8).convert_to<int>();\n    if ((factors_of_two % 2 == 1) && (den_mod_8 == 3 || den_mod_8 == 5)) {\n        product_of_twos = -1;\n    }\n\n    // (3) If the remaining \"numerator\" (after extraction of twos) is 1,\n    // then the remaining jacobi symbol is 1.\n    // If the \"numerator\" and \"denominator\" are not coprime, result is 0.\n    if (num == 1) {\n        return product_of_twos;\n    }\n    if (boost::multiprecision::gcd(num, den) != 1) {\n        return 0;\n    }\n\n    // (4) Otherwise, the \"numerator\" and \"denominator\" are now odd\n    // positive coprime integers, so we can flip the symbol\n    // with quadratic reciprocity, then return to step (1)\n\n    // (num | den) == (den | num), unless num % 4 and den %4 are both\n    // 3, in which case (num | den) == (-1) * (den | num)\n    int quadratic_reciprocity_factor = 1;\n    if ((fmod(num, 4) == 3) && (fmod(den, 4) == 3)) {\n        quadratic_reciprocity_factor = -1;\n    }\n    return product_of_twos * quadratic_reciprocity_factor\n           * unchecked_jacobi(den, num);\n}\n\n// public interface for computing jacobi symbols.  performs checking.\nint mp_jacobi(const integer_class &a, const integer_class &n)\n{\n    if (n < 0) {\n        throw std::runtime_error(\"jacobi denominator must be positive\");\n    }\n    if (n % 2 == 0) {\n        throw std::runtime_error(\"jacobi denominator must be odd\");\n    }\n    return unchecked_jacobi(a, n);\n}\n\nint mp_kronecker(const integer_class &a, const integer_class &n)\n{\n    /*\n    https://en.wikipedia.org/wiki/Kronecker_symbol\n    We compute the Kronecker symbol in terms of the Jacobi symbol.\n    For an integer n!=0, let n = u * PRODUCT (p_i**e_i), where u = -1 or 1 and\n    the p_i's and e_i's are the primes and corresponding powers\n    in the prime factorization of |n|.\n    Then for an integer a, the Kronecker symbol is given by\n    (a | n) = (a | u) * PRODUCT [(a | p_i)**e_i]\n    where\n    (a | u) is -1 if u is -1 and a < 0. Otherwise it is 1.\n    (a | 2) is 0 if a is even, 1 if (a mod 8) == 1 or 7, and -1 if (a mod 8) ==\n    3 or 5.\n    (a | p) is the Legendre symbol if p is an odd prime.\n\n    Let j be the power of the prime 2 in n's prime factorization, and let\n    m = |n|/(2**j) -- that is, m is |n| with all factors of 2 extracted.\n\n    Notice that, if p_1 is 2, then\n    PRODUCT [(a | p_i)**e_i]\n    == (a | 2)**j * PRODUCT [(a | p_i)**e_i]\there the p_i's are the remaining\n    (odd) prime factors\n    == (a | 2)**j * (a | m), \t\t\t\t\there (a | m) is the Jacobi\n    symbol, because m>0 is odd\n\n    Thus,\n    (a | n) == (a | u) * (a | 2)**j * (a | m)\tif n is even\n    (a | n) == (a | u) * (a | m) \t\t\t\tif n is odd\n    */\n\n    if (n == 0) {\n        throw std::runtime_error(\"second arg of Kronecker cannot be zero\");\n    }\n\n    // Compute (a | u)\n    int kr_a_u = 1;\n    if (n.sign() == -1 && a < 0) {\n        kr_a_u = -1;\n    }\n\n    // Compute m, j\n    integer_class m = boost::multiprecision::abs(n);\n    unsigned long j = 0;\n    while (m % 2 == 0 && m != 0) { // while m is even\n        m /= 2;                    // implement with shift?  faster?\n        ++j;\n    }\n\n    // if n is even, compute (a | 2)**j\n    int kr_a_2 = 0;\n    int kr_a_2_to_j = 0;\n    int a_mod_8 = fmod(a, 8).convert_to<int>();\n\n    if (a % 2 != 0) {\n        kr_a_2 = (a_mod_8 == 1 || a_mod_8 == 7) ? 1 : -1;\n        kr_a_2_to_j = (kr_a_2 == -1 && (j % 2 != 0))\n                          ? -1\n                          : 1; //(-1)**odd == -1; (-1)**even=(1)**integer=1\n    }\n\n    if (n % 2 == 0) {\n        return kr_a_u * kr_a_2_to_j * unchecked_jacobi(a, m);\n    } else {\n        return kr_a_u * unchecked_jacobi(a, m);\n    }\n}\n\n} // SymEngine\n\n#endif // SYMENGINE_INTEGER_CLASS == SYMENGINE_BOOSTMP\n", "meta": {"hexsha": "4f5379f34ff057e29b13d9e5e10bed07a1949820", "size": 18430, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "symengine/mp_boost.cpp", "max_stars_repo_name": "jmig5776/symengine", "max_stars_repo_head_hexsha": "03babc5c56b047b2fe81ef6f8391d1845e6bb66c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 11.0, "max_stars_repo_stars_event_min_datetime": "2020-02-15T23:54:19.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-28T12:45:45.000Z", "max_issues_repo_path": "symengine/mp_boost.cpp", "max_issues_repo_name": "HQSquantumsimulations/symengine", "max_issues_repo_head_hexsha": "95d6af92dc6a759d9320d6bdadfa51d038c81218", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 11.0, "max_issues_repo_issues_event_min_datetime": "2015-07-18T04:13:48.000Z", "max_issues_repo_issues_event_max_datetime": "2017-06-08T07:05:14.000Z", "max_forks_repo_path": "symengine/mp_boost.cpp", "max_forks_repo_name": "HQSquantumsimulations/symengine", "max_forks_repo_head_hexsha": "95d6af92dc6a759d9320d6bdadfa51d038c81218", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-09-10T13:08:39.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-10T13:08:39.000Z", "avg_line_length": 30.4125412541, "max_line_length": 80, "alphanum_fraction": 0.5765599566, "num_tokens": 5553, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6039318337259584, "lm_q2_score": 0.5, "lm_q1q2_score": 0.3019659168629792}}
{"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 <string>\n#include <stdexcept>\n#include <cmath>\n\n#include <boost/lexical_cast.hpp>\n#include <boost/filesystem/operations.hpp>\n\n#include <hashclash/saveload_gz.hpp>\n#include <hashclash/md5detail.hpp>\n#include <hashclash/booleanfunction.hpp>\n#include <hashclash/rng.hpp>\n\n#include \"main.hpp\"\n\n#define HASHCLASH_MD5COMPRESS_STEP(f, a, b, c, d, m, ac, rc) \\\n        a += f(b, c, d) + m + ac; a = rotate_left(a,rc); a += b;\n\ndouble testnearcollprob(uint32 dm11, uint32 diffcd, uint32 diffb) {\n        uint32 count = 0;\n        for (unsigned k = 0; k < (1<<23); ++k)\n        {\n                uint32 a = xrng64(), b = xrng64()+xrng64()*11, c = xrng64(), d = xrng64()+xrng64()*11;\n                uint32 a2 = a, b2 = b, c2 = c, d2 = d;\n                uint32 m11 = xrng64(), m2 = xrng64(), m9 = xrng64();\n                HASHCLASH_MD5COMPRESS_STEP(md5_ii, d, a, b, c, m11, 0xbd3af235, 10);\n                HASHCLASH_MD5COMPRESS_STEP(md5_ii, c, d, a, b, m2, 0x2ad7d2bb, 15);\n                HASHCLASH_MD5COMPRESS_STEP(md5_ii, b, c, d, a, m9, 0xeb86d391, 21);\n                HASHCLASH_MD5COMPRESS_STEP(md5_ii, d2, a2, b2, c2, m11+dm11, 0xbd3af235, 10);\n                HASHCLASH_MD5COMPRESS_STEP(md5_ii, c2, d2, a2, b2, m2, 0x2ad7d2bb, 15);\n                HASHCLASH_MD5COMPRESS_STEP(md5_ii, b2, c2, d2, a2, m9, 0xeb86d391, 21);\n                if (d2-d==diffcd && c2-c==diffcd && b2-b==diffb)\n                        ++count;\n        }\n        return double(count)/double(1<<23);\n}\n\nvoid constructupperpath_sbcpc(differentialpath& path, uint32 dm[16], uint32 diffihv[4])\n{\n\tuint32 a,b,c,d,a2,b2,c2,d2,oa,ob,oc,od,m11,m2,m9,m4;\n\ta = xrng64(); b = xrng64()+xrng64()*11; c = xrng64(); d = xrng64()+xrng64()*11;\n\twhile (true) {\n                oa = a2 = a; ob = b2 = b; oc = c2 = c; od = d2 = d;\n                m4 = xrng64();\n\t\tHASHCLASH_MD5COMPRESS_STEP(md5_ii, a, b, c, d, m4, 0xf7537e82,  6);\n\t\tHASHCLASH_MD5COMPRESS_STEP(md5_ii, a2, b2, c2, d2, m4+dm[4], 0xf7537e82,  6);\n\t\tif (a2-a != diffihv[0]) {\n\t\t\tb = xrng64(); c = xrng64(); d = xrng64();\n\t\t\tcontinue;\n\t\t}\n\t\tm11 = xrng64(); \n                HASHCLASH_MD5COMPRESS_STEP(md5_ii, d, a, b, c, m11, 0xbd3af235, 10);\n                HASHCLASH_MD5COMPRESS_STEP(md5_ii, d2, a2, b2, c2, m11+dm[11], 0xbd3af235, 10);\n\t\tif (d2-d != diffihv[3]) {\n\t\t\tb = xrng64(); c = xrng64();\n\t\t\tcontinue;\n\t\t}\n\t\tm2 = xrng64(); \n                HASHCLASH_MD5COMPRESS_STEP(md5_ii, c, d, a, b, m2, 0x2ad7d2bb, 15);\n                HASHCLASH_MD5COMPRESS_STEP(md5_ii, c2, d2, a2, b2, m2+dm[2], 0x2ad7d2bb, 15);\n\t\tif (c2-c != diffihv[2]) {\n\t\t\tb = xrng64();\n\t\t\tcontinue;\n\t\t}\n\t\tm9 = xrng64(); \n                HASHCLASH_MD5COMPRESS_STEP(md5_ii, b, c, d, a, m9, 0xeb86d391, 21);\n                HASHCLASH_MD5COMPRESS_STEP(md5_ii, b2, c2, d2, a2, m9+dm[9], 0xeb86d391, 21);\n\t\tif (b2-b == diffihv[1]) break;\n        }\n\tfor (unsigned i = 55; i <= 64; ++i)\n\t\tpath[i].clear();\n\tpath[61] = sdr(a,a2);\n\tpath[62] = sdr(d,d2);\n\tpath[63] = sdr(c,c2);\n\tpath[64] = sdr(b,b2);\n\n\ta2 = oa; b2 = ob; c2 = oc; d2 = od;\n\ta = oa; b = ob; c = oc; d = od;\n\tHASHCLASH_MD5COMPRESS_STEP(md5_ii, a, b, c, d, m4, 0xf7537e82,  6);\n\tHASHCLASH_MD5COMPRESS_STEP(md5_ii, a2, b2, c2, d2, m4+dm[4], 0xf7537e82,  6);\n\tsdr dF61 = sdr(md5_ii(a,b,c),md5_ii(a2,b2,c2));\n\tHASHCLASH_MD5COMPRESS_STEP(md5_ii, d, a, b, c, m11, 0xbd3af235, 10);\n\tHASHCLASH_MD5COMPRESS_STEP(md5_ii, d2, a2, b2, c2, m11+dm[11], 0xbd3af235, 10);\n\tsdr dF62 = sdr(md5_ii(d,a,b),md5_ii(d2,a2,b2));\n\tHASHCLASH_MD5COMPRESS_STEP(md5_ii, c, d, a, b, m2, 0x2ad7d2bb, 15);\n\tHASHCLASH_MD5COMPRESS_STEP(md5_ii, c2, d2, a2, b2, m2+dm[2], 0x2ad7d2bb, 15);\n\tsdr dF63 = sdr(md5_ii(c,d,a),md5_ii(c2,d2,a2));\n\n\tfor (unsigned b = 0; b < 32; ++b) {\n\t\tbitcondition f61 = bc_constant, f62 = bc_constant, f63 = bc_constant;\n\t\tif (dF61.get(b) == +1) f61 = bc_plus;\n\t\tif (dF61.get(b) == -1) f61 = bc_minus;\n\t\tif (dF62.get(b) == +1) f62 = bc_plus;\n\t\tif (dF62.get(b) == -1) f62 = bc_minus;\n\t\tif (dF63.get(b) == +1) f63 = bc_plus;\n\t\tif (dF63.get(b) == -1) f63 = bc_minus;\n\t\tbf_conditions bc0 = MD5_I_data.forwardconditions(path[61][b], bc_constant, bc_constant, f61);\n\t\tbf_conditions bc1 = MD5_I_data.forwardconditions(path[62][b], bc0.first, bc0.second, f62);\n\t\tbf_conditions bc2 = MD5_I_data.forwardconditions(path[63][b], bc1.first, bc1.second, f63);\n\t\tpath.setbitcondition(59, b, bc0.third);\n\t\tpath.setbitcondition(60, b, bc1.third);\n\t\tpath.setbitcondition(61, b, bc2.third);\n\t\tpath.setbitcondition(62, b, bc2.second);\n\t\tpath.setbitcondition(63, b, bc2.first);\n\t}\n}\n\nvoid constructupperpath(differentialpath& path, uint32 dm11, uint32 diffcd, uint32 diffb)\n{\n\tuint32 a,b,c,d,a2,b2,c2,d2,oa,ob,oc,od,m11,m2,m9;\n\twhile (true) {\n                a = xrng64(); b = xrng64()+xrng64()*11; c = xrng64(); d = xrng64()+xrng64()*11;\n                a2 = a; b2 = b; c2 = c; d2 = d;\n                oa = a; ob = b; oc = c; od = d;\n                m11 = xrng64(); m2 = xrng64(); m9 = xrng64();\n                HASHCLASH_MD5COMPRESS_STEP(md5_ii, d, a, b, c, m11, 0xbd3af235, 10);\n                HASHCLASH_MD5COMPRESS_STEP(md5_ii, c, d, a, b, m2, 0x2ad7d2bb, 15);\n                HASHCLASH_MD5COMPRESS_STEP(md5_ii, b, c, d, a, m9, 0xeb86d391, 21);\n                HASHCLASH_MD5COMPRESS_STEP(md5_ii, d2, a2, b2, c2, m11+dm11, 0xbd3af235, 10);\n                HASHCLASH_MD5COMPRESS_STEP(md5_ii, c2, d2, a2, b2, m2, 0x2ad7d2bb, 15);\n                HASHCLASH_MD5COMPRESS_STEP(md5_ii, b2, c2, d2, a2, m9, 0xeb86d391, 21);\n                if (d2-d==diffcd && c2-c==diffcd && b2-b==diffb)\n                \tbreak;\n        }\n\tfor (unsigned i = 58; i <= 64; ++i)\n\t\tpath[i].clear();\n\tpath[62] = sdr(d,d2);\n\tpath[63] = sdr(c,c2);\n\tpath[64] = sdr(b,b2);\n\n\ta2 = oa; b2 = ob; c2 = oc; d2 = od;\n\ta = oa; b = ob; c = oc; d = od;\n\tHASHCLASH_MD5COMPRESS_STEP(md5_ii, d, a, b, c, m11, 0xbd3af235, 10);\n\tHASHCLASH_MD5COMPRESS_STEP(md5_ii, d2, a2, b2, c2, m11+dm11, 0xbd3af235, 10);\n\tsdr dF62 = sdr(md5_ii(d,a,b),md5_ii(d2,a2,b2));\n\tHASHCLASH_MD5COMPRESS_STEP(md5_ii, c, d, a, b, m2, 0x2ad7d2bb, 15);\n\tHASHCLASH_MD5COMPRESS_STEP(md5_ii, c2, d2, a2, b2, m2, 0x2ad7d2bb, 15);\n\tsdr dF63 = sdr(md5_ii(c,d,a),md5_ii(c2,d2,a2));\n\n\tfor (unsigned b = 0; b < 32; ++b) {\n\t\tbitcondition f62 = bc_constant, f63 = bc_constant;\n\t\tif (dF62.get(b) == +1) f62 = bc_plus;\n\t\tif (dF62.get(b) == -1) f62 = bc_minus;\n\t\tif (dF63.get(b) == +1) f63 = bc_plus;\n\t\tif (dF63.get(b) == -1) f63 = bc_minus;\n\t\tbf_conditions bc1 = MD5_I_data.forwardconditions(path[62][b], bc_constant, bc_constant, f62);\n\t\tbf_conditions bc2 = MD5_I_data.forwardconditions(path[63][b], bc1.first, bc1.second, f63);\n\t\tpath.setbitcondition(60, b, bc1.third);\n\t\tpath.setbitcondition(61, b, bc2.third);\n\t\tpath.setbitcondition(62, b, bc2.second);\n\t\tpath.setbitcondition(63, b, bc2.first);\n\t}\n}\n\nint startnearcollision(parameters_type& parameters)\n{\n\tuint32 ihv1[4];\n\tuint32 ihv2[4];\n\tuint32 msg1[16];\n\tuint32 msg2[16];\n\t{\n\t\tifstream if1(parameters.infile1.c_str(), ios::binary);\n\t\tif (!if1) {\n\t\t\tcerr << \"Error: cannot open inputfile 1 '\" << parameters.infile1 << \"'!\" << endl;\n\t\t\treturn 1;\n\t\t}\n\t\tifstream if2(parameters.infile2.c_str(), ios::binary);\n\t\tif (!if2) {\n\t\t\tcerr << \"Error: cannot open inputfile 2 '\" << parameters.infile2 << \"'!\" << endl;\n\t\t\treturn 1;\n\t\t}\n\t\t\n\t\tfor (unsigned k = 0; k < 4; ++k)\n\t\t\tihv1[k] = ihv2[k] = md5_iv[k];\n\n\t\t// load, md5 and save inputfile1\n\t\tunsigned file1blocks = 0;\n\t\twhile (load_block(if1, msg1) > 0) {\n\t\t\tmd5compress(ihv1, msg1);\n\t\t\t++file1blocks;\n\t\t}\n\t\t// load, md5 and save inputfile2\n\t\tunsigned file2blocks = 0;\n\t\twhile (load_block(if2, msg2) > 0) {\n\t\t\tmd5compress(ihv2, msg2);\t\t\t\n\t\t\t++file2blocks;\n\t\t}\n\t\tif (file1blocks != file2blocks) {\n\t\t\tcerr << \"Error: inputfile 1 and 2 are not of equal size\" << endl;\n\t\t\treturn 2;\n\t\t}\n\t}\n\n\tcout << \"IHV1   = {\" << ihv1[0] << \",\" << ihv1[1] << \",\" << ihv1[2] << \",\" << ihv1[3] << \"}\" << endl;\n\tcout << \"IHV1   = \" << hex;\n\tfor (unsigned k = 0; k < 4; ++k)\n\t\tfor (unsigned c = 0; c < 4; ++c)\n\t\t{\n\t\t\tcout.width(2); cout.fill('0');\n\t\t\tcout << ((ihv1[k]>>(c*8))&0xFF);\n\t\t}\n\tcout << dec << endl << endl;\n\n\tcout << \"IHV2   = {\" << ihv2[0] << \",\" << ihv2[1] << \",\" << ihv2[2] << \",\" << ihv2[3] << \"}\" << endl;\n\tcout << \"IHV2   = \" << hex;\n\tfor (unsigned k = 0; k < 4; ++k)\n\t\tfor (unsigned c = 0; c < 4; ++c)\n\t\t{\n\t\t\tcout.width(2); cout.fill('0');\n\t\t\tcout << ((ihv2[k]>>(c*8))&0xFF);\n\t\t}\n\tcout << dec << endl << endl;\n\n\tuint32 dihv[4] = { ihv2[0] - ihv1[0], ihv2[1] - ihv1[1], ihv2[2] - ihv1[2], ihv2[3] - ihv1[3] };\n\tcout << \"dIHV   = {\" << dihv[0] << \",\" << dihv[1] << \",\" << dihv[2] << \",\" << dihv[3] << \"}\" << endl;\n\n\tbool sbcpc = false;\n\tif (dihv[0]==0 && dihv[1]==0 && dihv[2]==0 && dihv[3]==0)\n\t{\n\t\tcerr << \"dIHV is zero!\" << endl;\n\t\treturn 4;\n\t}\n\tif (dihv[0] == +(1<<5) && dihv[3] == +(1<<5) -(1<<25))\n\t\tsbcpc = true;\n\telse if (dihv[0] != 0 || dihv[2] != dihv[3])\n\t{\n\t\tcerr << \"Error: dIHV is not of the required form dIHV[0]=0, dIHV[2]=dIHV[3]\" << endl;\n\t\treturn 3;\n\t}\n\tuint32 m_diff[16] = { 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0 };\n\tvector<uint32> dm11;\n\tvector< pair<uint32,uint32> > ncdiff;\n\tunsigned j = 0;\n\tif (sbcpc) {\n\t\tm_diff[11] = 1<<15;\n\t\tm_diff[4] = 1<<31;\n\t\tm_diff[14] = 1<<31;\n\t\tm_diff[2] = 1<<8;\n\t} else {\n\t\tsdr diffcd = naf(0-dihv[3]);\n\t\tsdr diffb  = naf(dihv[3] - dihv[1]);\t\t\n\t\tunsigned bb = 0;\n\t\twhile (bb < 32) {\n\t\t\tif (diffcd.get(bb) != 0) {\n\t\t\t\tunsigned bend=bb+1;\n\t\t\t\twhile (bend < 32 && bend<=bb+parameters.pathtyperange && diffcd.get(bend)==0)\n\t\t\t\t\t++bend;\n\t\t\t\tuint32 diff1 = 1<<bb;\n\t\t\t\tif (diffcd.get(bb) == -1)\n\t\t\t\t\tdiff1 = -(1<<bb);\n\t\t\t\tuint32 diff2 = diff1;\n\t\t\t\tfor (unsigned b2 = bb; b2 < bend; ++b2)\n\t\t\t\t\tif (diffb.get((b2+21)%32) == +1)\n\t\t\t\t\t\tdiff2 += 1<<((b2+21)%32);\n\t\t\t\t\telse if (diffb.get((b2+21)%32) == -1)\n\t\t\t\t\t\tdiff2 -= 1<<((b2+21)%32);\n\t\t\t\tncdiff.push_back( pair<uint32,uint32>(diff1,diff2) );\n\t\t\t\tbb = bend;\n\t\t\t} else if (diffb.get((bb+21)%32) != 0) {\n\t\t\t\tuint32 diff1 = 0, diff2 = 0;\n\t\t\t\tunsigned bend=bb+1;\n\t\t\t\tunsigned tempinc=0;\n\t\t\t\tif (bb+1 < 32 && diffcd.get(bb+1) != 0) {\n\t\t\t\t\tif (diffcd.get(bb+1) == +1)\n\t\t\t\t\t\tdiff1 += 1<<bb;\n\t\t\t\t\telse\n\t\t\t\t\t\tdiff1 -= 1<<bb;\n\t\t\t\t\tncdiff.push_back( pair<uint32,uint32>(diff1,diff1) );\n\t\t\t\t\tbend=bb+2;\n\t\t\t\t\ttempinc=1;\t\t\t\t\n\t\t\t\t} else {\n\t\t\t\t\tdiff1 = 1<<bb;\n\t\t\t\t\tif (diffb.get((bb+21)%32) == +1)\n\t\t\t\t\t\tdiff1 = 0-(1<<bb);\n\t\t\t\t\tncdiff.push_back( pair<uint32,uint32>(0-diff1,0-diff1) );\n\t\t\t\t}\n\t\t\t\tdiff2 = diff1;\n\t\t\t\twhile (bend < 32 && bend<=bb+parameters.pathtyperange+tempinc && diffcd.get(bend)==0)\n\t\t\t\t\t++bend;\n\t\t\t\tfor (unsigned b2 = bb; b2 < bend; ++b2)\n\t\t\t\t\tif (diffb.get((b2+21)%32) == +1)\n\t\t\t\t\t\tdiff2 += 1<<((b2+21)%32);\n\t\t\t\t\telse if (diffb.get((b2+21)%32) == -1)\n\t\t\t\t\t\tdiff2 -= 1<<((b2+21)%32);\n\t\t\t\tncdiff.push_back( pair<uint32,uint32>(diff1,diff2) );\n\t\t\t\tbb = bend;\n\t\t\t} else ++bb;\n\t\t}\n\t\tif (ncdiff.size()> 1 && 0!=naf(ncdiff[ncdiff.size()-1].first).get(31) && 0!=(ncdiff[0].first&1)) {\n\t\t\tncdiff[0].first += ncdiff[ncdiff.size()-1].first;\n\t\t\tncdiff[0].second += ncdiff[ncdiff.size()-1].second;\n\t\t\tncdiff.pop_back();\n\t\t}\n\t\tuint32 temp1 = 0, temp2 = 0;\n\t\tfor (unsigned i = 0; i < ncdiff.size(); ++i)\n\t\t{\n\t\t\tcout << \"NC\" << i << \": delta c = delta d = \" << naf(ncdiff[i].first) << endl;\n\t\t\tcout << \"NC\" << i << \": delta b           = \" << naf(ncdiff[i].second) << endl;\n\t\t\ttemp1 += ncdiff[i].first;\n\t\t\ttemp2 += ncdiff[i].second;\n\t\t}\n\t\tif (dihv[3] != uint32(0-temp1) || dihv[1] != uint32(0-temp2)) {\n\t\t\tcerr << \"Internal error in determining near-collision blocks:\" << endl;\n\t\t\tcerr << dihv[3] << \"=?\" << uint32(0-temp1) << endl;\n\t\t\tcerr << dihv[1] << \"=?\" << uint32(0-temp2) << endl;\n\t\t}\n\t\tdm11.resize(ncdiff.size(),0);\n\t\tvector<double> prob(ncdiff.size(),0);\n\t\tfor (unsigned i = 0; i < ncdiff.size(); ++i)\n\t\t{\n\t\t\tsdr fnaf = naf(ncdiff[i].first);\n\t\t\tfor (unsigned b = 0; b < 32; ++b)\n\t\t\t\tif (fnaf.get(b) == +1) {\n\t\t\t\t\tdm11[i] = uint32(1)<<((b-10)%32);\n\t\t\t\t\tbreak;\n\t\t\t\t} else if (fnaf.get(b) == -1) {\n\t\t\t\t\tdm11[i] = 0-(uint32(1)<<((b-10)%32));\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\tif (fnaf.get(0) != 0 && fnaf.get(31) != 0) {\n\t\t\t\tif (fnaf.get(0) == +1)\n\t\t\t\t\tdm11[i] = uint32(1)<<21;\n\t\t\t\telse\n\t\t\t\t\tdm11[i] = 0-(uint32(1)<<21);\n\t\t\t}\n\t\t\tprob[i] = testnearcollprob(dm11[i], ncdiff[i].first, ncdiff[i].second);\n\t\t\tcout << \"NC\" << i << \": prob=\" << log(prob[i])/log(double(2)) << endl;\n\t\t}\n\t\tj = 0;\n\t\tfor (unsigned i = 1; i < prob.size(); ++i)\n\t\t\tif (prob[i] > prob[j]) j = i;\n\t\tunsigned skipnum = parameters.skipnc % ncdiff.size();\n\t\tfor (unsigned skip = 0; skip < skipnum; ++skip) {\n\t\t\tswap(dm11[j],dm11[dm11.size()-1]); dm11.pop_back();\n\t\t\tswap(ncdiff[j],ncdiff[ncdiff.size()-1]); ncdiff.pop_back();\n\t\t\tswap(prob[j],prob[prob.size()-1]); prob.pop_back();\n\t\t\tj = 0;\n\t\t\tfor (unsigned i = 1; i < prob.size(); ++i)\n\t\t\t\tif (prob[i] > prob[j]) j = i;\n\t\t}\n\t\tunsigned b = 0;\n\t\tint m11sign = +1;\n\t\tfor (bb = 0; bb < 32; ++bb)\n\t\t\tif (naf(dm11[j]).get(bb) != 0) {\n\t\t\t\tb = bb;\n\t\t\t\tif (naf(dm11[j]).get(bb) == -1) \n\t\t\t\t\tm11sign = -1;\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\tcout << \"delta m_11 = \" << naf(dm11[j]) << endl;\n\t\tm_diff[11] = dm11[j];\n\t}\n\n\t/*** Construct lower diff. path ***/\n\tdifferentialpath lowerpath;\n\tuint32 Q1[4] = { ihv1[0], ihv1[3], ihv1[2], ihv1[1] };\n\tuint32 Q2[4] = { ihv2[0], ihv2[3], ihv2[2], ihv2[1] };\n\tfor (int i = 0; i < 4; ++i)\n\t\tfor (unsigned k = 0; k < 32; ++k)\n\t\t{\n\t\t\tif ((Q1[i]>>k)&1) {\n\t\t\t\tif ((Q2[i]>>k)&1)\n\t\t\t\t\tlowerpath.setbitcondition(i-3,k,bc_one);\n\t\t\t\telse\n\t\t\t\t\tlowerpath.setbitcondition(i-3,k,bc_minus);\n\t\t\t} else {\n\t\t\t\tif ((Q2[i]>>k)&1)\n\t\t\t\t\tlowerpath.setbitcondition(i-3,k,bc_plus);\n\t\t\t\telse\n\t\t\t\t\tlowerpath.setbitcondition(i-3,k,bc_zero);\n\t\t\t}\n\t\t}\n\tuint32 dF = 0;\n\tfor (unsigned k = 0; k < 32; ++k)\n\t{\n\t\tbf_outcome outcome = MD5_F_data.outcome(lowerpath(0,k), lowerpath(-1,k), lowerpath(-2,k));\n\t\tif (outcome.size()) {\n\t\t\tif (outcome[0] == bc_plus) \t\t\tdF += 1<<k;\n\t\t\telse if (outcome[0] == bc_minus)\tdF -= 1<<k;\n\t\t}\n\t}\n\tuint32 dQtm3 = lowerpath[-3].diff();\n\tuint32 dT = dQtm3 + dF + m_diff[0];\n\tstd::vector<std::pair<uint32,double> > rotateddiff;\n\trotate_difference(dT, md5_rc[0], rotateddiff);\n\tdouble bestrot = 0;\n\tfor (unsigned i = 0; i < rotateddiff.size(); ++i)\n\t{\n\t\tuint32 dR = rotateddiff[i].first;\n\t\twordconditions Q1 = naf(lowerpath[0].diff() + dR);\n\t\trotateddiff[i].second = check_rotation(dR, dT, md5_rc[0], lowerpath[0], Q1, 1<<12);\n\t\tif (rotateddiff[i].second > bestrot) {\n\t\t\tlowerpath[1] = Q1;\n\t\t\tbestrot = rotateddiff[i].second;\n\t\t}\n\t}\n\n\t/*** Show and store lower diff. path ***/\n\tshow_path(lowerpath, m_diff);\n\ttry {\n\t\tvector<differentialpath> temp;\n\t\ttemp.push_back(lowerpath);\n\t\tsave_gz(temp, workdir +  \"/lowerpath\", binary_archive);\n\t\tcout << \"Saved lower diff. path to '\" << workdir + \"/lowerpath.bin.gz'.\" << endl;\n\t} catch (...) {\n\t\tcerr << \"Error: could not write '\" << workdir + \"/lowerpath.bin.gz'!\" << endl;\n\t}\n\tcout << endl;\n\t\n\t/*** Construct upper diff. path ***/\n\tdifferentialpath upperpath, bestpath;\n\tunsigned bestcond = 1<<31;\n\tfor (unsigned i = 0; i < 1<<10; ++i) {\n\t\tif (sbcpc) {\n\t\t\tuint32 dihvmin[4] = { -dihv[0], -dihv[1], -dihv[2], -dihv[3] };\n\t\t\tconstructupperpath_sbcpc(upperpath, m_diff, dihvmin);\n\t\t} else {\n\t\t\tupperpath[32].clear();\n\t\t\tconstructupperpath(upperpath, dm11[j], ncdiff[j].first, ncdiff[j].second);\n\t\t}\n\t\tif (upperpath.nrcond() < bestcond) {\n\t\t\tbestcond = upperpath.nrcond();\n\t\t\tbestpath = upperpath;\n\t\t}\n\t}\n\tupperpath = bestpath;\n\n\t/*** Show and store upper diff. path ***/\n\tshow_path(upperpath, m_diff);\n\ttry {\n\t\tvector<differentialpath> temp;\n\t\ttemp.push_back(upperpath);\n\t\tsave_gz(temp, workdir +  \"/upperpath\", binary_archive);\n\t\tcout << \"Saved upper diff. path to '\" << workdir + \"/upperpath.bin.gz'.\" << endl;\n\t} catch (...) {\n\t\tcerr << \"Error: could not write '\" << workdir + \"/upperpath.bin.gz'!\" << endl;\n\t}\n\n\t/*** Write md5diffpath_forward.cfg ***/\n\t{\n\t\tofstream off(\"md5diffpathforward.cfg\");\n\t\tif (!off)\n\t\t\tcerr << \"Error: could not write md5diffpathforward.cfg!\" << endl;\n\t\telse {\n\t\t\t/* write IHV info */\n\t\t\toff << \"# IHV\" << endl;\n\t\t\toff << \"ihv0a = \" << ihv1[0] << endl;\n\t\t\toff << \"ihv1a = \" << ihv1[1] << endl;\n\t\t\toff << \"ihv2a = \" << ihv1[2] << endl;\n\t\t\toff << \"ihv3a = \" << ihv1[3] << endl << endl;\n\t\t\toff << \"# IHV'\" << endl;\n\t\t\toff << \"ihv0b = \" << ihv2[0] << endl;\n\t\t\toff << \"ihv1b = \" << ihv2[1] << endl;\n\t\t\toff << \"ihv2b = \" << ihv2[2] << endl;\n\t\t\toff << \"ihv3b = \" << ihv2[3] << endl << endl;\n\t\t\t/* write delta m11 */\n\t\t\toff << \"# message block difference\" << endl;\n\t\t\tfor (unsigned i = 0; i < 16; ++i)\n\t\t\t\tfor (unsigned b = 0; b < 32; ++b)\n\t\t\t\t\tif (naf(m_diff[i]).get(b) != 0)\n\t\t\t\t\t\toff << \"diffm\" << i << \" = \" << int(b+1)*naf(m_diff[i]).get(b) << endl;\n\t\t\t/* other settings */\n\t\t\toff << \"# parameters\" << endl;\n\n\t\t\t/* copy template file if any */\n\t\t\tifstream iff(\"md5diffpathforward.cfg.template\");\n\t\t\tif (!iff)\n\t\t\t\tcerr << \"Warning: could not read md5diffpathforward.cfg.template\" << endl;\n\t\t\telse\n\t\t\t\toff << iff.rdbuf() << endl;\n\t\t\tcout << \"Saved 'md5diffpathforward.cfg'.\" << endl;\n\t\t}\n\t}\n\n\t/*** Write md5diffpath_backward.cfg ***/\n\t{\n\t\tofstream ofb(\"md5diffpathbackward.cfg\");\n\t\tif (!ofb)\n\t\t\tcerr << \"Error: could not write md5diffpathbackward.cfg!\" << endl;\n\t\telse {\n\t\t\t/* write delta m11 */\n\t\t\tofb << \"# message block difference\" << endl;\n\t\t\tfor (unsigned i = 0; i < 16; ++i)\n\t\t\t\tfor (unsigned b = 0; b < 32; ++b)\n\t\t\t\t\tif (naf(m_diff[i]).get(b) != 0)\n\t\t\t\t\t\tofb << \"diffm\" << i << \" = \" << int(b+1)*naf(m_diff[i]).get(b) << endl;\n\t\t\t/* other settings */\n\t\t\tofb << \"# parameters\" << endl;\n\n\t\t\t/* copy template file if any */\n\t\t\tifstream ifb(\"md5diffpathbackward.cfg.template\");\n\t\t\tif (!ifb)\n\t\t\t\tcerr << \"Warning: could not read md5diffpathbackward.cfg.template\" << endl;\n\t\t\telse\n\t\t\t\tofb << ifb.rdbuf() << endl;\n\t\t\tcout << \"Saved 'md5diffpathbackward.cfg'.\" << endl;\n\t\t}\n\t}\n\n\t/*** Write md5diffpath_connect.cfg ***/\n\t{\n\t\tofstream ofc(\"md5diffpathconnect.cfg\");\n\t\tif (!ofc)\n\t\t\tcerr << \"Error: could not write md5diffpathconnect.cfg!\" << endl;\n\t\telse {\n\t\t\t/* write delta m11 */\n\t\t\tofc << \"# message block difference\" << endl;\n\t\t\tfor (unsigned i = 0; i < 16; ++i)\n\t\t\t\tfor (unsigned b = 0; b < 32; ++b)\n\t\t\t\t\tif (naf(m_diff[i]).get(b) != 0)\n\t\t\t\t\t\tofc << \"diffm\" << i << \" = \" << int(b+1)*naf(m_diff[i]).get(b) << endl;\n\t\t\t/* other settings */\n\t\t\tofc << \"# parameters\" << endl;\n\n\t\t\t/* copy template file if any */\n\t\t\tifstream ifc(\"md5diffpathconnect.cfg.template\");\n\t\t\tif (!ifc)\n\t\t\t\tcerr << \"Warning: could not read md5diffpathconnect.cfg.template\" << endl;\n\t\t\telse\n\t\t\t\tofc << ifc.rdbuf() << endl;\n\t\t\tcout << \"Saved 'md5diffpathconnect.cfg'.\" << endl;\n\t\t}\n\t}\n\n\t/*** Write md5diffpath_helper.cfg ***/\n\t{\n\t\tofstream ofc(\"md5diffpathhelper.cfg\");\n\t\tif (!ofc)\n\t\t\tcerr << \"Error: could not write md5diffpathhelper.cfg!\" << endl;\n\t\telse {\n\t\t\t/* write delta m11 */\n\t\t\tofc << \"# message block difference\" << endl;\n\t\t\tfor (unsigned i = 0; i < 16; ++i)\n\t\t\t\tfor (unsigned b = 0; b < 32; ++b)\n\t\t\t\t\tif (naf(m_diff[i]).get(b) != 0)\n\t\t\t\t\t\tofc << \"diffm\" << i << \" = \" << int(b+1)*naf(m_diff[i]).get(b) << endl;\n\n\t\t\tcout << \"Saved 'md5diffpathhelper.cfg'.\" << endl;\n\t\t}\n\t}\n\n\treturn 0;\n}\n\n\n\n\n\n\n\n\n\n\n\nvoid writeupperpath(std::string dir, parameters_type& parameters, unsigned b, int m11sign)\n{\n\ttry {\n\t\tboost::filesystem::create_directory(dir);\n\t} catch( std::exception& e) {\n\t\tstd::cerr << e.what() << endl;\n\t\tstd::cerr << \"failed to create directory: \" << dir << endl;\n\t\tthrow;\n\t} catch(...) {\n\t\tstd::cerr << \"failed to create directory: \" << dir << endl;\n\t\tthrow;\n\t}\n\tbitcondition plus = bc_plus, minus = bc_minus;\n\tif (m11sign == -1)\n\t\tswap(plus, minus);\n\tuint32 m_diff[16] = { 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0 };\n\tm_diff[11] = m11sign * (1<<b);\n\n\t/*** Construct upper diff. path ***/\n\tdifferentialpath upperpath;\n\tupperpath[32].clear();\n\tupperpath.setbitcondition(60, (b+10)&31, bc_zero);\n\tupperpath.setbitcondition(61, (b+10)&31, bc_one);\n\tupperpath.setbitcondition(62, (b+10)&31, plus);\n\tupperpath.setbitcondition(63, (b+10)&31, plus);\n\tupperpath.setbitcondition(64, (b+10)&31, plus);\n\n\t/*** Show and store upper diff. path ***/\n\ttry {\n\t\tvector<differentialpath> temp;\n\t\ttemp.push_back(upperpath);\n\t\tsave_gz(temp, dir +  \"/upperpath\", binary_archive);\n\t\t//cout << \"Saved upper diff. path to '\" << dir + \"/upperpath.bin'.\" << endl;\n\t} catch (...) {\n\t\tcerr << \"Error: could not write '\" << dir << \"/upperpath.bin'!\" << endl;\n\t}\n\n\t/*** Write md5diffpath_backward.cfg ***/\n\t{\n\t\tofstream ofb((dir+\"/md5diffpathbackward.cfg\").c_str());\n\t\tif (!ofb)\n\t\t\tcerr << \"Error: could not write \" << dir << \"md5diffpathbackward.cfg!\" << endl;\n\t\telse {\n\t\t\t/* write delta m11 */\n\t\t\tofb << \"# message block difference\" << endl;\n\t\t\tofb << \"diffm11 = \" << m11sign*int(b+1) << endl << endl;\n\t\t\t/* other settings */\n\t\t\tofb << \"# parameters\" << endl;\n\n\t\t\t/* copy template file if any */\n\t\t\tifstream ifb(\"md5diffpathbackward.cfg.template\");\n\t\t\tif (!ifb)\n\t\t\t\tcerr << \"Error: could not read md5diffpathbackward.cfg.template\" << endl;\n\t\t\telse {\n\t\t\t\tofb << ifb.rdbuf() << endl;\n\t\t\t}\n\t\t\tcout << \"Saved '\" << dir << \"md5diffpathbackward.cfg'.\" << endl;\n\t\t}\n\t}\n}\n\nint upperpaths(parameters_type& parameters)\n{\n\tfor (unsigned b = 0; b < 32; ++b) \n\t{\n\t\tstring bitstr = boost::lexical_cast<string>(b);\n\t\twriteupperpath(workdir + \"plus2power\" + bitstr, parameters, b, 1);\n\t\twriteupperpath(workdir + \"minus2power\" + bitstr, parameters, b, -1);\n\t}\n\treturn 0;\n}\n\n", "meta": {"hexsha": "f09b741744d66b6181ff287cc016f7869155aab9", "size": 21949, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/md5helper/startnearcollision.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/md5helper/startnearcollision.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/md5helper/startnearcollision.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.9767801858, "max_line_length": 102, "alphanum_fraction": 0.5726912388, "num_tokens": 8367, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6548947290421275, "lm_q2_score": 0.46101677931231594, "lm_q1q2_score": 0.30191745877161347}}
{"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 * @file MatrixTypes.hpp\n * @author Thomas Wiemann (twiemann@uos.de)\n * @date 2019-08-14\n * \n * @copyright Copyright (c) 2019\n * \n */\n\n#ifndef LVR2_TYPES_MATRIXTYPES_HPP\n#define LVR2_TYPES_MATRIXTYPES_HPP\n\n#include <Eigen/Dense>\n\nnamespace lvr2\n{\n/// General alias for row major 4x4 matrices \ntemplate<typename T> \nusing Matrix4RM = Eigen::Matrix<T, 4, 4, Eigen::RowMajor>;\n\n/// 4x4 row major matrix with float scalars\nusing Matrix4fRM = Matrix4RM<float>;\n\n/// 4x4 row major matrix with double scalars\nusing Matrix4dRM = Matrix4RM<double>;\n\n/// General alias for row major 3x3 matrices \ntemplate<typename T> \nusing Matrix3RM = Eigen::Matrix<T, 3, 3, Eigen::RowMajor>;\n\n/// 3x3 row major matrix with float scalars\nusing Matrix3fRM = Matrix3RM<float>;\n/// 3x3 row major matrix with double scalars\nusing Matrix3dRM = Matrix3RM<double>;\n\n/// General 4x4 transformation matrix (4x4)\ntemplate<typename T>\nusing Transform = Eigen::Matrix<T, 4, 4>;\n\n/// 4x4 single precision transformation matrix\nusing Transformf = Transform<float>;\n\n/// 4x4 double precision transformation matrix\nusing Transformd = Transform<double>;\n\n/// General 3x3 rotation matrix\ntemplate<typename T>\nusing Rotation = Eigen::Matrix<T, 3, 3>;\n\n/// Single precision 3x3 rotation matrix\nusing Rotationf = Rotation<float>;\n\n/// Double precision 3x3 rotation matrix\nusing Rotationd = Rotation<double>;\n\n/// 4x4 extrinsic calibration\ntemplate<typename T>\nusing Extrinsics = Eigen::Matrix<T, 4, 4>;\n\n/// 4x4 extrinsic calibration (single precision)\nusing Extrinsicsf = Extrinsics<float>;\n\n/// 4x4 extrinsic calibration (double precision)\nusing Extrinsicsd = Extrinsics<double>;\n\n/// 4x4 extrinsic calibration\ntemplate<typename T>\nusing Intrinsics = Eigen::Matrix<T, 3, 3>;\n\n/// 4x4 intrinsic calibration (single precision)\nusing Intrinsicsf = Intrinsics<float>;\n\n/// 4x4 extrinsic calibration (double precision)\nusing Intrinsicsd = Intrinsics<double>;\n\n/// Distortion Parameters\ntemplate<typename T>\nusing Distortion = Eigen::Matrix<T, 6, 1>;\n\n/// Distortion Parameters (double precision)\nusing Distortiond = Distortion<double>;\n\n/// Distortion Parameters (single precision)\nusing Distortionf = Distortion<float>;\n\n/// Eigen 3D vector\ntemplate<typename T>\nusing Vector3 = Eigen::Matrix<T, 3, 1>;\n\n/// Eigen 3D vector, single precision\nusing Vector3f = Eigen::Vector3f;\n\n/// Eigen 3D vector, double precision\nusing Vector3d = Eigen::Vector3d;\n\n/// Eigen 3D vector, integer\nusing Vector3i = Eigen::Vector3i;\n\n/// Eigen 4D vector\ntemplate<typename T>\nusing Vector4 = Eigen::Matrix<T, 4, 1>;\n\n/// Eigen 4D vector, single precision\nusing Vector4f = Eigen::Vector4f;\n\n/// Eigen 4D vector, double precision\nusing Vector4d = Eigen::Vector4d;\n\n/// Eigen 2D vector\ntemplate<typename T>\nusing Vector2 = Eigen::Matrix<T, 2, 1>;\n\n/// Eigen 2D vector, single precision\nusing Vector2f = Eigen::Vector2f;\n\n/// Eigen 2D vector, double precision\nusing Vector2d = Eigen::Vector2d;\n\n/// Eigen 4x4 matrix, single precision\nusing Matrix4f = Eigen::Matrix4f;\n\n/// Eigen 4x4 matrix, double precision\nusing Matrix4d = Eigen::Matrix4d;\n\n/// 6D Matrix, single precision\nusing Matrix6f = Eigen::Matrix<float, 6, 6>;\n\n/// 6D vector, single precision\nusing Vector6f = Eigen::Matrix<float, 6, 1>;\n\n/// 6D matrix double precision\nusing Matrix6d = Eigen::Matrix<double, 6, 6>;\n\n/// 6D vector double precision\nusing Vector6d = Eigen::Matrix<double, 6, 1>;\n\ntemplate<typename T> \nVector3<T> multiply(const Transform<T>& transform, const Vector3<T>& p)\n{\n    Vector4<T> ret(p.coeff(0), p.coeff(1), p.coeff(2), 1.0);\n    ret = transform * ret;\n    return Vector3<T>(ret.coeff(0), ret.coeff(1), ret.coeff(2));\n}\n\n} // namespace lvr2\n\n// additional operators\n\n\n\n\ntemplate<typename T>\nlvr2::Vector3<T> operator*(const lvr2::Transform<T>& transform, const lvr2::Vector3<T>& p)\n{\n    return lvr2::multiply(transform, p);\n}\n\n#endif // LVR2_TYPES_MATRIXTYPES_HPP", "meta": {"hexsha": "b981a887587a1aeabd65a28dc1ae8c4019e370c3", "size": 5474, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/lvr2/types/MatrixTypes.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/types/MatrixTypes.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/types/MatrixTypes.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": 29.5891891892, "max_line_length": 90, "alphanum_fraction": 0.7378516624, "num_tokens": 1413, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.63341027751814, "lm_q2_score": 0.47657965106367595, "lm_q1q2_score": 0.3018704490397413}}
{"text": "#pragma once\n\n#include \"ga/ga.h\"\n#include \"tamm/tamm.hpp\"\n#include <Eigen/Dense>\n\nnamespace tamm {\n\ntemplate<typename T>\ninline void jacobi(ExecutionContext& ec, Tensor<T>& d_r, Tensor<T>& d_t,\n                   T shift, bool transpose, std::vector<double>& evl_sorted, \n                   const TAMM_SIZE& n_occ_alpha, const TAMM_SIZE& n_occ_beta) {\n    // EXPECTS(transpose == false);\n    block_for(ec, d_r(), [&](IndexVector blockid) {\n        const TAMM_SIZE rsize = d_r.block_size(blockid);\n        std::vector<T> rbuf(rsize);\n        d_r.get(blockid, rbuf);\n\n        const TAMM_SIZE tsize = d_t.block_size(blockid);\n\n        std::vector<T> tbuf(tsize);\n\n        auto& rtiss      = d_r.tiled_index_spaces();\n        auto rblock_dims = d_r.block_dims(blockid);\n\n        TAMM_SIZE noab = n_occ_alpha+n_occ_beta;\n        std::vector<double> p_evl_sorted_occ(noab);\n        std::vector<double> p_evl_sorted_virt(evl_sorted.size()-noab);\n        std::copy(evl_sorted.begin(), evl_sorted.begin() + noab,\n                  p_evl_sorted_occ.begin());\n        std::copy(evl_sorted.begin() + noab, evl_sorted.end(),\n                  p_evl_sorted_virt.begin());\n\n        if(d_r.num_modes() == 2) {\n            auto ioff  = rtiss[0].tile_offset(blockid[0]);\n            auto joff  = rtiss[1].tile_offset(blockid[1]);\n            auto isize = rblock_dims[0];\n            auto jsize = rblock_dims[1];\n\n            if(!transpose) {\n                for(auto i = 0U, c = 0U; i < isize; i++) {\n                    for(auto j = 0U; j < jsize; j++, c++) {\n                        tbuf[c] =\n                          rbuf[c] / (-p_evl_sorted_virt[ioff + i] +\n                                     p_evl_sorted_occ[joff + j] + shift);\n                    }\n                }\n            } else {\n                for(auto i = 0U, c = 0U; i < isize; i++) {\n                    for(auto j = 0U; j < jsize; j++, c++) {\n                        tbuf[c] =\n                          rbuf[c] / (p_evl_sorted_occ[ioff + i] -\n                                     p_evl_sorted_virt[joff + j] + shift);\n                    }\n                }\n            }\n            d_t.add(blockid, tbuf);\n        } else if(d_r.num_modes() == 4) {\n            \n            auto rblock_offset = d_r.block_offsets(blockid);\n\n            std::vector<size_t> ioff;\n            for(auto x : rblock_offset) { ioff.push_back(x); }\n            std::vector<size_t> isize;\n            for(auto x : rblock_dims) { isize.push_back(x); }\n\n            if(!transpose) {\n                for(auto i0 = 0U, c = 0U; i0 < isize[0]; i0++) {\n                    for(auto i1 = 0U; i1 < isize[1]; i1++) {\n                        for(auto i2 = 0U; i2 < isize[2]; i2++) {\n                            for(auto i3 = 0U; i3 < isize[3]; i3++, c++) {\n                                tbuf[c] =\n                                  rbuf[c] /\n                                  (-p_evl_sorted_virt[ioff[0] + i0] -\n                                   p_evl_sorted_virt[ioff[1] + i1] +\n                                   p_evl_sorted_occ[ioff[2] + i2] +\n                                   p_evl_sorted_occ[ioff[3] + i3] + shift);\n                            }\n                        }\n                    }\n                }\n            } else {\n                for(auto i0 = 0U, c = 0U; i0 < isize[0]; i0++) {\n                    for(auto i1 = 0U; i1 < isize[1]; i1++) {\n                        for(auto i2 = 0U; i2 < isize[2]; i2++) {\n                            for(auto i3 = 0U; i3 < isize[3]; i3++, c++) {\n                                tbuf[c] =\n                                  rbuf[c] /\n                                  (p_evl_sorted_occ[ioff[0] + i0] +\n                                   p_evl_sorted_occ[ioff[1] + i1] -\n                                   p_evl_sorted_virt[ioff[2] + i2] -\n                                   p_evl_sorted_virt[ioff[3] + i3] + shift);\n                            }\n                        }\n                    }\n                }\n            }\n            d_t.add(blockid, tbuf);\n        } else {\n            assert(0); // @todo implement\n        }\n    });\n    // GA_Sync();\n}\n\ntemplate<typename T>\ninline void jacobi_cs(ExecutionContext& ec, Tensor<T>& d_r, Tensor<T>& d_t,\n                   T shift, bool transpose, std::vector<double>& evl_sorted, \n                   const TAMM_SIZE& n_occ_alpha, const TAMM_SIZE& n_vir_alpha,\n                   const bool not_spin_orbital=false) {\n    // EXPECTS(transpose == false);\n    block_for(ec, d_r(), [&](IndexVector blockid) {\n        const TAMM_SIZE rsize = d_r.block_size(blockid);\n        std::vector<T> rbuf(rsize);\n        d_r.get(blockid, rbuf);\n\n        const TAMM_SIZE tsize = d_t.block_size(blockid);\n\n        std::vector<T> tbuf(tsize);\n\n        auto& rtiss      = d_r.tiled_index_spaces();\n        auto rblock_dims = d_r.block_dims(blockid);\n\n        TAMM_SIZE noa  = n_occ_alpha;\n        TAMM_SIZE noab = n_occ_alpha + n_occ_alpha;\n        TAMM_SIZE nva  = n_vir_alpha;\n        std::vector<double> p_evl_sorted_occ(noa);\n        std::vector<double> p_evl_sorted_virt(nva);\n        std::copy(evl_sorted.begin(), evl_sorted.begin() + noa,\n                  p_evl_sorted_occ.begin());\n        if(not_spin_orbital)\n            std::copy(evl_sorted.begin() + noa, evl_sorted.begin() + noa + nva,\n                        p_evl_sorted_virt.begin());\n        else\n            std::copy(evl_sorted.begin() + noab, evl_sorted.begin() + noab + nva,\n                  p_evl_sorted_virt.begin());\n\n        if(d_r.num_modes() == 2) {\n            auto ioff  = rtiss[0].tile_offset(blockid[0]);\n            auto joff  = rtiss[1].tile_offset(blockid[1]);\n            auto isize = rblock_dims[0];\n            auto jsize = rblock_dims[1];\n\n            if(!transpose) {\n                for(auto i = 0U, c = 0U; i < isize; i++) {\n                    for(auto j = 0U; j < jsize; j++, c++) {\n                        tbuf[c] =\n                          rbuf[c] / (-p_evl_sorted_virt[ioff + i] +\n                                     p_evl_sorted_occ[joff + j] + shift);\n                    }\n                }\n            } else {\n                for(auto i = 0U, c = 0U; i < isize; i++) {\n                    for(auto j = 0U; j < jsize; j++, c++) {\n                        tbuf[c] =\n                          rbuf[c] / (p_evl_sorted_occ[ioff + i] -\n                                     p_evl_sorted_virt[joff + j] + shift);\n                    }\n                }\n            }\n            d_t.add(blockid, tbuf);\n        } else if(d_r.num_modes() == 4) {\n            \n            auto rblock_offset = d_r.block_offsets(blockid);\n\n            std::vector<size_t> ioff;\n            for(auto x : rblock_offset) { ioff.push_back(x); }\n            std::vector<size_t> isize;\n            for(auto x : rblock_dims) { isize.push_back(x); }\n\n            if(!transpose) {\n                for(auto i0 = 0U, c = 0U; i0 < isize[0]; i0++) {\n                    for(auto i1 = 0U; i1 < isize[1]; i1++) {\n                        for(auto i2 = 0U; i2 < isize[2]; i2++) {\n                            for(auto i3 = 0U; i3 < isize[3]; i3++, c++) {\n                                tbuf[c] =\n                                  rbuf[c] /\n                                  (-p_evl_sorted_virt[ioff[0] + i0] -\n                                   p_evl_sorted_virt[ioff[1] + i1] +\n                                   p_evl_sorted_occ[ioff[2] + i2] +\n                                   p_evl_sorted_occ[ioff[3] + i3] + shift);\n                            }\n                        }\n                    }\n                }\n            } else {\n                for(auto i0 = 0U, c = 0U; i0 < isize[0]; i0++) {\n                    for(auto i1 = 0U; i1 < isize[1]; i1++) {\n                        for(auto i2 = 0U; i2 < isize[2]; i2++) {\n                            for(auto i3 = 0U; i3 < isize[3]; i3++, c++) {\n                                tbuf[c] =\n                                  rbuf[c] /\n                                  (p_evl_sorted_occ[ioff[0] + i0] +\n                                   p_evl_sorted_occ[ioff[1] + i1] -\n                                   p_evl_sorted_virt[ioff[2] + i2] -\n                                   p_evl_sorted_virt[ioff[3] + i3] + shift);\n                            }\n                        }\n                    }\n                }\n            }\n            d_t.add(blockid, tbuf);\n        } else {\n            assert(0); // @todo implement\n        }\n    });\n    // GA_Sync();\n}\n\ntemplate<typename T>\ninline void jacobi_eom(ExecutionContext& ec, LabeledTensor<T> d_r_lt, LabeledTensor<T> d_t_lt,\n                      T shift, bool transpose, std::vector<double>& evl_sorted, const TAMM_SIZE n_occ_alpha, const TAMM_SIZE n_occ_beta) {\n    // EXPECTS(transpose == false);\n     Tensor<T> d_r = d_r_lt.tensor();\n     Tensor<T> d_t = d_t_lt.tensor();\n\n    block_for(ec, d_r_lt, [&](IndexVector bid) {\n        IndexVector blockid   = internal::translate_blockid(bid, d_r_lt);\n\n        const TAMM_SIZE rsize = d_r.block_size(blockid);\n        std::vector<T> rbuf(rsize);\n        d_r.get(blockid, rbuf);\n\n        const TAMM_SIZE tsize = d_t.block_size(blockid);\n\n        std::vector<T> tbuf(tsize);\n\n        // auto& rtiss      = d_r.tiled_index_spaces();\n        auto rblock_dims = d_r.block_dims(blockid);\n        auto rblock_offset = d_r.block_offsets(blockid);\n\n        TAMM_SIZE noab = n_occ_alpha+n_occ_beta;\n        std::vector<double> p_evl_sorted_occ(noab);\n        std::vector<double> p_evl_sorted_virt(evl_sorted.size()-noab);\n        std::copy(evl_sorted.begin(), evl_sorted.begin() + noab,\n                  p_evl_sorted_occ.begin());\n        std::copy(evl_sorted.begin() + noab, evl_sorted.end(),\n                  p_evl_sorted_virt.begin());\n\n        if(d_r.num_modes() == 3) {\n\n            std::vector<size_t> ioff;\n            for(auto x : rblock_offset) { ioff.push_back(x); }\n            std::vector<size_t> isize;\n            for(auto x : rblock_dims) { isize.push_back(x); }\n\n            if(!transpose) {\n                for(auto i = 0U, c = 0U; i < isize[0]; i++) {\n                    for(auto j = 0U; j < isize[1]; j++, c++) {\n                        tbuf[c] =\n                          rbuf[c] / (-p_evl_sorted_virt[ioff[0] + i] +\n                                     p_evl_sorted_occ[ioff[1] + j] + shift);\n                    }\n                }\n            } else {\n                for(auto i = 0U, c = 0U; i < isize[0]; i++) {\n                    for(auto j = 0U; j < isize[1]; j++, c++) {\n                        tbuf[c] =\n                          rbuf[c] / (p_evl_sorted_occ[ioff[0] + i] -\n                                     p_evl_sorted_virt[ioff[1] + j] + shift);\n                    }\n                }\n            }\n            // auto last_id = rtiss[2].translate(blockid[2], d_t.tiled_index_spaces()[2]);\n            // blockid[2] = last_id;\n            d_t.add(blockid, tbuf);\n        } else if(d_r.num_modes() == 5) {\n            \n            std::vector<size_t> ioff;\n            for(auto x : rblock_offset) { ioff.push_back(x); }\n            std::vector<size_t> isize;\n            for(auto x : rblock_dims) { isize.push_back(x); }\n\n            if(!transpose) {\n                for(auto i0 = 0U, c = 0U; i0 < isize[0]; i0++) {\n                    for(auto i1 = 0U; i1 < isize[1]; i1++) {\n                        for(auto i2 = 0U; i2 < isize[2]; i2++) {\n                            for(auto i3 = 0U; i3 < isize[3]; i3++, c++) {\n                                tbuf[c] =\n                                  rbuf[c] /\n                                  (-p_evl_sorted_virt[ioff[0] + i0] -\n                                   p_evl_sorted_virt[ioff[1] + i1] +\n                                   p_evl_sorted_occ[ioff[2] + i2] +\n                                   p_evl_sorted_occ[ioff[3] + i3] + shift);\n                            }\n                        }\n                    }\n                }\n            } else {\n                for(auto i0 = 0U, c = 0U; i0 < isize[0]; i0++) {\n                    for(auto i1 = 0U; i1 < isize[1]; i1++) {\n                        for(auto i2 = 0U; i2 < isize[2]; i2++) {\n                            for(auto i3 = 0U; i3 < isize[3]; i3++, c++) {\n                                tbuf[c] =\n                                  rbuf[c] /\n                                  (p_evl_sorted_occ[ioff[0] + i0] +\n                                   p_evl_sorted_occ[ioff[1] + i1] -\n                                   p_evl_sorted_virt[ioff[2] + i2] -\n                                   p_evl_sorted_virt[ioff[3] + i3] + shift);\n                            }\n                        }\n                    }\n                }\n            }\n            // auto last_id = rtiss[4].translate(blockid[4], d_t.tiled_index_spaces()[4]);\n            // blockid[4] = last_id;\n            d_t.add(blockid, tbuf);\n        } else {\n            assert(0); // @todo implement\n        }\n    });\n    // GA_Sync();\n}\n\n/**\n * @brief dot product between data held in two labeled tensors. Corresponding\n * elements are multiplied.\n *\n * This routine ignores permutation symmetry, and associated symmetrizatin\n * factors\n *\n * @tparam T Type of elements in both tensors\n * @param ec Execution context in which this function is invoked\n * @param lta Labeled tensor A\n * @param ltb labeled Tensor B\n * @return dot product A . B\n */\ntemplate<typename T>\ninline T ddot(ExecutionContext& ec, LabeledTensor<T> lta,\n              LabeledTensor<T> ltb) {\n    T ret = 0;\n    block_for(ec.pg(), lta, [&](IndexVector blockid) {\n        Tensor<T> atensor     = lta.tensor();\n        const TAMM_SIZE asize = atensor.block_size(blockid);\n        std::vector<T> abuf(asize);\n\n        Tensor<T> btensor     = ltb.tensor();\n        const TAMM_SIZE bsize = btensor.block_size(blockid);\n        std::vector<T> bbuf(bsize);\n\n        const size_t sz = asize;\n        for(size_t i = 0; i < sz; i++) { ret += abuf[i] * bbuf[i]; }\n    });\n    return ret;\n}\n\n/**\n * @brief DIIS routine\n * @tparam T Type of element in each tensor\n * @param ec Execution context in which this function invoked\n * @param[in] d_rs Vector of R tensors\n * @param[in] d_ts Vector of T tensors\n * @param[out] d_t Vector of T tensors produced by DIIS\n * @pre d_rs.size() == d_ts.size()\n * @pre 0<=i<d_rs.size(): d_rs[i].size() == d_t.size()\n * @pre 0<=i<d_ts.size(): d_ts[i].size() == d_t.size()\n */\ntemplate<typename T>\ninline void diis(ExecutionContext& ec,\n                 std::vector<std::vector<Tensor<T>>>& d_rs,\n                 std::vector<std::vector<Tensor<T>>>& d_ts,\n                 std::vector<Tensor<T>> d_t) {\n\n    EXPECTS(d_t.size() == d_rs.size());\n    size_t ntensors = d_t.size();\n    EXPECTS(ntensors > 0);\n    size_t ndiis = d_rs[0].size();\n    EXPECTS(ndiis > 0);\n    for(auto i = 0U; i < ntensors; i++) { EXPECTS(d_rs[i].size() == ndiis); }\n\n    using Matrix =\n      Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>;\n    using Vector =\n      Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>;\n    Matrix A = Matrix::Zero(ndiis + 1, ndiis + 1);\n    Vector b = Vector::Zero(ndiis + 1, 1);\n    for(auto k = 0U; k < ntensors; k++) {\n        for(auto i = 0U; i < ndiis; i++) {\n            for(auto j = i; j < ndiis; j++) {\n                Tensor<T> d_r1{};\n                Tensor<T>::allocate(&ec,d_r1);\n                Tensor<T>& t1 = d_rs[k].at(i);\n                Tensor<T>& t2 = d_rs[k].at(j);\n                //A(i, j) += ddot(ec, (*d_rs[k]->at(i))(), (*d_rs[k]->at(j))());                \n                Scheduler{ec}(d_r1() = t1() * t2()).execute();\n\n                A(i,j) += get_scalar(d_r1);\n                Tensor<T>::deallocate(d_r1);\n            }\n        }\n    }\n\n    for(auto i = 0U; i < ndiis; i++) {\n        for(auto j = i; j < ndiis; j++) { A(j, i) = A(i, j); }\n    }\n    for(auto i = 0U; i < ndiis; i++) {\n        A(i, ndiis) = -1.0;\n        A(ndiis, i) = -1.0;\n    }\n\n    b(ndiis, 0) = -1;\n\n    // Solve AX = B\n    // call dgesv(diis+1,1,a,maxdiis+1,iwork,b,maxdiis+1,info)\n    // Vector x = A.colPivHouseholderQr().solve(b);\n    Vector x = A.lu().solve(b);\n\n    auto sch = Scheduler{ec};\n    for(auto k = 0U; k < ntensors; k++) {\n        Tensor<T>& dt = d_t[k];\n        sch(dt() = 0);\n        for(auto j = 0U; j < ndiis; j++) {\n            auto& tb = d_ts[k].at(j);\n            sch(dt() += x(j, 0) * tb());\n        }\n    }\n    // GA_Sync();\n    sch.execute();\n    // GA_Sync();\n}\n\n} // namespace tamm\n", "meta": {"hexsha": "3a420cb72ab269f3b164ec13e36c563cbadb5b7c", "size": 16479, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/gfcc/contrib/diis.hpp", "max_stars_repo_name": "ltalirz/gfcc", "max_stars_repo_head_hexsha": "4fe9e677383e2d5626428d8e535d7f92807523b7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/gfcc/contrib/diis.hpp", "max_issues_repo_name": "ltalirz/gfcc", "max_issues_repo_head_hexsha": "4fe9e677383e2d5626428d8e535d7f92807523b7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/gfcc/contrib/diis.hpp", "max_forks_repo_name": "ltalirz/gfcc", "max_forks_repo_head_hexsha": "4fe9e677383e2d5626428d8e535d7f92807523b7", "max_forks_repo_licenses": ["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.9574468085, "max_line_length": 138, "alphanum_fraction": 0.4408641301, "num_tokens": 4435, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6893056040203135, "lm_q2_score": 0.43782349911420193, "lm_q1q2_score": 0.3017941915112021}}
{"text": "///////////////////////////////////////////////////////////////////////////////\n// weighted_tail_mean.hpp\n//\n//  Copyright 2006 Daniel Egloff, Olivier Gygi. Distributed under the Boost\n//  Software License, Version 1.0. (See accompanying file\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n#ifndef BOOST_ACCUMULATORS_STATISTICS_WEIGHTED_TAIL_MEAN_HPP_DE_01_01_2006\n#define BOOST_ACCUMULATORS_STATISTICS_WEIGHTED_TAIL_MEAN_HPP_DE_01_01_2006\n\n#include <numeric>\n#include <vector>\n#include <limits>\n#include <functional>\n#include <sstream>\n#include <stdexcept>\n#include <boost/throw_exception.hpp>\n#include <boost/parameter/keyword.hpp>\n#include <boost/mpl/placeholders.hpp>\n#include <boost/type_traits/is_same.hpp>\n#include <boost/accumulators/numeric/functional.hpp>\n#include <boost/accumulators/framework/accumulator_base.hpp>\n#include <boost/accumulators/framework/extractor.hpp>\n#include <boost/accumulators/framework/parameters/sample.hpp>\n#include <boost/accumulators/statistics_fwd.hpp>\n#include <boost/accumulators/statistics/tail.hpp>\n#include <boost/accumulators/statistics/tail_mean.hpp>\n#include <boost/accumulators/statistics/parameters/quantile_probability.hpp>\n\n#ifdef _MSC_VER\n# pragma warning(push)\n# pragma warning(disable: 4127) // conditional expression is constant\n#endif\n\nnamespace boost { namespace accumulators\n{\n\nnamespace impl\n{\n\n    ///////////////////////////////////////////////////////////////////////////////\n    // coherent_weighted_tail_mean_impl\n    //\n    // TODO\n\n    ///////////////////////////////////////////////////////////////////////////////\n    // non_coherent_weighted_tail_mean_impl\n    //\n    /**\n        @brief Estimation of the (non-coherent) weighted tail mean based on order statistics (for both left and right tails)\n\n\n\n        An estimation of the non-coherent, weighted tail mean \\f$\\widehat{NCTM}_{n,\\alpha}(X)\\f$ is given by the weighted mean\n        of the\n\n        \\f[\n            \\lambda = \\inf\\left\\{ l \\left| \\frac{1}{\\bar{w}_n}\\sum_{i=1}^{l} w_i \\geq \\alpha \\right. \\right\\}\n        \\f]\n\n        smallest samples (left tail) or the weighted mean of the\n\n        \\f[\n            n + 1 - \\rho = n + 1 - \\sup\\left\\{ r \\left| \\frac{1}{\\bar{w}_n}\\sum_{i=r}^{n} w_i \\geq (1 - \\alpha) \\right. \\right\\}\n        \\f]\n\n        largest samples (right tail) above a quantile \\f$\\hat{q}_{\\alpha}\\f$ of level \\f$\\alpha\\f$, \\f$n\\f$ being the total number of sample\n        and \\f$\\bar{w}_n\\f$ the sum of all \\f$n\\f$ weights:\n\n        \\f[\n            \\widehat{NCTM}_{n,\\alpha}^{\\mathrm{left}}(X) = \\frac{\\sum_{i=1}^{\\lambda} w_i X_{i:n}}{\\sum_{i=1}^{\\lambda} w_i},\n        \\f]\n\n        \\f[\n            \\widehat{NCTM}_{n,\\alpha}^{\\mathrm{right}}(X) = \\frac{\\sum_{i=\\rho}^n w_i X_{i:n}}{\\sum_{i=\\rho}^n w_i}.\n        \\f]\n\n        @param quantile_probability\n    */\n    template<typename Sample, typename Weight, typename LeftRight>\n    struct non_coherent_weighted_tail_mean_impl\n      : accumulator_base\n    {\n        typedef typename numeric::functional::multiplies<Sample, Weight>::result_type weighted_sample;\n        typedef typename numeric::functional::fdiv<Weight, std::size_t>::result_type float_type;\n        // for boost::result_of\n        typedef typename numeric::functional::fdiv<weighted_sample, std::size_t>::result_type result_type;\n\n        non_coherent_weighted_tail_mean_impl(dont_care) {}\n\n        template<typename Args>\n        result_type result(Args const &args) const\n        {\n            float_type threshold = sum_of_weights(args)\n                             * ( ( is_same<LeftRight, left>::value ) ? args[quantile_probability] : 1. - args[quantile_probability] );\n\n            std::size_t n = 0;\n            Weight sum = Weight(0);\n\n            while (sum < threshold)\n            {\n                if (n < static_cast<std::size_t>(tail_weights(args).size()))\n                {\n                    sum += *(tail_weights(args).begin() + n);\n                    n++;\n                }\n                else\n                {\n                    if (std::numeric_limits<result_type>::has_quiet_NaN)\n                    {\n                        return std::numeric_limits<result_type>::quiet_NaN();\n                    }\n                    else\n                    {\n                        std::ostringstream msg;\n                        msg << \"index n = \" << n << \" is not in valid range [0, \" << tail(args).size() << \")\";\n                        boost::throw_exception(std::runtime_error(msg.str()));\n                        return result_type(0);\n                    }\n                }\n            }\n\n            return numeric::fdiv(\n                std::inner_product(\n                    tail(args).begin()\n                  , tail(args).begin() + n\n                  , tail_weights(args).begin()\n                  , weighted_sample(0)\n                )\n              , sum\n            );\n        }\n    };\n\n} // namespace impl\n\n\n///////////////////////////////////////////////////////////////////////////////\n// tag::non_coherent_weighted_tail_mean<>\n//\nnamespace tag\n{\n    template<typename LeftRight>\n    struct non_coherent_weighted_tail_mean\n      : depends_on<sum_of_weights, tail_weights<LeftRight> >\n    {\n        typedef accumulators::impl::non_coherent_weighted_tail_mean_impl<mpl::_1, mpl::_2, LeftRight> impl;\n    };\n}\n\n///////////////////////////////////////////////////////////////////////////////\n// extract::non_coherent_weighted_tail_mean;\n//\nnamespace extract\n{\n    extractor<tag::abstract_non_coherent_tail_mean> const non_coherent_weighted_tail_mean = {};\n\n    BOOST_ACCUMULATORS_IGNORE_GLOBAL(non_coherent_weighted_tail_mean)\n}\n\nusing extract::non_coherent_weighted_tail_mean;\n\n}} // namespace boost::accumulators\n\n#ifdef _MSC_VER\n# pragma warning(pop)\n#endif\n\n#endif\n", "meta": {"hexsha": "bae8530674ebbdc34352a7c0c37ac2bfb1ef4d4a", "size": 5788, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ReactNativeFrontend/ios/Pods/boost/boost/accumulators/statistics/weighted_tail_mean.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/accumulators/statistics/weighted_tail_mean.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/accumulators/statistics/weighted_tail_mean.hpp", "max_forks_repo_name": "c7yrus/alyson-v3", "max_forks_repo_head_hexsha": "5ad95a8f782f5f5d2fd543d44ca6a8b093395965", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1343.0, "max_forks_repo_forks_event_min_datetime": "2017-12-08T19:47:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-26T11:31:36.000Z", "avg_line_length": 34.0470588235, "max_line_length": 140, "alphanum_fraction": 0.5725639254, "num_tokens": 1340, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.665410558746814, "lm_q2_score": 0.4532618480153861, "lm_q1q2_score": 0.3016052195465315}}
{"text": "#ifndef SODES_BOOSTODEINT_HPP\n#define SODES_BOOSTODEINT_HPP\n\n#include <Eigen/Core>\n#include <boost/numeric/odeint.hpp>\n#include <boost/numeric/odeint/algebra/vector_space_algebra.hpp>\n#include <boost/numeric/odeint/external/eigen/eigen_resize.hpp>\n\n#include <tuple>\n#include <functional>\n#include <vector>\n#include <utility>\n#include <stdexcept>\n\n#include \"math_types.hpp\"\n\nnamespace sodes::detail::odeint {\n\nusing namespace boost::numeric::odeint;\nusing namespace Eigen;\nusing namespace std;\n\nusing namespace sodes::math_types;\n\ntypedef eigen_array_1d state_type;\n\nstruct Observer\n{\n    vector<state_type>& m_states;\n    vector<double>& m_times;\n\n    Observer(vector<state_type>& states, vector<double>& times)\n        : m_states(states), m_times(times) {}\n\n    void operator()(const state_type& x, const double& t)\n    {\n        m_states.push_back(x);\n        m_times.push_back(t);\n    }\n};\n\ntemplate<typename Stepper>\npair<vector<double>, vector<state_type>> _integrate_const_stepper(\n    const function<state_type(eigen_array_1d_constref, eigen_array_1d_ref, const double&)>& f,\n    const tuple<double, double>& t_span,\n    const double& dt,\n    state_type& y0,\n    Stepper stepper)\n{\n    // Containers to store solution\n    vector<state_type> states;\n    vector<double> times;\n\n    // Integrate over time\n    auto[t_init, t_final] = t_span;\n    auto observer = Observer(states, times);\n    integrate_const(\n        stepper,\n        f,\n        y0,\n        t_init,\n        t_final,\n        dt,\n        observer);\n\n    auto solution_pair = make_pair(times, states);\n\n    return solution_pair;\n}\n}  // namespace sodes::detail::odeint\n\nnamespace sodes::odeint {\n\nusing namespace std;\nusing namespace Eigen;\nusing namespace sodes::math_types;\n\npair<vector<double>, vector<ArrayXd>> solve_ivp_const(\n    const function<ArrayXd(eigen_array_1d_constref, eigen_array_1d_ref, const double&)>& f,\n    const tuple<double, double>& t_span,\n    const double& dt,\n    ArrayXd& y0,\n    const string& method = \"runge_kutta4\")\n{\n    using namespace sodes::detail::odeint;\n\n    if (method == \"runge_kutta4\") {\n        typedef runge_kutta4<state_type, double, state_type, double, vector_space_algebra> stepper;\n        return _integrate_const_stepper<stepper>(f, t_span, dt, y0, stepper());\n    }\n//    else if (method == \"runge_kutta_dopri5\") {\n//        typedef runge_kutta_dopri5<state_type, double, state_type, double, vector_space_algebra> stepper;\n//        auto dense_output = make_dense_output<stepper>(1e-6, 1e-6);\n//        return _integrate_const_stepper<dense_output>(f, t_span, dt, y0, dense_output);\n//    }\n    else if (method == \"runge_kutta_cash_karp54\") {\n        typedef runge_kutta_cash_karp54<state_type, double, state_type, double, vector_space_algebra> stepper;\n        return _integrate_const_stepper<stepper>(f, t_span, dt, y0, stepper());\n    }\n    else if (method == \"runge_kutta_fehlberg78\") {\n        typedef runge_kutta_fehlberg78<state_type, double, state_type, double, vector_space_algebra> stepper;\n        return _integrate_const_stepper<stepper>(f, t_span, dt, y0, stepper());\n    }\n    else if (method == \"modified_midpoint\") {\n        typedef modified_midpoint<state_type, double, state_type, double, vector_space_algebra> stepper;\n        return _integrate_const_stepper<stepper>(f, t_span, dt, y0, stepper());\n    }\n    else if (method == \"euler\") {\n        typedef euler<state_type, double, state_type, double, vector_space_algebra> stepper;\n        return _integrate_const_stepper<stepper>(f, t_span, dt, y0, stepper());\n    }\n    else {\n        throw invalid_argument(\"Unavailable integration method from Boost::odeint\");\n    }\n}\n}  // namespace sodes::odeint\n\n#endif //SODES_BOOSTODEINT_HPP\n", "meta": {"hexsha": "70ae66dd17e6d5fc7d2f51c3ac9dec9abe047609", "size": 3718, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/sodes/odeint/BoostOdeint.hpp", "max_stars_repo_name": "volpatto/pysodes", "max_stars_repo_head_hexsha": "48add3ce16ee48e2f3af7a928935f9b22d74d908", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-11-16T08:28:51.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-09T07:29:11.000Z", "max_issues_repo_path": "src/sodes/odeint/BoostOdeint.hpp", "max_issues_repo_name": "volpatto/pysodes", "max_issues_repo_head_hexsha": "48add3ce16ee48e2f3af7a928935f9b22d74d908", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/sodes/odeint/BoostOdeint.hpp", "max_forks_repo_name": "volpatto/pysodes", "max_forks_repo_head_hexsha": "48add3ce16ee48e2f3af7a928935f9b22d74d908", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-03-09T07:29:15.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-09T07:29:15.000Z", "avg_line_length": 31.243697479, "max_line_length": 110, "alphanum_fraction": 0.7030661646, "num_tokens": 979, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6224593312018546, "lm_q2_score": 0.48438008427698437, "lm_q1q2_score": 0.30150690330654967}}
{"text": "/*\n * ThreephaseEngine.cpp\n *\n * Copyright (c) 2014, Alessandro Pezzato\n */\n\n#include \"ThreephaseEngine.h\"\n#include \"../../common/Logger.h\"\n#include \"../../common/Config.h\"\n#include \"../../projector/Projector.h\"\n#include \"../../input/ImageInput.h\"\n\n#include <format.h>\n#include <opencv2/highgui/highgui.hpp>\n#include <opencv2/opencv.hpp>\n#include <opencv2/core/core.hpp>\n#include <opencv2/highgui/highgui.hpp>\n#include <glm/gtx/transform.hpp>\n#include <glm/gtc/type_ptr.hpp>\n#include <glm/gtc/matrix_transform.hpp>\n#include <boost/foreach.hpp>\n#include <boost/algorithm/string.hpp>\n\n/*\n * http://public.vrac.iastate.edu/~song/publications/papers/2010-ole-review.pdf\n */\n\nnamespace threescanner {\n\nnamespace /* anonymous */{\n\nstatic const int WRAP_V_SIZE = 511; /* i1 - i3, -255 to 255, |511| */\nstatic const int WRAP_U_SIZE = 1021; /* 2 * i2 - i1 - i3, -510 to 510, |1021| */\nstatic const int WRAP_V_OFFSET = 255; /* min value is -255 */\nstatic const int WRAP_U_OFFSET = 510; /* min value is -510 */\nstatic unsigned char PHASE_GAMMA_LUT[WRAP_V_SIZE][WRAP_U_SIZE][2];\n\n/*\n * initPhaseGammaLut() is automatically called once at startup\n */\nvoid initPhaseGammaLut() __attribute__ ((constructor)); /* FIXME: only gcc is compatible */\nvoid initPhaseGammaLut() {\n\tfloat sqrt3 = sqrtf(3.0);\n\tfloat ipi = float(128. / CV_PI);\n\tfor (int vo = 0; vo < WRAP_V_SIZE; vo++) {\n\t\tfor (int uo = 0; uo < WRAP_U_SIZE; uo++) {\n\t\t\tfloat v = float(vo - WRAP_V_OFFSET);\n\t\t\tfloat u = float(uo - WRAP_U_OFFSET);\n\t\t\tfloat phase = atan2f(sqrt3 * v, u) * ipi;\n\t\t\tfloat modulation = sqrtf(3 * v * v + u * u);\n\t\t\tPHASE_GAMMA_LUT[vo][uo][0] = 128 + (unsigned char) phase;\n\t\t\tPHASE_GAMMA_LUT[vo][uo][1] = modulation > 255 ? 255 : (unsigned char) modulation;\n\t\t}\n\t}\n}\n\nbool isVertical(const std::string& orientation) {\n\treturn orientation[0] == 'v' || orientation[0] == 'V';\n}\n\nbool isHorizontal(const std::string& orientation) {\n\treturn orientation[0] == 'h' || orientation[0] == 'H';\n}\n\nvoid traceMatrix(const std::string& name, const glm::mat4& mat) {\n\tconst float* a = (const float*) glm::value_ptr(mat);\n\tlogDebug(\"%16s | %8.3f %8.3f %8.3f %8.3f\", name.c_str(), a[0], a[4], a[8], a[12]);\n\tlogDebug(\"                 | %8.3f %8.3f %8.3f %8.3f\", a[1], a[5], a[9], a[13]);\n\tlogDebug(\"                 | %8.3f %8.3f %8.3f %8.3f\", a[2], a[6], a[10], a[14]);\n\tlogDebug(\"                 | %8.3f %8.3f %8.3f %8.3f\", a[3], a[7], a[11], a[15]);\n}\n\n} /* namespace anonymous */\n\nThreephaseEngine::ThreephaseEngine(const Config& cfg) :\n\t\t\t\tEngine(cfg),\n\t\t\t\twrapMethod_(cfg.get<int>(\"wrapMethod\")),\n\t\t\t\toptions_(),\n\t\t\t\ttoProcess_(),\n\t\t\t\thImages_ { },\n\t\t\t\tvImages_ { },\n\t\t\t\tphases_(hImages_),\n\t\t\t\tprocess_(),\n\t\t\t\tunwrapped_(),\n\t\t\t\tmask_(),\n\t\t\t\tdepth_() {\n\t/* tuning */\n\tConfig tuning = cfg.getChild(\"tuning\");\n\n\toptions_[\"mscale\"] = tuning.get<float>(\"mscale\", 200.0);\n\toptions_[\"zscale\"] = tuning.get<float>(\"zscale\", 151.0);\n\toptions_[\"zskew\"] = tuning.get<float>(\"zskew\", 180.0);\n\toptions_[\"znoise\"] = tuning.get<float>(\"znoise\", 0.720);\n\toptions_[\"zblur\"] = tuning.get<float>(\"zblur\", 16);\n\toptions_[\"cloudScale\"] = tuning.get<float>(\"cloudScale\", 1.0);\n\n}\n\nThreephaseEngine::~ThreephaseEngine() {\n\n}\n\nvoid ThreephaseEngine::scanSync() {\n\t/* TODO:\n\t * should get images from ImageInput (Camera)\n\t */\n\tif (projector_.get() == nullptr) {\n\t\tthrow std::runtime_error(\"Cannot scan without a valid projector\");\n\t}\n\tif (input_.get() == nullptr) {\n\t\tthrow std::runtime_error(\"Cannot scan without a valid image input\");\n\t}\n\tlogDebug(\"Wait until ready\");\n\tprojector_->waitUntilReady();\n\tlogDebug(\"ready\");\n\tstd::string orientation = \"h\"; /* TODO: from Config */\n\tprojector_->setParameter(\"orientation\", orientation);\n\tfor (int phase = 1; phase <= 3; ++phase) {\n\t\tlogDebug(\"Scan phase %i\", phase);\n\t\tthis->projector_->setParameter(\"phase\", fmt::sprintf(\"%i\", phase));\n\t\tstd::this_thread::sleep_for(std::chrono::milliseconds(250));\n\t\tImagePtr image = input_->grabImage();\n\t\tthis->setImage(fmt::sprintf(\"%s:%i\", orientation, phase), *image);\n\t}\n\tthis->process(orientation);\n}\n\nvoid ThreephaseEngine::setImage(const std::string& orientation, const size_t& phase, const cv::Mat& image) {\n\tif (phase > 3) {\n\t\tthrow std::runtime_error(fmt::sprintf(\"Threephase invalid phase: %u\", phase));\n\t}\n\tcv::Mat* phases = isVertical(orientation) ? vImages_ : hImages_;\n\tcv::Mat& dst = phases[phase - 1];\n\tcv::cvtColor(image, dst, CV_RGB2GRAY);\n\tlogDebug(\"Threephase set image %u\", phase);\n}\n\nvoid ThreephaseEngine::process(const std::string& orientation) {\n\tif (isVertical(orientation)) {\n\t\tphases_ = vImages_;\n\t} else if (isHorizontal(orientation)) {\n\t\tphases_ = hImages_;\n\t} else if (orientation == \"last\" && phases_ == nullptr) {\n\t\tthrow std::runtime_error(\"Last orientation is undefined\");\n\t} else {\n\t\tthrow std::runtime_error(\"Invalid orientation\");\n\t}\n\tif (!phases_[0].rows || !phases_[1].rows || !phases_[2].rows) {\n\t\tlogWarning(\"Cannot process empty images\");\n\t\treturn;\n\t}\n\tconst int znoise = options_[\"znoise\"];\n\tconst float zscale = options_[\"zscale\"];\n\tconst float mscale = options_[\"mscale\"];\n\tconst float zskew = options_[\"zskew\"];\n\tthis->setup();\n\tthis->wrap(znoise);\n\tthis->unwrap();\n\tthis->blurMask();\n\tthis->computeDepth(zscale - mscale, zskew - mscale);\n\tthis->createCloud();\n}\n\nvoid ThreephaseEngine::blurMask() {\n\tconst int zblur = options_[\"zblur\"];\n\tif (zblur) {\n\t\tcv::blur(mask_, mask_, cv::Size(zblur, zblur));\n\t}\n}\n\nvoid ThreephaseEngine::unwrap() {\n\tint width = phases_[0].cols;\n\tint height = phases_[0].rows;\n\tint startX = width / 2;\n\tint startY = height / 2;\n\n\ttoProcess_.clear();\n\n\ttoProcess_.push_back(cv::Point(startX, startY));\n\tprocess_.at<uchar>(startY, startX) = false;\n\n\twhile (!toProcess_.empty()) {\n\t\tcv::Point p = toProcess_.back();\n\t\ttoProcess_.pop_back();\n\n\t\tint x = p.x;\n\t\tint y = p.y;\n\t\tfloat r = unwrapped_.at<float>(y, x);\n\t\tif (y > 0) {\n\t\t\tthis->unwrap(r, x, y - 1);\n\t\t}\n\t\tif (y < height - 2) {\n\t\t\tthis->unwrap(r, x, y + 1);\n\t\t}\n\t\tif (x > 0) {\n\t\t\tthis->unwrap(r, x - 1, y);\n\t\t}\n\t\tif (x < width - 2) {\n\t\t\tthis->unwrap(r, x + 1, y);\n\t\t}\n\t}\n\ttoProcess_.clear();\n}\n\nvoid ThreephaseEngine::unwrap(float basePhase, int x, int y) {\n\tconst int idx = x + y * process_.cols;\n\tfloat* unwrappedBuffer = reinterpret_cast<float*>(unwrapped_.data);\n\tconst float bfquo = basePhase - round(basePhase);\n\tif (process_.data[idx]) {\n\t\tfloat& p0 = unwrappedBuffer[idx];\n\t\tfloat diff = p0 - bfquo;\n\t\tif (diff > 0.5f) {\n\t\t\tdiff -= 1.0;\n\t\t} else if (diff < -0.5f) {\n\t\t\tdiff += 1.0;\n\t\t}\n\t\tp0 = basePhase + diff;\n\t\tprocess_.data[idx] = 0;\n\t\ttoProcess_.push_back(cv::Point(x, y));\n\t}\n}\n\nvoid ThreephaseEngine::wrap(float noiseThreshold) {\n\tint width = process_.cols;\n\tint height = process_.rows;\n\n\tfor (int y = 0; y < height; y++) {\n\t\tfor (int x = 0; x < width; x++) {\n\t\t\tconst int i = x + y * width;\n\t\t\tconst int lum0 = phases_[0].data[i];\n\t\t\tconst int lum1 = phases_[1].data[i];\n\t\t\tconst int lum2 = phases_[2].data[i];\n\t\t\tconst int v = lum0 - lum2;\n\t\t\tconst int u = 2 * lum1 - lum0 - lum2;\n\t\t\tconst unsigned char* const cur = PHASE_GAMMA_LUT[v + WRAP_V_OFFSET][u + WRAP_U_OFFSET];\n\t\t\tmask_.data[i] = (cur[1] < noiseThreshold * 64);\n\n\t\t\tprocess_.data[i] = !mask_.data[i];\n\t\t\tstatic const float SQRT3 = sqrtf(3.0);\n\t\t\tstatic const float TWO_PI = 6.283185;\n\n\t\t\tfloat p2;\n\t\t\tswitch (wrapMethod_) {\n\t\t\tcase 0:\n\t\t\t\tp2 = atan2(SQRT3 * (lum0 - lum2), 2.0f * lum1 - lum0 - lum2) / TWO_PI;\n\t\t\t\tbreak;\n\t\t\tcase 1:\n\t\t\t\tp2 = (cur[0] - 128.0f) / 255.0f;\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tlogWarning(\"calibration.json engine.wrapMethod can be 0 or 1\");\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tfloat* unwrappedBuffer = reinterpret_cast<float*>(unwrapped_.data);\n\t\t\tunwrappedBuffer[i] = p2;\n\t\t}\n\t}\n}\n\nvoid ThreephaseEngine::computeDepth(float zscale, float zskew) {\n\tfloat* unwrappedBuffer = reinterpret_cast<float*>(unwrapped_.data);\n\tfloat* depthBuffer = reinterpret_cast<float*>(depth_.data);\n\n\tfor (int i = 0; i < unwrapped_.rows; ++i) {\n\t\tfloat planephase = float(i - unwrapped_.rows / 2);\n\t\tif (zskew) {\n\t\t\tplanephase /= zskew;\n\t\t}\n\t\tplanephase += 0.5f;\n\t\tfor (int j = 0; j < unwrapped_.cols; ++j) {\n\t\t\tint ii = i * unwrapped_.cols + j;\n\t\t\tdepthBuffer[ii] = mask_.data[ii] ? 0.0f : ((unwrappedBuffer[ii] - planephase) * zscale);\n\t\t}\n\t}\n}\n\nvoid ThreephaseEngine::setup() {\n\tint w = phases_[0].cols;\n\tint h = phases_[0].rows;\n\tlogDebug(\"Threephase setup %ux%u\", w, h);\n\tunwrapped_ = cv::Mat::zeros(h, w, CV_32F);\n\tdepth_ = cv::Mat::zeros(h, w, CV_32F);\n\tmask_ = cv::Mat::zeros(h, w, CV_8U);\n\tprocess_ = cv::Mat::zeros(h, w, CV_8U);\n}\n\nvoid ThreephaseEngine::createCloud() {\n\tlogDebug(\"Save to cloud\");\n\t/*\n\t * TODO: controlla che il risultato sia corretto prima di salvare la point cloud.\n\t * A volte (causa delay telecamera) le immagini catturate non sono valide.\n\t * Un'opzione per controllare se e` valido e` vedere se il numero di punti\n\t * rispetta una soglia minima aspettata.\n\t */\n\tconst float zscale = options_[\"zscale\"];\n\tconst float mscale = options_[\"mscale\"];\n\tconst float zskew = options_[\"zskew\"];\n\tconst float scale = zscale - mscale;\n\tfloat skew = zskew - mscale;\n\tif (skew == 0.0) {\n\t\tskew = 1.0;\n\t}\n\tint width = depth_.cols;\n\tint height = depth_.rows;\n\n\tstruct RawPoint {\n\t\tfloat x, y, z;\n\t};\n\n\tPointCloud& cloud = *cloud_;\n\t/*\n\t * TODO: need optimization. cloud_ memory can be reserved in\n\t * initialization, then only size change. But how? std::vector\n\t * do not permit to change size without deallocating.\n\t */\n\tcloud.clear();\n\n\tfor (int y = 0; y < height; ++y) {\n\t\tfloat planephase = 0.5 + float(y - (height / 2)) / skew;\n\t\tfor (int x = 0; x < width; ++x) {\n\t\t\tif (!mask_.at<uchar>(y, x)) {\n\t\t\t\tfloat z = (unwrapped_.at<float>(y, x) - planephase) * scale;\n\t\t\t\tPoint p;\n\t\t\t\tp.x = x;\n\t\t\t\tp.y = y;\n\t\t\t\tp.z = z;\n\t\t\t\tp.r = 0xff;\n\t\t\t\tp.g = 0xff;\n\t\t\t\tp.b = 0xff;\n\t\t\t\tcloud.push_back(p);\n\t\t\t}\n\t\t}\n\t}\n\n\tlogDebug(\"Points: %u\", cloud.size());\n}\n\nvoid ThreephaseEngine::setOption(const std::string& key, const float& value) {\n\tif (!options_.count(key)) {\n\t\tthrow std::invalid_argument(\"Threephase option does not exist: \" + key);\n\t}\n\toptions_[key] = value;\n}\n\nvoid ThreephaseEngine::setParameter(const std::string& key, const std::string& value) {\n\tstd::vector<std::string> k;\n\tboost::split(k, key, boost::is_any_of(\":\"));\n\tif (k[0] == \"tuning\" && k.size() == 2) {\n\t\treturn this->setOption(k[1], boost::lexical_cast<float>(value));\n\t}\n\tthrow std::invalid_argument(\"Threephase invalid parameter: \" + key);\n}\n\nvoid ThreephaseEngine::setImage(const std::string& id, const cv::Mat& image) {\n\tstd::vector<std::string> params;\n\tboost::split(params, id, boost::is_any_of(\":\"));\n\tauto orientation = params[0];\n\tauto phase = boost::lexical_cast<size_t>(params[1]);\n\tthis->setImage(orientation, phase, image);\n}\n\n} /* namespace threescanner */\n", "meta": {"hexsha": "a811aa9ebf1b19234f97bbcf1b2d920ef6cd21ce", "size": 10656, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/lib/scanner/threephase/ThreephaseEngine.cpp", "max_stars_repo_name": "alepez/threescanner", "max_stars_repo_head_hexsha": "7fe03ecde0c7f18c4059f42a69c59e56e854c7f2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 12.0, "max_stars_repo_stars_event_min_datetime": "2016-01-18T14:50:04.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-05T09:12:26.000Z", "max_issues_repo_path": "src/lib/scanner/threephase/ThreephaseEngine.cpp", "max_issues_repo_name": "lazytiger/threescanner", "max_issues_repo_head_hexsha": "7fe03ecde0c7f18c4059f42a69c59e56e854c7f2", "max_issues_repo_licenses": ["MIT"], "max_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/scanner/threephase/ThreephaseEngine.cpp", "max_forks_repo_name": "lazytiger/threescanner", "max_forks_repo_head_hexsha": "7fe03ecde0c7f18c4059f42a69c59e56e854c7f2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2016-07-07T07:30:54.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-26T19:18:49.000Z", "avg_line_length": 29.3553719008, "max_line_length": 108, "alphanum_fraction": 0.6438626126, "num_tokens": 3431, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6224593171945417, "lm_q2_score": 0.4843800842769844, "lm_q1q2_score": 0.30150689652168633}}
{"text": "#include \"types.hh\"\n#include \"tcrdist.hh\"\n#include \"io.hh\"\n#include <random>\n#include <boost/math/distributions/hypergeometric.hpp>\n\nSize const MIN_FG_COUNT(5);\nReal const MIN_CORE_ENRICH(1.05);\nReal const MIN_PAIR_ENRICH(1.5);\nReal const MIN_TRIPLE_ENRICH(2.0);\nReal const MAX_CORE_PVAL_ADJ(100.);\nReal const MAX_PAIR_PVAL_ADJ(1.);\nReal const MAX_TRIPLE_PVAL_ADJ(1.);\nReal const MAX_FINAL_PVAL_ADJ(1.);\nReal const MAX_JACCARD(0.7);\nSize const NUM_CORE_AAS(26); // 'A'-'Z'\nSize const NUM_CORE_GAPS(3); // 0,1,2\n\nSize const NUM_CORES(\n\tNUM_CORE_AAS*NUM_CORE_AAS*NUM_CORE_AAS*NUM_CORE_GAPS*NUM_CORE_GAPS);\n\nReal const PSEUDOCOUNT(0.25);\n\ntypedef vector< char > chars;\n\ninline\nSize\nget_core_index(\n\tchar const aa1, // 'A' - 'Z'\n\tSize const gap1, // 0-2\n\tchar const aa2, // 'A' - 'Z'\n\tSize const gap2, // 0-2\n\tchar const aa3  // 'A' - 'Z'\n)\n{\n\t// 26 * 3 * 26 * 3 * 26\n\treturn  (\n\t\tNUM_CORE_AAS*NUM_CORE_GAPS*NUM_CORE_AAS*NUM_CORE_GAPS*(aa1-'A')+\n\t\tNUM_CORE_AAS*NUM_CORE_GAPS*NUM_CORE_AAS*gap1+\n\t\tNUM_CORE_AAS*NUM_CORE_GAPS*(aa2-'A')+\n\t\tNUM_CORE_AAS*gap2+\n\t\t(aa3-'A'));\n}\n\n\nstruct Motif {\n\tchars aas;\n\tSizes gaps;\n\t//Size span;\n\t//Size core_index;\n\n\tMotif():\n\t\taas(),\n\t\tgaps()\n\t\t//core_index(0)\n\t{}\n\n\n\tMotif(\n\t\tchar const aa1,\n\t\tSize const gap1,\n\t\tchar const aa2,\n\t\tSize const gap2,\n\t\tchar const aa3\n\t){\n\t\taas.resize(3);\n\t\taas[0] = aa1;\n\t\taas[1] = aa2;\n\t\taas[2] = aa3;\n\t\tgaps.resize(2);\n\t\tgaps[0] = gap1;\n\t\tgaps[1] = gap2;\n\t\t//core_index = get_core_index(aa1,gap1,aa2,gap2,aa3);\n\t\t//span = gaps[0] + gaps[1] + 1; // gap between first and last position\n\t}\n\n\t// total gap between aa_i and aa_j\n\tSize\n\tgap(Size const i, Size const j) const\n\t{\n\t\tSize total(0);\n\t\tfor ( Size k=i; k<j; ++k)\n\t\t\ttotal += gaps[k];\n\t\treturn total+(j-i)-1;\n\t}\n\n\tstring\n\tto_string() const\n\t{\n\t\truntime_assert(aas.size() == gaps.size()+1);\n\t\tostringstream out;\n\t\tfor (Size k=0; k<aas.size(); ++k ){\n\t\t\tout << aas[k];\n\t\t\tif (k<gaps.size()) {\n\t\t\t\tfor (Size g=0; g<gaps[k]; ++g) out << '.';\n\t\t\t}\n\t\t}\n\t\treturn out.str();\n\t}\n};\n\n\ninline\nReal\ncompute_overlap_pvalue(\n\tSize const overlap,\n\tSize const count1,\n\tSize const count2,\n\tSize const total\n)\n{\n\tusing namespace boost::math;\n\t// whats the smallest possible overlap? max( 0, count1+count2-total )\n\tif ( overlap==0 || count1==total || count2==total ||\n\t\tcount1+count2 >= total+overlap ) return 1.0;\n\thypergeometric_distribution<> hgd( count1, count2, total );\n\t// need overlap-1 to be a valid overlap value:\n\treturn cdf( complement( hgd, overlap-1 ) );\n}\n\n\ninline\nvoid\nunpack_core_index(\n\tSize ind,\n\tchar & aa1,\n\tSize & gap1,\n\tchar & aa2,\n\tSize & gap2,\n\tchar & aa3\n)\n{\n\tSize aa3_i = ind%NUM_CORE_AAS;\n\tind = (ind-aa3_i)/NUM_CORE_AAS;\n\tgap2 = ind%NUM_CORE_GAPS;\n\tind = (ind-gap2)/NUM_CORE_GAPS;\n\tSize aa2_i = ind%NUM_CORE_AAS;\n\tind = (ind-aa2_i)/NUM_CORE_AAS;\n\tgap1 = ind%NUM_CORE_GAPS;\n\tind = (ind-gap1)/NUM_CORE_GAPS;\n\tSize aa1_i = ind%NUM_CORE_AAS;\n\n\taa1 = char('A'+aa1_i);\n\taa2 = char('A'+aa2_i);\n\taa3 = char('A'+aa3_i);\n}\n\ninline\nstring\ncore_index_to_string(\n\tSize ind\n)\n{\n\tchar aa1, aa2, aa3;\n\tSize gap1, gap2;\n\n\tunpack_core_index(ind, aa1, gap1, aa2, gap2, aa3);\n\tostringstream out;\n\tout << aa1;\n\tfor (Size g=0; g<gap1; ++g) out << '.';\n\tout << aa2;\n\tfor (Size g=0; g<gap2; ++g) out << '.';\n\tout << aa3;\n\treturn out.str();\n}\n\ninline\nMotif\ncore_index_to_motif(\n\tSize ind\n)\n{\n\tchar aa1, aa2, aa3;\n\tSize gap1, gap2;\n\n\tunpack_core_index(ind, aa1, gap1, aa2, gap2, aa3);\n\treturn Motif(aa1, gap1, aa2, gap2, aa3);\n}\n\ninline\nbool\nmotifs_overlap(\n\tMotif const & a,\n\tMotif const & b,\n\tSize & a1,\n\tSize & a2,\n\tSize & b1,\n\tSize & b2\n)\n{\n\t// NOTE -- there might be more than one match? if dup aas?\n\t//\n\t// a.aas[a1] == b.aas[b1]\n\t// a.aas[a2] == b.aas[b2]\n\t//\n\n\tfor ( a1=0; a1<1; ++a1 ){\n\t\tfor ( b1=0; b1<1; ++b1 ){\n\t\t\tif (a.aas[a1] == b.aas[b1] ) {\n\t\t\t\tfor ( a2=a1+1; a2<2; ++a2 ){\n\t\t\t\t\tfor ( b2=b1+1; b2<2; ++b2 ){\n\t\t\t\t\t\tif (a.aas[a2] == b.aas[b2] &&\n\t\t\t\t\t\t\ta.gap(a1,a2) == b.gap(b1,b2)){\n\t\t\t\t\t\t\t// actually they could be in conflict\n\t\t\t\t\t\t\tif (a1==b1 && a2==b2 && a.gaps[0]==b.gaps[0] &&\n\t\t\t\t\t\t\t\ta.gaps[1]==b.gaps[1]) return false; // unless they are identical\n\t\t\t\t\t\t\treturn true; // and a1,a2,b1,b2 are set\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn false;\n}\n\ninline\nbool\nmotifs_overlap(\n\tMotif const & a,\n\tMotif const & b\n)\n{\n\tstatic Size a1, a2, b1, b2;\n\treturn motifs_overlap(a,b,a1,a2,b1,b2);\n}\n\n\nvoid\nget_core_counts_for_cdr3s(\n\tstrings const & cdr3s,\n\tSizes & counts\n)\n{\n\tcounts.clear();\n\tcounts.resize(NUM_CORES);\n\n\tcout << \"get_core_counts_for_cdr3s: num cdr3s= \" << cdr3s.size() << endl;\n\n\tfor (string const & cdr3 : cdr3s ) {\n\t\tfor ( Size i=0; i<cdr3.size()-2; ++i ) {\n\t\t\tfor ( Size j=i+1; j<cdr3.size()-1 && j<=i+NUM_CORE_GAPS; ++j ) {\n\t\t\t\tfor ( Size k=j+1; k<cdr3.size() && k<=j+NUM_CORE_GAPS; ++k ) {\n\t\t\t\t\t++counts[get_core_index(cdr3[i], j-i-1, cdr3[j], k-j-1, cdr3[k])];\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\n}\n\n//typedef map<Size, set<Size>> AllOccs;\ntypedef map<Size, Sizes> AllOccs;\n\nvoid\nget_core_occurrences_for_cdr3s(\n\tstrings const & cdr3s,\n\tAllOccs & all_occs\n)\n{\n\tcout << \"get_core_occurrences_for_cdr3s: num cdr3s= \" << cdr3s.size() << endl;\n\n\tAllOccs::iterator it;\n\n\tSize ind(0);\n\tfor (Size icdr3=0; icdr3< cdr3s.size(); ++icdr3) {\n\t\tstring const & cdr3(cdr3s[icdr3]);\n\t\tfor ( Size i=0; i<cdr3.size()-2; ++i ) {\n\t\t\tfor ( Size j=i+1; j<cdr3.size()-1 && j<=i+NUM_CORE_GAPS; ++j ) {\n\t\t\t\tfor ( Size k=j+1; k<cdr3.size() && k<=j+NUM_CORE_GAPS; ++k ) {\n\t\t\t\t\tind = get_core_index(cdr3[i], j-i-1, cdr3[j], k-j-1, cdr3[k]);\n\t\t\t\t\tit = all_occs.find(ind);\n\t\t\t\t\tif (it != all_occs.end()) it->second.push_back(icdr3);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\n}\n\n// assumes that a and b are sorted!!!\nReal\ncompute_jaccard(\n\tSizes const & a,\n\tSizes const & b\n)\n{\n\tSizes overlap(max(a.size(),b.size()));\n\n\tSizes::iterator const ite(\n\t\tset_intersection(a.begin(), a.end(), b.begin(), b.end(), overlap.begin()));\n\tSize overlap_size(ite - overlap.begin());\n\treturn Real(overlap_size)/(a.size() + b.size() - overlap_size);\n}\n\n\nint main(int argc, char** argv)\n{\n\ttry { // to catch tclap exceptions\n\n\t\tTCLAP::CmdLine cmd( \"tcrdist_distributions\",' ', \"0.1\" );\n\n\t\t// path to database files\n \t\tTCLAP::ValueArg<std::string> db_filename_arg(\"d\",\"db_filename\",\n\t\t\t\"Database file with info for tcrdist calculation\", true,\n\t\t\t\"\", \"string\",cmd);\n\n \t\tTCLAP::ValueArg<string> fg_tcrs_file_arg(\"f\",\"fg_tcrs_file\",\"TSV (tab separated values) \"\n\t\t\t\"file containing TCRs for neighbor calculation. Should contain the 4 columns \"\n\t\t\t\"'va_gene' 'cdr3a' 'vb_gene' 'cdr3b' (or alt fieldnames: 'va' and 'vb')\", true,\n\t\t\t\"unk\", \"string\", cmd);\n\n \t\tTCLAP::ValueArg<string> bg_tcrs_file_arg(\"b\",\"bg_tcrs_file\",\"TSV (tab separated values) \"\n\t\t\t\"file containing TCRs for neighbor calculation. Should contain the 4 columns \"\n\t\t\t\"'va_gene' 'cdr3a' 'vb_gene' 'cdr3b' (or alt fieldnames: 'va' and 'vb')\", true,\n\t\t\t\"unk\", \"string\", cmd);\n\n \t\tTCLAP::ValueArg<std::string> outfile_prefix_arg(\"o\",\"outfile_prefix\",\n\t\t\t\"Prefix for the knn_indices and knn_distances output files\",true,\n\t\t\t\"\", \"string\",cmd);\n\n \t\tTCLAP::ValueArg<string> chain_arg(\"c\", \"chain\",\n\t\t\t\"TCR chain (A or B)\", true, \"\", \"string\", cmd);\n\n\t\tcmd.parse( argc, argv );\n\n\t\tstring const db_filename( db_filename_arg.getValue() );\n\t\tstring const fg_tcrs_file( fg_tcrs_file_arg.getValue() );\n\t\tstring const bg_tcrs_file( bg_tcrs_file_arg.getValue() );\n\t\tchar const chain(chain_arg.getValue()[0]);\n\t\truntime_assert(chain == 'A' || chain == 'B');\n\t\tstring const outfile_prefix( outfile_prefix_arg.getValue());\n\n\t\tTCRdistCalculator const tcrdist(chain, db_filename);\n\n\t\t// tmp hacking-- we really only need the CDR3, right?\n\t\tvector< DistanceTCR_g > fg_tcrs, bg_tcrs;\n\n\t\tread_single_chain_tcrs_from_tsv_file(fg_tcrs_file, chain, tcrdist, fg_tcrs);\n\t\tread_single_chain_tcrs_from_tsv_file(bg_tcrs_file, chain, tcrdist, bg_tcrs);\n\n\t\tstrings fg_cdr3s, bg_cdr3s;\n\t\tfor (auto t : fg_tcrs) {\n\t\t\tfg_cdr3s.push_back(\"B\"+t.cdr3.substr(3,t.cdr3.size()-5)+\"Z\");\n\t\t}\n\t\t//cout <<fg_cdr3s.front() << ' ' << fg_cdr3s.back() << endl;\n\n\t\tfor (auto t : bg_tcrs) {\n\t\t\tbg_cdr3s.push_back(\"B\"+t.cdr3.substr(3,t.cdr3.size()-5)+\"Z\");\n\t\t}\n\n\t\tReal const fg_bg_ratio(Real(fg_cdr3s.size())/bg_cdr3s.size());\n\n\t\t//\n\t\tSizes fg_counts, bg_counts;\n\n\t\tget_core_counts_for_cdr3s(fg_cdr3s, fg_counts);\n\t\tget_core_counts_for_cdr3s(bg_cdr3s, bg_counts);\n\n\n\t\tSize total_core_pvals(0);\n\t\tfor ( Size ind=0; ind<NUM_CORES; ++ind ) {\n\t\t\tif ( fg_counts[ind] >= MIN_FG_COUNT ) ++total_core_pvals;\n\t\t}\n\n\t\tvector<pair<Real, Size> > sortl;\n\t\t//vector<Motif> motifs;\n\t\tmap<Size,Motif> motifs;\n\t\tAllOccs all_fg_occs, all_bg_occs;\n\t\tReals all_pvals_adj(NUM_CORES, Real(NUM_CORES));\n\n\t\tfor ( Size ind=0; ind<NUM_CORES; ++ind ) {\n\t\t\tif ( fg_counts[ind] < MIN_FG_COUNT ) continue;\n\t\t\tSize const fg_count(fg_counts[ind]), bg_count(bg_counts[ind]);\n\t\t\tReal const expected(max(PSEUDOCOUNT,Real(bg_count))*fg_bg_ratio),\n\t\t\t\tenrich(fg_count/expected);\n\t\t\tif (enrich>=MIN_CORE_ENRICH) {\n\t\t\t\tReal const pval(compute_overlap_pvalue(fg_count, fg_count+bg_count,\n\t\t\t\t\t\tfg_cdr3s.size(), fg_cdr3s.size() + bg_cdr3s.size())),\n\t\t\t\t\tpval_adj(pval*total_core_pvals);\n\t\t\t\t//Real chisq((fg_count-expected)*(fg_count-expected)/expected);\n\t\t\t\t//if (chisq>5){ // tmp hack\n\t\t\t\tif (pval_adj <= MAX_CORE_PVAL_ADJ) {\n\t\t\t\t\tcout << \"core_pval: \" << core_index_to_string(ind) <<\n\t\t\t\t\t\t//\" pval: \" << pval <<\n\t\t\t\t\t\t\" pval_adj: \" << pval_adj <<\n\t\t\t\t\t\t\" enrich: \" << enrich <<\n\t\t\t\t\t\t\" counts: \" << fg_count << ' ' << bg_count <<\n\t\t\t\t\t\t\" total_pvals: \" << total_core_pvals << endl;\n\t\t\t\t\tsortl.push_back(make_pair(pval*total_core_pvals, ind));\n\t\t\t\t\tmotifs[ind] = core_index_to_motif(ind);\n\t\t\t\t\tall_fg_occs[ind]; // create empty list\n\t\t\t\t\tall_bg_occs[ind]; // create empty list\n\t\t\t\t\tall_pvals_adj[ind] = pval_adj;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// get occurrence list for all good cores\n\t\tget_core_occurrences_for_cdr3s(fg_cdr3s, all_fg_occs);\n\t\tget_core_occurrences_for_cdr3s(bg_cdr3s, all_bg_occs);\n\n\n\t\tsort(sortl.begin(), sortl.end());\n\n\t\t//Size a,b,c,d;\n\t\tSizes fg_overlap(fg_cdr3s.size()), bg_overlap(bg_cdr3s.size());\n\n\n\t\tSize total_pair_pvals(0);\n\t\tvector<pair<Real, Size> > pair_sortl;\n\t\tmap<Size, Sizes> all_combos; // indexed by \"index\"\n\n\t\tfor (Size jj=1; jj<sortl.size(); ++jj) { // jj is the lower-scoring motif\n\t\t\tSize const ind2(sortl[jj].second);\n\t\t\tMotif const & m2(motifs[ind2]);\n\t\t\tSizes const & m2_fg_occs(all_fg_occs.find(ind2)->second);\n\t\t\tSizes const & m2_bg_occs(all_bg_occs.find(ind2)->second);\n\t\t\tfor (Size ii=0; ii<jj; ++ii) { // ii is the higher-scoring motif\n\t\t\t\tSize const ind1(sortl[ii].second);\n\t\t\t\tMotif const & m1(motifs[ind1]);\n\t\t\t\tif (motifs_overlap(m1,m2)) {\n\t\t\t\t\t// look at intersection\n\t\t\t\t\tSizes const & m1_fg_occs(all_fg_occs.find(ind1)->second);\n\t\t\t\t\tSizes::iterator const fg_ite(\n\t\t\t\t\t\tset_intersection(m1_fg_occs.begin(), m1_fg_occs.end(),\n\t\t\t\t\t\t\tm2_fg_occs.begin(), m2_fg_occs.end(), fg_overlap.begin()));\n\t\t\t\t\tSize const fg_overlap_size(fg_ite - fg_overlap.begin());\n\t\t\t\t\tif ( fg_overlap_size >= MIN_FG_COUNT ){\n\t\t\t\t\t\tSizes const & m1_bg_occs(all_bg_occs.find(ind1)->second);\n\t\t\t\t\t\tSizes::iterator const bg_ite(\n\t\t\t\t\t\t\tset_intersection(m1_bg_occs.begin(), m1_bg_occs.end(),\n\t\t\t\t\t\t\t\tm2_bg_occs.begin(), m2_bg_occs.end(), bg_overlap.begin()));\n\t\t\t\t\t\tSize const bg_overlap_size(bg_ite - bg_overlap.begin());\n\t\t\t\t\t\t++total_pair_pvals;\n\n\t\t\t\t\t\tReal const\n\t\t\t\t\t\t\texpected(max(PSEUDOCOUNT,Real(bg_overlap_size))*fg_bg_ratio),\n\t\t\t\t\t\t\tenrich(fg_overlap_size/expected);\n\t\t\t\t\t\tif (enrich>=MIN_PAIR_ENRICH) {\n\t\t\t\t\t\t\tReal const\n\t\t\t\t\t\t\t\tpval(compute_overlap_pvalue(fg_overlap_size, fg_overlap_size+\n\t\t\t\t\t\t\t\t\t\tbg_overlap_size, fg_cdr3s.size(), fg_cdr3s.size() +\n\t\t\t\t\t\t\t\t\t\tbg_cdr3s.size())),\n\t\t\t\t\t\t\t\tpval_adj(pval*(total_core_pvals+total_pair_pvals));\n\t\t\t\t\t\t\tif (pval_adj <= MAX_PAIR_PVAL_ADJ) {\n\t\t\t\t\t\t\t\tcout << \"pair_pval: \" << core_index_to_string(ind1) << '+' <<\n\t\t\t\t\t\t\t\t\tcore_index_to_string(ind2) << ' ' <<\n\t\t\t\t\t\t\t\t\t//\" pval: \" << pval <<\n\t\t\t\t\t\t\t\t\t\" pval_adj: \" << pval_adj <<\n\t\t\t\t\t\t\t\t\t\" enrich: \" << enrich <<\n\t\t\t\t\t\t\t\t\t\" counts: \" << fg_overlap_size << ' ' << bg_overlap_size <<\n\t\t\t\t\t\t\t\t\t\" total_pvals: \" << total_core_pvals + total_pair_pvals <<\n\t\t\t\t\t\t\t\t\tendl;\n\t\t\t\t\t\t\t\t// create a new index\n\t\t\t\t\t\t\t\tSize const index(fg_counts.size());\n\t\t\t\t\t\t\t\t// extend the arrays\n\t\t\t\t\t\t\t\truntime_assert(index == bg_counts.size());\n\t\t\t\t\t\t\t\tfg_counts.push_back(fg_overlap_size);\n\t\t\t\t\t\t\t\tbg_counts.push_back(bg_overlap_size);\n\t\t\t\t\t\t\t\tall_pvals_adj.push_back(pval_adj);\n\t\t\t\t\t\t\t\t// add index to the dictionaries\n\t\t\t\t\t\t\t\tall_fg_occs[index].resize(fg_overlap_size);\n\t\t\t\t\t\t\t\tcopy(fg_overlap.begin(), fg_ite,\n\t\t\t\t\t\t\t\t\tall_fg_occs.find(index)->second.begin());\n\t\t\t\t\t\t\t\tall_bg_occs[index].resize(bg_overlap_size);\n\t\t\t\t\t\t\t\tcopy(bg_overlap.begin(), bg_ite,\n\t\t\t\t\t\t\t\t\tall_bg_occs.find(index)->second.begin());\n\t\t\t\t\t\t\t\tall_combos[index] = Sizes({ind1, ind2});\n\t\t\t\t\t\t\t\tpair_sortl.push_back(make_pair(pval_adj, index));\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tsort(pair_sortl.begin(), pair_sortl.end());\n\t\t// now go through and look for pair+single combos\n\t\t//\n\t\t// what data structures do we have?\n\t\t// all_fg_occs, all_bg_occs  keys are \"index\"\n\t\t//\n\t\t// all_combos  keys are \"index\"\n\t\t//\n\t\t// motifs  keys are \"index\" only valid for core indices\n\t\t//\n\t\tSize total_triple_pvals(0);\n\t\tfor ( Size ij_sum=0; ij_sum <pair_sortl.size()+sortl.size(); ++ij_sum) {\n\t\t\tfor ( Size ii=0; ii<ij_sum && ii<pair_sortl.size(); ++ii) {\n\t\t\t\tSize const jj(ij_sum-ii);\n\t\t\t\tif (jj>=sortl.size()) continue;\n\t\t\t\tSize const ii_index(pair_sortl[ii].second);\n\t\t\t\tSize const jj_index(sortl[jj].second);\n\t\t\t\tSizes const & ii_combos(all_combos[ii_index]);\n\t\t\t\tMotif const & m1(motifs[ii_combos[0]]);\n\t\t\t\tMotif const & m2(motifs[ii_combos[1]]);\n\t\t\t\tMotif const & m3(motifs[jj_index]);\n\t\t\t\truntime_assert(motifs_overlap(m1,m2)); // HACKING REMOVE LATER\n\t\t\t\tif (motifs_overlap(m1,m3) || motifs_overlap(m2,m3)) {\n\t\t\t\t\tSizes const & m1m2_fg_occs(all_fg_occs[ii_index]),\n\t\t\t\t\t\t& m1m2_bg_occs(all_bg_occs[ii_index]),\n\t\t\t\t\t\t& m3_fg_occs(all_fg_occs[jj_index]),\n\t\t\t\t\t\t& m3_bg_occs(all_bg_occs[jj_index]);\n\n\t\t\t\t\tSizes::iterator const fg_ite(\n\t\t\t\t\t\tset_intersection(m1m2_fg_occs.begin(), m1m2_fg_occs.end(),\n\t\t\t\t\t\t\tm3_fg_occs.begin(), m3_fg_occs.end(), fg_overlap.begin()));\n\t\t\t\t\tSize const fg_overlap_size(fg_ite - fg_overlap.begin());\n\t\t\t\t\tif ( fg_overlap_size >= MIN_FG_COUNT ){\n\t\t\t\t\t\tSizes::iterator const bg_ite(\n\t\t\t\t\t\t\tset_intersection(m1m2_bg_occs.begin(), m1m2_bg_occs.end(),\n\t\t\t\t\t\t\t\tm3_bg_occs.begin(), m3_bg_occs.end(), bg_overlap.begin()));\n\t\t\t\t\t\tSize const bg_overlap_size(bg_ite - bg_overlap.begin());\n\t\t\t\t\t\t++total_triple_pvals;\n\n\t\t\t\t\t\tReal const\n\t\t\t\t\t\t\texpected(max(PSEUDOCOUNT,Real(bg_overlap_size))*fg_bg_ratio),\n\t\t\t\t\t\t\tenrich(fg_overlap_size/expected);\n\t\t\t\t\t\tif (enrich>=MIN_TRIPLE_ENRICH) {\n\t\t\t\t\t\t\tReal const\n\t\t\t\t\t\t\t\tpval(compute_overlap_pvalue(fg_overlap_size, fg_overlap_size+\n\t\t\t\t\t\t\t\t\t\tbg_overlap_size, fg_cdr3s.size(), fg_cdr3s.size() +\n\t\t\t\t\t\t\t\t\t\tbg_cdr3s.size())),\n\t\t\t\t\t\t\t\tpval_adj(pval*(total_core_pvals+total_pair_pvals+\n\t\t\t\t\t\t\t\t\t\ttotal_triple_pvals));\n\t\t\t\t\t\t\tif (pval_adj <= MAX_TRIPLE_PVAL_ADJ) {\n\t\t\t\t\t\t\t\tcout << \"triple_pval: \" <<\n\t\t\t\t\t\t\t\t\tcore_index_to_string(ii_combos[0]) << '+' <<\n\t\t\t\t\t\t\t\t\tcore_index_to_string(ii_combos[1]) << '+' <<\n\t\t\t\t\t\t\t\t\tcore_index_to_string(jj_index) << ' ' <<\n\t\t\t\t\t\t\t\t\t//\" pval: \" << pval <<\n\t\t\t\t\t\t\t\t\t\" pval_adj: \" << pval_adj <<\n\t\t\t\t\t\t\t\t\t\" enrich: \" << enrich <<\n\t\t\t\t\t\t\t\t\t\" counts: \" << fg_overlap_size << ' ' << bg_overlap_size <<\n\t\t\t\t\t\t\t\t\t\" total_pvals: \" << total_core_pvals + total_pair_pvals +\n\t\t\t\t\t\t\t\t\ttotal_triple_pvals << endl;\n\n\t\t\t\t\t\t\t\t// new motif, create a new index\n\t\t\t\t\t\t\t\tSize const index(fg_counts.size());\n\t\t\t\t\t\t\t\t// extend the arrays\n\t\t\t\t\t\t\t\truntime_assert(index == bg_counts.size());\n\t\t\t\t\t\t\t\tfg_counts.push_back(fg_overlap_size);\n\t\t\t\t\t\t\t\tbg_counts.push_back(bg_overlap_size);\n\t\t\t\t\t\t\t\tall_pvals_adj.push_back(pval_adj);\n\t\t\t\t\t\t\t\t// add index to the dictionaries\n\t\t\t\t\t\t\t\tall_fg_occs[index].resize(fg_overlap_size);\n\t\t\t\t\t\t\t\tcopy(fg_overlap.begin(), fg_ite,\n\t\t\t\t\t\t\t\t\tall_fg_occs.find(index)->second.begin());\n\t\t\t\t\t\t\t\tall_bg_occs[index].resize(bg_overlap_size);\n\t\t\t\t\t\t\t\tcopy(bg_overlap.begin(), bg_ite,\n\t\t\t\t\t\t\t\t\tall_bg_occs.find(index)->second.begin());\n\t\t\t\t\t\t\t\tall_combos[index] = Sizes(\n\t\t\t\t\t\t\t\t\t{ii_combos[0], ii_combos[1], jj_index}); // pair then single\n\t\t\t\t\t\t\t} // pval <\n\t\t\t\t\t\t} // enrich >\n\t\t\t\t\t} // fg_overlap_size >\n\t\t\t\t}\n\t\t\t} // ii\n\t\t} // ij_sum, actually ii+jj\n\n\n\t\t// now sort all the motifs by pval, look for overlap\n\t\tvector<pair<Real,Size> > final_sortl;\n\t\tfor (Size i=0; i<all_pvals_adj.size(); ++i ) {\n\t\t\tif (all_pvals_adj[i] <= MAX_FINAL_PVAL_ADJ) {\n\t\t\t\tfinal_sortl.push_back(make_pair(all_pvals_adj[i], i));\n\t\t\t}\n\t\t}\n\t\tsort(final_sortl.begin(), final_sortl.end());\n\n\t\tbools is_good(final_sortl.size(), true); // indexed by rank in final_sortl\n\n\t\tofstream out_info(outfile_prefix+\"_motif_info.tsv\");\n\t\tofstream out_members(outfile_prefix+\"_motif_members.txt\");\n\t\tofstream out_distances(outfile_prefix+\"_motif_distances.txt\");\n\n\t\tout_info << \"motif_string\\tpval_adj\\tenrich\\tmax_jaccard\\tnum_positions\\tfg_count\\tbg_count\\ttotal_pvals\\n\";\n\n\t\tvector<Reals> all_jdists;\n\t\tSize const total_pvals(\n\t\t\ttotal_core_pvals + total_pair_pvals + total_triple_pvals);\n\n\t\tfor ( Size ii=0; ii<final_sortl.size(); ++ii ) {\n\t\t\tSize const ii_index(final_sortl[ii].second);\n\t\t\t// check if too close to previous motif\n\t\t\tReal max_jaccard(0);\n\t\t\tReals jdists;\n\t\t\tfor ( Size jj=0; jj<ii; ++jj ) {\n\t\t\t\tif (is_good[jj]) {\n\t\t\t\t\tSize const jj_index(final_sortl[jj].second);\n\t\t\t\t\tReal const jaccard(compute_jaccard(\n\t\t\t\t\t\t\tall_fg_occs[ii_index], all_fg_occs[jj_index]));\n\t\t\t\t\tjdists.push_back(1.0-jaccard);\n\t\t\t\t\tmax_jaccard = max(max_jaccard, jaccard);\n\t\t\t\t\tif ( jaccard > MAX_JACCARD ) {\n\t\t\t\t\t\t//cout<< \"too close: \" << jaccard << ' ' << ii << ' ' << jj << endl;\n\t\t\t\t\t\tis_good[ii] = false;\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\tif ( is_good[ii] ) {\n\t\t\t\t// update the distance matrix\n\t\t\t\tjdists.push_back(0.0); // self dist\n\t\t\t\tfor ( Size jj=0; jj<all_jdists.size(); ++jj ) { // make it square\n\t\t\t\t\tall_jdists[jj].push_back(jdists[jj]);\n\t\t\t\t\t// runtime_assert(all_jdists[jj].size() == jdists.size());\n\t\t\t\t}\n\t\t\t\tall_jdists.push_back(jdists);\n\n\t\t\t\t// not redundant by jaccard\n\t\t\t\tcout << \"final_pval: \";\n\t\t\t\t// show the motif\n\t\t\t\tif (ii_index < NUM_CORES) {\n\t\t\t\t\tcout << motifs[ii_index].to_string();\n\t\t\t\t\tout_info << motifs[ii_index].to_string() << '\\t';\n\t\t\t\t} else {\n\t\t\t\t\tbool first(true);\n\t\t\t\t\tfor ( Size kk : all_combos[ii_index] ) {\n\t\t\t\t\t\tif (!first) {\n\t\t\t\t\t\t\tcout << '+';\n\t\t\t\t\t\t\tout_info << '+';\n\t\t\t\t\t\t} else first=false;\n\t\t\t\t\t\tcout << motifs[kk].to_string();\n\t\t\t\t\t\tout_info << motifs[kk].to_string();\n\t\t\t\t\t}\n\t\t\t\t\tout_info << '\\t';\n\t\t\t\t}\n\t\t\t\t// this is not quite right: triple could only specify 4 positions...\n\t\t\t\tSize const num_positions\n\t\t\t\t\t(ii_index<NUM_CORES ? 3 : 2+all_combos[ii_index].size());\n\t\t\t\tReal const\n\t\t\t\t\texpected(max(PSEUDOCOUNT,Real(bg_counts[ii_index]))*fg_bg_ratio),\n\t\t\t\t\tenrich(fg_counts[ii_index]/expected);\n\t\t\t\tcout << \" pval_adj: \" << all_pvals_adj[ii_index] <<\n\t\t\t\t\t\" enrich: \" << enrich <<\n\t\t\t\t\t\" max_jaccard: \" << max_jaccard <<\n\t\t\t\t\t\" num_positions: \" << num_positions <<\n\t\t\t\t\t\" counts: \" << fg_counts[ii_index] << ' ' << bg_counts[ii_index] <<\n\t\t\t\t\t\" total_pvals: \" << total_pvals << endl;\n\n\t\t\t\tout_info << all_pvals_adj[ii_index] << '\\t' <<\n\t\t\t\t\tenrich << '\\t' <<\n\t\t\t\t\tmax_jaccard << '\\t' <<\n\t\t\t\t\tnum_positions << '\\t' <<\n\t\t\t\t\tfg_counts[ii_index] << '\\t' <<\n\t\t\t\t\tbg_counts[ii_index] << '\\t' <<\n\t\t\t\t\ttotal_pvals << '\\n';\n\t\t\t\t{ // write members\n\t\t\t\t\truntime_assert(all_fg_occs[ii_index].size() == fg_counts[ii_index]);\n\t\t\t\t\tbool first(true);\n\t\t\t\t\tfor ( Size m : all_fg_occs[ii_index] ) {\n\t\t\t\t\t\tif (first) first=false;\n\t\t\t\t\t\telse out_members << ' ';\n\t\t\t\t\t\tout_members << m;\n\t\t\t\t\t}\n\t\t\t\t\tout_members << '\\n';\n\t\t\t\t}\n\t\t\t} // good!\n\t\t}\n\t\tout_info.close();\n\t\tout_members.close();\n\n\t\t// write jaccard distance matrix:\n\t\tfor ( Reals const & jdists : all_jdists ) {\n\t\t\truntime_assert(jdists.size() == all_jdists.size());\n\t\t\tbool first(true);\n\t\t\tfor ( Real d : jdists ) {\n\t\t\t\tif ( first ) first=false;\n\t\t\t\telse out_distances << ' ';\n\t\t\t\tout_distances << d;\n\t\t\t}\n\t\t\tout_distances << '\\n';\n\t\t}\n\t\tout_distances.close();\n\n\n\t\tcout << \"DONE\" << endl;\n\n\t} catch (TCLAP::ArgException &e)  // catch any exceptions\n\t\t{\n\t\t\tstd::cerr << \"error: \" << e.error() << \" for arg \" << e.argId() <<\n\t\t\t\tstd::endl;\n\t\t}\n\n}\n\n\n", "meta": {"hexsha": "e531d5fe834f0ed782cf1f674724e460ca979e0a", "size": 20152, "ext": "cc", "lang": "C++", "max_stars_repo_path": "tcrdist_cpp/src/find_cdr3_motifs.cc", "max_stars_repo_name": "phbradley/conga", "max_stars_repo_head_hexsha": "ce7257ab5ac9283305800dafc8a238ccf53ee084", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 46.0, "max_stars_repo_stars_event_min_datetime": "2020-06-09T18:43:23.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-21T07:47:47.000Z", "max_issues_repo_path": "tcrdist_cpp/src/find_cdr3_motifs.cc", "max_issues_repo_name": "phbradley/conga", "max_issues_repo_head_hexsha": "ce7257ab5ac9283305800dafc8a238ccf53ee084", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 32.0, "max_issues_repo_issues_event_min_datetime": "2020-08-25T10:00:37.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-25T17:54:01.000Z", "max_forks_repo_path": "tcrdist_cpp/src/find_cdr3_motifs.cc", "max_forks_repo_name": "phbradley/conga", "max_forks_repo_head_hexsha": "ce7257ab5ac9283305800dafc8a238ccf53ee084", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2020-06-19T14:08:25.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-14T08:43:41.000Z", "avg_line_length": 29.1213872832, "max_line_length": 110, "alphanum_fraction": 0.6341802303, "num_tokens": 6537, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6825737344123242, "lm_q2_score": 0.4416730056646256, "lm_q1q2_score": 0.3014743928656191}}
{"text": "#ifndef SKYLARK_GEMM_HPP\n#define SKYLARK_GEMM_HPP\n\n#include <boost/mpi.hpp>\n#include \"exception.hpp\"\n#include \"sparse_matrix.hpp\"\n#include \"computed_matrix.hpp\"\n#include \"../utility/typer.hpp\"\n\n// Defines a generic Gemm function that receives both dense and sparse matrices.\n\nnamespace skylark { namespace base {\n\n/**\n * Rename the Elemental Gemm function, so that we have unified access.\n */\n\ntemplate<typename T>\ninline void Gemm(El::Orientation oA, El::Orientation oB,\n    T alpha, const El::Matrix<T>& A, const El::Matrix<T>& B,\n    T beta, El::Matrix<T>& C) {\n    El::Gemm(oA, oB, alpha, A, B, beta, C);\n}\n\ntemplate<typename T>\ninline void Gemm(El::Orientation oA, El::Orientation oB,\n    T alpha, const El::Matrix<T>& A, const El::Matrix<T>& B,\n    El::Matrix<T>& C) {\n    El::Gemm(oA, oB, alpha, A, B, C);\n}\n\ntemplate<typename T>\ninline void Gemm(El::Orientation oA, El::Orientation oB,\n    T alpha, const El::DistMatrix<T, El::STAR, El::STAR>& A,\n    const El::DistMatrix<T, El::STAR, El::STAR>& B,\n    T beta, El::DistMatrix<T, El::STAR, El::STAR>& C) {\n    El::Gemm(oA, oB, alpha, A.LockedMatrix(), B.LockedMatrix(), beta, C.Matrix());\n}\n\ntemplate<typename T>\ninline void Gemm(El::Orientation oA, El::Orientation oB,\n    T alpha, const El::DistMatrix<T, El::STAR, El::STAR>& A,\n    const El::DistMatrix<T, El::STAR, El::STAR>& B,\n    El::DistMatrix<T, El::STAR, El::STAR>& C) {\n    El::Gemm(oA, oB, alpha, A.LockedMatrix(), B.LockedMatrix(), C.Matrix());\n}\n\ntemplate<typename T>\ninline void Gemm(El::Orientation oA, El::Orientation oB,\n    T alpha, const El::DistMatrix<T, El::CIRC, El::CIRC>& A,\n    const El::DistMatrix<T, El::CIRC, El::CIRC>& B,\n    T beta, El::DistMatrix<T, El::CIRC, El::CIRC>& C) {\n    El::Gemm(oA, oB, alpha, A.LockedMatrix(), B.LockedMatrix(), beta, C.Matrix());\n}\n\ntemplate<typename T>\ninline void Gemm(El::Orientation oA, El::Orientation oB,\n    T alpha, const El::DistMatrix<T, El::CIRC, El::CIRC>& A,\n    const El::DistMatrix<T, El::CIRC, El::CIRC>& B,\n    El::DistMatrix<T, El::CIRC, El::CIRC>& C) {\n    El::Gemm(oA, oB, alpha, A.LockedMatrix(), B.LockedMatrix(), C.Matrix());\n}\n\ntemplate<typename T>\ninline void Gemm(El::Orientation oA, El::Orientation oB,\n    T alpha, const El::DistMatrix<T>& A, const El::DistMatrix<T>& B,\n    T beta, El::DistMatrix<T>& C) {\n    El::Gemm(oA, oB, alpha, A, B, beta, C);\n}\n\ntemplate<typename T>\ninline void Gemm(El::Orientation oA, El::Orientation oB,\n    T alpha, const El::DistMatrix<T>& A, const El::DistMatrix<T>& B,\n    El::DistMatrix<T>& C) {\n    El::Gemm(oA, oB, alpha, A, B, C);\n}\n\n/**\n * The following combinations is not offered by Elemental, but are useful for us.\n * We implement them partially.\n */\n\ntemplate<typename T>\ninline void Gemm(El::Orientation oA, El::Orientation oB,\n    T alpha, const El::DistMatrix<T, El::VC, El::STAR>& A,\n    const El::DistMatrix<T, El::VC, El::STAR>& B,\n    T beta, El::DistMatrix<T, El::STAR, El::STAR>& C) {\n    // TODO verify sizes etc.\n\n    if ((oA == El::TRANSPOSE || oA == El::ADJOINT) && oB == El::NORMAL) {\n        boost::mpi::communicator comm(C.Grid().Comm().comm,\n            boost::mpi::comm_attach);\n        El::Matrix<T> Clocal(C.Matrix());\n        El::Gemm(oA, El::NORMAL,\n            alpha, A.LockedMatrix(), B.LockedMatrix(),\n            beta / T(comm.size()), Clocal);\n        boost::mpi::all_reduce(comm,\n            Clocal.Buffer(), Clocal.MemorySize(), C.Matrix().Buffer(),\n            std::plus<T>());\n    } else {\n        SKYLARK_THROW_EXCEPTION(base::unsupported_base_operation());\n    }\n}\n\ntemplate<typename T>\ninline void Gemm(El::Orientation oA, El::Orientation oB,\n    T alpha, const El::DistMatrix<T, El::VC, El::STAR>& A,\n    const El::DistMatrix<T, El::VC, El::STAR>& B,\n    El::DistMatrix<T, El::STAR, El::STAR>& C) {\n\n    int C_height = (oA == El::NORMAL ? A.Height() : A.Width());\n    int C_width = (oB == El::NORMAL ? B.Width() : B.Height());\n    El::Zeros(C, C_height, C_width);\n    base::Gemm(oA, oB, alpha, A, B, T(0), C);\n}\n\ntemplate<typename T>\ninline void Gemm(El::Orientation oA, El::Orientation oB,\n    T alpha, const El::DistMatrix<T, El::VC, El::STAR>& A,\n    const El::DistMatrix<T, El::STAR, El::STAR>& B,\n    T beta, El::DistMatrix<T, El::VC, El::STAR>& C) {\n    // TODO verify sizes etc.\n\n    if (oA == El::NORMAL && oB == El::NORMAL) {\n        El::Gemm(El::NORMAL, El::NORMAL,\n            alpha, A.LockedMatrix(), B.LockedMatrix(),\n            beta, C.Matrix());\n    } else {\n        SKYLARK_THROW_EXCEPTION(base::unsupported_base_operation());\n    }\n}\n\ntemplate<typename T>\ninline void Gemm(El::Orientation oA, El::Orientation oB,\n    T alpha, const El::DistMatrix<T, El::VC, El::STAR>& A,\n    const El::DistMatrix<T, El::STAR, El::STAR>& B,\n    El::DistMatrix<T, El::VC, El::STAR>& C) {\n\n    int C_height = (oA == El::NORMAL ? A.Height() : A.Width());\n    int C_width = (oB == El::NORMAL ? B.Width() : B.Height());\n    El::Zeros(C, C_height, C_width);\n    base::Gemm(oA, oB, alpha, A, B, T(0), C);\n}\n\n\ntemplate<typename T>\ninline void Gemm(El::Orientation oA, El::Orientation oB,\n    T alpha, const El::DistMatrix<T, El::VR, El::STAR>& A,\n    const El::DistMatrix<T, El::VR, El::STAR>& B,\n    T beta, El::DistMatrix<T, El::STAR, El::STAR>& C) {\n    // TODO verify sizes etc.\n\n    if ((oA == El::TRANSPOSE || oA == El::ADJOINT) && oB == El::NORMAL) {\n        boost::mpi::communicator comm(C.Grid().Comm(), boost::mpi::comm_attach);\n        El::Matrix<T> Clocal(C.Matrix());\n        El::Gemm(oA, El::NORMAL,\n            alpha, A.LockedMatrix(), B.LockedMatrix(),\n            beta / T(comm.size()), Clocal);\n        boost::mpi::all_reduce(comm,\n            Clocal.Buffer(), Clocal.MemorySize(), C.Matrix().Buffer(),\n            std::plus<T>());\n    } else {\n        SKYLARK_THROW_EXCEPTION(base::unsupported_base_operation());\n    }\n}\n\ntemplate<typename T>\ninline void Gemm(El::Orientation oA, El::Orientation oB,\n    T alpha, const El::DistMatrix<T, El::VR, El::STAR>& A,\n    const El::DistMatrix<T, El::VR, El::STAR>& B,\n    El::DistMatrix<T, El::STAR, El::STAR>& C) {\n\n    int C_height = (oA == El::NORMAL ? A.Height() : A.Width());\n    int C_width = (oB == El::NORMAL ? B.Width() : B.Height());\n    El::Zeros(C, C_height, C_width);\n    base::Gemm(oA, oB, alpha, A, B, T(0), C);\n}\n\ntemplate<typename T>\ninline void Gemm(El::Orientation oA, El::Orientation oB,\n    T alpha, const El::DistMatrix<T, El::VR, El::STAR>& A,\n    const El::DistMatrix<T, El::STAR, El::STAR>& B,\n    T beta, El::DistMatrix<T, El::VR, El::STAR>& C) {\n    // TODO verify sizes etc.\n\n    if (oA == El::NORMAL && oB == El::NORMAL) {\n        El::Gemm(El::NORMAL, El::NORMAL,\n            alpha, A.LockedMatrix(), B.LockedMatrix(),\n            beta, C.Matrix());\n    } else {\n        SKYLARK_THROW_EXCEPTION(base::unsupported_base_operation());\n    }\n}\n\ntemplate<typename T>\ninline void Gemm(El::Orientation oA, El::Orientation oB,\n    T alpha, const El::DistMatrix<T, El::VR, El::STAR>& A,\n    const El::DistMatrix<T, El::STAR, El::STAR>& B,\n    El::DistMatrix<T, El::VR, El::STAR>& C) {\n\n    int C_height = (oA == El::NORMAL ? A.Height() : A.Width());\n    int C_width = (oB == El::NORMAL ? B.Width() : B.Height());\n    El::Zeros(C, C_height, C_width);\n    base::Gemm(oA, oB, alpha, A, B, T(0), C);\n}\n\n/**\n * Gemm between mixed Elemental, sparse input. Output is dense Elemental.\n */\n\ntemplate<typename T>\ninline void Gemm(El::Orientation oA, El::Orientation oB,\n    T alpha, const El::Matrix<T>& A, const sparse_matrix_t<T>& B,\n    T beta, El::Matrix<T>& C) {\n    // TODO verify sizes etc.\n\n    const int* indptr = B.indptr();\n    const int* indices = B.indices();\n    const T *values = B.locked_values();\n\n    if (oA == El::ADJOINT && std::is_same<T, El::Base<T> >::value)\n        oA = El::TRANSPOSE;\n\n    if (oB == El::ADJOINT && std::is_same<T, El::Base<T> >::value)\n        oB = El::TRANSPOSE;\n\n    if (oA == El::ADJOINT || oB == El::ADJOINT)\n        SKYLARK_THROW_EXCEPTION(base::unsupported_base_operation());\n\n    // NN\n    if (oA == El::NORMAL && oB == El::NORMAL) {\n        int k = A.Width();\n        int n = B.width();\n        int m = A.Height();\n\n        El::Scale(beta, C);\n\n        El::Matrix<T> Ac;\n        El::Matrix<T> Cc;\n\n#       if SKYLARK_HAVE_OPENMP\n#       pragma omp parallel for private(Cc, Ac)\n#       endif\n        for(int col = 0; col < n; col++) {\n            El::View(Cc, C, 0, col, m, 1);\n            for (int j = indptr[col]; j < indptr[col + 1]; j++) {\n                int row = indices[j];\n                T val = values[j];\n                El::LockedView(Ac, A, 0, row, m, 1);\n                El::Axpy(alpha * val, Ac, Cc);\n            }\n        }\n    }\n\n    // NT\n    if (oA == El::NORMAL && oB == El::TRANSPOSE) {\n        int k = A.Width();\n        int n = B.width();\n        int m = A.Height();\n\n        El::Scale(beta, C);\n\n        El::Matrix<T> Ac;\n        El::Matrix<T> Cc;\n\n        // Now, we simply think of B has being in CSR mode...\n        int row = 0;\n        for(int row = 0; row < n; row++) {\n            El::LockedView(Ac, A, 0, row, m, 1);\n#           if SKYLARK_HAVE_OPENMP\n#           pragma omp parallel for private(Cc)\n#           endif\n            for (int j = indptr[row]; j < indptr[row + 1]; j++) {\n                int col = indices[j];\n                T val = values[j];\n                El::View(Cc, C, 0, col, m, 1);\n                El::Axpy(alpha * val, Ac, Cc);\n            }\n        }\n    }\n\n\n    // TN - TODO: Not tested!\n    if (oA == El::TRANSPOSE && oB == El::NORMAL) {\n        int k = A.Height();\n        int n = B.width();\n        int m = A.Width();\n\n        T *c = C.Buffer();\n        int ldc = C.LDim();\n\n        const T *a = A.LockedBuffer();\n        int lda = A.LDim();\n\n#       if SKYLARK_HAVE_OPENMP\n#       pragma omp parallel for collapse(2)\n#       endif\n        for (int j = 0; j < n; j++)\n            for(int row = 0; row < m; row++) {\n                c[j * ldc + row] *= beta;\n                 for (int l = indptr[j]; l < indptr[j + 1]; l++) {\n                     int rr = indices[l];\n                     T val = values[l];\n                     c[j * ldc + row] += val * a[row * lda + rr];\n                 }\n            }\n    }\n\n    // TT - TODO: Not tested!\n    if (oA == El::TRANSPOSE && oB == El::TRANSPOSE) {\n        int k = A.Height();\n        int n = B.width();\n        int m = A.Width();\n\n        El::Scale(beta, C);\n\n        T *c = C.Buffer();\n        int ldc = C.LDim();\n\n        const T *a = A.LockedBuffer();\n        int lda = A.LDim();\n\n#       if SKYLARK_HAVE_OPENMP\n#       pragma omp parallel for\n#       endif\n        for(int row = 0; row < k; row++)\n            for(int rb = 0; rb < n; rb++)\n                for (int l = indptr[rb]; l < indptr[rb + 1]; l++) {\n                    int col = indices[l];\n                    c[col * ldc + row] += values[l] * a[row * lda + rb];\n                }\n    }\n}\n\ntemplate<typename T>\ninline void Gemm(El::Orientation oA, El::Orientation oB,\n    T alpha, const sparse_matrix_t<T>& A, const El::Matrix<T>& B,\n    T beta, El::Matrix<T>& C) {\n    // TODO verify sizes etc.\n\n    const int* indptr = A.indptr();\n    const int* indices = A.indices();\n    const T *values = A.locked_values();\n\n    int k = A.width();\n    int n = B.Width();\n    int m = B.Height();\n\n    if (oA == El::ADJOINT && std::is_same<T, El::Base<T> >::value)\n        oA = El::TRANSPOSE;\n\n    if (oB == El::ADJOINT && std::is_same<T, El::Base<T> >::value)\n        oB = El::TRANSPOSE;\n\n    // NN\n    if (oA == El::NORMAL && oB == El::NORMAL) {\n\n        El::Scale(beta, C);\n\n        T *c = C.Buffer();\n        int ldc = C.LDim();\n\n        const T *b = B.LockedBuffer();\n        int ldb = B.LDim();\n\n#       if SKYLARK_HAVE_OPENMP\n#       pragma omp parallel for\n#       endif\n        for(int i = 0; i < n; i++)\n            for(int col = 0; col < k; col++)\n                 for (int j = indptr[col]; j < indptr[col + 1]; j++) {\n                     int row = indices[j];\n                     T val = values[j];\n                     c[i * ldc + row] += alpha * val * b[i * ldb + col];\n                 }\n    }\n\n    // NT\n    if (oA == El::NORMAL && (oB == El::TRANSPOSE || oB == El::ADJOINT)) {\n\n        El::Scale(beta, C);\n\n        El::Matrix<T> Bc;\n        El::Matrix<T> BTr;\n        El::Matrix<T> Cr;\n\n        for(int col = 0; col < k; col++) {\n            El::LockedView(Bc, B, 0, col, m, 1);\n            El::Transpose(Bc, BTr, oB == El::ADJOINT);\n#           if SKYLARK_HAVE_OPENMP\n#           pragma omp parallel for private(Cr)\n#           endif\n            for (int j = indptr[col]; j < indptr[col + 1]; j++) {\n                int row = indices[j];\n                T val = values[j];\n                El::View(Cr, C, row, 0, 1, m);\n                El::Axpy(alpha * val, BTr, Cr);\n            }\n        }\n    }\n\n    // TN - TODO: Not tested!\n    if (oA == El::TRANSPOSE && oB == El::NORMAL) {\n        T *c = C.Buffer();\n        int ldc = C.LDim();\n\n        const T *b = B.LockedBuffer();\n        int ldb = B.LDim();\n\n#       if SKYLARK_HAVE_OPENMP\n#       pragma omp parallel for collapse(2)\n#       endif\n        for (int j = 0; j < n; j++)\n            for(int row = 0; row < k; row++) {\n                c[j * ldc + row] *= beta;\n                 for (int l = indptr[row]; l < indptr[row + 1]; l++) {\n                     int col = indices[l];\n                     T val = values[l];\n                     c[j * ldc + row] += val * b[j * ldb + col];\n                 }\n            }\n    }\n\n    // AN - TODO: Not tested!\n    if (oA == El::ADJOINT && oB == El::NORMAL) {\n        T *c = C.Buffer();\n        int ldc = C.LDim();\n\n        const T *b = B.LockedBuffer();\n        int ldb = B.LDim();\n\n#       if SKYLARK_HAVE_OPENMP\n#       pragma omp parallel for collapse(2)\n#       endif\n        for (int j = 0; j < n; j++)\n            for(int row = 0; row < k; row++) {\n                c[j * ldc + row] *= beta;\n                 for (int l = indptr[row]; l < indptr[row + 1]; l++) {\n                     int col = indices[l];\n                     T val = El::Conj(values[l]);\n                     c[j * ldc + row] += val * b[j * ldb + col];\n                 }\n            }\n    }\n\n\n    // TT - TODO: Not tested!\n    if (oA == El::TRANSPOSE && (oB == El::TRANSPOSE || oB == El::ADJOINT)) {\n\n        El::Scale(beta, C);\n\n        El::Matrix<T> Bc;\n        El::Matrix<T> BTr;\n        El::Matrix<T> Cr;\n\n#       if SKYLARK_HAVE_OPENMP\n#       pragma omp parallel for private(Cr, Bc, BTr)\n#       endif\n        for(int row = 0; row < k; row++) {\n            El::View(Cr, C, row, 0, 1, m);\n            for (int l = indptr[row]; l < indptr[row + 1]; l++) {\n                int col = indices[l];\n                T val = values[l];\n                El::LockedView(Bc, B, 0, col, m, 1);\n                El::Transpose(Bc, BTr, oB == El::ADJOINT);\n                El::Axpy(alpha * val, BTr, Cr);\n            }\n        }\n    }\n\n    // AT - TODO: Not tested!\n    if (oA == El::ADJOINT && (oB == El::TRANSPOSE || oB == El::ADJOINT)) {\n\n        El::Scale(beta, C);\n\n        El::Matrix<T> Bc;\n        El::Matrix<T> BTr;\n        El::Matrix<T> Cr;\n\n#       if SKYLARK_HAVE_OPENMP\n#       pragma omp parallel for private(Cr, Bc, BTr)\n#       endif\n        for(int row = 0; row < k; row++) {\n            El::View(Cr, C, row, 0, 1, m);\n            for (int l = indptr[row]; l < indptr[row + 1]; l++) {\n                int col = indices[l];\n                T val = El::Conj(values[l]);\n                El::LockedView(Bc, B, 0, col, m, 1);\n                El::Transpose(Bc, BTr, oB == El::ADJOINT);\n                El::Axpy(alpha * val, BTr, Cr);\n            }\n        }\n    }\n}\n\ntemplate<typename T>\ninline void Gemm(El::Orientation oA, El::Orientation oB,\n    T alpha, const sparse_matrix_t<T>& A, const El::Matrix<T>& B,\n    El::Matrix<T>& C) {\n    int C_height = (oA == El::NORMAL ? A.height() : A.width());\n    int C_width = (oB == El::NORMAL ? B.Width() : B.Height());\n    El::Zeros(C, C_height, C_width);\n    base::Gemm(oA, oB, alpha, A, B, T(0), C);\n}\n\ntemplate<typename T>\ninline void Gemm(El::Orientation oA, El::Orientation oB,\n    T alpha, const El::Matrix<T>& A, const sparse_matrix_t<T>& B,\n    El::Matrix<T>& C) {\n    int C_height = (oA == El::NORMAL ? A.Height() : A.Width());\n    int C_width = (oB == El::NORMAL ? B.width() : B.height());\n    El::Zeros(C, C_height, C_width);\n    base::Gemm(oA, oB, alpha, A, B, T(0), C);\n}\n\n\n\n\ntemplate<typename value_type>\nvoid Gemm(El::Orientation oA, El::Orientation oB, value_type alpha,\n          const El::DistMatrix<value_type, El::VC, El::STAR> &A,\n          const El::DistMatrix<value_type, El::VC, El::STAR> &B,\n          value_type beta, El::DistMatrix<value_type, El::VC, El::STAR> &C) {\n\n    //XXX: Just forward to Elemental for now\n    El::Gemm(oA, oB, alpha, A, B, beta, C);\n}\n\ntemplate<typename value_type>\nvoid Gemm(El::Orientation oA, El::Orientation oB, value_type alpha,\n          const El::DistMatrix<value_type, El::VC, El::STAR> &A,\n          const El::DistMatrix<value_type, El::VC, El::STAR> &B,\n          El::DistMatrix<value_type, El::VC, El::STAR> &C) {\n\n    Gemm(oA, oB, alpha, A, B, static_cast<value_type>(0.0), C);\n}\n\n\n/* All combinations with computed matrix */\n\ntemplate<typename CT, typename RT, typename OT>\ninline void Gemm(El::Orientation oA, El::Orientation oB,\n    typename utility::typer_t<OT>::value_type alpha, const computed_matrix_t<CT>& A,\n    const RT& B, typename utility::typer_t<OT>::value_type beta, OT& C) {\n    base::Gemm(oA, oB, alpha, A.materialize(), B, beta, C);\n}\n\ntemplate<typename CT, typename RT, typename OT>\ninline void Gemm(El::Orientation oA, El::Orientation oB,\n    typename utility::typer_t<OT>::value_type alpha, const computed_matrix_t<CT>& A,\n    const RT& B, OT& C) {\n    base::Gemm(oA, oB, alpha, A.materialize(), B, C);\n}\n\ntemplate<typename CT, typename RT, typename OT>\ninline void Gemm(El::Orientation oA, El::Orientation oB,\n    typename utility::typer_t<OT>::value_type alpha, const RT& A,\n    const computed_matrix_t<CT>& B,\n    typename utility::typer_t<OT>::value_type beta, OT& C) {\n    base::Gemm(oA, oB, alpha, A, B.materialize(), beta, C);\n}\n\ntemplate<typename CT, typename RT, typename OT>\ninline void Gemm(El::Orientation oA, El::Orientation oB,\n    typename utility::typer_t<OT>::value_type alpha, const RT& A,\n    const computed_matrix_t<CT>& B, OT& C) {\n    base::Gemm(oA, oB, alpha, A, B.materialize(), C);\n}\n\ntemplate<typename CT1, typename CT2, typename OT>\ninline void Gemm(El::Orientation oA, El::Orientation oB,\n    typename utility::typer_t<OT>::value_type alpha, const computed_matrix_t<CT1>& A,\n    const computed_matrix_t<CT2>& B, typename utility::typer_t<OT>::value_type beta,\n    OT& C) {\n    base::Gemm(oA, oB, alpha, A.materialize(), B.materialize(), beta, C);\n}\n\ntemplate<typename CT1, typename CT2, typename OT>\ninline void Gemm(El::Orientation oA, El::Orientation oB,\n    typename utility::typer_t<OT>::value_type alpha, const computed_matrix_t<CT1>& A,\n    const computed_matrix_t<CT2>& B, OT& C) {\n    base::Gemm(oA, oB, alpha, A.materialize(), B.materialize(), C);\n}\n\n} } // namespace skylark::base\n\n// Additional implementations\n#include \"detail/dist_mixed_gemm.hpp\"\n#include \"detail/combblas_mixed_gemm.hpp\"\n\n#endif // SKYLARK_GEMM_HPP\n", "meta": {"hexsha": "20dad692dbeb1982c084b913d052951ee7bfda19", "size": 19218, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "base/Gemm.hpp", "max_stars_repo_name": "xdata-skylark/libskylark", "max_stars_repo_head_hexsha": "89c3736136a24d519c14fc0738c21f37f1e10360", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 86.0, "max_stars_repo_stars_event_min_datetime": "2015-01-20T03:12:46.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-10T04:05:21.000Z", "max_issues_repo_path": "base/Gemm.hpp", "max_issues_repo_name": "xdata-skylark/libskylark", "max_issues_repo_head_hexsha": "89c3736136a24d519c14fc0738c21f37f1e10360", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 48.0, "max_issues_repo_issues_event_min_datetime": "2015-05-12T09:31:23.000Z", "max_issues_repo_issues_event_max_datetime": "2018-12-05T14:45:46.000Z", "max_forks_repo_path": "base/Gemm.hpp", "max_forks_repo_name": "xdata-skylark/libskylark", "max_forks_repo_head_hexsha": "89c3736136a24d519c14fc0738c21f37f1e10360", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 25.0, "max_forks_repo_forks_event_min_datetime": "2015-01-18T23:02:11.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-12T07:30:35.000Z", "avg_line_length": 32.4628378378, "max_line_length": 85, "alphanum_fraction": 0.5424601936, "num_tokens": 5842, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6076631698328916, "lm_q2_score": 0.4960938294709195, "lm_q1q2_score": 0.30145794895083694}}
{"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 * This file contains an example of graphlab used for MAP inference \n * in a discrete graphical model (pairwise MRF). The algorithm\n * implemented is the MPLP LP-Relaxation scheme of Globerson & Jaakkola. \n *\n *  \\author Dhruv Batra\n */\n\n\n#include <vector>\n#include <string>\n#include <fstream>\n\n\n#include <Eigen/Dense>\n\n#include <cv.h>\n#include <highgui.h>  \n\n\n\n#include <graphlab.hpp>\n\n#include \"eigen_serialization.hpp\"\n\n#include <graphlab/macros_def.hpp>\n\ntypedef Eigen::VectorXd vector;\ntypedef Eigen::MatrixXd matrix;\n\ntemplate <typename T>\ninline std::ostream& operator<<(std::ostream& os, std::vector<T>& x)\n{\n    typename std::vector<T>::const_iterator i(x.begin());\n    while(i != x.end()) os << *i++ << ' ';\n    return os;\n}\n\n// Global variables\nsize_t NCOLORS;\ndouble SIGMA;\ndouble BOUND;\n\n// LP-based upper-bound on MAP\ngraphlab::mutex mutex;\n//mutex.lock();\ndouble LPval = 0;\ndouble MAPval = 0;\ndouble MAPrepval = 0;\n//mutex.unlock();\n\n// Shared base edge potential\nmatrix THETA_ij; \n\n// keep track of predictions at each node\nvector PRED_COLOR;\n\n// check if all nodes are visited\n//Eigen::Matrix<graphlab::atomic<int>, Eigen::Dynamic,1> vinit;\n//Eigen::Matrix<graphlab::atomic<int>, Eigen::Dynamic,1> vapply;\n//vector vinit;\n//vector vapply;\n//std::vector<graphlab::atomic<int> > vinit;\n//std::vector<graphlab::atomic<int> > vapply;\nstd::vector<int> vinit;\nstd::vector<int> vapply;\n\n\n\n// STRUCTS (Edge and Vertex data) =============================================>\n\n/**\n * Each GraphLab vertex is a (pairwise) factor from the MRF\n */\nstruct vertex_data {\n    /** variable ids */\n    int i, j; \n    \n    // degree of these nodes in the MRF\n    int deg_i, deg_j; \n    \n    /** observed color for each variable */\n    float obs_color_i, obs_color_j;\n    /** predicted color for each variable */\n    float pred_color_i, pred_color_j;\n    \n    // current maximizers of reparameterized theta_i, theta_j and theta_IJ\n    int maxI, maxJ, maxIJ_i, maxIJ_j;\n    \n    // current contribution to LP dual value\n    double vali, valj, valij;\n    // current contribution to MAP value\n    double pvali, pvalj, pvalij;\n    // current contribution to MAPrep value\n    double prvali, prvalj, prvalij;\n    \n    // since variables i and j are present in multiple factors, this determines who owns them\n    bool iowner, jowner; \n    \n    /** dual variables being optimized (or messages) */\n    vector delf_i, delf_j;  \n\n    // constructor\n    vertex_data(): i(-1), j(-1), deg_i(0), deg_j(0), \n    obs_color_i(-1), obs_color_j(-1), \n    pred_color_i(0), pred_color_j(0),\n    vali(0), valj(0), valij(0),\n    pvali(0), pvalj(0), pvalij(0), \n    prvali(0), prvalj(0), prvalij(0), \n    iowner(false), jowner(false)\n    { }\n    \n    void save(graphlab::oarchive& arc) const \n    {\n        arc << i << j \n        << deg_i << deg_j \n        << obs_color_i << obs_color_j \n        << pred_color_i << pred_color_j \n        << maxI << maxJ << maxIJ_i << maxIJ_j\n        << vali << valj << valij \n        << pvali << pvalj << pvalij \n        << prvali << prvalj << prvalij \n        << iowner << jowner\n        << delf_i << delf_j;\n    }\n    void load(graphlab::iarchive& arc) \n    {\n        arc >> i >> j \n        >> deg_i >> deg_j\n        >> obs_color_i >> obs_color_j \n        >> pred_color_i >> pred_color_j \n        >> maxI >> maxJ >> maxIJ_i >> maxIJ_j\n        >> vali >> valj >> valij\n        >> pvali >> pvalj >> pvalij\n        >> prvali >> prvalj >> prvalij\n        >> iowner >> jowner\n        >> delf_i >> delf_j;\n    }\n}; // End of vertex data\n\n\n// /**\n//  * The data associated with a pair of factors in a pairwise MRF\n//  */\n//struct edge_data : public graphlab::IS_POD_TYPE \n//{\n//    // primal labelling; We assume pairwise factors, so intersection has\n//    // a single node\n//    int pred_color;\n//    \n//    // current contribution to LP dual value\n//    double dval;\n//    // current contribution to MAP value\n//    double pval;\n//    // current contribution to MAPrep value\n//    double prval;\n//    \n//    edge_data():\n//    pred_color(0),\n//    dval(0), pval(0), prval(0)\n//    {}\n//     \n//    void save(graphlab::oarchive& arc) const \n//    {\n//        arc << pred_color\n//        << dval << pval << prval; \n//    }\n//    void load(graphlab::iarchive& arc) \n//    {\n//        arc >> pred_color\n//        >> dval >> pval >> prval;\n//    }\n//}; // End of edge data\ntypedef graphlab::empty edge_data;\n\n/**\n * The graph type\n */\ntypedef graphlab::distributed_graph<vertex_data, edge_data> graph_type;\n\n\n// GraphLab Vertex Program ====================================================\n/**\n * The type passed around during the gather phase\n */\nstruct gather_type \n{\n    vector delf_i, delf_j;\n    \n    gather_type& operator+=(const gather_type& other) \n    {\n        if(!other.delf_i.size() == 0) \n        {\n            if(delf_i.size() == 0) delf_i = other.delf_i;\n            else delf_i += other.delf_i;\n        }\n        if(!other.delf_j.size() == 0) \n        {\n            if(delf_j.size() == 0) delf_j = other.delf_j;\n            else delf_j += other.delf_j;\n        }\n        return *this;\n    } // end of operator +=\n    void save(graphlab::oarchive& arc) const \n    {\n        arc << delf_i << delf_j;\n    }\n    void load(graphlab::iarchive& arc) \n    {\n        arc >> delf_i >> delf_j;\n    }\n}; // end of gather type\n\n\n\n/** \n * The core belief propagation update function.  This update satisfies\n * the graphlab update_function interface.  \n */\nclass mplp_vertex_program : \npublic graphlab::ivertex_program<graph_type, gather_type, \ngraphlab::messages::sum_priority>,\npublic graphlab::IS_POD_TYPE {\nprivate:\n    double priority;\npublic:\n    \n    mplp_vertex_program() : priority(0) { }\n    \n    // void save(graphlab::oarchive& arc) const { /** save members */ }\n    // void load(graphlab::iarchive& arc) { /** load members */ }\n    \n    /**\n     * This function is now called in the main by invoking:\n     * engine.transform_vertices(mplp_vertex_program::init)\n     */\n    static void init_vertex_data(icontext_type& context, vertex_type& vertex)\n    { \n        vertex_data& vdata = vertex.data();\n        \n        // Create zero messages\n        vdata.delf_i = vector::Zero(NCOLORS);\n        vdata.delf_j = vector::Zero(NCOLORS);\n        \n        // create temporary node potentials\n        vector theta_i = make_unary_potential(vertex, 'i');\n        vector theta_j = make_unary_potential(vertex, 'j');\n\n        // if we own i\n        if (vdata.iowner) \n        {\n            // get dual contribution\n            vdata.vali = theta_i.maxCoeff(&vdata.maxI); \n\n            // get primal contribution\n            vdata.pred_color_i = vdata.maxI;\n            vdata.pvali = vdata.vali;\n            \n            // also update the global copy\n            PRED_COLOR[vdata.i] = vdata.pred_color_i;\n\n            // get rep primal contribution\n            vdata.prvali = vdata.pvali;\n        }\n        else // if we don't own then just copy over the global predicted color\n            vdata.pred_color_i = PRED_COLOR[vdata.i];\n\n        // if we own j\n        if (vdata.jowner) \n        {\n            // get dual contribution\n            vdata.valj = theta_j.maxCoeff(&vdata.maxJ); \n            \n            // get primal contribution\n            vdata.pred_color_j = vdata.maxJ;\n            vdata.pvalj = vdata.valj;\n            \n            // also update the global copy\n            PRED_COLOR[vdata.j] = vdata.pred_color_j;\n\n            // get rep primal contribution\n            vdata.prvalj = vdata.pvalj;\n        }\n        else \n            vdata.pred_color_j = PRED_COLOR[vdata.j];\n        \n        // we always own edge i,j\n        vdata.valij = THETA_ij.maxCoeff(&vdata.maxIJ_i,&vdata.maxIJ_j); \n        vdata.pvalij = THETA_ij(vdata.pred_color_i, vdata.pred_color_j);\n        vdata.prvalij = vdata.pvalij;\n             \n        mutex.lock();\n        LPval += vdata.vali; LPval += vdata.valj; LPval += vdata.valij;\n        MAPval += vdata.pvali; MAPval += vdata.pvalj; MAPval += vdata.pvalij;\n        MAPrepval += vdata.prvali; MAPrepval += vdata.prvalj; MAPrepval += vdata.prvalij;\n        mutex.unlock();\n\n        // debug code to check in all nodes are inited\n        if (vinit[vertex.id()] == 0)\n            vinit[vertex.id()] = 1;\n    }\n    \n    /**\n     * Recv message is called by the engine to receive a message to this\n     * vertex program.  The vertex program can use this to initialize\n     * any state before entering the gather phase.  If the vertex\n     * program does not implement this function then the default\n     * implementation (NOP) is used.\n     */\n    // void init(icontext_type& context, const vertex_type& vertex, \n    //                   const message_type& msg) { /** NOP */ }\n    \n    /**\n     * Since the MRF is undirected we will use all edges for gather and\n     * scatter\n     */\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    // Run the gather operation over all in edges\n    gather_type gather(icontext_type& context, const vertex_type& target_vertex, \n                       edge_type& edge) const \n    {\n        const vertex_type source_vertex = get_other_vertex(edge, target_vertex);   \n        const vertex_data& source_vdata = source_vertex.data();\n        const vertex_data& target_vdata = target_vertex.data();\n        \n        // Accumulate message\n        gather_type ret_value;\n        if (target_vdata.i == source_vdata.i)\n            ret_value.delf_i = source_vdata.delf_i;\n        else if (target_vdata.j == source_vdata.i)\n            ret_value.delf_j = source_vdata.delf_i;\n        else if (target_vdata.i == source_vdata.j)\n            ret_value.delf_i = source_vdata.delf_j;\n        else if (target_vdata.j == source_vdata.j)\n            ret_value.delf_j = source_vdata.delf_j;\n        else assert(false); // invalid state\n        \n        return ret_value;\n    } // end of gather\n    \n    /** Update the dual parameters */\n    void apply(icontext_type& context, vertex_type& vertex, \n               const gather_type& sum) \n    {\n        // Make sure this vertex has neighbours. Everyone should have neighbours\n        ASSERT_GT(vertex.num_in_edges() + vertex.num_out_edges(), 0);\n        \n        vertex_data& vdata = vertex.data();  \n        vector theta_i = make_unary_potential(vertex, 'i');\n        vector theta_j = make_unary_potential(vertex, 'j');\n                \n        ASSERT_EQ(THETA_ij.rows(), theta_i.size());\n        ASSERT_EQ(THETA_ij.rows(), sum.delf_i.size());\n        ASSERT_EQ(THETA_ij.cols(), theta_j.size());\n        ASSERT_EQ(THETA_ij.cols(), sum.delf_j.size());   \n        \n        // debug code to check in all nodes are applied\n        if (vapply[vertex.id()] == 0)\n            vapply[vertex.id()] = 1;\n        \n        \n        ////////////////////////////////////////////\n        // Update outgoing messages (coordinate descent)\n        \n        // Backup the old prediction\n        const vector old_delf_i = vdata.delf_i;\n        const vector old_delf_j = vdata.delf_j;\n        \n        // Update del fi\n        vdata.delf_i = -(theta_i + sum.delf_i)/2 + \n        (THETA_ij + (theta_j + sum.delf_j).transpose().replicate(THETA_ij.rows(),1)).\n        rowwise().maxCoeff()/2;\n        // Update del fj\n        vdata.delf_j = -(theta_j + sum.delf_j)/2 + \n        ((THETA_ij + (theta_i + sum.delf_i).replicate(1,THETA_ij.cols())).\n         colwise().maxCoeff()).transpose()/2;\n        \n        ////////////////////////////////////////////\n        // Compute contributions to dual, primal and rep primal\n        \n        // Remove contribution of old labels from LPval\n        double LPremove=0, MAPremove=0, MAPrepremove=0;\n        LPremove += vdata.vali; LPremove += vdata.valj; LPremove += vdata.valij;\n        MAPremove += vdata.pvali; MAPremove += vdata.pvalj; MAPremove += vdata.pvalij;\n        MAPrepremove += vdata.prvali; MAPrepremove += vdata.prvalj; MAPrepremove += vdata.prvalij;\n\n        // Update dual, primal and rep primal contributions. \n        // TODO: if primal labelling changes at a node we own, update it's edge potential too\n        if (vdata.iowner)\n        {\n            // reparameterized node potential\n            vector thetarep_i = theta_i + sum.delf_i + vdata.delf_i;\n            \n            vdata.vali = thetarep_i.maxCoeff(&vdata.maxI);\n            \n            vdata.pred_color_i = vdata.maxI;\n            vdata.pvali = theta_i[vdata.pred_color_i];\n            \n            PRED_COLOR[vdata.i] = vdata.pred_color_i;\n            \n            vdata.prvali = thetarep_i[vdata.pred_color_i];\n        } \n        else\n            vdata.pred_color_i = PRED_COLOR[vdata.i];\n        if (vdata.jowner)\n        {\n            // reparameterized node potential\n            vector thetarep_j = theta_j + sum.delf_j + vdata.delf_j;\n            \n            vdata.valj = thetarep_j.maxCoeff(&vdata.maxJ);\n            \n            vdata.pred_color_j = vdata.maxJ;\n            vdata.pvalj = theta_j[vdata.pred_color_j];\n            \n            PRED_COLOR[vdata.j] = vdata.pred_color_j;\n\n            vdata.prvalj = thetarep_j[vdata.pred_color_j];\n        }\n        else\n            vdata.pred_color_j = PRED_COLOR[vdata.j];\n        \n        // We always own edge i,j\n        matrix thetarep_ij = THETA_ij - (vdata.delf_i.replicate(1,THETA_ij.cols()))\n                            - (vdata.delf_j.transpose().replicate(THETA_ij.rows(),1));\n        \n        vdata.valij = thetarep_ij.maxCoeff(&vdata.maxIJ_i, &vdata.maxIJ_j);\n        vdata.pvalij = THETA_ij(vdata.pred_color_i, vdata.pred_color_j);\n        vdata.prvalij = thetarep_ij(vdata.pred_color_i, vdata.pred_color_j);\n        \n        mutex.lock();\n        LPval -= LPremove; MAPval -= MAPremove; MAPrepval -= MAPrepremove;\n        LPval += vdata.vali; LPval += vdata.valj; LPval += vdata.valij;\n        MAPval += vdata.pvali; MAPval += vdata.pvalj; MAPval += vdata.pvalij;\n        MAPrepval += vdata.prvali; MAPrepval += vdata.prvalj; MAPrepval += vdata.prvalij;\n        mutex.unlock();\n        \n        ////////////////////////////////////////////\n        // Debugging printing and residuals\n        \n        //std::cout << vertex.id() << \": \" << vdata.i << \",\" << vdata.j << \"\\n\";\n        if (0) // (vdata.i == 0 )\n        {\n            mutex.lock();\n            std::cout << \"Applying at vertex: \" << vertex.id() << \"(\" << vdata.i << \",\" << vdata.j << \")\\n\";\n            \n            std::cout << LPval << \",\" << MAPval << \",\" << MAPrepval << \"\\t\" ;        \n            int vinitsum = 0, vapplysum = 0;\n            //std::vector<graphlab::atomic<int> >::iterator it;\n            std::vector<int>::iterator it;\n            for (it = vinit.begin(); it < vinit.end(); ++it)\n                vinitsum += *it;\n            for (it = vapply.begin(); it < vapply.end(); ++it)\n                vapplysum += *it;\n            \n            // if all vertices have been visited start counting again\n            if (vapply.size() == vapplysum)\n                for (int i=0; i!=vapply.size(); ++i)\n                    vapply[i] = 0;\n            \n            std::cout << \"Verted Id: \" << vertex.id() << \" \"  << vdata.i << \",\" << vdata.j << \" \"; \n            std::cout << \"Inited: \" << vinitsum << \" Applied: \" << vapplysum << \"\\n\";\n            if (vinit.size() == vinitsum)\n                std::cout << \"Restarting counting of apply\\n\";\n            std::cout.flush();\n            mutex.unlock();\n        }\n        \n        if (0)//vdata.i == 1) \n        {\n            std::cout << \"\\n\\n\";\n            \n            std::cout << \"Pairwise Potential\\n\" << THETA_ij << \"\\n\\n\";\n            std::cout << \"theta_ij reparameterized: \\n\" <<         \n            (THETA_ij - vdata.delf_i.replicate(1,THETA_ij.cols()) \n             - vdata.delf_j.transpose().replicate(THETA_ij.rows(),1)   )  << \"\\n\\n\";\n            std::cout << \"maxIJ_i: \" << vdata.maxIJ_i << \" maxIJ_j: \" << vdata.maxIJ_j << \"\\n\\n\";\n            \n            std::cout << \"thetai \\n\" << theta_i << \"\\n\\n\";\n            std::cout << \"sum of incomming messages into i\\n\" << sum.delf_i << \"\\n\\n\";\n            std::cout << \"outgoing message to i\\n\" << vdata.delf_i << \"\\n\\n\";\n            std::cout << \" Reparamterized thetai\\n\" << (theta_i + sum.delf_i + vdata.delf_i) << \"\\n\\n\";\n            std::cout << \"maxI: \" << vdata.maxI << \"\\n\\n\";\n            \n            std::cout << \"thetaj \\n\" << theta_j << \"\\n\\n\";\n            std::cout << \"sum of incomming messages into j\\n\" << sum.delf_j << \"\\n\\n\";\n            std::cout << \"outgoing message to j\\n\" << vdata.delf_j << \"\\n\\n\";\n            std::cout << \" Reparamterized thetaj\\n\" << (theta_j + sum.delf_j + vdata.delf_j) << \"\\n\\n\";\n            std::cout << \"maxJ: \" << vdata.maxJ << \"\\n\\n\";\n            \n            std::cout << \"thetaij + j message\\n\" << (THETA_ij + sum.delf_j.transpose().replicate(THETA_ij.rows(),1))/2 << \"\\n\\n\";\n            \n            std::cout << (THETA_ij + sum.delf_j.transpose().replicate(THETA_ij.rows(),1)).\n            rowwise().maxCoeff()/2 << std::endl << std::endl;\n            \n            std::cout << \"thetaij + i message\\n\" << (THETA_ij + sum.delf_i.replicate(1,THETA_ij.cols()))/2 << \"\\n\\n\";\n            std::cout << \t  ((THETA_ij + sum.delf_i.replicate(1,THETA_ij.cols())).\n                               colwise().maxCoeff()).transpose()/2 << \"\\n\\n\";\n            \n            std::cout << \"Old del_fi\\n\" << vdata.delf_i << \"\\n\\n\";\n            std::cout << \"Old del_fj\\n\" << vdata.delf_j << \"\\n\\n\";\n            std::cout << \"New del_fi\\n\" << -(theta_i + sum.delf_i)/2 + \n            (THETA_ij + (theta_j + sum.delf_j).transpose().replicate(THETA_ij.rows(),1)).\n            rowwise().maxCoeff()/2 << \"\\n\\n\";\n            \n            std::cout << \"New del_fj\\n\" << -(theta_j + sum.delf_j)/2 + \n            ((THETA_ij + (theta_i + sum.delf_i).replicate(1,THETA_ij.cols())).\n             colwise().maxCoeff()).transpose()/2 << \"\\n\\n\";\n            \n            getchar();\n        }\n        \n        // const double residual = (vdata.delf_i - old_delf_i).cwiseAbs().sum() +\n        // (vdata.delf_j - old_delf_j).cwiseAbs().sum();\n        \n        //priority = residual;\n        priority = LPval - MAPval;\n        //std::cout << \"priority: \" << priority << std::endl;\n        //std::cout << LPval << std::endl;\n        //test code; for now, only run 1 iteration\n        //priority = 0;\n    } // end of apply\n    \n    /**\n     * Since the MRF is undirected we will use all edges for gather and\n     * scatter\n     */\n    edge_dir_type scatter_edges(icontext_type& context,\n                                const vertex_type& vertex) const { \n        //return priority < BOUND? graphlab::NO_EDGES : graphlab::ALL_EDGES; \n        return graphlab::ALL_EDGES;\n    }; // end of gather_edges \n    \n    \n    /** reschedule neighbors with a given priority and updated\n     predictions on each edge*/\n    void scatter(icontext_type& context, const vertex_type& vertex, \n                 edge_type& edge) const {  \n        context.signal(get_other_vertex(edge, vertex), priority);\n    } // end of scatter\n    \nprivate:\n    \n    /**\n     * Construct the unary evidence potential\n     */\n    static vector make_unary_potential(const vertex_type& vertex, \n                                       const char varid) {\n        vector potential(NCOLORS);\n        const double obs = varid == 'i'? \n        vertex.data().obs_color_i : vertex.data().obs_color_j;\n        const double sigmaSq = SIGMA*SIGMA;\n        for(int pred = 0; pred < potential.size(); ++pred) {\n            potential(pred) = -(obs - pred)*(obs - pred) / (2.0 * sigmaSq);\n        }\n        //potential /= std::abs(potential.sum());\n        \n        //float tmp = potential.minCoeff();\n        //potential.array() -= tmp; // (float) potential.minCoeff();\n        return potential;\n    } // end of make_potentail\n    \n    /**\n     * Return the other vertex\n     */\n    vertex_type get_other_vertex(edge_type& edge, \n                                 const vertex_type& vertex) const {\n        return vertex.id() == edge.source().id()? edge.target() : edge.source();\n    } // end of other_vertex\n    \n}; // end of MPLP vertex program\n\n\n\n\n/**\n * Define the engine type\n */\n//typedef graphlab::synchronous_engine<mplp_vertex_program> engine_type;\ntypedef graphlab::async_consistent_engine<mplp_vertex_program> engine_type;\n//typedef graphlab::asynchronous_consistent_engine<mplp_vertex_program> engine_type;\n\n\n\n\n/////////////////////////////////////////////////////////////////////////////////////\n// Aggregator functions to compute primal & dual values\ndouble get_energy_fun(mplp_vertex_program::icontext_type& context, const mplp_vertex_program::vertex_type& vertex) \n{\n    double tmp = 0;\n    \n    const vertex_data &vdata = vertex.data();\n    \n    if (vdata.iowner)\n        tmp += vdata.vali;\n    if (vdata.jowner)\n        tmp += vdata.valj;\n    tmp += vdata.valij;\n\n    return tmp;\n}\n\nvoid finalize_fun(mplp_vertex_program::icontext_type& context, double total) \n{\n    if(context.procid() == 0) \n        std::cout << \"Dual value: \" << total << std::endl;\n}\n\n\n\n// Helper functions ===========================================================>\ngraphlab::vertex_id_type pixel_ind(size_t rows, size_t cols,\n                                   size_t r, size_t c) {\n    return r * cols + c;\n}; // end of pixel_ind\n\n\ngraphlab::vertex_id_type factor_ind(size_t rows, size_t cols,\n                                    size_t i, size_t j) {\n    if(i > j) std::swap(i,j);\n    return i * (rows * cols) + j;\n}; // end of factor_ind\n\ngraphlab::vertex_id_type factor_ind2(size_t rows, size_t cols,\n                                    size_t i, size_t j) {\n    if(i > j) std::swap(i,j);\n    \n    if (j == (i+1)) // horizontal edge\n        return i - std::floor(i/cols);\n    else if (j == (i+cols))\n        return rows*(cols-1) + i;\n    else\n      std::cout << \"Problem \";\n      //ASSERT_TRUE(false);\n    return 0;\n}; // end of factor_ind\n\n\nvoid create_synthetic_cluster_graph(graphlab::distributed_control& dc,\n                                    graph_type& graph,\n                                    const size_t rows, const size_t cols) {\n    dc.barrier();\n    // Generate the image on all machines --------------------------------------->\n    // Need to ensure that all machines generate the same noisy image\n    graphlab::random::generator gen; gen.seed(314);\n    std::vector<float>    obs_pixels(rows * cols);\n    std::vector<uint16_t> true_pixels(rows * cols);\n    const double center_r = rows / 2.0;\n    const double center_c = cols / 2.0;\n    const double max_radius = std::min(rows, cols) / 2.0;\n    for(size_t r = 0; r < rows; ++r) \n    {\n        for(size_t c = 0; c < cols; ++c) \n        {\n            // Compute the true pixel value\n            const double distance = sqrt((r-center_r)*(r-center_r) + \n                                         (c-center_c)*(c-center_c));\n            // Compute ring of sunset\n            const uint16_t ring_color =  \n            std::floor(std::min(1.0, distance/max_radius) * (NCOLORS - 1) );\n            // Compute the true pixel color by masking with the horizon\n            const uint16_t true_color = r < rows/2 ? ring_color : 0;\n            // compute the predicted color\n            const float obs_color = true_color + gen.normal(0, SIGMA);\n            // determine the true pixel id\n            const size_t pixel = pixel_ind(rows,cols,r,c);\n            true_pixels[pixel] = true_color; obs_pixels[pixel] = obs_color;\n        } // end of loop over cols\n    } // end of loop over rows\n    \n    if(dc.procid() == 0) \n    {\n        //int nedges = 2*rows*cols -rows-cols;\n        int nedges = factor_ind2(rows,cols,rows*cols-cols,rows*cols);\n        //vinit = vector::Zero(2*rows*cols -rows-cols);\n        //vapply = vector::Zero(2*rows*cols -rows-cols);\n        vinit.clear(); vinit.resize(nedges, 0);\n        vapply.clear(); vapply.resize(nedges,0);\n\n        int max_vid = 0; \n        \n        PRED_COLOR = vector::Zero(rows*cols);\n        int ownercount = 0; \n        \n        // temp code \n        std::ofstream ne, ee; \n        ne.open(\"./node_en.txt\");\n        //ee.open(\"./edge_en.txt\");\n        \n        ne << rows*cols << \" \" << NCOLORS << \" \"\n        << 0 << \" \" << rows << \" \" << cols << std::endl;\n        // end temp\n        \n        std::vector<graphlab::vertex_id_type> nbrs;\n        // load the graph\n        for(size_t r = 0; r < rows; ++r) \n        {\n            for(size_t c = 0; c < cols; ++c) \n            {\n                // temp code to write out potential to file:\n                std::vector<double> potential(NCOLORS);\n                const double obs = obs_pixels[pixel_ind(rows,cols,r,c)];\n                const double sigmaSq = SIGMA*SIGMA;\n                double sum = 0;\n                for(int pred = 0; pred < potential.size(); ++pred) \n                {\n                    potential[pred] = +(obs - pred)*(obs - pred) / (2.0 * sigmaSq);\n                    sum += potential[pred];\n                }\n                //                for(int pred = 0; pred < potential.size(); ++pred)                 \n                //                    potential[pred] /= sum;\n                //                ne << true_pixels[pixel_ind(rows,cols,r,c)] << \" \" <<  obs << \" \" << potential << std::endl;\n                //                ne << 4 - int((r==0)||(r==(rows-1))) - int((c==0)||(c==(cols-1))) << \" \" << potential << std::endl;\n                ne << potential << std::endl;\n                // end temp\n                \n                // Add the two vertices (factors to the right and below this\n                // pixel)\n                if(r + 1 < rows) \n                {\n                    vertex_data vdata;\n                    vdata.i = pixel_ind(rows,cols,r,c);\n                    vdata.j = pixel_ind(rows,cols,r+1,c);\n                    vdata.deg_i = 4 - int((r==0)||(r==(rows-1))) - int((c==0)||(c==(cols-1)));\n                    vdata.deg_j = 4 - int(((r+1)==0)||((r+1)==(rows-1))) - int((c==0)||(c==(cols-1)));\n                    vdata.obs_color_i = obs_pixels[vdata.i];\n                    vdata.obs_color_j = obs_pixels[vdata.j];\n                    graph.add_vertex(factor_ind2(rows,cols,vdata.i,vdata.j), vdata);\n                    \n                    // temp code\n                    max_vid = std::max((int)factor_ind2(rows,cols,vdata.i,vdata.j), max_vid); \n                }\n                if(c + 1 < cols) \n                {\n                    vertex_data vdata;\n                    vdata.i = pixel_ind(rows,cols,r,c);\n                    vdata.j = pixel_ind(rows,cols,r,c+1);\n                    vdata.deg_i = 4 - int((r==0)||(r==(rows-1))) - int((c==0)||(c==(cols-1)));\n                    vdata.deg_j = 4 - int((r==0)||(r==(rows-1))) - int(((c+1)==0)||((c+1)==(cols-1)));\n                    vdata.obs_color_i = obs_pixels[vdata.i];\n                    vdata.obs_color_j = obs_pixels[vdata.j];\n\n                    vdata.iowner = true; // give i-ownership to horizontal edges\n                    ++ownercount;\n                    if ((c+1)==(cols-1)) // and j-ownership too if last node in this row\n                    {\n                        vdata.jowner = true;\n                        ++ownercount;\n                    }\n                    graph.add_vertex(factor_ind2(rows,cols,vdata.i,vdata.j), vdata);\n                    \n                    // temp code\n                    max_vid = std::max((int)factor_ind2(rows,cols,vdata.i,vdata.j), max_vid); \n                }\n                // Compute all the factors that contain this pixel\n                nbrs.clear();\n                if(r+1 < rows)\n                    nbrs.push_back(factor_ind2(rows,cols,\n                                              pixel_ind(rows,cols,r,c),\n                                              pixel_ind(rows,cols,r+1,c)));\n                if(r-1 < rows)\n                    //if(r-1 >= 0)\n                    nbrs.push_back(factor_ind2(rows,cols,\n                                              pixel_ind(rows,cols,r-1,c),\n                                              pixel_ind(rows,cols,r,c)));\n                if(c+1 < cols)\n                    nbrs.push_back(factor_ind2(rows,cols,\n                                              pixel_ind(rows,cols,r,c),\n                                              pixel_ind(rows,cols,r,c+1)));\n                if(c-1 < cols)\n                    //if(c-1 >= 0)\n                    nbrs.push_back(factor_ind2(rows,cols,\n                                              pixel_ind(rows,cols,r,c-1),\n                                              pixel_ind(rows,cols,r,c)));\n                // construct the clique over the factors\n                for(size_t i = 0; i < nbrs.size(); ++i) \n                {\n                    for(size_t j = i+1; j < nbrs.size(); ++j) \n                    {\n                        graph.add_edge(nbrs[i], nbrs[j]);\n                    }\n                }\n            } // end of for cols\n        } // end of for rows\n        \n        // temp code\n        ne.close(); //ee.close();\n        std::cout << \"Max vid fed into graphlab: \" << max_vid << \"\\n\";\n        std::cout << \"No. of owners: \" << ownercount << \"\\n\";\n    } // end of if proc 0\n    dc.barrier();\n} // end of create synthetic cluster graph\n\n\n\n\n\nvoid initialize_theta_ij(const std::string& smoothing,\n                         const double lambda) \n{\n    THETA_ij.resize(NCOLORS, NCOLORS);\n    // Set the smoothing type\n    if(smoothing == \"laplace\") \n    {\n        for(int i = 0; i < THETA_ij.rows(); ++i) \n            for(int j = 0; j < THETA_ij.cols(); ++j) \n                THETA_ij(i,j) = -std::abs(double(i) - double(j)) * lambda;\n    } \n    else \n    {   \n        for(int i = 0; i < THETA_ij.rows(); ++i) \n            for(int j = 0; j < THETA_ij.cols(); ++j) \n                THETA_ij(i,j) = -(i == j? 0 : lambda);\n    } \n} // end of initialize_theta_ij\n\n\n\ntemplate<typename T>\nstruct merge_reduce {\n    std::set<T> values;\n    void save(graphlab::oarchive& arc) const { arc << values; }\n    void load(graphlab::iarchive& arc) { arc >> values; }\n    merge_reduce& operator+=(const merge_reduce& other) {\n        values.insert(other.values.begin(), other.values.end());\n        return *this;\n    }\n}; // end of merge_reduce\n\ntypedef std::pair<graphlab::vertex_id_type, float> pred_pair_type; \ntypedef merge_reduce<pred_pair_type> merge_reduce_type;\n\nmerge_reduce_type pred_map_function(graph_type::vertex_type vertex) {\n    merge_reduce<pred_pair_type> ret;\n    ret.values.insert(pred_pair_type(vertex.data().i, vertex.data().pred_color_i));\n    ret.values.insert(pred_pair_type(vertex.data().j, vertex.data().pred_color_j));\n    return ret;\n} // end of pred_map_function\n\nmerge_reduce_type obs_map_function(graph_type::vertex_type vertex) {\n    merge_reduce<pred_pair_type> ret;\n    ret.values.insert(pred_pair_type(vertex.data().i, vertex.data().obs_color_i));\n    ret.values.insert(pred_pair_type(vertex.data().j, vertex.data().obs_color_j));\n    return ret;\n} // end of obs_map_function\n\n\n\n\nstd::pair<int,int> ind2sub(size_t rows, size_t cols,\n                           size_t ind) {\n    return std::make_pair(ind / cols, ind % cols);\n}; // end of sub2ind\n\n\n// /**\n//  * Saving an image as a pgm file.\n//  */\n// void save_image(const size_t rows, const size_t cols,\n//                 const std::set<pred_pair_type>& values,\n//                 const std::string& fname) {\n//     std::cout << \"NPixels: \" << values.size() << std::endl;\n//     image img(rows, cols);\n//     foreach(pred_pair_type pair, values) \n//     img.pixel(pair.first) = pair.second;\n//     img.save(fname);\n// } // end of save_image\n\n\n/**\n * Saving an image as a pgm file.\n */\n\nvoid save_image(const size_t rows, const size_t cols,\n                const std::set<pred_pair_type>& values,\n                const std::string& fname) {\n  std::cout << \"NPixels: \" << values.size() << std::endl;\n  // determine the max and min colors\n  float max_color = -std::numeric_limits<float>::max();\n  float min_color =  std::numeric_limits<float>::max();\n  foreach(pred_pair_type pair, values) {\n    max_color = std::max(max_color, pair.second);\n    min_color = std::min(min_color, pair.second);\n  }\n\n  cv::Mat img(cols, rows, CV_8UC1);\n  foreach(pred_pair_type pair, values) {\n    std::pair<int,int> coords = ind2sub(rows,cols, pair.first);\n    float value = (pair.second - min_color) / (max_color - min_color);\n    int color = 255 * value > 255 ? 255 : 255 * value;\n    img.at<unsigned char>(coords.first, coords.second) = color;\n  }\n  cv::imwrite(fname, img);\n}\n\n\n\n\n// MAIN =======================================================================>\nint main(int argc, char** argv) {\n    std::cout << \"This program creates and denoises a synthetic \" << std::endl\n    << \"image using loopy belief propagation inside \" << std::endl\n    << \"the graphlab framework.\" << std::endl;\n    \n    // // set the global logger\n    // global_logger().set_log_level(LOG_WARNING);\n    // global_logger().set_log_to_console(true);\n    \n    // Set initial values for members ------------------------------------------->\n    NCOLORS = 5;\n    SIGMA = 2;\n    BOUND = 1E-4;\n    \n    \n//    size_t nrows = 200;\n//    size_t ncols = 200;\n    size_t nrows = 20;\n    size_t ncols = 20;\n    double lambda = 0.2;\n    \n    std::string smoothing = \"square\";\n    \n    std::string orig_fn =  \"source_img.jpeg\";\n    std::string noisy_fn = \"noisy_img.jpeg\";\n    std::string pred_fn = \"pred_img.jpeg\";\n    \n    // std::string orig_fn =  \"source_img.pgm\";\n    // std::string noisy_fn = \"noisy_img.pgm\";\n    // std::string pred_fn = \"pred_img.pgm\";\n    \n    \n    \n    // Parse command line arguments --------------------------------------------->\n    graphlab::command_line_options clopts(\"Loopy BP image denoising\");\n    clopts.attach_option(\"bound\", BOUND,\n                         \"Residual termination bound\");\n    clopts.attach_option(\"ncolors\", NCOLORS,\n                         \"The number of colors in the noisy image\");\n    clopts.attach_option(\"sigma\", SIGMA,\n                         \"Standard deviation of noise.\");\n    clopts.attach_option(\"nrows\", nrows,\n                         \"The number of rows in the noisy image\");\n    clopts.attach_option(\"ncols\", ncols,\n                         \"The number of columns in the noisy image\");\n    clopts.attach_option(\"lambda\", lambda,\n                         \"Smoothness parameter (larger => smoother).\");\n    clopts.attach_option(\"smoothing\", smoothing,\n                         \"Options are {square, laplace}\");\n    clopts.attach_option(\"orig\", orig_fn,\n                         \"Original image file name.\");\n    clopts.attach_option(\"noisy\", noisy_fn,\n                         \"Noisy image file name.\");\n    clopts.attach_option(\"pred\", pred_fn,\n                         \"Predicted image file name.\");\n    \n    ///! Initialize control plain using mpi\n    graphlab::mpi_tools::init(argc, argv);\n    const bool success = clopts.parse(argc, argv);\n    if(!success) {\n        clopts.print_description();\n        graphlab::mpi_tools::finalize();\n        return EXIT_FAILURE;\n    }\n    \n    ///! Create a distributed control object \n    graphlab::distributed_control dc;\n    ///! display settings  \n    if(dc.procid() == 0) {\n        std::cout << \"ncpus:          \" << clopts.get_ncpus() << std::endl\n        << \"bound:          \" << BOUND << std::endl\n        << \"colors:         \" << NCOLORS << std::endl\n        << \"nrows:           \" << nrows << std::endl\n        << \"ncols:           \" << ncols << std::endl\n        << \"sigma:          \" << SIGMA << std::endl\n        << \"lambda:         \" << lambda << std::endl\n        << \"smoothing:      \" << smoothing << std::endl\n        << \"scheduler:      \" << clopts.get_scheduler_type() << std::endl\n        << \"orig_fn:        \" << orig_fn << std::endl\n        << \"noisy_fn:       \" << noisy_fn << std::endl\n        << \"pred_fn:        \" << pred_fn << std::endl;\n    }\n    \n    \n    \n    \n    // Create synthetic images -------------------------------------------------->\n    std::cout << \"Creating a synthetic noisy image.\" << std::endl;\n    graph_type graph(dc, clopts);\n    create_synthetic_cluster_graph(dc, graph, nrows, ncols);\n    std::cout << \"Finalizing the graph.\" << std::endl;\n    graph.finalize();\n    \n    std::cout << \"Collect the noisy image. \" << std::endl;\n    merge_reduce_type obs_image = \n    graph.map_reduce_vertices<merge_reduce_type>(obs_map_function);\n    std::cout << \"saving the noisy image.\" << std::endl;\n    if(dc.procid() == 0) {\n        save_image(nrows, ncols, obs_image.values, noisy_fn);\n    }\n    \n    // Initialze the edge factor ----------------------------------------------->\n    std::cout << \"Initializing shared edge factor. \" << std::endl;\n    // dummy variables 0 and 1 and num_rings by num_rings\n    initialize_theta_ij(smoothing, lambda);\n    if(dc.procid() == 0) std::cout << THETA_ij << std::endl;\n    \n    // Create the engine -------------------------------------------------------->\n    std::cout << \"Creating the engine. \" << std::endl;\n    engine_type engine(dc, graph, clopts);\n\n    engine.add_vertex_aggregator<double>(\"energy\", get_energy_fun, finalize_fun);\n    engine.aggregate_periodic(\"energy\", 3); // run every 3 seconds\n\n    engine.transform_vertices(mplp_vertex_program::init_vertex_data);\n\n    std::cout << \"Scheduling all vertices\" << std::endl;\n    engine.signal_all();\n    std::cout << \"Starting the engine\" << std::endl;\n    engine.start();\n    const float runtime = engine.elapsed_seconds();\n    size_t update_count = engine.num_updates();\n    std::cout << \"Finished Running engine in \" << runtime \n    << \" seconds.\" << std::endl\n    << \"Total updates: \" << update_count << std::endl\n    << \"Efficiency: \" << (double(update_count) / runtime)\n    << \" updates per second \"\n    << std::endl;  \n    \n    \n    // Saving the output -------------------------------------------------------->\n    std::cout << \"Saving the predicted image\" << std::endl;\n    std::cout << \"Collect the noisy image. \" << std::endl;\n    merge_reduce_type pred_image = \n    graph.map_reduce_vertices<merge_reduce_type>(pred_map_function);\n    std::cout << \"saving the pred image.\" << std::endl;\n    if(dc.procid() == 0) {\n        save_image(nrows, ncols, pred_image.values, pred_fn);\n    }\n    \n    std::cout << \"Done!\" << std::endl;\n    graphlab::mpi_tools::finalize();\n    return EXIT_SUCCESS;\n} // End of main\n\n\n\n", "meta": {"hexsha": "1713c245e55caf7d6a2c5c26173dffe797283e08", "size": 39234, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "toolkits/graphical_models/mplp_denoise.cpp", "max_stars_repo_name": "coreyp1/graphlab", "max_stars_repo_head_hexsha": "637be90021c5f83ab7833ca15c48e76039057969", "max_stars_repo_licenses": ["ECL-2.0", "Apache-2.0"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2017-11-19T11:46:55.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-08T22:45:55.000Z", "max_issues_repo_path": "toolkits/graphical_models/mplp_denoise.cpp", "max_issues_repo_name": "coreyp1/graphlab", "max_issues_repo_head_hexsha": "637be90021c5f83ab7833ca15c48e76039057969", "max_issues_repo_licenses": ["ECL-2.0", "Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "toolkits/graphical_models/mplp_denoise.cpp", "max_forks_repo_name": "coreyp1/graphlab", "max_forks_repo_head_hexsha": "637be90021c5f83ab7833ca15c48e76039057969", "max_forks_repo_licenses": ["ECL-2.0", "Apache-2.0"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2015-12-15T12:12:23.000Z", "max_forks_repo_forks_event_max_datetime": "2019-10-16T16:48:40.000Z", "avg_line_length": 36.5647716682, "max_line_length": 133, "alphanum_fraction": 0.5380027527, "num_tokens": 9936, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6477982179521102, "lm_q2_score": 0.46490157137338844, "lm_q1q2_score": 0.30116240945881684}}
{"text": "/*\n * self_similarity.hpp\n *\n *  Created on: Jan 25, 2012\n *      Author: lbossard\n */\n\n#ifndef VISION_FEATURES_SELF_SIMILARITY_HPP_\n#define VISION_FEATURES_SELF_SIMILARITY_HPP_\n\n#include \"low_level_feature_extractor.hpp\"\n\n#include <iostream>\n\n#include <boost/math/constants/constants.hpp>\n#include <opencv2/highgui/highgui.hpp>\n#include <opencv2/imgproc/imgproc.hpp>\nnamespace vision\n{\nnamespace features\n{\n\n\nclass SelfSimilarity\n{\npublic:\n    // Andrea Vedaldi: Multiple Kernels for Object Detection: 5 40 3 10\n    // Ken Chatfield: Efficient Retrieval of Deformable Shape Classes using Local Self-Similarities  5 40 12 3\n\n    SelfSimilarity(\n            unsigned int patch_size = 5,\n            unsigned int window_radius = 40,\n            unsigned int radius_bin_count = 3,\n            unsigned int angle_bin_count = 10,\n            float var_noise=25*3*16,\n            unsigned int auto_var_radius=1);\n\n    virtual ~SelfSimilarity();\n\n    void setParameters(unsigned int patch_size,\n            unsigned int window_radius,\n            unsigned int radius_bin_count,\n            unsigned int angle_bin_count,\n            float var_noise,\n            unsigned int auto_var_radius);\n\n    bool extract(const cv::Mat& image, const cv::Point& location, cv::Mat_<float>& descriptor) const;\n\n    void compute_distance_surface(const cv::Mat& image, const cv::Point& loaction, cv::Mat_<float>& distance_surface) const;\n\n    void compute_descriptor(const cv::Mat_<float>& distance_surface, cv::Mat_<float>& descriptor) const;\n\n    inline const cv::Mat_<int>& getBinMap() const;\n    inline static float ssd_slow(const cv::Mat_<cv::Vec3b>& a, const cv::Mat_<cv::Vec3b>& b);\n\n    inline static float ssd3(const cv::Mat_<cv::Vec3b>& patch_a, const cv::Mat_<cv::Vec3b>& patch_b);\n    inline static float ssd1(const cv::Mat_<uchar>& patch_a, const cv::Mat_<uchar>& patch_b);\n\n    inline unsigned int descriptorLength() const;\n\nprotected:\n\nprivate:\n\n    unsigned int patch_size_; // dimension of the inner patch\n    unsigned int window_radius_; // dimension of the outer path\n    unsigned int radius_bin_count_;\n    unsigned int angle_bin_count_;\n    float var_noise_;\n\n    cv::Mat_<int> bin_map_;\n    std::vector<cv::Point> autovar_indices_;\n\n};\n\n\nclass SelfSimilarityExtractor : public LowLevelFeatureExtractor\n{\npublic:\n    SelfSimilarityExtractor(\n                bool color_ssd = false,\n                unsigned int patch_size = 5,\n                unsigned int window_radius = 40,\n                unsigned int radius_bin_count = 3,\n                unsigned int angle_bin_count = 10,\n                float var_noise=25*3*16,\n                unsigned int auto_var_radius=1);\n\n    virtual ~SelfSimilarityExtractor();\n\n\n    void setSelfSimilarityParameters(\n                unsigned int patch_size,\n                unsigned int window_radius,\n                unsigned int radius_bin_count,\n                unsigned int angle_bin_count,\n                float var_noise,\n                unsigned int auto_var_radius);\n\n    virtual void extract_at_extremas(const cv::Mat& image,\n             cv::Mat_<float>* descriptors,\n             const cv::Mat_<uchar>& mask) const {\n      CHECK(false) << \"not implemented.\";\n    }\n\n    virtual cv::Mat_<float> denseExtract(\n            const cv::Mat& image,\n            std::vector<cv::Point>& descriptor_locations,\n            const cv::Mat_<uchar>& mask = cv::Mat_<char>()\n    ) const;\n\n    virtual unsigned int descriptorLength() const;\nprivate:\n    SelfSimilarity self_similarity_;\n    bool color_ssd_;\n\n};\n////////////////////////////////////////////////////////////////////////////////\n\ninline /*static*/ float SelfSimilarity::ssd3(const cv::Mat_<cv::Vec3b>& patch_a, const cv::Mat_<cv::Vec3b>& patch_b)\n{\n    int ssd = 0;\n    int diff_r, diff_g, diff_b;\n    for (int r = 0; r < patch_a.rows; ++r)\n    {\n        for (int c = 0; c < patch_a.cols; ++c)\n        {\n            const cv::Vec3b& a = patch_a(r, c);\n            const cv::Vec3b& b = patch_b(r, c);\n            diff_r = a[0] - b[0];\n            diff_g = a[1] - b[1];\n            diff_b = a[2] - b[2];\n            ssd +=    (diff_r * diff_r)\n                    + (diff_g * diff_g)\n                    + (diff_b * diff_b);\n        }\n    }\n    return ssd;\n}\n\ninline /*static*/ float SelfSimilarity::ssd1(const cv::Mat_<uchar>& patch_a, const cv::Mat_<uchar>& patch_b)\n{\n    int ssd = 0;\n    int diff;\n    for (int r = 0; r < patch_a.rows; ++r)\n    {\n        for (int c = 0; c < patch_a.cols; ++c)\n        {\n            diff = static_cast<int>(patch_a(r, c)) - patch_b(r, c);\n            ssd += (diff * diff);\n        }\n    }\n    return ssd;\n}\n\ninline const cv::Mat_<int>& SelfSimilarity::getBinMap() const\n{\n    return bin_map_;\n}\ninline unsigned int SelfSimilarity::descriptorLength() const\n{\n    return radius_bin_count_ * angle_bin_count_;\n}\n\n} /* namespace features */\n} /* namespace vision */\n#endif /* VISION_FEATURES_SELF_SIMILARITY_HPP_ */\n", "meta": {"hexsha": "d2d1bebc772af718bd804011d1d3443360f5f9bf", "size": 4934, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "MEX/src/cpp/vision/features/low_level/self_similarity.hpp", "max_stars_repo_name": "umariqb/3D_Pose_Estimation_CVPR2016", "max_stars_repo_head_hexsha": "83f6bf36aa68366ea8fa078eea6d91427e28503b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 47.0, "max_stars_repo_stars_event_min_datetime": "2016-07-25T00:48:59.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-17T09:19:03.000Z", "max_issues_repo_path": "MEX/src/cpp/vision/features/low_level/self_similarity.hpp", "max_issues_repo_name": "umariqb/3D_Pose_Estimation_CVPR2016", "max_issues_repo_head_hexsha": "83f6bf36aa68366ea8fa078eea6d91427e28503b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2016-09-17T19:40:46.000Z", "max_issues_repo_issues_event_max_datetime": "2018-11-07T06:49:02.000Z", "max_forks_repo_path": "MEX/src/cpp/vision/features/low_level/self_similarity.hpp", "max_forks_repo_name": "iqbalu/3D_Pose_Estimation_CVPR2016", "max_forks_repo_head_hexsha": "83f6bf36aa68366ea8fa078eea6d91427e28503b", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 35.0, "max_forks_repo_forks_event_min_datetime": "2016-07-21T09:13:15.000Z", "max_forks_repo_forks_event_max_datetime": "2019-05-13T14:11:37.000Z", "avg_line_length": 29.369047619, "max_line_length": 124, "alphanum_fraction": 0.6163356303, "num_tokens": 1220, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6370308082623217, "lm_q2_score": 0.47268347662043286, "lm_q1q2_score": 0.3011139371637586}}
{"text": "//==================================================================================================\n/*!\n  @file\n\n  @copyright 2016 NumScale SAS\n\n  Distributed under the Boost Software License, Version 1.0.\n  (See accompanying file LICENSE.md or copy at http://boost.org/LICENSbd:E_1_0.txt)\n*/\n//==================================================================================================\n#ifndef BOOST_SIMD_ARCH_COMMON_DETAIL_GENERIC_TRIG_REDUCTION_HPP_INCLUDED\n#define BOOST_SIMD_ARCH_COMMON_DETAIL_GENERIC_TRIG_REDUCTION_HPP_INCLUDED\n\n#include <boost/simd/function/fast.hpp>\n#include <boost/simd/function/rem_pio2_medium.hpp>\n#include <boost/simd/function/rem_pio2_cephes.hpp>\n#include <boost/simd/function/rem_pio2_straight.hpp>\n#include <boost/simd/function/rem_pio2.hpp>\n#include <boost/simd/function/logical_and.hpp>\n#include <boost/simd/function/split.hpp>\n#include <boost/simd/function/group.hpp>\n#include <boost/simd/detail/dispatch/meta/upgrade.hpp>\n\n#include <boost/simd/function/all.hpp>\n#include <boost/simd/function/toint.hpp>\n#include <boost/simd/function/nearbyint.hpp>\n#include <boost/simd/function/if_else_nan.hpp>\n#include <boost/simd/function/is_not_greater.hpp>\n#include <boost/simd/function/is_nez.hpp>\n#include <boost/simd/function/is_flint.hpp>\n#include <boost/simd/function/all.hpp>\n#include <boost/simd/function/inrad.hpp>\n#include <boost/simd/function/multiplies.hpp>\n#include <boost/simd/function/divides.hpp>\n#include <boost/simd/function/minus.hpp>\n#include <boost/simd/constant/zero.hpp>\n#include <boost/simd/constant/pi.hpp>\n#include <boost/simd/constant/pio_2.hpp>\n#include <boost/simd/constant/pio_4.hpp>\n#include <boost/simd/constant/half.hpp>\n#include <boost/simd/constant/two.hpp>\n#include <boost/simd/detail/constant/medium_pi.hpp>\n#include <boost/simd/constant/false.hpp>\n#include <boost/simd/constant/ratio.hpp>\n#include <boost/simd/constant/constant.hpp>\n#include <boost/simd/constant/real.hpp>\n#include <boost/simd/detail/dispatch/meta/as_integer.hpp>\n#include <boost/simd/detail/dispatch/meta/scalar_of.hpp>\n#include <utility>\n\nnamespace boost { namespace simd\n{\n  namespace detail\n  {\n    template< class A0\n            , class unit_tag\n            , class style\n            , class mode\n            , class base_A0 = bd::scalar_of_t<A0>\n    >\n    struct trig_reduction;\n\n    // This class exposes the public static member:\n    // reduce:                to provide range reduction\n    //\n    // unit_tag allows to choose statically the scaling  among radian_tag, pi_tag, degree_tag\n    // meaning that the cosa function will (for example) define respectively\n    // x-->cos(x)          (radian_tag),\n    // x-->cos(pi*x)        (pi_tag)\n    // x-->cos((pi/180)*x) (degree_tag)\n    //\n\n    // trigonometric reduction strategies in the [-pi/4, pi/4] range.\n    // these reductions are used in the accurate and fast\n    // trigonometric functions with different policies\n\n\n    template<class A0, class style>\n    struct trig_reduction<A0,tag::degree_tag, style, tag::big_tag>\n    {\n      using i_t = bd::as_integer_t<A0, signed>;\n\n      static BOOST_FORCEINLINE auto cot_invalid(const A0& x) BOOST_NOEXCEPT\n      -> decltype(is_nez(x)&&is_flint(x*Ratio<A0,1,180>()))\n      {\n        return is_nez(x)&&is_flint(x*Ratio<A0,1,180>());\n      }\n      static BOOST_FORCEINLINE auto tan_invalid(const A0& x) BOOST_NOEXCEPT\n      -> decltype(is_flint((x- Ratio<A0,90>())*Ratio<A0,1,180>()))\n      {\n        return is_flint((x- Ratio<A0,90>())*Ratio<A0,1,180>());\n      }\n\n      static BOOST_FORCEINLINE i_t reduce(const A0& x, A0& xr) BOOST_NOEXCEPT\n      {\n        A0 xi = nearbyint(x*Ratio<A0,1,90>());\n        A0 x2 = x - xi * Ratio<A0,90>();\n\n        xr =  inrad(x2);\n        return toint(xi);\n      }\n    };\n\n#ifdef BOOST_SIMD_HAS_X87\n    template<class A0>\n    struct trig_reduction<A0,degree_tag, tag::not_simd_type, tag::big_tag>\n    {\n      using i_t = bd::as_integer_t<A0, signed>;\n\n      static BOOST_FORCEINLINE auto cot_invalid(const A0& x) BOOST_NOEXCEPT\n      -> decltype(is_nez(x)&&is_flint(x*Ratio<A0,1,180>()))\n      {\n        return is_nez(x)&&is_flint(x/Constant<A0,180>());\n      }\n      static BOOST_FORCEINLINE auto tan_invalid(const A0& x) BOOST_NOEXCEPT\n      -> decltype(is_flint((x- Ratio<A0,90>())/Constant<A0,180>()))\n      {\n        return is_flint((x- Ratio<A0,90>())*Ratio<A0,1,180>());\n      }\n\n      static BOOST_FORCEINLINE i_t reduce(const A0& x, A0& xr) BOOST_NOEXCEPT\n      {\n        A0 xi = nearbyint(x*Ratio<A0,1,90>());\n        A0 x2 = x - xi * Ratio<A0,90>();\n\n        xr =  inrad(x2);\n        return toint(xi);\n      }\n    };\n#endif\n\n    template < class A0, class style>\n    struct trig_reduction < A0, tag::pi_tag,  style, tag::big_tag>\n    {\n      using i_t = bd::as_integer_t<A0, signed>;\n\n      static BOOST_FORCEINLINE auto cot_invalid(const A0& x) BOOST_NOEXCEPT\n      -> decltype(is_nez(x)&&is_flint(x))\n      {\n        return is_nez(x)&&is_flint(x);\n      }\n      static BOOST_FORCEINLINE auto tan_invalid(const A0& x) BOOST_NOEXCEPT\n      -> decltype(is_flint(x-Half<A0>()))\n      {\n        return is_flint(x-Half<A0>()) ;\n      }\n\n      static BOOST_FORCEINLINE i_t reduce(const A0& x,  A0& xr) BOOST_NOEXCEPT\n      {\n        A0 xi = nearbyint(x*Two<A0>());\n        A0 x2 = x - xi * Half<A0>();\n        xr = x2*Pi<A0>();\n        return toint(xi);\n      }\n    };\n  }\n} }\n\n\n#endif\n", "meta": {"hexsha": "86f7cf52f67a9c792d3c02ff7b97347b1cd4510a", "size": 5373, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/arch/common/detail/generic/trig_reduction.hpp", "max_stars_repo_name": "xmar/pythran", "max_stars_repo_head_hexsha": "dbf2e8b70ed1e4d4ac6b5f26ead4add940a72592", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "third_party/boost/simd/arch/common/detail/generic/trig_reduction.hpp", "max_issues_repo_name": "xmar/pythran", "max_issues_repo_head_hexsha": "dbf2e8b70ed1e4d4ac6b5f26ead4add940a72592", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "third_party/boost/simd/arch/common/detail/generic/trig_reduction.hpp", "max_forks_repo_name": "xmar/pythran", "max_forks_repo_head_hexsha": "dbf2e8b70ed1e4d4ac6b5f26ead4add940a72592", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.3726708075, "max_line_length": 100, "alphanum_fraction": 0.6396798809, "num_tokens": 1429, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6370308082623216, "lm_q2_score": 0.4726834766204328, "lm_q1q2_score": 0.3011139371637585}}
{"text": "//==============================================================================\n//         Copyright 2003 - 2012   LASMEA UMR 6602 CNRS/Univ. Clermont II\n//         Copyright 2009 - 2012   LRI    UMR 8623 CNRS/Univ Paris Sud XI\n//\n//          Distributed under the Boost Software License, Version 1.0.\n//                 See accompanying file LICENSE.txt or copy at\n//                     http://www.boost.org/LICENSE_1_0.txt\n//==============================================================================\n#ifndef NT2_TOOLBOX_TRIGONOMETRIC_FUNCTIONS_SCALAR_IMPL_TRIGO_F_TRIG_REDUCTION_HPP_INCLUDED\n#define NT2_TOOLBOX_TRIGONOMETRIC_FUNCTIONS_SCALAR_IMPL_TRIGO_F_TRIG_REDUCTION_HPP_INCLUDED\n\n#include <nt2/sdk/meta/upgrade.hpp>\n#include <nt2/sdk/meta/as_integer.hpp>\n#include <nt2/include/functions/simd/rem_pio2_medium.hpp>\n#include <nt2/include/functions/simd/rem_pio2_cephes.hpp>\n#include <nt2/include/functions/simd/rem_pio2_straight.hpp>\n#include <nt2/include/functions/simd/rem_pio2.hpp>\n#include <nt2/toolbox/arithmetic/include/functions/toint.hpp>\n#include <nt2/include/functions/simd/inrad.hpp>\n#include <nt2/include/functions/simd/round.hpp>\n#include <nt2/include/functions/simd/is_odd.hpp>\n#include <nt2/include/functions/simd/if_else.hpp>\n#include <nt2/include/functions/simd/is_not_less.hpp>\n#include <nt2/include/functions/simd/is_not_greater.hpp>\n#include <nt2/include/functions/simd/is_greater_equal.hpp>\n#include <nt2/include/functions/simd/is_less_equal.hpp>\n#include <nt2/include/functions/simd/is_greater_equal.hpp>\n#include <nt2/include/functions/simd/is_nez.hpp>\n#include <nt2/include/functions/simd/multiplies.hpp>\n#include <nt2/include/functions/simd/is_inf.hpp>\n#include <nt2/include/functions/simd/bitwise_andnot.hpp>\n#include <nt2/include/functions/simd/is_invalid.hpp>\n#include <nt2/include/functions/simd/is_flint.hpp>\n#include <nt2/include/functions/simd/rec.hpp>\n#include <nt2/include/functions/simd/all.hpp>\n#include <nt2/include/constants/false.hpp>\n#include <nt2/include/constants/true.hpp>\n#include <nt2/include/constants/pio_2.hpp>\n#include <boost/mpl/not.hpp>\n#include <boost/type_traits/is_same.hpp>\n\nnamespace nt2\n{\n  namespace details\n  {\n    namespace internal\n    {\n      template< class A0\n                , class unit_tag\n                , class style\n                , class mode\n                , class base_A0 = typename meta::scalar_of<A0>::type\n      >\n      struct trig_reduction;\n    }\n  }\n}\n\nnamespace nt2\n{\n  namespace details\n  {\n    namespace internal\n    {\n//       template< class A0\n//               , class unit_tag\n//               , class precision_tag\n//               , class style\n//               , class mode\n//               , class base_A0 = typename meta::scalar_of<A0>::type\n//               >\n//       struct trig_reduction;\n\n      // This class exposes the public static member:\n      // reduce:                to provide range reduction\n      //\n      // unit_tag allows to choose statically the scaling  among radian_tag, pi_tag, degree_tag\n      // meaning that the cosa function will (for example) define respectively\n      // x-->cos(x)          (radian_tag),\n      // x-->cos(p*x)        (pi_tag)\n      // x-->cos((pi/180)*x) (degree_tag)\n      //\n      // precision_tag allows to choose policies among accuracy and speed\n      // are defined:\n      //   trig_tag\n      //   fast_tag\n      // fast_tag doe not mean that functions are returning stupid values\n      //    but that the range is very restricted.\n      // accu_tag does not mean that functions are ever slow,  but that they are\n      //    slower and slower with increased range, but they are speedier than\n      //    standard ones except for really big_ parameters values, because they return\n      //    quite accurate values even in these cases\n      //\n      // for each trigonometric function, xxx\n      //   xxx_\n      //   fast_xxx_\n      // NT2 functors are provided.\n\n      // trigonometric reduction strategies to the [-pi/4, pi/4] range.\n      // these reductions are used in the normal and fast\n      // trigonometric functions with different policies\n\n      template<class A0, class mode>\n      struct trig_reduction < A0, radian_tag,  tag::not_simd_type, mode, float>\n      {\n        typedef typename meta::as_integer<A0, signed>::type int_type;\n\n        static inline bool isalreadyreduced(const A0&a0) { return le(a0, Pio_4<A0>()); }\n\n        static inline bool ismedium (const A0&a0)  { return le(a0,single_constant<A0,0x43490fdb>()); }\n        static inline bool issmall  (const A0&a0)  { return le(a0,single_constant<A0,0x427b53d1>()); }\n        static inline bool islessthanpi_2  (const A0&a0)  { return le(a0,Pio_2<A0>()); }\n        static inline bool conversion_allowed(){\n          typedef typename meta::upgrade<A0>::type uA0;\n          return boost::mpl::not_<boost::is_same<A0,uA0> >::value;\n        }\n\n        static inline bool cot_invalid(const A0& ) { return false; }\n        static inline bool tan_invalid(const A0& ) { return false; }\n\n        static inline int_type reduce(const A0& x, A0& xr, A0& xc){ return inner_reduce(x, xr, xc, mode()); }\n      private:\n        static inline int_type inner_reduce(const A0& x, A0& xr, A0& xc, const big_&)\n        {\n          // x is always positive here\n          if (isalreadyreduced(x)) // all of x are in [0, pi/4], no reduction\n            {\n              xr = x;\n              xc = Zero<A0>();\n              return Zero<int_type>();\n            }\n          else if (islessthanpi_2(x)) // all of x are in [0, pi/2],  straight algorithm is sufficient for 1 ulp\n            return rem_pio2_straight(x, xr, xc);\n          else if (issmall(x)) // all of x are in [0, 20*pi],  cephes algorithm is sufficient for 1 ulp\n            return rem_pio2_cephes(x, xr, xc);\n          else if (ismedium(x)) // all of x are in [0, 2^7*pi/2],  fdlibm medium_ way\n            return rem_pio2_medium(x, xr, xc);\n          else if (conversion_allowed())  // all of x are in [0, 2^18*pi],  conversion to double is used to reduce if available\n            {\n              typedef typename meta::upgrade<A0>::type uA0;\n              typedef trig_reduction< uA0, radian_tag,  tag::not_simd_type, mode, double> aux_reduction;\n              uA0 ux = x, uxr, uxc;\n              int_type n = static_cast<int_type>(aux_reduction::reduce(ux, uxr, uxc));\n              xr = static_cast<A0>(uxr);\n              xc = static_cast<A0>((uxr-static_cast<uA0>(xr))+uxc);\n              return n;\n            }\n          else  // all of x are in [0, inf],  standard big_ way // too long\n            return rem_pio2(x, xr, xc);\n        }\n\n        static inline int_type inner_reduce(const A0& x, A0& xr, A0& xc, const medium_&)\n        {\n          // x is always positive here\n          if (isalreadyreduced(x)) // all of x are in [0, pi/4], no reduction\n            {\n              xr = x;\n              xc = Zero<A0>();\n              return Zero<int_type>();\n            }\n          else if (islessthanpi_2(x)) // all of x are in [0, pi/2],  straight algorithm is sufficient for 1 ulp\n            {\n              return rem_pio2_straight(x, xr, xc);\n            }\n          else if (issmall(x)) // all of x are in [0, 20*pi],  cephes algorithm is sufficient for 1 ulp\n            {\n              return rem_pio2_cephes(x, xr, xc);\n            }\n          else  // correct only if all of x are in [0, 2^7*pi/2],  fdlibm medium_ way\n            {\n              return rem_pio2_medium(x, xr, xc);\n            }\n        }\n\n        static inline int_type inner_reduce(const A0& x, A0& xr, A0& xc, const small_&)\n        {\n          // x is always positive here\n          if (isalreadyreduced(x)) // all of x are in [0, pi/4], no reduction\n            {\n              xr = x;\n              xc = Zero<A0>();\n              return Zero<int_type>();\n            }\n          else if (islessthanpi_2(x)) // all of x are in [0, pi/2],  straight algorithm is sufficient for 1 ulp\n            return rem_pio2_straight(x, xr, xc);\n          else  // correct only if all of x are in [0, 20*pi],  cephes algorithm is sufficient for 1 ulp\n            return rem_pio2_cephes(x, xr, xc);\n        }\n        static inline int_type inner_reduce(const A0& x, A0& xr, A0& xc, const direct_small_&)\n        {\n          return rem_pio2_cephes(x, xr, xc);\n        }\n        static inline int_type inner_reduce(const A0& x, A0& xr, A0& xc, const direct_medium_&)\n        {\n          return rem_pio2_medium(x, xr, xc);\n        }\n        static inline int_type inner_reduce(const A0& x, A0& xr, A0& xc, const direct_big_&)\n        {\n          if (conversion_allowed()) // conversion to double is used to reduce time, if available\n            {\n              typedef typename meta::upgrade<A0>::type uA0;\n              typedef trig_reduction< uA0, radian_tag,  tag::not_simd_type, mode, double> aux_reduction;\n              uA0 ux = x, uxr, uxc;\n              int_type n = aux_reduction::reduce(ux, uxr, uxc);\n              xr = uxr;\n              xc = (uxr-xr)+uxc;\n              return n;\n            }\n          else\n            return nt2::rem_pio2(x, xr, xc);\n        }\n        static inline int_type inner_reduce(const A0& x, A0& xr, A0& xc, const clipped_pio4_&)\n        {\n          xr = select(isalreadyreduced(x), x, Nan<A0>());\n          xc = Zero<A0>();\n          return Zero<int_type>();\n        }\n        static inline int_type inner_reduce(const A0& x, A0& xr, A0& xc, const clipped_small_&)\n        {\n          xr = select(issmall(x), x, Nan<A0>());\n          return inner_reduce(xr, xr, xc, small_());\n        }\n        static inline int_type inner_reduce(const A0& x, A0& xr, A0& xc, const clipped_medium_&)\n        {\n          xr = select(ismedium(x), x, Nan<A0>());\n          return inner_reduce(xr, xr, xc, medium_());\n        }\n      };\n\n      template<class A0>\n      struct trig_reduction<A0,degree_tag, tag::not_simd_type,big_, float>\n      {\n        typedef typename meta::as_integer<A0, signed>::type int_type;\n\n        static inline bool cot_invalid(const A0& x) { return (is_nez(x)&&is_flint(x/_180<A0>())); }\n        static inline bool tan_invalid(const A0& x) { return is_flint((x-_90<A0>())/_180<A0>()); }\n\n        static inline int_type reduce(const A0& x, A0& xr, A0& xc)\n        {\n          A0 xi = round(x*single_constant<A0,0x3c360b61>()); //  1.111111111111111e-02f\n          A0 x2 = x - xi * _90<A0>();\n\n          xr =  x2*single_constant<A0,0x3c8efa35>(); //0.0174532925199432957692f\n          xc = Zero<A0>();\n          return toint(xi);\n        }\n        static inline int_type inner_reduce(const A0& x, A0& xr, A0& xc, const clipped_pio4_&)\n        {\n          xr = select(isalreadyreduced(nt2::abs(x)), x, Nan<A0>());\n          xc = Zero<A0>();\n          return Zero<int_type>();\n        }\n        static inline int_type inner_reduce(const A0& x, A0& xr, A0& xc, const clipped_small_&)\n        {\n          x = select(issmall(nt2::abs(x)), x, Nan<A0>());\n          return inner_reduce(x, xr, xc, small_());\n        }\n        static inline int_type inner_reduce(const A0& x, A0& xr, A0& xc, const clipped_medium_&)\n        {\n          x = select(ismedium(nt2::abs(x)), x, Nan<A0>());\n          return inner_reduce(x, xr, xc, medium_());\n        }\n      };\n\n       template < class A0>\n       struct trig_reduction < A0, pi_tag,  tag::not_simd_type, big_, float>\n      {\n        typedef typename meta::as_integer<A0, signed>::type int_type;\n\n        static inline bool cot_invalid(const A0& x) { return is_nez(x)&&is_flint(x); }\n        static inline bool tan_invalid(const A0& x) { return is_flint(x-Half<A0>()) ; }\n\n        static inline int_type reduce(const A0& x,  A0& xr, A0&xc)\n        {\n          A0 xi = round(x*Two<A0>());\n          A0 x2 = x - xi * Half<A0>();\n          xr = x2*Pi<A0>();\n          xc = Zero<A0>();\n          return toint(xi);\n        }\n      };\n    }\n  }\n}\n\n#endif\n\n// /////////////////////////////////////////////////////////////////////////////\n// End of f_trig_reduction.hpp\n// /////////////////////////////////////////////////////////////////////////////\n", "meta": {"hexsha": "7ef7aefae4f6b9f9ce39a573bf7fe2f4e47f2375", "size": 12075, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/core/trigonometric/include/nt2/toolbox/trigonometric/functions/scalar/impl/trigo/f_trig_reduction.hpp", "max_stars_repo_name": "timblechmann/nt2", "max_stars_repo_head_hexsha": "6c71f7063ca4e5975c9c019877e6b2fe07c9e4ce", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2016-09-14T00:23:53.000Z", "max_stars_repo_stars_event_max_datetime": "2018-01-14T12:51:18.000Z", "max_issues_repo_path": "modules/core/trigonometric/include/nt2/toolbox/trigonometric/functions/scalar/impl/trigo/f_trig_reduction.hpp", "max_issues_repo_name": "timblechmann/nt2", "max_issues_repo_head_hexsha": "6c71f7063ca4e5975c9c019877e6b2fe07c9e4ce", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "modules/core/trigonometric/include/nt2/toolbox/trigonometric/functions/scalar/impl/trigo/f_trig_reduction.hpp", "max_forks_repo_name": "timblechmann/nt2", "max_forks_repo_head_hexsha": "6c71f7063ca4e5975c9c019877e6b2fe07c9e4ce", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.4948453608, "max_line_length": 127, "alphanum_fraction": 0.5767287785, "num_tokens": 3162, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6370307944803832, "lm_q2_score": 0.47268347662043286, "lm_q1q2_score": 0.301113930649264}}
{"text": "//==============================================================================\n//         Copyright 2003 - 2012   LASMEA UMR 6602 CNRS/Univ. Clermont II\n//         Copyright 2009 - 2013   LRI    UMR 8623 CNRS/Univ Paris Sud XI\n//\n//          Distributed under the Boost Software License, Version 1.0.\n//                 See accompanying file LICENSE.txt or copy at\n//                     http://www.boost.org/LICENSE_1_0.txt\n//==============================================================================\n#ifndef NT2_LINALG_FUNCTIONS_LAPACK_CLINSOLVE_HPP_INCLUDED\n#define NT2_LINALG_FUNCTIONS_LAPACK_CLINSOLVE_HPP_INCLUDED\n\n\n#include <nt2/linalg/functions/clinsolve.hpp>\n\n#include <nt2/include/functions/issquare.hpp>\n#include <nt2/include/functions/zeros.hpp>\n#include <nt2/include/functions/gelsy.hpp>\n#include <nt2/include/functions/gesv.hpp>\n#include <nt2/include/functions/gbsv.hpp>\n#include <nt2/include/functions/posv.hpp>\n#include <nt2/include/functions/sysv.hpp>\n#include <nt2/include/functions/lange.hpp>\n#include <nt2/include/functions/lansy.hpp>\n#include <nt2/include/functions/langb.hpp>\n#include <nt2/include/functions/gecon.hpp>\n#include <nt2/include/functions/sycon.hpp>\n#include <nt2/include/functions/pocon.hpp>\n#include <nt2/include/functions/gbcon.hpp>\n#include <nt2/include/functions/trsolve.hpp>\n\n#include <nt2/include/functions/tie.hpp>\n\n#include <nt2/linalg/options.hpp>\n#include <nt2/linalg/functions/details/eval_linsolve.hpp>\n#include <nt2/sdk/meta/settings_of.hpp>\n#include <boost/dispatch/meta/hierarchy_of.hpp>\n#include <nt2/sdk/meta/as_real.hpp>\n#include <boost/dispatch/meta/terminal_of.hpp>\n#include <nt2/core/container/table/table.hpp>\n\n\n\nnamespace nt2 { namespace ext\n{\n  //============================================================================\n  // LINSOLVE classic\n  //============================================================================\n  BOOST_DISPATCH_IMPLEMENT  ( clinsolve_, tag::cpu_\n                            , (A0)(A1)(A2)(N2)\n                            , ((ast_<A0, nt2::container::domain>))   // A\n                              ((ast_<A1, nt2::container::domain>))   // B\n                              ((node_<A2, nt2::tag::tie_             // X-R\n                                    , N2, nt2::container::domain\n                                     >\n                              ))\n                            )\n  {\n    typedef void  result_type;\n    typedef typename A0::value_type ctype_t;\n    typedef typename nt2::meta::as_real<ctype_t>::type   type_t;\n    typedef typename meta::option<typename A0::proto_child0::settings_type,nt2::tag::shape_>::type shape;\n    typedef nt2::memory::container<tag::table_, ctype_t, nt2::settings(nt2::_2D)> desired_semantic;\n    typedef nt2::container::table<ctype_t>  entry_type;\n    typedef nt2::container::table<ctype_t,shape>  matrix_type;\n\n    BOOST_FORCEINLINE result_type operator()( A0 const& a0, A1 const& a1, A2 const& a2  ) const\n    {\n      nt2::container::table<nt2_la_int> piv;\n      eval(a0,a1,a2,piv,N2(),shape());\n    }\n\n    //==========================================================================\n    /// INTERNAL ONLY - Shape analysis\n\n    /// INTERNAL ONLY - X = LINSOLVE(A,B) - rectangular shape\n    BOOST_FORCEINLINE\n    void eval ( A0 const& a0, A1 const& a1 , A2 const& a2, nt2::container::table<nt2_la_int>& piv\n              , boost::mpl::long_<1> const&, nt2::rectangular_ const&\n              ) const\n    {\n      NT2_AS_TERMINAL_INOUT(desired_semantic,b,a1,boost::proto::child_c<0>(a2) );\n      entry_type entry(a0);\n      eval_param( a0, a1, b);\n\n      if (issquare(entry)) nt2::gesv(boost::proto::value(entry)\n                           ,boost::proto::value(piv), boost::proto::value(b));\n\n      else {\n        nt2_la_int n = nt2::width(a0);\n        piv = nt2::zeros(n,1, nt2::meta::as_<nt2_la_int>());\n        nt2::gelsy( boost::proto::value(entry) ,boost::proto::value(piv)\n                , boost::proto::value(b) );\n      }\n\n      assign_swap (boost::proto::child_c<0>(a2), b);\n    }\n\n    //==========================================================================\n    /// INTERNAL ONLY - X = LINSOLVE(A,B) - positive definite shape\n    BOOST_FORCEINLINE\n    void eval ( A0 const& a0, A1 const& a1 , A2 const& a2, nt2::container::table<nt2_la_int>& /*piv*/\n              , boost::mpl::long_<1> const&, nt2::positive_definite_ const&\n              ) const\n    {\n      NT2_AS_TERMINAL_INOUT(desired_semantic,b,a1,boost::proto::child_c<0>(a2) );\n      matrix_type entry(a0);\n\n      nt2::posv(boost::proto::value(entry), boost::proto::value(b));\n      assign_swap (boost::proto::child_c<0>(a2), b);\n    }\n\n    //==========================================================================\n    /// INTERNAL ONLY - X = LINSOLVE(A,B) - symmetric shape\n    BOOST_FORCEINLINE\n    void eval ( A0 const& a0, A1 const& a1 , A2 const& a2, nt2::container::table<nt2_la_int>& piv\n              , boost::mpl::long_<1> const&, nt2::symmetric_ const&\n              ) const\n    {\n      NT2_AS_TERMINAL_INOUT(desired_semantic,b,a1,boost::proto::child_c<0>(a2) );\n      matrix_type entry(a0);\n      piv.resize(nt2::of_size(a0.leading_size(),1));\n      nt2::sysv( boost::proto::value(entry),boost::proto::value(piv)\n              , boost::proto::value(b));\n      assign_swap (boost::proto::child_c<0>(a2), b);\n\n    }\n\n    //==========================================================================\n    /// INTERNAL ONLY - X = LINSOLVE(A,B) - band shape\n    template<int U, int L>\n    BOOST_FORCEINLINE\n    void eval ( A0 const& a0, A1 const& a1 , A2 const& a2, nt2::container::table<nt2_la_int>& piv\n              , boost::mpl::long_<1> const&, nt2::band_diagonal_<U,L> const&\n              ) const\n    {\n      NT2_AS_TERMINAL_INOUT(desired_semantic,b,a1,boost::proto::child_c<0>(a2) );\n      matrix_type entry(a0);\n\n      nt2::gbsv( boost::proto::value(entry),boost::proto::value(piv)\n              , boost::proto::value(b));\n      assign_swap (boost::proto::child_c<0>(a2), b);\n\n    }\n\n    //==========================================================================\n    /// INTERNAL ONLY - X = LINSOLVE(A,B) -- upper triangular shape\n    BOOST_FORCEINLINE\n    void eval ( A0 const& a0, A1 const& a1 , A2 const& a2, nt2::container::table<nt2_la_int>&\n              , boost::mpl::long_<1> const&, nt2::upper_triangular_ const&\n              ) const\n    {\n      boost::proto::child_c<0>(a2) = nt2::trsolve(a0,a1);\n    }\n\n    //==========================================================================\n    /// INTERNAL ONLY - X = LINSOLVE(A,B) -- lower triangular shape\n    BOOST_FORCEINLINE\n    void eval ( A0 const& a0, A1 const& a1 , A2 const& a2, nt2::container::table<nt2_la_int>&\n              , boost::mpl::long_<1> const&, nt2::lower_triangular_ const&\n              ) const\n    {\n      boost::proto::child_c<0>(a2) = nt2::trsolve(a0,a1);\n    }\n\n    //==========================================================================\n    /// INTERNAL ONLY - [X,R] = LINSOLVE(A,B) -- Rectangular shape\n    BOOST_FORCEINLINE\n    void eval( A0 const& a0, A1 const& a1 , A2 const& a2, nt2::container::table<nt2_la_int>& piv\n              , boost::mpl::long_<2> const&\n              ) const\n    {\n      NT2_AS_TERMINAL_INOUT(desired_semantic,b,a1,boost::proto::child_c<0>(a2) );\n      matrix_type entry(a0);\n\n      eval_param( entry, a1, boost::proto::child_c<0>(a2));\n\n      if (issquare(entry))\n      {\n        nt2::gesv( boost::proto::value(entry), boost::proto::value(piv)\n               , boost::proto::value(b) );\n        char norm = '1';\n\n        type_t anorm = nt2::lange(boost::proto::value(entry),norm);\n        boost::proto::child_c<1>(a2) = nt2::gecon(boost::proto::value(entry),norm,anorm);\n      }\n      else\n      {\n        nt2_la_int rank;\n        nt2_la_int n = nt2::width(entry);\n        piv = nt2::zeros(n,1, nt2::meta::as_<nt2_la_int>());\n\n        nt2::gelsy( boost::proto::value(entry), boost::proto::value(piv)\n                , boost::proto::value(b), rank);\n        boost::proto::child_c<1>(a2) = static_cast<type_t>(rank);\n      }\n      assign_swap (boost::proto::child_c<0>(a2), b);\n    }\n\n    //==========================================================================\n    /// INTERNAL ONLY - [X,R] = LINSOLVE(A,B) -- symmetric shape\n    BOOST_FORCEINLINE\n    void eval ( A0 const& a0, A1 const& a1 , A2 const& a2, nt2::container::table<nt2_la_int>& piv\n              , boost::mpl::long_<2> const&, nt2::symmetric_ const&\n              ) const\n    {\n      NT2_AS_TERMINAL_INOUT(desired_semantic,b,a1,boost::proto::child_c<0>(a2) );\n      matrix_type entry(a0);\n      char norm = '1';\n\n      piv = nt2::zeros(entry.leading_size(), 1, nt2::meta::as_<nt2_la_int>() );\n\n      typedef typename meta::hierarchy_of<nt2::symmetric_>::stripped h_;\n\n      type_t anorm = nt2::lange(boost::proto::value(entry), norm, h_());\n\n      nt2::sysv( boost::proto::value(entry),boost::proto::value(piv)\n              , boost::proto::value(b));\n      boost::proto::child_c<1>(a2) = nt2::sycon( boost::proto::value(entry)\n                                               , boost::proto::value(piv) ,anorm);\n      assign_swap (boost::proto::child_c<0>(a2), b);\n    }\n\n    //==========================================================================\n    /// INTERNAL ONLY - [X,R] = LINSOLVE(A,B) -- positive definite shape\n    BOOST_FORCEINLINE\n    void eval ( A0 const& a0, A1 const& a1 , A2 const& a2, nt2::container::table<nt2_la_int>& /*piv*/\n              , boost::mpl::long_<2> const&, nt2::positive_definite_ const&\n              ) const\n    {\n      NT2_AS_TERMINAL_INOUT(desired_semantic,b,a1,boost::proto::child_c<0>(a2) );\n      matrix_type entry(a0);\n\n      char norm = '1';\n      typedef typename meta::hierarchy_of<nt2::symmetric_>::stripped h_;\n      type_t anorm = nt2::lange(boost::proto::value(entry) ,norm, h_());\n      nt2::posv(boost::proto::value(entry), boost::proto::value(b));\n      boost::proto::child_c<1>(a2) = nt2::pocon(boost::proto::value(entry),anorm);\n      assign_swap (boost::proto::child_c<0>(a2), b);\n    }\n\n    //==========================================================================\n    /// INTERNAL ONLY - [X,R] = LINSOLVE(A,B) -- general band shape\n    template<int U, int L>\n    BOOST_FORCEINLINE\n    void eval ( A0 const& a0, A1 const& a1 , A2 const& a2, nt2::container::table<nt2_la_int>& piv\n              , boost::mpl::long_<2> const&, nt2::band_diagonal_<U,L> const&\n              ) const\n    {\n      NT2_AS_TERMINAL_INOUT(desired_semantic,b,a1,boost::proto::child_c<0>(a2) );\n      matrix_type entry(a0);\n\n      char norm = '1';\n\n      type_t anorm = nt2::langb(boost::proto::value(entry),norm);\n      nt2::gbsv( boost::proto::value(entry), boost::proto::value(piv)\n              , boost::proto::value(b));\n      boost::proto::child_c<1>(a2) = nt2::gbcon( boost::proto::value(entry)\n                                               , boost::proto::value(piv),anorm);\n\n      assign_swap (boost::proto::child_c<0>(a2), b);\n\n    }\n\n    /// INTERNAL ONLY - X = LINSOLVE(A,B) - default case\n    template<typename N, typename sh> BOOST_FORCEINLINE\n    void eval ( A0 const& a0, A1 const& a1 , A2 const& a2, nt2::container::table<nt2_la_int>& piv\n              , N const&, sh const&\n              ) const\n    {\n      eval(a0,a1,a2,piv,boost::mpl::long_<1>() ,nt2::rectangular_());\n    }\n\n  };\n} }\n\n\n#endif\n", "meta": {"hexsha": "e8bf8a90de617b319b79c80d6a0eec20f93b6dc6", "size": 11370, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/core/linalg/include/nt2/linalg/functions/lapack/clinsolve.hpp", "max_stars_repo_name": "psiha/nt2", "max_stars_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 34.0, "max_stars_repo_stars_event_min_datetime": "2017-05-19T18:10:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-04T02:18:13.000Z", "max_issues_repo_path": "modules/core/linalg/include/nt2/linalg/functions/lapack/clinsolve.hpp", "max_issues_repo_name": "psiha/nt2", "max_issues_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "modules/core/linalg/include/nt2/linalg/functions/lapack/clinsolve.hpp", "max_forks_repo_name": "psiha/nt2", "max_forks_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2017-12-02T12:59:17.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-31T12:46:14.000Z", "avg_line_length": 40.8992805755, "max_line_length": 105, "alphanum_fraction": 0.5407211961, "num_tokens": 3075, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6370307944803832, "lm_q2_score": 0.4726834766204328, "lm_q1q2_score": 0.30111393064926395}}
{"text": "/**\n * @author Andre Anjos <andre.anjos@idiap.ch>\n * @date Tue 29 Apr 09:26:02 2014 CEST\n *\n * @brief Bindings for Cost functions\n *\n * Copyright (C) 2011-2014 Idiap Research Institute, Martigny, Switzerland\n */\n\n#define BOB_LEARN_MLP_MODULE\n#include <bob.blitz/cppapi.h>\n#include <bob.blitz/cleanup.h>\n#include <bob.extension/defines.h>\n#include <bob.learn.mlp/api.h>\n#include <bob.learn.activation/api.h>\n#include <structmember.h>\n#include <boost/function.hpp>\n#include <boost/bind.hpp>\n\n/*************************************\n * Implementation of Cost base class *\n *************************************/\n\nPyDoc_STRVAR(s_cost_str, BOB_EXT_MODULE_PREFIX \".Cost\");\n\nPyDoc_STRVAR(s_cost_doc,\n\"A base class for evaluating the performance cost.\\n\\\n\\n\\\nThis is the base class for all concrete (C++ only) loss\\n\\\nfunction implementations. You cannot instantiate objects\\n\\\nof this type directly, use one of the derived classes.\\n\\\n\");\n\nstatic int PyBobLearnCost_init\n(PyBobLearnCostObject* self, PyObject* args, PyObject* kwds) {\n\n  PyErr_Format(PyExc_NotImplementedError, \"cannot instantiate objects of type `%s', use one of the derived classes\", Py_TYPE(self)->tp_name);\n  return -1;\n\n}\n\nint PyBobLearnCost_Check(PyObject* o) {\n  return PyObject_IsInstance(o, reinterpret_cast<PyObject*>(&PyBobLearnCost_Type));\n}\n\nstatic PyObject* PyBobLearnCost_RichCompare\n(PyBobLearnCostObject* self, PyObject* other, int op) {\n\n  if (!PyBobLearnCost_Check(other)) {\n    PyErr_Format(PyExc_TypeError, \"cannot compare `%s' with `%s'\",\n        Py_TYPE(self)->tp_name, Py_TYPE(other)->tp_name);\n    return 0;\n  }\n\n  auto other_ = reinterpret_cast<PyBobLearnCostObject*>(other);\n\n  switch (op) {\n    case Py_EQ:\n      if (self->cxx->str() == other_->cxx->str()) Py_RETURN_TRUE;\n      Py_RETURN_FALSE;\n      break;\n    case Py_NE:\n      if (self->cxx->str() != other_->cxx->str()) Py_RETURN_TRUE;\n      Py_RETURN_FALSE;\n      break;\n    default:\n      Py_INCREF(Py_NotImplemented);\n      return Py_NotImplemented;\n  }\n\n}\n\n#if PY_VERSION_HEX >= 0x03000000\n#  define PYOBJECT_STR PyObject_Str\n#else\n#  define PYOBJECT_STR PyObject_Unicode\n#endif\n\nPyObject* PyBobLearnCost_Repr(PyBobLearnCostObject* self) {\n\n  /**\n   * Expected output:\n   *\n   * <bob.learn.linear.Cost [...]>\n   */\n\n  auto retval = PyUnicode_FromFormat(\"<%s [act: %s]>\",\n        Py_TYPE(self)->tp_name, self->cxx->str().c_str());\n\n#if PYTHON_VERSION_HEX < 0x03000000\n  if (!retval) return 0;\n  PyObject* tmp = PyObject_Str(retval);\n  Py_DECREF(retval);\n  retval = tmp;\n#endif\n\n  return retval;\n\n}\n\nPyObject* PyBobLearnCost_Str(PyBobLearnCostObject* self) {\n  return Py_BuildValue(\"s\", self->cxx->str().c_str());\n}\n\n/**\n * Checks if a array `a1' and `a2' have a matching shape.\n */\nstatic int have_same_shape (PyBlitzArrayObject* a1, PyBlitzArrayObject* a2) {\n\n  if (a1->ndim != a2->ndim) return 0;\n\n  for (Py_ssize_t k=0; k<a1->ndim; ++k) {\n    if (a1->shape[k] != a2->shape[k]) return 0;\n  }\n\n  return 1;\n}\n\nstatic PyObject* apply_scalar(PyBobLearnCostObject* self, const char*,\n    boost::function<double (double, double)> function,\n    PyObject* args, PyObject* kwds) {\n\n  static const char* const_kwlist[] = {\"output\", \"target\", 0};\n  static char** kwlist = const_cast<char**>(const_kwlist);\n\n  double output = 0.;\n  double target = 0.;\n\n  if (!PyArg_ParseTupleAndKeywords(args, kwds, \"dd\", kwlist,\n        &output, &target)) return 0;\n\n  return Py_BuildValue(\"d\", function(output, target));\n\n}\n\n/**\n * Maps all elements of arr through function() into `result'\n */\nstatic PyObject* apply_array(PyBobLearnCostObject* self, const char* fname,\n    boost::function<double (double, double)> function,\n    PyObject* args, PyObject* kwds) {\n\n  static const char* const_kwlist[] = {\"output\", \"target\", \"result\", 0};\n  static char** kwlist = const_cast<char**>(const_kwlist);\n\n  PyBlitzArrayObject* output = 0;\n  PyBlitzArrayObject* target = 0;\n  PyBlitzArrayObject* result = 0;\n\n  if (!PyArg_ParseTupleAndKeywords(args, kwds, \"O&O&|O&\", kwlist,\n        &PyBlitzArray_Converter, &output,\n        &PyBlitzArray_Converter, &target,\n        &PyBlitzArray_OutputConverter, &result\n        )) return 0;\n\n  //protects acquired resources through this scope\n  auto output_ = make_safe(output);\n  auto target_ = make_safe(target);\n  auto result_ = make_xsafe(result);\n\n  if (output->type_num != NPY_FLOAT64) {\n    PyErr_Format(PyExc_TypeError, \"`%s.%s' only supports 64-bit float arrays for input array `output'\", Py_TYPE(self)->tp_name, fname);\n    return 0;\n  }\n\n  if (target->type_num != NPY_FLOAT64) {\n    PyErr_Format(PyExc_TypeError, \"`%s.%s' only supports 64-bit float arrays for input array `target'\", Py_TYPE(self)->tp_name, fname);\n    return 0;\n  }\n\n  if (result && result->type_num != NPY_FLOAT64) {\n    PyErr_Format(PyExc_TypeError, \"`%s.%s' only supports 64-bit float arrays for output array `result'\", Py_TYPE(self)->tp_name, fname);\n    return 0;\n  }\n\n  if (!have_same_shape(output, target)) {\n    PyErr_Format(PyExc_RuntimeError, \"`%s.%s' requires input arrays `output' and `target' to have the same shape, but you provided arrays with different shapes\", Py_TYPE(self)->tp_name, fname);\n    return 0;\n  }\n\n  if (result && !have_same_shape(output, result)) {\n    PyErr_Format(PyExc_RuntimeError, \"`%s.%s' requires output array `result' to have the same shape as input arrays `output' and `target', but you provided arrays with different shapes\", Py_TYPE(self)->tp_name, fname);\n    return 0;\n  }\n\n  /** if ``result`` was not pre-allocated, do it now **/\n  if (!result) {\n    result = (PyBlitzArrayObject*)PyBlitzArray_SimpleNew(NPY_FLOAT64, output->ndim, output->shape);\n    result_ = make_safe(result);\n  }\n\n  switch (output->ndim) {\n    case 1:\n      {\n        blitz::Array<double,1>& output_ =\n          *PyBlitzArrayCxx_AsBlitz<double,1>(output);\n        blitz::Array<double,1>& target_ =\n          *PyBlitzArrayCxx_AsBlitz<double,1>(target);\n        blitz::Array<double,1>& result_ =\n          *PyBlitzArrayCxx_AsBlitz<double,1>(result);\n        for (int k=0; k<output_.extent(0); ++k)\n          result_(k) = function(output_(k), target_(k));\n      }\n      break;\n\n    case 2:\n      {\n        blitz::Array<double,2>& output_ =\n          *PyBlitzArrayCxx_AsBlitz<double,2>(output);\n        blitz::Array<double,2>& target_ =\n          *PyBlitzArrayCxx_AsBlitz<double,2>(target);\n        blitz::Array<double,2>& result_ =\n          *PyBlitzArrayCxx_AsBlitz<double,2>(result);\n        for (int k=0; k<output_.extent(0); ++k)\n          for (int l=0; l<output_.extent(1); ++l)\n            result_(k,l) = function(output_(k,l), target_(k,l));\n      }\n      break;\n\n    case 3:\n      {\n        blitz::Array<double,3>& output_ =\n          *PyBlitzArrayCxx_AsBlitz<double,3>(output);\n        blitz::Array<double,3>& target_ =\n          *PyBlitzArrayCxx_AsBlitz<double,3>(target);\n        blitz::Array<double,3>& result_ =\n          *PyBlitzArrayCxx_AsBlitz<double,3>(result);\n        for (int k=0; k<output_.extent(0); ++k)\n          for (int l=0; l<output_.extent(1); ++l)\n            for (int m=0; m<output_.extent(2); ++m)\n              result_(k,l,m) = function(output_(k,l,m), target_(k,l,m));\n      }\n      break;\n\n    case 4:\n      {\n        blitz::Array<double,4>& output_ =\n          *PyBlitzArrayCxx_AsBlitz<double,4>(output);\n        blitz::Array<double,4>& target_ =\n          *PyBlitzArrayCxx_AsBlitz<double,4>(target);\n        blitz::Array<double,4>& result_ =\n          *PyBlitzArrayCxx_AsBlitz<double,4>(result);\n        for (int k=0; k<output_.extent(0); ++k)\n          for (int l=0; l<output_.extent(1); ++l)\n            for (int m=0; m<output_.extent(2); ++m)\n              for (int n=0; n<output_.extent(3); ++n)\n                result_(k,l,m,n) = function(output_(k,l,m,n), target_(k,l,m,n));\n      }\n      break;\n\n    default:\n      PyErr_Format(PyExc_RuntimeError, \"`%s.%s' only accepts 1, 2, 3 or 4-dimensional double arrays (not %\" PY_FORMAT_SIZE_T \"dD arrays)\", Py_TYPE(self)->tp_name, fname, output->ndim);\n    return 0;\n\n  }\n\n  return PyBlitzArray_NUMPY_WRAP(Py_BuildValue(\"O\", result));\n\n}\n\nPyDoc_STRVAR(s_f_str, \"f\");\nPyDoc_STRVAR(s_f_doc,\n\"o.f(output, target, [result]) -> result\\n\\\n\\n\\\nComputes the cost, given the current and expected outputs.\\n\\\n\\n\\\nKeyword arguments:\\n\\\n\\n\\\noutput, ND array, float64 | scalar\\n\\\n  Real output from the machine. May be a N-dimensional array\\n\\\n  or a plain scalar.\\n\\\n\\n\\\ntarget, ND array, float64 | scalar\\n\\\n  Target output you are training to achieve. The data type\\n\\\n  and extents for this object must match that of ``target``.\\n\\\n\\n\\\nresult (optional), ND array, float64\\n\\\n  Where to place the result from the calculation. You can\\n\\\n  pass this argument if the input are N-dimensional arrays.\\n\\\n  Otherwise, it is an error to pass such a container. If the\\n\\\n  inputs are arrays and an object for ``result`` is passed,\\n\\\n  then its dimensions and data-type must match that of both\\n\\\n  ``output`` and ``result``.\\n\\\n\\n\\\nReturns the cost as a scalar, if the input were scalars or\\n\\\nas an array with matching size of ``output`` and ``target``\\n\\\notherwise.\\n\\\n\");\n\nstatic PyObject* PyBobLearnCost_f\n(PyBobLearnCostObject* self, PyObject* args, PyObject* kwds) {\n\n  PyObject* arg = 0; ///< borrowed (don't delete)\n  if (PyTuple_Size(args)) arg = PyTuple_GET_ITEM(args, 0);\n  else {\n    PyObject* tmp = PyDict_Values(kwds);\n    auto tmp_ = make_safe(tmp);\n    arg = PyList_GET_ITEM(tmp, 0);\n  }\n\n  if (PyBob_NumberCheck(arg))\n    return apply_scalar(self, s_f_str,\n        boost::bind(&bob::learn::mlp::Cost::f, self->cxx, _1, _2), args, kwds);\n\n  return apply_array(self, s_f_str,\n      boost::bind(&bob::learn::mlp::Cost::f, self->cxx, _1, _2), args, kwds);\n\n}\n\nPyDoc_STRVAR(s_f_prime_str, \"f_prime\");\nPyDoc_STRVAR(s_f_prime_doc,\n\"o.f_prime(output, target, [result]) -> result\\n\\\n\\n\\\nComputes the derivative of the cost w.r.t. output.\\n\\\n\\n\\\nKeyword arguments:\\n\\\n\\n\\\noutput, ND array, float64 | scalar\\n\\\n  Real output from the machine. May be a N-dimensional array\\n\\\n  or a plain scalar.\\n\\\n\\n\\\ntarget, ND array, float64 | scalar\\n\\\n  Target output you are training to achieve. The data type\\n\\\n  and extents for this object must match that of ``target``.\\n\\\n\\n\\\nresult (optional), ND array, float64\\n\\\n  Where to place the result from the calculation. You can\\n\\\n  pass this argument if the input are N-dimensional arrays.\\n\\\n  Otherwise, it is an error to pass such a container. If the\\n\\\n  inputs are arrays and an object for ``result`` is passed,\\n\\\n  then its dimensions and data-type must match that of both\\n\\\n  ``output`` and ``result``.\\n\\\n\\n\\\nReturns the cost as a scalar, if the input were scalars or\\n\\\nas an array with matching size of ``output`` and ``target``\\n\\\notherwise.\\n\\\n\");\n\nstatic PyObject* PyBobLearnCost_f_prime\n(PyBobLearnCostObject* self, PyObject* args, PyObject* kwds) {\n\n  PyObject* arg = 0; ///< borrowed (don't delete)\n  if (PyTuple_Size(args)) arg = PyTuple_GET_ITEM(args, 0);\n  else {\n    PyObject* tmp = PyDict_Values(kwds);\n    auto tmp_ = make_safe(tmp);\n    arg = PyList_GET_ITEM(tmp, 0);\n  }\n\n  if (PyBob_NumberCheck(arg))\n    return apply_scalar(self, s_f_prime_str,\n        boost::bind(&bob::learn::mlp::Cost::f_prime,\n          self->cxx, _1, _2), args, kwds);\n\n  return apply_array(self, s_f_prime_str,\n      boost::bind(&bob::learn::mlp::Cost::f_prime,\n        self->cxx, _1, _2), args, kwds);\n\n}\n\nPyDoc_STRVAR(s_error_str, \"error\");\nPyDoc_STRVAR(s_error_doc,\n\"o.error(output, target, [result]) -> result\\n\\\n\\n\\\nComputes the back-propagated error for a given MLP ``output``\\n\\\nlayer.\\n\\\n\\n\\\nComputes the back-propagated error for a given MLP ``output``\\n\\\nlayer, given its activation function and outputs - i.e., the\\n\\\nerror back-propagated through the last layer neuron up to the\\n\\\nsynapse connecting the last hidden layer to the output layer.\\n\\\n\\n\\\nThis implementation allows for optimization in the\\n\\\ncalculation of the back-propagated errors in cases where there\\n\\\nis a possibility of mathematical simplification when using a\\n\\\ncertain combination of cost-function and activation. For\\n\\\nexample, using a ML-cost and a logistic activation function.\\n\\\n\\n\\\nKeyword arguments:\\n\\\n\\n\\\noutput, ND array, float64 | scalar\\n\\\n  Real output from the machine. May be a N-dimensional array\\n\\\n  or a plain scalar.\\n\\\n\\n\\\ntarget, ND array, float64 | scalar\\n\\\n  Target output you are training to achieve. The data type and\\n\\\n  extents for this object must match that of ``target``.\\n\\\n\\n\\\nresult (optional), ND array, float64\\n\\\n  Where to place the result from the calculation. You can pass\\n\\\n  this argument if the input are N-dimensional arrays.\\n\\\n  Otherwise, it is an error to pass such a container. If the\\n\\\n  inputs are arrays and an object for ``result`` is passed,\\n\\\n  then its dimensions and data-type must match that of both\\n\\\n  ``output`` and ``result``.\\n\\\n\\n\\\nReturns the cost as a scalar, if the input were scalars or as\\n\\\n        an array with matching size of ``output`` and\\n\\\n        ``target`` otherwise.\\n\\\n\");\n\nstatic PyObject* PyBobLearnCost_error\n(PyBobLearnCostObject* self, PyObject* args, PyObject* kwds) {\n\n  PyObject* arg = 0; ///< borrowed (don't delete)\n  if (PyTuple_Size(args)) arg = PyTuple_GET_ITEM(args, 0);\n  else {\n    PyObject* tmp = PyDict_Values(kwds);\n    auto tmp_ = make_safe(tmp);\n    arg = PyList_GET_ITEM(tmp, 0);\n  }\n\n  if (PyBob_NumberCheck(arg))\n    return apply_scalar(self, s_error_str,\n        boost::bind(&bob::learn::mlp::Cost::error, self->cxx, _1, _2), args, kwds);\n\n  return apply_array(self, s_error_str,\n      boost::bind(&bob::learn::mlp::Cost::error, self->cxx, _1, _2), args, kwds);\n\n}\n\nstatic PyMethodDef PyBobLearnCost_methods[] = {\n  {\n    s_f_str,\n    (PyCFunction)PyBobLearnCost_f,\n    METH_VARARGS|METH_KEYWORDS,\n    s_f_doc\n  },\n  {\n    s_f_prime_str,\n    (PyCFunction)PyBobLearnCost_f_prime,\n    METH_VARARGS|METH_KEYWORDS,\n    s_f_prime_doc\n  },\n  {\n    s_error_str,\n    (PyCFunction)PyBobLearnCost_error,\n    METH_VARARGS|METH_KEYWORDS,\n    s_error_doc\n  },\n  {0} /* Sentinel */\n};\n\nstatic PyObject* PyBobLearnCost_new (PyTypeObject* type, PyObject*, PyObject*) {\n\n  /* Allocates the python object itself */\n  PyBobLearnCostObject* self = (PyBobLearnCostObject*)type->tp_alloc(type, 0);\n\n  self->cxx.reset();\n\n  return reinterpret_cast<PyObject*>(self);\n\n}\n\nPyObject* PyBobLearnCost_NewFromCost (boost::shared_ptr<bob::learn::mlp::Cost> p) {\n\n  PyBobLearnCostObject* retval = (PyBobLearnCostObject*)PyBobLearnCost_new(&PyBobLearnCost_Type, 0, 0);\n\n  retval->cxx = p;\n\n  return reinterpret_cast<PyObject*>(retval);\n\n}\n\nPyTypeObject PyBobLearnCost_Type = {\n    PyVarObject_HEAD_INIT(0, 0)\n    s_cost_str,                               /* tp_name */\n    sizeof(PyBobLearnCostObject),             /* tp_basicsize */\n    0,                                        /* tp_itemsize */\n    0,                                        /* tp_dealloc */\n    0,                                        /* tp_print */\n    0,                                        /* tp_getattr */\n    0,                                        /* tp_setattr */\n    0,                                        /* tp_compare */\n    (reprfunc)PyBobLearnCost_Repr,            /* tp_repr */\n    0,                                        /* tp_as_number */\n    0,                                        /* tp_as_sequence */\n    0,                                        /* tp_as_mapping */\n    0,                                        /* tp_hash */\n    (ternaryfunc)PyBobLearnCost_f,            /* tp_call */\n    (reprfunc)PyBobLearnCost_Str,             /* tp_str */\n    0,                                        /* tp_getattro */\n    0,                                        /* tp_setattro */\n    0,                                        /* tp_as_buffer */\n    Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */\n    s_cost_doc,                               /* tp_doc */\n    0,                                        /* tp_traverse */\n    0,                                        /* tp_clear */\n    (richcmpfunc)PyBobLearnCost_RichCompare,  /* tp_richcompare */\n    0,                                        /* tp_weaklistoffset */\n    0,                                        /* tp_iter */\n    0,                                        /* tp_iternext */\n    PyBobLearnCost_methods,                   /* tp_methods */\n    0,                                        /* tp_members */\n    0,                                        /* tp_getset */\n    0,                                        /* tp_base */\n    0,                                        /* tp_dict */\n    0,                                        /* tp_descr_get */\n    0,                                        /* tp_descr_set */\n    0,                                        /* tp_dictoffset */\n    (initproc)PyBobLearnCost_init,            /* tp_init */\n    0,                                        /* tp_alloc */\n    PyBobLearnCost_new,                       /* tp_new */\n};\n\nPyDoc_STRVAR(s_squareerror_str, BOB_EXT_MODULE_PREFIX \".SquareError\");\n\nPyDoc_STRVAR(s_squareerror_doc,\n\"SquareError(actfun) -> new SquareError functor\\n\\\n\\n\\\nCalculates the Square-Error between output and target.\\n\\\n\\n\\\nThe square error is defined as follows:\\n\\\n\\n\\\n.. math::\\n\\\n   J = \\\\frac{(\\\\hat{y} - y)^2}{2}\\n\\\n\\n\\\nwhere :math:`\\\\hat{y}` is the output estimated by your machine and\\n\\\n:math:`y` is the expected output.\\n\\\n\\n\\\nKeyword arguments:\\n\\\n\\n\\\nactfun\\n\\\n  The activation function object used at the last layer\\n\\\n\\n\\\n\");\n\nstatic int PyBobLearnSquareError_init\n(PyBobLearnSquareErrorObject* self, PyObject* args, PyObject* kwds) {\n\n  /* Parses input arguments in a single shot */\n  static const char* const_kwlist[] = {\"actfun\", 0};\n  static char** kwlist = const_cast<char**>(const_kwlist);\n\n  PyObject* actfun = 0;\n\n  if (!PyArg_ParseTupleAndKeywords(args, kwds, \"O!\", kwlist,\n        &PyBobLearnActivation_Type, &actfun)) return -1;\n\n  try {\n    auto _actfun = reinterpret_cast<PyBobLearnActivationObject*>(actfun);\n    self->cxx.reset(new bob::learn::mlp::SquareError(_actfun->cxx));\n  }\n  catch (std::exception& ex) {\n    PyErr_SetString(PyExc_RuntimeError, ex.what());\n  }\n  catch (...) {\n    PyErr_Format(PyExc_RuntimeError, \"cannot create new object of type `%s' - unknown exception thrown\", Py_TYPE(self)->tp_name);\n  }\n\n  self->parent.cxx = self->cxx;\n\n  if (PyErr_Occurred()) return -1;\n\n  return 0;\n\n}\n\nstatic void PyBobLearnSquareError_delete\n(PyBobLearnSquareErrorObject* self) {\n\n  self->parent.cxx.reset();\n  self->cxx.reset();\n  Py_TYPE(&self->parent)->tp_free((PyObject*)self);\n\n}\n\nPyTypeObject PyBobLearnSquareError_Type = {\n    PyVarObject_HEAD_INIT(0, 0)\n    s_squareerror_str,                        /*tp_name*/\n    sizeof(PyBobLearnSquareErrorObject),      /*tp_basicsize*/\n    0,                                        /*tp_itemsize*/\n    (destructor)PyBobLearnSquareError_delete, /*tp_dealloc*/\n    0,                                        /*tp_print*/\n    0,                                        /*tp_getattr*/\n    0,                                        /*tp_setattr*/\n    0,                                        /*tp_compare*/\n    0,                                        /*tp_repr*/\n    0,                                        /*tp_as_number*/\n    0,                                        /*tp_as_sequence*/\n    0,                                        /*tp_as_mapping*/\n    0,                                        /*tp_hash */\n    0,                                        /*tp_call*/\n    0,                                        /*tp_str*/\n    0,                                        /*tp_getattro*/\n    0,                                        /*tp_setattro*/\n    0,                                        /*tp_as_buffer*/\n    Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /*tp_flags*/\n    s_squareerror_doc,                        /* tp_doc */\n    0,\t\t                                    /* tp_traverse */\n    0,\t\t                                    /* tp_clear */\n    0,                                        /* tp_richcompare */\n    0,\t\t                                    /* tp_weaklistoffset */\n    0,\t\t                                    /* tp_iter */\n    0,\t\t                                    /* tp_iternext */\n    0,                                        /* tp_methods */\n    0,                                        /* tp_members */\n    0,                                        /* tp_getset */\n    0,                                        /* tp_base */\n    0,                                        /* tp_dict */\n    0,                                        /* tp_descr_get */\n    0,                                        /* tp_descr_set */\n    0,                                        /* tp_dictoffset */\n    (initproc)PyBobLearnSquareError_init,     /* tp_init */\n};\n\nPyDoc_STRVAR(s_crossentropyloss_str, BOB_EXT_MODULE_PREFIX \".CrossEntropyLoss\");\n\nPyDoc_STRVAR(s_crossentropyloss_doc,\n\"CrossEntropyLoss(actfun) -> new CrossEntropyLoss functor\\n\\\n\\n\\\nCalculates the Cross Entropy Loss between output and target.\\n\\\n\\n\\\nThe cross entropy loss is defined as follows:\\n\\\n\\n\\\n.. math::\\n\\\n   J = - y \\\\cdot \\\\log{(\\\\hat{y})} - (1-y) \\\\log{(1-\\\\hat{y})}\\n\\\n\\n\\\nwhere :math:`\\\\hat{y}` is the output estimated by your machine and\\n\\\n:math:`y` is the expected output.\\n\\\n\\n\\\nKeyword arguments:\\n\\\n\\n\\\nactfun\\n\\\n  The activation function object used at the last layer. If you\\n\\\n  set this to :py:class:`bob.learn.activation.Logistic`, a\\n\\\n  mathematical simplification is possible in which\\n\\\n  ``backprop_error()`` can benefit increasing the numerical\\n\\\n  stability of the training process. The simplification goes\\n\\\n  as follows:\\n\\\n  \\n\\\n  .. math::\\n\\\n     b = \\\\delta \\\\cdot \\\\varphi'(z)\\n\\\n  \\n\\\n  But, for the cross-entropy loss: \\n\\\n  \\n\\\n  .. math::\\n\\\n     \\\\delta = \\\\frac{\\\\hat{y} - y}{\\\\hat{y}(1 - \\\\hat{y})}\\n\\\n  \\n\\\n  and :math:`\\\\varphi'(z) = \\\\hat{y} - (1 - \\\\hat{y})`, so:\\n\\\n  \\n\\\n  .. math::\\n\\\n     b = \\\\hat{y} - y\\n\\\n\\n\\\n\");\n\nstatic int PyBobLearnCrossEntropyLoss_init\n(PyBobLearnCrossEntropyLossObject* self, PyObject* args, PyObject* kwds) {\n\n  /* Parses input arguments in a single shot */\n  static const char* const_kwlist[] = {\"actfun\", 0};\n  static char** kwlist = const_cast<char**>(const_kwlist);\n\n  PyObject* actfun = 0;\n\n  if (!PyArg_ParseTupleAndKeywords(args, kwds, \"O!\", kwlist,\n        &PyBobLearnActivation_Type, &actfun)) return -1;\n\n  try {\n    auto _actfun = reinterpret_cast<PyBobLearnActivationObject*>(actfun);\n    self->cxx.reset(new bob::learn::mlp::CrossEntropyLoss(_actfun->cxx));\n  }\n  catch (std::exception& ex) {\n    PyErr_SetString(PyExc_RuntimeError, ex.what());\n  }\n  catch (...) {\n    PyErr_Format(PyExc_RuntimeError, \"cannot create new object of type `%s' - unknown exception thrown\", Py_TYPE(self)->tp_name);\n  }\n\n  self->parent.cxx = self->cxx;\n\n  if (PyErr_Occurred()) return -1;\n\n  return 0;\n\n}\n\nstatic void PyBobLearnCrossEntropyLoss_delete\n(PyBobLearnCrossEntropyLossObject* self) {\n\n  self->parent.cxx.reset();\n  self->cxx.reset();\n  Py_TYPE(&self->parent)->tp_free((PyObject*)self);\n\n}\n\nPyDoc_STRVAR(s_logistic_activation_str, \"logistic_activation\");\nPyDoc_STRVAR(s_logistic_activation_doc,\n\"o.logistic_activation() -> bool\\n\\\n\\n\\\nTells if this functor is set to operate together with a\\n\\\n:py:class:`bob.learn.activation.Logistic` activation function.\\n\\\n\");\n\nstatic PyObject* PyBobLearnCrossEntropyLoss_getLogisticActivation\n(PyBobLearnCrossEntropyLossObject* self, void* /*closure*/) {\n  if (self->cxx->logistic_activation()) Py_RETURN_TRUE;\n  Py_RETURN_FALSE;\n}\n\nstatic PyGetSetDef PyBobLearnCrossEntropyLoss_getseters[] = {\n    {\n      s_logistic_activation_str,\n      (getter)PyBobLearnCrossEntropyLoss_getLogisticActivation,\n      0,\n      s_logistic_activation_doc,\n      0\n    },\n    {0}  /* Sentinel */\n};\n\nPyTypeObject PyBobLearnCrossEntropyLoss_Type = {\n    PyVarObject_HEAD_INIT(0, 0)\n    s_crossentropyloss_str,                        /*tp_name*/\n    sizeof(PyBobLearnCrossEntropyLossObject),      /*tp_basicsize*/\n    0,                                             /*tp_itemsize*/\n    (destructor)PyBobLearnCrossEntropyLoss_delete, /*tp_dealloc*/\n    0,                                             /*tp_print*/\n    0,                                             /*tp_getattr*/\n    0,                                             /*tp_setattr*/\n    0,                                             /*tp_compare*/\n    0,                                             /*tp_repr*/\n    0,                                             /*tp_as_number*/\n    0,                                             /*tp_as_sequence*/\n    0,                                             /*tp_as_mapping*/\n    0,                                             /*tp_hash */\n    0,                                             /*tp_call*/\n    0,                                             /*tp_str*/\n    0,                                             /*tp_getattro*/\n    0,                                             /*tp_setattro*/\n    0,                                             /*tp_as_buffer*/\n    Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,      /*tp_flags*/\n    s_crossentropyloss_doc,                        /* tp_doc */\n    0,\t\t                                         /* tp_traverse */\n    0,\t\t                                         /* tp_clear */\n    0,                                             /* tp_richcompare */\n    0,\t\t                                         /* tp_weaklistoffset */\n    0,\t\t                                         /* tp_iter */\n    0,\t\t                                         /* tp_iternext */\n    0,                                             /* tp_methods */\n    0,                                             /* tp_members */\n    PyBobLearnCrossEntropyLoss_getseters,          /* tp_getset */\n    0,                                             /* tp_base */\n    0,                                             /* tp_dict */\n    0,                                             /* tp_descr_get */\n    0,                                             /* tp_descr_set */\n    0,                                             /* tp_dictoffset */\n    (initproc)PyBobLearnCrossEntropyLoss_init,     /* tp_init */\n};\n", "meta": {"hexsha": "6a31dd69c8951032648f3a7528b69add93ead39b", "size": 26232, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "bob/learn/mlp/cost.cpp", "max_stars_repo_name": "bioidiap/bob.learn.mlp", "max_stars_repo_head_hexsha": "c4b1534236c94dc1acf16dcdc6e7d8478cdffd58", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "bob/learn/mlp/cost.cpp", "max_issues_repo_name": "bioidiap/bob.learn.mlp", "max_issues_repo_head_hexsha": "c4b1534236c94dc1acf16dcdc6e7d8478cdffd58", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2015-02-26T14:51:51.000Z", "max_issues_repo_issues_event_max_datetime": "2017-07-06T11:55:46.000Z", "max_forks_repo_path": "bob/learn/mlp/cost.cpp", "max_forks_repo_name": "bioidiap/bob.learn.mlp", "max_forks_repo_head_hexsha": "c4b1534236c94dc1acf16dcdc6e7d8478cdffd58", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2015-06-14T18:24:29.000Z", "max_forks_repo_forks_event_max_datetime": "2017-07-05T23:10:34.000Z", "avg_line_length": 34.976, "max_line_length": 218, "alphanum_fraction": 0.5715538274, "num_tokens": 6691, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.546738151984614, "lm_q2_score": 0.5506073655352404, "lm_q1q2_score": 0.30103805350185414}}
{"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 <limits>\n#include <tuple>\n\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 \"Domain/Structure/Direction.hpp\"\n#include \"Domain/Structure/ElementId.hpp\"\n#include \"Domain/Structure/MaxNumberOfNeighbors.hpp\"\n#include \"Utilities/ContainerHelpers.hpp\"\n#include \"Utilities/ErrorHandling/Assert.hpp\"\n\nnamespace LinearSolver::Schwarz {\n\n/// Identifies a subdomain region that overlaps with another element\ntemplate <size_t Dim>\nusing OverlapId = std::pair<Direction<Dim>, ElementId<Dim>>;\n\n/// Data structure that can store the `ValueType` on each possible overlap of an\n/// element-centered subdomain with its neighbors. Overlaps are identified by\n/// their `OverlapId`.\ntemplate <size_t Dim, typename ValueType>\nusing OverlapMap =\n    FixedHashMap<maximum_number_of_neighbors(Dim), OverlapId<Dim>, ValueType,\n                 boost::hash<OverlapId<Dim>>>;\n\n/*!\n * \\brief The number of points that an overlap extends into the `volume_extent`\n *\n * In a dimension where an element has `volume_extent` points, the overlap\n * extent is the largest number under these constraints:\n *\n * - It is at most `max_overlap`.\n * - It is smaller than the `volume_extent`.\n *\n * This means the overlap extent is always smaller than the `volume_extent`. The\n * reason for this constraint is that we define the _width_ of the overlap as\n * the element-logical coordinate distance from the face of the element to the\n * first collocation point _outside_ the overlap extent. Therefore, even an\n * overlap region that covers the full element in width does not include the\n * collocation point on the opposite side of the element.\n *\n * Here's a few notes on the definition of the overlap extent and width:\n *\n * - A typical smooth weighting function goes to zero at the overlap width, so\n *   if the grid points located at the overlap width were included in the\n *   subdomain, their solutions would not contribute to the weighted sum of\n *   subdomain solutions.\n * - Defining the overlap width as the distance to the first point _outside_ the\n *   overlap extent makes it non-zero even for a single point of overlap into a\n *   Gauss-Lobatto grid (which has points located at the element face).\n * - Boundary contributions for many (but not all) discontinuous Galerkin\n *   schemes on Gauss-Lobatto grids are limited to the grid points on the\n *   element face, e.g. for a DG operator that is pre-multiplied by the mass\n *   matrix, or one where boundary contributions are lifted using the diagonal\n *   mass-matrix approximation. Not including the grid points facing away from\n *   the subdomain in the overlap allows to ignore that face altogether in the\n *   subdomain operator.\n */\nsize_t overlap_extent(size_t volume_extent, size_t max_overlap) noexcept;\n\n/*!\n * \\brief Total number of grid points in an overlap region that extends\n * `overlap_extent` points into the `volume_extents` from either side in the\n * `overlap_dimension`\n *\n * The overlap region has `overlap_extent` points in the `overlap_dimension`,\n * and `volume_extents` points in the other dimensions. The number of grid\n * points returned by this function is the product of these extents.\n */\ntemplate <size_t Dim>\nsize_t overlap_num_points(const Index<Dim>& volume_extents,\n                          size_t overlap_extent,\n                          size_t overlap_dimension) noexcept;\n\n/*!\n * \\brief Width of an overlap extending `overlap_extent` points into the\n * `collocation_points` from either side.\n *\n * The \"width\" of an overlap is the element-logical coordinate distance from the\n * element boundary to the first collocation point outside the overlap region in\n * the overlap dimension, i.e. the dimension perpendicular to the element face.\n * See `LinearSolver::Schwarz::overlap_extent` for details.\n *\n * This function assumes the `collocation_points` are mirrored around 0.\n */\ndouble overlap_width(size_t overlap_extent,\n                     const DataVector& collocation_points) noexcept;\n\n/*!\n * \\brief Iterate over grid points in a region that extends partially into the\n * volume\n *\n * Here's an example how to use this iterator:\n *\n * \\snippet Test_OverlapHelpers.cpp overlap_iterator\n */\nclass OverlapIterator {\n public:\n  template <size_t Dim>\n  OverlapIterator(const Index<Dim>& volume_extents, size_t overlap_extent,\n                  const Direction<Dim>& direction) noexcept;\n\n  explicit operator bool() const noexcept;\n\n  OverlapIterator& operator++();\n\n  /// Offset into a DataVector that holds full volume data\n  size_t volume_offset() const noexcept;\n\n  /// Offset into a DataVector that holds data only on the overlap region\n  size_t overlap_offset() const noexcept;\n\n  void reset() noexcept;\n\n private:\n  size_t size_ = std::numeric_limits<size_t>::max();\n  size_t num_slices_ = std::numeric_limits<size_t>::max();\n  size_t stride_ = std::numeric_limits<size_t>::max();\n  size_t stride_count_ = std::numeric_limits<size_t>::max();\n  size_t jump_ = std::numeric_limits<size_t>::max();\n  size_t initial_offset_ = std::numeric_limits<size_t>::max();\n  size_t volume_offset_ = std::numeric_limits<size_t>::max();\n  size_t overlap_offset_ = std::numeric_limits<size_t>::max();\n};\n\n// @{\n/// The part of the tensor data that lies within the overlap region\ntemplate <size_t Dim, typename DataType, typename... TensorStructure>\nvoid data_on_overlap(const gsl::not_null<Tensor<DataType, TensorStructure...>*>\n                         restricted_tensor,\n                     const Tensor<DataType, TensorStructure...>& tensor,\n                     const Index<Dim>& volume_extents,\n                     const size_t overlap_extent,\n                     const Direction<Dim>& direction) noexcept {\n  for (OverlapIterator overlap_iterator{volume_extents, overlap_extent,\n                                        direction};\n       overlap_iterator; ++overlap_iterator) {\n    for (size_t tensor_component = 0; tensor_component < tensor.size();\n         ++tensor_component) {\n      (*restricted_tensor)[tensor_component][overlap_iterator\n                                                 .overlap_offset()] =\n          tensor[tensor_component][overlap_iterator.volume_offset()];\n    }\n  }\n}\n\ntemplate <size_t Dim, typename DataType, typename... TensorStructure>\nTensor<DataType, TensorStructure...> data_on_overlap(\n    const Tensor<DataType, TensorStructure...>& tensor,\n    const Index<Dim>& volume_extents, const size_t overlap_extent,\n    const Direction<Dim>& direction) noexcept {\n  Tensor<DataType, TensorStructure...> restricted_tensor{overlap_num_points(\n      volume_extents, overlap_extent, direction.dimension())};\n  data_on_overlap(make_not_null(&restricted_tensor), tensor, volume_extents,\n                  overlap_extent, direction);\n  return restricted_tensor;\n}\n\nnamespace detail {\ntemplate <size_t Dim>\nvoid data_on_overlap_impl(double* overlap_data, const double* volume_data,\n                          size_t num_components,\n                          const Index<Dim>& volume_extents,\n                          size_t overlap_extent,\n                          const Direction<Dim>& direction) noexcept;\n}  // namespace detail\n\ntemplate <size_t Dim, typename OverlapTagsList, typename VolumeTagsList>\nvoid data_on_overlap(\n    const gsl::not_null<Variables<OverlapTagsList>*> overlap_data,\n    const Variables<VolumeTagsList>& volume_data,\n    const Index<Dim>& volume_extents, const size_t overlap_extent,\n    const Direction<Dim>& direction) noexcept {\n  constexpr size_t num_components =\n      Variables<VolumeTagsList>::number_of_independent_components;\n  ASSERT(volume_data.number_of_grid_points() == volume_extents.product(),\n         \"volume_data has wrong number of grid points.  Expected \"\n             << volume_extents.product() << \", got \"\n             << volume_data.number_of_grid_points());\n  ASSERT(overlap_data->number_of_grid_points() ==\n             overlap_num_points(volume_extents, overlap_extent,\n                                direction.dimension()),\n         \"overlap_data has wrong number of grid points.  Expected \"\n             << overlap_num_points(volume_extents, overlap_extent,\n                                   direction.dimension())\n             << \", got \" << overlap_data->number_of_grid_points());\n  detail::data_on_overlap_impl(overlap_data->data(), volume_data.data(),\n                               num_components, volume_extents, overlap_extent,\n                               direction);\n}\n\ntemplate <size_t Dim, typename TagsList>\nVariables<TagsList> data_on_overlap(const Variables<TagsList>& volume_data,\n                                    const Index<Dim>& volume_extents,\n                                    const size_t overlap_extent,\n                                    const Direction<Dim>& direction) noexcept {\n  Variables<TagsList> overlap_data{overlap_num_points(\n      volume_extents, overlap_extent, direction.dimension())};\n  data_on_overlap(make_not_null(&overlap_data), volume_data, volume_extents,\n                  overlap_extent, direction);\n  return overlap_data;\n}\n// @}\n\nnamespace detail {\ntemplate <size_t Dim>\nvoid add_overlap_data_impl(double* volume_data, const double* overlap_data,\n                           size_t num_components,\n                           const Index<Dim>& volume_extents,\n                           size_t overlap_extent,\n                           const Direction<Dim>& direction) noexcept;\n}  // namespace detail\n\n/// Add the `overlap_data` to the `volume_data`\ntemplate <size_t Dim, typename VolumeTagsList, typename OverlapTagsList>\nvoid add_overlap_data(\n    const gsl::not_null<Variables<VolumeTagsList>*> volume_data,\n    const Variables<OverlapTagsList>& overlap_data,\n    const Index<Dim>& volume_extents, const size_t overlap_extent,\n    const Direction<Dim>& direction) noexcept {\n  constexpr size_t num_components =\n      Variables<VolumeTagsList>::number_of_independent_components;\n  ASSERT(volume_data->number_of_grid_points() == volume_extents.product(),\n         \"volume_data has wrong number of grid points.  Expected \"\n             << volume_extents.product() << \", got \"\n             << volume_data->number_of_grid_points());\n  ASSERT(overlap_data.number_of_grid_points() ==\n             overlap_num_points(volume_extents, overlap_extent,\n                                direction.dimension()),\n         \"overlap_data has wrong number of grid points.  Expected \"\n             << overlap_num_points(volume_extents, overlap_extent,\n                                   direction.dimension())\n             << \", got \" << overlap_data.number_of_grid_points());\n  detail::add_overlap_data_impl(volume_data->data(), overlap_data.data(),\n                                num_components, volume_extents, overlap_extent,\n                                direction);\n}\n\n// @{\n/// Extend the overlap data to the full mesh by filling it with zeros outside\n/// the overlap region\ntemplate <size_t Dim, typename ExtendedTagsList, typename OverlapTagsList>\nvoid extended_overlap_data(\n    const gsl::not_null<Variables<ExtendedTagsList>*> extended_data,\n    const Variables<OverlapTagsList>& overlap_data,\n    const Index<Dim>& volume_extents, const size_t overlap_extent,\n    const Direction<Dim>& direction) noexcept {\n  *extended_data = Variables<ExtendedTagsList>{volume_extents.product(), 0.};\n  add_overlap_data(extended_data, overlap_data, volume_extents, overlap_extent,\n                   direction);\n}\n\ntemplate <size_t Dim, typename TagsList>\nVariables<TagsList> extended_overlap_data(\n    const Variables<TagsList>& overlap_data, const Index<Dim>& volume_extents,\n    const size_t overlap_extent, const Direction<Dim>& direction) noexcept {\n  Variables<TagsList> extended_data{volume_extents.product()};\n  extended_overlap_data(make_not_null(&extended_data), overlap_data,\n                        volume_extents, overlap_extent, direction);\n  return extended_data;\n}\n// @}\n\n}  // namespace LinearSolver::Schwarz\n", "meta": {"hexsha": "6a81c115be0366e43ad45adf8cfdafb2d3871f55", "size": 12217, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/ParallelAlgorithms/LinearSolver/Schwarz/OverlapHelpers.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/ParallelAlgorithms/LinearSolver/Schwarz/OverlapHelpers.hpp", "max_issues_repo_name": "trami18/spectre", "max_issues_repo_head_hexsha": "6b1f6497bf2e26d1474bfadf143b3321942c40b4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2022-03-25T18:26:16.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-25T19:30:39.000Z", "max_forks_repo_path": "src/ParallelAlgorithms/LinearSolver/Schwarz/OverlapHelpers.hpp", "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": 44.4254545455, "max_line_length": 80, "alphanum_fraction": 0.7015633953, "num_tokens": 2507, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.5467381519846138, "lm_q1q2_score": 0.3010380535018541}}
{"text": "#ifndef TCM_CONSTANTS_HPP\n#define TCM_CONSTANTS_HPP\n\n#include <functional>\n#include <type_traits>\n#include <map>\n#include <unordered_map>\n#include <cmath>\n\n#include <boost/program_options.hpp>\n#include <boost/algorithm/string/erase.hpp>\n#include <boost/algorithm/string/predicate.hpp>\n#include <boost/range/adaptor/filtered.hpp>\n#include <boost/range/adaptor/transformed.hpp>\n\n\n///////////////////////////////////////////////////////////////////////////////\n/// \\file constants.hpp\n/// \\brief Defines the 'default' constants map.\n///\n/// \\detail We implement some useful functions to manipulate _physical_\n///         constants. These constants are represented as a symbol table\n///         mapping #std::string to some numerical type _R representing real\n///         field.\n///\n/// For the calculations, we're interested in the following constants:\n/// |              Key             |     Notation     | Value(default) | Dimension |\n/// | ---------------------------- | ---------------- | -------------- | --------- |\n/// | `pi`                         | \\f$\\pi\\f$        | 3.14159...     | 1         |\n/// | `boltzmann-constant`         | \\f$k_\\text{B}\\f$ | 8.61733...E-5  | eV        |\n/// | `elementary-charge`          | \\f$e\\f$          | 1.60217...E-19 | C         |\n/// | `planck-constant`            | \\f$\\hbar\\f$      | 6.58212...E-16 | eV        |\n/// | `self-interaction-potential` | \\f$V_0\\f$        | 15.78          | eV        |\n/// | `temperature`                | \\f$T\\f$          | 300.0          | K         |\n/// | `vacuum-permittivity`        | \\f$\\epsilon_0\\f$ | 8.85419...E-12 | F/m       |\n/// A table with these values can be easily obtained using the \n/// #default_constants() function.\n///\n/// For different simulations different values of, for example, temperature\n/// may be desired. To account for this case, we implement two additional\n/// functions: \n/// * #init_constants_options() simplifies the creation of \n///   boost::program_options::options_description for the user to be able\n///   to specify constants.\n/// * #load_constants() allows the creation of constants table from\n///   boost::program_options::variables_map, i.e. from command line arguments.\n///\n/// Here is an example how these functions can be used together:\n/// \\include src/constants_example.cpp\n///////////////////////////////////////////////////////////////////////////////\n\n\nnamespace tcm {\n\n//////////////////////////////////////////////////////////////////////////////\n/// \\brief Returns a table with default values for relevalnt physical \n///        constants.\n\n/// This function has the following behavior:\n/// \\snippet include/constants.hpp Default constants\n///\n/// \\todo make this function return std::unordered_map in place of std::map.\n/// Or even better, make the container type a template parameter.\n//////////////////////////////////////////////////////////////////////////////\ntemplate <class _R>\nauto default_constants() -> std::map<std::string, _R>\n{\n//! [Default constants]\n\tstd::map<std::string, _R> constants =\n\t\t{ {\"pi\",                          M_PI}\n\t\t, {\"boltzmann-constant\",          8.6173303E-5}\n\t\t, {\"chemical-potential\",          0.4}\n\t\t, {\"elementary-charge\",           1.6021766208E-19}\n\t\t, {\"planck-constant\",             6.582119514E-16}\n\t\t, {\"self-interaction-potential\",  15.78}\n\t\t, {\"temperature\",                 300.0}\n\t\t, {\"vacuum-permittivity\",         8.854187817E-12}\n\t\t, {\"tau\",                         6.0E-3}\n\t\t};\n\treturn constants;\n//! [Default constants]\n}\n\n\n///////////////////////////////////////////////////////////////////////////////\n/// \\brief Simplifies the creation of #options_descriptions concerning\n///        constants.\n\n/// Creates a #boost::program_options::options_description called \n/// _Simulation Constants_ with options of the form \"in.constants.KEY\" where\n/// KEYs are the names of the constants such as `pi` or `planck-constant`.\n/// Each of these options has a default value provided by the\n/// #default_constants() function. Template parameter `_R` specifies the type\n/// of the constants. It is used to create the default constants table and to\n/// extract values from `any` where program_options stores the values.\n///////////////////////////////////////////////////////////////////////////////\ntemplate <class _R>\nauto init_constants_options() -> boost::program_options::options_description\n{\n\tusing namespace boost::program_options;\n\toptions_description description{\"Simulation Constants\"};\n\tauto const cs = tcm::default_constants<_R>();\n\tdescription.add_options()\n\t\t( \"in.constants.pi\"\n\t\t, value<_R>()->default_value(cs.at(\"pi\"))\n\t\t, \"PI.\" )\n\t\t( \"in.constants.boltzmann-constant\"\n\t\t, value<_R>()->default_value(cs.at(\"boltzmann-constant\"))\n\t\t, \"Boltzmann constant.\" )\n\t\t( \"in.constants.chemical-potential\"\n\t\t, value<_R>()->default_value(cs.at(\"chemical-potential\"))\n\t\t, \"Chemical potential.\" )\n\t\t( \"in.constants.elementary-charge\"\n\t\t, value<_R>()->default_value(cs.at(\"elementary-charge\"))\n\t\t, \"Elementary charge.\" )\n\t\t( \"in.constants.planck-constant\"\n\t\t, value<_R>()->default_value(cs.at(\"planck-constant\"))\n\t\t, \"Planck constant\" )\n\t\t( \"in.constants.self-interaction-potential\"\n\t\t, value<_R>()->default_value(cs.at(\"self-interaction-potential\"))\n\t\t, \"Self interaction Coulomb potential.\" )\n\t\t( \"in.constants.temperature\"\n\t\t, value<_R>()->default_value(cs.at(\"temperature\"))\n\t\t, \"Temperature\" )\n\t\t( \"in.constants.vacuum-permittivity\"\n\t\t, value<_R>()->default_value(cs.at(\"vacuum-permittivity\"))\n\t\t, \"Vacuum permittivity.\" )\n\t\t( \"in.constants.tau\"\n\t\t, value<_R>()->default_value(cs.at(\"tau\"))\n\t\t, \"Relaxation time tau.\" );\n\treturn description;\n}\n\n\n///////////////////////////////////////////////////////////////////////////////\n/// \\brief Creates a constants table from a \n///        #boost::program_options::variables_map.\n\n/// This function iterates over entries in \\p vm, searches for all options\n/// that are of the form \"in.constants.*\", converts the values from\n/// boost::program_options::variable_value to _To and returns a table of \n/// type _Map consisting only of those options.\n/// \\snippet include/constants.hpp Load constants\n///////////////////////////////////////////////////////////////////////////////\ntemplate< class _To\n        , class _From = _To\n        , class _Map = std::unordered_map<std::string, _To> \n        >\nauto load_constants(boost::program_options::variables_map const& vm) -> _Map\n{\n\tstatic_assert( std::is_same<typename _Map::key_type, std::string>::value\n\t             , \"Wrong key_type: must be std::string.\" );\n\tstatic_assert( std::is_same<typename _Map::mapped_type, _To>::value\n\t             , \"Wrong mapped_type: must be _To.\" );\n//! [Load constants]\n\tconstexpr char const prefix[] = \"in.constants.\";\n\tauto const is_constant = [](auto const& p) { \n\t\treturn boost::algorithm::starts_with(p.first, prefix); \n\t};\n\n\tusing value_type = boost::program_options::variables_map::value_type;\n\tauto const mk_constant = [](value_type const& p) {\n\t\treturn std::make_pair(boost::algorithm::erase_head_copy(\n\t\t\tp.first, std::char_traits<char>::length(prefix)), \n\t\t\tp.second.as<_From>());\n\t};\n\n\tauto rng = vm | boost::adaptors::filtered(std::cref(is_constant))\n\t              | boost::adaptors::transformed(std::cref(mk_constant));\n\treturn _Map{rng.begin(), rng.end()};\n//! [Load constants]\n}\n\n\n///////////////////////////////////////////////////////////////////////////////\n/// \\brief Checks whether \\p key is in \\p constants map and throws if it is\n///        not.\n\n/// \\snippet include/constants.hpp Require constant\n///////////////////////////////////////////////////////////////////////////////\ntemplate<class _Map>\nauto require( std::string const& func_name\n            , _Map const& constants_map\n            , std::string const& key ) -> void\n{\n//! [Require constant]\n\tif (!constants_map.count(key)) {\n\t\tthrow std::runtime_error{ \"Constant `\" + key + \"` is required to run \"\n\t\t                          \"`\" + func_name + \"`!\" };\n\t}\n//! [Require constant]\n}\n\n} // namespace tcm\n\n#endif // TCM_CONSTANTS_HPP\n", "meta": {"hexsha": "1e7eac9b7b1e09abfcffce0032921d07f672cf5e", "size": 8021, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/constants.hpp", "max_stars_repo_name": "twesterhout/plasmon-cpp", "max_stars_repo_head_hexsha": "a0e343ee718d9b30602b322ade6077e42e08d8e5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-01-05T11:12:07.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-05T11:12:07.000Z", "max_issues_repo_path": "include/constants.hpp", "max_issues_repo_name": "twesterhout/plasmon-cpp", "max_issues_repo_head_hexsha": "a0e343ee718d9b30602b322ade6077e42e08d8e5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/constants.hpp", "max_forks_repo_name": "twesterhout/plasmon-cpp", "max_forks_repo_head_hexsha": "a0e343ee718d9b30602b322ade6077e42e08d8e5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.7157360406, "max_line_length": 84, "alphanum_fraction": 0.5797282134, "num_tokens": 1864, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.5506073655352404, "lm_q1q2_score": 0.3010380535018541}}
{"text": "// TopicModelLocalStepCPPX.cpp\n// Define this symbol to enable runtime tests for allocations\n#define EIGEN_RUNTIME_NO_MALLOC \n\n#include <math.h>\n#include <time.h>\n#include \"Eigen/Dense\"\n#include <boost/math/special_functions/digamma.hpp>\n#include <boost/math/special_functions/gamma.hpp>\n#include \"fastexp.h\"\nusing namespace Eigen;\nusing namespace std;\n\n// ======================================================== Declare funcs\n// ======================================================== visible externally\n\nextern \"C\" {\n    void sparseLocalStepManyDocs_ActiveOnly(  \n        double* alphaEbeta_IN,\n        double* Eloglik_IN,\n        double* word_count_IN,\n        int* word_id_IN,\n        int* doc_range_IN,\n        int nnzPerRow,\n        int Nall,\n        int K,\n        int D,\n        int V,\n        int nCoordAscentIterLP,\n        double convThrLP,\n        int initProbsToEbeta,\n        double* topicCount_OUT,\n        double* spResp_data_OUT,\n        int* spResp_colids_OUT,\n        int* numIterVec_OUT,\n        double* maxDiffVec_OUT,\n        int numRestarts,\n        int* rAcceptVec_IN,\n        int* rTrialVec_IN,\n        int REVISE_FIRST,\n        int REVISE_EVERY,\n        int verbose\n    );\n}\n\n// ======================================================== Custom Type Defs\n// ========================================================\n// Simple names for array types\ntypedef Matrix<double, Dynamic, Dynamic, RowMajor> Mat2D_d;\ntypedef Matrix<double, 1, Dynamic, RowMajor> Mat1D_d;\ntypedef Array<double, Dynamic, Dynamic, RowMajor> Arr2D_d;\ntypedef Array<double, 1, Dynamic, RowMajor> Arr1D_d;\ntypedef Array<int, 1, Dynamic, RowMajor> Arr1D_i;\n\n// Simple names for array types with externally allocated memory\ntypedef Map<Mat2D_d> ExtMat2D_d;\ntypedef Map<Mat1D_d> ExtMat1D_d;\ntypedef Map<Arr2D_d> ExtArr2D_d;\ntypedef Map<Arr1D_d> ExtArr1D_d;\ntypedef Map<Arr1D_i> ExtArr1D_i;\n\n\ndouble calcElapsedTime(timespec start_time, timespec end_time) {\n    double diffSec = (double) end_time.tv_sec - start_time.tv_sec;\n    double diffNano = (double) end_time.tv_nsec - start_time.tv_nsec;\n    return diffSec + diffNano / 1.0e9;\n}\n\n\nstruct LessThanFor1DArray {\n    const double* xptr;\n\n    LessThanFor1DArray(const double * xptrIN) {\n        xptr = xptrIN;\n    }\n\n    bool operator()(int i, int j) {\n        return xptr[i] < xptr[j];\n    }\n\n};\n\nstruct GreaterThanFor1DArray {\n    const double* xptr;\n\n    GreaterThanFor1DArray(const double * xptrIN) {\n        xptr = xptrIN;\n    }\n\n    bool operator()(int i, int j) {\n        return xptr[i] > xptr[j];\n    }\n};\n\nstruct Argsortable1DArray {\n    double* xptr;\n    int* iptr;\n    int size;\n    \n    // Constructor\n    Argsortable1DArray(double* xptrIN, int sizeIN) {\n        xptr = xptrIN;\n        size = sizeIN;\n        iptr = new int[size];\n        resetIndices(size);\n    }\n\n    // Helper method: reset iptr array to 0, 1, ... K-1 \n    void resetIndices(int cursize) {\n        assert(cursize <= size);\n        for (int i = 0; i < cursize; i++) {\n            iptr[i] = i;\n        }\n    }\n\n    void pprint() {\n        for (int i = 0; i < size; i++) {\n            printf(\"%03d:% 05.2f \",\n                this->iptr[i],\n                this->xptr[this->iptr[i]]);\n        }\n        printf(\"\\n\");\n    }\n\n    void argsort() {\n        this->argsort_AscendingOrder();\n    }\n\n    void argsort_AscendingOrder() {\n        std::sort(\n            this->iptr,\n            this->iptr + this->size,\n            LessThanFor1DArray(this->xptr)\n            );\n    }\n\n    void argsort_DescendingOrder() {\n        std::sort(\n            this->iptr,\n            this->iptr + this->size,\n            GreaterThanFor1DArray(this->xptr)\n            );\n    }\n\n    void findSmallestL(int L) {\n        assert(L >= 0);\n        assert(L < this->size);\n        std::nth_element(\n            this->iptr,\n            this->iptr + L,\n            this->iptr + this->size,\n            LessThanFor1DArray(this->xptr)\n            );\n    }\n\n    void findLargestL(int L, int Kactive) {\n        assert(L >= 0);\n        assert(L <= Kactive);\n        std::nth_element(\n            this->iptr,\n            this->iptr + Kactive - L,\n            this->iptr + Kactive,\n            LessThanFor1DArray(this->xptr)\n            );\n    }\n};\n\nvoid precomputeTopLRespForEachVocabTerm(\n        int nnzPerRow,\n        int V,\n        int K,\n        ExtArr2D_d & Eloglik,\n        ExtArr1D_d & alphaEbeta,\n        Arr1D_d & ElogProb,\n        Arr1D_d & logScores_n,\n        Arr1D_d & tempScores_n,\n        Arr1D_d & termResp_data,\n        Arr1D_i & termResp_colids\n        )\n{\n    ElogProb = alphaEbeta.log();\n    for (int v = 0; v < V; v++) {\n        int argmax_n = -1;\n        double maxScore_n;\n        double curScore;\n        for (int k = 0; k < K; k++) {\n            curScore = ElogProb(k) + Eloglik(v, k);\n            if (k == 0 || curScore > maxScore_n) {\n                maxScore_n = curScore;\n                if (nnzPerRow == 1) {\n                    argmax_n = k;\n                }\n            }\n            logScores_n(k) = curScore;\n        } // end loop over K\n        if (nnzPerRow == 1) {\n            termResp_data(v) = 1.0;\n            termResp_colids(v) = argmax_n;\n        } else {\n            // Find the top L entries in logScores_n\n            // Copy current row over into a temp buffer\n            std::copy(\n                logScores_n.data(),\n                logScores_n.data() + K,\n                tempScores_n.data());\n            // Sort the data in the temp buffer (in place)\n            std::nth_element(\n                tempScores_n.data(),\n                tempScores_n.data() + K - nnzPerRow,\n                tempScores_n.data() + K);\n            // Walk thru this row and find the top \"nnzPerRow\" positions\n            double pivotScore = tempScores_n(K - nnzPerRow);\n            double sumResp_n = 0.0;\n            int termResp_start = v * nnzPerRow;\n            int termResp_id = termResp_start;\n            for (int k = 0; k < K; k++) {\n                if (logScores_n(k) >= pivotScore) {\n                    termResp_data(termResp_id) = \\\n                        fastexp(logScores_n(k) - maxScore_n);\n                    termResp_colids(termResp_id) = k;\n                    sumResp_n += termResp_data(termResp_id);\n                    termResp_id += 1;                        \n                }\n            }\n            assert(termResp_id - v * nnzPerRow == nnzPerRow);\n            for (termResp_id = v * nnzPerRow;\n                    termResp_id < (v+1) * nnzPerRow;\n                    termResp_id++) {\n                termResp_data(termResp_id) /= sumResp_n;\n            }\n\n        }\n    }    \n}\n\nint updateActiveSetForDoc(\n        int d,\n        ExtArr2D_d & topicCount,\n        Arr1D_i & activeTopics_d,\n        Arr1D_i & spareActiveTopics_d,\n        double ACTIVE_THR,\n        int prevKactive,\n        int nnzPerRow\n        )\n{\n    int newKactive = 0;\n    int ia = 0; // spare inactive topics\n    for (int a = 0; a < prevKactive; a++) {\n        int k = activeTopics_d(a);\n        if (topicCount(d, k) > ACTIVE_THR) {\n            activeTopics_d(newKactive) = k;\n            newKactive += 1;\n        } else if (newKactive < nnzPerRow - ia) {\n            spareActiveTopics_d(ia) = k;\n            ia += 1;\n        }\n    }\n\n    int Kactive = newKactive;\n    while (Kactive < nnzPerRow) {\n        int k = spareActiveTopics_d(Kactive - newKactive);\n        activeTopics_d(Kactive) = k;\n        Kactive++;\n    }\n    return Kactive;\n}\n\n/*\n * Initialize activeTopics_d from provided topicCount\n * All K possible topics are available.\n */\nint updateActiveSetForDocFromScratch(\n        int d,\n        ExtArr2D_d & topicCount,\n        Arr1D_i & activeTopics_d,\n        Arr1D_i & spareActiveTopics_d,\n        double ACTIVE_THR,\n        int K,\n        int nnzPerRow\n        )\n{\n    int newKactive = 0;\n    int ia = 0; // spare inactive topics\n    for (int k = 0; k < K; k++) {\n        if (topicCount(d, k) > ACTIVE_THR) {\n            activeTopics_d(newKactive) = k;\n            newKactive += 1;\n        } else if (newKactive < nnzPerRow - ia) {\n            spareActiveTopics_d(ia) = k;\n            ia += 1;\n        }\n    }\n\n    int Kactive = newKactive;\n    while (Kactive < nnzPerRow) {\n        int k = spareActiveTopics_d(Kactive - newKactive);\n        activeTopics_d(Kactive) = k;\n        Kactive++;\n    }\n    return Kactive;\n}\n\ndouble calcELBOForDoc(\n    int d,\n    ExtArr1D_d & alphaEbeta,\n    ExtArr2D_d & topicCount,\n    Arr1D_d & ElogProb_d,\n    Arr1D_i & activeTopics_d,\n    double totalLogSumResp,\n    double sum_gammalnalphaEbeta,\n    int Kactive\n    )\n{\n    double ELBO = sum_gammalnalphaEbeta;\n    for (int ka = 0; ka < Kactive; ka++) {\n        int k = activeTopics_d(ka);\n        ELBO += (\n            boost::math::lgamma(topicCount(d, k) + alphaEbeta(k))\n            - boost::math::lgamma(alphaEbeta(k))\n            - topicCount(d, k) * ElogProb_d(k)\n            );\n    }\n    ELBO += totalLogSumResp;\n    return ELBO;\n}\n\n\ndouble updateAssignmentsForDoc_ReviseActiveSetDupOK(  \n    int d,\n    int start_d,\n    int N_d,\n    int nnzPerRow,\n    int Kactive,\n    ExtArr1D_d alphaEbeta, \n    ExtArr2D_d Eloglik,\n    ExtArr1D_d word_count,\n    ExtArr1D_i word_id,\n    ExtArr2D_d & topicCount,\n    ExtArr1D_d & spResp_data,\n    ExtArr1D_i & spResp_colids,\n    Arr1D_i & activeTopics_d,\n    Arr1D_d & ElogProb_d,\n    Arr1D_d & logScores_n,\n    Argsortable1DArray & logScoresHandler,\n    int initProbsToEbeta,\n    int doTrackELBO\n    )\n{\n    double totalLogSumResp = 0.0;\n\n    // Update ElogProb_d for active topics\n    if (initProbsToEbeta == 1) {\n        for (int ka = 0; ka < Kactive; ka++) {\n            int k = activeTopics_d(ka);\n            ElogProb_d(k) = log(alphaEbeta(k));\n        }\n    }  else {\n        for (int ka = 0; ka < Kactive; ka++) {\n            int k = activeTopics_d(ka);\n            ElogProb_d(k) = boost::math::digamma(\n                topicCount(d, k) + alphaEbeta(k));\n        }\n    }\n    // RESET topicCounts for doc d\n    topicCount.row(d).fill(0);\n\n    // Update Resp_d for active topics\n    // UPDATE assignments, obeying sparsity constraint\n    for (int n = start_d; n < start_d + N_d; n++) {\n        int spRind_dn_start = n * nnzPerRow;\n        double w_ct = word_count(n);\n        int w_id = word_id(n);\n        int argmax_n = 0;\n        double maxScore_n;\n        for (int ka = 0; ka < Kactive; ka++) {\n            int k = activeTopics_d(ka);\n            logScores_n(ka) = ElogProb_d(k) + Eloglik(w_id, k);\n            if (ka == 0 || logScores_n(ka) > maxScore_n) {\n                maxScore_n = logScores_n(ka);\n                if (nnzPerRow == 1) {\n                    argmax_n = k;\n                }\n            }\n        }\n        if (nnzPerRow == 1) {\n            spResp_data(spRind_dn_start) = 1.0;\n            spResp_colids(spRind_dn_start) = argmax_n;\n            topicCount(d, argmax_n) += w_ct;\n            if (doTrackELBO) {\n                totalLogSumResp += w_ct * maxScore_n;\n            }\n        } else {\n            // Use handler's built-in findLargestL functionality\n            logScoresHandler.resetIndices(Kactive);\n            logScoresHandler.findLargestL(nnzPerRow, Kactive);\n\n            // Read off the top L values into spR data structures\n            int spRind_dn = spRind_dn_start;\n            double sumResp_n = 0.0;\n            for (int j = 0; j < nnzPerRow; j++) {\n                int ka = logScoresHandler.iptr[Kactive - j - 1];\n                spResp_data(spRind_dn) = fastexp(\n                    logScoresHandler.xptr[ka] - maxScore_n);\n                spResp_colids(spRind_dn) = activeTopics_d(ka);\n                sumResp_n += spResp_data(spRind_dn);\n                spRind_dn += 1;\n            }\n            for (spRind_dn = spRind_dn_start;\n                    spRind_dn < spRind_dn_start + nnzPerRow; spRind_dn++) {\n                spResp_data(spRind_dn) /= sumResp_n;\n                topicCount(d, spResp_colids(spRind_dn)) += \\\n                    w_ct * spResp_data(spRind_dn);\n            }\n            if (doTrackELBO) {\n                totalLogSumResp += w_ct * (maxScore_n + log(sumResp_n));\n            }\n        } // end if statement branch for nnz > 1\n    } // end for loop over tokens in this doc\n    return totalLogSumResp;\n}\n\ndouble updateAssignmentsForDoc_ReviseActiveSet(  \n    int d,\n    int start_d,\n    int N_d,\n    int nnzPerRow,\n    int Kactive,\n    ExtArr1D_d alphaEbeta, \n    ExtArr2D_d Eloglik,\n    ExtArr1D_d word_count,\n    ExtArr1D_i word_id,\n    ExtArr2D_d & topicCount,\n    ExtArr1D_d & spResp_data,\n    ExtArr1D_i & spResp_colids,\n    Arr1D_i & activeTopics_d,\n    Arr1D_d & ElogProb_d,\n    Arr1D_d & logScores_n,\n    Arr1D_d & tempScores_n,\n    int initProbsToEbeta,\n    int doTrackELBO\n    )\n{\n    double totalLogSumResp = 0.0;\n\n    // Update ElogProb_d for active topics\n    if (initProbsToEbeta == 1) {\n        for (int ka = 0; ka < Kactive; ka++) {\n            int k = activeTopics_d(ka);\n            ElogProb_d(k) = log(alphaEbeta(k));\n        }\n    }  else {\n        for (int ka = 0; ka < Kactive; ka++) {\n            int k = activeTopics_d(ka);\n            ElogProb_d(k) = boost::math::digamma(\n                topicCount(d, k) + alphaEbeta(k));\n        }\n    }\n    // RESET topicCounts for doc d\n    topicCount.row(d).fill(0);\n\n    // Update Resp_d for active topics\n    // UPDATE assignments, obeying sparsity constraint\n    for (int n = start_d; n < start_d + N_d; n++) {\n        int spRind_dn_start = n * nnzPerRow;\n        double w_ct = word_count(n);\n        int w_id = word_id(n);\n        int argmax_n = 0;\n        double maxScore_n;\n        for (int ka = 0; ka < Kactive; ka++) {\n            int k = activeTopics_d(ka);\n            logScores_n(ka) = ElogProb_d(k) + Eloglik(w_id, k);\n            if (ka == 0 || logScores_n(ka) > maxScore_n) {\n                maxScore_n = logScores_n(ka);\n                if (nnzPerRow == 1) {\n                    argmax_n = k;\n                }\n            }\n        }\n        if (nnzPerRow == 1) {\n            spResp_data(spRind_dn_start) = 1.0;\n            spResp_colids(spRind_dn_start) = argmax_n;\n            topicCount(d, argmax_n) += w_ct;\n            if (doTrackELBO) {\n                totalLogSumResp += w_ct * maxScore_n;\n            }\n        } else {\n            // Find the top L entries in logScores_n\n            // Copy current row over into a temp buffer\n            std::copy(\n                logScores_n.data(),\n                logScores_n.data() + Kactive,\n                tempScores_n.data());\n            // Sort the data in the temp buffer (in place)\n            std::nth_element(\n                tempScores_n.data(),\n                tempScores_n.data() + Kactive - nnzPerRow,\n                tempScores_n.data() + Kactive);\n            // Walk thru this row and find the top \"nnzPerRow\" positions\n            double pivotScore = tempScores_n(Kactive - nnzPerRow);\n\n            int spRind_dn = spRind_dn_start;\n            double sumResp_n = 0.0;\n            for (int ka = 0; ka < Kactive; ka++) {\n                if (logScores_n(ka) >= pivotScore) {\n                    spResp_data(spRind_dn) = \\\n                        fastexp(logScores_n(ka) - maxScore_n);\n                    spResp_colids(spRind_dn) = activeTopics_d(ka);\n                    sumResp_n += spResp_data(spRind_dn);\n                    spRind_dn += 1;                        \n                }\n            }\n            assert(spRind_dn - spRind_dn_start == nnzPerRow);\n            for (spRind_dn = spRind_dn_start;\n                    spRind_dn < spRind_dn_start + nnzPerRow; spRind_dn++) {\n                spResp_data(spRind_dn) /= sumResp_n;\n                topicCount(d, spResp_colids(spRind_dn)) += \\\n                    w_ct * spResp_data(spRind_dn);\n            }\n            if (doTrackELBO) {\n                totalLogSumResp += w_ct * (maxScore_n + log(sumResp_n));\n            }\n        } // end if statement branch for nnz > 1\n    } // end for loop over tokens in this doc\n    return totalLogSumResp;\n}\n\n\n/* Update spResp_data values, keeping spResp_colids fixed.\n *\n */\nvoid updateAssignmentsForDoc_FixPerTokenActiveSet(  \n    int d,\n    int start_d,\n    int N_d,\n    int nnzPerRow,\n    int Kactive,\n    ExtArr1D_d alphaEbeta, \n    ExtArr2D_d Eloglik,\n    ExtArr1D_d word_count,\n    ExtArr1D_i word_id,\n    ExtArr2D_d & topicCount,\n    ExtArr1D_d & spResp_data,\n    ExtArr1D_i & spResp_colids,\n    Arr1D_i & activeTopics_d,\n    Arr1D_d & ElogProb_d,\n    Arr1D_d & logScores_n\n    )\n{\n    assert(nnzPerRow > 1);\n    //timespec start_time, end_time;\n    //clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &start_time);\n    // Update ElogProb_d for active topics\n    for (int ka = 0; ka < Kactive; ka++) {\n        int k = activeTopics_d(ka);\n        ElogProb_d(k) = boost::math::digamma(\n            topicCount(d, k) + alphaEbeta(k));\n    }\n    //clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &end_time);\n    //double timeSpent_Digamma = calcElapsedTime(start_time, end_time);\n\n    // RESET topicCounts for doc d\n    topicCount.row(d).fill(0);\n\n    //clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &start_time);\n    // Update Resp_d for active topics\n    for (int n = start_d; n < start_d + N_d; n++) {\n        int spRind_dn_start = n * nnzPerRow;\n        double w_ct = word_count(n);\n        int w_id = word_id(n);\n        double maxScore_n;\n        for (int ka = 0; ka < nnzPerRow; ka++) {\n            int k = spResp_colids(spRind_dn_start + ka);\n            logScores_n(ka) = ElogProb_d(k) + Eloglik(w_id, k);\n            if (ka == 0 || logScores_n(ka) > maxScore_n) {\n                maxScore_n = logScores_n(ka);\n            }\n        }\n\n        double sumResp_n = 0.0;\n        for (int ka = 0; ka < nnzPerRow; ka++) {\n            spResp_data(spRind_dn_start + ka) = \\\n                fastexp(logScores_n(ka) - maxScore_n);\n            sumResp_n += spResp_data(spRind_dn_start + ka);\n        }\n\n        for (int ka = 0; ka < nnzPerRow; ka++) {\n            spResp_data(spRind_dn_start + ka) /= sumResp_n;\n            topicCount(d, spResp_colids(spRind_dn_start + ka)) += \\\n                w_ct * spResp_data(spRind_dn_start + ka);\n        }\n\n    } // end for loop over tokens in this doc\n    /*clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &end_time);\n    double timeSpent_Resp = calcElapsedTime(start_time, end_time);\n    logScores_n(0) = timeSpent_Digamma;\n    logScores_n(1) = timeSpent_Resp;\n    */\n}\n\n\ndouble tryRestartsForDoc(\n    int d,\n    int start_d,\n    int N_d,\n    int nnzPerRow,\n    int Kactive,\n    ExtArr1D_d alphaEbeta, \n    ExtArr2D_d Eloglik,\n    ExtArr1D_d word_count,\n    ExtArr1D_i word_id,\n    ExtArr2D_d & topicCount,\n    ExtArr1D_d & spResp_data,\n    ExtArr1D_i & spResp_colids,\n    Arr1D_i & activeTopics_d,\n    Arr1D_d & prevTopicCount_d,\n    Arr1D_d & ElogProb_d,\n    Arr1D_d & logScores_n,\n    Argsortable1DArray & logScoresHandler,\n    //Arr1D_d & tempScores_n,\n    ExtArr1D_i & rAcceptVec,\n    ExtArr1D_i & rTrialVec,\n    int numRestarts,\n    double sum_gammalnalphaEbeta,\n    int verbose\n    )\n{\n    // Find active topics eligible for sparse restart\n    int nAccept = 0;\n    int nTrial = 0;\n    \n    double CANDIDATE_THR = 1e-10;\n    double curELBO = 0.0;\n    double totalLogSumResp = 0.0;\n    prevTopicCount_d.fill(0);\n    if (verbose > 1 && d < 1) {\n        printf(\"\\nSPARSE RESTARTS at doc %d!!\\n\", d);\n    }\n    if (verbose > 1 && d < 1) {\n        for (int ka = 0; ka < Kactive; ka++) {\n            int k = activeTopics_d(ka);\n            printf(\" %03d:%06.2f\", k, topicCount(d,k));\n        }\n        printf(\"\\n\");\n    }\n    for (int riter = 0; riter < numRestarts; riter++) {\n        // Seach for smallest topic we have yet to try\n        double minVal = N_d + 1.0; // Will never be a value in topicCount\n        int numAboveThr = 0;\n        int chosenTopicID = -1;\n        for (int ka = 0; ka < Kactive; ka++) {\n            int k = activeTopics_d(ka);\n            if (topicCount(d, k) > CANDIDATE_THR) {\n                numAboveThr += 1;\n                if (topicCount(d, k) < minVal) {\n                    minVal = topicCount(d, k);\n                    chosenTopicID = k;\n                }\n            }\n        }\n\n        // Need at least two topics with non-neglible size to try restarting.\n        // Otherwise, we should just quit\n        if (numAboveThr <= 1 || chosenTopicID < 0) {\n            break;\n        }\n\n        if (riter == 0) {\n            totalLogSumResp = updateAssignmentsForDoc_ReviseActiveSetDupOK(\n                d, start_d, N_d, nnzPerRow, Kactive,\n                alphaEbeta, Eloglik, word_count, word_id, \n                topicCount, spResp_data, spResp_colids,\n                activeTopics_d, ElogProb_d, logScores_n, logScoresHandler,\n                0, 1);\n            // ELBO for current configuration\n            curELBO = calcELBOForDoc(d, alphaEbeta, topicCount,\n                ElogProb_d, activeTopics_d,\n                totalLogSumResp, sum_gammalnalphaEbeta, Kactive);\n            // Remember the best-known topic-count vector!\n            for (int ka = 0; ka < Kactive; ka++) {\n                int k = activeTopics_d(ka);\n                prevTopicCount_d(k) = topicCount(d, k);\n            }\n        }\n\n        if (verbose > 1 && d < 1) {\n            printf(\"START: best known counts. ELBO=%.5e \\n\", curELBO);\n            for (int ka = 0; ka < Kactive; ka++) {\n                int k = activeTopics_d(ka);\n                printf(\"%02d:%06.2f \", k, topicCount(d, k));\n            }\n            printf(\"\\n\");\n        }\n\n        // Force chosen topic to zero\n        topicCount(d, chosenTopicID) = 0.0;\n        if (verbose > 1 && d < 1) {        \n            printf(\n                \"RESTART: Set index %d to zero (%d left)\\n\", \n                chosenTopicID, numAboveThr - 1);\n            for (int ka = 0; ka < Kactive; ka++) {\n                int k = activeTopics_d(ka);\n                printf(\"%02d:%06.2f \", k, topicCount(d, k));\n            }\n            printf(\"\\n\");\n        }\n        // Run inference forward from forced new location\n        int NSTEP = 2;\n        for (int step = 0; step < NSTEP; step++) { \n            totalLogSumResp = updateAssignmentsForDoc_ReviseActiveSetDupOK(\n                d, start_d, N_d, nnzPerRow, Kactive,\n                alphaEbeta, Eloglik, word_count, word_id, \n                topicCount, spResp_data, spResp_colids,\n                activeTopics_d, ElogProb_d, logScores_n, logScoresHandler,\n                0, step == NSTEP - 1);\n        }\n        // If the change is small, abandon current proposal\n        double propELBO;\n        if (abs(prevTopicCount_d(chosenTopicID) - topicCount(d, chosenTopicID)) < 1e-5) {\n            propELBO = curELBO;\n        } else {\n            propELBO = calcELBOForDoc(d, alphaEbeta, topicCount,\n                ElogProb_d, activeTopics_d,\n                totalLogSumResp, sum_gammalnalphaEbeta, Kactive);\n        }\n        if (verbose > 1 && d < 1) {\n            for (int ka = 0; ka < Kactive; ka++) {\n                int k = activeTopics_d(ka);\n                printf(\"%02d:%06.2f \", k, topicCount(d, k));\n            }\n            printf(\"\\n\");\n            printf(\"propELBO % .6e\\n\", propELBO);\n            printf(\" curELBO % .6e\\n\", curELBO);\n            if (propELBO > curELBO) {\n                printf(\"beforeCount: %.6f\\n\", prevTopicCount_d(chosenTopicID));\n                printf(\" afterCount: %.6f\\n\", topicCount(d, chosenTopicID));\n                printf(\"gainELBO % .6e ACCEPTED \\n\", propELBO - curELBO);\n            } else {\n                printf(\"gainELBO % .6e rejected \\n\", propELBO - curELBO);\n            }\n        }\n\n        // Reset threshold for which topic to choose next\n        CANDIDATE_THR = prevTopicCount_d(chosenTopicID);\n\n        // If accepted, set current best doc-topic counts to latest proposal\n        // Otherwise, reset the starting point for the next proposal.\n        if (propELBO > curELBO) {\n            curELBO = propELBO;\n            for (int ka = 0; ka < Kactive; ka++) {\n                int k = activeTopics_d(ka);\n                prevTopicCount_d(k) = topicCount(d, k);\n            }\n            nAccept += 1;\n        } else {\n            for (int ka = 0; ka < Kactive; ka++) {\n                int k = activeTopics_d(ka);\n                topicCount(d, k) = prevTopicCount_d(k);\n            }\n        }\n        nTrial += 1;\n\n        if (verbose > 1 && d < 1) {\n            printf(\"topicCount(d,k) = %.5e\\n\", topicCount(d,chosenTopicID));\n            printf(\"prevTopicCount(d,k) = %.5e\\n\", prevTopicCount_d(chosenTopicID));\n            printf(\"NEW THR = %.5e\\n\", CANDIDATE_THR);\n        }\n\n    } // end loop over restarts\n\n    if (numRestarts > 0 && nTrial > 0) {\n        rAcceptVec(0) += nAccept;\n        rTrialVec(0) += nTrial;\n        for (int ka = 0; ka < Kactive; ka++) {\n            int k = activeTopics_d(ka);\n            topicCount(d, k) = prevTopicCount_d(k);\n        }\n        // Final update! Make sure spResp reflects best topicCounts found\n        updateAssignmentsForDoc_ReviseActiveSetDupOK(\n            d, start_d, N_d, nnzPerRow, Kactive,\n            alphaEbeta, Eloglik, word_count, word_id, \n            topicCount, spResp_data, spResp_colids,\n            activeTopics_d, ElogProb_d, logScores_n, logScoresHandler,\n            0, 0);\n    } // end if to synchronize at best known assignments\n\n    return curELBO;\n}\n\nvoid sparseLocalStepManyDocs_ActiveOnly(\n        double* alphaEbeta_IN,\n        double* Eloglik_IN,\n        double* word_count_IN,\n        int* word_id_IN,\n        int* doc_range_IN,\n        int nnzPerRow,\n        int Nall,\n        int K,\n        int D,\n        int V,\n        int nCoordAscentIterLP,\n        double convThrLP,\n        int initProbsToEbeta,\n        double* topicCount_OUT,\n        double* spResp_data_OUT,\n        int* spResp_colids_OUT,\n        int* numIterVec_OUT,\n        double* maxDiffVec_OUT,\n        int numRestarts,\n        int* rAcceptVec_IN,\n        int* rTrialVec_IN,\n        int REVISE_FIRST,\n        int REVISE_EVERY,\n        int verbose\n        )\n{\n    /*timespec start_time, end_time;\n    double timeSpent_FindActive = 0.0;\n    double timeSpent_Assign = 0.0;\n    double timeSpent_AssignFixed = 0.0;\n    double timeSpent_Restart = 0.0;\n    double timeSpent_AssignFixed_Digamma = 0.0;\n    double timeSpent_AssignFixed_Resp = 0.0;\n    */\n    nCoordAscentIterLP = max(nCoordAscentIterLP, 0);\n    if (initProbsToEbeta == 1) {\n        nCoordAscentIterLP += 1;\n    }\n    nCoordAscentIterLP = max(nCoordAscentIterLP, 1);\n\n    if (nnzPerRow == 1) {\n        REVISE_EVERY = 1;\n    } else {\n        REVISE_EVERY = max(REVISE_EVERY, 1);    \n    }\n    REVISE_FIRST = max(REVISE_FIRST, 0);\n\n    int CHECK_EVERY = 5; // Check convergence every X iterations.\n\n    // Allocate temporary storage\n    Arr1D_d ElogProb_d (K);\n    Arr1D_d prevTopicCount_d (K);\n    Arr1D_d logScores_n (K);\n    Arr1D_d tempScores_n (K);\n    Arr1D_i activeTopics_d (K);\n    Arr1D_i spareActiveTopics_d (nnzPerRow);\n    \n    Arr1D_d termResp_data;\n    Arr1D_i termResp_colids;\n\n    Argsortable1DArray logScoresHandler = Argsortable1DArray(\n        logScores_n.data(), K);  \n\n    if (initProbsToEbeta == 2) {\n        termResp_data = Arr1D_d::Zero(V * nnzPerRow);\n        termResp_colids = Arr1D_i::Zero(V * nnzPerRow);   \n    }\n\n    // Disable all further memory allocation.\n    // We do this to verify that we have no memory leaks!\n    internal::set_is_malloc_allowed(false);\n\n    // Unpack input arrays\n    ExtArr1D_d alphaEbeta (alphaEbeta_IN, K);\n    ExtArr2D_d Eloglik (Eloglik_IN, V, K);\n\n    ExtArr1D_d word_count (word_count_IN, Nall);\n    ExtArr1D_i word_id (word_id_IN, Nall);\n    ExtArr1D_i doc_range (doc_range_IN, D+1);\n\n    // Unpack output arrays\n    ExtArr1D_d spResp_data (spResp_data_OUT, Nall * nnzPerRow);\n    ExtArr1D_i spResp_colids (spResp_colids_OUT, Nall * nnzPerRow);\n    ExtArr2D_d topicCount (topicCount_OUT, D, K);\n\n    ExtArr1D_i numIterVec (numIterVec_OUT, D);\n    ExtArr1D_d maxDiffVec (maxDiffVec_OUT, D);\n\n    ExtArr1D_i rAcceptVec (rAcceptVec_IN, 1);\n    ExtArr1D_i rTrialVec (rTrialVec_IN, 1);\n    \n    // Compute quantity used in sparse restart ELBO computation\n    double sum_gammalnalphaEbeta = 0.0;\n    if (numRestarts > 0) {\n        for (int k = 0; k < K; k++) {\n            sum_gammalnalphaEbeta += boost::math::lgamma(alphaEbeta(k));\n        }\n    }\n\n    if (initProbsToEbeta == 2) {\n        precomputeTopLRespForEachVocabTerm(\n            nnzPerRow, V, K,\n            Eloglik,\n            alphaEbeta,\n            ElogProb_d,\n            logScores_n,\n            tempScores_n,\n            termResp_data,\n            termResp_colids);\n        if (verbose > 0) {\n            printf(\"Precalculated Topics-by-term\\n\");\n            for (int v = 0; v < 5; v++) {\n                printf(\"term %06d \", v);\n                for (int vid = v * nnzPerRow; vid < (v+1) * nnzPerRow; vid++) {\n                    printf(\"%03d:%.2f \",\n                        termResp_colids(vid), termResp_data(vid));\n                }\n                printf(\"\\n\");\n            }\n            for (int v = V-5; v < V; v++) {\n                printf(\"term %06d \", v);\n                for (int vid = v * nnzPerRow; vid < (v+1) * nnzPerRow; vid++) {\n                    printf(\"%03d:%.2f \",\n                        termResp_colids(vid), termResp_data(vid));\n                }\n                printf(\"\\n\");\n            }\n        }\n    }\n\n    // Visit each document and update its spResp (and corresponding topicCount)\n    for (int d = 0; d < D; d++) {\n        if (verbose == 2 && d < 1) {\n            printf(\"\\nSTANDARD INFERENCE AT DOC %d\\n\", d);\n        }\n\n        int start_d = doc_range(d);\n        int N_d = doc_range(d+1) - doc_range(d);\n\n        prevTopicCount_d.fill(0);\n        double maxDiff = N_d;\n        int iter = 0;\n        double ACTIVE_THR = 1e-9;\n        int doReviseActiveSet = 1;\n        int Kactive = K;\n        // Initialize activeTopics_d and topicCount_d    \n        if (initProbsToEbeta == 2) {\n            // using the precomputed per-token resp values!\n            for (int n = start_d; n < start_d + N_d; n++) {\n                int wid = word_id(n);\n                for (int a = wid * nnzPerRow; a < (wid+1) * nnzPerRow; a++) {\n                    int k = termResp_colids(a);\n                    topicCount(d, k) += word_count(n) * termResp_data(a);\n                }\n            }\n            Kactive = updateActiveSetForDocFromScratch(\n                d,\n                topicCount,\n                activeTopics_d,\n                spareActiveTopics_d,\n                ACTIVE_THR,\n                K, nnzPerRow);\n        } else if (initProbsToEbeta == 0) {\n             Kactive = updateActiveSetForDocFromScratch(\n                 d,\n                 topicCount,\n                 activeTopics_d,\n                 spareActiveTopics_d,\n                 ACTIVE_THR,\n                 K, nnzPerRow);\n        } else {\n            // Initialize active set to ALL topics    \n            Kactive = K;\n            for (int k = 0; k < K; k++) {\n                activeTopics_d(k) = k;\n            }\n        }\n\n        for (iter = 0; iter < nCoordAscentIterLP; iter++) {\n            //clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &start_time);\n            // DETERMINE CURRENT ACTIVE SET\n            if (iter > 0 && nnzPerRow > 1 && Kactive <= nnzPerRow) {\n                // Set of active docs is already as small as can be,\n                // so nothing to gain from revising\n                doReviseActiveSet = 0;\n            } else if (iter < REVISE_FIRST || (iter - 1) % REVISE_EVERY == 0) {\n                doReviseActiveSet = 1;\n            } else {\n                doReviseActiveSet = 0;\n            }\n            if (iter > 0 && doReviseActiveSet) {\n                Kactive = updateActiveSetForDoc(\n                    d,\n                    topicCount,\n                    activeTopics_d,\n                    spareActiveTopics_d,\n                    ACTIVE_THR,\n                    Kactive, nnzPerRow);\n            }\n            assert(Kactive >= nnzPerRow);\n            assert(Kactive <= K);\n            //clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &end_time);\n            //timeSpent_FindActive += calcElapsedTime(start_time, end_time);\n\n            // COMPUTE ASSIGNMENTS FOR CURRENT ACTIVE SET\n            if (doReviseActiveSet) {\n                //clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &start_time);\n                updateAssignmentsForDoc_ReviseActiveSetDupOK(\n                    d, start_d, N_d, nnzPerRow, Kactive,\n                    alphaEbeta,\n                    Eloglik,\n                    word_count,\n                    word_id,\n                    topicCount,\n                    spResp_data,\n                    spResp_colids,\n                    activeTopics_d,\n                    ElogProb_d,\n                    logScores_n,\n                    logScoresHandler,\n                    (initProbsToEbeta == 1) && (iter == 0),\n                    0);\n                //clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &end_time);\n                //timeSpent_Assign += calcElapsedTime(start_time, end_time);\n            } else {\n                //clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &start_time);\n                updateAssignmentsForDoc_FixPerTokenActiveSet(\n                    d, start_d, N_d, nnzPerRow, Kactive,\n                    alphaEbeta,\n                    Eloglik,\n                    word_count,\n                    word_id,\n                    topicCount,\n                    spResp_data,\n                    spResp_colids,\n                    activeTopics_d,\n                    ElogProb_d,\n                    logScores_n\n                    );\n                /*clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &end_time);\n                timeSpent_AssignFixed += calcElapsedTime(start_time, end_time);\n                timeSpent_AssignFixed_Digamma += logScores_n(0);\n                timeSpent_AssignFixed_Resp += logScores_n(1);\n                */\n            }\n\n            // END ITERATION. Decide whether to quit early\n            // Find maximum difference from previous doc-topic count\n            if (iter % CHECK_EVERY == 0 && iter > 0) {\n                double absDiff_k = 0.0;\n                maxDiff = 0.0;\n                for (int ka = 0; ka < Kactive; ka++) {\n                    int k = activeTopics_d(ka);\n                    absDiff_k = abs(prevTopicCount_d(k) - topicCount(d, k));\n                    if (absDiff_k > maxDiff) {\n                        maxDiff = absDiff_k;\n                    }\n                }\n            }\n\n            if (verbose == 2 && d < 1) {\n                printf(\"d %3d iter %3d doRevise %d Kactive %4d maxDiff %11.6f\\n\",\n                    d, iter, doReviseActiveSet, Kactive, maxDiff);\n                printf(\"  \");\n                for (int ka = 0; ka < Kactive; ka++) {\n                    int k = activeTopics_d(ka);\n                    printf(\"%02d:%06.2f \", k, topicCount(d,k));\n                }\n                printf(\"\\n\");\n            }\n            if (maxDiff <= convThrLP) {\n                if (verbose > 2) {\n                    printf(\"EARLY EXIT! maxDiff < %11.6f\\n\", convThrLP);\n                }\n                break;\n            }\n\n            if (iter % CHECK_EVERY == CHECK_EVERY - 1) {\n                // Make sure prevTopicCount vector is updated\n                for (int ka = 0; ka < Kactive; ka++) {\n                    int k = activeTopics_d(ka);\n                    prevTopicCount_d(k) = topicCount(d, k);\n                }\n            }\n\n        } // end loop over iterations at doc d\n        maxDiffVec(d) = maxDiff;\n        numIterVec(d) = iter; // iter will already be +1'd by last iter of loop\n\n        if (numRestarts > 0) {\n            //clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &start_time);\n            tryRestartsForDoc(\n                d, start_d, N_d, nnzPerRow, Kactive,\n                alphaEbeta,\n                Eloglik,\n                word_count,\n                word_id,\n                topicCount,\n                spResp_data,\n                spResp_colids,\n                activeTopics_d,\n                prevTopicCount_d,\n                ElogProb_d,\n                logScores_n,\n                logScoresHandler,\n                rAcceptVec,\n                rTrialVec,\n                numRestarts,\n                sum_gammalnalphaEbeta,\n                verbose\n                );\n           //clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &end_time);\n           //timeSpent_Restart += calcElapsedTime(start_time, end_time);\n\n        }\n    } // end loop over documents\n    internal::set_is_malloc_allowed(true);\n\n    if (verbose > 0) {\n        printf(\n            \"Sparse Restarts: %d/%d accepted\\n\", rAcceptVec(0), rTrialVec(0));\n    }\n\n    /*\n    double timeSpent_total = \\\n        timeSpent_FindActive + timeSpent_Assign + \\\n        timeSpent_AssignFixed + timeSpent_Restart;\n\n    printf(\"FindActive   %8.3f sec  %.3f %%\\n\", timeSpent_FindActive,\n        timeSpent_FindActive / timeSpent_total);\n    printf(\"Assign:      %8.3f sec  %.3f %%\\n\", timeSpent_Assign,\n        timeSpent_Assign / timeSpent_total);\n    printf(\"AssignFixed: %8.3f sec  %.3f %%\\n\", timeSpent_AssignFixed,\n        timeSpent_AssignFixed / timeSpent_total);\n    printf(\"  -Digamma:  %8.3f sec\\n\", timeSpent_AssignFixed_Digamma);\n    printf(\"  -Resp:     %8.3f sec\\n\", timeSpent_AssignFixed_Resp);\n    printf(\"Restarts:    %8.3f sec  %.3f %%\\n\", timeSpent_Restart,\n        timeSpent_Restart / timeSpent_total);\n    printf(\"TOTAL:       %8.3f sec\\n\", timeSpent_total);\n    */\n}\n\n", "meta": {"hexsha": "afee4cb6d5984bfa4ea221960cfde35a268bac54", "size": 37452, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "bnpy/util/lib/sparseResp/TopicModelLocalStepManyDocsCPPX.cpp", "max_stars_repo_name": "jun2tong/bnp-anomaly", "max_stars_repo_head_hexsha": "c7fa106b5bb29ed6688a3d91e3f302a0a130b896", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 184.0, "max_stars_repo_stars_event_min_datetime": "2016-12-13T21:05:48.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-28T11:47:23.000Z", "max_issues_repo_path": "bnpy/util/lib/sparseResp/TopicModelLocalStepManyDocsCPPX.cpp", "max_issues_repo_name": "jun2tong/bnp-anomaly", "max_issues_repo_head_hexsha": "c7fa106b5bb29ed6688a3d91e3f302a0a130b896", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 37.0, "max_issues_repo_issues_event_min_datetime": "2016-12-18T14:07:53.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-13T10:58:14.000Z", "max_forks_repo_path": "bnpy/util/lib/sparseResp/TopicModelLocalStepManyDocsCPPX.cpp", "max_forks_repo_name": "jun2tong/bnp-anomaly", "max_forks_repo_head_hexsha": "c7fa106b5bb29ed6688a3d91e3f302a0a130b896", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 50.0, "max_forks_repo_forks_event_min_datetime": "2017-01-25T19:44:34.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-15T10:22:01.000Z", "avg_line_length": 33.0848056537, "max_line_length": 89, "alphanum_fraction": 0.5307860728, "num_tokens": 10229, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5467381372136563, "lm_q2_score": 0.5506073655352404, "lm_q1q2_score": 0.30103804536885603}}
{"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: lambertGrid.cc,v $\n//       Version: $Revision: 1.6 $  Dated: $Date: 2012-01-06 19:57:45 $\n//\n//==============================================================================\n\n/**\n * @file cloudGrid.cc\n *\n * Convert lat-longs cloud 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 \"LambertConfigReader.hh\"\n#include \"Proj4Wrap.hh\"\n\nusing boost::format;\nusing std::string;\nusing std::vector;\n\n// Functions\n\n\n\nvoid usage(char *programName)\n{\n  fprintf(stderr, \"Usage: %s configFile\\n\", programName);\n}\n\n\nint main(int argc, char **argv)\n{\n  printf(\"argc %d\\n\", argc);\n\n  if (argc != 2)\n    {\n      usage(argv[0]);\n      exit(2);\n    }\n\n  LambertConfigReader cfg(argv[1]);\n  if (cfg.error != string(\"\"))\n    {\n      printf(\"Error: configuration file error %s\\n\", cfg.error.c_str());\n      return 1;\n    }\n\n  // Uses latitude where lambert conformal projection is true and\n  // median aligned with cartesian y-axis\n  string paramString = str(format(\"+proj=lcc +R=6371200 +lon_0=%1% +lat_0=%2% +lat_1=%3% +lat_2=%4%\") % cfg.lov % cfg.latin1 % cfg.latin1 % cfg.latin2);\n\n  printf(\"paramString %s\\n\", paramString.c_str());\n  p4w::Proj4Wrap lambertProj(paramString, p4w::Proj4Wrap::LON_LAT_TYPE, cfg.lo1, cfg.la1, cfg.dx, cfg.dy);\n  double xc;\n  double yc;\n  double lon;\n  double lat;\n  \n  lambertProj.ll2xy(cfg.lo1, cfg.la1, &xc, &yc);\n  printf(\"lower corner for %g %g: xc, yc: %g %g\\n\", cfg.lo1, cfg.la1, xc, yc);\n  lambertProj.ll2xy(-57.383, 55.481, &xc, &yc);\n  printf(\"upper corner for -57.383, 55.481 : xc, yc: %g %g\\n\", xc, yc);\n  lambertProj.xy2ll(0, 0, &lon, &lat);\n  printf(\"0,0 lon, lat: %g %g\\n\", lon, lat);\n  lambertProj.xy2ll(1, 0, &lon, &lat);\n  printf(\"1,0 lon, lat: %g %g\\n\", lon, lat);\n  lambertProj.xy2ll(2, 0, &lon, &lat);\n  printf(\"2,0 lon, lat: %g %g\\n\", lon, lat);\n  lambertProj.xy2ll(cfg.nx-1, cfg.ny-1, &lon, &lat);\n  printf(\"%d, %d, lon, lat: %g %g\\n\", cfg.nx-1, cfg.ny-1, lon, lat);\n  /*\n  */\n\n  vector<float> xvec;\n  vector<float> yvec;\n\n  for (int i=0; i<cfg.ny; i++)\n    {\n      for (int j=0; j<cfg.nx; j++)\n\t{\n\t  lat = cfg.la1 + i * cfg.dy;\n\t  lon = cfg.lo1 + j * cfg.dx;\n\n\t  lambertProj.ll2xy(lon, lat, &xc, &yc);\n\t  xvec.push_back(xc);\n\t  yvec.push_back(yc);\n\t}\n    }\n\n  // Print cdl header\n\n  printf(\"netcdf coord {\\n\");\n  printf(\"dimensions:\\n\");\n  printf(\"y = %d ;\\n\", cfg.ny);\n  printf(\"x = %d ;\\n\", cfg.nx);\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\");\n\n  printf(\"x = \\n\");\n  for (uint i=0; i<xvec.size()-1; i++)\n    {\n      printf(\"%.7f,\\n\", xvec[i]);\n    }\n\n  printf(\"%.7f;\\n\", xvec[xvec.size()-1]);\n\n  printf(\"y = \\n\");\n\n  for (uint i=0; i<yvec.size()-1; i++)\n    {\n      printf(\"%.7f,\\n\", yvec[i]);\n    }\n  printf(\"%.7f;\\n\", yvec[yvec.size()-1]);\n\n\n  printf(\"}\\n\");\n}\n\n\n", "meta": {"hexsha": "e2a27b900cc35fe6e92785b2a9840f7b85b970e2", "size": 3270, "ext": "cc", "lang": "C++", "max_stars_repo_path": "libs/Proj4Wrap/src/Proj4Wrap/lambertGrid.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/lambertGrid.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/lambertGrid.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": 24.0441176471, "max_line_length": 152, "alphanum_fraction": 0.5544342508, "num_tokens": 1098, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5428632831725053, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.3010016570306031}}
{"text": "// Copyright (C) 2016-2018 T. Zachary Laine\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//[ self_evaluation\n#include <boost/yap/expression.hpp>\n\n#include <boost/optional.hpp>\n#include <boost/hana/fold.hpp>\n#include <boost/hana/maximum.hpp>\n\n#include <algorithm>\n#include <cassert>\n#include <iostream>\n#include <vector>\n\n\n// A super-basic matrix type, and a few associated operations.\nstruct matrix\n{\n    matrix() : values_(), rows_(0), cols_(0) {}\n\n    matrix(int rows, int cols) : values_(rows * cols), rows_(rows), cols_(cols)\n    {\n        assert(0 < rows);\n        assert(0 < cols);\n    }\n\n    int rows() const { return rows_; }\n    int cols() const { return cols_; }\n\n    double operator()(int r, int c) const\n    { return values_[r * cols_ + c]; }\n    double & operator()(int r, int c)\n    { return values_[r * cols_ + c]; }\n\nprivate:\n    std::vector<double> values_;\n    int rows_;\n    int cols_;\n};\n\nmatrix operator*(matrix const & lhs, double x)\n{\n    matrix retval = lhs;\n    for (int i = 0; i < retval.rows(); ++i) {\n        for (int j = 0; j < retval.cols(); ++j) {\n            retval(i, j) *= x;\n        }\n    }\n    return retval;\n}\nmatrix operator*(double x, matrix const & lhs) { return lhs * x; }\n\nmatrix operator+(matrix const & lhs, matrix const & rhs)\n{\n    assert(lhs.rows() == rhs.rows());\n    assert(lhs.cols() == rhs.cols());\n    matrix retval = lhs;\n    for (int i = 0; i < retval.rows(); ++i) {\n        for (int j = 0; j < retval.cols(); ++j) {\n            retval(i, j) += rhs(i, j);\n        }\n    }\n    return retval;\n}\n\n// daxpy() means Double-precision AX Plus Y.  This crazy name comes from BLAS.\n// It is more efficient than a naive implementation, because it does not\n// create temporaries.  The covnention of using Y as an out-parameter comes\n// from FORTRAN BLAS.\nmatrix & daxpy(double a, matrix const & x, matrix & y)\n{\n    assert(x.rows() == y.rows());\n    assert(x.cols() == y.cols());\n    for (int i = 0; i < y.rows(); ++i) {\n        for (int j = 0; j < y.cols(); ++j) {\n            y(i, j) += a * x(i, j);\n        }\n    }\n    return y;\n}\n\ntemplate <boost::yap::expr_kind Kind, typename Tuple>\nstruct self_evaluating_expr;\n\ntemplate <boost::yap::expr_kind Kind, typename Tuple>\nauto evaluate_matrix_expr(self_evaluating_expr<Kind, Tuple> const & expr);\n\n// This is the primary template for our expression template.  If you assign a\n// self_evaluating_expr to a matrix, its conversion operator transforms and\n// evaluates the expression with a call to evaluate_matrix_expr().\ntemplate <boost::yap::expr_kind Kind, typename Tuple>\nstruct self_evaluating_expr\n{\n    operator auto() const;\n\n    static const boost::yap::expr_kind kind = Kind;\n\n    Tuple elements;\n};\n\n// This is a specialization of our expression template for assignment\n// expressions.  The destructor transforms and evaluates via a call to\n// evaluate_matrix_expr(), and then assigns the result to the variable on the\n// left side of the assignment.\n//\n// In a production implementation, you'd need to have specializations for\n// plus_assign, minus_assign, etc.\ntemplate <typename Tuple>\nstruct self_evaluating_expr<boost::yap::expr_kind::assign, Tuple>\n{\n    ~self_evaluating_expr();\n\n    static const boost::yap::expr_kind kind = boost::yap::expr_kind::assign;\n\n    Tuple elements;\n};\n\nstruct use_daxpy\n{\n    // A plus-expression, which may be of the form double * matrix + matrix,\n    // or may be something else.  Since our daxpy() above requires a mutable\n    // \"y\", we only need to match a mutable lvalue matrix reference here.\n    template <typename Tuple>\n    auto operator()(\n        boost::yap::expr_tag<boost::yap::expr_kind::plus>,\n        self_evaluating_expr<boost::yap::expr_kind::multiplies, Tuple> const & expr,\n        matrix & m)\n    {\n        // Here, we transform the left-hand side into a pair if it's the\n        // double * matrix operation we're looking for.  Otherwise, we just\n        // get a copy of the left side expression.\n        //\n        // Note that this is a bit of a cheat, done for clarity.  If we pass a\n        // larger expression that happens to contain a double * matrix\n        // subexpression, that subexpression will be transformed into a tuple!\n        // In production code, this transform should probably only be\n        // performed on an expression with all terminal members.\n        auto lhs = boost::yap::transform(\n            expr,\n            [](boost::yap::expr_tag<boost::yap::expr_kind::multiplies>,\n               double d,\n               matrix const & m) {\n                return std::pair<double, matrix const &>(d, m);\n            });\n\n        // If we got back a copy of expr above, just re-construct the\n        // expression this function mathes; in other words, do not effectively\n        // transform anything.  Otherwise, replace the expression matched by\n        // this function with a call to daxpy().\n        if constexpr (boost::yap::is_expr<decltype(lhs)>::value) {\n            return expr + m;\n        } else {\n            return boost::yap::make_terminal(daxpy)(lhs.first, lhs.second, m);\n        }\n    }\n};\n\n\n// This is the heart of what self_evaluating_expr does.  If we had other\n// optimizations/transformations we wanted to do, we'd put them in this\n// function, either before or after the use_daxpy transformation.\ntemplate <boost::yap::expr_kind Kind, typename Tuple>\nauto evaluate_matrix_expr(self_evaluating_expr<Kind, Tuple> const & expr)\n{\n    auto daxpy_form = boost::yap::transform(expr, use_daxpy{});\n    return boost::yap::evaluate(daxpy_form);\n}\n\ntemplate<boost::yap::expr_kind Kind, typename Tuple>\nself_evaluating_expr<Kind, Tuple>::operator auto() const\n{\n    return evaluate_matrix_expr(*this);\n}\n\ntemplate<typename Tuple>\nself_evaluating_expr<boost::yap::expr_kind::assign, Tuple>::\n    ~self_evaluating_expr()\n{\n    using namespace boost::hana::literals;\n    boost::yap::evaluate(elements[0_c]) = evaluate_matrix_expr(elements[1_c]);\n}\n\n// In order to define the = operator with the semantics we want, it's\n// convenient to derive a terminal type from a terminal instantiation of\n// self_evaluating_expr.  Note that we could have written a template\n// specialization here instead -- either one would work.  That would of course\n// have required more typing.\nstruct self_evaluating :\n    self_evaluating_expr<\n        boost::yap::expr_kind::terminal,\n        boost::hana::tuple<matrix>\n    >\n{\n    self_evaluating() {}\n\n    explicit self_evaluating(matrix m)\n    { elements = boost::hana::tuple<matrix>(std::move(m)); }\n\n    BOOST_YAP_USER_ASSIGN_OPERATOR(self_evaluating_expr, ::self_evaluating_expr);\n};\n\nBOOST_YAP_USER_BINARY_OPERATOR(plus, self_evaluating_expr, self_evaluating_expr)\nBOOST_YAP_USER_BINARY_OPERATOR(minus, self_evaluating_expr, self_evaluating_expr)\nBOOST_YAP_USER_BINARY_OPERATOR(multiplies, self_evaluating_expr, self_evaluating_expr)\n\n\nint main()\n{\n    matrix identity(2, 2);\n    identity(0, 0) = 1.0;\n    identity(1, 1) = 1.0;\n\n    // These are YAP-ified terminal expressions.\n    self_evaluating m1(identity);\n    self_evaluating m2(identity);\n    self_evaluating m3(identity);\n\n    // This transforms the YAP expression to use daxpy(), so it creates no\n    // temporaries.  The transform happens in the destructor of the\n    // assignment-expression specialization of self_evaluating_expr.\n    m1 = 3.0 * m2 + m3;\n\n    // Same as above, except that it uses the matrix conversion operator on\n    // the self_evaluating_expr primary template, because here we're assigning\n    // a YAP expression to a non-YAP-ified matrix.\n    matrix m_result_1 = 3.0 * m2 + m3;\n\n    // Creates temporaries and does not use daxpy(), because the A * X + Y\n    // pattern does not occur within the expression.\n    matrix m_result_2 = 3.0 * m2;\n\n    return 0;\n}\n//]\n", "meta": {"hexsha": "d5c7323d744e2a8eb900be441c6553160463ffcd", "size": 7890, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "3rdParty/boost/1.71.0/libs/yap/example/self_evaluation.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/yap/example/self_evaluation.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/yap/example/self_evaluation.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": 33.1512605042, "max_line_length": 86, "alphanum_fraction": 0.6685678074, "num_tokens": 1993, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.30100165703060305}}
{"text": "//==============================================================================\n//         Copyright 2003 - 2011 LASMEA UMR 6602 CNRS/Univ. Clermont II\n//         Copyright 2009 - 2011 LRI    UMR 8623 CNRS/Univ Paris Sud XI\n//\n//          Distributed under the Boost Software License, Version 1.0.\n//                 See accompanying file LICENSE.txt or copy at\n//                     http://www.boost.org/LICENSE_1_0.txt\n//==============================================================================\n#ifndef BOOST_SIMD_ARITHMETIC_FUNCTIONS_SCALAR_VMX_FAST_RSQRT_HPP_INCLUDED\n#define BOOST_SIMD_ARITHMETIC_FUNCTIONS_SCALAR_VMX_FAST_RSQRT_HPP_INCLUDED\n#if defined(BOOST_SIMD_HAS_VMX_SUPPORT)\n\n#include <boost/simd/arithmetic/functions/fast_rsqrt.hpp>\n#include <boost/simd/include/functions/simd/multiplies.hpp>\n#include <boost/simd/include/functions/simd/minus.hpp>\n\nnamespace boost { namespace simd { namespace ext\n{\n  BOOST_DISPATCH_IMPLEMENT          ( fast_rsqrt_\n                                    , boost::simd::tag::vmx_\n                                    , (A0)\n                                    , (scalar_< single_<A0> >)\n                                    )\n  {\n    typedef A0 result_type;\n\n    BOOST_FORCEINLINE result_type operator()(float a0) const\n    {\n      float r;\n      __asm__ (\"frsqrte %0, %1\"\n              : \"=f\" (r)\n              : \"f\" (a0)\n              );\n\n      r *= ((3.0f - (r * r) * a0) * 0.5f);\n      r *= ((3.0f - (r * r) * a0) * 0.5f);\n\n      return r;\n    }\n  };\n\n  BOOST_DISPATCH_IMPLEMENT          ( fast_rsqrt_\n                                    , boost::simd::tag::vmx_\n                                    , (A0)\n                                    , (scalar_< double_<A0> >)\n                                    )\n  {\n    typedef A0 result_type;\n\n    BOOST_FORCEINLINE result_type operator()(double a0) const\n    {\n      double r;\n      __asm__ (\"frsqrte %0, %1\"\n              : \"=f\" (r)\n              : \"f\" (a0)\n              );\n\n      r *= ((3.0f - (r * r) * a0) * 0.5f);\n      r *= ((3.0f - (r * r) * a0) * 0.5f);\n      r *= ((3.0f - (r * r) * a0) * 0.5f);\n\n      return r;\n    }\n  };\n} } }\n\n#endif\n\n#endif\n", "meta": {"hexsha": "3e5b874e408de1e6169b983c08dd8b7aa1180c8a", "size": 2156, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/boost/simd/base/include/boost/simd/arithmetic/functions/scalar/vmx/fast_rsqrt.hpp", "max_stars_repo_name": "psiha/nt2", "max_stars_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 34.0, "max_stars_repo_stars_event_min_datetime": "2017-05-19T18:10:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-04T02:18:13.000Z", "max_issues_repo_path": "modules/boost/simd/base/include/boost/simd/arithmetic/functions/scalar/vmx/fast_rsqrt.hpp", "max_issues_repo_name": "psiha/nt2", "max_issues_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "modules/boost/simd/base/include/boost/simd/arithmetic/functions/scalar/vmx/fast_rsqrt.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": 30.8, "max_line_length": 80, "alphanum_fraction": 0.4522263451, "num_tokens": 556, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6584175139669997, "lm_q2_score": 0.4571367168274948, "lm_q1q2_score": 0.30098682063659543}}
{"text": "//////////////////////////////////////////////////////////////////////////////\n//\n// (C) Copyright Alejandro Cabrera 2011.\n// Distributed under the Boost\n// Software License, Version 1.0.\n// (See accompanying file LICENSE_1_0.txt or\n// copy at http://www.boost.org/LICENSE_1_0.txt)\n//\n// See http://www.boost.org/libs/bloom_filter for documentation.\n//\n//////////////////////////////////////////////////////////////////////////////\n\n#ifndef BOOST_BLOOM_FILTER_TWOHASH_DYNAMIC_BASIC_BLOOM_FILTER_HPP\n#define BOOST_BLOOM_FILTER_TWOHASH_DYNAMIC_BASIC_BLOOM_FILTER_HPP 1\n\n#include <cmath>\n\n#include <boost/config.hpp>\n#include <boost/dynamic_bitset.hpp>\n\n#include <boost/bloom_filter/hash/default.hpp>\n#include <boost/bloom_filter/hash/murmurhash3.hpp>\n#include <boost/bloom_filter/detail/extenders.hpp>\n#include <boost/bloom_filter/detail/twohash_apply_hash.hpp>\n#include <boost/bloom_filter/detail/exceptions.hpp>\n\nnamespace boost {\n  namespace bloom_filters {\n    template <typename T,\n\t      size_t HashValues = 2,\n\t      size_t ExpectedInsertionCount = 0,\n\t      class HashFunction1 = boost_hash<T>,\n\t      class HashFunction2 = murmurhash3<T>, \n\t      typename ExtensionFunction = detail::square,\n\t      typename Block = size_t,\n\t      typename Allocator = std::allocator<Block> >// = ???\n    class twohash_dynamic_basic_bloom_filter {\n    public:\n      typedef T value_type;\n      typedef T key_type;\n      typedef Block block_type;\n      typedef Allocator allocator_type;\n      typedef boost::dynamic_bitset<Block, Allocator> bitset_type;\n      typedef HashFunction1 hash_function1_type;\n      typedef HashFunction2 hash_function2_type;\n      typedef ExtensionFunction extension_function_type;\n      typedef twohash_dynamic_basic_bloom_filter<T, \n\t\t\t\t\t\t HashValues,\n\t\t\t\t\t\t ExpectedInsertionCount,\n\t\t\t\t\t\t HashFunction1,\n\t\t\t\t\t\t HashFunction2,\n\t\t\t\t\t\t ExtensionFunction,\n\t\t\t\t\t\t Block,\n\t\t\t\t\t\t Allocator> this_type;\n\n      static const size_t default_size = 32;\n\n    private:\n      typedef detail::twohash_apply_hash<HashValues,\n\t\t\t\t\t this_type> apply_hash_type;\n\n    public:\n      //* constructors\n      twohash_dynamic_basic_bloom_filter()\n\t: bits(default_size)\n      {\n      }\n\n      explicit twohash_dynamic_basic_bloom_filter(const size_t size)\n\t: bits(size)\n      {\n      }\n\n      template <typename InputIterator>\n      twohash_dynamic_basic_bloom_filter(const InputIterator start, \n\t\t\t\t const InputIterator end)\n\t: bits(std::distance(start, end) * 4)\n      {\n\tfor (InputIterator i = start; i != end; ++i)\n\t  this->insert(*i);\n      }\n\n      //* meta-ops\n      size_t bit_capacity() const\n      {\n\treturn bits.size();\n      }\n\n      static BOOST_CONSTEXPR size_t num_hash_functions()\n      {\n\treturn HashValues;\n      }\n\n      static BOOST_CONSTEXPR size_t expected_insertion_count()\n      {\n\treturn ExpectedInsertionCount;\n      }\n\n      double false_positive_rate() const\n      {\n        const double n = static_cast<double>(this->bits.count());\n        static const double k = static_cast<double>(HashValues);\n        static const double m = static_cast<double>(this->bit_capacity());\n        static const double e =\n\t  2.718281828459045235360287471352662497757247093699959574966;\n        return std::pow(1 - std::pow(e, -k * n / m), k);\n      }\n\n      size_t count() const\n      {\n\treturn this->bits.count();\n      }\n\n      bool empty() const\n      {\n\treturn this->count() == 0;\n      }\n\n      const bitset_type&\n      data() const \n      {\n\treturn this->bits;\n      }\n\n      //* core ops\n      void insert(const T& t)\n      {\n\tapply_hash_type::insert(t, bits);\n      }\n\n      template <typename InputIterator>\n      void insert(const InputIterator start, \n\t\t  const InputIterator end)\n      {\n\tfor (InputIterator i = start; i != end; ++i)\n\t  this->insert(*i);\n      }\n\n      bool probably_contains(const T& t) const\n      {\n\treturn apply_hash_type::contains(t, bits);\n      }\n\n      void clear()\n      {\n\tthis->bits.reset();\n      }\n\n      void swap(twohash_dynamic_basic_bloom_filter& other)\n      {\n\ttwohash_dynamic_basic_bloom_filter tmp = other;\n\tother = *this;\n\t*this = tmp;\n      }\n\n      //* pairwise ops\n      twohash_dynamic_basic_bloom_filter& \n      operator|=(const twohash_dynamic_basic_bloom_filter& rhs)\n      {\n\tif (this->bit_capacity() != rhs.bit_capacity())\n\t  throw detail::incompatible_size_exception();\n\n\tthis->bits |= rhs.bits;\n\treturn *this;\n      }\n\n      twohash_dynamic_basic_bloom_filter& \n      operator&=(const twohash_dynamic_basic_bloom_filter& rhs)\n      {\n\tif (this->bit_capacity() != rhs.bit_capacity())\n\t  throw detail::incompatible_size_exception();\n\n\tthis->bits &= rhs.bits;\n\treturn *this;\n      }\n\n      template<class _T, size_t _HashValues, \n\t       size_t _ExpectedInsertionCount,\n\t       class _HashFunction1,\n\t       class _HashFunction2,\n\t       class _ExtensionFunction,\n\t       typename _Block, class _Allocator>\n      friend bool\n      operator==(const twohash_dynamic_basic_bloom_filter<_T, \n\t\t                                          _HashValues, \n\t\t\t\t\t\t          _ExpectedInsertionCount,\n\t\t\t\t\t\t          _HashFunction1,\n\t\t\t\t\t\t          _HashFunction2,\n\t\t                                          _ExtensionFunction,\n\t\t                                          _Block,\n\t\t                                          _Allocator>&,\n\t\t const twohash_dynamic_basic_bloom_filter<_T, \n\t\t                                          _HashValues,\n\t\t\t\t\t\t          _ExpectedInsertionCount,\n\t\t\t\t\t\t          _HashFunction1,\n\t\t\t\t\t\t          _HashFunction2,\n\t\t                                          _ExtensionFunction,\n\t\t                                          _Block,\n\t\t                                          _Allocator>&);\n      \n    private:\n      bitset_type bits;\n    };\n\n    //* global ops\n    template<class T, size_t HashValues, \n\t     size_t ExpectedInsertionCount,\n\t     class HashFunction1,\n\t     class HashFunction2, class ExtensionFunction,\n\t     typename Block, class Allocator>\n    bool\n    operator==(const twohash_dynamic_basic_bloom_filter<T, \n\t       \t       \t       \t       \t       \t        HashValues,\n\t                                                ExpectedInsertionCount,\n\t                                                HashFunction1,\n\t                                                HashFunction2,\n\t                                                ExtensionFunction,\n\t                                                Block, \n\t                                                Allocator>& lhs,\n\t       const twohash_dynamic_basic_bloom_filter<T, \n\t                                        HashValues,\n\t\t\t\t\t\tExpectedInsertionCount,\n\t\t\t\t\t\tHashFunction1,\n\t\t\t\t\t\tHashFunction2,\n\t                                        ExtensionFunction,\n\t                                        Block,\n\t                                        Allocator>& rhs)\n    {\n\tif (lhs.bit_capacity() != rhs.bit_capacity())\n\t  throw detail::incompatible_size_exception();\n\n      return lhs.bits == rhs.bits;\n    }\n\n    template<class T, size_t HashValues, \n\t     size_t ExpectedInsertionCount,\n\t     class HashFunction1,\n\t     class HashFunction2, class ExtensionFunction,\n\t     typename Block, class Allocator>\n    bool\n    operator!=(const twohash_dynamic_basic_bloom_filter<T, \n\t       \t       \t       \t       \t       \t        HashValues,\n\t                                                ExpectedInsertionCount,\n\t                                                HashFunction1,\n\t                                                HashFunction2,\n\t                                                ExtensionFunction,\n\t                                                Block, \n\t                                                Allocator>& lhs,\n\t       const twohash_dynamic_basic_bloom_filter<T, \n\t                                                HashValues,\n\t\t\t\t\t\t        ExpectedInsertionCount,\n\t\t\t\t\t\t        HashFunction1,\n\t\t\t\t\t\t        HashFunction2,\n\t                                                ExtensionFunction,\n\t                                                Block,\n\t                                                Allocator>& rhs)\n    {\n      return !(lhs == rhs);\n    }\n    \n    template<class T, size_t HashValues, \n\t     size_t ExpectedInsertionCount,\n\t     class HashFunction1,\n\t     class HashFunction2, class ExtensionFunction,\n\t     typename Block, class Allocator>\n    twohash_dynamic_basic_bloom_filter<T, \n\t\t\t\t       HashValues,\n\t\t\t\t       ExpectedInsertionCount,\n\t\t\t\t       HashFunction1, \n\t\t\t\t       HashFunction2, ExtensionFunction,\n\t\t\t\t       Block, Allocator>\n    operator|(const twohash_dynamic_basic_bloom_filter<T, \n\t                                               HashValues,\n\t                                               ExpectedInsertionCount,\n\t                                               HashFunction1,\n\t                                               HashFunction2,\n\t                                               ExtensionFunction,\n\t                                               Block,\n\t                                               Allocator>& lhs,\n\t      const twohash_dynamic_basic_bloom_filter<T, \n\t                                               HashValues,\n\t                                               ExpectedInsertionCount,\n\t                                               HashFunction1,\n\t                                               HashFunction2,\n\t                                               ExtensionFunction,\n\t                                               Block,\n\t                                               Allocator>& rhs)\n    {\n      twohash_dynamic_basic_bloom_filter<T, HashValues,\n\t\t\t\t\t ExpectedInsertionCount,\n\t\t\t\t\t HashFunction1, HashFunction2,\n\t\t\t\t\t ExtensionFunction,\n\t\t\t\t\t Block,\n\t\t\t\t\t Allocator> result(lhs);\n      \n      result |= rhs;\n      return result;\n    }\n\n    template<class T, size_t HashValues, \n\t     size_t ExpectedInsertionCount,\n\t     class HashFunction1,\n\t     class HashFunction2, class ExtensionFunction,\n\t     typename Block, class Allocator>\n    twohash_dynamic_basic_bloom_filter<T, \n\t\t\t\t       HashValues,\n\t\t\t\t       ExpectedInsertionCount,\n\t\t\t\t       HashFunction1, \n\t\t\t\t       HashFunction2, ExtensionFunction,\n\t\t\t\t       Block, Allocator>\n    operator&(const twohash_dynamic_basic_bloom_filter<T, \n\t                                               HashValues,\n\t                                               ExpectedInsertionCount,\n\t                                               HashFunction1,\n\t                                               HashFunction2,\n\t                                               ExtensionFunction,\n\t                                               Block,\n\t                                               Allocator>& lhs,\n\t      const twohash_dynamic_basic_bloom_filter<T, \n\t                                               HashValues,\n\t                                               ExpectedInsertionCount,\n\t                                               HashFunction1,\n\t                                               HashFunction2,\n\t                                               ExtensionFunction,\n\t                                               Block,\n\t                                               Allocator>& rhs)\n    {\n      twohash_dynamic_basic_bloom_filter<T, HashValues,\n\t\t\t\t\t ExpectedInsertionCount,\n\t\t\t\t\t HashFunction1, HashFunction2,\n\t\t\t\t\t ExtensionFunction,\n\t\t\t\t\t Block,\n\t\t\t\t\t Allocator> result(lhs);\n      \n      result &= rhs;\n      return result;\n    }\n\n    template<class T, size_t Size, size_t HashValues, \n\t     size_t ExpectedInsertionCount, \n\t     class HashFunction1,\n\t     class HashFunction2, class ExtensionFunction,\n\t     typename Block, class Allocator>\n    void swap(twohash_dynamic_basic_bloom_filter<T, \n\t                                         HashValues,\n\t                                         ExpectedInsertionCount,\n\t                                         HashFunction1,\n\t                                         HashFunction2,\n\t                                         ExtensionFunction,\n\t                                         Block,\n\t                                         Allocator>& lhs,\n\t      twohash_dynamic_basic_bloom_filter<T, \n\t                                         HashValues,\n\t                                         ExpectedInsertionCount,\n\t                                         HashFunction1,\n\t                                         HashFunction2,\n\t                                         ExtensionFunction,\n\t                                         Block,\n\t                                         Allocator>& rhs)\n    {\n      return lhs.swap(rhs);\n    }\n  } // namespace bloom_filters\n} // namespace boost\n#endif\n \n", "meta": {"hexsha": "a9aba4823d6a247a330e367ae20ee305985e94fd", "size": 12636, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/bloom_filter/twohash_dynamic_basic_bloom_filter.hpp", "max_stars_repo_name": "tetzank/boost-bloom-filters", "max_stars_repo_head_hexsha": "7c6717f403c041a092187568908f3661782ddb24", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 15.0, "max_stars_repo_stars_event_min_datetime": "2016-10-18T16:05:37.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-23T03:01:42.000Z", "max_issues_repo_path": "boost/bloom_filter/twohash_dynamic_basic_bloom_filter.hpp", "max_issues_repo_name": "tetzank/boost-bloom-filters", "max_issues_repo_head_hexsha": "7c6717f403c041a092187568908f3661782ddb24", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "boost/bloom_filter/twohash_dynamic_basic_bloom_filter.hpp", "max_forks_repo_name": "tetzank/boost-bloom-filters", "max_forks_repo_head_hexsha": "7c6717f403c041a092187568908f3661782ddb24", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 12.0, "max_forks_repo_forks_event_min_datetime": "2016-04-15T18:17:24.000Z", "max_forks_repo_forks_event_max_datetime": "2020-04-16T06:29:58.000Z", "avg_line_length": 34.4305177112, "max_line_length": 78, "alphanum_fraction": 0.4959639126, "num_tokens": 2257, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.658417500561683, "lm_q2_score": 0.45713671682749485, "lm_q1q2_score": 0.30098681450853304}}
{"text": "#ifndef FSTCLASSIFIERSVM_H\n#define FSTCLASSIFIERSVM_H\n\n/*!======================================================================\n   Feature Selection Toolbox 3 source code\n   ---------------------------------------\n\t\n   \\file    classifier_svm.hpp\n   \\brief   Wraps external Support Vector Machine implementation (in LibSVM) to serve as FST3 classifier\n   \\author  Petr Somol (somol@utia.cas.cz) with collaborators, see Contacts at http://fst.utia.cz\n   \\date    March 2011\n   \\version 3.1.0.beta\n   \\note    FST3 was developed using gcc 4.3 and requires\n   \\note    \\li Boost library (http://www.boost.org/, tested with versions 1.33.1 and 1.44),\n   \\note    \\li (\\e optionally) LibSVM (http://www.csie.ntu.edu.tw/~cjlin/libsvm/, \n                tested with version 3.00)\n   \\note    Note that LibSVM is required for SVM related tools only,\n            as demonstrated in demo12t.cpp, demo23.cpp, demo25t.cpp, demo32t.cpp, etc.\n\n*/ /* \n=========================================================================\nCopyright:\n  * FST3 software (with exception of any externally linked libraries) \n    is copyrighted by Institute of Information Theory and Automation (UTIA), \n    Academy of Sciences of the Czech Republic.\n  * FST3 source codes as presented here do not contain code of third parties. \n    FST3 may need linkage to external libraries to exploit its functionality\n    in full. For details on obtaining and possible usage restrictions \n    of external libraries follow their original sources (referenced from\n    FST3 documentation wherever applicable).\n  * FST3 software is available free of charge for non-commercial use. \n    Please address all inquires concerning possible commercial use \n    of FST3, or if in doubt, to FST3 maintainer (see http://fst.utia.cz)\n  * Derivative works based on FST3 are permitted as long as they remain\n    non-commercial only.\n  * Re-distribution of FST3 software is not allowed without explicit\n    consent of the copyright holder.\nDisclaimer of Warranty:\n  * FST3 software is presented \"as is\", without warranty of any kind, \n    either expressed or implied, including, but not limited to, the implied \n    warranties of merchantability and fitness for a particular purpose. \n    The entire risk as to the quality and performance of the program \n    is with you. Should the program prove defective, you assume the cost \n    of all necessary servicing, repair or correction.\nLimitation of Liability:\n  * The copyright holder will in no event be liable to you for damages, \n    including any general, special, incidental or consequential damages \n    arising out of the use or inability to use the code (including but not \n    limited to loss of data or data being rendered inaccurate or losses \n    sustained by you or third parties or a failure of the program to operate \n    with any other programs).\n========================================================================== */\n\n#include <boost/smart_ptr.hpp>\n#include <iostream>\n#include <sstream>\n#include <list>\n#include <cstring> // memcpy\n#include \"error.hpp\"\n#include \"global.hpp\"\n#include \"classifier.hpp\"\n\n#include \"svm.h\"\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// NOTE: this is the proxy to LIBSVM external library\n//       therefore some FST coding conventions can not\n//       be strictly kept\n\n/*! \\brief Wraps external Support Vector Machine implementation (in LibSVM) to serve as FST3 classifier\n    \\note clone() implementation assumes LibSVM's svm_model and svm_node is equivalent to that in LibSVM version 300\n\n \\warning LIBSVM especially with LINEAR kernel seems to have occassional problems with certain C values on certain datasets and may freeze. \n          (Other kernels are more stable but not completely immune to this problem.) This is a problem outside FST3.\n*/\n\ntemplate<class RETURNTYPE, typename IDXTYPE, typename DIMTYPE, class SUBSET, class DATAACCESSOR>\nclass Classifier_LIBSVM : public Classifier<RETURNTYPE,DIMTYPE,SUBSET,DATAACCESSOR> { \npublic:\n\ttypedef boost::shared_ptr<DATAACCESSOR> PDataAccessor;\n\ttypedef boost::shared_ptr<SUBSET> const PSubset;\n\ttypedef typename DATAACCESSOR::PPattern PPattern;\n\tClassifier_LIBSVM();\n\tvirtual ~Classifier_LIBSVM() {notify(\"Classifier_LIBSVM destructor.\"); cleanup();}\n\n\tvoid initialize(const PDataAccessor da); // must be called to pre-allocate data transfer buffers\nprotected:\n\tvoid allocate(); // to be called in initialize(), pre-allocates everything\n\tvoid cleanup(); // deallocates everything\npublic:\n\tvoid set_parameter_C(double newC) {parameters.C = newC;};\n\tvoid set_parameter_gamma(double newgamma) {parameters.gamma = newgamma;};\n\tvoid set_parameter_coef0(double newcoef0) {parameters.coef0 = newcoef0;};\n\tvoid set_kernel_type(int kernel_type) {parameters.kernel_type = kernel_type;}; // see svm.h for admissible values\n\tdouble get_parameter_C() const {return parameters.C;}\n\tdouble get_parameter_gamma() const {return parameters.gamma;}\n\tdouble get_parameter_coef0() const {return parameters.coef0;}\n\tint get_kernel_type() const {return parameters.kernel_type;}; // see svm.h for admissible values\n\n\tvirtual bool classify(DIMTYPE &cls, const PPattern &pattern);  // classifies pattern, returns the respective class index\n\tvirtual bool train(const PDataAccessor da, const PSubset sub); // learns from designated training part of data\n\tvirtual bool test(RETURNTYPE &result, const PDataAccessor da); // estimates accuracy using designated test data\n\t\n\tbool optimize_parameters(const PDataAccessor da, const PSubset sub, const int max_points=100, const int max_throws=100, const double lgC_min=-5, const double lgC_max=9, const double lggamma_min=-15, const double lggamma_max=3, const double lgcoef0_min=-2, const double lgcoef0_max=5, std::ostream& os=std::cout);\n\t\n\tClassifier_LIBSVM* clone() const {return stateless_clone();} //! \\note dirty workaround to enable easy usage in sequential_step ...\n\tClassifier_LIBSVM* sharing_clone() const {throw fst_error(\"Classifier_LIBSVM::sharing_clone() not supported, use Classifier_LIBSVM::stateless_clone() instead.\");}\n\tClassifier_LIBSVM* stateless_clone() const;\n\t\n\tvirtual std::ostream& print(std::ostream& os) const {os << \"Classifier_LIBSVM(kernel=\"<<get_kernel_type()<<\")\"; return os;}\nprivate:\n\tClassifier_LIBSVM(const Classifier_LIBSVM& csvm, int); // weak copy-constructor, does not copy LibSVM internal structures\nprotected:\n\t// the following to be initialized using initialize() based on dataaccessor info\n\tIDXTYPE _all_patterns;\n\tDIMTYPE _classes;\n\tDIMTYPE _features;\n\tstruct svm_problem problem; // data to be stored in here\n\tstruct svm_parameter parameters;\n\tstruct svm_model *model;\n\tstruct svm_node *onepattern;\n\n\tbool svm_class_weighing;\n\n\t//! Nested class to hold parameter candidates in the course of optimize_parameters() run\n\tclass ParameterSet {\n\tpublic:\n\t\tParameterSet(): _crit_value(0.0), _Cpar(1.0), _gamma(1.0), _coef0(1.0) {}\n\t\tParameterSet(const RETURNTYPE crit_value, const double C, const double gamma, const double coef0) : _crit_value(crit_value), _Cpar(C), _gamma(gamma), _coef0(coef0) {}\n\t\tParameterSet(const ParameterSet& ps) : _crit_value(ps._crit_value), _Cpar(ps._Cpar), _gamma(ps._gamma), _coef0(ps._coef0) {}\n\t\tvoid operator=(const ParameterSet& ps) {_crit_value=ps._crit_value; _Cpar=ps._Cpar; _gamma=ps._gamma; _coef0=ps._coef0;}\n\t\tRETURNTYPE _crit_value;\n\t\tdouble _Cpar; // _C is reserved\n\t\tdouble _gamma; \n\t\tdouble _coef0;\n\t};\n\ttypedef list<ParameterSet> PARAMSETLIST;\n\ttypename PARAMSETLIST::iterator iter; \n\nprivate:\n\tboost::scoped_array<DIMTYPE> _index;\n\tDIMTYPE _subfeatures;\t\n};\n\ntemplate<class RETURNTYPE, typename IDXTYPE, typename DIMTYPE, class SUBSET, class DATAACCESSOR>\nClassifier_LIBSVM<RETURNTYPE,IDXTYPE,DIMTYPE,SUBSET,DATAACCESSOR>::Classifier_LIBSVM(const Classifier_LIBSVM& csvm, int) : // copy-constructor\n\t_all_patterns(csvm._all_patterns),\n\t_classes(csvm._classes),\n\t_features(csvm._features),\n\tsvm_class_weighing(csvm.svm_class_weighing),\n\t_subfeatures(csvm._subfeatures)\n{\n\tnotify(\"Classifier_LIBSVM (weak) copy-constructor.\");\n\t// does not copy LibSVM-defined structures, except for 'parameters'\n\t// other-than 'parameters' LibSVM structures are only pre-allocated using allocate()\n\tparameters.svm_type=csvm.parameters.svm_type;\n\tparameters.kernel_type=csvm.parameters.kernel_type;\n\tparameters.degree=csvm.parameters.degree;\n\tparameters.gamma=csvm.parameters.gamma;\n\tparameters.coef0=csvm.parameters.coef0;\n\tparameters.cache_size=csvm.parameters.cache_size;\n\tparameters.eps=csvm.parameters.eps;\n\tparameters.C=csvm.parameters.C;\n\tparameters.nr_weight=csvm.parameters.nr_weight;\n\tparameters.nu=csvm.parameters.nu;\n\tparameters.p=csvm.parameters.p;\n\tparameters.shrinking=csvm.parameters.shrinking;\n\tparameters.probability=csvm.parameters.probability;\t\n\tallocate();\n\tmodel=NULL;\n\tif(csvm.parameters.weight_label) memcpy((void *)parameters.weight_label,(void *)csvm.parameters.weight_label,(long)(_classes) * sizeof(int));\n\tif(csvm.parameters.weight) memcpy((void *)parameters.weight,(void *)csvm.parameters.weight,(long)(_classes) * sizeof(double));\n\tif(csvm._index) {_index.reset(new DIMTYPE[_features]); memcpy((void *)_index.get(),(void *)(csvm._index).get(),sizeof(DIMTYPE)*_features);}\n}\n\ntemplate<class RETURNTYPE, typename IDXTYPE, typename DIMTYPE, class SUBSET, class DATAACCESSOR>\nClassifier_LIBSVM<RETURNTYPE,IDXTYPE,DIMTYPE,SUBSET,DATAACCESSOR>* Classifier_LIBSVM<RETURNTYPE,IDXTYPE,DIMTYPE,SUBSET,DATAACCESSOR>::stateless_clone() const\n{\n\tClassifier_LIBSVM<RETURNTYPE,IDXTYPE,DIMTYPE,SUBSET,DATAACCESSOR> *clone=new Classifier_LIBSVM<RETURNTYPE,IDXTYPE,DIMTYPE,SUBSET,DATAACCESSOR>(*this,(int)0);\n\tclone->set_cloned();\n\treturn clone;\n}\n\ntemplate<class RETURNTYPE, typename IDXTYPE, typename DIMTYPE, class SUBSET, class DATAACCESSOR>\nClassifier_LIBSVM<RETURNTYPE,IDXTYPE,DIMTYPE,SUBSET,DATAACCESSOR>::Classifier_LIBSVM()\n{\n\tnotify(\"Classifier_LIBSVM constructor.\");\n\t_all_patterns=0;\n\t_classes=0;\n\t_features=0;\n\tproblem.x=NULL;\n\tproblem.y=NULL;\n\tonepattern=NULL;\n\tparameters.weight_label=NULL;\n\tparameters.weight=NULL;\n\tmodel=NULL;\n\t_subfeatures=0;\n\n\t// default parameters\n\tparameters.svm_type=C_SVC;\n\tparameters.kernel_type=RBF; //LINEAR;\n\tparameters.degree=2;\n\tparameters.gamma=/*standard_gamma=*/1.0;\n\tparameters.coef0=1.0;\n\tparameters.cache_size=10;\n\tparameters.eps=0.001;\n\tparameters.C=/*standard_C=*/1.0;\n\tparameters.nr_weight=0;\n\tparameters.weight_label=NULL; // just sharing a pointer\n\tparameters.weight=NULL; // just sharing a pointer\n\tparameters.nu=1.0;\n\tparameters.p=1.0;\n\tparameters.shrinking=0;\n\tparameters.probability=0;\n\tsvm_class_weighing=false;\n}\n\ntemplate<class RETURNTYPE, typename IDXTYPE, typename DIMTYPE, class SUBSET, class DATAACCESSOR>\nbool Classifier_LIBSVM<RETURNTYPE,IDXTYPE,DIMTYPE,SUBSET,DATAACCESSOR>::optimize_parameters(const PDataAccessor da, const PSubset sub, const int max_points, const int max_throws, const double lgC_min, const double lgC_max, const double lggamma_min, const double lggamma_max, const double lgcoef0_min, const double lgcoef0_max, std::ostream& os)\n{\n\t// \\note: assumes Classifier_LIBSVM::initialize() had been called for this da\n\t// assumes initial C, gamma, and coef0 have been set using set_parameter_*(), or that default values are OK\n\t// (the initial values are used as search starting point)\n\t/*! \\warning LIBSVM LINEAR kernel seems to have problems with certain C values on certain datasets. If the optimization\n\t             process seemingly freezes, try narrower lgC_min and lgC_max. Especially the lower bound seems\n\t             important to be increased.\n\t*/\n\tassert(da);\n\tassert(sub);\n\tassert(sub->get_d()>0);\n\tassert(max_points>0);\n\tassert(max_throws>0);\n\tassert(lgC_max>lgC_min);\n\tassert(lggamma_max>lggamma_min);\n\tassert(lgcoef0_max>lgcoef0_min);\n\tconst double lgCrange=lgC_max-lgC_min;\n\tconst double lggammarange=lggamma_max-lggamma_min;\n\tconst double lgcoef0range=lgcoef0_max-lgcoef0_min;\n\tPARAMSETLIST _paramlist; // _paramlist.clear();\n\tParameterSet tmpset, bestset;\n\t// evaluate the initial (current) parameter set\n\tRETURNTYPE val, maxval, firstval;\n\tRETURNTYPE result=0.0;\n\tRETURNTYPE cnt=0.0;\n\tfor(bool b=da->getFirstSplit();b==true;b=da->getNextSplit()) {\n\t\tif(!train(da,sub)) return false;\n\t\tif(!test(val,da)) return false;\n\t\tresult+=val;\n\t\tcnt+=1.0;\n\t}\n\tfirstval=maxval=val=result/(RETURNTYPE)cnt;\n\t{\n\t\tostringstream sos;\n\t\tsos << \"SVM before optimization: accuracy=\" << val << \", C=\" << get_parameter_C();\n\t\tswitch(get_kernel_type()) {\n\t\t\tcase LINEAR:  sos << std::endl; break;\n\t\t\tcase RBF:     sos << \", gamma=\" << get_parameter_gamma() << std::endl; break;\n\t\t\tcase POLY:    \n\t\t\tcase SIGMOID: sos << \", gamma=\" << get_parameter_gamma() << \", coef0=\" << get_parameter_coef0() << std::endl; break;\n\t\t}\n\t\tsyncout::print(os,sos);\n\t}\n\t_paramlist.push_back(ParameterSet(val,get_parameter_C(),get_parameter_gamma(),get_parameter_coef0()));\n\tfor(int i=0;i<max_points;i++)\n\t{ // find and evaluate next parameter set candidate\n\t\tdouble maxdistmin=0.0;\n\t\tfor(int j=0;j<max_throws;j++)\n\t\t{ // find next parameter set candidate\n\t\t\ttmpset._Cpar =exp(lgC_min+(((double)rand()*(double)(lgC_max-lgC_min))/(double)RAND_MAX));\n\t\t\ttmpset._gamma=exp(lggamma_min+(((double)rand()*(double)(lggamma_max-lggamma_min))/(double)RAND_MAX));\n\t\t\ttmpset._coef0=exp(lgcoef0_min+(((double)rand()*(double)(lgcoef0_max-lgcoef0_min))/(double)RAND_MAX));\n\t\t\t\n\t\t\tdouble distmin=-1.0; // potential new candidate (weighted) distance to already evaluated candidates\n\t\t\tfor(iter=_paramlist.begin();iter!=_paramlist.end();iter++)\n\t\t\t{\n\t\t\t\tdouble dist=0.0;\n\t\t\t\tassert(get_kernel_type()==LINEAR || get_kernel_type()==POLY || get_kernel_type()==RBF || get_kernel_type()==SIGMOID);\n\t\t\t\tswitch(get_kernel_type()) {\n\t\t\t\t\tcase LINEAR:  dist=sqrt(((log(tmpset._Cpar)-log(iter->_Cpar))/lgCrange)*((log(tmpset._Cpar)-log(iter->_Cpar))/lgCrange)); break;\n\t\t\t\t\tcase RBF:     dist=sqrt(((log(tmpset._Cpar)-log(iter->_Cpar))/lgCrange)*((log(tmpset._Cpar)-log(iter->_Cpar))/lgCrange)+((log(tmpset._gamma)-log(iter->_gamma))/lggammarange)*((log(tmpset._gamma)-log(iter->_gamma))/lggammarange)); break;\n\t\t\t\t\tcase POLY:    \n\t\t\t\t\tcase SIGMOID: dist=sqrt(((log(tmpset._Cpar)-log(iter->_Cpar))/lgCrange)*((log(tmpset._Cpar)-log(iter->_Cpar))/lgCrange)+((log(tmpset._gamma)-log(iter->_gamma))/lggammarange)*((log(tmpset._gamma)-log(iter->_gamma))/lggammarange)+((log(tmpset._coef0)-log(iter->_coef0))/lgcoef0range)*((log(tmpset._coef0)-log(iter->_coef0))/lgcoef0range)); break;\n\t\t\t\t}\n\t\t\t\t// candidates more distant from all others are preferred\n\t\t\t\t// distances are weighed to penalize closeness to worse-performing candidates\n\t\t\t\tassert(iter->_crit_value>0.0);\n\t\t\t\tif(distmin<0 || dist*iter->_crit_value<distmin) distmin=dist*iter->_crit_value;\n\t\t\t}\n\t\t\tassert(distmin>=0.0);\n\t\t\tif(distmin>maxdistmin)\n\t\t\t{ // better (more distant from those already tested, esp. from the bad ones) parameter set candidate found\n\t\t\t\tmaxdistmin=distmin;\n\t\t\t\tbestset=tmpset;\n\t\t\t}\n\t\t}\n\t\t// evaluate the chosen candidate and add it to list\n\t\tset_parameter_C(bestset._Cpar);\n\t\tset_parameter_gamma(bestset._gamma);\n\t\tset_parameter_coef0(bestset._coef0);\n\t\tassert(svm_check_parameter(&problem,&parameters)==NULL);\n\t\tresult=0.0;\n\t\tcnt=0.0;\n\t\tfor(bool b=da->getFirstSplit();b==true;b=da->getNextSplit()) {\n\t\t\tif(!train(da,sub)) return false;\n\t\t\tif(!test(val,da)) return false;\n\t\t\tresult+=val;\n\t\t\tcnt+=1.0;\n\t\t}\n\t\tval=result/(RETURNTYPE)cnt;\n\t\tbestset._crit_value=val;\n\t\t_paramlist.push_back(bestset);\n\t\tif(true)\n\t\t{\n\t\t\tostringstream sos;\n\t\t\tsos << i+1 << \". \";\n\t\t\tif(val>maxval) {maxval=val; sos << \"BEST accuracy=\";} else sos << \"test accuracy=\";\n\t\t\tsos << bestset._crit_value << \", C=\" << get_parameter_C();\n\t\t\tswitch(get_kernel_type()) {\n\t\t\t\tcase LINEAR:  sos << std::endl; break;\n\t\t\t\tcase RBF:     sos << \", gamma=\" << get_parameter_gamma() << std::endl; break;\n\t\t\t\tcase POLY:    \n\t\t\t\tcase SIGMOID: sos << \", gamma=\" << get_parameter_gamma() << \", coef0=\" << get_parameter_coef0() << std::endl; break;\n\t\t\t}\n\t\t\tsyncout::print(os,sos);\n\t\t}\n\t}\n\t// identify the best parameter set among all tested ones\n\tassert(!_paramlist.empty());\n\titer=_paramlist.begin();\n\tbestset=(*iter);\n\twhile(iter!=_paramlist.end())\n\t{\n\t\tif(iter->_crit_value>bestset._crit_value) bestset=(*iter);\n\t\titer++;\n\t}\n\tset_parameter_C(bestset._Cpar);\n\tset_parameter_gamma(bestset._gamma);\n\tset_parameter_coef0(bestset._coef0);\n\t{\n\t\tostringstream sos;\n\t\tsos << \"SVM after optimization: accuracy=\" << bestset._crit_value << \", C=\" << get_parameter_C();\n\t\tswitch(get_kernel_type()) {\n\t\t\tcase LINEAR:  sos << std::endl; break;\n\t\t\tcase RBF:     sos << \", gamma=\" << get_parameter_gamma() << std::endl; break;\n\t\t\tcase POLY:    \n\t\t\tcase SIGMOID: sos << \", gamma=\" << get_parameter_gamma() << \", coef0=\" << get_parameter_coef0() << std::endl; break;\n\t\t}\n\t\tsos << \"Accuracy difference=\" << bestset._crit_value-firstval << std::endl << std::endl;\n\t\tsyncout::print(os,sos);\n\t}\n\treturn false;\n}\n\ntemplate<class RETURNTYPE, typename IDXTYPE, typename DIMTYPE, class SUBSET, class DATAACCESSOR>\nvoid Classifier_LIBSVM<RETURNTYPE,IDXTYPE,DIMTYPE,SUBSET,DATAACCESSOR>::allocate()\n{\n\ttry {\n\t\t//cleanup(); - not to be called here or it would destroy original data in copy-constructor\n\t\tassert(_all_patterns>0);\n\t\tassert(_classes>1);\n\t\tassert(_features>0);\n\t\t\n\t\tproblem.y =               (double *)          malloc(_all_patterns * sizeof(double));\n\t\tproblem.x =               (struct svm_node **)malloc((long)(_all_patterns) * sizeof(struct svm_node *));\n\t\tparameters.weight_label = (int *)             malloc((long)(_classes) * sizeof(int));\n\t\tparameters.weight =       (double *)          malloc((long)(_classes) * sizeof(double));\n\t\tonepattern =              (struct svm_node *) malloc((long)(_features+1) * sizeof(struct svm_node));\n\t\tfor(IDXTYPE p=0;p<_all_patterns;p++) problem.x[p]=NULL;\n\t\t// pre-allocate all problem.x[] arrays to max size, to prevent re-allocation speed efficiency problems \n\t\t// - WARNING! this leads to uneconomical use of memory\n\t\tfor(IDXTYPE p=0;p<_all_patterns;p++) \n\t\t\tproblem.x[p] = (struct svm_node *) malloc((long)(_features+1) * sizeof(struct svm_node));\n\n\t\t// class penalty weighing disabled\n\t\tparameters.nr_weight=0;\n\t\tproblem.l = _all_patterns;\t\t\n\t\tassert(svm_check_parameter(&problem,&parameters)==NULL);\n\t}\n\tcatch (...) {\n\t\tcleanup();\n\t\tthrow fst_error(\"Classifier_LIBSVM allocation problem.\");\n\t}\n}\n\ntemplate<class RETURNTYPE, typename IDXTYPE, typename DIMTYPE, class SUBSET, class DATAACCESSOR>\nvoid Classifier_LIBSVM<RETURNTYPE,IDXTYPE,DIMTYPE,SUBSET,DATAACCESSOR>::initialize(const PDataAccessor da)\n{\n\tassert(da);\n\ttry {\n\t\tcleanup();\n\t\t_all_patterns = da->getClassSizeSum(); assert(_all_patterns>0);\n\t\t_classes = da->getNoOfClasses(); assert(_classes>1);\n\t\t_features = da->getNoOfFeatures(); assert(_features>0);\n\t\tallocate();\n\t}\n\tcatch (...) {\n\t\tcleanup();\n\t\tthrow fst_error(\"Classifier_LIBSVM initialization problem.\");\n\t}\n}\n\ntemplate<class RETURNTYPE, typename IDXTYPE, typename DIMTYPE, class SUBSET, class DATAACCESSOR>\nvoid Classifier_LIBSVM<RETURNTYPE,IDXTYPE,DIMTYPE,SUBSET,DATAACCESSOR>::cleanup()\n{\n\t// NOTE: called from destructor\n\t\tif(problem.x!=NULL) {\n\t\t\tfor(IDXTYPE p=0;p<_all_patterns;p++) if(problem.x[p]!=NULL) {free(problem.x[p]); problem.x[p]=NULL;}\n\t\t\tfree(problem.x); problem.x=NULL; // the array only, not the actual pointers\n\t\t}\n\t\tif(problem.y!=NULL) free(problem.y); problem.y=NULL;\n\t\tif(onepattern!=NULL) free(onepattern); onepattern=NULL;\n\t\tif(parameters.weight_label!=NULL) free(parameters.weight_label); parameters.weight_label=NULL;\n\t\tif(parameters.weight!=NULL) free(parameters.weight); parameters.weight=NULL;\n\t\tif(model!=NULL) {svm_free_and_destroy_model(&model); model=NULL;}\n\t\t\n\t\t_all_patterns=0;\n\t\t_classes=0;\n\t\t_features=0;\n}\n\ntemplate<class RETURNTYPE, typename IDXTYPE, typename DIMTYPE, class SUBSET, class DATAACCESSOR>\nbool Classifier_LIBSVM<RETURNTYPE,IDXTYPE,DIMTYPE,SUBSET,DATAACCESSOR>::train(const PDataAccessor da, const PSubset sub)\n{\n\tassert(da);\n\tassert(_classes==da->getNoOfClasses());\n\tassert(_features==da->getNoOfFeatures());\n\tassert(_all_patterns==da->getClassSizeSum());\n\tassert(problem.x!=NULL);\n\tassert(problem.y!=NULL);\n\tassert(onepattern!=NULL);\n\tassert(parameters.weight_label!=NULL);\n\tassert(parameters.weight!=NULL);\n\tassert(svm_check_parameter(&problem,&parameters)==NULL);\n\ttry {\n\t\t// feature index buffering to accelerate data transfer\n\t\tDIMTYPE f,ftmp;\n\t\tbool b;\n\t\tif(!_index || _features<sub->get_n_raw()) _index.reset(new DIMTYPE[_features]);\n\t\tfor(b=sub->getFirstFeature(f),_subfeatures=0;b==true;b=sub->getNextFeature(f),_subfeatures++) {assert(_subfeatures<_features); _index[_subfeatures]=f;}\n#ifdef DEBUG\n\t\t{\n\t\t\tostringstream sos;\n\t\t\tsos << \"index: \"; for(f=0;f<_subfeatures;f++) sos << _index[f] << \" \"; //sos << std::endl;\n\t\t\tsyncout::print(std::cout,sos);\n\t\t}\n#endif\n\t\tassert(_subfeatures==sub->get_d_raw());\n\t\t\n\t\ttypename DATAACCESSOR::PPattern p,ptmp;\n\t\tIDXTYPE s,i;//,ifeatures;\n\t\tIDXTYPE count;\n\t\tDIMTYPE nzfeat;\n\t\tdouble tmp;\n\t\tconst DIMTYPE da_train_loop=0; // to avoid mixup of get*Block() loops of different types\n\t\n\t\tcount=0;\n\t\tfor(DIMTYPE c_train=0;c_train<_classes;c_train++)\n\t\t{\n\t\t\tda->setClass(c_train);\n\t\t\tfor(b=da->getFirstBlock(TRAIN,p,s,da_train_loop);b==true;b=da->getNextBlock(TRAIN,p,s,da_train_loop)) for(i=0;i<s;i++)\n\t\t\t{\n\t\t\t\tproblem.y[count]=c_train; // current pattern class info\n\t\t\t\tnzfeat=0; // no. of nonzero features processed in current pattern\n\t\t\t\tptmp=&p[i*_features]; // temp pointer to current pattern\n\t\t\t\tfor(f=0;f<_subfeatures;f++)\n\t\t\t\t{\n\t\t\t\t\tftmp=_index[f]; // (full set) feature index\n\t\t\t\t\ttmp=ptmp[ftmp]; // feature value\n\t\t\t\t\tif(tmp!=0.0) {\n\t\t\t\t\t\tproblem.x[count][nzfeat].index=ftmp+1;\n\t\t\t\t\t\tproblem.x[count][nzfeat].value=tmp; \n\t\t\t\t\t\tnzfeat++;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tproblem.x[count][nzfeat].index=-1;\n\t\t\t\tcount++;\n\t\t\t}\n\t\t}\n\t\tassert(count>0);\n\t\tproblem.l=count;\n\t\tif(model!=NULL) svm_free_and_destroy_model(&model);\n\t\t// train SVM model\n\t\tmodel=svm_train(&problem, &parameters);\n\t}\n\tcatch(...) {\n\t\tcleanup();\n\t\tthrow fst_error(\"Classifier_LIBSVM::train() error.\");\n\t}\t\n\tif(model==NULL) return false;\n\treturn true;\n}\n\ntemplate<class RETURNTYPE, typename IDXTYPE, typename DIMTYPE, class SUBSET, class DATAACCESSOR>\nbool Classifier_LIBSVM<RETURNTYPE,IDXTYPE,DIMTYPE,SUBSET,DATAACCESSOR>::classify(DIMTYPE &cls, const PPattern &pattern)  // classifies pattern, returns the respective class index\n{\n\tassert(model!=NULL);\n\tassert(svm_check_parameter(&problem,&parameters)==NULL);\n\ttry {\n\t\t// assumes feature index buffering to accelerate data transfer\n\t\tassert(_index);\n\t\tassert(_subfeatures>0 && _subfeatures<=_features);\n\t\t\n\t\tDIMTYPE nzfeat;\n\t\tdouble tmp;\n\t\tRETURNTYPE tmpval;\n\t\tDIMTYPE ftmp;\n\t\n\t\tnzfeat=0; // no. of nonzero features processed in current pattern\n\t\tfor(DIMTYPE f=0;f<_subfeatures;f++)\n\t\t{\n\t\t\tftmp=_index[f]; // (full set) feature index\n\t\t\ttmp=pattern[ftmp]; // feature value\n\t\t\tif(tmp!=0.0) {\n\t\t\t\tonepattern[nzfeat].index=ftmp+1;\n\t\t\t\tonepattern[nzfeat].value=tmp; \n\t\t\t\tnzfeat++;\n\t\t\t}\n\t\t}\n\t\tonepattern[nzfeat].index=-1;\n\t\t// now classify the pattern\n\t\ttmpval=svm_predict(model, onepattern);\n\t\tcls=(DIMTYPE)tmpval;\n\t}\n\tcatch(...) {\n\t\tcleanup();\n\t\tthrow fst_error(\"Classifier_LIBSVM::classify() error.\");\n\t}\t\n\treturn true;\n}\n\ntemplate<class RETURNTYPE, typename IDXTYPE, typename DIMTYPE, class SUBSET, class DATAACCESSOR>\nbool Classifier_LIBSVM<RETURNTYPE,IDXTYPE,DIMTYPE,SUBSET,DATAACCESSOR>::test(RETURNTYPE &result, const PDataAccessor da)\n{\n\tassert(da);\n\tassert(_classes==da->getNoOfClasses());\n\tassert(_features==da->getNoOfFeatures());\n\tassert(_all_patterns==da->getClassSizeSum());\n\tassert(model!=NULL);\n\tassert(svm_check_parameter(&problem,&parameters)==NULL);\n\ttry {\n\t\t// assumes feature index buffering to accelerate data transfer\n\t\tassert(_index);\n\t\tassert(_subfeatures>0);\n\t\t\n\t\ttypename DATAACCESSOR::PPattern p; //,ptmp;\n\t\tIDXTYPE s,i;\n\t\tIDXTYPE count, correct;\n\t\tDIMTYPE clstmp;\n\t\tbool b;\n\t\tconst DIMTYPE da_test_loop=1; // to avoid mixup of get*Block() loops of different types\n\t\n\t\tcount=0;\n\t\tcorrect=0;\n\t\tfor(DIMTYPE c_test=0;c_test<_classes;c_test++)\n\t\t{\n\t\t\tda->setClass(c_test);\n\t\t\tfor(b=da->getFirstBlock(TEST,p,s,da_test_loop);b==true;b=da->getNextBlock(TEST,p,s,da_test_loop)) for(i=0;i<s;i++)\n\t\t\t{\n\t\t\t\tif(!classify(clstmp,&p[i*_features])) return false;\n\t\t\t\tif(clstmp==c_test) correct++;\n\t\t\t\tcount++;\n\t\t\t}\n\t\t}\n\t\tassert(count>0);\n\t\tresult=(RETURNTYPE)correct/(RETURNTYPE)count;\n#ifdef DEBUG\n\t\t{\n\t\t\tostringstream sos;\n\t\t\tsos << \" result=\" << result << std::endl;\n\t\t\tsyncout::print(std::cout,sos);\n\t\t}\n#endif\n\t}\n\tcatch(...) {\n\t\tcleanup();\n\t\tthrow fst_error(\"Classifier_LIBSVM::test() error.\");\n\t}\t\n\treturn true;\n}\n\n} // namespace\n#endif // FSTCLASSIFIERSVM_H ///:~\n", "meta": {"hexsha": "f103fd67bf474e35cc8f6387d1374147c9cefe05", "size": 26340, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "extern/FST3lib/_src_criteria/classifier_svm.hpp", "max_stars_repo_name": "boussaffawalid/FeatureSelection", "max_stars_repo_head_hexsha": "9768a044c0c0dc2c4a2dc0f6e65413d19e92766c", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2015-07-07T20:18:35.000Z", "max_stars_repo_stars_event_max_datetime": "2019-04-23T06:46:02.000Z", "max_issues_repo_path": "extern/FST3lib/_src_criteria/classifier_svm.hpp", "max_issues_repo_name": "boussaffawalid/FeatureSelection", "max_issues_repo_head_hexsha": "9768a044c0c0dc2c4a2dc0f6e65413d19e92766c", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-02-08T08:35:28.000Z", "max_issues_repo_issues_event_max_datetime": "2021-02-10T08:57:35.000Z", "max_forks_repo_path": "extern/FST3lib/_src_criteria/classifier_svm.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": 43.1803278689, "max_line_length": 349, "alphanum_fraction": 0.7183371298, "num_tokens": 6974, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.658417500561683, "lm_q2_score": 0.4571367168274948, "lm_q1q2_score": 0.300986814508533}}
{"text": "/*\n *  Copyright (c) 2009, Rene Wagner\n *  Copyright (c) 2010, 2011 DFKI GmbH\n *  All rights reserved.\n *\n *  Author: Rene Wagner <rene.wagner@dfki.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 DFKI GmbH 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 __UKFOM_UKF_HPP__\n#define __UKFOM_UKF_HPP__\n\n#include <vector>\n#include <algorithm>\n#include <numeric>\n\n#include <boost/bind.hpp>\n\n#include <Eigen/Core>\n#include <Eigen/LU>\n#include <Eigen/Eigenvalues>\n\n#include <Eigen/QR>\n\n#include \"lapack/cholesky.hpp\"\n#include \"traits/dof.hpp\"\n#include \"util.hpp\"\n\nnamespace ukfom {\n\t\n// import most common Eigen types \nusing namespace Eigen;\n\ntemplate <typename state>\nclass ukf {\n\ttypedef ukf self;\n\n\tenum {\n\t\tn = state::DOF\n\t};\n\t\npublic:\n\t\n\ttypedef typename state::scalar_type scalar_type;\n\ttypedef typename state::vectorized_type vectorized_state;\n\ttypedef Matrix<scalar_type, int(state::DOF), int(state::DOF)> cov;\n\ttypedef std::vector<state> state_vector;\n\t\n\tukf(const state &mu,\n\t\tconst cov &sigma)\n\t\t: mu_(mu),\n\t\t  sigma_(sigma)\n\t{\n\t}\n\n\ttemplate<typename ProcessModel>\n\tvoid predict(ProcessModel g, const cov &R)\n\t{\n\t\tpredict(g, boost::bind(id<cov>, R));\n\t}\n\n\ttemplate<typename ProcessModel, typename ProcessNoiseCovariance>\n\tvoid predict(ProcessModel g, ProcessNoiseCovariance R)\n\t{\n\t\tstate_vector X(2 * n + 1);\n\t\tgenerate_sigma_points(mu_, sigma_, X);\n\t\t\n\t\tstd::transform(X.begin(), X.end(), X.begin(), g);\n\n\t\tmu_ = sigma_points_mean(X);\n\n\t\t//std::cout << \"mu':\" << std::endl << mu_ << std::endl;\n\t\t\n\t\tsigma_ = sigma_points_cov<state::DOF>(mu_, X) + R();\n\t}\n\n\ttemplate<typename Measurement,\n\t\t\t typename MeasurementModel,\n\t\t\t typename MeasurementNoiseCovariance>\n\tvoid update(const Measurement &z,\n\t\t\t\tMeasurementModel h,\n\t\t\t\tMeasurementNoiseCovariance Q)\n\t{\n\t\tupdate(z, h, Q,\n\t\t\t   accept_any_mahalanobis_distance<scalar_type>);\n\t}\n\t\n\ttemplate<typename Measurement,\n\t\t\t typename MeasurementModel>\n\tvoid update(const Measurement &z,\n\t\t\t\tMeasurementModel h,\n\t\t\t\tconst Eigen::Matrix<scalar_type, dof<Measurement>::value, dof<Measurement>::value> &Q)\n\t{\n\t\ttypedef Eigen::Matrix<scalar_type, dof<Measurement>::value, dof<Measurement>::value> measurement_cov;\n\t\tupdate(z, h,\n\t\t\t   boost::bind(id<measurement_cov>, Q),\n\t\t\t   accept_any_mahalanobis_distance<scalar_type>);\n\t}\n\t\n\ttemplate<typename Measurement,\n\t\t\t typename MeasurementModel,\n\t\t\t typename MeasurementNoiseCovariance,\n\t\t\t typename MahalanobisTest>\n\tvoid update(const Measurement &z,\n\t\t\t\tMeasurementModel h,\n\t\t\t\tMeasurementNoiseCovariance Q,\n\t\t\t\tMahalanobisTest mt)\n\t{\n\t\tconst static int measurement_rows = dof<Measurement>::value;\n\t\ttypedef Measurement measurement;\n\t\ttypedef Eigen::Matrix<scalar_type, measurement_rows, 1> vectorized_measurement;\n\t\ttypedef Matrix<scalar_type, measurement_rows, measurement_rows> measurement_cov;\n\t\ttypedef Matrix<scalar_type, state::DOF, measurement_rows> cross_cov;\n\n\t\tstate_vector X(2 * n + 1);\n\t\tgenerate_sigma_points(mu_, sigma_, X);\n\n\t\tstd::vector<measurement> Z(X.size());\n\t\tstd::transform(X.begin(), X.end(), Z.begin(), h);\n\t\t\n\t\tconst measurement meanZ = sigma_points_mean(Z);\n\t\tconst measurement_cov S = sigma_points_cov<measurement_rows>(meanZ, Z) + Q();\n\t\tconst cross_cov covXZ = sigma_points_cross_cov<measurement_rows>(mu_, meanZ, X, Z);\n\n\t\tmeasurement_cov S_inverse(S.inverse());\n\n\t\tconst cross_cov K = covXZ * S_inverse;\n\t\t\n\t\tconst vectorized_measurement innovation = z - meanZ;\n\n\t\tconst scalar_type mahalanobis2 = (innovation.transpose() * S_inverse * innovation)(0);\n\n\t\tif (mt(mahalanobis2))\n\t\t{\n\t\t\tsigma_ -= K * S * K.transpose();\n\t\t\tapply_delta(K * innovation);\n\t\t}\n\t}\n\n\tconst state &mu() const\n\t{\n\t\treturn mu_;\n\t}\n\n\tconst cov &sigma() const\n\t{\n\t\treturn sigma_;\n\t}\n\t\nprivate:\n\n\tvoid generate_sigma_points(const state &mu,\n\t\t\t\t\t\t\t   const vectorized_state &delta,\n\t\t\t\t\t\t\t   const cov &sigma,\n\t\t\t\t\t\t\t   state_vector &X) const\n\t{\n\t\tassert(X.size() == 2 * n + 1);\n\n\t\tMatrixXd L(sigma.llt().matrixL());\n\n\t\t/*if (!L.isSPD())\n\t\t{\n\t\t\tstd::cerr << std::endl << \"sigma is not SPD:\" << std::endl\n\t\t\t\t\t  << sigma << std::endl\n\t\t\t\t\t  << \"---\" << std::endl;\n\t\t\tEigen::EigenSolver<cov> eig(sigma);\n\t\t\tstd::cerr << \"eigen values: \" << eig.eigenvalues().transpose() << std::endl;\n\t\t}\n\t\t\n\t\tassert(L.isSPD());*/\n\n\t\t/*\n\t\tstd::cout << \">> L\" << std::endl\n\t\t\t\t  << L.getL() << std::endl\n\t\t\t\t  << \"<< L\" << std::endl;\n\t\t*/\n\t\t\n\t\tX[0] = mu + delta;\n\t\tfor (std::size_t i = 1, j = 0; j < n; ++j)\n\t\t{\n\t\t\t//std::cout << \"L.col(\" << j << \"): \" << L.getL().col(j).transpose() << std::endl;\n\t\t\tX[i++] = mu + (delta + L.col(j));\n\t\t\tX[i++] = mu + (delta - L.col(j));\n\t\t}\n\t\t//print_sigma_points(X);\n\t}\n\n\tvoid generate_sigma_points(const state &mu,\n\t\t\t\t\t\t\t   const cov &sigma,\n\t\t\t\t\t\t\t   state_vector &X) const\n\t{\n\t\tgenerate_sigma_points(mu, vectorized_state::Zero(), sigma, X);\n\t}\n\n\t// manifold mean\n\ttemplate<typename manifold>\n\tmanifold\n\tsigma_points_mean(const std::vector<manifold> &X) const\n\t{\n\t\tmanifold reference = X[0];\n\t\ttypename manifold::vectorized_type mean_delta;\n\t\tconst static std::size_t max_it = 10000;\n\n\t\tstd::size_t i = 0;\n\t\tdo {\n\t\t\tmean_delta.setZero();\n\t\t\tfor (typename std::vector<manifold>::const_iterator Xi = X.begin(); Xi != X.end(); ++Xi)\n\t\t\t{\n\t\t\t\tmean_delta += *Xi - reference;\n\t\t\t}\n\t\t\tmean_delta /= X.size();\n\t\t\treference += mean_delta;\n\t\t} while (mean_delta.norm() > 1e-6\n\t\t\t\t && ++i < max_it);\n\n\t\tif (i >= max_it)\n\t\t{\n\t\t\tstd::cerr << \"ERROR: sigma_points_mean() did not converge. norm(mean_delta)=\" << mean_delta.norm() << std::endl;\n\t\t\tassert(false);\n\t\t}\n\t\t\n\t\treturn reference;\n\t}\n\t\n\t// vector mean\n\ttemplate<int measurement_rows>\n\tMatrix<scalar_type, measurement_rows, 1>\n\tsigma_points_mean(const std::vector<Matrix<scalar_type, measurement_rows, 1> > &Z) const\n\t{\n\t\ttypedef Matrix<scalar_type, measurement_rows, 1> measurement;\n\t\t\n\t\treturn std::accumulate(Z.begin(), Z.end(), measurement(measurement::Zero())) / Z.size();\n\t}\n\n#ifdef VECT_H_\n\t// MTK vector mean\n\ttemplate<int measurement_rows>\n\tMTK::vect<measurement_rows, scalar_type>\n\tsigma_points_mean(const std::vector<MTK::vect<measurement_rows, scalar_type> > &Z) const\n\t{\n\t\ttypedef MTK::vect<measurement_rows, scalar_type> measurement;\n\t\t\n\t\treturn std::accumulate(Z.begin(), Z.end(), measurement(measurement::Zero())) / Z.size();\n\t}\n#endif // VECT_H_\n\t\n\ttemplate<int cov_size, typename T>\n\tMatrix<scalar_type, -1, -1>\n\tsigma_points_cov(const T &mean, const std::vector<T> &V) const\n\t{\n\t\ttypedef Matrix<scalar_type, -1, -1> cov_mat;\n\t\ttypedef Matrix<scalar_type, cov_size, 1> cov_col;\n\t\t\n\t\tcov_mat c(cov_mat::Zero(cov_size,cov_size));\n\t\t\n\t\tfor (typename std::vector<T>::const_iterator Vi = V.begin(); Vi != V.end(); ++Vi)\n\t\t{\n\t\t\tcov_col d = *Vi - mean;\n\t\t\tc += d * d.transpose();\n\t\t}\n\n\t\treturn 0.5 * c;\n\t}\n\n\ttemplate<int measurement_rows, typename Measurement>\n\tMatrix<scalar_type, state::DOF, measurement_rows>\n\tsigma_points_cross_cov(const state &meanX,\n\t\t\t\t\t\t   const Measurement &meanZ,\n\t\t\t\t\t\t   const state_vector &X,\n\t\t\t\t\t\t   const std::vector<Measurement> &Z) const\n\t{\n\t\tassert(X.size() == Z.size());\n\n\t\ttypedef Matrix<scalar_type, state::DOF, measurement_rows> cross_cov;\n\n\t\tcross_cov c(cross_cov::Zero());\n\n\t\t{\n\t\t\ttypename state_vector::const_iterator Xi = X.begin();\n\t\t\ttypename std::vector<Measurement>::const_iterator Zi = Z.begin();\n\t\t\tfor (;Zi != Z.end(); ++Xi, ++Zi)\n\t\t\t{\n\t\t\t\tc += (*Xi - meanX) * (*Zi - meanZ).transpose();\n\t\t\t}\n\t\t}\n\t\t\n\t\treturn 0.5 * c;\n\t}\n\t\n\tvoid apply_delta(const vectorized_state &delta)\n\t{\n\t\tstate_vector X(2 * n + 1);\n\t\tgenerate_sigma_points(mu_, delta, sigma_, X);\n\n\t\tmu_ = sigma_points_mean(X);\n\t\tsigma_ = sigma_points_cov<state::DOF>(mu_, X);\n\t}\n\npublic: state mu_;\npublic: cov sigma_;\n\n\t// for debugging only\n\n\tvoid print_sigma_points(const state_vector &X) const\n\t{\n\t\tstd::cout << \"generated sigma points:\" << std::endl;\n\t\tfor (typename state_vector::const_iterator Xi = X.begin(); Xi != X.end(); ++Xi)\n\t\t{\n\t\t\tstd::cout << *Xi << std::endl << \"***\" << std::endl;\n\t\t}\n\t}\n\npublic:\n\tvoid check_sigma_points()\n    {\n\t\tstate_vector X(2 * n + 1);\n\t\tgenerate_sigma_points(mu_, sigma_, X);\n\n\t\tstate muX = sigma_points_mean(X);\n\t\t\n\t\tcov sigma_test = sigma_points_cov<state::DOF>(muX, X);\n\t\tif((sigma_test - sigma_).cwise().abs().maxCoeff()>1e-6){\n\t\t\tstd::cerr << sigma_test << \"\\n\\n\" << sigma_;\n\t\t\tassert(false);\n\t\t}\n\n\t\tif (mu_ != muX)\n\t\t{\n//\t\t\tstd::cout << \"mu_:\" << mu_ << std::endl;\n//\t\t\tstd::cout << \"muX:\" << muX << std::endl;\n\t\t\tstd::cout << \"norm:\" << ((mu_ - muX).norm() > 0. ? \">\" : \"=\") << std::endl;\n\t\t}\n\t\tassert (mu_ == muX);\n\t}\n\npublic:\n\tEIGEN_MAKE_ALIGNED_OPERATOR_NEW\n};\n\t\n} // namespace ukfom\n#endif // __UKFOM_UKF_HPP__\n", "meta": {"hexsha": "37fc688893b8c3f9367afdcf228af805e39d550e", "size": 9984, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "examples/slam_and_orientation/ukfom/ukf.hpp", "max_stars_repo_name": "mfkiwl/ADEKF", "max_stars_repo_head_hexsha": "178092b7585b0f311ed7889820704e74dab12bd1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 90.0, "max_stars_repo_stars_event_min_datetime": "2021-01-04T11:04:59.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-23T01:43:07.000Z", "max_issues_repo_path": "examples/slam_and_orientation/ukfom/ukf.hpp", "max_issues_repo_name": "mfkiwl/ADEKF", "max_issues_repo_head_hexsha": "178092b7585b0f311ed7889820704e74dab12bd1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/slam_and_orientation/ukfom/ukf.hpp", "max_forks_repo_name": "mfkiwl/ADEKF", "max_forks_repo_head_hexsha": "178092b7585b0f311ed7889820704e74dab12bd1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 11.0, "max_forks_repo_forks_event_min_datetime": "2021-04-26T09:18:07.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-23T01:43:10.000Z", "avg_line_length": 27.1304347826, "max_line_length": 115, "alphanum_fraction": 0.6727764423, "num_tokens": 2776, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.658417500561683, "lm_q2_score": 0.4571367168274948, "lm_q1q2_score": 0.300986814508533}}
{"text": "//==================================================================================================\n/*!\n    @file\n\n    @Copyright 2016 Numscale SAS\n    @copyright 2016 J.T.Lapreste\n\n    Distributed under the Boost Software License, Version 1.0.\n    (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\n*/\n//==================================================================================================\n#ifndef BOOST_SIMD_ARCH_X86_SSE2_SIMD_FUNCTION_SQRT_HPP_INCLUDED\n#define BOOST_SIMD_ARCH_X86_SSE2_SIMD_FUNCTION_SQRT_HPP_INCLUDED\n#include <boost/simd/detail/overload.hpp>\n\n#include <boost/simd/function/simd/bitwise_cast.hpp>\n#include <boost/simd/function/simd/plus.hpp>\n#include <boost/simd/function/simd/divides.hpp>\n#include <boost/simd/function/simd/gt.hpp>\n#include <boost/simd/function/simd/if_add.hpp>\n#include <boost/simd/function/simd/if_else.hpp>\n#include <boost/simd/function/simd/if_one_else_zero.hpp>\n#include <boost/simd/function/simd/is_gez.hpp>\n#include <boost/simd/function/simd/is_gtz.hpp>\n#include <boost/simd/function/simd/ge.hpp>\n#include <boost/simd/function/simd/is_nez.hpp>\n#include <boost/simd/function/simd/lt.hpp>\n#include <boost/simd/function/simd/minus.hpp>\n#include <boost/simd/function/simd/shift_right.hpp>\n#include <boost/simd/function/simd/tofloat.hpp>\n#include <boost/simd/function/simd/toint.hpp>\n#include <boost/simd/function/simd/touint.hpp>\n#include <boost/simd/constant/four.hpp>\n#include <boost/simd/constant/mone.hpp>\n#include <boost/simd/constant/one.hpp>\n#include <boost/simd/constant/zero.hpp>\n#include <boost/simd/detail/assert_utils.hpp>\n\nnamespace boost { namespace simd { namespace ext\n{\n  namespace bd =  boost::dispatch;\n  namespace bs =  boost::simd;\n  BOOST_DISPATCH_OVERLOAD ( sqrt_\n                          , (typename A0)\n                          , bs::sse2_\n                          , bs::pack_<bd::double_<A0>, bs::sse_>\n                         )\n  {\n    BOOST_FORCEINLINE A0 operator() ( const A0 & a0) const BOOST_NOEXCEPT\n    {\n       return _mm_sqrt_pd(a0);\n    }\n  };\n  BOOST_DISPATCH_OVERLOAD ( sqrt_\n                          , (typename A0)\n                          , bs::sse2_\n                          , bs::pack_<bd::int_<A0>, bs::sse_>\n                         )\n  {\n    BOOST_FORCEINLINE A0 operator() ( const A0 & a0) const BOOST_NOEXCEPT\n    {\n// TODO     BOOST_ASSERT_MSG(assert_all(is_gez(a0)), \"sqrt input is negative\");\n      using uint_type = bd::as_integer_t<A0,unsigned>;\n      return simd::bitwise_cast<A0>(sqrt( simd::bitwise_cast<uint_type>(a0)));\n    }\n  };\n\n  BOOST_DISPATCH_OVERLOAD ( sqrt_\n                          , (typename A0)\n                          , bs::sse2_\n                          , bs::pack_<bd::int64_<A0>, bs::sse_>\n                         )\n  {\n    BOOST_FORCEINLINE A0 operator() ( const A0 & a0) const BOOST_NOEXCEPT\n    {\n//  TODO     BOOST_ASSERT_MSG(assert_all(is_gez(a0)), \"sqrt input is negative\");\n      return bs::toint(bs::sqrt(bs::tofloat(a0)));\n    }\n  };\n\n  BOOST_DISPATCH_OVERLOAD ( sqrt_\n                          , (typename A0)\n                          , bs::sse2_\n                          , bs::pack_<bd::uint8_<A0>, bs::sse_>\n                          )\n  {\n    BOOST_FORCEINLINE A0 operator() ( const A0 & a0) const BOOST_NOEXCEPT\n    {\n      auto na  = is_nez(a0);\n      A0 n   = plus(shift_right(a0, 4), Four<A0>());\n      A0 n1  = shift_right(n+a0/n, 1);\n\n      auto ok = lt(n1, n);\n      n  = if_else(ok, n1, n);\n      n1 = if_else(ok, shift_right(n+a0/n, 1), n1);\n\n      ok = lt(n1, n);\n      n  = if_else(ok, n1, n);\n      n  = if_add( gt(n*n,a0), n, Mone<A0>());\n      return n+if_one_else_zero(na);\n    }\n  };\n\n  BOOST_DISPATCH_OVERLOAD ( sqrt_\n                          , (typename A0)\n                          , bs::sse2_\n                          , bs::pack_<bd::uint16_<A0>, bs::sse_>\n                          )\n  {\n    BOOST_FORCEINLINE A0 operator() ( const A0 & a0) const BOOST_NOEXCEPT\n    {\n      auto na = is_nez(a0);\n      A0 const  z1 = plus(shift_right(a0, 6), Ratio<A0, 16>());\n      A0 const  z2 = plus(shift_right(a0,10), Ratio<A0, 256>());\n      A0 const  C1 = Ratio<A0, 31679>();\n      // choose a proper starting point for approximation\n      A0 n  = if_else(lt(a0, C1), z1, z2);\n      auto ok =  is_gtz(n);\n      n  = if_else(ok, n, One<A0>());\n\n      A0 n1 = if_else(ok, shift_right(n+a0/n, 1), One<A0>());\n\n      ok = lt(n1, n);\n      n  = if_else(ok, n1, n);\n      n1 = if_else(ok, shift_right(n+a0/n, 1), n1);\n\n      ok = lt(n1, n);\n      n  = if_else(ok, n1, n);\n      n1 = if_else(ok, shift_right(n+a0/n, 1), n1);\n\n      ok =  lt(n1, n);\n      n  = if_else(ok, n1, n);\n      n  = if_add( gt(n*n,a0), n, Mone<A0>());\n\n     return if_add(na, Zero<A0>(), n);\n    }\n  };\n\n  BOOST_DISPATCH_OVERLOAD ( sqrt_\n                          , (typename A0)\n                          , bs::sse2_\n                          , bs::pack_<bd::uint32_<A0>, bs::sse_>\n                          )\n  {\n    BOOST_FORCEINLINE A0 operator() ( const A0 & a0) const BOOST_NOEXCEPT\n    {\n      auto na = is_nez(a0);\n      A0 const z1 = plus(shift_right(a0, 6),    Ratio<A0,16>());\n      A0 const z2 = plus(shift_right(a0,10),   Ratio<A0,256>());\n      A0 const z3 = plus(shift_right(a0,13),  Ratio<A0,2048>());\n      A0 const z4 = plus(shift_right(a0,16), Ratio<A0,16384>());\n      A0 n  = if_else( gt(a0, Ratio<A0,177155824>())\n                  , z4\n                  , if_else( gt(a0, Ratio<A0,4084387>())\n                        , z3\n                        , if_else( gt(a0, Ratio<A0,31679>())\n                                , z2\n                                , z1\n                                )\n                        )\n                  );\n      auto ok =  is_gtz(n);\n      n = if_else(ok, n, One<A0>());\n      A0 n1 = if_else(ok, shift_right(n+a0/n, 1), One<A0>());\n\n      ok = lt(n1, n);\n      n  = if_else(ok, n1, n);\n      n1 = if_else(ok, shift_right(n+a0/n, 1), n1);\n\n      ok =  lt(n1, n);\n      n  = if_else(ok, n1, n);\n      n1 = if_else(ok, shift_right(n+a0/n, 1), n1);\n\n      ok =  lt(n1, n);\n      n  = if_else(ok, n1, n);\n\n      A0 tmp = minus(n*minus(n, One<A0>()), One<A0>());\n      n  = if_add( ge(tmp+n,a0), n, Mone<A0>());\n      n =  if_add(na, Zero<A0>(), n);\n\n      return n;\n     }\n  };\n\n  BOOST_DISPATCH_OVERLOAD ( sqrt_\n                          , (typename A0)\n                          , bs::sse2_\n                          , bs::pack_<bd::uint64_<A0>, bs::sse_>\n                          )\n  {\n    BOOST_FORCEINLINE A0 operator() ( const A0 & a0) const BOOST_NOEXCEPT\n    {\n      return bs::touint(bs::sqrt(bs::tofloat(a0)));\n    }\n  };\n\n} } }\n\n#endif\n", "meta": {"hexsha": "f1fab87a1e0faf62f6e64ca921af590065434a64", "size": 6666, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/simd/arch/x86/sse2/simd/function/sqrt.hpp", "max_stars_repo_name": "yaeldarmon/boost.simd", "max_stars_repo_head_hexsha": "561316cc54bdc6353ca78f3b6d7e9120acd11144", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/boost/simd/arch/x86/sse2/simd/function/sqrt.hpp", "max_issues_repo_name": "yaeldarmon/boost.simd", "max_issues_repo_head_hexsha": "561316cc54bdc6353ca78f3b6d7e9120acd11144", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/boost/simd/arch/x86/sse2/simd/function/sqrt.hpp", "max_forks_repo_name": "yaeldarmon/boost.simd", "max_forks_repo_head_hexsha": "561316cc54bdc6353ca78f3b6d7e9120acd11144", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.33, "max_line_length": 100, "alphanum_fraction": 0.5147014701, "num_tokens": 1881, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.658417487156366, "lm_q2_score": 0.45713671682749474, "lm_q1q2_score": 0.30098680838047037}}
{"text": "\n#include <chrono>\n#include <iostream>\n\n#include <boost/filesystem.hpp>\n#include <boost/iostreams/device/mapped_file.hpp>\n\n#include <opencv2/highgui/highgui.hpp>\n\n#include \"gil/mat.hpp\"\n#include \"gil/vec.hpp\"\n#include \"poisson_serial.hpp\"\n#include \"poisson_tbb.hpp\"\n\n#include \"cl/device.hpp\"\n#include \"cl/context.hpp\"\n#include \"cl/memory.hpp\"\n#include \"cl/program.hpp\"\n#include \"cl/kernel.hpp\"\n\nconst size_t kNIter = 10000;\n\n/**\n * Finds the full path of |filename| in the working directory.\n */\nboost::filesystem::path find_file(const std::string& filename) {\n  boost::filesystem::path path(__FILE__);\n  path.remove_filename();\n  path.append(filename);\n  return path;\n}\n\n/**\n * Finds the smallest possible rectangular frame that contains the |mask|'s\n * white region, in other words the minimal region we'll need to consider to\n * apply poisson blending. Returns a vector with the 4 extremums of the frame.\n */\ngil::vec4<size_t> find_frame(gil::mat_cview<uint8_t> mask) {\n  gil::vec4<size_t> frame = {size_t(-1), size_t(-1), 0, 0};\n  for (size_t i = 2; i < mask.rows()-2; ++i) {\n    auto elem_it = mask.row_begin(i)+1;\n    for (size_t j = 2; j < mask.cols()-2; ++j, ++elem_it) {\n      // If the pixel is white, hence should be in the frame\n      if (*elem_it >= 128) {\n        // If the pixel is to the left of the frame, set it as the new leftmost\n        if (i <= frame[0])\n          frame[0] = i - 1;\n\n        // If the pixel is atop the frame, set it as the new topmost\n        if (j <= frame[1])\n          frame[1] = j - 1;\n\n        // If the pixel is to the right of the frame, set it as the new rightmost\n        if (i >= frame[2])\n          frame[2] = i + 1;\n\n        // If the pixel is under the frame, set it as the new bottommost\n        if (j >= frame[3])\n          frame[3] = j + 1;\n      }\n    }\n  }\n  frame[0] -= 1;\n  frame[1] -= 1;\n  frame[2] -= frame[0] - 2; // adjust indexes relative to the min, with a 1px border\n  frame[3] -= frame[1] - 2;\n  return frame;\n}\n\n/**\n * Applies poisson blending on a single process. Finds a patch by applying |mask|\n * upon |src| and blend this patch on |dst| at the corresponding region (again\n * described by applying |mask|). The result of the blending is put in the\n * output parameter |result|.\n */\nvoid poisson_blending_serial(gil::mat_cview<uint8_t> mask,\n                      gil::mat_cview<gil::vec3f> src,\n                      gil::mat_cview<gil::vec3f> dst,\n                      gil::mat_view<gil::vec3f> result,\n                      GradientMethod method) {\n\n  assert(src.size() == mask.size());\n  assert(dst.size() == mask.size());\n\n  // Formula applied here : for all p in the destination domain (omega)\n  // |N_p| * f_p - sum[all q in (N_p intersection omega)]{f_q} =\n  // sum[all q in (N_p intersection delta_omega)]{f*_q} + sum[all q in N_p]{v_pq}\n  // (equation 7 of http://www.cs.virginia.edu/~connelly/class/2014/comp_photo/proj2/poisson.pdf)\n  // Where N_p are the neighbooring 4 pixels to p, f_p is the intensity of the source at p,\n  // delta_omega is the boundary's domain, f*_q the intensity of the destination at q\n  // and v_pq is the vector guidance field's value for the point between p and q,\n  // ie. v_pq = g_p - g_q, with g_{something} being the source image's value at \"something\"\n  // Do note that we do not reuse this notation.\n  gil::mat<gil::vec3f> b = make_guidance(dst, src, mask, method);\n  apply_mask(mask, b); // select the part corresponding to the mask's region\n  gil::mat<gil::vec3f> f(dst.size()); //Will contain the intensity of the image used as input to get f_p\n  gil::mat<gil::vec3f> g(dst.size()); //Will contain the output of one iteration\n  copy(dst, mask, f); //applies the mask on destination and put the output as a copy in f.\n  for (int i = 0; i < kNIter; ++i) { // applying iterative method to have the value of f converge\n    jacobi_iteration(f, b, mask, g); // Calculate the new value of g\n    f.swap(g); // use g as an input for next iteration\n  }\n  result = dst;\n  copy(f, mask, result); // put resulting f's area corresponding to mask in\n                         // output |result| variable to return\n}\n\n/**\n * Applies poisson blending on a multiple cpu process. Finds a patch by applying\n * |mask|upon |src| and blend this patch on |dst| at the corresponding region\n * (again described by applying |mask|). The result of the blending is put in\n * the output parameter |result|.\n */\nvoid poisson_blending_tbb(gil::mat_cview<uint8_t> mask,\n                          gil::mat_cview<gil::vec3f> src,\n                          gil::mat_cview<gil::vec3f> dst,\n                          gil::mat_view<gil::vec3f> result,\n                          GradientMethod method) {\n\n  assert(src.size() == mask.size());\n  assert(dst.size() == mask.size());\n\n  // Formula applied here : for all p in the destination domain (omega)\n  // |N_p| * f_p - sum[all q in (N_p intersection omega)]{f_q} =\n  // sum[all q in (N_p intersection delta_omega)]{f*_q} + sum[all q in N_p]{v_pq}\n  // (equation 7 of http://www.cs.virginia.edu/~connelly/class/2014/comp_photo/proj2/poisson.pdf)\n  // Where N_p are the neighbooring 4 pixels to p, f_p is the intensity of the source at p,\n  // delta_omega is the boundary's domain, f*_q the intensity of the destination at q\n  // and v_pq is the vector guidance field's value for the point between p and q,\n  // ie. v_pq = g_p - g_q, with g_{something} being the source image's value at \"something\"\n  // Do note that we do not reuse this notation.\n\n  // calculate the right side of the equation, see above. Constant across solving\n  gil::mat<gil::vec3f> b = tbb_make_guidance(dst, src, mask, method);\n  tbb_apply_mask(mask, b); // select the part corresponding to the mask's region\n  gil::mat<gil::vec3f> f(dst.size()); //Will contain the intensity of the image used as input to get f_p\n  gil::mat<gil::vec3f> g(dst.size()); //Will contain the output of one iteration\n  copy(dst, mask, f); //applies the mask on destination and put the output as a copy in f.\n  for (int i = 0; i < kNIter; ++i) { // applying iterative method to have the value of f converge\n    tbb_jacobi_iteration(f, b, mask, g); // Calculate the new value of g\n    f.swap(g); // use g as an input for next iteration\n  }\n  result = dst;\n  copy(f, mask, result); // put resulting f's area corresponding to mask in\n  // output |result| variable to return\n}\n\n// Class to be used to execute the poisson blending with OpenCL.\n// In a class to compile the OpenCL program on c++ compilation\nclass poisson_blending_cl {\n public:\n  // Constructor, builds the OpenCL program\n  poisson_blending_cl()\n      : device_(cl::get_devices(cl::filter::gpu())[0]),\n        ctx_(device_) {\n    // read and load the OpenCL program from its file\n    boost::iostreams::mapped_file_source poisson_source(find_file(\"poisson.cl\"));\n    program_ = cl::program(ctx_, poisson_source.data());\n    try {\n      program_.build();\n    } catch (...) {\n      std::cout << program_.get_build_info<cl::program::BuildLog>(device_);\n      return;\n    }\n\n    make_boundary_ = cl::kernel(program_, \"make_boundary\");\n    make_guidance_ = cl::kernel(program_, \"make_guidance\");\n    make_guidance_mixed_gradient_ = cl::kernel(program_, \"make_guidance_mixed_gradient\");\n    make_guidance_mixed_gradient_avg_ = cl::kernel(program_, \"make_guidance_mixed_gradient_avg\");\n    jacobi_iteration_ = cl::kernel(program_, \"jacobi_iteration\");\n    apply_mask_ = cl::kernel(program_, \"apply_mask\");\n  }\n\n  /**\n   * Operator calculating the poisson blending using the OpenCL program.\n   * Finds a patch by applying |mask| upon |src| and blend this patch on |dst| at\n   * the corresponding region (again described by applying |mask|). The result\n   * of the blending is put in the output parameter |result|.\n   */\n  void operator()(gil::mat_cview<uint8_t> mask,\n                         gil::mat_cview<gil::vec3f> src,\n                         gil::mat_cview<gil::vec3f> dst,\n                         gil::mat_view<gil::vec3f> result,\n                         GradientMethod method) {\n\n    // Formula applied here : for all p in the destination domain (omega)\n    // |N_p| * f_p - sum[all q in (N_p intersection omega)]{f_q} =\n    // sum[all q in (N_p intersection delta_omega)]{f*_q} + sum[all q in N_p]{v_pq}\n    // (equation 7 of http://www.cs.virginia.edu/~connelly/class/2014/comp_photo/proj2/poisson.pdf)\n    // Where N_p are the neighbooring 4 pixels to p, f_p is the intensity of the source at p,\n    // delta_omega is the boundary's domain, f*_q the intensity of the destination at q\n    // and v_pq is the vector guidance field's value for the point between p and q,\n    // ie. v_pq = g_p - g_q, with g_{something} being the source image's value at \"something\"\n    // Do note that we do not reuse this notation.\n\n    // OpenCl image of the mask\n    cl::image cl_mask(ctx_,\n      cl::image_format{cl::channel_order::kR, cl::channel_type::kUInt8},\n      cl::image_desc::make_image_2d(mask.cols(), mask.rows()),\n      cl::buffer::device);\n\n    // OpenCl image of the boundary, used to calculate the right side of the poisson equation\n    cl::image cl_boundary(ctx_,\n      cl::image_format{cl::channel_order::kR, cl::channel_type::kUInt8},\n      cl::image_desc::make_image_2d(mask.cols(), mask.rows()),\n      cl::buffer::device);\n\n    // OpenCl image to contain the intensity values from last iteration\n    cl::image cl_f(ctx_,\n      cl::image_format{cl::channel_order::kRGB, cl::channel_type::kFloat},\n      cl::image_desc::make_image_2d(mask.cols(), mask.rows()),\n      cl::buffer::device);\n\n    // OpenCl image to contain the result of poisson iterations\n    cl::image cl_g(ctx_,\n      cl::image_format{cl::channel_order::kRGB, cl::channel_type::kFloat},\n      cl::image_desc::make_image_2d(mask.cols(), mask.rows()),\n      cl::buffer::device);\n\n    // OpenCl image to contain the right side of the equation\n    cl::image cl_guidance(ctx_,\n      cl::image_format{cl::channel_order::kRGB, cl::channel_type::kFloat},\n      cl::image_desc::make_image_2d(mask.cols(), mask.rows()),\n      cl::buffer::device);\n\n    // Initialise cl_mask using the mask image data\n    cl::write_image(cl_mask,\n      {0, 0, 0}, {mask.cols(), mask.rows(), 1}, mask.pitch(),\n      reinterpret_cast<const uint8_t*>(mask.data()))\n      (ctx_.default_queue(), {}).wait();\n\n    // Initialise cl_f using the destination image data\n    cl::write_image(cl_f,\n      {0, 0, 0}, {dst.cols(), dst.rows(), 1}, dst.pitch(),\n      reinterpret_cast<const uint8_t*>(dst.data()))\n      (ctx_.default_queue(), {}).wait();\n\n    // Initialise cl_g using the source image data\n    cl::write_image(cl_g,\n      {0, 0, 0}, {src.cols(), src.rows(), 1}, src.pitch(),\n      reinterpret_cast<const uint8_t*>(src.data()))\n      (ctx_.default_queue(), {}).wait();\n\n    // Initialise cl_boundary by calculating the cl_mask's boundary\n    cl::invoke_kernel(make_boundary_,\n      {mask.cols(), mask.rows()}, std::make_tuple(cl_mask, cl_boundary))\n      (ctx_.default_queue(), {}).wait();\n\n    // Initialise cl_guidance by calculating the right side of the poisson equation.\n    // We save the event of that call's end in e1.\n    cl::kernel b;\n    switch (method) {\n      default:\n      case GradientMethod::BASE:\n        b = make_guidance_;\n        break;\n\n      case GradientMethod::MAX_MIXING:\n        b = make_guidance_mixed_gradient_;\n        break;\n\n      case GradientMethod::AVG_MIXING:\n        b = make_guidance_mixed_gradient_avg_;\n        break;\n    }\n    auto e1 = cl::invoke_kernel(b,\n      {mask.cols(), mask.rows()},\n      std::make_tuple(cl_f, cl_g, cl_mask, cl_boundary, cl_guidance))\n      (ctx_.default_queue(), {});\n\n    // We apply the cl_mask on cl_f in order to select only the relevant information\n    // from the destination\n    cl::invoke_kernel(apply_mask_,\n      {mask.cols(), mask.rows()}, std::make_tuple(cl_mask, cl_f))\n      (ctx_.default_queue(), {}).wait();\n\n    // Using iterative method to calculate cl_g\n    for (size_t i = 0; i < kNIter; ++i) {\n      // Once e1 happened (guidance field complete for first iteration,\n      // previous iteration for the 499 other iterations), calculate\n      // a new value of intensity field based on the left side of the equation\n      e1 = cl::invoke_kernel(jacobi_iteration_,\n      {mask.cols(), mask.rows()},\n      std::make_tuple(cl_f, cl_guidance, cl_mask, cl_g))\n      (ctx_.default_queue(), {e1});\n      cl_g.swap(cl_f);\n    }\n\n    result = dst;\n    gil::mat<gil::vec3f> tmp(dst.size());\n    // once the last iteration is done, copy the resulting cl_f into tmp matrix.\n    cl::read_image(cl_f,\n      {0, 0, 0}, {tmp.cols(), tmp.rows(), 1}, tmp.pitch(),\n      reinterpret_cast<uint8_t*>(tmp.data()))(ctx_.default_queue(), {e1}).wait();\n    copy(tmp, mask, result); // Apply mask on tmp and paste the output at the corresponding\n                             // region onto result, initialised with destination\n  }\n\n private:\n  cl::device device_;\n  cl::context ctx_;\n  cl::program program_;\n  cl::kernel make_boundary_;\n  cl::kernel make_guidance_;\n  cl::kernel make_guidance_mixed_gradient_;\n  cl::kernel make_guidance_mixed_gradient_avg_;\n  cl::kernel jacobi_iteration_;\n  cl::kernel apply_mask_;\n};\n\ntemplate <class F>\ndouble benchmark(const F& fcn, int nb_run = 3) {\n  double avg = 0;\n  for (int i = 0; i < nb_run; ++i) {\n    auto start = std::chrono::high_resolution_clock::now();\n    fcn();\n    auto end = std::chrono::high_resolution_clock::now();\n    std::chrono::duration<double> diff = end-start;\n    avg += diff.count();\n  }\n  avg /= nb_run;\n  return avg;\n}\n\nstd::string make_filename(const std::string& base, GradientMethod method) {\n  return base + \"-\" + std::to_string(kNIter) + \"-\" +\n    std::to_string(static_cast<int>(method)) + \".jpg\";\n}\n\nint main(int argc, const char *argv[]) {\n  using namespace std::placeholders;\n\n  // Load images\n  gil::mat<gil::vec3f> dst(gil::mat_view<gil::vec3b>(\n      cv::imread(argv[1])));\n  gil::mat<gil::vec3f> src(gil::mat_view<gil::vec3b>(\n      cv::imread(argv[2])));\n  gil::mat<uint8_t> mask(gil::mat_view<gil::vec3b>(cv::imread(argv[3])));\n  GradientMethod method = static_cast<GradientMethod>(atoi(argv[4]));\n  \n  gil::mat<gil::vec3f> result = dst;\n  auto frame = find_frame(mask); // limit the mask's size to the minimum needed\n\n  // Time the serial calculation of serial poisson blending and save its output in a file\n  std::cout << benchmark([&](){\n    poisson_blending_serial(mask[frame], src[frame], dst[frame], result[frame], method);\n  }) << std::endl;\n  cv::imwrite(make_filename(\"result-serial\", method), cv::Mat(result));\n\n  // Time the opencl calculation of serial poisson blending and save its output in a file\n  poisson_blending_cl poisson_blending_cl;\n  std::cout << benchmark([&](){\n    poisson_blending_cl(mask[frame], src[frame], dst[frame], result[frame], method);\n  }) << std::endl;\n  cv::imwrite(make_filename(\"result-cl\", method), cv::Mat(result));\n\n  // Time the tbb calculation of serial poisson blending and save its output in a file\n  std::cout << benchmark([&](){\n    poisson_blending_tbb(mask[frame], src[frame], dst[frame], result[frame], method);\n  }) << std::endl;\n  cv::imwrite(make_filename(\"result-tbb\", method), cv::Mat(result));\n\n  return 0;\n}\n", "meta": {"hexsha": "6f4d9243886d6de1fb9327b8470e5e62e26c00f4", "size": 15199, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "main.cpp", "max_stars_repo_name": "eti-p-doray/inf8702", "max_stars_repo_head_hexsha": "1f420f6a6d8df5e9f5dce7c6192b622c761a909a", "max_stars_repo_licenses": ["MIT"], "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": "eti-p-doray/inf8702", "max_issues_repo_head_hexsha": "1f420f6a6d8df5e9f5dce7c6192b622c761a909a", "max_issues_repo_licenses": ["MIT"], "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": "eti-p-doray/inf8702", "max_forks_repo_head_hexsha": "1f420f6a6d8df5e9f5dce7c6192b622c761a909a", "max_forks_repo_licenses": ["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.6410958904, "max_line_length": 104, "alphanum_fraction": 0.6562273834, "num_tokens": 4157, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.30096313101869365}}
{"text": "/*\nFor more information, please see: http://software.sci.utah.edu\n\nThe MIT License\n\nCopyright (c) 2012 Scientific Computing and Imaging Institute,\nUniversity of Utah.\n\n\nPermission is hereby granted, free of charge, to any person obtaining a\ncopy of this software and associated documentation files (the \"Software\"),\nto deal in the Software without restriction, including without limitation\nthe rights to use, copy, modify, merge, publish, distribute, sublicense,\nand/or sell copies of the Software, and to permit persons to whom the\nSoftware is furnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included\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//    File       : SolveInverseProblemWithTikhonov.cc\n//    Author     : Moritz Dannhauer, Ayla Khan, Dan White\n//    Date       : November 02th, 2012 (last update)\n\n#include <boost/bind.hpp>\n#include <boost/lexical_cast.hpp>\n\n#include <Modules/Legacy/Inverse/SolveInverseProblemWithTikhonovImpl.h>\n\n#include <Core/Datatypes/Matrix.h>\n#include <Core/Datatypes/DenseMatrix.h>\n#include <Core/Datatypes/DenseColumnMatrix.h>\n#include <Core/Datatypes/SparseRowMatrix.h>\n#include <Core/Datatypes/MatrixTypeConversions.h>\n\n#include <Core/Logging/LoggerInterface.h>\n#include <Core/Utils/Exception.h>\n\nnamespace BioPSE\n{\n\nusing namespace SCIRun;\nusing namespace SCIRun::Core;\nusing namespace SCIRun::Core::Datatypes;\nusing namespace SCIRun::Core::Logging;\n\nTikhonovAlgorithmImpl::TikhonovAlgorithmImpl(const DenseMatrixHandle& forwardMatrix,\n                                             const DenseMatrixHandle& measuredData,\n                                             AlgorithmChoice regularizationChoice,\n                                             AlgorithmSolutionSubcase regularizationSolutionSubcase,\n                                             AlgorithmResidualSubcase regularizationResidualSubcase,\n                                             const DenseMatrixHandle sourceWeighting,\n                                             const DenseMatrixHandle sensorWeighting,\n                                             bool computeRegularizedInverse,\n                                             LegacyLoggerInterface* pr)\n: forwardMatrix_(forwardMatrix),\nmeasuredData_(measuredData),\nsourceWeighting_(sourceWeighting),\nsensorWeighting_(sensorWeighting),\nregularizationChoice_(regularizationChoice),\nregularizationSolutionSubcase_(regularizationSolutionSubcase),\nregularizationResidualSubcase_(regularizationResidualSubcase),\nlambda_(0),\ncomputeRegularizedInverse_(computeRegularizedInverse),\npr_(pr)\n{\n  //TODO: size checking here.\n}\n\nMatrixHandle TikhonovAlgorithmImpl::get_inverse_solution() const\n{\n  return inverseSolution_;\n}\n\nMatrixHandle TikhonovAlgorithmImpl::get_inverse_matrix() const\n{\n  return inverseMatrix_;\n}\n\nDenseColumnMatrixHandle TikhonovAlgorithmImpl::get_regularization_parameter() const\n{\n  return regularizationParameter_;\n}\n\n//! Find Corner, find the maximal curvature which corresponds to the L-curve corner\ndouble\nTikhonovAlgorithmImpl::FindCorner(const TikhonovAlgorithm::LCurveInput& input, int& lambda_index)\n{\n  const std::vector<double>& rho = input.rho_;\n  const std::vector<double>& eta = input.eta_;\n  const std::vector<double>& lambdaArray = input.lambdaArray_;\n  int nLambda = input.nLambda_;\n\n  std::vector<double> deta(nLambda);\n  std::vector<double> ddeta(nLambda);\n  std::vector<double> drho(nLambda);\n  std::vector<double> ddrho(nLambda);\n  std::vector<double> lrho(nLambda);\n  std::vector<double> leta(nLambda);\n  DenseColumnMatrix kapa(nLambda);\n\n  double maxKapa = -1.0e10;\n  for (int i = 0; i < nLambda; i++)\n  {\n    lrho[i] = std::log10(rho[i]);\n    leta[i] = std::log10(eta[i]);\n    if(i>0)\n    {\n      deta[i] = (leta[i]-leta[i-1]) / (lambdaArray[i]-lambdaArray[i-1]); // compute first derivative\n      drho[i] = (lrho[i]-lrho[i-1]) / (lambdaArray[i]-lambdaArray[i-1]);\n    }\n    if(i>1)\n    {\n      ddeta[i] = (deta[i]-deta[i-1]) / (lambdaArray[i]-lambdaArray[i-1]); // compute second derivative from first\n      ddrho[i] = (drho[i]-drho[i-1]) / (lambdaArray[i]-lambdaArray[i-1]);\n    }\n  }\n  drho[0] = drho[1];\n  deta[0] = deta[1];\n  ddrho[0] = ddrho[2];\n  ddrho[1] = ddrho[2];\n  ddeta[0] = ddeta[2];\n  ddeta[1] = ddeta[2];\n\n  lambda_index = 0;\n  for (int i = 0; i < nLambda; i++)\n  {\n    kapa[i] = std::abs((drho[i] * ddeta[i] - ddrho[i] * deta[i]) /  //compute curvature\n                       std::sqrt(std::pow((deta[i]*deta[i]+drho[i]*drho[i]), 3.0)));\n    if (kapa[i] > maxKapa) // find max curvature\n    {\n      maxKapa = kapa[i];\n      lambda_index = i;\n    }\n  }\n\n  return lambdaArray[lambda_index];\n}\n\ndouble\nTikhonovAlgorithmImpl::LambdaLookup(const TikhonovAlgorithm::LCurveInput& input, double lambda, int& lambda_index, const double epsilon)\n{\n  const std::vector<double>& lambdaArray = input.lambdaArray_;\n  int nLambda = input.nLambda_;\n\n  for (int i = 0; i < nLambda-1; ++i)\n  {\n    if (i > 0 && (lambda < lambdaArray[i-1] || lambda > lambdaArray[i+1])) continue;\n\n    double lambda_step_midpoint = std::abs(lambdaArray[i+1] - lambdaArray[i])/2;\n\n    if (std::abs(lambda - lambdaArray[i]) <= epsilon)  // TODO: is this a reasonable comparison???\n    {\n      lambda_index = i;\n      return lambdaArray[lambda_index];\n    }\n\n    if (std::abs(lambda - lambdaArray[i]) < lambda_step_midpoint)\n    {\n      lambda_index = i;\n      return lambdaArray[lambda_index];\n    }\n\n    if (std::abs(lambda - lambdaArray[i+1]) < lambda_step_midpoint)\n    {\n      lambda_index = i+1;\n      return lambdaArray[lambda_index];\n    }\n  }\n  return -1;\n}\n\nnamespace LinearAlgebra\n{\n  void solve_lapack(const DenseMatrix& A, const DenseColumnMatrix& b, DenseColumnMatrix& x)\n  {\n    x = A.lu().solve(b).eval();\n  }\n\n  class LapackError : public std::exception {};\n}\n\nvoid TikhonovAlgorithmImpl::run(const TikhonovAlgorithmImpl::Input& input)\n{\n  // TODO: use DimensionMismatch exception where appropriate\n  // DIMENSION CHECK!!\n  const int M = forwardMatrix_->nrows();\n  const int N = forwardMatrix_->ncols();\n  if (M != measuredData_->nrows())\n  {\n    BOOST_THROW_EXCEPTION(DimensionMismatch() << DimensionMismatchInfo(\"Input matrix dimensions must agree.\"));\n  }\n  if (1 != measuredData_->ncols())\n  {\n    BOOST_THROW_EXCEPTION(DimensionMismatch() << DimensionMismatchInfo(\"Measured data must be a vector\"));\n  }\n  //decide used Tikhonov regularization formulation (underdetermined or overdetermined)\n  //based purely on relationship of number of sensors compared to number of source reconstruction points\n  //UNDERDETERMINED CASE\n  if ( ((M < N) && (regularizationChoice_ == automatic)) || (regularizationChoice_ == underdetermined))\n  {\n    //.........................................................................\n    // OPERATE ON DATA:\n    // Compute X = R * R^T * A^T (A * R * R^T * A^T + LAMBDA * LAMBDA * C * C^T) * Y\n    //.........................................................................\n    DenseMatrix ARRtrAtr, RRtrAtr;\n    double lambda=0, lambda_sq=0;\n    DenseMatrix forward_transpose = forwardMatrix_->transpose();\n    DenseMatrix regMat;\n    #ifdef SCIRUN4_CODE_TO_BE_CONVERTED_LATER\n    SparseRowMatrixHandle sourceWeighting_sparse;\n    #endif\n    DenseColumnMatrix solution(M);\n    DenseColumnMatrix RRtrAtrsolution(N);\n\n    const DenseMatrixHandle measuredDataRef = measuredData_;\n    if (!sourceWeighting_) //check if a Source Space Weighting Matrix exist?\n    {\n      regMat = DenseMatrix::Identity(N, N);\n      ARRtrAtr = *forwardMatrix_ * forward_transpose;\n      RRtrAtr = forward_transpose;\n    }\n    else\n    {\n      if(((regularizationSolutionSubcase_==solution_constrained) && ((N != sourceWeighting_->nrows()) || (N != sourceWeighting_->ncols()))) ||\n         ((regularizationSolutionSubcase_==solution_constrained_squared) && (N != sourceWeighting_->nrows())))\n      {\n        BOOST_THROW_EXCEPTION(DimensionMismatch() << DimensionMismatchInfo(\"Solution Weighting Matrix (number of rows and columns) must fit matrix dimensions of Forward Matrix (number of columns) !\"));\n      }\n      regMat = *sourceWeighting_;\n      #ifdef SCIRUN4_CODE_TO_BE_CONVERTED_LATER\n      sourceWeighting_sparse = sourceWeighting_->sparse();\n      #endif\n\n      if (regularizationSolutionSubcase_== solution_constrained)\n      {\n        RRtrAtr = *sourceWeighting_ * forward_transpose;\n\t      auto AR = forwardMatrix_;\n\t      ARRtrAtr = *AR * RRtrAtr;\n      }\n      else if (regularizationSolutionSubcase_== solution_constrained_squared)\n      {\n        auto AR = *forwardMatrix_ * *sourceWeighting_;\n\t      auto RtrAtr = AR.transpose().eval();\n        RRtrAtr = *sourceWeighting_ * RtrAtr;\n\t      ARRtrAtr = AR * RtrAtr;\n      }\n    }\n    DenseMatrix CCtr;\n    if (!sensorWeighting_) //check if a Sensor Space (Noise Covariance) Weighting Matrix exist?\n    {\n      CCtr = DenseMatrix::Identity(M, M);\n    }\n    else\n    {\n      if (((regularizationResidualSubcase_ == residual_constrained) && ((M != sensorWeighting_->nrows()) || (M != sensorWeighting_->ncols()))) ||\n          ((regularizationResidualSubcase_ == residual_constrained_squared) && (M != sensorWeighting_->nrows())))\n      {\n        BOOST_THROW_EXCEPTION(DimensionMismatch() << DimensionMismatchInfo(\"Data Residual Weighting Matrix (number of rows and columns) must fit matrix dimensions of Forward Matrix (number of rows) !\"));\n      }\n      else\n      {\n        if (regularizationResidualSubcase_ == residual_constrained)\n          CCtr = *sensorWeighting_;\n        else\n          if ( regularizationResidualSubcase_ == residual_constrained_squared )\n            CCtr = *sensorWeighting_ * sensorWeighting_->transpose();\n      }\n    }\n\n    DenseMatrix regForMatrix(M, M);\n\n    //Get Regularization parameter(s) : Lambda\n    if ((input.regMethod_ == \"single\") || (input.regMethod_ == \"slider\"))\n    {\n      if (input.regMethod_ == \"single\")\n      {\n        // Use single fixed lambda value, entered in UI\n        lambda = input.lambdaFromTextEntry_;\n      }\n      else if (input.regMethod_ == \"slider\")\n      {\n        // Use single fixed lambda value, select via slider\n        lambda = input.lambdaSlider_;\n      }\n    }\n    else if (input.regMethod_ == \"lcurve\")\n    {\n      const int nLambda = input.lambdaCount_;  //declare needed variables\n\n      std::vector<double> lambdaArray(nLambda, 0.0);\n      std::vector<double> rho(nLambda, 0.0);\n      std::vector<double> eta(nLambda, 0.0);\n\n      lambdaArray[0] = input.lambdaMin_;\n      const double lam_step = pow(10.0, log10(input.lambdaMax_ / input.lambdaMin_) / (nLambda-1));\n\n      DenseColumnMatrix Ax(M);\n      DenseColumnMatrix Rx(N);\n\n      int lambda_index = 0;\n      const DenseMatrix &forwardMatrixRef = *forwardMatrix_;\n\n      int nr_rows = CCtr.nrows();\n      int nr_cols = CCtr.ncols();\n      const int NR_BOUNDS_CHECK = nr_rows * nr_cols;\n\n      double* AtrA = ARRtrAtr.data();\n      double* LLtr = CCtr.data();\n\n      for (int j = 0; j < nLambda; j++)\n      {\n        if (j)\n        {\n          lambdaArray[j] = lambdaArray[j-1] * lam_step;\n        }\n\n        lambda_sq = lambdaArray[j] * lambdaArray[j]; //generate current lambda\n\n        double* rm = regForMatrix.data();\n\n        for (int i = 0; i < NR_BOUNDS_CHECK; i++)\n        {\n          rm[i] = AtrA[i] + lambda_sq * LLtr[i];\n        }\n\n        try\n        {\n          LinearAlgebra::solve_lapack(regForMatrix, *measuredDataRef, solution);\n        }\n        catch (LinearAlgebra::LapackError&)\n        {\n          const std::string errorMessage(\"The Tikhonov linear system could not be solved for a regularization parameter in the Lambda Range of the L-curve. Use a higher Lambda Range ''From'' value for the L-Curve calculation.\");\n          if (pr_)\n          {\n            pr_->error(errorMessage);\n          }\n          else\n          {\n            std::cerr << errorMessage << std::endl;\n          }\n          throw;\n        }\n        catch(DimensionMismatch&)\n        {\n          const std::string errorMessage(\"Invalid matrix sizes are being used in the Tikhonov linear system.\");\n          if (pr_)\n          {\n            pr_->error(errorMessage);\n          }\n          else\n          {\n            std::cerr << errorMessage << std::endl;\n          }\n          throw;\n        }\n\n        RRtrAtrsolution = RRtrAtr * solution;\n\n        if (sourceWeighting_)\n        {\n          if (RRtrAtrsolution.nrows() == sourceWeighting_->ncols())\n            Rx = *sourceWeighting_ * RRtrAtrsolution;\n          else if  (RRtrAtrsolution.nrows() == sourceWeighting_->nrows())\n            Rx = sourceWeighting_->transpose() * RRtrAtrsolution;\n          else\n          {\n            const std::string errorMessage(\" Solution weighting matrix unexpectedly does not fit to compute the weighted solution norm. \");\n            if (pr_)\n            {\n              pr_->error(errorMessage);\n            }\n            else\n            {\n              std::cerr << errorMessage << std::endl;\n            }\n          }\n        }\n        else\n          Rx = RRtrAtrsolution;\n\n        // Calculate the norm of Ax-b and Rx for L curve\n        Ax = forwardMatrixRef * RRtrAtrsolution;\n\n        rho[j]=0; eta[j]=0;\n        for (int k = 0; k < Ax.nrows(); k++)\n        {\n          double T = Ax(k) - (*measuredDataRef)(k);\n          rho[j] += T*T; //norm of the data fit term\n        }\n\n        for (int k = 0; k < Rx.nrows(); k++)\n        {\n          double T = Rx[k];\n          eta[j] += T*T; //norm of the model term\n        }\n        // eta and rho needed to plot the Lcurve and determine the L corner\n        rho[j] = sqrt(rho[j]);\n        eta[j] = sqrt(eta[j]);\n      }\n      boost::shared_ptr<TikhonovAlgorithm::LCurveInput> lcurveInput(new TikhonovAlgorithm::LCurveInput(rho, eta, lambdaArray, nLambda));\n      lcurveInput_handle_ = lcurveInput;\n      lambda = FindCorner(*lcurveInput_handle_, lambda_index);\n\n      if (input.updateLCurveGui_)\n        input.updateLCurveGui_(lambda, *lcurveInput_handle_, lambda_index);\n    }\n    lambda_sq = lambda * lambda;\n    //compute the solution with the selected regularization parameter: lambda\n    regularizationParameter_.reset(new DenseColumnMatrix(1));\n    (*regularizationParameter_)(0) = lambda;\n    int nr_rows = regForMatrix.nrows();\n    int nr_cols = regForMatrix.ncols();\n\n    double* AtrA = ARRtrAtr.data();\n    double* RtrR = CCtr.data();\n    double* rm   = regForMatrix.data();\n    for (int i=0; i<(int)(nr_rows*nr_cols); i++)\n    {\n      rm[i] = AtrA[i] + lambda_sq * RtrR[i];\n    }\n\n    if (computeRegularizedInverse_)\n    {\n      if (sourceWeighting_)\n      {\n        inverseMatrix_.reset(new DenseMatrix(RRtrAtr * regForMatrix.inverse()));\n      }\n      else\n      {\n        inverseMatrix_.reset(new DenseMatrix(forward_transpose * regForMatrix.inverse()));\n      }\n      inverseSolution_.reset(new DenseMatrix(*inverseMatrix_ * *measuredData_));\n    }\n    else\n    {\n      try\n      {\n        LinearAlgebra::solve_lapack(regForMatrix, *measuredDataRef, solution);\n      }\n      catch (LinearAlgebra::LapackError&)\n      {\n        const std::string errorMessage(\"The Tikhonov linear system could not be solved for a regularization parameter in the Lambda Range of the L-curve. Use a higher Lambda Range ''From'' value for the L-Curve calculation.\");\n        if (pr_)\n        {\n          pr_->error(errorMessage);\n        }\n        else\n        {\n          std::cerr << errorMessage << std::endl;\n        }\n        throw;\n      }\n      catch(DimensionMismatch&)\n      {\n        const std::string errorMessage(\"Invalid matrix sizes are being used in the Tikhonov linear system.\");\n        if (pr_)\n        {\n          pr_->error(errorMessage);\n        }\n        else\n        {\n          std::cerr << errorMessage << std::endl;\n        }\n        throw;\n      }\n\n      RRtrAtrsolution = RRtrAtr * solution;\n      inverseSolution_.reset(new DenseMatrix(RRtrAtrsolution));\n    }\n\n  }\n  else\n    //OVERDETERMINED CASE,\n    //similar procedure as underdetermined case (documentation comments similar, see above)\n    if ( ((regularizationChoice_ == automatic) && (M>=N)) || (regularizationChoice_==overdetermined) )\n    {\n      //.........................................................................\n      // OPERATE ON DATA:\n      // Computes X = (A^T * C^T * C * A + LAMBDA * LAMBDA * R^T * R) * A^T * C^T * C *Y\n      //.........................................................................\n      // calculate A^T * A\n      DenseMatrix forward_transpose = forwardMatrix_->transpose();\n      DenseMatrix AtrA;\n      DenseMatrix CCtr;\n      DenseMatrix matrixNoiseCov_transpose;\n\n      if (!sensorWeighting_)\n      //check if a Sensor Space (Noise Covariance) Weighting Matrix exist?\n      {\n        // For large problems, allocating this matrix causes the module to hang.\n        // The CCtr matrix is only used if sensorWeighting is available.\n        //\n        // In general, this code really should be rewritten to use sparse matrices (SCIRun 5)\n        // or have replaced with more efficient calculations\n        // (Eigen may have algorithms we can use).\n        //CCtr = DenseMatrix::identity(M);\n        AtrA = forward_transpose * *forwardMatrix_;\n      }\n      else\n      {\n        if (((regularizationResidualSubcase_ == residual_constrained) && ((M != sensorWeighting_->nrows()) || (M != sensorWeighting_->ncols()))) ||\n            ((regularizationResidualSubcase_ == residual_constrained_squared) && (M != sensorWeighting_->ncols())))\n        {\n          BOOST_THROW_EXCEPTION(DimensionMismatch() << DimensionMismatchInfo(\"Data Residual Weighting Matrix (number of rows and columns) must fit matrix dimensions of Forward Matrix (number of rows)!\"));\n        }\n\n        matrixNoiseCov_transpose = sensorWeighting_->transpose();\n\n        // regularizationResidualSubcase_ is either residual_constrained (default) or residual_constrained_squared\n        if (regularizationResidualSubcase_ == residual_constrained)\n          CCtr = *sensorWeighting_;\n        else\n          if (regularizationResidualSubcase_ == residual_constrained_squared)\n            CCtr = matrixNoiseCov_transpose * *sensorWeighting_;\n\n        AtrA = forward_transpose * CCtr * *forwardMatrix_;\n      }\n      // calculate R^T * R\n      DenseMatrix RtrR;\n      DenseMatrix regMat;\n\n      if (!sourceWeighting_)\n      {\n        regMat = DenseMatrix::Identity(N, N);\n        RtrR = DenseMatrix::Identity(N, N);\n      }\n      else\n      {\n        if(((regularizationSolutionSubcase_==solution_constrained) && ((N != sourceWeighting_->nrows()) || (N != sourceWeighting_->ncols()))) ||\n           ((regularizationSolutionSubcase_==solution_constrained_squared) && (N != sourceWeighting_->ncols())))\n        {\n          BOOST_THROW_EXCEPTION(DimensionMismatch() << DimensionMismatchInfo(\"Solution Weighting Matrix (number of rows and columns) must fit matrix dimensions of Forward Matrix (number of columns) ! \"));\n        }\n        regMat = *sourceWeighting_;\n\n        if (regularizationSolutionSubcase_ == solution_constrained_squared)\n          RtrR = sourceWeighting_->transpose() * regMat;\n        else if (regularizationSolutionSubcase_ == solution_constrained)\n          RtrR = regMat;\n      }\n\n      double lambda = 0, lambda_sq = 0;\n      int lambda_index = 0;\n      // calculate A^T * Y\n      DenseColumnMatrix AtrY(N);\n      DenseColumnMatrix measuredDataRef;\n      if (sensorWeighting_)\n      {\n        measuredDataRef = CCtr * *measuredData_;\n      }\n      else\n      {\n        measuredDataRef = *measuredData_;\n      }\n      AtrY = forwardMatrix_->transpose() * measuredDataRef;\n      DenseMatrix regForMatrix(N, N);\n      DenseColumnMatrix solution(N);\n      DenseColumnMatrix Ax(M);\n      DenseColumnMatrix Rx(N);\n      if ((input.regMethod_ == \"single\") || (input.regMethod_ == \"slider\"))\n      {\n        if (input.regMethod_ == \"single\")\n        {\n          // Use single fixed lambda value, entered in UI\n          lambda = input.lambdaFromTextEntry_;\n        }\n        else if (input.regMethod_ == \"slider\")\n        {\n          // Use single fixed lambda value, select via slider\n          lambda = input.lambdaSlider_;\n        }\n      }\n      else if (input.regMethod_ == \"lcurve\")\n      {\n        // Use L-curve, lambda from corner of the L-curve\n        const int nLambda = input.lambdaCount_;\n\n        std::vector<double> lambdaArray(nLambda);\n        std::vector<double> rho(nLambda);\n        std::vector<double> eta(nLambda);\n\n        lambdaArray[0] = input.lambdaMin_;\n        const double lam_step = pow(10.0, log10(input.lambdaMax_ / input.lambdaMin_) / (nLambda-1));\n\n        double* AtrAptr = AtrA.data();\n        double* RtrRptr = RtrR.data();\n        double* rm   = regForMatrix.data();\n\n        int s = N*N;\n        for (int j = 0; j < nLambda; j++)\n        {\n          if (j)\n          {\n            lambdaArray[j] = lambdaArray[j-1] * lam_step;\n          }\n\n          lambda_sq = lambdaArray[j] * lambdaArray[j];\n\n          ///////////////////////////////////////\n          ////Calculating the solution directly\n          ///////////////////////////////////////\n          for (int i = 0; i < s; i++)\n          {\n            rm[i] = AtrAptr[i] + lambda_sq * RtrRptr[i];\n          }\n\n          // Before, solution will be equal to (A^T * y)\n          // After, solution will be equal to x_reg\n          try\n          {\n            LinearAlgebra::solve_lapack(regForMatrix, AtrY, solution);\n          }\n          catch (LinearAlgebra::LapackError&)\n          {\n            const std::string errorMessage(\"The Tikhonov linear system could not be solved for a regularization parameter in the Lambda Range of the L-curve. Use a higher Lambda value for the L-Curve calculation.\");\n            if (pr_)\n            {\n              pr_->error(errorMessage);\n            }\n            else\n            {\n              std::cerr << errorMessage << std::endl;\n            }\n            throw;\n          }\n          catch(DimensionMismatch&)\n          {\n            const std::string errorMessage(\"Invalid matrix sizes are being used in the Tikhonov linear system.\");\n            if (pr_)\n            {\n              pr_->error(errorMessage);\n            }\n            else\n            {\n              std::cerr << errorMessage << std::endl;\n            }\n            throw;\n          }\n\n          ////////////////////////////////\n          const DenseMatrix &forwardMatrixRef = *forwardMatrix_;\n\n          Ax = forwardMatrixRef * solution;\n          Rx = regMat * solution;\n          // Calculate the norm of Ax-b and Rx\n          rho[j]=0; eta[j]=0;\n          for (int k = 0; k < M; k++)\n          {\n            double T = Ax(k) - (*measuredData_)(k);\n            rho[j] += T*T;\n          }\n\n          for (int k = 0; k < N; k++)\n          {\n            double T = Rx(k);\n            eta[j] += T*T;\n          }\n\n          rho[j] = sqrt(rho[j]);\n          eta[j] = sqrt(eta[j]);\n        }\n        boost::shared_ptr<TikhonovAlgorithm::LCurveInput> lcurveInput(new TikhonovAlgorithm::LCurveInput(rho, eta, lambdaArray, nLambda));\n        lcurveInput_handle_ = lcurveInput;\n        lambda = FindCorner(*lcurveInput_handle_, lambda_index);\n\n        if (input.updateLCurveGui_)\n          input.updateLCurveGui_(lambda, *lcurveInput_handle_, lambda_index);\n\n      } // END  else if (reg_method_.get() == \"lcurve\")\n      lambda_sq = lambda * lambda;\n\n      regularizationParameter_.reset(new DenseColumnMatrix(1));\n      (*regularizationParameter_)[0] = lambda;\n      int nr_rows = regForMatrix.nrows();\n      int nr_cols = regForMatrix.ncols();\n      const int NR_BOUNDS_CHECK = nr_rows * nr_cols;\n      const double* AtrAptr = AtrA.data();\n      const double* RtrRptr = RtrR.data();\n      double* rm   = regForMatrix.data();\n\n      for (int i = 0; i < NR_BOUNDS_CHECK; i++)\n      {\n        rm[i] = AtrAptr[i] + lambda_sq * RtrRptr[i];\n      }\n      if (computeRegularizedInverse_)\n      {\n        if (CCtr.empty())\n          inverseMatrix_.reset(new DenseMatrix((regForMatrix.inverse() * forward_transpose)));\n        else\n          inverseMatrix_.reset(new DenseMatrix((regForMatrix.inverse() * forward_transpose) * CCtr));\n\n        inverseSolution_.reset(new DenseMatrix(*inverseMatrix_ * *measuredData_));\n      }\n      else\n      {\n        try\n        {\n          LinearAlgebra::solve_lapack(regForMatrix, AtrY, solution);\n        }\n        catch (LinearAlgebra::LapackError&)\n        {\n          const std::string errorMessage(\"The Tikhonov linear system could not be solved for a regularization parameter in the Lambda Range of the L-curve. Use a higher Lambda value for the L-Curve calculation.\");\n          if (pr_)\n          {\n            pr_->error(errorMessage);\n          }\n          else\n          {\n            std::cerr << errorMessage << std::endl;\n          }\n          throw;\n        }\n        catch(DimensionMismatch&)\n        {\n          const std::string errorMessage(\"Invalid matrix sizes are being used in the Tikhonov linear system.\");\n          if (pr_)\n          {\n            pr_->error(errorMessage);\n          }\n          else\n          {\n            std::cerr << errorMessage << std::endl;\n          }\n          throw;\n        }\n        inverseSolution_.reset(new DenseMatrix(solution));\n      }\n\n    }\n}\n\nvoid TikhonovAlgorithmImpl::update_graph(const TikhonovAlgorithmImpl::Input& input, double lambda, int lambda_index, const double epsilon)\n{\n  if (lcurveInput_handle_ && input.updateLCurveGui_)\n  {\n    lambda = LambdaLookup(*lcurveInput_handle_, lambda, lambda_index, epsilon);\n    if (lambda >= 0)\n    {\n      input.updateLCurveGui_(lambda, *lcurveInput_handle_, lambda_index);\n    }\n  }\n}\n\n#if 0\n\nvoid SolveInverseProblemWithTikhonov::tcl_command(GuiArgs& args, void* userdata)\n{\n  if (args[1] == \"updategraph\" && args.count() == 4)\n  {\n    double lambda = boost::lexical_cast<double>(args[2]);\n    int lambda_index = boost::lexical_cast<double>(args[3]);\n\n    if (input_handle_.get() != 0 && algo_handle_.get() != 0)\n    {\n      algo_handle_->update_graph(*input_handle_, lambda, lambda_index, lambda_resolution_.get());\n    }\n  }\n  else\n  {\n    // Relay data to the Module class\n    Module::tcl_command(args, userdata);\n  }\n}\n\n\n#endif\n\nTikhonovAlgorithm::LCurveInput::LCurveInput(const std::vector<double>& rho, const std::vector<double>& eta, const std::vector<double>& lambdaArray, int nLambda)\n: rho_(rho), eta_(eta), lambdaArray_(lambdaArray), nLambda_(nLambda)\n{}\n\nTikhonovAlgorithmImpl::Input::Input(const std::string& regMethod, double lambdaFromTextEntry, double lambdaSlider, int lambdaCount, double lambdaMin, double lambdaMax,\n                                    lcurveGuiUpdate updateLCurveGui)\n: regMethod_(regMethod), lambdaFromTextEntry_(lambdaFromTextEntry), lambdaSlider_(lambdaSlider), lambdaCount_(lambdaCount), lambdaMin_(lambdaMin), lambdaMax_(lambdaMax),\nupdateLCurveGui_(updateLCurveGui)\n{}\n\n} // End namespace BioPSE\n", "meta": {"hexsha": "541aed09897ffcca88ce849ec8f29e44ff139535", "size": 27374, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/Modules/Legacy/Inverse/SolveInverseProblemWithTikhonovImpl.cc", "max_stars_repo_name": "benjaminlarson/SCIRunGUIPrototype", "max_stars_repo_head_hexsha": "ed34ee11cda114e3761bd222a71a9f397517914d", "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/Modules/Legacy/Inverse/SolveInverseProblemWithTikhonovImpl.cc", "max_issues_repo_name": "benjaminlarson/SCIRunGUIPrototype", "max_issues_repo_head_hexsha": "ed34ee11cda114e3761bd222a71a9f397517914d", "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/Modules/Legacy/Inverse/SolveInverseProblemWithTikhonovImpl.cc", "max_forks_repo_name": "benjaminlarson/SCIRunGUIPrototype", "max_forks_repo_head_hexsha": "ed34ee11cda114e3761bd222a71a9f397517914d", "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.7385786802, "max_line_length": 228, "alphanum_fraction": 0.6127712428, "num_tokens": 6678, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5926665999540698, "lm_q2_score": 0.5078118642792044, "lm_q1q2_score": 0.30096313101869365}}
{"text": "/**\n * @file\n * @author  [Yi-Mu \"Enoch\" Chen](https://github.com/yimuchen)\n * @brief   Implementing measurement ostream interaction.\n */\n#ifdef CMSSW_GIT_HASH\n#include \"UserUtils/Common/interface/Maths.hpp\"\n#include \"UserUtils/Common/interface/STLUtils/StringUtils.hpp\"\n#include \"UserUtils/MathUtils/interface/Measurement.hpp\"\n#else\n#include \"UserUtils/Common/Maths.hpp\"\n#include \"UserUtils/Common/STLUtils/StringUtils.hpp\"\n#include \"UserUtils/MathUtils/Measurement.hpp\"\n#endif\n\n#include <boost/algorithm/string.hpp>\n#include <regex>\n#include <string>\n\nnamespace usr\n{\n\nnamespace fmt {\n\n/**\n * @brief Re-implementing a double input for common fmt interface\n *\n * This construction means that the measurement without uncertainty would\n * output the same values as if using a double.\n */\ndecimal::decimal( const double input, const int p ) :\n  _central( input ),\n  _upper( 0 ),\n  _lower( 0 )\n{\n  precision( p );\n}\n\n/**\n * @brief normal construction for typical measurements.\n */\ndecimal::decimal( const Measurement& input, const int p ) :\n  _central( input.CentralValue() ),\n  _upper( input.AbsUpperError() ),\n  _lower( input.AbsLowerError() )\n{\n  if( p < 0 ){\n    SetPrecision();\n  } else {\n    precision( p );\n  }\n}\n\n/**\n * @brief Construct using a RooRealVar status.\n */\ndecimal::decimal( const RooRealVar& input, const int p ) :\n  _central( input.getVal() ),\n  _upper( fabs( input.getErrorHi() ) ),\n  _lower( fabs( input.getErrorLo() ) )\n{\n  if( p < 0 ){\n    SetPrecision();\n  } else {\n    precision( p );\n  }\n}\n\n/**\n * @brief Construct using a RooRealVar status.\n */\ndecimal::decimal( const RooRealVar* input, const int p ) :\n  _central( input->getVal() ),\n  _upper( fabs( input->getErrorHi() ) ),\n  _lower( fabs( input->getErrorLo() ) )\n{\n  if( p < 0 ){\n    SetPrecision();\n  } else {\n    precision( p );\n  }\n}\n\n/**\n * @brief main operation for creating a latex string.\n *\n * @details Note that this function essentially calls the base::decimal\n * methods for creating the string representation of a double three times,\n * meaning that if the central value and uncertainties are of wildly different\n * orders of magnitude, the output could look very weird.\n */\nstd::string\ndecimal::str() const\n{\n  if( _upper == _lower && _upper == 0 ){\n    return base::decimal( _central ).dupsetting( *this ).str();\n  } else {\n    const std::string cen = base::decimal( _central ).dupsetting( *this ).str();\n    const std::string up  = base::decimal( _upper ).dupsetting( *this ).str();\n    const std::string lo  = base::decimal( _lower ).dupsetting( *this ).str();\n\n    if( up == lo ){// string-wise comparison!\n      return usr::fstr( \"%s\\\\pm%s\", cen, up );\n    } else {\n      return usr::fstr( \"%s^{+%s}_{-%s}\", cen, up, lo );\n    }\n  }\n}\n\n/**\n * @brief Base precision overloaded to allow for autoamtic precision setting\n *        with negative settings.\n */\ndecimal&\ndecimal::precision( const int p )\n{\n  if( p < 0 && ( _upper != 0 || _lower != 0 ) ){\n    SetPrecision();\n  } else {\n    base::format::precision( abs( p ) );\n  }\n  return *this;\n}\n\n/**\n * @brief automatic precision setting for the decimal representation.\n * @details The precision is set such that the larger uncertain would display\n *          at least two significant digits (0 if larger uncertainty is greater\n *          than 1).\n */\nvoid\ndecimal::SetPrecision()\n{\n  const double op_unc = std::max( _upper, _lower );\n  const int exp       = GetExponent( op_unc );\n  if( exp > 0 ){\n    _precision = 0;\n  } else {\n    _precision = -exp+1;\n  }\n}\n\n/*-----------------------------------------------------------------------------\n *  Scientific notation implementation functions\n   --------------------------------------------------------------------------*/\n\n\n/**\n * @brief allowing double input to avoid multiple interfaces for double input.\n *\n * This construction means that the measurement without uncertainty would\n * output the same values as if using a double.\n */\nscientific::scientific( const double input, const unsigned p ) :\n  _central( input ),\n  _upper( 0 ),\n  _lower( 0 ),\n  _exp( 0 )\n{\n  precision( p );\n  SetExponent();\n}\n\n/**\n * @brief simple construction with a measurement with uncertainties.\n */\nscientific::scientific( const Measurement& input, const int p ) :\n  _central( input.CentralValue() ),\n  _upper( input.AbsUpperError() ),\n  _lower( input.AbsLowerError() ),\n  _exp( 0 )\n{\n  SetExponent();\n  if( p < 0 ){\n    SetPrecision();\n  } else {\n    precision( p );\n  }\n}\n\n/**\n * @brief Construct using a RooRealVar instance\n */\nscientific::scientific( const RooRealVar& input, const int p ) :\n  _central( input.getVal() ),\n  _upper( fabs( input.getErrorHi() ) ),\n  _lower( fabs( input.getErrorLo() ) ),\n  _exp( 0 )\n{\n  SetExponent();\n  if( p < 0 ){\n    SetPrecision();\n  } else {\n    precision( p );\n  }\n}\n\n/**\n * @brief Construct using a RooRealVar instance\n */\nscientific::scientific( const RooRealVar* input, const int p ) :\n  _central( input->getVal() ),\n  _upper( fabs( input->getErrorHi() ) ),\n  _lower( fabs( input->getErrorLo() ) ),\n  _exp( 0 )\n{\n  SetExponent();\n  if( p < 0 ){\n    SetPrecision();\n  } else {\n    precision( p );\n  }\n}\n\n/**\n * @brief implementing the virtual function.\n *\n * The function attempts to use the simplest form to represent the uncertainty,\n * using as little latex symbols as possible.\n */\nstd::string\nscientific::str() const\n{\n  const std::string cen  = base::decimal( _central ).dupsetting( *this ).str();\n  const std::string up   = base::decimal( _upper ).dupsetting( *this ).str();\n  const std::string lo   = decimal( _lower ).dupsetting( *this ).str();\n  const std::string base =\n    ( up == lo && _upper == 0 ) ? cen :\n    ( up == lo )                ? usr::fstr( \"%s\\\\pm%s\", cen, up ) :\n    usr::fstr( \"%s^{+%s}_{-%s}\", cen, up, lo );\n\n  const std::string ans =\n    ( _exp == 0 )               ? base :\n    ( up == lo && _upper != 0 ) ? usr::fstr( \"(%s)\\\\times10^{%d}\", base, _exp ) :\n    usr::fstr( \"%s\\\\times10^{%d}\", base, _exp );\n\n  return ans;\n}\n\n/**\n * @brief overloading base implementation to allow for precision autodetection\n *        with a negative input.\n */\nscientific&\nscientific::precision( const int i )\n{\n  if( i < 0 && ( _upper != 0 || _lower != 0 ) ){\n    SetPrecision();\n  } else {\n    base::format::precision( abs( i ) );\n  }\n  return *this;\n}\n\n/**\n * @brief reducing/magnifying the central value and uncertainties by a common\n *        exponent value.\n *\n * If the central value is none-zero, then extracting the exponent of the\n * central value such that \\f$1 < |\\mathrm{central}_\\mathrm{man}| < 10\\f$;\n * If the central value is zero, then the exponent is determined by the\n * larger of the uncertainties, if it is non-zero.\n * If everything is zero, then the exponent is not set.\n */\nvoid\nscientific::SetExponent()\n{\n  if( _central != 0 ){\n    _exp      = GetExponent( _central );\n    _central /= IntPower( 10, _exp );\n    _upper   /= IntPower( 10, _exp );\n    _lower   /= IntPower( 10, _exp );\n  } else if( _upper != 0 || _lower != 0  ){\n    _exp      = std::max( GetExponent( _upper ), GetExponent( _lower ) );\n    _central /= IntPower( 10, _exp );\n    _upper   /= IntPower( 10, _exp );\n    _lower   /= IntPower( 10, _exp );\n  }\n}\n\n/**\n * @brief automatically determining the precision to use.\n *\n * If the central value is smaller than the larger uncertainty, then at most\n * the precision is 1 (if the uncertainty after the exponent has been factored\n * out smaller than 10).\n * if the central value is larger than the larger uncertainty, the precision\n * is set such that two significant digits of the larger uncertainty is\n * displayed.\n */\nvoid\nscientific::SetPrecision()\n{\n  double op_unc = std::max( _upper, _lower );\n  if( op_unc > _central ){\n    if( op_unc < 10 ){\n      _precision = 1;\n    } else {\n      _precision = 0;\n    }\n  } else {\n    _precision = 1;\n\n    while( op_unc < 1 && op_unc > 0 ){\n      _precision++;\n      op_unc *= 10;\n    }\n  }\n}\n\n}/* fmt */\n\n\n/**\n * @brief template specialization for a json file parsing.\n *\n * reading a list of doubles with 1-3 parameters as a measurement class.\n * * If only an empty list exists at the address, then the unit measurement\n *   (1+-0), * is returned.\n * * If only the list is only a single double long, a measurement with no\n *   uncertainty is returned.\n * * If only two double exist, then a measurement with symmetric uncertainty is\n *   returned. (x[0] +- x[1])\n * * If more than three doubles exists, then the first three doubles will be\n *   used to construct a measurement with asymmetric uncertainty:\n *   (x[0] +x[1] -x[2] )\n */\ntemplate<>\nvoid\nExceptJSONEntry<Measurement>( const JSONMap&     map,\n                              const std::string& index )\n{\n  ExceptJSONList( map, index );\n}\n\ntemplate<>\nMeasurement\nJSONEntry<Measurement>( const JSONMap&     map,\n                        const std::string& index )\n{\n  const auto array = JSONList<double>( map, index );\n  if( array.size() == 0 ){\n    throw std::invalid_argument( \"Array for usr::Measurement cannot be empty\" );\n  } else if( array.size() == 1 ){\n    return usr::Measurement( array.at( 0 ), 0, 0 );\n  } else if( array.size() == 2 ){\n    return usr::Measurement( array.at( 0 ), array.at( 1 ), array.at( 1 ) );\n  } else {\n    return usr::Measurement( array.at( 0 ), array.at( 1 ), array.at( 2 ) );\n  }\n}\n\ntemplate<>\nMeasurement\nJSONEntry<Measurement>( const JSONMap&     map,\n                        const std::string& index,\n                        const Measurement& def  )\n{\n  if( map.HasMember( index.c_str() ) ){\n    return JSONEntry<Measurement>( map, index );\n  } else {\n    return def;\n  }\n}\n\n\n}/* usr */\n", "meta": {"hexsha": "b6fc027d644970f92a806d7a0d25ff8e7b158d0e", "size": 9602, "ext": "cc", "lang": "C++", "max_stars_repo_path": "MathUtils/src/Measurement_Format.cc", "max_stars_repo_name": "yimuchen/UserUtils", "max_stars_repo_head_hexsha": "1a5c55d286f325424f4cfd23f22da63cfa6fb6a9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "MathUtils/src/Measurement_Format.cc", "max_issues_repo_name": "yimuchen/UserUtils", "max_issues_repo_head_hexsha": "1a5c55d286f325424f4cfd23f22da63cfa6fb6a9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-12-10T15:04:04.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-10T18:56:53.000Z", "max_forks_repo_path": "MathUtils/src/Measurement_Format.cc", "max_forks_repo_name": "yimuchen/UserUtils", "max_forks_repo_head_hexsha": "1a5c55d286f325424f4cfd23f22da63cfa6fb6a9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-06-05T14:08:08.000Z", "max_forks_repo_forks_event_max_datetime": "2018-06-05T14:08:08.000Z", "avg_line_length": 26.0923913043, "max_line_length": 81, "alphanum_fraction": 0.6200791502, "num_tokens": 2551, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5389832354982645, "lm_q2_score": 0.5583269943353744, "lm_q1q2_score": 0.3009288898729013}}
{"text": "#include <math.h>\n#include <Eigen/Core>\n#include <algorithm>\n#include <functional>\n\n#include \"crf_op.h\"\n\nnamespace caffe2 {\n\nnamespace {\n\ntemplate <typename T>\nvoid bilinear_interpolation(const float* input, float* output,\n                            const int batch_size, const int num_channels,\n                            const int input_height, const int input_width,\n                            const int output_height, const int output_width) {\n  int channels = num_channels * batch_size;\n\n  const float rheight = (output_height > 1)\n                            ? (float)(input_height - 1) / (output_height - 1)\n                            : 0.f;\n  const float rwidth =\n      (output_width > 1) ? (float)(input_width - 1) / (output_width - 1) : 0.f;\n  for (int h2 = 0; h2 < output_height; ++h2) {\n    const float h1r = rheight * h2;\n    const int h1 = h1r;\n    const int h1p = (h1 < input_height - 1) ? 1 : 0;\n    const float h1lambda = h1r - h1;\n    const float h0lambda = (float)1. - h1lambda;\n    for (int w2 = 0; w2 < output_width; ++w2) {\n      const float w1r = rwidth * w2;\n      const int w1 = w1r;\n      const int w1p = (w1 < input_width - 1) ? 1 : 0;\n      const float w1lambda = w1r - w1;\n      const float w0lambda = (float)1. - w1lambda;\n      const float* Xdata = &input[h1 * input_width + w1];\n      float* Ydata = &output[h2 * output_width + w2];\n      for (int c = 0; c < channels; ++c) {\n        Ydata[0] = h0lambda * (w0lambda * Xdata[0] + w1lambda * Xdata[w1p]) +\n                   h1lambda * (w0lambda * Xdata[h1p * input_width] +\n                               w1lambda * Xdata[h1p * input_width + w1p]);\n        Xdata += input_width * input_height;\n        Ydata += output_width * output_height;\n      }\n    }\n  }\n}\n\ntemplate <typename T>\nvoid image_process(const float* input, unsigned char* output,\n                   const int batch_size, const int height, const int width) {\n  // TODO(YH): add argument\n  float mean[] = {102.9801, 115.9465, 122.7717};\n  for (int b = 0; b < batch_size; b++) {\n    for (int c = 0; c < 3; c++) {\n      for (int h = 0; h < height; h++) {\n        for (int w = 0; w < width; w++) {\n          int idx_i = ((b * 3 + c) * height + h) * width + w;\n          int idx_o = ((b * height + h) * width + w) * 3 + c;\n          output[idx_o] = (unsigned char)(input[idx_i] + mean[c]);\n        }\n      }\n    }\n  }\n}\n\ntemplate <typename T>\nvoid unary_process(const float* input, float* output, const int batch_size,\n                   const int num_classes, const int height, const int width) {\n  const float min_prob = 0.0001;\n  for (int b = 0; b < batch_size; b++) {\n    for (int c = 0; c < num_classes; c++) {\n      for (int h = 0; h < height; h++) {\n        for (int w = 0; w < width; w++) {\n          int idx_i = ((b * num_classes + c) * height + h) * width + w;\n          int idx_o = ((b * height + h) * width + w) * num_classes + c;\n          output[idx_o] = std::max(input[idx_i], min_prob);\n          // output[idx_o] = -1. * std::max(input[idx_i], min_prob);\n          // output[idx_o] = -1. * input[idx_i];\n        }\n      }\n    }\n  }\n}\n\ntemplate <typename T>\nvoid result_process(const float* input, float* output, const int batch_size,\n                    const int num_classes, const int height, const int width) {\n  const float min_prob = 0.0001;\n\n  Tensor N(caffe2::CPU);\n  N.Resize(batch_size, height, width);\n  float* Nmdata = N.mutable_data<float>();\n\n  for (int b = 0; b < batch_size; b++) {\n    for (int h = 0; h < height; h++) {\n      for (int w = 0; w < width; w++) {\n        Nmdata[0] = 0;\n        for (int c = 0; c < num_classes; c++) {\n          int idx_i = ((b * height + h) * width + w) * num_classes + c;\n          int idx_o = ((b * num_classes + c) * height + h) * width + w;\n          output[idx_o] = std::max(input[idx_i], min_prob);\n          Nmdata[0] += output[idx_o];\n        }\n        Nmdata += 1;\n      }\n    }\n  }\n\n  const float* Ndata = N.data<float>();\n\n  for (int b = 0; b < batch_size; b++) {\n    for (int c = 0; c < num_classes; c++) {\n      for (int h = 0; h < height; h++) {\n        for (int w = 0; w < width; w++) {\n          int idx_o = ((b * num_classes + c) * height + h) * width + w;\n          float norm = *(Ndata + (b * height + h) * width + w);\n          // output[idx_o] = log(output[idx_o] / norm);\n          output[idx_o] = output[idx_o] / norm;\n        }\n      }\n    }\n  }\n}\n\n}  // namespace\n\ntemplate <>\nint DenseCRFOp<float, CPUContext>::npixels() {\n  return W * H;\n}\n\ntemplate <>\nint DenseCRFOp<float, CPUContext>::nlabels() {\n  return m_nlabels;\n}\n\ntemplate <>\nvoid DenseCRFOp<float, CPUContext>::add_pairwise_energy(\n    float w1, float theta_alpha_1, float theta_alpha_2, float theta_betta_1,\n    float theta_betta_2, float theta_betta_3, float w2, float theta_gamma_1,\n    float theta_gamma_2, const unsigned char* im) {\n  m_crf->addPairwiseGaussian(theta_gamma_1, theta_gamma_2,\n                             new PottsCompatibility(w2));\n  m_crf->addPairwiseBilateral(theta_alpha_1, theta_alpha_2, theta_betta_1,\n                              theta_betta_2, theta_betta_3, im,\n                              new PottsCompatibility(w1));\n  // m_crf->addPairwiseGaussian(3, 3, new PottsCompatibility(3));\n  // m_crf->addPairwiseBilateral(80, 80, 13, 13, 13, im,\n  // new PottsCompatibility(10));\n}\n\ntemplate <>\nvoid DenseCRFOp<float, CPUContext>::set_unary_energy(\n    const float* unary_costs_ptr) {\n  m_crf->setUnaryEnergy(\n      Eigen::Map<const Eigen::MatrixXf>(unary_costs_ptr, m_nlabels, W * H));\n}\n\ntemplate <>\nvoid DenseCRFOp<float, CPUContext>::map(int n_iters, int* labels) {\n  VectorXs labels_vec = m_crf->map(n_iters);\n  for (int i = 0; i < (W * H); ++i) labels[i] = labels_vec(i);\n}\n\ntemplate <>\nvoid DenseCRFOp<float, CPUContext>::inference(int n_iters, float* probs_out) {\n  MatrixXf probs = m_crf->inference(n_iters);\n  for (int i = 0; i < npixels(); ++i)\n    for (int j = 0; j < nlabels(); ++j)\n      probs_out[i * nlabels() + j] = probs(j, i);\n}\n\ntemplate <>\nvoid DenseCRFOp<float, CPUContext>::dense_crf(const unsigned char* image,\n                                              const float* unary,\n                                              float* probs_out) {\n  // set unary potentials\n  set_unary_energy(unary);\n\n  // set pairwise potentials\n  // add_pairwise_energy(10, 80 / scale_factor_, 80 / scale_factor_,\n  // color_factor_, color_factor_, color_factor_, 3, 3 / scale_factor_, 3 /\n  // scale_factor_, image);\n  add_pairwise_energy(BI_W, BI_X_STD / scale_factor_, BI_Y_STD / scale_factor_,\n                      BI_R_STD, BI_G_STD, BI_B_STD, POS_W,\n                      POS_X_STD / scale_factor_, POS_Y_STD / scale_factor_,\n                      image);\n\n  // run inference\n  inference(max_iter_, probs_out);\n}\n\ntemplate <>\nbool DenseCRFOp<float, CPUContext>::RunOnDevice() {\n  const auto& U = Input(0);\n  const auto& I = Input(1);\n\n  CAFFE_ENFORCE_EQ(U.dim(), 4);\n  CAFFE_ENFORCE_EQ(I.dim(), 4);\n  CAFFE_ENFORCE_EQ(U.dim32(0), I.dim32(0));\n  CAFFE_ENFORCE_EQ(I.dim32(1), 3);\n\n  const int batch_size = U.dim32(0);\n  const int num_classes = U.dim32(1);\n  const int height = U.dim32(2);\n  const int width = U.dim32(3);\n  const int height_im = I.dim32(2);\n  const int width_im = I.dim32(3);\n  H = height;\n  W = width;\n  m_nlabels = num_classes;\n\n  m_crf = new DenseCRF2D(W, H, m_nlabels);\n\n  auto* M = Output(0);\n  M->Resize(batch_size, num_classes, height, width);\n\n  Tensor MT(caffe2::CPU);\n  MT.Resize(batch_size, height, width, num_classes);\n\n  Tensor IT(caffe2::CPU);\n  IT.Resize(batch_size, height, width, 3);\n\n  if (height != height_im || width != width_im) {\n    Tensor IB(caffe2::CPU);\n    IB.Resize(batch_size, 3, height, width);\n    bilinear_interpolation<float>(I.data<float>(), IB.mutable_data<float>(),\n                                  batch_size, 3, height_im, width_im, height,\n                                  width);\n\n    image_process<float>(IB.data<float>(), IT.mutable_data<unsigned char>(),\n                         batch_size, height, width);\n  } else {\n    image_process<float>(I.data<float>(), IT.mutable_data<unsigned char>(),\n                         batch_size, height, width);\n  }\n\n  Tensor UT(caffe2::CPU);\n  UT.Resize(batch_size, height, width, num_classes);\n  unary_process<float>(U.data<float>(), UT.mutable_data<float>(), batch_size,\n                       num_classes, height, width);\n\n  for (int b = 0; b < batch_size; b++) {\n    const unsigned char* image =\n        IT.data<unsigned char>() + b * height * width * 3;\n    const float* unary = UT.data<float>() + b * height * width * num_classes;\n    float* probs_out =\n        MT.mutable_data<float>() + b * height * width * num_classes;\n\n    // auto adjust scale_factor_\n    scale_factor_ = 1.0 * SIZE_STD / std::max(height, width);\n\n    dense_crf(image, unary, probs_out);\n  }\n\n  result_process<float>(MT.data<float>(), M->mutable_data<float>(), batch_size,\n                        num_classes, height, width);\n\n  delete m_crf;\n  return true;\n}\n\nREGISTER_CPU_OPERATOR(DenseCRF, DenseCRFOp<float, CPUContext>);\n\nnamespace {}  // namespace\n\nusing namespace std::placeholders;\n\nOPERATOR_SCHEMA(DenseCRF)\n    .NumInputs(2)\n    .NumOutputs(1)\n    .SetDoc(R\"DOC(\n)DOC\")\n    .Arg(\"max_iter\", \"(int) default to 0\")\n    .Arg(\"debug_info\", \"(bool) default to false\")\n    .Input(0, \"U\", \"input tensor of size (BxCxH1xW1)\")\n    .Input(1, \"I\", \"input tensor of size (Bx3xH2xW2)\")\n    .Output(0, \"M\", \"output tensor of size (BxCxH1xW1)\");\n\nnamespace {\n\nNO_GRADIENT(DenseCRF);\n\n}  // namespace\n\n}  // namespace caffe2\n", "meta": {"hexsha": "580181e97ce2bebffe708f31f302d82e0752f6f9", "size": 9529, "ext": "cc", "lang": "C++", "max_stars_repo_path": "detectron/ops/crf_op.cc", "max_stars_repo_name": "zhiweichen95/DRNet", "max_stars_repo_head_hexsha": "996fe088a3615028359bd8cceb4037719f3dcd74", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 23.0, "max_stars_repo_stars_event_min_datetime": "2020-03-30T11:48:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-11T06:34:31.000Z", "max_issues_repo_path": "detectron/ops/crf_op.cc", "max_issues_repo_name": "zhiweichen95/DRNet", "max_issues_repo_head_hexsha": "996fe088a3615028359bd8cceb4037719f3dcd74", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 9.0, "max_issues_repo_issues_event_min_datetime": "2020-09-28T07:15:16.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-25T08:11:06.000Z", "max_forks_repo_path": "detectron/ops/crf_op.cc", "max_forks_repo_name": "zhiweichen95/DRNet", "max_forks_repo_head_hexsha": "996fe088a3615028359bd8cceb4037719f3dcd74", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2020-03-30T11:48:34.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-02T06:12:36.000Z", "avg_line_length": 33.0868055556, "max_line_length": 79, "alphanum_fraction": 0.5844264876, "num_tokens": 2790, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7122321842389469, "lm_q2_score": 0.42250463481418826, "lm_q1q2_score": 0.3009213989047879}}
{"text": "/**\n *  sim_onlineca_multi.cpp\n *\n *  Simulate the LTL motion planning with collision avoidance\n *  with multiple moving obstacles.\n *\n *  Created by Yinan Li on Feb. 27, 2021.\n *  Hybrid Systems Group, University of Waterloo.\n */\n\n\n#include <iostream>\n#include <fstream>\n#include <sstream>\n#include <string>\n#include <algorithm>\n#include <utility>\n#include <cmath>\n#include <sys/stat.h>\n#include <boost/numeric/odeint.hpp>\n#include <cstdlib>\n#include <ctime>\n\n#include \"src/grid.h\"\n#include \"src/definitions.h\"\n#include \"src/abstraction.hpp\"\n#include \"src/DBAparser.h\"\n#include \"src/bsolver.hpp\"\n#include \"src/patcher.h\"\n#include \"src/hdf5io.h\"\n\n#include \"car.hpp\"\n#include \"odes.hpp\"\n\n\nint main(int argc, char *argv[])\n{\n    std::string specfile, ctlrfile, cafile, graphfile;\n    specfile = \"dba1.txt\";\n    ctlrfile = \"controller_dba1_0.2-0.2-0.2.h5\";\n    graphfile = \"gwin.h5\";\n    const double eta[] = {0.2, 0.2, 0.2};\n\n    cafile = \"controller_safety_abst-0.8-0.9-0.1-0.1.h5\";\n    const double eta_r[] = {0.1, 0.1, 0.1};\n\n    /* Input arguments:\n     * ./simMulti dbafile ctlrfile cafile graphfile eta[0] eta_r[0]\n     */\n    if(argc!=1) {\n\tif(argc==7) {\n\t    specfile = std::string(argv[1]);\n\t    ctlrfile = std::string(argv[2]);\n\t    cafile = std::string(argv[3]);\n\t    graphfile = std::string(argv[4]);\n\t    eta[0] = std::atof(argv[5]);\n\t    eta[1] = std::atof(argv[5]);\n\t    eta[2] = std::atof(argv[5]);\n\t    eta_r[0] = std::atof(argv[6]);\n\t    eta_r[1] = std::atof(argv[6]);\n\t    eta_r[2] = std::atof(argv[6]);\n\t} else {\n\t    std::cout << \"Improper number of arguments.\\n\";\n\t    std::exit(1);\n\t}\n    }\n    std::cout << \"Simulate \" << specfile << \" with controller \" << ctlrfile << '\\n';\n\n\n    /**\n     * Setup the motion planning workspace\n     **/\n    const int x_dim = 3;\n    const double theta = 3.5;\n    const double xlb[] = {0, 0, -theta};\n    const double xub[] = {10, 10, theta};\n    /* set the control values */\n    const int u_dim = 2;\n    const double ulb[] = {-1.0, -1.0};\n    double uub[] = {1.0, 1.0};\n    /* discretization precision */\n    double mu[] = {0.3, 0.3};\n    /* generate grid */\n    rocs::grid x_grid(x_dim,eta,xlb,xub);\n    x_grid.gridding();\n    rocs::grid u_grid(u_dim,mu,ulb,uub);\n    std::cout << \"Number of discrete states: \" << x_grid._nv << \"\\n\";\n    std::cout << \"Number of discrete inputs: \" << u_grid._nv << \"\\n\";\n\n    clock_t tb, te;\n\n\n    /**\n     * Load specification\n     **/\n    std::cout << \"\\nReading the specification...\\n\";\n    rocs::UintSmall nAP = 0, nNodes = 0, q0 = 0;\n    std::vector<rocs::UintSmall> acc;\n    std::vector<std::vector<rocs::UintSmall>> arrayM;\n    if (!rocs::read_spec(specfile, nNodes, nAP, q0, arrayM, acc))\n\tstd::exit(1);\n    boost::dynamic_bitset<> isacc(nNodes, false);\n    for (rocs::UintSmall i = 0; i < acc.size(); ++i)\n\tisacc[acc[i]] = true;\n\n\n    /**\n     * Load global controller\n     **/\n    std::cout << \"\\nLoading global controller...\\n\";\n    std::vector<long long> w_x0, encode3;\n    std::vector<NODE_POST> nts_ctrlr;\n    std::vector<CTRL> ctrl;\n    std::vector<int> q_prime;\n    rocs::h5FileHandler planRdr(ctlrfile, H5F_ACC_RDONLY);\n    planRdr.read_discrete_controller(w_x0, encode3, nts_ctrlr, ctrl, q_prime);\n\n\n    /**\n     * Load local safety controller\n     **/\n    std::cout << \"\\nLoading local safety controller...\\n\";\n    rocs::h5FileHandler reader(cafile, H5F_ACC_RDONLY);\n    std::vector<size_t> optCtlr;\n    std::vector<double> value;\n    boost::dynamic_bitset<> safeCtlr;\n    boost::dynamic_bitset<> win;\n    size_t cdims[2];\n    reader.read_discrete_controller(win, safeCtlr, cdims, optCtlr, value);\n    double xrlb[] = {-3, -3, -theta};\n    double xrub[] = {3, 3, theta};\n    rocs::grid rel_grid(3, eta_r, xrlb, xrub);\n    rel_grid.gridding();\n\n\n\n    /**\n     * Launch patcher\n     **/\n    rocs::Patcher local;\n    struct stat buffer;\n    if(stat(graphfile.c_str(), &buffer) == 0) {\n    \t/* Read from a file */\n    \tstd::cout << \"\\nReading winning graph...\\n\";\n    \trocs::h5FileHandler graphRdr(graphfile, H5F_ACC_RDONLY);\n    \ttb = clock();\n    \tgraphRdr.read_winning_graph(local);\n    \tte = clock();\n    \tstd::cout << \"Time of reading graph: \" << (float)(te - tb)/CLOCKS_PER_SEC << '\\n';\n    } else {\n    \tstd::cout << \"Graph file doesn't exist.\\n\";\n    \treturn 1;\n    }\n    int horizon = 3;  //set forward propagation horizon\n\n\n\n    /**\n     * Simulation\n     **/\n    const double drange[] = {3.0, 3.0};\n    /* set ode solver */\n    const double tsim = 0.1; //simulation time\n    const double dt = 0.001; //integration step size for odeint\n    boost::numeric::odeint::runge_kutta_cash_karp54<rocs::Rn> rk45;\n    boost::dynamic_bitset<> u_safe(cdims[1]);\n\n    /* Initial condition of the ego robot */\n    rocs::Rn x{1, 1, M_PI/3.0};\n    rocs::Rn u{0, 0};\n    long long x_index = x_grid.val_to_id(x);\n    std::vector<long long>::iterator p1;\n    p1 = std::lower_bound(w_x0.begin(), w_x0.end(), x_index);\n    if(*p1 != x_index) {\n\tstd::cout << x[0] <<  \" \"  << x[1] << \" \" << x[2];\n\tstd::cout << \" is not in the winning set, change a new initial state.\" << std::endl;\n\treturn 1;\n    }\n    /* Initial condition of 3 obstacles */\n    rocs::Rn uomax{0.8, 0.8};\n    rocs::Rn uomin{-0.8, -0.8};\n    double v;\n    \n    /* State in local relative coordinate */\n    rocs::Rn xr1{0,0,0};\n    rocs::Rn xr2{0,0,0};\n    rocs::Rn xr3{0,0,0};\n    long long xr_id1, xr_id2, xr_id3;\n\n    /* obstacle 1 */\n    rocs::Rn xo1{3.0, 10.0, -1.5};\n    rocs::Rn uo1{0.1, 0.0};\n    auto obstacle_behavior1 = [&uo1, tsim](int j) {\n\t\t\t\t  double t = tsim*j;\n\t\t\t\t  if(t >= 0) {\n\t\t\t\t      uo1[0] = 0.2;\n\t\t\t\t      uo1[1] = 0.0;\n\t\t\t\t  }\n\t\t\t      };\n    \n\n    /* obstacle 2 */\n    rocs::Rn xo2{5.3, 0.0, 2.0};\n    rocs::Rn uo2{0.5, 0.0};\n    auto obstacle_behavior2 = [&uo2, tsim](int j) {\n\t\t\t\t  double t = tsim*j;\n\t\t\t\t  if(t >= 0) {\n\t\t\t\t      if(t < 14) {\n\t\t\t\t\t  uo2[0] = 0.5;\n\t\t\t\t\t  uo2[1] = 0.0;\n\t\t\t\t      } else {\n\t\t\t\t\t  uo2[0] = 0.5;\n\t\t\t\t\t  uo2[1] = 0.6;\n\t\t\t\t      }\n\t\t\t\t  }\n\t\t\t      };\n\n    /* obstacle 3 */\n    rocs::Rn xo3{10.0, 6.4, M_PI};\n    rocs::Rn uo3{0.15, 0.0};\n    auto obstacle_behavior3 = [&uo3, tsim](int j) {\n\t\t\t\t  double t = tsim*j;\n\t\t\t\t  if(t >= 0) {\n\t\t\t\t      if(t < 31) {\n\t\t\t\t\t  uo3[0] = 0.2;\n\t\t\t\t\t  uo3[1] = 0.0;\n\t\t\t\t      } else if(t < 35) {\n\t\t\t\t\t  uo3[0] = 0.2;\n\t\t\t\t\t  uo3[1] = 0.3;\n\t\t\t\t      } else {\n\t\t\t\t\t  uo3[0] = 0.2;\n\t\t\t\t\t  uo3[1] = 0.0;\n\t\t\t\t      }\n\t\t\t\t  }\n\t\t\t      };\n\n\n    /* Open files for writing results and logs */\n    std::string simfile = \"traj_closedloop_ca_4.txt\";\n    std::ofstream ctlrWtr(simfile);\n    if(!ctlrWtr.is_open())\n\tctlrWtr.open(simfile, std::ios::out);\n    std::string simother1 = \"traj_other_robot_4_1.txt\";\n    std::string simother2 = \"traj_other_robot_4_2.txt\";\n    std::string simother3 = \"traj_other_robot_4_3.txt\";\n    std::ofstream otherWtr1(simother1);\n    std::ofstream otherWtr2(simother2);\n    std::ofstream otherWtr3(simother3);\n    if(!otherWtr1.is_open())\n    \totherWtr1.open(simother1, std::ios::out);\n    if(!otherWtr2.is_open())\n    \totherWtr2.open(simother2, std::ios::out);\n    if(!otherWtr3.is_open())\n    \totherWtr3.open(simother3, std::ios::out);\n    /********** Logging **********/\n    std::ofstream logger;\n    logger.open(\"logs_4.txt\", std::ios::out);\n    /********** Logging **********/\n\n\n    /* Simulation loop */\n    srand(time(NULL));\n    float tpat = 0;\n    int max_num_achieve_acc=5, max_num_iteration=1500; //3000000;\n    rocs::UintSmall q;\n    int i, j;\n    double t0, tc; //record the time when an obstacle detected\n    bool o1, o2, o3;\n    o1 = false;\n    o2 = false;\n    o3 = false;\n    std::vector<CTRL>::iterator p7;\n    NODE_POST p5;\n    std::cout << \"\\nLaunching simulation...\\n\";\n    for(q = q0, i = j = 0; i<max_num_achieve_acc && j<max_num_iteration; ++j) {\n\t/* choose obstacle trajectory */\n\tobstacle_behavior1(j);\n\tobstacle_behavior2(j);\n\tobstacle_behavior3(j);\n\n\t/* Determine the control u by the product state (x_index, q) */\n\tp5 = nts_ctrlr[encode3[x_index]];\n\tp7 = std::lower_bound(ctrl.begin()+p5.pos, ctrl.begin()+p5.pos+p5.num_a,\n\t\t\t      q, [](const CTRL &item, const int val) {\n\t\t\t\t     return item.q < val;});\n\tif(p7->q != q) {\n\t    // std::cout << j << \"th iteration: \" << \"Reach accepting state \" << i << \" times.\\n\";\n\t    // std::cout << \"Automaton state: \" << q << '\\n';\n\t    // std::cout << \"Position in ctrl list: \" << p5.pos << \", number of actions: \" << p5.num_a << '\\n';\n\t    std::cout << \"Error in ctrl\" << std::endl;\n\t    break;\n\t}\n\tu_grid.id_to_val(u, p7->u);\n\n\t/* Print to screen */\n\tstd::cout << \"# \" << j << \":\\n\";\n\tstd::cout << \"x: [\" << x[0] <<  ','  << x[1] << ',' << x[2] << \"]\\n\";\n\tstd::cout << \"Nominal control: \" << p7->u << '('\n\t\t  << '[' << u[0] << ',' << u[1] << \"])\\n\";\n\tstd::cout << \"current dba state: \" << q << \"\\n\";\n\n\ttc = j*tsim; //record the current time\n\n\t/* Get the relative state xr */\n\txr1[0] = xo1[0]-x[0];\n\txr1[1] = xo1[1]-x[1];\n\txr1[2] = xo1[2]-x[2];\n\txr2[0] = xo2[0]-x[0];\n\txr2[1] = xo2[1]-x[1];\n\txr2[2] = xo2[2]-x[2];\n\txr3[0] = xo3[0]-x[0];\n\txr3[1] = xo3[1]-x[1];\n\txr3[2] = xo3[2]-x[2];\n\tif(xr1[2] > M_PI) //convert angle into [-pi, pi]\n\t    xr1[2] -= 2*M_PI;\n\tif(xr1[2] < -M_PI)\n\t    xr1[2] += 2*M_PI;\n\tif(xr2[2] > M_PI) //convert angle into [-pi, pi]\n\t    xr2[2] -= 2*M_PI;\n\tif(xr2[2] < -M_PI)\n\t    xr2[2] += 2*M_PI;\n\tif(xr3[2] > M_PI) //convert angle into [-pi, pi]\n\t    xr3[2] -= 2*M_PI;\n\tif(xr3[2] < -M_PI)\n\t    xr3[2] += 2*M_PI;\n\tinertia_to_body(xr1, x); //convert from the inertial to body frame\n\tinertia_to_body(xr2, x);\n\tinertia_to_body(xr3, x);\n\n\t/* Deal with obstacles */\n\tif(std::fabs(xr1[0])*std::fabs(xr1[0]) +\n\t   std::fabs(xr1[1])*std::fabs(xr1[1]) < drange[0]*drange[1]) {\n\t    o1 = true;\n\t    std::cout << \"Obstacle 1 detected.\\n\";\n\t    std::cout << \"Relative coordinate: \";\n\t    if(rel_grid._bds.isout(xr1)) { // xr is the out-of-domain node\n\t\tstd::cout << rel_grid._nv;\n\t    } else {\n\t\txr_id1 = rel_grid.val_to_id(xr1); //uniform grid rel_grid\n\t\tstd::cout << xr_id1;\n\t    }\n\t    std::cout << \"([\" << xr1[0] << ',' << xr1[1] << ',' << xr1[2] << \"])\\n\";\n\t} else {\n\t    o1 = false;\n\t}//end if obstacle is within range\n\n\tif(std::fabs(xr2[0])*std::fabs(xr2[0]) +\n\t   std::fabs(xr2[1])*std::fabs(xr2[1]) < drange[0]*drange[1]) {\n\t    o2 = true;\n\t    std::cout << \"Obstacle 2 detected.\\n\";\n\t    std::cout << \"Relative coordinate: \";\n\t    if(rel_grid._bds.isout(xr2)) { // xr is the out-of-domain node\n\t\tstd::cout << rel_grid._nv;\n\t    } else {\n\t\txr_id2 = rel_grid.val_to_id(xr2); //uniform grid rel_grid\n\t\tstd::cout << xr_id2;\n\t    }\n\t    std::cout << \"([\" << xr2[0] << ',' << xr2[1] << ',' << xr2[2] << \"])\\n\";\n\t} else {\n\t    o2 = false;\n\t}//end if obstacle is within range\n\n\tif(std::fabs(xr3[0])*std::fabs(xr3[0]) +\n\t   std::fabs(xr3[1])*std::fabs(xr3[1]) < drange[0]*drange[1]) {\n\t    o3 = true;\n\t    std::cout << \"Obstacle 3 detected.\\n\";\n\t    std::cout << \"Relative coordinate: \";\n\t    if(rel_grid._bds.isout(xr3)) { // xr is the out-of-domain node\n\t\tstd::cout << rel_grid._nv;\n\t    } else {\n\t\txr_id3 = rel_grid.val_to_id(xr3); //uniform grid rel_grid\n\t\tstd::cout << xr_id3;\n\t    }\n\t    std::cout << \"([\" << xr3[0] << ',' << xr3[1] << ',' << xr3[2] << \"])\\n\";\n\t} else {\n\t    o3 = false;\n\t}//end if obstacle is within range\n\n\t\n\t/* Perform RH (receding horizon) */\n\tif(o1||o2||o3) {\n\t    /********** Logging **********/\n\t    logger << tc << '(' << j << \"): \"\n\t       << x_index << '(' << x[0] << ',' << x[1] << ',' << x[2] << \"), \";\n\t    if(o1) {\n\t\tlogger << \"o1,\" << xr_id1 << '(' << xr1[0] << ',' << xr1[1] << ',' << xr1[2] << \"), \";\n\t\tfor(size_t k = 0; k < cdims[1]; ++k)\n\t\t    logger << safeCtlr[xr_id1*cdims[1]+k];\n\t\tlogger << '\\n';\n\t    }\n\t    if(o2) {\n\t\tlogger << \"o2,\" << xr_id2 << '(' << xr2[0] << ',' << xr2[1] << ',' << xr2[2]<< \"), \";\n\t\tfor(size_t k = 0; k < cdims[1]; ++k)\n\t\t    logger << safeCtlr[xr_id2*cdims[1]+k];\n\t\tlogger << '\\n';\n\t    }\n\t    if(o3) {\n\t\tlogger << \"o3,\" << xr_id3 << '(' << xr3[0] << ',' << xr3[1] << ',' << xr3[2] << \")\";\n\t\tfor(size_t k = 0; k < cdims[1]; ++k)\n\t\t    logger << safeCtlr[xr_id3*cdims[1]+k];\n\t\tlogger << '\\n';\n\t    }\n\t    std::cout << \"o1:\"<< o1 <<\", o2:\"<< o2 <<\", o3:\" << o3 <<'\\n';\n\t    // std::cout << \"Current state id of the robot:\" << xp << \", key:\" << key << '\\n';\n\t    /********** Logging **********/\n\t    \n\t    size_t xp = x_index*nNodes+q; // (idx,idq)=idx*nNodes+idq (buchi.c)\n\t    size_t uid;\n\t    \n\t    /********** Logging **********/\n\t    size_t row, key = local._encode[xp];\n\t    row = local._idmap[key];\n\t    // std::cout << \"id_n0n1: \" << xp << ',' << \" id_np: \" << key << '\\n';\n\t    for(size_t k = 0; k < u_grid._nv; ++k) {\n\t\tif(local._winfts._npost[row*local._na+k]) {//outdeg>0\n\t\t    logger << k << ' ';\n\t\t}\n\t    }\n\t    logger << \", \";\n\t    /********** Logging **********/\n\t    \n\t    /* Determine safe inputs for RH module */\n\t    std::cout << \"Use RH to find safe control inputs.\\n \";\n\t    u_safe.set();\n\t    int nSafeAct = 0;\n\t    rocs::Rn uu(u_dim);\n\t    double dtemp, u_dist=(uub[0]-ulb[0])*(uub[0]-ulb[0])+(uub[1]-ulb[1])*(uub[1]-ulb[1]);\n\t    for(size_t k = 0; k < cdims[1]; ++k) {\n\t\tif(o1)\n\t\t    u_safe[k] = u_safe[k] & safeCtlr[xr_id1*cdims[1]+k];\n\t\tif(o2)\n\t\t    u_safe[k] = u_safe[k] & safeCtlr[xr_id2*cdims[1]+k];\n\t\tif(o3)\n\t\t    u_safe[k] = u_safe[k] & safeCtlr[xr_id3*cdims[1]+k];\n\t\t\n\t\tif(u_safe[k]) {\n\t\t    /************* Logging **************/\n\t\t    // std::cout << k << ',';\n\t\t    // std::cout << \"Outdeg: \"\n\t\t    // \t      << local._winfts._npost[row*local._na+k]\n\t\t    // \t      << '\\n';\n\t\t    /************* Logging **************/\n\t\t    if(local._winfts._npost[row*local._na+k]) {//outdeg>0\n\t\t\t++nSafeAct; //count the # of safe valid controls\n\t\t\t/* take the closest to the original one */\n\t\t\tu_grid.id_to_val(uu, k);\n\t\t\tdtemp = (uu[0]-u[0])*(uu[0]-u[0])+(uu[1]-u[1])*(uu[1]-u[1]);\n\t\t\tif(dtemp < u_dist) {\n\t\t\t    uid = k;\n\t\t\t    u_dist= dtemp;\n\t\t\t}\n\t\t\t/************* Logging **************/\n\t\t\t// std::cout << \"Post nodes: \";\n\t\t\t// size_t pidstart=local._winfts._ptrpost[row*local._na+k];\n\t\t\t// for(size_t pid=pidstart; pid<pidstart+local._winfts._npost[row*local._na+k]; ++pid)\n\t\t\t//     std::cout << local._winfts._idpost[pid] << ' ';\n\t\t\t// std::cout << '\\n';\n\t\t\t/************* Logging **************/\n\t\t    }\n\t\t    // /************* Logging **************/\n\t\t    // logger << k << ' ';\n\t\t    // /************* Logging **************/\n\t\t}\n\t\t/********** Logging **********/\n\t\tlogger << u_safe[k];\n\t\t/********** Logging **********/\n\t    }\n\t    /********** Logging **********/\n\t    u_grid.id_to_val(uu, uid);\n\t    logger << '\\n'\n\t\t   << p7->u << ' ' << u[0] << ',' << u[1] << ';'\n\t\t   << uid << ' ' << uu[0] << ',' << uu[1] << ' ' << u_dist << ';';\n\t    /********** Logging **********/\n\n\t    /* Get a safe control from patcher */\n\t    if(u_safe[p7->u]) {\n\t\tstd::cout << \"The static strategy is safe.\\n\";\n\t\t// u_grid.id_to_val(u, uid);\n\t\tlogger << p7->u << ' ';\n\t    } else if(nSafeAct > 1) {\n\t\ttb = clock();\n\t\tint suc = local.solve_local_reachability(xp, horizon, u_safe);\n\t\tte = clock();\n\t\ttpat += (float)(te - tb)/CLOCKS_PER_SEC;\n\t\tstd::cout << \"Average time for RH: \"\n\t\t\t  << tpat/(j+1) << \".\\n\";\n\t\tif(!suc) {//if fails in re-planning, use the closest u\n\t\t    std::cout << \"Apply the safe control input closest to the original one.\\n\";\n\t\t    u_grid.id_to_val(u, uid);\n\t\t    logger << uid << ' ';\n\t\t} else {\n\t\t    std::cout << \"Apply controls returned by local reachability.\\n\";\n\t\t    u_grid.id_to_val(u, local._ctlr);\n\t\t    logger << local._ctlr << ' ';\n\t\t}\n\t    } else if(nSafeAct > 0) {\n\t\tstd::cout << \"Apply the only one safe control.\\n\";\n\t\tu_grid.id_to_val(u, uid);\n\t\tlogger << uid << ' ';\n\t    } else {\n\t\tstd::cout << \"No safe controls. Freeze.\\n\";\n\t\tu[0] = 0;\n\t\tu[1] = 0;\n\t\tlogger << p7->u << ' ';\n\t    }\n\t    /********** Logging **********/\n\t    logger << u[0] << ',' << u[1] << \"\\n\\n\";\n\t    /********** Logging **********/\n\t}//end RH\n\t\n\n\t/* Write to txt file */\n\t// ctlrWtr << j << ':';\n\tfor(int d = 0; d < x_dim; ++d) {\n\t    /* the controlled state */\n\t    ctlrWtr << x[d];\n\t    /* the state of the other robot */\n\t    otherWtr1 << xo1[d];\n\t    otherWtr2 << xo2[d];\n\t    otherWtr3 << xo3[d];\n\t    if(d<x_dim-1) {\n\t\tctlrWtr << ',';\n\t\totherWtr1 << ',';\n\t\totherWtr2 << ',';\n\t\totherWtr3 << ',';\n\t    }\n\t}\n\tctlrWtr << ';';\n\totherWtr1 << ';';\n\totherWtr2 << ';';\n\totherWtr3 << ';';\n\tfor(int d = 0; d < u_dim; ++d) {\n\t    ctlrWtr << u[d];\n\t    otherWtr1 << uo1[d];\n\t    otherWtr2 << uo2[d];\n\t    otherWtr3 << uo3[d];\n\t    if(d<u_dim-1) {\n\t\tctlrWtr << ',';\n\t\totherWtr1 << ',';\n\t\totherWtr2 << ',';\n\t\totherWtr3 << ',';\n\t    }\n\t}\n\tctlrWtr << '\\n';\n\totherWtr1 << '\\n';\n\totherWtr2 << '\\n';\n\totherWtr3 << '\\n';\n\n\t/* Integrate ego robot trajectory */\n\tboost::numeric::odeint::integrate_const(rk45, car_dynamics(u), x, 0.0, tsim, dt);\n\tif(x[2] > M_PI) //convert angle into [-pi, pi]\n\t    x[2] -= 2*M_PI;\n\tif(x[2] < -M_PI)\n\t    x[2] += 2*M_PI;\n\n\t/* integrate obstacle trajectory after it appears */\n\tboost::numeric::odeint::integrate_const(rk45, car_dynamics(uo1), xo1, 0.0, tsim, dt);\n\tif(xo1[2] > M_PI) //convert angle into [-pi, pi]\n\t    xo1[2] -= 2*M_PI;\n\tif(xo1[2] < -M_PI)\n\t    xo1[2] += 2*M_PI;\n\tboost::numeric::odeint::integrate_const(rk45, car_dynamics(uo2), xo2, 0.0, tsim, dt);\n\tif(xo2[2] > M_PI) //convert angle into [-pi, pi]\n\t    xo2[2] -= 2*M_PI;\n\tif(xo2[2] < -M_PI)\n\t    xo2[2] += 2*M_PI;\n\tboost::numeric::odeint::integrate_const(rk45, car_dynamics(uo3), xo3, 0.0, tsim, dt);\n\tif(xo3[2] > M_PI) //convert angle into [-pi, pi]\n\t    xo3[2] -= 2*M_PI;\n\tif(xo3[2] < -M_PI)\n\t    xo3[2] += 2*M_PI;\n\n\t/* Update automaton state q */\n\tx_index = x_grid.val_to_id(x);\n\tq = q_prime[p5.label*nNodes + q];\n\tif(isacc[q])\n\t    std::cout << \"******** achieve acc \\'\" << q << \"\\' \" << ++i << \" time ********\" << std::endl;\n    }\n\n    ctlrWtr.close();\n    otherWtr1.close();\n    otherWtr2.close();\n    otherWtr3.close();\n    logger.close();\n\n    return 0;\n}\n", "meta": {"hexsha": "b12d6d525f5cde5d0a8a80d50c85cdfcb27db8d1", "size": 17780, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/collision-avoid/sim_onlineca_multi.cpp", "max_stars_repo_name": "yinanl/rocs", "max_stars_repo_head_hexsha": "bf2483903e39f4c0ea254a9ef56720a1259955ad", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/collision-avoid/sim_onlineca_multi.cpp", "max_issues_repo_name": "yinanl/rocs", "max_issues_repo_head_hexsha": "bf2483903e39f4c0ea254a9ef56720a1259955ad", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/collision-avoid/sim_onlineca_multi.cpp", "max_forks_repo_name": "yinanl/rocs", "max_forks_repo_head_hexsha": "bf2483903e39f4c0ea254a9ef56720a1259955ad", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.2380952381, "max_line_length": 104, "alphanum_fraction": 0.5242969629, "num_tokens": 6321, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6113819874558603, "lm_q2_score": 0.49218813572079556, "lm_q1q2_score": 0.30091496061917467}}
{"text": "#include <unordered_map>\n#include <iostream>\n#include <string>\nusing std::string;\n\n#include <boost/log/utility/setup/console.hpp>\n#include <boost/log/trivial.hpp>\n\n#include \"streamTrace.hpp\"\n#include \"navigation.hpp\"\n#include \"constants.hpp\"\n#include \"station.hpp\"\n#include \"antenna.hpp\"\n#include \"satSys.hpp\"\n#include \"tides.hpp\"\n#include \"rinex.hpp\"\n#include \"gTime.hpp\"\n\n#define J2_GLO   1.0826257E-3     /* 2nd zonal harmonic of geopot   ref [2] */\n\n#define OMGE_GLO 7.292115E-5      /* earth angular velocity (rad/s) ref [2] */\n#define OMGE_GAL 7.2921151467E-5  /* earth angular velocity (rad/s) ref [7] */\n#define OMGE_CMP 7.292115E-5      /* earth angular velocity (rad/s) ref [9] */\n\n#define RTOL_KEPLER \t1E-14         /* relative tolerance for Kepler equation */\n#define MAX_ITER_KEPLER 30        /* max number of iteration of Kelpler */\n#define GLOSTEP   \t\t60.0\n\n#define SIN_5 -0.0871557427476582 /* sin(-5.0 deg) */\n#define COS_5  0.9961946980917456 /* cos(-5.0 deg) */\n\nnav_t\tnav = {};\nstring\t\t\tGNSSinp=\"GE\";\nmap<SatSys,int> BS_Satel_List;\nint \t\t\tBS_Start_Week\t\t= 0;\ndouble\t\t\tBS_Start_TOW\t\t= 0.0;\ndouble\t\t\tBS_Start_Epoc[6]\t= {0};\nint \t\t\tBS_Epoch_Num\t\t= 0;\ndouble\t\t\tBS_Epoch_Inter\t\t= 900.0;\nmap<E_Sys,double> BS_Max_Dtime;\n\nvoid helpstring(void)\n{\n\tfprintf(stdout, \" brdc2sp3 -ant <ATX file> -inp <RINEX NAV file> [options]\\n\");\n\tfprintf(stdout, \" Options [default]:\\n\");\n\tfprintf(stdout, \"     -gns string   GNSS to be processed: G: GPS, R:GLONASS, E:Galileo, C: Beidou, J: QZSS, A: all [GE]\\n\");\n\tfprintf(stdout, \"     -int float    Time spacing of SP3 entries [900.0]\\n\");\n\tfprintf(stdout, \"     -out string   File name for SP3 output [BS_orbits.sp3]\\n\");\n\tfprintf(stdout, \"     -*dt max_dt   set max_dt for constellation (*: 'G','R','E','J' or 'C') [86400.0]\\n\");\n\tfprintf(stdout, \"     -clst         Select ephemeris with closest Toe (within max_dt seconds) [Latest valid ephemeris]\\n\");\n\tfprintf(stdout, \"     -inav         I/NAV only for Galileo [use both F/NAV and I/NAV]\\n\");\n\tfprintf(stdout, \"     -fnav         F/NAV only for Galileo [use both F/NAV and I/NAV]\\n\");\n\tfprintf(stdout, \"     -frst         Filter out satellites with no/bad data in first epoc [not filtered]\\n\");\n} \n\nint BS_satantoff( GTime time, SatSys Sat, Vector3d& rs, Vector3d& dant, int gloind = 0)\n{\n\tdouble lam1, lam2;\n\n\tchar id[5];\n\tSat.getId(id);\n\t\n\tPhaseCenterData* pcsat = findAntenna(Sat.id(), time, nav);\n\n\tif (pcsat == nullptr) return -1;\n\tauto& pcoMap = pcsat->pcoMap;\n\t\n\tE_FType j = F1;\n\tE_FType k = F2;\n\tdouble glonfrq1 = FREQ1_GLO + DFRQ1_GLO*gloind;\n\tdouble glonfrq2 = FREQ2_GLO + DFRQ2_GLO*gloind;\n\tswitch (Sat.sys)\n\t{\n\t\tcase E_Sys::GPS: lam1 = CLIGHT/FREQ1; \t\tlam2 = CLIGHT/FREQ2;\t\t\tbreak;\n\t\tcase E_Sys::GLO: lam1 = CLIGHT/glonfrq1; \tlam2 = CLIGHT/glonfrq2;\t\t\tbreak;\n\t\tcase E_Sys::QZS: lam1 = CLIGHT/FREQ1; \t\tlam2 = CLIGHT/FREQ2;\t\t\tbreak;\n\t\tcase E_Sys::GAL: lam1 = CLIGHT/FREQ1; \t\tlam2 = CLIGHT/FREQ5;\tk=F5;\tbreak;\n\t\tcase E_Sys::BDS: lam1 = CLIGHT/FREQ1_CMP; \tlam2 = CLIGHT/FREQ2_CMP; \t\tbreak;\n\t\tdefault:     \t return -2; \n\t}\n\t\n\t/* sun position in ecef */\n\tVector3d rsun;\n\tdouble gmst;\n\tERPValues erpv;\n\tsunmoonpos(gpst2utc(time), erpv, &rsun, nullptr, &gmst);\n\n\t/* unit vectors of satellite fixed coordinates */\n\tVector3d r = -rs;\n\tVector3d ez = r.normalized();\n\tr = rsun - rs;\n\tVector3d es = r.normalized();\n\tr = ez.cross(es);\n\tVector3d ey = r.normalized();\n\tVector3d ex = ey.cross(ez);\n\t\n\tdouble gamma\t= lam2*lam2/lam1/lam1;\n\tdouble C1\t\t= gamma\t/ (gamma - 1);\n\tdouble C2\t\t= -1\t/ (gamma - 1);\n\n\t/* iono-free LC */\n\tfor (int i = 0; i < 3; i++)\t\n\t{\n\t\t/* ENU to NEU */\n\t\tVector3d pcoJ;\n\t\tVector3d pcoK;\n\t\tif (pcoMap.find(j) == pcoMap.end())\tpcoJ = Vector3d::Zero();\n\t\telse\t\t\t\t\t\t\t\tpcoJ = pcoMap[j];\n\t\tif (pcoMap.find(k) == pcoMap.end())\tpcoK = Vector3d::Zero();\n\t\telse\t\t\t\t\t\t\t\tpcoK = pcoMap[k];\n\t\tdouble dant1\t= pcoJ[1] * ex(i)\n\t\t\t\t\t\t+ pcoJ[0] * ey(i)\n\t\t\t\t\t\t+ pcoJ[2] * ez(i);\t//todo aaron, matrix\n\t\tdouble dant2\t= pcoK[1] * ex(i)\n\t\t\t\t\t\t+ pcoK[0] * ey(i)\n\t\t\t\t\t\t+ pcoK[2] * ez(i);\n\t\t\t\t\t\t\n\t\tfprintf( stdout,\"\\n  ATX: %s %11.6f %11.6f %11.6f  %11.6f %11.6f %11.6f\", Sat.id().c_str(), pcoJ[0], pcoJ[1], pcoJ[2], pcoK[0], pcoK[1], pcoK[2]);\n\n\t\t//dant(i)\t= C1 * dant1\n\t\t//\t\t+ C2 * dant2;\n\t\tdant(i) = dant1;\n\t}\n\treturn 0;\n}\n\nEph* BS_seleph( GTime time, SatSys Sat, int iode, nav_t& nav_, int opt=0)\n{\n\tdouble valid = 0;\n\t\n\tswitch (Sat.sys) \n\t{\n\t\tcase E_Sys::QZS:\tvalid = MAXDTOE_QZS\t+ 1; break;\n\t\tcase E_Sys::GAL:\tvalid = MAXDTOE_GAL\t+ 1; break;\n\t\tcase E_Sys::BDS:\tvalid = MAXDTOE_CMP\t+ 1; break;\n\t\tdefault: \t\t\tvalid = MAXDTOE\t\t+ 1; break;\n\t}\n\t\n\tauto& ephList = nav_.ephMap[Sat];\n\tEph* chosen = nullptr;\n\tGTime latestToe = GTime::noTime();\n\tdouble max_dtime = BS_Max_Dtime[Sat.sys];\n\tfor (auto& [dummy, eph] : ephList)\n\t{\n\t\tif \t( iode >= 0 )\n\t\t{\n\t\t\tif(iode == eph.iode) return &eph;\n\t\t\telse continue;\n\t\t}\n\t\t//fprintf(stdout, \"    %s %s\\n\",Sat.id().c_str(),eph.toe.to_string(0).c_str());\n\t\tif(opt == 0)\n\t\t{\n\t\t\tif (fabs(eph.toe - time) > valid)\n\t\t\t\tcontinue;\n\t\t\tif (eph.toe > latestToe)\n\t\t\t{\n\t\t\t\tchosen\t= &eph;\n\t\t\t\tlatestToe = eph.toe;\n\t\t\t}\n\t\t}\n\t\tif(opt==1)\n\t\t{\n\t\t\tdouble dtime=max_dtime;\n\t\t\tif (Sat.sys == +E_Sys::GPS)\tdtime = fabs(eph.toe - (time + 3600));\n\t\t\telse\t\t\t\t\t\tdtime = fabs(eph.toe - time);\n\t\t\t\n\t\t\tif ( max_dtime > dtime)\n\t\t\t{\n\t\t\t\tchosen\t= &eph;\n\t\t\t\tlatestToe = eph.toe;\n\t\t\t\tmax_dtime = dtime;\n\t\t\t}\n\t\t}\n\n\t}\n\t\n\treturn chosen;\n}\n\nGeph* BS_selgeph( GTime time, SatSys Sat, int iode, nav_t& nav_, int opt=0)\n{\n\tdouble valid = MAXDTOE_GLO\t+ 1;\n\t\n\tauto& gephList = nav_.gephMap[Sat];\n\tGeph* chosen = nullptr;\n\tGTime latestToe = GTime::noTime();\n\tdouble max_dtime = BS_Max_Dtime[E_Sys::GLO];\n\tfor (auto& [dummy, geph] : gephList)\n\t{\n\t\tif \t( iode >= 0 )\n\t\t{\n\t\t\tif(iode == geph.iode) \treturn &geph;\n\t\t\telse \t\t\t\t\tcontinue;\n\t\t}\n\t\t//fprintf(stdout, \"    %s %s\\n\",Sat.id().c_str(),geph.toe.to_string(0).c_str());\n\t\tif(opt==0)\n\t\t{\n\t\t\tif (fabs(geph.toe - time) > valid)\n\t\t\t\tcontinue;\n\t\t\tif (geph.toe > latestToe)\n\t\t\t{\n\t\t\t\tchosen\t= &geph;\n\t\t\t\tlatestToe = geph.toe;\n\t\t\t}\n\t\t}\n\t\tif(opt==1)\n\t\t{\n\t\t\tdouble dtime = fabs(geph.toe - time);\n\t\t\tif ( max_dtime > dtime)\n\t\t\t{\n\t\t\t\tchosen\t= &geph;\n\t\t\t\tlatestToe = geph.toe;\n\t\t\t\tmax_dtime = dtime;\n\t\t\t}\n\t\t}\n\t}\n\t\n\treturn chosen;\n}\n\n/* glonass orbit differential equations --------------------------------------*/\nvoid deq(const double* x, double* xdot, Vector3d& acc)\n{\n\tdouble a, b, c, r2 = dot(x, x, 3), r3 = r2 * sqrt(r2), omg2 = OMGE_GLO*OMGE_GLO;\n\n\tif (r2 <= 0.0)\n\t{\n\t\txdot[0] = xdot[1] = xdot[2] = xdot[3] = xdot[4] = xdot[5] = 0.0;\n\t\treturn;\n\t}\n\n\t/* ref [2] A.3.1.2 with bug fix for xdot[4],xdot[5] */\n\ta = 1.5 * J2_GLO * MU_GLO * RE_GLO*RE_GLO / r2 / r3; /* 3/2*J2*mu*Ae^2/r^5 */\n\tb = 5.0 * x[2] * x[2] / r2;            /* 5*z^2/r^2 */\n\tc = -MU_GLO / r3 - a * (1.0 - b);      /* -mu/r^3-a(1-b) */\n\txdot[0] = x[3];\n\txdot[1] = x[4];\n\txdot[2] = x[5];\n\txdot[3] = (c + omg2) * x[0] + 2.0 * OMGE_GLO * x[4] + acc[0];\n\txdot[4] = (c + omg2) * x[1] - 2.0 * OMGE_GLO * x[3] + acc[1];\n\txdot[5] = (c - 2.0 * a) * x[2] + acc[2];\n}\n\n/* glonass position and velocity by numerical integration --------------------*/\nvoid glorbit(double t, double* x, Vector3d& acc) \n{\n\tdouble k1[6], k2[6], k3[6], k4[6], w[6];\n\tint i;\n\n\tdeq(x, k1, acc); for (i = 0; i < 6; i++) w[i] = x[i] + k1[i] * t / 2;\n\tdeq(w, k2, acc); for (i = 0; i < 6; i++) w[i] = x[i] + k2[i] * t / 2;\n\tdeq(w, k3, acc); for (i = 0; i < 6; i++) w[i] = x[i] + k3[i] * t;\n\tdeq(w, k4, acc);\n\n\tfor (i = 0; i < 6; i++)\n\t\tx[i] += (k1[i] + 2 * k2[i] + 2 * k3[i] + k4[i]) * t / 6;\n}\n\nint BS_geph2pos( GTime\ttime, Geph* geph, Vector3d& rs, double*\tdts)\n{\n\tdouble t = time - geph->toe;\n\t*dts\t=  geph->taun \n\t\t\t+  geph->gamn * t;\n\n\tdouble x[6] = {0};\n\tfor (int i = 0; i < 3; i++)\t\n\t{\n\t\tx[i  ] = geph->pos[i];\n\t\tx[i+3] = geph->vel[i];\n\t}\n\n\tfor (double tt = t < 0 ? -GLOSTEP : GLOSTEP; fabs(t) > 1E-9; t -= tt)\t\n\t{\n\t\tif (fabs(t) < GLOSTEP) tt=t;\n\t\tglorbit(tt, x, geph->acc);\n\t}\n\n\tfor (int i = 0; i < 3; i++) rs(i) = x[i];\n\t\n\treturn 0;\n}\n\nint BS_eph2pos( GTime\ttime, Eph* eph, Vector3d& rs, double*\tdts) {\n\n\tif (eph->A <= 0) return -1;\n\n\tdouble tk = time - eph->toe;\n\tint prn = eph->Sat.prn;\n\tint sys = eph->Sat.sys;\n\n\tdouble mu;\n\tdouble omge;\n\tswitch (sys)\n\t{\n\t\tcase E_Sys::GAL: mu = MU_GAL; omge = OMGE_GAL; break;\n\t\tcase E_Sys::BDS: mu = MU_CMP; omge = OMGE_CMP; break;\n\t\tdefault:     \t mu = MU_GPS; omge = OMGE;     break;\n\t}\n\n\tdouble M = eph->M0 + (sqrt(mu / (eph->A * eph->A * eph->A)) + eph->deln) * tk;\n\n\tdouble E\t= M;\n\tdouble Ek\t= 0;\n\tint n;\n\tfor (n = 0; fabs(E - Ek) > RTOL_KEPLER && n < MAX_ITER_KEPLER; n++)\n\t{\n\t\tEk = E;\n\t\tE -= (E - eph->e * sin(E) - M) / (1 - eph->e * cos(E));\n\t}\n\n\tif (n >= MAX_ITER_KEPLER)\n\t{\n\t\tfprintf(stderr,\"WARNING for %s ephemeris: iteration divergent\", eph->Sat.id().c_str());\n\t\treturn -1;\n\t} \n\n\tdouble sinE  = sin(E);\n\tdouble cosE  = cos(E);\n\tdouble u \t = atan2(sqrt(1 - eph->e * eph->e) * sinE, cosE - eph->e) + eph->omg;\n\tdouble r \t = eph->A * (1 - eph->e * cosE);\n\tdouble i\t = eph->i0 + eph->idot * tk;\n\tdouble sin2u = sin(2 * u);\n\tdouble cos2u = cos(2 * u);\n\n\tu \t\t\t+= eph->cus * sin2u + eph->cuc * cos2u;\n\tr \t\t\t+= eph->crs * sin2u + eph->crc * cos2u;\n\ti \t\t\t+= eph->cis * sin2u + eph->cic * cos2u;\n\n\tdouble x\t = r * cos(u);\n\tdouble y\t = r * sin(u);\n\tdouble cosi  = cos(i);\n\n\t/* beidou geo satellite */\n\tif (sys == +E_Sys::BDS && prn <= 5)\n\t{\n\t\tdouble O\t= eph->OMG0\n\t\t\t\t\t+ eph->OMGd * tk\n\t\t\t\t\t- omge * eph->toes;\n\t\tdouble sinO = sin(O);\n\t\tdouble cosO = cos(O);\n\t\tdouble xg = x * cosO - y * cosi * sinO;\n\t\tdouble yg = x * sinO + y * cosi * cosO;\n\t\tdouble zg = y * sin(i);\n\t\tdouble sino = sin(omge * tk);\n\t\tdouble coso = cos(omge * tk);\n\t\trs(0) = +xg * coso + yg * sino * COS_5 + zg * sino * SIN_5;\n\t\trs(1) = -xg * sino + yg * coso * COS_5 + zg * coso * SIN_5;\n\t\trs(2) = -yg * SIN_5 + zg * COS_5;\n\t}\n\telse\n\t{\n\t\tdouble O\t= eph->OMG0\n\t\t\t\t\t+ (eph->OMGd - omge) * tk\n\t\t\t\t\t- omge * eph->toes;\n\t\tdouble sinO = sin(O);\n\t\tdouble cosO = cos(O);\n\t\trs(0) = x * cosO - y * cosi * sinO;\n\t\trs(1) = x * sinO + y * cosi * cosO;\n\t\trs(2) = y * sin(i);\n\t}\n\n\ttk = time - eph->toc;\n\t*dts\t= eph->f0\n\t\t\t+ eph->f1 * tk\n\t\t\t+ eph->f2 * tk * tk;\n\treturn 0;\n}\n\n\nvoid print_SP3header(FILE* fpout)\n{\n\t/* line one */\n\tfprintf(fpout,\"#dP%4.0f %2.0f %2.0f %2.0f %2.0f %11.8f \", BS_Start_Epoc[0], BS_Start_Epoc[1], BS_Start_Epoc[2], BS_Start_Epoc[3], BS_Start_Epoc[4], BS_Start_Epoc[5]);\n\tfprintf(fpout,\"%7d ORBIT WGS84 BCT   GA\", BS_Epoch_Num);\n\t\n\t/* Line two */\n\tdouble mjdate = 7.0*BS_Start_Week + BS_Start_TOW/86400.0 + 44244.0;\n\tfprintf(fpout,\"\\n## %4d %15.8f %5.0f %15.13f\", BS_Start_Week, BS_Start_TOW, mjdate, mjdate-floor(mjdate));\n\t\n\t/* satellite lines */\n\tint NumSatLeft = 85, satind=0, satinline=0;\n\tif(BS_Satel_List.size()>85) NumSatLeft = BS_Satel_List.size();\n\tauto it = BS_Satel_List.begin();\n\twhile(satind < NumSatLeft || satinline > 0)\n\t{\n\t\tif(satind == 0) fprintf(fpout, \"\\n+  %3d   \", (int)BS_Satel_List.size());\n\t\telse if(satinline == 0) fprintf(fpout, \"\\n+        \");\n\t\t\n\t\tif(it==BS_Satel_List.end()) fprintf(fpout, \"  0\");\n\t\telse\n\t\t{\n\t\t\tfprintf(fpout,\"%s\",it->first.id().c_str());\n\t\t\tit++;\n\t\t}\n\t\t\n\t\tsatind++;\n\t\tif(satinline<16) satinline++;\n\t\telse satinline = 0;\n\t}\n\t\n\t/* accuracy lines */\n\tsatind = 0;\n\tsatinline = 0;\n\twhile(satind<NumSatLeft)\n\t{\n\t\tif(satinline == 0) fprintf(fpout, \"\\n++       \");\n\t\t\n\t\tfprintf(fpout, \"  0\");\n\t\t\n\t\tsatind++;\n\t\tif(satinline<16) satinline++;\n\t\telse satinline = 0;\n\t}\n\t\n\t/* char variable lines */\n\tif(GNSSinp.size() > 1) fprintf(fpout, \"\\n%%c M \");\n\telse fprintf(fpout, \"\\n%%c %s \", GNSSinp.c_str());\n\tfprintf(fpout, \" cc GPS ccc cccc cccc cccc cccc ccccc ccccc ccccc ccccc\");\n\tfprintf(fpout, \"\\n%%c cc cc GPS ccc cccc cccc cccc cccc ccccc ccccc ccccc ccccc\");\n\t\n\t/* float variable lines */\n\tfprintf(fpout, \"\\n%%f  1.2500000  1.025000000  0.00000000000  0.000000000000000\");\n\tfprintf(fpout, \"\\n%%f  0.0000000  0.000000000  0.00000000000  0.000000000000000\");\n\t\n\t/* float variable lines */\n\tfprintf(fpout, \"\\n%%i    0    0    0    0      0      0      0      0         0\");\n\tfprintf(fpout, \"\\n%%i    0    0    0    0      0      0      0      0         0\");\n\t\n\tfprintf(fpout, \"\\n/* Created using Ginan at: %s. \", timeget().to_string(0).c_str());\n\tfprintf(fpout, \"\\n/* WARNING: For Geoscience Australia's internal use only\");\t\n}\n\nvoid print_SP3epoch(FILE* fpout, GTime tsync, map<SatSys, vector<double>>& temp_eph)\n{\n\tdouble ep[6];\n\ttime2epoch(tsync, ep);\n\tfprintf(fpout,\"\\n*  %4.0f %2.0f %2.0f %2.0f %2.0f %11.8f \", ep[0], ep[1], ep[2], ep[3], ep[4], ep[5]);\n\t\n\tfor(auto& [sat, neph] : BS_Satel_List){\n\t\tif(temp_eph.find(sat) == temp_eph.end()) \n\t\t\tfprintf(fpout, \"\\nP%s%14.6f%14.6f%14.6f 999999.999999                    \", sat.id().c_str(), 0.0, 0.0, 0.0);\n\t\telse\n\t\t{\n\t\t\tauto vect = temp_eph[sat];\n\t\t\tfprintf(fpout, \"\\nP%s%14.6f%14.6f%14.6f%14.6f                    \", sat.id().c_str(), vect[0]/1000, vect[1]/1000, vect[2]/1000, vect[3]*1e6);\t\n\t\t}\n\t}\n}\n\n\nint main(int argc, char **argv)\n{\n\tboost::log::core::get()->set_filter (boost::log::trivial::severity >= boost::log::trivial::info);\n\tstring atxfile = \"igs14.atx\";\n\tvector<string> navfiles;\n\tint GALSelection = 7;\n\t/* Argument parsing */\n\tstring inpfile;\n    string outfile = \"BS_orbits.sp3\";\n    bool fstreq = false;\n    BS_Max_Dtime[E_Sys::GPS] = 86400.0;\n    BS_Max_Dtime[E_Sys::GLO] = 86400.0;\n    BS_Max_Dtime[E_Sys::GAL] = 86400.0;\n    BS_Max_Dtime[E_Sys::QZS] = 86400.0;\n    BS_Max_Dtime[E_Sys::BDS] = 86400.0;\n    int ephopt = 0;\n    for (int i = 1; i < argc; i++) \n    {\n        if      (!strcmp(argv[i], \"-inp\") && i+1 < argc)\n        {\n        \tinpfile.assign(argv[++i]);\n        \tnavfiles.push_back(inpfile);\n        } \n        else if (!strcmp(argv[i], \"-out\") && i+1<argc) outfile.assign(argv[++i]);\n        else if (!strcmp(argv[i], \"-ant\") && i+1<argc) atxfile.assign(argv[++i]);\n        else if (!strcmp(argv[i], \"-gns\") && i+1<argc) GNSSinp.assign(argv[++i]);\n        else if (!strcmp(argv[i], \"-int\") && i+1<argc) BS_Epoch_Inter = atof(argv[++i]);\n    \telse if (!strcmp(argv[i], \"-Gdt\") && i+1<argc) BS_Max_Dtime[E_Sys::GPS] = atof(argv[++i]);\n    \telse if (!strcmp(argv[i], \"-Rdt\") && i+1<argc) BS_Max_Dtime[E_Sys::GLO] = atof(argv[++i]);\n    \telse if (!strcmp(argv[i], \"-Edt\") && i+1<argc) BS_Max_Dtime[E_Sys::GAL] = atof(argv[++i]);\n    \telse if (!strcmp(argv[i], \"-Jdt\") && i+1<argc) BS_Max_Dtime[E_Sys::QZS] = atof(argv[++i]);\n    \telse if (!strcmp(argv[i], \"-Cdt\") && i+1<argc) BS_Max_Dtime[E_Sys::BDS] = atof(argv[++i]);\n    \telse if (!strcmp(argv[i], \"-clst\"))\t\t\t   ephopt = 1;\n    \telse if (!strcmp(argv[i], \"-inav\"))            GALSelection = 5;\n        else if (!strcmp(argv[i], \"-fnav\"))  \t\t   GALSelection = 2;\n        else if (!strcmp(argv[i], \"-frst\"))\t\t\t   fstreq=true;\n        else if (!strcmp(argv[i], \"-help\"))\n        {\n        \thelpstring();\n        \texit(0);\n        } \n    }\n\tif(BS_Epoch_Inter <= 0.0) BS_Epoch_Inter = 900.0;\n\t\n\tbool pass = readantexf(atxfile, nav);\n\tif(!pass)\n\t{\n\t\tfprintf(stderr, \"ERROR: invalid ANTEX file %s\\n\", atxfile.c_str());\n\t\texit(0);\n\t}\n\tstd::cout << \"ATX file \" << atxfile << std::endl;\n\t\n\tmap<E_Sys,bool> GNSS_on;\n    if (GNSSinp.find(\"A\") != std::string::npos) GNSSinp = \"GRECJ\"; //All constellations\n    if (GNSSinp.find(\"G\") != std::string::npos) GNSS_on[E_Sys::GPS] = true; //GPS\n    if (GNSSinp.find(\"R\") != std::string::npos) GNSS_on[E_Sys::GLO] = true; //GLONASS\n    if (GNSSinp.find(\"E\") != std::string::npos) GNSS_on[E_Sys::GAL] = true; //Galileo\n    if (GNSSinp.find(\"C\") != std::string::npos) GNSS_on[E_Sys::BDS] = true; //Beidou\n    if (GNSSinp.find(\"J\") != std::string::npos) GNSS_on[E_Sys::QZS] = true; //QZSS\n    if (GNSS_on.empty())\n\t{\n        fprintf(stderr, \"No GNSS selected\\n\");\n        exit(0);\n    }\n\tstd::cout << \"Processed GNSS \" << GNSSinp << std::endl;\n    \n\tchar\t\t\ttype = 'N';\n\tObsList \t\tobsList;\n\tRinexStation\tsta;\n\tdouble\t\t\tversion = 0;\n\tE_Sys\t\t\tsys;\n\tint \t\t\ttsys;\n\tmap<E_Sys, vector<CodeType>>\tsysCodeTypes;\n\tint \t\t\tnfil = 0;\n\t\n\tfor (auto& file : navfiles)\n\t{\n\t\tstd::ifstream\tinputStream;\n\t\tinputStream.open(file, std::ifstream::in);\n\t\tint info = readrnx(inputStream, type , obsList, nav, &sta, version, sys, tsys, sysCodeTypes);\n\t\tif (info == false)\n\t\t{\n\t\t\tstd::cout << \"ERROR: invalid BRDC file \" << file.c_str() << std::endl;\n\t\t}\n\t\telse{\n\t\t\tstd::cout << \"Processed file \" << file << \" \" << type << \" \" << version << \" \" << std::endl;\n\t\t\tnfil++;\t\t\n\t\t\tinfo = readrnx(inputStream, type , obsList, nav, &sta, version, sys, tsys, sysCodeTypes);\n\t\t} \n\t}\n\t\n\tif(nfil == 0)\n\t{\n\t\tstd::cout << \"No valid Nav. files\" << std::endl;\n\t\texit(0);\n\t}\n\t\n\tFILE* sp3fp=fopen(outfile.c_str(),\"wt\");\n\tif(!sp3fp) \n\t{\n\t\tstd::cout << \"Cannot open output file: \" << outfile << std::endl;\n\t\texit(0);\n\t}\n\tstd::cout << \"Output file: \" << outfile << std::endl;\n\t\n\tGTime tstart = GTime::noTime();\n\tGTime tfinsh = GTime::noTime();\n\t\n\tfor(auto& [satint,ephlist] : nav.ephMap)\n\t{\n\t\tSatSys sat;\n\t\tsat.fromHash(satint);\n\t\tif(!GNSS_on[sat.sys]) continue;\n\t\tint neph = 0;\n\t\tfor(auto it = nav.ephMap[satint].begin(); it != nav.ephMap[satint].end();)\n\t\t{\n\t\t\tauto [dummy, eph] = *it;\n\t\t\tdouble dtoc = eph.toe - eph.toc;\n\t\t\tdouble dttr = eph.toe - eph.ttr;\n\t\t\tbool alert = false;\n\t\t\t\n\t\t\tif(dtoc !=0.0) alert = true;\n\t\t\tif(fabs(dttr)>10000.0) alert = true;\n\t\t\t\n\t\t\tif(sys == +E_Sys::GAL && !(eph.code & GALSelection)) alert=true;\t\t/* INAVs messages, change from 5 to 2 for FNAVs (we dont want to mix the two) */\n\t\t\t\n\t\t\tif(alert)\n\t\t\t{\n\t\t\t\tit=nav.ephMap[satint].erase(it);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\t//fprintf(stdout, \"%s, %s, %d, %.1f, %s\\n\", sat.id().c_str(), eph.toe.to_string(0).c_str(), eph.iode, dtoc, eph.ttr.to_string(0).c_str());\n\t\t\t\tneph++;\n\t\t\t\tif (tstart == GTime::noTime() || tstart > eph.toe)\t\ttstart = eph.toe;\n\t\t\t\tif (tfinsh == GTime::noTime() || tfinsh < eph.toe)\t\ttfinsh = eph.toe;\n\t\t\t\tit++;\n\t\t\t}\n\t\t}\n\t\tif(neph>0) BS_Satel_List[sat]=neph;\n\t}\n\t\n\tif(GNSS_on[E_Sys::GLO]) for(auto& [satint,gephlist] : nav.gephMap)\n\t{\n\t\tSatSys sat;\n\t\tsat.fromHash(satint);\n\t\tint neph = 0;\n\t\tfor(auto it = nav.gephMap[satint].begin(); it != nav.gephMap[satint].end();){\n\t\t\tauto& [dummy, geph] = *it;\n\t\t\tdouble dtoc = geph.toe - geph.tof;\n\t\t\tbool alert = false;\n\t\t\t\n\t\t\t//if(dtoc !=0.0) alert=true;\n\t\t\t//if(fabs(dttr)>10000.0) alert=true;\n\t\t\t\n\t\t\tif(alert){\n\t\t\t\tit = nav.gephMap[satint].erase(it);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\t//fprintf(stdout, \"%s %s %d, %.1f, %d\\n\", sat.id().c_str(), geph.toe.to_string(0).c_str(), geph.iode, dtoc, geph.svh);\n\t\t\t\n\t\t\tneph++;\n\t\t\tif (tstart == GTime::noTime() || tstart > geph.toe ) \ttstart = geph.toe;\n\t\t\tif (tfinsh == GTime::noTime() || tfinsh < geph.toe ) \ttfinsh = geph.toe;\n\t\t\tit++;\n\t\t}\n\t\t\n\t\tif (neph > 0)\n\t\t\tBS_Satel_List[sat] = neph;\n\t}\n\n\tdouble StarTow\t= time2gpst(tstart, &BS_Start_Week);\n\t//BS_Start_TOW\t= BS_Epoch_Inter*floor(StarTow/BS_Epoch_Inter);\n\tBS_Start_TOW\t= 3600.0 * floor(StarTow / 3600.0);\n\tGTime tsync \t= gpst2time(BS_Start_Week, BS_Start_TOW);\n\tBS_Epoch_Num\t= (int)(floor((tfinsh - tsync)/BS_Epoch_Inter) + 1);\n\ttime2epoch(tsync, BS_Start_Epoc);\n\n\tfprintf(stdout, \"\\nTstart= %s, Tini= %s, Nepoc=%d\\n\", tstart.to_string(0).c_str(), tsync.to_string(0).c_str(), BS_Epoch_Num);\n\n\tif(fstreq)for(auto it = BS_Satel_List.begin(); it != BS_Satel_List.end();)\n\t{\n\t\tSatSys sat = it->first;\n\t\tbool nofst = false;\n\t\tVector3d rs(0, 0, 0);\n\t\tVector3d dant(0, 0, 0);\n\t\tdouble dts;\t\n\t\tif(sat.sys == +E_Sys::GLO)\n\t\t{\n\t\t\tGeph* gephp=BS_selgeph( tsync, sat, -1, nav);\n\t\t\tif(!gephp) nofst = true;\n\t\t\telse if(BS_geph2pos( tsync, gephp, rs, &dts) < 0) nofst = true;\n\t\t\telse if(rs.norm() < RE_WGS84) nofst = true;\n\t\t\telse if(BS_satantoff( tsync, sat, rs, dant, gephp->frq ) < 0) nofst = true;\n\t\t\telse nofst = false;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tEph* ephp=BS_seleph( tsync, sat, -1, nav);\n\t\t\tif(!ephp) nofst = true;\n\t\t\telse if(BS_eph2pos( tsync, ephp, rs, &dts) < 0) nofst = true;\n\t\t\telse if(rs.norm() < RE_WGS84) nofst = true;\n\t\t\telse if(BS_satantoff( tsync, sat, rs, dant, 0 ) < 0) nofst = true;\n\t\t\telse nofst = false;\n\t\t}\n\t\t\t\n\t\tif(nofst){\n\t\t\tit = BS_Satel_List.erase(it);\n\t\t}\t\n\t\telse{\n\t\t\t++it;\n\t\t}\n\t}\n\n\tprint_SP3header(sp3fp);\n\t\n\tfor(int epc=0; epc<BS_Epoch_Num; epc++){\n\t\tfprintf(stdout, \"\\n%s\", tsync.to_string(0).c_str());\n\t\tmap<SatSys,vector<double>> temp_eph;\n\t\tfor(auto& [sat,neph] : BS_Satel_List){\n\t\t\tVector3d rs(0, 0, 0);\n\t\t\tVector3d dant(0, 0, 0);\n\t\t\tdouble dts;\n\t\t\t\n\t\t\tif(sat.sys == +E_Sys::GLO){\n\t\t\t\tGeph* gephp=BS_selgeph( tsync, sat, -1, nav, ephopt);\n\t\t\t\tif(!gephp) continue;\n\t\t\t\tif(BS_geph2pos( tsync, gephp, rs, &dts) < 0) continue;\n\t\t\t\tif(rs.norm() < RE_WGS84) continue;\n\t\t\t\tif(BS_satantoff( tsync, sat, rs, dant, gephp->frq ) < 0) continue;\n\t\t\t\tfprintf(stdout, \" %s \", sat.id().c_str());\n\t\t\t}\n\t\t\telse{\n\t\t\t\tEph* ephp=BS_seleph( tsync, sat, -1, nav, ephopt);\n\t\t\t\tif(!ephp) continue;\n\t\t\t\tif(BS_eph2pos( tsync, ephp, rs, &dts) < 0) continue;\n\t\t\t\tif(rs.norm() < RE_WGS84) continue;\n\t\t\t\tif(BS_satantoff( tsync, sat, rs, dant, 0 ) < 0) continue;\n\t\t\t\tfprintf(stdout, \" %s \", sat.id().c_str());\n\t\t\t}\n\t\t\t\n\t\t\tvector<double> sateph;\n\t\t\tsateph.push_back(rs(0) - dant(0));\n\t\t\tsateph.push_back(rs(1) - dant(1));\n\t\t\tsateph.push_back(rs(2) - dant(2));\n\t\t\tsateph.push_back(dts);\n\t\t\t\n\t\t\t//fprintf(stdout, \"\\n%s %11.6f %11.6f %11.6f\", sat.id().c_str(), dant(0),dant(1),dant(2));\n\t\t\t\n\t\t\ttemp_eph[sat] = sateph;\n\t\t}\n\t\t\n\t\tif (temp_eph.size() > 0) \n\t\t\tprint_SP3epoch(sp3fp, tsync, temp_eph);\n\t\t\n\t\ttsync = tsync + BS_Epoch_Inter;\n\t}\n\t\n\tfprintf(sp3fp, \"\\nEOF\");\n\t\n\treturn(EXIT_SUCCESS);\n}\n", "meta": {"hexsha": "4452bf5a09d9b274543002e0d9b12f6500fa1b90", "size": 21222, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/cpp/brdc2sp3/brdc2sp3_main.cpp", "max_stars_repo_name": "GnssTao/ginan", "max_stars_repo_head_hexsha": "b69593b584f75e03238c1c667796e2030391fbed", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-03-31T15:16:19.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T15:16:19.000Z", "max_issues_repo_path": "src/cpp/brdc2sp3/brdc2sp3_main.cpp", "max_issues_repo_name": "hqy123-cmyk/ginan", "max_issues_repo_head_hexsha": "b69593b584f75e03238c1c667796e2030391fbed", "max_issues_repo_licenses": ["Apache-2.0"], "max_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/brdc2sp3/brdc2sp3_main.cpp", "max_forks_repo_name": "hqy123-cmyk/ginan", "max_forks_repo_head_hexsha": "b69593b584f75e03238c1c667796e2030391fbed", "max_forks_repo_licenses": ["Apache-2.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.7643758766, "max_line_length": 167, "alphanum_fraction": 0.5813306946, "num_tokens": 8371, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7185944046238981, "lm_q2_score": 0.4186969093556867, "lm_q1q2_score": 0.30087325629631595}}
{"text": "//==============================================================================\n//         Copyright 2003 - 2011 LASMEA UMR 6602 CNRS/Univ. Clermont II\n//         Copyright 2009 - 2011 LRI    UMR 8623 CNRS/Univ Paris Sud XI\n//\n//          Distributed under the Boost Software License, Version 1.0.\n//                 See accompanying file LICENSE.txt or copy at\n//                     http://www.boost.org/LICENSE_1_0.txt\n//==============================================================================\n#ifndef BOOST_SIMD_TOOLBOX_ARITHMETIC_FUNCTIONS_SCALAR_HYPOT_HPP_INCLUDED\n#define BOOST_SIMD_TOOLBOX_ARITHMETIC_FUNCTIONS_SCALAR_HYPOT_HPP_INCLUDED\n\n#include <boost/simd/toolbox/arithmetic/functions/hypot.hpp>\n#include <boost/simd/include/functions/scalar/bitwise_cast.hpp>\n#include <boost/simd/include/functions/scalar/sqrt.hpp>\n#include <boost/simd/include/functions/scalar/sqr.hpp>\n#include <boost/simd/include/functions/scalar/max.hpp>\n#include <boost/simd/include/functions/scalar/min.hpp>\n#include <boost/simd/include/functions/scalar/logical_or.hpp>\n#include <boost/simd/include/functions/scalar/logical_and.hpp>\n#include <boost/simd/include/functions/scalar/exponent.hpp>\n#include <boost/simd/include/functions/scalar/is_nan.hpp>\n#include <boost/simd/include/functions/scalar/is_inf.hpp>\n#include <boost/simd/include/functions/scalar/ldexp.hpp>\n#include <boost/simd/include/constants/inf.hpp>\n#include <boost/simd/include/constants/nan.hpp>\n#include <boost/simd/sdk/meta/make_dependent.hpp>\n#include <boost/dispatch/meta/as_integer.hpp>\n\nnamespace boost { namespace simd { namespace ext\n{\n  template < class T, class I = typename dispatch::meta::as_integer<T, signed>::type>\n  struct hypot_constants;\n  //TODO make proper constants\n\n  template <class I> struct hypot_constants<float, I>\n  {\n    typedef I  int_type;\n    static inline int_type C0() { return (30);};\n    static inline int_type C1() { return (50);};\n    static inline int_type C2() { return (60);};\n    static inline int_type MC1(){ return (-50);};\n    static inline int_type MC2(){ return (-60);};\n    static inline int_type C3() { return (0x00800000);};\n    static inline int_type M1() { return (0xfffff000);};\n  };\n\n  template <class I> struct hypot_constants<double, I>\n  {\n    typedef I  int_type;\n    static inline int_type C0() { return (60);};\n    static inline int_type C1() { return (500);};\n    static inline int_type C2() { return (600);};\n    static inline int_type MC1(){ return (-500);};\n    static inline int_type MC2(){ return (-600);};\n    static inline int_type C3() { return (0x0010000000000000ll);}\n    static inline int_type M1() { return (0xffffffff00000000ll);};\n  };\n\n BOOST_SIMD_FUNCTOR_IMPLEMENTATION(boost::simd::tag::hypot_, tag::cpu_,\n                       (A0),\n                       (scalar_<arithmetic_<A0> >)(scalar_<arithmetic_<A0> >)\n                      )\n {\n   typedef typename boost::dispatch::meta::as_floating<A0>::type result_type;\n\n    BOOST_SIMD_FUNCTOR_CALL_REPEAT(2)\n    {\n      return internal(result_type(a0), result_type(a1));\n    }\n  private:\n\n    static inline float internal(const float& a0, const  float& a1)\n      {\n      // flibc does that in ::hypotf(a0, a1) in asm with no more speed!\n      // proper internal is 30% slower\n        return static_cast<float>(::sqrt(boost::simd::sqr(static_cast<typename meta::make_dependent<double, A0>::type>(a0))+\n                                         boost::simd::sqr(static_cast<typename meta::make_dependent<double, A0>::type>(a1))));\n      }\n\n    template < class AA0>\n    static inline AA0  internal(const AA0& a0, const  AA0& a1)\n    {\n      // in double ::hypot is very slow and is 4 times slower than internal\n      // this routine in float (with float constants) is 30% slower than\n      // the straightforward preceding overload for floats\n      // The float constants are provided in order to modify\n      // the algorithm if a architecture gived different speed results\n      if ( logical_or(logical_and(is_nan(a0), is_inf(a1)),\n                      logical_and(is_nan(a1), is_inf(a0)))) return Inf<result_type>();\n      typedef typename dispatch::meta::as_integer<AA0, signed>::type  int_type;\n      AA0 x =  boost::simd::abs(a0);\n      AA0 y =  boost::simd::abs(a1);\n      if (boost::simd::is_inf(x+y)) return Inf<AA0>();\n      if (boost::simd::is_nan(x+y)) return Nan<AA0>();\n      AA0 a =  boost::simd::max(x, y);\n      AA0 b =  boost::simd::min(x, y);\n      int_type ea =   boost::simd::exponent(a);\n      int_type eb  =  boost::simd::exponent(b);\n      if (ea-eb > hypot_constants<AA0>::C0()) return a+b;\n      int_type e = Zero<int_type>();\n      if (ea > hypot_constants<AA0>::C1())\n      {\n        e = hypot_constants<AA0>::MC2();\n      }\n      if (eb < hypot_constants<AA0>::MC1())\n      {\n        e = hypot_constants<AA0>::C1();\n      }\n      if (e)\n      {\n        a =  boost::simd::ldexp(a, e);\n        b =  boost::simd::ldexp(b, e);\n      }\n      AA0 w = a-b;\n      if (w > b)\n      {\n        AA0 t1 = b_and(a, hypot_constants<AA0>::M1());\n        AA0 t2 = a-t1;\n        w  = (t1*t1-(b*(-b)-t2*(a+t1)));\n      }\n      else\n      {\n        AA0 y1 = b_and(b, hypot_constants<AA0>::M1());\n        AA0 y2 = b - y1;\n        typedef typename dispatch::meta::as_integer<AA0, unsigned>::type type;\n        AA0 t1 =  bitwise_cast<AA0>(bitwise_cast<type>(a)+hypot_constants<AA0>::C3());\n        AA0 t2 = (a+a) - t1;\n        w  = (t1*y1-(w*(-w)-(t1*y2+t2*b)));\n      }\n      w = boost::simd::sqrt(w);\n      if (e) w = boost::simd::ldexp(w, -e);\n      return w;\n    }\n  };\n} } }\n\n#endif\n", "meta": {"hexsha": "a141518cc26c7f624b4dd0c787813cdc6564ceb5", "size": 5576, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/boost/simd/arithmetic/include/boost/simd/toolbox/arithmetic/functions/scalar/hypot.hpp", "max_stars_repo_name": "timblechmann/nt2", "max_stars_repo_head_hexsha": "6c71f7063ca4e5975c9c019877e6b2fe07c9e4ce", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2016-09-14T00:23:53.000Z", "max_stars_repo_stars_event_max_datetime": "2018-01-14T12:51:18.000Z", "max_issues_repo_path": "modules/boost/simd/arithmetic/include/boost/simd/toolbox/arithmetic/functions/scalar/hypot.hpp", "max_issues_repo_name": "timblechmann/nt2", "max_issues_repo_head_hexsha": "6c71f7063ca4e5975c9c019877e6b2fe07c9e4ce", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "modules/boost/simd/arithmetic/include/boost/simd/toolbox/arithmetic/functions/scalar/hypot.hpp", "max_forks_repo_name": "timblechmann/nt2", "max_forks_repo_head_hexsha": "6c71f7063ca4e5975c9c019877e6b2fe07c9e4ce", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.4057971014, "max_line_length": 126, "alphanum_fraction": 0.6145982783, "num_tokens": 1510, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6261241911813151, "lm_q2_score": 0.480478678047907, "lm_q1q2_score": 0.3008393236726133}}
{"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 ITERATE_GRID_HH\n#define ITERATE_GRID_HH\n\n#include <boost/fusion/algorithm.hpp>\n#include <boost/fusion/sequence.hpp>\n\n#include \"dune/grid/common/grid.hh\"\n#include \"dune/geometry/quadraturerules.hh\"\n\n#include \"fem/functionspace.hh\"\n#include \"fem/quadrature.hh\"\n#include \"fem/variables.hh\"\n\n#include \"utilities/threading.hh\"\n\nnamespace Kaskade\n{\n  namespace GridIterateDetail\n  {\n    template <class VariableDescriptions, class Functor, class Functions, class Spaces, class CellRange>\n    void gridIterateRange(VariableDescriptions const& varDesc, Functions const& functions, Spaces const& spaces, Functor& f, CellRange cells)\n    {\n      using namespace boost::fusion;\n      using namespace Dune;\n      \n      typedef typename SpaceType<Spaces,0>::type::Grid Grid;\n      typedef typename SpaceType<Spaces,0>::type::GridView GridView;\n      typedef typename SpaceType<Spaces,0>::type::Scalar Scalar;\n      typedef typename Grid::ctype CoordType;\n      int const dim = Grid::dimension;\n      \n      GridView const& gridView = at_c<0>(spaces)->gridView();\n      \n      // Shape function cache. Remember that every thread has to use its own cache!\n      typedef ShapeFunctionCache<Grid,Scalar> SfCache;\n      SfCache sfCache;\n      \n      // Quadrature rule cache\n      typedef Dune::QuadratureRule<CoordType,dim> QuadRule;\n      QuadratureTraits<QuadRule> quadratureCache;\n      \n      // Evaluators for shape functions of all FE spaces. Remember that\n      // every thread has to use its own collection of evaluators!\n      auto evaluators = getEvaluators(spaces,&sfCache);\n      \n      // Iterate over all cells.\n      for (auto ci=cells.begin(); ci!=cells.end(); ++ci) {\n        \n        // for all spaces involved, compute the shape functions and\n        // their global indices, which are needed for evaluating the\n        // functional's derivative.\n        auto idx = gridView.indexSet().index(*ci);\n        moveEvaluatorsToCell(evaluators,*ci,idx);\n        \n        // loop over all quadrature points and evaluate variables\n        int const p = f.integrationOrder(*ci,maxOrder(evaluators));\n        \n        QuadRule const& qr = quadratureCache.rule(ci->type(),p);\n        useQuadratureRuleInEvaluators(evaluators,qr,0);\n        \n        size_t nQuadPos = qr.size();\n        for (size_t g=0; g<nQuadPos; ++g) {\n          // pos of integration point\n          auto const& quadPos = qr[g].position();\n          \n          // for all spaces involved, update the evaluators associated\n          // to this quadrature point\n          moveEvaluatorsToIntegrationPoint(evaluators,quadPos,qr,g,0);\n          \n          // evaluate functions and call functor\n          f(ci,idx,quadPos,evaluateFunctions<VariableDescriptions>(functions,evaluators,valueMethod),\n            ci->geometry().integrationElement(quadPos)*qr[g].weight());\n        }\n      }\n    };\n    \n  } // end of namespace GridIterateDetail\n\n  /**\n   * \\brief A function that supports general iterations over a spatial domain and\n   * supports efficient evaluation of FE functions at the iterated\n   * quadrature points.\n   *\n   * \\param varDesc a heterogeneous container of VariableDescription structures\n   *\n   * \\param functions a heterogeneous container of FE functions or function\n   * views that can be evaluated given an Evaluator of the associated space.\n   *\n   * \\param spaces a heterogeneous container of pointers to FE function spaces.\n   * VariableDescription classes that gives the mapping of functions in\n   * data to their associated spaces.\n   *\n   * \\param f the functor that does the work. On each quadrature point,\n   * is operator() is called with a heterogeneous container of the\n   * values of the functions in data.\n   */\n  template <class VariableDescriptions, class Functor, class Functions, class Spaces>\n  void gridIterate(VariableDescriptions const& varDesc, Functions const& functions, Spaces const& spaces, Functor& f)\n  {\n    using namespace boost::fusion;\n    auto const& cellRanges = deref(begin(functions)).space().gridManager().leafCellRanges(); // WARNING: what if the grid view is not leaf?\n    \n    int n = std::min(NumaThreadPool::instance().cpus(),cellRanges.maxRanges());\n    std::vector<Functor> fs(n,f);\n\n    parallelFor([&varDesc,&functions,&spaces,&cellRanges,&fs](int i, int n) \n    {\n      GridIterateDetail::gridIterateRange(varDesc,functions,spaces,fs[i],cellRanges.range(n,i));\n    },n);\n    \n    for (auto& g: fs)\n      f.join(g);\n  }\n  \n  //---------------------------------------------------------------------\n\n  /**\n   * \\brief A trivial Scaling.\n   *\n   * The identity scaling which leaves its operand simply as it is. This\n   * is a convenience class to evaluate plain, unscaled norms.\n   */\n  struct IdentityScaling\n  {\n    template <class Cell, class F>\n    void scale(Cell const&,\n               Dune::FieldVector<typename Cell::Geometry::ctype,Cell::dimension> const&,\n               F&) const {}\n  };\n\n\n  /**\n   * \\brief A \\ref Collector that sums up the weighted contributions.\n   * \n   * This realizes a plain integration.\n   */\n  struct SummationCollector\n  {\n    template <class Cell>\n    int integrationOrder(Cell const& /* ci */, int shapeFunctionOrder) const\n    {\n      return shapeFunctionOrder;\n    }\n\n    template <class CellIterator, class Index, class Sequence>\n    void operator()(CellIterator const&, Index, double weight, Sequence const& x) \n    {\n      if (sum.empty())\n        sum.resize(boost::fusion::size(x),0);\n      auto i = sum.begin();                           // provide a reference to the iterator\n      boost::fusion::for_each(x,Add(weight,i));       // because that is incremented on each call of Add\n    }                                                 // (hack: for_each requires an immutable functor)\n    \n    void join(SummationCollector const& c)\n    {\n      if (sum.empty())\n        sum = c.sum;\n      else\n      {\n        assert(sum.size()==c.sum.size());\n        for (int i=0; i<sum.size(); ++i)\n          sum[i] += c.sum[i];\n      }\n    }\n\n    std::vector<double> sum;\n\n  private:\n    struct Add\n    {\n      Add(double w_, std::vector<double>::iterator& i_): w(w_), i(i_) {}\n      template <class T>\n      void operator()(T const& t) const { *i += w*t; ++i; }\n      \n    private:\n      double w;\n      std::vector<double>::iterator& i;\n    };\n  };\n\n\n\n\n  /**\n   * \\brief A functor for computing scaled \\f$L^2\\f$-norms of a set of (possibly vector-valued) functions. \n   * \n   * This is intended to be used with gridIterate. The plain \\f$L^2\\f$-norm is computed if the\n   * IdentityScaling is provided.\n   */\n  template <class Functions, class Scaling, class Collector>\n  class ScaledTwoNorm2Collector\n  {\n  public:\n    \n    /**\n     * \\brief Constructor.\n     * \n     * \\param scaling\n     * \\param collector \n     */\n    ScaledTwoNorm2Collector(Scaling const& scaling_, Collector& collector_): scaling(scaling_), collector(collector_) {    }\n\n    template <class Cell>\n    int integrationOrder(Cell const& cell, int shapeFunctionOrder) const\n    {\n      return 2*collector.integrationOrder(cell,shapeFunctionOrder);\n    }\n\n    template <class CellIterator, class Index, class Sequence>\n    void operator()(CellIterator const& ci, Index idx,\n                    Dune::FieldVector<typename CellIterator::Entity::Geometry::ctype,CellIterator::Entity::dimension> const& pos,\n                    Sequence const& seq, double weight)\n    {\n      using namespace boost::fusion;\n      typename result_of::as_vector<Sequence>::type values(seq);\n      scaling.scale(*ci,pos,values);\n      collector(ci,idx,weight,transform(values,TwoNorm2()));\n    }\n\n    void join(ScaledTwoNorm2Collector const& c)\n    {\n      collector.join(c.collector);\n    }\n    \n    Collector const& data() const { return collector; }\n\n  private:\n    // a boost::fusion functor computing the squared euclidean norm of given vectors\n    struct TwoNorm2\n    {\n      template <class T> struct result {};\n\n      template <class Vec>\n      struct result<TwoNorm2(Vec)> { typedef  Dune::FieldVector<double,1> type; };\n\n      template <class Vec>\n      typename result<TwoNorm2(Vec)>::type operator()(Vec const& v) const { return v.two_norm2(); }\n    };\n\n    Scaling const& scaling;\n    Collector collector; // keep collector by value as we write concurrently in different objects.\n  };\n\n  /**\n   * \\brief Evaluates the square of the scaled \\f$L^2\\f$-norms of a set of functions.\n   * \\tparam Variables a boost::fusion sequence of VariableDescription types\n   * \\tparam Functions a boost::fusion sequence of FE function types (or types providing the required interface subset)\n   * \\tparam Spaces\n   * \\tparam Scaling\n   * \\tparam Collector\n   * \n   * \\param varDesc a boost::fusion sequence of VariableDescription entries, e.g. obtained from VariableSetDescription::Variables()\n   * \n   * The required interface subset of FE functions includes the value() and the space() methods.\n   */\n  template <class Variables, class Functions, class Spaces, class Scaling, class Collector>\n  void scaledTwoNormSquared(Variables const& varDesc, Functions const& f, Spaces const& spaces,\n                            Scaling const& scaling, Collector& sum)\n  {\n    ScaledTwoNorm2Collector<Functions,Scaling,Collector> collector(scaling,sum);\n    gridIterate(varDesc,f,spaces,collector);\n    sum = collector.data();\n  }\n\n\n  //---------------------------------------------------------------------\n\n  /**\n   * \\cond internals\n   */\n  namespace relativeErrorDetail {\n\n    template <class F>\n    struct Difference\n    {\n      typedef typename F::Scalar RT;\n      typedef RT Scalar;\n\n      static int const Components = F::components;\n\n      typedef typename F::Space     Space;\n      typedef typename F::ValueType ValueType;\n\n      Difference(F const& f1_, F const& f2_): f1(f1_), f2(f2_) { }\n\n      ValueType value(typename Space::Evaluator const& evaluator) const\n      {\n        return f1.value(evaluator)-f2.value(evaluator);\n      }\n      \n      Space const& space() const { return f1.space(); }\n\n    private:\n      F const& f1;\n      F const& f2;\n    };\n\n\n    struct MakeDifference\n    {\n      template <class T> struct result {};\n\n      template <class Pair>\n      struct result<MakeDifference(Pair)>\n      {\n        typedef typename boost::fusion::result_of::value_at_c<Pair,0>::type T;\n\n        typedef Difference<typename boost::remove_const<typename boost::remove_reference<T>::type>::type> type;\n      };\n\n      template <class Pair>\n      typename result<MakeDifference(Pair)>::type operator()(Pair const& pair) const\n      {\n        return typename result<MakeDifference(Pair)>::type(boost::fusion::at_c<0>(pair),boost::fusion::at_c<1>(pair));\n      }\n    };\n\n\n  } // End of namespace relativeErrorDetail\n  /**\n   * \\endcond\n   */\n\n\n  /**\n   * For each variable, this function computes the following pair of values:\n   * \\f[ (\\|f_1-f_2\\|,\\|f_3\\|) \\f]\n   * \\tparam Variables a boost::fusion sequence of variable descriptions\n   * \\tparam OutIter an output iterator with value type std::pair(double,double)\n   * \\tparam Functions a boost::fusion sequence of finite element functions, referenced by the variable descriptions\n   * \\tparam Spaces a boost::fusion sequence of pointers to spaces, referenced by the variable descriptions\n   * \\tparam Scaling\n   */\n  template <class Variables, class OutIter, class Functions, class Spaces, class Scaling>\n  void relativeError(Variables const& varDesc, Functions const& f1, Functions const& f2, Functions const& f3,\n                     Spaces const& spaces, Scaling const& scaling, OutIter out)\n  {\n    using namespace boost::fusion;\n\n    int const s = size(f1);\n    SummationCollector sum;\n    //   scaledTwoNormSquared(join(varDesc,varDesc),\n    //                        join( f3, as_vector(transform(zip(f1,f2),relativeErrorDetail::MakeDifference())) ),\n    //                        spaces,scaling,sum);\n    scaledTwoNormSquared(join(varDesc,varDesc),\n                         join(as_vector(transform(zip(f1,f2),relativeErrorDetail::MakeDifference())),f3),\n                         spaces,scaling,sum);\n    // To my understanding, the as_vector call in the statement above\n    // should not be necessary. However, it prevents a (rare but\n    // reproducible) segfault with gcc 4.3.4 -O2. Funny thing is, some\n    // output statements to cerr have the same effect. The cause may be\n    // either a wild pointer bug in the code exposed by -O2 or a code\n    // generation bug in gcc.  Sigh. At least, since Difference objects\n    // are lightweight, the explicit vector construction should not be a\n    // performance penalty. ws 2009-12-03\n\n    for (int i=0; i<s; ++i) {\n      *out = std::make_pair(std::sqrt(sum.sum[i]),std::sqrt(sum.sum[i+s]));\n      ++out;\n    }\n  }\n} // end of namespace Kaskade\n\n\n#endif\n", "meta": {"hexsha": "d7c6f1f5c269030766afc1e8eb16e699533b6023", "size": 13656, "ext": "hh", "lang": "C++", "max_stars_repo_path": "Kaskade/fem/iterate_grid.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/iterate_grid.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/iterate_grid.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": 36.126984127, "max_line_length": 141, "alphanum_fraction": 0.6200937317, "num_tokens": 3168, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6261241772283034, "lm_q2_score": 0.48047867804790706, "lm_q1q2_score": 0.3008393169684887}}
{"text": "/*\n * Copyright (c) 2013-2018 Masahide Kashiwagi (kashi@waseda.jp)\n */\n\n#ifndef ODE_AFFINE_HPP\n#define ODE_AFFINE_HPP\n\n// ODE using Affine\n\n#include <iostream>\n#include <cmath>\n#include <algorithm>\n#include <boost/numeric/ublas/vector.hpp>\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/io.hpp>\n#include <kv/interval.hpp>\n#include <kv/rdouble.hpp>\n#include <kv/interval-vector.hpp>\n#include <kv/make-candidate.hpp>\n#include <kv/psa.hpp>\n#include <kv/affine.hpp>\n#include <kv/ode-param.hpp>\n#include <kv/ode-callback.hpp>\n\n\n#ifndef ODE_FAST\n#define ODE_FAST 1\n#endif\n\n#ifndef ODE_RESTART_RATIO\n#define ODE_RESTART_RATIO 1\n#endif\n\n#ifndef ODE_COEF_MID\n#define ODE_CORF_MID 0\n#endif\n\n\n\nnamespace kv {\n\nnamespace ub = boost::numeric::ublas;\n\n\ntemplate <class T, class F>\nint\node_affine(F f, ub::vector< affine<T> >& init, const interval<T>& start, interval<T>& end, ode_param<T> p = ode_param<T>(), ub::vector< psa< interval<T> > >* result_psa = NULL)\n{\n\tint n = init.size();\n\tint i, j;\n\n\tub::vector< psa< affine<T> > > x, y;\n\tpsa< affine<T> > torg;\n\tpsa< affine<T> > t;\n\n\tub::vector< psa< affine<T> > > z, w;\n\n\tpsa< affine<T> > temp;\n\tT m;\n\tub::vector<T> newton_step;\n\n\tbool flag, resized;\n\n\taffine<T> s1, s2;\n\tinterval<T> s2i;\n\t\n\tub::vector< affine<T> > s1_save;\n\tub::vector< interval<T> > s2i_save;\n\n\tinterval<T> deltat;\n\tub::vector< affine<T> > result;\n\n\tT radius, radius_tmp;\n\tT tolerance;\n\tint n_rad;\n\t#if ODE_RESTART_RATIO == 1\n\tT max_ratio;\n\t#endif\n\n\tint ret_val;\n\tinterval<T> end2;\n\tint restart;\n\n\tint maxnum_save = affine<T>::maxnum();\n\n\tbool save_mode, save_uh, save_rh;\n\n\n\tm = 1.;\n\tfor (i=0; i<n; i++) {\n\t\tm = std::max(m, norm(to_interval(init(i))));\n\t}\n\ttolerance = m * p.epsilon;\n\n\tx = init;\n\ttorg.v.resize(2);\n\ttorg.v(0) = start; torg.v(1) = 1.;\n\n\tsave_mode = psa< affine<T> >::mode();\n\tsave_uh = psa< affine<T> >::use_history();\n\tsave_rh = psa< affine<T> >::record_history();\n\tpsa< affine<T> >::mode() = 1;\n\tpsa< affine<T> >::use_history() = false;\n\tpsa< affine<T> >::record_history() = false;\n\t#if ODE_FAST == 1\n\tpsa< affine<T> >::record_history() = true;\n\tpsa< affine<T> >::history().clear();\n\t#endif\n\tfor (j=0; j<p.order; j++) {\n\t\t#if ODE_FAST == 1\n\t\tif (j == 1) psa< affine<T> >::use_history() = true;\n\t\t#endif\n\t\tt = setorder(torg, j);\n\t\ty = f(x, t);\n\t\tfor (i=0; i<n; i++) {\n\t\t\ty(i) = integrate(y(i));\n\t\t\ty(i) = setorder(y(i), j+1);\n\t\t}\n\t\tx = init + y;\n\t}\n\n\tif (p.autostep) {\n\t\tradius = 0.;\n\t\tn_rad = 0;\n\t\tfor (j = p.order; j>=1; j--) {\n\t\t\tm = 0.;\n\t\t\tfor (i=0; i<n; i++) {\n\t\t\t\t#if ODE_COEF_MID == 1\n\t\t\t\tusing std::abs;\n\t\t\t\tm = std::max(m, abs(x(i).v(j).get_mid()));\n\t\t\t\t#else\n\t\t\t\tm = std::max(m, norm(to_interval(x(i).v(j))));\n\t\t\t\t#endif\n\t\t\t}\n\t\t\tif (m == 0.) continue;\n\t\t\tradius = std::max(radius, (T)std::pow((double)m, 1./j));\n\t\t\tn_rad++;\n\t\t\tif (n_rad == 2) break;\n\t\t}\n\t\tradius = std::pow((double)tolerance, 1./p.order) / radius;\n\t}\n\n\tpsa< affine<T> >::mode() = 2;\n\n\trestart = 0;\n\t// disable resize because resize algorithm is not suitable\n\t//  for ode-affine\n\t// resized = false;\n\tresized = true;\n\n\twhile (true) {\n\t\tif (p.autostep) {\n\t\t\tend2 = mid(start + radius);\n\t\t\tif (end2 >= end.lower()) {\n\t\t\t\tend2 = end;\n\t\t\t\tradius = mid(end2 - start);\n\t\t\t\tret_val = 2;\n\t\t\t} else {\n\t\t\t\tret_val = 1;\n\t\t\t}\n\t\t} else {\n\t\t\tend2 = end;\n\t\t\tret_val = 2;\n\t\t}\n\t\tdeltat = end2 - start;\n\n\t\tpsa< affine<T> >::domain() = interval<T>(0., deltat.upper());\n\n\t\tz = x;\n\t\tt = setorder(torg, p.order);\n\n\t\ttry { \n\t\t\tw = f(z, t);\n\t\t}\n\t\tcatch (std::domain_error& e) {\n\t\t\t if (p.autostep && restart < p.restart_max) {\n\t\t\t\tpsa< affine<T> >::use_history() = false;\n\t\t\t\tif (p.verbose == 1) {\n\t\t\t\t\tstd::cout << \"ode: radius changed: \" << radius;\n\t\t\t\t}\n\t\t\t\tradius *= 0.5;\n\t\t\t\tif (p.verbose == 1) {\n\t\t\t\t\tstd::cout << \" -> \" << radius << \"\\n\";\n\t\t\t\t}\n\t\t\t\trestart++;\n\t\t\t\tcontinue;\n\t\t\t} else {\n\t\t\t\tthrow std::domain_error(\"ode_affine: evaluation error\");\n\t\t\t}\n\t\t}\n\n\t\tfor (i=0; i<n; i++) {\n\t\t\ttemp = integrate(w(i));\n\t\t\tw(i) = setorder(temp, p.order);\n\t\t}\n\t\tw = init + w;\n\n\t\tnewton_step.resize(n);\n\t\tfor (i=0; i<n; i++) {\n\t\t\tnewton_step(i) = norm(to_interval(w(i).v(p.order) - z(i).v(p.order)));\n\t\t}\n\t\tmake_candidate(newton_step);\n\n\t\ts1_save.resize(n);\n\t\ts2i_save.resize(n);\n\n\t\tfor (i=0; i<n; i++) {\n\t\t\tz(i).v(p.order) += (affine<T>)(newton_step(i) * interval<T>(-1., 1.));\n\t\t\t#ifdef ODE_AFFINE_SIMPLE\n\t\t\ts2i = to_interval(z(i).v(p.order));\n\t\t\ts2i_save(i) = s2i;\n\t\t\tz(i).v(p.order) = (affine<T>)s2i;\n\t\t\t#else \n\t\t\tsplit(z(i).v(p.order), maxnum_save, s1, s2);\n\t\t\ts2i = to_interval(s2);\n\t\t\ts1_save(i) = s1;\n\t\t\ts2i_save(i) = s2i;\n\t\t\tz(i).v(p.order) = append(s1, (affine<T>)s2i);\n\t\t\t#endif\n\t\t}\n\n\t\tif (p.autostep && ret_val != 2 && resized == false) {\n\t\t\tresized = true;\n\t\t\tm = (std::numeric_limits<T>::min)();\n\t\t\tfor (i=0; i<n; i++) {\n\t\t\t\tm = std::max(m, rad(eval(z(i), (affine<T>)deltat)) - rad(init(i)));\n\t\t\t}\n\t\t\tm = m / tolerance;\n\t\t\tradius_tmp = radius / std::pow((double)m, 1. / p.order);\n\t\t\tif (radius_tmp >= radius && restart > 0) {\n\t\t\t\t// do nothing, not continue\n\t\t\t} else {\n\t\t\t\tradius = radius_tmp;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t}\n\n\t\tw = f(z, t);\n\t\tfor (i=0; i<n; i++) {\n\t\t\ttemp = integrate(w(i));\n\t\t\tw(i) = setorder(temp, p.order);\n\t\t}\n\t\tw = init + w;\n\n\t\tflag = true;\n\t\t#if ODE_RESTART_RATIO == 1\n\t\tmax_ratio = 0.;\n\t\t#endif\n\t\tfor (i=0; i<n; i++) {\n\t\t\t#ifdef ODE_AFFINE_SIMPLE\n\t\t\ts2i = to_interval(w(i).v(p.order));\n\t\t\t#if ODE_RESTART_RATIO == 1\n\t\t\tmax_ratio = std::max(max_ratio, width(s2i) / width(s2i_save(i)));\n\t\t\t#endif\n\t\t\tflag = flag && subset(s2i, s2i_save(i));\n\t\t\ts2i_save(i) = s2i;\n\t\t\tw(i).v(p.order) = (affine<T>)s2i;\n\t\t\t#else\n\t\t\tsplit(w(i).v(p.order), maxnum_save, s1, s2);\n\t\t\ts2i = to_interval(s2);\n\t\t\t#if ODE_RESTART_RATIO == 1\n\t\t\tmax_ratio = std::max(max_ratio, width(to_interval(s1 - s1_save(i)) + s2i) / width(s2i_save(i)));\n\t\t\t#endif\n\t\t\tflag = flag && subset(to_interval(s1 - s1_save(i)) + s2i, s2i_save(i));\n\t\t\ts1_save(i) = s1;\n\t\t\ts2i_save(i) = s2i;\n\t\t\tw(i).v(p.order) = append(s1, (affine<T>)s2i);\n\t\t\t#endif\n\t\t}\n\t\tif (flag) break;\n\n\t\tif (!p.autostep || restart >= p.restart_max) {\n\t\t\tret_val = 0;\n\t\t\tbreak;\n\t\t}\n\t\tif (p.verbose == 1) {\n\t\t\tstd::cout << \"ode: radius changed: \" << radius;\n\t\t}\n\t\t#if ODE_RESTART_RATIO == 1\n\t\tradius *= std::max(std::min((T)0.5, (T)0.5 / max_ratio), (T)0.125);\n\t\t#else\n\t\tradius *= 0.5;\n\t\t#endif\n\t\tif (p.verbose == 1) {\n\t\t\tstd::cout << \" -> \" << radius << \"\\n\";\n\t\t}\n\t\trestart++;\n\t}\n\n\tif (ret_val != 0) {\n\t\tfor (j=0; j<p.iteration; j++) {\n\t\t\tw = f(w, t);\n\t\t\tfor (i=0; i<n; i++) {\n\t\t\t\ttemp = integrate(w(i));\n\t\t\t\tw(i) = setorder(temp, p.order);\n\t\t\t}\n\t\t\tw = init + w;\n\n\t\t\tfor (i=0; i<n; i++) {\n\t\t\t\t#ifdef ODE_AFFINE_SIMPLE\n\t\t\t\ts2i = to_interval(w(i).v(p.order));\n\t\t\t\ts2i = intersect(s2i, s2i_save(i));\n\t\t\t\ts2i_save(i) = s2i;\n\t\t\t\tw(i).v(p.order) = (affine<T>)s2i;\n\t\t\t\t#else\n\t\t\t\tsplit(w(i).v(p.order), maxnum_save, s1, s2);\n\t\t\t\ts2i = to_interval(s2);\n\t\t\t\t// s2i = intersect(to_interval(s1 - s1_save(i)) + s2i, s2i_save(i));\n\t\t\t\ts2i = intersect(to_interval(s1 - s1_save(i)) + s2i_save(i), s2i);\n\t\t\t\ts1_save(i) = s1;\n\t\t\t\ts2i_save(i) = s2i;\n\t\t\t\tw(i).v(p.order) = append(s1, (affine<T>)s2i);\n\t\t\t\t#endif\n\t\t\t}\n\t\t}\n\n\t\tif (result_psa != NULL) {\n\t\t\t// convert w to interval and store it to *result_psa\n\t\t\t(*result_psa).resize(n);\n\t\t\tfor (i=0; i<n; i++) {\n\t\t\t\t(*result_psa)(i).v.resize(w(i).v.size());\n\t\t\t\tfor (j=0; j<w(i).v.size(); j++) {\n\t\t\t\t\t(*result_psa)(i).v(j) = to_interval(w(i).v(j));\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tresult.resize(n);\n\t\tfor (i=0; i<n; i++) {\n\t\t\tresult(i) = eval(w(i), (affine<T>)deltat);\n\t\t\tif (p.ep_reduce == 0) {\n\t\t\t\tsplit(result(i), maxnum_save, s1, s2);\n\t\t\t\ts2i = to_interval(s2);\n\t\t\t\ts1_save(i) = s1;\n\t\t\t\ts2i_save(i) = s2i;\n\t\t\t}\n\t\t}\n\n\t\tif (p.ep_reduce == 0) {\n\t\t\taffine<T>::maxnum() = maxnum_save;\n\t\t\tfor (i=0; i<n; i++) {\n\t\t\t\ts1_save(i).resize();\n\t\t\t\tresult(i) = append(s1_save(i), (affine<T>)s2i_save(i));\n\t\t\t}\n\t\t} else {\n\t\t\tepsilon_reduce(result, p.ep_reduce, p.ep_reduce_limit);\n\t\t}\n\n\t\tinit = result;\n\t\tif (ret_val == 1) end = end2;\n\t}\n\n\tpsa< affine<T> >::mode() = save_mode;\n\tpsa< affine<T> >::use_history() = save_uh;\n\tpsa< affine<T> >::record_history() = save_rh;\n\n\treturn ret_val;\n}\n\ntemplate <class T, class F>\nint\nodelong_affine(\n\tF f,\n\tub::vector< affine<T> >& init,\n\tconst interval<T>& start,\n\tinterval<T>& end,\n\tode_param<T> p = ode_param<T>(),\n\tconst ode_callback<T>& callback = ode_callback<T>()\n) {\n\tint s = init.size();\n\tub::vector< affine<T> > x, x1;\n\tinterval<T> t, t1;\n\tint ret_ode;\n\tint ret_val = 0;\n\tbool ret_callback;\n\n\tub::vector< psa< interval<T> > > result_tmp;\n\n\n\tx = init;\n\tt = start;\n\tp.set_autostep(true);\n\n\twhile (1) {\n\t\tx1 = x;\n\t\tt1 = end;\n\n\t\tret_ode = ode_affine(f, x1, t, t1, p, &result_tmp);\n\t\tif (ret_ode == 0) {\n\t\t\tif (ret_val == 1) {\n\t\t\t\tinit = x1;\n\t\t\t\tend = t;\n\t\t\t}\n\t\t\treturn ret_val;\n\t\t}\n\t\tret_val = 1;\n\t\tif (p.verbose == 1) {\n\t\t\tstd::cout << \"t: \" << t1 << \"\\n\";\n\t\t\tstd::cout << to_interval(x1) << \"\\n\";\n\t\t}\n\n\t\tcallback(t, t1, to_interval(x), to_interval(x1), result_tmp);\n\t\t\n\t\tif (ret_callback == false) {\n\t\t\tinit = x1;\n\t\t\tend = t1;\n\t\t\treturn 3;\n\t\t}\n\n\t\tif (ret_ode == 2) {\n\t\t\tinit = x1;\n\t\t\treturn 2;\n\t\t}\n\n\t\tt = t1;\n\t\tx = x1;\n\t}\n}\n\ntemplate <class T, class F>\nint\nodelong_affine(\n\tF f,\n\tub::vector< interval<T> >& init,\n\tconst interval<T>& start,\n\tinterval<T>& end,\n\tode_param<T> p = ode_param<T>(),\n\tconst ode_callback<T>& callback = ode_callback<T>()\n) {\n\tint s = init.size();\n\tint i;\n\tub::vector< affine<T> > x;\n\tint maxnum_save;\n\tint r;\n\n\tmaxnum_save = affine<T>::maxnum();\n\taffine<T>::maxnum() = 0;\n\n\tx = init;\n\n\tr = odelong_affine(f, x, start, end, p, callback);\n\n\taffine<T>::maxnum() = maxnum_save;\n\n\tif (r == 0) return 0;\n\n\tfor (i=0; i<s; i++) init(i) = to_interval(x(i));\n\n\treturn r;\n}\n\n} // namespace kv\n\n#endif // ODE_AFFINE_HPP\n", "meta": {"hexsha": "24f21c09d1825bfb22d308f406bb5d694bc4fc1a", "size": 9622, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "kv/ode-affine.hpp", "max_stars_repo_name": "soonho-tri/kv", "max_stars_repo_head_hexsha": "4963be6560d8600cdc9ff22d004b2b965ae7b1df", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 67.0, "max_stars_repo_stars_event_min_datetime": "2017-01-04T15:30:54.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T05:45:02.000Z", "max_issues_repo_path": "src/interval/kv/ode-affine.hpp", "max_issues_repo_name": "takafumihoriuchi/HyLaGI", "max_issues_repo_head_hexsha": "26b9f32a84611ee62d9cbbd903773d224088c959", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2017-02-10T02:59:45.000Z", "max_issues_repo_issues_event_max_datetime": "2019-10-10T14:17:08.000Z", "max_forks_repo_path": "src/interval/kv/ode-affine.hpp", "max_forks_repo_name": "takafumihoriuchi/HyLaGI", "max_forks_repo_head_hexsha": "26b9f32a84611ee62d9cbbd903773d224088c959", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2021-09-29T02:27:46.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T05:45:04.000Z", "avg_line_length": 21.1472527473, "max_line_length": 176, "alphanum_fraction": 0.5690085221, "num_tokens": 3565, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5621765008857981, "lm_q2_score": 0.5350984286266116, "lm_q1q2_score": 0.30081976223479745}}
{"text": "#include \"Proof.hpp\"\n\n#include \"crypto/common.h\"\n\n#include <boost/static_assert.hpp>\n#include <libsnark/common/default_types/r1cs_ppzksnark_pp.hpp>\n#include <libsnark/zk_proof_systems/ppzksnark/r1cs_ppzksnark/r1cs_ppzksnark.hpp>\n#include <mutex>\n\nusing namespace libsnark;\n\ntypedef alt_bn128_pp curve_pp;\ntypedef alt_bn128_pp::G1_type curve_G1;\ntypedef alt_bn128_pp::G2_type curve_G2;\ntypedef alt_bn128_pp::GT_type curve_GT;\ntypedef alt_bn128_pp::Fp_type curve_Fr;\ntypedef alt_bn128_pp::Fq_type curve_Fq;\ntypedef alt_bn128_pp::Fqe_type curve_Fq2;\n\nBOOST_STATIC_ASSERT(sizeof(mp_limb_t) == 8);\n\nnamespace libvcoin {\n\n// FE2IP as defined in the protocol spec and IEEE Std 1363a-2004.\nbigint<8> fq2_to_bigint(const curve_Fq2 &e)\n{\n    auto modq = curve_Fq::field_char();\n    auto c0 = e.c0.as_bigint();\n    auto c1 = e.c1.as_bigint();\n\n    bigint<8> temp = c1 * modq;\n    temp += c0;\n    return temp;\n}\n\n// Writes a bigint in big endian\ntemplate<mp_size_t LIMBS>\nvoid write_bigint(base_blob<8 * LIMBS * sizeof(mp_limb_t)> &blob, const bigint<LIMBS> &val)\n{\n    auto ptr = blob.begin();\n    for (ssize_t i = LIMBS-1; i >= 0; i--, ptr += 8) {\n        WriteBE64(ptr, val.data[i]);\n    }\n}\n\n// Reads a bigint from big endian\ntemplate<mp_size_t LIMBS>\nbigint<LIMBS> read_bigint(const base_blob<8 * LIMBS * sizeof(mp_limb_t)> &blob)\n{\n    bigint<LIMBS> ret;\n\n    auto ptr = blob.begin();\n\n    for (ssize_t i = LIMBS-1; i >= 0; i--, ptr += 8) {\n        ret.data[i] = ReadBE64(ptr);\n    }\n\n    return ret;\n}\n\ntemplate<>\nFq::Fq(curve_Fq element) : data()\n{\n    write_bigint<4>(data, element.as_bigint());\n}\n\ntemplate<>\ncurve_Fq Fq::to_libsnark_fq() const\n{\n    auto element_bigint = read_bigint<4>(data);\n\n    // Check that the integer is smaller than the modulus\n    auto modq = curve_Fq::field_char();\n    element_bigint.limit(modq, \"element is not in Fq\");\n\n    return curve_Fq(element_bigint);\n}\n\ntemplate<>\nFq2::Fq2(curve_Fq2 element) : data()\n{\n    write_bigint<8>(data, fq2_to_bigint(element));\n}\n\ntemplate<>\ncurve_Fq2 Fq2::to_libsnark_fq2() const\n{\n    bigint<4> modq = curve_Fq::field_char();\n    bigint<8> combined = read_bigint<8>(data);\n    bigint<5> res;\n    bigint<4> c0;\n    bigint<8>::div_qr(res, c0, combined, modq);\n    bigint<4> c1 = res.shorten(modq, \"element is not in Fq2\");\n\n    return curve_Fq2(curve_Fq(c0), curve_Fq(c1));\n}\n\ntemplate<>\nCompressedG1::CompressedG1(curve_G1 point)\n{\n    if (point.is_zero()) {\n        throw std::domain_error(\"curve point is zero\");\n    }\n\n    point.to_affine_coordinates();\n\n    x = Fq(point.X);\n    y_lsb = point.Y.as_bigint().data[0] & 1;\n}\n\ntemplate<>\ncurve_G1 CompressedG1::to_libsnark_g1() const\n{\n    curve_Fq x_coordinate = x.to_libsnark_fq<curve_Fq>();\n\n    // y = +/- sqrt(x^3 + b)\n    auto y_coordinate = ((x_coordinate.squared() * x_coordinate) + alt_bn128_coeff_b).sqrt();\n\n    if ((y_coordinate.as_bigint().data[0] & 1) != y_lsb) {\n        y_coordinate = -y_coordinate;\n    }\n\n    curve_G1 r = curve_G1::one();\n    r.X = x_coordinate;\n    r.Y = y_coordinate;\n    r.Z = curve_Fq::one();\n\n    assert(r.is_well_formed());\n\n    return r;\n}\n\ntemplate<>\nCompressedG2::CompressedG2(curve_G2 point)\n{\n    if (point.is_zero()) {\n        throw std::domain_error(\"curve point is zero\");\n    }\n\n    point.to_affine_coordinates();\n\n    x = Fq2(point.X);\n    y_gt = fq2_to_bigint(point.Y) > fq2_to_bigint(-(point.Y));\n}\n\ntemplate<>\ncurve_G2 CompressedG2::to_libsnark_g2() const\n{\n    auto x_coordinate = x.to_libsnark_fq2<curve_Fq2>();\n\n    // y = +/- sqrt(x^3 + b)\n    auto y_coordinate = ((x_coordinate.squared() * x_coordinate) + alt_bn128_twist_coeff_b).sqrt();\n    auto y_coordinate_neg = -y_coordinate;\n\n    if ((fq2_to_bigint(y_coordinate) > fq2_to_bigint(y_coordinate_neg)) != y_gt) {\n        y_coordinate = y_coordinate_neg;\n    }\n\n    curve_G2 r = curve_G2::one();\n    r.X = x_coordinate;\n    r.Y = y_coordinate;\n    r.Z = curve_Fq2::one();\n\n    assert(r.is_well_formed());\n\n    if (alt_bn128_modulus_r * r != curve_G2::zero()) {\n        throw std::runtime_error(\"point is not in G2\");\n    }\n\n    return r;\n}\n\ntemplate<>\nPHGRProof::PHGRProof(const r1cs_ppzksnark_proof<curve_pp> &proof)\n{\n    g_A = CompressedG1(proof.g_A.g);\n    g_A_prime = CompressedG1(proof.g_A.h);\n    g_B = CompressedG2(proof.g_B.g);\n    g_B_prime = CompressedG1(proof.g_B.h);\n    g_C = CompressedG1(proof.g_C.g);\n    g_C_prime = CompressedG1(proof.g_C.h);\n    g_K = CompressedG1(proof.g_K);\n    g_H = CompressedG1(proof.g_H);\n}\n\ntemplate<>\nr1cs_ppzksnark_proof<curve_pp> PHGRProof::to_libsnark_proof() const\n{\n    r1cs_ppzksnark_proof<curve_pp> proof;\n\n    proof.g_A.g = g_A.to_libsnark_g1<curve_G1>();\n    proof.g_A.h = g_A_prime.to_libsnark_g1<curve_G1>();\n    proof.g_B.g = g_B.to_libsnark_g2<curve_G2>();\n    proof.g_B.h = g_B_prime.to_libsnark_g1<curve_G1>();\n    proof.g_C.g = g_C.to_libsnark_g1<curve_G1>();\n    proof.g_C.h = g_C_prime.to_libsnark_g1<curve_G1>();\n    proof.g_K = g_K.to_libsnark_g1<curve_G1>();\n    proof.g_H = g_H.to_libsnark_g1<curve_G1>();\n\n    return proof;\n}\n\nPHGRProof PHGRProof::random_invalid()\n{\n    PHGRProof p;\n    p.g_A = curve_G1::random_element();\n    p.g_A_prime = curve_G1::random_element();\n    p.g_B = curve_G2::random_element();\n    p.g_B_prime = curve_G1::random_element();\n    p.g_C = curve_G1::random_element();\n    p.g_C_prime = curve_G1::random_element();\n\n    p.g_K = curve_G1::random_element();\n    p.g_H = curve_G1::random_element();\n\n    return p;\n}\n\nstatic std::once_flag init_public_params_once_flag;\n\nvoid initialize_curve_params()\n{\n    std::call_once (init_public_params_once_flag, curve_pp::init_public_params);\n}\n\nProofVerifier ProofVerifier::Strict() {\n    initialize_curve_params();\n    return ProofVerifier(true);\n}\n\nProofVerifier ProofVerifier::Disabled() {\n    initialize_curve_params();\n    return ProofVerifier(false);\n}\n\ntemplate<>\nbool ProofVerifier::check(\n    const r1cs_ppzksnark_verification_key<curve_pp>& vk,\n    const r1cs_ppzksnark_processed_verification_key<curve_pp>& pvk,\n    const r1cs_primary_input<curve_Fr>& primary_input,\n    const r1cs_ppzksnark_proof<curve_pp>& proof\n)\n{\n    if (perform_verification) {\n        return r1cs_ppzksnark_online_verifier_strong_IC<curve_pp>(pvk, primary_input, proof);\n    } else {\n        return true;\n    }\n}\n\n}\n", "meta": {"hexsha": "cb56f64283595a5908cbe5e59e4e2844458db56f", "size": 6257, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/vcoin/Proof.cpp", "max_stars_repo_name": "vcurrency/vcoin", "max_stars_repo_head_hexsha": "5d6cbccad3fe2b59d7b4195377068504f780ee1a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-08-05T12:22:35.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-29T03:32:24.000Z", "max_issues_repo_path": "src/vcoin/Proof.cpp", "max_issues_repo_name": "vcurrency/vcoin", "max_issues_repo_head_hexsha": "5d6cbccad3fe2b59d7b4195377068504f780ee1a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/vcoin/Proof.cpp", "max_forks_repo_name": "vcurrency/vcoin", "max_forks_repo_head_hexsha": "5d6cbccad3fe2b59d7b4195377068504f780ee1a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-09-21T02:46:56.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-21T02:46:56.000Z", "avg_line_length": 24.8293650794, "max_line_length": 99, "alphanum_fraction": 0.6837142401, "num_tokens": 1948, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7248702761768248, "lm_q2_score": 0.41489884579676883, "lm_q1q2_score": 0.30074784093814966}}
{"text": "/* Copyright 2017 Ramakrishnan Kannan */\n\n#ifndef COMMON_TENSOR_HPP_\n#define COMMON_TENSOR_HPP_\n\n#include <cblas.h>\n#include <armadillo>\n#include <fstream>\n#include <ios>\n#include <random>\n#include <string>\n#include <type_traits>\n#include <utility>\n#include <vector>\n#include \"common/utils.h\"\n\nnamespace planc {\n/**\n * Data is stored such that the unfolding \\f$Y_0\\f$ is column\n * major.  This means the flattening \\f$Y_{N-1}\\f$ is row-major,\n * and any other flattening \\f$Y_n\\f$ can be represented as a set\n * of \\f$\\prod\\limits_{k=n+1}^{N-1}I_k\\f$ row major matrices, each\n * of which is \\f$I_n \\times \\prod\\limits_{k=0}^{n-1}I_k\\f$.\n */\n\n// sgemm (TRANSA, TRANSB, M, N, K, ALPHA, A, LDA, B, LDB, BETA, C, LDC)\n// extern \"C\" void dgemm_(const char*, const char*, const int*,\n//                      const int*, const int*, const double*, const double*,\n//                      const int*, const double*, const int*, const double*,\n//                      double*, const int*);\n\nclass Tensor {\n private:\n  int m_modes;\n  UVEC m_dimensions;\n  UWORD m_numel;\n  UVEC m_global_idx;\n  unsigned int rand_seed;\n\n  // for the time being it is used for debugging purposes\n  size_t sub2ind(UVEC sub, UVEC dimensions) {\n    assert(sub.n_rows == dimensions.n_rows);\n    UVEC cumprod_dims = arma::cumprod(dimensions);\n    UVEC cumprod_dims_shifted = arma::shift(cumprod_dims, 1);\n    cumprod_dims_shifted(0) = 1;\n    size_t idx = arma::dot(cumprod_dims_shifted, sub);\n    return idx;\n  }\n  UVEC ind2sub(UVEC dimensions, size_t idx) {\n    //   k = [1 cumprod(siz(1 : end - 1))];\n    //   n = length(siz);\n    //   idx = idx - 1;\n    // for i = n : -1 : 1\n    //   div = floor(idx / k(i));\n    //   subs( :, i) = div + 1;\n    //   idx = idx - k(i) * div;\n    // end\n    UVEC cumprod_dims = arma::cumprod(dimensions);\n    UVEC cumprod_dims_shifted = arma::shift(cumprod_dims, 1);\n    cumprod_dims_shifted(0) = 1;\n    int modes = dimensions.n_elem;\n    UVEC sub = arma::zeros<UVEC>(modes);\n    float temp;\n    for (int i = modes - 1; i >= 0; i--) {\n      temp = std::floor((idx * 1.0) / (cumprod_dims_shifted(i) * 1.0));\n      sub(i) = temp;\n      idx = idx - cumprod_dims_shifted(i) * temp;\n    }\n    return sub;\n  }\n\n public:\n  std::vector<double> m_data;\n\n  Tensor() {\n    this->m_modes = 0;\n    this->m_numel = 0;\n  }\n  /**\n   * Constructor that takes only dimensions of every mode as a vector\n   */\n  explicit Tensor(const UVEC &i_dimensions)\n      : m_modes(i_dimensions.n_rows),\n        m_dimensions(i_dimensions),\n        m_numel(arma::prod(i_dimensions)),\n        rand_seed(103) {\n    m_data.resize(m_numel);\n    randu();\n  }\n  Tensor(const UVEC &i_dimensions, const UVEC &i_start_idx)\n      : m_modes(i_dimensions.n_rows),\n        m_dimensions(i_dimensions),\n        m_numel(arma::prod(i_dimensions)),\n        m_global_idx(i_start_idx),\n        rand_seed(103) {\n    m_data.resize(m_numel);\n    randu();\n  }\n  /**\n   * Need when copying from matrix to Tensor. otherwise copy constructor\n   * will be called. The data will be passed in row major order\n   *\n   */\n  Tensor(const UVEC &i_dimensions, double *i_data)\n      : m_modes(i_dimensions.n_rows),\n        m_dimensions(i_dimensions),\n        m_numel(arma::prod(i_dimensions)),\n        rand_seed(103) {\n    m_data.resize(m_numel);\n    memcpy(&this->m_data[0], i_data, sizeof(double) * this->m_numel);\n  }\n  ~Tensor() {}\n\n  /**\n   *  copy constructor\n   */\n  Tensor(const Tensor &src) {\n    clear();\n    this->m_numel = src.numel();\n    this->m_modes = src.modes();\n    this->m_dimensions = src.dimensions();\n    this->m_global_idx = src.global_idx();\n    this->rand_seed = 103;\n    this->m_data = src.m_data;\n  }\n\n  Tensor &operator=(const Tensor &other) {  // copy assignment\n    if (this != &other) {                   // self-assignment check expected\n      clear();\n      // this->m_data = new double[other.numel()];  // create storage in this\n      this->m_numel = other.numel();\n      this->m_modes = other.modes();\n      this->m_dimensions = other.dimensions();\n      this->m_global_idx = other.global_idx();\n      this->m_data = other.m_data;\n    }\n    return *this;\n  }\n\n  void swap(Tensor &in) {\n    using std::swap;\n    swap(m_numel, in.m_numel);\n    swap(m_modes, in.m_modes);\n    swap(m_dimensions, in.m_dimensions);\n    swap(m_global_idx, in.m_global_idx);\n    swap(rand_seed, in.rand_seed);\n    swap(m_data, in.m_data);\n  }\n  /**\n   * Clears the data and also destroys the storage\n   */\n\n  void clear() {\n    this->m_numel = 0;\n    this->m_data.clear();\n  }\n\n  /// Return the number of modes. It is a scalar value.\n  int modes() const { return m_modes; }\n  /// Returns a vector of dimensions on every mode\n  UVEC dimensions() const { return m_dimensions; }\n  UVEC global_idx() const { return m_global_idx; }\n\n  /**\n   * Returns the dimension of the input mode.\n   * @param[in] a mode of the tensor.\n   * @return dimension of ith mode\n   */\n\n  int dimension(int i) const { return m_dimensions[i]; }\n  /// Returns total number of elements\n  UWORD numel() const { return m_numel; }\n\n  void set_idx(const UVEC &i_start_idx) { m_global_idx = i_start_idx; }\n  /**\n   * Return the product of dimensions except mode i\n   * @param[in] mode i\n   * @return product of dimensions except mode i\n   */\n  UWORD dimensions_leave_out_one(int i) const {\n    UWORD rc = arma::prod(this->m_dimensions);\n    return rc - this->m_dimensions(i);\n  }\n  /// Zeros out the entire tensor\n  void zeros() {\n    for (UWORD i = 0; i < this->m_numel; i++) {\n      this->m_data[i] = 0;\n    }\n  }\n  /// set the tensor with uniform random.\n  void rand() {\n#pragma omp parallel for\n    for (UWORD i = 0; i < this->m_numel; i++) {\n      unsigned int *temp = const_cast<unsigned int *>(&rand_seed);\n      this->m_data[i] =\n          static_cast<double>(rand_r(temp)) / static_cast<double>(RAND_MAX);\n    }\n  }\n  /// set the tensor with uniform int values\n  void randi() {\n    std::random_device rd;\n    std::mt19937 gen(rd());\n    int max_randi = this->m_numel;\n    std::uniform_int_distribution<> dis(0, max_randi);\n#pragma omp parallel for\n    for (UWORD i = 0; i < this->m_numel; i++) {\n      this->m_data[i] = dis(gen);\n    }\n  }\n  /**\n   * set the tensor with uniform random values starting with a seed.\n   * can be used to generate the same tensor again and again.\n   * @param[in] an integer seed value preferrably a relative prime number\n   */\n  void randu(const int i_seed = -1) {\n    std::random_device rd;\n    std::uniform_real_distribution<> dis(0, 1);\n    if (i_seed == -1) {\n      std::mt19937 gen(rand_seed);\n#pragma omp parallel for\n      for (unsigned int i = 0; i < this->m_numel; i++) {\n        m_data[i] = dis(gen);\n      }\n    } else {\n      std::mt19937 gen(i_seed);\n#pragma omp parallel for\n      for (unsigned int i = 0; i < this->m_numel; i++) {\n        m_data[i] = dis(gen);\n      }\n    }\n  }\n\n  /**\n   * size of krp must be product of all dimensions leaving out nxk.\n   * o_mttkrp will be of size dimension[n]xk.\n   * Memory must be allocated and freed by the caller\n   * @param[in]  i_n mode number\n   * @param[in]  i_krp Khatri-rao product matrix leaving out mode i_n\n   * @param[out] o_mttkrp pointer to the mttkrp matrix.\n   */\n\n  void mttkrp(const int i_n, const MAT &i_krp, MAT *o_mttkrp) const {\n    (*o_mttkrp).zeros();\n    if (i_n == 0) {\n      // if n == 1\n      // Ur = khatrirao(U{2: N}, 'r');\n      // Y = reshape(X.data, szn, szr);\n      // V =  Y * Ur;\n      // Compute number of columns of Y_n\n      // Technically, we could divide the total number of entries by n,\n      // but that seems like a bad decision\n      // size_t ncols = arma::prod(this->m_dimensions);\n      // ncols /= this->m_dimensions[0];\n      // Call matrix matrix multiply\n      // call dgemm (TRANSA, TRANSB, M, N, K, ALPHA, A, LDA, B, LDB, BETA, C,\n      // LDC) C := alpha*op( A )*op( B ) + beta*C A, B and C are matrices, with\n      // op( A ) an m by k matrix, op( B ) a k by n matrix and C an m by n\n      // matrix. matricized tensor is m x k is in column major format krp is k x\n      // n is in column major format output is m x n in column major format\n      // char transa = 'N';\n      // char transb = 'N';\n      int m = this->m_dimensions[0];\n      int n = i_krp.n_cols;\n      int k = i_krp.n_rows;\n      // int lda = m;\n      // int ldb = k;\n      // int ldc = m;\n      double alpha = 1;\n      double beta = 0;\n      // sgemm (TRANSA, TRANSB, M, N, K, ALPHA, A, LDA, B, LDB, BETA, C, LDC)\n      // dgemm_(&transa, &transb, &m, &n, &k, &alpha, this->m_data,\n      // &lda, i_krp.memptr(), &ldb, &beta, o_mttkrp->memptr() , &ldc);\n      // printf(\"mode=%d,i=%d,m=%d,n=%d,k=%d,alpha=%lf,T_stride=%d,lda=%d,krp_stride=%d,ldb=%d,beat=%lf,mttkrp=!!!,ldc=%d\\n\",0,\n      // 0, m, n, k,alpha,0*k*m,m,0*n*k,i_krp.n_rows,beta,n);\n      cblas_dgemm(CblasRowMajor, CblasTrans, CblasTrans, m, n, k, alpha,\n                  &this->m_data[0], m, i_krp.memptr(), k, beta,\n                  o_mttkrp->memptr(), n);\n\n    } else {\n      int ncols = 1;\n      int nmats = 1;\n      int lowrankk = i_krp.n_cols;\n\n      // Count the number of columns\n      for (int i = 0; i < i_n; i++) {\n        ncols *= this->m_dimensions[i];\n      }\n\n      // Count the number of matrices\n      for (int i = i_n + 1; i < this->m_modes; i++) {\n        nmats *= this->m_dimensions[i];\n      }\n      // For each matrix...\n      for (int i = 0; i < nmats; i++) {\n        // char transa = 'T';\n        // char transb = 'N';\n        int m = this->m_dimensions[i_n];\n        int n = lowrankk;\n        int k = ncols;\n        // int lda = k;  // not sure. could be m. higher confidence on k.\n        // int ldb = i_krp.n_rows;\n        // int ldc = m;\n        double alpha = 1;\n        double beta = (i == 0) ? 0 : 1;\n        // double *A = this->m_data + i * k * m;\n        // double *B = const_cast<double *>(i_krp.memptr()) + i * k;\n\n        // for KRP move ncols*lowrankk\n        // for tensor X move as n_cols*blas_n\n        // For output matrix don't move anything as beta=1;\n        // for reference from gram while moving input tensor like\n        // Y->data()+i*nrows*ncols sgemm (TRANSA, TRANSB, M, N, K, ALPHA, A,\n        // LDA, B, LDB, BETA, C, LDC)\n        // dgemm_(&transa, &transb, &m, &n, &k, &alpha, A,\n        // &lda, B , &ldb, &beta, (*o_mttkrp).memptr() , &ldc);\n        // printf(\"mode=%d,i=%d,m=%d,n=%d,k=%d,alpha=%lf,T_stride=%d,lda=%d,krp_stride=%d,ldb=%d,beat=%lf,mttkrp=!!!,ldc=%d\\n\",i_n,\n        // i, m, n, k,alpha,i*k*m,k,i*n*k,nmats*ncols,beta,n);\n        cblas_dgemm(CblasRowMajor, CblasNoTrans, CblasTrans, m, n, k, alpha,\n                    &this->m_data[0] + i * k * m, ncols, i_krp.memptr() + i * k,\n                    ncols * nmats, beta, o_mttkrp->memptr(), n);\n      }\n    }\n  }\n  /// prints the value of the tensor.\n  void print() const {\n    INFO << \"Dimensions: \" << this->m_dimensions;\n    for (unsigned int i = 0; i < this->m_numel; i++) {\n      std::cout << i << \" : \" << this->m_data[i] << std::endl;\n    }\n  }\n\n  void print(const UVEC &global_dims, const UVEC &global_start_sub) {\n    UVEC local_sub = arma::zeros<UVEC>(global_dims.n_elem);\n    // UVEC global_start_sub = ind2sub(global_dims, global_start_idx);\n    UVEC global_sub = arma::zeros<UVEC>(global_dims.n_elem);\n    int global_idx;\n    for (unsigned int i = 0; i < this->m_numel; i++) {\n      local_sub = ind2sub(this->m_dimensions, i);\n      global_sub = global_start_sub + local_sub;\n      global_idx = sub2ind(global_sub, global_dims);\n      std::cout << i << \" : \" << global_idx << \" : \" << this->m_data[i]\n                << std::endl;\n    }\n  }\n  /// returns the frobenius norm of the tensor\n  double norm() const {\n    double norm_fro = 0;\n    for (unsigned int i = 0; i < this->m_numel; i++) {\n      norm_fro += (this->m_data[i] * this->m_data[i]);\n    }\n    return norm_fro;\n  }\n  /**\n   * Computes the squared error with the input tensor\n   * @param[in] b an input tensor\n   */\n  double err(const Tensor &b) const {\n    double norm_fro = 0;\n    double err_diff;\n    for (unsigned int i = 0; i < this->m_numel; i++) {\n      err_diff = this->m_data[i] - b.m_data[i];\n      norm_fro += err_diff * err_diff;\n    }\n    return norm_fro;\n  }\n  /**\n   * Scales the tensor with the constant value.\n   * @param[in] scale can be an int, float or double value\n   */\n\n  template <typename NumericType>\n  void scale(NumericType scale) {\n    // static_assert(std::is_arithmetic<NumericType>::value,\n    //               \"NumericType for scale operation must be numeric\");\n    for (unsigned int i = 0; i < this->m_numel; i++) {\n      this->m_data[i] = this->m_data[i] * scale;\n    }\n  }\n  /**\n   * Shifts (add or subtract) the tensor with the constant value.\n   * If the i_shift is negative it subtracts, otherwise it adds.\n   * @param[in] i_shift can be an int, float or double value\n   */\n  template <typename NumericType>\n  void shift(NumericType i_shift) {\n    // static_assert(std::is_arithmetic<NumericType>::value,\n    //               \"NumericType for shift operation must be numeric\");\n    for (unsigned int i = 0; i < this->m_numel; i++) {\n      this->m_data[i] = this->m_data[i] + i_shift;\n    }\n  }\n  /**\n   * Truncate all the value between min and max. Any value beyond\n   * the min and max will be truncated to min and max.\n   * @param[in] min - any value less than min will be set to min\n   * @param[in] max - any value greater than max will be set to max\n   */\n  template <typename NumericType>\n  void bound(NumericType min, NumericType max) {\n    // static_assert(std::is_arithmetic<NumericType>::value,\n    //               \"NumericType for bound operation must be numeric\");\n    for (unsigned int i = 0; i < this->m_numel; i++) {\n      if (this->m_data[i] < min) this->m_data[i] = min;\n      if (this->m_data[i] > max) this->m_data[i] = max;\n    }\n  }\n  /**\n   * Sets only the lower bound\n   * @param[in] min - any value less than min will be set to min\n   */\n\n  template <typename NumericType>\n  void lower_bound(NumericType min) {\n    // static_assert(std::is_arithmetic<NumericType>::value,\n    //               \"NumericType for bound operation must be numeric\");\n    for (unsigned int i = 0; i < this->m_numel; i++) {\n      if (this->m_data[i] < min) this->m_data[i] = min;\n    }\n  }\n\n  /**\n   * Write the tensor to the given filename. Compile with\n   * -D_FILE_OFFSET_BITS=64 to support large files greater than 2GB\n   * @param[in] filename as std::string\n   */\n  void write(std::string filename,\n             std::ios_base::openmode mode = std::ios_base::out) {\n    std::string filename_no_extension =\n        filename.substr(0, filename.find_last_of(\".\"));\n    // info file always in text mode\n    filename_no_extension.append(\".info\");\n    std::ofstream ofs;\n    ofs.open(filename_no_extension, std::ios_base::out);\n    // write modes\n    ofs << this->m_modes << std::endl;\n    // dimension of modes\n    for (int i = 0; i < this->m_modes; i++) {\n      ofs << this->m_dimensions[i] << std::endl;\n    }\n    ofs << std::endl;\n    ofs.close();\n    FILE *fp = fopen(filename.c_str(), \"wb\");\n    INFO << \"size of the outputfile in GB \"\n         << (this->m_numel * 8.0) / (1024 * 1024 * 1024) << std::endl;\n    size_t nwrite =\n        fwrite(&this->m_data[0], sizeof(std::vector<double>::value_type),\n               this->numel(), fp);\n    if (nwrite != this->numel()) {\n      WARN << \"something wrong ::write::\" << nwrite\n           << \"::numel::\" << this->numel() << std::endl;\n    }\n    fclose(fp);\n  }\n  /**\n   * Reads a tensor from the file. Compile with\n   * -D_FILE_OFFSET_BITS=64 to support large files greater than 2GB\n   * @param[in] filename as std::string\n   */\n\n  void read(std::string filename,\n            std::ios_base::openmode mode = std::ios_base::in) {\n    // clear existing tensor\n    if (this->m_numel > 0) {\n      this->m_data.clear();  // destroy storage in this\n      this->m_numel = 0;\n    }\n    std::string filename_no_extension =\n        filename.substr(0, filename.find_last_of(\".\"));\n    filename_no_extension.append(\".info\");\n\n    std::ifstream ifs;\n    // info file always in text mode\n    ifs.open(filename_no_extension, std::ios_base::in);\n    // write modes\n    ifs >> this->m_modes;\n    // dimension of modes\n    this->m_dimensions = arma::zeros<UVEC>(this->m_modes);\n    for (int i = 0; i < this->m_modes; i++) {\n      ifs >> this->m_dimensions[i];\n    }\n    ifs.close();\n    // ifs.open(filename, mode);\n    FILE *fp = fopen(filename.c_str(), \"rb\");\n    this->m_numel = arma::prod(this->m_dimensions);\n    this->m_data.resize(this->m_numel);\n    // for (int i = 0; i < this->m_numel; i++) {\n    //   ifs >> this->m_data[i];\n    // }\n    // ifs.read(reinterpret_cast<char *>(this->m_data), sizeof(this->m_data));\n    size_t nread =\n        fread(&this->m_data[0], sizeof(std::vector<double>::value_type),\n              this->numel(), fp);\n    if (nread != this->numel()) {\n      WARN << \"something wrong ::write::\" << nread\n           << \"::numel::\" << this->numel() << std::endl;\n    }\n    // Close the file\n    fclose(fp);\n  }\n\n  /**\n   * Given a vector of subscripts, it return the linear index\n   * in the tensor.\n   * @param[in] vector of subscript\n   * @return linear index within the tensor\n   */\n\n  UWORD sub2ind(UVEC sub) {\n    assert(sub.n_cols == this->m_dimensions.n_cols);\n    UVEC cumprod_dims = arma::cumprod(this->m_dimensions);\n    UVEC cumprod_dims_shifted = arma::shift(cumprod_dims, 1);\n    cumprod_dims_shifted(0) = 1;\n    size_t idx = arma::dot(cumprod_dims_shifted, sub);\n    return idx;\n  }\n  double at(UVEC sub) { return m_data[sub2ind(sub)]; }\n};  // class Tensor\n}  // namespace planc\n\nvoid swap(planc::Tensor &x, planc::Tensor &y) { x.swap(y); }\n\n#endif  // COMMON_TENSOR_HPP_\n", "meta": {"hexsha": "0b30cf0d53324ace08b864c8fe0daea9c0481e55", "size": 17671, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "planc-master/common/tensor.hpp", "max_stars_repo_name": "lanl/DnMFkCPP", "max_stars_repo_head_hexsha": "a6bca290bf7d57be07f7a80d049d6b7714fbdc61", "max_stars_repo_licenses": ["BSD-3-Clause", "Unlicense"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-07-29T21:56:02.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-29T21:56:02.000Z", "max_issues_repo_path": "planc-master/common/tensor.hpp", "max_issues_repo_name": "rvangara/DnMFk", "max_issues_repo_head_hexsha": "a6bca290bf7d57be07f7a80d049d6b7714fbdc61", "max_issues_repo_licenses": ["BSD-3-Clause", "Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "planc-master/common/tensor.hpp", "max_forks_repo_name": "rvangara/DnMFk", "max_forks_repo_head_hexsha": "a6bca290bf7d57be07f7a80d049d6b7714fbdc61", "max_forks_repo_licenses": ["BSD-3-Clause", "Unlicense"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-07-29T21:55:33.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-02T21:30:15.000Z", "avg_line_length": 33.7877629063, "max_line_length": 131, "alphanum_fraction": 0.5939675174, "num_tokens": 5290, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5660185498374789, "lm_q2_score": 0.5312093733737563, "lm_q1q2_score": 0.3006743591770894}}
{"text": "#pragma once\n#include <memory>\n\n#include <Eigen/Dense>\n#include <Eigen/Eigenvalues>\n#include <Eigen/Sparse>\n\n#include \"../Univariate.hpp\"\n#include \"../Variable.hpp\"\n#include \"../utils.hpp\"\n\n#include \"Operator.hpp\"\n#include \"SumLocalHam.hpp\"\n\nnamespace yavque\n{\n\nclass SumLocalHamEvol final : public Operator, public Univariate\n{\nprivate:\n\tbool conjugate_ = false;\n\tstd::shared_ptr<const detail::SumLocalHamImpl> ham_;\n\n\tvoid dagger_in_place_impl() override { conjugate_ = !conjugate_; }\n\n\tSumLocalHamEvol(SumLocalHamEvol&&) = default;\n\tSumLocalHamEvol(const SumLocalHamEvol&) = default;\n\npublic:\n\texplicit SumLocalHamEvol(const SumLocalHam& ham)\n\t\t: Operator(ham.dim(), \"SumLocalHamEvol of \" + ham.name()), ham_{ham.get_impl()}\n\t{\n\t}\n\n\texplicit SumLocalHamEvol(const SumLocalHam& ham, Variable var)\n\t\t: Operator(ham.dim(), \"SumLocalHamEvol of \" + ham.name()),\n\t\t  Univariate(std::move(var)), ham_{ham.get_impl()}\n\t{\n\t}\n\n\tSumLocalHamEvol& operator=(const SumLocalHamEvol&) = delete;\n\tSumLocalHamEvol& operator=(SumLocalHamEvol&&) = delete;\n\n\t~SumLocalHamEvol() override = default;\n\n\t[[nodiscard]] std::unique_ptr<Operator> clone() const override\n\t{\n\t\tauto p = std::unique_ptr<SumLocalHamEvol>{new SumLocalHamEvol(*this)};\n\t\tp->change_variable(Variable{var_.value()});\n\t\treturn p;\n\t}\n\n\t[[nodiscard]] std::unique_ptr<Operator> log_deriv() const override\n\t{\n\t\tconstexpr std::complex<double> I(0., 1.0);\n\t\tstd::string op_name = std::string(\"derivative of \") + name(); // change to fmt\n\t\tcx_double constant = conjugate_ ? I : -I;\n\t\treturn std::make_unique<SumLocalHam>(ham_, op_name, constant);\n\t}\n\n\t[[nodiscard]] Eigen::VectorXcd apply_right(const Eigen::VectorXcd& st) const override\n\t{\n\t\tconstexpr std::complex<double> I(0., 1.0);\n\t\tEigen::VectorXcd res = st;\n\t\tEigen::MatrixXcd m = ham_->get_local_ham();\n\n\t\tdouble t = conjugate_ ? -var_.value() : var_.value();\n\t\tEigen::MatrixXcd expm = ham_->local_ham_exp(-I * t);\n\n\t\tfor(uint32_t k = 0; k < ham_->num_qubits(); ++k)\n\t\t{\n\t\t\tres = apply_single_qubit(res, expm, k);\n\t\t}\n\t\treturn res;\n\t}\n\n\t[[nodiscard]] bool can_merge(const Operator& rhs) const override\n\t{\n\t\tif(const auto* p = dynamic_cast<const SumLocalHamEvol*>(&rhs))\n\t\t{\n\t\t\tif(ham_ == p->ham_)\n\t\t\t{\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}\n\n\t[[nodiscard]] std::string desc() const override\n\t{\n\t\tstd::ostringstream ss;\n\t\tss << \"[\" << name() << \", variable name: \" << var_.name() << \", \"\n\t\t   << \"variable value: \" << var_.value() << \"]\";\n\t\treturn ss.str();\n\t}\n};\n} // namespace yavque\n", "meta": {"hexsha": "01957c6f12a875bc6b1246893a2e908ec458fa65", "size": 2491, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/yavque/Operators/SumLocalHamEvol.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/Operators/SumLocalHamEvol.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/Operators/SumLocalHamEvol.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": 25.4183673469, "max_line_length": 86, "alphanum_fraction": 0.679245283, "num_tokens": 743, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5660185351961015, "lm_q2_score": 0.5312093733737563, "lm_q1q2_score": 0.3006743513994525}}
{"text": "/*\r\n * lbp.cpp\r\n *\r\n * Author: F.Struck (florian.struck@cased.de), E. Pschernig (epschern@cosy.sbg.ac.at), P. Wild (pwild@cosy.sbg.ac.at)\r\n *\r\n * Generates an iris code from iris texture using the uniform LBP algorithm\r\n *\r\n */\r\n#include <cstdio>\r\n#include <map>\r\n#include <vector>\r\n#include <string>\r\n#include <cstring>\r\n#include <ctime>\r\n#include <fstream>\r\n#include <opencv2/core/core.hpp>\r\n#include <opencv2/imgproc/imgproc.hpp>\r\n#include <opencv2/highgui/highgui.hpp>\r\n#include <boost/regex.hpp>\r\n#include <boost/filesystem.hpp>\r\n#include <boost/date_time/posix_time/posix_time_types.hpp>\r\n\r\nusing namespace std;\r\nusing namespace cv;\r\n\r\n#define FILTER_SIZE 9\r\n#define CELL_WIDTH 16\r\n#define CELL_HEIGHT 16\r\n#define SCALING_WIDTH 512\r\n#define SCALING_HEIGHT 64\r\n#define DELTA_SHIFT 8\r\n\r\n/** no globbing in win32 mode **/\r\nint _CRT_glob = 0;\r\n\r\n/** Program modes **/\r\nstatic const int MODE_MAIN = 1, MODE_HELP = 2;\r\n\r\n/*\r\n * Print command line usage for this program\r\n */\r\nvoid printUsage() {\r\n    printf(\"+-----------------------------------------------------------------------------+\\n\");\r\n    printf(\"| LBP - Iris-code generation (feature extraction) using the uniform LBP       |\\n\");\r\n    printf(\"| algorithm with a 9x9 filter                                                 |\\n\");\r\n    printf(\"|                                                                             |\\n\");\r\n    printf(\"| MODES                                                                       |\\n\");\r\n    printf(\"|                                                                             |\\n\");\r\n    printf(\"| (# 1) Uniform LBP iris code extraction from iris textures                   |\\n\");\r\n    printf(\"| (# 2) usage                                                                 |\\n\");\r\n    printf(\"|                                                                             |\\n\");\r\n    printf(\"| ARGUMENTS                                                                   |\\n\");\r\n    printf(\"|                                                                             |\\n\");\r\n    printf(\"+------+------------+---+---+-------------------------------------------------+\\n\");\r\n    printf(\"| Name | Parameters | # | ? | Description                                     |\\n\");\r\n    printf(\"+------+------------+---+---+-------------------------------------------------+\\n\");\r\n    printf(\"| -i   | infile     | 1 | N | input iris texture (use * as wildcard, all other|\\n\");\r\n    printf(\"|      |            |   |   | file parameters may refer to n-th * with ?n)    |\\n\");\r\n    printf(\"| -o   | outfile    | 1 | N | output iris code image                          |\\n\");\r\n    printf(\"| -q   |            | 1 | Y | quiet mode on (off)                             |\\n\");\r\n    printf(\"| -t   |            | 1 | Y | time progress on (off)                          |\\n\");\r\n    printf(\"| -h   |            | 2 | N | prints usage                                    |\\n\");\r\n    printf(\"+------+------------+---+---+-------------------------------------------------+\\n\");\r\n    printf(\"|                                                                             |\\n\");\r\n    printf(\"| EXAMPLE USAGE                                                               |\\n\");\r\n    printf(\"|                                                                             |\\n\");\r\n    printf(\"| -i s1.tiff -o s1.png                                                        |\\n\");\r\n    printf(\"| -i *.tiff -o ?1.png -q -t                                                   |\\n\");\r\n    printf(\"|                                                                             |\\n\");\r\n    printf(\"| AUTHORS                                                                     |\\n\");\r\n    printf(\"|                                                                             |\\n\");\r\n    printf(\"| Florian Struck (florian.struck@cased.de)                                    |\\n\");\r\n    printf(\"| Elias Pschernig (epschern@cosy.sbg.ac.at)                                   |\\n\");\r\n    printf(\"| Peter Wild (pwild@cosy.sbg.ac.at)                                           |\\n\");\r\n    printf(\"|                                                                             |\\n\");\r\n    printf(\"| COPYRIGHT                                                                   |\\n\");\r\n    printf(\"|                                                                             |\\n\");\r\n    printf(\"| (C) 2016 All rights reserved. Do not distribute without written permission. |\\n\");\r\n    printf(\"+-----------------------------------------------------------------------------+\\n\");\r\n}\r\n\r\n/** ------------------------------- image processing functions ------------------------------- **/\r\n\r\nstruct Cell {\r\n    int startX, startY;\r\n    int endX, endY;\r\n    int width, height;\r\n};\r\n\r\n/**\r\n * calculates the new index of a shifted pixel\r\n * @param index         the old index\r\n * @param indexWidth    the row length of this pixel\r\n * @param shift         the shift\r\n * @return              the new index\r\n */\r\nint shiftIndex(const int index, const int indexWidth, const int shift) {\r\n    int indexInRow = index % indexWidth;\r\n    if (indexInRow + shift >= indexWidth) return index + shift - indexWidth;\r\n    else if (indexInRow + shift < 0) return index + shift + indexWidth;\r\n    else return index + shift;\r\n}\r\n\r\nuchar getAverageValue(const int centerX, const int centerY, const Cell& cell, const int filterSize, const Mat& texture) {\r\n    int averageValue = 0;\r\n    int mod_x, mod_y;\r\n    const int halfCellSize = filterSize / 2;\r\n\r\n    for (int y = centerY - halfCellSize; y <= centerY + halfCellSize; y++) {\r\n\r\n        mod_y = y;\r\n        if (mod_y < cell.startY) mod_y += cell.height;\r\n        else if (mod_y >= cell.endY) mod_y -= cell.height;\r\n\r\n        for (int x = centerX - halfCellSize; x <= centerX + halfCellSize; x++) {\r\n\r\n            mod_x = x;\r\n            if (mod_x < cell.startX) mod_x += cell.width;\r\n            else if (mod_x >= cell.endX) mod_x -= cell.width;\r\n\r\n            averageValue += *texture.ptr<uchar>(mod_y, mod_x);\r\n        }\r\n    }\r\n\r\n    return (uchar) (averageValue / pow(filterSize, 2));\r\n}\r\n\r\n/**\r\n * Calculate the LBP-Value clockwise of a pixel\r\n * @param x             the x-coordinate of the pixel in the texture\r\n * @param y             the y-coordinate of the pixel in the texture\r\n * @param filterSize    the filter-size of the MB-LBP algorithm (has to be a multiple of 3)\r\n * @param texture       the iris texture\r\n * @return              the clockwise LBP-Value of this pixel\r\n */\r\nuchar calculateLBPValue(const int centerY, const int centerX, const Cell& cellSize, const int filterSize, const Mat& texture) {\r\n    const int filterCellSize = filterSize / 3;\r\n    const uchar centerValue = getAverageValue(centerX, centerY, cellSize, filterCellSize, texture);\r\n\r\n    uchar LBPValue = 0x00;\r\n    const uchar bitMask = 0x01;\r\n\r\n    //----------------------Top-Neighbours--------------------------------------    \r\n    for (int x = centerX - filterCellSize; x <= centerX + filterCellSize; x += filterCellSize) {\r\n        if (getAverageValue(x, centerY - filterCellSize, cellSize, filterCellSize, texture) >= centerValue) LBPValue |= bitMask;\r\n        LBPValue = LBPValue << 1; //*2\r\n    }\r\n    //----------------------Right-Neighbour------------------------------------\r\n    if (getAverageValue(centerX + filterCellSize, centerY, cellSize, filterCellSize, texture) >= centerValue) LBPValue |= bitMask;\r\n    LBPValue = LBPValue << 1; //*2\r\n    //----------------------Bottom-Neighbours----------------------------------\r\n    for (int x = centerX + filterCellSize; x >= centerX - filterCellSize; x -= filterCellSize) {\r\n        if (getAverageValue(x, centerY + filterCellSize, cellSize, filterCellSize, texture) >= centerValue) LBPValue |= bitMask;\r\n        LBPValue = LBPValue << 1; //*2\r\n    }\r\n    //-----------------------Left-Neighbours-----------------------------------\r\n    if (getAverageValue(centerX - filterCellSize, centerY, cellSize, filterCellSize, texture) >= centerValue) LBPValue |= bitMask;\r\n\r\n    return LBPValue;\r\n}\r\n\r\n/**\r\n * Extracts the features of the complete iris texture with the lbp algorithm\r\n * @param extractedData     the destination for the extracted data\r\n * @param cell              the start- and end-positions of this cell in the texture\r\n * @param texture           the source iris-texture\r\n */\r\nvoid extractTexture(Mat& extractedData, const int filterSize, const Mat& texture) {\r\n    Cell cell;\r\n    cell.startX = 0;\r\n    cell.startY = 0;\r\n    cell.width = texture.cols;\r\n    cell.height = texture.rows;\r\n    cell.endX = cell.startX + cell.width;\r\n    cell.endY = cell.startY + cell.height;\r\n\r\n    for (int row = 0; row < texture.rows; row++) {\r\n        for (int col = 0; col < texture.cols; col++) {\r\n            *extractedData.ptr<uchar>(row, col) = calculateLBPValue(row, col, cell, filterSize, texture);\r\n        }\r\n    }\r\n}\r\n\r\n/**\r\n * Tests if a lbp-value is uniform\r\n * @param lbp_value the lbp-value wich should be tested\r\n * @return true if uniform und false if the value is not uniform\r\n */\r\nbool isUniform(const unsigned char lbpValue) {\r\n    unsigned char transmissions = 0;\r\n    unsigned char bitmask = 64;\r\n    unsigned char shifter = 6;\r\n    unsigned char lastValue = (lbpValue & 128) >> 7; //initialisation of the first bit    \r\n\r\n    for (char index = 1; index < 8; index++) { //analyse every bit\r\n        unsigned char value = (lbpValue & bitmask) >> shifter;\r\n        if (lastValue != value) {\r\n            lastValue = value;\r\n            transmissions++;\r\n        }\r\n        shifter--;\r\n        bitmask = bitmask >> 1;\r\n    }\r\n    return (transmissions <= 2);\r\n}\r\n\r\n/**\r\n * Translate a histogram to an uniformed histogram\r\n * @param uniformHistogram  a pointer of a uniformed histogram\r\n * @param extractedData     a pointer of a filled ununiformed histogram\r\n * @param size              the size of the ununiformed histogram\r\n */\r\nvoid toUniformHistogram(uint16_t *uniformHistogram, const uint16_t *extractedData, const int size) {\r\n    int uniformIndex = 0;\r\n    uniformHistogram[58] = 0; //reset the last field\r\n\r\n    for (int index = 0; index < size; index++) {\r\n        if (isUniform(index)) {\r\n            uniformHistogram[uniformIndex] = extractedData[index];\r\n            uniformIndex++;\r\n        }\r\n        else {\r\n            uniformHistogram[58] += extractedData[index];\r\n        }\r\n    }\r\n}\r\n\r\n/**\r\n * Transforms a part of a texture to a histogram\r\n * @param histogram     the destination of the histogram\r\n * @param cell          the part of the texture\r\n * @param sourceTexture the source texture\r\n * @param shift         the alignment of pixels for shifting\r\n */\r\nvoid toHistogram(uint16_t *histogram, const Cell& cell, const Mat& sourceTexture, const int shift) {\r\n    for (int row = cell.startY; row < cell.endY; row++) {\r\n        for (int col = cell.startX; col < cell.endX; col++) {\r\n            histogram[*sourceTexture.ptr<uchar>(row, shiftIndex(col, sourceTexture.cols, shift))]++;\r\n        }\r\n    }\r\n}\r\n\r\n/*\r\n * The LBP feature extraction algorithm\r\n *\r\n * code: Code matrix\r\n * texture: texture matrix\r\n */\r\n/**\r\n * Creates normalized histograms of the extracted features\r\n * @param code          the destination for the feature data\r\n * @param extractedData the extracted feature of the iris\r\n * @param shift         the alignment of pixels for shifting\r\n */\r\nvoid extractHistograms(Mat& code, const Mat& extractedData, const int shift) {\r\n    const int verticalCellNumber = extractedData.cols / CELL_WIDTH;\r\n    const int horizontalCellNumber = extractedData.rows / CELL_HEIGHT;\r\n    const int histogramLength = 256;\r\n\r\n    uint16_t *histogram = new uint16_t[histogramLength];\r\n    uint16_t *uniformHistogram = new uint16_t[59]; //58 values of 255 are uniform plus rest\r\n\r\n    Cell cell;\r\n    cell.width = CELL_WIDTH;\r\n    cell.height = CELL_HEIGHT;\r\n    \r\n    int cellIndex = 0;\r\n    for (int cellRow = 0; cellRow < horizontalCellNumber; cellRow++) {\r\n        for (int cellCol = 0; cellCol < verticalCellNumber; cellCol++, cellIndex++) {\r\n\r\n            cell.startX = cellCol * cell.width;\r\n            cell.startY = cellRow * cell.height;\r\n            cell.endX = cell.startX + cell.width;\r\n            cell.endY = cell.startY + cell.height;\r\n\r\n            for (int i = 0; i < histogramLength; i++) histogram[i] = 0; //set all values to 0\r\n            toHistogram(histogram, cell, extractedData, shift); //calculate Histogramm\r\n            toUniformHistogram(uniformHistogram, histogram, histogramLength); //calculate uniform Histogramm\r\n\r\n            int colIndex = 0;\r\n            for (int arrayIndex = 0; arrayIndex < 59; arrayIndex++, colIndex += 2) { //translate 16-Bit integer array to 8-Bit-Image              \r\n                code.at<uchar>(cellIndex, colIndex) = (uniformHistogram[arrayIndex] & 0xFF00) >> 8;\r\n                code.at<uchar>(cellIndex, colIndex + 1) = (uniformHistogram[arrayIndex] & 0x00FF);\r\n            }\r\n        }\r\n    }\r\n\r\n    delete[] histogram;\r\n    delete[] uniformHistogram;\r\n}\r\n\r\n/**\r\n * Extracts the iris texture with 3 diffrent alignments and saves these in one big code map\r\n * @param code          the big code mat for the extraction data\r\n * @param texture       the iris texture which should be extracted\r\n * @param deltaShift    the maximum alignment for shifting\r\n */\r\nvoid multipleExtract(Mat& code, const Mat& texture, const int deltaShift) {\r\n    const int verticalCellNumber = texture.cols / CELL_WIDTH;\r\n    const int horizontalCellNumber = texture.rows / CELL_HEIGHT;\r\n    const int histogrammLength = 59; //58 uniform histograms + rest\r\n    \r\n    Mat extractedData(texture.rows, texture.cols, CV_8UC1);\r\n    extractTexture(extractedData, FILTER_SIZE, texture);     //extract all features of this texture \r\n    \r\n    Mat singleCode(verticalCellNumber*horizontalCellNumber, 2 * histogrammLength, CV_8UC1);\r\n\r\n    int counter = 0;\r\n    for (int shift = -deltaShift; shift <= deltaShift; shift += deltaShift, counter++) {\r\n        singleCode.setTo(0);\r\n        extractHistograms(singleCode, extractedData, shift);\r\n        singleCode.copyTo(code(Rect(0, counter*singleCode.rows, singleCode.cols, singleCode.rows)));\r\n    }\r\n}\r\n\r\n/**\r\n * Scales a texuture\r\n * @param scaledTexture\r\n * @param orginalTexture\r\n */\r\nvoid scaleImage(Mat& scaledTexture, const Mat& orginalTexture){  \r\n    resize(orginalTexture, scaledTexture, Size(SCALING_WIDTH,SCALING_HEIGHT), 0, 0);\r\n}\r\n\r\n/** ------------------------------- commandline functions ------------------------------- **/\r\n\r\n/**\r\n * Parses a command line\r\n * This routine should be called for parsing command lines for executables.\r\n * Note, that all options require '-' as prefix and may contain an arbitrary\r\n * number of optional arguments.\r\n *\r\n * cmd: commandline representation\r\n * argc: number of parameters\r\n * argv: string array of argument values\r\n */\r\nvoid cmdRead(map<string, vector<string> >& cmd, int argc, char *argv[]) {\r\n    for (int i = 1; i < argc; i++) {\r\n        char * argument = argv[i];\r\n        if (strlen(argument) > 1 && argument[0] == '-' && (argument[1] < '0' || argument[1] > '9')) {\r\n            cmd[argument]; // insert\r\n            char * argument2;\r\n            while (i + 1 < argc && (strlen(argument2 = argv[i + 1]) <= 1 || argument2[0] != '-' || (argument2[1] >= '0' && argument2[1] <= '9'))) {\r\n                cmd[argument].push_back(argument2);\r\n                i++;\r\n            }\r\n        }\r\n        else {\r\n            CV_Error(CV_StsBadArg, \"Invalid command line format\");\r\n        }\r\n    }\r\n}\r\n\r\n/**\r\n * Checks, if each command line option is valid, i.e. exists in the options array\r\n *\r\n * cmd: commandline representation\r\n * validOptions: list of valid options separated by pipe (i.e. |) character\r\n */\r\nvoid cmdCheckOpts(map<string, vector<string> >& cmd, const string validOptions) {\r\n    vector<string> tokens;\r\n    const string delimiters = \"|\";\r\n    string::size_type lastPos = validOptions.find_first_not_of(delimiters, 0); // skip delimiters at beginning\r\n    string::size_type pos = validOptions.find_first_of(delimiters, lastPos); // find first non-delimiter\r\n    while (string::npos != pos || string::npos != lastPos) {\r\n        tokens.push_back(validOptions.substr(lastPos, pos - lastPos)); // add found token to vector\r\n        lastPos = validOptions.find_first_not_of(delimiters, pos); // skip delimiters\r\n        pos = validOptions.find_first_of(delimiters, lastPos); // find next non-delimiter\r\n    }\r\n    sort(tokens.begin(), tokens.end());\r\n    for (map<string, vector<string> >::iterator it = cmd.begin(); it != cmd.end(); it++) {\r\n        if (!binary_search(tokens.begin(), tokens.end(), it->first)) {\r\n            CV_Error(CV_StsBadArg, \"Command line parameter '\" + it->first + \"' not allowed.\");\r\n            tokens.clear();\r\n            return;\r\n        }\r\n    }\r\n    tokens.clear();\r\n}\r\n\r\n/*\r\n * Checks, if a specific required option exists in the command line\r\n *\r\n * cmd: commandline representation\r\n * option: option name\r\n */\r\nvoid cmdCheckOptExists(map<string, vector<string> >& cmd, const string option) {\r\n    map<string, vector<string> >::iterator it = cmd.find(option);\r\n    if (it == cmd.end()) CV_Error(CV_StsBadArg, \"Command line parameter '\" + option + \"' is required, but does not exist.\");\r\n}\r\n\r\n/*\r\n * Checks, if a specific option has the appropriate number of parameters\r\n *\r\n * cmd: commandline representation\r\n * option: option name\r\n * size: appropriate number of parameters for the option\r\n */\r\nvoid cmdCheckOptSize(map<string, vector<string> >& cmd, const string option, const unsigned int size = 1) {\r\n    map<string, vector<string> >::iterator it = cmd.find(option);\r\n    if (it->second.size() != size) CV_Error(CV_StsBadArg, \"Command line parameter '\" + option + \"' has unexpected size.\");\r\n}\r\n\r\n/*\r\n * Checks, if a specific option has the appropriate number of parameters\r\n *\r\n * cmd: commandline representation\r\n * option: option name\r\n * min: minimum appropriate number of parameters for the option\r\n * max: maximum appropriate number of parameters for the option\r\n */\r\nvoid cmdCheckOptRange(map<string, vector<string> >& cmd, string option, unsigned int min = 0, unsigned int max = 1) {\r\n    map<string, vector<string> >::iterator it = cmd.find(option);\r\n    unsigned int size = it->second.size();\r\n    if (size < min || size > max) CV_Error(CV_StsBadArg, \"Command line parameter '\" + option + \"' is out of range.\");\r\n}\r\n\r\n/*\r\n * Returns the list of parameters for a given option\r\n *\r\n * cmd: commandline representation\r\n * option: name of the option\r\n */\r\nvector<string> * cmdGetOpt(map<string, vector<string> >& cmd, const string option) {\r\n    map<string, vector<string> >::iterator it = cmd.find(option);\r\n    return (it != cmd.end()) ? &(it->second) : 0;\r\n}\r\n\r\n/*\r\n * Returns number of parameters in an option\r\n *\r\n * cmd: commandline representation\r\n * option: name of the option\r\n */\r\nunsigned int cmdSizePars(map<string, vector<string> >& cmd, const string option) {\r\n    map<string, vector<string> >::iterator it = cmd.find(option);\r\n    return (it != cmd.end()) ? it->second.size() : 0;\r\n}\r\n\r\n/*\r\n * Returns a specific parameter type (int) given an option and parameter index\r\n *\r\n * cmd: commandline representation\r\n * option: name of option\r\n * param: name of parameter\r\n */\r\nint cmdGetParInt(map<string, vector<string> >& cmd, string option, unsigned int param = 0) {\r\n    map<string, vector<string> >::iterator it = cmd.find(option);\r\n    if (it != cmd.end()) {\r\n        if (param < it->second.size()) {\r\n            return atoi(it->second[param].c_str());\r\n        }\r\n    }\r\n    return 0;\r\n}\r\n\r\n/*\r\n * Returns a specific parameter type (float) given an option and parameter index\r\n *\r\n * cmd: commandline representation\r\n * option: name of option\r\n * param: name of parameter\r\n */\r\nfloat cmdGetParFloat(map<string, vector<string> >& cmd, const string option, const unsigned int param = 0) {\r\n    map<string, vector<string> >::iterator it = cmd.find(option);\r\n    if (it != cmd.end()) {\r\n        if (param < it->second.size()) {\r\n            return atof(it->second[param].c_str());\r\n        }\r\n    }\r\n    return 0;\r\n}\r\n\r\n/*\r\n * Returns a specific parameter type (string) given an option and parameter index\r\n *\r\n * cmd: commandline representation\r\n * option: name of option\r\n * param: name of parameter\r\n */\r\nstring cmdGetPar(map<string, vector<string> >& cmd, const string option, const unsigned int param = 0) {\r\n    map<string, vector<string> >::iterator it = cmd.find(option);\r\n    if (it != cmd.end()) {\r\n        if (param < it->second.size()) {\r\n            return it->second[param];\r\n        }\r\n    }\r\n    return 0;\r\n}\r\n\r\n/** ------------------------------- timing functions ------------------------------- **/\r\n\r\n/**\r\n * Class for handling timing progress information\r\n */\r\nclass Timing {\r\npublic:\r\n    /** integer indicating progress with respect tot total **/\r\n    int progress;\r\n    /** total count for progress **/\r\n    int total;\r\n\r\n    /*\r\n     * Default constructor for timing initializing time.\r\n     * Automatically calls init()\r\n     *\r\n     * seconds: update interval in seconds\r\n     * eraseMode: if true, outputs sends erase characters at each print command\r\n     */\r\n    Timing(long seconds, bool eraseMode) {\r\n        updateInterval = seconds;\r\n        progress = 1;\r\n        total = 100;\r\n        eraseCount = 0;\r\n        erase = eraseMode;\r\n        init();\r\n    }\r\n\r\n    /*\r\n     * Destructor\r\n     */\r\n    ~Timing() {\r\n    }\r\n\r\n    /*\r\n     * Initializes timing variables\r\n     */\r\n    void init(void) {\r\n        start = boost::posix_time::microsec_clock::universal_time();\r\n        lastPrint = start - boost::posix_time::seconds(updateInterval);\r\n    }\r\n\r\n    /*\r\n     * Clears printing (for erase option only)\r\n     */\r\n    void clear(void) {\r\n        string erase(eraseCount, '\\r');\r\n        erase.append(eraseCount, ' ');\r\n        erase.append(eraseCount, '\\r');\r\n        printf(\"%s\", erase.c_str());\r\n        eraseCount = 0;\r\n    }\r\n\r\n    /*\r\n     * Updates current time and returns true, if output should be printed\r\n     */\r\n    bool update(void) {\r\n        current = boost::posix_time::microsec_clock::universal_time();\r\n        return ((current - lastPrint > boost::posix_time::seconds(updateInterval)) || (progress == total));\r\n    }\r\n\r\n    /*\r\n     * Prints timing object to STDOUT\r\n     */\r\n    void print(void) {\r\n        lastPrint = current;\r\n        float percent = 100.f * progress / total;\r\n        boost::posix_time::time_duration passed = (current - start);\r\n        boost::posix_time::time_duration togo = passed * (total - progress) / max(1, progress);\r\n        if (erase) {\r\n            string erase(eraseCount, '\\r');\r\n            printf(\"%s\", erase.c_str());\r\n            int newEraseCount = (progress != total) ? printf(\"Progress ... %3.2f%% (%i/%i Total %i:%02i:%02i.%03i Remaining ca. %i:%02i:%02i.%03i)\", percent, progress, total, passed.hours(), passed.minutes(), passed.seconds(), (int) (passed.total_milliseconds() % 1000), togo.hours(), togo.minutes(), togo.seconds(), (int) (togo.total_milliseconds() % 1000)) : printf(\"Progress ... %3.2f%% (%i/%i Total %i:%02i:%02i.%03d)\", percent, progress, total, passed.hours(), passed.minutes(), passed.seconds(), (int) (passed.total_milliseconds() % 1000));\r\n            if (newEraseCount < eraseCount) {\r\n                string erase(newEraseCount - eraseCount, ' ');\r\n                erase.append(newEraseCount - eraseCount, '\\r');\r\n                printf(\"%s\", erase.c_str());\r\n            }\r\n            eraseCount = newEraseCount;\r\n        }\r\n        else {\r\n            eraseCount = (progress != total) ? printf(\"Progress ... %3.2f%% (%i/%i Total %i:%02i:%02i.%03i Remaining ca. %i:%02i:%02i.%03i)\\n\", percent, progress, total, passed.hours(), passed.minutes(), passed.seconds(), (int) (passed.total_milliseconds() % 1000), togo.hours(), togo.minutes(), togo.seconds(), (int) (togo.total_milliseconds() % 1000)) : printf(\"Progress ... %3.2f%% (%i/%i Total %i:%02i:%02i.%03d)\\n\", percent, progress, total, passed.hours(), passed.minutes(), passed.seconds(), (int) (passed.total_milliseconds() % 1000));\r\n        }\r\n    }\r\nprivate:\r\n    long updateInterval;\r\n    boost::posix_time::ptime start;\r\n    boost::posix_time::ptime current;\r\n    boost::posix_time::ptime lastPrint;\r\n    int eraseCount;\r\n    bool erase;\r\n};\r\n\r\n/** ------------------------------- file pattern matching functions ------------------------------- **/\r\n\r\n/*\r\n * Formats a given string, such that it can be used as a regular expression\r\n * I.e. escapes special characters and uses * and ? as wildcards\r\n *\r\n * pattern: regular expression path pattern\r\n * pos: substring starting index\r\n * n: substring size\r\n *\r\n * returning: escaped substring\r\n */\r\nstring patternSubstrRegex(string& pattern, size_t pos, size_t n) {\r\n    string result;\r\n    for (size_t i = pos, e = pos + n; i < e; i++) {\r\n        char c = pattern[i];\r\n        if (c == '\\\\' || c == '.' || c == '+' || c == '[' || c == '{' || c == '|' || c == '(' || c == ')' || c == '^' || c == '$' || c == '}' || c == ']') {\r\n            result.append(1, '\\\\');\r\n            result.append(1, c);\r\n        }\r\n        else if (c == '*') {\r\n            result.append(\"([^/\\\\\\\\]*)\");\r\n        }\r\n        else if (c == '?') {\r\n            result.append(\"([^/\\\\\\\\])\");\r\n        }\r\n        else {\r\n            result.append(1, c);\r\n        }\r\n    }\r\n    return result;\r\n}\r\n\r\n/*\r\n * Converts a regular expression path pattern into a list of files matching with this pattern by replacing wildcards\r\n * starting in position pos assuming that all prior wildcards have been resolved yielding intermediate directory path.\r\n * I.e. this function appends the files in the specified path according to yet unresolved pattern by recursive calling.\r\n *\r\n * pattern: regular expression path pattern\r\n * files: the list to which new files can be applied\r\n * pos: an index such that positions 0...pos-1 of pattern are already considered/matched yielding path\r\n * path: the current directory (or empty)\r\n */\r\nvoid patternToFiles(string& pattern, vector<string>& files, const size_t& pos, const string& path) {\r\n    size_t first_unknown = pattern.find_first_of(\"*?\", pos); // find unknown * in pattern\r\n    if (first_unknown != string::npos) {\r\n        size_t last_dirpath = pattern.find_last_of(\"/\\\\\", first_unknown);\r\n        size_t next_dirpath = pattern.find_first_of(\"/\\\\\", first_unknown);\r\n        if (next_dirpath != string::npos) {\r\n            boost::regex expr((last_dirpath != string::npos && last_dirpath > pos) ? patternSubstrRegex(pattern, last_dirpath + 1, next_dirpath - last_dirpath - 1) : patternSubstrRegex(pattern, pos, next_dirpath - pos));\r\n            boost::filesystem::directory_iterator end_itr; // default construction yields past-the-end\r\n            try {\r\n                for (boost::filesystem::directory_iterator itr(((path.length() > 0) ? path + pattern[pos - 1] : (last_dirpath != string::npos && last_dirpath > pos) ? \"\" : \"./\") + ((last_dirpath != string::npos && last_dirpath > pos) ? pattern.substr(pos, last_dirpath - pos) : \"\")); itr != end_itr; ++itr) {\r\n                    if (boost::filesystem::is_directory(itr->path())) {\r\n                        boost::filesystem::path p = itr->path().filename();\r\n                        string s = p.string();\r\n                        if (boost::regex_match(s.c_str(), expr)) {\r\n                            patternToFiles(pattern, files, (int) (next_dirpath + 1), ((path.length() > 0) ? path + pattern[pos - 1] : \"\") + ((last_dirpath != string::npos && last_dirpath > pos) ? pattern.substr(pos, last_dirpath - pos) + pattern[last_dirpath] : \"\") + s);\r\n                        }\r\n                    }\r\n                }\r\n            } catch (boost::filesystem::filesystem_error &e) {\r\n            }\r\n        }\r\n        else {\r\n            boost::regex expr((last_dirpath != string::npos && last_dirpath > pos) ? patternSubstrRegex(pattern, last_dirpath + 1, pattern.length() - last_dirpath - 1) : patternSubstrRegex(pattern, pos, pattern.length() - pos));\r\n            boost::filesystem::directory_iterator end_itr; // default construction yields past-the-end\r\n            try {\r\n                for (boost::filesystem::directory_iterator itr(((path.length() > 0) ? path + pattern[pos - 1] : (last_dirpath != string::npos && last_dirpath > pos) ? \"\" : \"./\") + ((last_dirpath != string::npos && last_dirpath > pos) ? pattern.substr(pos, last_dirpath - pos) : \"\")); itr != end_itr; ++itr) {\r\n                    boost::filesystem::path p = itr->path().filename();\r\n                    string s = p.string();\r\n                    if (boost::regex_match(s.c_str(), expr)) {\r\n                        files.push_back(((path.length() > 0) ? path + pattern[pos - 1] : \"\") + ((last_dirpath != string::npos && last_dirpath > pos) ? pattern.substr(pos, last_dirpath - pos) + pattern[last_dirpath] : \"\") + s);\r\n                    }\r\n                }\r\n            } catch (boost::filesystem::filesystem_error &e) {\r\n            }\r\n        }\r\n    }\r\n    else { // no unknown symbols\r\n        boost::filesystem::path file(((path.length() > 0) ? path + \"/\" : \"\") + pattern.substr(pos, pattern.length() - pos));\r\n        if (boost::filesystem::exists(file)) {\r\n            files.push_back(file.string());\r\n        }\r\n    }\r\n}\r\n\r\n/**\r\n * Converts a regular expression path pattern into a list of files matching with this pattern\r\n *\r\n * pattern: regular expression path pattern\r\n * files: the list to which new files can be applied\r\n */\r\nvoid patternToFiles(string& pattern, vector<string>& files) {\r\n    patternToFiles(pattern, files, 0, \"\");\r\n}\r\n\r\n/*\r\n * Renames a given filename corresponding to the actual file pattern using a renaming pattern.\r\n * Wildcards can be referred to as ?1, ?2, ... in the order they appeared in the file pattern.\r\n *\r\n * pattern: regular expression path pattern\r\n * renamePattern: renaming pattern using ?1, ?2, ... as placeholders for wildcards\r\n * infile: path of the file (matching with pattern) to be renamed\r\n * outfile: path of the renamed file\r\n * par: used parameter (default: '?')\r\n */\r\nvoid patternFileRename(string& pattern, const string& renamePattern, const string& infile, string& outfile, const char par = '?') {\r\n    size_t first_unknown = renamePattern.find_first_of(par, 0); // find unknown ? in renamePattern\r\n    if (first_unknown != string::npos) {\r\n        string formatOut = \"\";\r\n        for (size_t i = 0, e = renamePattern.length(); i < e; i++) {\r\n            char c = renamePattern[i];\r\n            if (c == par && i + 1 < e) {\r\n                c = renamePattern[i + 1];\r\n                if (c > '0' && c <= '9') {\r\n                    formatOut.append(1, '$');\r\n                    formatOut.append(1, c);\r\n                }\r\n                else {\r\n                    formatOut.append(1, par);\r\n                    formatOut.append(1, c);\r\n                }\r\n                i++;\r\n            }\r\n            else {\r\n                formatOut.append(1, c);\r\n            }\r\n        }\r\n        boost::regex patternOut(patternSubstrRegex(pattern, 0, pattern.length()));\r\n        outfile = boost::regex_replace(infile, patternOut, formatOut, boost::match_default | boost::format_perl);\r\n    }\r\n    else {\r\n        outfile = renamePattern;\r\n    }\r\n}\r\n\r\n/** ------------------------------- Program ------------------------------- **/\r\n\r\n/*\r\n * Main program\r\n */\r\nint main(int argc, char *argv[]) {\r\n    int mode = MODE_HELP;\r\n    map<string, vector<string> > cmd;\r\n    try {\r\n        cmdRead(cmd, argc, argv);\r\n        if (cmd.size() == 0 || cmdGetOpt(cmd, \"-h\") != 0) mode = MODE_HELP;\r\n        else mode = MODE_MAIN;\r\n        if (mode == MODE_MAIN) {\r\n            // validate command line\r\n            cmdCheckOpts(cmd, \"-i|-o|-m|-q|-t\");\r\n\r\n            cmdCheckOptExists(cmd, \"-i\");\r\n            cmdCheckOptSize(cmd, \"-i\", 1);\r\n            string inFiles = cmdGetPar(cmd, \"-i\");\r\n\r\n            cmdCheckOptExists(cmd, \"-o\");\r\n            cmdCheckOptSize(cmd, \"-o\", 1);\r\n            string outFiles = cmdGetPar(cmd, \"-o\");\r\n\r\n            string imaskFiles, omaskFiles;\r\n\r\n            if (cmdGetOpt(cmd, \"-m\") != 0) {\r\n                cmdCheckOptSize(cmd, \"-m\", 2);\r\n                imaskFiles = cmdGetPar(cmd, \"-m\", 0);\r\n                omaskFiles = cmdGetPar(cmd, \"-m\", 1);\r\n            }\r\n            bool quiet = false;\r\n            if (cmdGetOpt(cmd, \"-q\") != 0) {\r\n                cmdCheckOptSize(cmd, \"-q\", 0);\r\n                quiet = true;\r\n            }\r\n            bool time = false;\r\n            if (cmdGetOpt(cmd, \"-t\") != 0) {\r\n                cmdCheckOptSize(cmd, \"-t\", 0);\r\n                time = true;\r\n            }\r\n            // starting routine\r\n            Timing timing(1, quiet);\r\n            vector<string> files;\r\n            patternToFiles(inFiles, files);\r\n            CV_Assert(files.size() > 0);\r\n            timing.total = files.size();\r\n            for (vector<string>::iterator inFile = files.begin(); inFile != files.end(); ++inFile, timing.progress++) {\r\n                if (!quiet) printf(\"Loading texture '%s' ...\\n\", (*inFile).c_str());\r\n\r\n                Mat imgOrginal = imread(*inFile, CV_LOAD_IMAGE_GRAYSCALE);\r\n                CV_Assert(imgOrginal.data != 0);\r\n                Mat out;\r\n                if (imgOrginal.rows != 64 || imgOrginal.cols != 512) {\r\n                    printf(\"Input texture has to be of size 512 x 64.\\n\");\r\n                    exit(EXIT_FAILURE);\r\n                }\r\n                \r\n                Mat img;\r\n                scaleImage(img, imgOrginal);\r\n\r\n                int verticalCellNumber = img.cols / CELL_WIDTH; //width\r\n                int horizontalCellNumber = img.rows / CELL_HEIGHT; //height\r\n\r\n                if (!quiet) printf(\"Creating %d x %d iris-code ...\\n\", 118, verticalCellNumber * horizontalCellNumber*3);\r\n                Mat code(verticalCellNumber*horizontalCellNumber*3, 118, CV_8UC1);\r\n                code.setTo(0);\r\n                multipleExtract(code, img, DELTA_SHIFT);\r\n                out = code;\r\n                string outfile;\r\n                patternFileRename(inFiles, outFiles, *inFile, outfile);\r\n                if (!quiet) printf(\"Storing code '%s' ...\\n\", outfile.c_str());\r\n                if (!imwrite(outfile, out)) CV_Error(CV_StsError, \"Could not save image '\" + outfile + \"'\");\r\n                if (time && timing.update()) timing.print();\r\n            }\r\n            if (time && quiet) timing.clear();\r\n        }\r\n        else if (mode == MODE_HELP) {\r\n            // validate command line\r\n            cmdCheckOpts(cmd, \"-h\");\r\n            if (cmdGetOpt(cmd, \"-h\") != 0) cmdCheckOptSize(cmd, \"-h\", 0);\r\n            // starting routine\r\n            printUsage();\r\n        }\r\n    } catch (...) {\r\n        printf(\"Exit with errors.\\n\");\r\n        exit(EXIT_FAILURE);\r\n    }\r\n    return EXIT_SUCCESS;\r\n}", "meta": {"hexsha": "409da693b3c28d1bc16c17c49d6167f51c0d2d23", "size": 34916, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lbp.cpp", "max_stars_repo_name": "ngoclamvt123/usit-v2.2.0", "max_stars_repo_head_hexsha": "3b2d27b7096e44eb41c786b4497b296ffd5a1519", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2020-12-20T12:40:14.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-17T20:04:22.000Z", "max_issues_repo_path": "lbp.cpp", "max_issues_repo_name": "ngoclamvt123/usit-v2.2.0", "max_issues_repo_head_hexsha": "3b2d27b7096e44eb41c786b4497b296ffd5a1519", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lbp.cpp", "max_forks_repo_name": "ngoclamvt123/usit-v2.2.0", "max_forks_repo_head_hexsha": "3b2d27b7096e44eb41c786b4497b296ffd5a1519", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2020-09-14T01:51:42.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-10T02:49:06.000Z", "avg_line_length": 43.1061728395, "max_line_length": 547, "alphanum_fraction": 0.5455951426, "num_tokens": 7912, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.3006743513994525}}
{"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#include \"Utils.h\"\n\n#include <mutex>\n#include <cstdarg>\n#include <cstdio>\n\n#include <boost/filesystem.hpp>\n#include <boost/math/distributions/students_t.hpp>\n\n#ifdef _WIN32\n#include <windows.h>\n#else\n#include <sys/select.h>\n#include <unistd.h>\n#include <sys/types.h>\n#include <pwd.h>\n#endif\n\n#include \"GTP.h\"\n\nUtils::ThreadPool thread_pool;\n\nauto constexpr z_entries = 1000;\nstd::array<float, z_entries> z_lookup;\n\nvoid Utils::create_z_table() {\n    for (auto i = 1; i < z_entries + 1; i++) {\n        boost::math::students_t dist(i);\n        auto z = boost::math::quantile(boost::math::complement(dist, cfg_ci_alpha));\n        z_lookup[i - 1] = z;\n    }\n}\n\nfloat Utils::cached_t_quantile(int v) {\n    if (v < 1) {\n        return z_lookup[0];\n    }\n    if (v < z_entries) {\n        return z_lookup[v - 1];\n    }\n    // z approaches constant when v is high enough.\n    // With default lookup table size the function is flat enough that we\n    // can just return the last entry for all v bigger than it.\n    return z_lookup[z_entries - 1];\n}\n\nbool Utils::input_pending() {\n#ifdef HAVE_SELECT\n    fd_set read_fds;\n    FD_ZERO(&read_fds);\n    FD_SET(0,&read_fds);\n    struct timeval timeout{0,0};\n    select(1,&read_fds,nullptr,nullptr,&timeout);\n    return FD_ISSET(0, &read_fds);\n#else\n    static int init = 0, pipe;\n    static HANDLE inh;\n    DWORD dw;\n\n    if (!init) {\n        init = 1;\n        inh = GetStdHandle(STD_INPUT_HANDLE);\n        pipe = !GetConsoleMode(inh, &dw);\n        if (!pipe) {\n            SetConsoleMode(inh, dw & ~(ENABLE_MOUSE_INPUT | ENABLE_WINDOW_INPUT));\n            FlushConsoleInputBuffer(inh);\n        }\n    }\n\n    if (pipe) {\n        if (!PeekNamedPipe(inh, nullptr, 0, nullptr, &dw, nullptr)) {\n            myprintf(\"Nothing at other end - exiting\\n\");\n            exit(EXIT_FAILURE);\n        }\n\n        return dw;\n    } else {\n        if (!GetNumberOfConsoleInputEvents(inh, &dw)) {\n            myprintf(\"Nothing at other end - exiting\\n\");\n            exit(EXIT_FAILURE);\n        }\n\n        return dw > 1;\n    }\n    return false;\n#endif\n}\n\nstatic std::mutex IOmutex;\n\nstatic void myprintf_base(const char *fmt, va_list ap) {\n    va_list ap2;\n    va_copy(ap2, ap);\n\n    vfprintf(stderr, fmt, ap);\n\n    if (cfg_logfile_handle) {\n        std::lock_guard<std::mutex> lock(IOmutex);\n        vfprintf(cfg_logfile_handle, fmt, ap2);\n    }\n    va_end(ap2);\n}\n\nvoid Utils::myprintf(const char *fmt, ...) {\n    if (cfg_quiet) {\n        return;\n    }\n\n    va_list ap;\n    va_start(ap, fmt);\n    myprintf_base(fmt, ap);\n    va_end(ap);\n}\n\nvoid Utils::myprintf_error(const char *fmt, ...) {\n    va_list ap;\n    va_start(ap, fmt);\n    myprintf_base(fmt, ap);\n    va_end(ap);\n}\n\nstatic void gtp_fprintf(FILE* file, const std::string& prefix,\n                        const char *fmt, va_list ap) {\n    fprintf(file, \"%s \", prefix.c_str());\n    vfprintf(file, fmt, ap);\n    fprintf(file, \"\\n\\n\");\n}\n\nstatic void gtp_base_printf(int id, std::string prefix,\n                            const char *fmt, va_list ap) {\n    if (id != -1) {\n        prefix += std::to_string(id);\n    }\n    gtp_fprintf(stdout, prefix, fmt, ap);\n    if (cfg_logfile_handle) {\n        std::lock_guard<std::mutex> lock(IOmutex);\n        gtp_fprintf(cfg_logfile_handle, prefix, fmt, ap);\n    }\n}\n\nvoid Utils::gtp_printf(int id, const char *fmt, ...) {\n    va_list ap;\n    va_start(ap, fmt);\n    gtp_base_printf(id, \"=\", fmt, ap);\n    va_end(ap);\n}\n\nvoid Utils::gtp_printf_raw(const char *fmt, ...) {\n    va_list ap;\n    va_start(ap, fmt);\n    vfprintf(stdout, fmt, ap);\n    va_end(ap);\n\n    if (cfg_logfile_handle) {\n        std::lock_guard<std::mutex> lock(IOmutex);\n        va_start(ap, fmt);\n        vfprintf(cfg_logfile_handle, fmt, ap);\n        va_end(ap);\n    }\n}\n\nvoid Utils::gtp_fail_printf(int id, const char *fmt, ...) {\n    va_list ap;\n    va_start(ap, fmt);\n    gtp_base_printf(id, \"?\", fmt, ap);\n    va_end(ap);\n}\n\nvoid Utils::log_input(const std::string& input) {\n    if (cfg_logfile_handle) {\n        std::lock_guard<std::mutex> lock(IOmutex);\n        fprintf(cfg_logfile_handle, \">>%s\\n\", input.c_str());\n    }\n}\n\nsize_t Utils::ceilMultiple(size_t a, size_t b) {\n    if (a % b == 0) {\n        return a;\n    }\n\n    auto ret = a + (b - a % b);\n    return ret;\n}\n\nconst std::string Utils::leelaz_file(std::string file) {\n#if defined(_WIN32) || defined(__ANDROID__)\n    boost::filesystem::path dir(boost::filesystem::current_path());\n#else\n/*\n    // https://stackoverflow.com/a/26696759\n    const char *homedir;\n    if ((homedir = getenv(\"HOME\")) == nullptr) {\n        struct passwd *pwd;\n        if ((pwd = getpwuid(getuid())) == nullptr) { // NOLINT(runtime/threadsafe_fn)\n            return std::string();\n        }\n        homedir = pwd->pw_dir;\n    }\n    boost::filesystem::path dir(homedir);\n    dir /= \".local/share/leela-zero\";\n*/\n    boost::filesystem::path dir(boost::filesystem::current_path());\n#endif\n    boost::filesystem::create_directories(dir);\n    dir /= file;\n    return dir.string();\n}\n", "meta": {"hexsha": "4ec7059b46ae7c418a883a9d3b0eb3dc0b0043c6", "size": 6401, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/usi-engine/Utils.cpp", "max_stars_repo_name": "bleu48/aobazero", "max_stars_repo_head_hexsha": "c805b80d9ed8d27ce507fc2b74fb7609d75b2426", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 43.0, "max_stars_repo_stars_event_min_datetime": "2019-05-10T05:50:23.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-03T02:46:00.000Z", "max_issues_repo_path": "src/usi-engine/Utils.cpp", "max_issues_repo_name": "bleu48/aobazero", "max_issues_repo_head_hexsha": "c805b80d9ed8d27ce507fc2b74fb7609d75b2426", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": 34.0, "max_issues_repo_issues_event_min_datetime": "2019-05-07T15:22:44.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-21T04:34:39.000Z", "max_forks_repo_path": "src/usi-engine/Utils.cpp", "max_forks_repo_name": "bleu48/aobazero", "max_forks_repo_head_hexsha": "c805b80d9ed8d27ce507fc2b74fb7609d75b2426", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 13.0, "max_forks_repo_forks_event_min_datetime": "2019-05-10T02:11:45.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-05T12:28:03.000Z", "avg_line_length": 26.6708333333, "max_line_length": 85, "alphanum_fraction": 0.6300578035, "num_tokens": 1670, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6926419958239132, "lm_q2_score": 0.4339814648038986, "lm_q1q2_score": 0.30059378793235764}}
{"text": "#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/graphviz.hpp>\n#include <string>\n#include <numeric>\n#include <fstream>\n#include <sstream>\n#include <boost/algorithm/string.hpp>\n#include <ctime> \n\n#include \"../../libs/main_path_analysis/src/mainPathAnalysis/checkGraphProperties.hpp\"\n#include \"../../libs/main_path_analysis/src/mainPathAnalysis/edgeWeightGeneration.hpp\"\n#include \"../../libs/main_path_analysis/src/mainPathAnalysis/mpaAlgorithms.hpp\"\n#include \"../../libs/main_path_analysis/src/mainPathAnalysis/preAndPostProcessing.hpp\"\n#include \"../../libs/main_path_analysis/src/mainPathAnalysis/propertyMaps.hpp\"\n\nusing VertexProperties = boost::property<boost::vertex_name_t, std::string, boost::property<boost::vertex_finish_time_t, std::tm>>;\nusing Graph = boost::adjacency_list<boost::vecS, boost::vecS, boost::bidirectionalS, VertexProperties, boost::property<boost::edge_index_t,std::size_t>, boost::vecS>;\n\nGraph read_graph_from_file(std::istream& input, std::set<std::size_t> forbidden_vertices)\n{\n\tstd::size_t n_vertices, n_edges;\n\n\tstd::string l;\n\tstd::getline(input, l);\n\tn_vertices = std::stoul(l);\n\tstd::getline(input, l);\n\tn_edges = std::stoul(l);\n\n\tGraph g;\n\n\tstd::map<std::size_t, Graph::vertex_descriptor> v_map;\n\n\tfor(std::size_t i = 0; i < n_vertices; i++)\n\t{\n\t\tstd::string line;\n\t\tstd::getline(input, line);\n\t\tboost::trim(line);\n\n\t\tif(!line.empty() && forbidden_vertices.find(i) == forbidden_vertices.end())\n\t\t{\n\t\t\tauto v = boost::add_vertex(g);\n\t\t\tv_map.insert({ i, v });\n\t\t\tstd::vector<std::string> tmp;\n\t\t\tboost::split(tmp, line, boost::is_any_of(\"\\t\"));\n\t\t\tboost::trim(tmp[0]);\n\n\t\t\tboost::put(boost::vertex_name, g, v, tmp[0]);\n\n\t\t\tstd::vector<std::string> date_strs;\n\t\t\tboost::split(date_strs, tmp[1], boost::is_any_of(\"_\"));\n\t\t\tint year = std::stoul(date_strs[0]), month = std::stoul(date_strs[1]), day = std::stoul(date_strs[2]);\n\t\t\tstd::tm date{};\n\t\t\tdate.tm_year = year-1900;\n\t\t\tdate.tm_mon = month-1;\n\t\t\tdate.tm_mday = day;\n\n\t\t\tboost::put(boost::vertex_finish_time, g, v, date);\n\t\t}\n\t}\n\n\tfor(std::size_t i = 0; i < n_edges; i++)\n\t{\n\t\tstd::string line;\n\t\tstd::getline(input, line);\n\t\tboost::trim(line);\n\n\t\tif(!line.empty())\n\t\t{\n\t\t\tstd::stringstream ss(line);\n\t\t\tstd::size_t from, to;\n\t\t\tss >> from >> to;\n\n\t\t\tif(forbidden_vertices.find(from) == forbidden_vertices.end() && forbidden_vertices.find(to) == forbidden_vertices.end())\n\t\t\t\tboost::add_edge(v_map.at(from), v_map.at(to), g);\n\t\t}\n\t}\n\n\treturn g;\n}\n\nclass VertexLabelWriter {\n\tpublic:\n\t\tVertexLabelWriter(Graph& g, std::vector<std::vector<Graph::edge_descriptor>> main_paths = std::vector<std::vector<Graph::edge_descriptor>>()) \n\t\t\t:_g(g),\n\t\t\tmain_path_colors({ \"blue\", \"green\", \"red\" })\n\t\t{\n\t\t\tfor (auto main_path : main_paths) {\n\t\t\t\tstd::set<Graph::vertex_descriptor> vertices_in_path;\n\t\t\t\tfor (auto e : main_path) {\n\t\t\t\t\tvertices_in_path.insert(boost::source(e,g));\t\n\t\t\t\t\tvertices_in_path.insert(boost::target(e,g));\t\n\t\t\t\t}\n\t\t\t\t_main_path_vertex_sets.push_back(vertices_in_path);\n\t\t\t}\t\n\t\t}\n\n\t\ttemplate <class VertexOrEdge>\n\t\t\tvoid operator()(std::ostream& out, const VertexOrEdge& v) const {\n\t\t\t\tconst std::size_t MAX_LENGTH = 50;\n\t\t\t\tstd::string lab = boost::get(boost::vertex_name, _g, v);\n\t\t\t\tif(lab.length() > MAX_LENGTH+5)\n\t\t\t\t\tlab = lab.substr(0, MAX_LENGTH) + \"[...]\";\n\t\t\t\tout << \"[\";\n\t\t\t\tout << \"label=\\\"\" << lab << \"\\\" \";\n\n\t\t\t\tstd::size_t i = 0;\n\t\t\t\tfor (auto mp : _main_path_vertex_sets) \n\t\t\t\t{\n\t\t\t\t\tif(mp.find(v) != mp.end())\n\t\t\t\t\t{\n\t\t\t\t\t\tout << \"color=\\\"\" << main_path_colors[i] << \"\\\" \";\n\t\t\t\t\t}\n\t\t\t\t\ti++;\n\t\t\t\t}\n\t\t\t\t// out << \"shape=point \";\n\n\t\t\t\tout << \"fontsize=70 \";\n\t\t\t\tout << \"]\";\n\t\t\t}\n\n\tprivate:\n\t\tGraph& _g;\n\n\t\tstd::vector<std::set<Graph::vertex_descriptor>> _main_path_vertex_sets;\n\t\tconst std::vector<std::string> main_path_colors;\n};\n\nclass EdgeLabelWriter {\n\tpublic:\n\t\tEdgeLabelWriter(Graph& g, std::vector<std::vector<Graph::edge_descriptor>> main_paths) \n\t\t\t:_g(g),\n\t\t\tmain_path_colors({ \"blue\", \"green\", \"red\" })\n\t\t{\n\t\t\tfor (auto mp : main_paths) {\n\t\t\t\t_main_path_sets.push_back(std::set<Graph::edge_descriptor>(mp.begin(), mp.end()));\n\t\t\t}\n\t\t}\n\n\n\t\ttemplate <class VertexOrEdge>\n\t\t\tvoid operator()(std::ostream& out, const VertexOrEdge& e) const {\n\t\t\t\tout << \"[\";\n\t\t\t\tout << \"fontsize=40 \";\n\n\t\t\t\tstd::size_t i = 0;\n\t\t\t\tbool found = false;\n\t\t\t\tfor (auto mp : _main_path_sets) \n\t\t\t\t{\n\t\t\t\t\tif(mp.find(e) != mp.end())\n\t\t\t\t\t{\n\t\t\t\t\t\tout << \"color=\\\"\" << main_path_colors[i] << \"\\\" \";\n\t\t\t\t\t\tfound = true;\n\t\t\t\t\t}\n\t\t\t\t\ti++;\n\t\t\t\t}\n\n\t\t\t\tif(found)\n\t\t\t\t\tout << \"penwidth=\\\"20\\\" \";\n\t\t\t\telse\n\t\t\t\t\tout << \"penwidth=\\\"15\\\" \";\n\t\t\t\tout << \"]\";\n\t\t\t}\n\n\tprivate:\n\t\tGraph& _g;\n\t\tstd::vector<std::set<Graph::edge_descriptor>> _main_path_sets;\n\t\tconst std::vector<std::string> main_path_colors;\n};\n\n\nint main(int argc, char *argv[])\n{\n\tstd::ifstream input_file(argv[1]);\t\n\n\tstd::set<std::size_t> forbidden_vertices;\n\tif(argc > 2)\n\t{\n\t\tstd::ifstream forbidden_file(argv[2]);\t\n\t\tstd::size_t i_forbidden;\n\t\twhile(!forbidden_file.eof())\n\t\t{\n\t\t\tforbidden_file >> i_forbidden;\t\n\t\t\tforbidden_vertices.insert(i_forbidden);\n\t\t}\n\t}\n\n\tauto g = read_graph_from_file(input_file, forbidden_vertices);\n\n\tstd::vector<Graph::vertex_descriptor> ordered_vertices(boost::num_vertices(g));\n\tstd::iota(ordered_vertices.begin(), ordered_vertices.end(), 0);\n\tstd::sort(ordered_vertices.begin(), ordered_vertices.end(), [&g](const Graph::vertex_descriptor& v1, const Graph::vertex_descriptor& v2)\n\t{\n\t\treturn boost::in_degree(v1,g) + boost::out_degree(v1,g) < boost::in_degree(v2,g) + boost::out_degree(v2,g);\n\t});\n\n\tfor (auto v : ordered_vertices) {\n\t\tstd::cout << boost::get(boost::vertex_name, g, v) << std::endl;\n\t}\n\n\tstd::cout << boost::num_vertices(g) << \" \" << boost::num_edges(g) << std::endl;\n\n\tMainPathAnalysis::set_increasing_edge_index(g);\n\n\t// add s and t vertex\n\tGraph::vertex_descriptor s, t;\n\tMainPathAnalysis::add_source_and_sink_vertex<Graph>(g, s, t);\n\n\t// compute spc weights\n\t// auto weights = MainPathAnalysis::generate_spc_weights(g, s, t);\n\tauto weights = MainPathAnalysis::generate_spc_weights_big_int(g, s, t);\n\n\t// compute global main path\n\t// double alpha = 1;\n\t// do {\n\t\t// main_path.clear();\n\t\t// // MainPathAnalysis::localForward(std::back_inserter(main_path), g, weights, s, t);\n\t\t// // MainPathAnalysis::localForward(std::back_inserter(main_path), g, weights, s, t);\n\t\t// MainPathAnalysis::globalAlpha(std::back_inserter(main_path), g, weights, s, t, alpha);\n\t\t// alpha += 1;\n\t\t// std::cout << main_path.size() << \" \" << alpha << std::endl;\n\t// }\n\t// while(main_path.size() > 50);\n\n\tstd::vector<Graph::edge_descriptor> main_path_local, main_path_global, main_path_alpha;\n\tMainPathAnalysis::localForward<Graph, MainPathAnalysis::BigInt, std::back_insert_iterator<std::vector<Graph::edge_descriptor>>>(std::back_inserter(main_path_local), g, weights, s, t);\n\t// MainPathAnalysis::global(std::back_inserter(main_path_global), g, weights, s, t);\n\n\tif(argc > 5)\n\t{\n\t\tmain_path_local.clear();\n\n\t\tstd::cout << \"Alpha Main Path\" << std::endl;\n\t\tstd::size_t max_length = std::stoul(argv[5]);\n\n\t\tMainPathAnalysis::BigInt upper_alpha = 1;\n\t\tMainPathAnalysis::BigInt lower_alpha = 0;\n\n\t\tMainPathAnalysis::globalAlpha(std::back_inserter(main_path_local), g, weights, s, t, lower_alpha);\n\n\t\t// multiply by 2 until bigger\n\t\twhile(main_path_local.size() > max_length)\n\t\t{\n\t\t\tmain_path_local.clear();\n\t\t\tMainPathAnalysis::globalAlpha(std::back_inserter(main_path_local), g, weights, s, t, upper_alpha);\n\t\t\tupper_alpha *= 2;\n\t\t}\n\n\t\tstd::cout << \"UPPER ALPHA \" << upper_alpha << std::endl;\n\n\t\t// binary search\n\t\tbool found = false;\n\t\twhile(!found)\n\t\t{\n\t\t\tstd::cout << \"loop\" << std::endl;\n\t\t\tMainPathAnalysis::BigInt middle_alpha = (upper_alpha + lower_alpha) / 2;\n\n\t\t\tstd::cout <<  lower_alpha << std::endl;\n\t\t\tstd::cout <<  middle_alpha << std::endl;\n\t\t\tstd::cout <<  upper_alpha << std::endl;\n\n\t\t\tmain_path_local.clear();\n\t\t\tMainPathAnalysis::globalAlpha(std::back_inserter(main_path_local), g, weights, s, t, middle_alpha);\n\n\t\t\tstd::cout << \"SIZE: \" << main_path_local.size() << std::endl;\n\n\t\t\tif(middle_alpha == upper_alpha || middle_alpha == lower_alpha)\n\t\t\t\tbreak;\n\n\t\t\tif(main_path_local.size() > max_length)\n\t\t\t\tlower_alpha = middle_alpha;\n\t\t\telse\n\t\t\t\tupper_alpha = middle_alpha;\n\n\t\t\tif(main_path_local.size() == max_length)\n\t\t\t\tfound = true;\n\n\t\t\tstd::cout << std::endl;\n\n\n\t\t}\t\n\n\t}\n\n\t// remove s and t from main path and from copy of graph\n\t// MainPathAnalysis::remove_edges_containing_source_or_sink(g, s, t, main_path_global);\n\tMainPathAnalysis::remove_edges_containing_source_or_sink(g, s, t, main_path_local);\n\t// MainPathAnalysis::remove_edges_containing_source_or_sink(g, s, t, main_path_alpha);\n\tMainPathAnalysis::remove_source_and_sink_vertex(g, s, t);\n\n\t// build json object of main path\n\t// EdgeList main_path_edges;\n\t// for (auto e : main_path) \n\t\t// main_path_edges.push_back({ boost::source(e,g), boost::target(e,g) });\n\n\t// _global_main_path_cache.insert({ category_id, std::move(main_path_edges) });\n\n\n\tstd::cout << \"main_path_local: \" << main_path_local.size() << std::endl;\n\tstd::cout << \"main_path_global: \" << main_path_global.size() << std::endl;\n\tstd::cout << \"main_path_alpha: \" << main_path_alpha.size() << std::endl;\n\n\tif(argc > 3)\n\t{\n\t\tstd::ofstream output_file(argv[3]);\n\t\tVertexLabelWriter vertex_label_writer(g, { main_path_local });\n\t\tEdgeLabelWriter edge_label_writer(g, { main_path_local });\n\t\tboost::write_graphviz(output_file, g, vertex_label_writer, edge_label_writer);\n\t}\n\n\tif(argc > 4)\n\t{\n\t\tstd::ofstream output_file(argv[4]);\n\n\t\tconst auto& mp = main_path_local;\n\t\tGraph mp_graph(mp.size() + 1);\n\t\tstd::size_t i_vertex = 0;\n\t\tfor (const auto& e : mp) {\n\t\t\tboost::add_edge(i_vertex, i_vertex+1, mp_graph);\t\n\t\t\tboost::put(boost::vertex_name, mp_graph, i_vertex, boost::get(boost::vertex_name, g, boost::source(e,g)));\n\t\t\tboost::put(boost::vertex_finish_time, mp_graph, i_vertex, boost::get(boost::vertex_finish_time, g, boost::source(e,g)));\n\t\t\ti_vertex++;\n\t\t}\n\t\tboost::put(boost::vertex_name, mp_graph, i_vertex, boost::get(boost::vertex_name, g, boost::target(mp.back(),g)));\n\t\tboost::put(boost::vertex_finish_time, mp_graph, i_vertex, boost::get(boost::vertex_finish_time, g, boost::target(mp.back(),g)));\n\n\t\tVertexLabelWriter vertex_label_writer(mp_graph);\n\t\tboost::write_graphviz(output_file, mp_graph, vertex_label_writer);\n\t}\n\n\treturn 0;\n}\n", "meta": {"hexsha": "35627ec024b5344817cfb30704cec8a3313e59d5", "size": 10286, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/backend/main_manuallyComputeNetwork.cpp", "max_stars_repo_name": "bencabrera/wikiMainPath", "max_stars_repo_head_hexsha": "a42e81a8fbe119e858548045653b2a22068a34f8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/backend/main_manuallyComputeNetwork.cpp", "max_issues_repo_name": "bencabrera/wikiMainPath", "max_issues_repo_head_hexsha": "a42e81a8fbe119e858548045653b2a22068a34f8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/backend/main_manuallyComputeNetwork.cpp", "max_forks_repo_name": "bencabrera/wikiMainPath", "max_forks_repo_head_hexsha": "a42e81a8fbe119e858548045653b2a22068a34f8", "max_forks_repo_licenses": ["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.9819277108, "max_line_length": 184, "alphanum_fraction": 0.6750923585, "num_tokens": 2887, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5964331319177487, "lm_q2_score": 0.5039061705290805, "lm_q1q2_score": 0.30054633548133863}}
{"text": "/**\n * @file methods/ann/layer/highway.hpp\n * @author Konstantin Sidorov\n * @author Saksham Bansal\n *\n * Definition of the Highway layer.\n *\n * mlpack is free software; you may redistribute it and/or modify it under the\n * terms of the 3-clause BSD license.  You should have received a copy of the\n * 3-clause BSD license along with mlpack.  If not, see\n * http://www.opensource.org/licenses/BSD-3-Clause for more information.\n */\n#ifndef MLPACK_METHODS_ANN_LAYER_HIGHWAY_HPP\n#define MLPACK_METHODS_ANN_LAYER_HIGHWAY_HPP\n\n#include <mlpack/prereqs.hpp>\n\n#include <boost/ptr_container/ptr_vector.hpp>\n\n#include \"../visitor/delete_visitor.hpp\"\n#include \"../visitor/delta_visitor.hpp\"\n#include \"../visitor/output_height_visitor.hpp\"\n#include \"../visitor/output_parameter_visitor.hpp\"\n#include \"../visitor/output_width_visitor.hpp\"\n\n#include \"layer_types.hpp\"\n#include \"add_merge.hpp\"\n\nnamespace mlpack {\nnamespace ann /** Artificial Neural Network. */ {\n\n/**\n * Implementation of the Highway layer. The Highway class can vary its behavior\n * between that of feed-forward fully connected network container and that\n * of a layer which simply passes its inputs through depending on the transform\n * gate. Note that the size of the input and output matrices of this class\n * should be equal.\n *\n * For more information, refer the following paper.\n *\n * @code\n * @article{Srivastava2015,\n *   author  = {Rupesh Kumar Srivastava, Klaus Greff, Jurgen Schmidhuber},\n *   title   = {Training Very Deep Networks},\n *   journal = {Advances in Neural Information Processing Systems},\n *   year    = {2015},\n *   url     = {https://arxiv.org/abs/1507.06228},\n * }\n * @endcode\n *\n * @tparam InputDataType Type of the input data (arma::colvec, arma::mat,\n *         arma::sp_mat or arma::cube).\n * @tparam OutputDataType Type of the output data (arma::colvec, arma::mat,\n *         arma::sp_mat or arma::cube).\n */\ntemplate <\n    typename InputDataType = arma::mat,\n    typename OutputDataType = arma::mat,\n    typename... CustomLayers>\nclass Highway\n{\n public:\n  //! Create the Highway object.\n  Highway();\n\n  /**\n   * Create the Highway object.\n   *\n   * @param inSize The number of input units.\n   * @param model Expose all the network modules.\n   */\n  Highway(const size_t inSize, const bool model = true);\n\n  //! Destroy the Highway object.\n  ~Highway();\n\n  /**\n   * Reset the layer parameter.\n   */\n  void Reset();\n\n  /**\n   * Ordinary feed-forward pass of a neural network, evaluating the function\n   * f(x) by propagating the activity forward through f.\n   *\n   * @param input Input data used for evaluating the specified function.\n   * @param output Resulting output activation.\n   */\n  template<typename eT>\n  void Forward(const arma::Mat<eT>& input, arma::Mat<eT>& output);\n\n  /**\n   * Ordinary feed-backward pass of a neural network, calculating the function\n   * f(x) by propagating x backwards through f. Using the results from the\n   * feed-forward pass.\n   *\n   * @param * (input) The propagated input activation.\n   * @param gy The backpropagated error.\n   * @param g The calculated gradient.\n   */\n  template<typename eT>\n  void Backward(const arma::Mat<eT>& /* input */,\n                const arma::Mat<eT>& gy,\n                arma::Mat<eT>& g);\n\n  /**\n   * Calculate the gradient using the output delta and the input activation.\n   *\n   * @param input The input parameter used for calculating the gradient.\n   * @param error The calculated error.\n   * @param gradient The calculated gradient.\n   */\n  template<typename eT>\n  void Gradient(const arma::Mat<eT>& input,\n                const arma::Mat<eT>& error,\n                arma::Mat<eT>& gradient);\n\n  /**\n   * Add a new module to the model.\n   *\n   * @param args The layer parameter.\n   */\n  template <class LayerType, class... Args>\n  void Add(Args... args)\n  {\n    network.push_back(new LayerType(args...));\n    networkOwnerships.push_back(true);\n  }\n\n  /**\n   * Add a new module to the model.\n   *\n   * @param layer The Layer to be added to the model.\n   */\n  void Add(LayerTypes<CustomLayers...> layer)\n  {\n    network.push_back(layer);\n    networkOwnerships.push_back(false);\n  }\n\n  //! Return the modules of the model.\n  std::vector<LayerTypes<CustomLayers...> >& Model()\n  {\n    if (model)\n    {\n      return network;\n    }\n\n    return empty;\n  }\n\n  //! Get the parameters.\n  OutputDataType const& Parameters() const { return weights; }\n  //! Modify the parameters.\n  OutputDataType& Parameters() { return weights; }\n\n  //! Get the input parameter.\n  InputDataType const& InputParameter() const { return inputParameter; }\n  //! Modify the input parameter.\n  InputDataType& InputParameter() { return inputParameter; }\n\n  //! Get the output parameter.\n  OutputDataType const& OutputParameter() const { return outputParameter; }\n  //! Modify the output parameter.\n  OutputDataType& OutputParameter() { return outputParameter; }\n\n  //! Get the delta.\n  OutputDataType const& Delta() const { return delta; }\n  //! Modify the delta.\n  OutputDataType& Delta() { return delta; }\n\n  //! Get the gradient.\n  OutputDataType const& Gradient() const { return gradient; }\n  //! Modify the gradient.\n  OutputDataType& Gradient() { return gradient; }\n\n  //! Get the number of input units.\n  size_t InSize() const { return inSize; }\n\n  /**\n   * Serialize the layer.\n   */\n  template<typename Archive>\n  void serialize(Archive& ar, const unsigned int /* version */);\n\n private:\n  //! Locally-stored number of input units.\n  size_t inSize;\n\n  //! Parameter which indicates if the modules should be exposed.\n  bool model;\n\n  //! Indicator if we already initialized the model.\n  bool reset;\n\n  //! Locally-stored network modules.\n  std::vector<LayerTypes<CustomLayers...> > network;\n\n  //! The list of network modules we are responsible for.\n  std::vector<bool> networkOwnerships;\n\n  //! Locally-stored empty list of modules.\n  std::vector<LayerTypes<CustomLayers...> > empty;\n\n  //! Locally-stored weight object.\n  OutputDataType weights;\n\n  //! Locally-stored delta object.\n  OutputDataType delta;\n\n  //! Locally-stored gradient object.\n  OutputDataType gradient;\n\n  //! Weights for transformation of output.\n  OutputDataType transformWeight;\n\n  //! Bias for transformation of output.\n  OutputDataType transformBias;\n\n  //! Locally-stored transform gate parameters.\n  OutputDataType transformGate;\n\n  //! Locally-stored transform gate activation.\n  OutputDataType transformGateActivation;\n\n  //! Locally-stored transform gate error.\n  OutputDataType transformGateError;\n\n  //! Locally-stored input parameter object.\n  InputDataType inputParameter;\n\n  //! Locally-stored output parameter object.\n  OutputDataType outputParameter;\n\n  //! The input width.\n  size_t width;\n\n  //! The input height.\n  size_t height;\n\n  //! The normal output without highway network.\n  OutputDataType networkOutput;\n\n  //! Locally-stored delta visitor.\n  DeltaVisitor deltaVisitor;\n\n  //! Locally-stored output parameter visitor.\n  OutputParameterVisitor outputParameterVisitor;\n\n  //! Locally-stored delete visitor.\n  DeleteVisitor deleteVisitor;\n\n  //! Locally-stored output width visitor.\n  OutputWidthVisitor outputWidthVisitor;\n\n  //! Locally-stored output height visitor.\n  OutputHeightVisitor outputHeightVisitor;\n}; // class Highway\n\n} // namespace ann\n} // namespace mlpack\n\n// Include implementation.\n#include \"highway_impl.hpp\"\n\n#endif\n", "meta": {"hexsha": "8b15ff66b85ef27e08230ab65b57716641df966e", "size": 7370, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/mlpack/methods/ann/layer/highway.hpp", "max_stars_repo_name": "gaurav-singh1998/mlpack", "max_stars_repo_head_hexsha": "c104a2dcf0b51a98d9d6fcfc01d4e7047cc83872", "max_stars_repo_licenses": ["BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-02-29T17:39:51.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-16T23:36:01.000Z", "max_issues_repo_path": "src/mlpack/methods/ann/layer/highway.hpp", "max_issues_repo_name": "R-Aravind/mlpack", "max_issues_repo_head_hexsha": "99d11a9b4d379885cf7f8160d8c71fb792fa1bbc", "max_issues_repo_licenses": ["BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/mlpack/methods/ann/layer/highway.hpp", "max_forks_repo_name": "R-Aravind/mlpack", "max_forks_repo_head_hexsha": "99d11a9b4d379885cf7f8160d8c71fb792fa1bbc", "max_forks_repo_licenses": ["BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-06-05T13:27:26.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-23T09:44:31.000Z", "avg_line_length": 27.6029962547, "max_line_length": 79, "alphanum_fraction": 0.6972862958, "num_tokens": 1727, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6150878696277513, "lm_q2_score": 0.4882833952958347, "lm_q1q2_score": 0.3003371933871201}}
{"text": "/***************************************************************************\n                          bddlsph.cc  -  description\n                             -------------------\n    begin                : Mon Jun 11 2007\n    copyright            : (C) 2005 by Knut-Helge Vik\n    email                : knuthelv@ifi.uio.no\n ***************************************************************************/\n#include \"bddlsph.h\"\n#include \"../treealgs/dijkstra_sp.h\"\n#include <fstream>\n#include \"../simtime.h\"\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/io.hpp>\n\nusing namespace std;\nusing namespace boost;\nusing namespace TreeAlgorithms;\n\n/* -------------------------------------------------------------------------\n\t\n\tAlgorithm(): Minimum Diameter Degree Limited Shortest Path Heuristic \n\t\t\t\t\t\t\tstart function\n\n------------------------------------------------------------------------- */\nvoid\nBDDLShortestPathHeuristic::Algorithm(vertex_descriptorN zsource, double D)\n{\n\tDB = D;\n\tinit(zsource, DB);\t// identify z-nodes and store them in VertexSet ZVertSet\n\tif(num_zvertices <= 0)\n\t{\n\t\tcout << WRITE_FUNCTION << \" Error: No Z-vertices.\" << endl;\texit(0);\n\t}\n\tcerr << WRITE_FUNCTION << \" Start SPH zsource \" << zsource << \" and \" << num_zvertices << \" znodes\" << endl ;\n\n\t// -- Start SPH Algorithm --\n\tT_bddlsph.insertVertex(zsource, g); \t\t\t\t// add source to the SPH tree\n\tZVertSet.erase(zsource);\n\tRunDijkstraForEveryZ(g);\t\t\t\t\t\t\t// find SP for every z-node and store in SPKeeper\n\n\twhile(!ZVertSet.empty())\n\t{\t\n\t\tdiameterBroken.clear();\n\t\tdegreeBroken.clear();\n\n\t\tint z = -1;\n\t\tPathVector newPath; \t\t\t\t\t\t\t// .first contains path to new z-node to be added to T_bddlsph\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t// .second is the tree-vertex link -> TODO: probably not needed\n\t\tif(!ExtractClosestZ(newPath, z)) \t\t\t\t// extract the z-node closest to T_bddlsph\n\t\t{\n\t\t\tif(!TreeAlgorithms::relaxDegreeAndDiameter(degreeBroken, degree_bound, diameterBroken, diameter_bound)) break; \n\t\t\tif(!TreeAlgorithms::isRelaxWorking(degreeBroken, diameterBroken)) break;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tASSERTING(z > -1);\n\n\t\t\tAddTreeSPH(newPath); // add the new path to T_bddlsph\n\t\t\tupdateDist(z);\n\t\t\t//char c = getchar();\n\t\t}\n\t}\n\t\n\t// -- start debug --\n\t//cerr << WRITE_FUNCTION << \"Produced Steiner Tree: \" << endl;\n\t//T_bddlsph.print();\n\t//T_bddlsph.printVertexState(cerr);\n\t// -- end debug --\n}\n\n/* -------------------------------------------------------------------------\n\n\tExtractClosestZ(): Returns the vertex that is closest to the T_bddlsph\n\n\t\tsrc: Dijkstra_shortest_path from this node\n\t\tp: next/parent pointers\n\t\tdistances: distances from src to each other node in the graph\n\n\tIDEA: iterate through the z-vertices and check how close they are to \n\tthe T_bddlsph return the closest z-vertex and add the path to the T_bddlsph\n\n --------------------------------------------------------------------------*/\nbool\nBDDLShortestPathHeuristic::ExtractClosestZ(PathVector &newPath, int &z_closest)\n{\n\tdouble distToTree\t= MAXIMUM_WEIGHT; //(numeric_limits<double>::max)(); \n\tint z_in = - 1;\n\tz_closest = -1;\n\tPathVector tempPath;\n\n\tVertexSet diameterNotBroken;\n\t// iterate through the z-vertices and check how close they are to T_bddlsph\n\tfor(VertexSet::iterator zit = ZVertSet.begin(), zit_end = ZVertSet.end(); zit != zit_end; ++zit)\n\t{\n\t\tvertex_descriptorN zAddToTree = *zit;\n\t\t\n\t\tASSERTING(!T_bddlsph.V.contains(zAddToTree));\n\t\t//cerr << WRITE_FUNCTION  << \" Z : \" << zAddToTree << endl;\n\n\t\tShortestPathKeeper &spk = findSPMaps(zAddToTree); \n\t\t\n\t\tVertexSet_it tit_bddlsph, tit_bddlsph_end;\n\t\tfor(tit_bddlsph = T_bddlsph.V.begin(), tit_bddlsph_end = T_bddlsph.V.end(); tit_bddlsph != tit_bddlsph_end; ++tit_bddlsph) // check distance between new znode zit to every tree node tit_bddlsph\n\t\t{\n\t\t\tvertex_descriptorN zInTree = *tit_bddlsph;\n\t\t\tdouble new_dist = spk.zdistance[zInTree];\n\t\t\tdouble new_diameter = ecc[zInTree] + spk.zdistance[zInTree];\n\t\t\t\n\t\t\t//cerr << zInTree << \": new dist \" << new_dist << \" new diameter \" << new_diameter << \" out degree zintree \" << getOutDegree(T_bddlsph.g, zInTree) << \" bound \" << degree_bound[zInTree] << endl;\n\t\t\t// is the new z-node closer than the previous and within diameter bound -> then update distance etc.\n\t\t\t//if(distToTree > new_dist && CheckPath(tempPath, zInTree, zAddToTree, spk.zparent))\t// is the new z-node closer than the previous -> then update distance etc.\n\t\t\tif(distToTree > new_dist && new_diameter <= diameter_bound[zAddToTree] && getOutDegree(T_bddlsph.g, zInTree) < degree_bound[zInTree]) // is the new z-node closer than the previous -> then update distance etc. \n\t\t\t{\n\t\t\t\tdiameterNotBroken.insert(zAddToTree);\n\t\t\t\t//diameterBroken.erase(zAddToTree);\n\t\t\t\t//if(CheckPath(tempPath, zInTree, zAddToTree, spk.zparent))\n\t\t\t\tif(FindPath(tempPath, zInTree, zAddToTree, spk.zparent, spk.zdistance))\n\t\t\t\t{\n\t\t\t\t\tdistToTree \t= new_dist;  \t\t\t\t\t// update shortest distance\n\t\t\t\t\tz_closest\t= zAddToTree;\n\t\t\t\t\tz_in\t\t= zInTree;\n\t\t\t\t\tnewPath\t\t= tempPath;\n\t\t\t\t\t//cerr << zAddToTree << \" new closest: \" << zInTree << \": new dist \" << new_dist << \" distToTree \" << distToTree << \" new diameter \" << new_diameter << \" diameter bound \" << diameter_bound[zAddToTree] << \" degree limit \" << degree_bound[zInTree] << endl;\n\t\t\t\t}\n\t\t\t}\n\t\n\t\t\tif(distToTree == MAXIMUM_WEIGHT)\n\t\t\t{\n\t\t\t\tif(new_diameter > diameter_bound[zAddToTree]) diameterBroken.insert(zAddToTree);\n\t\t\t\tif(getOutDegree(T_bddlsph.g, zInTree) >= degree_bound[zInTree]) degreeBroken.insert(zInTree);\n\t\t\t}\n\t\t\t\t\n\t\t\ttempPath = PathVector(); \n\t\t\n\t\t}\n\t}\n\t\n\tif(distToTree < MAXIMUM_WEIGHT) return true;\n\t\n\t//cerr << \" diameterbroken \" << diameterBroken << endl;\n\tdiameterBroken = diameterBroken - diameterNotBroken;\n\t//if(!diameterBroken.empty() || !degreeBroken.empty())\t\n\t//cerr << \" diameterbroken \" << diameterBroken << \" degreebroken \" << degreeBroken << \" diameterNotBroken \" << diameterNotBroken << endl;\n\n\treturn false;\n}\n\nbool \nBDDLShortestPathHeuristic::CheckPath(PathVector &newPath, vertex_descriptorN tree_vert, vertex_descriptorN z_vert, const ParentVector &zparent)\n{\n\tdouble tree_depth = ecc[tree_vert];\n\t\n\tASSERTING(tree_vert != z_vert);\n\tvertex_descriptorN traverse_vert = tree_vert;\n\tdo{\t\n\t\tbool intact = true;\t\n\t\tif(getOutDegree(T_bddlsph.g, traverse_vert) >= degree_bound[traverse_vert]) \n\t\t{\n\t\t\t//cerr << traverse_vert << \" degree broken \" << degree_bound[traverse_vert] << endl;\n\t\t\tdegreeBroken.insert(traverse_vert);\n\t\t\tintact = false;\n\t\t}\n\n\t\tpair<edge_descriptorN, bool> ep = edge(traverse_vert, zparent[traverse_vert], g);\n\t\tASSERTING(ep.second);\n\t\t//cerr << ep.first << \" tree_depth[\" << traverse_vert << \"] = \" << tree_depth << \" + \" << g[ep.first].weight << endl;\n\t\t//if(tree_depth > diameter_bound[traverse_vert])\n\t\tif(ZVertSet.contains(traverse_vert) && tree_depth > diameter_bound[traverse_vert])\n\t\t{\n\t\t\t//cerr << traverse_vert << \" diameter broken \" << tree_depth << \" > \" << diameter_bound[traverse_vert] << endl;\n\t\t\tdiameterBroken.insert(traverse_vert);\n\t\t\tintact = false;\n\t\t}\n\n\t\tif(!intact) return intact;\n\t\t\n\t\ttree_depth = tree_depth + g[ep.first].weight;\n\n\t\tnewPath.first.push_front(traverse_vert);\n\t\ttraverse_vert = zparent[traverse_vert];\t\n\t}while(traverse_vert != z_vert);\n\t\n\tnewPath.first.push_front(traverse_vert); \t\t// add last node\n\tASSERTING(newPath.first.size() > 1);\n\n\t//if(tree_depth > diameter_bound[traverse_vert])\n\tif(ZVertSet.contains(traverse_vert) && tree_depth > diameter_bound[traverse_vert])\n\t{\n\t\t//cerr << traverse_vert << \" diameter broken \" << tree_depth << \" > \" << diameter_bound[traverse_vert] << endl;\n\t\tdiameterBroken.insert(traverse_vert);\n\t\treturn false;\n\t}\n\n\treturn true;\n}\n\n/* -------------------------------------------------------------------------\n\n\tFindDistance():\tFind distance from z_vert to tree_vert using zparent \n\t\t\tand zdistance from DijkstraSP(z_vert)\n\n------------------------------------------------------------------------- */\nbool\nBDDLShortestPathHeuristic::FindPath(PathVector &newPath, vertex_descriptorN tree_vert, vertex_descriptorN z_vert, const ParentVector &zparent, const DistanceVector &zdistance) \n{\n\tbool intact = true;\n\tASSERTING(tree_vert != z_vert);\n\tvertex_descriptorN traverse_vert = tree_vert;\n\tdo{\t \n\t\tif(getOutDegree(T_bddlsph.g, traverse_vert) >= degree_bound[traverse_vert]) \n\t\t{\n\t\t\tdegreeBroken.insert(traverse_vert);\n\t\t    //cerr << WRITE_FUNCTION << \" can't add path violating degree bound \" << getOutDegree(T_bddlsph.g, traverse_vert) << \">=\" <<  degree_bound[traverse_vert] << endl;\n\t\t\tintact = false;\n\t\t}\n\t\tif(!T_bddlsph.V.contains(traverse_vert) && ecc[traverse_vert] + zdistance[traverse_vert] > diameter_bound[traverse_vert])\n\t\t{\n\t\t \t//cerr << WRITE_FUNCTION << \" can't add path violating diameter bound \" << ecc[traverse_vert] + zdistance[traverse_vert] << \">\" <<  diameter_bound[traverse_vert] << endl;\n\t\t\tdiameterBroken.insert(traverse_vert);\n\t\t\tintact = false;\n\t\t}\n\t\t\n\t\tif(!intact) return intact;\n\t\t\n\t\tnewPath.first.push_front(traverse_vert);\n\t\ttraverse_vert = zparent[traverse_vert];\t\n\t}while(traverse_vert != z_vert);\n\t\n\tnewPath.first.push_front(traverse_vert); \t\t// add last node\n\tASSERTING(newPath.first.size() > 1);\n\treturn intact;\n}\n\n/* -------------------------------------------------------------------------\n\n\tAddSPHTree(): Returns the vertex that is closest to the source\n\t\tif it is not already in the SPH-tree.\n\n\tall_vertex_info.first: path (vertex_descriptors) to new z_node \n\tall_vertex_info.second: node in the T_bddlsph (steiner or z-node) that \n\t\tlinks the new z-node to T_bddlsph\n --------------------------------------------------------------------------*/\nvoid\nBDDLShortestPathHeuristic::AddTreeSPH(PathVector &newPath)\n{\n\tASSERTING(newPath.first.size() > 1);\n\tfor(list<vertex_descriptorN>::reverse_iterator vit = newPath.first.rbegin(), vit_end = newPath.first.rend(); vit != vit_end; )\n\t{\n\t\t// iterate\n\t\tvertex_descriptorN u = *vit;\n\t\tvit++;\n\t\tif(vit == vit_end) break;\n\t\tvertex_descriptorN v = *vit;\n\t\t\n\t\tpair<edge_descriptorN, bool> ep = edge(u, v, g);\n\t\tASSERTING(ep.second);\n\n\t\tASSERTING(near_[u] > -1);\n\t\n\t\t//cerr << \"1 (\" << u << \",\" << v << \")\" << \" near[\" << u << \"] \" << near[u] << \" near[\" << v << \"] \" << near[v] << \" ecc[\" << v << \"] \" << ecc[v] << endl;\n\n\t\tif(near_[v] < 0) \n\t\t{\n\t\t\tnear_[v] = u;\n\t\t\tecc[v] = ecc[u] + g[ep.first].weight;\n\t\t}\n\t\t//cerr << \"2 (\" << u << \",\" << v << \")\" << \" near[\" << u << \"] \" << near[u] << \" near[\" << v << \"] \" << near[v] << \" ecc[\" << v << \"] \" << ecc[v] << endl;\n\t}\n\t\n\tbool done = false;\n\tlist<vertex_descriptorN>::iterator vit, vit_end; \n\tfor(vit = newPath.first.begin(), vit_end = newPath.first.end(); vit != vit_end; )\n\t{\n\t\t// iterate\n\t\tvertex_descriptorN u = *vit;\n\t\tvit++;\n\t\tif(vit == vit_end) break;\n\t\tvertex_descriptorN v = *vit;\n\n\t\t// -- debug --\n\t\t//cerr << \"adding (\" << u << \",\" << v << \")\" << endl;\n\t\t// -- end debug --\n\n\t\tif(T_bddlsph.V.contains(v)) done = true;\n\t\t\n\t\tT_bddlsph.insertEdge(u, v, g); \n\t\t\n\t\tZVertSet.erase(u); \n\t\tZVertSet.erase(v);\n\t\n\t\t// -- debug --\n\t\t/*if(getOutDegree(T_bddlsph.g, u) > degree_bound[u]) \n\t\t\tcerr << \" inserted \" << u << \" degree bound \" << degree_bound[u] << \" degree is \" << getOutDegree(T_bddlsph.g, u) << endl;\n\t\tif(getOutDegree(T_bddlsph.g, v) > degree_bound[v]) \n\t\t\tcerr << \" inserted \" << v << \" degree bound \" << degree_bound[v] << \" degree is \" << getOutDegree(T_bddlsph.g, v) << endl;\n\t\tif(ecc[u] > diameter_bound[u]) \n\t\t\tcerr << \" inserted \" << u << \" diameter bound \" << diameter_bound[u] << \" ecc is \" << ecc[u] << endl;\n\t\tif(ecc[v] > diameter_bound[v]) \n\t\t\tcerr << \" inserted \" << v << \" diameter bound \" << diameter_bound[v] << \" ecc is \" << ecc[v] << endl;*/\n\t\t// -- debug end --\n\n\t\tif(done) break;\n\t}\n}\n\nvoid\nBDDLShortestPathHeuristic::updateDist(int z)\n{\n\tASSERTING(z > -1);\n\tASSERTING(inputT.V.contains(z));\n\t//cerr << \" z : \" << g[z] << endl;\n\n\tASSERTING(g[z].vertexState == GROUP_MEMBER);\n\n\tVertexSet::iterator vit, vit_end, vit_in, vit_in_end;\n\tShortestPathKeeper &spk_z = findSPMaps(z); \n\t\n\t//cerr << WRITE_FUNCTION << \" z \" << z << \" near[z] \" << near[z] << \" spk.zdistance[near[z]]\" << spk_z.zdistance[near[z]] << endl;\n\tASSERTING(near_[z] > -1);\n\tASSERTING(ecc[near_[z]] >= 0);\n\n\t// set dist(z,u) and ecc(z)\n\tfor(vit = T_bddlsph.V.begin(), vit_end = T_bddlsph.V.end(); vit != vit_end; ++vit)\n\t{\n\t\tif(dist(near_[z],*vit) > 0) dist(z,*vit) = dist(near_[z],*vit) + spk_z.zdistance[near_[z]]; \n\t}\n\t\n\tdist(z,z) = 0;\n\tecc[z] = ecc[near_[z]] + spk_z.zdistance[near_[z]];  \n\t\n\t// update dist(near(z), u) and ecc(near(z))\n\tdist(near_[z],z) = spk_z.zdistance[near_[z]];  \n\tif(ecc[near_[z]] <= 0) ecc[near_[z]] = spk_z.zdistance[near_[z]];  \n\t\n\t// update other nodes' values of dist and ecc\n\tfor(vit = T_bddlsph.V.begin(), vit_end = T_bddlsph.V.end(); vit != vit_end; ++vit)\n\t{\n\t\tASSERTING(dist(*vit, near_[z]) >= 0);\n\t\tASSERTING(dist(*vit, z) >= 0);\n\t\tASSERTING(ecc[*vit] >= 0);\n\n\t\tdist(*vit,z) = dist(*vit, near_[z]) + spk_z.zdistance[near_[z]]; \n\t\tecc[*vit] = std::max(ecc[*vit], dist(*vit,z));\t\n\t}\n\t\n\t//cerr << \" update the near values for other nodes in G \" << endl;\n\tfor(vit = ZVertSet.begin(), vit_end = ZVertSet.end(); vit != vit_end; ++vit)\n\t{\n\t\tShortestPathKeeper &spk = findSPMaps(*vit); \n\t\n\t\tdouble dc_near_vit = (numeric_limits<double>::max)(), od_near_vit = 0; \n\t\tif(near_[*vit] > -1) \n\t\t{\n\t\t\tdc_near_vit = degree_bound[near_[*vit]]; \n\t\t\tod_near_vit = getOutDegree(T_bddlsph.g, near_[*vit]);\n\t\t}\n\t\t\t\n\t\tdouble curr_ecc = (std::numeric_limits<double>::max)(); \n\t\tif(near_[*vit] > -1 && od_near_vit < dc_near_vit) curr_ecc = ecc[near_[*vit]] + spk.zdistance[near_[*vit]];  \n\n\t\tif(curr_ecc > diameter_bound[*vit] || (getOutDegree(T_bddlsph.g, z) >= degree_bound[z]))\n\t\t{\n\t\t\t//cerr << \" examine all nodes in T_bddlsph to determine near(\" << *vit << \")\t\" << endl;\n\t\t\tfor(vit_in = T_bddlsph.V.begin(), vit_in_end = T_bddlsph.V.end(); vit_in != vit_in_end; ++vit_in)\n\t\t\t{\n\t\t\t\tdouble new_ecc = ecc[*vit_in] + spk.zdistance[*vit_in];\n\t\t\t\t\n\t\t\t\t//cerr << \" curr ecc \" << curr_ecc << \" new ecc \" << new_ecc << endl;\n\t\t\t\tASSERTING(ecc[*vit_in] >= 0);\n\t\t\t\tASSERTING(spk.zdistance[*vit_in] >= 0);\n\t\t\t\t\n\t\t\t\tif(new_ecc < curr_ecc && getOutDegree(T_bddlsph.g, *vit_in) < degree_bound[*vit_in]) \n\t\t\t\t{ \n\t\t\t\t\t//cerr << \" new near [\" << *vit << \"] = \" << *vit_in << endl;\n\t\t\t\t\tnear_[*vit] = *vit_in;\n\t\t\t\t\tcurr_ecc = new_ecc;\n\t\t\t\t}\t\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\t//cerr << \"Compare w(\" << *vit << \",\" << near[*vit] << \") = \" << spk.zdistance[near[*vit]] << \" to w(\" << *vit << \",\" <<  z << \")= \" << spk_z.zdistance[near[*vit]] << endl;\n\t\t\t\t\n\t\t\tif(spk_z.zdistance[*vit] <= spk.zdistance[near_[*vit]])\n\t\t\t{\n\t\t\t\t//cerr << \" new near [\" << *vit << \"] = \" << z << endl;\n\t\t\t\tnear_[*vit] = z;\n\t\t\t}\n\t\t}\n\n\t\t//if(near[*vit] > -1)\n\t\t//{\n\t\t\t//if(curr_ecc >= diameter_bound[*vit]) diameterBroken.insert(*vit);\n\t\t\t//if(getOutDegree(T_bddlsph.g, near[*vit]) >= degree_bound[ near[*vit] ] ) degreeBroken.insert(near[*vit]);\n\n\t\t\t//cerr << \" diameterbroken \" << diameterBroken << \" degreebroken \" << degreeBroken << endl;\n\t\t//}\n\t}\n}\n\nvoid\nBDDLShortestPathHeuristic::init(vertex_descriptorN src, const double &DB)\n{\n\tvsVertexMap \tvsmap = get(&VertexProp::vertexState, g);\n\t\n\tVertexSet::const_iterator vit, vit_end, vit_in, vit_in_end;\n\tfor(vit = inputT.V.begin(), vit_end = inputT.V.end(); vit != vit_end; ++vit)\n\t{\t\n\t\tif(vsmap[*vit] == GROUP_MEMBER)\n\t\t{\n\t\t\tZVertSet.insert(*vit);\n\t\t\tnum_zvertices++;\n\t\t}\n\t\t\n\t\tdiameter_bound[*vit] = DB;\n\t\tdegree_bound[*vit] = getDegreeConstraint(g, *vit);\n\n\t\tecc[*vit] = 0;\t\t\n\t\tif(*vit != (int)src)\n\t\t{\n\t\t\tpair<edge_descriptorN, bool> ep = edge(*vit, src, g);\n\t\t\tif(ep.second) near_[*vit] = src;\n\t\t\telse near_[*vit] = -1;\n\t\t}\n\t\telse \n\t\t{\n\t\t\tnear_[*vit] = *vit;\n\t\t\tecc[*vit] = 0;\n\t\t}\n\t\tfor(vit_in = inputT.V.begin(), vit_in_end = inputT.V.end(); vit_in != vit_in_end; ++vit_in)\n\t\t\tdist(*vit,*vit_in) = 0;\n\t}\n\tASSERTING(!ZVertSet.empty());\n}\n\n", "meta": {"hexsha": "63e2a33b595f0ae62df3ec3f173dad3320cacdc3", "size": 15741, "ext": "cc", "lang": "C++", "max_stars_repo_path": "GraphLib/smtalgs/bddlsph.cc", "max_stars_repo_name": "intact-software-systems/cpp-software-patterns", "max_stars_repo_head_hexsha": "e463fc7eeba4946b365b5f0b2eecf3da0f4c895b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-09-03T07:23:11.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-03T07:23:11.000Z", "max_issues_repo_path": "GraphLib/smtalgs/bddlsph.cc", "max_issues_repo_name": "intact-software-systems/cpp-software-patterns", "max_issues_repo_head_hexsha": "e463fc7eeba4946b365b5f0b2eecf3da0f4c895b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "GraphLib/smtalgs/bddlsph.cc", "max_forks_repo_name": "intact-software-systems/cpp-software-patterns", "max_forks_repo_head_hexsha": "e463fc7eeba4946b365b5f0b2eecf3da0f4c895b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.1032110092, "max_line_length": 259, "alphanum_fraction": 0.6152086907, "num_tokens": 4691, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6150878555160665, "lm_q2_score": 0.4882833952958347, "lm_q1q2_score": 0.3003371864966187}}
{"text": "/* Copyright (C) 2017 IBM Corp.\n *  Licensed under the Apache License, Version 2.0 (the \"License\"); \n * you may not use this file except in compliance with the License. \n * You may obtain a copy of the License at\n *     http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, \n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,\n * either express or implied. See the License for the specific\n * language governing permissions and limitations under the License.\n */\n/***********************************************************************\nCRTmatrix: implements A matrix in CRT representation\n************************************************************************/\n\n#include <vector>\n#include <cassert>\n#include <cstdlib>\n//#include <mpfr.h>\n#include <NTL/mat_lzz_p.h>\n#include <NTL/BasicThreadPool.h>\n#include <NTL/ZZ.h>\n#include <NTL/FFT.h>\n#include <NTL/SmartPtr.h>\n\nNTL_CLIENT\n#include \"utils/tools.h\"\n#include \"DGaussSampler.h\"\n#include \"CRTmatrix.h\"\n#include \"TDMatrixParams.h\"\n\n//#define DEBUGPRINT\n\nCRTmatrix& CRTmatrix::leftMultBy(const CRTmatrix& M) // A := M*A\n{\n    FHE_TIMER_START;\n    assert(length()==params->kFactors);\n    NTL::zz_pPush ppush; // backup NTL's current modulus\n\n    // multi-threaded implementation, threads handle different moduli\n\n    EXEC_RANGE(length(), first, last)\n    //EXEC_RANGE(length(), first, last)\n    for (long i=first; i<last; i++)\n    {\n        params->zzp_context[i].restore();\n        mat_zz_p& matMod = (*this)[i];\n        const mat_zz_p& Mmod = M[i];\n        mul(matMod, Mmod, matMod);\n    }\n    //EXEC_RANGE_END\n    EXEC_RANGE_END\n    return *this;\n}\n\nCRTmatrix& CRTmatrix::leftMultBy(const mat_l& M) // A := M*A\n{\n    FHE_TIMER_START;\n    assert(length()==params->kFactors);\n    NTL::zz_pPush ppush; // backup NTL's current modulus\n\n    // multi-threaded implementation, threads handle different moduli\n    EXEC_RANGE(length(), first, last)\n    for (long i=first; i<last; i++)\n    {\n        params->zzp_context[i].restore();\n        mat_zz_p& matMod = (*this)[i];\n        mat_zz_p Mmod = conv<mat_zz_p>(M);\n        mul(matMod, Mmod, matMod);\n    }\n    EXEC_RANGE_END\n\n    return *this;\n}\n\nCRTmatrix& CRTmatrix::leftMultBy(const vec_l& u) // A := u*A\n{\n    FHE_TIMER_START;\n    assert(length()==params->kFactors);\n    NTL::zz_pPush ppush; // backup NTL's current modulus\n\n    // multi-threaded implementation, threads handle different moduli\n    EXEC_RANGE(length(), first, last)\n\n    for (long i=first; i<last; i++)\n    {\n        params->zzp_context[i].restore();\n        mat_zz_p& matMod = (*this)[i]; // A\n        const vec_zz_p umod = conv<vec_zz_p>(u);\n        vec_zz_p vTmp;\n        mul(vTmp, umod, matMod); // tmp = u*A\n\n        // copy vTmp back to matMod\n        matMod.SetDims(1, vTmp.length());\n        matMod[0] = vTmp;\n    }\n    EXEC_RANGE_END\n\n    return *this;\n}\n\n// Convert Mat<long> to CRT format, we assume that params are already set\nCRTmatrix& CRTmatrix::operator=(const mat_l& M) // A := M\n{\n    FHE_TIMER_START;\n    assert(params != NULL);\n\n    NTL::zz_pPush ppush; // backup NTL's current modulus\n    SetLength(params->kFactors);\n    for (long i=0; i<length(); i++)\n    {\n        params->zzp_context[i].restore();\n        conv((*this)[i], M);\n    }\n\n    return *this;\n}\n\n\n// Default assignment should work: NTL now guarantees\n// that assignment and default constructors work, even\n// \"out of context\"\nCRTmatrix& CRTmatrix::operator=(const CRTmatrix& other) // A := M\n{\n    FHE_TIMER_START;\n    params = other.params;\n    NTL::zz_pPush ppush; // backup NTL's current modulus\n    SetLength(other.length());\n    for (long i=0; i<params->kFactors; i++)\n    {\n        params->zzp_context[i].restore();\n        (*this)[i] = other[i];\n    }\n    return *this;\n}\n\nCRTmatrix& CRTmatrix::operator*=(const mat_l& M) // A := M*A\n{\n    FHE_TIMER_START;\n    assert(length()==params->kFactors);\n    NTL::zz_pPush ppush; // backup NTL's current modulus\n\n    // multi-threaded implementation, threads handle different moduli\n    EXEC_RANGE(length(), first, last)\n    mat_zz_p Mmod;\n    for (long i=first; i<last; i++)\n    {\n        params->zzp_context[i].restore();\n        mat_zz_p& Amod = (*this)[i];\n        Mmod = conv<mat_zz_p>(M);\n        mul(Amod, Amod, Mmod);\n    }\n    EXEC_RANGE_END\n\n    return *this;\n}\n\nCRTmatrix& CRTmatrix::operator*=(const CRTmatrix& M) // A := A*M\n{\n    FHE_TIMER_START;\n    assert(length()==params->kFactors\n           && M.length()==M.params->kFactors\n           && params==M.params);\n    NTL::zz_pPush ppush; // dibackup NTL's current modulus\n\n    // multi-threaded implementation, threads handle different moduli\n    EXEC_RANGE(length(), first, last)\n    for (long i=first; i<last; i++)\n    {\n        params->zzp_context[i].restore();\n        mat_zz_p& Amod = (*this)[i];\n        const mat_zz_p& Mmod = M[i];\n        mul(Amod, Amod, Mmod);\n    }\n    EXEC_RANGE_END\n\n    return *this;\n}\n\nCRTmatrix& CRTmatrix::operator+=(const mat_l& M) // A := A+M\n{\n    FHE_TIMER_START;\n    assert(length()==params->kFactors);\n    NTL::zz_pPush ppush; // backup NTL's current modulus\n\n    // multi-threaded implementation, threads handle different moduli\n    EXEC_RANGE(length(), first, last)\n    //for (long i=0; i<length(); i++)\n    for (long i=first; i<last; i++)\n    {\n        mat_zz_p& matMod = (*this)[i];\n        assert(matMod.NumRows()==M.NumRows() && matMod.NumCols()==M.NumCols());\n\n        params->zzp_context[i].restore();\n        for (long j=0; j<matMod.NumRows(); j++)\n            for (long k=0; k<matMod.NumCols(); k++)\n                matMod[j][k] += M[j][k];\n    }\n    EXEC_RANGE_END\n    return *this;\n}\nCRTmatrix& CRTmatrix::operator-=(const mat_l& M) // A := A+M\n{\n    FHE_TIMER_START;\n    assert(length()==params->kFactors);\n    NTL::zz_pPush ppush; // backup NTL's current modulus\n\n    EXEC_RANGE(length(), first, last)\n    //for (long i=0; i<length(); i++)\n    for (long i=first; i<last; i++)\n    {\n        mat_zz_p& matMod = (*this)[i];\n        assert(matMod.NumRows()==M.NumRows() && matMod.NumCols()==M.NumCols());\n\n        params->zzp_context[i].restore();\n        for (long j=0; j<matMod.NumRows(); j++)\n            for (long k=0; k<matMod.NumCols(); k++)\n                matMod[j][k] -= M[j][k];\n    }\n    EXEC_RANGE_END\n    return *this;\n}\n\nCRTmatrix& CRTmatrix::operator+=(const CRTmatrix& M) // A := A+M\n{\n    FHE_TIMER_START;\n    assert(length()==params->kFactors\n           && M.length()==M.params->kFactors\n           && params==M.params);\n    NTL::zz_pPush ppush; // backup NTL's current modulus\n\n    EXEC_RANGE(length(), first, last)\n    //for (long i=0; i<length(); i++)\n    for (long i=first; i<last; i++)\n    {\n        mat_zz_p& Amod = (*this)[i];\n        const mat_zz_p& Mmod = M[i];\n\n        assert(Amod.NumRows()==Mmod.NumRows() && Amod.NumCols()==Mmod.NumCols());\n        params->zzp_context[i].restore();\n        Amod += Mmod;\n    }\n    EXEC_RANGE_END\n    return *this;\n}\n\nCRTmatrix& CRTmatrix::operator-=(const CRTmatrix& M) // A := A+M\n{\n    FHE_TIMER_START;\n    assert(length()==params->kFactors\n           && M.length()==M.params->kFactors\n           && params==M.params);\n    NTL::zz_pPush ppush; // backup NTL's current modulus\n\n    EXEC_RANGE(length(), first, last)\n    //for (long i=0; i<length(); i++)\n    for (long i=first; i<last; i++)\n    {\n        mat_zz_p& Amod = (*this)[i];\n        const mat_zz_p& Mmod = M[i];\n\n        assert(Amod.NumRows()==Mmod.NumRows() && Amod.NumCols()==Mmod.NumCols());\n        params->zzp_context[i].restore();\n        Amod -= Mmod;\n    }\n    EXEC_RANGE_END\n    return *this;\n}\n\n// Get a CRT column: crtCol[i] is the j'th column of this[i]\nvoid CRTmatrix::getColumn(Vec<vec_zz_p>& crtCol, long j)\n{\n    FHE_TIMER_START;\n    crtCol.SetLength(length());\n    for (long n=0; n<length(); n++)\n    {\n        vec_zz_p& colMod = crtCol[n];\n        mat_zz_p& matMod = (*this)[n];\n\n        colMod.SetLength(matMod.NumRows());\n        // NOTE: this is OK, but beware that this would\n        // not work for ZZ_p's without restoring context\n\n        for (long i=0; i<matMod.NumRows(); i++)\n            colMod[i] = matMod[i][j];\n    }\n}\n\n//checks if all values of the matrix are smaller than the modolus\nbool CRTmatrix::isSmall(long bitGap) const\n{\n    FHE_TIMER_START;\n    mat_ZZ M; // reconstruct the matrix in ZZ format\n    ZZ q;     // the modulus\n\n    convert(M, q, *this); // cnovert to ZZ format\n\n    q >>= bitGap;         // q / 2^{bitGap}\n\n    for (long i=0; i<M.NumRows(); i++) for (long j=0; j<M.NumCols(); j++)\n        {\n            if (abs(M[i][j]) > q)\n            {\n                return false;\n            }\n        }\n    return true;\n}\n\n// Choose a random n-by-m matrix in CRT representation\nvoid CRTmatrix::randomFill(long n, long m)\n{\n    FHE_TIMER_START;\n\n    const TDMatrixParams& prms = *params;\n    SetLength(prms.kFactors);\n\n    zz_pPush ppush; // backup NTL's current modulus\n\n    EXEC_RANGE(length(), first, last)\n    //for (long i=0; i< prms.kFactors; i++)\n    for (long i=first; i< last; i++)\n    {\n\n        prms.zzp_context[i].restore();\n        (*this)[i].SetDims(n, m);\n        RandomFill((*this)[i]);\n    }\n    EXEC_RANGE_END\n}\n\n// Invert M modulo the product of the factors\nbool CRTmatrix::invert(const mat_l& M)\n{\n    FHE_TIMER_START;\n    SetLength(params->kFactors);\n\n    zz_pPush ppush; // backup NTL's current modulus\n\n    std::atomic<bool> result(true);\n\n    EXEC_RANGE(params->kFactors, first, last)\n\n    // Invert M wrt each factor separately\n    //for (long i=0; i< params->kFactors; i++)\n     for (long i=first; i< last; i++)\n    {\n        params->zzp_context[i].restore();\n        // NOTE: Alternatively, can call relaxed_inv directly now\n        if (!invMod((*this)[i], M))   // not invertible\n        {\n            SetLength(0);\n            result = false;\n            //return false;\n        }\n    }\n    EXEC_RANGE_END\n\n    return result;\n    //return true;\n}\n\n\nvoid CRTmatrix::identity(long n)\n{\n    FHE_TIMER_START;\n    zz_pPush ppush; // backup NTL's current modulus\n    SetLength(params->kFactors);\n\n    // Invert M wrt each factor separately\n    for (long i=0; i< params->kFactors; i++)\n    {\n        params->zzp_context[i].restore();\n        ident( (*this)[i], n ); // set as the identity mod f_i\n    }\n}\n\nbool operator==(const CRTmatrix& A, const CRTmatrix& B)\n{\n    FHE_TIMER_START;\n    if (A.params != B.params) return false;\n\n    zz_pPush push; // backup the NTL current modulus\n    for (long i=0; i < A.params->kFactors; i++)\n    {\n        (A.params->zzp_context)[i].restore();\n#ifdef DEBUGPRINT\n        cout << \"A[i]=\" << A[i] << \", B[i]=\" << B[i] << endl;\n#endif // DEBUGPRINT\n        if (A[i] != B[i]) return false;\n    }\n    return true;\n}\n\n//invert a CRT matrix\nbool CRTmatrix::invert(const CRTmatrix& A)\n{\n    FHE_TIMER_START;\n    params = A.params;\n    SetLength(params->kFactors);\n\n    zz_pPush push; // backup the NTL current modulus\n\n    for (long i=0; i < params->kFactors; i++)\n    {\n        const mat_zz_p& Amod = A[i];\n        params->zzp_context[i].restore();\n\n        zz_p d;\n        //    if (isInvertible(Amod, params->factors[i]))\n        //inv((*this)[i],Amod); // raises error if Amod is singular\n        relaxed_inv(d,(*this)[i],Amod); //raises error if Amod is singular\n\n        if (IsZero(d))\n            return false; //non invertible\n    }\n    return true;\n}\n\n\n// reconstruct the matrix in ZZ fromat, returning in q the modulus\nvoid convert(mat_ZZ& to, ZZ& q, const CRTmatrix& from)\n{\n    FHE_TIMER_START;\n    q = to_ZZ(1L); // initalize to 1\n    if (from.length() <=0)\n    {\n        to.kill(); // set as 0-by-0 matrix\n        return;\n    }\n\n    to.SetDims(from[0].NumRows(), from[0].NumCols());\n    clear(to);     // initialize to zero\n\n    NTL::zz_pPush ppush; // backup NTL's current modulus\n    for (long k=0; k<from.length(); k++)   // go over the factors one at a time\n    {\n        from.params->zzp_context[k].restore();\n        NTL::CRT(to, q, from[k]); // incremental CRT\n    }\n}\n\n// reconstruct the matrix in CRT fromat\n// FIXME: can be optimized for many factors\nvoid convert(CRTmatrix& to, const mat_ZZ& from, const TDMatrixParams& prms)\n{\n    FHE_TIMER_START;\n    to.params = (TDMatrixParams*) &prms;\n    to.SetLength(prms.kFactors);\n    if (prms.kFactors==0) return; // nothing to do\n\n    NTL::zz_pPush ppush; // backup NTL's current modulus\n\n    EXEC_RANGE(to.length(), first, last)\n\n    for (long k=first; k<last; k++)   // go over the factors one at a time\n    {\n        prms.zzp_context[k].restore();\n        conv(to[k], from); // compute M mod current factor\n    }\n\n    EXEC_RANGE_END\n}\n\n\nvoid generateMultiPair(CRTmatrix& A, CRTmatrix& Ainv, long n)\n{\n    FHE_TIMER_START;\n\n    NTL::Vec<CRTmatrix> Amats(INIT_SIZE, 12, A);\n    NTL::Vec<CRTmatrix> Ainvmats(INIT_SIZE, 12, Ainv);\n\n    EXEC_RANGE(12, first, last)\n    for (long i=first; i<last; i++)\n    {\n\n        CRTmatrix &Apair = Amats[i];\n        CRTmatrix &AinvPair = Ainvmats[i];\n        generateMatrixPair(Apair, AinvPair, n);\n    }\n\n    EXEC_RANGE_END\n}\n\n\nvoid generateMatrixPair(CRTmatrix& A, CRTmatrix& Ainv, long n)\n{\n    FHE_TIMER_START;\n    const TDMatrixParams& prms = *(A.params);\n\n    A.SetLength(prms.kFactors);\n    Ainv.SetLength(prms.kFactors);\n\n    zz_pPush push; // backup the NTL current modulus\n\n    // It's possible to do parallilizing at this level\n    // need to call SetNumThreads(nt) in main.\n\n    // NOTE: the zz_pPush in the \"main\" thread is sufficient,\n    // as the \"worker\" threads do not (and should not) assume\n    // any particular contextual state\n\n#ifdef DEBUGPRINT\n        cerr << \"*** \" << prms.kFactors << \" \" << AvailableThreads() << \"\\n\";\n#endif // DEBUGPRINT\n\n    EXEC_RANGE(prms.kFactors, first, last)\n    for (long i=first; i<last; i++)\n    {\n\n        mat_zz_p& Amod = A[i];\n        mat_zz_p& AinvMod = Ainv[i];\n        prms.zzp_context[i].restore(); // set i'th factor as NTL's current modulus\n        GenerateMatrixPair(Amod, AinvMod, n);\n    }\n    EXEC_RANGE_END\n\n    FHE_TIMER_STOP;\n};\n\n// binary I/O\n#undef CRTMAT_CONVtoZZ\nlong CRTmatrix::writeToFile(FILE* handle) const\n{\n    FHE_TIMER_START;\n\n    // write the parameters first\n    long count = params->writeToFile(handle);\n    assert (this->length() == params->kFactors);\n\n#ifndef CRTMAT_CONVtoZZ\n    long n,m;\n    if (this->length()<=0)\n        n = m = 0;\n    else\n    {\n        n = (*this)[0].NumRows();\n        m = (*this)[0].NumCols();\n    }\n    count += fwrite(&n, sizeof(n), 1, handle); // how many rows\n    count += fwrite(&m, sizeof(m), 1, handle); // how many cols\n\n    unsigned char buf[params->e];\n    NTL::zz_pPush ppush; // backup NTL's current modulus\n    for (long f=0; f<this->length(); f++)   // write one factor at a time\n    {\n        params->zzp_context[f].restore();\n        const Mat<zz_p>& mat = (*this)[f];\n        for (long i=0; i<n; i++) for (long j=0; j<m; j++)   // write every entry\n            {\n                for (long ie=0; ie < params->e; ie++) // write every byte\n                    buf[ie] = (rep(mat[i][j]) >> (ie*8)) & 0xff; // extract one byte\n                count += fwrite(buf, params->e, 1, handle); // do the actual writing\n            }\n#ifdef DEBUGPRINT\n        //cout << \"*this[f]=\"  << (*this)[f] << endl;\n#endif // DEBUGPRINT\n    }\n\n\n#else\n    ZZ q;\n    mat_ZZ zM;\n    convert(zM, q, *this); // convert to ZZ representation, then write it\n\n    long qBytes = NumBytes(q); // # of bytes to represent q\n    count += fwrite(&qBytes, sizeof(qBytes),1, handle); // how many bytes per int\n\n    long n = zM.NumRows();\n    long m = zM.NumCols();\n    count += fwrite(&n, sizeof(n), 1, handle); // how many rows\n    count += fwrite(&m, sizeof(m), 1, handle); // how many cols\n\n    unsigned char buf[qBytes];\n    for (long i=0; i<n; i++)\n        for (long j=0; j<m; j++)\n        {\n            if (sign(zM[i][j])<0) zM[i][j] += q; // map to interval [0,q-1]\n            BytesFromZZ(buf, zM[i][j], qBytes);      // get binary representation\n            count += fwrite(buf, qBytes, 1, handle); // write it to file\n        }\n#endif\n    return count;\n}\n\nlong CRTmatrix::readFromFile(FILE* handle, TDMatrixParams* prmBuf)\n{\n    FHE_TIMER_START;\n\n#ifdef DEBUGPRINT\n    cout << \"reading\" << endl;\n#endif\n\n    assert(params != NULL || prmBuf != NULL); // some pointer must be provided\n    long count;\n\n    // If buffer is given, make params point to it and don't overwrite from iput\n    if (prmBuf != NULL)\n    {\n        TDMatrixParams p;\n        count = p.readFromFile(handle);\n        assert(p == *prmBuf); // sanity check\n        params = prmBuf;      // point to given params\n    }\n    else\n        count = params->readFromFile(handle); // overwrite params from input\n\n#ifndef CRTMAT_CONVtoZZ\n    long n,m;\n    count += fread(&n, sizeof(n), 1, handle); // how many rows\n    count += fread(&m, sizeof(m), 1, handle); // how many column\n    if (count == 0) return count; //nothing is read\n\n    this->SetLength(params->kFactors);\n    if (params->kFactors==0) return count; // nothing to do\n\n    unsigned char buf[params->e];\n    NTL::zz_pPush ppush; // backup NTL's current modulus\n    for (long f=0; f<this->length(); f++)   // write one factor at a time\n    {\n        params->zzp_context[f].restore();\n        (*this)[f].SetDims(n,m);\n        for (long i=0; i<n; i++) for (long j=0; j<m; j++)   // write every entry\n            {\n                count += fread(buf, params->e, 1, handle); // read from file\n\n\n\n                long zp = buf[(params->e)-1];  // assemble the integer, byte by byte\n                //for (long ie=1; ie < params->e; ie++)\n                for (long ie=((params->e)-2); ie >=0 ; ie--)\n                {\n                    zp <<= 8;\n                    zp += buf[ie];\n                }\n                (*this)[f][i][j].LoopHole() = zp; // avoid calling rem()\n            }\n    }\n#else\n    long qBytes, n, m;\n    count += fread(&qBytes, sizeof(qBytes), 1, handle); // how many bytes per int\n    count += fread(&n, sizeof(n), 1, handle); // how many rows\n    count += fread(&m, sizeof(m), 1, handle); // how many column\n\n    if (count == 0) return count; //nothing is read\n\n    unsigned char buf[qBytes];\n    mat_ZZ zM(INIT_SIZE, n, m);\n    for (long i=0; i<n; i++) for (long j=0; j<m; j++)\n        {\n            count += fread(buf, qBytes, 1, handle); // read from file\n            ZZFromBytes(zM[i][j], buf, qBytes);     // make a ZZ object\n        }\n\n    convert(*this, zM, *params); // convert to CRT representation\n#endif\n    return count;\n}\n\n", "meta": {"hexsha": "2c4b87837229b36b1e3094ea420c66e8879cbad0", "size": 18535, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "CRTmatrix.cpp", "max_stars_repo_name": "shaih/BPobfus", "max_stars_repo_head_hexsha": "9c116312a8c9c0bc47a1c4b20e771c60c2510c6e", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2017-09-25T14:37:20.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-11T03:19:43.000Z", "max_issues_repo_path": "CRTmatrix.cpp", "max_issues_repo_name": "shaih/BPobfus", "max_issues_repo_head_hexsha": "9c116312a8c9c0bc47a1c4b20e771c60c2510c6e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "CRTmatrix.cpp", "max_forks_repo_name": "shaih/BPobfus", "max_forks_repo_head_hexsha": "9c116312a8c9c0bc47a1c4b20e771c60c2510c6e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2017-12-23T04:03:34.000Z", "max_forks_repo_forks_event_max_datetime": "2019-09-12T07:42:29.000Z", "avg_line_length": 28.0833333333, "max_line_length": 84, "alphanum_fraction": 0.584299973, "num_tokens": 5319, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6150878555160665, "lm_q2_score": 0.48828339529583464, "lm_q1q2_score": 0.3003371864966187}}
{"text": "/******************************************************************************\n**\n** Copyright (C) 2009-2011 Kyle Lutz <kyle.r.lutz@gmail.com>\n** All rights reserved.\n**\n** This file is a part of the chemkit project. For more information\n** see <http://www.chemkit.org>.\n**\n** Redistribution and use in source and binary forms, with or without\n** modification, are permitted provided that the following conditions\n** are met:\n**\n**   * Redistributions of source code must retain the above copyright\n**     notice, this list of conditions and the following disclaimer.\n**   * Redistributions in binary form must reproduce the above copyright\n**     notice, this list of conditions and the following disclaimer in the\n**     documentation and/or other materials provided with the distribution.\n**   * Neither the name of the chemkit project nor the names of its\n**     contributors may be used to endorse or promote products derived\n**     from this software without specific prior written permission.\n**\n** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n** \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n**\n******************************************************************************/\n\n#include \"uffcalculation.h\"\n\n#include <boost/algorithm/string.hpp>\n\n#include \"uffatomtyper.h\"\n#include \"uffforcefield.h\"\n#include \"uffparameters.h\"\n\n#include <chemkit/topology.h>\n#include <chemkit/constants.h>\n#include <chemkit/cartesiancoordinates.h>\n\n// === UffCalculation ====================================================== //\nUffCalculation::UffCalculation(int type, int atomCount, int parameterCount)\n    : ForceFieldCalculation(type, atomCount, parameterCount)\n{\n}\n\n// Returns the parameters for the given atom.\nconst UffAtomParameters* UffCalculation::parameters(const std::string &type) const\n{\n    const UffForceField *forceField = static_cast<const UffForceField *>(this->forceField());\n\n    return forceField->parameters()->parameters(type);\n}\n\n// Returns the bond order of the bond between atom's a and b. If both\n// atoms have a resonant type the bond order returned is 1.5.\n// Otherwise the integer value of the bond order is returned.\nchemkit::Real UffCalculation::bondOrder(size_t a, size_t b) const\n{\n    const boost::shared_ptr<chemkit::Topology> &topology = this->topology();\n\n    int type = topology->bondedInteractionType(a, b);\n\n    if(type == UffAtomTyper::Resonant){\n        return 1.5; // resonant\n    }\n    else{\n        return type;\n    }\n}\n\n// Returns the length of the bond between two atoms.\nchemkit::Real UffCalculation::bondLength(const UffAtomParameters *a, const UffAtomParameters *b, chemkit::Real bondOrder) const\n{\n    // r_ij = r_i + r_j + r_bo - r_en\n    chemkit::Real r_bo = -0.1332 * (a->r + b->r) * log(bondOrder);\n    chemkit::Real r_en = ((a->r * b->r) * pow((sqrt(a->X) - sqrt(b->X)), 2)) / (a->X*a->r + b->X*b->r);\n\n    chemkit::Real r_ij = a->r + b->r + r_bo - r_en;\n\n    return r_ij;\n}\n\n// === UffBondStrechCalculation ============================================ //\nUffBondStrechCalculation::UffBondStrechCalculation(size_t a, size_t b)\n    : UffCalculation(BondStrech, 2, 2)\n{\n    setAtom(0, a);\n    setAtom(1, b);\n}\n\nbool UffBondStrechCalculation::setup()\n{\n    const UffAtomParameters *pa = parameters(atomType(0));\n    const UffAtomParameters *pb = parameters(atomType(1));\n\n    if(!pa || !pb){\n        return false;\n    }\n\n    // n = bondorder (1.5 for aromatic, 1.366 for amide)\n    chemkit::Real bondorder = bondOrder(atom(0), atom(1));\n\n    chemkit::Real r0 = bondLength(pa, pb, bondorder);\n\n    // parameter(1) = k_ij = 664.12 * (Z*_i * Z*_j) / r_ij^3\n    chemkit::Real za = pa->Z;\n    chemkit::Real zb = pb->Z;\n    chemkit::Real kb = 664.12 * (za * zb) / pow(r0, 3);\n\n    setParameter(0, kb);\n    setParameter(1, r0);\n\n    return true;\n}\n\nchemkit::Real UffBondStrechCalculation::energy(const chemkit::CartesianCoordinates *coordinates) const\n{\n    size_t a = atom(0);\n    size_t b = atom(1);\n\n    chemkit::Real kb = parameter(0);\n    chemkit::Real r0 = parameter(1);\n    chemkit::Real r = coordinates->distance(a, b);\n\n    return 0.5 * kb * pow(r - r0, 2);\n}\n\nstd::vector<chemkit::Vector3> UffBondStrechCalculation::gradient(const chemkit::CartesianCoordinates *coordinates) const\n{\n    size_t a = atom(0);\n    size_t b = atom(1);\n\n    chemkit::Real kb = parameter(0);\n    chemkit::Real r0 = parameter(1);\n    chemkit::Real r = coordinates->distance(a, b);\n\n    // dE/dr\n    chemkit::Real de_dr = kb * (r - r0);\n\n    boost::array<chemkit::Vector3, 2> gradient = coordinates->distanceGradient(a, b);\n\n    gradient[0] *= de_dr;\n    gradient[1] *= de_dr;\n\n    return std::vector<chemkit::Vector3>(gradient.begin(), gradient.end());\n}\n\n// === UffAngleBendCalculation ============================================= //\nUffAngleBendCalculation::UffAngleBendCalculation(size_t a, size_t b, size_t c)\n    : UffCalculation(AngleBend, 3, 4)\n{\n    setAtom(0, a);\n    setAtom(1, b);\n    setAtom(2, c);\n}\n\nbool UffAngleBendCalculation::setup()\n{\n    const UffAtomParameters *pa = parameters(atomType(0));\n    const UffAtomParameters *pb = parameters(atomType(1));\n    const UffAtomParameters *pc = parameters(atomType(2));\n\n    if(!pa || !pb || !pc){\n        return false;\n    }\n\n    chemkit::Real theta0 = pb->theta * chemkit::constants::DegreesToRadians;\n\n    chemkit::Real bo_ij = bondOrder(atom(0), atom(1));\n    chemkit::Real bo_jk = bondOrder(atom(1), atom(2));\n\n    chemkit::Real r_ab = bondLength(pa, pb, bo_ij);\n    chemkit::Real r_bc = bondLength(pb, pc, bo_jk);\n    chemkit::Real r_ac = sqrt(pow(r_ab, 2)  + pow(r_bc, 2) - (2.0 * r_ab * r_bc * cos(theta0)));\n\n    chemkit::Real beta = 664.12 / (r_ab * r_bc);\n\n    chemkit::Real z_a = pa->Z;\n    chemkit::Real z_c = pc->Z;\n\n    // equation 13\n    chemkit::Real ka = beta * ((z_a * z_c) / pow(r_ac, 5)) * r_ab * r_bc * (3.0 * r_ab * r_bc * (1.0 - pow(cos(theta0), 2.0)) - (pow(r_ac, 2.0) * cos(theta0)));\n\n    setParameter(0, ka);\n\n    chemkit::Real sinTheta0 = sin(theta0);\n\n    // clamp sin(theta0) to 1e-3 because for some atoms theta0 == pi which\n    // would lead to a division by zero error when calculating c2 below\n    if(std::abs(sinTheta0) < 1e-3){\n        sinTheta0 = 1e-3;\n    }\n\n    chemkit::Real c2 = 1 / (4 * pow(sinTheta0, 2));\n    chemkit::Real c1 = -4 * c2 * cos(theta0);\n    chemkit::Real c0 = c2 * (2 * pow(cos(theta0), 2) + 1);\n\n    setParameter(1, c0);\n    setParameter(2, c1);\n    setParameter(3, c2);\n\n    return true;\n}\n\nchemkit::Real UffAngleBendCalculation::energy(const chemkit::CartesianCoordinates *coordinates) const\n{\n    size_t a = atom(0);\n    size_t b = atom(1);\n    size_t c = atom(2);\n\n    chemkit::Real ka = parameter(0);\n    chemkit::Real c0 = parameter(1);\n    chemkit::Real c1 = parameter(2);\n    chemkit::Real c2 = parameter(3);\n\n    chemkit::Real theta = coordinates->angleRadians(a, b, c);\n\n    return ka * (c0 + (c1 * cos(theta)) + (c2 * cos(2*theta)));\n}\n\nstd::vector<chemkit::Vector3> UffAngleBendCalculation::gradient(const chemkit::CartesianCoordinates *coordinates) const\n{\n    size_t a = atom(0);\n    size_t b = atom(1);\n    size_t c = atom(2);\n\n    chemkit::Real ka = parameter(0);\n    chemkit::Real c1 = parameter(2);\n    chemkit::Real c2 = parameter(3);\n\n    chemkit::Real theta = coordinates->angleRadians(a, b, c);\n\n    // dE/dtheta\n    chemkit::Real de_dtheta = -ka * (c1 * sin(theta) + 2 * c2 * sin(2 * theta));\n\n    boost::array<chemkit::Vector3, 3> gradient = coordinates->angleGradientRadians(a, b, c);\n\n    gradient[0] *= de_dtheta;\n    gradient[1] *= de_dtheta;\n    gradient[2] *= de_dtheta;\n\n    return std::vector<chemkit::Vector3>(gradient.begin(), gradient.end());\n}\n\n// === UffTorsionCalculation =============================================== //\nUffTorsionCalculation::UffTorsionCalculation(size_t a, size_t b, size_t c, size_t d)\n    : UffCalculation(Torsion, 4, 3)\n{\n    setAtom(0, a);\n    setAtom(1, b);\n    setAtom(2, c);\n    setAtom(3, d);\n}\n\nbool UffTorsionCalculation::setup()\n{\n    UffForceField *forceField = static_cast<UffForceField *>(this->forceField());\n    const boost::shared_ptr<chemkit::Topology> &topology = this->topology();\n\n    size_t b = atom(1);\n    size_t c = atom(2);\n\n    std::string typeB = topology->type(b);\n    std::string typeC = topology->type(c);\n\n    if(typeB.length() < 3 || typeC.length() < 3){\n        return false;\n    }\n\n    const UffAtomParameters *pb = parameters(typeB);\n    const UffAtomParameters *pc = parameters(typeC);\n\n    chemkit::Real V = 0;\n    chemkit::Real n = 0;\n    chemkit::Real phi0 = 0;\n\n    // sp3-sp3\n    if(typeB[2] == '3' && typeC[2] == '3'){\n\n        // exception for two group six atoms\n        if(forceField->isGroupSix(atom(1)) && forceField->isGroupSix(atom(2))){\n            if(boost::starts_with(typeB, \"O_\") && boost::starts_with(typeC, \"O_\")){\n                V = 2; // sqrt(2*2)\n            }\n            else if(boost::starts_with(typeB, \"O_\") || boost::starts_with(typeC, \"O_\")){\n                V = sqrt(2 * 6.8);\n            }\n            else{\n                V = sqrt(6.8 * 6.8);\n            }\n\n            n = 2;\n            phi0 = 90;\n        }\n\n        // general case\n        else{\n            // equation 16\n            V = sqrt(pb->V * pc->V);\n\n            n = 3;\n            phi0 = 180 * chemkit::constants::DegreesToRadians;\n        }\n    }\n    // sp2-sp2\n    else if((typeB[2] == '2' || typeB[2] == 'R') && (typeC[2] == '2' || typeC[2] == 'R')){\n        chemkit::Real bondorder = bondOrder(b, c);\n\n        // equation 17\n        V = 5 * sqrt(pb->U * pc->U) * (1 + 4.18 * log(bondorder));\n\n        n = 2;\n        phi0 = 180 * chemkit::constants::DegreesToRadians;\n    }\n    // group 6 sp3 - any sp2 or R\n    else if((forceField->isGroupSix(b) && (typeC[2] == '2' || typeC[2] == 'R')) ||\n            (forceField->isGroupSix(c) && (typeB[2] == '2' || typeB[2] == 'R'))){\n        chemkit::Real bondorder = bondOrder(b, c);\n\n        // equation 17\n        V = 5 * sqrt(pb->U * pc->U) * (1 + 4.18 * log(bondorder));\n\n        n = 2;\n        phi0 = 90 * chemkit::constants::DegreesToRadians;\n    }\n    // sp3-sp2\n    else if((typeB[2] == '3' && (typeC[2] == '2' || typeC[2] == 'R')) ||\n            (typeC[2] == '3' && (typeB[2] == '2' || typeB[2] == 'R'))){\n        V = 1;\n        n = 6;\n        phi0 = 0;\n    }\n    else{\n        return false;\n    }\n\n    setParameter(0, V);\n    setParameter(1, n);\n    setParameter(2, phi0);\n\n    return true;\n}\n\nchemkit::Real UffTorsionCalculation::energy(const chemkit::CartesianCoordinates *coordinates) const\n{\n    size_t a = atom(0);\n    size_t b = atom(1);\n    size_t c = atom(2);\n    size_t d = atom(3);\n\n    chemkit::Real V = parameter(0);\n    chemkit::Real n = parameter(1);\n    chemkit::Real phi0 = parameter(2);\n\n    chemkit::Real phi = coordinates->torsionAngleRadians(a, b, c, d);\n\n    return 0.5 * V * (1 - cos(n * phi0) * cos(n * phi));\n}\n\nstd::vector<chemkit::Vector3> UffTorsionCalculation::gradient(const chemkit::CartesianCoordinates *coordinates) const\n{\n    size_t a = atom(0);\n    size_t b = atom(1);\n    size_t c = atom(2);\n    size_t d = atom(3);\n\n    chemkit::Real V = parameter(0);\n    chemkit::Real n = parameter(1);\n    chemkit::Real phi0 = parameter(2);\n\n    chemkit::Real phi = coordinates->torsionAngleRadians(a, b, c, d);\n\n    // dE/dphi\n    chemkit::Real de_dphi = 0.5 * V * n * cos(n * phi0) * sin(n * phi);\n\n    boost::array<chemkit::Vector3, 4> gradient = coordinates->torsionAngleGradientRadians(a, b, c, d);\n\n    gradient[0] *= de_dphi;\n    gradient[1] *= de_dphi;\n    gradient[2] *= de_dphi;\n    gradient[3] *= de_dphi;\n\n    return std::vector<chemkit::Vector3>(gradient.begin(), gradient.end());\n}\n\n// === UffInversionCalculation ============================================= //\nUffInversionCalculation::UffInversionCalculation(size_t a, size_t b, size_t c, size_t d)\n    : UffCalculation(Inversion, 4, 4)\n{\n    setAtom(0, a);\n    setAtom(1, b);\n    setAtom(2, c);\n    setAtom(3, d);\n}\n\nbool UffInversionCalculation::setup()\n{\n    const boost::shared_ptr<chemkit::Topology> &topology = this->topology();\n\n    // b is the center atom\n    size_t a = atom(0);\n    size_t b = atom(1);\n    size_t c = atom(2);\n    size_t d = atom(3);\n\n    std::string typeA = topology->type(a);\n    std::string typeB = topology->type(b);\n    std::string typeC = topology->type(c);\n    std::string typeD = topology->type(d);\n\n\n    chemkit::Real k = 0;\n    chemkit::Real c0 = 0;\n    chemkit::Real c1 = 0;\n    chemkit::Real c2 = 0;\n\n    // sp2 carbon\n    if(typeB == \"C_2\" || typeB == \"C_R\"){\n        if(typeA == \"O_2\" || typeC == \"O_2\" || typeD == \"O_2\"){\n            k = 50;\n        }\n        else{\n            k = 6;\n        }\n\n        c0 = 1;\n        c1 = -1;\n        c2 = 0;\n    }\n\n    // divide by 3\n    k /= 3;\n\n    setParameter(0, k);\n    setParameter(1, c0);\n    setParameter(2, c1);\n    setParameter(3, c2);\n\n    return true;\n}\n\nchemkit::Real UffInversionCalculation::energy(const chemkit::CartesianCoordinates *coordinates) const\n{\n    size_t a = atom(0);\n    size_t b = atom(1);\n    size_t c = atom(2);\n    size_t d = atom(3);\n\n    chemkit::Real k = parameter(0);\n    chemkit::Real c0 = parameter(1);\n    chemkit::Real c1 = parameter(2);\n    chemkit::Real c2 = parameter(3);\n\n    chemkit::Real w = coordinates->wilsonAngleRadians(a, b, c, d);\n    chemkit::Real y = w + (chemkit::constants::Pi / 2.0);\n\n    return k * (c0 + c1 * sin(y) + c2 * cos(2 * y));\n}\n\nstd::vector<chemkit::Vector3> UffInversionCalculation::gradient(const chemkit::CartesianCoordinates *coordinates) const\n{\n    size_t a = atom(0);\n    size_t b = atom(1);\n    size_t c = atom(2);\n    size_t d = atom(3);\n\n    chemkit::Real k = parameter(0);\n    chemkit::Real c1 = parameter(2);\n    chemkit::Real c2 = parameter(3);\n\n    chemkit::Real w = coordinates->wilsonAngleRadians(a, b, c, d);\n    chemkit::Real y = w + (chemkit::constants::Pi / 2.0);\n\n    // dE/dw\n    chemkit::Real de_dw = k * (c1 * cos(y) - 2 * c2 * sin(2 * y));\n\n    boost::array<chemkit::Vector3, 4> gradient = coordinates->wilsonAngleGradientRadians(a, b, c, d);\n\n    gradient[0] *= de_dw;\n    gradient[1] *= de_dw;\n    gradient[2] *= de_dw;\n    gradient[3] *= de_dw;\n\n    return std::vector<chemkit::Vector3>(gradient.begin(), gradient.end());\n}\n\n// === UffVanDerWaalsCalculation =========================================== //\nUffVanDerWaalsCalculation::UffVanDerWaalsCalculation(size_t a, size_t b)\n    : UffCalculation(VanDerWaals, 2, 2)\n{\n    setAtom(0, a);\n    setAtom(1, b);\n}\n\nbool UffVanDerWaalsCalculation::setup()\n{\n    const UffAtomParameters *pa = parameters(atomType(0));\n    const UffAtomParameters *pb = parameters(atomType(1));\n    if(!pa || !pb){\n        return false;\n    }\n\n    // equation 22\n    chemkit::Real d = sqrt(pa->D * pb->D);\n\n    // equation 21b\n    chemkit::Real x = sqrt(pa->x * pb->x);\n\n    setParameter(0, d);\n    setParameter(1, x);\n\n    return true;\n}\n\nchemkit::Real UffVanDerWaalsCalculation::energy(const chemkit::CartesianCoordinates *coordinates) const\n{\n    size_t a = atom(0);\n    size_t b = atom(1);\n\n    chemkit::Real d = parameter(0);\n    chemkit::Real x = parameter(1);\n    chemkit::Real r = coordinates->distance(a, b);\n\n    return d * (-2 * pow(x/r, 6) + pow(x/r, 12));\n}\n\nstd::vector<chemkit::Vector3> UffVanDerWaalsCalculation::gradient(const chemkit::CartesianCoordinates *coordinates) const\n{\n    size_t a = atom(0);\n    size_t b = atom(1);\n\n    chemkit::Real d = parameter(0);\n    chemkit::Real x = parameter(1);\n    chemkit::Real r = coordinates->distance(a, b);\n\n    // dE/dr\n    chemkit::Real de_dr = -12 * d * x / pow(r, 2) * (pow(x/r, 11) - pow(x/r, 5));\n\n    boost::array<chemkit::Vector3, 2> gradient = coordinates->distanceGradient(a, b);\n\n    gradient[0] *= de_dr;\n    gradient[1] *= de_dr;\n\n    return std::vector<chemkit::Vector3>(gradient.begin(), gradient.end());\n}\n\n// === UffElectrostaticCalculation ========================================= //\nUffElectrostaticCalculation::UffElectrostaticCalculation(size_t a, size_t b)\n    : UffCalculation(Electrostatic, 2, 2)\n{\n    setAtom(0, a);\n    setAtom(1, b);\n}\n\nbool UffElectrostaticCalculation::setup()\n{\n    return false;\n}\n\nchemkit::Real UffElectrostaticCalculation::energy(const chemkit::CartesianCoordinates *coordinates) const\n{\n    size_t a = atom(0);\n    size_t b = atom(1);\n\n    chemkit::Real qa = parameter(0);\n    chemkit::Real qb = parameter(1);\n\n    chemkit::Real e = 1;\n    chemkit::Real r = coordinates->distance(a, b);\n\n    return 332.037 * (qa * qb) / (e * r);\n}\n", "meta": {"hexsha": "676d94527ffafe654ec4f0673f6919ba3cce0c90", "size": 17119, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/plugins/uff/uffcalculation.cpp", "max_stars_repo_name": "quizzmaster/chemkit", "max_stars_repo_head_hexsha": "803e4688b514008c605cb5c7790f7b36e67b68fc", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 34.0, "max_stars_repo_stars_event_min_datetime": "2015-01-24T23:59:41.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-12T13:48:01.000Z", "max_issues_repo_path": "src/plugins/uff/uffcalculation.cpp", "max_issues_repo_name": "soplwang/chemkit", "max_issues_repo_head_hexsha": "d62b7912f2d724a05fa8be757f383776fdd5bbcb", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2015-12-28T20:29:16.000Z", "max_issues_repo_issues_event_max_datetime": "2016-01-26T06:48:19.000Z", "max_forks_repo_path": "src/plugins/uff/uffcalculation.cpp", "max_forks_repo_name": "soplwang/chemkit", "max_forks_repo_head_hexsha": "d62b7912f2d724a05fa8be757f383776fdd5bbcb", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 17.0, "max_forks_repo_forks_event_min_datetime": "2015-01-23T14:50:24.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-10T15:43:50.000Z", "avg_line_length": 29.4647160069, "max_line_length": 160, "alphanum_fraction": 0.6028973655, "num_tokens": 5208, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.640635854839898, "lm_q2_score": 0.46879062662624377, "lm_q1q2_score": 0.30032408382963516}}
{"text": "// Compare SoA, AoS, and Eigen (with expression parser)\n// Ideal situation: everything known at compile time\n//\n// g++ ampBench.cpp -O3 -march=native -std=c++17 -ffast-math -I/usr/local/opt/eigen/include/eigen3 -I/usr/local/Cellar/boost/1.72.0/include/boost/ -Rpass-missed=loop-vectorize -lboost_timer -o ampBench\n//\n\n// SoA:\n//  1.167841s wall, 1.100000s user + 0.060000s system = 1.160000s CPU (99.3%)\n//\n// SoA (array):\n//  0.637546s wall, 0.570000s user + 0.060000s system = 0.630000s CPU (98.8%)\n//\n// SoA (stack):\n//  0.926747s wall, 0.870000s user + 0.060000s system = 0.930000s CPU (100.4%)\n//\n// AoS:\n//  14.228890s wall, 12.890000s user + 1.260000s system = 14.150000s CPU (99.4%)\n//\n// AoS (stack):\n//  1.105483s wall, 0.910000s user + 0.180000s system = 1.090000s CPU (98.6%)\n//\n// Eigen:\n//  1.072285s wall, 0.930000s user + 0.140000s system = 1.070000s CPU (99.8%)\n\n#include <iostream>\n#include <vector>\n#include <array>\n#include <memory>\n\n#include <Eigen/Dense>\n\n#include <boost/timer/timer.hpp>\n\n// #include <blaze/math/StaticVector.h>\n// #include <blaze/math/DynamicVector.h>\n\n#include <blaze/Math.h>\n\n#include \"xtensor/xtensor.hpp\"\n#include \"xtensor/xfixed.hpp\"\n#include \"xtensor/xarray.hpp\"\n#include \"xtensor/xio.hpp\"\n\nusing blaze::StaticVector;\nusing blaze::DynamicVector;\n\nstatic const int n_global = 1E6;\n\n// Spin 5 - no need for template here\nfloat legFunc(float cosHel)\n{\n    return -32.0*(63.0*cosHel*cosHel*cosHel*cosHel*cosHel - 70.0*cosHel*cosHel*cosHel + 15.0*cosHel)/63.0;\n}\n\n// AoS\nstruct ResParams\n{\npublic:\n\n    float mass;\n    float qTerm;\n    float ffRatioP;\n    float ffRatioR;\n    float spinTerms;\n\n    float ampRe;\n    float ampIm;\n\n    ResParams()\n    : mass(0),\n      qTerm(0),\n      ffRatioP(0),\n      ffRatioR(0),\n      spinTerms(0),\n      ampRe(0),\n      ampIm(0) { }\n\n};\n\nstruct ResParamsSoA\n{\npublic:\n\n    float resMass;\n    float resWidth;\n\n    std::vector<float> * mass;\n    std::vector<float> * qTerm;\n    std::vector<float> * ffRatioP;\n    std::vector<float> * ffRatioR;\n    std::vector<float> * spinTerms;\n\n    std::vector<float> * ampRe;\n    std::vector<float> * ampIm;\n\n    // Deal with these guys later...\n    static const int spin = 4;\n    static const int spinType = 1;\n\n    ResParamsSoA(int s)\n    {\n        mass = new std::vector<float>(s);\n        qTerm = new std::vector<float>(s);\n        ffRatioP = new std::vector<float>(s);\n        ffRatioR = new std::vector<float>(s);\n        spinTerms = new std::vector<float>(s);\n\n        ampRe = new std::vector<float>(s);\n        ampIm = new std::vector<float>(s);\n    }\n\n    ~ResParamsSoA()\n    {\n        delete mass;\n        delete qTerm;\n        delete ffRatioP;\n        delete ffRatioR;\n        delete spinTerms;\n\n        delete ampRe;\n        delete ampIm;\n    }\n\n};\n\nstruct ResParamsSoAArray\n{\npublic:\n\n    float resMass;\n    float resWidth;\n\n    std::array<float, n_global> * mass;\n    std::array<float, n_global> * qTerm;\n    std::array<float, n_global> * ffRatioP;\n    std::array<float, n_global> * ffRatioR;\n    std::array<float, n_global> * spinTerms;\n\n    std::array<float, n_global> * ampRe;\n    std::array<float, n_global> * ampIm;\n\n    // Deal with these guys later...\n    static const int spin = 4;\n    static const int spinType = 1;\n\n    ResParamsSoAArray(int s)\n    {\n        mass = new std::array<float, n_global>();\n        qTerm = new std::array<float, n_global>();\n        ffRatioP = new std::array<float, n_global>();\n        ffRatioR = new std::array<float, n_global>();\n        spinTerms = new std::array<float, n_global>();\n\n        ampRe = new std::array<float, n_global>();\n        ampIm = new std::array<float, n_global>();\n    }\n\n    ~ResParamsSoAArray()\n    {\n        delete mass;\n        delete qTerm;\n        delete ffRatioP;\n        delete ffRatioR;\n        delete spinTerms;\n\n        delete ampRe;\n        delete ampIm;\n    }\n\n};\n\nstruct ResParamsSoAStack\n{\npublic:\n\n    float resMass;\n    float resWidth;\n\n    std::vector<float> mass;\n    std::vector<float> qTerm;\n    std::vector<float> ffRatioP;\n    std::vector<float> ffRatioR;\n    std::vector<float> spinTerms;\n\n    std::vector<float> ampRe;\n    std::vector<float> ampIm;\n\n    // Deal with these guys later...\n    static const int spin = 4;\n    static const int spinType = 1;\n\n    ResParamsSoAStack(int n) {\n\n        mass.resize(n);\n        qTerm.resize(n);\n        ffRatioP.resize(n);\n        ffRatioR.resize(n);\n        spinTerms.resize(n);\n\n        ampRe.resize(n);\n        ampIm.resize(n);\n    }\n\n    ~ResParamsSoAStack() { }\n\n};\n\nstruct ResParamsEigen\n{\npublic:\n\n    float resMass;\n    float resWidth;\n\n    // Too large to allocate on stack (?)\n    // Possible to do more with static allocation?\n\n    Eigen::Array<float,Eigen::Dynamic,1> mass;\n    Eigen::Array<float,Eigen::Dynamic,1> qTerm;\n    Eigen::Array<float,Eigen::Dynamic,1> ffRatioP;\n    Eigen::Array<float,Eigen::Dynamic,1> ffRatioR;\n    Eigen::Array<float,Eigen::Dynamic,1> spinTerms;\n\n    Eigen::Array<float,Eigen::Dynamic,1> ampRe;\n    Eigen::Array<float,Eigen::Dynamic,1> ampIm;\n\n    // Deal with these guys later...\n    static const int spin = 4;\n    static const int spinType = 1;\n\n    ResParamsEigen(int n)\n    {\n\n        resMass = 0;\n        resWidth = 0;\n\n        mass = Eigen::Array<float,Eigen::Dynamic,1>(n);\n        qTerm = Eigen::Array<float,Eigen::Dynamic,1>(n);\n        ffRatioP = Eigen::Array<float,Eigen::Dynamic,1>(n);\n        ffRatioR = Eigen::Array<float,Eigen::Dynamic,1>(n);\n        spinTerms = Eigen::Array<float,Eigen::Dynamic,1>(n);\n\n        ampRe = Eigen::Array<float,Eigen::Dynamic,1>(n);\n        ampIm = Eigen::Array<float,Eigen::Dynamic,1>(n);\n    }\n\n    ~ResParamsEigen()\n    {\n\n    }\n\n};\n\nstruct ResParamsBlaze\n{\npublic:\n\n    float resMass;\n    float resWidth;\n\n    static const int n = n_global;\n\n    // DynamicVector<float> mass;\n    // DynamicVector<float> qTerm;\n    // DynamicVector<float> ffRatioP;\n    // DynamicVector<float> ffRatioR;\n    // DynamicVector<float> spinTerms;\n    //\n    // DynamicVector<float> ampRe;\n    // DynamicVector<float> ampIm;\n\n    StaticVector<float, n> mass;\n    StaticVector<float, n> qTerm;\n    StaticVector<float, n> ffRatioP;\n    StaticVector<float, n> ffRatioR;\n    StaticVector<float, n> spinTerms;\n\n    StaticVector<float, n> ampRe;\n    StaticVector<float, n> ampIm;\n\n    // Deal with these guys later...\n    static const int spin = 4;\n    static const int spinType = 1;\n\n    ResParamsBlaze()\n    {\n\n        resMass = 0;\n        resWidth = 0;\n\n        // mass = DynamicVector<float>(this->n);\n        // qTerm = DynamicVector<float>(this->n);\n        // ffRatioP = DynamicVector<float>(this->n);\n        // ffRatioR = DynamicVector<float>(this->n);\n        // spinTerms = DynamicVector<float>(this->n);\n        //\n        // ampRe = DynamicVector<float>(this->n);\n        // ampIm = DynamicVector<float>(this->n);\n\n    }\n\n    ~ResParamsBlaze()\n    {\n\n    }\n\n};\n\nstruct ResParamsXTensor\n{\npublic:\n\n    float resMass;\n    float resWidth;\n\n    static const int n = n_global;\n\n    // DynamicVector<float> mass;\n    // DynamicVector<float> qTerm;\n    // DynamicVector<float> ffRatioP;\n    // DynamicVector<float> ffRatioR;\n    // DynamicVector<float> spinTerms;\n    //\n    // DynamicVector<float> ampRe;\n    // DynamicVector<float> ampIm;\n\n    xt::xtensor_fixed<double, xt::xshape<n, 1>> mass;\n    xt::xtensor_fixed<double, xt::xshape<n, 1>> qTerm;\n    xt::xtensor_fixed<double, xt::xshape<n, 1>> ffRatioP;\n    xt::xtensor_fixed<double, xt::xshape<n, 1>> ffRatioR;\n    xt::xtensor_fixed<double, xt::xshape<n, 1>> spinTerms;\n\n    xt::xtensor_fixed<double, xt::xshape<n, 1>> ampRe;\n    xt::xtensor_fixed<double, xt::xshape<n, 1>> ampIm;\n\n    // Deal with these guys later...\n    static const int spin = 4;\n    static const int spinType = 1;\n\n    ResParamsXTensor()\n    {\n\n        resMass = 0;\n        resWidth = 0;\n\n        // mass = DynamicVector<float>(this->n);\n        // qTerm = DynamicVector<float>(this->n);\n        // ffRatioP = DynamicVector<float>(this->n);\n        // ffRatioR = DynamicVector<float>(this->n);\n        // spinTerms = DynamicVector<float>(this->n);\n        //\n        // ampRe = DynamicVector<float>(this->n);\n        // ampIm = DynamicVector<float>(this->n);\n\n    }\n\n    ~ResParamsXTensor()\n    {\n\n    }\n\n};\n\nvoid calcAmpSoA(const ResParamsSoA & inParams)\n{\n    float resMass = inParams.resMass;\n    float resWidth = inParams.resWidth;\n\n    for (int i = 0; i < inParams.mass->size(); i++) {\n        float totWidth = resWidth * inParams.qTerm->at(i);\n        totWidth *= (resMass / inParams.mass->at(i));\n        totWidth *= inParams.ffRatioP->at(i) * inParams.ffRatioR->at(i);\n\n        float m2 = inParams.mass->at(i) * inParams.mass->at(i);\n        float m2Term = resMass * resMass - m2;\n\n        float scale = inParams.spinTerms->at(i);\n        scale /= m2Term * m2Term + resMass * resMass * totWidth * totWidth;\n        scale *= inParams.ffRatioP->at(i) * inParams.ffRatioR->at(i); // Optional -> template specialise?\n        scale *= legFunc(inParams.spinTerms->at(i));\n\n        inParams.ampRe->at(i) = m2Term * scale;\n        inParams.ampIm->at(i) = resMass * totWidth * scale;\n    }\n}\n\nvoid calcAmpSoA(const ResParamsSoAArray & inParams)\n{\n    float resMass = inParams.resMass;\n    float resWidth = inParams.resWidth;\n\n    #pragma clang loop vectorize(assume_safety)\n    for (int i = 0; i < n_global; i++) {\n        float totWidth = resWidth * inParams.qTerm->at(i);\n        totWidth *= (resMass / inParams.mass->at(i));\n        totWidth *= inParams.ffRatioP->at(i) * inParams.ffRatioR->at(i);\n\n        float m2 = inParams.mass->at(i) * inParams.mass->at(i);\n        float m2Term = resMass * resMass - m2;\n\n        float scale = inParams.spinTerms->at(i);\n        scale /= m2Term * m2Term + resMass * resMass * totWidth * totWidth;\n        scale *= inParams.ffRatioP->at(i) * inParams.ffRatioR->at(i); // Optional -> template specialise?\n        scale *= legFunc(inParams.spinTerms->at(i));\n\n        inParams.ampRe->at(i) = m2Term * scale;\n        inParams.ampIm->at(i) = resMass * totWidth * scale;\n    }\n}\n\nvoid calcAmpSoAStack(ResParamsSoAStack & inParams)\n{\n    float resMass = inParams.resMass;\n    float resWidth = inParams.resWidth;\n\n    for (int i = 0; i < inParams.mass.size(); i++) {\n        float totWidth = resWidth * inParams.qTerm.at(i);\n        totWidth *= (resMass / inParams.mass.at(i));\n        totWidth *= inParams.ffRatioP.at(i) * inParams.ffRatioR.at(i);\n\n        float m2 = inParams.mass.at(i) * inParams.mass.at(i);\n        float m2Term = resMass * resMass - m2;\n\n        float scale = inParams.spinTerms.at(i);\n        scale /= m2Term * m2Term + resMass * resMass * totWidth * totWidth;\n        scale *= inParams.ffRatioP.at(i) * inParams.ffRatioR.at(i); // Optional -> template specialise?\n        scale *= legFunc(inParams.spinTerms.at(i));\n\n        inParams.ampRe.at(i) = m2Term * scale;\n        inParams.ampIm.at(i) = resMass * totWidth * scale;\n    }\n}\n\nvoid calcAmpAoS(const std::vector<std::unique_ptr<ResParams> > & inParams, float resMass, float resWidth)\n{\n\n    for (int i = 0; i < inParams.size(); i++) {\n        float totWidth = resWidth * inParams.at(i)->qTerm;\n        totWidth *= (resMass / inParams.at(i)->mass);\n        totWidth *= inParams.at(i)->ffRatioP * inParams.at(i)->ffRatioR;\n\n        float m2 = inParams.at(i)->mass * inParams.at(i)->mass;\n        float m2Term = resMass * resMass - m2;\n\n        float scale = inParams.at(i)->spinTerms;\n        scale /= m2Term * m2Term + resMass * resMass * totWidth * totWidth;\n        scale *= inParams.at(i)->ffRatioP * inParams.at(i)->ffRatioR; // Optional -> template specialise?\n        scale *= legFunc(inParams.at(i)->spinTerms);\n\n        inParams.at(i)->ampRe = m2Term * scale;\n        inParams.at(i)->ampIm = resMass * totWidth * scale;\n    }\n}\n\nvoid calcAmpAoSStack(std::vector<ResParams> & inParams, float resMass, float resWidth)\n{\n\n    for (int i = 0; i < inParams.size(); i++) {\n        float totWidth = resWidth * inParams.at(i).qTerm;\n        totWidth *= (resMass / inParams.at(i).mass);\n        totWidth *= inParams.at(i).ffRatioP * inParams.at(i).ffRatioR;\n\n        float m2 = inParams.at(i).mass * inParams.at(i).mass;\n        float m2Term = resMass * resMass - m2;\n\n        float scale = inParams.at(i).spinTerms;\n        scale /= m2Term * m2Term + resMass * resMass * totWidth * totWidth;\n        scale *= inParams.at(i).ffRatioP * inParams.at(i).ffRatioR; // Optional -> template specialise?\n        scale *= legFunc(inParams.at(i).spinTerms);\n\n        inParams.at(i).ampRe = m2Term * scale;\n        inParams.at(i).ampIm = resMass * totWidth * scale;\n    }\n}\n\nvoid calcAmpEigen(ResParamsEigen & inParams)\n{\n    float resMass = inParams.resMass;\n    float resWidth = inParams.resWidth;\n\n    Eigen::Array<float,Eigen::Dynamic,1> totWidth = resWidth * (inParams.qTerm);\n    totWidth *= (resMass / (inParams.mass));\n    totWidth *= totWidth * (inParams.ffRatioP) * (inParams.ffRatioR);\n\n    Eigen::Array<float,Eigen::Dynamic,1> m2 = (inParams.mass) * (inParams.mass);\n    Eigen::Array<float,Eigen::Dynamic,1> m2Term = resMass * resMass - m2;\n\n    Eigen::Array<float,Eigen::Dynamic,1> scale = (inParams.spinTerms);\n    scale /= m2Term * m2Term + resMass * resMass * totWidth * totWidth;\n    scale *= (inParams.ffRatioP) * (inParams.ffRatioR);\n\n    inParams.ampRe = m2Term * scale;\n    inParams.ampIm = resMass * totWidth * scale;\n}\n\nvoid calcAmpBlaze(ResParamsBlaze & inParams)\n{\n    float resMass = inParams.resMass;\n    float resWidth = inParams.resWidth;\n\n    StaticVector<float, n_global> totWidth = resWidth * (inParams.qTerm);\n    totWidth *= (resMass / (inParams.mass));\n    totWidth *= totWidth * (inParams.ffRatioP) * (inParams.ffRatioR);\n\n    StaticVector<float, n_global> m2 = (inParams.mass) * (inParams.mass);\n    StaticVector<float, n_global> m2Term = resMass * resMass - m2;\n\n    StaticVector<float, n_global> scale = (inParams.spinTerms);\n    scale /= m2Term * m2Term + resMass * resMass * totWidth * totWidth;\n    scale *= (inParams.ffRatioP) * (inParams.ffRatioR);\n\n    inParams.ampRe = m2Term * scale;\n    inParams.ampIm = resMass * totWidth * scale;\n}\n\nvoid calcAmpXTensor(ResParamsXTensor & inParams)\n{\n    float resMass = inParams.resMass;\n    float resWidth = inParams.resWidth;\n\n    xt::xtensor_fixed<double, xt::xshape<n_global, 1>> totWidth = resWidth * (inParams.qTerm);\n    totWidth *= (resMass / (inParams.mass));\n    totWidth *= totWidth * (inParams.ffRatioP) * (inParams.ffRatioR);\n\n    xt::xtensor_fixed<double, xt::xshape<n_global, 1>> m2 = (inParams.mass) * (inParams.mass);\n    xt::xtensor_fixed<double, xt::xshape<n_global, 1>> m2Term = resMass * resMass - m2;\n\n    xt::xtensor_fixed<double, xt::xshape<n_global, 1>> scale = (inParams.spinTerms);\n    scale /= m2Term * m2Term + resMass * resMass * totWidth * totWidth;\n    scale *= (inParams.ffRatioP) * (inParams.ffRatioR);\n\n    inParams.ampRe = m2Term * scale;\n    inParams.ampIm = resMass * totWidth * scale;\n}\n\nvoid benchAoS()\n{\n    static const int n = n_global;\n\n    std::vector<std::unique_ptr<ResParams>> resParamsAoS;\n    resParamsAoS.resize(n);\n\n    for (auto & p : resParamsAoS) {\n\n        p = std::make_unique<ResParams>();\n\n        p->qTerm = 0.05;\n        p->mass = 0.3;\n        p->ffRatioP = 3.3;\n        p->ffRatioR = 1.0;\n        p->spinTerms = 1.0;\n\n        p->ampRe = 1.0;\n        p->ampIm = 1.0;\n    }\n\n    float resMass = 1.0;\n    float resWidth = 0.1;\n\n    calcAmpAoS(resParamsAoS, resMass, resWidth);\n\n    // std::cout << resParamsAoS.at(5)->ampRe << std::endl;\n\n}\n\nvoid benchAoSStack()\n{\n    int n = n_global;\n\n    std::vector<ResParams> resParamsAoSStack;\n    resParamsAoSStack.reserve(n);\n\n    for (int i = 0; i < n; i++) {\n\n        ResParams params;\n\n        params.qTerm = 0.05;\n        params.mass = 0.3;\n        params.ffRatioP = 3.3;\n        params.ffRatioR = 1.0;\n        params.spinTerms = 1.0;\n\n        params.ampRe = 1.0;\n        params.ampIm = 1.0;\n\n        resParamsAoSStack.push_back(params);\n\n    }\n\n    float resMass = 1.0;\n    float resWidth = 0.1;\n\n    calcAmpAoSStack(resParamsAoSStack, resMass, resWidth);\n\n    // std::cout << resParamsAoSStack.at(5).ampRe << std::endl;\n    // std::cout << resParamsAoSStack.at(5).ampIm << std::endl;\n}\n\nvoid benchSoA()\n{\n    ResParamsSoA parsR(n_global);\n\n    std::random_device r;\n\n    std::default_random_engine e1(r());\n    std::uniform_real_distribution<float> uniform_dist(0, 1);\n\n    std::fill(parsR.qTerm->begin(), parsR.qTerm->end(), uniform_dist(e1));\n    std::fill(parsR.mass->begin(), parsR.mass->end(), uniform_dist(e1));\n    std::fill(parsR.ffRatioP->begin(), parsR.ffRatioP->end(), uniform_dist(e1));\n    std::fill(parsR.ffRatioR->begin(), parsR.ffRatioR->end(), uniform_dist(e1));\n    std::fill(parsR.spinTerms->begin(), parsR.spinTerms->end(), uniform_dist(e1));\n\n    std::fill(parsR.ampRe->begin(), parsR.ampRe->end(), uniform_dist(e1));\n    std::fill(parsR.ampIm->begin(), parsR.ampIm->end(), uniform_dist(e1));\n\n    parsR.resMass =uniform_dist(e1);\n    parsR.resWidth =uniform_dist(e1);\n\n    calcAmpSoA(parsR);\n\n    // std::cout << (parsR.ampRe)->at(5) << std::endl;\n    // std::cout << (parsR.ampIm)->at(5) << std::endl;\n}\n\nvoid benchSoAArray()\n{\n    ResParamsSoAArray parsR(n_global);\n\n    std::random_device r;\n\n    std::default_random_engine e1(r());\n    std::uniform_real_distribution<float> uniform_dist(0, 1);\n\n    std::fill(parsR.qTerm->begin(), parsR.qTerm->end(), uniform_dist(e1));\n    std::fill(parsR.mass->begin(), parsR.mass->end(), uniform_dist(e1));\n    std::fill(parsR.ffRatioP->begin(), parsR.ffRatioP->end(), uniform_dist(e1));\n    std::fill(parsR.ffRatioR->begin(), parsR.ffRatioR->end(), uniform_dist(e1));\n    std::fill(parsR.spinTerms->begin(), parsR.spinTerms->end(), uniform_dist(e1));\n\n    std::fill(parsR.ampRe->begin(), parsR.ampRe->end(), uniform_dist(e1));\n    std::fill(parsR.ampIm->begin(), parsR.ampIm->end(), uniform_dist(e1));\n\n    parsR.resMass = uniform_dist(e1);\n    parsR.resWidth = uniform_dist(e1);\n\n    calcAmpSoA(parsR);\n\n    // std::cout << (parsR.ampRe)->at(5) << std::endl;\n    // std::cout << (parsR.ampIm)->at(5) << std::endl;\n}\n\nvoid benchSoAStack()\n{\n    ResParamsSoAStack parsR(n_global);\n\n    std::random_device r;\n\n    std::default_random_engine e1(r());\n    std::uniform_real_distribution<float> uniform_dist(0, 1);\n\n    std::fill(parsR.qTerm.begin(), parsR.qTerm.end(), uniform_dist(e1));\n    std::fill(parsR.mass.begin(), parsR.mass.end(), uniform_dist(e1));\n    std::fill(parsR.ffRatioP.begin(), parsR.ffRatioP.end(), uniform_dist(e1));\n    std::fill(parsR.ffRatioR.begin(), parsR.ffRatioR.end(), uniform_dist(e1));\n    std::fill(parsR.spinTerms.begin(), parsR.spinTerms.end(), uniform_dist(e1));\n\n    std::fill(parsR.ampRe.begin(), parsR.ampRe.end(), uniform_dist(e1));\n    std::fill(parsR.ampIm.begin(), parsR.ampIm.end(), uniform_dist(e1));\n\n    parsR.resMass = uniform_dist(e1);\n    parsR.resWidth = uniform_dist(e1);\n\n    calcAmpSoAStack(parsR);\n\n    // std::cout << parsR.ampRe.at(5) << std::endl;\n    // std::cout << parsR.ampIm.at(5) << std::endl;\n}\n\nvoid benchEigen()\n{\n    int n = n_global;\n    ResParamsEigen parsR(n);\n\n    parsR.qTerm = Eigen::ArrayXf::Ones(n, 1);\n    parsR.mass = Eigen::ArrayXf::Ones(n, 1);\n    parsR.ffRatioP = Eigen::ArrayXf::Ones(n, 1);\n    parsR.ffRatioR = Eigen::ArrayXf::Ones(n, 1);\n    parsR.spinTerms = Eigen::ArrayXf::Ones(n, 1);\n\n    parsR.ampRe = Eigen::ArrayXf::Ones(n, 1);\n    parsR.ampIm = Eigen::ArrayXf::Ones(n, 1);\n\n    parsR.resMass = 1.0;\n    parsR.resWidth = 0.1;\n\n    calcAmpEigen(parsR);\n\n    // std::cout << (*parsR.ampRe)[5] << std::endl;\n    // std::cout << (*parsR.ampIm)[5] << std::endl;\n}\n\nvoid benchBlaze()\n{\n    ResParamsBlaze parsR;\n\n    std::random_device r;\n\n    std::default_random_engine e1(r());\n    std::uniform_real_distribution<float> uniform_dist(0, 1);\n\n    parsR.qTerm = uniform_dist(e1);\n    parsR.mass = uniform_dist(e1);\n    parsR.ffRatioP = uniform_dist(e1);\n    parsR.ffRatioR = uniform_dist(e1);\n    parsR.spinTerms = uniform_dist(e1);\n\n    parsR.ampRe = uniform_dist(e1);\n    parsR.ampIm = uniform_dist(e1);\n\n    parsR.resMass = uniform_dist(e1);\n    parsR.resWidth = uniform_dist(e1);\n\n    calcAmpBlaze(parsR);\n\n    // std::cout << parsR.ampRe[5] << std::endl;\n    // std::cout << parsR.ampIm[5] << std::endl;\n}\n\nvoid benchXTensor()\n{\n    ResParamsXTensor parsR;\n\n    std::random_device r;\n\n    std::default_random_engine e1(r());\n    std::uniform_real_distribution<float> uniform_dist(0.0, 1.0);\n\n    parsR.qTerm.fill(uniform_dist(e1));\n    parsR.mass.fill(uniform_dist(e1));\n    parsR.ffRatioP.fill(uniform_dist(e1));\n    parsR.ffRatioR.fill(uniform_dist(e1));\n    parsR.spinTerms.fill(uniform_dist(e1));\n\n    parsR.ampRe.fill(uniform_dist(e1));\n    parsR.ampIm.fill(uniform_dist(e1));\n\n    parsR.resMass = uniform_dist(e1);\n    parsR.resWidth = uniform_dist(e1);\n\n    calcAmpXTensor(parsR);\n\n    // std::cout << parsR.ampRe[5] << std::endl;\n    // std::cout << parsR.ampIm[5] << std::endl;\n}\n\nint main(int argc, char const *argv[]) {\n\n    int n_itr = 100;\n\n    std::cout<< \"SoA:\" << std::endl;\n    {\n    boost::timer::auto_cpu_timer t;\n    for (int i = 0; i < n_itr; i++) { benchSoA(); }\n    }\n\n    std::cout << std::endl;\n\n    std::cout<< \"SoA (array):\" << std::endl;\n    {\n    boost::timer::auto_cpu_timer t;\n    for (int i = 0; i < n_itr; i++) { benchSoAArray(); }\n    }\n\n    std::cout << std::endl;\n\n    std::cout<< \"SoA (stack):\" << std::endl;\n    {\n    boost::timer::auto_cpu_timer t;\n    for (int i = 0; i < n_itr; i++) { benchSoAStack(); }\n    }\n\n    std::cout << std::endl;\n\n    std::cout<< \"AoS:\" << std::endl;\n    {\n    boost::timer::auto_cpu_timer t;\n    for (int i = 0; i < n_itr; i++) { benchAoS(); }\n    }\n\n    std::cout << std::endl;\n\n    std::cout<< \"AoS (stack):\" << std::endl;\n    {\n    boost::timer::auto_cpu_timer t;\n    for (int i = 0; i < n_itr; i++) { benchAoSStack(); }\n    }\n\n    std::cout << std::endl;\n\n    // Without Legendre term\n\n    std::cout<< \"Eigen:\" << std::endl;\n    {\n    boost::timer::auto_cpu_timer t;\n    for (int i = 0; i < n_itr; i++) { benchEigen(); }\n    }\n\n    // Segfaults for some reason?\n\n    // std::cout << std::endl;\n    //\n    // std::cout<< \"Blaze:\" << std::endl;\n    // {\n    // boost::timer::auto_cpu_timer t;\n    // for (int i = 0; i < n_itr; i++) { benchBlaze(); }\n    // }\n    //\n    // std::cout << std::endl;\n    //\n    // std::cout<< \"XTensor:\" << std::endl;\n    // {\n    // boost::timer::auto_cpu_timer t;\n    // for (int i = 0; i < n_itr; i++) { benchXTensor(); }\n    // }\n\n    return 0;\n}\n", "meta": {"hexsha": "900c2a4b83b9c9e88e503be427bbdf4a3a0ac07c", "size": 22538, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ampBench.cpp", "max_stars_repo_name": "dpohanlon/zemachCUDA", "max_stars_repo_head_hexsha": "7c55672adb84037903905b475e4aa50815c2ce27", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ampBench.cpp", "max_issues_repo_name": "dpohanlon/zemachCUDA", "max_issues_repo_head_hexsha": "7c55672adb84037903905b475e4aa50815c2ce27", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ampBench.cpp", "max_forks_repo_name": "dpohanlon/zemachCUDA", "max_forks_repo_head_hexsha": "7c55672adb84037903905b475e4aa50815c2ce27", "max_forks_repo_licenses": ["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.1869722557, "max_line_length": 201, "alphanum_fraction": 0.6153607241, "num_tokens": 6893, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6406358411176238, "lm_q2_score": 0.46879062662624377, "lm_q1q2_score": 0.30032407739676165}}
{"text": "// Copyright(c) 2020-Present, Matthew R. Hennefarth\n// Distributed under the MIT License (http://opensource.org/licenses/MIT)\n\n#include \"FieldLocations.h\"\n\n/* EXTERNAL LIBRARY HEADER FILES */\n#include <Eigen/Dense>\n#include <matplot/matplot.h>\n\n/* CPET HEADER FILES */\n#include \"System.h\"\n\nnamespace cpet {\n\nFieldLocations FieldLocations::fromSimple(\n    const std::vector<std::string>& options) {\n  FieldLocations fl;\n  constexpr auto create_location = [](const std::string& location) -> AtomID {\n    return AtomID{location};\n  };\n  std::transform(options.begin(), options.end(),\n                 std::back_inserter(fl.locations_), create_location);\n  return fl;\n}\n\nFieldLocations FieldLocations::fromBlock(\n    const std::vector<std::string>& options) {\n  constexpr const char* PLOT_KEY = \"plot\";\n  constexpr const char* LOCATIONS_KEY = \"locations\";\n  constexpr const char* OUTPUT_KEY = \"output\";\n\n  FieldLocations fl;\n  for (const auto& line : options) {\n    const auto tokens = util::split(line, ' ');\n    if (tokens.size() < 2) {\n      continue;\n    }\n\n    const auto key = util::tolower(tokens[0]);\n    const std::vector<std::string> key_options{tokens.begin() + 1,\n                                               tokens.end()};\n\n    if (key == LOCATIONS_KEY) {\n      constexpr auto create_location =\n          [](const std::string& location) -> AtomID {\n        return AtomID{location};\n      };\n\n      std::transform(key_options.begin(), key_options.end(),\n                     std::back_inserter(fl.locations_), create_location);\n    } else if (key == PLOT_KEY) {\n      fl.plotStyle_ = decodePlotStyle_(key_options);\n    } else if (key == OUTPUT_KEY) {\n      fl.output_ = *key_options.begin();\n    }\n  }\n  return fl;\n}\nvoid FieldLocations::computeEFieldsWith(\n    const std::vector<System>& systems) const {\n  std::vector<std::vector<Eigen::Vector3d>> results;\n  for (const auto& point : locations_) {\n    SPDLOG_INFO(\"=~=~=~=~[Field at {}]=~=~=~=~\", point.ID());\n    std::vector<Eigen::Vector3d> fieldTrajectoryAtPoint;\n\n    for (const auto& system : systems) {\n      Eigen::Vector3d location;\n      if (point.position()) {\n        location = *(point.position());\n      } else {\n        location = system.frame().find(point)->coordinate;\n      }\n\n      Eigen::Vector3d field = system.electricFieldAt(location);\n      SPDLOG_INFO(\"{} [{}]\", field.transpose(), field.norm());\n      fieldTrajectoryAtPoint.emplace_back(field);\n    }\n    results.push_back(fieldTrajectoryAtPoint);\n  }\n  if (output_) {\n    writeOutput_(results);\n  }\n  if (showPlots()) {\n    plot_(results);\n  }\n}\nvoid FieldLocations::writeOutput_(\n    const std::vector<std::vector<Eigen::Vector3d>>& results) const {\n  if (!output_) {\n    return;\n  }\n\n  std::ofstream outFile(*output_, std::ios::out);\n  if (outFile.is_open()) {\n    for (size_t i = 0; i < results.size(); i++) {\n      outFile << '#' << locations_[i].ID() << '\\n';\n      for (const Eigen::Vector3d& field : results[i]) {\n        outFile << field.transpose() << '\\n';\n      }\n    }\n    outFile << std::flush;\n  } else {\n    SPDLOG_ERROR(\"Could not open file {}\", *output_);\n    throw cpet::io_error(\"Could not open file \" + *output_);\n  }\n}\nvoid FieldLocations::plot_(\n    const std::vector<std::vector<Eigen::Vector3d>>& results) const {\n  const auto numberOfPlots =\n      util::countSetBits(static_cast<unsigned int>(plotStyle_));\n  if (numberOfPlots <= 0 || numberOfPlots > 4) {\n    SPDLOG_WARN(\n        \"Number of plots less than 1 or greater than 4! Error in logic\");\n    return;\n  }\n\n  auto figure = matplot::figure();\n  if (numberOfPlots < 3) {\n    figure->tiledlayout(numberOfPlots, 1);\n  } else {\n    figure->tiledlayout(2, 2);\n  }\n\n  /* can make this an option eventually\n   figure->size(500,500); */\n\n  auto current_ax = matplot::nexttile(0);\n\n  for (const auto& data : results) {\n    std::array<std::vector<double>, 4> rotatedElectricFields;\n    for (size_t index = 0; index < 3; index++) {\n      const auto extract_index =\n          [&index](const Eigen::Vector3d& vector) -> double {\n        return vector[static_cast<long>(index)];\n      };\n\n      std::transform(data.begin(), data.end(),\n                     std::back_inserter(rotatedElectricFields.at(index)),\n                     extract_index);\n    }\n\n    constexpr auto compute_magnitude =\n        [](const Eigen::Vector3d& vector) -> double { return vector.norm(); };\n\n    std::transform(data.begin(), data.end(),\n                   std::back_inserter(*rotatedElectricFields.rbegin()),\n                   compute_magnitude);\n\n    size_t plot_index = 0;\n\n    // constexpr std::array<const char*, 4> titles{\"X\", \"Y\", \"Z\", \"Magnitude\"};\n    const auto plot = [&rotatedElectricFields, &plot_index, &current_ax,\n                       &figure](size_t index) {\n      constexpr std::array<const char*, 4> titles{\"X\", \"Y\", \"Z\", \"Magnitude\"};\n      current_ax = figure->nexttile(plot_index);\n      matplot::hold(current_ax, matplot::on);\n      matplot::plot(current_ax, rotatedElectricFields.at(index));\n      current_ax->xlabel(\"Frame\");\n      current_ax->ylabel(\"Magnitude (V/Ang)\");\n      current_ax->title(titles.at(index));\n      ++plot_index;\n    };\n\n    if (plotX_()) {\n      plot(0);\n    }\n    if (plotY_()) {\n      plot(1);\n    }\n    if (plotZ_()) {\n      plot(2);\n    }\n    if (plotM_()) {\n      plot(3);\n    }\n  }\n\n  std::vector<std::string> legend_list;\n  constexpr auto get_string_representation = [](const AtomID& aid) {\n    return aid.ID();\n  };\n  std::transform(locations_.begin(), locations_.end(),\n                 std::back_inserter(legend_list), get_string_representation);\n\n  current_ax->legend(legend_list);\n  matplot::show();\n}\n\n}  // namespace cpet", "meta": {"hexsha": "2f43ee502c50da00dec7e27175d5792109862cda", "size": 5673, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/FieldLocations.cpp", "max_stars_repo_name": "santi921/CPET", "max_stars_repo_head_hexsha": "717c8db51578801288332aa6e49ff56e84058027", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/FieldLocations.cpp", "max_issues_repo_name": "santi921/CPET", "max_issues_repo_head_hexsha": "717c8db51578801288332aa6e49ff56e84058027", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-05-25T00:38:24.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-25T00:38:24.000Z", "max_forks_repo_path": "src/FieldLocations.cpp", "max_forks_repo_name": "santi921/CPET", "max_forks_repo_head_hexsha": "717c8db51578801288332aa6e49ff56e84058027", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-03-15T21:04:34.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-15T21:04:34.000Z", "avg_line_length": 30.0158730159, "max_line_length": 79, "alphanum_fraction": 0.6127269522, "num_tokens": 1439, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6513548782017745, "lm_q2_score": 0.46101677931231594, "lm_q1q2_score": 0.3002855281379479}}
{"text": "/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */\n/*                                                                           */\n/*  This file is part of the library KASKADE 7                               */\n/*    see http://www.zib.de/Numerik/numsoft/kaskade7/                        */\n/*                                                                           */\n/*  Copyright (C) 2002-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 ERROR_DISTRIBUTION_HH\n#define ERROR_DISTRIBUTION_HH\n\n#include <string>\n\n#include <boost/utility.hpp>\n#include <boost/fusion/include/as_vector.hpp>\n\n#include \"fem/assemble.hh\"\n#include \"fem/functionspace.hh\"\n#include \"fem/lagrangespace.hh\"\n#include \"fem/shapefunctioncache.hh\"\n\n// forward declarations\nnamespace Dune\n{\n  template <class,int> class FieldVector;\n  template <class,int,int> class FieldMatrix;\n  template <class, int> class QuadratureRule;\n}\n\nnamespace Kaskade\n{\n  using namespace boost::fusion;\n  using namespace AssemblyDetail;\n\n  enum class ErrorNorm { Energy, L2, H1, H1_half };\n\n  template <class OriginalEvaluators, class ExtensionEvaluators, class Functional,\n            class ArgYH, class ArgYE, class ArgUH, class ArgUE, class ArgPH, class ArgPE>\n  void evaluateData(OriginalEvaluators& originalEvaluators, ExtensionEvaluators& extendedEvaluators, Functional const& f,\n                    ArgYH& yl, ArgYE& yh, ArgUH& ul, ArgUE& uh, ArgPH& pl, ArgPE& ph, double w)\n  {\n      if( f.considerControlVariable_ )\n      {\n        uh.value += w * at_c<Functional::uIdx>(f.errorEstimateH.data).value(at_c<Functional::uSHIdx>(extendedEvaluators));\n        ul.value += w * at_c<Functional::uIdx>(f.errorEstimateL.data).value(at_c<Functional::uSLIdx>(originalEvaluators));\n        uh.gradient += w * at_c<Functional::uIdx>(f.errorEstimateH.data).gradient(at_c<Functional::uSHIdx>(extendedEvaluators));\n        ul.gradient += w * at_c<Functional::uIdx>(f.errorEstimateL.data).gradient(at_c<Functional::uSLIdx>(originalEvaluators));\n      }\n      if( f.considerStateVariable_ )\n      {\n        yh.value += w * at_c<Functional::yIdx>(f.errorEstimateH.data).value(at_c<Functional::ySHIdx>(extendedEvaluators));\n        yl.value += w * at_c<Functional::yIdx>(f.errorEstimateL.data).value(at_c<Functional::ySLIdx>(originalEvaluators));\n        yh.gradient += w * at_c<Functional::yIdx>(f.errorEstimateH.data).gradient(at_c<Functional::ySHIdx>(extendedEvaluators));\n        yl.gradient += w * at_c<Functional::yIdx>(f.errorEstimateL.data).gradient(at_c<Functional::ySLIdx>(originalEvaluators));\n      }\n      if( f.considerAdjointVariable_ )\n      {\n        ph.value += w * at_c<Functional::pIdx>(f.errorEstimateH.data).value(at_c<Functional::pSHIdx>(extendedEvaluators));\n        pl.value += w * at_c<Functional::pIdx>(f.errorEstimateL.data).value(at_c<Functional::pSLIdx>(originalEvaluators));\n        ph.gradient += w * at_c<Functional::pIdx>(f.errorEstimateH.data).gradient(at_c<Functional::pSHIdx>(extendedEvaluators));\n        pl.gradient += w * at_c<Functional::pIdx>(f.errorEstimateL.data).gradient(at_c<Functional::pSLIdx>(extendedEvaluators));\n      }\n  }\n\n  template <class ArgYL, class ArgYH, class ArgUL, class ArgUH, class ArgPL, class ArgPH>\n  void clearVarArgs(ArgYL& yl, ArgYH& yh, ArgUL& ul, ArgUH& uh, ArgPL& pl, ArgPH& ph)\n  {\n    ul.value = 0;  ul.gradient = 0;\n    yl.value = 0;  yl.gradient = 0;\n    pl.value = 0;  pl.gradient = 0;\n    uh.value = 0;  uh.gradient = 0;\n    yh.value = 0;  yh.gradient = 0;\n    ph.value = 0;  ph.gradient = 0;\n  }\n\n  template <class ArgU, class ArgY, class ArgP>\n  double computeL2Error(ArgU const& u, ArgY const& y, ArgP const& p)\n  {\n    return u.value*u.value + y.value*y.value + p.value*p.value;\n  }\n\n  template <class ArgU, class ArgY, class ArgP>\n  double computeH1HalfError(ArgU const& u, ArgY const& y, ArgP const& p)\n  {\n    LinAlg::EuclideanScalarProduct sp;\n    return sp(u.gradient,u.gradient) + sp(y.gradient,y.gradient) + sp(p.gradient,p.gradient);\n  }\n\n\n  template <class Functional, class ExtendedAnsatzVars >\n  class ErrorDistribution\n  {\n    typedef typename Functional::AnsatzVars OriginalAnsatzVars;\n    typedef typename OriginalAnsatzVars::Grid Grid;\n    typedef ShapeFunctionCache<Grid, typename Functional::Scalar> SfCache;\n    typedef ShapeFunctionCache<Grid, typename Functional::Scalar> SfCache2;\n    typedef typename OriginalAnsatzVars::Spaces OriginalSpaces;\n    typedef typename ExtendedAnsatzVars::Spaces ExtendedSpaces;\n    typedef typename result_of::as_vector<typename result_of::transform<OriginalSpaces, GetEvaluators<SfCache> >::type>::type OriginalEvaluators;\n    typedef typename result_of::as_vector<typename result_of::transform<ExtendedSpaces, GetEvaluators<SfCache2> >::type>::type ExtendedEvaluators;\n    typedef typename Grid::ctype CoordType;\n    typedef Dune::QuadratureRule<typename Functional::AnsatzVars::Grid::ctype, Functional::AnsatzVars::Grid::dimension> QuadRule;\n    typedef Dune::QuadratureRule<typename Functional::AnsatzVars::Grid::ctype, Functional::AnsatzVars::Grid::dimension-1> FaceQuadRule;\n  public:\n    typedef typename Functional::Scalar Scalar;\n    typedef FEFunctionSpace<DiscontinuousLagrangeMapper<Scalar,typename Grid::LeafGridView> > AnsatzSpace;\n    typedef boost::fusion::vector<AnsatzSpace const*> AnsatzSpaces;\n    typedef Variable<SpaceIndex<0>,Components<1>,VariableId<0> > AnsatzVariableInformation;\n    typedef boost::fusion::vector<AnsatzVariableInformation> VariableDescriptions;\n    typedef VariableSetDescription<AnsatzSpaces,VariableDescriptions> AnsatzVars;\n    typedef typename AnsatzVars::template CoefficientVectorRepresentation<0,1>::type ErrorVector;\n    typedef AnsatzVars TestVars;\n    typedef OriginalAnsatzVars OriginVars;\n    //typedef AnsatzVars OriginVars;\n    static int const dim = Grid::dimension;\n    static ProblemType const type = Functional::type;\n\n    static constexpr int yIdx = getStateId<Functional>();\n    static constexpr int uIdx = getControlId<Functional>();\n    static constexpr int pIdx = getAdjointId<Functional>();\n    static constexpr int uSLIdx = result_of::value_at_c<typename OriginalAnsatzVars::Variables, uIdx>::type::spaceIndex;\n    static constexpr int ySLIdx = result_of::value_at_c<typename OriginalAnsatzVars::Variables, yIdx>::type::spaceIndex;\n    static constexpr int pSLIdx = result_of::value_at_c<typename OriginalAnsatzVars::Variables, pIdx>::type::spaceIndex;\n    static constexpr int uSHIdx = result_of::value_at_c<typename ExtendedAnsatzVars::Variables, uIdx>::type::spaceIndex;\n    static constexpr int ySHIdx = result_of::value_at_c<typename ExtendedAnsatzVars::Variables, yIdx>::type::spaceIndex;\n    static constexpr int pSHIdx = result_of::value_at_c<typename ExtendedAnsatzVars::Variables, pIdx>::type::spaceIndex;\n\n    class DomainCache\n    {\n    public:\n      DomainCache(ErrorDistribution const& f_, typename OriginVars::VariableSet const& /*vars*/, int flags=7)\n        : f(f_), domainCache(f.functional,f.iterate,flags)\n      {\n      }\n\n      template <class Entity>\n      void moveTo(Entity const &entity)\n      {\n        e  = &entity;\n        domainCache.moveTo(entity);\n      }\n\n      template <class Position, class Evaluators>\n      void evaluateAt(Position const&, Evaluators const& evaluators)\n      {\n        clearVarArgs(yl,yh,ul,uh,pl,ph);\n        OriginalEvaluators originalEvaluators(transform(f.iterate.descriptions.spaces,GetEvaluators<SfCache>(&sfCache)));\n        ExtendedEvaluators extendedEvaluators(transform(f.errorEstimateH.descriptions.spaces,GetEvaluators<SfCache>(&extendedSFCache)));\n        QuadRule qr = QuadratureTraits<QuadRule>().rule(e->type(),f.qOrder);\n        moveEvaluatorsToCell(originalEvaluators,*e);\n        moveEvaluatorsToCell(extendedEvaluators,*e);\n        useQuadratureRuleInEvaluators(originalEvaluators,qr,0);\n        useQuadratureRuleInEvaluators(extendedEvaluators,qr,0);\n\n        size_t nQuadPos = qr.size();\n        for (size_t g=0; g<nQuadPos; ++g)\n        {\n          // pos of integration point\n          Dune::FieldVector<CoordType,dim> quadPos = qr[g].position();\n          // for all spaces involved, update the evaluators associated\n          // to this quadrature point\n          moveEvaluatorsToIntegrationPoint(originalEvaluators,quadPos);\n          moveEvaluatorsToIntegrationPoint(extendedEvaluators,quadPos);\n          // prepare evaluation of functional\n          domainCache.evaluateAt(qr[g].position(),originalEvaluators);\n\n          evaluateData(originalEvaluators, extendedEvaluators, f, yl, yh, ul, uh, pl, ph, qr[g].weight());\n        }\n      }\n\n      Scalar d0() const { return 0; }\n\n      template<int row, int dim>\n      Dune::FieldVector<Scalar, TestVars::template Components<row>::m>\n      d1 (VariationalArg<Scalar,dim> const& arg) const\n      {\n        VariationalArg<Scalar,dim,OriginalAnsatzVars::template Components<yIdx>::m> y(yh);\n        VariationalArg<Scalar,dim,OriginalAnsatzVars::template Components<uIdx>::m> u(uh);\n        VariationalArg<Scalar,dim,OriginalAnsatzVars::template Components<pIdx>::m> p(ph);\n\n        if( !f.onlyH_ )\n        {\n          u.value += ul.value;\n          u.gradient += ul.gradient;\n          y.value += yl.value;\n          y.gradient += yl.gradient;\n          p.value += pl.value;\n          p.gradient += pl.gradient;\n        }\n\n        if( f.errorNorm == ErrorNorm::L2 ) return computeL2Error(u,y,p);\n        if( f.errorNorm == ErrorNorm::H1_half ) return computeH1HalfError(u,y,p);\n        if( f.errorNorm == ErrorNorm::H1 ) return computeL2Error(u,y,p) + computeH1HalfError(u,y,p);\n\n        Scalar result = 0;\n        result += Functional::template D2<yIdx,yIdx>::present ? domainCache.template d2_impl<yIdx,yIdx>(y,y) : 0.;\n        result += Functional::template D2<yIdx,uIdx>::present ? domainCache.template d2_impl<yIdx,uIdx>(y,u) : 0.;\n        result += Functional::template D2<uIdx,yIdx>::present ? domainCache.template d2_impl<uIdx,yIdx>(u,y) : 0.;\n        result += Functional::template D2<uIdx,uIdx>::present ? domainCache.template d2_impl<uIdx,uIdx>(u,u) : 0.;\n        if( !f.useStateNormForAdjoint_ )\n        {\n          result += Functional::template D2<yIdx,pIdx>::present ? domainCache.template d2_impl<yIdx,pIdx>(y,p) : 0.;\n          result += Functional::template D2<pIdx,yIdx>::present ? domainCache.template d2_impl<pIdx,yIdx>(p,y) : 0.;\n          result += Functional::template D2<pIdx,uIdx>::present ? domainCache.template d2_impl<pIdx,uIdx>(p,u) : 0.;\n          result += Functional::template D2<uIdx,pIdx>::present ? domainCache.template d2_impl<uIdx,pIdx>(u,p) : 0.;\n          result += Functional::template D2<pIdx,pIdx>::present ? domainCache.template d2_impl<pIdx,pIdx>(p,p) : 0.;\n        }\n        else\n        {\n          result += Functional::template D2<pIdx,pIdx>::present ? domainCache.template d2_impl<yIdx,yIdx>(p,p) : 0.;\n        }\n        return result*arg.value[0];\n      }\n\n      template<int row, int col, int dim>\n      Dune::FieldMatrix<Scalar,1,1>\td2 (VariationalArg<Scalar,dim> const&, VariationalArg<Scalar,dim> const&) const { return Dune::FieldMatrix<Scalar,1,1>(0); }\n\n    private:\n      ErrorDistribution const& f;\n      typename Functional::DomainCache domainCache;\n      typename AnsatzVars::Grid::template Codim<0>::Entity const* e;\n      VariationalArg<Scalar,dim,OriginalAnsatzVars::template Components<yIdx>::m> yl;\n      VariationalArg<Scalar,dim,ExtendedAnsatzVars::template Components<yIdx>::m> yh;\n      VariationalArg<Scalar,dim,OriginalAnsatzVars::template Components<uIdx>::m> ul;\n      VariationalArg<Scalar,dim,ExtendedAnsatzVars::template Components<uIdx>::m> uh;\n      VariationalArg<Scalar,dim,OriginalAnsatzVars::template Components<pIdx>::m> pl;\n      VariationalArg<Scalar,dim,ExtendedAnsatzVars::template Components<pIdx>::m> ph;\n      SfCache sfCache;\n      SfCache2 extendedSFCache;\n    };\n\n    class BoundaryCache\n    {\n    public:\n      BoundaryCache(ErrorDistribution const& f_, typename OriginVars::VariableSet const& vars, int flags=7)\n        : f(f_), boundaryCache(f.functional,f.iterate,flags)\n      {}\n\n      template <class FaceIterator>\n      void moveTo(FaceIterator const& entity)\n      {\n        e = &entity;\n        boundaryCache.moveTo(entity);\n      }\n\n      template <class Evaluators>\n      void evaluateAt(Dune::FieldVector<typename AnsatzVars::Grid::ctype, AnsatzVars::Grid::dimension-1> const& xlocal, Evaluators const& evaluators)\n      {\n        clearVarArgs(yl,yh,ul,uh,pl,ph);\n        OriginalEvaluators originalEvaluators(transform(f.iterate.descriptions.spaces,GetEvaluators<SfCache>(&sfCache)));\n        ExtendedEvaluators extendedEvaluators(transform(f.errorEstimateH.descriptions.spaces,GetEvaluators<SfCache>(&extendedSFCache)));\n        FaceQuadRule qr = QuadratureTraits<FaceQuadRule>().rule((*e)->geometryInInside().type(),f.qOrder);\n        moveEvaluatorsToCell(originalEvaluators,*at_c<ySLIdx>(evaluators).cell_);\n        moveEvaluatorsToCell(extendedEvaluators,*at_c<ySLIdx>(evaluators).cell_);\n        moveEvaluatorsToCell(originalEvaluators,*e);\n        moveEvaluatorsToCell(extendedEvaluators,*e);\n        useQuadratureRuleInEvaluators(originalEvaluators,qr,(*e)->indexInInside());\n        useQuadratureRuleInEvaluators(extendedEvaluators,qr,(*e)->indexInInside());\n\n        size_t nQuadPos = qr.size();\n        for (size_t g=0; g<nQuadPos; ++g)\n        {\n          // pos of integration point\n          Dune::FieldVector<CoordType,dim> quadPos = (*e)->geometryInInside().global(qr[g].position());\n          // for all spaces involved, update the evaluators associated\n          // to this quadrature point\n          moveEvaluatorsToIntegrationPoint(originalEvaluators,quadPos);\n          moveEvaluatorsToIntegrationPoint(extendedEvaluators,quadPos);\n          // prepare evaluation of functional\n          boundaryCache.evaluateAt(qr[g].position(),originalEvaluators);\n\n          evaluateData(originalEvaluators, extendedEvaluators, f, yl, yh, ul, uh, pl, ph, qr[g].weight());\n        }\n      }\n\n      Scalar d0() const { return 0; }\n\n      template<int row, int dim>\n      Dune::FieldVector<Scalar,1> d1 (VariationalArg<Scalar,dim> const& arg) const\n      {\n        return Dune::FieldVector<Scalar,1>(0);\n        VariationalArg<Scalar,dim,OriginalAnsatzVars::template Components<yIdx>::m> y(yh);\n        VariationalArg<Scalar,dim,OriginalAnsatzVars::template Components<uIdx>::m> u(uh);\n        VariationalArg<Scalar,dim,OriginalAnsatzVars::template Components<pIdx>::m> p(ph);\n\n        if( !f.onlyH_ )\n        {\n          u.value += ul.value;\n          u.gradient += ul.gradient;\n          y.value += yl.value;\n          y.gradient += yl.gradient;\n          p.value += pl.value;\n          p.gradient += pl.gradient;\n        }\n\n        if( f.errorNorm != ErrorNorm::Energy ) return computeL2Error(u,y,p);\n\n        Scalar result = Functional::template D2<yIdx,yIdx>::present ? boundaryCache.template d2_impl<yIdx,yIdx>(y,y) : 0.;\n        result += Functional::template D2<yIdx,uIdx>::present ? boundaryCache.template d2_impl<yIdx,uIdx>(y,u) : 0.;\n        result += Functional::template D2<uIdx,yIdx>::present ? boundaryCache.template d2_impl<uIdx,yIdx>(u,y) : 0.;\n        result += Functional::template D2<uIdx,uIdx>::present ? boundaryCache.template d2_impl<uIdx,uIdx>(u,u) : 0.;\n        if( !f.useStateNormForAdjoint_ )\n        {\n          result += Functional::template D2<yIdx,pIdx>::present ? boundaryCache.template d2_impl<yIdx,pIdx>(y,p) : 0.;\n          result += Functional::template D2<pIdx,yIdx>::present ? boundaryCache.template d2_impl<pIdx,yIdx>(p,y) : 0.;\n          result += Functional::template D2<pIdx,uIdx>::present ? boundaryCache.template d2_impl<pIdx,uIdx>(p,u) : 0.;\n          result += Functional::template D2<uIdx,pIdx>::present ? boundaryCache.template d2_impl<uIdx,pIdx>(u,p) : 0.;\n          result += Functional::template D2<pIdx,pIdx>::present ? boundaryCache.template d2_impl<pIdx,pIdx>(p,p) : 0.;\n        }\n        else\n        {\n          result += Functional::template D2<pIdx,pIdx>::present ? boundaryCache.template d2_impl<yIdx,yIdx>(p,p) : 0.;\n        }\n        return result*arg.value[0];\n      }\n\n      template<int row, int col, int dim>\n      Dune::FieldMatrix<Scalar,1,1> d2 (VariationalArg<Scalar,dim> const&, VariationalArg<Scalar,dim> const&) const { return Dune::FieldMatrix<Scalar,1,1>(0); }\n\n    private:\n      ErrorDistribution const& f;\n      typename Functional::BoundaryCache boundaryCache;\n      typename AnsatzVars::Grid::LeafGridView::IntersectionIterator const* e;\n      VariationalArg<Scalar,dim,OriginalAnsatzVars::template Components<yIdx>::m> yl;\n      VariationalArg<Scalar,dim,ExtendedAnsatzVars::template Components<yIdx>::m> yh;\n      VariationalArg<Scalar,dim,OriginalAnsatzVars::template Components<uIdx>::m> ul;\n      VariationalArg<Scalar,dim,ExtendedAnsatzVars::template Components<uIdx>::m> uh;\n      VariationalArg<Scalar,dim,OriginalAnsatzVars::template Components<pIdx>::m> pl;\n      VariationalArg<Scalar,dim,ExtendedAnsatzVars::template Components<pIdx>::m> ph;\n      SfCache sfCache;\n      SfCache2 extendedSFCache;\n    };\n\n    ErrorDistribution(Functional const& functional_, typename OriginalAnsatzVars::VariableSet const& iterate_,\n                      typename OriginalAnsatzVars::VariableSet const& errorEstimateL_, typename ExtendedAnsatzVars::VariableSet const& errorEstimateH_)\n      : functional(functional_), iterate(iterate_), errorEstimateL(errorEstimateL_), errorEstimateH(errorEstimateH_), ansatzSpace(boost::fusion::at_c<0>(iterate.descriptions.spaces)->gridManager(), iterate.descriptions.gridView,0),\n        ansatzSpaces(&ansatzSpace), varName( {\"error\"} ), ansatzVars(ansatzSpaces,varName)\n\n    {}\n\n    template <int row>\n    struct D1\n    {\n      static bool const present   = true;\n      static bool const constant  = false;\n    };\n\n    template <int row, int col>\n    struct D2\n    {\n      static bool const present = false;\n      static bool const symmetric = false;\n      static bool const lumped = false;\n    };\n\n    template <class Cell>\n    int integrationOrder(Cell const&, int, bool) const { return 0; }\n\n    AnsatzSpaces const& getSpaces() const { return ansatzSpaces; }\n\n    AnsatzVars const& getVariableSetDescription() const { return ansatzVars; }\n\n    void ignoreLowerOrderError(bool ignore) { onlyH_ = ignore; }\n    void considerStateVariable(bool consider) { considerStateVariable_ = consider; }\n    void considerControlVariable(bool consider) { considerControlVariable_ = consider; }\n    void considerAdjointVariable(bool consider) { considerAdjointVariable_ = consider; }\n    void setErrorNorm(ErrorNorm errNorm) { errorNorm = errNorm; }\n    void useStateNormForAdjoint(bool useStateNorm) { useStateNormForAdjoint_ = useStateNorm; }\n\n    friend class DomainCache;\n    friend class BoundaryCache;\n\n    Functional const& functional;\n    typename OriginalAnsatzVars::VariableSet const& iterate;\n    typename OriginalAnsatzVars::VariableSet const& errorEstimateL;\n    typename ExtendedAnsatzVars::VariableSet const& errorEstimateH;\n    AnsatzSpace ansatzSpace;\n    AnsatzSpaces ansatzSpaces;\n    std::string varName[1];\n    AnsatzVars ansatzVars;\n    ErrorNorm errorNorm = ErrorNorm::Energy;\n    bool onlyH_ = false, considerStateVariable_ = true, considerControlVariable_ = true, considerAdjointVariable_ = false, useStateNormForAdjoint_ = false;\n    int qOrder = 6;\n  };\n}\n#endif\n", "meta": {"hexsha": "d1c0397a9073e5f38b2689b06bb470a1402867c5", "size": 19817, "ext": "hh", "lang": "C++", "max_stars_repo_path": "Kaskade/algorithm/errorDistribution.hh", "max_stars_repo_name": "chenzongxiong/streambox", "max_stars_repo_head_hexsha": "76f95780d1bf6c02731e39d8ac73937cea352b95", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2019-07-03T14:03:31.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-19T10:18:49.000Z", "max_issues_repo_path": "Kaskade/algorithm/errorDistribution.hh", "max_issues_repo_name": "chenzongxiong/streambox", "max_issues_repo_head_hexsha": "76f95780d1bf6c02731e39d8ac73937cea352b95", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2020-02-17T12:01:31.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-09T22:02:36.000Z", "max_forks_repo_path": "Kaskade/algorithm/errorDistribution.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": 50.6828644501, "max_line_length": 231, "alphanum_fraction": 0.6781046576, "num_tokens": 5091, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5736783928749127, "lm_q2_score": 0.523420348936324, "lm_q1q2_score": 0.30027494457581644}}
{"text": "///////////////////////////////////////////////////////////////////\n//  Copyright Christopher Kormanyos 2019 - 2022.                 //\n//  Distributed under the Boost Software License,                //\n//  Version 1.0. (See accompanying file LICENSE_1_0.txt          //\n//  or copy at http://www.boost.org/LICENSE_1_0.txt)             //\n///////////////////////////////////////////////////////////////////\n\n#ifndef UINTWIDE_T_BACKEND_2019_12_15_HPP\n  #define UINTWIDE_T_BACKEND_2019_12_15_HPP\n\n  #include <cstdint>\n  #include <limits>\n  #include <string>\n  #include <type_traits>\n\n  #if defined(__GNUC__)\n  #pragma GCC diagnostic push\n  #pragma GCC diagnostic ignored \"-Wconversion\"\n  #pragma GCC diagnostic push\n  #pragma GCC diagnostic ignored \"-Wsign-conversion\"\n  #pragma GCC diagnostic push\n  #pragma GCC diagnostic ignored \"-Wunused-parameter\"\n  #endif\n\n  #if (defined(__clang__) && (__clang_major__ > 9)) && !defined(__APPLE__)\n  #pragma GCC diagnostic push\n  #pragma GCC diagnostic ignored \"-Wdeprecated-copy\"\n  #endif\n\n  #include <boost/config.hpp>\n  #include <boost/multiprecision/number.hpp>\n  #include <boost/version.hpp>\n\n  #include <math/wide_integer/uintwide_t.h>\n\n  #if defined(WIDE_INTEGER_NAMESPACE)\n  #if (~(~WIDE_INTEGER_NAMESPACE + 0) == 0 && ~(~WIDE_INTEGER_NAMESPACE + 1) == 1)\n  #else\n  using namespace WIDE_INTEGER_NAMESPACE;\n  #endif\n  #endif\n\n  namespace boost { namespace multiprecision {\n\n  // Forward declaration of the uintwide_t_backend multiple precision\n  // class. This class binds native ::math::wide_integer::uintwide_t\n  // to boost::multiprecsion::uintwide_t_backend.\n\n  template<const ::math::wide_integer::size_t MyWidth2,\n           typename MyLimbType>\n  class uintwide_t_backend;\n\n  // Define the number category as an integer number kind\n  // for the uintwide_t_backend. This is needed for properly\n  // interacting as a backend with boost::muliprecision.\n  #if (defined(BOOST_VERSION) && (BOOST_VERSION <= 107200))\n  template<const ::math::wide_integer::size_t MyWidth2,\n           typename MyLimbType>\n  struct number_category<uintwide_t_backend<MyWidth2, MyLimbType>>\n    : public boost::mpl::int_<number_kind_integer> { };\n  #elif (defined(BOOST_VERSION) && (BOOST_VERSION <= 107500))\n  template<const ::math::wide_integer::size_t MyWidth2,\n           typename MyLimbType>\n  struct number_category<uintwide_t_backend<MyWidth2, MyLimbType>>\n    : public boost::integral_constant<int, number_kind_integer> { };\n  #else\n  template<const ::math::wide_integer::size_t MyWidth2,\n           typename MyLimbType>\n  struct number_category<uintwide_t_backend<MyWidth2, MyLimbType>>\n    : public std::integral_constant<int, number_kind_integer> { };\n  #endif\n\n  // This is the uintwide_t_backend multiple precision class.\n  template<const ::math::wide_integer::size_t MyWidth2,\n           typename MyLimbType = std::uint32_t>\n  class uintwide_t_backend // NOLINT(cppcoreguidelines-special-member-functions,hicpp-special-member-functions)\n  {\n  public:\n    using representation_type = ::math::wide_integer::uintwide_t<MyWidth2, MyLimbType>;\n\n    #if (defined(BOOST_VERSION) && (BOOST_VERSION <= 107500))\n    using signed_types   = mpl::list<std::int64_t>;\n    using unsigned_types = mpl::list<std::uint64_t>;\n    using float_types    = mpl::list<long double>;\n    #else\n    using   signed_types = std::tuple<  signed char,   signed short,   signed int,   signed long,   signed long long, std::intmax_t>;  // NOLINT(google-runtime-int)\n    using unsigned_types = std::tuple<unsigned char, unsigned short, unsigned int, unsigned long, unsigned long long, std::uintmax_t>; // NOLINT(google-runtime-int)\n    using float_types    = std::tuple<float, double, long double>;\n    #endif\n\n    constexpr uintwide_t_backend() : m_value() { }\n\n    explicit constexpr uintwide_t_backend(const representation_type& rep) : m_value(rep) { }\n\n    constexpr uintwide_t_backend(const uintwide_t_backend& other) : m_value(other.m_value) { }\n\n    template<typename UnsignedIntegralType,\n             typename std::enable_if<(   (std::is_integral<UnsignedIntegralType>::value == true)\n                                      && (std::is_unsigned<UnsignedIntegralType>::value == true))>::type const* = nullptr>\n    constexpr uintwide_t_backend(UnsignedIntegralType u) : m_value(representation_type(std::uint64_t(u))) { } // NOLINT(google-explicit-constructor,hicpp-explicit-conversions)\n\n    template<typename SignedIntegralType,\n             typename std::enable_if<(   (std::is_integral<SignedIntegralType>::value == true)\n                                      && (std::is_signed  <SignedIntegralType>::value == true))>::type const* = nullptr>\n    constexpr uintwide_t_backend(SignedIntegralType n) : m_value(representation_type(std::int64_t(n))) { } // NOLINT(google-explicit-constructor,hicpp-explicit-conversions)\n\n    template<typename FloatingPointType,\n             typename std::enable_if<std::is_floating_point<FloatingPointType>::value == true>::type const* = nullptr>\n    constexpr uintwide_t_backend(FloatingPointType f) : m_value(representation_type(static_cast<long double>(f))) { } // NOLINT(google-explicit-constructor,hicpp-explicit-conversions)\n\n    constexpr uintwide_t_backend(const char* c) : m_value(c) { } // NOLINT(google-explicit-constructor,hicpp-explicit-conversions)\n\n    constexpr uintwide_t_backend(const std::string& str) : m_value(str) { } // NOLINT(google-explicit-constructor,hicpp-explicit-conversions)\n\n    //~uintwide_t_backend() { }\n\n    WIDE_INTEGER_CONSTEXPR auto operator=(const uintwide_t_backend& other) -> uintwide_t_backend&\n    {\n      if(this != &other)\n      {\n        m_value.representation() = other.m_value.crepresentation();\n      }\n\n      return *this;\n    }\n\n    template<typename ArithmeticType,\n             typename std::enable_if<std::is_arithmetic<ArithmeticType>::value == true>::type const* = nullptr>\n    WIDE_INTEGER_CONSTEXPR auto operator=(const ArithmeticType& x) -> uintwide_t_backend&\n    {\n      m_value = representation_type(x);\n\n      return *this;\n    }\n\n    WIDE_INTEGER_CONSTEXPR auto operator=(const std::string& str_rep)  -> uintwide_t_backend& { m_value = representation_type(str_rep);  return *this; }\n    WIDE_INTEGER_CONSTEXPR auto operator=(const char*        char_ptr) -> uintwide_t_backend& { m_value = representation_type(char_ptr); return *this; }\n\n    WIDE_INTEGER_CONSTEXPR void swap(uintwide_t_backend& other_mp_cpp_backend)\n    {\n      m_value.representation().swap(other_mp_cpp_backend.m_value.representation());\n    }\n\n    WIDE_INTEGER_CONSTEXPR auto  representation()       ->       representation_type& { return m_value; }\n    WIDE_INTEGER_CONSTEXPR auto  representation() const -> const representation_type& { return m_value; }\n    WIDE_INTEGER_CONSTEXPR auto crepresentation() const -> const representation_type& { return m_value; }\n\n    auto str(std::streamsize number_of_digits, const std::ios::fmtflags format_flags) const -> std::string\n    {\n      (void) number_of_digits;\n\n      std::array<char, representation_type::wr_string_max_buffer_size_dec> pstr { };\n\n      const std::uint_fast8_t base_rep     = (((format_flags & std::ios::hex)       != 0) ? 16U : 10U);\n      const bool              show_base    = ( (format_flags & std::ios::showbase)  != 0);\n      const bool              show_pos     = ( (format_flags & std::ios::showpos)   != 0);\n      const bool              is_uppercase = ( (format_flags & std::ios::uppercase) != 0);\n\n      const bool wr_string_is_ok = m_value.wr_string(pstr.data(), base_rep, show_base, show_pos, is_uppercase);\n\n      std::string str_result = (wr_string_is_ok ? std::string(pstr.data()) : std::string());\n\n      return str_result;\n    }\n\n    WIDE_INTEGER_CONSTEXPR void negate()\n    {\n      m_value.negate();\n    }\n\n    constexpr auto compare(const uintwide_t_backend& other_mp_cpp_backend) const -> int\n    {\n      return static_cast<int>(m_value.compare(other_mp_cpp_backend.crepresentation()));\n    }\n\n    template<typename ArithmeticType,\n             typename std::enable_if<std::is_arithmetic<ArithmeticType>::value == true>::type const* = nullptr>\n    constexpr auto compare(ArithmeticType x) const -> int\n    {\n      return static_cast<int>(m_value.compare(representation_type(x)));\n    }\n\n    auto operator=(const representation_type&) -> uintwide_t_backend& = delete;\n\n  private:\n    representation_type m_value;\n  };\n\n  template<const ::math::wide_integer::size_t MyWidth2,\n           typename MyLimbType>\n  WIDE_INTEGER_CONSTEXPR void eval_add(uintwide_t_backend<MyWidth2, MyLimbType>& result, const uintwide_t_backend<MyWidth2, MyLimbType>& x)\n  {\n    result.representation() += x.crepresentation();\n  }\n\n  template<const ::math::wide_integer::size_t MyWidth2,\n           typename MyLimbType>\n  WIDE_INTEGER_CONSTEXPR void eval_subtract(uintwide_t_backend<MyWidth2, MyLimbType>& result, const uintwide_t_backend<MyWidth2, MyLimbType>& x)\n  {\n    result.representation() -= x.crepresentation();\n  }\n\n  template<const ::math::wide_integer::size_t MyWidth2,\n           typename MyLimbType>\n  WIDE_INTEGER_CONSTEXPR void eval_multiply(uintwide_t_backend<MyWidth2, MyLimbType>& result, const uintwide_t_backend<MyWidth2, MyLimbType>& x)\n  {\n    result.representation() *= x.crepresentation();\n  }\n\n  template<const ::math::wide_integer::size_t MyWidth2,\n           typename MyLimbType,\n           typename IntegralType,\n           typename std::enable_if<(std::is_integral<IntegralType>::value == true)>::type const* = nullptr>\n  WIDE_INTEGER_CONSTEXPR void eval_multiply(uintwide_t_backend<MyWidth2, MyLimbType>& result, const IntegralType& n)\n  {\n    result.representation() *= n;\n  }\n\n  template<const ::math::wide_integer::size_t MyWidth2,\n           typename MyLimbType>\n  WIDE_INTEGER_CONSTEXPR void eval_divide(uintwide_t_backend<MyWidth2, MyLimbType>& result, const uintwide_t_backend<MyWidth2, MyLimbType>& x)\n  {\n    result.representation() /= x.crepresentation();\n  }\n\n  template<const ::math::wide_integer::size_t MyWidth2,\n           typename MyLimbType,\n           typename IntegralType,\n           typename std::enable_if<(   (std::is_fundamental<IntegralType>::value == true)\n                                    && (std::is_integral   <IntegralType>::value == true)\n                                    && (std::is_unsigned   <IntegralType>::value == true)\n                                    && (std::numeric_limits<IntegralType>::digits <= std::numeric_limits<MyLimbType>::digits))>::type const* = nullptr>\n  WIDE_INTEGER_CONSTEXPR void eval_divide(uintwide_t_backend<MyWidth2, MyLimbType>& result, const IntegralType& n)\n  {\n    using local_wide_integer_type = typename uintwide_t_backend<MyWidth2, MyLimbType>::representation_type;\n\n    using local_limb_type = typename local_wide_integer_type::limb_type;\n\n    result.representation().eval_divide_by_single_limb(static_cast<local_limb_type>(n), 0U, nullptr);\n  }\n\n  template<const ::math::wide_integer::size_t MyWidth2,\n           typename MyLimbType,\n           typename IntegralType,\n           typename std::enable_if<(   (std::is_fundamental<IntegralType>::value == true)\n                                    && (std::is_integral   <IntegralType>::value == true)\n                                    && (std::is_unsigned   <IntegralType>::value == true)\n                                    && (std::numeric_limits<IntegralType>::digits) > std::numeric_limits<MyLimbType>::digits)>::type const* = nullptr>\n  WIDE_INTEGER_CONSTEXPR void eval_divide(uintwide_t_backend<MyWidth2, MyLimbType>& result, const IntegralType& n)\n  {\n    result.representation() /= n;\n  }\n\n  template<const ::math::wide_integer::size_t MyWidth2,\n           typename MyLimbType>\n  WIDE_INTEGER_CONSTEXPR void eval_modulus(uintwide_t_backend<MyWidth2, MyLimbType>& result, const uintwide_t_backend<MyWidth2, MyLimbType>& x)\n  {\n    result.representation() %= x.crepresentation();\n  }\n\n  template<const ::math::wide_integer::size_t MyWidth2,\n           typename MyLimbType,\n           typename IntegralType,\n           typename std::enable_if<(   (std::is_fundamental<IntegralType>::value == true)\n                                    && (std::is_integral   <IntegralType>::value == true)\n                                    && (std::is_unsigned   <IntegralType>::value == true)\n                                    && (std::numeric_limits<IntegralType>::digits <= std::numeric_limits<MyLimbType>::digits))>::type const* = nullptr>\n  WIDE_INTEGER_CONSTEXPR auto eval_integer_modulus(uintwide_t_backend<MyWidth2, MyLimbType>& x, const IntegralType& n) -> IntegralType\n  {\n    using local_wide_integer_type = typename uintwide_t_backend<MyWidth2, MyLimbType>::representation_type;\n\n    typename uintwide_t_backend<MyWidth2, MyLimbType>::representation_type rem;\n\n    local_wide_integer_type(x.crepresentation()).eval_divide_by_single_limb(n, 0U, &rem);\n\n    return static_cast<IntegralType>(rem);\n  }\n\n  template<const ::math::wide_integer::size_t MyWidth2,\n           typename MyLimbType,\n           typename IntegralType,\n           typename std::enable_if<(   (std::is_fundamental<IntegralType>::value == true)\n                                    && (std::is_integral   <IntegralType>::value == true)\n                                    && (std::is_unsigned   <IntegralType>::value == true)\n                                    && (std::numeric_limits<IntegralType>::digits) > std::numeric_limits<MyLimbType>::digits)>::type const* = nullptr>\n  WIDE_INTEGER_CONSTEXPR auto eval_integer_modulus(uintwide_t_backend<MyWidth2, MyLimbType>& x, const IntegralType& n) -> IntegralType\n  {\n    const uintwide_t_backend<MyWidth2, MyLimbType> rem = x.crepresentation() % uintwide_t_backend<MyWidth2, MyLimbType>(n);\n\n    return static_cast<IntegralType>(rem);\n  }\n\n  template<const ::math::wide_integer::size_t MyWidth2,\n           typename MyLimbType>\n  WIDE_INTEGER_CONSTEXPR void eval_bitwise_and(uintwide_t_backend<MyWidth2, MyLimbType>& result, const uintwide_t_backend<MyWidth2, MyLimbType>& x)\n  {\n    result.representation() &= x.crepresentation();\n  }\n\n  template<const ::math::wide_integer::size_t MyWidth2,\n           typename MyLimbType>\n  WIDE_INTEGER_CONSTEXPR void eval_bitwise_or(uintwide_t_backend<MyWidth2, MyLimbType>& result, const uintwide_t_backend<MyWidth2, MyLimbType>& x)\n  {\n    result.representation() |= x.crepresentation();\n  }\n\n  template<const ::math::wide_integer::size_t MyWidth2,\n           typename MyLimbType>\n  WIDE_INTEGER_CONSTEXPR void eval_bitwise_xor(uintwide_t_backend<MyWidth2, MyLimbType>& result, const uintwide_t_backend<MyWidth2, MyLimbType>& x)\n  {\n    result.representation() ^= x.crepresentation();\n  }\n\n  template<const ::math::wide_integer::size_t MyWidth2,\n           typename MyLimbType>\n  WIDE_INTEGER_CONSTEXPR void eval_complement(uintwide_t_backend<MyWidth2, MyLimbType>& result, const uintwide_t_backend<MyWidth2, MyLimbType>& x)\n  {\n    for(auto i = 0U; i < std::tuple_size<typename uintwide_t_backend<MyWidth2, MyLimbType>::representation_type>::value; ++i)\n    {\n      using local_limb_type = typename uintwide_t_backend<MyWidth2, MyLimbType>::limb_type;\n\n      result.representation().representation()[i] = static_cast<local_limb_type>(~x.crepresentation().crepresentation()[i]);\n    }\n  }\n\n  template<const ::math::wide_integer::size_t MyWidth2,\n           typename MyLimbType>\n  WIDE_INTEGER_CONSTEXPR void eval_powm(      uintwide_t_backend<MyWidth2, MyLimbType>& result,\n                                        const uintwide_t_backend<MyWidth2, MyLimbType>& b,\n                                        const uintwide_t_backend<MyWidth2, MyLimbType>& p,\n                                        const uintwide_t_backend<MyWidth2, MyLimbType>& m)\n  {\n    result.representation() = powm(b.crepresentation(),\n                                   p.crepresentation(),\n                                   m.crepresentation());\n  }\n\n  template<const ::math::wide_integer::size_t MyWidth2,\n           typename MyLimbType,\n           typename OtherIntegralTypeM,\n           typename std::enable_if<(   (std::is_integral   <OtherIntegralTypeM>::value == true)\n                                    && (std::is_fundamental<OtherIntegralTypeM>::value == true))>::type const* = nullptr>\n  WIDE_INTEGER_CONSTEXPR void eval_powm(      uintwide_t_backend<MyWidth2, MyLimbType>& result,\n                                        const uintwide_t_backend<MyWidth2, MyLimbType>& b,\n                                        const uintwide_t_backend<MyWidth2, MyLimbType>& p,\n                                        const OtherIntegralTypeM                         m)\n  {\n    result.representation() = powm(b.crepresentation(),\n                                   p.crepresentation(),\n                                   m);\n  }\n\n  template<const ::math::wide_integer::size_t MyWidth2,\n           typename MyLimbType,\n           typename OtherIntegralTypeP,\n           typename std::enable_if<(   (std::is_integral   <OtherIntegralTypeP>::value == true)\n                                    && (std::is_fundamental<OtherIntegralTypeP>::value == true))>::type const* = nullptr>\n  WIDE_INTEGER_CONSTEXPR void eval_powm(      uintwide_t_backend<MyWidth2, MyLimbType>& result,\n                                        const uintwide_t_backend<MyWidth2, MyLimbType>& b,\n                                        const OtherIntegralTypeP                         p,\n                                        const uintwide_t_backend<MyWidth2, MyLimbType>& m)\n  {\n    result.representation() = powm(b.crepresentation(),\n                                   p,\n                                   m.crepresentation());\n  }\n\n  template<const ::math::wide_integer::size_t MyWidth2,\n           typename MyLimbType,\n           typename IntegralType,\n           typename std::enable_if<(   (std::is_integral   <IntegralType>::value == true)\n                                    && (std::is_fundamental<IntegralType>::value == true))>::type const* = nullptr>\n  WIDE_INTEGER_CONSTEXPR void eval_left_shift(uintwide_t_backend<MyWidth2, MyLimbType>& result, const IntegralType& n)\n  {\n    result.representation() <<= n;\n  }\n\n  template<const ::math::wide_integer::size_t MyWidth2,\n           typename MyLimbType,\n           typename IntegralType,\n           typename std::enable_if<(   (std::is_integral   <IntegralType>::value == true)\n                                    && (std::is_fundamental<IntegralType>::value == true))>::type const* = nullptr>\n  WIDE_INTEGER_CONSTEXPR void eval_right_shift(uintwide_t_backend<MyWidth2, MyLimbType>& result, const IntegralType& n)\n  {\n    result.representation() >>= n;\n  }\n\n  template<const ::math::wide_integer::size_t MyWidth2,\n           typename MyLimbType>\n  WIDE_INTEGER_CONSTEXPR auto eval_lsb(const uintwide_t_backend<MyWidth2, MyLimbType>& a) -> unsigned\n  {\n    return static_cast<unsigned>(lsb(a.crepresentation()));\n  }\n\n  template<const ::math::wide_integer::size_t MyWidth2,\n           typename MyLimbType>\n  WIDE_INTEGER_CONSTEXPR auto eval_msb(const uintwide_t_backend<MyWidth2, MyLimbType>& a) -> unsigned\n  {\n    return static_cast<unsigned>(msb(a.crepresentation()));\n  }\n\n  template<const ::math::wide_integer::size_t MyWidth2,\n           typename MyLimbType>\n  WIDE_INTEGER_CONSTEXPR auto eval_eq(const uintwide_t_backend<MyWidth2, MyLimbType>& a, const uintwide_t_backend<MyWidth2, MyLimbType>& b) -> bool\n  {\n    return (a.compare(b) == 0);\n  }\n\n  template<const ::math::wide_integer::size_t MyWidth2,\n           typename MyLimbType,\n           typename ArithmeticType,\n           typename std::enable_if<(   (std::is_arithmetic <ArithmeticType>::value == true)\n                                    && (std::is_fundamental<ArithmeticType>::value == true))>::type const* = nullptr>\n  WIDE_INTEGER_CONSTEXPR auto eval_eq(const uintwide_t_backend<MyWidth2, MyLimbType>& a, const ArithmeticType& b) -> bool\n  {\n    return (a.compare(b) == 0);\n  }\n\n  template<const ::math::wide_integer::size_t MyWidth2,\n           typename MyLimbType,\n           typename ArithmeticType,\n           typename std::enable_if<(   (std::is_arithmetic <ArithmeticType>::value == true)\n                                    && (std::is_fundamental<ArithmeticType>::value == true))>::type const* = nullptr>\n  WIDE_INTEGER_CONSTEXPR auto eval_eq(const ArithmeticType& a, const uintwide_t_backend<MyWidth2, MyLimbType>& b) -> bool\n  {\n    return (uintwide_t_backend<MyWidth2, MyLimbType>(a).compare(b) == 0);\n  }\n\n  template<const ::math::wide_integer::size_t MyWidth2,\n           typename MyLimbType>\n  WIDE_INTEGER_CONSTEXPR auto eval_gt(const uintwide_t_backend<MyWidth2, MyLimbType>& a, const uintwide_t_backend<MyWidth2, MyLimbType>& b) -> bool\n  {\n    return (a.compare(b) == 1);\n  }\n\n  template<const ::math::wide_integer::size_t MyWidth2,\n           typename MyLimbType,\n           typename ArithmeticType,\n           typename std::enable_if<(   (std::is_arithmetic <ArithmeticType>::value == true)\n                                    && (std::is_fundamental<ArithmeticType>::value == true))>::type const* = nullptr>\n  WIDE_INTEGER_CONSTEXPR auto eval_gt(const uintwide_t_backend<MyWidth2, MyLimbType>& a, const ArithmeticType& b) -> bool\n  {\n    return (a.compare(b) == 1);\n  }\n\n  template<const ::math::wide_integer::size_t MyWidth2,\n           typename MyLimbType,\n           typename ArithmeticType,\n           typename std::enable_if<(   (std::is_arithmetic <ArithmeticType>::value == true)\n                                    && (std::is_fundamental<ArithmeticType>::value == true))>::type const* = nullptr>\n  WIDE_INTEGER_CONSTEXPR auto eval_gt(const ArithmeticType& a, const uintwide_t_backend<MyWidth2, MyLimbType>& b) -> bool\n  {\n    return (uintwide_t_backend<MyWidth2, MyLimbType>(a).compare(b) == 1);\n  }\n\n  template<const ::math::wide_integer::size_t MyWidth2,\n           typename MyLimbType>\n  WIDE_INTEGER_CONSTEXPR auto eval_lt(const uintwide_t_backend<MyWidth2, MyLimbType>& a, const uintwide_t_backend<MyWidth2, MyLimbType>& b) -> bool\n  {\n    return (a.compare(b) == -1);\n  }\n\n  template<const ::math::wide_integer::size_t MyWidth2,\n           typename MyLimbType,\n           typename ArithmeticType,\n           typename std::enable_if<(   (std::is_arithmetic <ArithmeticType>::value == true)\n                                    && (std::is_fundamental<ArithmeticType>::value == true))>::type const* = nullptr>\n  WIDE_INTEGER_CONSTEXPR auto eval_lt(const uintwide_t_backend<MyWidth2, MyLimbType>& a, const ArithmeticType& b) -> bool\n  {\n    return (a.compare(b) == -1);\n  }\n\n  template<const ::math::wide_integer::size_t MyWidth2,\n           typename MyLimbType,\n           typename ArithmeticType,\n           typename std::enable_if<(   (std::is_arithmetic <ArithmeticType>::value == true)\n                                    && (std::is_fundamental<ArithmeticType>::value == true))>::type const* = nullptr>\n  WIDE_INTEGER_CONSTEXPR auto eval_lt(const ArithmeticType& a, const uintwide_t_backend<MyWidth2, MyLimbType>& b) -> bool\n  {\n    return (uintwide_t_backend<MyWidth2, MyLimbType>(a).compare(b) == -1);\n  }\n\n  template<const ::math::wide_integer::size_t MyWidth2,\n           typename MyLimbType>\n  WIDE_INTEGER_CONSTEXPR auto eval_is_zero(const uintwide_t_backend<MyWidth2, MyLimbType>& x) -> bool\n  {\n    return (x.crepresentation() == 0U);\n  }\n\n  template<const ::math::wide_integer::size_t MyWidth2,\n           typename MyLimbType>\n  WIDE_INTEGER_CONSTEXPR auto eval_get_sign(const uintwide_t_backend<MyWidth2, MyLimbType>& x) -> int\n  {\n    int n_result { };\n\n    if  (x.crepresentation() == 0U) { n_result = 0; }\n    else                            { n_result = 1; }\n\n    return n_result;\n  }\n\n  template<const ::math::wide_integer::size_t MyWidth2,\n           typename MyLimbType>\n  WIDE_INTEGER_CONSTEXPR void eval_convert_to(unsigned long long* result, // NOLINT(google-runtime-int)\n                                              const uintwide_t_backend<MyWidth2, MyLimbType>& val)\n  {\n    *result = static_cast<unsigned long long>(val.crepresentation()); // NOLINT(google-runtime-int)\n  }\n\n  template<const ::math::wide_integer::size_t MyWidth2,\n           typename MyLimbType>\n  WIDE_INTEGER_CONSTEXPR void eval_convert_to(signed long long* result, // NOLINT(google-runtime-int)\n                                              const uintwide_t_backend<MyWidth2, MyLimbType>& val)\n  {\n    *result = static_cast<signed long long>(val.crepresentation()); // NOLINT(google-runtime-int)\n  }\n\n  template<const ::math::wide_integer::size_t MyWidth2,\n           typename MyLimbType>\n  WIDE_INTEGER_CONSTEXPR void eval_convert_to(long double* result,\n                                              const uintwide_t_backend<MyWidth2, MyLimbType>& val)\n  {\n    *result = static_cast<long double>(val.crepresentation());\n  }\n\n  } // namespace multiprecision\n  } // namespace boost\n\n  namespace boost { namespace math { namespace policies {\n\n  // Specialization of the precision structure.\n  template<const ::math::wide_integer::size_t MyWidth2,\n           typename MyLimbType,\n           typename ThisPolicy,\n           const boost::multiprecision::expression_template_option ExpressionTemplatesOptions>\n  struct precision<boost::multiprecision::number<boost::multiprecision::uintwide_t_backend<MyWidth2, MyLimbType>,\n                                                 ExpressionTemplatesOptions>,\n                   ThisPolicy>\n  {\n    using precision_type = typename ThisPolicy::precision_type;\n\n    using local_digits_2 = digits2<MyWidth2>;\n\n    #if (BOOST_VERSION <= 107500)\n    using type = typename mpl::if_c       <((local_digits_2::value <= precision_type::value) || (precision_type::value <= 0)),\n                                             local_digits_2,\n                                             precision_type>::type;\n    #else\n    using type = typename std::conditional<((local_digits_2::value <= precision_type::value) || (precision_type::value <= 0)),\n                                             local_digits_2,\n                                             precision_type>::type;\n    #endif\n  };\n\n  } // namespace policies\n  } // namespace math\n  } // namespace boost\n\n  namespace std // NOLINT(cert-dcl58-cpp)\n  {\n    template<const ::math::wide_integer::size_t MyWidth2,\n             typename MyLimbType,\n             const boost::multiprecision::expression_template_option ExpressionTemplatesOptions>\n    class numeric_limits<boost::multiprecision::number<boost::multiprecision::uintwide_t_backend<MyWidth2, MyLimbType>,\n                                                       ExpressionTemplatesOptions>>\n    {\n    public:\n      static constexpr bool is_specialized = true;\n      static constexpr bool is_signed      = false;\n      static constexpr bool is_integer     = true;\n      static constexpr bool is_exact       = true;\n      static constexpr bool is_bounded     = true;\n      static constexpr bool is_modulo      = false;\n      static constexpr bool is_iec559      = false;\n      static constexpr int  digits         = MyWidth2;\n      static constexpr int  digits10       = static_cast<int>((MyWidth2 * 301LL) / 1000LL);\n      static constexpr int  max_digits10   = static_cast<int>((MyWidth2 * 301LL) / 1000LL);\n\n      static constexpr int max_exponent   = std::numeric_limits<::math::wide_integer::uintwide_t<MyWidth2, MyLimbType>>::max_exponent;\n      static constexpr int max_exponent10 = std::numeric_limits<::math::wide_integer::uintwide_t<MyWidth2, MyLimbType>>::max_exponent10;\n      static constexpr int min_exponent   = std::numeric_limits<::math::wide_integer::uintwide_t<MyWidth2, MyLimbType>>::min_exponent;\n      static constexpr int min_exponent10 = std::numeric_limits<::math::wide_integer::uintwide_t<MyWidth2, MyLimbType>>::min_exponent10;\n\n      static constexpr int                     radix             = 2;\n      static constexpr std::float_round_style  round_style       = std::round_to_nearest;\n      static constexpr bool                    has_infinity      = false;\n      static constexpr bool                    has_quiet_NaN     = false;\n      static constexpr bool                    has_signaling_NaN = false;\n      static constexpr std::float_denorm_style has_denorm        = std::denorm_absent;\n      static constexpr bool                    has_denorm_loss   = false;\n      static constexpr bool                    traps             = false;\n      static constexpr bool                    tinyness_before   = false;\n\n      static WIDE_INTEGER_CONSTEXPR auto (min)        () -> boost::multiprecision::number<boost::multiprecision::uintwide_t_backend<MyWidth2, MyLimbType>, ExpressionTemplatesOptions> { return boost::multiprecision::uintwide_t_backend<MyWidth2, MyLimbType>((std::numeric_limits<::math::wide_integer::uintwide_t<MyWidth2, MyLimbType>>::min)()       ); }\n      static WIDE_INTEGER_CONSTEXPR auto (max)        () -> boost::multiprecision::number<boost::multiprecision::uintwide_t_backend<MyWidth2, MyLimbType>, ExpressionTemplatesOptions> { return boost::multiprecision::uintwide_t_backend<MyWidth2, MyLimbType>((std::numeric_limits<::math::wide_integer::uintwide_t<MyWidth2, MyLimbType>>::max)()       ); }\n      static WIDE_INTEGER_CONSTEXPR auto lowest       () -> boost::multiprecision::number<boost::multiprecision::uintwide_t_backend<MyWidth2, MyLimbType>, ExpressionTemplatesOptions> { return boost::multiprecision::uintwide_t_backend<MyWidth2, MyLimbType> (std::numeric_limits<::math::wide_integer::uintwide_t<MyWidth2, MyLimbType>>::lowest       ); }\n      static WIDE_INTEGER_CONSTEXPR auto epsilon      () -> boost::multiprecision::number<boost::multiprecision::uintwide_t_backend<MyWidth2, MyLimbType>, ExpressionTemplatesOptions> { return boost::multiprecision::uintwide_t_backend<MyWidth2, MyLimbType> (std::numeric_limits<::math::wide_integer::uintwide_t<MyWidth2, MyLimbType>>::epsilon      ); }\n      static WIDE_INTEGER_CONSTEXPR auto round_error  () -> boost::multiprecision::number<boost::multiprecision::uintwide_t_backend<MyWidth2, MyLimbType>, ExpressionTemplatesOptions> { return boost::multiprecision::uintwide_t_backend<MyWidth2, MyLimbType> (std::numeric_limits<::math::wide_integer::uintwide_t<MyWidth2, MyLimbType>>::round_error  ); }\n      static WIDE_INTEGER_CONSTEXPR auto infinity     () -> boost::multiprecision::number<boost::multiprecision::uintwide_t_backend<MyWidth2, MyLimbType>, ExpressionTemplatesOptions> { return boost::multiprecision::uintwide_t_backend<MyWidth2, MyLimbType> (std::numeric_limits<::math::wide_integer::uintwide_t<MyWidth2, MyLimbType>>::infinity     ); }\n      static WIDE_INTEGER_CONSTEXPR auto quiet_NaN    () -> boost::multiprecision::number<boost::multiprecision::uintwide_t_backend<MyWidth2, MyLimbType>, ExpressionTemplatesOptions> { return boost::multiprecision::uintwide_t_backend<MyWidth2, MyLimbType> (std::numeric_limits<::math::wide_integer::uintwide_t<MyWidth2, MyLimbType>>::quiet_NaN    ); }\n      static WIDE_INTEGER_CONSTEXPR auto signaling_NaN() -> boost::multiprecision::number<boost::multiprecision::uintwide_t_backend<MyWidth2, MyLimbType>, ExpressionTemplatesOptions> { return boost::multiprecision::uintwide_t_backend<MyWidth2, MyLimbType> (std::numeric_limits<::math::wide_integer::uintwide_t<MyWidth2, MyLimbType>>::signaling_NaN); }\n      static WIDE_INTEGER_CONSTEXPR auto denorm_min   () -> boost::multiprecision::number<boost::multiprecision::uintwide_t_backend<MyWidth2, MyLimbType>, ExpressionTemplatesOptions> { return boost::multiprecision::uintwide_t_backend<MyWidth2, MyLimbType> (std::numeric_limits<::math::wide_integer::uintwide_t<MyWidth2, MyLimbType>>::denorm_min   ); }\n    };\n\n    #ifndef BOOST_NO_INCLASS_MEMBER_INITIALIZATION\n\n    template<const ::math::wide_integer::size_t MyWidth2, typename MyLimbType, const boost::multiprecision::expression_template_option ExpressionTemplatesOptions> constexpr bool std::numeric_limits<boost::multiprecision::number<boost::multiprecision::uintwide_t_backend<MyWidth2, MyLimbType>, ExpressionTemplatesOptions>>::is_specialized;\n    template<const ::math::wide_integer::size_t MyWidth2, typename MyLimbType, const boost::multiprecision::expression_template_option ExpressionTemplatesOptions> constexpr bool std::numeric_limits<boost::multiprecision::number<boost::multiprecision::uintwide_t_backend<MyWidth2, MyLimbType>, ExpressionTemplatesOptions>>::is_signed;\n    template<const ::math::wide_integer::size_t MyWidth2, typename MyLimbType, const boost::multiprecision::expression_template_option ExpressionTemplatesOptions> constexpr bool std::numeric_limits<boost::multiprecision::number<boost::multiprecision::uintwide_t_backend<MyWidth2, MyLimbType>, ExpressionTemplatesOptions>>::is_integer;\n    template<const ::math::wide_integer::size_t MyWidth2, typename MyLimbType, const boost::multiprecision::expression_template_option ExpressionTemplatesOptions> constexpr bool std::numeric_limits<boost::multiprecision::number<boost::multiprecision::uintwide_t_backend<MyWidth2, MyLimbType>, ExpressionTemplatesOptions>>::is_exact;\n    template<const ::math::wide_integer::size_t MyWidth2, typename MyLimbType, const boost::multiprecision::expression_template_option ExpressionTemplatesOptions> constexpr bool std::numeric_limits<boost::multiprecision::number<boost::multiprecision::uintwide_t_backend<MyWidth2, MyLimbType>, ExpressionTemplatesOptions>>::is_bounded;\n    template<const ::math::wide_integer::size_t MyWidth2, typename MyLimbType, const boost::multiprecision::expression_template_option ExpressionTemplatesOptions> constexpr bool std::numeric_limits<boost::multiprecision::number<boost::multiprecision::uintwide_t_backend<MyWidth2, MyLimbType>, ExpressionTemplatesOptions>>::is_modulo;\n    template<const ::math::wide_integer::size_t MyWidth2, typename MyLimbType, const boost::multiprecision::expression_template_option ExpressionTemplatesOptions> constexpr bool std::numeric_limits<boost::multiprecision::number<boost::multiprecision::uintwide_t_backend<MyWidth2, MyLimbType>, ExpressionTemplatesOptions>>::is_iec559;\n    template<const ::math::wide_integer::size_t MyWidth2, typename MyLimbType, const boost::multiprecision::expression_template_option ExpressionTemplatesOptions> constexpr int  std::numeric_limits<boost::multiprecision::number<boost::multiprecision::uintwide_t_backend<MyWidth2, MyLimbType>, ExpressionTemplatesOptions>>::digits;\n    template<const ::math::wide_integer::size_t MyWidth2, typename MyLimbType, const boost::multiprecision::expression_template_option ExpressionTemplatesOptions> constexpr int  std::numeric_limits<boost::multiprecision::number<boost::multiprecision::uintwide_t_backend<MyWidth2, MyLimbType>, ExpressionTemplatesOptions>>::digits10;\n    template<const ::math::wide_integer::size_t MyWidth2, typename MyLimbType, const boost::multiprecision::expression_template_option ExpressionTemplatesOptions> constexpr int  std::numeric_limits<boost::multiprecision::number<boost::multiprecision::uintwide_t_backend<MyWidth2, MyLimbType>, ExpressionTemplatesOptions>>::max_digits10;\n\n    template<const ::math::wide_integer::size_t MyWidth2, typename MyLimbType, const boost::multiprecision::expression_template_option ExpressionTemplatesOptions> constexpr int std::numeric_limits<boost::multiprecision::number<boost::multiprecision::uintwide_t_backend<MyWidth2, MyLimbType>, ExpressionTemplatesOptions>>::max_exponent;\n    template<const ::math::wide_integer::size_t MyWidth2, typename MyLimbType, const boost::multiprecision::expression_template_option ExpressionTemplatesOptions> constexpr int std::numeric_limits<boost::multiprecision::number<boost::multiprecision::uintwide_t_backend<MyWidth2, MyLimbType>, ExpressionTemplatesOptions>>::max_exponent10;\n    template<const ::math::wide_integer::size_t MyWidth2, typename MyLimbType, const boost::multiprecision::expression_template_option ExpressionTemplatesOptions> constexpr int std::numeric_limits<boost::multiprecision::number<boost::multiprecision::uintwide_t_backend<MyWidth2, MyLimbType>, ExpressionTemplatesOptions>>::min_exponent;\n    template<const ::math::wide_integer::size_t MyWidth2, typename MyLimbType, const boost::multiprecision::expression_template_option ExpressionTemplatesOptions> constexpr int std::numeric_limits<boost::multiprecision::number<boost::multiprecision::uintwide_t_backend<MyWidth2, MyLimbType>, ExpressionTemplatesOptions>>::min_exponent10;\n\n    template<const ::math::wide_integer::size_t MyWidth2, typename MyLimbType, const boost::multiprecision::expression_template_option ExpressionTemplatesOptions> constexpr int                     std::numeric_limits<boost::multiprecision::number<boost::multiprecision::uintwide_t_backend<MyWidth2, MyLimbType>, ExpressionTemplatesOptions>>::radix;\n    template<const ::math::wide_integer::size_t MyWidth2, typename MyLimbType, const boost::multiprecision::expression_template_option ExpressionTemplatesOptions> constexpr std::float_round_style  std::numeric_limits<boost::multiprecision::number<boost::multiprecision::uintwide_t_backend<MyWidth2, MyLimbType>, ExpressionTemplatesOptions>>::round_style;\n    template<const ::math::wide_integer::size_t MyWidth2, typename MyLimbType, const boost::multiprecision::expression_template_option ExpressionTemplatesOptions> constexpr bool                    std::numeric_limits<boost::multiprecision::number<boost::multiprecision::uintwide_t_backend<MyWidth2, MyLimbType>, ExpressionTemplatesOptions>>::has_infinity;\n    template<const ::math::wide_integer::size_t MyWidth2, typename MyLimbType, const boost::multiprecision::expression_template_option ExpressionTemplatesOptions> constexpr bool                    std::numeric_limits<boost::multiprecision::number<boost::multiprecision::uintwide_t_backend<MyWidth2, MyLimbType>, ExpressionTemplatesOptions>>::has_quiet_NaN;\n    template<const ::math::wide_integer::size_t MyWidth2, typename MyLimbType, const boost::multiprecision::expression_template_option ExpressionTemplatesOptions> constexpr bool                    std::numeric_limits<boost::multiprecision::number<boost::multiprecision::uintwide_t_backend<MyWidth2, MyLimbType>, ExpressionTemplatesOptions>>::has_signaling_NaN;\n    template<const ::math::wide_integer::size_t MyWidth2, typename MyLimbType, const boost::multiprecision::expression_template_option ExpressionTemplatesOptions> constexpr std::float_denorm_style std::numeric_limits<boost::multiprecision::number<boost::multiprecision::uintwide_t_backend<MyWidth2, MyLimbType>, ExpressionTemplatesOptions>>::has_denorm;\n    template<const ::math::wide_integer::size_t MyWidth2, typename MyLimbType, const boost::multiprecision::expression_template_option ExpressionTemplatesOptions> constexpr bool                    std::numeric_limits<boost::multiprecision::number<boost::multiprecision::uintwide_t_backend<MyWidth2, MyLimbType>, ExpressionTemplatesOptions>>::has_denorm_loss;\n    template<const ::math::wide_integer::size_t MyWidth2, typename MyLimbType, const boost::multiprecision::expression_template_option ExpressionTemplatesOptions> constexpr bool                    std::numeric_limits<boost::multiprecision::number<boost::multiprecision::uintwide_t_backend<MyWidth2, MyLimbType>, ExpressionTemplatesOptions>>::traps;\n    template<const ::math::wide_integer::size_t MyWidth2, typename MyLimbType, const boost::multiprecision::expression_template_option ExpressionTemplatesOptions> constexpr bool                    std::numeric_limits<boost::multiprecision::number<boost::multiprecision::uintwide_t_backend<MyWidth2, MyLimbType>, ExpressionTemplatesOptions>>::tinyness_before;\n\n    #endif // !BOOST_NO_INCLASS_MEMBER_INITIALIZATION\n\n  } // namespace std\n\n  #if (defined(__clang__) && (__clang_major__ > 9)) && !defined(__APPLE__)\n  #pragma GCC diagnostic pop\n  #endif\n\n  #if defined(__GNUC__)\n  #pragma GCC diagnostic pop\n  #pragma GCC diagnostic pop\n  #pragma GCC diagnostic pop\n  #endif\n\n#endif // UINTWIDE_T_BACKEND_2019_12_15_HPP\n", "meta": {"hexsha": "921800b669a98e2768d8a8ae2968b9cc2b43a4cf", "size": 39923, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/multiprecision/uintwide_t_backend.hpp", "max_stars_repo_name": "johnmcfarlane/wide-integer", "max_stars_repo_head_hexsha": "731d4aca71ba3e668a9d069765bf221f74ae52f1", "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/multiprecision/uintwide_t_backend.hpp", "max_issues_repo_name": "johnmcfarlane/wide-integer", "max_issues_repo_head_hexsha": "731d4aca71ba3e668a9d069765bf221f74ae52f1", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-05-05T10:44:39.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-09T20:30:03.000Z", "max_forks_repo_path": "boost/multiprecision/uintwide_t_backend.hpp", "max_forks_repo_name": "johnmcfarlane/wide-integer", "max_forks_repo_head_hexsha": "731d4aca71ba3e668a9d069765bf221f74ae52f1", "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": 61.6095679012, "max_line_length": 360, "alphanum_fraction": 0.7024772687, "num_tokens": 9354, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.600188359260205, "lm_q2_score": 0.5, "lm_q1q2_score": 0.3000941796301025}}
{"text": "#ifndef BoostUnitDefinitions_Units_hpp\n#define BoostUnitDefinitions_Units_hpp\n\n#include <boost/units/base_units/angle/arcminute.hpp>\n#include <boost/units/base_units/angle/arcsecond.hpp>\n#include <boost/units/base_units/angle/degree.hpp>\n#include <boost/units/base_units/imperial/foot.hpp>\n#include <boost/units/base_units/imperial/inch.hpp>\n#include <boost/units/base_units/imperial/yard.hpp>\n#include <boost/units/base_units/metric/year.hpp>\n#include <boost/units/cmath.hpp>\n#include <boost/units/systems/cgs.hpp>\n#include <boost/units/systems/cgs/io.hpp>\n#include <boost/units/systems/si.hpp>\n#include <boost/units/systems/si/io.hpp>\n\nnamespace boost\n{\nnamespace units\n{\n\n/** @brief namespace for unit types */\nnamespace t\n{\n}\n/** @brief namespace for unit instances*/\nnamespace i\n{\n}\n}  // namespace units\n}  // namespace boost\n\n/* A preprocessor macro for defining new units. Creates a unit types in the 't'\n * namespace and an instance of it in the 'i' namespace.\n */\n#define ADD_UNIT(NAME, ...)                   \\\n  namespace boost                             \\\n  {                                           \\\n  namespace units                             \\\n  {                                           \\\n  namespace t                                 \\\n  {                                           \\\n  typedef __VA_ARGS__ NAME;                   \\\n  }                                           \\\n  namespace i                                 \\\n  {                                           \\\n  BOOST_UNITS_STATIC_CONSTANT(NAME, t::NAME); \\\n  }                                           \\\n  }                                           \\\n  }\n\n/* Create a set of base units with all of the SI prefixes. */\n#define ADD_BASE_UNIT_SET(NAME, SYMB, BASE)                                    \\\n  ADD_UNIT(giga##NAME,                                                         \\\n           scaled_base_unit<BASE, scale<10, static_rational<9>>>::unit_type)   \\\n  ADD_UNIT(mega##NAME,                                                         \\\n           scaled_base_unit<BASE, scale<10, static_rational<6>>>::unit_type)   \\\n  ADD_UNIT(kilo##NAME,                                                         \\\n           scaled_base_unit<BASE, scale<10, static_rational<3>>>::unit_type)   \\\n  ADD_UNIT(NAME, BASE::unit_type)                                              \\\n  ADD_UNIT(centi##NAME,                                                        \\\n           scaled_base_unit<BASE, scale<10, static_rational<-2>>>::unit_type)  \\\n  ADD_UNIT(milli##NAME,                                                        \\\n           scaled_base_unit<BASE, scale<10, static_rational<-3>>>::unit_type)  \\\n  ADD_UNIT(micro##NAME,                                                        \\\n           scaled_base_unit<BASE, scale<10, static_rational<-6>>>::unit_type)  \\\n  ADD_UNIT(nano##NAME,                                                         \\\n           scaled_base_unit<BASE, scale<10, static_rational<-9>>>::unit_type)  \\\n  ADD_UNIT(pico##NAME,                                                         \\\n           scaled_base_unit<BASE, scale<10, static_rational<-12>>>::unit_type) \\\n  ADD_UNIT(femto##NAME,                                                        \\\n           scaled_base_unit<BASE, scale<10, static_rational<-15>>>::unit_type) \\\n  ADD_UNIT(G##SYMB,                                                            \\\n           scaled_base_unit<BASE, scale<10, static_rational<9>>>::unit_type)   \\\n  ADD_UNIT(M##SYMB,                                                            \\\n           scaled_base_unit<BASE, scale<10, static_rational<6>>>::unit_type)   \\\n  ADD_UNIT(k##SYMB,                                                            \\\n           scaled_base_unit<BASE, scale<10, static_rational<3>>>::unit_type)   \\\n  ADD_UNIT(SYMB, BASE::unit_type)                                              \\\n  ADD_UNIT(c##SYMB,                                                            \\\n           scaled_base_unit<BASE, scale<10, static_rational<-2>>>::unit_type)  \\\n  ADD_UNIT(m##SYMB,                                                            \\\n           scaled_base_unit<BASE, scale<10, static_rational<-3>>>::unit_type)  \\\n  ADD_UNIT(u##SYMB,                                                            \\\n           scaled_base_unit<BASE, scale<10, static_rational<-6>>>::unit_type)  \\\n  ADD_UNIT(n##SYMB,                                                            \\\n           scaled_base_unit<BASE, scale<10, static_rational<-9>>>::unit_type)  \\\n  ADD_UNIT(p##SYMB,                                                            \\\n           scaled_base_unit<BASE, scale<10, static_rational<-12>>>::unit_type) \\\n  ADD_UNIT(f##SYMB,                                                            \\\n           scaled_base_unit<BASE, scale<10, static_rational<-15>>>::unit_type)\n\n/* Create a set of (not base) units with all of the SI prefixes. */\n#define ADD_UNIT_SET(NAME, SYMB, UNIT)                                    \\\n  ADD_UNIT(giga##NAME,                                                    \\\n           make_scaled_unit<UNIT, scale<10, static_rational<9>>>::type)   \\\n  ADD_UNIT(mega##NAME,                                                    \\\n           make_scaled_unit<UNIT, scale<10, static_rational<6>>>::type)   \\\n  ADD_UNIT(kilo##NAME,                                                    \\\n           make_scaled_unit<UNIT, scale<10, static_rational<3>>>::type)   \\\n  ADD_UNIT(NAME, UNIT)                                                    \\\n  ADD_UNIT(centi##NAME,                                                   \\\n           make_scaled_unit<UNIT, scale<10, static_rational<-2>>>::type)  \\\n  ADD_UNIT(milli##NAME,                                                   \\\n           make_scaled_unit<UNIT, scale<10, static_rational<-3>>>::type)  \\\n  ADD_UNIT(micro##NAME,                                                   \\\n           make_scaled_unit<UNIT, scale<10, static_rational<-6>>>::type)  \\\n  ADD_UNIT(nano##NAME,                                                    \\\n           make_scaled_unit<UNIT, scale<10, static_rational<-9>>>::type)  \\\n  ADD_UNIT(pico##NAME,                                                    \\\n           make_scaled_unit<UNIT, scale<10, static_rational<-12>>>::type) \\\n  ADD_UNIT(femto##NAME,                                                   \\\n           make_scaled_unit<UNIT, scale<10, static_rational<-15>>>::type) \\\n  ADD_UNIT(G##SYMB,                                                       \\\n           make_scaled_unit<UNIT, scale<10, static_rational<9>>>::type)   \\\n  ADD_UNIT(M##SYMB,                                                       \\\n           make_scaled_unit<UNIT, scale<10, static_rational<6>>>::type)   \\\n  ADD_UNIT(k##SYMB,                                                       \\\n           make_scaled_unit<UNIT, scale<10, static_rational<3>>>::type)   \\\n  ADD_UNIT(SYMB, UNIT)                                                    \\\n  ADD_UNIT(c##SYMB,                                                       \\\n           make_scaled_unit<UNIT, scale<10, static_rational<-2>>>::type)  \\\n  ADD_UNIT(m##SYMB,                                                       \\\n           make_scaled_unit<UNIT, scale<10, static_rational<-3>>>::type)  \\\n  ADD_UNIT(u##SYMB,                                                       \\\n           make_scaled_unit<UNIT, scale<10, static_rational<-6>>>::type)  \\\n  ADD_UNIT(n##SYMB,                                                       \\\n           make_scaled_unit<UNIT, scale<10, static_rational<-9>>>::type)  \\\n  ADD_UNIT(p##SYMB,                                                       \\\n           make_scaled_unit<UNIT, scale<10, static_rational<-12>>>::type) \\\n  ADD_UNIT(f##SYMB,                                                       \\\n           make_scaled_unit<UNIT, scale<10, static_rational<-15>>>::type)\n\n/* Add an output overload. I.e., set the string that will be output when the\n * user prints the unit.\n */\n#define ADD_UNIT_IO(NAME, NSTR, SSTR)                            \\\n  namespace boost                                                \\\n  {                                                              \\\n  namespace units                                                \\\n  {                                                              \\\n  inline std::string name_string(const boost::units::t::NAME&)   \\\n  {                                                              \\\n    return NSTR;                                                 \\\n  }                                                              \\\n  inline std::string symbol_string(const boost::units::t::NAME&) \\\n  {                                                              \\\n    return SSTR;                                                 \\\n  }                                                              \\\n  }                                                              \\\n  }\n\n// Aliases\n\nADD_UNIT(dimensionless, si::dimensionless)\nADD_UNIT(dimless, dimensionless)\n\n// Base units\n// these units are based on scaled base units, which is required to\n// get the si unit prefixes to work correctly\nADD_BASE_UNIT_SET(meter, m, si::meter_base_unit)\nADD_BASE_UNIT_SET(gram, g, cgs::gram_base_unit)\nADD_BASE_UNIT_SET(second, s, si::second_base_unit)\nADD_BASE_UNIT_SET(kelvin, K, si::kelvin_base_unit)\nADD_BASE_UNIT_SET(ampere, A, si::ampere_base_unit)\nADD_BASE_UNIT_SET(mole, mol, si::mole_base_unit)\nADD_BASE_UNIT_SET(candela, cd, si::candela_base_unit)\n\n// Alternate Base Units\n// these units are alternate base units, i.e. they are\n// units for a single dimension.\n\nADD_UNIT(year, metric::year_base_unit::unit_type)\nADD_UNIT(yr, year)\n\nADD_UNIT(degree, angle::degree_base_unit::unit_type)\nADD_UNIT(deg, degree)\nADD_UNIT(arcminute, angle::arcminute_base_unit::unit_type)\nADD_UNIT(arcmin, arcminute)\nADD_UNIT(arcsecond, angle::arcsecond_base_unit::unit_type)\nADD_UNIT(arcsec, arcsecond)\n\nADD_UNIT(percent,\n         make_scaled_unit<dimensionless, scale<10, static_rational<-2>>>::type)\nADD_UNIT(perc, percent)\n\n// Imperial Units\nADD_UNIT(inches, imperial::inch_base_unit::unit_type)\nADD_UNIT(inch, inches)\nADD_UNIT(in, inches)\nADD_UNIT(feet, imperial::foot_base_unit::unit_type)\nADD_UNIT(foot, feet)\nADD_UNIT(ft, foot)\nADD_UNIT(yards, imperial::yard_base_unit::unit_type)\nADD_UNIT(yard, yards)\nADD_UNIT(yd, yard)\n\n// NOTE: These MUST be equivalent to the si:: units or the trig\n// functions will not work. We CANNOT use si::radian_base_unit here.\nADD_UNIT_SET(radian, rad, si::plane_angle)\nADD_UNIT_SET(steradian, sr, si::solid_angle)\n\n// Derived Units\n\nADD_UNIT(inverse_second, divide_typeof_helper<dimensionless, second>::type)\nADD_UNIT(s_n1, inverse_second)\nADD_UNIT_SET(hertz, Hz, inverse_second)\nADD_UNIT_SET(joule, J, si::energy)\nADD_UNIT_SET(watt, W, si::power)\nADD_UNIT_SET(newton, N, si::force)\nADD_UNIT_SET(coulomb, C, si::electric_charge)\n\n// Inverse Length\nADD_UNIT(inverse_kilometer,\n         divide_typeof_helper<dimensionless, kilometer>::type)\nADD_UNIT(inverse_meter, divide_typeof_helper<dimensionless, meter>::type)\nADD_UNIT(inverse_centimeter,\n         divide_typeof_helper<dimensionless, centimeter>::type)\nADD_UNIT(inverse_millimeter,\n         divide_typeof_helper<dimensionless, millimeter>::type)\nADD_UNIT(inverse_micrometer,\n         divide_typeof_helper<dimensionless, micrometer>::type)\nADD_UNIT(inverse_nanometer,\n         divide_typeof_helper<dimensionless, nanometer>::type)\nADD_UNIT(inverse_picometer,\n         divide_typeof_helper<dimensionless, picometer>::type)\nADD_UNIT(inverse_femtometer,\n         divide_typeof_helper<dimensionless, femtometer>::type)\n\nADD_UNIT(km_n1, inverse_kilometer)\nADD_UNIT(m_n1, inverse_meter)\nADD_UNIT(cm_n1, inverse_centimeter)\nADD_UNIT(mm_n1, inverse_millimeter)\nADD_UNIT(um_n1, inverse_micrometer)\nADD_UNIT(nm_n1, inverse_nanometer)\nADD_UNIT(pm_n1, inverse_picometer)\nADD_UNIT(fm_n1, inverse_femtometer)\n\n// Area\nADD_UNIT(kilometer_squared, multiply_typeof_helper<kilometer, kilometer>::type)\nADD_UNIT(meter_squared, multiply_typeof_helper<meter, meter>::type)\nADD_UNIT(m_p2, meter_squared)\nADD_UNIT(centimeter_squared,\n         multiply_typeof_helper<centimeter, centimeter>::type)\nADD_UNIT(cm_p2, centimeter_squared)\nADD_UNIT(millimeter_squared,\n         multiply_typeof_helper<millimeter, millimeter>::type)\nADD_UNIT(mm_p2, millimeter_squared)\n\n// Inverse Area\n\nADD_UNIT(inverse_kilometer_squared,\n         divide_typeof_helper<dimensionless, kilometer_squared>::type)\nADD_UNIT(inverse_meter_squared,\n         divide_typeof_helper<dimensionless, meter_squared>::type)\nADD_UNIT(inverse_centimeter_squared,\n         divide_typeof_helper<dimensionless, centimeter_squared>::type)\nADD_UNIT(inverse_millimeter_squared,\n         divide_typeof_helper<dimensionless, millimeter_squared>::type)\n\nADD_UNIT(km_n2, inverse_kilometer_squared)\nADD_UNIT(m_n2, inverse_meter_squared)\nADD_UNIT(cm_n2, inverse_centimeter_squared)\nADD_UNIT(mm_n2, inverse_millimeter_squared)\n\n// Velocity\nADD_UNIT(meter_per_second, divide_typeof_helper<meter, second>::type)\nADD_UNIT(m_s_n2, divide_typeof_helper<m, s>::type)\n\n// Radiant Exposure\nADD_UNIT(joule_per_centimeter_squared,\n         divide_typeof_helper<joule, centimeter_squared>::type)\nADD_UNIT(millijoule_per_centimeter_squared,\n         divide_typeof_helper<millijoule, centimeter_squared>::type)\nADD_UNIT(microjoule_per_centimeter_squared,\n         divide_typeof_helper<microjoule, centimeter_squared>::type)\nADD_UNIT(nanojoule_per_centimeter_squared,\n         divide_typeof_helper<nanojoule, centimeter_squared>::type)\n\nADD_UNIT(J_cm_n2, joule_per_centimeter_squared)\nADD_UNIT(mJ_cm_n2, millijoule_per_centimeter_squared)\nADD_UNIT(uJ_cm_n2, microjoule_per_centimeter_squared)\nADD_UNIT(nJ_cm_n2, nanojoule_per_centimeter_squared)\n\nADD_UNIT(joule_per_meter_squared,\n         divide_typeof_helper<joule, meter_squared>::type)\nADD_UNIT(millijoule_per_meter_squared,\n         divide_typeof_helper<millijoule, meter_squared>::type)\nADD_UNIT(microjoule_per_meter_squared,\n         divide_typeof_helper<microjoule, meter_squared>::type)\nADD_UNIT(nanojoule_per_meter_squared,\n         divide_typeof_helper<nanojoule, meter_squared>::type)\n\nADD_UNIT(J_m_n2, joule_per_meter_squared)\nADD_UNIT(mJ_m_n2, millijoule_per_meter_squared)\nADD_UNIT(uJ_m_n2, microjoule_per_meter_squared)\nADD_UNIT(nJ_m_n2, nanojoule_per_meter_squared)\n\nADD_UNIT_IO(joule_per_centimeter_squared, \"joule per centimeter squared\",\n            \"J cm^-2\")\nADD_UNIT_IO(joule_per_meter_squared, \"joule per meter squared\", \"J m^-2\")\n\n// Irradiance\nADD_UNIT(watt_per_centimeter_squared,\n         divide_typeof_helper<watt, centimeter_squared>::type)\nADD_UNIT(milliwatt_per_centimeter_squared,\n         divide_typeof_helper<milliwatt, centimeter_squared>::type)\nADD_UNIT(microwatt_per_centimeter_squared,\n         divide_typeof_helper<microwatt, centimeter_squared>::type)\nADD_UNIT(nanowatt_per_centimeter_squared,\n         divide_typeof_helper<nanowatt, centimeter_squared>::type)\n\nADD_UNIT(W_cm_n2, watt_per_centimeter_squared)\nADD_UNIT(mW_cm_n2, milliwatt_per_centimeter_squared)\nADD_UNIT(uW_cm_n2, microwatt_per_centimeter_squared)\nADD_UNIT(nW_cm_n2, nanowatt_per_centimeter_squared)\n\nADD_UNIT(watt_per_meter_squared,\n         divide_typeof_helper<watt, meter_squared>::type)\nADD_UNIT(milliwatt_per_meter_squared,\n         divide_typeof_helper<milliwatt, meter_squared>::type)\nADD_UNIT(microwatt_per_meter_squared,\n         divide_typeof_helper<microwatt, meter_squared>::type)\nADD_UNIT(nanowatt_per_meter_squared,\n         divide_typeof_helper<nanowatt, meter_squared>::type)\n\nADD_UNIT(W_m_n2, watt_per_meter_squared)\nADD_UNIT(mW_m_n2, milliwatt_per_meter_squared)\nADD_UNIT(uW_m_n2, microwatt_per_meter_squared)\nADD_UNIT(nW_m_n2, nanowatt_per_meter_squared)\n\nADD_UNIT_IO(watt_per_centimeter_squared, \"watt per centimeter squared\",\n            \"W cm^-2\")\nADD_UNIT_IO(watt_per_meter_squared, \"watt per meter squared\", \"W m^-2\")\n\n// Integrated Radiance\nADD_UNIT(joule_per_centimeter_squared_per_steradian,\n         divide_typeof_helper<joule_per_centimeter_squared, steradian>::type)\nADD_UNIT(\n    millijoule_per_centimeter_squared_per_steradian,\n    divide_typeof_helper<millijoule_per_centimeter_squared, steradian>::type)\nADD_UNIT(\n    microjoule_per_centimeter_squared_per_steradian,\n    divide_typeof_helper<microjoule_per_centimeter_squared, steradian>::type)\nADD_UNIT(\n    nanojoule_per_centimeter_squared_per_steradian,\n    divide_typeof_helper<nanojoule_per_centimeter_squared, steradian>::type)\n\nADD_UNIT(J_cm_n2_sr_n1, joule_per_centimeter_squared_per_steradian)\nADD_UNIT(mJ_cm_n2_sr_n1, millijoule_per_centimeter_squared_per_steradian)\nADD_UNIT(uJ_cm_n2_sr_n1, microjoule_per_centimeter_squared_per_steradian)\nADD_UNIT(nJ_cm_n2_sr_n1, nanojoule_per_centimeter_squared_per_steradian)\n\nADD_UNIT(joule_per_meter_squared_per_steradian,\n         divide_typeof_helper<joule_per_meter_squared, steradian>::type)\nADD_UNIT(millijoule_per_meter_squared_per_steradian,\n         divide_typeof_helper<millijoule_per_meter_squared, steradian>::type)\nADD_UNIT(microjoule_per_meter_squared_per_steradian,\n         divide_typeof_helper<microjoule_per_meter_squared, steradian>::type)\nADD_UNIT(nanojoule_per_meter_squared_per_steradian,\n         divide_typeof_helper<nanojoule_per_meter_squared, steradian>::type)\n\nADD_UNIT(J_m_n2_sr_n1, joule_per_meter_squared_per_steradian)\nADD_UNIT(mJ_m_n2_sr_n1, millijoule_per_meter_squared_per_steradian)\nADD_UNIT(uJ_m_n2_sr_n1, microjoule_per_meter_squared_per_steradian)\nADD_UNIT(nJ_m_n2_sr_n1, nanojoule_per_meter_squared_per_steradian)\n\nADD_UNIT_IO(joule_per_centimeter_squared_per_steradian,\n            \"joule per centimeter squared per steradian\", \"J cm^-2 sr^-1\")\n\n// Radiance\nADD_UNIT(watt_per_centimeter_squared_per_steradian,\n         divide_typeof_helper<watt_per_centimeter_squared, steradian>::type)\nADD_UNIT(\n    milliwatt_per_centimeter_squared_per_steradian,\n    divide_typeof_helper<milliwatt_per_centimeter_squared, steradian>::type)\nADD_UNIT(\n    microwatt_per_centimeter_squared_per_steradian,\n    divide_typeof_helper<microwatt_per_centimeter_squared, steradian>::type)\nADD_UNIT(nanowatt_per_centimeter_squared_per_steradian,\n         divide_typeof_helper<nanowatt_per_centimeter_squared, steradian>::type)\n\nADD_UNIT(W_cm_n2_sr_n1, watt_per_centimeter_squared_per_steradian)\nADD_UNIT(mW_cm_n2_sr_n1, milliwatt_per_centimeter_squared_per_steradian)\nADD_UNIT(uW_cm_n2_sr_n1, microwatt_per_centimeter_squared_per_steradian)\nADD_UNIT(nW_cm_n2_sr_n1, nanowatt_per_centimeter_squared_per_steradian)\n\nADD_UNIT(watt_per_meter_squared_per_steradian,\n         divide_typeof_helper<watt_per_meter_squared, steradian>::type)\nADD_UNIT(milliwatt_per_meter_squared_per_steradian,\n         divide_typeof_helper<milliwatt_per_meter_squared, steradian>::type)\nADD_UNIT(microwatt_per_meter_squared_per_steradian,\n         divide_typeof_helper<microwatt_per_meter_squared, steradian>::type)\nADD_UNIT(nanowatt_per_meter_squared_per_steradian,\n         divide_typeof_helper<nanowatt_per_meter_squared, steradian>::type)\n\nADD_UNIT(W_m_n2_sr_n1, watt_per_meter_squared_per_steradian)\nADD_UNIT(mW_m_n2_sr_n1, milliwatt_per_meter_squared_per_steradian)\nADD_UNIT(uW_m_n2_sr_n1, microwatt_per_meter_squared_per_steradian)\nADD_UNIT(nW_m_n2_sr_n1, nanowatt_per_meter_squared_per_steradian)\n\nADD_UNIT_IO(watt_per_centimeter_squared_per_steradian,\n            \"watt per centimeter squared per steradian\", \"W cm^-2 sr^-1\")\n\n// Integrated Radiant Intensity\nADD_UNIT(joule_per_steradian, divide_typeof_helper<joule, steradian>::type)\nADD_UNIT(millijoule_per_steradian,\n         divide_typeof_helper<millijoule, steradian>::type)\nADD_UNIT(microjoule_per_steradian,\n         divide_typeof_helper<microjoule, steradian>::type)\nADD_UNIT(nanojoule_per_steradian,\n         divide_typeof_helper<nanojoule, steradian>::type)\n\nADD_UNIT(J_sr_n1, joule_per_steradian)\nADD_UNIT(mJ_sr_n1, millijoule_per_steradian)\nADD_UNIT(uJ_sr_n1, microjoule_per_steradian)\nADD_UNIT(nJ_sr_n1, nanojoule_per_steradian)\n\nADD_UNIT_IO(joule_per_steradian, \"joule per steradian\", \"J sr^-1\")\n\n// Radiant Intensity\nADD_UNIT(watt_per_steradian, divide_typeof_helper<watt, steradian>::type)\nADD_UNIT(milliwatt_per_steradian,\n         divide_typeof_helper<milliwatt, steradian>::type)\nADD_UNIT(microwatt_per_steradian,\n         divide_typeof_helper<microwatt, steradian>::type)\nADD_UNIT(nanowatt_per_steradian,\n         divide_typeof_helper<nanowatt, steradian>::type)\n\nADD_UNIT(W_sr_n1, watt_per_steradian)\nADD_UNIT(mW_sr_n1, milliwatt_per_steradian)\nADD_UNIT(uW_sr_n1, microwatt_per_steradian)\nADD_UNIT(nW_sr_n1, nanowatt_per_steradian)\n\nADD_UNIT_IO(watt_per_steradian, \"watt per steradian\", \"W sr^-1\")\n\n// Electric Potential\nADD_UNIT(volt, si::electric_potential)\nADD_UNIT(V, volt)\n\n// Electric Field\nADD_UNIT(volt_per_meter, divide_typeof_helper<volt, meter>::type)\nADD_UNIT(V_m_n2, volt_per_meter)\n\nADD_UNIT(newton_per_coulomb, divide_typeof_helper<newton, coulomb>::type)\nADD_UNIT(N_C_n1, newton_per_coulomb)\n\n#undef ADD_UNIT\n#undef ADD_BASE_UNIT_SET\n#undef ADD_UNIT_SET\n#undef ADD_UNIT_IO\n\nnamespace boost\n{\nnamespace units\n{\nnamespace d\n{\n// define some dimensions\ntypedef t::meter::dimension_type Length;\ntypedef t::kilogram::dimension_type Mass;\ntypedef t::second::dimension_type Time;\ntypedef t::meter_squared::dimension_type Area;\n\ntypedef t::joule::dimension_type Energy;\ntypedef t::watt::dimension_type Power;\ntypedef t::joule_per_centimeter_squared::dimension_type RadiantExposure;\ntypedef t::watt_per_centimeter_squared::dimension_type Irradiance;\ntypedef t::joule_per_centimeter_squared_per_steradian::dimension_type\n    IntegratedRadiance;\ntypedef t::watt_per_centimeter_squared_per_steradian::dimension_type Radiance;\ntypedef t::joule_per_steradian::dimension_type IntegratedRadiantIntensity;\ntypedef t::watt_per_steradian::dimension_type RadiantIntensity;\n}  // namespace d\n\n// function to convert from dimensionless to angle\ntemplate <typename U, typename T>\n// 1. convert to dimensionless\n// 2. cast to double\n// 3. create radian by multiply\n// 4. convert to return type\nquantity<t::rad, T> d2a(quantity<U, T> a)\n{\n  return quantity<t::rad, T>(i::rad *\n                             quantity_cast<T>(quantity<t::dimless, T>(a)));\n}\n\n// function to convert from angle to dimensionless\ntemplate <typename U, typename T>\n// 1. convert to radian\n// 2. cast to double\n// 3. create dimensionless by multiply\n// 4. convert to return type\nquantity<t::dimless, T> a2d(quantity<U, T> a)\n{\n  return quantity<t::dimless, T>(i::dimless *\n                                 quantity_cast<T>(quantity<t::radian, T>(a)));\n}\n\n}  // namespace units\n}  // namespace boost\n\n// we want to allow implicit conversions between\n// units that are the same, but have differen types.\n// for example, boost::units::t::radian is a scaled base unit based on\n// angle::radian_base_unit, so it is not implicitly convertible to/from\n// si::plane_angle, even through they represent the same unit. This is true for\n// all of the base units as well. boost::units::t::second is based on\n// si::second_base_unit, and cannot be implicitly converted to/from si::time.\n// below are a list of conversions between types that represent the same unit\n// that the user could reasonably expect to be the \"same\"\n#define ADD_IMPLICITLY_CONVERTIBLE_UNITS(A, B)                \\\n  namespace boost                                             \\\n  {                                                           \\\n  namespace units                                             \\\n  {                                                           \\\n  template <>                                                 \\\n  struct is_implicitly_convertible<A, B> : boost::true_type { \\\n  };                                                          \\\n  template <>                                                 \\\n  struct is_implicitly_convertible<B, A> : boost::true_type { \\\n  };                                                          \\\n  }                                                           \\\n  }\n\n// base units\nADD_IMPLICITLY_CONVERTIBLE_UNITS(boost::units::t::radian,\n                                 angle::radian_base_unit)\nADD_IMPLICITLY_CONVERTIBLE_UNITS(boost::units::t::steradian,\n                                 angle::steradian_base_unit)\nADD_IMPLICITLY_CONVERTIBLE_UNITS(boost::units::t::meter, si::meter_base_unit)\nADD_IMPLICITLY_CONVERTIBLE_UNITS(boost::units::t::gram, cgs::gram_base_unit)\nADD_IMPLICITLY_CONVERTIBLE_UNITS(boost::units::t::second, si::second_base_unit)\nADD_IMPLICITLY_CONVERTIBLE_UNITS(boost::units::t::kelvin, si::kelvin_base_unit)\nADD_IMPLICITLY_CONVERTIBLE_UNITS(boost::units::t::ampere, si::ampere_base_unit)\n\n// si system\nADD_IMPLICITLY_CONVERTIBLE_UNITS(boost::units::t::meter, si::length)\nADD_IMPLICITLY_CONVERTIBLE_UNITS(boost::units::t::kilogram, si::mass)\nADD_IMPLICITLY_CONVERTIBLE_UNITS(boost::units::t::second, si::time)\nADD_IMPLICITLY_CONVERTIBLE_UNITS(boost::units::t::kelvin, si::temperature)\nADD_IMPLICITLY_CONVERTIBLE_UNITS(boost::units::t::ampere, si::current)\nADD_IMPLICITLY_CONVERTIBLE_UNITS(boost::units::t::hertz, si::frequency)\nADD_IMPLICITLY_CONVERTIBLE_UNITS(boost::units::t::meter_squared, si::area)\n\n// cgs system\nADD_IMPLICITLY_CONVERTIBLE_UNITS(boost::units::t::centimeter, cgs::length)\nADD_IMPLICITLY_CONVERTIBLE_UNITS(boost::units::t::gram, cgs::mass)\nADD_IMPLICITLY_CONVERTIBLE_UNITS(boost::units::t::second, cgs::time)\nADD_IMPLICITLY_CONVERTIBLE_UNITS(boost::units::t::ampere, cgs::current)\nADD_IMPLICITLY_CONVERTIBLE_UNITS(boost::units::t::hertz, cgs::frequency)\nADD_IMPLICITLY_CONVERTIBLE_UNITS(boost::units::t::centimeter_squared,\n                                 cgs::area)\n\n// define multiplication between int's and quantity<unit>'s\n// otherwise, we can't do this\n// quantity<t::m> L(3.*m);\n// quantity<t::m> L2 = 3*L; // error\n// quantity<t::m> L2 = 3.*L; // OK\ntemplate <typename U, typename T>\nboost::units::quantity<U, T> operator*(int a, boost::units::quantity<U, T> b)\n{\n  return static_cast<T>(a) * b;\n}\n\ntemplate <typename U, typename T>\nboost::units::quantity<U, T> operator*(boost::units::quantity<U, T> b, int a)\n{\n  return static_cast<T>(a) * b;\n}\n\n// define multiplication between int's and units, so that template type\n// deduction will work.\n// otherwise, we can't do this\n//\n// template<typename U>\n// void Func( quantity<U> q );\n// ...\n// Func(3*m); // error\n// Func(3.*m); // OK\ntemplate <typename U, typename T>\nboost::units::quantity<boost::units::unit<U, T>> operator*(\n    int a, boost::units::unit<U, T> u)\n{\n  return static_cast<double>(a) * u;\n}\n\ntemplate <typename U, typename T>\nboost::units::quantity<boost::units::unit<U, T>> operator*(\n    boost::units::unit<U, T> u, int a)\n{\n  return static_cast<double>(a) * u;\n}\n\n// define division of quantity<unit>'s by ints\n// otherwise, we can't do this\n// quantity<t::m> L(3.*m);\n// quantity<t::m> L2 = L/3; // error\n// quantity<t::m> L2 = L/3.; // OK\ntemplate <typename U, typename T>\nboost::units::quantity<U, T> operator/(boost::units::quantity<U, T> b, int a)\n{\n  return b / static_cast<T>(a);\n}\n\n// define division of int by quantity<unit>\n// otherwise, we can't do this\n// quantity<t::s> T(2.*s);\n// quantity<t::Hz> L2 = 1/T; // error\n// quantity<t::Hz> L2 = 1./T.; // OK\ntemplate <typename U, typename T>\nboost::units::quantity<typename boost::units::divide_typeof_helper<\n                           boost::units::t::dimensionless, U>::type,\n                       T>\noperator/(int a, boost::units::quantity<U, T> b)\n{\n  return static_cast<T>(a) / b;\n}\n\n#endif  // include protector\n", "meta": {"hexsha": "b1edc4298b4e8af1464b849506d3a9585e3e2bb7", "size": 27596, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/BoostUnitDefinitions/Units.hpp", "max_stars_repo_name": "CD3/BoostUnitDefinitions", "max_stars_repo_head_hexsha": "5da5e8610a8fc3f0b9d8d7baf9b0dca6f18bec6f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/BoostUnitDefinitions/Units.hpp", "max_issues_repo_name": "CD3/BoostUnitDefinitions", "max_issues_repo_head_hexsha": "5da5e8610a8fc3f0b9d8d7baf9b0dca6f18bec6f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/BoostUnitDefinitions/Units.hpp", "max_forks_repo_name": "CD3/BoostUnitDefinitions", "max_forks_repo_head_hexsha": "5da5e8610a8fc3f0b9d8d7baf9b0dca6f18bec6f", "max_forks_repo_licenses": ["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.4380032206, "max_line_length": 80, "alphanum_fraction": 0.6503841136, "num_tokens": 6664, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6619228625116081, "lm_q2_score": 0.45326184801538605, "lm_q1q2_score": 0.3000243799056458}}
